diff --git a/index.ts b/index.ts new file mode 100644 index 0000000..19f611e --- /dev/null +++ b/index.ts @@ -0,0 +1,24 @@ +import flatten = require("lodash.flatten"); + +export function stringifyTree(tn: T, nameFn: (t: T) => string, childrenFn: (t: T) => T[]): string { + + function prefixChild(strs: string[], last: boolean): string[] { + return strs.map((s, i) => { + const prefix = i === 0 ? (last ? "└─" : "├─") : (last ? " " : "│ "); + return prefix + s; + }); + } + function nodeToStrings(tn: T): string[] { + const children = [...childrenFn(tn)]; // copy the array + if (children.length === 0) { + return ["─ " + nameFn(tn)]; + } + return ["┬ " + nameFn(tn), ...flatten(children.map((c, i) => { + const strs = nodeToStrings(c); + return prefixChild(strs, i === (children.length - 1)); + }))]; + } + + return nodeToStrings(tn).join("\n"); + +} diff --git a/node_modules/.bin/_mocha b/node_modules/.bin/_mocha new file mode 120000 index 0000000..f2a54ff --- /dev/null +++ b/node_modules/.bin/_mocha @@ -0,0 +1 @@ +../mocha/bin/_mocha \ No newline at end of file diff --git a/node_modules/.bin/he b/node_modules/.bin/he new file mode 120000 index 0000000..2a8eb5e --- /dev/null +++ b/node_modules/.bin/he @@ -0,0 +1 @@ +../he/bin/he \ No newline at end of file diff --git a/node_modules/.bin/mkdirp b/node_modules/.bin/mkdirp new file mode 120000 index 0000000..017896c --- /dev/null +++ b/node_modules/.bin/mkdirp @@ -0,0 +1 @@ +../mkdirp/bin/cmd.js \ No newline at end of file diff --git a/node_modules/.bin/mocha b/node_modules/.bin/mocha new file mode 120000 index 0000000..43c668d --- /dev/null +++ b/node_modules/.bin/mocha @@ -0,0 +1 @@ +../mocha/bin/mocha \ No newline at end of file diff --git a/node_modules/.bin/ts-node b/node_modules/.bin/ts-node new file mode 120000 index 0000000..b3ff94b --- /dev/null +++ b/node_modules/.bin/ts-node @@ -0,0 +1 @@ +../ts-node/dist/bin.js \ No newline at end of file diff --git a/node_modules/.bin/tsc b/node_modules/.bin/tsc new file mode 120000 index 0000000..0863208 --- /dev/null +++ b/node_modules/.bin/tsc @@ -0,0 +1 @@ +../typescript/bin/tsc \ No newline at end of file diff --git a/node_modules/.bin/tsserver b/node_modules/.bin/tsserver new file mode 120000 index 0000000..f8f8f1a --- /dev/null +++ b/node_modules/.bin/tsserver @@ -0,0 +1 @@ +../typescript/bin/tsserver \ No newline at end of file diff --git a/node_modules/@types/lodash.flatten/LICENSE b/node_modules/@types/lodash.flatten/LICENSE new file mode 100644 index 0000000..2107107 --- /dev/null +++ b/node_modules/@types/lodash.flatten/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. All rights reserved. + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE diff --git a/node_modules/@types/lodash.flatten/README.md b/node_modules/@types/lodash.flatten/README.md new file mode 100644 index 0000000..5ed5c72 --- /dev/null +++ b/node_modules/@types/lodash.flatten/README.md @@ -0,0 +1,16 @@ +# Installation +> `npm install --save @types/lodash.flatten` + +# Summary +This package contains type definitions for lodash.flatten (http://lodash.com/). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/lodash.flatten + +Additional Details + * Last updated: Mon, 23 Jul 2018 23:44:11 GMT + * Dependencies: lodash + * Global values: none + +# Credits +These definitions were written by Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk . diff --git a/node_modules/@types/lodash.flatten/index.d.ts b/node_modules/@types/lodash.flatten/index.d.ts new file mode 100644 index 0000000..766108b --- /dev/null +++ b/node_modules/@types/lodash.flatten/index.d.ts @@ -0,0 +1,10 @@ +// Type definitions for lodash.flatten 4.4 +// Project: http://lodash.com/ +// Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.6 + +// Generated from https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/lodash/scripts/generate-modules.ts + +import { flatten } from "lodash"; +export = flatten; diff --git a/node_modules/@types/lodash.flatten/package.json b/node_modules/@types/lodash.flatten/package.json new file mode 100644 index 0000000..07c285a --- /dev/null +++ b/node_modules/@types/lodash.flatten/package.json @@ -0,0 +1,62 @@ +{ + "_from": "@types/lodash.flatten", + "_id": "@types/lodash.flatten@4.4.4", + "_inBundle": false, + "_integrity": "sha512-F106FV2hmztEtMHozFMfS41u+58vjMEv2SJljMlXmPCn13yWS+/B1r0KjQuaZpsPE857req0BunDwzgpqQ2Ydg==", + "_location": "/@types/lodash.flatten", + "_phantomChildren": {}, + "_requested": { + "type": "tag", + "registry": true, + "raw": "@types/lodash.flatten", + "name": "@types/lodash.flatten", + "escapedName": "@types%2flodash.flatten", + "scope": "@types", + "rawSpec": "", + "saveSpec": null, + "fetchSpec": "latest" + }, + "_requiredBy": [ + "#USER", + "/" + ], + "_resolved": "https://registry.npmjs.org/@types/lodash.flatten/-/lodash.flatten-4.4.4.tgz", + "_shasum": "7f28009ef57c8d2b1d8463c3e53fdccf780120a5", + "_spec": "@types/lodash.flatten", + "_where": "/Users/jessitron/code/jessitron/stringify-tree", + "bugs": { + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped/issues" + }, + "bundleDependencies": false, + "contributors": [ + { + "name": "Brian Zengel", + "url": "https://github.com/bczengel" + }, + { + "name": "Ilya Mochalov", + "url": "https://github.com/chrootsu" + }, + { + "name": "Stepan Mikhaylyuk", + "url": "https://github.com/stepancar" + } + ], + "dependencies": { + "@types/lodash": "*" + }, + "deprecated": false, + "description": "TypeScript definitions for lodash.flatten", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped#readme", + "license": "MIT", + "main": "", + "name": "@types/lodash.flatten", + "repository": { + "type": "git", + "url": "git+https://github.com/DefinitelyTyped/DefinitelyTyped.git" + }, + "scripts": {}, + "typeScriptVersion": "2.6", + "typesPublisherContentHash": "082e6e2a78c5f9aff634d446554eee0119cd465708f6cc250473eedb06b499af", + "version": "4.4.4" +} diff --git a/node_modules/@types/lodash/LICENSE b/node_modules/@types/lodash/LICENSE new file mode 100644 index 0000000..4b1ad51 --- /dev/null +++ b/node_modules/@types/lodash/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. All rights reserved. + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE diff --git a/node_modules/@types/lodash/README.md b/node_modules/@types/lodash/README.md new file mode 100644 index 0000000..3dd8fdd --- /dev/null +++ b/node_modules/@types/lodash/README.md @@ -0,0 +1,16 @@ +# Installation +> `npm install --save @types/lodash` + +# Summary +This package contains type definitions for Lo-Dash (http://lodash.com/). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/lodash + +Additional Details + * Last updated: Tue, 04 Dec 2018 21:32:32 GMT + * Dependencies: none + * Global values: _ + +# Credits +These definitions were written by Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk , AJ Richardson , Junyoung Clare Jang , e-cloud , Georgii Dolzhykov , Jack Moore , Dominique Rau . diff --git a/node_modules/@types/lodash/add.d.ts b/node_modules/@types/lodash/add.d.ts new file mode 100644 index 0000000..4650a89 --- /dev/null +++ b/node_modules/@types/lodash/add.d.ts @@ -0,0 +1,2 @@ +import { add } from "./index"; +export = add; diff --git a/node_modules/@types/lodash/after.d.ts b/node_modules/@types/lodash/after.d.ts new file mode 100644 index 0000000..277ae1e --- /dev/null +++ b/node_modules/@types/lodash/after.d.ts @@ -0,0 +1,2 @@ +import { after } from "./index"; +export = after; diff --git a/node_modules/@types/lodash/ary.d.ts b/node_modules/@types/lodash/ary.d.ts new file mode 100644 index 0000000..ac1c72e --- /dev/null +++ b/node_modules/@types/lodash/ary.d.ts @@ -0,0 +1,2 @@ +import { ary } from "./index"; +export = ary; diff --git a/node_modules/@types/lodash/assign.d.ts b/node_modules/@types/lodash/assign.d.ts new file mode 100644 index 0000000..5ffc1e3 --- /dev/null +++ b/node_modules/@types/lodash/assign.d.ts @@ -0,0 +1,2 @@ +import { assign } from "./index"; +export = assign; diff --git a/node_modules/@types/lodash/assignIn.d.ts b/node_modules/@types/lodash/assignIn.d.ts new file mode 100644 index 0000000..3cc54e8 --- /dev/null +++ b/node_modules/@types/lodash/assignIn.d.ts @@ -0,0 +1,2 @@ +import { assignIn } from "./index"; +export = assignIn; diff --git a/node_modules/@types/lodash/assignInWith.d.ts b/node_modules/@types/lodash/assignInWith.d.ts new file mode 100644 index 0000000..b4c4dfe --- /dev/null +++ b/node_modules/@types/lodash/assignInWith.d.ts @@ -0,0 +1,2 @@ +import { assignInWith } from "./index"; +export = assignInWith; diff --git a/node_modules/@types/lodash/assignWith.d.ts b/node_modules/@types/lodash/assignWith.d.ts new file mode 100644 index 0000000..97da10c --- /dev/null +++ b/node_modules/@types/lodash/assignWith.d.ts @@ -0,0 +1,2 @@ +import { assignWith } from "./index"; +export = assignWith; diff --git a/node_modules/@types/lodash/at.d.ts b/node_modules/@types/lodash/at.d.ts new file mode 100644 index 0000000..49e7147 --- /dev/null +++ b/node_modules/@types/lodash/at.d.ts @@ -0,0 +1,2 @@ +import { at } from "./index"; +export = at; diff --git a/node_modules/@types/lodash/attempt.d.ts b/node_modules/@types/lodash/attempt.d.ts new file mode 100644 index 0000000..d4b6089 --- /dev/null +++ b/node_modules/@types/lodash/attempt.d.ts @@ -0,0 +1,2 @@ +import { attempt } from "./index"; +export = attempt; diff --git a/node_modules/@types/lodash/before.d.ts b/node_modules/@types/lodash/before.d.ts new file mode 100644 index 0000000..03c45c8 --- /dev/null +++ b/node_modules/@types/lodash/before.d.ts @@ -0,0 +1,2 @@ +import { before } from "./index"; +export = before; diff --git a/node_modules/@types/lodash/bind.d.ts b/node_modules/@types/lodash/bind.d.ts new file mode 100644 index 0000000..6367da1 --- /dev/null +++ b/node_modules/@types/lodash/bind.d.ts @@ -0,0 +1,2 @@ +import { bind } from "./index"; +export = bind; diff --git a/node_modules/@types/lodash/bindAll.d.ts b/node_modules/@types/lodash/bindAll.d.ts new file mode 100644 index 0000000..25d47e3 --- /dev/null +++ b/node_modules/@types/lodash/bindAll.d.ts @@ -0,0 +1,2 @@ +import { bindAll } from "./index"; +export = bindAll; diff --git a/node_modules/@types/lodash/bindKey.d.ts b/node_modules/@types/lodash/bindKey.d.ts new file mode 100644 index 0000000..128b065 --- /dev/null +++ b/node_modules/@types/lodash/bindKey.d.ts @@ -0,0 +1,2 @@ +import { bindKey } from "./index"; +export = bindKey; diff --git a/node_modules/@types/lodash/camelCase.d.ts b/node_modules/@types/lodash/camelCase.d.ts new file mode 100644 index 0000000..5c10659 --- /dev/null +++ b/node_modules/@types/lodash/camelCase.d.ts @@ -0,0 +1,2 @@ +import { camelCase } from "./index"; +export = camelCase; diff --git a/node_modules/@types/lodash/capitalize.d.ts b/node_modules/@types/lodash/capitalize.d.ts new file mode 100644 index 0000000..416f5f5 --- /dev/null +++ b/node_modules/@types/lodash/capitalize.d.ts @@ -0,0 +1,2 @@ +import { capitalize } from "./index"; +export = capitalize; diff --git a/node_modules/@types/lodash/castArray.d.ts b/node_modules/@types/lodash/castArray.d.ts new file mode 100644 index 0000000..74ea7bd --- /dev/null +++ b/node_modules/@types/lodash/castArray.d.ts @@ -0,0 +1,2 @@ +import { castArray } from "./index"; +export = castArray; diff --git a/node_modules/@types/lodash/ceil.d.ts b/node_modules/@types/lodash/ceil.d.ts new file mode 100644 index 0000000..0c6f1fd --- /dev/null +++ b/node_modules/@types/lodash/ceil.d.ts @@ -0,0 +1,2 @@ +import { ceil } from "./index"; +export = ceil; diff --git a/node_modules/@types/lodash/chain.d.ts b/node_modules/@types/lodash/chain.d.ts new file mode 100644 index 0000000..d09d2bb --- /dev/null +++ b/node_modules/@types/lodash/chain.d.ts @@ -0,0 +1,2 @@ +import { chain } from "./index"; +export = chain; diff --git a/node_modules/@types/lodash/chunk.d.ts b/node_modules/@types/lodash/chunk.d.ts new file mode 100644 index 0000000..125c98f --- /dev/null +++ b/node_modules/@types/lodash/chunk.d.ts @@ -0,0 +1,2 @@ +import { chunk } from "./index"; +export = chunk; diff --git a/node_modules/@types/lodash/clamp.d.ts b/node_modules/@types/lodash/clamp.d.ts new file mode 100644 index 0000000..df17066 --- /dev/null +++ b/node_modules/@types/lodash/clamp.d.ts @@ -0,0 +1,2 @@ +import { clamp } from "./index"; +export = clamp; diff --git a/node_modules/@types/lodash/clone.d.ts b/node_modules/@types/lodash/clone.d.ts new file mode 100644 index 0000000..c5884d7 --- /dev/null +++ b/node_modules/@types/lodash/clone.d.ts @@ -0,0 +1,2 @@ +import { clone } from "./index"; +export = clone; diff --git a/node_modules/@types/lodash/cloneDeep.d.ts b/node_modules/@types/lodash/cloneDeep.d.ts new file mode 100644 index 0000000..b7bd893 --- /dev/null +++ b/node_modules/@types/lodash/cloneDeep.d.ts @@ -0,0 +1,2 @@ +import { cloneDeep } from "./index"; +export = cloneDeep; diff --git a/node_modules/@types/lodash/cloneDeepWith.d.ts b/node_modules/@types/lodash/cloneDeepWith.d.ts new file mode 100644 index 0000000..3eb368b --- /dev/null +++ b/node_modules/@types/lodash/cloneDeepWith.d.ts @@ -0,0 +1,2 @@ +import { cloneDeepWith } from "./index"; +export = cloneDeepWith; diff --git a/node_modules/@types/lodash/cloneWith.d.ts b/node_modules/@types/lodash/cloneWith.d.ts new file mode 100644 index 0000000..1e6bf7a --- /dev/null +++ b/node_modules/@types/lodash/cloneWith.d.ts @@ -0,0 +1,2 @@ +import { cloneWith } from "./index"; +export = cloneWith; diff --git a/node_modules/@types/lodash/common/array.d.ts b/node_modules/@types/lodash/common/array.d.ts new file mode 100644 index 0000000..6d4aff3 --- /dev/null +++ b/node_modules/@types/lodash/common/array.d.ts @@ -0,0 +1,3708 @@ +import _ = require("../index"); +declare module "../index" { + // chunk + + interface LoDashStatic { + /** + * Creates an array of elements split into groups the length of size. If collection can’t be split evenly, the + * final chunk will be the remaining elements. + * + * @param array The array to process. + * @param size The length of each chunk. + * @return Returns the new array containing chunks. + */ + chunk( + array: List | null | undefined, + size?: number + ): T[][]; + } + + interface LoDashImplicitWrapper { + /** + * @see _.chunk + */ + chunk( + this: LoDashImplicitWrapper | null | undefined>, + size?: number, + ): LoDashImplicitWrapper; + } + + interface LoDashExplicitWrapper { + /** + * @see _.chunk + */ + chunk( + this: LoDashExplicitWrapper | null | undefined>, + size?: number, + ): LoDashExplicitWrapper; + } + + // compact + + interface LoDashStatic { + /** + * Creates an array with all falsey values removed. The values false, null, 0, "", undefined, and NaN are + * falsey. + * + * @param array The array to compact. + * @return Returns the new array of filtered values. + */ + compact(array: List | null | undefined): T[]; + } + + interface LoDashImplicitWrapper { + /** + * @see _.compact + */ + compact(this: LoDashImplicitWrapper | null | undefined>): LoDashImplicitWrapper; + } + + interface LoDashExplicitWrapper { + /** + * @see _.compact + */ + compact(this: LoDashExplicitWrapper | null | undefined>): LoDashExplicitWrapper; + } + + // concat + + interface LoDashStatic { + /** + * Creates a new array concatenating `array` with any additional arrays + * and/or values. + * + * @category Array + * @param array The array to concatenate. + * @param [values] The values to concatenate. + * @returns Returns the new concatenated array. + * @example + * + * var array = [1]; + * var other = _.concat(array, 2, [3], [[4]]); + * + * console.log(other); + * // => [1, 2, 3, [4]] + * + * console.log(array); + * // => [1] + */ + concat(array: Many, ...values: Array>): T[]; + } + + interface LoDashImplicitWrapper { + /** + * @see _.compact + */ + concat(this: LoDashImplicitWrapper>, ...values: Array>): LoDashImplicitWrapper; + } + + interface LoDashExplicitWrapper { + /** + * @see _.compact + */ + concat(this: LoDashExplicitWrapper>, ...values: Array>): LoDashExplicitWrapper; + } + + // difference + + interface LoDashStatic { + /** + * Creates an array of unique array values not included in the other provided arrays using SameValueZero for + * equality comparisons. + * + * @param array The array to inspect. + * @param values The arrays of values to exclude. + * @return Returns the new array of filtered values. + */ + difference( + array: List | null | undefined, + ...values: Array> + ): T[]; + } + + interface LoDashImplicitWrapper { + /** + * @see _.difference + */ + difference( + this: LoDashImplicitWrapper | null | undefined>, + ...values: Array> + ): LoDashImplicitWrapper; + } + + interface LoDashExplicitWrapper { + /** + * @see _.difference + */ + difference( + this: LoDashExplicitWrapper | null | undefined>, + ...values: Array> + ): LoDashExplicitWrapper; + } + + // differenceBy + + interface LoDashStatic { + /** + * This method is like _.difference except that it accepts iteratee which is invoked for each element of array + * and values to generate the criterion by which uniqueness is computed. The iteratee is invoked with one + * argument: (value). + * + * @param array The array to inspect. + * @param values The values to exclude. + * @param iteratee The iteratee invoked per element. + * @returns Returns the new array of filtered values. + */ + differenceBy( + array: List | null | undefined, + values: List, + iteratee: ValueIteratee + ): T1[]; + + /** + * @see _.differenceBy + */ + differenceBy( + array: List | null | undefined, + values1: List, + values2: List, + iteratee: ValueIteratee + ): T1[]; + + /** + * @see _.differenceBy + */ + differenceBy( + array: List | null | undefined, + values1: List, + values2: List, + values3: List, + iteratee: ValueIteratee + ): T1[]; + + /** + * @see _.differenceBy + */ + differenceBy( + array: List | null | undefined, + values1: List, + values2: List, + values3: List, + values4: List, + iteratee: ValueIteratee + ): T1[]; + + /** + * @see _.differenceBy + */ + differenceBy( + array: List | null | undefined, + values1: List, + values2: List, + values3: List, + values4: List, + values5: List, + iteratee: ValueIteratee + ): T1[]; + + /** + * @see _.differenceBy + */ + differenceBy( + array: List | null | undefined, + values1: List, + values2: List, + values3: List, + values4: List, + values5: List, + ...values: Array | ValueIteratee> + ): T1[]; + + /** + * @see _.differenceBy + */ + differenceBy( + array: List | null | undefined, + ...values: Array> + ): T[]; + } + + interface LoDashImplicitWrapper { + /** + * @see _.differenceBy + */ + differenceBy( + this: LoDashImplicitWrapper | null | undefined>, + values: List, + iteratee: ValueIteratee + ): LoDashImplicitWrapper; + + /** + * @see _.differenceBy + */ + differenceBy( + this: LoDashImplicitWrapper | null | undefined>, + values1: List, + values2: List, + iteratee: ValueIteratee + ): LoDashImplicitWrapper; + + /** + * @see _.differenceBy + */ + differenceBy( + this: LoDashImplicitWrapper | null | undefined>, + values1: List, + values2: List, + values3: List, + iteratee: ValueIteratee + ): LoDashImplicitWrapper; + + /** + * @see _.differenceBy + */ + differenceBy( + this: LoDashImplicitWrapper | null | undefined>, + values1: List, + values2: List, + values3: List, + values4: List, + iteratee: ValueIteratee + ): LoDashImplicitWrapper; + + /** + * @see _.differenceBy + */ + differenceBy( + this: LoDashImplicitWrapper | null | undefined>, + values1: List, + values2: List, + values3: List, + values4: List, + values5: List, + iteratee: ValueIteratee + ): LoDashImplicitWrapper; + + /** + * @see _.differenceBy + */ + differenceBy( + this: LoDashImplicitWrapper | null | undefined>, + values1: List, + values2: List, + values3: List, + values4: List, + values5: List, + ...values: Array | ValueIteratee> + ): LoDashImplicitWrapper; + + /** + * @see _.differenceBy + */ + differenceBy( + this: LoDashImplicitWrapper | null | undefined>, + ...values: Array> + ): LoDashImplicitWrapper; + } + + interface LoDashExplicitWrapper { + /** + * @see _.differenceBy + */ + differenceBy( + this: LoDashExplicitWrapper | null | undefined>, + values: List, + iteratee: ValueIteratee + ): LoDashExplicitWrapper; + + /** + * @see _.differenceBy + */ + differenceBy( + this: LoDashExplicitWrapper | null | undefined>, + values1: List, + values2: List, + iteratee: ValueIteratee + ): LoDashExplicitWrapper; + + /** + * @see _.differenceBy + */ + differenceBy( + this: LoDashExplicitWrapper | null | undefined>, + values1: List, + values2: List, + values3: List, + iteratee: ValueIteratee + ): LoDashExplicitWrapper; + + /** + * @see _.differenceBy + */ + differenceBy( + this: LoDashExplicitWrapper | null | undefined>, + values1: List, + values2: List, + values3: List, + values4: List, + iteratee: ValueIteratee + ): LoDashExplicitWrapper; + + /** + * @see _.differenceBy + */ + differenceBy( + this: LoDashExplicitWrapper | null | undefined>, + values1: List, + values2: List, + values3: List, + values4: List, + values5: List, + iteratee: ValueIteratee + ): LoDashExplicitWrapper; + + /** + * @see _.differenceBy + */ + differenceBy( + this: LoDashExplicitWrapper | null | undefined>, + values1: List, + values2: List, + values3: List, + values4: List, + values5: List, + ...values: Array | ValueIteratee> + ): LoDashExplicitWrapper; + + /** + * @see _.differenceBy + */ + differenceBy( + this: LoDashExplicitWrapper | null | undefined>, + ...values: Array> + ): LoDashExplicitWrapper; + } + + // differenceWith + + interface LoDashStatic { + /** + * Creates an array of unique `array` values not included in the other + * provided arrays using [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero) + * for equality comparisons. + * + * @category Array + * @param [values] The arrays to inspect. + * @param [comparator] The comparator invoked per element. + * @returns Returns the new array of filtered values. + * @example + * + * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; + + * _.differenceWith(objects, [{ 'x': 1, 'y': 2 }], _.isEqual); + * // => [{ 'x': 2, 'y': 1 }] + */ + differenceWith( + array: List | null | undefined, + values: List, + comparator: Comparator2 + ): T1[]; + + /** + * @see _.differenceWith + */ + differenceWith( + array: List | null | undefined, + values1: List, + values2: List, + comparator: Comparator2 + ): T1[]; + + /** + * @see _.differenceWith + */ + differenceWith( + array: List | null | undefined, + values1: List, + values2: List, + ...values: Array | Comparator2> + ): T1[]; + + /** + * @see _.differenceWith + */ + differenceWith( + array: List | null | undefined, + ...values: Array> + ): T[]; + } + + interface LoDashImplicitWrapper { + /** + * @see _.differenceWith + */ + differenceWith( + this: LoDashImplicitWrapper | null | undefined>, + values: List, + comparator: Comparator2 + ): LoDashImplicitWrapper; + + /** + * @see _.differenceWith + */ + differenceWith( + this: LoDashImplicitWrapper | null | undefined>, + values1: List, + values2: List, + comparator: Comparator2 + ): LoDashImplicitWrapper; + + /** + * @see _.differenceWith + */ + differenceWith( + this: LoDashImplicitWrapper | null | undefined>, + values1: List, + values2: List, + ...values: Array | Comparator2> + ): LoDashImplicitWrapper; + + /** + * @see _.differenceWith + */ + differenceWith( + this: LoDashImplicitWrapper | null | undefined>, + ...values: Array> + ): LoDashImplicitWrapper; + } + + interface LoDashExplicitWrapper { + /** + * @see _.differenceWith + */ + differenceWith( + this: LoDashExplicitWrapper | null | undefined>, + values: List, + comparator: Comparator2 + ): LoDashExplicitWrapper; + + /** + * @see _.differenceWith + */ + differenceWith( + this: LoDashExplicitWrapper | null | undefined>, + values1: List, + values2: List, + comparator: Comparator2 + ): LoDashExplicitWrapper; + + /** + * @see _.differenceWith + */ + differenceWith( + this: LoDashExplicitWrapper | null | undefined>, + values1: List, + values2: List, + ...values: Array | Comparator2> + ): LoDashExplicitWrapper; + + /** + * @see _.differenceWith + */ + differenceWith( + this: LoDashExplicitWrapper | null | undefined>, + ...values: Array> + ): LoDashExplicitWrapper; + } + + // drop + + interface LoDashStatic { + /** + * Creates a slice of array with n elements dropped from the beginning. + * + * @param array The array to query. + * @param n The number of elements to drop. + * @return Returns the slice of array. + */ + drop(array: List | null | undefined, n?: number): T[]; + } + + interface LoDashImplicitWrapper { + /** + * @see _.drop + */ + drop(this: LoDashImplicitWrapper | null | undefined>, n?: number): LoDashImplicitWrapper; + } + + interface LoDashExplicitWrapper { + /** + * @see _.drop + */ + drop(this: LoDashExplicitWrapper | null | undefined>, n?: number): LoDashExplicitWrapper; + } + + // dropRight + + interface LoDashStatic { + /** + * Creates a slice of array with n elements dropped from the end. + * + * @param array The array to query. + * @param n The number of elements to drop. + * @return Returns the slice of array. + */ + dropRight( + array: List | null | undefined, + n?: number + ): T[]; + } + + interface LoDashImplicitWrapper { + /** + * @see _.dropRight + */ + dropRight(this: LoDashImplicitWrapper | null | undefined>, n?: number): LoDashImplicitWrapper; + } + + interface LoDashExplicitWrapper { + /** + * @see _.dropRight + */ + dropRight(this: LoDashExplicitWrapper | null | undefined>, n?: number): LoDashExplicitWrapper; + } + + // dropRightWhile + + interface LoDashStatic { + /** + * Creates a slice of array excluding elements dropped from the end. Elements are dropped until predicate + * returns falsey. The predicate is invoked with three arguments: (value, index, array). + * + * @param array The array to query. + * @param predicate The function invoked per iteration. + * @return Returns the slice of array. + */ + dropRightWhile( + array: List | null | undefined, + predicate?: ListIteratee + ): T[]; + } + + interface LoDashImplicitWrapper { + /** + * @see _.dropRightWhile + */ + dropRightWhile( + this: LoDashImplicitWrapper | null | undefined>, + predicate?: ListIteratee + ): LoDashImplicitWrapper; + } + + interface LoDashExplicitWrapper { + /** + * @see _.dropRightWhile + */ + dropRightWhile( + this: LoDashExplicitWrapper | null | undefined>, + predicate?: ListIteratee + ): LoDashExplicitWrapper; + } + + // dropWhile + + interface LoDashStatic { + /** + * Creates a slice of array excluding elements dropped from the beginning. Elements are dropped until predicate + * returns falsey. The predicate is invoked with three arguments: (value, index, array). + * + * @param array The array to query. + * @param predicate The function invoked per iteration. + * @return Returns the slice of array. + */ + dropWhile( + array: List | null | undefined, + predicate?: ListIteratee + ): T[]; + } + + interface LoDashImplicitWrapper { + /** + * @see _.dropWhile + */ + dropWhile( + this: LoDashImplicitWrapper | null | undefined>, + predicate?: ListIteratee + ): LoDashImplicitWrapper; + } + + interface LoDashExplicitWrapper { + /** + * @see _.dropWhile + */ + dropWhile( + this: LoDashExplicitWrapper | null | undefined>, + predicate?: ListIteratee + ): LoDashExplicitWrapper; + } + + // fill + + interface LoDashStatic { + /** + * Fills elements of array with value from start up to, but not including, end. + * + * Note: This method mutates array. + * + * @param array The array to fill. + * @param value The value to fill array with. + * @param start The start position. + * @param end The end position. + * @return Returns array. + */ + fill( + array: any[] | null | undefined, + value: T + ): T[]; + + /** + * @see _.fill + */ + fill( + array: List | null | undefined, + value: T + ): List; + + /** + * @see _.fill + */ + fill( + array: U[] | null | undefined, + value: T, + start?: number, + end?: number + ): Array; + + /** + * @see _.fill + */ + fill( + array: List | null | undefined, + value: T, + start?: number, + end?: number + ): List; + } + + interface LoDashImplicitWrapper { + /** + * @see _.fill + */ + fill( + this: LoDashImplicitWrapper, + value: T + ): LoDashImplicitWrapper; + + /** + * @see _.fill + */ + fill( + this: LoDashImplicitWrapper | null | undefined>, + value: T + ): LoDashImplicitWrapper>; + + /** + * @see _.fill + */ + fill( + this: LoDashImplicitWrapper, + value: T, + start?: number, + end?: number + ): LoDashImplicitWrapper>; + + /** + * @see _.fill + */ + fill( + this: LoDashImplicitWrapper | null | undefined>, + value: T, + start?: number, + end?: number + ): LoDashImplicitWrapper>; + } + + interface LoDashExplicitWrapper { + /** + * @see _.fill + */ + fill( + this: LoDashExplicitWrapper, + value: T + ): LoDashExplicitWrapper; + + /** + * @see _.fill + */ + fill( + this: LoDashExplicitWrapper | null | undefined>, + value: T + ): LoDashExplicitWrapper>; + + /** + * @see _.fill + */ + fill( + this: LoDashExplicitWrapper, + value: T, + start?: number, + end?: number + ): LoDashExplicitWrapper>; + + /** + * @see _.fill + */ + fill( + this: LoDashExplicitWrapper | null | undefined>, + value: T, + start?: number, + end?: number + ): LoDashExplicitWrapper>; + } + + // findIndex + + interface LoDashStatic { + /** + * This method is like _.find except that it returns the index of the first element predicate returns truthy + * for instead of the element itself. + * + * @param array The array to search. + * @param predicate The function invoked per iteration. + * @param fromIndex The index to search from. + * @return Returns the index of the found element, else -1. + */ + findIndex( + array: List | null | undefined, + predicate?: ListIterateeCustom, + fromIndex?: number + ): number; + } + + interface LoDashImplicitWrapper { + /** + * @see _.findIndex + */ + findIndex( + this: LoDashImplicitWrapper | null | undefined>, + predicate?: ListIterateeCustom, + fromIndex?: number + ): number; + } + + interface LoDashExplicitWrapper { + /** + * @see _.findIndex + */ + findIndex( + this: LoDashExplicitWrapper | null | undefined>, + predicate?: ListIterateeCustom, + fromIndex?: number + ): LoDashExplicitWrapper; + } + + // findLastIndex + + interface LoDashStatic { + /** + * This method is like _.findIndex except that it iterates over elements of collection from right to left. + * + * @param array The array to search. + * @param predicate The function invoked per iteration. + * @param fromIndex The index to search from. + * @return Returns the index of the found element, else -1. + */ + findLastIndex( + array: List | null | undefined, + predicate?: ListIterateeCustom, + fromIndex?: number + ): number; + } + + interface LoDashImplicitWrapper { + /** + * @see _.findLastIndex + */ + findLastIndex( + this: LoDashImplicitWrapper | null | undefined>, + predicate?: ListIterateeCustom, + fromIndex?: number + ): number; + } + + interface LoDashExplicitWrapper { + /** + * @see _.findLastIndex + */ + findLastIndex( + this: LoDashExplicitWrapper | null | undefined>, + predicate?: ListIterateeCustom, + fromIndex?: number + ): LoDashExplicitWrapper; + } + + // first + + interface LoDashStatic { + first: typeof _.head; // tslint:disable-line:no-unnecessary-qualifier + } + + interface LoDashImplicitWrapper { + /** + * @see _.head + */ + first(this: LoDashImplicitWrapper | null | undefined>): T | undefined; + } + + interface LoDashExplicitWrapper { + /** + * @see _.head + */ + first(this: LoDashExplicitWrapper | null | undefined>): LoDashExplicitWrapper; + } + + interface RecursiveArray extends Array> {} + interface ListOfRecursiveArraysOrValues extends List> {} + + // flatten + + interface LoDashStatic { + /** + * Flattens `array` a single level deep. + * + * @param array The array to flatten. + * @return Returns the new flattened array. + */ + flatten(array: List> | null | undefined): T[]; + } + + interface LoDashImplicitWrapper { + /** + * @see _.flatten + */ + flatten(this: LoDashImplicitWrapper> | null | undefined>): LoDashImplicitWrapper; + } + + interface LoDashExplicitWrapper { + /** + * @see _.flatten + */ + flatten(this: LoDashExplicitWrapper> | null | undefined>): LoDashExplicitWrapper; + } + + // flattenDeep + + interface LoDashStatic { + /** + * Recursively flattens a nested array. + * + * @param array The array to recursively flatten. + * @return Returns the new flattened array. + */ + flattenDeep(array: ListOfRecursiveArraysOrValues | null | undefined): T[]; + } + + interface LoDashImplicitWrapper { + /** + * @see _.flattenDeep + */ + flattenDeep(this: LoDashImplicitWrapper | null | undefined>): LoDashImplicitWrapper; + } + + interface LoDashExplicitWrapper { + /** + * @see _.flattenDeep + */ + flattenDeep(this: LoDashExplicitWrapper | null | undefined>): LoDashExplicitWrapper; + } + + // flattenDepth + + interface LoDashStatic { + /** + * Recursively flatten array up to depth times. + * + * @param array The array to recursively flatten. + * @param number The maximum recursion depth. + * @return Returns the new flattened array. + */ + flattenDepth(array: ListOfRecursiveArraysOrValues | null | undefined, depth?: number): T[]; + } + + interface LoDashImplicitWrapper { + /** + * @see _.flattenDeep + */ + flattenDepth(this: LoDashImplicitWrapper | null | undefined>, depth?: number): LoDashImplicitWrapper; + } + + interface LoDashExplicitWrapper { + /** + * @see _.flattenDeep + */ + flattenDepth(this: LoDashExplicitWrapper | null | undefined>, depth?: number): LoDashExplicitWrapper; + } + + // fromPairs + + interface LoDashStatic { + /** + * The inverse of `_.toPairs`; this method returns an object composed + * from key-value `pairs`. + * + * @category Array + * @param pairs The key-value pairs. + * @returns Returns the new object. + * @example + * + * _.fromPairs([['fred', 30], ['barney', 40]]); + * // => { 'fred': 30, 'barney': 40 } + */ + fromPairs( + pairs: List<[PropertyName, T]> | null | undefined + ): Dictionary; + + /** + @see _.fromPairs + */ + fromPairs( + pairs: List | null | undefined + ): Dictionary; + } + + interface LoDashImplicitWrapper { + /** + * @see _.fromPairs + */ + fromPairs( + this: LoDashImplicitWrapper | null | undefined> + ): LoDashImplicitWrapper>; + + /** + @see _.fromPairs + */ + fromPairs( + this: LoDashImplicitWrapper | null | undefined> + ): LoDashImplicitWrapper>; + } + + interface LoDashExplicitWrapper { + /** + * @see _.fromPairs + */ + fromPairs( + this: LoDashExplicitWrapper | null | undefined> + ): LoDashExplicitWrapper>; + + /** + @see _.fromPairs + */ + fromPairs( + this: LoDashExplicitWrapper | null | undefined> + ): LoDashExplicitWrapper>; + } + + // head + + interface LoDashStatic { + /** + * Gets the first element of array. + * + * @alias _.first + * + * @param array The array to query. + * @return Returns the first element of array. + */ + head(array: List | null | undefined): T | undefined; + } + + interface LoDashImplicitWrapper { + /** + * @see _.head + */ + head(this: LoDashImplicitWrapper | null | undefined>): T | undefined; + } + + interface LoDashExplicitWrapper { + /** + * @see _.head + */ + head(this: LoDashExplicitWrapper | null | undefined>): LoDashExplicitWrapper; + } + + // indexOf + + interface LoDashStatic { + /** + * Gets the index at which the first occurrence of `value` is found in `array` + * using [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero) + * for equality comparisons. If `fromIndex` is negative, it's used as the offset + * from the end of `array`. + * + * @category Array + * @param array The array to search. + * @param value The value to search for. + * @param [fromIndex=0] The index to search from. + * @returns Returns the index of the matched value, else `-1`. + * @example + * + * _.indexOf([1, 2, 1, 2], 2); + * // => 1 + * + * // using `fromIndex` + * _.indexOf([1, 2, 1, 2], 2, 2); + * // => 3 + */ + indexOf( + array: List | null | undefined, + value: T, + fromIndex?: number + ): number; + } + + interface LoDashImplicitWrapper { + /** + * @see _.indexOf + */ + indexOf( + this: LoDashImplicitWrapper | null | undefined>, + value: T, + fromIndex?: number + ): number; + } + + interface LoDashExplicitWrapper { + /** + * @see _.indexOf + */ + indexOf( + this: LoDashExplicitWrapper | null | undefined>, + value: T, + fromIndex?: number + ): LoDashExplicitWrapper; + } + + // initial + + interface LoDashStatic { + /** + * Gets all but the last element of array. + * + * @param array The array to query. + * @return Returns the slice of array. + */ + initial(array: List | null | undefined): T[]; + } + + interface LoDashImplicitWrapper { + /** + * @see _.initial + */ + initial(this: LoDashImplicitWrapper | null | undefined>): LoDashImplicitWrapper; + } + + interface LoDashExplicitWrapper { + /** + * @see _.initial + */ + initial(this: LoDashExplicitWrapper | null | undefined>): LoDashExplicitWrapper; + } + + // intersection + + interface LoDashStatic { + /** + * Creates an array of unique values that are included in all of the provided arrays using SameValueZero for + * equality comparisons. + * + * @param arrays The arrays to inspect. + * @return Returns the new array of shared values. + */ + intersection(...arrays: Array>): T[]; + } + + interface LoDashImplicitWrapper { + /** + * @see _.intersection + */ + intersection( + this: LoDashImplicitWrapper>, + ...arrays: Array> + ): LoDashImplicitWrapper; + } + + interface LoDashExplicitWrapper { + /** + * @see _.intersection + */ + intersection( + this: LoDashExplicitWrapper>, + ...arrays: Array> + ): LoDashExplicitWrapper; + } + + // intersectionBy + + interface LoDashStatic { + /** + * This method is like `_.intersection` except that it accepts `iteratee` + * which is invoked for each element of each `arrays` to generate the criterion + * by which uniqueness is computed. The iteratee is invoked with one argument: (value). + * + * @category Array + * @param [arrays] The arrays to inspect. + * @param [iteratee=_.identity] The iteratee invoked per element. + * @returns Returns the new array of shared values. + * @example + * + * _.intersectionBy([2.1, 1.2], [4.3, 2.4], Math.floor); + * // => [2.1] + * + * // using the `_.property` iteratee shorthand + * _.intersectionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); + * // => [{ 'x': 1 }] + */ + intersectionBy( + array: List | null, + values: List, + iteratee: ValueIteratee + ): T1[]; + + /** + * @see _.intersectionBy + */ + intersectionBy( + array: List | null, + values1: List, + values2: List, + iteratee: ValueIteratee + ): T1[]; + + /** + * @see _.intersectionBy + */ + intersectionBy( + array: List | null | undefined, + values1: List, + values2: List, + ...values: Array | ValueIteratee> + ): T1[]; + + /** + * @see _.intersectionBy + */ + intersectionBy( + array?: List | null, + ...values: Array> + ): T[]; + } + + interface LoDashImplicitWrapper { + /** + * @see _.intersectionBy + */ + intersectionBy( + this: LoDashImplicitWrapper | null | undefined>, + values: List, + iteratee: ValueIteratee + ): LoDashImplicitWrapper; + + /** + * @see _.intersectionBy + */ + intersectionBy( + this: LoDashImplicitWrapper | null | undefined>, + values1: List, + values2: List, + iteratee: ValueIteratee + ): LoDashImplicitWrapper; + + /** + * @see _.intersectionBy + */ + intersectionBy( + this: LoDashImplicitWrapper | null | undefined>, + values1: List, + values2: List, + ...values: Array | ValueIteratee> + ): LoDashImplicitWrapper; + + /** + * @see _.intersectionBy + */ + intersectionBy( + this: LoDashImplicitWrapper | null | undefined>, + ...values: Array> + ): LoDashImplicitWrapper; + } + + interface LoDashExplicitWrapper { + /** + * @see _.intersectionBy + */ + intersectionBy( + this: LoDashExplicitWrapper | null | undefined>, + values: List, + iteratee: ValueIteratee + ): LoDashExplicitWrapper; + + /** + * @see _.intersectionBy + */ + intersectionBy( + this: LoDashExplicitWrapper | null | undefined>, + values1: List, + values2: List, + iteratee: ValueIteratee + ): LoDashExplicitWrapper; + + /** + * @see _.intersectionBy + */ + intersectionBy( + this: LoDashExplicitWrapper | null | undefined>, + values1: List, + values2: List, + ...values: Array | ValueIteratee> + ): LoDashExplicitWrapper; + + /** + * @see _.intersectionBy + */ + intersectionBy( + this: LoDashExplicitWrapper | null | undefined>, + ...values: Array> + ): LoDashExplicitWrapper; + } + + // intersectionWith + + interface LoDashStatic { + /** + * Creates an array of unique `array` values not included in the other + * provided arrays using [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero) + * for equality comparisons. + * + * @category Array + * @param [values] The arrays to inspect. + * @param [comparator] The comparator invoked per element. + * @returns Returns the new array of filtered values. + * @example + * + * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; + * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; + + * _.intersectionWith(objects, others, _.isEqual); + * // => [{ 'x': 1, 'y': 2 }] + */ + intersectionWith( + array: List | null | undefined, + values: List, + comparator: Comparator2 + ): T1[]; + + /** + * @see _.intersectionWith + */ + intersectionWith( + array: List | null | undefined, + values1: List, + values2: List, + comparator: Comparator2 + ): T1[]; + + /** + * @see _.intersectionWith + */ + intersectionWith( + array: List | null | undefined, + values1: List, + values2: List, + ...values: Array | Comparator2> + ): T1[]; + + /** + * @see _.intersectionWith + */ + intersectionWith( + array?: List | null, + ...values: Array> + ): T[]; + } + + interface LoDashImplicitWrapper { + /** + * @see _.intersectionWith + */ + intersectionWith( + this: LoDashImplicitWrapper | null | undefined>, + values: List, + comparator: Comparator2 + ): LoDashImplicitWrapper; + + /** + * @see _.intersectionWith + */ + intersectionWith( + this: LoDashImplicitWrapper | null | undefined>, + values1: List, + values2: List, + comparator: Comparator2 + ): LoDashImplicitWrapper; + + /** + * @see _.intersectionWith + */ + intersectionWith( + this: LoDashImplicitWrapper | null | undefined>, + values1: List, + values2: List, + ...values: Array | Comparator2> + ): LoDashImplicitWrapper; + + /** + * @see _.intersectionWith + */ + intersectionWith( + this: LoDashImplicitWrapper | null | undefined>, + ...values: Array> + ): LoDashImplicitWrapper; + } + + interface LoDashExplicitWrapper { + /** + * @see _.intersectionWith + */ + intersectionWith( + this: LoDashExplicitWrapper | null | undefined>, + values: List, + comparator: Comparator2 + ): LoDashExplicitWrapper; + + /** + * @see _.intersectionWith + */ + intersectionWith( + this: LoDashExplicitWrapper | null | undefined>, + values1: List, + values2: List, + comparator: Comparator2 + ): LoDashExplicitWrapper; + + /** + * @see _.intersectionWith + */ + intersectionWith( + this: LoDashExplicitWrapper | null | undefined>, + values1: List, + values2: List, + ...values: Array | Comparator2> + ): LoDashExplicitWrapper; + + /** + * @see _.intersectionWith + */ + intersectionWith( + this: LoDashExplicitWrapper | null | undefined>, + ...values: Array> + ): LoDashExplicitWrapper; + } + + // join + + interface LoDashStatic { + /** + * Converts all elements in `array` into a string separated by `separator`. + * + * @param array The array to convert. + * @param separator The element separator. + * @returns Returns the joined string. + */ + join( + array: List | null | undefined, + separator?: string + ): string; + } + + interface LoDashImplicitWrapper { + /** + * @see _.join + */ + join(separator?: string): string; + } + + interface LoDashExplicitWrapper { + /** + * @see _.join + */ + join(separator?: string): LoDashExplicitWrapper; + } + + // last + + interface LoDashStatic { + /** + * Gets the last element of array. + * + * @param array The array to query. + * @return Returns the last element of array. + */ + last(array: List | null | undefined): T | undefined; + } + + interface LoDashImplicitWrapper { + /** + * @see _.last + */ + last(this: LoDashImplicitWrapper | null | undefined>): T | undefined; + } + + interface LoDashExplicitWrapper { + /** + * @see _.last + */ + last(this: LoDashExplicitWrapper | null | undefined>): LoDashExplicitWrapper; + } + + // lastIndexOf + + interface LoDashStatic { + /** + * This method is like _.indexOf except that it iterates over elements of array from right to left. + * + * @param array The array to search. + * @param value The value to search for. + * @param fromIndex The index to search from or true to perform a binary search on a sorted array. + * @return Returns the index of the matched value, else -1. + */ + lastIndexOf( + array: List | null | undefined, + value: T, + fromIndex?: true|number + ): number; + } + + interface LoDashImplicitWrapper { + /** + * @see _.indexOf + */ + lastIndexOf( + this: LoDashImplicitWrapper | null | undefined>, + value: T, + fromIndex?: true|number + ): number; + } + + interface LoDashExplicitWrapper { + /** + * @see _.indexOf + */ + lastIndexOf( + this: LoDashExplicitWrapper | null | undefined>, + value: T, + fromIndex?: true|number + ): LoDashExplicitWrapper; + } + + // nth + + interface LoDashStatic { + /** + * Gets the element at index `n` of `array`. If `n` is negative, the nth element from the end is returned. + * + * @param array array The array to query. + * @param value The index of the element to return. + * @return Returns the nth element of `array`. + */ + nth( + array: List | null | undefined, + n?: number + ): T | undefined; + } + + interface LoDashImplicitWrapper { + /** + * @see _.nth + */ + nth( + this: LoDashImplicitWrapper | null | undefined>, + n?: number + ): T | undefined; + } + + interface LoDashExplicitWrapper { + /** + * @see _.nth + */ + nth( + this: LoDashExplicitWrapper | null | undefined>, + n?: number + ): LoDashExplicitWrapper; + } + + // pull + + interface LoDashStatic { + /** + * Removes all provided values from array using SameValueZero for equality comparisons. + * + * Note: Unlike _.without, this method mutates array. + * + * @param array The array to modify. + * @param values The values to remove. + * @return Returns array. + */ + pull( + array: T[], + ...values: T[] + ): T[]; + + /** + * @see _.pull + */ + pull( + array: List, + ...values: T[] + ): List; + } + + interface LoDashImplicitWrapper { + /** + * @see _.pull + */ + pull( + this: LoDashImplicitWrapper>, + ...values: T[] + ): this; + } + + interface LoDashExplicitWrapper { + /** + * @see _.pull + */ + pull( + this: LoDashExplicitWrapper>, + ...values: T[] + ): this; + } + + // pullAll + + interface LoDashStatic { + /** + * This method is like `_.pull` except that it accepts an array of values to remove. + * + * **Note:** Unlike `_.difference`, this method mutates `array`. + * + * @category Array + * @param array The array to modify. + * @param values The values to remove. + * @returns Returns `array`. + * @example + * + * var array = [1, 2, 3, 1, 2, 3]; + * + * _.pull(array, [2, 3]); + * console.log(array); + * // => [1, 1] + */ + pullAll( + array: T[], + values?: List, + ): T[]; + + /** + * @see _.pullAll + */ + pullAll( + array: List, + values?: List, + ): List; + } + + interface LoDashImplicitWrapper { + /** + * @see _.pullAll + */ + pullAll( + this: LoDashImplicitWrapper>, + values?: List + ): this; + } + + interface LoDashExplicitWrapper { + /** + * @see _.pullAll + */ + pullAll( + this: LoDashExplicitWrapper>, + values?: List + ): this; + } + + // pullAllBy + + interface LoDashStatic { + /** + * This method is like `_.pullAll` except that it accepts `iteratee` which is + * invoked for each element of `array` and `values` to to generate the criterion + * by which uniqueness is computed. The iteratee is invoked with one argument: (value). + * + * **Note:** Unlike `_.differenceBy`, this method mutates `array`. + * + * @category Array + * @param array The array to modify. + * @param values The values to remove. + * @param [iteratee=_.identity] The iteratee invoked per element. + * @returns Returns `array`. + * @example + * + * var array = [{ 'x': 1 }, { 'x': 2 }, { 'x': 3 }, { 'x': 1 }]; + * + * _.pullAllBy(array, [{ 'x': 1 }, { 'x': 3 }], 'x'); + * console.log(array); + * // => [{ 'x': 2 }] + */ + pullAllBy( + array: T[], + values?: List, + iteratee?: ValueIteratee + ): T[]; + + /** + * @see _.pullAllBy + */ + pullAllBy( + array: List, + values?: List, + iteratee?: ValueIteratee + ): List; + + /** + * @see _.pullAllBy + */ + pullAllBy( + array: T1[], + values: List, + iteratee: ValueIteratee + ): T1[]; + + /** + * @see _.pullAllBy + */ + pullAllBy( + array: List, + values: List, + iteratee: ValueIteratee + ): List; + } + + interface LoDashWrapper { + /** + * @see _.pullAllBy + */ + pullAllBy( + this: LoDashWrapper>, + values?: List, + iteratee?: ValueIteratee + ): this; + + /** + * @see _.pullAllBy + */ + pullAllBy( + this: LoDashWrapper>, + values: List, + iteratee: ValueIteratee + ): this; + } + + // pullAllWith + + interface LoDashStatic { + /** + * This method is like `_.pullAll` except that it accepts `comparator` which is + * invoked to compare elements of array to values. The comparator is invoked with + * two arguments: (arrVal, othVal). + * + * **Note:** Unlike `_.differenceWith`, this method mutates `array`. + * + * @category Array + * @param array The array to modify. + * @param values The values to remove. + * @param [iteratee=_.identity] The iteratee invoked per element. + * @returns Returns `array`. + * @example + * + * var array = [{ 'x': 1, 'y': 2 }, { 'x': 3, 'y': 4 }, { 'x': 5, 'y': 6 }]; + * + * _.pullAllWith(array, [{ 'x': 3, 'y': 4 }], _.isEqual); + * console.log(array); + * // => [{ 'x': 1, 'y': 2 }, { 'x': 5, 'y': 6 }] + */ + pullAllWith( + array: T[], + values?: List, + comparator?: Comparator + ): T[]; + + /** + * @see _.pullAllWith + */ + pullAllWith( + array: List, + values?: List, + comparator?: Comparator + ): List; + + /** + * @see _.pullAllWith + */ + pullAllWith( + array: T1[], + values: List, + comparator: Comparator2 + ): T1[]; + + /** + * @see _.pullAllWith + */ + pullAllWith( + array: List, + values: List, + comparator: Comparator2 + ): List; + } + + interface LoDashWrapper { + /** + * @see _.pullAllWith + */ + pullAllWith( + this: LoDashWrapper>, + values?: List, + comparator?: Comparator + ): this; + + /** + * @see _.pullAllWith + */ + pullAllWith( + this: LoDashWrapper>, + values: List, + comparator: Comparator2 + ): this; + } + + // pullAt + + interface LoDashStatic { + /** + * Removes elements from array corresponding to the given indexes and returns an array of the removed elements. + * Indexes may be specified as an array of indexes or as individual arguments. + * + * Note: Unlike _.at, this method mutates array. + * + * @param array The array to modify. + * @param indexes The indexes of elements to remove, specified as individual indexes or arrays of indexes. + * @return Returns the new array of removed elements. + */ + pullAt( + array: T[], + ...indexes: Array> + ): T[]; + + /** + * @see _.pullAt + */ + pullAt( + array: List, + ...indexes: Array> + ): List; + } + + interface LoDashWrapper { + /** + * @see _.pullAt + */ + pullAt(...indexes: Array>): this; + } + + // remove + + interface LoDashStatic { + /** + * Removes all elements from array that predicate returns truthy for and returns an array of the removed + * elements. The predicate is invoked with three arguments: (value, index, array). + * + * Note: Unlike _.filter, this method mutates array. + * + * @param array The array to modify. + * @param predicate The function invoked per iteration. + * @return Returns the new array of removed elements. + */ + remove( + array: List, + predicate?: ListIteratee + ): T[]; + } + + interface LoDashImplicitWrapper { + /** + * @see _.remove + */ + remove( + this: LoDashImplicitWrapper>, + predicate?: ListIteratee + ): LoDashImplicitWrapper; + } + + interface LoDashExplicitWrapper { + /** + * @see _.remove + */ + remove( + this: LoDashExplicitWrapper>, + predicate?: ListIteratee + ): LoDashExplicitWrapper; + } + + // reverse + + interface LoDashStatic { + /** + * Reverses `array` so that the first element becomes the last, the second + * element becomes the second to last, and so on. + * + * **Note:** This method mutates `array` and is based on + * [`Array#reverse`](https://mdn.io/Array/reverse). + * + * @category Array + * @returns Returns `array`. + * @example + * + * var array = [1, 2, 3]; + * + * _.reverse(array); + * // => [3, 2, 1] + * + * console.log(array); + * // => [3, 2, 1] + */ + reverse>( + array: TList, + ): TList; + } + + // slice + + interface LoDashStatic { + /** + * Creates a slice of array from start up to, but not including, end. + * + * @param array The array to slice. + * @param start The start position. + * @param end The end position. + * @return Returns the slice of array. + */ + slice( + array: List | null | undefined, + start?: number, + end?: number + ): T[]; + } + + interface LoDashImplicitWrapper { + /** + * @see _.slice + */ + slice( + this: LoDashImplicitWrapper | null | undefined>, + start?: number, + end?: number + ): LoDashImplicitWrapper; + } + + interface LoDashExplicitWrapper { + /** + * @see _.slice + */ + slice( + this: LoDashExplicitWrapper | null | undefined>, + start?: number, + end?: number + ): LoDashExplicitWrapper; + } + + // sortedIndex + + interface LoDashStatic { + /** + * Uses a binary search to determine the lowest index at which `value` should + * be inserted into `array` in order to maintain its sort order. + * + * @category Array + * @param array The sorted array to inspect. + * @param value The value to evaluate. + * @returns Returns the index at which `value` should be inserted into `array`. + * @example + * + * _.sortedIndex([30, 50], 40); + * // => 1 + * + * _.sortedIndex([4, 5], 4); + * // => 0 + */ + sortedIndex( + array: List | null | undefined, + value: T + ): number; + } + + interface LoDashImplicitWrapper { + /** + * @see _.sortedIndex + */ + sortedIndex( + this: LoDashImplicitWrapper | null | undefined>, + value: T + ): number; + } + + interface LoDashExplicitWrapper { + /** + * @see _.sortedIndex + */ + sortedIndex( + this: LoDashExplicitWrapper | null | undefined>, + value: T + ): LoDashExplicitWrapper; + } + + // sortedIndexBy + + interface LoDashStatic { + /** + * Uses a binary search to determine the lowest index at which `value` should + * be inserted into `array` in order to maintain its sort order. + * + * @category Array + * @param array The sorted array to inspect. + * @param value The value to evaluate. + * @returns Returns the index at which `value` should be inserted into `array`. + * @example + * + * _.sortedIndex([30, 50], 40); + * // => 1 + * + * _.sortedIndex([4, 5], 4); + * // => 0 + */ + sortedIndex( + array: List | null | undefined, + value: T + ): number; + } + + interface LoDashImplicitWrapper { + /** + * @see _.sortedIndex + */ + sortedIndex( + this: LoDashImplicitWrapper | null | undefined>, + value: T + ): number; + } + + interface LoDashExplicitWrapper { + /** + * @see _.sortedIndex + */ + sortedIndex( + this: LoDashExplicitWrapper | null | undefined>, + value: T + ): LoDashExplicitWrapper; + } + + // _.sortedIndexBy + interface LoDashStatic { + /** + * This method is like `_.sortedIndex` except that it accepts `iteratee` + * which is invoked for `value` and each element of `array` to compute their + * sort ranking. The iteratee is invoked with one argument: (value). + * + * @category Array + * @param array The sorted array to inspect. + * @param value The value to evaluate. + * @param [iteratee=_.identity] The iteratee invoked per element. + * @returns Returns the index at which `value` should be inserted into `array`. + * @example + * + * var dict = { 'thirty': 30, 'forty': 40, 'fifty': 50 }; + * + * _.sortedIndexBy(['thirty', 'fifty'], 'forty', _.propertyOf(dict)); + * // => 1 + * + * // using the `_.property` iteratee shorthand + * _.sortedIndexBy([{ 'x': 4 }, { 'x': 5 }], { 'x': 4 }, 'x'); + * // => 0 + */ + sortedIndexBy( + array: List | null | undefined, + value: T, + iteratee?: ValueIteratee + ): number; + } + + interface LoDashImplicitWrapper { + /** + * @see _.sortedIndexBy + */ + sortedIndexBy( + this: LoDashImplicitWrapper | null | undefined>, + value: T, + iteratee?: ValueIteratee + ): number; + } + + interface LoDashExplicitWrapper { + /** + * @see _.sortedIndexBy + */ + sortedIndexBy( + this: LoDashExplicitWrapper | null | undefined>, + value: T, + iteratee?: ValueIteratee + ): LoDashExplicitWrapper; + } + + // sortedIndexOf + + interface LoDashStatic { + /** + * This method is like `_.indexOf` except that it performs a binary + * search on a sorted `array`. + * + * @category Array + * @param array The array to search. + * @param value The value to search for. + * @returns Returns the index of the matched value, else `-1`. + * @example + * + * _.sortedIndexOf([1, 1, 2, 2], 2); + * // => 2 + */ + sortedIndexOf( + array: List | null | undefined, + value: T + ): number; + } + + interface LoDashImplicitWrapper { + /** + * @see _.sortedIndexOf + */ + sortedIndexOf( + this: LoDashImplicitWrapper | null | undefined>, + value: T + ): number; + } + + interface LoDashExplicitWrapper { + /** + * @see _.sortedIndexOf + */ + sortedIndexOf( + this: LoDashExplicitWrapper | null | undefined>, + value: T + ): LoDashExplicitWrapper; + } + + // sortedLastIndex + + interface LoDashStatic { + /** + * This method is like `_.sortedIndex` except that it returns the highest + * index at which `value` should be inserted into `array` in order to + * maintain its sort order. + * + * @category Array + * @param array The sorted array to inspect. + * @param value The value to evaluate. + * @returns Returns the index at which `value` should be inserted into `array`. + * @example + * + * _.sortedLastIndex([4, 5], 4); + * // => 1 + */ + sortedLastIndex( + array: List | null | undefined, + value: T + ): number; + } + + interface LoDashImplicitWrapper { + /** + * @see _.sortedLastIndex + */ + sortedLastIndex( + this: LoDashImplicitWrapper | null | undefined>, + value: T + ): number; + } + + interface LoDashExplicitWrapper { + /** + * @see _.sortedLastIndex + */ + sortedLastIndex( + this: LoDashExplicitWrapper | null | undefined>, + value: T + ): LoDashExplicitWrapper; + } + + // sortedLastIndexBy + + interface LoDashStatic { + /** + * This method is like `_.sortedLastIndex` except that it accepts `iteratee` + * which is invoked for `value` and each element of `array` to compute their + * sort ranking. The iteratee is invoked with one argument: (value). + * + * @category Array + * @param array The sorted array to inspect. + * @param value The value to evaluate. + * @param [iteratee=_.identity] The iteratee invoked per element. + * @returns Returns the index at which `value` should be inserted into `array`. + * @example + * + * // using the `_.property` iteratee shorthand + * _.sortedLastIndexBy([{ 'x': 4 }, { 'x': 5 }], { 'x': 4 }, 'x'); + * // => 1 + */ + sortedLastIndexBy( + array: List | null | undefined, + value: T, + iteratee: ValueIteratee + ): number; + } + + interface LoDashImplicitWrapper { + /** + * @see _.sortedLastIndexBy + */ + sortedLastIndexBy( + this: LoDashImplicitWrapper | null | undefined>, + value: T, + iteratee: ValueIteratee + ): number; + } + + interface LoDashExplicitWrapper { + /** + * @see _.sortedLastIndexBy + */ + sortedLastIndexBy( + this: LoDashExplicitWrapper | null | undefined>, + value: T, + iteratee: ValueIteratee + ): LoDashExplicitWrapper; + } + + // sortedLastIndexOf + + interface LoDashStatic { + /** + * This method is like `_.lastIndexOf` except that it performs a binary + * search on a sorted `array`. + * + * @category Array + * @param array The array to search. + * @param value The value to search for. + * @returns Returns the index of the matched value, else `-1`. + * @example + * + * _.sortedLastIndexOf([1, 1, 2, 2], 2); + * // => 3 + */ + sortedLastIndexOf( + array: List | null | undefined, + value: T + ): number; + } + + interface LoDashImplicitWrapper { + /** + * @see _.sortedLastIndexOf + */ + sortedLastIndexOf( + this: LoDashImplicitWrapper | null | undefined>, + value: T + ): number; + } + + interface LoDashExplicitWrapper { + /** + * @see _.sortedLastIndexOf + */ + sortedLastIndexOf( + this: LoDashExplicitWrapper | null | undefined>, + value: T + ): LoDashExplicitWrapper; + } + + // sortedUniq + + interface LoDashStatic { + /** + * This method is like `_.uniq` except that it's designed and optimized + * for sorted arrays. + * + * @category Array + * @param array The array to inspect. + * @returns Returns the new duplicate free array. + * @example + * + * _.sortedUniq([1, 1, 2]); + * // => [1, 2] + */ + sortedUniq( + array: List | null | undefined + ): T[]; + } + + interface LoDashImplicitWrapper { + /** + * @see _.sortedUniq + */ + sortedUniq(this: LoDashImplicitWrapper | null | undefined>): LoDashImplicitWrapper; + } + + interface LoDashExplicitWrapper { + /** + * @see _.sortedUniq + */ + sortedUniq(this: LoDashExplicitWrapper | null | undefined>): LoDashExplicitWrapper; + } + + // sortedUniqBy + + interface LoDashStatic { + /** + * This method is like `_.uniqBy` except that it's designed and optimized + * for sorted arrays. + * + * @category Array + * @param array The array to inspect. + * @param [iteratee] The iteratee invoked per element. + * @returns Returns the new duplicate free array. + * @example + * + * _.sortedUniqBy([1.1, 1.2, 2.3, 2.4], Math.floor); + * // => [1.1, 2.2] + */ + sortedUniqBy( + array: List | null | undefined, + iteratee: ValueIteratee + ): T[]; + } + + interface LoDashImplicitWrapper { + /** + * @see _.sortedUniqBy + */ + sortedUniqBy( + this: LoDashImplicitWrapper | null | undefined>, + iteratee: ValueIteratee + ): LoDashImplicitWrapper; + } + + interface LoDashExplicitWrapper { + /** + * @see _.sortedUniqBy + */ + sortedUniqBy( + this: LoDashExplicitWrapper | null | undefined>, + iteratee: ValueIteratee + ): LoDashExplicitWrapper; + } + + // tail + + interface LoDashStatic { + /** + * Gets all but the first element of array. + * + * @param array The array to query. + * @return Returns the slice of array. + */ + tail(array: List | null | undefined): T[]; + } + + interface LoDashImplicitWrapper { + /** + * @see _.tail + */ + tail(this: LoDashImplicitWrapper | null | undefined>): LoDashImplicitWrapper; + } + + interface LoDashExplicitWrapper { + /** + * @see _.tail + */ + tail(this: LoDashExplicitWrapper | null | undefined>): LoDashExplicitWrapper; + } + + // take + + interface LoDashStatic { + /** + * Creates a slice of array with n elements taken from the beginning. + * + * @param array The array to query. + * @param n The number of elements to take. + * @return Returns the slice of array. + */ + take( + array: List | null | undefined, + n?: number + ): T[]; + } + + interface LoDashImplicitWrapper { + /** + * @see _.take + */ + take( + this: LoDashImplicitWrapper | null | undefined>, + n?: number + ): LoDashImplicitWrapper; + } + + interface LoDashExplicitWrapper { + /** + * @see _.take + */ + take( + this: LoDashExplicitWrapper | null | undefined>, + n?: number + ): LoDashExplicitWrapper; + } + + // takeRight + + interface LoDashStatic { + /** + * Creates a slice of array with n elements taken from the end. + * + * @param array The array to query. + * @param n The number of elements to take. + * @return Returns the slice of array. + */ + takeRight( + array: List | null | undefined, + n?: number + ): T[]; + } + + interface LoDashImplicitWrapper { + /** + * @see _.takeRight + */ + takeRight( + this: LoDashImplicitWrapper | null | undefined>, + n?: number + ): LoDashImplicitWrapper; + } + + interface LoDashExplicitWrapper { + /** + * @see _.takeRight + */ + takeRight( + this: LoDashExplicitWrapper | null | undefined>, + n?: number + ): LoDashExplicitWrapper; + } + + // takeRightWhile + + interface LoDashStatic { + /** + * Creates a slice of array with elements taken from the end. Elements are taken until predicate returns + * falsey. The predicate is invoked with three arguments: (value, index, array). + * + * @param array The array to query. + * @param predicate The function invoked per iteration. + * @return Returns the slice of array. + */ + takeRightWhile( + array: List | null | undefined, + predicate?: ListIteratee + ): T[]; + } + + interface LoDashImplicitWrapper { + /** + * @see _.takeRightWhile + */ + takeRightWhile( + this: LoDashImplicitWrapper | null | undefined>, + predicate?: ListIteratee + ): LoDashImplicitWrapper; + } + + interface LoDashExplicitWrapper { + /** + * @see _.takeRightWhile + */ + takeRightWhile( + this: LoDashExplicitWrapper | null | undefined>, + predicate?: ListIteratee + ): LoDashExplicitWrapper; + } + + // takeWhile + + interface LoDashStatic { + /** + * Creates a slice of array with elements taken from the beginning. Elements are taken until predicate returns + * falsey. The predicate is invoked with three arguments: (value, index, array). + * + * @param array The array to query. + * @param predicate The function invoked per iteration. + * @return Returns the slice of array. + */ + takeWhile( + array: List | null | undefined, + predicate?: ListIteratee + ): T[]; + } + + interface LoDashImplicitWrapper { + /** + * @see _.takeWhile + */ + takeWhile( + this: LoDashImplicitWrapper | null | undefined>, + predicate?: ListIteratee + ): LoDashImplicitWrapper; + } + + interface LoDashExplicitWrapper { + /** + * @see _.takeWhile + */ + takeWhile( + this: LoDashExplicitWrapper | null | undefined>, + predicate?: ListIteratee + ): LoDashExplicitWrapper; + } + + // union + + interface LoDashStatic { + /** + * Creates an array of unique values, in order, from all of the provided arrays using SameValueZero for + * equality comparisons. + * + * @param arrays The arrays to inspect. + * @return Returns the new array of combined values. + */ + union(...arrays: Array | null | undefined>): T[]; + } + + interface LoDashImplicitWrapper { + /** + * @see _.union + */ + union( + this: LoDashImplicitWrapper | null | undefined>, + ...arrays: Array | null | undefined> + ): LoDashImplicitWrapper; + } + + interface LoDashExplicitWrapper { + /** + * @see _.union + */ + union( + this: LoDashExplicitWrapper | null | undefined>, + ...arrays: Array | null | undefined> + ): LoDashExplicitWrapper; + } + + // unionBy + + interface LoDashStatic { + /** + * This method is like `_.union` except that it accepts `iteratee` which is + * invoked for each element of each `arrays` to generate the criterion by which + * uniqueness is computed. The iteratee is invoked with one argument: (value). + * + * @param arrays The arrays to inspect. + * @param iteratee The iteratee invoked per element. + * @return Returns the new array of combined values. + */ + unionBy( + arrays: List | null | undefined, + iteratee?: ValueIteratee + ): T[]; + + /** + * @see _.unionBy + */ + unionBy( + arrays1: List | null | undefined, + arrays2: List | null | undefined, + iteratee?: ValueIteratee + ): T[]; + + /** + * @see _.unionBy + */ + unionBy( + arrays1: List | null | undefined, + arrays2: List | null | undefined, + arrays3: List | null | undefined, + iteratee?: ValueIteratee + ): T[]; + + /** + * @see _.unionBy + */ + unionBy( + arrays1: List | null | undefined, + arrays2: List | null | undefined, + arrays3: List | null | undefined, + arrays4: List | null | undefined, + iteratee?: ValueIteratee + ): T[]; + + /** + * @see _.unionBy + */ + unionBy( + arrays1: List | null | undefined, + arrays2: List | null | undefined, + arrays3: List | null | undefined, + arrays4: List | null | undefined, + arrays5: List | null | undefined, + ...iteratee: Array | List | null | undefined> + ): T[]; + } + + interface LoDashImplicitWrapper { + /** + * @see _.unionBy + */ + unionBy( + this: LoDashImplicitWrapper | null | undefined>, + iteratee?: ValueIteratee + ): LoDashImplicitWrapper; + + /** + * @see _.unionBy + */ + unionBy( + this: LoDashImplicitWrapper | null | undefined>, + arrays2: List | null | undefined, + iteratee?: ValueIteratee + ): LoDashImplicitWrapper; + + /** + * @see _.unionBy + */ + unionBy( + this: LoDashImplicitWrapper | null | undefined>, + arrays2: List | null | undefined, + arrays3: List | null | undefined, + iteratee?: ValueIteratee + ): LoDashImplicitWrapper; + + /** + * @see _.unionBy + */ + unionBy( + this: LoDashImplicitWrapper | null | undefined>, + arrays2: List | null | undefined, + arrays3: List | null | undefined, + arrays4: List | null | undefined, + iteratee?: ValueIteratee + ): LoDashImplicitWrapper; + + /** + * @see _.unionBy + */ + unionBy( + this: LoDashImplicitWrapper | null | undefined>, + arrays2: List | null | undefined, + arrays3: List | null | undefined, + arrays4: List | null | undefined, + arrays5: List | null | undefined, + ...iteratee: Array | List | null | undefined> + ): LoDashImplicitWrapper; + } + + interface LoDashExplicitWrapper { + /** + * @see _.unionBy + */ + unionBy( + this: LoDashExplicitWrapper | null | undefined>, + iteratee?: ValueIteratee + ): LoDashExplicitWrapper; + + /** + * @see _.unionBy + */ + unionBy( + this: LoDashExplicitWrapper | null | undefined>, + arrays2: List | null | undefined, + iteratee?: ValueIteratee + ): LoDashExplicitWrapper; + + /** + * @see _.unionBy + */ + unionBy( + this: LoDashExplicitWrapper | null | undefined>, + arrays2: List | null | undefined, + arrays3: List | null | undefined, + iteratee?: ValueIteratee + ): LoDashExplicitWrapper; + + /** + * @see _.unionBy + */ + unionBy( + this: LoDashExplicitWrapper | null | undefined>, + arrays2: List | null | undefined, + arrays3: List | null | undefined, + arrays4: List | null | undefined, + iteratee?: ValueIteratee + ): LoDashExplicitWrapper; + + /** + * @see _.unionBy + */ + unionBy( + this: LoDashExplicitWrapper | null | undefined>, + arrays2: List | null | undefined, + arrays3: List | null | undefined, + arrays4: List | null | undefined, + arrays5: List | null | undefined, + ...iteratee: Array | List | null | undefined> + ): LoDashExplicitWrapper; + } + + // unionWith + + interface LoDashStatic { + /** + * This method is like `_.union` except that it accepts `comparator` which + * is invoked to compare elements of `arrays`. The comparator is invoked + * with two arguments: (arrVal, othVal). + * + * @category Array + * @param [arrays] The arrays to inspect. + * @param [comparator] The comparator invoked per element. + * @returns Returns the new array of combined values. + * @example + * + * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; + * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; + * + * _.unionWith(objects, others, _.isEqual); + * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }] + */ + unionWith( + arrays: List | null | undefined, + comparator?: Comparator + ): T[]; + + /** + * @see _.unionBy + */ + unionWith( + arrays: List | null | undefined, + arrays2: List | null | undefined, + comparator?: Comparator + ): T[]; + + /** + * @see _.unionWith + */ + unionWith( + arrays: List | null | undefined, + arrays2: List | null | undefined, + arrays3: List | null | undefined, + ...comparator: Array | List | null | undefined> + ): T[]; + } + + interface LoDashImplicitWrapper { + /** + * @see _.unionWith + */ + unionWith( + this: LoDashImplicitWrapper | null | undefined>, + comparator?: Comparator + ): LoDashImplicitWrapper; + + /** + * @see _.unionWith + */ + unionWith( + this: LoDashImplicitWrapper | null | undefined>, + arrays2: List | null | undefined, + comparator?: Comparator + ): LoDashImplicitWrapper; + + /** + * @see _.unionWith + */ + unionWith( + this: LoDashImplicitWrapper | null | undefined>, + arrays2: List | null | undefined, + arrays3: List | null | undefined, + ...comparator: Array | List | null | undefined> + ): LoDashImplicitWrapper; + } + + interface LoDashExplicitWrapper { + /** + * @see _.unionWith + */ + unionWith( + this: LoDashExplicitWrapper | null | undefined>, + comparator?: Comparator + ): LoDashExplicitWrapper; + + /** + * @see _.unionWith + */ + unionWith( + this: LoDashExplicitWrapper | null | undefined>, + arrays2: List | null | undefined, + comparator?: Comparator + ): LoDashExplicitWrapper; + + /** + * @see _.unionWith + */ + unionWith( + this: LoDashExplicitWrapper | null | undefined>, + arrays2: List | null | undefined, + arrays3: List | null | undefined, + ...comparator: Array | List | null | undefined> + ): LoDashExplicitWrapper; + } + + // uniq + + interface LoDashStatic { + /** + * Creates a duplicate-free version of an array, using + * [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero) + * for equality comparisons, in which only the first occurrence of each element + * is kept. + * + * @category Array + * @param array The array to inspect. + * @returns Returns the new duplicate free array. + * @example + * + * _.uniq([2, 1, 2]); + * // => [2, 1] + */ + uniq( + array: List | null | undefined + ): T[]; + } + + interface LoDashImplicitWrapper { + /** + * @see _.uniq + */ + uniq(this: LoDashImplicitWrapper | null | undefined>): LoDashImplicitWrapper; + } + + interface LoDashExplicitWrapper { + /** + * @see _.uniq + */ + uniq(this: LoDashExplicitWrapper | null | undefined>): LoDashExplicitWrapper; + } + + // uniqBy + + interface LoDashStatic { + /** + * This method is like `_.uniq` except that it accepts `iteratee` which is + * invoked for each element in `array` to generate the criterion by which + * uniqueness is computed. The iteratee is invoked with one argument: (value). + * + * @category Array + * @param array The array to inspect. + * @param [iteratee=_.identity] The iteratee invoked per element. + * @returns Returns the new duplicate free array. + * @example + * + * _.uniqBy([2.1, 1.2, 2.3], Math.floor); + * // => [2.1, 1.2] + * + * // using the `_.property` iteratee shorthand + * _.uniqBy([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x'); + * // => [{ 'x': 1 }, { 'x': 2 }] + */ + uniqBy( + array: List | null | undefined, + iteratee: ValueIteratee + ): T[]; + } + + interface LoDashImplicitWrapper { + /** + * @see _.uniqBy + */ + uniqBy( + this: LoDashImplicitWrapper | null | undefined>, + iteratee: ValueIteratee + ): LoDashImplicitWrapper; + } + + interface LoDashExplicitWrapper { + /** + * @see _.uniqBy + */ + uniqBy( + this: LoDashExplicitWrapper | null | undefined>, + iteratee: ValueIteratee + ): LoDashExplicitWrapper; + } + + // uniqWith + + interface LoDashStatic { + /** + * This method is like `_.uniq` except that it accepts `comparator` which + * is invoked to compare elements of `array`. The comparator is invoked with + * two arguments: (arrVal, othVal). + * + * @category Array + * @param array The array to inspect. + * @param [comparator] The comparator invoked per element. + * @returns Returns the new duplicate free array. + * @example + * + * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 2 }]; + * + * _.uniqWith(objects, _.isEqual); + * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }] + */ + uniqWith( + array: List | null | undefined, + comparator?: Comparator + ): T[]; + } + + interface LoDashImplicitWrapper { + /** + * @see _.uniqWith + */ + uniqWith( + this: LoDashImplicitWrapper | null | undefined>, + comparator?: Comparator + ): LoDashImplicitWrapper; + } + + interface LoDashExplicitWrapper { + /** + * @see _.uniqWith + */ + uniqWith( + this: LoDashExplicitWrapper | null | undefined>, + comparator?: Comparator + ): LoDashExplicitWrapper; + } + + // unzip + + interface LoDashStatic { + /** + * This method is like _.zip except that it accepts an array of grouped elements and creates an array + * regrouping the elements to their pre-zip configuration. + * + * @param array The array of grouped elements to process. + * @return Returns the new array of regrouped elements. + */ + unzip(array: T[][] | List> | null | undefined): T[][]; + } + + interface LoDashImplicitWrapper { + /** + * @see _.unzip + */ + unzip(this: LoDashImplicitWrapper> | null | undefined>): LoDashImplicitWrapper; + } + + interface LoDashExplicitWrapper { + /** + * @see _.unzip + */ + unzip(this: LoDashExplicitWrapper> | null | undefined>): LoDashExplicitWrapper; + } + + // unzipWith + + interface LoDashStatic { + /** + * This method is like _.unzip except that it accepts an iteratee to specify how regrouped values should be + * combined. The iteratee is invoked with four arguments: (accumulator, value, index, group). + * + * @param array The array of grouped elements to process. + * @param iteratee The function to combine regrouped values. + * @return Returns the new array of regrouped elements. + */ + unzipWith( + array: List> | null | undefined, + iteratee: (...values: T[]) => TResult + ): TResult[]; + + /** + * @see _.unzipWith + */ + unzipWith( + array: List> | null | undefined + ): T[][]; + } + + interface LoDashImplicitWrapper { + /** + * @see _.unzipWith + */ + unzipWith( + this: LoDashImplicitWrapper> | null | undefined>, + iteratee: (...values: T[]) => TResult + ): LoDashImplicitWrapper; + + /** + * @see _.unzipWith + */ + unzipWith( + this: LoDashImplicitWrapper> | null | undefined> + ): LoDashImplicitWrapper; + } + + interface LoDashExplicitWrapper { + /** + * @see _.unzipWith + */ + unzipWith( + this: LoDashExplicitWrapper> | null | undefined>, + iteratee: (...values: T[]) => TResult + ): LoDashExplicitWrapper; + + /** + * @see _.unzipWith + */ + unzipWith( + this: LoDashExplicitWrapper> | null | undefined> + ): LoDashExplicitWrapper; + } + + // without + + interface LoDashStatic { + /** + * Creates an array excluding all provided values using SameValueZero for equality comparisons. + * + * @param array The array to filter. + * @param values The values to exclude. + * @return Returns the new array of filtered values. + */ + without( + array: List | null | undefined, + ...values: T[] + ): T[]; + } + + interface LoDashImplicitWrapper { + /** + * @see _.without + */ + without( + this: LoDashImplicitWrapper | null | undefined>, + ...values: T[] + ): LoDashImplicitWrapper; + } + + interface LoDashExplicitWrapper { + /** + * @see _.without + */ + without( + this: LoDashExplicitWrapper | null | undefined>, + ...values: T[] + ): LoDashExplicitWrapper; + } + + // xor + + interface LoDashStatic { + /** + * Creates an array of unique values that is the symmetric difference of the provided arrays. + * + * @param arrays The arrays to inspect. + * @return Returns the new array of values. + */ + xor(...arrays: Array | null | undefined>): T[]; + } + + interface LoDashImplicitWrapper { + /** + * @see _.xor + */ + xor( + this: LoDashImplicitWrapper | null | undefined>, + ...arrays: Array | null | undefined> + ): LoDashImplicitWrapper; + } + + interface LoDashExplicitWrapper { + /** + * @see _.xor + */ + xor( + this: LoDashExplicitWrapper | null | undefined>, + ...arrays: Array | null | undefined> + ): LoDashExplicitWrapper; + } + + // xorBy + + interface LoDashStatic { + /** + * This method is like `_.xor` except that it accepts `iteratee` which is + * invoked for each element of each `arrays` to generate the criterion by which + * uniqueness is computed. The iteratee is invoked with one argument: (value). + * + * @category Array + * @param [arrays] The arrays to inspect. + * @param [iteratee=_.identity] The iteratee invoked per element. + * @returns Returns the new array of values. + * @example + * + * _.xorBy([2.1, 1.2], [4.3, 2.4], Math.floor); + * // => [1.2, 4.3] + * + * // using the `_.property` iteratee shorthand + * _.xorBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); + * // => [{ 'x': 2 }] + */ + xorBy( + arrays: List | null | undefined, + iteratee?: ValueIteratee + ): T[]; + + /** + * @see _.xorBy + */ + xorBy( + arrays: List | null | undefined, + arrays2: List | null | undefined, + iteratee?: ValueIteratee + ): T[]; + + /** + * @see _.xorBy + */ + xorBy( + arrays: List | null | undefined, + arrays2: List | null | undefined, + arrays3: List | null | undefined, + ...iteratee: Array | List | null | undefined> + ): T[]; + } + + interface LoDashImplicitWrapper { + /** + * @see _.xor + */ + xorBy( + this: LoDashImplicitWrapper | null | undefined>, + iteratee?: ValueIteratee + ): LoDashImplicitWrapper; + + /** + * @see _.xorBy + */ + xorBy( + this: LoDashImplicitWrapper | null | undefined>, + arrays2: List | null | undefined, + iteratee?: ValueIteratee + ): LoDashImplicitWrapper; + + /** + * @see _.xorBy + */ + xorBy( + this: LoDashImplicitWrapper | null | undefined>, + arrays2: List | null | undefined, + arrays3: List | null | undefined, + ...iteratee: Array | List | null | undefined> + ): LoDashImplicitWrapper; + } + + interface LoDashExplicitWrapper { + /** + * @see _.xorBy + */ + xorBy( + this: LoDashExplicitWrapper | null | undefined>, + iteratee?: ValueIteratee + ): LoDashExplicitWrapper; + + /** + * @see _.xorBy + */ + xorBy( + this: LoDashExplicitWrapper | null | undefined>, + arrays2: List | null | undefined, + iteratee?: ValueIteratee + ): LoDashExplicitWrapper; + + /** + * @see _.xorBy + */ + xorBy( + this: LoDashExplicitWrapper | null | undefined>, + arrays2: List | null | undefined, + arrays3: List | null | undefined, + ...iteratee: Array | List | null | undefined> + ): LoDashExplicitWrapper; + } + + // xorWith + + interface LoDashStatic { + /** + * This method is like `_.xor` except that it accepts `comparator` which is + * invoked to compare elements of `arrays`. The comparator is invoked with + * two arguments: (arrVal, othVal). + * + * @category Array + * @param [arrays] The arrays to inspect. + * @param [comparator] The comparator invoked per element. + * @returns Returns the new array of values. + * @example + * + * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; + * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; + * + * _.xorWith(objects, others, _.isEqual); + * // => [{ 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }] + */ + xorWith( + arrays: List | null | undefined, + comparator?: Comparator + ): T[]; + + /** + * @see _.xorWith + */ + xorWith( + arrays: List | null | undefined, + arrays2: List | null | undefined, + comparator?: Comparator + ): T[]; + + /** + * @see _.xorWith + */ + xorWith( + arrays: List | null | undefined, + arrays2: List | null | undefined, + arrays3: List | null | undefined, + ...comparator: Array | List | null | undefined> + ): T[]; + } + + interface LoDashImplicitWrapper { + /** + * @see _.xorWith + */ + xorWith( + this: LoDashImplicitWrapper | null | undefined>, + comparator?: Comparator + ): LoDashImplicitWrapper; + + /** + * @see _.xorWith + */ + xorWith( + this: LoDashImplicitWrapper | null | undefined>, + arrays2: List | null | undefined, + comparator?: Comparator + ): LoDashImplicitWrapper; + + /** + * @see _.xorWith + */ + xorWith( + this: LoDashImplicitWrapper | null | undefined>, + arrays2: List | null | undefined, + arrays3: List | null | undefined, + ...comparator: Array | List | null | undefined> + ): LoDashImplicitWrapper; + } + + interface LoDashExplicitWrapper { + /** + * @see _.xorWith + */ + xorWith( + this: LoDashExplicitWrapper | null | undefined>, + comparator?: Comparator + ): LoDashExplicitWrapper; + + /** + * @see _.xorWith + */ + xorWith( + this: LoDashExplicitWrapper | null | undefined>, + arrays2: List | null | undefined, + comparator?: Comparator + ): LoDashExplicitWrapper; + + /** + * @see _.xorWith + */ + xorWith( + this: LoDashExplicitWrapper | null | undefined>, + arrays2: List | null | undefined, + arrays3: List | null | undefined, + ...comparator: Array | List | null | undefined> + ): LoDashExplicitWrapper; + } + + // zip + + interface LoDashStatic { + /** + * Creates an array of grouped elements, the first of which contains the first elements of the given arrays, + * the second of which contains the second elements of the given arrays, and so on. + * + * @param arrays The arrays to process. + * @return Returns the new array of grouped elements. + */ + zip(arrays1: List, arrays2: List): Array<[T1 | undefined, T2 | undefined]>; + + /** + * @see _.zip + */ + zip(arrays1: List, arrays2: List, arrays3: List): Array<[T1 | undefined, T2 | undefined, T3 | undefined]>; + + /** + * @see _.zip + */ + zip(arrays1: List, arrays2: List, arrays3: List, arrays4: List): Array<[T1 | undefined, T2 | undefined, T3 | undefined, T4 | undefined]>; + + /** + * @see _.zip + */ + zip(arrays1: List, arrays2: List, arrays3: List, arrays4: List, arrays5: List): Array<[T1 | undefined, T2 | undefined, T3 | undefined, T4 | undefined, T5 | undefined]>; + + /** + * @see _.zip + */ + zip(...arrays: Array | null | undefined>): Array>; + } + + interface LoDashImplicitWrapper { + /** + * @see _.zip + */ + zip( + this: LoDashImplicitWrapper>, + arrays2: List, + ): LoDashImplicitWrapper>; + + /** + * @see _.zip + */ + zip( + this: LoDashImplicitWrapper>, + arrays2: List, + arrays3: List, + ): LoDashImplicitWrapper>; + + /** + * @see _.zip + */ + zip( + this: LoDashImplicitWrapper>, + arrays2: List, + arrays3: List, + arrays4: List, + ): LoDashImplicitWrapper>; + + /** + * @see _.zip + */ + zip( + this: LoDashImplicitWrapper>, + arrays2: List, + arrays3: List, + arrays4: List, + arrays5: List, + ): LoDashImplicitWrapper>; + + /** + * @see _.zip + */ + zip( + this: LoDashImplicitWrapper | null | undefined>, + ...arrays: Array | null | undefined> + ): LoDashImplicitWrapper>>; + } + + interface LoDashExplicitWrapper { + /** + * @see _.zip + */ + zip( + this: LoDashExplicitWrapper>, + arrays2: List, + ): LoDashExplicitWrapper>; + + /** + * @see _.zip + */ + zip( + this: LoDashExplicitWrapper>, + arrays2: List, + arrays3: List, + ): LoDashExplicitWrapper>; + + /** + * @see _.zip + */ + zip( + this: LoDashExplicitWrapper>, + arrays2: List, + arrays3: List, + arrays4: List, + ): LoDashExplicitWrapper>; + + /** + * @see _.zip + */ + zip( + this: LoDashExplicitWrapper>, + arrays2: List, + arrays3: List, + arrays4: List, + arrays5: List, + ): LoDashExplicitWrapper>; + + /** + * @see _.zip + */ + zip( + this: LoDashExplicitWrapper | null | undefined>, + ...arrays: Array | null | undefined> + ): LoDashExplicitWrapper>>; + } + + // zipObject + + interface LoDashStatic { + /** + * This method is like _.fromPairs except that it accepts two arrays, one of property + * identifiers and one of corresponding values. + * + * @param props The property names. + * @param values The property values. + * @return Returns the new object. + */ + zipObject( + props: List, + values: List + ): Dictionary; + + /** + * @see _.zipObject + */ + zipObject( + props?: List + ): Dictionary; + } + + interface LoDashImplicitWrapper { + /** + * @see _.zipObject + */ + zipObject( + this: LoDashImplicitWrapper>, + values: List + ): LoDashImplicitWrapper>; + + /** + * @see _.zipObject + */ + zipObject( + this: LoDashImplicitWrapper> + ): LoDashImplicitWrapper>; + } + + interface LoDashExplicitWrapper { + /** + * @see _.zipObject + */ + zipObject( + this: LoDashExplicitWrapper>, + values: List + ): LoDashExplicitWrapper>; + + /** + * @see _.zipObject + */ + zipObject( + this: LoDashExplicitWrapper> + ): LoDashExplicitWrapper>; + } + + // zipObjectDeep + + interface LoDashStatic { + /** + * This method is like _.zipObject except that it supports property paths. + * + * @param paths The property names. + * @param values The property values. + * @return Returns the new object. + */ + zipObjectDeep( + paths?: List, + values?: List + ): object; + } + + interface LoDashImplicitWrapper { + /** + * @see _.zipObjectDeep + */ + zipObjectDeep( + this: LoDashImplicitWrapper>, + values?: List + ): LoDashImplicitWrapper; + } + + interface LoDashExplicitWrapper { + /** + * @see _.zipObjectDeep + */ + zipObjectDeep( + this: LoDashExplicitWrapper>, + values?: List + ): LoDashExplicitWrapper; + } + + // zipWith + + interface LoDashStatic { + /** + * This method is like _.zip except that it accepts an iteratee to specify how grouped values should be + * combined. The iteratee is invoked with four arguments: (accumulator, value, index, + * group). + * @param arrays The arrays to process. + * @param iteratee The function to combine grouped values. + * @return Returns the new array of grouped elements. + */ + zipWith( + arrays: List, + iteratee: (value1: T) => TResult + ): TResult[]; + + /** + * @see _.zipWith + */ + zipWith( + arrays1: List, + arrays2: List, + iteratee: (value1: T1, value2: T2) => TResult + ): TResult[]; + + /** + * @see _.zipWith + */ + zipWith( + arrays1: List, + arrays2: List, + arrays3: List, + iteratee: (value1: T1, value2: T2, value3: T3) => TResult + ): TResult[]; + + /** + * @see _.zipWith + */ + zipWith( + arrays1: List, + arrays2: List, + arrays3: List, + arrays4: List, + iteratee: (value1: T1, value2: T2, value3: T3, value4: T4) => TResult + ): TResult[]; + + /** + * @see _.zipWith + */ + zipWith( + arrays1: List, + arrays2: List, + arrays3: List, + arrays4: List, + arrays5: List, + iteratee: (value1: T1, value2: T2, value3: T3, value4: T4, value5: T5) => TResult + ): TResult[]; + + /** + * @see _.zipWith + */ + zipWith( + ...iteratee: Array<((...group: T[]) => TResult) | List | null | undefined> + ): TResult[]; + } + + interface LoDashImplicitWrapper { + /** + * @see _.zipWith + */ + zipWith( + this: LoDashImplicitWrapper>, + iteratee: (value1: T) => TResult + ): LoDashImplicitWrapper; + + /** + * @see _.zipWith + */ + zipWith( + this: LoDashImplicitWrapper>, + arrays2: List, + iteratee: (value1: T1, value2: T2) => TResult + ): LoDashImplicitWrapper; + + /** + * @see _.zipWith + */ + zipWith( + this: LoDashImplicitWrapper>, + arrays2: List, + arrays3: List, + iteratee: (value1: T1, value2: T2, value3: T3) => TResult + ): LoDashImplicitWrapper; + + /** + * @see _.zipWith + */ + zipWith( + this: LoDashImplicitWrapper>, + arrays2: List, + arrays3: List, + arrays4: List, + iteratee: (value1: T1, value2: T2, value3: T3, value4: T4) => TResult + ): LoDashImplicitWrapper; + + /** + * @see _.zipWith + */ + zipWith( + this: LoDashImplicitWrapper>, + arrays2: List, + arrays3: List, + arrays4: List, + arrays5: List, + iteratee: (value1: T1, value2: T2, value3: T3, value4: T4, value5: T5) => TResult + ): LoDashImplicitWrapper; + + /** + * @see _.zipWith + */ + zipWith( + this: LoDashImplicitWrapper | null | undefined>, + ...iteratee: Array<((...group: T[]) => TResult) | List | null | undefined> + ): LoDashImplicitWrapper; + } + + interface LoDashExplicitWrapper { + /** + * @see _.zipWith + */ + zipWith( + this: LoDashExplicitWrapper>, + iteratee: (value1: T) => TResult + ): LoDashExplicitWrapper; + + /** + * @see _.zipWith + */ + zipWith( + this: LoDashExplicitWrapper>, + arrays2: List, + iteratee: (value1: T1, value2: T2) => TResult + ): LoDashExplicitWrapper; + + /** + * @see _.zipWith + */ + zipWith( + this: LoDashExplicitWrapper>, + arrays2: List, + arrays3: List, + iteratee: (value1: T1, value2: T2, value3: T3) => TResult + ): LoDashExplicitWrapper; + + /** + * @see _.zipWith + */ + zipWith( + this: LoDashExplicitWrapper>, + arrays2: List, + arrays3: List, + arrays4: List, + iteratee: (value1: T1, value2: T2, value3: T3, value4: T4) => TResult + ): LoDashExplicitWrapper; + + /** + * @see _.zipWith + */ + zipWith( + this: LoDashExplicitWrapper>, + arrays2: List, + arrays3: List, + arrays4: List, + arrays5: List, + iteratee: (value1: T1, value2: T2, value3: T3, value4: T4, value5: T5) => TResult + ): LoDashExplicitWrapper; + + /** + * @see _.zipWith + */ + zipWith( + this: LoDashExplicitWrapper | null | undefined>, + ...iteratee: Array<((...group: T[]) => TResult) | List | null | undefined> + ): LoDashExplicitWrapper; + } +} diff --git a/node_modules/@types/lodash/common/collection.d.ts b/node_modules/@types/lodash/common/collection.d.ts new file mode 100644 index 0000000..d8ddc97 --- /dev/null +++ b/node_modules/@types/lodash/common/collection.d.ts @@ -0,0 +1,2575 @@ +import _ = require("../index"); +declare module "../index" { + // countBy + + interface LoDashStatic { + /** + * Creates an object composed of keys generated from the results of running each element of collection through + * iteratee. The corresponding value of each key is the number of times the key was returned by iteratee. The + * iteratee is invoked with one argument: (value). + * + * @param collection The collection to iterate over. + * @param iteratee The function invoked per iteration. + * @return Returns the composed aggregate object. + */ + countBy( + collection: List | null | undefined, + iteratee?: ValueIteratee + ): Dictionary; + + /** + * @see _.countBy + */ + countBy( + collection: T | null | undefined, + iteratee?: ValueIteratee + ): Dictionary; + } + + interface LoDashImplicitWrapper { + /** + * @see _.countBy + */ + countBy( + this: LoDashImplicitWrapper | null | undefined>, + iteratee?: ValueIteratee + ): LoDashImplicitWrapper>; + + /** + * @see _.countBy + */ + countBy( + this: LoDashImplicitWrapper, + iteratee?: ValueIteratee + ): LoDashImplicitWrapper>; + } + + interface LoDashExplicitWrapper { + /** + * @see _.countBy + */ + countBy( + this: LoDashExplicitWrapper | null | undefined>, + iteratee?: ValueIteratee + ): LoDashExplicitWrapper>; + + /** + * @see _.countBy + */ + countBy( + this: LoDashExplicitWrapper, + iteratee?: ValueIteratee + ): LoDashExplicitWrapper>; + } + + // each + + interface LoDashStatic { + each: typeof _.forEach; // tslint:disable-line:no-unnecessary-qualifier + } + + interface LoDashWrapper { + /** + * @see _.forEach + */ + each( + this: LoDashWrapper, + iteratee?: ArrayIterator + ): this; + + /** + * @see _.forEach + */ + each( + this: LoDashWrapper, + iteratee?: StringIterator + ): this; + + /** + * @see _.forEach + */ + each( + this: LoDashWrapper | null | undefined>, + iteratee?: ListIterator + ): this; + + /** + * @see _.forEach + */ + each( + this: LoDashWrapper, + iteratee?: ObjectIterator + ): this; + } + + // eachRight + + interface LoDashStatic { + eachRight: typeof _.forEachRight; // tslint:disable-line:no-unnecessary-qualifier + } + + interface LoDashWrapper { + /** + * @see _.forEachRight + */ + eachRight( + this: LoDashWrapper, + iteratee?: ArrayIterator + ): this; + + /** + * @see _.forEachRight + */ + eachRight( + this: LoDashWrapper, + iteratee?: StringIterator + ): this; + + /** + * @see _.forEachRight + */ + eachRight( + this: LoDashWrapper | null | undefined>, + iteratee?: ListIterator + ): this; + + /** + * @see _.forEachRight + */ + eachRight( + this: LoDashWrapper, + iteratee?: ObjectIterator + ): this; + } + + // every + + interface LoDashStatic { + /** + * Checks if predicate returns truthy for all elements of collection. Iteration is stopped once predicate + * returns falsey. The predicate is invoked with three arguments: (value, index|key, collection). + * + * @param collection The collection to iterate over. + * @param predicate The function invoked per iteration. + * @return Returns true if all elements pass the predicate check, else false. + */ + every( + collection: List | null | undefined, + predicate?: ListIterateeCustom + ): boolean; + + /** + * @see _.every + */ + every( + collection: T | null | undefined, + predicate?: ObjectIterateeCustom + ): boolean; + } + + interface LoDashImplicitWrapper { + /** + * @see _.every + */ + every( + this: LoDashImplicitWrapper | null | undefined>, + predicate?: ListIterateeCustom + ): boolean; + + /** + * @see _.every + */ + every( + this: LoDashImplicitWrapper, + predicate?: ObjectIterateeCustom + ): boolean; + } + + interface LoDashExplicitWrapper { + /** + * @see _.every + */ + every( + this: LoDashExplicitWrapper | null | undefined>, + predicate?: ListIterateeCustom + ): LoDashExplicitWrapper; + + /** + * @see _.every + */ + every( + this: LoDashExplicitWrapper, + predicate?: ObjectIterateeCustom + ): LoDashExplicitWrapper; + } + + // filter + + interface LoDashStatic { + /** + * Iterates over elements of collection, returning an array of all elements predicate returns truthy for. The + * predicate is invoked with three arguments: (value, index|key, collection). + * + * @param collection The collection to iterate over. + * @param predicate The function invoked per iteration. + * @return Returns the new filtered array. + */ + filter( + collection: string | null | undefined, + predicate?: StringIterator + ): string[]; + + /** + * @see _.filter + */ + filter( + collection: List | null | undefined, + predicate: ListIteratorTypeGuard + ): S[]; + + /** + * @see _.filter + */ + filter( + collection: List | null | undefined, + predicate?: ListIterateeCustom + ): T[]; + + /** + * @see _.filter + */ + filter( + collection: T | null | undefined, + predicate: ObjectIteratorTypeGuard + ): S[]; + + /** + * @see _.filter + */ + filter( + collection: T | null | undefined, + predicate?: ObjectIterateeCustom + ): Array; + } + + interface LoDashImplicitWrapper { + /** + * @see _.filter + */ + filter( + this: LoDashImplicitWrapper, + predicate?: StringIterator + ): LoDashImplicitWrapper; + + /** + * @see _.filter + */ + filter( + this: LoDashImplicitWrapper | null | undefined>, + predicate: ListIteratorTypeGuard + ): LoDashImplicitWrapper; + + /** + * @see _.filter + */ + filter( + this: LoDashImplicitWrapper | null | undefined>, + predicate?: ListIterateeCustom + ): LoDashImplicitWrapper; + + /** + * @see _.filter + */ + filter( + this: LoDashImplicitWrapper, + predicate: ObjectIteratorTypeGuard + ): LoDashImplicitWrapper; + + /** + * @see _.filter + */ + filter( + this: LoDashImplicitWrapper, + predicate?: ObjectIterateeCustom + ): LoDashImplicitWrapper>; + } + + interface LoDashExplicitWrapper { + /** + * @see _.filter + */ + filter( + this: LoDashExplicitWrapper, + predicate?: StringIterator + ): LoDashExplicitWrapper; + + /** + * @see _.filter + */ + filter( + this: LoDashExplicitWrapper | null | undefined>, + predicate: ListIteratorTypeGuard + ): LoDashExplicitWrapper; + + /** + * @see _.filter + */ + filter( + this: LoDashExplicitWrapper | null | undefined>, + predicate?: ListIterateeCustom + ): LoDashExplicitWrapper; + + /** + * @see _.filter + */ + filter( + this: LoDashExplicitWrapper, + predicate: ObjectIteratorTypeGuard + ): LoDashExplicitWrapper; + + /** + * @see _.filter + */ + filter( + this: LoDashExplicitWrapper, + predicate?: ObjectIterateeCustom + ): LoDashExplicitWrapper>; + } + + // find + + interface LoDashStatic { + /** + * Iterates over elements of collection, returning the first element predicate returns truthy for. + * The predicate is invoked with three arguments: (value, index|key, collection). + * + * @param collection The collection to search. + * @param predicate The function invoked per iteration. + * @param fromIndex The index to search from. + * @return Returns the matched element, else undefined. + */ + find( + collection: List | null | undefined, + predicate: ListIteratorTypeGuard, + fromIndex?: number + ): S|undefined; + + /** + * @see _.find + */ + find( + collection: List | null | undefined, + predicate?: ListIterateeCustom, + fromIndex?: number + ): T|undefined; + + /** + * @see _.find + */ + find( + collection: T | null | undefined, + predicate: ObjectIteratorTypeGuard, + fromIndex?: number + ): S|undefined; + + /** + * @see _.find + */ + find( + collection: T | null | undefined, + predicate?: ObjectIterateeCustom, + fromIndex?: number + ): T[keyof T]|undefined; + } + + interface LoDashImplicitWrapper { + /** + * @see _.find + */ + find( + this: LoDashImplicitWrapper | null | undefined>, + predicate: ListIteratorTypeGuard, + fromIndex?: number + ): S|undefined; + + /** + * @see _.find + */ + find( + this: LoDashImplicitWrapper | null | undefined>, + predicate?: ListIterateeCustom, + fromIndex?: number + ): T|undefined; + + /** + * @see _.find + */ + find( + this: LoDashImplicitWrapper, + predicate: ObjectIteratorTypeGuard, + fromIndex?: number + ): S|undefined; + + /** + * @see _.find + */ + find( + this: LoDashImplicitWrapper, + predicate?: ObjectIterateeCustom, + fromIndex?: number + ): T[keyof T]|undefined; + } + + interface LoDashExplicitWrapper { + /** + * @see _.find + */ + find( + this: LoDashExplicitWrapper | null | undefined>, + predicate: ListIteratorTypeGuard, + fromIndex?: number + ): LoDashExplicitWrapper; + + /** + * @see _.find + */ + find( + this: LoDashExplicitWrapper | null | undefined>, + predicate?: ListIterateeCustom, + fromIndex?: number + ): LoDashExplicitWrapper; + + /** + * @see _.find + */ + find( + this: LoDashExplicitWrapper, + predicate: ObjectIteratorTypeGuard, + fromIndex?: number + ): LoDashExplicitWrapper; + + /** + * @see _.find + */ + find( + this: LoDashExplicitWrapper, + predicate?: ObjectIterateeCustom, + fromIndex?: number + ): LoDashExplicitWrapper; + } + + // findLast + + interface LoDashStatic { + /** + * This method is like _.find except that it iterates over elements of a collection from + * right to left. + * @param collection Searches for a value in this list. + * @param predicate The function called per iteration. + * @param fromIndex The index to search from. + * @return The found element, else undefined. + */ + findLast( + collection: List | null | undefined, + predicate: ListIteratorTypeGuard, + fromIndex?: number + ): S|undefined; + + /** + * @see _.findLast + */ + findLast( + collection: List | null | undefined, + predicate?: ListIterateeCustom, + fromIndex?: number + ): T|undefined; + + /** + * @see _.findLast + */ + findLast( + collection: T | null | undefined, + predicate: ObjectIteratorTypeGuard, + fromIndex?: number + ): S|undefined; + + /** + * @see _.findLast + */ + findLast( + collection: T | null | undefined, + predicate?: ObjectIterateeCustom, + fromIndex?: number + ): T[keyof T]|undefined; + } + + interface LoDashImplicitWrapper { + /** + * @see _.findLast + */ + findLast( + this: LoDashImplicitWrapper | null | undefined>, + predicate: ListIteratorTypeGuard, + fromIndex?: number + ): S | undefined; + + /** + * @see _.findLast + */ + findLast( + this: LoDashImplicitWrapper | null | undefined>, + predicate?: ListIterateeCustom, + fromIndex?: number + ): T | undefined; + + /** + * @see _.findLast + */ + findLast( + this: LoDashImplicitWrapper, + predicate: ObjectIteratorTypeGuard, + fromIndex?: number + ): S|undefined; + + /** + * @see _.findLast + */ + findLast( + this: LoDashImplicitWrapper, + predicate?: ObjectIterateeCustom, + fromIndex?: number + ): T[keyof T]|undefined; + } + + interface LoDashExplicitWrapper { + /** + * @see _.findLast + */ + findLast( + this: LoDashExplicitWrapper | null | undefined>, + predicate: ListIteratorTypeGuard, + fromIndex?: number + ): LoDashExplicitWrapper; + + /** + * @see _.findLast + */ + findLast( + this: LoDashExplicitWrapper | null | undefined>, + predicate?: ListIterateeCustom, + fromIndex?: number + ): LoDashExplicitWrapper; + + /** + * @see _.findLast + */ + findLast( + this: LoDashExplicitWrapper, + predicate: ObjectIteratorTypeGuard, + fromIndex?: number + ): LoDashExplicitWrapper; + + /** + * @see _.findLast + */ + findLast( + this: LoDashExplicitWrapper, + predicate?: ObjectIterateeCustom, + fromIndex?: number + ): LoDashExplicitWrapper; + } + + // flatMap + + interface LoDashStatic { + /** + * Creates an array of flattened values by running each element in collection through iteratee + * and concating its result to the other mapped values. The iteratee is invoked with three arguments: + * (value, index|key, collection). + * + * @param collection The collection to iterate over. + * @param iteratee The function invoked per iteration. + * @return Returns the new flattened array. + */ + flatMap( + collection: List> | Dictionary> | NumericDictionary> | null | undefined + ): T[]; + + /** + * @see _.flatMap + */ + flatMap( + collection: object | null | undefined + ): any[]; + + /** + * @see _.flatMap + */ + flatMap( + collection: List | null | undefined, + iteratee: ListIterator> + ): TResult[]; + + /** + * @see _.flatMap + */ + flatMap( + collection: T | null | undefined, + iteratee: ObjectIterator> + ): TResult[]; + + /** + * @see _.flatMap + */ + flatMap( + collection: object | null | undefined, + iteratee: string + ): any[]; + + /** + * @see _.flatMap + */ + flatMap( + collection: object | null | undefined, + iteratee: object + ): boolean[]; + } + + interface LoDashImplicitWrapper { + /** + * @see _.flatMap + */ + flatMap(this: LoDashImplicitWrapper> | Dictionary> | NumericDictionary> | null | undefined>): LoDashImplicitWrapper; + + /** + * @see _.flatMap + */ + flatMap(): LoDashImplicitWrapper; + + /** + * @see _.flatMap + */ + flatMap( + this: LoDashImplicitWrapper | null | undefined>, + iteratee: ListIterator> + ): LoDashImplicitWrapper; + + /** + * @see _.flatMap + */ + flatMap( + this: LoDashImplicitWrapper, + iteratee: ObjectIterator> + ): LoDashImplicitWrapper; + + /** + * @see _.flatMap + */ + flatMap( + iteratee: string + ): LoDashImplicitWrapper; + + /** + * @see _.flatMap + */ + flatMap( + iteratee: object + ): LoDashImplicitWrapper; + } + + interface LoDashExplicitWrapper { + /** + * @see _.flatMap + */ + flatMap(this: LoDashExplicitWrapper> | Dictionary> | NumericDictionary> | null | undefined>): LoDashExplicitWrapper; + + /** + * @see _.flatMap + */ + flatMap(): LoDashExplicitWrapper; + + /** + * @see _.flatMap + */ + flatMap( + this: LoDashExplicitWrapper | null | undefined>, + iteratee: ListIterator> + ): LoDashExplicitWrapper; + + /** + * @see _.flatMap + */ + flatMap( + this: LoDashExplicitWrapper, + iteratee: ObjectIterator> + ): LoDashExplicitWrapper; + + /** + * @see _.flatMap + */ + flatMap( + iteratee: string + ): LoDashExplicitWrapper; + + /** + * @see _.flatMap + */ + flatMap( + iteratee: object + ): LoDashExplicitWrapper; + } + + // flatMapDeep + + interface LoDashStatic { + /** + * This method is like `_.flatMap` except that it recursively flattens the + * mapped results. + * + * @since 4.7.0 + * @category Collection + * @param collection The collection to iterate over. + * @param [iteratee=_.identity] The function invoked per iteration. + * @returns Returns the new flattened array. + * @example + * + * function duplicate(n) { + * return [[[n, n]]]; + * } + * + * _.flatMapDeep([1, 2], duplicate); + * // => [1, 1, 2, 2] + */ + flatMapDeep( + collection: List | T> | Dictionary | T> | NumericDictionary | T> | null | undefined + ): T[]; + + /** + * @see _.flatMapDeep + */ + flatMapDeep( + collection: List | null | undefined, + iteratee: ListIterator | TResult> + ): TResult[]; + + /** + * @see _.flatMapDeep + */ + flatMapDeep( + collection: T | null | undefined, + iteratee: ObjectIterator | TResult> + ): TResult[]; + + /** + * @see _.flatMapDeep + */ + flatMapDeep( + collection: object | null | undefined, + iteratee: string + ): any[]; + + /** + * @see _.flatMapDeep + */ + flatMapDeep( + collection: object | null | undefined, + iteratee: object + ): boolean[]; + } + + interface LoDashImplicitWrapper { + /** + * @see _.flatMapDeep + */ + flatMapDeep( + this: LoDashImplicitWrapper | T> | Dictionary | T> | NumericDictionary | T> | null | undefined> + ): LoDashImplicitWrapper; + + /** + * @see _.flatMapDeep + */ + flatMapDeep( + this: LoDashImplicitWrapper | null | undefined>, + iteratee: ListIterator | TResult> + ): LoDashImplicitWrapper; + + /** + * @see _.flatMapDeep + */ + flatMapDeep( + this: LoDashImplicitWrapper, + iteratee: ObjectIterator | TResult> + ): LoDashImplicitWrapper; + + /** + * @see _.flatMapDeep + */ + flatMapDeep( + this: LoDashImplicitWrapper, + iteratee: string + ): LoDashImplicitWrapper; + + /** + * @see _.flatMapDeep + */ + flatMapDeep( + this: LoDashImplicitWrapper, + iteratee: object + ): LoDashImplicitWrapper; + } + + interface LoDashExplicitWrapper { + /** + * @see _.flatMapDeep + */ + flatMapDeep( + this: LoDashExplicitWrapper | T> | Dictionary | T> | NumericDictionary | T> | null | undefined> + ): LoDashExplicitWrapper; + + /** + * @see _.flatMapDeep + */ + flatMapDeep( + this: LoDashExplicitWrapper | null | undefined>, + iteratee: ListIterator | TResult> + ): LoDashExplicitWrapper; + + /** + * @see _.flatMapDeep + */ + flatMapDeep( + this: LoDashExplicitWrapper, + iteratee: ObjectIterator | TResult> + ): LoDashExplicitWrapper; + + /** + * @see _.flatMapDeep + */ + flatMapDeep( + this: LoDashExplicitWrapper, + iteratee: string + ): LoDashExplicitWrapper; + + /** + * @see _.flatMapDeep + */ + flatMapDeep( + this: LoDashExplicitWrapper, + iteratee: object + ): LoDashExplicitWrapper; + } + + // flatMapDepth + + interface LoDashStatic { + /** + * This method is like `_.flatMap` except that it recursively flattens the + * mapped results up to `depth` times. + * + * @since 4.7.0 + * @category Collection + * @param collection The collection to iterate over. + * @param [iteratee=_.identity] The function invoked per iteration. + * @param [depth=1] The maximum recursion depth. + * @returns Returns the new flattened array. + * @example + * + * function duplicate(n) { + * return [[[n, n]]]; + * } + * + * _.flatMapDepth([1, 2], duplicate, 2); + * // => [[1, 1], [2, 2]] + */ + flatMapDepth( + collection: List | T> | Dictionary | T> | NumericDictionary | T> | null | undefined + ): T[]; + + /** + * @see _.flatMapDepth + */ + flatMapDepth( + collection: List | null | undefined, + iteratee: ListIterator | TResult>, + depth?: number + ): TResult[]; + + /** + * @see _.flatMapDepth + */ + flatMapDepth( + collection: T | null | undefined, + iteratee: ObjectIterator | TResult>, + depth?: number + ): TResult[]; + + /** + * @see _.flatMapDepth + */ + flatMapDepth( + collection: object | null | undefined, + iteratee: string, + depth?: number + ): any[]; + + /** + * @see _.flatMapDepth + */ + flatMapDepth( + collection: object | null | undefined, + iteratee: object, + depth?: number + ): boolean[]; + } + + interface LoDashImplicitWrapper { + /** + * @see _.flatMapDepth + */ + flatMapDepth( + this: LoDashImplicitWrapper | T> | Dictionary | T> | NumericDictionary | T> | null | undefined> + ): LoDashImplicitWrapper; + + /** + * @see _.flatMapDepth + */ + flatMapDepth( + this: LoDashImplicitWrapper | null | undefined>, + iteratee: ListIterator | TResult>, + depth?: number + ): LoDashImplicitWrapper; + + /** + * @see _.flatMapDepth + */ + flatMapDepth( + this: LoDashImplicitWrapper, + iteratee: ObjectIterator | TResult>, + depth?: number + ): LoDashImplicitWrapper; + + /** + * @see _.flatMapDepth + */ + flatMapDepth( + this: LoDashImplicitWrapper, + iteratee: string, + depth?: number + ): LoDashImplicitWrapper; + + /** + * @see _.flatMapDepth + */ + flatMapDepth( + this: LoDashImplicitWrapper, + iteratee: object, + depth?: number + ): LoDashImplicitWrapper; + } + + interface LoDashExplicitWrapper { + /** + * @see _.flatMapDepth + */ + flatMapDepth( + this: LoDashExplicitWrapper | T> | Dictionary | T> | NumericDictionary | T> | null | undefined> + ): LoDashExplicitWrapper; + + /** + * @see _.flatMapDepth + */ + flatMapDepth( + this: LoDashExplicitWrapper | null | undefined>, + iteratee: ListIterator | TResult>, + depth?: number + ): LoDashExplicitWrapper; + + /** + * @see _.flatMapDepth + */ + flatMapDepth( + this: LoDashExplicitWrapper, + iteratee: ObjectIterator | TResult>, + depth?: number + ): LoDashExplicitWrapper; + + /** + * @see _.flatMapDepth + */ + flatMapDepth( + this: LoDashExplicitWrapper, + iteratee: string, + depth?: number + ): LoDashExplicitWrapper; + + /** + * @see _.flatMapDepth + */ + flatMapDepth( + this: LoDashExplicitWrapper, + iteratee: object, + depth?: number + ): LoDashExplicitWrapper; + } + + // forEach + + interface LoDashStatic { + /** + * Iterates over elements of collection invoking iteratee for each element. The iteratee is invoked with three arguments: + * (value, index|key, collection). Iteratee functions may exit iteration early by explicitly returning false. + * + * Note: As with other "Collections" methods, objects with a "length" property are iterated like arrays. To + * avoid this behavior _.forIn or _.forOwn may be used for object iteration. + * + * @alias _.each + * + * @param collection The collection to iterate over. + * @param iteratee The function invoked per iteration. + */ + forEach( + collection: T[], + iteratee?: ArrayIterator + ): T[]; + + /** + * @see _.forEach + */ + forEach( + collection: string, + iteratee?: StringIterator + ): string; + + /** + * @see _.forEach + */ + forEach( + collection: List, + iteratee?: ListIterator + ): List; + + /** + * @see _.forEach + */ + forEach( + collection: T, + iteratee?: ObjectIterator + ): T; + + /** + * @see _.forEach + */ + forEach( + collection: TArray & (T[] | null | undefined), + iteratee?: ArrayIterator + ): TArray; + + /** + * @see _.forEach + */ + forEach( + collection: TString, + iteratee?: StringIterator + ): TString; + + /** + * @see _.forEach + */ + forEach | null | undefined>( + collection: TList & (List | null | undefined), + iteratee?: ListIterator + ): TList; + + /** + * @see _.forEach + */ + forEach( + collection: T | null | undefined, + iteratee?: ObjectIterator + ): T | null | undefined; + } + + interface LoDashWrapper { + /** + * @see _.forEach + */ + forEach( + this: LoDashWrapper, + iteratee?: ArrayIterator + ): this; + + /** + * @see _.forEach + */ + forEach( + this: LoDashWrapper, + iteratee?: StringIterator + ): this; + + /** + * @see _.forEach + */ + forEach( + this: LoDashWrapper | null | undefined>, + iteratee?: ListIterator + ): this; + + /** + * @see _.forEach + */ + forEach( + this: LoDashWrapper, + iteratee?: ObjectIterator + ): this; + } + + // forEachRight + + interface LoDashStatic { + /** + * This method is like _.forEach except that it iterates over elements of collection from right to left. + * + * @alias _.eachRight + * + * @param collection The collection to iterate over. + * @param iteratee The function called per iteration. + */ + forEachRight( + collection: T[], + iteratee?: ArrayIterator + ): T[]; + + /** + * @see _.forEachRight + */ + forEachRight( + collection: string, + iteratee?: StringIterator + ): string; + + /** + * @see _.forEachRight + */ + forEachRight( + collection: List, + iteratee?: ListIterator + ): List; + + /** + * @see _.forEachRight + */ + forEachRight( + collection: T, + iteratee?: ObjectIterator + ): T; + + /** + * @see _.forEachRight + */ + forEachRight( + collection: TArray & (T[] | null | undefined), + iteratee?: ArrayIterator + ): TArray; + + /** + * @see _.forEachRight + */ + forEachRight( + collection: TString, + iteratee?: StringIterator + ): TString; + + /** + * @see _.forEachRight + */ + forEachRight | null | undefined>( + collection: TList & (List | null | undefined), + iteratee?: ListIterator + ): TList; + + /** + * @see _.forEachRight + */ + forEachRight( + collection: T | null | undefined, + iteratee?: ObjectIterator + ): T | null | undefined; + } + + interface LoDashWrapper { + /** + * @see _.forEachRight + */ + forEachRight( + this: LoDashWrapper, + iteratee?: ArrayIterator + ): this; + + /** + * @see _.forEachRight + */ + forEachRight( + this: LoDashWrapper, + iteratee?: StringIterator + ): this; + + /** + * @see _.forEachRight + */ + forEachRight( + this: LoDashWrapper | null | undefined>, + iteratee?: ListIterator + ): this; + + /** + * @see _.forEachRight + */ + forEachRight( + this: LoDashWrapper, + iteratee?: ObjectIterator + ): this; + } + + // groupBy + + interface LoDashStatic { + /** + * Creates an object composed of keys generated from the results of running each element of collection through + * iteratee. The corresponding value of each key is an array of the elements responsible for generating the + * key. The iteratee is invoked with one argument: (value). + * + * @param collection The collection to iterate over. + * @param iteratee The function invoked per iteration. + * @return Returns the composed aggregate object. + */ + groupBy( + collection: List | null | undefined, + iteratee?: ValueIteratee + ): Dictionary; + + /** + * @see _.groupBy + */ + groupBy( + collection: T | null | undefined, + iteratee?: ValueIteratee + ): Dictionary>; + } + + interface LoDashImplicitWrapper { + /** + * @see _.groupBy + */ + groupBy( + this: LoDashImplicitWrapper | null | undefined>, + iteratee?: ValueIteratee + ): LoDashImplicitWrapper>; + + /** + * @see _.groupBy + */ + groupBy( + this: LoDashImplicitWrapper, + iteratee?: ValueIteratee + ): LoDashImplicitWrapper>>; + } + + interface LoDashExplicitWrapper { + /** + * @see _.groupBy + */ + groupBy( + this: LoDashExplicitWrapper | null | undefined>, + iteratee?: ValueIteratee + ): LoDashExplicitWrapper>; + + /** + * @see _.groupBy + */ + groupBy( + this: LoDashExplicitWrapper, + iteratee?: ValueIteratee + ): LoDashExplicitWrapper>>; + } + + // includes + + interface LoDashStatic { + /** + * Checks if target is in collection using SameValueZero for equality comparisons. If fromIndex is negative, + * it’s used as the offset from the end of collection. + * + * @param collection The collection to search. + * @param target The value to search for. + * @param fromIndex The index to search from. + * @return True if the target element is found, else false. + */ + includes( + collection: List | Dictionary | NumericDictionary | null | undefined, + target: T, + fromIndex?: number + ): boolean; + } + + interface LoDashImplicitWrapper { + /** + * @see _.includes + */ + includes( + this: LoDashImplicitWrapper | Dictionary | NumericDictionary | null | undefined>, + target: T, + fromIndex?: number + ): boolean; + } + + interface LoDashExplicitWrapper { + /** + * @see _.includes + */ + includes( + this: LoDashExplicitWrapper | Dictionary | NumericDictionary | null | undefined>, + target: T, + fromIndex?: number + ): LoDashExplicitWrapper; + } + + // invokeMap + + interface LoDashStatic { + /** + * Invokes the method named by methodName on each element in the collection returning + * an array of the results of each invoked method. Additional arguments will be provided + * to each invoked method. If methodName is a function it will be invoked for, and this + * bound to, each element in the collection. + * @param collection The collection to iterate over. + * @param methodName The name of the method to invoke. + * @param args Arguments to invoke the method with. + **/ + invokeMap( + collection: object | null | undefined, + methodName: string, + ...args: any[]): any[]; + + /** + * @see _.invokeMap + **/ + invokeMap( + collection: object | null | undefined, + method: (...args: any[]) => TResult, + ...args: any[]): TResult[]; + } + + interface LoDashImplicitWrapper { + /** + * @see _.invokeMap + **/ + invokeMap( + methodName: string, + ...args: any[]): LoDashImplicitWrapper; + + /** + * @see _.invokeMap + **/ + invokeMap( + method: (...args: any[]) => TResult, + ...args: any[]): LoDashImplicitWrapper; + } + + interface LoDashExplicitWrapper { + /** + * @see _.invokeMap + **/ + invokeMap( + methodName: string, + ...args: any[]): LoDashExplicitWrapper; + + /** + * @see _.invokeMap + **/ + invokeMap( + method: (...args: any[]) => TResult, + ...args: any[]): LoDashExplicitWrapper; + } + + // keyBy + + interface LoDashStatic { + /** + * Creates an object composed of keys generated from the results of running each element of collection through + * iteratee. The corresponding value of each key is the last element responsible for generating the key. The + * iteratee function is invoked with one argument: (value). + * + * @param collection The collection to iterate over. + * @param iteratee The function invoked per iteration. + * @return Returns the composed aggregate object. + */ + keyBy( + collection: List | null | undefined, + iteratee?: ValueIterateeCustom + ): Dictionary; + + /** + * @see _.keyBy + */ + keyBy( + collection: T | null | undefined, + iteratee?: ValueIterateeCustom + ): Dictionary; + } + + interface LoDashImplicitWrapper { + /** + * @see _.keyBy + */ + keyBy( + this: LoDashImplicitWrapper | null | undefined>, + iteratee?: ValueIterateeCustom + ): LoDashImplicitWrapper>; + + /** + * @see _.keyBy + */ + keyBy( + this: LoDashImplicitWrapper, + iteratee?: ValueIterateeCustom + ): LoDashImplicitWrapper>; + } + + interface LoDashExplicitWrapper { + /** + * @see _.keyBy + */ + keyBy( + this: LoDashExplicitWrapper | null | undefined>, + iteratee?: ValueIterateeCustom + ): LoDashExplicitWrapper>; + + /** + * @see _.keyBy + */ + keyBy( + this: LoDashExplicitWrapper, + iteratee?: ValueIterateeCustom + ): LoDashExplicitWrapper>; + } + + // map + + interface LoDashStatic { + /** + * Creates an array of values by running each element in collection through iteratee. The iteratee is + * invoked with three arguments: (value, index|key, collection). + * + * Many lodash methods are guarded to work as iteratees for methods like _.every, _.filter, _.map, _.mapValues, + * _.reject, and _.some. + * + * The guarded methods are: + * ary, callback, chunk, clone, create, curry, curryRight, drop, dropRight, every, fill, flatten, invert, max, + * min, parseInt, slice, sortBy, take, takeRight, template, trim, trimLeft, trimRight, trunc, random, range, + * sample, some, sum, uniq, and words + * + * @param collection The collection to iterate over. + * @param iteratee The function invoked per iteration. + * @return Returns the new mapped array. + */ + map( + collection: T[] | null | undefined, + iteratee: ArrayIterator + ): TResult[]; + + /** + * @see _.map + */ + map( + collection: List | null | undefined, + iteratee: ListIterator + ): TResult[]; + + /** + * @see _.map + */ + map(collection: List | Dictionary | NumericDictionary | null | undefined): T[]; + + /** + * @see _.map + */ + map( + collection: T | null | undefined, + iteratee: ObjectIterator + ): TResult[]; + + /** @see _.map */ + map( + collection: List | Dictionary | NumericDictionary | null | undefined, + iteratee: K + ): Array; + + /** + * @see _.map + */ + map( + collection: List | Dictionary | NumericDictionary | null | undefined, + iteratee?: string + ): any[]; + + /** + * @see _.map + */ + map( + collection: List | Dictionary | NumericDictionary | null | undefined, + iteratee?: object + ): boolean[]; + } + + interface LoDashImplicitWrapper { + /** + * @see _.map + */ + map( + this: LoDashImplicitWrapper, + iteratee: ArrayIterator + ): LoDashImplicitWrapper; + + /** + * @see _.map + */ + map( + this: LoDashImplicitWrapper | null | undefined>, + iteratee: ListIterator + ): LoDashImplicitWrapper; + + /** + * @see _.map + */ + map(this: LoDashImplicitWrapper | Dictionary | NumericDictionary | null | undefined>): LoDashImplicitWrapper; + + /** + * @see _.map + */ + map( + this: LoDashImplicitWrapper, + iteratee: ObjectIterator + ): LoDashImplicitWrapper; + + /** @see _.map */ + map( + this: LoDashImplicitWrapper | Dictionary | NumericDictionary | null | undefined>, + iteratee: K + ): LoDashImplicitWrapper>; + + /** + * @see _.map + */ + map( + this: LoDashImplicitWrapper | Dictionary | NumericDictionary | null | undefined>, + iteratee?: string + ): LoDashImplicitWrapper; + + /** + * @see _.map + */ + map( + this: LoDashImplicitWrapper | Dictionary | NumericDictionary | null | undefined>, + iteratee?: object + ): LoDashImplicitWrapper; + } + + interface LoDashExplicitWrapper { + /** + * @see _.map + */ + map( + this: LoDashExplicitWrapper, + iteratee: ArrayIterator + ): LoDashExplicitWrapper; + + /** + * @see _.map + */ + map( + this: LoDashExplicitWrapper | null | undefined>, + iteratee: ListIterator + ): LoDashExplicitWrapper; + + /** + * @see _.map + */ + map(this: LoDashExplicitWrapper | Dictionary | NumericDictionary | null | undefined>): LoDashExplicitWrapper; + + /** + * @see _.map + */ + map( + this: LoDashExplicitWrapper, + iteratee: ObjectIterator + ): LoDashExplicitWrapper; + + /** @see _.map */ + map( + this: LoDashExplicitWrapper | Dictionary | NumericDictionary | null | undefined>, + iteratee: K + ): LoDashExplicitWrapper>; + + /** + * @see _.map + */ + map( + this: LoDashExplicitWrapper | Dictionary | NumericDictionary | null | undefined>, + iteratee?: string + ): LoDashExplicitWrapper; + + /** + * @see _.map + */ + map( + this: LoDashExplicitWrapper | Dictionary | NumericDictionary | null | undefined>, + iteratee?: object + ): LoDashExplicitWrapper; + } + + // orderBy + + interface LoDashStatic { + /** + * This method is like `_.sortBy` except that it allows specifying the sort + * orders of the iteratees to sort by. If `orders` is unspecified, all values + * are sorted in ascending order. Otherwise, specify an order of "desc" for + * descending or "asc" for ascending sort order of corresponding values. + * + * @category Collection + * @param collection The collection to iterate over. + * @param [iteratees=[_.identity]] The iteratees to sort by. + * @param [orders] The sort orders of `iteratees`. + * @param- {Object} [guard] Enables use as an iteratee for functions like `_.reduce`. + * @returns Returns the new sorted array. + * @example + * + * var users = [ + * { 'user': 'fred', 'age': 48 }, + * { 'user': 'barney', 'age': 34 }, + * { 'user': 'fred', 'age': 42 }, + * { 'user': 'barney', 'age': 36 } + * ]; + * + * // sort by `user` in ascending order and by `age` in descending order + * _.orderBy(users, ['user', 'age'], ['asc', 'desc']); + * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 42]] + */ + orderBy( + collection: List | null | undefined, + iteratees?: Many>, + orders?: Many + ): T[]; + + /** + * @see _.orderBy + */ + orderBy( + collection: List | null | undefined, + iteratees?: Many>, + orders?: Many + ): T[]; + + /** + * @see _.orderBy + */ + orderBy( + collection: T | null | undefined, + iteratees?: Many>, + orders?: Many + ): Array; + + /** + * @see _.orderBy + */ + orderBy( + collection: T | null | undefined, + iteratees?: Many>, + orders?: Many + ): Array; + } + + interface LoDashImplicitWrapper { + /** + * @see _.orderBy + */ + orderBy( + this: LoDashImplicitWrapper | null | undefined>, + iteratees?: Many>, + orders?: Many + ): LoDashImplicitWrapper; + + /** + * @see _.orderBy + */ + orderBy( + this: LoDashImplicitWrapper | null | undefined>, + iteratees?: Many>, + orders?: Many + ): LoDashImplicitWrapper; + + /** + * @see _.orderBy + */ + orderBy( + this: LoDashImplicitWrapper, + iteratees?: Many>, + orders?: Many + ): LoDashImplicitWrapper>; + + /** + * @see _.orderBy + */ + orderBy( + this: LoDashImplicitWrapper, + iteratees?: Many>, + orders?: Many + ): LoDashImplicitWrapper>; + } + + interface LoDashExplicitWrapper { + /** + * @see _.orderBy + */ + orderBy( + this: LoDashExplicitWrapper | null | undefined>, + iteratees?: Many>, + orders?: Many + ): LoDashExplicitWrapper; + + /** + * @see _.orderBy + */ + orderBy( + this: LoDashExplicitWrapper | null | undefined>, + iteratees?: Many>, + orders?: Many + ): LoDashExplicitWrapper; + + /** + * @see _.orderBy + */ + orderBy( + this: LoDashExplicitWrapper, + iteratees?: Many>, + orders?: Many + ): LoDashExplicitWrapper>; + + /** + * @see _.orderBy + */ + orderBy( + this: LoDashExplicitWrapper, + iteratees?: Many>, + orders?: Many + ): LoDashExplicitWrapper>; + } + + // partition + + interface LoDashStatic { + /** + * Creates an array of elements split into two groups, the first of which contains elements predicate returns truthy for, + * while the second of which contains elements predicate returns falsey for. + * The predicate is invoked with three arguments: (value, index|key, collection). + * + * @param collection The collection to iterate over. + * @param callback The function called per iteration. + * @return Returns the array of grouped elements. + **/ + partition( + collection: List | null | undefined, + callback: ValueIteratee + ): [T[], T[]]; + + /** + * @see _.partition + */ + partition( + collection: T | null | undefined, + callback: ValueIteratee + ): [Array, Array]; + } + + interface LoDashImplicitWrapper { + /** + * @see _.partition + */ + partition( + this: LoDashImplicitWrapper | null | undefined>, + callback: ValueIteratee + ): LoDashImplicitWrapper<[T[], T[]]>; + + /** + * @see _.partition + */ + partition( + this: LoDashImplicitWrapper, + callback: ValueIteratee + ): LoDashImplicitWrapper<[Array, Array]>; + } + + interface LoDashExplicitWrapper { + /** + * @see _.partition + */ + partition( + this: LoDashExplicitWrapper | null | undefined>, + callback: ValueIteratee + ): LoDashExplicitWrapper<[T[], T[]]>; + + /** + * @see _.partition + */ + partition( + this: LoDashExplicitWrapper, + callback: ValueIteratee + ): LoDashExplicitWrapper<[Array, Array]>; + } + + // reduce + + interface LoDashStatic { + /** + * Reduces a collection to a value which is the accumulated result of running each + * element in the collection through the callback, where each successive callback execution + * consumes the return value of the previous execution. If accumulator is not provided the + * first element of the collection will be used as the initial accumulator value. The callback + * is invoked with four arguments: (accumulator, value, index|key, collection). + * @param collection The collection to iterate over. + * @param callback The function called per iteration. + * @param accumulator Initial value of the accumulator. + * @return Returns the accumulated value. + **/ + reduce( + collection: T[] | null | undefined, + callback: MemoListIterator, + accumulator: TResult + ): TResult; + + /** + * @see _.reduce + **/ + reduce( + collection: List | null | undefined, + callback: MemoListIterator>, + accumulator: TResult + ): TResult; + + /** + * @see _.reduce + **/ + reduce( + collection: T | null | undefined, + callback: MemoObjectIterator, + accumulator: TResult + ): TResult; + + /** + * @see _.reduce + **/ + reduce( + collection: T[] | null | undefined, + callback: MemoListIterator + ): T | undefined; + + /** + * @see _.reduce + **/ + reduce( + collection: List | null | undefined, + callback: MemoListIterator> + ): T | undefined; + + /** + * @see _.reduce + **/ + reduce( + collection: T | null | undefined, + callback: MemoObjectIterator + ): T[keyof T] | undefined; + } + + interface LoDashImplicitWrapper { + /** + * @see _.reduce + **/ + reduce( + this: LoDashImplicitWrapper, + callback: MemoListIterator, + accumulator: TResult + ): TResult; + + /** + * @see _.reduce + **/ + reduce( + this: LoDashImplicitWrapper | null | undefined>, + callback: MemoListIterator>, + accumulator: TResult + ): TResult; + + /** + * @see _.reduce + **/ + reduce( + this: LoDashImplicitWrapper, + callback: MemoObjectIterator, + accumulator: TResult + ): TResult; + + /** + * @see _.reduce + **/ + reduce( + this: LoDashImplicitWrapper, + callback: MemoListIterator + ): T | undefined; + + /** + * @see _.reduce + **/ + reduce( + this: LoDashImplicitWrapper | null | undefined>, + callback: MemoListIterator> + ): T | undefined; + + /** + * @see _.reduce + **/ + reduce( + this: LoDashImplicitWrapper, + callback: MemoObjectIterator + ): T[keyof T] | undefined; + } + + interface LoDashExplicitWrapper { + /** + * @see _.reduce + **/ + reduce( + this: LoDashExplicitWrapper, + callback: MemoListIterator, + accumulator: TResult + ): LoDashExplicitWrapper; + + /** + * @see _.reduce + **/ + reduce( + this: LoDashExplicitWrapper | null | undefined>, + callback: MemoListIterator>, + accumulator: TResult + ): LoDashExplicitWrapper; + + /** + * @see _.reduce + **/ + reduce( + this: LoDashExplicitWrapper, + callback: MemoObjectIterator, + accumulator: TResult + ): LoDashExplicitWrapper; + + /** + * @see _.reduce + **/ + reduce( + this: LoDashExplicitWrapper, + callback: MemoListIterator + ): LoDashExplicitWrapper; + + /** + * @see _.reduce + **/ + reduce( + this: LoDashExplicitWrapper | null | undefined>, + callback: MemoListIterator> + ): LoDashExplicitWrapper; + + /** + * @see _.reduce + **/ + reduce( + this: LoDashExplicitWrapper, + callback: MemoObjectIterator + ): LoDashExplicitWrapper; + } + + // reduceRight + + interface LoDashStatic { + /** + * This method is like _.reduce except that it iterates over elements of a collection from + * right to left. + * @param collection The collection to iterate over. + * @param callback The function called per iteration. + * @param accumulator Initial value of the accumulator. + * @return The accumulated value. + **/ + reduceRight( + collection: T[] | null | undefined, + callback: MemoListIterator, + accumulator: TResult + ): TResult; + + /** + * @see _.reduceRight + **/ + reduceRight( + collection: List | null | undefined, + callback: MemoListIterator>, + accumulator: TResult + ): TResult; + + /** + * @see _.reduceRight + **/ + reduceRight( + collection: T | null | undefined, + callback: MemoObjectIterator, + accumulator: TResult + ): TResult; + + /** + * @see _.reduceRight + **/ + reduceRight( + collection: T[] | null | undefined, + callback: MemoListIterator + ): T | undefined; + + /** + * @see _.reduceRight + **/ + reduceRight( + collection: List | null | undefined, + callback: MemoListIterator> + ): T | undefined; + + /** + * @see _.reduceRight + **/ + reduceRight( + collection: T | null | undefined, + callback: MemoObjectIterator + ): T[keyof T] | undefined; + } + + interface LoDashImplicitWrapper { + /** + * @see _.reduceRight + **/ + reduceRight( + this: LoDashImplicitWrapper, + callback: MemoListIterator, + accumulator: TResult + ): TResult; + + /** + * @see _.reduceRight + **/ + reduceRight( + this: LoDashImplicitWrapper | null | undefined>, + callback: MemoListIterator>, + accumulator: TResult + ): TResult; + + /** + * @see _.reduceRight + **/ + reduceRight( + this: LoDashImplicitWrapper, + callback: MemoObjectIterator, + accumulator: TResult + ): TResult; + + /** + * @see _.reduceRight + **/ + reduceRight( + this: LoDashImplicitWrapper, + callback: MemoListIterator + ): T | undefined; + + /** + * @see _.reduceRight + **/ + reduceRight( + this: LoDashImplicitWrapper | null | undefined>, + callback: MemoListIterator> + ): T | undefined; + + /** + * @see _.reduceRight + **/ + reduceRight( + this: LoDashImplicitWrapper, + callback: MemoObjectIterator + ): T[keyof T] | undefined; + } + + interface LoDashExplicitWrapper { + /** + * @see _.reduceRight + **/ + reduceRight( + this: LoDashExplicitWrapper, + callback: MemoListIterator, + accumulator: TResult + ): LoDashExplicitWrapper; + + /** + * @see _.reduceRight + **/ + reduceRight( + this: LoDashExplicitWrapper | null | undefined>, + callback: MemoListIterator>, + accumulator: TResult + ): LoDashExplicitWrapper; + + /** + * @see _.reduceRight + **/ + reduceRight( + this: LoDashExplicitWrapper, + callback: MemoObjectIterator, + accumulator: TResult + ): LoDashExplicitWrapper; + + /** + * @see _.reduceRight + **/ + reduceRight( + this: LoDashExplicitWrapper, + callback: MemoListIterator + ): LoDashExplicitWrapper; + + /** + * @see _.reduceRight + **/ + reduceRight( + this: LoDashExplicitWrapper | null | undefined>, + callback: MemoListIterator> + ): LoDashExplicitWrapper; + + /** + * @see _.reduceRight + **/ + reduceRight( + this: LoDashExplicitWrapper, + callback: MemoObjectIterator + ): LoDashExplicitWrapper; + } + + // reject + + interface LoDashStatic { + /** + * The opposite of _.filter; this method returns the elements of collection that predicate does not return + * truthy for. + * + * @param collection The collection to iterate over. + * @param predicate The function invoked per iteration. + * @return Returns the new filtered array. + */ + reject( + collection: string | null | undefined, + predicate?: StringIterator + ): string[]; + + /** + * @see _.reject + */ + reject( + collection: List | null | undefined, + predicate?: ListIterateeCustom + ): T[]; + + /** + * @see _.reject + */ + reject( + collection: T | null | undefined, + predicate?: ObjectIterateeCustom + ): Array; + } + + interface LoDashImplicitWrapper { + /** + * @see _.reject + */ + reject( + this: LoDashImplicitWrapper, + predicate?: StringIterator + ): LoDashImplicitWrapper; + + /** + * @see _.reject + */ + reject( + this: LoDashImplicitWrapper | null | undefined>, + predicate?: ListIterateeCustom + ): LoDashImplicitWrapper; + + /** + * @see _.reject + */ + reject( + this: LoDashImplicitWrapper, + predicate?: ObjectIterateeCustom + ): LoDashImplicitWrapper>; + } + + interface LoDashExplicitWrapper { + /** + * @see _.reject + */ + reject( + this: LoDashExplicitWrapper, + predicate?: StringIterator + ): LoDashExplicitWrapper; + + /** + * @see _.reject + */ + reject( + this: LoDashExplicitWrapper | null | undefined>, + predicate?: ListIterateeCustom + ): LoDashExplicitWrapper; + + /** + * @see _.reject + */ + reject( + this: LoDashExplicitWrapper, + predicate?: ObjectIterateeCustom + ): LoDashExplicitWrapper>; + } + + // sample + + interface LoDashStatic { + /** + * Gets a random element from collection. + * + * @param collection The collection to sample. + * @return Returns the random element. + */ + sample( + collection: List | Dictionary | NumericDictionary | null | undefined + ): T | undefined; + + /** + * @see _.sample + */ + sample( + collection: T | null | undefined + ): T[keyof T] | undefined; + } + + interface LoDashImplicitWrapper { + /** + * @see _.sample + */ + sample( + this: LoDashImplicitWrapper | Dictionary | NumericDictionary | null | undefined> + ): T | undefined; + + /** + * @see _.sample + */ + sample( + this: LoDashImplicitWrapper + ): T[keyof T] | undefined; + } + + interface LoDashExplicitWrapper { + /** + * @see _.sample + */ + sample( + this: LoDashExplicitWrapper | Dictionary | NumericDictionary | null | undefined> + ): LoDashExplicitWrapper; + + /** + * @see _.sample + */ + sample( + this: LoDashExplicitWrapper + ): LoDashExplicitWrapper; + } + + // sampleSize + + interface LoDashStatic { + /** + * Gets n random elements at unique keys from collection up to the size of collection. + * + * @param collection The collection to sample. + * @param n The number of elements to sample. + * @return Returns the random elements. + */ + sampleSize( + collection: List | Dictionary | NumericDictionary | null | undefined, + n?: number + ): T[]; + + /** + * @see _.sampleSize + */ + sampleSize( + collection: T | null | undefined, + n?: number + ): Array; + } + + interface LoDashImplicitWrapper { + /** + * @see _.sampleSize + */ + sampleSize( + this: LoDashImplicitWrapper | Dictionary | NumericDictionary | null | undefined>, + n?: number + ): LoDashImplicitWrapper; + + /** + * @see _.sampleSize + */ + sampleSize( + this: LoDashImplicitWrapper, + n?: number + ): LoDashImplicitWrapper>; + } + + interface LoDashExplicitWrapper { + /** + * @see _.sampleSize + */ + sampleSize( + this: LoDashExplicitWrapper | Dictionary | NumericDictionary | null | undefined>, + n?: number + ): LoDashExplicitWrapper; + + /** + * @see _.sampleSize + */ + sampleSize( + this: LoDashExplicitWrapper, + n?: number + ): LoDashExplicitWrapper>; + } + + // shuffle + + interface LoDashStatic { + /** + * Creates an array of shuffled values, using a version of the Fisher-Yates shuffle. + * + * @param collection The collection to shuffle. + * @return Returns the new shuffled array. + */ + shuffle(collection: List | null | undefined): T[]; + + /** + * @see _.shuffle + */ + shuffle(collection: T | null | undefined): Array; + } + + interface LoDashImplicitWrapper { + /** + * @see _.shuffle + */ + shuffle(this: LoDashImplicitWrapper | null | undefined>): LoDashImplicitWrapper; + + /** + * @see _.shuffle + */ + shuffle(this: LoDashImplicitWrapper): LoDashImplicitWrapper>; + } + + interface LoDashExplicitWrapper { + /** + * @see _.shuffle + */ + shuffle(this: LoDashExplicitWrapper | null | undefined>): LoDashExplicitWrapper; + + /** + * @see _.shuffle + */ + shuffle(this: LoDashExplicitWrapper): LoDashExplicitWrapper>; + } + + // size + + interface LoDashStatic { + /** + * Gets the size of collection by returning its length for array-like values or the number of own enumerable + * properties for objects. + * + * @param collection The collection to inspect. + * @return Returns the size of collection. + */ + size(collection: object | string | null | undefined): number; + } + + interface LoDashImplicitWrapper { + /** + * @see _.size + */ + size(): number; + } + + interface LoDashExplicitWrapper { + /** + * @see _.size + */ + size(): LoDashExplicitWrapper; + } + + // some + + interface LoDashStatic { + /** + * Checks if predicate returns truthy for any element of collection. Iteration is stopped once predicate + * returns truthy. The predicate is invoked with three arguments: (value, index|key, collection). + * + * @param collection The collection to iterate over. + * @param predicate The function invoked per iteration. + * @return Returns true if any element passes the predicate check, else false. + */ + some( + collection: List | null | undefined, + predicate?: ListIterateeCustom + ): boolean; + + /** + * @see _.some + */ + some( + collection: T | null | undefined, + predicate?: ObjectIterateeCustom + ): boolean; + } + + interface LoDashImplicitWrapper { + /** + * @see _.some + */ + some( + this: LoDashImplicitWrapper | null | undefined>, + predicate?: ListIterateeCustom + ): boolean; + + /** + * @see _.some + */ + some( + this: LoDashImplicitWrapper, + predicate?: ObjectIterateeCustom + ): boolean; + } + + interface LoDashExplicitWrapper { + /** + * @see _.some + */ + some( + this: LoDashExplicitWrapper | null | undefined>, + predicate?: ListIterateeCustom + ): LoDashExplicitWrapper; + + /** + * @see _.some + */ + some( + this: LoDashExplicitWrapper, + predicate?: ObjectIterateeCustom + ): LoDashExplicitWrapper; + } + + // sortBy + + interface LoDashStatic { + /** + * Creates an array of elements, sorted in ascending order by the results of + * running each element in a collection through each iteratee. This method + * performs a stable sort, that is, it preserves the original sort order of + * equal elements. The iteratees are invoked with one argument: (value). + * + * @category Collection + * @param collection The collection to iterate over. + * @param [iteratees=[_.identity]] + * The iteratees to sort by, specified individually or in arrays. + * @returns Returns the new sorted array. + * @example + * + * var users = [ + * { 'user': 'fred', 'age': 48 }, + * { 'user': 'barney', 'age': 36 }, + * { 'user': 'fred', 'age': 42 }, + * { 'user': 'barney', 'age': 34 } + * ]; + * + * _.sortBy(users, function(o) { return o.user; }); + * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 42]] + * + * _.sortBy(users, ['user', 'age']); + * // => objects for [['barney', 34], ['barney', 36], ['fred', 42], ['fred', 48]] + * + * _.sortBy(users, 'user', function(o) { + * return Math.floor(o.age / 10); + * }); + * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 42]] + */ + sortBy( + collection: List | null | undefined, + ...iteratees: Array>> + ): T[]; + + /** + * @see _.sortBy + */ + sortBy( + collection: T | null | undefined, + ...iteratees: Array>> + ): Array; + } + + interface LoDashImplicitWrapper { + /** + * @see _.sortBy + */ + sortBy( + this: LoDashImplicitWrapper | null | undefined>, + ...iteratees: Array>> + ): LoDashImplicitWrapper; + + /** + * @see _.sortBy + */ + sortBy( + this: LoDashImplicitWrapper, + ...iteratees: Array>> + ): LoDashImplicitWrapper>; + } + + interface LoDashExplicitWrapper { + /** + * @see _.sortBy + */ + sortBy( + this: LoDashExplicitWrapper | null | undefined>, + ...iteratees: Array>> + ): LoDashExplicitWrapper; + + /** + * @see _.sortBy + */ + sortBy( + this: LoDashExplicitWrapper, + ...iteratees: Array>> + ): LoDashExplicitWrapper>; + } +} diff --git a/node_modules/@types/lodash/common/common.d.ts b/node_modules/@types/lodash/common/common.d.ts new file mode 100644 index 0000000..66dbafa --- /dev/null +++ b/node_modules/@types/lodash/common/common.d.ts @@ -0,0 +1,270 @@ +import _ = require("../index"); +// tslint:disable-next-line:strict-export-declare-modifiers +type GlobalPartial = Partial; +declare module "../index" { + type PartialObject = GlobalPartial; + type Many = T | ReadonlyArray; + interface LoDashStatic { + /** + * Creates a lodash object which wraps value to enable implicit method chain sequences. + * Methods that operate on and return arrays, collections, and functions can be chained together. + * Methods that retrieve a single value or may return a primitive value will automatically end the + * chain sequence and return the unwrapped value. Otherwise, the value must be unwrapped with value(). + * + * Explicit chain sequences, which must be unwrapped with value(), may be enabled using _.chain. + * + * The execution of chained methods is lazy, that is, it's deferred until value() is + * implicitly or explicitly called. + * + * Lazy evaluation allows several methods to support shortcut fusion. Shortcut fusion + * is an optimization to merge iteratee calls; this avoids the creation of intermediate + * arrays and can greatly reduce the number of iteratee executions. Sections of a chain + * sequence qualify for shortcut fusion if the section is applied to an array and iteratees + * accept only one argument. The heuristic for whether a section qualifies for shortcut + * fusion is subject to change. + * + * Chaining is supported in custom builds as long as the value() method is directly or + * indirectly included in the build. + * + * In addition to lodash methods, wrappers have Array and String methods. + * The wrapper Array methods are: + * concat, join, pop, push, shift, sort, splice, and unshift. + * The wrapper String methods are: + * replace and split. + * + * The wrapper methods that support shortcut fusion are: + * at, compact, drop, dropRight, dropWhile, filter, find, findLast, head, initial, last, + * map, reject, reverse, slice, tail, take, takeRight, takeRightWhile, takeWhile, and toArray + * + * The chainable wrapper methods are: + * after, ary, assign, assignIn, assignInWith, assignWith, at, before, bind, bindAll, bindKey, + * castArray, chain, chunk, commit, compact, concat, conforms, constant, countBy, create, + * curry, debounce, defaults, defaultsDeep, defer, delay, difference, differenceBy, differenceWith, + * drop, dropRight, dropRightWhile, dropWhile, extend, extendWith, fill, filter, flatMap, + * flatMapDeep, flatMapDepth, flatten, flattenDeep, flattenDepth, flip, flow, flowRight, + * fromPairs, functions, functionsIn, groupBy, initial, intersection, intersectionBy, intersectionWith, + * invert, invertBy, invokeMap, iteratee, keyBy, keys, keysIn, map, mapKeys, mapValues, + * matches, matchesProperty, memoize, merge, mergeWith, method, methodOf, mixin, negate, + * nthArg, omit, omitBy, once, orderBy, over, overArgs, overEvery, overSome, partial, partialRight, + * partition, pick, pickBy, plant, property, propertyOf, pull, pullAll, pullAllBy, pullAllWith, pullAt, + * push, range, rangeRight, rearg, reject, remove, rest, reverse, sampleSize, set, setWith, + * shuffle, slice, sort, sortBy, sortedUniq, sortedUniqBy, splice, spread, tail, take, + * takeRight, takeRightWhile, takeWhile, tap, throttle, thru, toArray, toPairs, toPairsIn, + * toPath, toPlainObject, transform, unary, union, unionBy, unionWith, uniq, uniqBy, uniqWith, + * unset, unshift, unzip, unzipWith, update, updateWith, values, valuesIn, without, wrap, + * xor, xorBy, xorWith, zip, zipObject, zipObjectDeep, and zipWith. + * + * The wrapper methods that are not chainable by default are: + * add, attempt, camelCase, capitalize, ceil, clamp, clone, cloneDeep, cloneDeepWith, cloneWith, + * conformsTo, deburr, defaultTo, divide, each, eachRight, endsWith, eq, escape, escapeRegExp, + * every, find, findIndex, findKey, findLast, findLastIndex, findLastKey, first, floor, forEach, + * forEachRight, forIn, forInRight, forOwn, forOwnRight, get, gt, gte, has, hasIn, head, + * identity, includes, indexOf, inRange, invoke, isArguments, isArray, isArrayBuffer, + * isArrayLike, isArrayLikeObject, isBoolean, isBuffer, isDate, isElement, isEmpty, isEqual, isEqualWith, + * isError, isFinite, isFunction, isInteger, isLength, isMap, isMatch, isMatchWith, isNaN, + * isNative, isNil, isNull, isNumber, isObject, isObjectLike, isPlainObject, isRegExp, + * isSafeInteger, isSet, isString, isUndefined, isTypedArray, isWeakMap, isWeakSet, join, + * kebabCase, last, lastIndexOf, lowerCase, lowerFirst, lt, lte, max, maxBy, mean, meanBy, + * min, minBy, multiply, noConflict, noop, now, nth, pad, padEnd, padStart, parseInt, pop, + * random, reduce, reduceRight, repeat, result, round, runInContext, sample, shift, size, + * snakeCase, some, sortedIndex, sortedIndexBy, sortedLastIndex, sortedLastIndexBy, startCase, + * startsWith, stubArray, stubFalse, stubObject, stubString, stubTrue, subtract, sum, sumBy, + * template, times, toFinite, toInteger, toJSON, toLength, toLower, toNumber, toSafeInteger, + * toString, toUpper, trim, trimEnd, trimStart, truncate, unescape, uniqueId, upperCase, + * upperFirst, value, and words. + **/ + (value: T): LoDashImplicitWrapper; + + /** + * The semantic version number. + **/ + VERSION: string; + + /** + * By default, the template delimiters used by Lo-Dash are similar to those in embedded Ruby + * (ERB). Change the following template settings to use alternative delimiters. + **/ + templateSettings: TemplateSettings; + } + + /** + * By default, the template delimiters used by Lo-Dash are similar to those in embedded Ruby + * (ERB). Change the following template settings to use alternative delimiters. + **/ + interface TemplateSettings { + /** + * The "escape" delimiter. + **/ + escape?: RegExp; + + /** + * The "evaluate" delimiter. + **/ + evaluate?: RegExp; + + /** + * An object to import into the template as local variables. + **/ + imports?: Dictionary; + + /** + * The "interpolate" delimiter. + **/ + interpolate?: RegExp; + + /** + * Used to reference the data object in the template text. + **/ + variable?: string; + } + + /** + * Creates a cache object to store key/value pairs. + */ + interface MapCache { + /** + * Removes `key` and its value from the cache. + * @param key The key of the value to remove. + * @return Returns `true` if the entry was removed successfully, else `false`. + */ + delete(key: any): boolean; + + /** + * Gets the cached value for `key`. + * @param key The key of the value to get. + * @return Returns the cached value. + */ + get(key: any): any; + + /** + * Checks if a cached value for `key` exists. + * @param key The key of the entry to check. + * @return Returns `true` if an entry for `key` exists, else `false`. + */ + has(key: any): boolean; + + /** + * Sets `value` to `key` of the cache. + * @param key The key of the value to cache. + * @param value The value to cache. + * @return Returns the cache object. + */ + set(key: any, value: any): this; + + /** + * Removes all key-value entries from the map. + */ + clear?: () => void; + } + interface MapCacheConstructor { + new (): MapCache; + } + + interface LoDashImplicitWrapper extends LoDashWrapper { + pop(this: LoDashImplicitWrapper | null | undefined>): T | undefined; + push(this: LoDashImplicitWrapper | null | undefined>, ...items: T[]): this; + shift(this: LoDashImplicitWrapper | null | undefined>): T | undefined; + sort(this: LoDashImplicitWrapper | null | undefined>, compareFn?: (a: T, b: T) => number): this; + splice(this: LoDashImplicitWrapper | null | undefined>, start: number, deleteCount?: number, ...items: T[]): this; + unshift(this: LoDashImplicitWrapper | null | undefined>, ...items: T[]): this; + } + + interface LoDashExplicitWrapper extends LoDashWrapper { + pop(this: LoDashExplicitWrapper | null | undefined>): LoDashExplicitWrapper; + push(this: LoDashExplicitWrapper | null | undefined>, ...items: T[]): this; + shift(this: LoDashExplicitWrapper | null | undefined>): LoDashExplicitWrapper; + sort(this: LoDashExplicitWrapper | null | undefined>, compareFn?: (a: T, b: T) => number): this; + splice(this: LoDashExplicitWrapper | null | undefined>, start: number, deleteCount?: number, ...items: T[]): this; + unshift(this: LoDashExplicitWrapper | null | undefined>, ...items: T[]): this; + } + + type NotVoid = {} | null | undefined; + type IterateeShorthand = PropertyName | [PropertyName, any] | PartialDeep; + type ArrayIterator = (value: T, index: number, collection: T[]) => TResult; + type ListIterator = (value: T, index: number, collection: List) => TResult; + type ListIteratee = ListIterator | IterateeShorthand; + type ListIterateeCustom = ListIterator | IterateeShorthand; + type ListIteratorTypeGuard = (value: T, index: number, collection: List) => value is S; + + // Note: key should be string, not keyof T, because the actual object may contain extra properties that were not specified in the type. + type ObjectIterator = (value: TObject[keyof TObject], key: string, collection: TObject) => TResult; + type ObjectIteratee = ObjectIterator | IterateeShorthand; + type ObjectIterateeCustom = ObjectIterator | IterateeShorthand; + type ObjectIteratorTypeGuard = (value: TObject[keyof TObject], key: string, collection: TObject) => value is S; + + type StringIterator = (char: string, index: number, string: string) => TResult; + + /** @deprecated Use MemoVoidArrayIterator or MemoVoidDictionaryIterator instead. */ + type MemoVoidIterator = (prev: TResult, curr: T, indexOrKey: any, list: T[]) => void; + + /** @deprecated Use MemoListIterator or MemoObjectIterator instead. */ + type MemoIterator = (prev: TResult, curr: T, indexOrKey: any, list: T[]) => TResult; + type MemoListIterator = (prev: TResult, curr: T, index: number, list: TList) => TResult; + type MemoObjectIterator = (prev: TResult, curr: T, key: string, list: TList) => TResult; + type MemoIteratorCapped = (prev: TResult, curr: T) => TResult; + type MemoIteratorCappedRight = (curr: T, prev: TResult) => TResult; + + type MemoVoidArrayIterator = (acc: TResult, curr: T, index: number, arr: T[]) => void; + type MemoVoidDictionaryIterator = (acc: TResult, curr: T, key: string, dict: Dictionary) => void; + type MemoVoidIteratorCapped = (acc: TResult, curr: T) => void; + + type ValueIteratee = ((value: T) => NotVoid) | IterateeShorthand; + type ValueIterateeCustom = ((value: T) => TResult) | IterateeShorthand; + type ValueIteratorTypeGuard = (value: T) => value is S; + type ValueKeyIteratee = ((value: T, key: string) => NotVoid) | IterateeShorthand; + type ValueKeyIterateeTypeGuard = (value: T, key: string) => value is S; + type Comparator = (a: T, b: T) => boolean; + type Comparator2 = (a: T1, b: T2) => boolean; + + type PropertyName = string | number | symbol; + type PropertyPath = Many; + + type Omit = Pick; + + /** Common interface between Arrays and jQuery objects */ + type List = ArrayLike; + + interface Dictionary { + [index: string]: T; + } + + interface NumericDictionary { + [index: number]: T; + } + + // Crazy typedef needed get _.omit to work properly with Dictionary and NumericDictionary + type AnyKindOfDictionary = + | Dictionary<{} | null | undefined> + | NumericDictionary<{} | null | undefined>; + + interface Cancelable { + cancel(): void; + flush(): void; + } + + type PartialDeep = { + [P in keyof T]?: PartialDeep; + }; + + // For backwards compatibility + type LoDashImplicitArrayWrapper = LoDashImplicitWrapper; + type LoDashImplicitNillableArrayWrapper = LoDashImplicitWrapper; + type LoDashImplicitObjectWrapper = LoDashImplicitWrapper; + type LoDashImplicitNillableObjectWrapper = LoDashImplicitWrapper; + type LoDashImplicitNumberArrayWrapper = LoDashImplicitWrapper; + type LoDashImplicitStringWrapper = LoDashImplicitWrapper; + type LoDashExplicitArrayWrapper = LoDashExplicitWrapper; + type LoDashExplicitNillableArrayWrapper = LoDashExplicitWrapper; + type LoDashExplicitObjectWrapper = LoDashExplicitWrapper; + type LoDashExplicitNillableObjectWrapper = LoDashExplicitWrapper; + type LoDashExplicitNumberArrayWrapper = LoDashExplicitWrapper; + type LoDashExplicitStringWrapper = LoDashExplicitWrapper; + + type DictionaryIterator = ObjectIterator, TResult>; + type DictionaryIteratee = ObjectIteratee>; + type DictionaryIteratorTypeGuard = ObjectIteratorTypeGuard, S>; + // NOTE: keys of objects at run time are always strings, even when a NumericDictionary is being iterated. + type NumericDictionaryIterator = (value: T, key: string, collection: NumericDictionary) => TResult; + type NumericDictionaryIteratee = NumericDictionaryIterator | IterateeShorthand; + type NumericDictionaryIterateeCustom = NumericDictionaryIterator | IterateeShorthand; +} diff --git a/node_modules/@types/lodash/common/date.d.ts b/node_modules/@types/lodash/common/date.d.ts new file mode 100644 index 0000000..79131e4 --- /dev/null +++ b/node_modules/@types/lodash/common/date.d.ts @@ -0,0 +1,27 @@ +import _ = require("../index"); +declare module "../index" { + // now + + interface LoDashStatic { + /** + * Gets the number of milliseconds that have elapsed since the Unix epoch (1 January 1970 00:00:00 UTC). + * + * @return The number of milliseconds. + */ + now(): number; + } + + interface LoDashImplicitWrapper { + /** + * @see _.now + */ + now(): number; + } + + interface LoDashExplicitWrapper { + /** + * @see _.now + */ + now(): LoDashExplicitWrapper; + } +} diff --git a/node_modules/@types/lodash/common/function.d.ts b/node_modules/@types/lodash/common/function.d.ts new file mode 100644 index 0000000..66dc75a --- /dev/null +++ b/node_modules/@types/lodash/common/function.d.ts @@ -0,0 +1,1489 @@ +import _ = require("../index"); +declare module "../index" { + // after + + interface LoDashStatic { + /** + * The opposite of _.before; this method creates a function that invokes func once it’s called n or more times. + * + * @param n The number of calls before func is invoked. + * @param func The function to restrict. + * @return Returns the new restricted function. + */ + after any>( + n: number, + func: TFunc + ): TFunc; + } + + interface LoDashImplicitWrapper { + /** + * @see _.after + **/ + after any>(func: TFunc): LoDashImplicitWrapper; + } + + interface LoDashExplicitWrapper { + /** + * @see _.after + **/ + after any>(func: TFunc): LoDashExplicitWrapper; + } + + // ary + + interface LoDashStatic { + /** + * Creates a function that accepts up to n arguments ignoring any additional arguments. + * + * @param func The function to cap arguments for. + * @param n The arity cap. + * @returns Returns the new function. + */ + ary( + func: (...args: any[]) => any, + n?: number + ): (...args: any[]) => any; + } + + interface LoDashImplicitWrapper { + /** + * @see _.ary + */ + ary(n?: number): LoDashImplicitWrapper<(...args: any[]) => any>; + } + + interface LoDashExplicitWrapper { + /** + * @see _.ary + */ + ary(n?: number): LoDashExplicitWrapper<(...args: any[]) => any>; + } + + // before + + interface LoDashStatic { + /** + * Creates a function that invokes func, with the this binding and arguments of the created function, while + * it’s called less than n times. Subsequent calls to the created function return the result of the last func + * invocation. + * + * @param n The number of calls at which func is no longer invoked. + * @param func The function to restrict. + * @return Returns the new restricted function. + */ + before any>( + n: number, + func: TFunc + ): TFunc; + } + + interface LoDashImplicitWrapper { + /** + * @see _.before + **/ + before any>(func: TFunc): LoDashImplicitWrapper; + } + + interface LoDashExplicitWrapper { + /** + * @see _.before + **/ + before any>(func: TFunc): LoDashExplicitWrapper; + } + + // bind + + interface FunctionBind { + placeholder: __; + + ( + func: (...args: any[]) => any, + thisArg: any, + ...partials: any[] + ): (...args: any[]) => any; + } + + interface LoDashStatic { + /** + * Creates a function that invokes func with the this binding of thisArg and prepends any additional _.bind + * arguments to those provided to the bound function. + * + * The _.bind.placeholder value, which defaults to _ in monolithic builds, may be used as a placeholder for + * partially applied arguments. + * + * Note: Unlike native Function#bind this method does not set the "length" property of bound functions. + * + * @param func The function to bind. + * @param thisArg The this binding of func. + * @param partials The arguments to be partially applied. + * @return Returns the new bound function. + */ + bind: FunctionBind; + } + + interface LoDashImplicitWrapper { + /** + * @see _.bind + */ + bind( + thisArg: any, + ...partials: any[] + ): LoDashImplicitWrapper<(...args: any[]) => any>; + } + + interface LoDashExplicitWrapper { + /** + * @see _.bind + */ + bind( + thisArg: any, + ...partials: any[] + ): LoDashExplicitWrapper<(...args: any[]) => any>; + } + + // bindKey + + interface FunctionBindKey { + placeholder: __; + + ( + object: object, + key: string, + ...partials: any[] + ): (...args: any[]) => any; + } + + interface LoDashStatic { + /** + * Creates a function that invokes the method at object[key] and prepends any additional _.bindKey arguments + * to those provided to the bound function. + * + * This method differs from _.bind by allowing bound functions to reference methods that may be redefined + * or don’t yet exist. See Peter Michaux’s article for more details. + * + * The _.bindKey.placeholder value, which defaults to _ in monolithic builds, may be used as a placeholder + * for partially applied arguments. + * + * @param object The object the method belongs to. + * @param key The key of the method. + * @param partials The arguments to be partially applied. + * @return Returns the new bound function. + */ + bindKey: FunctionBindKey; + } + + interface LoDashImplicitWrapper { + /** + * @see _.bindKey + */ + bindKey( + key: string, + ...partials: any[] + ): LoDashImplicitWrapper<(...args: any[]) => any>; + } + + interface LoDashExplicitWrapper { + /** + * @see _.bindKey + */ + bindKey( + key: string, + ...partials: any[] + ): LoDashExplicitWrapper<(...args: any[]) => any>; + } + + // curry + + interface Curry { + /** + * Creates a function that accepts one or more arguments of func that when called either invokes func returning + * its result, if all func arguments have been provided, or returns a function that accepts one or more of the + * remaining func arguments, and so on. The arity of func may be specified if func.length is not sufficient. + * @param func The function to curry. + * @param arity The arity of func. + * @return Returns the new curried function. + */ + (func: (t1: T1) => R, arity?: number): + CurriedFunction1; + /** + * Creates a function that accepts one or more arguments of func that when called either invokes func returning + * its result, if all func arguments have been provided, or returns a function that accepts one or more of the + * remaining func arguments, and so on. The arity of func may be specified if func.length is not sufficient. + * @param func The function to curry. + * @param arity The arity of func. + * @return Returns the new curried function. + */ + (func: (t1: T1, t2: T2) => R, arity?: number): + CurriedFunction2; + /** + * Creates a function that accepts one or more arguments of func that when called either invokes func returning + * its result, if all func arguments have been provided, or returns a function that accepts one or more of the + * remaining func arguments, and so on. The arity of func may be specified if func.length is not sufficient. + * @param func The function to curry. + * @param arity The arity of func. + * @return Returns the new curried function. + */ + (func: (t1: T1, t2: T2, t3: T3) => R, arity?: number): + CurriedFunction3; + /** + * Creates a function that accepts one or more arguments of func that when called either invokes func returning + * its result, if all func arguments have been provided, or returns a function that accepts one or more of the + * remaining func arguments, and so on. The arity of func may be specified if func.length is not sufficient. + * @param func The function to curry. + * @param arity The arity of func. + * @return Returns the new curried function. + */ + (func: (t1: T1, t2: T2, t3: T3, t4: T4) => R, arity?: number): + CurriedFunction4; + /** + * Creates a function that accepts one or more arguments of func that when called either invokes func returning + * its result, if all func arguments have been provided, or returns a function that accepts one or more of the + * remaining func arguments, and so on. The arity of func may be specified if func.length is not sufficient. + * @param func The function to curry. + * @param arity The arity of func. + * @return Returns the new curried function. + */ + (func: (t1: T1, t2: T2, t3: T3, t4: T4, t5: T5) => R, arity?: number): + CurriedFunction5; + /** + * Creates a function that accepts one or more arguments of func that when called either invokes func returning + * its result, if all func arguments have been provided, or returns a function that accepts one or more of the + * remaining func arguments, and so on. The arity of func may be specified if func.length is not sufficient. + * @param func The function to curry. + * @param arity The arity of func. + * @return Returns the new curried function. + */ + (func: (...args: any[]) => any, arity?: number): (...args: any[]) => any; + + placeholder: __; + } + + interface LoDashStatic { + curry: Curry; + } + + interface CurriedFunction1 { + (): CurriedFunction1; + (t1: T1): R; + } + + interface CurriedFunction2 { + (): CurriedFunction2; + (t1: T1): CurriedFunction1; + (t1: __, t2: T2): CurriedFunction1; + (t1: T1, t2: T2): R; + } + + interface CurriedFunction3 { + (): CurriedFunction3; + (t1: T1): CurriedFunction2; + (t1: __, t2: T2): CurriedFunction2; + (t1: T1, t2: T2): CurriedFunction1; + (t1: __, t2: __, t3: T3): CurriedFunction2; + (t1: T1, t2: __, t3: T3): CurriedFunction1; + (t1: __, t2: T2, t3: T3): CurriedFunction1; + (t1: T1, t2: T2, t3: T3): R; + } + + interface CurriedFunction4 { + (): CurriedFunction4; + (t1: T1): CurriedFunction3; + (t1: __, t2: T2): CurriedFunction3; + (t1: T1, t2: T2): CurriedFunction2; + (t1: __, t2: __, t3: T3): CurriedFunction3; + (t1: __, t2: __, t3: T3): CurriedFunction2; + (t1: __, t2: T2, t3: T3): CurriedFunction2; + (t1: T1, t2: T2, t3: T3): CurriedFunction1; + (t1: __, t2: __, t3: __, t4: T4): CurriedFunction3; + (t1: T1, t2: __, t3: __, t4: T4): CurriedFunction2; + (t1: __, t2: T2, t3: __, t4: T4): CurriedFunction2; + (t1: __, t2: __, t3: T3, t4: T4): CurriedFunction2; + (t1: T1, t2: T2, t3: __, t4: T4): CurriedFunction1; + (t1: T1, t2: __, t3: T3, t4: T4): CurriedFunction1; + (t1: __, t2: T2, t3: T3, t4: T4): CurriedFunction1; + (t1: T1, t2: T2, t3: T3, t4: T4): R; + } + + interface CurriedFunction5 { + (): CurriedFunction5; + (t1: T1): CurriedFunction4; + (t1: __, t2: T2): CurriedFunction4; + (t1: T1, t2: T2): CurriedFunction3; + (t1: __, t2: __, t3: T3): CurriedFunction4; + (t1: T1, t2: __, t3: T3): CurriedFunction3; + (t1: __, t2: T2, t3: T3): CurriedFunction3; + (t1: T1, t2: T2, t3: T3): CurriedFunction2; + (t1: __, t2: __, t3: __, t4: T4): CurriedFunction4; + (t1: T1, t2: __, t3: __, t4: T4): CurriedFunction3; + (t1: __, t2: T2, t3: __, t4: T4): CurriedFunction3; + (t1: __, t2: __, t3: T3, t4: T4): CurriedFunction3; + (t1: T1, t2: T2, t3: __, t4: T4): CurriedFunction2; + (t1: T1, t2: __, t3: T3, t4: T4): CurriedFunction2; + (t1: __, t2: T2, t3: T3, t4: T4): CurriedFunction2; + (t1: T1, t2: T2, t3: T3, t4: T4): CurriedFunction1; + (t1: __, t2: __, t3: __, t4: __, t5: T5): CurriedFunction4; + (t1: T1, t2: __, t3: __, t4: __, t5: T5): CurriedFunction3; + (t1: __, t2: T2, t3: __, t4: __, t5: T5): CurriedFunction3; + (t1: __, t2: __, t3: T3, t4: __, t5: T5): CurriedFunction3; + (t1: __, t2: __, t3: __, t4: T4, t5: T5): CurriedFunction3; + (t1: T1, t2: T2, t3: __, t4: __, t5: T5): CurriedFunction2; + (t1: T1, t2: __, t3: T3, t4: __, t5: T5): CurriedFunction2; + (t1: T1, t2: __, t3: __, t4: T4, t5: T5): CurriedFunction2; + (t1: __, t2: T2, t3: T3, t4: __, t5: T5): CurriedFunction2; + (t1: __, t2: T2, t3: __, t4: T4, t5: T5): CurriedFunction2; + (t1: __, t2: __, t3: T3, t4: T4, t5: T5): CurriedFunction2; + (t1: T1, t2: T2, t3: T3, t4: __, t5: T5): CurriedFunction1; + (t1: T1, t2: T2, t3: __, t4: T4, t5: T5): CurriedFunction1; + (t1: T1, t2: __, t3: T3, t4: T4, t5: T5): CurriedFunction1; + (t1: __, t2: T2, t3: T3, t4: T4, t5: T5): CurriedFunction1; + (t1: T1, t2: T2, t3: T3, t4: T4, t5: T5): R; + } + + interface RightCurriedFunction1 { + (): RightCurriedFunction1; + (t1: T1): R; + } + + interface RightCurriedFunction2 { + (): RightCurriedFunction2; + (t2: T2): RightCurriedFunction1; + (t1: T1, t2: __): RightCurriedFunction1; + (t1: T1, t2: T2): R; + } + + interface RightCurriedFunction3 { + (): RightCurriedFunction3; + (t3: T3): RightCurriedFunction2; + (t2: T2, t3: __): RightCurriedFunction2; + (t2: T2, t3: T3): RightCurriedFunction1; + (t1: T1, t2: __, t3: __): RightCurriedFunction2; + (t1: T1, t2: T2, t3: __): RightCurriedFunction1; + (t1: T1, t2: __, t3: T3): RightCurriedFunction1; + (t1: T1, t2: T2, t3: T3): R; + } + + interface RightCurriedFunction4 { + (): RightCurriedFunction4; + (t4: T4): RightCurriedFunction3; + (t3: T3, t4: __): RightCurriedFunction3; + (t3: T3, t4: T4): RightCurriedFunction2; + (t2: T2, t3: __, t4: __): RightCurriedFunction3; + (t2: T2, t3: T3, t4: __): RightCurriedFunction2; + (t2: T2, t3: __, t4: T4): RightCurriedFunction2; + (t2: T2, t3: T3, t4: T4): RightCurriedFunction1; + (t1: T1, t2: __, t3: __, t4: __): RightCurriedFunction3; + (t1: T1, t2: T2, t3: __, t4: __): RightCurriedFunction2; + (t1: T1, t2: __, t3: T3, t4: __): RightCurriedFunction2; + (t1: T1, t2: __, t3: __, t4: T4): RightCurriedFunction2; + (t1: T1, t2: T2, t3: T3, t4: __): RightCurriedFunction1; + (t1: T1, t2: T2, t3: __, t4: T4): RightCurriedFunction1; + (t1: T1, t2: __, t3: T3, t4: T4): RightCurriedFunction1; + (t1: T1, t2: T2, t3: T3, t4: T4): R; + } + + interface RightCurriedFunction5 { + (): RightCurriedFunction5; + (t5: T5): RightCurriedFunction4; + (t4: T4, t5: __): RightCurriedFunction4; + (t4: T4, t5: T5): RightCurriedFunction3; + (t3: T3, t4: __, t5: __): RightCurriedFunction4; + (t3: T3, t4: T4, t5: __): RightCurriedFunction3; + (t3: T3, t4: __, t5: T5): RightCurriedFunction3; + (t3: T3, t4: T4, t5: T5): RightCurriedFunction2; + (t2: T2, t3: __, t4: __, t5: __): RightCurriedFunction4; + (t2: T2, t3: T3, t4: __, t5: __): RightCurriedFunction3; + (t2: T2, t3: __, t4: T4, t5: __): RightCurriedFunction3; + (t2: T2, t3: __, t4: __, t5: T5): RightCurriedFunction3; + (t2: T2, t3: T3, t4: T4, t5: __): RightCurriedFunction2; + (t2: T2, t3: T3, t4: __, t5: T5): RightCurriedFunction2; + (t2: T2, t3: __, t4: T4, t5: T5): RightCurriedFunction2; + (t2: T2, t3: T3, t4: T4, t5: T5): RightCurriedFunction1; + (t1: T1, t2: __, t3: __, t4: __, t5: __): RightCurriedFunction4; + (t1: T1, t2: T2, t3: __, t4: __, t5: __): RightCurriedFunction3; + (t1: T1, t2: __, t3: T3, t4: __, t5: __): RightCurriedFunction3; + (t1: T1, t2: __, t3: __, t4: T4, t5: __): RightCurriedFunction3; + (t1: T1, t2: __, t3: __, t4: __, t5: T5): RightCurriedFunction3; + (t1: T1, t2: T2, t3: T3, t4: __, t5: __): RightCurriedFunction2; + (t1: T1, t2: T2, t3: __, t4: T4, t5: __): RightCurriedFunction2; + (t1: T1, t2: T2, t3: __, t4: __, t5: T5): RightCurriedFunction2; + (t1: T1, t2: __, t3: T3, t4: T4, t5: __): RightCurriedFunction2; + (t1: T1, t2: __, t3: T3, t4: __, t5: T5): RightCurriedFunction2; + (t1: T1, t2: __, t3: __, t4: T4, t5: T5): RightCurriedFunction2; + (t1: T1, t2: T2, t3: T3, t4: T4, t5: __): RightCurriedFunction1; + (t1: T1, t2: T2, t3: T3, t4: __, t5: T5): RightCurriedFunction1; + (t1: T1, t2: T2, t3: __, t4: T4, t5: T5): RightCurriedFunction1; + (t1: T1, t2: __, t3: T3, t4: T4, t5: T5): RightCurriedFunction1; + (t1: T1, t2: T2, t3: T3, t4: T4, t5: T5): R; + } + + interface LoDashImplicitWrapper { + /** + * @see _.curry + **/ + curry(this: LoDashImplicitWrapper<(t1: T1) => R>, arity?: number): + LoDashImplicitWrapper>; + + /** + * @see _.curry + **/ + curry(this: LoDashImplicitWrapper<(t1: T1, t2: T2) => R>, arity?: number): + LoDashImplicitWrapper>; + + /** + * @see _.curry + **/ + curry(this: LoDashImplicitWrapper<(t1: T1, t2: T2, t3: T3) => R>, arity?: number): + LoDashImplicitWrapper>; + + /** + * @see _.curry + **/ + curry(this: LoDashImplicitWrapper<(t1: T1, t2: T2, t3: T3, t4: T4) => R>, arity?: number): + LoDashImplicitWrapper>; + + /** + * @see _.curry + **/ + curry(this: LoDashImplicitWrapper<(t1: T1, t2: T2, t3: T3, t4: T4, t5: T5) => R>, arity?: number): + LoDashImplicitWrapper>; + + /** + * @see _.curry + **/ + curry(arity?: number): LoDashImplicitWrapper<(...args: any[]) => any>; + } + + interface LoDashExplicitWrapper { + /** + * @see _.curry + **/ + curry(this: LoDashExplicitWrapper<(t1: T1) => R>): + LoDashExplicitWrapper>; + + /** + * @see _.curry + **/ + curry(this: LoDashExplicitWrapper<(t1: T1, t2: T2) => R>): + LoDashExplicitWrapper>; + + /** + * @see _.curry + **/ + curry(this: LoDashExplicitWrapper<(t1: T1, t2: T2, t3: T3) => R>): + LoDashExplicitWrapper>; + + /** + * @see _.curry + **/ + curry(this: LoDashExplicitWrapper<(t1: T1, t2: T2, t3: T3, t4: T4) => R>): + LoDashExplicitWrapper>; + + /** + * @see _.curry + **/ + curry(this: LoDashExplicitWrapper<(t1: T1, t2: T2, t3: T3, t4: T4, t5: T5) => R>): + LoDashExplicitWrapper>; + + /** + * @see _.curry + **/ + curry(arity?: number): LoDashExplicitWrapper<(...args: any[]) => any>; + } + + // curryRight + + interface CurryRight { + /** + * This method is like _.curry except that arguments are applied to func in the manner of _.partialRight + * instead of _.partial. + * @param func The function to curry. + * @param arity The arity of func. + * @return Returns the new curried function. + */ + (func: (t1: T1) => R, arity?: number): + RightCurriedFunction1; + /** + * This method is like _.curry except that arguments are applied to func in the manner of _.partialRight + * instead of _.partial. + * @param func The function to curry. + * @param arity The arity of func. + * @return Returns the new curried function. + */ + (func: (t1: T1, t2: T2) => R, arity?: number): + RightCurriedFunction2; + /** + * This method is like _.curry except that arguments are applied to func in the manner of _.partialRight + * instead of _.partial. + * @param func The function to curry. + * @param arity The arity of func. + * @return Returns the new curried function. + */ + (func: (t1: T1, t2: T2, t3: T3) => R, arity?: number): + RightCurriedFunction3; + /** + * This method is like _.curry except that arguments are applied to func in the manner of _.partialRight + * instead of _.partial. + * @param func The function to curry. + * @param arity The arity of func. + * @return Returns the new curried function. + */ + (func: (t1: T1, t2: T2, t3: T3, t4: T4) => R, arity?: number): + RightCurriedFunction4; + /** + * This method is like _.curry except that arguments are applied to func in the manner of _.partialRight + * instead of _.partial. + * @param func The function to curry. + * @param arity The arity of func. + * @return Returns the new curried function. + */ + (func: (t1: T1, t2: T2, t3: T3, t4: T4, t5: T5) => R, arity?: number): + RightCurriedFunction5; + /** + * This method is like _.curry except that arguments are applied to func in the manner of _.partialRight + * instead of _.partial. + * @param func The function to curry. + * @param arity The arity of func. + * @return Returns the new curried function. + */ + (func: (...args: any[]) => any, arity?: number): (...args: any[]) => any; + + placeholder: __; + } + + interface LoDashStatic { + curryRight: CurryRight; + } + + interface LoDashImplicitWrapper { + /** + * @see _.curryRight + **/ + curryRight(this: LoDashImplicitWrapper<(t1: T1) => R>, arity?: number): + LoDashImplicitWrapper>; + + /** + * @see _.curryRight + **/ + curryRight(this: LoDashImplicitWrapper<(t1: T1, t2: T2) => R>, arity?: number): + LoDashImplicitWrapper>; + + /** + * @see _.curryRight + **/ + curryRight(this: LoDashImplicitWrapper<(t1: T1, t2: T2, t3: T3) => R>, arity?: number): + LoDashImplicitWrapper>; + + /** + * @see _.curryRight + **/ + curryRight(this: LoDashImplicitWrapper<(t1: T1, t2: T2, t3: T3, t4: T4) => R>, arity?: number): + LoDashImplicitWrapper>; + + /** + * @see _.curryRight + **/ + curryRight(this: LoDashImplicitWrapper<(t1: T1, t2: T2, t3: T3, t4: T4, t5: T5) => R>, arity?: number): + LoDashImplicitWrapper>; + + /** + * @see _.curryRight + **/ + curryRight(arity?: number): LoDashImplicitWrapper<(...args: any[]) => any>; + } + + interface LoDashExplicitWrapper { + /** + * @see _.curryRight + **/ + curryRight(this: LoDashExplicitWrapper<(t1: T1) => R>, arity?: number): + LoDashExplicitWrapper>; + + /** + * @see _.curryRight + **/ + curryRight(this: LoDashExplicitWrapper<(t1: T1, t2: T2) => R>, arity?: number): + LoDashExplicitWrapper>; + + /** + * @see _.curryRight + **/ + curryRight(this: LoDashExplicitWrapper<(t1: T1, t2: T2, t3: T3) => R>, arity?: number): + LoDashExplicitWrapper>; + + /** + * @see _.curryRight + **/ + curryRight(this: LoDashExplicitWrapper<(t1: T1, t2: T2, t3: T3, t4: T4) => R>, arity?: number): + LoDashExplicitWrapper>; + + /** + * @see _.curryRight + **/ + curryRight(this: LoDashExplicitWrapper<(t1: T1, t2: T2, t3: T3, t4: T4, t5: T5) => R>, arity?: number): + LoDashExplicitWrapper>; + + /** + * @see _.curryRight + **/ + curryRight(arity?: number): LoDashExplicitWrapper<(...args: any[]) => any>; + } + + // debounce + + interface DebounceSettings { + /** + * Specify invoking on the leading edge of the timeout. + */ + leading?: boolean; + + /** + * The maximum time func is allowed to be delayed before it’s invoked. + */ + maxWait?: number; + + /** + * Specify invoking on the trailing edge of the timeout. + */ + trailing?: boolean; + } + + interface LoDashStatic { + /** + * Creates a debounced function that delays invoking func until after wait milliseconds have elapsed since + * the last time the debounced function was invoked. The debounced function comes with a cancel method to + * cancel delayed invocations and a flush method to immediately invoke them. Provide an options object to + * indicate that func should be invoked on the leading and/or trailing edge of the wait timeout. Subsequent + * calls to the debounced function return the result of the last func invocation. + * + * Note: If leading and trailing options are true, func is invoked on the trailing edge of the timeout only + * if the the debounced function is invoked more than once during the wait timeout. + * + * See David Corbacho’s article for details over the differences between _.debounce and _.throttle. + * + * @param func The function to debounce. + * @param wait The number of milliseconds to delay. + * @param options The options object. + * @param options.leading Specify invoking on the leading edge of the timeout. + * @param options.maxWait The maximum time func is allowed to be delayed before it’s invoked. + * @param options.trailing Specify invoking on the trailing edge of the timeout. + * @return Returns the new debounced function. + */ + debounce any>( + func: T, + wait?: number, + options?: DebounceSettings + ): T & Cancelable; + } + + interface LoDashImplicitWrapper { + /** + * @see _.debounce + */ + debounce( + wait?: number, + options?: DebounceSettings + ): LoDashImplicitWrapper; + } + + interface LoDashExplicitWrapper { + /** + * @see _.debounce + */ + debounce( + wait?: number, + options?: DebounceSettings + ): LoDashExplicitWrapper; + } + + // defer + + interface LoDashStatic { + /** + * Defers invoking the func until the current call stack has cleared. Any additional arguments are provided to + * func when it’s invoked. + * + * @param func The function to defer. + * @param args The arguments to invoke the function with. + * @return Returns the timer id. + */ + defer( + func: (...args: any[]) => any, + ...args: any[] + ): number; + } + + interface LoDashImplicitWrapper { + /** + * @see _.defer + */ + defer(...args: any[]): LoDashImplicitWrapper; + } + + interface LoDashExplicitWrapper { + /** + * @see _.defer + */ + defer(...args: any[]): LoDashExplicitWrapper; + } + + // delay + + interface LoDashStatic { + /** + * Invokes func after wait milliseconds. Any additional arguments are provided to func when it’s invoked. + * + * @param func The function to delay. + * @param wait The number of milliseconds to delay invocation. + * @param args The arguments to invoke the function with. + * @return Returns the timer id. + */ + delay( + func: (...args: any[]) => any, + wait: number, + ...args: any[] + ): number; + } + + interface LoDashImplicitWrapper { + /** + * @see _.delay + */ + delay( + wait: number, + ...args: any[] + ): LoDashImplicitWrapper; + } + + interface LoDashExplicitWrapper { + /** + * @see _.delay + */ + delay( + wait: number, + ...args: any[] + ): LoDashExplicitWrapper; + } + + // flip + + interface LoDashStatic { + /** + * Creates a function that invokes `func` with arguments reversed. + * + * @category Function + * @param func The function to flip arguments for. + * @returns Returns the new function. + * @example + * + * var flipped = _.flip(function() { + * return _.toArray(arguments); + * }); + * + * flipped('a', 'b', 'c', 'd'); + * // => ['d', 'c', 'b', 'a'] + */ + flip any>(func: T): T; + } + + interface LoDashWrapper { + /** + * @see _.flip + */ + flip(): this; + } + + // memoize + + interface MemoizedFunction { + cache: MapCache; + } + + interface LoDashStatic { + /** + * Creates a function that memoizes the result of func. If resolver is provided it determines the cache key for + * storing the result based on the arguments provided to the memoized function. By default, the first argument + * provided to the memoized function is coerced to a string and used as the cache key. The func is invoked with + * the this binding of the memoized function. + * + * @param func The function to have its output memoized. + * @param resolver The function to resolve the cache key. + * @return Returns the new memoizing function. + */ + memoize: { + any>(func: T, resolver?: (...args: any[]) => any): T & MemoizedFunction; + Cache: MapCacheConstructor; + }; + } + + interface LoDashImplicitWrapper { + /** + * @see _.memoize + */ + memoize(resolver?: (...args: any[]) => any): LoDashImplicitWrapper; + } + + interface LoDashExplicitWrapper { + /** + * @see _.memoize + */ + memoize(resolver?: (...args: any[]) => any): LoDashExplicitWrapper; + } + + // negate + + interface LoDashStatic { + /** + * Creates a function that negates the result of the predicate func. The func predicate is invoked with + * the this binding and arguments of the created function. + * + * @param predicate The predicate to negate. + * @return Returns the new function. + */ + negate(predicate: () => boolean): () => boolean; + negate(predicate: (a1: A1) => boolean): (a1: A1) => boolean; + negate(predicate: (a1: A1, a2: A2) => boolean): (a1: A1, a2: A2) => boolean; + negate(predicate: (...args: any[]) => any): (...args: any[]) => boolean; + } + + interface LoDashImplicitWrapper { + /** + * @see _.negate + */ + negate(this: LoDashImplicitWrapper<() => boolean>): LoDashImplicitWrapper<() => boolean>; + negate(this: LoDashImplicitWrapper<(a1: A1) => boolean>): LoDashImplicitWrapper<(a1: A1) => boolean>; + negate(this: LoDashImplicitWrapper<(a1: A1, a2: A2) => boolean>): LoDashImplicitWrapper<(a1: A1, a2: A2) => boolean>; + negate(this: LoDashImplicitWrapper<(...args: any[]) => any>): LoDashImplicitWrapper<(...args: any[]) => boolean>; + } + + interface LoDashExplicitWrapper { + /** + * @see _.negate + */ + negate(this: LoDashExplicitWrapper<() => boolean>): LoDashExplicitWrapper<() => boolean>; + negate(this: LoDashExplicitWrapper<(a1: A1) => boolean>): LoDashExplicitWrapper<(a1: A1) => boolean>; + negate(this: LoDashExplicitWrapper<(a1: A1, a2: A2) => boolean>): LoDashExplicitWrapper<(a1: A1, a2: A2) => boolean>; + negate(this: LoDashExplicitWrapper<(...args: any[]) => any>): LoDashExplicitWrapper<(...args: any[]) => boolean>; + } + + // once + + interface LoDashStatic { + /** + * Creates a function that is restricted to invoking func once. Repeat calls to the function return the value + * of the first call. The func is invoked with the this binding and arguments of the created function. + * + * @param func The function to restrict. + * @return Returns the new restricted function. + */ + once any>(func: T): T; + } + + interface LoDashWrapper { + /** + * @see _.once + */ + once(): this; + } + + // overArgs + + interface LoDashStatic { + /** + * Creates a function that runs each argument through a corresponding transform function. + * + * @param func The function to wrap. + * @param transforms The functions to transform arguments, specified as individual functions or arrays + * of functions. + * @return Returns the new function. + */ + overArgs( + func: (...args: any[]) => any, + ...transforms: Array any>> + ): (...args: any[]) => any; + } + + interface LoDashImplicitWrapper { + /** + * @see _.overArgs + */ + overArgs(...transforms: Array any>>): LoDashImplicitWrapper<(...args: any[]) => any>; + } + + interface LoDashExplicitWrapper { + /** + * @see _.overArgs + */ + overArgs(...transforms: Array any>>): LoDashExplicitWrapper<(...args: any[]) => any>; + } + + // partial + + interface LoDashStatic { + /** + * Creates a function that, when called, invokes func with any additional partial arguments + * prepended to those provided to the new function. This method is similar to _.bind except + * it does not alter the this binding. + * @param func The function to partially apply arguments to. + * @param args Arguments to be partially applied. + * @return The new partially applied function. + **/ + partial: Partial; + } + + interface LoDashImplicitWrapper { + /** + * @see _.partial + */ + partial: ImplicitPartial; + } + + interface LoDashExplicitWrapper { + /** + * @see _.partial + */ + partial: ExplicitPartial; + } + + /** The placeholder, to be used in curried functions */ + type __ = LoDashStatic; + + type Function0 = () => R; + type Function1 = (t1: T1) => R; + type Function2 = (t1: T1, t2: T2) => R; + type Function3 = (t1: T1, t2: T2, t3: T3) => R; + type Function4 = (t1: T1, t2: T2, t3: T3, t4: T4) => R; + + interface Partial { + // arity 0 + (func: Function0): Function0; + // arity 1 + (func: Function1): Function1; + (func: Function1, arg1: T1): Function0; + // arity 2 + (func: Function2): Function2; + (func: Function2, arg1: T1): Function1< T2, R>; + (func: Function2, plc1: __, arg2: T2): Function1; + (func: Function2, arg1: T1, arg2: T2): Function0< R>; + // arity 3 + (func: Function3): Function3; + (func: Function3, arg1: T1): Function2< T2, T3, R>; + (func: Function3, plc1: __, arg2: T2): Function2; + (func: Function3, arg1: T1, arg2: T2): Function1< T3, R>; + (func: Function3, plc1: __, plc2: __, arg3: T3): Function2; + (func: Function3, arg1: T1, plc2: __, arg3: T3): Function1< T2, R>; + (func: Function3, plc1: __, arg2: T2, arg3: T3): Function1; + (func: Function3, arg1: T1, arg2: T2, arg3: T3): Function0< R>; + // arity 4 + (func: Function4): Function4; + (func: Function4, arg1: T1): Function3< T2, T3, T4, R>; + (func: Function4, plc1: __, arg2: T2): Function3; + (func: Function4, arg1: T1, arg2: T2): Function2< T3, T4, R>; + (func: Function4, plc1: __, plc2: __, arg3: T3): Function3; + (func: Function4, arg1: T1, plc2: __, arg3: T3): Function2< T2, T4, R>; + (func: Function4, plc1: __, arg2: T2, arg3: T3): Function2; + (func: Function4, arg1: T1, arg2: T2, arg3: T3): Function1< T4, R>; + (func: Function4, plc1: __, plc2: __, plc3: __, arg4: T4): Function3; + (func: Function4, arg1: T1, plc2: __, plc3: __, arg4: T4): Function2< T2, T3, R>; + (func: Function4, plc1: __, arg2: T2, plc3: __, arg4: T4): Function2; + (func: Function4, arg1: T1, arg2: T2, plc3: __, arg4: T4): Function1< T3, R>; + (func: Function4, plc1: __, plc2: __, arg3: T3, arg4: T4): Function2; + (func: Function4, arg1: T1, plc2: __, arg3: T3, arg4: T4): Function1< T2, R>; + (func: Function4, plc1: __, arg2: T2, arg3: T3, arg4: T4): Function1; + (func: Function4, arg1: T1, arg2: T2, arg3: T3, arg4: T4): Function0< R>; + // catch-all + (func: (...args: any[]) => any, ...args: any[]): (...args: any[]) => any; + + placeholder: __; + } + + interface ImplicitPartial { + // arity 0 + (this: LoDashImplicitWrapper>): LoDashImplicitWrapper>; + // arity 1 + (this: LoDashImplicitWrapper>): LoDashImplicitWrapper>; + (this: LoDashImplicitWrapper>, arg1: T1): LoDashImplicitWrapper>; + // arity 2 + (this: LoDashImplicitWrapper>): LoDashImplicitWrapper>; + (this: LoDashImplicitWrapper>, arg1: T1): LoDashImplicitWrapper>; + (this: LoDashImplicitWrapper>, plc1: __, arg2: T2): LoDashImplicitWrapper>; + (this: LoDashImplicitWrapper>, arg1: T1, arg2: T2): LoDashImplicitWrapper>; + // arity 3 + (this: LoDashImplicitWrapper>): LoDashImplicitWrapper>; + (this: LoDashImplicitWrapper>, arg1: T1): LoDashImplicitWrapper>; + (this: LoDashImplicitWrapper>, plc1: __, arg2: T2): LoDashImplicitWrapper>; + (this: LoDashImplicitWrapper>, arg1: T1, arg2: T2): LoDashImplicitWrapper>; + (this: LoDashImplicitWrapper>, plc1: __, plc2: __, arg3: T3): LoDashImplicitWrapper>; + (this: LoDashImplicitWrapper>, arg1: T1, plc2: __, arg3: T3): LoDashImplicitWrapper>; + (this: LoDashImplicitWrapper>, plc1: __, arg2: T2, arg3: T3): LoDashImplicitWrapper>; + (this: LoDashImplicitWrapper>, arg1: T1, arg2: T2, arg3: T3): LoDashImplicitWrapper>; + // arity 4 + (this: LoDashImplicitWrapper>): LoDashImplicitWrapper>; + (this: LoDashImplicitWrapper>, arg1: T1): LoDashImplicitWrapper>; + (this: LoDashImplicitWrapper>, plc1: __, arg2: T2): LoDashImplicitWrapper>; + (this: LoDashImplicitWrapper>, arg1: T1, arg2: T2): LoDashImplicitWrapper>; + (this: LoDashImplicitWrapper>, plc1: __, plc2: __, arg3: T3): LoDashImplicitWrapper>; + (this: LoDashImplicitWrapper>, arg1: T1, plc2: __, arg3: T3): LoDashImplicitWrapper>; + (this: LoDashImplicitWrapper>, plc1: __, arg2: T2, arg3: T3): LoDashImplicitWrapper>; + (this: LoDashImplicitWrapper>, arg1: T1, arg2: T2, arg3: T3): LoDashImplicitWrapper>; + (this: LoDashImplicitWrapper>, plc1: __, plc2: __, plc3: __, arg4: T4): LoDashImplicitWrapper>; + (this: LoDashImplicitWrapper>, arg1: T1, plc2: __, plc3: __, arg4: T4): LoDashImplicitWrapper>; + (this: LoDashImplicitWrapper>, plc1: __, arg2: T2, plc3: __, arg4: T4): LoDashImplicitWrapper>; + (this: LoDashImplicitWrapper>, arg1: T1, arg2: T2, plc3: __, arg4: T4): LoDashImplicitWrapper>; + (this: LoDashImplicitWrapper>, plc1: __, plc2: __, arg3: T3, arg4: T4): LoDashImplicitWrapper>; + (this: LoDashImplicitWrapper>, arg1: T1, plc2: __, arg3: T3, arg4: T4): LoDashImplicitWrapper>; + (this: LoDashImplicitWrapper>, plc1: __, arg2: T2, arg3: T3, arg4: T4): LoDashImplicitWrapper>; + (this: LoDashImplicitWrapper>, arg1: T1, arg2: T2, arg3: T3, arg4: T4): LoDashImplicitWrapper>; + // catch-all + (...args: any[]): LoDashImplicitWrapper<(...args: any[]) => any>; + } + + interface ExplicitPartial { + // arity 0 + (this: LoDashExplicitWrapper>): LoDashExplicitWrapper>; + // arity 1 + (this: LoDashExplicitWrapper>): LoDashExplicitWrapper>; + (this: LoDashExplicitWrapper>, arg1: T1): LoDashExplicitWrapper>; + // arity 2 + (this: LoDashExplicitWrapper>): LoDashExplicitWrapper>; + (this: LoDashExplicitWrapper>, arg1: T1): LoDashExplicitWrapper>; + (this: LoDashExplicitWrapper>, plc1: __, arg2: T2): LoDashExplicitWrapper>; + (this: LoDashExplicitWrapper>, arg1: T1, arg2: T2): LoDashExplicitWrapper>; + // arity 3 + (this: LoDashExplicitWrapper>): LoDashExplicitWrapper>; + (this: LoDashExplicitWrapper>, arg1: T1): LoDashExplicitWrapper>; + (this: LoDashExplicitWrapper>, plc1: __, arg2: T2): LoDashExplicitWrapper>; + (this: LoDashExplicitWrapper>, arg1: T1, arg2: T2): LoDashExplicitWrapper>; + (this: LoDashExplicitWrapper>, plc1: __, plc2: __, arg3: T3): LoDashExplicitWrapper>; + (this: LoDashExplicitWrapper>, arg1: T1, plc2: __, arg3: T3): LoDashExplicitWrapper>; + (this: LoDashExplicitWrapper>, plc1: __, arg2: T2, arg3: T3): LoDashExplicitWrapper>; + (this: LoDashExplicitWrapper>, arg1: T1, arg2: T2, arg3: T3): LoDashExplicitWrapper>; + // arity 4 + (this: LoDashExplicitWrapper>): LoDashExplicitWrapper>; + (this: LoDashExplicitWrapper>, arg1: T1): LoDashExplicitWrapper>; + (this: LoDashExplicitWrapper>, plc1: __, arg2: T2): LoDashExplicitWrapper>; + (this: LoDashExplicitWrapper>, arg1: T1, arg2: T2): LoDashExplicitWrapper>; + (this: LoDashExplicitWrapper>, plc1: __, plc2: __, arg3: T3): LoDashExplicitWrapper>; + (this: LoDashExplicitWrapper>, arg1: T1, plc2: __, arg3: T3): LoDashExplicitWrapper>; + (this: LoDashExplicitWrapper>, plc1: __, arg2: T2, arg3: T3): LoDashExplicitWrapper>; + (this: LoDashExplicitWrapper>, arg1: T1, arg2: T2, arg3: T3): LoDashExplicitWrapper>; + (this: LoDashExplicitWrapper>, plc1: __, plc2: __, plc3: __, arg4: T4): LoDashExplicitWrapper>; + (this: LoDashExplicitWrapper>, arg1: T1, plc2: __, plc3: __, arg4: T4): LoDashExplicitWrapper>; + (this: LoDashExplicitWrapper>, plc1: __, arg2: T2, plc3: __, arg4: T4): LoDashExplicitWrapper>; + (this: LoDashExplicitWrapper>, arg1: T1, arg2: T2, plc3: __, arg4: T4): LoDashExplicitWrapper>; + (this: LoDashExplicitWrapper>, plc1: __, plc2: __, arg3: T3, arg4: T4): LoDashExplicitWrapper>; + (this: LoDashExplicitWrapper>, arg1: T1, plc2: __, arg3: T3, arg4: T4): LoDashExplicitWrapper>; + (this: LoDashExplicitWrapper>, plc1: __, arg2: T2, arg3: T3, arg4: T4): LoDashExplicitWrapper>; + (this: LoDashExplicitWrapper>, arg1: T1, arg2: T2, arg3: T3, arg4: T4): LoDashExplicitWrapper>; + // catch-all + (...args: any[]): LoDashExplicitWrapper<(...args: any[]) => any>; + } + + // partialRight + + interface LoDashStatic { + /** + * This method is like _.partial except that partial arguments are appended to those provided + * to the new function. + * @param func The function to partially apply arguments to. + * @param args Arguments to be partially applied. + * @return The new partially applied function. + **/ + partialRight: PartialRight; + } + + interface LoDashImplicitWrapper { + /** + * @see _.partialRight + */ + partialRight: ImplicitPartialRight; + } + + interface LoDashExplicitWrapper { + /** + * @see _.partialRight + */ + partialRight: ExplicitPartialRight; + } + + interface PartialRight { + // arity 0 + (func: Function0): Function0; + // arity 1 + (func: Function1): Function1; + (func: Function1, arg1: T1): Function0; + // arity 2 + (func: Function2): Function2; + (func: Function2, arg1: T1, plc2: __): Function1< T2, R>; + (func: Function2, arg2: T2): Function1; + (func: Function2, arg1: T1, arg2: T2): Function0< R>; + // arity 3 + (func: Function3): Function3; + (func: Function3, arg1: T1, plc2: __, plc3: __): Function2< T2, T3, R>; + (func: Function3, arg2: T2, plc3: __): Function2; + (func: Function3, arg1: T1, arg2: T2, plc3: __): Function1< T3, R>; + (func: Function3, arg3: T3): Function2; + (func: Function3, arg1: T1, plc2: __, arg3: T3): Function1< T2, R>; + (func: Function3, arg2: T2, arg3: T3): Function1; + (func: Function3, arg1: T1, arg2: T2, arg3: T3): Function0< R>; + // arity 4 + (func: Function4): Function4; + (func: Function4, arg1: T1, plc2: __, plc3: __, plc4: __): Function3< T2, T3, T4, R>; + (func: Function4, arg2: T2, plc3: __, plc4: __): Function3; + (func: Function4, arg1: T1, arg2: T2, plc3: __, plc4: __): Function2< T3, T4, R>; + (func: Function4, arg3: T3, plc4: __): Function3; + (func: Function4, arg1: T1, plc2: __, arg3: T3, plc4: __): Function2< T2, T4, R>; + (func: Function4, arg2: T2, arg3: T3, plc4: __): Function2; + (func: Function4, arg1: T1, arg2: T2, arg3: T3, plc4: __): Function1< T4, R>; + (func: Function4, arg4: T4): Function3; + (func: Function4, arg1: T1, plc2: __, plc3: __, arg4: T4): Function2< T2, T3, R>; + (func: Function4, arg2: T2, plc3: __, arg4: T4): Function2; + (func: Function4, arg1: T1, arg2: T2, plc3: __, arg4: T4): Function1< T3, R>; + (func: Function4, arg3: T3, arg4: T4): Function2; + (func: Function4, arg1: T1, plc2: __, arg3: T3, arg4: T4): Function1< T2, R>; + (func: Function4, arg2: T2, arg3: T3, arg4: T4): Function1; + (func: Function4, arg1: T1, arg2: T2, arg3: T3, arg4: T4): Function0< R>; + // catch-all + (func: (...args: any[]) => any, ...args: any[]): (...args: any[]) => any; + + placeholder: __; + } + + interface ImplicitPartialRight { + // arity 0 + (this: LoDashImplicitWrapper>): LoDashImplicitWrapper>; + // arity 1 + (this: LoDashImplicitWrapper>): LoDashImplicitWrapper>; + (this: LoDashImplicitWrapper>, arg1: T1): LoDashImplicitWrapper>; + // arity 2 + (this: LoDashImplicitWrapper>): LoDashImplicitWrapper>; + (this: LoDashImplicitWrapper>, arg1: T1, plc2: __): LoDashImplicitWrapper>; + (this: LoDashImplicitWrapper>, arg2: T2): LoDashImplicitWrapper>; + (this: LoDashImplicitWrapper>, arg1: T1, arg2: T2): LoDashImplicitWrapper>; + // arity 3 + (this: LoDashImplicitWrapper>): LoDashImplicitWrapper>; + (this: LoDashImplicitWrapper>, arg1: T1, plc2: __, plc3: __): LoDashImplicitWrapper>; + (this: LoDashImplicitWrapper>, arg2: T2, plc3: __): LoDashImplicitWrapper>; + (this: LoDashImplicitWrapper>, arg1: T1, arg2: T2, plc3: __): LoDashImplicitWrapper>; + (this: LoDashImplicitWrapper>, arg3: T3): LoDashImplicitWrapper>; + (this: LoDashImplicitWrapper>, arg1: T1, plc2: __, arg3: T3): LoDashImplicitWrapper>; + (this: LoDashImplicitWrapper>, arg2: T2, arg3: T3): LoDashImplicitWrapper>; + (this: LoDashImplicitWrapper>, arg1: T1, arg2: T2, arg3: T3): LoDashImplicitWrapper>; + // arity 4 + (this: LoDashImplicitWrapper>): LoDashImplicitWrapper>; + (this: LoDashImplicitWrapper>, arg1: T1, plc2: __, plc3: __, plc4: __): LoDashImplicitWrapper>; + (this: LoDashImplicitWrapper>, arg2: T2, plc3: __, plc4: __): LoDashImplicitWrapper>; + (this: LoDashImplicitWrapper>, arg1: T1, arg2: T2, plc3: __, plc4: __): LoDashImplicitWrapper>; + (this: LoDashImplicitWrapper>, arg3: T3, plc4: __): LoDashImplicitWrapper>; + (this: LoDashImplicitWrapper>, arg1: T1, plc2: __, arg3: T3, plc4: __): LoDashImplicitWrapper>; + (this: LoDashImplicitWrapper>, arg2: T2, arg3: T3, plc4: __): LoDashImplicitWrapper>; + (this: LoDashImplicitWrapper>, arg1: T1, arg2: T2, arg3: T3, plc4: __): LoDashImplicitWrapper>; + (this: LoDashImplicitWrapper>, arg4: T4): LoDashImplicitWrapper>; + (this: LoDashImplicitWrapper>, arg1: T1, plc2: __, plc3: __, arg4: T4): LoDashImplicitWrapper>; + (this: LoDashImplicitWrapper>, arg2: T2, plc3: __, arg4: T4): LoDashImplicitWrapper>; + (this: LoDashImplicitWrapper>, arg1: T1, arg2: T2, plc3: __, arg4: T4): LoDashImplicitWrapper>; + (this: LoDashImplicitWrapper>, arg3: T3, arg4: T4): LoDashImplicitWrapper>; + (this: LoDashImplicitWrapper>, arg1: T1, plc2: __, arg3: T3, arg4: T4): LoDashImplicitWrapper>; + (this: LoDashImplicitWrapper>, arg2: T2, arg3: T3, arg4: T4): LoDashImplicitWrapper>; + (this: LoDashImplicitWrapper>, arg1: T1, arg2: T2, arg3: T3, arg4: T4): LoDashImplicitWrapper>; + // catch-all + (...args: any[]): LoDashImplicitWrapper<(...args: any[]) => any>; + } + + interface ExplicitPartialRight { + // arity 0 + (this: LoDashExplicitWrapper>): LoDashExplicitWrapper>; + // arity 1 + (this: LoDashExplicitWrapper>): LoDashExplicitWrapper>; + (this: LoDashExplicitWrapper>, arg1: T1): LoDashExplicitWrapper>; + // arity 2 + (this: LoDashExplicitWrapper>): LoDashExplicitWrapper>; + (this: LoDashExplicitWrapper>, arg1: T1, plc2: __): LoDashExplicitWrapper>; + (this: LoDashExplicitWrapper>, arg2: T2): LoDashExplicitWrapper>; + (this: LoDashExplicitWrapper>, arg1: T1, arg2: T2): LoDashExplicitWrapper>; + // arity 3 + (this: LoDashExplicitWrapper>): LoDashExplicitWrapper>; + (this: LoDashExplicitWrapper>, arg1: T1, plc2: __, plc3: __): LoDashExplicitWrapper>; + (this: LoDashExplicitWrapper>, arg2: T2, plc3: __): LoDashExplicitWrapper>; + (this: LoDashExplicitWrapper>, arg1: T1, arg2: T2, plc3: __): LoDashExplicitWrapper>; + (this: LoDashExplicitWrapper>, arg3: T3): LoDashExplicitWrapper>; + (this: LoDashExplicitWrapper>, arg1: T1, plc2: __, arg3: T3): LoDashExplicitWrapper>; + (this: LoDashExplicitWrapper>, arg2: T2, arg3: T3): LoDashExplicitWrapper>; + (this: LoDashExplicitWrapper>, arg1: T1, arg2: T2, arg3: T3): LoDashExplicitWrapper>; + // arity 4 + (this: LoDashExplicitWrapper>): LoDashExplicitWrapper>; + (this: LoDashExplicitWrapper>, arg1: T1, plc2: __, plc3: __, plc4: __): LoDashExplicitWrapper>; + (this: LoDashExplicitWrapper>, arg2: T2, plc3: __, plc4: __): LoDashExplicitWrapper>; + (this: LoDashExplicitWrapper>, arg1: T1, arg2: T2, plc3: __, plc4: __): LoDashExplicitWrapper>; + (this: LoDashExplicitWrapper>, arg3: T3, plc4: __): LoDashExplicitWrapper>; + (this: LoDashExplicitWrapper>, arg1: T1, plc2: __, arg3: T3, plc4: __): LoDashExplicitWrapper>; + (this: LoDashExplicitWrapper>, arg2: T2, arg3: T3, plc4: __): LoDashExplicitWrapper>; + (this: LoDashExplicitWrapper>, arg1: T1, arg2: T2, arg3: T3, plc4: __): LoDashExplicitWrapper>; + (this: LoDashExplicitWrapper>, arg4: T4): LoDashExplicitWrapper>; + (this: LoDashExplicitWrapper>, arg1: T1, plc2: __, plc3: __, arg4: T4): LoDashExplicitWrapper>; + (this: LoDashExplicitWrapper>, arg2: T2, plc3: __, arg4: T4): LoDashExplicitWrapper>; + (this: LoDashExplicitWrapper>, arg1: T1, arg2: T2, plc3: __, arg4: T4): LoDashExplicitWrapper>; + (this: LoDashExplicitWrapper>, arg3: T3, arg4: T4): LoDashExplicitWrapper>; + (this: LoDashExplicitWrapper>, arg1: T1, plc2: __, arg3: T3, arg4: T4): LoDashExplicitWrapper>; + (this: LoDashExplicitWrapper>, arg2: T2, arg3: T3, arg4: T4): LoDashExplicitWrapper>; + (this: LoDashExplicitWrapper>, arg1: T1, arg2: T2, arg3: T3, arg4: T4): LoDashExplicitWrapper>; + // catch-all + (...args: any[]): LoDashExplicitWrapper<(...args: any[]) => any>; + } + + // rearg + + interface LoDashStatic { + /** + * Creates a function that invokes func with arguments arranged according to the specified indexes where the + * argument value at the first index is provided as the first argument, the argument value at the second index + * is provided as the second argument, and so on. + * @param func The function to rearrange arguments for. + * @param indexes The arranged argument indexes, specified as individual indexes or arrays of indexes. + * @return Returns the new function. + */ + rearg(func: (...args: any[]) => any, ...indexes: Array>): (...args: any[]) => any; + } + + interface LoDashImplicitWrapper { + /** + * @see _.rearg + */ + rearg(...indexes: Array>): LoDashImplicitWrapper<(...args: any[]) => any>; + } + + interface LoDashExplicitWrapper { + /** + * @see _.rearg + */ + rearg(...indexes: Array>): LoDashExplicitWrapper<(...args: any[]) => any>; + } + + // rest + + interface LoDashStatic { + /** + * Creates a function that invokes func with the this binding of the created function and arguments from start + * and beyond provided as an array. + * + * Note: This method is based on the rest parameter. + * + * @param func The function to apply a rest parameter to. + * @param start The start position of the rest parameter. + * @return Returns the new function. + */ + rest( + func: (...args: any[]) => any, + start?: number + ): (...args: any[]) => any; + } + + interface LoDashImplicitWrapper { + /** + * @see _.rest + */ + rest(start?: number): LoDashImplicitWrapper<(...args: any[]) => any>; + } + + interface LoDashExplicitWrapper { + /** + * @see _.rest + */ + rest(start?: number): LoDashExplicitWrapper<(...args: any[]) => any>; + } + + // spread + + interface LoDashStatic { + /** + * Creates a function that invokes func with the this binding of the created function and an array of arguments + * much like Function#apply. + * + * Note: This method is based on the spread operator. + * + * @param func The function to spread arguments over. + * @return Returns the new function. + */ + spread(func: (...args: any[]) => TResult): (...args: any[]) => TResult; + + /** + * @see _.spread + */ + spread(func: (...args: any[]) => TResult, start: number): (...args: any[]) => TResult; + } + + interface LoDashImplicitWrapper { + /** + * @see _.spread + */ + spread(this: LoDashImplicitWrapper<(...args: any[]) => TResult>): LoDashImplicitWrapper<(...args: any[]) => TResult>; + + /** + * @see _.spread + */ + spread(this: LoDashImplicitWrapper<(...args: any[]) => TResult>, start: number): LoDashImplicitWrapper<(...args: any[]) => TResult>; + } + + interface LoDashExplicitWrapper { + /** + * @see _.spread + */ + spread(this: LoDashExplicitWrapper<(...args: any[]) => TResult>): LoDashExplicitWrapper<(...args: any[]) => TResult>; + + /** + * @see _.spread + */ + spread(this: LoDashExplicitWrapper<(...args: any[]) => TResult>, start: number): LoDashExplicitWrapper<(...args: any[]) => TResult>; + } + + // throttle + + interface ThrottleSettings { + /** + * If you'd like to disable the leading-edge call, pass this as false. + */ + leading?: boolean; + + /** + * If you'd like to disable the execution on the trailing-edge, pass false. + */ + trailing?: boolean; + } + + interface LoDashStatic { + /** + * Creates a throttled function that only invokes func at most once per every wait milliseconds. The throttled + * function comes with a cancel method to cancel delayed invocations and a flush method to immediately invoke + * them. Provide an options object to indicate that func should be invoked on the leading and/or trailing edge + * of the wait timeout. Subsequent calls to the throttled function return the result of the last func call. + * + * Note: If leading and trailing options are true, func is invoked on the trailing edge of the timeout only if + * the the throttled function is invoked more than once during the wait timeout. + * + * @param func The function to throttle. + * @param wait The number of milliseconds to throttle invocations to. + * @param options The options object. + * @param options.leading Specify invoking on the leading edge of the timeout. + * @param options.trailing Specify invoking on the trailing edge of the timeout. + * @return Returns the new throttled function. + */ + throttle any>( + func: T, + wait?: number, + options?: ThrottleSettings + ): T & Cancelable; + } + + interface LoDashImplicitWrapper { + /** + * @see _.throttle + */ + throttle( + wait?: number, + options?: ThrottleSettings + ): LoDashImplicitWrapper; + } + + interface LoDashExplicitWrapper { + /** + * @see _.throttle + */ + throttle( + wait?: number, + options?: ThrottleSettings + ): LoDashExplicitWrapper; + } + + // unary + + interface LoDashStatic { + /** + * Creates a function that accepts up to one argument, ignoring any + * additional arguments. + * + * @category Function + * @param func The function to cap arguments for. + * @returns Returns the new function. + * @example + * + * _.map(['6', '8', '10'], _.unary(parseInt)); + * // => [6, 8, 10] + */ + unary(func: (arg1: T, ...args: any[]) => TResult): (arg1: T) => TResult; + } + + interface LoDashImplicitWrapper { + /** + * @see _.unary + */ + unary(this: LoDashImplicitWrapper<(arg1: T, ...args: any[]) => TResult>): LoDashImplicitWrapper<(arg1: T) => TResult>; + } + + interface LoDashExplicitWrapper { + /** + * @see _.unary + */ + unary(this: LoDashExplicitWrapper<(arg1: T, ...args: any[]) => TResult>): LoDashExplicitWrapper<(arg1: T) => TResult>; + } + + // wrap + + interface LoDashStatic { + /** + * Creates a function that provides value to the wrapper function as its first argument. Any additional + * arguments provided to the function are appended to those provided to the wrapper function. The wrapper is + * invoked with the this binding of the created function. + * + * @param value The value to wrap. + * @param wrapper The wrapper function. + * @return Returns the new function. + */ + wrap( + value: T, + wrapper: (value: T, ...args: TArgs[]) => TResult + ): (...args: TArgs[]) => TResult; + + /** + * @see _.wrap + */ + wrap( + value: T, + wrapper: (value: T, ...args: any[]) => TResult + ): (...args: any[]) => TResult; + } + + interface LoDashImplicitWrapper { + /** + * @see _.wrap + */ + wrap( + wrapper: (value: TValue, ...args: TArgs[]) => TResult + ): LoDashImplicitWrapper<(...args: TArgs[]) => TResult>; + + /** + * @see _.wrap + */ + wrap( + wrapper: (value: TValue, ...args: any[]) => TResult + ): LoDashImplicitWrapper<(...args: any[]) => TResult>; + } + + interface LoDashExplicitWrapper { + /** + * @see _.wrap + */ + /** + * @see _.wrap + */ + wrap( + wrapper: (value: TValue, ...args: TArgs[]) => TResult + ): LoDashExplicitWrapper<(...args: TArgs[]) => TResult>; + + /** + * @see _.wrap + */ + wrap( + wrapper: (value: TValue, ...args: any[]) => TResult + ): LoDashExplicitWrapper<(...args: any[]) => TResult>; + } +} diff --git a/node_modules/@types/lodash/common/lang.d.ts b/node_modules/@types/lodash/common/lang.d.ts new file mode 100644 index 0000000..723388c --- /dev/null +++ b/node_modules/@types/lodash/common/lang.d.ts @@ -0,0 +1,1936 @@ +import _ = require("../index"); +declare module "../index" { + // castArray + + interface LoDashStatic { + /** + * Casts value as an array if it’s not one. + * + * @param value The value to inspect. + * @return Returns the cast array. + */ + castArray(value?: Many): T[]; + } + + interface LoDashImplicitWrapper { + /** + * @see _.castArray + */ + castArray(this: LoDashImplicitWrapper>): LoDashImplicitWrapper; + } + + interface LoDashExplicitWrapper { + /** + * @see _.castArray + */ + castArray(this: LoDashExplicitWrapper>): LoDashExplicitWrapper; + } + + // clone + + interface LoDashStatic { + /** + * Creates a shallow clone of value. + * + * Note: This method is loosely based on the structured clone algorithm and supports cloning arrays, + * array buffers, booleans, date objects, maps, numbers, Object objects, regexes, sets, strings, symbols, + * and typed arrays. The own enumerable properties of arguments objects are cloned as plain objects. An empty + * object is returned for uncloneable values such as error objects, functions, DOM nodes, and WeakMaps. + * + * @param value The value to clone. + * @return Returns the cloned value. + */ + clone(value: T): T; + } + + interface LoDashImplicitWrapper { + /** + * @see _.clone + */ + clone(): TValue; + } + + interface LoDashExplicitWrapper { + /** + * @see _.clone + */ + clone(): this; + } + + // cloneDeep + + interface LoDashStatic { + /** + * This method is like _.clone except that it recursively clones value. + * + * @param value The value to recursively clone. + * @return Returns the deep cloned value. + */ + cloneDeep(value: T): T; + } + + interface LoDashImplicitWrapper { + /** + * @see _.cloneDeep + */ + cloneDeep(): TValue; + } + + interface LoDashExplicitWrapper { + /** + * @see _.cloneDeep + */ + cloneDeep(): this; + } + + // cloneDeepWith + + type CloneDeepWithCustomizer = (value: any, key: number | string | undefined, object: TObject | undefined, stack: any) => any; + + interface LoDashStatic { + /** + * This method is like _.cloneWith except that it recursively clones value. + * + * @param value The value to recursively clone. + * @param customizer The function to customize cloning. + * @return Returns the deep cloned value. + */ + cloneDeepWith( + value: T, + customizer: CloneDeepWithCustomizer + ): any; + + /** + * @see _.cloneDeepWith + */ + cloneDeepWith(value: T): T; + } + + interface LoDashImplicitWrapper { + /** + * @see _.cloneDeepWith + */ + cloneDeepWith( + customizer: CloneDeepWithCustomizer + ): any; + + /** + * @see _.cloneDeepWith + */ + cloneDeepWith(): TValue; + } + + interface LoDashExplicitWrapper { + /** + * @see _.cloneDeepWith + */ + cloneDeepWith( + customizer: CloneDeepWithCustomizer + ): LoDashExplicitWrapper; + + /** + * @see _.cloneDeepWith + */ + cloneDeepWith(): this; + } + + // cloneWith + + type CloneWithCustomizer = (value: TValue, key: number | string | undefined, object: any, stack: any) => TResult; + + interface LoDashStatic { + /** + * This method is like _.clone except that it accepts customizer which is invoked to produce the cloned value. + * If customizer returns undefined cloning is handled by the method instead. + * + * @param value The value to clone. + * @param customizer The function to customize cloning. + * @return Returns the cloned value. + */ + cloneWith( + value: T, + customizer: CloneWithCustomizer + ): TResult; + + /** + * @see _.cloneWith + */ + cloneWith( + value: T, + customizer: CloneWithCustomizer + ): TResult | T; + + /** + * @see _.cloneWith + */ + cloneWith(value: T): T; + } + + interface LoDashImplicitWrapper { + /** + * @see _.cloneWith + */ + cloneWith( + customizer: CloneWithCustomizer + ): TResult; + + /** + * @see _.cloneWith + */ + cloneWith( + customizer: CloneWithCustomizer + ): TResult | TValue; + + /** + * @see _.cloneWith + */ + cloneWith(): TValue; + } + + interface LoDashExplicitWrapper { + /** + * @see _.cloneWith + */ + cloneWith( + customizer: CloneWithCustomizer + ): LoDashExplicitWrapper; + + /** + * @see _.cloneWith + */ + cloneWith( + customizer: CloneWithCustomizer + ): LoDashExplicitWrapper; + + /** + * @see _.cloneWith + */ + cloneWith(): this; + } + + // conformsTo + + interface LoDashStatic { + /** + * Checks if object conforms to source by invoking the predicate properties of source with the + * corresponding property values of object. + * + * Note: This method is equivalent to _.conforms when source is partially applied. + */ + conformsTo(object: T, source: ConformsPredicateObject): boolean; + } + + interface LoDashImplicitWrapper { + /** + * @see _.conformsTo + */ + conformsTo(this: LoDashImplicitWrapper, source: ConformsPredicateObject): boolean; + // Note: we can't use TValue here, because it generates a typescript error when strictFunctionTypes is enabled. + } + + interface LoDashExplicitWrapper { + /** + * @see _.conformsTo + */ + conformsTo(this: LoDashExplicitWrapper, source: ConformsPredicateObject): LoDashExplicitWrapper; + // Note: we can't use TValue here, because it generates a typescript error when strictFunctionTypes is enabled. + } + + type CondPair = [(val: T) => boolean, (val: T) => R]; + + // eq + + interface LoDashStatic { + /** + * Performs a [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero) + * comparison between two values to determine if they are equivalent. + * + * @category Lang + * @param value The value to compare. + * @param other The other value to compare. + * @returns Returns `true` if the values are equivalent, else `false`. + * @example + * + * var object = { 'user': 'fred' }; + * var other = { 'user': 'fred' }; + * + * _.eq(object, object); + * // => true + * + * _.eq(object, other); + * // => false + * + * _.eq('a', 'a'); + * // => true + * + * _.eq('a', Object('a')); + * // => false + * + * _.eq(NaN, NaN); + * // => true + */ + eq( + value: any, + other: any + ): boolean; + } + + interface LoDashImplicitWrapper { + /** + * @see _.eq + */ + eq( + other: any + ): boolean; + } + + interface LoDashExplicitWrapper { + /** + * @see _.eq + */ + eq( + other: any + ): LoDashExplicitWrapper; + } + + // gt + + interface LoDashStatic { + /** + * Checks if value is greater than other. + * + * @param value The value to compare. + * @param other The other value to compare. + * @return Returns true if value is greater than other, else false. + */ + gt( + value: any, + other: any + ): boolean; + } + + interface LoDashImplicitWrapper { + /** + * @see _.gt + */ + gt(other: any): boolean; + } + + interface LoDashExplicitWrapper { + /** + * @see _.gt + */ + gt(other: any): LoDashExplicitWrapper; + } + + // gte + + interface LoDashStatic { + /** + * Checks if value is greater than or equal to other. + * + * @param value The value to compare. + * @param other The other value to compare. + * @return Returns true if value is greater than or equal to other, else false. + */ + gte( + value: any, + other: any + ): boolean; + } + + interface LoDashImplicitWrapper { + /** + * @see _.gte + */ + gte(other: any): boolean; + } + + interface LoDashExplicitWrapper { + /** + * @see _.gte + */ + gte(other: any): LoDashExplicitWrapper; + } + + // isArguments + + interface LoDashStatic { + /** + * Checks if value is classified as an arguments object. + * + * @param value The value to check. + * @return Returns true if value is correctly classified, else false. + */ + isArguments(value?: any): value is IArguments; + } + + interface LoDashImplicitWrapper { + /** + * @see _.isArguments + */ + isArguments(): boolean; + } + + interface LoDashExplicitWrapper { + /** + * @see _.isArguments + */ + isArguments(): LoDashExplicitWrapper; + } + + // isArray + + interface LoDashStatic { + /** + * Checks if value is classified as an Array object. + * @param value The value to check. + * + * @return Returns true if value is correctly classified, else false. + */ + isArray(value?: any): value is any[]; + + /** + * DEPRECATED + */ + isArray(value?: any): value is any[]; + } + + interface LoDashImplicitWrapper { + /** + * @see _.isArray + */ + isArray(): boolean; + } + + interface LoDashExplicitWrapper { + /** + * @see _.isArray + */ + isArray(): LoDashExplicitWrapper; + } + + // isArrayBuffer + + interface LoDashStatic { + /** + * Checks if value is classified as an ArrayBuffer object. + * + * @param value The value to check. + * @return Returns true if value is correctly classified, else false. + */ + isArrayBuffer(value?: any): value is ArrayBuffer; + } + + interface LoDashImplicitWrapper { + /** + * @see _.isArrayBuffer + */ + isArrayBuffer(): boolean; + } + + interface LoDashExplicitWrapper { + /** + * @see _.isArrayBuffer + */ + isArrayBuffer(): LoDashExplicitWrapper; + } + + // isArrayLike + + interface LoDashStatic { + /** + * Checks if `value` is array-like. A value is considered array-like if it's + * not a function and has a `value.length` that's an integer greater than or + * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. + * + * @category Lang + * @param value The value to check. + * @returns Returns `true` if `value` is array-like, else `false`. + * @example + * + * _.isArrayLike([1, 2, 3]); + * // => true + * + * _.isArrayLike(document.body.children); + * // => true + * + * _.isArrayLike('abc'); + * // => true + * + * _.isArrayLike(_.noop); + * // => false + */ + isArrayLike(value: T & string & number): boolean; // should only match if T = any + + /** + * @see _.isArrayLike + */ + isArrayLike(value: ((...args: any[]) => any) | null | undefined): value is never; + + /** + * @see _.isArrayLike + */ + isArrayLike(value: any): value is { length: number }; + } + + interface LoDashImplicitWrapper { + /** + * @see _.isArrayLike + */ + isArrayLike(): boolean; + } + + interface LoDashExplicitWrapper { + /** + * @see _.isArrayLike + */ + isArrayLike(): LoDashExplicitWrapper; + } + + // isArrayLikeObject + + interface LoDashStatic { + /** + * This method is like `_.isArrayLike` except that it also checks if `value` + * is an object. + * + * @category Lang + * @param value The value to check. + * @returns Returns `true` if `value` is an array-like object, else `false`. + * @example + * + * _.isArrayLikeObject([1, 2, 3]); + * // => true + * + * _.isArrayLikeObject(document.body.children); + * // => true + * + * _.isArrayLikeObject('abc'); + * // => false + * + * _.isArrayLikeObject(_.noop); + * // => false + */ + isArrayLikeObject(value: T & string & number): boolean; // should only match if T = any + + /** + * @see _.isArrayLike + */ + // tslint:disable-next-line:ban-types (type guard doesn't seem to work correctly without the Function type) + isArrayLikeObject(value: ((...args: any[]) => any) | Function | string | boolean | number | null | undefined): value is never; + + /** + * @see _.isArrayLike + */ + // tslint:disable-next-line:ban-types (type guard doesn't seem to work correctly without the Function type) + isArrayLikeObject(value: T | ((...args: any[]) => any) | Function | string | boolean | number | null | undefined): value is T & { length: number }; + } + + interface LoDashImplicitWrapper { + /** + * @see _.isArrayLikeObject + */ + isArrayLikeObject(): boolean; + } + + interface LoDashExplicitWrapper { + /** + * @see _.isArrayLikeObject + */ + isArrayLikeObject(): LoDashExplicitWrapper; + } + + // isBoolean + + interface LoDashStatic { + /** + * Checks if value is classified as a boolean primitive or object. + * + * @param value The value to check. + * @return Returns true if value is correctly classified, else false. + */ + isBoolean(value?: any): value is boolean; + } + + interface LoDashImplicitWrapper { + /** + * @see _.isBoolean + */ + isBoolean(): boolean; + } + + interface LoDashExplicitWrapper { + /** + * @see _.isBoolean + */ + isBoolean(): LoDashExplicitWrapper; + } + + // isBuffer + + interface LoDashStatic { + /** + * Checks if value is a buffer. + * + * @param value The value to check. + * @return Returns true if value is a buffer, else false. + */ + isBuffer(value?: any): boolean; + } + + interface LoDashImplicitWrapper { + /** + * @see _.isBuffer + */ + isBuffer(): boolean; + } + + interface LoDashExplicitWrapper { + /** + * @see _.isBuffer + */ + isBuffer(): LoDashExplicitWrapper; + } + + // isDate + + interface LoDashStatic { + /** + * Checks if value is classified as a Date object. + * @param value The value to check. + * + * @return Returns true if value is correctly classified, else false. + */ + isDate(value?: any): value is Date; + } + + interface LoDashImplicitWrapper { + /** + * @see _.isDate + */ + isDate(): boolean; + } + + interface LoDashExplicitWrapper { + /** + * @see _.isDate + */ + isDate(): LoDashExplicitWrapper; + } + + // isElement + + interface LoDashStatic { + /** + * Checks if value is a DOM element. + * + * @param value The value to check. + * @return Returns true if value is a DOM element, else false. + */ + isElement(value?: any): boolean; + } + + interface LoDashImplicitWrapper { + /** + * @see _.isElement + */ + isElement(): boolean; + } + + interface LoDashExplicitWrapper { + /** + * @see _.isElement + */ + isElement(): LoDashExplicitWrapper; + } + + // isEmpty + + interface LoDashStatic { + /** + * Checks if value is empty. A value is considered empty unless it’s an arguments object, array, string, or + * jQuery-like collection with a length greater than 0 or an object with own enumerable properties. + * + * @param value The value to inspect. + * @return Returns true if value is empty, else false. + */ + isEmpty(value?: any): boolean; + } + + interface LoDashImplicitWrapper { + /** + * @see _.isEmpty + */ + isEmpty(): boolean; + } + + interface LoDashExplicitWrapper { + /** + * @see _.isEmpty + */ + isEmpty(): LoDashExplicitWrapper; + } + + // isEqual + + interface LoDashStatic { + /** + * Performs a deep comparison between two values to determine if they are + * equivalent. + * + * **Note:** This method supports comparing arrays, array buffers, booleans, + * date objects, error objects, maps, numbers, `Object` objects, regexes, + * sets, strings, symbols, and typed arrays. `Object` objects are compared + * by their own, not inherited, enumerable properties. Functions and DOM + * nodes are **not** supported. + * + * @category Lang + * @param value The value to compare. + * @param other The other value to compare. + * @returns Returns `true` if the values are equivalent, else `false`. + * @example + * + * var object = { 'user': 'fred' }; + * var other = { 'user': 'fred' }; + * + * _.isEqual(object, other); + * // => true + * + * object === other; + * // => false + */ + isEqual( + value: any, + other: any + ): boolean; + } + + interface LoDashImplicitWrapper { + /** + * @see _.isEqual + */ + isEqual( + other: any + ): boolean; + } + + interface LoDashExplicitWrapper { + /** + * @see _.isEqual + */ + isEqual( + other: any + ): LoDashExplicitWrapper; + } + + // isEqualWith + + type IsEqualCustomizer = (value: any, other: any, indexOrKey: PropertyName | undefined, parent: any, otherParent: any, stack: any) => boolean|undefined; + + interface LoDashStatic { + /** + * This method is like `_.isEqual` except that it accepts `customizer` which is + * invoked to compare values. If `customizer` returns `undefined` comparisons are + * handled by the method instead. The `customizer` is invoked with up to seven arguments: + * (objValue, othValue [, index|key, object, other, stack]). + * + * @category Lang + * @param value The value to compare. + * @param other The other value to compare. + * @param [customizer] The function to customize comparisons. + * @returns Returns `true` if the values are equivalent, else `false`. + * @example + * + * function isGreeting(value) { + * return /^h(?:i|ello)$/.test(value); + * } + * + * function customizer(objValue, othValue) { + * if (isGreeting(objValue) && isGreeting(othValue)) { + * return true; + * } + * } + * + * var array = ['hello', 'goodbye']; + * var other = ['hi', 'goodbye']; + * + * _.isEqualWith(array, other, customizer); + * // => true + */ + isEqualWith( + value: any, + other: any, + customizer?: IsEqualCustomizer + ): boolean; + } + + interface LoDashImplicitWrapper { + /** + * @see _.isEqualWith + */ + isEqualWith( + other: any, + customizer?: IsEqualCustomizer + ): boolean; + } + + interface LoDashExplicitWrapper { + /** + * @see _.isEqualWith + */ + isEqualWith( + other: any, + customizer?: IsEqualCustomizer + ): LoDashExplicitWrapper; + } + + // isError + + interface LoDashStatic { + /** + * Checks if value is an Error, EvalError, RangeError, ReferenceError, SyntaxError, TypeError, or URIError + * object. + * + * @param value The value to check. + * @return Returns true if value is an error object, else false. + */ + isError(value: any): value is Error; + } + + interface LoDashImplicitWrapper { + /** + * @see _.isError + */ + isError(): boolean; + } + + interface LoDashExplicitWrapper { + /** + * @see _.isError + */ + isError(): LoDashExplicitWrapper; + } + + // isFinite + + interface LoDashStatic { + /** + * Checks if value is a finite primitive number. + * + * Note: This method is based on Number.isFinite. + * + * @param value The value to check. + * @return Returns true if value is a finite number, else false. + */ + isFinite(value?: any): boolean; + } + + interface LoDashImplicitWrapper { + /** + * @see _.isFinite + */ + isFinite(): boolean; + } + + interface LoDashExplicitWrapper { + /** + * @see _.isFinite + */ + isFinite(): LoDashExplicitWrapper; + } + + // isFunction + + interface LoDashStatic { + /** + * Checks if value is a callable function. + * + * @param value The value to check. + * @return Returns true if value is correctly classified, else false. + */ + isFunction(value: any): value is (...args: any[]) => any; + } + + interface LoDashImplicitWrapper { + /** + * @see _.isFunction + */ + isFunction(): boolean; + } + + interface LoDashExplicitWrapper { + /** + * @see _.isFunction + */ + isFunction(): LoDashExplicitWrapper; + } + + // isInteger + + interface LoDashStatic { + /** + * Checks if `value` is an integer. + * + * **Note:** This method is based on [`Number.isInteger`](https://mdn.io/Number/isInteger). + * + * @category Lang + * @param value The value to check. + * @returns Returns `true` if `value` is an integer, else `false`. + * @example + * + * _.isInteger(3); + * // => true + * + * _.isInteger(Number.MIN_VALUE); + * // => false + * + * _.isInteger(Infinity); + * // => false + * + * _.isInteger('3'); + * // => false + */ + isInteger(value?: any): boolean; + } + + interface LoDashImplicitWrapper { + /** + * @see _.isInteger + */ + isInteger(): boolean; + } + + interface LoDashExplicitWrapper { + /** + * @see _.isInteger + */ + isInteger(): LoDashExplicitWrapper; + } + + // isLength + + interface LoDashStatic { + /** + * Checks if `value` is a valid array-like length. + * + * **Note:** This function is loosely based on [`ToLength`](http://ecma-international.org/ecma-262/6.0/#sec-tolength). + * + * @category Lang + * @param value The value to check. + * @returns Returns `true` if `value` is a valid length, else `false`. + * @example + * + * _.isLength(3); + * // => true + * + * _.isLength(Number.MIN_VALUE); + * // => false + * + * _.isLength(Infinity); + * // => false + * + * _.isLength('3'); + * // => false + */ + isLength(value?: any): boolean; + } + + interface LoDashImplicitWrapper { + /** + * @see _.isLength + */ + isLength(): boolean; + } + + interface LoDashExplicitWrapper { + /** + * @see _.isLength + */ + isLength(): LoDashExplicitWrapper; + } + + // isMap + + interface LoDashStatic { + /** + * Checks if value is classified as a Map object. + * + * @param value The value to check. + * @returns Returns true if value is correctly classified, else false. + */ + isMap(value?: any): value is Map; + } + + interface LoDashImplicitWrapper { + /** + * @see _.isMap + */ + isMap(): boolean; + } + + interface LoDashExplicitWrapper { + /** + * @see _.isMap + */ + isMap(): LoDashExplicitWrapper; + } + + // isMatch + + type isMatchCustomizer = (value: any, other: any, indexOrKey?: PropertyName) => boolean; + + interface LoDashStatic { + /** + * Performs a deep comparison between `object` and `source` to determine if + * `object` contains equivalent property values. + * + * **Note:** This method supports comparing the same values as `_.isEqual`. + * + * @category Lang + * @param object The object to inspect. + * @param source The object of property values to match. + * @returns Returns `true` if `object` is a match, else `false`. + * @example + * + * var object = { 'user': 'fred', 'age': 40 }; + * + * _.isMatch(object, { 'age': 40 }); + * // => true + * + * _.isMatch(object, { 'age': 36 }); + * // => false + */ + isMatch(object: object, source: object): boolean; + } + + interface LoDashImplicitWrapper { + /** + * @see _.isMatch + */ + isMatch(source: object): boolean; + } + + interface LoDashExplicitWrapper { + /** + * @see _.isMatch + */ + isMatch(source: object): LoDashExplicitWrapper; + } + + // isMatchWith + + type isMatchWithCustomizer = (value: any, other: any, indexOrKey: PropertyName, object: object, source: object) => boolean; + + interface LoDashStatic { + /** + * This method is like `_.isMatch` except that it accepts `customizer` which + * is invoked to compare values. If `customizer` returns `undefined` comparisons + * are handled by the method instead. The `customizer` is invoked with three + * arguments: (objValue, srcValue, index|key, object, source). + * + * @category Lang + * @param object The object to inspect. + * @param source The object of property values to match. + * @param [customizer] The function to customize comparisons. + * @returns Returns `true` if `object` is a match, else `false`. + * @example + * + * function isGreeting(value) { + * return /^h(?:i|ello)$/.test(value); + * } + * + * function customizer(objValue, srcValue) { + * if (isGreeting(objValue) && isGreeting(srcValue)) { + * return true; + * } + * } + * + * var object = { 'greeting': 'hello' }; + * var source = { 'greeting': 'hi' }; + * + * _.isMatchWith(object, source, customizer); + * // => true + */ + isMatchWith(object: object, source: object, customizer: isMatchWithCustomizer): boolean; + } + + interface LoDashImplicitWrapper { + /** + * @see _.isMatchWith + */ + isMatchWith(source: object, customizer: isMatchWithCustomizer): boolean; + } + + interface LoDashExplicitWrapper { + /** + * @see _.isMatchWith + */ + isMatchWith(source: object, customizer: isMatchWithCustomizer): LoDashExplicitWrapper; + } + + // isNaN + + interface LoDashStatic { + /** + * Checks if value is NaN. + * + * Note: This method is not the same as isNaN which returns true for undefined and other non-numeric values. + * + * @param value The value to check. + * @return Returns true if value is NaN, else false. + */ + isNaN(value?: any): boolean; + } + + interface LoDashImplicitWrapper { + /** + * @see _.isNaN + */ + isNaN(): boolean; + } + + interface LoDashExplicitWrapper { + /** + * @see _.isNaN + */ + isNaN(): LoDashExplicitWrapper; + } + + // isNative + + interface LoDashStatic { + /** + * Checks if value is a native function. + * @param value The value to check. + * + * @retrun Returns true if value is a native function, else false. + */ + isNative(value: any): value is (...args: any[]) => any; + } + + interface LoDashImplicitWrapper { + /** + * see _.isNative + */ + isNative(): boolean; + } + + interface LoDashExplicitWrapper { + /** + * see _.isNative + */ + isNative(): LoDashExplicitWrapper; + } + + // isNil + + interface LoDashStatic { + /** + * Checks if `value` is `null` or `undefined`. + * + * @category Lang + * @param value The value to check. + * @returns Returns `true` if `value` is nullish, else `false`. + * @example + * + * _.isNil(null); + * // => true + * + * _.isNil(void 0); + * // => true + * + * _.isNil(NaN); + * // => false + */ + isNil(value: any): value is null | undefined; + } + + interface LoDashImplicitWrapper { + /** + * see _.isNil + */ + isNil(): boolean; + } + + interface LoDashExplicitWrapper { + /** + * see _.isNil + */ + isNil(): LoDashExplicitWrapper; + } + + // isNull + + interface LoDashStatic { + /** + * Checks if value is null. + * + * @param value The value to check. + * @return Returns true if value is null, else false. + */ + isNull(value: any): value is null; + } + + interface LoDashImplicitWrapper { + /** + * see _.isNull + */ + isNull(): boolean; + } + + interface LoDashExplicitWrapper { + /** + * see _.isNull + */ + isNull(): LoDashExplicitWrapper; + } + + // isNumber + + interface LoDashStatic { + /** + * Checks if value is classified as a Number primitive or object. + * + * Note: To exclude Infinity, -Infinity, and NaN, which are classified as numbers, use the _.isFinite method. + * + * @param value The value to check. + * @return Returns true if value is correctly classified, else false. + */ + isNumber(value?: any): value is number; + } + + interface LoDashImplicitWrapper { + /** + * see _.isNumber + */ + isNumber(): boolean; + } + + interface LoDashExplicitWrapper { + /** + * see _.isNumber + */ + isNumber(): LoDashExplicitWrapper; + } + + // isObject + + interface LoDashStatic { + /** + * Checks if value is the language type of Object. (e.g. arrays, functions, objects, regexes, new Number(0), + * and new String('')) + * + * @param value The value to check. + * @return Returns true if value is an object, else false. + */ + isObject(value?: any): boolean; + } + + interface LoDashImplicitWrapper { + /** + * see _.isObject + */ + isObject(): boolean; + } + + interface LoDashExplicitWrapper { + /** + * see _.isObject + */ + isObject(): LoDashExplicitWrapper; + } + + // isObjectLike + + interface LoDashStatic { + /** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". + * + * @category Lang + * @param value The value to check. + * @returns Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ + isObjectLike(value?: any): boolean; + } + + interface LoDashImplicitWrapper { + /** + * see _.isObjectLike + */ + isObjectLike(): boolean; + } + + interface LoDashExplicitWrapper { + /** + * see _.isObjectLike + */ + isObjectLike(): LoDashExplicitWrapper; + } + + // isPlainObject + + interface LoDashStatic { + /** + * Checks if value is a plain object, that is, an object created by the Object constructor or one with a + * [[Prototype]] of null. + * + * Note: This method assumes objects created by the Object constructor have no inherited enumerable properties. + * + * @param value The value to check. + * @return Returns true if value is a plain object, else false. + */ + isPlainObject(value?: any): boolean; + } + + interface LoDashImplicitWrapper { + /** + * see _.isPlainObject + */ + isPlainObject(): boolean; + } + + interface LoDashExplicitWrapper { + /** + * see _.isPlainObject + */ + isPlainObject(): LoDashExplicitWrapper; + } + + // isRegExp + + interface LoDashStatic { + /** + * Checks if value is classified as a RegExp object. + * @param value The value to check. + * + * @return Returns true if value is correctly classified, else false. + */ + isRegExp(value?: any): value is RegExp; + } + + interface LoDashImplicitWrapper { + /** + * see _.isRegExp + */ + isRegExp(): boolean; + } + + interface LoDashExplicitWrapper { + /** + * see _.isRegExp + */ + isRegExp(): LoDashExplicitWrapper; + } + + // isSafeInteger + + interface LoDashStatic { + /** + * Checks if `value` is a safe integer. An integer is safe if it's an IEEE-754 + * double precision number which isn't the result of a rounded unsafe integer. + * + * **Note:** This method is based on [`Number.isSafeInteger`](https://mdn.io/Number/isSafeInteger). + * + * @category Lang + * @param value The value to check. + * @returns Returns `true` if `value` is a safe integer, else `false`. + * @example + * + * _.isSafeInteger(3); + * // => true + * + * _.isSafeInteger(Number.MIN_VALUE); + * // => false + * + * _.isSafeInteger(Infinity); + * // => false + * + * _.isSafeInteger('3'); + * // => false + */ + isSafeInteger(value: any): boolean; + } + + interface LoDashImplicitWrapper { + /** + * see _.isSafeInteger + */ + isSafeInteger(): boolean; + } + + interface LoDashExplicitWrapper { + /** + * see _.isSafeInteger + */ + isSafeInteger(): LoDashExplicitWrapper; + } + + // isSet + + interface LoDashStatic { + /** + * Checks if value is classified as a Set object. + * + * @param value The value to check. + * @returns Returns true if value is correctly classified, else false. + */ + isSet(value?: any): value is Set; + } + + interface LoDashImplicitWrapper { + /** + * @see _.isSet + */ + isSet(): boolean; + } + + interface LoDashExplicitWrapper { + /** + * @see _.isSet + */ + isSet(): LoDashExplicitWrapper; + } + + // isString + + interface LoDashStatic { + /** + * Checks if value is classified as a String primitive or object. + * + * @param value The value to check. + * @return Returns true if value is correctly classified, else false. + */ + isString(value?: any): value is string; + } + + interface LoDashImplicitWrapper { + /** + * see _.isString + */ + isString(): boolean; + } + + interface LoDashExplicitWrapper { + /** + * see _.isString + */ + isString(): LoDashExplicitWrapper; + } + + // isSymbol + + interface LoDashStatic { + /** + * Checks if `value` is classified as a `Symbol` primitive or object. + * + * @category Lang + * @param value The value to check. + * @returns Returns `true` if `value` is correctly classified, else `false`. + * @example + * + * _.isSymbol(Symbol.iterator); + * // => true + * + * _.isSymbol('abc'); + * // => false + */ + isSymbol(value: any): boolean; + } + + interface LoDashImplicitWrapper { + /** + * see _.isSymbol + */ + isSymbol(): boolean; + } + + interface LoDashExplicitWrapper { + /** + * see _.isSymbol + */ + isSymbol(): LoDashExplicitWrapper; + } + + // isTypedArray + + interface LoDashStatic { + /** + * Checks if value is classified as a typed array. + * + * @param value The value to check. + * @return Returns true if value is correctly classified, else false. + */ + isTypedArray(value: any): boolean; + } + + interface LoDashImplicitWrapper { + /** + * see _.isTypedArray + */ + isTypedArray(): boolean; + } + + interface LoDashExplicitWrapper { + /** + * see _.isTypedArray + */ + isTypedArray(): LoDashExplicitWrapper; + } + + // isUndefined + + interface LoDashStatic { + /** + * Checks if value is undefined. + * + * @param value The value to check. + * @return Returns true if value is undefined, else false. + */ + isUndefined(value: any): value is undefined; + } + + interface LoDashImplicitWrapper { + /** + * see _.isUndefined + */ + isUndefined(): boolean; + } + + interface LoDashExplicitWrapper { + /** + * see _.isUndefined + */ + isUndefined(): LoDashExplicitWrapper; + } + + // isWeakMap + + interface LoDashStatic { + /** + * Checks if value is classified as a WeakMap object. + * + * @param value The value to check. + * @returns Returns true if value is correctly classified, else false. + */ + isWeakMap(value?: any): value is WeakMap; + } + + interface LoDashImplicitWrapper { + /** + * @see _.isSet + */ + isWeakMap(): boolean; + } + + interface LoDashExplicitWrapper { + /** + * @see _.isSet + */ + isWeakMap(): LoDashExplicitWrapper; + } + + // isWeakSet + + interface LoDashStatic { + /** + * Checks if value is classified as a WeakSet object. + * + * @param value The value to check. + * @returns Returns true if value is correctly classified, else false. + */ + isWeakSet(value?: any): value is WeakSet; + } + + interface LoDashImplicitWrapper { + /** + * @see _.isWeakSet + */ + isWeakSet(): boolean; + } + + interface LoDashExplicitWrapper { + /** + * @see _.isWeakSet + */ + isWeakSet(): LoDashExplicitWrapper; + } + + // lt + + interface LoDashStatic { + /** + * Checks if value is less than other. + * + * @param value The value to compare. + * @param other The other value to compare. + * @return Returns true if value is less than other, else false. + */ + lt( + value: any, + other: any + ): boolean; + } + + interface LoDashImplicitWrapper { + /** + * @see _.lt + */ + lt(other: any): boolean; + } + + interface LoDashExplicitWrapper { + /** + * @see _.lt + */ + lt(other: any): LoDashExplicitWrapper; + } + + // lte + + interface LoDashStatic { + /** + * Checks if value is less than or equal to other. + * + * @param value The value to compare. + * @param other The other value to compare. + * @return Returns true if value is less than or equal to other, else false. + */ + lte( + value: any, + other: any + ): boolean; + } + + interface LoDashImplicitWrapper { + /** + * @see _.lte + */ + lte(other: any): boolean; + } + + interface LoDashExplicitWrapper { + /** + * @see _.lte + */ + lte(other: any): LoDashExplicitWrapper; + } + + // toArray + + interface LoDashStatic { + /** + * Converts value to an array. + * + * @param value The value to convert. + * @return Returns the converted array. + */ + toArray(value: List | Dictionary | NumericDictionary | null | undefined): T[]; + + /** + * @see _.toArray + */ + toArray(value: T): Array; + + /** + * @see _.toArray + */ + toArray(): any[]; + } + + interface LoDashImplicitWrapper { + /** + * @see _.toArray + */ + toArray(this: LoDashImplicitWrapper | Dictionary | NumericDictionary | null | undefined>): LoDashImplicitWrapper; + + /** + * @see _.toArray + */ + toArray(this: LoDashImplicitWrapper): LoDashImplicitWrapper>; + } + + interface LoDashExplicitWrapper { + /** + * @see _.toArray + */ + toArray(this: LoDashExplicitWrapper | Dictionary | NumericDictionary | null | undefined>): LoDashExplicitWrapper; + + /** + * @see _.toArray + */ + toArray(this: LoDashImplicitWrapper): LoDashExplicitWrapper>; + } + + // toFinite + + interface LoDashStatic { + /** + * Converts `value` to a finite number. + * + * @since 4.12.0 + * @category Lang + * @param value The value to convert. + * @returns Returns the converted number. + * @example + * + * _.toFinite(3.2); + * // => 3.2 + * + * _.toFinite(Number.MIN_VALUE); + * // => 5e-324 + * + * _.toFinite(Infinity); + * // => 1.7976931348623157e+308 + * + * _.toFinite('3.2'); + * // => 3.2 + */ + toFinite(value: any): number; + } + + interface LoDashImplicitWrapper { + /** + * @see _.toFinite + */ + toFinite(): number; + } + + interface LoDashExplicitWrapper { + /** + * @see _.toFinite + */ + toFinite(): LoDashExplicitWrapper; + } + + // toInteger + + interface LoDashStatic { + /** + * Converts `value` to an integer. + * + * **Note:** This function is loosely based on [`ToInteger`](http://www.ecma-international.org/ecma-262/6.0/#sec-tointeger). + * + * @category Lang + * @param value The value to convert. + * @returns Returns the converted integer. + * @example + * + * _.toInteger(3); + * // => 3 + * + * _.toInteger(Number.MIN_VALUE); + * // => 0 + * + * _.toInteger(Infinity); + * // => 1.7976931348623157e+308 + * + * _.toInteger('3'); + * // => 3 + */ + toInteger(value: any): number; + } + + interface LoDashImplicitWrapper { + /** + * @see _.toInteger + */ + toInteger(): number; + } + + interface LoDashExplicitWrapper { + /** + * @see _.toInteger + */ + toInteger(): LoDashExplicitWrapper; + } + + // toLength + + interface LoDashStatic { + /** + * Converts `value` to an integer suitable for use as the length of an + * array-like object. + * + * **Note:** This method is based on [`ToLength`](http://ecma-international.org/ecma-262/6.0/#sec-tolength). + * + * @category Lang + * @param value The value to convert. + * @return Returns the converted integer. + * @example + * + * _.toLength(3); + * // => 3 + * + * _.toLength(Number.MIN_VALUE); + * // => 0 + * + * _.toLength(Infinity); + * // => 4294967295 + * + * _.toLength('3'); + * // => 3 + */ + toLength(value: any): number; + } + + interface LoDashImplicitWrapper { + /** + * @see _.toLength + */ + toLength(): number; + } + + interface LoDashExplicitWrapper { + /** + * @see _.toLength + */ + toLength(): LoDashExplicitWrapper; + } + + // toNumber + + interface LoDashStatic { + /** + * Converts `value` to a number. + * + * @category Lang + * @param value The value to process. + * @returns Returns the number. + * @example + * + * _.toNumber(3); + * // => 3 + * + * _.toNumber(Number.MIN_VALUE); + * // => 5e-324 + * + * _.toNumber(Infinity); + * // => Infinity + * + * _.toNumber('3'); + * // => 3 + */ + toNumber(value: any): number; + } + + interface LoDashImplicitWrapper { + /** + * @see _.toNumber + */ + toNumber(): number; + } + + interface LoDashExplicitWrapper { + /** + * @see _.toNumber + */ + toNumber(): LoDashExplicitWrapper; + } + + // toPlainObject + + interface LoDashStatic { + /** + * Converts value to a plain object flattening inherited enumerable properties of value to own properties + * of the plain object. + * + * @param value The value to convert. + * @return Returns the converted plain object. + */ + toPlainObject(value?: any): any; + } + + interface LoDashImplicitWrapper { + /** + * @see _.toPlainObject + */ + toPlainObject(): LoDashImplicitWrapper; + } + + interface LoDashExplicitWrapper { + /** + * @see _.toPlainObject + */ + toPlainObject(): LoDashExplicitWrapper; + } + + // toSafeInteger + + interface LoDashStatic { + /** + * Converts `value` to a safe integer. A safe integer can be compared and + * represented correctly. + * + * @category Lang + * @param value The value to convert. + * @returns Returns the converted integer. + * @example + * + * _.toSafeInteger(3); + * // => 3 + * + * _.toSafeInteger(Number.MIN_VALUE); + * // => 0 + * + * _.toSafeInteger(Infinity); + * // => 9007199254740991 + * + * _.toSafeInteger('3'); + * // => 3 + */ + toSafeInteger(value: any): number; + } + + interface LoDashImplicitWrapper { + /** + * @see _.toSafeInteger + */ + toSafeInteger(): number; + } + + interface LoDashExplicitWrapper { + /** + * @see _.toSafeInteger + */ + toSafeInteger(): LoDashExplicitWrapper; + } + + // toString + + interface LoDashStatic { + /** + * Converts `value` to a string if it's not one. An empty string is returned + * for `null` and `undefined` values. The sign of `-0` is preserved. + * + * @category Lang + * @param value The value to process. + * @returns Returns the string. + * @example + * + * _.toString(null); + * // => '' + * + * _.toString(-0); + * // => '-0' + * + * _.toString([1, 2, 3]); + * // => '1,2,3' + */ + toString(value: any): string; + } +} diff --git a/node_modules/@types/lodash/common/math.d.ts b/node_modules/@types/lodash/common/math.d.ts new file mode 100644 index 0000000..640fbc4 --- /dev/null +++ b/node_modules/@types/lodash/common/math.d.ts @@ -0,0 +1,532 @@ +import _ = require("../index"); +declare module "../index" { + // add + + interface LoDashStatic { + /** + * Adds two numbers. + * + * @param augend The first number to add. + * @param addend The second number to add. + * @return Returns the sum. + */ + add( + augend: number, + addend: number + ): number; + } + + interface LoDashImplicitWrapper { + /** + * @see _.add + */ + add(addend: number): number; + } + + interface LoDashExplicitWrapper { + /** + * @see _.add + */ + add(addend: number): LoDashExplicitWrapper; + } + + // ceil + + interface LoDashStatic { + /** + * Calculates n rounded up to precision. + * + * @param n The number to round up. + * @param precision The precision to round up to. + * @return Returns the rounded up number. + */ + ceil( + n: number, + precision?: number + ): number; + } + + interface LoDashImplicitWrapper { + /** + * @see _.ceil + */ + ceil(precision?: number): number; + } + + interface LoDashExplicitWrapper { + /** + * @see _.ceil + */ + ceil(precision?: number): LoDashExplicitWrapper; + } + + // divide + + interface LoDashStatic { + /** + * Divide two numbers. + * + * @param dividend The first number in a division. + * @param divisor The second number in a division. + * @returns Returns the quotient. + */ + divide( + dividend: number, + divisor: number + ): number; + } + + interface LoDashImplicitWrapper { + /** + * @see _.divide + */ + divide(divisor: number): number; + } + + interface LoDashExplicitWrapper { + /** + * @see _.divide + */ + divide(divisor: number): LoDashExplicitWrapper; + } + + // floor + + interface LoDashStatic { + /** + * Calculates n rounded down to precision. + * + * @param n The number to round down. + * @param precision The precision to round down to. + * @return Returns the rounded down number. + */ + floor( + n: number, + precision?: number + ): number; + } + + interface LoDashImplicitWrapper { + /** + * @see _.floor + */ + floor(precision?: number): number; + } + + interface LoDashExplicitWrapper { + /** + * @see _.floor + */ + floor(precision?: number): LoDashExplicitWrapper; + } + + // max + + interface LoDashStatic { + /** + * Computes the maximum value of `array`. If `array` is empty or falsey + * `undefined` is returned. + * + * @category Math + * @param array The array to iterate over. + * @returns Returns the maximum value. + */ + max( + collection: List | null | undefined + ): T | undefined; + } + + interface LoDashImplicitWrapper { + /** + * @see _.max + */ + max(this: LoDashImplicitWrapper | null | undefined>): T | undefined; + } + + interface LoDashExplicitWrapper { + /** + * @see _.max + */ + max(this: LoDashExplicitWrapper | null | undefined>): LoDashExplicitWrapper; + } + + // maxBy + + interface LoDashStatic { + /** + * This method is like `_.max` except that it accepts `iteratee` which is + * invoked for each element in `array` to generate the criterion by which + * the value is ranked. The iteratee is invoked with one argument: (value). + * + * @category Math + * @param array The array to iterate over. + * @param iteratee The iteratee invoked per element. + * @returns Returns the maximum value. + * @example + * + * var objects = [{ 'n': 1 }, { 'n': 2 }]; + * + * _.maxBy(objects, function(o) { return o.a; }); + * // => { 'n': 2 } + * + * // using the `_.property` iteratee shorthand + * _.maxBy(objects, 'n'); + * // => { 'n': 2 } + */ + maxBy( + collection: List | null | undefined, + iteratee?: ValueIteratee + ): T | undefined; + } + + interface LoDashImplicitWrapper { + /** + * @see _.maxBy + */ + maxBy( + this: LoDashImplicitWrapper | null | undefined>, + iteratee?: ValueIteratee + ): T | undefined; + } + + interface LoDashExplicitWrapper { + /** + * @see _.maxBy + */ + maxBy( + this: LoDashExplicitWrapper | null | undefined>, + iteratee?: ValueIteratee + ): LoDashExplicitWrapper; + } + + // mean + + interface LoDashStatic { + /** + * Computes the mean of the values in `array`. + * + * @category Math + * @param array The array to iterate over. + * @returns Returns the mean. + * @example + * + * _.mean([4, 2, 8, 6]); + * // => 5 + */ + mean( + collection: List | null | undefined + ): number; + } + + interface LoDashImplicitWrapper { + /** + * @see _.mean + */ + mean(): number; + } + + interface LoDashExplicitWrapper { + /** + * @see _.mean + */ + mean(): LoDashExplicitWrapper; + } + + // meanBy + + interface LoDashStatic { + /** + * Computes the mean of the provided propties of the objects in the `array` + * + * @category Math + * @param array The array to iterate over. + * @param iteratee The iteratee invoked per element. + * @returns Returns the mean. + * @example + * + * _.mean([{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }], 'n'); + * // => 5 + */ + meanBy( + collection: List | null | undefined, + iteratee?: ValueIteratee + ): number; + } + + interface LoDashImplicitWrapper { + /** + * @see _.meanBy + */ + meanBy( + this: LoDashImplicitWrapper | null | undefined>, + iteratee?: ValueIteratee + ): number; + } + + interface LoDashExplicitWrapper { + /** + * @see _.meanBy + */ + meanBy( + this: LoDashExplicitWrapper | null | undefined>, + iteratee?: ValueIteratee + ): LoDashExplicitWrapper; + } + + // min + + interface LoDashStatic { + /** + * Computes the minimum value of `array`. If `array` is empty or falsey + * `undefined` is returned. + * + * @category Math + * @param array The array to iterate over. + * @returns Returns the minimum value. + */ + min( + collection: List | null | undefined + ): T | undefined; + } + + interface LoDashImplicitWrapper { + /** + * @see _.min + */ + min(this: LoDashImplicitWrapper | null | undefined>): T | undefined; + } + + interface LoDashExplicitWrapper { + /** + * @see _.min + */ + min(this: LoDashExplicitWrapper | null | undefined>): LoDashExplicitWrapper; + } + + // minBy + + interface LoDashStatic { + /** + * This method is like `_.min` except that it accepts `iteratee` which is + * invoked for each element in `array` to generate the criterion by which + * the value is ranked. The iteratee is invoked with one argument: (value). + * + * @category Math + * @param array The array to iterate over. + * @param iteratee The iteratee invoked per element. + * @returns Returns the minimum value. + * @example + * + * var objects = [{ 'n': 1 }, { 'n': 2 }]; + * + * _.minBy(objects, function(o) { return o.a; }); + * // => { 'n': 1 } + * + * // using the `_.property` iteratee shorthand + * _.minBy(objects, 'n'); + * // => { 'n': 1 } + */ + minBy( + collection: List | null | undefined, + iteratee?: ValueIteratee + ): T | undefined; + } + + interface LoDashImplicitWrapper { + /** + * @see _.minBy + */ + minBy( + this: LoDashImplicitWrapper | null | undefined>, + iteratee?: ValueIteratee + ): T | undefined; + } + + interface LoDashExplicitWrapper { + /** + * @see _.minBy + */ + minBy( + this: LoDashExplicitWrapper | null | undefined>, + iteratee?: ValueIteratee + ): LoDashExplicitWrapper; + } + + // multiply + + interface LoDashStatic { + /** + * Multiply two numbers. + * @param multiplier The first number in a multiplication. + * @param multiplicand The second number in a multiplication. + * @returns Returns the product. + */ + multiply( + multiplier: number, + multiplicand: number + ): number; + } + + interface LoDashImplicitWrapper { + /** + * @see _.multiply + */ + multiply(multiplicand: number): number; + } + + interface LoDashExplicitWrapper { + /** + * @see _.multiply + */ + multiply(multiplicand: number): LoDashExplicitWrapper; + } + + // round + + interface LoDashStatic { + /** + * Calculates n rounded to precision. + * + * @param n The number to round. + * @param precision The precision to round to. + * @return Returns the rounded number. + */ + round( + n: number, + precision?: number + ): number; + } + + interface LoDashImplicitWrapper { + /** + * @see _.round + */ + round(precision?: number): number; + } + + interface LoDashExplicitWrapper { + /** + * @see _.round + */ + round(precision?: number): LoDashExplicitWrapper; + } + + // subtract + + interface LoDashStatic { + /** + * Subtract two numbers. + * + * @category Math + * @param minuend The first number in a subtraction. + * @param subtrahend The second number in a subtraction. + * @returns Returns the difference. + * @example + * + * _.subtract(6, 4); + * // => 2 + */ + subtract( + minuend: number, + subtrahend: number + ): number; + } + + interface LoDashImplicitWrapper { + /** + * @see _.subtract + */ + subtract( + subtrahend: number + ): number; + } + + interface LoDashExplicitWrapper { + /** + * @see _.subtract + */ + subtract( + subtrahend: number + ): LoDashExplicitWrapper; + } + + // sum + + interface LoDashStatic { + /** + * Computes the sum of the values in `array`. + * + * @category Math + * @param array The array to iterate over. + * @returns Returns the sum. + * @example + * + * _.sum([4, 2, 8, 6]); + * // => 20 + */ + sum(collection: List | null | undefined): number; + } + + interface LoDashImplicitWrapper { + /** + * @see _.sum + */ + sum(): number; + } + + interface LoDashExplicitWrapper { + /** + * @see _.sum + */ + sum(): LoDashExplicitWrapper; + } + + // sumBy + + interface LoDashStatic { + /** + * This method is like `_.sum` except that it accepts `iteratee` which is + * invoked for each element in `array` to generate the value to be summed. + * The iteratee is invoked with one argument: (value). + * + * @category Math + * @param array The array to iterate over. + * @param [iteratee=_.identity] The iteratee invoked per element. + * @returns Returns the sum. + * @example + * + * var objects = [{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }]; + * + * _.sumBy(objects, function(o) { return o.n; }); + * // => 20 + * + * // using the `_.property` iteratee shorthand + * _.sumBy(objects, 'n'); + * // => 20 + */ + sumBy( + collection: List | null | undefined, + iteratee?: ((value: T) => number) | string + ): number; + } + + interface LoDashImplicitWrapper { + /** + * @see _.sumBy + */ + sumBy( + this: LoDashImplicitWrapper | null | undefined>, + iteratee?: ((value: T) => number) | string + ): number; + } + + interface LoDashExplicitWrapper { + /** + * @see _.sumBy + */ + sumBy( + this: LoDashExplicitWrapper | null | undefined>, + iteratee?: ((value: T) => number) | string + ): LoDashExplicitWrapper; + } +} diff --git a/node_modules/@types/lodash/common/number.d.ts b/node_modules/@types/lodash/common/number.d.ts new file mode 100644 index 0000000..7da1cab --- /dev/null +++ b/node_modules/@types/lodash/common/number.d.ts @@ -0,0 +1,178 @@ +import _ = require("../index"); +declare module "../index" { + // clamp + + interface LoDashStatic { + /** + * Clamps `number` within the inclusive `lower` and `upper` bounds. + * + * @category Number + * @param number The number to clamp. + * @param [lower] The lower bound. + * @param upper The upper bound. + * @returns Returns the clamped number. + * @example + * + * _.clamp(-10, -5, 5); + * // => -5 + * + * _.clamp(10, -5, 5); + * // => 5 + */ + clamp( + number: number, + lower: number, + upper: number + ): number; + clamp( + number: number, + upper: number + ): number; + } + + interface LoDashImplicitWrapper { + /** + * @see _.clamp + */ + clamp( + lower: number, + upper: number + ): number; + clamp( + upper: number + ): number; + } + + interface LoDashExplicitWrapper { + /** + * @see _.clamp + */ + clamp( + lower: number, + upper: number + ): LoDashExplicitWrapper; + clamp( + upper: number + ): LoDashExplicitWrapper; + } + + // inRange + + interface LoDashStatic { + /** + * Checks if n is between start and up to but not including, end. If end is not specified it’s set to start + * with start then set to 0. + * + * @param n The number to check. + * @param start The start of the range. + * @param end The end of the range. + * @return Returns true if n is in the range, else false. + */ + inRange( + n: number, + start: number, + end?: number + ): boolean; + } + + interface LoDashImplicitWrapper { + /** + * @see _.inRange + */ + inRange( + start: number, + end?: number + ): boolean; + } + + interface LoDashExplicitWrapper { + /** + * @see _.inRange + */ + inRange( + start: number, + end?: number + ): LoDashExplicitWrapper; + } + + // random + + interface LoDashStatic { + /** + * Produces a random number between min and max (inclusive). If only one argument is provided a number between + * 0 and the given number is returned. If floating is true, or either min or max are floats, a floating-point + * number is returned instead of an integer. + * + * @param min The minimum possible value. + * @param max The maximum possible value. + * @param floating Specify returning a floating-point number. + * @return Returns the random number. + */ + random( + floating?: boolean + ): number; + + /** + * @see _.random + */ + random( + max: number, + floating?: boolean + ): number; + + /** + * @see _.random + */ + random( + min: number, + max: number, + floating?: boolean + ): number; + + /** + * Produces a random number between min and max (inclusive). If only one argument is provided a number between + * 0 and the given number is returned. If floating is true, or either min or max are floats, a floating-point + * number is returned instead of an integer. + * + * @param min The minimum possible value. + * @param index Not used in this overload. + * @param guard Enables use as an iteratee for methods like _.map. You should not pass this parameter directly in your code. + * @return Returns the random number. + */ + random( + min: number, + index: string | number, + guard: object + ): number; + } + + interface LoDashImplicitWrapper { + /** + * @see _.random + */ + random(floating?: boolean): number; + + /** + * @see _.random + */ + random( + max: number, + floating?: boolean + ): number; + } + + interface LoDashExplicitWrapper { + /** + * @see _.random + */ + random(floating?: boolean): LoDashExplicitWrapper; + + /** + * @see _.random + */ + random( + max: number, + floating?: boolean + ): LoDashExplicitWrapper; + } +} diff --git a/node_modules/@types/lodash/common/object.d.ts b/node_modules/@types/lodash/common/object.d.ts new file mode 100644 index 0000000..b136e94 --- /dev/null +++ b/node_modules/@types/lodash/common/object.d.ts @@ -0,0 +1,3905 @@ +import _ = require("../index"); +declare module "../index" { + // assign + + interface LoDashStatic { + /** + * Assigns own enumerable properties of source objects to the destination + * object. Source objects are applied from left to right. Subsequent sources + * overwrite property assignments of previous sources. + * + * **Note:** This method mutates `object` and is loosely based on + * [`Object.assign`](https://mdn.io/Object/assign). + * + * @category Object + * @param object The destination object. + * @param [sources] The source objects. + * @returns Returns `object`. + * @example + * + * function Foo() { + * this.c = 3; + * } + * + * function Bar() { + * this.e = 5; + * } + * + * Foo.prototype.d = 4; + * Bar.prototype.f = 6; + * + * _.assign({ 'a': 1 }, new Foo, new Bar); + * // => { 'a': 1, 'c': 3, 'e': 5 } + */ + assign( + object: TObject, + source: TSource + ): TObject & TSource; + + /** + * @see assign + */ + assign( + object: TObject, + source1: TSource1, + source2: TSource2 + ): TObject & TSource1 & TSource2; + + /** + * @see assign + */ + assign( + object: TObject, + source1: TSource1, + source2: TSource2, + source3: TSource3 + ): TObject & TSource1 & TSource2 & TSource3; + + /** + * @see assign + */ + assign( + object: TObject, + source1: TSource1, + source2: TSource2, + source3: TSource3, + source4: TSource4 + ): TObject & TSource1 & TSource2 & TSource3 & TSource4; + + /** + * @see _.assign + */ + assign(object: TObject): TObject; + + /** + * @see _.assign + */ + assign( + object: any, + ...otherArgs: any[] + ): any; + } + + interface LoDashImplicitWrapper { + /** + * @see _.assign + */ + assign( + source: TSource + ): LoDashImplicitWrapper; + + /** + * @see assign + */ + assign( + source1: TSource1, + source2: TSource2 + ): LoDashImplicitWrapper; + + /** + * @see assign + */ + assign( + source1: TSource1, + source2: TSource2, + source3: TSource3 + ): LoDashImplicitWrapper; + + /** + * @see assign + */ + assign( + source1: TSource1, + source2: TSource2, + source3: TSource3, + source4: TSource4 + ): LoDashImplicitWrapper; + + /** + * @see _.assign + */ + assign(): LoDashImplicitWrapper; + + /** + * @see _.assign + */ + assign(...otherArgs: any[]): LoDashImplicitWrapper; + } + + interface LoDashExplicitWrapper { + /** + * @see _.assign + */ + assign( + source: TSource + ): LoDashExplicitWrapper; + + /** + * @see assign + */ + assign( + source1: TSource1, + source2: TSource2 + ): LoDashExplicitWrapper; + + /** + * @see assign + */ + assign( + source1: TSource1, + source2: TSource2, + source3: TSource3 + ): LoDashExplicitWrapper; + + /** + * @see assign + */ + assign( + source1: TSource1, + source2: TSource2, + source3: TSource3, + source4: TSource4 + ): LoDashExplicitWrapper; + + /** + * @see _.assign + */ + assign(): LoDashExplicitWrapper; + + /** + * @see _.assign + */ + assign(...otherArgs: any[]): LoDashExplicitWrapper; + } + + // assignIn + + interface LoDashStatic { + /** + * This method is like `_.assign` except that it iterates over own and + * inherited source properties. + * + * **Note:** This method mutates `object`. + * + * @alias extend + * @category Object + * @param object The destination object. + * @param [sources] The source objects. + * @returns Returns `object`. + * @example + * + * function Foo() { + * this.b = 2; + * } + * + * function Bar() { + * this.d = 4; + * } + * + * Foo.prototype.c = 3; + * Bar.prototype.e = 5; + * + * _.assignIn({ 'a': 1 }, new Foo, new Bar); + * // => { 'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5 } + */ + assignIn( + object: TObject, + source: TSource + ): TObject & TSource; + + /** + * @see assignIn + */ + assignIn( + object: TObject, + source1: TSource1, + source2: TSource2 + ): TObject & TSource1 & TSource2; + + /** + * @see assignIn + */ + assignIn( + object: TObject, + source1: TSource1, + source2: TSource2, + source3: TSource3 + ): TObject & TSource1 & TSource2 & TSource3; + + /** + * @see assignIn + */ + assignIn( + object: TObject, + source1: TSource1, + source2: TSource2, + source3: TSource3, + source4: TSource4 + ): TObject & TSource1 & TSource2 & TSource3 & TSource4; + + /** + * @see _.assignIn + */ + assignIn(object: TObject): TObject; + + /** + * @see _.assignIn + */ + assignIn( + object: any, + ...otherArgs: any[] + ): TResult; + } + + interface LoDashImplicitWrapper { + /** + * @see _.assignIn + */ + assignIn( + source: TSource + ): LoDashImplicitWrapper; + + /** + * @see assignIn + */ + assignIn( + source1: TSource1, + source2: TSource2 + ): LoDashImplicitWrapper; + + /** + * @see assignIn + */ + assignIn( + source1: TSource1, + source2: TSource2, + source3: TSource3 + ): LoDashImplicitWrapper; + + /** + * @see assignIn + */ + assignIn( + source1: TSource1, + source2: TSource2, + source3: TSource3, + source4: TSource4 + ): LoDashImplicitWrapper; + + /** + * @see _.assignIn + */ + assignIn(): LoDashImplicitWrapper; + + /** + * @see _.assignIn + */ + assignIn(...otherArgs: any[]): LoDashImplicitWrapper; + } + + interface LoDashExplicitWrapper { + /** + * @see _.assignIn + */ + assignIn( + source: TSource + ): LoDashExplicitWrapper; + + /** + * @see assignIn + */ + assignIn( + source1: TSource1, + source2: TSource2 + ): LoDashExplicitWrapper; + + /** + * @see assignIn + */ + assignIn( + source1: TSource1, + source2: TSource2, + source3: TSource3 + ): LoDashExplicitWrapper; + + /** + * @see assignIn + */ + assignIn( + source1: TSource1, + source2: TSource2, + source3: TSource3, + source4: TSource4 + ): LoDashExplicitWrapper; + + /** + * @see _.assignIn + */ + assignIn(): LoDashExplicitWrapper; + + /** + * @see _.assignIn + */ + assignIn(...otherArgs: any[]): LoDashExplicitWrapper; + } + + // assignInWith + + type AssignCustomizer = (objectValue: any, sourceValue: any, key?: string, object?: {}, source?: {}) => any; + + interface LoDashStatic { + /** + * This method is like `_.assignIn` except that it accepts `customizer` which + * is invoked to produce the assigned values. If `customizer` returns `undefined` + * assignment is handled by the method instead. The `customizer` is invoked + * with five arguments: (objValue, srcValue, key, object, source). + * + * **Note:** This method mutates `object`. + * + * @alias extendWith + * @category Object + * @param object The destination object. + * @param sources The source objects. + * @param [customizer] The function to customize assigned values. + * @returns Returns `object`. + * @example + * + * function customizer(objValue, srcValue) { + * return _.isUndefined(objValue) ? srcValue : objValue; + * } + * + * var defaults = _.partialRight(_.assignInWith, customizer); + * + * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); + * // => { 'a': 1, 'b': 2 } + */ + assignInWith( + object: TObject, + source: TSource, + customizer: AssignCustomizer + ): TObject & TSource; + + /** + * @see assignInWith + */ + assignInWith( + object: TObject, + source1: TSource1, + source2: TSource2, + customizer: AssignCustomizer + ): TObject & TSource1 & TSource2; + + /** + * @see assignInWith + */ + assignInWith( + object: TObject, + source1: TSource1, + source2: TSource2, + source3: TSource3, + customizer: AssignCustomizer + ): TObject & TSource1 & TSource2 & TSource3; + + /** + * @see assignInWith + */ + assignInWith( + object: TObject, + source1: TSource1, + source2: TSource2, + source3: TSource3, + source4: TSource4, + customizer: AssignCustomizer + ): TObject & TSource1 & TSource2 & TSource3 & TSource4; + + /** + * @see _.assignInWith + */ + assignInWith(object: TObject): TObject; + + /** + * @see _.assignInWith + */ + assignInWith( + object: any, + ...otherArgs: any[] + ): TResult; + } + + interface LoDashImplicitWrapper { + /** + * @see _.assignInWith + */ + assignInWith( + source: TSource, + customizer: AssignCustomizer + ): LoDashImplicitWrapper; + + /** + * @see assignInWith + */ + assignInWith( + source1: TSource1, + source2: TSource2, + customizer: AssignCustomizer + ): LoDashImplicitWrapper; + + /** + * @see assignInWith + */ + assignInWith( + source1: TSource1, + source2: TSource2, + source3: TSource3, + customizer: AssignCustomizer + ): LoDashImplicitWrapper; + + /** + * @see assignInWith + */ + assignInWith( + source1: TSource1, + source2: TSource2, + source3: TSource3, + source4: TSource4, + customizer: AssignCustomizer + ): LoDashImplicitWrapper; + + /** + * @see _.assignInWith + */ + assignInWith(): LoDashImplicitWrapper; + + /** + * @see _.assignInWith + */ + assignInWith(...otherArgs: any[]): LoDashImplicitWrapper; + } + + interface LoDashExplicitWrapper { + /** + * @see _.assignInWith + */ + assignInWith( + source: TSource, + customizer: AssignCustomizer + ): LoDashExplicitWrapper; + + /** + * @see assignInWith + */ + assignInWith( + source1: TSource1, + source2: TSource2, + customizer: AssignCustomizer + ): LoDashExplicitWrapper; + + /** + * @see assignInWith + */ + assignInWith( + source1: TSource1, + source2: TSource2, + source3: TSource3, + customizer: AssignCustomizer + ): LoDashExplicitWrapper; + + /** + * @see assignInWith + */ + assignInWith( + source1: TSource1, + source2: TSource2, + source3: TSource3, + source4: TSource4, + customizer: AssignCustomizer + ): LoDashExplicitWrapper; + + /** + * @see _.assignInWith + */ + assignInWith(): LoDashExplicitWrapper; + + /** + * @see _.assignInWith + */ + assignInWith(...otherArgs: any[]): LoDashExplicitWrapper; + } + + // assignWith + + interface LoDashStatic { + /** + * This method is like `_.assign` except that it accepts `customizer` which + * is invoked to produce the assigned values. If `customizer` returns `undefined` + * assignment is handled by the method instead. The `customizer` is invoked + * with five arguments: (objValue, srcValue, key, object, source). + * + * **Note:** This method mutates `object`. + * + * @category Object + * @param object The destination object. + * @param sources The source objects. + * @param [customizer] The function to customize assigned values. + * @returns Returns `object`. + * @example + * + * function customizer(objValue, srcValue) { + * return _.isUndefined(objValue) ? srcValue : objValue; + * } + * + * var defaults = _.partialRight(_.assignWith, customizer); + * + * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); + * // => { 'a': 1, 'b': 2 } + */ + assignWith( + object: TObject, + source: TSource, + customizer: AssignCustomizer + ): TObject & TSource; + + /** + * @see assignWith + */ + assignWith( + object: TObject, + source1: TSource1, + source2: TSource2, + customizer: AssignCustomizer + ): TObject & TSource1 & TSource2; + + /** + * @see assignWith + */ + assignWith( + object: TObject, + source1: TSource1, + source2: TSource2, + source3: TSource3, + customizer: AssignCustomizer + ): TObject & TSource1 & TSource2 & TSource3; + + /** + * @see assignWith + */ + assignWith( + object: TObject, + source1: TSource1, + source2: TSource2, + source3: TSource3, + source4: TSource4, + customizer: AssignCustomizer + ): TObject & TSource1 & TSource2 & TSource3 & TSource4; + + /** + * @see _.assignWith + */ + assignWith(object: TObject): TObject; + + /** + * @see _.assignWith + */ + assignWith( + object: any, + ...otherArgs: any[] + ): TResult; + } + + interface LoDashImplicitWrapper { + /** + * @see _.assignWith + */ + assignWith( + source: TSource, + customizer: AssignCustomizer + ): LoDashImplicitWrapper; + + /** + * @see assignWith + */ + assignWith( + source1: TSource1, + source2: TSource2, + customizer: AssignCustomizer + ): LoDashImplicitWrapper; + + /** + * @see assignWith + */ + assignWith( + source1: TSource1, + source2: TSource2, + source3: TSource3, + customizer: AssignCustomizer + ): LoDashImplicitWrapper; + + /** + * @see assignWith + */ + assignWith( + source1: TSource1, + source2: TSource2, + source3: TSource3, + source4: TSource4, + customizer: AssignCustomizer + ): LoDashImplicitWrapper; + + /** + * @see _.assignWith + */ + assignWith(): LoDashImplicitWrapper; + + /** + * @see _.assignWith + */ + assignWith(...otherArgs: any[]): LoDashImplicitWrapper; + } + + interface LoDashExplicitWrapper { + /** + * @see _.assignWith + */ + assignWith( + source: TSource, + customizer: AssignCustomizer + ): LoDashExplicitWrapper; + + /** + * @see assignWith + */ + assignWith( + source1: TSource1, + source2: TSource2, + customizer: AssignCustomizer + ): LoDashExplicitWrapper; + + /** + * @see assignWith + */ + assignWith( + source1: TSource1, + source2: TSource2, + source3: TSource3, + customizer: AssignCustomizer + ): LoDashExplicitWrapper; + + /** + * @see assignWith + */ + assignWith( + source1: TSource1, + source2: TSource2, + source3: TSource3, + source4: TSource4, + customizer: AssignCustomizer + ): LoDashExplicitWrapper; + + /** + * @see _.assignWith + */ + assignWith(): LoDashExplicitWrapper; + + /** + * @see _.assignWith + */ + assignWith(...otherArgs: any[]): LoDashExplicitWrapper; + } + + // at + + interface LoDashStatic { + /** + * Creates an array of elements corresponding to the given keys, or indexes, of collection. Keys may be + * specified as individual arguments or as arrays of keys. + * + * @param object The object to iterate over. + * @param props The property names or indexes of elements to pick, specified individually or in arrays. + * @return Returns the new array of picked elements. + */ + at( + object: List | Dictionary | NumericDictionary | null | undefined, + ...props: PropertyPath[] + ): T[]; + + /** + * @see _.at + */ + at( + object: T | null | undefined, + ...props: Array> + ): Array; + } + + interface LoDashImplicitWrapper { + /** + * @see _.at + */ + at( + this: LoDashImplicitWrapper | Dictionary | NumericDictionary | null | undefined>, + ...props: PropertyPath[] + ): LoDashImplicitWrapper; + + /** + * @see _.at + */ + at( + this: LoDashImplicitWrapper, + ...props: Array> + ): LoDashImplicitWrapper>; + } + + interface LoDashExplicitWrapper { + /** + * @see _.at + */ + at( + this: LoDashExplicitWrapper | Dictionary | NumericDictionary | null | undefined>, + ...props: PropertyPath[] + ): LoDashExplicitWrapper; + + /** + * @see _.at + */ + at( + this: LoDashExplicitWrapper, + ...props: Array> + ): LoDashExplicitWrapper>; + } + + // create + + interface LoDashStatic { + /** + * Creates an object that inherits from the given prototype object. If a properties object is provided its own + * enumerable properties are assigned to the created object. + * + * @param prototype The object to inherit from. + * @param properties The properties to assign to the object. + * @return Returns the new object. + */ + create( + prototype: T, + properties?: U + ): T & U; + } + + interface LoDashImplicitWrapper { + /** + * @see _.create + */ + create(properties?: U): LoDashImplicitWrapper; + } + + interface LoDashExplicitWrapper { + /** + * @see _.create + */ + create(properties?: U): LoDashExplicitWrapper; + } + + // defaults + + interface LoDashStatic { + /** + * Assigns own enumerable properties of source object(s) to the destination object for all destination + * properties that resolve to undefined. Once a property is set, additional values of the same property are + * ignored. + * + * Note: This method mutates object. + * + * @param object The destination object. + * @param sources The source objects. + * @return The destination object. + */ + defaults( + object: TObject, + source: TSource + ): TSource & TObject; + + /** + * @see _.defaults + */ + defaults( + object: TObject, + source1: TSource1, + source2: TSource2 + ): TSource2 & TSource1 & TObject; + + /** + * @see _.defaults + */ + defaults( + object: TObject, + source1: TSource1, + source2: TSource2, + source3: TSource3 + ): TSource3 & TSource2 & TSource1 & TObject; + + /** + * @see _.defaults + */ + defaults( + object: TObject, + source1: TSource1, + source2: TSource2, + source3: TSource3, + source4: TSource4 + ): TSource4 & TSource3 & TSource2 & TSource1 & TObject; + + /** + * @see _.defaults + */ + defaults(object: TObject): TObject; + + /** + * @see _.defaults + */ + defaults( + object: any, + ...sources: any[] + ): any; + } + + interface LoDashImplicitWrapper { + /** + * @see _.defaults + */ + defaults( + source: TSource + ): LoDashImplicitWrapper; + + /** + * @see _.defaults + */ + defaults( + source1: TSource1, + source2: TSource2 + ): LoDashImplicitWrapper; + + /** + * @see _.defaults + */ + defaults( + source1: TSource1, + source2: TSource2, + source3: TSource3 + ): LoDashImplicitWrapper; + + /** + * @see _.defaults + */ + defaults( + source1: TSource1, + source2: TSource2, + source3: TSource3, + source4: TSource4 + ): LoDashImplicitWrapper; + + /** + * @see _.defaults + */ + defaults(): LoDashImplicitWrapper; + + /** + * @see _.defaults + */ + defaults(...sources: any[]): LoDashImplicitWrapper; + } + + interface LoDashExplicitWrapper { + /** + * @see _.defaults + */ + defaults( + source: TSource + ): LoDashExplicitWrapper; + + /** + * @see _.defaults + */ + defaults( + source1: TSource1, + source2: TSource2 + ): LoDashExplicitWrapper; + + /** + * @see _.defaults + */ + defaults( + source1: TSource1, + source2: TSource2, + source3: TSource3 + ): LoDashExplicitWrapper; + + /** + * @see _.defaults + */ + defaults( + source1: TSource1, + source2: TSource2, + source3: TSource3, + source4: TSource4 + ): LoDashExplicitWrapper; + + /** + * @see _.defaults + */ + defaults(): LoDashExplicitWrapper; + + /** + * @see _.defaults + */ + defaults(...sources: any[]): LoDashExplicitWrapper; + } + + // defaultsDeep + + interface LoDashStatic { + /** + * This method is like _.defaults except that it recursively assigns default properties. + * @param object The destination object. + * @param sources The source objects. + * @return Returns object. + **/ + defaultsDeep( + object: any, + ...sources: any[]): any; + } + + interface LoDashImplicitWrapper { + /** + * @see _.defaultsDeep + **/ + defaultsDeep(...sources: any[]): LoDashImplicitWrapper; + } + + interface LoDashExplicitWrapper { + /** + * @see _.defaultsDeep + **/ + defaultsDeep(...sources: any[]): LoDashExplicitWrapper; + } + + // entries + + interface LoDashStatic { + /** + * @see _.toPairs + */ + entries(object?: Dictionary | NumericDictionary): Array<[string, T]>; + + /** + * @see _.toPairs + */ + entries(object?: object): Array<[string, any]>; + } + + interface LoDashImplicitWrapper { + /** + * @see _.toPairs + */ + entries(this: LoDashImplicitWrapper | NumericDictionary>): LoDashImplicitWrapper>; + + /** + * @see _.toPairs + */ + entries(): LoDashImplicitWrapper>; + } + + interface LoDashExplicitWrapper { + /** + * @see _.toPairs + */ + entries(this: LoDashExplicitWrapper | NumericDictionary>): LoDashExplicitWrapper>; + + /** + * @see _.toPairs + */ + entries(): LoDashExplicitWrapper>; + } + + // entriesIn + + interface LoDashStatic { + /** + * @see _.entriesIn + */ + entriesIn(object?: Dictionary | NumericDictionary): Array<[string, T]>; + + /** + * @see _.entriesIn + */ + entriesIn(object?: object): Array<[string, any]>; + } + + interface LoDashImplicitWrapper { + /** + * @see _.entriesIn + */ + entriesIn(this: LoDashImplicitWrapper | NumericDictionary>): LoDashImplicitWrapper>; + + /** + * @see _.entriesIn + */ + entriesIn(): LoDashImplicitWrapper>; + } + + interface LoDashExplicitWrapper { + /** + * @see _.entriesIn + */ + entriesIn(this: LoDashExplicitWrapper | NumericDictionary>): LoDashExplicitWrapper>; + + /** + * @see _.entriesIn + */ + entriesIn(): LoDashExplicitWrapper>; + } + + // extend + + interface LoDashStatic { + /** + * @see _.extend + */ + extend( + object: TObject, + source: TSource + ): TObject & TSource; + + /** + * @see _.extend + */ + extend( + object: TObject, + source1: TSource1, + source2: TSource2 + ): TObject & TSource1 & TSource2; + + /** + * @see _.extend + */ + extend( + object: TObject, + source1: TSource1, + source2: TSource2, + source3: TSource3 + ): TObject & TSource1 & TSource2 & TSource3; + + /** + * @see _.extend + */ + extend( + object: TObject, + source1: TSource1, + source2: TSource2, + source3: TSource3, + source4: TSource4 + ): TObject & TSource1 & TSource2 & TSource3 & TSource4; + + /** + * @see _.extend + */ + extend(object: TObject): TObject; + + /** + * @see _.extend + */ + extend( + object: any, + ...otherArgs: any[] + ): TResult; + } + + interface LoDashImplicitWrapper { + /** + * @see _.extend + */ + extend( + source: TSource + ): LoDashImplicitWrapper; + + /** + * @see _.extend + */ + extend( + source1: TSource1, + source2: TSource2 + ): LoDashImplicitWrapper; + + /** + * @see _.extend + */ + extend( + source1: TSource1, + source2: TSource2, + source3: TSource3 + ): LoDashImplicitWrapper; + + /** + * @see _.extend + */ + extend( + source1: TSource1, + source2: TSource2, + source3: TSource3, + source4: TSource4 + ): LoDashImplicitWrapper; + + /** + * @see _.extend + */ + extend(): LoDashImplicitWrapper; + + /** + * @see _.extend + */ + extend(...otherArgs: any[]): LoDashImplicitWrapper; + } + + interface LoDashExplicitWrapper { + /** + * @see _.extend + */ + extend( + source: TSource + ): LoDashExplicitWrapper; + + /** + * @see _.extend + */ + extend( + source1: TSource1, + source2: TSource2 + ): LoDashExplicitWrapper; + + /** + * @see _.extend + */ + extend( + source1: TSource1, + source2: TSource2, + source3: TSource3 + ): LoDashExplicitWrapper; + + /** + * @see _.extend + */ + extend( + source1: TSource1, + source2: TSource2, + source3: TSource3, + source4: TSource4 + ): LoDashExplicitWrapper; + + /** + * @see _.extend + */ + extend(): LoDashExplicitWrapper; + + /** + * @see _.extend + */ + extend(...otherArgs: any[]): LoDashExplicitWrapper; + } + + // extendWith + + interface LoDashStatic { + /** + * @see _.extendWith + */ + extendWith( + object: TObject, + source: TSource, + customizer: AssignCustomizer + ): TObject & TSource; + + /** + * @see _.extendWith + */ + extendWith( + object: TObject, + source1: TSource1, + source2: TSource2, + customizer: AssignCustomizer + ): TObject & TSource1 & TSource2; + + /** + * @see _.extendWith + */ + extendWith( + object: TObject, + source1: TSource1, + source2: TSource2, + source3: TSource3, + customizer: AssignCustomizer + ): TObject & TSource1 & TSource2 & TSource3; + + /** + * @see _.extendWith + */ + extendWith( + object: TObject, + source1: TSource1, + source2: TSource2, + source3: TSource3, + source4: TSource4, + customizer: AssignCustomizer + ): TObject & TSource1 & TSource2 & TSource3 & TSource4; + + /** + * @see _.extendWith + */ + extendWith(object: TObject): TObject; + + /** + * @see _.extendWith + */ + extendWith( + object: any, + ...otherArgs: any[] + ): TResult; + } + + interface LoDashImplicitWrapper { + /** + * @see _.extendWith + */ + extendWith( + source: TSource, + customizer: AssignCustomizer + ): LoDashImplicitWrapper; + + /** + * @see _.extendWith + */ + extendWith( + source1: TSource1, + source2: TSource2, + customizer: AssignCustomizer + ): LoDashImplicitWrapper; + + /** + * @see _.extendWith + */ + extendWith( + source1: TSource1, + source2: TSource2, + source3: TSource3, + customizer: AssignCustomizer + ): LoDashImplicitWrapper; + + /** + * @see _.extendWith + */ + extendWith( + source1: TSource1, + source2: TSource2, + source3: TSource3, + source4: TSource4, + customizer: AssignCustomizer + ): LoDashImplicitWrapper; + + /** + * @see _.extendWith + */ + extendWith(): LoDashImplicitWrapper; + + /** + * @see _.extendWith + */ + extendWith(...otherArgs: any[]): LoDashImplicitWrapper; + } + + interface LoDashExplicitWrapper { + /** + * @see _.extendWith + */ + extendWith( + source: TSource, + customizer: AssignCustomizer + ): LoDashExplicitWrapper; + + /** + * @see _.extendWith + */ + extendWith( + source1: TSource1, + source2: TSource2, + customizer: AssignCustomizer + ): LoDashExplicitWrapper; + + /** + * @see _.extendWith + */ + extendWith( + source1: TSource1, + source2: TSource2, + source3: TSource3, + customizer: AssignCustomizer + ): LoDashExplicitWrapper; + + /** + * @see _.extendWith + */ + extendWith( + source1: TSource1, + source2: TSource2, + source3: TSource3, + source4: TSource4, + customizer: AssignCustomizer + ): LoDashExplicitWrapper; + + /** + * @see _.extendWith + */ + extendWith(): LoDashExplicitWrapper; + + /** + * @see _.extendWith + */ + extendWith(...otherArgs: any[]): LoDashExplicitWrapper; + } + + // findKey + + interface LoDashStatic { + /** + * This method is like _.find except that it returns the key of the first element predicate returns truthy for + * instead of the element itself. + * + * @param object The object to search. + * @param predicate The function invoked per iteration. + * @return Returns the key of the matched element, else undefined. + */ + findKey( + object: T | null | undefined, + predicate?: ObjectIteratee + ): string | undefined; + } + + interface LoDashImplicitWrapper { + /** + * @see _.findKey + */ + findKey( + this: LoDashImplicitWrapper, + predicate?: ObjectIteratee + ): string | undefined; + } + + interface LoDashExplicitWrapper { + /** + * @see _.findKey + */ + findKey( + this: LoDashExplicitWrapper, + predicate?: ObjectIteratee + ): LoDashExplicitWrapper; + } + + // findLastKey + + interface LoDashStatic { + /** + * This method is like _.findKey except that it iterates over elements of a collection in the opposite order. + * + * @param object The object to search. + * @param predicate The function invoked per iteration. + * @return Returns the key of the matched element, else undefined. + */ + findLastKey( + object: T | null | undefined, + predicate?: ObjectIteratee + ): string | undefined; + } + + interface LoDashImplicitWrapper { + /** + * @see _.findLastKey + */ + findLastKey( + this: LoDashImplicitWrapper, + predicate?: ObjectIteratee + ): string | undefined; + } + + interface LoDashExplicitWrapper { + /** + * @see _.findLastKey + */ + findLastKey( + this: LoDashExplicitWrapper, + predicate?: ObjectIteratee + ): LoDashExplicitWrapper; + } + + // forIn + + interface LoDashStatic { + /** + * Iterates over own and inherited enumerable properties of an object invoking iteratee for each property. The + * iteratee is invoked with three arguments: (value, key, object). Iteratee functions may + * exit iteration early by explicitly returning false. + * + * @param object The object to iterate over. + * @param iteratee The function invoked per iteration. + * @return Returns object. + */ + forIn( + object: T, + iteratee?: ObjectIterator + ): T; + + /** + * @see _.forIn + */ + forIn( + object: T | null | undefined, + iteratee?: ObjectIterator + ): T | null | undefined; + } + + interface LoDashWrapper { + /** + * @see _.forIn + */ + forIn( + this: LoDashWrapper, + iteratee?: ObjectIterator + ): this; + } + + // forInRight + + interface LoDashStatic { + /** + * This method is like _.forIn except that it iterates over properties of object in the opposite order. + * + * @param object The object to iterate over. + * @param iteratee The function invoked per iteration. + * @return Returns object. + */ + forInRight( + object: T, + iteratee?: ObjectIterator + ): T; + + /** + * @see _.forInRight + */ + forInRight( + object: T | null | undefined, + iteratee?: ObjectIterator + ): T | null | undefined; + } + + interface LoDashWrapper { + /** + * @see _.forInRight + */ + forInRight( + this: LoDashWrapper, + iteratee?: ObjectIterator + ): this; + } + + // forOwn + + interface LoDashStatic { + /** + * Iterates over own enumerable properties of an object invoking iteratee for each property. The iteratee is + * invoked with three arguments: (value, key, object). Iteratee functions may exit + * iteration early by explicitly returning false. + * + * @param object The object to iterate over. + * @param iteratee The function invoked per iteration. + * @return Returns object. + */ + forOwn( + object: T, + iteratee?: ObjectIterator + ): T; + + /** + * @see _.forOwn + */ + forOwn( + object: T | null | undefined, + iteratee?: ObjectIterator + ): T | null | undefined; + } + + interface LoDashWrapper { + /** + * @see _.forOwn + */ + forOwn( + this: LoDashWrapper, + iteratee?: ObjectIterator + ): this; + } + + // forOwnRight + + interface LoDashStatic { + /** + * This method is like _.forOwn except that it iterates over properties of object in the opposite order. + * + * @param object The object to iterate over. + * @param iteratee The function invoked per iteration. + * @return Returns object. + */ + forOwnRight( + object: T, + iteratee?: ObjectIterator + ): T; + + /** + * @see _.forOwnRight + */ + forOwnRight( + object: T | null | undefined, + iteratee?: ObjectIterator + ): T | null | undefined; + } + + interface LoDashWrapper { + /** + * @see _.forOwnRight + */ + forOwnRight( + this: LoDashWrapper, + iteratee?: ObjectIterator + ): this; + } + + // functions + + interface LoDashStatic { + /** + * Creates an array of function property names from own enumerable properties + * of `object`. + * + * @category Object + * @param object The object to inspect. + * @returns Returns the new array of property names. + * @example + * + * function Foo() { + * this.a = _.constant('a'); + * this.b = _.constant('b'); + * } + * + * Foo.prototype.c = _.constant('c'); + * + * _.functions(new Foo); + * // => ['a', 'b'] + */ + functions(object: any): string[]; + } + + interface LoDashImplicitWrapper { + /** + * @see _.functions + */ + functions(): LoDashImplicitWrapper; + } + + interface LoDashExplicitWrapper { + /** + * @see _.functions + */ + functions(): LoDashExplicitWrapper; + } + + // functionsIn + + interface LoDashStatic { + /** + * Creates an array of function property names from own and inherited + * enumerable properties of `object`. + * + * @category Object + * @param object The object to inspect. + * @returns Returns the new array of property names. + * @example + * + * function Foo() { + * this.a = _.constant('a'); + * this.b = _.constant('b'); + * } + * + * Foo.prototype.c = _.constant('c'); + * + * _.functionsIn(new Foo); + * // => ['a', 'b', 'c'] + */ + functionsIn(object: any): string[]; + } + + interface LoDashImplicitWrapper { + /** + * @see _.functionsIn + */ + functionsIn(): LoDashImplicitWrapper; + } + + interface LoDashExplicitWrapper { + /** + * @see _.functionsIn + */ + functionsIn(): LoDashExplicitWrapper; + } + + // get + + interface LoDashStatic { + /** + * Gets the property value at path of object. If the resolved value is undefined the defaultValue is used + * in its place. + * + * @param object The object to query. + * @param path The path of the property to get. + * @param defaultValue The value returned if the resolved value is undefined. + * @return Returns the resolved value. + */ + get( + object: TObject, + path: TKey | [TKey] + ): TObject[TKey]; + + /** + * @see _.get + */ + get( + object: TObject | null | undefined, + path: TKey | [TKey] + ): TObject[TKey] | undefined; + + /** + * @see _.get + */ + get( + object: TObject | null | undefined, + path: TKey | [TKey], + defaultValue: TDefault + ): TObject[TKey] | TDefault; + + /** + * @see _.get + */ + get( + object: NumericDictionary, + path: number + ): T; + + /** + * @see _.get + */ + get( + object: NumericDictionary | null | undefined, + path: number + ): T | undefined; + + /** + * @see _.get + */ + get( + object: NumericDictionary | null | undefined, + path: number, + defaultValue: TDefault + ): T | TDefault; + + /** + * @see _.get + */ + get( + object: null | undefined, + path: PropertyPath, + defaultValue: TDefault + ): TDefault; + + /** + * @see _.get + */ + get( + object: null | undefined, + path: PropertyPath + ): undefined; + + /** + * @see _.get + */ + get( + object: any, + path: PropertyPath, + defaultValue?: any + ): any; + } + + interface LoDashImplicitWrapper { + /** + * @see _.get + */ + get( + path: TKey | [TKey] + ): TValue[TKey]; + + /** + * @see _.get + */ + get( + this: LoDashImplicitWrapper, + path: TKey | [TKey], + ): TObject[TKey] | undefined; + + /** + * @see _.get + */ + get( + this: LoDashImplicitWrapper, + path: TKey | [TKey], + defaultValue: TDefault + ): TObject[TKey] | TDefault; + + /** + * @see _.get + */ + get( + this: LoDashImplicitWrapper>, + path: number + ): T; + + /** + * @see _.get + */ + get( + this: LoDashImplicitWrapper | null | undefined>, + path: number + ): T | undefined; + + /** + * @see _.get + */ + get( + this: LoDashImplicitWrapper | null | undefined>, + path: number, + defaultValue: TDefault + ): T | TDefault; + + /** + * @see _.get + */ + get( + this: LoDashImplicitWrapper, + path: PropertyPath, + defaultValue: TDefault + ): TDefault; + + /** + * @see _.get + */ + get( + this: LoDashImplicitWrapper, + path: PropertyPath + ): undefined; + + /** + * @see _.get + */ + get( + path: PropertyPath, + defaultValue?: any + ): any; + } + + interface LoDashExplicitWrapper { + /** + * @see _.get + */ + get( + path: TKey | [TKey] + ): LoDashExplicitWrapper; + + /** + * @see _.get + */ + get( + this: LoDashExplicitWrapper, + path: TKey | [TKey], + ): LoDashExplicitWrapper; + + /** + * @see _.get + */ + get( + this: LoDashExplicitWrapper, + path: TKey | [TKey], + defaultValue: TDefault + ): LoDashExplicitWrapper; + + /** + * @see _.get + */ + get( + this: LoDashExplicitWrapper>, + path: number + ): LoDashExplicitWrapper; + + /** + * @see _.get + */ + get( + this: LoDashExplicitWrapper | null | undefined>, + path: number + ): LoDashExplicitWrapper; + + /** + * @see _.get + */ + get( + this: LoDashExplicitWrapper | null | undefined>, + path: number, + defaultValue: TDefault + ): LoDashExplicitWrapper; + + /** + * @see _.get + */ + get( + this: LoDashExplicitWrapper, + path: PropertyPath, + defaultValue: TDefault + ): LoDashExplicitWrapper; + + /** + * @see _.get + */ + get( + this: LoDashExplicitWrapper, + path: PropertyPath + ): LoDashExplicitWrapper; + + /** + * @see _.get + */ + get( + path: PropertyPath, + defaultValue?: any + ): LoDashExplicitWrapper; + } + + // has + + interface LoDashStatic { + /** + * Checks if `path` is a direct property of `object`. + * + * @category Object + * @param object The object to query. + * @param path The path to check. + * @returns Returns `true` if `path` exists, else `false`. + * @example + * + * var object = { 'a': { 'b': { 'c': 3 } } }; + * var other = _.create({ 'a': _.create({ 'b': _.create({ 'c': 3 }) }) }); + * + * _.has(object, 'a'); + * // => true + * + * _.has(object, 'a.b.c'); + * // => true + * + * _.has(object, ['a', 'b', 'c']); + * // => true + * + * _.has(other, 'a'); + * // => false + */ + has( + object: T, + path: PropertyPath + ): boolean; + } + + interface LoDashImplicitWrapper { + /** + * @see _.has + */ + has(path: PropertyPath): boolean; + } + + interface LoDashExplicitWrapper { + /** + * @see _.has + */ + has(path: PropertyPath): LoDashExplicitWrapper; + } + + // hasIn + + interface LoDashStatic { + /** + * Checks if `path` is a direct or inherited property of `object`. + * + * @category Object + * @param object The object to query. + * @param path The path to check. + * @returns Returns `true` if `path` exists, else `false`. + * @example + * + * var object = _.create({ 'a': _.create({ 'b': _.create({ 'c': 3 }) }) }); + * + * _.hasIn(object, 'a'); + * // => true + * + * _.hasIn(object, 'a.b.c'); + * // => true + * + * _.hasIn(object, ['a', 'b', 'c']); + * // => true + * + * _.hasIn(object, 'b'); + * // => false + */ + hasIn( + object: T, + path: PropertyPath + ): boolean; + } + + interface LoDashImplicitWrapper { + /** + * @see _.hasIn + */ + hasIn(path: PropertyPath): boolean; + } + + interface LoDashExplicitWrapper { + /** + * @see _.hasIn + */ + hasIn(path: PropertyPath): LoDashExplicitWrapper; + } + + // invert + + interface LoDashStatic { + /** + * Creates an object composed of the inverted keys and values of object. If object contains duplicate values, + * subsequent values overwrite property assignments of previous values unless multiValue is true. + * + * @param object The object to invert. + * @param multiValue Allow multiple values per key. + * @return Returns the new inverted object. + */ + invert( + object: object + ): Dictionary; + } + + interface LoDashImplicitWrapper { + /** + * @see _.invert + */ + invert(): LoDashImplicitWrapper>; + } + + interface LoDashExplicitWrapper { + /** + * @see _.invert + */ + invert(): LoDashExplicitWrapper>; + } + + // invertBy + + interface LoDashStatic { + /** + * This method is like _.invert except that the inverted object is generated from the results of running each + * element of object through iteratee. The corresponding inverted value of each inverted key is an array of + * keys responsible for generating the inverted value. The iteratee is invoked with one argument: (value). + * + * @param object The object to invert. + * @param interatee The iteratee invoked per element. + * @return Returns the new inverted object. + */ + invertBy( + object: List | Dictionary | NumericDictionary | null | undefined, + interatee?: ValueIteratee + ): Dictionary; + + /** + * @see _.invertBy + */ + invertBy( + object: T | null | undefined, + interatee?: ValueIteratee + ): Dictionary; + } + + interface LoDashImplicitWrapper { + /** + * @see _.invertBy + */ + invertBy( + this: LoDashImplicitWrapper | Dictionary | NumericDictionary | null | undefined>, + interatee?: ValueIteratee + ): LoDashImplicitWrapper>; + + /** + * @see _.invertBy + */ + invertBy( + this: LoDashImplicitWrapper, + interatee?: ValueIteratee + ): LoDashImplicitWrapper>; + } + + interface LoDashExplicitWrapper { + /** + * @see _.invertBy + */ + invertBy( + this: LoDashExplicitWrapper | Dictionary | NumericDictionary | null | undefined>, + interatee?: ValueIteratee + ): LoDashExplicitWrapper>; + + /** + * @see _.invertBy + */ + invertBy( + this: LoDashExplicitWrapper, + interatee?: ValueIteratee + ): LoDashExplicitWrapper>; + } + + // invoke + + interface LoDashStatic { + /** + * Invokes the method at path of object. + * @param object The object to query. + * @param path The path of the method to invoke. + * @param args The arguments to invoke the method with. + **/ + invoke( + object: any, + path: PropertyPath, + ...args: any[]): any; + } + + interface LoDashImplicitWrapper { + /** + * @see _.invoke + **/ + invoke( + path: PropertyPath, + ...args: any[]): any; + } + + interface LoDashExplicitWrapper { + /** + * @see _.invoke + **/ + invoke( + path: PropertyPath, + ...args: any[]): LoDashExplicitWrapper; + } + + // keys + + interface LoDashStatic { + /** + * Creates an array of the own enumerable property names of object. + * + * Note: Non-object values are coerced to objects. See the ES spec for more details. + * + * @param object The object to query. + * @return Returns the array of property names. + */ + keys(object?: any): string[]; + } + + interface LoDashImplicitWrapper { + /** + * @see _.keys + */ + keys(): LoDashImplicitWrapper; + } + + interface LoDashExplicitWrapper { + /** + * @see _.keys + */ + keys(): LoDashExplicitWrapper; + } + + // keysIn + + interface LoDashStatic { + /** + * Creates an array of the own and inherited enumerable property names of object. + * + * Note: Non-object values are coerced to objects. + * + * @param object The object to query. + * @return An array of property names. + */ + keysIn(object?: any): string[]; + } + + interface LoDashImplicitWrapper { + /** + * @see _.keysIn + */ + keysIn(): LoDashImplicitWrapper; + } + + interface LoDashExplicitWrapper { + /** + * @see _.keysIn + */ + keysIn(): LoDashExplicitWrapper; + } + + // mapKeys + + interface LoDashStatic { + /** + * The opposite of _.mapValues; this method creates an object with the same values as object and keys generated + * by running each own enumerable property of object through iteratee. + * + * @param object The object to iterate over. + * @param iteratee The function invoked per iteration. + * @return Returns the new mapped object. + */ + mapKeys( + object: List | null | undefined, + iteratee?: ListIteratee + ): Dictionary; + + /** + * @see _.mapKeys + */ + mapKeys( + object: T | null | undefined, + iteratee?: ObjectIteratee + ): Dictionary; + } + + interface LoDashImplicitWrapper { + /** + * @see _.mapKeys + */ + mapKeys( + this: LoDashImplicitWrapper | null | undefined>, + iteratee?: ListIteratee + ): LoDashImplicitWrapper>; + + /** + * @see _.mapKeys + */ + mapKeys( + this: LoDashImplicitWrapper, + iteratee?: ObjectIteratee + ): LoDashImplicitWrapper>; + } + + interface LoDashExplicitWrapper { + /** + * @see _.mapKeys + */ + mapKeys( + this: LoDashExplicitWrapper | null | undefined>, + iteratee?: ListIteratee + ): LoDashExplicitWrapper>; + + /** + * @see _.mapKeys + */ + mapKeys( + this: LoDashExplicitWrapper, + iteratee?: ObjectIteratee + ): LoDashExplicitWrapper>; + } + + // mapValues + + interface LoDashStatic { + /** + * Creates an object with the same keys as object and values generated by running each own + * enumerable property of object through iteratee. The iteratee function is + * invoked with three arguments: (value, key, object). + * + * @param object The object to iterate over. + * @param iteratee The function invoked per iteration. + * @return Returns the new mapped object. + */ + mapValues(obj: string | null | undefined, callback: StringIterator): NumericDictionary; + + /** + * @see _.mapValues + * TODO: This would be better if we had a separate overload for obj: NumericDictionary that returned a NumericDictionary, + * but TypeScript cannot select overload signatures based on number vs string index key type. + */ + mapValues(obj: Dictionary | NumericDictionary | null | undefined, callback: DictionaryIterator): Dictionary; + + /** + * @see _.mapValues + */ + mapValues(obj: T | null | undefined, callback: ObjectIterator): { [P in keyof T]: TResult }; + + /** + * @see _.mapValues + * TODO: This would be better if we had a separate overload for obj: NumericDictionary that returned a NumericDictionary, + * but TypeScript cannot select overload signatures based on number vs string index key type. + */ + mapValues(obj: Dictionary | NumericDictionary | null | undefined, iteratee: object): Dictionary; + + /** + * @see _.mapValues + */ + mapValues(obj: T | null | undefined, iteratee: object): { [P in keyof T]: boolean }; + + /** + * @see _.mapValues + * TODO: This would be better if we had a separate overload for obj: NumericDictionary that returned a NumericDictionary, + * but TypeScript cannot select overload signatures based on number vs string index key type. + */ + mapValues(obj: Dictionary | NumericDictionary | null | undefined, iteratee: TKey): Dictionary; + + /** + * @see _.mapValues + * TODO: This would be better if we had a separate overload for obj: NumericDictionary that returned a NumericDictionary, + * but TypeScript cannot select overload signatures based on number vs string index key type. + */ + mapValues(obj: Dictionary | NumericDictionary | null | undefined, iteratee: string): Dictionary; + + /** + * @see _.mapValues + */ + mapValues(obj: T | null | undefined, iteratee: string): { [P in keyof T]: any }; + + /** + * @see _.mapValues + */ + mapValues(obj: string | null | undefined): NumericDictionary; + + /** + * @see _.mapValues + * TODO: This would be better if we had a separate overload for obj: NumericDictionary that returned a NumericDictionary, + * but TypeScript cannot select overload signatures based on number vs string index key type. + */ + mapValues(obj: Dictionary | NumericDictionary | null | undefined): Dictionary; + + /** + * @see _.mapValues + */ + mapValues(obj: T): T; + + /** + * @see _.mapValues + */ + mapValues(obj: T | null | undefined): PartialObject; + } + + interface LoDashImplicitWrapper { + /** + * @see _.mapValues + */ + mapValues( + this: LoDashImplicitWrapper, + callback: StringIterator + ): LoDashImplicitWrapper>; + + /** + * @see _.mapValues + * TODO: This would be better if we had a separate overload for obj: NumericDictionary that returned a NumericDictionary, + * but TypeScript cannot select overload signatures based on number vs string index key type. + */ + mapValues( + this: LoDashImplicitWrapper | NumericDictionary | null | undefined>, + callback: DictionaryIterator + ): LoDashImplicitWrapper>; + + /** + * @see _.mapValues + */ + mapValues( + this: LoDashImplicitWrapper, + callback: ObjectIterator + ): LoDashImplicitWrapper<{ [P in keyof T]: TResult }>; + + /** + * @see _.mapValues + * TODO: This would be better if we had a separate overload for obj: NumericDictionary that returned a NumericDictionary, + * but TypeScript cannot select overload signatures based on number vs string index key type. + */ + mapValues( + this: LoDashImplicitWrapper | NumericDictionary | null | undefined>, + iteratee: object + ): LoDashImplicitWrapper>; + + /** + * @see _.mapValues + */ + mapValues( + this: LoDashImplicitWrapper, + iteratee: object + ): LoDashImplicitWrapper<{ [P in keyof T]: boolean }>; + + /** + * @see _.mapValues + * TODO: This would be better if we had a separate overload for obj: NumericDictionary that returned a NumericDictionary, + * but TypeScript cannot select overload signatures based on number vs string index key type. + */ + mapValues( + this: LoDashImplicitWrapper | NumericDictionary | null | undefined>, + iteratee: TKey + ): LoDashImplicitWrapper>; + + /** + * @see _.mapValues + * TODO: This would be better if we had a separate overload for obj: NumericDictionary that returned a NumericDictionary, + * but TypeScript cannot select overload signatures based on number vs string index key type. + */ + mapValues( + this: LoDashImplicitWrapper | NumericDictionary | null | undefined>, + iteratee: string + ): LoDashImplicitWrapper>; + + /** + * @see _.mapValues + */ + mapValues( + this: LoDashImplicitWrapper, + iteratee: string + ): LoDashImplicitWrapper<{ [P in keyof T]: any }>; + + /** + * @see _.mapValues + */ + mapValues(this: LoDashImplicitWrapper): LoDashImplicitWrapper>; + + /** + * @see _.mapValues + * TODO: This would be better if we had a separate overload for obj: NumericDictionary that returned a NumericDictionary, + * but TypeScript cannot select overload signatures based on number vs string index key type. + */ + mapValues(this: LoDashImplicitWrapper | NumericDictionary | null | undefined>): LoDashImplicitWrapper>; + + /** + * @see _.mapValues + */ + mapValues(this: LoDashImplicitWrapper): LoDashImplicitWrapper; + + /** + * @see _.mapValues + */ + mapValues(this: LoDashImplicitWrapper): LoDashImplicitWrapper>; + } + + interface LoDashExplicitWrapper { + /** + * @see _.mapValues + */ + mapValues( + this: LoDashExplicitWrapper, + callback: StringIterator + ): LoDashExplicitWrapper>; + + /** + * @see _.mapValues + * TODO: This would be better if we had a separate overload for obj: NumericDictionary that returned a NumericDictionary, + * but TypeScript cannot select overload signatures based on number vs string index key type. + */ + mapValues( + this: LoDashExplicitWrapper | NumericDictionary | null | undefined>, + callback: DictionaryIterator + ): LoDashExplicitWrapper>; + + /** + * @see _.mapValues + */ + mapValues( + this: LoDashExplicitWrapper, + callback: ObjectIterator + ): LoDashExplicitWrapper<{ [P in keyof T]: TResult }>; + + /** + * @see _.mapValues + * TODO: This would be better if we had a separate overload for obj: NumericDictionary that returned a NumericDictionary, + * but TypeScript cannot select overload signatures based on number vs string index key type. + */ + mapValues( + this: LoDashExplicitWrapper | NumericDictionary | null | undefined>, + iteratee: object + ): LoDashExplicitWrapper>; + + /** + * @see _.mapValues + */ + mapValues( + this: LoDashExplicitWrapper, + iteratee: object + ): LoDashExplicitWrapper<{ [P in keyof T]: boolean }>; + + /** + * @see _.mapValues + * TODO: This would be better if we had a separate overload for obj: NumericDictionary that returned a NumericDictionary, + * but TypeScript cannot select overload signatures based on number vs string index key type. + */ + mapValues( + this: LoDashExplicitWrapper | NumericDictionary | null | undefined>, + iteratee: TKey + ): LoDashExplicitWrapper>; + + /** + * @see _.mapValues + * TODO: This would be better if we had a separate overload for obj: NumericDictionary that returned a NumericDictionary, + * but TypeScript cannot select overload signatures based on number vs string index key type. + */ + mapValues( + this: LoDashExplicitWrapper | NumericDictionary | null | undefined>, + iteratee: string + ): LoDashExplicitWrapper>; + + /** + * @see _.mapValues + */ + mapValues( + this: LoDashExplicitWrapper, + iteratee: string + ): LoDashExplicitWrapper<{ [P in keyof T]: any }>; + + /** + * @see _.mapValues + */ + mapValues(this: LoDashExplicitWrapper): LoDashExplicitWrapper>; + + /** + * @see _.mapValues + * TODO: This would be better if we had a separate overload for obj: NumericDictionary that returned a NumericDictionary, + * but TypeScript cannot select overload signatures based on number vs string index key type. + */ + mapValues(this: LoDashExplicitWrapper | NumericDictionary | null | undefined>): LoDashExplicitWrapper>; + + /** + * @see _.mapValues + */ + mapValues(this: LoDashExplicitWrapper): LoDashExplicitWrapper; + + /** + * @see _.mapValues + */ + mapValues(this: LoDashExplicitWrapper): LoDashExplicitWrapper>; + } + + // merge + + interface LoDashStatic { + /** + * Recursively merges own and inherited enumerable properties of source + * objects into the destination object, skipping source properties that resolve + * to `undefined`. Array and plain object properties are merged recursively. + * Other objects and value types are overridden by assignment. Source objects + * are applied from left to right. Subsequent sources overwrite property + * assignments of previous sources. + * + * **Note:** This method mutates `object`. + * + * @category Object + * @param object The destination object. + * @param [sources] The source objects. + * @returns Returns `object`. + * @example + * + * var users = { + * 'data': [{ 'user': 'barney' }, { 'user': 'fred' }] + * }; + * + * var ages = { + * 'data': [{ 'age': 36 }, { 'age': 40 }] + * }; + * + * _.merge(users, ages); + * // => { 'data': [{ 'user': 'barney', 'age': 36 }, { 'user': 'fred', 'age': 40 }] } + */ + merge( + object: TObject, + source: TSource + ): TObject & TSource; + + /** + * @see _.merge + */ + merge( + object: TObject, + source1: TSource1, + source2: TSource2 + ): TObject & TSource1 & TSource2; + + /** + * @see _.merge + */ + merge( + object: TObject, + source1: TSource1, + source2: TSource2, + source3: TSource3 + ): TObject & TSource1 & TSource2 & TSource3; + + /** + * @see _.merge + */ + merge( + object: TObject, + source1: TSource1, + source2: TSource2, + source3: TSource3, + source4: TSource4 + ): TObject & TSource1 & TSource2 & TSource3 & TSource4; + + /** + * @see _.merge + */ + merge( + object: any, + ...otherArgs: any[] + ): any; + } + + interface LoDashImplicitWrapper { + /** + * @see _.merge + */ + merge( + source: TSource + ): LoDashImplicitWrapper; + + /** + * @see _.merge + */ + merge( + source1: TSource1, + source2: TSource2 + ): LoDashImplicitWrapper; + + /** + * @see _.merge + */ + merge( + source1: TSource1, + source2: TSource2, + source3: TSource3 + ): LoDashImplicitWrapper; + + /** + * @see _.merge + */ + merge( + source1: TSource1, + source2: TSource2, + source3: TSource3, + source4: TSource4 + ): LoDashImplicitWrapper; + + /** + * @see _.merge + */ + merge( + ...otherArgs: any[] + ): LoDashImplicitWrapper; + } + + interface LoDashExplicitWrapper { + /** + * @see _.merge + */ + merge( + source: TSource + ): LoDashExplicitWrapper; + + /** + * @see _.merge + */ + merge( + source1: TSource1, + source2: TSource2 + ): LoDashExplicitWrapper; + + /** + * @see _.merge + */ + merge( + source1: TSource1, + source2: TSource2, + source3: TSource3 + ): LoDashExplicitWrapper; + + /** + * @see _.merge + */ + merge( + source1: TSource1, + source2: TSource2, + source3: TSource3, + source4: TSource4 + ): LoDashExplicitWrapper; + + /** + * @see _.merge + */ + merge( + ...otherArgs: any[] + ): LoDashExplicitWrapper; + } + + // mergeWith + + type MergeWithCustomizer = { bivariantHack(value: any, srcValue: any, key: string, object: any, source: any): any; }["bivariantHack"]; + + interface LoDashStatic { + /** + * This method is like `_.merge` except that it accepts `customizer` which + * is invoked to produce the merged values of the destination and source + * properties. If `customizer` returns `undefined` merging is handled by the + * method instead. The `customizer` is invoked with seven arguments: + * (objValue, srcValue, key, object, source, stack). + * + * @category Object + * @param object The destination object. + * @param sources The source objects. + * @param customizer The function to customize assigned values. + * @returns Returns `object`. + * @example + * + * function customizer(objValue, srcValue) { + * if (_.isArray(objValue)) { + * return objValue.concat(srcValue); + * } + * } + * + * var object = { + * 'fruits': ['apple'], + * 'vegetables': ['beet'] + * }; + * + * var other = { + * 'fruits': ['banana'], + * 'vegetables': ['carrot'] + * }; + * + * _.merge(object, other, customizer); + * // => { 'fruits': ['apple', 'banana'], 'vegetables': ['beet', 'carrot'] } + */ + mergeWith( + object: TObject, + source: TSource, + customizer: MergeWithCustomizer + ): TObject & TSource; + + /** + * @see _.mergeWith + */ + mergeWith( + object: TObject, + source1: TSource1, + source2: TSource2, + customizer: MergeWithCustomizer + ): TObject & TSource1 & TSource2; + + /** + * @see _.mergeWith + */ + mergeWith( + object: TObject, + source1: TSource1, + source2: TSource2, + source3: TSource3, + customizer: MergeWithCustomizer + ): TObject & TSource1 & TSource2 & TSource3; + + /** + * @see _.mergeWith + */ + mergeWith( + object: TObject, + source1: TSource1, + source2: TSource2, + source3: TSource3, + source4: TSource4, + customizer: MergeWithCustomizer + ): TObject & TSource1 & TSource2 & TSource3 & TSource4; + + /** + * @see _.mergeWith + */ + mergeWith( + object: any, + ...otherArgs: any[] + ): any; + } + + interface LoDashImplicitWrapper { + /** + * @see _.mergeWith + */ + mergeWith( + source: TSource, + customizer: MergeWithCustomizer + ): LoDashImplicitWrapper; + + /** + * @see _.mergeWith + */ + mergeWith( + source1: TSource1, + source2: TSource2, + customizer: MergeWithCustomizer + ): LoDashImplicitWrapper; + + /** + * @see _.mergeWith + */ + mergeWith( + source1: TSource1, + source2: TSource2, + source3: TSource3, + customizer: MergeWithCustomizer + ): LoDashImplicitWrapper; + + /** + * @see _.mergeWith + */ + mergeWith( + source1: TSource1, + source2: TSource2, + source3: TSource3, + source4: TSource4, + customizer: MergeWithCustomizer + ): LoDashImplicitWrapper; + + /** + * @see _.mergeWith + */ + mergeWith( + ...otherArgs: any[] + ): LoDashImplicitWrapper; + } + + interface LoDashExplicitWrapper { + /** + * @see _.mergeWith + */ + mergeWith( + source: TSource, + customizer: MergeWithCustomizer + ): LoDashExplicitWrapper; + + /** + * @see _.mergeWith + */ + mergeWith( + source1: TSource1, + source2: TSource2, + customizer: MergeWithCustomizer + ): LoDashExplicitWrapper; + + /** + * @see _.mergeWith + */ + mergeWith( + source1: TSource1, + source2: TSource2, + source3: TSource3, + customizer: MergeWithCustomizer + ): LoDashExplicitWrapper; + + /** + * @see _.mergeWith + */ + mergeWith( + source1: TSource1, + source2: TSource2, + source3: TSource3, + source4: TSource4, + customizer: MergeWithCustomizer + ): LoDashExplicitWrapper; + + /** + * @see _.mergeWith + */ + mergeWith( + ...otherArgs: any[] + ): LoDashExplicitWrapper; + } + + // omit + + interface LoDashStatic { + /** + * The opposite of `_.pick`; this method creates an object composed of the + * own and inherited enumerable properties of `object` that are not omitted. + * + * @category Object + * @param object The source object. + * @param [paths] The property names to omit, specified + * individually or in arrays.. + * @returns Returns the new object. + * @example + * + * var object = { 'a': 1, 'b': '2', 'c': 3 }; + * + * _.omit(object, ['a', 'c']); + * // => { 'b': '2' } + */ + omit( + object: T | null | undefined, + ...paths: Array> + ): T; + + /** + * @see _.omit + */ + omit( + object: T | null | undefined, + ...paths: Array> + ): Omit; + + /** + * @see _.omit + */ + omit( + object: T | null | undefined, + ...paths: Array> + ): PartialObject; + } + + interface LoDashImplicitWrapper { + /** + * @see _.omit + */ + omit( + this: LoDashImplicitWrapper, + ...paths: Array> + ): LoDashImplicitWrapper; + + /** + * @see _.omit + */ + omit( + this: LoDashImplicitWrapper, + ...paths: Array> + ): LoDashImplicitWrapper>; + + /** + * @see _.omit + */ + omit( + this: LoDashImplicitWrapper, + ...paths: Array> + ): LoDashImplicitWrapper>; + } + + interface LoDashExplicitWrapper { + /** + * @see _.omit + */ + omit( + this: LoDashExplicitWrapper, + ...paths: Array> + ): LoDashExplicitWrapper; + + /** + * @see _.omit + */ + omit( + this: LoDashExplicitWrapper, + ...paths: Array> + ): LoDashExplicitWrapper>; + + /** + * @see _.omit + */ + omit( + this: LoDashExplicitWrapper, + ...paths: Array> + ): LoDashExplicitWrapper>; + } + + // omitBy + + interface LoDashStatic { + /** + * The opposite of `_.pickBy`; this method creates an object composed of the + * own and inherited enumerable properties of `object` that `predicate` + * doesn't return truthy for. + * + * @category Object + * @param object The source object. + * @param [predicate=_.identity] The function invoked per property. + * @returns Returns the new object. + * @example + * + * var object = { 'a': 1, 'b': '2', 'c': 3 }; + * + * _.omitBy(object, _.isNumber); + * // => { 'b': '2' } + */ + omitBy( + object: Dictionary | null | undefined, + predicate?: ValueKeyIteratee + ): Dictionary; + + /** + * @see _.omitBy + */ + omitBy( + object: NumericDictionary | null | undefined, + predicate?: ValueKeyIteratee + ): NumericDictionary; + + /** + * @see _.omitBy + */ + omitBy( + object: T | null | undefined, + predicate: ValueKeyIteratee + ): PartialObject; + } + + interface LoDashImplicitWrapper { + /** + * @see _.omitBy + */ + omitBy( + this: LoDashImplicitWrapper | null | undefined>, + predicate?: ValueKeyIteratee + ): LoDashImplicitWrapper>; + + /** + * @see _.omitBy + */ + omitBy( + this: LoDashImplicitWrapper | null | undefined>, + predicate?: ValueKeyIteratee + ): LoDashImplicitWrapper>; + + /** + * @see _.omitBy + */ + omitBy( + this: LoDashImplicitWrapper, + predicate: ValueKeyIteratee + ): LoDashImplicitWrapper>; + } + + interface LoDashExplicitWrapper { + /** + * @see _.omitBy + */ + omitBy( + this: LoDashExplicitWrapper | null | undefined>, + predicate?: ValueKeyIteratee + ): LoDashExplicitWrapper>; + + /** + * @see _.omitBy + */ + omitBy( + this: LoDashExplicitWrapper | null | undefined>, + predicate?: ValueKeyIteratee + ): LoDashExplicitWrapper>; + + /** + * @see _.omitBy + */ + omitBy( + this: LoDashExplicitWrapper, + predicate: ValueKeyIteratee + ): LoDashExplicitWrapper>; + } + + // pick + + interface LoDashStatic { + /** + * Creates an object composed of the picked `object` properties. + * + * @category Object + * @param object The source object. + * @param [props] The property names to pick, specified + * individually or in arrays. + * @returns Returns the new object. + * @example + * + * var object = { 'a': 1, 'b': '2', 'c': 3 }; + * + * _.pick(object, ['a', 'c']); + * // => { 'a': 1, 'c': 3 } + */ + pick( + object: T, + ...props: Array> + ): Pick; + + /** + * @see _.pick + */ + pick( + object: T | null | undefined, + ...props: PropertyPath[] + ): PartialDeep; + } + + interface LoDashImplicitWrapper { + /** + * @see _.pick + */ + pick( + this: LoDashImplicitWrapper, + ...props: Array> + ): LoDashImplicitWrapper>; + + /** + * @see _.pick + */ + pick( + this: LoDashImplicitWrapper, + ...props: PropertyPath[] + ): LoDashImplicitWrapper>; + } + + interface LoDashExplicitWrapper { + /** + * @see _.pick + */ + pick( + this: LoDashExplicitWrapper, + ...props: Array> + ): LoDashExplicitWrapper>; + + /** + * @see _.pick + */ + pick( + this: LoDashExplicitWrapper, + ...props: PropertyPath[] + ): LoDashExplicitWrapper>; + } + + // pickBy + + interface LoDashStatic { + /** + * Creates an object composed of the `object` properties `predicate` returns + * truthy for. The predicate is invoked with two arguments: (value, key). + * + * @category Object + * @param object The source object. + * @param [predicate=_.identity] The function invoked per property. + * @returns Returns the new object. + * @example + * + * var object = { 'a': 1, 'b': '2', 'c': 3 }; + * + * _.pickBy(object, _.isNumber); + * // => { 'a': 1, 'c': 3 } + */ + pickBy( + object: Dictionary | null | undefined, + predicate: ValueKeyIterateeTypeGuard + ): Dictionary; + + /** + * @see _.pickBy + */ + pickBy( + object: NumericDictionary | null | undefined, + predicate: ValueKeyIterateeTypeGuard + ): NumericDictionary; + + /** + * @see _.pickBy + */ + pickBy( + object: Dictionary | null | undefined, + predicate?: ValueKeyIteratee + ): Dictionary; + + /** + * @see _.pickBy + */ + pickBy( + object: NumericDictionary | null | undefined, + predicate?: ValueKeyIteratee + ): NumericDictionary; + + /** + * @see _.pickBy + */ + pickBy( + object: T | null | undefined, + predicate?: ValueKeyIteratee + ): PartialObject; + } + + interface LoDashImplicitWrapper { + /** + * @see _.pickBy + */ + pickBy( + this: LoDashImplicitWrapper | null | undefined>, + predicate: ValueKeyIterateeTypeGuard + ): LoDashImplicitWrapper>; + + /** + * @see _.pickBy + */ + pickBy( + this: LoDashImplicitWrapper | null | undefined>, + predicate: ValueKeyIterateeTypeGuard + ): LoDashImplicitWrapper>; + + /** + * @see _.pickBy + */ + pickBy( + this: LoDashImplicitWrapper | null | undefined>, + predicate?: ValueKeyIteratee + ): LoDashImplicitWrapper>; + + /** + * @see _.pickBy + */ + pickBy( + this: LoDashImplicitWrapper | null | undefined>, + predicate?: ValueKeyIteratee + ): LoDashImplicitWrapper>; + + /** + * @see _.pickBy + */ + pickBy( + this: LoDashImplicitWrapper, + predicate?: ValueKeyIteratee + ): LoDashImplicitWrapper>; + } + + interface LoDashExplicitWrapper { + /** + * @see _.pickBy + */ + pickBy( + this: LoDashExplicitWrapper | null | undefined>, + predicate: ValueKeyIterateeTypeGuard + ): LoDashExplicitWrapper>; + + /** + * @see _.pickBy + */ + pickBy( + this: LoDashExplicitWrapper | null | undefined>, + predicate: ValueKeyIterateeTypeGuard + ): LoDashExplicitWrapper>; + + /** + * @see _.pickBy + */ + pickBy( + this: LoDashExplicitWrapper | null | undefined>, + predicate?: ValueKeyIteratee + ): LoDashExplicitWrapper>; + + /** + * @see _.pickBy + */ + pickBy( + this: LoDashExplicitWrapper | null | undefined>, + predicate?: ValueKeyIteratee + ): LoDashExplicitWrapper>; + + /** + * @see _.pickBy + */ + pickBy( + this: LoDashExplicitWrapper, + predicate?: ValueKeyIteratee + ): LoDashExplicitWrapper>; + } + + // result + + interface LoDashStatic { + /** + * This method is like _.get except that if the resolved value is a function it’s invoked with the this binding + * of its parent object and its result is returned. + * + * @param object The object to query. + * @param path The path of the property to resolve. + * @param defaultValue The value returned if the resolved value is undefined. + * @return Returns the resolved value. + */ + result( + object: any, + path: PropertyPath, + defaultValue?: TResult|((...args: any[]) => TResult) + ): TResult; + } + + interface LoDashImplicitWrapper { + /** + * @see _.result + */ + result( + path: PropertyPath, + defaultValue?: TResult|((...args: any[]) => TResult) + ): TResult; + } + + interface LoDashExplicitWrapper { + /** + * @see _.result + */ + result( + path: PropertyPath, + defaultValue?: TResult|((...args: any[]) => TResult) + ): LoDashExplicitWrapper; + } + + // set + + interface LoDashStatic { + /** + * Sets the value at path of object. If a portion of path doesn’t exist it’s created. Arrays are created for + * missing index properties while objects are created for all other missing properties. Use _.setWith to + * customize path creation. + * + * @param object The object to modify. + * @param path The path of the property to set. + * @param value The value to set. + * @return Returns object. + */ + set( + object: T, + path: PropertyPath, + value: any + ): T; + + /** + * @see _.set + */ + set( + object: object, + path: PropertyPath, + value: any + ): TResult; + } + + interface LoDashImplicitWrapper { + /** + * @see _.set + */ + set( + path: PropertyPath, + value: any + ): this; + + /** + * @see _.set + */ + set( + path: PropertyPath, + value: any + ): LoDashImplicitWrapper; + } + + interface LoDashExplicitWrapper { + /** + * @see _.set + */ + set( + path: PropertyPath, + value: any + ): this; + + /** + * @see _.set + */ + set( + path: PropertyPath, + value: any + ): LoDashExplicitWrapper; + } + + // setWith + + type SetWithCustomizer = (nsValue: any, key: string, nsObject: T) => any; + + interface LoDashStatic { + /** + * This method is like _.set except that it accepts customizer which is invoked to produce the objects of + * path. If customizer returns undefined path creation is handled by the method instead. The customizer is + * invoked with three arguments: (nsValue, key, nsObject). + * + * @param object The object to modify. + * @param path The path of the property to set. + * @param value The value to set. + * @param customizer The function to customize assigned values. + * @return Returns object. + */ + setWith( + object: T, + path: PropertyPath, + value: any, + customizer?: SetWithCustomizer + ): T; + + setWith( + object: T, + path: PropertyPath, + value: any, + customizer?: SetWithCustomizer + ): TResult; + } + + interface LoDashImplicitWrapper { + /** + * @see _.setWith + */ + setWith( + path: PropertyPath, + value: any, + customizer?: SetWithCustomizer + ): this; + + /** + * @see _.setWith + */ + setWith( + path: PropertyPath, + value: any, + customizer?: SetWithCustomizer + ): LoDashImplicitWrapper; + } + + interface LoDashExplicitWrapper { + /** + * @see _.setWith + */ + setWith( + path: PropertyPath, + value: any, + customizer?: SetWithCustomizer + ): this; + + /** + * @see _.setWith + */ + setWith( + path: PropertyPath, + value: any, + customizer?: SetWithCustomizer + ): LoDashExplicitWrapper; + } + + // toPairs + + interface LoDashStatic { + /** + * Creates an array of own enumerable key-value pairs for object. + * + * @param object The object to query. + * @return Returns the new array of key-value pairs. + */ + toPairs(object?: Dictionary | NumericDictionary): Array<[string, T]>; + + /** + * @see _.toPairs + */ + toPairs(object?: object): Array<[string, any]>; + } + + interface LoDashImplicitWrapper { + /** + * @see _.toPairs + */ + toPairs(this: LoDashImplicitWrapper | NumericDictionary>): LoDashImplicitWrapper>; + + /** + * @see _.toPairs + */ + toPairs(): LoDashImplicitWrapper>; + } + + interface LoDashExplicitWrapper { + /** + * @see _.toPairs + */ + toPairs(this: LoDashExplicitWrapper | NumericDictionary>): LoDashExplicitWrapper>; + + /** + * @see _.toPairs + */ + toPairs(): LoDashExplicitWrapper>; + } + + // toPairsIn + + interface LoDashStatic { + /** + * Creates an array of own and inherited enumerable key-value pairs for object. + * + * @param object The object to query. + * @return Returns the new array of key-value pairs. + */ + toPairsIn(object?: Dictionary | NumericDictionary): Array<[string, T]>; + + /** + * @see _.toPairsIn + */ + toPairsIn(object?: object): Array<[string, any]>; + } + + interface LoDashImplicitWrapper { + /** + * @see _.toPairsIn + */ + toPairsIn(this: LoDashImplicitWrapper | NumericDictionary>): LoDashImplicitWrapper>; + + /** + * @see _.toPairsIn + */ + toPairsIn(): LoDashImplicitWrapper>; + } + + interface LoDashExplicitWrapper { + /** + * @see _.toPairsIn + */ + toPairsIn(this: LoDashExplicitWrapper | NumericDictionary>): LoDashExplicitWrapper>; + + /** + * @see _.toPairsIn + */ + toPairsIn(): LoDashExplicitWrapper>; + } + + // transform + + interface LoDashStatic { + /** + * An alternative to _.reduce; this method transforms object to a new accumulator object which is the result of + * running each of its own enumerable properties through iteratee, with each invocation potentially mutating + * the accumulator object. The iteratee is invoked with four arguments: (accumulator, + * value, key, object). Iteratee functions may exit iteration early by explicitly returning false. + * + * @param object The object to iterate over. + * @param iteratee The function invoked per iteration. + * @param accumulator The custom accumulator value. + * @return Returns the accumulated value. + */ + transform( + object: T[], + iteratee: MemoVoidArrayIterator, + accumulator?: TResult[] + ): TResult[]; + + /** + * @see _.transform + */ + transform( + object: T[], + iteratee: MemoVoidArrayIterator>, + accumulator: Dictionary + ): Dictionary; + + /** + * @see _.transform + */ + transform( + object: Dictionary, + iteratee: MemoVoidDictionaryIterator>, + accumulator?: Dictionary + ): Dictionary; + + /** + * @see _.transform + */ + transform( + object: Dictionary, + iteratee: MemoVoidDictionaryIterator, + accumulator: TResult[] + ): TResult[]; + + /** + * @see _.transform + */ + transform( + object: any[], + ): any[]; + + /** + * @see _.transform + */ + transform( + object: object, + ): Dictionary; + } + + interface LoDashImplicitWrapper { + /** + * @see _.transform + */ + transform( + this: LoDashImplicitWrapper, + iteratee: MemoVoidArrayIterator, + accumulator?: TResult[] + ): LoDashImplicitWrapper; + + /** + * @see _.transform + */ + transform( + this: LoDashImplicitWrapper, + iteratee: MemoVoidArrayIterator>, + accumulator: Dictionary + ): LoDashImplicitWrapper>; + + /** + * @see _.transform + */ + transform( + this: LoDashImplicitWrapper>, + iteratee: MemoVoidDictionaryIterator>, + accumulator?: Dictionary + ): LoDashImplicitWrapper>; + + /** + * @see _.transform + */ + transform( + this: LoDashImplicitWrapper>, + iteratee: MemoVoidDictionaryIterator, + accumulator: TResult[] + ): LoDashImplicitWrapper; + + /** + * @see _.transform + */ + transform( + this: LoDashImplicitWrapper, + ): LoDashImplicitWrapper; + + /** + * @see _.transform + */ + transform(): LoDashImplicitWrapper>; + } + + interface LoDashExplicitWrapper { + /** + * @see _.transform + */ + transform( + this: LoDashExplicitWrapper, + iteratee: MemoVoidArrayIterator, + accumulator?: TResult[] + ): LoDashExplicitWrapper; + + /** + * @see _.transform + */ + transform( + this: LoDashExplicitWrapper, + iteratee: MemoVoidArrayIterator>, + accumulator?: Dictionary + ): LoDashExplicitWrapper>; + + /** + * @see _.transform + */ + transform( + this: LoDashExplicitWrapper>, + iteratee: MemoVoidDictionaryIterator>, + accumulator?: Dictionary + ): LoDashExplicitWrapper>; + + /** + * @see _.transform + */ + transform( + this: LoDashExplicitWrapper>, + iteratee: MemoVoidDictionaryIterator, + accumulator?: TResult[] + ): LoDashExplicitWrapper; + + /** + * @see _.transform + */ + transform( + this: LoDashExplicitWrapper, + ): LoDashExplicitWrapper; + + /** + * @see _.transform + */ + transform(): LoDashExplicitWrapper>; + } + + // unset + + interface LoDashStatic { + /** + * Removes the property at path of object. + * + * Note: This method mutates object. + * + * @param object The object to modify. + * @param path The path of the property to unset. + * @return Returns true if the property is deleted, else false. + */ + unset( + object: any, + path: PropertyPath + ): boolean; + } + + interface LoDashImplicitWrapper { + /** + * @see _.unset + */ + unset(path: PropertyPath): LoDashImplicitWrapper; + } + + interface LoDashExplicitWrapper { + /** + * @see _.unset + */ + unset(path: PropertyPath): LoDashExplicitWrapper; + } + + // update + + interface LoDashStatic { + /** + * This method is like _.set except that accepts updater to produce the value to set. Use _.updateWith to + * customize path creation. The updater is invoked with one argument: (value). + * + * @param object The object to modify. + * @param path The path of the property to set. + * @param updater The function to produce the updated value. + * @return Returns object. + */ + update( + object: object, + path: PropertyPath, + updater: (value: any) => any + ): any; + } + + interface LoDashImplicitWrapper { + /** + * @see _.update + */ + update( + path: PropertyPath, + updater: (value: any) => any + ): LoDashImplicitWrapper; + } + + interface LoDashExplicitWrapper { + /** + * @see _.update + */ + update( + path: PropertyPath, + updater: (value: any) => any + ): LoDashExplicitWrapper; + } + + // updateWith + + interface LoDashStatic { + /** + * This method is like `_.update` except that it accepts `customizer` which is + * invoked to produce the objects of `path`. If `customizer` returns `undefined` + * path creation is handled by the method instead. The `customizer` is invoked + * with three arguments: (nsValue, key, nsObject). + * + * **Note:** This method mutates `object`. + * + * @since 4.6.0 + * @category Object + * @param object The object to modify. + * @param path The path of the property to set. + * @param updater The function to produce the updated value. + * @param [customizer] The function to customize assigned values. + * @returns Returns `object`. + * @example + * + * var object = {}; + * + * _.updateWith(object, '[0][1]', _.constant('a'), Object); + * // => { '0': { '1': 'a' } } + */ + updateWith( + object: T, + path: PropertyPath, + updater: (oldValue: any) => any, + customizer?: SetWithCustomizer + ): T; + + /** + * @see _.updateWith + */ + updateWith( + object: T, + path: PropertyPath, + updater: (oldValue: any) => any, + customizer?: SetWithCustomizer + ): TResult; + } + + interface LoDashImplicitWrapper { + /** + * @see _.updateWith + */ + updateWith( + path: PropertyPath, + updater: (oldValue: any) => any, + customizer?: SetWithCustomizer + ): this; + + /** + * @see _.updateWith + */ + updateWith( + path: PropertyPath, + updater: (oldValue: any) => any, + customizer?: SetWithCustomizer + ): LoDashImplicitWrapper; + } + + interface LoDashExplicitWrapper { + /** + * @see _.updateWith + */ + updateWith( + path: PropertyPath, + updater: (oldValue: any) => any, + customizer?: SetWithCustomizer + ): this; + + /** + * @see _.updateWith + */ + updateWith( + path: PropertyPath, + updater: (oldValue: any) => any, + customizer?: SetWithCustomizer + ): LoDashExplicitWrapper; + } + + // values + + interface LoDashStatic { + /** + * Creates an array of the own enumerable property values of object. + * + * @param object The object to query. + * @return Returns an array of property values. + */ + values(object: Dictionary | NumericDictionary | List | null | undefined): T[]; + + /** + * @see _.values + */ + values(object: T | null | undefined): Array; + + /** + * @see _.values + */ + values(object: any): any[]; + } + + interface LoDashImplicitWrapper { + /** + * @see _.values + */ + values(this: LoDashImplicitWrapper | NumericDictionary | List | null | undefined>): LoDashImplicitWrapper; + + /** + * @see _.values + */ + values(this: LoDashImplicitWrapper): LoDashImplicitWrapper>; + + /** + * @see _.values + */ + values(): LoDashImplicitWrapper; + } + + interface LoDashExplicitWrapper { + /** + * @see _.values + */ + values(this: LoDashExplicitWrapper | NumericDictionary | List | null | undefined>): LoDashExplicitWrapper; + + /** + * @see _.values + */ + values(this: LoDashExplicitWrapper): LoDashExplicitWrapper>; + + /** + * @see _.values + */ + values(): LoDashExplicitWrapper; + } + + // valuesIn + + interface LoDashStatic { + /** + * Creates an array of the own and inherited enumerable property values of object. + * + * @param object The object to query. + * @return Returns the array of property values. + */ + valuesIn(object: Dictionary|NumericDictionary|List | null | undefined): T[]; + + /** + * @see _.valuesIn + */ + valuesIn(object: T | null | undefined): Array; + } + + interface LoDashImplicitWrapper { + /** + * @see _.valuesIn + */ + valuesIn(this: LoDashImplicitWrapper | NumericDictionary | List | null | undefined>): LoDashImplicitWrapper; + + /** + * @see _.valuesIn + */ + valuesIn(this: LoDashImplicitWrapper): LoDashImplicitWrapper>; + } + + interface LoDashExplicitWrapper { + /** + * @see _.valuesIn + */ + valuesIn(this: LoDashExplicitWrapper | NumericDictionary | List | null | undefined>): LoDashExplicitWrapper; + + /** + * @see _.valuesIn + */ + valuesIn(this: LoDashExplicitWrapper): LoDashExplicitWrapper>; + } +} diff --git a/node_modules/@types/lodash/common/seq.d.ts b/node_modules/@types/lodash/common/seq.d.ts new file mode 100644 index 0000000..bc3cc39 --- /dev/null +++ b/node_modules/@types/lodash/common/seq.d.ts @@ -0,0 +1,196 @@ +import _ = require("../index"); +declare module "../index" { + // chain + + interface LoDashStatic { + /** + * Creates a lodash object that wraps value with explicit method chaining enabled. + * + * @param value The value to wrap. + * @return Returns the new lodash wrapper instance. + */ + chain(value: T): LoDashExplicitWrapper; + } + + interface LoDashImplicitWrapper { + /** + * @see _.chain + */ + chain(): LoDashExplicitWrapper; + } + + interface LoDashExplicitWrapper { + /** + * @see _.chain + */ + chain(): this; + } + + // prototype.chain + + interface LoDashStatic { + /** + * Creates a lodash object that wraps value with explicit method chaining enabled. + * + * @param value The value to wrap. + * @return Returns the new lodash wrapper instance. + */ + chain(value: T): LoDashExplicitWrapper; + } + + interface LoDashImplicitWrapper { + /** + * @see _.chain + */ + chain(): LoDashExplicitWrapper; + } + + interface LoDashExplicitWrapper { + /** + * @see _.chain + */ + chain(): this; + } + + // prototype.commit + + interface LoDashWrapper { + /** + * Executes the chained sequence and returns the wrapped result. + * + * @return Returns the new lodash wrapper instance. + */ + commit(): this; + } + + // prototype.plant + + interface LoDashImplicitWrapper { + /** + * Creates a clone of the chained sequence planting value as the wrapped value. + * @param value The value to plant as the wrapped value. + * @return Returns the new lodash wrapper instance. + */ + plant(value: T): LoDashImplicitWrapper; + } + + interface LoDashExplicitWrapper { + /** + * @see _.plant + */ + plant(value: T): LoDashExplicitWrapper; + } + + // prototype.reverse + + interface LoDashWrapper { + /** + * Reverses the wrapped array so the first element becomes the last, the second element becomes the second to + * last, and so on. + * + * Note: This method mutates the wrapped array. + * + * @return Returns the new reversed lodash wrapper instance. + */ + reverse(): this; + } + + // prototype.toJSON + + interface LoDashWrapper { + /** + * @see _.value + */ + toJSON(): TValue; + } + + // prototype.toString + + interface LoDashWrapper { + /** + * Produces the result of coercing the unwrapped value to a string. + * + * @return Returns the coerced string value. + */ + toString(): string; + } + + // prototype.value + + interface LoDashWrapper { + /** + * Executes the chained sequence to extract the unwrapped value. + * + * @alias _.toJSON, _.valueOf + * + * @return Returns the resolved unwrapped value. + */ + value(): TValue; + } + + // prototype.valueOf + + interface LoDashWrapper { + /** + * @see _.value + */ + valueOf(): TValue; + } + + // tap + + interface LoDashStatic { + /** + * This method invokes interceptor and returns value. The interceptor is invoked with one + * argument; (value). The purpose of this method is to "tap into" a method chain in order to perform operations + * on intermediate results within the chain. + * + * @param value The value to provide to interceptor. + * @param interceptor The function to invoke. + * @return Returns value. + **/ + tap( + value: T, + interceptor: (value: T) => void + ): T; + } + + interface LoDashWrapper { + /** + * @see _.tap + */ + tap( + interceptor: (value: TValue) => void + ): this; + } + + // thru + + interface LoDashStatic { + /** + * This method is like _.tap except that it returns the result of interceptor. + * + * @param value The value to provide to interceptor. + * @param interceptor The function to invoke. + * @return Returns the result of interceptor. + */ + thru( + value: T, + interceptor: (value: T) => TResult + ): TResult; + } + + interface LoDashImplicitWrapper { + /** + * @see _.thru + */ + thru(interceptor: (value: TValue) => TResult): LoDashImplicitWrapper; + } + + interface LoDashExplicitWrapper { + /** + * @see _.thru + */ + thru(interceptor: (value: TValue) => TResult): LoDashExplicitWrapper; + } +} diff --git a/node_modules/@types/lodash/common/string.d.ts b/node_modules/@types/lodash/common/string.d.ts new file mode 100644 index 0000000..d940406 --- /dev/null +++ b/node_modules/@types/lodash/common/string.d.ts @@ -0,0 +1,1059 @@ +import _ = require("../index"); +declare module "../index" { + // camelCase + + interface LoDashStatic { + /** + * Converts string to camel case. + * + * @param string The string to convert. + * @return Returns the camel cased string. + */ + camelCase(string?: string): string; + } + + interface LoDashImplicitWrapper { + /** + * @see _.camelCase + */ + camelCase(): string; + } + + interface LoDashExplicitWrapper { + /** + * @see _.camelCase + */ + camelCase(): LoDashExplicitWrapper; + } + + // capitalize + + interface LoDashStatic { + /** + * Converts the first character of string to upper case and the remaining to lower case. + * + * @param string The string to capitalize. + * @return Returns the capitalized string. + */ + capitalize(string?: string): string; + } + + interface LoDashImplicitWrapper { + /** + * @see _.capitalize + */ + capitalize(): string; + } + + interface LoDashExplicitWrapper { + /** + * @see _.capitalize + */ + capitalize(): LoDashExplicitWrapper; + } + + // deburr + + interface LoDashStatic { + /** + * Deburrs string by converting latin-1 supplementary letters to basic latin letters and removing combining + * diacritical marks. + * + * @param string The string to deburr. + * @return Returns the deburred string. + */ + deburr(string?: string): string; + } + + interface LoDashImplicitWrapper { + /** + * @see _.deburr + */ + deburr(): string; + } + + interface LoDashExplicitWrapper { + /** + * @see _.deburr + */ + deburr(): LoDashExplicitWrapper; + } + + // endsWith + + interface LoDashStatic { + /** + * Checks if string ends with the given target string. + * + * @param string The string to search. + * @param target The string to search for. + * @param position The position to search from. + * @return Returns true if string ends with target, else false. + */ + endsWith( + string?: string, + target?: string, + position?: number + ): boolean; + } + + interface LoDashImplicitWrapper { + /** + * @see _.endsWith + */ + endsWith( + target?: string, + position?: number + ): boolean; + } + + interface LoDashExplicitWrapper { + /** + * @see _.endsWith + */ + endsWith( + target?: string, + position?: number + ): LoDashExplicitWrapper; + } + + // escape + + interface LoDashStatic { + /** + * Converts the characters "&", "<", ">", '"', "'", and "`" in string to their corresponding HTML entities. + * + * Note: No other characters are escaped. To escape additional characters use a third-party library like he. + * + * hough the ">" character is escaped for symmetry, characters like ">" and "/" don’t need escaping in HTML + * and have no special meaning unless they're part of a tag or unquoted attribute value. See Mathias Bynens’s + * article (under "semi-related fun fact") for more details. + * + * Backticks are escaped because in IE < 9, they can break out of attribute values or HTML comments. See #59, + * #102, #108, and #133 of the HTML5 Security Cheatsheet for more details. + * + * When working with HTML you should always quote attribute values to reduce XSS vectors. + * + * @param string The string to escape. + * @return Returns the escaped string. + */ + escape(string?: string): string; + } + + interface LoDashImplicitWrapper { + /** + * @see _.escape + */ + escape(): string; + } + + interface LoDashExplicitWrapper { + /** + * @see _.escape + */ + escape(): LoDashExplicitWrapper; + } + + // escapeRegExp + + interface LoDashStatic { + /** + * Escapes the RegExp special characters "^", "$", "\", ".", "*", "+", "?", "(", ")", "[", "]", + * "{", "}", and "|" in string. + * + * @param string The string to escape. + * @return Returns the escaped string. + */ + escapeRegExp(string?: string): string; + } + + interface LoDashImplicitWrapper { + /** + * @see _.escapeRegExp + */ + escapeRegExp(): string; + } + + interface LoDashExplicitWrapper { + /** + * @see _.escapeRegExp + */ + escapeRegExp(): LoDashExplicitWrapper; + } + + // kebabCase + + interface LoDashStatic { + /** + * Converts string to kebab case. + * + * @param string The string to convert. + * @return Returns the kebab cased string. + */ + kebabCase(string?: string): string; + } + + interface LoDashImplicitWrapper { + /** + * @see _.kebabCase + */ + kebabCase(): string; + } + + interface LoDashExplicitWrapper { + /** + * @see _.kebabCase + */ + kebabCase(): LoDashExplicitWrapper; + } + + // lowerCase + + interface LoDashStatic { + /** + * Converts `string`, as space separated words, to lower case. + * + * @param string The string to convert. + * @return Returns the lower cased string. + */ + lowerCase(string?: string): string; + } + + interface LoDashImplicitWrapper { + /** + * @see _.lowerCase + */ + lowerCase(): string; + } + + interface LoDashExplicitWrapper { + /** + * @see _.lowerCase + */ + lowerCase(): LoDashExplicitWrapper; + } + + // lowerFirst + + interface LoDashStatic { + /** + * Converts the first character of `string` to lower case. + * + * @param string The string to convert. + * @return Returns the converted string. + */ + lowerFirst(string?: string): string; + } + + interface LoDashImplicitWrapper { + /** + * @see _.lowerFirst + */ + lowerFirst(): string; + } + + interface LoDashExplicitWrapper { + /** + * @see _.lowerFirst + */ + lowerFirst(): LoDashExplicitWrapper; + } + + // pad + + interface LoDashStatic { + /** + * Pads string on the left and right sides if it’s shorter than length. Padding characters are truncated if + * they can’t be evenly divided by length. + * + * @param string The string to pad. + * @param length The padding length. + * @param chars The string used as padding. + * @return Returns the padded string. + */ + pad( + string?: string, + length?: number, + chars?: string + ): string; + } + + interface LoDashImplicitWrapper { + /** + * @see _.pad + */ + pad( + length?: number, + chars?: string + ): string; + } + + interface LoDashExplicitWrapper { + /** + * @see _.pad + */ + pad( + length?: number, + chars?: string + ): LoDashExplicitWrapper; + } + + // padEnd + + interface LoDashStatic { + /** + * Pads string on the right side if it’s shorter than length. Padding characters are truncated if they exceed + * length. + * + * @param string The string to pad. + * @param length The padding length. + * @param chars The string used as padding. + * @return Returns the padded string. + */ + padEnd( + string?: string, + length?: number, + chars?: string + ): string; + } + + interface LoDashImplicitWrapper { + /** + * @see _.padEnd + */ + padEnd( + length?: number, + chars?: string + ): string; + } + + interface LoDashExplicitWrapper { + /** + * @see _.padEnd + */ + padEnd( + length?: number, + chars?: string + ): LoDashExplicitWrapper; + } + + // padStart + + interface LoDashStatic { + /** + * Pads string on the left side if it’s shorter than length. Padding characters are truncated if they exceed + * length. + * + * @param string The string to pad. + * @param length The padding length. + * @param chars The string used as padding. + * @return Returns the padded string. + */ + padStart( + string?: string, + length?: number, + chars?: string + ): string; + } + + interface LoDashImplicitWrapper { + /** + * @see _.padStart + */ + padStart( + length?: number, + chars?: string + ): string; + } + + interface LoDashExplicitWrapper { + /** + * @see _.padStart + */ + padStart( + length?: number, + chars?: string + ): LoDashExplicitWrapper; + } + + // parseInt + + interface LoDashStatic { + /** + * Converts string to an integer of the specified radix. If radix is undefined or 0, a radix of 10 is used + * unless value is a hexadecimal, in which case a radix of 16 is used. + * + * Note: This method aligns with the ES5 implementation of parseInt. + * + * @param string The string to convert. + * @param radix The radix to interpret value by. + * @return Returns the converted integer. + */ + parseInt( + string: string, + radix?: number + ): number; + } + + interface LoDashImplicitWrapper { + /** + * @see _.parseInt + */ + parseInt(radix?: number): number; + } + + interface LoDashExplicitWrapper { + /** + * @see _.parseInt + */ + parseInt(radix?: number): LoDashExplicitWrapper; + } + + // repeat + + interface LoDashStatic { + /** + * Repeats the given string n times. + * + * @param string The string to repeat. + * @param n The number of times to repeat the string. + * @return Returns the repeated string. + */ + repeat( + string?: string, + n?: number + ): string; + } + + interface LoDashImplicitWrapper { + /** + * @see _.repeat + */ + repeat(n?: number): string; + } + + interface LoDashExplicitWrapper { + /** + * @see _.repeat + */ + repeat(n?: number): LoDashExplicitWrapper; + } + + type ReplaceFunction = (match: string, ...args: any[]) => string; + + // replace + + interface LoDashStatic { + /** + * Replaces matches for pattern in string with replacement. + * + * Note: This method is based on String#replace. + * + * @return Returns the modified string. + */ + replace( + string: string, + pattern: RegExp | string, + replacement: ReplaceFunction | string + ): string; + + /** + * @see _.replace + */ + replace( + pattern: RegExp | string, + replacement: ReplaceFunction | string + ): string; + } + + interface LoDashImplicitWrapper { + /** + * @see _.replace + */ + replace( + pattern: RegExp|string, + replacement: ReplaceFunction | string + ): string; + + /** + * @see _.replace + */ + replace( + replacement: ReplaceFunction | string + ): string; + } + + interface LoDashExplicitWrapper { + /** + * @see _.replace + */ + replace( + pattern: RegExp | string, + replacement: ReplaceFunction | string + ): LoDashExplicitWrapper; + + /** + * @see _.replace + */ + replace( + replacement: ReplaceFunction | string + ): LoDashExplicitWrapper; + } + + // snakeCase + + interface LoDashStatic { + /** + * Converts string to snake case. + * + * @param string The string to convert. + * @return Returns the snake cased string. + */ + snakeCase(string?: string): string; + } + + interface LoDashImplicitWrapper { + /** + * @see _.snakeCase + */ + snakeCase(): string; + } + + interface LoDashExplicitWrapper { + /** + * @see _.snakeCase + */ + snakeCase(): LoDashExplicitWrapper; + } + + // split + + interface LoDashStatic { + /** + * Splits string by separator. + * + * Note: This method is based on String#split. + * + * @param string The string to trim. + * @param separator The separator pattern to split by. + * @param limit The length to truncate results to. + * @return Returns the new array of string segments. + */ + split( + string: string, + separator?: RegExp|string, + limit?: number + ): string[]; + + /** + * Splits string by separator. + * + * Note: This method is based on String#split. + * + * @param string The string to trim. + * @param index Not used in this overload. + * @param guard Enables use as an iteratee for methods like _.map. You should not pass this parameter directly in your code. + * @return Returns the new array of string segments. + */ + split( + string: string, + index: string | number, + guard: object + ): string[]; + } + + interface LoDashImplicitWrapper { + /** + * @see _.split + */ + split( + separator?: RegExp|string, + limit?: number + ): LoDashImplicitWrapper; + } + + interface LoDashExplicitWrapper { + /** + * @see _.split + */ + split( + separator?: RegExp|string, + limit?: number + ): LoDashExplicitWrapper; + } + + // startCase + + interface LoDashStatic { + /** + * Converts string to start case. + * + * @param string The string to convert. + * @return Returns the start cased string. + */ + startCase(string?: string): string; + } + + interface LoDashImplicitWrapper { + /** + * @see _.startCase + */ + startCase(): string; + } + + interface LoDashExplicitWrapper { + /** + * @see _.startCase + */ + startCase(): LoDashExplicitWrapper; + } + + // startsWith + + interface LoDashStatic { + /** + * Checks if string starts with the given target string. + * + * @param string The string to search. + * @param target The string to search for. + * @param position The position to search from. + * @return Returns true if string starts with target, else false. + */ + startsWith( + string?: string, + target?: string, + position?: number + ): boolean; + } + + interface LoDashImplicitWrapper { + /** + * @see _.startsWith + */ + startsWith( + target?: string, + position?: number + ): boolean; + } + + interface LoDashExplicitWrapper { + /** + * @see _.startsWith + */ + startsWith( + target?: string, + position?: number + ): LoDashExplicitWrapper; + } + + // template + + interface TemplateOptions extends TemplateSettings { + /** + * The sourceURL of the template's compiled source. + */ + sourceURL?: string; + } + + interface TemplateExecutor { + (data?: object): string; + source: string; + } + + interface LoDashStatic { + /** + * Creates a compiled template function that can interpolate data properties in "interpolate" delimiters, + * HTML-escape interpolated data properties in "escape" delimiters, and execute JavaScript in "evaluate" + * delimiters. Data properties may be accessed as free variables in the template. If a setting object is + * provided it takes precedence over _.templateSettings values. + * + * Note: In the development build _.template utilizes + * [sourceURLs](http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl) for easier + * debugging. + * + * For more information on precompiling templates see + * [lodash's custom builds documentation](https://lodash.com/custom-builds). + * + * For more information on Chrome extension sandboxes see + * [Chrome's extensions documentation](https://developer.chrome.com/extensions/sandboxingEval). + * + * @param string The template string. + * @param options The options object. + * @param options.escape The HTML "escape" delimiter. + * @param options.evaluate The "evaluate" delimiter. + * @param options.imports An object to import into the template as free variables. + * @param options.interpolate The "interpolate" delimiter. + * @param options.sourceURL The sourceURL of the template's compiled source. + * @param options.variable The data object variable name. + * @return Returns the compiled template function. + */ + template( + string?: string, + options?: TemplateOptions + ): TemplateExecutor; + } + + interface LoDashImplicitWrapper { + /** + * @see _.template + */ + template(options?: TemplateOptions): TemplateExecutor; + } + + interface LoDashExplicitWrapper { + /** + * @see _.template + */ + template(options?: TemplateOptions): LoDashExplicitWrapper; + } + + // toLower + + interface LoDashStatic { + /** + * Converts `string`, as a whole, to lower case. + * + * @param string The string to convert. + * @return Returns the lower cased string. + */ + toLower(string?: string): string; + } + + interface LoDashImplicitWrapper { + /** + * @see _.toLower + */ + toLower(): string; + } + + interface LoDashExplicitWrapper { + /** + * @see _.toLower + */ + toLower(): LoDashExplicitWrapper; + } + + // toUpper + + interface LoDashStatic { + /** + * Converts `string`, as a whole, to upper case. + * + * @param string The string to convert. + * @return Returns the upper cased string. + */ + toUpper(string?: string): string; + } + + interface LoDashImplicitWrapper { + /** + * @see _.toUpper + */ + toUpper(): string; + } + + interface LoDashExplicitWrapper { + /** + * @see _.toUpper + */ + toUpper(): LoDashExplicitWrapper; + } + + // trim + + interface LoDashStatic { + /** + * Removes leading and trailing whitespace or specified characters from string. + * + * @param string The string to trim. + * @param chars The characters to trim. + * @return Returns the trimmed string. + */ + trim( + string?: string, + chars?: string + ): string; + + /** + * Removes leading and trailing whitespace or specified characters from string. + * + * @param string The string to trim. + * @param index Not used in this overload. + * @param guard Enables use as an iteratee for methods like _.map. You should not pass this parameter directly in your code. + * @return Returns the trimmed string. + */ + trim( + string: string, + index: string | number, + guard: object + ): string; + } + + interface LoDashImplicitWrapper { + /** + * @see _.trim + */ + trim(chars?: string): string; + } + + interface LoDashExplicitWrapper { + /** + * @see _.trim + */ + trim(chars?: string): LoDashExplicitWrapper; + } + + // trimEnd + + interface LoDashStatic { + /** + * Removes trailing whitespace or specified characters from string. + * + * @param string The string to trim. + * @param chars The characters to trim. + * @return Returns the trimmed string. + */ + trimEnd( + string?: string, + chars?: string + ): string; + + /** + * Removes trailing whitespace or specified characters from string. + * + * @param string The string to trim. + * @param index Not used in this overload. + * @param guard Enables use as an iteratee for methods like _.map. You should not pass this parameter directly in your code. + * @return Returns the trimmed string. + */ + trimEnd( + string: string, + index: string | number, + guard: object + ): string; + } + + interface LoDashImplicitWrapper { + /** + * @see _.trimEnd + */ + trimEnd(chars?: string): string; + } + + interface LoDashExplicitWrapper { + /** + * @see _.trimEnd + */ + trimEnd(chars?: string): LoDashExplicitWrapper; + } + + // trimStart + + interface LoDashStatic { + /** + * Removes leading whitespace or specified characters from string. + * + * @param string The string to trim. + * @param chars The characters to trim. + * @return Returns the trimmed string. + */ + trimStart( + string?: string, + chars?: string + ): string; + + /** + * Removes leading whitespace or specified characters from string. + * + * @param string The string to trim. + * @param index Not used in this overload. + * @param guard Enables use as an iteratee for methods like _.map. You should not pass this parameter directly in your code. + * @return Returns the trimmed string. + */ + trimStart( + string: string, + index: string | number, + guard: object + ): string; + } + + interface LoDashImplicitWrapper { + /** + * @see _.trimStart + */ + trimStart(chars?: string): string; + } + + interface LoDashExplicitWrapper { + /** + * @see _.trimStart + */ + trimStart(chars?: string): LoDashExplicitWrapper; + } + + // truncate + + interface TruncateOptions { + /** The maximum string length. */ + length?: number; + /** The string to indicate text is omitted. */ + omission?: string; + /** The separator pattern to truncate to. */ + separator?: string|RegExp; + } + + interface LoDashStatic { + /** + * Truncates string if it’s longer than the given maximum string length. The last characters of the truncated + * string are replaced with the omission string which defaults to "…". + * + * @param string The string to truncate. + * @param options The options object or maximum string length. + * @return Returns the truncated string. + */ + truncate( + string?: string, + options?: TruncateOptions + ): string; + } + + interface LoDashImplicitWrapper { + /** + * @see _.truncate + */ + truncate(options?: TruncateOptions): string; + } + + interface LoDashExplicitWrapper { + /** + * @see _.truncate + */ + truncate(options?: TruncateOptions): LoDashExplicitWrapper; + } + + // unescape + + interface LoDashStatic { + /** + * The inverse of _.escape; this method converts the HTML entities &, <, >, ", ', and ` + * in string to their corresponding characters. + * + * Note: No other HTML entities are unescaped. To unescape additional HTML entities use a third-party library + * like he. + * + * @param string The string to unescape. + * @return Returns the unescaped string. + */ + unescape(string?: string): string; + } + + interface LoDashImplicitWrapper { + /** + * @see _.unescape + */ + unescape(): string; + } + + interface LoDashExplicitWrapper { + /** + * @see _.unescape + */ + unescape(): LoDashExplicitWrapper; + } + + // upperCase + + interface LoDashStatic { + /** + * Converts `string`, as space separated words, to upper case. + * + * @param string The string to convert. + * @return Returns the upper cased string. + */ + upperCase(string?: string): string; + } + + interface LoDashImplicitWrapper { + /** + * @see _.upperCase + */ + upperCase(): string; + } + + interface LoDashExplicitWrapper { + /** + * @see _.upperCase + */ + upperCase(): LoDashExplicitWrapper; + } + + // upperFirst + + interface LoDashStatic { + /** + * Converts the first character of `string` to upper case. + * + * @param string The string to convert. + * @return Returns the converted string. + */ + upperFirst(string?: string): string; + } + + interface LoDashImplicitWrapper { + /** + * @see _.upperFirst + */ + upperFirst(): string; + } + + interface LoDashExplicitWrapper { + /** + * @see _.upperFirst + */ + upperFirst(): LoDashExplicitWrapper; + } + + // words + + interface LoDashStatic { + /** + * Splits `string` into an array of its words. + * + * @param string The string to inspect. + * @param pattern The pattern to match words. + * @return Returns the words of `string`. + */ + words( + string?: string, + pattern?: string|RegExp + ): string[]; + + /** + * Splits `string` into an array of its words. + * + * @param string The string to inspect. + * @param index Not used in this overload. + * @param guard Enables use as an iteratee for methods like _.map. You should not pass this parameter directly in your code. + * @return Returns the words of `string`. + */ + words( + string: string, + index: string | number, + guard: object + ): string[]; + } + + interface LoDashImplicitWrapper { + /** + * @see _.words + */ + words(pattern?: string|RegExp): string[]; + } + + interface LoDashExplicitWrapper { + /** + * @see _.words + */ + words(pattern?: string|RegExp): LoDashExplicitWrapper; + } +} diff --git a/node_modules/@types/lodash/common/util.d.ts b/node_modules/@types/lodash/common/util.d.ts new file mode 100644 index 0000000..80b0677 --- /dev/null +++ b/node_modules/@types/lodash/common/util.d.ts @@ -0,0 +1,1463 @@ +import _ = require("../index"); +declare module "../index" { + // attempt + + interface LoDashStatic { + /** + * Attempts to invoke func, returning either the result or the caught error object. Any additional arguments + * are provided to func when it’s invoked. + * + * @param func The function to attempt. + * @return Returns the func result or error object. + */ + attempt(func: (...args: any[]) => TResult, ...args: any[]): TResult|Error; + } + + interface LoDashImplicitWrapper { + /** + * @see _.attempt + */ + attempt(...args: any[]): TResult|Error; + } + + interface LoDashExplicitWrapper { + /** + * @see _.attempt + */ + attempt(...args: any[]): LoDashExplicitWrapper; + } + + // bindAll + + interface LoDashStatic { + /** + * Binds methods of an object to the object itself, overwriting the existing method. Method names may be + * specified as individual arguments or as arrays of method names. If no method names are provided all + * enumerable function properties, own and inherited, of object are bound. + * + * Note: This method does not set the "length" property of bound functions. + * + * @param object The object to bind and assign the bound methods to. + * @param methodNames The object method names to bind, specified as individual method names or arrays of + * method names. + * @return Returns object. + */ + bindAll( + object: T, + ...methodNames: Array> + ): T; + } + + interface LoDashWrapper { + /** + * @see _.bindAll + */ + bindAll(...methodNames: Array>): this; + } + + // cond + + interface LoDashStatic { + /** + * Creates a function that iterates over `pairs` and invokes the corresponding + * function of the first predicate to return truthy. The predicate-function + * pairs are invoked with the `this` binding and arguments of the created + * function. + * + * @since 4.0.0 + * @category Util + * @param pairs The predicate-function pairs. + * @returns Returns the new composite function. + * @example + * + * var func = _.cond([ + * [_.matches({ 'a': 1 }), _.constant('matches A')], + * [_.conforms({ 'b': _.isNumber }), _.constant('matches B')], + * [_.stubTrue, _.constant('no match')] + * ]); + * + * func({ 'a': 1, 'b': 2 }); + * // => 'matches A' + * + * func({ 'a': 0, 'b': 1 }); + * // => 'matches B' + * + * func({ 'a': '1', 'b': '2' }); + * // => 'no match' + */ + cond(pairs: Array>): (Target: T) => R; + } + + // conforms + + type ConformsPredicateObject = { + [P in keyof T]?: (val: T[P]) => boolean; + }; + + interface LoDashStatic { + /** + * Creates a function that invokes the predicate properties of `source` with the corresponding + * property values of a given object, returning true if all predicates return truthy, else false. + */ + conforms(source: ConformsPredicateObject): (value: T) => boolean; + } + + interface LoDashImplicitWrapper { + /** + * @see _.conforms + */ + conforms(this: LoDashImplicitWrapper>): LoDashImplicitWrapper<(value: T) => boolean>; + } + + interface LoDashExplicitWrapper { + /** + * @see _.conforms + */ + conforms(this: LoDashExplicitWrapper>): LoDashExplicitWrapper<(value: T) => boolean>; + } + + // constant + + interface LoDashStatic { + /** + * Creates a function that returns value. + * + * @param value The value to return from the new function. + * @return Returns the new function. + */ + constant(value: T): () => T; + } + + interface LoDashImplicitWrapper { + /** + * @see _.constant + */ + constant(): LoDashImplicitWrapper<() => TValue>; + } + + interface LoDashExplicitWrapper { + /** + * @see _.constant + */ + constant(): LoDashExplicitWrapper<() => TValue>; + } + + // defaultTo + + interface LoDashStatic { + /** + * Checks `value` to determine whether a default value should be returned in + * its place. The `defaultValue` is returned if `value` is `NaN`, `null`, + * or `undefined`. + * + * @param value The value to check. + * @param defaultValue The default value. + * @returns Returns the resolved value. + */ + defaultTo(value: T | null | undefined, defaultValue: T): T; + + /** + * @see _.defaultTo + */ + defaultTo( + value: T | null | undefined, + defaultValue: TDefault + ): T | TDefault; + } + + interface LoDashImplicitWrapper { + /** + * @see _.defaultTo + */ + defaultTo(this: LoDashImplicitWrapper, defaultValue: T): T; + + /** + * @see _.defaultTo + */ + defaultTo( + this: LoDashImplicitWrapper, + defaultValue: TDefault + ): T | TDefault; + } + + interface LoDashExplicitWrapper { + /** + * @see _.defaultTo + */ + defaultTo(this: LoDashExplicitWrapper, defaultValue: T): LoDashExplicitWrapper; + + /** + * @see _.defaultTo + */ + defaultTo( + this: LoDashExplicitWrapper, + defaultValue: TDefault + ): LoDashExplicitWrapper; + } + + // flow + + interface LoDashStatic { + /** + * Creates a function that returns the result of invoking the provided functions with the this binding of the + * created function, where each successive invocation is supplied the return value of the previous. + * + * @param funcs Functions to invoke. + * @return Returns the new function. + */ + // 0-argument first function + flow(f1: () => R1, f2: (a: R1) => R2): () => R2; + flow(f1: () => R1, f2: (a: R1) => R2, f3: (a: R2) => R3): () => R3; + flow(f1: () => R1, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4): () => R4; + flow(f1: () => R1, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5): () => R5; + flow(f1: () => R1, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6): () => R6; + flow(f1: () => R1, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6, f7: (a: R6) => R7): () => R7; + flow(f1: () => R1, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6, f7: (a: R6) => R7, ...funcs: Array any>>): () => any; + // 1-argument first function + flow(f1: (a1: A1) => R1, f2: (a: R1) => R2): (a1: A1) => R2; + flow(f1: (a1: A1) => R1, f2: (a: R1) => R2, f3: (a: R2) => R3): (a1: A1) => R3; + flow(f1: (a1: A1) => R1, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4): (a1: A1) => R4; + flow(f1: (a1: A1) => R1, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5): (a1: A1) => R5; + flow(f1: (a1: A1) => R1, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6): (a1: A1) => R6; + flow(f1: (a1: A1) => R1, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6, f7: (a: R6) => R7): (a1: A1) => R7; + flow(f1: (a1: A1) => R1, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6, f7: (a: R6) => R7, ...funcs: Array any>>): (a1: A1) => any; + // 2-argument first function + flow(f1: (a1: A1, a2: A2) => R1, f2: (a: R1) => R2): (a1: A1, a2: A2) => R2; + flow(f1: (a1: A1, a2: A2) => R1, f2: (a: R1) => R2, f3: (a: R2) => R3): (a1: A1, a2: A2) => R3; + flow(f1: (a1: A1, a2: A2) => R1, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4): (a1: A1, a2: A2) => R4; + flow(f1: (a1: A1, a2: A2) => R1, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5): (a1: A1, a2: A2) => R5; + flow(f1: (a1: A1, a2: A2) => R1, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6): (a1: A1, a2: A2) => R6; + flow(f1: (a1: A1, a2: A2) => R1, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6, f7: (a: R6) => R7): (a1: A1, a2: A2) => R7; + flow(f1: (a1: A1, a2: A2) => R1, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6, f7: (a: R6) => R7, ...funcs: Array any>>): (a1: A1, a2: A2) => any; + // 3-argument first function + flow(f1: (a1: A1, a2: A2, a3: A3) => R1, f2: (a: R1) => R2): (a1: A1, a2: A2, a3: A3) => R2; + flow(f1: (a1: A1, a2: A2, a3: A3) => R1, f2: (a: R1) => R2, f3: (a: R2) => R3): (a1: A1, a2: A2, a3: A3) => R3; + flow(f1: (a1: A1, a2: A2, a3: A3) => R1, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4): (a1: A1, a2: A2, a3: A3) => R4; + flow(f1: (a1: A1, a2: A2, a3: A3) => R1, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5): (a1: A1, a2: A2, a3: A3) => R5; + flow(f1: (a1: A1, a2: A2, a3: A3) => R1, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6): (a1: A1, a2: A2, a3: A3) => R6; + flow(f1: (a1: A1, a2: A2, a3: A3) => R1, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6, f7: (a: R6) => R7): (a1: A1, a2: A2, a3: A3) => R7; + flow(f1: (a1: A1, a2: A2, a3: A3) => R1, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6, f7: (a: R6) => R7, ...funcs: Array any>>): (a1: A1, a2: A2, a3: A3) => any; + // 4-argument first function + flow(f1: (a1: A1, a2: A2, a3: A3, a4: A4) => R1, f2: (a: R1) => R2): (a1: A1, a2: A2, a3: A3, a4: A4) => R2; + flow(f1: (a1: A1, a2: A2, a3: A3, a4: A4) => R1, f2: (a: R1) => R2, f3: (a: R2) => R3): (a1: A1, a2: A2, a3: A3, a4: A4) => R3; + flow(f1: (a1: A1, a2: A2, a3: A3, a4: A4) => R1, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4): (a1: A1, a2: A2, a3: A3, a4: A4) => R4; + flow(f1: (a1: A1, a2: A2, a3: A3, a4: A4) => R1, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5): (a1: A1, a2: A2, a3: A3, a4: A4) => R5; + flow(f1: (a1: A1, a2: A2, a3: A3, a4: A4) => R1, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6): (a1: A1, a2: A2, a3: A3, a4: A4) => R6; + flow(f1: (a1: A1, a2: A2, a3: A3, a4: A4) => R1, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6, f7: (a: R6) => R7): (a1: A1, a2: A2, a3: A3, a4: A4) => R7; + flow(f1: (a1: A1, a2: A2, a3: A3, a4: A4) => R1, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6, f7: (a: R6) => R7, ...funcs: Array any>>): (a1: A1, a2: A2, a3: A3, a4: A4) => any; + // any-argument first function + flow(f1: (a1: A1, a2: A2, a3: A3, a4: A4, ...args: any[]) => R1, f2: (a: R1) => R2): (a1: A1, a2: A2, a3: A3, a4: A4, ...args: any[]) => R2; + flow(f1: (a1: A1, a2: A2, a3: A3, a4: A4, ...args: any[]) => R1, f2: (a: R1) => R2, f3: (a: R2) => R3): (a1: A1, a2: A2, a3: A3, a4: A4, ...args: any[]) => R3; + flow(f1: (a1: A1, a2: A2, a3: A3, a4: A4, ...args: any[]) => R1, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4): (a1: A1, a2: A2, a3: A3, a4: A4, ...args: any[]) => R4; + flow(f1: (a1: A1, a2: A2, a3: A3, a4: A4, ...args: any[]) => R1, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5): (a1: A1, a2: A2, a3: A3, a4: A4, ...args: any[]) => R5; + flow(f1: (a1: A1, a2: A2, a3: A3, a4: A4, ...args: any[]) => R1, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6): (a1: A1, a2: A2, a3: A3, a4: A4, ...args: any[]) => R6; + flow(f1: (a1: A1, a2: A2, a3: A3, a4: A4, ...args: any[]) => R1, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6, f7: (a: R6) => R7): (a1: A1, a2: A2, a3: A3, a4: A4, ...args: any[]) => R7; + flow(f1: (a1: A1, a2: A2, a3: A3, a4: A4, ...args: any[]) => R1, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6, f7: (a: R6) => R7, ...funcs: Array any>>): (a1: A1, a2: A2, a3: A3, a4: A4, ...args: any[]) => any; + flow(funcs: Array any>>): (...args: any[]) => any; + } + + interface LoDashImplicitWrapper { + /** + * @see _.flow + */ + // 0-argument first function + flow(this: LoDashImplicitWrapper<() => R1>, f2: (a: R1) => R2): LoDashImplicitWrapper<() => R2>; + flow(this: LoDashImplicitWrapper<() => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3): LoDashImplicitWrapper<() => R3>; + flow(this: LoDashImplicitWrapper<() => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4): LoDashImplicitWrapper<() => R4>; + flow(this: LoDashImplicitWrapper<() => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5): LoDashImplicitWrapper<() => R5>; + flow(this: LoDashImplicitWrapper<() => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6): LoDashImplicitWrapper<() => R6>; + flow(this: LoDashImplicitWrapper<() => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6, f7: (a: R6) => R7): LoDashImplicitWrapper<() => R7>; + flow(this: LoDashImplicitWrapper<() => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6, f7: (a: R6) => R7, ...funcs: Array any>>): LoDashImplicitWrapper<() => any>; + // 1-argument first function + flow(this: LoDashImplicitWrapper<(a1: A1) => R1>, f2: (a: R1) => R2): LoDashImplicitWrapper<(a1: A1) => R2>; + flow(this: LoDashImplicitWrapper<(a1: A1) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3): LoDashImplicitWrapper<(a1: A1) => R3>; + flow(this: LoDashImplicitWrapper<(a1: A1) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4): LoDashImplicitWrapper<(a1: A1) => R4>; + flow(this: LoDashImplicitWrapper<(a1: A1) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5): LoDashImplicitWrapper<(a1: A1) => R5>; + flow(this: LoDashImplicitWrapper<(a1: A1) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6): LoDashImplicitWrapper<(a1: A1) => R6>; + flow(this: LoDashImplicitWrapper<(a1: A1) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6, f7: (a: R6) => R7): LoDashImplicitWrapper<(a1: A1) => R7>; + flow(this: LoDashImplicitWrapper<(a1: A1) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6, f7: (a: R6) => R7, ...funcs: Array any>>): LoDashImplicitWrapper<(a1: A1) => any>; + // 2-argument first function + flow(this: LoDashImplicitWrapper<(a1: A1, a2: A2) => R1>, f2: (a: R1) => R2): LoDashImplicitWrapper<(a1: A1, a2: A2) => R2>; + flow(this: LoDashImplicitWrapper<(a1: A1, a2: A2) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3): LoDashImplicitWrapper<(a1: A1, a2: A2) => R3>; + flow(this: LoDashImplicitWrapper<(a1: A1, a2: A2) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4): LoDashImplicitWrapper<(a1: A1, a2: A2) => R4>; + flow(this: LoDashImplicitWrapper<(a1: A1, a2: A2) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5): LoDashImplicitWrapper<(a1: A1, a2: A2) => R5>; + flow(this: LoDashImplicitWrapper<(a1: A1, a2: A2) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6): LoDashImplicitWrapper<(a1: A1, a2: A2) => R6>; + flow(this: LoDashImplicitWrapper<(a1: A1, a2: A2) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6, f7: (a: R6) => R7): LoDashImplicitWrapper<(a1: A1, a2: A2) => R7>; + flow(this: LoDashImplicitWrapper<(a1: A1, a2: A2) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6, f7: (a: R6) => R7, ...funcs: Array any>>): LoDashImplicitWrapper<(a1: A1, a2: A2) => any>; + // 3-argument first function + flow(this: LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3) => R1>, f2: (a: R1) => R2): LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3) => R2>; + flow(this: LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3): LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3) => R3>; + flow(this: LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4): LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3) => R4>; + flow(this: LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5): LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3) => R5>; + flow(this: LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6): LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3) => R6>; + flow(this: LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6, f7: (a: R6) => R7): LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3) => R7>; + flow(this: LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6, f7: (a: R6) => R7, ...funcs: Array any>>): LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3) => any>; + // 4-argument first function + flow(this: LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4) => R1>, f2: (a: R1) => R2): LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4) => R2>; + flow(this: LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3): LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4) => R3>; + flow(this: LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4): LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4) => R4>; + flow(this: LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5): LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4) => R5>; + flow(this: LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6): LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4) => R6>; + flow(this: LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6, f7: (a: R6) => R7): LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4) => R7>; + flow(this: LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6, f7: (a: R6) => R7, ...funcs: Array any>>): LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4) => any>; + // any-argument first function + flow(this: LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4, ...args: any[]) => R1>, f2: (a: R1) => R2): LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4, ...args: any[]) => R2>; + flow(this: LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4, ...args: any[]) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3): LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4, ...args: any[]) => R3>; + flow(this: LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4, ...args: any[]) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4): LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4, ...args: any[]) => R4>; + flow(this: LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4, ...args: any[]) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5): LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4, ...args: any[]) => R5>; + flow(this: LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4, ...args: any[]) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6): LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4, ...args: any[]) => R6>; + flow(this: LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4, ...args: any[]) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6, f7: (a: R6) => R7): LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4, ...args: any[]) => R7>; + flow(this: LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4, ...args: any[]) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6, f7: (a: R6) => R7, ...funcs: Array any>>): LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4, ...args: any[]) => any>; + flow(this: LoDashImplicitWrapper<(...args: any[]) => any>, funcs: Array any>>): LoDashImplicitWrapper<(...args: any[]) => any>; + } + + interface LoDashExplicitWrapper { + /** + * @see _.flow + */ + // 0-argument first function + flow(this: LoDashExplicitWrapper<() => R1>, f2: (a: R1) => R2): LoDashExplicitWrapper<() => R2>; + flow(this: LoDashExplicitWrapper<() => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3): LoDashExplicitWrapper<() => R3>; + flow(this: LoDashExplicitWrapper<() => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4): LoDashExplicitWrapper<() => R4>; + flow(this: LoDashExplicitWrapper<() => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5): LoDashExplicitWrapper<() => R5>; + flow(this: LoDashExplicitWrapper<() => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6): LoDashExplicitWrapper<() => R6>; + flow(this: LoDashExplicitWrapper<() => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6, f7: (a: R6) => R7): LoDashExplicitWrapper<() => R7>; + flow(this: LoDashExplicitWrapper<() => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6, f7: (a: R6) => R7, ...funcs: Array any>>): LoDashExplicitWrapper<() => any>; + // 1-argument first function + flow(this: LoDashExplicitWrapper<(a1: A1) => R1>, f2: (a: R1) => R2): LoDashExplicitWrapper<(a1: A1) => R2>; + flow(this: LoDashExplicitWrapper<(a1: A1) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3): LoDashExplicitWrapper<(a1: A1) => R3>; + flow(this: LoDashExplicitWrapper<(a1: A1) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4): LoDashExplicitWrapper<(a1: A1) => R4>; + flow(this: LoDashExplicitWrapper<(a1: A1) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5): LoDashExplicitWrapper<(a1: A1) => R5>; + flow(this: LoDashExplicitWrapper<(a1: A1) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6): LoDashExplicitWrapper<(a1: A1) => R6>; + flow(this: LoDashExplicitWrapper<(a1: A1) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6, f7: (a: R6) => R7): LoDashExplicitWrapper<(a1: A1) => R7>; + flow(this: LoDashExplicitWrapper<(a1: A1) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6, f7: (a: R6) => R7, ...funcs: Array any>>): LoDashExplicitWrapper<(a1: A1) => any>; + // 2-argument first function + flow(this: LoDashExplicitWrapper<(a1: A1, a2: A2) => R1>, f2: (a: R1) => R2): LoDashExplicitWrapper<(a1: A1, a2: A2) => R2>; + flow(this: LoDashExplicitWrapper<(a1: A1, a2: A2) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3): LoDashExplicitWrapper<(a1: A1, a2: A2) => R3>; + flow(this: LoDashExplicitWrapper<(a1: A1, a2: A2) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4): LoDashExplicitWrapper<(a1: A1, a2: A2) => R4>; + flow(this: LoDashExplicitWrapper<(a1: A1, a2: A2) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5): LoDashExplicitWrapper<(a1: A1, a2: A2) => R5>; + flow(this: LoDashExplicitWrapper<(a1: A1, a2: A2) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6): LoDashExplicitWrapper<(a1: A1, a2: A2) => R6>; + flow(this: LoDashExplicitWrapper<(a1: A1, a2: A2) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6, f7: (a: R6) => R7): LoDashExplicitWrapper<(a1: A1, a2: A2) => R7>; + flow(this: LoDashExplicitWrapper<(a1: A1, a2: A2) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6, f7: (a: R6) => R7, ...funcs: Array any>>): LoDashExplicitWrapper<(a1: A1, a2: A2) => any>; + // 3-argument first function + flow(this: LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3) => R1>, f2: (a: R1) => R2): LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3) => R2>; + flow(this: LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3): LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3) => R3>; + flow(this: LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4): LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3) => R4>; + flow(this: LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5): LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3) => R5>; + flow(this: LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6): LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3) => R6>; + flow(this: LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6, f7: (a: R6) => R7): LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3) => R7>; + flow(this: LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6, f7: (a: R6) => R7, ...funcs: Array any>>): LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3) => any>; + // 4-argument first function + flow(this: LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4) => R1>, f2: (a: R1) => R2): LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4) => R2>; + flow(this: LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3): LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4) => R3>; + flow(this: LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4): LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4) => R4>; + flow(this: LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5): LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4) => R5>; + flow(this: LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6): LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4) => R6>; + flow(this: LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6, f7: (a: R6) => R7): LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4) => R7>; + flow(this: LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6, f7: (a: R6) => R7, ...funcs: Array any>>): LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4) => any>; + // any-argument first function + flow(this: LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4, ...args: any[]) => R1>, f2: (a: R1) => R2): LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4, ...args: any[]) => R2>; + flow(this: LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4, ...args: any[]) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3): LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4, ...args: any[]) => R3>; + flow(this: LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4, ...args: any[]) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4): LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4, ...args: any[]) => R4>; + flow(this: LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4, ...args: any[]) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5): LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4, ...args: any[]) => R5>; + flow(this: LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4, ...args: any[]) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6): LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4, ...args: any[]) => R6>; + flow(this: LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4, ...args: any[]) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6, f7: (a: R6) => R7): LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4, ...args: any[]) => R7>; + flow(this: LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4, ...args: any[]) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6, f7: (a: R6) => R7, ...funcs: Array any>>): LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4, ...args: any[]) => any>; + flow(this: LoDashExplicitWrapper<(...args: any[]) => any>, funcs: Array any>>): LoDashExplicitWrapper<(...args: any[]) => any>; + } + + // flowRight + + interface LoDashStatic { + /** + * This method is like _.flow except that it creates a function that invokes the provided functions from right + * to left. + * + * @param funcs Functions to invoke. + * @return Returns the new function. + */ + // 0-argument first function + flowRight(f2: (a: R1) => R2, f1: () => R1): () => R2; + flowRight(f3: (a: R2) => R3, f2: (a: R1) => R2, f1: () => R1): () => R3; + flowRight(f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: () => R1): () => R4; + flowRight(f5: (a: R4) => R5, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: () => R1): () => R5; + flowRight(f6: (a: R5) => R6, f5: (a: R4) => R5, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: () => R1): () => R6; + flowRight(f7: (a: R6) => R7, f6: (a: R5) => R6, f5: (a: R4) => R5, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: () => R1): () => R7; + // 1-argument first function + flowRight(f2: (a: R1) => R2, f1: (a1: A1) => R1): (a1: A1) => R2; + flowRight(f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1) => R1): (a1: A1) => R3; + flowRight(f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1) => R1): (a1: A1) => R4; + flowRight(f5: (a: R4) => R5, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1) => R1): (a1: A1) => R5; + flowRight(f6: (a: R5) => R6, f5: (a: R4) => R5, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1) => R1): (a1: A1) => R6; + flowRight(f7: (a: R6) => R7, f6: (a: R5) => R6, f5: (a: R4) => R5, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1) => R1): (a1: A1) => R7; + // 2-argument first function + flowRight(f2: (a: R1) => R2, f1: (a1: A1, a2: A2) => R1): (a1: A1, a2: A2) => R2; + flowRight(f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1, a2: A2) => R1): (a1: A1, a2: A2) => R3; + flowRight(f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1, a2: A2) => R1): (a1: A1, a2: A2) => R4; + flowRight(f5: (a: R4) => R5, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1, a2: A2) => R1): (a1: A1, a2: A2) => R5; + flowRight(f6: (a: R5) => R6, f5: (a: R4) => R5, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1, a2: A2) => R1): (a1: A1, a2: A2) => R6; + flowRight(f7: (a: R6) => R7, f6: (a: R5) => R6, f5: (a: R4) => R5, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1, a2: A2) => R1): (a1: A1, a2: A2) => R7; + // 3-argument first function + flowRight(f2: (a: R1) => R2, f1: (a1: A1, a2: A2, a3: A3) => R1): (a1: A1, a2: A2, a3: A3) => R2; + flowRight(f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1, a2: A2, a3: A3) => R1): (a1: A1, a2: A2, a3: A3) => R3; + flowRight(f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1, a2: A2, a3: A3) => R1): (a1: A1, a2: A2, a3: A3) => R4; + flowRight(f5: (a: R4) => R5, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1, a2: A2, a3: A3) => R1): (a1: A1, a2: A2, a3: A3) => R5; + flowRight(f6: (a: R5) => R6, f5: (a: R4) => R5, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1, a2: A2, a3: A3) => R1): (a1: A1, a2: A2, a3: A3) => R6; + flowRight(f7: (a: R6) => R7, f6: (a: R5) => R6, f5: (a: R4) => R5, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1, a2: A2, a3: A3) => R1): (a1: A1, a2: A2, a3: A3) => R7; + // 4-argument first function + flowRight(f2: (a: R1) => R2, f1: (a1: A1, a2: A2, a3: A3, a4: A4) => R1): (a1: A1, a2: A2, a3: A3, a4: A4) => R2; + flowRight(f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1, a2: A2, a3: A3, a4: A4) => R1): (a1: A1, a2: A2, a3: A3, a4: A4) => R3; + flowRight(f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1, a2: A2, a3: A3, a4: A4) => R1): (a1: A1, a2: A2, a3: A3, a4: A4) => R4; + flowRight(f5: (a: R4) => R5, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1, a2: A2, a3: A3, a4: A4) => R1): (a1: A1, a2: A2, a3: A3, a4: A4) => R5; + flowRight(f6: (a: R5) => R6, f5: (a: R4) => R5, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1, a2: A2, a3: A3, a4: A4) => R1): (a1: A1, a2: A2, a3: A3, a4: A4) => R6; + flowRight(f7: (a: R6) => R7, f6: (a: R5) => R6, f5: (a: R4) => R5, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1, a2: A2, a3: A3, a4: A4) => R1): (a1: A1, a2: A2, a3: A3, a4: A4) => R7; + // any-argument first function + flowRight(f2: (a: R1) => R2, f1: (...args: any[]) => R1): (...args: any[]) => R2; + flowRight(f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (...args: any[]) => R1): (...args: any[]) => R3; + flowRight(f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (...args: any[]) => R1): (...args: any[]) => R4; + flowRight(f5: (a: R4) => R5, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (...args: any[]) => R1): (...args: any[]) => R5; + flowRight(f6: (a: R5) => R6, f5: (a: R4) => R5, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (...args: any[]) => R1): (...args: any[]) => R6; + flowRight(f7: (a: R6) => R7, f6: (a: R5) => R6, f5: (a: R4) => R5, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (...args: any[]) => R1): (...args: any[]) => R7; + flowRight(f7: (a: any) => any, f6: (a: any) => any, f5: (a: any) => any, f4: (a: any) => any, f3: (a: any) => any, f2: (a: any) => any, f1: () => any, ...funcs: Array any>>): (...args: any[]) => any; + flowRight(funcs: Array any>>): (...args: any[]) => any; + } + + interface LoDashImplicitWrapper { + /** + * @see _.flowRight + */ + // 0-argument first function + flowRight(this: LoDashImplicitWrapper<(a: R1) => R2>, f1: () => R1): LoDashImplicitWrapper<() => R2>; + flowRight(this: LoDashImplicitWrapper<(a: R2) => R3>, f2: (a: R1) => R2, f1: () => R1): LoDashImplicitWrapper<() => R3>; + flowRight(this: LoDashImplicitWrapper<(a: R3) => R4>, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: () => R1): LoDashImplicitWrapper<() => R4>; + flowRight(this: LoDashImplicitWrapper<(a: R4) => R5>, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: () => R1): LoDashImplicitWrapper<() => R5>; + flowRight(this: LoDashImplicitWrapper<(a: R5) => R6>, f5: (a: R4) => R5, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: () => R1): LoDashImplicitWrapper<() => R6>; + flowRight(this: LoDashImplicitWrapper<(a: R6) => R7>, f6: (a: R5) => R6, f5: (a: R4) => R5, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: () => R1): LoDashImplicitWrapper<() => R7>; + // 1-argument first function + flowRight(this: LoDashImplicitWrapper<(a: R1) => R2>, f1: (a1: A1) => R1): LoDashImplicitWrapper<(a1: A1) => R2>; + flowRight(this: LoDashImplicitWrapper<(a: R2) => R3>, f2: (a: R1) => R2, f1: (a1: A1) => R1): LoDashImplicitWrapper<(a1: A1) => R3>; + flowRight(this: LoDashImplicitWrapper<(a: R3) => R4>, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1) => R1): LoDashImplicitWrapper<(a1: A1) => R4>; + flowRight(this: LoDashImplicitWrapper<(a: R4) => R5>, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1) => R1): LoDashImplicitWrapper<(a1: A1) => R5>; + flowRight(this: LoDashImplicitWrapper<(a: R5) => R6>, f5: (a: R4) => R5, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1) => R1): LoDashImplicitWrapper<(a1: A1) => R6>; + flowRight(this: LoDashImplicitWrapper<(a: R6) => R7>, f6: (a: R5) => R6, f5: (a: R4) => R5, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1) => R1): LoDashImplicitWrapper<(a1: A1) => R7>; + // 2-argument first function + flowRight(this: LoDashImplicitWrapper<(a: R1) => R2>, f1: (a1: A1, a2: A2) => R1): LoDashImplicitWrapper<(a1: A1, a2: A2) => R2>; + flowRight(this: LoDashImplicitWrapper<(a: R2) => R3>, f2: (a: R1) => R2, f1: (a1: A1, a2: A2) => R1): LoDashImplicitWrapper<(a1: A1, a2: A2) => R3>; + flowRight(this: LoDashImplicitWrapper<(a: R3) => R4>, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1, a2: A2) => R1): LoDashImplicitWrapper<(a1: A1, a2: A2) => R4>; + flowRight(this: LoDashImplicitWrapper<(a: R4) => R5>, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1, a2: A2) => R1): LoDashImplicitWrapper<(a1: A1, a2: A2) => R5>; + flowRight(this: LoDashImplicitWrapper<(a: R5) => R6>, f5: (a: R4) => R5, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1, a2: A2) => R1): LoDashImplicitWrapper<(a1: A1, a2: A2) => R6>; + flowRight(this: LoDashImplicitWrapper<(a: R6) => R7>, f6: (a: R5) => R6, f5: (a: R4) => R5, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1, a2: A2) => R1): LoDashImplicitWrapper<(a1: A1, a2: A2) => R7>; + // 3-argument first function + flowRight(this: LoDashImplicitWrapper<(a: R1) => R2>, f1: (a1: A1, a2: A2, a3: A3) => R1): LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3) => R2>; + flowRight(this: LoDashImplicitWrapper<(a: R2) => R3>, f2: (a: R1) => R2, f1: (a1: A1, a2: A2, a3: A3) => R1): LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3) => R3>; + flowRight(this: LoDashImplicitWrapper<(a: R3) => R4>, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1, a2: A2, a3: A3) => R1): LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3) => R4>; + flowRight(this: LoDashImplicitWrapper<(a: R4) => R5>, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1, a2: A2, a3: A3) => R1): LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3) => R5>; + flowRight(this: LoDashImplicitWrapper<(a: R5) => R6>, f5: (a: R4) => R5, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1, a2: A2, a3: A3) => R1): LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3) => R6>; + flowRight(this: LoDashImplicitWrapper<(a: R6) => R7>, f6: (a: R5) => R6, f5: (a: R4) => R5, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1, a2: A2, a3: A3) => R1): LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3) => R7>; + // 4-argument first function + flowRight(this: LoDashImplicitWrapper<(a: R1) => R2>, f1: (a1: A1, a2: A2, a3: A3, a4: A4) => R1): LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4) => R2>; + flowRight(this: LoDashImplicitWrapper<(a: R2) => R3>, f2: (a: R1) => R2, f1: (a1: A1, a2: A2, a3: A3, a4: A4) => R1): LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4) => R3>; + flowRight(this: LoDashImplicitWrapper<(a: R3) => R4>, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1, a2: A2, a3: A3, a4: A4) => R1): LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4) => R4>; + flowRight(this: LoDashImplicitWrapper<(a: R4) => R5>, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1, a2: A2, a3: A3, a4: A4) => R1): LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4) => R5>; + flowRight(this: LoDashImplicitWrapper<(a: R5) => R6>, f5: (a: R4) => R5, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1, a2: A2, a3: A3, a4: A4) => R1): LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4) => R6>; + flowRight(this: LoDashImplicitWrapper<(a: R6) => R7>, f6: (a: R5) => R6, f5: (a: R4) => R5, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1, a2: A2, a3: A3, a4: A4) => R1): LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4) => R7>; + // any-argument first function + flowRight(this: LoDashImplicitWrapper<(a: R1) => R2>, f1: (...args: any[]) => R1): LoDashImplicitWrapper<(...args: any[]) => R2>; + flowRight(this: LoDashImplicitWrapper<(a: R1) => R2>, f2: (a: R1) => R2, f1: (...args: any[]) => R1): LoDashImplicitWrapper<(...args: any[]) => R3>; + flowRight(this: LoDashImplicitWrapper<(a: R1) => R2>, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (...args: any[]) => R1): LoDashImplicitWrapper<(...args: any[]) => R4>; + flowRight(this: LoDashImplicitWrapper<(a: R1) => R2>, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (...args: any[]) => R1): LoDashImplicitWrapper<(...args: any[]) => R5>; + flowRight(this: LoDashImplicitWrapper<(a: R1) => R2>, f5: (a: R4) => R5, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (...args: any[]) => R1): LoDashImplicitWrapper<(...args: any[]) => R6>; + flowRight(this: LoDashImplicitWrapper<(a: R1) => R2>, f6: (a: R5) => R6, f5: (a: R4) => R5, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (...args: any[]) => R1): LoDashImplicitWrapper<(...args: any[]) => R7>; + flowRight(this: LoDashImplicitWrapper<(a: any) => any>, f6: (a: any) => any, f5: (a: any) => any, f4: (a: any) => any, f3: (a: any) => any, f2: (a: any) => any, f1: () => any, ...funcs: Array any>>): LoDashImplicitWrapper<(...args: any[]) => any>; + flowRight(this: LoDashImplicitWrapper<(a: any) => any>, funcs: Array any>>): LoDashImplicitWrapper<(...args: any[]) => any>; + } + + interface LoDashExplicitWrapper { + /** + * @see _.flowRight + */ + // 0-argument first function + flowRight(this: LoDashExplicitWrapper<(a: R1) => R2>, f1: () => R1): LoDashExplicitWrapper<() => R2>; + flowRight(this: LoDashExplicitWrapper<(a: R2) => R3>, f2: (a: R1) => R2, f1: () => R1): LoDashExplicitWrapper<() => R3>; + flowRight(this: LoDashExplicitWrapper<(a: R3) => R4>, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: () => R1): LoDashExplicitWrapper<() => R4>; + flowRight(this: LoDashExplicitWrapper<(a: R4) => R5>, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: () => R1): LoDashExplicitWrapper<() => R5>; + flowRight(this: LoDashExplicitWrapper<(a: R5) => R6>, f5: (a: R4) => R5, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: () => R1): LoDashExplicitWrapper<() => R6>; + flowRight(this: LoDashExplicitWrapper<(a: R6) => R7>, f6: (a: R5) => R6, f5: (a: R4) => R5, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: () => R1): LoDashExplicitWrapper<() => R7>; + // 1-argument first function + flowRight(this: LoDashExplicitWrapper<(a: R1) => R2>, f1: (a1: A1) => R1): LoDashExplicitWrapper<(a1: A1) => R2>; + flowRight(this: LoDashExplicitWrapper<(a: R2) => R3>, f2: (a: R1) => R2, f1: (a1: A1) => R1): LoDashExplicitWrapper<(a1: A1) => R3>; + flowRight(this: LoDashExplicitWrapper<(a: R3) => R4>, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1) => R1): LoDashExplicitWrapper<(a1: A1) => R4>; + flowRight(this: LoDashExplicitWrapper<(a: R4) => R5>, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1) => R1): LoDashExplicitWrapper<(a1: A1) => R5>; + flowRight(this: LoDashExplicitWrapper<(a: R5) => R6>, f5: (a: R4) => R5, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1) => R1): LoDashExplicitWrapper<(a1: A1) => R6>; + flowRight(this: LoDashExplicitWrapper<(a: R6) => R7>, f6: (a: R5) => R6, f5: (a: R4) => R5, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1) => R1): LoDashExplicitWrapper<(a1: A1) => R7>; + // 2-argument first function + flowRight(this: LoDashExplicitWrapper<(a: R1) => R2>, f1: (a1: A1, a2: A2) => R1): LoDashExplicitWrapper<(a1: A1, a2: A2) => R2>; + flowRight(this: LoDashExplicitWrapper<(a: R2) => R3>, f2: (a: R1) => R2, f1: (a1: A1, a2: A2) => R1): LoDashExplicitWrapper<(a1: A1, a2: A2) => R3>; + flowRight(this: LoDashExplicitWrapper<(a: R3) => R4>, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1, a2: A2) => R1): LoDashExplicitWrapper<(a1: A1, a2: A2) => R4>; + flowRight(this: LoDashExplicitWrapper<(a: R4) => R5>, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1, a2: A2) => R1): LoDashExplicitWrapper<(a1: A1, a2: A2) => R5>; + flowRight(this: LoDashExplicitWrapper<(a: R5) => R6>, f5: (a: R4) => R5, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1, a2: A2) => R1): LoDashExplicitWrapper<(a1: A1, a2: A2) => R6>; + flowRight(this: LoDashExplicitWrapper<(a: R6) => R7>, f6: (a: R5) => R6, f5: (a: R4) => R5, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1, a2: A2) => R1): LoDashExplicitWrapper<(a1: A1, a2: A2) => R7>; + // 3-argument first function + flowRight(this: LoDashExplicitWrapper<(a: R1) => R2>, f1: (a1: A1, a2: A2, a3: A3) => R1): LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3) => R2>; + flowRight(this: LoDashExplicitWrapper<(a: R2) => R3>, f2: (a: R1) => R2, f1: (a1: A1, a2: A2, a3: A3) => R1): LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3) => R3>; + flowRight(this: LoDashExplicitWrapper<(a: R3) => R4>, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1, a2: A2, a3: A3) => R1): LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3) => R4>; + flowRight(this: LoDashExplicitWrapper<(a: R4) => R5>, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1, a2: A2, a3: A3) => R1): LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3) => R5>; + flowRight(this: LoDashExplicitWrapper<(a: R5) => R6>, f5: (a: R4) => R5, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1, a2: A2, a3: A3) => R1): LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3) => R6>; + flowRight(this: LoDashExplicitWrapper<(a: R6) => R7>, f6: (a: R5) => R6, f5: (a: R4) => R5, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1, a2: A2, a3: A3) => R1): LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3) => R7>; + // 4-argument first function + flowRight(this: LoDashExplicitWrapper<(a: R1) => R2>, f1: (a1: A1, a2: A2, a3: A3, a4: A4) => R1): LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4) => R2>; + flowRight(this: LoDashExplicitWrapper<(a: R2) => R3>, f2: (a: R1) => R2, f1: (a1: A1, a2: A2, a3: A3, a4: A4) => R1): LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4) => R3>; + flowRight(this: LoDashExplicitWrapper<(a: R3) => R4>, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1, a2: A2, a3: A3, a4: A4) => R1): LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4) => R4>; + flowRight(this: LoDashExplicitWrapper<(a: R4) => R5>, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1, a2: A2, a3: A3, a4: A4) => R1): LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4) => R5>; + flowRight(this: LoDashExplicitWrapper<(a: R5) => R6>, f5: (a: R4) => R5, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1, a2: A2, a3: A3, a4: A4) => R1): LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4) => R6>; + flowRight(this: LoDashExplicitWrapper<(a: R6) => R7>, f6: (a: R5) => R6, f5: (a: R4) => R5, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1, a2: A2, a3: A3, a4: A4) => R1): LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4) => R7>; + // any-argument first function + flowRight(this: LoDashExplicitWrapper<(a: R1) => R2>, f1: (...args: any[]) => R1): LoDashExplicitWrapper<(...args: any[]) => R2>; + flowRight(this: LoDashExplicitWrapper<(a: R1) => R2>, f2: (a: R1) => R2, f1: (...args: any[]) => R1): LoDashExplicitWrapper<(...args: any[]) => R3>; + flowRight(this: LoDashExplicitWrapper<(a: R1) => R2>, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (...args: any[]) => R1): LoDashExplicitWrapper<(...args: any[]) => R4>; + flowRight(this: LoDashExplicitWrapper<(a: R1) => R2>, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (...args: any[]) => R1): LoDashExplicitWrapper<(...args: any[]) => R5>; + flowRight(this: LoDashExplicitWrapper<(a: R1) => R2>, f5: (a: R4) => R5, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (...args: any[]) => R1): LoDashExplicitWrapper<(...args: any[]) => R6>; + flowRight(this: LoDashExplicitWrapper<(a: R1) => R2>, f6: (a: R5) => R6, f5: (a: R4) => R5, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (...args: any[]) => R1): LoDashExplicitWrapper<(...args: any[]) => R7>; + flowRight(this: LoDashExplicitWrapper<(a: any) => any>, f6: (a: any) => any, f5: (a: any) => any, f4: (a: any) => any, f3: (a: any) => any, f2: (a: any) => any, f1: () => any, ...funcs: Array any>>): LoDashExplicitWrapper<(...args: any[]) => any>; + flowRight(this: LoDashExplicitWrapper<(a: any) => any>, funcs: Array any>>): LoDashExplicitWrapper<(...args: any[]) => any>; + } + + // identity + + interface LoDashStatic { + /** + * This method returns the first argument provided to it. + * + * @param value Any value. + * @return Returns value. + */ + identity(value: T): T; + + /** + * @see _.identity + */ + identity(): undefined; + } + + interface LoDashImplicitWrapper { + /** + * @see _.identity + */ + identity(): TValue; + } + + interface LoDashExplicitWrapper { + /** + * @see _.identity + */ + identity(): this; + } + + // iteratee + + interface LoDashStatic { + /** + * Creates a function that invokes `func` with the arguments of the created + * function. If `func` is a property name the created callback returns the + * property value for a given element. If `func` is an object the created + * callback returns `true` for elements that contain the equivalent object properties, otherwise it returns `false`. + * + * @category Util + * @param [func=_.identity] The value to convert to a callback. + * @returns Returns the callback. + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36 }, + * { 'user': 'fred', 'age': 40 } + * ]; + * + * // create custom iteratee shorthands + * _.iteratee = _.wrap(_.iteratee, function(callback, func) { + * var p = /^(\S+)\s*([<>])\s*(\S+)$/.exec(func); + * return !p ? callback(func) : function(object) { + * return (p[2] == '>' ? object[p[1]] > p[3] : object[p[1]] < p[3]); + * }; + * }); + * + * _.filter(users, 'age > 36'); + * // => [{ 'user': 'fred', 'age': 40 }] + */ + iteratee any>( + func: TFunction + ): TFunction; + + /** + * @see _.iteratee + */ + // tslint:disable-next-line:unified-signatures Tests fail in TS2.3 if the overloads are joined + iteratee( + func: string | object + ): (...args: any[]) => any; + + /** + * @see _.iteratee + */ + iteratee(): typeof _.identity; // tslint:disable-line:no-unnecessary-qualifier + } + + interface LoDashImplicitWrapper { + /** + * @see _.iteratee + */ + iteratee any>( + this: LoDashImplicitWrapper + ): LoDashImplicitWrapper; + } + + interface LoDashExplicitWrapper { + /** + * @see _.iteratee + */ + iteratee any>( + this: LoDashExplicitWrapper + ): LoDashExplicitWrapper; + } + + // matches + + interface LoDashStatic { + /** + * Creates a function that performs a deep comparison between a given object and source, returning true if the + * given object has equivalent property values, else false. + * + * Note: This method supports comparing arrays, booleans, Date objects, numbers, Object objects, regexes, and + * strings. Objects are compared by their own, not inherited, enumerable properties. For comparing a single own + * or inherited property value see _.matchesProperty. + * + * @param source The object of property values to match. + * @return Returns the new function. + */ + matches(source: T): (value: any) => boolean; + + /** + * @see _.matches + */ + matches(source: T): (value: V) => boolean; + } + + interface LoDashImplicitWrapper { + /** + * @see _.matches + */ + matches(): LoDashImplicitWrapper<(value: V) => boolean>; + } + + interface LoDashExplicitWrapper { + /** + * @see _.matches + */ + matches(): LoDashExplicitWrapper<(value: V) => boolean>; + } + + // matchesProperty + + interface LoDashStatic { + /** + * Creates a function that compares the property value of path on a given object to value. + * + * Note: This method supports comparing arrays, booleans, Date objects, numbers, Object objects, regexes, and + * strings. Objects are compared by their own, not inherited, enumerable properties. + * + * @param path The path of the property to get. + * @param srcValue The value to match. + * @return Returns the new function. + */ + matchesProperty( + path: PropertyPath, + srcValue: T + ): (value: any) => boolean; + + /** + * @see _.matchesProperty + */ + matchesProperty( + path: PropertyPath, + srcValue: T + ): (value: V) => boolean; + } + + interface LoDashImplicitWrapper { + /** + * @see _.matchesProperty + */ + matchesProperty( + srcValue: SrcValue + ): LoDashImplicitWrapper<(value: any) => boolean>; + + /** + * @see _.matchesProperty + */ + matchesProperty( + srcValue: SrcValue + ): LoDashImplicitWrapper<(value: Value) => boolean>; + } + + interface LoDashExplicitWrapper { + /** + * @see _.matchesProperty + */ + matchesProperty( + srcValue: SrcValue + ): LoDashExplicitWrapper<(value: any) => boolean>; + + /** + * @see _.matchesProperty + */ + matchesProperty( + srcValue: SrcValue + ): LoDashExplicitWrapper<(value: Value) => boolean>; + } + + // method + + interface LoDashStatic { + /** + * Creates a function that invokes the method at path on a given object. Any additional arguments are provided + * to the invoked method. + * + * @param path The path of the method to invoke. + * @param args The arguments to invoke the method with. + * @return Returns the new function. + */ + method( + path: PropertyPath, + ...args: any[] + ): (object: any) => any; + } + + interface LoDashImplicitWrapper { + /** + * @see _.method + */ + method(...args: any[]): LoDashImplicitWrapper<(object: any) => any>; + } + + interface LoDashExplicitWrapper { + /** + * @see _.method + */ + method(...args: any[]): LoDashExplicitWrapper<(object: any) => any>; + } + + // methodOf + + interface LoDashStatic { + /** + * The opposite of _.method; this method creates a function that invokes the method at a given path on object. + * Any additional arguments are provided to the invoked method. + * + * @param object The object to query. + * @param args The arguments to invoke the method with. + * @return Returns the new function. + */ + methodOf( + object: object, + ...args: any[] + ): (path: PropertyPath) => any; + } + + interface LoDashImplicitWrapper { + /** + * @see _.methodOf + */ + methodOf( + ...args: any[] + ): LoDashImplicitWrapper<(path: PropertyPath) => any>; + } + + interface LoDashExplicitWrapper { + /** + * @see _.methodOf + */ + methodOf( + ...args: any[] + ): LoDashExplicitWrapper<(path: PropertyPath) => any>; + } + + // mixin + + interface MixinOptions { + chain?: boolean; + } + + interface LoDashStatic { + /** + * Adds all own enumerable function properties of a source object to the destination object. If object is a + * function then methods are added to its prototype as well. + * + * Note: Use _.runInContext to create a pristine lodash function to avoid conflicts caused by modifying + * the original. + * + * @param object The destination object. + * @param source The object of functions to add. + * @param options The options object. + * @param options.chain Specify whether the functions added are chainable. + * @return Returns object. + */ + mixin( + object: TObject, + source: Dictionary<(...args: any[]) => any>, + options?: MixinOptions + ): TObject; + + /** + * @see _.mixin + */ + mixin( + source: Dictionary<(...args: any[]) => any>, + options?: MixinOptions + ): LoDashStatic; + } + + interface LoDashImplicitWrapper { + /** + * @see _.mixin + */ + mixin( + source: Dictionary<(...args: any[]) => any>, + options?: MixinOptions + ): this; + + /** + * @see _.mixin + */ + mixin( + options?: MixinOptions + ): LoDashImplicitWrapper; + } + + interface LoDashExplicitWrapper { + /** + * @see _.mixin + */ + mixin( + source: Dictionary<(...args: any[]) => any>, + options?: MixinOptions + ): this; + + /** + * @see _.mixin + */ + mixin( + options?: MixinOptions + ): LoDashExplicitWrapper; + } + + // noConflict + + interface LoDashStatic { + /** + * Reverts the _ variable to its previous value and returns a reference to the lodash function. + * + * @return Returns the lodash function. + */ + noConflict(): typeof _; + } + + interface LoDashImplicitWrapper { + /** + * @see _.noConflict + */ + noConflict(): typeof _; + } + + interface LoDashExplicitWrapper { + /** + * @see _.noConflict + */ + noConflict(): LoDashExplicitWrapper; + } + + // noop + + interface LoDashStatic { + /** + * A no-operation function that returns undefined regardless of the arguments it receives. + * + * @return undefined + */ + noop(...args: any[]): void; + } + + interface LoDashImplicitWrapper { + /** + * @see _.noop + */ + noop(...args: any[]): void; + } + + interface LoDashExplicitWrapper { + /** + * @see _.noop + */ + noop(...args: any[]): LoDashExplicitWrapper; + } + + // nthArg + + interface LoDashStatic { + /** + * Creates a function that returns its nth argument. + * + * @param n The index of the argument to return. + * @return Returns the new function. + */ + nthArg(n?: number): (...args: any[]) => any; + } + + interface LoDashImplicitWrapper { + /** + * @see _.nthArg + */ + nthArg(): LoDashImplicitWrapper<(...args: any[]) => any>; + } + + interface LoDashExplicitWrapper { + /** + * @see _.nthArg + */ + nthArg(): LoDashExplicitWrapper<(...args: any[]) => any>; + } + + // over + + interface LoDashStatic { + /** + * Creates a function that invokes iteratees with the arguments provided to the created function and returns + * their results. + * + * @param iteratees The iteratees to invoke. + * @return Returns the new function. + */ + over(...iteratees: Array TResult>>): (...args: any[]) => TResult[]; + } + + interface LoDashImplicitWrapper { + /** + * @see _.over + */ + over( + this: LoDashImplicitWrapper TResult>>, + ...iteratees: Array TResult>> + ): LoDashImplicitWrapper<(...args: any[]) => TResult[]>; + } + + interface LoDashExplicitWrapper { + /** + * @see _.over + */ + over( + this: LoDashExplicitWrapper TResult>>, + ...iteratees: Array TResult>> + ): LoDashExplicitWrapper<(...args: any[]) => TResult[]>; + } + + // overEvery + + interface LoDashStatic { + /** + * Creates a function that checks if all of the predicates return truthy when invoked with the arguments + * provided to the created function. + * + * @param predicates The predicates to check. + * @return Returns the new function. + */ + overEvery(...predicates: Array boolean>>): (...args: T[]) => boolean; + } + + interface LoDashImplicitWrapper { + /** + * @see _.overEvery + */ + overEvery(...predicates: Array boolean>>): LoDashImplicitWrapper<(...args: T[]) => boolean>; + } + + interface LoDashExplicitWrapper { + /** + * @see _.overEvery + */ + overEvery(...predicates: Array boolean>>): LoDashExplicitWrapper<(...args: T[]) => boolean>; + } + + // overSome + + interface LoDashStatic { + /** + * Creates a function that checks if any of the predicates return truthy when invoked with the arguments + * provided to the created function. + * + * @param predicates The predicates to check. + * @return Returns the new function. + */ + overSome(...predicates: Array boolean>>): (...args: T[]) => boolean; + } + + interface LoDashImplicitWrapper { + /** + * @see _.overSome + */ + overSome(...predicates: Array boolean>>): LoDashImplicitWrapper<(...args: T[]) => boolean>; + } + + interface LoDashExplicitWrapper { + /** + * @see _.overSome + */ + overSome(...predicates: Array boolean>>): LoDashExplicitWrapper<(...args: T[]) => boolean>; + } + + // property + + interface LoDashStatic { + /** + * Creates a function that returns the property value at path on a given object. + * + * @param path The path of the property to get. + * @return Returns the new function. + */ + property(path: PropertyPath): (obj: TObj) => TResult; + } + + interface LoDashImplicitWrapper { + /** + * @see _.property + */ + property(): LoDashImplicitWrapper<(obj: TObj) => TResult>; + } + + interface LoDashExplicitWrapper { + /** + * @see _.property + */ + property(): LoDashExplicitWrapper<(obj: TObj) => TResult>; + } + + // propertyOf + + interface LoDashStatic { + /** + * The opposite of _.property; this method creates a function that returns the property value at a given path + * on object. + * + * @param object The object to query. + * @return Returns the new function. + */ + propertyOf(object: T): (path: PropertyPath) => any; + } + + interface LoDashImplicitWrapper { + /** + * @see _.propertyOf + */ + propertyOf(): LoDashImplicitWrapper<(path: PropertyPath) => any>; + } + + interface LoDashExplicitWrapper { + /** + * @see _.propertyOf + */ + propertyOf(): LoDashExplicitWrapper<(path: PropertyPath) => any>; + } + + // range + + interface LoDashStatic { + /** + * Creates an array of numbers (positive and/or negative) progressing from start up to, but not including, end. + * If end is not specified it’s set to start with start then set to 0. If end is less than start a zero-length + * range is created unless a negative step is specified. + * + * @param start The start of the range. + * @param end The end of the range. + * @param step The value to increment or decrement by. + * @return Returns a new range array. + */ + range( + start: number, + end?: number, + step?: number + ): number[]; + + /** + * Creates an array of numbers (positive and/or negative) progressing from start up to, but not including, end. + * If end is not specified it’s set to start with start then set to 0. If end is less than start a zero-length + * range is created unless a negative step is specified. + * + * @param start The start of the range. + * @param index Not used in this overload. + * @param guard Enables use as an iteratee for methods like _.map. You should not pass this parameter directly in your code. + * @return Returns a new range array. + */ + range( + end: number, + index: string | number, + guard: object + ): number[]; + } + + interface LoDashImplicitWrapper { + /** + * @see _.range + */ + range( + end?: number, + step?: number + ): LoDashImplicitWrapper; + } + + interface LoDashExplicitWrapper { + /** + * @see _.range + */ + range( + end?: number, + step?: number + ): LoDashExplicitWrapper; + } + + // rangeRight + + interface LoDashStatic { + /** + * This method is like `_.range` except that it populates values in + * descending order. + * + * @category Util + * @param start The start of the range. + * @param end The end of the range. + * @param step The value to increment or decrement by. + * @returns Returns the new array of numbers. + * @example + * + * _.rangeRight(4); + * // => [3, 2, 1, 0] + * + * _.rangeRight(-4); + * // => [-3, -2, -1, 0] + * + * _.rangeRight(1, 5); + * // => [4, 3, 2, 1] + * + * _.rangeRight(0, 20, 5); + * // => [15, 10, 5, 0] + * + * _.rangeRight(0, -4, -1); + * // => [-3, -2, -1, 0] + * + * _.rangeRight(1, 4, 0); + * // => [1, 1, 1] + * + * _.rangeRight(0); + * // => [] + */ + rangeRight( + start: number, + end?: number, + step?: number + ): number[]; + + /** + * This method is like _.range except that it populates values in + * descending order. + * + * @param start The start of the range. + * @param index Not used in this overload. + * @param guard Enables use as an iteratee for methods like _.map. You should not pass this parameter directly in your code. + * @return Returns a new range array. + */ + rangeRight( + end: number, + index: string | number, + guard: object + ): number[]; + } + + interface LoDashImplicitWrapper { + /** + * @see _.rangeRight + */ + rangeRight( + end?: number, + step?: number + ): LoDashImplicitWrapper; + } + + interface LoDashExplicitWrapper { + /** + * @see _.rangeRight + */ + rangeRight( + end?: number, + step?: number + ): LoDashExplicitWrapper; + } + + // runInContext + + interface LoDashStatic { + /** + * Create a new pristine lodash function using the given context object. + * + * @param context The context object. + * @return Returns a new lodash function. + */ + runInContext(context?: object): LoDashStatic; + } + + interface LoDashImplicitWrapper { + /** + * @see _.runInContext + */ + runInContext(): LoDashStatic; + } + + // stubArray + + interface LoDashStatic { + /** + * This method returns a new empty array. + * + * @returns Returns the new empty array. + */ + stubArray(): any[]; + } + + interface LoDashImplicitWrapper { + /** + * @see _.stubArray + */ + stubArray(): any[]; + } + + interface LoDashExplicitWrapper { + /** + * @see _.stubArray + */ + stubArray(): LoDashExplicitWrapper; + } + + // stubFalse + + interface LoDashStatic { + /** + * This method returns `false`. + * + * @returns Returns `false`. + */ + stubFalse(): false; + } + + interface LoDashImplicitWrapper { + /** + * @see _.stubFalse + */ + stubFalse(): false; + } + + interface LoDashExplicitWrapper { + /** + * @see _.stubFalse + */ + stubFalse(): LoDashExplicitWrapper; + } + + // stubObject + + interface LoDashStatic { + /** + * This method returns a new empty object. + * + * @returns Returns the new empty object. + */ + stubObject(): any; + } + + interface LoDashImplicitWrapper { + /** + * @see _.stubObject + */ + stubObject(): any; + } + + interface LoDashExplicitWrapper { + /** + * @see _.stubObject + */ + stubObject(): LoDashExplicitWrapper; + } + + // stubString + + interface LoDashStatic { + /** + * This method returns an empty string. + * + * @returns Returns the empty string. + */ + stubString(): string; + } + + interface LoDashImplicitWrapper { + /** + * @see _.stubString + */ + stubString(): string; + } + + interface LoDashExplicitWrapper { + /** + * @see _.stubString + */ + stubString(): LoDashExplicitWrapper; + } + + // stubTrue + + interface LoDashStatic { + /** + * This method returns `true`. + * + * @returns Returns `true`. + */ + stubTrue(): true; + } + + interface LoDashImplicitWrapper { + /** + * @see _.stubTrue + */ + stubTrue(): true; + } + + interface LoDashExplicitWrapper { + /** + * @see _.stubTrue + */ + stubTrue(): LoDashExplicitWrapper; + } + + // times + + interface LoDashStatic { + /** + * Invokes the iteratee function n times, returning an array of the results of each invocation. The iteratee + * is invoked with one argument; (index). + * + * @param n The number of times to invoke iteratee. + * @param iteratee The function invoked per iteration. + * @return Returns the array of results. + */ + times( + n: number, + iteratee: (num: number) => TResult + ): TResult[]; + + /** + * @see _.times + */ + times(n: number): number[]; + } + + interface LoDashImplicitWrapper { + /** + * @see _.times + */ + times( + iteratee: (num: number) => TResult + ): TResult[]; + + /** + * @see _.times + */ + times(): number[]; + } + + interface LoDashExplicitWrapper { + /** + * @see _.times + */ + times( + iteratee: (num: number) => TResult + ): LoDashExplicitWrapper; + + /** + * @see _.times + */ + times(): LoDashExplicitWrapper; + } + + // toPath + + interface LoDashStatic { + /** + * Converts `value` to a property path array. + * + * @category Util + * @param value The value to convert. + * @returns Returns the new property path array. + * @example + * + * _.toPath('a.b.c'); + * // => ['a', 'b', 'c'] + * + * _.toPath('a[0].b.c'); + * // => ['a', '0', 'b', 'c'] + * + * var path = ['a', 'b', 'c'], + * newPath = _.toPath(path); + * + * console.log(newPath); + * // => ['a', 'b', 'c'] + * + * console.log(path === newPath); + * // => false + */ + toPath(value: any): string[]; + } + + interface LoDashImplicitWrapper { + /** + * @see _.toPath + */ + toPath(): LoDashImplicitWrapper; + } + + interface LoDashExplicitWrapper { + /** + * @see _.toPath + */ + toPath(): LoDashExplicitWrapper; + } + + // uniqueId + + interface LoDashStatic { + /** + * Generates a unique ID. If prefix is provided the ID is appended to it. + * + * @param prefix The value to prefix the ID with. + * @return Returns the unique ID. + */ + uniqueId(prefix?: string): string; + } + + interface LoDashImplicitWrapper { + /** + * @see _.uniqueId + */ + uniqueId(): string; + } + + interface LoDashExplicitWrapper { + /** + * @see _.uniqueId + */ + uniqueId(): LoDashExplicitWrapper; + } +} diff --git a/node_modules/@types/lodash/compact.d.ts b/node_modules/@types/lodash/compact.d.ts new file mode 100644 index 0000000..94a5397 --- /dev/null +++ b/node_modules/@types/lodash/compact.d.ts @@ -0,0 +1,2 @@ +import { compact } from "./index"; +export = compact; diff --git a/node_modules/@types/lodash/concat.d.ts b/node_modules/@types/lodash/concat.d.ts new file mode 100644 index 0000000..f8c2612 --- /dev/null +++ b/node_modules/@types/lodash/concat.d.ts @@ -0,0 +1,2 @@ +import { concat } from "./index"; +export = concat; diff --git a/node_modules/@types/lodash/cond.d.ts b/node_modules/@types/lodash/cond.d.ts new file mode 100644 index 0000000..a325bad --- /dev/null +++ b/node_modules/@types/lodash/cond.d.ts @@ -0,0 +1,2 @@ +import { cond } from "./index"; +export = cond; diff --git a/node_modules/@types/lodash/conformsTo.d.ts b/node_modules/@types/lodash/conformsTo.d.ts new file mode 100644 index 0000000..320b180 --- /dev/null +++ b/node_modules/@types/lodash/conformsTo.d.ts @@ -0,0 +1,2 @@ +import { conformsTo } from "./index"; +export = conformsTo; diff --git a/node_modules/@types/lodash/constant.d.ts b/node_modules/@types/lodash/constant.d.ts new file mode 100644 index 0000000..ebab572 --- /dev/null +++ b/node_modules/@types/lodash/constant.d.ts @@ -0,0 +1,2 @@ +import { constant } from "./index"; +export = constant; diff --git a/node_modules/@types/lodash/countBy.d.ts b/node_modules/@types/lodash/countBy.d.ts new file mode 100644 index 0000000..db56ff3 --- /dev/null +++ b/node_modules/@types/lodash/countBy.d.ts @@ -0,0 +1,2 @@ +import { countBy } from "./index"; +export = countBy; diff --git a/node_modules/@types/lodash/create.d.ts b/node_modules/@types/lodash/create.d.ts new file mode 100644 index 0000000..5c7dc7a --- /dev/null +++ b/node_modules/@types/lodash/create.d.ts @@ -0,0 +1,2 @@ +import { create } from "./index"; +export = create; diff --git a/node_modules/@types/lodash/curry.d.ts b/node_modules/@types/lodash/curry.d.ts new file mode 100644 index 0000000..afbb8f4 --- /dev/null +++ b/node_modules/@types/lodash/curry.d.ts @@ -0,0 +1,2 @@ +import { curry } from "./index"; +export = curry; diff --git a/node_modules/@types/lodash/curryRight.d.ts b/node_modules/@types/lodash/curryRight.d.ts new file mode 100644 index 0000000..7d224c9 --- /dev/null +++ b/node_modules/@types/lodash/curryRight.d.ts @@ -0,0 +1,2 @@ +import { curryRight } from "./index"; +export = curryRight; diff --git a/node_modules/@types/lodash/debounce.d.ts b/node_modules/@types/lodash/debounce.d.ts new file mode 100644 index 0000000..983edd7 --- /dev/null +++ b/node_modules/@types/lodash/debounce.d.ts @@ -0,0 +1,2 @@ +import { debounce } from "./index"; +export = debounce; diff --git a/node_modules/@types/lodash/deburr.d.ts b/node_modules/@types/lodash/deburr.d.ts new file mode 100644 index 0000000..cf1fa37 --- /dev/null +++ b/node_modules/@types/lodash/deburr.d.ts @@ -0,0 +1,2 @@ +import { deburr } from "./index"; +export = deburr; diff --git a/node_modules/@types/lodash/defaultTo.d.ts b/node_modules/@types/lodash/defaultTo.d.ts new file mode 100644 index 0000000..89fb565 --- /dev/null +++ b/node_modules/@types/lodash/defaultTo.d.ts @@ -0,0 +1,2 @@ +import { defaultTo } from "./index"; +export = defaultTo; diff --git a/node_modules/@types/lodash/defaults.d.ts b/node_modules/@types/lodash/defaults.d.ts new file mode 100644 index 0000000..e83508d --- /dev/null +++ b/node_modules/@types/lodash/defaults.d.ts @@ -0,0 +1,2 @@ +import { defaults } from "./index"; +export = defaults; diff --git a/node_modules/@types/lodash/defaultsDeep.d.ts b/node_modules/@types/lodash/defaultsDeep.d.ts new file mode 100644 index 0000000..19ff551 --- /dev/null +++ b/node_modules/@types/lodash/defaultsDeep.d.ts @@ -0,0 +1,2 @@ +import { defaultsDeep } from "./index"; +export = defaultsDeep; diff --git a/node_modules/@types/lodash/defer.d.ts b/node_modules/@types/lodash/defer.d.ts new file mode 100644 index 0000000..144bf5b --- /dev/null +++ b/node_modules/@types/lodash/defer.d.ts @@ -0,0 +1,2 @@ +import { defer } from "./index"; +export = defer; diff --git a/node_modules/@types/lodash/delay.d.ts b/node_modules/@types/lodash/delay.d.ts new file mode 100644 index 0000000..ead89c1 --- /dev/null +++ b/node_modules/@types/lodash/delay.d.ts @@ -0,0 +1,2 @@ +import { delay } from "./index"; +export = delay; diff --git a/node_modules/@types/lodash/difference.d.ts b/node_modules/@types/lodash/difference.d.ts new file mode 100644 index 0000000..4a73c56 --- /dev/null +++ b/node_modules/@types/lodash/difference.d.ts @@ -0,0 +1,2 @@ +import { difference } from "./index"; +export = difference; diff --git a/node_modules/@types/lodash/differenceBy.d.ts b/node_modules/@types/lodash/differenceBy.d.ts new file mode 100644 index 0000000..34558c4 --- /dev/null +++ b/node_modules/@types/lodash/differenceBy.d.ts @@ -0,0 +1,2 @@ +import { differenceBy } from "./index"; +export = differenceBy; diff --git a/node_modules/@types/lodash/differenceWith.d.ts b/node_modules/@types/lodash/differenceWith.d.ts new file mode 100644 index 0000000..86aebd8 --- /dev/null +++ b/node_modules/@types/lodash/differenceWith.d.ts @@ -0,0 +1,2 @@ +import { differenceWith } from "./index"; +export = differenceWith; diff --git a/node_modules/@types/lodash/divide.d.ts b/node_modules/@types/lodash/divide.d.ts new file mode 100644 index 0000000..3d8e393 --- /dev/null +++ b/node_modules/@types/lodash/divide.d.ts @@ -0,0 +1,2 @@ +import { divide } from "./index"; +export = divide; diff --git a/node_modules/@types/lodash/drop.d.ts b/node_modules/@types/lodash/drop.d.ts new file mode 100644 index 0000000..1283f99 --- /dev/null +++ b/node_modules/@types/lodash/drop.d.ts @@ -0,0 +1,2 @@ +import { drop } from "./index"; +export = drop; diff --git a/node_modules/@types/lodash/dropRight.d.ts b/node_modules/@types/lodash/dropRight.d.ts new file mode 100644 index 0000000..4133c98 --- /dev/null +++ b/node_modules/@types/lodash/dropRight.d.ts @@ -0,0 +1,2 @@ +import { dropRight } from "./index"; +export = dropRight; diff --git a/node_modules/@types/lodash/dropRightWhile.d.ts b/node_modules/@types/lodash/dropRightWhile.d.ts new file mode 100644 index 0000000..0dda808 --- /dev/null +++ b/node_modules/@types/lodash/dropRightWhile.d.ts @@ -0,0 +1,2 @@ +import { dropRightWhile } from "./index"; +export = dropRightWhile; diff --git a/node_modules/@types/lodash/dropWhile.d.ts b/node_modules/@types/lodash/dropWhile.d.ts new file mode 100644 index 0000000..894ebaa --- /dev/null +++ b/node_modules/@types/lodash/dropWhile.d.ts @@ -0,0 +1,2 @@ +import { dropWhile } from "./index"; +export = dropWhile; diff --git a/node_modules/@types/lodash/each.d.ts b/node_modules/@types/lodash/each.d.ts new file mode 100644 index 0000000..608f8a9 --- /dev/null +++ b/node_modules/@types/lodash/each.d.ts @@ -0,0 +1,2 @@ +import { each } from "./index"; +export = each; diff --git a/node_modules/@types/lodash/eachRight.d.ts b/node_modules/@types/lodash/eachRight.d.ts new file mode 100644 index 0000000..ae0bb6f --- /dev/null +++ b/node_modules/@types/lodash/eachRight.d.ts @@ -0,0 +1,2 @@ +import { eachRight } from "./index"; +export = eachRight; diff --git a/node_modules/@types/lodash/endsWith.d.ts b/node_modules/@types/lodash/endsWith.d.ts new file mode 100644 index 0000000..d8475b1 --- /dev/null +++ b/node_modules/@types/lodash/endsWith.d.ts @@ -0,0 +1,2 @@ +import { endsWith } from "./index"; +export = endsWith; diff --git a/node_modules/@types/lodash/entries.d.ts b/node_modules/@types/lodash/entries.d.ts new file mode 100644 index 0000000..24b2417 --- /dev/null +++ b/node_modules/@types/lodash/entries.d.ts @@ -0,0 +1,2 @@ +import { entries } from "./index"; +export = entries; diff --git a/node_modules/@types/lodash/entriesIn.d.ts b/node_modules/@types/lodash/entriesIn.d.ts new file mode 100644 index 0000000..a68ab1e --- /dev/null +++ b/node_modules/@types/lodash/entriesIn.d.ts @@ -0,0 +1,2 @@ +import { entriesIn } from "./index"; +export = entriesIn; diff --git a/node_modules/@types/lodash/eq.d.ts b/node_modules/@types/lodash/eq.d.ts new file mode 100644 index 0000000..88ec887 --- /dev/null +++ b/node_modules/@types/lodash/eq.d.ts @@ -0,0 +1,2 @@ +import { eq } from "./index"; +export = eq; diff --git a/node_modules/@types/lodash/escape.d.ts b/node_modules/@types/lodash/escape.d.ts new file mode 100644 index 0000000..9f628a3 --- /dev/null +++ b/node_modules/@types/lodash/escape.d.ts @@ -0,0 +1,2 @@ +import { escape } from "./index"; +export = escape; diff --git a/node_modules/@types/lodash/escapeRegExp.d.ts b/node_modules/@types/lodash/escapeRegExp.d.ts new file mode 100644 index 0000000..97519c1 --- /dev/null +++ b/node_modules/@types/lodash/escapeRegExp.d.ts @@ -0,0 +1,2 @@ +import { escapeRegExp } from "./index"; +export = escapeRegExp; diff --git a/node_modules/@types/lodash/every.d.ts b/node_modules/@types/lodash/every.d.ts new file mode 100644 index 0000000..d9717d4 --- /dev/null +++ b/node_modules/@types/lodash/every.d.ts @@ -0,0 +1,2 @@ +import { every } from "./index"; +export = every; diff --git a/node_modules/@types/lodash/extend.d.ts b/node_modules/@types/lodash/extend.d.ts new file mode 100644 index 0000000..1b3107a --- /dev/null +++ b/node_modules/@types/lodash/extend.d.ts @@ -0,0 +1,2 @@ +import { extend } from "./index"; +export = extend; diff --git a/node_modules/@types/lodash/extendWith.d.ts b/node_modules/@types/lodash/extendWith.d.ts new file mode 100644 index 0000000..99ca5d0 --- /dev/null +++ b/node_modules/@types/lodash/extendWith.d.ts @@ -0,0 +1,2 @@ +import { extendWith } from "./index"; +export = extendWith; diff --git a/node_modules/@types/lodash/fill.d.ts b/node_modules/@types/lodash/fill.d.ts new file mode 100644 index 0000000..f595dfc --- /dev/null +++ b/node_modules/@types/lodash/fill.d.ts @@ -0,0 +1,2 @@ +import { fill } from "./index"; +export = fill; diff --git a/node_modules/@types/lodash/filter.d.ts b/node_modules/@types/lodash/filter.d.ts new file mode 100644 index 0000000..a4496de --- /dev/null +++ b/node_modules/@types/lodash/filter.d.ts @@ -0,0 +1,2 @@ +import { filter } from "./index"; +export = filter; diff --git a/node_modules/@types/lodash/find.d.ts b/node_modules/@types/lodash/find.d.ts new file mode 100644 index 0000000..e8da4b4 --- /dev/null +++ b/node_modules/@types/lodash/find.d.ts @@ -0,0 +1,2 @@ +import { find } from "./index"; +export = find; diff --git a/node_modules/@types/lodash/findIndex.d.ts b/node_modules/@types/lodash/findIndex.d.ts new file mode 100644 index 0000000..6b72444 --- /dev/null +++ b/node_modules/@types/lodash/findIndex.d.ts @@ -0,0 +1,2 @@ +import { findIndex } from "./index"; +export = findIndex; diff --git a/node_modules/@types/lodash/findKey.d.ts b/node_modules/@types/lodash/findKey.d.ts new file mode 100644 index 0000000..90230b4 --- /dev/null +++ b/node_modules/@types/lodash/findKey.d.ts @@ -0,0 +1,2 @@ +import { findKey } from "./index"; +export = findKey; diff --git a/node_modules/@types/lodash/findLast.d.ts b/node_modules/@types/lodash/findLast.d.ts new file mode 100644 index 0000000..c4f24fc --- /dev/null +++ b/node_modules/@types/lodash/findLast.d.ts @@ -0,0 +1,2 @@ +import { findLast } from "./index"; +export = findLast; diff --git a/node_modules/@types/lodash/findLastIndex.d.ts b/node_modules/@types/lodash/findLastIndex.d.ts new file mode 100644 index 0000000..21856e5 --- /dev/null +++ b/node_modules/@types/lodash/findLastIndex.d.ts @@ -0,0 +1,2 @@ +import { findLastIndex } from "./index"; +export = findLastIndex; diff --git a/node_modules/@types/lodash/findLastKey.d.ts b/node_modules/@types/lodash/findLastKey.d.ts new file mode 100644 index 0000000..ed7ff79 --- /dev/null +++ b/node_modules/@types/lodash/findLastKey.d.ts @@ -0,0 +1,2 @@ +import { findLastKey } from "./index"; +export = findLastKey; diff --git a/node_modules/@types/lodash/first.d.ts b/node_modules/@types/lodash/first.d.ts new file mode 100644 index 0000000..fd1cda7 --- /dev/null +++ b/node_modules/@types/lodash/first.d.ts @@ -0,0 +1,2 @@ +import { first } from "./index"; +export = first; diff --git a/node_modules/@types/lodash/flatMap.d.ts b/node_modules/@types/lodash/flatMap.d.ts new file mode 100644 index 0000000..0057053 --- /dev/null +++ b/node_modules/@types/lodash/flatMap.d.ts @@ -0,0 +1,2 @@ +import { flatMap } from "./index"; +export = flatMap; diff --git a/node_modules/@types/lodash/flatMapDeep.d.ts b/node_modules/@types/lodash/flatMapDeep.d.ts new file mode 100644 index 0000000..c65639a --- /dev/null +++ b/node_modules/@types/lodash/flatMapDeep.d.ts @@ -0,0 +1,2 @@ +import { flatMapDeep } from "./index"; +export = flatMapDeep; diff --git a/node_modules/@types/lodash/flatMapDepth.d.ts b/node_modules/@types/lodash/flatMapDepth.d.ts new file mode 100644 index 0000000..7ec1853 --- /dev/null +++ b/node_modules/@types/lodash/flatMapDepth.d.ts @@ -0,0 +1,2 @@ +import { flatMapDepth } from "./index"; +export = flatMapDepth; diff --git a/node_modules/@types/lodash/flatten.d.ts b/node_modules/@types/lodash/flatten.d.ts new file mode 100644 index 0000000..43ac0f4 --- /dev/null +++ b/node_modules/@types/lodash/flatten.d.ts @@ -0,0 +1,2 @@ +import { flatten } from "./index"; +export = flatten; diff --git a/node_modules/@types/lodash/flattenDeep.d.ts b/node_modules/@types/lodash/flattenDeep.d.ts new file mode 100644 index 0000000..df08bfa --- /dev/null +++ b/node_modules/@types/lodash/flattenDeep.d.ts @@ -0,0 +1,2 @@ +import { flattenDeep } from "./index"; +export = flattenDeep; diff --git a/node_modules/@types/lodash/flattenDepth.d.ts b/node_modules/@types/lodash/flattenDepth.d.ts new file mode 100644 index 0000000..f6be541 --- /dev/null +++ b/node_modules/@types/lodash/flattenDepth.d.ts @@ -0,0 +1,2 @@ +import { flattenDepth } from "./index"; +export = flattenDepth; diff --git a/node_modules/@types/lodash/flip.d.ts b/node_modules/@types/lodash/flip.d.ts new file mode 100644 index 0000000..48c9924 --- /dev/null +++ b/node_modules/@types/lodash/flip.d.ts @@ -0,0 +1,2 @@ +import { flip } from "./index"; +export = flip; diff --git a/node_modules/@types/lodash/floor.d.ts b/node_modules/@types/lodash/floor.d.ts new file mode 100644 index 0000000..a101e5d --- /dev/null +++ b/node_modules/@types/lodash/floor.d.ts @@ -0,0 +1,2 @@ +import { floor } from "./index"; +export = floor; diff --git a/node_modules/@types/lodash/flow.d.ts b/node_modules/@types/lodash/flow.d.ts new file mode 100644 index 0000000..37af0d4 --- /dev/null +++ b/node_modules/@types/lodash/flow.d.ts @@ -0,0 +1,2 @@ +import { flow } from "./index"; +export = flow; diff --git a/node_modules/@types/lodash/flowRight.d.ts b/node_modules/@types/lodash/flowRight.d.ts new file mode 100644 index 0000000..6c63f3e --- /dev/null +++ b/node_modules/@types/lodash/flowRight.d.ts @@ -0,0 +1,2 @@ +import { flowRight } from "./index"; +export = flowRight; diff --git a/node_modules/@types/lodash/forEach.d.ts b/node_modules/@types/lodash/forEach.d.ts new file mode 100644 index 0000000..8416aab --- /dev/null +++ b/node_modules/@types/lodash/forEach.d.ts @@ -0,0 +1,2 @@ +import { forEach } from "./index"; +export = forEach; diff --git a/node_modules/@types/lodash/forEachRight.d.ts b/node_modules/@types/lodash/forEachRight.d.ts new file mode 100644 index 0000000..af65b5c --- /dev/null +++ b/node_modules/@types/lodash/forEachRight.d.ts @@ -0,0 +1,2 @@ +import { forEachRight } from "./index"; +export = forEachRight; diff --git a/node_modules/@types/lodash/forIn.d.ts b/node_modules/@types/lodash/forIn.d.ts new file mode 100644 index 0000000..77d6f48 --- /dev/null +++ b/node_modules/@types/lodash/forIn.d.ts @@ -0,0 +1,2 @@ +import { forIn } from "./index"; +export = forIn; diff --git a/node_modules/@types/lodash/forInRight.d.ts b/node_modules/@types/lodash/forInRight.d.ts new file mode 100644 index 0000000..d732969 --- /dev/null +++ b/node_modules/@types/lodash/forInRight.d.ts @@ -0,0 +1,2 @@ +import { forInRight } from "./index"; +export = forInRight; diff --git a/node_modules/@types/lodash/forOwn.d.ts b/node_modules/@types/lodash/forOwn.d.ts new file mode 100644 index 0000000..dfa930f --- /dev/null +++ b/node_modules/@types/lodash/forOwn.d.ts @@ -0,0 +1,2 @@ +import { forOwn } from "./index"; +export = forOwn; diff --git a/node_modules/@types/lodash/forOwnRight.d.ts b/node_modules/@types/lodash/forOwnRight.d.ts new file mode 100644 index 0000000..fddde6a --- /dev/null +++ b/node_modules/@types/lodash/forOwnRight.d.ts @@ -0,0 +1,2 @@ +import { forOwnRight } from "./index"; +export = forOwnRight; diff --git a/node_modules/@types/lodash/fp.d.ts b/node_modules/@types/lodash/fp.d.ts new file mode 100644 index 0000000..9b6cf52 --- /dev/null +++ b/node_modules/@types/lodash/fp.d.ts @@ -0,0 +1,4803 @@ +// AUTO-GENERATED: do not modify this file directly. +// If you need to make changes, modify generate-fp.ts (if necessary), then open a terminal in types/lodash/scripts, and do: +// npm install && npm run generate + +import lodash = require("./index"); + +export = _; + +declare const _: _.LoDashFp; +declare namespace _ { + interface LodashAdd { + (augend: number): LodashAdd1x1; + (augend: lodash.__, addend: number): LodashAdd1x2; + (augend: number, addend: number): number; + } + type LodashAdd1x1 = (addend: number) => number; + type LodashAdd1x2 = (augend: number) => number; + interface LodashAfter { + any>(func: TFunc): LodashAfter1x1; + (func: lodash.__, n: number): LodashAfter1x2; + any>(func: TFunc, n: number): TFunc; + } + type LodashAfter1x1 = (n: number) => TFunc; + type LodashAfter1x2 = any>(func: TFunc) => TFunc; + interface LodashEvery { + (predicate: lodash.ValueIterateeCustom): LodashEvery1x1; + (predicate: lodash.__, collection: lodash.List | null | undefined): LodashEvery1x2; + (predicate: lodash.ValueIterateeCustom, collection: lodash.List | null | undefined): boolean; + (predicate: lodash.__, collection: T | null | undefined): LodashEvery2x2; + (predicate: lodash.ValueIterateeCustom, collection: T | null | undefined): boolean; + } + type LodashEvery1x1 = (collection: lodash.List | object | null | undefined) => boolean; + type LodashEvery1x2 = (predicate: lodash.ValueIterateeCustom) => boolean; + type LodashEvery2x2 = (predicate: lodash.ValueIterateeCustom) => boolean; + type LodashOverEvery = (predicates: lodash.Many<(...args: T[]) => boolean>) => (...args: T[]) => boolean; + type LodashConstant = (value: T) => () => T; + interface LodashSome { + (predicate: lodash.ValueIterateeCustom): LodashSome1x1; + (predicate: lodash.__, collection: lodash.List | null | undefined): LodashSome1x2; + (predicate: lodash.ValueIterateeCustom, collection: lodash.List | null | undefined): boolean; + (predicate: lodash.__, collection: T | null | undefined): LodashSome2x2; + (predicate: lodash.ValueIterateeCustom, collection: T | null | undefined): boolean; + } + type LodashSome1x1 = (collection: lodash.List | object | null | undefined) => boolean; + type LodashSome1x2 = (predicate: lodash.ValueIterateeCustom) => boolean; + type LodashSome2x2 = (predicate: lodash.ValueIterateeCustom) => boolean; + type LodashOverSome = (predicates: lodash.Many<(...args: T[]) => boolean>) => (...args: T[]) => boolean; + type LodashApply = (func: (...args: any[]) => TResult) => (...args: any[]) => TResult; + interface LodashAry { + (n: number): LodashAry1x1; + (n: lodash.__, func: (...args: any[]) => any): LodashAry1x2; + (n: number, func: (...args: any[]) => any): (...args: any[]) => any; + } + type LodashAry1x1 = (func: (...args: any[]) => any) => (...args: any[]) => any; + type LodashAry1x2 = (n: number) => (...args: any[]) => any; + interface LodashAssign { + (object: TObject): LodashAssign1x1; + (object: lodash.__, source: TSource): LodashAssign1x2; + (object: TObject, source: TSource): TObject & TSource; + } + type LodashAssign1x1 = (source: TSource) => TObject & TSource; + type LodashAssign1x2 = (object: TObject) => TObject & TSource; + interface LodashAssignAll { + (object: [TObject, TSource]): TObject & TSource; + (object: [TObject, TSource1, TSource2]): TObject & TSource1 & TSource2; + (object: [TObject, TSource1, TSource2, TSource3]): TObject & TSource1 & TSource2 & TSource3; + (object: [TObject, TSource1, TSource2, TSource3, TSource4]): TObject & TSource1 & TSource2 & TSource3 & TSource4; + (object: [TObject]): TObject; + (object: ReadonlyArray): any; + } + interface LodashAssignAllWith { + (customizer: lodash.AssignCustomizer): LodashAssignAllWith1x1; + (customizer: lodash.__, args: ReadonlyArray): LodashAssignAllWith1x2; + (customizer: lodash.AssignCustomizer, args: ReadonlyArray): any; + } + type LodashAssignAllWith1x1 = (args: ReadonlyArray) => any; + type LodashAssignAllWith1x2 = (customizer: lodash.AssignCustomizer) => any; + interface LodashAssignIn { + (object: TObject): LodashAssignIn1x1; + (object: lodash.__, source: TSource): LodashAssignIn1x2; + (object: TObject, source: TSource): TObject & TSource; + } + type LodashAssignIn1x1 = (source: TSource) => TObject & TSource; + type LodashAssignIn1x2 = (object: TObject) => TObject & TSource; + interface LodashAssignInAll { + (object: [TObject, TSource]): TObject & TSource; + (object: [TObject, TSource1, TSource2]): TObject & TSource1 & TSource2; + (object: [TObject, TSource1, TSource2, TSource3]): TObject & TSource1 & TSource2 & TSource3; + (object: [TObject, TSource1, TSource2, TSource3, TSource4]): TObject & TSource1 & TSource2 & TSource3 & TSource4; + (object: [TObject]): TObject; + (object: ReadonlyArray): TResult; + } + interface LodashAssignInAllWith { + (customizer: lodash.AssignCustomizer): LodashAssignInAllWith1x1; + (customizer: lodash.__, args: ReadonlyArray): LodashAssignInAllWith1x2; + (customizer: lodash.AssignCustomizer, args: ReadonlyArray): any; + } + type LodashAssignInAllWith1x1 = (args: ReadonlyArray) => any; + type LodashAssignInAllWith1x2 = (customizer: lodash.AssignCustomizer) => any; + interface LodashAssignInWith { + (customizer: lodash.AssignCustomizer): LodashAssignInWith1x1; + (customizer: lodash.__, object: TObject): LodashAssignInWith1x2; + (customizer: lodash.AssignCustomizer, object: TObject): LodashAssignInWith1x3; + (customizer: lodash.__, object: lodash.__, source: TSource): LodashAssignInWith1x4; + (customizer: lodash.AssignCustomizer, object: lodash.__, source: TSource): LodashAssignInWith1x5; + (customizer: lodash.__, object: TObject, source: TSource): LodashAssignInWith1x6; + (customizer: lodash.AssignCustomizer, object: TObject, source: TSource): TObject & TSource; + } + interface LodashAssignInWith1x1 { + (object: TObject): LodashAssignInWith1x3; + (object: lodash.__, source: TSource): LodashAssignInWith1x5; + (object: TObject, source: TSource): TObject & TSource; + } + interface LodashAssignInWith1x2 { + (customizer: lodash.AssignCustomizer): LodashAssignInWith1x3; + (customizer: lodash.__, source: TSource): LodashAssignInWith1x6; + (customizer: lodash.AssignCustomizer, source: TSource): TObject & TSource; + } + type LodashAssignInWith1x3 = (source: TSource) => TObject & TSource; + interface LodashAssignInWith1x4 { + (customizer: lodash.AssignCustomizer): LodashAssignInWith1x5; + (customizer: lodash.__, object: TObject): LodashAssignInWith1x6; + (customizer: lodash.AssignCustomizer, object: TObject): TObject & TSource; + } + type LodashAssignInWith1x5 = (object: TObject) => TObject & TSource; + type LodashAssignInWith1x6 = (customizer: lodash.AssignCustomizer) => TObject & TSource; + interface LodashAssignWith { + (customizer: lodash.AssignCustomizer): LodashAssignWith1x1; + (customizer: lodash.__, object: TObject): LodashAssignWith1x2; + (customizer: lodash.AssignCustomizer, object: TObject): LodashAssignWith1x3; + (customizer: lodash.__, object: lodash.__, source: TSource): LodashAssignWith1x4; + (customizer: lodash.AssignCustomizer, object: lodash.__, source: TSource): LodashAssignWith1x5; + (customizer: lodash.__, object: TObject, source: TSource): LodashAssignWith1x6; + (customizer: lodash.AssignCustomizer, object: TObject, source: TSource): TObject & TSource; + } + interface LodashAssignWith1x1 { + (object: TObject): LodashAssignWith1x3; + (object: lodash.__, source: TSource): LodashAssignWith1x5; + (object: TObject, source: TSource): TObject & TSource; + } + interface LodashAssignWith1x2 { + (customizer: lodash.AssignCustomizer): LodashAssignWith1x3; + (customizer: lodash.__, source: TSource): LodashAssignWith1x6; + (customizer: lodash.AssignCustomizer, source: TSource): TObject & TSource; + } + type LodashAssignWith1x3 = (source: TSource) => TObject & TSource; + interface LodashAssignWith1x4 { + (customizer: lodash.AssignCustomizer): LodashAssignWith1x5; + (customizer: lodash.__, object: TObject): LodashAssignWith1x6; + (customizer: lodash.AssignCustomizer, object: TObject): TObject & TSource; + } + type LodashAssignWith1x5 = (object: TObject) => TObject & TSource; + type LodashAssignWith1x6 = (customizer: lodash.AssignCustomizer) => TObject & TSource; + interface LodashSet { + (path: lodash.PropertyPath): LodashSet1x1; + (path: lodash.__, value: any): LodashSet1x2; + (path: lodash.PropertyPath, value: any): LodashSet1x3; + (path: lodash.__, value: lodash.__, object: T): LodashSet1x4; + (path: lodash.PropertyPath, value: lodash.__, object: T): LodashSet1x5; + (path: lodash.__, value: any, object: T): LodashSet1x6; + (path: lodash.PropertyPath, value: any, object: T): T; + (path: lodash.__, value: lodash.__, object: object): LodashSet2x4; + (path: lodash.PropertyPath, value: lodash.__, object: object): LodashSet2x5; + (path: lodash.__, value: any, object: object): LodashSet2x6; + (path: lodash.PropertyPath, value: any, object: object): TResult; + } + interface LodashSet1x1 { + (value: any): LodashSet1x3; + (value: lodash.__, object: T): LodashSet1x5; + (value: any, object: T): T; + (value: lodash.__, object: object): LodashSet2x5; + (value: any, object: object): TResult; + } + interface LodashSet1x2 { + (path: lodash.PropertyPath): LodashSet1x3; + (path: lodash.__, object: T): LodashSet1x6; + (path: lodash.PropertyPath, object: T): T; + (path: lodash.__, object: object): LodashSet2x6; + (path: lodash.PropertyPath, object: object): TResult; + } + interface LodashSet1x3 { + (object: T): T; + (object: object): TResult; + } + interface LodashSet1x4 { + (path: lodash.PropertyPath): LodashSet1x5; + (path: lodash.__, value: any): LodashSet1x6; + (path: lodash.PropertyPath, value: any): T; + } + type LodashSet1x5 = (value: any) => T; + type LodashSet1x6 = (path: lodash.PropertyPath) => T; + interface LodashSet2x4 { + (path: lodash.PropertyPath): LodashSet2x5; + (path: lodash.__, value: any): LodashSet2x6; + (path: lodash.PropertyPath, value: any): TResult; + } + type LodashSet2x5 = (value: any) => TResult; + type LodashSet2x6 = (path: lodash.PropertyPath) => TResult; + interface LodashAt { + (props: lodash.PropertyPath): LodashAt1x1; + (props: lodash.__, object: lodash.List | lodash.Dictionary | lodash.NumericDictionary | null | undefined): LodashAt1x2; + (props: lodash.PropertyPath, object: lodash.List | lodash.Dictionary | lodash.NumericDictionary | null | undefined): T[]; + (props: lodash.Many): LodashAt2x1; + (props: lodash.__, object: T | null | undefined): LodashAt2x2; + (props: lodash.Many, object: T | null | undefined): Array; + } + type LodashAt1x1 = (object: lodash.List | lodash.Dictionary | lodash.NumericDictionary | null | undefined) => T[]; + type LodashAt1x2 = (props: lodash.PropertyPath) => T[]; + type LodashAt2x1 = (object: T | null | undefined) => Array; + type LodashAt2x2 = (props: lodash.Many) => Array; + type LodashAttempt = (func: (...args: any[]) => TResult) => TResult|Error; + interface LodashBefore { + any>(func: TFunc): LodashBefore1x1; + (func: lodash.__, n: number): LodashBefore1x2; + any>(func: TFunc, n: number): TFunc; + } + type LodashBefore1x1 = (n: number) => TFunc; + type LodashBefore1x2 = any>(func: TFunc) => TFunc; + interface LodashBind { + (func: (...args: any[]) => any): LodashBind1x1; + (func: lodash.__, thisArg: any): LodashBind1x2; + (func: (...args: any[]) => any, thisArg: any): (...args: any[]) => any; + placeholder: lodash.__; + } + type LodashBind1x1 = (thisArg: any) => (...args: any[]) => any; + type LodashBind1x2 = (func: (...args: any[]) => any) => (...args: any[]) => any; + interface LodashBindAll { + (methodNames: lodash.Many): LodashBindAll1x1; + (methodNames: lodash.__, object: T): LodashBindAll1x2; + (methodNames: lodash.Many, object: T): T; + } + type LodashBindAll1x1 = (object: T) => T; + type LodashBindAll1x2 = (methodNames: lodash.Many) => T; + interface LodashBindKey { + (object: object): LodashBindKey1x1; + (object: lodash.__, key: string): LodashBindKey1x2; + (object: object, key: string): (...args: any[]) => any; + placeholder: lodash.__; + } + type LodashBindKey1x1 = (key: string) => (...args: any[]) => any; + type LodashBindKey1x2 = (object: object) => (...args: any[]) => any; + type LodashCamelCase = (string: string) => string; + type LodashCapitalize = (string: string) => string; + type LodashCastArray = (value: lodash.Many) => T[]; + type LodashCeil = (n: number) => number; + interface LodashChunk { + (size: number): LodashChunk1x1; + (size: lodash.__, array: lodash.List | null | undefined): LodashChunk1x2; + (size: number, array: lodash.List | null | undefined): T[][]; + } + type LodashChunk1x1 = (array: lodash.List | null | undefined) => T[][]; + type LodashChunk1x2 = (size: number) => T[][]; + interface LodashClamp { + (lower: number): LodashClamp1x1; + (lower: lodash.__, upper: number): LodashClamp1x2; + (lower: number, upper: number): LodashClamp1x3; + (lower: lodash.__, upper: lodash.__, number: number): LodashClamp1x4; + (lower: number, upper: lodash.__, number: number): LodashClamp1x5; + (lower: lodash.__, upper: number, number: number): LodashClamp1x6; + (lower: number, upper: number, number: number): number; + } + interface LodashClamp1x1 { + (upper: number): LodashClamp1x3; + (upper: lodash.__, number: number): LodashClamp1x5; + (upper: number, number: number): number; + } + interface LodashClamp1x2 { + (lower: number): LodashClamp1x3; + (lower: lodash.__, number: number): LodashClamp1x6; + (lower: number, number: number): number; + } + type LodashClamp1x3 = (number: number) => number; + interface LodashClamp1x4 { + (lower: number): LodashClamp1x5; + (lower: lodash.__, upper: number): LodashClamp1x6; + (lower: number, upper: number): number; + } + type LodashClamp1x5 = (upper: number) => number; + type LodashClamp1x6 = (lower: number) => number; + type LodashClone = (value: T) => T; + type LodashCloneDeep = (value: T) => T; + interface LodashCloneDeepWith { + (customizer: lodash.CloneDeepWithCustomizer): LodashCloneDeepWith1x1; + (customizer: lodash.__, value: T): LodashCloneDeepWith1x2; + (customizer: lodash.CloneDeepWithCustomizer, value: T): any; + } + type LodashCloneDeepWith1x1 = (value: T) => any; + type LodashCloneDeepWith1x2 = (customizer: lodash.CloneDeepWithCustomizer) => any; + interface LodashCloneWith { + (customizer: lodash.CloneWithCustomizer): LodashCloneWith1x1; + (customizer: lodash.__, value: T): LodashCloneWith1x2; + (customizer: lodash.CloneWithCustomizer, value: T): TResult; + (customizer: lodash.CloneWithCustomizer): LodashCloneWith2x1; + (customizer: lodash.CloneWithCustomizer, value: T): TResult | T; + } + type LodashCloneWith1x1 = (value: T) => TResult; + interface LodashCloneWith1x2 { + (customizer: lodash.CloneWithCustomizer): TResult; + (customizer: lodash.CloneWithCustomizer): TResult | T; + } + type LodashCloneWith2x1 = (value: T) => TResult | T; + type LodashCompact = (array: lodash.List | null | undefined) => T[]; + interface LodashNegate { + (predicate: () => boolean): () => boolean; + (predicate: (a1: A1) => boolean): (a1: A1) => boolean; + (predicate: (a1: A1, a2: A2) => boolean): (a1: A1, a2: A2) => boolean; + (predicate: (...args: any[]) => any): (...args: any[]) => boolean; + } + interface LodashFlowRight { + (f2: (a: R1) => R2, f1: () => R1): () => R2; + (f3: (a: R2) => R3, f2: (a: R1) => R2, f1: () => R1): () => R3; + (f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: () => R1): () => R4; + (f5: (a: R4) => R5, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: () => R1): () => R5; + (f6: (a: R5) => R6, f5: (a: R4) => R5, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: () => R1): () => R6; + (f7: (a: R6) => R7, f6: (a: R5) => R6, f5: (a: R4) => R5, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: () => R1): () => R7; + (f2: (a: R1) => R2, f1: (a1: A1) => R1): (a1: A1) => R2; + (f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1) => R1): (a1: A1) => R3; + (f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1) => R1): (a1: A1) => R4; + (f5: (a: R4) => R5, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1) => R1): (a1: A1) => R5; + (f6: (a: R5) => R6, f5: (a: R4) => R5, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1) => R1): (a1: A1) => R6; + (f7: (a: R6) => R7, f6: (a: R5) => R6, f5: (a: R4) => R5, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1) => R1): (a1: A1) => R7; + (f2: (a: R1) => R2, f1: (a1: A1, a2: A2) => R1): (a1: A1, a2: A2) => R2; + (f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1, a2: A2) => R1): (a1: A1, a2: A2) => R3; + (f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1, a2: A2) => R1): (a1: A1, a2: A2) => R4; + (f5: (a: R4) => R5, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1, a2: A2) => R1): (a1: A1, a2: A2) => R5; + (f6: (a: R5) => R6, f5: (a: R4) => R5, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1, a2: A2) => R1): (a1: A1, a2: A2) => R6; + (f7: (a: R6) => R7, f6: (a: R5) => R6, f5: (a: R4) => R5, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1, a2: A2) => R1): (a1: A1, a2: A2) => R7; + (f2: (a: R1) => R2, f1: (a1: A1, a2: A2, a3: A3) => R1): (a1: A1, a2: A2, a3: A3) => R2; + (f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1, a2: A2, a3: A3) => R1): (a1: A1, a2: A2, a3: A3) => R3; + (f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1, a2: A2, a3: A3) => R1): (a1: A1, a2: A2, a3: A3) => R4; + (f5: (a: R4) => R5, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1, a2: A2, a3: A3) => R1): (a1: A1, a2: A2, a3: A3) => R5; + (f6: (a: R5) => R6, f5: (a: R4) => R5, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1, a2: A2, a3: A3) => R1): (a1: A1, a2: A2, a3: A3) => R6; + (f7: (a: R6) => R7, f6: (a: R5) => R6, f5: (a: R4) => R5, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1, a2: A2, a3: A3) => R1): (a1: A1, a2: A2, a3: A3) => R7; + (f2: (a: R1) => R2, f1: (a1: A1, a2: A2, a3: A3, a4: A4) => R1): (a1: A1, a2: A2, a3: A3, a4: A4) => R2; + (f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1, a2: A2, a3: A3, a4: A4) => R1): (a1: A1, a2: A2, a3: A3, a4: A4) => R3; + (f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1, a2: A2, a3: A3, a4: A4) => R1): (a1: A1, a2: A2, a3: A3, a4: A4) => R4; + (f5: (a: R4) => R5, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1, a2: A2, a3: A3, a4: A4) => R1): (a1: A1, a2: A2, a3: A3, a4: A4) => R5; + (f6: (a: R5) => R6, f5: (a: R4) => R5, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1, a2: A2, a3: A3, a4: A4) => R1): (a1: A1, a2: A2, a3: A3, a4: A4) => R6; + (f7: (a: R6) => R7, f6: (a: R5) => R6, f5: (a: R4) => R5, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1, a2: A2, a3: A3, a4: A4) => R1): (a1: A1, a2: A2, a3: A3, a4: A4) => R7; + (f2: (a: R1) => R2, f1: (...args: any[]) => R1): (...args: any[]) => R2; + (f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (...args: any[]) => R1): (...args: any[]) => R3; + (f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (...args: any[]) => R1): (...args: any[]) => R4; + (f5: (a: R4) => R5, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (...args: any[]) => R1): (...args: any[]) => R5; + (f6: (a: R5) => R6, f5: (a: R4) => R5, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (...args: any[]) => R1): (...args: any[]) => R6; + (f7: (a: R6) => R7, f6: (a: R5) => R6, f5: (a: R4) => R5, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (...args: any[]) => R1): (...args: any[]) => R7; + (f7: (a: any) => any, f6: (a: any) => any, f5: (a: any) => any, f4: (a: any) => any, f3: (a: any) => any, f2: (a: any) => any, f1: () => any, ...funcs: Array any>>): (...args: any[]) => any; + (funcs: Array any>>): (...args: any[]) => any; + } + interface LodashConcat { + (array: lodash.Many): LodashConcat1x1; + (array: lodash.__, values: lodash.Many): LodashConcat1x2; + (array: lodash.Many, values: lodash.Many): T[]; + } + type LodashConcat1x1 = (values: lodash.Many) => T[]; + type LodashConcat1x2 = (array: lodash.Many) => T[]; + type LodashCond = (pairs: Array>) => (Target: T) => R; + interface LodashConformsTo { + (source: lodash.ConformsPredicateObject): LodashConformsTo1x1; + (source: lodash.__, object: T): LodashConformsTo1x2; + (source: lodash.ConformsPredicateObject, object: T): boolean; + } + type LodashConformsTo1x1 = (object: T) => boolean; + type LodashConformsTo1x2 = (source: lodash.ConformsPredicateObject) => boolean; + interface LodashContains { + (target: T): LodashContains1x1; + (target: lodash.__, collection: lodash.List | lodash.Dictionary | lodash.NumericDictionary | null | undefined): LodashContains1x2; + (target: T, collection: lodash.List | lodash.Dictionary | lodash.NumericDictionary | null | undefined): boolean; + } + type LodashContains1x1 = (collection: lodash.List | lodash.Dictionary | lodash.NumericDictionary | null | undefined) => boolean; + type LodashContains1x2 = (target: T) => boolean; + interface LodashCountBy { + (iteratee: lodash.ValueIteratee): LodashCountBy1x1; + (iteratee: lodash.__, collection: lodash.List | null | undefined): LodashCountBy1x2; + (iteratee: lodash.ValueIteratee, collection: lodash.List | null | undefined): lodash.Dictionary; + (iteratee: lodash.__, collection: T | null | undefined): LodashCountBy2x2; + (iteratee: lodash.ValueIteratee, collection: T | null | undefined): lodash.Dictionary; + } + type LodashCountBy1x1 = (collection: lodash.List | object | null | undefined) => lodash.Dictionary; + type LodashCountBy1x2 = (iteratee: lodash.ValueIteratee) => lodash.Dictionary; + type LodashCountBy2x2 = (iteratee: lodash.ValueIteratee) => lodash.Dictionary; + type LodashCreate = (prototype: T) => T & U; + interface LodashCurry { + (func: (t1: T1) => R): lodash.CurriedFunction1; + (func: (t1: T1, t2: T2) => R): lodash.CurriedFunction2; + (func: (t1: T1, t2: T2, t3: T3) => R): lodash.CurriedFunction3; + (func: (t1: T1, t2: T2, t3: T3, t4: T4) => R): lodash.CurriedFunction4; + (func: (t1: T1, t2: T2, t3: T3, t4: T4, t5: T5) => R): lodash.CurriedFunction5; + (func: (...args: any[]) => any): (...args: any[]) => any; + placeholder: lodash.__; + } + interface LodashCurryN { + (arity: number): LodashCurryN1x1; + (arity: lodash.__, func: (t1: T1) => R): LodashCurryN1x2; + (arity: number, func: (t1: T1) => R): lodash.CurriedFunction1; + (arity: lodash.__, func: (t1: T1, t2: T2) => R): LodashCurryN2x2; + (arity: number, func: (t1: T1, t2: T2) => R): lodash.CurriedFunction2; + (arity: lodash.__, func: (t1: T1, t2: T2, t3: T3) => R): LodashCurryN3x2; + (arity: number, func: (t1: T1, t2: T2, t3: T3) => R): lodash.CurriedFunction3; + (arity: lodash.__, func: (t1: T1, t2: T2, t3: T3, t4: T4) => R): LodashCurryN4x2; + (arity: number, func: (t1: T1, t2: T2, t3: T3, t4: T4) => R): lodash.CurriedFunction4; + (arity: lodash.__, func: (t1: T1, t2: T2, t3: T3, t4: T4, t5: T5) => R): LodashCurryN5x2; + (arity: number, func: (t1: T1, t2: T2, t3: T3, t4: T4, t5: T5) => R): lodash.CurriedFunction5; + (arity: lodash.__, func: (...args: any[]) => any): LodashCurryN6x2; + (arity: number, func: (...args: any[]) => any): (...args: any[]) => any; + placeholder: lodash.__; + } + interface LodashCurryN1x1 { + (func: (t1: T1) => R): lodash.CurriedFunction1; + (func: (t1: T1, t2: T2) => R): lodash.CurriedFunction2; + (func: (t1: T1, t2: T2, t3: T3) => R): lodash.CurriedFunction3; + (func: (t1: T1, t2: T2, t3: T3, t4: T4) => R): lodash.CurriedFunction4; + (func: (t1: T1, t2: T2, t3: T3, t4: T4, t5: T5) => R): lodash.CurriedFunction5; + (func: (...args: any[]) => any): (...args: any[]) => any; + } + type LodashCurryN1x2 = (arity: number) => lodash.CurriedFunction1; + type LodashCurryN2x2 = (arity: number) => lodash.CurriedFunction2; + type LodashCurryN3x2 = (arity: number) => lodash.CurriedFunction3; + type LodashCurryN4x2 = (arity: number) => lodash.CurriedFunction4; + type LodashCurryN5x2 = (arity: number) => lodash.CurriedFunction5; + type LodashCurryN6x2 = (arity: number) => (...args: any[]) => any; + interface LodashCurryRight { + (func: (t1: T1) => R): lodash.RightCurriedFunction1; + (func: (t1: T1, t2: T2) => R): lodash.RightCurriedFunction2; + (func: (t1: T1, t2: T2, t3: T3) => R): lodash.RightCurriedFunction3; + (func: (t1: T1, t2: T2, t3: T3, t4: T4) => R): lodash.RightCurriedFunction4; + (func: (t1: T1, t2: T2, t3: T3, t4: T4, t5: T5) => R): lodash.RightCurriedFunction5; + (func: (...args: any[]) => any): (...args: any[]) => any; + placeholder: lodash.__; + } + interface LodashCurryRightN { + (arity: number): LodashCurryRightN1x1; + (arity: lodash.__, func: (t1: T1) => R): LodashCurryRightN1x2; + (arity: number, func: (t1: T1) => R): lodash.RightCurriedFunction1; + (arity: lodash.__, func: (t1: T1, t2: T2) => R): LodashCurryRightN2x2; + (arity: number, func: (t1: T1, t2: T2) => R): lodash.RightCurriedFunction2; + (arity: lodash.__, func: (t1: T1, t2: T2, t3: T3) => R): LodashCurryRightN3x2; + (arity: number, func: (t1: T1, t2: T2, t3: T3) => R): lodash.RightCurriedFunction3; + (arity: lodash.__, func: (t1: T1, t2: T2, t3: T3, t4: T4) => R): LodashCurryRightN4x2; + (arity: number, func: (t1: T1, t2: T2, t3: T3, t4: T4) => R): lodash.RightCurriedFunction4; + (arity: lodash.__, func: (t1: T1, t2: T2, t3: T3, t4: T4, t5: T5) => R): LodashCurryRightN5x2; + (arity: number, func: (t1: T1, t2: T2, t3: T3, t4: T4, t5: T5) => R): lodash.RightCurriedFunction5; + (arity: lodash.__, func: (...args: any[]) => any): LodashCurryRightN6x2; + (arity: number, func: (...args: any[]) => any): (...args: any[]) => any; + placeholder: lodash.__; + } + interface LodashCurryRightN1x1 { + (func: (t1: T1) => R): lodash.RightCurriedFunction1; + (func: (t1: T1, t2: T2) => R): lodash.RightCurriedFunction2; + (func: (t1: T1, t2: T2, t3: T3) => R): lodash.RightCurriedFunction3; + (func: (t1: T1, t2: T2, t3: T3, t4: T4) => R): lodash.RightCurriedFunction4; + (func: (t1: T1, t2: T2, t3: T3, t4: T4, t5: T5) => R): lodash.RightCurriedFunction5; + (func: (...args: any[]) => any): (...args: any[]) => any; + } + type LodashCurryRightN1x2 = (arity: number) => lodash.RightCurriedFunction1; + type LodashCurryRightN2x2 = (arity: number) => lodash.RightCurriedFunction2; + type LodashCurryRightN3x2 = (arity: number) => lodash.RightCurriedFunction3; + type LodashCurryRightN4x2 = (arity: number) => lodash.RightCurriedFunction4; + type LodashCurryRightN5x2 = (arity: number) => lodash.RightCurriedFunction5; + type LodashCurryRightN6x2 = (arity: number) => (...args: any[]) => any; + interface LodashDebounce { + (wait: number): LodashDebounce1x1; + any>(wait: lodash.__, func: T): LodashDebounce1x2; + any>(wait: number, func: T): T & lodash.Cancelable; + } + type LodashDebounce1x1 = any>(func: T) => T & lodash.Cancelable; + type LodashDebounce1x2 = (wait: number) => T & lodash.Cancelable; + type LodashDeburr = (string: string) => string; + interface LodashDefaults { + (source: TSource): LodashDefaults1x1; + (source: lodash.__, object: TObject): LodashDefaults1x2; + (source: TSource, object: TObject): TSource & TObject; + } + type LodashDefaults1x1 = (object: TObject) => TSource & TObject; + type LodashDefaults1x2 = (source: TSource) => TSource & TObject; + interface LodashDefaultsAll { + (object: [TObject, TSource]): TSource & TObject; + (object: [TObject, TSource1, TSource2]): TSource2 & TSource1 & TObject; + (object: [TObject, TSource1, TSource2, TSource3]): TSource3 & TSource2 & TSource1 & TObject; + (object: [TObject, TSource1, TSource2, TSource3, TSource4]): TSource4 & TSource3 & TSource2 & TSource1 & TObject; + (object: [TObject]): TObject; + (object: ReadonlyArray): any; + } + interface LodashDefaultsDeep { + (sources: any): LodashDefaultsDeep1x1; + (sources: lodash.__, object: any): LodashDefaultsDeep1x2; + (sources: any, object: any): any; + } + type LodashDefaultsDeep1x1 = (object: any) => any; + type LodashDefaultsDeep1x2 = (sources: any) => any; + type LodashDefaultsDeepAll = (object: ReadonlyArray) => any; + interface LodashDefaultTo { + (defaultValue: T): LodashDefaultTo1x1; + (defaultValue: lodash.__, value: T | null | undefined): LodashDefaultTo1x2; + (defaultValue: T, value: T | null | undefined): T; + (defaultValue: TDefault): LodashDefaultTo2x1; + (defaultValue: TDefault, value: T | null | undefined): T | TDefault; + } + type LodashDefaultTo1x1 = (value: T | null | undefined) => T; + interface LodashDefaultTo1x2 { + (defaultValue: T): T; + (defaultValue: TDefault): T | TDefault; + } + type LodashDefaultTo2x1 = (value: T | null | undefined) => T | TDefault; + type LodashDefer = (func: (...args: any[]) => any, ...args: any[]) => number; + interface LodashDelay { + (wait: number): LodashDelay1x1; + (wait: lodash.__, func: (...args: any[]) => any): LodashDelay1x2; + (wait: number, func: (...args: any[]) => any): number; + } + type LodashDelay1x1 = (func: (...args: any[]) => any) => number; + type LodashDelay1x2 = (wait: number) => number; + interface LodashDifference { + (array: lodash.List | null | undefined): LodashDifference1x1; + (array: lodash.__, values: lodash.List): LodashDifference1x2; + (array: lodash.List | null | undefined, values: lodash.List): T[]; + } + type LodashDifference1x1 = (values: lodash.List) => T[]; + type LodashDifference1x2 = (array: lodash.List | null | undefined) => T[]; + interface LodashDifferenceBy { + (iteratee: lodash.ValueIteratee): LodashDifferenceBy1x1; + (iteratee: lodash.__, array: lodash.List | null | undefined): LodashDifferenceBy1x2; + (iteratee: lodash.ValueIteratee, array: lodash.List | null | undefined): LodashDifferenceBy1x3; + (iteratee: lodash.__, array: lodash.__, values: lodash.List): LodashDifferenceBy1x4; + (iteratee: lodash.ValueIteratee, array: lodash.__, values: lodash.List): LodashDifferenceBy1x5; + (iteratee: lodash.__, array: lodash.List | null | undefined, values: lodash.List): LodashDifferenceBy1x6; + (iteratee: lodash.ValueIteratee, array: lodash.List | null | undefined, values: lodash.List): T1[]; + } + interface LodashDifferenceBy1x1 { + (array: lodash.List | null | undefined): LodashDifferenceBy1x3; + (array: lodash.__, values: lodash.List): LodashDifferenceBy1x5; + (array: lodash.List | null | undefined, values: lodash.List): T1[]; + } + interface LodashDifferenceBy1x2 { + (iteratee: lodash.ValueIteratee): LodashDifferenceBy1x3; + (iteratee: lodash.__, values: lodash.List): LodashDifferenceBy1x6; + (iteratee: lodash.ValueIteratee, values: lodash.List): T1[]; + } + type LodashDifferenceBy1x3 = (values: lodash.List) => T1[]; + interface LodashDifferenceBy1x4 { + (iteratee: lodash.ValueIteratee): LodashDifferenceBy1x5; + (iteratee: lodash.__, array: lodash.List | null | undefined): LodashDifferenceBy1x6; + (iteratee: lodash.ValueIteratee, array: lodash.List | null | undefined): T1[]; + } + type LodashDifferenceBy1x5 = (array: lodash.List | null | undefined) => T1[]; + type LodashDifferenceBy1x6 = (iteratee: lodash.ValueIteratee) => T1[]; + interface LodashDifferenceWith { + (comparator: lodash.Comparator2): LodashDifferenceWith1x1; + (comparator: lodash.__, array: lodash.List | null | undefined): LodashDifferenceWith1x2; + (comparator: lodash.Comparator2, array: lodash.List | null | undefined): LodashDifferenceWith1x3; + (comparator: lodash.__, array: lodash.__, values: lodash.List): LodashDifferenceWith1x4; + (comparator: lodash.Comparator2, array: lodash.__, values: lodash.List): LodashDifferenceWith1x5; + (comparator: lodash.__, array: lodash.List | null | undefined, values: lodash.List): LodashDifferenceWith1x6; + (comparator: lodash.Comparator2, array: lodash.List | null | undefined, values: lodash.List): T1[]; + } + interface LodashDifferenceWith1x1 { + (array: lodash.List | null | undefined): LodashDifferenceWith1x3; + (array: lodash.__, values: lodash.List): LodashDifferenceWith1x5; + (array: lodash.List | null | undefined, values: lodash.List): T1[]; + } + interface LodashDifferenceWith1x2 { + (comparator: lodash.Comparator2): LodashDifferenceWith1x3; + (comparator: lodash.__, values: lodash.List): LodashDifferenceWith1x6; + (comparator: lodash.Comparator2, values: lodash.List): T1[]; + } + type LodashDifferenceWith1x3 = (values: lodash.List) => T1[]; + interface LodashDifferenceWith1x4 { + (comparator: lodash.Comparator2): LodashDifferenceWith1x5; + (comparator: lodash.__, array: lodash.List | null | undefined): LodashDifferenceWith1x6; + (comparator: lodash.Comparator2, array: lodash.List | null | undefined): T1[]; + } + type LodashDifferenceWith1x5 = (array: lodash.List | null | undefined) => T1[]; + type LodashDifferenceWith1x6 = (comparator: lodash.Comparator2) => T1[]; + interface LodashUnset { + (path: lodash.PropertyPath): LodashUnset1x1; + (path: lodash.__, object: T): LodashUnset1x2; + (path: lodash.PropertyPath, object: T): T; + } + type LodashUnset1x1 = (object: T) => T; + type LodashUnset1x2 = (path: lodash.PropertyPath) => T; + interface LodashDivide { + (dividend: number): LodashDivide1x1; + (dividend: lodash.__, divisor: number): LodashDivide1x2; + (dividend: number, divisor: number): number; + } + type LodashDivide1x1 = (divisor: number) => number; + type LodashDivide1x2 = (dividend: number) => number; + interface LodashDrop { + (n: number): LodashDrop1x1; + (n: lodash.__, array: lodash.List | null | undefined): LodashDrop1x2; + (n: number, array: lodash.List | null | undefined): T[]; + } + type LodashDrop1x1 = (array: lodash.List | null | undefined) => T[]; + type LodashDrop1x2 = (n: number) => T[]; + interface LodashDropRight { + (n: number): LodashDropRight1x1; + (n: lodash.__, array: lodash.List | null | undefined): LodashDropRight1x2; + (n: number, array: lodash.List | null | undefined): T[]; + } + type LodashDropRight1x1 = (array: lodash.List | null | undefined) => T[]; + type LodashDropRight1x2 = (n: number) => T[]; + interface LodashDropRightWhile { + (predicate: lodash.ValueIteratee): LodashDropRightWhile1x1; + (predicate: lodash.__, array: lodash.List | null | undefined): LodashDropRightWhile1x2; + (predicate: lodash.ValueIteratee, array: lodash.List | null | undefined): T[]; + } + type LodashDropRightWhile1x1 = (array: lodash.List | null | undefined) => T[]; + type LodashDropRightWhile1x2 = (predicate: lodash.ValueIteratee) => T[]; + interface LodashDropWhile { + (predicate: lodash.ValueIteratee): LodashDropWhile1x1; + (predicate: lodash.__, array: lodash.List | null | undefined): LodashDropWhile1x2; + (predicate: lodash.ValueIteratee, array: lodash.List | null | undefined): T[]; + } + type LodashDropWhile1x1 = (array: lodash.List | null | undefined) => T[]; + type LodashDropWhile1x2 = (predicate: lodash.ValueIteratee) => T[]; + interface LodashForEach { + (iteratee: (value: T) => any): LodashForEach1x1; + (iteratee: lodash.__, collection: ReadonlyArray): LodashForEach1x2; + (iteratee: (value: T) => any, collection: ReadonlyArray): T[]; + (iteratee: (value: string) => any): LodashForEach2x1; + (iteratee: lodash.__, collection: string): LodashForEach2x2; + (iteratee: (value: string) => any, collection: string): string; + (iteratee: lodash.__, collection: lodash.List): LodashForEach3x2; + (iteratee: (value: T) => any, collection: lodash.List): lodash.List; + (iteratee: lodash.__, collection: T): LodashForEach4x2; + (iteratee: (value: T[keyof T]) => any, collection: T): T; + (iteratee: lodash.__, collection: TArray & (T[] | null | undefined)): LodashForEach5x2; + (iteratee: (value: T) => any, collection: TArray & (T[] | null | undefined)): TArray; + (iteratee: lodash.__, collection: TString): LodashForEach6x2; + (iteratee: (value: string) => any, collection: TString): TString; + | null | undefined>(iteratee: lodash.__, collection: TList & (lodash.List | null | undefined)): LodashForEach7x2; + | null | undefined>(iteratee: (value: T) => any, collection: TList & (lodash.List | null | undefined)): TList; + (iteratee: lodash.__, collection: T | null | undefined): LodashForEach8x2; + (iteratee: (value: T[keyof T]) => any, collection: T | null | undefined): T | null | undefined; + } + interface LodashForEach1x1 { + (collection: ReadonlyArray): T[]; + (collection: lodash.List): lodash.List; + (collection: T1): T1; + (collection: TArray & (T[] | null | undefined)): TArray; + | null | undefined>(collection: TList & (lodash.List | null | undefined)): TList; + (collection: T1 | null | undefined): T1 | null | undefined; + } + type LodashForEach1x2 = (iteratee: (value: T) => any) => T[]; + interface LodashForEach2x1 { + (collection: string): string; + (collection: TString): TString; + } + type LodashForEach2x2 = (iteratee: (value: string) => any) => string; + type LodashForEach3x2 = (iteratee: (value: T) => any) => lodash.List; + type LodashForEach4x2 = (iteratee: (value: T[keyof T]) => any) => T; + type LodashForEach5x2 = (iteratee: (value: T) => any) => TArray; + type LodashForEach6x2 = (iteratee: (value: string) => any) => TString; + type LodashForEach7x2 = (iteratee: (value: T) => any) => TList; + type LodashForEach8x2 = (iteratee: (value: T[keyof T]) => any) => T | null | undefined; + interface LodashForEachRight { + (iteratee: (value: T) => any): LodashForEachRight1x1; + (iteratee: lodash.__, collection: ReadonlyArray): LodashForEachRight1x2; + (iteratee: (value: T) => any, collection: ReadonlyArray): T[]; + (iteratee: (value: string) => any): LodashForEachRight2x1; + (iteratee: lodash.__, collection: string): LodashForEachRight2x2; + (iteratee: (value: string) => any, collection: string): string; + (iteratee: lodash.__, collection: lodash.List): LodashForEachRight3x2; + (iteratee: (value: T) => any, collection: lodash.List): lodash.List; + (iteratee: lodash.__, collection: T): LodashForEachRight4x2; + (iteratee: (value: T[keyof T]) => any, collection: T): T; + (iteratee: lodash.__, collection: TArray & (T[] | null | undefined)): LodashForEachRight5x2; + (iteratee: (value: T) => any, collection: TArray & (T[] | null | undefined)): TArray; + (iteratee: lodash.__, collection: TString): LodashForEachRight6x2; + (iteratee: (value: string) => any, collection: TString): TString; + | null | undefined>(iteratee: lodash.__, collection: TList & (lodash.List | null | undefined)): LodashForEachRight7x2; + | null | undefined>(iteratee: (value: T) => any, collection: TList & (lodash.List | null | undefined)): TList; + (iteratee: lodash.__, collection: T | null | undefined): LodashForEachRight8x2; + (iteratee: (value: T[keyof T]) => any, collection: T | null | undefined): T | null | undefined; + } + interface LodashForEachRight1x1 { + (collection: ReadonlyArray): T[]; + (collection: lodash.List): lodash.List; + (collection: T1): T1; + (collection: TArray & (T[] | null | undefined)): TArray; + | null | undefined>(collection: TList & (lodash.List | null | undefined)): TList; + (collection: T1 | null | undefined): T1 | null | undefined; + } + type LodashForEachRight1x2 = (iteratee: (value: T) => any) => T[]; + interface LodashForEachRight2x1 { + (collection: string): string; + (collection: TString): TString; + } + type LodashForEachRight2x2 = (iteratee: (value: string) => any) => string; + type LodashForEachRight3x2 = (iteratee: (value: T) => any) => lodash.List; + type LodashForEachRight4x2 = (iteratee: (value: T[keyof T]) => any) => T; + type LodashForEachRight5x2 = (iteratee: (value: T) => any) => TArray; + type LodashForEachRight6x2 = (iteratee: (value: string) => any) => TString; + type LodashForEachRight7x2 = (iteratee: (value: T) => any) => TList; + type LodashForEachRight8x2 = (iteratee: (value: T[keyof T]) => any) => T | null | undefined; + interface LodashEndsWith { + (target: string): LodashEndsWith1x1; + (target: lodash.__, string: string): LodashEndsWith1x2; + (target: string, string: string): boolean; + } + type LodashEndsWith1x1 = (string: string) => boolean; + type LodashEndsWith1x2 = (target: string) => boolean; + interface LodashToPairs { + (object: lodash.Dictionary | lodash.NumericDictionary): Array<[string, T]>; + (object: object): Array<[string, any]>; + } + interface LodashToPairsIn { + (object: lodash.Dictionary | lodash.NumericDictionary): Array<[string, T]>; + (object: object): Array<[string, any]>; + } + interface LodashEq { + (value: any): LodashEq1x1; + (value: lodash.__, other: any): LodashEq1x2; + (value: any, other: any): boolean; + } + type LodashEq1x1 = (other: any) => boolean; + type LodashEq1x2 = (value: any) => boolean; + interface LodashIsEqual { + (value: any): LodashIsEqual1x1; + (value: lodash.__, other: any): LodashIsEqual1x2; + (value: any, other: any): boolean; + } + type LodashIsEqual1x1 = (other: any) => boolean; + type LodashIsEqual1x2 = (value: any) => boolean; + type LodashEscape = (string: string) => string; + type LodashEscapeRegExp = (string: string) => string; + interface LodashExtend { + (object: TObject): LodashExtend1x1; + (object: lodash.__, source: TSource): LodashExtend1x2; + (object: TObject, source: TSource): TObject & TSource; + } + type LodashExtend1x1 = (source: TSource) => TObject & TSource; + type LodashExtend1x2 = (object: TObject) => TObject & TSource; + interface LodashExtendAll { + (object: [TObject, TSource]): TObject & TSource; + (object: [TObject, TSource1, TSource2]): TObject & TSource1 & TSource2; + (object: [TObject, TSource1, TSource2, TSource3]): TObject & TSource1 & TSource2 & TSource3; + (object: [TObject, TSource1, TSource2, TSource3, TSource4]): TObject & TSource1 & TSource2 & TSource3 & TSource4; + (object: [TObject]): TObject; + (object: ReadonlyArray): TResult; + } + interface LodashExtendAllWith { + (customizer: lodash.AssignCustomizer): LodashExtendAllWith1x1; + (customizer: lodash.__, args: ReadonlyArray): LodashExtendAllWith1x2; + (customizer: lodash.AssignCustomizer, args: ReadonlyArray): any; + } + type LodashExtendAllWith1x1 = (args: ReadonlyArray) => any; + type LodashExtendAllWith1x2 = (customizer: lodash.AssignCustomizer) => any; + interface LodashExtendWith { + (customizer: lodash.AssignCustomizer): LodashExtendWith1x1; + (customizer: lodash.__, object: TObject): LodashExtendWith1x2; + (customizer: lodash.AssignCustomizer, object: TObject): LodashExtendWith1x3; + (customizer: lodash.__, object: lodash.__, source: TSource): LodashExtendWith1x4; + (customizer: lodash.AssignCustomizer, object: lodash.__, source: TSource): LodashExtendWith1x5; + (customizer: lodash.__, object: TObject, source: TSource): LodashExtendWith1x6; + (customizer: lodash.AssignCustomizer, object: TObject, source: TSource): TObject & TSource; + } + interface LodashExtendWith1x1 { + (object: TObject): LodashExtendWith1x3; + (object: lodash.__, source: TSource): LodashExtendWith1x5; + (object: TObject, source: TSource): TObject & TSource; + } + interface LodashExtendWith1x2 { + (customizer: lodash.AssignCustomizer): LodashExtendWith1x3; + (customizer: lodash.__, source: TSource): LodashExtendWith1x6; + (customizer: lodash.AssignCustomizer, source: TSource): TObject & TSource; + } + type LodashExtendWith1x3 = (source: TSource) => TObject & TSource; + interface LodashExtendWith1x4 { + (customizer: lodash.AssignCustomizer): LodashExtendWith1x5; + (customizer: lodash.__, object: TObject): LodashExtendWith1x6; + (customizer: lodash.AssignCustomizer, object: TObject): TObject & TSource; + } + type LodashExtendWith1x5 = (object: TObject) => TObject & TSource; + type LodashExtendWith1x6 = (customizer: lodash.AssignCustomizer) => TObject & TSource; + type LodashStubFalse = () => false; + interface LodashFill { + (start: number): LodashFill1x1; + (start: lodash.__, end: number): LodashFill1x2; + (start: number, end: number): LodashFill1x3; + (start: lodash.__, end: lodash.__, value: T): LodashFill1x4; + (start: number, end: lodash.__, value: T): LodashFill1x5; + (start: lodash.__, end: number, value: T): LodashFill1x6; + (start: number, end: number, value: T): LodashFill1x7; + (start: lodash.__, end: lodash.__, value: lodash.__, array: U[] | null | undefined): LodashFill1x8; + (start: number, end: lodash.__, value: lodash.__, array: U[] | null | undefined): LodashFill1x9; + (start: lodash.__, end: number, value: lodash.__, array: U[] | null | undefined): LodashFill1x10; + (start: number, end: number, value: lodash.__, array: U[] | null | undefined): LodashFill1x11; + (start: lodash.__, end: lodash.__, value: T, array: U[] | null | undefined): LodashFill1x12; + (start: number, end: lodash.__, value: T, array: U[] | null | undefined): LodashFill1x13; + (start: lodash.__, end: number, value: T, array: U[] | null | undefined): LodashFill1x14; + (start: number, end: number, value: T, array: U[] | null | undefined): Array; + (start: lodash.__, end: lodash.__, value: lodash.__, array: lodash.List | null | undefined): LodashFill2x8; + (start: number, end: lodash.__, value: lodash.__, array: lodash.List | null | undefined): LodashFill2x9; + (start: lodash.__, end: number, value: lodash.__, array: lodash.List | null | undefined): LodashFill2x10; + (start: number, end: number, value: lodash.__, array: lodash.List | null | undefined): LodashFill2x11; + (start: lodash.__, end: lodash.__, value: T, array: lodash.List | null | undefined): LodashFill2x12; + (start: number, end: lodash.__, value: T, array: lodash.List | null | undefined): LodashFill2x13; + (start: lodash.__, end: number, value: T, array: lodash.List | null | undefined): LodashFill2x14; + (start: number, end: number, value: T, array: lodash.List | null | undefined): lodash.List; + } + interface LodashFill1x1 { + (end: number): LodashFill1x3; + (end: lodash.__, value: T): LodashFill1x5; + (end: number, value: T): LodashFill1x7; + (end: lodash.__, value: lodash.__, array: U[] | null | undefined): LodashFill1x9; + (end: number, value: lodash.__, array: U[] | null | undefined): LodashFill1x11; + (end: lodash.__, value: T, array: U[] | null | undefined): LodashFill1x13; + (end: number, value: T, array: U[] | null | undefined): Array; + (end: lodash.__, value: lodash.__, array: lodash.List | null | undefined): LodashFill2x9; + (end: number, value: lodash.__, array: lodash.List | null | undefined): LodashFill2x11; + (end: lodash.__, value: T, array: lodash.List | null | undefined): LodashFill2x13; + (end: number, value: T, array: lodash.List | null | undefined): lodash.List; + } + interface LodashFill1x2 { + (start: number): LodashFill1x3; + (start: lodash.__, value: T): LodashFill1x6; + (start: number, value: T): LodashFill1x7; + (start: lodash.__, value: lodash.__, array: U[] | null | undefined): LodashFill1x10; + (start: number, value: lodash.__, array: U[] | null | undefined): LodashFill1x11; + (start: lodash.__, value: T, array: U[] | null | undefined): LodashFill1x14; + (start: number, value: T, array: U[] | null | undefined): Array; + (start: lodash.__, value: lodash.__, array: lodash.List | null | undefined): LodashFill2x10; + (start: number, value: lodash.__, array: lodash.List | null | undefined): LodashFill2x11; + (start: lodash.__, value: T, array: lodash.List | null | undefined): LodashFill2x14; + (start: number, value: T, array: lodash.List | null | undefined): lodash.List; + } + interface LodashFill1x3 { + (value: T): LodashFill1x7; + (value: lodash.__, array: U[] | null | undefined): LodashFill1x11; + (value: T, array: U[] | null | undefined): Array; + (value: lodash.__, array: lodash.List | null | undefined): LodashFill2x11; + (value: T, array: lodash.List | null | undefined): lodash.List; + } + interface LodashFill1x4 { + (start: number): LodashFill1x5; + (start: lodash.__, end: number): LodashFill1x6; + (start: number, end: number): LodashFill1x7; + (start: lodash.__, end: lodash.__, array: U[] | null | undefined): LodashFill1x12; + (start: number, end: lodash.__, array: U[] | null | undefined): LodashFill1x13; + (start: lodash.__, end: number, array: U[] | null | undefined): LodashFill1x14; + (start: number, end: number, array: U[] | null | undefined): Array; + (start: lodash.__, end: lodash.__, array: lodash.List | null | undefined): LodashFill2x12; + (start: number, end: lodash.__, array: lodash.List | null | undefined): LodashFill2x13; + (start: lodash.__, end: number, array: lodash.List | null | undefined): LodashFill2x14; + (start: number, end: number, array: lodash.List | null | undefined): lodash.List; + } + interface LodashFill1x5 { + (end: number): LodashFill1x7; + (end: lodash.__, array: U[] | null | undefined): LodashFill1x13; + (end: number, array: U[] | null | undefined): Array; + (end: lodash.__, array: lodash.List | null | undefined): LodashFill2x13; + (end: number, array: lodash.List | null | undefined): lodash.List; + } + interface LodashFill1x6 { + (start: number): LodashFill1x7; + (start: lodash.__, array: U[] | null | undefined): LodashFill1x14; + (start: number, array: U[] | null | undefined): Array; + (start: lodash.__, array: lodash.List | null | undefined): LodashFill2x14; + (start: number, array: lodash.List | null | undefined): lodash.List; + } + interface LodashFill1x7 { + (array: U[] | null | undefined): Array; + (array: lodash.List | null | undefined): lodash.List; + } + interface LodashFill1x8 { + (start: number): LodashFill1x9; + (start: lodash.__, end: number): LodashFill1x10; + (start: number, end: number): LodashFill1x11; + (start: lodash.__, end: lodash.__, value: T): LodashFill1x12; + (start: number, end: lodash.__, value: T): LodashFill1x13; + (start: lodash.__, end: number, value: T): LodashFill1x14; + (start: number, end: number, value: T): Array; + } + interface LodashFill1x9 { + (end: number): LodashFill1x11; + (end: lodash.__, value: T): LodashFill1x13; + (end: number, value: T): Array; + } + interface LodashFill1x10 { + (start: number): LodashFill1x11; + (start: lodash.__, value: T): LodashFill1x14; + (start: number, value: T): Array; + } + type LodashFill1x11 = (value: T) => Array; + interface LodashFill1x12 { + (start: number): LodashFill1x13; + (start: lodash.__, end: number): LodashFill1x14; + (start: number, end: number): Array; + } + type LodashFill1x13 = (end: number) => Array; + type LodashFill1x14 = (start: number) => Array; + interface LodashFill2x8 { + (start: number): LodashFill2x9; + (start: lodash.__, end: number): LodashFill2x10; + (start: number, end: number): LodashFill2x11; + (start: lodash.__, end: lodash.__, value: T): LodashFill2x12; + (start: number, end: lodash.__, value: T): LodashFill2x13; + (start: lodash.__, end: number, value: T): LodashFill2x14; + (start: number, end: number, value: T): lodash.List; + } + interface LodashFill2x9 { + (end: number): LodashFill2x11; + (end: lodash.__, value: T): LodashFill2x13; + (end: number, value: T): lodash.List; + } + interface LodashFill2x10 { + (start: number): LodashFill2x11; + (start: lodash.__, value: T): LodashFill2x14; + (start: number, value: T): lodash.List; + } + type LodashFill2x11 = (value: T) => lodash.List; + interface LodashFill2x12 { + (start: number): LodashFill2x13; + (start: lodash.__, end: number): LodashFill2x14; + (start: number, end: number): lodash.List; + } + type LodashFill2x13 = (end: number) => lodash.List; + type LodashFill2x14 = (start: number) => lodash.List; + interface LodashFilter { + (predicate: (value: string) => boolean): LodashFilter1x1; + (predicate: lodash.__, collection: string | null | undefined): LodashFilter1x2; + (predicate: (value: string) => boolean, collection: string | null | undefined): string[]; + (predicate: lodash.ValueIteratorTypeGuard): LodashFilter2x1; + (predicate: lodash.__, collection: lodash.List | null | undefined): LodashFilter2x2; + (predicate: lodash.ValueIteratorTypeGuard, collection: lodash.List | null | undefined): S[]; + (predicate: lodash.ValueIterateeCustom): LodashFilter3x1; + (predicate: lodash.ValueIterateeCustom, collection: lodash.List | null | undefined): T[]; + (predicate: lodash.ValueIteratorTypeGuard): LodashFilter4x1; + (predicate: lodash.__, collection: T | null | undefined): LodashFilter4x2; + (predicate: lodash.ValueIteratorTypeGuard, collection: T | null | undefined): S[]; + (predicate: lodash.ValueIterateeCustom, collection: T | null | undefined): Array; + } + type LodashFilter1x1 = (collection: string | null | undefined) => string[]; + type LodashFilter1x2 = (predicate: (value: string) => boolean) => string[]; + type LodashFilter2x1 = (collection: lodash.List | null | undefined) => S[]; + interface LodashFilter2x2 { + (predicate: lodash.ValueIteratorTypeGuard): S[]; + (predicate: lodash.ValueIterateeCustom): T[]; + } + type LodashFilter3x1 = (collection: lodash.List | object | null | undefined) => T[]; + type LodashFilter4x1 = (collection: T | null | undefined) => S[]; + interface LodashFilter4x2 { + (predicate: lodash.ValueIteratorTypeGuard): S[]; + (predicate: lodash.ValueIterateeCustom): Array; + } + interface LodashFind { + (predicate: lodash.ValueIteratorTypeGuard): LodashFind1x1; + (predicate: lodash.__, collection: lodash.List | null | undefined): LodashFind1x2; + (predicate: lodash.ValueIteratorTypeGuard, collection: lodash.List | null | undefined): S|undefined; + (predicate: lodash.ValueIterateeCustom): LodashFind2x1; + (predicate: lodash.ValueIterateeCustom, collection: lodash.List | null | undefined): T|undefined; + (predicate: lodash.ValueIteratorTypeGuard): LodashFind3x1; + (predicate: lodash.__, collection: T | null | undefined): LodashFind3x2; + (predicate: lodash.ValueIteratorTypeGuard, collection: T | null | undefined): S|undefined; + (predicate: lodash.ValueIterateeCustom, collection: T | null | undefined): T[keyof T]|undefined; + } + type LodashFind1x1 = (collection: lodash.List | null | undefined) => S|undefined; + interface LodashFind1x2 { + (predicate: lodash.ValueIteratorTypeGuard): S|undefined; + (predicate: lodash.ValueIterateeCustom): T|undefined; + } + type LodashFind2x1 = (collection: lodash.List | object | null | undefined) => T|undefined; + type LodashFind3x1 = (collection: T | null | undefined) => S|undefined; + interface LodashFind3x2 { + (predicate: lodash.ValueIteratorTypeGuard): S|undefined; + (predicate: lodash.ValueIterateeCustom): T[keyof T]|undefined; + } + interface LodashFindFrom { + (predicate: lodash.ValueIteratorTypeGuard): LodashFindFrom1x1; + (predicate: lodash.__, fromIndex: number): LodashFindFrom1x2; + (predicate: lodash.ValueIteratorTypeGuard, fromIndex: number): LodashFindFrom1x3; + (predicate: lodash.__, fromIndex: lodash.__, collection: lodash.List | null | undefined): LodashFindFrom1x4; + (predicate: lodash.ValueIteratorTypeGuard, fromIndex: lodash.__, collection: lodash.List | null | undefined): LodashFindFrom1x5; + (predicate: lodash.__, fromIndex: number, collection: lodash.List | null | undefined): LodashFindFrom1x6; + (predicate: lodash.ValueIteratorTypeGuard, fromIndex: number, collection: lodash.List | null | undefined): S|undefined; + (predicate: lodash.ValueIterateeCustom): LodashFindFrom2x1; + (predicate: lodash.ValueIterateeCustom, fromIndex: number): LodashFindFrom2x3; + (predicate: lodash.ValueIterateeCustom, fromIndex: lodash.__, collection: lodash.List | null | undefined): LodashFindFrom2x5; + (predicate: lodash.ValueIterateeCustom, fromIndex: number, collection: lodash.List | null | undefined): T|undefined; + (predicate: lodash.ValueIteratorTypeGuard): LodashFindFrom3x1; + (predicate: lodash.ValueIteratorTypeGuard, fromIndex: number): LodashFindFrom3x3; + (predicate: lodash.__, fromIndex: lodash.__, collection: T | null | undefined): LodashFindFrom3x4; + (predicate: lodash.ValueIteratorTypeGuard, fromIndex: lodash.__, collection: T | null | undefined): LodashFindFrom3x5; + (predicate: lodash.__, fromIndex: number, collection: T | null | undefined): LodashFindFrom3x6; + (predicate: lodash.ValueIteratorTypeGuard, fromIndex: number, collection: T | null | undefined): S|undefined; + (predicate: lodash.ValueIterateeCustom, fromIndex: lodash.__, collection: T | null | undefined): LodashFindFrom4x5; + (predicate: lodash.ValueIterateeCustom, fromIndex: number, collection: T | null | undefined): T[keyof T]|undefined; + } + interface LodashFindFrom1x1 { + (fromIndex: number): LodashFindFrom1x3; + (fromIndex: lodash.__, collection: lodash.List | null | undefined): LodashFindFrom1x5; + (fromIndex: number, collection: lodash.List | null | undefined): S|undefined; + } + interface LodashFindFrom1x2 { + (predicate: lodash.ValueIteratorTypeGuard): LodashFindFrom1x3; + (predicate: lodash.__, collection: lodash.List | null | undefined): LodashFindFrom1x6; + (predicate: lodash.ValueIteratorTypeGuard, collection: lodash.List | null | undefined): S|undefined; + (predicate: lodash.ValueIterateeCustom): LodashFindFrom2x3; + (predicate: lodash.ValueIterateeCustom, collection: lodash.List | null | undefined): T|undefined; + (predicate: lodash.ValueIteratorTypeGuard): LodashFindFrom3x3; + (predicate: lodash.__, collection: T | null | undefined): LodashFindFrom3x6; + (predicate: lodash.ValueIteratorTypeGuard, collection: T | null | undefined): S|undefined; + (predicate: lodash.ValueIterateeCustom, collection: T | null | undefined): T[keyof T]|undefined; + } + type LodashFindFrom1x3 = (collection: lodash.List | null | undefined) => S|undefined; + interface LodashFindFrom1x4 { + (predicate: lodash.ValueIteratorTypeGuard): LodashFindFrom1x5; + (predicate: lodash.__, fromIndex: number): LodashFindFrom1x6; + (predicate: lodash.ValueIteratorTypeGuard, fromIndex: number): S|undefined; + (predicate: lodash.ValueIterateeCustom): LodashFindFrom2x5; + (predicate: lodash.ValueIterateeCustom, fromIndex: number): T|undefined; + } + type LodashFindFrom1x5 = (fromIndex: number) => S|undefined; + interface LodashFindFrom1x6 { + (predicate: lodash.ValueIteratorTypeGuard): S|undefined; + (predicate: lodash.ValueIterateeCustom): T|undefined; + } + interface LodashFindFrom2x1 { + (fromIndex: number): LodashFindFrom2x3; + (fromIndex: lodash.__, collection: lodash.List | null | undefined): LodashFindFrom2x5; + (fromIndex: number, collection: lodash.List | object | null | undefined): T|undefined; + (fromIndex: lodash.__, collection: T1 | null | undefined): LodashFindFrom4x5; + } + interface LodashFindFrom2x3 { + (collection: lodash.List | null | undefined): T|undefined; + (collection: object | null | undefined): object|undefined; + } + type LodashFindFrom2x5 = (fromIndex: number) => T|undefined; + interface LodashFindFrom3x1 { + (fromIndex: number): LodashFindFrom3x3; + (fromIndex: lodash.__, collection: T | null | undefined): LodashFindFrom3x5; + (fromIndex: number, collection: T | null | undefined): S|undefined; + } + type LodashFindFrom3x3 = (collection: T | null | undefined) => S|undefined; + interface LodashFindFrom3x4 { + (predicate: lodash.ValueIteratorTypeGuard): LodashFindFrom3x5; + (predicate: lodash.__, fromIndex: number): LodashFindFrom3x6; + (predicate: lodash.ValueIteratorTypeGuard, fromIndex: number): S|undefined; + (predicate: lodash.ValueIterateeCustom): LodashFindFrom4x5; + (predicate: lodash.ValueIterateeCustom, fromIndex: number): T[keyof T]|undefined; + } + type LodashFindFrom3x5 = (fromIndex: number) => S|undefined; + interface LodashFindFrom3x6 { + (predicate: lodash.ValueIteratorTypeGuard): S|undefined; + (predicate: lodash.ValueIterateeCustom): T[keyof T]|undefined; + } + type LodashFindFrom4x5 = (fromIndex: number) => T[keyof T]|undefined; + interface LodashFindIndex { + (predicate: lodash.ValueIterateeCustom): LodashFindIndex1x1; + (predicate: lodash.__, array: lodash.List | null | undefined): LodashFindIndex1x2; + (predicate: lodash.ValueIterateeCustom, array: lodash.List | null | undefined): number; + } + type LodashFindIndex1x1 = (array: lodash.List | null | undefined) => number; + type LodashFindIndex1x2 = (predicate: lodash.ValueIterateeCustom) => number; + interface LodashFindIndexFrom { + (predicate: lodash.ValueIterateeCustom): LodashFindIndexFrom1x1; + (predicate: lodash.__, fromIndex: number): LodashFindIndexFrom1x2; + (predicate: lodash.ValueIterateeCustom, fromIndex: number): LodashFindIndexFrom1x3; + (predicate: lodash.__, fromIndex: lodash.__, array: lodash.List | null | undefined): LodashFindIndexFrom1x4; + (predicate: lodash.ValueIterateeCustom, fromIndex: lodash.__, array: lodash.List | null | undefined): LodashFindIndexFrom1x5; + (predicate: lodash.__, fromIndex: number, array: lodash.List | null | undefined): LodashFindIndexFrom1x6; + (predicate: lodash.ValueIterateeCustom, fromIndex: number, array: lodash.List | null | undefined): number; + } + interface LodashFindIndexFrom1x1 { + (fromIndex: number): LodashFindIndexFrom1x3; + (fromIndex: lodash.__, array: lodash.List | null | undefined): LodashFindIndexFrom1x5; + (fromIndex: number, array: lodash.List | null | undefined): number; + } + interface LodashFindIndexFrom1x2 { + (predicate: lodash.ValueIterateeCustom): LodashFindIndexFrom1x3; + (predicate: lodash.__, array: lodash.List | null | undefined): LodashFindIndexFrom1x6; + (predicate: lodash.ValueIterateeCustom, array: lodash.List | null | undefined): number; + } + type LodashFindIndexFrom1x3 = (array: lodash.List | null | undefined) => number; + interface LodashFindIndexFrom1x4 { + (predicate: lodash.ValueIterateeCustom): LodashFindIndexFrom1x5; + (predicate: lodash.__, fromIndex: number): LodashFindIndexFrom1x6; + (predicate: lodash.ValueIterateeCustom, fromIndex: number): number; + } + type LodashFindIndexFrom1x5 = (fromIndex: number) => number; + type LodashFindIndexFrom1x6 = (predicate: lodash.ValueIterateeCustom) => number; + interface LodashFindKey { + (predicate: lodash.ValueIteratee): LodashFindKey1x1; + (predicate: lodash.__, object: T | null | undefined): LodashFindKey1x2; + (predicate: lodash.ValueIteratee, object: T | null | undefined): string | undefined; + } + type LodashFindKey1x1 = (object: object | null | undefined) => string | undefined; + type LodashFindKey1x2 = (predicate: lodash.ValueIteratee) => string | undefined; + interface LodashFindLast { + (predicate: lodash.ValueIteratorTypeGuard): LodashFindLast1x1; + (predicate: lodash.__, collection: lodash.List | null | undefined): LodashFindLast1x2; + (predicate: lodash.ValueIteratorTypeGuard, collection: lodash.List | null | undefined): S|undefined; + (predicate: lodash.ValueIterateeCustom): LodashFindLast2x1; + (predicate: lodash.ValueIterateeCustom, collection: lodash.List | null | undefined): T|undefined; + (predicate: lodash.ValueIteratorTypeGuard): LodashFindLast3x1; + (predicate: lodash.__, collection: T | null | undefined): LodashFindLast3x2; + (predicate: lodash.ValueIteratorTypeGuard, collection: T | null | undefined): S|undefined; + (predicate: lodash.ValueIterateeCustom, collection: T | null | undefined): T[keyof T]|undefined; + } + type LodashFindLast1x1 = (collection: lodash.List | null | undefined) => S|undefined; + interface LodashFindLast1x2 { + (predicate: lodash.ValueIteratorTypeGuard): S|undefined; + (predicate: lodash.ValueIterateeCustom): T|undefined; + } + type LodashFindLast2x1 = (collection: lodash.List | object | null | undefined) => T|undefined; + type LodashFindLast3x1 = (collection: T | null | undefined) => S|undefined; + interface LodashFindLast3x2 { + (predicate: lodash.ValueIteratorTypeGuard): S|undefined; + (predicate: lodash.ValueIterateeCustom): T[keyof T]|undefined; + } + interface LodashFindLastFrom { + (predicate: lodash.ValueIteratorTypeGuard): LodashFindLastFrom1x1; + (predicate: lodash.__, fromIndex: number): LodashFindLastFrom1x2; + (predicate: lodash.ValueIteratorTypeGuard, fromIndex: number): LodashFindLastFrom1x3; + (predicate: lodash.__, fromIndex: lodash.__, collection: lodash.List | null | undefined): LodashFindLastFrom1x4; + (predicate: lodash.ValueIteratorTypeGuard, fromIndex: lodash.__, collection: lodash.List | null | undefined): LodashFindLastFrom1x5; + (predicate: lodash.__, fromIndex: number, collection: lodash.List | null | undefined): LodashFindLastFrom1x6; + (predicate: lodash.ValueIteratorTypeGuard, fromIndex: number, collection: lodash.List | null | undefined): S|undefined; + (predicate: lodash.ValueIterateeCustom): LodashFindLastFrom2x1; + (predicate: lodash.ValueIterateeCustom, fromIndex: number): LodashFindLastFrom2x3; + (predicate: lodash.ValueIterateeCustom, fromIndex: lodash.__, collection: lodash.List | null | undefined): LodashFindLastFrom2x5; + (predicate: lodash.ValueIterateeCustom, fromIndex: number, collection: lodash.List | null | undefined): T|undefined; + (predicate: lodash.ValueIteratorTypeGuard): LodashFindLastFrom3x1; + (predicate: lodash.ValueIteratorTypeGuard, fromIndex: number): LodashFindLastFrom3x3; + (predicate: lodash.__, fromIndex: lodash.__, collection: T | null | undefined): LodashFindLastFrom3x4; + (predicate: lodash.ValueIteratorTypeGuard, fromIndex: lodash.__, collection: T | null | undefined): LodashFindLastFrom3x5; + (predicate: lodash.__, fromIndex: number, collection: T | null | undefined): LodashFindLastFrom3x6; + (predicate: lodash.ValueIteratorTypeGuard, fromIndex: number, collection: T | null | undefined): S|undefined; + (predicate: lodash.ValueIterateeCustom, fromIndex: lodash.__, collection: T | null | undefined): LodashFindLastFrom4x5; + (predicate: lodash.ValueIterateeCustom, fromIndex: number, collection: T | null | undefined): T[keyof T]|undefined; + } + interface LodashFindLastFrom1x1 { + (fromIndex: number): LodashFindLastFrom1x3; + (fromIndex: lodash.__, collection: lodash.List | null | undefined): LodashFindLastFrom1x5; + (fromIndex: number, collection: lodash.List | null | undefined): S|undefined; + } + interface LodashFindLastFrom1x2 { + (predicate: lodash.ValueIteratorTypeGuard): LodashFindLastFrom1x3; + (predicate: lodash.__, collection: lodash.List | null | undefined): LodashFindLastFrom1x6; + (predicate: lodash.ValueIteratorTypeGuard, collection: lodash.List | null | undefined): S|undefined; + (predicate: lodash.ValueIterateeCustom): LodashFindLastFrom2x3; + (predicate: lodash.ValueIterateeCustom, collection: lodash.List | null | undefined): T|undefined; + (predicate: lodash.ValueIteratorTypeGuard): LodashFindLastFrom3x3; + (predicate: lodash.__, collection: T | null | undefined): LodashFindLastFrom3x6; + (predicate: lodash.ValueIteratorTypeGuard, collection: T | null | undefined): S|undefined; + (predicate: lodash.ValueIterateeCustom, collection: T | null | undefined): T[keyof T]|undefined; + } + type LodashFindLastFrom1x3 = (collection: lodash.List | null | undefined) => S|undefined; + interface LodashFindLastFrom1x4 { + (predicate: lodash.ValueIteratorTypeGuard): LodashFindLastFrom1x5; + (predicate: lodash.__, fromIndex: number): LodashFindLastFrom1x6; + (predicate: lodash.ValueIteratorTypeGuard, fromIndex: number): S|undefined; + (predicate: lodash.ValueIterateeCustom): LodashFindLastFrom2x5; + (predicate: lodash.ValueIterateeCustom, fromIndex: number): T|undefined; + } + type LodashFindLastFrom1x5 = (fromIndex: number) => S|undefined; + interface LodashFindLastFrom1x6 { + (predicate: lodash.ValueIteratorTypeGuard): S|undefined; + (predicate: lodash.ValueIterateeCustom): T|undefined; + } + interface LodashFindLastFrom2x1 { + (fromIndex: number): LodashFindLastFrom2x3; + (fromIndex: lodash.__, collection: lodash.List | null | undefined): LodashFindLastFrom2x5; + (fromIndex: number, collection: lodash.List | object | null | undefined): T|undefined; + (fromIndex: lodash.__, collection: T1 | null | undefined): LodashFindLastFrom4x5; + } + interface LodashFindLastFrom2x3 { + (collection: lodash.List | null | undefined): T|undefined; + (collection: object | null | undefined): object|undefined; + } + type LodashFindLastFrom2x5 = (fromIndex: number) => T|undefined; + interface LodashFindLastFrom3x1 { + (fromIndex: number): LodashFindLastFrom3x3; + (fromIndex: lodash.__, collection: T | null | undefined): LodashFindLastFrom3x5; + (fromIndex: number, collection: T | null | undefined): S|undefined; + } + type LodashFindLastFrom3x3 = (collection: T | null | undefined) => S|undefined; + interface LodashFindLastFrom3x4 { + (predicate: lodash.ValueIteratorTypeGuard): LodashFindLastFrom3x5; + (predicate: lodash.__, fromIndex: number): LodashFindLastFrom3x6; + (predicate: lodash.ValueIteratorTypeGuard, fromIndex: number): S|undefined; + (predicate: lodash.ValueIterateeCustom): LodashFindLastFrom4x5; + (predicate: lodash.ValueIterateeCustom, fromIndex: number): T[keyof T]|undefined; + } + type LodashFindLastFrom3x5 = (fromIndex: number) => S|undefined; + interface LodashFindLastFrom3x6 { + (predicate: lodash.ValueIteratorTypeGuard): S|undefined; + (predicate: lodash.ValueIterateeCustom): T[keyof T]|undefined; + } + type LodashFindLastFrom4x5 = (fromIndex: number) => T[keyof T]|undefined; + interface LodashFindLastIndex { + (predicate: lodash.ValueIterateeCustom): LodashFindLastIndex1x1; + (predicate: lodash.__, array: lodash.List | null | undefined): LodashFindLastIndex1x2; + (predicate: lodash.ValueIterateeCustom, array: lodash.List | null | undefined): number; + } + type LodashFindLastIndex1x1 = (array: lodash.List | null | undefined) => number; + type LodashFindLastIndex1x2 = (predicate: lodash.ValueIterateeCustom) => number; + interface LodashFindLastIndexFrom { + (predicate: lodash.ValueIterateeCustom): LodashFindLastIndexFrom1x1; + (predicate: lodash.__, fromIndex: number): LodashFindLastIndexFrom1x2; + (predicate: lodash.ValueIterateeCustom, fromIndex: number): LodashFindLastIndexFrom1x3; + (predicate: lodash.__, fromIndex: lodash.__, array: lodash.List | null | undefined): LodashFindLastIndexFrom1x4; + (predicate: lodash.ValueIterateeCustom, fromIndex: lodash.__, array: lodash.List | null | undefined): LodashFindLastIndexFrom1x5; + (predicate: lodash.__, fromIndex: number, array: lodash.List | null | undefined): LodashFindLastIndexFrom1x6; + (predicate: lodash.ValueIterateeCustom, fromIndex: number, array: lodash.List | null | undefined): number; + } + interface LodashFindLastIndexFrom1x1 { + (fromIndex: number): LodashFindLastIndexFrom1x3; + (fromIndex: lodash.__, array: lodash.List | null | undefined): LodashFindLastIndexFrom1x5; + (fromIndex: number, array: lodash.List | null | undefined): number; + } + interface LodashFindLastIndexFrom1x2 { + (predicate: lodash.ValueIterateeCustom): LodashFindLastIndexFrom1x3; + (predicate: lodash.__, array: lodash.List | null | undefined): LodashFindLastIndexFrom1x6; + (predicate: lodash.ValueIterateeCustom, array: lodash.List | null | undefined): number; + } + type LodashFindLastIndexFrom1x3 = (array: lodash.List | null | undefined) => number; + interface LodashFindLastIndexFrom1x4 { + (predicate: lodash.ValueIterateeCustom): LodashFindLastIndexFrom1x5; + (predicate: lodash.__, fromIndex: number): LodashFindLastIndexFrom1x6; + (predicate: lodash.ValueIterateeCustom, fromIndex: number): number; + } + type LodashFindLastIndexFrom1x5 = (fromIndex: number) => number; + type LodashFindLastIndexFrom1x6 = (predicate: lodash.ValueIterateeCustom) => number; + interface LodashFindLastKey { + (predicate: lodash.ValueIteratee): LodashFindLastKey1x1; + (predicate: lodash.__, object: T | null | undefined): LodashFindLastKey1x2; + (predicate: lodash.ValueIteratee, object: T | null | undefined): string | undefined; + } + type LodashFindLastKey1x1 = (object: object | null | undefined) => string | undefined; + type LodashFindLastKey1x2 = (predicate: lodash.ValueIteratee) => string | undefined; + type LodashHead = (array: lodash.List | null | undefined) => T | undefined; + interface LodashFlatMap { + (iteratee: (value: T) => lodash.Many): LodashFlatMap1x1; + (iteratee: lodash.__, collection: lodash.List | null | undefined): LodashFlatMap1x2; + (iteratee: (value: T) => lodash.Many, collection: lodash.List | null | undefined): TResult[]; + (iteratee: (value: T[keyof T]) => lodash.Many): LodashFlatMap2x1; + (iteratee: lodash.__, collection: T | null | undefined): LodashFlatMap2x2; + (iteratee: (value: T[keyof T]) => lodash.Many, collection: T | null | undefined): TResult[]; + (iteratee: string): LodashFlatMap3x1; + (iteratee: lodash.__, collection: object | null | undefined): LodashFlatMap3x2; + (iteratee: string, collection: object | null | undefined): any[]; + (iteratee: object): LodashFlatMap4x1; + (iteratee: object, collection: object | null | undefined): boolean[]; + } + type LodashFlatMap1x1 = (collection: lodash.List | null | undefined) => TResult[]; + type LodashFlatMap1x2 = (iteratee: (value: T) => lodash.Many) => TResult[]; + type LodashFlatMap2x1 = (collection: T | null | undefined) => TResult[]; + type LodashFlatMap2x2 = (iteratee: (value: T[keyof T]) => lodash.Many) => TResult[]; + type LodashFlatMap3x1 = (collection: object | null | undefined) => any[]; + interface LodashFlatMap3x2 { + (iteratee: string): any[]; + (iteratee: object): boolean[]; + } + type LodashFlatMap4x1 = (collection: object | null | undefined) => boolean[]; + interface LodashFlatMapDeep { + (iteratee: (value: T) => lodash.ListOfRecursiveArraysOrValues | TResult): LodashFlatMapDeep1x1; + (iteratee: lodash.__, collection: lodash.List | null | undefined): LodashFlatMapDeep1x2; + (iteratee: (value: T) => lodash.ListOfRecursiveArraysOrValues | TResult, collection: lodash.List | null | undefined): TResult[]; + (iteratee: (value: T[keyof T]) => lodash.ListOfRecursiveArraysOrValues | TResult): LodashFlatMapDeep2x1; + (iteratee: lodash.__, collection: T | null | undefined): LodashFlatMapDeep2x2; + (iteratee: (value: T[keyof T]) => lodash.ListOfRecursiveArraysOrValues | TResult, collection: T | null | undefined): TResult[]; + (iteratee: string): LodashFlatMapDeep3x1; + (iteratee: lodash.__, collection: object | null | undefined): LodashFlatMapDeep3x2; + (iteratee: string, collection: object | null | undefined): any[]; + (iteratee: object): LodashFlatMapDeep4x1; + (iteratee: object, collection: object | null | undefined): boolean[]; + } + type LodashFlatMapDeep1x1 = (collection: lodash.List | null | undefined) => TResult[]; + type LodashFlatMapDeep1x2 = (iteratee: (value: T) => lodash.ListOfRecursiveArraysOrValues | TResult) => TResult[]; + type LodashFlatMapDeep2x1 = (collection: T | null | undefined) => TResult[]; + type LodashFlatMapDeep2x2 = (iteratee: (value: T[keyof T]) => lodash.ListOfRecursiveArraysOrValues | TResult) => TResult[]; + type LodashFlatMapDeep3x1 = (collection: object | null | undefined) => any[]; + interface LodashFlatMapDeep3x2 { + (iteratee: string): any[]; + (iteratee: object): boolean[]; + } + type LodashFlatMapDeep4x1 = (collection: object | null | undefined) => boolean[]; + interface LodashFlatMapDepth { + (iteratee: (value: T) => lodash.ListOfRecursiveArraysOrValues | TResult): LodashFlatMapDepth1x1; + (iteratee: lodash.__, depth: number): LodashFlatMapDepth1x2; + (iteratee: (value: T) => lodash.ListOfRecursiveArraysOrValues | TResult, depth: number): LodashFlatMapDepth1x3; + (iteratee: lodash.__, depth: lodash.__, collection: lodash.List | null | undefined): LodashFlatMapDepth1x4; + (iteratee: (value: T) => lodash.ListOfRecursiveArraysOrValues | TResult, depth: lodash.__, collection: lodash.List | null | undefined): LodashFlatMapDepth1x5; + (iteratee: lodash.__, depth: number, collection: lodash.List | null | undefined): LodashFlatMapDepth1x6; + (iteratee: (value: T) => lodash.ListOfRecursiveArraysOrValues | TResult, depth: number, collection: lodash.List | null | undefined): TResult[]; + (iteratee: (value: T[keyof T]) => lodash.ListOfRecursiveArraysOrValues | TResult): LodashFlatMapDepth2x1; + (iteratee: (value: T[keyof T]) => lodash.ListOfRecursiveArraysOrValues | TResult, depth: number): LodashFlatMapDepth2x3; + (iteratee: lodash.__, depth: lodash.__, collection: T | null | undefined): LodashFlatMapDepth2x4; + (iteratee: (value: T[keyof T]) => lodash.ListOfRecursiveArraysOrValues | TResult, depth: lodash.__, collection: T | null | undefined): LodashFlatMapDepth2x5; + (iteratee: lodash.__, depth: number, collection: T | null | undefined): LodashFlatMapDepth2x6; + (iteratee: (value: T[keyof T]) => lodash.ListOfRecursiveArraysOrValues | TResult, depth: number, collection: T | null | undefined): TResult[]; + (iteratee: string): LodashFlatMapDepth3x1; + (iteratee: string, depth: number): LodashFlatMapDepth3x3; + (iteratee: lodash.__, depth: lodash.__, collection: object | null | undefined): LodashFlatMapDepth3x4; + (iteratee: string, depth: lodash.__, collection: object | null | undefined): LodashFlatMapDepth3x5; + (iteratee: lodash.__, depth: number, collection: object | null | undefined): LodashFlatMapDepth3x6; + (iteratee: string, depth: number, collection: object | null | undefined): any[]; + (iteratee: object): LodashFlatMapDepth4x1; + (iteratee: object, depth: number): LodashFlatMapDepth4x3; + (iteratee: object, depth: lodash.__, collection: object | null | undefined): LodashFlatMapDepth4x5; + (iteratee: object, depth: number, collection: object | null | undefined): boolean[]; + } + interface LodashFlatMapDepth1x1 { + (depth: number): LodashFlatMapDepth1x3; + (depth: lodash.__, collection: lodash.List | null | undefined): LodashFlatMapDepth1x5; + (depth: number, collection: lodash.List | null | undefined): TResult[]; + } + interface LodashFlatMapDepth1x2 { + (iteratee: (value: T) => lodash.ListOfRecursiveArraysOrValues | TResult): LodashFlatMapDepth1x3; + (iteratee: lodash.__, collection: lodash.List | null | undefined): LodashFlatMapDepth1x6; + (iteratee: (value: T) => lodash.ListOfRecursiveArraysOrValues | TResult, collection: lodash.List | null | undefined): TResult[]; + (iteratee: (value: T[keyof T]) => lodash.ListOfRecursiveArraysOrValues | TResult): LodashFlatMapDepth2x3; + (iteratee: lodash.__, collection: T | null | undefined): LodashFlatMapDepth2x6; + (iteratee: (value: T[keyof T]) => lodash.ListOfRecursiveArraysOrValues | TResult, collection: T | null | undefined): TResult[]; + (iteratee: string): LodashFlatMapDepth3x3; + (iteratee: lodash.__, collection: object | null | undefined): LodashFlatMapDepth3x6; + (iteratee: string, collection: object | null | undefined): any[]; + (iteratee: object): LodashFlatMapDepth4x3; + (iteratee: object, collection: object | null | undefined): boolean[]; + } + type LodashFlatMapDepth1x3 = (collection: lodash.List | null | undefined) => TResult[]; + interface LodashFlatMapDepth1x4 { + (iteratee: (value: T) => lodash.ListOfRecursiveArraysOrValues | TResult): LodashFlatMapDepth1x5; + (iteratee: lodash.__, depth: number): LodashFlatMapDepth1x6; + (iteratee: (value: T) => lodash.ListOfRecursiveArraysOrValues | TResult, depth: number): TResult[]; + } + type LodashFlatMapDepth1x5 = (depth: number) => TResult[]; + type LodashFlatMapDepth1x6 = (iteratee: (value: T) => lodash.ListOfRecursiveArraysOrValues | TResult) => TResult[]; + interface LodashFlatMapDepth2x1 { + (depth: number): LodashFlatMapDepth2x3; + (depth: lodash.__, collection: T | null | undefined): LodashFlatMapDepth2x5; + (depth: number, collection: T | null | undefined): TResult[]; + } + type LodashFlatMapDepth2x3 = (collection: T | null | undefined) => TResult[]; + interface LodashFlatMapDepth2x4 { + (iteratee: (value: T[keyof T]) => lodash.ListOfRecursiveArraysOrValues | TResult): LodashFlatMapDepth2x5; + (iteratee: lodash.__, depth: number): LodashFlatMapDepth2x6; + (iteratee: (value: T[keyof T]) => lodash.ListOfRecursiveArraysOrValues | TResult, depth: number): TResult[]; + } + type LodashFlatMapDepth2x5 = (depth: number) => TResult[]; + type LodashFlatMapDepth2x6 = (iteratee: (value: T[keyof T]) => lodash.ListOfRecursiveArraysOrValues | TResult) => TResult[]; + interface LodashFlatMapDepth3x1 { + (depth: number): LodashFlatMapDepth3x3; + (depth: lodash.__, collection: object | null | undefined): LodashFlatMapDepth3x5; + (depth: number, collection: object | null | undefined): any[]; + } + type LodashFlatMapDepth3x3 = (collection: object | null | undefined) => any[]; + interface LodashFlatMapDepth3x4 { + (iteratee: string): LodashFlatMapDepth3x5; + (iteratee: lodash.__, depth: number): LodashFlatMapDepth3x6; + (iteratee: string, depth: number): any[]; + (iteratee: object): LodashFlatMapDepth4x5; + (iteratee: object, depth: number): boolean[]; + } + type LodashFlatMapDepth3x5 = (depth: number) => any[]; + interface LodashFlatMapDepth3x6 { + (iteratee: string): any[]; + (iteratee: object): boolean[]; + } + interface LodashFlatMapDepth4x1 { + (depth: number): LodashFlatMapDepth4x3; + (depth: lodash.__, collection: object | null | undefined): LodashFlatMapDepth4x5; + (depth: number, collection: object | null | undefined): boolean[]; + } + type LodashFlatMapDepth4x3 = (collection: object | null | undefined) => boolean[]; + type LodashFlatMapDepth4x5 = (depth: number) => boolean[]; + type LodashFlatten = (array: lodash.List> | null | undefined) => T[]; + type LodashFlattenDeep = (array: lodash.ListOfRecursiveArraysOrValues | null | undefined) => T[]; + interface LodashFlattenDepth { + (depth: number): LodashFlattenDepth1x1; + (depth: lodash.__, array: lodash.ListOfRecursiveArraysOrValues | null | undefined): LodashFlattenDepth1x2; + (depth: number, array: lodash.ListOfRecursiveArraysOrValues | null | undefined): T[]; + } + type LodashFlattenDepth1x1 = (array: lodash.ListOfRecursiveArraysOrValues | null | undefined) => T[]; + type LodashFlattenDepth1x2 = (depth: number) => T[]; + type LodashFlip = any>(func: T) => T; + type LodashFloor = (n: number) => number; + interface LodashFlow { + (f1: () => R1, f2: (a: R1) => R2): () => R2; + (f1: () => R1, f2: (a: R1) => R2, f3: (a: R2) => R3): () => R3; + (f1: () => R1, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4): () => R4; + (f1: () => R1, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5): () => R5; + (f1: () => R1, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6): () => R6; + (f1: () => R1, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6, f7: (a: R6) => R7): () => R7; + (f1: () => R1, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6, f7: (a: R6) => R7, ...funcs: Array any>>): () => any; + (f1: (a1: A1) => R1, f2: (a: R1) => R2): (a1: A1) => R2; + (f1: (a1: A1) => R1, f2: (a: R1) => R2, f3: (a: R2) => R3): (a1: A1) => R3; + (f1: (a1: A1) => R1, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4): (a1: A1) => R4; + (f1: (a1: A1) => R1, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5): (a1: A1) => R5; + (f1: (a1: A1) => R1, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6): (a1: A1) => R6; + (f1: (a1: A1) => R1, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6, f7: (a: R6) => R7): (a1: A1) => R7; + (f1: (a1: A1) => R1, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6, f7: (a: R6) => R7, ...funcs: Array any>>): (a1: A1) => any; + (f1: (a1: A1, a2: A2) => R1, f2: (a: R1) => R2): (a1: A1, a2: A2) => R2; + (f1: (a1: A1, a2: A2) => R1, f2: (a: R1) => R2, f3: (a: R2) => R3): (a1: A1, a2: A2) => R3; + (f1: (a1: A1, a2: A2) => R1, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4): (a1: A1, a2: A2) => R4; + (f1: (a1: A1, a2: A2) => R1, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5): (a1: A1, a2: A2) => R5; + (f1: (a1: A1, a2: A2) => R1, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6): (a1: A1, a2: A2) => R6; + (f1: (a1: A1, a2: A2) => R1, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6, f7: (a: R6) => R7): (a1: A1, a2: A2) => R7; + (f1: (a1: A1, a2: A2) => R1, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6, f7: (a: R6) => R7, ...funcs: Array any>>): (a1: A1, a2: A2) => any; + (f1: (a1: A1, a2: A2, a3: A3) => R1, f2: (a: R1) => R2): (a1: A1, a2: A2, a3: A3) => R2; + (f1: (a1: A1, a2: A2, a3: A3) => R1, f2: (a: R1) => R2, f3: (a: R2) => R3): (a1: A1, a2: A2, a3: A3) => R3; + (f1: (a1: A1, a2: A2, a3: A3) => R1, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4): (a1: A1, a2: A2, a3: A3) => R4; + (f1: (a1: A1, a2: A2, a3: A3) => R1, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5): (a1: A1, a2: A2, a3: A3) => R5; + (f1: (a1: A1, a2: A2, a3: A3) => R1, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6): (a1: A1, a2: A2, a3: A3) => R6; + (f1: (a1: A1, a2: A2, a3: A3) => R1, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6, f7: (a: R6) => R7): (a1: A1, a2: A2, a3: A3) => R7; + (f1: (a1: A1, a2: A2, a3: A3) => R1, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6, f7: (a: R6) => R7, ...funcs: Array any>>): (a1: A1, a2: A2, a3: A3) => any; + (f1: (a1: A1, a2: A2, a3: A3, a4: A4) => R1, f2: (a: R1) => R2): (a1: A1, a2: A2, a3: A3, a4: A4) => R2; + (f1: (a1: A1, a2: A2, a3: A3, a4: A4) => R1, f2: (a: R1) => R2, f3: (a: R2) => R3): (a1: A1, a2: A2, a3: A3, a4: A4) => R3; + (f1: (a1: A1, a2: A2, a3: A3, a4: A4) => R1, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4): (a1: A1, a2: A2, a3: A3, a4: A4) => R4; + (f1: (a1: A1, a2: A2, a3: A3, a4: A4) => R1, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5): (a1: A1, a2: A2, a3: A3, a4: A4) => R5; + (f1: (a1: A1, a2: A2, a3: A3, a4: A4) => R1, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6): (a1: A1, a2: A2, a3: A3, a4: A4) => R6; + (f1: (a1: A1, a2: A2, a3: A3, a4: A4) => R1, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6, f7: (a: R6) => R7): (a1: A1, a2: A2, a3: A3, a4: A4) => R7; + (f1: (a1: A1, a2: A2, a3: A3, a4: A4) => R1, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6, f7: (a: R6) => R7, ...funcs: Array any>>): (a1: A1, a2: A2, a3: A3, a4: A4) => any; + (f1: (a1: A1, a2: A2, a3: A3, a4: A4, ...args: any[]) => R1, f2: (a: R1) => R2): (a1: A1, a2: A2, a3: A3, a4: A4, ...args: any[]) => R2; + (f1: (a1: A1, a2: A2, a3: A3, a4: A4, ...args: any[]) => R1, f2: (a: R1) => R2, f3: (a: R2) => R3): (a1: A1, a2: A2, a3: A3, a4: A4, ...args: any[]) => R3; + (f1: (a1: A1, a2: A2, a3: A3, a4: A4, ...args: any[]) => R1, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4): (a1: A1, a2: A2, a3: A3, a4: A4, ...args: any[]) => R4; + (f1: (a1: A1, a2: A2, a3: A3, a4: A4, ...args: any[]) => R1, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5): (a1: A1, a2: A2, a3: A3, a4: A4, ...args: any[]) => R5; + (f1: (a1: A1, a2: A2, a3: A3, a4: A4, ...args: any[]) => R1, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6): (a1: A1, a2: A2, a3: A3, a4: A4, ...args: any[]) => R6; + (f1: (a1: A1, a2: A2, a3: A3, a4: A4, ...args: any[]) => R1, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6, f7: (a: R6) => R7): (a1: A1, a2: A2, a3: A3, a4: A4, ...args: any[]) => R7; + (f1: (a1: A1, a2: A2, a3: A3, a4: A4, ...args: any[]) => R1, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6, f7: (a: R6) => R7, ...funcs: Array any>>): (a1: A1, a2: A2, a3: A3, a4: A4, ...args: any[]) => any; + (funcs: Array any>>): (...args: any[]) => any; + } + interface LodashForIn { + (iteratee: (value: T) => any): LodashForIn1x1; + (iteratee: lodash.__, object: T): LodashForIn1x2; + (iteratee: (value: T[keyof T]) => any, object: T): T; + (iteratee: lodash.__, object: T | null | undefined): LodashForIn2x2; + (iteratee: (value: T[keyof T]) => any, object: T | null | undefined): T | null | undefined; + } + interface LodashForIn1x1 { + (object: T1): T1; + (object: T1 | null | undefined): T1 | null | undefined; + } + type LodashForIn1x2 = (iteratee: (value: T[keyof T]) => any) => T; + type LodashForIn2x2 = (iteratee: (value: T[keyof T]) => any) => T | null | undefined; + interface LodashForInRight { + (iteratee: (value: T) => any): LodashForInRight1x1; + (iteratee: lodash.__, object: T): LodashForInRight1x2; + (iteratee: (value: T[keyof T]) => any, object: T): T; + (iteratee: lodash.__, object: T | null | undefined): LodashForInRight2x2; + (iteratee: (value: T[keyof T]) => any, object: T | null | undefined): T | null | undefined; + } + interface LodashForInRight1x1 { + (object: T1): T1; + (object: T1 | null | undefined): T1 | null | undefined; + } + type LodashForInRight1x2 = (iteratee: (value: T[keyof T]) => any) => T; + type LodashForInRight2x2 = (iteratee: (value: T[keyof T]) => any) => T | null | undefined; + interface LodashForOwn { + (iteratee: (value: T) => any): LodashForOwn1x1; + (iteratee: lodash.__, object: T): LodashForOwn1x2; + (iteratee: (value: T[keyof T]) => any, object: T): T; + (iteratee: lodash.__, object: T | null | undefined): LodashForOwn2x2; + (iteratee: (value: T[keyof T]) => any, object: T | null | undefined): T | null | undefined; + } + interface LodashForOwn1x1 { + (object: T1): T1; + (object: T1 | null | undefined): T1 | null | undefined; + } + type LodashForOwn1x2 = (iteratee: (value: T[keyof T]) => any) => T; + type LodashForOwn2x2 = (iteratee: (value: T[keyof T]) => any) => T | null | undefined; + interface LodashForOwnRight { + (iteratee: (value: T) => any): LodashForOwnRight1x1; + (iteratee: lodash.__, object: T): LodashForOwnRight1x2; + (iteratee: (value: T[keyof T]) => any, object: T): T; + (iteratee: lodash.__, object: T | null | undefined): LodashForOwnRight2x2; + (iteratee: (value: T[keyof T]) => any, object: T | null | undefined): T | null | undefined; + } + interface LodashForOwnRight1x1 { + (object: T1): T1; + (object: T1 | null | undefined): T1 | null | undefined; + } + type LodashForOwnRight1x2 = (iteratee: (value: T[keyof T]) => any) => T; + type LodashForOwnRight2x2 = (iteratee: (value: T[keyof T]) => any) => T | null | undefined; + interface LodashFromPairs { + (pairs: lodash.List<[lodash.PropertyName, T]> | null | undefined): lodash.Dictionary; + (pairs: lodash.List | null | undefined): lodash.Dictionary; + } + type LodashFunctions = (object: any) => string[]; + type LodashFunctionsIn = (object: any) => string[]; + interface LodashGet { + (path: TKey | [TKey]): LodashGet1x1; + (path: lodash.__, object: TObject): LodashGet1x2; + (path: TKey | [TKey], object: TObject): TObject[TKey]; + (path: lodash.__, object: TObject | null | undefined): LodashGet2x2; + (path: TKey | [TKey], object: TObject | null | undefined): TObject[TKey] | undefined; + (path: number): LodashGet3x1; + (path: lodash.__, object: lodash.NumericDictionary): LodashGet3x2; + (path: number, object: lodash.NumericDictionary): T; + (path: lodash.__, object: lodash.NumericDictionary | null | undefined): LodashGet4x2; + (path: number, object: lodash.NumericDictionary | null | undefined): T | undefined; + (path: lodash.PropertyPath): LodashGet5x1; + (path: lodash.__, object: null | undefined): LodashGet5x2; + (path: lodash.PropertyPath, object: null | undefined): undefined; + (path: lodash.__, object: any): LodashGet6x2; + (path: lodash.PropertyPath, object: any): any; + } + interface LodashGet1x1 { + (object: TObject): TObject[TKey]; + (object: TObject | null | undefined): TObject[TKey] | undefined; + } + type LodashGet1x2 = (path: TKey | [TKey]) => TObject[TKey]; + type LodashGet2x2 = (path: TKey | [TKey]) => TObject[TKey] | undefined; + interface LodashGet3x1 { + (object: lodash.NumericDictionary): T; + (object: lodash.NumericDictionary | null | undefined): T | undefined; + } + type LodashGet3x2 = (path: number) => T; + type LodashGet4x2 = (path: number) => T | undefined; + interface LodashGet5x1 { + (object: null | undefined): undefined; + (object: any): any; + } + type LodashGet5x2 = (path: lodash.PropertyPath) => undefined; + type LodashGet6x2 = (path: lodash.PropertyPath) => any; + interface LodashGetOr { + (defaultValue: TDefault): LodashGetOr1x1; + (defaultValue: lodash.__, path: TKey | [TKey]): LodashGetOr1x2; + (defaultValue: TDefault, path: TKey | [TKey]): LodashGetOr1x3; + (defaultValue: lodash.__, path: lodash.__, object: TObject | null | undefined): LodashGetOr1x4; + (defaultValue: TDefault, path: lodash.__, object: TObject | null | undefined): LodashGetOr1x5; + (defaultValue: lodash.__, path: TKey | [TKey], object: TObject | null | undefined): LodashGetOr1x6; + (defaultValue: TDefault, path: TKey | [TKey], object: TObject | null | undefined): TObject[TKey] | TDefault; + (defaultValue: lodash.__, path: number): LodashGetOr2x2; + (defaultValue: TDefault, path: number): LodashGetOr2x3; + (defaultValue: lodash.__, path: lodash.__, object: lodash.NumericDictionary | null | undefined): LodashGetOr2x4; + (defaultValue: TDefault, path: lodash.__, object: lodash.NumericDictionary | null | undefined): LodashGetOr2x5; + (defaultValue: lodash.__, path: number, object: lodash.NumericDictionary | null | undefined): LodashGetOr2x6; + (defaultValue: TDefault, path: number, object: lodash.NumericDictionary | null | undefined): T | TDefault; + (defaultValue: lodash.__, path: lodash.PropertyPath): LodashGetOr3x2; + (defaultValue: TDefault, path: lodash.PropertyPath): LodashGetOr3x3; + (defaultValue: lodash.__, path: lodash.__, object: null | undefined): LodashGetOr3x4; + (defaultValue: TDefault, path: lodash.__, object: null | undefined): LodashGetOr3x5; + (defaultValue: lodash.__, path: lodash.PropertyPath, object: null | undefined): LodashGetOr3x6; + (defaultValue: TDefault, path: lodash.PropertyPath, object: null | undefined): TDefault; + (defaultValue: any): LodashGetOr4x1; + (defaultValue: any, path: lodash.PropertyPath): LodashGetOr4x3; + (defaultValue: lodash.__, path: lodash.__, object: any): LodashGetOr4x4; + (defaultValue: any, path: lodash.__, object: any): LodashGetOr4x5; + (defaultValue: lodash.__, path: lodash.PropertyPath, object: any): LodashGetOr4x6; + (defaultValue: any, path: lodash.PropertyPath, object: any): any; + } + interface LodashGetOr1x1 { + (path: TKey | [TKey]): LodashGetOr1x3; + (path: lodash.__, object: TObject | null | undefined): LodashGetOr1x5; + (path: TKey | [TKey], object: TObject | null | undefined): TObject[TKey] | TDefault; + (path: number): LodashGetOr2x3; + (path: lodash.__, object: lodash.NumericDictionary | null | undefined): LodashGetOr2x5; + (path: number, object: lodash.NumericDictionary | null | undefined): T | TDefault; + (path: lodash.PropertyPath): LodashGetOr3x3; + (path: lodash.__, object: null | undefined): LodashGetOr3x5; + (path: lodash.PropertyPath, object: null | undefined): TDefault; + } + interface LodashGetOr1x2 { + (defaultValue: TDefault): LodashGetOr1x3; + (defaultValue: lodash.__, object: TObject | null | undefined): LodashGetOr1x6; + (defaultValue: TDefault, object: TObject | null | undefined): TObject[TKey] | TDefault; + } + type LodashGetOr1x3 = (object: TObject | null | undefined) => TObject[TKey] | TDefault; + interface LodashGetOr1x4 { + (defaultValue: TDefault): LodashGetOr1x5; + (defaultValue: lodash.__, path: TKey | [TKey]): LodashGetOr1x6; + (defaultValue: TDefault, path: TKey | [TKey]): TObject[TKey] | TDefault; + } + type LodashGetOr1x5 = (path: TKey | [TKey]) => TObject[TKey] | TDefault; + type LodashGetOr1x6 = (defaultValue: TDefault) => TObject[TKey] | TDefault; + interface LodashGetOr2x2 { + (defaultValue: TDefault): LodashGetOr2x3; + (defaultValue: lodash.__, object: lodash.NumericDictionary | null | undefined): LodashGetOr2x6; + (defaultValue: TDefault, object: lodash.NumericDictionary | null | undefined): T | TDefault; + } + type LodashGetOr2x3 = (object: lodash.NumericDictionary | null | undefined) => T | TDefault; + interface LodashGetOr2x4 { + (defaultValue: TDefault): LodashGetOr2x5; + (defaultValue: lodash.__, path: number): LodashGetOr2x6; + (defaultValue: TDefault, path: number): T | TDefault; + } + type LodashGetOr2x5 = (path: number) => T | TDefault; + type LodashGetOr2x6 = (defaultValue: TDefault) => T | TDefault; + interface LodashGetOr3x2 { + (defaultValue: TDefault): LodashGetOr3x3; + (defaultValue: lodash.__, object: null | undefined): LodashGetOr3x6; + (defaultValue: TDefault, object: null | undefined): TDefault; + (defaultValue: any): LodashGetOr4x3; + (defaultValue: lodash.__, object: any): LodashGetOr4x6; + (defaultValue: any, object: any): any; + } + type LodashGetOr3x3 = (object: null | undefined) => TDefault; + interface LodashGetOr3x4 { + (defaultValue: TDefault): LodashGetOr3x5; + (defaultValue: lodash.__, path: lodash.PropertyPath): LodashGetOr3x6; + (defaultValue: TDefault, path: lodash.PropertyPath): TDefault; + } + type LodashGetOr3x5 = (path: lodash.PropertyPath) => TDefault; + type LodashGetOr3x6 = (defaultValue: TDefault) => TDefault; + interface LodashGetOr4x1 { + (path: lodash.PropertyPath): LodashGetOr4x3; + (path: lodash.__, object: any): LodashGetOr4x5; + (path: lodash.PropertyPath, object: any): any; + } + type LodashGetOr4x3 = (object: any) => any; + interface LodashGetOr4x4 { + (defaultValue: any): LodashGetOr4x5; + (defaultValue: lodash.__, path: lodash.PropertyPath): LodashGetOr4x6; + (defaultValue: any, path: lodash.PropertyPath): any; + } + type LodashGetOr4x5 = (path: lodash.PropertyPath) => any; + type LodashGetOr4x6 = (defaultValue: any) => any; + interface LodashGroupBy { + (iteratee: lodash.ValueIteratee): LodashGroupBy1x1; + (iteratee: lodash.__, collection: lodash.List | null | undefined): LodashGroupBy1x2; + (iteratee: lodash.ValueIteratee, collection: lodash.List | null | undefined): lodash.Dictionary; + (iteratee: lodash.__, collection: T | null | undefined): LodashGroupBy2x2; + (iteratee: lodash.ValueIteratee, collection: T | null | undefined): lodash.Dictionary>; + } + type LodashGroupBy1x1 = (collection: lodash.List | object | null | undefined) => lodash.Dictionary; + type LodashGroupBy1x2 = (iteratee: lodash.ValueIteratee) => lodash.Dictionary; + type LodashGroupBy2x2 = (iteratee: lodash.ValueIteratee) => lodash.Dictionary>; + interface LodashGt { + (value: any): LodashGt1x1; + (value: lodash.__, other: any): LodashGt1x2; + (value: any, other: any): boolean; + } + type LodashGt1x1 = (other: any) => boolean; + type LodashGt1x2 = (value: any) => boolean; + interface LodashGte { + (value: any): LodashGte1x1; + (value: lodash.__, other: any): LodashGte1x2; + (value: any, other: any): boolean; + } + type LodashGte1x1 = (other: any) => boolean; + type LodashGte1x2 = (value: any) => boolean; + interface LodashHas { + (path: lodash.PropertyPath): LodashHas1x1; + (path: lodash.__, object: T): LodashHas1x2; + (path: lodash.PropertyPath, object: T): boolean; + } + type LodashHas1x1 = (object: T) => boolean; + type LodashHas1x2 = (path: lodash.PropertyPath) => boolean; + interface LodashHasIn { + (path: lodash.PropertyPath): LodashHasIn1x1; + (path: lodash.__, object: T): LodashHasIn1x2; + (path: lodash.PropertyPath, object: T): boolean; + } + type LodashHasIn1x1 = (object: T) => boolean; + type LodashHasIn1x2 = (path: lodash.PropertyPath) => boolean; + interface LodashIdentity { + (value: T): T; + (): undefined; + } + interface LodashIncludes { + (target: T): LodashIncludes1x1; + (target: lodash.__, collection: lodash.List | lodash.Dictionary | lodash.NumericDictionary | null | undefined): LodashIncludes1x2; + (target: T, collection: lodash.List | lodash.Dictionary | lodash.NumericDictionary | null | undefined): boolean; + } + type LodashIncludes1x1 = (collection: lodash.List | lodash.Dictionary | lodash.NumericDictionary | null | undefined) => boolean; + type LodashIncludes1x2 = (target: T) => boolean; + interface LodashIncludesFrom { + (target: T): LodashIncludesFrom1x1; + (target: lodash.__, fromIndex: number): LodashIncludesFrom1x2; + (target: T, fromIndex: number): LodashIncludesFrom1x3; + (target: lodash.__, fromIndex: lodash.__, collection: lodash.List | lodash.Dictionary | lodash.NumericDictionary | null | undefined): LodashIncludesFrom1x4; + (target: T, fromIndex: lodash.__, collection: lodash.List | lodash.Dictionary | lodash.NumericDictionary | null | undefined): LodashIncludesFrom1x5; + (target: lodash.__, fromIndex: number, collection: lodash.List | lodash.Dictionary | lodash.NumericDictionary | null | undefined): LodashIncludesFrom1x6; + (target: T, fromIndex: number, collection: lodash.List | lodash.Dictionary | lodash.NumericDictionary | null | undefined): boolean; + } + interface LodashIncludesFrom1x1 { + (fromIndex: number): LodashIncludesFrom1x3; + (fromIndex: lodash.__, collection: lodash.List | lodash.Dictionary | lodash.NumericDictionary | null | undefined): LodashIncludesFrom1x5; + (fromIndex: number, collection: lodash.List | lodash.Dictionary | lodash.NumericDictionary | null | undefined): boolean; + } + interface LodashIncludesFrom1x2 { + (target: T): LodashIncludesFrom1x3; + (target: lodash.__, collection: lodash.List | lodash.Dictionary | lodash.NumericDictionary | null | undefined): LodashIncludesFrom1x6; + (target: T, collection: lodash.List | lodash.Dictionary | lodash.NumericDictionary | null | undefined): boolean; + } + type LodashIncludesFrom1x3 = (collection: lodash.List | lodash.Dictionary | lodash.NumericDictionary | null | undefined) => boolean; + interface LodashIncludesFrom1x4 { + (target: T): LodashIncludesFrom1x5; + (target: lodash.__, fromIndex: number): LodashIncludesFrom1x6; + (target: T, fromIndex: number): boolean; + } + type LodashIncludesFrom1x5 = (fromIndex: number) => boolean; + type LodashIncludesFrom1x6 = (target: T) => boolean; + interface LodashKeyBy { + (iteratee: lodash.ValueIterateeCustom): LodashKeyBy1x1; + (iteratee: lodash.__, collection: lodash.List | null | undefined): LodashKeyBy1x2; + (iteratee: lodash.ValueIterateeCustom, collection: lodash.List | null | undefined): lodash.Dictionary; + (iteratee: lodash.__, collection: T | null | undefined): LodashKeyBy2x2; + (iteratee: lodash.ValueIterateeCustom, collection: T | null | undefined): lodash.Dictionary; + } + type LodashKeyBy1x1 = (collection: lodash.List | object | null | undefined) => lodash.Dictionary; + type LodashKeyBy1x2 = (iteratee: lodash.ValueIterateeCustom) => lodash.Dictionary; + type LodashKeyBy2x2 = (iteratee: lodash.ValueIterateeCustom) => lodash.Dictionary; + interface LodashIndexOf { + (value: T): LodashIndexOf1x1; + (value: lodash.__, array: lodash.List | null | undefined): LodashIndexOf1x2; + (value: T, array: lodash.List | null | undefined): number; + } + type LodashIndexOf1x1 = (array: lodash.List | null | undefined) => number; + type LodashIndexOf1x2 = (value: T) => number; + interface LodashIndexOfFrom { + (value: T): LodashIndexOfFrom1x1; + (value: lodash.__, fromIndex: number): LodashIndexOfFrom1x2; + (value: T, fromIndex: number): LodashIndexOfFrom1x3; + (value: lodash.__, fromIndex: lodash.__, array: lodash.List | null | undefined): LodashIndexOfFrom1x4; + (value: T, fromIndex: lodash.__, array: lodash.List | null | undefined): LodashIndexOfFrom1x5; + (value: lodash.__, fromIndex: number, array: lodash.List | null | undefined): LodashIndexOfFrom1x6; + (value: T, fromIndex: number, array: lodash.List | null | undefined): number; + } + interface LodashIndexOfFrom1x1 { + (fromIndex: number): LodashIndexOfFrom1x3; + (fromIndex: lodash.__, array: lodash.List | null | undefined): LodashIndexOfFrom1x5; + (fromIndex: number, array: lodash.List | null | undefined): number; + } + interface LodashIndexOfFrom1x2 { + (value: T): LodashIndexOfFrom1x3; + (value: lodash.__, array: lodash.List | null | undefined): LodashIndexOfFrom1x6; + (value: T, array: lodash.List | null | undefined): number; + } + type LodashIndexOfFrom1x3 = (array: lodash.List | null | undefined) => number; + interface LodashIndexOfFrom1x4 { + (value: T): LodashIndexOfFrom1x5; + (value: lodash.__, fromIndex: number): LodashIndexOfFrom1x6; + (value: T, fromIndex: number): number; + } + type LodashIndexOfFrom1x5 = (fromIndex: number) => number; + type LodashIndexOfFrom1x6 = (value: T) => number; + type LodashInitial = (array: lodash.List | null | undefined) => T[]; + interface LodashInRange { + (start: number): LodashInRange1x1; + (start: lodash.__, end: number): LodashInRange1x2; + (start: number, end: number): LodashInRange1x3; + (start: lodash.__, end: lodash.__, n: number): LodashInRange1x4; + (start: number, end: lodash.__, n: number): LodashInRange1x5; + (start: lodash.__, end: number, n: number): LodashInRange1x6; + (start: number, end: number, n: number): boolean; + } + interface LodashInRange1x1 { + (end: number): LodashInRange1x3; + (end: lodash.__, n: number): LodashInRange1x5; + (end: number, n: number): boolean; + } + interface LodashInRange1x2 { + (start: number): LodashInRange1x3; + (start: lodash.__, n: number): LodashInRange1x6; + (start: number, n: number): boolean; + } + type LodashInRange1x3 = (n: number) => boolean; + interface LodashInRange1x4 { + (start: number): LodashInRange1x5; + (start: lodash.__, end: number): LodashInRange1x6; + (start: number, end: number): boolean; + } + type LodashInRange1x5 = (end: number) => boolean; + type LodashInRange1x6 = (start: number) => boolean; + interface LodashIntersection { + (arrays2: lodash.List): LodashIntersection1x1; + (arrays2: lodash.__, arrays: lodash.List): LodashIntersection1x2; + (arrays2: lodash.List, arrays: lodash.List): T[]; + } + type LodashIntersection1x1 = (arrays: lodash.List) => T[]; + type LodashIntersection1x2 = (arrays2: lodash.List) => T[]; + interface LodashIntersectionBy { + (iteratee: lodash.ValueIteratee): LodashIntersectionBy1x1; + (iteratee: lodash.__, array: lodash.List | null): LodashIntersectionBy1x2; + (iteratee: lodash.ValueIteratee, array: lodash.List | null): LodashIntersectionBy1x3; + (iteratee: lodash.__, array: lodash.__, values: lodash.List): LodashIntersectionBy1x4; + (iteratee: lodash.ValueIteratee, array: lodash.__, values: lodash.List): LodashIntersectionBy1x5; + (iteratee: lodash.__, array: lodash.List | null, values: lodash.List): LodashIntersectionBy1x6; + (iteratee: lodash.ValueIteratee, array: lodash.List | null, values: lodash.List): T1[]; + } + interface LodashIntersectionBy1x1 { + (array: lodash.List | null): LodashIntersectionBy1x3; + (array: lodash.__, values: lodash.List): LodashIntersectionBy1x5; + (array: lodash.List | null, values: lodash.List): T1[]; + } + interface LodashIntersectionBy1x2 { + (iteratee: lodash.ValueIteratee): LodashIntersectionBy1x3; + (iteratee: lodash.__, values: lodash.List): LodashIntersectionBy1x6; + (iteratee: lodash.ValueIteratee, values: lodash.List): T1[]; + } + type LodashIntersectionBy1x3 = (values: lodash.List) => T1[]; + interface LodashIntersectionBy1x4 { + (iteratee: lodash.ValueIteratee): LodashIntersectionBy1x5; + (iteratee: lodash.__, array: lodash.List | null): LodashIntersectionBy1x6; + (iteratee: lodash.ValueIteratee, array: lodash.List | null): T1[]; + } + type LodashIntersectionBy1x5 = (array: lodash.List | null) => T1[]; + type LodashIntersectionBy1x6 = (iteratee: lodash.ValueIteratee) => T1[]; + interface LodashIntersectionWith { + (comparator: lodash.Comparator2): LodashIntersectionWith1x1; + (comparator: lodash.__, array: lodash.List | null | undefined): LodashIntersectionWith1x2; + (comparator: lodash.Comparator2, array: lodash.List | null | undefined): LodashIntersectionWith1x3; + (comparator: lodash.__, array: lodash.__, values: lodash.List): LodashIntersectionWith1x4; + (comparator: lodash.Comparator2, array: lodash.__, values: lodash.List): LodashIntersectionWith1x5; + (comparator: lodash.__, array: lodash.List | null | undefined, values: lodash.List): LodashIntersectionWith1x6; + (comparator: lodash.Comparator2, array: lodash.List | null | undefined, values: lodash.List): T1[]; + } + interface LodashIntersectionWith1x1 { + (array: lodash.List | null | undefined): LodashIntersectionWith1x3; + (array: lodash.__, values: lodash.List): LodashIntersectionWith1x5; + (array: lodash.List | null | undefined, values: lodash.List): T1[]; + } + interface LodashIntersectionWith1x2 { + (comparator: lodash.Comparator2): LodashIntersectionWith1x3; + (comparator: lodash.__, values: lodash.List): LodashIntersectionWith1x6; + (comparator: lodash.Comparator2, values: lodash.List): T1[]; + } + type LodashIntersectionWith1x3 = (values: lodash.List) => T1[]; + interface LodashIntersectionWith1x4 { + (comparator: lodash.Comparator2): LodashIntersectionWith1x5; + (comparator: lodash.__, array: lodash.List | null | undefined): LodashIntersectionWith1x6; + (comparator: lodash.Comparator2, array: lodash.List | null | undefined): T1[]; + } + type LodashIntersectionWith1x5 = (array: lodash.List | null | undefined) => T1[]; + type LodashIntersectionWith1x6 = (comparator: lodash.Comparator2) => T1[]; + type LodashInvert = (object: object) => lodash.Dictionary; + interface LodashInvertBy { + (interatee: lodash.ValueIteratee): LodashInvertBy1x1; + (interatee: lodash.__, object: lodash.List | lodash.Dictionary | lodash.NumericDictionary | null | undefined): LodashInvertBy1x2; + (interatee: lodash.ValueIteratee, object: lodash.List | lodash.Dictionary | lodash.NumericDictionary | null | undefined): lodash.Dictionary; + (interatee: lodash.__, object: T | null | undefined): LodashInvertBy2x2; + (interatee: lodash.ValueIteratee, object: T | null | undefined): lodash.Dictionary; + } + type LodashInvertBy1x1 = (object: lodash.List | lodash.Dictionary | lodash.NumericDictionary | object | null | undefined) => lodash.Dictionary; + type LodashInvertBy1x2 = (interatee: lodash.ValueIteratee) => lodash.Dictionary; + type LodashInvertBy2x2 = (interatee: lodash.ValueIteratee) => lodash.Dictionary; + interface LodashInvoke { + (path: lodash.PropertyPath): LodashInvoke1x1; + (path: lodash.__, object: any): LodashInvoke1x2; + (path: lodash.PropertyPath, object: any): any; + } + type LodashInvoke1x1 = (object: any) => any; + type LodashInvoke1x2 = (path: lodash.PropertyPath) => any; + interface LodashInvokeArgs { + (path: lodash.PropertyPath): LodashInvokeArgs1x1; + (path: lodash.__, args: ReadonlyArray): LodashInvokeArgs1x2; + (path: lodash.PropertyPath, args: ReadonlyArray): LodashInvokeArgs1x3; + (path: lodash.__, args: lodash.__, object: any): LodashInvokeArgs1x4; + (path: lodash.PropertyPath, args: lodash.__, object: any): LodashInvokeArgs1x5; + (path: lodash.__, args: ReadonlyArray, object: any): LodashInvokeArgs1x6; + (path: lodash.PropertyPath, args: ReadonlyArray, object: any): any; + } + interface LodashInvokeArgs1x1 { + (args: ReadonlyArray): LodashInvokeArgs1x3; + (args: lodash.__, object: any): LodashInvokeArgs1x5; + (args: ReadonlyArray, object: any): any; + } + interface LodashInvokeArgs1x2 { + (path: lodash.PropertyPath): LodashInvokeArgs1x3; + (path: lodash.__, object: any): LodashInvokeArgs1x6; + (path: lodash.PropertyPath, object: any): any; + } + type LodashInvokeArgs1x3 = (object: any) => any; + interface LodashInvokeArgs1x4 { + (path: lodash.PropertyPath): LodashInvokeArgs1x5; + (path: lodash.__, args: ReadonlyArray): LodashInvokeArgs1x6; + (path: lodash.PropertyPath, args: ReadonlyArray): any; + } + type LodashInvokeArgs1x5 = (args: ReadonlyArray) => any; + type LodashInvokeArgs1x6 = (path: lodash.PropertyPath) => any; + interface LodashInvokeArgsMap { + (methodName: string): LodashInvokeArgsMap1x1; + (methodNameOrMethod: lodash.__, args: ReadonlyArray): LodashInvokeArgsMap1x2; + (methodName: string, args: ReadonlyArray): LodashInvokeArgsMap1x3; + (methodNameOrMethod: lodash.__, args: lodash.__, collection: object | null | undefined): LodashInvokeArgsMap1x4; + (methodName: string, args: lodash.__, collection: object | null | undefined): LodashInvokeArgsMap1x5; + (methodNameOrMethod: lodash.__, args: ReadonlyArray, collection: object | null | undefined): LodashInvokeArgsMap1x6; + (methodName: string, args: ReadonlyArray, collection: object | null | undefined): any[]; + (method: (...args: any[]) => TResult): LodashInvokeArgsMap2x1; + (method: (...args: any[]) => TResult, args: ReadonlyArray): LodashInvokeArgsMap2x3; + (method: (...args: any[]) => TResult, args: lodash.__, collection: object | null | undefined): LodashInvokeArgsMap2x5; + (method: (...args: any[]) => TResult, args: ReadonlyArray, collection: object | null | undefined): TResult[]; + } + interface LodashInvokeArgsMap1x1 { + (args: ReadonlyArray): LodashInvokeArgsMap1x3; + (args: lodash.__, collection: object | null | undefined): LodashInvokeArgsMap1x5; + (args: ReadonlyArray, collection: object | null | undefined): any[]; + } + interface LodashInvokeArgsMap1x2 { + (methodName: string): LodashInvokeArgsMap1x3; + (methodNameOrMethod: lodash.__, collection: object | null | undefined): LodashInvokeArgsMap1x6; + (methodName: string, collection: object | null | undefined): any[]; + (method: (...args: any[]) => TResult): LodashInvokeArgsMap2x3; + (method: (...args: any[]) => TResult, collection: object | null | undefined): TResult[]; + } + type LodashInvokeArgsMap1x3 = (collection: object | null | undefined) => any[]; + interface LodashInvokeArgsMap1x4 { + (methodName: string): LodashInvokeArgsMap1x5; + (methodNameOrMethod: lodash.__, args: ReadonlyArray): LodashInvokeArgsMap1x6; + (methodName: string, args: ReadonlyArray): any[]; + (method: (...args: any[]) => TResult): LodashInvokeArgsMap2x5; + (method: (...args: any[]) => TResult, args: ReadonlyArray): TResult[]; + } + type LodashInvokeArgsMap1x5 = (args: ReadonlyArray) => any[]; + interface LodashInvokeArgsMap1x6 { + (methodName: string): any[]; + (method: (...args: any[]) => TResult): TResult[]; + } + interface LodashInvokeArgsMap2x1 { + (args: ReadonlyArray): LodashInvokeArgsMap2x3; + (args: lodash.__, collection: object | null | undefined): LodashInvokeArgsMap2x5; + (args: ReadonlyArray, collection: object | null | undefined): TResult[]; + } + type LodashInvokeArgsMap2x3 = (collection: object | null | undefined) => TResult[]; + type LodashInvokeArgsMap2x5 = (args: ReadonlyArray) => TResult[]; + interface LodashInvokeMap { + (methodName: string): LodashInvokeMap1x1; + (methodNameOrMethod: lodash.__, collection: object | null | undefined): LodashInvokeMap1x2; + (methodName: string, collection: object | null | undefined): any[]; + (method: (...args: any[]) => TResult): LodashInvokeMap2x1; + (method: (...args: any[]) => TResult, collection: object | null | undefined): TResult[]; + } + type LodashInvokeMap1x1 = (collection: object | null | undefined) => any[]; + interface LodashInvokeMap1x2 { + (methodName: string): any[]; + (method: (...args: any[]) => TResult): TResult[]; + } + type LodashInvokeMap2x1 = (collection: object | null | undefined) => TResult[]; + type LodashIsArguments = (value: any) => value is IArguments; + type LodashIsArray = (value: any) => value is any[]; + type LodashIsArrayBuffer = (value: any) => value is ArrayBuffer; + interface LodashIsArrayLike { + (value: T & string & number): boolean; + (value: ((...args: any[]) => any) | null | undefined): value is never; + (value: any): value is { length: number }; + } + interface LodashIsArrayLikeObject { + (value: T & string & number): boolean; + // tslint:disable-next-line:ban-types (type guard doesn't seem to work correctly without the Function type) + (value: ((...args: any[]) => any) | Function | string | boolean | number | null | undefined): value is never; + // tslint:disable-next-line:ban-types (type guard doesn't seem to work correctly without the Function type) + (value: T | ((...args: any[]) => any) | Function | string | boolean | number | null | undefined): value is T & { length: number }; + } + type LodashIsBoolean = (value: any) => value is boolean; + type LodashIsBuffer = (value: any) => boolean; + type LodashIsDate = (value: any) => value is Date; + type LodashIsElement = (value: any) => boolean; + type LodashIsEmpty = (value: any) => boolean; + interface LodashIsEqualWith { + (customizer: lodash.IsEqualCustomizer): LodashIsEqualWith1x1; + (customizer: lodash.__, value: any): LodashIsEqualWith1x2; + (customizer: lodash.IsEqualCustomizer, value: any): LodashIsEqualWith1x3; + (customizer: lodash.__, value: lodash.__, other: any): LodashIsEqualWith1x4; + (customizer: lodash.IsEqualCustomizer, value: lodash.__, other: any): LodashIsEqualWith1x5; + (customizer: lodash.__, value: any, other: any): LodashIsEqualWith1x6; + (customizer: lodash.IsEqualCustomizer, value: any, other: any): boolean; + } + interface LodashIsEqualWith1x1 { + (value: any): LodashIsEqualWith1x3; + (value: lodash.__, other: any): LodashIsEqualWith1x5; + (value: any, other: any): boolean; + } + interface LodashIsEqualWith1x2 { + (customizer: lodash.IsEqualCustomizer): LodashIsEqualWith1x3; + (customizer: lodash.__, other: any): LodashIsEqualWith1x6; + (customizer: lodash.IsEqualCustomizer, other: any): boolean; + } + type LodashIsEqualWith1x3 = (other: any) => boolean; + interface LodashIsEqualWith1x4 { + (customizer: lodash.IsEqualCustomizer): LodashIsEqualWith1x5; + (customizer: lodash.__, value: any): LodashIsEqualWith1x6; + (customizer: lodash.IsEqualCustomizer, value: any): boolean; + } + type LodashIsEqualWith1x5 = (value: any) => boolean; + type LodashIsEqualWith1x6 = (customizer: lodash.IsEqualCustomizer) => boolean; + type LodashIsError = (value: any) => value is Error; + type LodashIsFinite = (value: any) => boolean; + type LodashIsFunction = (value: any) => value is (...args: any[]) => any; + type LodashIsInteger = (value: any) => boolean; + type LodashIsLength = (value: any) => boolean; + type LodashIsMap = (value: any) => value is Map; + interface LodashIsMatch { + (source: object): LodashIsMatch1x1; + (source: lodash.__, object: object): LodashIsMatch1x2; + (source: object, object: object): boolean; + } + type LodashIsMatch1x1 = (object: object) => boolean; + type LodashIsMatch1x2 = (source: object) => boolean; + interface LodashIsMatchWith { + (customizer: lodash.isMatchWithCustomizer): LodashIsMatchWith1x1; + (customizer: lodash.__, source: object): LodashIsMatchWith1x2; + (customizer: lodash.isMatchWithCustomizer, source: object): LodashIsMatchWith1x3; + (customizer: lodash.__, source: lodash.__, object: object): LodashIsMatchWith1x4; + (customizer: lodash.isMatchWithCustomizer, source: lodash.__, object: object): LodashIsMatchWith1x5; + (customizer: lodash.__, source: object, object: object): LodashIsMatchWith1x6; + (customizer: lodash.isMatchWithCustomizer, source: object, object: object): boolean; + } + interface LodashIsMatchWith1x1 { + (source: object): LodashIsMatchWith1x3; + (source: lodash.__, object: object): LodashIsMatchWith1x5; + (source: object, object: object): boolean; + } + interface LodashIsMatchWith1x2 { + (customizer: lodash.isMatchWithCustomizer): LodashIsMatchWith1x3; + (customizer: lodash.__, object: object): LodashIsMatchWith1x6; + (customizer: lodash.isMatchWithCustomizer, object: object): boolean; + } + type LodashIsMatchWith1x3 = (object: object) => boolean; + interface LodashIsMatchWith1x4 { + (customizer: lodash.isMatchWithCustomizer): LodashIsMatchWith1x5; + (customizer: lodash.__, source: object): LodashIsMatchWith1x6; + (customizer: lodash.isMatchWithCustomizer, source: object): boolean; + } + type LodashIsMatchWith1x5 = (source: object) => boolean; + type LodashIsMatchWith1x6 = (customizer: lodash.isMatchWithCustomizer) => boolean; + type LodashIsNaN = (value: any) => boolean; + type LodashIsNative = (value: any) => value is (...args: any[]) => any; + type LodashIsNil = (value: any) => value is null | undefined; + type LodashIsNull = (value: any) => value is null; + type LodashIsNumber = (value: any) => value is number; + type LodashIsObject = (value: any) => boolean; + type LodashIsObjectLike = (value: any) => boolean; + type LodashIsPlainObject = (value: any) => boolean; + type LodashIsRegExp = (value: any) => value is RegExp; + type LodashIsSafeInteger = (value: any) => boolean; + type LodashIsSet = (value: any) => value is Set; + type LodashIsString = (value: any) => value is string; + type LodashIsSymbol = (value: any) => boolean; + type LodashIsTypedArray = (value: any) => boolean; + type LodashIsUndefined = (value: any) => value is undefined; + type LodashIsWeakMap = (value: any) => value is WeakMap; + type LodashIsWeakSet = (value: any) => value is WeakSet; + interface LodashIteratee { + any>(func: TFunction): TFunction; + (func: string | object): (...args: any[]) => any; + } + interface LodashJoin { + (separator: string): LodashJoin1x1; + (separator: lodash.__, array: lodash.List | null | undefined): LodashJoin1x2; + (separator: string, array: lodash.List | null | undefined): string; + } + type LodashJoin1x1 = (array: lodash.List | null | undefined) => string; + type LodashJoin1x2 = (separator: string) => string; + type LodashOver = (iteratees: lodash.Many<(...args: any[]) => TResult>) => (...args: any[]) => TResult[]; + type LodashKebabCase = (string: string) => string; + type LodashKeys = (object: any) => string[]; + type LodashKeysIn = (object: any) => string[]; + type LodashLast = (array: lodash.List | null | undefined) => T | undefined; + interface LodashLastIndexOf { + (value: T): LodashLastIndexOf1x1; + (value: lodash.__, array: lodash.List | null | undefined): LodashLastIndexOf1x2; + (value: T, array: lodash.List | null | undefined): number; + } + type LodashLastIndexOf1x1 = (array: lodash.List | null | undefined) => number; + type LodashLastIndexOf1x2 = (value: T) => number; + interface LodashLastIndexOfFrom { + (value: T): LodashLastIndexOfFrom1x1; + (value: lodash.__, fromIndex: true|number): LodashLastIndexOfFrom1x2; + (value: T, fromIndex: true|number): LodashLastIndexOfFrom1x3; + (value: lodash.__, fromIndex: lodash.__, array: lodash.List | null | undefined): LodashLastIndexOfFrom1x4; + (value: T, fromIndex: lodash.__, array: lodash.List | null | undefined): LodashLastIndexOfFrom1x5; + (value: lodash.__, fromIndex: true|number, array: lodash.List | null | undefined): LodashLastIndexOfFrom1x6; + (value: T, fromIndex: true|number, array: lodash.List | null | undefined): number; + } + interface LodashLastIndexOfFrom1x1 { + (fromIndex: true|number): LodashLastIndexOfFrom1x3; + (fromIndex: lodash.__, array: lodash.List | null | undefined): LodashLastIndexOfFrom1x5; + (fromIndex: true|number, array: lodash.List | null | undefined): number; + } + interface LodashLastIndexOfFrom1x2 { + (value: T): LodashLastIndexOfFrom1x3; + (value: lodash.__, array: lodash.List | null | undefined): LodashLastIndexOfFrom1x6; + (value: T, array: lodash.List | null | undefined): number; + } + type LodashLastIndexOfFrom1x3 = (array: lodash.List | null | undefined) => number; + interface LodashLastIndexOfFrom1x4 { + (value: T): LodashLastIndexOfFrom1x5; + (value: lodash.__, fromIndex: true|number): LodashLastIndexOfFrom1x6; + (value: T, fromIndex: true|number): number; + } + type LodashLastIndexOfFrom1x5 = (fromIndex: true|number) => number; + type LodashLastIndexOfFrom1x6 = (value: T) => number; + type LodashLowerCase = (string: string) => string; + type LodashLowerFirst = (string: string) => string; + interface LodashLt { + (value: any): LodashLt1x1; + (value: lodash.__, other: any): LodashLt1x2; + (value: any, other: any): boolean; + } + type LodashLt1x1 = (other: any) => boolean; + type LodashLt1x2 = (value: any) => boolean; + interface LodashLte { + (value: any): LodashLte1x1; + (value: lodash.__, other: any): LodashLte1x2; + (value: any, other: any): boolean; + } + type LodashLte1x1 = (other: any) => boolean; + type LodashLte1x2 = (value: any) => boolean; + interface LodashMap { + (iteratee: (value: T) => TResult): LodashMap1x1; + (iteratee: lodash.__, collection: T[] | null | undefined): LodashMap1x2; + (iteratee: (value: T) => TResult, collection: T[] | lodash.List | null | undefined): TResult[]; + (iteratee: lodash.__, collection: lodash.List | null | undefined): LodashMap2x2; + (iteratee: (value: T[keyof T]) => TResult): LodashMap3x1; + (iteratee: lodash.__, collection: T | null | undefined): LodashMap3x2; + (iteratee: (value: T[keyof T]) => TResult, collection: T | null | undefined): TResult[]; + (iteratee: K): LodashMap4x1; + (iteratee: lodash.__, collection: lodash.List | lodash.Dictionary | lodash.NumericDictionary | null | undefined): LodashMap4x2; + (iteratee: K, collection: lodash.List | lodash.Dictionary | lodash.NumericDictionary | null | undefined): Array; + (iteratee: string): LodashMap5x1; + (iteratee: string, collection: lodash.List | lodash.Dictionary | lodash.NumericDictionary | null | undefined): any[]; + (iteratee: object): LodashMap6x1; + (iteratee: object, collection: lodash.List | lodash.Dictionary | lodash.NumericDictionary | null | undefined): boolean[]; + } + type LodashMap1x1 = (collection: T[] | lodash.List | null | undefined) => TResult[]; + type LodashMap1x2 = (iteratee: (value: T) => TResult) => TResult[]; + type LodashMap2x2 = (iteratee: (value: T) => TResult) => TResult[]; + type LodashMap3x1 = (collection: T | null | undefined) => TResult[]; + type LodashMap3x2 = (iteratee: (value: T[keyof T]) => TResult) => TResult[]; + type LodashMap4x1 = (collection: lodash.List | lodash.Dictionary | lodash.NumericDictionary | null | undefined) => Array; + interface LodashMap4x2 { + (iteratee: K): Array; + (iteratee: string): any[]; + (iteratee: object): boolean[]; + } + type LodashMap5x1 = (collection: lodash.List | lodash.Dictionary | lodash.NumericDictionary | null | undefined) => any[]; + type LodashMap6x1 = (collection: lodash.List | lodash.Dictionary | lodash.NumericDictionary | null | undefined) => boolean[]; + interface LodashMapKeys { + (iteratee: lodash.ValueIteratee): LodashMapKeys1x1; + (iteratee: lodash.__, object: lodash.List | null | undefined): LodashMapKeys1x2; + (iteratee: lodash.ValueIteratee, object: lodash.List | null | undefined): lodash.Dictionary; + (iteratee: lodash.ValueIteratee): LodashMapKeys2x1; + (iteratee: lodash.__, object: T | null | undefined): LodashMapKeys2x2; + (iteratee: lodash.ValueIteratee, object: T | null | undefined): lodash.Dictionary; + } + type LodashMapKeys1x1 = (object: lodash.List | null | undefined) => lodash.Dictionary; + type LodashMapKeys1x2 = (iteratee: lodash.ValueIteratee) => lodash.Dictionary; + type LodashMapKeys2x1 = (object: T | null | undefined) => lodash.Dictionary; + type LodashMapKeys2x2 = (iteratee: lodash.ValueIteratee) => lodash.Dictionary; + interface LodashMapValues { + (callback: (value: string) => TResult): LodashMapValues1x1; + (callback: lodash.__, obj: string | null | undefined): LodashMapValues1x2; + (callback: (value: string) => TResult, obj: string | null | undefined): lodash.NumericDictionary; + (callback: (value: T) => TResult): LodashMapValues2x1; + (callbackOrIterateeOrIterateeOrIteratee: lodash.__, obj: lodash.Dictionary | lodash.NumericDictionary | null | undefined): LodashMapValues2x2; + (callback: (value: T) => TResult, obj: lodash.Dictionary | lodash.NumericDictionary | null | undefined): lodash.Dictionary; + (callback: (value: T[keyof T]) => TResult): LodashMapValues3x1; + (callbackOrIterateeOrIteratee: lodash.__, obj: T | null | undefined): LodashMapValues3x2; + (callback: (value: T[keyof T]) => TResult, obj: T | null | undefined): { [P in keyof T]: TResult }; + (iteratee: object): LodashMapValues4x1; + (iteratee: object, obj: lodash.Dictionary | lodash.NumericDictionary | null | undefined): lodash.Dictionary; + (iteratee: object, obj: T | null | undefined): { [P in keyof T]: boolean }; + (iteratee: TKey): LodashMapValues6x1; + (iteratee: TKey, obj: lodash.Dictionary | lodash.NumericDictionary | null | undefined): lodash.Dictionary; + (iteratee: string): LodashMapValues7x1; + (iteratee: string, obj: lodash.Dictionary | lodash.NumericDictionary | null | undefined): lodash.Dictionary; + (iteratee: string, obj: T | null | undefined): { [P in keyof T]: any }; + } + type LodashMapValues1x1 = (obj: string | null | undefined) => lodash.NumericDictionary; + type LodashMapValues1x2 = (callback: (value: string) => TResult) => lodash.NumericDictionary; + type LodashMapValues2x1 = (obj: lodash.Dictionary | lodash.NumericDictionary | null | undefined) => lodash.Dictionary; + interface LodashMapValues2x2 { + (callback: (value: T) => TResult): lodash.Dictionary; + (iteratee: object): lodash.Dictionary; + (iteratee: TKey): lodash.Dictionary; + (iteratee: string): lodash.Dictionary; + } + type LodashMapValues3x1 = (obj: T | null | undefined) => { [P in keyof T]: TResult }; + interface LodashMapValues3x2 { + (callback: (value: T[keyof T]) => TResult): { [P in keyof T]: TResult }; + (iteratee: object): { [P in keyof T]: boolean }; + (iteratee: string): { [P in keyof T]: any }; + } + interface LodashMapValues4x1 { + (obj: lodash.Dictionary | lodash.NumericDictionary | null | undefined): lodash.Dictionary; + (obj: T | null | undefined): { [P in keyof T]: boolean }; + } + type LodashMapValues6x1 = (obj: lodash.Dictionary | lodash.NumericDictionary | null | undefined) => lodash.Dictionary; + interface LodashMapValues7x1 { + (obj: lodash.Dictionary | lodash.NumericDictionary | null | undefined): lodash.Dictionary; + (obj: T | null | undefined): { [P in keyof T]: any }; + } + interface LodashMatchesProperty { + (path: lodash.PropertyPath): LodashMatchesProperty1x1; + (path: lodash.__, srcValue: T): LodashMatchesProperty1x2; + (path: lodash.PropertyPath, srcValue: T): (value: any) => boolean; + } + type LodashMatchesProperty1x1 = (srcValue: T) => (value: any) => boolean; + type LodashMatchesProperty1x2 = (path: lodash.PropertyPath) => (value: any) => boolean; + type LodashMax = (collection: lodash.List | null | undefined) => T | undefined; + interface LodashMaxBy { + (iteratee: lodash.ValueIteratee): LodashMaxBy1x1; + (iteratee: lodash.__, collection: lodash.List | null | undefined): LodashMaxBy1x2; + (iteratee: lodash.ValueIteratee, collection: lodash.List | null | undefined): T | undefined; + } + type LodashMaxBy1x1 = (collection: lodash.List | null | undefined) => T | undefined; + type LodashMaxBy1x2 = (iteratee: lodash.ValueIteratee) => T | undefined; + type LodashMean = (collection: lodash.List | null | undefined) => number; + interface LodashMeanBy { + (iteratee: lodash.ValueIteratee): LodashMeanBy1x1; + (iteratee: lodash.__, collection: lodash.List | null | undefined): LodashMeanBy1x2; + (iteratee: lodash.ValueIteratee, collection: lodash.List | null | undefined): number; + } + type LodashMeanBy1x1 = (collection: lodash.List | null | undefined) => number; + type LodashMeanBy1x2 = (iteratee: lodash.ValueIteratee) => number; + type LodashMemoize = any>(func: T) => T & lodash.MemoizedFunction; + interface LodashMerge { + (object: TObject): LodashMerge1x1; + (object: lodash.__, source: TSource): LodashMerge1x2; + (object: TObject, source: TSource): TObject & TSource; + } + type LodashMerge1x1 = (source: TSource) => TObject & TSource; + type LodashMerge1x2 = (object: TObject) => TObject & TSource; + interface LodashMergeAll { + (object: [TObject, TSource]): TObject & TSource; + (object: [TObject, TSource1, TSource2]): TObject & TSource1 & TSource2; + (object: [TObject, TSource1, TSource2, TSource3]): TObject & TSource1 & TSource2 & TSource3; + (object: [TObject, TSource1, TSource2, TSource3, TSource4]): TObject & TSource1 & TSource2 & TSource3 & TSource4; + (object: ReadonlyArray): any; + } + interface LodashMergeAllWith { + (customizer: lodash.MergeWithCustomizer): LodashMergeAllWith1x1; + (customizer: lodash.__, args: ReadonlyArray): LodashMergeAllWith1x2; + (customizer: lodash.MergeWithCustomizer, args: ReadonlyArray): any; + } + type LodashMergeAllWith1x1 = (args: ReadonlyArray) => any; + type LodashMergeAllWith1x2 = (customizer: lodash.MergeWithCustomizer) => any; + interface LodashMergeWith { + (customizer: lodash.MergeWithCustomizer): LodashMergeWith1x1; + (customizer: lodash.__, object: TObject): LodashMergeWith1x2; + (customizer: lodash.MergeWithCustomizer, object: TObject): LodashMergeWith1x3; + (customizer: lodash.__, object: lodash.__, source: TSource): LodashMergeWith1x4; + (customizer: lodash.MergeWithCustomizer, object: lodash.__, source: TSource): LodashMergeWith1x5; + (customizer: lodash.__, object: TObject, source: TSource): LodashMergeWith1x6; + (customizer: lodash.MergeWithCustomizer, object: TObject, source: TSource): TObject & TSource; + } + interface LodashMergeWith1x1 { + (object: TObject): LodashMergeWith1x3; + (object: lodash.__, source: TSource): LodashMergeWith1x5; + (object: TObject, source: TSource): TObject & TSource; + } + interface LodashMergeWith1x2 { + (customizer: lodash.MergeWithCustomizer): LodashMergeWith1x3; + (customizer: lodash.__, source: TSource): LodashMergeWith1x6; + (customizer: lodash.MergeWithCustomizer, source: TSource): TObject & TSource; + } + type LodashMergeWith1x3 = (source: TSource) => TObject & TSource; + interface LodashMergeWith1x4 { + (customizer: lodash.MergeWithCustomizer): LodashMergeWith1x5; + (customizer: lodash.__, object: TObject): LodashMergeWith1x6; + (customizer: lodash.MergeWithCustomizer, object: TObject): TObject & TSource; + } + type LodashMergeWith1x5 = (object: TObject) => TObject & TSource; + type LodashMergeWith1x6 = (customizer: lodash.MergeWithCustomizer) => TObject & TSource; + type LodashMethod = (path: lodash.PropertyPath) => (object: any) => any; + type LodashMethodOf = (object: object) => (path: lodash.PropertyPath) => any; + type LodashMin = (collection: lodash.List | null | undefined) => T | undefined; + interface LodashMinBy { + (iteratee: lodash.ValueIteratee): LodashMinBy1x1; + (iteratee: lodash.__, collection: lodash.List | null | undefined): LodashMinBy1x2; + (iteratee: lodash.ValueIteratee, collection: lodash.List | null | undefined): T | undefined; + } + type LodashMinBy1x1 = (collection: lodash.List | null | undefined) => T | undefined; + type LodashMinBy1x2 = (iteratee: lodash.ValueIteratee) => T | undefined; + interface LodashMultiply { + (multiplier: number): LodashMultiply1x1; + (multiplier: lodash.__, multiplicand: number): LodashMultiply1x2; + (multiplier: number, multiplicand: number): number; + } + type LodashMultiply1x1 = (multiplicand: number) => number; + type LodashMultiply1x2 = (multiplier: number) => number; + type LodashNoConflict = () => typeof _; + type LodashNoop = (...args: any[]) => void; + type LodashNow = () => number; + interface LodashNth { + (n: number): LodashNth1x1; + (n: lodash.__, array: lodash.List | null | undefined): LodashNth1x2; + (n: number, array: lodash.List | null | undefined): T | undefined; + } + type LodashNth1x1 = (array: lodash.List | null | undefined) => T | undefined; + type LodashNth1x2 = (n: number) => T | undefined; + type LodashNthArg = (n: number) => (...args: any[]) => any; + interface LodashOmit { + (paths: lodash.Many): LodashOmit1x1; + (paths: lodash.__, object: T | null | undefined): LodashOmit1x2; + (paths: lodash.Many, object: T | null | undefined): T; + (paths: lodash.Many): LodashOmit2x1; + (paths: lodash.__, object: T | null | undefined): LodashOmit2x2; + (paths: lodash.Many, object: T | null | undefined): lodash.Omit; + (paths: lodash.Many, object: T | null | undefined): lodash.PartialObject; + } + interface LodashOmit1x1 { + (object: T | null | undefined): T; + (object: T | null | undefined): lodash.PartialObject; + } + type LodashOmit1x2 = (paths: lodash.Many) => T; + type LodashOmit2x1 = (object: T | null | undefined) => lodash.Omit; + interface LodashOmit2x2 { + (paths: lodash.Many): lodash.Omit; + (paths: lodash.Many): lodash.PartialObject; + } + interface LodashOmitBy { + (predicate: lodash.ValueKeyIteratee): LodashOmitBy1x1; + (predicate: lodash.__, object: lodash.Dictionary | null | undefined): LodashOmitBy1x2; + (predicate: lodash.ValueKeyIteratee, object: lodash.Dictionary | null | undefined): lodash.Dictionary; + (predicate: lodash.__, object: lodash.NumericDictionary | null | undefined): LodashOmitBy2x2; + (predicate: lodash.ValueKeyIteratee, object: lodash.NumericDictionary | null | undefined): lodash.NumericDictionary; + (predicate: lodash.__, object: T | null | undefined): LodashOmitBy3x2; + (predicate: lodash.ValueKeyIteratee, object: T | null | undefined): lodash.PartialObject; + } + interface LodashOmitBy1x1 { + (object: lodash.Dictionary | null | undefined): lodash.Dictionary; + (object: lodash.NumericDictionary | null | undefined): lodash.NumericDictionary; + (object: T1 | null | undefined): lodash.PartialObject; + } + type LodashOmitBy1x2 = (predicate: lodash.ValueKeyIteratee) => lodash.Dictionary; + type LodashOmitBy2x2 = (predicate: lodash.ValueKeyIteratee) => lodash.NumericDictionary; + type LodashOmitBy3x2 = (predicate: lodash.ValueKeyIteratee) => lodash.PartialObject; + type LodashOnce = any>(func: T) => T; + interface LodashOrderBy { + (iteratees: lodash.Many<(value: T) => lodash.NotVoid>): LodashOrderBy1x1; + (iteratees: lodash.__, orders: lodash.Many): LodashOrderBy1x2; + (iteratees: lodash.Many<(value: T) => lodash.NotVoid>, orders: lodash.Many): LodashOrderBy1x3; + (iteratees: lodash.__, orders: lodash.__, collection: lodash.List | null | undefined): LodashOrderBy1x4; + (iteratees: lodash.Many<(value: T) => lodash.NotVoid>, orders: lodash.__, collection: lodash.List | null | undefined): LodashOrderBy1x5; + (iteratees: lodash.__, orders: lodash.Many, collection: lodash.List | null | undefined): LodashOrderBy1x6; + (iteratees: lodash.Many<(value: T) => lodash.NotVoid> | lodash.Many>, orders: lodash.Many, collection: lodash.List | null | undefined): T[]; + (iteratees: lodash.Many>): LodashOrderBy2x1; + (iteratees: lodash.Many>, orders: lodash.Many): LodashOrderBy2x3; + (iteratees: lodash.Many>, orders: lodash.__, collection: lodash.List | null | undefined): LodashOrderBy2x5; + (iteratees: lodash.__, orders: lodash.__, collection: T | null | undefined): LodashOrderBy3x4; + (iteratees: lodash.Many<(value: T[keyof T]) => lodash.NotVoid>, orders: lodash.__, collection: T | null | undefined): LodashOrderBy3x5; + (iteratees: lodash.__, orders: lodash.Many, collection: T | null | undefined): LodashOrderBy3x6; + (iteratees: lodash.Many<(value: T[keyof T]) => lodash.NotVoid> | lodash.Many>, orders: lodash.Many, collection: T | null | undefined): Array; + (iteratees: lodash.Many>, orders: lodash.__, collection: T | null | undefined): LodashOrderBy4x5; + } + interface LodashOrderBy1x1 { + (orders: lodash.Many): LodashOrderBy1x3; + (orders: lodash.__, collection: lodash.List | null | undefined): LodashOrderBy1x5; + (orders: lodash.Many, collection: lodash.List | object | null | undefined): T[]; + (orders: lodash.__, collection: T1 | null | undefined): LodashOrderBy3x5; + } + interface LodashOrderBy1x2 { + (iteratees: lodash.Many<(value: T) => lodash.NotVoid>): LodashOrderBy1x3; + (iteratees: lodash.__, collection: lodash.List | null | undefined): LodashOrderBy1x6; + (iteratees: lodash.Many<(value: T) => lodash.NotVoid> | lodash.Many>, collection: lodash.List | null | undefined): T[]; + (iteratees: lodash.Many>): LodashOrderBy2x3; + (iteratees: lodash.__, collection: T | null | undefined): LodashOrderBy3x6; + (iteratees: lodash.Many<(value: T[keyof T]) => lodash.NotVoid> | lodash.Many>, collection: T | null | undefined): Array; + } + interface LodashOrderBy1x3 { + (collection: lodash.List | null | undefined): T[]; + (collection: object | null | undefined): object[]; + } + interface LodashOrderBy1x4 { + (iteratees: lodash.Many<(value: T) => lodash.NotVoid>): LodashOrderBy1x5; + (iteratees: lodash.__, orders: lodash.Many): LodashOrderBy1x6; + (iteratees: lodash.Many<(value: T) => lodash.NotVoid> | lodash.Many>, orders: lodash.Many): T[]; + (iteratees: lodash.Many>): LodashOrderBy2x5; + } + type LodashOrderBy1x5 = (orders: lodash.Many) => T[]; + type LodashOrderBy1x6 = (iteratees: lodash.Many<(value: T) => lodash.NotVoid> | lodash.Many>) => T[]; + interface LodashOrderBy2x1 { + (orders: lodash.Many): LodashOrderBy2x3; + (orders: lodash.__, collection: lodash.List | null | undefined): LodashOrderBy2x5; + (orders: lodash.Many, collection: lodash.List | object | null | undefined): T[]; + (orders: lodash.__, collection: T1 | null | undefined): LodashOrderBy4x5; + } + interface LodashOrderBy2x3 { + (collection: lodash.List | null | undefined): T[]; + (collection: object | null | undefined): object[]; + } + type LodashOrderBy2x5 = (orders: lodash.Many) => T[]; + interface LodashOrderBy3x4 { + (iteratees: lodash.Many<(value: T[keyof T]) => lodash.NotVoid>): LodashOrderBy3x5; + (iteratees: lodash.__, orders: lodash.Many): LodashOrderBy3x6; + (iteratees: lodash.Many<(value: T[keyof T]) => lodash.NotVoid> | lodash.Many>, orders: lodash.Many): Array; + (iteratees: lodash.Many>): LodashOrderBy4x5; + } + type LodashOrderBy3x5 = (orders: lodash.Many) => Array; + type LodashOrderBy3x6 = (iteratees: lodash.Many<(value: T[keyof T]) => lodash.NotVoid> | lodash.Many>) => Array; + type LodashOrderBy4x5 = (orders: lodash.Many) => Array; + interface LodashOverArgs { + (func: (...args: any[]) => any): LodashOverArgs1x1; + (func: lodash.__, transforms: lodash.Many<(...args: any[]) => any>): LodashOverArgs1x2; + (func: (...args: any[]) => any, transforms: lodash.Many<(...args: any[]) => any>): (...args: any[]) => any; + } + type LodashOverArgs1x1 = (transforms: lodash.Many<(...args: any[]) => any>) => (...args: any[]) => any; + type LodashOverArgs1x2 = (func: (...args: any[]) => any) => (...args: any[]) => any; + interface LodashPad { + (length: number): LodashPad1x1; + (length: lodash.__, string: string): LodashPad1x2; + (length: number, string: string): string; + } + type LodashPad1x1 = (string: string) => string; + type LodashPad1x2 = (length: number) => string; + interface LodashPadChars { + (chars: string): LodashPadChars1x1; + (chars: lodash.__, length: number): LodashPadChars1x2; + (chars: string, length: number): LodashPadChars1x3; + (chars: lodash.__, length: lodash.__, string: string): LodashPadChars1x4; + (chars: string, length: lodash.__, string: string): LodashPadChars1x5; + (chars: lodash.__, length: number, string: string): LodashPadChars1x6; + (chars: string, length: number, string: string): string; + } + interface LodashPadChars1x1 { + (length: number): LodashPadChars1x3; + (length: lodash.__, string: string): LodashPadChars1x5; + (length: number, string: string): string; + } + interface LodashPadChars1x2 { + (chars: string): LodashPadChars1x3; + (chars: lodash.__, string: string): LodashPadChars1x6; + (chars: string, string: string): string; + } + type LodashPadChars1x3 = (string: string) => string; + interface LodashPadChars1x4 { + (chars: string): LodashPadChars1x5; + (chars: lodash.__, length: number): LodashPadChars1x6; + (chars: string, length: number): string; + } + type LodashPadChars1x5 = (length: number) => string; + type LodashPadChars1x6 = (chars: string) => string; + interface LodashPadCharsEnd { + (chars: string): LodashPadCharsEnd1x1; + (chars: lodash.__, length: number): LodashPadCharsEnd1x2; + (chars: string, length: number): LodashPadCharsEnd1x3; + (chars: lodash.__, length: lodash.__, string: string): LodashPadCharsEnd1x4; + (chars: string, length: lodash.__, string: string): LodashPadCharsEnd1x5; + (chars: lodash.__, length: number, string: string): LodashPadCharsEnd1x6; + (chars: string, length: number, string: string): string; + } + interface LodashPadCharsEnd1x1 { + (length: number): LodashPadCharsEnd1x3; + (length: lodash.__, string: string): LodashPadCharsEnd1x5; + (length: number, string: string): string; + } + interface LodashPadCharsEnd1x2 { + (chars: string): LodashPadCharsEnd1x3; + (chars: lodash.__, string: string): LodashPadCharsEnd1x6; + (chars: string, string: string): string; + } + type LodashPadCharsEnd1x3 = (string: string) => string; + interface LodashPadCharsEnd1x4 { + (chars: string): LodashPadCharsEnd1x5; + (chars: lodash.__, length: number): LodashPadCharsEnd1x6; + (chars: string, length: number): string; + } + type LodashPadCharsEnd1x5 = (length: number) => string; + type LodashPadCharsEnd1x6 = (chars: string) => string; + interface LodashPadCharsStart { + (chars: string): LodashPadCharsStart1x1; + (chars: lodash.__, length: number): LodashPadCharsStart1x2; + (chars: string, length: number): LodashPadCharsStart1x3; + (chars: lodash.__, length: lodash.__, string: string): LodashPadCharsStart1x4; + (chars: string, length: lodash.__, string: string): LodashPadCharsStart1x5; + (chars: lodash.__, length: number, string: string): LodashPadCharsStart1x6; + (chars: string, length: number, string: string): string; + } + interface LodashPadCharsStart1x1 { + (length: number): LodashPadCharsStart1x3; + (length: lodash.__, string: string): LodashPadCharsStart1x5; + (length: number, string: string): string; + } + interface LodashPadCharsStart1x2 { + (chars: string): LodashPadCharsStart1x3; + (chars: lodash.__, string: string): LodashPadCharsStart1x6; + (chars: string, string: string): string; + } + type LodashPadCharsStart1x3 = (string: string) => string; + interface LodashPadCharsStart1x4 { + (chars: string): LodashPadCharsStart1x5; + (chars: lodash.__, length: number): LodashPadCharsStart1x6; + (chars: string, length: number): string; + } + type LodashPadCharsStart1x5 = (length: number) => string; + type LodashPadCharsStart1x6 = (chars: string) => string; + interface LodashPadEnd { + (length: number): LodashPadEnd1x1; + (length: lodash.__, string: string): LodashPadEnd1x2; + (length: number, string: string): string; + } + type LodashPadEnd1x1 = (string: string) => string; + type LodashPadEnd1x2 = (length: number) => string; + interface LodashPadStart { + (length: number): LodashPadStart1x1; + (length: lodash.__, string: string): LodashPadStart1x2; + (length: number, string: string): string; + } + type LodashPadStart1x1 = (string: string) => string; + type LodashPadStart1x2 = (length: number) => string; + interface LodashParseInt { + (radix: number): LodashParseInt1x1; + (radix: lodash.__, string: string): LodashParseInt1x2; + (radix: number, string: string): number; + } + type LodashParseInt1x1 = (string: string) => number; + type LodashParseInt1x2 = (radix: number) => number; + interface LodashPartial { + (func: lodash.Function1): LodashPartial1x1; + (func: lodash.__, arg1: [T1]): LodashPartial1x2; + (func: lodash.Function1, arg1: [T1]): lodash.Function0; + (func: lodash.Function2): LodashPartial2x1; + (func: lodash.Function2, arg1: [T1]): lodash.Function1< T2, R>; + (func: lodash.__, plc1: [lodash.__, T2]): LodashPartial3x2; + (func: lodash.Function2, plc1: [lodash.__, T2]): lodash.Function1; + (func: lodash.__, arg1: [T1, T2]): LodashPartial4x2; + (func: lodash.Function2, arg1: [T1, T2]): lodash.Function0< R>; + (func: lodash.Function3): LodashPartial5x1; + (func: lodash.Function3, arg1: [T1]): lodash.Function2< T2, T3, R>; + (func: lodash.Function3, plc1: [lodash.__, T2]): lodash.Function2; + (func: lodash.Function3, arg1: [T1, T2]): lodash.Function1< T3, R>; + (func: lodash.__, plc1: [lodash.__, lodash.__, T3]): LodashPartial8x2; + (func: lodash.Function3, plc1: [lodash.__, lodash.__, T3]): lodash.Function2; + (func: lodash.__, arg1: [T1, lodash.__, T3]): LodashPartial9x2; + (func: lodash.Function3, arg1: [T1, lodash.__, T3]): lodash.Function1< T2, R>; + (func: lodash.__, plc1: [lodash.__, T2, T3]): LodashPartial10x2; + (func: lodash.Function3, plc1: [lodash.__, T2, T3]): lodash.Function1; + (func: lodash.__, arg1: [T1, T2, T3]): LodashPartial11x2; + (func: lodash.Function3, arg1: [T1, T2, T3]): lodash.Function0< R>; + (func: lodash.Function4): LodashPartial12x1; + (func: lodash.Function4, arg1: [T1]): lodash.Function3< T2, T3, T4, R>; + (func: lodash.Function4, plc1: [lodash.__, T2]): lodash.Function3; + (func: lodash.Function4, arg1: [T1, T2]): lodash.Function2< T3, T4, R>; + (func: lodash.Function4, plc1: [lodash.__, lodash.__, T3]): lodash.Function3; + (func: lodash.Function4, arg1: [T1, lodash.__, T3]): lodash.Function2< T2, T4, R>; + (func: lodash.Function4, plc1: [lodash.__, T2, T3]): lodash.Function2; + (func: lodash.Function4, arg1: [T1, T2, T3]): lodash.Function1< T4, R>; + (func: lodash.__, plc1: [lodash.__, lodash.__, lodash.__, T4]): LodashPartial19x2; + (func: lodash.Function4, plc1: [lodash.__, lodash.__, lodash.__, T4]): lodash.Function3; + (func: lodash.__, arg1: [T1, lodash.__, lodash.__, T4]): LodashPartial20x2; + (func: lodash.Function4, arg1: [T1, lodash.__, lodash.__, T4]): lodash.Function2< T2, T3, R>; + (func: lodash.__, plc1: [lodash.__, T2, lodash.__, T4]): LodashPartial21x2; + (func: lodash.Function4, plc1: [lodash.__, T2, lodash.__, T4]): lodash.Function2; + (func: lodash.__, arg1: [T1, T2, lodash.__, T4]): LodashPartial22x2; + (func: lodash.Function4, arg1: [T1, T2, lodash.__, T4]): lodash.Function1< T3, R>; + (func: lodash.__, plc1: [lodash.__, lodash.__, T3, T4]): LodashPartial23x2; + (func: lodash.Function4, plc1: [lodash.__, lodash.__, T3, T4]): lodash.Function2; + (func: lodash.__, arg1: [T1, lodash.__, T3, T4]): LodashPartial24x2; + (func: lodash.Function4, arg1: [T1, lodash.__, T3, T4]): lodash.Function1< T2, R>; + (func: lodash.__, plc1: [lodash.__, T2, T3, T4]): LodashPartial25x2; + (func: lodash.Function4, plc1: [lodash.__, T2, T3, T4]): lodash.Function1; + (func: lodash.__, arg1: [T1, T2, T3, T4]): LodashPartial26x2; + (func: lodash.Function4, arg1: [T1, T2, T3, T4]): lodash.Function0< R>; + (func: (...args: any[]) => any): LodashPartial27x1; + (func: lodash.__, args: ReadonlyArray): LodashPartial27x2; + (func: (...args: any[]) => any, args: ReadonlyArray): (...args: any[]) => any; + placeholder: lodash.__; + } + type LodashPartial1x1 = (arg1: [T1]) => lodash.Function0; + interface LodashPartial1x2 { + (func: lodash.Function1): lodash.Function0; + (func: lodash.Function2): lodash.Function1< T2, R>; + (func: lodash.Function3): lodash.Function2< T2, T3, R>; + (func: lodash.Function4): lodash.Function3< T2, T3, T4, R>; + } + interface LodashPartial2x1 { + (arg1: [T1]): lodash.Function1< T2, R>; + (plc1: [lodash.__, T2]): lodash.Function1; + (arg1: [T1, T2]): lodash.Function0< R>; + } + interface LodashPartial3x2 { + (func: lodash.Function2): lodash.Function1; + (func: lodash.Function3): lodash.Function2; + (func: lodash.Function4): lodash.Function3; + } + interface LodashPartial4x2 { + (func: lodash.Function2): lodash.Function0< R>; + (func: lodash.Function3): lodash.Function1< T3, R>; + (func: lodash.Function4): lodash.Function2< T3, T4, R>; + } + interface LodashPartial5x1 { + (arg1: [T1]): lodash.Function2< T2, T3, R>; + (plc1: [lodash.__, T2]): lodash.Function2; + (arg1: [T1, T2]): lodash.Function1< T3, R>; + (plc1: [lodash.__, lodash.__, T3]): lodash.Function2; + (arg1: [T1, lodash.__, T3]): lodash.Function1< T2, R>; + (plc1: [lodash.__, T2, T3]): lodash.Function1; + (arg1: [T1, T2, T3]): lodash.Function0< R>; + } + interface LodashPartial8x2 { + (func: lodash.Function3): lodash.Function2; + (func: lodash.Function4): lodash.Function3; + } + interface LodashPartial9x2 { + (func: lodash.Function3): lodash.Function1< T2, R>; + (func: lodash.Function4): lodash.Function2< T2, T4, R>; + } + interface LodashPartial10x2 { + (func: lodash.Function3): lodash.Function1; + (func: lodash.Function4): lodash.Function2; + } + interface LodashPartial11x2 { + (func: lodash.Function3): lodash.Function0< R>; + (func: lodash.Function4): lodash.Function1< T4, R>; + } + interface LodashPartial12x1 { + (arg1: [T1]): lodash.Function3< T2, T3, T4, R>; + (plc1: [lodash.__, T2]): lodash.Function3; + (arg1: [T1, T2]): lodash.Function2< T3, T4, R>; + (plc1: [lodash.__, lodash.__, T3]): lodash.Function3; + (arg1: [T1, lodash.__, T3]): lodash.Function2< T2, T4, R>; + (plc1: [lodash.__, T2, T3]): lodash.Function2; + (arg1: [T1, T2, T3]): lodash.Function1< T4, R>; + (plc1: [lodash.__, lodash.__, lodash.__, T4]): lodash.Function3; + (arg1: [T1, lodash.__, lodash.__, T4]): lodash.Function2< T2, T3, R>; + (plc1: [lodash.__, T2, lodash.__, T4]): lodash.Function2; + (arg1: [T1, T2, lodash.__, T4]): lodash.Function1< T3, R>; + (plc1: [lodash.__, lodash.__, T3, T4]): lodash.Function2; + (arg1: [T1, lodash.__, T3, T4]): lodash.Function1< T2, R>; + (plc1: [lodash.__, T2, T3, T4]): lodash.Function1; + (arg1: [T1, T2, T3, T4]): lodash.Function0< R>; + } + type LodashPartial19x2 = (func: lodash.Function4) => lodash.Function3; + type LodashPartial20x2 = (func: lodash.Function4) => lodash.Function2< T2, T3, R>; + type LodashPartial21x2 = (func: lodash.Function4) => lodash.Function2; + type LodashPartial22x2 = (func: lodash.Function4) => lodash.Function1< T3, R>; + type LodashPartial23x2 = (func: lodash.Function4) => lodash.Function2; + type LodashPartial24x2 = (func: lodash.Function4) => lodash.Function1< T2, R>; + type LodashPartial25x2 = (func: lodash.Function4) => lodash.Function1; + type LodashPartial26x2 = (func: lodash.Function4) => lodash.Function0< R>; + type LodashPartial27x1 = (args: ReadonlyArray) => (...args: any[]) => any; + type LodashPartial27x2 = (func: (...args: any[]) => any) => (...args: any[]) => any; + interface LodashPartialRight { + (func: lodash.Function1): LodashPartialRight1x1; + (func: lodash.__, arg1: [T1]): LodashPartialRight1x2; + (func: lodash.Function1, arg1: [T1]): lodash.Function0; + (func: lodash.Function2): LodashPartialRight2x1; + (func: lodash.__, arg1: [T1, lodash.__]): LodashPartialRight2x2; + (func: lodash.Function2, arg1: [T1, lodash.__]): lodash.Function1< T2, R>; + (func: lodash.__, arg2: [T2]): LodashPartialRight3x2; + (func: lodash.Function2, arg2: [T2]): lodash.Function1; + (func: lodash.__, arg1: [T1, T2]): LodashPartialRight4x2; + (func: lodash.Function2, arg1: [T1, T2]): lodash.Function0< R>; + (func: lodash.Function3): LodashPartialRight5x1; + (func: lodash.__, arg1: [T1, lodash.__, lodash.__]): LodashPartialRight5x2; + (func: lodash.Function3, arg1: [T1, lodash.__, lodash.__]): lodash.Function2< T2, T3, R>; + (func: lodash.__, arg2: [T2, lodash.__]): LodashPartialRight6x2; + (func: lodash.Function3, arg2: [T2, lodash.__]): lodash.Function2; + (func: lodash.__, arg1: [T1, T2, lodash.__]): LodashPartialRight7x2; + (func: lodash.Function3, arg1: [T1, T2, lodash.__]): lodash.Function1< T3, R>; + (func: lodash.__, arg3: [T3]): LodashPartialRight8x2; + (func: lodash.Function3, arg3: [T3]): lodash.Function2; + (func: lodash.__, arg1: [T1, lodash.__, T3]): LodashPartialRight9x2; + (func: lodash.Function3, arg1: [T1, lodash.__, T3]): lodash.Function1< T2, R>; + (func: lodash.__, arg2: [T2, T3]): LodashPartialRight10x2; + (func: lodash.Function3, arg2: [T2, T3]): lodash.Function1; + (func: lodash.__, arg1: [T1, T2, T3]): LodashPartialRight11x2; + (func: lodash.Function3, arg1: [T1, T2, T3]): lodash.Function0< R>; + (func: lodash.Function4): LodashPartialRight12x1; + (func: lodash.__, arg1: [T1, lodash.__, lodash.__, lodash.__]): LodashPartialRight12x2; + (func: lodash.Function4, arg1: [T1, lodash.__, lodash.__, lodash.__]): lodash.Function3< T2, T3, T4, R>; + (func: lodash.__, arg2: [T2, lodash.__, lodash.__]): LodashPartialRight13x2; + (func: lodash.Function4, arg2: [T2, lodash.__, lodash.__]): lodash.Function3; + (func: lodash.__, arg1: [T1, T2, lodash.__, lodash.__]): LodashPartialRight14x2; + (func: lodash.Function4, arg1: [T1, T2, lodash.__, lodash.__]): lodash.Function2< T3, T4, R>; + (func: lodash.__, arg3: [T3, lodash.__]): LodashPartialRight15x2; + (func: lodash.Function4, arg3: [T3, lodash.__]): lodash.Function3; + (func: lodash.__, arg1: [T1, lodash.__, T3, lodash.__]): LodashPartialRight16x2; + (func: lodash.Function4, arg1: [T1, lodash.__, T3, lodash.__]): lodash.Function2< T2, T4, R>; + (func: lodash.__, arg2: [T2, T3, lodash.__]): LodashPartialRight17x2; + (func: lodash.Function4, arg2: [T2, T3, lodash.__]): lodash.Function2; + (func: lodash.__, arg1: [T1, T2, T3, lodash.__]): LodashPartialRight18x2; + (func: lodash.Function4, arg1: [T1, T2, T3, lodash.__]): lodash.Function1< T4, R>; + (func: lodash.__, arg4: [T4]): LodashPartialRight19x2; + (func: lodash.Function4, arg4: [T4]): lodash.Function3; + (func: lodash.__, arg1: [T1, lodash.__, lodash.__, T4]): LodashPartialRight20x2; + (func: lodash.Function4, arg1: [T1, lodash.__, lodash.__, T4]): lodash.Function2< T2, T3, R>; + (func: lodash.__, arg2: [T2, lodash.__, T4]): LodashPartialRight21x2; + (func: lodash.Function4, arg2: [T2, lodash.__, T4]): lodash.Function2; + (func: lodash.__, arg1: [T1, T2, lodash.__, T4]): LodashPartialRight22x2; + (func: lodash.Function4, arg1: [T1, T2, lodash.__, T4]): lodash.Function1< T3, R>; + (func: lodash.__, arg3: [T3, T4]): LodashPartialRight23x2; + (func: lodash.Function4, arg3: [T3, T4]): lodash.Function2; + (func: lodash.__, arg1: [T1, lodash.__, T3, T4]): LodashPartialRight24x2; + (func: lodash.Function4, arg1: [T1, lodash.__, T3, T4]): lodash.Function1< T2, R>; + (func: lodash.__, arg2: [T2, T3, T4]): LodashPartialRight25x2; + (func: lodash.Function4, arg2: [T2, T3, T4]): lodash.Function1; + (func: lodash.__, arg1: [T1, T2, T3, T4]): LodashPartialRight26x2; + (func: lodash.Function4, arg1: [T1, T2, T3, T4]): lodash.Function0< R>; + (func: (...args: any[]) => any): LodashPartialRight27x1; + (func: lodash.__, args: ReadonlyArray): LodashPartialRight27x2; + (func: (...args: any[]) => any, args: ReadonlyArray): (...args: any[]) => any; + placeholder: lodash.__; + } + type LodashPartialRight1x1 = (arg1: [T1]) => lodash.Function0; + type LodashPartialRight1x2 = (func: lodash.Function1) => lodash.Function0; + interface LodashPartialRight2x1 { + (arg1: [T1, lodash.__]): lodash.Function1< T2, R>; + (arg2: [T2]): lodash.Function1; + (arg1: [T1, T2]): lodash.Function0< R>; + } + type LodashPartialRight2x2 = (func: lodash.Function2) => lodash.Function1< T2, R>; + type LodashPartialRight3x2 = (func: lodash.Function2) => lodash.Function1; + type LodashPartialRight4x2 = (func: lodash.Function2) => lodash.Function0< R>; + interface LodashPartialRight5x1 { + (arg1: [T1, lodash.__, lodash.__]): lodash.Function2< T2, T3, R>; + (arg2: [T2, lodash.__]): lodash.Function2; + (arg1: [T1, T2, lodash.__]): lodash.Function1< T3, R>; + (arg3: [T3]): lodash.Function2; + (arg1: [T1, lodash.__, T3]): lodash.Function1< T2, R>; + (arg2: [T2, T3]): lodash.Function1; + (arg1: [T1, T2, T3]): lodash.Function0< R>; + } + type LodashPartialRight5x2 = (func: lodash.Function3) => lodash.Function2< T2, T3, R>; + type LodashPartialRight6x2 = (func: lodash.Function3) => lodash.Function2; + type LodashPartialRight7x2 = (func: lodash.Function3) => lodash.Function1< T3, R>; + type LodashPartialRight8x2 = (func: lodash.Function3) => lodash.Function2; + type LodashPartialRight9x2 = (func: lodash.Function3) => lodash.Function1< T2, R>; + type LodashPartialRight10x2 = (func: lodash.Function3) => lodash.Function1; + type LodashPartialRight11x2 = (func: lodash.Function3) => lodash.Function0< R>; + interface LodashPartialRight12x1 { + (arg1: [T1, lodash.__, lodash.__, lodash.__]): lodash.Function3< T2, T3, T4, R>; + (arg2: [T2, lodash.__, lodash.__]): lodash.Function3; + (arg1: [T1, T2, lodash.__, lodash.__]): lodash.Function2< T3, T4, R>; + (arg3: [T3, lodash.__]): lodash.Function3; + (arg1: [T1, lodash.__, T3, lodash.__]): lodash.Function2< T2, T4, R>; + (arg2: [T2, T3, lodash.__]): lodash.Function2; + (arg1: [T1, T2, T3, lodash.__]): lodash.Function1< T4, R>; + (arg4: [T4]): lodash.Function3; + (arg1: [T1, lodash.__, lodash.__, T4]): lodash.Function2< T2, T3, R>; + (arg2: [T2, lodash.__, T4]): lodash.Function2; + (arg1: [T1, T2, lodash.__, T4]): lodash.Function1< T3, R>; + (arg3: [T3, T4]): lodash.Function2; + (arg1: [T1, lodash.__, T3, T4]): lodash.Function1< T2, R>; + (arg2: [T2, T3, T4]): lodash.Function1; + (arg1: [T1, T2, T3, T4]): lodash.Function0< R>; + } + type LodashPartialRight12x2 = (func: lodash.Function4) => lodash.Function3< T2, T3, T4, R>; + type LodashPartialRight13x2 = (func: lodash.Function4) => lodash.Function3; + type LodashPartialRight14x2 = (func: lodash.Function4) => lodash.Function2< T3, T4, R>; + type LodashPartialRight15x2 = (func: lodash.Function4) => lodash.Function3; + type LodashPartialRight16x2 = (func: lodash.Function4) => lodash.Function2< T2, T4, R>; + type LodashPartialRight17x2 = (func: lodash.Function4) => lodash.Function2; + type LodashPartialRight18x2 = (func: lodash.Function4) => lodash.Function1< T4, R>; + type LodashPartialRight19x2 = (func: lodash.Function4) => lodash.Function3; + type LodashPartialRight20x2 = (func: lodash.Function4) => lodash.Function2< T2, T3, R>; + type LodashPartialRight21x2 = (func: lodash.Function4) => lodash.Function2; + type LodashPartialRight22x2 = (func: lodash.Function4) => lodash.Function1< T3, R>; + type LodashPartialRight23x2 = (func: lodash.Function4) => lodash.Function2; + type LodashPartialRight24x2 = (func: lodash.Function4) => lodash.Function1< T2, R>; + type LodashPartialRight25x2 = (func: lodash.Function4) => lodash.Function1; + type LodashPartialRight26x2 = (func: lodash.Function4) => lodash.Function0< R>; + type LodashPartialRight27x1 = (args: ReadonlyArray) => (...args: any[]) => any; + type LodashPartialRight27x2 = (func: (...args: any[]) => any) => (...args: any[]) => any; + interface LodashPartition { + (callback: lodash.ValueIteratee): LodashPartition1x1; + (callback: lodash.__, collection: lodash.List | null | undefined): LodashPartition1x2; + (callback: lodash.ValueIteratee, collection: lodash.List | null | undefined): [T[], T[]]; + (callback: lodash.__, collection: T | null | undefined): LodashPartition2x2; + (callback: lodash.ValueIteratee, collection: T | null | undefined): [Array, Array]; + } + type LodashPartition1x1 = (collection: lodash.List | object | null | undefined) => [T[], T[]]; + type LodashPartition1x2 = (callback: lodash.ValueIteratee) => [T[], T[]]; + type LodashPartition2x2 = (callback: lodash.ValueIteratee) => [Array, Array]; + interface LodashPath { + (path: TKey | [TKey]): LodashPath1x1; + (path: lodash.__, object: TObject): LodashPath1x2; + (path: TKey | [TKey], object: TObject): TObject[TKey]; + (path: lodash.__, object: TObject | null | undefined): LodashPath2x2; + (path: TKey | [TKey], object: TObject | null | undefined): TObject[TKey] | undefined; + (path: number): LodashPath3x1; + (path: lodash.__, object: lodash.NumericDictionary): LodashPath3x2; + (path: number, object: lodash.NumericDictionary): T; + (path: lodash.__, object: lodash.NumericDictionary | null | undefined): LodashPath4x2; + (path: number, object: lodash.NumericDictionary | null | undefined): T | undefined; + (path: lodash.PropertyPath): LodashPath5x1; + (path: lodash.__, object: null | undefined): LodashPath5x2; + (path: lodash.PropertyPath, object: null | undefined): undefined; + (path: lodash.__, object: any): LodashPath6x2; + (path: lodash.PropertyPath, object: any): any; + } + interface LodashPath1x1 { + (object: TObject): TObject[TKey]; + (object: TObject | null | undefined): TObject[TKey] | undefined; + } + type LodashPath1x2 = (path: TKey | [TKey]) => TObject[TKey]; + type LodashPath2x2 = (path: TKey | [TKey]) => TObject[TKey] | undefined; + interface LodashPath3x1 { + (object: lodash.NumericDictionary): T; + (object: lodash.NumericDictionary | null | undefined): T | undefined; + } + type LodashPath3x2 = (path: number) => T; + type LodashPath4x2 = (path: number) => T | undefined; + interface LodashPath5x1 { + (object: null | undefined): undefined; + (object: any): any; + } + type LodashPath5x2 = (path: lodash.PropertyPath) => undefined; + type LodashPath6x2 = (path: lodash.PropertyPath) => any; + interface LodashPathOr { + (defaultValue: TDefault): LodashPathOr1x1; + (defaultValue: lodash.__, path: TKey | [TKey]): LodashPathOr1x2; + (defaultValue: TDefault, path: TKey | [TKey]): LodashPathOr1x3; + (defaultValue: lodash.__, path: lodash.__, object: TObject | null | undefined): LodashPathOr1x4; + (defaultValue: TDefault, path: lodash.__, object: TObject | null | undefined): LodashPathOr1x5; + (defaultValue: lodash.__, path: TKey | [TKey], object: TObject | null | undefined): LodashPathOr1x6; + (defaultValue: TDefault, path: TKey | [TKey], object: TObject | null | undefined): TObject[TKey] | TDefault; + (defaultValue: lodash.__, path: number): LodashPathOr2x2; + (defaultValue: TDefault, path: number): LodashPathOr2x3; + (defaultValue: lodash.__, path: lodash.__, object: lodash.NumericDictionary | null | undefined): LodashPathOr2x4; + (defaultValue: TDefault, path: lodash.__, object: lodash.NumericDictionary | null | undefined): LodashPathOr2x5; + (defaultValue: lodash.__, path: number, object: lodash.NumericDictionary | null | undefined): LodashPathOr2x6; + (defaultValue: TDefault, path: number, object: lodash.NumericDictionary | null | undefined): T | TDefault; + (defaultValue: lodash.__, path: lodash.PropertyPath): LodashPathOr3x2; + (defaultValue: TDefault, path: lodash.PropertyPath): LodashPathOr3x3; + (defaultValue: lodash.__, path: lodash.__, object: null | undefined): LodashPathOr3x4; + (defaultValue: TDefault, path: lodash.__, object: null | undefined): LodashPathOr3x5; + (defaultValue: lodash.__, path: lodash.PropertyPath, object: null | undefined): LodashPathOr3x6; + (defaultValue: TDefault, path: lodash.PropertyPath, object: null | undefined): TDefault; + (defaultValue: any): LodashPathOr4x1; + (defaultValue: any, path: lodash.PropertyPath): LodashPathOr4x3; + (defaultValue: lodash.__, path: lodash.__, object: any): LodashPathOr4x4; + (defaultValue: any, path: lodash.__, object: any): LodashPathOr4x5; + (defaultValue: lodash.__, path: lodash.PropertyPath, object: any): LodashPathOr4x6; + (defaultValue: any, path: lodash.PropertyPath, object: any): any; + } + interface LodashPathOr1x1 { + (path: TKey | [TKey]): LodashPathOr1x3; + (path: lodash.__, object: TObject | null | undefined): LodashPathOr1x5; + (path: TKey | [TKey], object: TObject | null | undefined): TObject[TKey] | TDefault; + (path: number): LodashPathOr2x3; + (path: lodash.__, object: lodash.NumericDictionary | null | undefined): LodashPathOr2x5; + (path: number, object: lodash.NumericDictionary | null | undefined): T | TDefault; + (path: lodash.PropertyPath): LodashPathOr3x3; + (path: lodash.__, object: null | undefined): LodashPathOr3x5; + (path: lodash.PropertyPath, object: null | undefined): TDefault; + } + interface LodashPathOr1x2 { + (defaultValue: TDefault): LodashPathOr1x3; + (defaultValue: lodash.__, object: TObject | null | undefined): LodashPathOr1x6; + (defaultValue: TDefault, object: TObject | null | undefined): TObject[TKey] | TDefault; + } + type LodashPathOr1x3 = (object: TObject | null | undefined) => TObject[TKey] | TDefault; + interface LodashPathOr1x4 { + (defaultValue: TDefault): LodashPathOr1x5; + (defaultValue: lodash.__, path: TKey | [TKey]): LodashPathOr1x6; + (defaultValue: TDefault, path: TKey | [TKey]): TObject[TKey] | TDefault; + } + type LodashPathOr1x5 = (path: TKey | [TKey]) => TObject[TKey] | TDefault; + type LodashPathOr1x6 = (defaultValue: TDefault) => TObject[TKey] | TDefault; + interface LodashPathOr2x2 { + (defaultValue: TDefault): LodashPathOr2x3; + (defaultValue: lodash.__, object: lodash.NumericDictionary | null | undefined): LodashPathOr2x6; + (defaultValue: TDefault, object: lodash.NumericDictionary | null | undefined): T | TDefault; + } + type LodashPathOr2x3 = (object: lodash.NumericDictionary | null | undefined) => T | TDefault; + interface LodashPathOr2x4 { + (defaultValue: TDefault): LodashPathOr2x5; + (defaultValue: lodash.__, path: number): LodashPathOr2x6; + (defaultValue: TDefault, path: number): T | TDefault; + } + type LodashPathOr2x5 = (path: number) => T | TDefault; + type LodashPathOr2x6 = (defaultValue: TDefault) => T | TDefault; + interface LodashPathOr3x2 { + (defaultValue: TDefault): LodashPathOr3x3; + (defaultValue: lodash.__, object: null | undefined): LodashPathOr3x6; + (defaultValue: TDefault, object: null | undefined): TDefault; + (defaultValue: any): LodashPathOr4x3; + (defaultValue: lodash.__, object: any): LodashPathOr4x6; + (defaultValue: any, object: any): any; + } + type LodashPathOr3x3 = (object: null | undefined) => TDefault; + interface LodashPathOr3x4 { + (defaultValue: TDefault): LodashPathOr3x5; + (defaultValue: lodash.__, path: lodash.PropertyPath): LodashPathOr3x6; + (defaultValue: TDefault, path: lodash.PropertyPath): TDefault; + } + type LodashPathOr3x5 = (path: lodash.PropertyPath) => TDefault; + type LodashPathOr3x6 = (defaultValue: TDefault) => TDefault; + interface LodashPathOr4x1 { + (path: lodash.PropertyPath): LodashPathOr4x3; + (path: lodash.__, object: any): LodashPathOr4x5; + (path: lodash.PropertyPath, object: any): any; + } + type LodashPathOr4x3 = (object: any) => any; + interface LodashPathOr4x4 { + (defaultValue: any): LodashPathOr4x5; + (defaultValue: lodash.__, path: lodash.PropertyPath): LodashPathOr4x6; + (defaultValue: any, path: lodash.PropertyPath): any; + } + type LodashPathOr4x5 = (path: lodash.PropertyPath) => any; + type LodashPathOr4x6 = (defaultValue: any) => any; + interface LodashPick { + (props: lodash.Many): LodashPick1x1; + (props: lodash.__, object: T): LodashPick1x2; + (props: lodash.Many, object: T): Pick; + (props: lodash.PropertyPath): LodashPick2x1; + (props: lodash.__, object: T | null | undefined): LodashPick2x2; + (props: lodash.PropertyPath, object: T | null | undefined): lodash.PartialDeep; + } + type LodashPick1x1 = (object: T) => Pick; + type LodashPick1x2 = (props: lodash.Many) => Pick; + type LodashPick2x1 = (object: T | null | undefined) => lodash.PartialDeep; + type LodashPick2x2 = (props: lodash.PropertyPath) => lodash.PartialDeep; + interface LodashPickBy { + (predicate: lodash.ValueKeyIterateeTypeGuard): LodashPickBy1x1; + (predicate: lodash.__, object: lodash.Dictionary | null | undefined): LodashPickBy1x2; + (predicate: lodash.ValueKeyIterateeTypeGuard, object: lodash.Dictionary | null | undefined): lodash.Dictionary; + (predicate: lodash.__, object: lodash.NumericDictionary | null | undefined): LodashPickBy2x2; + (predicate: lodash.ValueKeyIterateeTypeGuard, object: lodash.NumericDictionary | null | undefined): lodash.NumericDictionary; + (predicate: lodash.ValueKeyIteratee): LodashPickBy3x1; + (predicate: lodash.ValueKeyIteratee, object: lodash.Dictionary | null | undefined): lodash.Dictionary; + (predicate: lodash.ValueKeyIteratee, object: lodash.NumericDictionary | null | undefined): lodash.NumericDictionary; + (predicate: lodash.__, object: T | null | undefined): LodashPickBy5x2; + (predicate: lodash.ValueKeyIteratee, object: T | null | undefined): lodash.PartialObject; + } + interface LodashPickBy1x1 { + (object: lodash.Dictionary | null | undefined): lodash.Dictionary; + (object: lodash.NumericDictionary | null | undefined): lodash.NumericDictionary; + } + interface LodashPickBy1x2 { + (predicate: lodash.ValueKeyIterateeTypeGuard): lodash.Dictionary; + (predicate: lodash.ValueKeyIteratee): lodash.Dictionary; + } + interface LodashPickBy2x2 { + (predicate: lodash.ValueKeyIterateeTypeGuard): lodash.NumericDictionary; + (predicate: lodash.ValueKeyIteratee): lodash.NumericDictionary; + } + interface LodashPickBy3x1 { + (object: lodash.Dictionary | null | undefined): lodash.Dictionary; + (object: lodash.NumericDictionary | null | undefined): lodash.NumericDictionary; + (object: T1 | null | undefined): lodash.PartialObject; + } + type LodashPickBy5x2 = (predicate: lodash.ValueKeyIteratee) => lodash.PartialObject; + interface LodashProp { + (path: TKey | [TKey]): LodashProp1x1; + (path: lodash.__, object: TObject): LodashProp1x2; + (path: TKey | [TKey], object: TObject): TObject[TKey]; + (path: lodash.__, object: TObject | null | undefined): LodashProp2x2; + (path: TKey | [TKey], object: TObject | null | undefined): TObject[TKey] | undefined; + (path: number): LodashProp3x1; + (path: lodash.__, object: lodash.NumericDictionary): LodashProp3x2; + (path: number, object: lodash.NumericDictionary): T; + (path: lodash.__, object: lodash.NumericDictionary | null | undefined): LodashProp4x2; + (path: number, object: lodash.NumericDictionary | null | undefined): T | undefined; + (path: lodash.PropertyPath): LodashProp5x1; + (path: lodash.__, object: null | undefined): LodashProp5x2; + (path: lodash.PropertyPath, object: null | undefined): undefined; + (path: lodash.__, object: any): LodashProp6x2; + (path: lodash.PropertyPath, object: any): any; + } + interface LodashProp1x1 { + (object: TObject): TObject[TKey]; + (object: TObject | null | undefined): TObject[TKey] | undefined; + } + type LodashProp1x2 = (path: TKey | [TKey]) => TObject[TKey]; + type LodashProp2x2 = (path: TKey | [TKey]) => TObject[TKey] | undefined; + interface LodashProp3x1 { + (object: lodash.NumericDictionary): T; + (object: lodash.NumericDictionary | null | undefined): T | undefined; + } + type LodashProp3x2 = (path: number) => T; + type LodashProp4x2 = (path: number) => T | undefined; + interface LodashProp5x1 { + (object: null | undefined): undefined; + (object: any): any; + } + type LodashProp5x2 = (path: lodash.PropertyPath) => undefined; + type LodashProp6x2 = (path: lodash.PropertyPath) => any; + interface LodashProperty { + (path: TKey | [TKey]): LodashProperty1x1; + (path: lodash.__, object: TObject): LodashProperty1x2; + (path: TKey | [TKey], object: TObject): TObject[TKey]; + (path: lodash.__, object: TObject | null | undefined): LodashProperty2x2; + (path: TKey | [TKey], object: TObject | null | undefined): TObject[TKey] | undefined; + (path: number): LodashProperty3x1; + (path: lodash.__, object: lodash.NumericDictionary): LodashProperty3x2; + (path: number, object: lodash.NumericDictionary): T; + (path: lodash.__, object: lodash.NumericDictionary | null | undefined): LodashProperty4x2; + (path: number, object: lodash.NumericDictionary | null | undefined): T | undefined; + (path: lodash.PropertyPath): LodashProperty5x1; + (path: lodash.__, object: null | undefined): LodashProperty5x2; + (path: lodash.PropertyPath, object: null | undefined): undefined; + (path: lodash.__, object: any): LodashProperty6x2; + (path: lodash.PropertyPath, object: any): any; + } + interface LodashProperty1x1 { + (object: TObject): TObject[TKey]; + (object: TObject | null | undefined): TObject[TKey] | undefined; + } + type LodashProperty1x2 = (path: TKey | [TKey]) => TObject[TKey]; + type LodashProperty2x2 = (path: TKey | [TKey]) => TObject[TKey] | undefined; + interface LodashProperty3x1 { + (object: lodash.NumericDictionary): T; + (object: lodash.NumericDictionary | null | undefined): T | undefined; + } + type LodashProperty3x2 = (path: number) => T; + type LodashProperty4x2 = (path: number) => T | undefined; + interface LodashProperty5x1 { + (object: null | undefined): undefined; + (object: any): any; + } + type LodashProperty5x2 = (path: lodash.PropertyPath) => undefined; + type LodashProperty6x2 = (path: lodash.PropertyPath) => any; + interface LodashPropertyOf { + (path: TKey | [TKey]): LodashPropertyOf1x1; + (path: lodash.__, object: TObject): LodashPropertyOf1x2; + (path: TKey | [TKey], object: TObject): TObject[TKey]; + (path: lodash.__, object: TObject | null | undefined): LodashPropertyOf2x2; + (path: TKey | [TKey], object: TObject | null | undefined): TObject[TKey] | undefined; + (path: number): LodashPropertyOf3x1; + (path: lodash.__, object: lodash.NumericDictionary): LodashPropertyOf3x2; + (path: number, object: lodash.NumericDictionary): T; + (path: lodash.__, object: lodash.NumericDictionary | null | undefined): LodashPropertyOf4x2; + (path: number, object: lodash.NumericDictionary | null | undefined): T | undefined; + (path: lodash.PropertyPath): LodashPropertyOf5x1; + (path: lodash.__, object: null | undefined): LodashPropertyOf5x2; + (path: lodash.PropertyPath, object: null | undefined): undefined; + (path: lodash.__, object: any): LodashPropertyOf6x2; + (path: lodash.PropertyPath, object: any): any; + } + interface LodashPropertyOf1x1 { + (object: TObject): TObject[TKey]; + (object: TObject | null | undefined): TObject[TKey] | undefined; + } + type LodashPropertyOf1x2 = (path: TKey | [TKey]) => TObject[TKey]; + type LodashPropertyOf2x2 = (path: TKey | [TKey]) => TObject[TKey] | undefined; + interface LodashPropertyOf3x1 { + (object: lodash.NumericDictionary): T; + (object: lodash.NumericDictionary | null | undefined): T | undefined; + } + type LodashPropertyOf3x2 = (path: number) => T; + type LodashPropertyOf4x2 = (path: number) => T | undefined; + interface LodashPropertyOf5x1 { + (object: null | undefined): undefined; + (object: any): any; + } + type LodashPropertyOf5x2 = (path: lodash.PropertyPath) => undefined; + type LodashPropertyOf6x2 = (path: lodash.PropertyPath) => any; + interface LodashPropOr { + (defaultValue: TDefault): LodashPropOr1x1; + (defaultValue: lodash.__, path: TKey | [TKey]): LodashPropOr1x2; + (defaultValue: TDefault, path: TKey | [TKey]): LodashPropOr1x3; + (defaultValue: lodash.__, path: lodash.__, object: TObject | null | undefined): LodashPropOr1x4; + (defaultValue: TDefault, path: lodash.__, object: TObject | null | undefined): LodashPropOr1x5; + (defaultValue: lodash.__, path: TKey | [TKey], object: TObject | null | undefined): LodashPropOr1x6; + (defaultValue: TDefault, path: TKey | [TKey], object: TObject | null | undefined): TObject[TKey] | TDefault; + (defaultValue: lodash.__, path: number): LodashPropOr2x2; + (defaultValue: TDefault, path: number): LodashPropOr2x3; + (defaultValue: lodash.__, path: lodash.__, object: lodash.NumericDictionary | null | undefined): LodashPropOr2x4; + (defaultValue: TDefault, path: lodash.__, object: lodash.NumericDictionary | null | undefined): LodashPropOr2x5; + (defaultValue: lodash.__, path: number, object: lodash.NumericDictionary | null | undefined): LodashPropOr2x6; + (defaultValue: TDefault, path: number, object: lodash.NumericDictionary | null | undefined): T | TDefault; + (defaultValue: lodash.__, path: lodash.PropertyPath): LodashPropOr3x2; + (defaultValue: TDefault, path: lodash.PropertyPath): LodashPropOr3x3; + (defaultValue: lodash.__, path: lodash.__, object: null | undefined): LodashPropOr3x4; + (defaultValue: TDefault, path: lodash.__, object: null | undefined): LodashPropOr3x5; + (defaultValue: lodash.__, path: lodash.PropertyPath, object: null | undefined): LodashPropOr3x6; + (defaultValue: TDefault, path: lodash.PropertyPath, object: null | undefined): TDefault; + (defaultValue: any): LodashPropOr4x1; + (defaultValue: any, path: lodash.PropertyPath): LodashPropOr4x3; + (defaultValue: lodash.__, path: lodash.__, object: any): LodashPropOr4x4; + (defaultValue: any, path: lodash.__, object: any): LodashPropOr4x5; + (defaultValue: lodash.__, path: lodash.PropertyPath, object: any): LodashPropOr4x6; + (defaultValue: any, path: lodash.PropertyPath, object: any): any; + } + interface LodashPropOr1x1 { + (path: TKey | [TKey]): LodashPropOr1x3; + (path: lodash.__, object: TObject | null | undefined): LodashPropOr1x5; + (path: TKey | [TKey], object: TObject | null | undefined): TObject[TKey] | TDefault; + (path: number): LodashPropOr2x3; + (path: lodash.__, object: lodash.NumericDictionary | null | undefined): LodashPropOr2x5; + (path: number, object: lodash.NumericDictionary | null | undefined): T | TDefault; + (path: lodash.PropertyPath): LodashPropOr3x3; + (path: lodash.__, object: null | undefined): LodashPropOr3x5; + (path: lodash.PropertyPath, object: null | undefined): TDefault; + } + interface LodashPropOr1x2 { + (defaultValue: TDefault): LodashPropOr1x3; + (defaultValue: lodash.__, object: TObject | null | undefined): LodashPropOr1x6; + (defaultValue: TDefault, object: TObject | null | undefined): TObject[TKey] | TDefault; + } + type LodashPropOr1x3 = (object: TObject | null | undefined) => TObject[TKey] | TDefault; + interface LodashPropOr1x4 { + (defaultValue: TDefault): LodashPropOr1x5; + (defaultValue: lodash.__, path: TKey | [TKey]): LodashPropOr1x6; + (defaultValue: TDefault, path: TKey | [TKey]): TObject[TKey] | TDefault; + } + type LodashPropOr1x5 = (path: TKey | [TKey]) => TObject[TKey] | TDefault; + type LodashPropOr1x6 = (defaultValue: TDefault) => TObject[TKey] | TDefault; + interface LodashPropOr2x2 { + (defaultValue: TDefault): LodashPropOr2x3; + (defaultValue: lodash.__, object: lodash.NumericDictionary | null | undefined): LodashPropOr2x6; + (defaultValue: TDefault, object: lodash.NumericDictionary | null | undefined): T | TDefault; + } + type LodashPropOr2x3 = (object: lodash.NumericDictionary | null | undefined) => T | TDefault; + interface LodashPropOr2x4 { + (defaultValue: TDefault): LodashPropOr2x5; + (defaultValue: lodash.__, path: number): LodashPropOr2x6; + (defaultValue: TDefault, path: number): T | TDefault; + } + type LodashPropOr2x5 = (path: number) => T | TDefault; + type LodashPropOr2x6 = (defaultValue: TDefault) => T | TDefault; + interface LodashPropOr3x2 { + (defaultValue: TDefault): LodashPropOr3x3; + (defaultValue: lodash.__, object: null | undefined): LodashPropOr3x6; + (defaultValue: TDefault, object: null | undefined): TDefault; + (defaultValue: any): LodashPropOr4x3; + (defaultValue: lodash.__, object: any): LodashPropOr4x6; + (defaultValue: any, object: any): any; + } + type LodashPropOr3x3 = (object: null | undefined) => TDefault; + interface LodashPropOr3x4 { + (defaultValue: TDefault): LodashPropOr3x5; + (defaultValue: lodash.__, path: lodash.PropertyPath): LodashPropOr3x6; + (defaultValue: TDefault, path: lodash.PropertyPath): TDefault; + } + type LodashPropOr3x5 = (path: lodash.PropertyPath) => TDefault; + type LodashPropOr3x6 = (defaultValue: TDefault) => TDefault; + interface LodashPropOr4x1 { + (path: lodash.PropertyPath): LodashPropOr4x3; + (path: lodash.__, object: any): LodashPropOr4x5; + (path: lodash.PropertyPath, object: any): any; + } + type LodashPropOr4x3 = (object: any) => any; + interface LodashPropOr4x4 { + (defaultValue: any): LodashPropOr4x5; + (defaultValue: lodash.__, path: lodash.PropertyPath): LodashPropOr4x6; + (defaultValue: any, path: lodash.PropertyPath): any; + } + type LodashPropOr4x5 = (path: lodash.PropertyPath) => any; + type LodashPropOr4x6 = (defaultValue: any) => any; + interface LodashPull { + (values: T): LodashPull1x1; + (values: lodash.__, array: ReadonlyArray): LodashPull1x2; + (values: T, array: ReadonlyArray): T[]; + (values: lodash.__, array: lodash.List): LodashPull2x2; + (values: T, array: lodash.List): lodash.List; + } + interface LodashPull1x1 { + (array: ReadonlyArray): T[]; + (array: lodash.List): lodash.List; + } + type LodashPull1x2 = (values: T) => T[]; + type LodashPull2x2 = (values: T) => lodash.List; + interface LodashPullAll { + (values: lodash.List): LodashPullAll1x1; + (values: lodash.__, array: ReadonlyArray): LodashPullAll1x2; + (values: lodash.List, array: ReadonlyArray): T[]; + (values: lodash.__, array: lodash.List): LodashPullAll2x2; + (values: lodash.List, array: lodash.List): lodash.List; + } + interface LodashPullAll1x1 { + (array: ReadonlyArray): T[]; + (array: lodash.List): lodash.List; + } + type LodashPullAll1x2 = (values: lodash.List) => T[]; + type LodashPullAll2x2 = (values: lodash.List) => lodash.List; + interface LodashPullAllBy { + (iteratee: lodash.ValueIteratee): LodashPullAllBy1x1; + (iteratee: lodash.__, values: lodash.List): LodashPullAllBy1x2; + (iteratee: lodash.ValueIteratee, values: lodash.List): LodashPullAllBy1x3; + (iteratee: lodash.__, values: lodash.__, array: ReadonlyArray): LodashPullAllBy1x4; + (iteratee: lodash.ValueIteratee, values: lodash.__, array: ReadonlyArray): LodashPullAllBy1x5; + (iteratee: lodash.__, values: lodash.List, array: ReadonlyArray): LodashPullAllBy1x6; + (iteratee: lodash.ValueIteratee, values: lodash.List, array: ReadonlyArray): T[]; + (iteratee: lodash.__, values: lodash.__, array: lodash.List): LodashPullAllBy2x4; + (iteratee: lodash.ValueIteratee, values: lodash.__, array: lodash.List): LodashPullAllBy2x5; + (iteratee: lodash.__, values: lodash.List, array: lodash.List): LodashPullAllBy2x6; + (iteratee: lodash.ValueIteratee, values: lodash.List, array: lodash.List): lodash.List; + (iteratee: lodash.ValueIteratee): LodashPullAllBy3x1; + (iteratee: lodash.__, values: lodash.List): LodashPullAllBy3x2; + (iteratee: lodash.ValueIteratee, values: lodash.List): LodashPullAllBy3x3; + (iteratee: lodash.__, values: lodash.__, array: ReadonlyArray): LodashPullAllBy3x4; + (iteratee: lodash.ValueIteratee, values: lodash.__, array: ReadonlyArray): LodashPullAllBy3x5; + (iteratee: lodash.__, values: lodash.List, array: ReadonlyArray): LodashPullAllBy3x6; + (iteratee: lodash.ValueIteratee, values: lodash.List, array: ReadonlyArray): T1[]; + (iteratee: lodash.__, values: lodash.__, array: lodash.List): LodashPullAllBy4x4; + (iteratee: lodash.ValueIteratee, values: lodash.__, array: lodash.List): LodashPullAllBy4x5; + (iteratee: lodash.__, values: lodash.List, array: lodash.List): LodashPullAllBy4x6; + (iteratee: lodash.ValueIteratee, values: lodash.List, array: lodash.List): lodash.List; + } + interface LodashPullAllBy1x1 { + (values: lodash.List): LodashPullAllBy1x3; + (values: lodash.__, array: ReadonlyArray): LodashPullAllBy1x5; + (values: lodash.List, array: ReadonlyArray): T[]; + (values: lodash.__, array: lodash.List): LodashPullAllBy2x5; + (values: lodash.List, array: lodash.List): lodash.List; + } + interface LodashPullAllBy1x2 { + (iteratee: lodash.ValueIteratee): LodashPullAllBy1x3; + (iteratee: lodash.__, array: ReadonlyArray): LodashPullAllBy1x6; + (iteratee: lodash.ValueIteratee, array: ReadonlyArray): T[]; + (iteratee: lodash.__, array: lodash.List): LodashPullAllBy2x6; + (iteratee: lodash.ValueIteratee, array: lodash.List): lodash.List; + } + interface LodashPullAllBy1x3 { + (array: ReadonlyArray): T[]; + (array: lodash.List): lodash.List; + } + interface LodashPullAllBy1x4 { + (iteratee: lodash.ValueIteratee): LodashPullAllBy1x5; + (iteratee: lodash.__, values: lodash.List): LodashPullAllBy1x6; + (iteratee: lodash.ValueIteratee, values: lodash.List): T[]; + } + type LodashPullAllBy1x5 = (values: lodash.List) => T[]; + type LodashPullAllBy1x6 = (iteratee: lodash.ValueIteratee) => T[]; + interface LodashPullAllBy2x4 { + (iteratee: lodash.ValueIteratee): LodashPullAllBy2x5; + (iteratee: lodash.__, values: lodash.List): LodashPullAllBy2x6; + (iteratee: lodash.ValueIteratee, values: lodash.List): lodash.List; + } + type LodashPullAllBy2x5 = (values: lodash.List) => lodash.List; + type LodashPullAllBy2x6 = (iteratee: lodash.ValueIteratee) => lodash.List; + interface LodashPullAllBy3x1 { + (values: lodash.List): LodashPullAllBy3x3; + (values: lodash.__, array: ReadonlyArray): LodashPullAllBy3x5; + (values: lodash.List, array: ReadonlyArray): T1[]; + (values: lodash.__, array: lodash.List): LodashPullAllBy4x5; + (values: lodash.List, array: lodash.List): lodash.List; + } + interface LodashPullAllBy3x2 { + (iteratee: lodash.ValueIteratee): LodashPullAllBy3x3; + (iteratee: lodash.__, array: ReadonlyArray): LodashPullAllBy3x6; + (iteratee: lodash.ValueIteratee, array: ReadonlyArray): T1[]; + (iteratee: lodash.__, array: lodash.List): LodashPullAllBy4x6; + (iteratee: lodash.ValueIteratee, array: lodash.List): lodash.List; + } + interface LodashPullAllBy3x3 { + (array: ReadonlyArray): T1[]; + (array: lodash.List): lodash.List; + } + interface LodashPullAllBy3x4 { + (iteratee: lodash.ValueIteratee): LodashPullAllBy3x5; + (iteratee: lodash.__, values: lodash.List): LodashPullAllBy3x6; + (iteratee: lodash.ValueIteratee, values: lodash.List): T1[]; + } + type LodashPullAllBy3x5 = (values: lodash.List) => T1[]; + type LodashPullAllBy3x6 = (iteratee: lodash.ValueIteratee) => T1[]; + interface LodashPullAllBy4x4 { + (iteratee: lodash.ValueIteratee): LodashPullAllBy4x5; + (iteratee: lodash.__, values: lodash.List): LodashPullAllBy4x6; + (iteratee: lodash.ValueIteratee, values: lodash.List): lodash.List; + } + type LodashPullAllBy4x5 = (values: lodash.List) => lodash.List; + type LodashPullAllBy4x6 = (iteratee: lodash.ValueIteratee) => lodash.List; + interface LodashPullAllWith { + (comparator: lodash.Comparator): LodashPullAllWith1x1; + (comparator: lodash.__, values: lodash.List): LodashPullAllWith1x2; + (comparator: lodash.Comparator, values: lodash.List): LodashPullAllWith1x3; + (comparator: lodash.__, values: lodash.__, array: ReadonlyArray): LodashPullAllWith1x4; + (comparator: lodash.Comparator, values: lodash.__, array: ReadonlyArray): LodashPullAllWith1x5; + (comparator: lodash.__, values: lodash.List, array: ReadonlyArray): LodashPullAllWith1x6; + (comparator: lodash.Comparator, values: lodash.List, array: ReadonlyArray): T[]; + (comparator: lodash.__, values: lodash.__, array: lodash.List): LodashPullAllWith2x4; + (comparator: lodash.Comparator, values: lodash.__, array: lodash.List): LodashPullAllWith2x5; + (comparator: lodash.__, values: lodash.List, array: lodash.List): LodashPullAllWith2x6; + (comparator: lodash.Comparator, values: lodash.List, array: lodash.List): lodash.List; + (comparator: lodash.Comparator2): LodashPullAllWith3x1; + (comparator: lodash.__, values: lodash.List): LodashPullAllWith3x2; + (comparator: lodash.Comparator2, values: lodash.List): LodashPullAllWith3x3; + (comparator: lodash.__, values: lodash.__, array: ReadonlyArray): LodashPullAllWith3x4; + (comparator: lodash.Comparator2, values: lodash.__, array: ReadonlyArray): LodashPullAllWith3x5; + (comparator: lodash.__, values: lodash.List, array: ReadonlyArray): LodashPullAllWith3x6; + (comparator: lodash.Comparator2, values: lodash.List, array: ReadonlyArray): T1[]; + (comparator: lodash.__, values: lodash.__, array: lodash.List): LodashPullAllWith4x4; + (comparator: lodash.Comparator2, values: lodash.__, array: lodash.List): LodashPullAllWith4x5; + (comparator: lodash.__, values: lodash.List, array: lodash.List): LodashPullAllWith4x6; + (comparator: lodash.Comparator2, values: lodash.List, array: lodash.List): lodash.List; + } + interface LodashPullAllWith1x1 { + (values: lodash.List): LodashPullAllWith1x3; + (values: lodash.__, array: ReadonlyArray): LodashPullAllWith1x5; + (values: lodash.List, array: ReadonlyArray): T[]; + (values: lodash.__, array: lodash.List): LodashPullAllWith2x5; + (values: lodash.List, array: lodash.List): lodash.List; + } + interface LodashPullAllWith1x2 { + (comparator: lodash.Comparator): LodashPullAllWith1x3; + (comparator: lodash.__, array: ReadonlyArray): LodashPullAllWith1x6; + (comparator: lodash.Comparator, array: ReadonlyArray): T[]; + (comparator: lodash.__, array: lodash.List): LodashPullAllWith2x6; + (comparator: lodash.Comparator, array: lodash.List): lodash.List; + } + interface LodashPullAllWith1x3 { + (array: ReadonlyArray): T[]; + (array: lodash.List): lodash.List; + } + interface LodashPullAllWith1x4 { + (comparator: lodash.Comparator): LodashPullAllWith1x5; + (comparator: lodash.__, values: lodash.List): LodashPullAllWith1x6; + (comparator: lodash.Comparator, values: lodash.List): T[]; + } + type LodashPullAllWith1x5 = (values: lodash.List) => T[]; + type LodashPullAllWith1x6 = (comparator: lodash.Comparator) => T[]; + interface LodashPullAllWith2x4 { + (comparator: lodash.Comparator): LodashPullAllWith2x5; + (comparator: lodash.__, values: lodash.List): LodashPullAllWith2x6; + (comparator: lodash.Comparator, values: lodash.List): lodash.List; + } + type LodashPullAllWith2x5 = (values: lodash.List) => lodash.List; + type LodashPullAllWith2x6 = (comparator: lodash.Comparator) => lodash.List; + interface LodashPullAllWith3x1 { + (values: lodash.List): LodashPullAllWith3x3; + (values: lodash.__, array: ReadonlyArray): LodashPullAllWith3x5; + (values: lodash.List, array: ReadonlyArray): T1[]; + (values: lodash.__, array: lodash.List): LodashPullAllWith4x5; + (values: lodash.List, array: lodash.List): lodash.List; + } + interface LodashPullAllWith3x2 { + (comparator: lodash.Comparator2): LodashPullAllWith3x3; + (comparator: lodash.__, array: ReadonlyArray): LodashPullAllWith3x6; + (comparator: lodash.Comparator2, array: ReadonlyArray): T1[]; + (comparator: lodash.__, array: lodash.List): LodashPullAllWith4x6; + (comparator: lodash.Comparator2, array: lodash.List): lodash.List; + } + interface LodashPullAllWith3x3 { + (array: ReadonlyArray): T1[]; + (array: lodash.List): lodash.List; + } + interface LodashPullAllWith3x4 { + (comparator: lodash.Comparator2): LodashPullAllWith3x5; + (comparator: lodash.__, values: lodash.List): LodashPullAllWith3x6; + (comparator: lodash.Comparator2, values: lodash.List): T1[]; + } + type LodashPullAllWith3x5 = (values: lodash.List) => T1[]; + type LodashPullAllWith3x6 = (comparator: lodash.Comparator2) => T1[]; + interface LodashPullAllWith4x4 { + (comparator: lodash.Comparator2): LodashPullAllWith4x5; + (comparator: lodash.__, values: lodash.List): LodashPullAllWith4x6; + (comparator: lodash.Comparator2, values: lodash.List): lodash.List; + } + type LodashPullAllWith4x5 = (values: lodash.List) => lodash.List; + type LodashPullAllWith4x6 = (comparator: lodash.Comparator2) => lodash.List; + interface LodashPullAt { + (indexes: lodash.Many): LodashPullAt1x1; + (indexes: lodash.__, array: ReadonlyArray): LodashPullAt1x2; + (indexes: lodash.Many, array: ReadonlyArray): T[]; + (indexes: lodash.__, array: lodash.List): LodashPullAt2x2; + (indexes: lodash.Many, array: lodash.List): lodash.List; + } + interface LodashPullAt1x1 { + (array: ReadonlyArray): T[]; + (array: lodash.List): lodash.List; + } + type LodashPullAt1x2 = (indexes: lodash.Many) => T[]; + type LodashPullAt2x2 = (indexes: lodash.Many) => lodash.List; + interface LodashRandom { + (maxOrMin: number): LodashRandom1x1; + (max: lodash.__, floating: boolean): LodashRandom1x2; + (maxOrMin: number, floatingOrMax: boolean | number): number; + (min: lodash.__, max: number): LodashRandom2x2; + } + type LodashRandom1x1 = (floatingOrMax: boolean | number) => number; + type LodashRandom1x2 = (max: number) => number; + type LodashRandom2x2 = (min: number) => number; + interface LodashRange { + (start: number): LodashRange1x1; + (start: lodash.__, end: number): LodashRange1x2; + (start: number, end: number): number[]; + } + type LodashRange1x1 = (end: number) => number[]; + type LodashRange1x2 = (start: number) => number[]; + interface LodashRangeRight { + (start: number): LodashRangeRight1x1; + (start: lodash.__, end: number): LodashRangeRight1x2; + (start: number, end: number): number[]; + } + type LodashRangeRight1x1 = (end: number) => number[]; + type LodashRangeRight1x2 = (start: number) => number[]; + interface LodashRangeStep { + (start: number): LodashRangeStep1x1; + (start: lodash.__, end: number): LodashRangeStep1x2; + (start: number, end: number): LodashRangeStep1x3; + (start: lodash.__, end: lodash.__, step: number): LodashRangeStep1x4; + (start: number, end: lodash.__, step: number): LodashRangeStep1x5; + (start: lodash.__, end: number, step: number): LodashRangeStep1x6; + (start: number, end: number, step: number): number[]; + } + interface LodashRangeStep1x1 { + (end: number): LodashRangeStep1x3; + (end: lodash.__, step: number): LodashRangeStep1x5; + (end: number, step: number): number[]; + } + interface LodashRangeStep1x2 { + (start: number): LodashRangeStep1x3; + (start: lodash.__, step: number): LodashRangeStep1x6; + (start: number, step: number): number[]; + } + type LodashRangeStep1x3 = (step: number) => number[]; + interface LodashRangeStep1x4 { + (start: number): LodashRangeStep1x5; + (start: lodash.__, end: number): LodashRangeStep1x6; + (start: number, end: number): number[]; + } + type LodashRangeStep1x5 = (end: number) => number[]; + type LodashRangeStep1x6 = (start: number) => number[]; + interface LodashRangeStepRight { + (start: number): LodashRangeStepRight1x1; + (start: lodash.__, end: number): LodashRangeStepRight1x2; + (start: number, end: number): LodashRangeStepRight1x3; + (start: lodash.__, end: lodash.__, step: number): LodashRangeStepRight1x4; + (start: number, end: lodash.__, step: number): LodashRangeStepRight1x5; + (start: lodash.__, end: number, step: number): LodashRangeStepRight1x6; + (start: number, end: number, step: number): number[]; + } + interface LodashRangeStepRight1x1 { + (end: number): LodashRangeStepRight1x3; + (end: lodash.__, step: number): LodashRangeStepRight1x5; + (end: number, step: number): number[]; + } + interface LodashRangeStepRight1x2 { + (start: number): LodashRangeStepRight1x3; + (start: lodash.__, step: number): LodashRangeStepRight1x6; + (start: number, step: number): number[]; + } + type LodashRangeStepRight1x3 = (step: number) => number[]; + interface LodashRangeStepRight1x4 { + (start: number): LodashRangeStepRight1x5; + (start: lodash.__, end: number): LodashRangeStepRight1x6; + (start: number, end: number): number[]; + } + type LodashRangeStepRight1x5 = (end: number) => number[]; + type LodashRangeStepRight1x6 = (start: number) => number[]; + interface LodashRearg { + (indexes: lodash.Many): LodashRearg1x1; + (indexes: lodash.__, func: (...args: any[]) => any): LodashRearg1x2; + (indexes: lodash.Many, func: (...args: any[]) => any): (...args: any[]) => any; + } + type LodashRearg1x1 = (func: (...args: any[]) => any) => (...args: any[]) => any; + type LodashRearg1x2 = (indexes: lodash.Many) => (...args: any[]) => any; + interface LodashReduce { + (callback: lodash.MemoIteratorCapped): LodashReduce1x1; + (callback: lodash.__, accumulator: TResult): LodashReduce1x2; + (callback: lodash.MemoIteratorCapped, accumulator: TResult): LodashReduce1x3; + (callback: lodash.__, accumulator: lodash.__, collection: T[] | null | undefined): LodashReduce1x4; + (callback: lodash.MemoIteratorCapped, accumulator: lodash.__, collection: T[] | null | undefined): LodashReduce1x5; + (callback: lodash.__, accumulator: TResult, collection: T[] | null | undefined): LodashReduce1x6; + (callback: lodash.MemoIteratorCapped, accumulator: TResult, collection: T[] | lodash.List | null | undefined): TResult; + (callback: lodash.__, accumulator: lodash.__, collection: lodash.List | null | undefined): LodashReduce2x4; + (callback: lodash.MemoIteratorCapped, accumulator: lodash.__, collection: lodash.List | null | undefined): LodashReduce2x5; + (callback: lodash.__, accumulator: TResult, collection: lodash.List | null | undefined): LodashReduce2x6; + (callback: lodash.MemoIteratorCapped): LodashReduce3x1; + (callback: lodash.MemoIteratorCapped, accumulator: TResult): LodashReduce3x3; + (callback: lodash.__, accumulator: lodash.__, collection: T | null | undefined): LodashReduce3x4; + (callback: lodash.MemoIteratorCapped, accumulator: lodash.__, collection: T | null | undefined): LodashReduce3x5; + (callback: lodash.__, accumulator: TResult, collection: T | null | undefined): LodashReduce3x6; + (callback: lodash.MemoIteratorCapped, accumulator: TResult, collection: T | null | undefined): TResult; + } + interface LodashReduce1x1 { + (accumulator: TResult): LodashReduce1x3; + (accumulator: lodash.__, collection: T[] | null | undefined): LodashReduce1x5; + (accumulator: TResult, collection: T[] | lodash.List | null | undefined): TResult; + (accumulator: lodash.__, collection: lodash.List | null | undefined): LodashReduce2x5; + } + interface LodashReduce1x2 { + (callback: lodash.MemoIteratorCapped): LodashReduce1x3; + (callback: lodash.__, collection: T[] | null | undefined): LodashReduce1x6; + (callback: lodash.MemoIteratorCapped, collection: T[] | lodash.List | null | undefined): TResult; + (callback: lodash.__, collection: lodash.List | null | undefined): LodashReduce2x6; + (callback: lodash.MemoIteratorCapped): LodashReduce3x3; + (callback: lodash.__, collection: T | null | undefined): LodashReduce3x6; + (callback: lodash.MemoIteratorCapped, collection: T | null | undefined): TResult; + } + type LodashReduce1x3 = (collection: T[] | lodash.List | null | undefined) => TResult; + interface LodashReduce1x4 { + (callback: lodash.MemoIteratorCapped): LodashReduce1x5; + (callback: lodash.__, accumulator: TResult): LodashReduce1x6; + (callback: lodash.MemoIteratorCapped, accumulator: TResult): TResult; + } + type LodashReduce1x5 = (accumulator: TResult) => TResult; + type LodashReduce1x6 = (callback: lodash.MemoIteratorCapped) => TResult; + interface LodashReduce2x4 { + (callback: lodash.MemoIteratorCapped): LodashReduce2x5; + (callback: lodash.__, accumulator: TResult): LodashReduce2x6; + (callback: lodash.MemoIteratorCapped, accumulator: TResult): TResult; + } + type LodashReduce2x5 = (accumulator: TResult) => TResult; + type LodashReduce2x6 = (callback: lodash.MemoIteratorCapped) => TResult; + interface LodashReduce3x1 { + (accumulator: TResult): LodashReduce3x3; + (accumulator: lodash.__, collection: T | null | undefined): LodashReduce3x5; + (accumulator: TResult, collection: T | null | undefined): TResult; + } + type LodashReduce3x3 = (collection: T | null | undefined) => TResult; + interface LodashReduce3x4 { + (callback: lodash.MemoIteratorCapped): LodashReduce3x5; + (callback: lodash.__, accumulator: TResult): LodashReduce3x6; + (callback: lodash.MemoIteratorCapped, accumulator: TResult): TResult; + } + type LodashReduce3x5 = (accumulator: TResult) => TResult; + type LodashReduce3x6 = (callback: lodash.MemoIteratorCapped) => TResult; + interface LodashReduceRight { + (callback: lodash.MemoIteratorCappedRight): LodashReduceRight1x1; + (callback: lodash.__, accumulator: TResult): LodashReduceRight1x2; + (callback: lodash.MemoIteratorCappedRight, accumulator: TResult): LodashReduceRight1x3; + (callback: lodash.__, accumulator: lodash.__, collection: T[] | null | undefined): LodashReduceRight1x4; + (callback: lodash.MemoIteratorCappedRight, accumulator: lodash.__, collection: T[] | null | undefined): LodashReduceRight1x5; + (callback: lodash.__, accumulator: TResult, collection: T[] | null | undefined): LodashReduceRight1x6; + (callback: lodash.MemoIteratorCappedRight, accumulator: TResult, collection: T[] | lodash.List | null | undefined): TResult; + (callback: lodash.__, accumulator: lodash.__, collection: lodash.List | null | undefined): LodashReduceRight2x4; + (callback: lodash.MemoIteratorCappedRight, accumulator: lodash.__, collection: lodash.List | null | undefined): LodashReduceRight2x5; + (callback: lodash.__, accumulator: TResult, collection: lodash.List | null | undefined): LodashReduceRight2x6; + (callback: lodash.MemoIteratorCappedRight): LodashReduceRight3x1; + (callback: lodash.MemoIteratorCappedRight, accumulator: TResult): LodashReduceRight3x3; + (callback: lodash.__, accumulator: lodash.__, collection: T | null | undefined): LodashReduceRight3x4; + (callback: lodash.MemoIteratorCappedRight, accumulator: lodash.__, collection: T | null | undefined): LodashReduceRight3x5; + (callback: lodash.__, accumulator: TResult, collection: T | null | undefined): LodashReduceRight3x6; + (callback: lodash.MemoIteratorCappedRight, accumulator: TResult, collection: T | null | undefined): TResult; + } + interface LodashReduceRight1x1 { + (accumulator: TResult): LodashReduceRight1x3; + (accumulator: lodash.__, collection: T[] | null | undefined): LodashReduceRight1x5; + (accumulator: TResult, collection: T[] | lodash.List | null | undefined): TResult; + (accumulator: lodash.__, collection: lodash.List | null | undefined): LodashReduceRight2x5; + } + interface LodashReduceRight1x2 { + (callback: lodash.MemoIteratorCappedRight): LodashReduceRight1x3; + (callback: lodash.__, collection: T[] | null | undefined): LodashReduceRight1x6; + (callback: lodash.MemoIteratorCappedRight, collection: T[] | lodash.List | null | undefined): TResult; + (callback: lodash.__, collection: lodash.List | null | undefined): LodashReduceRight2x6; + (callback: lodash.MemoIteratorCappedRight): LodashReduceRight3x3; + (callback: lodash.__, collection: T | null | undefined): LodashReduceRight3x6; + (callback: lodash.MemoIteratorCappedRight, collection: T | null | undefined): TResult; + } + type LodashReduceRight1x3 = (collection: T[] | lodash.List | null | undefined) => TResult; + interface LodashReduceRight1x4 { + (callback: lodash.MemoIteratorCappedRight): LodashReduceRight1x5; + (callback: lodash.__, accumulator: TResult): LodashReduceRight1x6; + (callback: lodash.MemoIteratorCappedRight, accumulator: TResult): TResult; + } + type LodashReduceRight1x5 = (accumulator: TResult) => TResult; + type LodashReduceRight1x6 = (callback: lodash.MemoIteratorCappedRight) => TResult; + interface LodashReduceRight2x4 { + (callback: lodash.MemoIteratorCappedRight): LodashReduceRight2x5; + (callback: lodash.__, accumulator: TResult): LodashReduceRight2x6; + (callback: lodash.MemoIteratorCappedRight, accumulator: TResult): TResult; + } + type LodashReduceRight2x5 = (accumulator: TResult) => TResult; + type LodashReduceRight2x6 = (callback: lodash.MemoIteratorCappedRight) => TResult; + interface LodashReduceRight3x1 { + (accumulator: TResult): LodashReduceRight3x3; + (accumulator: lodash.__, collection: T | null | undefined): LodashReduceRight3x5; + (accumulator: TResult, collection: T | null | undefined): TResult; + } + type LodashReduceRight3x3 = (collection: T | null | undefined) => TResult; + interface LodashReduceRight3x4 { + (callback: lodash.MemoIteratorCappedRight): LodashReduceRight3x5; + (callback: lodash.__, accumulator: TResult): LodashReduceRight3x6; + (callback: lodash.MemoIteratorCappedRight, accumulator: TResult): TResult; + } + type LodashReduceRight3x5 = (accumulator: TResult) => TResult; + type LodashReduceRight3x6 = (callback: lodash.MemoIteratorCappedRight) => TResult; + interface LodashReject { + (predicate: (value: string) => boolean): LodashReject1x1; + (predicate: lodash.__, collection: string | null | undefined): LodashReject1x2; + (predicate: (value: string) => boolean, collection: string | null | undefined): string[]; + (predicate: lodash.ValueIterateeCustom): LodashReject2x1; + (predicate: lodash.__, collection: lodash.List | null | undefined): LodashReject2x2; + (predicate: lodash.ValueIterateeCustom, collection: lodash.List | null | undefined): T[]; + (predicate: lodash.__, collection: T | null | undefined): LodashReject3x2; + (predicate: lodash.ValueIterateeCustom, collection: T | null | undefined): Array; + } + type LodashReject1x1 = (collection: string | null | undefined) => string[]; + type LodashReject1x2 = (predicate: (value: string) => boolean) => string[]; + type LodashReject2x1 = (collection: lodash.List | object | null | undefined) => T[]; + type LodashReject2x2 = (predicate: lodash.ValueIterateeCustom) => T[]; + type LodashReject3x2 = (predicate: lodash.ValueIterateeCustom) => Array; + interface LodashRemove { + (predicate: lodash.ValueIteratee): LodashRemove1x1; + (predicate: lodash.__, array: lodash.List): LodashRemove1x2; + (predicate: lodash.ValueIteratee, array: lodash.List): T[]; + } + type LodashRemove1x1 = (array: lodash.List) => T[]; + type LodashRemove1x2 = (predicate: lodash.ValueIteratee) => T[]; + interface LodashRepeat { + (n: number): LodashRepeat1x1; + (n: lodash.__, string: string): LodashRepeat1x2; + (n: number, string: string): string; + } + type LodashRepeat1x1 = (string: string) => string; + type LodashRepeat1x2 = (n: number) => string; + interface LodashReplace { + (pattern: RegExp | string): LodashReplace1x1; + (pattern: lodash.__, replacement: lodash.ReplaceFunction | string): LodashReplace1x2; + (pattern: RegExp | string, replacement: lodash.ReplaceFunction | string): LodashReplace1x3; + (pattern: lodash.__, replacement: lodash.__, string: string): LodashReplace1x4; + (pattern: RegExp | string, replacement: lodash.__, string: string): LodashReplace1x5; + (pattern: lodash.__, replacement: lodash.ReplaceFunction | string, string: string): LodashReplace1x6; + (pattern: RegExp | string, replacement: lodash.ReplaceFunction | string, string: string): string; + } + interface LodashReplace1x1 { + (replacement: lodash.ReplaceFunction | string): LodashReplace1x3; + (replacement: lodash.__, string: string): LodashReplace1x5; + (replacement: lodash.ReplaceFunction | string, string: string): string; + } + interface LodashReplace1x2 { + (pattern: RegExp | string): LodashReplace1x3; + (pattern: lodash.__, string: string): LodashReplace1x6; + (pattern: RegExp | string, string: string): string; + } + type LodashReplace1x3 = (string: string) => string; + interface LodashReplace1x4 { + (pattern: RegExp | string): LodashReplace1x5; + (pattern: lodash.__, replacement: lodash.ReplaceFunction | string): LodashReplace1x6; + (pattern: RegExp | string, replacement: lodash.ReplaceFunction | string): string; + } + type LodashReplace1x5 = (replacement: lodash.ReplaceFunction | string) => string; + type LodashReplace1x6 = (pattern: RegExp | string) => string; + type LodashRest = (func: (...args: any[]) => any) => (...args: any[]) => any; + interface LodashRestFrom { + (start: number): LodashRestFrom1x1; + (start: lodash.__, func: (...args: any[]) => any): LodashRestFrom1x2; + (start: number, func: (...args: any[]) => any): (...args: any[]) => any; + } + type LodashRestFrom1x1 = (func: (...args: any[]) => any) => (...args: any[]) => any; + type LodashRestFrom1x2 = (start: number) => (...args: any[]) => any; + interface LodashResult { + (path: lodash.PropertyPath): LodashResult1x1; + (path: lodash.__, object: any): LodashResult1x2; + (path: lodash.PropertyPath, object: any): TResult; + } + type LodashResult1x1 = (object: any) => TResult; + type LodashResult1x2 = (path: lodash.PropertyPath) => TResult; + type LodashReverse = >(array: TList) => TList; + type LodashRound = (n: number) => number; + type LodashRunInContext = (context: object) => lodash.LoDashStatic; + interface LodashSample { + (collection: lodash.List | lodash.Dictionary | lodash.NumericDictionary | null | undefined): T | undefined; + (collection: T | null | undefined): T[keyof T] | undefined; + } + interface LodashSampleSize { + (n: number): LodashSampleSize1x1; + (n: lodash.__, collection: lodash.List | lodash.Dictionary | lodash.NumericDictionary | null | undefined): LodashSampleSize1x2; + (n: number, collection: lodash.List | lodash.Dictionary | lodash.NumericDictionary | null | undefined): T[]; + (n: lodash.__, collection: T | null | undefined): LodashSampleSize2x2; + (n: number, collection: T | null | undefined): Array; + } + interface LodashSampleSize1x1 { + (collection: lodash.List | lodash.Dictionary | lodash.NumericDictionary | null | undefined): T[]; + (collection: T | null | undefined): Array; + } + type LodashSampleSize1x2 = (n: number) => T[]; + type LodashSampleSize2x2 = (n: number) => Array; + interface LodashSetWith { + (customizer: lodash.SetWithCustomizer): LodashSetWith1x1; + (customizer: lodash.__, path: lodash.PropertyPath): LodashSetWith1x2; + (customizer: lodash.SetWithCustomizer, path: lodash.PropertyPath): LodashSetWith1x3; + (customizer: lodash.__, path: lodash.__, value: any): LodashSetWith1x4; + (customizer: lodash.SetWithCustomizer, path: lodash.__, value: any): LodashSetWith1x5; + (customizer: lodash.__, path: lodash.PropertyPath, value: any): LodashSetWith1x6; + (customizer: lodash.SetWithCustomizer, path: lodash.PropertyPath, value: any): LodashSetWith1x7; + (customizer: lodash.__, path: lodash.__, value: lodash.__, object: T): LodashSetWith1x8; + (customizer: lodash.SetWithCustomizer, path: lodash.__, value: lodash.__, object: T): LodashSetWith1x9; + (customizer: lodash.__, path: lodash.PropertyPath, value: lodash.__, object: T): LodashSetWith1x10; + (customizer: lodash.SetWithCustomizer, path: lodash.PropertyPath, value: lodash.__, object: T): LodashSetWith1x11; + (customizer: lodash.__, path: lodash.__, value: any, object: T): LodashSetWith1x12; + (customizer: lodash.SetWithCustomizer, path: lodash.__, value: any, object: T): LodashSetWith1x13; + (customizer: lodash.__, path: lodash.PropertyPath, value: any, object: T): LodashSetWith1x14; + (customizer: lodash.SetWithCustomizer, path: lodash.PropertyPath, value: any, object: T): T; + } + interface LodashSetWith1x1 { + (path: lodash.PropertyPath): LodashSetWith1x3; + (path: lodash.__, value: any): LodashSetWith1x5; + (path: lodash.PropertyPath, value: any): LodashSetWith1x7; + (path: lodash.__, value: lodash.__, object: T): LodashSetWith1x9; + (path: lodash.PropertyPath, value: lodash.__, object: T): LodashSetWith1x11; + (path: lodash.__, value: any, object: T): LodashSetWith1x13; + (path: lodash.PropertyPath, value: any, object: T): T; + } + interface LodashSetWith1x2 { + (customizer: lodash.SetWithCustomizer): LodashSetWith1x3; + (customizer: lodash.__, value: any): LodashSetWith1x6; + (customizer: lodash.SetWithCustomizer, value: any): LodashSetWith1x7; + (customizer: lodash.__, value: lodash.__, object: T): LodashSetWith1x10; + (customizer: lodash.SetWithCustomizer, value: lodash.__, object: T): LodashSetWith1x11; + (customizer: lodash.__, value: any, object: T): LodashSetWith1x14; + (customizer: lodash.SetWithCustomizer, value: any, object: T): T; + } + interface LodashSetWith1x3 { + (value: any): LodashSetWith1x7; + (value: lodash.__, object: T): LodashSetWith1x11; + (value: any, object: T): T; + } + interface LodashSetWith1x4 { + (customizer: lodash.SetWithCustomizer): LodashSetWith1x5; + (customizer: lodash.__, path: lodash.PropertyPath): LodashSetWith1x6; + (customizer: lodash.SetWithCustomizer, path: lodash.PropertyPath): LodashSetWith1x7; + (customizer: lodash.__, path: lodash.__, object: T): LodashSetWith1x12; + (customizer: lodash.SetWithCustomizer, path: lodash.__, object: T): LodashSetWith1x13; + (customizer: lodash.__, path: lodash.PropertyPath, object: T): LodashSetWith1x14; + (customizer: lodash.SetWithCustomizer, path: lodash.PropertyPath, object: T): T; + } + interface LodashSetWith1x5 { + (path: lodash.PropertyPath): LodashSetWith1x7; + (path: lodash.__, object: T): LodashSetWith1x13; + (path: lodash.PropertyPath, object: T): T; + } + interface LodashSetWith1x6 { + (customizer: lodash.SetWithCustomizer): LodashSetWith1x7; + (customizer: lodash.__, object: T): LodashSetWith1x14; + (customizer: lodash.SetWithCustomizer, object: T): T; + } + type LodashSetWith1x7 = (object: T) => T; + interface LodashSetWith1x8 { + (customizer: lodash.SetWithCustomizer): LodashSetWith1x9; + (customizer: lodash.__, path: lodash.PropertyPath): LodashSetWith1x10; + (customizer: lodash.SetWithCustomizer, path: lodash.PropertyPath): LodashSetWith1x11; + (customizer: lodash.__, path: lodash.__, value: any): LodashSetWith1x12; + (customizer: lodash.SetWithCustomizer, path: lodash.__, value: any): LodashSetWith1x13; + (customizer: lodash.__, path: lodash.PropertyPath, value: any): LodashSetWith1x14; + (customizer: lodash.SetWithCustomizer, path: lodash.PropertyPath, value: any): T; + } + interface LodashSetWith1x9 { + (path: lodash.PropertyPath): LodashSetWith1x11; + (path: lodash.__, value: any): LodashSetWith1x13; + (path: lodash.PropertyPath, value: any): T; + } + interface LodashSetWith1x10 { + (customizer: lodash.SetWithCustomizer): LodashSetWith1x11; + (customizer: lodash.__, value: any): LodashSetWith1x14; + (customizer: lodash.SetWithCustomizer, value: any): T; + } + type LodashSetWith1x11 = (value: any) => T; + interface LodashSetWith1x12 { + (customizer: lodash.SetWithCustomizer): LodashSetWith1x13; + (customizer: lodash.__, path: lodash.PropertyPath): LodashSetWith1x14; + (customizer: lodash.SetWithCustomizer, path: lodash.PropertyPath): T; + } + type LodashSetWith1x13 = (path: lodash.PropertyPath) => T; + type LodashSetWith1x14 = (customizer: lodash.SetWithCustomizer) => T; + interface LodashShuffle { + (collection: lodash.List | null | undefined): T[]; + (collection: T | null | undefined): Array; + } + type LodashSize = (collection: object | string | null | undefined) => number; + interface LodashSlice { + (start: number): LodashSlice1x1; + (start: lodash.__, end: number): LodashSlice1x2; + (start: number, end: number): LodashSlice1x3; + (start: lodash.__, end: lodash.__, array: lodash.List | null | undefined): LodashSlice1x4; + (start: number, end: lodash.__, array: lodash.List | null | undefined): LodashSlice1x5; + (start: lodash.__, end: number, array: lodash.List | null | undefined): LodashSlice1x6; + (start: number, end: number, array: lodash.List | null | undefined): T[]; + } + interface LodashSlice1x1 { + (end: number): LodashSlice1x3; + (end: lodash.__, array: lodash.List | null | undefined): LodashSlice1x5; + (end: number, array: lodash.List | null | undefined): T[]; + } + interface LodashSlice1x2 { + (start: number): LodashSlice1x3; + (start: lodash.__, array: lodash.List | null | undefined): LodashSlice1x6; + (start: number, array: lodash.List | null | undefined): T[]; + } + type LodashSlice1x3 = (array: lodash.List | null | undefined) => T[]; + interface LodashSlice1x4 { + (start: number): LodashSlice1x5; + (start: lodash.__, end: number): LodashSlice1x6; + (start: number, end: number): T[]; + } + type LodashSlice1x5 = (end: number) => T[]; + type LodashSlice1x6 = (start: number) => T[]; + type LodashSnakeCase = (string: string) => string; + interface LodashSortBy { + (iteratees: lodash.Many>): LodashSortBy1x1; + (iteratees: lodash.__, collection: lodash.List | null | undefined): LodashSortBy1x2; + (iteratees: lodash.Many>, collection: lodash.List | null | undefined): T[]; + (iteratees: lodash.__, collection: T | null | undefined): LodashSortBy2x2; + (iteratees: lodash.Many>, collection: T | null | undefined): Array; + } + type LodashSortBy1x1 = (collection: lodash.List | object | null | undefined) => T[]; + type LodashSortBy1x2 = (iteratees: lodash.Many>) => T[]; + type LodashSortBy2x2 = (iteratees: lodash.Many>) => Array; + interface LodashSortedIndex { + (value: T): LodashSortedIndex1x1; + (value: lodash.__, array: lodash.List | null | undefined): LodashSortedIndex1x2; + (value: T, array: lodash.List | null | undefined): number; + } + type LodashSortedIndex1x1 = (array: lodash.List | null | undefined) => number; + type LodashSortedIndex1x2 = (value: T) => number; + interface LodashSortedIndexBy { + (iteratee: lodash.ValueIteratee): LodashSortedIndexBy1x1; + (iteratee: lodash.__, value: T): LodashSortedIndexBy1x2; + (iteratee: lodash.ValueIteratee, value: T): LodashSortedIndexBy1x3; + (iteratee: lodash.__, value: lodash.__, array: lodash.List | null | undefined): LodashSortedIndexBy1x4; + (iteratee: lodash.ValueIteratee, value: lodash.__, array: lodash.List | null | undefined): LodashSortedIndexBy1x5; + (iteratee: lodash.__, value: T, array: lodash.List | null | undefined): LodashSortedIndexBy1x6; + (iteratee: lodash.ValueIteratee, value: T, array: lodash.List | null | undefined): number; + } + interface LodashSortedIndexBy1x1 { + (value: T): LodashSortedIndexBy1x3; + (value: lodash.__, array: lodash.List | null | undefined): LodashSortedIndexBy1x5; + (value: T, array: lodash.List | null | undefined): number; + } + interface LodashSortedIndexBy1x2 { + (iteratee: lodash.ValueIteratee): LodashSortedIndexBy1x3; + (iteratee: lodash.__, array: lodash.List | null | undefined): LodashSortedIndexBy1x6; + (iteratee: lodash.ValueIteratee, array: lodash.List | null | undefined): number; + } + type LodashSortedIndexBy1x3 = (array: lodash.List | null | undefined) => number; + interface LodashSortedIndexBy1x4 { + (iteratee: lodash.ValueIteratee): LodashSortedIndexBy1x5; + (iteratee: lodash.__, value: T): LodashSortedIndexBy1x6; + (iteratee: lodash.ValueIteratee, value: T): number; + } + type LodashSortedIndexBy1x5 = (value: T) => number; + type LodashSortedIndexBy1x6 = (iteratee: lodash.ValueIteratee) => number; + interface LodashSortedIndexOf { + (value: T): LodashSortedIndexOf1x1; + (value: lodash.__, array: lodash.List | null | undefined): LodashSortedIndexOf1x2; + (value: T, array: lodash.List | null | undefined): number; + } + type LodashSortedIndexOf1x1 = (array: lodash.List | null | undefined) => number; + type LodashSortedIndexOf1x2 = (value: T) => number; + interface LodashSortedLastIndex { + (value: T): LodashSortedLastIndex1x1; + (value: lodash.__, array: lodash.List | null | undefined): LodashSortedLastIndex1x2; + (value: T, array: lodash.List | null | undefined): number; + } + type LodashSortedLastIndex1x1 = (array: lodash.List | null | undefined) => number; + type LodashSortedLastIndex1x2 = (value: T) => number; + interface LodashSortedLastIndexBy { + (iteratee: lodash.ValueIteratee): LodashSortedLastIndexBy1x1; + (iteratee: lodash.__, value: T): LodashSortedLastIndexBy1x2; + (iteratee: lodash.ValueIteratee, value: T): LodashSortedLastIndexBy1x3; + (iteratee: lodash.__, value: lodash.__, array: lodash.List | null | undefined): LodashSortedLastIndexBy1x4; + (iteratee: lodash.ValueIteratee, value: lodash.__, array: lodash.List | null | undefined): LodashSortedLastIndexBy1x5; + (iteratee: lodash.__, value: T, array: lodash.List | null | undefined): LodashSortedLastIndexBy1x6; + (iteratee: lodash.ValueIteratee, value: T, array: lodash.List | null | undefined): number; + } + interface LodashSortedLastIndexBy1x1 { + (value: T): LodashSortedLastIndexBy1x3; + (value: lodash.__, array: lodash.List | null | undefined): LodashSortedLastIndexBy1x5; + (value: T, array: lodash.List | null | undefined): number; + } + interface LodashSortedLastIndexBy1x2 { + (iteratee: lodash.ValueIteratee): LodashSortedLastIndexBy1x3; + (iteratee: lodash.__, array: lodash.List | null | undefined): LodashSortedLastIndexBy1x6; + (iteratee: lodash.ValueIteratee, array: lodash.List | null | undefined): number; + } + type LodashSortedLastIndexBy1x3 = (array: lodash.List | null | undefined) => number; + interface LodashSortedLastIndexBy1x4 { + (iteratee: lodash.ValueIteratee): LodashSortedLastIndexBy1x5; + (iteratee: lodash.__, value: T): LodashSortedLastIndexBy1x6; + (iteratee: lodash.ValueIteratee, value: T): number; + } + type LodashSortedLastIndexBy1x5 = (value: T) => number; + type LodashSortedLastIndexBy1x6 = (iteratee: lodash.ValueIteratee) => number; + interface LodashSortedLastIndexOf { + (value: T): LodashSortedLastIndexOf1x1; + (value: lodash.__, array: lodash.List | null | undefined): LodashSortedLastIndexOf1x2; + (value: T, array: lodash.List | null | undefined): number; + } + type LodashSortedLastIndexOf1x1 = (array: lodash.List | null | undefined) => number; + type LodashSortedLastIndexOf1x2 = (value: T) => number; + type LodashSortedUniq = (array: lodash.List | null | undefined) => T[]; + interface LodashSortedUniqBy { + (iteratee: lodash.ValueIteratee): LodashSortedUniqBy1x1; + (iteratee: lodash.__, array: lodash.List | null | undefined): LodashSortedUniqBy1x2; + (iteratee: lodash.ValueIteratee, array: lodash.List | null | undefined): T[]; + } + type LodashSortedUniqBy1x1 = (array: lodash.List | null | undefined) => T[]; + type LodashSortedUniqBy1x2 = (iteratee: lodash.ValueIteratee) => T[]; + interface LodashSplit { + (separator: RegExp|string): LodashSplit1x1; + (separator: lodash.__, string: string): LodashSplit1x2; + (separator: RegExp|string, string: string): string[]; + } + type LodashSplit1x1 = (string: string) => string[]; + type LodashSplit1x2 = (separator: RegExp|string) => string[]; + type LodashSpread = (func: (...args: any[]) => TResult) => (...args: any[]) => TResult; + interface LodashSpreadFrom { + (start: number): LodashSpreadFrom1x1; + (start: lodash.__, func: (...args: any[]) => TResult): LodashSpreadFrom1x2; + (start: number, func: (...args: any[]) => TResult): (...args: any[]) => TResult; + } + type LodashSpreadFrom1x1 = (func: (...args: any[]) => TResult) => (...args: any[]) => TResult; + type LodashSpreadFrom1x2 = (start: number) => (...args: any[]) => TResult; + type LodashStartCase = (string: string) => string; + interface LodashStartsWith { + (target: string): LodashStartsWith1x1; + (target: lodash.__, string: string): LodashStartsWith1x2; + (target: string, string: string): boolean; + } + type LodashStartsWith1x1 = (string: string) => boolean; + type LodashStartsWith1x2 = (target: string) => boolean; + type LodashStubArray = () => any[]; + type LodashStubObject = () => any; + type LodashStubString = () => string; + type LodashStubTrue = () => true; + interface LodashSubtract { + (minuend: number): LodashSubtract1x1; + (minuend: lodash.__, subtrahend: number): LodashSubtract1x2; + (minuend: number, subtrahend: number): number; + } + type LodashSubtract1x1 = (subtrahend: number) => number; + type LodashSubtract1x2 = (minuend: number) => number; + type LodashSum = (collection: lodash.List | null | undefined) => number; + interface LodashSumBy { + (iteratee: ((value: T) => number) | string): LodashSumBy1x1; + (iteratee: lodash.__, collection: lodash.List | null | undefined): LodashSumBy1x2; + (iteratee: ((value: T) => number) | string, collection: lodash.List | null | undefined): number; + } + type LodashSumBy1x1 = (collection: lodash.List | null | undefined) => number; + type LodashSumBy1x2 = (iteratee: ((value: T) => number) | string) => number; + interface LodashXor { + (arrays2: lodash.List | null | undefined): LodashXor1x1; + (arrays2: lodash.__, arrays: lodash.List | null | undefined): LodashXor1x2; + (arrays2: lodash.List | null | undefined, arrays: lodash.List | null | undefined): T[]; + } + type LodashXor1x1 = (arrays: lodash.List | null | undefined) => T[]; + type LodashXor1x2 = (arrays2: lodash.List | null | undefined) => T[]; + interface LodashXorBy { + (iteratee: lodash.ValueIteratee): LodashXorBy1x1; + (iteratee: lodash.__, arrays: lodash.List | null | undefined): LodashXorBy1x2; + (iteratee: lodash.ValueIteratee, arrays: lodash.List | null | undefined): LodashXorBy1x3; + (iteratee: lodash.__, arrays: lodash.__, arrays2: lodash.List | null | undefined): LodashXorBy1x4; + (iteratee: lodash.ValueIteratee, arrays: lodash.__, arrays2: lodash.List | null | undefined): LodashXorBy1x5; + (iteratee: lodash.__, arrays: lodash.List | null | undefined, arrays2: lodash.List | null | undefined): LodashXorBy1x6; + (iteratee: lodash.ValueIteratee, arrays: lodash.List | null | undefined, arrays2: lodash.List | null | undefined): T[]; + } + interface LodashXorBy1x1 { + (arrays: lodash.List | null | undefined): LodashXorBy1x3; + (arrays: lodash.__, arrays2: lodash.List | null | undefined): LodashXorBy1x5; + (arrays: lodash.List | null | undefined, arrays2: lodash.List | null | undefined): T[]; + } + interface LodashXorBy1x2 { + (iteratee: lodash.ValueIteratee): LodashXorBy1x3; + (iteratee: lodash.__, arrays2: lodash.List | null | undefined): LodashXorBy1x6; + (iteratee: lodash.ValueIteratee, arrays2: lodash.List | null | undefined): T[]; + } + type LodashXorBy1x3 = (arrays2: lodash.List | null | undefined) => T[]; + interface LodashXorBy1x4 { + (iteratee: lodash.ValueIteratee): LodashXorBy1x5; + (iteratee: lodash.__, arrays: lodash.List | null | undefined): LodashXorBy1x6; + (iteratee: lodash.ValueIteratee, arrays: lodash.List | null | undefined): T[]; + } + type LodashXorBy1x5 = (arrays: lodash.List | null | undefined) => T[]; + type LodashXorBy1x6 = (iteratee: lodash.ValueIteratee) => T[]; + interface LodashXorWith { + (comparator: lodash.Comparator): LodashXorWith1x1; + (comparator: lodash.__, arrays: lodash.List | null | undefined): LodashXorWith1x2; + (comparator: lodash.Comparator, arrays: lodash.List | null | undefined): LodashXorWith1x3; + (comparator: lodash.__, arrays: lodash.__, arrays2: lodash.List | null | undefined): LodashXorWith1x4; + (comparator: lodash.Comparator, arrays: lodash.__, arrays2: lodash.List | null | undefined): LodashXorWith1x5; + (comparator: lodash.__, arrays: lodash.List | null | undefined, arrays2: lodash.List | null | undefined): LodashXorWith1x6; + (comparator: lodash.Comparator, arrays: lodash.List | null | undefined, arrays2: lodash.List | null | undefined): T[]; + } + interface LodashXorWith1x1 { + (arrays: lodash.List | null | undefined): LodashXorWith1x3; + (arrays: lodash.__, arrays2: lodash.List | null | undefined): LodashXorWith1x5; + (arrays: lodash.List | null | undefined, arrays2: lodash.List | null | undefined): T[]; + } + interface LodashXorWith1x2 { + (comparator: lodash.Comparator): LodashXorWith1x3; + (comparator: lodash.__, arrays2: lodash.List | null | undefined): LodashXorWith1x6; + (comparator: lodash.Comparator, arrays2: lodash.List | null | undefined): T[]; + } + type LodashXorWith1x3 = (arrays2: lodash.List | null | undefined) => T[]; + interface LodashXorWith1x4 { + (comparator: lodash.Comparator): LodashXorWith1x5; + (comparator: lodash.__, arrays: lodash.List | null | undefined): LodashXorWith1x6; + (comparator: lodash.Comparator, arrays: lodash.List | null | undefined): T[]; + } + type LodashXorWith1x5 = (arrays: lodash.List | null | undefined) => T[]; + type LodashXorWith1x6 = (comparator: lodash.Comparator) => T[]; + type LodashTail = (array: lodash.List | null | undefined) => T[]; + interface LodashTake { + (n: number): LodashTake1x1; + (n: lodash.__, array: lodash.List | null | undefined): LodashTake1x2; + (n: number, array: lodash.List | null | undefined): T[]; + } + type LodashTake1x1 = (array: lodash.List | null | undefined) => T[]; + type LodashTake1x2 = (n: number) => T[]; + interface LodashTakeRight { + (n: number): LodashTakeRight1x1; + (n: lodash.__, array: lodash.List | null | undefined): LodashTakeRight1x2; + (n: number, array: lodash.List | null | undefined): T[]; + } + type LodashTakeRight1x1 = (array: lodash.List | null | undefined) => T[]; + type LodashTakeRight1x2 = (n: number) => T[]; + interface LodashTakeRightWhile { + (predicate: lodash.ValueIteratee): LodashTakeRightWhile1x1; + (predicate: lodash.__, array: lodash.List | null | undefined): LodashTakeRightWhile1x2; + (predicate: lodash.ValueIteratee, array: lodash.List | null | undefined): T[]; + } + type LodashTakeRightWhile1x1 = (array: lodash.List | null | undefined) => T[]; + type LodashTakeRightWhile1x2 = (predicate: lodash.ValueIteratee) => T[]; + interface LodashTakeWhile { + (predicate: lodash.ValueIteratee): LodashTakeWhile1x1; + (predicate: lodash.__, array: lodash.List | null | undefined): LodashTakeWhile1x2; + (predicate: lodash.ValueIteratee, array: lodash.List | null | undefined): T[]; + } + type LodashTakeWhile1x1 = (array: lodash.List | null | undefined) => T[]; + type LodashTakeWhile1x2 = (predicate: lodash.ValueIteratee) => T[]; + interface LodashTap { + (interceptor: (value: T) => void): LodashTap1x1; + (interceptor: lodash.__, value: T): LodashTap1x2; + (interceptor: (value: T) => void, value: T): T; + } + type LodashTap1x1 = (value: T) => T; + type LodashTap1x2 = (interceptor: (value: T) => void) => T; + type LodashTemplate = (string: string) => lodash.TemplateExecutor; + interface LodashThrottle { + (wait: number): LodashThrottle1x1; + any>(wait: lodash.__, func: T): LodashThrottle1x2; + any>(wait: number, func: T): T & lodash.Cancelable; + } + type LodashThrottle1x1 = any>(func: T) => T & lodash.Cancelable; + type LodashThrottle1x2 = (wait: number) => T & lodash.Cancelable; + interface LodashThru { + (interceptor: (value: T) => TResult): LodashThru1x1; + (interceptor: lodash.__, value: T): LodashThru1x2; + (interceptor: (value: T) => TResult, value: T): TResult; + } + type LodashThru1x1 = (value: T) => TResult; + type LodashThru1x2 = (interceptor: (value: T) => TResult) => TResult; + interface LodashTimes { + (iteratee: (num: number) => TResult): LodashTimes1x1; + (iteratee: lodash.__, n: number): LodashTimes1x2; + (iteratee: (num: number) => TResult, n: number): TResult[]; + } + type LodashTimes1x1 = (n: number) => TResult[]; + type LodashTimes1x2 = (iteratee: (num: number) => TResult) => TResult[]; + interface LodashToArray { + (value: lodash.List | lodash.Dictionary | lodash.NumericDictionary | null | undefined): T[]; + (value: T): Array; + (): any[]; + } + type LodashToFinite = (value: any) => number; + type LodashToInteger = (value: any) => number; + type LodashToLength = (value: any) => number; + type LodashToLower = (string: string) => string; + type LodashToNumber = (value: any) => number; + type LodashToPath = (value: any) => string[]; + type LodashToPlainObject = (value: any) => any; + type LodashToSafeInteger = (value: any) => number; + type LodashToString = (value: any) => string; + type LodashToUpper = (string: string) => string; + interface LodashTransform { + (iteratee: lodash.MemoVoidIteratorCapped): LodashTransform1x1; + (iteratee: lodash.__, accumulator: ReadonlyArray): LodashTransform1x2; + (iteratee: lodash.MemoVoidIteratorCapped, accumulator: ReadonlyArray): LodashTransform1x3; + (iteratee: lodash.__, accumulator: lodash.__, object: ReadonlyArray): LodashTransform1x4; + (iteratee: lodash.MemoVoidIteratorCapped, accumulator: lodash.__, object: ReadonlyArray): LodashTransform1x5; + (iteratee: lodash.__, accumulator: ReadonlyArray, object: ReadonlyArray): LodashTransform1x6; + (iteratee: lodash.MemoVoidIteratorCapped, accumulator: ReadonlyArray, object: ReadonlyArray | lodash.Dictionary): TResult[]; + (iteratee: lodash.MemoVoidIteratorCapped>): LodashTransform2x1; + (iteratee: lodash.__, accumulator: lodash.Dictionary): LodashTransform2x2; + (iteratee: lodash.MemoVoidIteratorCapped>, accumulator: lodash.Dictionary): LodashTransform2x3; + (iteratee: lodash.MemoVoidIteratorCapped>, accumulator: lodash.__, object: ReadonlyArray): LodashTransform2x5; + (iteratee: lodash.__, accumulator: lodash.Dictionary, object: ReadonlyArray): LodashTransform2x6; + (iteratee: lodash.MemoVoidIteratorCapped>, accumulator: lodash.Dictionary, object: ReadonlyArray | lodash.Dictionary): lodash.Dictionary; + (iteratee: lodash.__, accumulator: lodash.__, object: lodash.Dictionary): LodashTransform3x4; + (iteratee: lodash.MemoVoidIteratorCapped>, accumulator: lodash.__, object: lodash.Dictionary): LodashTransform3x5; + (iteratee: lodash.__, accumulator: lodash.Dictionary, object: lodash.Dictionary): LodashTransform3x6; + (iteratee: lodash.MemoVoidIteratorCapped, accumulator: lodash.__, object: lodash.Dictionary): LodashTransform4x5; + (iteratee: lodash.__, accumulator: ReadonlyArray, object: lodash.Dictionary): LodashTransform4x6; + } + interface LodashTransform1x1 { + (accumulator: ReadonlyArray): LodashTransform1x3; + (accumulator: lodash.__, object: ReadonlyArray): LodashTransform1x5; + (accumulator: ReadonlyArray, object: ReadonlyArray | lodash.Dictionary): TResult[]; + (accumulator: lodash.__, object: lodash.Dictionary): LodashTransform4x5; + } + interface LodashTransform1x2 { + (iteratee: lodash.MemoVoidIteratorCapped): LodashTransform1x3; + (iteratee: lodash.__, object: ReadonlyArray): LodashTransform1x6; + (iteratee: lodash.MemoVoidIteratorCapped, object: ReadonlyArray | lodash.Dictionary): TResult[]; + (iteratee: lodash.__, object: lodash.Dictionary): LodashTransform4x6; + } + type LodashTransform1x3 = (object: ReadonlyArray | lodash.Dictionary) => TResult[]; + interface LodashTransform1x4 { + (iteratee: lodash.MemoVoidIteratorCapped): LodashTransform1x5; + (iteratee: lodash.__, accumulator: ReadonlyArray): LodashTransform1x6; + (iteratee: lodash.MemoVoidIteratorCapped, accumulator: ReadonlyArray): TResult[]; + (iteratee: lodash.MemoVoidIteratorCapped>): LodashTransform2x5; + (iteratee: lodash.__, accumulator: lodash.Dictionary): LodashTransform2x6; + (iteratee: lodash.MemoVoidIteratorCapped>, accumulator: lodash.Dictionary): lodash.Dictionary; + } + type LodashTransform1x5 = (accumulator: ReadonlyArray) => TResult[]; + type LodashTransform1x6 = (iteratee: lodash.MemoVoidIteratorCapped) => TResult[]; + interface LodashTransform2x1 { + (accumulator: lodash.Dictionary): LodashTransform2x3; + (accumulator: lodash.__, object: ReadonlyArray): LodashTransform2x5; + (accumulator: lodash.Dictionary, object: ReadonlyArray | lodash.Dictionary): lodash.Dictionary; + (accumulator: lodash.__, object: lodash.Dictionary): LodashTransform3x5; + } + interface LodashTransform2x2 { + (iteratee: lodash.MemoVoidIteratorCapped>): LodashTransform2x3; + (iteratee: lodash.__, object: ReadonlyArray): LodashTransform2x6; + (iteratee: lodash.MemoVoidIteratorCapped>, object: ReadonlyArray | lodash.Dictionary): lodash.Dictionary; + (iteratee: lodash.__, object: lodash.Dictionary): LodashTransform3x6; + } + type LodashTransform2x3 = (object: ReadonlyArray | lodash.Dictionary) => lodash.Dictionary; + type LodashTransform2x5 = (accumulator: lodash.Dictionary) => lodash.Dictionary; + type LodashTransform2x6 = (iteratee: lodash.MemoVoidIteratorCapped>) => lodash.Dictionary; + interface LodashTransform3x4 { + (iteratee: lodash.MemoVoidIteratorCapped>): LodashTransform3x5; + (iteratee: lodash.__, accumulator: lodash.Dictionary): LodashTransform3x6; + (iteratee: lodash.MemoVoidIteratorCapped>, accumulator: lodash.Dictionary): lodash.Dictionary; + (iteratee: lodash.MemoVoidIteratorCapped): LodashTransform4x5; + (iteratee: lodash.__, accumulator: ReadonlyArray): LodashTransform4x6; + (iteratee: lodash.MemoVoidIteratorCapped, accumulator: ReadonlyArray): TResult[]; + } + type LodashTransform3x5 = (accumulator: lodash.Dictionary) => lodash.Dictionary; + type LodashTransform3x6 = (iteratee: lodash.MemoVoidIteratorCapped>) => lodash.Dictionary; + type LodashTransform4x5 = (accumulator: ReadonlyArray) => TResult[]; + type LodashTransform4x6 = (iteratee: lodash.MemoVoidIteratorCapped) => TResult[]; + type LodashTrim = (string: string) => string; + interface LodashTrimChars { + (chars: string): LodashTrimChars1x1; + (chars: lodash.__, string: string): LodashTrimChars1x2; + (chars: string, string: string): string; + } + type LodashTrimChars1x1 = (string: string) => string; + type LodashTrimChars1x2 = (chars: string) => string; + interface LodashTrimCharsEnd { + (chars: string): LodashTrimCharsEnd1x1; + (chars: lodash.__, string: string): LodashTrimCharsEnd1x2; + (chars: string, string: string): string; + } + type LodashTrimCharsEnd1x1 = (string: string) => string; + type LodashTrimCharsEnd1x2 = (chars: string) => string; + interface LodashTrimCharsStart { + (chars: string): LodashTrimCharsStart1x1; + (chars: lodash.__, string: string): LodashTrimCharsStart1x2; + (chars: string, string: string): string; + } + type LodashTrimCharsStart1x1 = (string: string) => string; + type LodashTrimCharsStart1x2 = (chars: string) => string; + type LodashTrimEnd = (string: string) => string; + type LodashTrimStart = (string: string) => string; + interface LodashTruncate { + (options: lodash.TruncateOptions): LodashTruncate1x1; + (options: lodash.__, string: string): LodashTruncate1x2; + (options: lodash.TruncateOptions, string: string): string; + } + type LodashTruncate1x1 = (string: string) => string; + type LodashTruncate1x2 = (options: lodash.TruncateOptions) => string; + type LodashUnapply = (func: (...args: any[]) => any) => (...args: any[]) => any; + type LodashUnary = (func: (arg1: T, ...args: any[]) => TResult) => (arg1: T) => TResult; + type LodashUnescape = (string: string) => string; + interface LodashUnion { + (arrays2: lodash.List | null | undefined): LodashUnion1x1; + (arrays2: lodash.__, arrays: lodash.List | null | undefined): LodashUnion1x2; + (arrays2: lodash.List | null | undefined, arrays: lodash.List | null | undefined): T[]; + } + type LodashUnion1x1 = (arrays: lodash.List | null | undefined) => T[]; + type LodashUnion1x2 = (arrays2: lodash.List | null | undefined) => T[]; + interface LodashUnionBy { + (iteratee: lodash.ValueIteratee): LodashUnionBy1x1; + (iteratee: lodash.__, arrays1: lodash.List | null | undefined): LodashUnionBy1x2; + (iteratee: lodash.ValueIteratee, arrays1: lodash.List | null | undefined): LodashUnionBy1x3; + (iteratee: lodash.__, arrays1: lodash.__, arrays2: lodash.List | null | undefined): LodashUnionBy1x4; + (iteratee: lodash.ValueIteratee, arrays1: lodash.__, arrays2: lodash.List | null | undefined): LodashUnionBy1x5; + (iteratee: lodash.__, arrays1: lodash.List | null | undefined, arrays2: lodash.List | null | undefined): LodashUnionBy1x6; + (iteratee: lodash.ValueIteratee, arrays1: lodash.List | null | undefined, arrays2: lodash.List | null | undefined): T[]; + } + interface LodashUnionBy1x1 { + (arrays1: lodash.List | null | undefined): LodashUnionBy1x3; + (arrays1: lodash.__, arrays2: lodash.List | null | undefined): LodashUnionBy1x5; + (arrays1: lodash.List | null | undefined, arrays2: lodash.List | null | undefined): T[]; + } + interface LodashUnionBy1x2 { + (iteratee: lodash.ValueIteratee): LodashUnionBy1x3; + (iteratee: lodash.__, arrays2: lodash.List | null | undefined): LodashUnionBy1x6; + (iteratee: lodash.ValueIteratee, arrays2: lodash.List | null | undefined): T[]; + } + type LodashUnionBy1x3 = (arrays2: lodash.List | null | undefined) => T[]; + interface LodashUnionBy1x4 { + (iteratee: lodash.ValueIteratee): LodashUnionBy1x5; + (iteratee: lodash.__, arrays1: lodash.List | null | undefined): LodashUnionBy1x6; + (iteratee: lodash.ValueIteratee, arrays1: lodash.List | null | undefined): T[]; + } + type LodashUnionBy1x5 = (arrays1: lodash.List | null | undefined) => T[]; + type LodashUnionBy1x6 = (iteratee: lodash.ValueIteratee) => T[]; + interface LodashUnionWith { + (comparator: lodash.Comparator): LodashUnionWith1x1; + (comparator: lodash.__, arrays: lodash.List | null | undefined): LodashUnionWith1x2; + (comparator: lodash.Comparator, arrays: lodash.List | null | undefined): LodashUnionWith1x3; + (comparator: lodash.__, arrays: lodash.__, arrays2: lodash.List | null | undefined): LodashUnionWith1x4; + (comparator: lodash.Comparator, arrays: lodash.__, arrays2: lodash.List | null | undefined): LodashUnionWith1x5; + (comparator: lodash.__, arrays: lodash.List | null | undefined, arrays2: lodash.List | null | undefined): LodashUnionWith1x6; + (comparator: lodash.Comparator, arrays: lodash.List | null | undefined, arrays2: lodash.List | null | undefined): T[]; + } + interface LodashUnionWith1x1 { + (arrays: lodash.List | null | undefined): LodashUnionWith1x3; + (arrays: lodash.__, arrays2: lodash.List | null | undefined): LodashUnionWith1x5; + (arrays: lodash.List | null | undefined, arrays2: lodash.List | null | undefined): T[]; + } + interface LodashUnionWith1x2 { + (comparator: lodash.Comparator): LodashUnionWith1x3; + (comparator: lodash.__, arrays2: lodash.List | null | undefined): LodashUnionWith1x6; + (comparator: lodash.Comparator, arrays2: lodash.List | null | undefined): T[]; + } + type LodashUnionWith1x3 = (arrays2: lodash.List | null | undefined) => T[]; + interface LodashUnionWith1x4 { + (comparator: lodash.Comparator): LodashUnionWith1x5; + (comparator: lodash.__, arrays: lodash.List | null | undefined): LodashUnionWith1x6; + (comparator: lodash.Comparator, arrays: lodash.List | null | undefined): T[]; + } + type LodashUnionWith1x5 = (arrays: lodash.List | null | undefined) => T[]; + type LodashUnionWith1x6 = (comparator: lodash.Comparator) => T[]; + type LodashUniq = (array: lodash.List | null | undefined) => T[]; + interface LodashUniqBy { + (iteratee: lodash.ValueIteratee): LodashUniqBy1x1; + (iteratee: lodash.__, array: lodash.List | null | undefined): LodashUniqBy1x2; + (iteratee: lodash.ValueIteratee, array: lodash.List | null | undefined): T[]; + } + type LodashUniqBy1x1 = (array: lodash.List | null | undefined) => T[]; + type LodashUniqBy1x2 = (iteratee: lodash.ValueIteratee) => T[]; + type LodashUniqueId = (prefix: string) => string; + interface LodashUniqWith { + (comparator: lodash.Comparator): LodashUniqWith1x1; + (comparator: lodash.__, array: lodash.List | null | undefined): LodashUniqWith1x2; + (comparator: lodash.Comparator, array: lodash.List | null | undefined): T[]; + } + type LodashUniqWith1x1 = (array: lodash.List | null | undefined) => T[]; + type LodashUniqWith1x2 = (comparator: lodash.Comparator) => T[]; + type LodashUnzip = (array: T[][] | lodash.List> | null | undefined) => T[][]; + interface LodashUnzipWith { + (iteratee: (...values: T[]) => TResult): LodashUnzipWith1x1; + (iteratee: lodash.__, array: lodash.List> | null | undefined): LodashUnzipWith1x2; + (iteratee: (...values: T[]) => TResult, array: lodash.List> | null | undefined): TResult[]; + } + type LodashUnzipWith1x1 = (array: lodash.List> | null | undefined) => TResult[]; + type LodashUnzipWith1x2 = (iteratee: (...values: T[]) => TResult) => TResult[]; + interface LodashUpdate { + (path: lodash.PropertyPath): LodashUpdate1x1; + (path: lodash.__, updater: (value: any) => any): LodashUpdate1x2; + (path: lodash.PropertyPath, updater: (value: any) => any): LodashUpdate1x3; + (path: lodash.__, updater: lodash.__, object: object): LodashUpdate1x4; + (path: lodash.PropertyPath, updater: lodash.__, object: object): LodashUpdate1x5; + (path: lodash.__, updater: (value: any) => any, object: object): LodashUpdate1x6; + (path: lodash.PropertyPath, updater: (value: any) => any, object: object): any; + } + interface LodashUpdate1x1 { + (updater: (value: any) => any): LodashUpdate1x3; + (updater: lodash.__, object: object): LodashUpdate1x5; + (updater: (value: any) => any, object: object): any; + } + interface LodashUpdate1x2 { + (path: lodash.PropertyPath): LodashUpdate1x3; + (path: lodash.__, object: object): LodashUpdate1x6; + (path: lodash.PropertyPath, object: object): any; + } + type LodashUpdate1x3 = (object: object) => any; + interface LodashUpdate1x4 { + (path: lodash.PropertyPath): LodashUpdate1x5; + (path: lodash.__, updater: (value: any) => any): LodashUpdate1x6; + (path: lodash.PropertyPath, updater: (value: any) => any): any; + } + type LodashUpdate1x5 = (updater: (value: any) => any) => any; + type LodashUpdate1x6 = (path: lodash.PropertyPath) => any; + interface LodashUpdateWith { + (customizer: lodash.SetWithCustomizer): LodashUpdateWith1x1; + (customizer: lodash.__, path: lodash.PropertyPath): LodashUpdateWith1x2; + (customizer: lodash.SetWithCustomizer, path: lodash.PropertyPath): LodashUpdateWith1x3; + (customizer: lodash.__, path: lodash.__, updater: (oldValue: any) => any): LodashUpdateWith1x4; + (customizer: lodash.SetWithCustomizer, path: lodash.__, updater: (oldValue: any) => any): LodashUpdateWith1x5; + (customizer: lodash.__, path: lodash.PropertyPath, updater: (oldValue: any) => any): LodashUpdateWith1x6; + (customizer: lodash.SetWithCustomizer, path: lodash.PropertyPath, updater: (oldValue: any) => any): LodashUpdateWith1x7; + (customizer: lodash.__, path: lodash.__, updater: lodash.__, object: T): LodashUpdateWith1x8; + (customizer: lodash.SetWithCustomizer, path: lodash.__, updater: lodash.__, object: T): LodashUpdateWith1x9; + (customizer: lodash.__, path: lodash.PropertyPath, updater: lodash.__, object: T): LodashUpdateWith1x10; + (customizer: lodash.SetWithCustomizer, path: lodash.PropertyPath, updater: lodash.__, object: T): LodashUpdateWith1x11; + (customizer: lodash.__, path: lodash.__, updater: (oldValue: any) => any, object: T): LodashUpdateWith1x12; + (customizer: lodash.SetWithCustomizer, path: lodash.__, updater: (oldValue: any) => any, object: T): LodashUpdateWith1x13; + (customizer: lodash.__, path: lodash.PropertyPath, updater: (oldValue: any) => any, object: T): LodashUpdateWith1x14; + (customizer: lodash.SetWithCustomizer, path: lodash.PropertyPath, updater: (oldValue: any) => any, object: T): T; + } + interface LodashUpdateWith1x1 { + (path: lodash.PropertyPath): LodashUpdateWith1x3; + (path: lodash.__, updater: (oldValue: any) => any): LodashUpdateWith1x5; + (path: lodash.PropertyPath, updater: (oldValue: any) => any): LodashUpdateWith1x7; + (path: lodash.__, updater: lodash.__, object: T): LodashUpdateWith1x9; + (path: lodash.PropertyPath, updater: lodash.__, object: T): LodashUpdateWith1x11; + (path: lodash.__, updater: (oldValue: any) => any, object: T): LodashUpdateWith1x13; + (path: lodash.PropertyPath, updater: (oldValue: any) => any, object: T): T; + } + interface LodashUpdateWith1x2 { + (customizer: lodash.SetWithCustomizer): LodashUpdateWith1x3; + (customizer: lodash.__, updater: (oldValue: any) => any): LodashUpdateWith1x6; + (customizer: lodash.SetWithCustomizer, updater: (oldValue: any) => any): LodashUpdateWith1x7; + (customizer: lodash.__, updater: lodash.__, object: T): LodashUpdateWith1x10; + (customizer: lodash.SetWithCustomizer, updater: lodash.__, object: T): LodashUpdateWith1x11; + (customizer: lodash.__, updater: (oldValue: any) => any, object: T): LodashUpdateWith1x14; + (customizer: lodash.SetWithCustomizer, updater: (oldValue: any) => any, object: T): T; + } + interface LodashUpdateWith1x3 { + (updater: (oldValue: any) => any): LodashUpdateWith1x7; + (updater: lodash.__, object: T): LodashUpdateWith1x11; + (updater: (oldValue: any) => any, object: T): T; + } + interface LodashUpdateWith1x4 { + (customizer: lodash.SetWithCustomizer): LodashUpdateWith1x5; + (customizer: lodash.__, path: lodash.PropertyPath): LodashUpdateWith1x6; + (customizer: lodash.SetWithCustomizer, path: lodash.PropertyPath): LodashUpdateWith1x7; + (customizer: lodash.__, path: lodash.__, object: T): LodashUpdateWith1x12; + (customizer: lodash.SetWithCustomizer, path: lodash.__, object: T): LodashUpdateWith1x13; + (customizer: lodash.__, path: lodash.PropertyPath, object: T): LodashUpdateWith1x14; + (customizer: lodash.SetWithCustomizer, path: lodash.PropertyPath, object: T): T; + } + interface LodashUpdateWith1x5 { + (path: lodash.PropertyPath): LodashUpdateWith1x7; + (path: lodash.__, object: T): LodashUpdateWith1x13; + (path: lodash.PropertyPath, object: T): T; + } + interface LodashUpdateWith1x6 { + (customizer: lodash.SetWithCustomizer): LodashUpdateWith1x7; + (customizer: lodash.__, object: T): LodashUpdateWith1x14; + (customizer: lodash.SetWithCustomizer, object: T): T; + } + type LodashUpdateWith1x7 = (object: T) => T; + interface LodashUpdateWith1x8 { + (customizer: lodash.SetWithCustomizer): LodashUpdateWith1x9; + (customizer: lodash.__, path: lodash.PropertyPath): LodashUpdateWith1x10; + (customizer: lodash.SetWithCustomizer, path: lodash.PropertyPath): LodashUpdateWith1x11; + (customizer: lodash.__, path: lodash.__, updater: (oldValue: any) => any): LodashUpdateWith1x12; + (customizer: lodash.SetWithCustomizer, path: lodash.__, updater: (oldValue: any) => any): LodashUpdateWith1x13; + (customizer: lodash.__, path: lodash.PropertyPath, updater: (oldValue: any) => any): LodashUpdateWith1x14; + (customizer: lodash.SetWithCustomizer, path: lodash.PropertyPath, updater: (oldValue: any) => any): T; + } + interface LodashUpdateWith1x9 { + (path: lodash.PropertyPath): LodashUpdateWith1x11; + (path: lodash.__, updater: (oldValue: any) => any): LodashUpdateWith1x13; + (path: lodash.PropertyPath, updater: (oldValue: any) => any): T; + } + interface LodashUpdateWith1x10 { + (customizer: lodash.SetWithCustomizer): LodashUpdateWith1x11; + (customizer: lodash.__, updater: (oldValue: any) => any): LodashUpdateWith1x14; + (customizer: lodash.SetWithCustomizer, updater: (oldValue: any) => any): T; + } + type LodashUpdateWith1x11 = (updater: (oldValue: any) => any) => T; + interface LodashUpdateWith1x12 { + (customizer: lodash.SetWithCustomizer): LodashUpdateWith1x13; + (customizer: lodash.__, path: lodash.PropertyPath): LodashUpdateWith1x14; + (customizer: lodash.SetWithCustomizer, path: lodash.PropertyPath): T; + } + type LodashUpdateWith1x13 = (path: lodash.PropertyPath) => T; + type LodashUpdateWith1x14 = (customizer: lodash.SetWithCustomizer) => T; + type LodashUpperCase = (string: string) => string; + type LodashUpperFirst = (string: string) => string; + interface LodashValues { + (object: lodash.Dictionary | lodash.NumericDictionary | lodash.List | null | undefined): T[]; + (object: T | null | undefined): Array; + (object: any): any[]; + } + interface LodashValuesIn { + (object: lodash.Dictionary|lodash.NumericDictionary|lodash.List | null | undefined): T[]; + (object: T | null | undefined): Array; + } + interface LodashWithout { + (values: ReadonlyArray): LodashWithout1x1; + (values: lodash.__, array: lodash.List | null | undefined): LodashWithout1x2; + (values: ReadonlyArray, array: lodash.List | null | undefined): T[]; + } + type LodashWithout1x1 = (array: lodash.List | null | undefined) => T[]; + type LodashWithout1x2 = (values: ReadonlyArray) => T[]; + type LodashWords = (string: string) => string[]; + interface LodashWrap { + (wrapper: (value: T, ...args: TArgs[]) => TResult): LodashWrap1x1; + (wrapper: lodash.__, value: T): LodashWrap1x2; + (wrapper: (value: T, ...args: TArgs[]) => TResult, value: T): (...args: TArgs[]) => TResult; + (wrapper: (value: T, ...args: any[]) => TResult): LodashWrap2x1; + (wrapper: (value: T, ...args: any[]) => TResult, value: T): (...args: any[]) => TResult; + } + type LodashWrap1x1 = (value: T) => (...args: TArgs[]) => TResult; + interface LodashWrap1x2 { + (wrapper: (value: T, ...args: TArgs[]) => TResult): (...args: TArgs[]) => TResult; + (wrapper: (value: T, ...args: any[]) => TResult): (...args: any[]) => TResult; + } + type LodashWrap2x1 = (value: T) => (...args: any[]) => TResult; + interface LodashZip { + (arrays1: lodash.List): LodashZip1x1; + (arrays1: lodash.__, arrays2: lodash.List): LodashZip1x2; + (arrays1: lodash.List, arrays2: lodash.List): Array<[T1 | undefined, T2 | undefined]>; + } + type LodashZip1x1 = (arrays2: lodash.List) => Array<[T1 | undefined, T2 | undefined]>; + type LodashZip1x2 = (arrays1: lodash.List) => Array<[T1 | undefined, T2 | undefined]>; + interface LodashZipAll { + (arrays1: [lodash.List, lodash.List]): Array<[T1 | undefined, T2 | undefined]>; + (arrays1: [lodash.List, lodash.List, lodash.List]): Array<[T1 | undefined, T2 | undefined, T3 | undefined]>; + (arrays1: [lodash.List, lodash.List, lodash.List, lodash.List]): Array<[T1 | undefined, T2 | undefined, T3 | undefined, T4 | undefined]>; + (arrays1: [lodash.List, lodash.List, lodash.List, lodash.List, lodash.List]): Array<[T1 | undefined, T2 | undefined, T3 | undefined, T4 | undefined, T5 | undefined]>; + (arrays: ReadonlyArray | null | undefined>): Array>; + } + interface LodashZipObject { + (props: lodash.List): LodashZipObject1x1; + (props: lodash.__, values: lodash.List): LodashZipObject1x2; + (props: lodash.List, values: lodash.List): lodash.Dictionary; + } + type LodashZipObject1x1 = (values: lodash.List) => lodash.Dictionary; + type LodashZipObject1x2 = (props: lodash.List) => lodash.Dictionary; + interface LodashZipObjectDeep { + (paths: lodash.List): LodashZipObjectDeep1x1; + (paths: lodash.__, values: lodash.List): LodashZipObjectDeep1x2; + (paths: lodash.List, values: lodash.List): object; + } + type LodashZipObjectDeep1x1 = (values: lodash.List) => object; + type LodashZipObjectDeep1x2 = (paths: lodash.List) => object; + interface LodashZipWith { + (iteratee: (value1: T1, value2: T2) => TResult): LodashZipWith1x1; + (iteratee: lodash.__, arrays1: lodash.List): LodashZipWith1x2; + (iteratee: (value1: T1, value2: T2) => TResult, arrays1: lodash.List): LodashZipWith1x3; + (iteratee: lodash.__, arrays1: lodash.__, arrays2: lodash.List): LodashZipWith1x4; + (iteratee: (value1: T1, value2: T2) => TResult, arrays1: lodash.__, arrays2: lodash.List): LodashZipWith1x5; + (iteratee: lodash.__, arrays1: lodash.List, arrays2: lodash.List): LodashZipWith1x6; + (iteratee: (value1: T1, value2: T2) => TResult, arrays1: lodash.List, arrays2: lodash.List): TResult[]; + } + interface LodashZipWith1x1 { + (arrays1: lodash.List): LodashZipWith1x3; + (arrays1: lodash.__, arrays2: lodash.List): LodashZipWith1x5; + (arrays1: lodash.List, arrays2: lodash.List): TResult[]; + } + interface LodashZipWith1x2 { + (iteratee: (value1: T1, value2: T2) => TResult): LodashZipWith1x3; + (iteratee: lodash.__, arrays2: lodash.List): LodashZipWith1x6; + (iteratee: (value1: T1, value2: T2) => TResult, arrays2: lodash.List): TResult[]; + } + type LodashZipWith1x3 = (arrays2: lodash.List) => TResult[]; + interface LodashZipWith1x4 { + (iteratee: (value1: T1, value2: T2) => TResult): LodashZipWith1x5; + (iteratee: lodash.__, arrays1: lodash.List): LodashZipWith1x6; + (iteratee: (value1: T1, value2: T2) => TResult, arrays1: lodash.List): TResult[]; + } + type LodashZipWith1x5 = (arrays1: lodash.List) => TResult[]; + type LodashZipWith1x6 = (iteratee: (value1: T1, value2: T2) => TResult) => TResult[]; + + interface LoDashFp { + add: LodashAdd; + after: LodashAfter; + all: LodashEvery; + allPass: LodashOverEvery; + always: LodashConstant; + any: LodashSome; + anyPass: LodashOverSome; + apply: LodashApply; + ary: LodashAry; + assign: LodashAssign; + assignAll: LodashAssignAll; + assignAllWith: LodashAssignAllWith; + assignIn: LodashAssignIn; + assignInAll: LodashAssignInAll; + assignInAllWith: LodashAssignInAllWith; + assignInWith: LodashAssignInWith; + assignWith: LodashAssignWith; + assoc: LodashSet; + assocPath: LodashSet; + at: LodashAt; + attempt: LodashAttempt; + before: LodashBefore; + bind: LodashBind; + bindAll: LodashBindAll; + bindKey: LodashBindKey; + camelCase: LodashCamelCase; + capitalize: LodashCapitalize; + castArray: LodashCastArray; + ceil: LodashCeil; + chunk: LodashChunk; + clamp: LodashClamp; + clone: LodashClone; + cloneDeep: LodashCloneDeep; + cloneDeepWith: LodashCloneDeepWith; + cloneWith: LodashCloneWith; + compact: LodashCompact; + complement: LodashNegate; + compose: LodashFlowRight; + concat: LodashConcat; + cond: LodashCond; + conforms: LodashConformsTo; + conformsTo: LodashConformsTo; + constant: LodashConstant; + contains: LodashContains; + countBy: LodashCountBy; + create: LodashCreate; + curry: LodashCurry; + curryN: LodashCurryN; + curryRight: LodashCurryRight; + curryRightN: LodashCurryRightN; + debounce: LodashDebounce; + deburr: LodashDeburr; + defaults: LodashDefaults; + defaultsAll: LodashDefaultsAll; + defaultsDeep: LodashDefaultsDeep; + defaultsDeepAll: LodashDefaultsDeepAll; + defaultTo: LodashDefaultTo; + defer: LodashDefer; + delay: LodashDelay; + difference: LodashDifference; + differenceBy: LodashDifferenceBy; + differenceWith: LodashDifferenceWith; + dissoc: LodashUnset; + dissocPath: LodashUnset; + divide: LodashDivide; + drop: LodashDrop; + dropLast: LodashDropRight; + dropLastWhile: LodashDropRightWhile; + dropRight: LodashDropRight; + dropRightWhile: LodashDropRightWhile; + dropWhile: LodashDropWhile; + each: LodashForEach; + eachRight: LodashForEachRight; + endsWith: LodashEndsWith; + entries: LodashToPairs; + entriesIn: LodashToPairsIn; + eq: LodashEq; + equals: LodashIsEqual; + escape: LodashEscape; + escapeRegExp: LodashEscapeRegExp; + every: LodashEvery; + extend: LodashExtend; + extendAll: LodashExtendAll; + extendAllWith: LodashExtendAllWith; + extendWith: LodashExtendWith; + F: LodashStubFalse; + fill: LodashFill; + filter: LodashFilter; + find: LodashFind; + findFrom: LodashFindFrom; + findIndex: LodashFindIndex; + findIndexFrom: LodashFindIndexFrom; + findKey: LodashFindKey; + findLast: LodashFindLast; + findLastFrom: LodashFindLastFrom; + findLastIndex: LodashFindLastIndex; + findLastIndexFrom: LodashFindLastIndexFrom; + findLastKey: LodashFindLastKey; + first: LodashHead; + flatMap: LodashFlatMap; + flatMapDeep: LodashFlatMapDeep; + flatMapDepth: LodashFlatMapDepth; + flatten: LodashFlatten; + flattenDeep: LodashFlattenDeep; + flattenDepth: LodashFlattenDepth; + flip: LodashFlip; + floor: LodashFloor; + flow: LodashFlow; + flowRight: LodashFlowRight; + forEach: LodashForEach; + forEachRight: LodashForEachRight; + forIn: LodashForIn; + forInRight: LodashForInRight; + forOwn: LodashForOwn; + forOwnRight: LodashForOwnRight; + fromPairs: LodashFromPairs; + functions: LodashFunctions; + functionsIn: LodashFunctionsIn; + get: LodashGet; + getOr: LodashGetOr; + groupBy: LodashGroupBy; + gt: LodashGt; + gte: LodashGte; + has: LodashHas; + hasIn: LodashHasIn; + head: LodashHead; + identical: LodashEq; + identity: LodashIdentity; + includes: LodashIncludes; + includesFrom: LodashIncludesFrom; + indexBy: LodashKeyBy; + indexOf: LodashIndexOf; + indexOfFrom: LodashIndexOfFrom; + init: LodashInitial; + initial: LodashInitial; + inRange: LodashInRange; + intersection: LodashIntersection; + intersectionBy: LodashIntersectionBy; + intersectionWith: LodashIntersectionWith; + invert: LodashInvert; + invertBy: LodashInvertBy; + invertObj: LodashInvert; + invoke: LodashInvoke; + invokeArgs: LodashInvokeArgs; + invokeArgsMap: LodashInvokeArgsMap; + invokeMap: LodashInvokeMap; + isArguments: LodashIsArguments; + isArray: LodashIsArray; + isArrayBuffer: LodashIsArrayBuffer; + isArrayLike: LodashIsArrayLike; + isArrayLikeObject: LodashIsArrayLikeObject; + isBoolean: LodashIsBoolean; + isBuffer: LodashIsBuffer; + isDate: LodashIsDate; + isElement: LodashIsElement; + isEmpty: LodashIsEmpty; + isEqual: LodashIsEqual; + isEqualWith: LodashIsEqualWith; + isError: LodashIsError; + isFinite: LodashIsFinite; + isFunction: LodashIsFunction; + isInteger: LodashIsInteger; + isLength: LodashIsLength; + isMap: LodashIsMap; + isMatch: LodashIsMatch; + isMatchWith: LodashIsMatchWith; + isNaN: LodashIsNaN; + isNative: LodashIsNative; + isNil: LodashIsNil; + isNull: LodashIsNull; + isNumber: LodashIsNumber; + isObject: LodashIsObject; + isObjectLike: LodashIsObjectLike; + isPlainObject: LodashIsPlainObject; + isRegExp: LodashIsRegExp; + isSafeInteger: LodashIsSafeInteger; + isSet: LodashIsSet; + isString: LodashIsString; + isSymbol: LodashIsSymbol; + isTypedArray: LodashIsTypedArray; + isUndefined: LodashIsUndefined; + isWeakMap: LodashIsWeakMap; + isWeakSet: LodashIsWeakSet; + iteratee: LodashIteratee; + join: LodashJoin; + juxt: LodashOver; + kebabCase: LodashKebabCase; + keyBy: LodashKeyBy; + keys: LodashKeys; + keysIn: LodashKeysIn; + last: LodashLast; + lastIndexOf: LodashLastIndexOf; + lastIndexOfFrom: LodashLastIndexOfFrom; + lowerCase: LodashLowerCase; + lowerFirst: LodashLowerFirst; + lt: LodashLt; + lte: LodashLte; + map: LodashMap; + mapKeys: LodashMapKeys; + mapValues: LodashMapValues; + matches: LodashIsMatch; + matchesProperty: LodashMatchesProperty; + max: LodashMax; + maxBy: LodashMaxBy; + mean: LodashMean; + meanBy: LodashMeanBy; + memoize: LodashMemoize; + merge: LodashMerge; + mergeAll: LodashMergeAll; + mergeAllWith: LodashMergeAllWith; + mergeWith: LodashMergeWith; + method: LodashMethod; + methodOf: LodashMethodOf; + min: LodashMin; + minBy: LodashMinBy; + multiply: LodashMultiply; + nAry: LodashAry; + negate: LodashNegate; + noConflict: LodashNoConflict; + noop: LodashNoop; + now: LodashNow; + nth: LodashNth; + nthArg: LodashNthArg; + omit: LodashOmit; + omitAll: LodashOmit; + omitBy: LodashOmitBy; + once: LodashOnce; + orderBy: LodashOrderBy; + over: LodashOver; + overArgs: LodashOverArgs; + overEvery: LodashOverEvery; + overSome: LodashOverSome; + pad: LodashPad; + padChars: LodashPadChars; + padCharsEnd: LodashPadCharsEnd; + padCharsStart: LodashPadCharsStart; + padEnd: LodashPadEnd; + padStart: LodashPadStart; + parseInt: LodashParseInt; + partial: LodashPartial; + partialRight: LodashPartialRight; + partition: LodashPartition; + path: LodashPath; + pathEq: LodashMatchesProperty; + pathOr: LodashPathOr; + paths: LodashAt; + pick: LodashPick; + pickAll: LodashPick; + pickBy: LodashPickBy; + pipe: LodashFlow; + pluck: LodashMap; + prop: LodashProp; + propEq: LodashMatchesProperty; + property: LodashProperty; + propertyOf: LodashPropertyOf; + propOr: LodashPropOr; + props: LodashAt; + pull: LodashPull; + pullAll: LodashPullAll; + pullAllBy: LodashPullAllBy; + pullAllWith: LodashPullAllWith; + pullAt: LodashPullAt; + random: LodashRandom; + range: LodashRange; + rangeRight: LodashRangeRight; + rangeStep: LodashRangeStep; + rangeStepRight: LodashRangeStepRight; + rearg: LodashRearg; + reduce: LodashReduce; + reduceRight: LodashReduceRight; + reject: LodashReject; + remove: LodashRemove; + repeat: LodashRepeat; + replace: LodashReplace; + rest: LodashRest; + restFrom: LodashRestFrom; + result: LodashResult; + reverse: LodashReverse; + round: LodashRound; + runInContext: LodashRunInContext; + sample: LodashSample; + sampleSize: LodashSampleSize; + set: LodashSet; + setWith: LodashSetWith; + shuffle: LodashShuffle; + size: LodashSize; + slice: LodashSlice; + snakeCase: LodashSnakeCase; + some: LodashSome; + sortBy: LodashSortBy; + sortedIndex: LodashSortedIndex; + sortedIndexBy: LodashSortedIndexBy; + sortedIndexOf: LodashSortedIndexOf; + sortedLastIndex: LodashSortedLastIndex; + sortedLastIndexBy: LodashSortedLastIndexBy; + sortedLastIndexOf: LodashSortedLastIndexOf; + sortedUniq: LodashSortedUniq; + sortedUniqBy: LodashSortedUniqBy; + split: LodashSplit; + spread: LodashSpread; + spreadFrom: LodashSpreadFrom; + startCase: LodashStartCase; + startsWith: LodashStartsWith; + stubArray: LodashStubArray; + stubFalse: LodashStubFalse; + stubObject: LodashStubObject; + stubString: LodashStubString; + stubTrue: LodashStubTrue; + subtract: LodashSubtract; + sum: LodashSum; + sumBy: LodashSumBy; + symmetricDifference: LodashXor; + symmetricDifferenceBy: LodashXorBy; + symmetricDifferenceWith: LodashXorWith; + T: LodashStubTrue; + tail: LodashTail; + take: LodashTake; + takeLast: LodashTakeRight; + takeLastWhile: LodashTakeRightWhile; + takeRight: LodashTakeRight; + takeRightWhile: LodashTakeRightWhile; + takeWhile: LodashTakeWhile; + tap: LodashTap; + template: LodashTemplate; + throttle: LodashThrottle; + thru: LodashThru; + times: LodashTimes; + toArray: LodashToArray; + toFinite: LodashToFinite; + toInteger: LodashToInteger; + toLength: LodashToLength; + toLower: LodashToLower; + toNumber: LodashToNumber; + toPairs: LodashToPairs; + toPairsIn: LodashToPairsIn; + toPath: LodashToPath; + toPlainObject: LodashToPlainObject; + toSafeInteger: LodashToSafeInteger; + toString: LodashToString; + toUpper: LodashToUpper; + transform: LodashTransform; + trim: LodashTrim; + trimChars: LodashTrimChars; + trimCharsEnd: LodashTrimCharsEnd; + trimCharsStart: LodashTrimCharsStart; + trimEnd: LodashTrimEnd; + trimStart: LodashTrimStart; + truncate: LodashTruncate; + unapply: LodashUnapply; + unary: LodashUnary; + unescape: LodashUnescape; + union: LodashUnion; + unionBy: LodashUnionBy; + unionWith: LodashUnionWith; + uniq: LodashUniq; + uniqBy: LodashUniqBy; + uniqueId: LodashUniqueId; + uniqWith: LodashUniqWith; + unnest: LodashFlatten; + unset: LodashUnset; + unzip: LodashUnzip; + unzipWith: LodashUnzipWith; + update: LodashUpdate; + updateWith: LodashUpdateWith; + upperCase: LodashUpperCase; + upperFirst: LodashUpperFirst; + useWith: LodashOverArgs; + values: LodashValues; + valuesIn: LodashValuesIn; + where: LodashConformsTo; + whereEq: LodashIsMatch; + without: LodashWithout; + words: LodashWords; + wrap: LodashWrap; + xor: LodashXor; + xorBy: LodashXorBy; + xorWith: LodashXorWith; + zip: LodashZip; + zipAll: LodashZipAll; + zipObj: LodashZipObject; + zipObject: LodashZipObject; + zipObjectDeep: LodashZipObjectDeep; + zipWith: LodashZipWith; + __: lodash.__; + placeholder: lodash.__; + } +} diff --git a/node_modules/@types/lodash/fp/F.d.ts b/node_modules/@types/lodash/fp/F.d.ts new file mode 100644 index 0000000..33fc579 --- /dev/null +++ b/node_modules/@types/lodash/fp/F.d.ts @@ -0,0 +1,2 @@ +import { F } from "../fp"; +export = F; diff --git a/node_modules/@types/lodash/fp/T.d.ts b/node_modules/@types/lodash/fp/T.d.ts new file mode 100644 index 0000000..886606e --- /dev/null +++ b/node_modules/@types/lodash/fp/T.d.ts @@ -0,0 +1,2 @@ +import { T } from "../fp"; +export = T; diff --git a/node_modules/@types/lodash/fp/__.d.ts b/node_modules/@types/lodash/fp/__.d.ts new file mode 100644 index 0000000..aec0a51 --- /dev/null +++ b/node_modules/@types/lodash/fp/__.d.ts @@ -0,0 +1,3 @@ +import _ = require("../index"); +declare const __: _.__; +export = __; diff --git a/node_modules/@types/lodash/fp/add.d.ts b/node_modules/@types/lodash/fp/add.d.ts new file mode 100644 index 0000000..47c9c6a --- /dev/null +++ b/node_modules/@types/lodash/fp/add.d.ts @@ -0,0 +1,2 @@ +import { add } from "../fp"; +export = add; diff --git a/node_modules/@types/lodash/fp/after.d.ts b/node_modules/@types/lodash/fp/after.d.ts new file mode 100644 index 0000000..93863a5 --- /dev/null +++ b/node_modules/@types/lodash/fp/after.d.ts @@ -0,0 +1,2 @@ +import { after } from "../fp"; +export = after; diff --git a/node_modules/@types/lodash/fp/all.d.ts b/node_modules/@types/lodash/fp/all.d.ts new file mode 100644 index 0000000..5ca0f70 --- /dev/null +++ b/node_modules/@types/lodash/fp/all.d.ts @@ -0,0 +1,2 @@ +import { all } from "../fp"; +export = all; diff --git a/node_modules/@types/lodash/fp/allPass.d.ts b/node_modules/@types/lodash/fp/allPass.d.ts new file mode 100644 index 0000000..5013913 --- /dev/null +++ b/node_modules/@types/lodash/fp/allPass.d.ts @@ -0,0 +1,2 @@ +import { allPass } from "../fp"; +export = allPass; diff --git a/node_modules/@types/lodash/fp/always.d.ts b/node_modules/@types/lodash/fp/always.d.ts new file mode 100644 index 0000000..07bd82d --- /dev/null +++ b/node_modules/@types/lodash/fp/always.d.ts @@ -0,0 +1,2 @@ +import { always } from "../fp"; +export = always; diff --git a/node_modules/@types/lodash/fp/any.d.ts b/node_modules/@types/lodash/fp/any.d.ts new file mode 100644 index 0000000..5d8c38f --- /dev/null +++ b/node_modules/@types/lodash/fp/any.d.ts @@ -0,0 +1,2 @@ +import { any } from "../fp"; +export = any; diff --git a/node_modules/@types/lodash/fp/anyPass.d.ts b/node_modules/@types/lodash/fp/anyPass.d.ts new file mode 100644 index 0000000..b69becf --- /dev/null +++ b/node_modules/@types/lodash/fp/anyPass.d.ts @@ -0,0 +1,2 @@ +import { anyPass } from "../fp"; +export = anyPass; diff --git a/node_modules/@types/lodash/fp/apply.d.ts b/node_modules/@types/lodash/fp/apply.d.ts new file mode 100644 index 0000000..e13c42c --- /dev/null +++ b/node_modules/@types/lodash/fp/apply.d.ts @@ -0,0 +1,2 @@ +import { apply } from "../fp"; +export = apply; diff --git a/node_modules/@types/lodash/fp/ary.d.ts b/node_modules/@types/lodash/fp/ary.d.ts new file mode 100644 index 0000000..932d7f4 --- /dev/null +++ b/node_modules/@types/lodash/fp/ary.d.ts @@ -0,0 +1,2 @@ +import { ary } from "../fp"; +export = ary; diff --git a/node_modules/@types/lodash/fp/assign.d.ts b/node_modules/@types/lodash/fp/assign.d.ts new file mode 100644 index 0000000..cf17310 --- /dev/null +++ b/node_modules/@types/lodash/fp/assign.d.ts @@ -0,0 +1,2 @@ +import { assign } from "../fp"; +export = assign; diff --git a/node_modules/@types/lodash/fp/assignAll.d.ts b/node_modules/@types/lodash/fp/assignAll.d.ts new file mode 100644 index 0000000..f95b06b --- /dev/null +++ b/node_modules/@types/lodash/fp/assignAll.d.ts @@ -0,0 +1,2 @@ +import { assignAll } from "../fp"; +export = assignAll; diff --git a/node_modules/@types/lodash/fp/assignAllWith.d.ts b/node_modules/@types/lodash/fp/assignAllWith.d.ts new file mode 100644 index 0000000..c2695a0 --- /dev/null +++ b/node_modules/@types/lodash/fp/assignAllWith.d.ts @@ -0,0 +1,2 @@ +import { assignAllWith } from "../fp"; +export = assignAllWith; diff --git a/node_modules/@types/lodash/fp/assignIn.d.ts b/node_modules/@types/lodash/fp/assignIn.d.ts new file mode 100644 index 0000000..f6cdee7 --- /dev/null +++ b/node_modules/@types/lodash/fp/assignIn.d.ts @@ -0,0 +1,2 @@ +import { assignIn } from "../fp"; +export = assignIn; diff --git a/node_modules/@types/lodash/fp/assignInAll.d.ts b/node_modules/@types/lodash/fp/assignInAll.d.ts new file mode 100644 index 0000000..539344b --- /dev/null +++ b/node_modules/@types/lodash/fp/assignInAll.d.ts @@ -0,0 +1,2 @@ +import { assignInAll } from "../fp"; +export = assignInAll; diff --git a/node_modules/@types/lodash/fp/assignInAllWith.d.ts b/node_modules/@types/lodash/fp/assignInAllWith.d.ts new file mode 100644 index 0000000..3b421fb --- /dev/null +++ b/node_modules/@types/lodash/fp/assignInAllWith.d.ts @@ -0,0 +1,2 @@ +import { assignInAllWith } from "../fp"; +export = assignInAllWith; diff --git a/node_modules/@types/lodash/fp/assignInWith.d.ts b/node_modules/@types/lodash/fp/assignInWith.d.ts new file mode 100644 index 0000000..c410091 --- /dev/null +++ b/node_modules/@types/lodash/fp/assignInWith.d.ts @@ -0,0 +1,2 @@ +import { assignInWith } from "../fp"; +export = assignInWith; diff --git a/node_modules/@types/lodash/fp/assignWith.d.ts b/node_modules/@types/lodash/fp/assignWith.d.ts new file mode 100644 index 0000000..2205db0 --- /dev/null +++ b/node_modules/@types/lodash/fp/assignWith.d.ts @@ -0,0 +1,2 @@ +import { assignWith } from "../fp"; +export = assignWith; diff --git a/node_modules/@types/lodash/fp/assoc.d.ts b/node_modules/@types/lodash/fp/assoc.d.ts new file mode 100644 index 0000000..2a2e29c --- /dev/null +++ b/node_modules/@types/lodash/fp/assoc.d.ts @@ -0,0 +1,2 @@ +import { assoc } from "../fp"; +export = assoc; diff --git a/node_modules/@types/lodash/fp/assocPath.d.ts b/node_modules/@types/lodash/fp/assocPath.d.ts new file mode 100644 index 0000000..e2dd517 --- /dev/null +++ b/node_modules/@types/lodash/fp/assocPath.d.ts @@ -0,0 +1,2 @@ +import { assocPath } from "../fp"; +export = assocPath; diff --git a/node_modules/@types/lodash/fp/at.d.ts b/node_modules/@types/lodash/fp/at.d.ts new file mode 100644 index 0000000..beefa33 --- /dev/null +++ b/node_modules/@types/lodash/fp/at.d.ts @@ -0,0 +1,2 @@ +import { at } from "../fp"; +export = at; diff --git a/node_modules/@types/lodash/fp/attempt.d.ts b/node_modules/@types/lodash/fp/attempt.d.ts new file mode 100644 index 0000000..72d60af --- /dev/null +++ b/node_modules/@types/lodash/fp/attempt.d.ts @@ -0,0 +1,2 @@ +import { attempt } from "../fp"; +export = attempt; diff --git a/node_modules/@types/lodash/fp/before.d.ts b/node_modules/@types/lodash/fp/before.d.ts new file mode 100644 index 0000000..ead2869 --- /dev/null +++ b/node_modules/@types/lodash/fp/before.d.ts @@ -0,0 +1,2 @@ +import { before } from "../fp"; +export = before; diff --git a/node_modules/@types/lodash/fp/bind.d.ts b/node_modules/@types/lodash/fp/bind.d.ts new file mode 100644 index 0000000..a312192 --- /dev/null +++ b/node_modules/@types/lodash/fp/bind.d.ts @@ -0,0 +1,2 @@ +import { bind } from "../fp"; +export = bind; diff --git a/node_modules/@types/lodash/fp/bindAll.d.ts b/node_modules/@types/lodash/fp/bindAll.d.ts new file mode 100644 index 0000000..4f7c7db --- /dev/null +++ b/node_modules/@types/lodash/fp/bindAll.d.ts @@ -0,0 +1,2 @@ +import { bindAll } from "../fp"; +export = bindAll; diff --git a/node_modules/@types/lodash/fp/bindKey.d.ts b/node_modules/@types/lodash/fp/bindKey.d.ts new file mode 100644 index 0000000..8986b2f --- /dev/null +++ b/node_modules/@types/lodash/fp/bindKey.d.ts @@ -0,0 +1,2 @@ +import { bindKey } from "../fp"; +export = bindKey; diff --git a/node_modules/@types/lodash/fp/camelCase.d.ts b/node_modules/@types/lodash/fp/camelCase.d.ts new file mode 100644 index 0000000..be6628d --- /dev/null +++ b/node_modules/@types/lodash/fp/camelCase.d.ts @@ -0,0 +1,2 @@ +import { camelCase } from "../fp"; +export = camelCase; diff --git a/node_modules/@types/lodash/fp/capitalize.d.ts b/node_modules/@types/lodash/fp/capitalize.d.ts new file mode 100644 index 0000000..7dc552f --- /dev/null +++ b/node_modules/@types/lodash/fp/capitalize.d.ts @@ -0,0 +1,2 @@ +import { capitalize } from "../fp"; +export = capitalize; diff --git a/node_modules/@types/lodash/fp/castArray.d.ts b/node_modules/@types/lodash/fp/castArray.d.ts new file mode 100644 index 0000000..a431805 --- /dev/null +++ b/node_modules/@types/lodash/fp/castArray.d.ts @@ -0,0 +1,2 @@ +import { castArray } from "../fp"; +export = castArray; diff --git a/node_modules/@types/lodash/fp/ceil.d.ts b/node_modules/@types/lodash/fp/ceil.d.ts new file mode 100644 index 0000000..13cd731 --- /dev/null +++ b/node_modules/@types/lodash/fp/ceil.d.ts @@ -0,0 +1,2 @@ +import { ceil } from "../fp"; +export = ceil; diff --git a/node_modules/@types/lodash/fp/chunk.d.ts b/node_modules/@types/lodash/fp/chunk.d.ts new file mode 100644 index 0000000..2e40666 --- /dev/null +++ b/node_modules/@types/lodash/fp/chunk.d.ts @@ -0,0 +1,2 @@ +import { chunk } from "../fp"; +export = chunk; diff --git a/node_modules/@types/lodash/fp/clamp.d.ts b/node_modules/@types/lodash/fp/clamp.d.ts new file mode 100644 index 0000000..121c6f9 --- /dev/null +++ b/node_modules/@types/lodash/fp/clamp.d.ts @@ -0,0 +1,2 @@ +import { clamp } from "../fp"; +export = clamp; diff --git a/node_modules/@types/lodash/fp/clone.d.ts b/node_modules/@types/lodash/fp/clone.d.ts new file mode 100644 index 0000000..9edf0c8 --- /dev/null +++ b/node_modules/@types/lodash/fp/clone.d.ts @@ -0,0 +1,2 @@ +import { clone } from "../fp"; +export = clone; diff --git a/node_modules/@types/lodash/fp/cloneDeep.d.ts b/node_modules/@types/lodash/fp/cloneDeep.d.ts new file mode 100644 index 0000000..3bdab15 --- /dev/null +++ b/node_modules/@types/lodash/fp/cloneDeep.d.ts @@ -0,0 +1,2 @@ +import { cloneDeep } from "../fp"; +export = cloneDeep; diff --git a/node_modules/@types/lodash/fp/cloneDeepWith.d.ts b/node_modules/@types/lodash/fp/cloneDeepWith.d.ts new file mode 100644 index 0000000..57cf5af --- /dev/null +++ b/node_modules/@types/lodash/fp/cloneDeepWith.d.ts @@ -0,0 +1,2 @@ +import { cloneDeepWith } from "../fp"; +export = cloneDeepWith; diff --git a/node_modules/@types/lodash/fp/cloneWith.d.ts b/node_modules/@types/lodash/fp/cloneWith.d.ts new file mode 100644 index 0000000..9c63e13 --- /dev/null +++ b/node_modules/@types/lodash/fp/cloneWith.d.ts @@ -0,0 +1,2 @@ +import { cloneWith } from "../fp"; +export = cloneWith; diff --git a/node_modules/@types/lodash/fp/compact.d.ts b/node_modules/@types/lodash/fp/compact.d.ts new file mode 100644 index 0000000..6ca1547 --- /dev/null +++ b/node_modules/@types/lodash/fp/compact.d.ts @@ -0,0 +1,2 @@ +import { compact } from "../fp"; +export = compact; diff --git a/node_modules/@types/lodash/fp/complement.d.ts b/node_modules/@types/lodash/fp/complement.d.ts new file mode 100644 index 0000000..e4c3112 --- /dev/null +++ b/node_modules/@types/lodash/fp/complement.d.ts @@ -0,0 +1,2 @@ +import { complement } from "../fp"; +export = complement; diff --git a/node_modules/@types/lodash/fp/compose.d.ts b/node_modules/@types/lodash/fp/compose.d.ts new file mode 100644 index 0000000..7950c7c --- /dev/null +++ b/node_modules/@types/lodash/fp/compose.d.ts @@ -0,0 +1,2 @@ +import { compose } from "../fp"; +export = compose; diff --git a/node_modules/@types/lodash/fp/concat.d.ts b/node_modules/@types/lodash/fp/concat.d.ts new file mode 100644 index 0000000..5e109d1 --- /dev/null +++ b/node_modules/@types/lodash/fp/concat.d.ts @@ -0,0 +1,2 @@ +import { concat } from "../fp"; +export = concat; diff --git a/node_modules/@types/lodash/fp/cond.d.ts b/node_modules/@types/lodash/fp/cond.d.ts new file mode 100644 index 0000000..b9216e3 --- /dev/null +++ b/node_modules/@types/lodash/fp/cond.d.ts @@ -0,0 +1,2 @@ +import { cond } from "../fp"; +export = cond; diff --git a/node_modules/@types/lodash/fp/conforms.d.ts b/node_modules/@types/lodash/fp/conforms.d.ts new file mode 100644 index 0000000..9bd3353 --- /dev/null +++ b/node_modules/@types/lodash/fp/conforms.d.ts @@ -0,0 +1,2 @@ +import { conforms } from "../fp"; +export = conforms; diff --git a/node_modules/@types/lodash/fp/conformsTo.d.ts b/node_modules/@types/lodash/fp/conformsTo.d.ts new file mode 100644 index 0000000..ad17280 --- /dev/null +++ b/node_modules/@types/lodash/fp/conformsTo.d.ts @@ -0,0 +1,2 @@ +import { conformsTo } from "../fp"; +export = conformsTo; diff --git a/node_modules/@types/lodash/fp/constant.d.ts b/node_modules/@types/lodash/fp/constant.d.ts new file mode 100644 index 0000000..ef80ff5 --- /dev/null +++ b/node_modules/@types/lodash/fp/constant.d.ts @@ -0,0 +1,2 @@ +import { constant } from "../fp"; +export = constant; diff --git a/node_modules/@types/lodash/fp/contains.d.ts b/node_modules/@types/lodash/fp/contains.d.ts new file mode 100644 index 0000000..6c29e95 --- /dev/null +++ b/node_modules/@types/lodash/fp/contains.d.ts @@ -0,0 +1,2 @@ +import { contains } from "../fp"; +export = contains; diff --git a/node_modules/@types/lodash/fp/convert.d.ts b/node_modules/@types/lodash/fp/convert.d.ts new file mode 100644 index 0000000..c06ecd9 --- /dev/null +++ b/node_modules/@types/lodash/fp/convert.d.ts @@ -0,0 +1,15 @@ +interface ConvertOptions { + cap?: boolean; + curry?: boolean; + fixed?: boolean; + immutable?: boolean; + rearg?: boolean; +} + +interface Convert { + (func: object, options?: ConvertOptions): any; + (name: string, func: (...args: any[]) => any, options?: ConvertOptions): any; +} + +declare const convert: Convert; +export = convert; diff --git a/node_modules/@types/lodash/fp/countBy.d.ts b/node_modules/@types/lodash/fp/countBy.d.ts new file mode 100644 index 0000000..e3725c3 --- /dev/null +++ b/node_modules/@types/lodash/fp/countBy.d.ts @@ -0,0 +1,2 @@ +import { countBy } from "../fp"; +export = countBy; diff --git a/node_modules/@types/lodash/fp/create.d.ts b/node_modules/@types/lodash/fp/create.d.ts new file mode 100644 index 0000000..2818e10 --- /dev/null +++ b/node_modules/@types/lodash/fp/create.d.ts @@ -0,0 +1,2 @@ +import { create } from "../fp"; +export = create; diff --git a/node_modules/@types/lodash/fp/curry.d.ts b/node_modules/@types/lodash/fp/curry.d.ts new file mode 100644 index 0000000..e8fcf1d --- /dev/null +++ b/node_modules/@types/lodash/fp/curry.d.ts @@ -0,0 +1,2 @@ +import { curry } from "../fp"; +export = curry; diff --git a/node_modules/@types/lodash/fp/curryN.d.ts b/node_modules/@types/lodash/fp/curryN.d.ts new file mode 100644 index 0000000..55b579b --- /dev/null +++ b/node_modules/@types/lodash/fp/curryN.d.ts @@ -0,0 +1,2 @@ +import { curryN } from "../fp"; +export = curryN; diff --git a/node_modules/@types/lodash/fp/curryRight.d.ts b/node_modules/@types/lodash/fp/curryRight.d.ts new file mode 100644 index 0000000..d431f3c --- /dev/null +++ b/node_modules/@types/lodash/fp/curryRight.d.ts @@ -0,0 +1,2 @@ +import { curryRight } from "../fp"; +export = curryRight; diff --git a/node_modules/@types/lodash/fp/curryRightN.d.ts b/node_modules/@types/lodash/fp/curryRightN.d.ts new file mode 100644 index 0000000..89866d1 --- /dev/null +++ b/node_modules/@types/lodash/fp/curryRightN.d.ts @@ -0,0 +1,2 @@ +import { curryRightN } from "../fp"; +export = curryRightN; diff --git a/node_modules/@types/lodash/fp/debounce.d.ts b/node_modules/@types/lodash/fp/debounce.d.ts new file mode 100644 index 0000000..88b003c --- /dev/null +++ b/node_modules/@types/lodash/fp/debounce.d.ts @@ -0,0 +1,2 @@ +import { debounce } from "../fp"; +export = debounce; diff --git a/node_modules/@types/lodash/fp/deburr.d.ts b/node_modules/@types/lodash/fp/deburr.d.ts new file mode 100644 index 0000000..769abfb --- /dev/null +++ b/node_modules/@types/lodash/fp/deburr.d.ts @@ -0,0 +1,2 @@ +import { deburr } from "../fp"; +export = deburr; diff --git a/node_modules/@types/lodash/fp/defaultTo.d.ts b/node_modules/@types/lodash/fp/defaultTo.d.ts new file mode 100644 index 0000000..e02cc46 --- /dev/null +++ b/node_modules/@types/lodash/fp/defaultTo.d.ts @@ -0,0 +1,2 @@ +import { defaultTo } from "../fp"; +export = defaultTo; diff --git a/node_modules/@types/lodash/fp/defaults.d.ts b/node_modules/@types/lodash/fp/defaults.d.ts new file mode 100644 index 0000000..132e47b --- /dev/null +++ b/node_modules/@types/lodash/fp/defaults.d.ts @@ -0,0 +1,2 @@ +import { defaults } from "../fp"; +export = defaults; diff --git a/node_modules/@types/lodash/fp/defaultsAll.d.ts b/node_modules/@types/lodash/fp/defaultsAll.d.ts new file mode 100644 index 0000000..1f2a330 --- /dev/null +++ b/node_modules/@types/lodash/fp/defaultsAll.d.ts @@ -0,0 +1,2 @@ +import { defaultsAll } from "../fp"; +export = defaultsAll; diff --git a/node_modules/@types/lodash/fp/defaultsDeep.d.ts b/node_modules/@types/lodash/fp/defaultsDeep.d.ts new file mode 100644 index 0000000..6268a02 --- /dev/null +++ b/node_modules/@types/lodash/fp/defaultsDeep.d.ts @@ -0,0 +1,2 @@ +import { defaultsDeep } from "../fp"; +export = defaultsDeep; diff --git a/node_modules/@types/lodash/fp/defaultsDeepAll.d.ts b/node_modules/@types/lodash/fp/defaultsDeepAll.d.ts new file mode 100644 index 0000000..7791666 --- /dev/null +++ b/node_modules/@types/lodash/fp/defaultsDeepAll.d.ts @@ -0,0 +1,2 @@ +import { defaultsDeepAll } from "../fp"; +export = defaultsDeepAll; diff --git a/node_modules/@types/lodash/fp/defer.d.ts b/node_modules/@types/lodash/fp/defer.d.ts new file mode 100644 index 0000000..f8be4ae --- /dev/null +++ b/node_modules/@types/lodash/fp/defer.d.ts @@ -0,0 +1,2 @@ +import { defer } from "../fp"; +export = defer; diff --git a/node_modules/@types/lodash/fp/delay.d.ts b/node_modules/@types/lodash/fp/delay.d.ts new file mode 100644 index 0000000..2f0c399 --- /dev/null +++ b/node_modules/@types/lodash/fp/delay.d.ts @@ -0,0 +1,2 @@ +import { delay } from "../fp"; +export = delay; diff --git a/node_modules/@types/lodash/fp/difference.d.ts b/node_modules/@types/lodash/fp/difference.d.ts new file mode 100644 index 0000000..9448085 --- /dev/null +++ b/node_modules/@types/lodash/fp/difference.d.ts @@ -0,0 +1,2 @@ +import { difference } from "../fp"; +export = difference; diff --git a/node_modules/@types/lodash/fp/differenceBy.d.ts b/node_modules/@types/lodash/fp/differenceBy.d.ts new file mode 100644 index 0000000..52ba5b8 --- /dev/null +++ b/node_modules/@types/lodash/fp/differenceBy.d.ts @@ -0,0 +1,2 @@ +import { differenceBy } from "../fp"; +export = differenceBy; diff --git a/node_modules/@types/lodash/fp/differenceWith.d.ts b/node_modules/@types/lodash/fp/differenceWith.d.ts new file mode 100644 index 0000000..fd3c9a2 --- /dev/null +++ b/node_modules/@types/lodash/fp/differenceWith.d.ts @@ -0,0 +1,2 @@ +import { differenceWith } from "../fp"; +export = differenceWith; diff --git a/node_modules/@types/lodash/fp/dissoc.d.ts b/node_modules/@types/lodash/fp/dissoc.d.ts new file mode 100644 index 0000000..9b0fd6b --- /dev/null +++ b/node_modules/@types/lodash/fp/dissoc.d.ts @@ -0,0 +1,2 @@ +import { dissoc } from "../fp"; +export = dissoc; diff --git a/node_modules/@types/lodash/fp/dissocPath.d.ts b/node_modules/@types/lodash/fp/dissocPath.d.ts new file mode 100644 index 0000000..a201aa4 --- /dev/null +++ b/node_modules/@types/lodash/fp/dissocPath.d.ts @@ -0,0 +1,2 @@ +import { dissocPath } from "../fp"; +export = dissocPath; diff --git a/node_modules/@types/lodash/fp/divide.d.ts b/node_modules/@types/lodash/fp/divide.d.ts new file mode 100644 index 0000000..5cd02e4 --- /dev/null +++ b/node_modules/@types/lodash/fp/divide.d.ts @@ -0,0 +1,2 @@ +import { divide } from "../fp"; +export = divide; diff --git a/node_modules/@types/lodash/fp/drop.d.ts b/node_modules/@types/lodash/fp/drop.d.ts new file mode 100644 index 0000000..bc3b9b2 --- /dev/null +++ b/node_modules/@types/lodash/fp/drop.d.ts @@ -0,0 +1,2 @@ +import { drop } from "../fp"; +export = drop; diff --git a/node_modules/@types/lodash/fp/dropLast.d.ts b/node_modules/@types/lodash/fp/dropLast.d.ts new file mode 100644 index 0000000..1dd388a --- /dev/null +++ b/node_modules/@types/lodash/fp/dropLast.d.ts @@ -0,0 +1,2 @@ +import { dropLast } from "../fp"; +export = dropLast; diff --git a/node_modules/@types/lodash/fp/dropLastWhile.d.ts b/node_modules/@types/lodash/fp/dropLastWhile.d.ts new file mode 100644 index 0000000..97529a6 --- /dev/null +++ b/node_modules/@types/lodash/fp/dropLastWhile.d.ts @@ -0,0 +1,2 @@ +import { dropLastWhile } from "../fp"; +export = dropLastWhile; diff --git a/node_modules/@types/lodash/fp/dropRight.d.ts b/node_modules/@types/lodash/fp/dropRight.d.ts new file mode 100644 index 0000000..a2740ff --- /dev/null +++ b/node_modules/@types/lodash/fp/dropRight.d.ts @@ -0,0 +1,2 @@ +import { dropRight } from "../fp"; +export = dropRight; diff --git a/node_modules/@types/lodash/fp/dropRightWhile.d.ts b/node_modules/@types/lodash/fp/dropRightWhile.d.ts new file mode 100644 index 0000000..1a5aa5f --- /dev/null +++ b/node_modules/@types/lodash/fp/dropRightWhile.d.ts @@ -0,0 +1,2 @@ +import { dropRightWhile } from "../fp"; +export = dropRightWhile; diff --git a/node_modules/@types/lodash/fp/dropWhile.d.ts b/node_modules/@types/lodash/fp/dropWhile.d.ts new file mode 100644 index 0000000..2cab8d8 --- /dev/null +++ b/node_modules/@types/lodash/fp/dropWhile.d.ts @@ -0,0 +1,2 @@ +import { dropWhile } from "../fp"; +export = dropWhile; diff --git a/node_modules/@types/lodash/fp/each.d.ts b/node_modules/@types/lodash/fp/each.d.ts new file mode 100644 index 0000000..af1d3b2 --- /dev/null +++ b/node_modules/@types/lodash/fp/each.d.ts @@ -0,0 +1,2 @@ +import { each } from "../fp"; +export = each; diff --git a/node_modules/@types/lodash/fp/eachRight.d.ts b/node_modules/@types/lodash/fp/eachRight.d.ts new file mode 100644 index 0000000..5ca2934 --- /dev/null +++ b/node_modules/@types/lodash/fp/eachRight.d.ts @@ -0,0 +1,2 @@ +import { eachRight } from "../fp"; +export = eachRight; diff --git a/node_modules/@types/lodash/fp/endsWith.d.ts b/node_modules/@types/lodash/fp/endsWith.d.ts new file mode 100644 index 0000000..7e1b243 --- /dev/null +++ b/node_modules/@types/lodash/fp/endsWith.d.ts @@ -0,0 +1,2 @@ +import { endsWith } from "../fp"; +export = endsWith; diff --git a/node_modules/@types/lodash/fp/entries.d.ts b/node_modules/@types/lodash/fp/entries.d.ts new file mode 100644 index 0000000..534c7bd --- /dev/null +++ b/node_modules/@types/lodash/fp/entries.d.ts @@ -0,0 +1,2 @@ +import { entries } from "../fp"; +export = entries; diff --git a/node_modules/@types/lodash/fp/entriesIn.d.ts b/node_modules/@types/lodash/fp/entriesIn.d.ts new file mode 100644 index 0000000..932b17f --- /dev/null +++ b/node_modules/@types/lodash/fp/entriesIn.d.ts @@ -0,0 +1,2 @@ +import { entriesIn } from "../fp"; +export = entriesIn; diff --git a/node_modules/@types/lodash/fp/eq.d.ts b/node_modules/@types/lodash/fp/eq.d.ts new file mode 100644 index 0000000..4778846 --- /dev/null +++ b/node_modules/@types/lodash/fp/eq.d.ts @@ -0,0 +1,2 @@ +import { eq } from "../fp"; +export = eq; diff --git a/node_modules/@types/lodash/fp/equals.d.ts b/node_modules/@types/lodash/fp/equals.d.ts new file mode 100644 index 0000000..18ec108 --- /dev/null +++ b/node_modules/@types/lodash/fp/equals.d.ts @@ -0,0 +1,2 @@ +import { equals } from "../fp"; +export = equals; diff --git a/node_modules/@types/lodash/fp/escape.d.ts b/node_modules/@types/lodash/fp/escape.d.ts new file mode 100644 index 0000000..36e7e87 --- /dev/null +++ b/node_modules/@types/lodash/fp/escape.d.ts @@ -0,0 +1,2 @@ +import { escape } from "../fp"; +export = escape; diff --git a/node_modules/@types/lodash/fp/escapeRegExp.d.ts b/node_modules/@types/lodash/fp/escapeRegExp.d.ts new file mode 100644 index 0000000..6adc20e --- /dev/null +++ b/node_modules/@types/lodash/fp/escapeRegExp.d.ts @@ -0,0 +1,2 @@ +import { escapeRegExp } from "../fp"; +export = escapeRegExp; diff --git a/node_modules/@types/lodash/fp/every.d.ts b/node_modules/@types/lodash/fp/every.d.ts new file mode 100644 index 0000000..7fbeaf7 --- /dev/null +++ b/node_modules/@types/lodash/fp/every.d.ts @@ -0,0 +1,2 @@ +import { every } from "../fp"; +export = every; diff --git a/node_modules/@types/lodash/fp/extend.d.ts b/node_modules/@types/lodash/fp/extend.d.ts new file mode 100644 index 0000000..cbe294e --- /dev/null +++ b/node_modules/@types/lodash/fp/extend.d.ts @@ -0,0 +1,2 @@ +import { extend } from "../fp"; +export = extend; diff --git a/node_modules/@types/lodash/fp/extendAll.d.ts b/node_modules/@types/lodash/fp/extendAll.d.ts new file mode 100644 index 0000000..92cb3d6 --- /dev/null +++ b/node_modules/@types/lodash/fp/extendAll.d.ts @@ -0,0 +1,2 @@ +import { extendAll } from "../fp"; +export = extendAll; diff --git a/node_modules/@types/lodash/fp/extendAllWith.d.ts b/node_modules/@types/lodash/fp/extendAllWith.d.ts new file mode 100644 index 0000000..712d1d8 --- /dev/null +++ b/node_modules/@types/lodash/fp/extendAllWith.d.ts @@ -0,0 +1,2 @@ +import { extendAllWith } from "../fp"; +export = extendAllWith; diff --git a/node_modules/@types/lodash/fp/extendWith.d.ts b/node_modules/@types/lodash/fp/extendWith.d.ts new file mode 100644 index 0000000..9681360 --- /dev/null +++ b/node_modules/@types/lodash/fp/extendWith.d.ts @@ -0,0 +1,2 @@ +import { extendWith } from "../fp"; +export = extendWith; diff --git a/node_modules/@types/lodash/fp/fill.d.ts b/node_modules/@types/lodash/fp/fill.d.ts new file mode 100644 index 0000000..5778015 --- /dev/null +++ b/node_modules/@types/lodash/fp/fill.d.ts @@ -0,0 +1,2 @@ +import { fill } from "../fp"; +export = fill; diff --git a/node_modules/@types/lodash/fp/filter.d.ts b/node_modules/@types/lodash/fp/filter.d.ts new file mode 100644 index 0000000..8619741 --- /dev/null +++ b/node_modules/@types/lodash/fp/filter.d.ts @@ -0,0 +1,2 @@ +import { filter } from "../fp"; +export = filter; diff --git a/node_modules/@types/lodash/fp/find.d.ts b/node_modules/@types/lodash/fp/find.d.ts new file mode 100644 index 0000000..06418fb --- /dev/null +++ b/node_modules/@types/lodash/fp/find.d.ts @@ -0,0 +1,2 @@ +import { find } from "../fp"; +export = find; diff --git a/node_modules/@types/lodash/fp/findFrom.d.ts b/node_modules/@types/lodash/fp/findFrom.d.ts new file mode 100644 index 0000000..64275d0 --- /dev/null +++ b/node_modules/@types/lodash/fp/findFrom.d.ts @@ -0,0 +1,2 @@ +import { findFrom } from "../fp"; +export = findFrom; diff --git a/node_modules/@types/lodash/fp/findIndex.d.ts b/node_modules/@types/lodash/fp/findIndex.d.ts new file mode 100644 index 0000000..77d1f7b --- /dev/null +++ b/node_modules/@types/lodash/fp/findIndex.d.ts @@ -0,0 +1,2 @@ +import { findIndex } from "../fp"; +export = findIndex; diff --git a/node_modules/@types/lodash/fp/findIndexFrom.d.ts b/node_modules/@types/lodash/fp/findIndexFrom.d.ts new file mode 100644 index 0000000..22330ad --- /dev/null +++ b/node_modules/@types/lodash/fp/findIndexFrom.d.ts @@ -0,0 +1,2 @@ +import { findIndexFrom } from "../fp"; +export = findIndexFrom; diff --git a/node_modules/@types/lodash/fp/findKey.d.ts b/node_modules/@types/lodash/fp/findKey.d.ts new file mode 100644 index 0000000..c5a225a --- /dev/null +++ b/node_modules/@types/lodash/fp/findKey.d.ts @@ -0,0 +1,2 @@ +import { findKey } from "../fp"; +export = findKey; diff --git a/node_modules/@types/lodash/fp/findLast.d.ts b/node_modules/@types/lodash/fp/findLast.d.ts new file mode 100644 index 0000000..b400c94 --- /dev/null +++ b/node_modules/@types/lodash/fp/findLast.d.ts @@ -0,0 +1,2 @@ +import { findLast } from "../fp"; +export = findLast; diff --git a/node_modules/@types/lodash/fp/findLastFrom.d.ts b/node_modules/@types/lodash/fp/findLastFrom.d.ts new file mode 100644 index 0000000..1f034df --- /dev/null +++ b/node_modules/@types/lodash/fp/findLastFrom.d.ts @@ -0,0 +1,2 @@ +import { findLastFrom } from "../fp"; +export = findLastFrom; diff --git a/node_modules/@types/lodash/fp/findLastIndex.d.ts b/node_modules/@types/lodash/fp/findLastIndex.d.ts new file mode 100644 index 0000000..51ee410 --- /dev/null +++ b/node_modules/@types/lodash/fp/findLastIndex.d.ts @@ -0,0 +1,2 @@ +import { findLastIndex } from "../fp"; +export = findLastIndex; diff --git a/node_modules/@types/lodash/fp/findLastIndexFrom.d.ts b/node_modules/@types/lodash/fp/findLastIndexFrom.d.ts new file mode 100644 index 0000000..08bd53a --- /dev/null +++ b/node_modules/@types/lodash/fp/findLastIndexFrom.d.ts @@ -0,0 +1,2 @@ +import { findLastIndexFrom } from "../fp"; +export = findLastIndexFrom; diff --git a/node_modules/@types/lodash/fp/findLastKey.d.ts b/node_modules/@types/lodash/fp/findLastKey.d.ts new file mode 100644 index 0000000..7437a9d --- /dev/null +++ b/node_modules/@types/lodash/fp/findLastKey.d.ts @@ -0,0 +1,2 @@ +import { findLastKey } from "../fp"; +export = findLastKey; diff --git a/node_modules/@types/lodash/fp/first.d.ts b/node_modules/@types/lodash/fp/first.d.ts new file mode 100644 index 0000000..4554ad0 --- /dev/null +++ b/node_modules/@types/lodash/fp/first.d.ts @@ -0,0 +1,2 @@ +import { first } from "../fp"; +export = first; diff --git a/node_modules/@types/lodash/fp/flatMap.d.ts b/node_modules/@types/lodash/fp/flatMap.d.ts new file mode 100644 index 0000000..eb6d804 --- /dev/null +++ b/node_modules/@types/lodash/fp/flatMap.d.ts @@ -0,0 +1,2 @@ +import { flatMap } from "../fp"; +export = flatMap; diff --git a/node_modules/@types/lodash/fp/flatMapDeep.d.ts b/node_modules/@types/lodash/fp/flatMapDeep.d.ts new file mode 100644 index 0000000..0ce4db4 --- /dev/null +++ b/node_modules/@types/lodash/fp/flatMapDeep.d.ts @@ -0,0 +1,2 @@ +import { flatMapDeep } from "../fp"; +export = flatMapDeep; diff --git a/node_modules/@types/lodash/fp/flatMapDepth.d.ts b/node_modules/@types/lodash/fp/flatMapDepth.d.ts new file mode 100644 index 0000000..b60af92 --- /dev/null +++ b/node_modules/@types/lodash/fp/flatMapDepth.d.ts @@ -0,0 +1,2 @@ +import { flatMapDepth } from "../fp"; +export = flatMapDepth; diff --git a/node_modules/@types/lodash/fp/flatten.d.ts b/node_modules/@types/lodash/fp/flatten.d.ts new file mode 100644 index 0000000..02c051f --- /dev/null +++ b/node_modules/@types/lodash/fp/flatten.d.ts @@ -0,0 +1,2 @@ +import { flatten } from "../fp"; +export = flatten; diff --git a/node_modules/@types/lodash/fp/flattenDeep.d.ts b/node_modules/@types/lodash/fp/flattenDeep.d.ts new file mode 100644 index 0000000..44b40e3 --- /dev/null +++ b/node_modules/@types/lodash/fp/flattenDeep.d.ts @@ -0,0 +1,2 @@ +import { flattenDeep } from "../fp"; +export = flattenDeep; diff --git a/node_modules/@types/lodash/fp/flattenDepth.d.ts b/node_modules/@types/lodash/fp/flattenDepth.d.ts new file mode 100644 index 0000000..f046f20 --- /dev/null +++ b/node_modules/@types/lodash/fp/flattenDepth.d.ts @@ -0,0 +1,2 @@ +import { flattenDepth } from "../fp"; +export = flattenDepth; diff --git a/node_modules/@types/lodash/fp/flip.d.ts b/node_modules/@types/lodash/fp/flip.d.ts new file mode 100644 index 0000000..e5b3b7d --- /dev/null +++ b/node_modules/@types/lodash/fp/flip.d.ts @@ -0,0 +1,2 @@ +import { flip } from "../fp"; +export = flip; diff --git a/node_modules/@types/lodash/fp/floor.d.ts b/node_modules/@types/lodash/fp/floor.d.ts new file mode 100644 index 0000000..167ab95 --- /dev/null +++ b/node_modules/@types/lodash/fp/floor.d.ts @@ -0,0 +1,2 @@ +import { floor } from "../fp"; +export = floor; diff --git a/node_modules/@types/lodash/fp/flow.d.ts b/node_modules/@types/lodash/fp/flow.d.ts new file mode 100644 index 0000000..97f0fb8 --- /dev/null +++ b/node_modules/@types/lodash/fp/flow.d.ts @@ -0,0 +1,2 @@ +import { flow } from "../fp"; +export = flow; diff --git a/node_modules/@types/lodash/fp/flowRight.d.ts b/node_modules/@types/lodash/fp/flowRight.d.ts new file mode 100644 index 0000000..f148fea --- /dev/null +++ b/node_modules/@types/lodash/fp/flowRight.d.ts @@ -0,0 +1,2 @@ +import { flowRight } from "../fp"; +export = flowRight; diff --git a/node_modules/@types/lodash/fp/forEach.d.ts b/node_modules/@types/lodash/fp/forEach.d.ts new file mode 100644 index 0000000..f8aa7a4 --- /dev/null +++ b/node_modules/@types/lodash/fp/forEach.d.ts @@ -0,0 +1,2 @@ +import { forEach } from "../fp"; +export = forEach; diff --git a/node_modules/@types/lodash/fp/forEachRight.d.ts b/node_modules/@types/lodash/fp/forEachRight.d.ts new file mode 100644 index 0000000..135a424 --- /dev/null +++ b/node_modules/@types/lodash/fp/forEachRight.d.ts @@ -0,0 +1,2 @@ +import { forEachRight } from "../fp"; +export = forEachRight; diff --git a/node_modules/@types/lodash/fp/forIn.d.ts b/node_modules/@types/lodash/fp/forIn.d.ts new file mode 100644 index 0000000..dab37b1 --- /dev/null +++ b/node_modules/@types/lodash/fp/forIn.d.ts @@ -0,0 +1,2 @@ +import { forIn } from "../fp"; +export = forIn; diff --git a/node_modules/@types/lodash/fp/forInRight.d.ts b/node_modules/@types/lodash/fp/forInRight.d.ts new file mode 100644 index 0000000..c560df0 --- /dev/null +++ b/node_modules/@types/lodash/fp/forInRight.d.ts @@ -0,0 +1,2 @@ +import { forInRight } from "../fp"; +export = forInRight; diff --git a/node_modules/@types/lodash/fp/forOwn.d.ts b/node_modules/@types/lodash/fp/forOwn.d.ts new file mode 100644 index 0000000..7099c48 --- /dev/null +++ b/node_modules/@types/lodash/fp/forOwn.d.ts @@ -0,0 +1,2 @@ +import { forOwn } from "../fp"; +export = forOwn; diff --git a/node_modules/@types/lodash/fp/forOwnRight.d.ts b/node_modules/@types/lodash/fp/forOwnRight.d.ts new file mode 100644 index 0000000..f1e3928 --- /dev/null +++ b/node_modules/@types/lodash/fp/forOwnRight.d.ts @@ -0,0 +1,2 @@ +import { forOwnRight } from "../fp"; +export = forOwnRight; diff --git a/node_modules/@types/lodash/fp/fromPairs.d.ts b/node_modules/@types/lodash/fp/fromPairs.d.ts new file mode 100644 index 0000000..b0d0082 --- /dev/null +++ b/node_modules/@types/lodash/fp/fromPairs.d.ts @@ -0,0 +1,2 @@ +import { fromPairs } from "../fp"; +export = fromPairs; diff --git a/node_modules/@types/lodash/fp/functions.d.ts b/node_modules/@types/lodash/fp/functions.d.ts new file mode 100644 index 0000000..727d68e --- /dev/null +++ b/node_modules/@types/lodash/fp/functions.d.ts @@ -0,0 +1,2 @@ +import { functions } from "../fp"; +export = functions; diff --git a/node_modules/@types/lodash/fp/functionsIn.d.ts b/node_modules/@types/lodash/fp/functionsIn.d.ts new file mode 100644 index 0000000..448746e --- /dev/null +++ b/node_modules/@types/lodash/fp/functionsIn.d.ts @@ -0,0 +1,2 @@ +import { functionsIn } from "../fp"; +export = functionsIn; diff --git a/node_modules/@types/lodash/fp/get.d.ts b/node_modules/@types/lodash/fp/get.d.ts new file mode 100644 index 0000000..ff3ab8b --- /dev/null +++ b/node_modules/@types/lodash/fp/get.d.ts @@ -0,0 +1,2 @@ +import { get } from "../fp"; +export = get; diff --git a/node_modules/@types/lodash/fp/getOr.d.ts b/node_modules/@types/lodash/fp/getOr.d.ts new file mode 100644 index 0000000..ce3d5bb --- /dev/null +++ b/node_modules/@types/lodash/fp/getOr.d.ts @@ -0,0 +1,2 @@ +import { getOr } from "../fp"; +export = getOr; diff --git a/node_modules/@types/lodash/fp/groupBy.d.ts b/node_modules/@types/lodash/fp/groupBy.d.ts new file mode 100644 index 0000000..813830a --- /dev/null +++ b/node_modules/@types/lodash/fp/groupBy.d.ts @@ -0,0 +1,2 @@ +import { groupBy } from "../fp"; +export = groupBy; diff --git a/node_modules/@types/lodash/fp/gt.d.ts b/node_modules/@types/lodash/fp/gt.d.ts new file mode 100644 index 0000000..517071f --- /dev/null +++ b/node_modules/@types/lodash/fp/gt.d.ts @@ -0,0 +1,2 @@ +import { gt } from "../fp"; +export = gt; diff --git a/node_modules/@types/lodash/fp/gte.d.ts b/node_modules/@types/lodash/fp/gte.d.ts new file mode 100644 index 0000000..5f6d85c --- /dev/null +++ b/node_modules/@types/lodash/fp/gte.d.ts @@ -0,0 +1,2 @@ +import { gte } from "../fp"; +export = gte; diff --git a/node_modules/@types/lodash/fp/has.d.ts b/node_modules/@types/lodash/fp/has.d.ts new file mode 100644 index 0000000..8cbda7f --- /dev/null +++ b/node_modules/@types/lodash/fp/has.d.ts @@ -0,0 +1,2 @@ +import { has } from "../fp"; +export = has; diff --git a/node_modules/@types/lodash/fp/hasIn.d.ts b/node_modules/@types/lodash/fp/hasIn.d.ts new file mode 100644 index 0000000..7e06a87 --- /dev/null +++ b/node_modules/@types/lodash/fp/hasIn.d.ts @@ -0,0 +1,2 @@ +import { hasIn } from "../fp"; +export = hasIn; diff --git a/node_modules/@types/lodash/fp/head.d.ts b/node_modules/@types/lodash/fp/head.d.ts new file mode 100644 index 0000000..4a7d5e5 --- /dev/null +++ b/node_modules/@types/lodash/fp/head.d.ts @@ -0,0 +1,2 @@ +import { head } from "../fp"; +export = head; diff --git a/node_modules/@types/lodash/fp/identical.d.ts b/node_modules/@types/lodash/fp/identical.d.ts new file mode 100644 index 0000000..954dff5 --- /dev/null +++ b/node_modules/@types/lodash/fp/identical.d.ts @@ -0,0 +1,2 @@ +import { identical } from "../fp"; +export = identical; diff --git a/node_modules/@types/lodash/fp/identity.d.ts b/node_modules/@types/lodash/fp/identity.d.ts new file mode 100644 index 0000000..97e613c --- /dev/null +++ b/node_modules/@types/lodash/fp/identity.d.ts @@ -0,0 +1,2 @@ +import { identity } from "../fp"; +export = identity; diff --git a/node_modules/@types/lodash/fp/inRange.d.ts b/node_modules/@types/lodash/fp/inRange.d.ts new file mode 100644 index 0000000..06ed312 --- /dev/null +++ b/node_modules/@types/lodash/fp/inRange.d.ts @@ -0,0 +1,2 @@ +import { inRange } from "../fp"; +export = inRange; diff --git a/node_modules/@types/lodash/fp/includes.d.ts b/node_modules/@types/lodash/fp/includes.d.ts new file mode 100644 index 0000000..afc9984 --- /dev/null +++ b/node_modules/@types/lodash/fp/includes.d.ts @@ -0,0 +1,2 @@ +import { includes } from "../fp"; +export = includes; diff --git a/node_modules/@types/lodash/fp/includesFrom.d.ts b/node_modules/@types/lodash/fp/includesFrom.d.ts new file mode 100644 index 0000000..13042d0 --- /dev/null +++ b/node_modules/@types/lodash/fp/includesFrom.d.ts @@ -0,0 +1,2 @@ +import { includesFrom } from "../fp"; +export = includesFrom; diff --git a/node_modules/@types/lodash/fp/indexBy.d.ts b/node_modules/@types/lodash/fp/indexBy.d.ts new file mode 100644 index 0000000..f3f75a4 --- /dev/null +++ b/node_modules/@types/lodash/fp/indexBy.d.ts @@ -0,0 +1,2 @@ +import { indexBy } from "../fp"; +export = indexBy; diff --git a/node_modules/@types/lodash/fp/indexOf.d.ts b/node_modules/@types/lodash/fp/indexOf.d.ts new file mode 100644 index 0000000..8078c46 --- /dev/null +++ b/node_modules/@types/lodash/fp/indexOf.d.ts @@ -0,0 +1,2 @@ +import { indexOf } from "../fp"; +export = indexOf; diff --git a/node_modules/@types/lodash/fp/indexOfFrom.d.ts b/node_modules/@types/lodash/fp/indexOfFrom.d.ts new file mode 100644 index 0000000..fe66609 --- /dev/null +++ b/node_modules/@types/lodash/fp/indexOfFrom.d.ts @@ -0,0 +1,2 @@ +import { indexOfFrom } from "../fp"; +export = indexOfFrom; diff --git a/node_modules/@types/lodash/fp/init.d.ts b/node_modules/@types/lodash/fp/init.d.ts new file mode 100644 index 0000000..2f37ecd --- /dev/null +++ b/node_modules/@types/lodash/fp/init.d.ts @@ -0,0 +1,2 @@ +import { init } from "../fp"; +export = init; diff --git a/node_modules/@types/lodash/fp/initial.d.ts b/node_modules/@types/lodash/fp/initial.d.ts new file mode 100644 index 0000000..446da06 --- /dev/null +++ b/node_modules/@types/lodash/fp/initial.d.ts @@ -0,0 +1,2 @@ +import { initial } from "../fp"; +export = initial; diff --git a/node_modules/@types/lodash/fp/intersection.d.ts b/node_modules/@types/lodash/fp/intersection.d.ts new file mode 100644 index 0000000..41d7915 --- /dev/null +++ b/node_modules/@types/lodash/fp/intersection.d.ts @@ -0,0 +1,2 @@ +import { intersection } from "../fp"; +export = intersection; diff --git a/node_modules/@types/lodash/fp/intersectionBy.d.ts b/node_modules/@types/lodash/fp/intersectionBy.d.ts new file mode 100644 index 0000000..a123ddd --- /dev/null +++ b/node_modules/@types/lodash/fp/intersectionBy.d.ts @@ -0,0 +1,2 @@ +import { intersectionBy } from "../fp"; +export = intersectionBy; diff --git a/node_modules/@types/lodash/fp/intersectionWith.d.ts b/node_modules/@types/lodash/fp/intersectionWith.d.ts new file mode 100644 index 0000000..9ad9941 --- /dev/null +++ b/node_modules/@types/lodash/fp/intersectionWith.d.ts @@ -0,0 +1,2 @@ +import { intersectionWith } from "../fp"; +export = intersectionWith; diff --git a/node_modules/@types/lodash/fp/invert.d.ts b/node_modules/@types/lodash/fp/invert.d.ts new file mode 100644 index 0000000..a41c2bc --- /dev/null +++ b/node_modules/@types/lodash/fp/invert.d.ts @@ -0,0 +1,2 @@ +import { invert } from "../fp"; +export = invert; diff --git a/node_modules/@types/lodash/fp/invertBy.d.ts b/node_modules/@types/lodash/fp/invertBy.d.ts new file mode 100644 index 0000000..e28f713 --- /dev/null +++ b/node_modules/@types/lodash/fp/invertBy.d.ts @@ -0,0 +1,2 @@ +import { invertBy } from "../fp"; +export = invertBy; diff --git a/node_modules/@types/lodash/fp/invertObj.d.ts b/node_modules/@types/lodash/fp/invertObj.d.ts new file mode 100644 index 0000000..2e16c4f --- /dev/null +++ b/node_modules/@types/lodash/fp/invertObj.d.ts @@ -0,0 +1,2 @@ +import { invertObj } from "../fp"; +export = invertObj; diff --git a/node_modules/@types/lodash/fp/invoke.d.ts b/node_modules/@types/lodash/fp/invoke.d.ts new file mode 100644 index 0000000..1a9ce3b --- /dev/null +++ b/node_modules/@types/lodash/fp/invoke.d.ts @@ -0,0 +1,2 @@ +import { invoke } from "../fp"; +export = invoke; diff --git a/node_modules/@types/lodash/fp/invokeArgs.d.ts b/node_modules/@types/lodash/fp/invokeArgs.d.ts new file mode 100644 index 0000000..8b498e0 --- /dev/null +++ b/node_modules/@types/lodash/fp/invokeArgs.d.ts @@ -0,0 +1,2 @@ +import { invokeArgs } from "../fp"; +export = invokeArgs; diff --git a/node_modules/@types/lodash/fp/invokeArgsMap.d.ts b/node_modules/@types/lodash/fp/invokeArgsMap.d.ts new file mode 100644 index 0000000..f5ba3e7 --- /dev/null +++ b/node_modules/@types/lodash/fp/invokeArgsMap.d.ts @@ -0,0 +1,2 @@ +import { invokeArgsMap } from "../fp"; +export = invokeArgsMap; diff --git a/node_modules/@types/lodash/fp/invokeMap.d.ts b/node_modules/@types/lodash/fp/invokeMap.d.ts new file mode 100644 index 0000000..9f0aea9 --- /dev/null +++ b/node_modules/@types/lodash/fp/invokeMap.d.ts @@ -0,0 +1,2 @@ +import { invokeMap } from "../fp"; +export = invokeMap; diff --git a/node_modules/@types/lodash/fp/isArguments.d.ts b/node_modules/@types/lodash/fp/isArguments.d.ts new file mode 100644 index 0000000..23c438c --- /dev/null +++ b/node_modules/@types/lodash/fp/isArguments.d.ts @@ -0,0 +1,2 @@ +import { isArguments } from "../fp"; +export = isArguments; diff --git a/node_modules/@types/lodash/fp/isArray.d.ts b/node_modules/@types/lodash/fp/isArray.d.ts new file mode 100644 index 0000000..dadecce --- /dev/null +++ b/node_modules/@types/lodash/fp/isArray.d.ts @@ -0,0 +1,2 @@ +import { isArray } from "../fp"; +export = isArray; diff --git a/node_modules/@types/lodash/fp/isArrayBuffer.d.ts b/node_modules/@types/lodash/fp/isArrayBuffer.d.ts new file mode 100644 index 0000000..3201834 --- /dev/null +++ b/node_modules/@types/lodash/fp/isArrayBuffer.d.ts @@ -0,0 +1,2 @@ +import { isArrayBuffer } from "../fp"; +export = isArrayBuffer; diff --git a/node_modules/@types/lodash/fp/isArrayLike.d.ts b/node_modules/@types/lodash/fp/isArrayLike.d.ts new file mode 100644 index 0000000..2be9b54 --- /dev/null +++ b/node_modules/@types/lodash/fp/isArrayLike.d.ts @@ -0,0 +1,2 @@ +import { isArrayLike } from "../fp"; +export = isArrayLike; diff --git a/node_modules/@types/lodash/fp/isArrayLikeObject.d.ts b/node_modules/@types/lodash/fp/isArrayLikeObject.d.ts new file mode 100644 index 0000000..709f513 --- /dev/null +++ b/node_modules/@types/lodash/fp/isArrayLikeObject.d.ts @@ -0,0 +1,2 @@ +import { isArrayLikeObject } from "../fp"; +export = isArrayLikeObject; diff --git a/node_modules/@types/lodash/fp/isBoolean.d.ts b/node_modules/@types/lodash/fp/isBoolean.d.ts new file mode 100644 index 0000000..605cb2c --- /dev/null +++ b/node_modules/@types/lodash/fp/isBoolean.d.ts @@ -0,0 +1,2 @@ +import { isBoolean } from "../fp"; +export = isBoolean; diff --git a/node_modules/@types/lodash/fp/isBuffer.d.ts b/node_modules/@types/lodash/fp/isBuffer.d.ts new file mode 100644 index 0000000..3d06b54 --- /dev/null +++ b/node_modules/@types/lodash/fp/isBuffer.d.ts @@ -0,0 +1,2 @@ +import { isBuffer } from "../fp"; +export = isBuffer; diff --git a/node_modules/@types/lodash/fp/isDate.d.ts b/node_modules/@types/lodash/fp/isDate.d.ts new file mode 100644 index 0000000..979594f --- /dev/null +++ b/node_modules/@types/lodash/fp/isDate.d.ts @@ -0,0 +1,2 @@ +import { isDate } from "../fp"; +export = isDate; diff --git a/node_modules/@types/lodash/fp/isElement.d.ts b/node_modules/@types/lodash/fp/isElement.d.ts new file mode 100644 index 0000000..26739ad --- /dev/null +++ b/node_modules/@types/lodash/fp/isElement.d.ts @@ -0,0 +1,2 @@ +import { isElement } from "../fp"; +export = isElement; diff --git a/node_modules/@types/lodash/fp/isEmpty.d.ts b/node_modules/@types/lodash/fp/isEmpty.d.ts new file mode 100644 index 0000000..ed9b33f --- /dev/null +++ b/node_modules/@types/lodash/fp/isEmpty.d.ts @@ -0,0 +1,2 @@ +import { isEmpty } from "../fp"; +export = isEmpty; diff --git a/node_modules/@types/lodash/fp/isEqual.d.ts b/node_modules/@types/lodash/fp/isEqual.d.ts new file mode 100644 index 0000000..0a51c5c --- /dev/null +++ b/node_modules/@types/lodash/fp/isEqual.d.ts @@ -0,0 +1,2 @@ +import { isEqual } from "../fp"; +export = isEqual; diff --git a/node_modules/@types/lodash/fp/isEqualWith.d.ts b/node_modules/@types/lodash/fp/isEqualWith.d.ts new file mode 100644 index 0000000..27fa441 --- /dev/null +++ b/node_modules/@types/lodash/fp/isEqualWith.d.ts @@ -0,0 +1,2 @@ +import { isEqualWith } from "../fp"; +export = isEqualWith; diff --git a/node_modules/@types/lodash/fp/isError.d.ts b/node_modules/@types/lodash/fp/isError.d.ts new file mode 100644 index 0000000..4adb988 --- /dev/null +++ b/node_modules/@types/lodash/fp/isError.d.ts @@ -0,0 +1,2 @@ +import { isError } from "../fp"; +export = isError; diff --git a/node_modules/@types/lodash/fp/isFinite.d.ts b/node_modules/@types/lodash/fp/isFinite.d.ts new file mode 100644 index 0000000..5641edc --- /dev/null +++ b/node_modules/@types/lodash/fp/isFinite.d.ts @@ -0,0 +1,2 @@ +import { isFinite } from "../fp"; +export = isFinite; diff --git a/node_modules/@types/lodash/fp/isFunction.d.ts b/node_modules/@types/lodash/fp/isFunction.d.ts new file mode 100644 index 0000000..3404e74 --- /dev/null +++ b/node_modules/@types/lodash/fp/isFunction.d.ts @@ -0,0 +1,2 @@ +import { isFunction } from "../fp"; +export = isFunction; diff --git a/node_modules/@types/lodash/fp/isInteger.d.ts b/node_modules/@types/lodash/fp/isInteger.d.ts new file mode 100644 index 0000000..310df93 --- /dev/null +++ b/node_modules/@types/lodash/fp/isInteger.d.ts @@ -0,0 +1,2 @@ +import { isInteger } from "../fp"; +export = isInteger; diff --git a/node_modules/@types/lodash/fp/isLength.d.ts b/node_modules/@types/lodash/fp/isLength.d.ts new file mode 100644 index 0000000..3073b67 --- /dev/null +++ b/node_modules/@types/lodash/fp/isLength.d.ts @@ -0,0 +1,2 @@ +import { isLength } from "../fp"; +export = isLength; diff --git a/node_modules/@types/lodash/fp/isMap.d.ts b/node_modules/@types/lodash/fp/isMap.d.ts new file mode 100644 index 0000000..e76745c --- /dev/null +++ b/node_modules/@types/lodash/fp/isMap.d.ts @@ -0,0 +1,2 @@ +import { isMap } from "../fp"; +export = isMap; diff --git a/node_modules/@types/lodash/fp/isMatch.d.ts b/node_modules/@types/lodash/fp/isMatch.d.ts new file mode 100644 index 0000000..58a0a2d --- /dev/null +++ b/node_modules/@types/lodash/fp/isMatch.d.ts @@ -0,0 +1,2 @@ +import { isMatch } from "../fp"; +export = isMatch; diff --git a/node_modules/@types/lodash/fp/isMatchWith.d.ts b/node_modules/@types/lodash/fp/isMatchWith.d.ts new file mode 100644 index 0000000..40ff3a6 --- /dev/null +++ b/node_modules/@types/lodash/fp/isMatchWith.d.ts @@ -0,0 +1,2 @@ +import { isMatchWith } from "../fp"; +export = isMatchWith; diff --git a/node_modules/@types/lodash/fp/isNaN.d.ts b/node_modules/@types/lodash/fp/isNaN.d.ts new file mode 100644 index 0000000..2f92885 --- /dev/null +++ b/node_modules/@types/lodash/fp/isNaN.d.ts @@ -0,0 +1,2 @@ +import { isNaN } from "../fp"; +export = isNaN; diff --git a/node_modules/@types/lodash/fp/isNative.d.ts b/node_modules/@types/lodash/fp/isNative.d.ts new file mode 100644 index 0000000..6e189a8 --- /dev/null +++ b/node_modules/@types/lodash/fp/isNative.d.ts @@ -0,0 +1,2 @@ +import { isNative } from "../fp"; +export = isNative; diff --git a/node_modules/@types/lodash/fp/isNil.d.ts b/node_modules/@types/lodash/fp/isNil.d.ts new file mode 100644 index 0000000..0baee7f --- /dev/null +++ b/node_modules/@types/lodash/fp/isNil.d.ts @@ -0,0 +1,2 @@ +import { isNil } from "../fp"; +export = isNil; diff --git a/node_modules/@types/lodash/fp/isNull.d.ts b/node_modules/@types/lodash/fp/isNull.d.ts new file mode 100644 index 0000000..5e5fad5 --- /dev/null +++ b/node_modules/@types/lodash/fp/isNull.d.ts @@ -0,0 +1,2 @@ +import { isNull } from "../fp"; +export = isNull; diff --git a/node_modules/@types/lodash/fp/isNumber.d.ts b/node_modules/@types/lodash/fp/isNumber.d.ts new file mode 100644 index 0000000..93368f1 --- /dev/null +++ b/node_modules/@types/lodash/fp/isNumber.d.ts @@ -0,0 +1,2 @@ +import { isNumber } from "../fp"; +export = isNumber; diff --git a/node_modules/@types/lodash/fp/isObject.d.ts b/node_modules/@types/lodash/fp/isObject.d.ts new file mode 100644 index 0000000..7e9e257 --- /dev/null +++ b/node_modules/@types/lodash/fp/isObject.d.ts @@ -0,0 +1,2 @@ +import { isObject } from "../fp"; +export = isObject; diff --git a/node_modules/@types/lodash/fp/isObjectLike.d.ts b/node_modules/@types/lodash/fp/isObjectLike.d.ts new file mode 100644 index 0000000..ba03ddc --- /dev/null +++ b/node_modules/@types/lodash/fp/isObjectLike.d.ts @@ -0,0 +1,2 @@ +import { isObjectLike } from "../fp"; +export = isObjectLike; diff --git a/node_modules/@types/lodash/fp/isPlainObject.d.ts b/node_modules/@types/lodash/fp/isPlainObject.d.ts new file mode 100644 index 0000000..87da4bd --- /dev/null +++ b/node_modules/@types/lodash/fp/isPlainObject.d.ts @@ -0,0 +1,2 @@ +import { isPlainObject } from "../fp"; +export = isPlainObject; diff --git a/node_modules/@types/lodash/fp/isRegExp.d.ts b/node_modules/@types/lodash/fp/isRegExp.d.ts new file mode 100644 index 0000000..47edf50 --- /dev/null +++ b/node_modules/@types/lodash/fp/isRegExp.d.ts @@ -0,0 +1,2 @@ +import { isRegExp } from "../fp"; +export = isRegExp; diff --git a/node_modules/@types/lodash/fp/isSafeInteger.d.ts b/node_modules/@types/lodash/fp/isSafeInteger.d.ts new file mode 100644 index 0000000..a32b12c --- /dev/null +++ b/node_modules/@types/lodash/fp/isSafeInteger.d.ts @@ -0,0 +1,2 @@ +import { isSafeInteger } from "../fp"; +export = isSafeInteger; diff --git a/node_modules/@types/lodash/fp/isSet.d.ts b/node_modules/@types/lodash/fp/isSet.d.ts new file mode 100644 index 0000000..85e4933 --- /dev/null +++ b/node_modules/@types/lodash/fp/isSet.d.ts @@ -0,0 +1,2 @@ +import { isSet } from "../fp"; +export = isSet; diff --git a/node_modules/@types/lodash/fp/isString.d.ts b/node_modules/@types/lodash/fp/isString.d.ts new file mode 100644 index 0000000..9a21494 --- /dev/null +++ b/node_modules/@types/lodash/fp/isString.d.ts @@ -0,0 +1,2 @@ +import { isString } from "../fp"; +export = isString; diff --git a/node_modules/@types/lodash/fp/isSymbol.d.ts b/node_modules/@types/lodash/fp/isSymbol.d.ts new file mode 100644 index 0000000..3d82e97 --- /dev/null +++ b/node_modules/@types/lodash/fp/isSymbol.d.ts @@ -0,0 +1,2 @@ +import { isSymbol } from "../fp"; +export = isSymbol; diff --git a/node_modules/@types/lodash/fp/isTypedArray.d.ts b/node_modules/@types/lodash/fp/isTypedArray.d.ts new file mode 100644 index 0000000..fce6c44 --- /dev/null +++ b/node_modules/@types/lodash/fp/isTypedArray.d.ts @@ -0,0 +1,2 @@ +import { isTypedArray } from "../fp"; +export = isTypedArray; diff --git a/node_modules/@types/lodash/fp/isUndefined.d.ts b/node_modules/@types/lodash/fp/isUndefined.d.ts new file mode 100644 index 0000000..ccb0100 --- /dev/null +++ b/node_modules/@types/lodash/fp/isUndefined.d.ts @@ -0,0 +1,2 @@ +import { isUndefined } from "../fp"; +export = isUndefined; diff --git a/node_modules/@types/lodash/fp/isWeakMap.d.ts b/node_modules/@types/lodash/fp/isWeakMap.d.ts new file mode 100644 index 0000000..11edaab --- /dev/null +++ b/node_modules/@types/lodash/fp/isWeakMap.d.ts @@ -0,0 +1,2 @@ +import { isWeakMap } from "../fp"; +export = isWeakMap; diff --git a/node_modules/@types/lodash/fp/isWeakSet.d.ts b/node_modules/@types/lodash/fp/isWeakSet.d.ts new file mode 100644 index 0000000..6d877e9 --- /dev/null +++ b/node_modules/@types/lodash/fp/isWeakSet.d.ts @@ -0,0 +1,2 @@ +import { isWeakSet } from "../fp"; +export = isWeakSet; diff --git a/node_modules/@types/lodash/fp/iteratee.d.ts b/node_modules/@types/lodash/fp/iteratee.d.ts new file mode 100644 index 0000000..0ec2832 --- /dev/null +++ b/node_modules/@types/lodash/fp/iteratee.d.ts @@ -0,0 +1,2 @@ +import { iteratee } from "../fp"; +export = iteratee; diff --git a/node_modules/@types/lodash/fp/join.d.ts b/node_modules/@types/lodash/fp/join.d.ts new file mode 100644 index 0000000..beee04c --- /dev/null +++ b/node_modules/@types/lodash/fp/join.d.ts @@ -0,0 +1,2 @@ +import { join } from "../fp"; +export = join; diff --git a/node_modules/@types/lodash/fp/juxt.d.ts b/node_modules/@types/lodash/fp/juxt.d.ts new file mode 100644 index 0000000..5e972d4 --- /dev/null +++ b/node_modules/@types/lodash/fp/juxt.d.ts @@ -0,0 +1,2 @@ +import { juxt } from "../fp"; +export = juxt; diff --git a/node_modules/@types/lodash/fp/kebabCase.d.ts b/node_modules/@types/lodash/fp/kebabCase.d.ts new file mode 100644 index 0000000..8231b15 --- /dev/null +++ b/node_modules/@types/lodash/fp/kebabCase.d.ts @@ -0,0 +1,2 @@ +import { kebabCase } from "../fp"; +export = kebabCase; diff --git a/node_modules/@types/lodash/fp/keyBy.d.ts b/node_modules/@types/lodash/fp/keyBy.d.ts new file mode 100644 index 0000000..e4b1381 --- /dev/null +++ b/node_modules/@types/lodash/fp/keyBy.d.ts @@ -0,0 +1,2 @@ +import { keyBy } from "../fp"; +export = keyBy; diff --git a/node_modules/@types/lodash/fp/keys.d.ts b/node_modules/@types/lodash/fp/keys.d.ts new file mode 100644 index 0000000..0323484 --- /dev/null +++ b/node_modules/@types/lodash/fp/keys.d.ts @@ -0,0 +1,2 @@ +import { keys } from "../fp"; +export = keys; diff --git a/node_modules/@types/lodash/fp/keysIn.d.ts b/node_modules/@types/lodash/fp/keysIn.d.ts new file mode 100644 index 0000000..f6f3482 --- /dev/null +++ b/node_modules/@types/lodash/fp/keysIn.d.ts @@ -0,0 +1,2 @@ +import { keysIn } from "../fp"; +export = keysIn; diff --git a/node_modules/@types/lodash/fp/last.d.ts b/node_modules/@types/lodash/fp/last.d.ts new file mode 100644 index 0000000..f74171a --- /dev/null +++ b/node_modules/@types/lodash/fp/last.d.ts @@ -0,0 +1,2 @@ +import { last } from "../fp"; +export = last; diff --git a/node_modules/@types/lodash/fp/lastIndexOf.d.ts b/node_modules/@types/lodash/fp/lastIndexOf.d.ts new file mode 100644 index 0000000..2d60e64 --- /dev/null +++ b/node_modules/@types/lodash/fp/lastIndexOf.d.ts @@ -0,0 +1,2 @@ +import { lastIndexOf } from "../fp"; +export = lastIndexOf; diff --git a/node_modules/@types/lodash/fp/lastIndexOfFrom.d.ts b/node_modules/@types/lodash/fp/lastIndexOfFrom.d.ts new file mode 100644 index 0000000..7a2f23e --- /dev/null +++ b/node_modules/@types/lodash/fp/lastIndexOfFrom.d.ts @@ -0,0 +1,2 @@ +import { lastIndexOfFrom } from "../fp"; +export = lastIndexOfFrom; diff --git a/node_modules/@types/lodash/fp/lowerCase.d.ts b/node_modules/@types/lodash/fp/lowerCase.d.ts new file mode 100644 index 0000000..1a5360f --- /dev/null +++ b/node_modules/@types/lodash/fp/lowerCase.d.ts @@ -0,0 +1,2 @@ +import { lowerCase } from "../fp"; +export = lowerCase; diff --git a/node_modules/@types/lodash/fp/lowerFirst.d.ts b/node_modules/@types/lodash/fp/lowerFirst.d.ts new file mode 100644 index 0000000..23ce925 --- /dev/null +++ b/node_modules/@types/lodash/fp/lowerFirst.d.ts @@ -0,0 +1,2 @@ +import { lowerFirst } from "../fp"; +export = lowerFirst; diff --git a/node_modules/@types/lodash/fp/lt.d.ts b/node_modules/@types/lodash/fp/lt.d.ts new file mode 100644 index 0000000..a309bdc --- /dev/null +++ b/node_modules/@types/lodash/fp/lt.d.ts @@ -0,0 +1,2 @@ +import { lt } from "../fp"; +export = lt; diff --git a/node_modules/@types/lodash/fp/lte.d.ts b/node_modules/@types/lodash/fp/lte.d.ts new file mode 100644 index 0000000..0d4af2c --- /dev/null +++ b/node_modules/@types/lodash/fp/lte.d.ts @@ -0,0 +1,2 @@ +import { lte } from "../fp"; +export = lte; diff --git a/node_modules/@types/lodash/fp/map.d.ts b/node_modules/@types/lodash/fp/map.d.ts new file mode 100644 index 0000000..17d014c --- /dev/null +++ b/node_modules/@types/lodash/fp/map.d.ts @@ -0,0 +1,2 @@ +import { map } from "../fp"; +export = map; diff --git a/node_modules/@types/lodash/fp/mapKeys.d.ts b/node_modules/@types/lodash/fp/mapKeys.d.ts new file mode 100644 index 0000000..acc6d75 --- /dev/null +++ b/node_modules/@types/lodash/fp/mapKeys.d.ts @@ -0,0 +1,2 @@ +import { mapKeys } from "../fp"; +export = mapKeys; diff --git a/node_modules/@types/lodash/fp/mapValues.d.ts b/node_modules/@types/lodash/fp/mapValues.d.ts new file mode 100644 index 0000000..abef821 --- /dev/null +++ b/node_modules/@types/lodash/fp/mapValues.d.ts @@ -0,0 +1,2 @@ +import { mapValues } from "../fp"; +export = mapValues; diff --git a/node_modules/@types/lodash/fp/matches.d.ts b/node_modules/@types/lodash/fp/matches.d.ts new file mode 100644 index 0000000..e9796de --- /dev/null +++ b/node_modules/@types/lodash/fp/matches.d.ts @@ -0,0 +1,2 @@ +import { matches } from "../fp"; +export = matches; diff --git a/node_modules/@types/lodash/fp/matchesProperty.d.ts b/node_modules/@types/lodash/fp/matchesProperty.d.ts new file mode 100644 index 0000000..81db8f7 --- /dev/null +++ b/node_modules/@types/lodash/fp/matchesProperty.d.ts @@ -0,0 +1,2 @@ +import { matchesProperty } from "../fp"; +export = matchesProperty; diff --git a/node_modules/@types/lodash/fp/max.d.ts b/node_modules/@types/lodash/fp/max.d.ts new file mode 100644 index 0000000..7b08dc5 --- /dev/null +++ b/node_modules/@types/lodash/fp/max.d.ts @@ -0,0 +1,2 @@ +import { max } from "../fp"; +export = max; diff --git a/node_modules/@types/lodash/fp/maxBy.d.ts b/node_modules/@types/lodash/fp/maxBy.d.ts new file mode 100644 index 0000000..68f30dd --- /dev/null +++ b/node_modules/@types/lodash/fp/maxBy.d.ts @@ -0,0 +1,2 @@ +import { maxBy } from "../fp"; +export = maxBy; diff --git a/node_modules/@types/lodash/fp/mean.d.ts b/node_modules/@types/lodash/fp/mean.d.ts new file mode 100644 index 0000000..a0b7e22 --- /dev/null +++ b/node_modules/@types/lodash/fp/mean.d.ts @@ -0,0 +1,2 @@ +import { mean } from "../fp"; +export = mean; diff --git a/node_modules/@types/lodash/fp/meanBy.d.ts b/node_modules/@types/lodash/fp/meanBy.d.ts new file mode 100644 index 0000000..d76afd7 --- /dev/null +++ b/node_modules/@types/lodash/fp/meanBy.d.ts @@ -0,0 +1,2 @@ +import { meanBy } from "../fp"; +export = meanBy; diff --git a/node_modules/@types/lodash/fp/memoize.d.ts b/node_modules/@types/lodash/fp/memoize.d.ts new file mode 100644 index 0000000..a60b79c --- /dev/null +++ b/node_modules/@types/lodash/fp/memoize.d.ts @@ -0,0 +1,2 @@ +import { memoize } from "../fp"; +export = memoize; diff --git a/node_modules/@types/lodash/fp/merge.d.ts b/node_modules/@types/lodash/fp/merge.d.ts new file mode 100644 index 0000000..f80117b --- /dev/null +++ b/node_modules/@types/lodash/fp/merge.d.ts @@ -0,0 +1,2 @@ +import { merge } from "../fp"; +export = merge; diff --git a/node_modules/@types/lodash/fp/mergeAll.d.ts b/node_modules/@types/lodash/fp/mergeAll.d.ts new file mode 100644 index 0000000..6b462d8 --- /dev/null +++ b/node_modules/@types/lodash/fp/mergeAll.d.ts @@ -0,0 +1,2 @@ +import { mergeAll } from "../fp"; +export = mergeAll; diff --git a/node_modules/@types/lodash/fp/mergeAllWith.d.ts b/node_modules/@types/lodash/fp/mergeAllWith.d.ts new file mode 100644 index 0000000..3d2f7f2 --- /dev/null +++ b/node_modules/@types/lodash/fp/mergeAllWith.d.ts @@ -0,0 +1,2 @@ +import { mergeAllWith } from "../fp"; +export = mergeAllWith; diff --git a/node_modules/@types/lodash/fp/mergeWith.d.ts b/node_modules/@types/lodash/fp/mergeWith.d.ts new file mode 100644 index 0000000..d1f541e --- /dev/null +++ b/node_modules/@types/lodash/fp/mergeWith.d.ts @@ -0,0 +1,2 @@ +import { mergeWith } from "../fp"; +export = mergeWith; diff --git a/node_modules/@types/lodash/fp/method.d.ts b/node_modules/@types/lodash/fp/method.d.ts new file mode 100644 index 0000000..f9f2ee8 --- /dev/null +++ b/node_modules/@types/lodash/fp/method.d.ts @@ -0,0 +1,2 @@ +import { method } from "../fp"; +export = method; diff --git a/node_modules/@types/lodash/fp/methodOf.d.ts b/node_modules/@types/lodash/fp/methodOf.d.ts new file mode 100644 index 0000000..a9e0e4f --- /dev/null +++ b/node_modules/@types/lodash/fp/methodOf.d.ts @@ -0,0 +1,2 @@ +import { methodOf } from "../fp"; +export = methodOf; diff --git a/node_modules/@types/lodash/fp/min.d.ts b/node_modules/@types/lodash/fp/min.d.ts new file mode 100644 index 0000000..7c80ab0 --- /dev/null +++ b/node_modules/@types/lodash/fp/min.d.ts @@ -0,0 +1,2 @@ +import { min } from "../fp"; +export = min; diff --git a/node_modules/@types/lodash/fp/minBy.d.ts b/node_modules/@types/lodash/fp/minBy.d.ts new file mode 100644 index 0000000..020a8f5 --- /dev/null +++ b/node_modules/@types/lodash/fp/minBy.d.ts @@ -0,0 +1,2 @@ +import { minBy } from "../fp"; +export = minBy; diff --git a/node_modules/@types/lodash/fp/multiply.d.ts b/node_modules/@types/lodash/fp/multiply.d.ts new file mode 100644 index 0000000..b3e5f3a --- /dev/null +++ b/node_modules/@types/lodash/fp/multiply.d.ts @@ -0,0 +1,2 @@ +import { multiply } from "../fp"; +export = multiply; diff --git a/node_modules/@types/lodash/fp/nAry.d.ts b/node_modules/@types/lodash/fp/nAry.d.ts new file mode 100644 index 0000000..882e4a3 --- /dev/null +++ b/node_modules/@types/lodash/fp/nAry.d.ts @@ -0,0 +1,2 @@ +import { nAry } from "../fp"; +export = nAry; diff --git a/node_modules/@types/lodash/fp/negate.d.ts b/node_modules/@types/lodash/fp/negate.d.ts new file mode 100644 index 0000000..a7693c1 --- /dev/null +++ b/node_modules/@types/lodash/fp/negate.d.ts @@ -0,0 +1,2 @@ +import { negate } from "../fp"; +export = negate; diff --git a/node_modules/@types/lodash/fp/noConflict.d.ts b/node_modules/@types/lodash/fp/noConflict.d.ts new file mode 100644 index 0000000..7694f5a --- /dev/null +++ b/node_modules/@types/lodash/fp/noConflict.d.ts @@ -0,0 +1,2 @@ +import { noConflict } from "../fp"; +export = noConflict; diff --git a/node_modules/@types/lodash/fp/noop.d.ts b/node_modules/@types/lodash/fp/noop.d.ts new file mode 100644 index 0000000..5b6a27b --- /dev/null +++ b/node_modules/@types/lodash/fp/noop.d.ts @@ -0,0 +1,2 @@ +import { noop } from "../fp"; +export = noop; diff --git a/node_modules/@types/lodash/fp/now.d.ts b/node_modules/@types/lodash/fp/now.d.ts new file mode 100644 index 0000000..fdbbd2b --- /dev/null +++ b/node_modules/@types/lodash/fp/now.d.ts @@ -0,0 +1,2 @@ +import { now } from "../fp"; +export = now; diff --git a/node_modules/@types/lodash/fp/nth.d.ts b/node_modules/@types/lodash/fp/nth.d.ts new file mode 100644 index 0000000..e3987e1 --- /dev/null +++ b/node_modules/@types/lodash/fp/nth.d.ts @@ -0,0 +1,2 @@ +import { nth } from "../fp"; +export = nth; diff --git a/node_modules/@types/lodash/fp/nthArg.d.ts b/node_modules/@types/lodash/fp/nthArg.d.ts new file mode 100644 index 0000000..216c9bb --- /dev/null +++ b/node_modules/@types/lodash/fp/nthArg.d.ts @@ -0,0 +1,2 @@ +import { nthArg } from "../fp"; +export = nthArg; diff --git a/node_modules/@types/lodash/fp/omit.d.ts b/node_modules/@types/lodash/fp/omit.d.ts new file mode 100644 index 0000000..1cd1b7f --- /dev/null +++ b/node_modules/@types/lodash/fp/omit.d.ts @@ -0,0 +1,2 @@ +import { omit } from "../fp"; +export = omit; diff --git a/node_modules/@types/lodash/fp/omitAll.d.ts b/node_modules/@types/lodash/fp/omitAll.d.ts new file mode 100644 index 0000000..dab5cfa --- /dev/null +++ b/node_modules/@types/lodash/fp/omitAll.d.ts @@ -0,0 +1,2 @@ +import { omitAll } from "../fp"; +export = omitAll; diff --git a/node_modules/@types/lodash/fp/omitBy.d.ts b/node_modules/@types/lodash/fp/omitBy.d.ts new file mode 100644 index 0000000..8be4f5b --- /dev/null +++ b/node_modules/@types/lodash/fp/omitBy.d.ts @@ -0,0 +1,2 @@ +import { omitBy } from "../fp"; +export = omitBy; diff --git a/node_modules/@types/lodash/fp/once.d.ts b/node_modules/@types/lodash/fp/once.d.ts new file mode 100644 index 0000000..24d859c --- /dev/null +++ b/node_modules/@types/lodash/fp/once.d.ts @@ -0,0 +1,2 @@ +import { once } from "../fp"; +export = once; diff --git a/node_modules/@types/lodash/fp/orderBy.d.ts b/node_modules/@types/lodash/fp/orderBy.d.ts new file mode 100644 index 0000000..9443fcf --- /dev/null +++ b/node_modules/@types/lodash/fp/orderBy.d.ts @@ -0,0 +1,2 @@ +import { orderBy } from "../fp"; +export = orderBy; diff --git a/node_modules/@types/lodash/fp/over.d.ts b/node_modules/@types/lodash/fp/over.d.ts new file mode 100644 index 0000000..1bd2502 --- /dev/null +++ b/node_modules/@types/lodash/fp/over.d.ts @@ -0,0 +1,2 @@ +import { over } from "../fp"; +export = over; diff --git a/node_modules/@types/lodash/fp/overArgs.d.ts b/node_modules/@types/lodash/fp/overArgs.d.ts new file mode 100644 index 0000000..c054c92 --- /dev/null +++ b/node_modules/@types/lodash/fp/overArgs.d.ts @@ -0,0 +1,2 @@ +import { overArgs } from "../fp"; +export = overArgs; diff --git a/node_modules/@types/lodash/fp/overEvery.d.ts b/node_modules/@types/lodash/fp/overEvery.d.ts new file mode 100644 index 0000000..1cf8b40 --- /dev/null +++ b/node_modules/@types/lodash/fp/overEvery.d.ts @@ -0,0 +1,2 @@ +import { overEvery } from "../fp"; +export = overEvery; diff --git a/node_modules/@types/lodash/fp/overSome.d.ts b/node_modules/@types/lodash/fp/overSome.d.ts new file mode 100644 index 0000000..6b098b7 --- /dev/null +++ b/node_modules/@types/lodash/fp/overSome.d.ts @@ -0,0 +1,2 @@ +import { overSome } from "../fp"; +export = overSome; diff --git a/node_modules/@types/lodash/fp/pad.d.ts b/node_modules/@types/lodash/fp/pad.d.ts new file mode 100644 index 0000000..a551977 --- /dev/null +++ b/node_modules/@types/lodash/fp/pad.d.ts @@ -0,0 +1,2 @@ +import { pad } from "../fp"; +export = pad; diff --git a/node_modules/@types/lodash/fp/padChars.d.ts b/node_modules/@types/lodash/fp/padChars.d.ts new file mode 100644 index 0000000..74d1aab --- /dev/null +++ b/node_modules/@types/lodash/fp/padChars.d.ts @@ -0,0 +1,2 @@ +import { padChars } from "../fp"; +export = padChars; diff --git a/node_modules/@types/lodash/fp/padCharsEnd.d.ts b/node_modules/@types/lodash/fp/padCharsEnd.d.ts new file mode 100644 index 0000000..3a468dc --- /dev/null +++ b/node_modules/@types/lodash/fp/padCharsEnd.d.ts @@ -0,0 +1,2 @@ +import { padCharsEnd } from "../fp"; +export = padCharsEnd; diff --git a/node_modules/@types/lodash/fp/padCharsStart.d.ts b/node_modules/@types/lodash/fp/padCharsStart.d.ts new file mode 100644 index 0000000..a225235 --- /dev/null +++ b/node_modules/@types/lodash/fp/padCharsStart.d.ts @@ -0,0 +1,2 @@ +import { padCharsStart } from "../fp"; +export = padCharsStart; diff --git a/node_modules/@types/lodash/fp/padEnd.d.ts b/node_modules/@types/lodash/fp/padEnd.d.ts new file mode 100644 index 0000000..5c4e4d8 --- /dev/null +++ b/node_modules/@types/lodash/fp/padEnd.d.ts @@ -0,0 +1,2 @@ +import { padEnd } from "../fp"; +export = padEnd; diff --git a/node_modules/@types/lodash/fp/padStart.d.ts b/node_modules/@types/lodash/fp/padStart.d.ts new file mode 100644 index 0000000..a4fca5d --- /dev/null +++ b/node_modules/@types/lodash/fp/padStart.d.ts @@ -0,0 +1,2 @@ +import { padStart } from "../fp"; +export = padStart; diff --git a/node_modules/@types/lodash/fp/parseInt.d.ts b/node_modules/@types/lodash/fp/parseInt.d.ts new file mode 100644 index 0000000..47aff97 --- /dev/null +++ b/node_modules/@types/lodash/fp/parseInt.d.ts @@ -0,0 +1,2 @@ +import { parseInt } from "../fp"; +export = parseInt; diff --git a/node_modules/@types/lodash/fp/partial.d.ts b/node_modules/@types/lodash/fp/partial.d.ts new file mode 100644 index 0000000..f5ebd72 --- /dev/null +++ b/node_modules/@types/lodash/fp/partial.d.ts @@ -0,0 +1,2 @@ +import { partial } from "../fp"; +export = partial; diff --git a/node_modules/@types/lodash/fp/partialRight.d.ts b/node_modules/@types/lodash/fp/partialRight.d.ts new file mode 100644 index 0000000..bc0fa1b --- /dev/null +++ b/node_modules/@types/lodash/fp/partialRight.d.ts @@ -0,0 +1,2 @@ +import { partialRight } from "../fp"; +export = partialRight; diff --git a/node_modules/@types/lodash/fp/partition.d.ts b/node_modules/@types/lodash/fp/partition.d.ts new file mode 100644 index 0000000..6ad41cd --- /dev/null +++ b/node_modules/@types/lodash/fp/partition.d.ts @@ -0,0 +1,2 @@ +import { partition } from "../fp"; +export = partition; diff --git a/node_modules/@types/lodash/fp/path.d.ts b/node_modules/@types/lodash/fp/path.d.ts new file mode 100644 index 0000000..db86d60 --- /dev/null +++ b/node_modules/@types/lodash/fp/path.d.ts @@ -0,0 +1,2 @@ +import { path } from "../fp"; +export = path; diff --git a/node_modules/@types/lodash/fp/pathEq.d.ts b/node_modules/@types/lodash/fp/pathEq.d.ts new file mode 100644 index 0000000..9f32875 --- /dev/null +++ b/node_modules/@types/lodash/fp/pathEq.d.ts @@ -0,0 +1,2 @@ +import { pathEq } from "../fp"; +export = pathEq; diff --git a/node_modules/@types/lodash/fp/pathOr.d.ts b/node_modules/@types/lodash/fp/pathOr.d.ts new file mode 100644 index 0000000..6cad6b1 --- /dev/null +++ b/node_modules/@types/lodash/fp/pathOr.d.ts @@ -0,0 +1,2 @@ +import { pathOr } from "../fp"; +export = pathOr; diff --git a/node_modules/@types/lodash/fp/paths.d.ts b/node_modules/@types/lodash/fp/paths.d.ts new file mode 100644 index 0000000..1e6eb89 --- /dev/null +++ b/node_modules/@types/lodash/fp/paths.d.ts @@ -0,0 +1,2 @@ +import { paths } from "../fp"; +export = paths; diff --git a/node_modules/@types/lodash/fp/pick.d.ts b/node_modules/@types/lodash/fp/pick.d.ts new file mode 100644 index 0000000..4772eca --- /dev/null +++ b/node_modules/@types/lodash/fp/pick.d.ts @@ -0,0 +1,2 @@ +import { pick } from "../fp"; +export = pick; diff --git a/node_modules/@types/lodash/fp/pickAll.d.ts b/node_modules/@types/lodash/fp/pickAll.d.ts new file mode 100644 index 0000000..38d2e3f --- /dev/null +++ b/node_modules/@types/lodash/fp/pickAll.d.ts @@ -0,0 +1,2 @@ +import { pickAll } from "../fp"; +export = pickAll; diff --git a/node_modules/@types/lodash/fp/pickBy.d.ts b/node_modules/@types/lodash/fp/pickBy.d.ts new file mode 100644 index 0000000..0b19262 --- /dev/null +++ b/node_modules/@types/lodash/fp/pickBy.d.ts @@ -0,0 +1,2 @@ +import { pickBy } from "../fp"; +export = pickBy; diff --git a/node_modules/@types/lodash/fp/pipe.d.ts b/node_modules/@types/lodash/fp/pipe.d.ts new file mode 100644 index 0000000..a53a048 --- /dev/null +++ b/node_modules/@types/lodash/fp/pipe.d.ts @@ -0,0 +1,2 @@ +import { pipe } from "../fp"; +export = pipe; diff --git a/node_modules/@types/lodash/fp/placeholder.d.ts b/node_modules/@types/lodash/fp/placeholder.d.ts new file mode 100644 index 0000000..ddaed8e --- /dev/null +++ b/node_modules/@types/lodash/fp/placeholder.d.ts @@ -0,0 +1,3 @@ +import _ = require("../index"); +declare const placeholder: _.__; +export = placeholder; diff --git a/node_modules/@types/lodash/fp/pluck.d.ts b/node_modules/@types/lodash/fp/pluck.d.ts new file mode 100644 index 0000000..c5c916f --- /dev/null +++ b/node_modules/@types/lodash/fp/pluck.d.ts @@ -0,0 +1,2 @@ +import { pluck } from "../fp"; +export = pluck; diff --git a/node_modules/@types/lodash/fp/prop.d.ts b/node_modules/@types/lodash/fp/prop.d.ts new file mode 100644 index 0000000..f2061e7 --- /dev/null +++ b/node_modules/@types/lodash/fp/prop.d.ts @@ -0,0 +1,2 @@ +import { prop } from "../fp"; +export = prop; diff --git a/node_modules/@types/lodash/fp/propEq.d.ts b/node_modules/@types/lodash/fp/propEq.d.ts new file mode 100644 index 0000000..5e3f4b4 --- /dev/null +++ b/node_modules/@types/lodash/fp/propEq.d.ts @@ -0,0 +1,2 @@ +import { propEq } from "../fp"; +export = propEq; diff --git a/node_modules/@types/lodash/fp/propOr.d.ts b/node_modules/@types/lodash/fp/propOr.d.ts new file mode 100644 index 0000000..feabcf6 --- /dev/null +++ b/node_modules/@types/lodash/fp/propOr.d.ts @@ -0,0 +1,2 @@ +import { propOr } from "../fp"; +export = propOr; diff --git a/node_modules/@types/lodash/fp/property.d.ts b/node_modules/@types/lodash/fp/property.d.ts new file mode 100644 index 0000000..aaa6c25 --- /dev/null +++ b/node_modules/@types/lodash/fp/property.d.ts @@ -0,0 +1,2 @@ +import { property } from "../fp"; +export = property; diff --git a/node_modules/@types/lodash/fp/propertyOf.d.ts b/node_modules/@types/lodash/fp/propertyOf.d.ts new file mode 100644 index 0000000..a4d5513 --- /dev/null +++ b/node_modules/@types/lodash/fp/propertyOf.d.ts @@ -0,0 +1,2 @@ +import { propertyOf } from "../fp"; +export = propertyOf; diff --git a/node_modules/@types/lodash/fp/props.d.ts b/node_modules/@types/lodash/fp/props.d.ts new file mode 100644 index 0000000..46addba --- /dev/null +++ b/node_modules/@types/lodash/fp/props.d.ts @@ -0,0 +1,2 @@ +import { props } from "../fp"; +export = props; diff --git a/node_modules/@types/lodash/fp/pull.d.ts b/node_modules/@types/lodash/fp/pull.d.ts new file mode 100644 index 0000000..801cf33 --- /dev/null +++ b/node_modules/@types/lodash/fp/pull.d.ts @@ -0,0 +1,2 @@ +import { pull } from "../fp"; +export = pull; diff --git a/node_modules/@types/lodash/fp/pullAll.d.ts b/node_modules/@types/lodash/fp/pullAll.d.ts new file mode 100644 index 0000000..042fe89 --- /dev/null +++ b/node_modules/@types/lodash/fp/pullAll.d.ts @@ -0,0 +1,2 @@ +import { pullAll } from "../fp"; +export = pullAll; diff --git a/node_modules/@types/lodash/fp/pullAllBy.d.ts b/node_modules/@types/lodash/fp/pullAllBy.d.ts new file mode 100644 index 0000000..5e5de1f --- /dev/null +++ b/node_modules/@types/lodash/fp/pullAllBy.d.ts @@ -0,0 +1,2 @@ +import { pullAllBy } from "../fp"; +export = pullAllBy; diff --git a/node_modules/@types/lodash/fp/pullAllWith.d.ts b/node_modules/@types/lodash/fp/pullAllWith.d.ts new file mode 100644 index 0000000..0c448bf --- /dev/null +++ b/node_modules/@types/lodash/fp/pullAllWith.d.ts @@ -0,0 +1,2 @@ +import { pullAllWith } from "../fp"; +export = pullAllWith; diff --git a/node_modules/@types/lodash/fp/pullAt.d.ts b/node_modules/@types/lodash/fp/pullAt.d.ts new file mode 100644 index 0000000..4bdffd9 --- /dev/null +++ b/node_modules/@types/lodash/fp/pullAt.d.ts @@ -0,0 +1,2 @@ +import { pullAt } from "../fp"; +export = pullAt; diff --git a/node_modules/@types/lodash/fp/random.d.ts b/node_modules/@types/lodash/fp/random.d.ts new file mode 100644 index 0000000..a69555c --- /dev/null +++ b/node_modules/@types/lodash/fp/random.d.ts @@ -0,0 +1,2 @@ +import { random } from "../fp"; +export = random; diff --git a/node_modules/@types/lodash/fp/range.d.ts b/node_modules/@types/lodash/fp/range.d.ts new file mode 100644 index 0000000..ace50ce --- /dev/null +++ b/node_modules/@types/lodash/fp/range.d.ts @@ -0,0 +1,2 @@ +import { range } from "../fp"; +export = range; diff --git a/node_modules/@types/lodash/fp/rangeRight.d.ts b/node_modules/@types/lodash/fp/rangeRight.d.ts new file mode 100644 index 0000000..20c8bae --- /dev/null +++ b/node_modules/@types/lodash/fp/rangeRight.d.ts @@ -0,0 +1,2 @@ +import { rangeRight } from "../fp"; +export = rangeRight; diff --git a/node_modules/@types/lodash/fp/rangeStep.d.ts b/node_modules/@types/lodash/fp/rangeStep.d.ts new file mode 100644 index 0000000..e5f4c89 --- /dev/null +++ b/node_modules/@types/lodash/fp/rangeStep.d.ts @@ -0,0 +1,2 @@ +import { rangeStep } from "../fp"; +export = rangeStep; diff --git a/node_modules/@types/lodash/fp/rangeStepRight.d.ts b/node_modules/@types/lodash/fp/rangeStepRight.d.ts new file mode 100644 index 0000000..6c7add4 --- /dev/null +++ b/node_modules/@types/lodash/fp/rangeStepRight.d.ts @@ -0,0 +1,2 @@ +import { rangeStepRight } from "../fp"; +export = rangeStepRight; diff --git a/node_modules/@types/lodash/fp/rearg.d.ts b/node_modules/@types/lodash/fp/rearg.d.ts new file mode 100644 index 0000000..5c407d1 --- /dev/null +++ b/node_modules/@types/lodash/fp/rearg.d.ts @@ -0,0 +1,2 @@ +import { rearg } from "../fp"; +export = rearg; diff --git a/node_modules/@types/lodash/fp/reduce.d.ts b/node_modules/@types/lodash/fp/reduce.d.ts new file mode 100644 index 0000000..e262f39 --- /dev/null +++ b/node_modules/@types/lodash/fp/reduce.d.ts @@ -0,0 +1,2 @@ +import { reduce } from "../fp"; +export = reduce; diff --git a/node_modules/@types/lodash/fp/reduceRight.d.ts b/node_modules/@types/lodash/fp/reduceRight.d.ts new file mode 100644 index 0000000..fa54fa3 --- /dev/null +++ b/node_modules/@types/lodash/fp/reduceRight.d.ts @@ -0,0 +1,2 @@ +import { reduceRight } from "../fp"; +export = reduceRight; diff --git a/node_modules/@types/lodash/fp/reject.d.ts b/node_modules/@types/lodash/fp/reject.d.ts new file mode 100644 index 0000000..d0a12af --- /dev/null +++ b/node_modules/@types/lodash/fp/reject.d.ts @@ -0,0 +1,2 @@ +import { reject } from "../fp"; +export = reject; diff --git a/node_modules/@types/lodash/fp/remove.d.ts b/node_modules/@types/lodash/fp/remove.d.ts new file mode 100644 index 0000000..e0da9b1 --- /dev/null +++ b/node_modules/@types/lodash/fp/remove.d.ts @@ -0,0 +1,2 @@ +import { remove } from "../fp"; +export = remove; diff --git a/node_modules/@types/lodash/fp/repeat.d.ts b/node_modules/@types/lodash/fp/repeat.d.ts new file mode 100644 index 0000000..1f757a2 --- /dev/null +++ b/node_modules/@types/lodash/fp/repeat.d.ts @@ -0,0 +1,2 @@ +import { repeat } from "../fp"; +export = repeat; diff --git a/node_modules/@types/lodash/fp/replace.d.ts b/node_modules/@types/lodash/fp/replace.d.ts new file mode 100644 index 0000000..c7a75d1 --- /dev/null +++ b/node_modules/@types/lodash/fp/replace.d.ts @@ -0,0 +1,2 @@ +import { replace } from "../fp"; +export = replace; diff --git a/node_modules/@types/lodash/fp/rest.d.ts b/node_modules/@types/lodash/fp/rest.d.ts new file mode 100644 index 0000000..b059d67 --- /dev/null +++ b/node_modules/@types/lodash/fp/rest.d.ts @@ -0,0 +1,2 @@ +import { rest } from "../fp"; +export = rest; diff --git a/node_modules/@types/lodash/fp/restFrom.d.ts b/node_modules/@types/lodash/fp/restFrom.d.ts new file mode 100644 index 0000000..218edbd --- /dev/null +++ b/node_modules/@types/lodash/fp/restFrom.d.ts @@ -0,0 +1,2 @@ +import { restFrom } from "../fp"; +export = restFrom; diff --git a/node_modules/@types/lodash/fp/result.d.ts b/node_modules/@types/lodash/fp/result.d.ts new file mode 100644 index 0000000..5a919dd --- /dev/null +++ b/node_modules/@types/lodash/fp/result.d.ts @@ -0,0 +1,2 @@ +import { result } from "../fp"; +export = result; diff --git a/node_modules/@types/lodash/fp/reverse.d.ts b/node_modules/@types/lodash/fp/reverse.d.ts new file mode 100644 index 0000000..f754d6a --- /dev/null +++ b/node_modules/@types/lodash/fp/reverse.d.ts @@ -0,0 +1,2 @@ +import { reverse } from "../fp"; +export = reverse; diff --git a/node_modules/@types/lodash/fp/round.d.ts b/node_modules/@types/lodash/fp/round.d.ts new file mode 100644 index 0000000..02f4e6f --- /dev/null +++ b/node_modules/@types/lodash/fp/round.d.ts @@ -0,0 +1,2 @@ +import { round } from "../fp"; +export = round; diff --git a/node_modules/@types/lodash/fp/runInContext.d.ts b/node_modules/@types/lodash/fp/runInContext.d.ts new file mode 100644 index 0000000..6041db7 --- /dev/null +++ b/node_modules/@types/lodash/fp/runInContext.d.ts @@ -0,0 +1,2 @@ +import { runInContext } from "../fp"; +export = runInContext; diff --git a/node_modules/@types/lodash/fp/sample.d.ts b/node_modules/@types/lodash/fp/sample.d.ts new file mode 100644 index 0000000..f2fcf1a --- /dev/null +++ b/node_modules/@types/lodash/fp/sample.d.ts @@ -0,0 +1,2 @@ +import { sample } from "../fp"; +export = sample; diff --git a/node_modules/@types/lodash/fp/sampleSize.d.ts b/node_modules/@types/lodash/fp/sampleSize.d.ts new file mode 100644 index 0000000..41a3cab --- /dev/null +++ b/node_modules/@types/lodash/fp/sampleSize.d.ts @@ -0,0 +1,2 @@ +import { sampleSize } from "../fp"; +export = sampleSize; diff --git a/node_modules/@types/lodash/fp/set.d.ts b/node_modules/@types/lodash/fp/set.d.ts new file mode 100644 index 0000000..57960cb --- /dev/null +++ b/node_modules/@types/lodash/fp/set.d.ts @@ -0,0 +1,2 @@ +import { set } from "../fp"; +export = set; diff --git a/node_modules/@types/lodash/fp/setWith.d.ts b/node_modules/@types/lodash/fp/setWith.d.ts new file mode 100644 index 0000000..800a494 --- /dev/null +++ b/node_modules/@types/lodash/fp/setWith.d.ts @@ -0,0 +1,2 @@ +import { setWith } from "../fp"; +export = setWith; diff --git a/node_modules/@types/lodash/fp/shuffle.d.ts b/node_modules/@types/lodash/fp/shuffle.d.ts new file mode 100644 index 0000000..7f07282 --- /dev/null +++ b/node_modules/@types/lodash/fp/shuffle.d.ts @@ -0,0 +1,2 @@ +import { shuffle } from "../fp"; +export = shuffle; diff --git a/node_modules/@types/lodash/fp/size.d.ts b/node_modules/@types/lodash/fp/size.d.ts new file mode 100644 index 0000000..657c8b7 --- /dev/null +++ b/node_modules/@types/lodash/fp/size.d.ts @@ -0,0 +1,2 @@ +import { size } from "../fp"; +export = size; diff --git a/node_modules/@types/lodash/fp/slice.d.ts b/node_modules/@types/lodash/fp/slice.d.ts new file mode 100644 index 0000000..fabbbe0 --- /dev/null +++ b/node_modules/@types/lodash/fp/slice.d.ts @@ -0,0 +1,2 @@ +import { slice } from "../fp"; +export = slice; diff --git a/node_modules/@types/lodash/fp/snakeCase.d.ts b/node_modules/@types/lodash/fp/snakeCase.d.ts new file mode 100644 index 0000000..a06ac45 --- /dev/null +++ b/node_modules/@types/lodash/fp/snakeCase.d.ts @@ -0,0 +1,2 @@ +import { snakeCase } from "../fp"; +export = snakeCase; diff --git a/node_modules/@types/lodash/fp/some.d.ts b/node_modules/@types/lodash/fp/some.d.ts new file mode 100644 index 0000000..870b231 --- /dev/null +++ b/node_modules/@types/lodash/fp/some.d.ts @@ -0,0 +1,2 @@ +import { some } from "../fp"; +export = some; diff --git a/node_modules/@types/lodash/fp/sortBy.d.ts b/node_modules/@types/lodash/fp/sortBy.d.ts new file mode 100644 index 0000000..72c5799 --- /dev/null +++ b/node_modules/@types/lodash/fp/sortBy.d.ts @@ -0,0 +1,2 @@ +import { sortBy } from "../fp"; +export = sortBy; diff --git a/node_modules/@types/lodash/fp/sortedIndex.d.ts b/node_modules/@types/lodash/fp/sortedIndex.d.ts new file mode 100644 index 0000000..35b57fe --- /dev/null +++ b/node_modules/@types/lodash/fp/sortedIndex.d.ts @@ -0,0 +1,2 @@ +import { sortedIndex } from "../fp"; +export = sortedIndex; diff --git a/node_modules/@types/lodash/fp/sortedIndexBy.d.ts b/node_modules/@types/lodash/fp/sortedIndexBy.d.ts new file mode 100644 index 0000000..f6968df --- /dev/null +++ b/node_modules/@types/lodash/fp/sortedIndexBy.d.ts @@ -0,0 +1,2 @@ +import { sortedIndexBy } from "../fp"; +export = sortedIndexBy; diff --git a/node_modules/@types/lodash/fp/sortedIndexOf.d.ts b/node_modules/@types/lodash/fp/sortedIndexOf.d.ts new file mode 100644 index 0000000..beeb6db --- /dev/null +++ b/node_modules/@types/lodash/fp/sortedIndexOf.d.ts @@ -0,0 +1,2 @@ +import { sortedIndexOf } from "../fp"; +export = sortedIndexOf; diff --git a/node_modules/@types/lodash/fp/sortedLastIndex.d.ts b/node_modules/@types/lodash/fp/sortedLastIndex.d.ts new file mode 100644 index 0000000..eea77a0 --- /dev/null +++ b/node_modules/@types/lodash/fp/sortedLastIndex.d.ts @@ -0,0 +1,2 @@ +import { sortedLastIndex } from "../fp"; +export = sortedLastIndex; diff --git a/node_modules/@types/lodash/fp/sortedLastIndexBy.d.ts b/node_modules/@types/lodash/fp/sortedLastIndexBy.d.ts new file mode 100644 index 0000000..6c8e4ee --- /dev/null +++ b/node_modules/@types/lodash/fp/sortedLastIndexBy.d.ts @@ -0,0 +1,2 @@ +import { sortedLastIndexBy } from "../fp"; +export = sortedLastIndexBy; diff --git a/node_modules/@types/lodash/fp/sortedLastIndexOf.d.ts b/node_modules/@types/lodash/fp/sortedLastIndexOf.d.ts new file mode 100644 index 0000000..a02caf3 --- /dev/null +++ b/node_modules/@types/lodash/fp/sortedLastIndexOf.d.ts @@ -0,0 +1,2 @@ +import { sortedLastIndexOf } from "../fp"; +export = sortedLastIndexOf; diff --git a/node_modules/@types/lodash/fp/sortedUniq.d.ts b/node_modules/@types/lodash/fp/sortedUniq.d.ts new file mode 100644 index 0000000..03d8e69 --- /dev/null +++ b/node_modules/@types/lodash/fp/sortedUniq.d.ts @@ -0,0 +1,2 @@ +import { sortedUniq } from "../fp"; +export = sortedUniq; diff --git a/node_modules/@types/lodash/fp/sortedUniqBy.d.ts b/node_modules/@types/lodash/fp/sortedUniqBy.d.ts new file mode 100644 index 0000000..466981a --- /dev/null +++ b/node_modules/@types/lodash/fp/sortedUniqBy.d.ts @@ -0,0 +1,2 @@ +import { sortedUniqBy } from "../fp"; +export = sortedUniqBy; diff --git a/node_modules/@types/lodash/fp/split.d.ts b/node_modules/@types/lodash/fp/split.d.ts new file mode 100644 index 0000000..8274d40 --- /dev/null +++ b/node_modules/@types/lodash/fp/split.d.ts @@ -0,0 +1,2 @@ +import { split } from "../fp"; +export = split; diff --git a/node_modules/@types/lodash/fp/spread.d.ts b/node_modules/@types/lodash/fp/spread.d.ts new file mode 100644 index 0000000..44eb90c --- /dev/null +++ b/node_modules/@types/lodash/fp/spread.d.ts @@ -0,0 +1,2 @@ +import { spread } from "../fp"; +export = spread; diff --git a/node_modules/@types/lodash/fp/spreadFrom.d.ts b/node_modules/@types/lodash/fp/spreadFrom.d.ts new file mode 100644 index 0000000..7eb840b --- /dev/null +++ b/node_modules/@types/lodash/fp/spreadFrom.d.ts @@ -0,0 +1,2 @@ +import { spreadFrom } from "../fp"; +export = spreadFrom; diff --git a/node_modules/@types/lodash/fp/startCase.d.ts b/node_modules/@types/lodash/fp/startCase.d.ts new file mode 100644 index 0000000..4f580aa --- /dev/null +++ b/node_modules/@types/lodash/fp/startCase.d.ts @@ -0,0 +1,2 @@ +import { startCase } from "../fp"; +export = startCase; diff --git a/node_modules/@types/lodash/fp/startsWith.d.ts b/node_modules/@types/lodash/fp/startsWith.d.ts new file mode 100644 index 0000000..f84397d --- /dev/null +++ b/node_modules/@types/lodash/fp/startsWith.d.ts @@ -0,0 +1,2 @@ +import { startsWith } from "../fp"; +export = startsWith; diff --git a/node_modules/@types/lodash/fp/stubArray.d.ts b/node_modules/@types/lodash/fp/stubArray.d.ts new file mode 100644 index 0000000..8ff910e --- /dev/null +++ b/node_modules/@types/lodash/fp/stubArray.d.ts @@ -0,0 +1,2 @@ +import { stubArray } from "../fp"; +export = stubArray; diff --git a/node_modules/@types/lodash/fp/stubFalse.d.ts b/node_modules/@types/lodash/fp/stubFalse.d.ts new file mode 100644 index 0000000..4cc0414 --- /dev/null +++ b/node_modules/@types/lodash/fp/stubFalse.d.ts @@ -0,0 +1,2 @@ +import { stubFalse } from "../fp"; +export = stubFalse; diff --git a/node_modules/@types/lodash/fp/stubObject.d.ts b/node_modules/@types/lodash/fp/stubObject.d.ts new file mode 100644 index 0000000..d7c8269 --- /dev/null +++ b/node_modules/@types/lodash/fp/stubObject.d.ts @@ -0,0 +1,2 @@ +import { stubObject } from "../fp"; +export = stubObject; diff --git a/node_modules/@types/lodash/fp/stubString.d.ts b/node_modules/@types/lodash/fp/stubString.d.ts new file mode 100644 index 0000000..cbfa449 --- /dev/null +++ b/node_modules/@types/lodash/fp/stubString.d.ts @@ -0,0 +1,2 @@ +import { stubString } from "../fp"; +export = stubString; diff --git a/node_modules/@types/lodash/fp/stubTrue.d.ts b/node_modules/@types/lodash/fp/stubTrue.d.ts new file mode 100644 index 0000000..0ed7e5b --- /dev/null +++ b/node_modules/@types/lodash/fp/stubTrue.d.ts @@ -0,0 +1,2 @@ +import { stubTrue } from "../fp"; +export = stubTrue; diff --git a/node_modules/@types/lodash/fp/subtract.d.ts b/node_modules/@types/lodash/fp/subtract.d.ts new file mode 100644 index 0000000..201301b --- /dev/null +++ b/node_modules/@types/lodash/fp/subtract.d.ts @@ -0,0 +1,2 @@ +import { subtract } from "../fp"; +export = subtract; diff --git a/node_modules/@types/lodash/fp/sum.d.ts b/node_modules/@types/lodash/fp/sum.d.ts new file mode 100644 index 0000000..6d7d020 --- /dev/null +++ b/node_modules/@types/lodash/fp/sum.d.ts @@ -0,0 +1,2 @@ +import { sum } from "../fp"; +export = sum; diff --git a/node_modules/@types/lodash/fp/sumBy.d.ts b/node_modules/@types/lodash/fp/sumBy.d.ts new file mode 100644 index 0000000..3f44c3f --- /dev/null +++ b/node_modules/@types/lodash/fp/sumBy.d.ts @@ -0,0 +1,2 @@ +import { sumBy } from "../fp"; +export = sumBy; diff --git a/node_modules/@types/lodash/fp/symmetricDifference.d.ts b/node_modules/@types/lodash/fp/symmetricDifference.d.ts new file mode 100644 index 0000000..cba1d1f --- /dev/null +++ b/node_modules/@types/lodash/fp/symmetricDifference.d.ts @@ -0,0 +1,2 @@ +import { symmetricDifference } from "../fp"; +export = symmetricDifference; diff --git a/node_modules/@types/lodash/fp/symmetricDifferenceBy.d.ts b/node_modules/@types/lodash/fp/symmetricDifferenceBy.d.ts new file mode 100644 index 0000000..8e9316c --- /dev/null +++ b/node_modules/@types/lodash/fp/symmetricDifferenceBy.d.ts @@ -0,0 +1,2 @@ +import { symmetricDifferenceBy } from "../fp"; +export = symmetricDifferenceBy; diff --git a/node_modules/@types/lodash/fp/symmetricDifferenceWith.d.ts b/node_modules/@types/lodash/fp/symmetricDifferenceWith.d.ts new file mode 100644 index 0000000..864ec01 --- /dev/null +++ b/node_modules/@types/lodash/fp/symmetricDifferenceWith.d.ts @@ -0,0 +1,2 @@ +import { symmetricDifferenceWith } from "../fp"; +export = symmetricDifferenceWith; diff --git a/node_modules/@types/lodash/fp/tail.d.ts b/node_modules/@types/lodash/fp/tail.d.ts new file mode 100644 index 0000000..df9bcdc --- /dev/null +++ b/node_modules/@types/lodash/fp/tail.d.ts @@ -0,0 +1,2 @@ +import { tail } from "../fp"; +export = tail; diff --git a/node_modules/@types/lodash/fp/take.d.ts b/node_modules/@types/lodash/fp/take.d.ts new file mode 100644 index 0000000..ab46aca --- /dev/null +++ b/node_modules/@types/lodash/fp/take.d.ts @@ -0,0 +1,2 @@ +import { take } from "../fp"; +export = take; diff --git a/node_modules/@types/lodash/fp/takeLast.d.ts b/node_modules/@types/lodash/fp/takeLast.d.ts new file mode 100644 index 0000000..027dcda --- /dev/null +++ b/node_modules/@types/lodash/fp/takeLast.d.ts @@ -0,0 +1,2 @@ +import { takeLast } from "../fp"; +export = takeLast; diff --git a/node_modules/@types/lodash/fp/takeLastWhile.d.ts b/node_modules/@types/lodash/fp/takeLastWhile.d.ts new file mode 100644 index 0000000..c6729c3 --- /dev/null +++ b/node_modules/@types/lodash/fp/takeLastWhile.d.ts @@ -0,0 +1,2 @@ +import { takeLastWhile } from "../fp"; +export = takeLastWhile; diff --git a/node_modules/@types/lodash/fp/takeRight.d.ts b/node_modules/@types/lodash/fp/takeRight.d.ts new file mode 100644 index 0000000..162c516 --- /dev/null +++ b/node_modules/@types/lodash/fp/takeRight.d.ts @@ -0,0 +1,2 @@ +import { takeRight } from "../fp"; +export = takeRight; diff --git a/node_modules/@types/lodash/fp/takeRightWhile.d.ts b/node_modules/@types/lodash/fp/takeRightWhile.d.ts new file mode 100644 index 0000000..b23f7a4 --- /dev/null +++ b/node_modules/@types/lodash/fp/takeRightWhile.d.ts @@ -0,0 +1,2 @@ +import { takeRightWhile } from "../fp"; +export = takeRightWhile; diff --git a/node_modules/@types/lodash/fp/takeWhile.d.ts b/node_modules/@types/lodash/fp/takeWhile.d.ts new file mode 100644 index 0000000..b8cb517 --- /dev/null +++ b/node_modules/@types/lodash/fp/takeWhile.d.ts @@ -0,0 +1,2 @@ +import { takeWhile } from "../fp"; +export = takeWhile; diff --git a/node_modules/@types/lodash/fp/tap.d.ts b/node_modules/@types/lodash/fp/tap.d.ts new file mode 100644 index 0000000..8ffbbd7 --- /dev/null +++ b/node_modules/@types/lodash/fp/tap.d.ts @@ -0,0 +1,2 @@ +import { tap } from "../fp"; +export = tap; diff --git a/node_modules/@types/lodash/fp/template.d.ts b/node_modules/@types/lodash/fp/template.d.ts new file mode 100644 index 0000000..3a37ed1 --- /dev/null +++ b/node_modules/@types/lodash/fp/template.d.ts @@ -0,0 +1,2 @@ +import { template } from "../fp"; +export = template; diff --git a/node_modules/@types/lodash/fp/throttle.d.ts b/node_modules/@types/lodash/fp/throttle.d.ts new file mode 100644 index 0000000..24d8b7f --- /dev/null +++ b/node_modules/@types/lodash/fp/throttle.d.ts @@ -0,0 +1,2 @@ +import { throttle } from "../fp"; +export = throttle; diff --git a/node_modules/@types/lodash/fp/thru.d.ts b/node_modules/@types/lodash/fp/thru.d.ts new file mode 100644 index 0000000..b972582 --- /dev/null +++ b/node_modules/@types/lodash/fp/thru.d.ts @@ -0,0 +1,2 @@ +import { thru } from "../fp"; +export = thru; diff --git a/node_modules/@types/lodash/fp/times.d.ts b/node_modules/@types/lodash/fp/times.d.ts new file mode 100644 index 0000000..3d9f0c6 --- /dev/null +++ b/node_modules/@types/lodash/fp/times.d.ts @@ -0,0 +1,2 @@ +import { times } from "../fp"; +export = times; diff --git a/node_modules/@types/lodash/fp/toArray.d.ts b/node_modules/@types/lodash/fp/toArray.d.ts new file mode 100644 index 0000000..4b18ce6 --- /dev/null +++ b/node_modules/@types/lodash/fp/toArray.d.ts @@ -0,0 +1,2 @@ +import { toArray } from "../fp"; +export = toArray; diff --git a/node_modules/@types/lodash/fp/toFinite.d.ts b/node_modules/@types/lodash/fp/toFinite.d.ts new file mode 100644 index 0000000..1d41996 --- /dev/null +++ b/node_modules/@types/lodash/fp/toFinite.d.ts @@ -0,0 +1,2 @@ +import { toFinite } from "../fp"; +export = toFinite; diff --git a/node_modules/@types/lodash/fp/toInteger.d.ts b/node_modules/@types/lodash/fp/toInteger.d.ts new file mode 100644 index 0000000..46ccaf9 --- /dev/null +++ b/node_modules/@types/lodash/fp/toInteger.d.ts @@ -0,0 +1,2 @@ +import { toInteger } from "../fp"; +export = toInteger; diff --git a/node_modules/@types/lodash/fp/toLength.d.ts b/node_modules/@types/lodash/fp/toLength.d.ts new file mode 100644 index 0000000..bb62924 --- /dev/null +++ b/node_modules/@types/lodash/fp/toLength.d.ts @@ -0,0 +1,2 @@ +import { toLength } from "../fp"; +export = toLength; diff --git a/node_modules/@types/lodash/fp/toLower.d.ts b/node_modules/@types/lodash/fp/toLower.d.ts new file mode 100644 index 0000000..64e6e36 --- /dev/null +++ b/node_modules/@types/lodash/fp/toLower.d.ts @@ -0,0 +1,2 @@ +import { toLower } from "../fp"; +export = toLower; diff --git a/node_modules/@types/lodash/fp/toNumber.d.ts b/node_modules/@types/lodash/fp/toNumber.d.ts new file mode 100644 index 0000000..262b91c --- /dev/null +++ b/node_modules/@types/lodash/fp/toNumber.d.ts @@ -0,0 +1,2 @@ +import { toNumber } from "../fp"; +export = toNumber; diff --git a/node_modules/@types/lodash/fp/toPairs.d.ts b/node_modules/@types/lodash/fp/toPairs.d.ts new file mode 100644 index 0000000..89334fc --- /dev/null +++ b/node_modules/@types/lodash/fp/toPairs.d.ts @@ -0,0 +1,2 @@ +import { toPairs } from "../fp"; +export = toPairs; diff --git a/node_modules/@types/lodash/fp/toPairsIn.d.ts b/node_modules/@types/lodash/fp/toPairsIn.d.ts new file mode 100644 index 0000000..278ff0b --- /dev/null +++ b/node_modules/@types/lodash/fp/toPairsIn.d.ts @@ -0,0 +1,2 @@ +import { toPairsIn } from "../fp"; +export = toPairsIn; diff --git a/node_modules/@types/lodash/fp/toPath.d.ts b/node_modules/@types/lodash/fp/toPath.d.ts new file mode 100644 index 0000000..9f2287c --- /dev/null +++ b/node_modules/@types/lodash/fp/toPath.d.ts @@ -0,0 +1,2 @@ +import { toPath } from "../fp"; +export = toPath; diff --git a/node_modules/@types/lodash/fp/toPlainObject.d.ts b/node_modules/@types/lodash/fp/toPlainObject.d.ts new file mode 100644 index 0000000..22fa070 --- /dev/null +++ b/node_modules/@types/lodash/fp/toPlainObject.d.ts @@ -0,0 +1,2 @@ +import { toPlainObject } from "../fp"; +export = toPlainObject; diff --git a/node_modules/@types/lodash/fp/toSafeInteger.d.ts b/node_modules/@types/lodash/fp/toSafeInteger.d.ts new file mode 100644 index 0000000..2f85078 --- /dev/null +++ b/node_modules/@types/lodash/fp/toSafeInteger.d.ts @@ -0,0 +1,2 @@ +import { toSafeInteger } from "../fp"; +export = toSafeInteger; diff --git a/node_modules/@types/lodash/fp/toString.d.ts b/node_modules/@types/lodash/fp/toString.d.ts new file mode 100644 index 0000000..ee6703c --- /dev/null +++ b/node_modules/@types/lodash/fp/toString.d.ts @@ -0,0 +1,2 @@ +import { toString } from "../fp"; +export = toString; diff --git a/node_modules/@types/lodash/fp/toUpper.d.ts b/node_modules/@types/lodash/fp/toUpper.d.ts new file mode 100644 index 0000000..6bf21c1 --- /dev/null +++ b/node_modules/@types/lodash/fp/toUpper.d.ts @@ -0,0 +1,2 @@ +import { toUpper } from "../fp"; +export = toUpper; diff --git a/node_modules/@types/lodash/fp/transform.d.ts b/node_modules/@types/lodash/fp/transform.d.ts new file mode 100644 index 0000000..ab0653c --- /dev/null +++ b/node_modules/@types/lodash/fp/transform.d.ts @@ -0,0 +1,2 @@ +import { transform } from "../fp"; +export = transform; diff --git a/node_modules/@types/lodash/fp/trim.d.ts b/node_modules/@types/lodash/fp/trim.d.ts new file mode 100644 index 0000000..f0f9b90 --- /dev/null +++ b/node_modules/@types/lodash/fp/trim.d.ts @@ -0,0 +1,2 @@ +import { trim } from "../fp"; +export = trim; diff --git a/node_modules/@types/lodash/fp/trimChars.d.ts b/node_modules/@types/lodash/fp/trimChars.d.ts new file mode 100644 index 0000000..929a493 --- /dev/null +++ b/node_modules/@types/lodash/fp/trimChars.d.ts @@ -0,0 +1,2 @@ +import { trimChars } from "../fp"; +export = trimChars; diff --git a/node_modules/@types/lodash/fp/trimCharsEnd.d.ts b/node_modules/@types/lodash/fp/trimCharsEnd.d.ts new file mode 100644 index 0000000..2f5609a --- /dev/null +++ b/node_modules/@types/lodash/fp/trimCharsEnd.d.ts @@ -0,0 +1,2 @@ +import { trimCharsEnd } from "../fp"; +export = trimCharsEnd; diff --git a/node_modules/@types/lodash/fp/trimCharsStart.d.ts b/node_modules/@types/lodash/fp/trimCharsStart.d.ts new file mode 100644 index 0000000..fb998f7 --- /dev/null +++ b/node_modules/@types/lodash/fp/trimCharsStart.d.ts @@ -0,0 +1,2 @@ +import { trimCharsStart } from "../fp"; +export = trimCharsStart; diff --git a/node_modules/@types/lodash/fp/trimEnd.d.ts b/node_modules/@types/lodash/fp/trimEnd.d.ts new file mode 100644 index 0000000..b666494 --- /dev/null +++ b/node_modules/@types/lodash/fp/trimEnd.d.ts @@ -0,0 +1,2 @@ +import { trimEnd } from "../fp"; +export = trimEnd; diff --git a/node_modules/@types/lodash/fp/trimStart.d.ts b/node_modules/@types/lodash/fp/trimStart.d.ts new file mode 100644 index 0000000..988227c --- /dev/null +++ b/node_modules/@types/lodash/fp/trimStart.d.ts @@ -0,0 +1,2 @@ +import { trimStart } from "../fp"; +export = trimStart; diff --git a/node_modules/@types/lodash/fp/truncate.d.ts b/node_modules/@types/lodash/fp/truncate.d.ts new file mode 100644 index 0000000..d38b7b1 --- /dev/null +++ b/node_modules/@types/lodash/fp/truncate.d.ts @@ -0,0 +1,2 @@ +import { truncate } from "../fp"; +export = truncate; diff --git a/node_modules/@types/lodash/fp/unapply.d.ts b/node_modules/@types/lodash/fp/unapply.d.ts new file mode 100644 index 0000000..c59b6b2 --- /dev/null +++ b/node_modules/@types/lodash/fp/unapply.d.ts @@ -0,0 +1,2 @@ +import { unapply } from "../fp"; +export = unapply; diff --git a/node_modules/@types/lodash/fp/unary.d.ts b/node_modules/@types/lodash/fp/unary.d.ts new file mode 100644 index 0000000..02e3195 --- /dev/null +++ b/node_modules/@types/lodash/fp/unary.d.ts @@ -0,0 +1,2 @@ +import { unary } from "../fp"; +export = unary; diff --git a/node_modules/@types/lodash/fp/unescape.d.ts b/node_modules/@types/lodash/fp/unescape.d.ts new file mode 100644 index 0000000..efcccf2 --- /dev/null +++ b/node_modules/@types/lodash/fp/unescape.d.ts @@ -0,0 +1,2 @@ +import { unescape } from "../fp"; +export = unescape; diff --git a/node_modules/@types/lodash/fp/union.d.ts b/node_modules/@types/lodash/fp/union.d.ts new file mode 100644 index 0000000..8e098ee --- /dev/null +++ b/node_modules/@types/lodash/fp/union.d.ts @@ -0,0 +1,2 @@ +import { union } from "../fp"; +export = union; diff --git a/node_modules/@types/lodash/fp/unionBy.d.ts b/node_modules/@types/lodash/fp/unionBy.d.ts new file mode 100644 index 0000000..f3882c6 --- /dev/null +++ b/node_modules/@types/lodash/fp/unionBy.d.ts @@ -0,0 +1,2 @@ +import { unionBy } from "../fp"; +export = unionBy; diff --git a/node_modules/@types/lodash/fp/unionWith.d.ts b/node_modules/@types/lodash/fp/unionWith.d.ts new file mode 100644 index 0000000..46e19fd --- /dev/null +++ b/node_modules/@types/lodash/fp/unionWith.d.ts @@ -0,0 +1,2 @@ +import { unionWith } from "../fp"; +export = unionWith; diff --git a/node_modules/@types/lodash/fp/uniq.d.ts b/node_modules/@types/lodash/fp/uniq.d.ts new file mode 100644 index 0000000..877d0d9 --- /dev/null +++ b/node_modules/@types/lodash/fp/uniq.d.ts @@ -0,0 +1,2 @@ +import { uniq } from "../fp"; +export = uniq; diff --git a/node_modules/@types/lodash/fp/uniqBy.d.ts b/node_modules/@types/lodash/fp/uniqBy.d.ts new file mode 100644 index 0000000..0e6522d --- /dev/null +++ b/node_modules/@types/lodash/fp/uniqBy.d.ts @@ -0,0 +1,2 @@ +import { uniqBy } from "../fp"; +export = uniqBy; diff --git a/node_modules/@types/lodash/fp/uniqWith.d.ts b/node_modules/@types/lodash/fp/uniqWith.d.ts new file mode 100644 index 0000000..165f45f --- /dev/null +++ b/node_modules/@types/lodash/fp/uniqWith.d.ts @@ -0,0 +1,2 @@ +import { uniqWith } from "../fp"; +export = uniqWith; diff --git a/node_modules/@types/lodash/fp/uniqueId.d.ts b/node_modules/@types/lodash/fp/uniqueId.d.ts new file mode 100644 index 0000000..57736d9 --- /dev/null +++ b/node_modules/@types/lodash/fp/uniqueId.d.ts @@ -0,0 +1,2 @@ +import { uniqueId } from "../fp"; +export = uniqueId; diff --git a/node_modules/@types/lodash/fp/unnest.d.ts b/node_modules/@types/lodash/fp/unnest.d.ts new file mode 100644 index 0000000..852e9a1 --- /dev/null +++ b/node_modules/@types/lodash/fp/unnest.d.ts @@ -0,0 +1,2 @@ +import { unnest } from "../fp"; +export = unnest; diff --git a/node_modules/@types/lodash/fp/unset.d.ts b/node_modules/@types/lodash/fp/unset.d.ts new file mode 100644 index 0000000..3e99247 --- /dev/null +++ b/node_modules/@types/lodash/fp/unset.d.ts @@ -0,0 +1,2 @@ +import { unset } from "../fp"; +export = unset; diff --git a/node_modules/@types/lodash/fp/unzip.d.ts b/node_modules/@types/lodash/fp/unzip.d.ts new file mode 100644 index 0000000..ba9d4cd --- /dev/null +++ b/node_modules/@types/lodash/fp/unzip.d.ts @@ -0,0 +1,2 @@ +import { unzip } from "../fp"; +export = unzip; diff --git a/node_modules/@types/lodash/fp/unzipWith.d.ts b/node_modules/@types/lodash/fp/unzipWith.d.ts new file mode 100644 index 0000000..599eadb --- /dev/null +++ b/node_modules/@types/lodash/fp/unzipWith.d.ts @@ -0,0 +1,2 @@ +import { unzipWith } from "../fp"; +export = unzipWith; diff --git a/node_modules/@types/lodash/fp/update.d.ts b/node_modules/@types/lodash/fp/update.d.ts new file mode 100644 index 0000000..76dfe48 --- /dev/null +++ b/node_modules/@types/lodash/fp/update.d.ts @@ -0,0 +1,2 @@ +import { update } from "../fp"; +export = update; diff --git a/node_modules/@types/lodash/fp/updateWith.d.ts b/node_modules/@types/lodash/fp/updateWith.d.ts new file mode 100644 index 0000000..6d6331d --- /dev/null +++ b/node_modules/@types/lodash/fp/updateWith.d.ts @@ -0,0 +1,2 @@ +import { updateWith } from "../fp"; +export = updateWith; diff --git a/node_modules/@types/lodash/fp/upperCase.d.ts b/node_modules/@types/lodash/fp/upperCase.d.ts new file mode 100644 index 0000000..10aadb2 --- /dev/null +++ b/node_modules/@types/lodash/fp/upperCase.d.ts @@ -0,0 +1,2 @@ +import { upperCase } from "../fp"; +export = upperCase; diff --git a/node_modules/@types/lodash/fp/upperFirst.d.ts b/node_modules/@types/lodash/fp/upperFirst.d.ts new file mode 100644 index 0000000..e2c9adf --- /dev/null +++ b/node_modules/@types/lodash/fp/upperFirst.d.ts @@ -0,0 +1,2 @@ +import { upperFirst } from "../fp"; +export = upperFirst; diff --git a/node_modules/@types/lodash/fp/useWith.d.ts b/node_modules/@types/lodash/fp/useWith.d.ts new file mode 100644 index 0000000..991905a --- /dev/null +++ b/node_modules/@types/lodash/fp/useWith.d.ts @@ -0,0 +1,2 @@ +import { useWith } from "../fp"; +export = useWith; diff --git a/node_modules/@types/lodash/fp/values.d.ts b/node_modules/@types/lodash/fp/values.d.ts new file mode 100644 index 0000000..75ec6fb --- /dev/null +++ b/node_modules/@types/lodash/fp/values.d.ts @@ -0,0 +1,2 @@ +import { values } from "../fp"; +export = values; diff --git a/node_modules/@types/lodash/fp/valuesIn.d.ts b/node_modules/@types/lodash/fp/valuesIn.d.ts new file mode 100644 index 0000000..6f4f3b4 --- /dev/null +++ b/node_modules/@types/lodash/fp/valuesIn.d.ts @@ -0,0 +1,2 @@ +import { valuesIn } from "../fp"; +export = valuesIn; diff --git a/node_modules/@types/lodash/fp/where.d.ts b/node_modules/@types/lodash/fp/where.d.ts new file mode 100644 index 0000000..41e21ec --- /dev/null +++ b/node_modules/@types/lodash/fp/where.d.ts @@ -0,0 +1,2 @@ +import { where } from "../fp"; +export = where; diff --git a/node_modules/@types/lodash/fp/whereEq.d.ts b/node_modules/@types/lodash/fp/whereEq.d.ts new file mode 100644 index 0000000..893316d --- /dev/null +++ b/node_modules/@types/lodash/fp/whereEq.d.ts @@ -0,0 +1,2 @@ +import { whereEq } from "../fp"; +export = whereEq; diff --git a/node_modules/@types/lodash/fp/without.d.ts b/node_modules/@types/lodash/fp/without.d.ts new file mode 100644 index 0000000..600890a --- /dev/null +++ b/node_modules/@types/lodash/fp/without.d.ts @@ -0,0 +1,2 @@ +import { without } from "../fp"; +export = without; diff --git a/node_modules/@types/lodash/fp/words.d.ts b/node_modules/@types/lodash/fp/words.d.ts new file mode 100644 index 0000000..2b06b26 --- /dev/null +++ b/node_modules/@types/lodash/fp/words.d.ts @@ -0,0 +1,2 @@ +import { words } from "../fp"; +export = words; diff --git a/node_modules/@types/lodash/fp/wrap.d.ts b/node_modules/@types/lodash/fp/wrap.d.ts new file mode 100644 index 0000000..d9c2a28 --- /dev/null +++ b/node_modules/@types/lodash/fp/wrap.d.ts @@ -0,0 +1,2 @@ +import { wrap } from "../fp"; +export = wrap; diff --git a/node_modules/@types/lodash/fp/xor.d.ts b/node_modules/@types/lodash/fp/xor.d.ts new file mode 100644 index 0000000..ac69bde --- /dev/null +++ b/node_modules/@types/lodash/fp/xor.d.ts @@ -0,0 +1,2 @@ +import { xor } from "../fp"; +export = xor; diff --git a/node_modules/@types/lodash/fp/xorBy.d.ts b/node_modules/@types/lodash/fp/xorBy.d.ts new file mode 100644 index 0000000..1232972 --- /dev/null +++ b/node_modules/@types/lodash/fp/xorBy.d.ts @@ -0,0 +1,2 @@ +import { xorBy } from "../fp"; +export = xorBy; diff --git a/node_modules/@types/lodash/fp/xorWith.d.ts b/node_modules/@types/lodash/fp/xorWith.d.ts new file mode 100644 index 0000000..ec93e40 --- /dev/null +++ b/node_modules/@types/lodash/fp/xorWith.d.ts @@ -0,0 +1,2 @@ +import { xorWith } from "../fp"; +export = xorWith; diff --git a/node_modules/@types/lodash/fp/zip.d.ts b/node_modules/@types/lodash/fp/zip.d.ts new file mode 100644 index 0000000..2a83e73 --- /dev/null +++ b/node_modules/@types/lodash/fp/zip.d.ts @@ -0,0 +1,2 @@ +import { zip } from "../fp"; +export = zip; diff --git a/node_modules/@types/lodash/fp/zipAll.d.ts b/node_modules/@types/lodash/fp/zipAll.d.ts new file mode 100644 index 0000000..af0b3ed --- /dev/null +++ b/node_modules/@types/lodash/fp/zipAll.d.ts @@ -0,0 +1,2 @@ +import { zipAll } from "../fp"; +export = zipAll; diff --git a/node_modules/@types/lodash/fp/zipObj.d.ts b/node_modules/@types/lodash/fp/zipObj.d.ts new file mode 100644 index 0000000..4f4c19a --- /dev/null +++ b/node_modules/@types/lodash/fp/zipObj.d.ts @@ -0,0 +1,2 @@ +import { zipObj } from "../fp"; +export = zipObj; diff --git a/node_modules/@types/lodash/fp/zipObject.d.ts b/node_modules/@types/lodash/fp/zipObject.d.ts new file mode 100644 index 0000000..f302d7b --- /dev/null +++ b/node_modules/@types/lodash/fp/zipObject.d.ts @@ -0,0 +1,2 @@ +import { zipObject } from "../fp"; +export = zipObject; diff --git a/node_modules/@types/lodash/fp/zipObjectDeep.d.ts b/node_modules/@types/lodash/fp/zipObjectDeep.d.ts new file mode 100644 index 0000000..6010634 --- /dev/null +++ b/node_modules/@types/lodash/fp/zipObjectDeep.d.ts @@ -0,0 +1,2 @@ +import { zipObjectDeep } from "../fp"; +export = zipObjectDeep; diff --git a/node_modules/@types/lodash/fp/zipWith.d.ts b/node_modules/@types/lodash/fp/zipWith.d.ts new file mode 100644 index 0000000..9faaf3c --- /dev/null +++ b/node_modules/@types/lodash/fp/zipWith.d.ts @@ -0,0 +1,2 @@ +import { zipWith } from "../fp"; +export = zipWith; diff --git a/node_modules/@types/lodash/fromPairs.d.ts b/node_modules/@types/lodash/fromPairs.d.ts new file mode 100644 index 0000000..1c2006c --- /dev/null +++ b/node_modules/@types/lodash/fromPairs.d.ts @@ -0,0 +1,2 @@ +import { fromPairs } from "./index"; +export = fromPairs; diff --git a/node_modules/@types/lodash/functions.d.ts b/node_modules/@types/lodash/functions.d.ts new file mode 100644 index 0000000..8698336 --- /dev/null +++ b/node_modules/@types/lodash/functions.d.ts @@ -0,0 +1,2 @@ +import { functions } from "./index"; +export = functions; diff --git a/node_modules/@types/lodash/functionsIn.d.ts b/node_modules/@types/lodash/functionsIn.d.ts new file mode 100644 index 0000000..9f72a78 --- /dev/null +++ b/node_modules/@types/lodash/functionsIn.d.ts @@ -0,0 +1,2 @@ +import { functionsIn } from "./index"; +export = functionsIn; diff --git a/node_modules/@types/lodash/get.d.ts b/node_modules/@types/lodash/get.d.ts new file mode 100644 index 0000000..5ea7a5a --- /dev/null +++ b/node_modules/@types/lodash/get.d.ts @@ -0,0 +1,2 @@ +import { get } from "./index"; +export = get; diff --git a/node_modules/@types/lodash/groupBy.d.ts b/node_modules/@types/lodash/groupBy.d.ts new file mode 100644 index 0000000..ef49718 --- /dev/null +++ b/node_modules/@types/lodash/groupBy.d.ts @@ -0,0 +1,2 @@ +import { groupBy } from "./index"; +export = groupBy; diff --git a/node_modules/@types/lodash/gt.d.ts b/node_modules/@types/lodash/gt.d.ts new file mode 100644 index 0000000..860134f --- /dev/null +++ b/node_modules/@types/lodash/gt.d.ts @@ -0,0 +1,2 @@ +import { gt } from "./index"; +export = gt; diff --git a/node_modules/@types/lodash/gte.d.ts b/node_modules/@types/lodash/gte.d.ts new file mode 100644 index 0000000..994e882 --- /dev/null +++ b/node_modules/@types/lodash/gte.d.ts @@ -0,0 +1,2 @@ +import { gte } from "./index"; +export = gte; diff --git a/node_modules/@types/lodash/has.d.ts b/node_modules/@types/lodash/has.d.ts new file mode 100644 index 0000000..fff1468 --- /dev/null +++ b/node_modules/@types/lodash/has.d.ts @@ -0,0 +1,2 @@ +import { has } from "./index"; +export = has; diff --git a/node_modules/@types/lodash/hasIn.d.ts b/node_modules/@types/lodash/hasIn.d.ts new file mode 100644 index 0000000..a898071 --- /dev/null +++ b/node_modules/@types/lodash/hasIn.d.ts @@ -0,0 +1,2 @@ +import { hasIn } from "./index"; +export = hasIn; diff --git a/node_modules/@types/lodash/head.d.ts b/node_modules/@types/lodash/head.d.ts new file mode 100644 index 0000000..0e16da1 --- /dev/null +++ b/node_modules/@types/lodash/head.d.ts @@ -0,0 +1,2 @@ +import { head } from "./index"; +export = head; diff --git a/node_modules/@types/lodash/identity.d.ts b/node_modules/@types/lodash/identity.d.ts new file mode 100644 index 0000000..6814a16 --- /dev/null +++ b/node_modules/@types/lodash/identity.d.ts @@ -0,0 +1,2 @@ +import { identity } from "./index"; +export = identity; diff --git a/node_modules/@types/lodash/inRange.d.ts b/node_modules/@types/lodash/inRange.d.ts new file mode 100644 index 0000000..d9c57c0 --- /dev/null +++ b/node_modules/@types/lodash/inRange.d.ts @@ -0,0 +1,2 @@ +import { inRange } from "./index"; +export = inRange; diff --git a/node_modules/@types/lodash/includes.d.ts b/node_modules/@types/lodash/includes.d.ts new file mode 100644 index 0000000..4edd226 --- /dev/null +++ b/node_modules/@types/lodash/includes.d.ts @@ -0,0 +1,2 @@ +import { includes } from "./index"; +export = includes; diff --git a/node_modules/@types/lodash/index.d.ts b/node_modules/@types/lodash/index.d.ts new file mode 100644 index 0000000..95228b8 --- /dev/null +++ b/node_modules/@types/lodash/index.d.ts @@ -0,0 +1,47 @@ +// Type definitions for Lo-Dash 4.14 +// Project: http://lodash.com/ +// Definitions by: Brian Zengel , +// Ilya Mochalov , +// Stepan Mikhaylyuk , +// AJ Richardson , +// Junyoung Clare Jang , +// e-cloud , +// Georgii Dolzhykov , +// Jack Moore , +// Dominique Rau +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.6 + +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// + +export = _; +export as namespace _; + +declare const _: _.LoDashStatic; +declare namespace _ { + // tslint:disable-next-line no-empty-interface (This will be augmented) + interface LoDashStatic {} +} + +// Backward compatibility with --target es5 +declare global { + // tslint:disable-next-line:no-empty-interface + interface Set { } + // tslint:disable-next-line:no-empty-interface + interface Map { } + // tslint:disable-next-line:no-empty-interface + interface WeakSet { } + // tslint:disable-next-line:no-empty-interface + interface WeakMap { } +} diff --git a/node_modules/@types/lodash/indexOf.d.ts b/node_modules/@types/lodash/indexOf.d.ts new file mode 100644 index 0000000..50b8f70 --- /dev/null +++ b/node_modules/@types/lodash/indexOf.d.ts @@ -0,0 +1,2 @@ +import { indexOf } from "./index"; +export = indexOf; diff --git a/node_modules/@types/lodash/initial.d.ts b/node_modules/@types/lodash/initial.d.ts new file mode 100644 index 0000000..3ce64eb --- /dev/null +++ b/node_modules/@types/lodash/initial.d.ts @@ -0,0 +1,2 @@ +import { initial } from "./index"; +export = initial; diff --git a/node_modules/@types/lodash/intersection.d.ts b/node_modules/@types/lodash/intersection.d.ts new file mode 100644 index 0000000..1fbe4e5 --- /dev/null +++ b/node_modules/@types/lodash/intersection.d.ts @@ -0,0 +1,2 @@ +import { intersection } from "./index"; +export = intersection; diff --git a/node_modules/@types/lodash/intersectionBy.d.ts b/node_modules/@types/lodash/intersectionBy.d.ts new file mode 100644 index 0000000..b4885da --- /dev/null +++ b/node_modules/@types/lodash/intersectionBy.d.ts @@ -0,0 +1,2 @@ +import { intersectionBy } from "./index"; +export = intersectionBy; diff --git a/node_modules/@types/lodash/intersectionWith.d.ts b/node_modules/@types/lodash/intersectionWith.d.ts new file mode 100644 index 0000000..bacccd0 --- /dev/null +++ b/node_modules/@types/lodash/intersectionWith.d.ts @@ -0,0 +1,2 @@ +import { intersectionWith } from "./index"; +export = intersectionWith; diff --git a/node_modules/@types/lodash/invert.d.ts b/node_modules/@types/lodash/invert.d.ts new file mode 100644 index 0000000..2287ea1 --- /dev/null +++ b/node_modules/@types/lodash/invert.d.ts @@ -0,0 +1,2 @@ +import { invert } from "./index"; +export = invert; diff --git a/node_modules/@types/lodash/invertBy.d.ts b/node_modules/@types/lodash/invertBy.d.ts new file mode 100644 index 0000000..5951600 --- /dev/null +++ b/node_modules/@types/lodash/invertBy.d.ts @@ -0,0 +1,2 @@ +import { invertBy } from "./index"; +export = invertBy; diff --git a/node_modules/@types/lodash/invoke.d.ts b/node_modules/@types/lodash/invoke.d.ts new file mode 100644 index 0000000..eea6b38 --- /dev/null +++ b/node_modules/@types/lodash/invoke.d.ts @@ -0,0 +1,2 @@ +import { invoke } from "./index"; +export = invoke; diff --git a/node_modules/@types/lodash/invokeMap.d.ts b/node_modules/@types/lodash/invokeMap.d.ts new file mode 100644 index 0000000..814cf05 --- /dev/null +++ b/node_modules/@types/lodash/invokeMap.d.ts @@ -0,0 +1,2 @@ +import { invokeMap } from "./index"; +export = invokeMap; diff --git a/node_modules/@types/lodash/isArguments.d.ts b/node_modules/@types/lodash/isArguments.d.ts new file mode 100644 index 0000000..5b22572 --- /dev/null +++ b/node_modules/@types/lodash/isArguments.d.ts @@ -0,0 +1,2 @@ +import { isArguments } from "./index"; +export = isArguments; diff --git a/node_modules/@types/lodash/isArray.d.ts b/node_modules/@types/lodash/isArray.d.ts new file mode 100644 index 0000000..a35ab5a --- /dev/null +++ b/node_modules/@types/lodash/isArray.d.ts @@ -0,0 +1,2 @@ +import { isArray } from "./index"; +export = isArray; diff --git a/node_modules/@types/lodash/isArrayBuffer.d.ts b/node_modules/@types/lodash/isArrayBuffer.d.ts new file mode 100644 index 0000000..ec7c68c --- /dev/null +++ b/node_modules/@types/lodash/isArrayBuffer.d.ts @@ -0,0 +1,2 @@ +import { isArrayBuffer } from "./index"; +export = isArrayBuffer; diff --git a/node_modules/@types/lodash/isArrayLike.d.ts b/node_modules/@types/lodash/isArrayLike.d.ts new file mode 100644 index 0000000..aa95c77 --- /dev/null +++ b/node_modules/@types/lodash/isArrayLike.d.ts @@ -0,0 +1,2 @@ +import { isArrayLike } from "./index"; +export = isArrayLike; diff --git a/node_modules/@types/lodash/isArrayLikeObject.d.ts b/node_modules/@types/lodash/isArrayLikeObject.d.ts new file mode 100644 index 0000000..736c91d --- /dev/null +++ b/node_modules/@types/lodash/isArrayLikeObject.d.ts @@ -0,0 +1,2 @@ +import { isArrayLikeObject } from "./index"; +export = isArrayLikeObject; diff --git a/node_modules/@types/lodash/isBoolean.d.ts b/node_modules/@types/lodash/isBoolean.d.ts new file mode 100644 index 0000000..96c306d --- /dev/null +++ b/node_modules/@types/lodash/isBoolean.d.ts @@ -0,0 +1,2 @@ +import { isBoolean } from "./index"; +export = isBoolean; diff --git a/node_modules/@types/lodash/isBuffer.d.ts b/node_modules/@types/lodash/isBuffer.d.ts new file mode 100644 index 0000000..b22d782 --- /dev/null +++ b/node_modules/@types/lodash/isBuffer.d.ts @@ -0,0 +1,2 @@ +import { isBuffer } from "./index"; +export = isBuffer; diff --git a/node_modules/@types/lodash/isDate.d.ts b/node_modules/@types/lodash/isDate.d.ts new file mode 100644 index 0000000..1269a69 --- /dev/null +++ b/node_modules/@types/lodash/isDate.d.ts @@ -0,0 +1,2 @@ +import { isDate } from "./index"; +export = isDate; diff --git a/node_modules/@types/lodash/isElement.d.ts b/node_modules/@types/lodash/isElement.d.ts new file mode 100644 index 0000000..e4510cd --- /dev/null +++ b/node_modules/@types/lodash/isElement.d.ts @@ -0,0 +1,2 @@ +import { isElement } from "./index"; +export = isElement; diff --git a/node_modules/@types/lodash/isEmpty.d.ts b/node_modules/@types/lodash/isEmpty.d.ts new file mode 100644 index 0000000..9e71bfa --- /dev/null +++ b/node_modules/@types/lodash/isEmpty.d.ts @@ -0,0 +1,2 @@ +import { isEmpty } from "./index"; +export = isEmpty; diff --git a/node_modules/@types/lodash/isEqual.d.ts b/node_modules/@types/lodash/isEqual.d.ts new file mode 100644 index 0000000..1e065fa --- /dev/null +++ b/node_modules/@types/lodash/isEqual.d.ts @@ -0,0 +1,2 @@ +import { isEqual } from "./index"; +export = isEqual; diff --git a/node_modules/@types/lodash/isEqualWith.d.ts b/node_modules/@types/lodash/isEqualWith.d.ts new file mode 100644 index 0000000..e14d005 --- /dev/null +++ b/node_modules/@types/lodash/isEqualWith.d.ts @@ -0,0 +1,2 @@ +import { isEqualWith } from "./index"; +export = isEqualWith; diff --git a/node_modules/@types/lodash/isError.d.ts b/node_modules/@types/lodash/isError.d.ts new file mode 100644 index 0000000..d9d5785 --- /dev/null +++ b/node_modules/@types/lodash/isError.d.ts @@ -0,0 +1,2 @@ +import { isError } from "./index"; +export = isError; diff --git a/node_modules/@types/lodash/isFinite.d.ts b/node_modules/@types/lodash/isFinite.d.ts new file mode 100644 index 0000000..7aba1dc --- /dev/null +++ b/node_modules/@types/lodash/isFinite.d.ts @@ -0,0 +1,2 @@ +import { isFinite } from "./index"; +export = isFinite; diff --git a/node_modules/@types/lodash/isFunction.d.ts b/node_modules/@types/lodash/isFunction.d.ts new file mode 100644 index 0000000..0a22d6c --- /dev/null +++ b/node_modules/@types/lodash/isFunction.d.ts @@ -0,0 +1,2 @@ +import { isFunction } from "./index"; +export = isFunction; diff --git a/node_modules/@types/lodash/isInteger.d.ts b/node_modules/@types/lodash/isInteger.d.ts new file mode 100644 index 0000000..40d33d3 --- /dev/null +++ b/node_modules/@types/lodash/isInteger.d.ts @@ -0,0 +1,2 @@ +import { isInteger } from "./index"; +export = isInteger; diff --git a/node_modules/@types/lodash/isLength.d.ts b/node_modules/@types/lodash/isLength.d.ts new file mode 100644 index 0000000..ee5a933 --- /dev/null +++ b/node_modules/@types/lodash/isLength.d.ts @@ -0,0 +1,2 @@ +import { isLength } from "./index"; +export = isLength; diff --git a/node_modules/@types/lodash/isMap.d.ts b/node_modules/@types/lodash/isMap.d.ts new file mode 100644 index 0000000..441c538 --- /dev/null +++ b/node_modules/@types/lodash/isMap.d.ts @@ -0,0 +1,2 @@ +import { isMap } from "./index"; +export = isMap; diff --git a/node_modules/@types/lodash/isMatch.d.ts b/node_modules/@types/lodash/isMatch.d.ts new file mode 100644 index 0000000..69d194a --- /dev/null +++ b/node_modules/@types/lodash/isMatch.d.ts @@ -0,0 +1,2 @@ +import { isMatch } from "./index"; +export = isMatch; diff --git a/node_modules/@types/lodash/isMatchWith.d.ts b/node_modules/@types/lodash/isMatchWith.d.ts new file mode 100644 index 0000000..932310a --- /dev/null +++ b/node_modules/@types/lodash/isMatchWith.d.ts @@ -0,0 +1,2 @@ +import { isMatchWith } from "./index"; +export = isMatchWith; diff --git a/node_modules/@types/lodash/isNaN.d.ts b/node_modules/@types/lodash/isNaN.d.ts new file mode 100644 index 0000000..970702b --- /dev/null +++ b/node_modules/@types/lodash/isNaN.d.ts @@ -0,0 +1,2 @@ +import { isNaN } from "./index"; +export = isNaN; diff --git a/node_modules/@types/lodash/isNative.d.ts b/node_modules/@types/lodash/isNative.d.ts new file mode 100644 index 0000000..3174f8a --- /dev/null +++ b/node_modules/@types/lodash/isNative.d.ts @@ -0,0 +1,2 @@ +import { isNative } from "./index"; +export = isNative; diff --git a/node_modules/@types/lodash/isNil.d.ts b/node_modules/@types/lodash/isNil.d.ts new file mode 100644 index 0000000..9e15819 --- /dev/null +++ b/node_modules/@types/lodash/isNil.d.ts @@ -0,0 +1,2 @@ +import { isNil } from "./index"; +export = isNil; diff --git a/node_modules/@types/lodash/isNull.d.ts b/node_modules/@types/lodash/isNull.d.ts new file mode 100644 index 0000000..e572c45 --- /dev/null +++ b/node_modules/@types/lodash/isNull.d.ts @@ -0,0 +1,2 @@ +import { isNull } from "./index"; +export = isNull; diff --git a/node_modules/@types/lodash/isNumber.d.ts b/node_modules/@types/lodash/isNumber.d.ts new file mode 100644 index 0000000..91c8359 --- /dev/null +++ b/node_modules/@types/lodash/isNumber.d.ts @@ -0,0 +1,2 @@ +import { isNumber } from "./index"; +export = isNumber; diff --git a/node_modules/@types/lodash/isObject.d.ts b/node_modules/@types/lodash/isObject.d.ts new file mode 100644 index 0000000..9a43544 --- /dev/null +++ b/node_modules/@types/lodash/isObject.d.ts @@ -0,0 +1,2 @@ +import { isObject } from "./index"; +export = isObject; diff --git a/node_modules/@types/lodash/isObjectLike.d.ts b/node_modules/@types/lodash/isObjectLike.d.ts new file mode 100644 index 0000000..a17d39c --- /dev/null +++ b/node_modules/@types/lodash/isObjectLike.d.ts @@ -0,0 +1,2 @@ +import { isObjectLike } from "./index"; +export = isObjectLike; diff --git a/node_modules/@types/lodash/isPlainObject.d.ts b/node_modules/@types/lodash/isPlainObject.d.ts new file mode 100644 index 0000000..4df85e2 --- /dev/null +++ b/node_modules/@types/lodash/isPlainObject.d.ts @@ -0,0 +1,2 @@ +import { isPlainObject } from "./index"; +export = isPlainObject; diff --git a/node_modules/@types/lodash/isRegExp.d.ts b/node_modules/@types/lodash/isRegExp.d.ts new file mode 100644 index 0000000..ed206d9 --- /dev/null +++ b/node_modules/@types/lodash/isRegExp.d.ts @@ -0,0 +1,2 @@ +import { isRegExp } from "./index"; +export = isRegExp; diff --git a/node_modules/@types/lodash/isSafeInteger.d.ts b/node_modules/@types/lodash/isSafeInteger.d.ts new file mode 100644 index 0000000..6bc6083 --- /dev/null +++ b/node_modules/@types/lodash/isSafeInteger.d.ts @@ -0,0 +1,2 @@ +import { isSafeInteger } from "./index"; +export = isSafeInteger; diff --git a/node_modules/@types/lodash/isSet.d.ts b/node_modules/@types/lodash/isSet.d.ts new file mode 100644 index 0000000..7967b50 --- /dev/null +++ b/node_modules/@types/lodash/isSet.d.ts @@ -0,0 +1,2 @@ +import { isSet } from "./index"; +export = isSet; diff --git a/node_modules/@types/lodash/isString.d.ts b/node_modules/@types/lodash/isString.d.ts new file mode 100644 index 0000000..757802e --- /dev/null +++ b/node_modules/@types/lodash/isString.d.ts @@ -0,0 +1,2 @@ +import { isString } from "./index"; +export = isString; diff --git a/node_modules/@types/lodash/isSymbol.d.ts b/node_modules/@types/lodash/isSymbol.d.ts new file mode 100644 index 0000000..e28b2b0 --- /dev/null +++ b/node_modules/@types/lodash/isSymbol.d.ts @@ -0,0 +1,2 @@ +import { isSymbol } from "./index"; +export = isSymbol; diff --git a/node_modules/@types/lodash/isTypedArray.d.ts b/node_modules/@types/lodash/isTypedArray.d.ts new file mode 100644 index 0000000..7f32601 --- /dev/null +++ b/node_modules/@types/lodash/isTypedArray.d.ts @@ -0,0 +1,2 @@ +import { isTypedArray } from "./index"; +export = isTypedArray; diff --git a/node_modules/@types/lodash/isUndefined.d.ts b/node_modules/@types/lodash/isUndefined.d.ts new file mode 100644 index 0000000..7a5c64f --- /dev/null +++ b/node_modules/@types/lodash/isUndefined.d.ts @@ -0,0 +1,2 @@ +import { isUndefined } from "./index"; +export = isUndefined; diff --git a/node_modules/@types/lodash/isWeakMap.d.ts b/node_modules/@types/lodash/isWeakMap.d.ts new file mode 100644 index 0000000..b0609da --- /dev/null +++ b/node_modules/@types/lodash/isWeakMap.d.ts @@ -0,0 +1,2 @@ +import { isWeakMap } from "./index"; +export = isWeakMap; diff --git a/node_modules/@types/lodash/isWeakSet.d.ts b/node_modules/@types/lodash/isWeakSet.d.ts new file mode 100644 index 0000000..6beda3d --- /dev/null +++ b/node_modules/@types/lodash/isWeakSet.d.ts @@ -0,0 +1,2 @@ +import { isWeakSet } from "./index"; +export = isWeakSet; diff --git a/node_modules/@types/lodash/iteratee.d.ts b/node_modules/@types/lodash/iteratee.d.ts new file mode 100644 index 0000000..493b39c --- /dev/null +++ b/node_modules/@types/lodash/iteratee.d.ts @@ -0,0 +1,2 @@ +import { iteratee } from "./index"; +export = iteratee; diff --git a/node_modules/@types/lodash/join.d.ts b/node_modules/@types/lodash/join.d.ts new file mode 100644 index 0000000..b2c5fb4 --- /dev/null +++ b/node_modules/@types/lodash/join.d.ts @@ -0,0 +1,2 @@ +import { join } from "./index"; +export = join; diff --git a/node_modules/@types/lodash/kebabCase.d.ts b/node_modules/@types/lodash/kebabCase.d.ts new file mode 100644 index 0000000..c088ef7 --- /dev/null +++ b/node_modules/@types/lodash/kebabCase.d.ts @@ -0,0 +1,2 @@ +import { kebabCase } from "./index"; +export = kebabCase; diff --git a/node_modules/@types/lodash/keyBy.d.ts b/node_modules/@types/lodash/keyBy.d.ts new file mode 100644 index 0000000..664a722 --- /dev/null +++ b/node_modules/@types/lodash/keyBy.d.ts @@ -0,0 +1,2 @@ +import { keyBy } from "./index"; +export = keyBy; diff --git a/node_modules/@types/lodash/keys.d.ts b/node_modules/@types/lodash/keys.d.ts new file mode 100644 index 0000000..7eb29a0 --- /dev/null +++ b/node_modules/@types/lodash/keys.d.ts @@ -0,0 +1,2 @@ +import { keys } from "./index"; +export = keys; diff --git a/node_modules/@types/lodash/keysIn.d.ts b/node_modules/@types/lodash/keysIn.d.ts new file mode 100644 index 0000000..c9eeee6 --- /dev/null +++ b/node_modules/@types/lodash/keysIn.d.ts @@ -0,0 +1,2 @@ +import { keysIn } from "./index"; +export = keysIn; diff --git a/node_modules/@types/lodash/last.d.ts b/node_modules/@types/lodash/last.d.ts new file mode 100644 index 0000000..cfdeb75 --- /dev/null +++ b/node_modules/@types/lodash/last.d.ts @@ -0,0 +1,2 @@ +import { last } from "./index"; +export = last; diff --git a/node_modules/@types/lodash/lastIndexOf.d.ts b/node_modules/@types/lodash/lastIndexOf.d.ts new file mode 100644 index 0000000..979d80d --- /dev/null +++ b/node_modules/@types/lodash/lastIndexOf.d.ts @@ -0,0 +1,2 @@ +import { lastIndexOf } from "./index"; +export = lastIndexOf; diff --git a/node_modules/@types/lodash/lowerCase.d.ts b/node_modules/@types/lodash/lowerCase.d.ts new file mode 100644 index 0000000..475297d --- /dev/null +++ b/node_modules/@types/lodash/lowerCase.d.ts @@ -0,0 +1,2 @@ +import { lowerCase } from "./index"; +export = lowerCase; diff --git a/node_modules/@types/lodash/lowerFirst.d.ts b/node_modules/@types/lodash/lowerFirst.d.ts new file mode 100644 index 0000000..0836228 --- /dev/null +++ b/node_modules/@types/lodash/lowerFirst.d.ts @@ -0,0 +1,2 @@ +import { lowerFirst } from "./index"; +export = lowerFirst; diff --git a/node_modules/@types/lodash/lt.d.ts b/node_modules/@types/lodash/lt.d.ts new file mode 100644 index 0000000..92cd4e2 --- /dev/null +++ b/node_modules/@types/lodash/lt.d.ts @@ -0,0 +1,2 @@ +import { lt } from "./index"; +export = lt; diff --git a/node_modules/@types/lodash/lte.d.ts b/node_modules/@types/lodash/lte.d.ts new file mode 100644 index 0000000..7c80f37 --- /dev/null +++ b/node_modules/@types/lodash/lte.d.ts @@ -0,0 +1,2 @@ +import { lte } from "./index"; +export = lte; diff --git a/node_modules/@types/lodash/map.d.ts b/node_modules/@types/lodash/map.d.ts new file mode 100644 index 0000000..2f783cb --- /dev/null +++ b/node_modules/@types/lodash/map.d.ts @@ -0,0 +1,2 @@ +import { map } from "./index"; +export = map; diff --git a/node_modules/@types/lodash/mapKeys.d.ts b/node_modules/@types/lodash/mapKeys.d.ts new file mode 100644 index 0000000..7c7e1b5 --- /dev/null +++ b/node_modules/@types/lodash/mapKeys.d.ts @@ -0,0 +1,2 @@ +import { mapKeys } from "./index"; +export = mapKeys; diff --git a/node_modules/@types/lodash/mapValues.d.ts b/node_modules/@types/lodash/mapValues.d.ts new file mode 100644 index 0000000..3e87ea6 --- /dev/null +++ b/node_modules/@types/lodash/mapValues.d.ts @@ -0,0 +1,2 @@ +import { mapValues } from "./index"; +export = mapValues; diff --git a/node_modules/@types/lodash/matches.d.ts b/node_modules/@types/lodash/matches.d.ts new file mode 100644 index 0000000..5bb3cc2 --- /dev/null +++ b/node_modules/@types/lodash/matches.d.ts @@ -0,0 +1,2 @@ +import { matches } from "./index"; +export = matches; diff --git a/node_modules/@types/lodash/matchesProperty.d.ts b/node_modules/@types/lodash/matchesProperty.d.ts new file mode 100644 index 0000000..7378498 --- /dev/null +++ b/node_modules/@types/lodash/matchesProperty.d.ts @@ -0,0 +1,2 @@ +import { matchesProperty } from "./index"; +export = matchesProperty; diff --git a/node_modules/@types/lodash/max.d.ts b/node_modules/@types/lodash/max.d.ts new file mode 100644 index 0000000..36d0646 --- /dev/null +++ b/node_modules/@types/lodash/max.d.ts @@ -0,0 +1,2 @@ +import { max } from "./index"; +export = max; diff --git a/node_modules/@types/lodash/maxBy.d.ts b/node_modules/@types/lodash/maxBy.d.ts new file mode 100644 index 0000000..d483d95 --- /dev/null +++ b/node_modules/@types/lodash/maxBy.d.ts @@ -0,0 +1,2 @@ +import { maxBy } from "./index"; +export = maxBy; diff --git a/node_modules/@types/lodash/mean.d.ts b/node_modules/@types/lodash/mean.d.ts new file mode 100644 index 0000000..983ad77 --- /dev/null +++ b/node_modules/@types/lodash/mean.d.ts @@ -0,0 +1,2 @@ +import { mean } from "./index"; +export = mean; diff --git a/node_modules/@types/lodash/meanBy.d.ts b/node_modules/@types/lodash/meanBy.d.ts new file mode 100644 index 0000000..67aebbb --- /dev/null +++ b/node_modules/@types/lodash/meanBy.d.ts @@ -0,0 +1,2 @@ +import { meanBy } from "./index"; +export = meanBy; diff --git a/node_modules/@types/lodash/memoize.d.ts b/node_modules/@types/lodash/memoize.d.ts new file mode 100644 index 0000000..6ff535b --- /dev/null +++ b/node_modules/@types/lodash/memoize.d.ts @@ -0,0 +1,2 @@ +import { memoize } from "./index"; +export = memoize; diff --git a/node_modules/@types/lodash/merge.d.ts b/node_modules/@types/lodash/merge.d.ts new file mode 100644 index 0000000..eb8bd95 --- /dev/null +++ b/node_modules/@types/lodash/merge.d.ts @@ -0,0 +1,2 @@ +import { merge } from "./index"; +export = merge; diff --git a/node_modules/@types/lodash/mergeWith.d.ts b/node_modules/@types/lodash/mergeWith.d.ts new file mode 100644 index 0000000..a58dd90 --- /dev/null +++ b/node_modules/@types/lodash/mergeWith.d.ts @@ -0,0 +1,2 @@ +import { mergeWith } from "./index"; +export = mergeWith; diff --git a/node_modules/@types/lodash/method.d.ts b/node_modules/@types/lodash/method.d.ts new file mode 100644 index 0000000..cc30588 --- /dev/null +++ b/node_modules/@types/lodash/method.d.ts @@ -0,0 +1,2 @@ +import { method } from "./index"; +export = method; diff --git a/node_modules/@types/lodash/methodOf.d.ts b/node_modules/@types/lodash/methodOf.d.ts new file mode 100644 index 0000000..af7f19a --- /dev/null +++ b/node_modules/@types/lodash/methodOf.d.ts @@ -0,0 +1,2 @@ +import { methodOf } from "./index"; +export = methodOf; diff --git a/node_modules/@types/lodash/min.d.ts b/node_modules/@types/lodash/min.d.ts new file mode 100644 index 0000000..e8ba597 --- /dev/null +++ b/node_modules/@types/lodash/min.d.ts @@ -0,0 +1,2 @@ +import { min } from "./index"; +export = min; diff --git a/node_modules/@types/lodash/minBy.d.ts b/node_modules/@types/lodash/minBy.d.ts new file mode 100644 index 0000000..74860f9 --- /dev/null +++ b/node_modules/@types/lodash/minBy.d.ts @@ -0,0 +1,2 @@ +import { minBy } from "./index"; +export = minBy; diff --git a/node_modules/@types/lodash/mixin.d.ts b/node_modules/@types/lodash/mixin.d.ts new file mode 100644 index 0000000..7984246 --- /dev/null +++ b/node_modules/@types/lodash/mixin.d.ts @@ -0,0 +1,2 @@ +import { mixin } from "./index"; +export = mixin; diff --git a/node_modules/@types/lodash/negate.d.ts b/node_modules/@types/lodash/negate.d.ts new file mode 100644 index 0000000..46d0596 --- /dev/null +++ b/node_modules/@types/lodash/negate.d.ts @@ -0,0 +1,2 @@ +import { negate } from "./index"; +export = negate; diff --git a/node_modules/@types/lodash/noConflict.d.ts b/node_modules/@types/lodash/noConflict.d.ts new file mode 100644 index 0000000..78b3c92 --- /dev/null +++ b/node_modules/@types/lodash/noConflict.d.ts @@ -0,0 +1,2 @@ +import { noConflict } from "./index"; +export = noConflict; diff --git a/node_modules/@types/lodash/noop.d.ts b/node_modules/@types/lodash/noop.d.ts new file mode 100644 index 0000000..bfaeb88 --- /dev/null +++ b/node_modules/@types/lodash/noop.d.ts @@ -0,0 +1,2 @@ +import { noop } from "./index"; +export = noop; diff --git a/node_modules/@types/lodash/now.d.ts b/node_modules/@types/lodash/now.d.ts new file mode 100644 index 0000000..00f807e --- /dev/null +++ b/node_modules/@types/lodash/now.d.ts @@ -0,0 +1,2 @@ +import { now } from "./index"; +export = now; diff --git a/node_modules/@types/lodash/nth.d.ts b/node_modules/@types/lodash/nth.d.ts new file mode 100644 index 0000000..ce1013f --- /dev/null +++ b/node_modules/@types/lodash/nth.d.ts @@ -0,0 +1,2 @@ +import { nth } from "./index"; +export = nth; diff --git a/node_modules/@types/lodash/nthArg.d.ts b/node_modules/@types/lodash/nthArg.d.ts new file mode 100644 index 0000000..2729d70 --- /dev/null +++ b/node_modules/@types/lodash/nthArg.d.ts @@ -0,0 +1,2 @@ +import { nthArg } from "./index"; +export = nthArg; diff --git a/node_modules/@types/lodash/omit.d.ts b/node_modules/@types/lodash/omit.d.ts new file mode 100644 index 0000000..5868a07 --- /dev/null +++ b/node_modules/@types/lodash/omit.d.ts @@ -0,0 +1,2 @@ +import { omit } from "./index"; +export = omit; diff --git a/node_modules/@types/lodash/omitBy.d.ts b/node_modules/@types/lodash/omitBy.d.ts new file mode 100644 index 0000000..41bf6b4 --- /dev/null +++ b/node_modules/@types/lodash/omitBy.d.ts @@ -0,0 +1,2 @@ +import { omitBy } from "./index"; +export = omitBy; diff --git a/node_modules/@types/lodash/once.d.ts b/node_modules/@types/lodash/once.d.ts new file mode 100644 index 0000000..4340e88 --- /dev/null +++ b/node_modules/@types/lodash/once.d.ts @@ -0,0 +1,2 @@ +import { once } from "./index"; +export = once; diff --git a/node_modules/@types/lodash/orderBy.d.ts b/node_modules/@types/lodash/orderBy.d.ts new file mode 100644 index 0000000..02320d5 --- /dev/null +++ b/node_modules/@types/lodash/orderBy.d.ts @@ -0,0 +1,2 @@ +import { orderBy } from "./index"; +export = orderBy; diff --git a/node_modules/@types/lodash/over.d.ts b/node_modules/@types/lodash/over.d.ts new file mode 100644 index 0000000..172c822 --- /dev/null +++ b/node_modules/@types/lodash/over.d.ts @@ -0,0 +1,2 @@ +import { over } from "./index"; +export = over; diff --git a/node_modules/@types/lodash/overArgs.d.ts b/node_modules/@types/lodash/overArgs.d.ts new file mode 100644 index 0000000..f8518f6 --- /dev/null +++ b/node_modules/@types/lodash/overArgs.d.ts @@ -0,0 +1,2 @@ +import { overArgs } from "./index"; +export = overArgs; diff --git a/node_modules/@types/lodash/overEvery.d.ts b/node_modules/@types/lodash/overEvery.d.ts new file mode 100644 index 0000000..b8328fb --- /dev/null +++ b/node_modules/@types/lodash/overEvery.d.ts @@ -0,0 +1,2 @@ +import { overEvery } from "./index"; +export = overEvery; diff --git a/node_modules/@types/lodash/overSome.d.ts b/node_modules/@types/lodash/overSome.d.ts new file mode 100644 index 0000000..2f17258 --- /dev/null +++ b/node_modules/@types/lodash/overSome.d.ts @@ -0,0 +1,2 @@ +import { overSome } from "./index"; +export = overSome; diff --git a/node_modules/@types/lodash/package.json b/node_modules/@types/lodash/package.json new file mode 100644 index 0000000..a3dc572 --- /dev/null +++ b/node_modules/@types/lodash/package.json @@ -0,0 +1,84 @@ +{ + "_from": "@types/lodash@*", + "_id": "@types/lodash@4.14.119", + "_inBundle": false, + "_integrity": "sha512-Z3TNyBL8Vd/M9D9Ms2S3LmFq2sSMzahodD6rCS9V2N44HUMINb75jNkSuwAx7eo2ufqTdfOdtGQpNbieUjPQmw==", + "_location": "/@types/lodash", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "@types/lodash@*", + "name": "@types/lodash", + "escapedName": "@types%2flodash", + "scope": "@types", + "rawSpec": "*", + "saveSpec": null, + "fetchSpec": "*" + }, + "_requiredBy": [ + "/@types/lodash.flatten" + ], + "_resolved": "https://registry.npmjs.org/@types/lodash/-/lodash-4.14.119.tgz", + "_shasum": "be847e5f4bc3e35e46d041c394ead8b603ad8b39", + "_spec": "@types/lodash@*", + "_where": "/Users/jessitron/code/jessitron/stringify-tree/node_modules/@types/lodash.flatten", + "bugs": { + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped/issues" + }, + "bundleDependencies": false, + "contributors": [ + { + "name": "Brian Zengel", + "url": "https://github.com/bczengel" + }, + { + "name": "Ilya Mochalov", + "url": "https://github.com/chrootsu" + }, + { + "name": "Stepan Mikhaylyuk", + "url": "https://github.com/stepancar" + }, + { + "name": "AJ Richardson", + "url": "https://github.com/aj-r" + }, + { + "name": "Junyoung Clare Jang", + "url": "https://github.com/ailrun" + }, + { + "name": "e-cloud", + "url": "https://github.com/e-cloud" + }, + { + "name": "Georgii Dolzhykov", + "url": "https://github.com/thorn0" + }, + { + "name": "Jack Moore", + "url": "https://github.com/jtmthf" + }, + { + "name": "Dominique Rau", + "url": "https://github.com/DomiR" + } + ], + "dependencies": {}, + "deprecated": false, + "description": "TypeScript definitions for Lo-Dash", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped#readme", + "license": "MIT", + "main": "", + "name": "@types/lodash", + "repository": { + "type": "git", + "url": "git+https://github.com/DefinitelyTyped/DefinitelyTyped.git" + }, + "scripts": {}, + "typeScriptVersion": "2.6", + "types": "index", + "typesPublisherContentHash": "7fed5fbfc26139d57cf40ffce7716a91e8343701cf12fe238051c81804c6de70", + "version": "4.14.119" +} diff --git a/node_modules/@types/lodash/pad.d.ts b/node_modules/@types/lodash/pad.d.ts new file mode 100644 index 0000000..552667a --- /dev/null +++ b/node_modules/@types/lodash/pad.d.ts @@ -0,0 +1,2 @@ +import { pad } from "./index"; +export = pad; diff --git a/node_modules/@types/lodash/padEnd.d.ts b/node_modules/@types/lodash/padEnd.d.ts new file mode 100644 index 0000000..c81a7b0 --- /dev/null +++ b/node_modules/@types/lodash/padEnd.d.ts @@ -0,0 +1,2 @@ +import { padEnd } from "./index"; +export = padEnd; diff --git a/node_modules/@types/lodash/padStart.d.ts b/node_modules/@types/lodash/padStart.d.ts new file mode 100644 index 0000000..c119c35 --- /dev/null +++ b/node_modules/@types/lodash/padStart.d.ts @@ -0,0 +1,2 @@ +import { padStart } from "./index"; +export = padStart; diff --git a/node_modules/@types/lodash/parseInt.d.ts b/node_modules/@types/lodash/parseInt.d.ts new file mode 100644 index 0000000..de59e7b --- /dev/null +++ b/node_modules/@types/lodash/parseInt.d.ts @@ -0,0 +1,2 @@ +import { parseInt } from "./index"; +export = parseInt; diff --git a/node_modules/@types/lodash/partial.d.ts b/node_modules/@types/lodash/partial.d.ts new file mode 100644 index 0000000..d764f6e --- /dev/null +++ b/node_modules/@types/lodash/partial.d.ts @@ -0,0 +1,2 @@ +import { partial } from "./index"; +export = partial; diff --git a/node_modules/@types/lodash/partialRight.d.ts b/node_modules/@types/lodash/partialRight.d.ts new file mode 100644 index 0000000..ed60160 --- /dev/null +++ b/node_modules/@types/lodash/partialRight.d.ts @@ -0,0 +1,2 @@ +import { partialRight } from "./index"; +export = partialRight; diff --git a/node_modules/@types/lodash/partition.d.ts b/node_modules/@types/lodash/partition.d.ts new file mode 100644 index 0000000..f26ab15 --- /dev/null +++ b/node_modules/@types/lodash/partition.d.ts @@ -0,0 +1,2 @@ +import { partition } from "./index"; +export = partition; diff --git a/node_modules/@types/lodash/pick.d.ts b/node_modules/@types/lodash/pick.d.ts new file mode 100644 index 0000000..6d346f8 --- /dev/null +++ b/node_modules/@types/lodash/pick.d.ts @@ -0,0 +1,2 @@ +import { pick } from "./index"; +export = pick; diff --git a/node_modules/@types/lodash/pickBy.d.ts b/node_modules/@types/lodash/pickBy.d.ts new file mode 100644 index 0000000..5285ead --- /dev/null +++ b/node_modules/@types/lodash/pickBy.d.ts @@ -0,0 +1,2 @@ +import { pickBy } from "./index"; +export = pickBy; diff --git a/node_modules/@types/lodash/property.d.ts b/node_modules/@types/lodash/property.d.ts new file mode 100644 index 0000000..3ff96f0 --- /dev/null +++ b/node_modules/@types/lodash/property.d.ts @@ -0,0 +1,2 @@ +import { property } from "./index"; +export = property; diff --git a/node_modules/@types/lodash/propertyOf.d.ts b/node_modules/@types/lodash/propertyOf.d.ts new file mode 100644 index 0000000..27c628f --- /dev/null +++ b/node_modules/@types/lodash/propertyOf.d.ts @@ -0,0 +1,2 @@ +import { propertyOf } from "./index"; +export = propertyOf; diff --git a/node_modules/@types/lodash/pull.d.ts b/node_modules/@types/lodash/pull.d.ts new file mode 100644 index 0000000..b496ebd --- /dev/null +++ b/node_modules/@types/lodash/pull.d.ts @@ -0,0 +1,2 @@ +import { pull } from "./index"; +export = pull; diff --git a/node_modules/@types/lodash/pullAll.d.ts b/node_modules/@types/lodash/pullAll.d.ts new file mode 100644 index 0000000..22c81c4 --- /dev/null +++ b/node_modules/@types/lodash/pullAll.d.ts @@ -0,0 +1,2 @@ +import { pullAll } from "./index"; +export = pullAll; diff --git a/node_modules/@types/lodash/pullAllBy.d.ts b/node_modules/@types/lodash/pullAllBy.d.ts new file mode 100644 index 0000000..e0629ce --- /dev/null +++ b/node_modules/@types/lodash/pullAllBy.d.ts @@ -0,0 +1,2 @@ +import { pullAllBy } from "./index"; +export = pullAllBy; diff --git a/node_modules/@types/lodash/pullAllWith.d.ts b/node_modules/@types/lodash/pullAllWith.d.ts new file mode 100644 index 0000000..d3ce829 --- /dev/null +++ b/node_modules/@types/lodash/pullAllWith.d.ts @@ -0,0 +1,2 @@ +import { pullAllWith } from "./index"; +export = pullAllWith; diff --git a/node_modules/@types/lodash/pullAt.d.ts b/node_modules/@types/lodash/pullAt.d.ts new file mode 100644 index 0000000..47be382 --- /dev/null +++ b/node_modules/@types/lodash/pullAt.d.ts @@ -0,0 +1,2 @@ +import { pullAt } from "./index"; +export = pullAt; diff --git a/node_modules/@types/lodash/random.d.ts b/node_modules/@types/lodash/random.d.ts new file mode 100644 index 0000000..a68cc27 --- /dev/null +++ b/node_modules/@types/lodash/random.d.ts @@ -0,0 +1,2 @@ +import { random } from "./index"; +export = random; diff --git a/node_modules/@types/lodash/range.d.ts b/node_modules/@types/lodash/range.d.ts new file mode 100644 index 0000000..8f737ca --- /dev/null +++ b/node_modules/@types/lodash/range.d.ts @@ -0,0 +1,2 @@ +import { range } from "./index"; +export = range; diff --git a/node_modules/@types/lodash/rangeRight.d.ts b/node_modules/@types/lodash/rangeRight.d.ts new file mode 100644 index 0000000..cabd0ed --- /dev/null +++ b/node_modules/@types/lodash/rangeRight.d.ts @@ -0,0 +1,2 @@ +import { rangeRight } from "./index"; +export = rangeRight; diff --git a/node_modules/@types/lodash/rearg.d.ts b/node_modules/@types/lodash/rearg.d.ts new file mode 100644 index 0000000..7684e86 --- /dev/null +++ b/node_modules/@types/lodash/rearg.d.ts @@ -0,0 +1,2 @@ +import { rearg } from "./index"; +export = rearg; diff --git a/node_modules/@types/lodash/reduce.d.ts b/node_modules/@types/lodash/reduce.d.ts new file mode 100644 index 0000000..4765fcd --- /dev/null +++ b/node_modules/@types/lodash/reduce.d.ts @@ -0,0 +1,2 @@ +import { reduce } from "./index"; +export = reduce; diff --git a/node_modules/@types/lodash/reduceRight.d.ts b/node_modules/@types/lodash/reduceRight.d.ts new file mode 100644 index 0000000..1cfdb5f --- /dev/null +++ b/node_modules/@types/lodash/reduceRight.d.ts @@ -0,0 +1,2 @@ +import { reduceRight } from "./index"; +export = reduceRight; diff --git a/node_modules/@types/lodash/reject.d.ts b/node_modules/@types/lodash/reject.d.ts new file mode 100644 index 0000000..aabc141 --- /dev/null +++ b/node_modules/@types/lodash/reject.d.ts @@ -0,0 +1,2 @@ +import { reject } from "./index"; +export = reject; diff --git a/node_modules/@types/lodash/remove.d.ts b/node_modules/@types/lodash/remove.d.ts new file mode 100644 index 0000000..dca4718 --- /dev/null +++ b/node_modules/@types/lodash/remove.d.ts @@ -0,0 +1,2 @@ +import { remove } from "./index"; +export = remove; diff --git a/node_modules/@types/lodash/repeat.d.ts b/node_modules/@types/lodash/repeat.d.ts new file mode 100644 index 0000000..ca3c7fc --- /dev/null +++ b/node_modules/@types/lodash/repeat.d.ts @@ -0,0 +1,2 @@ +import { repeat } from "./index"; +export = repeat; diff --git a/node_modules/@types/lodash/replace.d.ts b/node_modules/@types/lodash/replace.d.ts new file mode 100644 index 0000000..7015411 --- /dev/null +++ b/node_modules/@types/lodash/replace.d.ts @@ -0,0 +1,2 @@ +import { replace } from "./index"; +export = replace; diff --git a/node_modules/@types/lodash/rest.d.ts b/node_modules/@types/lodash/rest.d.ts new file mode 100644 index 0000000..433a4fd --- /dev/null +++ b/node_modules/@types/lodash/rest.d.ts @@ -0,0 +1,2 @@ +import { rest } from "./index"; +export = rest; diff --git a/node_modules/@types/lodash/result.d.ts b/node_modules/@types/lodash/result.d.ts new file mode 100644 index 0000000..6578642 --- /dev/null +++ b/node_modules/@types/lodash/result.d.ts @@ -0,0 +1,2 @@ +import { result } from "./index"; +export = result; diff --git a/node_modules/@types/lodash/reverse.d.ts b/node_modules/@types/lodash/reverse.d.ts new file mode 100644 index 0000000..ecef173 --- /dev/null +++ b/node_modules/@types/lodash/reverse.d.ts @@ -0,0 +1,2 @@ +import { reverse } from "./index"; +export = reverse; diff --git a/node_modules/@types/lodash/round.d.ts b/node_modules/@types/lodash/round.d.ts new file mode 100644 index 0000000..ed2c179 --- /dev/null +++ b/node_modules/@types/lodash/round.d.ts @@ -0,0 +1,2 @@ +import { round } from "./index"; +export = round; diff --git a/node_modules/@types/lodash/runInContext.d.ts b/node_modules/@types/lodash/runInContext.d.ts new file mode 100644 index 0000000..9ee01f3 --- /dev/null +++ b/node_modules/@types/lodash/runInContext.d.ts @@ -0,0 +1,2 @@ +import { runInContext } from "./index"; +export = runInContext; diff --git a/node_modules/@types/lodash/sample.d.ts b/node_modules/@types/lodash/sample.d.ts new file mode 100644 index 0000000..c225178 --- /dev/null +++ b/node_modules/@types/lodash/sample.d.ts @@ -0,0 +1,2 @@ +import { sample } from "./index"; +export = sample; diff --git a/node_modules/@types/lodash/sampleSize.d.ts b/node_modules/@types/lodash/sampleSize.d.ts new file mode 100644 index 0000000..0f1ed89 --- /dev/null +++ b/node_modules/@types/lodash/sampleSize.d.ts @@ -0,0 +1,2 @@ +import { sampleSize } from "./index"; +export = sampleSize; diff --git a/node_modules/@types/lodash/set.d.ts b/node_modules/@types/lodash/set.d.ts new file mode 100644 index 0000000..09d0c24 --- /dev/null +++ b/node_modules/@types/lodash/set.d.ts @@ -0,0 +1,2 @@ +import { set } from "./index"; +export = set; diff --git a/node_modules/@types/lodash/setWith.d.ts b/node_modules/@types/lodash/setWith.d.ts new file mode 100644 index 0000000..d4e319a --- /dev/null +++ b/node_modules/@types/lodash/setWith.d.ts @@ -0,0 +1,2 @@ +import { setWith } from "./index"; +export = setWith; diff --git a/node_modules/@types/lodash/shuffle.d.ts b/node_modules/@types/lodash/shuffle.d.ts new file mode 100644 index 0000000..ff96f88 --- /dev/null +++ b/node_modules/@types/lodash/shuffle.d.ts @@ -0,0 +1,2 @@ +import { shuffle } from "./index"; +export = shuffle; diff --git a/node_modules/@types/lodash/size.d.ts b/node_modules/@types/lodash/size.d.ts new file mode 100644 index 0000000..13d492f --- /dev/null +++ b/node_modules/@types/lodash/size.d.ts @@ -0,0 +1,2 @@ +import { size } from "./index"; +export = size; diff --git a/node_modules/@types/lodash/slice.d.ts b/node_modules/@types/lodash/slice.d.ts new file mode 100644 index 0000000..311d2fa --- /dev/null +++ b/node_modules/@types/lodash/slice.d.ts @@ -0,0 +1,2 @@ +import { slice } from "./index"; +export = slice; diff --git a/node_modules/@types/lodash/snakeCase.d.ts b/node_modules/@types/lodash/snakeCase.d.ts new file mode 100644 index 0000000..8245a7d --- /dev/null +++ b/node_modules/@types/lodash/snakeCase.d.ts @@ -0,0 +1,2 @@ +import { snakeCase } from "./index"; +export = snakeCase; diff --git a/node_modules/@types/lodash/some.d.ts b/node_modules/@types/lodash/some.d.ts new file mode 100644 index 0000000..90ef478 --- /dev/null +++ b/node_modules/@types/lodash/some.d.ts @@ -0,0 +1,2 @@ +import { some } from "./index"; +export = some; diff --git a/node_modules/@types/lodash/sortBy.d.ts b/node_modules/@types/lodash/sortBy.d.ts new file mode 100644 index 0000000..5f3d4f2 --- /dev/null +++ b/node_modules/@types/lodash/sortBy.d.ts @@ -0,0 +1,2 @@ +import { sortBy } from "./index"; +export = sortBy; diff --git a/node_modules/@types/lodash/sortedIndex.d.ts b/node_modules/@types/lodash/sortedIndex.d.ts new file mode 100644 index 0000000..c9c7911 --- /dev/null +++ b/node_modules/@types/lodash/sortedIndex.d.ts @@ -0,0 +1,2 @@ +import { sortedIndex } from "./index"; +export = sortedIndex; diff --git a/node_modules/@types/lodash/sortedIndexBy.d.ts b/node_modules/@types/lodash/sortedIndexBy.d.ts new file mode 100644 index 0000000..fdbedac --- /dev/null +++ b/node_modules/@types/lodash/sortedIndexBy.d.ts @@ -0,0 +1,2 @@ +import { sortedIndexBy } from "./index"; +export = sortedIndexBy; diff --git a/node_modules/@types/lodash/sortedIndexOf.d.ts b/node_modules/@types/lodash/sortedIndexOf.d.ts new file mode 100644 index 0000000..a076c4a --- /dev/null +++ b/node_modules/@types/lodash/sortedIndexOf.d.ts @@ -0,0 +1,2 @@ +import { sortedIndexOf } from "./index"; +export = sortedIndexOf; diff --git a/node_modules/@types/lodash/sortedLastIndex.d.ts b/node_modules/@types/lodash/sortedLastIndex.d.ts new file mode 100644 index 0000000..808c2c0 --- /dev/null +++ b/node_modules/@types/lodash/sortedLastIndex.d.ts @@ -0,0 +1,2 @@ +import { sortedLastIndex } from "./index"; +export = sortedLastIndex; diff --git a/node_modules/@types/lodash/sortedLastIndexBy.d.ts b/node_modules/@types/lodash/sortedLastIndexBy.d.ts new file mode 100644 index 0000000..9f23b9b --- /dev/null +++ b/node_modules/@types/lodash/sortedLastIndexBy.d.ts @@ -0,0 +1,2 @@ +import { sortedLastIndexBy } from "./index"; +export = sortedLastIndexBy; diff --git a/node_modules/@types/lodash/sortedLastIndexOf.d.ts b/node_modules/@types/lodash/sortedLastIndexOf.d.ts new file mode 100644 index 0000000..abdeba0 --- /dev/null +++ b/node_modules/@types/lodash/sortedLastIndexOf.d.ts @@ -0,0 +1,2 @@ +import { sortedLastIndexOf } from "./index"; +export = sortedLastIndexOf; diff --git a/node_modules/@types/lodash/sortedUniq.d.ts b/node_modules/@types/lodash/sortedUniq.d.ts new file mode 100644 index 0000000..257d35a --- /dev/null +++ b/node_modules/@types/lodash/sortedUniq.d.ts @@ -0,0 +1,2 @@ +import { sortedUniq } from "./index"; +export = sortedUniq; diff --git a/node_modules/@types/lodash/sortedUniqBy.d.ts b/node_modules/@types/lodash/sortedUniqBy.d.ts new file mode 100644 index 0000000..316156e --- /dev/null +++ b/node_modules/@types/lodash/sortedUniqBy.d.ts @@ -0,0 +1,2 @@ +import { sortedUniqBy } from "./index"; +export = sortedUniqBy; diff --git a/node_modules/@types/lodash/split.d.ts b/node_modules/@types/lodash/split.d.ts new file mode 100644 index 0000000..8879eb0 --- /dev/null +++ b/node_modules/@types/lodash/split.d.ts @@ -0,0 +1,2 @@ +import { split } from "./index"; +export = split; diff --git a/node_modules/@types/lodash/spread.d.ts b/node_modules/@types/lodash/spread.d.ts new file mode 100644 index 0000000..4f816b2 --- /dev/null +++ b/node_modules/@types/lodash/spread.d.ts @@ -0,0 +1,2 @@ +import { spread } from "./index"; +export = spread; diff --git a/node_modules/@types/lodash/startCase.d.ts b/node_modules/@types/lodash/startCase.d.ts new file mode 100644 index 0000000..c201a11 --- /dev/null +++ b/node_modules/@types/lodash/startCase.d.ts @@ -0,0 +1,2 @@ +import { startCase } from "./index"; +export = startCase; diff --git a/node_modules/@types/lodash/startsWith.d.ts b/node_modules/@types/lodash/startsWith.d.ts new file mode 100644 index 0000000..a18b54f --- /dev/null +++ b/node_modules/@types/lodash/startsWith.d.ts @@ -0,0 +1,2 @@ +import { startsWith } from "./index"; +export = startsWith; diff --git a/node_modules/@types/lodash/subtract.d.ts b/node_modules/@types/lodash/subtract.d.ts new file mode 100644 index 0000000..6502fe2 --- /dev/null +++ b/node_modules/@types/lodash/subtract.d.ts @@ -0,0 +1,2 @@ +import { subtract } from "./index"; +export = subtract; diff --git a/node_modules/@types/lodash/sum.d.ts b/node_modules/@types/lodash/sum.d.ts new file mode 100644 index 0000000..4e01cb4 --- /dev/null +++ b/node_modules/@types/lodash/sum.d.ts @@ -0,0 +1,2 @@ +import { sum } from "./index"; +export = sum; diff --git a/node_modules/@types/lodash/sumBy.d.ts b/node_modules/@types/lodash/sumBy.d.ts new file mode 100644 index 0000000..92c4342 --- /dev/null +++ b/node_modules/@types/lodash/sumBy.d.ts @@ -0,0 +1,2 @@ +import { sumBy } from "./index"; +export = sumBy; diff --git a/node_modules/@types/lodash/tail.d.ts b/node_modules/@types/lodash/tail.d.ts new file mode 100644 index 0000000..2d80b44 --- /dev/null +++ b/node_modules/@types/lodash/tail.d.ts @@ -0,0 +1,2 @@ +import { tail } from "./index"; +export = tail; diff --git a/node_modules/@types/lodash/take.d.ts b/node_modules/@types/lodash/take.d.ts new file mode 100644 index 0000000..be99122 --- /dev/null +++ b/node_modules/@types/lodash/take.d.ts @@ -0,0 +1,2 @@ +import { take } from "./index"; +export = take; diff --git a/node_modules/@types/lodash/takeRight.d.ts b/node_modules/@types/lodash/takeRight.d.ts new file mode 100644 index 0000000..9d78866 --- /dev/null +++ b/node_modules/@types/lodash/takeRight.d.ts @@ -0,0 +1,2 @@ +import { takeRight } from "./index"; +export = takeRight; diff --git a/node_modules/@types/lodash/takeRightWhile.d.ts b/node_modules/@types/lodash/takeRightWhile.d.ts new file mode 100644 index 0000000..3b293de --- /dev/null +++ b/node_modules/@types/lodash/takeRightWhile.d.ts @@ -0,0 +1,2 @@ +import { takeRightWhile } from "./index"; +export = takeRightWhile; diff --git a/node_modules/@types/lodash/takeWhile.d.ts b/node_modules/@types/lodash/takeWhile.d.ts new file mode 100644 index 0000000..088234a --- /dev/null +++ b/node_modules/@types/lodash/takeWhile.d.ts @@ -0,0 +1,2 @@ +import { takeWhile } from "./index"; +export = takeWhile; diff --git a/node_modules/@types/lodash/tap.d.ts b/node_modules/@types/lodash/tap.d.ts new file mode 100644 index 0000000..e15a13c --- /dev/null +++ b/node_modules/@types/lodash/tap.d.ts @@ -0,0 +1,2 @@ +import { tap } from "./index"; +export = tap; diff --git a/node_modules/@types/lodash/template.d.ts b/node_modules/@types/lodash/template.d.ts new file mode 100644 index 0000000..854e753 --- /dev/null +++ b/node_modules/@types/lodash/template.d.ts @@ -0,0 +1,2 @@ +import { template } from "./index"; +export = template; diff --git a/node_modules/@types/lodash/throttle.d.ts b/node_modules/@types/lodash/throttle.d.ts new file mode 100644 index 0000000..2650896 --- /dev/null +++ b/node_modules/@types/lodash/throttle.d.ts @@ -0,0 +1,2 @@ +import { throttle } from "./index"; +export = throttle; diff --git a/node_modules/@types/lodash/thru.d.ts b/node_modules/@types/lodash/thru.d.ts new file mode 100644 index 0000000..0447e12 --- /dev/null +++ b/node_modules/@types/lodash/thru.d.ts @@ -0,0 +1,2 @@ +import { thru } from "./index"; +export = thru; diff --git a/node_modules/@types/lodash/times.d.ts b/node_modules/@types/lodash/times.d.ts new file mode 100644 index 0000000..7fda4de --- /dev/null +++ b/node_modules/@types/lodash/times.d.ts @@ -0,0 +1,2 @@ +import { times } from "./index"; +export = times; diff --git a/node_modules/@types/lodash/toArray.d.ts b/node_modules/@types/lodash/toArray.d.ts new file mode 100644 index 0000000..dd94c8a --- /dev/null +++ b/node_modules/@types/lodash/toArray.d.ts @@ -0,0 +1,2 @@ +import { toArray } from "./index"; +export = toArray; diff --git a/node_modules/@types/lodash/toFinite.d.ts b/node_modules/@types/lodash/toFinite.d.ts new file mode 100644 index 0000000..c575b47 --- /dev/null +++ b/node_modules/@types/lodash/toFinite.d.ts @@ -0,0 +1,2 @@ +import { toFinite } from "./index"; +export = toFinite; diff --git a/node_modules/@types/lodash/toInteger.d.ts b/node_modules/@types/lodash/toInteger.d.ts new file mode 100644 index 0000000..021a9c0 --- /dev/null +++ b/node_modules/@types/lodash/toInteger.d.ts @@ -0,0 +1,2 @@ +import { toInteger } from "./index"; +export = toInteger; diff --git a/node_modules/@types/lodash/toLength.d.ts b/node_modules/@types/lodash/toLength.d.ts new file mode 100644 index 0000000..41a4098 --- /dev/null +++ b/node_modules/@types/lodash/toLength.d.ts @@ -0,0 +1,2 @@ +import { toLength } from "./index"; +export = toLength; diff --git a/node_modules/@types/lodash/toLower.d.ts b/node_modules/@types/lodash/toLower.d.ts new file mode 100644 index 0000000..766c173 --- /dev/null +++ b/node_modules/@types/lodash/toLower.d.ts @@ -0,0 +1,2 @@ +import { toLower } from "./index"; +export = toLower; diff --git a/node_modules/@types/lodash/toNumber.d.ts b/node_modules/@types/lodash/toNumber.d.ts new file mode 100644 index 0000000..a6c5e1f --- /dev/null +++ b/node_modules/@types/lodash/toNumber.d.ts @@ -0,0 +1,2 @@ +import { toNumber } from "./index"; +export = toNumber; diff --git a/node_modules/@types/lodash/toPairs.d.ts b/node_modules/@types/lodash/toPairs.d.ts new file mode 100644 index 0000000..4a7846e --- /dev/null +++ b/node_modules/@types/lodash/toPairs.d.ts @@ -0,0 +1,2 @@ +import { toPairs } from "./index"; +export = toPairs; diff --git a/node_modules/@types/lodash/toPairsIn.d.ts b/node_modules/@types/lodash/toPairsIn.d.ts new file mode 100644 index 0000000..82d71b3 --- /dev/null +++ b/node_modules/@types/lodash/toPairsIn.d.ts @@ -0,0 +1,2 @@ +import { toPairsIn } from "./index"; +export = toPairsIn; diff --git a/node_modules/@types/lodash/toPath.d.ts b/node_modules/@types/lodash/toPath.d.ts new file mode 100644 index 0000000..ff354e5 --- /dev/null +++ b/node_modules/@types/lodash/toPath.d.ts @@ -0,0 +1,2 @@ +import { toPath } from "./index"; +export = toPath; diff --git a/node_modules/@types/lodash/toPlainObject.d.ts b/node_modules/@types/lodash/toPlainObject.d.ts new file mode 100644 index 0000000..0561ab6 --- /dev/null +++ b/node_modules/@types/lodash/toPlainObject.d.ts @@ -0,0 +1,2 @@ +import { toPlainObject } from "./index"; +export = toPlainObject; diff --git a/node_modules/@types/lodash/toSafeInteger.d.ts b/node_modules/@types/lodash/toSafeInteger.d.ts new file mode 100644 index 0000000..6bb24d8 --- /dev/null +++ b/node_modules/@types/lodash/toSafeInteger.d.ts @@ -0,0 +1,2 @@ +import { toSafeInteger } from "./index"; +export = toSafeInteger; diff --git a/node_modules/@types/lodash/toString.d.ts b/node_modules/@types/lodash/toString.d.ts new file mode 100644 index 0000000..7765d10 --- /dev/null +++ b/node_modules/@types/lodash/toString.d.ts @@ -0,0 +1,2 @@ +import { toString } from "./index"; +export = toString; diff --git a/node_modules/@types/lodash/toUpper.d.ts b/node_modules/@types/lodash/toUpper.d.ts new file mode 100644 index 0000000..af43041 --- /dev/null +++ b/node_modules/@types/lodash/toUpper.d.ts @@ -0,0 +1,2 @@ +import { toUpper } from "./index"; +export = toUpper; diff --git a/node_modules/@types/lodash/transform.d.ts b/node_modules/@types/lodash/transform.d.ts new file mode 100644 index 0000000..05e6543 --- /dev/null +++ b/node_modules/@types/lodash/transform.d.ts @@ -0,0 +1,2 @@ +import { transform } from "./index"; +export = transform; diff --git a/node_modules/@types/lodash/trim.d.ts b/node_modules/@types/lodash/trim.d.ts new file mode 100644 index 0000000..7d0bf90 --- /dev/null +++ b/node_modules/@types/lodash/trim.d.ts @@ -0,0 +1,2 @@ +import { trim } from "./index"; +export = trim; diff --git a/node_modules/@types/lodash/trimEnd.d.ts b/node_modules/@types/lodash/trimEnd.d.ts new file mode 100644 index 0000000..b80c844 --- /dev/null +++ b/node_modules/@types/lodash/trimEnd.d.ts @@ -0,0 +1,2 @@ +import { trimEnd } from "./index"; +export = trimEnd; diff --git a/node_modules/@types/lodash/trimStart.d.ts b/node_modules/@types/lodash/trimStart.d.ts new file mode 100644 index 0000000..a040712 --- /dev/null +++ b/node_modules/@types/lodash/trimStart.d.ts @@ -0,0 +1,2 @@ +import { trimStart } from "./index"; +export = trimStart; diff --git a/node_modules/@types/lodash/truncate.d.ts b/node_modules/@types/lodash/truncate.d.ts new file mode 100644 index 0000000..0ae065b --- /dev/null +++ b/node_modules/@types/lodash/truncate.d.ts @@ -0,0 +1,2 @@ +import { truncate } from "./index"; +export = truncate; diff --git a/node_modules/@types/lodash/unary.d.ts b/node_modules/@types/lodash/unary.d.ts new file mode 100644 index 0000000..4456997 --- /dev/null +++ b/node_modules/@types/lodash/unary.d.ts @@ -0,0 +1,2 @@ +import { unary } from "./index"; +export = unary; diff --git a/node_modules/@types/lodash/unescape.d.ts b/node_modules/@types/lodash/unescape.d.ts new file mode 100644 index 0000000..71ba85d --- /dev/null +++ b/node_modules/@types/lodash/unescape.d.ts @@ -0,0 +1,2 @@ +import { unescape } from "./index"; +export = unescape; diff --git a/node_modules/@types/lodash/union.d.ts b/node_modules/@types/lodash/union.d.ts new file mode 100644 index 0000000..7b12e92 --- /dev/null +++ b/node_modules/@types/lodash/union.d.ts @@ -0,0 +1,2 @@ +import { union } from "./index"; +export = union; diff --git a/node_modules/@types/lodash/unionBy.d.ts b/node_modules/@types/lodash/unionBy.d.ts new file mode 100644 index 0000000..0cb1992 --- /dev/null +++ b/node_modules/@types/lodash/unionBy.d.ts @@ -0,0 +1,2 @@ +import { unionBy } from "./index"; +export = unionBy; diff --git a/node_modules/@types/lodash/unionWith.d.ts b/node_modules/@types/lodash/unionWith.d.ts new file mode 100644 index 0000000..9888092 --- /dev/null +++ b/node_modules/@types/lodash/unionWith.d.ts @@ -0,0 +1,2 @@ +import { unionWith } from "./index"; +export = unionWith; diff --git a/node_modules/@types/lodash/uniq.d.ts b/node_modules/@types/lodash/uniq.d.ts new file mode 100644 index 0000000..6c105ac --- /dev/null +++ b/node_modules/@types/lodash/uniq.d.ts @@ -0,0 +1,2 @@ +import { uniq } from "./index"; +export = uniq; diff --git a/node_modules/@types/lodash/uniqBy.d.ts b/node_modules/@types/lodash/uniqBy.d.ts new file mode 100644 index 0000000..7101b0e --- /dev/null +++ b/node_modules/@types/lodash/uniqBy.d.ts @@ -0,0 +1,2 @@ +import { uniqBy } from "./index"; +export = uniqBy; diff --git a/node_modules/@types/lodash/uniqWith.d.ts b/node_modules/@types/lodash/uniqWith.d.ts new file mode 100644 index 0000000..72c3f8f --- /dev/null +++ b/node_modules/@types/lodash/uniqWith.d.ts @@ -0,0 +1,2 @@ +import { uniqWith } from "./index"; +export = uniqWith; diff --git a/node_modules/@types/lodash/uniqueId.d.ts b/node_modules/@types/lodash/uniqueId.d.ts new file mode 100644 index 0000000..4ea55f9 --- /dev/null +++ b/node_modules/@types/lodash/uniqueId.d.ts @@ -0,0 +1,2 @@ +import { uniqueId } from "./index"; +export = uniqueId; diff --git a/node_modules/@types/lodash/unset.d.ts b/node_modules/@types/lodash/unset.d.ts new file mode 100644 index 0000000..1eac8dd --- /dev/null +++ b/node_modules/@types/lodash/unset.d.ts @@ -0,0 +1,2 @@ +import { unset } from "./index"; +export = unset; diff --git a/node_modules/@types/lodash/unzip.d.ts b/node_modules/@types/lodash/unzip.d.ts new file mode 100644 index 0000000..7e320a2 --- /dev/null +++ b/node_modules/@types/lodash/unzip.d.ts @@ -0,0 +1,2 @@ +import { unzip } from "./index"; +export = unzip; diff --git a/node_modules/@types/lodash/unzipWith.d.ts b/node_modules/@types/lodash/unzipWith.d.ts new file mode 100644 index 0000000..2bf5394 --- /dev/null +++ b/node_modules/@types/lodash/unzipWith.d.ts @@ -0,0 +1,2 @@ +import { unzipWith } from "./index"; +export = unzipWith; diff --git a/node_modules/@types/lodash/update.d.ts b/node_modules/@types/lodash/update.d.ts new file mode 100644 index 0000000..d072c0f --- /dev/null +++ b/node_modules/@types/lodash/update.d.ts @@ -0,0 +1,2 @@ +import { update } from "./index"; +export = update; diff --git a/node_modules/@types/lodash/updateWith.d.ts b/node_modules/@types/lodash/updateWith.d.ts new file mode 100644 index 0000000..4417542 --- /dev/null +++ b/node_modules/@types/lodash/updateWith.d.ts @@ -0,0 +1,2 @@ +import { updateWith } from "./index"; +export = updateWith; diff --git a/node_modules/@types/lodash/upperCase.d.ts b/node_modules/@types/lodash/upperCase.d.ts new file mode 100644 index 0000000..c33598a --- /dev/null +++ b/node_modules/@types/lodash/upperCase.d.ts @@ -0,0 +1,2 @@ +import { upperCase } from "./index"; +export = upperCase; diff --git a/node_modules/@types/lodash/upperFirst.d.ts b/node_modules/@types/lodash/upperFirst.d.ts new file mode 100644 index 0000000..1f1b2a7 --- /dev/null +++ b/node_modules/@types/lodash/upperFirst.d.ts @@ -0,0 +1,2 @@ +import { upperFirst } from "./index"; +export = upperFirst; diff --git a/node_modules/@types/lodash/values.d.ts b/node_modules/@types/lodash/values.d.ts new file mode 100644 index 0000000..2015ebf --- /dev/null +++ b/node_modules/@types/lodash/values.d.ts @@ -0,0 +1,2 @@ +import { values } from "./index"; +export = values; diff --git a/node_modules/@types/lodash/valuesIn.d.ts b/node_modules/@types/lodash/valuesIn.d.ts new file mode 100644 index 0000000..6f8d6a3 --- /dev/null +++ b/node_modules/@types/lodash/valuesIn.d.ts @@ -0,0 +1,2 @@ +import { valuesIn } from "./index"; +export = valuesIn; diff --git a/node_modules/@types/lodash/without.d.ts b/node_modules/@types/lodash/without.d.ts new file mode 100644 index 0000000..bbdfe16 --- /dev/null +++ b/node_modules/@types/lodash/without.d.ts @@ -0,0 +1,2 @@ +import { without } from "./index"; +export = without; diff --git a/node_modules/@types/lodash/words.d.ts b/node_modules/@types/lodash/words.d.ts new file mode 100644 index 0000000..22da6cb --- /dev/null +++ b/node_modules/@types/lodash/words.d.ts @@ -0,0 +1,2 @@ +import { words } from "./index"; +export = words; diff --git a/node_modules/@types/lodash/wrap.d.ts b/node_modules/@types/lodash/wrap.d.ts new file mode 100644 index 0000000..3c20f28 --- /dev/null +++ b/node_modules/@types/lodash/wrap.d.ts @@ -0,0 +1,2 @@ +import { wrap } from "./index"; +export = wrap; diff --git a/node_modules/@types/lodash/xor.d.ts b/node_modules/@types/lodash/xor.d.ts new file mode 100644 index 0000000..894735c --- /dev/null +++ b/node_modules/@types/lodash/xor.d.ts @@ -0,0 +1,2 @@ +import { xor } from "./index"; +export = xor; diff --git a/node_modules/@types/lodash/xorBy.d.ts b/node_modules/@types/lodash/xorBy.d.ts new file mode 100644 index 0000000..6a08c6a --- /dev/null +++ b/node_modules/@types/lodash/xorBy.d.ts @@ -0,0 +1,2 @@ +import { xorBy } from "./index"; +export = xorBy; diff --git a/node_modules/@types/lodash/xorWith.d.ts b/node_modules/@types/lodash/xorWith.d.ts new file mode 100644 index 0000000..7cdcaf3 --- /dev/null +++ b/node_modules/@types/lodash/xorWith.d.ts @@ -0,0 +1,2 @@ +import { xorWith } from "./index"; +export = xorWith; diff --git a/node_modules/@types/lodash/zip.d.ts b/node_modules/@types/lodash/zip.d.ts new file mode 100644 index 0000000..e7467cd --- /dev/null +++ b/node_modules/@types/lodash/zip.d.ts @@ -0,0 +1,2 @@ +import { zip } from "./index"; +export = zip; diff --git a/node_modules/@types/lodash/zipObject.d.ts b/node_modules/@types/lodash/zipObject.d.ts new file mode 100644 index 0000000..ad049fd --- /dev/null +++ b/node_modules/@types/lodash/zipObject.d.ts @@ -0,0 +1,2 @@ +import { zipObject } from "./index"; +export = zipObject; diff --git a/node_modules/@types/lodash/zipObjectDeep.d.ts b/node_modules/@types/lodash/zipObjectDeep.d.ts new file mode 100644 index 0000000..2a483e8 --- /dev/null +++ b/node_modules/@types/lodash/zipObjectDeep.d.ts @@ -0,0 +1,2 @@ +import { zipObjectDeep } from "./index"; +export = zipObjectDeep; diff --git a/node_modules/@types/lodash/zipWith.d.ts b/node_modules/@types/lodash/zipWith.d.ts new file mode 100644 index 0000000..4869374 --- /dev/null +++ b/node_modules/@types/lodash/zipWith.d.ts @@ -0,0 +1,2 @@ +import { zipWith } from "./index"; +export = zipWith; diff --git a/node_modules/@types/mocha/LICENSE b/node_modules/@types/mocha/LICENSE new file mode 100644 index 0000000..2107107 --- /dev/null +++ b/node_modules/@types/mocha/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. All rights reserved. + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE diff --git a/node_modules/@types/mocha/README.md b/node_modules/@types/mocha/README.md new file mode 100644 index 0000000..76420f8 --- /dev/null +++ b/node_modules/@types/mocha/README.md @@ -0,0 +1,16 @@ +# Installation +> `npm install --save @types/mocha` + +# Summary +This package contains type definitions for mocha (http://mochajs.org/). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/mocha + +Additional Details + * Last updated: Mon, 16 Jul 2018 17:07:43 GMT + * Dependencies: none + * Global values: Mocha, after, afterEach, before, beforeEach, context, describe, it, mocha, run, setup, specify, suite, suiteSetup, suiteTeardown, teardown, test, xcontext, xdescribe, xit, xspecify + +# Credits +These definitions were written by Kazi Manzur Rashid , otiai10 , jt000 , Vadim Macagon , Andrew Bradley , Dmitrii Sorin . diff --git a/node_modules/@types/mocha/index.d.ts b/node_modules/@types/mocha/index.d.ts new file mode 100644 index 0000000..868a6c3 --- /dev/null +++ b/node_modules/@types/mocha/index.d.ts @@ -0,0 +1,2986 @@ +// Type definitions for mocha 5.2 +// Project: http://mochajs.org/ +// Definitions by: Kazi Manzur Rashid +// otiai10 +// jt000 +// Vadim Macagon +// Andrew Bradley +// Dmitrii Sorin +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +/** + * Mocha API + * + * @see https://mochajs.org/api/mocha + */ +declare class Mocha { + private _growl; + private _reporter; + private _ui; + + constructor(options?: Mocha.MochaOptions); + + suite: Mocha.Suite; + files: string[]; + options: Mocha.MochaInstanceOptions; + + /** + * Enable or disable bailing on the first failure. + * + * @see https://mochajs.org/api/mocha#bail + */ + bail(bail?: boolean): this; + + /** + * Add test `file`. + * + * @see https://mochajs.org/api/mocha#addFile + */ + addFile(file: string): this; + + /** + * Set reporter to one of the built-in reporters. + * + * @see https://mochajs.org/api/mocha#reporter + */ + reporter(reporter: Mocha.Reporter, reporterOptions?: any): this; + + /** + * Set reporter to the provided constructor, one of the built-in reporters, or loads a reporter + * from a module path. Defaults to `"spec"`. + * + * @see https://mochajs.org/api/mocha#reporter + */ + reporter(reporter?: string | Mocha.ReporterConstructor, reporterOptions?: any): this; + + /** + * Set test UI to one of the built-in test interfaces. + * + * @see https://mochajs.org/api/mocha#ui + */ + ui(name: Mocha.Interface): this; + + /** + * Set test UI to one of the built-in test interfaces or loads a test interface from a module + * path. Defaults to `"bdd"`. + * + * @see https://mochajs.org/api/mocha#ui + */ + ui(name?: string): this; + + /** + * Escape string and add it to grep as a RegExp. + * + * @see https://mochajs.org/api/mocha#fgrep + */ + fgrep(str: string): this; + + /** + * Add regexp to grep, if `re` is a string it is escaped. + * + * @see https://mochajs.org/api/mocha#grep + */ + grep(re: string | RegExp): this; + + /** + * Invert `.grep()` matches. + * + * @see https://mochajs.org/api/mocha#invert + */ + invert(): this; + + /** + * Ignore global leaks. + * + * @see https://mochajs.org/api/mocha#ignoreLeaks + */ + ignoreLeaks(ignore: boolean): this; + + /** + * Enable global leak checking. + * + * @see https://mochajs.org/api/mocha#checkLeaks + */ + checkLeaks(): this; + + /** + * Display long stack-trace on failing + * + * @see https://mochajs.org/api/mocha#fullTrace + */ + fullTrace(): this; + + /** + * Enable growl support. + * + * @see https://mochajs.org/api/mocha#growl + */ + growl(): this; + + /** + * Ignore `globals` array or string. + * + * @see https://mochajs.org/api/mocha#globals + */ + globals(globals: string | ReadonlyArray): this; + + /** + * Emit color output. + * + * @see https://mochajs.org/api/mocha#useColors + */ + useColors(colors: boolean): this; + + /** + * Use inline diffs rather than +/-. + * + * @see https://mochajs.org/api/mocha#useInlineDiffs + */ + useInlineDiffs(inlineDiffs: boolean): this; + + /** + * Do not show diffs at all. + * + * @see https://mochajs.org/api/mocha#hideDiff + */ + hideDiff(hideDiff: boolean): this; + + /** + * Set the timeout in milliseconds. + * + * @see https://mochajs.org/api/mocha#timeout + */ + timeout(timeout: string | number): this; + + /** + * Set the number of times to retry failed tests. + * + * @see https://mochajs.org/api/mocha#retries + */ + retries(n: number): this; + + /** + * Set slowness threshold in milliseconds. + * + * @see https://mochajs.org/api/mocha#slow + */ + slow(slow: string | number): this; + + /** + * Enable timeouts. + * + * @see https://mochajs.org/api/mocha#enableTimeouts + */ + enableTimeouts(enabled?: boolean): this; + + /** + * Makes all tests async (accepting a callback) + * + * @see https://mochajs.org/api/mocha#asyncOnly. + */ + asyncOnly(): this; + + /** + * Disable syntax highlighting (in browser). + * + * @see https://mochajs.org/api/mocha#noHighlighting + */ + noHighlighting(): this; + + /** + * Enable uncaught errors to propagate (in browser). + * + * @see https://mochajs.org/api/mocha#allowUncaught + */ + allowUncaught(): boolean; + + /** + * Delay root suite execution. + * + * @see https://mochajs.org/api/mocha#delay + */ + delay(): boolean; + + /** + * Tests marked only fail the suite + * + * @see https://mochajs.org/api/mocha#forbidOnly + */ + forbidOnly(): boolean; + + /** + * Pending tests and tests marked skip fail the suite + * + * @see https://mochajs.org/api/mocha#forbidPending + */ + forbidPending(): boolean; + + /** + * Run tests and invoke `fn()` when complete. + * + * Note that `run` relies on Node's `require` to execute + * the test interface functions and will be subject to the + * cache - if the files are already in the `require` cache, + * they will effectively be skipped. Therefore, to run tests + * multiple times or to run tests in files that are already + * in the `require` cache, make sure to clear them from the + * cache first in whichever manner best suits your needs. + * + * @see https://mochajs.org/api/mocha#run + */ + run(fn?: (failures: number) => void): Mocha.Runner; + + /** + * Load registered files. + * + * @see https://mochajs.org/api/mocha#loadFiles + */ + protected loadFiles(fn?: () => void): void; +} + +declare namespace Mocha { + namespace utils { + /** + * Compute a slug from the given `str`. + * + * @see https://mochajs.org/api/module-utils.html#.slug + */ + function slug(str: string): string; + + /** + * Strip the function definition from `str`, and re-indent for pre whitespace. + * + * @see https://mochajs.org/api/module-utils.html#.clean + */ + function clean(str: string): string; + + /** + * Highlight the given string of `js`. + */ + function highlight(js: string): string; + + /** + * Takes some variable and asks `Object.prototype.toString()` what it thinks it is. + */ + function type(value: any): string; + + /** + * Stringify `value`. Different behavior depending on type of value: + * + * - If `value` is undefined or null, return `'[undefined]'` or `'[null]'`, respectively. + * - If `value` is not an object, function or array, return result of `value.toString()` wrapped in double-quotes. + * - If `value` is an *empty* object, function, or array, returns `'{}'`, `'[Function]'`, or `'[]'` respectively. + * - If `value` has properties, call canonicalize} on it, then return result of `JSON.stringify()` + * + * @see https://mochajs.org/api/module-utils.html#.stringify + */ + function stringify(value: any): string; + + /** + * Return a new Thing that has the keys in sorted order. Recursive. + * + * If the Thing... + * - has already been seen, return string `'[Circular]'` + * - is `undefined`, return string `'[undefined]'` + * - is `null`, return value `null` + * - is some other primitive, return the value + * - is not a primitive or an `Array`, `Object`, or `Function`, return the value of the Thing's `toString()` method + * - is a non-empty `Array`, `Object`, or `Function`, return the result of calling this function again. + * - is an empty `Array`, `Object`, or `Function`, returns `'[]'`, `'{}'`, or `'[Function]'` respectively. + * + * @see https://mochajs.org/api/module-utils.html#.canonicalize + */ + function canonicalize(value: any, stack: any[], typeHint: string): any; + + /** + * Lookup file names at the given `path`. + * + * @see https://mochajs.org/api/Mocha.utils.html#.exports.lookupFiles + */ + function lookupFiles(filepath: string, extensions?: string[], recursive?: boolean): string[]; + + /** + * Generate an undefined error with a message warning the user. + * + * @see https://mochajs.org/api/module-utils.html#.undefinedError + */ + function undefinedError(): Error; + + /** + * Generate an undefined error if `err` is not defined. + * + * @see https://mochajs.org/api/module-utils.html#.getError + */ + function getError(err: Error | undefined): Error; + + /** + * When invoking this function you get a filter function that get the Error.stack as an + * input, and return a prettify output. (i.e: strip Mocha and internal node functions from + * stack trace). + * + * @see https://mochajs.org/api/module-utils.html#.stackTraceFilter + */ + function stackTraceFilter(): (stack: string) => string; + } + + namespace interfaces { + function bdd(suite: Suite): void; + function tdd(suite: Suite): void; + function qunit(suite: Suite): void; + function exports(suite: Suite): void; + } + + // #region Test interface augmentations + + interface HookFunction { + /** + * [bdd, qunit, tdd] Describe a "hook" to execute the given callback `fn`. The name of the + * function is used as the name of the hook. + * + * - _Only available when invoked via the mocha CLI._ + */ + (fn: Func): void; + + /** + * [bdd, qunit, tdd] Describe a "hook" to execute the given callback `fn`. The name of the + * function is used as the name of the hook. + * + * - _Only available when invoked via the mocha CLI._ + */ + (fn: AsyncFunc): void; + + /** + * [bdd, qunit, tdd] Describe a "hook" to execute the given `title` and callback `fn`. + * + * - _Only available when invoked via the mocha CLI._ + */ + (name: string, fn?: Func): void; + + /** + * [bdd, qunit, tdd] Describe a "hook" to execute the given `title` and callback `fn`. + * + * - _Only available when invoked via the mocha CLI._ + */ + (name: string, fn?: AsyncFunc): void; + } + + interface SuiteFunction { + /** + * [bdd, tdd] Describe a "suite" with the given `title` and callback `fn` containing + * nested suites. + * + * - _Only available when invoked via the mocha CLI._ + */ + (title: string, fn: (this: Suite) => void): Suite; + + /** + * [qunit] Describe a "suite" with the given `title`. + * + * - _Only available when invoked via the mocha CLI._ + */ + (title: string): Suite; + + /** + * [bdd, tdd, qunit] Indicates this suite should be executed exclusively. + * + * - _Only available when invoked via the mocha CLI._ + */ + only: ExclusiveSuiteFunction; + + /** + * [bdd, tdd] Indicates this suite should not be executed. + * + * - _Only available when invoked via the mocha CLI._ + */ + skip: PendingSuiteFunction; + } + + interface ExclusiveSuiteFunction { + /** + * [bdd, tdd] Describe a "suite" with the given `title` and callback `fn` containing + * nested suites. Indicates this suite should be executed exclusively. + * + * - _Only available when invoked via the mocha CLI._ + */ + (title: string, fn: (this: Suite) => void): Suite; + + /** + * [qunit] Describe a "suite" with the given `title`. Indicates this suite should be executed + * exclusively. + * + * - _Only available when invoked via the mocha CLI._ + */ + (title: string): Suite; + } + + /** + * [bdd, tdd] Describe a "suite" with the given `title` and callback `fn` containing + * nested suites. Indicates this suite should not be executed. + * + * - _Only available when invoked via the mocha CLI._ + * + * @returns [bdd] `Suite` + * @returns [tdd] `void` + */ + interface PendingSuiteFunction { + (title: string, fn: (this: Suite) => void): Suite | void; + } + + interface TestFunction { + /** + * Describe a specification or test-case with the given callback `fn` acting as a thunk. + * The name of the function is used as the name of the test. + * + * - _Only available when invoked via the mocha CLI._ + */ + (fn: Func): Test; + + /** + * Describe a specification or test-case with the given callback `fn` acting as a thunk. + * The name of the function is used as the name of the test. + * + * - _Only available when invoked via the mocha CLI._ + */ + (fn: AsyncFunc): Test; + + /** + * Describe a specification or test-case with the given `title` and callback `fn` acting + * as a thunk. + * + * - _Only available when invoked via the mocha CLI._ + */ + (title: string, fn?: Func): Test; + + /** + * Describe a specification or test-case with the given `title` and callback `fn` acting + * as a thunk. + * + * - _Only available when invoked via the mocha CLI._ + */ + (title: string, fn?: AsyncFunc): Test; + + /** + * Indicates this test should be executed exclusively. + * + * - _Only available when invoked via the mocha CLI._ + */ + only: ExclusiveTestFunction; + + /** + * Indicates this test should not be executed. + * + * - _Only available when invoked via the mocha CLI._ + */ + skip: PendingTestFunction; + + /** + * Number of attempts to retry. + * + * - _Only available when invoked via the mocha CLI._ + */ + retries(n: number): void; + } + + interface ExclusiveTestFunction { + /** + * [bdd, tdd, qunit] Describe a specification or test-case with the given callback `fn` + * acting as a thunk. The name of the function is used as the name of the test. Indicates + * this test should be executed exclusively. + * + * - _Only available when invoked via the mocha CLI._ + */ + (fn: Func): Test; + + /** + * [bdd, tdd, qunit] Describe a specification or test-case with the given callback `fn` + * acting as a thunk. The name of the function is used as the name of the test. Indicates + * this test should be executed exclusively. + * + * - _Only available when invoked via the mocha CLI._ + */ + (fn: AsyncFunc): Test; + + /** + * [bdd, tdd, qunit] Describe a specification or test-case with the given `title` and + * callback `fn` acting as a thunk. Indicates this test should be executed exclusively. + * + * - _Only available when invoked via the mocha CLI._ + */ + (title: string, fn?: Func): Test; + + /** + * [bdd, tdd, qunit] Describe a specification or test-case with the given `title` and + * callback `fn` acting as a thunk. Indicates this test should be executed exclusively. + * + * - _Only available when invoked via the mocha CLI._ + */ + (title: string, fn?: AsyncFunc): Test; + } + + interface PendingTestFunction { + /** + * [bdd, tdd, qunit] Describe a specification or test-case with the given callback `fn` + * acting as a thunk. The name of the function is used as the name of the test. Indicates + * this test should not be executed. + * + * - _Only available when invoked via the mocha CLI._ + */ + (fn: Func): Test; + + /** + * [bdd, tdd, qunit] Describe a specification or test-case with the given callback `fn` + * acting as a thunk. The name of the function is used as the name of the test. Indicates + * this test should not be executed. + * + * - _Only available when invoked via the mocha CLI._ + */ + (fn: AsyncFunc): Test; + + /** + * [bdd, tdd, qunit] Describe a specification or test-case with the given `title` and + * callback `fn` acting as a thunk. Indicates this test should not be executed. + * + * - _Only available when invoked via the mocha CLI._ + */ + (title: string, fn?: Func): Test; + + /** + * [bdd, tdd, qunit] Describe a specification or test-case with the given `title` and + * callback `fn` acting as a thunk. Indicates this test should not be executed. + * + * - _Only available when invoked via the mocha CLI._ + */ + (title: string, fn?: AsyncFunc): Test; + } + + /** + * Execute after each test case. + * + * - _Only available when invoked via the mocha CLI._ + * + * @see https://mochajs.org/api/global.html#afterEach + */ + let afterEach: HookFunction; + + /** + * Execute after running tests. + * + * - _Only available when invoked via the mocha CLI._ + * + * @see https://mochajs.org/api/global.html#after + */ + let after: HookFunction; + + /** + * Execute before each test case. + * + * - _Only available when invoked via the mocha CLI._ + * + * @see https://mochajs.org/api/global.html#beforeEach + */ + let beforeEach: HookFunction; + + /** + * Execute before running tests. + * + * - _Only available when invoked via the mocha CLI._ + * + * @see https://mochajs.org/api/global.html#before + */ + let before: HookFunction; + + /** + * Describe a "suite" containing nested suites and tests. + * + * - _Only available when invoked via the mocha CLI._ + */ + let describe: SuiteFunction; + + /** + * Describes a test case. + * + * - _Only available when invoked via the mocha CLI._ + */ + let it: TestFunction; + + /** + * Describes a pending test case. + * + * - _Only available when invoked via the mocha CLI._ + */ + let xit: PendingTestFunction; + + /** + * Execute before each test case. + * + * - _Only available when invoked via the mocha CLI._ + * + * @see https://mochajs.org/api/global.html#beforeEach + */ + let setup: HookFunction; + + /** + * Execute before running tests. + * + * - _Only available when invoked via the mocha CLI._ + * + * @see https://mochajs.org/api/global.html#before + */ + let suiteSetup: HookFunction; + + /** + * Execute after running tests. + * + * - _Only available when invoked via the mocha CLI._ + * + * @see https://mochajs.org/api/global.html#after + */ + let suiteTeardown: HookFunction; + + /** + * Describe a "suite" containing nested suites and tests. + * + * - _Only available when invoked via the mocha CLI._ + */ + let suite: SuiteFunction; + + /** + * Execute after each test case. + * + * - _Only available when invoked via the mocha CLI._ + * + * @see https://mochajs.org/api/global.html#afterEach + */ + let teardown: HookFunction; + + /** + * Describes a test case. + * + * - _Only available when invoked via the mocha CLI._ + */ + let test: TestFunction; + + /** + * Triggers root suite execution. + * + * - _Only available if flag --delay is passed into Mocha._ + * - _Only available when invoked via the mocha CLI._ + * + * @see https://mochajs.org/api/global.html#runWithSuite + */ + function run(): void; + + // #endregion Test interface augmentations + + namespace reporters { + /** + * Initialize a new `Base` reporter. + * + * All other reporters generally inherit from this reporter, providing stats such as test duration, + * number of tests passed / failed, etc. + * + * @see https://mochajs.org/api/Mocha.reporters.Base.html + */ + class Base { + constructor(runner: Runner, options?: MochaOptions); + /** @deprecated Use the overload that accepts `Mocha.Runner` instead. */ + constructor(runner: IRunner, options?: MochaOptions); + + /** + * Test run statistics + */ + stats: Stats; + + /** + * Test failures + */ + failures: Test[]; + + /** + * The configured runner + */ + runner: Runner; + + /** + * Output common epilogue used by many of the bundled reporters. + * + * @see https://mochajs.org/api/Mocha.reporters.Base.html#.Base#epilogue + */ + epilogue(): void; + + done?(failures: number, fn?: (failures: number) => void): void; + } + + namespace Base { + /** + * Enables coloring by default + * + * @see https://mochajs.org/api/module-base#.useColors + */ + let useColors: boolean; + + /** + * Inline diffs instead of +/- + * + * @see https://mochajs.org/api/module-base#.inlineDiffs + */ + let inlineDiffs: boolean; + + /** + * Default color map + * + * @see https://mochajs.org/api/module-base#.colors + */ + const colors: ColorMap; + + /** + * Default color map + * + * @see https://mochajs.org/api/module-base#.colors + */ + interface ColorMap { + // added by Base + pass: number; + fail: number; + "bright pass": number; + "bright fail": number; + "bright yellow": number; + pending: number; + suite: number; + "error title": number; + "error message": number; + "error stack": number; + checkmark: number; + fast: number; + medium: number; + slow: number; + green: number; + light: number; + "diff gutter": number; + "diff added": number; + "diff removed": number; + + // added by Progress + progress: number; + + // added by Landing + plane: number; + "plane crash": number; + runway: number; + + [key: string]: number; + } + + /** + * Default symbol map + * + * @see https://mochajs.org/api/module-base#.symbols + */ + const symbols: SymbolMap; + + /** + * Default symbol map + * + * @see https://mochajs.org/api/module-base#.symbols + */ + interface SymbolMap { + ok: string; + err: string; + dot: string; + comma: string; + bang: string; + [key: string]: string; + } + + /** + * Color `str` with the given `type` (from `colors`) + * + * @see https://mochajs.org/api/module-base#.color + */ + function color(type: string, str: string): string; + + /** + * Expose terminal window size + * + * @see https://mochajs.org/api/module-base#.window + */ + const window: { + width: number; + }; + + /** + * ANSI TTY control sequences common among reporters. + * + * @see https://mochajs.org/api/module-base#.cursor + */ + namespace cursor { + /** + * Hides the cursor + */ + function hide(): void; + + /** + * Shows the cursor + */ + function show(): void; + + /** + * Deletes the current line + */ + function deleteLine(): void; + + /** + * Moves to the beginning of the line + */ + function beginningOfLine(): void; + + /** + * Clears the line and moves to the beginning of the line. + */ + function CR(): void; + } + + /** + * Returns a diff between two strings with colored ANSI output. + * + * @see https://mochajs.org/api/module-base#.generateDiff + */ + function generateDiff(actual: string, expected: string): string; + + /** + * Output the given `failures` as a list. + * + * @see https://mochajs.org/api/Mocha.reporters.Base.html#.exports.list1 + */ + function list(failures: Test[]): void; + } + + /** + * Initialize a new `Dot` matrix test reporter. + * + * @see https://mochajs.org/api/Mocha.reporters.Dot.html + */ + class Dot extends Base { + } + + /** + * Initialize a new `Doc` reporter. + * + * @see https://mochajs.org/api/Mocha.reporters.Doc.html + */ + class Doc extends Base { + } + + /** + * Initialize a new `TAP` test reporter. + * + * @see https://mochajs.org/api/Mocha.reporters.TAP.html + */ + class TAP extends Base { + } + + /** + * Initialize a new `JSON` reporter + * + * @see https://mochajs.org/api/Mocha.reporters.JSON.html + */ + class JSON extends Base { + } + + /** + * Initialize a new `HTML` reporter. + * + * - _This reporter cannot be used on the console._ + * + * @see https://mochajs.org/api/Mocha.reporters.HTML.html + */ + class HTML extends Base { + /** + * Provide suite URL. + * + * @see https://mochajs.org/api/Mocha.reporters.HTML.html#suiteURL + */ + suiteURL(suite: Suite): string; + + /** + * Provide test URL. + * + * @see https://mochajs.org/api/Mocha.reporters.HTML.html#testURL + */ + testURL(test: Test): string; + + /** + * Adds code toggle functionality for the provided test's list element. + * + * @see https://mochajs.org/api/Mocha.reporters.HTML.html#addCodeToggle + */ + addCodeToggle(el: HTMLLIElement, contents: string): void; + } + + /** + * Initialize a new `List` test reporter. + * + * @see https://mochajs.org/api/Mocha.reporters.List.html + */ + class List extends Base { + } + + /** + * Initialize a new `Min` minimal test reporter (best used with --watch). + * + * @see https://mochajs.org/api/Mocha.reporters.Min.html + */ + class Min extends Base { + } + + /** + * Initialize a new `Spec` test reporter. + * + * @see https://mochajs.org/api/Mocha.reporters.Spec.html + */ + class Spec extends Base { + } + + /** + * Initialize a new `NyanCat` test reporter. + * + * @see https://mochajs.org/api/Mocha.reporters.Nyan.html + */ + class Nyan extends Base { + private colorIndex; + private numberOfLines; + private rainbowColors; + private scoreboardWidth; + private tick; + private trajectories; + private trajectoryWidthMax; + private draw; + private drawScoreboard; + private appendRainbow; + private drawRainbow; + private drawNyanCat; + private face; + private cursorUp; + private cursorDown; + private generateColors; + private rainbowify; + } + + /** + * Initialize a new `XUnit` test reporter. + * + * @see https://mochajs.org/api/Mocha.reporters.XUnit.html + */ + class XUnit extends Base { + constructor(runner: Runner, options?: XUnit.MochaOptions); + /** @deprecated Use the overload that accepts `Mocha.Runner` instead. */ + constructor(runner: IRunner, options?: XUnit.MochaOptions); + + /** + * Override done to close the stream (if it's a file). + * + * @see https://mochajs.org/api/Mocha.reporters.XUnit.html#done + */ + done(failures: number, fn: (failures: number) => void): void; + + /** + * Write out the given line. + * + * @see https://mochajs.org/api/Mocha.reporters.XUnit.html#write + */ + write(line: string): void; + + /** + * Output tag for the given `test.` + * + * @see https://mochajs.org/api/Mocha.reporters.XUnit.html#test + */ + test(test: Test): void; + } + + namespace XUnit { + interface MochaOptions extends Mocha.MochaOptions { + reporterOptions?: ReporterOptions; + } + + interface ReporterOptions { + output?: string; + suiteName?: string; + } + } + + /** + * Initialize a new `Markdown` test reporter. + * + * @see https://mochajs.org/api/Mocha.reporters.Markdown.html + */ + class Markdown extends Base { + } + + /** + * Initialize a new `Progress` bar test reporter. + * + * @see https://mochajs.org/api/Mocha.reporters.Progress.html + */ + class Progress extends Base { + constructor(runner: Runner, options?: Progress.MochaOptions); + /** @deprecated Use the overload that accepts `Mocha.Runner` instead. */ + constructor(runner: IRunner, options?: Progress.MochaOptions); + } + + namespace Progress { + interface MochaOptions extends Mocha.MochaOptions { + reporterOptions?: ReporterOptions; + } + + interface ReporterOptions { + open?: string; + complete?: string; + incomplete?: string; + close?: string; + verbose?: boolean; + } + } + + /** + * Initialize a new `Landing` reporter. + * + * @see https://mochajs.org/api/Mocha.reporters.Landing.html + */ + class Landing extends Base { + } + + /** + * Initialize a new `JSONStream` test reporter. + * + * @see https://mochajs.org/api/Mocha.reporters.JSONStream.html + */ + class JSONStream extends Base { + } + + // value-only aliases + const base: typeof Base; + const dot: typeof Dot; + const doc: typeof Doc; + const tap: typeof TAP; + const json: typeof JSON; + const html: typeof HTML; + const list: typeof List; + const spec: typeof Spec; + const nyan: typeof Nyan; + const xunit: typeof XUnit; + const markdown: typeof Markdown; + const progress: typeof Progress; + const landing: typeof Landing; + // NOTE: not possible to type this correctly: + // const "json-stream": typeof JSONStream; + } + + /** + * Initialize a new `Runnable` with the given `title` and callback `fn`. + * + * @see https://mochajs.org/api/Runnable.html + */ + class Runnable { + private _slow; + private _enableTimeouts; + private _retries; + private _currentRetry; + private _timeout; + private _timeoutError; + + constructor(title: string, fn?: Func | AsyncFunc); + + title: string; + fn: Func | AsyncFunc | undefined; + body: string; + async: boolean; + sync: boolean; + timedOut: boolean; + pending: boolean; + duration?: number; + parent?: Suite; + state?: "failed" | "passed"; + timer?: any; + ctx?: Context; + callback?: Done; + allowUncaught?: boolean; + file?: string; + + /** + * Get test timeout. + * + * @see https://mochajs.org/api/Runnable.html#timeout + */ + timeout(): number; + + /** + * Set test timeout. + * + * @see https://mochajs.org/api/Runnable.html#timeout + */ + timeout(ms: string | number): this; + + /** + * Get test slowness threshold. + * + * @see https://mochajs.org/api/Runnable.html#slow + */ + slow(): number; + + /** + * Set test slowness threshold. + * + * @see https://mochajs.org/api/Runnable.html#slow + */ + slow(ms: string | number): this; + + /** + * Get whether timeouts are enabled. + * + * @see https://mochajs.org/api/Runnable.html#enableTimeouts + */ + enableTimeouts(): boolean; + + /** + * Set whether timeouts are enabled. + * + * @see https://mochajs.org/api/Runnable.html#enableTimeouts + */ + enableTimeouts(enabled: boolean): this; + + /** + * Halt and mark as pending. + */ + skip(): never; + + /** + * Check if this runnable or its parent suite is marked as pending. + * + * @see https://mochajs.org/api/Runnable.html#isPending + */ + isPending(): boolean; + + /** + * Return `true` if this Runnable has failed. + */ + isFailed(): boolean; + + /** + * Return `true` if this Runnable has passed. + */ + isPassed(): boolean; + + /** + * Set or get number of retries. + * + * @see https://mochajs.org/api/Runnable.html#retries + */ + retries(): number; + + /** + * Set or get number of retries. + * + * @see https://mochajs.org/api/Runnable.html#retries + */ + retries(n: number): void; + + /** + * Set or get current retry + * + * @see https://mochajs.org/api/Runnable.html#currentRetry + */ + protected currentRetry(): number; + + /** + * Set or get current retry + * + * @see https://mochajs.org/api/Runnable.html#currentRetry + */ + protected currentRetry(n: number): void; + + /** + * Return the full title generated by recursively concatenating the parent's full title. + */ + fullTitle(): string; + + /** + * Return the title path generated by concatenating the parent's title path with the title. + */ + titlePath(): string[]; + + /** + * Clear the timeout. + * + * @see https://mochajs.org/api/Runnable.html#clearTimeout + */ + clearTimeout(): void; + + /** + * Inspect the runnable void of private properties. + * + * @see https://mochajs.org/api/Runnable.html#inspect + */ + inspect(): string; + + /** + * Reset the timeout. + * + * @see https://mochajs.org/api/Runnable.html#resetTimeout + */ + resetTimeout(): void; + + /** + * Get a list of whitelisted globals for this test run. + * + * @see https://mochajs.org/api/Runnable.html#globals + */ + globals(): string[]; + + /** + * Set a list of whitelisted globals for this test run. + * + * @see https://mochajs.org/api/Runnable.html#globals + */ + globals(globals: ReadonlyArray): void; + + /** + * Run the test and invoke `fn(err)`. + * + * @see https://mochajs.org/api/Runnable.html#run + */ + run(fn: Done): void; + } + + // #region Runnable "error" event + interface Runnable extends NodeJS.EventEmitter { + on(event: "error", listener: (error: any) => void): this; + once(event: "error", listener: (error: any) => void): this; + addListener(event: "error", listener: (error: any) => void): this; + removeListener(event: "error", listener: (error: any) => void): this; + prependListener(event: "error", listener: (error: any) => void): this; + prependOnceListener(event: "error", listener: (error: any) => void): this; + emit(name: "error", error: any): boolean; + } + // #endregion Runnable "error" event + // #region Runnable untyped events + interface Runnable extends NodeJS.EventEmitter { + on(event: string, listener: (...args: any[]) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + addListener(event: string, listener: (...args: any[]) => void): this; + removeListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + emit(name: string, ...args: any[]): boolean; + } + // #endregion Runnable untyped events + + /** + * Test context + * + * @see https://mochajs.org/api/module-Context.html#~Context + */ + class Context { + private _runnable; + + test?: Runnable; + currentTest?: Test; + + /** + * Get the context `Runnable`. + */ + runnable(): Runnable; + + /** + * Set the context `Runnable`. + */ + runnable(runnable: Runnable): this; + /** @deprecated Use the overload that accepts `Mocha.Runnable` instead. */ + runnable(runnable: IRunnable): this; + + /** + * Get test timeout. + */ + timeout(): number; + + /** + * Set test timeout. + */ + timeout(ms: string | number): this; + + /** + * Get whether timeouts are enabled. + */ + enableTimeouts(): boolean; + + /** + * Set whether timeouts are enabled. + */ + enableTimeouts(enabled: boolean): this; + + /** + * Get test slowness threshold. + */ + slow(): number; + + /** + * Set test slowness threshold. + */ + slow(ms: string | number): this; + + /** + * Mark a test as skipped. + */ + skip(): never; + + /** + * Get the number of allowed retries on failed tests. + */ + retries(): number; + + /** + * Set the number of allowed retries on failed tests. + */ + retries(n: number): this; + + [key: string]: any; + } + + /** + * Initialize a `Runner` for the given `suite`. + * + * @see https://mochajs.org/api/Mocha.Runner.html + */ + class Runner { + private _globals; + private _abort; + private _delay; + private _defaultGrep; + private next; + private hookErr; + private prevGlobalsLength; + private nextSuite; + + constructor(suite: Suite, delay: boolean); + + /** @deprecated Use the overload that accepts `Mocha.Suite` instead. */ + constructor(suite: ISuite, delay: boolean); + + suite: Suite; + started: boolean; + total: number; + failures: number; + asyncOnly?: boolean; + allowUncaught?: boolean; + fullStackTrace?: boolean; + forbidOnly?: boolean; + forbidPending?: boolean; + ignoreLeaks?: boolean; + test?: Test; + currentRunnable?: Runnable; + stats?: Stats; // added by reporters + + /** + * Run tests with full titles matching `re`. Updates runner.total + * with number of tests matched. + * + * @see https://mochajs.org/api/Mocha.Runner.html#.Runner#grep + */ + grep(re: RegExp, invert: boolean): this; + + /** + * Returns the number of tests matching the grep search for the + * given suite. + * + * @see https://mochajs.org/api/Mocha.Runner.html#.Runner#grepTotal + */ + grepTotal(suite: Suite): number; + + /** @deprecated Use the overload that accepts `Mocha.Suite` instead. */ + grepTotal(suite: ISuite): number; + + /** + * Gets the allowed globals. + * + * @see https://mochajs.org/api/Mocha.Runner.html#.Runner#globals + */ + globals(): string[]; + + /** + * Allow the given `arr` of globals. + * + * @see https://mochajs.org/api/Mocha.Runner.html#.Runner#globals + */ + globals(arr: ReadonlyArray): this; + + /** + * Run the root suite and invoke `fn(failures)` on completion. + * + * @see https://mochajs.org/api/Mocha.Runner.html#.Runner#run + */ + run(fn?: (failures: number) => void): this; + + /** + * Cleanly abort execution. + * + * @see https://mochajs.org/api/Mocha.Runner.html#.Runner#abort + */ + abort(): this; + + /** + * Handle uncaught exceptions. + * + * @see https://mochajs.org/api/Mocha.Runner.html#uncaught + */ + uncaught(err: any): void; + + /** + * Wrapper for setImmediate, process.nextTick, or browser polyfill. + */ + protected static immediately(callback: Function): void; + + /** + * Return a list of global properties. + * + * @see https://mochajs.org/api/Mocha.Runner.html#globalProps + */ + protected globalProps(): string[]; + + /** + * Check for global variable leaks. + * + * @see https://mochajs.org/api/Mocha.Runner.html#checkGlobals + */ + protected checkGlobals(test: Test): void; + + /** + * Fail the given `test`. + * + * @see https://mochajs.org/api/Mocha.Runner.html#fail + */ + protected fail(test: Test, err: any): void; + + /** + * Fail the given `hook` with `err`. + * + * Hook failures work in the following pattern: + * - If bail, then exit + * - Failed `before` hook skips all tests in a suite and subsuites, + * but jumps to corresponding `after` hook + * - Failed `before each` hook skips remaining tests in a + * suite and jumps to corresponding `after each` hook, + * which is run only once + * - Failed `after` hook does not alter + * execution order + * - Failed `after each` hook skips remaining tests in a + * suite and subsuites, but executes other `after each` + * hooks + * + * @see https://mochajs.org/api/Mocha.Runner.html#failHook + */ + protected failHook(hook: Hook, err: any): void; + + /** + * Run hook `name` callbacks and then invoke `fn()`. + * + * @see https://mochajs.org/api/Mocha.Runner.html#hook + */ + protected hook(name: string, fn: () => void): void; + + /** + * Run hook `name` for the given array of `suites` + * in order, and callback `fn(err, errSuite)`. + * + * @see https://mochajs.org/api/Mocha.Runner.html#hooks + */ + protected hooks(name: string, suites: Suite[], fn: (err?: any, errSuite?: Suite) => void): void; + + /** + * Run hooks from the top level down. + * + * @see https://mochajs.org/api/Mocha.Runner.html#hookUp + */ + protected hookUp(name: string, fn: (err?: any, errSuite?: Suite) => void): void; + + /** + * Run hooks from the bottom up. + * + * @see https://mochajs.org/api/Mocha.Runner.html#hookDown + */ + protected hookDown(name: string, fn: (err?: any, errSuite?: Suite) => void): void; + + /** + * Return an array of parent Suites from closest to furthest. + * + * @see https://mochajs.org/api/Mocha.Runner.html#parents + */ + protected parents(): Suite[]; + + /** + * Run the current test and callback `fn(err)`. + * + * @see https://mochajs.org/api/Mocha.Runner.html#runTest + */ + protected runTest(fn: Done): any; + + /** + * Run tests in the given `suite` and invoke the callback `fn()` when complete. + * + * @see https://mochajs.org/api/Mocha.Runner.html#runTests + */ + protected runTests(suite: Suite, fn: (errSuite?: Suite) => void): void; + + /** + * Run the given `suite` and invoke the callback `fn()` when complete. + * + * @see https://mochajs.org/api/Mocha.Runner.html#runSuite + */ + protected runSuite(suite: Suite, fn: (errSuite?: Suite) => void): void; + } + + // #region Runner "waiting" event + interface Runner { + on(event: "waiting", listener: (rootSuite: Suite) => void): this; + once(event: "waiting", listener: (rootSuite: Suite) => void): this; + addListener(event: "waiting", listener: (rootSuite: Suite) => void): this; + removeListener(event: "waiting", listener: (rootSuite: Suite) => void): this; + prependListener(event: "waiting", listener: (rootSuite: Suite) => void): this; + prependOnceListener(event: "waiting", listener: (rootSuite: Suite) => void): this; + emit(name: "waiting", rootSuite: Suite): boolean; + } + // #endregion Runner "waiting" event + // #region Runner "start" event + interface Runner extends NodeJS.EventEmitter { + on(event: "start", listener: () => void): this; + once(event: "start", listener: () => void): this; + addListener(event: "start", listener: () => void): this; + removeListener(event: "start", listener: () => void): this; + prependListener(event: "start", listener: () => void): this; + prependOnceListener(event: "start", listener: () => void): this; + emit(name: "start"): boolean; + } + // #endregion Runner "start" event + // #region Runner "end" event + interface Runner extends NodeJS.EventEmitter { + on(event: "end", listener: () => void): this; + once(event: "end", listener: () => void): this; + addListener(event: "end", listener: () => void): this; + removeListener(event: "end", listener: () => void): this; + prependListener(event: "end", listener: () => void): this; + prependOnceListener(event: "end", listener: () => void): this; + emit(name: "end"): boolean; + } + // #endregion Runner "end" event + // #region Runner "suite" event + interface Runner extends NodeJS.EventEmitter { + on(event: "suite", listener: (suite: Suite) => void): this; + once(event: "suite", listener: (suite: Suite) => void): this; + addListener(event: "suite", listener: (suite: Suite) => void): this; + removeListener(event: "suite", listener: (suite: Suite) => void): this; + prependListener(event: "suite", listener: (suite: Suite) => void): this; + prependOnceListener(event: "suite", listener: (suite: Suite) => void): this; + emit(name: "suite", suite: Suite): boolean; + } + // #endregion Runner "suite" event + // #region Runner "suite end" event + interface Runner extends NodeJS.EventEmitter { + on(event: "suite end", listener: (suite: Suite) => void): this; + once(event: "suite end", listener: (suite: Suite) => void): this; + addListener(event: "suite end", listener: (suite: Suite) => void): this; + removeListener(event: "suite end", listener: (suite: Suite) => void): this; + prependListener(event: "suite end", listener: (suite: Suite) => void): this; + prependOnceListener(event: "suite end", listener: (suite: Suite) => void): this; + emit(name: "suite end", suite: Suite): boolean; + } + // #endregion Runner "suite end" event + // #region Runner "test" event + interface Runner extends NodeJS.EventEmitter { + on(event: "test", listener: (test: Test) => void): this; + once(event: "test", listener: (test: Test) => void): this; + addListener(event: "test", listener: (test: Test) => void): this; + removeListener(event: "test", listener: (test: Test) => void): this; + prependListener(event: "test", listener: (test: Test) => void): this; + prependOnceListener(event: "test", listener: (test: Test) => void): this; + emit(name: "test", test: Test): boolean; + } + // #endregion Runner "test" event + // #region Runner "test end" event + interface Runner extends NodeJS.EventEmitter { + on(event: "test end", listener: (test: Test) => void): this; + once(event: "test end", listener: (test: Test) => void): this; + addListener(event: "test end", listener: (test: Test) => void): this; + removeListener(event: "test end", listener: (test: Test) => void): this; + prependListener(event: "test end", listener: (test: Test) => void): this; + prependOnceListener(event: "test end", listener: (test: Test) => void): this; + emit(name: "test end", test: Test): boolean; + } + // #endregion Runner "test end" event + // #region Runner "hook" event + interface Runner extends NodeJS.EventEmitter { + on(event: "hook", listener: (hook: Hook) => void): this; + once(event: "hook", listener: (hook: Hook) => void): this; + addListener(event: "hook", listener: (hook: Hook) => void): this; + removeListener(event: "hook", listener: (hook: Hook) => void): this; + prependListener(event: "hook", listener: (hook: Hook) => void): this; + prependOnceListener(event: "hook", listener: (hook: Hook) => void): this; + emit(name: "hook", hook: Hook): boolean; + } + // #endregion Runner "hook" event + // #region Runner "hook end" event + interface Runner extends NodeJS.EventEmitter { + on(event: "hook end", listener: (hook: Hook) => void): this; + once(event: "hook end", listener: (hook: Hook) => void): this; + addListener(event: "hook end", listener: (hook: Hook) => void): this; + removeListener(event: "hook end", listener: (hook: Hook) => void): this; + prependListener(event: "hook end", listener: (hook: Hook) => void): this; + prependOnceListener(event: "hook end", listener: (hook: Hook) => void): this; + emit(name: "hook end", hook: Hook): boolean; + } + // #endregion Runner "hook end" event + // #region Runner "pass" event + interface Runner extends NodeJS.EventEmitter { + on(event: "pass", listener: (test: Test) => void): this; + once(event: "pass", listener: (test: Test) => void): this; + addListener(event: "pass", listener: (test: Test) => void): this; + removeListener(event: "pass", listener: (test: Test) => void): this; + prependListener(event: "pass", listener: (test: Test) => void): this; + prependOnceListener(event: "pass", listener: (test: Test) => void): this; + emit(name: "pass", test: Test): boolean; + } + // #endregion Runner "pass" event + // #region Runner "fail" event + interface Runner extends NodeJS.EventEmitter { + on(event: "fail", listener: (test: Test, err: any) => void): this; + once(event: "fail", listener: (test: Test, err: any) => void): this; + addListener(event: "fail", listener: (test: Test, err: any) => void): this; + removeListener(event: "fail", listener: (test: Test, err: any) => void): this; + prependListener(event: "fail", listener: (test: Test, err: any) => void): this; + prependOnceListener(event: "fail", listener: (test: Test, err: any) => void): this; + emit(name: "fail", test: Test, err: any): boolean; + } + // #endregion Runner "fail" event + // #region Runner "pending" event + interface Runner extends NodeJS.EventEmitter { + on(event: "pending", listener: (test: Test) => void): this; + once(event: "pending", listener: (test: Test) => void): this; + addListener(event: "pending", listener: (test: Test) => void): this; + removeListener(event: "pending", listener: (test: Test) => void): this; + prependListener(event: "pending", listener: (test: Test) => void): this; + prependOnceListener(event: "pending", listener: (test: Test) => void): this; + emit(name: "pending", test: Test): boolean; + } + // #endregion Runner "pending" event + // #region Runner untyped events + interface Runner extends NodeJS.EventEmitter { + on(event: string, listener: (...args: any[]) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + addListener(event: string, listener: (...args: any[]) => void): this; + removeListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + emit(name: string, ...args: any[]): boolean; + } + // #endregion Runner untyped events + + /** + * Initialize a new `Suite` with the given `title` and `ctx`. + * + * @see https://mochajs.org/api/Mocha.Suite.html + */ + class Suite { + private _beforeEach; + private _beforeAll; + private _afterEach; + private _afterAll; + private _timeout; + private _enableTimeouts; + private _slow; + private _bail; + private _retries; + private _onlyTests; + private _onlySuites; + + constructor(title: string, parentContext?: Context); + /** @deprecated Use the overload that accepts `Mocha.Context` instead. */ + constructor(title: string, parentContext?: IContext); + + ctx: Context; + suites: Suite[]; + tests: Test[]; + pending: boolean; + file?: string; + root: boolean; + delayed: boolean; + parent: Suite | undefined; + title: string; + + /** + * Create a new `Suite` with the given `title` and parent `Suite`. When a suite + * with the same title is already present, that suite is returned to provide + * nicer reporter and more flexible meta-testing. + * + * @see https://mochajs.org/api/mocha#.exports.create + */ + static create(parent: Suite, title: string): Suite; + /** @deprecated Use the overload that accepts `Mocha.Suite` instead. */ + static create(parent: ISuite, title: string): Suite; + + /** + * Return a clone of this `Suite`. + * + * @see https://mochajs.org/api/Mocha.Suite.html#clone + */ + clone(): Suite; + + /** + * Get timeout `ms`. + * + * @see https://mochajs.org/api/Mocha.Suite.html#timeout + */ + timeout(): number; + + /** + * Set timeout `ms` or short-hand such as "2s". + * + * @see https://mochajs.org/api/Mocha.Suite.html#timeout + */ + timeout(ms: string | number): this; + + /** + * Get number of times to retry a failed test. + * + * @see https://mochajs.org/api/Mocha.Suite.html#retries + */ + retries(): number; + + /** + * Set number of times to retry a failed test. + * + * @see https://mochajs.org/api/Mocha.Suite.html#retries + */ + retries(n: string | number): this; + + /** + * Get whether timeouts are enabled. + * + * @see https://mochajs.org/api/Mocha.Suite.html#enableTimeouts + */ + enableTimeouts(): boolean; + + /** + * Set whether timeouts are `enabled`. + * + * @see https://mochajs.org/api/Mocha.Suite.html#enableTimeouts + */ + enableTimeouts(enabled: boolean): this; + + /** + * Get slow `ms`. + * + * @see https://mochajs.org/api/Mocha.Suite.html#slow + */ + slow(): number; + + /** + * Set slow `ms` or short-hand such as "2s". + * + * @see https://mochajs.org/api/Mocha.Suite.html#slow + */ + slow(ms: string | number): this; + + /** + * Get whether to bail after first error. + * + * @see https://mochajs.org/api/Mocha.Suite.html#bail + */ + bail(): boolean; + + /** + * Set whether to bail after first error. + * + * @see https://mochajs.org/api/Mocha.Suite.html#bail + */ + bail(bail: boolean): this; + + /** + * Check if this suite or its parent suite is marked as pending. + * + * @see https://mochajs.org/api/Mocha.Suite.html#isPending + */ + isPending(): boolean; + + /** + * Run `fn(test[, done])` before running tests. + * + * @see https://mochajs.org/api/Mocha.Suite.html#beforeAll + */ + beforeAll(fn?: Func): this; + + /** + * Run `fn(test[, done])` before running tests. + * + * @see https://mochajs.org/api/Mocha.Suite.html#beforeAll + */ + beforeAll(fn?: AsyncFunc): this; + + /** + * Run `fn(test[, done])` before running tests. + * + * @see https://mochajs.org/api/Mocha.Suite.html#beforeAll + */ + beforeAll(title: string, fn?: Func): this; + + /** + * Run `fn(test[, done])` before running tests. + * + * @see https://mochajs.org/api/Mocha.Suite.html#beforeAll + */ + beforeAll(title: string, fn?: AsyncFunc): this; + + /** + * Run `fn(test[, done])` after running tests. + * + * @see https://mochajs.org/api/Mocha.Suite.html#afterAll + */ + afterAll(fn?: Func): this; + + /** + * Run `fn(test[, done])` after running tests. + * + * @see https://mochajs.org/api/Mocha.Suite.html#afterAll + */ + afterAll(fn?: AsyncFunc): this; + + /** + * Run `fn(test[, done])` after running tests. + * + * @see https://mochajs.org/api/Mocha.Suite.html#afterAll + */ + afterAll(title: string, fn?: Func): this; + + /** + * Run `fn(test[, done])` after running tests. + * + * @see https://mochajs.org/api/Mocha.Suite.html#afterAll + */ + afterAll(title: string, fn?: AsyncFunc): this; + + /** + * Run `fn(test[, done])` before each test case. + * + * @see https://mochajs.org/api/Mocha.Suite.html#beforeEach + */ + beforeEach(fn?: Func): this; + + /** + * Run `fn(test[, done])` before each test case. + * + * @see https://mochajs.org/api/Mocha.Suite.html#beforeEach + */ + beforeEach(fn?: AsyncFunc): this; + + /** + * Run `fn(test[, done])` before each test case. + * + * @see https://mochajs.org/api/Mocha.Suite.html#beforeEach + */ + beforeEach(title: string, fn?: Func): this; + + /** + * Run `fn(test[, done])` before each test case. + * + * @see https://mochajs.org/api/Mocha.Suite.html#beforeEach + */ + beforeEach(title: string, fn?: AsyncFunc): this; + + /** + * Run `fn(test[, done])` after each test case. + * + * @see https://mochajs.org/api/Mocha.Suite.html#afterEach + */ + afterEach(fn?: Func): this; + + /** + * Run `fn(test[, done])` after each test case. + * + * @see https://mochajs.org/api/Mocha.Suite.html#afterEach + */ + afterEach(fn?: AsyncFunc): this; + + /** + * Run `fn(test[, done])` after each test case. + * + * @see https://mochajs.org/api/Mocha.Suite.html#afterEach + */ + afterEach(title: string, fn?: Func): this; + + /** + * Run `fn(test[, done])` after each test case. + * + * @see https://mochajs.org/api/Mocha.Suite.html#afterEach + */ + afterEach(title: string, fn?: AsyncFunc): this; + + /** + * Add a test `suite`. + * + * @see https://mochajs.org/api/Mocha.Suite.html#addSuite + */ + addSuite(suite: Suite): this; + /** @deprecated Use the overload that accepts `Mocha.ISuite` instead. */ + addSuite(suite: ISuite): this; + + /** + * Add a `test` to this suite. + * + * @see https://mochajs.org/api/Mocha.Suite.html#addTest + */ + addTest(test: Test): this; + /** @deprecated Use the overload that accepts `Mocha.ITest` instead. */ + addTest(test: ITest): this; + + /** + * Return the full title generated by recursively concatenating the parent's + * full title. + * + * @see https://mochajs.org/api/Mocha.Suite.html#.Suite#fullTitle + */ + fullTitle(): string; + + /** + * Return the title path generated by recursively concatenating the parent's + * title path. + * + * @see https://mochajs.org/api/Mocha.Suite.html#.Suite#titlePath + */ + titlePath(): string[]; + + /** + * Return the total number of tests. + * + * @see https://mochajs.org/api/Mocha.Suite.html#.Suite#total + */ + total(): number; + + /** + * Iterates through each suite recursively to find all tests. Applies a + * function in the format `fn(test)`. + * + * @see https://mochajs.org/api/Mocha.Suite.html#eachTest + */ + eachTest(fn: (test: Test) => void): this; + + /** + * This will run the root suite if we happen to be running in delayed mode. + * + * @see https://mochajs.org/api/Mocha.Suite.html#run + */ + run(): void; + + /** + * Generic hook-creator. + */ + protected _createHook(title: string, fn?: Func | AsyncFunc): Hook; + } + + // #region Suite "beforeAll" event + interface Suite extends NodeJS.EventEmitter { + on(event: "beforeAll", listener: (hook: Hook) => void): this; + once(event: "beforeAll", listener: (hook: Hook) => void): this; + addListener(event: "beforeAll", listener: (hook: Hook) => void): this; + removeListener(event: "beforeAll", listener: (hook: Hook) => void): this; + prependListener(event: "beforeAll", listener: (hook: Hook) => void): this; + prependOnceListener(event: "beforeAll", listener: (hook: Hook) => void): this; + emit(name: "beforeAll", hook: Hook): boolean; + } + // #endregion Suite "beforeAll" event + // #region Suite "afterAll" event + interface Suite extends NodeJS.EventEmitter { + on(event: "afterAll", listener: (hook: Hook) => void): this; + once(event: "afterAll", listener: (hook: Hook) => void): this; + addListener(event: "afterAll", listener: (hook: Hook) => void): this; + removeListener(event: "afterAll", listener: (hook: Hook) => void): this; + prependListener(event: "afterAll", listener: (hook: Hook) => void): this; + prependOnceListener(event: "afterAll", listener: (hook: Hook) => void): this; + emit(name: "afterAll", hook: Hook): boolean; + } + // #endregion Suite "afterAll" event + // #region Suite "beforeEach" event + interface Suite extends NodeJS.EventEmitter { + on(event: "beforeEach", listener: (hook: Hook) => void): this; + once(event: "beforeEach", listener: (hook: Hook) => void): this; + addListener(event: "beforeEach", listener: (hook: Hook) => void): this; + removeListener(event: "beforeEach", listener: (hook: Hook) => void): this; + prependListener(event: "beforeEach", listener: (hook: Hook) => void): this; + prependOnceListener(event: "beforeEach", listener: (hook: Hook) => void): this; + emit(name: "beforeEach", hook: Hook): boolean; + } + // #endregion Suite "beforeEach" event + // #region Suite "afterEach" event + interface Suite extends NodeJS.EventEmitter { + on(event: "afterEach", listener: (hook: Hook) => void): this; + once(event: "afterEach", listener: (hook: Hook) => void): this; + addListener(event: "afterEach", listener: (hook: Hook) => void): this; + removeListener(event: "afterEach", listener: (hook: Hook) => void): this; + prependListener(event: "afterEach", listener: (hook: Hook) => void): this; + prependOnceListener(event: "afterEach", listener: (hook: Hook) => void): this; + emit(name: "afterEach", hook: Hook): boolean; + } + // #endregion Suite "afterEach" event + // #region Suite "suite" event + interface Suite extends NodeJS.EventEmitter { + on(event: "suite", listener: (suite: Suite) => void): this; + once(event: "suite", listener: (suite: Suite) => void): this; + addListener(event: "suite", listener: (suite: Suite) => void): this; + removeListener(event: "suite", listener: (suite: Suite) => void): this; + prependListener(event: "suite", listener: (suite: Suite) => void): this; + prependOnceListener(event: "suite", listener: (suite: Suite) => void): this; + emit(name: "suite", suite: Suite): boolean; + } + // #endregion Suite "suite" event + // #region Suite "test" event + interface Suite { + on(event: "test", listener: (test: Test) => void): this; + once(event: "test", listener: (test: Test) => void): this; + addListener(event: "test", listener: (test: Test) => void): this; + removeListener(event: "test", listener: (test: Test) => void): this; + prependListener(event: "test", listener: (test: Test) => void): this; + prependOnceListener(event: "test", listener: (test: Test) => void): this; + emit(name: "test", test: Test): boolean; + } + // #endregion Suite "test" event + // #region Suite "run" event + interface Suite extends NodeJS.EventEmitter { + on(event: "run", listener: () => void): this; + once(event: "run", listener: () => void): this; + addListener(event: "run", listener: () => void): this; + removeListener(event: "run", listener: () => void): this; + prependListener(event: "run", listener: () => void): this; + prependOnceListener(event: "run", listener: () => void): this; + emit(name: "run"): boolean; + } + // #endregion Suite "run" event + // #region Suite "pre-require" event + interface Suite extends NodeJS.EventEmitter { + on(event: "pre-require", listener: (context: MochaGlobals, file: string, mocha: Mocha) => void): this; + once(event: "pre-require", listener: (context: MochaGlobals, file: string, mocha: Mocha) => void): this; + addListener(event: "pre-require", listener: (context: MochaGlobals, file: string, mocha: Mocha) => void): this; + removeListener(event: "pre-require", listener: (context: MochaGlobals, file: string, mocha: Mocha) => void): this; + prependListener(event: "pre-require", listener: (context: MochaGlobals, file: string, mocha: Mocha) => void): this; + prependOnceListener(event: "pre-require", listener: (context: MochaGlobals, file: string, mocha: Mocha) => void): this; + emit(name: "pre-require", context: MochaGlobals, file: string, mocha: Mocha): boolean; + } + // #endregion Suite "pre-require" event + // #region Suite "require" event + interface Suite extends NodeJS.EventEmitter { + on(event: "require", listener: (module: any, file: string, mocha: Mocha) => void): this; + once(event: "require", listener: (module: any, file: string, mocha: Mocha) => void): this; + addListener(event: "require", listener: (module: any, file: string, mocha: Mocha) => void): this; + removeListener(event: "require", listener: (module: any, file: string, mocha: Mocha) => void): this; + prependListener(event: "require", listener: (module: any, file: string, mocha: Mocha) => void): this; + prependOnceListener(event: "require", listener: (module: any, file: string, mocha: Mocha) => void): this; + emit(name: "require", module: any, file: string, mocha: Mocha): boolean; + } + // #endregion Suite "require" event + // #region Suite "post-require" event + interface Suite extends NodeJS.EventEmitter { + on(event: "post-require", listener: (context: MochaGlobals, file: string, mocha: Mocha) => void): this; + once(event: "post-require", listener: (context: MochaGlobals, file: string, mocha: Mocha) => void): this; + addListener(event: "post-require", listener: (context: MochaGlobals, file: string, mocha: Mocha) => void): this; + removeListener(event: "post-require", listener: (context: MochaGlobals, file: string, mocha: Mocha) => void): this; + prependListener(event: "post-require", listener: (context: MochaGlobals, file: string, mocha: Mocha) => void): this; + prependOnceListener(event: "post-require", listener: (context: MochaGlobals, file: string, mocha: Mocha) => void): this; + emit(name: "post-require", context: MochaGlobals, file: string, mocha: Mocha): boolean; + } + // #endregion Suite "post-require" event + // #region Suite untyped events + interface Suite extends NodeJS.EventEmitter { + on(event: string, listener: (...args: any[]) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + addListener(event: string, listener: (...args: any[]) => void): this; + removeListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + emit(name: string, ...args: any[]): boolean; + } + // #endregion Runner untyped events + + /** + * Initialize a new `Hook` with the given `title` and callback `fn` + * + * @see https://mochajs.org/api/Hook.html + */ + class Hook extends Runnable { + private _error; + + type: "hook"; + originalTitle?: string; // added by Runner + + /** + * Get the test `err`. + * + * @see https://mochajs.org/api/Hook.html#error + */ + error(): any; + + /** + * Set the test `err`. + * + * @see https://mochajs.org/api/Hook.html#error + */ + error(err: any): void; + } + + /** + * Initialize a new `Test` with the given `title` and callback `fn`. + * + * @see https://mochajs.org/api/Test.html + */ + class Test extends Runnable { + type: "test"; + speed?: "slow" | "medium" | "fast"; // added by reporters + err?: Error; // added by reporters + clone(): Test; + } + + /** + * Test statistics + */ + interface Stats { + suites: number; + tests: number; + passes: number; + pending: number; + failures: number; + start?: Date; + end?: Date; + duration?: number; + } + + type TestInterface = (suite: Suite) => void; + + interface ReporterConstructor { + new (runner: Runner, options: { reporterOptions?: any; }): reporters.Base; + } + + type Done = (err?: any) => void; + + /** + * Callback function used for tests and hooks. + */ + type Func = (this: Context, done: Done) => void; + + /** + * Async callback function used for tests and hooks. + */ + type AsyncFunc = (this: Context) => PromiseLike; + + /** + * Options to pass to Mocha. + */ + interface MochaOptions { + /** Test interfaces ("bdd", "tdd", "exports", etc.). */ + ui?: Interface; + + /** + * Reporter constructor, built-in reporter name, or reporter module path. Defaults to + * `"spec"`. + */ + reporter?: string | ReporterConstructor; + + /** Options to pass to the reporter. */ + reporterOptions?: any; + + /** Array of accepted globals. */ + globals?: string[]; + + /** timeout in milliseconds. */ + timeout?: number; + + enableTimeouts?: boolean; + + /** number of times to retry failed tests. */ + retries?: number; + + /** bail on the first test failure. */ + bail?: boolean; + + /** milliseconds to wait before considering a test slow. */ + slow?: number; + + /** ignore global leaks. */ + ignoreLeaks?: boolean; + + /** display the full stack trace on failure. */ + fullStackTrace?: boolean; + + /** string or regexp to filter tests with. */ + grep?: string | RegExp; + + /** Enable growl support. */ + growl?: boolean; + + /** Emit color output. */ + useColors?: boolean; + + /** Use inline diffs rather than +/-. */ + inlineDiffs?: boolean; + + /** Do not show diffs at all. */ + hideDiff?: boolean; + + asyncOnly?: boolean; + delay?: boolean; + forbidOnly?: boolean; + forbidPending?: boolean; + noHighlighting?: boolean; + allowUncaught?: boolean; + } + + interface MochaInstanceOptions extends MochaOptions { + files?: string[]; + } + + /** + * Variables added to the global scope by Mocha when run in the CLI. + */ + interface MochaGlobals { + /** + * Execute before running tests. + * + * - _Only available when invoked via the mocha CLI._ + * + * @see https://mochajs.org/api/global.html#before + */ + before: HookFunction; + + /** + * Execute after running tests. + * + * - _Only available when invoked via the mocha CLI._ + * + * @see https://mochajs.org/api/global.html#after + */ + after: HookFunction; + + /** + * Execute before each test case. + * + * - _Only available when invoked via the mocha CLI._ + * + * @see https://mochajs.org/api/global.html#beforeEach + */ + beforeEach: HookFunction; + + /** + * Execute after each test case. + * + * - _Only available when invoked via the mocha CLI._ + * + * @see https://mochajs.org/api/global.html#afterEach + */ + afterEach: HookFunction; + + /** + * Describe a "suite" containing nested suites and tests. + * + * - _Only available when invoked via the mocha CLI._ + */ + describe: SuiteFunction; + + /** + * Describe a "suite" containing nested suites and tests. + * + * - _Only available when invoked via the mocha CLI._ + */ + context: SuiteFunction; + + /** + * Pending suite. + * + * - _Only available when invoked via the mocha CLI._ + */ + xdescribe: PendingSuiteFunction; + + /** + * Pending suite. + * + * - _Only available when invoked via the mocha CLI._ + */ + xcontext: PendingSuiteFunction; + + /** + * Describes a test case. + * + * - _Only available when invoked via the mocha CLI._ + */ + it: TestFunction; + + /** + * Describes a test case. + * + * - _Only available when invoked via the mocha CLI._ + */ + specify: TestFunction; + + /** + * Describes a pending test case. + * + * - _Only available when invoked via the mocha CLI._ + */ + xit: PendingTestFunction; + + /** + * Describes a pending test case. + * + * - _Only available when invoked via the mocha CLI._ + */ + xspecify: PendingTestFunction; + + /** + * Execute before running tests. + * + * - _Only available when invoked via the mocha CLI._ + * + * @see https://mochajs.org/api/global.html#before + */ + suiteSetup: HookFunction; + + /** + * Execute after running tests. + * + * - _Only available when invoked via the mocha CLI._ + * + * @see https://mochajs.org/api/global.html#after + */ + suiteTeardown: HookFunction; + + /** + * Execute before each test case. + * + * - _Only available when invoked via the mocha CLI._ + * + * @see https://mochajs.org/api/global.html#beforeEach + */ + setup: HookFunction; + + /** + * Execute after each test case. + * + * - _Only available when invoked via the mocha CLI._ + * + * @see https://mochajs.org/api/global.html#afterEach + */ + teardown: HookFunction; + + /** + * Describe a "suite" containing nested suites and tests. + * + * - _Only available when invoked via the mocha CLI._ + */ + suite: SuiteFunction; + + /** + * Describes a test case. + * + * - _Only available when invoked via the mocha CLI._ + */ + test: TestFunction; + + run: typeof run; + } + + /** + * Third-party declarations that want to add new entries to the `Reporter` union can + * contribute names here. + */ + interface ReporterContributions { + Base: never; + base: never; + Dot: never; + dot: never; + TAP: never; + tap: never; + JSON: never; + json: never; + HTML: never; + html: never; + List: never; + list: never; + Min: never; + min: never; + Spec: never; + spec: never; + Nyan: never; + nyan: never; + XUnit: never; + xunit: never; + Markdown: never; + markdown: never; + Progress: never; + progress: never; + Landing: never; + landing: never; + JSONStream: never; + "json-stream": never; + } + + type Reporter = keyof ReporterContributions; + + /** + * Third-party declarations that want to add new entries to the `Interface` union can + * contribute names here. + */ + interface InterfaceContributions { + bdd: never; + tdd: never; + qunit: never; + exports: never; + } + + type Interface = keyof InterfaceContributions; + + // #region Deprecations + + /** @deprecated use `Mocha.Context` instead. */ + interface IContext { + test?: IRunnable; + runnable(): IRunnable | undefined; + /** @deprecated `.runnable()` returns `this` in `Mocha.Context`. */ + runnable(runnable: IRunnable): IContext; + timeout(): number; + /** @deprecated `.timeout()` returns `this` in `Mocha.Context`. */ + timeout(timeout: number): IContext; + /** @deprecated `.enableTimeouts()` has additional overloads in `Mocha.Context`. */ + /** @deprecated `.enableTimeouts()` returns `this` in `Mocha.Context`. */ + enableTimeouts(enableTimeouts: boolean): IContext; + /** @deprecated `.slow()` has additional overloads in `Mocha.Context`. */ + /** @deprecated `.slow()` returns `this` in `Mocha.Context`. */ + slow(slow: number): IContext; + /** @deprecated `.skip()` returns `never` in `Mocha.Context`. */ + skip(): IContext; + retries(): number; + /** @deprecated `.retries()` returns `this` in `Mocha.Context`. */ + retries(retries: number): IContext; + } + + /** @deprecated use `Mocha.Suite` instead. */ + interface ISuiteCallbackContext { + /** @deprecated `.timeout()` has additional overloads in `Mocha.Suite`. */ + timeout(ms: number | string): this; + /** @deprecated `.retries()` has additional overloads in `Mocha.Suite`. */ + retries(n: number): this; + /** @deprecated `.slow()` has additional overloads in `Mocha.Suite`. */ + slow(ms: number): this; + } + + /** @deprecated use `Mocha.Context` instead. */ + interface IHookCallbackContext { + /** @deprecated `.skip()` returns `never` in `Mocha.Context`. */ + skip(): this; + /** @deprecated `.timeout()` has additional overloads in `Mocha.Context`. */ + timeout(ms: number | string): this; + [index: string]: any; + } + + /** @deprecated use `Mocha.Context` instead. */ + interface ITestCallbackContext { + /** @deprecated `.skip()` returns `never` in `Mocha.Context`. */ + skip(): this; + /** @deprecated `.timeout()` has additional overloads in `Mocha.Context`. */ + timeout(ms: number | string): this; + /** @deprecated `.retries()` has additional overloads in `Mocha.Context`. */ + retries(n: number): this; + /** @deprecated `.slow()` has additional overloads in `Mocha.Context`. */ + slow(ms: number): this; + [index: string]: any; + } + + /** Partial interface for Mocha's `Runnable` class. */ + /** @deprecated use `Mocha.Runnable` instead. */ + interface IRunnable extends NodeJS.EventEmitter { + title: string; + /** @deprecated `.fn` has type `Func | AsyncFunc` in `Mocha.Runnable`. */ + fn: Function | undefined; + async: boolean; + sync: boolean; + timedOut: boolean; + /** @deprecated `.timeout()` has additional overloads in `Mocha.Runnable`. */ + timeout(n: number | string): this; + duration?: number; + } + + /** Partial interface for Mocha's `Suite` class. */ + /** @deprecated use `Mocha.Suite` instead. */ + interface ISuite { + /** @deprecated `.ctx` has type `Mocha.Context` in `Mocha.Suite`. */ + ctx: IContext; + /** @deprecated `.parent` has type `Mocha.Suite | undefined` in `Mocha.Suite`. */ + parent: ISuite | undefined; + root: boolean; + title: string; + /** @deprecated `.suites` has type `Mocha.Suite[]` in `Mocha.Suite`. */ + suites: ISuite[]; + /** @deprecated `.tests` has type `Mocha.Test[]` in `Mocha.Suite`. */ + tests: ITest[]; + + bail(): boolean; + /** @deprecated `.bail()` returns `this` in `Mocha.Suite`. */ + bail(bail: boolean): ISuite; + fullTitle(): string; + retries(): number; + /** @deprecated `.retries()` returns `this` in `Mocha.Suite`. */ + retries(retries: number): ISuite; + slow(): number; + /** @deprecated `.slow()` returns `this` in `Mocha.Suite`. */ + slow(slow: number): ISuite; + timeout(): number; + /** @deprecated `.timeout()` returns `this` in `Mocha.Suite`. */ + timeout(timeout: number): ISuite; + } + + /** Partial interface for Mocha's `Test` class. */ + /** @deprecated use `Mocha.Test` instead. */ + interface ITest extends IRunnable { + body?: string; + file?: string; + /** @deprecated `.parent` has type `Mocha.Suite | undefined` in `Mocha.Test`. */ + parent?: ISuite; + pending: boolean; + state?: 'failed' | 'passed'; + type: 'test'; + fullTitle(): string; + } + + /** @deprecated use `Mocha.Hook` instead. */ + interface IHook extends IRunnable { + /** @deprecated `.ctx` has type `Mocha.Context` in `Mocha.Runnable`. */ + ctx?: IContext; + /** @deprecated `.parent` has type `Mocha.Suite` in `Mocha.Runnable`. */ + parent?: ISuite; + type: 'hook'; + /** @deprecated `.error()` has additional overloads in `Mocha.Hook`. */ + error(err: Error): void; + } + + /** @deprecated use `Mocha.Context` instead. */ + interface IBeforeAndAfterContext extends IHookCallbackContext { + /** @deprecated `.currentTest` has type `Mocha.Test` in `Mocha.Context`. */ + currentTest?: ITest; + } + + /** @deprecated use `Mocha.Stats` instead. */ + type IStats = Stats; + + /** Partial interface for Mocha's `Runner` class. */ + /** @deprecated use `Mocha.Runner` instead. */ + interface IRunner extends NodeJS.EventEmitter { + asyncOnly?: boolean; + stats?: IStats; + started: boolean; + /** @deprecated `.suite` has type `Mocha.Suite` in `Mocha.Runner`. */ + suite: ISuite; + total: number; + failures: number; + forbidOnly?: boolean; + forbidPending?: boolean; + fullStackTrace?: boolean; + ignoreLeaks?: boolean; + grep(re: RegExp, invert: boolean): this; + /** @deprecated Parameter `suite` has type `Mocha.Suite` in `Mocha.Runner`. */ + grepTotal(suite: ISuite): number; + /** @deprecated `.globals()` has different overloads in `Mocha.Runner`. */ + globals(arr: ReadonlyArray): this | string[]; + abort(): this; + run(fn?: (failures: number) => void): this; + } + + /** @deprecated use `Mocha.SuiteFunction` instead. */ + interface IContextDefinition { + /** @deprecated use `Mocha.SuiteFunction` instead. */ + (description: string, callback: (this: ISuiteCallbackContext) => void): ISuite; + /** @deprecated use `Mocha.SuiteFunction` instead. */ + only(description: string, callback: (this: ISuiteCallbackContext) => void): ISuite; + /** @deprecated use `Mocha.SuiteFunction` instead. */ + skip(description: string, callback: (this: ISuiteCallbackContext) => void): void; + } + + /** @deprecated use `Mocha.TestFunction` instead. */ + interface ITestDefinition { + /** @deprecated use `Mocha.TestFunction` instead. */ + /** @deprecated `Mocha.TestFunction` does not allow mixing `done` with a return type of `PromiseLike`. */ + (expectation: string, callback?: (this: ITestCallbackContext, done: MochaDone) => PromiseLike | void): ITest; + /** @deprecated use `Mocha.TestFunction` instead. */ + /** @deprecated `Mocha.TestFunction#only` does not allow mixing `done` with a return type of `PromiseLike`. */ + only(expectation: string, callback?: (this: ITestCallbackContext, done: MochaDone) => PromiseLike | void): ITest; + /** @deprecated use `Mocha.TestFunction` instead. */ + /** @deprecated `Mocha.TestFunction#skip` does not allow mixing `done` with a return type of `PromiseLike`. */ + skip(expectation: string, callback?: (this: ITestCallbackContext, done: MochaDone) => PromiseLike | void): void; + } + + // #endregion +} + +// #region Test interface augmentations + +/** + * Triggers root suite execution. + * + * - _Only available if flag --delay is passed into Mocha._ + * - _Only available when invoked via the mocha CLI._ + * + * @see https://mochajs.org/api/global.html#runWithSuite + */ +declare function run(): void; + +/** + * Execute before running tests. + * + * - _Only available when invoked via the mocha CLI._ + * + * @see https://mochajs.org/api/global.html#before + */ +declare var before: Mocha.HookFunction; + +/** + * Execute before running tests. + * + * - _Only available when invoked via the mocha CLI._ + * + * @see https://mochajs.org/api/global.html#before + */ +declare var suiteSetup: Mocha.HookFunction; + +/** + * Execute after running tests. + * + * - _Only available when invoked via the mocha CLI._ + * + * @see https://mochajs.org/api/global.html#after + */ +declare var after: Mocha.HookFunction; + +/** + * Execute after running tests. + * + * - _Only available when invoked via the mocha CLI._ + * + * @see https://mochajs.org/api/global.html#after + */ +declare var suiteTeardown: Mocha.HookFunction; + +/** + * Execute before each test case. + * + * - _Only available when invoked via the mocha CLI._ + * + * @see https://mochajs.org/api/global.html#beforeEach + */ +declare var beforeEach: Mocha.HookFunction; + +/** + * Execute before each test case. + * + * - _Only available when invoked via the mocha CLI._ + * + * @see https://mochajs.org/api/global.html#beforeEach + */ +declare var setup: Mocha.HookFunction; + +/** + * Execute after each test case. + * + * - _Only available when invoked via the mocha CLI._ + * + * @see https://mochajs.org/api/global.html#afterEach + */ +declare var afterEach: Mocha.HookFunction; + +/** + * Execute after each test case. + * + * - _Only available when invoked via the mocha CLI._ + * + * @see https://mochajs.org/api/global.html#afterEach + */ +declare var teardown: Mocha.HookFunction; + +/** + * Describe a "suite" containing nested suites and tests. + * + * - _Only available when invoked via the mocha CLI._ + */ +declare var describe: Mocha.SuiteFunction; + +/** + * Describe a "suite" containing nested suites and tests. + * + * - _Only available when invoked via the mocha CLI._ + */ +declare var context: Mocha.SuiteFunction; + +/** + * Describe a "suite" containing nested suites and tests. + * + * - _Only available when invoked via the mocha CLI._ + */ +declare var suite: Mocha.SuiteFunction; + +/** + * Pending suite. + * + * - _Only available when invoked via the mocha CLI._ + */ +declare var xdescribe: Mocha.PendingSuiteFunction; + +/** + * Pending suite. + * + * - _Only available when invoked via the mocha CLI._ + */ +declare var xcontext: Mocha.PendingSuiteFunction; + +/** + * Describes a test case. + * + * - _Only available when invoked via the mocha CLI._ + */ +declare var it: Mocha.TestFunction; + +/** + * Describes a test case. + * + * - _Only available when invoked via the mocha CLI._ + */ +declare var specify: Mocha.TestFunction; + +/** + * Describes a test case. + * + * - _Only available when invoked via the mocha CLI._ + */ +declare var test: Mocha.TestFunction; + +/** + * Describes a pending test case. + * + * - _Only available when invoked via the mocha CLI._ + */ +declare var xit: Mocha.PendingTestFunction; + +/** + * Describes a pending test case. + * + * - _Only available when invoked via the mocha CLI._ + */ +declare var xspecify: Mocha.PendingTestFunction; + +// #endregion Test interface augmentations + +// #region Reporter augmentations + +// Forward declaration for `HTMLLIElement` from lib.dom.d.ts. +// Required by Mocha.reporters.HTML. +// NOTE: Mocha *must not* have a direct dependency on DOM types. +// tslint:disable-next-line no-empty-interface +interface HTMLLIElement { } + +// Augments the DOM `Window` object when lib.dom.d.ts is loaded. +// tslint:disable-next-line no-empty-interface +interface Window extends Mocha.MochaGlobals { } + +declare namespace NodeJS { + // Forward declaration for `NodeJS.EventEmitter` from node.d.ts. + // Required by Mocha.Runnable, Mocha.Runner, and Mocha.Suite. + // NOTE: Mocha *must not* have a direct dependency on @types/node. + // tslint:disable-next-line no-empty-interface + interface EventEmitter { } + + // Augments NodeJS's `global` object when node.d.ts is loaded + // tslint:disable-next-line no-empty-interface + interface Global extends Mocha.MochaGlobals { } +} + +// #endregion Reporter augmentations + +// #region Browser augmentations + +/** + * Mocha global. + * + * - _Only supported in the browser._ + */ +declare const mocha: BrowserMocha; + +interface BrowserMocha extends Mocha { + /** + * Function to allow assertion libraries to throw errors directly into mocha. + * This is useful when running tests in a browser because window.onerror will + * only receive the 'message' attribute of the Error. + * + * - _Only supported in the browser._ + */ + throwError(err: any): never; + + /** + * Setup mocha with the given settings options. + * + * - _Only supported in the browser._ + */ + setup(opts?: Mocha.Interface | MochaSetupOptions): this; +} + +/** + * Options to pass to `mocha.setup` in the browser. + */ +interface MochaSetupOptions extends Mocha.MochaOptions { + /** @deprecated This is not used by Mocha. Use `files` instead. */ + require?: string[]; + fullTrace?: boolean; +} + +// #endregion Browser augmentations + +// #region Deprecations + +/** @deprecated use `Mocha.Done` instead. */ +type MochaDone = Mocha.Done; + +/** @deprecated use `Mocha.ReporterConstructor` instead. */ +type ReporterConstructor = Mocha.ReporterConstructor; + +// #endregion Deprecations + +declare module "mocha" { + export = Mocha; +} + +declare module "mocha/lib/ms" { + export = milliseconds; + /** + * Parse the given `str` and return milliseconds. + * + * @see {@link https://mochajs.org/api/module-milliseconds.html} + * @see {@link https://mochajs.org/api/module-milliseconds.html#~parse} + */ + function milliseconds(val: string): number; + + /** + * Format for `ms`. + * + * @see {@link https://mochajs.org/api/module-milliseconds.html} + * @see {@link https://mochajs.org/api/module-milliseconds.html#~format} + */ + function milliseconds(val: number): string; +} + +declare module "mocha/lib/interfaces/common" { + export = common; + + function common(suites: Mocha.Suite[], context: Mocha.MochaGlobals, mocha: Mocha): common.CommonFunctions; + + namespace common { + interface CommonFunctions { + /** + * This is only present if flag --delay is passed into Mocha. It triggers + * root suite execution. + */ + runWithSuite(suite: Mocha.Suite): () => void; + + /** + * Execute before running tests. + */ + before(fn?: Mocha.Func | Mocha.AsyncFunc): void; + + /** + * Execute before running tests. + */ + before(name: string, fn?: Mocha.Func | Mocha.AsyncFunc): void; + + /** + * Execute after running tests. + */ + after(fn?: Mocha.Func | Mocha.AsyncFunc): void; + + /** + * Execute after running tests. + */ + after(name: string, fn?: Mocha.Func | Mocha.AsyncFunc): void; + + /** + * Execute before each test case. + */ + beforeEach(fn?: Mocha.Func | Mocha.AsyncFunc): void; + + /** + * Execute before each test case. + */ + beforeEach(name: string, fn?: Mocha.Func | Mocha.AsyncFunc): void; + + /** + * Execute after each test case. + */ + afterEach(fn?: Mocha.Func | Mocha.AsyncFunc): void; + + /** + * Execute after each test case. + */ + afterEach(name: string, fn?: Mocha.Func | Mocha.AsyncFunc): void; + + suite: SuiteFunctions; + test: TestFunctions; + } + + interface CreateOptions { + /** Title of suite */ + title: string; + + /** Suite function */ + fn?: (this: Mocha.Suite) => void; + + /** Is suite pending? */ + pending?: boolean; + + /** Filepath where this Suite resides */ + file?: string; + + /** Is suite exclusive? */ + isOnly?: boolean; + } + + interface SuiteFunctions { + /** + * Create an exclusive Suite; convenience function + */ + only(opts: CreateOptions): Mocha.Suite; + + /** + * Create a Suite, but skip it; convenience function + */ + skip(opts: CreateOptions): Mocha.Suite; + + /** + * Creates a suite. + */ + create(opts: CreateOptions): Mocha.Suite; + } + + interface TestFunctions { + /** + * Exclusive test-case. + */ + only(mocha: Mocha, test: Mocha.Test): Mocha.Test; + + /** + * Pending test case. + */ + skip(title: string): void; + + /** + * Number of retry attempts + */ + retries(n: number): void; + } + } +} diff --git a/node_modules/@types/mocha/package.json b/node_modules/@types/mocha/package.json new file mode 100644 index 0000000..3f27c7e --- /dev/null +++ b/node_modules/@types/mocha/package.json @@ -0,0 +1,72 @@ +{ + "_from": "@types/mocha", + "_id": "@types/mocha@5.2.5", + "_inBundle": false, + "_integrity": "sha512-lAVp+Kj54ui/vLUFxsJTMtWvZraZxum3w3Nwkble2dNuV5VnPA+Mi2oGX9XYJAaIvZi3tn3cbjS/qcJXRb6Bww==", + "_location": "/@types/mocha", + "_phantomChildren": {}, + "_requested": { + "type": "tag", + "registry": true, + "raw": "@types/mocha", + "name": "@types/mocha", + "escapedName": "@types%2fmocha", + "scope": "@types", + "rawSpec": "", + "saveSpec": null, + "fetchSpec": "latest" + }, + "_requiredBy": [ + "#DEV:/", + "#USER" + ], + "_resolved": "https://registry.npmjs.org/@types/mocha/-/mocha-5.2.5.tgz", + "_shasum": "8a4accfc403c124a0bafe8a9fc61a05ec1032073", + "_spec": "@types/mocha", + "_where": "/Users/jessitron/code/jessitron/stringify-tree", + "bugs": { + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped/issues" + }, + "bundleDependencies": false, + "contributors": [ + { + "name": "Kazi Manzur Rashid", + "url": "https://github.com/kazimanzurrashid" + }, + { + "name": "otiai10", + "url": "https://github.com/otiai10" + }, + { + "name": "jt000", + "url": "https://github.com/jt000" + }, + { + "name": "Vadim Macagon", + "url": "https://github.com/enlight" + }, + { + "name": "Andrew Bradley", + "url": "https://github.com/cspotcode" + }, + { + "name": "Dmitrii Sorin", + "url": "https://github.com/1999" + } + ], + "dependencies": {}, + "deprecated": false, + "description": "TypeScript definitions for mocha", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped#readme", + "license": "MIT", + "main": "", + "name": "@types/mocha", + "repository": { + "type": "git", + "url": "git+https://github.com/DefinitelyTyped/DefinitelyTyped.git" + }, + "scripts": {}, + "typeScriptVersion": "2.1", + "typesPublisherContentHash": "124e2d9760528f989ad88208285587c1b513b5bca25aba78ebc5fa22e67b5b00", + "version": "5.2.5" +} diff --git a/node_modules/@types/node/LICENSE b/node_modules/@types/node/LICENSE new file mode 100644 index 0000000..4b1ad51 --- /dev/null +++ b/node_modules/@types/node/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. All rights reserved. + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE diff --git a/node_modules/@types/node/README.md b/node_modules/@types/node/README.md new file mode 100644 index 0000000..e9f0a55 --- /dev/null +++ b/node_modules/@types/node/README.md @@ -0,0 +1,16 @@ +# Installation +> `npm install --save @types/node` + +# Summary +This package contains type definitions for Node.js (http://nodejs.org/). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/node + +Additional Details + * Last updated: Wed, 19 Dec 2018 18:17:49 GMT + * Dependencies: none + * Global values: Buffer, NodeJS, SlowBuffer, Symbol, __dirname, __filename, clearImmediate, clearInterval, clearTimeout, console, exports, global, module, process, require, setImmediate, setInterval, setTimeout + +# Credits +These definitions were written by Microsoft TypeScript , DefinitelyTyped , Alberto Schiabel , Alexander T. , Alvis HT Tang , Andrew Makarov , Bruno Scheufler , Chigozirim C. , Christian Vaagland Tellnes , Deividas Bakanas , Eugene Y. Q. Shen , Flarna , Hannes Magnusson , Hoàng Văn Khải , Huw , Kelvin Jin , Klaus Meinhardt , Lishude , Mariusz Wiktorczyk , Matthieu Sieben , Mohsen Azimi , Nicolas Even , Nicolas Voigt , Parambir Singh , Sebastian Silbermann , Simon Schick , Thomas den Hollander , Wilco Bakker , wwwy3y3 , Zane Hannan AU , Jeremie Rodriguez , Samuel Ainsworth . diff --git a/node_modules/@types/node/index.d.ts b/node_modules/@types/node/index.d.ts new file mode 100644 index 0000000..c63b6c8 --- /dev/null +++ b/node_modules/@types/node/index.d.ts @@ -0,0 +1,9219 @@ +// Type definitions for Node.js 10.12 +// Project: http://nodejs.org/ +// Definitions by: Microsoft TypeScript +// DefinitelyTyped +// Alberto Schiabel +// Alexander T. +// Alvis HT Tang +// Andrew Makarov +// Bruno Scheufler +// Chigozirim C. +// Christian Vaagland Tellnes +// Deividas Bakanas +// Eugene Y. Q. Shen +// Flarna +// Hannes Magnusson +// Hoàng Văn Khải +// Huw +// Kelvin Jin +// Klaus Meinhardt +// Lishude +// Mariusz Wiktorczyk +// Matthieu Sieben +// Mohsen Azimi +// Nicolas Even +// Nicolas Voigt +// Parambir Singh +// Sebastian Silbermann +// Simon Schick +// Thomas den Hollander +// Wilco Bakker +// wwwy3y3 +// Zane Hannan AU +// Jeremie Rodriguez +// Samuel Ainsworth +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/** inspector module types */ +/// + +// This needs to be global to avoid TS2403 in case lib.dom.d.ts is present in the same build +interface Console { + Console: NodeJS.ConsoleConstructor; + /** + * A simple assertion test that verifies whether `value` is truthy. + * If it is not, an `AssertionError` is thrown. + * If provided, the error `message` is formatted using `util.format()` and used as the error message. + */ + assert(value: any, message?: string, ...optionalParams: any[]): void; + /** + * When `stdout` is a TTY, calling `console.clear()` will attempt to clear the TTY. + * When `stdout` is not a TTY, this method does nothing. + */ + clear(): void; + /** + * Maintains an internal counter specific to `label` and outputs to `stdout` the number of times `console.count()` has been called with the given `label`. + */ + count(label?: string): void; + /** + * Resets the internal counter specific to `label`. + */ + countReset(label?: string): void; + /** + * The `console.debug()` function is an alias for {@link console.log()}. + */ + debug(message?: any, ...optionalParams: any[]): void; + /** + * Uses {@link util.inspect()} on `obj` and prints the resulting string to `stdout`. + * This function bypasses any custom `inspect()` function defined on `obj`. + */ + dir(obj: any, options?: NodeJS.InspectOptions): void; + /** + * This method calls {@link console.log()} passing it the arguments received. Please note that this method does not produce any XML formatting + */ + dirxml(...data: any[]): void; + /** + * Prints to `stderr` with newline. + */ + error(message?: any, ...optionalParams: any[]): void; + /** + * Increases indentation of subsequent lines by two spaces. + * If one or more `label`s are provided, those are printed first without the additional indentation. + */ + group(...label: any[]): void; + /** + * The `console.groupCollapsed()` function is an alias for {@link console.group()}. + */ + groupCollapsed(): void; + /** + * Decreases indentation of subsequent lines by two spaces. + */ + groupEnd(): void; + /** + * The {@link console.info()} function is an alias for {@link console.log()}. + */ + info(message?: any, ...optionalParams: any[]): void; + /** + * Prints to `stdout` with newline. + */ + log(message?: any, ...optionalParams: any[]): void; + /** + * This method does not display anything unless used in the inspector. + * Prints to `stdout` the array `array` formatted as a table. + */ + table(tabularData: any, properties?: string[]): void; + /** + * Starts a timer that can be used to compute the duration of an operation. Timers are identified by a unique `label`. + */ + time(label?: string): void; + /** + * Stops a timer that was previously started by calling {@link console.time()} and prints the result to `stdout`. + */ + timeEnd(label?: string): void; + /** + * For a timer that was previously started by calling {@link console.time()}, prints the elapsed time and other `data` arguments to `stdout`. + */ + timeLog(label?: string, ...data: any[]): void; + /** + * Prints to `stderr` the string 'Trace :', followed by the {@link util.format()} formatted message and stack trace to the current position in the code. + */ + trace(message?: any, ...optionalParams: any[]): void; + /** + * The {@link console.warn()} function is an alias for {@link console.error()}. + */ + warn(message?: any, ...optionalParams: any[]): void; + + // --- Inspector mode only --- + /** + * This method does not display anything unless used in the inspector. + * The console.markTimeline() method is the deprecated form of console.timeStamp(). + * + * @deprecated Use console.timeStamp() instead. + */ + markTimeline(label?: string): void; + /** + * This method does not display anything unless used in the inspector. + * Starts a JavaScript CPU profile with an optional label. + */ + profile(label?: string): void; + /** + * This method does not display anything unless used in the inspector. + * Stops the current JavaScript CPU profiling session if one has been started and prints the report to the Profiles panel of the inspector. + */ + profileEnd(label?: string): void; + /** + * This method does not display anything unless used in the inspector. + * Adds an event with the label `label` to the Timeline panel of the inspector. + */ + timeStamp(label?: string): void; + /** + * This method does not display anything unless used in the inspector. + * The console.timeline() method is the deprecated form of console.time(). + * + * @deprecated Use console.time() instead. + */ + timeline(label?: string): void; + /** + * This method does not display anything unless used in the inspector. + * The console.timelineEnd() method is the deprecated form of console.timeEnd(). + * + * @deprecated Use console.timeEnd() instead. + */ + timelineEnd(label?: string): void; +} + +interface Error { + stack?: string; +} + +// Declare "static" methods in Error +interface ErrorConstructor { + /** Create .stack property on a target object */ + captureStackTrace(targetObject: Object, constructorOpt?: Function): void; + + /** + * Optional override for formatting stack traces + * + * @see https://github.com/v8/v8/wiki/Stack%20Trace%20API#customizing-stack-traces + */ + prepareStackTrace?: (err: Error, stackTraces: NodeJS.CallSite[]) => any; + + stackTraceLimit: number; +} + +// compat for TypeScript 1.8 and default es5 target +// if you use with --target es3 or --target es5 and use below definitions, +// use the lib.es6.d.ts that is bundled with TypeScript 1.8. +interface MapConstructor { } +interface WeakMapConstructor { } +interface SetConstructor { } +interface WeakSetConstructor { } + +interface Set {} +interface ReadonlySet {} + +// Forward-declare needed types from lib.es2015.d.ts (in case users are using `--lib es5`) +interface Iterable { } +interface Iterator { + next(value?: any): IteratorResult; +} +interface IteratorResult { } +interface AsyncIterableIterator {} +interface SymbolConstructor { + readonly observable: symbol; + readonly iterator: symbol; + readonly asyncIterator: symbol; +} +declare var Symbol: SymbolConstructor; +interface SharedArrayBuffer { + readonly byteLength: number; + slice(begin?: number, end?: number): SharedArrayBuffer; +} + +// Node.js ESNEXT support +interface String { + /** Removes whitespace from the left end of a string. */ + trimLeft(): string; + /** Removes whitespace from the right end of a string. */ + trimRight(): string; +} + +/*-----------------------------------------------* + * * + * GLOBAL * + * * + ------------------------------------------------*/ +declare var process: NodeJS.Process; +declare var global: NodeJS.Global; +declare var console: Console; + +declare var __filename: string; +declare var __dirname: string; + +declare function setTimeout(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timeout; +declare namespace setTimeout { + function __promisify__(ms: number): Promise; + function __promisify__(ms: number, value: T): Promise; +} +declare function clearTimeout(timeoutId: NodeJS.Timeout): void; +declare function setInterval(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timeout; +declare function clearInterval(intervalId: NodeJS.Timeout): void; +declare function setImmediate(callback: (...args: any[]) => void, ...args: any[]): NodeJS.Immediate; +declare namespace setImmediate { + function __promisify__(): Promise; + function __promisify__(value: T): Promise; +} +declare function clearImmediate(immediateId: NodeJS.Immediate): void; + +// TODO: change to `type NodeRequireFunction = (id: string) => any;` in next mayor version. +interface NodeRequireFunction { + /* tslint:disable-next-line:callable-types */ + (id: string): any; +} + +interface NodeRequire extends NodeRequireFunction { + resolve: RequireResolve; + cache: any; + extensions: NodeExtensions; + main: NodeModule | undefined; +} + +interface RequireResolve { + (id: string, options?: { paths?: string[]; }): string; + paths(request: string): string[] | null; +} + +interface NodeExtensions { + '.js': (m: NodeModule, filename: string) => any; + '.json': (m: NodeModule, filename: string) => any; + '.node': (m: NodeModule, filename: string) => any; + [ext: string]: (m: NodeModule, filename: string) => any; +} + +declare var require: NodeRequire; + +interface NodeModule { + exports: any; + require: NodeRequireFunction; + id: string; + filename: string; + loaded: boolean; + parent: NodeModule | null; + children: NodeModule[]; + paths: string[]; +} + +declare var module: NodeModule; + +// Same as module.exports +declare var exports: any; +declare const SlowBuffer: { + new(str: string, encoding?: string): Buffer; + new(size: number): Buffer; + new(size: Uint8Array): Buffer; + new(array: any[]): Buffer; + prototype: Buffer; + isBuffer(obj: any): boolean; + byteLength(string: string, encoding?: string): number; + concat(list: Buffer[], totalLength?: number): Buffer; +}; + +// Buffer class +type BufferEncoding = "ascii" | "utf8" | "utf16le" | "ucs2" | "base64" | "latin1" | "binary" | "hex"; +interface Buffer extends Uint8Array { + constructor: typeof Buffer; + write(string: string, offset?: number, length?: number, encoding?: string): number; + toString(encoding?: string, start?: number, end?: number): string; + toJSON(): { type: 'Buffer', data: any[] }; + equals(otherBuffer: Uint8Array): boolean; + compare(otherBuffer: Uint8Array, targetStart?: number, targetEnd?: number, sourceStart?: number, sourceEnd?: number): number; + copy(targetBuffer: Uint8Array, targetStart?: number, sourceStart?: number, sourceEnd?: number): number; + slice(start?: number, end?: number): Buffer; + writeUIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeUIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + readUIntLE(offset: number, byteLength: number, noAssert?: boolean): number; + readUIntBE(offset: number, byteLength: number, noAssert?: boolean): number; + readIntLE(offset: number, byteLength: number, noAssert?: boolean): number; + readIntBE(offset: number, byteLength: number, noAssert?: boolean): number; + readUInt8(offset: number, noAssert?: boolean): number; + readUInt16LE(offset: number, noAssert?: boolean): number; + readUInt16BE(offset: number, noAssert?: boolean): number; + readUInt32LE(offset: number, noAssert?: boolean): number; + readUInt32BE(offset: number, noAssert?: boolean): number; + readInt8(offset: number, noAssert?: boolean): number; + readInt16LE(offset: number, noAssert?: boolean): number; + readInt16BE(offset: number, noAssert?: boolean): number; + readInt32LE(offset: number, noAssert?: boolean): number; + readInt32BE(offset: number, noAssert?: boolean): number; + readFloatLE(offset: number, noAssert?: boolean): number; + readFloatBE(offset: number, noAssert?: boolean): number; + readDoubleLE(offset: number, noAssert?: boolean): number; + readDoubleBE(offset: number, noAssert?: boolean): number; + swap16(): Buffer; + swap32(): Buffer; + swap64(): Buffer; + writeUInt8(value: number, offset: number, noAssert?: boolean): number; + writeUInt16LE(value: number, offset: number, noAssert?: boolean): number; + writeUInt16BE(value: number, offset: number, noAssert?: boolean): number; + writeUInt32LE(value: number, offset: number, noAssert?: boolean): number; + writeUInt32BE(value: number, offset: number, noAssert?: boolean): number; + writeInt8(value: number, offset: number, noAssert?: boolean): number; + writeInt16LE(value: number, offset: number, noAssert?: boolean): number; + writeInt16BE(value: number, offset: number, noAssert?: boolean): number; + writeInt32LE(value: number, offset: number, noAssert?: boolean): number; + writeInt32BE(value: number, offset: number, noAssert?: boolean): number; + writeFloatLE(value: number, offset: number, noAssert?: boolean): number; + writeFloatBE(value: number, offset: number, noAssert?: boolean): number; + writeDoubleLE(value: number, offset: number, noAssert?: boolean): number; + writeDoubleBE(value: number, offset: number, noAssert?: boolean): number; + fill(value: any, offset?: number, end?: number): this; + indexOf(value: string | number | Uint8Array, byteOffset?: number, encoding?: string): number; + lastIndexOf(value: string | number | Uint8Array, byteOffset?: number, encoding?: string): number; + entries(): IterableIterator<[number, number]>; + includes(value: string | number | Buffer, byteOffset?: number, encoding?: string): boolean; + keys(): IterableIterator; + values(): IterableIterator; +} + +/** + * Raw data is stored in instances of the Buffer class. + * A Buffer is similar to an array of integers but corresponds to a raw memory allocation outside the V8 heap. A Buffer cannot be resized. + * Valid string encodings: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'binary'(deprecated)|'hex' + */ +declare const Buffer: { + /** + * Allocates a new buffer containing the given {str}. + * + * @param str String to store in buffer. + * @param encoding encoding to use, optional. Default is 'utf8' + * @deprecated since v10.0.0 - Use `Buffer.from(string[, encoding])` instead. + */ + new(str: string, encoding?: string): Buffer; + /** + * Allocates a new buffer of {size} octets. + * + * @param size count of octets to allocate. + * @deprecated since v10.0.0 - Use `Buffer.alloc()` instead (also see `Buffer.allocUnsafe()`). + */ + new(size: number): Buffer; + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + * @deprecated since v10.0.0 - Use `Buffer.from(array)` instead. + */ + new(array: Uint8Array): Buffer; + /** + * Produces a Buffer backed by the same allocated memory as + * the given {ArrayBuffer}/{SharedArrayBuffer}. + * + * + * @param arrayBuffer The ArrayBuffer with which to share memory. + * @deprecated since v10.0.0 - Use `Buffer.from(arrayBuffer[, byteOffset[, length]])` instead. + */ + new(arrayBuffer: ArrayBuffer | SharedArrayBuffer): Buffer; + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + * @deprecated since v10.0.0 - Use `Buffer.from(array)` instead. + */ + new(array: any[]): Buffer; + /** + * Copies the passed {buffer} data onto a new {Buffer} instance. + * + * @param buffer The buffer to copy. + * @deprecated since v10.0.0 - Use `Buffer.from(buffer)` instead. + */ + new(buffer: Buffer): Buffer; + prototype: Buffer; + /** + * When passed a reference to the .buffer property of a TypedArray instance, + * the newly created Buffer will share the same allocated memory as the TypedArray. + * The optional {byteOffset} and {length} arguments specify a memory range + * within the {arrayBuffer} that will be shared by the Buffer. + * + * @param arrayBuffer The .buffer property of any TypedArray or a new ArrayBuffer() + */ + from(arrayBuffer: ArrayBuffer | SharedArrayBuffer, byteOffset?: number, length?: number): Buffer; + /** + * Creates a new Buffer using the passed {data} + * @param data data to create a new Buffer + */ + from(data: any[]): Buffer; + from(data: Uint8Array): Buffer; + /** + * Creates a new Buffer containing the given JavaScript string {str}. + * If provided, the {encoding} parameter identifies the character encoding. + * If not provided, {encoding} defaults to 'utf8'. + */ + from(str: string, encoding?: string): Buffer; + /** + * Creates a new Buffer using the passed {data} + * @param values to create a new Buffer + */ + of(...items: number[]): Buffer; + /** + * Returns true if {obj} is a Buffer + * + * @param obj object to test. + */ + isBuffer(obj: any): obj is Buffer; + /** + * Returns true if {encoding} is a valid encoding argument. + * Valid string encodings in Node 0.12: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'binary'(deprecated)|'hex' + * + * @param encoding string to test. + */ + isEncoding(encoding: string): boolean | undefined; + /** + * Gives the actual byte length of a string. encoding defaults to 'utf8'. + * This is not the same as String.prototype.length since that returns the number of characters in a string. + * + * @param string string to test. + * @param encoding encoding used to evaluate (defaults to 'utf8') + */ + byteLength(string: string | NodeJS.TypedArray | DataView | ArrayBuffer | SharedArrayBuffer, encoding?: string): number; + /** + * Returns a buffer which is the result of concatenating all the buffers in the list together. + * + * If the list has no items, or if the totalLength is 0, then it returns a zero-length buffer. + * If the list has exactly one item, then the first item of the list is returned. + * If the list has more than one item, then a new Buffer is created. + * + * @param list An array of Buffer objects to concatenate + * @param totalLength Total length of the buffers when concatenated. + * If totalLength is not provided, it is read from the buffers in the list. However, this adds an additional loop to the function, so it is faster to provide the length explicitly. + */ + concat(list: Uint8Array[], totalLength?: number): Buffer; + /** + * The same as buf1.compare(buf2). + */ + compare(buf1: Uint8Array, buf2: Uint8Array): number; + /** + * Allocates a new buffer of {size} octets. + * + * @param size count of octets to allocate. + * @param fill if specified, buffer will be initialized by calling buf.fill(fill). + * If parameter is omitted, buffer will be filled with zeros. + * @param encoding encoding used for call to buf.fill while initalizing + */ + alloc(size: number, fill?: string | Buffer | number, encoding?: string): Buffer; + /** + * Allocates a new buffer of {size} octets, leaving memory not initialized, so the contents + * of the newly created Buffer are unknown and may contain sensitive data. + * + * @param size count of octets to allocate + */ + allocUnsafe(size: number): Buffer; + /** + * Allocates a new non-pooled buffer of {size} octets, leaving memory not initialized, so the contents + * of the newly created Buffer are unknown and may contain sensitive data. + * + * @param size count of octets to allocate + */ + allocUnsafeSlow(size: number): Buffer; + /** + * This is the number of bytes used to determine the size of pre-allocated, internal Buffer instances used for pooling. This value may be modified. + */ + poolSize: number; +}; + +/*----------------------------------------------* +* * +* GLOBAL INTERFACES * +* * +*-----------------------------------------------*/ +declare namespace NodeJS { + interface InspectOptions { + showHidden?: boolean; + depth?: number | null; + colors?: boolean; + customInspect?: boolean; + showProxy?: boolean; + maxArrayLength?: number | null; + breakLength?: number; + compact?: boolean; + sorted?: boolean | ((a: string, b: string) => number); + } + + interface ConsoleConstructorOptions { + stdout: WritableStream; + stderr?: WritableStream; + ignoreErrors?: boolean; + colorMode?: boolean | 'auto'; + } + + interface ConsoleConstructor { + prototype: Console; + new(stdout: WritableStream, stderr?: WritableStream, ignoreErrors?: boolean): Console; + new(options: ConsoleConstructorOptions): Console; + } + + interface CallSite { + /** + * Value of "this" + */ + getThis(): any; + + /** + * Type of "this" as a string. + * This is the name of the function stored in the constructor field of + * "this", if available. Otherwise the object's [[Class]] internal + * property. + */ + getTypeName(): string | null; + + /** + * Current function + */ + getFunction(): Function | undefined; + + /** + * Name of the current function, typically its name property. + * If a name property is not available an attempt will be made to try + * to infer a name from the function's context. + */ + getFunctionName(): string | null; + + /** + * Name of the property [of "this" or one of its prototypes] that holds + * the current function + */ + getMethodName(): string | null; + + /** + * Name of the script [if this function was defined in a script] + */ + getFileName(): string | null; + + /** + * Current line number [if this function was defined in a script] + */ + getLineNumber(): number | null; + + /** + * Current column number [if this function was defined in a script] + */ + getColumnNumber(): number | null; + + /** + * A call site object representing the location where eval was called + * [if this function was created using a call to eval] + */ + getEvalOrigin(): string | undefined; + + /** + * Is this a toplevel invocation, that is, is "this" the global object? + */ + isToplevel(): boolean; + + /** + * Does this call take place in code defined by a call to eval? + */ + isEval(): boolean; + + /** + * Is this call in native V8 code? + */ + isNative(): boolean; + + /** + * Is this a constructor call? + */ + isConstructor(): boolean; + } + + interface ErrnoException extends Error { + errno?: number; + code?: string; + path?: string; + syscall?: string; + stack?: string; + } + + class EventEmitter { + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + removeListener(event: string | symbol, listener: (...args: any[]) => void): this; + off(event: string | symbol, listener: (...args: any[]) => void): this; + removeAllListeners(event?: string | symbol): this; + setMaxListeners(n: number): this; + getMaxListeners(): number; + listeners(event: string | symbol): Function[]; + rawListeners(event: string | symbol): Function[]; + emit(event: string | symbol, ...args: any[]): boolean; + listenerCount(type: string | symbol): number; + // Added in Node 6... + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + eventNames(): Array; + } + + interface ReadableStream extends EventEmitter { + readable: boolean; + read(size?: number): string | Buffer; + setEncoding(encoding: string): this; + pause(): this; + resume(): this; + isPaused(): boolean; + pipe(destination: T, options?: { end?: boolean; }): T; + unpipe(destination?: WritableStream): this; + unshift(chunk: string): void; + unshift(chunk: Buffer): void; + wrap(oldStream: ReadableStream): this; + [Symbol.asyncIterator](): AsyncIterableIterator; + } + + interface WritableStream extends EventEmitter { + writable: boolean; + write(buffer: Buffer | string, cb?: Function): boolean; + write(str: string, encoding?: string, cb?: Function): boolean; + end(cb?: Function): void; + end(buffer: Buffer, cb?: Function): void; + end(str: string, cb?: Function): void; + end(str: string, encoding?: string, cb?: Function): void; + } + + interface ReadWriteStream extends ReadableStream, WritableStream { } + + interface Events extends EventEmitter { } + + interface Domain extends Events { + run(fn: Function): void; + add(emitter: Events): void; + remove(emitter: Events): void; + bind(cb: (err: Error, data: any) => any): any; + intercept(cb: (data: any) => any): any; + + addListener(event: string, listener: (...args: any[]) => void): this; + on(event: string, listener: (...args: any[]) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + removeListener(event: string, listener: (...args: any[]) => void): this; + removeAllListeners(event?: string): this; + } + + interface MemoryUsage { + rss: number; + heapTotal: number; + heapUsed: number; + external: number; + } + + interface CpuUsage { + user: number; + system: number; + } + + interface ProcessRelease { + name: string; + sourceUrl?: string; + headersUrl?: string; + libUrl?: string; + lts?: string; + } + + interface ProcessVersions { + http_parser: string; + node: string; + v8: string; + ares: string; + uv: string; + zlib: string; + modules: string; + openssl: string; + } + + type Platform = 'aix' + | 'android' + | 'darwin' + | 'freebsd' + | 'linux' + | 'openbsd' + | 'sunos' + | 'win32' + | 'cygwin'; + + type Signals = + "SIGABRT" | "SIGALRM" | "SIGBUS" | "SIGCHLD" | "SIGCONT" | "SIGFPE" | "SIGHUP" | "SIGILL" | "SIGINT" | "SIGIO" | + "SIGIOT" | "SIGKILL" | "SIGPIPE" | "SIGPOLL" | "SIGPROF" | "SIGPWR" | "SIGQUIT" | "SIGSEGV" | "SIGSTKFLT" | + "SIGSTOP" | "SIGSYS" | "SIGTERM" | "SIGTRAP" | "SIGTSTP" | "SIGTTIN" | "SIGTTOU" | "SIGUNUSED" | "SIGURG" | + "SIGUSR1" | "SIGUSR2" | "SIGVTALRM" | "SIGWINCH" | "SIGXCPU" | "SIGXFSZ" | "SIGBREAK" | "SIGLOST" | "SIGINFO"; + + type MultipleResolveType = 'resolve' | 'reject'; + + type BeforeExitListener = (code: number) => void; + type DisconnectListener = () => void; + type ExitListener = (code: number) => void; + type RejectionHandledListener = (promise: Promise) => void; + type UncaughtExceptionListener = (error: Error) => void; + type UnhandledRejectionListener = (reason: any, promise: Promise) => void; + type WarningListener = (warning: Error) => void; + type MessageListener = (message: any, sendHandle: any) => void; + type SignalsListener = (signal: Signals) => void; + type NewListenerListener = (type: string | symbol, listener: (...args: any[]) => void) => void; + type RemoveListenerListener = (type: string | symbol, listener: (...args: any[]) => void) => void; + type MultipleResolveListener = (type: MultipleResolveType, promise: Promise, value: any) => void; + + interface Socket extends ReadWriteStream { + isTTY?: true; + } + + interface ProcessEnv { + [key: string]: string | undefined; + } + + interface WriteStream extends Socket { + readonly writableHighWaterMark: number; + readonly writableLength: number; + columns?: number; + rows?: number; + _write(chunk: any, encoding: string, callback: Function): void; + _destroy(err: Error | null, callback: Function): void; + _final(callback: Function): void; + setDefaultEncoding(encoding: string): this; + cork(): void; + uncork(): void; + destroy(error?: Error): void; + } + interface ReadStream extends Socket { + readonly readableHighWaterMark: number; + readonly readableLength: number; + isRaw?: boolean; + setRawMode?(mode: boolean): void; + _read(size: number): void; + _destroy(err: Error | null, callback: Function): void; + push(chunk: any, encoding?: string): boolean; + destroy(error?: Error): void; + } + + interface Process extends EventEmitter { + stdout: WriteStream; + stderr: WriteStream; + stdin: ReadStream; + openStdin(): Socket; + argv: string[]; + argv0: string; + execArgv: string[]; + execPath: string; + abort(): void; + chdir(directory: string): void; + cwd(): string; + debugPort: number; + emitWarning(warning: string | Error, name?: string, ctor?: Function): void; + env: ProcessEnv; + exit(code?: number): never; + exitCode: number; + getgid(): number; + setgid(id: number | string): void; + getuid(): number; + setuid(id: number | string): void; + geteuid(): number; + seteuid(id: number | string): void; + getegid(): number; + setegid(id: number | string): void; + getgroups(): number[]; + setgroups(groups: Array): void; + setUncaughtExceptionCaptureCallback(cb: ((err: Error) => void) | null): void; + hasUncaughtExceptionCaptureCallback(): boolean; + version: string; + versions: ProcessVersions; + config: { + target_defaults: { + cflags: any[]; + default_configuration: string; + defines: string[]; + include_dirs: string[]; + libraries: string[]; + }; + variables: { + clang: number; + host_arch: string; + node_install_npm: boolean; + node_install_waf: boolean; + node_prefix: string; + node_shared_openssl: boolean; + node_shared_v8: boolean; + node_shared_zlib: boolean; + node_use_dtrace: boolean; + node_use_etw: boolean; + node_use_openssl: boolean; + target_arch: string; + v8_no_strict_aliasing: number; + v8_use_snapshot: boolean; + visibility: string; + }; + }; + kill(pid: number, signal?: string | number): void; + pid: number; + ppid: number; + title: string; + arch: string; + platform: Platform; + mainModule?: NodeModule; + memoryUsage(): MemoryUsage; + cpuUsage(previousValue?: CpuUsage): CpuUsage; + nextTick(callback: Function, ...args: any[]): void; + release: ProcessRelease; + umask(mask?: number): number; + uptime(): number; + hrtime(time?: [number, number]): [number, number]; + domain: Domain; + + // Worker + send?(message: any, sendHandle?: any): void; + disconnect(): void; + connected: boolean; + + /** + * The `process.allowedNodeEnvironmentFlags` property is a special, + * read-only `Set` of flags allowable within the [`NODE_OPTIONS`][] + * environment variable. + */ + allowedNodeEnvironmentFlags: ReadonlySet; + + /** + * EventEmitter + * 1. beforeExit + * 2. disconnect + * 3. exit + * 4. message + * 5. rejectionHandled + * 6. uncaughtException + * 7. unhandledRejection + * 8. warning + * 9. message + * 10. + * 11. newListener/removeListener inherited from EventEmitter + */ + addListener(event: "beforeExit", listener: BeforeExitListener): this; + addListener(event: "disconnect", listener: DisconnectListener): this; + addListener(event: "exit", listener: ExitListener): this; + addListener(event: "rejectionHandled", listener: RejectionHandledListener): this; + addListener(event: "uncaughtException", listener: UncaughtExceptionListener): this; + addListener(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + addListener(event: "warning", listener: WarningListener): this; + addListener(event: "message", listener: MessageListener): this; + addListener(event: Signals, listener: SignalsListener): this; + addListener(event: "newListener", listener: NewListenerListener): this; + addListener(event: "removeListener", listener: RemoveListenerListener): this; + addListener(event: "multipleResolves", listener: MultipleResolveListener): this; + + emit(event: "beforeExit", code: number): boolean; + emit(event: "disconnect"): boolean; + emit(event: "exit", code: number): boolean; + emit(event: "rejectionHandled", promise: Promise): boolean; + emit(event: "uncaughtException", error: Error): boolean; + emit(event: "unhandledRejection", reason: any, promise: Promise): boolean; + emit(event: "warning", warning: Error): boolean; + emit(event: "message", message: any, sendHandle: any): this; + emit(event: Signals, signal: Signals): boolean; + emit(event: "newListener", eventName: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "removeListener", eventName: string, listener: (...args: any[]) => void): this; + emit(event: "multipleResolves", listener: MultipleResolveListener): this; + + on(event: "beforeExit", listener: BeforeExitListener): this; + on(event: "disconnect", listener: DisconnectListener): this; + on(event: "exit", listener: ExitListener): this; + on(event: "rejectionHandled", listener: RejectionHandledListener): this; + on(event: "uncaughtException", listener: UncaughtExceptionListener): this; + on(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + on(event: "warning", listener: WarningListener): this; + on(event: "message", listener: MessageListener): this; + on(event: Signals, listener: SignalsListener): this; + on(event: "newListener", listener: NewListenerListener): this; + on(event: "removeListener", listener: RemoveListenerListener): this; + on(event: "multipleResolves", listener: MultipleResolveListener): this; + + once(event: "beforeExit", listener: BeforeExitListener): this; + once(event: "disconnect", listener: DisconnectListener): this; + once(event: "exit", listener: ExitListener): this; + once(event: "rejectionHandled", listener: RejectionHandledListener): this; + once(event: "uncaughtException", listener: UncaughtExceptionListener): this; + once(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + once(event: "warning", listener: WarningListener): this; + once(event: "message", listener: MessageListener): this; + once(event: Signals, listener: SignalsListener): this; + once(event: "newListener", listener: NewListenerListener): this; + once(event: "removeListener", listener: RemoveListenerListener): this; + once(event: "multipleResolves", listener: MultipleResolveListener): this; + + prependListener(event: "beforeExit", listener: BeforeExitListener): this; + prependListener(event: "disconnect", listener: DisconnectListener): this; + prependListener(event: "exit", listener: ExitListener): this; + prependListener(event: "rejectionHandled", listener: RejectionHandledListener): this; + prependListener(event: "uncaughtException", listener: UncaughtExceptionListener): this; + prependListener(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + prependListener(event: "warning", listener: WarningListener): this; + prependListener(event: "message", listener: MessageListener): this; + prependListener(event: Signals, listener: SignalsListener): this; + prependListener(event: "newListener", listener: NewListenerListener): this; + prependListener(event: "removeListener", listener: RemoveListenerListener): this; + prependListener(event: "multipleResolves", listener: MultipleResolveListener): this; + + prependOnceListener(event: "beforeExit", listener: BeforeExitListener): this; + prependOnceListener(event: "disconnect", listener: DisconnectListener): this; + prependOnceListener(event: "exit", listener: ExitListener): this; + prependOnceListener(event: "rejectionHandled", listener: RejectionHandledListener): this; + prependOnceListener(event: "uncaughtException", listener: UncaughtExceptionListener): this; + prependOnceListener(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + prependOnceListener(event: "warning", listener: WarningListener): this; + prependOnceListener(event: "message", listener: MessageListener): this; + prependOnceListener(event: Signals, listener: SignalsListener): this; + prependOnceListener(event: "newListener", listener: NewListenerListener): this; + prependOnceListener(event: "removeListener", listener: RemoveListenerListener): this; + prependOnceListener(event: "multipleResolves", listener: MultipleResolveListener): this; + + listeners(event: "beforeExit"): BeforeExitListener[]; + listeners(event: "disconnect"): DisconnectListener[]; + listeners(event: "exit"): ExitListener[]; + listeners(event: "rejectionHandled"): RejectionHandledListener[]; + listeners(event: "uncaughtException"): UncaughtExceptionListener[]; + listeners(event: "unhandledRejection"): UnhandledRejectionListener[]; + listeners(event: "warning"): WarningListener[]; + listeners(event: "message"): MessageListener[]; + listeners(event: Signals): SignalsListener[]; + listeners(event: "newListener"): NewListenerListener[]; + listeners(event: "removeListener"): RemoveListenerListener[]; + listeners(event: "multipleResolves"): MultipleResolveListener[]; + } + + interface Global { + Array: typeof Array; + ArrayBuffer: typeof ArrayBuffer; + Boolean: typeof Boolean; + Buffer: typeof Buffer; + DataView: typeof DataView; + Date: typeof Date; + Error: typeof Error; + EvalError: typeof EvalError; + Float32Array: typeof Float32Array; + Float64Array: typeof Float64Array; + Function: typeof Function; + GLOBAL: Global; + Infinity: typeof Infinity; + Int16Array: typeof Int16Array; + Int32Array: typeof Int32Array; + Int8Array: typeof Int8Array; + Intl: typeof Intl; + JSON: typeof JSON; + Map: MapConstructor; + Math: typeof Math; + NaN: typeof NaN; + Number: typeof Number; + Object: typeof Object; + Promise: Function; + RangeError: typeof RangeError; + ReferenceError: typeof ReferenceError; + RegExp: typeof RegExp; + Set: SetConstructor; + String: typeof String; + Symbol: Function; + SyntaxError: typeof SyntaxError; + TypeError: typeof TypeError; + URIError: typeof URIError; + Uint16Array: typeof Uint16Array; + Uint32Array: typeof Uint32Array; + Uint8Array: typeof Uint8Array; + Uint8ClampedArray: Function; + WeakMap: WeakMapConstructor; + WeakSet: WeakSetConstructor; + clearImmediate: (immediateId: Immediate) => void; + clearInterval: (intervalId: Timeout) => void; + clearTimeout: (timeoutId: Timeout) => void; + console: typeof console; + decodeURI: typeof decodeURI; + decodeURIComponent: typeof decodeURIComponent; + encodeURI: typeof encodeURI; + encodeURIComponent: typeof encodeURIComponent; + escape: (str: string) => string; + eval: typeof eval; + global: Global; + isFinite: typeof isFinite; + isNaN: typeof isNaN; + parseFloat: typeof parseFloat; + parseInt: typeof parseInt; + process: Process; + root: Global; + setImmediate: (callback: (...args: any[]) => void, ...args: any[]) => Immediate; + setInterval: (callback: (...args: any[]) => void, ms: number, ...args: any[]) => Timeout; + setTimeout: (callback: (...args: any[]) => void, ms: number, ...args: any[]) => Timeout; + undefined: typeof undefined; + unescape: (str: string) => string; + gc: () => void; + v8debug?: any; + } + + interface Timer { + ref(): void; + refresh(): void; + unref(): void; + } + + class Immediate { + ref(): void; + unref(): void; + _onImmediate: Function; // to distinguish it from the Timeout class + } + + class Timeout implements Timer { + ref(): void; + refresh(): void; + unref(): void; + } + + class Module { + static runMain(): void; + static wrap(code: string): string; + static createRequireFromPath(path: string): (path: string) => any; + static builtinModules: string[]; + + static Module: typeof Module; + + exports: any; + require: NodeRequireFunction; + id: string; + filename: string; + loaded: boolean; + parent: Module | null; + children: Module[]; + paths: string[]; + + constructor(id: string, parent?: Module); + } + + type TypedArray = Uint8Array | Uint8ClampedArray | Uint16Array | Uint32Array | Int8Array | Int16Array | Int32Array | Float32Array | Float64Array; +} + +interface IterableIterator { } + +/*----------------------------------------------* +* * +* MODULES * +* * +*-----------------------------------------------*/ +declare module "buffer" { + export const INSPECT_MAX_BYTES: number; + const BuffType: typeof Buffer; + const SlowBuffType: typeof SlowBuffer; + export { BuffType as Buffer, SlowBuffType as SlowBuffer }; +} + +declare module "querystring" { + interface StringifyOptions { + encodeURIComponent?: Function; + } + + interface ParseOptions { + maxKeys?: number; + decodeURIComponent?: Function; + } + + interface ParsedUrlQuery { [key: string]: string | string[]; } + + function stringify(obj?: {}, sep?: string, eq?: string, options?: StringifyOptions): string; + function parse(str: string, sep?: string, eq?: string, options?: ParseOptions): ParsedUrlQuery; + function escape(str: string): string; + function unescape(str: string): string; +} + +declare module "events" { + class internal extends NodeJS.EventEmitter { } + + namespace internal { + class EventEmitter extends internal { + /** @deprecated since v4.0.0 */ + static listenerCount(emitter: EventEmitter, event: string | symbol): number; + static defaultMaxListeners: number; + + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + removeListener(event: string | symbol, listener: (...args: any[]) => void): this; + off(event: string | symbol, listener: (...args: any[]) => void): this; + removeAllListeners(event?: string | symbol): this; + setMaxListeners(n: number): this; + getMaxListeners(): number; + listeners(event: string | symbol): Function[]; + rawListeners(event: string | symbol): Function[]; + emit(event: string | symbol, ...args: any[]): boolean; + eventNames(): Array; + listenerCount(type: string | symbol): number; + } + } + + export = internal; +} + +declare module "http" { + import * as events from "events"; + import * as net from "net"; + import * as stream from "stream"; + import { URL } from "url"; + + // incoming headers will never contain number + interface IncomingHttpHeaders { + 'accept'?: string; + 'access-control-allow-origin'?: string; + 'access-control-allow-credentials'?: string; + 'access-control-expose-headers'?: string; + 'access-control-max-age'?: string; + 'access-control-allow-methods'?: string; + 'access-control-allow-headers'?: string; + 'accept-patch'?: string; + 'accept-ranges'?: string; + 'age'?: string; + 'allow'?: string; + 'alt-svc'?: string; + 'authorization'?: string; + 'cache-control'?: string; + 'connection'?: string; + 'content-disposition'?: string; + 'content-encoding'?: string; + 'content-language'?: string; + 'content-length'?: string; + 'content-location'?: string; + 'content-range'?: string; + 'content-type'?: string; + 'cookie'?: string; + 'date'?: string; + 'expect'?: string; + 'expires'?: string; + 'forwarded'?: string; + 'from'?: string; + 'host'?: string; + 'if-match'?: string; + 'if-modified-since'?: string; + 'if-none-match'?: string; + 'if-unmodified-since'?: string; + 'last-modified'?: string; + 'location'?: string; + 'pragma'?: string; + 'proxy-authenticate'?: string; + 'proxy-authorization'?: string; + 'public-key-pins'?: string; + 'range'?: string; + 'referer'?: string; + 'retry-after'?: string; + 'set-cookie'?: string[]; + 'strict-transport-security'?: string; + 'trailer'?: string; + 'transfer-encoding'?: string; + 'tk'?: string; + 'upgrade'?: string; + 'user-agent'?: string; + 'vary'?: string; + 'via'?: string; + 'warning'?: string; + 'www-authenticate'?: string; + [header: string]: string | string[] | undefined; + } + + // outgoing headers allows numbers (as they are converted internally to strings) + interface OutgoingHttpHeaders { + [header: string]: number | string | string[] | undefined; + } + + interface ClientRequestArgs { + protocol?: string; + host?: string; + hostname?: string; + family?: number; + port?: number | string; + defaultPort?: number | string; + localAddress?: string; + socketPath?: string; + method?: string; + path?: string; + headers?: OutgoingHttpHeaders; + auth?: string; + agent?: Agent | boolean; + _defaultAgent?: Agent; + timeout?: number; + setHost?: boolean; + // https://github.com/nodejs/node/blob/master/lib/_http_client.js#L278 + createConnection?: (options: ClientRequestArgs, oncreate: (err: Error, socket: net.Socket) => void) => net.Socket; + } + + class Server extends net.Server { + constructor(requestListener?: (req: IncomingMessage, res: ServerResponse) => void); + + setTimeout(msecs?: number, callback?: () => void): this; + setTimeout(callback: () => void): this; + maxHeadersCount: number; + timeout: number; + keepAliveTimeout: number; + } + + // https://github.com/nodejs/node/blob/master/lib/_http_outgoing.js + class OutgoingMessage extends stream.Writable { + upgrading: boolean; + chunkedEncoding: boolean; + shouldKeepAlive: boolean; + useChunkedEncodingByDefault: boolean; + sendDate: boolean; + finished: boolean; + headersSent: boolean; + connection: net.Socket; + + constructor(); + + setTimeout(msecs: number, callback?: () => void): this; + setHeader(name: string, value: number | string | string[]): void; + getHeader(name: string): number | string | string[] | undefined; + getHeaders(): OutgoingHttpHeaders; + getHeaderNames(): string[]; + hasHeader(name: string): boolean; + removeHeader(name: string): void; + addTrailers(headers: OutgoingHttpHeaders | Array<[string, string]>): void; + flushHeaders(): void; + } + + // https://github.com/nodejs/node/blob/master/lib/_http_server.js#L108-L256 + class ServerResponse extends OutgoingMessage { + statusCode: number; + statusMessage: string; + + constructor(req: IncomingMessage); + + assignSocket(socket: net.Socket): void; + detachSocket(socket: net.Socket): void; + // https://github.com/nodejs/node/blob/master/test/parallel/test-http-write-callbacks.js#L53 + // no args in writeContinue callback + writeContinue(callback?: () => void): void; + writeHead(statusCode: number, reasonPhrase?: string, headers?: OutgoingHttpHeaders): void; + writeHead(statusCode: number, headers?: OutgoingHttpHeaders): void; + } + + // https://github.com/nodejs/node/blob/master/lib/_http_client.js#L77 + class ClientRequest extends OutgoingMessage { + connection: net.Socket; + socket: net.Socket; + aborted: number; + + constructor(url: string | URL | ClientRequestArgs, cb?: (res: IncomingMessage) => void); + + abort(): void; + onSocket(socket: net.Socket): void; + setTimeout(timeout: number, callback?: () => void): this; + setNoDelay(noDelay?: boolean): void; + setSocketKeepAlive(enable?: boolean, initialDelay?: number): void; + } + + class IncomingMessage extends stream.Readable { + constructor(socket: net.Socket); + + httpVersion: string; + httpVersionMajor: number; + httpVersionMinor: number; + connection: net.Socket; + headers: IncomingHttpHeaders; + rawHeaders: string[]; + trailers: { [key: string]: string | undefined }; + rawTrailers: string[]; + setTimeout(msecs: number, callback: () => void): this; + /** + * Only valid for request obtained from http.Server. + */ + method?: string; + /** + * Only valid for request obtained from http.Server. + */ + url?: string; + /** + * Only valid for response obtained from http.ClientRequest. + */ + statusCode?: number; + /** + * Only valid for response obtained from http.ClientRequest. + */ + statusMessage?: string; + socket: net.Socket; + destroy(error?: Error): void; + } + + interface AgentOptions { + /** + * Keep sockets around in a pool to be used by other requests in the future. Default = false + */ + keepAlive?: boolean; + /** + * When using HTTP KeepAlive, how often to send TCP KeepAlive packets over sockets being kept alive. Default = 1000. + * Only relevant if keepAlive is set to true. + */ + keepAliveMsecs?: number; + /** + * Maximum number of sockets to allow per host. Default for Node 0.10 is 5, default for Node 0.12 is Infinity + */ + maxSockets?: number; + /** + * Maximum number of sockets to leave open in a free state. Only relevant if keepAlive is set to true. Default = 256. + */ + maxFreeSockets?: number; + /** + * Socket timeout in milliseconds. This will set the timeout after the socket is connected. + */ + timeout?: number; + } + + class Agent { + maxFreeSockets: number; + maxSockets: number; + sockets: any; + requests: any; + + constructor(opts?: AgentOptions); + + /** + * Destroy any sockets that are currently in use by the agent. + * It is usually not necessary to do this. However, if you are using an agent with KeepAlive enabled, + * then it is best to explicitly shut down the agent when you know that it will no longer be used. Otherwise, + * sockets may hang open for quite a long time before the server terminates them. + */ + destroy(): void; + } + + const METHODS: string[]; + + const STATUS_CODES: { + [errorCode: number]: string | undefined; + [errorCode: string]: string | undefined; + }; + + function createServer(requestListener?: (request: IncomingMessage, response: ServerResponse) => void): Server; + function createClient(port?: number, host?: string): any; + + // although RequestOptions are passed as ClientRequestArgs to ClientRequest directly, + // create interface RequestOptions would make the naming more clear to developers + interface RequestOptions extends ClientRequestArgs { } + function request(options: RequestOptions | string | URL, callback?: (res: IncomingMessage) => void): ClientRequest; + function request(url: string | URL, options: RequestOptions, callback?: (res: IncomingMessage) => void): ClientRequest; + function get(options: RequestOptions | string | URL, callback?: (res: IncomingMessage) => void): ClientRequest; + function get(url: string | URL, options: RequestOptions, callback?: (res: IncomingMessage) => void): ClientRequest; + let globalAgent: Agent; +} + +declare module "cluster" { + import * as child from "child_process"; + import * as events from "events"; + import * as net from "net"; + + // interfaces + interface ClusterSettings { + execArgv?: string[]; // default: process.execArgv + exec?: string; + args?: string[]; + silent?: boolean; + stdio?: any[]; + uid?: number; + gid?: number; + inspectPort?: number | (() => number); + } + + interface Address { + address: string; + port: number; + addressType: number | "udp4" | "udp6"; // 4, 6, -1, "udp4", "udp6" + } + + class Worker extends events.EventEmitter { + id: number; + process: child.ChildProcess; + suicide: boolean; + send(message: any, sendHandle?: any, callback?: (error: Error) => void): boolean; + kill(signal?: string): void; + destroy(signal?: string): void; + disconnect(): void; + isConnected(): boolean; + isDead(): boolean; + exitedAfterDisconnect: boolean; + + /** + * events.EventEmitter + * 1. disconnect + * 2. error + * 3. exit + * 4. listening + * 5. message + * 6. online + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "disconnect", listener: () => void): this; + addListener(event: "error", listener: (error: Error) => void): this; + addListener(event: "exit", listener: (code: number, signal: string) => void): this; + addListener(event: "listening", listener: (address: Address) => void): this; + addListener(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + addListener(event: "online", listener: () => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "disconnect"): boolean; + emit(event: "error", error: Error): boolean; + emit(event: "exit", code: number, signal: string): boolean; + emit(event: "listening", address: Address): boolean; + emit(event: "message", message: any, handle: net.Socket | net.Server): boolean; + emit(event: "online"): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "disconnect", listener: () => void): this; + on(event: "error", listener: (error: Error) => void): this; + on(event: "exit", listener: (code: number, signal: string) => void): this; + on(event: "listening", listener: (address: Address) => void): this; + on(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + on(event: "online", listener: () => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "disconnect", listener: () => void): this; + once(event: "error", listener: (error: Error) => void): this; + once(event: "exit", listener: (code: number, signal: string) => void): this; + once(event: "listening", listener: (address: Address) => void): this; + once(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + once(event: "online", listener: () => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "disconnect", listener: () => void): this; + prependListener(event: "error", listener: (error: Error) => void): this; + prependListener(event: "exit", listener: (code: number, signal: string) => void): this; + prependListener(event: "listening", listener: (address: Address) => void): this; + prependListener(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + prependListener(event: "online", listener: () => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "disconnect", listener: () => void): this; + prependOnceListener(event: "error", listener: (error: Error) => void): this; + prependOnceListener(event: "exit", listener: (code: number, signal: string) => void): this; + prependOnceListener(event: "listening", listener: (address: Address) => void): this; + prependOnceListener(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + prependOnceListener(event: "online", listener: () => void): this; + } + + interface Cluster extends events.EventEmitter { + Worker: Worker; + disconnect(callback?: Function): void; + fork(env?: any): Worker; + isMaster: boolean; + isWorker: boolean; + // TODO: cluster.schedulingPolicy + settings: ClusterSettings; + setupMaster(settings?: ClusterSettings): void; + worker?: Worker; + workers?: { + [index: string]: Worker | undefined + }; + + /** + * events.EventEmitter + * 1. disconnect + * 2. exit + * 3. fork + * 4. listening + * 5. message + * 6. online + * 7. setup + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "disconnect", listener: (worker: Worker) => void): this; + addListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; + addListener(event: "fork", listener: (worker: Worker) => void): this; + addListener(event: "listening", listener: (worker: Worker, address: Address) => void): this; + addListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + addListener(event: "online", listener: (worker: Worker) => void): this; + addListener(event: "setup", listener: (settings: any) => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "disconnect", worker: Worker): boolean; + emit(event: "exit", worker: Worker, code: number, signal: string): boolean; + emit(event: "fork", worker: Worker): boolean; + emit(event: "listening", worker: Worker, address: Address): boolean; + emit(event: "message", worker: Worker, message: any, handle: net.Socket | net.Server): boolean; + emit(event: "online", worker: Worker): boolean; + emit(event: "setup", settings: any): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "disconnect", listener: (worker: Worker) => void): this; + on(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; + on(event: "fork", listener: (worker: Worker) => void): this; + on(event: "listening", listener: (worker: Worker, address: Address) => void): this; + on(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + on(event: "online", listener: (worker: Worker) => void): this; + on(event: "setup", listener: (settings: any) => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "disconnect", listener: (worker: Worker) => void): this; + once(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; + once(event: "fork", listener: (worker: Worker) => void): this; + once(event: "listening", listener: (worker: Worker, address: Address) => void): this; + once(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + once(event: "online", listener: (worker: Worker) => void): this; + once(event: "setup", listener: (settings: any) => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "disconnect", listener: (worker: Worker) => void): this; + prependListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; + prependListener(event: "fork", listener: (worker: Worker) => void): this; + prependListener(event: "listening", listener: (worker: Worker, address: Address) => void): this; + prependListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + prependListener(event: "online", listener: (worker: Worker) => void): this; + prependListener(event: "setup", listener: (settings: any) => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "disconnect", listener: (worker: Worker) => void): this; + prependOnceListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; + prependOnceListener(event: "fork", listener: (worker: Worker) => void): this; + prependOnceListener(event: "listening", listener: (worker: Worker, address: Address) => void): this; + // the handle is a net.Socket or net.Server object, or undefined. + prependOnceListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; + prependOnceListener(event: "online", listener: (worker: Worker) => void): this; + prependOnceListener(event: "setup", listener: (settings: any) => void): this; + } + + function disconnect(callback?: Function): void; + function fork(env?: any): Worker; + const isMaster: boolean; + const isWorker: boolean; + // TODO: cluster.schedulingPolicy + const settings: ClusterSettings; + function setupMaster(settings?: ClusterSettings): void; + const worker: Worker; + const workers: { + [index: string]: Worker | undefined + }; + + /** + * events.EventEmitter + * 1. disconnect + * 2. exit + * 3. fork + * 4. listening + * 5. message + * 6. online + * 7. setup + */ + function addListener(event: string, listener: (...args: any[]) => void): Cluster; + function addListener(event: "disconnect", listener: (worker: Worker) => void): Cluster; + function addListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster; + function addListener(event: "fork", listener: (worker: Worker) => void): Cluster; + function addListener(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster; + // the handle is a net.Socket or net.Server object, or undefined. + function addListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster; + function addListener(event: "online", listener: (worker: Worker) => void): Cluster; + function addListener(event: "setup", listener: (settings: any) => void): Cluster; + + function emit(event: string | symbol, ...args: any[]): boolean; + function emit(event: "disconnect", worker: Worker): boolean; + function emit(event: "exit", worker: Worker, code: number, signal: string): boolean; + function emit(event: "fork", worker: Worker): boolean; + function emit(event: "listening", worker: Worker, address: Address): boolean; + function emit(event: "message", worker: Worker, message: any, handle: net.Socket | net.Server): boolean; + function emit(event: "online", worker: Worker): boolean; + function emit(event: "setup", settings: any): boolean; + + function on(event: string, listener: (...args: any[]) => void): Cluster; + function on(event: "disconnect", listener: (worker: Worker) => void): Cluster; + function on(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster; + function on(event: "fork", listener: (worker: Worker) => void): Cluster; + function on(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster; + function on(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster; // the handle is a net.Socket or net.Server object, or undefined. + function on(event: "online", listener: (worker: Worker) => void): Cluster; + function on(event: "setup", listener: (settings: any) => void): Cluster; + + function once(event: string, listener: (...args: any[]) => void): Cluster; + function once(event: "disconnect", listener: (worker: Worker) => void): Cluster; + function once(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster; + function once(event: "fork", listener: (worker: Worker) => void): Cluster; + function once(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster; + function once(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster; // the handle is a net.Socket or net.Server object, or undefined. + function once(event: "online", listener: (worker: Worker) => void): Cluster; + function once(event: "setup", listener: (settings: any) => void): Cluster; + + function removeListener(event: string, listener: (...args: any[]) => void): Cluster; + function removeAllListeners(event?: string): Cluster; + function setMaxListeners(n: number): Cluster; + function getMaxListeners(): number; + function listeners(event: string): Function[]; + function listenerCount(type: string): number; + + function prependListener(event: string, listener: (...args: any[]) => void): Cluster; + function prependListener(event: "disconnect", listener: (worker: Worker) => void): Cluster; + function prependListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster; + function prependListener(event: "fork", listener: (worker: Worker) => void): Cluster; + function prependListener(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster; + // the handle is a net.Socket or net.Server object, or undefined. + function prependListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster; + function prependListener(event: "online", listener: (worker: Worker) => void): Cluster; + function prependListener(event: "setup", listener: (settings: any) => void): Cluster; + + function prependOnceListener(event: string, listener: (...args: any[]) => void): Cluster; + function prependOnceListener(event: "disconnect", listener: (worker: Worker) => void): Cluster; + function prependOnceListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster; + function prependOnceListener(event: "fork", listener: (worker: Worker) => void): Cluster; + function prependOnceListener(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster; + // the handle is a net.Socket or net.Server object, or undefined. + function prependOnceListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster; + function prependOnceListener(event: "online", listener: (worker: Worker) => void): Cluster; + function prependOnceListener(event: "setup", listener: (settings: any) => void): Cluster; + + function eventNames(): string[]; +} + +declare module "worker_threads" { + import { EventEmitter } from "events"; + import { Readable, Writable } from "stream"; + + const isMainThread: boolean; + const parentPort: null | MessagePort; + const threadId: number; + const workerData: any; + + class MessageChannel { + readonly port1: MessagePort; + readonly port2: MessagePort; + } + + class MessagePort extends EventEmitter { + close(): void; + postMessage(value: any, transferList?: Array): void; + ref(): void; + unref(): void; + start(): void; + + addListener(event: "close", listener: () => void): this; + addListener(event: "message", listener: (value: any) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + + emit(event: "close"): boolean; + emit(event: "message", value: any): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + + on(event: "close", listener: () => void): this; + on(event: "message", listener: (value: any) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + + once(event: "close", listener: () => void): this; + once(event: "message", listener: (value: any) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + + prependListener(event: "close", listener: () => void): this; + prependListener(event: "message", listener: (value: any) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "message", listener: (value: any) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + + removeListener(event: "close", listener: () => void): this; + removeListener(event: "message", listener: (value: any) => void): this; + removeListener(event: string | symbol, listener: (...args: any[]) => void): this; + + off(event: "close", listener: () => void): this; + off(event: "message", listener: (value: any) => void): this; + off(event: string | symbol, listener: (...args: any[]) => void): this; + } + + interface WorkerOptions { + eval?: boolean; + workerData?: any; + stdin?: boolean; + stdout?: boolean; + stderr?: boolean; + } + + class Worker extends EventEmitter { + readonly stdin: Writable | null; + readonly stdout: Readable; + readonly stderr: Readable; + readonly threadId: number; + + constructor(filename: string, options?: WorkerOptions); + + postMessage(value: any, transferList?: Array): void; + ref(): void; + unref(): void; + terminate(callback?: (err: any, exitCode: number) => void): void; + + addListener(event: "error", listener: (err: any) => void): this; + addListener(event: "exit", listener: (exitCode: number) => void): this; + addListener(event: "message", listener: (value: any) => void): this; + addListener(event: "online", listener: () => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + + emit(event: "error", err: any): boolean; + emit(event: "exit", exitCode: number): boolean; + emit(event: "message", value: any): boolean; + emit(event: "online"): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + + on(event: "error", listener: (err: any) => void): this; + on(event: "exit", listener: (exitCode: number) => void): this; + on(event: "message", listener: (value: any) => void): this; + on(event: "online", listener: () => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + + once(event: "error", listener: (err: any) => void): this; + once(event: "exit", listener: (exitCode: number) => void): this; + once(event: "message", listener: (value: any) => void): this; + once(event: "online", listener: () => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + + prependListener(event: "error", listener: (err: any) => void): this; + prependListener(event: "exit", listener: (exitCode: number) => void): this; + prependListener(event: "message", listener: (value: any) => void): this; + prependListener(event: "online", listener: () => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + + prependOnceListener(event: "error", listener: (err: any) => void): this; + prependOnceListener(event: "exit", listener: (exitCode: number) => void): this; + prependOnceListener(event: "message", listener: (value: any) => void): this; + prependOnceListener(event: "online", listener: () => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + + removeListener(event: "error", listener: (err: any) => void): this; + removeListener(event: "exit", listener: (exitCode: number) => void): this; + removeListener(event: "message", listener: (value: any) => void): this; + removeListener(event: "online", listener: () => void): this; + removeListener(event: string | symbol, listener: (...args: any[]) => void): this; + + off(event: "error", listener: (err: any) => void): this; + off(event: "exit", listener: (exitCode: number) => void): this; + off(event: "message", listener: (value: any) => void): this; + off(event: "online", listener: () => void): this; + off(event: string | symbol, listener: (...args: any[]) => void): this; + } +} + +declare module "zlib" { + import * as stream from "stream"; + + interface ZlibOptions { + flush?: number; // default: zlib.constants.Z_NO_FLUSH + finishFlush?: number; // default: zlib.constants.Z_FINISH + chunkSize?: number; // default: 16*1024 + windowBits?: number; + level?: number; // compression only + memLevel?: number; // compression only + strategy?: number; // compression only + dictionary?: Buffer | NodeJS.TypedArray | DataView | ArrayBuffer; // deflate/inflate only, empty dictionary by default + } + + interface Zlib { + readonly bytesRead: number; + close(callback?: () => void): void; + flush(kind?: number | (() => void), callback?: () => void): void; + } + + interface ZlibParams { + params(level: number, strategy: number, callback: () => void): void; + } + + interface ZlibReset { + reset(): void; + } + + interface Gzip extends stream.Transform, Zlib { } + interface Gunzip extends stream.Transform, Zlib { } + interface Deflate extends stream.Transform, Zlib, ZlibReset, ZlibParams { } + interface Inflate extends stream.Transform, Zlib, ZlibReset { } + interface DeflateRaw extends stream.Transform, Zlib, ZlibReset, ZlibParams { } + interface InflateRaw extends stream.Transform, Zlib, ZlibReset { } + interface Unzip extends stream.Transform, Zlib { } + + function createGzip(options?: ZlibOptions): Gzip; + function createGunzip(options?: ZlibOptions): Gunzip; + function createDeflate(options?: ZlibOptions): Deflate; + function createInflate(options?: ZlibOptions): Inflate; + function createDeflateRaw(options?: ZlibOptions): DeflateRaw; + function createInflateRaw(options?: ZlibOptions): InflateRaw; + function createUnzip(options?: ZlibOptions): Unzip; + + type InputType = string | Buffer | DataView | ArrayBuffer | NodeJS.TypedArray; + function deflate(buf: InputType, callback: (error: Error | null, result: Buffer) => void): void; + function deflate(buf: InputType, options: ZlibOptions, callback: (error: Error | null, result: Buffer) => void): void; + function deflateSync(buf: InputType, options?: ZlibOptions): Buffer; + function deflateRaw(buf: InputType, callback: (error: Error | null, result: Buffer) => void): void; + function deflateRaw(buf: InputType, options: ZlibOptions, callback: (error: Error | null, result: Buffer) => void): void; + function deflateRawSync(buf: InputType, options?: ZlibOptions): Buffer; + function gzip(buf: InputType, callback: (error: Error | null, result: Buffer) => void): void; + function gzip(buf: InputType, options: ZlibOptions, callback: (error: Error | null, result: Buffer) => void): void; + function gzipSync(buf: InputType, options?: ZlibOptions): Buffer; + function gunzip(buf: InputType, callback: (error: Error | null, result: Buffer) => void): void; + function gunzip(buf: InputType, options: ZlibOptions, callback: (error: Error | null, result: Buffer) => void): void; + function gunzipSync(buf: InputType, options?: ZlibOptions): Buffer; + function inflate(buf: InputType, callback: (error: Error | null, result: Buffer) => void): void; + function inflate(buf: InputType, options: ZlibOptions, callback: (error: Error | null, result: Buffer) => void): void; + function inflateSync(buf: InputType, options?: ZlibOptions): Buffer; + function inflateRaw(buf: InputType, callback: (error: Error | null, result: Buffer) => void): void; + function inflateRaw(buf: InputType, options: ZlibOptions, callback: (error: Error | null, result: Buffer) => void): void; + function inflateRawSync(buf: InputType, options?: ZlibOptions): Buffer; + function unzip(buf: InputType, callback: (error: Error | null, result: Buffer) => void): void; + function unzip(buf: InputType, options: ZlibOptions, callback: (error: Error | null, result: Buffer) => void): void; + function unzipSync(buf: InputType, options?: ZlibOptions): Buffer; + + namespace constants { + // Allowed flush values. + + const Z_NO_FLUSH: number; + const Z_PARTIAL_FLUSH: number; + const Z_SYNC_FLUSH: number; + const Z_FULL_FLUSH: number; + const Z_FINISH: number; + const Z_BLOCK: number; + const Z_TREES: number; + + // Return codes for the compression/decompression functions. Negative values are errors, positive values are used for special but normal events. + + const Z_OK: number; + const Z_STREAM_END: number; + const Z_NEED_DICT: number; + const Z_ERRNO: number; + const Z_STREAM_ERROR: number; + const Z_DATA_ERROR: number; + const Z_MEM_ERROR: number; + const Z_BUF_ERROR: number; + const Z_VERSION_ERROR: number; + + // Compression levels. + + const Z_NO_COMPRESSION: number; + const Z_BEST_SPEED: number; + const Z_BEST_COMPRESSION: number; + const Z_DEFAULT_COMPRESSION: number; + + // Compression strategy. + + const Z_FILTERED: number; + const Z_HUFFMAN_ONLY: number; + const Z_RLE: number; + const Z_FIXED: number; + const Z_DEFAULT_STRATEGY: number; + } + + // Constants + const Z_NO_FLUSH: number; + const Z_PARTIAL_FLUSH: number; + const Z_SYNC_FLUSH: number; + const Z_FULL_FLUSH: number; + const Z_FINISH: number; + const Z_BLOCK: number; + const Z_TREES: number; + const Z_OK: number; + const Z_STREAM_END: number; + const Z_NEED_DICT: number; + const Z_ERRNO: number; + const Z_STREAM_ERROR: number; + const Z_DATA_ERROR: number; + const Z_MEM_ERROR: number; + const Z_BUF_ERROR: number; + const Z_VERSION_ERROR: number; + const Z_NO_COMPRESSION: number; + const Z_BEST_SPEED: number; + const Z_BEST_COMPRESSION: number; + const Z_DEFAULT_COMPRESSION: number; + const Z_FILTERED: number; + const Z_HUFFMAN_ONLY: number; + const Z_RLE: number; + const Z_FIXED: number; + const Z_DEFAULT_STRATEGY: number; + const Z_BINARY: number; + const Z_TEXT: number; + const Z_ASCII: number; + const Z_UNKNOWN: number; + const Z_DEFLATED: number; +} + +declare module "os" { + interface CpuInfo { + model: string; + speed: number; + times: { + user: number; + nice: number; + sys: number; + idle: number; + irq: number; + }; + } + + interface NetworkInterfaceBase { + address: string; + netmask: string; + mac: string; + internal: boolean; + cidr: string | null; + } + + interface NetworkInterfaceInfoIPv4 extends NetworkInterfaceBase { + family: "IPv4"; + } + + interface NetworkInterfaceInfoIPv6 extends NetworkInterfaceBase { + family: "IPv6"; + scopeid: number; + } + + type NetworkInterfaceInfo = NetworkInterfaceInfoIPv4 | NetworkInterfaceInfoIPv6; + + function hostname(): string; + function loadavg(): number[]; + function uptime(): number; + function freemem(): number; + function totalmem(): number; + function cpus(): CpuInfo[]; + function type(): string; + function release(): string; + function networkInterfaces(): { [index: string]: NetworkInterfaceInfo[] }; + function homedir(): string; + function userInfo(options?: { encoding: string }): { username: string, uid: number, gid: number, shell: any, homedir: string }; + const constants: { + UV_UDP_REUSEADDR: number; + signals: { + SIGHUP: number; + SIGINT: number; + SIGQUIT: number; + SIGILL: number; + SIGTRAP: number; + SIGABRT: number; + SIGIOT: number; + SIGBUS: number; + SIGFPE: number; + SIGKILL: number; + SIGUSR1: number; + SIGSEGV: number; + SIGUSR2: number; + SIGPIPE: number; + SIGALRM: number; + SIGTERM: number; + SIGCHLD: number; + SIGSTKFLT: number; + SIGCONT: number; + SIGSTOP: number; + SIGTSTP: number; + SIGTTIN: number; + SIGTTOU: number; + SIGURG: number; + SIGXCPU: number; + SIGXFSZ: number; + SIGVTALRM: number; + SIGPROF: number; + SIGWINCH: number; + SIGIO: number; + SIGPOLL: number; + SIGPWR: number; + SIGSYS: number; + SIGUNUSED: number; + }; + errno: { + E2BIG: number; + EACCES: number; + EADDRINUSE: number; + EADDRNOTAVAIL: number; + EAFNOSUPPORT: number; + EAGAIN: number; + EALREADY: number; + EBADF: number; + EBADMSG: number; + EBUSY: number; + ECANCELED: number; + ECHILD: number; + ECONNABORTED: number; + ECONNREFUSED: number; + ECONNRESET: number; + EDEADLK: number; + EDESTADDRREQ: number; + EDOM: number; + EDQUOT: number; + EEXIST: number; + EFAULT: number; + EFBIG: number; + EHOSTUNREACH: number; + EIDRM: number; + EILSEQ: number; + EINPROGRESS: number; + EINTR: number; + EINVAL: number; + EIO: number; + EISCONN: number; + EISDIR: number; + ELOOP: number; + EMFILE: number; + EMLINK: number; + EMSGSIZE: number; + EMULTIHOP: number; + ENAMETOOLONG: number; + ENETDOWN: number; + ENETRESET: number; + ENETUNREACH: number; + ENFILE: number; + ENOBUFS: number; + ENODATA: number; + ENODEV: number; + ENOENT: number; + ENOEXEC: number; + ENOLCK: number; + ENOLINK: number; + ENOMEM: number; + ENOMSG: number; + ENOPROTOOPT: number; + ENOSPC: number; + ENOSR: number; + ENOSTR: number; + ENOSYS: number; + ENOTCONN: number; + ENOTDIR: number; + ENOTEMPTY: number; + ENOTSOCK: number; + ENOTSUP: number; + ENOTTY: number; + ENXIO: number; + EOPNOTSUPP: number; + EOVERFLOW: number; + EPERM: number; + EPIPE: number; + EPROTO: number; + EPROTONOSUPPORT: number; + EPROTOTYPE: number; + ERANGE: number; + EROFS: number; + ESPIPE: number; + ESRCH: number; + ESTALE: number; + ETIME: number; + ETIMEDOUT: number; + ETXTBSY: number; + EWOULDBLOCK: number; + EXDEV: number; + }; + priority: { + PRIORITY_LOW: number; + PRIORITY_BELOW_NORMAL: number; + PRIORITY_NORMAL: number; + PRIORITY_ABOVE_NORMAL: number; + PRIORITY_HIGH: number; + PRIORITY_HIGHEST: number; + } + }; + function arch(): string; + function platform(): NodeJS.Platform; + function tmpdir(): string; + const EOL: string; + function endianness(): "BE" | "LE"; + /** + * Gets the priority of a process. + * Defaults to current process. + */ + function getPriority(pid?: number): number; + /** + * Sets the priority of the current process. + * @param priority Must be in range of -20 to 19 + */ + function setPriority(priority: number): void; + /** + * Sets the priority of the process specified process. + * @param priority Must be in range of -20 to 19 + */ + function setPriority(pid: number, priority: number): void; +} + +declare module "https" { + import * as tls from "tls"; + import * as events from "events"; + import * as http from "http"; + import { URL } from "url"; + + type ServerOptions = tls.SecureContextOptions & tls.TlsOptions; + + type RequestOptions = http.RequestOptions & tls.SecureContextOptions & { + rejectUnauthorized?: boolean; // Defaults to true + servername?: string; // SNI TLS Extension + }; + + interface AgentOptions extends http.AgentOptions, tls.ConnectionOptions { + rejectUnauthorized?: boolean; + maxCachedSessions?: number; + } + + class Agent extends http.Agent { + constructor(options?: AgentOptions); + options: AgentOptions; + } + + class Server extends tls.Server { + setTimeout(callback: () => void): this; + setTimeout(msecs?: number, callback?: () => void): this; + timeout: number; + keepAliveTimeout: number; + } + + function createServer(options: ServerOptions, requestListener?: (req: http.IncomingMessage, res: http.ServerResponse) => void): Server; + function request(options: RequestOptions | string | URL, callback?: (res: http.IncomingMessage) => void): http.ClientRequest; + function request(url: string | URL, options: RequestOptions, callback?: (res: http.IncomingMessage) => void): http.ClientRequest; + function get(options: RequestOptions | string | URL, callback?: (res: http.IncomingMessage) => void): http.ClientRequest; + function get(url: string | URL, options: RequestOptions, callback?: (res: http.IncomingMessage) => void): http.ClientRequest; + let globalAgent: Agent; +} + +declare module "punycode" { + function decode(string: string): string; + function encode(string: string): string; + function toUnicode(domain: string): string; + function toASCII(domain: string): string; + const ucs2: ucs2; + interface ucs2 { + decode(string: string): number[]; + encode(codePoints: number[]): string; + } + const version: any; +} + +declare module "repl" { + import { Interface, Completer, AsyncCompleter } from "readline"; + import { Context } from "vm"; + import { InspectOptions } from "util"; + + interface ReplOptions { + /** + * The input prompt to display. + * Default: `"> "` + */ + prompt?: string; + /** + * The `Readable` stream from which REPL input will be read. + * Default: `process.stdin` + */ + input?: NodeJS.ReadableStream; + /** + * The `Writable` stream to which REPL output will be written. + * Default: `process.stdout` + */ + output?: NodeJS.WritableStream; + /** + * If `true`, specifies that the output should be treated as a TTY terminal, and have + * ANSI/VT100 escape codes written to it. + * Default: checking the value of the `isTTY` property on the output stream upon + * instantiation. + */ + terminal?: boolean; + /** + * The function to be used when evaluating each given line of input. + * Default: an async wrapper for the JavaScript `eval()` function. An `eval` function can + * error with `repl.Recoverable` to indicate the input was incomplete and prompt for + * additional lines. + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_default_evaluation + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_custom_evaluation_functions + */ + eval?: REPLEval; + /** + * If `true`, specifies that the default `writer` function should include ANSI color + * styling to REPL output. If a custom `writer` function is provided then this has no + * effect. + * Default: the REPL instance's `terminal` value. + */ + useColors?: boolean; + /** + * If `true`, specifies that the default evaluation function will use the JavaScript + * `global` as the context as opposed to creating a new separate context for the REPL + * instance. The node CLI REPL sets this value to `true`. + * Default: `false`. + */ + useGlobal?: boolean; + /** + * If `true`, specifies that the default writer will not output the return value of a + * command if it evaluates to `undefined`. + * Default: `false`. + */ + ignoreUndefined?: boolean; + /** + * The function to invoke to format the output of each command before writing to `output`. + * Default: a wrapper for `util.inspect`. + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_customizing_repl_output + */ + writer?: REPLWriter; + /** + * An optional function used for custom Tab auto completion. + * + * @see https://nodejs.org/dist/latest-v11.x/docs/api/readline.html#readline_use_of_the_completer_function + */ + completer?: Completer | AsyncCompleter; + /** + * A flag that specifies whether the default evaluator executes all JavaScript commands in + * strict mode or default (sloppy) mode. + * Accepted values are: + * - `repl.REPL_MODE_SLOPPY` - evaluates expressions in sloppy mode. + * - `repl.REPL_MODE_STRICT` - evaluates expressions in strict mode. This is equivalent to + * prefacing every repl statement with `'use strict'`. + */ + replMode?: typeof REPL_MODE_SLOPPY | typeof REPL_MODE_STRICT; + /** + * Stop evaluating the current piece of code when `SIGINT` is received, i.e. `Ctrl+C` is + * pressed. This cannot be used together with a custom `eval` function. + * Default: `false`. + */ + breakEvalOnSigint?: boolean; + } + + type REPLEval = (this: REPLServer, evalCmd: string, context: Context, file: string, cb: (err: Error | null, result: any) => void) => void; + type REPLWriter = (this: REPLServer, obj: any) => string; + + /** + * This is the default "writer" value, if none is passed in the REPL options, + * and it can be overridden by custom print functions. + */ + const writer: REPLWriter & { options: InspectOptions }; + + type REPLCommandAction = (this: REPLServer, text: string) => void; + + interface REPLCommand { + /** + * Help text to be displayed when `.help` is entered. + */ + help?: string; + /** + * The function to execute, optionally accepting a single string argument. + */ + action: REPLCommandAction; + } + + /** + * Provides a customizable Read-Eval-Print-Loop (REPL). + * + * Instances of `repl.REPLServer` will accept individual lines of user input, evaluate those + * according to a user-defined evaluation function, then output the result. Input and output + * may be from `stdin` and `stdout`, respectively, or may be connected to any Node.js `stream`. + * + * Instances of `repl.REPLServer` support automatic completion of inputs, simplistic Emacs-style + * line editing, multi-line inputs, ANSI-styled output, saving and restoring current REPL session + * state, error recovery, and customizable evaluation functions. + * + * Instances of `repl.REPLServer` are created using the `repl.start()` method and _should not_ + * be created directly using the JavaScript `new` keyword. + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_repl + */ + class REPLServer extends Interface { + /** + * The `vm.Context` provided to the `eval` function to be used for JavaScript + * evaluation. + */ + readonly context: Context; + /** + * The `Readable` stream from which REPL input will be read. + */ + readonly inputStream: NodeJS.ReadableStream; + /** + * The `Writable` stream to which REPL output will be written. + */ + readonly outputStream: NodeJS.WritableStream; + /** + * The commands registered via `replServer.defineCommand()`. + */ + readonly commands: { readonly [name: string]: REPLCommand | undefined }; + /** + * A value indicating whether the REPL is currently in "editor mode". + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_commands_and_special_keys + */ + readonly editorMode: boolean; + /** + * A value indicating whether the `_` variable has been assigned. + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable + */ + readonly underscoreAssigned: boolean; + /** + * The last evaluation result from the REPL (assigned to the `_` variable inside of the REPL). + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable + */ + readonly last: any; + /** + * A value indicating whether the `_error` variable has been assigned. + * + * @since v9.8.0 + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable + */ + readonly underscoreErrAssigned: boolean; + /** + * The last error raised inside the REPL (assigned to the `_error` variable inside of the REPL). + * + * @since v9.8.0 + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable + */ + readonly lastError: any; + /** + * Specified in the REPL options, this is the function to be used when evaluating each + * given line of input. If not specified in the REPL options, this is an async wrapper + * for the JavaScript `eval()` function. + */ + readonly eval: REPLEval; + /** + * Specified in the REPL options, this is a value indicating whether the default + * `writer` function should include ANSI color styling to REPL output. + */ + readonly useColors: boolean; + /** + * Specified in the REPL options, this is a value indicating whether the default `eval` + * function will use the JavaScript `global` as the context as opposed to creating a new + * separate context for the REPL instance. + */ + readonly useGlobal: boolean; + /** + * Specified in the REPL options, this is a value indicating whether the default `writer` + * function should output the result of a command if it evaluates to `undefined`. + */ + readonly ignoreUndefined: boolean; + /** + * Specified in the REPL options, this is the function to invoke to format the output of + * each command before writing to `outputStream`. If not specified in the REPL options, + * this will be a wrapper for `util.inspect`. + */ + readonly writer: REPLWriter; + /** + * Specified in the REPL options, this is the function to use for custom Tab auto-completion. + */ + readonly completer: Completer | AsyncCompleter; + /** + * Specified in the REPL options, this is a flag that specifies whether the default `eval` + * function should execute all JavaScript commands in strict mode or default (sloppy) mode. + * Possible values are: + * - `repl.REPL_MODE_SLOPPY` - evaluates expressions in sloppy mode. + * - `repl.REPL_MODE_STRICT` - evaluates expressions in strict mode. This is equivalent to + * prefacing every repl statement with `'use strict'`. + */ + readonly replMode: typeof REPL_MODE_SLOPPY | typeof REPL_MODE_STRICT; + + /** + * NOTE: According to the documentation: + * + * > Instances of `repl.REPLServer` are created using the `repl.start()` method and + * > _should not_ be created directly using the JavaScript `new` keyword. + * + * `REPLServer` cannot be subclassed due to implementation specifics in NodeJS. + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_class_replserver + */ + private constructor(); + + /** + * Used to add new `.`-prefixed commands to the REPL instance. Such commands are invoked + * by typing a `.` followed by the `keyword`. + * + * @param keyword The command keyword (_without_ a leading `.` character). + * @param cmd The function to invoke when the command is processed. + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_replserver_definecommand_keyword_cmd + */ + defineCommand(keyword: string, cmd: REPLCommandAction | REPLCommand): void; + /** + * Readies the REPL instance for input from the user, printing the configured `prompt` to a + * new line in the `output` and resuming the `input` to accept new input. + * + * When multi-line input is being entered, an ellipsis is printed rather than the 'prompt'. + * + * This method is primarily intended to be called from within the action function for + * commands registered using the `replServer.defineCommand()` method. + * + * @param preserveCursor When `true`, the cursor placement will not be reset to `0`. + */ + displayPrompt(preserveCursor?: boolean): void; + /** + * Clears any command that has been buffered but not yet executed. + * + * This method is primarily intended to be called from within the action function for + * commands registered using the `replServer.defineCommand()` method. + * + * @since v9.0.0 + */ + clearBufferedCommand(): void; + + /** + * events.EventEmitter + * 1. close - inherited from `readline.Interface` + * 2. line - inherited from `readline.Interface` + * 3. pause - inherited from `readline.Interface` + * 4. resume - inherited from `readline.Interface` + * 5. SIGCONT - inherited from `readline.Interface` + * 6. SIGINT - inherited from `readline.Interface` + * 7. SIGTSTP - inherited from `readline.Interface` + * 8. exit + * 9. reset + */ + + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "line", listener: (input: string) => void): this; + addListener(event: "pause", listener: () => void): this; + addListener(event: "resume", listener: () => void): this; + addListener(event: "SIGCONT", listener: () => void): this; + addListener(event: "SIGINT", listener: () => void): this; + addListener(event: "SIGTSTP", listener: () => void): this; + addListener(event: "exit", listener: () => void): this; + addListener(event: "reset", listener: (context: Context) => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "close"): boolean; + emit(event: "line", input: string): boolean; + emit(event: "pause"): boolean; + emit(event: "resume"): boolean; + emit(event: "SIGCONT"): boolean; + emit(event: "SIGINT"): boolean; + emit(event: "SIGTSTP"): boolean; + emit(event: "exit"): boolean; + emit(event: "reset", context: Context): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: () => void): this; + on(event: "line", listener: (input: string) => void): this; + on(event: "pause", listener: () => void): this; + on(event: "resume", listener: () => void): this; + on(event: "SIGCONT", listener: () => void): this; + on(event: "SIGINT", listener: () => void): this; + on(event: "SIGTSTP", listener: () => void): this; + on(event: "exit", listener: () => void): this; + on(event: "reset", listener: (context: Context) => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "line", listener: (input: string) => void): this; + once(event: "pause", listener: () => void): this; + once(event: "resume", listener: () => void): this; + once(event: "SIGCONT", listener: () => void): this; + once(event: "SIGINT", listener: () => void): this; + once(event: "SIGTSTP", listener: () => void): this; + once(event: "exit", listener: () => void): this; + once(event: "reset", listener: (context: Context) => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "line", listener: (input: string) => void): this; + prependListener(event: "pause", listener: () => void): this; + prependListener(event: "resume", listener: () => void): this; + prependListener(event: "SIGCONT", listener: () => void): this; + prependListener(event: "SIGINT", listener: () => void): this; + prependListener(event: "SIGTSTP", listener: () => void): this; + prependListener(event: "exit", listener: () => void): this; + prependListener(event: "reset", listener: (context: Context) => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "line", listener: (input: string) => void): this; + prependOnceListener(event: "pause", listener: () => void): this; + prependOnceListener(event: "resume", listener: () => void): this; + prependOnceListener(event: "SIGCONT", listener: () => void): this; + prependOnceListener(event: "SIGINT", listener: () => void): this; + prependOnceListener(event: "SIGTSTP", listener: () => void): this; + prependOnceListener(event: "exit", listener: () => void): this; + prependOnceListener(event: "reset", listener: (context: Context) => void): this; + } + + /** + * A flag passed in the REPL options. Evaluates expressions in sloppy mode. + */ + export const REPL_MODE_SLOPPY: symbol; // TODO: unique symbol + + /** + * A flag passed in the REPL options. Evaluates expressions in strict mode. + * This is equivalent to prefacing every repl statement with `'use strict'`. + */ + export const REPL_MODE_STRICT: symbol; // TODO: unique symbol + + /** + * Creates and starts a `repl.REPLServer` instance. + * + * @param options The options for the `REPLServer`. If `options` is a string, then it specifies + * the input prompt. + */ + function start(options?: string | ReplOptions): REPLServer; + + /** + * Indicates a recoverable error that a `REPLServer` can use to support multi-line input. + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_recoverable_errors + */ + class Recoverable extends SyntaxError { + err: Error; + + constructor(err: Error); + } +} + +declare module "readline" { + import * as events from "events"; + import * as stream from "stream"; + + interface Key { + sequence?: string; + name?: string; + ctrl?: boolean; + meta?: boolean; + shift?: boolean; + } + + class Interface extends events.EventEmitter { + readonly terminal: boolean; + + /** + * NOTE: According to the documentation: + * + * > Instances of the `readline.Interface` class are constructed using the + * > `readline.createInterface()` method. + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/readline.html#readline_class_interface + */ + protected constructor(input: NodeJS.ReadableStream, output?: NodeJS.WritableStream, completer?: Completer | AsyncCompleter, terminal?: boolean); + /** + * NOTE: According to the documentation: + * + * > Instances of the `readline.Interface` class are constructed using the + * > `readline.createInterface()` method. + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/readline.html#readline_class_interface + */ + protected constructor(options: ReadLineOptions); + + setPrompt(prompt: string): void; + prompt(preserveCursor?: boolean): void; + question(query: string, callback: (answer: string) => void): void; + pause(): this; + resume(): this; + close(): void; + write(data: string | Buffer, key?: Key): void; + + /** + * events.EventEmitter + * 1. close + * 2. line + * 3. pause + * 4. resume + * 5. SIGCONT + * 6. SIGINT + * 7. SIGTSTP + */ + + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "line", listener: (input: string) => void): this; + addListener(event: "pause", listener: () => void): this; + addListener(event: "resume", listener: () => void): this; + addListener(event: "SIGCONT", listener: () => void): this; + addListener(event: "SIGINT", listener: () => void): this; + addListener(event: "SIGTSTP", listener: () => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "close"): boolean; + emit(event: "line", input: string): boolean; + emit(event: "pause"): boolean; + emit(event: "resume"): boolean; + emit(event: "SIGCONT"): boolean; + emit(event: "SIGINT"): boolean; + emit(event: "SIGTSTP"): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: () => void): this; + on(event: "line", listener: (input: string) => void): this; + on(event: "pause", listener: () => void): this; + on(event: "resume", listener: () => void): this; + on(event: "SIGCONT", listener: () => void): this; + on(event: "SIGINT", listener: () => void): this; + on(event: "SIGTSTP", listener: () => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "line", listener: (input: string) => void): this; + once(event: "pause", listener: () => void): this; + once(event: "resume", listener: () => void): this; + once(event: "SIGCONT", listener: () => void): this; + once(event: "SIGINT", listener: () => void): this; + once(event: "SIGTSTP", listener: () => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "line", listener: (input: string) => void): this; + prependListener(event: "pause", listener: () => void): this; + prependListener(event: "resume", listener: () => void): this; + prependListener(event: "SIGCONT", listener: () => void): this; + prependListener(event: "SIGINT", listener: () => void): this; + prependListener(event: "SIGTSTP", listener: () => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "line", listener: (input: string) => void): this; + prependOnceListener(event: "pause", listener: () => void): this; + prependOnceListener(event: "resume", listener: () => void): this; + prependOnceListener(event: "SIGCONT", listener: () => void): this; + prependOnceListener(event: "SIGINT", listener: () => void): this; + prependOnceListener(event: "SIGTSTP", listener: () => void): this; + } + + type ReadLine = Interface; // type forwarded for backwards compatiblity + + type Completer = (line: string) => CompleterResult; + type AsyncCompleter = (line: string, callback: (err: any, result: CompleterResult) => void) => any; + + type CompleterResult = [string[], string]; + + interface ReadLineOptions { + input: NodeJS.ReadableStream; + output?: NodeJS.WritableStream; + completer?: Completer | AsyncCompleter; + terminal?: boolean; + historySize?: number; + prompt?: string; + crlfDelay?: number; + removeHistoryDuplicates?: boolean; + } + + function createInterface(input: NodeJS.ReadableStream, output?: NodeJS.WritableStream, completer?: Completer | AsyncCompleter, terminal?: boolean): Interface; + function createInterface(options: ReadLineOptions): Interface; + + function cursorTo(stream: NodeJS.WritableStream, x: number, y?: number): void; + function emitKeypressEvents(stream: NodeJS.ReadableStream, interface?: Interface): void; + function moveCursor(stream: NodeJS.WritableStream, dx: number | string, dy: number | string): void; + function clearLine(stream: NodeJS.WritableStream, dir: number): void; + function clearScreenDown(stream: NodeJS.WritableStream): void; +} + +declare module "vm" { + interface Context { + [key: string]: any; + } + interface BaseOptions { + /** + * Specifies the filename used in stack traces produced by this script. + * Default: `''`. + */ + filename?: string; + /** + * Specifies the line number offset that is displayed in stack traces produced by this script. + * Default: `0`. + */ + lineOffset?: number; + /** + * Specifies the column number offset that is displayed in stack traces produced by this script. + * Default: `0` + */ + columnOffset?: number; + } + interface ScriptOptions extends BaseOptions { + displayErrors?: boolean; + timeout?: number; + cachedData?: Buffer; + produceCachedData?: boolean; + } + interface RunningScriptOptions extends BaseOptions { + displayErrors?: boolean; + timeout?: number; + } + interface CompileFunctionOptions extends BaseOptions { + /** + * Provides an optional data with V8's code cache data for the supplied source. + */ + cachedData?: Buffer; + /** + * Specifies whether to produce new cache data. + * Default: `false`, + */ + produceCachedData?: boolean; + /** + * The sandbox/context in which the said function should be compiled in. + */ + parsingContext?: Context; + + /** + * An array containing a collection of context extensions (objects wrapping the current scope) to be applied while compiling + */ + contextExtensions?: Object[]; + } + class Script { + constructor(code: string, options?: ScriptOptions); + runInContext(contextifiedSandbox: Context, options?: RunningScriptOptions): any; + runInNewContext(sandbox?: Context, options?: RunningScriptOptions): any; + runInThisContext(options?: RunningScriptOptions): any; + } + function createContext(sandbox?: Context): Context; + function isContext(sandbox: Context): boolean; + function runInContext(code: string, contextifiedSandbox: Context, options?: RunningScriptOptions | string): any; + function runInNewContext(code: string, sandbox?: Context, options?: RunningScriptOptions | string): any; + function runInThisContext(code: string, options?: RunningScriptOptions | string): any; + function compileFunction(code: string, params: string[], options: CompileFunctionOptions): Function; +} + +declare module "child_process" { + import * as events from "events"; + import * as stream from "stream"; + import * as net from "net"; + + interface ChildProcess extends events.EventEmitter { + stdin: stream.Writable; + stdout: stream.Readable; + stderr: stream.Readable; + stdio: [stream.Writable, stream.Readable, stream.Readable]; + killed: boolean; + pid: number; + kill(signal?: string): void; + send(message: any, callback?: (error: Error) => void): boolean; + send(message: any, sendHandle?: net.Socket | net.Server, callback?: (error: Error) => void): boolean; + send(message: any, sendHandle?: net.Socket | net.Server, options?: MessageOptions, callback?: (error: Error) => void): boolean; + connected: boolean; + disconnect(): void; + unref(): void; + ref(): void; + + /** + * events.EventEmitter + * 1. close + * 2. disconnect + * 3. error + * 4. exit + * 5. message + */ + + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "close", listener: (code: number, signal: string) => void): this; + addListener(event: "disconnect", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "exit", listener: (code: number | null, signal: string | null) => void): this; + addListener(event: "message", listener: (message: any, sendHandle: net.Socket | net.Server) => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "close", code: number, signal: string): boolean; + emit(event: "disconnect"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "exit", code: number | null, signal: string | null): boolean; + emit(event: "message", message: any, sendHandle: net.Socket | net.Server): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: (code: number, signal: string) => void): this; + on(event: "disconnect", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "exit", listener: (code: number | null, signal: string | null) => void): this; + on(event: "message", listener: (message: any, sendHandle: net.Socket | net.Server) => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: (code: number, signal: string) => void): this; + once(event: "disconnect", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "exit", listener: (code: number | null, signal: string | null) => void): this; + once(event: "message", listener: (message: any, sendHandle: net.Socket | net.Server) => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: (code: number, signal: string) => void): this; + prependListener(event: "disconnect", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "exit", listener: (code: number | null, signal: string | null) => void): this; + prependListener(event: "message", listener: (message: any, sendHandle: net.Socket | net.Server) => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: (code: number, signal: string) => void): this; + prependOnceListener(event: "disconnect", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "exit", listener: (code: number | null, signal: string | null) => void): this; + prependOnceListener(event: "message", listener: (message: any, sendHandle: net.Socket | net.Server) => void): this; + } + + interface MessageOptions { + keepOpen?: boolean; + } + + type StdioOptions = "pipe" | "ignore" | "inherit" | Array<("pipe" | "ipc" | "ignore" | "inherit" | stream.Stream | number | null | undefined)>; + + interface SpawnOptions { + cwd?: string; + env?: NodeJS.ProcessEnv; + argv0?: string; + stdio?: StdioOptions; + detached?: boolean; + uid?: number; + gid?: number; + shell?: boolean | string; + windowsVerbatimArguments?: boolean; + windowsHide?: boolean; + } + + function spawn(command: string, options?: SpawnOptions): ChildProcess; + function spawn(command: string, args?: ReadonlyArray, options?: SpawnOptions): ChildProcess; + + interface ExecOptions { + cwd?: string; + env?: NodeJS.ProcessEnv; + shell?: string; + timeout?: number; + maxBuffer?: number; + killSignal?: string; + uid?: number; + gid?: number; + windowsHide?: boolean; + } + + interface ExecOptionsWithStringEncoding extends ExecOptions { + encoding: BufferEncoding; + } + + interface ExecOptionsWithBufferEncoding extends ExecOptions { + encoding: string | null; // specify `null`. + } + + interface ExecException extends Error { + cmd?: string; + killed?: boolean; + code?: number; + signal?: string; + } + + // no `options` definitely means stdout/stderr are `string`. + function exec(command: string, callback?: (error: ExecException | null, stdout: string, stderr: string) => void): ChildProcess; + + // `options` with `"buffer"` or `null` for `encoding` means stdout/stderr are definitely `Buffer`. + function exec(command: string, options: { encoding: "buffer" | null } & ExecOptions, callback?: (error: ExecException | null, stdout: Buffer, stderr: Buffer) => void): ChildProcess; + + // `options` with well known `encoding` means stdout/stderr are definitely `string`. + function exec(command: string, options: { encoding: BufferEncoding } & ExecOptions, callback?: (error: ExecException | null, stdout: string, stderr: string) => void): ChildProcess; + + // `options` with an `encoding` whose type is `string` means stdout/stderr could either be `Buffer` or `string`. + // There is no guarantee the `encoding` is unknown as `string` is a superset of `BufferEncoding`. + function exec(command: string, options: { encoding: string } & ExecOptions, callback?: (error: ExecException | null, stdout: string | Buffer, stderr: string | Buffer) => void): ChildProcess; + + // `options` without an `encoding` means stdout/stderr are definitely `string`. + function exec(command: string, options: ExecOptions, callback?: (error: ExecException | null, stdout: string, stderr: string) => void): ChildProcess; + + // fallback if nothing else matches. Worst case is always `string | Buffer`. + function exec( + command: string, + options: ({ encoding?: string | null } & ExecOptions) | undefined | null, + callback?: (error: ExecException | null, stdout: string | Buffer, stderr: string | Buffer) => void, + ): ChildProcess; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace exec { + function __promisify__(command: string): Promise<{ stdout: string, stderr: string }>; + function __promisify__(command: string, options: { encoding: "buffer" | null } & ExecOptions): Promise<{ stdout: Buffer, stderr: Buffer }>; + function __promisify__(command: string, options: { encoding: BufferEncoding } & ExecOptions): Promise<{ stdout: string, stderr: string }>; + function __promisify__(command: string, options: ExecOptions): Promise<{ stdout: string, stderr: string }>; + function __promisify__(command: string, options?: ({ encoding?: string | null } & ExecOptions) | null): Promise<{ stdout: string | Buffer, stderr: string | Buffer }>; + } + + interface ExecFileOptions { + cwd?: string; + env?: NodeJS.ProcessEnv; + timeout?: number; + maxBuffer?: number; + killSignal?: string; + uid?: number; + gid?: number; + windowsHide?: boolean; + windowsVerbatimArguments?: boolean; + } + interface ExecFileOptionsWithStringEncoding extends ExecFileOptions { + encoding: BufferEncoding; + } + interface ExecFileOptionsWithBufferEncoding extends ExecFileOptions { + encoding: 'buffer' | null; + } + interface ExecFileOptionsWithOtherEncoding extends ExecFileOptions { + encoding: string; + } + + function execFile(file: string): ChildProcess; + function execFile(file: string, options: ({ encoding?: string | null } & ExecFileOptions) | undefined | null): ChildProcess; + function execFile(file: string, args?: ReadonlyArray | null): ChildProcess; + function execFile(file: string, args: ReadonlyArray | undefined | null, options: ({ encoding?: string | null } & ExecFileOptions) | undefined | null): ChildProcess; + + // no `options` definitely means stdout/stderr are `string`. + function execFile(file: string, callback: (error: Error | null, stdout: string, stderr: string) => void): ChildProcess; + function execFile(file: string, args: ReadonlyArray | undefined | null, callback: (error: Error | null, stdout: string, stderr: string) => void): ChildProcess; + + // `options` with `"buffer"` or `null` for `encoding` means stdout/stderr are definitely `Buffer`. + function execFile(file: string, options: ExecFileOptionsWithBufferEncoding, callback: (error: Error | null, stdout: Buffer, stderr: Buffer) => void): ChildProcess; + function execFile( + file: string, + args: ReadonlyArray | undefined | null, + options: ExecFileOptionsWithBufferEncoding, + callback: (error: Error | null, stdout: Buffer, stderr: Buffer) => void, + ): ChildProcess; + + // `options` with well known `encoding` means stdout/stderr are definitely `string`. + function execFile(file: string, options: ExecFileOptionsWithStringEncoding, callback: (error: Error | null, stdout: string, stderr: string) => void): ChildProcess; + function execFile( + file: string, + args: ReadonlyArray | undefined | null, + options: ExecFileOptionsWithStringEncoding, + callback: (error: Error | null, stdout: string, stderr: string) => void, + ): ChildProcess; + + // `options` with an `encoding` whose type is `string` means stdout/stderr could either be `Buffer` or `string`. + // There is no guarantee the `encoding` is unknown as `string` is a superset of `BufferEncoding`. + function execFile( + file: string, + options: ExecFileOptionsWithOtherEncoding, + callback: (error: Error | null, stdout: string | Buffer, stderr: string | Buffer) => void, + ): ChildProcess; + function execFile( + file: string, + args: ReadonlyArray | undefined | null, + options: ExecFileOptionsWithOtherEncoding, + callback: (error: Error | null, stdout: string | Buffer, stderr: string | Buffer) => void, + ): ChildProcess; + + // `options` without an `encoding` means stdout/stderr are definitely `string`. + function execFile(file: string, options: ExecFileOptions, callback: (error: Error | null, stdout: string, stderr: string) => void): ChildProcess; + function execFile(file: string, args: ReadonlyArray | undefined | null, options: ExecFileOptions, callback: (error: Error | null, stdout: string, stderr: string) => void): ChildProcess; + + // fallback if nothing else matches. Worst case is always `string | Buffer`. + function execFile( + file: string, + options: ({ encoding?: string | null } & ExecFileOptions) | undefined | null, + callback: ((error: Error | null, stdout: string | Buffer, stderr: string | Buffer) => void) | undefined | null, + ): ChildProcess; + function execFile( + file: string, + args: ReadonlyArray | undefined | null, + options: ({ encoding?: string | null } & ExecFileOptions) | undefined | null, + callback: ((error: Error | null, stdout: string | Buffer, stderr: string | Buffer) => void) | undefined | null, + ): ChildProcess; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace execFile { + function __promisify__(file: string): Promise<{ stdout: string, stderr: string }>; + function __promisify__(file: string, args: string[] | undefined | null): Promise<{ stdout: string, stderr: string }>; + function __promisify__(file: string, options: ExecFileOptionsWithBufferEncoding): Promise<{ stdout: Buffer, stderr: Buffer }>; + function __promisify__(file: string, args: string[] | undefined | null, options: ExecFileOptionsWithBufferEncoding): Promise<{ stdout: Buffer, stderr: Buffer }>; + function __promisify__(file: string, options: ExecFileOptionsWithStringEncoding): Promise<{ stdout: string, stderr: string }>; + function __promisify__(file: string, args: string[] | undefined | null, options: ExecFileOptionsWithStringEncoding): Promise<{ stdout: string, stderr: string }>; + function __promisify__(file: string, options: ExecFileOptionsWithOtherEncoding): Promise<{ stdout: string | Buffer, stderr: string | Buffer }>; + function __promisify__(file: string, args: string[] | undefined | null, options: ExecFileOptionsWithOtherEncoding): Promise<{ stdout: string | Buffer, stderr: string | Buffer }>; + function __promisify__(file: string, options: ExecFileOptions): Promise<{ stdout: string, stderr: string }>; + function __promisify__(file: string, args: string[] | undefined | null, options: ExecFileOptions): Promise<{ stdout: string, stderr: string }>; + function __promisify__(file: string, options: ({ encoding?: string | null } & ExecFileOptions) | undefined | null): Promise<{ stdout: string | Buffer, stderr: string | Buffer }>; + function __promisify__( + file: string, + args: string[] | undefined | null, + options: ({ encoding?: string | null } & ExecFileOptions) | undefined | null, + ): Promise<{ stdout: string | Buffer, stderr: string | Buffer }>; + } + + interface ForkOptions { + cwd?: string; + env?: NodeJS.ProcessEnv; + execPath?: string; + execArgv?: string[]; + silent?: boolean; + stdio?: StdioOptions; + windowsVerbatimArguments?: boolean; + uid?: number; + gid?: number; + } + function fork(modulePath: string, args?: ReadonlyArray, options?: ForkOptions): ChildProcess; + + interface SpawnSyncOptions { + argv0?: string; // Not specified in the docs + cwd?: string; + input?: string | Buffer | NodeJS.TypedArray | DataView; + stdio?: StdioOptions; + env?: NodeJS.ProcessEnv; + uid?: number; + gid?: number; + timeout?: number; + killSignal?: string | number; + maxBuffer?: number; + encoding?: string; + shell?: boolean | string; + windowsVerbatimArguments?: boolean; + windowsHide?: boolean; + } + interface SpawnSyncOptionsWithStringEncoding extends SpawnSyncOptions { + encoding: BufferEncoding; + } + interface SpawnSyncOptionsWithBufferEncoding extends SpawnSyncOptions { + encoding: string; // specify `null`. + } + interface SpawnSyncReturns { + pid: number; + output: string[]; + stdout: T; + stderr: T; + status: number; + signal: string; + error: Error; + } + function spawnSync(command: string): SpawnSyncReturns; + function spawnSync(command: string, options?: SpawnSyncOptionsWithStringEncoding): SpawnSyncReturns; + function spawnSync(command: string, options?: SpawnSyncOptionsWithBufferEncoding): SpawnSyncReturns; + function spawnSync(command: string, options?: SpawnSyncOptions): SpawnSyncReturns; + function spawnSync(command: string, args?: ReadonlyArray, options?: SpawnSyncOptionsWithStringEncoding): SpawnSyncReturns; + function spawnSync(command: string, args?: ReadonlyArray, options?: SpawnSyncOptionsWithBufferEncoding): SpawnSyncReturns; + function spawnSync(command: string, args?: ReadonlyArray, options?: SpawnSyncOptions): SpawnSyncReturns; + + interface ExecSyncOptions { + cwd?: string; + input?: string | Buffer | Uint8Array; + stdio?: StdioOptions; + env?: NodeJS.ProcessEnv; + shell?: string; + uid?: number; + gid?: number; + timeout?: number; + killSignal?: string | number; + maxBuffer?: number; + encoding?: string; + windowsHide?: boolean; + } + interface ExecSyncOptionsWithStringEncoding extends ExecSyncOptions { + encoding: BufferEncoding; + } + interface ExecSyncOptionsWithBufferEncoding extends ExecSyncOptions { + encoding: string; // specify `null`. + } + function execSync(command: string): Buffer; + function execSync(command: string, options?: ExecSyncOptionsWithStringEncoding): string; + function execSync(command: string, options?: ExecSyncOptionsWithBufferEncoding): Buffer; + function execSync(command: string, options?: ExecSyncOptions): Buffer; + + interface ExecFileSyncOptions { + cwd?: string; + input?: string | Buffer | NodeJS.TypedArray | DataView; + stdio?: StdioOptions; + env?: NodeJS.ProcessEnv; + uid?: number; + gid?: number; + timeout?: number; + killSignal?: string | number; + maxBuffer?: number; + encoding?: string; + windowsHide?: boolean; + shell?: boolean | string; + } + interface ExecFileSyncOptionsWithStringEncoding extends ExecFileSyncOptions { + encoding: BufferEncoding; + } + interface ExecFileSyncOptionsWithBufferEncoding extends ExecFileSyncOptions { + encoding: string; // specify `null`. + } + function execFileSync(command: string): Buffer; + function execFileSync(command: string, options?: ExecFileSyncOptionsWithStringEncoding): string; + function execFileSync(command: string, options?: ExecFileSyncOptionsWithBufferEncoding): Buffer; + function execFileSync(command: string, options?: ExecFileSyncOptions): Buffer; + function execFileSync(command: string, args?: ReadonlyArray, options?: ExecFileSyncOptionsWithStringEncoding): string; + function execFileSync(command: string, args?: ReadonlyArray, options?: ExecFileSyncOptionsWithBufferEncoding): Buffer; + function execFileSync(command: string, args?: ReadonlyArray, options?: ExecFileSyncOptions): Buffer; +} + +declare module "url" { + import { ParsedUrlQuery } from 'querystring'; + + interface UrlObjectCommon { + auth?: string; + hash?: string; + host?: string; + hostname?: string; + href?: string; + path?: string; + pathname?: string; + protocol?: string; + search?: string; + slashes?: boolean; + } + + // Input to `url.format` + interface UrlObject extends UrlObjectCommon { + port?: string | number; + query?: string | null | { [key: string]: any }; + } + + // Output of `url.parse` + interface Url extends UrlObjectCommon { + port?: string; + query?: string | null | ParsedUrlQuery; + } + + interface UrlWithParsedQuery extends Url { + query: ParsedUrlQuery; + } + + interface UrlWithStringQuery extends Url { + query: string | null; + } + + function parse(urlStr: string): UrlWithStringQuery; + function parse(urlStr: string, parseQueryString: false | undefined, slashesDenoteHost?: boolean): UrlWithStringQuery; + function parse(urlStr: string, parseQueryString: true, slashesDenoteHost?: boolean): UrlWithParsedQuery; + function parse(urlStr: string, parseQueryString: boolean, slashesDenoteHost?: boolean): Url; + + function format(URL: URL, options?: URLFormatOptions): string; + function format(urlObject: UrlObject | string): string; + function resolve(from: string, to: string): string; + + function domainToASCII(domain: string): string; + function domainToUnicode(domain: string): string; + + /** + * This function ensures the correct decodings of percent-encoded characters as + * well as ensuring a cross-platform valid absolute path string. + * @param url The file URL string or URL object to convert to a path. + */ + function fileURLToPath(url: string | URL): string; + + /** + * This function ensures that path is resolved absolutely, and that the URL + * control characters are correctly encoded when converting into a File URL. + * @param url The path to convert to a File URL. + */ + function pathToFileURL(url: string): URL; + + interface URLFormatOptions { + auth?: boolean; + fragment?: boolean; + search?: boolean; + unicode?: boolean; + } + + class URL { + constructor(input: string, base?: string | URL); + hash: string; + host: string; + hostname: string; + href: string; + readonly origin: string; + password: string; + pathname: string; + port: string; + protocol: string; + search: string; + readonly searchParams: URLSearchParams; + username: string; + toString(): string; + toJSON(): string; + } + + class URLSearchParams implements Iterable<[string, string]> { + constructor(init?: URLSearchParams | string | { [key: string]: string | string[] | undefined } | Iterable<[string, string]> | Array<[string, string]>); + append(name: string, value: string): void; + delete(name: string): void; + entries(): IterableIterator<[string, string]>; + forEach(callback: (value: string, name: string, searchParams: this) => void): void; + get(name: string): string | null; + getAll(name: string): string[]; + has(name: string): boolean; + keys(): IterableIterator; + set(name: string, value: string): void; + sort(): void; + toString(): string; + values(): IterableIterator; + [Symbol.iterator](): IterableIterator<[string, string]>; + } +} + +declare module "dns" { + // Supported getaddrinfo flags. + const ADDRCONFIG: number; + const V4MAPPED: number; + + interface LookupOptions { + family?: number; + hints?: number; + all?: boolean; + verbatim?: boolean; + } + + interface LookupOneOptions extends LookupOptions { + all?: false; + } + + interface LookupAllOptions extends LookupOptions { + all: true; + } + + interface LookupAddress { + address: string; + family: number; + } + + function lookup(hostname: string, family: number, callback: (err: NodeJS.ErrnoException, address: string, family: number) => void): void; + function lookup(hostname: string, options: LookupOneOptions, callback: (err: NodeJS.ErrnoException, address: string, family: number) => void): void; + function lookup(hostname: string, options: LookupAllOptions, callback: (err: NodeJS.ErrnoException, addresses: LookupAddress[]) => void): void; + function lookup(hostname: string, options: LookupOptions, callback: (err: NodeJS.ErrnoException, address: string | LookupAddress[], family: number) => void): void; + function lookup(hostname: string, callback: (err: NodeJS.ErrnoException, address: string, family: number) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace lookup { + function __promisify__(hostname: string, options: LookupAllOptions): Promise<{ address: LookupAddress[] }>; + function __promisify__(hostname: string, options?: LookupOneOptions | number): Promise<{ address: string, family: number }>; + function __promisify__(hostname: string, options?: LookupOptions | number): Promise<{ address: string | LookupAddress[], family?: number }>; + } + + function lookupService(address: string, port: number, callback: (err: NodeJS.ErrnoException, hostname: string, service: string) => void): void; + + namespace lookupService { + function __promisify__(address: string, port: number): Promise<{ hostname: string, service: string }>; + } + + interface ResolveOptions { + ttl: boolean; + } + + interface ResolveWithTtlOptions extends ResolveOptions { + ttl: true; + } + + interface RecordWithTtl { + address: string; + ttl: number; + } + + /** @deprecated Use AnyARecord or AnyAaaaRecord instead. */ + type AnyRecordWithTtl = AnyARecord | AnyAaaaRecord; + + interface AnyARecord extends RecordWithTtl { + type: "A"; + } + + interface AnyAaaaRecord extends RecordWithTtl { + type: "AAAA"; + } + + interface MxRecord { + priority: number; + exchange: string; + } + + interface AnyMxRecord extends MxRecord { + type: "MX"; + } + + interface NaptrRecord { + flags: string; + service: string; + regexp: string; + replacement: string; + order: number; + preference: number; + } + + interface AnyNaptrRecord extends NaptrRecord { + type: "NAPTR"; + } + + interface SoaRecord { + nsname: string; + hostmaster: string; + serial: number; + refresh: number; + retry: number; + expire: number; + minttl: number; + } + + interface AnySoaRecord extends SoaRecord { + type: "SOA"; + } + + interface SrvRecord { + priority: number; + weight: number; + port: number; + name: string; + } + + interface AnySrvRecord extends SrvRecord { + type: "SRV"; + } + + interface AnyTxtRecord { + type: "TXT"; + entries: string[]; + } + + interface AnyNsRecord { + type: "NS"; + value: string; + } + + interface AnyPtrRecord { + type: "PTR"; + value: string; + } + + interface AnyCnameRecord { + type: "CNAME"; + value: string; + } + + type AnyRecord = AnyARecord | + AnyAaaaRecord | + AnyCnameRecord | + AnyMxRecord | + AnyNaptrRecord | + AnyNsRecord | + AnyPtrRecord | + AnySoaRecord | + AnySrvRecord | + AnyTxtRecord; + + function resolve(hostname: string, callback: (err: NodeJS.ErrnoException, addresses: string[]) => void): void; + function resolve(hostname: string, rrtype: "A", callback: (err: NodeJS.ErrnoException, addresses: string[]) => void): void; + function resolve(hostname: string, rrtype: "AAAA", callback: (err: NodeJS.ErrnoException, addresses: string[]) => void): void; + function resolve(hostname: string, rrtype: "ANY", callback: (err: NodeJS.ErrnoException, addresses: AnyRecord[]) => void): void; + function resolve(hostname: string, rrtype: "CNAME", callback: (err: NodeJS.ErrnoException, addresses: string[]) => void): void; + function resolve(hostname: string, rrtype: "MX", callback: (err: NodeJS.ErrnoException, addresses: MxRecord[]) => void): void; + function resolve(hostname: string, rrtype: "NAPTR", callback: (err: NodeJS.ErrnoException, addresses: NaptrRecord[]) => void): void; + function resolve(hostname: string, rrtype: "NS", callback: (err: NodeJS.ErrnoException, addresses: string[]) => void): void; + function resolve(hostname: string, rrtype: "PTR", callback: (err: NodeJS.ErrnoException, addresses: string[]) => void): void; + function resolve(hostname: string, rrtype: "SOA", callback: (err: NodeJS.ErrnoException, addresses: SoaRecord) => void): void; + function resolve(hostname: string, rrtype: "SRV", callback: (err: NodeJS.ErrnoException, addresses: SrvRecord[]) => void): void; + function resolve(hostname: string, rrtype: "TXT", callback: (err: NodeJS.ErrnoException, addresses: string[][]) => void): void; + function resolve( + hostname: string, + rrtype: string, + callback: (err: NodeJS.ErrnoException, addresses: string[] | MxRecord[] | NaptrRecord[] | SoaRecord | SrvRecord[] | string[][] | AnyRecord[]) => void, + ): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace resolve { + function __promisify__(hostname: string, rrtype?: "A" | "AAAA" | "CNAME" | "NS" | "PTR"): Promise; + function __promisify__(hostname: string, rrtype: "ANY"): Promise; + function __promisify__(hostname: string, rrtype: "MX"): Promise; + function __promisify__(hostname: string, rrtype: "NAPTR"): Promise; + function __promisify__(hostname: string, rrtype: "SOA"): Promise; + function __promisify__(hostname: string, rrtype: "SRV"): Promise; + function __promisify__(hostname: string, rrtype: "TXT"): Promise; + function __promisify__(hostname: string, rrtype: string): Promise; + } + + function resolve4(hostname: string, callback: (err: NodeJS.ErrnoException, addresses: string[]) => void): void; + function resolve4(hostname: string, options: ResolveWithTtlOptions, callback: (err: NodeJS.ErrnoException, addresses: RecordWithTtl[]) => void): void; + function resolve4(hostname: string, options: ResolveOptions, callback: (err: NodeJS.ErrnoException, addresses: string[] | RecordWithTtl[]) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace resolve4 { + function __promisify__(hostname: string): Promise; + function __promisify__(hostname: string, options: ResolveWithTtlOptions): Promise; + function __promisify__(hostname: string, options?: ResolveOptions): Promise; + } + + function resolve6(hostname: string, callback: (err: NodeJS.ErrnoException, addresses: string[]) => void): void; + function resolve6(hostname: string, options: ResolveWithTtlOptions, callback: (err: NodeJS.ErrnoException, addresses: RecordWithTtl[]) => void): void; + function resolve6(hostname: string, options: ResolveOptions, callback: (err: NodeJS.ErrnoException, addresses: string[] | RecordWithTtl[]) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace resolve6 { + function __promisify__(hostname: string): Promise; + function __promisify__(hostname: string, options: ResolveWithTtlOptions): Promise; + function __promisify__(hostname: string, options?: ResolveOptions): Promise; + } + + function resolveCname(hostname: string, callback: (err: NodeJS.ErrnoException, addresses: string[]) => void): void; + namespace resolveCname { + function __promisify__(hostname: string): Promise; + } + + function resolveMx(hostname: string, callback: (err: NodeJS.ErrnoException, addresses: MxRecord[]) => void): void; + namespace resolveMx { + function __promisify__(hostname: string): Promise; + } + + function resolveNaptr(hostname: string, callback: (err: NodeJS.ErrnoException, addresses: NaptrRecord[]) => void): void; + namespace resolveNaptr { + function __promisify__(hostname: string): Promise; + } + + function resolveNs(hostname: string, callback: (err: NodeJS.ErrnoException, addresses: string[]) => void): void; + namespace resolveNs { + function __promisify__(hostname: string): Promise; + } + + function resolvePtr(hostname: string, callback: (err: NodeJS.ErrnoException, addresses: string[]) => void): void; + namespace resolvePtr { + function __promisify__(hostname: string): Promise; + } + + function resolveSoa(hostname: string, callback: (err: NodeJS.ErrnoException, address: SoaRecord) => void): void; + namespace resolveSoa { + function __promisify__(hostname: string): Promise; + } + + function resolveSrv(hostname: string, callback: (err: NodeJS.ErrnoException, addresses: SrvRecord[]) => void): void; + namespace resolveSrv { + function __promisify__(hostname: string): Promise; + } + + function resolveTxt(hostname: string, callback: (err: NodeJS.ErrnoException, addresses: string[][]) => void): void; + namespace resolveTxt { + function __promisify__(hostname: string): Promise; + } + + function resolveAny(hostname: string, callback: (err: NodeJS.ErrnoException, addresses: AnyRecord[]) => void): void; + namespace resolveAny { + function __promisify__(hostname: string): Promise; + } + + function reverse(ip: string, callback: (err: NodeJS.ErrnoException, hostnames: string[]) => void): void; + function setServers(servers: string[]): void; + function getServers(): string[]; + + // Error codes + const NODATA: string; + const FORMERR: string; + const SERVFAIL: string; + const NOTFOUND: string; + const NOTIMP: string; + const REFUSED: string; + const BADQUERY: string; + const BADNAME: string; + const BADFAMILY: string; + const BADRESP: string; + const CONNREFUSED: string; + const TIMEOUT: string; + const EOF: string; + const FILE: string; + const NOMEM: string; + const DESTRUCTION: string; + const BADSTR: string; + const BADFLAGS: string; + const NONAME: string; + const BADHINTS: string; + const NOTINITIALIZED: string; + const LOADIPHLPAPI: string; + const ADDRGETNETWORKPARAMS: string; + const CANCELLED: string; + + class Resolver { + getServers: typeof getServers; + setServers: typeof setServers; + resolve: typeof resolve; + resolve4: typeof resolve4; + resolve6: typeof resolve6; + resolveAny: typeof resolveAny; + resolveCname: typeof resolveCname; + resolveMx: typeof resolveMx; + resolveNaptr: typeof resolveNaptr; + resolveNs: typeof resolveNs; + resolvePtr: typeof resolvePtr; + resolveSoa: typeof resolveSoa; + resolveSrv: typeof resolveSrv; + resolveTxt: typeof resolveTxt; + reverse: typeof reverse; + cancel(): void; + } +} + +declare module "net" { + import * as stream from "stream"; + import * as events from "events"; + import * as dns from "dns"; + + type LookupFunction = (hostname: string, options: dns.LookupOneOptions, callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void) => void; + + interface AddressInfo { + address: string; + family: string; + port: number; + } + + interface SocketConstructorOpts { + fd?: number; + allowHalfOpen?: boolean; + readable?: boolean; + writable?: boolean; + } + + interface TcpSocketConnectOpts { + port: number; + host?: string; + localAddress?: string; + localPort?: number; + hints?: number; + family?: number; + lookup?: LookupFunction; + } + + interface IpcSocketConnectOpts { + path: string; + } + + type SocketConnectOpts = TcpSocketConnectOpts | IpcSocketConnectOpts; + + class Socket extends stream.Duplex { + constructor(options?: SocketConstructorOpts); + + // Extended base methods + write(buffer: Buffer): boolean; + write(buffer: Buffer, cb?: Function): boolean; + write(str: string, cb?: Function): boolean; + write(str: string, encoding?: string, cb?: Function): boolean; + write(str: string, encoding?: string, fd?: string): boolean; + write(data: any, encoding?: string, callback?: Function): void; + + connect(options: SocketConnectOpts, connectionListener?: Function): this; + connect(port: number, host: string, connectionListener?: Function): this; + connect(port: number, connectionListener?: Function): this; + connect(path: string, connectionListener?: Function): this; + + setEncoding(encoding?: string): this; + pause(): this; + resume(): this; + setTimeout(timeout: number, callback?: Function): this; + setNoDelay(noDelay?: boolean): this; + setKeepAlive(enable?: boolean, initialDelay?: number): this; + address(): AddressInfo | string; + unref(): void; + ref(): void; + + readonly bufferSize: number; + readonly bytesRead: number; + readonly bytesWritten: number; + readonly connecting: boolean; + readonly destroyed: boolean; + readonly localAddress: string; + readonly localPort: number; + readonly remoteAddress?: string; + readonly remoteFamily?: string; + readonly remotePort?: number; + + // Extended base methods + end(): void; + end(buffer: Buffer, cb?: Function): void; + end(str: string, cb?: Function): void; + end(str: string, encoding?: string, cb?: Function): void; + end(data?: any, encoding?: string): void; + + /** + * events.EventEmitter + * 1. close + * 2. connect + * 3. data + * 4. drain + * 5. end + * 6. error + * 7. lookup + * 8. timeout + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "close", listener: (had_error: boolean) => void): this; + addListener(event: "connect", listener: () => void): this; + addListener(event: "data", listener: (data: Buffer) => void): this; + addListener(event: "drain", listener: () => void): this; + addListener(event: "end", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "lookup", listener: (err: Error, address: string, family: string | number, host: string) => void): this; + addListener(event: "timeout", listener: () => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "close", had_error: boolean): boolean; + emit(event: "connect"): boolean; + emit(event: "data", data: Buffer): boolean; + emit(event: "drain"): boolean; + emit(event: "end"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "lookup", err: Error, address: string, family: string | number, host: string): boolean; + emit(event: "timeout"): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: (had_error: boolean) => void): this; + on(event: "connect", listener: () => void): this; + on(event: "data", listener: (data: Buffer) => void): this; + on(event: "drain", listener: () => void): this; + on(event: "end", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "lookup", listener: (err: Error, address: string, family: string | number, host: string) => void): this; + on(event: "timeout", listener: () => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: (had_error: boolean) => void): this; + once(event: "connect", listener: () => void): this; + once(event: "data", listener: (data: Buffer) => void): this; + once(event: "drain", listener: () => void): this; + once(event: "end", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "lookup", listener: (err: Error, address: string, family: string | number, host: string) => void): this; + once(event: "timeout", listener: () => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: (had_error: boolean) => void): this; + prependListener(event: "connect", listener: () => void): this; + prependListener(event: "data", listener: (data: Buffer) => void): this; + prependListener(event: "drain", listener: () => void): this; + prependListener(event: "end", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "lookup", listener: (err: Error, address: string, family: string | number, host: string) => void): this; + prependListener(event: "timeout", listener: () => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: (had_error: boolean) => void): this; + prependOnceListener(event: "connect", listener: () => void): this; + prependOnceListener(event: "data", listener: (data: Buffer) => void): this; + prependOnceListener(event: "drain", listener: () => void): this; + prependOnceListener(event: "end", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "lookup", listener: (err: Error, address: string, family: string | number, host: string) => void): this; + prependOnceListener(event: "timeout", listener: () => void): this; + } + + interface ListenOptions { + port?: number; + host?: string; + backlog?: number; + path?: string; + exclusive?: boolean; + readableAll?: boolean; + writableAll?: boolean; + } + + // https://github.com/nodejs/node/blob/master/lib/net.js + class Server extends events.EventEmitter { + constructor(connectionListener?: (socket: Socket) => void); + constructor(options?: { allowHalfOpen?: boolean, pauseOnConnect?: boolean }, connectionListener?: (socket: Socket) => void); + + listen(port?: number, hostname?: string, backlog?: number, listeningListener?: Function): this; + listen(port?: number, hostname?: string, listeningListener?: Function): this; + listen(port?: number, backlog?: number, listeningListener?: Function): this; + listen(port?: number, listeningListener?: Function): this; + listen(path: string, backlog?: number, listeningListener?: Function): this; + listen(path: string, listeningListener?: Function): this; + listen(options: ListenOptions, listeningListener?: Function): this; + listen(handle: any, backlog?: number, listeningListener?: Function): this; + listen(handle: any, listeningListener?: Function): this; + close(callback?: Function): this; + address(): AddressInfo | string; + getConnections(cb: (error: Error | null, count: number) => void): void; + ref(): this; + unref(): this; + maxConnections: number; + connections: number; + listening: boolean; + + /** + * events.EventEmitter + * 1. close + * 2. connection + * 3. error + * 4. listening + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "connection", listener: (socket: Socket) => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "listening", listener: () => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "close"): boolean; + emit(event: "connection", socket: Socket): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "listening"): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: () => void): this; + on(event: "connection", listener: (socket: Socket) => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "listening", listener: () => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "connection", listener: (socket: Socket) => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "listening", listener: () => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "connection", listener: (socket: Socket) => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "listening", listener: () => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "connection", listener: (socket: Socket) => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "listening", listener: () => void): this; + } + + interface TcpNetConnectOpts extends TcpSocketConnectOpts, SocketConstructorOpts { + timeout?: number; + } + + interface IpcNetConnectOpts extends IpcSocketConnectOpts, SocketConstructorOpts { + timeout?: number; + } + + type NetConnectOpts = TcpNetConnectOpts | IpcNetConnectOpts; + + function createServer(connectionListener?: (socket: Socket) => void): Server; + function createServer(options?: { allowHalfOpen?: boolean, pauseOnConnect?: boolean }, connectionListener?: (socket: Socket) => void): Server; + function connect(options: NetConnectOpts, connectionListener?: Function): Socket; + function connect(port: number, host?: string, connectionListener?: Function): Socket; + function connect(path: string, connectionListener?: Function): Socket; + function createConnection(options: NetConnectOpts, connectionListener?: Function): Socket; + function createConnection(port: number, host?: string, connectionListener?: Function): Socket; + function createConnection(path: string, connectionListener?: Function): Socket; + function isIP(input: string): number; + function isIPv4(input: string): boolean; + function isIPv6(input: string): boolean; +} + +declare module "dgram" { + import { AddressInfo } from "net"; + import * as dns from "dns"; + import * as events from "events"; + + interface RemoteInfo { + address: string; + family: string; + port: number; + } + + interface BindOptions { + port: number; + address?: string; + exclusive?: boolean; + } + + type SocketType = "udp4" | "udp6"; + + interface SocketOptions { + type: SocketType; + reuseAddr?: boolean; + recvBufferSize?: number; + sendBufferSize?: number; + lookup?: (hostname: string, options: dns.LookupOneOptions, callback: (err: NodeJS.ErrnoException, address: string, family: number) => void) => void; + } + + function createSocket(type: SocketType, callback?: (msg: Buffer, rinfo: RemoteInfo) => void): Socket; + function createSocket(options: SocketOptions, callback?: (msg: Buffer, rinfo: RemoteInfo) => void): Socket; + + class Socket extends events.EventEmitter { + send(msg: Buffer | string | Uint8Array | any[], port: number, address?: string, callback?: (error: Error | null, bytes: number) => void): void; + send(msg: Buffer | string | Uint8Array, offset: number, length: number, port: number, address?: string, callback?: (error: Error | null, bytes: number) => void): void; + bind(port?: number, address?: string, callback?: () => void): void; + bind(port?: number, callback?: () => void): void; + bind(callback?: () => void): void; + bind(options: BindOptions, callback?: Function): void; + close(callback?: () => void): void; + address(): AddressInfo | string; + setBroadcast(flag: boolean): void; + setTTL(ttl: number): void; + setMulticastTTL(ttl: number): void; + setMulticastInterface(multicastInterface: string): void; + setMulticastLoopback(flag: boolean): void; + addMembership(multicastAddress: string, multicastInterface?: string): void; + dropMembership(multicastAddress: string, multicastInterface?: string): void; + ref(): this; + unref(): this; + setRecvBufferSize(size: number): void; + setSendBufferSize(size: number): void; + getRecvBufferSize(): number; + getSendBufferSize(): number; + + /** + * events.EventEmitter + * 1. close + * 2. error + * 3. listening + * 4. message + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "listening", listener: () => void): this; + addListener(event: "message", listener: (msg: Buffer, rinfo: AddressInfo) => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "close"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "listening"): boolean; + emit(event: "message", msg: Buffer, rinfo: AddressInfo): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "listening", listener: () => void): this; + on(event: "message", listener: (msg: Buffer, rinfo: AddressInfo) => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "listening", listener: () => void): this; + once(event: "message", listener: (msg: Buffer, rinfo: AddressInfo) => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "listening", listener: () => void): this; + prependListener(event: "message", listener: (msg: Buffer, rinfo: AddressInfo) => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "listening", listener: () => void): this; + prependOnceListener(event: "message", listener: (msg: Buffer, rinfo: AddressInfo) => void): this; + } +} + +declare module "fs" { + import * as stream from "stream"; + import * as events from "events"; + import { URL } from "url"; + + /** + * Valid types for path values in "fs". + */ + type PathLike = string | Buffer | URL; + + type BinaryData = Buffer | DataView | NodeJS.TypedArray; + class Stats { + isFile(): boolean; + isDirectory(): boolean; + isBlockDevice(): boolean; + isCharacterDevice(): boolean; + isSymbolicLink(): boolean; + isFIFO(): boolean; + isSocket(): boolean; + dev: number; + ino: number; + mode: number; + nlink: number; + uid: number; + gid: number; + rdev: number; + size: number; + blksize: number; + blocks: number; + atimeMs: number; + mtimeMs: number; + ctimeMs: number; + birthtimeMs: number; + atime: Date; + mtime: Date; + ctime: Date; + birthtime: Date; + } + + class Dirent { + isFile(): boolean; + isDirectory(): boolean; + isBlockDevice(): boolean; + isCharacterDevice(): boolean; + isSymbolicLink(): boolean; + isFIFO(): boolean; + isSocket(): boolean; + name: string; + } + + interface FSWatcher extends events.EventEmitter { + close(): void; + + /** + * events.EventEmitter + * 1. change + * 2. error + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; + addListener(event: "error", listener: (error: Error) => void): this; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; + on(event: "error", listener: (error: Error) => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; + once(event: "error", listener: (error: Error) => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; + prependListener(event: "error", listener: (error: Error) => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; + prependOnceListener(event: "error", listener: (error: Error) => void): this; + } + + class ReadStream extends stream.Readable { + close(): void; + bytesRead: number; + path: string | Buffer; + + /** + * events.EventEmitter + * 1. open + * 2. close + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "open", listener: (fd: number) => void): this; + addListener(event: "close", listener: () => void): this; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "open", listener: (fd: number) => void): this; + on(event: "close", listener: () => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "open", listener: (fd: number) => void): this; + once(event: "close", listener: () => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "open", listener: (fd: number) => void): this; + prependListener(event: "close", listener: () => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "open", listener: (fd: number) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + } + + class WriteStream extends stream.Writable { + close(): void; + bytesWritten: number; + path: string | Buffer; + + /** + * events.EventEmitter + * 1. open + * 2. close + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "open", listener: (fd: number) => void): this; + addListener(event: "close", listener: () => void): this; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "open", listener: (fd: number) => void): this; + on(event: "close", listener: () => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "open", listener: (fd: number) => void): this; + once(event: "close", listener: () => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "open", listener: (fd: number) => void): this; + prependListener(event: "close", listener: () => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "open", listener: (fd: number) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + } + + /** + * Asynchronous rename(2) - Change the name or location of a file or directory. + * @param oldPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function rename(oldPath: PathLike, newPath: PathLike, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace rename { + /** + * Asynchronous rename(2) - Change the name or location of a file or directory. + * @param oldPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function __promisify__(oldPath: PathLike, newPath: PathLike): Promise; + } + + /** + * Synchronous rename(2) - Change the name or location of a file or directory. + * @param oldPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function renameSync(oldPath: PathLike, newPath: PathLike): void; + + /** + * Asynchronous truncate(2) - Truncate a file to a specified length. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param len If not specified, defaults to `0`. + */ + function truncate(path: PathLike, len: number | undefined | null, callback: (err: NodeJS.ErrnoException) => void): void; + + /** + * Asynchronous truncate(2) - Truncate a file to a specified length. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function truncate(path: PathLike, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace truncate { + /** + * Asynchronous truncate(2) - Truncate a file to a specified length. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param len If not specified, defaults to `0`. + */ + function __promisify__(path: PathLike, len?: number | null): Promise; + } + + /** + * Synchronous truncate(2) - Truncate a file to a specified length. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param len If not specified, defaults to `0`. + */ + function truncateSync(path: PathLike, len?: number | null): void; + + /** + * Asynchronous ftruncate(2) - Truncate a file to a specified length. + * @param fd A file descriptor. + * @param len If not specified, defaults to `0`. + */ + function ftruncate(fd: number, len: number | undefined | null, callback: (err: NodeJS.ErrnoException) => void): void; + + /** + * Asynchronous ftruncate(2) - Truncate a file to a specified length. + * @param fd A file descriptor. + */ + function ftruncate(fd: number, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace ftruncate { + /** + * Asynchronous ftruncate(2) - Truncate a file to a specified length. + * @param fd A file descriptor. + * @param len If not specified, defaults to `0`. + */ + function __promisify__(fd: number, len?: number | null): Promise; + } + + /** + * Synchronous ftruncate(2) - Truncate a file to a specified length. + * @param fd A file descriptor. + * @param len If not specified, defaults to `0`. + */ + function ftruncateSync(fd: number, len?: number | null): void; + + /** + * Asynchronous chown(2) - Change ownership of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function chown(path: PathLike, uid: number, gid: number, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace chown { + /** + * Asynchronous chown(2) - Change ownership of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(path: PathLike, uid: number, gid: number): Promise; + } + + /** + * Synchronous chown(2) - Change ownership of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function chownSync(path: PathLike, uid: number, gid: number): void; + + /** + * Asynchronous fchown(2) - Change ownership of a file. + * @param fd A file descriptor. + */ + function fchown(fd: number, uid: number, gid: number, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace fchown { + /** + * Asynchronous fchown(2) - Change ownership of a file. + * @param fd A file descriptor. + */ + function __promisify__(fd: number, uid: number, gid: number): Promise; + } + + /** + * Synchronous fchown(2) - Change ownership of a file. + * @param fd A file descriptor. + */ + function fchownSync(fd: number, uid: number, gid: number): void; + + /** + * Asynchronous lchown(2) - Change ownership of a file. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function lchown(path: PathLike, uid: number, gid: number, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace lchown { + /** + * Asynchronous lchown(2) - Change ownership of a file. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(path: PathLike, uid: number, gid: number): Promise; + } + + /** + * Synchronous lchown(2) - Change ownership of a file. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function lchownSync(path: PathLike, uid: number, gid: number): void; + + /** + * Asynchronous chmod(2) - Change permissions of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function chmod(path: PathLike, mode: string | number, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace chmod { + /** + * Asynchronous chmod(2) - Change permissions of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function __promisify__(path: PathLike, mode: string | number): Promise; + } + + /** + * Synchronous chmod(2) - Change permissions of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function chmodSync(path: PathLike, mode: string | number): void; + + /** + * Asynchronous fchmod(2) - Change permissions of a file. + * @param fd A file descriptor. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function fchmod(fd: number, mode: string | number, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace fchmod { + /** + * Asynchronous fchmod(2) - Change permissions of a file. + * @param fd A file descriptor. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function __promisify__(fd: number, mode: string | number): Promise; + } + + /** + * Synchronous fchmod(2) - Change permissions of a file. + * @param fd A file descriptor. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function fchmodSync(fd: number, mode: string | number): void; + + /** + * Asynchronous lchmod(2) - Change permissions of a file. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function lchmod(path: PathLike, mode: string | number, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace lchmod { + /** + * Asynchronous lchmod(2) - Change permissions of a file. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function __promisify__(path: PathLike, mode: string | number): Promise; + } + + /** + * Synchronous lchmod(2) - Change permissions of a file. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function lchmodSync(path: PathLike, mode: string | number): void; + + /** + * Asynchronous stat(2) - Get file status. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function stat(path: PathLike, callback: (err: NodeJS.ErrnoException, stats: Stats) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace stat { + /** + * Asynchronous stat(2) - Get file status. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(path: PathLike): Promise; + } + + /** + * Synchronous stat(2) - Get file status. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function statSync(path: PathLike): Stats; + + /** + * Asynchronous fstat(2) - Get file status. + * @param fd A file descriptor. + */ + function fstat(fd: number, callback: (err: NodeJS.ErrnoException, stats: Stats) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace fstat { + /** + * Asynchronous fstat(2) - Get file status. + * @param fd A file descriptor. + */ + function __promisify__(fd: number): Promise; + } + + /** + * Synchronous fstat(2) - Get file status. + * @param fd A file descriptor. + */ + function fstatSync(fd: number): Stats; + + /** + * Asynchronous lstat(2) - Get file status. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function lstat(path: PathLike, callback: (err: NodeJS.ErrnoException, stats: Stats) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace lstat { + /** + * Asynchronous lstat(2) - Get file status. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(path: PathLike): Promise; + } + + /** + * Synchronous lstat(2) - Get file status. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function lstatSync(path: PathLike): Stats; + + /** + * Asynchronous link(2) - Create a new link (also known as a hard link) to an existing file. + * @param existingPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function link(existingPath: PathLike, newPath: PathLike, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace link { + /** + * Asynchronous link(2) - Create a new link (also known as a hard link) to an existing file. + * @param existingPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function link(existingPath: PathLike, newPath: PathLike): Promise; + } + + /** + * Synchronous link(2) - Create a new link (also known as a hard link) to an existing file. + * @param existingPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function linkSync(existingPath: PathLike, newPath: PathLike): void; + + /** + * Asynchronous symlink(2) - Create a new symbolic link to an existing file. + * @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol. + * @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol. + * @param type May be set to `'dir'`, `'file'`, or `'junction'` (default is `'file'`) and is only available on Windows (ignored on other platforms). + * When using `'junction'`, the `target` argument will automatically be normalized to an absolute path. + */ + function symlink(target: PathLike, path: PathLike, type: symlink.Type | undefined | null, callback: (err: NodeJS.ErrnoException) => void): void; + + /** + * Asynchronous symlink(2) - Create a new symbolic link to an existing file. + * @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol. + * @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol. + */ + function symlink(target: PathLike, path: PathLike, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace symlink { + /** + * Asynchronous symlink(2) - Create a new symbolic link to an existing file. + * @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol. + * @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol. + * @param type May be set to `'dir'`, `'file'`, or `'junction'` (default is `'file'`) and is only available on Windows (ignored on other platforms). + * When using `'junction'`, the `target` argument will automatically be normalized to an absolute path. + */ + function __promisify__(target: PathLike, path: PathLike, type?: string | null): Promise; + + type Type = "dir" | "file" | "junction"; + } + + /** + * Synchronous symlink(2) - Create a new symbolic link to an existing file. + * @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol. + * @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol. + * @param type May be set to `'dir'`, `'file'`, or `'junction'` (default is `'file'`) and is only available on Windows (ignored on other platforms). + * When using `'junction'`, the `target` argument will automatically be normalized to an absolute path. + */ + function symlinkSync(target: PathLike, path: PathLike, type?: symlink.Type | null): void; + + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readlink(path: PathLike, options: { encoding?: BufferEncoding | null } | BufferEncoding | undefined | null, callback: (err: NodeJS.ErrnoException, linkString: string) => void): void; + + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readlink(path: PathLike, options: { encoding: "buffer" } | "buffer", callback: (err: NodeJS.ErrnoException, linkString: Buffer) => void): void; + + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readlink(path: PathLike, options: { encoding?: string | null } | string | undefined | null, callback: (err: NodeJS.ErrnoException, linkString: string | Buffer) => void): void; + + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function readlink(path: PathLike, callback: (err: NodeJS.ErrnoException, linkString: string) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace readlink { + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): Promise; + + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options: { encoding: "buffer" } | "buffer"): Promise; + + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options?: { encoding?: string | null } | string | null): Promise; + } + + /** + * Synchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readlinkSync(path: PathLike, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): string; + + /** + * Synchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readlinkSync(path: PathLike, options: { encoding: "buffer" } | "buffer"): Buffer; + + /** + * Synchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readlinkSync(path: PathLike, options?: { encoding?: string | null } | string | null): string | Buffer; + + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function realpath(path: PathLike, options: { encoding?: BufferEncoding | null } | BufferEncoding | undefined | null, callback: (err: NodeJS.ErrnoException, resolvedPath: string) => void): void; + + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function realpath(path: PathLike, options: { encoding: "buffer" } | "buffer", callback: (err: NodeJS.ErrnoException, resolvedPath: Buffer) => void): void; + + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function realpath(path: PathLike, options: { encoding?: string | null } | string | undefined | null, callback: (err: NodeJS.ErrnoException, resolvedPath: string | Buffer) => void): void; + + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function realpath(path: PathLike, callback: (err: NodeJS.ErrnoException, resolvedPath: string) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace realpath { + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): Promise; + + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options: { encoding: "buffer" } | "buffer"): Promise; + + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options?: { encoding?: string | null } | string | null): Promise; + + function native(path: PathLike, options: { encoding?: BufferEncoding | null } | BufferEncoding | undefined | null, callback: (err: NodeJS.ErrnoException, resolvedPath: string) => void): void; + function native(path: PathLike, options: { encoding: "buffer" } | "buffer", callback: (err: NodeJS.ErrnoException, resolvedPath: Buffer) => void): void; + function native(path: PathLike, options: { encoding?: string | null } | string | undefined | null, callback: (err: NodeJS.ErrnoException, resolvedPath: string | Buffer) => void): void; + function native(path: PathLike, callback: (err: NodeJS.ErrnoException, resolvedPath: string) => void): void; + } + + /** + * Synchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function realpathSync(path: PathLike, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): string; + + /** + * Synchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function realpathSync(path: PathLike, options: { encoding: "buffer" } | "buffer"): Buffer; + + /** + * Synchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function realpathSync(path: PathLike, options?: { encoding?: string | null } | string | null): string | Buffer; + + namespace realpathSync { + function native(path: PathLike, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): string; + function native(path: PathLike, options: { encoding: "buffer" } | "buffer"): Buffer; + function native(path: PathLike, options?: { encoding?: string | null } | string | null): string | Buffer; + } + + /** + * Asynchronous unlink(2) - delete a name and possibly the file it refers to. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function unlink(path: PathLike, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace unlink { + /** + * Asynchronous unlink(2) - delete a name and possibly the file it refers to. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(path: PathLike): Promise; + } + + /** + * Synchronous unlink(2) - delete a name and possibly the file it refers to. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function unlinkSync(path: PathLike): void; + + /** + * Asynchronous rmdir(2) - delete a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function rmdir(path: PathLike, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace rmdir { + /** + * Asynchronous rmdir(2) - delete a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(path: PathLike): Promise; + } + + /** + * Synchronous rmdir(2) - delete a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function rmdirSync(path: PathLike): void; + + export interface MakeDirectoryOptions { + /** + * Indicates whether parent folders should be created. + * @default false + */ + recursive?: boolean; + /** + * A file mode. If a string is passed, it is parsed as an octal integer. If not specified + * @default 0o777. + */ + mode?: number; + } + + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function mkdir(path: PathLike, options: number | string | MakeDirectoryOptions | undefined | null, callback: (err: NodeJS.ErrnoException) => void): void; + + /** + * Asynchronous mkdir(2) - create a directory with a mode of `0o777`. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function mkdir(path: PathLike, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace mkdir { + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function __promisify__(path: PathLike, options?: number | string | MakeDirectoryOptions | null): Promise; + } + + /** + * Synchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function mkdirSync(path: PathLike, options?: number | string | MakeDirectoryOptions | null): void; + + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function mkdtemp(prefix: string, options: { encoding?: BufferEncoding | null } | BufferEncoding | undefined | null, callback: (err: NodeJS.ErrnoException, folder: string) => void): void; + + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function mkdtemp(prefix: string, options: "buffer" | { encoding: "buffer" }, callback: (err: NodeJS.ErrnoException, folder: Buffer) => void): void; + + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function mkdtemp(prefix: string, options: { encoding?: string | null } | string | undefined | null, callback: (err: NodeJS.ErrnoException, folder: string | Buffer) => void): void; + + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + */ + function mkdtemp(prefix: string, callback: (err: NodeJS.ErrnoException, folder: string) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace mkdtemp { + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(prefix: string, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): Promise; + + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(prefix: string, options: { encoding: "buffer" } | "buffer"): Promise; + + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(prefix: string, options?: { encoding?: string | null } | string | null): Promise; + } + + /** + * Synchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function mkdtempSync(prefix: string, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): string; + + /** + * Synchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function mkdtempSync(prefix: string, options: { encoding: "buffer" } | "buffer"): Buffer; + + /** + * Synchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function mkdtempSync(prefix: string, options?: { encoding?: string | null } | string | null): string | Buffer; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readdir( + path: PathLike, + options: { encoding: BufferEncoding | null; withFileTypes?: false } | BufferEncoding | undefined | null, + callback: (err: NodeJS.ErrnoException, files: string[]) => void, + ): void; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readdir(path: PathLike, options: { encoding: "buffer"; withFileTypes?: false } | "buffer", callback: (err: NodeJS.ErrnoException, files: Buffer[]) => void): void; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readdir( + path: PathLike, + options: { encoding?: string | null; withFileTypes?: false } | string | undefined | null, + callback: (err: NodeJS.ErrnoException, files: string[] | Buffer[]) => void, + ): void; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function readdir(path: PathLike, callback: (err: NodeJS.ErrnoException, files: string[]) => void): void; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options If called with `withFileTypes: true` the result data will be an array of Dirent. + */ + function readdir(path: PathLike, options: { withFileTypes: true }, callback: (err: NodeJS.ErrnoException, files: Dirent[]) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace readdir { + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options?: { encoding: BufferEncoding | null; withFileTypes?: false } | BufferEncoding | null): Promise; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options: "buffer" | { encoding: "buffer"; withFileTypes?: false }): Promise; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options?: { encoding?: string | null; withFileTypes?: false } | string | null): Promise; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options If called with `withFileTypes: true` the result data will be an array of Dirent + */ + function __promisify__(path: PathLike, options: { withFileTypes: true }): Promise; + } + + /** + * Synchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readdirSync(path: PathLike, options?: { encoding: BufferEncoding | null; withFileTypes?: false } | BufferEncoding | null): string[]; + + /** + * Synchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readdirSync(path: PathLike, options: { encoding: "buffer"; withFileTypes?: false } | "buffer"): Buffer[]; + + /** + * Synchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readdirSync(path: PathLike, options?: { encoding?: string | null; withFileTypes?: false } | string | null): string[] | Buffer[]; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options If called with `withFileTypes: true` the result data will be an array of Dirent. + */ + function readdirSync(path: PathLike, options: { withFileTypes: true }): Dirent[]; + + /** + * Asynchronous close(2) - close a file descriptor. + * @param fd A file descriptor. + */ + function close(fd: number, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace close { + /** + * Asynchronous close(2) - close a file descriptor. + * @param fd A file descriptor. + */ + function __promisify__(fd: number): Promise; + } + + /** + * Synchronous close(2) - close a file descriptor. + * @param fd A file descriptor. + */ + function closeSync(fd: number): void; + + /** + * Asynchronous open(2) - open and possibly create a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. If not supplied, defaults to `0o666`. + */ + function open(path: PathLike, flags: string | number, mode: string | number | undefined | null, callback: (err: NodeJS.ErrnoException, fd: number) => void): void; + + /** + * Asynchronous open(2) - open and possibly create a file. If the file is created, its mode will be `0o666`. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function open(path: PathLike, flags: string | number, callback: (err: NodeJS.ErrnoException, fd: number) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace open { + /** + * Asynchronous open(2) - open and possibly create a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. If not supplied, defaults to `0o666`. + */ + function __promisify__(path: PathLike, flags: string | number, mode?: string | number | null): Promise; + } + + /** + * Synchronous open(2) - open and possibly create a file, returning a file descriptor.. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. If not supplied, defaults to `0o666`. + */ + function openSync(path: PathLike, flags: string | number, mode?: string | number | null): number; + + /** + * Asynchronously change file timestamps of the file referenced by the supplied path. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + function utimes(path: PathLike, atime: string | number | Date, mtime: string | number | Date, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace utimes { + /** + * Asynchronously change file timestamps of the file referenced by the supplied path. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + function __promisify__(path: PathLike, atime: string | number | Date, mtime: string | number | Date): Promise; + } + + /** + * Synchronously change file timestamps of the file referenced by the supplied path. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + function utimesSync(path: PathLike, atime: string | number | Date, mtime: string | number | Date): void; + + /** + * Asynchronously change file timestamps of the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + function futimes(fd: number, atime: string | number | Date, mtime: string | number | Date, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace futimes { + /** + * Asynchronously change file timestamps of the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + function __promisify__(fd: number, atime: string | number | Date, mtime: string | number | Date): Promise; + } + + /** + * Synchronously change file timestamps of the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + function futimesSync(fd: number, atime: string | number | Date, mtime: string | number | Date): void; + + /** + * Asynchronous fsync(2) - synchronize a file's in-core state with the underlying storage device. + * @param fd A file descriptor. + */ + function fsync(fd: number, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace fsync { + /** + * Asynchronous fsync(2) - synchronize a file's in-core state with the underlying storage device. + * @param fd A file descriptor. + */ + function __promisify__(fd: number): Promise; + } + + /** + * Synchronous fsync(2) - synchronize a file's in-core state with the underlying storage device. + * @param fd A file descriptor. + */ + function fsyncSync(fd: number): void; + + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + */ + function write( + fd: number, + buffer: TBuffer, + offset: number | undefined | null, + length: number | undefined | null, + position: number | undefined | null, + callback: (err: NodeJS.ErrnoException, written: number, buffer: TBuffer) => void, + ): void; + + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. + */ + function write( + fd: number, + buffer: TBuffer, + offset: number | undefined | null, + length: number | undefined | null, + callback: (err: NodeJS.ErrnoException, written: number, buffer: TBuffer) => void, + ): void; + + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + */ + function write(fd: number, buffer: TBuffer, offset: number | undefined | null, callback: (err: NodeJS.ErrnoException, written: number, buffer: TBuffer) => void): void; + + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + */ + function write(fd: number, buffer: TBuffer, callback: (err: NodeJS.ErrnoException, written: number, buffer: TBuffer) => void): void; + + /** + * Asynchronously writes `string` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param string A string to write. If something other than a string is supplied it will be coerced to a string. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + * @param encoding The expected string encoding. + */ + function write( + fd: number, + string: any, + position: number | undefined | null, + encoding: string | undefined | null, + callback: (err: NodeJS.ErrnoException, written: number, str: string) => void, + ): void; + + /** + * Asynchronously writes `string` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param string A string to write. If something other than a string is supplied it will be coerced to a string. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + */ + function write(fd: number, string: any, position: number | undefined | null, callback: (err: NodeJS.ErrnoException, written: number, str: string) => void): void; + + /** + * Asynchronously writes `string` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param string A string to write. If something other than a string is supplied it will be coerced to a string. + */ + function write(fd: number, string: any, callback: (err: NodeJS.ErrnoException, written: number, str: string) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace write { + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + */ + function __promisify__( + fd: number, + buffer?: TBuffer, + offset?: number, + length?: number, + position?: number | null, + ): Promise<{ bytesWritten: number, buffer: TBuffer }>; + + /** + * Asynchronously writes `string` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param string A string to write. If something other than a string is supplied it will be coerced to a string. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + * @param encoding The expected string encoding. + */ + function __promisify__(fd: number, string: any, position?: number | null, encoding?: string | null): Promise<{ bytesWritten: number, buffer: string }>; + } + + /** + * Synchronously writes `buffer` to the file referenced by the supplied file descriptor, returning the number of bytes written. + * @param fd A file descriptor. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + */ + function writeSync(fd: number, buffer: BinaryData, offset?: number | null, length?: number | null, position?: number | null): number; + + /** + * Synchronously writes `string` to the file referenced by the supplied file descriptor, returning the number of bytes written. + * @param fd A file descriptor. + * @param string A string to write. If something other than a string is supplied it will be coerced to a string. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + * @param encoding The expected string encoding. + */ + function writeSync(fd: number, string: any, position?: number | null, encoding?: string | null): number; + + /** + * Asynchronously reads data from the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param buffer The buffer that the data will be written to. + * @param offset The offset in the buffer at which to start writing. + * @param length The number of bytes to read. + * @param position The offset from the beginning of the file from which data should be read. If `null`, data will be read from the current position. + */ + function read( + fd: number, + buffer: TBuffer, + offset: number, + length: number, + position: number | null, + callback?: (err: NodeJS.ErrnoException, bytesRead: number, buffer: TBuffer) => void, + ): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace read { + /** + * @param fd A file descriptor. + * @param buffer The buffer that the data will be written to. + * @param offset The offset in the buffer at which to start writing. + * @param length The number of bytes to read. + * @param position The offset from the beginning of the file from which data should be read. If `null`, data will be read from the current position. + */ + function __promisify__(fd: number, buffer: TBuffer, offset: number, length: number, position: number | null): Promise<{ bytesRead: number, buffer: TBuffer }>; + } + + /** + * Synchronously reads data from the file referenced by the supplied file descriptor, returning the number of bytes read. + * @param fd A file descriptor. + * @param buffer The buffer that the data will be written to. + * @param offset The offset in the buffer at which to start writing. + * @param length The number of bytes to read. + * @param position The offset from the beginning of the file from which data should be read. If `null`, data will be read from the current position. + */ + function readSync(fd: number, buffer: BinaryData, offset: number, length: number, position: number | null): number; + + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function readFile(path: PathLike | number, options: { encoding?: null; flag?: string; } | undefined | null, callback: (err: NodeJS.ErrnoException, data: Buffer) => void): void; + + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function readFile(path: PathLike | number, options: { encoding: string; flag?: string; } | string, callback: (err: NodeJS.ErrnoException, data: string) => void): void; + + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function readFile( + path: PathLike | number, + options: { encoding?: string | null; flag?: string; } | string | undefined | null, + callback: (err: NodeJS.ErrnoException, data: string | Buffer) => void, + ): void; + + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + */ + function readFile(path: PathLike | number, callback: (err: NodeJS.ErrnoException, data: Buffer) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace readFile { + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function __promisify__(path: PathLike | number, options?: { encoding?: null; flag?: string; } | null): Promise; + + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function __promisify__(path: PathLike | number, options: { encoding: string; flag?: string; } | string): Promise; + + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function __promisify__(path: PathLike | number, options?: { encoding?: string | null; flag?: string; } | string | null): Promise; + } + + /** + * Synchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options An object that may contain an optional flag. If a flag is not provided, it defaults to `'r'`. + */ + function readFileSync(path: PathLike | number, options?: { encoding?: null; flag?: string; } | null): Buffer; + + /** + * Synchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function readFileSync(path: PathLike | number, options: { encoding: string; flag?: string; } | string): string; + + /** + * Synchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function readFileSync(path: PathLike | number, options?: { encoding?: string | null; flag?: string; } | string | null): string | Buffer; + + type WriteFileOptions = { encoding?: string | null; mode?: number | string; flag?: string; } | string | null; + + /** + * Asynchronously writes data to a file, replacing the file if it already exists. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'w'` is used. + */ + function writeFile(path: PathLike | number, data: any, options: WriteFileOptions, callback: (err: NodeJS.ErrnoException) => void): void; + + /** + * Asynchronously writes data to a file, replacing the file if it already exists. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + */ + function writeFile(path: PathLike | number, data: any, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace writeFile { + /** + * Asynchronously writes data to a file, replacing the file if it already exists. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'w'` is used. + */ + function __promisify__(path: PathLike | number, data: any, options?: WriteFileOptions): Promise; + } + + /** + * Synchronously writes data to a file, replacing the file if it already exists. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'w'` is used. + */ + function writeFileSync(path: PathLike | number, data: any, options?: WriteFileOptions): void; + + /** + * Asynchronously append data to a file, creating the file if it does not exist. + * @param file A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'a'` is used. + */ + function appendFile(file: PathLike | number, data: any, options: WriteFileOptions, callback: (err: NodeJS.ErrnoException) => void): void; + + /** + * Asynchronously append data to a file, creating the file if it does not exist. + * @param file A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + */ + function appendFile(file: PathLike | number, data: any, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace appendFile { + /** + * Asynchronously append data to a file, creating the file if it does not exist. + * @param file A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'a'` is used. + */ + function __promisify__(file: PathLike | number, data: any, options?: WriteFileOptions): Promise; + } + + /** + * Synchronously append data to a file, creating the file if it does not exist. + * @param file A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'a'` is used. + */ + function appendFileSync(file: PathLike | number, data: any, options?: WriteFileOptions): void; + + /** + * Watch for changes on `filename`. The callback `listener` will be called each time the file is accessed. + */ + function watchFile(filename: PathLike, options: { persistent?: boolean; interval?: number; } | undefined, listener: (curr: Stats, prev: Stats) => void): void; + + /** + * Watch for changes on `filename`. The callback `listener` will be called each time the file is accessed. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function watchFile(filename: PathLike, listener: (curr: Stats, prev: Stats) => void): void; + + /** + * Stop watching for changes on `filename`. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function unwatchFile(filename: PathLike, listener?: (curr: Stats, prev: Stats) => void): void; + + /** + * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * @param options Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `persistent` is not supplied, the default of `true` is used. + * If `recursive` is not supplied, the default of `false` is used. + */ + function watch( + filename: PathLike, + options: { encoding?: BufferEncoding | null, persistent?: boolean, recursive?: boolean } | BufferEncoding | undefined | null, + listener?: (event: string, filename: string) => void, + ): FSWatcher; + + /** + * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * @param options Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `persistent` is not supplied, the default of `true` is used. + * If `recursive` is not supplied, the default of `false` is used. + */ + function watch(filename: PathLike, options: { encoding: "buffer", persistent?: boolean, recursive?: boolean } | "buffer", listener?: (event: string, filename: Buffer) => void): FSWatcher; + + /** + * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * @param options Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `persistent` is not supplied, the default of `true` is used. + * If `recursive` is not supplied, the default of `false` is used. + */ + function watch( + filename: PathLike, + options: { encoding?: string | null, persistent?: boolean, recursive?: boolean } | string | null, + listener?: (event: string, filename: string | Buffer) => void, + ): FSWatcher; + + /** + * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function watch(filename: PathLike, listener?: (event: string, filename: string) => any): FSWatcher; + + /** + * Asynchronously tests whether or not the given path exists by checking with the file system. + * @deprecated + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function exists(path: PathLike, callback: (exists: boolean) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace exists { + /** + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function __promisify__(path: PathLike): Promise; + } + + /** + * Synchronously tests whether or not the given path exists by checking with the file system. + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function existsSync(path: PathLike): boolean; + + namespace constants { + // File Access Constants + + /** Constant for fs.access(). File is visible to the calling process. */ + const F_OK: number; + + /** Constant for fs.access(). File can be read by the calling process. */ + const R_OK: number; + + /** Constant for fs.access(). File can be written by the calling process. */ + const W_OK: number; + + /** Constant for fs.access(). File can be executed by the calling process. */ + const X_OK: number; + + // File Copy Constants + + /** Constant for fs.copyFile. Flag indicating the destination file should not be overwritten if it already exists. */ + const COPYFILE_EXCL: number; + + /** + * Constant for fs.copyFile. copy operation will attempt to create a copy-on-write reflink. + * If the underlying platform does not support copy-on-write, then a fallback copy mechanism is used. + */ + const COPYFILE_FICLONE: number; + + /** + * Constant for fs.copyFile. Copy operation will attempt to create a copy-on-write reflink. + * If the underlying platform does not support copy-on-write, then the operation will fail with an error. + */ + const COPYFILE_FICLONE_FORCE: number; + + // File Open Constants + + /** Constant for fs.open(). Flag indicating to open a file for read-only access. */ + const O_RDONLY: number; + + /** Constant for fs.open(). Flag indicating to open a file for write-only access. */ + const O_WRONLY: number; + + /** Constant for fs.open(). Flag indicating to open a file for read-write access. */ + const O_RDWR: number; + + /** Constant for fs.open(). Flag indicating to create the file if it does not already exist. */ + const O_CREAT: number; + + /** Constant for fs.open(). Flag indicating that opening a file should fail if the O_CREAT flag is set and the file already exists. */ + const O_EXCL: number; + + /** + * Constant for fs.open(). Flag indicating that if path identifies a terminal device, + * opening the path shall not cause that terminal to become the controlling terminal for the process + * (if the process does not already have one). + */ + const O_NOCTTY: number; + + /** Constant for fs.open(). Flag indicating that if the file exists and is a regular file, and the file is opened successfully for write access, its length shall be truncated to zero. */ + const O_TRUNC: number; + + /** Constant for fs.open(). Flag indicating that data will be appended to the end of the file. */ + const O_APPEND: number; + + /** Constant for fs.open(). Flag indicating that the open should fail if the path is not a directory. */ + const O_DIRECTORY: number; + + /** + * constant for fs.open(). + * Flag indicating reading accesses to the file system will no longer result in + * an update to the atime information associated with the file. + * This flag is available on Linux operating systems only. + */ + const O_NOATIME: number; + + /** Constant for fs.open(). Flag indicating that the open should fail if the path is a symbolic link. */ + const O_NOFOLLOW: number; + + /** Constant for fs.open(). Flag indicating that the file is opened for synchronous I/O. */ + const O_SYNC: number; + + /** Constant for fs.open(). Flag indicating that the file is opened for synchronous I/O with write operations waiting for data integrity. */ + const O_DSYNC: number; + + /** Constant for fs.open(). Flag indicating to open the symbolic link itself rather than the resource it is pointing to. */ + const O_SYMLINK: number; + + /** Constant for fs.open(). When set, an attempt will be made to minimize caching effects of file I/O. */ + const O_DIRECT: number; + + /** Constant for fs.open(). Flag indicating to open the file in nonblocking mode when possible. */ + const O_NONBLOCK: number; + + // File Type Constants + + /** Constant for fs.Stats mode property for determining a file's type. Bit mask used to extract the file type code. */ + const S_IFMT: number; + + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a regular file. */ + const S_IFREG: number; + + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a directory. */ + const S_IFDIR: number; + + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a character-oriented device file. */ + const S_IFCHR: number; + + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a block-oriented device file. */ + const S_IFBLK: number; + + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a FIFO/pipe. */ + const S_IFIFO: number; + + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a symbolic link. */ + const S_IFLNK: number; + + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a socket. */ + const S_IFSOCK: number; + + // File Mode Constants + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by owner. */ + const S_IRWXU: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by owner. */ + const S_IRUSR: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by owner. */ + const S_IWUSR: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by owner. */ + const S_IXUSR: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by group. */ + const S_IRWXG: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by group. */ + const S_IRGRP: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by group. */ + const S_IWGRP: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by group. */ + const S_IXGRP: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by others. */ + const S_IRWXO: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by others. */ + const S_IROTH: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by others. */ + const S_IWOTH: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by others. */ + const S_IXOTH: number; + } + + /** + * Asynchronously tests a user's permissions for the file specified by path. + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function access(path: PathLike, mode: number | undefined, callback: (err: NodeJS.ErrnoException) => void): void; + + /** + * Asynchronously tests a user's permissions for the file specified by path. + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function access(path: PathLike, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace access { + /** + * Asynchronously tests a user's permissions for the file specified by path. + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function __promisify__(path: PathLike, mode?: number): Promise; + } + + /** + * Synchronously tests a user's permissions for the file specified by path. + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function accessSync(path: PathLike, mode?: number): void; + + /** + * Returns a new `ReadStream` object. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function createReadStream(path: PathLike, options?: string | { + flags?: string; + encoding?: string; + fd?: number; + mode?: number; + autoClose?: boolean; + start?: number; + end?: number; + highWaterMark?: number; + }): ReadStream; + + /** + * Returns a new `WriteStream` object. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function createWriteStream(path: PathLike, options?: string | { + flags?: string; + encoding?: string; + fd?: number; + mode?: number; + autoClose?: boolean; + start?: number; + }): WriteStream; + + /** + * Asynchronous fdatasync(2) - synchronize a file's in-core state with storage device. + * @param fd A file descriptor. + */ + function fdatasync(fd: number, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace fdatasync { + /** + * Asynchronous fdatasync(2) - synchronize a file's in-core state with storage device. + * @param fd A file descriptor. + */ + function __promisify__(fd: number): Promise; + } + + /** + * Synchronous fdatasync(2) - synchronize a file's in-core state with storage device. + * @param fd A file descriptor. + */ + function fdatasyncSync(fd: number): void; + + /** + * Asynchronously copies src to dest. By default, dest is overwritten if it already exists. + * No arguments other than a possible exception are given to the callback function. + * Node.js makes no guarantees about the atomicity of the copy operation. + * If an error occurs after the destination file has been opened for writing, Node.js will attempt + * to remove the destination. + * @param src A path to the source file. + * @param dest A path to the destination file. + */ + function copyFile(src: PathLike, dest: PathLike, callback: (err: NodeJS.ErrnoException) => void): void; + /** + * Asynchronously copies src to dest. By default, dest is overwritten if it already exists. + * No arguments other than a possible exception are given to the callback function. + * Node.js makes no guarantees about the atomicity of the copy operation. + * If an error occurs after the destination file has been opened for writing, Node.js will attempt + * to remove the destination. + * @param src A path to the source file. + * @param dest A path to the destination file. + * @param flags An integer that specifies the behavior of the copy operation. The only supported flag is fs.constants.COPYFILE_EXCL, which causes the copy operation to fail if dest already exists. + */ + function copyFile(src: PathLike, dest: PathLike, flags: number, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace copyFile { + /** + * Asynchronously copies src to dest. By default, dest is overwritten if it already exists. + * No arguments other than a possible exception are given to the callback function. + * Node.js makes no guarantees about the atomicity of the copy operation. + * If an error occurs after the destination file has been opened for writing, Node.js will attempt + * to remove the destination. + * @param src A path to the source file. + * @param dest A path to the destination file. + * @param flags An optional integer that specifies the behavior of the copy operation. + * The only supported flag is fs.constants.COPYFILE_EXCL, + * which causes the copy operation to fail if dest already exists. + */ + function __promisify__(src: PathLike, dst: PathLike, flags?: number): Promise; + } + + /** + * Synchronously copies src to dest. By default, dest is overwritten if it already exists. + * Node.js makes no guarantees about the atomicity of the copy operation. + * If an error occurs after the destination file has been opened for writing, Node.js will attempt + * to remove the destination. + * @param src A path to the source file. + * @param dest A path to the destination file. + * @param flags An optional integer that specifies the behavior of the copy operation. + * The only supported flag is fs.constants.COPYFILE_EXCL, which causes the copy operation to fail if dest already exists. + */ + function copyFileSync(src: PathLike, dest: PathLike, flags?: number): void; + + namespace promises { + interface FileHandle { + /** + * Gets the file descriptor for this file handle. + */ + readonly fd: number; + + /** + * Asynchronously append data to a file, creating the file if it does not exist. The underlying file will _not_ be closed automatically. + * The `FileHandle` must have been opened for appending. + * @param data The data to write. If something other than a `Buffer` or `Uint8Array` is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'a'` is used. + */ + appendFile(data: any, options?: { encoding?: string | null, mode?: string | number, flag?: string | number } | string | null): Promise; + + /** + * Asynchronous fchown(2) - Change ownership of a file. + */ + chown(uid: number, gid: number): Promise; + + /** + * Asynchronous fchmod(2) - Change permissions of a file. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + chmod(mode: string | number): Promise; + + /** + * Asynchronous fdatasync(2) - synchronize a file's in-core state with storage device. + */ + datasync(): Promise; + + /** + * Asynchronous fsync(2) - synchronize a file's in-core state with the underlying storage device. + */ + sync(): Promise; + + /** + * Asynchronously reads data from the file. + * The `FileHandle` must have been opened for reading. + * @param buffer The buffer that the data will be written to. + * @param offset The offset in the buffer at which to start writing. + * @param length The number of bytes to read. + * @param position The offset from the beginning of the file from which data should be read. If `null`, data will be read from the current position. + */ + read(buffer: TBuffer, offset?: number | null, length?: number | null, position?: number | null): Promise<{ bytesRead: number, buffer: TBuffer }>; + + /** + * Asynchronously reads the entire contents of a file. The underlying file will _not_ be closed automatically. + * The `FileHandle` must have been opened for reading. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + readFile(options?: { encoding?: null, flag?: string | number } | null): Promise; + + /** + * Asynchronously reads the entire contents of a file. The underlying file will _not_ be closed automatically. + * The `FileHandle` must have been opened for reading. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + readFile(options: { encoding: BufferEncoding, flag?: string | number } | BufferEncoding): Promise; + + /** + * Asynchronously reads the entire contents of a file. The underlying file will _not_ be closed automatically. + * The `FileHandle` must have been opened for reading. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + readFile(options?: { encoding?: string | null, flag?: string | number } | string | null): Promise; + + /** + * Asynchronous fstat(2) - Get file status. + */ + stat(): Promise; + + /** + * Asynchronous ftruncate(2) - Truncate a file to a specified length. + * @param len If not specified, defaults to `0`. + */ + truncate(len?: number): Promise; + + /** + * Asynchronously change file timestamps of the file. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + utimes(atime: string | number | Date, mtime: string | number | Date): Promise; + + /** + * Asynchronously writes `buffer` to the file. + * The `FileHandle` must have been opened for writing. + * @param buffer The buffer that the data will be written to. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + */ + write(buffer: TBuffer, offset?: number | null, length?: number | null, position?: number | null): Promise<{ bytesWritten: number, buffer: TBuffer }>; + + /** + * Asynchronously writes `string` to the file. + * The `FileHandle` must have been opened for writing. + * It is unsafe to call `write()` multiple times on the same file without waiting for the `Promise` + * to be resolved (or rejected). For this scenario, `fs.createWriteStream` is strongly recommended. + * @param string A string to write. If something other than a string is supplied it will be coerced to a string. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + * @param encoding The expected string encoding. + */ + write(data: any, position?: number | null, encoding?: string | null): Promise<{ bytesWritten: number, buffer: string }>; + + /** + * Asynchronously writes data to a file, replacing the file if it already exists. The underlying file will _not_ be closed automatically. + * The `FileHandle` must have been opened for writing. + * It is unsafe to call `writeFile()` multiple times on the same file without waiting for the `Promise` to be resolved (or rejected). + * @param data The data to write. If something other than a `Buffer` or `Uint8Array` is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'w'` is used. + */ + writeFile(data: any, options?: { encoding?: string | null, mode?: string | number, flag?: string | number } | string | null): Promise; + + /** + * Asynchronous close(2) - close a `FileHandle`. + */ + close(): Promise; + } + + /** + * Asynchronously tests a user's permissions for the file specified by path. + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function access(path: PathLike, mode?: number): Promise; + + /** + * Asynchronously copies `src` to `dest`. By default, `dest` is overwritten if it already exists. + * Node.js makes no guarantees about the atomicity of the copy operation. + * If an error occurs after the destination file has been opened for writing, Node.js will attempt + * to remove the destination. + * @param src A path to the source file. + * @param dest A path to the destination file. + * @param flags An optional integer that specifies the behavior of the copy operation. The only + * supported flag is `fs.constants.COPYFILE_EXCL`, which causes the copy operation to fail if + * `dest` already exists. + */ + function copyFile(src: PathLike, dest: PathLike, flags?: number): Promise; + + /** + * Asynchronous open(2) - open and possibly create a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. If not + * supplied, defaults to `0o666`. + */ + function open(path: PathLike, flags: string | number, mode?: string | number): Promise; + + /** + * Asynchronously reads data from the file referenced by the supplied `FileHandle`. + * @param handle A `FileHandle`. + * @param buffer The buffer that the data will be written to. + * @param offset The offset in the buffer at which to start writing. + * @param length The number of bytes to read. + * @param position The offset from the beginning of the file from which data should be read. If + * `null`, data will be read from the current position. + */ + function read( + handle: FileHandle, + buffer: TBuffer, + offset?: number | null, + length?: number | null, + position?: number | null, + ): Promise<{ bytesRead: number, buffer: TBuffer }>; + + /** + * Asynchronously writes `buffer` to the file referenced by the supplied `FileHandle`. + * It is unsafe to call `fsPromises.write()` multiple times on the same file without waiting for the `Promise` + * to be resolved (or rejected). For this scenario, `fs.createWriteStream` is strongly recommended. + * @param handle A `FileHandle`. + * @param buffer The buffer that the data will be written to. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + */ + function write( + handle: FileHandle, + buffer: TBuffer, + offset?: number | null, + length?: number | null, position?: number | null): Promise<{ bytesWritten: number, buffer: TBuffer }>; + + /** + * Asynchronously writes `string` to the file referenced by the supplied `FileHandle`. + * It is unsafe to call `fsPromises.write()` multiple times on the same file without waiting for the `Promise` + * to be resolved (or rejected). For this scenario, `fs.createWriteStream` is strongly recommended. + * @param handle A `FileHandle`. + * @param string A string to write. If something other than a string is supplied it will be coerced to a string. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + * @param encoding The expected string encoding. + */ + function write(handle: FileHandle, string: any, position?: number | null, encoding?: string | null): Promise<{ bytesWritten: number, buffer: string }>; + + /** + * Asynchronous rename(2) - Change the name or location of a file or directory. + * @param oldPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function rename(oldPath: PathLike, newPath: PathLike): Promise; + + /** + * Asynchronous truncate(2) - Truncate a file to a specified length. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param len If not specified, defaults to `0`. + */ + function truncate(path: PathLike, len?: number): Promise; + + /** + * Asynchronous ftruncate(2) - Truncate a file to a specified length. + * @param handle A `FileHandle`. + * @param len If not specified, defaults to `0`. + */ + function ftruncate(handle: FileHandle, len?: number): Promise; + + /** + * Asynchronous rmdir(2) - delete a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function rmdir(path: PathLike): Promise; + + /** + * Asynchronous fdatasync(2) - synchronize a file's in-core state with storage device. + * @param handle A `FileHandle`. + */ + function fdatasync(handle: FileHandle): Promise; + + /** + * Asynchronous fsync(2) - synchronize a file's in-core state with the underlying storage device. + * @param handle A `FileHandle`. + */ + function fsync(handle: FileHandle): Promise; + + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function mkdir(path: PathLike, options?: number | string | MakeDirectoryOptions | null): Promise; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readdir(path: PathLike, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): Promise; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readdir(path: PathLike, options: { encoding: "buffer" } | "buffer"): Promise; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readdir(path: PathLike, options?: { encoding?: string | null } | string | null): Promise; + + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readlink(path: PathLike, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): Promise; + + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readlink(path: PathLike, options: { encoding: "buffer" } | "buffer"): Promise; + + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readlink(path: PathLike, options?: { encoding?: string | null } | string | null): Promise; + + /** + * Asynchronous symlink(2) - Create a new symbolic link to an existing file. + * @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol. + * @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol. + * @param type May be set to `'dir'`, `'file'`, or `'junction'` (default is `'file'`) and is only available on Windows (ignored on other platforms). + * When using `'junction'`, the `target` argument will automatically be normalized to an absolute path. + */ + function symlink(target: PathLike, path: PathLike, type?: string | null): Promise; + + /** + * Asynchronous fstat(2) - Get file status. + * @param handle A `FileHandle`. + */ + function fstat(handle: FileHandle): Promise; + + /** + * Asynchronous lstat(2) - Get file status. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function lstat(path: PathLike): Promise; + + /** + * Asynchronous stat(2) - Get file status. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function stat(path: PathLike): Promise; + + /** + * Asynchronous link(2) - Create a new link (also known as a hard link) to an existing file. + * @param existingPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function link(existingPath: PathLike, newPath: PathLike): Promise; + + /** + * Asynchronous unlink(2) - delete a name and possibly the file it refers to. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function unlink(path: PathLike): Promise; + + /** + * Asynchronous fchmod(2) - Change permissions of a file. + * @param handle A `FileHandle`. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function fchmod(handle: FileHandle, mode: string | number): Promise; + + /** + * Asynchronous chmod(2) - Change permissions of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function chmod(path: PathLike, mode: string | number): Promise; + + /** + * Asynchronous lchmod(2) - Change permissions of a file. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function lchmod(path: PathLike, mode: string | number): Promise; + + /** + * Asynchronous lchown(2) - Change ownership of a file. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function lchown(path: PathLike, uid: number, gid: number): Promise; + + /** + * Asynchronous fchown(2) - Change ownership of a file. + * @param handle A `FileHandle`. + */ + function fchown(handle: FileHandle, uid: number, gid: number): Promise; + + /** + * Asynchronous chown(2) - Change ownership of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function chown(path: PathLike, uid: number, gid: number): Promise; + + /** + * Asynchronously change file timestamps of the file referenced by the supplied path. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + function utimes(path: PathLike, atime: string | number | Date, mtime: string | number | Date): Promise; + + /** + * Asynchronously change file timestamps of the file referenced by the supplied `FileHandle`. + * @param handle A `FileHandle`. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + function futimes(handle: FileHandle, atime: string | number | Date, mtime: string | number | Date): Promise; + + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function realpath(path: PathLike, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): Promise; + + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function realpath(path: PathLike, options: { encoding: "buffer" } | "buffer"): Promise; + + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function realpath(path: PathLike, options?: { encoding?: string | null } | string | null): Promise; + + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required `prefix` to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function mkdtemp(prefix: string, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): Promise; + + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required `prefix` to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function mkdtemp(prefix: string, options: { encoding: "buffer" } | "buffer"): Promise; + + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required `prefix` to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function mkdtemp(prefix: string, options?: { encoding?: string | null } | string | null): Promise; + + /** + * Asynchronously writes data to a file, replacing the file if it already exists. + * It is unsafe to call `fsPromises.writeFile()` multiple times on the same file without waiting for the `Promise` to be resolved (or rejected). + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a `FileHandle` is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a `Buffer` or `Uint8Array` is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'w'` is used. + */ + function writeFile(path: PathLike | FileHandle, data: any, options?: { encoding?: string | null, mode?: string | number, flag?: string | number } | string | null): Promise; + + /** + * Asynchronously append data to a file, creating the file if it does not exist. + * @param file A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a `FileHandle` is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a `Buffer` or `Uint8Array` is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'a'` is used. + */ + function appendFile(path: PathLike | FileHandle, data: any, options?: { encoding?: string | null, mode?: string | number, flag?: string | number } | string | null): Promise; + + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a `FileHandle` is provided, the underlying file will _not_ be closed automatically. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function readFile(path: PathLike | FileHandle, options?: { encoding?: null, flag?: string | number } | null): Promise; + + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a `FileHandle` is provided, the underlying file will _not_ be closed automatically. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function readFile(path: PathLike | FileHandle, options: { encoding: BufferEncoding, flag?: string | number } | BufferEncoding): Promise; + + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a `FileHandle` is provided, the underlying file will _not_ be closed automatically. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function readFile(path: PathLike | FileHandle, options?: { encoding?: string | null, flag?: string | number } | string | null): Promise; + } +} + +declare module "path" { + /** + * A parsed path object generated by path.parse() or consumed by path.format(). + */ + interface ParsedPath { + /** + * The root of the path such as '/' or 'c:\' + */ + root: string; + /** + * The full directory path such as '/home/user/dir' or 'c:\path\dir' + */ + dir: string; + /** + * The file name including extension (if any) such as 'index.html' + */ + base: string; + /** + * The file extension (if any) such as '.html' + */ + ext: string; + /** + * The file name without extension (if any) such as 'index' + */ + name: string; + } + interface FormatInputPathObject { + /** + * The root of the path such as '/' or 'c:\' + */ + root?: string; + /** + * The full directory path such as '/home/user/dir' or 'c:\path\dir' + */ + dir?: string; + /** + * The file name including extension (if any) such as 'index.html' + */ + base?: string; + /** + * The file extension (if any) such as '.html' + */ + ext?: string; + /** + * The file name without extension (if any) such as 'index' + */ + name?: string; + } + + /** + * Normalize a string path, reducing '..' and '.' parts. + * When multiple slashes are found, they're replaced by a single one; when the path contains a trailing slash, it is preserved. On Windows backslashes are used. + * + * @param p string path to normalize. + */ + function normalize(p: string): string; + /** + * Join all arguments together and normalize the resulting path. + * Arguments must be strings. In v0.8, non-string arguments were silently ignored. In v0.10 and up, an exception is thrown. + * + * @param paths paths to join. + */ + function join(...paths: string[]): string; + /** + * The right-most parameter is considered {to}. Other parameters are considered an array of {from}. + * + * Starting from leftmost {from} parameter, resolves {to} to an absolute path. + * + * If {to} isn't already absolute, {from} arguments are prepended in right to left order, + * until an absolute path is found. If after using all {from} paths still no absolute path is found, + * the current working directory is used as well. The resulting path is normalized, + * and trailing slashes are removed unless the path gets resolved to the root directory. + * + * @param pathSegments string paths to join. Non-string arguments are ignored. + */ + function resolve(...pathSegments: string[]): string; + /** + * Determines whether {path} is an absolute path. An absolute path will always resolve to the same location, regardless of the working directory. + * + * @param path path to test. + */ + function isAbsolute(path: string): boolean; + /** + * Solve the relative path from {from} to {to}. + * At times we have two absolute paths, and we need to derive the relative path from one to the other. This is actually the reverse transform of path.resolve. + */ + function relative(from: string, to: string): string; + /** + * Return the directory name of a path. Similar to the Unix dirname command. + * + * @param p the path to evaluate. + */ + function dirname(p: string): string; + /** + * Return the last portion of a path. Similar to the Unix basename command. + * Often used to extract the file name from a fully qualified path. + * + * @param p the path to evaluate. + * @param ext optionally, an extension to remove from the result. + */ + function basename(p: string, ext?: string): string; + /** + * Return the extension of the path, from the last '.' to end of string in the last portion of the path. + * If there is no '.' in the last portion of the path or the first character of it is '.', then it returns an empty string + * + * @param p the path to evaluate. + */ + function extname(p: string): string; + /** + * The platform-specific file separator. '\\' or '/'. + */ + const sep: '\\' | '/'; + /** + * The platform-specific file delimiter. ';' or ':'. + */ + const delimiter: ';' | ':'; + /** + * Returns an object from a path string - the opposite of format(). + * + * @param pathString path to evaluate. + */ + function parse(pathString: string): ParsedPath; + /** + * Returns a path string from an object - the opposite of parse(). + * + * @param pathString path to evaluate. + */ + function format(pathObject: FormatInputPathObject): string; + + namespace posix { + function normalize(p: string): string; + function join(...paths: any[]): string; + function resolve(...pathSegments: any[]): string; + function isAbsolute(p: string): boolean; + function relative(from: string, to: string): string; + function dirname(p: string): string; + function basename(p: string, ext?: string): string; + function extname(p: string): string; + const sep: string; + const delimiter: string; + function parse(p: string): ParsedPath; + function format(pP: FormatInputPathObject): string; + } + + namespace win32 { + function normalize(p: string): string; + function join(...paths: any[]): string; + function resolve(...pathSegments: any[]): string; + function isAbsolute(p: string): boolean; + function relative(from: string, to: string): string; + function dirname(p: string): string; + function basename(p: string, ext?: string): string; + function extname(p: string): string; + const sep: string; + const delimiter: string; + function parse(p: string): ParsedPath; + function format(pP: FormatInputPathObject): string; + } +} + +declare module "string_decoder" { + interface NodeStringDecoder { + write(buffer: Buffer): string; + end(buffer?: Buffer): string; + } + const StringDecoder: { + new(encoding?: string): NodeStringDecoder; + }; +} + +declare module "tls" { + import * as crypto from "crypto"; + import * as dns from "dns"; + import * as net from "net"; + import * as stream from "stream"; + + const CLIENT_RENEG_LIMIT: number; + const CLIENT_RENEG_WINDOW: number; + + interface Certificate { + /** + * Country code. + */ + C: string; + /** + * Street. + */ + ST: string; + /** + * Locality. + */ + L: string; + /** + * Organization. + */ + O: string; + /** + * Organizational unit. + */ + OU: string; + /** + * Common name. + */ + CN: string; + } + + interface PeerCertificate { + subject: Certificate; + issuer: Certificate; + subjectaltname: string; + infoAccess: { [index: string]: string[] | undefined }; + modulus: string; + exponent: string; + valid_from: string; + valid_to: string; + fingerprint: string; + ext_key_usage: string[]; + serialNumber: string; + raw: Buffer; + } + + interface DetailedPeerCertificate extends PeerCertificate { + issuerCertificate: DetailedPeerCertificate; + } + + interface CipherNameAndProtocol { + /** + * The cipher name. + */ + name: string; + /** + * SSL/TLS protocol version. + */ + version: string; + } + + class TLSSocket extends net.Socket { + /** + * Construct a new tls.TLSSocket object from an existing TCP socket. + */ + constructor(socket: net.Socket, options?: { + /** + * An optional TLS context object from tls.createSecureContext() + */ + secureContext?: SecureContext, + /** + * If true the TLS socket will be instantiated in server-mode. + * Defaults to false. + */ + isServer?: boolean, + /** + * An optional net.Server instance. + */ + server?: net.Server, + /** + * If true the server will request a certificate from clients that + * connect and attempt to verify that certificate. Defaults to + * false. + */ + requestCert?: boolean, + /** + * If true the server will reject any connection which is not + * authorized with the list of supplied CAs. This option only has an + * effect if requestCert is true. Defaults to false. + */ + rejectUnauthorized?: boolean, + /** + * An array of strings or a Buffer naming possible NPN protocols. + * (Protocols should be ordered by their priority.) + */ + NPNProtocols?: string[] | Buffer[] | Uint8Array[] | Buffer | Uint8Array, + /** + * An array of strings or a Buffer naming possible ALPN protocols. + * (Protocols should be ordered by their priority.) When the server + * receives both NPN and ALPN extensions from the client, ALPN takes + * precedence over NPN and the server does not send an NPN extension + * to the client. + */ + ALPNProtocols?: string[] | Buffer[] | Uint8Array[] | Buffer | Uint8Array, + /** + * SNICallback(servername, cb) A function that will be + * called if the client supports SNI TLS extension. Two arguments + * will be passed when called: servername and cb. SNICallback should + * invoke cb(null, ctx), where ctx is a SecureContext instance. + * (tls.createSecureContext(...) can be used to get a proper + * SecureContext.) If SNICallback wasn't provided the default callback + * with high-level API will be used (see below). + */ + SNICallback?: (servername: string, cb: (err: Error | null, ctx: SecureContext) => void) => void, + /** + * An optional Buffer instance containing a TLS session. + */ + session?: Buffer, + /** + * If true, specifies that the OCSP status request extension will be + * added to the client hello and an 'OCSPResponse' event will be + * emitted on the socket before establishing a secure communication + */ + requestOCSP?: boolean + }); + + /** + * A boolean that is true if the peer certificate was signed by one of the specified CAs, otherwise false. + */ + authorized: boolean; + /** + * The reason why the peer's certificate has not been verified. + * This property becomes available only when tlsSocket.authorized === false. + */ + authorizationError: Error; + /** + * Static boolean value, always true. + * May be used to distinguish TLS sockets from regular ones. + */ + encrypted: boolean; + + /** + * String containing the selected ALPN protocol. + * When ALPN has no selected protocol, tlsSocket.alpnProtocol equals false. + */ + alpnProtocol?: string; + + /** + * Returns an object representing the cipher name and the SSL/TLS protocol version of the current connection. + * @returns Returns an object representing the cipher name + * and the SSL/TLS protocol version of the current connection. + */ + getCipher(): CipherNameAndProtocol; + /** + * Returns an object representing the peer's certificate. + * The returned object has some properties corresponding to the field of the certificate. + * If detailed argument is true the full chain with issuer property will be returned, + * if false only the top certificate without issuer property. + * If the peer does not provide a certificate, it returns null or an empty object. + * @param detailed - If true; the full chain with issuer property will be returned. + * @returns An object representing the peer's certificate. + */ + getPeerCertificate(detailed: true): DetailedPeerCertificate; + getPeerCertificate(detailed?: false): PeerCertificate; + getPeerCertificate(detailed?: boolean): PeerCertificate | DetailedPeerCertificate; + /** + * Returns a string containing the negotiated SSL/TLS protocol version of the current connection. + * The value `'unknown'` will be returned for connected sockets that have not completed the handshaking process. + * The value `null` will be returned for server sockets or disconnected client sockets. + * See https://www.openssl.org/docs/man1.0.2/ssl/SSL_get_version.html for more information. + * @returns negotiated SSL/TLS protocol version of the current connection + */ + getProtocol(): string | null; + /** + * Could be used to speed up handshake establishment when reconnecting to the server. + * @returns ASN.1 encoded TLS session or undefined if none was negotiated. + */ + getSession(): any; + /** + * NOTE: Works only with client TLS sockets. + * Useful only for debugging, for session reuse provide session option to tls.connect(). + * @returns TLS session ticket or undefined if none was negotiated. + */ + getTLSTicket(): any; + /** + * Initiate TLS renegotiation process. + * + * NOTE: Can be used to request peer's certificate after the secure connection has been established. + * ANOTHER NOTE: When running as the server, socket will be destroyed with an error after handshakeTimeout timeout. + * @param options - The options may contain the following fields: rejectUnauthorized, + * requestCert (See tls.createServer() for details). + * @param callback - callback(err) will be executed with null as err, once the renegotiation + * is successfully completed. + */ + renegotiate(options: { rejectUnauthorized?: boolean, requestCert?: boolean }, callback: (err: Error | null) => void): any; + /** + * Set maximum TLS fragment size (default and maximum value is: 16384, minimum is: 512). + * Smaller fragment size decreases buffering latency on the client: large fragments are buffered by + * the TLS layer until the entire fragment is received and its integrity is verified; + * large fragments can span multiple roundtrips, and their processing can be delayed due to packet + * loss or reordering. However, smaller fragments add extra TLS framing bytes and CPU overhead, + * which may decrease overall server throughput. + * @param size - TLS fragment size (default and maximum value is: 16384, minimum is: 512). + * @returns Returns true on success, false otherwise. + */ + setMaxSendFragment(size: number): boolean; + + /** + * events.EventEmitter + * 1. OCSPResponse + * 2. secureConnect + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "OCSPResponse", listener: (response: Buffer) => void): this; + addListener(event: "secureConnect", listener: () => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "OCSPResponse", response: Buffer): boolean; + emit(event: "secureConnect"): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "OCSPResponse", listener: (response: Buffer) => void): this; + on(event: "secureConnect", listener: () => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "OCSPResponse", listener: (response: Buffer) => void): this; + once(event: "secureConnect", listener: () => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "OCSPResponse", listener: (response: Buffer) => void): this; + prependListener(event: "secureConnect", listener: () => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "OCSPResponse", listener: (response: Buffer) => void): this; + prependOnceListener(event: "secureConnect", listener: () => void): this; + } + + interface TlsOptions extends SecureContextOptions { + handshakeTimeout?: number; + requestCert?: boolean; + rejectUnauthorized?: boolean; + NPNProtocols?: string[] | Buffer[] | Uint8Array[] | Buffer | Uint8Array; + ALPNProtocols?: string[] | Buffer[] | Uint8Array[] | Buffer | Uint8Array; + SNICallback?: (servername: string, cb: (err: Error | null, ctx: SecureContext) => void) => void; + sessionTimeout?: number; + ticketKeys?: Buffer; + } + + interface ConnectionOptions extends SecureContextOptions { + host?: string; + port?: number; + path?: string; // Creates unix socket connection to path. If this option is specified, `host` and `port` are ignored. + socket?: net.Socket; // Establish secure connection on a given socket rather than creating a new socket + rejectUnauthorized?: boolean; // Defaults to true + NPNProtocols?: string[] | Buffer[] | Uint8Array[] | Buffer | Uint8Array; + ALPNProtocols?: string[] | Buffer[] | Uint8Array[] | Buffer | Uint8Array; + checkServerIdentity?: typeof checkServerIdentity; + servername?: string; // SNI TLS Extension + session?: Buffer; + minDHSize?: number; + secureContext?: SecureContext; // If not provided, the entire ConnectionOptions object will be passed to tls.createSecureContext() + lookup?: net.LookupFunction; + } + + class Server extends net.Server { + addContext(hostName: string, credentials: { + key: string; + cert: string; + ca: string; + }): void; + + /** + * events.EventEmitter + * 1. tlsClientError + * 2. newSession + * 3. OCSPRequest + * 4. resumeSession + * 5. secureConnection + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + addListener(event: "newSession", listener: (sessionId: any, sessionData: any, callback: (err: Error, resp: Buffer) => void) => void): this; + addListener(event: "OCSPRequest", listener: (certificate: Buffer, issuer: Buffer, callback: Function) => void): this; + addListener(event: "resumeSession", listener: (sessionId: any, callback: (err: Error, sessionData: any) => void) => void): this; + addListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "tlsClientError", err: Error, tlsSocket: TLSSocket): boolean; + emit(event: "newSession", sessionId: any, sessionData: any, callback: (err: Error, resp: Buffer) => void): boolean; + emit(event: "OCSPRequest", certificate: Buffer, issuer: Buffer, callback: Function): boolean; + emit(event: "resumeSession", sessionId: any, callback: (err: Error, sessionData: any) => void): boolean; + emit(event: "secureConnection", tlsSocket: TLSSocket): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + on(event: "newSession", listener: (sessionId: any, sessionData: any, callback: (err: Error, resp: Buffer) => void) => void): this; + on(event: "OCSPRequest", listener: (certificate: Buffer, issuer: Buffer, callback: Function) => void): this; + on(event: "resumeSession", listener: (sessionId: any, callback: (err: Error, sessionData: any) => void) => void): this; + on(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + once(event: "newSession", listener: (sessionId: any, sessionData: any, callback: (err: Error, resp: Buffer) => void) => void): this; + once(event: "OCSPRequest", listener: (certificate: Buffer, issuer: Buffer, callback: Function) => void): this; + once(event: "resumeSession", listener: (sessionId: any, callback: (err: Error, sessionData: any) => void) => void): this; + once(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + prependListener(event: "newSession", listener: (sessionId: any, sessionData: any, callback: (err: Error, resp: Buffer) => void) => void): this; + prependListener(event: "OCSPRequest", listener: (certificate: Buffer, issuer: Buffer, callback: Function) => void): this; + prependListener(event: "resumeSession", listener: (sessionId: any, callback: (err: Error, sessionData: any) => void) => void): this; + prependListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + prependOnceListener(event: "newSession", listener: (sessionId: any, sessionData: any, callback: (err: Error, resp: Buffer) => void) => void): this; + prependOnceListener(event: "OCSPRequest", listener: (certificate: Buffer, issuer: Buffer, callback: Function) => void): this; + prependOnceListener(event: "resumeSession", listener: (sessionId: any, callback: (err: Error, sessionData: any) => void) => void): this; + prependOnceListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; + } + + interface SecurePair { + encrypted: any; + cleartext: any; + } + + interface SecureContextOptions { + pfx?: string | Buffer | Array; + key?: string | Buffer | Array; + passphrase?: string; + cert?: string | Buffer | Array; + ca?: string | Buffer | Array; + ciphers?: string; + honorCipherOrder?: boolean; + ecdhCurve?: string; + clientCertEngine?: string; + crl?: string | Buffer | Array; + dhparam?: string | Buffer; + secureOptions?: number; // Value is a numeric bitmask of the `SSL_OP_*` options + secureProtocol?: string; // SSL Method, e.g. SSLv23_method + sessionIdContext?: string; + } + + interface SecureContext { + context: any; + } + + /* + * Verifies the certificate `cert` is issued to host `host`. + * @host The hostname to verify the certificate against + * @cert PeerCertificate representing the peer's certificate + * + * Returns Error object, populating it with the reason, host and cert on failure. On success, returns undefined. + */ + function checkServerIdentity(host: string, cert: PeerCertificate): Error | undefined; + function createServer(options: TlsOptions, secureConnectionListener?: (socket: TLSSocket) => void): Server; + function connect(options: ConnectionOptions, secureConnectListener?: () => void): TLSSocket; + function connect(port: number, host?: string, options?: ConnectionOptions, secureConnectListener?: () => void): TLSSocket; + function connect(port: number, options?: ConnectionOptions, secureConnectListener?: () => void): TLSSocket; + function createSecurePair(credentials?: crypto.Credentials, isServer?: boolean, requestCert?: boolean, rejectUnauthorized?: boolean): SecurePair; + function createSecureContext(details: SecureContextOptions): SecureContext; + function getCiphers(): string[]; + + const DEFAULT_ECDH_CURVE: string; +} + +declare module "crypto" { + import * as stream from "stream"; + + interface Certificate { + exportChallenge(spkac: string | Buffer | NodeJS.TypedArray | DataView): Buffer; + exportPublicKey(spkac: string | Buffer | NodeJS.TypedArray | DataView): Buffer; + verifySpkac(spkac: Buffer | NodeJS.TypedArray | DataView): boolean; + } + const Certificate: { + new(): Certificate; + (): Certificate; + }; + + /** @deprecated since v10.0.0 */ + const fips: boolean; + + interface CredentialDetails { + pfx: string; + key: string; + passphrase: string; + cert: string; + ca: string | string[]; + crl: string | string[]; + ciphers: string; + } + interface Credentials { context?: any; } + function createCredentials(details: CredentialDetails): Credentials; + function createHash(algorithm: string, options?: stream.TransformOptions): Hash; + function createHmac(algorithm: string, key: string | Buffer | NodeJS.TypedArray | DataView, options?: stream.TransformOptions): Hmac; + + type Utf8AsciiLatin1Encoding = "utf8" | "ascii" | "latin1"; + type HexBase64Latin1Encoding = "latin1" | "hex" | "base64"; + type Utf8AsciiBinaryEncoding = "utf8" | "ascii" | "binary"; + type HexBase64BinaryEncoding = "binary" | "base64" | "hex"; + type ECDHKeyFormat = "compressed" | "uncompressed" | "hybrid"; + + interface Hash extends NodeJS.ReadWriteStream { + update(data: string | Buffer | NodeJS.TypedArray | DataView): Hash; + update(data: string, input_encoding: Utf8AsciiLatin1Encoding): Hash; + digest(): Buffer; + digest(encoding: HexBase64Latin1Encoding): string; + } + interface Hmac extends NodeJS.ReadWriteStream { + update(data: string | Buffer | NodeJS.TypedArray | DataView): Hmac; + update(data: string, input_encoding: Utf8AsciiLatin1Encoding): Hmac; + digest(): Buffer; + digest(encoding: HexBase64Latin1Encoding): string; + } + type CipherCCMTypes = 'aes-128-ccm' | 'aes-192-ccm' | 'aes-256-ccm'; + type CipherGCMTypes = 'aes-128-gcm' | 'aes-192-gcm' | 'aes-256-gcm'; + interface CipherCCMOptions extends stream.TransformOptions { + authTagLength: number; + } + interface CipherGCMOptions extends stream.TransformOptions { + authTagLength?: number; + } + /** @deprecated since v10.0.0 use createCipheriv() */ + function createCipher(algorithm: CipherCCMTypes, password: string | Buffer | NodeJS.TypedArray | DataView, options: CipherCCMOptions): CipherCCM; + /** @deprecated since v10.0.0 use createCipheriv() */ + function createCipher(algorithm: CipherGCMTypes, password: string | Buffer | NodeJS.TypedArray | DataView, options?: CipherGCMOptions): CipherGCM; + /** @deprecated since v10.0.0 use createCipheriv() */ + function createCipher(algorithm: string, password: string | Buffer | NodeJS.TypedArray | DataView, options?: stream.TransformOptions): Cipher; + + function createCipheriv(algorithm: CipherCCMTypes, key: string | Buffer | NodeJS.TypedArray | DataView, iv: string | Buffer | NodeJS.TypedArray | DataView, options: CipherCCMOptions): CipherCCM; + function createCipheriv(algorithm: CipherGCMTypes, key: string | Buffer | NodeJS.TypedArray | DataView, iv: string | Buffer | NodeJS.TypedArray | DataView, options?: CipherGCMOptions): CipherGCM; + function createCipheriv(algorithm: string, key: string | Buffer | NodeJS.TypedArray | DataView, iv: string | Buffer | NodeJS.TypedArray | DataView, options?: stream.TransformOptions): Cipher; + + interface Cipher extends NodeJS.ReadWriteStream { + update(data: string | Buffer | NodeJS.TypedArray | DataView): Buffer; + update(data: string, input_encoding: Utf8AsciiBinaryEncoding): Buffer; + update(data: Buffer | NodeJS.TypedArray | DataView, output_encoding: HexBase64BinaryEncoding): string; + update(data: Buffer | NodeJS.TypedArray | DataView, input_encoding: any, output_encoding: HexBase64BinaryEncoding): string; + // second arg ignored + update(data: string, input_encoding: Utf8AsciiBinaryEncoding, output_encoding: HexBase64BinaryEncoding): string; + final(): Buffer; + final(output_encoding: string): string; + setAutoPadding(auto_padding?: boolean): this; + // getAuthTag(): Buffer; + // setAAD(buffer: Buffer): this; // docs only say buffer + } + interface CipherCCM extends Cipher { + setAAD(buffer: Buffer, options: { plaintextLength: number }): this; + getAuthTag(): Buffer; + } + interface CipherGCM extends Cipher { + setAAD(buffer: Buffer, options?: { plaintextLength: number }): this; + getAuthTag(): Buffer; + } + /** @deprecated since v10.0.0 use createCipheriv() */ + function createDecipher(algorithm: CipherCCMTypes, password: string | Buffer | NodeJS.TypedArray | DataView, options: CipherCCMOptions): DecipherCCM; + /** @deprecated since v10.0.0 use createCipheriv() */ + function createDecipher(algorithm: CipherGCMTypes, password: string | Buffer | NodeJS.TypedArray | DataView, options?: CipherGCMOptions): DecipherGCM; + /** @deprecated since v10.0.0 use createCipheriv() */ + function createDecipher(algorithm: string, password: string | Buffer | NodeJS.TypedArray | DataView, options?: stream.TransformOptions): Decipher; + + function createDecipheriv( + algorithm: CipherCCMTypes, + key: string | Buffer | NodeJS.TypedArray | DataView, + iv: string | Buffer | NodeJS.TypedArray | DataView, + options: CipherCCMOptions, + ): DecipherCCM; + function createDecipheriv( + algorithm: CipherGCMTypes, + key: string | Buffer | NodeJS.TypedArray | DataView, + iv: string | Buffer | NodeJS.TypedArray | DataView, + options?: CipherGCMOptions, + ): DecipherGCM; + function createDecipheriv(algorithm: string, key: string | Buffer | NodeJS.TypedArray | DataView, iv: string | Buffer | NodeJS.TypedArray | DataView, options?: stream.TransformOptions): Decipher; + + interface Decipher extends NodeJS.ReadWriteStream { + update(data: Buffer | NodeJS.TypedArray | DataView): Buffer; + update(data: string, input_encoding: HexBase64BinaryEncoding): Buffer; + update(data: Buffer | NodeJS.TypedArray | DataView, input_encoding: any, output_encoding: Utf8AsciiBinaryEncoding): string; + // second arg is ignored + update(data: string, input_encoding: HexBase64BinaryEncoding, output_encoding: Utf8AsciiBinaryEncoding): string; + final(): Buffer; + final(output_encoding: string): string; + setAutoPadding(auto_padding?: boolean): this; + // setAuthTag(tag: Buffer | NodeJS.TypedArray | DataView): this; + // setAAD(buffer: Buffer | NodeJS.TypedArray | DataView): this; + } + interface DecipherCCM extends Decipher { + setAuthTag(buffer: Buffer | NodeJS.TypedArray | DataView): this; + setAAD(buffer: Buffer | NodeJS.TypedArray | DataView, options: { plaintextLength: number }): this; + } + interface DecipherGCM extends Decipher { + setAuthTag(buffer: Buffer | NodeJS.TypedArray | DataView): this; + setAAD(buffer: Buffer | NodeJS.TypedArray | DataView, options?: { plaintextLength: number }): this; + } + + function createSign(algorithm: string, options?: stream.WritableOptions): Signer; + interface Signer extends NodeJS.WritableStream { + update(data: string | Buffer | NodeJS.TypedArray | DataView): Signer; + update(data: string, input_encoding: Utf8AsciiLatin1Encoding): Signer; + sign(private_key: string | { key: string; passphrase?: string, padding?: number, saltLength?: number }): Buffer; + sign(private_key: string | { key: string; passphrase?: string, padding?: number, saltLength?: number }, output_format: HexBase64Latin1Encoding): string; + } + function createVerify(algorith: string, options?: stream.WritableOptions): Verify; + interface Verify extends NodeJS.WritableStream { + update(data: string | Buffer | NodeJS.TypedArray | DataView): Verify; + update(data: string, input_encoding: Utf8AsciiLatin1Encoding): Verify; + verify(object: string | Object, signature: Buffer | NodeJS.TypedArray | DataView): boolean; + verify(object: string | Object, signature: string, signature_format: HexBase64Latin1Encoding): boolean; + // https://nodejs.org/api/crypto.html#crypto_verifier_verify_object_signature_signature_format + // The signature field accepts a TypedArray type, but it is only available starting ES2017 + } + function createDiffieHellman(prime_length: number, generator?: number | Buffer | NodeJS.TypedArray | DataView): DiffieHellman; + function createDiffieHellman(prime: Buffer | NodeJS.TypedArray | DataView): DiffieHellman; + function createDiffieHellman(prime: string, prime_encoding: HexBase64Latin1Encoding): DiffieHellman; + function createDiffieHellman(prime: string, prime_encoding: HexBase64Latin1Encoding, generator: number | Buffer | NodeJS.TypedArray | DataView): DiffieHellman; + function createDiffieHellman(prime: string, prime_encoding: HexBase64Latin1Encoding, generator: string, generator_encoding: HexBase64Latin1Encoding): DiffieHellman; + interface DiffieHellman { + generateKeys(): Buffer; + generateKeys(encoding: HexBase64Latin1Encoding): string; + computeSecret(other_public_key: Buffer | NodeJS.TypedArray | DataView): Buffer; + computeSecret(other_public_key: string, input_encoding: HexBase64Latin1Encoding): Buffer; + computeSecret(other_public_key: Buffer | NodeJS.TypedArray | DataView, output_encoding: HexBase64Latin1Encoding): string; + computeSecret(other_public_key: string, input_encoding: HexBase64Latin1Encoding, output_encoding: HexBase64Latin1Encoding): string; + getPrime(): Buffer; + getPrime(encoding: HexBase64Latin1Encoding): string; + getGenerator(): Buffer; + getGenerator(encoding: HexBase64Latin1Encoding): string; + getPublicKey(): Buffer; + getPublicKey(encoding: HexBase64Latin1Encoding): string; + getPrivateKey(): Buffer; + getPrivateKey(encoding: HexBase64Latin1Encoding): string; + setPublicKey(public_key: Buffer | NodeJS.TypedArray | DataView): void; + setPublicKey(public_key: string, encoding: string): void; + setPrivateKey(private_key: Buffer | NodeJS.TypedArray | DataView): void; + setPrivateKey(private_key: string, encoding: string): void; + verifyError: number; + } + function getDiffieHellman(group_name: string): DiffieHellman; + function pbkdf2( + password: string | Buffer | NodeJS.TypedArray | DataView, + salt: string | Buffer | NodeJS.TypedArray | DataView, + iterations: number, + keylen: number, + digest: string, + callback: (err: Error | null, derivedKey: Buffer) => any, + ): void; + function pbkdf2Sync(password: string | Buffer | NodeJS.TypedArray | DataView, salt: string | Buffer | NodeJS.TypedArray | DataView, iterations: number, keylen: number, digest: string): Buffer; + + function randomBytes(size: number): Buffer; + function randomBytes(size: number, callback: (err: Error | null, buf: Buffer) => void): void; + function pseudoRandomBytes(size: number): Buffer; + function pseudoRandomBytes(size: number, callback: (err: Error | null, buf: Buffer) => void): void; + + function randomFillSync(buffer: T, offset?: number, size?: number): T; + function randomFill(buffer: T, callback: (err: Error | null, buf: T) => void): void; + function randomFill(buffer: T, offset: number, callback: (err: Error | null, buf: T) => void): void; + function randomFill(buffer: T, offset: number, size: number, callback: (err: Error | null, buf: T) => void): void; + + interface ScryptOptions { + N?: number; + r?: number; + p?: number; + maxmem?: number; + } + function scrypt( + password: string | Buffer | NodeJS.TypedArray | DataView, + salt: string | Buffer | NodeJS.TypedArray | DataView, + keylen: number, callback: (err: Error | null, derivedKey: Buffer) => void, + ): void; + function scrypt( + password: string | Buffer | NodeJS.TypedArray | DataView, + salt: string | Buffer | NodeJS.TypedArray | DataView, + keylen: number, + options: ScryptOptions, + callback: (err: Error | null, derivedKey: Buffer) => void, + ): void; + function scryptSync(password: string | Buffer | NodeJS.TypedArray | DataView, salt: string | Buffer | NodeJS.TypedArray | DataView, keylen: number, options?: ScryptOptions): Buffer; + + interface RsaPublicKey { + key: string; + padding?: number; + } + interface RsaPrivateKey { + key: string; + passphrase?: string; + padding?: number; + } + function publicEncrypt(public_key: string | RsaPublicKey, buffer: Buffer | NodeJS.TypedArray | DataView): Buffer; + function privateDecrypt(private_key: string | RsaPrivateKey, buffer: Buffer | NodeJS.TypedArray | DataView): Buffer; + function privateEncrypt(private_key: string | RsaPrivateKey, buffer: Buffer | NodeJS.TypedArray | DataView): Buffer; + function publicDecrypt(public_key: string | RsaPublicKey, buffer: Buffer | NodeJS.TypedArray | DataView): Buffer; + function getCiphers(): string[]; + function getCurves(): string[]; + function getHashes(): string[]; + class ECDH { + static convertKey( + key: string | Buffer | NodeJS.TypedArray | DataView, + curve: string, + inputEncoding?: HexBase64Latin1Encoding, + outputEncoding?: "latin1" | "hex" | "base64", + format?: "uncompressed" | "compressed" | "hybrid", + ): Buffer | string; + generateKeys(): Buffer; + generateKeys(encoding: HexBase64Latin1Encoding, format?: ECDHKeyFormat): string; + computeSecret(other_public_key: Buffer | NodeJS.TypedArray | DataView): Buffer; + computeSecret(other_public_key: string, input_encoding: HexBase64Latin1Encoding): Buffer; + computeSecret(other_public_key: Buffer | NodeJS.TypedArray | DataView, output_encoding: HexBase64Latin1Encoding): string; + computeSecret(other_public_key: string, input_encoding: HexBase64Latin1Encoding, output_encoding: HexBase64Latin1Encoding): string; + getPrivateKey(): Buffer; + getPrivateKey(encoding: HexBase64Latin1Encoding): string; + getPublicKey(): Buffer; + getPublicKey(encoding: HexBase64Latin1Encoding, format?: ECDHKeyFormat): string; + setPrivateKey(private_key: Buffer | NodeJS.TypedArray | DataView): void; + setPrivateKey(private_key: string, encoding: HexBase64Latin1Encoding): void; + } + function createECDH(curve_name: string): ECDH; + function timingSafeEqual(a: Buffer | NodeJS.TypedArray | DataView, b: Buffer | NodeJS.TypedArray | DataView): boolean; + /** @deprecated since v10.0.0 */ + const DEFAULT_ENCODING: string; + + export type KeyType = 'rsa' | 'dsa' | 'ec'; + export type KeyFormat = 'pem' | 'der'; + + interface BasePrivateKeyEncodingOptions { + format: T; + cipher: string; + passphrase: string; + } + + interface RSAKeyPairOptions { + /** + * Key size in bits + */ + modulusLength: number; + /** + * @default 0x10001 + */ + publicExponent?: number; + + publicKeyEncoding: { + type: 'pkcs1' | 'spki'; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: 'pkcs1' | 'pkcs8'; + }; + } + + interface DSAKeyPairOptions { + /** + * Key size in bits + */ + modulusLength: number; + /** + * Size of q in bits + */ + divisorLength: number; + + publicKeyEncoding: { + type: 'spki'; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: 'pkcs8'; + }; + } + + interface ECKeyPairOptions { + /** + * Name of the curve to use. + */ + namedCurve: string; + + publicKeyEncoding: { + type: 'pkcs1' | 'spki'; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: 'sec1' | 'pkcs8'; + }; + } + + interface KeyPairSyncResult { + publicKey: T1; + privateKey: T2; + } + + function generateKeyPairSync(type: 'rsa', options: RSAKeyPairOptions<'pem', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'rsa', options: RSAKeyPairOptions<'pem', 'der'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'rsa', options: RSAKeyPairOptions<'der', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'rsa', options: RSAKeyPairOptions<'der', 'der'>): KeyPairSyncResult; + + function generateKeyPairSync(type: 'dsa', options: DSAKeyPairOptions<'pem', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'dsa', options: DSAKeyPairOptions<'pem', 'der'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'dsa', options: DSAKeyPairOptions<'der', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'dsa', options: DSAKeyPairOptions<'der', 'der'>): KeyPairSyncResult; + + function generateKeyPairSync(type: 'ec', options: ECKeyPairOptions<'pem', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'ec', options: ECKeyPairOptions<'pem', 'der'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'ec', options: ECKeyPairOptions<'der', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'ec', options: ECKeyPairOptions<'der', 'der'>): KeyPairSyncResult; + + function generateKeyPair(type: 'rsa', options: RSAKeyPairOptions<'pem', 'pem'>, callback: (err: Error | null, publicKey: string, privateKey: string) => void): void; + function generateKeyPair(type: 'rsa', options: RSAKeyPairOptions<'pem', 'der'>, callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void): void; + function generateKeyPair(type: 'rsa', options: RSAKeyPairOptions<'der', 'pem'>, callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void): void; + function generateKeyPair(type: 'rsa', options: RSAKeyPairOptions<'der', 'der'>, callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void): void; + + function generateKeyPair(type: 'dsa', options: DSAKeyPairOptions<'pem', 'pem'>, callback: (err: Error | null, publicKey: string, privateKey: string) => void): void; + function generateKeyPair(type: 'dsa', options: DSAKeyPairOptions<'pem', 'der'>, callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void): void; + function generateKeyPair(type: 'dsa', options: DSAKeyPairOptions<'der', 'pem'>, callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void): void; + function generateKeyPair(type: 'dsa', options: DSAKeyPairOptions<'der', 'der'>, callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void): void; + + function generateKeyPair(type: 'ec', options: ECKeyPairOptions<'pem', 'pem'>, callback: (err: Error | null, publicKey: string, privateKey: string) => void): void; + function generateKeyPair(type: 'ec', options: ECKeyPairOptions<'pem', 'der'>, callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void): void; + function generateKeyPair(type: 'ec', options: ECKeyPairOptions<'der', 'pem'>, callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void): void; + function generateKeyPair(type: 'ec', options: ECKeyPairOptions<'der', 'der'>, callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void): void; + + namespace generateKeyPair { + function __promisify__(type: "rsa", options: RSAKeyPairOptions<'pem', 'pem'>): Promise<{ publicKey: string, privateKey: string }>; + function __promisify__(type: "rsa", options: RSAKeyPairOptions<'pem', 'der'>): Promise<{ publicKey: string, privateKey: Buffer }>; + function __promisify__(type: "rsa", options: RSAKeyPairOptions<'der', 'pem'>): Promise<{ publicKey: Buffer, privateKey: string }>; + function __promisify__(type: "rsa", options: RSAKeyPairOptions<'der', 'der'>): Promise<{ publicKey: Buffer, privateKey: Buffer }>; + + function __promisify__(type: "dsa", options: DSAKeyPairOptions<'pem', 'pem'>): Promise<{ publicKey: string, privateKey: string }>; + function __promisify__(type: "dsa", options: DSAKeyPairOptions<'pem', 'der'>): Promise<{ publicKey: string, privateKey: Buffer }>; + function __promisify__(type: "dsa", options: DSAKeyPairOptions<'der', 'pem'>): Promise<{ publicKey: Buffer, privateKey: string }>; + function __promisify__(type: "dsa", options: DSAKeyPairOptions<'der', 'der'>): Promise<{ publicKey: Buffer, privateKey: Buffer }>; + + function __promisify__(type: "ec", options: ECKeyPairOptions<'pem', 'pem'>): Promise<{ publicKey: string, privateKey: string }>; + function __promisify__(type: "ec", options: ECKeyPairOptions<'pem', 'der'>): Promise<{ publicKey: string, privateKey: Buffer }>; + function __promisify__(type: "ec", options: ECKeyPairOptions<'der', 'pem'>): Promise<{ publicKey: Buffer, privateKey: string }>; + function __promisify__(type: "ec", options: ECKeyPairOptions<'der', 'der'>): Promise<{ publicKey: Buffer, privateKey: Buffer }>; + } +} + +declare module "stream" { + import * as events from "events"; + + class internal extends events.EventEmitter { + pipe(destination: T, options?: { end?: boolean; }): T; + } + + namespace internal { + class Stream extends internal { } + + interface ReadableOptions { + highWaterMark?: number; + encoding?: string; + objectMode?: boolean; + read?(this: Readable, size: number): void; + destroy?(this: Readable, error: Error | null, callback: (error: Error | null) => void): void; + } + + class Readable extends Stream implements NodeJS.ReadableStream { + readable: boolean; + readonly readableHighWaterMark: number; + readonly readableLength: number; + constructor(opts?: ReadableOptions); + _read(size: number): void; + read(size?: number): any; + setEncoding(encoding: string): this; + pause(): this; + resume(): this; + isPaused(): boolean; + unpipe(destination?: NodeJS.WritableStream): this; + unshift(chunk: any): void; + wrap(oldStream: NodeJS.ReadableStream): this; + push(chunk: any, encoding?: string): boolean; + _destroy(error: Error | null, callback: (error: Error | null) => void): void; + destroy(error?: Error): void; + + /** + * Event emitter + * The defined events on documents including: + * 1. close + * 2. data + * 3. end + * 4. readable + * 5. error + */ + addListener(event: "close", listener: () => void): this; + addListener(event: "data", listener: (chunk: any) => void): this; + addListener(event: "end", listener: () => void): this; + addListener(event: "readable", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + + emit(event: "close"): boolean; + emit(event: "data", chunk: any): boolean; + emit(event: "end"): boolean; + emit(event: "readable"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + + on(event: "close", listener: () => void): this; + on(event: "data", listener: (chunk: any) => void): this; + on(event: "end", listener: () => void): this; + on(event: "readable", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + + once(event: "close", listener: () => void): this; + once(event: "data", listener: (chunk: any) => void): this; + once(event: "end", listener: () => void): this; + once(event: "readable", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + + prependListener(event: "close", listener: () => void): this; + prependListener(event: "data", listener: (chunk: any) => void): this; + prependListener(event: "end", listener: () => void): this; + prependListener(event: "readable", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "data", listener: (chunk: any) => void): this; + prependOnceListener(event: "end", listener: () => void): this; + prependOnceListener(event: "readable", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + + removeListener(event: "close", listener: () => void): this; + removeListener(event: "data", listener: (chunk: any) => void): this; + removeListener(event: "end", listener: () => void): this; + removeListener(event: "readable", listener: () => void): this; + removeListener(event: "error", listener: (err: Error) => void): this; + removeListener(event: string | symbol, listener: (...args: any[]) => void): this; + + [Symbol.asyncIterator](): AsyncIterableIterator; + } + + interface WritableOptions { + highWaterMark?: number; + decodeStrings?: boolean; + objectMode?: boolean; + write?(this: Writable, chunk: any, encoding: string, callback: (error?: Error | null) => void): void; + writev?(this: Writable, chunks: Array<{ chunk: any, encoding: string }>, callback: (error?: Error | null) => void): void; + destroy?(this: Writable, error: Error | null, callback: (error: Error | null) => void): void; + final?(this: Writable, callback: (error?: Error | null) => void): void; + } + + class Writable extends Stream implements NodeJS.WritableStream { + writable: boolean; + readonly writableHighWaterMark: number; + readonly writableLength: number; + constructor(opts?: WritableOptions); + _write(chunk: any, encoding: string, callback: (error?: Error | null) => void): void; + _writev?(chunks: Array<{ chunk: any, encoding: string }>, callback: (error?: Error | null) => void): void; + _destroy(error: Error | null, callback: (error: Error | null) => void): void; + _final(callback: (error?: Error | null) => void): void; + write(chunk: any, cb?: (error: Error | null | undefined) => void): boolean; + write(chunk: any, encoding?: string, cb?: (error: Error | null | undefined) => void): boolean; + setDefaultEncoding(encoding: string): this; + end(cb?: () => void): void; + end(chunk: any, cb?: () => void): void; + end(chunk: any, encoding?: string, cb?: () => void): void; + cork(): void; + uncork(): void; + destroy(error?: Error): void; + + /** + * Event emitter + * The defined events on documents including: + * 1. close + * 2. drain + * 3. error + * 4. finish + * 5. pipe + * 6. unpipe + */ + addListener(event: "close", listener: () => void): this; + addListener(event: "drain", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "finish", listener: () => void): this; + addListener(event: "pipe", listener: (src: Readable) => void): this; + addListener(event: "unpipe", listener: (src: Readable) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + + emit(event: "close"): boolean; + emit(event: "drain"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "finish"): boolean; + emit(event: "pipe", src: Readable): boolean; + emit(event: "unpipe", src: Readable): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + + on(event: "close", listener: () => void): this; + on(event: "drain", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "finish", listener: () => void): this; + on(event: "pipe", listener: (src: Readable) => void): this; + on(event: "unpipe", listener: (src: Readable) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + + once(event: "close", listener: () => void): this; + once(event: "drain", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "finish", listener: () => void): this; + once(event: "pipe", listener: (src: Readable) => void): this; + once(event: "unpipe", listener: (src: Readable) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + + prependListener(event: "close", listener: () => void): this; + prependListener(event: "drain", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "finish", listener: () => void): this; + prependListener(event: "pipe", listener: (src: Readable) => void): this; + prependListener(event: "unpipe", listener: (src: Readable) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "drain", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "finish", listener: () => void): this; + prependOnceListener(event: "pipe", listener: (src: Readable) => void): this; + prependOnceListener(event: "unpipe", listener: (src: Readable) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + + removeListener(event: "close", listener: () => void): this; + removeListener(event: "drain", listener: () => void): this; + removeListener(event: "error", listener: (err: Error) => void): this; + removeListener(event: "finish", listener: () => void): this; + removeListener(event: "pipe", listener: (src: Readable) => void): this; + removeListener(event: "unpipe", listener: (src: Readable) => void): this; + removeListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + + interface DuplexOptions extends ReadableOptions, WritableOptions { + allowHalfOpen?: boolean; + readableObjectMode?: boolean; + writableObjectMode?: boolean; + read?(this: Duplex, size: number): void; + write?(this: Duplex, chunk: any, encoding: string, callback: (error?: Error | null) => void): void; + writev?(this: Duplex, chunks: Array<{ chunk: any, encoding: string }>, callback: (error?: Error | null) => void): void; + final?(this: Duplex, callback: (error?: Error | null) => void): void; + destroy?(this: Duplex, error: Error | null, callback: (error: Error | null) => void): void; + } + + // Note: Duplex extends both Readable and Writable. + class Duplex extends Readable implements Writable { + writable: boolean; + readonly writableHighWaterMark: number; + readonly writableLength: number; + constructor(opts?: DuplexOptions); + _write(chunk: any, encoding: string, callback: (error?: Error | null) => void): void; + _writev?(chunks: Array<{ chunk: any, encoding: string }>, callback: (error?: Error | null) => void): void; + _destroy(error: Error | null, callback: (error: Error | null) => void): void; + _final(callback: (error?: Error | null) => void): void; + write(chunk: any, cb?: (error: Error | null | undefined) => void): boolean; + write(chunk: any, encoding?: string, cb?: (error: Error | null | undefined) => void): boolean; + setDefaultEncoding(encoding: string): this; + end(cb?: () => void): void; + end(chunk: any, cb?: () => void): void; + end(chunk: any, encoding?: string, cb?: () => void): void; + cork(): void; + uncork(): void; + } + + type TransformCallback = (error?: Error, data?: any) => void; + + interface TransformOptions extends DuplexOptions { + read?(this: Transform, size: number): void; + write?(this: Transform, chunk: any, encoding: string, callback: (error?: Error | null) => void): void; + writev?(this: Transform, chunks: Array<{ chunk: any, encoding: string }>, callback: (error?: Error | null) => void): void; + final?(this: Transform, callback: (error?: Error | null) => void): void; + destroy?(this: Transform, error: Error | null, callback: (error: Error | null) => void): void; + transform?(this: Transform, chunk: any, encoding: string, callback: TransformCallback): void; + flush?(this: Transform, callback: TransformCallback): void; + } + + class Transform extends Duplex { + constructor(opts?: TransformOptions); + _transform(chunk: any, encoding: string, callback: TransformCallback): void; + _flush(callback: TransformCallback): void; + } + + class PassThrough extends Transform { } + + function finished(stream: NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.ReadWriteStream, callback: (err?: NodeJS.ErrnoException) => void): () => void; + namespace finished { + function __promisify__(stream: NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.ReadWriteStream): Promise; + } + + function pipeline(stream1: NodeJS.ReadableStream, stream2: T, callback?: (err: NodeJS.ErrnoException) => void): T; + function pipeline(stream1: NodeJS.ReadableStream, stream2: NodeJS.ReadWriteStream, stream3: T, callback?: (err: NodeJS.ErrnoException) => void): T; + function pipeline( + stream1: NodeJS.ReadableStream, + stream2: NodeJS.ReadWriteStream, + stream3: NodeJS.ReadWriteStream, + stream4: T, + callback?: (err: NodeJS.ErrnoException) => void, + ): T; + function pipeline( + stream1: NodeJS.ReadableStream, + stream2: NodeJS.ReadWriteStream, + stream3: NodeJS.ReadWriteStream, + stream4: NodeJS.ReadWriteStream, + stream5: T, + callback?: (err: NodeJS.ErrnoException) => void, + ): T; + function pipeline(streams: Array, callback?: (err: NodeJS.ErrnoException) => void): NodeJS.WritableStream; + function pipeline( + stream1: NodeJS.ReadableStream, + stream2: NodeJS.ReadWriteStream | NodeJS.WritableStream, + ...streams: Array void)>, + ): NodeJS.WritableStream; + namespace pipeline { + function __promisify__(stream1: NodeJS.ReadableStream, stream2: NodeJS.WritableStream): Promise; + function __promisify__(stream1: NodeJS.ReadableStream, stream2: NodeJS.ReadWriteStream, stream3: NodeJS.WritableStream): Promise; + function __promisify__(stream1: NodeJS.ReadableStream, stream2: NodeJS.ReadWriteStream, stream3: NodeJS.ReadWriteStream, stream4: NodeJS.WritableStream): Promise; + function __promisify__( + stream1: NodeJS.ReadableStream, + stream2: NodeJS.ReadWriteStream, + stream3: NodeJS.ReadWriteStream, + stream4: NodeJS.ReadWriteStream, + stream5: NodeJS.WritableStream, + ): Promise; + function __promisify__(streams: Array): Promise; + function __promisify__( + stream1: NodeJS.ReadableStream, + stream2: NodeJS.ReadWriteStream | NodeJS.WritableStream, + ...streams: Array, + ): Promise; + } + } + + export = internal; +} + +declare module "util" { + interface InspectOptions extends NodeJS.InspectOptions { } + function format(format: any, ...param: any[]): string; + function formatWithOptions(inspectOptions: InspectOptions, format: string, ...param: any[]): string; + /** @deprecated since v0.11.3 - use `console.error()` instead. */ + function debug(string: string): void; + /** @deprecated since v0.11.3 - use `console.error()` instead. */ + function error(...param: any[]): void; + /** @deprecated since v0.11.3 - use `console.log()` instead. */ + function puts(...param: any[]): void; + /** @deprecated since v0.11.3 - use `console.log()` instead. */ + function print(...param: any[]): void; + /** @deprecated since v0.11.3 - use a third party module instead. */ + function log(string: string): void; + const inspect: { + (object: any, showHidden?: boolean, depth?: number | null, color?: boolean): string; + (object: any, options: InspectOptions): string; + colors: { + [color: string]: [number, number] | undefined + } + styles: { + [style: string]: string | undefined + } + defaultOptions: InspectOptions; + custom: symbol; + }; + /** @deprecated since v4.0.0 - use `Array.isArray()` instead. */ + function isArray(object: any): object is any[]; + /** @deprecated since v4.0.0 - use `util.types.isRegExp()` instead. */ + function isRegExp(object: any): object is RegExp; + /** @deprecated since v4.0.0 - use `util.types.isDate()` instead. */ + function isDate(object: any): object is Date; + /** @deprecated since v4.0.0 - use `util.types.isNativeError()` instead. */ + function isError(object: any): object is Error; + function inherits(constructor: any, superConstructor: any): void; + function debuglog(key: string): (msg: string, ...param: any[]) => void; + /** @deprecated since v4.0.0 - use `typeof value === 'boolean'` instead. */ + function isBoolean(object: any): object is boolean; + /** @deprecated since v4.0.0 - use `Buffer.isBuffer()` instead. */ + function isBuffer(object: any): object is Buffer; + /** @deprecated since v4.0.0 - use `typeof value === 'function'` instead. */ + function isFunction(object: any): boolean; + /** @deprecated since v4.0.0 - use `value === null` instead. */ + function isNull(object: any): object is null; + /** @deprecated since v4.0.0 - use `value === null || value === undefined` instead. */ + function isNullOrUndefined(object: any): object is null | undefined; + /** @deprecated since v4.0.0 - use `typeof value === 'number'` instead. */ + function isNumber(object: any): object is number; + /** @deprecated since v4.0.0 - use `value !== null && typeof value === 'object'` instead. */ + function isObject(object: any): boolean; + /** @deprecated since v4.0.0 - use `(typeof value !== 'object' && typeof value !== 'function') || value === null` instead. */ + function isPrimitive(object: any): boolean; + /** @deprecated since v4.0.0 - use `typeof value === 'string'` instead. */ + function isString(object: any): object is string; + /** @deprecated since v4.0.0 - use `typeof value === 'symbol'` instead. */ + function isSymbol(object: any): object is symbol; + /** @deprecated since v4.0.0 - use `value === undefined` instead. */ + function isUndefined(object: any): object is undefined; + function deprecate(fn: T, message: string): T; + function isDeepStrictEqual(val1: any, val2: any): boolean; + + interface CustomPromisify extends Function { + __promisify__: TCustom; + } + + function callbackify(fn: () => Promise): (callback: (err: NodeJS.ErrnoException) => void) => void; + function callbackify(fn: () => Promise): (callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; + function callbackify(fn: (arg1: T1) => Promise): (arg1: T1, callback: (err: NodeJS.ErrnoException) => void) => void; + function callbackify(fn: (arg1: T1) => Promise): (arg1: T1, callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; + function callbackify(fn: (arg1: T1, arg2: T2) => Promise): (arg1: T1, arg2: T2, callback: (err: NodeJS.ErrnoException) => void) => void; + function callbackify(fn: (arg1: T1, arg2: T2) => Promise): (arg1: T1, arg2: T2, callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; + function callbackify(fn: (arg1: T1, arg2: T2, arg3: T3) => Promise): (arg1: T1, arg2: T2, arg3: T3, callback: (err: NodeJS.ErrnoException) => void) => void; + function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3) => Promise): (arg1: T1, arg2: T2, arg3: T3, callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; + function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: NodeJS.ErrnoException) => void) => void; + function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; + function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: NodeJS.ErrnoException) => void) => void; + function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; + function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6) => Promise, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6, callback: (err: NodeJS.ErrnoException) => void) => void; + function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6) => Promise + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6, callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; + + function promisify(fn: CustomPromisify): TCustom; + function promisify(fn: (callback: (err: Error | null, result: TResult) => void) => void): () => Promise; + function promisify(fn: (callback: (err?: Error | null) => void) => void): () => Promise; + function promisify(fn: (arg1: T1, callback: (err: Error | null, result: TResult) => void) => void): (arg1: T1) => Promise; + function promisify(fn: (arg1: T1, callback: (err?: Error | null) => void) => void): (arg1: T1) => Promise; + function promisify(fn: (arg1: T1, arg2: T2, callback: (err: Error | null, result: TResult) => void) => void): (arg1: T1, arg2: T2) => Promise; + function promisify(fn: (arg1: T1, arg2: T2, callback: (err?: Error | null) => void) => void): (arg1: T1, arg2: T2) => Promise; + function promisify(fn: (arg1: T1, arg2: T2, arg3: T3, callback: (err: Error | null, result: TResult) => void) => void): (arg1: T1, arg2: T2, arg3: T3) => Promise; + function promisify(fn: (arg1: T1, arg2: T2, arg3: T3, callback: (err?: Error | null) => void) => void): (arg1: T1, arg2: T2, arg3: T3) => Promise; + function promisify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: Error | null, result: TResult) => void) => void, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise; + function promisify(fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err?: Error | null) => void) => void): (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise; + function promisify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: Error | null, result: TResult) => void) => void, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise; + function promisify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err?: Error | null) => void) => void, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise; + function promisify(fn: Function): Function; + namespace promisify { + const custom: symbol; + } + + namespace types { + function isAnyArrayBuffer(object: any): boolean; + function isArgumentsObject(object: any): object is IArguments; + function isArrayBuffer(object: any): object is ArrayBuffer; + function isAsyncFunction(object: any): boolean; + function isBooleanObject(object: any): object is Boolean; + function isBoxedPrimitive(object: any): object is (Number | Boolean | String | Symbol /* BigInt */); + function isDataView(object: any): object is DataView; + function isDate(object: any): object is Date; + function isExternal(object: any): boolean; + function isFloat32Array(object: any): object is Float32Array; + function isFloat64Array(object: any): object is Float64Array; + function isGeneratorFunction(object: any): boolean; + function isGeneratorObject(object: any): boolean; + function isInt8Array(object: any): object is Int8Array; + function isInt16Array(object: any): object is Int16Array; + function isInt32Array(object: any): object is Int32Array; + function isMap(object: any): boolean; + function isMapIterator(object: any): boolean; + function isNativeError(object: any): object is Error; + function isNumberObject(object: any): object is Number; + function isPromise(object: any): boolean; + function isProxy(object: any): boolean; + function isRegExp(object: any): object is RegExp; + function isSet(object: any): boolean; + function isSetIterator(object: any): boolean; + function isSharedArrayBuffer(object: any): boolean; + function isStringObject(object: any): boolean; + function isSymbolObject(object: any): boolean; + function isTypedArray(object: any): object is NodeJS.TypedArray; + function isUint8Array(object: any): object is Uint8Array; + function isUint8ClampedArray(object: any): object is Uint8ClampedArray; + function isUint16Array(object: any): object is Uint16Array; + function isUint32Array(object: any): object is Uint32Array; + function isWeakMap(object: any): boolean; + function isWeakSet(object: any): boolean; + function isWebAssemblyCompiledModule(object: any): boolean; + } + + class TextDecoder { + readonly encoding: string; + readonly fatal: boolean; + readonly ignoreBOM: boolean; + constructor( + encoding?: string, + options?: { fatal?: boolean; ignoreBOM?: boolean } + ); + decode( + input?: NodeJS.TypedArray | DataView | ArrayBuffer | null, + options?: { stream?: boolean } + ): string; + } + + class TextEncoder { + readonly encoding: string; + constructor(); + encode(input?: string): Uint8Array; + } +} + +declare module "assert" { + function internal(value: any, message?: string | Error): void; + namespace internal { + class AssertionError implements Error { + name: string; + message: string; + actual: any; + expected: any; + operator: string; + generatedMessage: boolean; + code: 'ERR_ASSERTION'; + + constructor(options?: { + message?: string; actual?: any; expected?: any; + operator?: string; stackStartFn?: Function + }); + } + + function fail(message?: string | Error): never; + /** @deprecated since v10.0.0 - use fail([message]) or other assert functions instead. */ + function fail(actual: any, expected: any, message?: string | Error, operator?: string, stackStartFn?: Function): never; + function ok(value: any, message?: string | Error): void; + /** @deprecated since v9.9.0 - use strictEqual() instead. */ + function equal(actual: any, expected: any, message?: string | Error): void; + /** @deprecated since v9.9.0 - use notStrictEqual() instead. */ + function notEqual(actual: any, expected: any, message?: string | Error): void; + /** @deprecated since v9.9.0 - use deepStrictEqual() instead. */ + function deepEqual(actual: any, expected: any, message?: string | Error): void; + /** @deprecated since v9.9.0 - use notDeepStrictEqual() instead. */ + function notDeepEqual(actual: any, expected: any, message?: string | Error): void; + function strictEqual(actual: any, expected: any, message?: string | Error): void; + function notStrictEqual(actual: any, expected: any, message?: string | Error): void; + function deepStrictEqual(actual: any, expected: any, message?: string | Error): void; + function notDeepStrictEqual(actual: any, expected: any, message?: string | Error): void; + + function throws(block: Function, message?: string | Error): void; + function throws(block: Function, error: RegExp | Function | Object | Error, message?: string | Error): void; + function doesNotThrow(block: Function, message?: string | Error): void; + function doesNotThrow(block: Function, error: RegExp | Function, message?: string | Error): void; + + function ifError(value: any): void; + + function rejects(block: Function | Promise, message?: string | Error): Promise; + function rejects(block: Function | Promise, error: RegExp | Function | Object | Error, message?: string | Error): Promise; + function doesNotReject(block: Function | Promise, message?: string | Error): Promise; + function doesNotReject(block: Function | Promise, error: RegExp | Function, message?: string | Error): Promise; + + const strict: typeof internal; + } + + export = internal; +} + +declare module "tty" { + import * as net from "net"; + + function isatty(fd: number): boolean; + class ReadStream extends net.Socket { + isRaw: boolean; + setRawMode(mode: boolean): void; + isTTY: boolean; + } + class WriteStream extends net.Socket { + columns: number; + rows: number; + isTTY: boolean; + } +} + +declare module "domain" { + import * as events from "events"; + + class Domain extends events.EventEmitter implements NodeJS.Domain { + run(fn: Function): void; + add(emitter: events.EventEmitter): void; + remove(emitter: events.EventEmitter): void; + bind(cb: (err: Error, data: any) => any): any; + intercept(cb: (data: any) => any): any; + members: any[]; + enter(): void; + exit(): void; + } + + function create(): Domain; +} + +declare module "constants" { + const E2BIG: number; + const EACCES: number; + const EADDRINUSE: number; + const EADDRNOTAVAIL: number; + const EAFNOSUPPORT: number; + const EAGAIN: number; + const EALREADY: number; + const EBADF: number; + const EBADMSG: number; + const EBUSY: number; + const ECANCELED: number; + const ECHILD: number; + const ECONNABORTED: number; + const ECONNREFUSED: number; + const ECONNRESET: number; + const EDEADLK: number; + const EDESTADDRREQ: number; + const EDOM: number; + const EEXIST: number; + const EFAULT: number; + const EFBIG: number; + const EHOSTUNREACH: number; + const EIDRM: number; + const EILSEQ: number; + const EINPROGRESS: number; + const EINTR: number; + const EINVAL: number; + const EIO: number; + const EISCONN: number; + const EISDIR: number; + const ELOOP: number; + const EMFILE: number; + const EMLINK: number; + const EMSGSIZE: number; + const ENAMETOOLONG: number; + const ENETDOWN: number; + const ENETRESET: number; + const ENETUNREACH: number; + const ENFILE: number; + const ENOBUFS: number; + const ENODATA: number; + const ENODEV: number; + const ENOENT: number; + const ENOEXEC: number; + const ENOLCK: number; + const ENOLINK: number; + const ENOMEM: number; + const ENOMSG: number; + const ENOPROTOOPT: number; + const ENOSPC: number; + const ENOSR: number; + const ENOSTR: number; + const ENOSYS: number; + const ENOTCONN: number; + const ENOTDIR: number; + const ENOTEMPTY: number; + const ENOTSOCK: number; + const ENOTSUP: number; + const ENOTTY: number; + const ENXIO: number; + const EOPNOTSUPP: number; + const EOVERFLOW: number; + const EPERM: number; + const EPIPE: number; + const EPROTO: number; + const EPROTONOSUPPORT: number; + const EPROTOTYPE: number; + const ERANGE: number; + const EROFS: number; + const ESPIPE: number; + const ESRCH: number; + const ETIME: number; + const ETIMEDOUT: number; + const ETXTBSY: number; + const EWOULDBLOCK: number; + const EXDEV: number; + const WSAEINTR: number; + const WSAEBADF: number; + const WSAEACCES: number; + const WSAEFAULT: number; + const WSAEINVAL: number; + const WSAEMFILE: number; + const WSAEWOULDBLOCK: number; + const WSAEINPROGRESS: number; + const WSAEALREADY: number; + const WSAENOTSOCK: number; + const WSAEDESTADDRREQ: number; + const WSAEMSGSIZE: number; + const WSAEPROTOTYPE: number; + const WSAENOPROTOOPT: number; + const WSAEPROTONOSUPPORT: number; + const WSAESOCKTNOSUPPORT: number; + const WSAEOPNOTSUPP: number; + const WSAEPFNOSUPPORT: number; + const WSAEAFNOSUPPORT: number; + const WSAEADDRINUSE: number; + const WSAEADDRNOTAVAIL: number; + const WSAENETDOWN: number; + const WSAENETUNREACH: number; + const WSAENETRESET: number; + const WSAECONNABORTED: number; + const WSAECONNRESET: number; + const WSAENOBUFS: number; + const WSAEISCONN: number; + const WSAENOTCONN: number; + const WSAESHUTDOWN: number; + const WSAETOOMANYREFS: number; + const WSAETIMEDOUT: number; + const WSAECONNREFUSED: number; + const WSAELOOP: number; + const WSAENAMETOOLONG: number; + const WSAEHOSTDOWN: number; + const WSAEHOSTUNREACH: number; + const WSAENOTEMPTY: number; + const WSAEPROCLIM: number; + const WSAEUSERS: number; + const WSAEDQUOT: number; + const WSAESTALE: number; + const WSAEREMOTE: number; + const WSASYSNOTREADY: number; + const WSAVERNOTSUPPORTED: number; + const WSANOTINITIALISED: number; + const WSAEDISCON: number; + const WSAENOMORE: number; + const WSAECANCELLED: number; + const WSAEINVALIDPROCTABLE: number; + const WSAEINVALIDPROVIDER: number; + const WSAEPROVIDERFAILEDINIT: number; + const WSASYSCALLFAILURE: number; + const WSASERVICE_NOT_FOUND: number; + const WSATYPE_NOT_FOUND: number; + const WSA_E_NO_MORE: number; + const WSA_E_CANCELLED: number; + const WSAEREFUSED: number; + const SIGHUP: number; + const SIGINT: number; + const SIGILL: number; + const SIGABRT: number; + const SIGFPE: number; + const SIGKILL: number; + const SIGSEGV: number; + const SIGTERM: number; + const SIGBREAK: number; + const SIGWINCH: number; + const SSL_OP_ALL: number; + const SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION: number; + const SSL_OP_CIPHER_SERVER_PREFERENCE: number; + const SSL_OP_CISCO_ANYCONNECT: number; + const SSL_OP_COOKIE_EXCHANGE: number; + const SSL_OP_CRYPTOPRO_TLSEXT_BUG: number; + const SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS: number; + const SSL_OP_EPHEMERAL_RSA: number; + const SSL_OP_LEGACY_SERVER_CONNECT: number; + const SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER: number; + const SSL_OP_MICROSOFT_SESS_ID_BUG: number; + const SSL_OP_MSIE_SSLV2_RSA_PADDING: number; + const SSL_OP_NETSCAPE_CA_DN_BUG: number; + const SSL_OP_NETSCAPE_CHALLENGE_BUG: number; + const SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG: number; + const SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG: number; + const SSL_OP_NO_COMPRESSION: number; + const SSL_OP_NO_QUERY_MTU: number; + const SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION: number; + const SSL_OP_NO_SSLv2: number; + const SSL_OP_NO_SSLv3: number; + const SSL_OP_NO_TICKET: number; + const SSL_OP_NO_TLSv1: number; + const SSL_OP_NO_TLSv1_1: number; + const SSL_OP_NO_TLSv1_2: number; + const SSL_OP_PKCS1_CHECK_1: number; + const SSL_OP_PKCS1_CHECK_2: number; + const SSL_OP_SINGLE_DH_USE: number; + const SSL_OP_SINGLE_ECDH_USE: number; + const SSL_OP_SSLEAY_080_CLIENT_DH_BUG: number; + const SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG: number; + const SSL_OP_TLS_BLOCK_PADDING_BUG: number; + const SSL_OP_TLS_D5_BUG: number; + const SSL_OP_TLS_ROLLBACK_BUG: number; + const ENGINE_METHOD_DSA: number; + const ENGINE_METHOD_DH: number; + const ENGINE_METHOD_RAND: number; + const ENGINE_METHOD_ECDH: number; + const ENGINE_METHOD_ECDSA: number; + const ENGINE_METHOD_CIPHERS: number; + const ENGINE_METHOD_DIGESTS: number; + const ENGINE_METHOD_STORE: number; + const ENGINE_METHOD_PKEY_METHS: number; + const ENGINE_METHOD_PKEY_ASN1_METHS: number; + const ENGINE_METHOD_ALL: number; + const ENGINE_METHOD_NONE: number; + const DH_CHECK_P_NOT_SAFE_PRIME: number; + const DH_CHECK_P_NOT_PRIME: number; + const DH_UNABLE_TO_CHECK_GENERATOR: number; + const DH_NOT_SUITABLE_GENERATOR: number; + const NPN_ENABLED: number; + const RSA_PKCS1_PADDING: number; + const RSA_SSLV23_PADDING: number; + const RSA_NO_PADDING: number; + const RSA_PKCS1_OAEP_PADDING: number; + const RSA_X931_PADDING: number; + const RSA_PKCS1_PSS_PADDING: number; + const POINT_CONVERSION_COMPRESSED: number; + const POINT_CONVERSION_UNCOMPRESSED: number; + const POINT_CONVERSION_HYBRID: number; + const O_RDONLY: number; + const O_WRONLY: number; + const O_RDWR: number; + const S_IFMT: number; + const S_IFREG: number; + const S_IFDIR: number; + const S_IFCHR: number; + const S_IFBLK: number; + const S_IFIFO: number; + const S_IFSOCK: number; + const S_IRWXU: number; + const S_IRUSR: number; + const S_IWUSR: number; + const S_IXUSR: number; + const S_IRWXG: number; + const S_IRGRP: number; + const S_IWGRP: number; + const S_IXGRP: number; + const S_IRWXO: number; + const S_IROTH: number; + const S_IWOTH: number; + const S_IXOTH: number; + const S_IFLNK: number; + const O_CREAT: number; + const O_EXCL: number; + const O_NOCTTY: number; + const O_DIRECTORY: number; + const O_NOATIME: number; + const O_NOFOLLOW: number; + const O_SYNC: number; + const O_DSYNC: number; + const O_SYMLINK: number; + const O_DIRECT: number; + const O_NONBLOCK: number; + const O_TRUNC: number; + const O_APPEND: number; + const F_OK: number; + const R_OK: number; + const W_OK: number; + const X_OK: number; + const COPYFILE_EXCL: number; + const COPYFILE_FICLONE: number; + const COPYFILE_FICLONE_FORCE: number; + const UV_UDP_REUSEADDR: number; + const SIGQUIT: number; + const SIGTRAP: number; + const SIGIOT: number; + const SIGBUS: number; + const SIGUSR1: number; + const SIGUSR2: number; + const SIGPIPE: number; + const SIGALRM: number; + const SIGCHLD: number; + const SIGSTKFLT: number; + const SIGCONT: number; + const SIGSTOP: number; + const SIGTSTP: number; + const SIGTTIN: number; + const SIGTTOU: number; + const SIGURG: number; + const SIGXCPU: number; + const SIGXFSZ: number; + const SIGVTALRM: number; + const SIGPROF: number; + const SIGIO: number; + const SIGPOLL: number; + const SIGPWR: number; + const SIGSYS: number; + const SIGUNUSED: number; + const defaultCoreCipherList: string; + const defaultCipherList: string; + const ENGINE_METHOD_RSA: number; + const ALPN_ENABLED: number; +} + +declare module "module" { + export = NodeJS.Module; +} + +declare module "process" { + export = process; +} + +declare module "v8" { + interface HeapSpaceInfo { + space_name: string; + space_size: number; + space_used_size: number; + space_available_size: number; + physical_space_size: number; + } + + // ** Signifies if the --zap_code_space option is enabled or not. 1 == enabled, 0 == disabled. */ + type DoesZapCodeSpaceFlag = 0 | 1; + + interface HeapInfo { + total_heap_size: number; + total_heap_size_executable: number; + total_physical_size: number; + total_available_size: number; + used_heap_size: number; + heap_size_limit: number; + malloced_memory: number; + peak_malloced_memory: number; + does_zap_garbage: DoesZapCodeSpaceFlag; + } + + function getHeapStatistics(): HeapInfo; + function getHeapSpaceStatistics(): HeapSpaceInfo[]; + function setFlagsFromString(flags: string): void; +} + +declare module "timers" { + function setTimeout(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timeout; + namespace setTimeout { + function __promisify__(ms: number): Promise; + function __promisify__(ms: number, value: T): Promise; + } + function clearTimeout(timeoutId: NodeJS.Timeout): void; + function setInterval(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timeout; + function clearInterval(intervalId: NodeJS.Timeout): void; + function setImmediate(callback: (...args: any[]) => void, ...args: any[]): NodeJS.Immediate; + namespace setImmediate { + function __promisify__(): Promise; + function __promisify__(value: T): Promise; + } + function clearImmediate(immediateId: NodeJS.Immediate): void; +} + +declare module "console" { + export = console; +} + +/** + * Async Hooks module: https://nodejs.org/api/async_hooks.html + */ +declare module "async_hooks" { + /** + * Returns the asyncId of the current execution context. + */ + function executionAsyncId(): number; + + /** + * Returns the ID of the resource responsible for calling the callback that is currently being executed. + */ + function triggerAsyncId(): number; + + interface HookCallbacks { + /** + * Called when a class is constructed that has the possibility to emit an asynchronous event. + * @param asyncId a unique ID for the async resource + * @param type the type of the async resource + * @param triggerAsyncId the unique ID of the async resource in whose execution context this async resource was created + * @param resource reference to the resource representing the async operation, needs to be released during destroy + */ + init?(asyncId: number, type: string, triggerAsyncId: number, resource: Object): void; + + /** + * When an asynchronous operation is initiated or completes a callback is called to notify the user. + * The before callback is called just before said callback is executed. + * @param asyncId the unique identifier assigned to the resource about to execute the callback. + */ + before?(asyncId: number): void; + + /** + * Called immediately after the callback specified in before is completed. + * @param asyncId the unique identifier assigned to the resource which has executed the callback. + */ + after?(asyncId: number): void; + + /** + * Called when a promise has resolve() called. This may not be in the same execution id + * as the promise itself. + * @param asyncId the unique id for the promise that was resolve()d. + */ + promiseResolve?(asyncId: number): void; + + /** + * Called after the resource corresponding to asyncId is destroyed + * @param asyncId a unique ID for the async resource + */ + destroy?(asyncId: number): void; + } + + interface AsyncHook { + /** + * Enable the callbacks for a given AsyncHook instance. If no callbacks are provided enabling is a noop. + */ + enable(): this; + + /** + * Disable the callbacks for a given AsyncHook instance from the global pool of AsyncHook callbacks to be executed. Once a hook has been disabled it will not be called again until enabled. + */ + disable(): this; + } + + /** + * Registers functions to be called for different lifetime events of each async operation. + * @param options the callbacks to register + * @return an AsyncHooks instance used for disabling and enabling hooks + */ + function createHook(options: HookCallbacks): AsyncHook; + + interface AsyncResourceOptions { + /** + * The ID of the execution context that created this async event. + * Default: `executionAsyncId()` + */ + triggerAsyncId?: number; + + /** + * Disables automatic `emitDestroy` when the object is garbage collected. + * This usually does not need to be set (even if `emitDestroy` is called + * manually), unless the resource's `asyncId` is retrieved and the + * sensitive API's `emitDestroy` is called with it. + * Default: `false` + */ + requireManualDestroy?: boolean; + } + + /** + * The class AsyncResource was designed to be extended by the embedder's async resources. + * Using this users can easily trigger the lifetime events of their own resources. + */ + class AsyncResource { + /** + * AsyncResource() is meant to be extended. Instantiating a + * new AsyncResource() also triggers init. If triggerAsyncId is omitted then + * async_hook.executionAsyncId() is used. + * @param type The type of async event. + * @param triggerAsyncId The ID of the execution context that created + * this async event (default: `executionAsyncId()`), or an + * AsyncResourceOptions object (since 9.3) + */ + constructor(type: string, triggerAsyncId?: number|AsyncResourceOptions); + + /** + * Call AsyncHooks before callbacks. + * @deprecated since 9.6 - Use asyncResource.runInAsyncScope() instead. + */ + emitBefore(): void; + + /** + * Call AsyncHooks after callbacks. + * @deprecated since 9.6 - Use asyncResource.runInAsyncScope() instead. + */ + emitAfter(): void; + + /** + * Call the provided function with the provided arguments in the + * execution context of the async resource. This will establish the + * context, trigger the AsyncHooks before callbacks, call the function, + * trigger the AsyncHooks after callbacks, and then restore the original + * execution context. + * @param fn The function to call in the execution context of this + * async resource. + * @param thisArg The receiver to be used for the function call. + * @param args Optional arguments to pass to the function. + */ + runInAsyncScope(fn: (this: This, ...args: any[]) => Result, thisArg?: This, ...args: any[]): Result; + + /** + * Call AsyncHooks destroy callbacks. + */ + emitDestroy(): void; + + /** + * @return the unique ID assigned to this AsyncResource instance. + */ + asyncId(): number; + + /** + * @return the trigger ID for this AsyncResource instance. + */ + triggerAsyncId(): number; + } +} + +declare module "http2" { + import * as events from "events"; + import * as fs from "fs"; + import * as net from "net"; + import * as stream from "stream"; + import * as tls from "tls"; + import * as url from "url"; + + import { IncomingHttpHeaders as Http1IncomingHttpHeaders, OutgoingHttpHeaders } from "http"; + export { OutgoingHttpHeaders } from "http"; + + export interface IncomingHttpStatusHeader { + ":status"?: number; + } + + export interface IncomingHttpHeaders extends Http1IncomingHttpHeaders { + ":path"?: string; + ":method"?: string; + ":authority"?: string; + ":scheme"?: string; + } + + // Http2Stream + + export interface StreamPriorityOptions { + exclusive?: boolean; + parent?: number; + weight?: number; + silent?: boolean; + } + + export interface StreamState { + localWindowSize?: number; + state?: number; + streamLocalClose?: number; + streamRemoteClose?: number; + sumDependencyWeight?: number; + weight?: number; + } + + export interface ServerStreamResponseOptions { + endStream?: boolean; + waitForTrailers?: boolean; + } + + export interface StatOptions { + offset: number; + length: number; + } + + export interface ServerStreamFileResponseOptions { + statCheck?: (stats: fs.Stats, headers: OutgoingHttpHeaders, statOptions: StatOptions) => void | boolean; + getTrailers?: (trailers: OutgoingHttpHeaders) => void; + offset?: number; + length?: number; + } + + export interface ServerStreamFileResponseOptionsWithError extends ServerStreamFileResponseOptions { + onError?: (err: NodeJS.ErrnoException) => void; + } + + export interface Http2Stream extends stream.Duplex { + readonly aborted: boolean; + readonly closed: boolean; + readonly destroyed: boolean; + readonly pending: boolean; + readonly rstCode: number; + readonly sentHeaders: OutgoingHttpHeaders; + readonly sentInfoHeaders?: OutgoingHttpHeaders[]; + readonly sentTrailers?: OutgoingHttpHeaders; + readonly session: Http2Session; + readonly state: StreamState; + /** + * Set the true if the END_STREAM flag was set in the request or response HEADERS frame received, + * indicating that no additional data should be received and the readable side of the Http2Stream will be closed. + */ + readonly endAfterHeaders: boolean; + close(code?: number, callback?: () => void): void; + priority(options: StreamPriorityOptions): void; + setTimeout(msecs: number, callback?: () => void): void; + + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "aborted", listener: () => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "data", listener: (chunk: Buffer | string) => void): this; + addListener(event: "drain", listener: () => void): this; + addListener(event: "end", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "finish", listener: () => void): this; + addListener(event: "frameError", listener: (frameType: number, errorCode: number) => void): this; + addListener(event: "pipe", listener: (src: stream.Readable) => void): this; + addListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + addListener(event: "streamClosed", listener: (code: number) => void): this; + addListener(event: "timeout", listener: () => void): this; + addListener(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + addListener(event: "wantTrailers", listener: () => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "aborted"): boolean; + emit(event: "close"): boolean; + emit(event: "data", chunk: Buffer | string): boolean; + emit(event: "drain"): boolean; + emit(event: "end"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "finish"): boolean; + emit(event: "frameError", frameType: number, errorCode: number): boolean; + emit(event: "pipe", src: stream.Readable): boolean; + emit(event: "unpipe", src: stream.Readable): boolean; + emit(event: "streamClosed", code: number): boolean; + emit(event: "timeout"): boolean; + emit(event: "trailers", trailers: IncomingHttpHeaders, flags: number): boolean; + emit(event: "wantTrailers"): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "aborted", listener: () => void): this; + on(event: "close", listener: () => void): this; + on(event: "data", listener: (chunk: Buffer | string) => void): this; + on(event: "drain", listener: () => void): this; + on(event: "end", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "finish", listener: () => void): this; + on(event: "frameError", listener: (frameType: number, errorCode: number) => void): this; + on(event: "pipe", listener: (src: stream.Readable) => void): this; + on(event: "unpipe", listener: (src: stream.Readable) => void): this; + on(event: "streamClosed", listener: (code: number) => void): this; + on(event: "timeout", listener: () => void): this; + on(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + on(event: "wantTrailers", listener: () => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "aborted", listener: () => void): this; + once(event: "close", listener: () => void): this; + once(event: "data", listener: (chunk: Buffer | string) => void): this; + once(event: "drain", listener: () => void): this; + once(event: "end", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "finish", listener: () => void): this; + once(event: "frameError", listener: (frameType: number, errorCode: number) => void): this; + once(event: "pipe", listener: (src: stream.Readable) => void): this; + once(event: "unpipe", listener: (src: stream.Readable) => void): this; + once(event: "streamClosed", listener: (code: number) => void): this; + once(event: "timeout", listener: () => void): this; + once(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + once(event: "wantTrailers", listener: () => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "aborted", listener: () => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "data", listener: (chunk: Buffer | string) => void): this; + prependListener(event: "drain", listener: () => void): this; + prependListener(event: "end", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "finish", listener: () => void): this; + prependListener(event: "frameError", listener: (frameType: number, errorCode: number) => void): this; + prependListener(event: "pipe", listener: (src: stream.Readable) => void): this; + prependListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + prependListener(event: "streamClosed", listener: (code: number) => void): this; + prependListener(event: "timeout", listener: () => void): this; + prependListener(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + prependListener(event: "wantTrailers", listener: () => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "aborted", listener: () => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "data", listener: (chunk: Buffer | string) => void): this; + prependOnceListener(event: "drain", listener: () => void): this; + prependOnceListener(event: "end", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "finish", listener: () => void): this; + prependOnceListener(event: "frameError", listener: (frameType: number, errorCode: number) => void): this; + prependOnceListener(event: "pipe", listener: (src: stream.Readable) => void): this; + prependOnceListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + prependOnceListener(event: "streamClosed", listener: (code: number) => void): this; + prependOnceListener(event: "timeout", listener: () => void): this; + prependOnceListener(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + prependOnceListener(event: "wantTrailers", listener: () => void): this; + + sendTrailers(headers: OutgoingHttpHeaders): this; + } + + export interface ClientHttp2Stream extends Http2Stream { + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "headers", listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + addListener(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + addListener(event: "response", listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "headers", headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number): boolean; + emit(event: "push", headers: IncomingHttpHeaders, flags: number): boolean; + emit(event: "response", headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "headers", listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + on(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + on(event: "response", listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "headers", listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + once(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + once(event: "response", listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "headers", listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + prependListener(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + prependListener(event: "response", listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "headers", listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + prependOnceListener(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + prependOnceListener(event: "response", listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + } + + export interface ServerHttp2Stream extends Http2Stream { + additionalHeaders(headers: OutgoingHttpHeaders): void; + readonly headersSent: boolean; + readonly pushAllowed: boolean; + pushStream(headers: OutgoingHttpHeaders, callback?: (err: Error | null, pushStream: ServerHttp2Stream, headers: OutgoingHttpHeaders) => void): void; + pushStream(headers: OutgoingHttpHeaders, options?: StreamPriorityOptions, callback?: (err: Error | null, pushStream: ServerHttp2Stream, headers: OutgoingHttpHeaders) => void): void; + respond(headers?: OutgoingHttpHeaders, options?: ServerStreamResponseOptions): void; + respondWithFD(fd: number, headers?: OutgoingHttpHeaders, options?: ServerStreamFileResponseOptions): void; + respondWithFile(path: string, headers?: OutgoingHttpHeaders, options?: ServerStreamFileResponseOptionsWithError): void; + } + + // Http2Session + + export interface Settings { + headerTableSize?: number; + enablePush?: boolean; + initialWindowSize?: number; + maxFrameSize?: number; + maxConcurrentStreams?: number; + maxHeaderListSize?: number; + } + + export interface ClientSessionRequestOptions { + endStream?: boolean; + exclusive?: boolean; + parent?: number; + weight?: number; + getTrailers?: (trailers: OutgoingHttpHeaders, flags: number) => void; + } + + export interface SessionState { + effectiveLocalWindowSize?: number; + effectiveRecvDataLength?: number; + nextStreamID?: number; + localWindowSize?: number; + lastProcStreamID?: number; + remoteWindowSize?: number; + outboundQueueSize?: number; + deflateDynamicTableSize?: number; + inflateDynamicTableSize?: number; + } + + export interface Http2Session extends events.EventEmitter { + readonly alpnProtocol?: string; + close(callback?: () => void): void; + readonly closed: boolean; + readonly connecting: boolean; + destroy(error?: Error, code?: number): void; + readonly destroyed: boolean; + readonly encrypted?: boolean; + goaway(code?: number, lastStreamID?: number, opaqueData?: Buffer | DataView | NodeJS.TypedArray): void; + readonly localSettings: Settings; + readonly originSet?: string[]; + readonly pendingSettingsAck: boolean; + ping(callback: (err: Error | null, duration: number, payload: Buffer) => void): boolean; + ping(payload: Buffer | DataView | NodeJS.TypedArray , callback: (err: Error | null, duration: number, payload: Buffer) => void): boolean; + ref(): void; + readonly remoteSettings: Settings; + rstStream(stream: Http2Stream, code?: number): void; + setTimeout(msecs: number, callback?: () => void): void; + readonly socket: net.Socket | tls.TLSSocket; + readonly state: SessionState; + priority(stream: Http2Stream, options: StreamPriorityOptions): void; + settings(settings: Settings): void; + readonly type: number; + unref(): void; + + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "frameError", listener: (frameType: number, errorCode: number, streamID: number) => void): this; + addListener(event: "goaway", listener: (errorCode: number, lastStreamID: number, opaqueData: Buffer) => void): this; + addListener(event: "localSettings", listener: (settings: Settings) => void): this; + addListener(event: "remoteSettings", listener: (settings: Settings) => void): this; + addListener(event: "timeout", listener: () => void): this; + addListener(event: "ping", listener: () => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "close"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "frameError", frameType: number, errorCode: number, streamID: number): boolean; + emit(event: "goaway", errorCode: number, lastStreamID: number, opaqueData: Buffer): boolean; + emit(event: "localSettings", settings: Settings): boolean; + emit(event: "remoteSettings", settings: Settings): boolean; + emit(event: "timeout"): boolean; + emit(event: "ping"): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "frameError", listener: (frameType: number, errorCode: number, streamID: number) => void): this; + on(event: "goaway", listener: (errorCode: number, lastStreamID: number, opaqueData: Buffer) => void): this; + on(event: "localSettings", listener: (settings: Settings) => void): this; + on(event: "remoteSettings", listener: (settings: Settings) => void): this; + on(event: "timeout", listener: () => void): this; + on(event: "ping", listener: () => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "frameError", listener: (frameType: number, errorCode: number, streamID: number) => void): this; + once(event: "goaway", listener: (errorCode: number, lastStreamID: number, opaqueData: Buffer) => void): this; + once(event: "localSettings", listener: (settings: Settings) => void): this; + once(event: "remoteSettings", listener: (settings: Settings) => void): this; + once(event: "timeout", listener: () => void): this; + once(event: "ping", listener: () => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "frameError", listener: (frameType: number, errorCode: number, streamID: number) => void): this; + prependListener(event: "goaway", listener: (errorCode: number, lastStreamID: number, opaqueData: Buffer) => void): this; + prependListener(event: "localSettings", listener: (settings: Settings) => void): this; + prependListener(event: "remoteSettings", listener: (settings: Settings) => void): this; + prependListener(event: "timeout", listener: () => void): this; + prependListener(event: "ping", listener: () => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "frameError", listener: (frameType: number, errorCode: number, streamID: number) => void): this; + prependOnceListener(event: "goaway", listener: (errorCode: number, lastStreamID: number, opaqueData: Buffer) => void): this; + prependOnceListener(event: "localSettings", listener: (settings: Settings) => void): this; + prependOnceListener(event: "remoteSettings", listener: (settings: Settings) => void): this; + prependOnceListener(event: "timeout", listener: () => void): this; + prependOnceListener(event: "ping", listener: () => void): this; + } + + export interface ClientHttp2Session extends Http2Session { + request(headers?: OutgoingHttpHeaders, options?: ClientSessionRequestOptions): ClientHttp2Stream; + + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; + addListener(event: "connect", listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + addListener(event: "stream", listener: (stream: ClientHttp2Stream, headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "altsvc", alt: string, origin: string, stream: number): boolean; + emit(event: "connect", session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket): boolean; + emit(event: "stream", stream: ClientHttp2Stream, headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; + on(event: "connect", listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + on(event: "stream", listener: (stream: ClientHttp2Stream, headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; + once(event: "connect", listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + once(event: "stream", listener: (stream: ClientHttp2Stream, headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; + prependListener(event: "connect", listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + prependListener(event: "stream", listener: (stream: ClientHttp2Stream, headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; + prependOnceListener(event: "connect", listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + prependOnceListener(event: "stream", listener: (stream: ClientHttp2Stream, headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + } + + export interface AlternativeServiceOptions { + origin: number | string | url.URL; + } + + export interface ServerHttp2Session extends Http2Session { + altsvc(alt: string, originOrStream: number | string | url.URL | AlternativeServiceOptions): void; + readonly server: Http2Server | Http2SecureServer; + + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "connect", listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + addListener(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "connect", session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket): boolean; + emit(event: "stream", stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "connect", listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + on(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "connect", listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + once(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "connect", listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + prependListener(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "connect", listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + prependOnceListener(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + } + + // Http2Server + + export interface SessionOptions { + maxDeflateDynamicTableSize?: number; + maxReservedRemoteStreams?: number; + maxSendHeaderBlockLength?: number; + paddingStrategy?: number; + peerMaxConcurrentStreams?: number; + selectPadding?: (frameLen: number, maxFrameLen: number) => number; + settings?: Settings; + createConnection?: (option: SessionOptions) => stream.Duplex; + } + + export type ClientSessionOptions = SessionOptions; + export type ServerSessionOptions = SessionOptions; + + export interface SecureClientSessionOptions extends ClientSessionOptions, tls.ConnectionOptions { } + export interface SecureServerSessionOptions extends ServerSessionOptions, tls.TlsOptions { } + + export interface ServerOptions extends ServerSessionOptions { + allowHTTP1?: boolean; + } + + export interface SecureServerOptions extends SecureServerSessionOptions { + allowHTTP1?: boolean; + } + + export interface Http2Server extends net.Server { + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + addListener(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + addListener(event: "sessionError", listener: (err: Error) => void): this; + addListener(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + addListener(event: "timeout", listener: () => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "checkContinue", request: Http2ServerRequest, response: Http2ServerResponse): boolean; + emit(event: "request", request: Http2ServerRequest, response: Http2ServerResponse): boolean; + emit(event: "sessionError", err: Error): boolean; + emit(event: "stream", stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number): boolean; + emit(event: "timeout"): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + on(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + on(event: "sessionError", listener: (err: Error) => void): this; + on(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + on(event: "timeout", listener: () => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + once(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + once(event: "sessionError", listener: (err: Error) => void): this; + once(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + once(event: "timeout", listener: () => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + prependListener(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + prependListener(event: "sessionError", listener: (err: Error) => void): this; + prependListener(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + prependListener(event: "timeout", listener: () => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + prependOnceListener(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + prependOnceListener(event: "sessionError", listener: (err: Error) => void): this; + prependOnceListener(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + prependOnceListener(event: "timeout", listener: () => void): this; + } + + export interface Http2SecureServer extends tls.Server { + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + addListener(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + addListener(event: "sessionError", listener: (err: Error) => void): this; + addListener(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + addListener(event: "timeout", listener: () => void): this; + addListener(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "checkContinue", request: Http2ServerRequest, response: Http2ServerResponse): boolean; + emit(event: "request", request: Http2ServerRequest, response: Http2ServerResponse): boolean; + emit(event: "sessionError", err: Error): boolean; + emit(event: "stream", stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number): boolean; + emit(event: "timeout"): boolean; + emit(event: "unknownProtocol", socket: tls.TLSSocket): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + on(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + on(event: "sessionError", listener: (err: Error) => void): this; + on(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + on(event: "timeout", listener: () => void): this; + on(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + once(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + once(event: "sessionError", listener: (err: Error) => void): this; + once(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + once(event: "timeout", listener: () => void): this; + once(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + prependListener(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + prependListener(event: "sessionError", listener: (err: Error) => void): this; + prependListener(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + prependListener(event: "timeout", listener: () => void): this; + prependListener(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + prependOnceListener(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + prependOnceListener(event: "sessionError", listener: (err: Error) => void): this; + prependOnceListener(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + prependOnceListener(event: "timeout", listener: () => void): this; + prependOnceListener(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; + } + + export class Http2ServerRequest extends stream.Readable { + private constructor(); + headers: IncomingHttpHeaders; + httpVersion: string; + method: string; + rawHeaders: string[]; + rawTrailers: string[]; + setTimeout(msecs: number, callback?: () => void): void; + socket: net.Socket | tls.TLSSocket; + stream: ServerHttp2Stream; + trailers: IncomingHttpHeaders; + url: string; + + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "aborted", listener: (hadError: boolean, code: number) => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "aborted", hadError: boolean, code: number): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "aborted", listener: (hadError: boolean, code: number) => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "aborted", listener: (hadError: boolean, code: number) => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "aborted", listener: (hadError: boolean, code: number) => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "aborted", listener: (hadError: boolean, code: number) => void): this; + } + + export class Http2ServerResponse extends events.EventEmitter { + private constructor(); + addTrailers(trailers: OutgoingHttpHeaders): void; + connection: net.Socket | tls.TLSSocket; + end(callback?: () => void): void; + end(data?: string | Buffer, callback?: () => void): void; + end(data?: string | Buffer, encoding?: string, callback?: () => void): void; + readonly finished: boolean; + getHeader(name: string): string; + getHeaderNames(): string[]; + getHeaders(): OutgoingHttpHeaders; + hasHeader(name: string): boolean; + readonly headersSent: boolean; + removeHeader(name: string): void; + sendDate: boolean; + setHeader(name: string, value: number | string | string[]): void; + setTimeout(msecs: number, callback?: () => void): void; + socket: net.Socket | tls.TLSSocket; + statusCode: number; + statusMessage: ''; + stream: ServerHttp2Stream; + write(chunk: string | Buffer, callback?: (err: Error) => void): boolean; + write(chunk: string | Buffer, encoding?: string, callback?: (err: Error) => void): boolean; + writeContinue(): void; + writeHead(statusCode: number, headers?: OutgoingHttpHeaders): void; + writeHead(statusCode: number, statusMessage?: string, headers?: OutgoingHttpHeaders): void; + createPushResponse(headers: OutgoingHttpHeaders, callback: (err: Error | null, res: Http2ServerResponse) => void): void; + + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "aborted", listener: (hadError: boolean, code: number) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "drain", listener: () => void): this; + addListener(event: "error", listener: (error: Error) => void): this; + addListener(event: "finish", listener: () => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "aborted", hadError: boolean, code: number): boolean; + emit(event: "close"): boolean; + emit(event: "drain"): boolean; + emit(event: "error", error: Error): boolean; + emit(event: "finish"): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "aborted", listener: (hadError: boolean, code: number) => void): this; + on(event: "close", listener: () => void): this; + on(event: "drain", listener: () => void): this; + on(event: "error", listener: (error: Error) => void): this; + on(event: "finish", listener: () => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "aborted", listener: (hadError: boolean, code: number) => void): this; + once(event: "close", listener: () => void): this; + once(event: "drain", listener: () => void): this; + once(event: "error", listener: (error: Error) => void): this; + once(event: "finish", listener: () => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "aborted", listener: (hadError: boolean, code: number) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "drain", listener: () => void): this; + prependListener(event: "error", listener: (error: Error) => void): this; + prependListener(event: "finish", listener: () => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "aborted", listener: (hadError: boolean, code: number) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "drain", listener: () => void): this; + prependOnceListener(event: "error", listener: (error: Error) => void): this; + prependOnceListener(event: "finish", listener: () => void): this; + } + + // Public API + + export namespace constants { + const NGHTTP2_SESSION_SERVER: number; + const NGHTTP2_SESSION_CLIENT: number; + const NGHTTP2_STREAM_STATE_IDLE: number; + const NGHTTP2_STREAM_STATE_OPEN: number; + const NGHTTP2_STREAM_STATE_RESERVED_LOCAL: number; + const NGHTTP2_STREAM_STATE_RESERVED_REMOTE: number; + const NGHTTP2_STREAM_STATE_HALF_CLOSED_LOCAL: number; + const NGHTTP2_STREAM_STATE_HALF_CLOSED_REMOTE: number; + const NGHTTP2_STREAM_STATE_CLOSED: number; + const NGHTTP2_NO_ERROR: number; + const NGHTTP2_PROTOCOL_ERROR: number; + const NGHTTP2_INTERNAL_ERROR: number; + const NGHTTP2_FLOW_CONTROL_ERROR: number; + const NGHTTP2_SETTINGS_TIMEOUT: number; + const NGHTTP2_STREAM_CLOSED: number; + const NGHTTP2_FRAME_SIZE_ERROR: number; + const NGHTTP2_REFUSED_STREAM: number; + const NGHTTP2_CANCEL: number; + const NGHTTP2_COMPRESSION_ERROR: number; + const NGHTTP2_CONNECT_ERROR: number; + const NGHTTP2_ENHANCE_YOUR_CALM: number; + const NGHTTP2_INADEQUATE_SECURITY: number; + const NGHTTP2_HTTP_1_1_REQUIRED: number; + const NGHTTP2_ERR_FRAME_SIZE_ERROR: number; + const NGHTTP2_FLAG_NONE: number; + const NGHTTP2_FLAG_END_STREAM: number; + const NGHTTP2_FLAG_END_HEADERS: number; + const NGHTTP2_FLAG_ACK: number; + const NGHTTP2_FLAG_PADDED: number; + const NGHTTP2_FLAG_PRIORITY: number; + const DEFAULT_SETTINGS_HEADER_TABLE_SIZE: number; + const DEFAULT_SETTINGS_ENABLE_PUSH: number; + const DEFAULT_SETTINGS_INITIAL_WINDOW_SIZE: number; + const DEFAULT_SETTINGS_MAX_FRAME_SIZE: number; + const MAX_MAX_FRAME_SIZE: number; + const MIN_MAX_FRAME_SIZE: number; + const MAX_INITIAL_WINDOW_SIZE: number; + const NGHTTP2_DEFAULT_WEIGHT: number; + const NGHTTP2_SETTINGS_HEADER_TABLE_SIZE: number; + const NGHTTP2_SETTINGS_ENABLE_PUSH: number; + const NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS: number; + const NGHTTP2_SETTINGS_INITIAL_WINDOW_SIZE: number; + const NGHTTP2_SETTINGS_MAX_FRAME_SIZE: number; + const NGHTTP2_SETTINGS_MAX_HEADER_LIST_SIZE: number; + const PADDING_STRATEGY_NONE: number; + const PADDING_STRATEGY_MAX: number; + const PADDING_STRATEGY_CALLBACK: number; + const HTTP2_HEADER_STATUS: string; + const HTTP2_HEADER_METHOD: string; + const HTTP2_HEADER_AUTHORITY: string; + const HTTP2_HEADER_SCHEME: string; + const HTTP2_HEADER_PATH: string; + const HTTP2_HEADER_ACCEPT_CHARSET: string; + const HTTP2_HEADER_ACCEPT_ENCODING: string; + const HTTP2_HEADER_ACCEPT_LANGUAGE: string; + const HTTP2_HEADER_ACCEPT_RANGES: string; + const HTTP2_HEADER_ACCEPT: string; + const HTTP2_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN: string; + const HTTP2_HEADER_AGE: string; + const HTTP2_HEADER_ALLOW: string; + const HTTP2_HEADER_AUTHORIZATION: string; + const HTTP2_HEADER_CACHE_CONTROL: string; + const HTTP2_HEADER_CONNECTION: string; + const HTTP2_HEADER_CONTENT_DISPOSITION: string; + const HTTP2_HEADER_CONTENT_ENCODING: string; + const HTTP2_HEADER_CONTENT_LANGUAGE: string; + const HTTP2_HEADER_CONTENT_LENGTH: string; + const HTTP2_HEADER_CONTENT_LOCATION: string; + const HTTP2_HEADER_CONTENT_MD5: string; + const HTTP2_HEADER_CONTENT_RANGE: string; + const HTTP2_HEADER_CONTENT_TYPE: string; + const HTTP2_HEADER_COOKIE: string; + const HTTP2_HEADER_DATE: string; + const HTTP2_HEADER_ETAG: string; + const HTTP2_HEADER_EXPECT: string; + const HTTP2_HEADER_EXPIRES: string; + const HTTP2_HEADER_FROM: string; + const HTTP2_HEADER_HOST: string; + const HTTP2_HEADER_IF_MATCH: string; + const HTTP2_HEADER_IF_MODIFIED_SINCE: string; + const HTTP2_HEADER_IF_NONE_MATCH: string; + const HTTP2_HEADER_IF_RANGE: string; + const HTTP2_HEADER_IF_UNMODIFIED_SINCE: string; + const HTTP2_HEADER_LAST_MODIFIED: string; + const HTTP2_HEADER_LINK: string; + const HTTP2_HEADER_LOCATION: string; + const HTTP2_HEADER_MAX_FORWARDS: string; + const HTTP2_HEADER_PREFER: string; + const HTTP2_HEADER_PROXY_AUTHENTICATE: string; + const HTTP2_HEADER_PROXY_AUTHORIZATION: string; + const HTTP2_HEADER_RANGE: string; + const HTTP2_HEADER_REFERER: string; + const HTTP2_HEADER_REFRESH: string; + const HTTP2_HEADER_RETRY_AFTER: string; + const HTTP2_HEADER_SERVER: string; + const HTTP2_HEADER_SET_COOKIE: string; + const HTTP2_HEADER_STRICT_TRANSPORT_SECURITY: string; + const HTTP2_HEADER_TRANSFER_ENCODING: string; + const HTTP2_HEADER_TE: string; + const HTTP2_HEADER_UPGRADE: string; + const HTTP2_HEADER_USER_AGENT: string; + const HTTP2_HEADER_VARY: string; + const HTTP2_HEADER_VIA: string; + const HTTP2_HEADER_WWW_AUTHENTICATE: string; + const HTTP2_HEADER_HTTP2_SETTINGS: string; + const HTTP2_HEADER_KEEP_ALIVE: string; + const HTTP2_HEADER_PROXY_CONNECTION: string; + const HTTP2_METHOD_ACL: string; + const HTTP2_METHOD_BASELINE_CONTROL: string; + const HTTP2_METHOD_BIND: string; + const HTTP2_METHOD_CHECKIN: string; + const HTTP2_METHOD_CHECKOUT: string; + const HTTP2_METHOD_CONNECT: string; + const HTTP2_METHOD_COPY: string; + const HTTP2_METHOD_DELETE: string; + const HTTP2_METHOD_GET: string; + const HTTP2_METHOD_HEAD: string; + const HTTP2_METHOD_LABEL: string; + const HTTP2_METHOD_LINK: string; + const HTTP2_METHOD_LOCK: string; + const HTTP2_METHOD_MERGE: string; + const HTTP2_METHOD_MKACTIVITY: string; + const HTTP2_METHOD_MKCALENDAR: string; + const HTTP2_METHOD_MKCOL: string; + const HTTP2_METHOD_MKREDIRECTREF: string; + const HTTP2_METHOD_MKWORKSPACE: string; + const HTTP2_METHOD_MOVE: string; + const HTTP2_METHOD_OPTIONS: string; + const HTTP2_METHOD_ORDERPATCH: string; + const HTTP2_METHOD_PATCH: string; + const HTTP2_METHOD_POST: string; + const HTTP2_METHOD_PRI: string; + const HTTP2_METHOD_PROPFIND: string; + const HTTP2_METHOD_PROPPATCH: string; + const HTTP2_METHOD_PUT: string; + const HTTP2_METHOD_REBIND: string; + const HTTP2_METHOD_REPORT: string; + const HTTP2_METHOD_SEARCH: string; + const HTTP2_METHOD_TRACE: string; + const HTTP2_METHOD_UNBIND: string; + const HTTP2_METHOD_UNCHECKOUT: string; + const HTTP2_METHOD_UNLINK: string; + const HTTP2_METHOD_UNLOCK: string; + const HTTP2_METHOD_UPDATE: string; + const HTTP2_METHOD_UPDATEREDIRECTREF: string; + const HTTP2_METHOD_VERSION_CONTROL: string; + const HTTP_STATUS_CONTINUE: number; + const HTTP_STATUS_SWITCHING_PROTOCOLS: number; + const HTTP_STATUS_PROCESSING: number; + const HTTP_STATUS_OK: number; + const HTTP_STATUS_CREATED: number; + const HTTP_STATUS_ACCEPTED: number; + const HTTP_STATUS_NON_AUTHORITATIVE_INFORMATION: number; + const HTTP_STATUS_NO_CONTENT: number; + const HTTP_STATUS_RESET_CONTENT: number; + const HTTP_STATUS_PARTIAL_CONTENT: number; + const HTTP_STATUS_MULTI_STATUS: number; + const HTTP_STATUS_ALREADY_REPORTED: number; + const HTTP_STATUS_IM_USED: number; + const HTTP_STATUS_MULTIPLE_CHOICES: number; + const HTTP_STATUS_MOVED_PERMANENTLY: number; + const HTTP_STATUS_FOUND: number; + const HTTP_STATUS_SEE_OTHER: number; + const HTTP_STATUS_NOT_MODIFIED: number; + const HTTP_STATUS_USE_PROXY: number; + const HTTP_STATUS_TEMPORARY_REDIRECT: number; + const HTTP_STATUS_PERMANENT_REDIRECT: number; + const HTTP_STATUS_BAD_REQUEST: number; + const HTTP_STATUS_UNAUTHORIZED: number; + const HTTP_STATUS_PAYMENT_REQUIRED: number; + const HTTP_STATUS_FORBIDDEN: number; + const HTTP_STATUS_NOT_FOUND: number; + const HTTP_STATUS_METHOD_NOT_ALLOWED: number; + const HTTP_STATUS_NOT_ACCEPTABLE: number; + const HTTP_STATUS_PROXY_AUTHENTICATION_REQUIRED: number; + const HTTP_STATUS_REQUEST_TIMEOUT: number; + const HTTP_STATUS_CONFLICT: number; + const HTTP_STATUS_GONE: number; + const HTTP_STATUS_LENGTH_REQUIRED: number; + const HTTP_STATUS_PRECONDITION_FAILED: number; + const HTTP_STATUS_PAYLOAD_TOO_LARGE: number; + const HTTP_STATUS_URI_TOO_LONG: number; + const HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE: number; + const HTTP_STATUS_RANGE_NOT_SATISFIABLE: number; + const HTTP_STATUS_EXPECTATION_FAILED: number; + const HTTP_STATUS_TEAPOT: number; + const HTTP_STATUS_MISDIRECTED_REQUEST: number; + const HTTP_STATUS_UNPROCESSABLE_ENTITY: number; + const HTTP_STATUS_LOCKED: number; + const HTTP_STATUS_FAILED_DEPENDENCY: number; + const HTTP_STATUS_UNORDERED_COLLECTION: number; + const HTTP_STATUS_UPGRADE_REQUIRED: number; + const HTTP_STATUS_PRECONDITION_REQUIRED: number; + const HTTP_STATUS_TOO_MANY_REQUESTS: number; + const HTTP_STATUS_REQUEST_HEADER_FIELDS_TOO_LARGE: number; + const HTTP_STATUS_UNAVAILABLE_FOR_LEGAL_REASONS: number; + const HTTP_STATUS_INTERNAL_SERVER_ERROR: number; + const HTTP_STATUS_NOT_IMPLEMENTED: number; + const HTTP_STATUS_BAD_GATEWAY: number; + const HTTP_STATUS_SERVICE_UNAVAILABLE: number; + const HTTP_STATUS_GATEWAY_TIMEOUT: number; + const HTTP_STATUS_HTTP_VERSION_NOT_SUPPORTED: number; + const HTTP_STATUS_VARIANT_ALSO_NEGOTIATES: number; + const HTTP_STATUS_INSUFFICIENT_STORAGE: number; + const HTTP_STATUS_LOOP_DETECTED: number; + const HTTP_STATUS_BANDWIDTH_LIMIT_EXCEEDED: number; + const HTTP_STATUS_NOT_EXTENDED: number; + const HTTP_STATUS_NETWORK_AUTHENTICATION_REQUIRED: number; + } + + export function getDefaultSettings(): Settings; + export function getPackedSettings(settings: Settings): Settings; + export function getUnpackedSettings(buf: Buffer | Uint8Array): Settings; + + export function createServer(onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void): Http2Server; + export function createServer(options: ServerOptions, onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void): Http2Server; + + export function createSecureServer(onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void): Http2SecureServer; + export function createSecureServer(options: SecureServerOptions, onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void): Http2SecureServer; + + export function connect(authority: string | url.URL, listener?: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): ClientHttp2Session; + export function connect( + authority: string | url.URL, + options?: ClientSessionOptions | SecureClientSessionOptions, + listener?: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void, + ): ClientHttp2Session; +} + +declare module "perf_hooks" { + import { AsyncResource } from "async_hooks"; + + interface PerformanceEntry { + /** + * The total number of milliseconds elapsed for this entry. + * This value will not be meaningful for all Performance Entry types. + */ + readonly duration: number; + + /** + * The name of the performance entry. + */ + readonly name: string; + + /** + * The high resolution millisecond timestamp marking the starting time of the Performance Entry. + */ + readonly startTime: number; + + /** + * The type of the performance entry. + * Currently it may be one of: 'node', 'mark', 'measure', 'gc', or 'function'. + */ + readonly entryType: string; + + /** + * When performanceEntry.entryType is equal to 'gc', the performance.kind property identifies + * the type of garbage collection operation that occurred. + * The value may be one of perf_hooks.constants. + */ + readonly kind?: number; + } + + interface PerformanceNodeTiming extends PerformanceEntry { + /** + * The high resolution millisecond timestamp at which the Node.js process completed bootstrap. + */ + readonly bootstrapComplete: number; + + /** + * The high resolution millisecond timestamp at which cluster processing ended. + */ + readonly clusterSetupEnd: number; + + /** + * The high resolution millisecond timestamp at which cluster processing started. + */ + readonly clusterSetupStart: number; + + /** + * The high resolution millisecond timestamp at which the Node.js event loop exited. + */ + readonly loopExit: number; + + /** + * The high resolution millisecond timestamp at which the Node.js event loop started. + */ + readonly loopStart: number; + + /** + * The high resolution millisecond timestamp at which main module load ended. + */ + readonly moduleLoadEnd: number; + + /** + * The high resolution millisecond timestamp at which main module load started. + */ + readonly moduleLoadStart: number; + + /** + * The high resolution millisecond timestamp at which the Node.js process was initialized. + */ + readonly nodeStart: number; + + /** + * The high resolution millisecond timestamp at which preload module load ended. + */ + readonly preloadModuleLoadEnd: number; + + /** + * The high resolution millisecond timestamp at which preload module load started. + */ + readonly preloadModuleLoadStart: number; + + /** + * The high resolution millisecond timestamp at which third_party_main processing ended. + */ + readonly thirdPartyMainEnd: number; + + /** + * The high resolution millisecond timestamp at which third_party_main processing started. + */ + readonly thirdPartyMainStart: number; + + /** + * The high resolution millisecond timestamp at which the V8 platform was initialized. + */ + readonly v8Start: number; + } + + interface Performance { + /** + * If name is not provided, removes all PerformanceFunction objects from the Performance Timeline. + * If name is provided, removes entries with name. + * @param name + */ + clearFunctions(name?: string): void; + + /** + * If name is not provided, removes all PerformanceMark objects from the Performance Timeline. + * If name is provided, removes only the named mark. + * @param name + */ + clearMarks(name?: string): void; + + /** + * If name is not provided, removes all PerformanceMeasure objects from the Performance Timeline. + * If name is provided, removes only objects whose performanceEntry.name matches name. + */ + clearMeasures(name?: string): void; + + /** + * Returns a list of all PerformanceEntry objects in chronological order with respect to performanceEntry.startTime. + * @return list of all PerformanceEntry objects + */ + getEntries(): PerformanceEntry[]; + + /** + * Returns a list of all PerformanceEntry objects in chronological order with respect to performanceEntry.startTime + * whose performanceEntry.name is equal to name, and optionally, whose performanceEntry.entryType is equal to type. + * @param name + * @param type + * @return list of all PerformanceEntry objects + */ + getEntriesByName(name: string, type?: string): PerformanceEntry[]; + + /** + * Returns a list of all PerformanceEntry objects in chronological order with respect to performanceEntry.startTime + * whose performanceEntry.entryType is equal to type. + * @param type + * @return list of all PerformanceEntry objects + */ + getEntriesByType(type: string): PerformanceEntry[]; + + /** + * Creates a new PerformanceMark entry in the Performance Timeline. + * A PerformanceMark is a subclass of PerformanceEntry whose performanceEntry.entryType is always 'mark', + * and whose performanceEntry.duration is always 0. + * Performance marks are used to mark specific significant moments in the Performance Timeline. + * @param name + */ + mark(name?: string): void; + + /** + * Creates a new PerformanceMeasure entry in the Performance Timeline. + * A PerformanceMeasure is a subclass of PerformanceEntry whose performanceEntry.entryType is always 'measure', + * and whose performanceEntry.duration measures the number of milliseconds elapsed since startMark and endMark. + * + * The startMark argument may identify any existing PerformanceMark in the the Performance Timeline, or may identify + * any of the timestamp properties provided by the PerformanceNodeTiming class. If the named startMark does not exist, + * then startMark is set to timeOrigin by default. + * + * The endMark argument must identify any existing PerformanceMark in the the Performance Timeline or any of the timestamp + * properties provided by the PerformanceNodeTiming class. If the named endMark does not exist, an error will be thrown. + * @param name + * @param startMark + * @param endMark + */ + measure(name: string, startMark: string, endMark: string): void; + + /** + * An instance of the PerformanceNodeTiming class that provides performance metrics for specific Node.js operational milestones. + */ + readonly nodeTiming: PerformanceNodeTiming; + + /** + * @return the current high resolution millisecond timestamp + */ + now(): number; + + /** + * The timeOrigin specifies the high resolution millisecond timestamp from which all performance metric durations are measured. + */ + readonly timeOrigin: number; + + /** + * Wraps a function within a new function that measures the running time of the wrapped function. + * A PerformanceObserver must be subscribed to the 'function' event type in order for the timing details to be accessed. + * @param fn + */ + timerify any>(fn: T): T; + } + + interface PerformanceObserverEntryList { + /** + * @return a list of PerformanceEntry objects in chronological order with respect to performanceEntry.startTime. + */ + getEntries(): PerformanceEntry[]; + + /** + * @return a list of PerformanceEntry objects in chronological order with respect to performanceEntry.startTime + * whose performanceEntry.name is equal to name, and optionally, whose performanceEntry.entryType is equal to type. + */ + getEntriesByName(name: string, type?: string): PerformanceEntry[]; + + /** + * @return Returns a list of PerformanceEntry objects in chronological order with respect to performanceEntry.startTime + * whose performanceEntry.entryType is equal to type. + */ + getEntriesByType(type: string): PerformanceEntry[]; + } + + type PerformanceObserverCallback = (list: PerformanceObserverEntryList, observer: PerformanceObserver) => void; + + class PerformanceObserver extends AsyncResource { + constructor(callback: PerformanceObserverCallback); + + /** + * Disconnects the PerformanceObserver instance from all notifications. + */ + disconnect(): void; + + /** + * Subscribes the PerformanceObserver instance to notifications of new PerformanceEntry instances identified by options.entryTypes. + * When options.buffered is false, the callback will be invoked once for every PerformanceEntry instance. + * Property buffered defaults to false. + * @param options + */ + observe(options: { entryTypes: string[], buffered?: boolean }): void; + } + + namespace constants { + const NODE_PERFORMANCE_GC_MAJOR: number; + const NODE_PERFORMANCE_GC_MINOR: number; + const NODE_PERFORMANCE_GC_INCREMENTAL: number; + const NODE_PERFORMANCE_GC_WEAKCB: number; + } + + const performance: Performance; +} + +declare module "trace_events" { + /** + * The `Tracing` object is used to enable or disable tracing for sets of + * categories. Instances are created using the + * `trace_events.createTracing()` method. + * + * When created, the `Tracing` object is disabled. Calling the + * `tracing.enable()` method adds the categories to the set of enabled trace + * event categories. Calling `tracing.disable()` will remove the categories + * from the set of enabled trace event categories. + */ + export interface Tracing { + /** + * A comma-separated list of the trace event categories covered by this + * `Tracing` object. + */ + readonly categories: string; + + /** + * Disables this `Tracing` object. + * + * Only trace event categories _not_ covered by other enabled `Tracing` + * objects and _not_ specified by the `--trace-event-categories` flag + * will be disabled. + */ + disable(): void; + + /** + * Enables this `Tracing` object for the set of categories covered by + * the `Tracing` object. + */ + enable(): void; + + /** + * `true` only if the `Tracing` object has been enabled. + */ + readonly enabled: boolean; + } + + interface CreateTracingOptions { + /** + * An array of trace category names. Values included in the array are + * coerced to a string when possible. An error will be thrown if the + * value cannot be coerced. + */ + categories: string[]; + } + + /** + * Creates and returns a Tracing object for the given set of categories. + */ + export function createTracing(options: CreateTracingOptions): Tracing; + + /** + * Returns a comma-separated list of all currently-enabled trace event + * categories. The current set of enabled trace event categories is + * determined by the union of all currently-enabled `Tracing` objects and + * any categories enabled using the `--trace-event-categories` flag. + */ + export function getEnabledCategories(): string; +} diff --git a/node_modules/@types/node/inspector.d.ts b/node_modules/@types/node/inspector.d.ts new file mode 100644 index 0000000..a9d0f11 --- /dev/null +++ b/node_modules/@types/node/inspector.d.ts @@ -0,0 +1,3163 @@ +// tslint:disable-next-line:dt-header +// Type definitions for inspector + +// These definitions are auto-generated. +// Please see https://github.com/DefinitelyTyped/DefinitelyTyped/pull/19330 +// for more information. + +/** + * The inspector module provides an API for interacting with the V8 inspector. + */ +// tslint:disable-next-line:no-single-declare-module +declare module "inspector" { + import { EventEmitter } from 'events'; + + interface InspectorNotification { + method: string; + params: T; + } + + namespace Console { + /** + * Console message. + */ + interface ConsoleMessage { + /** + * Message source. + */ + source: string; + /** + * Message severity. + */ + level: string; + /** + * Message text. + */ + text: string; + /** + * URL of the message origin. + */ + url?: string; + /** + * Line number in the resource that generated this message (1-based). + */ + line?: number; + /** + * Column number in the resource that generated this message (1-based). + */ + column?: number; + } + + interface MessageAddedEventDataType { + /** + * Console message that has been added. + */ + message: ConsoleMessage; + } + } + + namespace Debugger { + /** + * Breakpoint identifier. + */ + type BreakpointId = string; + + /** + * Call frame identifier. + */ + type CallFrameId = string; + + /** + * Location in the source code. + */ + interface Location { + /** + * Script identifier as reported in the `Debugger.scriptParsed`. + */ + scriptId: Runtime.ScriptId; + /** + * Line number in the script (0-based). + */ + lineNumber: number; + /** + * Column number in the script (0-based). + */ + columnNumber?: number; + } + + /** + * Location in the source code. + * @experimental + */ + interface ScriptPosition { + lineNumber: number; + columnNumber: number; + } + + /** + * JavaScript call frame. Array of call frames form the call stack. + */ + interface CallFrame { + /** + * Call frame identifier. This identifier is only valid while the virtual machine is paused. + */ + callFrameId: CallFrameId; + /** + * Name of the JavaScript function called on this call frame. + */ + functionName: string; + /** + * Location in the source code. + */ + functionLocation?: Location; + /** + * Location in the source code. + */ + location: Location; + /** + * JavaScript script name or url. + */ + url: string; + /** + * Scope chain for this call frame. + */ + scopeChain: Scope[]; + /** + * `this` object for this call frame. + */ + this: Runtime.RemoteObject; + /** + * The value being returned, if the function is at return point. + */ + returnValue?: Runtime.RemoteObject; + } + + /** + * Scope description. + */ + interface Scope { + /** + * Scope type. + */ + type: string; + /** + * Object representing the scope. For `global` and `with` scopes it represents the actual + * object; for the rest of the scopes, it is artificial transient object enumerating scope + * variables as its properties. + */ + object: Runtime.RemoteObject; + name?: string; + /** + * Location in the source code where scope starts + */ + startLocation?: Location; + /** + * Location in the source code where scope ends + */ + endLocation?: Location; + } + + /** + * Search match for resource. + */ + interface SearchMatch { + /** + * Line number in resource content. + */ + lineNumber: number; + /** + * Line with match content. + */ + lineContent: string; + } + + interface BreakLocation { + /** + * Script identifier as reported in the `Debugger.scriptParsed`. + */ + scriptId: Runtime.ScriptId; + /** + * Line number in the script (0-based). + */ + lineNumber: number; + /** + * Column number in the script (0-based). + */ + columnNumber?: number; + type?: string; + } + + interface ContinueToLocationParameterType { + /** + * Location to continue to. + */ + location: Location; + targetCallFrames?: string; + } + + interface EvaluateOnCallFrameParameterType { + /** + * Call frame identifier to evaluate on. + */ + callFrameId: CallFrameId; + /** + * Expression to evaluate. + */ + expression: string; + /** + * String object group name to put result into (allows rapid releasing resulting object handles + * using `releaseObjectGroup`). + */ + objectGroup?: string; + /** + * Specifies whether command line API should be available to the evaluated expression, defaults + * to false. + */ + includeCommandLineAPI?: boolean; + /** + * In silent mode exceptions thrown during evaluation are not reported and do not pause + * execution. Overrides `setPauseOnException` state. + */ + silent?: boolean; + /** + * Whether the result is expected to be a JSON object that should be sent by value. + */ + returnByValue?: boolean; + /** + * Whether preview should be generated for the result. + * @experimental + */ + generatePreview?: boolean; + /** + * Whether to throw an exception if side effect cannot be ruled out during evaluation. + */ + throwOnSideEffect?: boolean; + /** + * Terminate execution after timing out (number of milliseconds). + * @experimental + */ + timeout?: Runtime.TimeDelta; + } + + interface GetPossibleBreakpointsParameterType { + /** + * Start of range to search possible breakpoint locations in. + */ + start: Location; + /** + * End of range to search possible breakpoint locations in (excluding). When not specified, end + * of scripts is used as end of range. + */ + end?: Location; + /** + * Only consider locations which are in the same (non-nested) function as start. + */ + restrictToFunction?: boolean; + } + + interface GetScriptSourceParameterType { + /** + * Id of the script to get source for. + */ + scriptId: Runtime.ScriptId; + } + + interface GetStackTraceParameterType { + stackTraceId: Runtime.StackTraceId; + } + + interface PauseOnAsyncCallParameterType { + /** + * Debugger will pause when async call with given stack trace is started. + */ + parentStackTraceId: Runtime.StackTraceId; + } + + interface RemoveBreakpointParameterType { + breakpointId: BreakpointId; + } + + interface RestartFrameParameterType { + /** + * Call frame identifier to evaluate on. + */ + callFrameId: CallFrameId; + } + + interface SearchInContentParameterType { + /** + * Id of the script to search in. + */ + scriptId: Runtime.ScriptId; + /** + * String to search for. + */ + query: string; + /** + * If true, search is case sensitive. + */ + caseSensitive?: boolean; + /** + * If true, treats string parameter as regex. + */ + isRegex?: boolean; + } + + interface SetAsyncCallStackDepthParameterType { + /** + * Maximum depth of async call stacks. Setting to `0` will effectively disable collecting async + * call stacks (default). + */ + maxDepth: number; + } + + interface SetBlackboxPatternsParameterType { + /** + * Array of regexps that will be used to check script url for blackbox state. + */ + patterns: string[]; + } + + interface SetBlackboxedRangesParameterType { + /** + * Id of the script. + */ + scriptId: Runtime.ScriptId; + positions: ScriptPosition[]; + } + + interface SetBreakpointParameterType { + /** + * Location to set breakpoint in. + */ + location: Location; + /** + * Expression to use as a breakpoint condition. When specified, debugger will only stop on the + * breakpoint if this expression evaluates to true. + */ + condition?: string; + } + + interface SetBreakpointByUrlParameterType { + /** + * Line number to set breakpoint at. + */ + lineNumber: number; + /** + * URL of the resources to set breakpoint on. + */ + url?: string; + /** + * Regex pattern for the URLs of the resources to set breakpoints on. Either `url` or + * `urlRegex` must be specified. + */ + urlRegex?: string; + /** + * Script hash of the resources to set breakpoint on. + */ + scriptHash?: string; + /** + * Offset in the line to set breakpoint at. + */ + columnNumber?: number; + /** + * Expression to use as a breakpoint condition. When specified, debugger will only stop on the + * breakpoint if this expression evaluates to true. + */ + condition?: string; + } + + interface SetBreakpointOnFunctionCallParameterType { + /** + * Function object id. + */ + objectId: Runtime.RemoteObjectId; + /** + * Expression to use as a breakpoint condition. When specified, debugger will + * stop on the breakpoint if this expression evaluates to true. + */ + condition?: string; + } + + interface SetBreakpointsActiveParameterType { + /** + * New value for breakpoints active state. + */ + active: boolean; + } + + interface SetPauseOnExceptionsParameterType { + /** + * Pause on exceptions mode. + */ + state: string; + } + + interface SetReturnValueParameterType { + /** + * New return value. + */ + newValue: Runtime.CallArgument; + } + + interface SetScriptSourceParameterType { + /** + * Id of the script to edit. + */ + scriptId: Runtime.ScriptId; + /** + * New content of the script. + */ + scriptSource: string; + /** + * If true the change will not actually be applied. Dry run may be used to get result + * description without actually modifying the code. + */ + dryRun?: boolean; + } + + interface SetSkipAllPausesParameterType { + /** + * New value for skip pauses state. + */ + skip: boolean; + } + + interface SetVariableValueParameterType { + /** + * 0-based number of scope as was listed in scope chain. Only 'local', 'closure' and 'catch' + * scope types are allowed. Other scopes could be manipulated manually. + */ + scopeNumber: number; + /** + * Variable name. + */ + variableName: string; + /** + * New variable value. + */ + newValue: Runtime.CallArgument; + /** + * Id of callframe that holds variable. + */ + callFrameId: CallFrameId; + } + + interface StepIntoParameterType { + /** + * Debugger will issue additional Debugger.paused notification if any async task is scheduled + * before next pause. + * @experimental + */ + breakOnAsyncCall?: boolean; + } + + interface EnableReturnType { + /** + * Unique identifier of the debugger. + * @experimental + */ + debuggerId: Runtime.UniqueDebuggerId; + } + + interface EvaluateOnCallFrameReturnType { + /** + * Object wrapper for the evaluation result. + */ + result: Runtime.RemoteObject; + /** + * Exception details. + */ + exceptionDetails?: Runtime.ExceptionDetails; + } + + interface GetPossibleBreakpointsReturnType { + /** + * List of the possible breakpoint locations. + */ + locations: BreakLocation[]; + } + + interface GetScriptSourceReturnType { + /** + * Script source. + */ + scriptSource: string; + } + + interface GetStackTraceReturnType { + stackTrace: Runtime.StackTrace; + } + + interface RestartFrameReturnType { + /** + * New stack trace. + */ + callFrames: CallFrame[]; + /** + * Async stack trace, if any. + */ + asyncStackTrace?: Runtime.StackTrace; + /** + * Async stack trace, if any. + * @experimental + */ + asyncStackTraceId?: Runtime.StackTraceId; + } + + interface SearchInContentReturnType { + /** + * List of search matches. + */ + result: SearchMatch[]; + } + + interface SetBreakpointReturnType { + /** + * Id of the created breakpoint for further reference. + */ + breakpointId: BreakpointId; + /** + * Location this breakpoint resolved into. + */ + actualLocation: Location; + } + + interface SetBreakpointByUrlReturnType { + /** + * Id of the created breakpoint for further reference. + */ + breakpointId: BreakpointId; + /** + * List of the locations this breakpoint resolved into upon addition. + */ + locations: Location[]; + } + + interface SetBreakpointOnFunctionCallReturnType { + /** + * Id of the created breakpoint for further reference. + */ + breakpointId: BreakpointId; + } + + interface SetScriptSourceReturnType { + /** + * New stack trace in case editing has happened while VM was stopped. + */ + callFrames?: CallFrame[]; + /** + * Whether current call stack was modified after applying the changes. + */ + stackChanged?: boolean; + /** + * Async stack trace, if any. + */ + asyncStackTrace?: Runtime.StackTrace; + /** + * Async stack trace, if any. + * @experimental + */ + asyncStackTraceId?: Runtime.StackTraceId; + /** + * Exception details if any. + */ + exceptionDetails?: Runtime.ExceptionDetails; + } + + interface BreakpointResolvedEventDataType { + /** + * Breakpoint unique identifier. + */ + breakpointId: BreakpointId; + /** + * Actual breakpoint location. + */ + location: Location; + } + + interface PausedEventDataType { + /** + * Call stack the virtual machine stopped on. + */ + callFrames: CallFrame[]; + /** + * Pause reason. + */ + reason: string; + /** + * Object containing break-specific auxiliary properties. + */ + data?: {}; + /** + * Hit breakpoints IDs + */ + hitBreakpoints?: string[]; + /** + * Async stack trace, if any. + */ + asyncStackTrace?: Runtime.StackTrace; + /** + * Async stack trace, if any. + * @experimental + */ + asyncStackTraceId?: Runtime.StackTraceId; + /** + * Just scheduled async call will have this stack trace as parent stack during async execution. + * This field is available only after `Debugger.stepInto` call with `breakOnAsynCall` flag. + * @experimental + */ + asyncCallStackTraceId?: Runtime.StackTraceId; + } + + interface ScriptFailedToParseEventDataType { + /** + * Identifier of the script parsed. + */ + scriptId: Runtime.ScriptId; + /** + * URL or name of the script parsed (if any). + */ + url: string; + /** + * Line offset of the script within the resource with given URL (for script tags). + */ + startLine: number; + /** + * Column offset of the script within the resource with given URL. + */ + startColumn: number; + /** + * Last line of the script. + */ + endLine: number; + /** + * Length of the last line of the script. + */ + endColumn: number; + /** + * Specifies script creation context. + */ + executionContextId: Runtime.ExecutionContextId; + /** + * Content hash of the script. + */ + hash: string; + /** + * Embedder-specific auxiliary data. + */ + executionContextAuxData?: {}; + /** + * URL of source map associated with script (if any). + */ + sourceMapURL?: string; + /** + * True, if this script has sourceURL. + */ + hasSourceURL?: boolean; + /** + * True, if this script is ES6 module. + */ + isModule?: boolean; + /** + * This script length. + */ + length?: number; + /** + * JavaScript top stack frame of where the script parsed event was triggered if available. + * @experimental + */ + stackTrace?: Runtime.StackTrace; + } + + interface ScriptParsedEventDataType { + /** + * Identifier of the script parsed. + */ + scriptId: Runtime.ScriptId; + /** + * URL or name of the script parsed (if any). + */ + url: string; + /** + * Line offset of the script within the resource with given URL (for script tags). + */ + startLine: number; + /** + * Column offset of the script within the resource with given URL. + */ + startColumn: number; + /** + * Last line of the script. + */ + endLine: number; + /** + * Length of the last line of the script. + */ + endColumn: number; + /** + * Specifies script creation context. + */ + executionContextId: Runtime.ExecutionContextId; + /** + * Content hash of the script. + */ + hash: string; + /** + * Embedder-specific auxiliary data. + */ + executionContextAuxData?: {}; + /** + * True, if this script is generated as a result of the live edit operation. + * @experimental + */ + isLiveEdit?: boolean; + /** + * URL of source map associated with script (if any). + */ + sourceMapURL?: string; + /** + * True, if this script has sourceURL. + */ + hasSourceURL?: boolean; + /** + * True, if this script is ES6 module. + */ + isModule?: boolean; + /** + * This script length. + */ + length?: number; + /** + * JavaScript top stack frame of where the script parsed event was triggered if available. + * @experimental + */ + stackTrace?: Runtime.StackTrace; + } + } + + namespace HeapProfiler { + /** + * Heap snapshot object id. + */ + type HeapSnapshotObjectId = string; + + /** + * Sampling Heap Profile node. Holds callsite information, allocation statistics and child nodes. + */ + interface SamplingHeapProfileNode { + /** + * Function location. + */ + callFrame: Runtime.CallFrame; + /** + * Allocations size in bytes for the node excluding children. + */ + selfSize: number; + /** + * Child nodes. + */ + children: SamplingHeapProfileNode[]; + } + + /** + * Profile. + */ + interface SamplingHeapProfile { + head: SamplingHeapProfileNode; + } + + interface AddInspectedHeapObjectParameterType { + /** + * Heap snapshot object id to be accessible by means of $x command line API. + */ + heapObjectId: HeapSnapshotObjectId; + } + + interface GetHeapObjectIdParameterType { + /** + * Identifier of the object to get heap object id for. + */ + objectId: Runtime.RemoteObjectId; + } + + interface GetObjectByHeapObjectIdParameterType { + objectId: HeapSnapshotObjectId; + /** + * Symbolic group name that can be used to release multiple objects. + */ + objectGroup?: string; + } + + interface StartSamplingParameterType { + /** + * Average sample interval in bytes. Poisson distribution is used for the intervals. The + * default value is 32768 bytes. + */ + samplingInterval?: number; + } + + interface StartTrackingHeapObjectsParameterType { + trackAllocations?: boolean; + } + + interface StopTrackingHeapObjectsParameterType { + /** + * If true 'reportHeapSnapshotProgress' events will be generated while snapshot is being taken + * when the tracking is stopped. + */ + reportProgress?: boolean; + } + + interface TakeHeapSnapshotParameterType { + /** + * If true 'reportHeapSnapshotProgress' events will be generated while snapshot is being taken. + */ + reportProgress?: boolean; + } + + interface GetHeapObjectIdReturnType { + /** + * Id of the heap snapshot object corresponding to the passed remote object id. + */ + heapSnapshotObjectId: HeapSnapshotObjectId; + } + + interface GetObjectByHeapObjectIdReturnType { + /** + * Evaluation result. + */ + result: Runtime.RemoteObject; + } + + interface GetSamplingProfileReturnType { + /** + * Return the sampling profile being collected. + */ + profile: SamplingHeapProfile; + } + + interface StopSamplingReturnType { + /** + * Recorded sampling heap profile. + */ + profile: SamplingHeapProfile; + } + + interface AddHeapSnapshotChunkEventDataType { + chunk: string; + } + + interface HeapStatsUpdateEventDataType { + /** + * An array of triplets. Each triplet describes a fragment. The first integer is the fragment + * index, the second integer is a total count of objects for the fragment, the third integer is + * a total size of the objects for the fragment. + */ + statsUpdate: number[]; + } + + interface LastSeenObjectIdEventDataType { + lastSeenObjectId: number; + timestamp: number; + } + + interface ReportHeapSnapshotProgressEventDataType { + done: number; + total: number; + finished?: boolean; + } + } + + namespace Profiler { + /** + * Profile node. Holds callsite information, execution statistics and child nodes. + */ + interface ProfileNode { + /** + * Unique id of the node. + */ + id: number; + /** + * Function location. + */ + callFrame: Runtime.CallFrame; + /** + * Number of samples where this node was on top of the call stack. + */ + hitCount?: number; + /** + * Child node ids. + */ + children?: number[]; + /** + * The reason of being not optimized. The function may be deoptimized or marked as don't + * optimize. + */ + deoptReason?: string; + /** + * An array of source position ticks. + */ + positionTicks?: PositionTickInfo[]; + } + + /** + * Profile. + */ + interface Profile { + /** + * The list of profile nodes. First item is the root node. + */ + nodes: ProfileNode[]; + /** + * Profiling start timestamp in microseconds. + */ + startTime: number; + /** + * Profiling end timestamp in microseconds. + */ + endTime: number; + /** + * Ids of samples top nodes. + */ + samples?: number[]; + /** + * Time intervals between adjacent samples in microseconds. The first delta is relative to the + * profile startTime. + */ + timeDeltas?: number[]; + } + + /** + * Specifies a number of samples attributed to a certain source position. + */ + interface PositionTickInfo { + /** + * Source line number (1-based). + */ + line: number; + /** + * Number of samples attributed to the source line. + */ + ticks: number; + } + + /** + * Coverage data for a source range. + */ + interface CoverageRange { + /** + * JavaScript script source offset for the range start. + */ + startOffset: number; + /** + * JavaScript script source offset for the range end. + */ + endOffset: number; + /** + * Collected execution count of the source range. + */ + count: number; + } + + /** + * Coverage data for a JavaScript function. + */ + interface FunctionCoverage { + /** + * JavaScript function name. + */ + functionName: string; + /** + * Source ranges inside the function with coverage data. + */ + ranges: CoverageRange[]; + /** + * Whether coverage data for this function has block granularity. + */ + isBlockCoverage: boolean; + } + + /** + * Coverage data for a JavaScript script. + */ + interface ScriptCoverage { + /** + * JavaScript script id. + */ + scriptId: Runtime.ScriptId; + /** + * JavaScript script name or url. + */ + url: string; + /** + * Functions contained in the script that has coverage data. + */ + functions: FunctionCoverage[]; + } + + /** + * Describes a type collected during runtime. + * @experimental + */ + interface TypeObject { + /** + * Name of a type collected with type profiling. + */ + name: string; + } + + /** + * Source offset and types for a parameter or return value. + * @experimental + */ + interface TypeProfileEntry { + /** + * Source offset of the parameter or end of function for return values. + */ + offset: number; + /** + * The types for this parameter or return value. + */ + types: TypeObject[]; + } + + /** + * Type profile data collected during runtime for a JavaScript script. + * @experimental + */ + interface ScriptTypeProfile { + /** + * JavaScript script id. + */ + scriptId: Runtime.ScriptId; + /** + * JavaScript script name or url. + */ + url: string; + /** + * Type profile entries for parameters and return values of the functions in the script. + */ + entries: TypeProfileEntry[]; + } + + interface SetSamplingIntervalParameterType { + /** + * New sampling interval in microseconds. + */ + interval: number; + } + + interface StartPreciseCoverageParameterType { + /** + * Collect accurate call counts beyond simple 'covered' or 'not covered'. + */ + callCount?: boolean; + /** + * Collect block-based coverage. + */ + detailed?: boolean; + } + + interface GetBestEffortCoverageReturnType { + /** + * Coverage data for the current isolate. + */ + result: ScriptCoverage[]; + } + + interface StopReturnType { + /** + * Recorded profile. + */ + profile: Profile; + } + + interface TakePreciseCoverageReturnType { + /** + * Coverage data for the current isolate. + */ + result: ScriptCoverage[]; + } + + interface TakeTypeProfileReturnType { + /** + * Type profile for all scripts since startTypeProfile() was turned on. + */ + result: ScriptTypeProfile[]; + } + + interface ConsoleProfileFinishedEventDataType { + id: string; + /** + * Location of console.profileEnd(). + */ + location: Debugger.Location; + profile: Profile; + /** + * Profile title passed as an argument to console.profile(). + */ + title?: string; + } + + interface ConsoleProfileStartedEventDataType { + id: string; + /** + * Location of console.profile(). + */ + location: Debugger.Location; + /** + * Profile title passed as an argument to console.profile(). + */ + title?: string; + } + } + + namespace Runtime { + /** + * Unique script identifier. + */ + type ScriptId = string; + + /** + * Unique object identifier. + */ + type RemoteObjectId = string; + + /** + * Primitive value which cannot be JSON-stringified. Includes values `-0`, `NaN`, `Infinity`, + * `-Infinity`, and bigint literals. + */ + type UnserializableValue = string; + + /** + * Mirror object referencing original JavaScript object. + */ + interface RemoteObject { + /** + * Object type. + */ + type: string; + /** + * Object subtype hint. Specified for `object` type values only. + */ + subtype?: string; + /** + * Object class (constructor) name. Specified for `object` type values only. + */ + className?: string; + /** + * Remote object value in case of primitive values or JSON values (if it was requested). + */ + value?: any; + /** + * Primitive value which can not be JSON-stringified does not have `value`, but gets this + * property. + */ + unserializableValue?: UnserializableValue; + /** + * String representation of the object. + */ + description?: string; + /** + * Unique object identifier (for non-primitive values). + */ + objectId?: RemoteObjectId; + /** + * Preview containing abbreviated property values. Specified for `object` type values only. + * @experimental + */ + preview?: ObjectPreview; + /** + * @experimental + */ + customPreview?: CustomPreview; + } + + /** + * @experimental + */ + interface CustomPreview { + header: string; + hasBody: boolean; + formatterObjectId: RemoteObjectId; + bindRemoteObjectFunctionId: RemoteObjectId; + configObjectId?: RemoteObjectId; + } + + /** + * Object containing abbreviated remote object value. + * @experimental + */ + interface ObjectPreview { + /** + * Object type. + */ + type: string; + /** + * Object subtype hint. Specified for `object` type values only. + */ + subtype?: string; + /** + * String representation of the object. + */ + description?: string; + /** + * True iff some of the properties or entries of the original object did not fit. + */ + overflow: boolean; + /** + * List of the properties. + */ + properties: PropertyPreview[]; + /** + * List of the entries. Specified for `map` and `set` subtype values only. + */ + entries?: EntryPreview[]; + } + + /** + * @experimental + */ + interface PropertyPreview { + /** + * Property name. + */ + name: string; + /** + * Object type. Accessor means that the property itself is an accessor property. + */ + type: string; + /** + * User-friendly property value string. + */ + value?: string; + /** + * Nested value preview. + */ + valuePreview?: ObjectPreview; + /** + * Object subtype hint. Specified for `object` type values only. + */ + subtype?: string; + } + + /** + * @experimental + */ + interface EntryPreview { + /** + * Preview of the key. Specified for map-like collection entries. + */ + key?: ObjectPreview; + /** + * Preview of the value. + */ + value: ObjectPreview; + } + + /** + * Object property descriptor. + */ + interface PropertyDescriptor { + /** + * Property name or symbol description. + */ + name: string; + /** + * The value associated with the property. + */ + value?: RemoteObject; + /** + * True if the value associated with the property may be changed (data descriptors only). + */ + writable?: boolean; + /** + * A function which serves as a getter for the property, or `undefined` if there is no getter + * (accessor descriptors only). + */ + get?: RemoteObject; + /** + * A function which serves as a setter for the property, or `undefined` if there is no setter + * (accessor descriptors only). + */ + set?: RemoteObject; + /** + * True if the type of this property descriptor may be changed and if the property may be + * deleted from the corresponding object. + */ + configurable: boolean; + /** + * True if this property shows up during enumeration of the properties on the corresponding + * object. + */ + enumerable: boolean; + /** + * True if the result was thrown during the evaluation. + */ + wasThrown?: boolean; + /** + * True if the property is owned for the object. + */ + isOwn?: boolean; + /** + * Property symbol object, if the property is of the `symbol` type. + */ + symbol?: RemoteObject; + } + + /** + * Object internal property descriptor. This property isn't normally visible in JavaScript code. + */ + interface InternalPropertyDescriptor { + /** + * Conventional property name. + */ + name: string; + /** + * The value associated with the property. + */ + value?: RemoteObject; + } + + /** + * Represents function call argument. Either remote object id `objectId`, primitive `value`, + * unserializable primitive value or neither of (for undefined) them should be specified. + */ + interface CallArgument { + /** + * Primitive value or serializable javascript object. + */ + value?: any; + /** + * Primitive value which can not be JSON-stringified. + */ + unserializableValue?: UnserializableValue; + /** + * Remote object handle. + */ + objectId?: RemoteObjectId; + } + + /** + * Id of an execution context. + */ + type ExecutionContextId = number; + + /** + * Description of an isolated world. + */ + interface ExecutionContextDescription { + /** + * Unique id of the execution context. It can be used to specify in which execution context + * script evaluation should be performed. + */ + id: ExecutionContextId; + /** + * Execution context origin. + */ + origin: string; + /** + * Human readable name describing given context. + */ + name: string; + /** + * Embedder-specific auxiliary data. + */ + auxData?: {}; + } + + /** + * Detailed information about exception (or error) that was thrown during script compilation or + * execution. + */ + interface ExceptionDetails { + /** + * Exception id. + */ + exceptionId: number; + /** + * Exception text, which should be used together with exception object when available. + */ + text: string; + /** + * Line number of the exception location (0-based). + */ + lineNumber: number; + /** + * Column number of the exception location (0-based). + */ + columnNumber: number; + /** + * Script ID of the exception location. + */ + scriptId?: ScriptId; + /** + * URL of the exception location, to be used when the script was not reported. + */ + url?: string; + /** + * JavaScript stack trace if available. + */ + stackTrace?: StackTrace; + /** + * Exception object if available. + */ + exception?: RemoteObject; + /** + * Identifier of the context where exception happened. + */ + executionContextId?: ExecutionContextId; + } + + /** + * Number of milliseconds since epoch. + */ + type Timestamp = number; + + /** + * Number of milliseconds. + */ + type TimeDelta = number; + + /** + * Stack entry for runtime errors and assertions. + */ + interface CallFrame { + /** + * JavaScript function name. + */ + functionName: string; + /** + * JavaScript script id. + */ + scriptId: ScriptId; + /** + * JavaScript script name or url. + */ + url: string; + /** + * JavaScript script line number (0-based). + */ + lineNumber: number; + /** + * JavaScript script column number (0-based). + */ + columnNumber: number; + } + + /** + * Call frames for assertions or error messages. + */ + interface StackTrace { + /** + * String label of this stack trace. For async traces this may be a name of the function that + * initiated the async call. + */ + description?: string; + /** + * JavaScript function name. + */ + callFrames: CallFrame[]; + /** + * Asynchronous JavaScript stack trace that preceded this stack, if available. + */ + parent?: StackTrace; + /** + * Asynchronous JavaScript stack trace that preceded this stack, if available. + * @experimental + */ + parentId?: StackTraceId; + } + + /** + * Unique identifier of current debugger. + * @experimental + */ + type UniqueDebuggerId = string; + + /** + * If `debuggerId` is set stack trace comes from another debugger and can be resolved there. This + * allows to track cross-debugger calls. See `Runtime.StackTrace` and `Debugger.paused` for usages. + * @experimental + */ + interface StackTraceId { + id: string; + debuggerId?: UniqueDebuggerId; + } + + interface AwaitPromiseParameterType { + /** + * Identifier of the promise. + */ + promiseObjectId: RemoteObjectId; + /** + * Whether the result is expected to be a JSON object that should be sent by value. + */ + returnByValue?: boolean; + /** + * Whether preview should be generated for the result. + */ + generatePreview?: boolean; + } + + interface CallFunctionOnParameterType { + /** + * Declaration of the function to call. + */ + functionDeclaration: string; + /** + * Identifier of the object to call function on. Either objectId or executionContextId should + * be specified. + */ + objectId?: RemoteObjectId; + /** + * Call arguments. All call arguments must belong to the same JavaScript world as the target + * object. + */ + arguments?: CallArgument[]; + /** + * In silent mode exceptions thrown during evaluation are not reported and do not pause + * execution. Overrides `setPauseOnException` state. + */ + silent?: boolean; + /** + * Whether the result is expected to be a JSON object which should be sent by value. + */ + returnByValue?: boolean; + /** + * Whether preview should be generated for the result. + * @experimental + */ + generatePreview?: boolean; + /** + * Whether execution should be treated as initiated by user in the UI. + */ + userGesture?: boolean; + /** + * Whether execution should `await` for resulting value and return once awaited promise is + * resolved. + */ + awaitPromise?: boolean; + /** + * Specifies execution context which global object will be used to call function on. Either + * executionContextId or objectId should be specified. + */ + executionContextId?: ExecutionContextId; + /** + * Symbolic group name that can be used to release multiple objects. If objectGroup is not + * specified and objectId is, objectGroup will be inherited from object. + */ + objectGroup?: string; + } + + interface CompileScriptParameterType { + /** + * Expression to compile. + */ + expression: string; + /** + * Source url to be set for the script. + */ + sourceURL: string; + /** + * Specifies whether the compiled script should be persisted. + */ + persistScript: boolean; + /** + * Specifies in which execution context to perform script run. If the parameter is omitted the + * evaluation will be performed in the context of the inspected page. + */ + executionContextId?: ExecutionContextId; + } + + interface EvaluateParameterType { + /** + * Expression to evaluate. + */ + expression: string; + /** + * Symbolic group name that can be used to release multiple objects. + */ + objectGroup?: string; + /** + * Determines whether Command Line API should be available during the evaluation. + */ + includeCommandLineAPI?: boolean; + /** + * In silent mode exceptions thrown during evaluation are not reported and do not pause + * execution. Overrides `setPauseOnException` state. + */ + silent?: boolean; + /** + * Specifies in which execution context to perform evaluation. If the parameter is omitted the + * evaluation will be performed in the context of the inspected page. + */ + contextId?: ExecutionContextId; + /** + * Whether the result is expected to be a JSON object that should be sent by value. + */ + returnByValue?: boolean; + /** + * Whether preview should be generated for the result. + * @experimental + */ + generatePreview?: boolean; + /** + * Whether execution should be treated as initiated by user in the UI. + */ + userGesture?: boolean; + /** + * Whether execution should `await` for resulting value and return once awaited promise is + * resolved. + */ + awaitPromise?: boolean; + /** + * Whether to throw an exception if side effect cannot be ruled out during evaluation. + * @experimental + */ + throwOnSideEffect?: boolean; + /** + * Terminate execution after timing out (number of milliseconds). + * @experimental + */ + timeout?: TimeDelta; + } + + interface GetPropertiesParameterType { + /** + * Identifier of the object to return properties for. + */ + objectId: RemoteObjectId; + /** + * If true, returns properties belonging only to the element itself, not to its prototype + * chain. + */ + ownProperties?: boolean; + /** + * If true, returns accessor properties (with getter/setter) only; internal properties are not + * returned either. + * @experimental + */ + accessorPropertiesOnly?: boolean; + /** + * Whether preview should be generated for the results. + * @experimental + */ + generatePreview?: boolean; + } + + interface GlobalLexicalScopeNamesParameterType { + /** + * Specifies in which execution context to lookup global scope variables. + */ + executionContextId?: ExecutionContextId; + } + + interface QueryObjectsParameterType { + /** + * Identifier of the prototype to return objects for. + */ + prototypeObjectId: RemoteObjectId; + /** + * Symbolic group name that can be used to release the results. + */ + objectGroup?: string; + } + + interface ReleaseObjectParameterType { + /** + * Identifier of the object to release. + */ + objectId: RemoteObjectId; + } + + interface ReleaseObjectGroupParameterType { + /** + * Symbolic object group name. + */ + objectGroup: string; + } + + interface RunScriptParameterType { + /** + * Id of the script to run. + */ + scriptId: ScriptId; + /** + * Specifies in which execution context to perform script run. If the parameter is omitted the + * evaluation will be performed in the context of the inspected page. + */ + executionContextId?: ExecutionContextId; + /** + * Symbolic group name that can be used to release multiple objects. + */ + objectGroup?: string; + /** + * In silent mode exceptions thrown during evaluation are not reported and do not pause + * execution. Overrides `setPauseOnException` state. + */ + silent?: boolean; + /** + * Determines whether Command Line API should be available during the evaluation. + */ + includeCommandLineAPI?: boolean; + /** + * Whether the result is expected to be a JSON object which should be sent by value. + */ + returnByValue?: boolean; + /** + * Whether preview should be generated for the result. + */ + generatePreview?: boolean; + /** + * Whether execution should `await` for resulting value and return once awaited promise is + * resolved. + */ + awaitPromise?: boolean; + } + + interface SetCustomObjectFormatterEnabledParameterType { + enabled: boolean; + } + + interface AwaitPromiseReturnType { + /** + * Promise result. Will contain rejected value if promise was rejected. + */ + result: RemoteObject; + /** + * Exception details if stack strace is available. + */ + exceptionDetails?: ExceptionDetails; + } + + interface CallFunctionOnReturnType { + /** + * Call result. + */ + result: RemoteObject; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails; + } + + interface CompileScriptReturnType { + /** + * Id of the script. + */ + scriptId?: ScriptId; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails; + } + + interface EvaluateReturnType { + /** + * Evaluation result. + */ + result: RemoteObject; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails; + } + + interface GetIsolateIdReturnType { + /** + * The isolate id. + */ + id: string; + } + + interface GetHeapUsageReturnType { + /** + * Used heap size in bytes. + */ + usedSize: number; + /** + * Allocated heap size in bytes. + */ + totalSize: number; + } + + interface GetPropertiesReturnType { + /** + * Object properties. + */ + result: PropertyDescriptor[]; + /** + * Internal object properties (only of the element itself). + */ + internalProperties?: InternalPropertyDescriptor[]; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails; + } + + interface GlobalLexicalScopeNamesReturnType { + names: string[]; + } + + interface QueryObjectsReturnType { + /** + * Array with objects. + */ + objects: RemoteObject; + } + + interface RunScriptReturnType { + /** + * Run result. + */ + result: RemoteObject; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails; + } + + interface ConsoleAPICalledEventDataType { + /** + * Type of the call. + */ + type: string; + /** + * Call arguments. + */ + args: RemoteObject[]; + /** + * Identifier of the context where the call was made. + */ + executionContextId: ExecutionContextId; + /** + * Call timestamp. + */ + timestamp: Timestamp; + /** + * Stack trace captured when the call was made. + */ + stackTrace?: StackTrace; + /** + * Console context descriptor for calls on non-default console context (not console.*): + * 'anonymous#unique-logger-id' for call on unnamed context, 'name#unique-logger-id' for call + * on named context. + * @experimental + */ + context?: string; + } + + interface ExceptionRevokedEventDataType { + /** + * Reason describing why exception was revoked. + */ + reason: string; + /** + * The id of revoked exception, as reported in `exceptionThrown`. + */ + exceptionId: number; + } + + interface ExceptionThrownEventDataType { + /** + * Timestamp of the exception. + */ + timestamp: Timestamp; + exceptionDetails: ExceptionDetails; + } + + interface ExecutionContextCreatedEventDataType { + /** + * A newly created execution context. + */ + context: ExecutionContextDescription; + } + + interface ExecutionContextDestroyedEventDataType { + /** + * Id of the destroyed context + */ + executionContextId: ExecutionContextId; + } + + interface InspectRequestedEventDataType { + object: RemoteObject; + hints: {}; + } + } + + namespace Schema { + /** + * Description of the protocol domain. + */ + interface Domain { + /** + * Domain name. + */ + name: string; + /** + * Domain version. + */ + version: string; + } + + interface GetDomainsReturnType { + /** + * List of supported domains. + */ + domains: Domain[]; + } + } + + namespace NodeTracing { + interface TraceConfig { + /** + * Controls how the trace buffer stores data. + */ + recordMode?: string; + /** + * Included category filters. + */ + includedCategories: string[]; + } + + interface StartParameterType { + traceConfig: TraceConfig; + } + + interface GetCategoriesReturnType { + /** + * A list of supported tracing categories. + */ + categories: string[]; + } + + interface DataCollectedEventDataType { + value: Array<{}>; + } + } + + namespace NodeWorker { + type WorkerID = string; + + /** + * Unique identifier of attached debugging session. + */ + type SessionID = string; + + interface WorkerInfo { + workerId: WorkerID; + type: string; + title: string; + url: string; + } + + interface SendMessageToWorkerParameterType { + message: string; + /** + * Identifier of the session. + */ + sessionId: SessionID; + } + + interface EnableParameterType { + /** + * Whether to new workers should be paused until the frontend sends `Runtime.runIfWaitingForDebugger` + * message to run them. + */ + waitForDebuggerOnStart: boolean; + } + + interface AttachedToWorkerEventDataType { + /** + * Identifier assigned to the session used to send/receive messages. + */ + sessionId: SessionID; + workerInfo: WorkerInfo; + waitingForDebugger: boolean; + } + + interface DetachedFromWorkerEventDataType { + /** + * Detached session identifier. + */ + sessionId: SessionID; + } + + interface ReceivedMessageFromWorkerEventDataType { + /** + * Identifier of a session which sends a message. + */ + sessionId: SessionID; + message: string; + } + } + + /** + * The inspector.Session is used for dispatching messages to the V8 inspector back-end and receiving message responses and notifications. + */ + class Session extends EventEmitter { + /** + * Create a new instance of the inspector.Session class. + * The inspector session needs to be connected through session.connect() before the messages can be dispatched to the inspector backend. + */ + constructor(); + + /** + * Connects a session to the inspector back-end. + * An exception will be thrown if there is already a connected session established either + * through the API or by a front-end connected to the Inspector WebSocket port. + */ + connect(): void; + + /** + * Immediately close the session. All pending message callbacks will be called with an error. + * session.connect() will need to be called to be able to send messages again. + * Reconnected session will lose all inspector state, such as enabled agents or configured breakpoints. + */ + disconnect(): void; + + /** + * Posts a message to the inspector back-end. callback will be notified when a response is received. + * callback is a function that accepts two optional arguments - error and message-specific result. + */ + post(method: string, params?: {}, callback?: (err: Error | null, params?: {}) => void): void; + post(method: string, callback?: (err: Error | null, params?: {}) => void): void; + + /** + * Does nothing. + */ + post(method: "Console.clearMessages", callback?: (err: Error | null) => void): void; + + /** + * Disables console domain, prevents further console messages from being reported to the client. + */ + post(method: "Console.disable", callback?: (err: Error | null) => void): void; + + /** + * Enables console domain, sends the messages collected so far to the client by means of the + * `messageAdded` notification. + */ + post(method: "Console.enable", callback?: (err: Error | null) => void): void; + + /** + * Continues execution until specific location is reached. + */ + post(method: "Debugger.continueToLocation", params?: Debugger.ContinueToLocationParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.continueToLocation", callback?: (err: Error | null) => void): void; + + /** + * Disables debugger for given page. + */ + post(method: "Debugger.disable", callback?: (err: Error | null) => void): void; + + /** + * Enables debugger for the given page. Clients should not assume that the debugging has been + * enabled until the result for this command is received. + */ + post(method: "Debugger.enable", callback?: (err: Error | null, params: Debugger.EnableReturnType) => void): void; + + /** + * Evaluates expression on a given call frame. + */ + post(method: "Debugger.evaluateOnCallFrame", params?: Debugger.EvaluateOnCallFrameParameterType, callback?: (err: Error | null, params: Debugger.EvaluateOnCallFrameReturnType) => void): void; + post(method: "Debugger.evaluateOnCallFrame", callback?: (err: Error | null, params: Debugger.EvaluateOnCallFrameReturnType) => void): void; + + /** + * Returns possible locations for breakpoint. scriptId in start and end range locations should be + * the same. + */ + post( + method: "Debugger.getPossibleBreakpoints", + params?: Debugger.GetPossibleBreakpointsParameterType, + callback?: (err: Error | null, params: Debugger.GetPossibleBreakpointsReturnType) => void + ): void; + post(method: "Debugger.getPossibleBreakpoints", callback?: (err: Error | null, params: Debugger.GetPossibleBreakpointsReturnType) => void): void; + + /** + * Returns source for the script with given id. + */ + post(method: "Debugger.getScriptSource", params?: Debugger.GetScriptSourceParameterType, callback?: (err: Error | null, params: Debugger.GetScriptSourceReturnType) => void): void; + post(method: "Debugger.getScriptSource", callback?: (err: Error | null, params: Debugger.GetScriptSourceReturnType) => void): void; + + /** + * Returns stack trace with given `stackTraceId`. + * @experimental + */ + post(method: "Debugger.getStackTrace", params?: Debugger.GetStackTraceParameterType, callback?: (err: Error | null, params: Debugger.GetStackTraceReturnType) => void): void; + post(method: "Debugger.getStackTrace", callback?: (err: Error | null, params: Debugger.GetStackTraceReturnType) => void): void; + + /** + * Stops on the next JavaScript statement. + */ + post(method: "Debugger.pause", callback?: (err: Error | null) => void): void; + + /** + * @experimental + */ + post(method: "Debugger.pauseOnAsyncCall", params?: Debugger.PauseOnAsyncCallParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.pauseOnAsyncCall", callback?: (err: Error | null) => void): void; + + /** + * Removes JavaScript breakpoint. + */ + post(method: "Debugger.removeBreakpoint", params?: Debugger.RemoveBreakpointParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.removeBreakpoint", callback?: (err: Error | null) => void): void; + + /** + * Restarts particular call frame from the beginning. + */ + post(method: "Debugger.restartFrame", params?: Debugger.RestartFrameParameterType, callback?: (err: Error | null, params: Debugger.RestartFrameReturnType) => void): void; + post(method: "Debugger.restartFrame", callback?: (err: Error | null, params: Debugger.RestartFrameReturnType) => void): void; + + /** + * Resumes JavaScript execution. + */ + post(method: "Debugger.resume", callback?: (err: Error | null) => void): void; + + /** + * This method is deprecated - use Debugger.stepInto with breakOnAsyncCall and + * Debugger.pauseOnAsyncTask instead. Steps into next scheduled async task if any is scheduled + * before next pause. Returns success when async task is actually scheduled, returns error if no + * task were scheduled or another scheduleStepIntoAsync was called. + * @experimental + */ + post(method: "Debugger.scheduleStepIntoAsync", callback?: (err: Error | null) => void): void; + + /** + * Searches for given string in script content. + */ + post(method: "Debugger.searchInContent", params?: Debugger.SearchInContentParameterType, callback?: (err: Error | null, params: Debugger.SearchInContentReturnType) => void): void; + post(method: "Debugger.searchInContent", callback?: (err: Error | null, params: Debugger.SearchInContentReturnType) => void): void; + + /** + * Enables or disables async call stacks tracking. + */ + post(method: "Debugger.setAsyncCallStackDepth", params?: Debugger.SetAsyncCallStackDepthParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.setAsyncCallStackDepth", callback?: (err: Error | null) => void): void; + + /** + * Replace previous blackbox patterns with passed ones. Forces backend to skip stepping/pausing in + * scripts with url matching one of the patterns. VM will try to leave blackboxed script by + * performing 'step in' several times, finally resorting to 'step out' if unsuccessful. + * @experimental + */ + post(method: "Debugger.setBlackboxPatterns", params?: Debugger.SetBlackboxPatternsParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.setBlackboxPatterns", callback?: (err: Error | null) => void): void; + + /** + * Makes backend skip steps in the script in blackboxed ranges. VM will try leave blacklisted + * scripts by performing 'step in' several times, finally resorting to 'step out' if unsuccessful. + * Positions array contains positions where blackbox state is changed. First interval isn't + * blackboxed. Array should be sorted. + * @experimental + */ + post(method: "Debugger.setBlackboxedRanges", params?: Debugger.SetBlackboxedRangesParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.setBlackboxedRanges", callback?: (err: Error | null) => void): void; + + /** + * Sets JavaScript breakpoint at a given location. + */ + post(method: "Debugger.setBreakpoint", params?: Debugger.SetBreakpointParameterType, callback?: (err: Error | null, params: Debugger.SetBreakpointReturnType) => void): void; + post(method: "Debugger.setBreakpoint", callback?: (err: Error | null, params: Debugger.SetBreakpointReturnType) => void): void; + + /** + * Sets JavaScript breakpoint at given location specified either by URL or URL regex. Once this + * command is issued, all existing parsed scripts will have breakpoints resolved and returned in + * `locations` property. Further matching script parsing will result in subsequent + * `breakpointResolved` events issued. This logical breakpoint will survive page reloads. + */ + post(method: "Debugger.setBreakpointByUrl", params?: Debugger.SetBreakpointByUrlParameterType, callback?: (err: Error | null, params: Debugger.SetBreakpointByUrlReturnType) => void): void; + post(method: "Debugger.setBreakpointByUrl", callback?: (err: Error | null, params: Debugger.SetBreakpointByUrlReturnType) => void): void; + + /** + * Sets JavaScript breakpoint before each call to the given function. + * If another function was created from the same source as a given one, + * calling it will also trigger the breakpoint. + * @experimental + */ + post( + method: "Debugger.setBreakpointOnFunctionCall", + params?: Debugger.SetBreakpointOnFunctionCallParameterType, + callback?: (err: Error | null, params: Debugger.SetBreakpointOnFunctionCallReturnType) => void + ): void; + post(method: "Debugger.setBreakpointOnFunctionCall", callback?: (err: Error | null, params: Debugger.SetBreakpointOnFunctionCallReturnType) => void): void; + + /** + * Activates / deactivates all breakpoints on the page. + */ + post(method: "Debugger.setBreakpointsActive", params?: Debugger.SetBreakpointsActiveParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.setBreakpointsActive", callback?: (err: Error | null) => void): void; + + /** + * Defines pause on exceptions state. Can be set to stop on all exceptions, uncaught exceptions or + * no exceptions. Initial pause on exceptions state is `none`. + */ + post(method: "Debugger.setPauseOnExceptions", params?: Debugger.SetPauseOnExceptionsParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.setPauseOnExceptions", callback?: (err: Error | null) => void): void; + + /** + * Changes return value in top frame. Available only at return break position. + * @experimental + */ + post(method: "Debugger.setReturnValue", params?: Debugger.SetReturnValueParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.setReturnValue", callback?: (err: Error | null) => void): void; + + /** + * Edits JavaScript source live. + */ + post(method: "Debugger.setScriptSource", params?: Debugger.SetScriptSourceParameterType, callback?: (err: Error | null, params: Debugger.SetScriptSourceReturnType) => void): void; + post(method: "Debugger.setScriptSource", callback?: (err: Error | null, params: Debugger.SetScriptSourceReturnType) => void): void; + + /** + * Makes page not interrupt on any pauses (breakpoint, exception, dom exception etc). + */ + post(method: "Debugger.setSkipAllPauses", params?: Debugger.SetSkipAllPausesParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.setSkipAllPauses", callback?: (err: Error | null) => void): void; + + /** + * Changes value of variable in a callframe. Object-based scopes are not supported and must be + * mutated manually. + */ + post(method: "Debugger.setVariableValue", params?: Debugger.SetVariableValueParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.setVariableValue", callback?: (err: Error | null) => void): void; + + /** + * Steps into the function call. + */ + post(method: "Debugger.stepInto", params?: Debugger.StepIntoParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.stepInto", callback?: (err: Error | null) => void): void; + + /** + * Steps out of the function call. + */ + post(method: "Debugger.stepOut", callback?: (err: Error | null) => void): void; + + /** + * Steps over the statement. + */ + post(method: "Debugger.stepOver", callback?: (err: Error | null) => void): void; + + /** + * Enables console to refer to the node with given id via $x (see Command Line API for more details + * $x functions). + */ + post(method: "HeapProfiler.addInspectedHeapObject", params?: HeapProfiler.AddInspectedHeapObjectParameterType, callback?: (err: Error | null) => void): void; + post(method: "HeapProfiler.addInspectedHeapObject", callback?: (err: Error | null) => void): void; + + post(method: "HeapProfiler.collectGarbage", callback?: (err: Error | null) => void): void; + + post(method: "HeapProfiler.disable", callback?: (err: Error | null) => void): void; + + post(method: "HeapProfiler.enable", callback?: (err: Error | null) => void): void; + + post(method: "HeapProfiler.getHeapObjectId", params?: HeapProfiler.GetHeapObjectIdParameterType, callback?: (err: Error | null, params: HeapProfiler.GetHeapObjectIdReturnType) => void): void; + post(method: "HeapProfiler.getHeapObjectId", callback?: (err: Error | null, params: HeapProfiler.GetHeapObjectIdReturnType) => void): void; + + post( + method: "HeapProfiler.getObjectByHeapObjectId", + params?: HeapProfiler.GetObjectByHeapObjectIdParameterType, + callback?: (err: Error | null, params: HeapProfiler.GetObjectByHeapObjectIdReturnType) => void + ): void; + post(method: "HeapProfiler.getObjectByHeapObjectId", callback?: (err: Error | null, params: HeapProfiler.GetObjectByHeapObjectIdReturnType) => void): void; + + post(method: "HeapProfiler.getSamplingProfile", callback?: (err: Error | null, params: HeapProfiler.GetSamplingProfileReturnType) => void): void; + + post(method: "HeapProfiler.startSampling", params?: HeapProfiler.StartSamplingParameterType, callback?: (err: Error | null) => void): void; + post(method: "HeapProfiler.startSampling", callback?: (err: Error | null) => void): void; + + post(method: "HeapProfiler.startTrackingHeapObjects", params?: HeapProfiler.StartTrackingHeapObjectsParameterType, callback?: (err: Error | null) => void): void; + post(method: "HeapProfiler.startTrackingHeapObjects", callback?: (err: Error | null) => void): void; + + post(method: "HeapProfiler.stopSampling", callback?: (err: Error | null, params: HeapProfiler.StopSamplingReturnType) => void): void; + + post(method: "HeapProfiler.stopTrackingHeapObjects", params?: HeapProfiler.StopTrackingHeapObjectsParameterType, callback?: (err: Error | null) => void): void; + post(method: "HeapProfiler.stopTrackingHeapObjects", callback?: (err: Error | null) => void): void; + + post(method: "HeapProfiler.takeHeapSnapshot", params?: HeapProfiler.TakeHeapSnapshotParameterType, callback?: (err: Error | null) => void): void; + post(method: "HeapProfiler.takeHeapSnapshot", callback?: (err: Error | null) => void): void; + + post(method: "Profiler.disable", callback?: (err: Error | null) => void): void; + + post(method: "Profiler.enable", callback?: (err: Error | null) => void): void; + + /** + * Collect coverage data for the current isolate. The coverage data may be incomplete due to + * garbage collection. + */ + post(method: "Profiler.getBestEffortCoverage", callback?: (err: Error | null, params: Profiler.GetBestEffortCoverageReturnType) => void): void; + + /** + * Changes CPU profiler sampling interval. Must be called before CPU profiles recording started. + */ + post(method: "Profiler.setSamplingInterval", params?: Profiler.SetSamplingIntervalParameterType, callback?: (err: Error | null) => void): void; + post(method: "Profiler.setSamplingInterval", callback?: (err: Error | null) => void): void; + + post(method: "Profiler.start", callback?: (err: Error | null) => void): void; + + /** + * Enable precise code coverage. Coverage data for JavaScript executed before enabling precise code + * coverage may be incomplete. Enabling prevents running optimized code and resets execution + * counters. + */ + post(method: "Profiler.startPreciseCoverage", params?: Profiler.StartPreciseCoverageParameterType, callback?: (err: Error | null) => void): void; + post(method: "Profiler.startPreciseCoverage", callback?: (err: Error | null) => void): void; + + /** + * Enable type profile. + * @experimental + */ + post(method: "Profiler.startTypeProfile", callback?: (err: Error | null) => void): void; + + post(method: "Profiler.stop", callback?: (err: Error | null, params: Profiler.StopReturnType) => void): void; + + /** + * Disable precise code coverage. Disabling releases unnecessary execution count records and allows + * executing optimized code. + */ + post(method: "Profiler.stopPreciseCoverage", callback?: (err: Error | null) => void): void; + + /** + * Disable type profile. Disabling releases type profile data collected so far. + * @experimental + */ + post(method: "Profiler.stopTypeProfile", callback?: (err: Error | null) => void): void; + + /** + * Collect coverage data for the current isolate, and resets execution counters. Precise code + * coverage needs to have started. + */ + post(method: "Profiler.takePreciseCoverage", callback?: (err: Error | null, params: Profiler.TakePreciseCoverageReturnType) => void): void; + + /** + * Collect type profile. + * @experimental + */ + post(method: "Profiler.takeTypeProfile", callback?: (err: Error | null, params: Profiler.TakeTypeProfileReturnType) => void): void; + + /** + * Add handler to promise with given promise object id. + */ + post(method: "Runtime.awaitPromise", params?: Runtime.AwaitPromiseParameterType, callback?: (err: Error | null, params: Runtime.AwaitPromiseReturnType) => void): void; + post(method: "Runtime.awaitPromise", callback?: (err: Error | null, params: Runtime.AwaitPromiseReturnType) => void): void; + + /** + * Calls function with given declaration on the given object. Object group of the result is + * inherited from the target object. + */ + post(method: "Runtime.callFunctionOn", params?: Runtime.CallFunctionOnParameterType, callback?: (err: Error | null, params: Runtime.CallFunctionOnReturnType) => void): void; + post(method: "Runtime.callFunctionOn", callback?: (err: Error | null, params: Runtime.CallFunctionOnReturnType) => void): void; + + /** + * Compiles expression. + */ + post(method: "Runtime.compileScript", params?: Runtime.CompileScriptParameterType, callback?: (err: Error | null, params: Runtime.CompileScriptReturnType) => void): void; + post(method: "Runtime.compileScript", callback?: (err: Error | null, params: Runtime.CompileScriptReturnType) => void): void; + + /** + * Disables reporting of execution contexts creation. + */ + post(method: "Runtime.disable", callback?: (err: Error | null) => void): void; + + /** + * Discards collected exceptions and console API calls. + */ + post(method: "Runtime.discardConsoleEntries", callback?: (err: Error | null) => void): void; + + /** + * Enables reporting of execution contexts creation by means of `executionContextCreated` event. + * When the reporting gets enabled the event will be sent immediately for each existing execution + * context. + */ + post(method: "Runtime.enable", callback?: (err: Error | null) => void): void; + + /** + * Evaluates expression on global object. + */ + post(method: "Runtime.evaluate", params?: Runtime.EvaluateParameterType, callback?: (err: Error | null, params: Runtime.EvaluateReturnType) => void): void; + post(method: "Runtime.evaluate", callback?: (err: Error | null, params: Runtime.EvaluateReturnType) => void): void; + + /** + * Returns the isolate id. + * @experimental + */ + post(method: "Runtime.getIsolateId", callback?: (err: Error | null, params: Runtime.GetIsolateIdReturnType) => void): void; + + /** + * Returns the JavaScript heap usage. + * It is the total usage of the corresponding isolate not scoped to a particular Runtime. + * @experimental + */ + post(method: "Runtime.getHeapUsage", callback?: (err: Error | null, params: Runtime.GetHeapUsageReturnType) => void): void; + + /** + * Returns properties of a given object. Object group of the result is inherited from the target + * object. + */ + post(method: "Runtime.getProperties", params?: Runtime.GetPropertiesParameterType, callback?: (err: Error | null, params: Runtime.GetPropertiesReturnType) => void): void; + post(method: "Runtime.getProperties", callback?: (err: Error | null, params: Runtime.GetPropertiesReturnType) => void): void; + + /** + * Returns all let, const and class variables from global scope. + */ + post( + method: "Runtime.globalLexicalScopeNames", + params?: Runtime.GlobalLexicalScopeNamesParameterType, + callback?: (err: Error | null, params: Runtime.GlobalLexicalScopeNamesReturnType) => void + ): void; + post(method: "Runtime.globalLexicalScopeNames", callback?: (err: Error | null, params: Runtime.GlobalLexicalScopeNamesReturnType) => void): void; + + post(method: "Runtime.queryObjects", params?: Runtime.QueryObjectsParameterType, callback?: (err: Error | null, params: Runtime.QueryObjectsReturnType) => void): void; + post(method: "Runtime.queryObjects", callback?: (err: Error | null, params: Runtime.QueryObjectsReturnType) => void): void; + + /** + * Releases remote object with given id. + */ + post(method: "Runtime.releaseObject", params?: Runtime.ReleaseObjectParameterType, callback?: (err: Error | null) => void): void; + post(method: "Runtime.releaseObject", callback?: (err: Error | null) => void): void; + + /** + * Releases all remote objects that belong to a given group. + */ + post(method: "Runtime.releaseObjectGroup", params?: Runtime.ReleaseObjectGroupParameterType, callback?: (err: Error | null) => void): void; + post(method: "Runtime.releaseObjectGroup", callback?: (err: Error | null) => void): void; + + /** + * Tells inspected instance to run if it was waiting for debugger to attach. + */ + post(method: "Runtime.runIfWaitingForDebugger", callback?: (err: Error | null) => void): void; + + /** + * Runs script with given id in a given context. + */ + post(method: "Runtime.runScript", params?: Runtime.RunScriptParameterType, callback?: (err: Error | null, params: Runtime.RunScriptReturnType) => void): void; + post(method: "Runtime.runScript", callback?: (err: Error | null, params: Runtime.RunScriptReturnType) => void): void; + + /** + * @experimental + */ + post(method: "Runtime.setCustomObjectFormatterEnabled", params?: Runtime.SetCustomObjectFormatterEnabledParameterType, callback?: (err: Error | null) => void): void; + post(method: "Runtime.setCustomObjectFormatterEnabled", callback?: (err: Error | null) => void): void; + + /** + * Terminate current or next JavaScript execution. + * Will cancel the termination when the outer-most script execution ends. + * @experimental + */ + post(method: "Runtime.terminateExecution", callback?: (err: Error | null) => void): void; + + /** + * Returns supported domains. + */ + post(method: "Schema.getDomains", callback?: (err: Error | null, params: Schema.GetDomainsReturnType) => void): void; + + /** + * Gets supported tracing categories. + */ + post(method: "NodeTracing.getCategories", callback?: (err: Error | null, params: NodeTracing.GetCategoriesReturnType) => void): void; + + /** + * Start trace events collection. + */ + post(method: "NodeTracing.start", params?: NodeTracing.StartParameterType, callback?: (err: Error | null) => void): void; + post(method: "NodeTracing.start", callback?: (err: Error | null) => void): void; + + /** + * Stop trace events collection. Remaining collected events will be sent as a sequence of + * dataCollected events followed by tracingComplete event. + */ + post(method: "NodeTracing.stop", callback?: (err: Error | null) => void): void; + + /** + * Sends protocol message over session with given id. + */ + post(method: "NodeWorker.sendMessageToWorker", params?: NodeWorker.SendMessageToWorkerParameterType, callback?: (err: Error | null) => void): void; + post(method: "NodeWorker.sendMessageToWorker", callback?: (err: Error | null) => void): void; + + /** + * Instructs the inspector to attach to running workers. Will also attach to new workers + * as they start + */ + post(method: "NodeWorker.enable", params?: NodeWorker.EnableParameterType, callback?: (err: Error | null) => void): void; + post(method: "NodeWorker.enable", callback?: (err: Error | null) => void): void; + + /** + * Detaches from all running workers and disables attaching to new workers as they are started. + */ + post(method: "NodeWorker.disable", callback?: (err: Error | null) => void): void; + + // Events + + addListener(event: string, listener: (...args: any[]) => void): this; + + /** + * Emitted when any notification from the V8 Inspector is received. + */ + addListener(event: "inspectorNotification", listener: (message: InspectorNotification<{}>) => void): this; + + /** + * Issued when new console message is added. + */ + addListener(event: "Console.messageAdded", listener: (message: InspectorNotification) => void): this; + + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + addListener(event: "Debugger.breakpointResolved", listener: (message: InspectorNotification) => void): this; + + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + addListener(event: "Debugger.paused", listener: (message: InspectorNotification) => void): this; + + /** + * Fired when the virtual machine resumed execution. + */ + addListener(event: "Debugger.resumed", listener: () => void): this; + + /** + * Fired when virtual machine fails to parse the script. + */ + addListener(event: "Debugger.scriptFailedToParse", listener: (message: InspectorNotification) => void): this; + + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected + * scripts upon enabling debugger. + */ + addListener(event: "Debugger.scriptParsed", listener: (message: InspectorNotification) => void): this; + + addListener(event: "HeapProfiler.addHeapSnapshotChunk", listener: (message: InspectorNotification) => void): this; + + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + addListener(event: "HeapProfiler.heapStatsUpdate", listener: (message: InspectorNotification) => void): this; + + /** + * If heap objects tracking has been started then backend regularly sends a current value for last + * seen object id and corresponding timestamp. If the were changes in the heap since last event + * then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + addListener(event: "HeapProfiler.lastSeenObjectId", listener: (message: InspectorNotification) => void): this; + + addListener(event: "HeapProfiler.reportHeapSnapshotProgress", listener: (message: InspectorNotification) => void): this; + addListener(event: "HeapProfiler.resetProfiles", listener: () => void): this; + addListener(event: "Profiler.consoleProfileFinished", listener: (message: InspectorNotification) => void): this; + + /** + * Sent when new profile recording is started using console.profile() call. + */ + addListener(event: "Profiler.consoleProfileStarted", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when console API was called. + */ + addListener(event: "Runtime.consoleAPICalled", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when unhandled exception was revoked. + */ + addListener(event: "Runtime.exceptionRevoked", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when exception was thrown and unhandled. + */ + addListener(event: "Runtime.exceptionThrown", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when new execution context is created. + */ + addListener(event: "Runtime.executionContextCreated", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when execution context is destroyed. + */ + addListener(event: "Runtime.executionContextDestroyed", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when all executionContexts were cleared in browser + */ + addListener(event: "Runtime.executionContextsCleared", listener: () => void): this; + + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API + * call). + */ + addListener(event: "Runtime.inspectRequested", listener: (message: InspectorNotification) => void): this; + + /** + * Contains an bucket of collected trace events. + */ + addListener(event: "NodeTracing.dataCollected", listener: (message: InspectorNotification) => void): this; + + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + addListener(event: "NodeTracing.tracingComplete", listener: () => void): this; + + /** + * Issued when attached to a worker. + */ + addListener(event: "NodeWorker.attachedToWorker", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when detached from the worker. + */ + addListener(event: "NodeWorker.detachedFromWorker", listener: (message: InspectorNotification) => void): this; + + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + addListener(event: "NodeWorker.receivedMessageFromWorker", listener: (message: InspectorNotification) => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "inspectorNotification", message: InspectorNotification<{}>): boolean; + emit(event: "Console.messageAdded", message: InspectorNotification): boolean; + emit(event: "Debugger.breakpointResolved", message: InspectorNotification): boolean; + emit(event: "Debugger.paused", message: InspectorNotification): boolean; + emit(event: "Debugger.resumed"): boolean; + emit(event: "Debugger.scriptFailedToParse", message: InspectorNotification): boolean; + emit(event: "Debugger.scriptParsed", message: InspectorNotification): boolean; + emit(event: "HeapProfiler.addHeapSnapshotChunk", message: InspectorNotification): boolean; + emit(event: "HeapProfiler.heapStatsUpdate", message: InspectorNotification): boolean; + emit(event: "HeapProfiler.lastSeenObjectId", message: InspectorNotification): boolean; + emit(event: "HeapProfiler.reportHeapSnapshotProgress", message: InspectorNotification): boolean; + emit(event: "HeapProfiler.resetProfiles"): boolean; + emit(event: "Profiler.consoleProfileFinished", message: InspectorNotification): boolean; + emit(event: "Profiler.consoleProfileStarted", message: InspectorNotification): boolean; + emit(event: "Runtime.consoleAPICalled", message: InspectorNotification): boolean; + emit(event: "Runtime.exceptionRevoked", message: InspectorNotification): boolean; + emit(event: "Runtime.exceptionThrown", message: InspectorNotification): boolean; + emit(event: "Runtime.executionContextCreated", message: InspectorNotification): boolean; + emit(event: "Runtime.executionContextDestroyed", message: InspectorNotification): boolean; + emit(event: "Runtime.executionContextsCleared"): boolean; + emit(event: "Runtime.inspectRequested", message: InspectorNotification): boolean; + emit(event: "NodeTracing.dataCollected", message: InspectorNotification): boolean; + emit(event: "NodeTracing.tracingComplete"): boolean; + emit(event: "NodeWorker.attachedToWorker", message: InspectorNotification): boolean; + emit(event: "NodeWorker.detachedFromWorker", message: InspectorNotification): boolean; + emit(event: "NodeWorker.receivedMessageFromWorker", message: InspectorNotification): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + + /** + * Emitted when any notification from the V8 Inspector is received. + */ + on(event: "inspectorNotification", listener: (message: InspectorNotification<{}>) => void): this; + + /** + * Issued when new console message is added. + */ + on(event: "Console.messageAdded", listener: (message: InspectorNotification) => void): this; + + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + on(event: "Debugger.breakpointResolved", listener: (message: InspectorNotification) => void): this; + + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + on(event: "Debugger.paused", listener: (message: InspectorNotification) => void): this; + + /** + * Fired when the virtual machine resumed execution. + */ + on(event: "Debugger.resumed", listener: () => void): this; + + /** + * Fired when virtual machine fails to parse the script. + */ + on(event: "Debugger.scriptFailedToParse", listener: (message: InspectorNotification) => void): this; + + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected + * scripts upon enabling debugger. + */ + on(event: "Debugger.scriptParsed", listener: (message: InspectorNotification) => void): this; + + on(event: "HeapProfiler.addHeapSnapshotChunk", listener: (message: InspectorNotification) => void): this; + + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + on(event: "HeapProfiler.heapStatsUpdate", listener: (message: InspectorNotification) => void): this; + + /** + * If heap objects tracking has been started then backend regularly sends a current value for last + * seen object id and corresponding timestamp. If the were changes in the heap since last event + * then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + on(event: "HeapProfiler.lastSeenObjectId", listener: (message: InspectorNotification) => void): this; + + on(event: "HeapProfiler.reportHeapSnapshotProgress", listener: (message: InspectorNotification) => void): this; + on(event: "HeapProfiler.resetProfiles", listener: () => void): this; + on(event: "Profiler.consoleProfileFinished", listener: (message: InspectorNotification) => void): this; + + /** + * Sent when new profile recording is started using console.profile() call. + */ + on(event: "Profiler.consoleProfileStarted", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when console API was called. + */ + on(event: "Runtime.consoleAPICalled", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when unhandled exception was revoked. + */ + on(event: "Runtime.exceptionRevoked", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when exception was thrown and unhandled. + */ + on(event: "Runtime.exceptionThrown", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when new execution context is created. + */ + on(event: "Runtime.executionContextCreated", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when execution context is destroyed. + */ + on(event: "Runtime.executionContextDestroyed", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when all executionContexts were cleared in browser + */ + on(event: "Runtime.executionContextsCleared", listener: () => void): this; + + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API + * call). + */ + on(event: "Runtime.inspectRequested", listener: (message: InspectorNotification) => void): this; + + /** + * Contains an bucket of collected trace events. + */ + on(event: "NodeTracing.dataCollected", listener: (message: InspectorNotification) => void): this; + + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + on(event: "NodeTracing.tracingComplete", listener: () => void): this; + + /** + * Issued when attached to a worker. + */ + on(event: "NodeWorker.attachedToWorker", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when detached from the worker. + */ + on(event: "NodeWorker.detachedFromWorker", listener: (message: InspectorNotification) => void): this; + + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + on(event: "NodeWorker.receivedMessageFromWorker", listener: (message: InspectorNotification) => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + + /** + * Emitted when any notification from the V8 Inspector is received. + */ + once(event: "inspectorNotification", listener: (message: InspectorNotification<{}>) => void): this; + + /** + * Issued when new console message is added. + */ + once(event: "Console.messageAdded", listener: (message: InspectorNotification) => void): this; + + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + once(event: "Debugger.breakpointResolved", listener: (message: InspectorNotification) => void): this; + + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + once(event: "Debugger.paused", listener: (message: InspectorNotification) => void): this; + + /** + * Fired when the virtual machine resumed execution. + */ + once(event: "Debugger.resumed", listener: () => void): this; + + /** + * Fired when virtual machine fails to parse the script. + */ + once(event: "Debugger.scriptFailedToParse", listener: (message: InspectorNotification) => void): this; + + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected + * scripts upon enabling debugger. + */ + once(event: "Debugger.scriptParsed", listener: (message: InspectorNotification) => void): this; + + once(event: "HeapProfiler.addHeapSnapshotChunk", listener: (message: InspectorNotification) => void): this; + + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + once(event: "HeapProfiler.heapStatsUpdate", listener: (message: InspectorNotification) => void): this; + + /** + * If heap objects tracking has been started then backend regularly sends a current value for last + * seen object id and corresponding timestamp. If the were changes in the heap since last event + * then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + once(event: "HeapProfiler.lastSeenObjectId", listener: (message: InspectorNotification) => void): this; + + once(event: "HeapProfiler.reportHeapSnapshotProgress", listener: (message: InspectorNotification) => void): this; + once(event: "HeapProfiler.resetProfiles", listener: () => void): this; + once(event: "Profiler.consoleProfileFinished", listener: (message: InspectorNotification) => void): this; + + /** + * Sent when new profile recording is started using console.profile() call. + */ + once(event: "Profiler.consoleProfileStarted", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when console API was called. + */ + once(event: "Runtime.consoleAPICalled", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when unhandled exception was revoked. + */ + once(event: "Runtime.exceptionRevoked", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when exception was thrown and unhandled. + */ + once(event: "Runtime.exceptionThrown", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when new execution context is created. + */ + once(event: "Runtime.executionContextCreated", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when execution context is destroyed. + */ + once(event: "Runtime.executionContextDestroyed", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when all executionContexts were cleared in browser + */ + once(event: "Runtime.executionContextsCleared", listener: () => void): this; + + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API + * call). + */ + once(event: "Runtime.inspectRequested", listener: (message: InspectorNotification) => void): this; + + /** + * Contains an bucket of collected trace events. + */ + once(event: "NodeTracing.dataCollected", listener: (message: InspectorNotification) => void): this; + + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + once(event: "NodeTracing.tracingComplete", listener: () => void): this; + + /** + * Issued when attached to a worker. + */ + once(event: "NodeWorker.attachedToWorker", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when detached from the worker. + */ + once(event: "NodeWorker.detachedFromWorker", listener: (message: InspectorNotification) => void): this; + + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + once(event: "NodeWorker.receivedMessageFromWorker", listener: (message: InspectorNotification) => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + + /** + * Emitted when any notification from the V8 Inspector is received. + */ + prependListener(event: "inspectorNotification", listener: (message: InspectorNotification<{}>) => void): this; + + /** + * Issued when new console message is added. + */ + prependListener(event: "Console.messageAdded", listener: (message: InspectorNotification) => void): this; + + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + prependListener(event: "Debugger.breakpointResolved", listener: (message: InspectorNotification) => void): this; + + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + prependListener(event: "Debugger.paused", listener: (message: InspectorNotification) => void): this; + + /** + * Fired when the virtual machine resumed execution. + */ + prependListener(event: "Debugger.resumed", listener: () => void): this; + + /** + * Fired when virtual machine fails to parse the script. + */ + prependListener(event: "Debugger.scriptFailedToParse", listener: (message: InspectorNotification) => void): this; + + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected + * scripts upon enabling debugger. + */ + prependListener(event: "Debugger.scriptParsed", listener: (message: InspectorNotification) => void): this; + + prependListener(event: "HeapProfiler.addHeapSnapshotChunk", listener: (message: InspectorNotification) => void): this; + + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + prependListener(event: "HeapProfiler.heapStatsUpdate", listener: (message: InspectorNotification) => void): this; + + /** + * If heap objects tracking has been started then backend regularly sends a current value for last + * seen object id and corresponding timestamp. If the were changes in the heap since last event + * then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + prependListener(event: "HeapProfiler.lastSeenObjectId", listener: (message: InspectorNotification) => void): this; + + prependListener(event: "HeapProfiler.reportHeapSnapshotProgress", listener: (message: InspectorNotification) => void): this; + prependListener(event: "HeapProfiler.resetProfiles", listener: () => void): this; + prependListener(event: "Profiler.consoleProfileFinished", listener: (message: InspectorNotification) => void): this; + + /** + * Sent when new profile recording is started using console.profile() call. + */ + prependListener(event: "Profiler.consoleProfileStarted", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when console API was called. + */ + prependListener(event: "Runtime.consoleAPICalled", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when unhandled exception was revoked. + */ + prependListener(event: "Runtime.exceptionRevoked", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when exception was thrown and unhandled. + */ + prependListener(event: "Runtime.exceptionThrown", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when new execution context is created. + */ + prependListener(event: "Runtime.executionContextCreated", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when execution context is destroyed. + */ + prependListener(event: "Runtime.executionContextDestroyed", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when all executionContexts were cleared in browser + */ + prependListener(event: "Runtime.executionContextsCleared", listener: () => void): this; + + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API + * call). + */ + prependListener(event: "Runtime.inspectRequested", listener: (message: InspectorNotification) => void): this; + + /** + * Contains an bucket of collected trace events. + */ + prependListener(event: "NodeTracing.dataCollected", listener: (message: InspectorNotification) => void): this; + + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + prependListener(event: "NodeTracing.tracingComplete", listener: () => void): this; + + /** + * Issued when attached to a worker. + */ + prependListener(event: "NodeWorker.attachedToWorker", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when detached from the worker. + */ + prependListener(event: "NodeWorker.detachedFromWorker", listener: (message: InspectorNotification) => void): this; + + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + prependListener(event: "NodeWorker.receivedMessageFromWorker", listener: (message: InspectorNotification) => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + + /** + * Emitted when any notification from the V8 Inspector is received. + */ + prependOnceListener(event: "inspectorNotification", listener: (message: InspectorNotification<{}>) => void): this; + + /** + * Issued when new console message is added. + */ + prependOnceListener(event: "Console.messageAdded", listener: (message: InspectorNotification) => void): this; + + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + prependOnceListener(event: "Debugger.breakpointResolved", listener: (message: InspectorNotification) => void): this; + + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + prependOnceListener(event: "Debugger.paused", listener: (message: InspectorNotification) => void): this; + + /** + * Fired when the virtual machine resumed execution. + */ + prependOnceListener(event: "Debugger.resumed", listener: () => void): this; + + /** + * Fired when virtual machine fails to parse the script. + */ + prependOnceListener(event: "Debugger.scriptFailedToParse", listener: (message: InspectorNotification) => void): this; + + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected + * scripts upon enabling debugger. + */ + prependOnceListener(event: "Debugger.scriptParsed", listener: (message: InspectorNotification) => void): this; + + prependOnceListener(event: "HeapProfiler.addHeapSnapshotChunk", listener: (message: InspectorNotification) => void): this; + + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + prependOnceListener(event: "HeapProfiler.heapStatsUpdate", listener: (message: InspectorNotification) => void): this; + + /** + * If heap objects tracking has been started then backend regularly sends a current value for last + * seen object id and corresponding timestamp. If the were changes in the heap since last event + * then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + prependOnceListener(event: "HeapProfiler.lastSeenObjectId", listener: (message: InspectorNotification) => void): this; + + prependOnceListener(event: "HeapProfiler.reportHeapSnapshotProgress", listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: "HeapProfiler.resetProfiles", listener: () => void): this; + prependOnceListener(event: "Profiler.consoleProfileFinished", listener: (message: InspectorNotification) => void): this; + + /** + * Sent when new profile recording is started using console.profile() call. + */ + prependOnceListener(event: "Profiler.consoleProfileStarted", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when console API was called. + */ + prependOnceListener(event: "Runtime.consoleAPICalled", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when unhandled exception was revoked. + */ + prependOnceListener(event: "Runtime.exceptionRevoked", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when exception was thrown and unhandled. + */ + prependOnceListener(event: "Runtime.exceptionThrown", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when new execution context is created. + */ + prependOnceListener(event: "Runtime.executionContextCreated", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when execution context is destroyed. + */ + prependOnceListener(event: "Runtime.executionContextDestroyed", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when all executionContexts were cleared in browser + */ + prependOnceListener(event: "Runtime.executionContextsCleared", listener: () => void): this; + + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API + * call). + */ + prependOnceListener(event: "Runtime.inspectRequested", listener: (message: InspectorNotification) => void): this; + + /** + * Contains an bucket of collected trace events. + */ + prependOnceListener(event: "NodeTracing.dataCollected", listener: (message: InspectorNotification) => void): this; + + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + prependOnceListener(event: "NodeTracing.tracingComplete", listener: () => void): this; + + /** + * Issued when attached to a worker. + */ + prependOnceListener(event: "NodeWorker.attachedToWorker", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when detached from the worker. + */ + prependOnceListener(event: "NodeWorker.detachedFromWorker", listener: (message: InspectorNotification) => void): this; + + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + prependOnceListener(event: "NodeWorker.receivedMessageFromWorker", listener: (message: InspectorNotification) => void): this; + } + + // Top Level API + + /** + * Activate inspector on host and port. Equivalent to node --inspect=[[host:]port], but can be done programatically after node has started. + * If wait is true, will block until a client has connected to the inspect port and flow control has been passed to the debugger client. + * @param port Port to listen on for inspector connections. Optional, defaults to what was specified on the CLI. + * @param host Host to listen on for inspector connections. Optional, defaults to what was specified on the CLI. + * @param wait Block until a client has connected. Optional, defaults to false. + */ + function open(port?: number, host?: string, wait?: boolean): void; + + /** + * Deactivate the inspector. Blocks until there are no active connections. + */ + function close(): void; + + /** + * Return the URL of the active inspector, or undefined if there is none. + */ + function url(): string; +} diff --git a/node_modules/@types/node/package.json b/node_modules/@types/node/package.json new file mode 100644 index 0000000..9d4624b --- /dev/null +++ b/node_modules/@types/node/package.json @@ -0,0 +1,177 @@ +{ + "_from": "@types/node", + "_id": "@types/node@10.12.18", + "_inBundle": false, + "_integrity": "sha512-fh+pAqt4xRzPfqA6eh3Z2y6fyZavRIumvjhaCL753+TVkGKGhpPeyrJG2JftD0T9q4GF00KjefsQ+PQNDdWQaQ==", + "_location": "/@types/node", + "_phantomChildren": {}, + "_requested": { + "type": "tag", + "registry": true, + "raw": "@types/node", + "name": "@types/node", + "escapedName": "@types%2fnode", + "scope": "@types", + "rawSpec": "", + "saveSpec": null, + "fetchSpec": "latest" + }, + "_requiredBy": [ + "#DEV:/", + "#USER" + ], + "_resolved": "https://registry.npmjs.org/@types/node/-/node-10.12.18.tgz", + "_shasum": "1d3ca764718915584fcd9f6344621b7672665c67", + "_spec": "@types/node", + "_where": "/Users/jessitron/code/jessitron/stringify-tree", + "bugs": { + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped/issues" + }, + "bundleDependencies": false, + "contributors": [ + { + "name": "Microsoft TypeScript", + "url": "https://github.com/Microsoft" + }, + { + "name": "DefinitelyTyped", + "url": "https://github.com/DefinitelyTyped" + }, + { + "name": "Alberto Schiabel", + "url": "https://github.com/jkomyno" + }, + { + "name": "Alexander T.", + "url": "https://github.com/a-tarasyuk" + }, + { + "name": "Alvis HT Tang", + "url": "https://github.com/alvis" + }, + { + "name": "Andrew Makarov", + "url": "https://github.com/r3nya" + }, + { + "name": "Bruno Scheufler", + "url": "https://github.com/brunoscheufler" + }, + { + "name": "Chigozirim C.", + "url": "https://github.com/smac89" + }, + { + "name": "Christian Vaagland Tellnes", + "url": "https://github.com/tellnes" + }, + { + "name": "Deividas Bakanas", + "url": "https://github.com/DeividasBakanas" + }, + { + "name": "Eugene Y. Q. Shen", + "url": "https://github.com/eyqs" + }, + { + "name": "Flarna", + "url": "https://github.com/Flarna" + }, + { + "name": "Hannes Magnusson", + "url": "https://github.com/Hannes-Magnusson-CK" + }, + { + "name": "Hoàng Văn Khải", + "url": "https://github.com/KSXGitHub" + }, + { + "name": "Huw", + "url": "https://github.com/hoo29" + }, + { + "name": "Kelvin Jin", + "url": "https://github.com/kjin" + }, + { + "name": "Klaus Meinhardt", + "url": "https://github.com/ajafff" + }, + { + "name": "Lishude", + "url": "https://github.com/islishude" + }, + { + "name": "Mariusz Wiktorczyk", + "url": "https://github.com/mwiktorczyk" + }, + { + "name": "Matthieu Sieben", + "url": "https://github.com/matthieusieben" + }, + { + "name": "Mohsen Azimi", + "url": "https://github.com/mohsen1" + }, + { + "name": "Nicolas Even", + "url": "https://github.com/n-e" + }, + { + "name": "Nicolas Voigt", + "url": "https://github.com/octo-sniffle" + }, + { + "name": "Parambir Singh", + "url": "https://github.com/parambirs" + }, + { + "name": "Sebastian Silbermann", + "url": "https://github.com/eps1lon" + }, + { + "name": "Simon Schick", + "url": "https://github.com/SimonSchick" + }, + { + "name": "Thomas den Hollander", + "url": "https://github.com/ThomasdenH" + }, + { + "name": "Wilco Bakker", + "url": "https://github.com/WilcoBakker" + }, + { + "name": "wwwy3y3", + "url": "https://github.com/wwwy3y3" + }, + { + "name": "Zane Hannan AU", + "url": "https://github.com/ZaneHannanAU" + }, + { + "name": "Jeremie Rodriguez", + "url": "https://github.com/jeremiergz" + }, + { + "name": "Samuel Ainsworth", + "url": "https://github.com/samuela" + } + ], + "dependencies": {}, + "deprecated": false, + "description": "TypeScript definitions for Node.js", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped#readme", + "license": "MIT", + "main": "", + "name": "@types/node", + "repository": { + "type": "git", + "url": "git+https://github.com/DefinitelyTyped/DefinitelyTyped.git" + }, + "scripts": {}, + "typeScriptVersion": "2.0", + "types": "index", + "typesPublisherContentHash": "2ab4e2583634afae0837756aa0330daeca55b67e8b9947d540c0efdd33becf3d", + "version": "10.12.18" +} diff --git a/node_modules/arrify/index.js b/node_modules/arrify/index.js new file mode 100644 index 0000000..2a2fdee --- /dev/null +++ b/node_modules/arrify/index.js @@ -0,0 +1,8 @@ +'use strict'; +module.exports = function (val) { + if (val === null || val === undefined) { + return []; + } + + return Array.isArray(val) ? val : [val]; +}; diff --git a/node_modules/arrify/license b/node_modules/arrify/license new file mode 100644 index 0000000..654d0bf --- /dev/null +++ b/node_modules/arrify/license @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/arrify/package.json b/node_modules/arrify/package.json new file mode 100644 index 0000000..a525c9d --- /dev/null +++ b/node_modules/arrify/package.json @@ -0,0 +1,65 @@ +{ + "_from": "arrify@^1.0.0", + "_id": "arrify@1.0.1", + "_inBundle": false, + "_integrity": "sha1-iYUI2iIm84DfkEcoRWhJwVAaSw0=", + "_location": "/arrify", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "arrify@^1.0.0", + "name": "arrify", + "escapedName": "arrify", + "rawSpec": "^1.0.0", + "saveSpec": null, + "fetchSpec": "^1.0.0" + }, + "_requiredBy": [ + "/ts-node" + ], + "_resolved": "https://registry.npmjs.org/arrify/-/arrify-1.0.1.tgz", + "_shasum": "898508da2226f380df904728456849c1501a4b0d", + "_spec": "arrify@^1.0.0", + "_where": "/Users/jessitron/code/jessitron/stringify-tree/node_modules/ts-node", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "bugs": { + "url": "https://github.com/sindresorhus/arrify/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "Convert a value to an array", + "devDependencies": { + "ava": "*", + "xo": "*" + }, + "engines": { + "node": ">=0.10.0" + }, + "files": [ + "index.js" + ], + "homepage": "https://github.com/sindresorhus/arrify#readme", + "keywords": [ + "array", + "arr", + "arrify", + "arrayify", + "convert", + "value" + ], + "license": "MIT", + "name": "arrify", + "repository": { + "type": "git", + "url": "git+https://github.com/sindresorhus/arrify.git" + }, + "scripts": { + "test": "xo && ava" + }, + "version": "1.0.1" +} diff --git a/node_modules/arrify/readme.md b/node_modules/arrify/readme.md new file mode 100644 index 0000000..183d075 --- /dev/null +++ b/node_modules/arrify/readme.md @@ -0,0 +1,36 @@ +# arrify [![Build Status](https://travis-ci.org/sindresorhus/arrify.svg?branch=master)](https://travis-ci.org/sindresorhus/arrify) + +> Convert a value to an array + + +## Install + +``` +$ npm install --save arrify +``` + + +## Usage + +```js +const arrify = require('arrify'); + +arrify('unicorn'); +//=> ['unicorn'] + +arrify(['unicorn']); +//=> ['unicorn'] + +arrify(null); +//=> [] + +arrify(undefined); +//=> [] +``` + +*Supplying `null` or `undefined` results in an empty array.* + + +## License + +MIT © [Sindre Sorhus](http://sindresorhus.com) diff --git a/node_modules/balanced-match/.npmignore b/node_modules/balanced-match/.npmignore new file mode 100644 index 0000000..ae5d8c3 --- /dev/null +++ b/node_modules/balanced-match/.npmignore @@ -0,0 +1,5 @@ +test +.gitignore +.travis.yml +Makefile +example.js diff --git a/node_modules/balanced-match/LICENSE.md b/node_modules/balanced-match/LICENSE.md new file mode 100644 index 0000000..2cdc8e4 --- /dev/null +++ b/node_modules/balanced-match/LICENSE.md @@ -0,0 +1,21 @@ +(MIT) + +Copyright (c) 2013 Julian Gruber <julian@juliangruber.com> + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/balanced-match/README.md b/node_modules/balanced-match/README.md new file mode 100644 index 0000000..08e918c --- /dev/null +++ b/node_modules/balanced-match/README.md @@ -0,0 +1,91 @@ +# balanced-match + +Match balanced string pairs, like `{` and `}` or `` and ``. Supports regular expressions as well! + +[![build status](https://secure.travis-ci.org/juliangruber/balanced-match.svg)](http://travis-ci.org/juliangruber/balanced-match) +[![downloads](https://img.shields.io/npm/dm/balanced-match.svg)](https://www.npmjs.org/package/balanced-match) + +[![testling badge](https://ci.testling.com/juliangruber/balanced-match.png)](https://ci.testling.com/juliangruber/balanced-match) + +## Example + +Get the first matching pair of braces: + +```js +var balanced = require('balanced-match'); + +console.log(balanced('{', '}', 'pre{in{nested}}post')); +console.log(balanced('{', '}', 'pre{first}between{second}post')); +console.log(balanced(/\s+\{\s+/, /\s+\}\s+/, 'pre { in{nest} } post')); +``` + +The matches are: + +```bash +$ node example.js +{ start: 3, end: 14, pre: 'pre', body: 'in{nested}', post: 'post' } +{ start: 3, + end: 9, + pre: 'pre', + body: 'first', + post: 'between{second}post' } +{ start: 3, end: 17, pre: 'pre', body: 'in{nest}', post: 'post' } +``` + +## API + +### var m = balanced(a, b, str) + +For the first non-nested matching pair of `a` and `b` in `str`, return an +object with those keys: + +* **start** the index of the first match of `a` +* **end** the index of the matching `b` +* **pre** the preamble, `a` and `b` not included +* **body** the match, `a` and `b` not included +* **post** the postscript, `a` and `b` not included + +If there's no match, `undefined` will be returned. + +If the `str` contains more `a` than `b` / there are unmatched pairs, the first match that was closed will be used. For example, `{{a}` will match `['{', 'a', '']` and `{a}}` will match `['', 'a', '}']`. + +### var r = balanced.range(a, b, str) + +For the first non-nested matching pair of `a` and `b` in `str`, return an +array with indexes: `[ , ]`. + +If there's no match, `undefined` will be returned. + +If the `str` contains more `a` than `b` / there are unmatched pairs, the first match that was closed will be used. For example, `{{a}` will match `[ 1, 3 ]` and `{a}}` will match `[0, 2]`. + +## Installation + +With [npm](https://npmjs.org) do: + +```bash +npm install balanced-match +``` + +## License + +(MIT) + +Copyright (c) 2013 Julian Gruber <julian@juliangruber.com> + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/balanced-match/index.js b/node_modules/balanced-match/index.js new file mode 100644 index 0000000..1685a76 --- /dev/null +++ b/node_modules/balanced-match/index.js @@ -0,0 +1,59 @@ +'use strict'; +module.exports = balanced; +function balanced(a, b, str) { + if (a instanceof RegExp) a = maybeMatch(a, str); + if (b instanceof RegExp) b = maybeMatch(b, str); + + var r = range(a, b, str); + + return r && { + start: r[0], + end: r[1], + pre: str.slice(0, r[0]), + body: str.slice(r[0] + a.length, r[1]), + post: str.slice(r[1] + b.length) + }; +} + +function maybeMatch(reg, str) { + var m = str.match(reg); + return m ? m[0] : null; +} + +balanced.range = range; +function range(a, b, str) { + var begs, beg, left, right, result; + var ai = str.indexOf(a); + var bi = str.indexOf(b, ai + 1); + var i = ai; + + if (ai >= 0 && bi > 0) { + begs = []; + left = str.length; + + while (i >= 0 && !result) { + if (i == ai) { + begs.push(i); + ai = str.indexOf(a, i + 1); + } else if (begs.length == 1) { + result = [ begs.pop(), bi ]; + } else { + beg = begs.pop(); + if (beg < left) { + left = beg; + right = bi; + } + + bi = str.indexOf(b, i + 1); + } + + i = ai < bi && ai >= 0 ? ai : bi; + } + + if (begs.length) { + result = [ left, right ]; + } + } + + return result; +} diff --git a/node_modules/balanced-match/package.json b/node_modules/balanced-match/package.json new file mode 100644 index 0000000..420b434 --- /dev/null +++ b/node_modules/balanced-match/package.json @@ -0,0 +1,77 @@ +{ + "_from": "balanced-match@^1.0.0", + "_id": "balanced-match@1.0.0", + "_inBundle": false, + "_integrity": "sha1-ibTRmasr7kneFk6gK4nORi1xt2c=", + "_location": "/balanced-match", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "balanced-match@^1.0.0", + "name": "balanced-match", + "escapedName": "balanced-match", + "rawSpec": "^1.0.0", + "saveSpec": null, + "fetchSpec": "^1.0.0" + }, + "_requiredBy": [ + "/brace-expansion" + ], + "_resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.0.tgz", + "_shasum": "89b4d199ab2bee49de164ea02b89ce462d71b767", + "_spec": "balanced-match@^1.0.0", + "_where": "/Users/jessitron/code/jessitron/stringify-tree/node_modules/brace-expansion", + "author": { + "name": "Julian Gruber", + "email": "mail@juliangruber.com", + "url": "http://juliangruber.com" + }, + "bugs": { + "url": "https://github.com/juliangruber/balanced-match/issues" + }, + "bundleDependencies": false, + "dependencies": {}, + "deprecated": false, + "description": "Match balanced character pairs, like \"{\" and \"}\"", + "devDependencies": { + "matcha": "^0.7.0", + "tape": "^4.6.0" + }, + "homepage": "https://github.com/juliangruber/balanced-match", + "keywords": [ + "match", + "regexp", + "test", + "balanced", + "parse" + ], + "license": "MIT", + "main": "index.js", + "name": "balanced-match", + "repository": { + "type": "git", + "url": "git://github.com/juliangruber/balanced-match.git" + }, + "scripts": { + "bench": "make bench", + "test": "make test" + }, + "testling": { + "files": "test/*.js", + "browsers": [ + "ie/8..latest", + "firefox/20..latest", + "firefox/nightly", + "chrome/25..latest", + "chrome/canary", + "opera/12..latest", + "opera/next", + "safari/5.1..latest", + "ipad/6.0..latest", + "iphone/6.0..latest", + "android-browser/4.2..latest" + ] + }, + "version": "1.0.0" +} diff --git a/node_modules/brace-expansion/LICENSE b/node_modules/brace-expansion/LICENSE new file mode 100644 index 0000000..de32266 --- /dev/null +++ b/node_modules/brace-expansion/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2013 Julian Gruber + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/brace-expansion/README.md b/node_modules/brace-expansion/README.md new file mode 100644 index 0000000..6b4e0e1 --- /dev/null +++ b/node_modules/brace-expansion/README.md @@ -0,0 +1,129 @@ +# brace-expansion + +[Brace expansion](https://www.gnu.org/software/bash/manual/html_node/Brace-Expansion.html), +as known from sh/bash, in JavaScript. + +[![build status](https://secure.travis-ci.org/juliangruber/brace-expansion.svg)](http://travis-ci.org/juliangruber/brace-expansion) +[![downloads](https://img.shields.io/npm/dm/brace-expansion.svg)](https://www.npmjs.org/package/brace-expansion) +[![Greenkeeper badge](https://badges.greenkeeper.io/juliangruber/brace-expansion.svg)](https://greenkeeper.io/) + +[![testling badge](https://ci.testling.com/juliangruber/brace-expansion.png)](https://ci.testling.com/juliangruber/brace-expansion) + +## Example + +```js +var expand = require('brace-expansion'); + +expand('file-{a,b,c}.jpg') +// => ['file-a.jpg', 'file-b.jpg', 'file-c.jpg'] + +expand('-v{,,}') +// => ['-v', '-v', '-v'] + +expand('file{0..2}.jpg') +// => ['file0.jpg', 'file1.jpg', 'file2.jpg'] + +expand('file-{a..c}.jpg') +// => ['file-a.jpg', 'file-b.jpg', 'file-c.jpg'] + +expand('file{2..0}.jpg') +// => ['file2.jpg', 'file1.jpg', 'file0.jpg'] + +expand('file{0..4..2}.jpg') +// => ['file0.jpg', 'file2.jpg', 'file4.jpg'] + +expand('file-{a..e..2}.jpg') +// => ['file-a.jpg', 'file-c.jpg', 'file-e.jpg'] + +expand('file{00..10..5}.jpg') +// => ['file00.jpg', 'file05.jpg', 'file10.jpg'] + +expand('{{A..C},{a..c}}') +// => ['A', 'B', 'C', 'a', 'b', 'c'] + +expand('ppp{,config,oe{,conf}}') +// => ['ppp', 'pppconfig', 'pppoe', 'pppoeconf'] +``` + +## API + +```js +var expand = require('brace-expansion'); +``` + +### var expanded = expand(str) + +Return an array of all possible and valid expansions of `str`. If none are +found, `[str]` is returned. + +Valid expansions are: + +```js +/^(.*,)+(.+)?$/ +// {a,b,...} +``` + +A comma separated list of options, like `{a,b}` or `{a,{b,c}}` or `{,a,}`. + +```js +/^-?\d+\.\.-?\d+(\.\.-?\d+)?$/ +// {x..y[..incr]} +``` + +A numeric sequence from `x` to `y` inclusive, with optional increment. +If `x` or `y` start with a leading `0`, all the numbers will be padded +to have equal length. Negative numbers and backwards iteration work too. + +```js +/^-?\d+\.\.-?\d+(\.\.-?\d+)?$/ +// {x..y[..incr]} +``` + +An alphabetic sequence from `x` to `y` inclusive, with optional increment. +`x` and `y` must be exactly one character, and if given, `incr` must be a +number. + +For compatibility reasons, the string `${` is not eligible for brace expansion. + +## Installation + +With [npm](https://npmjs.org) do: + +```bash +npm install brace-expansion +``` + +## Contributors + +- [Julian Gruber](https://github.com/juliangruber) +- [Isaac Z. Schlueter](https://github.com/isaacs) + +## Sponsors + +This module is proudly supported by my [Sponsors](https://github.com/juliangruber/sponsors)! + +Do you want to support modules like this to improve their quality, stability and weigh in on new features? Then please consider donating to my [Patreon](https://www.patreon.com/juliangruber). Not sure how much of my modules you're using? Try [feross/thanks](https://github.com/feross/thanks)! + +## License + +(MIT) + +Copyright (c) 2013 Julian Gruber <julian@juliangruber.com> + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/brace-expansion/index.js b/node_modules/brace-expansion/index.js new file mode 100644 index 0000000..0478be8 --- /dev/null +++ b/node_modules/brace-expansion/index.js @@ -0,0 +1,201 @@ +var concatMap = require('concat-map'); +var balanced = require('balanced-match'); + +module.exports = expandTop; + +var escSlash = '\0SLASH'+Math.random()+'\0'; +var escOpen = '\0OPEN'+Math.random()+'\0'; +var escClose = '\0CLOSE'+Math.random()+'\0'; +var escComma = '\0COMMA'+Math.random()+'\0'; +var escPeriod = '\0PERIOD'+Math.random()+'\0'; + +function numeric(str) { + return parseInt(str, 10) == str + ? parseInt(str, 10) + : str.charCodeAt(0); +} + +function escapeBraces(str) { + return str.split('\\\\').join(escSlash) + .split('\\{').join(escOpen) + .split('\\}').join(escClose) + .split('\\,').join(escComma) + .split('\\.').join(escPeriod); +} + +function unescapeBraces(str) { + return str.split(escSlash).join('\\') + .split(escOpen).join('{') + .split(escClose).join('}') + .split(escComma).join(',') + .split(escPeriod).join('.'); +} + + +// Basically just str.split(","), but handling cases +// where we have nested braced sections, which should be +// treated as individual members, like {a,{b,c},d} +function parseCommaParts(str) { + if (!str) + return ['']; + + var parts = []; + var m = balanced('{', '}', str); + + if (!m) + return str.split(','); + + var pre = m.pre; + var body = m.body; + var post = m.post; + var p = pre.split(','); + + p[p.length-1] += '{' + body + '}'; + var postParts = parseCommaParts(post); + if (post.length) { + p[p.length-1] += postParts.shift(); + p.push.apply(p, postParts); + } + + parts.push.apply(parts, p); + + return parts; +} + +function expandTop(str) { + if (!str) + return []; + + // I don't know why Bash 4.3 does this, but it does. + // Anything starting with {} will have the first two bytes preserved + // but *only* at the top level, so {},a}b will not expand to anything, + // but a{},b}c will be expanded to [a}c,abc]. + // One could argue that this is a bug in Bash, but since the goal of + // this module is to match Bash's rules, we escape a leading {} + if (str.substr(0, 2) === '{}') { + str = '\\{\\}' + str.substr(2); + } + + return expand(escapeBraces(str), true).map(unescapeBraces); +} + +function identity(e) { + return e; +} + +function embrace(str) { + return '{' + str + '}'; +} +function isPadded(el) { + return /^-?0\d/.test(el); +} + +function lte(i, y) { + return i <= y; +} +function gte(i, y) { + return i >= y; +} + +function expand(str, isTop) { + var expansions = []; + + var m = balanced('{', '}', str); + if (!m || /\$$/.test(m.pre)) return [str]; + + var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body); + var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body); + var isSequence = isNumericSequence || isAlphaSequence; + var isOptions = m.body.indexOf(',') >= 0; + if (!isSequence && !isOptions) { + // {a},b} + if (m.post.match(/,.*\}/)) { + str = m.pre + '{' + m.body + escClose + m.post; + return expand(str); + } + return [str]; + } + + var n; + if (isSequence) { + n = m.body.split(/\.\./); + } else { + n = parseCommaParts(m.body); + if (n.length === 1) { + // x{{a,b}}y ==> x{a}y x{b}y + n = expand(n[0], false).map(embrace); + if (n.length === 1) { + var post = m.post.length + ? expand(m.post, false) + : ['']; + return post.map(function(p) { + return m.pre + n[0] + p; + }); + } + } + } + + // at this point, n is the parts, and we know it's not a comma set + // with a single entry. + + // no need to expand pre, since it is guaranteed to be free of brace-sets + var pre = m.pre; + var post = m.post.length + ? expand(m.post, false) + : ['']; + + var N; + + if (isSequence) { + var x = numeric(n[0]); + var y = numeric(n[1]); + var width = Math.max(n[0].length, n[1].length) + var incr = n.length == 3 + ? Math.abs(numeric(n[2])) + : 1; + var test = lte; + var reverse = y < x; + if (reverse) { + incr *= -1; + test = gte; + } + var pad = n.some(isPadded); + + N = []; + + for (var i = x; test(i, y); i += incr) { + var c; + if (isAlphaSequence) { + c = String.fromCharCode(i); + if (c === '\\') + c = ''; + } else { + c = String(i); + if (pad) { + var need = width - c.length; + if (need > 0) { + var z = new Array(need + 1).join('0'); + if (i < 0) + c = '-' + z + c.slice(1); + else + c = z + c; + } + } + } + N.push(c); + } + } else { + N = concatMap(n, function(el) { return expand(el, false) }); + } + + for (var j = 0; j < N.length; j++) { + for (var k = 0; k < post.length; k++) { + var expansion = pre + N[j] + post[k]; + if (!isTop || isSequence || expansion) + expansions.push(expansion); + } + } + + return expansions; +} + diff --git a/node_modules/brace-expansion/package.json b/node_modules/brace-expansion/package.json new file mode 100644 index 0000000..227b8fe --- /dev/null +++ b/node_modules/brace-expansion/package.json @@ -0,0 +1,75 @@ +{ + "_from": "brace-expansion@^1.1.7", + "_id": "brace-expansion@1.1.11", + "_inBundle": false, + "_integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", + "_location": "/brace-expansion", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "brace-expansion@^1.1.7", + "name": "brace-expansion", + "escapedName": "brace-expansion", + "rawSpec": "^1.1.7", + "saveSpec": null, + "fetchSpec": "^1.1.7" + }, + "_requiredBy": [ + "/minimatch" + ], + "_resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", + "_shasum": "3c7fcbf529d87226f3d2f52b966ff5271eb441dd", + "_spec": "brace-expansion@^1.1.7", + "_where": "/Users/jessitron/code/jessitron/stringify-tree/node_modules/minimatch", + "author": { + "name": "Julian Gruber", + "email": "mail@juliangruber.com", + "url": "http://juliangruber.com" + }, + "bugs": { + "url": "https://github.com/juliangruber/brace-expansion/issues" + }, + "bundleDependencies": false, + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + }, + "deprecated": false, + "description": "Brace expansion as known from sh/bash", + "devDependencies": { + "matcha": "^0.7.0", + "tape": "^4.6.0" + }, + "homepage": "https://github.com/juliangruber/brace-expansion", + "keywords": [], + "license": "MIT", + "main": "index.js", + "name": "brace-expansion", + "repository": { + "type": "git", + "url": "git://github.com/juliangruber/brace-expansion.git" + }, + "scripts": { + "bench": "matcha test/perf/bench.js", + "gentest": "bash test/generate.sh", + "test": "tape test/*.js" + }, + "testling": { + "files": "test/*.js", + "browsers": [ + "ie/8..latest", + "firefox/20..latest", + "firefox/nightly", + "chrome/25..latest", + "chrome/canary", + "opera/12..latest", + "opera/next", + "safari/5.1..latest", + "ipad/6.0..latest", + "iphone/6.0..latest", + "android-browser/4.2..latest" + ] + }, + "version": "1.1.11" +} diff --git a/node_modules/browser-stdout/LICENSE b/node_modules/browser-stdout/LICENSE new file mode 100644 index 0000000..775f6ce --- /dev/null +++ b/node_modules/browser-stdout/LICENSE @@ -0,0 +1,5 @@ +Copyright 2018 kumavis + +Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/browser-stdout/README.md b/node_modules/browser-stdout/README.md new file mode 100644 index 0000000..f32028a --- /dev/null +++ b/node_modules/browser-stdout/README.md @@ -0,0 +1,40 @@ +### wat? + +`process.stdout` in your browser. + +### wai? + +iono. cuz hakz. + +### hau? + +```js +var BrowserStdout = require('browser-stdout') + +myStream.pipe(BrowserStdout()) +``` + +### monkey + +You can monkey-patch `process.stdout` for your dependency graph like this: + +``` +process.stdout = require('browser-stdout')() +var coolTool = require('module-that-uses-stdout-somewhere-in-its-depths') +``` + +### opts + +opts are passed directly to `stream.Writable`. +additionally, a label arg can be used to label console output. + +```js +BrowserStdout({ + objectMode: true, + label: 'dataz', +}) +``` + +### ur doin it rong + +i accept pr's. \ No newline at end of file diff --git a/node_modules/browser-stdout/index.js b/node_modules/browser-stdout/index.js new file mode 100644 index 0000000..daf39c3 --- /dev/null +++ b/node_modules/browser-stdout/index.js @@ -0,0 +1,25 @@ +var WritableStream = require('stream').Writable +var inherits = require('util').inherits + +module.exports = BrowserStdout + + +inherits(BrowserStdout, WritableStream) + +function BrowserStdout(opts) { + if (!(this instanceof BrowserStdout)) return new BrowserStdout(opts) + + opts = opts || {} + WritableStream.call(this, opts) + this.label = (opts.label !== undefined) ? opts.label : 'stdout' +} + +BrowserStdout.prototype._write = function(chunks, encoding, cb) { + var output = chunks.toString ? chunks.toString() : chunks + if (this.label === false) { + console.log(output) + } else { + console.log(this.label+':', output) + } + process.nextTick(cb) +} diff --git a/node_modules/browser-stdout/package.json b/node_modules/browser-stdout/package.json new file mode 100644 index 0000000..3806e70 --- /dev/null +++ b/node_modules/browser-stdout/package.json @@ -0,0 +1,46 @@ +{ + "_from": "browser-stdout@1.3.1", + "_id": "browser-stdout@1.3.1", + "_inBundle": false, + "_integrity": "sha512-qhAVI1+Av2X7qelOfAIYwXONood6XlZE/fXaBSmW/T5SzLAmCgzi+eiWE7fUvbHaeNBQH13UftjpXxsfLkMpgw==", + "_location": "/browser-stdout", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "browser-stdout@1.3.1", + "name": "browser-stdout", + "escapedName": "browser-stdout", + "rawSpec": "1.3.1", + "saveSpec": null, + "fetchSpec": "1.3.1" + }, + "_requiredBy": [ + "/mocha" + ], + "_resolved": "https://registry.npmjs.org/browser-stdout/-/browser-stdout-1.3.1.tgz", + "_shasum": "baa559ee14ced73452229bad7326467c61fabd60", + "_spec": "browser-stdout@1.3.1", + "_where": "/Users/jessitron/code/jessitron/stringify-tree/node_modules/mocha", + "author": { + "name": "kumavis" + }, + "bugs": { + "url": "https://github.com/kumavis/browser-stdout/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "`process.stdout` in your browser.", + "homepage": "https://github.com/kumavis/browser-stdout#readme", + "license": "ISC", + "main": "index.js", + "name": "browser-stdout", + "repository": { + "type": "git", + "url": "git+ssh://git@github.com/kumavis/browser-stdout.git" + }, + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "version": "1.3.1" +} diff --git a/node_modules/buffer-from/LICENSE b/node_modules/buffer-from/LICENSE new file mode 100644 index 0000000..e4bf1d6 --- /dev/null +++ b/node_modules/buffer-from/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2016, 2018 Linus Unnebäck + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/buffer-from/index.js b/node_modules/buffer-from/index.js new file mode 100644 index 0000000..d92a83d --- /dev/null +++ b/node_modules/buffer-from/index.js @@ -0,0 +1,69 @@ +var toString = Object.prototype.toString + +var isModern = ( + typeof Buffer.alloc === 'function' && + typeof Buffer.allocUnsafe === 'function' && + typeof Buffer.from === 'function' +) + +function isArrayBuffer (input) { + return toString.call(input).slice(8, -1) === 'ArrayBuffer' +} + +function fromArrayBuffer (obj, byteOffset, length) { + byteOffset >>>= 0 + + var maxLength = obj.byteLength - byteOffset + + if (maxLength < 0) { + throw new RangeError("'offset' is out of bounds") + } + + if (length === undefined) { + length = maxLength + } else { + length >>>= 0 + + if (length > maxLength) { + throw new RangeError("'length' is out of bounds") + } + } + + return isModern + ? Buffer.from(obj.slice(byteOffset, byteOffset + length)) + : new Buffer(new Uint8Array(obj.slice(byteOffset, byteOffset + length))) +} + +function fromString (string, encoding) { + if (typeof encoding !== 'string' || encoding === '') { + encoding = 'utf8' + } + + if (!Buffer.isEncoding(encoding)) { + throw new TypeError('"encoding" must be a valid string encoding') + } + + return isModern + ? Buffer.from(string, encoding) + : new Buffer(string, encoding) +} + +function bufferFrom (value, encodingOrOffset, length) { + if (typeof value === 'number') { + throw new TypeError('"value" argument must not be a number') + } + + if (isArrayBuffer(value)) { + return fromArrayBuffer(value, encodingOrOffset, length) + } + + if (typeof value === 'string') { + return fromString(value, encodingOrOffset) + } + + return isModern + ? Buffer.from(value) + : new Buffer(value) +} + +module.exports = bufferFrom diff --git a/node_modules/buffer-from/package.json b/node_modules/buffer-from/package.json new file mode 100644 index 0000000..fdbe68b --- /dev/null +++ b/node_modules/buffer-from/package.json @@ -0,0 +1,53 @@ +{ + "_from": "buffer-from@^1.1.0", + "_id": "buffer-from@1.1.1", + "_inBundle": false, + "_integrity": "sha512-MQcXEUbCKtEo7bhqEs6560Hyd4XaovZlO/k9V3hjVUF/zwW7KBVdSK4gIt/bzwS9MbR5qob+F5jusZsb0YQK2A==", + "_location": "/buffer-from", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "buffer-from@^1.1.0", + "name": "buffer-from", + "escapedName": "buffer-from", + "rawSpec": "^1.1.0", + "saveSpec": null, + "fetchSpec": "^1.1.0" + }, + "_requiredBy": [ + "/source-map-support", + "/ts-node" + ], + "_resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.1.tgz", + "_shasum": "32713bc028f75c02fdb710d7c7bcec1f2c6070ef", + "_spec": "buffer-from@^1.1.0", + "_where": "/Users/jessitron/code/jessitron/stringify-tree/node_modules/ts-node", + "bugs": { + "url": "https://github.com/LinusU/buffer-from/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "A [ponyfill](https://ponyfill.com) for `Buffer.from`, uses native implementation if available.", + "devDependencies": { + "standard": "^7.1.2" + }, + "files": [ + "index.js" + ], + "homepage": "https://github.com/LinusU/buffer-from#readme", + "keywords": [ + "buffer", + "buffer from" + ], + "license": "MIT", + "name": "buffer-from", + "repository": { + "type": "git", + "url": "git+https://github.com/LinusU/buffer-from.git" + }, + "scripts": { + "test": "standard && node test" + }, + "version": "1.1.1" +} diff --git a/node_modules/buffer-from/readme.md b/node_modules/buffer-from/readme.md new file mode 100644 index 0000000..9880a55 --- /dev/null +++ b/node_modules/buffer-from/readme.md @@ -0,0 +1,69 @@ +# Buffer From + +A [ponyfill](https://ponyfill.com) for `Buffer.from`, uses native implementation if available. + +## Installation + +```sh +npm install --save buffer-from +``` + +## Usage + +```js +const bufferFrom = require('buffer-from') + +console.log(bufferFrom([1, 2, 3, 4])) +//=> + +const arr = new Uint8Array([1, 2, 3, 4]) +console.log(bufferFrom(arr.buffer, 1, 2)) +//=> + +console.log(bufferFrom('test', 'utf8')) +//=> + +const buf = bufferFrom('test') +console.log(bufferFrom(buf)) +//=> +``` + +## API + +### bufferFrom(array) + +- `array` <Array> + +Allocates a new `Buffer` using an `array` of octets. + +### bufferFrom(arrayBuffer[, byteOffset[, length]]) + +- `arrayBuffer` <ArrayBuffer> The `.buffer` property of a TypedArray or ArrayBuffer +- `byteOffset` <Integer> Where to start copying from `arrayBuffer`. **Default:** `0` +- `length` <Integer> How many bytes to copy from `arrayBuffer`. **Default:** `arrayBuffer.length - byteOffset` + +When passed a reference to the `.buffer` property of a TypedArray instance, the +newly created `Buffer` will share the same allocated memory as the TypedArray. + +The optional `byteOffset` and `length` arguments specify a memory range within +the `arrayBuffer` that will be shared by the `Buffer`. + +### bufferFrom(buffer) + +- `buffer` <Buffer> An existing `Buffer` to copy data from + +Copies the passed `buffer` data onto a new `Buffer` instance. + +### bufferFrom(string[, encoding]) + +- `string` <String> A string to encode. +- `encoding` <String> The encoding of `string`. **Default:** `'utf8'` + +Creates a new `Buffer` containing the given JavaScript string `string`. If +provided, the `encoding` parameter identifies the character encoding of +`string`. + +## See also + +- [buffer-alloc](https://github.com/LinusU/buffer-alloc) A ponyfill for `Buffer.alloc` +- [buffer-alloc-unsafe](https://github.com/LinusU/buffer-alloc-unsafe) A ponyfill for `Buffer.allocUnsafe` diff --git a/node_modules/commander/CHANGELOG.md b/node_modules/commander/CHANGELOG.md new file mode 100644 index 0000000..5e2f813 --- /dev/null +++ b/node_modules/commander/CHANGELOG.md @@ -0,0 +1,356 @@ + +2.15.0 / 2018-03-07 +================== + + * Update downloads badge to point to graph of downloads over time instead of duplicating link to npm + * Arguments description + +2.14.1 / 2018-02-07 +================== + + * Fix typing of help function + +2.14.0 / 2018-02-05 +================== + + * only register the option:version event once + * Fixes issue #727: Passing empty string for option on command is set to undefined + * enable eqeqeq rule + * resolves #754 add linter configuration to project + * resolves #560 respect custom name for version option + * document how to override the version flag + * document using options per command + +2.13.0 / 2018-01-09 +================== + + * Do not print default for --no- + * remove trailing spaces in command help + * Update CI's Node.js to LTS and latest version + * typedefs: Command and Option types added to commander namespace + +2.12.2 / 2017-11-28 +================== + + * fix: typings are not shipped + +2.12.1 / 2017-11-23 +================== + + * Move @types/node to dev dependency + +2.12.0 / 2017-11-22 +================== + + * add attributeName() method to Option objects + * Documentation updated for options with --no prefix + * typings: `outputHelp` takes a string as the first parameter + * typings: use overloads + * feat(typings): update to match js api + * Print default value in option help + * Fix translation error + * Fail when using same command and alias (#491) + * feat(typings): add help callback + * fix bug when description is add after command with options (#662) + * Format js code + * Rename History.md to CHANGELOG.md (#668) + * feat(typings): add typings to support TypeScript (#646) + * use current node + +2.11.0 / 2017-07-03 +================== + + * Fix help section order and padding (#652) + * feature: support for signals to subcommands (#632) + * Fixed #37, --help should not display first (#447) + * Fix translation errors. (#570) + * Add package-lock.json + * Remove engines + * Upgrade package version + * Prefix events to prevent conflicts between commands and options (#494) + * Removing dependency on graceful-readlink + * Support setting name in #name function and make it chainable + * Add .vscode directory to .gitignore (Visual Studio Code metadata) + * Updated link to ruby commander in readme files + +2.10.0 / 2017-06-19 +================== + + * Update .travis.yml. drop support for older node.js versions. + * Fix require arguments in README.md + * On SemVer you do not start from 0.0.1 + * Add missing semi colon in readme + * Add save param to npm install + * node v6 travis test + * Update Readme_zh-CN.md + * Allow literal '--' to be passed-through as an argument + * Test subcommand alias help + * link build badge to master branch + * Support the alias of Git style sub-command + * added keyword commander for better search result on npm + * Fix Sub-Subcommands + * test node.js stable + * Fixes TypeError when a command has an option called `--description` + * Update README.md to make it beginner friendly and elaborate on the difference between angled and square brackets. + * Add chinese Readme file + +2.9.0 / 2015-10-13 +================== + + * Add option `isDefault` to set default subcommand #415 @Qix- + * Add callback to allow filtering or post-processing of help text #434 @djulien + * Fix `undefined` text in help information close #414 #416 @zhiyelee + +2.8.1 / 2015-04-22 +================== + + * Back out `support multiline description` Close #396 #397 + +2.8.0 / 2015-04-07 +================== + + * Add `process.execArg` support, execution args like `--harmony` will be passed to sub-commands #387 @DigitalIO @zhiyelee + * Fix bug in Git-style sub-commands #372 @zhiyelee + * Allow commands to be hidden from help #383 @tonylukasavage + * When git-style sub-commands are in use, yet none are called, display help #382 @claylo + * Add ability to specify arguments syntax for top-level command #258 @rrthomas + * Support multiline descriptions #208 @zxqfox + +2.7.1 / 2015-03-11 +================== + + * Revert #347 (fix collisions when option and first arg have same name) which causes a bug in #367. + +2.7.0 / 2015-03-09 +================== + + * Fix git-style bug when installed globally. Close #335 #349 @zhiyelee + * Fix collisions when option and first arg have same name. Close #346 #347 @tonylukasavage + * Add support for camelCase on `opts()`. Close #353 @nkzawa + * Add node.js 0.12 and io.js to travis.yml + * Allow RegEx options. #337 @palanik + * Fixes exit code when sub-command failing. Close #260 #332 @pirelenito + * git-style `bin` files in $PATH make sense. Close #196 #327 @zhiyelee + +2.6.0 / 2014-12-30 +================== + + * added `Command#allowUnknownOption` method. Close #138 #318 @doozr @zhiyelee + * Add application description to the help msg. Close #112 @dalssoft + +2.5.1 / 2014-12-15 +================== + + * fixed two bugs incurred by variadic arguments. Close #291 @Quentin01 #302 @zhiyelee + +2.5.0 / 2014-10-24 +================== + + * add support for variadic arguments. Closes #277 @whitlockjc + +2.4.0 / 2014-10-17 +================== + + * fixed a bug on executing the coercion function of subcommands option. Closes #270 + * added `Command.prototype.name` to retrieve command name. Closes #264 #266 @tonylukasavage + * added `Command.prototype.opts` to retrieve all the options as a simple object of key-value pairs. Closes #262 @tonylukasavage + * fixed a bug on subcommand name. Closes #248 @jonathandelgado + * fixed function normalize doesn’t honor option terminator. Closes #216 @abbr + +2.3.0 / 2014-07-16 +================== + + * add command alias'. Closes PR #210 + * fix: Typos. Closes #99 + * fix: Unused fs module. Closes #217 + +2.2.0 / 2014-03-29 +================== + + * add passing of previous option value + * fix: support subcommands on windows. Closes #142 + * Now the defaultValue passed as the second argument of the coercion function. + +2.1.0 / 2013-11-21 +================== + + * add: allow cflag style option params, unit test, fixes #174 + +2.0.0 / 2013-07-18 +================== + + * remove input methods (.prompt, .confirm, etc) + +1.3.2 / 2013-07-18 +================== + + * add support for sub-commands to co-exist with the original command + +1.3.1 / 2013-07-18 +================== + + * add quick .runningCommand hack so you can opt-out of other logic when running a sub command + +1.3.0 / 2013-07-09 +================== + + * add EACCES error handling + * fix sub-command --help + +1.2.0 / 2013-06-13 +================== + + * allow "-" hyphen as an option argument + * support for RegExp coercion + +1.1.1 / 2012-11-20 +================== + + * add more sub-command padding + * fix .usage() when args are present. Closes #106 + +1.1.0 / 2012-11-16 +================== + + * add git-style executable subcommand support. Closes #94 + +1.0.5 / 2012-10-09 +================== + + * fix `--name` clobbering. Closes #92 + * fix examples/help. Closes #89 + +1.0.4 / 2012-09-03 +================== + + * add `outputHelp()` method. + +1.0.3 / 2012-08-30 +================== + + * remove invalid .version() defaulting + +1.0.2 / 2012-08-24 +================== + + * add `--foo=bar` support [arv] + * fix password on node 0.8.8. Make backward compatible with 0.6 [focusaurus] + +1.0.1 / 2012-08-03 +================== + + * fix issue #56 + * fix tty.setRawMode(mode) was moved to tty.ReadStream#setRawMode() (i.e. process.stdin.setRawMode()) + +1.0.0 / 2012-07-05 +================== + + * add support for optional option descriptions + * add defaulting of `.version()` to package.json's version + +0.6.1 / 2012-06-01 +================== + + * Added: append (yes or no) on confirmation + * Added: allow node.js v0.7.x + +0.6.0 / 2012-04-10 +================== + + * Added `.prompt(obj, callback)` support. Closes #49 + * Added default support to .choose(). Closes #41 + * Fixed the choice example + +0.5.1 / 2011-12-20 +================== + + * Fixed `password()` for recent nodes. Closes #36 + +0.5.0 / 2011-12-04 +================== + + * Added sub-command option support [itay] + +0.4.3 / 2011-12-04 +================== + + * Fixed custom help ordering. Closes #32 + +0.4.2 / 2011-11-24 +================== + + * Added travis support + * Fixed: line-buffered input automatically trimmed. Closes #31 + +0.4.1 / 2011-11-18 +================== + + * Removed listening for "close" on --help + +0.4.0 / 2011-11-15 +================== + + * Added support for `--`. Closes #24 + +0.3.3 / 2011-11-14 +================== + + * Fixed: wait for close event when writing help info [Jerry Hamlet] + +0.3.2 / 2011-11-01 +================== + + * Fixed long flag definitions with values [felixge] + +0.3.1 / 2011-10-31 +================== + + * Changed `--version` short flag to `-V` from `-v` + * Changed `.version()` so it's configurable [felixge] + +0.3.0 / 2011-10-31 +================== + + * Added support for long flags only. Closes #18 + +0.2.1 / 2011-10-24 +================== + + * "node": ">= 0.4.x < 0.7.0". Closes #20 + +0.2.0 / 2011-09-26 +================== + + * Allow for defaults that are not just boolean. Default peassignment only occurs for --no-*, optional, and required arguments. [Jim Isaacs] + +0.1.0 / 2011-08-24 +================== + + * Added support for custom `--help` output + +0.0.5 / 2011-08-18 +================== + + * Changed: when the user enters nothing prompt for password again + * Fixed issue with passwords beginning with numbers [NuckChorris] + +0.0.4 / 2011-08-15 +================== + + * Fixed `Commander#args` + +0.0.3 / 2011-08-15 +================== + + * Added default option value support + +0.0.2 / 2011-08-15 +================== + + * Added mask support to `Command#password(str[, mask], fn)` + * Added `Command#password(str, fn)` + +0.0.1 / 2010-01-03 +================== + + * Initial release diff --git a/node_modules/commander/LICENSE b/node_modules/commander/LICENSE new file mode 100644 index 0000000..10f997a --- /dev/null +++ b/node_modules/commander/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2011 TJ Holowaychuk + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/commander/Readme.md b/node_modules/commander/Readme.md new file mode 100644 index 0000000..a29da40 --- /dev/null +++ b/node_modules/commander/Readme.md @@ -0,0 +1,408 @@ +# Commander.js + + +[![Build Status](https://api.travis-ci.org/tj/commander.js.svg?branch=master)](http://travis-ci.org/tj/commander.js) +[![NPM Version](http://img.shields.io/npm/v/commander.svg?style=flat)](https://www.npmjs.org/package/commander) +[![NPM Downloads](https://img.shields.io/npm/dm/commander.svg?style=flat)](https://npmcharts.com/compare/commander?minimal=true) +[![Join the chat at https://gitter.im/tj/commander.js](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/tj/commander.js?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) + + The complete solution for [node.js](http://nodejs.org) command-line interfaces, inspired by Ruby's [commander](https://github.com/commander-rb/commander). + [API documentation](http://tj.github.com/commander.js/) + + +## Installation + + $ npm install commander --save + +## Option parsing + +Options with commander are defined with the `.option()` method, also serving as documentation for the options. The example below parses args and options from `process.argv`, leaving remaining args as the `program.args` array which were not consumed by options. + +```js +#!/usr/bin/env node + +/** + * Module dependencies. + */ + +var program = require('commander'); + +program + .version('0.1.0') + .option('-p, --peppers', 'Add peppers') + .option('-P, --pineapple', 'Add pineapple') + .option('-b, --bbq-sauce', 'Add bbq sauce') + .option('-c, --cheese [type]', 'Add the specified type of cheese [marble]', 'marble') + .parse(process.argv); + +console.log('you ordered a pizza with:'); +if (program.peppers) console.log(' - peppers'); +if (program.pineapple) console.log(' - pineapple'); +if (program.bbqSauce) console.log(' - bbq'); +console.log(' - %s cheese', program.cheese); +``` + +Short flags may be passed as a single arg, for example `-abc` is equivalent to `-a -b -c`. Multi-word options such as "--template-engine" are camel-cased, becoming `program.templateEngine` etc. + +Note that multi-word options starting with `--no` prefix negate the boolean value of the following word. For example, `--no-sauce` sets the value of `program.sauce` to false. + +```js +#!/usr/bin/env node + +/** + * Module dependencies. + */ + +var program = require('commander'); + +program + .option('--no-sauce', 'Remove sauce') + .parse(process.argv); + +console.log('you ordered a pizza'); +if (program.sauce) console.log(' with sauce'); +else console.log(' without sauce'); +``` + +## Version option + +Calling the `version` implicitly adds the `-V` and `--version` options to the command. +When either of these options is present, the command prints the version number and exits. + + $ ./examples/pizza -V + 0.0.1 + +If you want your program to respond to the `-v` option instead of the `-V` option, simply pass custom flags to the `version` method using the same syntax as the `option` method. + +```js +program + .version('0.0.1', '-v, --version') +``` + +The version flags can be named anything, but the long option is required. + +## Command-specific options + +You can attach options to a command. + +```js +#!/usr/bin/env node + +var program = require('commander'); + +program + .command('rm ') + .option('-r, --recursive', 'Remove recursively') + .action(function (dir, cmd) { + console.log('remove ' + dir + (cmd.recursive ? ' recursively' : '')) + }) + +program.parse(process.argv) +``` + +A command's options are validated when the command is used. Any unknown options will be reported as an error. However, if an action-based command does not define an action, then the options are not validated. + +## Coercion + +```js +function range(val) { + return val.split('..').map(Number); +} + +function list(val) { + return val.split(','); +} + +function collect(val, memo) { + memo.push(val); + return memo; +} + +function increaseVerbosity(v, total) { + return total + 1; +} + +program + .version('0.1.0') + .usage('[options] ') + .option('-i, --integer ', 'An integer argument', parseInt) + .option('-f, --float ', 'A float argument', parseFloat) + .option('-r, --range ..', 'A range', range) + .option('-l, --list ', 'A list', list) + .option('-o, --optional [value]', 'An optional value') + .option('-c, --collect [value]', 'A repeatable value', collect, []) + .option('-v, --verbose', 'A value that can be increased', increaseVerbosity, 0) + .parse(process.argv); + +console.log(' int: %j', program.integer); +console.log(' float: %j', program.float); +console.log(' optional: %j', program.optional); +program.range = program.range || []; +console.log(' range: %j..%j', program.range[0], program.range[1]); +console.log(' list: %j', program.list); +console.log(' collect: %j', program.collect); +console.log(' verbosity: %j', program.verbose); +console.log(' args: %j', program.args); +``` + +## Regular Expression +```js +program + .version('0.1.0') + .option('-s --size ', 'Pizza size', /^(large|medium|small)$/i, 'medium') + .option('-d --drink [drink]', 'Drink', /^(coke|pepsi|izze)$/i) + .parse(process.argv); + +console.log(' size: %j', program.size); +console.log(' drink: %j', program.drink); +``` + +## Variadic arguments + + The last argument of a command can be variadic, and only the last argument. To make an argument variadic you have to + append `...` to the argument name. Here is an example: + +```js +#!/usr/bin/env node + +/** + * Module dependencies. + */ + +var program = require('commander'); + +program + .version('0.1.0') + .command('rmdir [otherDirs...]') + .action(function (dir, otherDirs) { + console.log('rmdir %s', dir); + if (otherDirs) { + otherDirs.forEach(function (oDir) { + console.log('rmdir %s', oDir); + }); + } + }); + +program.parse(process.argv); +``` + + An `Array` is used for the value of a variadic argument. This applies to `program.args` as well as the argument passed + to your action as demonstrated above. + +## Specify the argument syntax + +```js +#!/usr/bin/env node + +var program = require('commander'); + +program + .version('0.1.0') + .arguments(' [env]') + .action(function (cmd, env) { + cmdValue = cmd; + envValue = env; + }); + +program.parse(process.argv); + +if (typeof cmdValue === 'undefined') { + console.error('no command given!'); + process.exit(1); +} +console.log('command:', cmdValue); +console.log('environment:', envValue || "no environment given"); +``` +Angled brackets (e.g. ``) indicate required input. Square brackets (e.g. `[env]`) indicate optional input. + +## Git-style sub-commands + +```js +// file: ./examples/pm +var program = require('commander'); + +program + .version('0.1.0') + .command('install [name]', 'install one or more packages') + .command('search [query]', 'search with optional query') + .command('list', 'list packages installed', {isDefault: true}) + .parse(process.argv); +``` + +When `.command()` is invoked with a description argument, no `.action(callback)` should be called to handle sub-commands, otherwise there will be an error. This tells commander that you're going to use separate executables for sub-commands, much like `git(1)` and other popular tools. +The commander will try to search the executables in the directory of the entry script (like `./examples/pm`) with the name `program-command`, like `pm-install`, `pm-search`. + +Options can be passed with the call to `.command()`. Specifying `true` for `opts.noHelp` will remove the option from the generated help output. Specifying `true` for `opts.isDefault` will run the subcommand if no other subcommand is specified. + +If the program is designed to be installed globally, make sure the executables have proper modes, like `755`. + +### `--harmony` + +You can enable `--harmony` option in two ways: +* Use `#! /usr/bin/env node --harmony` in the sub-commands scripts. Note some os version don’t support this pattern. +* Use the `--harmony` option when call the command, like `node --harmony examples/pm publish`. The `--harmony` option will be preserved when spawning sub-command process. + +## Automated --help + + The help information is auto-generated based on the information commander already knows about your program, so the following `--help` info is for free: + +``` + $ ./examples/pizza --help + + Usage: pizza [options] + + An application for pizzas ordering + + Options: + + -h, --help output usage information + -V, --version output the version number + -p, --peppers Add peppers + -P, --pineapple Add pineapple + -b, --bbq Add bbq sauce + -c, --cheese Add the specified type of cheese [marble] + -C, --no-cheese You do not want any cheese + +``` + +## Custom help + + You can display arbitrary `-h, --help` information + by listening for "--help". Commander will automatically + exit once you are done so that the remainder of your program + does not execute causing undesired behaviours, for example + in the following executable "stuff" will not output when + `--help` is used. + +```js +#!/usr/bin/env node + +/** + * Module dependencies. + */ + +var program = require('commander'); + +program + .version('0.1.0') + .option('-f, --foo', 'enable some foo') + .option('-b, --bar', 'enable some bar') + .option('-B, --baz', 'enable some baz'); + +// must be before .parse() since +// node's emit() is immediate + +program.on('--help', function(){ + console.log(' Examples:'); + console.log(''); + console.log(' $ custom-help --help'); + console.log(' $ custom-help -h'); + console.log(''); +}); + +program.parse(process.argv); + +console.log('stuff'); +``` + +Yields the following help output when `node script-name.js -h` or `node script-name.js --help` are run: + +``` + +Usage: custom-help [options] + +Options: + + -h, --help output usage information + -V, --version output the version number + -f, --foo enable some foo + -b, --bar enable some bar + -B, --baz enable some baz + +Examples: + + $ custom-help --help + $ custom-help -h + +``` + +## .outputHelp(cb) + +Output help information without exiting. +Optional callback cb allows post-processing of help text before it is displayed. + +If you want to display help by default (e.g. if no command was provided), you can use something like: + +```js +var program = require('commander'); +var colors = require('colors'); + +program + .version('0.1.0') + .command('getstream [url]', 'get stream URL') + .parse(process.argv); + +if (!process.argv.slice(2).length) { + program.outputHelp(make_red); +} + +function make_red(txt) { + return colors.red(txt); //display the help text in red on the console +} +``` + +## .help(cb) + + Output help information and exit immediately. + Optional callback cb allows post-processing of help text before it is displayed. + +## Examples + +```js +var program = require('commander'); + +program + .version('0.1.0') + .option('-C, --chdir ', 'change the working directory') + .option('-c, --config ', 'set config path. defaults to ./deploy.conf') + .option('-T, --no-tests', 'ignore test hook'); + +program + .command('setup [env]') + .description('run setup commands for all envs') + .option("-s, --setup_mode [mode]", "Which setup mode to use") + .action(function(env, options){ + var mode = options.setup_mode || "normal"; + env = env || 'all'; + console.log('setup for %s env(s) with %s mode', env, mode); + }); + +program + .command('exec ') + .alias('ex') + .description('execute the given remote cmd') + .option("-e, --exec_mode ", "Which exec mode to use") + .action(function(cmd, options){ + console.log('exec "%s" using %s mode', cmd, options.exec_mode); + }).on('--help', function() { + console.log(' Examples:'); + console.log(); + console.log(' $ deploy exec sequential'); + console.log(' $ deploy exec async'); + console.log(); + }); + +program + .command('*') + .action(function(env){ + console.log('deploying "%s"', env); + }); + +program.parse(process.argv); +``` + +More Demos can be found in the [examples](https://github.com/tj/commander.js/tree/master/examples) directory. + +## License + +MIT diff --git a/node_modules/commander/index.js b/node_modules/commander/index.js new file mode 100644 index 0000000..fb648be --- /dev/null +++ b/node_modules/commander/index.js @@ -0,0 +1,1231 @@ +/** + * Module dependencies. + */ + +var EventEmitter = require('events').EventEmitter; +var spawn = require('child_process').spawn; +var path = require('path'); +var dirname = path.dirname; +var basename = path.basename; +var fs = require('fs'); + +/** + * Inherit `Command` from `EventEmitter.prototype`. + */ + +require('util').inherits(Command, EventEmitter); + +/** + * Expose the root command. + */ + +exports = module.exports = new Command(); + +/** + * Expose `Command`. + */ + +exports.Command = Command; + +/** + * Expose `Option`. + */ + +exports.Option = Option; + +/** + * Initialize a new `Option` with the given `flags` and `description`. + * + * @param {String} flags + * @param {String} description + * @api public + */ + +function Option(flags, description) { + this.flags = flags; + this.required = ~flags.indexOf('<'); + this.optional = ~flags.indexOf('['); + this.bool = !~flags.indexOf('-no-'); + flags = flags.split(/[ ,|]+/); + if (flags.length > 1 && !/^[[<]/.test(flags[1])) this.short = flags.shift(); + this.long = flags.shift(); + this.description = description || ''; +} + +/** + * Return option name. + * + * @return {String} + * @api private + */ + +Option.prototype.name = function() { + return this.long + .replace('--', '') + .replace('no-', ''); +}; + +/** + * Return option name, in a camelcase format that can be used + * as a object attribute key. + * + * @return {String} + * @api private + */ + +Option.prototype.attributeName = function() { + return camelcase(this.name()); +}; + +/** + * Check if `arg` matches the short or long flag. + * + * @param {String} arg + * @return {Boolean} + * @api private + */ + +Option.prototype.is = function(arg) { + return this.short === arg || this.long === arg; +}; + +/** + * Initialize a new `Command`. + * + * @param {String} name + * @api public + */ + +function Command(name) { + this.commands = []; + this.options = []; + this._execs = {}; + this._allowUnknownOption = false; + this._args = []; + this._name = name || ''; +} + +/** + * Add command `name`. + * + * The `.action()` callback is invoked when the + * command `name` is specified via __ARGV__, + * and the remaining arguments are applied to the + * function for access. + * + * When the `name` is "*" an un-matched command + * will be passed as the first arg, followed by + * the rest of __ARGV__ remaining. + * + * Examples: + * + * program + * .version('0.0.1') + * .option('-C, --chdir ', 'change the working directory') + * .option('-c, --config ', 'set config path. defaults to ./deploy.conf') + * .option('-T, --no-tests', 'ignore test hook') + * + * program + * .command('setup') + * .description('run remote setup commands') + * .action(function() { + * console.log('setup'); + * }); + * + * program + * .command('exec ') + * .description('run the given remote command') + * .action(function(cmd) { + * console.log('exec "%s"', cmd); + * }); + * + * program + * .command('teardown [otherDirs...]') + * .description('run teardown commands') + * .action(function(dir, otherDirs) { + * console.log('dir "%s"', dir); + * if (otherDirs) { + * otherDirs.forEach(function (oDir) { + * console.log('dir "%s"', oDir); + * }); + * } + * }); + * + * program + * .command('*') + * .description('deploy the given env') + * .action(function(env) { + * console.log('deploying "%s"', env); + * }); + * + * program.parse(process.argv); + * + * @param {String} name + * @param {String} [desc] for git-style sub-commands + * @return {Command} the new command + * @api public + */ + +Command.prototype.command = function(name, desc, opts) { + if (typeof desc === 'object' && desc !== null) { + opts = desc; + desc = null; + } + opts = opts || {}; + var args = name.split(/ +/); + var cmd = new Command(args.shift()); + + if (desc) { + cmd.description(desc); + this.executables = true; + this._execs[cmd._name] = true; + if (opts.isDefault) this.defaultExecutable = cmd._name; + } + cmd._noHelp = !!opts.noHelp; + this.commands.push(cmd); + cmd.parseExpectedArgs(args); + cmd.parent = this; + + if (desc) return this; + return cmd; +}; + +/** + * Define argument syntax for the top-level command. + * + * @api public + */ + +Command.prototype.arguments = function(desc) { + return this.parseExpectedArgs(desc.split(/ +/)); +}; + +/** + * Add an implicit `help [cmd]` subcommand + * which invokes `--help` for the given command. + * + * @api private + */ + +Command.prototype.addImplicitHelpCommand = function() { + this.command('help [cmd]', 'display help for [cmd]'); +}; + +/** + * Parse expected `args`. + * + * For example `["[type]"]` becomes `[{ required: false, name: 'type' }]`. + * + * @param {Array} args + * @return {Command} for chaining + * @api public + */ + +Command.prototype.parseExpectedArgs = function(args) { + if (!args.length) return; + var self = this; + args.forEach(function(arg) { + var argDetails = { + required: false, + name: '', + variadic: false + }; + + switch (arg[0]) { + case '<': + argDetails.required = true; + argDetails.name = arg.slice(1, -1); + break; + case '[': + argDetails.name = arg.slice(1, -1); + break; + } + + if (argDetails.name.length > 3 && argDetails.name.slice(-3) === '...') { + argDetails.variadic = true; + argDetails.name = argDetails.name.slice(0, -3); + } + if (argDetails.name) { + self._args.push(argDetails); + } + }); + return this; +}; + +/** + * Register callback `fn` for the command. + * + * Examples: + * + * program + * .command('help') + * .description('display verbose help') + * .action(function() { + * // output help here + * }); + * + * @param {Function} fn + * @return {Command} for chaining + * @api public + */ + +Command.prototype.action = function(fn) { + var self = this; + var listener = function(args, unknown) { + // Parse any so-far unknown options + args = args || []; + unknown = unknown || []; + + var parsed = self.parseOptions(unknown); + + // Output help if necessary + outputHelpIfNecessary(self, parsed.unknown); + + // If there are still any unknown options, then we simply + // die, unless someone asked for help, in which case we give it + // to them, and then we die. + if (parsed.unknown.length > 0) { + self.unknownOption(parsed.unknown[0]); + } + + // Leftover arguments need to be pushed back. Fixes issue #56 + if (parsed.args.length) args = parsed.args.concat(args); + + self._args.forEach(function(arg, i) { + if (arg.required && args[i] == null) { + self.missingArgument(arg.name); + } else if (arg.variadic) { + if (i !== self._args.length - 1) { + self.variadicArgNotLast(arg.name); + } + + args[i] = args.splice(i); + } + }); + + // Always append ourselves to the end of the arguments, + // to make sure we match the number of arguments the user + // expects + if (self._args.length) { + args[self._args.length] = self; + } else { + args.push(self); + } + + fn.apply(self, args); + }; + var parent = this.parent || this; + var name = parent === this ? '*' : this._name; + parent.on('command:' + name, listener); + if (this._alias) parent.on('command:' + this._alias, listener); + return this; +}; + +/** + * Define option with `flags`, `description` and optional + * coercion `fn`. + * + * The `flags` string should contain both the short and long flags, + * separated by comma, a pipe or space. The following are all valid + * all will output this way when `--help` is used. + * + * "-p, --pepper" + * "-p|--pepper" + * "-p --pepper" + * + * Examples: + * + * // simple boolean defaulting to false + * program.option('-p, --pepper', 'add pepper'); + * + * --pepper + * program.pepper + * // => Boolean + * + * // simple boolean defaulting to true + * program.option('-C, --no-cheese', 'remove cheese'); + * + * program.cheese + * // => true + * + * --no-cheese + * program.cheese + * // => false + * + * // required argument + * program.option('-C, --chdir ', 'change the working directory'); + * + * --chdir /tmp + * program.chdir + * // => "/tmp" + * + * // optional argument + * program.option('-c, --cheese [type]', 'add cheese [marble]'); + * + * @param {String} flags + * @param {String} description + * @param {Function|*} [fn] or default + * @param {*} [defaultValue] + * @return {Command} for chaining + * @api public + */ + +Command.prototype.option = function(flags, description, fn, defaultValue) { + var self = this, + option = new Option(flags, description), + oname = option.name(), + name = option.attributeName(); + + // default as 3rd arg + if (typeof fn !== 'function') { + if (fn instanceof RegExp) { + var regex = fn; + fn = function(val, def) { + var m = regex.exec(val); + return m ? m[0] : def; + }; + } else { + defaultValue = fn; + fn = null; + } + } + + // preassign default value only for --no-*, [optional], or + if (!option.bool || option.optional || option.required) { + // when --no-* we make sure default is true + if (!option.bool) defaultValue = true; + // preassign only if we have a default + if (defaultValue !== undefined) { + self[name] = defaultValue; + option.defaultValue = defaultValue; + } + } + + // register the option + this.options.push(option); + + // when it's passed assign the value + // and conditionally invoke the callback + this.on('option:' + oname, function(val) { + // coercion + if (val !== null && fn) { + val = fn(val, self[name] === undefined ? defaultValue : self[name]); + } + + // unassigned or bool + if (typeof self[name] === 'boolean' || typeof self[name] === 'undefined') { + // if no value, bool true, and we have a default, then use it! + if (val == null) { + self[name] = option.bool + ? defaultValue || true + : false; + } else { + self[name] = val; + } + } else if (val !== null) { + // reassign + self[name] = val; + } + }); + + return this; +}; + +/** + * Allow unknown options on the command line. + * + * @param {Boolean} arg if `true` or omitted, no error will be thrown + * for unknown options. + * @api public + */ +Command.prototype.allowUnknownOption = function(arg) { + this._allowUnknownOption = arguments.length === 0 || arg; + return this; +}; + +/** + * Parse `argv`, settings options and invoking commands when defined. + * + * @param {Array} argv + * @return {Command} for chaining + * @api public + */ + +Command.prototype.parse = function(argv) { + // implicit help + if (this.executables) this.addImplicitHelpCommand(); + + // store raw args + this.rawArgs = argv; + + // guess name + this._name = this._name || basename(argv[1], '.js'); + + // github-style sub-commands with no sub-command + if (this.executables && argv.length < 3 && !this.defaultExecutable) { + // this user needs help + argv.push('--help'); + } + + // process argv + var parsed = this.parseOptions(this.normalize(argv.slice(2))); + var args = this.args = parsed.args; + + var result = this.parseArgs(this.args, parsed.unknown); + + // executable sub-commands + var name = result.args[0]; + + var aliasCommand = null; + // check alias of sub commands + if (name) { + aliasCommand = this.commands.filter(function(command) { + return command.alias() === name; + })[0]; + } + + if (this._execs[name] && typeof this._execs[name] !== 'function') { + return this.executeSubCommand(argv, args, parsed.unknown); + } else if (aliasCommand) { + // is alias of a subCommand + args[0] = aliasCommand._name; + return this.executeSubCommand(argv, args, parsed.unknown); + } else if (this.defaultExecutable) { + // use the default subcommand + args.unshift(this.defaultExecutable); + return this.executeSubCommand(argv, args, parsed.unknown); + } + + return result; +}; + +/** + * Execute a sub-command executable. + * + * @param {Array} argv + * @param {Array} args + * @param {Array} unknown + * @api private + */ + +Command.prototype.executeSubCommand = function(argv, args, unknown) { + args = args.concat(unknown); + + if (!args.length) this.help(); + if (args[0] === 'help' && args.length === 1) this.help(); + + // --help + if (args[0] === 'help') { + args[0] = args[1]; + args[1] = '--help'; + } + + // executable + var f = argv[1]; + // name of the subcommand, link `pm-install` + var bin = basename(f, '.js') + '-' + args[0]; + + // In case of globally installed, get the base dir where executable + // subcommand file should be located at + var baseDir, + link = fs.lstatSync(f).isSymbolicLink() ? fs.readlinkSync(f) : f; + + // when symbolink is relative path + if (link !== f && link.charAt(0) !== '/') { + link = path.join(dirname(f), link); + } + baseDir = dirname(link); + + // prefer local `./` to bin in the $PATH + var localBin = path.join(baseDir, bin); + + // whether bin file is a js script with explicit `.js` extension + var isExplicitJS = false; + if (exists(localBin + '.js')) { + bin = localBin + '.js'; + isExplicitJS = true; + } else if (exists(localBin)) { + bin = localBin; + } + + args = args.slice(1); + + var proc; + if (process.platform !== 'win32') { + if (isExplicitJS) { + args.unshift(bin); + // add executable arguments to spawn + args = (process.execArgv || []).concat(args); + + proc = spawn(process.argv[0], args, { stdio: 'inherit', customFds: [0, 1, 2] }); + } else { + proc = spawn(bin, args, { stdio: 'inherit', customFds: [0, 1, 2] }); + } + } else { + args.unshift(bin); + proc = spawn(process.execPath, args, { stdio: 'inherit' }); + } + + var signals = ['SIGUSR1', 'SIGUSR2', 'SIGTERM', 'SIGINT', 'SIGHUP']; + signals.forEach(function(signal) { + process.on(signal, function() { + if (proc.killed === false && proc.exitCode === null) { + proc.kill(signal); + } + }); + }); + proc.on('close', process.exit.bind(process)); + proc.on('error', function(err) { + if (err.code === 'ENOENT') { + console.error('\n %s(1) does not exist, try --help\n', bin); + } else if (err.code === 'EACCES') { + console.error('\n %s(1) not executable. try chmod or run with root\n', bin); + } + process.exit(1); + }); + + // Store the reference to the child process + this.runningCommand = proc; +}; + +/** + * Normalize `args`, splitting joined short flags. For example + * the arg "-abc" is equivalent to "-a -b -c". + * This also normalizes equal sign and splits "--abc=def" into "--abc def". + * + * @param {Array} args + * @return {Array} + * @api private + */ + +Command.prototype.normalize = function(args) { + var ret = [], + arg, + lastOpt, + index; + + for (var i = 0, len = args.length; i < len; ++i) { + arg = args[i]; + if (i > 0) { + lastOpt = this.optionFor(args[i - 1]); + } + + if (arg === '--') { + // Honor option terminator + ret = ret.concat(args.slice(i)); + break; + } else if (lastOpt && lastOpt.required) { + ret.push(arg); + } else if (arg.length > 1 && arg[0] === '-' && arg[1] !== '-') { + arg.slice(1).split('').forEach(function(c) { + ret.push('-' + c); + }); + } else if (/^--/.test(arg) && ~(index = arg.indexOf('='))) { + ret.push(arg.slice(0, index), arg.slice(index + 1)); + } else { + ret.push(arg); + } + } + + return ret; +}; + +/** + * Parse command `args`. + * + * When listener(s) are available those + * callbacks are invoked, otherwise the "*" + * event is emitted and those actions are invoked. + * + * @param {Array} args + * @return {Command} for chaining + * @api private + */ + +Command.prototype.parseArgs = function(args, unknown) { + var name; + + if (args.length) { + name = args[0]; + if (this.listeners('command:' + name).length) { + this.emit('command:' + args.shift(), args, unknown); + } else { + this.emit('command:*', args); + } + } else { + outputHelpIfNecessary(this, unknown); + + // If there were no args and we have unknown options, + // then they are extraneous and we need to error. + if (unknown.length > 0) { + this.unknownOption(unknown[0]); + } + } + + return this; +}; + +/** + * Return an option matching `arg` if any. + * + * @param {String} arg + * @return {Option} + * @api private + */ + +Command.prototype.optionFor = function(arg) { + for (var i = 0, len = this.options.length; i < len; ++i) { + if (this.options[i].is(arg)) { + return this.options[i]; + } + } +}; + +/** + * Parse options from `argv` returning `argv` + * void of these options. + * + * @param {Array} argv + * @return {Array} + * @api public + */ + +Command.prototype.parseOptions = function(argv) { + var args = [], + len = argv.length, + literal, + option, + arg; + + var unknownOptions = []; + + // parse options + for (var i = 0; i < len; ++i) { + arg = argv[i]; + + // literal args after -- + if (literal) { + args.push(arg); + continue; + } + + if (arg === '--') { + literal = true; + continue; + } + + // find matching Option + option = this.optionFor(arg); + + // option is defined + if (option) { + // requires arg + if (option.required) { + arg = argv[++i]; + if (arg == null) return this.optionMissingArgument(option); + this.emit('option:' + option.name(), arg); + // optional arg + } else if (option.optional) { + arg = argv[i + 1]; + if (arg == null || (arg[0] === '-' && arg !== '-')) { + arg = null; + } else { + ++i; + } + this.emit('option:' + option.name(), arg); + // bool + } else { + this.emit('option:' + option.name()); + } + continue; + } + + // looks like an option + if (arg.length > 1 && arg[0] === '-') { + unknownOptions.push(arg); + + // If the next argument looks like it might be + // an argument for this option, we pass it on. + // If it isn't, then it'll simply be ignored + if ((i + 1) < argv.length && argv[i + 1][0] !== '-') { + unknownOptions.push(argv[++i]); + } + continue; + } + + // arg + args.push(arg); + } + + return { args: args, unknown: unknownOptions }; +}; + +/** + * Return an object containing options as key-value pairs + * + * @return {Object} + * @api public + */ +Command.prototype.opts = function() { + var result = {}, + len = this.options.length; + + for (var i = 0; i < len; i++) { + var key = this.options[i].attributeName(); + result[key] = key === this._versionOptionName ? this._version : this[key]; + } + return result; +}; + +/** + * Argument `name` is missing. + * + * @param {String} name + * @api private + */ + +Command.prototype.missingArgument = function(name) { + console.error(); + console.error(" error: missing required argument `%s'", name); + console.error(); + process.exit(1); +}; + +/** + * `Option` is missing an argument, but received `flag` or nothing. + * + * @param {String} option + * @param {String} flag + * @api private + */ + +Command.prototype.optionMissingArgument = function(option, flag) { + console.error(); + if (flag) { + console.error(" error: option `%s' argument missing, got `%s'", option.flags, flag); + } else { + console.error(" error: option `%s' argument missing", option.flags); + } + console.error(); + process.exit(1); +}; + +/** + * Unknown option `flag`. + * + * @param {String} flag + * @api private + */ + +Command.prototype.unknownOption = function(flag) { + if (this._allowUnknownOption) return; + console.error(); + console.error(" error: unknown option `%s'", flag); + console.error(); + process.exit(1); +}; + +/** + * Variadic argument with `name` is not the last argument as required. + * + * @param {String} name + * @api private + */ + +Command.prototype.variadicArgNotLast = function(name) { + console.error(); + console.error(" error: variadic arguments must be last `%s'", name); + console.error(); + process.exit(1); +}; + +/** + * Set the program version to `str`. + * + * This method auto-registers the "-V, --version" flag + * which will print the version number when passed. + * + * @param {String} str + * @param {String} [flags] + * @return {Command} for chaining + * @api public + */ + +Command.prototype.version = function(str, flags) { + if (arguments.length === 0) return this._version; + this._version = str; + flags = flags || '-V, --version'; + var versionOption = new Option(flags, 'output the version number'); + this._versionOptionName = versionOption.long.substr(2) || 'version'; + this.options.push(versionOption); + this.on('option:' + this._versionOptionName, function() { + process.stdout.write(str + '\n'); + process.exit(0); + }); + return this; +}; + +/** + * Set the description to `str`. + * + * @param {String} str + * @param {Object} argsDescription + * @return {String|Command} + * @api public + */ + +Command.prototype.description = function(str, argsDescription) { + if (arguments.length === 0) return this._description; + this._description = str; + this._argsDescription = argsDescription; + return this; +}; + +/** + * Set an alias for the command + * + * @param {String} alias + * @return {String|Command} + * @api public + */ + +Command.prototype.alias = function(alias) { + var command = this; + if (this.commands.length !== 0) { + command = this.commands[this.commands.length - 1]; + } + + if (arguments.length === 0) return command._alias; + + if (alias === command._name) throw new Error('Command alias can\'t be the same as its name'); + + command._alias = alias; + return this; +}; + +/** + * Set / get the command usage `str`. + * + * @param {String} str + * @return {String|Command} + * @api public + */ + +Command.prototype.usage = function(str) { + var args = this._args.map(function(arg) { + return humanReadableArgName(arg); + }); + + var usage = '[options]' + + (this.commands.length ? ' [command]' : '') + + (this._args.length ? ' ' + args.join(' ') : ''); + + if (arguments.length === 0) return this._usage || usage; + this._usage = str; + + return this; +}; + +/** + * Get or set the name of the command + * + * @param {String} str + * @return {String|Command} + * @api public + */ + +Command.prototype.name = function(str) { + if (arguments.length === 0) return this._name; + this._name = str; + return this; +}; + +/** + * Return prepared commands. + * + * @return {Array} + * @api private + */ + +Command.prototype.prepareCommands = function() { + return this.commands.filter(function(cmd) { + return !cmd._noHelp; + }).map(function(cmd) { + var args = cmd._args.map(function(arg) { + return humanReadableArgName(arg); + }).join(' '); + + return [ + cmd._name + + (cmd._alias ? '|' + cmd._alias : '') + + (cmd.options.length ? ' [options]' : '') + + (args ? ' ' + args : ''), + cmd._description + ]; + }); +}; + +/** + * Return the largest command length. + * + * @return {Number} + * @api private + */ + +Command.prototype.largestCommandLength = function() { + var commands = this.prepareCommands(); + return commands.reduce(function(max, command) { + return Math.max(max, command[0].length); + }, 0); +}; + +/** + * Return the largest option length. + * + * @return {Number} + * @api private + */ + +Command.prototype.largestOptionLength = function() { + var options = [].slice.call(this.options); + options.push({ + flags: '-h, --help' + }); + return options.reduce(function(max, option) { + return Math.max(max, option.flags.length); + }, 0); +}; + +/** + * Return the largest arg length. + * + * @return {Number} + * @api private + */ + +Command.prototype.largestArgLength = function() { + return this._args.reduce(function(max, arg) { + return Math.max(max, arg.name.length); + }, 0); +}; + +/** + * Return the pad width. + * + * @return {Number} + * @api private + */ + +Command.prototype.padWidth = function() { + var width = this.largestOptionLength(); + if (this._argsDescription && this._args.length) { + if (this.largestArgLength() > width) { + width = this.largestArgLength(); + } + } + + if (this.commands && this.commands.length) { + if (this.largestCommandLength() > width) { + width = this.largestCommandLength(); + } + } + + return width; +}; + +/** + * Return help for options. + * + * @return {String} + * @api private + */ + +Command.prototype.optionHelp = function() { + var width = this.padWidth(); + + // Append the help information + return this.options.map(function(option) { + return pad(option.flags, width) + ' ' + option.description + + ((option.bool && option.defaultValue !== undefined) ? ' (default: ' + option.defaultValue + ')' : ''); + }).concat([pad('-h, --help', width) + ' ' + 'output usage information']) + .join('\n'); +}; + +/** + * Return command help documentation. + * + * @return {String} + * @api private + */ + +Command.prototype.commandHelp = function() { + if (!this.commands.length) return ''; + + var commands = this.prepareCommands(); + var width = this.padWidth(); + + return [ + ' Commands:', + '', + commands.map(function(cmd) { + var desc = cmd[1] ? ' ' + cmd[1] : ''; + return (desc ? pad(cmd[0], width) : cmd[0]) + desc; + }).join('\n').replace(/^/gm, ' '), + '' + ].join('\n'); +}; + +/** + * Return program help documentation. + * + * @return {String} + * @api private + */ + +Command.prototype.helpInformation = function() { + var desc = []; + if (this._description) { + desc = [ + ' ' + this._description, + '' + ]; + + var argsDescription = this._argsDescription; + if (argsDescription && this._args.length) { + var width = this.padWidth(); + desc.push(' Arguments:'); + desc.push(''); + this._args.forEach(function(arg) { + desc.push(' ' + pad(arg.name, width) + ' ' + argsDescription[arg.name]); + }); + desc.push(''); + } + } + + var cmdName = this._name; + if (this._alias) { + cmdName = cmdName + '|' + this._alias; + } + var usage = [ + '', + ' Usage: ' + cmdName + ' ' + this.usage(), + '' + ]; + + var cmds = []; + var commandHelp = this.commandHelp(); + if (commandHelp) cmds = [commandHelp]; + + var options = [ + ' Options:', + '', + '' + this.optionHelp().replace(/^/gm, ' '), + '' + ]; + + return usage + .concat(desc) + .concat(options) + .concat(cmds) + .join('\n'); +}; + +/** + * Output help information for this command + * + * @api public + */ + +Command.prototype.outputHelp = function(cb) { + if (!cb) { + cb = function(passthru) { + return passthru; + }; + } + process.stdout.write(cb(this.helpInformation())); + this.emit('--help'); +}; + +/** + * Output help information and exit. + * + * @api public + */ + +Command.prototype.help = function(cb) { + this.outputHelp(cb); + process.exit(); +}; + +/** + * Camel-case the given `flag` + * + * @param {String} flag + * @return {String} + * @api private + */ + +function camelcase(flag) { + return flag.split('-').reduce(function(str, word) { + return str + word[0].toUpperCase() + word.slice(1); + }); +} + +/** + * Pad `str` to `width`. + * + * @param {String} str + * @param {Number} width + * @return {String} + * @api private + */ + +function pad(str, width) { + var len = Math.max(0, width - str.length); + return str + Array(len + 1).join(' '); +} + +/** + * Output help information if necessary + * + * @param {Command} command to output help for + * @param {Array} array of options to search for -h or --help + * @api private + */ + +function outputHelpIfNecessary(cmd, options) { + options = options || []; + for (var i = 0; i < options.length; i++) { + if (options[i] === '--help' || options[i] === '-h') { + cmd.outputHelp(); + process.exit(0); + } + } +} + +/** + * Takes an argument an returns its human readable equivalent for help usage. + * + * @param {Object} arg + * @return {String} + * @api private + */ + +function humanReadableArgName(arg) { + var nameOutput = arg.name + (arg.variadic === true ? '...' : ''); + + return arg.required + ? '<' + nameOutput + '>' + : '[' + nameOutput + ']'; +} + +// for versions before node v0.8 when there weren't `fs.existsSync` +function exists(file) { + try { + if (fs.statSync(file).isFile()) { + return true; + } + } catch (e) { + return false; + } +} diff --git a/node_modules/commander/package.json b/node_modules/commander/package.json new file mode 100644 index 0000000..33cb19b --- /dev/null +++ b/node_modules/commander/package.json @@ -0,0 +1,69 @@ +{ + "_from": "commander@2.15.1", + "_id": "commander@2.15.1", + "_inBundle": false, + "_integrity": "sha512-VlfT9F3V0v+jr4yxPc5gg9s62/fIVWsd2Bk2iD435um1NlGMYdVCq+MjcXnhYq2icNOizHr1kK+5TI6H0Hy0ag==", + "_location": "/commander", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "commander@2.15.1", + "name": "commander", + "escapedName": "commander", + "rawSpec": "2.15.1", + "saveSpec": null, + "fetchSpec": "2.15.1" + }, + "_requiredBy": [ + "/mocha" + ], + "_resolved": "http://registry.npmjs.org/commander/-/commander-2.15.1.tgz", + "_shasum": "df46e867d0fc2aec66a34662b406a9ccafff5b0f", + "_spec": "commander@2.15.1", + "_where": "/Users/jessitron/code/jessitron/stringify-tree/node_modules/mocha", + "author": { + "name": "TJ Holowaychuk", + "email": "tj@vision-media.ca" + }, + "bugs": { + "url": "https://github.com/tj/commander.js/issues" + }, + "bundleDependencies": false, + "dependencies": {}, + "deprecated": false, + "description": "the complete solution for node.js command-line programs", + "devDependencies": { + "@types/node": "^7.0.55", + "eslint": "^3.19.0", + "should": "^11.2.1", + "sinon": "^2.4.1", + "standard": "^10.0.3", + "typescript": "^2.7.2" + }, + "files": [ + "index.js", + "typings/index.d.ts" + ], + "homepage": "https://github.com/tj/commander.js#readme", + "keywords": [ + "commander", + "command", + "option", + "parser" + ], + "license": "MIT", + "main": "index", + "name": "commander", + "repository": { + "type": "git", + "url": "git+https://github.com/tj/commander.js.git" + }, + "scripts": { + "lint": "eslint index.js", + "test": "make test && npm run test-typings", + "test-typings": "node_modules/typescript/bin/tsc -p tsconfig.json" + }, + "typings": "typings/index.d.ts", + "version": "2.15.1" +} diff --git a/node_modules/commander/typings/index.d.ts b/node_modules/commander/typings/index.d.ts new file mode 100644 index 0000000..4830767 --- /dev/null +++ b/node_modules/commander/typings/index.d.ts @@ -0,0 +1,309 @@ +// Type definitions for commander 2.11 +// Project: https://github.com/visionmedia/commander.js +// Definitions by: Alan Agius , Marcelo Dezem , vvakame , Jules Randolph +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace local { + + class Option { + flags: string; + required: boolean; + optional: boolean; + bool: boolean; + short?: string; + long: string; + description: string; + + /** + * Initialize a new `Option` with the given `flags` and `description`. + * + * @param {string} flags + * @param {string} [description] + */ + constructor(flags: string, description?: string); + } + + class Command extends NodeJS.EventEmitter { + [key: string]: any; + + args: string[]; + + /** + * Initialize a new `Command`. + * + * @param {string} [name] + */ + constructor(name?: string); + + /** + * Set the program version to `str`. + * + * This method auto-registers the "-V, --version" flag + * which will print the version number when passed. + * + * @param {string} str + * @param {string} [flags] + * @returns {Command} for chaining + */ + version(str: string, flags?: string): Command; + + /** + * Add command `name`. + * + * The `.action()` callback is invoked when the + * command `name` is specified via __ARGV__, + * and the remaining arguments are applied to the + * function for access. + * + * When the `name` is "*" an un-matched command + * will be passed as the first arg, followed by + * the rest of __ARGV__ remaining. + * + * @example + * program + * .version('0.0.1') + * .option('-C, --chdir ', 'change the working directory') + * .option('-c, --config ', 'set config path. defaults to ./deploy.conf') + * .option('-T, --no-tests', 'ignore test hook') + * + * program + * .command('setup') + * .description('run remote setup commands') + * .action(function() { + * console.log('setup'); + * }); + * + * program + * .command('exec ') + * .description('run the given remote command') + * .action(function(cmd) { + * console.log('exec "%s"', cmd); + * }); + * + * program + * .command('teardown [otherDirs...]') + * .description('run teardown commands') + * .action(function(dir, otherDirs) { + * console.log('dir "%s"', dir); + * if (otherDirs) { + * otherDirs.forEach(function (oDir) { + * console.log('dir "%s"', oDir); + * }); + * } + * }); + * + * program + * .command('*') + * .description('deploy the given env') + * .action(function(env) { + * console.log('deploying "%s"', env); + * }); + * + * program.parse(process.argv); + * + * @param {string} name + * @param {string} [desc] for git-style sub-commands + * @param {CommandOptions} [opts] command options + * @returns {Command} the new command + */ + command(name: string, desc?: string, opts?: commander.CommandOptions): Command; + + /** + * Define argument syntax for the top-level command. + * + * @param {string} desc + * @returns {Command} for chaining + */ + arguments(desc: string): Command; + + /** + * Parse expected `args`. + * + * For example `["[type]"]` becomes `[{ required: false, name: 'type' }]`. + * + * @param {string[]} args + * @returns {Command} for chaining + */ + parseExpectedArgs(args: string[]): Command; + + /** + * Register callback `fn` for the command. + * + * @example + * program + * .command('help') + * .description('display verbose help') + * .action(function() { + * // output help here + * }); + * + * @param {(...args: any[]) => void} fn + * @returns {Command} for chaining + */ + action(fn: (...args: any[]) => void): Command; + + /** + * Define option with `flags`, `description` and optional + * coercion `fn`. + * + * The `flags` string should contain both the short and long flags, + * separated by comma, a pipe or space. The following are all valid + * all will output this way when `--help` is used. + * + * "-p, --pepper" + * "-p|--pepper" + * "-p --pepper" + * + * @example + * // simple boolean defaulting to false + * program.option('-p, --pepper', 'add pepper'); + * + * --pepper + * program.pepper + * // => Boolean + * + * // simple boolean defaulting to true + * program.option('-C, --no-cheese', 'remove cheese'); + * + * program.cheese + * // => true + * + * --no-cheese + * program.cheese + * // => false + * + * // required argument + * program.option('-C, --chdir ', 'change the working directory'); + * + * --chdir /tmp + * program.chdir + * // => "/tmp" + * + * // optional argument + * program.option('-c, --cheese [type]', 'add cheese [marble]'); + * + * @param {string} flags + * @param {string} [description] + * @param {((arg1: any, arg2: any) => void) | RegExp} [fn] function or default + * @param {*} [defaultValue] + * @returns {Command} for chaining + */ + option(flags: string, description?: string, fn?: ((arg1: any, arg2: any) => void) | RegExp, defaultValue?: any): Command; + option(flags: string, description?: string, defaultValue?: any): Command; + + /** + * Allow unknown options on the command line. + * + * @param {boolean} [arg] if `true` or omitted, no error will be thrown for unknown options. + * @returns {Command} for chaining + */ + allowUnknownOption(arg?: boolean): Command; + + /** + * Parse `argv`, settings options and invoking commands when defined. + * + * @param {string[]} argv + * @returns {Command} for chaining + */ + parse(argv: string[]): Command; + + /** + * Parse options from `argv` returning `argv` void of these options. + * + * @param {string[]} argv + * @returns {ParseOptionsResult} + */ + parseOptions(argv: string[]): commander.ParseOptionsResult; + + /** + * Return an object containing options as key-value pairs + * + * @returns {{[key: string]: string}} + */ + opts(): { [key: string]: string }; + + /** + * Set the description to `str`. + * + * @param {string} str + * @return {(Command | string)} + */ + description(str: string): Command; + description(): string; + + /** + * Set an alias for the command. + * + * @param {string} alias + * @return {(Command | string)} + */ + alias(alias: string): Command; + alias(): string; + + /** + * Set or get the command usage. + * + * @param {string} str + * @return {(Command | string)} + */ + usage(str: string): Command; + usage(): string; + + /** + * Set the name of the command. + * + * @param {string} str + * @return {Command} + */ + name(str: string): Command; + + /** + * Get the name of the command. + * + * @return {string} + */ + name(): string; + + /** + * Output help information for this command. + * + * @param {(str: string) => string} [cb] + */ + outputHelp(cb?: (str: string) => string): void; + + /** Output help information and exit. + * + * @param {(str: string) => string} [cb] + */ + help(cb?: (str: string) => string): void; + } + +} + +declare namespace commander { + + type Command = local.Command + + type Option = local.Option + + interface CommandOptions { + noHelp?: boolean; + isDefault?: boolean; + } + + interface ParseOptionsResult { + args: string[]; + unknown: string[]; + } + + interface CommanderStatic extends Command { + Command: typeof local.Command; + Option: typeof local.Option; + CommandOptions: CommandOptions; + ParseOptionsResult: ParseOptionsResult; + } + +} + +declare const commander: commander.CommanderStatic; +export = commander; diff --git a/node_modules/concat-map/.travis.yml b/node_modules/concat-map/.travis.yml new file mode 100644 index 0000000..f1d0f13 --- /dev/null +++ b/node_modules/concat-map/.travis.yml @@ -0,0 +1,4 @@ +language: node_js +node_js: + - 0.4 + - 0.6 diff --git a/node_modules/concat-map/LICENSE b/node_modules/concat-map/LICENSE new file mode 100644 index 0000000..ee27ba4 --- /dev/null +++ b/node_modules/concat-map/LICENSE @@ -0,0 +1,18 @@ +This software is released under the MIT license: + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/concat-map/README.markdown b/node_modules/concat-map/README.markdown new file mode 100644 index 0000000..408f70a --- /dev/null +++ b/node_modules/concat-map/README.markdown @@ -0,0 +1,62 @@ +concat-map +========== + +Concatenative mapdashery. + +[![browser support](http://ci.testling.com/substack/node-concat-map.png)](http://ci.testling.com/substack/node-concat-map) + +[![build status](https://secure.travis-ci.org/substack/node-concat-map.png)](http://travis-ci.org/substack/node-concat-map) + +example +======= + +``` js +var concatMap = require('concat-map'); +var xs = [ 1, 2, 3, 4, 5, 6 ]; +var ys = concatMap(xs, function (x) { + return x % 2 ? [ x - 0.1, x, x + 0.1 ] : []; +}); +console.dir(ys); +``` + +*** + +``` +[ 0.9, 1, 1.1, 2.9, 3, 3.1, 4.9, 5, 5.1 ] +``` + +methods +======= + +``` js +var concatMap = require('concat-map') +``` + +concatMap(xs, fn) +----------------- + +Return an array of concatenated elements by calling `fn(x, i)` for each element +`x` and each index `i` in the array `xs`. + +When `fn(x, i)` returns an array, its result will be concatenated with the +result array. If `fn(x, i)` returns anything else, that value will be pushed +onto the end of the result array. + +install +======= + +With [npm](http://npmjs.org) do: + +``` +npm install concat-map +``` + +license +======= + +MIT + +notes +===== + +This module was written while sitting high above the ground in a tree. diff --git a/node_modules/concat-map/example/map.js b/node_modules/concat-map/example/map.js new file mode 100644 index 0000000..3365621 --- /dev/null +++ b/node_modules/concat-map/example/map.js @@ -0,0 +1,6 @@ +var concatMap = require('../'); +var xs = [ 1, 2, 3, 4, 5, 6 ]; +var ys = concatMap(xs, function (x) { + return x % 2 ? [ x - 0.1, x, x + 0.1 ] : []; +}); +console.dir(ys); diff --git a/node_modules/concat-map/index.js b/node_modules/concat-map/index.js new file mode 100644 index 0000000..b29a781 --- /dev/null +++ b/node_modules/concat-map/index.js @@ -0,0 +1,13 @@ +module.exports = function (xs, fn) { + var res = []; + for (var i = 0; i < xs.length; i++) { + var x = fn(xs[i], i); + if (isArray(x)) res.push.apply(res, x); + else res.push(x); + } + return res; +}; + +var isArray = Array.isArray || function (xs) { + return Object.prototype.toString.call(xs) === '[object Array]'; +}; diff --git a/node_modules/concat-map/package.json b/node_modules/concat-map/package.json new file mode 100644 index 0000000..9afd4d6 --- /dev/null +++ b/node_modules/concat-map/package.json @@ -0,0 +1,88 @@ +{ + "_from": "concat-map@0.0.1", + "_id": "concat-map@0.0.1", + "_inBundle": false, + "_integrity": "sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=", + "_location": "/concat-map", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "concat-map@0.0.1", + "name": "concat-map", + "escapedName": "concat-map", + "rawSpec": "0.0.1", + "saveSpec": null, + "fetchSpec": "0.0.1" + }, + "_requiredBy": [ + "/brace-expansion" + ], + "_resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", + "_shasum": "d8a96bd77fd68df7793a73036a3ba0d5405d477b", + "_spec": "concat-map@0.0.1", + "_where": "/Users/jessitron/code/jessitron/stringify-tree/node_modules/brace-expansion", + "author": { + "name": "James Halliday", + "email": "mail@substack.net", + "url": "http://substack.net" + }, + "bugs": { + "url": "https://github.com/substack/node-concat-map/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "concatenative mapdashery", + "devDependencies": { + "tape": "~2.4.0" + }, + "directories": { + "example": "example", + "test": "test" + }, + "homepage": "https://github.com/substack/node-concat-map#readme", + "keywords": [ + "concat", + "concatMap", + "map", + "functional", + "higher-order" + ], + "license": "MIT", + "main": "index.js", + "name": "concat-map", + "repository": { + "type": "git", + "url": "git://github.com/substack/node-concat-map.git" + }, + "scripts": { + "test": "tape test/*.js" + }, + "testling": { + "files": "test/*.js", + "browsers": { + "ie": [ + 6, + 7, + 8, + 9 + ], + "ff": [ + 3.5, + 10, + 15 + ], + "chrome": [ + 10, + 22 + ], + "safari": [ + 5.1 + ], + "opera": [ + 12 + ] + } + }, + "version": "0.0.1" +} diff --git a/node_modules/concat-map/test/map.js b/node_modules/concat-map/test/map.js new file mode 100644 index 0000000..fdbd702 --- /dev/null +++ b/node_modules/concat-map/test/map.js @@ -0,0 +1,39 @@ +var concatMap = require('../'); +var test = require('tape'); + +test('empty or not', function (t) { + var xs = [ 1, 2, 3, 4, 5, 6 ]; + var ixes = []; + var ys = concatMap(xs, function (x, ix) { + ixes.push(ix); + return x % 2 ? [ x - 0.1, x, x + 0.1 ] : []; + }); + t.same(ys, [ 0.9, 1, 1.1, 2.9, 3, 3.1, 4.9, 5, 5.1 ]); + t.same(ixes, [ 0, 1, 2, 3, 4, 5 ]); + t.end(); +}); + +test('always something', function (t) { + var xs = [ 'a', 'b', 'c', 'd' ]; + var ys = concatMap(xs, function (x) { + return x === 'b' ? [ 'B', 'B', 'B' ] : [ x ]; + }); + t.same(ys, [ 'a', 'B', 'B', 'B', 'c', 'd' ]); + t.end(); +}); + +test('scalars', function (t) { + var xs = [ 'a', 'b', 'c', 'd' ]; + var ys = concatMap(xs, function (x) { + return x === 'b' ? [ 'B', 'B', 'B' ] : x; + }); + t.same(ys, [ 'a', 'B', 'B', 'B', 'c', 'd' ]); + t.end(); +}); + +test('undefs', function (t) { + var xs = [ 'a', 'b', 'c', 'd' ]; + var ys = concatMap(xs, function () {}); + t.same(ys, [ undefined, undefined, undefined, undefined ]); + t.end(); +}); diff --git a/node_modules/debug/.coveralls.yml b/node_modules/debug/.coveralls.yml new file mode 100644 index 0000000..20a7068 --- /dev/null +++ b/node_modules/debug/.coveralls.yml @@ -0,0 +1 @@ +repo_token: SIAeZjKYlHK74rbcFvNHMUzjRiMpflxve diff --git a/node_modules/debug/.eslintrc b/node_modules/debug/.eslintrc new file mode 100644 index 0000000..146371e --- /dev/null +++ b/node_modules/debug/.eslintrc @@ -0,0 +1,14 @@ +{ + "env": { + "browser": true, + "node": true + }, + "globals": { + "chrome": true + }, + "rules": { + "no-console": 0, + "no-empty": [1, { "allowEmptyCatch": true }] + }, + "extends": "eslint:recommended" +} diff --git a/node_modules/debug/.npmignore b/node_modules/debug/.npmignore new file mode 100644 index 0000000..5f60eec --- /dev/null +++ b/node_modules/debug/.npmignore @@ -0,0 +1,9 @@ +support +test +examples +example +*.sock +dist +yarn.lock +coverage +bower.json diff --git a/node_modules/debug/.travis.yml b/node_modules/debug/.travis.yml new file mode 100644 index 0000000..a764300 --- /dev/null +++ b/node_modules/debug/.travis.yml @@ -0,0 +1,20 @@ +sudo: false + +language: node_js + +node_js: + - "4" + - "6" + - "8" + +install: + - make install + +script: + - make lint + - make test + +matrix: + include: + - node_js: '8' + env: BROWSER=1 diff --git a/node_modules/debug/CHANGELOG.md b/node_modules/debug/CHANGELOG.md new file mode 100644 index 0000000..820d21e --- /dev/null +++ b/node_modules/debug/CHANGELOG.md @@ -0,0 +1,395 @@ + +3.1.0 / 2017-09-26 +================== + + * Add `DEBUG_HIDE_DATE` env var (#486) + * Remove ReDoS regexp in %o formatter (#504) + * Remove "component" from package.json + * Remove `component.json` + * Ignore package-lock.json + * Examples: fix colors printout + * Fix: browser detection + * Fix: spelling mistake (#496, @EdwardBetts) + +3.0.1 / 2017-08-24 +================== + + * Fix: Disable colors in Edge and Internet Explorer (#489) + +3.0.0 / 2017-08-08 +================== + + * Breaking: Remove DEBUG_FD (#406) + * Breaking: Use `Date#toISOString()` instead to `Date#toUTCString()` when output is not a TTY (#418) + * Breaking: Make millisecond timer namespace specific and allow 'always enabled' output (#408) + * Addition: document `enabled` flag (#465) + * Addition: add 256 colors mode (#481) + * Addition: `enabled()` updates existing debug instances, add `destroy()` function (#440) + * Update: component: update "ms" to v2.0.0 + * Update: separate the Node and Browser tests in Travis-CI + * Update: refactor Readme, fixed documentation, added "Namespace Colors" section, redid screenshots + * Update: separate Node.js and web browser examples for organization + * Update: update "browserify" to v14.4.0 + * Fix: fix Readme typo (#473) + +2.6.9 / 2017-09-22 +================== + + * remove ReDoS regexp in %o formatter (#504) + +2.6.8 / 2017-05-18 +================== + + * Fix: Check for undefined on browser globals (#462, @marbemac) + +2.6.7 / 2017-05-16 +================== + + * Fix: Update ms to 2.0.0 to fix regular expression denial of service vulnerability (#458, @hubdotcom) + * Fix: Inline extend function in node implementation (#452, @dougwilson) + * Docs: Fix typo (#455, @msasad) + +2.6.5 / 2017-04-27 +================== + + * Fix: null reference check on window.documentElement.style.WebkitAppearance (#447, @thebigredgeek) + * Misc: clean up browser reference checks (#447, @thebigredgeek) + * Misc: add npm-debug.log to .gitignore (@thebigredgeek) + + +2.6.4 / 2017-04-20 +================== + + * Fix: bug that would occur if process.env.DEBUG is a non-string value. (#444, @LucianBuzzo) + * Chore: ignore bower.json in npm installations. (#437, @joaovieira) + * Misc: update "ms" to v0.7.3 (@tootallnate) + +2.6.3 / 2017-03-13 +================== + + * Fix: Electron reference to `process.env.DEBUG` (#431, @paulcbetts) + * Docs: Changelog fix (@thebigredgeek) + +2.6.2 / 2017-03-10 +================== + + * Fix: DEBUG_MAX_ARRAY_LENGTH (#420, @slavaGanzin) + * Docs: Add backers and sponsors from Open Collective (#422, @piamancini) + * Docs: Add Slackin invite badge (@tootallnate) + +2.6.1 / 2017-02-10 +================== + + * Fix: Module's `export default` syntax fix for IE8 `Expected identifier` error + * Fix: Whitelist DEBUG_FD for values 1 and 2 only (#415, @pi0) + * Fix: IE8 "Expected identifier" error (#414, @vgoma) + * Fix: Namespaces would not disable once enabled (#409, @musikov) + +2.6.0 / 2016-12-28 +================== + + * Fix: added better null pointer checks for browser useColors (@thebigredgeek) + * Improvement: removed explicit `window.debug` export (#404, @tootallnate) + * Improvement: deprecated `DEBUG_FD` environment variable (#405, @tootallnate) + +2.5.2 / 2016-12-25 +================== + + * Fix: reference error on window within webworkers (#393, @KlausTrainer) + * Docs: fixed README typo (#391, @lurch) + * Docs: added notice about v3 api discussion (@thebigredgeek) + +2.5.1 / 2016-12-20 +================== + + * Fix: babel-core compatibility + +2.5.0 / 2016-12-20 +================== + + * Fix: wrong reference in bower file (@thebigredgeek) + * Fix: webworker compatibility (@thebigredgeek) + * Fix: output formatting issue (#388, @kribblo) + * Fix: babel-loader compatibility (#383, @escwald) + * Misc: removed built asset from repo and publications (@thebigredgeek) + * Misc: moved source files to /src (#378, @yamikuronue) + * Test: added karma integration and replaced babel with browserify for browser tests (#378, @yamikuronue) + * Test: coveralls integration (#378, @yamikuronue) + * Docs: simplified language in the opening paragraph (#373, @yamikuronue) + +2.4.5 / 2016-12-17 +================== + + * Fix: `navigator` undefined in Rhino (#376, @jochenberger) + * Fix: custom log function (#379, @hsiliev) + * Improvement: bit of cleanup + linting fixes (@thebigredgeek) + * Improvement: rm non-maintainted `dist/` dir (#375, @freewil) + * Docs: simplified language in the opening paragraph. (#373, @yamikuronue) + +2.4.4 / 2016-12-14 +================== + + * Fix: work around debug being loaded in preload scripts for electron (#368, @paulcbetts) + +2.4.3 / 2016-12-14 +================== + + * Fix: navigation.userAgent error for react native (#364, @escwald) + +2.4.2 / 2016-12-14 +================== + + * Fix: browser colors (#367, @tootallnate) + * Misc: travis ci integration (@thebigredgeek) + * Misc: added linting and testing boilerplate with sanity check (@thebigredgeek) + +2.4.1 / 2016-12-13 +================== + + * Fix: typo that broke the package (#356) + +2.4.0 / 2016-12-13 +================== + + * Fix: bower.json references unbuilt src entry point (#342, @justmatt) + * Fix: revert "handle regex special characters" (@tootallnate) + * Feature: configurable util.inspect()`options for NodeJS (#327, @tootallnate) + * Feature: %O`(big O) pretty-prints objects (#322, @tootallnate) + * Improvement: allow colors in workers (#335, @botverse) + * Improvement: use same color for same namespace. (#338, @lchenay) + +2.3.3 / 2016-11-09 +================== + + * Fix: Catch `JSON.stringify()` errors (#195, Jovan Alleyne) + * Fix: Returning `localStorage` saved values (#331, Levi Thomason) + * Improvement: Don't create an empty object when no `process` (Nathan Rajlich) + +2.3.2 / 2016-11-09 +================== + + * Fix: be super-safe in index.js as well (@TooTallNate) + * Fix: should check whether process exists (Tom Newby) + +2.3.1 / 2016-11-09 +================== + + * Fix: Added electron compatibility (#324, @paulcbetts) + * Improvement: Added performance optimizations (@tootallnate) + * Readme: Corrected PowerShell environment variable example (#252, @gimre) + * Misc: Removed yarn lock file from source control (#321, @fengmk2) + +2.3.0 / 2016-11-07 +================== + + * Fix: Consistent placement of ms diff at end of output (#215, @gorangajic) + * Fix: Escaping of regex special characters in namespace strings (#250, @zacronos) + * Fix: Fixed bug causing crash on react-native (#282, @vkarpov15) + * Feature: Enabled ES6+ compatible import via default export (#212 @bucaran) + * Feature: Added %O formatter to reflect Chrome's console.log capability (#279, @oncletom) + * Package: Update "ms" to 0.7.2 (#315, @DevSide) + * Package: removed superfluous version property from bower.json (#207 @kkirsche) + * Readme: fix USE_COLORS to DEBUG_COLORS + * Readme: Doc fixes for format string sugar (#269, @mlucool) + * Readme: Updated docs for DEBUG_FD and DEBUG_COLORS environment variables (#232, @mattlyons0) + * Readme: doc fixes for PowerShell (#271 #243, @exoticknight @unreadable) + * Readme: better docs for browser support (#224, @matthewmueller) + * Tooling: Added yarn integration for development (#317, @thebigredgeek) + * Misc: Renamed History.md to CHANGELOG.md (@thebigredgeek) + * Misc: Added license file (#226 #274, @CantemoInternal @sdaitzman) + * Misc: Updated contributors (@thebigredgeek) + +2.2.0 / 2015-05-09 +================== + + * package: update "ms" to v0.7.1 (#202, @dougwilson) + * README: add logging to file example (#193, @DanielOchoa) + * README: fixed a typo (#191, @amir-s) + * browser: expose `storage` (#190, @stephenmathieson) + * Makefile: add a `distclean` target (#189, @stephenmathieson) + +2.1.3 / 2015-03-13 +================== + + * Updated stdout/stderr example (#186) + * Updated example/stdout.js to match debug current behaviour + * Renamed example/stderr.js to stdout.js + * Update Readme.md (#184) + * replace high intensity foreground color for bold (#182, #183) + +2.1.2 / 2015-03-01 +================== + + * dist: recompile + * update "ms" to v0.7.0 + * package: update "browserify" to v9.0.3 + * component: fix "ms.js" repo location + * changed bower package name + * updated documentation about using debug in a browser + * fix: security error on safari (#167, #168, @yields) + +2.1.1 / 2014-12-29 +================== + + * browser: use `typeof` to check for `console` existence + * browser: check for `console.log` truthiness (fix IE 8/9) + * browser: add support for Chrome apps + * Readme: added Windows usage remarks + * Add `bower.json` to properly support bower install + +2.1.0 / 2014-10-15 +================== + + * node: implement `DEBUG_FD` env variable support + * package: update "browserify" to v6.1.0 + * package: add "license" field to package.json (#135, @panuhorsmalahti) + +2.0.0 / 2014-09-01 +================== + + * package: update "browserify" to v5.11.0 + * node: use stderr rather than stdout for logging (#29, @stephenmathieson) + +1.0.4 / 2014-07-15 +================== + + * dist: recompile + * example: remove `console.info()` log usage + * example: add "Content-Type" UTF-8 header to browser example + * browser: place %c marker after the space character + * browser: reset the "content" color via `color: inherit` + * browser: add colors support for Firefox >= v31 + * debug: prefer an instance `log()` function over the global one (#119) + * Readme: update documentation about styled console logs for FF v31 (#116, @wryk) + +1.0.3 / 2014-07-09 +================== + + * Add support for multiple wildcards in namespaces (#122, @seegno) + * browser: fix lint + +1.0.2 / 2014-06-10 +================== + + * browser: update color palette (#113, @gscottolson) + * common: make console logging function configurable (#108, @timoxley) + * node: fix %o colors on old node <= 0.8.x + * Makefile: find node path using shell/which (#109, @timoxley) + +1.0.1 / 2014-06-06 +================== + + * browser: use `removeItem()` to clear localStorage + * browser, node: don't set DEBUG if namespaces is undefined (#107, @leedm777) + * package: add "contributors" section + * node: fix comment typo + * README: list authors + +1.0.0 / 2014-06-04 +================== + + * make ms diff be global, not be scope + * debug: ignore empty strings in enable() + * node: make DEBUG_COLORS able to disable coloring + * *: export the `colors` array + * npmignore: don't publish the `dist` dir + * Makefile: refactor to use browserify + * package: add "browserify" as a dev dependency + * Readme: add Web Inspector Colors section + * node: reset terminal color for the debug content + * node: map "%o" to `util.inspect()` + * browser: map "%j" to `JSON.stringify()` + * debug: add custom "formatters" + * debug: use "ms" module for humanizing the diff + * Readme: add "bash" syntax highlighting + * browser: add Firebug color support + * browser: add colors for WebKit browsers + * node: apply log to `console` + * rewrite: abstract common logic for Node & browsers + * add .jshintrc file + +0.8.1 / 2014-04-14 +================== + + * package: re-add the "component" section + +0.8.0 / 2014-03-30 +================== + + * add `enable()` method for nodejs. Closes #27 + * change from stderr to stdout + * remove unnecessary index.js file + +0.7.4 / 2013-11-13 +================== + + * remove "browserify" key from package.json (fixes something in browserify) + +0.7.3 / 2013-10-30 +================== + + * fix: catch localStorage security error when cookies are blocked (Chrome) + * add debug(err) support. Closes #46 + * add .browser prop to package.json. Closes #42 + +0.7.2 / 2013-02-06 +================== + + * fix package.json + * fix: Mobile Safari (private mode) is broken with debug + * fix: Use unicode to send escape character to shell instead of octal to work with strict mode javascript + +0.7.1 / 2013-02-05 +================== + + * add repository URL to package.json + * add DEBUG_COLORED to force colored output + * add browserify support + * fix component. Closes #24 + +0.7.0 / 2012-05-04 +================== + + * Added .component to package.json + * Added debug.component.js build + +0.6.0 / 2012-03-16 +================== + + * Added support for "-" prefix in DEBUG [Vinay Pulim] + * Added `.enabled` flag to the node version [TooTallNate] + +0.5.0 / 2012-02-02 +================== + + * Added: humanize diffs. Closes #8 + * Added `debug.disable()` to the CS variant + * Removed padding. Closes #10 + * Fixed: persist client-side variant again. Closes #9 + +0.4.0 / 2012-02-01 +================== + + * Added browser variant support for older browsers [TooTallNate] + * Added `debug.enable('project:*')` to browser variant [TooTallNate] + * Added padding to diff (moved it to the right) + +0.3.0 / 2012-01-26 +================== + + * Added millisecond diff when isatty, otherwise UTC string + +0.2.0 / 2012-01-22 +================== + + * Added wildcard support + +0.1.0 / 2011-12-02 +================== + + * Added: remove colors unless stderr isatty [TooTallNate] + +0.0.1 / 2010-01-03 +================== + + * Initial release diff --git a/node_modules/debug/LICENSE b/node_modules/debug/LICENSE new file mode 100644 index 0000000..658c933 --- /dev/null +++ b/node_modules/debug/LICENSE @@ -0,0 +1,19 @@ +(The MIT License) + +Copyright (c) 2014 TJ Holowaychuk + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software +and associated documentation files (the 'Software'), to deal in the Software without restriction, +including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, +and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial +portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT +LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + diff --git a/node_modules/debug/Makefile b/node_modules/debug/Makefile new file mode 100644 index 0000000..3ddd136 --- /dev/null +++ b/node_modules/debug/Makefile @@ -0,0 +1,58 @@ +# get Makefile directory name: http://stackoverflow.com/a/5982798/376773 +THIS_MAKEFILE_PATH:=$(word $(words $(MAKEFILE_LIST)),$(MAKEFILE_LIST)) +THIS_DIR:=$(shell cd $(dir $(THIS_MAKEFILE_PATH));pwd) + +# BIN directory +BIN := $(THIS_DIR)/node_modules/.bin + +# Path +PATH := node_modules/.bin:$(PATH) +SHELL := /bin/bash + +# applications +NODE ?= $(shell which node) +YARN ?= $(shell which yarn) +PKG ?= $(if $(YARN),$(YARN),$(NODE) $(shell which npm)) +BROWSERIFY ?= $(NODE) $(BIN)/browserify + +install: node_modules + +browser: dist/debug.js + +node_modules: package.json + @NODE_ENV= $(PKG) install + @touch node_modules + +dist/debug.js: src/*.js node_modules + @mkdir -p dist + @$(BROWSERIFY) \ + --standalone debug \ + . > dist/debug.js + +lint: + @eslint *.js src/*.js + +test-node: + @istanbul cover node_modules/mocha/bin/_mocha -- test/**.js + @cat ./coverage/lcov.info | ./node_modules/coveralls/bin/coveralls.js + +test-browser: + @$(MAKE) browser + @karma start --single-run + +test-all: + @concurrently \ + "make test-node" \ + "make test-browser" + +test: + @if [ "x$(BROWSER)" = "x" ]; then \ + $(MAKE) test-node; \ + else \ + $(MAKE) test-browser; \ + fi + +clean: + rimraf dist coverage + +.PHONY: browser install clean lint test test-all test-node test-browser diff --git a/node_modules/debug/README.md b/node_modules/debug/README.md new file mode 100644 index 0000000..8e754d1 --- /dev/null +++ b/node_modules/debug/README.md @@ -0,0 +1,368 @@ +# debug +[![Build Status](https://travis-ci.org/visionmedia/debug.svg?branch=master)](https://travis-ci.org/visionmedia/debug) [![Coverage Status](https://coveralls.io/repos/github/visionmedia/debug/badge.svg?branch=master)](https://coveralls.io/github/visionmedia/debug?branch=master) [![Slack](https://visionmedia-community-slackin.now.sh/badge.svg)](https://visionmedia-community-slackin.now.sh/) [![OpenCollective](https://opencollective.com/debug/backers/badge.svg)](#backers) +[![OpenCollective](https://opencollective.com/debug/sponsors/badge.svg)](#sponsors) + + + +A tiny JavaScript debugging utility modelled after Node.js core's debugging +technique. Works in Node.js and web browsers. + +## Installation + +```bash +$ npm install debug +``` + +## Usage + +`debug` exposes a function; simply pass this function the name of your module, and it will return a decorated version of `console.error` for you to pass debug statements to. This will allow you to toggle the debug output for different parts of your module as well as the module as a whole. + +Example [_app.js_](./examples/node/app.js): + +```js +var debug = require('debug')('http') + , http = require('http') + , name = 'My App'; + +// fake app + +debug('booting %o', name); + +http.createServer(function(req, res){ + debug(req.method + ' ' + req.url); + res.end('hello\n'); +}).listen(3000, function(){ + debug('listening'); +}); + +// fake worker of some kind + +require('./worker'); +``` + +Example [_worker.js_](./examples/node/worker.js): + +```js +var a = require('debug')('worker:a') + , b = require('debug')('worker:b'); + +function work() { + a('doing lots of uninteresting work'); + setTimeout(work, Math.random() * 1000); +} + +work(); + +function workb() { + b('doing some work'); + setTimeout(workb, Math.random() * 2000); +} + +workb(); +``` + +The `DEBUG` environment variable is then used to enable these based on space or +comma-delimited names. + +Here are some examples: + +screen shot 2017-08-08 at 12 53 04 pm +screen shot 2017-08-08 at 12 53 38 pm +screen shot 2017-08-08 at 12 53 25 pm + +#### Windows note + +On Windows the environment variable is set using the `set` command. + +```cmd +set DEBUG=*,-not_this +``` + +Note that PowerShell uses different syntax to set environment variables. + +```cmd +$env:DEBUG = "*,-not_this" +``` + +Then, run the program to be debugged as usual. + + +## Namespace Colors + +Every debug instance has a color generated for it based on its namespace name. +This helps when visually parsing the debug output to identify which debug instance +a debug line belongs to. + +#### Node.js + +In Node.js, colors are enabled when stderr is a TTY. You also _should_ install +the [`supports-color`](https://npmjs.org/supports-color) module alongside debug, +otherwise debug will only use a small handful of basic colors. + + + +#### Web Browser + +Colors are also enabled on "Web Inspectors" that understand the `%c` formatting +option. These are WebKit web inspectors, Firefox ([since version +31](https://hacks.mozilla.org/2014/05/editable-box-model-multiple-selection-sublime-text-keys-much-more-firefox-developer-tools-episode-31/)) +and the Firebug plugin for Firefox (any version). + + + + +## Millisecond diff + +When actively developing an application it can be useful to see when the time spent between one `debug()` call and the next. Suppose for example you invoke `debug()` before requesting a resource, and after as well, the "+NNNms" will show you how much time was spent between calls. + + + +When stdout is not a TTY, `Date#toISOString()` is used, making it more useful for logging the debug information as shown below: + + + + +## Conventions + +If you're using this in one or more of your libraries, you _should_ use the name of your library so that developers may toggle debugging as desired without guessing names. If you have more than one debuggers you _should_ prefix them with your library name and use ":" to separate features. For example "bodyParser" from Connect would then be "connect:bodyParser". If you append a "*" to the end of your name, it will always be enabled regardless of the setting of the DEBUG environment variable. You can then use it for normal output as well as debug output. + +## Wildcards + +The `*` character may be used as a wildcard. Suppose for example your library has +debuggers named "connect:bodyParser", "connect:compress", "connect:session", +instead of listing all three with +`DEBUG=connect:bodyParser,connect:compress,connect:session`, you may simply do +`DEBUG=connect:*`, or to run everything using this module simply use `DEBUG=*`. + +You can also exclude specific debuggers by prefixing them with a "-" character. +For example, `DEBUG=*,-connect:*` would include all debuggers except those +starting with "connect:". + +## Environment Variables + +When running through Node.js, you can set a few environment variables that will +change the behavior of the debug logging: + +| Name | Purpose | +|-----------|-------------------------------------------------| +| `DEBUG` | Enables/disables specific debugging namespaces. | +| `DEBUG_HIDE_DATE` | Hide date from debug output (non-TTY). | +| `DEBUG_COLORS`| Whether or not to use colors in the debug output. | +| `DEBUG_DEPTH` | Object inspection depth. | +| `DEBUG_SHOW_HIDDEN` | Shows hidden properties on inspected objects. | + + +__Note:__ The environment variables beginning with `DEBUG_` end up being +converted into an Options object that gets used with `%o`/`%O` formatters. +See the Node.js documentation for +[`util.inspect()`](https://nodejs.org/api/util.html#util_util_inspect_object_options) +for the complete list. + +## Formatters + +Debug uses [printf-style](https://wikipedia.org/wiki/Printf_format_string) formatting. +Below are the officially supported formatters: + +| Formatter | Representation | +|-----------|----------------| +| `%O` | Pretty-print an Object on multiple lines. | +| `%o` | Pretty-print an Object all on a single line. | +| `%s` | String. | +| `%d` | Number (both integer and float). | +| `%j` | JSON. Replaced with the string '[Circular]' if the argument contains circular references. | +| `%%` | Single percent sign ('%'). This does not consume an argument. | + + +### Custom formatters + +You can add custom formatters by extending the `debug.formatters` object. +For example, if you wanted to add support for rendering a Buffer as hex with +`%h`, you could do something like: + +```js +const createDebug = require('debug') +createDebug.formatters.h = (v) => { + return v.toString('hex') +} + +// …elsewhere +const debug = createDebug('foo') +debug('this is hex: %h', new Buffer('hello world')) +// foo this is hex: 68656c6c6f20776f726c6421 +0ms +``` + + +## Browser Support + +You can build a browser-ready script using [browserify](https://github.com/substack/node-browserify), +or just use the [browserify-as-a-service](https://wzrd.in/) [build](https://wzrd.in/standalone/debug@latest), +if you don't want to build it yourself. + +Debug's enable state is currently persisted by `localStorage`. +Consider the situation shown below where you have `worker:a` and `worker:b`, +and wish to debug both. You can enable this using `localStorage.debug`: + +```js +localStorage.debug = 'worker:*' +``` + +And then refresh the page. + +```js +a = debug('worker:a'); +b = debug('worker:b'); + +setInterval(function(){ + a('doing some work'); +}, 1000); + +setInterval(function(){ + b('doing some work'); +}, 1200); +``` + + +## Output streams + + By default `debug` will log to stderr, however this can be configured per-namespace by overriding the `log` method: + +Example [_stdout.js_](./examples/node/stdout.js): + +```js +var debug = require('debug'); +var error = debug('app:error'); + +// by default stderr is used +error('goes to stderr!'); + +var log = debug('app:log'); +// set this namespace to log via console.log +log.log = console.log.bind(console); // don't forget to bind to console! +log('goes to stdout'); +error('still goes to stderr!'); + +// set all output to go via console.info +// overrides all per-namespace log settings +debug.log = console.info.bind(console); +error('now goes to stdout via console.info'); +log('still goes to stdout, but via console.info now'); +``` + +## Checking whether a debug target is enabled + +After you've created a debug instance, you can determine whether or not it is +enabled by checking the `enabled` property: + +```javascript +const debug = require('debug')('http'); + +if (debug.enabled) { + // do stuff... +} +``` + +You can also manually toggle this property to force the debug instance to be +enabled or disabled. + + +## Authors + + - TJ Holowaychuk + - Nathan Rajlich + - Andrew Rhyne + +## Backers + +Support us with a monthly donation and help us continue our activities. [[Become a backer](https://opencollective.com/debug#backer)] + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +## Sponsors + +Become a sponsor and get your logo on our README on Github with a link to your site. [[Become a sponsor](https://opencollective.com/debug#sponsor)] + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +## License + +(The MIT License) + +Copyright (c) 2014-2017 TJ Holowaychuk <tj@vision-media.ca> + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/debug/karma.conf.js b/node_modules/debug/karma.conf.js new file mode 100644 index 0000000..103a82d --- /dev/null +++ b/node_modules/debug/karma.conf.js @@ -0,0 +1,70 @@ +// Karma configuration +// Generated on Fri Dec 16 2016 13:09:51 GMT+0000 (UTC) + +module.exports = function(config) { + config.set({ + + // base path that will be used to resolve all patterns (eg. files, exclude) + basePath: '', + + + // frameworks to use + // available frameworks: https://npmjs.org/browse/keyword/karma-adapter + frameworks: ['mocha', 'chai', 'sinon'], + + + // list of files / patterns to load in the browser + files: [ + 'dist/debug.js', + 'test/*spec.js' + ], + + + // list of files to exclude + exclude: [ + 'src/node.js' + ], + + + // preprocess matching files before serving them to the browser + // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor + preprocessors: { + }, + + // test results reporter to use + // possible values: 'dots', 'progress' + // available reporters: https://npmjs.org/browse/keyword/karma-reporter + reporters: ['progress'], + + + // web server port + port: 9876, + + + // enable / disable colors in the output (reporters and logs) + colors: true, + + + // level of logging + // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG + logLevel: config.LOG_INFO, + + + // enable / disable watching file and executing tests whenever any file changes + autoWatch: true, + + + // start these browsers + // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher + browsers: ['PhantomJS'], + + + // Continuous Integration mode + // if true, Karma captures browsers, runs the tests and exits + singleRun: false, + + // Concurrency level + // how many browser should be started simultaneous + concurrency: Infinity + }) +} diff --git a/node_modules/debug/node.js b/node_modules/debug/node.js new file mode 100644 index 0000000..7fc36fe --- /dev/null +++ b/node_modules/debug/node.js @@ -0,0 +1 @@ +module.exports = require('./src/node'); diff --git a/node_modules/debug/package.json b/node_modules/debug/package.json new file mode 100644 index 0000000..317eb09 --- /dev/null +++ b/node_modules/debug/package.json @@ -0,0 +1,82 @@ +{ + "_from": "debug@3.1.0", + "_id": "debug@3.1.0", + "_inBundle": false, + "_integrity": "sha512-OX8XqP7/1a9cqkxYw2yXss15f26NKWBpDXQd0/uK/KPqdQhxbPa994hnzjcE2VqQpDslf55723cKPUOGSmMY3g==", + "_location": "/debug", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "debug@3.1.0", + "name": "debug", + "escapedName": "debug", + "rawSpec": "3.1.0", + "saveSpec": null, + "fetchSpec": "3.1.0" + }, + "_requiredBy": [ + "/mocha" + ], + "_resolved": "https://registry.npmjs.org/debug/-/debug-3.1.0.tgz", + "_shasum": "5bb5a0672628b64149566ba16819e61518c67261", + "_spec": "debug@3.1.0", + "_where": "/Users/jessitron/code/jessitron/stringify-tree/node_modules/mocha", + "author": { + "name": "TJ Holowaychuk", + "email": "tj@vision-media.ca" + }, + "browser": "./src/browser.js", + "bugs": { + "url": "https://github.com/visionmedia/debug/issues" + }, + "bundleDependencies": false, + "contributors": [ + { + "name": "Nathan Rajlich", + "email": "nathan@tootallnate.net", + "url": "http://n8.io" + }, + { + "name": "Andrew Rhyne", + "email": "rhyneandrew@gmail.com" + } + ], + "dependencies": { + "ms": "2.0.0" + }, + "deprecated": false, + "description": "small debugging utility", + "devDependencies": { + "browserify": "14.4.0", + "chai": "^3.5.0", + "concurrently": "^3.1.0", + "coveralls": "^2.11.15", + "eslint": "^3.12.1", + "istanbul": "^0.4.5", + "karma": "^1.3.0", + "karma-chai": "^0.1.0", + "karma-mocha": "^1.3.0", + "karma-phantomjs-launcher": "^1.0.2", + "karma-sinon": "^1.0.5", + "mocha": "^3.2.0", + "mocha-lcov-reporter": "^1.2.0", + "rimraf": "^2.5.4", + "sinon": "^1.17.6", + "sinon-chai": "^2.8.0" + }, + "homepage": "https://github.com/visionmedia/debug#readme", + "keywords": [ + "debug", + "log", + "debugger" + ], + "license": "MIT", + "main": "./src/index.js", + "name": "debug", + "repository": { + "type": "git", + "url": "git://github.com/visionmedia/debug.git" + }, + "version": "3.1.0" +} diff --git a/node_modules/debug/src/browser.js b/node_modules/debug/src/browser.js new file mode 100644 index 0000000..f5149ff --- /dev/null +++ b/node_modules/debug/src/browser.js @@ -0,0 +1,195 @@ +/** + * This is the web browser implementation of `debug()`. + * + * Expose `debug()` as the module. + */ + +exports = module.exports = require('./debug'); +exports.log = log; +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; +exports.storage = 'undefined' != typeof chrome + && 'undefined' != typeof chrome.storage + ? chrome.storage.local + : localstorage(); + +/** + * Colors. + */ + +exports.colors = [ + '#0000CC', '#0000FF', '#0033CC', '#0033FF', '#0066CC', '#0066FF', '#0099CC', + '#0099FF', '#00CC00', '#00CC33', '#00CC66', '#00CC99', '#00CCCC', '#00CCFF', + '#3300CC', '#3300FF', '#3333CC', '#3333FF', '#3366CC', '#3366FF', '#3399CC', + '#3399FF', '#33CC00', '#33CC33', '#33CC66', '#33CC99', '#33CCCC', '#33CCFF', + '#6600CC', '#6600FF', '#6633CC', '#6633FF', '#66CC00', '#66CC33', '#9900CC', + '#9900FF', '#9933CC', '#9933FF', '#99CC00', '#99CC33', '#CC0000', '#CC0033', + '#CC0066', '#CC0099', '#CC00CC', '#CC00FF', '#CC3300', '#CC3333', '#CC3366', + '#CC3399', '#CC33CC', '#CC33FF', '#CC6600', '#CC6633', '#CC9900', '#CC9933', + '#CCCC00', '#CCCC33', '#FF0000', '#FF0033', '#FF0066', '#FF0099', '#FF00CC', + '#FF00FF', '#FF3300', '#FF3333', '#FF3366', '#FF3399', '#FF33CC', '#FF33FF', + '#FF6600', '#FF6633', '#FF9900', '#FF9933', '#FFCC00', '#FFCC33' +]; + +/** + * Currently only WebKit-based Web Inspectors, Firefox >= v31, + * and the Firebug extension (any Firefox version) are known + * to support "%c" CSS customizations. + * + * TODO: add a `localStorage` variable to explicitly enable/disable colors + */ + +function useColors() { + // NB: In an Electron preload script, document will be defined but not fully + // initialized. Since we know we're in Chrome, we'll just detect this case + // explicitly + if (typeof window !== 'undefined' && window.process && window.process.type === 'renderer') { + return true; + } + + // Internet Explorer and Edge do not support colors. + if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { + return false; + } + + // is webkit? http://stackoverflow.com/a/16459606/376773 + // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 + return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || + // is firebug? http://stackoverflow.com/a/398120/376773 + (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || + // is firefox >= v31? + // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || + // double check webkit in userAgent just in case we are in a worker + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); +} + +/** + * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. + */ + +exports.formatters.j = function(v) { + try { + return JSON.stringify(v); + } catch (err) { + return '[UnexpectedJSONParseError]: ' + err.message; + } +}; + + +/** + * Colorize log arguments if enabled. + * + * @api public + */ + +function formatArgs(args) { + var useColors = this.useColors; + + args[0] = (useColors ? '%c' : '') + + this.namespace + + (useColors ? ' %c' : ' ') + + args[0] + + (useColors ? '%c ' : ' ') + + '+' + exports.humanize(this.diff); + + if (!useColors) return; + + var c = 'color: ' + this.color; + args.splice(1, 0, c, 'color: inherit') + + // the final "%c" is somewhat tricky, because there could be other + // arguments passed either before or after the %c, so we need to + // figure out the correct index to insert the CSS into + var index = 0; + var lastC = 0; + args[0].replace(/%[a-zA-Z%]/g, function(match) { + if ('%%' === match) return; + index++; + if ('%c' === match) { + // we only are interested in the *last* %c + // (the user may have provided their own) + lastC = index; + } + }); + + args.splice(lastC, 0, c); +} + +/** + * Invokes `console.log()` when available. + * No-op when `console.log` is not a "function". + * + * @api public + */ + +function log() { + // this hackery is required for IE8/9, where + // the `console.log` function doesn't have 'apply' + return 'object' === typeof console + && console.log + && Function.prototype.apply.call(console.log, console, arguments); +} + +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ + +function save(namespaces) { + try { + if (null == namespaces) { + exports.storage.removeItem('debug'); + } else { + exports.storage.debug = namespaces; + } + } catch(e) {} +} + +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ + +function load() { + var r; + try { + r = exports.storage.debug; + } catch(e) {} + + // If debug isn't set in LS, and we're in Electron, try to load $DEBUG + if (!r && typeof process !== 'undefined' && 'env' in process) { + r = process.env.DEBUG; + } + + return r; +} + +/** + * Enable namespaces listed in `localStorage.debug` initially. + */ + +exports.enable(load()); + +/** + * Localstorage attempts to return the localstorage. + * + * This is necessary because safari throws + * when a user disables cookies/localstorage + * and you attempt to access it. + * + * @return {LocalStorage} + * @api private + */ + +function localstorage() { + try { + return window.localStorage; + } catch (e) {} +} diff --git a/node_modules/debug/src/debug.js b/node_modules/debug/src/debug.js new file mode 100644 index 0000000..77e6384 --- /dev/null +++ b/node_modules/debug/src/debug.js @@ -0,0 +1,225 @@ + +/** + * This is the common logic for both the Node.js and web browser + * implementations of `debug()`. + * + * Expose `debug()` as the module. + */ + +exports = module.exports = createDebug.debug = createDebug['default'] = createDebug; +exports.coerce = coerce; +exports.disable = disable; +exports.enable = enable; +exports.enabled = enabled; +exports.humanize = require('ms'); + +/** + * Active `debug` instances. + */ +exports.instances = []; + +/** + * The currently active debug mode names, and names to skip. + */ + +exports.names = []; +exports.skips = []; + +/** + * Map of special "%n" handling functions, for the debug "format" argument. + * + * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". + */ + +exports.formatters = {}; + +/** + * Select a color. + * @param {String} namespace + * @return {Number} + * @api private + */ + +function selectColor(namespace) { + var hash = 0, i; + + for (i in namespace) { + hash = ((hash << 5) - hash) + namespace.charCodeAt(i); + hash |= 0; // Convert to 32bit integer + } + + return exports.colors[Math.abs(hash) % exports.colors.length]; +} + +/** + * Create a debugger with the given `namespace`. + * + * @param {String} namespace + * @return {Function} + * @api public + */ + +function createDebug(namespace) { + + var prevTime; + + function debug() { + // disabled? + if (!debug.enabled) return; + + var self = debug; + + // set `diff` timestamp + var curr = +new Date(); + var ms = curr - (prevTime || curr); + self.diff = ms; + self.prev = prevTime; + self.curr = curr; + prevTime = curr; + + // turn the `arguments` into a proper Array + var args = new Array(arguments.length); + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i]; + } + + args[0] = exports.coerce(args[0]); + + if ('string' !== typeof args[0]) { + // anything else let's inspect with %O + args.unshift('%O'); + } + + // apply any `formatters` transformations + var index = 0; + args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) { + // if we encounter an escaped % then don't increase the array index + if (match === '%%') return match; + index++; + var formatter = exports.formatters[format]; + if ('function' === typeof formatter) { + var val = args[index]; + match = formatter.call(self, val); + + // now we need to remove `args[index]` since it's inlined in the `format` + args.splice(index, 1); + index--; + } + return match; + }); + + // apply env-specific formatting (colors, etc.) + exports.formatArgs.call(self, args); + + var logFn = debug.log || exports.log || console.log.bind(console); + logFn.apply(self, args); + } + + debug.namespace = namespace; + debug.enabled = exports.enabled(namespace); + debug.useColors = exports.useColors(); + debug.color = selectColor(namespace); + debug.destroy = destroy; + + // env-specific initialization logic for debug instances + if ('function' === typeof exports.init) { + exports.init(debug); + } + + exports.instances.push(debug); + + return debug; +} + +function destroy () { + var index = exports.instances.indexOf(this); + if (index !== -1) { + exports.instances.splice(index, 1); + return true; + } else { + return false; + } +} + +/** + * Enables a debug mode by namespaces. This can include modes + * separated by a colon and wildcards. + * + * @param {String} namespaces + * @api public + */ + +function enable(namespaces) { + exports.save(namespaces); + + exports.names = []; + exports.skips = []; + + var i; + var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); + var len = split.length; + + for (i = 0; i < len; i++) { + if (!split[i]) continue; // ignore empty strings + namespaces = split[i].replace(/\*/g, '.*?'); + if (namespaces[0] === '-') { + exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); + } else { + exports.names.push(new RegExp('^' + namespaces + '$')); + } + } + + for (i = 0; i < exports.instances.length; i++) { + var instance = exports.instances[i]; + instance.enabled = exports.enabled(instance.namespace); + } +} + +/** + * Disable debug output. + * + * @api public + */ + +function disable() { + exports.enable(''); +} + +/** + * Returns true if the given mode name is enabled, false otherwise. + * + * @param {String} name + * @return {Boolean} + * @api public + */ + +function enabled(name) { + if (name[name.length - 1] === '*') { + return true; + } + var i, len; + for (i = 0, len = exports.skips.length; i < len; i++) { + if (exports.skips[i].test(name)) { + return false; + } + } + for (i = 0, len = exports.names.length; i < len; i++) { + if (exports.names[i].test(name)) { + return true; + } + } + return false; +} + +/** + * Coerce `val`. + * + * @param {Mixed} val + * @return {Mixed} + * @api private + */ + +function coerce(val) { + if (val instanceof Error) return val.stack || val.message; + return val; +} diff --git a/node_modules/debug/src/index.js b/node_modules/debug/src/index.js new file mode 100644 index 0000000..cabcbcd --- /dev/null +++ b/node_modules/debug/src/index.js @@ -0,0 +1,10 @@ +/** + * Detect Electron renderer process, which is node, but we should + * treat as a browser. + */ + +if (typeof process === 'undefined' || process.type === 'renderer') { + module.exports = require('./browser.js'); +} else { + module.exports = require('./node.js'); +} diff --git a/node_modules/debug/src/node.js b/node_modules/debug/src/node.js new file mode 100644 index 0000000..d666fb9 --- /dev/null +++ b/node_modules/debug/src/node.js @@ -0,0 +1,186 @@ +/** + * Module dependencies. + */ + +var tty = require('tty'); +var util = require('util'); + +/** + * This is the Node.js implementation of `debug()`. + * + * Expose `debug()` as the module. + */ + +exports = module.exports = require('./debug'); +exports.init = init; +exports.log = log; +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; + +/** + * Colors. + */ + +exports.colors = [ 6, 2, 3, 4, 5, 1 ]; + +try { + var supportsColor = require('supports-color'); + if (supportsColor && supportsColor.level >= 2) { + exports.colors = [ + 20, 21, 26, 27, 32, 33, 38, 39, 40, 41, 42, 43, 44, 45, 56, 57, 62, 63, 68, + 69, 74, 75, 76, 77, 78, 79, 80, 81, 92, 93, 98, 99, 112, 113, 128, 129, 134, + 135, 148, 149, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, + 172, 173, 178, 179, 184, 185, 196, 197, 198, 199, 200, 201, 202, 203, 204, + 205, 206, 207, 208, 209, 214, 215, 220, 221 + ]; + } +} catch (err) { + // swallow - we only care if `supports-color` is available; it doesn't have to be. +} + +/** + * Build up the default `inspectOpts` object from the environment variables. + * + * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js + */ + +exports.inspectOpts = Object.keys(process.env).filter(function (key) { + return /^debug_/i.test(key); +}).reduce(function (obj, key) { + // camel-case + var prop = key + .substring(6) + .toLowerCase() + .replace(/_([a-z])/g, function (_, k) { return k.toUpperCase() }); + + // coerce string value into JS value + var val = process.env[key]; + if (/^(yes|on|true|enabled)$/i.test(val)) val = true; + else if (/^(no|off|false|disabled)$/i.test(val)) val = false; + else if (val === 'null') val = null; + else val = Number(val); + + obj[prop] = val; + return obj; +}, {}); + +/** + * Is stdout a TTY? Colored output is enabled when `true`. + */ + +function useColors() { + return 'colors' in exports.inspectOpts + ? Boolean(exports.inspectOpts.colors) + : tty.isatty(process.stderr.fd); +} + +/** + * Map %o to `util.inspect()`, all on a single line. + */ + +exports.formatters.o = function(v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts) + .split('\n').map(function(str) { + return str.trim() + }).join(' '); +}; + +/** + * Map %o to `util.inspect()`, allowing multiple lines if needed. + */ + +exports.formatters.O = function(v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts); +}; + +/** + * Adds ANSI color escape codes if enabled. + * + * @api public + */ + +function formatArgs(args) { + var name = this.namespace; + var useColors = this.useColors; + + if (useColors) { + var c = this.color; + var colorCode = '\u001b[3' + (c < 8 ? c : '8;5;' + c); + var prefix = ' ' + colorCode + ';1m' + name + ' ' + '\u001b[0m'; + + args[0] = prefix + args[0].split('\n').join('\n' + prefix); + args.push(colorCode + 'm+' + exports.humanize(this.diff) + '\u001b[0m'); + } else { + args[0] = getDate() + name + ' ' + args[0]; + } +} + +function getDate() { + if (exports.inspectOpts.hideDate) { + return ''; + } else { + return new Date().toISOString() + ' '; + } +} + +/** + * Invokes `util.format()` with the specified arguments and writes to stderr. + */ + +function log() { + return process.stderr.write(util.format.apply(util, arguments) + '\n'); +} + +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ + +function save(namespaces) { + if (null == namespaces) { + // If you set a process.env field to null or undefined, it gets cast to the + // string 'null' or 'undefined'. Just delete instead. + delete process.env.DEBUG; + } else { + process.env.DEBUG = namespaces; + } +} + +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ + +function load() { + return process.env.DEBUG; +} + +/** + * Init logic for `debug` instances. + * + * Create a new `inspectOpts` object in case `useColors` is set + * differently for a particular `debug` instance. + */ + +function init (debug) { + debug.inspectOpts = {}; + + var keys = Object.keys(exports.inspectOpts); + for (var i = 0; i < keys.length; i++) { + debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; + } +} + +/** + * Enable namespaces listed in `process.env.DEBUG` initially. + */ + +exports.enable(load()); diff --git a/node_modules/diff/CONTRIBUTING.md b/node_modules/diff/CONTRIBUTING.md new file mode 100644 index 0000000..96f4530 --- /dev/null +++ b/node_modules/diff/CONTRIBUTING.md @@ -0,0 +1,39 @@ +# How to Contribute + +## Pull Requests + +We also accept [pull requests][pull-request]! + +Generally we like to see pull requests that +- Maintain the existing code style +- Are focused on a single change (i.e. avoid large refactoring or style adjustments in untouched code if not the primary goal of the pull request) +- Have [good commit messages](http://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html) +- Have tests +- Don't decrease the current code coverage (see coverage/lcov-report/index.html) + +## Building + +``` +npm install +npm test +```` + +The `npm test -- dev` implements watching for tests within Node and `karma start` may be used for manual testing in browsers. + +If you notice any problems, please report them to the GitHub issue tracker at +[http://github.com/kpdecker/jsdiff/issues](http://github.com/kpdecker/jsdiff/issues). + +## Releasing + +JsDiff utilizes the [release yeoman generator][generator-release] to perform most release tasks. + +A full release may be completed with the following: + +``` +yo release +npm publish +yo release:publish components jsdiff dist/components/ +``` + +[generator-release]: https://github.com/walmartlabs/generator-release +[pull-request]: https://github.com/kpdecker/jsdiff/pull/new/master diff --git a/node_modules/diff/LICENSE b/node_modules/diff/LICENSE new file mode 100644 index 0000000..4e7146e --- /dev/null +++ b/node_modules/diff/LICENSE @@ -0,0 +1,31 @@ +Software License Agreement (BSD License) + +Copyright (c) 2009-2015, Kevin Decker + +All rights reserved. + +Redistribution and use of this software in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above + copyright notice, this list of conditions and the + following disclaimer. + +* Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the + following disclaimer in the documentation and/or other + materials provided with the distribution. + +* Neither the name of Kevin Decker nor the names of its + contributors may be used to endorse or promote products + derived from this software without specific prior + written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. \ No newline at end of file diff --git a/node_modules/diff/README.md b/node_modules/diff/README.md new file mode 100644 index 0000000..5747fe3 --- /dev/null +++ b/node_modules/diff/README.md @@ -0,0 +1,211 @@ +# jsdiff + +[![Build Status](https://secure.travis-ci.org/kpdecker/jsdiff.svg)](http://travis-ci.org/kpdecker/jsdiff) +[![Sauce Test Status](https://saucelabs.com/buildstatus/jsdiff)](https://saucelabs.com/u/jsdiff) + +A javascript text differencing implementation. + +Based on the algorithm proposed in +["An O(ND) Difference Algorithm and its Variations" (Myers, 1986)](http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.4.6927). + +## Installation +```bash +npm install diff --save +``` +or +```bash +bower install jsdiff --save +``` + +## API + +* `JsDiff.diffChars(oldStr, newStr[, options])` - diffs two blocks of text, comparing character by character. + + Returns a list of change objects (See below). + + Options + * `ignoreCase`: `true` to ignore casing difference. Defaults to `false`. + +* `JsDiff.diffWords(oldStr, newStr[, options])` - diffs two blocks of text, comparing word by word, ignoring whitespace. + + Returns a list of change objects (See below). + + Options + * `ignoreCase`: Same as in `diffChars`. + +* `JsDiff.diffWordsWithSpace(oldStr, newStr[, options])` - diffs two blocks of text, comparing word by word, treating whitespace as significant. + + Returns a list of change objects (See below). + +* `JsDiff.diffLines(oldStr, newStr[, options])` - diffs two blocks of text, comparing line by line. + + Options + * `ignoreWhitespace`: `true` to ignore leading and trailing whitespace. This is the same as `diffTrimmedLines` + * `newlineIsToken`: `true` to treat newline characters as separate tokens. This allows for changes to the newline structure to occur independently of the line content and to be treated as such. In general this is the more human friendly form of `diffLines` and `diffLines` is better suited for patches and other computer friendly output. + + Returns a list of change objects (See below). + +* `JsDiff.diffTrimmedLines(oldStr, newStr[, options])` - diffs two blocks of text, comparing line by line, ignoring leading and trailing whitespace. + + Returns a list of change objects (See below). + +* `JsDiff.diffSentences(oldStr, newStr[, options])` - diffs two blocks of text, comparing sentence by sentence. + + Returns a list of change objects (See below). + +* `JsDiff.diffCss(oldStr, newStr[, options])` - diffs two blocks of text, comparing CSS tokens. + + Returns a list of change objects (See below). + +* `JsDiff.diffJson(oldObj, newObj[, options])` - diffs two JSON objects, comparing the fields defined on each. The order of fields, etc does not matter in this comparison. + + Returns a list of change objects (See below). + +* `JsDiff.diffArrays(oldArr, newArr[, options])` - diffs two arrays, comparing each item for strict equality (===). + + Options + * `comparator`: `function(left, right)` for custom equality checks + + Returns a list of change objects (See below). + +* `JsDiff.createTwoFilesPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader)` - creates a unified diff patch. + + Parameters: + * `oldFileName` : String to be output in the filename section of the patch for the removals + * `newFileName` : String to be output in the filename section of the patch for the additions + * `oldStr` : Original string value + * `newStr` : New string value + * `oldHeader` : Additional information to include in the old file header + * `newHeader` : Additional information to include in the new file header + * `options` : An object with options. Currently, only `context` is supported and describes how many lines of context should be included. + +* `JsDiff.createPatch(fileName, oldStr, newStr, oldHeader, newHeader)` - creates a unified diff patch. + + Just like JsDiff.createTwoFilesPatch, but with oldFileName being equal to newFileName. + + +* `JsDiff.structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options)` - returns an object with an array of hunk objects. + + This method is similar to createTwoFilesPatch, but returns a data structure + suitable for further processing. Parameters are the same as createTwoFilesPatch. The data structure returned may look like this: + + ```js + { + oldFileName: 'oldfile', newFileName: 'newfile', + oldHeader: 'header1', newHeader: 'header2', + hunks: [{ + oldStart: 1, oldLines: 3, newStart: 1, newLines: 3, + lines: [' line2', ' line3', '-line4', '+line5', '\\ No newline at end of file'], + }] + } + ``` + +* `JsDiff.applyPatch(source, patch[, options])` - applies a unified diff patch. + + Return a string containing new version of provided data. `patch` may be a string diff or the output from the `parsePatch` or `structuredPatch` methods. + + The optional `options` object may have the following keys: + + - `fuzzFactor`: Number of lines that are allowed to differ before rejecting a patch. Defaults to 0. + - `compareLine(lineNumber, line, operation, patchContent)`: Callback used to compare to given lines to determine if they should be considered equal when patching. Defaults to strict equality but may be overridden to provide fuzzier comparison. Should return false if the lines should be rejected. + +* `JsDiff.applyPatches(patch, options)` - applies one or more patches. + + This method will iterate over the contents of the patch and apply to data provided through callbacks. The general flow for each patch index is: + + - `options.loadFile(index, callback)` is called. The caller should then load the contents of the file and then pass that to the `callback(err, data)` callback. Passing an `err` will terminate further patch execution. + - `options.patched(index, content, callback)` is called once the patch has been applied. `content` will be the return value from `applyPatch`. When it's ready, the caller should call `callback(err)` callback. Passing an `err` will terminate further patch execution. + + Once all patches have been applied or an error occurs, the `options.complete(err)` callback is made. + +* `JsDiff.parsePatch(diffStr)` - Parses a patch into structured data + + Return a JSON object representation of the a patch, suitable for use with the `applyPatch` method. This parses to the same structure returned by `JsDiff.structuredPatch`. + +* `convertChangesToXML(changes)` - converts a list of changes to a serialized XML format + + +All methods above which accept the optional `callback` method will run in sync mode when that parameter is omitted and in async mode when supplied. This allows for larger diffs without blocking the event loop. This may be passed either directly as the final parameter or as the `callback` field in the `options` object. + +### Change Objects +Many of the methods above return change objects. These objects consist of the following fields: + +* `value`: Text content +* `added`: True if the value was inserted into the new string +* `removed`: True of the value was removed from the old string + +Note that some cases may omit a particular flag field. Comparison on the flag fields should always be done in a truthy or falsy manner. + +## Examples + +Basic example in Node + +```js +require('colors'); +var jsdiff = require('diff'); + +var one = 'beep boop'; +var other = 'beep boob blah'; + +var diff = jsdiff.diffChars(one, other); + +diff.forEach(function(part){ + // green for additions, red for deletions + // grey for common parts + var color = part.added ? 'green' : + part.removed ? 'red' : 'grey'; + process.stderr.write(part.value[color]); +}); + +console.log(); +``` +Running the above program should yield + +Node Example + +Basic example in a web page + +```html +

+
+
+```
+
+Open the above .html file in a browser and you should see
+
+Node Example
+
+**[Full online demo](http://kpdecker.github.com/jsdiff)**
+
+## Compatibility
+
+[![Sauce Test Status](https://saucelabs.com/browser-matrix/jsdiff.svg)](https://saucelabs.com/u/jsdiff)
+
+jsdiff supports all ES3 environments with some known issues on IE8 and below. Under these browsers some diff algorithms such as word diff and others may fail due to lack of support for capturing groups in the `split` operation.
+
+## License
+
+See [LICENSE](https://github.com/kpdecker/jsdiff/blob/master/LICENSE).
diff --git a/node_modules/diff/dist/diff.js b/node_modules/diff/dist/diff.js
new file mode 100644
index 0000000..0b824f1
--- /dev/null
+++ b/node_modules/diff/dist/diff.js
@@ -0,0 +1,1843 @@
+/*!
+
+ diff v3.5.0
+
+Software License Agreement (BSD License)
+
+Copyright (c) 2009-2015, Kevin Decker 
+
+All rights reserved.
+
+Redistribution and use of this software in source and binary forms, with or without modification,
+are permitted provided that the following conditions are met:
+
+* Redistributions of source code must retain the above
+  copyright notice, this list of conditions and the
+  following disclaimer.
+
+* Redistributions in binary form must reproduce the above
+  copyright notice, this list of conditions and the
+  following disclaimer in the documentation and/or other
+  materials provided with the distribution.
+
+* Neither the name of Kevin Decker nor the names of its
+  contributors may be used to endorse or promote products
+  derived from this software without specific prior
+  written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
+IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
+FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
+CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
+IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
+OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+@license
+*/
+(function webpackUniversalModuleDefinition(root, factory) {
+	if(typeof exports === 'object' && typeof module === 'object')
+		module.exports = factory();
+	else if(typeof define === 'function' && define.amd)
+		define([], factory);
+	else if(typeof exports === 'object')
+		exports["JsDiff"] = factory();
+	else
+		root["JsDiff"] = factory();
+})(this, function() {
+return /******/ (function(modules) { // webpackBootstrap
+/******/ 	// The module cache
+/******/ 	var installedModules = {};
+
+/******/ 	// The require function
+/******/ 	function __webpack_require__(moduleId) {
+
+/******/ 		// Check if module is in cache
+/******/ 		if(installedModules[moduleId])
+/******/ 			return installedModules[moduleId].exports;
+
+/******/ 		// Create a new module (and put it into the cache)
+/******/ 		var module = installedModules[moduleId] = {
+/******/ 			exports: {},
+/******/ 			id: moduleId,
+/******/ 			loaded: false
+/******/ 		};
+
+/******/ 		// Execute the module function
+/******/ 		modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
+
+/******/ 		// Flag the module as loaded
+/******/ 		module.loaded = true;
+
+/******/ 		// Return the exports of the module
+/******/ 		return module.exports;
+/******/ 	}
+
+
+/******/ 	// expose the modules object (__webpack_modules__)
+/******/ 	__webpack_require__.m = modules;
+
+/******/ 	// expose the module cache
+/******/ 	__webpack_require__.c = installedModules;
+
+/******/ 	// __webpack_public_path__
+/******/ 	__webpack_require__.p = "";
+
+/******/ 	// Load entry module and return exports
+/******/ 	return __webpack_require__(0);
+/******/ })
+/************************************************************************/
+/******/ ([
+/* 0 */
+/***/ (function(module, exports, __webpack_require__) {
+
+	/*istanbul ignore start*/'use strict';
+
+	exports.__esModule = true;
+	exports.canonicalize = exports.convertChangesToXML = exports.convertChangesToDMP = exports.merge = exports.parsePatch = exports.applyPatches = exports.applyPatch = exports.createPatch = exports.createTwoFilesPatch = exports.structuredPatch = exports.diffArrays = exports.diffJson = exports.diffCss = exports.diffSentences = exports.diffTrimmedLines = exports.diffLines = exports.diffWordsWithSpace = exports.diffWords = exports.diffChars = exports.Diff = undefined;
+
+	/*istanbul ignore end*/var /*istanbul ignore start*/_base = __webpack_require__(1) /*istanbul ignore end*/;
+
+	/*istanbul ignore start*/var _base2 = _interopRequireDefault(_base);
+
+	/*istanbul ignore end*/var /*istanbul ignore start*/_character = __webpack_require__(2) /*istanbul ignore end*/;
+
+	var /*istanbul ignore start*/_word = __webpack_require__(3) /*istanbul ignore end*/;
+
+	var /*istanbul ignore start*/_line = __webpack_require__(5) /*istanbul ignore end*/;
+
+	var /*istanbul ignore start*/_sentence = __webpack_require__(6) /*istanbul ignore end*/;
+
+	var /*istanbul ignore start*/_css = __webpack_require__(7) /*istanbul ignore end*/;
+
+	var /*istanbul ignore start*/_json = __webpack_require__(8) /*istanbul ignore end*/;
+
+	var /*istanbul ignore start*/_array = __webpack_require__(9) /*istanbul ignore end*/;
+
+	var /*istanbul ignore start*/_apply = __webpack_require__(10) /*istanbul ignore end*/;
+
+	var /*istanbul ignore start*/_parse = __webpack_require__(11) /*istanbul ignore end*/;
+
+	var /*istanbul ignore start*/_merge = __webpack_require__(13) /*istanbul ignore end*/;
+
+	var /*istanbul ignore start*/_create = __webpack_require__(14) /*istanbul ignore end*/;
+
+	var /*istanbul ignore start*/_dmp = __webpack_require__(16) /*istanbul ignore end*/;
+
+	var /*istanbul ignore start*/_xml = __webpack_require__(17) /*istanbul ignore end*/;
+
+	/*istanbul ignore start*/function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
+
+	/* See LICENSE file for terms of use */
+
+	/*
+	 * Text diff implementation.
+	 *
+	 * This library supports the following APIS:
+	 * JsDiff.diffChars: Character by character diff
+	 * JsDiff.diffWords: Word (as defined by \b regex) diff which ignores whitespace
+	 * JsDiff.diffLines: Line based diff
+	 *
+	 * JsDiff.diffCss: Diff targeted at CSS content
+	 *
+	 * These methods are based on the implementation proposed in
+	 * "An O(ND) Difference Algorithm and its Variations" (Myers, 1986).
+	 * http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.4.6927
+	 */
+	exports. /*istanbul ignore end*/Diff = _base2['default'];
+	/*istanbul ignore start*/exports. /*istanbul ignore end*/diffChars = _character.diffChars;
+	/*istanbul ignore start*/exports. /*istanbul ignore end*/diffWords = _word.diffWords;
+	/*istanbul ignore start*/exports. /*istanbul ignore end*/diffWordsWithSpace = _word.diffWordsWithSpace;
+	/*istanbul ignore start*/exports. /*istanbul ignore end*/diffLines = _line.diffLines;
+	/*istanbul ignore start*/exports. /*istanbul ignore end*/diffTrimmedLines = _line.diffTrimmedLines;
+	/*istanbul ignore start*/exports. /*istanbul ignore end*/diffSentences = _sentence.diffSentences;
+	/*istanbul ignore start*/exports. /*istanbul ignore end*/diffCss = _css.diffCss;
+	/*istanbul ignore start*/exports. /*istanbul ignore end*/diffJson = _json.diffJson;
+	/*istanbul ignore start*/exports. /*istanbul ignore end*/diffArrays = _array.diffArrays;
+	/*istanbul ignore start*/exports. /*istanbul ignore end*/structuredPatch = _create.structuredPatch;
+	/*istanbul ignore start*/exports. /*istanbul ignore end*/createTwoFilesPatch = _create.createTwoFilesPatch;
+	/*istanbul ignore start*/exports. /*istanbul ignore end*/createPatch = _create.createPatch;
+	/*istanbul ignore start*/exports. /*istanbul ignore end*/applyPatch = _apply.applyPatch;
+	/*istanbul ignore start*/exports. /*istanbul ignore end*/applyPatches = _apply.applyPatches;
+	/*istanbul ignore start*/exports. /*istanbul ignore end*/parsePatch = _parse.parsePatch;
+	/*istanbul ignore start*/exports. /*istanbul ignore end*/merge = _merge.merge;
+	/*istanbul ignore start*/exports. /*istanbul ignore end*/convertChangesToDMP = _dmp.convertChangesToDMP;
+	/*istanbul ignore start*/exports. /*istanbul ignore end*/convertChangesToXML = _xml.convertChangesToXML;
+	/*istanbul ignore start*/exports. /*istanbul ignore end*/canonicalize = _json.canonicalize;
+	//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uL3NyYy9pbmRleC5qcyJdLCJuYW1lcyI6WyJEaWZmIiwiZGlmZkNoYXJzIiwiZGlmZldvcmRzIiwiZGlmZldvcmRzV2l0aFNwYWNlIiwiZGlmZkxpbmVzIiwiZGlmZlRyaW1tZWRMaW5lcyIsImRpZmZTZW50ZW5jZXMiLCJkaWZmQ3NzIiwiZGlmZkpzb24iLCJkaWZmQXJyYXlzIiwic3RydWN0dXJlZFBhdGNoIiwiY3JlYXRlVHdvRmlsZXNQYXRjaCIsImNyZWF0ZVBhdGNoIiwiYXBwbHlQYXRjaCIsImFwcGx5UGF0Y2hlcyIsInBhcnNlUGF0Y2giLCJtZXJnZSIsImNvbnZlcnRDaGFuZ2VzVG9ETVAiLCJjb252ZXJ0Q2hhbmdlc1RvWE1MIiwiY2Fub25pY2FsaXplIl0sIm1hcHBpbmdzIjoiOzs7Ozt1QkFnQkE7Ozs7dUJBQ0E7O0FBQ0E7O0FBQ0E7O0FBQ0E7O0FBRUE7O0FBQ0E7O0FBRUE7O0FBRUE7O0FBQ0E7O0FBQ0E7O0FBQ0E7O0FBRUE7O0FBQ0E7Ozs7QUFqQ0E7O0FBRUE7Ozs7Ozs7Ozs7Ozs7O2dDQWtDRUEsSTt5REFFQUMsUzt5REFDQUMsUzt5REFDQUMsa0I7eURBQ0FDLFM7eURBQ0FDLGdCO3lEQUNBQyxhO3lEQUVBQyxPO3lEQUNBQyxRO3lEQUVBQyxVO3lEQUVBQyxlO3lEQUNBQyxtQjt5REFDQUMsVzt5REFDQUMsVTt5REFDQUMsWTt5REFDQUMsVTt5REFDQUMsSzt5REFDQUMsbUI7eURBQ0FDLG1CO3lEQUNBQyxZIiwiZmlsZSI6ImluZGV4LmpzIiwic291cmNlc0NvbnRlbnQiOlsiLyogU2VlIExJQ0VOU0UgZmlsZSBmb3IgdGVybXMgb2YgdXNlICovXG5cbi8qXG4gKiBUZXh0IGRpZmYgaW1wbGVtZW50YXRpb24uXG4gKlxuICogVGhpcyBsaWJyYXJ5IHN1cHBvcnRzIHRoZSBmb2xsb3dpbmcgQVBJUzpcbiAqIEpzRGlmZi5kaWZmQ2hhcnM6IENoYXJhY3RlciBieSBjaGFyYWN0ZXIgZGlmZlxuICogSnNEaWZmLmRpZmZXb3JkczogV29yZCAoYXMgZGVmaW5lZCBieSBcXGIgcmVnZXgpIGRpZmYgd2hpY2ggaWdub3JlcyB3aGl0ZXNwYWNlXG4gKiBKc0RpZmYuZGlmZkxpbmVzOiBMaW5lIGJhc2VkIGRpZmZcbiAqXG4gKiBKc0RpZmYuZGlmZkNzczogRGlmZiB0YXJnZXRlZCBhdCBDU1MgY29udGVudFxuICpcbiAqIFRoZXNlIG1ldGhvZHMgYXJlIGJhc2VkIG9uIHRoZSBpbXBsZW1lbnRhdGlvbiBwcm9wb3NlZCBpblxuICogXCJBbiBPKE5EKSBEaWZmZXJlbmNlIEFsZ29yaXRobSBhbmQgaXRzIFZhcmlhdGlvbnNcIiAoTXllcnMsIDE5ODYpLlxuICogaHR0cDovL2NpdGVzZWVyeC5pc3QucHN1LmVkdS92aWV3ZG9jL3N1bW1hcnk/ZG9pPTEwLjEuMS40LjY5MjdcbiAqL1xuaW1wb3J0IERpZmYgZnJvbSAnLi9kaWZmL2Jhc2UnO1xuaW1wb3J0IHtkaWZmQ2hhcnN9IGZyb20gJy4vZGlmZi9jaGFyYWN0ZXInO1xuaW1wb3J0IHtkaWZmV29yZHMsIGRpZmZXb3Jkc1dpdGhTcGFjZX0gZnJvbSAnLi9kaWZmL3dvcmQnO1xuaW1wb3J0IHtkaWZmTGluZXMsIGRpZmZUcmltbWVkTGluZXN9IGZyb20gJy4vZGlmZi9saW5lJztcbmltcG9ydCB7ZGlmZlNlbnRlbmNlc30gZnJvbSAnLi9kaWZmL3NlbnRlbmNlJztcblxuaW1wb3J0IHtkaWZmQ3NzfSBmcm9tICcuL2RpZmYvY3NzJztcbmltcG9ydCB7ZGlmZkpzb24sIGNhbm9uaWNhbGl6ZX0gZnJvbSAnLi9kaWZmL2pzb24nO1xuXG5pbXBvcnQge2RpZmZBcnJheXN9IGZyb20gJy4vZGlmZi9hcnJheSc7XG5cbmltcG9ydCB7YXBwbHlQYXRjaCwgYXBwbHlQYXRjaGVzfSBmcm9tICcuL3BhdGNoL2FwcGx5JztcbmltcG9ydCB7cGFyc2VQYXRjaH0gZnJvbSAnLi9wYXRjaC9wYXJzZSc7XG5pbXBvcnQge21lcmdlfSBmcm9tICcuL3BhdGNoL21lcmdlJztcbmltcG9ydCB7c3RydWN0dXJlZFBhdGNoLCBjcmVhdGVUd29GaWxlc1BhdGNoLCBjcmVhdGVQYXRjaH0gZnJvbSAnLi9wYXRjaC9jcmVhdGUnO1xuXG5pbXBvcnQge2NvbnZlcnRDaGFuZ2VzVG9ETVB9IGZyb20gJy4vY29udmVydC9kbXAnO1xuaW1wb3J0IHtjb252ZXJ0Q2hhbmdlc1RvWE1MfSBmcm9tICcuL2NvbnZlcnQveG1sJztcblxuZXhwb3J0IHtcbiAgRGlmZixcblxuICBkaWZmQ2hhcnMsXG4gIGRpZmZXb3JkcyxcbiAgZGlmZldvcmRzV2l0aFNwYWNlLFxuICBkaWZmTGluZXMsXG4gIGRpZmZUcmltbWVkTGluZXMsXG4gIGRpZmZTZW50ZW5jZXMsXG5cbiAgZGlmZkNzcyxcbiAgZGlmZkpzb24sXG5cbiAgZGlmZkFycmF5cyxcblxuICBzdHJ1Y3R1cmVkUGF0Y2gsXG4gIGNyZWF0ZVR3b0ZpbGVzUGF0Y2gsXG4gIGNyZWF0ZVBhdGNoLFxuICBhcHBseVBhdGNoLFxuICBhcHBseVBhdGNoZXMsXG4gIHBhcnNlUGF0Y2gsXG4gIG1lcmdlLFxuICBjb252ZXJ0Q2hhbmdlc1RvRE1QLFxuICBjb252ZXJ0Q2hhbmdlc1RvWE1MLFxuICBjYW5vbmljYWxpemVcbn07XG4iXX0=
+
+
+/***/ }),
+/* 1 */
+/***/ (function(module, exports) {
+
+	/*istanbul ignore start*/'use strict';
+
+	exports.__esModule = true;
+	exports['default'] = /*istanbul ignore end*/Diff;
+	function Diff() {}
+
+	Diff.prototype = {
+	  /*istanbul ignore start*/ /*istanbul ignore end*/diff: function diff(oldString, newString) {
+	    /*istanbul ignore start*/var /*istanbul ignore end*/options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
+
+	    var callback = options.callback;
+	    if (typeof options === 'function') {
+	      callback = options;
+	      options = {};
+	    }
+	    this.options = options;
+
+	    var self = this;
+
+	    function done(value) {
+	      if (callback) {
+	        setTimeout(function () {
+	          callback(undefined, value);
+	        }, 0);
+	        return true;
+	      } else {
+	        return value;
+	      }
+	    }
+
+	    // Allow subclasses to massage the input prior to running
+	    oldString = this.castInput(oldString);
+	    newString = this.castInput(newString);
+
+	    oldString = this.removeEmpty(this.tokenize(oldString));
+	    newString = this.removeEmpty(this.tokenize(newString));
+
+	    var newLen = newString.length,
+	        oldLen = oldString.length;
+	    var editLength = 1;
+	    var maxEditLength = newLen + oldLen;
+	    var bestPath = [{ newPos: -1, components: [] }];
+
+	    // Seed editLength = 0, i.e. the content starts with the same values
+	    var oldPos = this.extractCommon(bestPath[0], newString, oldString, 0);
+	    if (bestPath[0].newPos + 1 >= newLen && oldPos + 1 >= oldLen) {
+	      // Identity per the equality and tokenizer
+	      return done([{ value: this.join(newString), count: newString.length }]);
+	    }
+
+	    // Main worker method. checks all permutations of a given edit length for acceptance.
+	    function execEditLength() {
+	      for (var diagonalPath = -1 * editLength; diagonalPath <= editLength; diagonalPath += 2) {
+	        var basePath = /*istanbul ignore start*/void 0 /*istanbul ignore end*/;
+	        var addPath = bestPath[diagonalPath - 1],
+	            removePath = bestPath[diagonalPath + 1],
+	            _oldPos = (removePath ? removePath.newPos : 0) - diagonalPath;
+	        if (addPath) {
+	          // No one else is going to attempt to use this value, clear it
+	          bestPath[diagonalPath - 1] = undefined;
+	        }
+
+	        var canAdd = addPath && addPath.newPos + 1 < newLen,
+	            canRemove = removePath && 0 <= _oldPos && _oldPos < oldLen;
+	        if (!canAdd && !canRemove) {
+	          // If this path is a terminal then prune
+	          bestPath[diagonalPath] = undefined;
+	          continue;
+	        }
+
+	        // Select the diagonal that we want to branch from. We select the prior
+	        // path whose position in the new string is the farthest from the origin
+	        // and does not pass the bounds of the diff graph
+	        if (!canAdd || canRemove && addPath.newPos < removePath.newPos) {
+	          basePath = clonePath(removePath);
+	          self.pushComponent(basePath.components, undefined, true);
+	        } else {
+	          basePath = addPath; // No need to clone, we've pulled it from the list
+	          basePath.newPos++;
+	          self.pushComponent(basePath.components, true, undefined);
+	        }
+
+	        _oldPos = self.extractCommon(basePath, newString, oldString, diagonalPath);
+
+	        // If we have hit the end of both strings, then we are done
+	        if (basePath.newPos + 1 >= newLen && _oldPos + 1 >= oldLen) {
+	          return done(buildValues(self, basePath.components, newString, oldString, self.useLongestToken));
+	        } else {
+	          // Otherwise track this path as a potential candidate and continue.
+	          bestPath[diagonalPath] = basePath;
+	        }
+	      }
+
+	      editLength++;
+	    }
+
+	    // Performs the length of edit iteration. Is a bit fugly as this has to support the
+	    // sync and async mode which is never fun. Loops over execEditLength until a value
+	    // is produced.
+	    if (callback) {
+	      (function exec() {
+	        setTimeout(function () {
+	          // This should not happen, but we want to be safe.
+	          /* istanbul ignore next */
+	          if (editLength > maxEditLength) {
+	            return callback();
+	          }
+
+	          if (!execEditLength()) {
+	            exec();
+	          }
+	        }, 0);
+	      })();
+	    } else {
+	      while (editLength <= maxEditLength) {
+	        var ret = execEditLength();
+	        if (ret) {
+	          return ret;
+	        }
+	      }
+	    }
+	  },
+	  /*istanbul ignore start*/ /*istanbul ignore end*/pushComponent: function pushComponent(components, added, removed) {
+	    var last = components[components.length - 1];
+	    if (last && last.added === added && last.removed === removed) {
+	      // We need to clone here as the component clone operation is just
+	      // as shallow array clone
+	      components[components.length - 1] = { count: last.count + 1, added: added, removed: removed };
+	    } else {
+	      components.push({ count: 1, added: added, removed: removed });
+	    }
+	  },
+	  /*istanbul ignore start*/ /*istanbul ignore end*/extractCommon: function extractCommon(basePath, newString, oldString, diagonalPath) {
+	    var newLen = newString.length,
+	        oldLen = oldString.length,
+	        newPos = basePath.newPos,
+	        oldPos = newPos - diagonalPath,
+	        commonCount = 0;
+	    while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(newString[newPos + 1], oldString[oldPos + 1])) {
+	      newPos++;
+	      oldPos++;
+	      commonCount++;
+	    }
+
+	    if (commonCount) {
+	      basePath.components.push({ count: commonCount });
+	    }
+
+	    basePath.newPos = newPos;
+	    return oldPos;
+	  },
+	  /*istanbul ignore start*/ /*istanbul ignore end*/equals: function equals(left, right) {
+	    if (this.options.comparator) {
+	      return this.options.comparator(left, right);
+	    } else {
+	      return left === right || this.options.ignoreCase && left.toLowerCase() === right.toLowerCase();
+	    }
+	  },
+	  /*istanbul ignore start*/ /*istanbul ignore end*/removeEmpty: function removeEmpty(array) {
+	    var ret = [];
+	    for (var i = 0; i < array.length; i++) {
+	      if (array[i]) {
+	        ret.push(array[i]);
+	      }
+	    }
+	    return ret;
+	  },
+	  /*istanbul ignore start*/ /*istanbul ignore end*/castInput: function castInput(value) {
+	    return value;
+	  },
+	  /*istanbul ignore start*/ /*istanbul ignore end*/tokenize: function tokenize(value) {
+	    return value.split('');
+	  },
+	  /*istanbul ignore start*/ /*istanbul ignore end*/join: function join(chars) {
+	    return chars.join('');
+	  }
+	};
+
+	function buildValues(diff, components, newString, oldString, useLongestToken) {
+	  var componentPos = 0,
+	      componentLen = components.length,
+	      newPos = 0,
+	      oldPos = 0;
+
+	  for (; componentPos < componentLen; componentPos++) {
+	    var component = components[componentPos];
+	    if (!component.removed) {
+	      if (!component.added && useLongestToken) {
+	        var value = newString.slice(newPos, newPos + component.count);
+	        value = value.map(function (value, i) {
+	          var oldValue = oldString[oldPos + i];
+	          return oldValue.length > value.length ? oldValue : value;
+	        });
+
+	        component.value = diff.join(value);
+	      } else {
+	        component.value = diff.join(newString.slice(newPos, newPos + component.count));
+	      }
+	      newPos += component.count;
+
+	      // Common case
+	      if (!component.added) {
+	        oldPos += component.count;
+	      }
+	    } else {
+	      component.value = diff.join(oldString.slice(oldPos, oldPos + component.count));
+	      oldPos += component.count;
+
+	      // Reverse add and remove so removes are output first to match common convention
+	      // The diffing algorithm is tied to add then remove output and this is the simplest
+	      // route to get the desired output with minimal overhead.
+	      if (componentPos && components[componentPos - 1].added) {
+	        var tmp = components[componentPos - 1];
+	        components[componentPos - 1] = components[componentPos];
+	        components[componentPos] = tmp;
+	      }
+	    }
+	  }
+
+	  // Special case handle for when one terminal is ignored (i.e. whitespace).
+	  // For this case we merge the terminal into the prior string and drop the change.
+	  // This is only available for string mode.
+	  var lastComponent = components[componentLen - 1];
+	  if (componentLen > 1 && typeof lastComponent.value === 'string' && (lastComponent.added || lastComponent.removed) && diff.equals('', lastComponent.value)) {
+	    components[componentLen - 2].value += lastComponent.value;
+	    components.pop();
+	  }
+
+	  return components;
+	}
+
+	function clonePath(path) {
+	  return { newPos: path.newPos, components: path.components.slice(0) };
+	}
+	//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9kaWZmL2Jhc2UuanMiXSwibmFtZXMiOlsiRGlmZiIsInByb3RvdHlwZSIsImRpZmYiLCJvbGRTdHJpbmciLCJuZXdTdHJpbmciLCJvcHRpb25zIiwiY2FsbGJhY2siLCJzZWxmIiwiZG9uZSIsInZhbHVlIiwic2V0VGltZW91dCIsInVuZGVmaW5lZCIsImNhc3RJbnB1dCIsInJlbW92ZUVtcHR5IiwidG9rZW5pemUiLCJuZXdMZW4iLCJsZW5ndGgiLCJvbGRMZW4iLCJlZGl0TGVuZ3RoIiwibWF4RWRpdExlbmd0aCIsImJlc3RQYXRoIiwibmV3UG9zIiwiY29tcG9uZW50cyIsIm9sZFBvcyIsImV4dHJhY3RDb21tb24iLCJqb2luIiwiY291bnQiLCJleGVjRWRpdExlbmd0aCIsImRpYWdvbmFsUGF0aCIsImJhc2VQYXRoIiwiYWRkUGF0aCIsInJlbW92ZVBhdGgiLCJjYW5BZGQiLCJjYW5SZW1vdmUiLCJjbG9uZVBhdGgiLCJwdXNoQ29tcG9uZW50IiwiYnVpbGRWYWx1ZXMiLCJ1c2VMb25nZXN0VG9rZW4iLCJleGVjIiwicmV0IiwiYWRkZWQiLCJyZW1vdmVkIiwibGFzdCIsInB1c2giLCJjb21tb25Db3VudCIsImVxdWFscyIsImxlZnQiLCJyaWdodCIsImNvbXBhcmF0b3IiLCJpZ25vcmVDYXNlIiwidG9Mb3dlckNhc2UiLCJhcnJheSIsImkiLCJzcGxpdCIsImNoYXJzIiwiY29tcG9uZW50UG9zIiwiY29tcG9uZW50TGVuIiwiY29tcG9uZW50Iiwic2xpY2UiLCJtYXAiLCJvbGRWYWx1ZSIsInRtcCIsImxhc3RDb21wb25lbnQiLCJwb3AiLCJwYXRoIl0sIm1hcHBpbmdzIjoiOzs7NENBQXdCQSxJO0FBQVQsU0FBU0EsSUFBVCxHQUFnQixDQUFFOztBQUVqQ0EsS0FBS0MsU0FBTCxHQUFpQjtBQUFBLG1EQUNmQyxJQURlLGdCQUNWQyxTQURVLEVBQ0NDLFNBREQsRUFDMEI7QUFBQSx3REFBZEMsT0FBYyx1RUFBSixFQUFJOztBQUN2QyxRQUFJQyxXQUFXRCxRQUFRQyxRQUF2QjtBQUNBLFFBQUksT0FBT0QsT0FBUCxLQUFtQixVQUF2QixFQUFtQztBQUNqQ0MsaUJBQVdELE9BQVg7QUFDQUEsZ0JBQVUsRUFBVjtBQUNEO0FBQ0QsU0FBS0EsT0FBTCxHQUFlQSxPQUFmOztBQUVBLFFBQUlFLE9BQU8sSUFBWDs7QUFFQSxhQUFTQyxJQUFULENBQWNDLEtBQWQsRUFBcUI7QUFDbkIsVUFBSUgsUUFBSixFQUFjO0FBQ1pJLG1CQUFXLFlBQVc7QUFBRUosbUJBQVNLLFNBQVQsRUFBb0JGLEtBQXBCO0FBQTZCLFNBQXJELEVBQXVELENBQXZEO0FBQ0EsZUFBTyxJQUFQO0FBQ0QsT0FIRCxNQUdPO0FBQ0wsZUFBT0EsS0FBUDtBQUNEO0FBQ0Y7O0FBRUQ7QUFDQU4sZ0JBQVksS0FBS1MsU0FBTCxDQUFlVCxTQUFmLENBQVo7QUFDQUMsZ0JBQVksS0FBS1EsU0FBTCxDQUFlUixTQUFmLENBQVo7O0FBRUFELGdCQUFZLEtBQUtVLFdBQUwsQ0FBaUIsS0FBS0MsUUFBTCxDQUFjWCxTQUFkLENBQWpCLENBQVo7QUFDQUMsZ0JBQVksS0FBS1MsV0FBTCxDQUFpQixLQUFLQyxRQUFMLENBQWNWLFNBQWQsQ0FBakIsQ0FBWjs7QUFFQSxRQUFJVyxTQUFTWCxVQUFVWSxNQUF2QjtBQUFBLFFBQStCQyxTQUFTZCxVQUFVYSxNQUFsRDtBQUNBLFFBQUlFLGFBQWEsQ0FBakI7QUFDQSxRQUFJQyxnQkFBZ0JKLFNBQVNFLE1BQTdCO0FBQ0EsUUFBSUcsV0FBVyxDQUFDLEVBQUVDLFFBQVEsQ0FBQyxDQUFYLEVBQWNDLFlBQVksRUFBMUIsRUFBRCxDQUFmOztBQUVBO0FBQ0EsUUFBSUMsU0FBUyxLQUFLQyxhQUFMLENBQW1CSixTQUFTLENBQVQsQ0FBbkIsRUFBZ0NoQixTQUFoQyxFQUEyQ0QsU0FBM0MsRUFBc0QsQ0FBdEQsQ0FBYjtBQUNBLFFBQUlpQixTQUFTLENBQVQsRUFBWUMsTUFBWixHQUFxQixDQUFyQixJQUEwQk4sTUFBMUIsSUFBb0NRLFNBQVMsQ0FBVCxJQUFjTixNQUF0RCxFQUE4RDtBQUM1RDtBQUNBLGFBQU9ULEtBQUssQ0FBQyxFQUFDQyxPQUFPLEtBQUtnQixJQUFMLENBQVVyQixTQUFWLENBQVIsRUFBOEJzQixPQUFPdEIsVUFBVVksTUFBL0MsRUFBRCxDQUFMLENBQVA7QUFDRDs7QUFFRDtBQUNBLGFBQVNXLGNBQVQsR0FBMEI7QUFDeEIsV0FBSyxJQUFJQyxlQUFlLENBQUMsQ0FBRCxHQUFLVixVQUE3QixFQUF5Q1UsZ0JBQWdCVixVQUF6RCxFQUFxRVUsZ0JBQWdCLENBQXJGLEVBQXdGO0FBQ3RGLFlBQUlDLDBDQUFKO0FBQ0EsWUFBSUMsVUFBVVYsU0FBU1EsZUFBZSxDQUF4QixDQUFkO0FBQUEsWUFDSUcsYUFBYVgsU0FBU1EsZUFBZSxDQUF4QixDQURqQjtBQUFBLFlBRUlMLFVBQVMsQ0FBQ1EsYUFBYUEsV0FBV1YsTUFBeEIsR0FBaUMsQ0FBbEMsSUFBdUNPLFlBRnBEO0FBR0EsWUFBSUUsT0FBSixFQUFhO0FBQ1g7QUFDQVYsbUJBQVNRLGVBQWUsQ0FBeEIsSUFBNkJqQixTQUE3QjtBQUNEOztBQUVELFlBQUlxQixTQUFTRixXQUFXQSxRQUFRVCxNQUFSLEdBQWlCLENBQWpCLEdBQXFCTixNQUE3QztBQUFBLFlBQ0lrQixZQUFZRixjQUFjLEtBQUtSLE9BQW5CLElBQTZCQSxVQUFTTixNQUR0RDtBQUVBLFlBQUksQ0FBQ2UsTUFBRCxJQUFXLENBQUNDLFNBQWhCLEVBQTJCO0FBQ3pCO0FBQ0FiLG1CQUFTUSxZQUFULElBQXlCakIsU0FBekI7QUFDQTtBQUNEOztBQUVEO0FBQ0E7QUFDQTtBQUNBLFlBQUksQ0FBQ3FCLE1BQUQsSUFBWUMsYUFBYUgsUUFBUVQsTUFBUixHQUFpQlUsV0FBV1YsTUFBekQsRUFBa0U7QUFDaEVRLHFCQUFXSyxVQUFVSCxVQUFWLENBQVg7QUFDQXhCLGVBQUs0QixhQUFMLENBQW1CTixTQUFTUCxVQUE1QixFQUF3Q1gsU0FBeEMsRUFBbUQsSUFBbkQ7QUFDRCxTQUhELE1BR087QUFDTGtCLHFCQUFXQyxPQUFYLENBREssQ0FDaUI7QUFDdEJELG1CQUFTUixNQUFUO0FBQ0FkLGVBQUs0QixhQUFMLENBQW1CTixTQUFTUCxVQUE1QixFQUF3QyxJQUF4QyxFQUE4Q1gsU0FBOUM7QUFDRDs7QUFFRFksa0JBQVNoQixLQUFLaUIsYUFBTCxDQUFtQkssUUFBbkIsRUFBNkJ6QixTQUE3QixFQUF3Q0QsU0FBeEMsRUFBbUR5QixZQUFuRCxDQUFUOztBQUVBO0FBQ0EsWUFBSUMsU0FBU1IsTUFBVCxHQUFrQixDQUFsQixJQUF1Qk4sTUFBdkIsSUFBaUNRLFVBQVMsQ0FBVCxJQUFjTixNQUFuRCxFQUEyRDtBQUN6RCxpQkFBT1QsS0FBSzRCLFlBQVk3QixJQUFaLEVBQWtCc0IsU0FBU1AsVUFBM0IsRUFBdUNsQixTQUF2QyxFQUFrREQsU0FBbEQsRUFBNkRJLEtBQUs4QixlQUFsRSxDQUFMLENBQVA7QUFDRCxTQUZELE1BRU87QUFDTDtBQUNBakIsbUJBQVNRLFlBQVQsSUFBeUJDLFFBQXpCO0FBQ0Q7QUFDRjs7QUFFRFg7QUFDRDs7QUFFRDtBQUNBO0FBQ0E7QUFDQSxRQUFJWixRQUFKLEVBQWM7QUFDWCxnQkFBU2dDLElBQVQsR0FBZ0I7QUFDZjVCLG1CQUFXLFlBQVc7QUFDcEI7QUFDQTtBQUNBLGNBQUlRLGFBQWFDLGFBQWpCLEVBQWdDO0FBQzlCLG1CQUFPYixVQUFQO0FBQ0Q7O0FBRUQsY0FBSSxDQUFDcUIsZ0JBQUwsRUFBdUI7QUFDckJXO0FBQ0Q7QUFDRixTQVZELEVBVUcsQ0FWSDtBQVdELE9BWkEsR0FBRDtBQWFELEtBZEQsTUFjTztBQUNMLGFBQU9wQixjQUFjQyxhQUFyQixFQUFvQztBQUNsQyxZQUFJb0IsTUFBTVosZ0JBQVY7QUFDQSxZQUFJWSxHQUFKLEVBQVM7QUFDUCxpQkFBT0EsR0FBUDtBQUNEO0FBQ0Y7QUFDRjtBQUNGLEdBOUdjO0FBQUEsbURBZ0hmSixhQWhIZSx5QkFnSERiLFVBaEhDLEVBZ0hXa0IsS0FoSFgsRUFnSGtCQyxPQWhIbEIsRUFnSDJCO0FBQ3hDLFFBQUlDLE9BQU9wQixXQUFXQSxXQUFXTixNQUFYLEdBQW9CLENBQS9CLENBQVg7QUFDQSxRQUFJMEIsUUFBUUEsS0FBS0YsS0FBTCxLQUFlQSxLQUF2QixJQUFnQ0UsS0FBS0QsT0FBTCxLQUFpQkEsT0FBckQsRUFBOEQ7QUFDNUQ7QUFDQTtBQUNBbkIsaUJBQVdBLFdBQVdOLE1BQVgsR0FBb0IsQ0FBL0IsSUFBb0MsRUFBQ1UsT0FBT2dCLEtBQUtoQixLQUFMLEdBQWEsQ0FBckIsRUFBd0JjLE9BQU9BLEtBQS9CLEVBQXNDQyxTQUFTQSxPQUEvQyxFQUFwQztBQUNELEtBSkQsTUFJTztBQUNMbkIsaUJBQVdxQixJQUFYLENBQWdCLEVBQUNqQixPQUFPLENBQVIsRUFBV2MsT0FBT0EsS0FBbEIsRUFBeUJDLFNBQVNBLE9BQWxDLEVBQWhCO0FBQ0Q7QUFDRixHQXpIYztBQUFBLG1EQTBIZmpCLGFBMUhlLHlCQTBIREssUUExSEMsRUEwSFN6QixTQTFIVCxFQTBIb0JELFNBMUhwQixFQTBIK0J5QixZQTFIL0IsRUEwSDZDO0FBQzFELFFBQUliLFNBQVNYLFVBQVVZLE1BQXZCO0FBQUEsUUFDSUMsU0FBU2QsVUFBVWEsTUFEdkI7QUFBQSxRQUVJSyxTQUFTUSxTQUFTUixNQUZ0QjtBQUFBLFFBR0lFLFNBQVNGLFNBQVNPLFlBSHRCO0FBQUEsUUFLSWdCLGNBQWMsQ0FMbEI7QUFNQSxXQUFPdkIsU0FBUyxDQUFULEdBQWFOLE1BQWIsSUFBdUJRLFNBQVMsQ0FBVCxHQUFhTixNQUFwQyxJQUE4QyxLQUFLNEIsTUFBTCxDQUFZekMsVUFBVWlCLFNBQVMsQ0FBbkIsQ0FBWixFQUFtQ2xCLFVBQVVvQixTQUFTLENBQW5CLENBQW5DLENBQXJELEVBQWdIO0FBQzlHRjtBQUNBRTtBQUNBcUI7QUFDRDs7QUFFRCxRQUFJQSxXQUFKLEVBQWlCO0FBQ2ZmLGVBQVNQLFVBQVQsQ0FBb0JxQixJQUFwQixDQUF5QixFQUFDakIsT0FBT2tCLFdBQVIsRUFBekI7QUFDRDs7QUFFRGYsYUFBU1IsTUFBVCxHQUFrQkEsTUFBbEI7QUFDQSxXQUFPRSxNQUFQO0FBQ0QsR0E3SWM7QUFBQSxtREErSWZzQixNQS9JZSxrQkErSVJDLElBL0lRLEVBK0lGQyxLQS9JRSxFQStJSztBQUNsQixRQUFJLEtBQUsxQyxPQUFMLENBQWEyQyxVQUFqQixFQUE2QjtBQUMzQixhQUFPLEtBQUszQyxPQUFMLENBQWEyQyxVQUFiLENBQXdCRixJQUF4QixFQUE4QkMsS0FBOUIsQ0FBUDtBQUNELEtBRkQsTUFFTztBQUNMLGFBQU9ELFNBQVNDLEtBQVQsSUFDRCxLQUFLMUMsT0FBTCxDQUFhNEMsVUFBYixJQUEyQkgsS0FBS0ksV0FBTCxPQUF1QkgsTUFBTUcsV0FBTixFQUR4RDtBQUVEO0FBQ0YsR0F0SmM7QUFBQSxtREF1SmZyQyxXQXZKZSx1QkF1SkhzQyxLQXZKRyxFQXVKSTtBQUNqQixRQUFJWixNQUFNLEVBQVY7QUFDQSxTQUFLLElBQUlhLElBQUksQ0FBYixFQUFnQkEsSUFBSUQsTUFBTW5DLE1BQTFCLEVBQWtDb0MsR0FBbEMsRUFBdUM7QUFDckMsVUFBSUQsTUFBTUMsQ0FBTixDQUFKLEVBQWM7QUFDWmIsWUFBSUksSUFBSixDQUFTUSxNQUFNQyxDQUFOLENBQVQ7QUFDRDtBQUNGO0FBQ0QsV0FBT2IsR0FBUDtBQUNELEdBL0pjO0FBQUEsbURBZ0tmM0IsU0FoS2UscUJBZ0tMSCxLQWhLSyxFQWdLRTtBQUNmLFdBQU9BLEtBQVA7QUFDRCxHQWxLYztBQUFBLG1EQW1LZkssUUFuS2Usb0JBbUtOTCxLQW5LTSxFQW1LQztBQUNkLFdBQU9BLE1BQU00QyxLQUFOLENBQVksRUFBWixDQUFQO0FBQ0QsR0FyS2M7QUFBQSxtREFzS2Y1QixJQXRLZSxnQkFzS1Y2QixLQXRLVSxFQXNLSDtBQUNWLFdBQU9BLE1BQU03QixJQUFOLENBQVcsRUFBWCxDQUFQO0FBQ0Q7QUF4S2MsQ0FBakI7O0FBMktBLFNBQVNXLFdBQVQsQ0FBcUJsQyxJQUFyQixFQUEyQm9CLFVBQTNCLEVBQXVDbEIsU0FBdkMsRUFBa0RELFNBQWxELEVBQTZEa0MsZUFBN0QsRUFBOEU7QUFDNUUsTUFBSWtCLGVBQWUsQ0FBbkI7QUFBQSxNQUNJQyxlQUFlbEMsV0FBV04sTUFEOUI7QUFBQSxNQUVJSyxTQUFTLENBRmI7QUFBQSxNQUdJRSxTQUFTLENBSGI7O0FBS0EsU0FBT2dDLGVBQWVDLFlBQXRCLEVBQW9DRCxjQUFwQyxFQUFvRDtBQUNsRCxRQUFJRSxZQUFZbkMsV0FBV2lDLFlBQVgsQ0FBaEI7QUFDQSxRQUFJLENBQUNFLFVBQVVoQixPQUFmLEVBQXdCO0FBQ3RCLFVBQUksQ0FBQ2dCLFVBQVVqQixLQUFYLElBQW9CSCxlQUF4QixFQUF5QztBQUN2QyxZQUFJNUIsUUFBUUwsVUFBVXNELEtBQVYsQ0FBZ0JyQyxNQUFoQixFQUF3QkEsU0FBU29DLFVBQVUvQixLQUEzQyxDQUFaO0FBQ0FqQixnQkFBUUEsTUFBTWtELEdBQU4sQ0FBVSxVQUFTbEQsS0FBVCxFQUFnQjJDLENBQWhCLEVBQW1CO0FBQ25DLGNBQUlRLFdBQVd6RCxVQUFVb0IsU0FBUzZCLENBQW5CLENBQWY7QUFDQSxpQkFBT1EsU0FBUzVDLE1BQVQsR0FBa0JQLE1BQU1PLE1BQXhCLEdBQWlDNEMsUUFBakMsR0FBNENuRCxLQUFuRDtBQUNELFNBSE8sQ0FBUjs7QUFLQWdELGtCQUFVaEQsS0FBVixHQUFrQlAsS0FBS3VCLElBQUwsQ0FBVWhCLEtBQVYsQ0FBbEI7QUFDRCxPQVJELE1BUU87QUFDTGdELGtCQUFVaEQsS0FBVixHQUFrQlAsS0FBS3VCLElBQUwsQ0FBVXJCLFVBQVVzRCxLQUFWLENBQWdCckMsTUFBaEIsRUFBd0JBLFNBQVNvQyxVQUFVL0IsS0FBM0MsQ0FBVixDQUFsQjtBQUNEO0FBQ0RMLGdCQUFVb0MsVUFBVS9CLEtBQXBCOztBQUVBO0FBQ0EsVUFBSSxDQUFDK0IsVUFBVWpCLEtBQWYsRUFBc0I7QUFDcEJqQixrQkFBVWtDLFVBQVUvQixLQUFwQjtBQUNEO0FBQ0YsS0FsQkQsTUFrQk87QUFDTCtCLGdCQUFVaEQsS0FBVixHQUFrQlAsS0FBS3VCLElBQUwsQ0FBVXRCLFVBQVV1RCxLQUFWLENBQWdCbkMsTUFBaEIsRUFBd0JBLFNBQVNrQyxVQUFVL0IsS0FBM0MsQ0FBVixDQUFsQjtBQUNBSCxnQkFBVWtDLFVBQVUvQixLQUFwQjs7QUFFQTtBQUNBO0FBQ0E7QUFDQSxVQUFJNkIsZ0JBQWdCakMsV0FBV2lDLGVBQWUsQ0FBMUIsRUFBNkJmLEtBQWpELEVBQXdEO0FBQ3RELFlBQUlxQixNQUFNdkMsV0FBV2lDLGVBQWUsQ0FBMUIsQ0FBVjtBQUNBakMsbUJBQVdpQyxlQUFlLENBQTFCLElBQStCakMsV0FBV2lDLFlBQVgsQ0FBL0I7QUFDQWpDLG1CQUFXaUMsWUFBWCxJQUEyQk0sR0FBM0I7QUFDRDtBQUNGO0FBQ0Y7O0FBRUQ7QUFDQTtBQUNBO0FBQ0EsTUFBSUMsZ0JBQWdCeEMsV0FBV2tDLGVBQWUsQ0FBMUIsQ0FBcEI7QUFDQSxNQUFJQSxlQUFlLENBQWYsSUFDRyxPQUFPTSxjQUFjckQsS0FBckIsS0FBK0IsUUFEbEMsS0FFSXFELGNBQWN0QixLQUFkLElBQXVCc0IsY0FBY3JCLE9BRnpDLEtBR0d2QyxLQUFLMkMsTUFBTCxDQUFZLEVBQVosRUFBZ0JpQixjQUFjckQsS0FBOUIsQ0FIUCxFQUc2QztBQUMzQ2EsZUFBV2tDLGVBQWUsQ0FBMUIsRUFBNkIvQyxLQUE3QixJQUFzQ3FELGNBQWNyRCxLQUFwRDtBQUNBYSxlQUFXeUMsR0FBWDtBQUNEOztBQUVELFNBQU96QyxVQUFQO0FBQ0Q7O0FBRUQsU0FBU1ksU0FBVCxDQUFtQjhCLElBQW5CLEVBQXlCO0FBQ3ZCLFNBQU8sRUFBRTNDLFFBQVEyQyxLQUFLM0MsTUFBZixFQUF1QkMsWUFBWTBDLEtBQUsxQyxVQUFMLENBQWdCb0MsS0FBaEIsQ0FBc0IsQ0FBdEIsQ0FBbkMsRUFBUDtBQUNEIiwiZmlsZSI6ImJhc2UuanMiLCJzb3VyY2VzQ29udGVudCI6WyJleHBvcnQgZGVmYXVsdCBmdW5jdGlvbiBEaWZmKCkge31cblxuRGlmZi5wcm90b3R5cGUgPSB7XG4gIGRpZmYob2xkU3RyaW5nLCBuZXdTdHJpbmcsIG9wdGlvbnMgPSB7fSkge1xuICAgIGxldCBjYWxsYmFjayA9IG9wdGlvbnMuY2FsbGJhY2s7XG4gICAgaWYgKHR5cGVvZiBvcHRpb25zID09PSAnZnVuY3Rpb24nKSB7XG4gICAgICBjYWxsYmFjayA9IG9wdGlvbnM7XG4gICAgICBvcHRpb25zID0ge307XG4gICAgfVxuICAgIHRoaXMub3B0aW9ucyA9IG9wdGlvbnM7XG5cbiAgICBsZXQgc2VsZiA9IHRoaXM7XG5cbiAgICBmdW5jdGlvbiBkb25lKHZhbHVlKSB7XG4gICAgICBpZiAoY2FsbGJhY2spIHtcbiAgICAgICAgc2V0VGltZW91dChmdW5jdGlvbigpIHsgY2FsbGJhY2sodW5kZWZpbmVkLCB2YWx1ZSk7IH0sIDApO1xuICAgICAgICByZXR1cm4gdHJ1ZTtcbiAgICAgIH0gZWxzZSB7XG4gICAgICAgIHJldHVybiB2YWx1ZTtcbiAgICAgIH1cbiAgICB9XG5cbiAgICAvLyBBbGxvdyBzdWJjbGFzc2VzIHRvIG1hc3NhZ2UgdGhlIGlucHV0IHByaW9yIHRvIHJ1bm5pbmdcbiAgICBvbGRTdHJpbmcgPSB0aGlzLmNhc3RJbnB1dChvbGRTdHJpbmcpO1xuICAgIG5ld1N0cmluZyA9IHRoaXMuY2FzdElucHV0KG5ld1N0cmluZyk7XG5cbiAgICBvbGRTdHJpbmcgPSB0aGlzLnJlbW92ZUVtcHR5KHRoaXMudG9rZW5pemUob2xkU3RyaW5nKSk7XG4gICAgbmV3U3RyaW5nID0gdGhpcy5yZW1vdmVFbXB0eSh0aGlzLnRva2VuaXplKG5ld1N0cmluZykpO1xuXG4gICAgbGV0IG5ld0xlbiA9IG5ld1N0cmluZy5sZW5ndGgsIG9sZExlbiA9IG9sZFN0cmluZy5sZW5ndGg7XG4gICAgbGV0IGVkaXRMZW5ndGggPSAxO1xuICAgIGxldCBtYXhFZGl0TGVuZ3RoID0gbmV3TGVuICsgb2xkTGVuO1xuICAgIGxldCBiZXN0UGF0aCA9IFt7IG5ld1BvczogLTEsIGNvbXBvbmVudHM6IFtdIH1dO1xuXG4gICAgLy8gU2VlZCBlZGl0TGVuZ3RoID0gMCwgaS5lLiB0aGUgY29udGVudCBzdGFydHMgd2l0aCB0aGUgc2FtZSB2YWx1ZXNcbiAgICBsZXQgb2xkUG9zID0gdGhpcy5leHRyYWN0Q29tbW9uKGJlc3RQYXRoWzBdLCBuZXdTdHJpbmcsIG9sZFN0cmluZywgMCk7XG4gICAgaWYgKGJlc3RQYXRoWzBdLm5ld1BvcyArIDEgPj0gbmV3TGVuICYmIG9sZFBvcyArIDEgPj0gb2xkTGVuKSB7XG4gICAgICAvLyBJZGVudGl0eSBwZXIgdGhlIGVxdWFsaXR5IGFuZCB0b2tlbml6ZXJcbiAgICAgIHJldHVybiBkb25lKFt7dmFsdWU6IHRoaXMuam9pbihuZXdTdHJpbmcpLCBjb3VudDogbmV3U3RyaW5nLmxlbmd0aH1dKTtcbiAgICB9XG5cbiAgICAvLyBNYWluIHdvcmtlciBtZXRob2QuIGNoZWNrcyBhbGwgcGVybXV0YXRpb25zIG9mIGEgZ2l2ZW4gZWRpdCBsZW5ndGggZm9yIGFjY2VwdGFuY2UuXG4gICAgZnVuY3Rpb24gZXhlY0VkaXRMZW5ndGgoKSB7XG4gICAgICBmb3IgKGxldCBkaWFnb25hbFBhdGggPSAtMSAqIGVkaXRMZW5ndGg7IGRpYWdvbmFsUGF0aCA8PSBlZGl0TGVuZ3RoOyBkaWFnb25hbFBhdGggKz0gMikge1xuICAgICAgICBsZXQgYmFzZVBhdGg7XG4gICAgICAgIGxldCBhZGRQYXRoID0gYmVzdFBhdGhbZGlhZ29uYWxQYXRoIC0gMV0sXG4gICAgICAgICAgICByZW1vdmVQYXRoID0gYmVzdFBhdGhbZGlhZ29uYWxQYXRoICsgMV0sXG4gICAgICAgICAgICBvbGRQb3MgPSAocmVtb3ZlUGF0aCA/IHJlbW92ZVBhdGgubmV3UG9zIDogMCkgLSBkaWFnb25hbFBhdGg7XG4gICAgICAgIGlmIChhZGRQYXRoKSB7XG4gICAgICAgICAgLy8gTm8gb25lIGVsc2UgaXMgZ29pbmcgdG8gYXR0ZW1wdCB0byB1c2UgdGhpcyB2YWx1ZSwgY2xlYXIgaXRcbiAgICAgICAgICBiZXN0UGF0aFtkaWFnb25hbFBhdGggLSAxXSA9IHVuZGVmaW5lZDtcbiAgICAgICAgfVxuXG4gICAgICAgIGxldCBjYW5BZGQgPSBhZGRQYXRoICYmIGFkZFBhdGgubmV3UG9zICsgMSA8IG5ld0xlbixcbiAgICAgICAgICAgIGNhblJlbW92ZSA9IHJlbW92ZVBhdGggJiYgMCA8PSBvbGRQb3MgJiYgb2xkUG9zIDwgb2xkTGVuO1xuICAgICAgICBpZiAoIWNhbkFkZCAmJiAhY2FuUmVtb3ZlKSB7XG4gICAgICAgICAgLy8gSWYgdGhpcyBwYXRoIGlzIGEgdGVybWluYWwgdGhlbiBwcnVuZVxuICAgICAgICAgIGJlc3RQYXRoW2RpYWdvbmFsUGF0aF0gPSB1bmRlZmluZWQ7XG4gICAgICAgICAgY29udGludWU7XG4gICAgICAgIH1cblxuICAgICAgICAvLyBTZWxlY3QgdGhlIGRpYWdvbmFsIHRoYXQgd2Ugd2FudCB0byBicmFuY2ggZnJvbS4gV2Ugc2VsZWN0IHRoZSBwcmlvclxuICAgICAgICAvLyBwYXRoIHdob3NlIHBvc2l0aW9uIGluIHRoZSBuZXcgc3RyaW5nIGlzIHRoZSBmYXJ0aGVzdCBmcm9tIHRoZSBvcmlnaW5cbiAgICAgICAgLy8gYW5kIGRvZXMgbm90IHBhc3MgdGhlIGJvdW5kcyBvZiB0aGUgZGlmZiBncmFwaFxuICAgICAgICBpZiAoIWNhbkFkZCB8fCAoY2FuUmVtb3ZlICYmIGFkZFBhdGgubmV3UG9zIDwgcmVtb3ZlUGF0aC5uZXdQb3MpKSB7XG4gICAgICAgICAgYmFzZVBhdGggPSBjbG9uZVBhdGgocmVtb3ZlUGF0aCk7XG4gICAgICAgICAgc2VsZi5wdXNoQ29tcG9uZW50KGJhc2VQYXRoLmNvbXBvbmVudHMsIHVuZGVmaW5lZCwgdHJ1ZSk7XG4gICAgICAgIH0gZWxzZSB7XG4gICAgICAgICAgYmFzZVBhdGggPSBhZGRQYXRoOyAgIC8vIE5vIG5lZWQgdG8gY2xvbmUsIHdlJ3ZlIHB1bGxlZCBpdCBmcm9tIHRoZSBsaXN0XG4gICAgICAgICAgYmFzZVBhdGgubmV3UG9zKys7XG4gICAgICAgICAgc2VsZi5wdXNoQ29tcG9uZW50KGJhc2VQYXRoLmNvbXBvbmVudHMsIHRydWUsIHVuZGVmaW5lZCk7XG4gICAgICAgIH1cblxuICAgICAgICBvbGRQb3MgPSBzZWxmLmV4dHJhY3RDb21tb24oYmFzZVBhdGgsIG5ld1N0cmluZywgb2xkU3RyaW5nLCBkaWFnb25hbFBhdGgpO1xuXG4gICAgICAgIC8vIElmIHdlIGhhdmUgaGl0IHRoZSBlbmQgb2YgYm90aCBzdHJpbmdzLCB0aGVuIHdlIGFyZSBkb25lXG4gICAgICAgIGlmIChiYXNlUGF0aC5uZXdQb3MgKyAxID49IG5ld0xlbiAmJiBvbGRQb3MgKyAxID49IG9sZExlbikge1xuICAgICAgICAgIHJldHVybiBkb25lKGJ1aWxkVmFsdWVzKHNlbGYsIGJhc2VQYXRoLmNvbXBvbmVudHMsIG5ld1N0cmluZywgb2xkU3RyaW5nLCBzZWxmLnVzZUxvbmdlc3RUb2tlbikpO1xuICAgICAgICB9IGVsc2Uge1xuICAgICAgICAgIC8vIE90aGVyd2lzZSB0cmFjayB0aGlzIHBhdGggYXMgYSBwb3RlbnRpYWwgY2FuZGlkYXRlIGFuZCBjb250aW51ZS5cbiAgICAgICAgICBiZXN0UGF0aFtkaWFnb25hbFBhdGhdID0gYmFzZVBhdGg7XG4gICAgICAgIH1cbiAgICAgIH1cblxuICAgICAgZWRpdExlbmd0aCsrO1xuICAgIH1cblxuICAgIC8vIFBlcmZvcm1zIHRoZSBsZW5ndGggb2YgZWRpdCBpdGVyYXRpb24uIElzIGEgYml0IGZ1Z2x5IGFzIHRoaXMgaGFzIHRvIHN1cHBvcnQgdGhlXG4gICAgLy8gc3luYyBhbmQgYXN5bmMgbW9kZSB3aGljaCBpcyBuZXZlciBmdW4uIExvb3BzIG92ZXIgZXhlY0VkaXRMZW5ndGggdW50aWwgYSB2YWx1ZVxuICAgIC8vIGlzIHByb2R1Y2VkLlxuICAgIGlmIChjYWxsYmFjaykge1xuICAgICAgKGZ1bmN0aW9uIGV4ZWMoKSB7XG4gICAgICAgIHNldFRpbWVvdXQoZnVuY3Rpb24oKSB7XG4gICAgICAgICAgLy8gVGhpcyBzaG91bGQgbm90IGhhcHBlbiwgYnV0IHdlIHdhbnQgdG8gYmUgc2FmZS5cbiAgICAgICAgICAvKiBpc3RhbmJ1bCBpZ25vcmUgbmV4dCAqL1xuICAgICAgICAgIGlmIChlZGl0TGVuZ3RoID4gbWF4RWRpdExlbmd0aCkge1xuICAgICAgICAgICAgcmV0dXJuIGNhbGxiYWNrKCk7XG4gICAgICAgICAgfVxuXG4gICAgICAgICAgaWYgKCFleGVjRWRpdExlbmd0aCgpKSB7XG4gICAgICAgICAgICBleGVjKCk7XG4gICAgICAgICAgfVxuICAgICAgICB9LCAwKTtcbiAgICAgIH0oKSk7XG4gICAgfSBlbHNlIHtcbiAgICAgIHdoaWxlIChlZGl0TGVuZ3RoIDw9IG1heEVkaXRMZW5ndGgpIHtcbiAgICAgICAgbGV0IHJldCA9IGV4ZWNFZGl0TGVuZ3RoKCk7XG4gICAgICAgIGlmIChyZXQpIHtcbiAgICAgICAgICByZXR1cm4gcmV0O1xuICAgICAgICB9XG4gICAgICB9XG4gICAgfVxuICB9LFxuXG4gIHB1c2hDb21wb25lbnQoY29tcG9uZW50cywgYWRkZWQsIHJlbW92ZWQpIHtcbiAgICBsZXQgbGFzdCA9IGNvbXBvbmVudHNbY29tcG9uZW50cy5sZW5ndGggLSAxXTtcbiAgICBpZiAobGFzdCAmJiBsYXN0LmFkZGVkID09PSBhZGRlZCAmJiBsYXN0LnJlbW92ZWQgPT09IHJlbW92ZWQpIHtcbiAgICAgIC8vIFdlIG5lZWQgdG8gY2xvbmUgaGVyZSBhcyB0aGUgY29tcG9uZW50IGNsb25lIG9wZXJhdGlvbiBpcyBqdXN0XG4gICAgICAvLyBhcyBzaGFsbG93IGFycmF5IGNsb25lXG4gICAgICBjb21wb25lbnRzW2NvbXBvbmVudHMubGVuZ3RoIC0gMV0gPSB7Y291bnQ6IGxhc3QuY291bnQgKyAxLCBhZGRlZDogYWRkZWQsIHJlbW92ZWQ6IHJlbW92ZWQgfTtcbiAgICB9IGVsc2Uge1xuICAgICAgY29tcG9uZW50cy5wdXNoKHtjb3VudDogMSwgYWRkZWQ6IGFkZGVkLCByZW1vdmVkOiByZW1vdmVkIH0pO1xuICAgIH1cbiAgfSxcbiAgZXh0cmFjdENvbW1vbihiYXNlUGF0aCwgbmV3U3RyaW5nLCBvbGRTdHJpbmcsIGRpYWdvbmFsUGF0aCkge1xuICAgIGxldCBuZXdMZW4gPSBuZXdTdHJpbmcubGVuZ3RoLFxuICAgICAgICBvbGRMZW4gPSBvbGRTdHJpbmcubGVuZ3RoLFxuICAgICAgICBuZXdQb3MgPSBiYXNlUGF0aC5uZXdQb3MsXG4gICAgICAgIG9sZFBvcyA9IG5ld1BvcyAtIGRpYWdvbmFsUGF0aCxcblxuICAgICAgICBjb21tb25Db3VudCA9IDA7XG4gICAgd2hpbGUgKG5ld1BvcyArIDEgPCBuZXdMZW4gJiYgb2xkUG9zICsgMSA8IG9sZExlbiAmJiB0aGlzLmVxdWFscyhuZXdTdHJpbmdbbmV3UG9zICsgMV0sIG9sZFN0cmluZ1tvbGRQb3MgKyAxXSkpIHtcbiAgICAgIG5ld1BvcysrO1xuICAgICAgb2xkUG9zKys7XG4gICAgICBjb21tb25Db3VudCsrO1xuICAgIH1cblxuICAgIGlmIChjb21tb25Db3VudCkge1xuICAgICAgYmFzZVBhdGguY29tcG9uZW50cy5wdXNoKHtjb3VudDogY29tbW9uQ291bnR9KTtcbiAgICB9XG5cbiAgICBiYXNlUGF0aC5uZXdQb3MgPSBuZXdQb3M7XG4gICAgcmV0dXJuIG9sZFBvcztcbiAgfSxcblxuICBlcXVhbHMobGVmdCwgcmlnaHQpIHtcbiAgICBpZiAodGhpcy5vcHRpb25zLmNvbXBhcmF0b3IpIHtcbiAgICAgIHJldHVybiB0aGlzLm9wdGlvbnMuY29tcGFyYXRvcihsZWZ0LCByaWdodCk7XG4gICAgfSBlbHNlIHtcbiAgICAgIHJldHVybiBsZWZ0ID09PSByaWdodFxuICAgICAgICB8fCAodGhpcy5vcHRpb25zLmlnbm9yZUNhc2UgJiYgbGVmdC50b0xvd2VyQ2FzZSgpID09PSByaWdodC50b0xvd2VyQ2FzZSgpKTtcbiAgICB9XG4gIH0sXG4gIHJlbW92ZUVtcHR5KGFycmF5KSB7XG4gICAgbGV0IHJldCA9IFtdO1xuICAgIGZvciAobGV0IGkgPSAwOyBpIDwgYXJyYXkubGVuZ3RoOyBpKyspIHtcbiAgICAgIGlmIChhcnJheVtpXSkge1xuICAgICAgICByZXQucHVzaChhcnJheVtpXSk7XG4gICAgICB9XG4gICAgfVxuICAgIHJldHVybiByZXQ7XG4gIH0sXG4gIGNhc3RJbnB1dCh2YWx1ZSkge1xuICAgIHJldHVybiB2YWx1ZTtcbiAgfSxcbiAgdG9rZW5pemUodmFsdWUpIHtcbiAgICByZXR1cm4gdmFsdWUuc3BsaXQoJycpO1xuICB9LFxuICBqb2luKGNoYXJzKSB7XG4gICAgcmV0dXJuIGNoYXJzLmpvaW4oJycpO1xuICB9XG59O1xuXG5mdW5jdGlvbiBidWlsZFZhbHVlcyhkaWZmLCBjb21wb25lbnRzLCBuZXdTdHJpbmcsIG9sZFN0cmluZywgdXNlTG9uZ2VzdFRva2VuKSB7XG4gIGxldCBjb21wb25lbnRQb3MgPSAwLFxuICAgICAgY29tcG9uZW50TGVuID0gY29tcG9uZW50cy5sZW5ndGgsXG4gICAgICBuZXdQb3MgPSAwLFxuICAgICAgb2xkUG9zID0gMDtcblxuICBmb3IgKDsgY29tcG9uZW50UG9zIDwgY29tcG9uZW50TGVuOyBjb21wb25lbnRQb3MrKykge1xuICAgIGxldCBjb21wb25lbnQgPSBjb21wb25lbnRzW2NvbXBvbmVudFBvc107XG4gICAgaWYgKCFjb21wb25lbnQucmVtb3ZlZCkge1xuICAgICAgaWYgKCFjb21wb25lbnQuYWRkZWQgJiYgdXNlTG9uZ2VzdFRva2VuKSB7XG4gICAgICAgIGxldCB2YWx1ZSA9IG5ld1N0cmluZy5zbGljZShuZXdQb3MsIG5ld1BvcyArIGNvbXBvbmVudC5jb3VudCk7XG4gICAgICAgIHZhbHVlID0gdmFsdWUubWFwKGZ1bmN0aW9uKHZhbHVlLCBpKSB7XG4gICAgICAgICAgbGV0IG9sZFZhbHVlID0gb2xkU3RyaW5nW29sZFBvcyArIGldO1xuICAgICAgICAgIHJldHVybiBvbGRWYWx1ZS5sZW5ndGggPiB2YWx1ZS5sZW5ndGggPyBvbGRWYWx1ZSA6IHZhbHVlO1xuICAgICAgICB9KTtcblxuICAgICAgICBjb21wb25lbnQudmFsdWUgPSBkaWZmLmpvaW4odmFsdWUpO1xuICAgICAgfSBlbHNlIHtcbiAgICAgICAgY29tcG9uZW50LnZhbHVlID0gZGlmZi5qb2luKG5ld1N0cmluZy5zbGljZShuZXdQb3MsIG5ld1BvcyArIGNvbXBvbmVudC5jb3VudCkpO1xuICAgICAgfVxuICAgICAgbmV3UG9zICs9IGNvbXBvbmVudC5jb3VudDtcblxuICAgICAgLy8gQ29tbW9uIGNhc2VcbiAgICAgIGlmICghY29tcG9uZW50LmFkZGVkKSB7XG4gICAgICAgIG9sZFBvcyArPSBjb21wb25lbnQuY291bnQ7XG4gICAgICB9XG4gICAgfSBlbHNlIHtcbiAgICAgIGNvbXBvbmVudC52YWx1ZSA9IGRpZmYuam9pbihvbGRTdHJpbmcuc2xpY2Uob2xkUG9zLCBvbGRQb3MgKyBjb21wb25lbnQuY291bnQpKTtcbiAgICAgIG9sZFBvcyArPSBjb21wb25lbnQuY291bnQ7XG5cbiAgICAgIC8vIFJldmVyc2UgYWRkIGFuZCByZW1vdmUgc28gcmVtb3ZlcyBhcmUgb3V0cHV0IGZpcnN0IHRvIG1hdGNoIGNvbW1vbiBjb252ZW50aW9uXG4gICAgICAvLyBUaGUgZGlmZmluZyBhbGdvcml0aG0gaXMgdGllZCB0byBhZGQgdGhlbiByZW1vdmUgb3V0cHV0IGFuZCB0aGlzIGlzIHRoZSBzaW1wbGVzdFxuICAgICAgLy8gcm91dGUgdG8gZ2V0IHRoZSBkZXNpcmVkIG91dHB1dCB3aXRoIG1pbmltYWwgb3ZlcmhlYWQuXG4gICAgICBpZiAoY29tcG9uZW50UG9zICYmIGNvbXBvbmVudHNbY29tcG9uZW50UG9zIC0gMV0uYWRkZWQpIHtcbiAgICAgICAgbGV0IHRtcCA9IGNvbXBvbmVudHNbY29tcG9uZW50UG9zIC0gMV07XG4gICAgICAgIGNvbXBvbmVudHNbY29tcG9uZW50UG9zIC0gMV0gPSBjb21wb25lbnRzW2NvbXBvbmVudFBvc107XG4gICAgICAgIGNvbXBvbmVudHNbY29tcG9uZW50UG9zXSA9IHRtcDtcbiAgICAgIH1cbiAgICB9XG4gIH1cblxuICAvLyBTcGVjaWFsIGNhc2UgaGFuZGxlIGZvciB3aGVuIG9uZSB0ZXJtaW5hbCBpcyBpZ25vcmVkIChpLmUuIHdoaXRlc3BhY2UpLlxuICAvLyBGb3IgdGhpcyBjYXNlIHdlIG1lcmdlIHRoZSB0ZXJtaW5hbCBpbnRvIHRoZSBwcmlvciBzdHJpbmcgYW5kIGRyb3AgdGhlIGNoYW5nZS5cbiAgLy8gVGhpcyBpcyBvbmx5IGF2YWlsYWJsZSBmb3Igc3RyaW5nIG1vZGUuXG4gIGxldCBsYXN0Q29tcG9uZW50ID0gY29tcG9uZW50c1tjb21wb25lbnRMZW4gLSAxXTtcbiAgaWYgKGNvbXBvbmVudExlbiA+IDFcbiAgICAgICYmIHR5cGVvZiBsYXN0Q29tcG9uZW50LnZhbHVlID09PSAnc3RyaW5nJ1xuICAgICAgJiYgKGxhc3RDb21wb25lbnQuYWRkZWQgfHwgbGFzdENvbXBvbmVudC5yZW1vdmVkKVxuICAgICAgJiYgZGlmZi5lcXVhbHMoJycsIGxhc3RDb21wb25lbnQudmFsdWUpKSB7XG4gICAgY29tcG9uZW50c1tjb21wb25lbnRMZW4gLSAyXS52YWx1ZSArPSBsYXN0Q29tcG9uZW50LnZhbHVlO1xuICAgIGNvbXBvbmVudHMucG9wKCk7XG4gIH1cblxuICByZXR1cm4gY29tcG9uZW50cztcbn1cblxuZnVuY3Rpb24gY2xvbmVQYXRoKHBhdGgpIHtcbiAgcmV0dXJuIHsgbmV3UG9zOiBwYXRoLm5ld1BvcywgY29tcG9uZW50czogcGF0aC5jb21wb25lbnRzLnNsaWNlKDApIH07XG59XG4iXX0=
+
+
+/***/ }),
+/* 2 */
+/***/ (function(module, exports, __webpack_require__) {
+
+	/*istanbul ignore start*/'use strict';
+
+	exports.__esModule = true;
+	exports.characterDiff = undefined;
+	exports. /*istanbul ignore end*/diffChars = diffChars;
+
+	var /*istanbul ignore start*/_base = __webpack_require__(1) /*istanbul ignore end*/;
+
+	/*istanbul ignore start*/var _base2 = _interopRequireDefault(_base);
+
+	function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
+
+	/*istanbul ignore end*/var characterDiff = /*istanbul ignore start*/exports. /*istanbul ignore end*/characterDiff = new /*istanbul ignore start*/_base2['default'] /*istanbul ignore end*/();
+	function diffChars(oldStr, newStr, options) {
+	  return characterDiff.diff(oldStr, newStr, options);
+	}
+	//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9kaWZmL2NoYXJhY3Rlci5qcyJdLCJuYW1lcyI6WyJkaWZmQ2hhcnMiLCJjaGFyYWN0ZXJEaWZmIiwib2xkU3RyIiwibmV3U3RyIiwib3B0aW9ucyIsImRpZmYiXSwibWFwcGluZ3MiOiI7Ozs7Z0NBR2dCQSxTLEdBQUFBLFM7O0FBSGhCOzs7Ozs7dUJBRU8sSUFBTUMseUZBQWdCLHdFQUF0QjtBQUNBLFNBQVNELFNBQVQsQ0FBbUJFLE1BQW5CLEVBQTJCQyxNQUEzQixFQUFtQ0MsT0FBbkMsRUFBNEM7QUFBRSxTQUFPSCxjQUFjSSxJQUFkLENBQW1CSCxNQUFuQixFQUEyQkMsTUFBM0IsRUFBbUNDLE9BQW5DLENBQVA7QUFBcUQiLCJmaWxlIjoiY2hhcmFjdGVyLmpzIiwic291cmNlc0NvbnRlbnQiOlsiaW1wb3J0IERpZmYgZnJvbSAnLi9iYXNlJztcblxuZXhwb3J0IGNvbnN0IGNoYXJhY3RlckRpZmYgPSBuZXcgRGlmZigpO1xuZXhwb3J0IGZ1bmN0aW9uIGRpZmZDaGFycyhvbGRTdHIsIG5ld1N0ciwgb3B0aW9ucykgeyByZXR1cm4gY2hhcmFjdGVyRGlmZi5kaWZmKG9sZFN0ciwgbmV3U3RyLCBvcHRpb25zKTsgfVxuIl19
+
+
+/***/ }),
+/* 3 */
+/***/ (function(module, exports, __webpack_require__) {
+
+	/*istanbul ignore start*/'use strict';
+
+	exports.__esModule = true;
+	exports.wordDiff = undefined;
+	exports. /*istanbul ignore end*/diffWords = diffWords;
+	/*istanbul ignore start*/exports. /*istanbul ignore end*/diffWordsWithSpace = diffWordsWithSpace;
+
+	var /*istanbul ignore start*/_base = __webpack_require__(1) /*istanbul ignore end*/;
+
+	/*istanbul ignore start*/var _base2 = _interopRequireDefault(_base);
+
+	/*istanbul ignore end*/var /*istanbul ignore start*/_params = __webpack_require__(4) /*istanbul ignore end*/;
+
+	/*istanbul ignore start*/function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
+
+	/*istanbul ignore end*/ // Based on https://en.wikipedia.org/wiki/Latin_script_in_Unicode
+	//
+	// Ranges and exceptions:
+	// Latin-1 Supplement, 0080–00FF
+	//  - U+00D7  × Multiplication sign
+	//  - U+00F7  ÷ Division sign
+	// Latin Extended-A, 0100–017F
+	// Latin Extended-B, 0180–024F
+	// IPA Extensions, 0250–02AF
+	// Spacing Modifier Letters, 02B0–02FF
+	//  - U+02C7  ˇ ˇ  Caron
+	//  - U+02D8  ˘ ˘  Breve
+	//  - U+02D9  ˙ ˙  Dot Above
+	//  - U+02DA  ˚ ˚  Ring Above
+	//  - U+02DB  ˛ ˛  Ogonek
+	//  - U+02DC  ˜ ˜  Small Tilde
+	//  - U+02DD  ˝ ˝  Double Acute Accent
+	// Latin Extended Additional, 1E00–1EFF
+	var extendedWordChars = /^[A-Za-z\xC0-\u02C6\u02C8-\u02D7\u02DE-\u02FF\u1E00-\u1EFF]+$/;
+
+	var reWhitespace = /\S/;
+
+	var wordDiff = /*istanbul ignore start*/exports. /*istanbul ignore end*/wordDiff = new /*istanbul ignore start*/_base2['default'] /*istanbul ignore end*/();
+	wordDiff.equals = function (left, right) {
+	  if (this.options.ignoreCase) {
+	    left = left.toLowerCase();
+	    right = right.toLowerCase();
+	  }
+	  return left === right || this.options.ignoreWhitespace && !reWhitespace.test(left) && !reWhitespace.test(right);
+	};
+	wordDiff.tokenize = function (value) {
+	  var tokens = value.split(/(\s+|\b)/);
+
+	  // Join the boundary splits that we do not consider to be boundaries. This is primarily the extended Latin character set.
+	  for (var i = 0; i < tokens.length - 1; i++) {
+	    // If we have an empty string in the next field and we have only word chars before and after, merge
+	    if (!tokens[i + 1] && tokens[i + 2] && extendedWordChars.test(tokens[i]) && extendedWordChars.test(tokens[i + 2])) {
+	      tokens[i] += tokens[i + 2];
+	      tokens.splice(i + 1, 2);
+	      i--;
+	    }
+	  }
+
+	  return tokens;
+	};
+
+	function diffWords(oldStr, newStr, options) {
+	  options = /*istanbul ignore start*/(0, _params.generateOptions) /*istanbul ignore end*/(options, { ignoreWhitespace: true });
+	  return wordDiff.diff(oldStr, newStr, options);
+	}
+
+	function diffWordsWithSpace(oldStr, newStr, options) {
+	  return wordDiff.diff(oldStr, newStr, options);
+	}
+	//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9kaWZmL3dvcmQuanMiXSwibmFtZXMiOlsiZGlmZldvcmRzIiwiZGlmZldvcmRzV2l0aFNwYWNlIiwiZXh0ZW5kZWRXb3JkQ2hhcnMiLCJyZVdoaXRlc3BhY2UiLCJ3b3JkRGlmZiIsImVxdWFscyIsImxlZnQiLCJyaWdodCIsIm9wdGlvbnMiLCJpZ25vcmVDYXNlIiwidG9Mb3dlckNhc2UiLCJpZ25vcmVXaGl0ZXNwYWNlIiwidGVzdCIsInRva2VuaXplIiwidmFsdWUiLCJ0b2tlbnMiLCJzcGxpdCIsImkiLCJsZW5ndGgiLCJzcGxpY2UiLCJvbGRTdHIiLCJuZXdTdHIiLCJkaWZmIl0sIm1hcHBpbmdzIjoiOzs7O2dDQW1EZ0JBLFMsR0FBQUEsUzt5REFLQUMsa0IsR0FBQUEsa0I7O0FBeERoQjs7Ozt1QkFDQTs7Ozt3QkFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSxJQUFNQyxvQkFBb0IsK0RBQTFCOztBQUVBLElBQU1DLGVBQWUsSUFBckI7O0FBRU8sSUFBTUMsK0VBQVcsd0VBQWpCO0FBQ1BBLFNBQVNDLE1BQVQsR0FBa0IsVUFBU0MsSUFBVCxFQUFlQyxLQUFmLEVBQXNCO0FBQ3RDLE1BQUksS0FBS0MsT0FBTCxDQUFhQyxVQUFqQixFQUE2QjtBQUMzQkgsV0FBT0EsS0FBS0ksV0FBTCxFQUFQO0FBQ0FILFlBQVFBLE1BQU1HLFdBQU4sRUFBUjtBQUNEO0FBQ0QsU0FBT0osU0FBU0MsS0FBVCxJQUFtQixLQUFLQyxPQUFMLENBQWFHLGdCQUFiLElBQWlDLENBQUNSLGFBQWFTLElBQWIsQ0FBa0JOLElBQWxCLENBQWxDLElBQTZELENBQUNILGFBQWFTLElBQWIsQ0FBa0JMLEtBQWxCLENBQXhGO0FBQ0QsQ0FORDtBQU9BSCxTQUFTUyxRQUFULEdBQW9CLFVBQVNDLEtBQVQsRUFBZ0I7QUFDbEMsTUFBSUMsU0FBU0QsTUFBTUUsS0FBTixDQUFZLFVBQVosQ0FBYjs7QUFFQTtBQUNBLE9BQUssSUFBSUMsSUFBSSxDQUFiLEVBQWdCQSxJQUFJRixPQUFPRyxNQUFQLEdBQWdCLENBQXBDLEVBQXVDRCxHQUF2QyxFQUE0QztBQUMxQztBQUNBLFFBQUksQ0FBQ0YsT0FBT0UsSUFBSSxDQUFYLENBQUQsSUFBa0JGLE9BQU9FLElBQUksQ0FBWCxDQUFsQixJQUNLZixrQkFBa0JVLElBQWxCLENBQXVCRyxPQUFPRSxDQUFQLENBQXZCLENBREwsSUFFS2Ysa0JBQWtCVSxJQUFsQixDQUF1QkcsT0FBT0UsSUFBSSxDQUFYLENBQXZCLENBRlQsRUFFZ0Q7QUFDOUNGLGFBQU9FLENBQVAsS0FBYUYsT0FBT0UsSUFBSSxDQUFYLENBQWI7QUFDQUYsYUFBT0ksTUFBUCxDQUFjRixJQUFJLENBQWxCLEVBQXFCLENBQXJCO0FBQ0FBO0FBQ0Q7QUFDRjs7QUFFRCxTQUFPRixNQUFQO0FBQ0QsQ0FoQkQ7O0FBa0JPLFNBQVNmLFNBQVQsQ0FBbUJvQixNQUFuQixFQUEyQkMsTUFBM0IsRUFBbUNiLE9BQW5DLEVBQTRDO0FBQ2pEQSxZQUFVLDhFQUFnQkEsT0FBaEIsRUFBeUIsRUFBQ0csa0JBQWtCLElBQW5CLEVBQXpCLENBQVY7QUFDQSxTQUFPUCxTQUFTa0IsSUFBVCxDQUFjRixNQUFkLEVBQXNCQyxNQUF0QixFQUE4QmIsT0FBOUIsQ0FBUDtBQUNEOztBQUVNLFNBQVNQLGtCQUFULENBQTRCbUIsTUFBNUIsRUFBb0NDLE1BQXBDLEVBQTRDYixPQUE1QyxFQUFxRDtBQUMxRCxTQUFPSixTQUFTa0IsSUFBVCxDQUFjRixNQUFkLEVBQXNCQyxNQUF0QixFQUE4QmIsT0FBOUIsQ0FBUDtBQUNEIiwiZmlsZSI6IndvcmQuanMiLCJzb3VyY2VzQ29udGVudCI6WyJpbXBvcnQgRGlmZiBmcm9tICcuL2Jhc2UnO1xuaW1wb3J0IHtnZW5lcmF0ZU9wdGlvbnN9IGZyb20gJy4uL3V0aWwvcGFyYW1zJztcblxuLy8gQmFzZWQgb24gaHR0cHM6Ly9lbi53aWtpcGVkaWEub3JnL3dpa2kvTGF0aW5fc2NyaXB0X2luX1VuaWNvZGVcbi8vXG4vLyBSYW5nZXMgYW5kIGV4Y2VwdGlvbnM6XG4vLyBMYXRpbi0xIFN1cHBsZW1lbnQsIDAwODDigJMwMEZGXG4vLyAgLSBVKzAwRDcgIMOXIE11bHRpcGxpY2F0aW9uIHNpZ25cbi8vICAtIFUrMDBGNyAgw7cgRGl2aXNpb24gc2lnblxuLy8gTGF0aW4gRXh0ZW5kZWQtQSwgMDEwMOKAkzAxN0Zcbi8vIExhdGluIEV4dGVuZGVkLUIsIDAxODDigJMwMjRGXG4vLyBJUEEgRXh0ZW5zaW9ucywgMDI1MOKAkzAyQUZcbi8vIFNwYWNpbmcgTW9kaWZpZXIgTGV0dGVycywgMDJCMOKAkzAyRkZcbi8vICAtIFUrMDJDNyAgy4cgJiM3MTE7ICBDYXJvblxuLy8gIC0gVSswMkQ4ICDLmCAmIzcyODsgIEJyZXZlXG4vLyAgLSBVKzAyRDkgIMuZICYjNzI5OyAgRG90IEFib3ZlXG4vLyAgLSBVKzAyREEgIMuaICYjNzMwOyAgUmluZyBBYm92ZVxuLy8gIC0gVSswMkRCICDLmyAmIzczMTsgIE9nb25la1xuLy8gIC0gVSswMkRDICDLnCAmIzczMjsgIFNtYWxsIFRpbGRlXG4vLyAgLSBVKzAyREQgIMudICYjNzMzOyAgRG91YmxlIEFjdXRlIEFjY2VudFxuLy8gTGF0aW4gRXh0ZW5kZWQgQWRkaXRpb25hbCwgMUUwMOKAkzFFRkZcbmNvbnN0IGV4dGVuZGVkV29yZENoYXJzID0gL15bYS16QS1aXFx1e0MwfS1cXHV7RkZ9XFx1e0Q4fS1cXHV7RjZ9XFx1e0Y4fS1cXHV7MkM2fVxcdXsyQzh9LVxcdXsyRDd9XFx1ezJERX0tXFx1ezJGRn1cXHV7MUUwMH0tXFx1ezFFRkZ9XSskL3U7XG5cbmNvbnN0IHJlV2hpdGVzcGFjZSA9IC9cXFMvO1xuXG5leHBvcnQgY29uc3Qgd29yZERpZmYgPSBuZXcgRGlmZigpO1xud29yZERpZmYuZXF1YWxzID0gZnVuY3Rpb24obGVmdCwgcmlnaHQpIHtcbiAgaWYgKHRoaXMub3B0aW9ucy5pZ25vcmVDYXNlKSB7XG4gICAgbGVmdCA9IGxlZnQudG9Mb3dlckNhc2UoKTtcbiAgICByaWdodCA9IHJpZ2h0LnRvTG93ZXJDYXNlKCk7XG4gIH1cbiAgcmV0dXJuIGxlZnQgPT09IHJpZ2h0IHx8ICh0aGlzLm9wdGlvbnMuaWdub3JlV2hpdGVzcGFjZSAmJiAhcmVXaGl0ZXNwYWNlLnRlc3QobGVmdCkgJiYgIXJlV2hpdGVzcGFjZS50ZXN0KHJpZ2h0KSk7XG59O1xud29yZERpZmYudG9rZW5pemUgPSBmdW5jdGlvbih2YWx1ZSkge1xuICBsZXQgdG9rZW5zID0gdmFsdWUuc3BsaXQoLyhcXHMrfFxcYikvKTtcblxuICAvLyBKb2luIHRoZSBib3VuZGFyeSBzcGxpdHMgdGhhdCB3ZSBkbyBub3QgY29uc2lkZXIgdG8gYmUgYm91bmRhcmllcy4gVGhpcyBpcyBwcmltYXJpbHkgdGhlIGV4dGVuZGVkIExhdGluIGNoYXJhY3RlciBzZXQuXG4gIGZvciAobGV0IGkgPSAwOyBpIDwgdG9rZW5zLmxlbmd0aCAtIDE7IGkrKykge1xuICAgIC8vIElmIHdlIGhhdmUgYW4gZW1wdHkgc3RyaW5nIGluIHRoZSBuZXh0IGZpZWxkIGFuZCB3ZSBoYXZlIG9ubHkgd29yZCBjaGFycyBiZWZvcmUgYW5kIGFmdGVyLCBtZXJnZVxuICAgIGlmICghdG9rZW5zW2kgKyAxXSAmJiB0b2tlbnNbaSArIDJdXG4gICAgICAgICAgJiYgZXh0ZW5kZWRXb3JkQ2hhcnMudGVzdCh0b2tlbnNbaV0pXG4gICAgICAgICAgJiYgZXh0ZW5kZWRXb3JkQ2hhcnMudGVzdCh0b2tlbnNbaSArIDJdKSkge1xuICAgICAgdG9rZW5zW2ldICs9IHRva2Vuc1tpICsgMl07XG4gICAgICB0b2tlbnMuc3BsaWNlKGkgKyAxLCAyKTtcbiAgICAgIGktLTtcbiAgICB9XG4gIH1cblxuICByZXR1cm4gdG9rZW5zO1xufTtcblxuZXhwb3J0IGZ1bmN0aW9uIGRpZmZXb3JkcyhvbGRTdHIsIG5ld1N0ciwgb3B0aW9ucykge1xuICBvcHRpb25zID0gZ2VuZXJhdGVPcHRpb25zKG9wdGlvbnMsIHtpZ25vcmVXaGl0ZXNwYWNlOiB0cnVlfSk7XG4gIHJldHVybiB3b3JkRGlmZi5kaWZmKG9sZFN0ciwgbmV3U3RyLCBvcHRpb25zKTtcbn1cblxuZXhwb3J0IGZ1bmN0aW9uIGRpZmZXb3Jkc1dpdGhTcGFjZShvbGRTdHIsIG5ld1N0ciwgb3B0aW9ucykge1xuICByZXR1cm4gd29yZERpZmYuZGlmZihvbGRTdHIsIG5ld1N0ciwgb3B0aW9ucyk7XG59XG4iXX0=
+
+
+/***/ }),
+/* 4 */
+/***/ (function(module, exports) {
+
+	/*istanbul ignore start*/'use strict';
+
+	exports.__esModule = true;
+	exports. /*istanbul ignore end*/generateOptions = generateOptions;
+	function generateOptions(options, defaults) {
+	  if (typeof options === 'function') {
+	    defaults.callback = options;
+	  } else if (options) {
+	    for (var name in options) {
+	      /* istanbul ignore else */
+	      if (options.hasOwnProperty(name)) {
+	        defaults[name] = options[name];
+	      }
+	    }
+	  }
+	  return defaults;
+	}
+	//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy91dGlsL3BhcmFtcy5qcyJdLCJuYW1lcyI6WyJnZW5lcmF0ZU9wdGlvbnMiLCJvcHRpb25zIiwiZGVmYXVsdHMiLCJjYWxsYmFjayIsIm5hbWUiLCJoYXNPd25Qcm9wZXJ0eSJdLCJtYXBwaW5ncyI6Ijs7O2dDQUFnQkEsZSxHQUFBQSxlO0FBQVQsU0FBU0EsZUFBVCxDQUF5QkMsT0FBekIsRUFBa0NDLFFBQWxDLEVBQTRDO0FBQ2pELE1BQUksT0FBT0QsT0FBUCxLQUFtQixVQUF2QixFQUFtQztBQUNqQ0MsYUFBU0MsUUFBVCxHQUFvQkYsT0FBcEI7QUFDRCxHQUZELE1BRU8sSUFBSUEsT0FBSixFQUFhO0FBQ2xCLFNBQUssSUFBSUcsSUFBVCxJQUFpQkgsT0FBakIsRUFBMEI7QUFDeEI7QUFDQSxVQUFJQSxRQUFRSSxjQUFSLENBQXVCRCxJQUF2QixDQUFKLEVBQWtDO0FBQ2hDRixpQkFBU0UsSUFBVCxJQUFpQkgsUUFBUUcsSUFBUixDQUFqQjtBQUNEO0FBQ0Y7QUFDRjtBQUNELFNBQU9GLFFBQVA7QUFDRCIsImZpbGUiOiJwYXJhbXMuanMiLCJzb3VyY2VzQ29udGVudCI6WyJleHBvcnQgZnVuY3Rpb24gZ2VuZXJhdGVPcHRpb25zKG9wdGlvbnMsIGRlZmF1bHRzKSB7XG4gIGlmICh0eXBlb2Ygb3B0aW9ucyA9PT0gJ2Z1bmN0aW9uJykge1xuICAgIGRlZmF1bHRzLmNhbGxiYWNrID0gb3B0aW9ucztcbiAgfSBlbHNlIGlmIChvcHRpb25zKSB7XG4gICAgZm9yIChsZXQgbmFtZSBpbiBvcHRpb25zKSB7XG4gICAgICAvKiBpc3RhbmJ1bCBpZ25vcmUgZWxzZSAqL1xuICAgICAgaWYgKG9wdGlvbnMuaGFzT3duUHJvcGVydHkobmFtZSkpIHtcbiAgICAgICAgZGVmYXVsdHNbbmFtZV0gPSBvcHRpb25zW25hbWVdO1xuICAgICAgfVxuICAgIH1cbiAgfVxuICByZXR1cm4gZGVmYXVsdHM7XG59XG4iXX0=
+
+
+/***/ }),
+/* 5 */
+/***/ (function(module, exports, __webpack_require__) {
+
+	/*istanbul ignore start*/'use strict';
+
+	exports.__esModule = true;
+	exports.lineDiff = undefined;
+	exports. /*istanbul ignore end*/diffLines = diffLines;
+	/*istanbul ignore start*/exports. /*istanbul ignore end*/diffTrimmedLines = diffTrimmedLines;
+
+	var /*istanbul ignore start*/_base = __webpack_require__(1) /*istanbul ignore end*/;
+
+	/*istanbul ignore start*/var _base2 = _interopRequireDefault(_base);
+
+	/*istanbul ignore end*/var /*istanbul ignore start*/_params = __webpack_require__(4) /*istanbul ignore end*/;
+
+	/*istanbul ignore start*/function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
+
+	/*istanbul ignore end*/var lineDiff = /*istanbul ignore start*/exports. /*istanbul ignore end*/lineDiff = new /*istanbul ignore start*/_base2['default'] /*istanbul ignore end*/();
+	lineDiff.tokenize = function (value) {
+	  var retLines = [],
+	      linesAndNewlines = value.split(/(\n|\r\n)/);
+
+	  // Ignore the final empty token that occurs if the string ends with a new line
+	  if (!linesAndNewlines[linesAndNewlines.length - 1]) {
+	    linesAndNewlines.pop();
+	  }
+
+	  // Merge the content and line separators into single tokens
+	  for (var i = 0; i < linesAndNewlines.length; i++) {
+	    var line = linesAndNewlines[i];
+
+	    if (i % 2 && !this.options.newlineIsToken) {
+	      retLines[retLines.length - 1] += line;
+	    } else {
+	      if (this.options.ignoreWhitespace) {
+	        line = line.trim();
+	      }
+	      retLines.push(line);
+	    }
+	  }
+
+	  return retLines;
+	};
+
+	function diffLines(oldStr, newStr, callback) {
+	  return lineDiff.diff(oldStr, newStr, callback);
+	}
+	function diffTrimmedLines(oldStr, newStr, callback) {
+	  var options = /*istanbul ignore start*/(0, _params.generateOptions) /*istanbul ignore end*/(callback, { ignoreWhitespace: true });
+	  return lineDiff.diff(oldStr, newStr, options);
+	}
+	//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9kaWZmL2xpbmUuanMiXSwibmFtZXMiOlsiZGlmZkxpbmVzIiwiZGlmZlRyaW1tZWRMaW5lcyIsImxpbmVEaWZmIiwidG9rZW5pemUiLCJ2YWx1ZSIsInJldExpbmVzIiwibGluZXNBbmROZXdsaW5lcyIsInNwbGl0IiwibGVuZ3RoIiwicG9wIiwiaSIsImxpbmUiLCJvcHRpb25zIiwibmV3bGluZUlzVG9rZW4iLCJpZ25vcmVXaGl0ZXNwYWNlIiwidHJpbSIsInB1c2giLCJvbGRTdHIiLCJuZXdTdHIiLCJjYWxsYmFjayIsImRpZmYiXSwibWFwcGluZ3MiOiI7Ozs7Z0NBOEJnQkEsUyxHQUFBQSxTO3lEQUNBQyxnQixHQUFBQSxnQjs7QUEvQmhCOzs7O3VCQUNBOzs7O3VCQUVPLElBQU1DLCtFQUFXLHdFQUFqQjtBQUNQQSxTQUFTQyxRQUFULEdBQW9CLFVBQVNDLEtBQVQsRUFBZ0I7QUFDbEMsTUFBSUMsV0FBVyxFQUFmO0FBQUEsTUFDSUMsbUJBQW1CRixNQUFNRyxLQUFOLENBQVksV0FBWixDQUR2Qjs7QUFHQTtBQUNBLE1BQUksQ0FBQ0QsaUJBQWlCQSxpQkFBaUJFLE1BQWpCLEdBQTBCLENBQTNDLENBQUwsRUFBb0Q7QUFDbERGLHFCQUFpQkcsR0FBakI7QUFDRDs7QUFFRDtBQUNBLE9BQUssSUFBSUMsSUFBSSxDQUFiLEVBQWdCQSxJQUFJSixpQkFBaUJFLE1BQXJDLEVBQTZDRSxHQUE3QyxFQUFrRDtBQUNoRCxRQUFJQyxPQUFPTCxpQkFBaUJJLENBQWpCLENBQVg7O0FBRUEsUUFBSUEsSUFBSSxDQUFKLElBQVMsQ0FBQyxLQUFLRSxPQUFMLENBQWFDLGNBQTNCLEVBQTJDO0FBQ3pDUixlQUFTQSxTQUFTRyxNQUFULEdBQWtCLENBQTNCLEtBQWlDRyxJQUFqQztBQUNELEtBRkQsTUFFTztBQUNMLFVBQUksS0FBS0MsT0FBTCxDQUFhRSxnQkFBakIsRUFBbUM7QUFDakNILGVBQU9BLEtBQUtJLElBQUwsRUFBUDtBQUNEO0FBQ0RWLGVBQVNXLElBQVQsQ0FBY0wsSUFBZDtBQUNEO0FBQ0Y7O0FBRUQsU0FBT04sUUFBUDtBQUNELENBeEJEOztBQTBCTyxTQUFTTCxTQUFULENBQW1CaUIsTUFBbkIsRUFBMkJDLE1BQTNCLEVBQW1DQyxRQUFuQyxFQUE2QztBQUFFLFNBQU9qQixTQUFTa0IsSUFBVCxDQUFjSCxNQUFkLEVBQXNCQyxNQUF0QixFQUE4QkMsUUFBOUIsQ0FBUDtBQUFpRDtBQUNoRyxTQUFTbEIsZ0JBQVQsQ0FBMEJnQixNQUExQixFQUFrQ0MsTUFBbEMsRUFBMENDLFFBQTFDLEVBQW9EO0FBQ3pELE1BQUlQLFVBQVUsOEVBQWdCTyxRQUFoQixFQUEwQixFQUFDTCxrQkFBa0IsSUFBbkIsRUFBMUIsQ0FBZDtBQUNBLFNBQU9aLFNBQVNrQixJQUFULENBQWNILE1BQWQsRUFBc0JDLE1BQXRCLEVBQThCTixPQUE5QixDQUFQO0FBQ0QiLCJmaWxlIjoibGluZS5qcyIsInNvdXJjZXNDb250ZW50IjpbImltcG9ydCBEaWZmIGZyb20gJy4vYmFzZSc7XG5pbXBvcnQge2dlbmVyYXRlT3B0aW9uc30gZnJvbSAnLi4vdXRpbC9wYXJhbXMnO1xuXG5leHBvcnQgY29uc3QgbGluZURpZmYgPSBuZXcgRGlmZigpO1xubGluZURpZmYudG9rZW5pemUgPSBmdW5jdGlvbih2YWx1ZSkge1xuICBsZXQgcmV0TGluZXMgPSBbXSxcbiAgICAgIGxpbmVzQW5kTmV3bGluZXMgPSB2YWx1ZS5zcGxpdCgvKFxcbnxcXHJcXG4pLyk7XG5cbiAgLy8gSWdub3JlIHRoZSBmaW5hbCBlbXB0eSB0b2tlbiB0aGF0IG9jY3VycyBpZiB0aGUgc3RyaW5nIGVuZHMgd2l0aCBhIG5ldyBsaW5lXG4gIGlmICghbGluZXNBbmROZXdsaW5lc1tsaW5lc0FuZE5ld2xpbmVzLmxlbmd0aCAtIDFdKSB7XG4gICAgbGluZXNBbmROZXdsaW5lcy5wb3AoKTtcbiAgfVxuXG4gIC8vIE1lcmdlIHRoZSBjb250ZW50IGFuZCBsaW5lIHNlcGFyYXRvcnMgaW50byBzaW5nbGUgdG9rZW5zXG4gIGZvciAobGV0IGkgPSAwOyBpIDwgbGluZXNBbmROZXdsaW5lcy5sZW5ndGg7IGkrKykge1xuICAgIGxldCBsaW5lID0gbGluZXNBbmROZXdsaW5lc1tpXTtcblxuICAgIGlmIChpICUgMiAmJiAhdGhpcy5vcHRpb25zLm5ld2xpbmVJc1Rva2VuKSB7XG4gICAgICByZXRMaW5lc1tyZXRMaW5lcy5sZW5ndGggLSAxXSArPSBsaW5lO1xuICAgIH0gZWxzZSB7XG4gICAgICBpZiAodGhpcy5vcHRpb25zLmlnbm9yZVdoaXRlc3BhY2UpIHtcbiAgICAgICAgbGluZSA9IGxpbmUudHJpbSgpO1xuICAgICAgfVxuICAgICAgcmV0TGluZXMucHVzaChsaW5lKTtcbiAgICB9XG4gIH1cblxuICByZXR1cm4gcmV0TGluZXM7XG59O1xuXG5leHBvcnQgZnVuY3Rpb24gZGlmZkxpbmVzKG9sZFN0ciwgbmV3U3RyLCBjYWxsYmFjaykgeyByZXR1cm4gbGluZURpZmYuZGlmZihvbGRTdHIsIG5ld1N0ciwgY2FsbGJhY2spOyB9XG5leHBvcnQgZnVuY3Rpb24gZGlmZlRyaW1tZWRMaW5lcyhvbGRTdHIsIG5ld1N0ciwgY2FsbGJhY2spIHtcbiAgbGV0IG9wdGlvbnMgPSBnZW5lcmF0ZU9wdGlvbnMoY2FsbGJhY2ssIHtpZ25vcmVXaGl0ZXNwYWNlOiB0cnVlfSk7XG4gIHJldHVybiBsaW5lRGlmZi5kaWZmKG9sZFN0ciwgbmV3U3RyLCBvcHRpb25zKTtcbn1cbiJdfQ==
+
+
+/***/ }),
+/* 6 */
+/***/ (function(module, exports, __webpack_require__) {
+
+	/*istanbul ignore start*/'use strict';
+
+	exports.__esModule = true;
+	exports.sentenceDiff = undefined;
+	exports. /*istanbul ignore end*/diffSentences = diffSentences;
+
+	var /*istanbul ignore start*/_base = __webpack_require__(1) /*istanbul ignore end*/;
+
+	/*istanbul ignore start*/var _base2 = _interopRequireDefault(_base);
+
+	function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
+
+	/*istanbul ignore end*/var sentenceDiff = /*istanbul ignore start*/exports. /*istanbul ignore end*/sentenceDiff = new /*istanbul ignore start*/_base2['default'] /*istanbul ignore end*/();
+	sentenceDiff.tokenize = function (value) {
+	  return value.split(/(\S.+?[.!?])(?=\s+|$)/);
+	};
+
+	function diffSentences(oldStr, newStr, callback) {
+	  return sentenceDiff.diff(oldStr, newStr, callback);
+	}
+	//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9kaWZmL3NlbnRlbmNlLmpzIl0sIm5hbWVzIjpbImRpZmZTZW50ZW5jZXMiLCJzZW50ZW5jZURpZmYiLCJ0b2tlbml6ZSIsInZhbHVlIiwic3BsaXQiLCJvbGRTdHIiLCJuZXdTdHIiLCJjYWxsYmFjayIsImRpZmYiXSwibWFwcGluZ3MiOiI7Ozs7Z0NBUWdCQSxhLEdBQUFBLGE7O0FBUmhCOzs7Ozs7dUJBR08sSUFBTUMsdUZBQWUsd0VBQXJCO0FBQ1BBLGFBQWFDLFFBQWIsR0FBd0IsVUFBU0MsS0FBVCxFQUFnQjtBQUN0QyxTQUFPQSxNQUFNQyxLQUFOLENBQVksdUJBQVosQ0FBUDtBQUNELENBRkQ7O0FBSU8sU0FBU0osYUFBVCxDQUF1QkssTUFBdkIsRUFBK0JDLE1BQS9CLEVBQXVDQyxRQUF2QyxFQUFpRDtBQUFFLFNBQU9OLGFBQWFPLElBQWIsQ0FBa0JILE1BQWxCLEVBQTBCQyxNQUExQixFQUFrQ0MsUUFBbEMsQ0FBUDtBQUFxRCIsImZpbGUiOiJzZW50ZW5jZS5qcyIsInNvdXJjZXNDb250ZW50IjpbImltcG9ydCBEaWZmIGZyb20gJy4vYmFzZSc7XG5cblxuZXhwb3J0IGNvbnN0IHNlbnRlbmNlRGlmZiA9IG5ldyBEaWZmKCk7XG5zZW50ZW5jZURpZmYudG9rZW5pemUgPSBmdW5jdGlvbih2YWx1ZSkge1xuICByZXR1cm4gdmFsdWUuc3BsaXQoLyhcXFMuKz9bLiE/XSkoPz1cXHMrfCQpLyk7XG59O1xuXG5leHBvcnQgZnVuY3Rpb24gZGlmZlNlbnRlbmNlcyhvbGRTdHIsIG5ld1N0ciwgY2FsbGJhY2spIHsgcmV0dXJuIHNlbnRlbmNlRGlmZi5kaWZmKG9sZFN0ciwgbmV3U3RyLCBjYWxsYmFjayk7IH1cbiJdfQ==
+
+
+/***/ }),
+/* 7 */
+/***/ (function(module, exports, __webpack_require__) {
+
+	/*istanbul ignore start*/'use strict';
+
+	exports.__esModule = true;
+	exports.cssDiff = undefined;
+	exports. /*istanbul ignore end*/diffCss = diffCss;
+
+	var /*istanbul ignore start*/_base = __webpack_require__(1) /*istanbul ignore end*/;
+
+	/*istanbul ignore start*/var _base2 = _interopRequireDefault(_base);
+
+	function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
+
+	/*istanbul ignore end*/var cssDiff = /*istanbul ignore start*/exports. /*istanbul ignore end*/cssDiff = new /*istanbul ignore start*/_base2['default'] /*istanbul ignore end*/();
+	cssDiff.tokenize = function (value) {
+	  return value.split(/([{}:;,]|\s+)/);
+	};
+
+	function diffCss(oldStr, newStr, callback) {
+	  return cssDiff.diff(oldStr, newStr, callback);
+	}
+	//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9kaWZmL2Nzcy5qcyJdLCJuYW1lcyI6WyJkaWZmQ3NzIiwiY3NzRGlmZiIsInRva2VuaXplIiwidmFsdWUiLCJzcGxpdCIsIm9sZFN0ciIsIm5ld1N0ciIsImNhbGxiYWNrIiwiZGlmZiJdLCJtYXBwaW5ncyI6Ijs7OztnQ0FPZ0JBLE8sR0FBQUEsTzs7QUFQaEI7Ozs7Ozt1QkFFTyxJQUFNQyw2RUFBVSx3RUFBaEI7QUFDUEEsUUFBUUMsUUFBUixHQUFtQixVQUFTQyxLQUFULEVBQWdCO0FBQ2pDLFNBQU9BLE1BQU1DLEtBQU4sQ0FBWSxlQUFaLENBQVA7QUFDRCxDQUZEOztBQUlPLFNBQVNKLE9BQVQsQ0FBaUJLLE1BQWpCLEVBQXlCQyxNQUF6QixFQUFpQ0MsUUFBakMsRUFBMkM7QUFBRSxTQUFPTixRQUFRTyxJQUFSLENBQWFILE1BQWIsRUFBcUJDLE1BQXJCLEVBQTZCQyxRQUE3QixDQUFQO0FBQWdEIiwiZmlsZSI6ImNzcy5qcyIsInNvdXJjZXNDb250ZW50IjpbImltcG9ydCBEaWZmIGZyb20gJy4vYmFzZSc7XG5cbmV4cG9ydCBjb25zdCBjc3NEaWZmID0gbmV3IERpZmYoKTtcbmNzc0RpZmYudG9rZW5pemUgPSBmdW5jdGlvbih2YWx1ZSkge1xuICByZXR1cm4gdmFsdWUuc3BsaXQoLyhbe306OyxdfFxccyspLyk7XG59O1xuXG5leHBvcnQgZnVuY3Rpb24gZGlmZkNzcyhvbGRTdHIsIG5ld1N0ciwgY2FsbGJhY2spIHsgcmV0dXJuIGNzc0RpZmYuZGlmZihvbGRTdHIsIG5ld1N0ciwgY2FsbGJhY2spOyB9XG4iXX0=
+
+
+/***/ }),
+/* 8 */
+/***/ (function(module, exports, __webpack_require__) {
+
+	/*istanbul ignore start*/'use strict';
+
+	exports.__esModule = true;
+	exports.jsonDiff = undefined;
+
+	var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
+
+	exports. /*istanbul ignore end*/diffJson = diffJson;
+	/*istanbul ignore start*/exports. /*istanbul ignore end*/canonicalize = canonicalize;
+
+	var /*istanbul ignore start*/_base = __webpack_require__(1) /*istanbul ignore end*/;
+
+	/*istanbul ignore start*/var _base2 = _interopRequireDefault(_base);
+
+	/*istanbul ignore end*/var /*istanbul ignore start*/_line = __webpack_require__(5) /*istanbul ignore end*/;
+
+	/*istanbul ignore start*/function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
+
+	/*istanbul ignore end*/var objectPrototypeToString = Object.prototype.toString;
+
+	var jsonDiff = /*istanbul ignore start*/exports. /*istanbul ignore end*/jsonDiff = new /*istanbul ignore start*/_base2['default'] /*istanbul ignore end*/();
+	// Discriminate between two lines of pretty-printed, serialized JSON where one of them has a
+	// dangling comma and the other doesn't. Turns out including the dangling comma yields the nicest output:
+	jsonDiff.useLongestToken = true;
+
+	jsonDiff.tokenize = /*istanbul ignore start*/_line.lineDiff /*istanbul ignore end*/.tokenize;
+	jsonDiff.castInput = function (value) {
+	  /*istanbul ignore start*/var _options = /*istanbul ignore end*/this.options,
+	      undefinedReplacement = _options.undefinedReplacement,
+	      _options$stringifyRep = _options.stringifyReplacer,
+	      stringifyReplacer = _options$stringifyRep === undefined ? function (k, v) /*istanbul ignore start*/{
+	    return (/*istanbul ignore end*/typeof v === 'undefined' ? undefinedReplacement : v
+	    );
+	  } : _options$stringifyRep;
+
+
+	  return typeof value === 'string' ? value : JSON.stringify(canonicalize(value, null, null, stringifyReplacer), stringifyReplacer, '  ');
+	};
+	jsonDiff.equals = function (left, right) {
+	  return (/*istanbul ignore start*/_base2['default'] /*istanbul ignore end*/.prototype.equals.call(jsonDiff, left.replace(/,([\r\n])/g, '$1'), right.replace(/,([\r\n])/g, '$1'))
+	  );
+	};
+
+	function diffJson(oldObj, newObj, options) {
+	  return jsonDiff.diff(oldObj, newObj, options);
+	}
+
+	// This function handles the presence of circular references by bailing out when encountering an
+	// object that is already on the "stack" of items being processed. Accepts an optional replacer
+	function canonicalize(obj, stack, replacementStack, replacer, key) {
+	  stack = stack || [];
+	  replacementStack = replacementStack || [];
+
+	  if (replacer) {
+	    obj = replacer(key, obj);
+	  }
+
+	  var i = /*istanbul ignore start*/void 0 /*istanbul ignore end*/;
+
+	  for (i = 0; i < stack.length; i += 1) {
+	    if (stack[i] === obj) {
+	      return replacementStack[i];
+	    }
+	  }
+
+	  var canonicalizedObj = /*istanbul ignore start*/void 0 /*istanbul ignore end*/;
+
+	  if ('[object Array]' === objectPrototypeToString.call(obj)) {
+	    stack.push(obj);
+	    canonicalizedObj = new Array(obj.length);
+	    replacementStack.push(canonicalizedObj);
+	    for (i = 0; i < obj.length; i += 1) {
+	      canonicalizedObj[i] = canonicalize(obj[i], stack, replacementStack, replacer, key);
+	    }
+	    stack.pop();
+	    replacementStack.pop();
+	    return canonicalizedObj;
+	  }
+
+	  if (obj && obj.toJSON) {
+	    obj = obj.toJSON();
+	  }
+
+	  if ( /*istanbul ignore start*/(typeof /*istanbul ignore end*/obj === 'undefined' ? 'undefined' : _typeof(obj)) === 'object' && obj !== null) {
+	    stack.push(obj);
+	    canonicalizedObj = {};
+	    replacementStack.push(canonicalizedObj);
+	    var sortedKeys = [],
+	        _key = /*istanbul ignore start*/void 0 /*istanbul ignore end*/;
+	    for (_key in obj) {
+	      /* istanbul ignore else */
+	      if (obj.hasOwnProperty(_key)) {
+	        sortedKeys.push(_key);
+	      }
+	    }
+	    sortedKeys.sort();
+	    for (i = 0; i < sortedKeys.length; i += 1) {
+	      _key = sortedKeys[i];
+	      canonicalizedObj[_key] = canonicalize(obj[_key], stack, replacementStack, replacer, _key);
+	    }
+	    stack.pop();
+	    replacementStack.pop();
+	  } else {
+	    canonicalizedObj = obj;
+	  }
+	  return canonicalizedObj;
+	}
+	//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9kaWZmL2pzb24uanMiXSwibmFtZXMiOlsiZGlmZkpzb24iLCJjYW5vbmljYWxpemUiLCJvYmplY3RQcm90b3R5cGVUb1N0cmluZyIsIk9iamVjdCIsInByb3RvdHlwZSIsInRvU3RyaW5nIiwianNvbkRpZmYiLCJ1c2VMb25nZXN0VG9rZW4iLCJ0b2tlbml6ZSIsImNhc3RJbnB1dCIsInZhbHVlIiwib3B0aW9ucyIsInVuZGVmaW5lZFJlcGxhY2VtZW50Iiwic3RyaW5naWZ5UmVwbGFjZXIiLCJrIiwidiIsIkpTT04iLCJzdHJpbmdpZnkiLCJlcXVhbHMiLCJsZWZ0IiwicmlnaHQiLCJjYWxsIiwicmVwbGFjZSIsIm9sZE9iaiIsIm5ld09iaiIsImRpZmYiLCJvYmoiLCJzdGFjayIsInJlcGxhY2VtZW50U3RhY2siLCJyZXBsYWNlciIsImtleSIsImkiLCJsZW5ndGgiLCJjYW5vbmljYWxpemVkT2JqIiwicHVzaCIsIkFycmF5IiwicG9wIiwidG9KU09OIiwic29ydGVkS2V5cyIsImhhc093blByb3BlcnR5Iiwic29ydCJdLCJtYXBwaW5ncyI6Ijs7Ozs7OztnQ0FxQmdCQSxRLEdBQUFBLFE7eURBSUFDLFksR0FBQUEsWTs7QUF6QmhCOzs7O3VCQUNBOzs7O3VCQUVBLElBQU1DLDBCQUEwQkMsT0FBT0MsU0FBUCxDQUFpQkMsUUFBakQ7O0FBR08sSUFBTUMsK0VBQVcsd0VBQWpCO0FBQ1A7QUFDQTtBQUNBQSxTQUFTQyxlQUFULEdBQTJCLElBQTNCOztBQUVBRCxTQUFTRSxRQUFULEdBQW9CLGdFQUFTQSxRQUE3QjtBQUNBRixTQUFTRyxTQUFULEdBQXFCLFVBQVNDLEtBQVQsRUFBZ0I7QUFBQSxpRUFDK0UsS0FBS0MsT0FEcEY7QUFBQSxNQUM1QkMsb0JBRDRCLFlBQzVCQSxvQkFENEI7QUFBQSx1Q0FDTkMsaUJBRE07QUFBQSxNQUNOQSxpQkFETSx5Q0FDYyxVQUFDQyxDQUFELEVBQUlDLENBQUo7QUFBQSxtQ0FBVSxPQUFPQSxDQUFQLEtBQWEsV0FBYixHQUEyQkgsb0JBQTNCLEdBQWtERztBQUE1RDtBQUFBLEdBRGQ7OztBQUduQyxTQUFPLE9BQU9MLEtBQVAsS0FBaUIsUUFBakIsR0FBNEJBLEtBQTVCLEdBQW9DTSxLQUFLQyxTQUFMLENBQWVoQixhQUFhUyxLQUFiLEVBQW9CLElBQXBCLEVBQTBCLElBQTFCLEVBQWdDRyxpQkFBaEMsQ0FBZixFQUFtRUEsaUJBQW5FLEVBQXNGLElBQXRGLENBQTNDO0FBQ0QsQ0FKRDtBQUtBUCxTQUFTWSxNQUFULEdBQWtCLFVBQVNDLElBQVQsRUFBZUMsS0FBZixFQUFzQjtBQUN0QyxTQUFPLG9FQUFLaEIsU0FBTCxDQUFlYyxNQUFmLENBQXNCRyxJQUF0QixDQUEyQmYsUUFBM0IsRUFBcUNhLEtBQUtHLE9BQUwsQ0FBYSxZQUFiLEVBQTJCLElBQTNCLENBQXJDLEVBQXVFRixNQUFNRSxPQUFOLENBQWMsWUFBZCxFQUE0QixJQUE1QixDQUF2RTtBQUFQO0FBQ0QsQ0FGRDs7QUFJTyxTQUFTdEIsUUFBVCxDQUFrQnVCLE1BQWxCLEVBQTBCQyxNQUExQixFQUFrQ2IsT0FBbEMsRUFBMkM7QUFBRSxTQUFPTCxTQUFTbUIsSUFBVCxDQUFjRixNQUFkLEVBQXNCQyxNQUF0QixFQUE4QmIsT0FBOUIsQ0FBUDtBQUFnRDs7QUFFcEc7QUFDQTtBQUNPLFNBQVNWLFlBQVQsQ0FBc0J5QixHQUF0QixFQUEyQkMsS0FBM0IsRUFBa0NDLGdCQUFsQyxFQUFvREMsUUFBcEQsRUFBOERDLEdBQTlELEVBQW1FO0FBQ3hFSCxVQUFRQSxTQUFTLEVBQWpCO0FBQ0FDLHFCQUFtQkEsb0JBQW9CLEVBQXZDOztBQUVBLE1BQUlDLFFBQUosRUFBYztBQUNaSCxVQUFNRyxTQUFTQyxHQUFULEVBQWNKLEdBQWQsQ0FBTjtBQUNEOztBQUVELE1BQUlLLG1DQUFKOztBQUVBLE9BQUtBLElBQUksQ0FBVCxFQUFZQSxJQUFJSixNQUFNSyxNQUF0QixFQUE4QkQsS0FBSyxDQUFuQyxFQUFzQztBQUNwQyxRQUFJSixNQUFNSSxDQUFOLE1BQWFMLEdBQWpCLEVBQXNCO0FBQ3BCLGFBQU9FLGlCQUFpQkcsQ0FBakIsQ0FBUDtBQUNEO0FBQ0Y7O0FBRUQsTUFBSUUsa0RBQUo7O0FBRUEsTUFBSSxxQkFBcUIvQix3QkFBd0JtQixJQUF4QixDQUE2QkssR0FBN0IsQ0FBekIsRUFBNEQ7QUFDMURDLFVBQU1PLElBQU4sQ0FBV1IsR0FBWDtBQUNBTyx1QkFBbUIsSUFBSUUsS0FBSixDQUFVVCxJQUFJTSxNQUFkLENBQW5CO0FBQ0FKLHFCQUFpQk0sSUFBakIsQ0FBc0JELGdCQUF0QjtBQUNBLFNBQUtGLElBQUksQ0FBVCxFQUFZQSxJQUFJTCxJQUFJTSxNQUFwQixFQUE0QkQsS0FBSyxDQUFqQyxFQUFvQztBQUNsQ0UsdUJBQWlCRixDQUFqQixJQUFzQjlCLGFBQWF5QixJQUFJSyxDQUFKLENBQWIsRUFBcUJKLEtBQXJCLEVBQTRCQyxnQkFBNUIsRUFBOENDLFFBQTlDLEVBQXdEQyxHQUF4RCxDQUF0QjtBQUNEO0FBQ0RILFVBQU1TLEdBQU47QUFDQVIscUJBQWlCUSxHQUFqQjtBQUNBLFdBQU9ILGdCQUFQO0FBQ0Q7O0FBRUQsTUFBSVAsT0FBT0EsSUFBSVcsTUFBZixFQUF1QjtBQUNyQlgsVUFBTUEsSUFBSVcsTUFBSixFQUFOO0FBQ0Q7O0FBRUQsTUFBSSx5REFBT1gsR0FBUCx5Q0FBT0EsR0FBUCxPQUFlLFFBQWYsSUFBMkJBLFFBQVEsSUFBdkMsRUFBNkM7QUFDM0NDLFVBQU1PLElBQU4sQ0FBV1IsR0FBWDtBQUNBTyx1QkFBbUIsRUFBbkI7QUFDQUwscUJBQWlCTSxJQUFqQixDQUFzQkQsZ0JBQXRCO0FBQ0EsUUFBSUssYUFBYSxFQUFqQjtBQUFBLFFBQ0lSLHNDQURKO0FBRUEsU0FBS0EsSUFBTCxJQUFZSixHQUFaLEVBQWlCO0FBQ2Y7QUFDQSxVQUFJQSxJQUFJYSxjQUFKLENBQW1CVCxJQUFuQixDQUFKLEVBQTZCO0FBQzNCUSxtQkFBV0osSUFBWCxDQUFnQkosSUFBaEI7QUFDRDtBQUNGO0FBQ0RRLGVBQVdFLElBQVg7QUFDQSxTQUFLVCxJQUFJLENBQVQsRUFBWUEsSUFBSU8sV0FBV04sTUFBM0IsRUFBbUNELEtBQUssQ0FBeEMsRUFBMkM7QUFDekNELGFBQU1RLFdBQVdQLENBQVgsQ0FBTjtBQUNBRSx1QkFBaUJILElBQWpCLElBQXdCN0IsYUFBYXlCLElBQUlJLElBQUosQ0FBYixFQUF1QkgsS0FBdkIsRUFBOEJDLGdCQUE5QixFQUFnREMsUUFBaEQsRUFBMERDLElBQTFELENBQXhCO0FBQ0Q7QUFDREgsVUFBTVMsR0FBTjtBQUNBUixxQkFBaUJRLEdBQWpCO0FBQ0QsR0FuQkQsTUFtQk87QUFDTEgsdUJBQW1CUCxHQUFuQjtBQUNEO0FBQ0QsU0FBT08sZ0JBQVA7QUFDRCIsImZpbGUiOiJqc29uLmpzIiwic291cmNlc0NvbnRlbnQiOlsiaW1wb3J0IERpZmYgZnJvbSAnLi9iYXNlJztcbmltcG9ydCB7bGluZURpZmZ9IGZyb20gJy4vbGluZSc7XG5cbmNvbnN0IG9iamVjdFByb3RvdHlwZVRvU3RyaW5nID0gT2JqZWN0LnByb3RvdHlwZS50b1N0cmluZztcblxuXG5leHBvcnQgY29uc3QganNvbkRpZmYgPSBuZXcgRGlmZigpO1xuLy8gRGlzY3JpbWluYXRlIGJldHdlZW4gdHdvIGxpbmVzIG9mIHByZXR0eS1wcmludGVkLCBzZXJpYWxpemVkIEpTT04gd2hlcmUgb25lIG9mIHRoZW0gaGFzIGFcbi8vIGRhbmdsaW5nIGNvbW1hIGFuZCB0aGUgb3RoZXIgZG9lc24ndC4gVHVybnMgb3V0IGluY2x1ZGluZyB0aGUgZGFuZ2xpbmcgY29tbWEgeWllbGRzIHRoZSBuaWNlc3Qgb3V0cHV0OlxuanNvbkRpZmYudXNlTG9uZ2VzdFRva2VuID0gdHJ1ZTtcblxuanNvbkRpZmYudG9rZW5pemUgPSBsaW5lRGlmZi50b2tlbml6ZTtcbmpzb25EaWZmLmNhc3RJbnB1dCA9IGZ1bmN0aW9uKHZhbHVlKSB7XG4gIGNvbnN0IHt1bmRlZmluZWRSZXBsYWNlbWVudCwgc3RyaW5naWZ5UmVwbGFjZXIgPSAoaywgdikgPT4gdHlwZW9mIHYgPT09ICd1bmRlZmluZWQnID8gdW5kZWZpbmVkUmVwbGFjZW1lbnQgOiB2fSA9IHRoaXMub3B0aW9ucztcblxuICByZXR1cm4gdHlwZW9mIHZhbHVlID09PSAnc3RyaW5nJyA/IHZhbHVlIDogSlNPTi5zdHJpbmdpZnkoY2Fub25pY2FsaXplKHZhbHVlLCBudWxsLCBudWxsLCBzdHJpbmdpZnlSZXBsYWNlciksIHN0cmluZ2lmeVJlcGxhY2VyLCAnICAnKTtcbn07XG5qc29uRGlmZi5lcXVhbHMgPSBmdW5jdGlvbihsZWZ0LCByaWdodCkge1xuICByZXR1cm4gRGlmZi5wcm90b3R5cGUuZXF1YWxzLmNhbGwoanNvbkRpZmYsIGxlZnQucmVwbGFjZSgvLChbXFxyXFxuXSkvZywgJyQxJyksIHJpZ2h0LnJlcGxhY2UoLywoW1xcclxcbl0pL2csICckMScpKTtcbn07XG5cbmV4cG9ydCBmdW5jdGlvbiBkaWZmSnNvbihvbGRPYmosIG5ld09iaiwgb3B0aW9ucykgeyByZXR1cm4ganNvbkRpZmYuZGlmZihvbGRPYmosIG5ld09iaiwgb3B0aW9ucyk7IH1cblxuLy8gVGhpcyBmdW5jdGlvbiBoYW5kbGVzIHRoZSBwcmVzZW5jZSBvZiBjaXJjdWxhciByZWZlcmVuY2VzIGJ5IGJhaWxpbmcgb3V0IHdoZW4gZW5jb3VudGVyaW5nIGFuXG4vLyBvYmplY3QgdGhhdCBpcyBhbHJlYWR5IG9uIHRoZSBcInN0YWNrXCIgb2YgaXRlbXMgYmVpbmcgcHJvY2Vzc2VkLiBBY2NlcHRzIGFuIG9wdGlvbmFsIHJlcGxhY2VyXG5leHBvcnQgZnVuY3Rpb24gY2Fub25pY2FsaXplKG9iaiwgc3RhY2ssIHJlcGxhY2VtZW50U3RhY2ssIHJlcGxhY2VyLCBrZXkpIHtcbiAgc3RhY2sgPSBzdGFjayB8fCBbXTtcbiAgcmVwbGFjZW1lbnRTdGFjayA9IHJlcGxhY2VtZW50U3RhY2sgfHwgW107XG5cbiAgaWYgKHJlcGxhY2VyKSB7XG4gICAgb2JqID0gcmVwbGFjZXIoa2V5LCBvYmopO1xuICB9XG5cbiAgbGV0IGk7XG5cbiAgZm9yIChpID0gMDsgaSA8IHN0YWNrLmxlbmd0aDsgaSArPSAxKSB7XG4gICAgaWYgKHN0YWNrW2ldID09PSBvYmopIHtcbiAgICAgIHJldHVybiByZXBsYWNlbWVudFN0YWNrW2ldO1xuICAgIH1cbiAgfVxuXG4gIGxldCBjYW5vbmljYWxpemVkT2JqO1xuXG4gIGlmICgnW29iamVjdCBBcnJheV0nID09PSBvYmplY3RQcm90b3R5cGVUb1N0cmluZy5jYWxsKG9iaikpIHtcbiAgICBzdGFjay5wdXNoKG9iaik7XG4gICAgY2Fub25pY2FsaXplZE9iaiA9IG5ldyBBcnJheShvYmoubGVuZ3RoKTtcbiAgICByZXBsYWNlbWVudFN0YWNrLnB1c2goY2Fub25pY2FsaXplZE9iaik7XG4gICAgZm9yIChpID0gMDsgaSA8IG9iai5sZW5ndGg7IGkgKz0gMSkge1xuICAgICAgY2Fub25pY2FsaXplZE9ialtpXSA9IGNhbm9uaWNhbGl6ZShvYmpbaV0sIHN0YWNrLCByZXBsYWNlbWVudFN0YWNrLCByZXBsYWNlciwga2V5KTtcbiAgICB9XG4gICAgc3RhY2sucG9wKCk7XG4gICAgcmVwbGFjZW1lbnRTdGFjay5wb3AoKTtcbiAgICByZXR1cm4gY2Fub25pY2FsaXplZE9iajtcbiAgfVxuXG4gIGlmIChvYmogJiYgb2JqLnRvSlNPTikge1xuICAgIG9iaiA9IG9iai50b0pTT04oKTtcbiAgfVxuXG4gIGlmICh0eXBlb2Ygb2JqID09PSAnb2JqZWN0JyAmJiBvYmogIT09IG51bGwpIHtcbiAgICBzdGFjay5wdXNoKG9iaik7XG4gICAgY2Fub25pY2FsaXplZE9iaiA9IHt9O1xuICAgIHJlcGxhY2VtZW50U3RhY2sucHVzaChjYW5vbmljYWxpemVkT2JqKTtcbiAgICBsZXQgc29ydGVkS2V5cyA9IFtdLFxuICAgICAgICBrZXk7XG4gICAgZm9yIChrZXkgaW4gb2JqKSB7XG4gICAgICAvKiBpc3RhbmJ1bCBpZ25vcmUgZWxzZSAqL1xuICAgICAgaWYgKG9iai5oYXNPd25Qcm9wZXJ0eShrZXkpKSB7XG4gICAgICAgIHNvcnRlZEtleXMucHVzaChrZXkpO1xuICAgICAgfVxuICAgIH1cbiAgICBzb3J0ZWRLZXlzLnNvcnQoKTtcbiAgICBmb3IgKGkgPSAwOyBpIDwgc29ydGVkS2V5cy5sZW5ndGg7IGkgKz0gMSkge1xuICAgICAga2V5ID0gc29ydGVkS2V5c1tpXTtcbiAgICAgIGNhbm9uaWNhbGl6ZWRPYmpba2V5XSA9IGNhbm9uaWNhbGl6ZShvYmpba2V5XSwgc3RhY2ssIHJlcGxhY2VtZW50U3RhY2ssIHJlcGxhY2VyLCBrZXkpO1xuICAgIH1cbiAgICBzdGFjay5wb3AoKTtcbiAgICByZXBsYWNlbWVudFN0YWNrLnBvcCgpO1xuICB9IGVsc2Uge1xuICAgIGNhbm9uaWNhbGl6ZWRPYmogPSBvYmo7XG4gIH1cbiAgcmV0dXJuIGNhbm9uaWNhbGl6ZWRPYmo7XG59XG4iXX0=
+
+
+/***/ }),
+/* 9 */
+/***/ (function(module, exports, __webpack_require__) {
+
+	/*istanbul ignore start*/'use strict';
+
+	exports.__esModule = true;
+	exports.arrayDiff = undefined;
+	exports. /*istanbul ignore end*/diffArrays = diffArrays;
+
+	var /*istanbul ignore start*/_base = __webpack_require__(1) /*istanbul ignore end*/;
+
+	/*istanbul ignore start*/var _base2 = _interopRequireDefault(_base);
+
+	function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
+
+	/*istanbul ignore end*/var arrayDiff = /*istanbul ignore start*/exports. /*istanbul ignore end*/arrayDiff = new /*istanbul ignore start*/_base2['default'] /*istanbul ignore end*/();
+	arrayDiff.tokenize = function (value) {
+	  return value.slice();
+	};
+	arrayDiff.join = arrayDiff.removeEmpty = function (value) {
+	  return value;
+	};
+
+	function diffArrays(oldArr, newArr, callback) {
+	  return arrayDiff.diff(oldArr, newArr, callback);
+	}
+	//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9kaWZmL2FycmF5LmpzIl0sIm5hbWVzIjpbImRpZmZBcnJheXMiLCJhcnJheURpZmYiLCJ0b2tlbml6ZSIsInZhbHVlIiwic2xpY2UiLCJqb2luIiwicmVtb3ZlRW1wdHkiLCJvbGRBcnIiLCJuZXdBcnIiLCJjYWxsYmFjayIsImRpZmYiXSwibWFwcGluZ3MiOiI7Ozs7Z0NBVWdCQSxVLEdBQUFBLFU7O0FBVmhCOzs7Ozs7dUJBRU8sSUFBTUMsaUZBQVksd0VBQWxCO0FBQ1BBLFVBQVVDLFFBQVYsR0FBcUIsVUFBU0MsS0FBVCxFQUFnQjtBQUNuQyxTQUFPQSxNQUFNQyxLQUFOLEVBQVA7QUFDRCxDQUZEO0FBR0FILFVBQVVJLElBQVYsR0FBaUJKLFVBQVVLLFdBQVYsR0FBd0IsVUFBU0gsS0FBVCxFQUFnQjtBQUN2RCxTQUFPQSxLQUFQO0FBQ0QsQ0FGRDs7QUFJTyxTQUFTSCxVQUFULENBQW9CTyxNQUFwQixFQUE0QkMsTUFBNUIsRUFBb0NDLFFBQXBDLEVBQThDO0FBQUUsU0FBT1IsVUFBVVMsSUFBVixDQUFlSCxNQUFmLEVBQXVCQyxNQUF2QixFQUErQkMsUUFBL0IsQ0FBUDtBQUFrRCIsImZpbGUiOiJhcnJheS5qcyIsInNvdXJjZXNDb250ZW50IjpbImltcG9ydCBEaWZmIGZyb20gJy4vYmFzZSc7XG5cbmV4cG9ydCBjb25zdCBhcnJheURpZmYgPSBuZXcgRGlmZigpO1xuYXJyYXlEaWZmLnRva2VuaXplID0gZnVuY3Rpb24odmFsdWUpIHtcbiAgcmV0dXJuIHZhbHVlLnNsaWNlKCk7XG59O1xuYXJyYXlEaWZmLmpvaW4gPSBhcnJheURpZmYucmVtb3ZlRW1wdHkgPSBmdW5jdGlvbih2YWx1ZSkge1xuICByZXR1cm4gdmFsdWU7XG59O1xuXG5leHBvcnQgZnVuY3Rpb24gZGlmZkFycmF5cyhvbGRBcnIsIG5ld0FyciwgY2FsbGJhY2spIHsgcmV0dXJuIGFycmF5RGlmZi5kaWZmKG9sZEFyciwgbmV3QXJyLCBjYWxsYmFjayk7IH1cbiJdfQ==
+
+
+/***/ }),
+/* 10 */
+/***/ (function(module, exports, __webpack_require__) {
+
+	/*istanbul ignore start*/'use strict';
+
+	exports.__esModule = true;
+	exports. /*istanbul ignore end*/applyPatch = applyPatch;
+	/*istanbul ignore start*/exports. /*istanbul ignore end*/applyPatches = applyPatches;
+
+	var /*istanbul ignore start*/_parse = __webpack_require__(11) /*istanbul ignore end*/;
+
+	var /*istanbul ignore start*/_distanceIterator = __webpack_require__(12) /*istanbul ignore end*/;
+
+	/*istanbul ignore start*/var _distanceIterator2 = _interopRequireDefault(_distanceIterator);
+
+	function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
+
+	/*istanbul ignore end*/function applyPatch(source, uniDiff) {
+	  /*istanbul ignore start*/var /*istanbul ignore end*/options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
+
+	  if (typeof uniDiff === 'string') {
+	    uniDiff = /*istanbul ignore start*/(0, _parse.parsePatch) /*istanbul ignore end*/(uniDiff);
+	  }
+
+	  if (Array.isArray(uniDiff)) {
+	    if (uniDiff.length > 1) {
+	      throw new Error('applyPatch only works with a single input.');
+	    }
+
+	    uniDiff = uniDiff[0];
+	  }
+
+	  // Apply the diff to the input
+	  var lines = source.split(/\r\n|[\n\v\f\r\x85]/),
+	      delimiters = source.match(/\r\n|[\n\v\f\r\x85]/g) || [],
+	      hunks = uniDiff.hunks,
+	      compareLine = options.compareLine || function (lineNumber, line, operation, patchContent) /*istanbul ignore start*/{
+	    return (/*istanbul ignore end*/line === patchContent
+	    );
+	  },
+	      errorCount = 0,
+	      fuzzFactor = options.fuzzFactor || 0,
+	      minLine = 0,
+	      offset = 0,
+	      removeEOFNL = /*istanbul ignore start*/void 0 /*istanbul ignore end*/,
+	      addEOFNL = /*istanbul ignore start*/void 0 /*istanbul ignore end*/;
+
+	  /**
+	   * Checks if the hunk exactly fits on the provided location
+	   */
+	  function hunkFits(hunk, toPos) {
+	    for (var j = 0; j < hunk.lines.length; j++) {
+	      var line = hunk.lines[j],
+	          operation = line.length > 0 ? line[0] : ' ',
+	          content = line.length > 0 ? line.substr(1) : line;
+
+	      if (operation === ' ' || operation === '-') {
+	        // Context sanity check
+	        if (!compareLine(toPos + 1, lines[toPos], operation, content)) {
+	          errorCount++;
+
+	          if (errorCount > fuzzFactor) {
+	            return false;
+	          }
+	        }
+	        toPos++;
+	      }
+	    }
+
+	    return true;
+	  }
+
+	  // Search best fit offsets for each hunk based on the previous ones
+	  for (var i = 0; i < hunks.length; i++) {
+	    var hunk = hunks[i],
+	        maxLine = lines.length - hunk.oldLines,
+	        localOffset = 0,
+	        toPos = offset + hunk.oldStart - 1;
+
+	    var iterator = /*istanbul ignore start*/(0, _distanceIterator2['default']) /*istanbul ignore end*/(toPos, minLine, maxLine);
+
+	    for (; localOffset !== undefined; localOffset = iterator()) {
+	      if (hunkFits(hunk, toPos + localOffset)) {
+	        hunk.offset = offset += localOffset;
+	        break;
+	      }
+	    }
+
+	    if (localOffset === undefined) {
+	      return false;
+	    }
+
+	    // Set lower text limit to end of the current hunk, so next ones don't try
+	    // to fit over already patched text
+	    minLine = hunk.offset + hunk.oldStart + hunk.oldLines;
+	  }
+
+	  // Apply patch hunks
+	  var diffOffset = 0;
+	  for (var _i = 0; _i < hunks.length; _i++) {
+	    var _hunk = hunks[_i],
+	        _toPos = _hunk.oldStart + _hunk.offset + diffOffset - 1;
+	    diffOffset += _hunk.newLines - _hunk.oldLines;
+
+	    if (_toPos < 0) {
+	      // Creating a new file
+	      _toPos = 0;
+	    }
+
+	    for (var j = 0; j < _hunk.lines.length; j++) {
+	      var line = _hunk.lines[j],
+	          operation = line.length > 0 ? line[0] : ' ',
+	          content = line.length > 0 ? line.substr(1) : line,
+	          delimiter = _hunk.linedelimiters[j];
+
+	      if (operation === ' ') {
+	        _toPos++;
+	      } else if (operation === '-') {
+	        lines.splice(_toPos, 1);
+	        delimiters.splice(_toPos, 1);
+	        /* istanbul ignore else */
+	      } else if (operation === '+') {
+	        lines.splice(_toPos, 0, content);
+	        delimiters.splice(_toPos, 0, delimiter);
+	        _toPos++;
+	      } else if (operation === '\\') {
+	        var previousOperation = _hunk.lines[j - 1] ? _hunk.lines[j - 1][0] : null;
+	        if (previousOperation === '+') {
+	          removeEOFNL = true;
+	        } else if (previousOperation === '-') {
+	          addEOFNL = true;
+	        }
+	      }
+	    }
+	  }
+
+	  // Handle EOFNL insertion/removal
+	  if (removeEOFNL) {
+	    while (!lines[lines.length - 1]) {
+	      lines.pop();
+	      delimiters.pop();
+	    }
+	  } else if (addEOFNL) {
+	    lines.push('');
+	    delimiters.push('\n');
+	  }
+	  for (var _k = 0; _k < lines.length - 1; _k++) {
+	    lines[_k] = lines[_k] + delimiters[_k];
+	  }
+	  return lines.join('');
+	}
+
+	// Wrapper that supports multiple file patches via callbacks.
+	function applyPatches(uniDiff, options) {
+	  if (typeof uniDiff === 'string') {
+	    uniDiff = /*istanbul ignore start*/(0, _parse.parsePatch) /*istanbul ignore end*/(uniDiff);
+	  }
+
+	  var currentIndex = 0;
+	  function processIndex() {
+	    var index = uniDiff[currentIndex++];
+	    if (!index) {
+	      return options.complete();
+	    }
+
+	    options.loadFile(index, function (err, data) {
+	      if (err) {
+	        return options.complete(err);
+	      }
+
+	      var updatedContent = applyPatch(data, index, options);
+	      options.patched(index, updatedContent, function (err) {
+	        if (err) {
+	          return options.complete(err);
+	        }
+
+	        processIndex();
+	      });
+	    });
+	  }
+	  processIndex();
+	}
+	//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9wYXRjaC9hcHBseS5qcyJdLCJuYW1lcyI6WyJhcHBseVBhdGNoIiwiYXBwbHlQYXRjaGVzIiwic291cmNlIiwidW5pRGlmZiIsIm9wdGlvbnMiLCJBcnJheSIsImlzQXJyYXkiLCJsZW5ndGgiLCJFcnJvciIsImxpbmVzIiwic3BsaXQiLCJkZWxpbWl0ZXJzIiwibWF0Y2giLCJodW5rcyIsImNvbXBhcmVMaW5lIiwibGluZU51bWJlciIsImxpbmUiLCJvcGVyYXRpb24iLCJwYXRjaENvbnRlbnQiLCJlcnJvckNvdW50IiwiZnV6ekZhY3RvciIsIm1pbkxpbmUiLCJvZmZzZXQiLCJyZW1vdmVFT0ZOTCIsImFkZEVPRk5MIiwiaHVua0ZpdHMiLCJodW5rIiwidG9Qb3MiLCJqIiwiY29udGVudCIsInN1YnN0ciIsImkiLCJtYXhMaW5lIiwib2xkTGluZXMiLCJsb2NhbE9mZnNldCIsIm9sZFN0YXJ0IiwiaXRlcmF0b3IiLCJ1bmRlZmluZWQiLCJkaWZmT2Zmc2V0IiwibmV3TGluZXMiLCJkZWxpbWl0ZXIiLCJsaW5lZGVsaW1pdGVycyIsInNwbGljZSIsInByZXZpb3VzT3BlcmF0aW9uIiwicG9wIiwicHVzaCIsIl9rIiwiam9pbiIsImN1cnJlbnRJbmRleCIsInByb2Nlc3NJbmRleCIsImluZGV4IiwiY29tcGxldGUiLCJsb2FkRmlsZSIsImVyciIsImRhdGEiLCJ1cGRhdGVkQ29udGVudCIsInBhdGNoZWQiXSwibWFwcGluZ3MiOiI7OztnQ0FHZ0JBLFUsR0FBQUEsVTt5REFvSUFDLFksR0FBQUEsWTs7QUF2SWhCOztBQUNBOzs7Ozs7dUJBRU8sU0FBU0QsVUFBVCxDQUFvQkUsTUFBcEIsRUFBNEJDLE9BQTVCLEVBQW1EO0FBQUEsc0RBQWRDLE9BQWMsdUVBQUosRUFBSTs7QUFDeEQsTUFBSSxPQUFPRCxPQUFQLEtBQW1CLFFBQXZCLEVBQWlDO0FBQy9CQSxjQUFVLHdFQUFXQSxPQUFYLENBQVY7QUFDRDs7QUFFRCxNQUFJRSxNQUFNQyxPQUFOLENBQWNILE9BQWQsQ0FBSixFQUE0QjtBQUMxQixRQUFJQSxRQUFRSSxNQUFSLEdBQWlCLENBQXJCLEVBQXdCO0FBQ3RCLFlBQU0sSUFBSUMsS0FBSixDQUFVLDRDQUFWLENBQU47QUFDRDs7QUFFREwsY0FBVUEsUUFBUSxDQUFSLENBQVY7QUFDRDs7QUFFRDtBQUNBLE1BQUlNLFFBQVFQLE9BQU9RLEtBQVAsQ0FBYSxxQkFBYixDQUFaO0FBQUEsTUFDSUMsYUFBYVQsT0FBT1UsS0FBUCxDQUFhLHNCQUFiLEtBQXdDLEVBRHpEO0FBQUEsTUFFSUMsUUFBUVYsUUFBUVUsS0FGcEI7QUFBQSxNQUlJQyxjQUFjVixRQUFRVSxXQUFSLElBQXdCLFVBQUNDLFVBQUQsRUFBYUMsSUFBYixFQUFtQkMsU0FBbkIsRUFBOEJDLFlBQTlCO0FBQUEsbUNBQStDRixTQUFTRTtBQUF4RDtBQUFBLEdBSjFDO0FBQUEsTUFLSUMsYUFBYSxDQUxqQjtBQUFBLE1BTUlDLGFBQWFoQixRQUFRZ0IsVUFBUixJQUFzQixDQU52QztBQUFBLE1BT0lDLFVBQVUsQ0FQZDtBQUFBLE1BUUlDLFNBQVMsQ0FSYjtBQUFBLE1BVUlDLDZDQVZKO0FBQUEsTUFXSUMsMENBWEo7O0FBYUE7OztBQUdBLFdBQVNDLFFBQVQsQ0FBa0JDLElBQWxCLEVBQXdCQyxLQUF4QixFQUErQjtBQUM3QixTQUFLLElBQUlDLElBQUksQ0FBYixFQUFnQkEsSUFBSUYsS0FBS2pCLEtBQUwsQ0FBV0YsTUFBL0IsRUFBdUNxQixHQUF2QyxFQUE0QztBQUMxQyxVQUFJWixPQUFPVSxLQUFLakIsS0FBTCxDQUFXbUIsQ0FBWCxDQUFYO0FBQUEsVUFDSVgsWUFBYUQsS0FBS1QsTUFBTCxHQUFjLENBQWQsR0FBa0JTLEtBQUssQ0FBTCxDQUFsQixHQUE0QixHQUQ3QztBQUFBLFVBRUlhLFVBQVdiLEtBQUtULE1BQUwsR0FBYyxDQUFkLEdBQWtCUyxLQUFLYyxNQUFMLENBQVksQ0FBWixDQUFsQixHQUFtQ2QsSUFGbEQ7O0FBSUEsVUFBSUMsY0FBYyxHQUFkLElBQXFCQSxjQUFjLEdBQXZDLEVBQTRDO0FBQzFDO0FBQ0EsWUFBSSxDQUFDSCxZQUFZYSxRQUFRLENBQXBCLEVBQXVCbEIsTUFBTWtCLEtBQU4sQ0FBdkIsRUFBcUNWLFNBQXJDLEVBQWdEWSxPQUFoRCxDQUFMLEVBQStEO0FBQzdEVjs7QUFFQSxjQUFJQSxhQUFhQyxVQUFqQixFQUE2QjtBQUMzQixtQkFBTyxLQUFQO0FBQ0Q7QUFDRjtBQUNETztBQUNEO0FBQ0Y7O0FBRUQsV0FBTyxJQUFQO0FBQ0Q7O0FBRUQ7QUFDQSxPQUFLLElBQUlJLElBQUksQ0FBYixFQUFnQkEsSUFBSWxCLE1BQU1OLE1BQTFCLEVBQWtDd0IsR0FBbEMsRUFBdUM7QUFDckMsUUFBSUwsT0FBT2IsTUFBTWtCLENBQU4sQ0FBWDtBQUFBLFFBQ0lDLFVBQVV2QixNQUFNRixNQUFOLEdBQWVtQixLQUFLTyxRQURsQztBQUFBLFFBRUlDLGNBQWMsQ0FGbEI7QUFBQSxRQUdJUCxRQUFRTCxTQUFTSSxLQUFLUyxRQUFkLEdBQXlCLENBSHJDOztBQUtBLFFBQUlDLFdBQVcsb0ZBQWlCVCxLQUFqQixFQUF3Qk4sT0FBeEIsRUFBaUNXLE9BQWpDLENBQWY7O0FBRUEsV0FBT0UsZ0JBQWdCRyxTQUF2QixFQUFrQ0gsY0FBY0UsVUFBaEQsRUFBNEQ7QUFDMUQsVUFBSVgsU0FBU0MsSUFBVCxFQUFlQyxRQUFRTyxXQUF2QixDQUFKLEVBQXlDO0FBQ3ZDUixhQUFLSixNQUFMLEdBQWNBLFVBQVVZLFdBQXhCO0FBQ0E7QUFDRDtBQUNGOztBQUVELFFBQUlBLGdCQUFnQkcsU0FBcEIsRUFBK0I7QUFDN0IsYUFBTyxLQUFQO0FBQ0Q7O0FBRUQ7QUFDQTtBQUNBaEIsY0FBVUssS0FBS0osTUFBTCxHQUFjSSxLQUFLUyxRQUFuQixHQUE4QlQsS0FBS08sUUFBN0M7QUFDRDs7QUFFRDtBQUNBLE1BQUlLLGFBQWEsQ0FBakI7QUFDQSxPQUFLLElBQUlQLEtBQUksQ0FBYixFQUFnQkEsS0FBSWxCLE1BQU1OLE1BQTFCLEVBQWtDd0IsSUFBbEMsRUFBdUM7QUFDckMsUUFBSUwsUUFBT2IsTUFBTWtCLEVBQU4sQ0FBWDtBQUFBLFFBQ0lKLFNBQVFELE1BQUtTLFFBQUwsR0FBZ0JULE1BQUtKLE1BQXJCLEdBQThCZ0IsVUFBOUIsR0FBMkMsQ0FEdkQ7QUFFQUEsa0JBQWNaLE1BQUthLFFBQUwsR0FBZ0JiLE1BQUtPLFFBQW5DOztBQUVBLFFBQUlOLFNBQVEsQ0FBWixFQUFlO0FBQUU7QUFDZkEsZUFBUSxDQUFSO0FBQ0Q7O0FBRUQsU0FBSyxJQUFJQyxJQUFJLENBQWIsRUFBZ0JBLElBQUlGLE1BQUtqQixLQUFMLENBQVdGLE1BQS9CLEVBQXVDcUIsR0FBdkMsRUFBNEM7QUFDMUMsVUFBSVosT0FBT1UsTUFBS2pCLEtBQUwsQ0FBV21CLENBQVgsQ0FBWDtBQUFBLFVBQ0lYLFlBQWFELEtBQUtULE1BQUwsR0FBYyxDQUFkLEdBQWtCUyxLQUFLLENBQUwsQ0FBbEIsR0FBNEIsR0FEN0M7QUFBQSxVQUVJYSxVQUFXYixLQUFLVCxNQUFMLEdBQWMsQ0FBZCxHQUFrQlMsS0FBS2MsTUFBTCxDQUFZLENBQVosQ0FBbEIsR0FBbUNkLElBRmxEO0FBQUEsVUFHSXdCLFlBQVlkLE1BQUtlLGNBQUwsQ0FBb0JiLENBQXBCLENBSGhCOztBQUtBLFVBQUlYLGNBQWMsR0FBbEIsRUFBdUI7QUFDckJVO0FBQ0QsT0FGRCxNQUVPLElBQUlWLGNBQWMsR0FBbEIsRUFBdUI7QUFDNUJSLGNBQU1pQyxNQUFOLENBQWFmLE1BQWIsRUFBb0IsQ0FBcEI7QUFDQWhCLG1CQUFXK0IsTUFBWCxDQUFrQmYsTUFBbEIsRUFBeUIsQ0FBekI7QUFDRjtBQUNDLE9BSk0sTUFJQSxJQUFJVixjQUFjLEdBQWxCLEVBQXVCO0FBQzVCUixjQUFNaUMsTUFBTixDQUFhZixNQUFiLEVBQW9CLENBQXBCLEVBQXVCRSxPQUF2QjtBQUNBbEIsbUJBQVcrQixNQUFYLENBQWtCZixNQUFsQixFQUF5QixDQUF6QixFQUE0QmEsU0FBNUI7QUFDQWI7QUFDRCxPQUpNLE1BSUEsSUFBSVYsY0FBYyxJQUFsQixFQUF3QjtBQUM3QixZQUFJMEIsb0JBQW9CakIsTUFBS2pCLEtBQUwsQ0FBV21CLElBQUksQ0FBZixJQUFvQkYsTUFBS2pCLEtBQUwsQ0FBV21CLElBQUksQ0FBZixFQUFrQixDQUFsQixDQUFwQixHQUEyQyxJQUFuRTtBQUNBLFlBQUllLHNCQUFzQixHQUExQixFQUErQjtBQUM3QnBCLHdCQUFjLElBQWQ7QUFDRCxTQUZELE1BRU8sSUFBSW9CLHNCQUFzQixHQUExQixFQUErQjtBQUNwQ25CLHFCQUFXLElBQVg7QUFDRDtBQUNGO0FBQ0Y7QUFDRjs7QUFFRDtBQUNBLE1BQUlELFdBQUosRUFBaUI7QUFDZixXQUFPLENBQUNkLE1BQU1BLE1BQU1GLE1BQU4sR0FBZSxDQUFyQixDQUFSLEVBQWlDO0FBQy9CRSxZQUFNbUMsR0FBTjtBQUNBakMsaUJBQVdpQyxHQUFYO0FBQ0Q7QUFDRixHQUxELE1BS08sSUFBSXBCLFFBQUosRUFBYztBQUNuQmYsVUFBTW9DLElBQU4sQ0FBVyxFQUFYO0FBQ0FsQyxlQUFXa0MsSUFBWCxDQUFnQixJQUFoQjtBQUNEO0FBQ0QsT0FBSyxJQUFJQyxLQUFLLENBQWQsRUFBaUJBLEtBQUtyQyxNQUFNRixNQUFOLEdBQWUsQ0FBckMsRUFBd0N1QyxJQUF4QyxFQUE4QztBQUM1Q3JDLFVBQU1xQyxFQUFOLElBQVlyQyxNQUFNcUMsRUFBTixJQUFZbkMsV0FBV21DLEVBQVgsQ0FBeEI7QUFDRDtBQUNELFNBQU9yQyxNQUFNc0MsSUFBTixDQUFXLEVBQVgsQ0FBUDtBQUNEOztBQUVEO0FBQ08sU0FBUzlDLFlBQVQsQ0FBc0JFLE9BQXRCLEVBQStCQyxPQUEvQixFQUF3QztBQUM3QyxNQUFJLE9BQU9ELE9BQVAsS0FBbUIsUUFBdkIsRUFBaUM7QUFDL0JBLGNBQVUsd0VBQVdBLE9BQVgsQ0FBVjtBQUNEOztBQUVELE1BQUk2QyxlQUFlLENBQW5CO0FBQ0EsV0FBU0MsWUFBVCxHQUF3QjtBQUN0QixRQUFJQyxRQUFRL0MsUUFBUTZDLGNBQVIsQ0FBWjtBQUNBLFFBQUksQ0FBQ0UsS0FBTCxFQUFZO0FBQ1YsYUFBTzlDLFFBQVErQyxRQUFSLEVBQVA7QUFDRDs7QUFFRC9DLFlBQVFnRCxRQUFSLENBQWlCRixLQUFqQixFQUF3QixVQUFTRyxHQUFULEVBQWNDLElBQWQsRUFBb0I7QUFDMUMsVUFBSUQsR0FBSixFQUFTO0FBQ1AsZUFBT2pELFFBQVErQyxRQUFSLENBQWlCRSxHQUFqQixDQUFQO0FBQ0Q7O0FBRUQsVUFBSUUsaUJBQWlCdkQsV0FBV3NELElBQVgsRUFBaUJKLEtBQWpCLEVBQXdCOUMsT0FBeEIsQ0FBckI7QUFDQUEsY0FBUW9ELE9BQVIsQ0FBZ0JOLEtBQWhCLEVBQXVCSyxjQUF2QixFQUF1QyxVQUFTRixHQUFULEVBQWM7QUFDbkQsWUFBSUEsR0FBSixFQUFTO0FBQ1AsaUJBQU9qRCxRQUFRK0MsUUFBUixDQUFpQkUsR0FBakIsQ0FBUDtBQUNEOztBQUVESjtBQUNELE9BTkQ7QUFPRCxLQWJEO0FBY0Q7QUFDREE7QUFDRCIsImZpbGUiOiJhcHBseS5qcyIsInNvdXJjZXNDb250ZW50IjpbImltcG9ydCB7cGFyc2VQYXRjaH0gZnJvbSAnLi9wYXJzZSc7XG5pbXBvcnQgZGlzdGFuY2VJdGVyYXRvciBmcm9tICcuLi91dGlsL2Rpc3RhbmNlLWl0ZXJhdG9yJztcblxuZXhwb3J0IGZ1bmN0aW9uIGFwcGx5UGF0Y2goc291cmNlLCB1bmlEaWZmLCBvcHRpb25zID0ge30pIHtcbiAgaWYgKHR5cGVvZiB1bmlEaWZmID09PSAnc3RyaW5nJykge1xuICAgIHVuaURpZmYgPSBwYXJzZVBhdGNoKHVuaURpZmYpO1xuICB9XG5cbiAgaWYgKEFycmF5LmlzQXJyYXkodW5pRGlmZikpIHtcbiAgICBpZiAodW5pRGlmZi5sZW5ndGggPiAxKSB7XG4gICAgICB0aHJvdyBuZXcgRXJyb3IoJ2FwcGx5UGF0Y2ggb25seSB3b3JrcyB3aXRoIGEgc2luZ2xlIGlucHV0LicpO1xuICAgIH1cblxuICAgIHVuaURpZmYgPSB1bmlEaWZmWzBdO1xuICB9XG5cbiAgLy8gQXBwbHkgdGhlIGRpZmYgdG8gdGhlIGlucHV0XG4gIGxldCBsaW5lcyA9IHNvdXJjZS5zcGxpdCgvXFxyXFxufFtcXG5cXHZcXGZcXHJcXHg4NV0vKSxcbiAgICAgIGRlbGltaXRlcnMgPSBzb3VyY2UubWF0Y2goL1xcclxcbnxbXFxuXFx2XFxmXFxyXFx4ODVdL2cpIHx8IFtdLFxuICAgICAgaHVua3MgPSB1bmlEaWZmLmh1bmtzLFxuXG4gICAgICBjb21wYXJlTGluZSA9IG9wdGlvbnMuY29tcGFyZUxpbmUgfHwgKChsaW5lTnVtYmVyLCBsaW5lLCBvcGVyYXRpb24sIHBhdGNoQ29udGVudCkgPT4gbGluZSA9PT0gcGF0Y2hDb250ZW50KSxcbiAgICAgIGVycm9yQ291bnQgPSAwLFxuICAgICAgZnV6ekZhY3RvciA9IG9wdGlvbnMuZnV6ekZhY3RvciB8fCAwLFxuICAgICAgbWluTGluZSA9IDAsXG4gICAgICBvZmZzZXQgPSAwLFxuXG4gICAgICByZW1vdmVFT0ZOTCxcbiAgICAgIGFkZEVPRk5MO1xuXG4gIC8qKlxuICAgKiBDaGVja3MgaWYgdGhlIGh1bmsgZXhhY3RseSBmaXRzIG9uIHRoZSBwcm92aWRlZCBsb2NhdGlvblxuICAgKi9cbiAgZnVuY3Rpb24gaHVua0ZpdHMoaHVuaywgdG9Qb3MpIHtcbiAgICBmb3IgKGxldCBqID0gMDsgaiA8IGh1bmsubGluZXMubGVuZ3RoOyBqKyspIHtcbiAgICAgIGxldCBsaW5lID0gaHVuay5saW5lc1tqXSxcbiAgICAgICAgICBvcGVyYXRpb24gPSAobGluZS5sZW5ndGggPiAwID8gbGluZVswXSA6ICcgJyksXG4gICAgICAgICAgY29udGVudCA9IChsaW5lLmxlbmd0aCA+IDAgPyBsaW5lLnN1YnN0cigxKSA6IGxpbmUpO1xuXG4gICAgICBpZiAob3BlcmF0aW9uID09PSAnICcgfHwgb3BlcmF0aW9uID09PSAnLScpIHtcbiAgICAgICAgLy8gQ29udGV4dCBzYW5pdHkgY2hlY2tcbiAgICAgICAgaWYgKCFjb21wYXJlTGluZSh0b1BvcyArIDEsIGxpbmVzW3RvUG9zXSwgb3BlcmF0aW9uLCBjb250ZW50KSkge1xuICAgICAgICAgIGVycm9yQ291bnQrKztcblxuICAgICAgICAgIGlmIChlcnJvckNvdW50ID4gZnV6ekZhY3Rvcikge1xuICAgICAgICAgICAgcmV0dXJuIGZhbHNlO1xuICAgICAgICAgIH1cbiAgICAgICAgfVxuICAgICAgICB0b1BvcysrO1xuICAgICAgfVxuICAgIH1cblxuICAgIHJldHVybiB0cnVlO1xuICB9XG5cbiAgLy8gU2VhcmNoIGJlc3QgZml0IG9mZnNldHMgZm9yIGVhY2ggaHVuayBiYXNlZCBvbiB0aGUgcHJldmlvdXMgb25lc1xuICBmb3IgKGxldCBpID0gMDsgaSA8IGh1bmtzLmxlbmd0aDsgaSsrKSB7XG4gICAgbGV0IGh1bmsgPSBodW5rc1tpXSxcbiAgICAgICAgbWF4TGluZSA9IGxpbmVzLmxlbmd0aCAtIGh1bmsub2xkTGluZXMsXG4gICAgICAgIGxvY2FsT2Zmc2V0ID0gMCxcbiAgICAgICAgdG9Qb3MgPSBvZmZzZXQgKyBodW5rLm9sZFN0YXJ0IC0gMTtcblxuICAgIGxldCBpdGVyYXRvciA9IGRpc3RhbmNlSXRlcmF0b3IodG9Qb3MsIG1pbkxpbmUsIG1heExpbmUpO1xuXG4gICAgZm9yICg7IGxvY2FsT2Zmc2V0ICE9PSB1bmRlZmluZWQ7IGxvY2FsT2Zmc2V0ID0gaXRlcmF0b3IoKSkge1xuICAgICAgaWYgKGh1bmtGaXRzKGh1bmssIHRvUG9zICsgbG9jYWxPZmZzZXQpKSB7XG4gICAgICAgIGh1bmsub2Zmc2V0ID0gb2Zmc2V0ICs9IGxvY2FsT2Zmc2V0O1xuICAgICAgICBicmVhaztcbiAgICAgIH1cbiAgICB9XG5cbiAgICBpZiAobG9jYWxPZmZzZXQgPT09IHVuZGVmaW5lZCkge1xuICAgICAgcmV0dXJuIGZhbHNlO1xuICAgIH1cblxuICAgIC8vIFNldCBsb3dlciB0ZXh0IGxpbWl0IHRvIGVuZCBvZiB0aGUgY3VycmVudCBodW5rLCBzbyBuZXh0IG9uZXMgZG9uJ3QgdHJ5XG4gICAgLy8gdG8gZml0IG92ZXIgYWxyZWFkeSBwYXRjaGVkIHRleHRcbiAgICBtaW5MaW5lID0gaHVuay5vZmZzZXQgKyBodW5rLm9sZFN0YXJ0ICsgaHVuay5vbGRMaW5lcztcbiAgfVxuXG4gIC8vIEFwcGx5IHBhdGNoIGh1bmtzXG4gIGxldCBkaWZmT2Zmc2V0ID0gMDtcbiAgZm9yIChsZXQgaSA9IDA7IGkgPCBodW5rcy5sZW5ndGg7IGkrKykge1xuICAgIGxldCBodW5rID0gaHVua3NbaV0sXG4gICAgICAgIHRvUG9zID0gaHVuay5vbGRTdGFydCArIGh1bmsub2Zmc2V0ICsgZGlmZk9mZnNldCAtIDE7XG4gICAgZGlmZk9mZnNldCArPSBodW5rLm5ld0xpbmVzIC0gaHVuay5vbGRMaW5lcztcblxuICAgIGlmICh0b1BvcyA8IDApIHsgLy8gQ3JlYXRpbmcgYSBuZXcgZmlsZVxuICAgICAgdG9Qb3MgPSAwO1xuICAgIH1cblxuICAgIGZvciAobGV0IGogPSAwOyBqIDwgaHVuay5saW5lcy5sZW5ndGg7IGorKykge1xuICAgICAgbGV0IGxpbmUgPSBodW5rLmxpbmVzW2pdLFxuICAgICAgICAgIG9wZXJhdGlvbiA9IChsaW5lLmxlbmd0aCA+IDAgPyBsaW5lWzBdIDogJyAnKSxcbiAgICAgICAgICBjb250ZW50ID0gKGxpbmUubGVuZ3RoID4gMCA/IGxpbmUuc3Vic3RyKDEpIDogbGluZSksXG4gICAgICAgICAgZGVsaW1pdGVyID0gaHVuay5saW5lZGVsaW1pdGVyc1tqXTtcblxuICAgICAgaWYgKG9wZXJhdGlvbiA9PT0gJyAnKSB7XG4gICAgICAgIHRvUG9zKys7XG4gICAgICB9IGVsc2UgaWYgKG9wZXJhdGlvbiA9PT0gJy0nKSB7XG4gICAgICAgIGxpbmVzLnNwbGljZSh0b1BvcywgMSk7XG4gICAgICAgIGRlbGltaXRlcnMuc3BsaWNlKHRvUG9zLCAxKTtcbiAgICAgIC8qIGlzdGFuYnVsIGlnbm9yZSBlbHNlICovXG4gICAgICB9IGVsc2UgaWYgKG9wZXJhdGlvbiA9PT0gJysnKSB7XG4gICAgICAgIGxpbmVzLnNwbGljZSh0b1BvcywgMCwgY29udGVudCk7XG4gICAgICAgIGRlbGltaXRlcnMuc3BsaWNlKHRvUG9zLCAwLCBkZWxpbWl0ZXIpO1xuICAgICAgICB0b1BvcysrO1xuICAgICAgfSBlbHNlIGlmIChvcGVyYXRpb24gPT09ICdcXFxcJykge1xuICAgICAgICBsZXQgcHJldmlvdXNPcGVyYXRpb24gPSBodW5rLmxpbmVzW2ogLSAxXSA/IGh1bmsubGluZXNbaiAtIDFdWzBdIDogbnVsbDtcbiAgICAgICAgaWYgKHByZXZpb3VzT3BlcmF0aW9uID09PSAnKycpIHtcbiAgICAgICAgICByZW1vdmVFT0ZOTCA9IHRydWU7XG4gICAgICAgIH0gZWxzZSBpZiAocHJldmlvdXNPcGVyYXRpb24gPT09ICctJykge1xuICAgICAgICAgIGFkZEVPRk5MID0gdHJ1ZTtcbiAgICAgICAgfVxuICAgICAgfVxuICAgIH1cbiAgfVxuXG4gIC8vIEhhbmRsZSBFT0ZOTCBpbnNlcnRpb24vcmVtb3ZhbFxuICBpZiAocmVtb3ZlRU9GTkwpIHtcbiAgICB3aGlsZSAoIWxpbmVzW2xpbmVzLmxlbmd0aCAtIDFdKSB7XG4gICAgICBsaW5lcy5wb3AoKTtcbiAgICAgIGRlbGltaXRlcnMucG9wKCk7XG4gICAgfVxuICB9IGVsc2UgaWYgKGFkZEVPRk5MKSB7XG4gICAgbGluZXMucHVzaCgnJyk7XG4gICAgZGVsaW1pdGVycy5wdXNoKCdcXG4nKTtcbiAgfVxuICBmb3IgKGxldCBfayA9IDA7IF9rIDwgbGluZXMubGVuZ3RoIC0gMTsgX2srKykge1xuICAgIGxpbmVzW19rXSA9IGxpbmVzW19rXSArIGRlbGltaXRlcnNbX2tdO1xuICB9XG4gIHJldHVybiBsaW5lcy5qb2luKCcnKTtcbn1cblxuLy8gV3JhcHBlciB0aGF0IHN1cHBvcnRzIG11bHRpcGxlIGZpbGUgcGF0Y2hlcyB2aWEgY2FsbGJhY2tzLlxuZXhwb3J0IGZ1bmN0aW9uIGFwcGx5UGF0Y2hlcyh1bmlEaWZmLCBvcHRpb25zKSB7XG4gIGlmICh0eXBlb2YgdW5pRGlmZiA9PT0gJ3N0cmluZycpIHtcbiAgICB1bmlEaWZmID0gcGFyc2VQYXRjaCh1bmlEaWZmKTtcbiAgfVxuXG4gIGxldCBjdXJyZW50SW5kZXggPSAwO1xuICBmdW5jdGlvbiBwcm9jZXNzSW5kZXgoKSB7XG4gICAgbGV0IGluZGV4ID0gdW5pRGlmZltjdXJyZW50SW5kZXgrK107XG4gICAgaWYgKCFpbmRleCkge1xuICAgICAgcmV0dXJuIG9wdGlvbnMuY29tcGxldGUoKTtcbiAgICB9XG5cbiAgICBvcHRpb25zLmxvYWRGaWxlKGluZGV4LCBmdW5jdGlvbihlcnIsIGRhdGEpIHtcbiAgICAgIGlmIChlcnIpIHtcbiAgICAgICAgcmV0dXJuIG9wdGlvbnMuY29tcGxldGUoZXJyKTtcbiAgICAgIH1cblxuICAgICAgbGV0IHVwZGF0ZWRDb250ZW50ID0gYXBwbHlQYXRjaChkYXRhLCBpbmRleCwgb3B0aW9ucyk7XG4gICAgICBvcHRpb25zLnBhdGNoZWQoaW5kZXgsIHVwZGF0ZWRDb250ZW50LCBmdW5jdGlvbihlcnIpIHtcbiAgICAgICAgaWYgKGVycikge1xuICAgICAgICAgIHJldHVybiBvcHRpb25zLmNvbXBsZXRlKGVycik7XG4gICAgICAgIH1cblxuICAgICAgICBwcm9jZXNzSW5kZXgoKTtcbiAgICAgIH0pO1xuICAgIH0pO1xuICB9XG4gIHByb2Nlc3NJbmRleCgpO1xufVxuIl19
+
+
+/***/ }),
+/* 11 */
+/***/ (function(module, exports) {
+
+	/*istanbul ignore start*/'use strict';
+
+	exports.__esModule = true;
+	exports. /*istanbul ignore end*/parsePatch = parsePatch;
+	function parsePatch(uniDiff) {
+	  /*istanbul ignore start*/var /*istanbul ignore end*/options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
+
+	  var diffstr = uniDiff.split(/\r\n|[\n\v\f\r\x85]/),
+	      delimiters = uniDiff.match(/\r\n|[\n\v\f\r\x85]/g) || [],
+	      list = [],
+	      i = 0;
+
+	  function parseIndex() {
+	    var index = {};
+	    list.push(index);
+
+	    // Parse diff metadata
+	    while (i < diffstr.length) {
+	      var line = diffstr[i];
+
+	      // File header found, end parsing diff metadata
+	      if (/^(\-\-\-|\+\+\+|@@)\s/.test(line)) {
+	        break;
+	      }
+
+	      // Diff index
+	      var header = /^(?:Index:|diff(?: -r \w+)+)\s+(.+?)\s*$/.exec(line);
+	      if (header) {
+	        index.index = header[1];
+	      }
+
+	      i++;
+	    }
+
+	    // Parse file headers if they are defined. Unified diff requires them, but
+	    // there's no technical issues to have an isolated hunk without file header
+	    parseFileHeader(index);
+	    parseFileHeader(index);
+
+	    // Parse hunks
+	    index.hunks = [];
+
+	    while (i < diffstr.length) {
+	      var _line = diffstr[i];
+
+	      if (/^(Index:|diff|\-\-\-|\+\+\+)\s/.test(_line)) {
+	        break;
+	      } else if (/^@@/.test(_line)) {
+	        index.hunks.push(parseHunk());
+	      } else if (_line && options.strict) {
+	        // Ignore unexpected content unless in strict mode
+	        throw new Error('Unknown line ' + (i + 1) + ' ' + JSON.stringify(_line));
+	      } else {
+	        i++;
+	      }
+	    }
+	  }
+
+	  // Parses the --- and +++ headers, if none are found, no lines
+	  // are consumed.
+	  function parseFileHeader(index) {
+	    var fileHeader = /^(---|\+\+\+)\s+(.*)$/.exec(diffstr[i]);
+	    if (fileHeader) {
+	      var keyPrefix = fileHeader[1] === '---' ? 'old' : 'new';
+	      var data = fileHeader[2].split('\t', 2);
+	      var fileName = data[0].replace(/\\\\/g, '\\');
+	      if (/^".*"$/.test(fileName)) {
+	        fileName = fileName.substr(1, fileName.length - 2);
+	      }
+	      index[keyPrefix + 'FileName'] = fileName;
+	      index[keyPrefix + 'Header'] = (data[1] || '').trim();
+
+	      i++;
+	    }
+	  }
+
+	  // Parses a hunk
+	  // This assumes that we are at the start of a hunk.
+	  function parseHunk() {
+	    var chunkHeaderIndex = i,
+	        chunkHeaderLine = diffstr[i++],
+	        chunkHeader = chunkHeaderLine.split(/@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/);
+
+	    var hunk = {
+	      oldStart: +chunkHeader[1],
+	      oldLines: +chunkHeader[2] || 1,
+	      newStart: +chunkHeader[3],
+	      newLines: +chunkHeader[4] || 1,
+	      lines: [],
+	      linedelimiters: []
+	    };
+
+	    var addCount = 0,
+	        removeCount = 0;
+	    for (; i < diffstr.length; i++) {
+	      // Lines starting with '---' could be mistaken for the "remove line" operation
+	      // But they could be the header for the next file. Therefore prune such cases out.
+	      if (diffstr[i].indexOf('--- ') === 0 && i + 2 < diffstr.length && diffstr[i + 1].indexOf('+++ ') === 0 && diffstr[i + 2].indexOf('@@') === 0) {
+	        break;
+	      }
+	      var operation = diffstr[i].length == 0 && i != diffstr.length - 1 ? ' ' : diffstr[i][0];
+
+	      if (operation === '+' || operation === '-' || operation === ' ' || operation === '\\') {
+	        hunk.lines.push(diffstr[i]);
+	        hunk.linedelimiters.push(delimiters[i] || '\n');
+
+	        if (operation === '+') {
+	          addCount++;
+	        } else if (operation === '-') {
+	          removeCount++;
+	        } else if (operation === ' ') {
+	          addCount++;
+	          removeCount++;
+	        }
+	      } else {
+	        break;
+	      }
+	    }
+
+	    // Handle the empty block count case
+	    if (!addCount && hunk.newLines === 1) {
+	      hunk.newLines = 0;
+	    }
+	    if (!removeCount && hunk.oldLines === 1) {
+	      hunk.oldLines = 0;
+	    }
+
+	    // Perform optional sanity checking
+	    if (options.strict) {
+	      if (addCount !== hunk.newLines) {
+	        throw new Error('Added line count did not match for hunk at line ' + (chunkHeaderIndex + 1));
+	      }
+	      if (removeCount !== hunk.oldLines) {
+	        throw new Error('Removed line count did not match for hunk at line ' + (chunkHeaderIndex + 1));
+	      }
+	    }
+
+	    return hunk;
+	  }
+
+	  while (i < diffstr.length) {
+	    parseIndex();
+	  }
+
+	  return list;
+	}
+	//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9wYXRjaC9wYXJzZS5qcyJdLCJuYW1lcyI6WyJwYXJzZVBhdGNoIiwidW5pRGlmZiIsIm9wdGlvbnMiLCJkaWZmc3RyIiwic3BsaXQiLCJkZWxpbWl0ZXJzIiwibWF0Y2giLCJsaXN0IiwiaSIsInBhcnNlSW5kZXgiLCJpbmRleCIsInB1c2giLCJsZW5ndGgiLCJsaW5lIiwidGVzdCIsImhlYWRlciIsImV4ZWMiLCJwYXJzZUZpbGVIZWFkZXIiLCJodW5rcyIsInBhcnNlSHVuayIsInN0cmljdCIsIkVycm9yIiwiSlNPTiIsInN0cmluZ2lmeSIsImZpbGVIZWFkZXIiLCJrZXlQcmVmaXgiLCJkYXRhIiwiZmlsZU5hbWUiLCJyZXBsYWNlIiwic3Vic3RyIiwidHJpbSIsImNodW5rSGVhZGVySW5kZXgiLCJjaHVua0hlYWRlckxpbmUiLCJjaHVua0hlYWRlciIsImh1bmsiLCJvbGRTdGFydCIsIm9sZExpbmVzIiwibmV3U3RhcnQiLCJuZXdMaW5lcyIsImxpbmVzIiwibGluZWRlbGltaXRlcnMiLCJhZGRDb3VudCIsInJlbW92ZUNvdW50IiwiaW5kZXhPZiIsIm9wZXJhdGlvbiJdLCJtYXBwaW5ncyI6Ijs7O2dDQUFnQkEsVSxHQUFBQSxVO0FBQVQsU0FBU0EsVUFBVCxDQUFvQkMsT0FBcEIsRUFBMkM7QUFBQSxzREFBZEMsT0FBYyx1RUFBSixFQUFJOztBQUNoRCxNQUFJQyxVQUFVRixRQUFRRyxLQUFSLENBQWMscUJBQWQsQ0FBZDtBQUFBLE1BQ0lDLGFBQWFKLFFBQVFLLEtBQVIsQ0FBYyxzQkFBZCxLQUF5QyxFQUQxRDtBQUFBLE1BRUlDLE9BQU8sRUFGWDtBQUFBLE1BR0lDLElBQUksQ0FIUjs7QUFLQSxXQUFTQyxVQUFULEdBQXNCO0FBQ3BCLFFBQUlDLFFBQVEsRUFBWjtBQUNBSCxTQUFLSSxJQUFMLENBQVVELEtBQVY7O0FBRUE7QUFDQSxXQUFPRixJQUFJTCxRQUFRUyxNQUFuQixFQUEyQjtBQUN6QixVQUFJQyxPQUFPVixRQUFRSyxDQUFSLENBQVg7O0FBRUE7QUFDQSxVQUFJLHdCQUF3Qk0sSUFBeEIsQ0FBNkJELElBQTdCLENBQUosRUFBd0M7QUFDdEM7QUFDRDs7QUFFRDtBQUNBLFVBQUlFLFNBQVUsMENBQUQsQ0FBNkNDLElBQTdDLENBQWtESCxJQUFsRCxDQUFiO0FBQ0EsVUFBSUUsTUFBSixFQUFZO0FBQ1ZMLGNBQU1BLEtBQU4sR0FBY0ssT0FBTyxDQUFQLENBQWQ7QUFDRDs7QUFFRFA7QUFDRDs7QUFFRDtBQUNBO0FBQ0FTLG9CQUFnQlAsS0FBaEI7QUFDQU8sb0JBQWdCUCxLQUFoQjs7QUFFQTtBQUNBQSxVQUFNUSxLQUFOLEdBQWMsRUFBZDs7QUFFQSxXQUFPVixJQUFJTCxRQUFRUyxNQUFuQixFQUEyQjtBQUN6QixVQUFJQyxRQUFPVixRQUFRSyxDQUFSLENBQVg7O0FBRUEsVUFBSSxpQ0FBaUNNLElBQWpDLENBQXNDRCxLQUF0QyxDQUFKLEVBQWlEO0FBQy9DO0FBQ0QsT0FGRCxNQUVPLElBQUksTUFBTUMsSUFBTixDQUFXRCxLQUFYLENBQUosRUFBc0I7QUFDM0JILGNBQU1RLEtBQU4sQ0FBWVAsSUFBWixDQUFpQlEsV0FBakI7QUFDRCxPQUZNLE1BRUEsSUFBSU4sU0FBUVgsUUFBUWtCLE1BQXBCLEVBQTRCO0FBQ2pDO0FBQ0EsY0FBTSxJQUFJQyxLQUFKLENBQVUsbUJBQW1CYixJQUFJLENBQXZCLElBQTRCLEdBQTVCLEdBQWtDYyxLQUFLQyxTQUFMLENBQWVWLEtBQWYsQ0FBNUMsQ0FBTjtBQUNELE9BSE0sTUFHQTtBQUNMTDtBQUNEO0FBQ0Y7QUFDRjs7QUFFRDtBQUNBO0FBQ0EsV0FBU1MsZUFBVCxDQUF5QlAsS0FBekIsRUFBZ0M7QUFDOUIsUUFBTWMsYUFBYyx1QkFBRCxDQUEwQlIsSUFBMUIsQ0FBK0JiLFFBQVFLLENBQVIsQ0FBL0IsQ0FBbkI7QUFDQSxRQUFJZ0IsVUFBSixFQUFnQjtBQUNkLFVBQUlDLFlBQVlELFdBQVcsQ0FBWCxNQUFrQixLQUFsQixHQUEwQixLQUExQixHQUFrQyxLQUFsRDtBQUNBLFVBQU1FLE9BQU9GLFdBQVcsQ0FBWCxFQUFjcEIsS0FBZCxDQUFvQixJQUFwQixFQUEwQixDQUExQixDQUFiO0FBQ0EsVUFBSXVCLFdBQVdELEtBQUssQ0FBTCxFQUFRRSxPQUFSLENBQWdCLE9BQWhCLEVBQXlCLElBQXpCLENBQWY7QUFDQSxVQUFJLFNBQVNkLElBQVQsQ0FBY2EsUUFBZCxDQUFKLEVBQTZCO0FBQzNCQSxtQkFBV0EsU0FBU0UsTUFBVCxDQUFnQixDQUFoQixFQUFtQkYsU0FBU2YsTUFBVCxHQUFrQixDQUFyQyxDQUFYO0FBQ0Q7QUFDREYsWUFBTWUsWUFBWSxVQUFsQixJQUFnQ0UsUUFBaEM7QUFDQWpCLFlBQU1lLFlBQVksUUFBbEIsSUFBOEIsQ0FBQ0MsS0FBSyxDQUFMLEtBQVcsRUFBWixFQUFnQkksSUFBaEIsRUFBOUI7O0FBRUF0QjtBQUNEO0FBQ0Y7O0FBRUQ7QUFDQTtBQUNBLFdBQVNXLFNBQVQsR0FBcUI7QUFDbkIsUUFBSVksbUJBQW1CdkIsQ0FBdkI7QUFBQSxRQUNJd0Isa0JBQWtCN0IsUUFBUUssR0FBUixDQUR0QjtBQUFBLFFBRUl5QixjQUFjRCxnQkFBZ0I1QixLQUFoQixDQUFzQiw0Q0FBdEIsQ0FGbEI7O0FBSUEsUUFBSThCLE9BQU87QUFDVEMsZ0JBQVUsQ0FBQ0YsWUFBWSxDQUFaLENBREY7QUFFVEcsZ0JBQVUsQ0FBQ0gsWUFBWSxDQUFaLENBQUQsSUFBbUIsQ0FGcEI7QUFHVEksZ0JBQVUsQ0FBQ0osWUFBWSxDQUFaLENBSEY7QUFJVEssZ0JBQVUsQ0FBQ0wsWUFBWSxDQUFaLENBQUQsSUFBbUIsQ0FKcEI7QUFLVE0sYUFBTyxFQUxFO0FBTVRDLHNCQUFnQjtBQU5QLEtBQVg7O0FBU0EsUUFBSUMsV0FBVyxDQUFmO0FBQUEsUUFDSUMsY0FBYyxDQURsQjtBQUVBLFdBQU9sQyxJQUFJTCxRQUFRUyxNQUFuQixFQUEyQkosR0FBM0IsRUFBZ0M7QUFDOUI7QUFDQTtBQUNBLFVBQUlMLFFBQVFLLENBQVIsRUFBV21DLE9BQVgsQ0FBbUIsTUFBbkIsTUFBK0IsQ0FBL0IsSUFDTW5DLElBQUksQ0FBSixHQUFRTCxRQUFRUyxNQUR0QixJQUVLVCxRQUFRSyxJQUFJLENBQVosRUFBZW1DLE9BQWYsQ0FBdUIsTUFBdkIsTUFBbUMsQ0FGeEMsSUFHS3hDLFFBQVFLLElBQUksQ0FBWixFQUFlbUMsT0FBZixDQUF1QixJQUF2QixNQUFpQyxDQUgxQyxFQUc2QztBQUN6QztBQUNIO0FBQ0QsVUFBSUMsWUFBYXpDLFFBQVFLLENBQVIsRUFBV0ksTUFBWCxJQUFxQixDQUFyQixJQUEwQkosS0FBTUwsUUFBUVMsTUFBUixHQUFpQixDQUFsRCxHQUF3RCxHQUF4RCxHQUE4RFQsUUFBUUssQ0FBUixFQUFXLENBQVgsQ0FBOUU7O0FBRUEsVUFBSW9DLGNBQWMsR0FBZCxJQUFxQkEsY0FBYyxHQUFuQyxJQUEwQ0EsY0FBYyxHQUF4RCxJQUErREEsY0FBYyxJQUFqRixFQUF1RjtBQUNyRlYsYUFBS0ssS0FBTCxDQUFXNUIsSUFBWCxDQUFnQlIsUUFBUUssQ0FBUixDQUFoQjtBQUNBMEIsYUFBS00sY0FBTCxDQUFvQjdCLElBQXBCLENBQXlCTixXQUFXRyxDQUFYLEtBQWlCLElBQTFDOztBQUVBLFlBQUlvQyxjQUFjLEdBQWxCLEVBQXVCO0FBQ3JCSDtBQUNELFNBRkQsTUFFTyxJQUFJRyxjQUFjLEdBQWxCLEVBQXVCO0FBQzVCRjtBQUNELFNBRk0sTUFFQSxJQUFJRSxjQUFjLEdBQWxCLEVBQXVCO0FBQzVCSDtBQUNBQztBQUNEO0FBQ0YsT0FaRCxNQVlPO0FBQ0w7QUFDRDtBQUNGOztBQUVEO0FBQ0EsUUFBSSxDQUFDRCxRQUFELElBQWFQLEtBQUtJLFFBQUwsS0FBa0IsQ0FBbkMsRUFBc0M7QUFDcENKLFdBQUtJLFFBQUwsR0FBZ0IsQ0FBaEI7QUFDRDtBQUNELFFBQUksQ0FBQ0ksV0FBRCxJQUFnQlIsS0FBS0UsUUFBTCxLQUFrQixDQUF0QyxFQUF5QztBQUN2Q0YsV0FBS0UsUUFBTCxHQUFnQixDQUFoQjtBQUNEOztBQUVEO0FBQ0EsUUFBSWxDLFFBQVFrQixNQUFaLEVBQW9CO0FBQ2xCLFVBQUlxQixhQUFhUCxLQUFLSSxRQUF0QixFQUFnQztBQUM5QixjQUFNLElBQUlqQixLQUFKLENBQVUsc0RBQXNEVSxtQkFBbUIsQ0FBekUsQ0FBVixDQUFOO0FBQ0Q7QUFDRCxVQUFJVyxnQkFBZ0JSLEtBQUtFLFFBQXpCLEVBQW1DO0FBQ2pDLGNBQU0sSUFBSWYsS0FBSixDQUFVLHdEQUF3RFUsbUJBQW1CLENBQTNFLENBQVYsQ0FBTjtBQUNEO0FBQ0Y7O0FBRUQsV0FBT0csSUFBUDtBQUNEOztBQUVELFNBQU8xQixJQUFJTCxRQUFRUyxNQUFuQixFQUEyQjtBQUN6Qkg7QUFDRDs7QUFFRCxTQUFPRixJQUFQO0FBQ0QiLCJmaWxlIjoicGFyc2UuanMiLCJzb3VyY2VzQ29udGVudCI6WyJleHBvcnQgZnVuY3Rpb24gcGFyc2VQYXRjaCh1bmlEaWZmLCBvcHRpb25zID0ge30pIHtcbiAgbGV0IGRpZmZzdHIgPSB1bmlEaWZmLnNwbGl0KC9cXHJcXG58W1xcblxcdlxcZlxcclxceDg1XS8pLFxuICAgICAgZGVsaW1pdGVycyA9IHVuaURpZmYubWF0Y2goL1xcclxcbnxbXFxuXFx2XFxmXFxyXFx4ODVdL2cpIHx8IFtdLFxuICAgICAgbGlzdCA9IFtdLFxuICAgICAgaSA9IDA7XG5cbiAgZnVuY3Rpb24gcGFyc2VJbmRleCgpIHtcbiAgICBsZXQgaW5kZXggPSB7fTtcbiAgICBsaXN0LnB1c2goaW5kZXgpO1xuXG4gICAgLy8gUGFyc2UgZGlmZiBtZXRhZGF0YVxuICAgIHdoaWxlIChpIDwgZGlmZnN0ci5sZW5ndGgpIHtcbiAgICAgIGxldCBsaW5lID0gZGlmZnN0cltpXTtcblxuICAgICAgLy8gRmlsZSBoZWFkZXIgZm91bmQsIGVuZCBwYXJzaW5nIGRpZmYgbWV0YWRhdGFcbiAgICAgIGlmICgvXihcXC1cXC1cXC18XFwrXFwrXFwrfEBAKVxccy8udGVzdChsaW5lKSkge1xuICAgICAgICBicmVhaztcbiAgICAgIH1cblxuICAgICAgLy8gRGlmZiBpbmRleFxuICAgICAgbGV0IGhlYWRlciA9ICgvXig/OkluZGV4OnxkaWZmKD86IC1yIFxcdyspKylcXHMrKC4rPylcXHMqJC8pLmV4ZWMobGluZSk7XG4gICAgICBpZiAoaGVhZGVyKSB7XG4gICAgICAgIGluZGV4LmluZGV4ID0gaGVhZGVyWzFdO1xuICAgICAgfVxuXG4gICAgICBpKys7XG4gICAgfVxuXG4gICAgLy8gUGFyc2UgZmlsZSBoZWFkZXJzIGlmIHRoZXkgYXJlIGRlZmluZWQuIFVuaWZpZWQgZGlmZiByZXF1aXJlcyB0aGVtLCBidXRcbiAgICAvLyB0aGVyZSdzIG5vIHRlY2huaWNhbCBpc3N1ZXMgdG8gaGF2ZSBhbiBpc29sYXRlZCBodW5rIHdpdGhvdXQgZmlsZSBoZWFkZXJcbiAgICBwYXJzZUZpbGVIZWFkZXIoaW5kZXgpO1xuICAgIHBhcnNlRmlsZUhlYWRlcihpbmRleCk7XG5cbiAgICAvLyBQYXJzZSBodW5rc1xuICAgIGluZGV4Lmh1bmtzID0gW107XG5cbiAgICB3aGlsZSAoaSA8IGRpZmZzdHIubGVuZ3RoKSB7XG4gICAgICBsZXQgbGluZSA9IGRpZmZzdHJbaV07XG5cbiAgICAgIGlmICgvXihJbmRleDp8ZGlmZnxcXC1cXC1cXC18XFwrXFwrXFwrKVxccy8udGVzdChsaW5lKSkge1xuICAgICAgICBicmVhaztcbiAgICAgIH0gZWxzZSBpZiAoL15AQC8udGVzdChsaW5lKSkge1xuICAgICAgICBpbmRleC5odW5rcy5wdXNoKHBhcnNlSHVuaygpKTtcbiAgICAgIH0gZWxzZSBpZiAobGluZSAmJiBvcHRpb25zLnN0cmljdCkge1xuICAgICAgICAvLyBJZ25vcmUgdW5leHBlY3RlZCBjb250ZW50IHVubGVzcyBpbiBzdHJpY3QgbW9kZVxuICAgICAgICB0aHJvdyBuZXcgRXJyb3IoJ1Vua25vd24gbGluZSAnICsgKGkgKyAxKSArICcgJyArIEpTT04uc3RyaW5naWZ5KGxpbmUpKTtcbiAgICAgIH0gZWxzZSB7XG4gICAgICAgIGkrKztcbiAgICAgIH1cbiAgICB9XG4gIH1cblxuICAvLyBQYXJzZXMgdGhlIC0tLSBhbmQgKysrIGhlYWRlcnMsIGlmIG5vbmUgYXJlIGZvdW5kLCBubyBsaW5lc1xuICAvLyBhcmUgY29uc3VtZWQuXG4gIGZ1bmN0aW9uIHBhcnNlRmlsZUhlYWRlcihpbmRleCkge1xuICAgIGNvbnN0IGZpbGVIZWFkZXIgPSAoL14oLS0tfFxcK1xcK1xcKylcXHMrKC4qKSQvKS5leGVjKGRpZmZzdHJbaV0pO1xuICAgIGlmIChmaWxlSGVhZGVyKSB7XG4gICAgICBsZXQga2V5UHJlZml4ID0gZmlsZUhlYWRlclsxXSA9PT0gJy0tLScgPyAnb2xkJyA6ICduZXcnO1xuICAgICAgY29uc3QgZGF0YSA9IGZpbGVIZWFkZXJbMl0uc3BsaXQoJ1xcdCcsIDIpO1xuICAgICAgbGV0IGZpbGVOYW1lID0gZGF0YVswXS5yZXBsYWNlKC9cXFxcXFxcXC9nLCAnXFxcXCcpO1xuICAgICAgaWYgKC9eXCIuKlwiJC8udGVzdChmaWxlTmFtZSkpIHtcbiAgICAgICAgZmlsZU5hbWUgPSBmaWxlTmFtZS5zdWJzdHIoMSwgZmlsZU5hbWUubGVuZ3RoIC0gMik7XG4gICAgICB9XG4gICAgICBpbmRleFtrZXlQcmVmaXggKyAnRmlsZU5hbWUnXSA9IGZpbGVOYW1lO1xuICAgICAgaW5kZXhba2V5UHJlZml4ICsgJ0hlYWRlciddID0gKGRhdGFbMV0gfHwgJycpLnRyaW0oKTtcblxuICAgICAgaSsrO1xuICAgIH1cbiAgfVxuXG4gIC8vIFBhcnNlcyBhIGh1bmtcbiAgLy8gVGhpcyBhc3N1bWVzIHRoYXQgd2UgYXJlIGF0IHRoZSBzdGFydCBvZiBhIGh1bmsuXG4gIGZ1bmN0aW9uIHBhcnNlSHVuaygpIHtcbiAgICBsZXQgY2h1bmtIZWFkZXJJbmRleCA9IGksXG4gICAgICAgIGNodW5rSGVhZGVyTGluZSA9IGRpZmZzdHJbaSsrXSxcbiAgICAgICAgY2h1bmtIZWFkZXIgPSBjaHVua0hlYWRlckxpbmUuc3BsaXQoL0BAIC0oXFxkKykoPzosKFxcZCspKT8gXFwrKFxcZCspKD86LChcXGQrKSk/IEBALyk7XG5cbiAgICBsZXQgaHVuayA9IHtcbiAgICAgIG9sZFN0YXJ0OiArY2h1bmtIZWFkZXJbMV0sXG4gICAgICBvbGRMaW5lczogK2NodW5rSGVhZGVyWzJdIHx8IDEsXG4gICAgICBuZXdTdGFydDogK2NodW5rSGVhZGVyWzNdLFxuICAgICAgbmV3TGluZXM6ICtjaHVua0hlYWRlcls0XSB8fCAxLFxuICAgICAgbGluZXM6IFtdLFxuICAgICAgbGluZWRlbGltaXRlcnM6IFtdXG4gICAgfTtcblxuICAgIGxldCBhZGRDb3VudCA9IDAsXG4gICAgICAgIHJlbW92ZUNvdW50ID0gMDtcbiAgICBmb3IgKDsgaSA8IGRpZmZzdHIubGVuZ3RoOyBpKyspIHtcbiAgICAgIC8vIExpbmVzIHN0YXJ0aW5nIHdpdGggJy0tLScgY291bGQgYmUgbWlzdGFrZW4gZm9yIHRoZSBcInJlbW92ZSBsaW5lXCIgb3BlcmF0aW9uXG4gICAgICAvLyBCdXQgdGhleSBjb3VsZCBiZSB0aGUgaGVhZGVyIGZvciB0aGUgbmV4dCBmaWxlLiBUaGVyZWZvcmUgcHJ1bmUgc3VjaCBjYXNlcyBvdXQuXG4gICAgICBpZiAoZGlmZnN0cltpXS5pbmRleE9mKCctLS0gJykgPT09IDBcbiAgICAgICAgICAgICYmIChpICsgMiA8IGRpZmZzdHIubGVuZ3RoKVxuICAgICAgICAgICAgJiYgZGlmZnN0cltpICsgMV0uaW5kZXhPZignKysrICcpID09PSAwXG4gICAgICAgICAgICAmJiBkaWZmc3RyW2kgKyAyXS5pbmRleE9mKCdAQCcpID09PSAwKSB7XG4gICAgICAgICAgYnJlYWs7XG4gICAgICB9XG4gICAgICBsZXQgb3BlcmF0aW9uID0gKGRpZmZzdHJbaV0ubGVuZ3RoID09IDAgJiYgaSAhPSAoZGlmZnN0ci5sZW5ndGggLSAxKSkgPyAnICcgOiBkaWZmc3RyW2ldWzBdO1xuXG4gICAgICBpZiAob3BlcmF0aW9uID09PSAnKycgfHwgb3BlcmF0aW9uID09PSAnLScgfHwgb3BlcmF0aW9uID09PSAnICcgfHwgb3BlcmF0aW9uID09PSAnXFxcXCcpIHtcbiAgICAgICAgaHVuay5saW5lcy5wdXNoKGRpZmZzdHJbaV0pO1xuICAgICAgICBodW5rLmxpbmVkZWxpbWl0ZXJzLnB1c2goZGVsaW1pdGVyc1tpXSB8fCAnXFxuJyk7XG5cbiAgICAgICAgaWYgKG9wZXJhdGlvbiA9PT0gJysnKSB7XG4gICAgICAgICAgYWRkQ291bnQrKztcbiAgICAgICAgfSBlbHNlIGlmIChvcGVyYXRpb24gPT09ICctJykge1xuICAgICAgICAgIHJlbW92ZUNvdW50Kys7XG4gICAgICAgIH0gZWxzZSBpZiAob3BlcmF0aW9uID09PSAnICcpIHtcbiAgICAgICAgICBhZGRDb3VudCsrO1xuICAgICAgICAgIHJlbW92ZUNvdW50Kys7XG4gICAgICAgIH1cbiAgICAgIH0gZWxzZSB7XG4gICAgICAgIGJyZWFrO1xuICAgICAgfVxuICAgIH1cblxuICAgIC8vIEhhbmRsZSB0aGUgZW1wdHkgYmxvY2sgY291bnQgY2FzZVxuICAgIGlmICghYWRkQ291bnQgJiYgaHVuay5uZXdMaW5lcyA9PT0gMSkge1xuICAgICAgaHVuay5uZXdMaW5lcyA9IDA7XG4gICAgfVxuICAgIGlmICghcmVtb3ZlQ291bnQgJiYgaHVuay5vbGRMaW5lcyA9PT0gMSkge1xuICAgICAgaHVuay5vbGRMaW5lcyA9IDA7XG4gICAgfVxuXG4gICAgLy8gUGVyZm9ybSBvcHRpb25hbCBzYW5pdHkgY2hlY2tpbmdcbiAgICBpZiAob3B0aW9ucy5zdHJpY3QpIHtcbiAgICAgIGlmIChhZGRDb3VudCAhPT0gaHVuay5uZXdMaW5lcykge1xuICAgICAgICB0aHJvdyBuZXcgRXJyb3IoJ0FkZGVkIGxpbmUgY291bnQgZGlkIG5vdCBtYXRjaCBmb3IgaHVuayBhdCBsaW5lICcgKyAoY2h1bmtIZWFkZXJJbmRleCArIDEpKTtcbiAgICAgIH1cbiAgICAgIGlmIChyZW1vdmVDb3VudCAhPT0gaHVuay5vbGRMaW5lcykge1xuICAgICAgICB0aHJvdyBuZXcgRXJyb3IoJ1JlbW92ZWQgbGluZSBjb3VudCBkaWQgbm90IG1hdGNoIGZvciBodW5rIGF0IGxpbmUgJyArIChjaHVua0hlYWRlckluZGV4ICsgMSkpO1xuICAgICAgfVxuICAgIH1cblxuICAgIHJldHVybiBodW5rO1xuICB9XG5cbiAgd2hpbGUgKGkgPCBkaWZmc3RyLmxlbmd0aCkge1xuICAgIHBhcnNlSW5kZXgoKTtcbiAgfVxuXG4gIHJldHVybiBsaXN0O1xufVxuIl19
+
+
+/***/ }),
+/* 12 */
+/***/ (function(module, exports) {
+
+	/*istanbul ignore start*/"use strict";
+
+	exports.__esModule = true;
+
+	exports["default"] = /*istanbul ignore end*/function (start, minLine, maxLine) {
+	  var wantForward = true,
+	      backwardExhausted = false,
+	      forwardExhausted = false,
+	      localOffset = 1;
+
+	  return function iterator() {
+	    if (wantForward && !forwardExhausted) {
+	      if (backwardExhausted) {
+	        localOffset++;
+	      } else {
+	        wantForward = false;
+	      }
+
+	      // Check if trying to fit beyond text length, and if not, check it fits
+	      // after offset location (or desired location on first iteration)
+	      if (start + localOffset <= maxLine) {
+	        return localOffset;
+	      }
+
+	      forwardExhausted = true;
+	    }
+
+	    if (!backwardExhausted) {
+	      if (!forwardExhausted) {
+	        wantForward = true;
+	      }
+
+	      // Check if trying to fit before text beginning, and if not, check it fits
+	      // before offset location
+	      if (minLine <= start - localOffset) {
+	        return -localOffset++;
+	      }
+
+	      backwardExhausted = true;
+	      return iterator();
+	    }
+
+	    // We tried to fit hunk before text beginning and beyond text length, then
+	    // hunk can't fit on the text. Return undefined
+	  };
+	};
+	//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy91dGlsL2Rpc3RhbmNlLWl0ZXJhdG9yLmpzIl0sIm5hbWVzIjpbInN0YXJ0IiwibWluTGluZSIsIm1heExpbmUiLCJ3YW50Rm9yd2FyZCIsImJhY2t3YXJkRXhoYXVzdGVkIiwiZm9yd2FyZEV4aGF1c3RlZCIsImxvY2FsT2Zmc2V0IiwiaXRlcmF0b3IiXSwibWFwcGluZ3MiOiI7Ozs7NENBR2UsVUFBU0EsS0FBVCxFQUFnQkMsT0FBaEIsRUFBeUJDLE9BQXpCLEVBQWtDO0FBQy9DLE1BQUlDLGNBQWMsSUFBbEI7QUFBQSxNQUNJQyxvQkFBb0IsS0FEeEI7QUFBQSxNQUVJQyxtQkFBbUIsS0FGdkI7QUFBQSxNQUdJQyxjQUFjLENBSGxCOztBQUtBLFNBQU8sU0FBU0MsUUFBVCxHQUFvQjtBQUN6QixRQUFJSixlQUFlLENBQUNFLGdCQUFwQixFQUFzQztBQUNwQyxVQUFJRCxpQkFBSixFQUF1QjtBQUNyQkU7QUFDRCxPQUZELE1BRU87QUFDTEgsc0JBQWMsS0FBZDtBQUNEOztBQUVEO0FBQ0E7QUFDQSxVQUFJSCxRQUFRTSxXQUFSLElBQXVCSixPQUEzQixFQUFvQztBQUNsQyxlQUFPSSxXQUFQO0FBQ0Q7O0FBRURELHlCQUFtQixJQUFuQjtBQUNEOztBQUVELFFBQUksQ0FBQ0QsaUJBQUwsRUFBd0I7QUFDdEIsVUFBSSxDQUFDQyxnQkFBTCxFQUF1QjtBQUNyQkYsc0JBQWMsSUFBZDtBQUNEOztBQUVEO0FBQ0E7QUFDQSxVQUFJRixXQUFXRCxRQUFRTSxXQUF2QixFQUFvQztBQUNsQyxlQUFPLENBQUNBLGFBQVI7QUFDRDs7QUFFREYsMEJBQW9CLElBQXBCO0FBQ0EsYUFBT0csVUFBUDtBQUNEOztBQUVEO0FBQ0E7QUFDRCxHQWxDRDtBQW1DRCxDIiwiZmlsZSI6ImRpc3RhbmNlLWl0ZXJhdG9yLmpzIiwic291cmNlc0NvbnRlbnQiOlsiLy8gSXRlcmF0b3IgdGhhdCB0cmF2ZXJzZXMgaW4gdGhlIHJhbmdlIG9mIFttaW4sIG1heF0sIHN0ZXBwaW5nXG4vLyBieSBkaXN0YW5jZSBmcm9tIGEgZ2l2ZW4gc3RhcnQgcG9zaXRpb24uIEkuZS4gZm9yIFswLCA0XSwgd2l0aFxuLy8gc3RhcnQgb2YgMiwgdGhpcyB3aWxsIGl0ZXJhdGUgMiwgMywgMSwgNCwgMC5cbmV4cG9ydCBkZWZhdWx0IGZ1bmN0aW9uKHN0YXJ0LCBtaW5MaW5lLCBtYXhMaW5lKSB7XG4gIGxldCB3YW50Rm9yd2FyZCA9IHRydWUsXG4gICAgICBiYWNrd2FyZEV4aGF1c3RlZCA9IGZhbHNlLFxuICAgICAgZm9yd2FyZEV4aGF1c3RlZCA9IGZhbHNlLFxuICAgICAgbG9jYWxPZmZzZXQgPSAxO1xuXG4gIHJldHVybiBmdW5jdGlvbiBpdGVyYXRvcigpIHtcbiAgICBpZiAod2FudEZvcndhcmQgJiYgIWZvcndhcmRFeGhhdXN0ZWQpIHtcbiAgICAgIGlmIChiYWNrd2FyZEV4aGF1c3RlZCkge1xuICAgICAgICBsb2NhbE9mZnNldCsrO1xuICAgICAgfSBlbHNlIHtcbiAgICAgICAgd2FudEZvcndhcmQgPSBmYWxzZTtcbiAgICAgIH1cblxuICAgICAgLy8gQ2hlY2sgaWYgdHJ5aW5nIHRvIGZpdCBiZXlvbmQgdGV4dCBsZW5ndGgsIGFuZCBpZiBub3QsIGNoZWNrIGl0IGZpdHNcbiAgICAgIC8vIGFmdGVyIG9mZnNldCBsb2NhdGlvbiAob3IgZGVzaXJlZCBsb2NhdGlvbiBvbiBmaXJzdCBpdGVyYXRpb24pXG4gICAgICBpZiAoc3RhcnQgKyBsb2NhbE9mZnNldCA8PSBtYXhMaW5lKSB7XG4gICAgICAgIHJldHVybiBsb2NhbE9mZnNldDtcbiAgICAgIH1cblxuICAgICAgZm9yd2FyZEV4aGF1c3RlZCA9IHRydWU7XG4gICAgfVxuXG4gICAgaWYgKCFiYWNrd2FyZEV4aGF1c3RlZCkge1xuICAgICAgaWYgKCFmb3J3YXJkRXhoYXVzdGVkKSB7XG4gICAgICAgIHdhbnRGb3J3YXJkID0gdHJ1ZTtcbiAgICAgIH1cblxuICAgICAgLy8gQ2hlY2sgaWYgdHJ5aW5nIHRvIGZpdCBiZWZvcmUgdGV4dCBiZWdpbm5pbmcsIGFuZCBpZiBub3QsIGNoZWNrIGl0IGZpdHNcbiAgICAgIC8vIGJlZm9yZSBvZmZzZXQgbG9jYXRpb25cbiAgICAgIGlmIChtaW5MaW5lIDw9IHN0YXJ0IC0gbG9jYWxPZmZzZXQpIHtcbiAgICAgICAgcmV0dXJuIC1sb2NhbE9mZnNldCsrO1xuICAgICAgfVxuXG4gICAgICBiYWNrd2FyZEV4aGF1c3RlZCA9IHRydWU7XG4gICAgICByZXR1cm4gaXRlcmF0b3IoKTtcbiAgICB9XG5cbiAgICAvLyBXZSB0cmllZCB0byBmaXQgaHVuayBiZWZvcmUgdGV4dCBiZWdpbm5pbmcgYW5kIGJleW9uZCB0ZXh0IGxlbmd0aCwgdGhlblxuICAgIC8vIGh1bmsgY2FuJ3QgZml0IG9uIHRoZSB0ZXh0LiBSZXR1cm4gdW5kZWZpbmVkXG4gIH07XG59XG4iXX0=
+
+
+/***/ }),
+/* 13 */
+/***/ (function(module, exports, __webpack_require__) {
+
+	/*istanbul ignore start*/'use strict';
+
+	exports.__esModule = true;
+	exports. /*istanbul ignore end*/calcLineCount = calcLineCount;
+	/*istanbul ignore start*/exports. /*istanbul ignore end*/merge = merge;
+
+	var /*istanbul ignore start*/_create = __webpack_require__(14) /*istanbul ignore end*/;
+
+	var /*istanbul ignore start*/_parse = __webpack_require__(11) /*istanbul ignore end*/;
+
+	var /*istanbul ignore start*/_array = __webpack_require__(15) /*istanbul ignore end*/;
+
+	/*istanbul ignore start*/function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
+
+	/*istanbul ignore end*/function calcLineCount(hunk) {
+	  /*istanbul ignore start*/var _calcOldNewLineCount = /*istanbul ignore end*/calcOldNewLineCount(hunk.lines),
+	      oldLines = _calcOldNewLineCount.oldLines,
+	      newLines = _calcOldNewLineCount.newLines;
+
+	  if (oldLines !== undefined) {
+	    hunk.oldLines = oldLines;
+	  } else {
+	    delete hunk.oldLines;
+	  }
+
+	  if (newLines !== undefined) {
+	    hunk.newLines = newLines;
+	  } else {
+	    delete hunk.newLines;
+	  }
+	}
+
+	function merge(mine, theirs, base) {
+	  mine = loadPatch(mine, base);
+	  theirs = loadPatch(theirs, base);
+
+	  var ret = {};
+
+	  // For index we just let it pass through as it doesn't have any necessary meaning.
+	  // Leaving sanity checks on this to the API consumer that may know more about the
+	  // meaning in their own context.
+	  if (mine.index || theirs.index) {
+	    ret.index = mine.index || theirs.index;
+	  }
+
+	  if (mine.newFileName || theirs.newFileName) {
+	    if (!fileNameChanged(mine)) {
+	      // No header or no change in ours, use theirs (and ours if theirs does not exist)
+	      ret.oldFileName = theirs.oldFileName || mine.oldFileName;
+	      ret.newFileName = theirs.newFileName || mine.newFileName;
+	      ret.oldHeader = theirs.oldHeader || mine.oldHeader;
+	      ret.newHeader = theirs.newHeader || mine.newHeader;
+	    } else if (!fileNameChanged(theirs)) {
+	      // No header or no change in theirs, use ours
+	      ret.oldFileName = mine.oldFileName;
+	      ret.newFileName = mine.newFileName;
+	      ret.oldHeader = mine.oldHeader;
+	      ret.newHeader = mine.newHeader;
+	    } else {
+	      // Both changed... figure it out
+	      ret.oldFileName = selectField(ret, mine.oldFileName, theirs.oldFileName);
+	      ret.newFileName = selectField(ret, mine.newFileName, theirs.newFileName);
+	      ret.oldHeader = selectField(ret, mine.oldHeader, theirs.oldHeader);
+	      ret.newHeader = selectField(ret, mine.newHeader, theirs.newHeader);
+	    }
+	  }
+
+	  ret.hunks = [];
+
+	  var mineIndex = 0,
+	      theirsIndex = 0,
+	      mineOffset = 0,
+	      theirsOffset = 0;
+
+	  while (mineIndex < mine.hunks.length || theirsIndex < theirs.hunks.length) {
+	    var mineCurrent = mine.hunks[mineIndex] || { oldStart: Infinity },
+	        theirsCurrent = theirs.hunks[theirsIndex] || { oldStart: Infinity };
+
+	    if (hunkBefore(mineCurrent, theirsCurrent)) {
+	      // This patch does not overlap with any of the others, yay.
+	      ret.hunks.push(cloneHunk(mineCurrent, mineOffset));
+	      mineIndex++;
+	      theirsOffset += mineCurrent.newLines - mineCurrent.oldLines;
+	    } else if (hunkBefore(theirsCurrent, mineCurrent)) {
+	      // This patch does not overlap with any of the others, yay.
+	      ret.hunks.push(cloneHunk(theirsCurrent, theirsOffset));
+	      theirsIndex++;
+	      mineOffset += theirsCurrent.newLines - theirsCurrent.oldLines;
+	    } else {
+	      // Overlap, merge as best we can
+	      var mergedHunk = {
+	        oldStart: Math.min(mineCurrent.oldStart, theirsCurrent.oldStart),
+	        oldLines: 0,
+	        newStart: Math.min(mineCurrent.newStart + mineOffset, theirsCurrent.oldStart + theirsOffset),
+	        newLines: 0,
+	        lines: []
+	      };
+	      mergeLines(mergedHunk, mineCurrent.oldStart, mineCurrent.lines, theirsCurrent.oldStart, theirsCurrent.lines);
+	      theirsIndex++;
+	      mineIndex++;
+
+	      ret.hunks.push(mergedHunk);
+	    }
+	  }
+
+	  return ret;
+	}
+
+	function loadPatch(param, base) {
+	  if (typeof param === 'string') {
+	    if (/^@@/m.test(param) || /^Index:/m.test(param)) {
+	      return (/*istanbul ignore start*/(0, _parse.parsePatch) /*istanbul ignore end*/(param)[0]
+	      );
+	    }
+
+	    if (!base) {
+	      throw new Error('Must provide a base reference or pass in a patch');
+	    }
+	    return (/*istanbul ignore start*/(0, _create.structuredPatch) /*istanbul ignore end*/(undefined, undefined, base, param)
+	    );
+	  }
+
+	  return param;
+	}
+
+	function fileNameChanged(patch) {
+	  return patch.newFileName && patch.newFileName !== patch.oldFileName;
+	}
+
+	function selectField(index, mine, theirs) {
+	  if (mine === theirs) {
+	    return mine;
+	  } else {
+	    index.conflict = true;
+	    return { mine: mine, theirs: theirs };
+	  }
+	}
+
+	function hunkBefore(test, check) {
+	  return test.oldStart < check.oldStart && test.oldStart + test.oldLines < check.oldStart;
+	}
+
+	function cloneHunk(hunk, offset) {
+	  return {
+	    oldStart: hunk.oldStart, oldLines: hunk.oldLines,
+	    newStart: hunk.newStart + offset, newLines: hunk.newLines,
+	    lines: hunk.lines
+	  };
+	}
+
+	function mergeLines(hunk, mineOffset, mineLines, theirOffset, theirLines) {
+	  // This will generally result in a conflicted hunk, but there are cases where the context
+	  // is the only overlap where we can successfully merge the content here.
+	  var mine = { offset: mineOffset, lines: mineLines, index: 0 },
+	      their = { offset: theirOffset, lines: theirLines, index: 0 };
+
+	  // Handle any leading content
+	  insertLeading(hunk, mine, their);
+	  insertLeading(hunk, their, mine);
+
+	  // Now in the overlap content. Scan through and select the best changes from each.
+	  while (mine.index < mine.lines.length && their.index < their.lines.length) {
+	    var mineCurrent = mine.lines[mine.index],
+	        theirCurrent = their.lines[their.index];
+
+	    if ((mineCurrent[0] === '-' || mineCurrent[0] === '+') && (theirCurrent[0] === '-' || theirCurrent[0] === '+')) {
+	      // Both modified ...
+	      mutualChange(hunk, mine, their);
+	    } else if (mineCurrent[0] === '+' && theirCurrent[0] === ' ') {
+	      /*istanbul ignore start*/var _hunk$lines;
+
+	      /*istanbul ignore end*/ // Mine inserted
+	      /*istanbul ignore start*/(_hunk$lines = /*istanbul ignore end*/hunk.lines).push. /*istanbul ignore start*/apply /*istanbul ignore end*/( /*istanbul ignore start*/_hunk$lines /*istanbul ignore end*/, /*istanbul ignore start*/_toConsumableArray( /*istanbul ignore end*/collectChange(mine)));
+	    } else if (theirCurrent[0] === '+' && mineCurrent[0] === ' ') {
+	      /*istanbul ignore start*/var _hunk$lines2;
+
+	      /*istanbul ignore end*/ // Theirs inserted
+	      /*istanbul ignore start*/(_hunk$lines2 = /*istanbul ignore end*/hunk.lines).push. /*istanbul ignore start*/apply /*istanbul ignore end*/( /*istanbul ignore start*/_hunk$lines2 /*istanbul ignore end*/, /*istanbul ignore start*/_toConsumableArray( /*istanbul ignore end*/collectChange(their)));
+	    } else if (mineCurrent[0] === '-' && theirCurrent[0] === ' ') {
+	      // Mine removed or edited
+	      removal(hunk, mine, their);
+	    } else if (theirCurrent[0] === '-' && mineCurrent[0] === ' ') {
+	      // Their removed or edited
+	      removal(hunk, their, mine, true);
+	    } else if (mineCurrent === theirCurrent) {
+	      // Context identity
+	      hunk.lines.push(mineCurrent);
+	      mine.index++;
+	      their.index++;
+	    } else {
+	      // Context mismatch
+	      conflict(hunk, collectChange(mine), collectChange(their));
+	    }
+	  }
+
+	  // Now push anything that may be remaining
+	  insertTrailing(hunk, mine);
+	  insertTrailing(hunk, their);
+
+	  calcLineCount(hunk);
+	}
+
+	function mutualChange(hunk, mine, their) {
+	  var myChanges = collectChange(mine),
+	      theirChanges = collectChange(their);
+
+	  if (allRemoves(myChanges) && allRemoves(theirChanges)) {
+	    // Special case for remove changes that are supersets of one another
+	    if ( /*istanbul ignore start*/(0, _array.arrayStartsWith) /*istanbul ignore end*/(myChanges, theirChanges) && skipRemoveSuperset(their, myChanges, myChanges.length - theirChanges.length)) {
+	      /*istanbul ignore start*/var _hunk$lines3;
+
+	      /*istanbul ignore end*/ /*istanbul ignore start*/(_hunk$lines3 = /*istanbul ignore end*/hunk.lines).push. /*istanbul ignore start*/apply /*istanbul ignore end*/( /*istanbul ignore start*/_hunk$lines3 /*istanbul ignore end*/, /*istanbul ignore start*/_toConsumableArray( /*istanbul ignore end*/myChanges));
+	      return;
+	    } else if ( /*istanbul ignore start*/(0, _array.arrayStartsWith) /*istanbul ignore end*/(theirChanges, myChanges) && skipRemoveSuperset(mine, theirChanges, theirChanges.length - myChanges.length)) {
+	      /*istanbul ignore start*/var _hunk$lines4;
+
+	      /*istanbul ignore end*/ /*istanbul ignore start*/(_hunk$lines4 = /*istanbul ignore end*/hunk.lines).push. /*istanbul ignore start*/apply /*istanbul ignore end*/( /*istanbul ignore start*/_hunk$lines4 /*istanbul ignore end*/, /*istanbul ignore start*/_toConsumableArray( /*istanbul ignore end*/theirChanges));
+	      return;
+	    }
+	  } else if ( /*istanbul ignore start*/(0, _array.arrayEqual) /*istanbul ignore end*/(myChanges, theirChanges)) {
+	    /*istanbul ignore start*/var _hunk$lines5;
+
+	    /*istanbul ignore end*/ /*istanbul ignore start*/(_hunk$lines5 = /*istanbul ignore end*/hunk.lines).push. /*istanbul ignore start*/apply /*istanbul ignore end*/( /*istanbul ignore start*/_hunk$lines5 /*istanbul ignore end*/, /*istanbul ignore start*/_toConsumableArray( /*istanbul ignore end*/myChanges));
+	    return;
+	  }
+
+	  conflict(hunk, myChanges, theirChanges);
+	}
+
+	function removal(hunk, mine, their, swap) {
+	  var myChanges = collectChange(mine),
+	      theirChanges = collectContext(their, myChanges);
+	  if (theirChanges.merged) {
+	    /*istanbul ignore start*/var _hunk$lines6;
+
+	    /*istanbul ignore end*/ /*istanbul ignore start*/(_hunk$lines6 = /*istanbul ignore end*/hunk.lines).push. /*istanbul ignore start*/apply /*istanbul ignore end*/( /*istanbul ignore start*/_hunk$lines6 /*istanbul ignore end*/, /*istanbul ignore start*/_toConsumableArray( /*istanbul ignore end*/theirChanges.merged));
+	  } else {
+	    conflict(hunk, swap ? theirChanges : myChanges, swap ? myChanges : theirChanges);
+	  }
+	}
+
+	function conflict(hunk, mine, their) {
+	  hunk.conflict = true;
+	  hunk.lines.push({
+	    conflict: true,
+	    mine: mine,
+	    theirs: their
+	  });
+	}
+
+	function insertLeading(hunk, insert, their) {
+	  while (insert.offset < their.offset && insert.index < insert.lines.length) {
+	    var line = insert.lines[insert.index++];
+	    hunk.lines.push(line);
+	    insert.offset++;
+	  }
+	}
+	function insertTrailing(hunk, insert) {
+	  while (insert.index < insert.lines.length) {
+	    var line = insert.lines[insert.index++];
+	    hunk.lines.push(line);
+	  }
+	}
+
+	function collectChange(state) {
+	  var ret = [],
+	      operation = state.lines[state.index][0];
+	  while (state.index < state.lines.length) {
+	    var line = state.lines[state.index];
+
+	    // Group additions that are immediately after subtractions and treat them as one "atomic" modify change.
+	    if (operation === '-' && line[0] === '+') {
+	      operation = '+';
+	    }
+
+	    if (operation === line[0]) {
+	      ret.push(line);
+	      state.index++;
+	    } else {
+	      break;
+	    }
+	  }
+
+	  return ret;
+	}
+	function collectContext(state, matchChanges) {
+	  var changes = [],
+	      merged = [],
+	      matchIndex = 0,
+	      contextChanges = false,
+	      conflicted = false;
+	  while (matchIndex < matchChanges.length && state.index < state.lines.length) {
+	    var change = state.lines[state.index],
+	        match = matchChanges[matchIndex];
+
+	    // Once we've hit our add, then we are done
+	    if (match[0] === '+') {
+	      break;
+	    }
+
+	    contextChanges = contextChanges || change[0] !== ' ';
+
+	    merged.push(match);
+	    matchIndex++;
+
+	    // Consume any additions in the other block as a conflict to attempt
+	    // to pull in the remaining context after this
+	    if (change[0] === '+') {
+	      conflicted = true;
+
+	      while (change[0] === '+') {
+	        changes.push(change);
+	        change = state.lines[++state.index];
+	      }
+	    }
+
+	    if (match.substr(1) === change.substr(1)) {
+	      changes.push(change);
+	      state.index++;
+	    } else {
+	      conflicted = true;
+	    }
+	  }
+
+	  if ((matchChanges[matchIndex] || '')[0] === '+' && contextChanges) {
+	    conflicted = true;
+	  }
+
+	  if (conflicted) {
+	    return changes;
+	  }
+
+	  while (matchIndex < matchChanges.length) {
+	    merged.push(matchChanges[matchIndex++]);
+	  }
+
+	  return {
+	    merged: merged,
+	    changes: changes
+	  };
+	}
+
+	function allRemoves(changes) {
+	  return changes.reduce(function (prev, change) {
+	    return prev && change[0] === '-';
+	  }, true);
+	}
+	function skipRemoveSuperset(state, removeChanges, delta) {
+	  for (var i = 0; i < delta; i++) {
+	    var changeContent = removeChanges[removeChanges.length - delta + i].substr(1);
+	    if (state.lines[state.index + i] !== ' ' + changeContent) {
+	      return false;
+	    }
+	  }
+
+	  state.index += delta;
+	  return true;
+	}
+
+	function calcOldNewLineCount(lines) {
+	  var oldLines = 0;
+	  var newLines = 0;
+
+	  lines.forEach(function (line) {
+	    if (typeof line !== 'string') {
+	      var myCount = calcOldNewLineCount(line.mine);
+	      var theirCount = calcOldNewLineCount(line.theirs);
+
+	      if (oldLines !== undefined) {
+	        if (myCount.oldLines === theirCount.oldLines) {
+	          oldLines += myCount.oldLines;
+	        } else {
+	          oldLines = undefined;
+	        }
+	      }
+
+	      if (newLines !== undefined) {
+	        if (myCount.newLines === theirCount.newLines) {
+	          newLines += myCount.newLines;
+	        } else {
+	          newLines = undefined;
+	        }
+	      }
+	    } else {
+	      if (newLines !== undefined && (line[0] === '+' || line[0] === ' ')) {
+	        newLines++;
+	      }
+	      if (oldLines !== undefined && (line[0] === '-' || line[0] === ' ')) {
+	        oldLines++;
+	      }
+	    }
+	  });
+
+	  return { oldLines: oldLines, newLines: newLines };
+	}
+	//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9wYXRjaC9tZXJnZS5qcyJdLCJuYW1lcyI6WyJjYWxjTGluZUNvdW50IiwibWVyZ2UiLCJodW5rIiwiY2FsY09sZE5ld0xpbmVDb3VudCIsImxpbmVzIiwib2xkTGluZXMiLCJuZXdMaW5lcyIsInVuZGVmaW5lZCIsIm1pbmUiLCJ0aGVpcnMiLCJiYXNlIiwibG9hZFBhdGNoIiwicmV0IiwiaW5kZXgiLCJuZXdGaWxlTmFtZSIsImZpbGVOYW1lQ2hhbmdlZCIsIm9sZEZpbGVOYW1lIiwib2xkSGVhZGVyIiwibmV3SGVhZGVyIiwic2VsZWN0RmllbGQiLCJodW5rcyIsIm1pbmVJbmRleCIsInRoZWlyc0luZGV4IiwibWluZU9mZnNldCIsInRoZWlyc09mZnNldCIsImxlbmd0aCIsIm1pbmVDdXJyZW50Iiwib2xkU3RhcnQiLCJJbmZpbml0eSIsInRoZWlyc0N1cnJlbnQiLCJodW5rQmVmb3JlIiwicHVzaCIsImNsb25lSHVuayIsIm1lcmdlZEh1bmsiLCJNYXRoIiwibWluIiwibmV3U3RhcnQiLCJtZXJnZUxpbmVzIiwicGFyYW0iLCJ0ZXN0IiwiRXJyb3IiLCJwYXRjaCIsImNvbmZsaWN0IiwiY2hlY2siLCJvZmZzZXQiLCJtaW5lTGluZXMiLCJ0aGVpck9mZnNldCIsInRoZWlyTGluZXMiLCJ0aGVpciIsImluc2VydExlYWRpbmciLCJ0aGVpckN1cnJlbnQiLCJtdXR1YWxDaGFuZ2UiLCJjb2xsZWN0Q2hhbmdlIiwicmVtb3ZhbCIsImluc2VydFRyYWlsaW5nIiwibXlDaGFuZ2VzIiwidGhlaXJDaGFuZ2VzIiwiYWxsUmVtb3ZlcyIsInNraXBSZW1vdmVTdXBlcnNldCIsInN3YXAiLCJjb2xsZWN0Q29udGV4dCIsIm1lcmdlZCIsImluc2VydCIsImxpbmUiLCJzdGF0ZSIsIm9wZXJhdGlvbiIsIm1hdGNoQ2hhbmdlcyIsImNoYW5nZXMiLCJtYXRjaEluZGV4IiwiY29udGV4dENoYW5nZXMiLCJjb25mbGljdGVkIiwiY2hhbmdlIiwibWF0Y2giLCJzdWJzdHIiLCJyZWR1Y2UiLCJwcmV2IiwicmVtb3ZlQ2hhbmdlcyIsImRlbHRhIiwiaSIsImNoYW5nZUNvbnRlbnQiLCJmb3JFYWNoIiwibXlDb3VudCIsInRoZWlyQ291bnQiXSwibWFwcGluZ3MiOiI7OztnQ0FLZ0JBLGEsR0FBQUEsYTt5REFnQkFDLEssR0FBQUEsSzs7QUFyQmhCOztBQUNBOztBQUVBOzs7O3VCQUVPLFNBQVNELGFBQVQsQ0FBdUJFLElBQXZCLEVBQTZCO0FBQUEsNkVBQ0xDLG9CQUFvQkQsS0FBS0UsS0FBekIsQ0FESztBQUFBLE1BQzNCQyxRQUQyQix3QkFDM0JBLFFBRDJCO0FBQUEsTUFDakJDLFFBRGlCLHdCQUNqQkEsUUFEaUI7O0FBR2xDLE1BQUlELGFBQWFFLFNBQWpCLEVBQTRCO0FBQzFCTCxTQUFLRyxRQUFMLEdBQWdCQSxRQUFoQjtBQUNELEdBRkQsTUFFTztBQUNMLFdBQU9ILEtBQUtHLFFBQVo7QUFDRDs7QUFFRCxNQUFJQyxhQUFhQyxTQUFqQixFQUE0QjtBQUMxQkwsU0FBS0ksUUFBTCxHQUFnQkEsUUFBaEI7QUFDRCxHQUZELE1BRU87QUFDTCxXQUFPSixLQUFLSSxRQUFaO0FBQ0Q7QUFDRjs7QUFFTSxTQUFTTCxLQUFULENBQWVPLElBQWYsRUFBcUJDLE1BQXJCLEVBQTZCQyxJQUE3QixFQUFtQztBQUN4Q0YsU0FBT0csVUFBVUgsSUFBVixFQUFnQkUsSUFBaEIsQ0FBUDtBQUNBRCxXQUFTRSxVQUFVRixNQUFWLEVBQWtCQyxJQUFsQixDQUFUOztBQUVBLE1BQUlFLE1BQU0sRUFBVjs7QUFFQTtBQUNBO0FBQ0E7QUFDQSxNQUFJSixLQUFLSyxLQUFMLElBQWNKLE9BQU9JLEtBQXpCLEVBQWdDO0FBQzlCRCxRQUFJQyxLQUFKLEdBQVlMLEtBQUtLLEtBQUwsSUFBY0osT0FBT0ksS0FBakM7QUFDRDs7QUFFRCxNQUFJTCxLQUFLTSxXQUFMLElBQW9CTCxPQUFPSyxXQUEvQixFQUE0QztBQUMxQyxRQUFJLENBQUNDLGdCQUFnQlAsSUFBaEIsQ0FBTCxFQUE0QjtBQUMxQjtBQUNBSSxVQUFJSSxXQUFKLEdBQWtCUCxPQUFPTyxXQUFQLElBQXNCUixLQUFLUSxXQUE3QztBQUNBSixVQUFJRSxXQUFKLEdBQWtCTCxPQUFPSyxXQUFQLElBQXNCTixLQUFLTSxXQUE3QztBQUNBRixVQUFJSyxTQUFKLEdBQWdCUixPQUFPUSxTQUFQLElBQW9CVCxLQUFLUyxTQUF6QztBQUNBTCxVQUFJTSxTQUFKLEdBQWdCVCxPQUFPUyxTQUFQLElBQW9CVixLQUFLVSxTQUF6QztBQUNELEtBTkQsTUFNTyxJQUFJLENBQUNILGdCQUFnQk4sTUFBaEIsQ0FBTCxFQUE4QjtBQUNuQztBQUNBRyxVQUFJSSxXQUFKLEdBQWtCUixLQUFLUSxXQUF2QjtBQUNBSixVQUFJRSxXQUFKLEdBQWtCTixLQUFLTSxXQUF2QjtBQUNBRixVQUFJSyxTQUFKLEdBQWdCVCxLQUFLUyxTQUFyQjtBQUNBTCxVQUFJTSxTQUFKLEdBQWdCVixLQUFLVSxTQUFyQjtBQUNELEtBTk0sTUFNQTtBQUNMO0FBQ0FOLFVBQUlJLFdBQUosR0FBa0JHLFlBQVlQLEdBQVosRUFBaUJKLEtBQUtRLFdBQXRCLEVBQW1DUCxPQUFPTyxXQUExQyxDQUFsQjtBQUNBSixVQUFJRSxXQUFKLEdBQWtCSyxZQUFZUCxHQUFaLEVBQWlCSixLQUFLTSxXQUF0QixFQUFtQ0wsT0FBT0ssV0FBMUMsQ0FBbEI7QUFDQUYsVUFBSUssU0FBSixHQUFnQkUsWUFBWVAsR0FBWixFQUFpQkosS0FBS1MsU0FBdEIsRUFBaUNSLE9BQU9RLFNBQXhDLENBQWhCO0FBQ0FMLFVBQUlNLFNBQUosR0FBZ0JDLFlBQVlQLEdBQVosRUFBaUJKLEtBQUtVLFNBQXRCLEVBQWlDVCxPQUFPUyxTQUF4QyxDQUFoQjtBQUNEO0FBQ0Y7O0FBRUROLE1BQUlRLEtBQUosR0FBWSxFQUFaOztBQUVBLE1BQUlDLFlBQVksQ0FBaEI7QUFBQSxNQUNJQyxjQUFjLENBRGxCO0FBQUEsTUFFSUMsYUFBYSxDQUZqQjtBQUFBLE1BR0lDLGVBQWUsQ0FIbkI7O0FBS0EsU0FBT0gsWUFBWWIsS0FBS1ksS0FBTCxDQUFXSyxNQUF2QixJQUFpQ0gsY0FBY2IsT0FBT1csS0FBUCxDQUFhSyxNQUFuRSxFQUEyRTtBQUN6RSxRQUFJQyxjQUFjbEIsS0FBS1ksS0FBTCxDQUFXQyxTQUFYLEtBQXlCLEVBQUNNLFVBQVVDLFFBQVgsRUFBM0M7QUFBQSxRQUNJQyxnQkFBZ0JwQixPQUFPVyxLQUFQLENBQWFFLFdBQWIsS0FBNkIsRUFBQ0ssVUFBVUMsUUFBWCxFQURqRDs7QUFHQSxRQUFJRSxXQUFXSixXQUFYLEVBQXdCRyxhQUF4QixDQUFKLEVBQTRDO0FBQzFDO0FBQ0FqQixVQUFJUSxLQUFKLENBQVVXLElBQVYsQ0FBZUMsVUFBVU4sV0FBVixFQUF1QkgsVUFBdkIsQ0FBZjtBQUNBRjtBQUNBRyxzQkFBZ0JFLFlBQVlwQixRQUFaLEdBQXVCb0IsWUFBWXJCLFFBQW5EO0FBQ0QsS0FMRCxNQUtPLElBQUl5QixXQUFXRCxhQUFYLEVBQTBCSCxXQUExQixDQUFKLEVBQTRDO0FBQ2pEO0FBQ0FkLFVBQUlRLEtBQUosQ0FBVVcsSUFBVixDQUFlQyxVQUFVSCxhQUFWLEVBQXlCTCxZQUF6QixDQUFmO0FBQ0FGO0FBQ0FDLG9CQUFjTSxjQUFjdkIsUUFBZCxHQUF5QnVCLGNBQWN4QixRQUFyRDtBQUNELEtBTE0sTUFLQTtBQUNMO0FBQ0EsVUFBSTRCLGFBQWE7QUFDZk4sa0JBQVVPLEtBQUtDLEdBQUwsQ0FBU1QsWUFBWUMsUUFBckIsRUFBK0JFLGNBQWNGLFFBQTdDLENBREs7QUFFZnRCLGtCQUFVLENBRks7QUFHZitCLGtCQUFVRixLQUFLQyxHQUFMLENBQVNULFlBQVlVLFFBQVosR0FBdUJiLFVBQWhDLEVBQTRDTSxjQUFjRixRQUFkLEdBQXlCSCxZQUFyRSxDQUhLO0FBSWZsQixrQkFBVSxDQUpLO0FBS2ZGLGVBQU87QUFMUSxPQUFqQjtBQU9BaUMsaUJBQVdKLFVBQVgsRUFBdUJQLFlBQVlDLFFBQW5DLEVBQTZDRCxZQUFZdEIsS0FBekQsRUFBZ0V5QixjQUFjRixRQUE5RSxFQUF3RkUsY0FBY3pCLEtBQXRHO0FBQ0FrQjtBQUNBRDs7QUFFQVQsVUFBSVEsS0FBSixDQUFVVyxJQUFWLENBQWVFLFVBQWY7QUFDRDtBQUNGOztBQUVELFNBQU9yQixHQUFQO0FBQ0Q7O0FBRUQsU0FBU0QsU0FBVCxDQUFtQjJCLEtBQW5CLEVBQTBCNUIsSUFBMUIsRUFBZ0M7QUFDOUIsTUFBSSxPQUFPNEIsS0FBUCxLQUFpQixRQUFyQixFQUErQjtBQUM3QixRQUFJLE9BQU9DLElBQVAsQ0FBWUQsS0FBWixLQUF1QixXQUFXQyxJQUFYLENBQWdCRCxLQUFoQixDQUEzQixFQUFvRDtBQUNsRCxhQUFPLHlFQUFXQSxLQUFYLEVBQWtCLENBQWxCO0FBQVA7QUFDRDs7QUFFRCxRQUFJLENBQUM1QixJQUFMLEVBQVc7QUFDVCxZQUFNLElBQUk4QixLQUFKLENBQVUsa0RBQVYsQ0FBTjtBQUNEO0FBQ0QsV0FBTywrRUFBZ0JqQyxTQUFoQixFQUEyQkEsU0FBM0IsRUFBc0NHLElBQXRDLEVBQTRDNEIsS0FBNUM7QUFBUDtBQUNEOztBQUVELFNBQU9BLEtBQVA7QUFDRDs7QUFFRCxTQUFTdkIsZUFBVCxDQUF5QjBCLEtBQXpCLEVBQWdDO0FBQzlCLFNBQU9BLE1BQU0zQixXQUFOLElBQXFCMkIsTUFBTTNCLFdBQU4sS0FBc0IyQixNQUFNekIsV0FBeEQ7QUFDRDs7QUFFRCxTQUFTRyxXQUFULENBQXFCTixLQUFyQixFQUE0QkwsSUFBNUIsRUFBa0NDLE1BQWxDLEVBQTBDO0FBQ3hDLE1BQUlELFNBQVNDLE1BQWIsRUFBcUI7QUFDbkIsV0FBT0QsSUFBUDtBQUNELEdBRkQsTUFFTztBQUNMSyxVQUFNNkIsUUFBTixHQUFpQixJQUFqQjtBQUNBLFdBQU8sRUFBQ2xDLFVBQUQsRUFBT0MsY0FBUCxFQUFQO0FBQ0Q7QUFDRjs7QUFFRCxTQUFTcUIsVUFBVCxDQUFvQlMsSUFBcEIsRUFBMEJJLEtBQTFCLEVBQWlDO0FBQy9CLFNBQU9KLEtBQUtaLFFBQUwsR0FBZ0JnQixNQUFNaEIsUUFBdEIsSUFDRFksS0FBS1osUUFBTCxHQUFnQlksS0FBS2xDLFFBQXRCLEdBQWtDc0MsTUFBTWhCLFFBRDdDO0FBRUQ7O0FBRUQsU0FBU0ssU0FBVCxDQUFtQjlCLElBQW5CLEVBQXlCMEMsTUFBekIsRUFBaUM7QUFDL0IsU0FBTztBQUNMakIsY0FBVXpCLEtBQUt5QixRQURWLEVBQ29CdEIsVUFBVUgsS0FBS0csUUFEbkM7QUFFTCtCLGNBQVVsQyxLQUFLa0MsUUFBTCxHQUFnQlEsTUFGckIsRUFFNkJ0QyxVQUFVSixLQUFLSSxRQUY1QztBQUdMRixXQUFPRixLQUFLRTtBQUhQLEdBQVA7QUFLRDs7QUFFRCxTQUFTaUMsVUFBVCxDQUFvQm5DLElBQXBCLEVBQTBCcUIsVUFBMUIsRUFBc0NzQixTQUF0QyxFQUFpREMsV0FBakQsRUFBOERDLFVBQTlELEVBQTBFO0FBQ3hFO0FBQ0E7QUFDQSxNQUFJdkMsT0FBTyxFQUFDb0MsUUFBUXJCLFVBQVQsRUFBcUJuQixPQUFPeUMsU0FBNUIsRUFBdUNoQyxPQUFPLENBQTlDLEVBQVg7QUFBQSxNQUNJbUMsUUFBUSxFQUFDSixRQUFRRSxXQUFULEVBQXNCMUMsT0FBTzJDLFVBQTdCLEVBQXlDbEMsT0FBTyxDQUFoRCxFQURaOztBQUdBO0FBQ0FvQyxnQkFBYy9DLElBQWQsRUFBb0JNLElBQXBCLEVBQTBCd0MsS0FBMUI7QUFDQUMsZ0JBQWMvQyxJQUFkLEVBQW9COEMsS0FBcEIsRUFBMkJ4QyxJQUEzQjs7QUFFQTtBQUNBLFNBQU9BLEtBQUtLLEtBQUwsR0FBYUwsS0FBS0osS0FBTCxDQUFXcUIsTUFBeEIsSUFBa0N1QixNQUFNbkMsS0FBTixHQUFjbUMsTUFBTTVDLEtBQU4sQ0FBWXFCLE1BQW5FLEVBQTJFO0FBQ3pFLFFBQUlDLGNBQWNsQixLQUFLSixLQUFMLENBQVdJLEtBQUtLLEtBQWhCLENBQWxCO0FBQUEsUUFDSXFDLGVBQWVGLE1BQU01QyxLQUFOLENBQVk0QyxNQUFNbkMsS0FBbEIsQ0FEbkI7O0FBR0EsUUFBSSxDQUFDYSxZQUFZLENBQVosTUFBbUIsR0FBbkIsSUFBMEJBLFlBQVksQ0FBWixNQUFtQixHQUE5QyxNQUNJd0IsYUFBYSxDQUFiLE1BQW9CLEdBQXBCLElBQTJCQSxhQUFhLENBQWIsTUFBb0IsR0FEbkQsQ0FBSixFQUM2RDtBQUMzRDtBQUNBQyxtQkFBYWpELElBQWIsRUFBbUJNLElBQW5CLEVBQXlCd0MsS0FBekI7QUFDRCxLQUpELE1BSU8sSUFBSXRCLFlBQVksQ0FBWixNQUFtQixHQUFuQixJQUEwQndCLGFBQWEsQ0FBYixNQUFvQixHQUFsRCxFQUF1RDtBQUFBOztBQUFBLDhCQUM1RDtBQUNBLDBFQUFLOUMsS0FBTCxFQUFXMkIsSUFBWCw0TEFBb0JxQixjQUFjNUMsSUFBZCxDQUFwQjtBQUNELEtBSE0sTUFHQSxJQUFJMEMsYUFBYSxDQUFiLE1BQW9CLEdBQXBCLElBQTJCeEIsWUFBWSxDQUFaLE1BQW1CLEdBQWxELEVBQXVEO0FBQUE7O0FBQUEsOEJBQzVEO0FBQ0EsMkVBQUt0QixLQUFMLEVBQVcyQixJQUFYLDZMQUFvQnFCLGNBQWNKLEtBQWQsQ0FBcEI7QUFDRCxLQUhNLE1BR0EsSUFBSXRCLFlBQVksQ0FBWixNQUFtQixHQUFuQixJQUEwQndCLGFBQWEsQ0FBYixNQUFvQixHQUFsRCxFQUF1RDtBQUM1RDtBQUNBRyxjQUFRbkQsSUFBUixFQUFjTSxJQUFkLEVBQW9Cd0MsS0FBcEI7QUFDRCxLQUhNLE1BR0EsSUFBSUUsYUFBYSxDQUFiLE1BQW9CLEdBQXBCLElBQTJCeEIsWUFBWSxDQUFaLE1BQW1CLEdBQWxELEVBQXVEO0FBQzVEO0FBQ0EyQixjQUFRbkQsSUFBUixFQUFjOEMsS0FBZCxFQUFxQnhDLElBQXJCLEVBQTJCLElBQTNCO0FBQ0QsS0FITSxNQUdBLElBQUlrQixnQkFBZ0J3QixZQUFwQixFQUFrQztBQUN2QztBQUNBaEQsV0FBS0UsS0FBTCxDQUFXMkIsSUFBWCxDQUFnQkwsV0FBaEI7QUFDQWxCLFdBQUtLLEtBQUw7QUFDQW1DLFlBQU1uQyxLQUFOO0FBQ0QsS0FMTSxNQUtBO0FBQ0w7QUFDQTZCLGVBQVN4QyxJQUFULEVBQWVrRCxjQUFjNUMsSUFBZCxDQUFmLEVBQW9DNEMsY0FBY0osS0FBZCxDQUFwQztBQUNEO0FBQ0Y7O0FBRUQ7QUFDQU0saUJBQWVwRCxJQUFmLEVBQXFCTSxJQUFyQjtBQUNBOEMsaUJBQWVwRCxJQUFmLEVBQXFCOEMsS0FBckI7O0FBRUFoRCxnQkFBY0UsSUFBZDtBQUNEOztBQUVELFNBQVNpRCxZQUFULENBQXNCakQsSUFBdEIsRUFBNEJNLElBQTVCLEVBQWtDd0MsS0FBbEMsRUFBeUM7QUFDdkMsTUFBSU8sWUFBWUgsY0FBYzVDLElBQWQsQ0FBaEI7QUFBQSxNQUNJZ0QsZUFBZUosY0FBY0osS0FBZCxDQURuQjs7QUFHQSxNQUFJUyxXQUFXRixTQUFYLEtBQXlCRSxXQUFXRCxZQUFYLENBQTdCLEVBQXVEO0FBQ3JEO0FBQ0EsUUFBSSw4RUFBZ0JELFNBQWhCLEVBQTJCQyxZQUEzQixLQUNHRSxtQkFBbUJWLEtBQW5CLEVBQTBCTyxTQUExQixFQUFxQ0EsVUFBVTlCLE1BQVYsR0FBbUIrQixhQUFhL0IsTUFBckUsQ0FEUCxFQUNxRjtBQUFBOztBQUFBLDZCQUNuRixzRUFBS3JCLEtBQUwsRUFBVzJCLElBQVgsNkxBQW9Cd0IsU0FBcEI7QUFDQTtBQUNELEtBSkQsTUFJTyxJQUFJLDhFQUFnQkMsWUFBaEIsRUFBOEJELFNBQTlCLEtBQ0pHLG1CQUFtQmxELElBQW5CLEVBQXlCZ0QsWUFBekIsRUFBdUNBLGFBQWEvQixNQUFiLEdBQXNCOEIsVUFBVTlCLE1BQXZFLENBREEsRUFDZ0Y7QUFBQTs7QUFBQSw2QkFDckYsc0VBQUtyQixLQUFMLEVBQVcyQixJQUFYLDZMQUFvQnlCLFlBQXBCO0FBQ0E7QUFDRDtBQUNGLEdBWEQsTUFXTyxJQUFJLHlFQUFXRCxTQUFYLEVBQXNCQyxZQUF0QixDQUFKLEVBQXlDO0FBQUE7O0FBQUEsMkJBQzlDLHNFQUFLcEQsS0FBTCxFQUFXMkIsSUFBWCw2TEFBb0J3QixTQUFwQjtBQUNBO0FBQ0Q7O0FBRURiLFdBQVN4QyxJQUFULEVBQWVxRCxTQUFmLEVBQTBCQyxZQUExQjtBQUNEOztBQUVELFNBQVNILE9BQVQsQ0FBaUJuRCxJQUFqQixFQUF1Qk0sSUFBdkIsRUFBNkJ3QyxLQUE3QixFQUFvQ1csSUFBcEMsRUFBMEM7QUFDeEMsTUFBSUosWUFBWUgsY0FBYzVDLElBQWQsQ0FBaEI7QUFBQSxNQUNJZ0QsZUFBZUksZUFBZVosS0FBZixFQUFzQk8sU0FBdEIsQ0FEbkI7QUFFQSxNQUFJQyxhQUFhSyxNQUFqQixFQUF5QjtBQUFBOztBQUFBLDJCQUN2QixzRUFBS3pELEtBQUwsRUFBVzJCLElBQVgsNkxBQW9CeUIsYUFBYUssTUFBakM7QUFDRCxHQUZELE1BRU87QUFDTG5CLGFBQVN4QyxJQUFULEVBQWV5RCxPQUFPSCxZQUFQLEdBQXNCRCxTQUFyQyxFQUFnREksT0FBT0osU0FBUCxHQUFtQkMsWUFBbkU7QUFDRDtBQUNGOztBQUVELFNBQVNkLFFBQVQsQ0FBa0J4QyxJQUFsQixFQUF3Qk0sSUFBeEIsRUFBOEJ3QyxLQUE5QixFQUFxQztBQUNuQzlDLE9BQUt3QyxRQUFMLEdBQWdCLElBQWhCO0FBQ0F4QyxPQUFLRSxLQUFMLENBQVcyQixJQUFYLENBQWdCO0FBQ2RXLGNBQVUsSUFESTtBQUVkbEMsVUFBTUEsSUFGUTtBQUdkQyxZQUFRdUM7QUFITSxHQUFoQjtBQUtEOztBQUVELFNBQVNDLGFBQVQsQ0FBdUIvQyxJQUF2QixFQUE2QjRELE1BQTdCLEVBQXFDZCxLQUFyQyxFQUE0QztBQUMxQyxTQUFPYyxPQUFPbEIsTUFBUCxHQUFnQkksTUFBTUosTUFBdEIsSUFBZ0NrQixPQUFPakQsS0FBUCxHQUFlaUQsT0FBTzFELEtBQVAsQ0FBYXFCLE1BQW5FLEVBQTJFO0FBQ3pFLFFBQUlzQyxPQUFPRCxPQUFPMUQsS0FBUCxDQUFhMEQsT0FBT2pELEtBQVAsRUFBYixDQUFYO0FBQ0FYLFNBQUtFLEtBQUwsQ0FBVzJCLElBQVgsQ0FBZ0JnQyxJQUFoQjtBQUNBRCxXQUFPbEIsTUFBUDtBQUNEO0FBQ0Y7QUFDRCxTQUFTVSxjQUFULENBQXdCcEQsSUFBeEIsRUFBOEI0RCxNQUE5QixFQUFzQztBQUNwQyxTQUFPQSxPQUFPakQsS0FBUCxHQUFlaUQsT0FBTzFELEtBQVAsQ0FBYXFCLE1BQW5DLEVBQTJDO0FBQ3pDLFFBQUlzQyxPQUFPRCxPQUFPMUQsS0FBUCxDQUFhMEQsT0FBT2pELEtBQVAsRUFBYixDQUFYO0FBQ0FYLFNBQUtFLEtBQUwsQ0FBVzJCLElBQVgsQ0FBZ0JnQyxJQUFoQjtBQUNEO0FBQ0Y7O0FBRUQsU0FBU1gsYUFBVCxDQUF1QlksS0FBdkIsRUFBOEI7QUFDNUIsTUFBSXBELE1BQU0sRUFBVjtBQUFBLE1BQ0lxRCxZQUFZRCxNQUFNNUQsS0FBTixDQUFZNEQsTUFBTW5ELEtBQWxCLEVBQXlCLENBQXpCLENBRGhCO0FBRUEsU0FBT21ELE1BQU1uRCxLQUFOLEdBQWNtRCxNQUFNNUQsS0FBTixDQUFZcUIsTUFBakMsRUFBeUM7QUFDdkMsUUFBSXNDLE9BQU9DLE1BQU01RCxLQUFOLENBQVk0RCxNQUFNbkQsS0FBbEIsQ0FBWDs7QUFFQTtBQUNBLFFBQUlvRCxjQUFjLEdBQWQsSUFBcUJGLEtBQUssQ0FBTCxNQUFZLEdBQXJDLEVBQTBDO0FBQ3hDRSxrQkFBWSxHQUFaO0FBQ0Q7O0FBRUQsUUFBSUEsY0FBY0YsS0FBSyxDQUFMLENBQWxCLEVBQTJCO0FBQ3pCbkQsVUFBSW1CLElBQUosQ0FBU2dDLElBQVQ7QUFDQUMsWUFBTW5ELEtBQU47QUFDRCxLQUhELE1BR087QUFDTDtBQUNEO0FBQ0Y7O0FBRUQsU0FBT0QsR0FBUDtBQUNEO0FBQ0QsU0FBU2dELGNBQVQsQ0FBd0JJLEtBQXhCLEVBQStCRSxZQUEvQixFQUE2QztBQUMzQyxNQUFJQyxVQUFVLEVBQWQ7QUFBQSxNQUNJTixTQUFTLEVBRGI7QUFBQSxNQUVJTyxhQUFhLENBRmpCO0FBQUEsTUFHSUMsaUJBQWlCLEtBSHJCO0FBQUEsTUFJSUMsYUFBYSxLQUpqQjtBQUtBLFNBQU9GLGFBQWFGLGFBQWF6QyxNQUExQixJQUNFdUMsTUFBTW5ELEtBQU4sR0FBY21ELE1BQU01RCxLQUFOLENBQVlxQixNQURuQyxFQUMyQztBQUN6QyxRQUFJOEMsU0FBU1AsTUFBTTVELEtBQU4sQ0FBWTRELE1BQU1uRCxLQUFsQixDQUFiO0FBQUEsUUFDSTJELFFBQVFOLGFBQWFFLFVBQWIsQ0FEWjs7QUFHQTtBQUNBLFFBQUlJLE1BQU0sQ0FBTixNQUFhLEdBQWpCLEVBQXNCO0FBQ3BCO0FBQ0Q7O0FBRURILHFCQUFpQkEsa0JBQWtCRSxPQUFPLENBQVAsTUFBYyxHQUFqRDs7QUFFQVYsV0FBTzlCLElBQVAsQ0FBWXlDLEtBQVo7QUFDQUo7O0FBRUE7QUFDQTtBQUNBLFFBQUlHLE9BQU8sQ0FBUCxNQUFjLEdBQWxCLEVBQXVCO0FBQ3JCRCxtQkFBYSxJQUFiOztBQUVBLGFBQU9DLE9BQU8sQ0FBUCxNQUFjLEdBQXJCLEVBQTBCO0FBQ3hCSixnQkFBUXBDLElBQVIsQ0FBYXdDLE1BQWI7QUFDQUEsaUJBQVNQLE1BQU01RCxLQUFOLENBQVksRUFBRTRELE1BQU1uRCxLQUFwQixDQUFUO0FBQ0Q7QUFDRjs7QUFFRCxRQUFJMkQsTUFBTUMsTUFBTixDQUFhLENBQWIsTUFBb0JGLE9BQU9FLE1BQVAsQ0FBYyxDQUFkLENBQXhCLEVBQTBDO0FBQ3hDTixjQUFRcEMsSUFBUixDQUFhd0MsTUFBYjtBQUNBUCxZQUFNbkQsS0FBTjtBQUNELEtBSEQsTUFHTztBQUNMeUQsbUJBQWEsSUFBYjtBQUNEO0FBQ0Y7O0FBRUQsTUFBSSxDQUFDSixhQUFhRSxVQUFiLEtBQTRCLEVBQTdCLEVBQWlDLENBQWpDLE1BQXdDLEdBQXhDLElBQ0dDLGNBRFAsRUFDdUI7QUFDckJDLGlCQUFhLElBQWI7QUFDRDs7QUFFRCxNQUFJQSxVQUFKLEVBQWdCO0FBQ2QsV0FBT0gsT0FBUDtBQUNEOztBQUVELFNBQU9DLGFBQWFGLGFBQWF6QyxNQUFqQyxFQUF5QztBQUN2Q29DLFdBQU85QixJQUFQLENBQVltQyxhQUFhRSxZQUFiLENBQVo7QUFDRDs7QUFFRCxTQUFPO0FBQ0xQLGtCQURLO0FBRUxNO0FBRkssR0FBUDtBQUlEOztBQUVELFNBQVNWLFVBQVQsQ0FBb0JVLE9BQXBCLEVBQTZCO0FBQzNCLFNBQU9BLFFBQVFPLE1BQVIsQ0FBZSxVQUFTQyxJQUFULEVBQWVKLE1BQWYsRUFBdUI7QUFDM0MsV0FBT0ksUUFBUUosT0FBTyxDQUFQLE1BQWMsR0FBN0I7QUFDRCxHQUZNLEVBRUosSUFGSSxDQUFQO0FBR0Q7QUFDRCxTQUFTYixrQkFBVCxDQUE0Qk0sS0FBNUIsRUFBbUNZLGFBQW5DLEVBQWtEQyxLQUFsRCxFQUF5RDtBQUN2RCxPQUFLLElBQUlDLElBQUksQ0FBYixFQUFnQkEsSUFBSUQsS0FBcEIsRUFBMkJDLEdBQTNCLEVBQWdDO0FBQzlCLFFBQUlDLGdCQUFnQkgsY0FBY0EsY0FBY25ELE1BQWQsR0FBdUJvRCxLQUF2QixHQUErQkMsQ0FBN0MsRUFBZ0RMLE1BQWhELENBQXVELENBQXZELENBQXBCO0FBQ0EsUUFBSVQsTUFBTTVELEtBQU4sQ0FBWTRELE1BQU1uRCxLQUFOLEdBQWNpRSxDQUExQixNQUFpQyxNQUFNQyxhQUEzQyxFQUEwRDtBQUN4RCxhQUFPLEtBQVA7QUFDRDtBQUNGOztBQUVEZixRQUFNbkQsS0FBTixJQUFlZ0UsS0FBZjtBQUNBLFNBQU8sSUFBUDtBQUNEOztBQUVELFNBQVMxRSxtQkFBVCxDQUE2QkMsS0FBN0IsRUFBb0M7QUFDbEMsTUFBSUMsV0FBVyxDQUFmO0FBQ0EsTUFBSUMsV0FBVyxDQUFmOztBQUVBRixRQUFNNEUsT0FBTixDQUFjLFVBQVNqQixJQUFULEVBQWU7QUFDM0IsUUFBSSxPQUFPQSxJQUFQLEtBQWdCLFFBQXBCLEVBQThCO0FBQzVCLFVBQUlrQixVQUFVOUUsb0JBQW9CNEQsS0FBS3ZELElBQXpCLENBQWQ7QUFDQSxVQUFJMEUsYUFBYS9FLG9CQUFvQjRELEtBQUt0RCxNQUF6QixDQUFqQjs7QUFFQSxVQUFJSixhQUFhRSxTQUFqQixFQUE0QjtBQUMxQixZQUFJMEUsUUFBUTVFLFFBQVIsS0FBcUI2RSxXQUFXN0UsUUFBcEMsRUFBOEM7QUFDNUNBLHNCQUFZNEUsUUFBUTVFLFFBQXBCO0FBQ0QsU0FGRCxNQUVPO0FBQ0xBLHFCQUFXRSxTQUFYO0FBQ0Q7QUFDRjs7QUFFRCxVQUFJRCxhQUFhQyxTQUFqQixFQUE0QjtBQUMxQixZQUFJMEUsUUFBUTNFLFFBQVIsS0FBcUI0RSxXQUFXNUUsUUFBcEMsRUFBOEM7QUFDNUNBLHNCQUFZMkUsUUFBUTNFLFFBQXBCO0FBQ0QsU0FGRCxNQUVPO0FBQ0xBLHFCQUFXQyxTQUFYO0FBQ0Q7QUFDRjtBQUNGLEtBbkJELE1BbUJPO0FBQ0wsVUFBSUQsYUFBYUMsU0FBYixLQUEyQndELEtBQUssQ0FBTCxNQUFZLEdBQVosSUFBbUJBLEtBQUssQ0FBTCxNQUFZLEdBQTFELENBQUosRUFBb0U7QUFDbEV6RDtBQUNEO0FBQ0QsVUFBSUQsYUFBYUUsU0FBYixLQUEyQndELEtBQUssQ0FBTCxNQUFZLEdBQVosSUFBbUJBLEtBQUssQ0FBTCxNQUFZLEdBQTFELENBQUosRUFBb0U7QUFDbEUxRDtBQUNEO0FBQ0Y7QUFDRixHQTVCRDs7QUE4QkEsU0FBTyxFQUFDQSxrQkFBRCxFQUFXQyxrQkFBWCxFQUFQO0FBQ0QiLCJmaWxlIjoibWVyZ2UuanMiLCJzb3VyY2VzQ29udGVudCI6WyJpbXBvcnQge3N0cnVjdHVyZWRQYXRjaH0gZnJvbSAnLi9jcmVhdGUnO1xuaW1wb3J0IHtwYXJzZVBhdGNofSBmcm9tICcuL3BhcnNlJztcblxuaW1wb3J0IHthcnJheUVxdWFsLCBhcnJheVN0YXJ0c1dpdGh9IGZyb20gJy4uL3V0aWwvYXJyYXknO1xuXG5leHBvcnQgZnVuY3Rpb24gY2FsY0xpbmVDb3VudChodW5rKSB7XG4gIGNvbnN0IHtvbGRMaW5lcywgbmV3TGluZXN9ID0gY2FsY09sZE5ld0xpbmVDb3VudChodW5rLmxpbmVzKTtcblxuICBpZiAob2xkTGluZXMgIT09IHVuZGVmaW5lZCkge1xuICAgIGh1bmsub2xkTGluZXMgPSBvbGRMaW5lcztcbiAgfSBlbHNlIHtcbiAgICBkZWxldGUgaHVuay5vbGRMaW5lcztcbiAgfVxuXG4gIGlmIChuZXdMaW5lcyAhPT0gdW5kZWZpbmVkKSB7XG4gICAgaHVuay5uZXdMaW5lcyA9IG5ld0xpbmVzO1xuICB9IGVsc2Uge1xuICAgIGRlbGV0ZSBodW5rLm5ld0xpbmVzO1xuICB9XG59XG5cbmV4cG9ydCBmdW5jdGlvbiBtZXJnZShtaW5lLCB0aGVpcnMsIGJhc2UpIHtcbiAgbWluZSA9IGxvYWRQYXRjaChtaW5lLCBiYXNlKTtcbiAgdGhlaXJzID0gbG9hZFBhdGNoKHRoZWlycywgYmFzZSk7XG5cbiAgbGV0IHJldCA9IHt9O1xuXG4gIC8vIEZvciBpbmRleCB3ZSBqdXN0IGxldCBpdCBwYXNzIHRocm91Z2ggYXMgaXQgZG9lc24ndCBoYXZlIGFueSBuZWNlc3NhcnkgbWVhbmluZy5cbiAgLy8gTGVhdmluZyBzYW5pdHkgY2hlY2tzIG9uIHRoaXMgdG8gdGhlIEFQSSBjb25zdW1lciB0aGF0IG1heSBrbm93IG1vcmUgYWJvdXQgdGhlXG4gIC8vIG1lYW5pbmcgaW4gdGhlaXIgb3duIGNvbnRleHQuXG4gIGlmIChtaW5lLmluZGV4IHx8IHRoZWlycy5pbmRleCkge1xuICAgIHJldC5pbmRleCA9IG1pbmUuaW5kZXggfHwgdGhlaXJzLmluZGV4O1xuICB9XG5cbiAgaWYgKG1pbmUubmV3RmlsZU5hbWUgfHwgdGhlaXJzLm5ld0ZpbGVOYW1lKSB7XG4gICAgaWYgKCFmaWxlTmFtZUNoYW5nZWQobWluZSkpIHtcbiAgICAgIC8vIE5vIGhlYWRlciBvciBubyBjaGFuZ2UgaW4gb3VycywgdXNlIHRoZWlycyAoYW5kIG91cnMgaWYgdGhlaXJzIGRvZXMgbm90IGV4aXN0KVxuICAgICAgcmV0Lm9sZEZpbGVOYW1lID0gdGhlaXJzLm9sZEZpbGVOYW1lIHx8IG1pbmUub2xkRmlsZU5hbWU7XG4gICAgICByZXQubmV3RmlsZU5hbWUgPSB0aGVpcnMubmV3RmlsZU5hbWUgfHwgbWluZS5uZXdGaWxlTmFtZTtcbiAgICAgIHJldC5vbGRIZWFkZXIgPSB0aGVpcnMub2xkSGVhZGVyIHx8IG1pbmUub2xkSGVhZGVyO1xuICAgICAgcmV0Lm5ld0hlYWRlciA9IHRoZWlycy5uZXdIZWFkZXIgfHwgbWluZS5uZXdIZWFkZXI7XG4gICAgfSBlbHNlIGlmICghZmlsZU5hbWVDaGFuZ2VkKHRoZWlycykpIHtcbiAgICAgIC8vIE5vIGhlYWRlciBvciBubyBjaGFuZ2UgaW4gdGhlaXJzLCB1c2Ugb3Vyc1xuICAgICAgcmV0Lm9sZEZpbGVOYW1lID0gbWluZS5vbGRGaWxlTmFtZTtcbiAgICAgIHJldC5uZXdGaWxlTmFtZSA9IG1pbmUubmV3RmlsZU5hbWU7XG4gICAgICByZXQub2xkSGVhZGVyID0gbWluZS5vbGRIZWFkZXI7XG4gICAgICByZXQubmV3SGVhZGVyID0gbWluZS5uZXdIZWFkZXI7XG4gICAgfSBlbHNlIHtcbiAgICAgIC8vIEJvdGggY2hhbmdlZC4uLiBmaWd1cmUgaXQgb3V0XG4gICAgICByZXQub2xkRmlsZU5hbWUgPSBzZWxlY3RGaWVsZChyZXQsIG1pbmUub2xkRmlsZU5hbWUsIHRoZWlycy5vbGRGaWxlTmFtZSk7XG4gICAgICByZXQubmV3RmlsZU5hbWUgPSBzZWxlY3RGaWVsZChyZXQsIG1pbmUubmV3RmlsZU5hbWUsIHRoZWlycy5uZXdGaWxlTmFtZSk7XG4gICAgICByZXQub2xkSGVhZGVyID0gc2VsZWN0RmllbGQocmV0LCBtaW5lLm9sZEhlYWRlciwgdGhlaXJzLm9sZEhlYWRlcik7XG4gICAgICByZXQubmV3SGVhZGVyID0gc2VsZWN0RmllbGQocmV0LCBtaW5lLm5ld0hlYWRlciwgdGhlaXJzLm5ld0hlYWRlcik7XG4gICAgfVxuICB9XG5cbiAgcmV0Lmh1bmtzID0gW107XG5cbiAgbGV0IG1pbmVJbmRleCA9IDAsXG4gICAgICB0aGVpcnNJbmRleCA9IDAsXG4gICAgICBtaW5lT2Zmc2V0ID0gMCxcbiAgICAgIHRoZWlyc09mZnNldCA9IDA7XG5cbiAgd2hpbGUgKG1pbmVJbmRleCA8IG1pbmUuaHVua3MubGVuZ3RoIHx8IHRoZWlyc0luZGV4IDwgdGhlaXJzLmh1bmtzLmxlbmd0aCkge1xuICAgIGxldCBtaW5lQ3VycmVudCA9IG1pbmUuaHVua3NbbWluZUluZGV4XSB8fCB7b2xkU3RhcnQ6IEluZmluaXR5fSxcbiAgICAgICAgdGhlaXJzQ3VycmVudCA9IHRoZWlycy5odW5rc1t0aGVpcnNJbmRleF0gfHwge29sZFN0YXJ0OiBJbmZpbml0eX07XG5cbiAgICBpZiAoaHVua0JlZm9yZShtaW5lQ3VycmVudCwgdGhlaXJzQ3VycmVudCkpIHtcbiAgICAgIC8vIFRoaXMgcGF0Y2ggZG9lcyBub3Qgb3ZlcmxhcCB3aXRoIGFueSBvZiB0aGUgb3RoZXJzLCB5YXkuXG4gICAgICByZXQuaHVua3MucHVzaChjbG9uZUh1bmsobWluZUN1cnJlbnQsIG1pbmVPZmZzZXQpKTtcbiAgICAgIG1pbmVJbmRleCsrO1xuICAgICAgdGhlaXJzT2Zmc2V0ICs9IG1pbmVDdXJyZW50Lm5ld0xpbmVzIC0gbWluZUN1cnJlbnQub2xkTGluZXM7XG4gICAgfSBlbHNlIGlmIChodW5rQmVmb3JlKHRoZWlyc0N1cnJlbnQsIG1pbmVDdXJyZW50KSkge1xuICAgICAgLy8gVGhpcyBwYXRjaCBkb2VzIG5vdCBvdmVybGFwIHdpdGggYW55IG9mIHRoZSBvdGhlcnMsIHlheS5cbiAgICAgIHJldC5odW5rcy5wdXNoKGNsb25lSHVuayh0aGVpcnNDdXJyZW50LCB0aGVpcnNPZmZzZXQpKTtcbiAgICAgIHRoZWlyc0luZGV4Kys7XG4gICAgICBtaW5lT2Zmc2V0ICs9IHRoZWlyc0N1cnJlbnQubmV3TGluZXMgLSB0aGVpcnNDdXJyZW50Lm9sZExpbmVzO1xuICAgIH0gZWxzZSB7XG4gICAgICAvLyBPdmVybGFwLCBtZXJnZSBhcyBiZXN0IHdlIGNhblxuICAgICAgbGV0IG1lcmdlZEh1bmsgPSB7XG4gICAgICAgIG9sZFN0YXJ0OiBNYXRoLm1pbihtaW5lQ3VycmVudC5vbGRTdGFydCwgdGhlaXJzQ3VycmVudC5vbGRTdGFydCksXG4gICAgICAgIG9sZExpbmVzOiAwLFxuICAgICAgICBuZXdTdGFydDogTWF0aC5taW4obWluZUN1cnJlbnQubmV3U3RhcnQgKyBtaW5lT2Zmc2V0LCB0aGVpcnNDdXJyZW50Lm9sZFN0YXJ0ICsgdGhlaXJzT2Zmc2V0KSxcbiAgICAgICAgbmV3TGluZXM6IDAsXG4gICAgICAgIGxpbmVzOiBbXVxuICAgICAgfTtcbiAgICAgIG1lcmdlTGluZXMobWVyZ2VkSHVuaywgbWluZUN1cnJlbnQub2xkU3RhcnQsIG1pbmVDdXJyZW50LmxpbmVzLCB0aGVpcnNDdXJyZW50Lm9sZFN0YXJ0LCB0aGVpcnNDdXJyZW50LmxpbmVzKTtcbiAgICAgIHRoZWlyc0luZGV4Kys7XG4gICAgICBtaW5lSW5kZXgrKztcblxuICAgICAgcmV0Lmh1bmtzLnB1c2gobWVyZ2VkSHVuayk7XG4gICAgfVxuICB9XG5cbiAgcmV0dXJuIHJldDtcbn1cblxuZnVuY3Rpb24gbG9hZFBhdGNoKHBhcmFtLCBiYXNlKSB7XG4gIGlmICh0eXBlb2YgcGFyYW0gPT09ICdzdHJpbmcnKSB7XG4gICAgaWYgKC9eQEAvbS50ZXN0KHBhcmFtKSB8fCAoL15JbmRleDovbS50ZXN0KHBhcmFtKSkpIHtcbiAgICAgIHJldHVybiBwYXJzZVBhdGNoKHBhcmFtKVswXTtcbiAgICB9XG5cbiAgICBpZiAoIWJhc2UpIHtcbiAgICAgIHRocm93IG5ldyBFcnJvcignTXVzdCBwcm92aWRlIGEgYmFzZSByZWZlcmVuY2Ugb3IgcGFzcyBpbiBhIHBhdGNoJyk7XG4gICAgfVxuICAgIHJldHVybiBzdHJ1Y3R1cmVkUGF0Y2godW5kZWZpbmVkLCB1bmRlZmluZWQsIGJhc2UsIHBhcmFtKTtcbiAgfVxuXG4gIHJldHVybiBwYXJhbTtcbn1cblxuZnVuY3Rpb24gZmlsZU5hbWVDaGFuZ2VkKHBhdGNoKSB7XG4gIHJldHVybiBwYXRjaC5uZXdGaWxlTmFtZSAmJiBwYXRjaC5uZXdGaWxlTmFtZSAhPT0gcGF0Y2gub2xkRmlsZU5hbWU7XG59XG5cbmZ1bmN0aW9uIHNlbGVjdEZpZWxkKGluZGV4LCBtaW5lLCB0aGVpcnMpIHtcbiAgaWYgKG1pbmUgPT09IHRoZWlycykge1xuICAgIHJldHVybiBtaW5lO1xuICB9IGVsc2Uge1xuICAgIGluZGV4LmNvbmZsaWN0ID0gdHJ1ZTtcbiAgICByZXR1cm4ge21pbmUsIHRoZWlyc307XG4gIH1cbn1cblxuZnVuY3Rpb24gaHVua0JlZm9yZSh0ZXN0LCBjaGVjaykge1xuICByZXR1cm4gdGVzdC5vbGRTdGFydCA8IGNoZWNrLm9sZFN0YXJ0XG4gICAgJiYgKHRlc3Qub2xkU3RhcnQgKyB0ZXN0Lm9sZExpbmVzKSA8IGNoZWNrLm9sZFN0YXJ0O1xufVxuXG5mdW5jdGlvbiBjbG9uZUh1bmsoaHVuaywgb2Zmc2V0KSB7XG4gIHJldHVybiB7XG4gICAgb2xkU3RhcnQ6IGh1bmsub2xkU3RhcnQsIG9sZExpbmVzOiBodW5rLm9sZExpbmVzLFxuICAgIG5ld1N0YXJ0OiBodW5rLm5ld1N0YXJ0ICsgb2Zmc2V0LCBuZXdMaW5lczogaHVuay5uZXdMaW5lcyxcbiAgICBsaW5lczogaHVuay5saW5lc1xuICB9O1xufVxuXG5mdW5jdGlvbiBtZXJnZUxpbmVzKGh1bmssIG1pbmVPZmZzZXQsIG1pbmVMaW5lcywgdGhlaXJPZmZzZXQsIHRoZWlyTGluZXMpIHtcbiAgLy8gVGhpcyB3aWxsIGdlbmVyYWxseSByZXN1bHQgaW4gYSBjb25mbGljdGVkIGh1bmssIGJ1dCB0aGVyZSBhcmUgY2FzZXMgd2hlcmUgdGhlIGNvbnRleHRcbiAgLy8gaXMgdGhlIG9ubHkgb3ZlcmxhcCB3aGVyZSB3ZSBjYW4gc3VjY2Vzc2Z1bGx5IG1lcmdlIHRoZSBjb250ZW50IGhlcmUuXG4gIGxldCBtaW5lID0ge29mZnNldDogbWluZU9mZnNldCwgbGluZXM6IG1pbmVMaW5lcywgaW5kZXg6IDB9LFxuICAgICAgdGhlaXIgPSB7b2Zmc2V0OiB0aGVpck9mZnNldCwgbGluZXM6IHRoZWlyTGluZXMsIGluZGV4OiAwfTtcblxuICAvLyBIYW5kbGUgYW55IGxlYWRpbmcgY29udGVudFxuICBpbnNlcnRMZWFkaW5nKGh1bmssIG1pbmUsIHRoZWlyKTtcbiAgaW5zZXJ0TGVhZGluZyhodW5rLCB0aGVpciwgbWluZSk7XG5cbiAgLy8gTm93IGluIHRoZSBvdmVybGFwIGNvbnRlbnQuIFNjYW4gdGhyb3VnaCBhbmQgc2VsZWN0IHRoZSBiZXN0IGNoYW5nZXMgZnJvbSBlYWNoLlxuICB3aGlsZSAobWluZS5pbmRleCA8IG1pbmUubGluZXMubGVuZ3RoICYmIHRoZWlyLmluZGV4IDwgdGhlaXIubGluZXMubGVuZ3RoKSB7XG4gICAgbGV0IG1pbmVDdXJyZW50ID0gbWluZS5saW5lc1ttaW5lLmluZGV4XSxcbiAgICAgICAgdGhlaXJDdXJyZW50ID0gdGhlaXIubGluZXNbdGhlaXIuaW5kZXhdO1xuXG4gICAgaWYgKChtaW5lQ3VycmVudFswXSA9PT0gJy0nIHx8IG1pbmVDdXJyZW50WzBdID09PSAnKycpXG4gICAgICAgICYmICh0aGVpckN1cnJlbnRbMF0gPT09ICctJyB8fCB0aGVpckN1cnJlbnRbMF0gPT09ICcrJykpIHtcbiAgICAgIC8vIEJvdGggbW9kaWZpZWQgLi4uXG4gICAgICBtdXR1YWxDaGFuZ2UoaHVuaywgbWluZSwgdGhlaXIpO1xuICAgIH0gZWxzZSBpZiAobWluZUN1cnJlbnRbMF0gPT09ICcrJyAmJiB0aGVpckN1cnJlbnRbMF0gPT09ICcgJykge1xuICAgICAgLy8gTWluZSBpbnNlcnRlZFxuICAgICAgaHVuay5saW5lcy5wdXNoKC4uLiBjb2xsZWN0Q2hhbmdlKG1pbmUpKTtcbiAgICB9IGVsc2UgaWYgKHRoZWlyQ3VycmVudFswXSA9PT0gJysnICYmIG1pbmVDdXJyZW50WzBdID09PSAnICcpIHtcbiAgICAgIC8vIFRoZWlycyBpbnNlcnRlZFxuICAgICAgaHVuay5saW5lcy5wdXNoKC4uLiBjb2xsZWN0Q2hhbmdlKHRoZWlyKSk7XG4gICAgfSBlbHNlIGlmIChtaW5lQ3VycmVudFswXSA9PT0gJy0nICYmIHRoZWlyQ3VycmVudFswXSA9PT0gJyAnKSB7XG4gICAgICAvLyBNaW5lIHJlbW92ZWQgb3IgZWRpdGVkXG4gICAgICByZW1vdmFsKGh1bmssIG1pbmUsIHRoZWlyKTtcbiAgICB9IGVsc2UgaWYgKHRoZWlyQ3VycmVudFswXSA9PT0gJy0nICYmIG1pbmVDdXJyZW50WzBdID09PSAnICcpIHtcbiAgICAgIC8vIFRoZWlyIHJlbW92ZWQgb3IgZWRpdGVkXG4gICAgICByZW1vdmFsKGh1bmssIHRoZWlyLCBtaW5lLCB0cnVlKTtcbiAgICB9IGVsc2UgaWYgKG1pbmVDdXJyZW50ID09PSB0aGVpckN1cnJlbnQpIHtcbiAgICAgIC8vIENvbnRleHQgaWRlbnRpdHlcbiAgICAgIGh1bmsubGluZXMucHVzaChtaW5lQ3VycmVudCk7XG4gICAgICBtaW5lLmluZGV4Kys7XG4gICAgICB0aGVpci5pbmRleCsrO1xuICAgIH0gZWxzZSB7XG4gICAgICAvLyBDb250ZXh0IG1pc21hdGNoXG4gICAgICBjb25mbGljdChodW5rLCBjb2xsZWN0Q2hhbmdlKG1pbmUpLCBjb2xsZWN0Q2hhbmdlKHRoZWlyKSk7XG4gICAgfVxuICB9XG5cbiAgLy8gTm93IHB1c2ggYW55dGhpbmcgdGhhdCBtYXkgYmUgcmVtYWluaW5nXG4gIGluc2VydFRyYWlsaW5nKGh1bmssIG1pbmUpO1xuICBpbnNlcnRUcmFpbGluZyhodW5rLCB0aGVpcik7XG5cbiAgY2FsY0xpbmVDb3VudChodW5rKTtcbn1cblxuZnVuY3Rpb24gbXV0dWFsQ2hhbmdlKGh1bmssIG1pbmUsIHRoZWlyKSB7XG4gIGxldCBteUNoYW5nZXMgPSBjb2xsZWN0Q2hhbmdlKG1pbmUpLFxuICAgICAgdGhlaXJDaGFuZ2VzID0gY29sbGVjdENoYW5nZSh0aGVpcik7XG5cbiAgaWYgKGFsbFJlbW92ZXMobXlDaGFuZ2VzKSAmJiBhbGxSZW1vdmVzKHRoZWlyQ2hhbmdlcykpIHtcbiAgICAvLyBTcGVjaWFsIGNhc2UgZm9yIHJlbW92ZSBjaGFuZ2VzIHRoYXQgYXJlIHN1cGVyc2V0cyBvZiBvbmUgYW5vdGhlclxuICAgIGlmIChhcnJheVN0YXJ0c1dpdGgobXlDaGFuZ2VzLCB0aGVpckNoYW5nZXMpXG4gICAgICAgICYmIHNraXBSZW1vdmVTdXBlcnNldCh0aGVpciwgbXlDaGFuZ2VzLCBteUNoYW5nZXMubGVuZ3RoIC0gdGhlaXJDaGFuZ2VzLmxlbmd0aCkpIHtcbiAgICAgIGh1bmsubGluZXMucHVzaCguLi4gbXlDaGFuZ2VzKTtcbiAgICAgIHJldHVybjtcbiAgICB9IGVsc2UgaWYgKGFycmF5U3RhcnRzV2l0aCh0aGVpckNoYW5nZXMsIG15Q2hhbmdlcylcbiAgICAgICAgJiYgc2tpcFJlbW92ZVN1cGVyc2V0KG1pbmUsIHRoZWlyQ2hhbmdlcywgdGhlaXJDaGFuZ2VzLmxlbmd0aCAtIG15Q2hhbmdlcy5sZW5ndGgpKSB7XG4gICAgICBodW5rLmxpbmVzLnB1c2goLi4uIHRoZWlyQ2hhbmdlcyk7XG4gICAgICByZXR1cm47XG4gICAgfVxuICB9IGVsc2UgaWYgKGFycmF5RXF1YWwobXlDaGFuZ2VzLCB0aGVpckNoYW5nZXMpKSB7XG4gICAgaHVuay5saW5lcy5wdXNoKC4uLiBteUNoYW5nZXMpO1xuICAgIHJldHVybjtcbiAgfVxuXG4gIGNvbmZsaWN0KGh1bmssIG15Q2hhbmdlcywgdGhlaXJDaGFuZ2VzKTtcbn1cblxuZnVuY3Rpb24gcmVtb3ZhbChodW5rLCBtaW5lLCB0aGVpciwgc3dhcCkge1xuICBsZXQgbXlDaGFuZ2VzID0gY29sbGVjdENoYW5nZShtaW5lKSxcbiAgICAgIHRoZWlyQ2hhbmdlcyA9IGNvbGxlY3RDb250ZXh0KHRoZWlyLCBteUNoYW5nZXMpO1xuICBpZiAodGhlaXJDaGFuZ2VzLm1lcmdlZCkge1xuICAgIGh1bmsubGluZXMucHVzaCguLi4gdGhlaXJDaGFuZ2VzLm1lcmdlZCk7XG4gIH0gZWxzZSB7XG4gICAgY29uZmxpY3QoaHVuaywgc3dhcCA/IHRoZWlyQ2hhbmdlcyA6IG15Q2hhbmdlcywgc3dhcCA/IG15Q2hhbmdlcyA6IHRoZWlyQ2hhbmdlcyk7XG4gIH1cbn1cblxuZnVuY3Rpb24gY29uZmxpY3QoaHVuaywgbWluZSwgdGhlaXIpIHtcbiAgaHVuay5jb25mbGljdCA9IHRydWU7XG4gIGh1bmsubGluZXMucHVzaCh7XG4gICAgY29uZmxpY3Q6IHRydWUsXG4gICAgbWluZTogbWluZSxcbiAgICB0aGVpcnM6IHRoZWlyXG4gIH0pO1xufVxuXG5mdW5jdGlvbiBpbnNlcnRMZWFkaW5nKGh1bmssIGluc2VydCwgdGhlaXIpIHtcbiAgd2hpbGUgKGluc2VydC5vZmZzZXQgPCB0aGVpci5vZmZzZXQgJiYgaW5zZXJ0LmluZGV4IDwgaW5zZXJ0LmxpbmVzLmxlbmd0aCkge1xuICAgIGxldCBsaW5lID0gaW5zZXJ0LmxpbmVzW2luc2VydC5pbmRleCsrXTtcbiAgICBodW5rLmxpbmVzLnB1c2gobGluZSk7XG4gICAgaW5zZXJ0Lm9mZnNldCsrO1xuICB9XG59XG5mdW5jdGlvbiBpbnNlcnRUcmFpbGluZyhodW5rLCBpbnNlcnQpIHtcbiAgd2hpbGUgKGluc2VydC5pbmRleCA8IGluc2VydC5saW5lcy5sZW5ndGgpIHtcbiAgICBsZXQgbGluZSA9IGluc2VydC5saW5lc1tpbnNlcnQuaW5kZXgrK107XG4gICAgaHVuay5saW5lcy5wdXNoKGxpbmUpO1xuICB9XG59XG5cbmZ1bmN0aW9uIGNvbGxlY3RDaGFuZ2Uoc3RhdGUpIHtcbiAgbGV0IHJldCA9IFtdLFxuICAgICAgb3BlcmF0aW9uID0gc3RhdGUubGluZXNbc3RhdGUuaW5kZXhdWzBdO1xuICB3aGlsZSAoc3RhdGUuaW5kZXggPCBzdGF0ZS5saW5lcy5sZW5ndGgpIHtcbiAgICBsZXQgbGluZSA9IHN0YXRlLmxpbmVzW3N0YXRlLmluZGV4XTtcblxuICAgIC8vIEdyb3VwIGFkZGl0aW9ucyB0aGF0IGFyZSBpbW1lZGlhdGVseSBhZnRlciBzdWJ0cmFjdGlvbnMgYW5kIHRyZWF0IHRoZW0gYXMgb25lIFwiYXRvbWljXCIgbW9kaWZ5IGNoYW5nZS5cbiAgICBpZiAob3BlcmF0aW9uID09PSAnLScgJiYgbGluZVswXSA9PT0gJysnKSB7XG4gICAgICBvcGVyYXRpb24gPSAnKyc7XG4gICAgfVxuXG4gICAgaWYgKG9wZXJhdGlvbiA9PT0gbGluZVswXSkge1xuICAgICAgcmV0LnB1c2gobGluZSk7XG4gICAgICBzdGF0ZS5pbmRleCsrO1xuICAgIH0gZWxzZSB7XG4gICAgICBicmVhaztcbiAgICB9XG4gIH1cblxuICByZXR1cm4gcmV0O1xufVxuZnVuY3Rpb24gY29sbGVjdENvbnRleHQoc3RhdGUsIG1hdGNoQ2hhbmdlcykge1xuICBsZXQgY2hhbmdlcyA9IFtdLFxuICAgICAgbWVyZ2VkID0gW10sXG4gICAgICBtYXRjaEluZGV4ID0gMCxcbiAgICAgIGNvbnRleHRDaGFuZ2VzID0gZmFsc2UsXG4gICAgICBjb25mbGljdGVkID0gZmFsc2U7XG4gIHdoaWxlIChtYXRjaEluZGV4IDwgbWF0Y2hDaGFuZ2VzLmxlbmd0aFxuICAgICAgICAmJiBzdGF0ZS5pbmRleCA8IHN0YXRlLmxpbmVzLmxlbmd0aCkge1xuICAgIGxldCBjaGFuZ2UgPSBzdGF0ZS5saW5lc1tzdGF0ZS5pbmRleF0sXG4gICAgICAgIG1hdGNoID0gbWF0Y2hDaGFuZ2VzW21hdGNoSW5kZXhdO1xuXG4gICAgLy8gT25jZSB3ZSd2ZSBoaXQgb3VyIGFkZCwgdGhlbiB3ZSBhcmUgZG9uZVxuICAgIGlmIChtYXRjaFswXSA9PT0gJysnKSB7XG4gICAgICBicmVhaztcbiAgICB9XG5cbiAgICBjb250ZXh0Q2hhbmdlcyA9IGNvbnRleHRDaGFuZ2VzIHx8IGNoYW5nZVswXSAhPT0gJyAnO1xuXG4gICAgbWVyZ2VkLnB1c2gobWF0Y2gpO1xuICAgIG1hdGNoSW5kZXgrKztcblxuICAgIC8vIENvbnN1bWUgYW55IGFkZGl0aW9ucyBpbiB0aGUgb3RoZXIgYmxvY2sgYXMgYSBjb25mbGljdCB0byBhdHRlbXB0XG4gICAgLy8gdG8gcHVsbCBpbiB0aGUgcmVtYWluaW5nIGNvbnRleHQgYWZ0ZXIgdGhpc1xuICAgIGlmIChjaGFuZ2VbMF0gPT09ICcrJykge1xuICAgICAgY29uZmxpY3RlZCA9IHRydWU7XG5cbiAgICAgIHdoaWxlIChjaGFuZ2VbMF0gPT09ICcrJykge1xuICAgICAgICBjaGFuZ2VzLnB1c2goY2hhbmdlKTtcbiAgICAgICAgY2hhbmdlID0gc3RhdGUubGluZXNbKytzdGF0ZS5pbmRleF07XG4gICAgICB9XG4gICAgfVxuXG4gICAgaWYgKG1hdGNoLnN1YnN0cigxKSA9PT0gY2hhbmdlLnN1YnN0cigxKSkge1xuICAgICAgY2hhbmdlcy5wdXNoKGNoYW5nZSk7XG4gICAgICBzdGF0ZS5pbmRleCsrO1xuICAgIH0gZWxzZSB7XG4gICAgICBjb25mbGljdGVkID0gdHJ1ZTtcbiAgICB9XG4gIH1cblxuICBpZiAoKG1hdGNoQ2hhbmdlc1ttYXRjaEluZGV4XSB8fCAnJylbMF0gPT09ICcrJ1xuICAgICAgJiYgY29udGV4dENoYW5nZXMpIHtcbiAgICBjb25mbGljdGVkID0gdHJ1ZTtcbiAgfVxuXG4gIGlmIChjb25mbGljdGVkKSB7XG4gICAgcmV0dXJuIGNoYW5nZXM7XG4gIH1cblxuICB3aGlsZSAobWF0Y2hJbmRleCA8IG1hdGNoQ2hhbmdlcy5sZW5ndGgpIHtcbiAgICBtZXJnZWQucHVzaChtYXRjaENoYW5nZXNbbWF0Y2hJbmRleCsrXSk7XG4gIH1cblxuICByZXR1cm4ge1xuICAgIG1lcmdlZCxcbiAgICBjaGFuZ2VzXG4gIH07XG59XG5cbmZ1bmN0aW9uIGFsbFJlbW92ZXMoY2hhbmdlcykge1xuICByZXR1cm4gY2hhbmdlcy5yZWR1Y2UoZnVuY3Rpb24ocHJldiwgY2hhbmdlKSB7XG4gICAgcmV0dXJuIHByZXYgJiYgY2hhbmdlWzBdID09PSAnLSc7XG4gIH0sIHRydWUpO1xufVxuZnVuY3Rpb24gc2tpcFJlbW92ZVN1cGVyc2V0KHN0YXRlLCByZW1vdmVDaGFuZ2VzLCBkZWx0YSkge1xuICBmb3IgKGxldCBpID0gMDsgaSA8IGRlbHRhOyBpKyspIHtcbiAgICBsZXQgY2hhbmdlQ29udGVudCA9IHJlbW92ZUNoYW5nZXNbcmVtb3ZlQ2hhbmdlcy5sZW5ndGggLSBkZWx0YSArIGldLnN1YnN0cigxKTtcbiAgICBpZiAoc3RhdGUubGluZXNbc3RhdGUuaW5kZXggKyBpXSAhPT0gJyAnICsgY2hhbmdlQ29udGVudCkge1xuICAgICAgcmV0dXJuIGZhbHNlO1xuICAgIH1cbiAgfVxuXG4gIHN0YXRlLmluZGV4ICs9IGRlbHRhO1xuICByZXR1cm4gdHJ1ZTtcbn1cblxuZnVuY3Rpb24gY2FsY09sZE5ld0xpbmVDb3VudChsaW5lcykge1xuICBsZXQgb2xkTGluZXMgPSAwO1xuICBsZXQgbmV3TGluZXMgPSAwO1xuXG4gIGxpbmVzLmZvckVhY2goZnVuY3Rpb24obGluZSkge1xuICAgIGlmICh0eXBlb2YgbGluZSAhPT0gJ3N0cmluZycpIHtcbiAgICAgIGxldCBteUNvdW50ID0gY2FsY09sZE5ld0xpbmVDb3VudChsaW5lLm1pbmUpO1xuICAgICAgbGV0IHRoZWlyQ291bnQgPSBjYWxjT2xkTmV3TGluZUNvdW50KGxpbmUudGhlaXJzKTtcblxuICAgICAgaWYgKG9sZExpbmVzICE9PSB1bmRlZmluZWQpIHtcbiAgICAgICAgaWYgKG15Q291bnQub2xkTGluZXMgPT09IHRoZWlyQ291bnQub2xkTGluZXMpIHtcbiAgICAgICAgICBvbGRMaW5lcyArPSBteUNvdW50Lm9sZExpbmVzO1xuICAgICAgICB9IGVsc2Uge1xuICAgICAgICAgIG9sZExpbmVzID0gdW5kZWZpbmVkO1xuICAgICAgICB9XG4gICAgICB9XG5cbiAgICAgIGlmIChuZXdMaW5lcyAhPT0gdW5kZWZpbmVkKSB7XG4gICAgICAgIGlmIChteUNvdW50Lm5ld0xpbmVzID09PSB0aGVpckNvdW50Lm5ld0xpbmVzKSB7XG4gICAgICAgICAgbmV3TGluZXMgKz0gbXlDb3VudC5uZXdMaW5lcztcbiAgICAgICAgfSBlbHNlIHtcbiAgICAgICAgICBuZXdMaW5lcyA9IHVuZGVmaW5lZDtcbiAgICAgICAgfVxuICAgICAgfVxuICAgIH0gZWxzZSB7XG4gICAgICBpZiAobmV3TGluZXMgIT09IHVuZGVmaW5lZCAmJiAobGluZVswXSA9PT0gJysnIHx8IGxpbmVbMF0gPT09ICcgJykpIHtcbiAgICAgICAgbmV3TGluZXMrKztcbiAgICAgIH1cbiAgICAgIGlmIChvbGRMaW5lcyAhPT0gdW5kZWZpbmVkICYmIChsaW5lWzBdID09PSAnLScgfHwgbGluZVswXSA9PT0gJyAnKSkge1xuICAgICAgICBvbGRMaW5lcysrO1xuICAgICAgfVxuICAgIH1cbiAgfSk7XG5cbiAgcmV0dXJuIHtvbGRMaW5lcywgbmV3TGluZXN9O1xufVxuIl19
+
+
+/***/ }),
+/* 14 */
+/***/ (function(module, exports, __webpack_require__) {
+
+	/*istanbul ignore start*/'use strict';
+
+	exports.__esModule = true;
+	exports. /*istanbul ignore end*/structuredPatch = structuredPatch;
+	/*istanbul ignore start*/exports. /*istanbul ignore end*/createTwoFilesPatch = createTwoFilesPatch;
+	/*istanbul ignore start*/exports. /*istanbul ignore end*/createPatch = createPatch;
+
+	var /*istanbul ignore start*/_line = __webpack_require__(5) /*istanbul ignore end*/;
+
+	/*istanbul ignore start*/function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
+
+	/*istanbul ignore end*/function structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) {
+	  if (!options) {
+	    options = {};
+	  }
+	  if (typeof options.context === 'undefined') {
+	    options.context = 4;
+	  }
+
+	  var diff = /*istanbul ignore start*/(0, _line.diffLines) /*istanbul ignore end*/(oldStr, newStr, options);
+	  diff.push({ value: '', lines: [] }); // Append an empty value to make cleanup easier
+
+	  function contextLines(lines) {
+	    return lines.map(function (entry) {
+	      return ' ' + entry;
+	    });
+	  }
+
+	  var hunks = [];
+	  var oldRangeStart = 0,
+	      newRangeStart = 0,
+	      curRange = [],
+	      oldLine = 1,
+	      newLine = 1;
+
+	  /*istanbul ignore start*/var _loop = function _loop( /*istanbul ignore end*/i) {
+	    var current = diff[i],
+	        lines = current.lines || current.value.replace(/\n$/, '').split('\n');
+	    current.lines = lines;
+
+	    if (current.added || current.removed) {
+	      /*istanbul ignore start*/var _curRange;
+
+	      /*istanbul ignore end*/ // If we have previous context, start with that
+	      if (!oldRangeStart) {
+	        var prev = diff[i - 1];
+	        oldRangeStart = oldLine;
+	        newRangeStart = newLine;
+
+	        if (prev) {
+	          curRange = options.context > 0 ? contextLines(prev.lines.slice(-options.context)) : [];
+	          oldRangeStart -= curRange.length;
+	          newRangeStart -= curRange.length;
+	        }
+	      }
+
+	      // Output our changes
+	      /*istanbul ignore start*/(_curRange = /*istanbul ignore end*/curRange).push. /*istanbul ignore start*/apply /*istanbul ignore end*/( /*istanbul ignore start*/_curRange /*istanbul ignore end*/, /*istanbul ignore start*/_toConsumableArray( /*istanbul ignore end*/lines.map(function (entry) {
+	        return (current.added ? '+' : '-') + entry;
+	      })));
+
+	      // Track the updated file position
+	      if (current.added) {
+	        newLine += lines.length;
+	      } else {
+	        oldLine += lines.length;
+	      }
+	    } else {
+	      // Identical context lines. Track line changes
+	      if (oldRangeStart) {
+	        // Close out any changes that have been output (or join overlapping)
+	        if (lines.length <= options.context * 2 && i < diff.length - 2) {
+	          /*istanbul ignore start*/var _curRange2;
+
+	          /*istanbul ignore end*/ // Overlapping
+	          /*istanbul ignore start*/(_curRange2 = /*istanbul ignore end*/curRange).push. /*istanbul ignore start*/apply /*istanbul ignore end*/( /*istanbul ignore start*/_curRange2 /*istanbul ignore end*/, /*istanbul ignore start*/_toConsumableArray( /*istanbul ignore end*/contextLines(lines)));
+	        } else {
+	          /*istanbul ignore start*/var _curRange3;
+
+	          /*istanbul ignore end*/ // end the range and output
+	          var contextSize = Math.min(lines.length, options.context);
+	          /*istanbul ignore start*/(_curRange3 = /*istanbul ignore end*/curRange).push. /*istanbul ignore start*/apply /*istanbul ignore end*/( /*istanbul ignore start*/_curRange3 /*istanbul ignore end*/, /*istanbul ignore start*/_toConsumableArray( /*istanbul ignore end*/contextLines(lines.slice(0, contextSize))));
+
+	          var hunk = {
+	            oldStart: oldRangeStart,
+	            oldLines: oldLine - oldRangeStart + contextSize,
+	            newStart: newRangeStart,
+	            newLines: newLine - newRangeStart + contextSize,
+	            lines: curRange
+	          };
+	          if (i >= diff.length - 2 && lines.length <= options.context) {
+	            // EOF is inside this hunk
+	            var oldEOFNewline = /\n$/.test(oldStr);
+	            var newEOFNewline = /\n$/.test(newStr);
+	            if (lines.length == 0 && !oldEOFNewline) {
+	              // special case: old has no eol and no trailing context; no-nl can end up before adds
+	              curRange.splice(hunk.oldLines, 0, '\\ No newline at end of file');
+	            } else if (!oldEOFNewline || !newEOFNewline) {
+	              curRange.push('\\ No newline at end of file');
+	            }
+	          }
+	          hunks.push(hunk);
+
+	          oldRangeStart = 0;
+	          newRangeStart = 0;
+	          curRange = [];
+	        }
+	      }
+	      oldLine += lines.length;
+	      newLine += lines.length;
+	    }
+	  };
+
+	  for (var i = 0; i < diff.length; i++) {
+	    /*istanbul ignore start*/_loop( /*istanbul ignore end*/i);
+	  }
+
+	  return {
+	    oldFileName: oldFileName, newFileName: newFileName,
+	    oldHeader: oldHeader, newHeader: newHeader,
+	    hunks: hunks
+	  };
+	}
+
+	function createTwoFilesPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) {
+	  var diff = structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options);
+
+	  var ret = [];
+	  if (oldFileName == newFileName) {
+	    ret.push('Index: ' + oldFileName);
+	  }
+	  ret.push('===================================================================');
+	  ret.push('--- ' + diff.oldFileName + (typeof diff.oldHeader === 'undefined' ? '' : '\t' + diff.oldHeader));
+	  ret.push('+++ ' + diff.newFileName + (typeof diff.newHeader === 'undefined' ? '' : '\t' + diff.newHeader));
+
+	  for (var i = 0; i < diff.hunks.length; i++) {
+	    var hunk = diff.hunks[i];
+	    ret.push('@@ -' + hunk.oldStart + ',' + hunk.oldLines + ' +' + hunk.newStart + ',' + hunk.newLines + ' @@');
+	    ret.push.apply(ret, hunk.lines);
+	  }
+
+	  return ret.join('\n') + '\n';
+	}
+
+	function createPatch(fileName, oldStr, newStr, oldHeader, newHeader, options) {
+	  return createTwoFilesPatch(fileName, fileName, oldStr, newStr, oldHeader, newHeader, options);
+	}
+	//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9wYXRjaC9jcmVhdGUuanMiXSwibmFtZXMiOlsic3RydWN0dXJlZFBhdGNoIiwiY3JlYXRlVHdvRmlsZXNQYXRjaCIsImNyZWF0ZVBhdGNoIiwib2xkRmlsZU5hbWUiLCJuZXdGaWxlTmFtZSIsIm9sZFN0ciIsIm5ld1N0ciIsIm9sZEhlYWRlciIsIm5ld0hlYWRlciIsIm9wdGlvbnMiLCJjb250ZXh0IiwiZGlmZiIsInB1c2giLCJ2YWx1ZSIsImxpbmVzIiwiY29udGV4dExpbmVzIiwibWFwIiwiZW50cnkiLCJodW5rcyIsIm9sZFJhbmdlU3RhcnQiLCJuZXdSYW5nZVN0YXJ0IiwiY3VyUmFuZ2UiLCJvbGRMaW5lIiwibmV3TGluZSIsImkiLCJjdXJyZW50IiwicmVwbGFjZSIsInNwbGl0IiwiYWRkZWQiLCJyZW1vdmVkIiwicHJldiIsInNsaWNlIiwibGVuZ3RoIiwiY29udGV4dFNpemUiLCJNYXRoIiwibWluIiwiaHVuayIsIm9sZFN0YXJ0Iiwib2xkTGluZXMiLCJuZXdTdGFydCIsIm5ld0xpbmVzIiwib2xkRU9GTmV3bGluZSIsInRlc3QiLCJuZXdFT0ZOZXdsaW5lIiwic3BsaWNlIiwicmV0IiwiYXBwbHkiLCJqb2luIiwiZmlsZU5hbWUiXSwibWFwcGluZ3MiOiI7OztnQ0FFZ0JBLGUsR0FBQUEsZTt5REFpR0FDLG1CLEdBQUFBLG1CO3lEQXdCQUMsVyxHQUFBQSxXOztBQTNIaEI7Ozs7dUJBRU8sU0FBU0YsZUFBVCxDQUF5QkcsV0FBekIsRUFBc0NDLFdBQXRDLEVBQW1EQyxNQUFuRCxFQUEyREMsTUFBM0QsRUFBbUVDLFNBQW5FLEVBQThFQyxTQUE5RSxFQUF5RkMsT0FBekYsRUFBa0c7QUFDdkcsTUFBSSxDQUFDQSxPQUFMLEVBQWM7QUFDWkEsY0FBVSxFQUFWO0FBQ0Q7QUFDRCxNQUFJLE9BQU9BLFFBQVFDLE9BQWYsS0FBMkIsV0FBL0IsRUFBNEM7QUFDMUNELFlBQVFDLE9BQVIsR0FBa0IsQ0FBbEI7QUFDRDs7QUFFRCxNQUFNQyxPQUFPLHNFQUFVTixNQUFWLEVBQWtCQyxNQUFsQixFQUEwQkcsT0FBMUIsQ0FBYjtBQUNBRSxPQUFLQyxJQUFMLENBQVUsRUFBQ0MsT0FBTyxFQUFSLEVBQVlDLE9BQU8sRUFBbkIsRUFBVixFQVR1RyxDQVNsRTs7QUFFckMsV0FBU0MsWUFBVCxDQUFzQkQsS0FBdEIsRUFBNkI7QUFDM0IsV0FBT0EsTUFBTUUsR0FBTixDQUFVLFVBQVNDLEtBQVQsRUFBZ0I7QUFBRSxhQUFPLE1BQU1BLEtBQWI7QUFBcUIsS0FBakQsQ0FBUDtBQUNEOztBQUVELE1BQUlDLFFBQVEsRUFBWjtBQUNBLE1BQUlDLGdCQUFnQixDQUFwQjtBQUFBLE1BQXVCQyxnQkFBZ0IsQ0FBdkM7QUFBQSxNQUEwQ0MsV0FBVyxFQUFyRDtBQUFBLE1BQ0lDLFVBQVUsQ0FEZDtBQUFBLE1BQ2lCQyxVQUFVLENBRDNCOztBQWhCdUcsOEVBa0I5RkMsQ0FsQjhGO0FBbUJyRyxRQUFNQyxVQUFVZCxLQUFLYSxDQUFMLENBQWhCO0FBQUEsUUFDTVYsUUFBUVcsUUFBUVgsS0FBUixJQUFpQlcsUUFBUVosS0FBUixDQUFjYSxPQUFkLENBQXNCLEtBQXRCLEVBQTZCLEVBQTdCLEVBQWlDQyxLQUFqQyxDQUF1QyxJQUF2QyxDQUQvQjtBQUVBRixZQUFRWCxLQUFSLEdBQWdCQSxLQUFoQjs7QUFFQSxRQUFJVyxRQUFRRyxLQUFSLElBQWlCSCxRQUFRSSxPQUE3QixFQUFzQztBQUFBOztBQUFBLDhCQUNwQztBQUNBLFVBQUksQ0FBQ1YsYUFBTCxFQUFvQjtBQUNsQixZQUFNVyxPQUFPbkIsS0FBS2EsSUFBSSxDQUFULENBQWI7QUFDQUwsd0JBQWdCRyxPQUFoQjtBQUNBRix3QkFBZ0JHLE9BQWhCOztBQUVBLFlBQUlPLElBQUosRUFBVTtBQUNSVCxxQkFBV1osUUFBUUMsT0FBUixHQUFrQixDQUFsQixHQUFzQkssYUFBYWUsS0FBS2hCLEtBQUwsQ0FBV2lCLEtBQVgsQ0FBaUIsQ0FBQ3RCLFFBQVFDLE9BQTFCLENBQWIsQ0FBdEIsR0FBeUUsRUFBcEY7QUFDQVMsMkJBQWlCRSxTQUFTVyxNQUExQjtBQUNBWiwyQkFBaUJDLFNBQVNXLE1BQTFCO0FBQ0Q7QUFDRjs7QUFFRDtBQUNBLDZFQUFTcEIsSUFBVCwwTEFBa0JFLE1BQU1FLEdBQU4sQ0FBVSxVQUFTQyxLQUFULEVBQWdCO0FBQzFDLGVBQU8sQ0FBQ1EsUUFBUUcsS0FBUixHQUFnQixHQUFoQixHQUFzQixHQUF2QixJQUE4QlgsS0FBckM7QUFDRCxPQUZpQixDQUFsQjs7QUFJQTtBQUNBLFVBQUlRLFFBQVFHLEtBQVosRUFBbUI7QUFDakJMLG1CQUFXVCxNQUFNa0IsTUFBakI7QUFDRCxPQUZELE1BRU87QUFDTFYsbUJBQVdSLE1BQU1rQixNQUFqQjtBQUNEO0FBQ0YsS0F6QkQsTUF5Qk87QUFDTDtBQUNBLFVBQUliLGFBQUosRUFBbUI7QUFDakI7QUFDQSxZQUFJTCxNQUFNa0IsTUFBTixJQUFnQnZCLFFBQVFDLE9BQVIsR0FBa0IsQ0FBbEMsSUFBdUNjLElBQUliLEtBQUtxQixNQUFMLEdBQWMsQ0FBN0QsRUFBZ0U7QUFBQTs7QUFBQSxrQ0FDOUQ7QUFDQSxrRkFBU3BCLElBQVQsMkxBQWtCRyxhQUFhRCxLQUFiLENBQWxCO0FBQ0QsU0FIRCxNQUdPO0FBQUE7O0FBQUEsa0NBQ0w7QUFDQSxjQUFJbUIsY0FBY0MsS0FBS0MsR0FBTCxDQUFTckIsTUFBTWtCLE1BQWYsRUFBdUJ2QixRQUFRQyxPQUEvQixDQUFsQjtBQUNBLGtGQUFTRSxJQUFULDJMQUFrQkcsYUFBYUQsTUFBTWlCLEtBQU4sQ0FBWSxDQUFaLEVBQWVFLFdBQWYsQ0FBYixDQUFsQjs7QUFFQSxjQUFJRyxPQUFPO0FBQ1RDLHNCQUFVbEIsYUFERDtBQUVUbUIsc0JBQVdoQixVQUFVSCxhQUFWLEdBQTBCYyxXQUY1QjtBQUdUTSxzQkFBVW5CLGFBSEQ7QUFJVG9CLHNCQUFXakIsVUFBVUgsYUFBVixHQUEwQmEsV0FKNUI7QUFLVG5CLG1CQUFPTztBQUxFLFdBQVg7QUFPQSxjQUFJRyxLQUFLYixLQUFLcUIsTUFBTCxHQUFjLENBQW5CLElBQXdCbEIsTUFBTWtCLE1BQU4sSUFBZ0J2QixRQUFRQyxPQUFwRCxFQUE2RDtBQUMzRDtBQUNBLGdCQUFJK0IsZ0JBQWlCLE1BQU1DLElBQU4sQ0FBV3JDLE1BQVgsQ0FBckI7QUFDQSxnQkFBSXNDLGdCQUFpQixNQUFNRCxJQUFOLENBQVdwQyxNQUFYLENBQXJCO0FBQ0EsZ0JBQUlRLE1BQU1rQixNQUFOLElBQWdCLENBQWhCLElBQXFCLENBQUNTLGFBQTFCLEVBQXlDO0FBQ3ZDO0FBQ0FwQix1QkFBU3VCLE1BQVQsQ0FBZ0JSLEtBQUtFLFFBQXJCLEVBQStCLENBQS9CLEVBQWtDLDhCQUFsQztBQUNELGFBSEQsTUFHTyxJQUFJLENBQUNHLGFBQUQsSUFBa0IsQ0FBQ0UsYUFBdkIsRUFBc0M7QUFDM0N0Qix1QkFBU1QsSUFBVCxDQUFjLDhCQUFkO0FBQ0Q7QUFDRjtBQUNETSxnQkFBTU4sSUFBTixDQUFXd0IsSUFBWDs7QUFFQWpCLDBCQUFnQixDQUFoQjtBQUNBQywwQkFBZ0IsQ0FBaEI7QUFDQUMscUJBQVcsRUFBWDtBQUNEO0FBQ0Y7QUFDREMsaUJBQVdSLE1BQU1rQixNQUFqQjtBQUNBVCxpQkFBV1QsTUFBTWtCLE1BQWpCO0FBQ0Q7QUF2Rm9HOztBQWtCdkcsT0FBSyxJQUFJUixJQUFJLENBQWIsRUFBZ0JBLElBQUliLEtBQUtxQixNQUF6QixFQUFpQ1IsR0FBakMsRUFBc0M7QUFBQSwyREFBN0JBLENBQTZCO0FBc0VyQzs7QUFFRCxTQUFPO0FBQ0xyQixpQkFBYUEsV0FEUixFQUNxQkMsYUFBYUEsV0FEbEM7QUFFTEcsZUFBV0EsU0FGTixFQUVpQkMsV0FBV0EsU0FGNUI7QUFHTFUsV0FBT0E7QUFIRixHQUFQO0FBS0Q7O0FBRU0sU0FBU2pCLG1CQUFULENBQTZCRSxXQUE3QixFQUEwQ0MsV0FBMUMsRUFBdURDLE1BQXZELEVBQStEQyxNQUEvRCxFQUF1RUMsU0FBdkUsRUFBa0ZDLFNBQWxGLEVBQTZGQyxPQUE3RixFQUFzRztBQUMzRyxNQUFNRSxPQUFPWCxnQkFBZ0JHLFdBQWhCLEVBQTZCQyxXQUE3QixFQUEwQ0MsTUFBMUMsRUFBa0RDLE1BQWxELEVBQTBEQyxTQUExRCxFQUFxRUMsU0FBckUsRUFBZ0ZDLE9BQWhGLENBQWI7O0FBRUEsTUFBTW9DLE1BQU0sRUFBWjtBQUNBLE1BQUkxQyxlQUFlQyxXQUFuQixFQUFnQztBQUM5QnlDLFFBQUlqQyxJQUFKLENBQVMsWUFBWVQsV0FBckI7QUFDRDtBQUNEMEMsTUFBSWpDLElBQUosQ0FBUyxxRUFBVDtBQUNBaUMsTUFBSWpDLElBQUosQ0FBUyxTQUFTRCxLQUFLUixXQUFkLElBQTZCLE9BQU9RLEtBQUtKLFNBQVosS0FBMEIsV0FBMUIsR0FBd0MsRUFBeEMsR0FBNkMsT0FBT0ksS0FBS0osU0FBdEYsQ0FBVDtBQUNBc0MsTUFBSWpDLElBQUosQ0FBUyxTQUFTRCxLQUFLUCxXQUFkLElBQTZCLE9BQU9PLEtBQUtILFNBQVosS0FBMEIsV0FBMUIsR0FBd0MsRUFBeEMsR0FBNkMsT0FBT0csS0FBS0gsU0FBdEYsQ0FBVDs7QUFFQSxPQUFLLElBQUlnQixJQUFJLENBQWIsRUFBZ0JBLElBQUliLEtBQUtPLEtBQUwsQ0FBV2MsTUFBL0IsRUFBdUNSLEdBQXZDLEVBQTRDO0FBQzFDLFFBQU1ZLE9BQU96QixLQUFLTyxLQUFMLENBQVdNLENBQVgsQ0FBYjtBQUNBcUIsUUFBSWpDLElBQUosQ0FDRSxTQUFTd0IsS0FBS0MsUUFBZCxHQUF5QixHQUF6QixHQUErQkQsS0FBS0UsUUFBcEMsR0FDRSxJQURGLEdBQ1NGLEtBQUtHLFFBRGQsR0FDeUIsR0FEekIsR0FDK0JILEtBQUtJLFFBRHBDLEdBRUUsS0FISjtBQUtBSyxRQUFJakMsSUFBSixDQUFTa0MsS0FBVCxDQUFlRCxHQUFmLEVBQW9CVCxLQUFLdEIsS0FBekI7QUFDRDs7QUFFRCxTQUFPK0IsSUFBSUUsSUFBSixDQUFTLElBQVQsSUFBaUIsSUFBeEI7QUFDRDs7QUFFTSxTQUFTN0MsV0FBVCxDQUFxQjhDLFFBQXJCLEVBQStCM0MsTUFBL0IsRUFBdUNDLE1BQXZDLEVBQStDQyxTQUEvQyxFQUEwREMsU0FBMUQsRUFBcUVDLE9BQXJFLEVBQThFO0FBQ25GLFNBQU9SLG9CQUFvQitDLFFBQXBCLEVBQThCQSxRQUE5QixFQUF3QzNDLE1BQXhDLEVBQWdEQyxNQUFoRCxFQUF3REMsU0FBeEQsRUFBbUVDLFNBQW5FLEVBQThFQyxPQUE5RSxDQUFQO0FBQ0QiLCJmaWxlIjoiY3JlYXRlLmpzIiwic291cmNlc0NvbnRlbnQiOlsiaW1wb3J0IHtkaWZmTGluZXN9IGZyb20gJy4uL2RpZmYvbGluZSc7XG5cbmV4cG9ydCBmdW5jdGlvbiBzdHJ1Y3R1cmVkUGF0Y2gob2xkRmlsZU5hbWUsIG5ld0ZpbGVOYW1lLCBvbGRTdHIsIG5ld1N0ciwgb2xkSGVhZGVyLCBuZXdIZWFkZXIsIG9wdGlvbnMpIHtcbiAgaWYgKCFvcHRpb25zKSB7XG4gICAgb3B0aW9ucyA9IHt9O1xuICB9XG4gIGlmICh0eXBlb2Ygb3B0aW9ucy5jb250ZXh0ID09PSAndW5kZWZpbmVkJykge1xuICAgIG9wdGlvbnMuY29udGV4dCA9IDQ7XG4gIH1cblxuICBjb25zdCBkaWZmID0gZGlmZkxpbmVzKG9sZFN0ciwgbmV3U3RyLCBvcHRpb25zKTtcbiAgZGlmZi5wdXNoKHt2YWx1ZTogJycsIGxpbmVzOiBbXX0pOyAgIC8vIEFwcGVuZCBhbiBlbXB0eSB2YWx1ZSB0byBtYWtlIGNsZWFudXAgZWFzaWVyXG5cbiAgZnVuY3Rpb24gY29udGV4dExpbmVzKGxpbmVzKSB7XG4gICAgcmV0dXJuIGxpbmVzLm1hcChmdW5jdGlvbihlbnRyeSkgeyByZXR1cm4gJyAnICsgZW50cnk7IH0pO1xuICB9XG5cbiAgbGV0IGh1bmtzID0gW107XG4gIGxldCBvbGRSYW5nZVN0YXJ0ID0gMCwgbmV3UmFuZ2VTdGFydCA9IDAsIGN1clJhbmdlID0gW10sXG4gICAgICBvbGRMaW5lID0gMSwgbmV3TGluZSA9IDE7XG4gIGZvciAobGV0IGkgPSAwOyBpIDwgZGlmZi5sZW5ndGg7IGkrKykge1xuICAgIGNvbnN0IGN1cnJlbnQgPSBkaWZmW2ldLFxuICAgICAgICAgIGxpbmVzID0gY3VycmVudC5saW5lcyB8fCBjdXJyZW50LnZhbHVlLnJlcGxhY2UoL1xcbiQvLCAnJykuc3BsaXQoJ1xcbicpO1xuICAgIGN1cnJlbnQubGluZXMgPSBsaW5lcztcblxuICAgIGlmIChjdXJyZW50LmFkZGVkIHx8IGN1cnJlbnQucmVtb3ZlZCkge1xuICAgICAgLy8gSWYgd2UgaGF2ZSBwcmV2aW91cyBjb250ZXh0LCBzdGFydCB3aXRoIHRoYXRcbiAgICAgIGlmICghb2xkUmFuZ2VTdGFydCkge1xuICAgICAgICBjb25zdCBwcmV2ID0gZGlmZltpIC0gMV07XG4gICAgICAgIG9sZFJhbmdlU3RhcnQgPSBvbGRMaW5lO1xuICAgICAgICBuZXdSYW5nZVN0YXJ0ID0gbmV3TGluZTtcblxuICAgICAgICBpZiAocHJldikge1xuICAgICAgICAgIGN1clJhbmdlID0gb3B0aW9ucy5jb250ZXh0ID4gMCA/IGNvbnRleHRMaW5lcyhwcmV2LmxpbmVzLnNsaWNlKC1vcHRpb25zLmNvbnRleHQpKSA6IFtdO1xuICAgICAgICAgIG9sZFJhbmdlU3RhcnQgLT0gY3VyUmFuZ2UubGVuZ3RoO1xuICAgICAgICAgIG5ld1JhbmdlU3RhcnQgLT0gY3VyUmFuZ2UubGVuZ3RoO1xuICAgICAgICB9XG4gICAgICB9XG5cbiAgICAgIC8vIE91dHB1dCBvdXIgY2hhbmdlc1xuICAgICAgY3VyUmFuZ2UucHVzaCguLi4gbGluZXMubWFwKGZ1bmN0aW9uKGVudHJ5KSB7XG4gICAgICAgIHJldHVybiAoY3VycmVudC5hZGRlZCA/ICcrJyA6ICctJykgKyBlbnRyeTtcbiAgICAgIH0pKTtcblxuICAgICAgLy8gVHJhY2sgdGhlIHVwZGF0ZWQgZmlsZSBwb3NpdGlvblxuICAgICAgaWYgKGN1cnJlbnQuYWRkZWQpIHtcbiAgICAgICAgbmV3TGluZSArPSBsaW5lcy5sZW5ndGg7XG4gICAgICB9IGVsc2Uge1xuICAgICAgICBvbGRMaW5lICs9IGxpbmVzLmxlbmd0aDtcbiAgICAgIH1cbiAgICB9IGVsc2Uge1xuICAgICAgLy8gSWRlbnRpY2FsIGNvbnRleHQgbGluZXMuIFRyYWNrIGxpbmUgY2hhbmdlc1xuICAgICAgaWYgKG9sZFJhbmdlU3RhcnQpIHtcbiAgICAgICAgLy8gQ2xvc2Ugb3V0IGFueSBjaGFuZ2VzIHRoYXQgaGF2ZSBiZWVuIG91dHB1dCAob3Igam9pbiBvdmVybGFwcGluZylcbiAgICAgICAgaWYgKGxpbmVzLmxlbmd0aCA8PSBvcHRpb25zLmNvbnRleHQgKiAyICYmIGkgPCBkaWZmLmxlbmd0aCAtIDIpIHtcbiAgICAgICAgICAvLyBPdmVybGFwcGluZ1xuICAgICAgICAgIGN1clJhbmdlLnB1c2goLi4uIGNvbnRleHRMaW5lcyhsaW5lcykpO1xuICAgICAgICB9IGVsc2Uge1xuICAgICAgICAgIC8vIGVuZCB0aGUgcmFuZ2UgYW5kIG91dHB1dFxuICAgICAgICAgIGxldCBjb250ZXh0U2l6ZSA9IE1hdGgubWluKGxpbmVzLmxlbmd0aCwgb3B0aW9ucy5jb250ZXh0KTtcbiAgICAgICAgICBjdXJSYW5nZS5wdXNoKC4uLiBjb250ZXh0TGluZXMobGluZXMuc2xpY2UoMCwgY29udGV4dFNpemUpKSk7XG5cbiAgICAgICAgICBsZXQgaHVuayA9IHtcbiAgICAgICAgICAgIG9sZFN0YXJ0OiBvbGRSYW5nZVN0YXJ0LFxuICAgICAgICAgICAgb2xkTGluZXM6IChvbGRMaW5lIC0gb2xkUmFuZ2VTdGFydCArIGNvbnRleHRTaXplKSxcbiAgICAgICAgICAgIG5ld1N0YXJ0OiBuZXdSYW5nZVN0YXJ0LFxuICAgICAgICAgICAgbmV3TGluZXM6IChuZXdMaW5lIC0gbmV3UmFuZ2VTdGFydCArIGNvbnRleHRTaXplKSxcbiAgICAgICAgICAgIGxpbmVzOiBjdXJSYW5nZVxuICAgICAgICAgIH07XG4gICAgICAgICAgaWYgKGkgPj0gZGlmZi5sZW5ndGggLSAyICYmIGxpbmVzLmxlbmd0aCA8PSBvcHRpb25zLmNvbnRleHQpIHtcbiAgICAgICAgICAgIC8vIEVPRiBpcyBpbnNpZGUgdGhpcyBodW5rXG4gICAgICAgICAgICBsZXQgb2xkRU9GTmV3bGluZSA9ICgvXFxuJC8udGVzdChvbGRTdHIpKTtcbiAgICAgICAgICAgIGxldCBuZXdFT0ZOZXdsaW5lID0gKC9cXG4kLy50ZXN0KG5ld1N0cikpO1xuICAgICAgICAgICAgaWYgKGxpbmVzLmxlbmd0aCA9PSAwICYmICFvbGRFT0ZOZXdsaW5lKSB7XG4gICAgICAgICAgICAgIC8vIHNwZWNpYWwgY2FzZTogb2xkIGhhcyBubyBlb2wgYW5kIG5vIHRyYWlsaW5nIGNvbnRleHQ7IG5vLW5sIGNhbiBlbmQgdXAgYmVmb3JlIGFkZHNcbiAgICAgICAgICAgICAgY3VyUmFuZ2Uuc3BsaWNlKGh1bmsub2xkTGluZXMsIDAsICdcXFxcIE5vIG5ld2xpbmUgYXQgZW5kIG9mIGZpbGUnKTtcbiAgICAgICAgICAgIH0gZWxzZSBpZiAoIW9sZEVPRk5ld2xpbmUgfHwgIW5ld0VPRk5ld2xpbmUpIHtcbiAgICAgICAgICAgICAgY3VyUmFuZ2UucHVzaCgnXFxcXCBObyBuZXdsaW5lIGF0IGVuZCBvZiBmaWxlJyk7XG4gICAgICAgICAgICB9XG4gICAgICAgICAgfVxuICAgICAgICAgIGh1bmtzLnB1c2goaHVuayk7XG5cbiAgICAgICAgICBvbGRSYW5nZVN0YXJ0ID0gMDtcbiAgICAgICAgICBuZXdSYW5nZVN0YXJ0ID0gMDtcbiAgICAgICAgICBjdXJSYW5nZSA9IFtdO1xuICAgICAgICB9XG4gICAgICB9XG4gICAgICBvbGRMaW5lICs9IGxpbmVzLmxlbmd0aDtcbiAgICAgIG5ld0xpbmUgKz0gbGluZXMubGVuZ3RoO1xuICAgIH1cbiAgfVxuXG4gIHJldHVybiB7XG4gICAgb2xkRmlsZU5hbWU6IG9sZEZpbGVOYW1lLCBuZXdGaWxlTmFtZTogbmV3RmlsZU5hbWUsXG4gICAgb2xkSGVhZGVyOiBvbGRIZWFkZXIsIG5ld0hlYWRlcjogbmV3SGVhZGVyLFxuICAgIGh1bmtzOiBodW5rc1xuICB9O1xufVxuXG5leHBvcnQgZnVuY3Rpb24gY3JlYXRlVHdvRmlsZXNQYXRjaChvbGRGaWxlTmFtZSwgbmV3RmlsZU5hbWUsIG9sZFN0ciwgbmV3U3RyLCBvbGRIZWFkZXIsIG5ld0hlYWRlciwgb3B0aW9ucykge1xuICBjb25zdCBkaWZmID0gc3RydWN0dXJlZFBhdGNoKG9sZEZpbGVOYW1lLCBuZXdGaWxlTmFtZSwgb2xkU3RyLCBuZXdTdHIsIG9sZEhlYWRlciwgbmV3SGVhZGVyLCBvcHRpb25zKTtcblxuICBjb25zdCByZXQgPSBbXTtcbiAgaWYgKG9sZEZpbGVOYW1lID09IG5ld0ZpbGVOYW1lKSB7XG4gICAgcmV0LnB1c2goJ0luZGV4OiAnICsgb2xkRmlsZU5hbWUpO1xuICB9XG4gIHJldC5wdXNoKCc9PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09Jyk7XG4gIHJldC5wdXNoKCctLS0gJyArIGRpZmYub2xkRmlsZU5hbWUgKyAodHlwZW9mIGRpZmYub2xkSGVhZGVyID09PSAndW5kZWZpbmVkJyA/ICcnIDogJ1xcdCcgKyBkaWZmLm9sZEhlYWRlcikpO1xuICByZXQucHVzaCgnKysrICcgKyBkaWZmLm5ld0ZpbGVOYW1lICsgKHR5cGVvZiBkaWZmLm5ld0hlYWRlciA9PT0gJ3VuZGVmaW5lZCcgPyAnJyA6ICdcXHQnICsgZGlmZi5uZXdIZWFkZXIpKTtcblxuICBmb3IgKGxldCBpID0gMDsgaSA8IGRpZmYuaHVua3MubGVuZ3RoOyBpKyspIHtcbiAgICBjb25zdCBodW5rID0gZGlmZi5odW5rc1tpXTtcbiAgICByZXQucHVzaChcbiAgICAgICdAQCAtJyArIGh1bmsub2xkU3RhcnQgKyAnLCcgKyBodW5rLm9sZExpbmVzXG4gICAgICArICcgKycgKyBodW5rLm5ld1N0YXJ0ICsgJywnICsgaHVuay5uZXdMaW5lc1xuICAgICAgKyAnIEBAJ1xuICAgICk7XG4gICAgcmV0LnB1c2guYXBwbHkocmV0LCBodW5rLmxpbmVzKTtcbiAgfVxuXG4gIHJldHVybiByZXQuam9pbignXFxuJykgKyAnXFxuJztcbn1cblxuZXhwb3J0IGZ1bmN0aW9uIGNyZWF0ZVBhdGNoKGZpbGVOYW1lLCBvbGRTdHIsIG5ld1N0ciwgb2xkSGVhZGVyLCBuZXdIZWFkZXIsIG9wdGlvbnMpIHtcbiAgcmV0dXJuIGNyZWF0ZVR3b0ZpbGVzUGF0Y2goZmlsZU5hbWUsIGZpbGVOYW1lLCBvbGRTdHIsIG5ld1N0ciwgb2xkSGVhZGVyLCBuZXdIZWFkZXIsIG9wdGlvbnMpO1xufVxuIl19
+
+
+/***/ }),
+/* 15 */
+/***/ (function(module, exports) {
+
+	/*istanbul ignore start*/"use strict";
+
+	exports.__esModule = true;
+	exports. /*istanbul ignore end*/arrayEqual = arrayEqual;
+	/*istanbul ignore start*/exports. /*istanbul ignore end*/arrayStartsWith = arrayStartsWith;
+	function arrayEqual(a, b) {
+	  if (a.length !== b.length) {
+	    return false;
+	  }
+
+	  return arrayStartsWith(a, b);
+	}
+
+	function arrayStartsWith(array, start) {
+	  if (start.length > array.length) {
+	    return false;
+	  }
+
+	  for (var i = 0; i < start.length; i++) {
+	    if (start[i] !== array[i]) {
+	      return false;
+	    }
+	  }
+
+	  return true;
+	}
+	//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy91dGlsL2FycmF5LmpzIl0sIm5hbWVzIjpbImFycmF5RXF1YWwiLCJhcnJheVN0YXJ0c1dpdGgiLCJhIiwiYiIsImxlbmd0aCIsImFycmF5Iiwic3RhcnQiLCJpIl0sIm1hcHBpbmdzIjoiOzs7Z0NBQWdCQSxVLEdBQUFBLFU7eURBUUFDLGUsR0FBQUEsZTtBQVJULFNBQVNELFVBQVQsQ0FBb0JFLENBQXBCLEVBQXVCQyxDQUF2QixFQUEwQjtBQUMvQixNQUFJRCxFQUFFRSxNQUFGLEtBQWFELEVBQUVDLE1BQW5CLEVBQTJCO0FBQ3pCLFdBQU8sS0FBUDtBQUNEOztBQUVELFNBQU9ILGdCQUFnQkMsQ0FBaEIsRUFBbUJDLENBQW5CLENBQVA7QUFDRDs7QUFFTSxTQUFTRixlQUFULENBQXlCSSxLQUF6QixFQUFnQ0MsS0FBaEMsRUFBdUM7QUFDNUMsTUFBSUEsTUFBTUYsTUFBTixHQUFlQyxNQUFNRCxNQUF6QixFQUFpQztBQUMvQixXQUFPLEtBQVA7QUFDRDs7QUFFRCxPQUFLLElBQUlHLElBQUksQ0FBYixFQUFnQkEsSUFBSUQsTUFBTUYsTUFBMUIsRUFBa0NHLEdBQWxDLEVBQXVDO0FBQ3JDLFFBQUlELE1BQU1DLENBQU4sTUFBYUYsTUFBTUUsQ0FBTixDQUFqQixFQUEyQjtBQUN6QixhQUFPLEtBQVA7QUFDRDtBQUNGOztBQUVELFNBQU8sSUFBUDtBQUNEIiwiZmlsZSI6ImFycmF5LmpzIiwic291cmNlc0NvbnRlbnQiOlsiZXhwb3J0IGZ1bmN0aW9uIGFycmF5RXF1YWwoYSwgYikge1xuICBpZiAoYS5sZW5ndGggIT09IGIubGVuZ3RoKSB7XG4gICAgcmV0dXJuIGZhbHNlO1xuICB9XG5cbiAgcmV0dXJuIGFycmF5U3RhcnRzV2l0aChhLCBiKTtcbn1cblxuZXhwb3J0IGZ1bmN0aW9uIGFycmF5U3RhcnRzV2l0aChhcnJheSwgc3RhcnQpIHtcbiAgaWYgKHN0YXJ0Lmxlbmd0aCA+IGFycmF5Lmxlbmd0aCkge1xuICAgIHJldHVybiBmYWxzZTtcbiAgfVxuXG4gIGZvciAobGV0IGkgPSAwOyBpIDwgc3RhcnQubGVuZ3RoOyBpKyspIHtcbiAgICBpZiAoc3RhcnRbaV0gIT09IGFycmF5W2ldKSB7XG4gICAgICByZXR1cm4gZmFsc2U7XG4gICAgfVxuICB9XG5cbiAgcmV0dXJuIHRydWU7XG59XG4iXX0=
+
+
+/***/ }),
+/* 16 */
+/***/ (function(module, exports) {
+
+	/*istanbul ignore start*/"use strict";
+
+	exports.__esModule = true;
+	exports. /*istanbul ignore end*/convertChangesToDMP = convertChangesToDMP;
+	// See: http://code.google.com/p/google-diff-match-patch/wiki/API
+	function convertChangesToDMP(changes) {
+	  var ret = [],
+	      change = /*istanbul ignore start*/void 0 /*istanbul ignore end*/,
+	      operation = /*istanbul ignore start*/void 0 /*istanbul ignore end*/;
+	  for (var i = 0; i < changes.length; i++) {
+	    change = changes[i];
+	    if (change.added) {
+	      operation = 1;
+	    } else if (change.removed) {
+	      operation = -1;
+	    } else {
+	      operation = 0;
+	    }
+
+	    ret.push([operation, change.value]);
+	  }
+	  return ret;
+	}
+	//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9jb252ZXJ0L2RtcC5qcyJdLCJuYW1lcyI6WyJjb252ZXJ0Q2hhbmdlc1RvRE1QIiwiY2hhbmdlcyIsInJldCIsImNoYW5nZSIsIm9wZXJhdGlvbiIsImkiLCJsZW5ndGgiLCJhZGRlZCIsInJlbW92ZWQiLCJwdXNoIiwidmFsdWUiXSwibWFwcGluZ3MiOiI7OztnQ0FDZ0JBLG1CLEdBQUFBLG1CO0FBRGhCO0FBQ08sU0FBU0EsbUJBQVQsQ0FBNkJDLE9BQTdCLEVBQXNDO0FBQzNDLE1BQUlDLE1BQU0sRUFBVjtBQUFBLE1BQ0lDLHdDQURKO0FBQUEsTUFFSUMsMkNBRko7QUFHQSxPQUFLLElBQUlDLElBQUksQ0FBYixFQUFnQkEsSUFBSUosUUFBUUssTUFBNUIsRUFBb0NELEdBQXBDLEVBQXlDO0FBQ3ZDRixhQUFTRixRQUFRSSxDQUFSLENBQVQ7QUFDQSxRQUFJRixPQUFPSSxLQUFYLEVBQWtCO0FBQ2hCSCxrQkFBWSxDQUFaO0FBQ0QsS0FGRCxNQUVPLElBQUlELE9BQU9LLE9BQVgsRUFBb0I7QUFDekJKLGtCQUFZLENBQUMsQ0FBYjtBQUNELEtBRk0sTUFFQTtBQUNMQSxrQkFBWSxDQUFaO0FBQ0Q7O0FBRURGLFFBQUlPLElBQUosQ0FBUyxDQUFDTCxTQUFELEVBQVlELE9BQU9PLEtBQW5CLENBQVQ7QUFDRDtBQUNELFNBQU9SLEdBQVA7QUFDRCIsImZpbGUiOiJkbXAuanMiLCJzb3VyY2VzQ29udGVudCI6WyIvLyBTZWU6IGh0dHA6Ly9jb2RlLmdvb2dsZS5jb20vcC9nb29nbGUtZGlmZi1tYXRjaC1wYXRjaC93aWtpL0FQSVxuZXhwb3J0IGZ1bmN0aW9uIGNvbnZlcnRDaGFuZ2VzVG9ETVAoY2hhbmdlcykge1xuICBsZXQgcmV0ID0gW10sXG4gICAgICBjaGFuZ2UsXG4gICAgICBvcGVyYXRpb247XG4gIGZvciAobGV0IGkgPSAwOyBpIDwgY2hhbmdlcy5sZW5ndGg7IGkrKykge1xuICAgIGNoYW5nZSA9IGNoYW5nZXNbaV07XG4gICAgaWYgKGNoYW5nZS5hZGRlZCkge1xuICAgICAgb3BlcmF0aW9uID0gMTtcbiAgICB9IGVsc2UgaWYgKGNoYW5nZS5yZW1vdmVkKSB7XG4gICAgICBvcGVyYXRpb24gPSAtMTtcbiAgICB9IGVsc2Uge1xuICAgICAgb3BlcmF0aW9uID0gMDtcbiAgICB9XG5cbiAgICByZXQucHVzaChbb3BlcmF0aW9uLCBjaGFuZ2UudmFsdWVdKTtcbiAgfVxuICByZXR1cm4gcmV0O1xufVxuIl19
+
+
+/***/ }),
+/* 17 */
+/***/ (function(module, exports) {
+
+	/*istanbul ignore start*/'use strict';
+
+	exports.__esModule = true;
+	exports. /*istanbul ignore end*/convertChangesToXML = convertChangesToXML;
+	function convertChangesToXML(changes) {
+	  var ret = [];
+	  for (var i = 0; i < changes.length; i++) {
+	    var change = changes[i];
+	    if (change.added) {
+	      ret.push('');
+	    } else if (change.removed) {
+	      ret.push('');
+	    }
+
+	    ret.push(escapeHTML(change.value));
+
+	    if (change.added) {
+	      ret.push('');
+	    } else if (change.removed) {
+	      ret.push('');
+	    }
+	  }
+	  return ret.join('');
+	}
+
+	function escapeHTML(s) {
+	  var n = s;
+	  n = n.replace(/&/g, '&');
+	  n = n.replace(//g, '>');
+	  n = n.replace(/"/g, '"');
+
+	  return n;
+	}
+	//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9jb252ZXJ0L3htbC5qcyJdLCJuYW1lcyI6WyJjb252ZXJ0Q2hhbmdlc1RvWE1MIiwiY2hhbmdlcyIsInJldCIsImkiLCJsZW5ndGgiLCJjaGFuZ2UiLCJhZGRlZCIsInB1c2giLCJyZW1vdmVkIiwiZXNjYXBlSFRNTCIsInZhbHVlIiwiam9pbiIsInMiLCJuIiwicmVwbGFjZSJdLCJtYXBwaW5ncyI6Ijs7O2dDQUFnQkEsbUIsR0FBQUEsbUI7QUFBVCxTQUFTQSxtQkFBVCxDQUE2QkMsT0FBN0IsRUFBc0M7QUFDM0MsTUFBSUMsTUFBTSxFQUFWO0FBQ0EsT0FBSyxJQUFJQyxJQUFJLENBQWIsRUFBZ0JBLElBQUlGLFFBQVFHLE1BQTVCLEVBQW9DRCxHQUFwQyxFQUF5QztBQUN2QyxRQUFJRSxTQUFTSixRQUFRRSxDQUFSLENBQWI7QUFDQSxRQUFJRSxPQUFPQyxLQUFYLEVBQWtCO0FBQ2hCSixVQUFJSyxJQUFKLENBQVMsT0FBVDtBQUNELEtBRkQsTUFFTyxJQUFJRixPQUFPRyxPQUFYLEVBQW9CO0FBQ3pCTixVQUFJSyxJQUFKLENBQVMsT0FBVDtBQUNEOztBQUVETCxRQUFJSyxJQUFKLENBQVNFLFdBQVdKLE9BQU9LLEtBQWxCLENBQVQ7O0FBRUEsUUFBSUwsT0FBT0MsS0FBWCxFQUFrQjtBQUNoQkosVUFBSUssSUFBSixDQUFTLFFBQVQ7QUFDRCxLQUZELE1BRU8sSUFBSUYsT0FBT0csT0FBWCxFQUFvQjtBQUN6Qk4sVUFBSUssSUFBSixDQUFTLFFBQVQ7QUFDRDtBQUNGO0FBQ0QsU0FBT0wsSUFBSVMsSUFBSixDQUFTLEVBQVQsQ0FBUDtBQUNEOztBQUVELFNBQVNGLFVBQVQsQ0FBb0JHLENBQXBCLEVBQXVCO0FBQ3JCLE1BQUlDLElBQUlELENBQVI7QUFDQUMsTUFBSUEsRUFBRUMsT0FBRixDQUFVLElBQVYsRUFBZ0IsT0FBaEIsQ0FBSjtBQUNBRCxNQUFJQSxFQUFFQyxPQUFGLENBQVUsSUFBVixFQUFnQixNQUFoQixDQUFKO0FBQ0FELE1BQUlBLEVBQUVDLE9BQUYsQ0FBVSxJQUFWLEVBQWdCLE1BQWhCLENBQUo7QUFDQUQsTUFBSUEsRUFBRUMsT0FBRixDQUFVLElBQVYsRUFBZ0IsUUFBaEIsQ0FBSjs7QUFFQSxTQUFPRCxDQUFQO0FBQ0QiLCJmaWxlIjoieG1sLmpzIiwic291cmNlc0NvbnRlbnQiOlsiZXhwb3J0IGZ1bmN0aW9uIGNvbnZlcnRDaGFuZ2VzVG9YTUwoY2hhbmdlcykge1xuICBsZXQgcmV0ID0gW107XG4gIGZvciAobGV0IGkgPSAwOyBpIDwgY2hhbmdlcy5sZW5ndGg7IGkrKykge1xuICAgIGxldCBjaGFuZ2UgPSBjaGFuZ2VzW2ldO1xuICAgIGlmIChjaGFuZ2UuYWRkZWQpIHtcbiAgICAgIHJldC5wdXNoKCc8aW5zPicpO1xuICAgIH0gZWxzZSBpZiAoY2hhbmdlLnJlbW92ZWQpIHtcbiAgICAgIHJldC5wdXNoKCc8ZGVsPicpO1xuICAgIH1cblxuICAgIHJldC5wdXNoKGVzY2FwZUhUTUwoY2hhbmdlLnZhbHVlKSk7XG5cbiAgICBpZiAoY2hhbmdlLmFkZGVkKSB7XG4gICAgICByZXQucHVzaCgnPC9pbnM+Jyk7XG4gICAgfSBlbHNlIGlmIChjaGFuZ2UucmVtb3ZlZCkge1xuICAgICAgcmV0LnB1c2goJzwvZGVsPicpO1xuICAgIH1cbiAgfVxuICByZXR1cm4gcmV0LmpvaW4oJycpO1xufVxuXG5mdW5jdGlvbiBlc2NhcGVIVE1MKHMpIHtcbiAgbGV0IG4gPSBzO1xuICBuID0gbi5yZXBsYWNlKC8mL2csICcmYW1wOycpO1xuICBuID0gbi5yZXBsYWNlKC88L2csICcmbHQ7Jyk7XG4gIG4gPSBuLnJlcGxhY2UoLz4vZywgJyZndDsnKTtcbiAgbiA9IG4ucmVwbGFjZSgvXCIvZywgJyZxdW90OycpO1xuXG4gIHJldHVybiBuO1xufVxuIl19
+
+
+/***/ })
+/******/ ])
+});
+;
\ No newline at end of file
diff --git a/node_modules/diff/dist/diff.min.js b/node_modules/diff/dist/diff.min.js
new file mode 100644
index 0000000..5049f84
--- /dev/null
+++ b/node_modules/diff/dist/diff.min.js
@@ -0,0 +1,416 @@
+/*!
+
+ diff v3.5.0
+
+Software License Agreement (BSD License)
+
+Copyright (c) 2009-2015, Kevin Decker 
+
+All rights reserved.
+
+Redistribution and use of this software in source and binary forms, with or without modification,
+are permitted provided that the following conditions are met:
+
+* Redistributions of source code must retain the above
+  copyright notice, this list of conditions and the
+  following disclaimer.
+
+* Redistributions in binary form must reproduce the above
+  copyright notice, this list of conditions and the
+  following disclaimer in the documentation and/or other
+  materials provided with the distribution.
+
+* Neither the name of Kevin Decker nor the names of its
+  contributors may be used to endorse or promote products
+  derived from this software without specific prior
+  written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
+IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
+FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
+CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
+IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
+OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+@license
+*/
+!function(a,b){"object"==typeof exports&&"object"==typeof module?module.exports=b():"function"==typeof define&&define.amd?define([],b):"object"==typeof exports?exports.JsDiff=b():a.JsDiff=b()}(this,function(){/******/
+return function(a){/******/
+// The require function
+/******/
+function b(d){/******/
+// Check if module is in cache
+/******/
+if(c[d])/******/
+return c[d].exports;/******/
+// Create a new module (and put it into the cache)
+/******/
+var e=c[d]={/******/
+exports:{},/******/
+id:d,/******/
+loaded:!1};/******/
+// Return the exports of the module
+/******/
+/******/
+// Execute the module function
+/******/
+/******/
+// Flag the module as loaded
+/******/
+return a[d].call(e.exports,e,e.exports,b),e.loaded=!0,e.exports}// webpackBootstrap
+/******/
+// The module cache
+/******/
+var c={};/******/
+// Load entry module and return exports
+/******/
+/******/
+// expose the modules object (__webpack_modules__)
+/******/
+/******/
+// expose the module cache
+/******/
+/******/
+// __webpack_public_path__
+/******/
+return b.m=a,b.c=c,b.p="",b(0)}([/* 0 */
+/***/
+function(a,b,c){/*istanbul ignore start*/
+"use strict";/*istanbul ignore start*/
+function d(a){return a&&a.__esModule?a:{"default":a}}b.__esModule=!0,b.canonicalize=b.convertChangesToXML=b.convertChangesToDMP=b.merge=b.parsePatch=b.applyPatches=b.applyPatch=b.createPatch=b.createTwoFilesPatch=b.structuredPatch=b.diffArrays=b.diffJson=b.diffCss=b.diffSentences=b.diffTrimmedLines=b.diffLines=b.diffWordsWithSpace=b.diffWords=b.diffChars=b.Diff=void 0;/*istanbul ignore end*/
+var/*istanbul ignore start*/e=c(1),f=d(e),/*istanbul ignore start*/g=c(2),/*istanbul ignore start*/h=c(3),/*istanbul ignore start*/i=c(5),/*istanbul ignore start*/j=c(6),/*istanbul ignore start*/k=c(7),/*istanbul ignore start*/l=c(8),/*istanbul ignore start*/m=c(9),/*istanbul ignore start*/n=c(10),/*istanbul ignore start*/o=c(11),/*istanbul ignore start*/p=c(13),/*istanbul ignore start*/q=c(14),/*istanbul ignore start*/r=c(16),/*istanbul ignore start*/s=c(17);/* See LICENSE file for terms of use */
+/*
+	 * Text diff implementation.
+	 *
+	 * This library supports the following APIS:
+	 * JsDiff.diffChars: Character by character diff
+	 * JsDiff.diffWords: Word (as defined by \b regex) diff which ignores whitespace
+	 * JsDiff.diffLines: Line based diff
+	 *
+	 * JsDiff.diffCss: Diff targeted at CSS content
+	 *
+	 * These methods are based on the implementation proposed in
+	 * "An O(ND) Difference Algorithm and its Variations" (Myers, 1986).
+	 * http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.4.6927
+	 */
+b.Diff=f["default"],/*istanbul ignore start*/
+b.diffChars=g.diffChars,/*istanbul ignore start*/
+b.diffWords=h.diffWords,/*istanbul ignore start*/
+b.diffWordsWithSpace=h.diffWordsWithSpace,/*istanbul ignore start*/
+b.diffLines=i.diffLines,/*istanbul ignore start*/
+b.diffTrimmedLines=i.diffTrimmedLines,/*istanbul ignore start*/
+b.diffSentences=j.diffSentences,/*istanbul ignore start*/
+b.diffCss=k.diffCss,/*istanbul ignore start*/
+b.diffJson=l.diffJson,/*istanbul ignore start*/
+b.diffArrays=m.diffArrays,/*istanbul ignore start*/
+b.structuredPatch=q.structuredPatch,/*istanbul ignore start*/
+b.createTwoFilesPatch=q.createTwoFilesPatch,/*istanbul ignore start*/
+b.createPatch=q.createPatch,/*istanbul ignore start*/
+b.applyPatch=n.applyPatch,/*istanbul ignore start*/
+b.applyPatches=n.applyPatches,/*istanbul ignore start*/
+b.parsePatch=o.parsePatch,/*istanbul ignore start*/
+b.merge=p.merge,/*istanbul ignore start*/
+b.convertChangesToDMP=r.convertChangesToDMP,/*istanbul ignore start*/
+b.convertChangesToXML=s.convertChangesToXML,/*istanbul ignore start*/
+b.canonicalize=l.canonicalize},/* 1 */
+/***/
+function(a,b){/*istanbul ignore start*/
+"use strict";function c(){}function d(a,b,c,d,e){for(var f=0,g=b.length,h=0,i=0;fa.length?c:a}),j.value=a.join(l)}else j.value=a.join(c.slice(h,h+j.count));h+=j.count,
+// Common case
+j.added||(i+=j.count)}}
+// Special case handle for when one terminal is ignored (i.e. whitespace).
+// For this case we merge the terminal into the prior string and drop the change.
+// This is only available for string mode.
+var m=b[g-1];return g>1&&"string"==typeof m.value&&(m.added||m.removed)&&a.equals("",m.value)&&(b[g-2].value+=m.value,b.pop()),b}function e(a){return{newPos:a.newPos,components:a.components.slice(0)}}b.__esModule=!0,b["default"]=/*istanbul ignore end*/c,c.prototype={/*istanbul ignore start*/
+/*istanbul ignore end*/
+diff:function(a,b){function c(a){return h?(setTimeout(function(){h(void 0,a)},0),!0):a}
+// Main worker method. checks all permutations of a given edit length for acceptance.
+function f(){for(var f=-1*l;f<=l;f+=2){var g=/*istanbul ignore start*/void 0,h=n[f-1],m=n[f+1],o=(m?m.newPos:0)-f;h&&(
+// No one else is going to attempt to use this value, clear it
+n[f-1]=void 0);var p=h&&h.newPos+1=j&&o+1>=k)return c(d(i,g.components,b,a,i.useLongestToken));
+// Otherwise track this path as a potential candidate and continue.
+n[f]=g}else
+// If this path is a terminal then prune
+n[f]=void 0}l++}/*istanbul ignore start*/
+var/*istanbul ignore end*/g=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},h=g.callback;"function"==typeof g&&(h=g,g={}),this.options=g;var i=this;
+// Allow subclasses to massage the input prior to running
+a=this.castInput(a),b=this.castInput(b),a=this.removeEmpty(this.tokenize(a)),b=this.removeEmpty(this.tokenize(b));var j=b.length,k=a.length,l=1,m=j+k,n=[{newPos:-1,components:[]}],o=this.extractCommon(n[0],b,a,0);if(n[0].newPos+1>=j&&o+1>=k)
+// Identity per the equality and tokenizer
+return c([{value:this.join(b),count:b.length}]);
+// Performs the length of edit iteration. Is a bit fugly as this has to support the
+// sync and async mode which is never fun. Loops over execEditLength until a value
+// is produced.
+if(h)!function q(){setTimeout(function(){
+// This should not happen, but we want to be safe.
+/* istanbul ignore next */
+// This should not happen, but we want to be safe.
+/* istanbul ignore next */
+return l>m?h():void(f()||q())},0)}();else for(;l<=m;){var p=f();if(p)return p}},/*istanbul ignore start*/
+/*istanbul ignore end*/
+pushComponent:function(a,b,c){var d=a[a.length-1];d&&d.added===b&&d.removed===c?
+// We need to clone here as the component clone operation is just
+// as shallow array clone
+a[a.length-1]={count:d.count+1,added:b,removed:c}:a.push({count:1,added:b,removed:c})},/*istanbul ignore start*/
+/*istanbul ignore end*/
+extractCommon:function(a,b,c,d){for(var e=b.length,f=c.length,g=a.newPos,h=g-d,i=0;g+10?d[0]:" ",g=d.length>0?d.substr(1):d;if(" "===f||"-"===f){
+// Context sanity check
+if(!j(b+1,e[b],f,g)&&(k++,k>l))return!1;b++}}return!0}/*istanbul ignore start*/
+var/*istanbul ignore end*/d=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if("string"==typeof b&&(b=/*istanbul ignore start*/(0,g.parsePatch)(b)),Array.isArray(b)){if(b.length>1)throw new Error("applyPatch only works with a single input.");b=b[0]}
+// Search best fit offsets for each hunk based on the previous ones
+for(var e=a.split(/\r\n|[\n\v\f\r\x85]/),f=a.match(/\r\n|[\n\v\f\r\x85]/g)||[],h=b.hunks,j=d.compareLine||function(a,b,c,d){/*istanbul ignore end*/
+return b===d},k=0,l=d.fuzzFactor||0,m=0,n=0,o=/*istanbul ignore start*/void 0,p=/*istanbul ignore start*/void 0,q=0;q0?B[0]:" ",D=B.length>0?B.substr(1):B,E=y.linedelimiters[A];if(" "===C)z++;else if("-"===C)e.splice(z,1),f.splice(z,1);else if("+"===C)e.splice(z,0,D),f.splice(z,0,E),z++;else if("\\"===C){var F=y.lines[A-1]?y.lines[A-1][0]:null;"+"===F?o=!0:"-"===F&&(p=!0)}}}
+// Handle EOFNL insertion/removal
+if(o)for(;!e[e.length-1];)e.pop(),f.pop();else p&&(e.push(""),f.push("\n"));for(var G=0;G1&&void 0!==arguments[1]?arguments[1]:{},f=a.split(/\r\n|[\n\v\f\r\x85]/),g=a.match(/\r\n|[\n\v\f\r\x85]/g)||[],h=[],i=0;i0?j(h.lines.slice(-i.context)):[],m-=o.length,n-=o.length)}
+// Output our changes
+/*istanbul ignore start*/
+(g=/*istanbul ignore end*/o).push.apply(/*istanbul ignore start*/g,/*istanbul ignore start*/d(/*istanbul ignore end*/f.map(function(a){return(b.added?"+":"-")+a}))),
+// Track the updated file position
+b.added?q+=f.length:p+=f.length}else{
+// Identical context lines. Track line changes
+if(m)
+// Close out any changes that have been output (or join overlapping)
+if(f.length<=2*i.context&&a=k.length-2&&f.length<=i.context){
+// EOF is inside this hunk
+var v=/\n$/.test(c),w=/\n$/.test(e);0!=f.length||v?v&&w||o.push("\\ No newline at end of file"):
+// special case: old has no eol and no trailing context; no-nl can end up before adds
+o.splice(u.oldLines,0,"\\ No newline at end of file")}l.push(u),m=0,n=0,o=[]}p+=f.length,q+=f.length}},s=0;sa.length)return!1;for(var c=0;c"):e.removed&&b.push(""),b.push(d(e.value)),e.added?b.push(""):e.removed&&b.push("")}return b.join("")}function d(a){var b=a;return b=b.replace(/&/g,"&"),b=b.replace(//g,">"),b=b.replace(/"/g,""")}b.__esModule=!0,b.convertChangesToXML=c}])});
\ No newline at end of file
diff --git a/node_modules/diff/lib/convert/dmp.js b/node_modules/diff/lib/convert/dmp.js
new file mode 100644
index 0000000..b9b646f
--- /dev/null
+++ b/node_modules/diff/lib/convert/dmp.js
@@ -0,0 +1,24 @@
+/*istanbul ignore start*/"use strict";
+
+exports.__esModule = true;
+exports. /*istanbul ignore end*/convertChangesToDMP = convertChangesToDMP;
+// See: http://code.google.com/p/google-diff-match-patch/wiki/API
+function convertChangesToDMP(changes) {
+  var ret = [],
+      change = /*istanbul ignore start*/void 0 /*istanbul ignore end*/,
+      operation = /*istanbul ignore start*/void 0 /*istanbul ignore end*/;
+  for (var i = 0; i < changes.length; i++) {
+    change = changes[i];
+    if (change.added) {
+      operation = 1;
+    } else if (change.removed) {
+      operation = -1;
+    } else {
+      operation = 0;
+    }
+
+    ret.push([operation, change.value]);
+  }
+  return ret;
+}
+//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9jb252ZXJ0L2RtcC5qcyJdLCJuYW1lcyI6WyJjb252ZXJ0Q2hhbmdlc1RvRE1QIiwiY2hhbmdlcyIsInJldCIsImNoYW5nZSIsIm9wZXJhdGlvbiIsImkiLCJsZW5ndGgiLCJhZGRlZCIsInJlbW92ZWQiLCJwdXNoIiwidmFsdWUiXSwibWFwcGluZ3MiOiI7OztnQ0FDZ0JBLG1CLEdBQUFBLG1CO0FBRGhCO0FBQ08sU0FBU0EsbUJBQVQsQ0FBNkJDLE9BQTdCLEVBQXNDO0FBQzNDLE1BQUlDLE1BQU0sRUFBVjtBQUFBLE1BQ0lDLHdDQURKO0FBQUEsTUFFSUMsMkNBRko7QUFHQSxPQUFLLElBQUlDLElBQUksQ0FBYixFQUFnQkEsSUFBSUosUUFBUUssTUFBNUIsRUFBb0NELEdBQXBDLEVBQXlDO0FBQ3ZDRixhQUFTRixRQUFRSSxDQUFSLENBQVQ7QUFDQSxRQUFJRixPQUFPSSxLQUFYLEVBQWtCO0FBQ2hCSCxrQkFBWSxDQUFaO0FBQ0QsS0FGRCxNQUVPLElBQUlELE9BQU9LLE9BQVgsRUFBb0I7QUFDekJKLGtCQUFZLENBQUMsQ0FBYjtBQUNELEtBRk0sTUFFQTtBQUNMQSxrQkFBWSxDQUFaO0FBQ0Q7O0FBRURGLFFBQUlPLElBQUosQ0FBUyxDQUFDTCxTQUFELEVBQVlELE9BQU9PLEtBQW5CLENBQVQ7QUFDRDtBQUNELFNBQU9SLEdBQVA7QUFDRCIsImZpbGUiOiJkbXAuanMiLCJzb3VyY2VzQ29udGVudCI6WyIvLyBTZWU6IGh0dHA6Ly9jb2RlLmdvb2dsZS5jb20vcC9nb29nbGUtZGlmZi1tYXRjaC1wYXRjaC93aWtpL0FQSVxuZXhwb3J0IGZ1bmN0aW9uIGNvbnZlcnRDaGFuZ2VzVG9ETVAoY2hhbmdlcykge1xuICBsZXQgcmV0ID0gW10sXG4gICAgICBjaGFuZ2UsXG4gICAgICBvcGVyYXRpb247XG4gIGZvciAobGV0IGkgPSAwOyBpIDwgY2hhbmdlcy5sZW5ndGg7IGkrKykge1xuICAgIGNoYW5nZSA9IGNoYW5nZXNbaV07XG4gICAgaWYgKGNoYW5nZS5hZGRlZCkge1xuICAgICAgb3BlcmF0aW9uID0gMTtcbiAgICB9IGVsc2UgaWYgKGNoYW5nZS5yZW1vdmVkKSB7XG4gICAgICBvcGVyYXRpb24gPSAtMTtcbiAgICB9IGVsc2Uge1xuICAgICAgb3BlcmF0aW9uID0gMDtcbiAgICB9XG5cbiAgICByZXQucHVzaChbb3BlcmF0aW9uLCBjaGFuZ2UudmFsdWVdKTtcbiAgfVxuICByZXR1cm4gcmV0O1xufVxuIl19
diff --git a/node_modules/diff/lib/convert/xml.js b/node_modules/diff/lib/convert/xml.js
new file mode 100644
index 0000000..331827a
--- /dev/null
+++ b/node_modules/diff/lib/convert/xml.js
@@ -0,0 +1,35 @@
+/*istanbul ignore start*/'use strict';
+
+exports.__esModule = true;
+exports. /*istanbul ignore end*/convertChangesToXML = convertChangesToXML;
+function convertChangesToXML(changes) {
+  var ret = [];
+  for (var i = 0; i < changes.length; i++) {
+    var change = changes[i];
+    if (change.added) {
+      ret.push('');
+    } else if (change.removed) {
+      ret.push('');
+    }
+
+    ret.push(escapeHTML(change.value));
+
+    if (change.added) {
+      ret.push('');
+    } else if (change.removed) {
+      ret.push('');
+    }
+  }
+  return ret.join('');
+}
+
+function escapeHTML(s) {
+  var n = s;
+  n = n.replace(/&/g, '&');
+  n = n.replace(//g, '>');
+  n = n.replace(/"/g, '"');
+
+  return n;
+}
+//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9jb252ZXJ0L3htbC5qcyJdLCJuYW1lcyI6WyJjb252ZXJ0Q2hhbmdlc1RvWE1MIiwiY2hhbmdlcyIsInJldCIsImkiLCJsZW5ndGgiLCJjaGFuZ2UiLCJhZGRlZCIsInB1c2giLCJyZW1vdmVkIiwiZXNjYXBlSFRNTCIsInZhbHVlIiwiam9pbiIsInMiLCJuIiwicmVwbGFjZSJdLCJtYXBwaW5ncyI6Ijs7O2dDQUFnQkEsbUIsR0FBQUEsbUI7QUFBVCxTQUFTQSxtQkFBVCxDQUE2QkMsT0FBN0IsRUFBc0M7QUFDM0MsTUFBSUMsTUFBTSxFQUFWO0FBQ0EsT0FBSyxJQUFJQyxJQUFJLENBQWIsRUFBZ0JBLElBQUlGLFFBQVFHLE1BQTVCLEVBQW9DRCxHQUFwQyxFQUF5QztBQUN2QyxRQUFJRSxTQUFTSixRQUFRRSxDQUFSLENBQWI7QUFDQSxRQUFJRSxPQUFPQyxLQUFYLEVBQWtCO0FBQ2hCSixVQUFJSyxJQUFKLENBQVMsT0FBVDtBQUNELEtBRkQsTUFFTyxJQUFJRixPQUFPRyxPQUFYLEVBQW9CO0FBQ3pCTixVQUFJSyxJQUFKLENBQVMsT0FBVDtBQUNEOztBQUVETCxRQUFJSyxJQUFKLENBQVNFLFdBQVdKLE9BQU9LLEtBQWxCLENBQVQ7O0FBRUEsUUFBSUwsT0FBT0MsS0FBWCxFQUFrQjtBQUNoQkosVUFBSUssSUFBSixDQUFTLFFBQVQ7QUFDRCxLQUZELE1BRU8sSUFBSUYsT0FBT0csT0FBWCxFQUFvQjtBQUN6Qk4sVUFBSUssSUFBSixDQUFTLFFBQVQ7QUFDRDtBQUNGO0FBQ0QsU0FBT0wsSUFBSVMsSUFBSixDQUFTLEVBQVQsQ0FBUDtBQUNEOztBQUVELFNBQVNGLFVBQVQsQ0FBb0JHLENBQXBCLEVBQXVCO0FBQ3JCLE1BQUlDLElBQUlELENBQVI7QUFDQUMsTUFBSUEsRUFBRUMsT0FBRixDQUFVLElBQVYsRUFBZ0IsT0FBaEIsQ0FBSjtBQUNBRCxNQUFJQSxFQUFFQyxPQUFGLENBQVUsSUFBVixFQUFnQixNQUFoQixDQUFKO0FBQ0FELE1BQUlBLEVBQUVDLE9BQUYsQ0FBVSxJQUFWLEVBQWdCLE1BQWhCLENBQUo7QUFDQUQsTUFBSUEsRUFBRUMsT0FBRixDQUFVLElBQVYsRUFBZ0IsUUFBaEIsQ0FBSjs7QUFFQSxTQUFPRCxDQUFQO0FBQ0QiLCJmaWxlIjoieG1sLmpzIiwic291cmNlc0NvbnRlbnQiOlsiZXhwb3J0IGZ1bmN0aW9uIGNvbnZlcnRDaGFuZ2VzVG9YTUwoY2hhbmdlcykge1xuICBsZXQgcmV0ID0gW107XG4gIGZvciAobGV0IGkgPSAwOyBpIDwgY2hhbmdlcy5sZW5ndGg7IGkrKykge1xuICAgIGxldCBjaGFuZ2UgPSBjaGFuZ2VzW2ldO1xuICAgIGlmIChjaGFuZ2UuYWRkZWQpIHtcbiAgICAgIHJldC5wdXNoKCc8aW5zPicpO1xuICAgIH0gZWxzZSBpZiAoY2hhbmdlLnJlbW92ZWQpIHtcbiAgICAgIHJldC5wdXNoKCc8ZGVsPicpO1xuICAgIH1cblxuICAgIHJldC5wdXNoKGVzY2FwZUhUTUwoY2hhbmdlLnZhbHVlKSk7XG5cbiAgICBpZiAoY2hhbmdlLmFkZGVkKSB7XG4gICAgICByZXQucHVzaCgnPC9pbnM+Jyk7XG4gICAgfSBlbHNlIGlmIChjaGFuZ2UucmVtb3ZlZCkge1xuICAgICAgcmV0LnB1c2goJzwvZGVsPicpO1xuICAgIH1cbiAgfVxuICByZXR1cm4gcmV0LmpvaW4oJycpO1xufVxuXG5mdW5jdGlvbiBlc2NhcGVIVE1MKHMpIHtcbiAgbGV0IG4gPSBzO1xuICBuID0gbi5yZXBsYWNlKC8mL2csICcmYW1wOycpO1xuICBuID0gbi5yZXBsYWNlKC88L2csICcmbHQ7Jyk7XG4gIG4gPSBuLnJlcGxhY2UoLz4vZywgJyZndDsnKTtcbiAgbiA9IG4ucmVwbGFjZSgvXCIvZywgJyZxdW90OycpO1xuXG4gIHJldHVybiBuO1xufVxuIl19
diff --git a/node_modules/diff/lib/diff/array.js b/node_modules/diff/lib/diff/array.js
new file mode 100644
index 0000000..f3daa4e
--- /dev/null
+++ b/node_modules/diff/lib/diff/array.js
@@ -0,0 +1,24 @@
+/*istanbul ignore start*/'use strict';
+
+exports.__esModule = true;
+exports.arrayDiff = undefined;
+exports. /*istanbul ignore end*/diffArrays = diffArrays;
+
+var /*istanbul ignore start*/_base = require('./base') /*istanbul ignore end*/;
+
+/*istanbul ignore start*/var _base2 = _interopRequireDefault(_base);
+
+function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
+
+/*istanbul ignore end*/var arrayDiff = /*istanbul ignore start*/exports. /*istanbul ignore end*/arrayDiff = new /*istanbul ignore start*/_base2['default'] /*istanbul ignore end*/();
+arrayDiff.tokenize = function (value) {
+  return value.slice();
+};
+arrayDiff.join = arrayDiff.removeEmpty = function (value) {
+  return value;
+};
+
+function diffArrays(oldArr, newArr, callback) {
+  return arrayDiff.diff(oldArr, newArr, callback);
+}
+//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9kaWZmL2FycmF5LmpzIl0sIm5hbWVzIjpbImRpZmZBcnJheXMiLCJhcnJheURpZmYiLCJ0b2tlbml6ZSIsInZhbHVlIiwic2xpY2UiLCJqb2luIiwicmVtb3ZlRW1wdHkiLCJvbGRBcnIiLCJuZXdBcnIiLCJjYWxsYmFjayIsImRpZmYiXSwibWFwcGluZ3MiOiI7Ozs7Z0NBVWdCQSxVLEdBQUFBLFU7O0FBVmhCOzs7Ozs7dUJBRU8sSUFBTUMsaUZBQVksd0VBQWxCO0FBQ1BBLFVBQVVDLFFBQVYsR0FBcUIsVUFBU0MsS0FBVCxFQUFnQjtBQUNuQyxTQUFPQSxNQUFNQyxLQUFOLEVBQVA7QUFDRCxDQUZEO0FBR0FILFVBQVVJLElBQVYsR0FBaUJKLFVBQVVLLFdBQVYsR0FBd0IsVUFBU0gsS0FBVCxFQUFnQjtBQUN2RCxTQUFPQSxLQUFQO0FBQ0QsQ0FGRDs7QUFJTyxTQUFTSCxVQUFULENBQW9CTyxNQUFwQixFQUE0QkMsTUFBNUIsRUFBb0NDLFFBQXBDLEVBQThDO0FBQUUsU0FBT1IsVUFBVVMsSUFBVixDQUFlSCxNQUFmLEVBQXVCQyxNQUF2QixFQUErQkMsUUFBL0IsQ0FBUDtBQUFrRCIsImZpbGUiOiJhcnJheS5qcyIsInNvdXJjZXNDb250ZW50IjpbImltcG9ydCBEaWZmIGZyb20gJy4vYmFzZSc7XG5cbmV4cG9ydCBjb25zdCBhcnJheURpZmYgPSBuZXcgRGlmZigpO1xuYXJyYXlEaWZmLnRva2VuaXplID0gZnVuY3Rpb24odmFsdWUpIHtcbiAgcmV0dXJuIHZhbHVlLnNsaWNlKCk7XG59O1xuYXJyYXlEaWZmLmpvaW4gPSBhcnJheURpZmYucmVtb3ZlRW1wdHkgPSBmdW5jdGlvbih2YWx1ZSkge1xuICByZXR1cm4gdmFsdWU7XG59O1xuXG5leHBvcnQgZnVuY3Rpb24gZGlmZkFycmF5cyhvbGRBcnIsIG5ld0FyciwgY2FsbGJhY2spIHsgcmV0dXJuIGFycmF5RGlmZi5kaWZmKG9sZEFyciwgbmV3QXJyLCBjYWxsYmFjayk7IH1cbiJdfQ==
diff --git a/node_modules/diff/lib/diff/base.js b/node_modules/diff/lib/diff/base.js
new file mode 100644
index 0000000..763daec
--- /dev/null
+++ b/node_modules/diff/lib/diff/base.js
@@ -0,0 +1,235 @@
+/*istanbul ignore start*/'use strict';
+
+exports.__esModule = true;
+exports['default'] = /*istanbul ignore end*/Diff;
+function Diff() {}
+
+Diff.prototype = {
+  /*istanbul ignore start*/ /*istanbul ignore end*/diff: function diff(oldString, newString) {
+    /*istanbul ignore start*/var /*istanbul ignore end*/options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
+
+    var callback = options.callback;
+    if (typeof options === 'function') {
+      callback = options;
+      options = {};
+    }
+    this.options = options;
+
+    var self = this;
+
+    function done(value) {
+      if (callback) {
+        setTimeout(function () {
+          callback(undefined, value);
+        }, 0);
+        return true;
+      } else {
+        return value;
+      }
+    }
+
+    // Allow subclasses to massage the input prior to running
+    oldString = this.castInput(oldString);
+    newString = this.castInput(newString);
+
+    oldString = this.removeEmpty(this.tokenize(oldString));
+    newString = this.removeEmpty(this.tokenize(newString));
+
+    var newLen = newString.length,
+        oldLen = oldString.length;
+    var editLength = 1;
+    var maxEditLength = newLen + oldLen;
+    var bestPath = [{ newPos: -1, components: [] }];
+
+    // Seed editLength = 0, i.e. the content starts with the same values
+    var oldPos = this.extractCommon(bestPath[0], newString, oldString, 0);
+    if (bestPath[0].newPos + 1 >= newLen && oldPos + 1 >= oldLen) {
+      // Identity per the equality and tokenizer
+      return done([{ value: this.join(newString), count: newString.length }]);
+    }
+
+    // Main worker method. checks all permutations of a given edit length for acceptance.
+    function execEditLength() {
+      for (var diagonalPath = -1 * editLength; diagonalPath <= editLength; diagonalPath += 2) {
+        var basePath = /*istanbul ignore start*/void 0 /*istanbul ignore end*/;
+        var addPath = bestPath[diagonalPath - 1],
+            removePath = bestPath[diagonalPath + 1],
+            _oldPos = (removePath ? removePath.newPos : 0) - diagonalPath;
+        if (addPath) {
+          // No one else is going to attempt to use this value, clear it
+          bestPath[diagonalPath - 1] = undefined;
+        }
+
+        var canAdd = addPath && addPath.newPos + 1 < newLen,
+            canRemove = removePath && 0 <= _oldPos && _oldPos < oldLen;
+        if (!canAdd && !canRemove) {
+          // If this path is a terminal then prune
+          bestPath[diagonalPath] = undefined;
+          continue;
+        }
+
+        // Select the diagonal that we want to branch from. We select the prior
+        // path whose position in the new string is the farthest from the origin
+        // and does not pass the bounds of the diff graph
+        if (!canAdd || canRemove && addPath.newPos < removePath.newPos) {
+          basePath = clonePath(removePath);
+          self.pushComponent(basePath.components, undefined, true);
+        } else {
+          basePath = addPath; // No need to clone, we've pulled it from the list
+          basePath.newPos++;
+          self.pushComponent(basePath.components, true, undefined);
+        }
+
+        _oldPos = self.extractCommon(basePath, newString, oldString, diagonalPath);
+
+        // If we have hit the end of both strings, then we are done
+        if (basePath.newPos + 1 >= newLen && _oldPos + 1 >= oldLen) {
+          return done(buildValues(self, basePath.components, newString, oldString, self.useLongestToken));
+        } else {
+          // Otherwise track this path as a potential candidate and continue.
+          bestPath[diagonalPath] = basePath;
+        }
+      }
+
+      editLength++;
+    }
+
+    // Performs the length of edit iteration. Is a bit fugly as this has to support the
+    // sync and async mode which is never fun. Loops over execEditLength until a value
+    // is produced.
+    if (callback) {
+      (function exec() {
+        setTimeout(function () {
+          // This should not happen, but we want to be safe.
+          /* istanbul ignore next */
+          if (editLength > maxEditLength) {
+            return callback();
+          }
+
+          if (!execEditLength()) {
+            exec();
+          }
+        }, 0);
+      })();
+    } else {
+      while (editLength <= maxEditLength) {
+        var ret = execEditLength();
+        if (ret) {
+          return ret;
+        }
+      }
+    }
+  },
+  /*istanbul ignore start*/ /*istanbul ignore end*/pushComponent: function pushComponent(components, added, removed) {
+    var last = components[components.length - 1];
+    if (last && last.added === added && last.removed === removed) {
+      // We need to clone here as the component clone operation is just
+      // as shallow array clone
+      components[components.length - 1] = { count: last.count + 1, added: added, removed: removed };
+    } else {
+      components.push({ count: 1, added: added, removed: removed });
+    }
+  },
+  /*istanbul ignore start*/ /*istanbul ignore end*/extractCommon: function extractCommon(basePath, newString, oldString, diagonalPath) {
+    var newLen = newString.length,
+        oldLen = oldString.length,
+        newPos = basePath.newPos,
+        oldPos = newPos - diagonalPath,
+        commonCount = 0;
+    while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(newString[newPos + 1], oldString[oldPos + 1])) {
+      newPos++;
+      oldPos++;
+      commonCount++;
+    }
+
+    if (commonCount) {
+      basePath.components.push({ count: commonCount });
+    }
+
+    basePath.newPos = newPos;
+    return oldPos;
+  },
+  /*istanbul ignore start*/ /*istanbul ignore end*/equals: function equals(left, right) {
+    if (this.options.comparator) {
+      return this.options.comparator(left, right);
+    } else {
+      return left === right || this.options.ignoreCase && left.toLowerCase() === right.toLowerCase();
+    }
+  },
+  /*istanbul ignore start*/ /*istanbul ignore end*/removeEmpty: function removeEmpty(array) {
+    var ret = [];
+    for (var i = 0; i < array.length; i++) {
+      if (array[i]) {
+        ret.push(array[i]);
+      }
+    }
+    return ret;
+  },
+  /*istanbul ignore start*/ /*istanbul ignore end*/castInput: function castInput(value) {
+    return value;
+  },
+  /*istanbul ignore start*/ /*istanbul ignore end*/tokenize: function tokenize(value) {
+    return value.split('');
+  },
+  /*istanbul ignore start*/ /*istanbul ignore end*/join: function join(chars) {
+    return chars.join('');
+  }
+};
+
+function buildValues(diff, components, newString, oldString, useLongestToken) {
+  var componentPos = 0,
+      componentLen = components.length,
+      newPos = 0,
+      oldPos = 0;
+
+  for (; componentPos < componentLen; componentPos++) {
+    var component = components[componentPos];
+    if (!component.removed) {
+      if (!component.added && useLongestToken) {
+        var value = newString.slice(newPos, newPos + component.count);
+        value = value.map(function (value, i) {
+          var oldValue = oldString[oldPos + i];
+          return oldValue.length > value.length ? oldValue : value;
+        });
+
+        component.value = diff.join(value);
+      } else {
+        component.value = diff.join(newString.slice(newPos, newPos + component.count));
+      }
+      newPos += component.count;
+
+      // Common case
+      if (!component.added) {
+        oldPos += component.count;
+      }
+    } else {
+      component.value = diff.join(oldString.slice(oldPos, oldPos + component.count));
+      oldPos += component.count;
+
+      // Reverse add and remove so removes are output first to match common convention
+      // The diffing algorithm is tied to add then remove output and this is the simplest
+      // route to get the desired output with minimal overhead.
+      if (componentPos && components[componentPos - 1].added) {
+        var tmp = components[componentPos - 1];
+        components[componentPos - 1] = components[componentPos];
+        components[componentPos] = tmp;
+      }
+    }
+  }
+
+  // Special case handle for when one terminal is ignored (i.e. whitespace).
+  // For this case we merge the terminal into the prior string and drop the change.
+  // This is only available for string mode.
+  var lastComponent = components[componentLen - 1];
+  if (componentLen > 1 && typeof lastComponent.value === 'string' && (lastComponent.added || lastComponent.removed) && diff.equals('', lastComponent.value)) {
+    components[componentLen - 2].value += lastComponent.value;
+    components.pop();
+  }
+
+  return components;
+}
+
+function clonePath(path) {
+  return { newPos: path.newPos, components: path.components.slice(0) };
+}
+//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9kaWZmL2Jhc2UuanMiXSwibmFtZXMiOlsiRGlmZiIsInByb3RvdHlwZSIsImRpZmYiLCJvbGRTdHJpbmciLCJuZXdTdHJpbmciLCJvcHRpb25zIiwiY2FsbGJhY2siLCJzZWxmIiwiZG9uZSIsInZhbHVlIiwic2V0VGltZW91dCIsInVuZGVmaW5lZCIsImNhc3RJbnB1dCIsInJlbW92ZUVtcHR5IiwidG9rZW5pemUiLCJuZXdMZW4iLCJsZW5ndGgiLCJvbGRMZW4iLCJlZGl0TGVuZ3RoIiwibWF4RWRpdExlbmd0aCIsImJlc3RQYXRoIiwibmV3UG9zIiwiY29tcG9uZW50cyIsIm9sZFBvcyIsImV4dHJhY3RDb21tb24iLCJqb2luIiwiY291bnQiLCJleGVjRWRpdExlbmd0aCIsImRpYWdvbmFsUGF0aCIsImJhc2VQYXRoIiwiYWRkUGF0aCIsInJlbW92ZVBhdGgiLCJjYW5BZGQiLCJjYW5SZW1vdmUiLCJjbG9uZVBhdGgiLCJwdXNoQ29tcG9uZW50IiwiYnVpbGRWYWx1ZXMiLCJ1c2VMb25nZXN0VG9rZW4iLCJleGVjIiwicmV0IiwiYWRkZWQiLCJyZW1vdmVkIiwibGFzdCIsInB1c2giLCJjb21tb25Db3VudCIsImVxdWFscyIsImxlZnQiLCJyaWdodCIsImNvbXBhcmF0b3IiLCJpZ25vcmVDYXNlIiwidG9Mb3dlckNhc2UiLCJhcnJheSIsImkiLCJzcGxpdCIsImNoYXJzIiwiY29tcG9uZW50UG9zIiwiY29tcG9uZW50TGVuIiwiY29tcG9uZW50Iiwic2xpY2UiLCJtYXAiLCJvbGRWYWx1ZSIsInRtcCIsImxhc3RDb21wb25lbnQiLCJwb3AiLCJwYXRoIl0sIm1hcHBpbmdzIjoiOzs7NENBQXdCQSxJO0FBQVQsU0FBU0EsSUFBVCxHQUFnQixDQUFFOztBQUVqQ0EsS0FBS0MsU0FBTCxHQUFpQjtBQUFBLG1EQUNmQyxJQURlLGdCQUNWQyxTQURVLEVBQ0NDLFNBREQsRUFDMEI7QUFBQSx3REFBZEMsT0FBYyx1RUFBSixFQUFJOztBQUN2QyxRQUFJQyxXQUFXRCxRQUFRQyxRQUF2QjtBQUNBLFFBQUksT0FBT0QsT0FBUCxLQUFtQixVQUF2QixFQUFtQztBQUNqQ0MsaUJBQVdELE9BQVg7QUFDQUEsZ0JBQVUsRUFBVjtBQUNEO0FBQ0QsU0FBS0EsT0FBTCxHQUFlQSxPQUFmOztBQUVBLFFBQUlFLE9BQU8sSUFBWDs7QUFFQSxhQUFTQyxJQUFULENBQWNDLEtBQWQsRUFBcUI7QUFDbkIsVUFBSUgsUUFBSixFQUFjO0FBQ1pJLG1CQUFXLFlBQVc7QUFBRUosbUJBQVNLLFNBQVQsRUFBb0JGLEtBQXBCO0FBQTZCLFNBQXJELEVBQXVELENBQXZEO0FBQ0EsZUFBTyxJQUFQO0FBQ0QsT0FIRCxNQUdPO0FBQ0wsZUFBT0EsS0FBUDtBQUNEO0FBQ0Y7O0FBRUQ7QUFDQU4sZ0JBQVksS0FBS1MsU0FBTCxDQUFlVCxTQUFmLENBQVo7QUFDQUMsZ0JBQVksS0FBS1EsU0FBTCxDQUFlUixTQUFmLENBQVo7O0FBRUFELGdCQUFZLEtBQUtVLFdBQUwsQ0FBaUIsS0FBS0MsUUFBTCxDQUFjWCxTQUFkLENBQWpCLENBQVo7QUFDQUMsZ0JBQVksS0FBS1MsV0FBTCxDQUFpQixLQUFLQyxRQUFMLENBQWNWLFNBQWQsQ0FBakIsQ0FBWjs7QUFFQSxRQUFJVyxTQUFTWCxVQUFVWSxNQUF2QjtBQUFBLFFBQStCQyxTQUFTZCxVQUFVYSxNQUFsRDtBQUNBLFFBQUlFLGFBQWEsQ0FBakI7QUFDQSxRQUFJQyxnQkFBZ0JKLFNBQVNFLE1BQTdCO0FBQ0EsUUFBSUcsV0FBVyxDQUFDLEVBQUVDLFFBQVEsQ0FBQyxDQUFYLEVBQWNDLFlBQVksRUFBMUIsRUFBRCxDQUFmOztBQUVBO0FBQ0EsUUFBSUMsU0FBUyxLQUFLQyxhQUFMLENBQW1CSixTQUFTLENBQVQsQ0FBbkIsRUFBZ0NoQixTQUFoQyxFQUEyQ0QsU0FBM0MsRUFBc0QsQ0FBdEQsQ0FBYjtBQUNBLFFBQUlpQixTQUFTLENBQVQsRUFBWUMsTUFBWixHQUFxQixDQUFyQixJQUEwQk4sTUFBMUIsSUFBb0NRLFNBQVMsQ0FBVCxJQUFjTixNQUF0RCxFQUE4RDtBQUM1RDtBQUNBLGFBQU9ULEtBQUssQ0FBQyxFQUFDQyxPQUFPLEtBQUtnQixJQUFMLENBQVVyQixTQUFWLENBQVIsRUFBOEJzQixPQUFPdEIsVUFBVVksTUFBL0MsRUFBRCxDQUFMLENBQVA7QUFDRDs7QUFFRDtBQUNBLGFBQVNXLGNBQVQsR0FBMEI7QUFDeEIsV0FBSyxJQUFJQyxlQUFlLENBQUMsQ0FBRCxHQUFLVixVQUE3QixFQUF5Q1UsZ0JBQWdCVixVQUF6RCxFQUFxRVUsZ0JBQWdCLENBQXJGLEVBQXdGO0FBQ3RGLFlBQUlDLDBDQUFKO0FBQ0EsWUFBSUMsVUFBVVYsU0FBU1EsZUFBZSxDQUF4QixDQUFkO0FBQUEsWUFDSUcsYUFBYVgsU0FBU1EsZUFBZSxDQUF4QixDQURqQjtBQUFBLFlBRUlMLFVBQVMsQ0FBQ1EsYUFBYUEsV0FBV1YsTUFBeEIsR0FBaUMsQ0FBbEMsSUFBdUNPLFlBRnBEO0FBR0EsWUFBSUUsT0FBSixFQUFhO0FBQ1g7QUFDQVYsbUJBQVNRLGVBQWUsQ0FBeEIsSUFBNkJqQixTQUE3QjtBQUNEOztBQUVELFlBQUlxQixTQUFTRixXQUFXQSxRQUFRVCxNQUFSLEdBQWlCLENBQWpCLEdBQXFCTixNQUE3QztBQUFBLFlBQ0lrQixZQUFZRixjQUFjLEtBQUtSLE9BQW5CLElBQTZCQSxVQUFTTixNQUR0RDtBQUVBLFlBQUksQ0FBQ2UsTUFBRCxJQUFXLENBQUNDLFNBQWhCLEVBQTJCO0FBQ3pCO0FBQ0FiLG1CQUFTUSxZQUFULElBQXlCakIsU0FBekI7QUFDQTtBQUNEOztBQUVEO0FBQ0E7QUFDQTtBQUNBLFlBQUksQ0FBQ3FCLE1BQUQsSUFBWUMsYUFBYUgsUUFBUVQsTUFBUixHQUFpQlUsV0FBV1YsTUFBekQsRUFBa0U7QUFDaEVRLHFCQUFXSyxVQUFVSCxVQUFWLENBQVg7QUFDQXhCLGVBQUs0QixhQUFMLENBQW1CTixTQUFTUCxVQUE1QixFQUF3Q1gsU0FBeEMsRUFBbUQsSUFBbkQ7QUFDRCxTQUhELE1BR087QUFDTGtCLHFCQUFXQyxPQUFYLENBREssQ0FDaUI7QUFDdEJELG1CQUFTUixNQUFUO0FBQ0FkLGVBQUs0QixhQUFMLENBQW1CTixTQUFTUCxVQUE1QixFQUF3QyxJQUF4QyxFQUE4Q1gsU0FBOUM7QUFDRDs7QUFFRFksa0JBQVNoQixLQUFLaUIsYUFBTCxDQUFtQkssUUFBbkIsRUFBNkJ6QixTQUE3QixFQUF3Q0QsU0FBeEMsRUFBbUR5QixZQUFuRCxDQUFUOztBQUVBO0FBQ0EsWUFBSUMsU0FBU1IsTUFBVCxHQUFrQixDQUFsQixJQUF1Qk4sTUFBdkIsSUFBaUNRLFVBQVMsQ0FBVCxJQUFjTixNQUFuRCxFQUEyRDtBQUN6RCxpQkFBT1QsS0FBSzRCLFlBQVk3QixJQUFaLEVBQWtCc0IsU0FBU1AsVUFBM0IsRUFBdUNsQixTQUF2QyxFQUFrREQsU0FBbEQsRUFBNkRJLEtBQUs4QixlQUFsRSxDQUFMLENBQVA7QUFDRCxTQUZELE1BRU87QUFDTDtBQUNBakIsbUJBQVNRLFlBQVQsSUFBeUJDLFFBQXpCO0FBQ0Q7QUFDRjs7QUFFRFg7QUFDRDs7QUFFRDtBQUNBO0FBQ0E7QUFDQSxRQUFJWixRQUFKLEVBQWM7QUFDWCxnQkFBU2dDLElBQVQsR0FBZ0I7QUFDZjVCLG1CQUFXLFlBQVc7QUFDcEI7QUFDQTtBQUNBLGNBQUlRLGFBQWFDLGFBQWpCLEVBQWdDO0FBQzlCLG1CQUFPYixVQUFQO0FBQ0Q7O0FBRUQsY0FBSSxDQUFDcUIsZ0JBQUwsRUFBdUI7QUFDckJXO0FBQ0Q7QUFDRixTQVZELEVBVUcsQ0FWSDtBQVdELE9BWkEsR0FBRDtBQWFELEtBZEQsTUFjTztBQUNMLGFBQU9wQixjQUFjQyxhQUFyQixFQUFvQztBQUNsQyxZQUFJb0IsTUFBTVosZ0JBQVY7QUFDQSxZQUFJWSxHQUFKLEVBQVM7QUFDUCxpQkFBT0EsR0FBUDtBQUNEO0FBQ0Y7QUFDRjtBQUNGLEdBOUdjO0FBQUEsbURBZ0hmSixhQWhIZSx5QkFnSERiLFVBaEhDLEVBZ0hXa0IsS0FoSFgsRUFnSGtCQyxPQWhIbEIsRUFnSDJCO0FBQ3hDLFFBQUlDLE9BQU9wQixXQUFXQSxXQUFXTixNQUFYLEdBQW9CLENBQS9CLENBQVg7QUFDQSxRQUFJMEIsUUFBUUEsS0FBS0YsS0FBTCxLQUFlQSxLQUF2QixJQUFnQ0UsS0FBS0QsT0FBTCxLQUFpQkEsT0FBckQsRUFBOEQ7QUFDNUQ7QUFDQTtBQUNBbkIsaUJBQVdBLFdBQVdOLE1BQVgsR0FBb0IsQ0FBL0IsSUFBb0MsRUFBQ1UsT0FBT2dCLEtBQUtoQixLQUFMLEdBQWEsQ0FBckIsRUFBd0JjLE9BQU9BLEtBQS9CLEVBQXNDQyxTQUFTQSxPQUEvQyxFQUFwQztBQUNELEtBSkQsTUFJTztBQUNMbkIsaUJBQVdxQixJQUFYLENBQWdCLEVBQUNqQixPQUFPLENBQVIsRUFBV2MsT0FBT0EsS0FBbEIsRUFBeUJDLFNBQVNBLE9BQWxDLEVBQWhCO0FBQ0Q7QUFDRixHQXpIYztBQUFBLG1EQTBIZmpCLGFBMUhlLHlCQTBIREssUUExSEMsRUEwSFN6QixTQTFIVCxFQTBIb0JELFNBMUhwQixFQTBIK0J5QixZQTFIL0IsRUEwSDZDO0FBQzFELFFBQUliLFNBQVNYLFVBQVVZLE1BQXZCO0FBQUEsUUFDSUMsU0FBU2QsVUFBVWEsTUFEdkI7QUFBQSxRQUVJSyxTQUFTUSxTQUFTUixNQUZ0QjtBQUFBLFFBR0lFLFNBQVNGLFNBQVNPLFlBSHRCO0FBQUEsUUFLSWdCLGNBQWMsQ0FMbEI7QUFNQSxXQUFPdkIsU0FBUyxDQUFULEdBQWFOLE1BQWIsSUFBdUJRLFNBQVMsQ0FBVCxHQUFhTixNQUFwQyxJQUE4QyxLQUFLNEIsTUFBTCxDQUFZekMsVUFBVWlCLFNBQVMsQ0FBbkIsQ0FBWixFQUFtQ2xCLFVBQVVvQixTQUFTLENBQW5CLENBQW5DLENBQXJELEVBQWdIO0FBQzlHRjtBQUNBRTtBQUNBcUI7QUFDRDs7QUFFRCxRQUFJQSxXQUFKLEVBQWlCO0FBQ2ZmLGVBQVNQLFVBQVQsQ0FBb0JxQixJQUFwQixDQUF5QixFQUFDakIsT0FBT2tCLFdBQVIsRUFBekI7QUFDRDs7QUFFRGYsYUFBU1IsTUFBVCxHQUFrQkEsTUFBbEI7QUFDQSxXQUFPRSxNQUFQO0FBQ0QsR0E3SWM7QUFBQSxtREErSWZzQixNQS9JZSxrQkErSVJDLElBL0lRLEVBK0lGQyxLQS9JRSxFQStJSztBQUNsQixRQUFJLEtBQUsxQyxPQUFMLENBQWEyQyxVQUFqQixFQUE2QjtBQUMzQixhQUFPLEtBQUszQyxPQUFMLENBQWEyQyxVQUFiLENBQXdCRixJQUF4QixFQUE4QkMsS0FBOUIsQ0FBUDtBQUNELEtBRkQsTUFFTztBQUNMLGFBQU9ELFNBQVNDLEtBQVQsSUFDRCxLQUFLMUMsT0FBTCxDQUFhNEMsVUFBYixJQUEyQkgsS0FBS0ksV0FBTCxPQUF1QkgsTUFBTUcsV0FBTixFQUR4RDtBQUVEO0FBQ0YsR0F0SmM7QUFBQSxtREF1SmZyQyxXQXZKZSx1QkF1SkhzQyxLQXZKRyxFQXVKSTtBQUNqQixRQUFJWixNQUFNLEVBQVY7QUFDQSxTQUFLLElBQUlhLElBQUksQ0FBYixFQUFnQkEsSUFBSUQsTUFBTW5DLE1BQTFCLEVBQWtDb0MsR0FBbEMsRUFBdUM7QUFDckMsVUFBSUQsTUFBTUMsQ0FBTixDQUFKLEVBQWM7QUFDWmIsWUFBSUksSUFBSixDQUFTUSxNQUFNQyxDQUFOLENBQVQ7QUFDRDtBQUNGO0FBQ0QsV0FBT2IsR0FBUDtBQUNELEdBL0pjO0FBQUEsbURBZ0tmM0IsU0FoS2UscUJBZ0tMSCxLQWhLSyxFQWdLRTtBQUNmLFdBQU9BLEtBQVA7QUFDRCxHQWxLYztBQUFBLG1EQW1LZkssUUFuS2Usb0JBbUtOTCxLQW5LTSxFQW1LQztBQUNkLFdBQU9BLE1BQU00QyxLQUFOLENBQVksRUFBWixDQUFQO0FBQ0QsR0FyS2M7QUFBQSxtREFzS2Y1QixJQXRLZSxnQkFzS1Y2QixLQXRLVSxFQXNLSDtBQUNWLFdBQU9BLE1BQU03QixJQUFOLENBQVcsRUFBWCxDQUFQO0FBQ0Q7QUF4S2MsQ0FBakI7O0FBMktBLFNBQVNXLFdBQVQsQ0FBcUJsQyxJQUFyQixFQUEyQm9CLFVBQTNCLEVBQXVDbEIsU0FBdkMsRUFBa0RELFNBQWxELEVBQTZEa0MsZUFBN0QsRUFBOEU7QUFDNUUsTUFBSWtCLGVBQWUsQ0FBbkI7QUFBQSxNQUNJQyxlQUFlbEMsV0FBV04sTUFEOUI7QUFBQSxNQUVJSyxTQUFTLENBRmI7QUFBQSxNQUdJRSxTQUFTLENBSGI7O0FBS0EsU0FBT2dDLGVBQWVDLFlBQXRCLEVBQW9DRCxjQUFwQyxFQUFvRDtBQUNsRCxRQUFJRSxZQUFZbkMsV0FBV2lDLFlBQVgsQ0FBaEI7QUFDQSxRQUFJLENBQUNFLFVBQVVoQixPQUFmLEVBQXdCO0FBQ3RCLFVBQUksQ0FBQ2dCLFVBQVVqQixLQUFYLElBQW9CSCxlQUF4QixFQUF5QztBQUN2QyxZQUFJNUIsUUFBUUwsVUFBVXNELEtBQVYsQ0FBZ0JyQyxNQUFoQixFQUF3QkEsU0FBU29DLFVBQVUvQixLQUEzQyxDQUFaO0FBQ0FqQixnQkFBUUEsTUFBTWtELEdBQU4sQ0FBVSxVQUFTbEQsS0FBVCxFQUFnQjJDLENBQWhCLEVBQW1CO0FBQ25DLGNBQUlRLFdBQVd6RCxVQUFVb0IsU0FBUzZCLENBQW5CLENBQWY7QUFDQSxpQkFBT1EsU0FBUzVDLE1BQVQsR0FBa0JQLE1BQU1PLE1BQXhCLEdBQWlDNEMsUUFBakMsR0FBNENuRCxLQUFuRDtBQUNELFNBSE8sQ0FBUjs7QUFLQWdELGtCQUFVaEQsS0FBVixHQUFrQlAsS0FBS3VCLElBQUwsQ0FBVWhCLEtBQVYsQ0FBbEI7QUFDRCxPQVJELE1BUU87QUFDTGdELGtCQUFVaEQsS0FBVixHQUFrQlAsS0FBS3VCLElBQUwsQ0FBVXJCLFVBQVVzRCxLQUFWLENBQWdCckMsTUFBaEIsRUFBd0JBLFNBQVNvQyxVQUFVL0IsS0FBM0MsQ0FBVixDQUFsQjtBQUNEO0FBQ0RMLGdCQUFVb0MsVUFBVS9CLEtBQXBCOztBQUVBO0FBQ0EsVUFBSSxDQUFDK0IsVUFBVWpCLEtBQWYsRUFBc0I7QUFDcEJqQixrQkFBVWtDLFVBQVUvQixLQUFwQjtBQUNEO0FBQ0YsS0FsQkQsTUFrQk87QUFDTCtCLGdCQUFVaEQsS0FBVixHQUFrQlAsS0FBS3VCLElBQUwsQ0FBVXRCLFVBQVV1RCxLQUFWLENBQWdCbkMsTUFBaEIsRUFBd0JBLFNBQVNrQyxVQUFVL0IsS0FBM0MsQ0FBVixDQUFsQjtBQUNBSCxnQkFBVWtDLFVBQVUvQixLQUFwQjs7QUFFQTtBQUNBO0FBQ0E7QUFDQSxVQUFJNkIsZ0JBQWdCakMsV0FBV2lDLGVBQWUsQ0FBMUIsRUFBNkJmLEtBQWpELEVBQXdEO0FBQ3RELFlBQUlxQixNQUFNdkMsV0FBV2lDLGVBQWUsQ0FBMUIsQ0FBVjtBQUNBakMsbUJBQVdpQyxlQUFlLENBQTFCLElBQStCakMsV0FBV2lDLFlBQVgsQ0FBL0I7QUFDQWpDLG1CQUFXaUMsWUFBWCxJQUEyQk0sR0FBM0I7QUFDRDtBQUNGO0FBQ0Y7O0FBRUQ7QUFDQTtBQUNBO0FBQ0EsTUFBSUMsZ0JBQWdCeEMsV0FBV2tDLGVBQWUsQ0FBMUIsQ0FBcEI7QUFDQSxNQUFJQSxlQUFlLENBQWYsSUFDRyxPQUFPTSxjQUFjckQsS0FBckIsS0FBK0IsUUFEbEMsS0FFSXFELGNBQWN0QixLQUFkLElBQXVCc0IsY0FBY3JCLE9BRnpDLEtBR0d2QyxLQUFLMkMsTUFBTCxDQUFZLEVBQVosRUFBZ0JpQixjQUFjckQsS0FBOUIsQ0FIUCxFQUc2QztBQUMzQ2EsZUFBV2tDLGVBQWUsQ0FBMUIsRUFBNkIvQyxLQUE3QixJQUFzQ3FELGNBQWNyRCxLQUFwRDtBQUNBYSxlQUFXeUMsR0FBWDtBQUNEOztBQUVELFNBQU96QyxVQUFQO0FBQ0Q7O0FBRUQsU0FBU1ksU0FBVCxDQUFtQjhCLElBQW5CLEVBQXlCO0FBQ3ZCLFNBQU8sRUFBRTNDLFFBQVEyQyxLQUFLM0MsTUFBZixFQUF1QkMsWUFBWTBDLEtBQUsxQyxVQUFMLENBQWdCb0MsS0FBaEIsQ0FBc0IsQ0FBdEIsQ0FBbkMsRUFBUDtBQUNEIiwiZmlsZSI6ImJhc2UuanMiLCJzb3VyY2VzQ29udGVudCI6WyJleHBvcnQgZGVmYXVsdCBmdW5jdGlvbiBEaWZmKCkge31cblxuRGlmZi5wcm90b3R5cGUgPSB7XG4gIGRpZmYob2xkU3RyaW5nLCBuZXdTdHJpbmcsIG9wdGlvbnMgPSB7fSkge1xuICAgIGxldCBjYWxsYmFjayA9IG9wdGlvbnMuY2FsbGJhY2s7XG4gICAgaWYgKHR5cGVvZiBvcHRpb25zID09PSAnZnVuY3Rpb24nKSB7XG4gICAgICBjYWxsYmFjayA9IG9wdGlvbnM7XG4gICAgICBvcHRpb25zID0ge307XG4gICAgfVxuICAgIHRoaXMub3B0aW9ucyA9IG9wdGlvbnM7XG5cbiAgICBsZXQgc2VsZiA9IHRoaXM7XG5cbiAgICBmdW5jdGlvbiBkb25lKHZhbHVlKSB7XG4gICAgICBpZiAoY2FsbGJhY2spIHtcbiAgICAgICAgc2V0VGltZW91dChmdW5jdGlvbigpIHsgY2FsbGJhY2sodW5kZWZpbmVkLCB2YWx1ZSk7IH0sIDApO1xuICAgICAgICByZXR1cm4gdHJ1ZTtcbiAgICAgIH0gZWxzZSB7XG4gICAgICAgIHJldHVybiB2YWx1ZTtcbiAgICAgIH1cbiAgICB9XG5cbiAgICAvLyBBbGxvdyBzdWJjbGFzc2VzIHRvIG1hc3NhZ2UgdGhlIGlucHV0IHByaW9yIHRvIHJ1bm5pbmdcbiAgICBvbGRTdHJpbmcgPSB0aGlzLmNhc3RJbnB1dChvbGRTdHJpbmcpO1xuICAgIG5ld1N0cmluZyA9IHRoaXMuY2FzdElucHV0KG5ld1N0cmluZyk7XG5cbiAgICBvbGRTdHJpbmcgPSB0aGlzLnJlbW92ZUVtcHR5KHRoaXMudG9rZW5pemUob2xkU3RyaW5nKSk7XG4gICAgbmV3U3RyaW5nID0gdGhpcy5yZW1vdmVFbXB0eSh0aGlzLnRva2VuaXplKG5ld1N0cmluZykpO1xuXG4gICAgbGV0IG5ld0xlbiA9IG5ld1N0cmluZy5sZW5ndGgsIG9sZExlbiA9IG9sZFN0cmluZy5sZW5ndGg7XG4gICAgbGV0IGVkaXRMZW5ndGggPSAxO1xuICAgIGxldCBtYXhFZGl0TGVuZ3RoID0gbmV3TGVuICsgb2xkTGVuO1xuICAgIGxldCBiZXN0UGF0aCA9IFt7IG5ld1BvczogLTEsIGNvbXBvbmVudHM6IFtdIH1dO1xuXG4gICAgLy8gU2VlZCBlZGl0TGVuZ3RoID0gMCwgaS5lLiB0aGUgY29udGVudCBzdGFydHMgd2l0aCB0aGUgc2FtZSB2YWx1ZXNcbiAgICBsZXQgb2xkUG9zID0gdGhpcy5leHRyYWN0Q29tbW9uKGJlc3RQYXRoWzBdLCBuZXdTdHJpbmcsIG9sZFN0cmluZywgMCk7XG4gICAgaWYgKGJlc3RQYXRoWzBdLm5ld1BvcyArIDEgPj0gbmV3TGVuICYmIG9sZFBvcyArIDEgPj0gb2xkTGVuKSB7XG4gICAgICAvLyBJZGVudGl0eSBwZXIgdGhlIGVxdWFsaXR5IGFuZCB0b2tlbml6ZXJcbiAgICAgIHJldHVybiBkb25lKFt7dmFsdWU6IHRoaXMuam9pbihuZXdTdHJpbmcpLCBjb3VudDogbmV3U3RyaW5nLmxlbmd0aH1dKTtcbiAgICB9XG5cbiAgICAvLyBNYWluIHdvcmtlciBtZXRob2QuIGNoZWNrcyBhbGwgcGVybXV0YXRpb25zIG9mIGEgZ2l2ZW4gZWRpdCBsZW5ndGggZm9yIGFjY2VwdGFuY2UuXG4gICAgZnVuY3Rpb24gZXhlY0VkaXRMZW5ndGgoKSB7XG4gICAgICBmb3IgKGxldCBkaWFnb25hbFBhdGggPSAtMSAqIGVkaXRMZW5ndGg7IGRpYWdvbmFsUGF0aCA8PSBlZGl0TGVuZ3RoOyBkaWFnb25hbFBhdGggKz0gMikge1xuICAgICAgICBsZXQgYmFzZVBhdGg7XG4gICAgICAgIGxldCBhZGRQYXRoID0gYmVzdFBhdGhbZGlhZ29uYWxQYXRoIC0gMV0sXG4gICAgICAgICAgICByZW1vdmVQYXRoID0gYmVzdFBhdGhbZGlhZ29uYWxQYXRoICsgMV0sXG4gICAgICAgICAgICBvbGRQb3MgPSAocmVtb3ZlUGF0aCA/IHJlbW92ZVBhdGgubmV3UG9zIDogMCkgLSBkaWFnb25hbFBhdGg7XG4gICAgICAgIGlmIChhZGRQYXRoKSB7XG4gICAgICAgICAgLy8gTm8gb25lIGVsc2UgaXMgZ29pbmcgdG8gYXR0ZW1wdCB0byB1c2UgdGhpcyB2YWx1ZSwgY2xlYXIgaXRcbiAgICAgICAgICBiZXN0UGF0aFtkaWFnb25hbFBhdGggLSAxXSA9IHVuZGVmaW5lZDtcbiAgICAgICAgfVxuXG4gICAgICAgIGxldCBjYW5BZGQgPSBhZGRQYXRoICYmIGFkZFBhdGgubmV3UG9zICsgMSA8IG5ld0xlbixcbiAgICAgICAgICAgIGNhblJlbW92ZSA9IHJlbW92ZVBhdGggJiYgMCA8PSBvbGRQb3MgJiYgb2xkUG9zIDwgb2xkTGVuO1xuICAgICAgICBpZiAoIWNhbkFkZCAmJiAhY2FuUmVtb3ZlKSB7XG4gICAgICAgICAgLy8gSWYgdGhpcyBwYXRoIGlzIGEgdGVybWluYWwgdGhlbiBwcnVuZVxuICAgICAgICAgIGJlc3RQYXRoW2RpYWdvbmFsUGF0aF0gPSB1bmRlZmluZWQ7XG4gICAgICAgICAgY29udGludWU7XG4gICAgICAgIH1cblxuICAgICAgICAvLyBTZWxlY3QgdGhlIGRpYWdvbmFsIHRoYXQgd2Ugd2FudCB0byBicmFuY2ggZnJvbS4gV2Ugc2VsZWN0IHRoZSBwcmlvclxuICAgICAgICAvLyBwYXRoIHdob3NlIHBvc2l0aW9uIGluIHRoZSBuZXcgc3RyaW5nIGlzIHRoZSBmYXJ0aGVzdCBmcm9tIHRoZSBvcmlnaW5cbiAgICAgICAgLy8gYW5kIGRvZXMgbm90IHBhc3MgdGhlIGJvdW5kcyBvZiB0aGUgZGlmZiBncmFwaFxuICAgICAgICBpZiAoIWNhbkFkZCB8fCAoY2FuUmVtb3ZlICYmIGFkZFBhdGgubmV3UG9zIDwgcmVtb3ZlUGF0aC5uZXdQb3MpKSB7XG4gICAgICAgICAgYmFzZVBhdGggPSBjbG9uZVBhdGgocmVtb3ZlUGF0aCk7XG4gICAgICAgICAgc2VsZi5wdXNoQ29tcG9uZW50KGJhc2VQYXRoLmNvbXBvbmVudHMsIHVuZGVmaW5lZCwgdHJ1ZSk7XG4gICAgICAgIH0gZWxzZSB7XG4gICAgICAgICAgYmFzZVBhdGggPSBhZGRQYXRoOyAgIC8vIE5vIG5lZWQgdG8gY2xvbmUsIHdlJ3ZlIHB1bGxlZCBpdCBmcm9tIHRoZSBsaXN0XG4gICAgICAgICAgYmFzZVBhdGgubmV3UG9zKys7XG4gICAgICAgICAgc2VsZi5wdXNoQ29tcG9uZW50KGJhc2VQYXRoLmNvbXBvbmVudHMsIHRydWUsIHVuZGVmaW5lZCk7XG4gICAgICAgIH1cblxuICAgICAgICBvbGRQb3MgPSBzZWxmLmV4dHJhY3RDb21tb24oYmFzZVBhdGgsIG5ld1N0cmluZywgb2xkU3RyaW5nLCBkaWFnb25hbFBhdGgpO1xuXG4gICAgICAgIC8vIElmIHdlIGhhdmUgaGl0IHRoZSBlbmQgb2YgYm90aCBzdHJpbmdzLCB0aGVuIHdlIGFyZSBkb25lXG4gICAgICAgIGlmIChiYXNlUGF0aC5uZXdQb3MgKyAxID49IG5ld0xlbiAmJiBvbGRQb3MgKyAxID49IG9sZExlbikge1xuICAgICAgICAgIHJldHVybiBkb25lKGJ1aWxkVmFsdWVzKHNlbGYsIGJhc2VQYXRoLmNvbXBvbmVudHMsIG5ld1N0cmluZywgb2xkU3RyaW5nLCBzZWxmLnVzZUxvbmdlc3RUb2tlbikpO1xuICAgICAgICB9IGVsc2Uge1xuICAgICAgICAgIC8vIE90aGVyd2lzZSB0cmFjayB0aGlzIHBhdGggYXMgYSBwb3RlbnRpYWwgY2FuZGlkYXRlIGFuZCBjb250aW51ZS5cbiAgICAgICAgICBiZXN0UGF0aFtkaWFnb25hbFBhdGhdID0gYmFzZVBhdGg7XG4gICAgICAgIH1cbiAgICAgIH1cblxuICAgICAgZWRpdExlbmd0aCsrO1xuICAgIH1cblxuICAgIC8vIFBlcmZvcm1zIHRoZSBsZW5ndGggb2YgZWRpdCBpdGVyYXRpb24uIElzIGEgYml0IGZ1Z2x5IGFzIHRoaXMgaGFzIHRvIHN1cHBvcnQgdGhlXG4gICAgLy8gc3luYyBhbmQgYXN5bmMgbW9kZSB3aGljaCBpcyBuZXZlciBmdW4uIExvb3BzIG92ZXIgZXhlY0VkaXRMZW5ndGggdW50aWwgYSB2YWx1ZVxuICAgIC8vIGlzIHByb2R1Y2VkLlxuICAgIGlmIChjYWxsYmFjaykge1xuICAgICAgKGZ1bmN0aW9uIGV4ZWMoKSB7XG4gICAgICAgIHNldFRpbWVvdXQoZnVuY3Rpb24oKSB7XG4gICAgICAgICAgLy8gVGhpcyBzaG91bGQgbm90IGhhcHBlbiwgYnV0IHdlIHdhbnQgdG8gYmUgc2FmZS5cbiAgICAgICAgICAvKiBpc3RhbmJ1bCBpZ25vcmUgbmV4dCAqL1xuICAgICAgICAgIGlmIChlZGl0TGVuZ3RoID4gbWF4RWRpdExlbmd0aCkge1xuICAgICAgICAgICAgcmV0dXJuIGNhbGxiYWNrKCk7XG4gICAgICAgICAgfVxuXG4gICAgICAgICAgaWYgKCFleGVjRWRpdExlbmd0aCgpKSB7XG4gICAgICAgICAgICBleGVjKCk7XG4gICAgICAgICAgfVxuICAgICAgICB9LCAwKTtcbiAgICAgIH0oKSk7XG4gICAgfSBlbHNlIHtcbiAgICAgIHdoaWxlIChlZGl0TGVuZ3RoIDw9IG1heEVkaXRMZW5ndGgpIHtcbiAgICAgICAgbGV0IHJldCA9IGV4ZWNFZGl0TGVuZ3RoKCk7XG4gICAgICAgIGlmIChyZXQpIHtcbiAgICAgICAgICByZXR1cm4gcmV0O1xuICAgICAgICB9XG4gICAgICB9XG4gICAgfVxuICB9LFxuXG4gIHB1c2hDb21wb25lbnQoY29tcG9uZW50cywgYWRkZWQsIHJlbW92ZWQpIHtcbiAgICBsZXQgbGFzdCA9IGNvbXBvbmVudHNbY29tcG9uZW50cy5sZW5ndGggLSAxXTtcbiAgICBpZiAobGFzdCAmJiBsYXN0LmFkZGVkID09PSBhZGRlZCAmJiBsYXN0LnJlbW92ZWQgPT09IHJlbW92ZWQpIHtcbiAgICAgIC8vIFdlIG5lZWQgdG8gY2xvbmUgaGVyZSBhcyB0aGUgY29tcG9uZW50IGNsb25lIG9wZXJhdGlvbiBpcyBqdXN0XG4gICAgICAvLyBhcyBzaGFsbG93IGFycmF5IGNsb25lXG4gICAgICBjb21wb25lbnRzW2NvbXBvbmVudHMubGVuZ3RoIC0gMV0gPSB7Y291bnQ6IGxhc3QuY291bnQgKyAxLCBhZGRlZDogYWRkZWQsIHJlbW92ZWQ6IHJlbW92ZWQgfTtcbiAgICB9IGVsc2Uge1xuICAgICAgY29tcG9uZW50cy5wdXNoKHtjb3VudDogMSwgYWRkZWQ6IGFkZGVkLCByZW1vdmVkOiByZW1vdmVkIH0pO1xuICAgIH1cbiAgfSxcbiAgZXh0cmFjdENvbW1vbihiYXNlUGF0aCwgbmV3U3RyaW5nLCBvbGRTdHJpbmcsIGRpYWdvbmFsUGF0aCkge1xuICAgIGxldCBuZXdMZW4gPSBuZXdTdHJpbmcubGVuZ3RoLFxuICAgICAgICBvbGRMZW4gPSBvbGRTdHJpbmcubGVuZ3RoLFxuICAgICAgICBuZXdQb3MgPSBiYXNlUGF0aC5uZXdQb3MsXG4gICAgICAgIG9sZFBvcyA9IG5ld1BvcyAtIGRpYWdvbmFsUGF0aCxcblxuICAgICAgICBjb21tb25Db3VudCA9IDA7XG4gICAgd2hpbGUgKG5ld1BvcyArIDEgPCBuZXdMZW4gJiYgb2xkUG9zICsgMSA8IG9sZExlbiAmJiB0aGlzLmVxdWFscyhuZXdTdHJpbmdbbmV3UG9zICsgMV0sIG9sZFN0cmluZ1tvbGRQb3MgKyAxXSkpIHtcbiAgICAgIG5ld1BvcysrO1xuICAgICAgb2xkUG9zKys7XG4gICAgICBjb21tb25Db3VudCsrO1xuICAgIH1cblxuICAgIGlmIChjb21tb25Db3VudCkge1xuICAgICAgYmFzZVBhdGguY29tcG9uZW50cy5wdXNoKHtjb3VudDogY29tbW9uQ291bnR9KTtcbiAgICB9XG5cbiAgICBiYXNlUGF0aC5uZXdQb3MgPSBuZXdQb3M7XG4gICAgcmV0dXJuIG9sZFBvcztcbiAgfSxcblxuICBlcXVhbHMobGVmdCwgcmlnaHQpIHtcbiAgICBpZiAodGhpcy5vcHRpb25zLmNvbXBhcmF0b3IpIHtcbiAgICAgIHJldHVybiB0aGlzLm9wdGlvbnMuY29tcGFyYXRvcihsZWZ0LCByaWdodCk7XG4gICAgfSBlbHNlIHtcbiAgICAgIHJldHVybiBsZWZ0ID09PSByaWdodFxuICAgICAgICB8fCAodGhpcy5vcHRpb25zLmlnbm9yZUNhc2UgJiYgbGVmdC50b0xvd2VyQ2FzZSgpID09PSByaWdodC50b0xvd2VyQ2FzZSgpKTtcbiAgICB9XG4gIH0sXG4gIHJlbW92ZUVtcHR5KGFycmF5KSB7XG4gICAgbGV0IHJldCA9IFtdO1xuICAgIGZvciAobGV0IGkgPSAwOyBpIDwgYXJyYXkubGVuZ3RoOyBpKyspIHtcbiAgICAgIGlmIChhcnJheVtpXSkge1xuICAgICAgICByZXQucHVzaChhcnJheVtpXSk7XG4gICAgICB9XG4gICAgfVxuICAgIHJldHVybiByZXQ7XG4gIH0sXG4gIGNhc3RJbnB1dCh2YWx1ZSkge1xuICAgIHJldHVybiB2YWx1ZTtcbiAgfSxcbiAgdG9rZW5pemUodmFsdWUpIHtcbiAgICByZXR1cm4gdmFsdWUuc3BsaXQoJycpO1xuICB9LFxuICBqb2luKGNoYXJzKSB7XG4gICAgcmV0dXJuIGNoYXJzLmpvaW4oJycpO1xuICB9XG59O1xuXG5mdW5jdGlvbiBidWlsZFZhbHVlcyhkaWZmLCBjb21wb25lbnRzLCBuZXdTdHJpbmcsIG9sZFN0cmluZywgdXNlTG9uZ2VzdFRva2VuKSB7XG4gIGxldCBjb21wb25lbnRQb3MgPSAwLFxuICAgICAgY29tcG9uZW50TGVuID0gY29tcG9uZW50cy5sZW5ndGgsXG4gICAgICBuZXdQb3MgPSAwLFxuICAgICAgb2xkUG9zID0gMDtcblxuICBmb3IgKDsgY29tcG9uZW50UG9zIDwgY29tcG9uZW50TGVuOyBjb21wb25lbnRQb3MrKykge1xuICAgIGxldCBjb21wb25lbnQgPSBjb21wb25lbnRzW2NvbXBvbmVudFBvc107XG4gICAgaWYgKCFjb21wb25lbnQucmVtb3ZlZCkge1xuICAgICAgaWYgKCFjb21wb25lbnQuYWRkZWQgJiYgdXNlTG9uZ2VzdFRva2VuKSB7XG4gICAgICAgIGxldCB2YWx1ZSA9IG5ld1N0cmluZy5zbGljZShuZXdQb3MsIG5ld1BvcyArIGNvbXBvbmVudC5jb3VudCk7XG4gICAgICAgIHZhbHVlID0gdmFsdWUubWFwKGZ1bmN0aW9uKHZhbHVlLCBpKSB7XG4gICAgICAgICAgbGV0IG9sZFZhbHVlID0gb2xkU3RyaW5nW29sZFBvcyArIGldO1xuICAgICAgICAgIHJldHVybiBvbGRWYWx1ZS5sZW5ndGggPiB2YWx1ZS5sZW5ndGggPyBvbGRWYWx1ZSA6IHZhbHVlO1xuICAgICAgICB9KTtcblxuICAgICAgICBjb21wb25lbnQudmFsdWUgPSBkaWZmLmpvaW4odmFsdWUpO1xuICAgICAgfSBlbHNlIHtcbiAgICAgICAgY29tcG9uZW50LnZhbHVlID0gZGlmZi5qb2luKG5ld1N0cmluZy5zbGljZShuZXdQb3MsIG5ld1BvcyArIGNvbXBvbmVudC5jb3VudCkpO1xuICAgICAgfVxuICAgICAgbmV3UG9zICs9IGNvbXBvbmVudC5jb3VudDtcblxuICAgICAgLy8gQ29tbW9uIGNhc2VcbiAgICAgIGlmICghY29tcG9uZW50LmFkZGVkKSB7XG4gICAgICAgIG9sZFBvcyArPSBjb21wb25lbnQuY291bnQ7XG4gICAgICB9XG4gICAgfSBlbHNlIHtcbiAgICAgIGNvbXBvbmVudC52YWx1ZSA9IGRpZmYuam9pbihvbGRTdHJpbmcuc2xpY2Uob2xkUG9zLCBvbGRQb3MgKyBjb21wb25lbnQuY291bnQpKTtcbiAgICAgIG9sZFBvcyArPSBjb21wb25lbnQuY291bnQ7XG5cbiAgICAgIC8vIFJldmVyc2UgYWRkIGFuZCByZW1vdmUgc28gcmVtb3ZlcyBhcmUgb3V0cHV0IGZpcnN0IHRvIG1hdGNoIGNvbW1vbiBjb252ZW50aW9uXG4gICAgICAvLyBUaGUgZGlmZmluZyBhbGdvcml0aG0gaXMgdGllZCB0byBhZGQgdGhlbiByZW1vdmUgb3V0cHV0IGFuZCB0aGlzIGlzIHRoZSBzaW1wbGVzdFxuICAgICAgLy8gcm91dGUgdG8gZ2V0IHRoZSBkZXNpcmVkIG91dHB1dCB3aXRoIG1pbmltYWwgb3ZlcmhlYWQuXG4gICAgICBpZiAoY29tcG9uZW50UG9zICYmIGNvbXBvbmVudHNbY29tcG9uZW50UG9zIC0gMV0uYWRkZWQpIHtcbiAgICAgICAgbGV0IHRtcCA9IGNvbXBvbmVudHNbY29tcG9uZW50UG9zIC0gMV07XG4gICAgICAgIGNvbXBvbmVudHNbY29tcG9uZW50UG9zIC0gMV0gPSBjb21wb25lbnRzW2NvbXBvbmVudFBvc107XG4gICAgICAgIGNvbXBvbmVudHNbY29tcG9uZW50UG9zXSA9IHRtcDtcbiAgICAgIH1cbiAgICB9XG4gIH1cblxuICAvLyBTcGVjaWFsIGNhc2UgaGFuZGxlIGZvciB3aGVuIG9uZSB0ZXJtaW5hbCBpcyBpZ25vcmVkIChpLmUuIHdoaXRlc3BhY2UpLlxuICAvLyBGb3IgdGhpcyBjYXNlIHdlIG1lcmdlIHRoZSB0ZXJtaW5hbCBpbnRvIHRoZSBwcmlvciBzdHJpbmcgYW5kIGRyb3AgdGhlIGNoYW5nZS5cbiAgLy8gVGhpcyBpcyBvbmx5IGF2YWlsYWJsZSBmb3Igc3RyaW5nIG1vZGUuXG4gIGxldCBsYXN0Q29tcG9uZW50ID0gY29tcG9uZW50c1tjb21wb25lbnRMZW4gLSAxXTtcbiAgaWYgKGNvbXBvbmVudExlbiA+IDFcbiAgICAgICYmIHR5cGVvZiBsYXN0Q29tcG9uZW50LnZhbHVlID09PSAnc3RyaW5nJ1xuICAgICAgJiYgKGxhc3RDb21wb25lbnQuYWRkZWQgfHwgbGFzdENvbXBvbmVudC5yZW1vdmVkKVxuICAgICAgJiYgZGlmZi5lcXVhbHMoJycsIGxhc3RDb21wb25lbnQudmFsdWUpKSB7XG4gICAgY29tcG9uZW50c1tjb21wb25lbnRMZW4gLSAyXS52YWx1ZSArPSBsYXN0Q29tcG9uZW50LnZhbHVlO1xuICAgIGNvbXBvbmVudHMucG9wKCk7XG4gIH1cblxuICByZXR1cm4gY29tcG9uZW50cztcbn1cblxuZnVuY3Rpb24gY2xvbmVQYXRoKHBhdGgpIHtcbiAgcmV0dXJuIHsgbmV3UG9zOiBwYXRoLm5ld1BvcywgY29tcG9uZW50czogcGF0aC5jb21wb25lbnRzLnNsaWNlKDApIH07XG59XG4iXX0=
diff --git a/node_modules/diff/lib/diff/character.js b/node_modules/diff/lib/diff/character.js
new file mode 100644
index 0000000..e15da7a
--- /dev/null
+++ b/node_modules/diff/lib/diff/character.js
@@ -0,0 +1,17 @@
+/*istanbul ignore start*/'use strict';
+
+exports.__esModule = true;
+exports.characterDiff = undefined;
+exports. /*istanbul ignore end*/diffChars = diffChars;
+
+var /*istanbul ignore start*/_base = require('./base') /*istanbul ignore end*/;
+
+/*istanbul ignore start*/var _base2 = _interopRequireDefault(_base);
+
+function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
+
+/*istanbul ignore end*/var characterDiff = /*istanbul ignore start*/exports. /*istanbul ignore end*/characterDiff = new /*istanbul ignore start*/_base2['default'] /*istanbul ignore end*/();
+function diffChars(oldStr, newStr, options) {
+  return characterDiff.diff(oldStr, newStr, options);
+}
+//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9kaWZmL2NoYXJhY3Rlci5qcyJdLCJuYW1lcyI6WyJkaWZmQ2hhcnMiLCJjaGFyYWN0ZXJEaWZmIiwib2xkU3RyIiwibmV3U3RyIiwib3B0aW9ucyIsImRpZmYiXSwibWFwcGluZ3MiOiI7Ozs7Z0NBR2dCQSxTLEdBQUFBLFM7O0FBSGhCOzs7Ozs7dUJBRU8sSUFBTUMseUZBQWdCLHdFQUF0QjtBQUNBLFNBQVNELFNBQVQsQ0FBbUJFLE1BQW5CLEVBQTJCQyxNQUEzQixFQUFtQ0MsT0FBbkMsRUFBNEM7QUFBRSxTQUFPSCxjQUFjSSxJQUFkLENBQW1CSCxNQUFuQixFQUEyQkMsTUFBM0IsRUFBbUNDLE9BQW5DLENBQVA7QUFBcUQiLCJmaWxlIjoiY2hhcmFjdGVyLmpzIiwic291cmNlc0NvbnRlbnQiOlsiaW1wb3J0IERpZmYgZnJvbSAnLi9iYXNlJztcblxuZXhwb3J0IGNvbnN0IGNoYXJhY3RlckRpZmYgPSBuZXcgRGlmZigpO1xuZXhwb3J0IGZ1bmN0aW9uIGRpZmZDaGFycyhvbGRTdHIsIG5ld1N0ciwgb3B0aW9ucykgeyByZXR1cm4gY2hhcmFjdGVyRGlmZi5kaWZmKG9sZFN0ciwgbmV3U3RyLCBvcHRpb25zKTsgfVxuIl19
diff --git a/node_modules/diff/lib/diff/css.js b/node_modules/diff/lib/diff/css.js
new file mode 100644
index 0000000..640af5e
--- /dev/null
+++ b/node_modules/diff/lib/diff/css.js
@@ -0,0 +1,21 @@
+/*istanbul ignore start*/'use strict';
+
+exports.__esModule = true;
+exports.cssDiff = undefined;
+exports. /*istanbul ignore end*/diffCss = diffCss;
+
+var /*istanbul ignore start*/_base = require('./base') /*istanbul ignore end*/;
+
+/*istanbul ignore start*/var _base2 = _interopRequireDefault(_base);
+
+function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
+
+/*istanbul ignore end*/var cssDiff = /*istanbul ignore start*/exports. /*istanbul ignore end*/cssDiff = new /*istanbul ignore start*/_base2['default'] /*istanbul ignore end*/();
+cssDiff.tokenize = function (value) {
+  return value.split(/([{}:;,]|\s+)/);
+};
+
+function diffCss(oldStr, newStr, callback) {
+  return cssDiff.diff(oldStr, newStr, callback);
+}
+//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9kaWZmL2Nzcy5qcyJdLCJuYW1lcyI6WyJkaWZmQ3NzIiwiY3NzRGlmZiIsInRva2VuaXplIiwidmFsdWUiLCJzcGxpdCIsIm9sZFN0ciIsIm5ld1N0ciIsImNhbGxiYWNrIiwiZGlmZiJdLCJtYXBwaW5ncyI6Ijs7OztnQ0FPZ0JBLE8sR0FBQUEsTzs7QUFQaEI7Ozs7Ozt1QkFFTyxJQUFNQyw2RUFBVSx3RUFBaEI7QUFDUEEsUUFBUUMsUUFBUixHQUFtQixVQUFTQyxLQUFULEVBQWdCO0FBQ2pDLFNBQU9BLE1BQU1DLEtBQU4sQ0FBWSxlQUFaLENBQVA7QUFDRCxDQUZEOztBQUlPLFNBQVNKLE9BQVQsQ0FBaUJLLE1BQWpCLEVBQXlCQyxNQUF6QixFQUFpQ0MsUUFBakMsRUFBMkM7QUFBRSxTQUFPTixRQUFRTyxJQUFSLENBQWFILE1BQWIsRUFBcUJDLE1BQXJCLEVBQTZCQyxRQUE3QixDQUFQO0FBQWdEIiwiZmlsZSI6ImNzcy5qcyIsInNvdXJjZXNDb250ZW50IjpbImltcG9ydCBEaWZmIGZyb20gJy4vYmFzZSc7XG5cbmV4cG9ydCBjb25zdCBjc3NEaWZmID0gbmV3IERpZmYoKTtcbmNzc0RpZmYudG9rZW5pemUgPSBmdW5jdGlvbih2YWx1ZSkge1xuICByZXR1cm4gdmFsdWUuc3BsaXQoLyhbe306OyxdfFxccyspLyk7XG59O1xuXG5leHBvcnQgZnVuY3Rpb24gZGlmZkNzcyhvbGRTdHIsIG5ld1N0ciwgY2FsbGJhY2spIHsgcmV0dXJuIGNzc0RpZmYuZGlmZihvbGRTdHIsIG5ld1N0ciwgY2FsbGJhY2spOyB9XG4iXX0=
diff --git a/node_modules/diff/lib/diff/json.js b/node_modules/diff/lib/diff/json.js
new file mode 100644
index 0000000..ca21739
--- /dev/null
+++ b/node_modules/diff/lib/diff/json.js
@@ -0,0 +1,108 @@
+/*istanbul ignore start*/'use strict';
+
+exports.__esModule = true;
+exports.jsonDiff = undefined;
+
+var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
+
+exports. /*istanbul ignore end*/diffJson = diffJson;
+/*istanbul ignore start*/exports. /*istanbul ignore end*/canonicalize = canonicalize;
+
+var /*istanbul ignore start*/_base = require('./base') /*istanbul ignore end*/;
+
+/*istanbul ignore start*/var _base2 = _interopRequireDefault(_base);
+
+/*istanbul ignore end*/var /*istanbul ignore start*/_line = require('./line') /*istanbul ignore end*/;
+
+/*istanbul ignore start*/function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
+
+/*istanbul ignore end*/var objectPrototypeToString = Object.prototype.toString;
+
+var jsonDiff = /*istanbul ignore start*/exports. /*istanbul ignore end*/jsonDiff = new /*istanbul ignore start*/_base2['default'] /*istanbul ignore end*/();
+// Discriminate between two lines of pretty-printed, serialized JSON where one of them has a
+// dangling comma and the other doesn't. Turns out including the dangling comma yields the nicest output:
+jsonDiff.useLongestToken = true;
+
+jsonDiff.tokenize = /*istanbul ignore start*/_line.lineDiff /*istanbul ignore end*/.tokenize;
+jsonDiff.castInput = function (value) {
+  /*istanbul ignore start*/var _options = /*istanbul ignore end*/this.options,
+      undefinedReplacement = _options.undefinedReplacement,
+      _options$stringifyRep = _options.stringifyReplacer,
+      stringifyReplacer = _options$stringifyRep === undefined ? function (k, v) /*istanbul ignore start*/{
+    return (/*istanbul ignore end*/typeof v === 'undefined' ? undefinedReplacement : v
+    );
+  } : _options$stringifyRep;
+
+
+  return typeof value === 'string' ? value : JSON.stringify(canonicalize(value, null, null, stringifyReplacer), stringifyReplacer, '  ');
+};
+jsonDiff.equals = function (left, right) {
+  return (/*istanbul ignore start*/_base2['default'] /*istanbul ignore end*/.prototype.equals.call(jsonDiff, left.replace(/,([\r\n])/g, '$1'), right.replace(/,([\r\n])/g, '$1'))
+  );
+};
+
+function diffJson(oldObj, newObj, options) {
+  return jsonDiff.diff(oldObj, newObj, options);
+}
+
+// This function handles the presence of circular references by bailing out when encountering an
+// object that is already on the "stack" of items being processed. Accepts an optional replacer
+function canonicalize(obj, stack, replacementStack, replacer, key) {
+  stack = stack || [];
+  replacementStack = replacementStack || [];
+
+  if (replacer) {
+    obj = replacer(key, obj);
+  }
+
+  var i = /*istanbul ignore start*/void 0 /*istanbul ignore end*/;
+
+  for (i = 0; i < stack.length; i += 1) {
+    if (stack[i] === obj) {
+      return replacementStack[i];
+    }
+  }
+
+  var canonicalizedObj = /*istanbul ignore start*/void 0 /*istanbul ignore end*/;
+
+  if ('[object Array]' === objectPrototypeToString.call(obj)) {
+    stack.push(obj);
+    canonicalizedObj = new Array(obj.length);
+    replacementStack.push(canonicalizedObj);
+    for (i = 0; i < obj.length; i += 1) {
+      canonicalizedObj[i] = canonicalize(obj[i], stack, replacementStack, replacer, key);
+    }
+    stack.pop();
+    replacementStack.pop();
+    return canonicalizedObj;
+  }
+
+  if (obj && obj.toJSON) {
+    obj = obj.toJSON();
+  }
+
+  if ( /*istanbul ignore start*/(typeof /*istanbul ignore end*/obj === 'undefined' ? 'undefined' : _typeof(obj)) === 'object' && obj !== null) {
+    stack.push(obj);
+    canonicalizedObj = {};
+    replacementStack.push(canonicalizedObj);
+    var sortedKeys = [],
+        _key = /*istanbul ignore start*/void 0 /*istanbul ignore end*/;
+    for (_key in obj) {
+      /* istanbul ignore else */
+      if (obj.hasOwnProperty(_key)) {
+        sortedKeys.push(_key);
+      }
+    }
+    sortedKeys.sort();
+    for (i = 0; i < sortedKeys.length; i += 1) {
+      _key = sortedKeys[i];
+      canonicalizedObj[_key] = canonicalize(obj[_key], stack, replacementStack, replacer, _key);
+    }
+    stack.pop();
+    replacementStack.pop();
+  } else {
+    canonicalizedObj = obj;
+  }
+  return canonicalizedObj;
+}
+//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9kaWZmL2pzb24uanMiXSwibmFtZXMiOlsiZGlmZkpzb24iLCJjYW5vbmljYWxpemUiLCJvYmplY3RQcm90b3R5cGVUb1N0cmluZyIsIk9iamVjdCIsInByb3RvdHlwZSIsInRvU3RyaW5nIiwianNvbkRpZmYiLCJ1c2VMb25nZXN0VG9rZW4iLCJ0b2tlbml6ZSIsImNhc3RJbnB1dCIsInZhbHVlIiwib3B0aW9ucyIsInVuZGVmaW5lZFJlcGxhY2VtZW50Iiwic3RyaW5naWZ5UmVwbGFjZXIiLCJrIiwidiIsIkpTT04iLCJzdHJpbmdpZnkiLCJlcXVhbHMiLCJsZWZ0IiwicmlnaHQiLCJjYWxsIiwicmVwbGFjZSIsIm9sZE9iaiIsIm5ld09iaiIsImRpZmYiLCJvYmoiLCJzdGFjayIsInJlcGxhY2VtZW50U3RhY2siLCJyZXBsYWNlciIsImtleSIsImkiLCJsZW5ndGgiLCJjYW5vbmljYWxpemVkT2JqIiwicHVzaCIsIkFycmF5IiwicG9wIiwidG9KU09OIiwic29ydGVkS2V5cyIsImhhc093blByb3BlcnR5Iiwic29ydCJdLCJtYXBwaW5ncyI6Ijs7Ozs7OztnQ0FxQmdCQSxRLEdBQUFBLFE7eURBSUFDLFksR0FBQUEsWTs7QUF6QmhCOzs7O3VCQUNBOzs7O3VCQUVBLElBQU1DLDBCQUEwQkMsT0FBT0MsU0FBUCxDQUFpQkMsUUFBakQ7O0FBR08sSUFBTUMsK0VBQVcsd0VBQWpCO0FBQ1A7QUFDQTtBQUNBQSxTQUFTQyxlQUFULEdBQTJCLElBQTNCOztBQUVBRCxTQUFTRSxRQUFULEdBQW9CLGdFQUFTQSxRQUE3QjtBQUNBRixTQUFTRyxTQUFULEdBQXFCLFVBQVNDLEtBQVQsRUFBZ0I7QUFBQSxpRUFDK0UsS0FBS0MsT0FEcEY7QUFBQSxNQUM1QkMsb0JBRDRCLFlBQzVCQSxvQkFENEI7QUFBQSx1Q0FDTkMsaUJBRE07QUFBQSxNQUNOQSxpQkFETSx5Q0FDYyxVQUFDQyxDQUFELEVBQUlDLENBQUo7QUFBQSxtQ0FBVSxPQUFPQSxDQUFQLEtBQWEsV0FBYixHQUEyQkgsb0JBQTNCLEdBQWtERztBQUE1RDtBQUFBLEdBRGQ7OztBQUduQyxTQUFPLE9BQU9MLEtBQVAsS0FBaUIsUUFBakIsR0FBNEJBLEtBQTVCLEdBQW9DTSxLQUFLQyxTQUFMLENBQWVoQixhQUFhUyxLQUFiLEVBQW9CLElBQXBCLEVBQTBCLElBQTFCLEVBQWdDRyxpQkFBaEMsQ0FBZixFQUFtRUEsaUJBQW5FLEVBQXNGLElBQXRGLENBQTNDO0FBQ0QsQ0FKRDtBQUtBUCxTQUFTWSxNQUFULEdBQWtCLFVBQVNDLElBQVQsRUFBZUMsS0FBZixFQUFzQjtBQUN0QyxTQUFPLG9FQUFLaEIsU0FBTCxDQUFlYyxNQUFmLENBQXNCRyxJQUF0QixDQUEyQmYsUUFBM0IsRUFBcUNhLEtBQUtHLE9BQUwsQ0FBYSxZQUFiLEVBQTJCLElBQTNCLENBQXJDLEVBQXVFRixNQUFNRSxPQUFOLENBQWMsWUFBZCxFQUE0QixJQUE1QixDQUF2RTtBQUFQO0FBQ0QsQ0FGRDs7QUFJTyxTQUFTdEIsUUFBVCxDQUFrQnVCLE1BQWxCLEVBQTBCQyxNQUExQixFQUFrQ2IsT0FBbEMsRUFBMkM7QUFBRSxTQUFPTCxTQUFTbUIsSUFBVCxDQUFjRixNQUFkLEVBQXNCQyxNQUF0QixFQUE4QmIsT0FBOUIsQ0FBUDtBQUFnRDs7QUFFcEc7QUFDQTtBQUNPLFNBQVNWLFlBQVQsQ0FBc0J5QixHQUF0QixFQUEyQkMsS0FBM0IsRUFBa0NDLGdCQUFsQyxFQUFvREMsUUFBcEQsRUFBOERDLEdBQTlELEVBQW1FO0FBQ3hFSCxVQUFRQSxTQUFTLEVBQWpCO0FBQ0FDLHFCQUFtQkEsb0JBQW9CLEVBQXZDOztBQUVBLE1BQUlDLFFBQUosRUFBYztBQUNaSCxVQUFNRyxTQUFTQyxHQUFULEVBQWNKLEdBQWQsQ0FBTjtBQUNEOztBQUVELE1BQUlLLG1DQUFKOztBQUVBLE9BQUtBLElBQUksQ0FBVCxFQUFZQSxJQUFJSixNQUFNSyxNQUF0QixFQUE4QkQsS0FBSyxDQUFuQyxFQUFzQztBQUNwQyxRQUFJSixNQUFNSSxDQUFOLE1BQWFMLEdBQWpCLEVBQXNCO0FBQ3BCLGFBQU9FLGlCQUFpQkcsQ0FBakIsQ0FBUDtBQUNEO0FBQ0Y7O0FBRUQsTUFBSUUsa0RBQUo7O0FBRUEsTUFBSSxxQkFBcUIvQix3QkFBd0JtQixJQUF4QixDQUE2QkssR0FBN0IsQ0FBekIsRUFBNEQ7QUFDMURDLFVBQU1PLElBQU4sQ0FBV1IsR0FBWDtBQUNBTyx1QkFBbUIsSUFBSUUsS0FBSixDQUFVVCxJQUFJTSxNQUFkLENBQW5CO0FBQ0FKLHFCQUFpQk0sSUFBakIsQ0FBc0JELGdCQUF0QjtBQUNBLFNBQUtGLElBQUksQ0FBVCxFQUFZQSxJQUFJTCxJQUFJTSxNQUFwQixFQUE0QkQsS0FBSyxDQUFqQyxFQUFvQztBQUNsQ0UsdUJBQWlCRixDQUFqQixJQUFzQjlCLGFBQWF5QixJQUFJSyxDQUFKLENBQWIsRUFBcUJKLEtBQXJCLEVBQTRCQyxnQkFBNUIsRUFBOENDLFFBQTlDLEVBQXdEQyxHQUF4RCxDQUF0QjtBQUNEO0FBQ0RILFVBQU1TLEdBQU47QUFDQVIscUJBQWlCUSxHQUFqQjtBQUNBLFdBQU9ILGdCQUFQO0FBQ0Q7O0FBRUQsTUFBSVAsT0FBT0EsSUFBSVcsTUFBZixFQUF1QjtBQUNyQlgsVUFBTUEsSUFBSVcsTUFBSixFQUFOO0FBQ0Q7O0FBRUQsTUFBSSx5REFBT1gsR0FBUCx5Q0FBT0EsR0FBUCxPQUFlLFFBQWYsSUFBMkJBLFFBQVEsSUFBdkMsRUFBNkM7QUFDM0NDLFVBQU1PLElBQU4sQ0FBV1IsR0FBWDtBQUNBTyx1QkFBbUIsRUFBbkI7QUFDQUwscUJBQWlCTSxJQUFqQixDQUFzQkQsZ0JBQXRCO0FBQ0EsUUFBSUssYUFBYSxFQUFqQjtBQUFBLFFBQ0lSLHNDQURKO0FBRUEsU0FBS0EsSUFBTCxJQUFZSixHQUFaLEVBQWlCO0FBQ2Y7QUFDQSxVQUFJQSxJQUFJYSxjQUFKLENBQW1CVCxJQUFuQixDQUFKLEVBQTZCO0FBQzNCUSxtQkFBV0osSUFBWCxDQUFnQkosSUFBaEI7QUFDRDtBQUNGO0FBQ0RRLGVBQVdFLElBQVg7QUFDQSxTQUFLVCxJQUFJLENBQVQsRUFBWUEsSUFBSU8sV0FBV04sTUFBM0IsRUFBbUNELEtBQUssQ0FBeEMsRUFBMkM7QUFDekNELGFBQU1RLFdBQVdQLENBQVgsQ0FBTjtBQUNBRSx1QkFBaUJILElBQWpCLElBQXdCN0IsYUFBYXlCLElBQUlJLElBQUosQ0FBYixFQUF1QkgsS0FBdkIsRUFBOEJDLGdCQUE5QixFQUFnREMsUUFBaEQsRUFBMERDLElBQTFELENBQXhCO0FBQ0Q7QUFDREgsVUFBTVMsR0FBTjtBQUNBUixxQkFBaUJRLEdBQWpCO0FBQ0QsR0FuQkQsTUFtQk87QUFDTEgsdUJBQW1CUCxHQUFuQjtBQUNEO0FBQ0QsU0FBT08sZ0JBQVA7QUFDRCIsImZpbGUiOiJqc29uLmpzIiwic291cmNlc0NvbnRlbnQiOlsiaW1wb3J0IERpZmYgZnJvbSAnLi9iYXNlJztcbmltcG9ydCB7bGluZURpZmZ9IGZyb20gJy4vbGluZSc7XG5cbmNvbnN0IG9iamVjdFByb3RvdHlwZVRvU3RyaW5nID0gT2JqZWN0LnByb3RvdHlwZS50b1N0cmluZztcblxuXG5leHBvcnQgY29uc3QganNvbkRpZmYgPSBuZXcgRGlmZigpO1xuLy8gRGlzY3JpbWluYXRlIGJldHdlZW4gdHdvIGxpbmVzIG9mIHByZXR0eS1wcmludGVkLCBzZXJpYWxpemVkIEpTT04gd2hlcmUgb25lIG9mIHRoZW0gaGFzIGFcbi8vIGRhbmdsaW5nIGNvbW1hIGFuZCB0aGUgb3RoZXIgZG9lc24ndC4gVHVybnMgb3V0IGluY2x1ZGluZyB0aGUgZGFuZ2xpbmcgY29tbWEgeWllbGRzIHRoZSBuaWNlc3Qgb3V0cHV0OlxuanNvbkRpZmYudXNlTG9uZ2VzdFRva2VuID0gdHJ1ZTtcblxuanNvbkRpZmYudG9rZW5pemUgPSBsaW5lRGlmZi50b2tlbml6ZTtcbmpzb25EaWZmLmNhc3RJbnB1dCA9IGZ1bmN0aW9uKHZhbHVlKSB7XG4gIGNvbnN0IHt1bmRlZmluZWRSZXBsYWNlbWVudCwgc3RyaW5naWZ5UmVwbGFjZXIgPSAoaywgdikgPT4gdHlwZW9mIHYgPT09ICd1bmRlZmluZWQnID8gdW5kZWZpbmVkUmVwbGFjZW1lbnQgOiB2fSA9IHRoaXMub3B0aW9ucztcblxuICByZXR1cm4gdHlwZW9mIHZhbHVlID09PSAnc3RyaW5nJyA/IHZhbHVlIDogSlNPTi5zdHJpbmdpZnkoY2Fub25pY2FsaXplKHZhbHVlLCBudWxsLCBudWxsLCBzdHJpbmdpZnlSZXBsYWNlciksIHN0cmluZ2lmeVJlcGxhY2VyLCAnICAnKTtcbn07XG5qc29uRGlmZi5lcXVhbHMgPSBmdW5jdGlvbihsZWZ0LCByaWdodCkge1xuICByZXR1cm4gRGlmZi5wcm90b3R5cGUuZXF1YWxzLmNhbGwoanNvbkRpZmYsIGxlZnQucmVwbGFjZSgvLChbXFxyXFxuXSkvZywgJyQxJyksIHJpZ2h0LnJlcGxhY2UoLywoW1xcclxcbl0pL2csICckMScpKTtcbn07XG5cbmV4cG9ydCBmdW5jdGlvbiBkaWZmSnNvbihvbGRPYmosIG5ld09iaiwgb3B0aW9ucykgeyByZXR1cm4ganNvbkRpZmYuZGlmZihvbGRPYmosIG5ld09iaiwgb3B0aW9ucyk7IH1cblxuLy8gVGhpcyBmdW5jdGlvbiBoYW5kbGVzIHRoZSBwcmVzZW5jZSBvZiBjaXJjdWxhciByZWZlcmVuY2VzIGJ5IGJhaWxpbmcgb3V0IHdoZW4gZW5jb3VudGVyaW5nIGFuXG4vLyBvYmplY3QgdGhhdCBpcyBhbHJlYWR5IG9uIHRoZSBcInN0YWNrXCIgb2YgaXRlbXMgYmVpbmcgcHJvY2Vzc2VkLiBBY2NlcHRzIGFuIG9wdGlvbmFsIHJlcGxhY2VyXG5leHBvcnQgZnVuY3Rpb24gY2Fub25pY2FsaXplKG9iaiwgc3RhY2ssIHJlcGxhY2VtZW50U3RhY2ssIHJlcGxhY2VyLCBrZXkpIHtcbiAgc3RhY2sgPSBzdGFjayB8fCBbXTtcbiAgcmVwbGFjZW1lbnRTdGFjayA9IHJlcGxhY2VtZW50U3RhY2sgfHwgW107XG5cbiAgaWYgKHJlcGxhY2VyKSB7XG4gICAgb2JqID0gcmVwbGFjZXIoa2V5LCBvYmopO1xuICB9XG5cbiAgbGV0IGk7XG5cbiAgZm9yIChpID0gMDsgaSA8IHN0YWNrLmxlbmd0aDsgaSArPSAxKSB7XG4gICAgaWYgKHN0YWNrW2ldID09PSBvYmopIHtcbiAgICAgIHJldHVybiByZXBsYWNlbWVudFN0YWNrW2ldO1xuICAgIH1cbiAgfVxuXG4gIGxldCBjYW5vbmljYWxpemVkT2JqO1xuXG4gIGlmICgnW29iamVjdCBBcnJheV0nID09PSBvYmplY3RQcm90b3R5cGVUb1N0cmluZy5jYWxsKG9iaikpIHtcbiAgICBzdGFjay5wdXNoKG9iaik7XG4gICAgY2Fub25pY2FsaXplZE9iaiA9IG5ldyBBcnJheShvYmoubGVuZ3RoKTtcbiAgICByZXBsYWNlbWVudFN0YWNrLnB1c2goY2Fub25pY2FsaXplZE9iaik7XG4gICAgZm9yIChpID0gMDsgaSA8IG9iai5sZW5ndGg7IGkgKz0gMSkge1xuICAgICAgY2Fub25pY2FsaXplZE9ialtpXSA9IGNhbm9uaWNhbGl6ZShvYmpbaV0sIHN0YWNrLCByZXBsYWNlbWVudFN0YWNrLCByZXBsYWNlciwga2V5KTtcbiAgICB9XG4gICAgc3RhY2sucG9wKCk7XG4gICAgcmVwbGFjZW1lbnRTdGFjay5wb3AoKTtcbiAgICByZXR1cm4gY2Fub25pY2FsaXplZE9iajtcbiAgfVxuXG4gIGlmIChvYmogJiYgb2JqLnRvSlNPTikge1xuICAgIG9iaiA9IG9iai50b0pTT04oKTtcbiAgfVxuXG4gIGlmICh0eXBlb2Ygb2JqID09PSAnb2JqZWN0JyAmJiBvYmogIT09IG51bGwpIHtcbiAgICBzdGFjay5wdXNoKG9iaik7XG4gICAgY2Fub25pY2FsaXplZE9iaiA9IHt9O1xuICAgIHJlcGxhY2VtZW50U3RhY2sucHVzaChjYW5vbmljYWxpemVkT2JqKTtcbiAgICBsZXQgc29ydGVkS2V5cyA9IFtdLFxuICAgICAgICBrZXk7XG4gICAgZm9yIChrZXkgaW4gb2JqKSB7XG4gICAgICAvKiBpc3RhbmJ1bCBpZ25vcmUgZWxzZSAqL1xuICAgICAgaWYgKG9iai5oYXNPd25Qcm9wZXJ0eShrZXkpKSB7XG4gICAgICAgIHNvcnRlZEtleXMucHVzaChrZXkpO1xuICAgICAgfVxuICAgIH1cbiAgICBzb3J0ZWRLZXlzLnNvcnQoKTtcbiAgICBmb3IgKGkgPSAwOyBpIDwgc29ydGVkS2V5cy5sZW5ndGg7IGkgKz0gMSkge1xuICAgICAga2V5ID0gc29ydGVkS2V5c1tpXTtcbiAgICAgIGNhbm9uaWNhbGl6ZWRPYmpba2V5XSA9IGNhbm9uaWNhbGl6ZShvYmpba2V5XSwgc3RhY2ssIHJlcGxhY2VtZW50U3RhY2ssIHJlcGxhY2VyLCBrZXkpO1xuICAgIH1cbiAgICBzdGFjay5wb3AoKTtcbiAgICByZXBsYWNlbWVudFN0YWNrLnBvcCgpO1xuICB9IGVsc2Uge1xuICAgIGNhbm9uaWNhbGl6ZWRPYmogPSBvYmo7XG4gIH1cbiAgcmV0dXJuIGNhbm9uaWNhbGl6ZWRPYmo7XG59XG4iXX0=
diff --git a/node_modules/diff/lib/diff/line.js b/node_modules/diff/lib/diff/line.js
new file mode 100644
index 0000000..f03eedb
--- /dev/null
+++ b/node_modules/diff/lib/diff/line.js
@@ -0,0 +1,50 @@
+/*istanbul ignore start*/'use strict';
+
+exports.__esModule = true;
+exports.lineDiff = undefined;
+exports. /*istanbul ignore end*/diffLines = diffLines;
+/*istanbul ignore start*/exports. /*istanbul ignore end*/diffTrimmedLines = diffTrimmedLines;
+
+var /*istanbul ignore start*/_base = require('./base') /*istanbul ignore end*/;
+
+/*istanbul ignore start*/var _base2 = _interopRequireDefault(_base);
+
+/*istanbul ignore end*/var /*istanbul ignore start*/_params = require('../util/params') /*istanbul ignore end*/;
+
+/*istanbul ignore start*/function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
+
+/*istanbul ignore end*/var lineDiff = /*istanbul ignore start*/exports. /*istanbul ignore end*/lineDiff = new /*istanbul ignore start*/_base2['default'] /*istanbul ignore end*/();
+lineDiff.tokenize = function (value) {
+  var retLines = [],
+      linesAndNewlines = value.split(/(\n|\r\n)/);
+
+  // Ignore the final empty token that occurs if the string ends with a new line
+  if (!linesAndNewlines[linesAndNewlines.length - 1]) {
+    linesAndNewlines.pop();
+  }
+
+  // Merge the content and line separators into single tokens
+  for (var i = 0; i < linesAndNewlines.length; i++) {
+    var line = linesAndNewlines[i];
+
+    if (i % 2 && !this.options.newlineIsToken) {
+      retLines[retLines.length - 1] += line;
+    } else {
+      if (this.options.ignoreWhitespace) {
+        line = line.trim();
+      }
+      retLines.push(line);
+    }
+  }
+
+  return retLines;
+};
+
+function diffLines(oldStr, newStr, callback) {
+  return lineDiff.diff(oldStr, newStr, callback);
+}
+function diffTrimmedLines(oldStr, newStr, callback) {
+  var options = /*istanbul ignore start*/(0, _params.generateOptions) /*istanbul ignore end*/(callback, { ignoreWhitespace: true });
+  return lineDiff.diff(oldStr, newStr, options);
+}
+//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9kaWZmL2xpbmUuanMiXSwibmFtZXMiOlsiZGlmZkxpbmVzIiwiZGlmZlRyaW1tZWRMaW5lcyIsImxpbmVEaWZmIiwidG9rZW5pemUiLCJ2YWx1ZSIsInJldExpbmVzIiwibGluZXNBbmROZXdsaW5lcyIsInNwbGl0IiwibGVuZ3RoIiwicG9wIiwiaSIsImxpbmUiLCJvcHRpb25zIiwibmV3bGluZUlzVG9rZW4iLCJpZ25vcmVXaGl0ZXNwYWNlIiwidHJpbSIsInB1c2giLCJvbGRTdHIiLCJuZXdTdHIiLCJjYWxsYmFjayIsImRpZmYiXSwibWFwcGluZ3MiOiI7Ozs7Z0NBOEJnQkEsUyxHQUFBQSxTO3lEQUNBQyxnQixHQUFBQSxnQjs7QUEvQmhCOzs7O3VCQUNBOzs7O3VCQUVPLElBQU1DLCtFQUFXLHdFQUFqQjtBQUNQQSxTQUFTQyxRQUFULEdBQW9CLFVBQVNDLEtBQVQsRUFBZ0I7QUFDbEMsTUFBSUMsV0FBVyxFQUFmO0FBQUEsTUFDSUMsbUJBQW1CRixNQUFNRyxLQUFOLENBQVksV0FBWixDQUR2Qjs7QUFHQTtBQUNBLE1BQUksQ0FBQ0QsaUJBQWlCQSxpQkFBaUJFLE1BQWpCLEdBQTBCLENBQTNDLENBQUwsRUFBb0Q7QUFDbERGLHFCQUFpQkcsR0FBakI7QUFDRDs7QUFFRDtBQUNBLE9BQUssSUFBSUMsSUFBSSxDQUFiLEVBQWdCQSxJQUFJSixpQkFBaUJFLE1BQXJDLEVBQTZDRSxHQUE3QyxFQUFrRDtBQUNoRCxRQUFJQyxPQUFPTCxpQkFBaUJJLENBQWpCLENBQVg7O0FBRUEsUUFBSUEsSUFBSSxDQUFKLElBQVMsQ0FBQyxLQUFLRSxPQUFMLENBQWFDLGNBQTNCLEVBQTJDO0FBQ3pDUixlQUFTQSxTQUFTRyxNQUFULEdBQWtCLENBQTNCLEtBQWlDRyxJQUFqQztBQUNELEtBRkQsTUFFTztBQUNMLFVBQUksS0FBS0MsT0FBTCxDQUFhRSxnQkFBakIsRUFBbUM7QUFDakNILGVBQU9BLEtBQUtJLElBQUwsRUFBUDtBQUNEO0FBQ0RWLGVBQVNXLElBQVQsQ0FBY0wsSUFBZDtBQUNEO0FBQ0Y7O0FBRUQsU0FBT04sUUFBUDtBQUNELENBeEJEOztBQTBCTyxTQUFTTCxTQUFULENBQW1CaUIsTUFBbkIsRUFBMkJDLE1BQTNCLEVBQW1DQyxRQUFuQyxFQUE2QztBQUFFLFNBQU9qQixTQUFTa0IsSUFBVCxDQUFjSCxNQUFkLEVBQXNCQyxNQUF0QixFQUE4QkMsUUFBOUIsQ0FBUDtBQUFpRDtBQUNoRyxTQUFTbEIsZ0JBQVQsQ0FBMEJnQixNQUExQixFQUFrQ0MsTUFBbEMsRUFBMENDLFFBQTFDLEVBQW9EO0FBQ3pELE1BQUlQLFVBQVUsOEVBQWdCTyxRQUFoQixFQUEwQixFQUFDTCxrQkFBa0IsSUFBbkIsRUFBMUIsQ0FBZDtBQUNBLFNBQU9aLFNBQVNrQixJQUFULENBQWNILE1BQWQsRUFBc0JDLE1BQXRCLEVBQThCTixPQUE5QixDQUFQO0FBQ0QiLCJmaWxlIjoibGluZS5qcyIsInNvdXJjZXNDb250ZW50IjpbImltcG9ydCBEaWZmIGZyb20gJy4vYmFzZSc7XG5pbXBvcnQge2dlbmVyYXRlT3B0aW9uc30gZnJvbSAnLi4vdXRpbC9wYXJhbXMnO1xuXG5leHBvcnQgY29uc3QgbGluZURpZmYgPSBuZXcgRGlmZigpO1xubGluZURpZmYudG9rZW5pemUgPSBmdW5jdGlvbih2YWx1ZSkge1xuICBsZXQgcmV0TGluZXMgPSBbXSxcbiAgICAgIGxpbmVzQW5kTmV3bGluZXMgPSB2YWx1ZS5zcGxpdCgvKFxcbnxcXHJcXG4pLyk7XG5cbiAgLy8gSWdub3JlIHRoZSBmaW5hbCBlbXB0eSB0b2tlbiB0aGF0IG9jY3VycyBpZiB0aGUgc3RyaW5nIGVuZHMgd2l0aCBhIG5ldyBsaW5lXG4gIGlmICghbGluZXNBbmROZXdsaW5lc1tsaW5lc0FuZE5ld2xpbmVzLmxlbmd0aCAtIDFdKSB7XG4gICAgbGluZXNBbmROZXdsaW5lcy5wb3AoKTtcbiAgfVxuXG4gIC8vIE1lcmdlIHRoZSBjb250ZW50IGFuZCBsaW5lIHNlcGFyYXRvcnMgaW50byBzaW5nbGUgdG9rZW5zXG4gIGZvciAobGV0IGkgPSAwOyBpIDwgbGluZXNBbmROZXdsaW5lcy5sZW5ndGg7IGkrKykge1xuICAgIGxldCBsaW5lID0gbGluZXNBbmROZXdsaW5lc1tpXTtcblxuICAgIGlmIChpICUgMiAmJiAhdGhpcy5vcHRpb25zLm5ld2xpbmVJc1Rva2VuKSB7XG4gICAgICByZXRMaW5lc1tyZXRMaW5lcy5sZW5ndGggLSAxXSArPSBsaW5lO1xuICAgIH0gZWxzZSB7XG4gICAgICBpZiAodGhpcy5vcHRpb25zLmlnbm9yZVdoaXRlc3BhY2UpIHtcbiAgICAgICAgbGluZSA9IGxpbmUudHJpbSgpO1xuICAgICAgfVxuICAgICAgcmV0TGluZXMucHVzaChsaW5lKTtcbiAgICB9XG4gIH1cblxuICByZXR1cm4gcmV0TGluZXM7XG59O1xuXG5leHBvcnQgZnVuY3Rpb24gZGlmZkxpbmVzKG9sZFN0ciwgbmV3U3RyLCBjYWxsYmFjaykgeyByZXR1cm4gbGluZURpZmYuZGlmZihvbGRTdHIsIG5ld1N0ciwgY2FsbGJhY2spOyB9XG5leHBvcnQgZnVuY3Rpb24gZGlmZlRyaW1tZWRMaW5lcyhvbGRTdHIsIG5ld1N0ciwgY2FsbGJhY2spIHtcbiAgbGV0IG9wdGlvbnMgPSBnZW5lcmF0ZU9wdGlvbnMoY2FsbGJhY2ssIHtpZ25vcmVXaGl0ZXNwYWNlOiB0cnVlfSk7XG4gIHJldHVybiBsaW5lRGlmZi5kaWZmKG9sZFN0ciwgbmV3U3RyLCBvcHRpb25zKTtcbn1cbiJdfQ==
diff --git a/node_modules/diff/lib/diff/sentence.js b/node_modules/diff/lib/diff/sentence.js
new file mode 100644
index 0000000..c1dcb20
--- /dev/null
+++ b/node_modules/diff/lib/diff/sentence.js
@@ -0,0 +1,21 @@
+/*istanbul ignore start*/'use strict';
+
+exports.__esModule = true;
+exports.sentenceDiff = undefined;
+exports. /*istanbul ignore end*/diffSentences = diffSentences;
+
+var /*istanbul ignore start*/_base = require('./base') /*istanbul ignore end*/;
+
+/*istanbul ignore start*/var _base2 = _interopRequireDefault(_base);
+
+function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
+
+/*istanbul ignore end*/var sentenceDiff = /*istanbul ignore start*/exports. /*istanbul ignore end*/sentenceDiff = new /*istanbul ignore start*/_base2['default'] /*istanbul ignore end*/();
+sentenceDiff.tokenize = function (value) {
+  return value.split(/(\S.+?[.!?])(?=\s+|$)/);
+};
+
+function diffSentences(oldStr, newStr, callback) {
+  return sentenceDiff.diff(oldStr, newStr, callback);
+}
+//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9kaWZmL3NlbnRlbmNlLmpzIl0sIm5hbWVzIjpbImRpZmZTZW50ZW5jZXMiLCJzZW50ZW5jZURpZmYiLCJ0b2tlbml6ZSIsInZhbHVlIiwic3BsaXQiLCJvbGRTdHIiLCJuZXdTdHIiLCJjYWxsYmFjayIsImRpZmYiXSwibWFwcGluZ3MiOiI7Ozs7Z0NBUWdCQSxhLEdBQUFBLGE7O0FBUmhCOzs7Ozs7dUJBR08sSUFBTUMsdUZBQWUsd0VBQXJCO0FBQ1BBLGFBQWFDLFFBQWIsR0FBd0IsVUFBU0MsS0FBVCxFQUFnQjtBQUN0QyxTQUFPQSxNQUFNQyxLQUFOLENBQVksdUJBQVosQ0FBUDtBQUNELENBRkQ7O0FBSU8sU0FBU0osYUFBVCxDQUF1QkssTUFBdkIsRUFBK0JDLE1BQS9CLEVBQXVDQyxRQUF2QyxFQUFpRDtBQUFFLFNBQU9OLGFBQWFPLElBQWIsQ0FBa0JILE1BQWxCLEVBQTBCQyxNQUExQixFQUFrQ0MsUUFBbEMsQ0FBUDtBQUFxRCIsImZpbGUiOiJzZW50ZW5jZS5qcyIsInNvdXJjZXNDb250ZW50IjpbImltcG9ydCBEaWZmIGZyb20gJy4vYmFzZSc7XG5cblxuZXhwb3J0IGNvbnN0IHNlbnRlbmNlRGlmZiA9IG5ldyBEaWZmKCk7XG5zZW50ZW5jZURpZmYudG9rZW5pemUgPSBmdW5jdGlvbih2YWx1ZSkge1xuICByZXR1cm4gdmFsdWUuc3BsaXQoLyhcXFMuKz9bLiE/XSkoPz1cXHMrfCQpLyk7XG59O1xuXG5leHBvcnQgZnVuY3Rpb24gZGlmZlNlbnRlbmNlcyhvbGRTdHIsIG5ld1N0ciwgY2FsbGJhY2spIHsgcmV0dXJuIHNlbnRlbmNlRGlmZi5kaWZmKG9sZFN0ciwgbmV3U3RyLCBjYWxsYmFjayk7IH1cbiJdfQ==
diff --git a/node_modules/diff/lib/diff/word.js b/node_modules/diff/lib/diff/word.js
new file mode 100644
index 0000000..4af1b05
--- /dev/null
+++ b/node_modules/diff/lib/diff/word.js
@@ -0,0 +1,70 @@
+/*istanbul ignore start*/'use strict';
+
+exports.__esModule = true;
+exports.wordDiff = undefined;
+exports. /*istanbul ignore end*/diffWords = diffWords;
+/*istanbul ignore start*/exports. /*istanbul ignore end*/diffWordsWithSpace = diffWordsWithSpace;
+
+var /*istanbul ignore start*/_base = require('./base') /*istanbul ignore end*/;
+
+/*istanbul ignore start*/var _base2 = _interopRequireDefault(_base);
+
+/*istanbul ignore end*/var /*istanbul ignore start*/_params = require('../util/params') /*istanbul ignore end*/;
+
+/*istanbul ignore start*/function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
+
+/*istanbul ignore end*/ // Based on https://en.wikipedia.org/wiki/Latin_script_in_Unicode
+//
+// Ranges and exceptions:
+// Latin-1 Supplement, 0080–00FF
+//  - U+00D7  × Multiplication sign
+//  - U+00F7  ÷ Division sign
+// Latin Extended-A, 0100–017F
+// Latin Extended-B, 0180–024F
+// IPA Extensions, 0250–02AF
+// Spacing Modifier Letters, 02B0–02FF
+//  - U+02C7  ˇ ˇ  Caron
+//  - U+02D8  ˘ ˘  Breve
+//  - U+02D9  ˙ ˙  Dot Above
+//  - U+02DA  ˚ ˚  Ring Above
+//  - U+02DB  ˛ ˛  Ogonek
+//  - U+02DC  ˜ ˜  Small Tilde
+//  - U+02DD  ˝ ˝  Double Acute Accent
+// Latin Extended Additional, 1E00–1EFF
+var extendedWordChars = /^[A-Za-z\xC0-\u02C6\u02C8-\u02D7\u02DE-\u02FF\u1E00-\u1EFF]+$/;
+
+var reWhitespace = /\S/;
+
+var wordDiff = /*istanbul ignore start*/exports. /*istanbul ignore end*/wordDiff = new /*istanbul ignore start*/_base2['default'] /*istanbul ignore end*/();
+wordDiff.equals = function (left, right) {
+  if (this.options.ignoreCase) {
+    left = left.toLowerCase();
+    right = right.toLowerCase();
+  }
+  return left === right || this.options.ignoreWhitespace && !reWhitespace.test(left) && !reWhitespace.test(right);
+};
+wordDiff.tokenize = function (value) {
+  var tokens = value.split(/(\s+|\b)/);
+
+  // Join the boundary splits that we do not consider to be boundaries. This is primarily the extended Latin character set.
+  for (var i = 0; i < tokens.length - 1; i++) {
+    // If we have an empty string in the next field and we have only word chars before and after, merge
+    if (!tokens[i + 1] && tokens[i + 2] && extendedWordChars.test(tokens[i]) && extendedWordChars.test(tokens[i + 2])) {
+      tokens[i] += tokens[i + 2];
+      tokens.splice(i + 1, 2);
+      i--;
+    }
+  }
+
+  return tokens;
+};
+
+function diffWords(oldStr, newStr, options) {
+  options = /*istanbul ignore start*/(0, _params.generateOptions) /*istanbul ignore end*/(options, { ignoreWhitespace: true });
+  return wordDiff.diff(oldStr, newStr, options);
+}
+
+function diffWordsWithSpace(oldStr, newStr, options) {
+  return wordDiff.diff(oldStr, newStr, options);
+}
+//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9kaWZmL3dvcmQuanMiXSwibmFtZXMiOlsiZGlmZldvcmRzIiwiZGlmZldvcmRzV2l0aFNwYWNlIiwiZXh0ZW5kZWRXb3JkQ2hhcnMiLCJyZVdoaXRlc3BhY2UiLCJ3b3JkRGlmZiIsImVxdWFscyIsImxlZnQiLCJyaWdodCIsIm9wdGlvbnMiLCJpZ25vcmVDYXNlIiwidG9Mb3dlckNhc2UiLCJpZ25vcmVXaGl0ZXNwYWNlIiwidGVzdCIsInRva2VuaXplIiwidmFsdWUiLCJ0b2tlbnMiLCJzcGxpdCIsImkiLCJsZW5ndGgiLCJzcGxpY2UiLCJvbGRTdHIiLCJuZXdTdHIiLCJkaWZmIl0sIm1hcHBpbmdzIjoiOzs7O2dDQW1EZ0JBLFMsR0FBQUEsUzt5REFLQUMsa0IsR0FBQUEsa0I7O0FBeERoQjs7Ozt1QkFDQTs7Ozt3QkFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSxJQUFNQyxvQkFBb0IsK0RBQTFCOztBQUVBLElBQU1DLGVBQWUsSUFBckI7O0FBRU8sSUFBTUMsK0VBQVcsd0VBQWpCO0FBQ1BBLFNBQVNDLE1BQVQsR0FBa0IsVUFBU0MsSUFBVCxFQUFlQyxLQUFmLEVBQXNCO0FBQ3RDLE1BQUksS0FBS0MsT0FBTCxDQUFhQyxVQUFqQixFQUE2QjtBQUMzQkgsV0FBT0EsS0FBS0ksV0FBTCxFQUFQO0FBQ0FILFlBQVFBLE1BQU1HLFdBQU4sRUFBUjtBQUNEO0FBQ0QsU0FBT0osU0FBU0MsS0FBVCxJQUFtQixLQUFLQyxPQUFMLENBQWFHLGdCQUFiLElBQWlDLENBQUNSLGFBQWFTLElBQWIsQ0FBa0JOLElBQWxCLENBQWxDLElBQTZELENBQUNILGFBQWFTLElBQWIsQ0FBa0JMLEtBQWxCLENBQXhGO0FBQ0QsQ0FORDtBQU9BSCxTQUFTUyxRQUFULEdBQW9CLFVBQVNDLEtBQVQsRUFBZ0I7QUFDbEMsTUFBSUMsU0FBU0QsTUFBTUUsS0FBTixDQUFZLFVBQVosQ0FBYjs7QUFFQTtBQUNBLE9BQUssSUFBSUMsSUFBSSxDQUFiLEVBQWdCQSxJQUFJRixPQUFPRyxNQUFQLEdBQWdCLENBQXBDLEVBQXVDRCxHQUF2QyxFQUE0QztBQUMxQztBQUNBLFFBQUksQ0FBQ0YsT0FBT0UsSUFBSSxDQUFYLENBQUQsSUFBa0JGLE9BQU9FLElBQUksQ0FBWCxDQUFsQixJQUNLZixrQkFBa0JVLElBQWxCLENBQXVCRyxPQUFPRSxDQUFQLENBQXZCLENBREwsSUFFS2Ysa0JBQWtCVSxJQUFsQixDQUF1QkcsT0FBT0UsSUFBSSxDQUFYLENBQXZCLENBRlQsRUFFZ0Q7QUFDOUNGLGFBQU9FLENBQVAsS0FBYUYsT0FBT0UsSUFBSSxDQUFYLENBQWI7QUFDQUYsYUFBT0ksTUFBUCxDQUFjRixJQUFJLENBQWxCLEVBQXFCLENBQXJCO0FBQ0FBO0FBQ0Q7QUFDRjs7QUFFRCxTQUFPRixNQUFQO0FBQ0QsQ0FoQkQ7O0FBa0JPLFNBQVNmLFNBQVQsQ0FBbUJvQixNQUFuQixFQUEyQkMsTUFBM0IsRUFBbUNiLE9BQW5DLEVBQTRDO0FBQ2pEQSxZQUFVLDhFQUFnQkEsT0FBaEIsRUFBeUIsRUFBQ0csa0JBQWtCLElBQW5CLEVBQXpCLENBQVY7QUFDQSxTQUFPUCxTQUFTa0IsSUFBVCxDQUFjRixNQUFkLEVBQXNCQyxNQUF0QixFQUE4QmIsT0FBOUIsQ0FBUDtBQUNEOztBQUVNLFNBQVNQLGtCQUFULENBQTRCbUIsTUFBNUIsRUFBb0NDLE1BQXBDLEVBQTRDYixPQUE1QyxFQUFxRDtBQUMxRCxTQUFPSixTQUFTa0IsSUFBVCxDQUFjRixNQUFkLEVBQXNCQyxNQUF0QixFQUE4QmIsT0FBOUIsQ0FBUDtBQUNEIiwiZmlsZSI6IndvcmQuanMiLCJzb3VyY2VzQ29udGVudCI6WyJpbXBvcnQgRGlmZiBmcm9tICcuL2Jhc2UnO1xuaW1wb3J0IHtnZW5lcmF0ZU9wdGlvbnN9IGZyb20gJy4uL3V0aWwvcGFyYW1zJztcblxuLy8gQmFzZWQgb24gaHR0cHM6Ly9lbi53aWtpcGVkaWEub3JnL3dpa2kvTGF0aW5fc2NyaXB0X2luX1VuaWNvZGVcbi8vXG4vLyBSYW5nZXMgYW5kIGV4Y2VwdGlvbnM6XG4vLyBMYXRpbi0xIFN1cHBsZW1lbnQsIDAwODDigJMwMEZGXG4vLyAgLSBVKzAwRDcgIMOXIE11bHRpcGxpY2F0aW9uIHNpZ25cbi8vICAtIFUrMDBGNyAgw7cgRGl2aXNpb24gc2lnblxuLy8gTGF0aW4gRXh0ZW5kZWQtQSwgMDEwMOKAkzAxN0Zcbi8vIExhdGluIEV4dGVuZGVkLUIsIDAxODDigJMwMjRGXG4vLyBJUEEgRXh0ZW5zaW9ucywgMDI1MOKAkzAyQUZcbi8vIFNwYWNpbmcgTW9kaWZpZXIgTGV0dGVycywgMDJCMOKAkzAyRkZcbi8vICAtIFUrMDJDNyAgy4cgJiM3MTE7ICBDYXJvblxuLy8gIC0gVSswMkQ4ICDLmCAmIzcyODsgIEJyZXZlXG4vLyAgLSBVKzAyRDkgIMuZICYjNzI5OyAgRG90IEFib3ZlXG4vLyAgLSBVKzAyREEgIMuaICYjNzMwOyAgUmluZyBBYm92ZVxuLy8gIC0gVSswMkRCICDLmyAmIzczMTsgIE9nb25la1xuLy8gIC0gVSswMkRDICDLnCAmIzczMjsgIFNtYWxsIFRpbGRlXG4vLyAgLSBVKzAyREQgIMudICYjNzMzOyAgRG91YmxlIEFjdXRlIEFjY2VudFxuLy8gTGF0aW4gRXh0ZW5kZWQgQWRkaXRpb25hbCwgMUUwMOKAkzFFRkZcbmNvbnN0IGV4dGVuZGVkV29yZENoYXJzID0gL15bYS16QS1aXFx1e0MwfS1cXHV7RkZ9XFx1e0Q4fS1cXHV7RjZ9XFx1e0Y4fS1cXHV7MkM2fVxcdXsyQzh9LVxcdXsyRDd9XFx1ezJERX0tXFx1ezJGRn1cXHV7MUUwMH0tXFx1ezFFRkZ9XSskL3U7XG5cbmNvbnN0IHJlV2hpdGVzcGFjZSA9IC9cXFMvO1xuXG5leHBvcnQgY29uc3Qgd29yZERpZmYgPSBuZXcgRGlmZigpO1xud29yZERpZmYuZXF1YWxzID0gZnVuY3Rpb24obGVmdCwgcmlnaHQpIHtcbiAgaWYgKHRoaXMub3B0aW9ucy5pZ25vcmVDYXNlKSB7XG4gICAgbGVmdCA9IGxlZnQudG9Mb3dlckNhc2UoKTtcbiAgICByaWdodCA9IHJpZ2h0LnRvTG93ZXJDYXNlKCk7XG4gIH1cbiAgcmV0dXJuIGxlZnQgPT09IHJpZ2h0IHx8ICh0aGlzLm9wdGlvbnMuaWdub3JlV2hpdGVzcGFjZSAmJiAhcmVXaGl0ZXNwYWNlLnRlc3QobGVmdCkgJiYgIXJlV2hpdGVzcGFjZS50ZXN0KHJpZ2h0KSk7XG59O1xud29yZERpZmYudG9rZW5pemUgPSBmdW5jdGlvbih2YWx1ZSkge1xuICBsZXQgdG9rZW5zID0gdmFsdWUuc3BsaXQoLyhcXHMrfFxcYikvKTtcblxuICAvLyBKb2luIHRoZSBib3VuZGFyeSBzcGxpdHMgdGhhdCB3ZSBkbyBub3QgY29uc2lkZXIgdG8gYmUgYm91bmRhcmllcy4gVGhpcyBpcyBwcmltYXJpbHkgdGhlIGV4dGVuZGVkIExhdGluIGNoYXJhY3RlciBzZXQuXG4gIGZvciAobGV0IGkgPSAwOyBpIDwgdG9rZW5zLmxlbmd0aCAtIDE7IGkrKykge1xuICAgIC8vIElmIHdlIGhhdmUgYW4gZW1wdHkgc3RyaW5nIGluIHRoZSBuZXh0IGZpZWxkIGFuZCB3ZSBoYXZlIG9ubHkgd29yZCBjaGFycyBiZWZvcmUgYW5kIGFmdGVyLCBtZXJnZVxuICAgIGlmICghdG9rZW5zW2kgKyAxXSAmJiB0b2tlbnNbaSArIDJdXG4gICAgICAgICAgJiYgZXh0ZW5kZWRXb3JkQ2hhcnMudGVzdCh0b2tlbnNbaV0pXG4gICAgICAgICAgJiYgZXh0ZW5kZWRXb3JkQ2hhcnMudGVzdCh0b2tlbnNbaSArIDJdKSkge1xuICAgICAgdG9rZW5zW2ldICs9IHRva2Vuc1tpICsgMl07XG4gICAgICB0b2tlbnMuc3BsaWNlKGkgKyAxLCAyKTtcbiAgICAgIGktLTtcbiAgICB9XG4gIH1cblxuICByZXR1cm4gdG9rZW5zO1xufTtcblxuZXhwb3J0IGZ1bmN0aW9uIGRpZmZXb3JkcyhvbGRTdHIsIG5ld1N0ciwgb3B0aW9ucykge1xuICBvcHRpb25zID0gZ2VuZXJhdGVPcHRpb25zKG9wdGlvbnMsIHtpZ25vcmVXaGl0ZXNwYWNlOiB0cnVlfSk7XG4gIHJldHVybiB3b3JkRGlmZi5kaWZmKG9sZFN0ciwgbmV3U3RyLCBvcHRpb25zKTtcbn1cblxuZXhwb3J0IGZ1bmN0aW9uIGRpZmZXb3Jkc1dpdGhTcGFjZShvbGRTdHIsIG5ld1N0ciwgb3B0aW9ucykge1xuICByZXR1cm4gd29yZERpZmYuZGlmZihvbGRTdHIsIG5ld1N0ciwgb3B0aW9ucyk7XG59XG4iXX0=
diff --git a/node_modules/diff/lib/index.js b/node_modules/diff/lib/index.js
new file mode 100644
index 0000000..8608caf
--- /dev/null
+++ b/node_modules/diff/lib/index.js
@@ -0,0 +1,74 @@
+/*istanbul ignore start*/'use strict';
+
+exports.__esModule = true;
+exports.canonicalize = exports.convertChangesToXML = exports.convertChangesToDMP = exports.merge = exports.parsePatch = exports.applyPatches = exports.applyPatch = exports.createPatch = exports.createTwoFilesPatch = exports.structuredPatch = exports.diffArrays = exports.diffJson = exports.diffCss = exports.diffSentences = exports.diffTrimmedLines = exports.diffLines = exports.diffWordsWithSpace = exports.diffWords = exports.diffChars = exports.Diff = undefined;
+
+/*istanbul ignore end*/var /*istanbul ignore start*/_base = require('./diff/base') /*istanbul ignore end*/;
+
+/*istanbul ignore start*/var _base2 = _interopRequireDefault(_base);
+
+/*istanbul ignore end*/var /*istanbul ignore start*/_character = require('./diff/character') /*istanbul ignore end*/;
+
+var /*istanbul ignore start*/_word = require('./diff/word') /*istanbul ignore end*/;
+
+var /*istanbul ignore start*/_line = require('./diff/line') /*istanbul ignore end*/;
+
+var /*istanbul ignore start*/_sentence = require('./diff/sentence') /*istanbul ignore end*/;
+
+var /*istanbul ignore start*/_css = require('./diff/css') /*istanbul ignore end*/;
+
+var /*istanbul ignore start*/_json = require('./diff/json') /*istanbul ignore end*/;
+
+var /*istanbul ignore start*/_array = require('./diff/array') /*istanbul ignore end*/;
+
+var /*istanbul ignore start*/_apply = require('./patch/apply') /*istanbul ignore end*/;
+
+var /*istanbul ignore start*/_parse = require('./patch/parse') /*istanbul ignore end*/;
+
+var /*istanbul ignore start*/_merge = require('./patch/merge') /*istanbul ignore end*/;
+
+var /*istanbul ignore start*/_create = require('./patch/create') /*istanbul ignore end*/;
+
+var /*istanbul ignore start*/_dmp = require('./convert/dmp') /*istanbul ignore end*/;
+
+var /*istanbul ignore start*/_xml = require('./convert/xml') /*istanbul ignore end*/;
+
+/*istanbul ignore start*/function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
+
+/* See LICENSE file for terms of use */
+
+/*
+ * Text diff implementation.
+ *
+ * This library supports the following APIS:
+ * JsDiff.diffChars: Character by character diff
+ * JsDiff.diffWords: Word (as defined by \b regex) diff which ignores whitespace
+ * JsDiff.diffLines: Line based diff
+ *
+ * JsDiff.diffCss: Diff targeted at CSS content
+ *
+ * These methods are based on the implementation proposed in
+ * "An O(ND) Difference Algorithm and its Variations" (Myers, 1986).
+ * http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.4.6927
+ */
+exports. /*istanbul ignore end*/Diff = _base2['default'];
+/*istanbul ignore start*/exports. /*istanbul ignore end*/diffChars = _character.diffChars;
+/*istanbul ignore start*/exports. /*istanbul ignore end*/diffWords = _word.diffWords;
+/*istanbul ignore start*/exports. /*istanbul ignore end*/diffWordsWithSpace = _word.diffWordsWithSpace;
+/*istanbul ignore start*/exports. /*istanbul ignore end*/diffLines = _line.diffLines;
+/*istanbul ignore start*/exports. /*istanbul ignore end*/diffTrimmedLines = _line.diffTrimmedLines;
+/*istanbul ignore start*/exports. /*istanbul ignore end*/diffSentences = _sentence.diffSentences;
+/*istanbul ignore start*/exports. /*istanbul ignore end*/diffCss = _css.diffCss;
+/*istanbul ignore start*/exports. /*istanbul ignore end*/diffJson = _json.diffJson;
+/*istanbul ignore start*/exports. /*istanbul ignore end*/diffArrays = _array.diffArrays;
+/*istanbul ignore start*/exports. /*istanbul ignore end*/structuredPatch = _create.structuredPatch;
+/*istanbul ignore start*/exports. /*istanbul ignore end*/createTwoFilesPatch = _create.createTwoFilesPatch;
+/*istanbul ignore start*/exports. /*istanbul ignore end*/createPatch = _create.createPatch;
+/*istanbul ignore start*/exports. /*istanbul ignore end*/applyPatch = _apply.applyPatch;
+/*istanbul ignore start*/exports. /*istanbul ignore end*/applyPatches = _apply.applyPatches;
+/*istanbul ignore start*/exports. /*istanbul ignore end*/parsePatch = _parse.parsePatch;
+/*istanbul ignore start*/exports. /*istanbul ignore end*/merge = _merge.merge;
+/*istanbul ignore start*/exports. /*istanbul ignore end*/convertChangesToDMP = _dmp.convertChangesToDMP;
+/*istanbul ignore start*/exports. /*istanbul ignore end*/convertChangesToXML = _xml.convertChangesToXML;
+/*istanbul ignore start*/exports. /*istanbul ignore end*/canonicalize = _json.canonicalize;
+//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uL3NyYy9pbmRleC5qcyJdLCJuYW1lcyI6WyJEaWZmIiwiZGlmZkNoYXJzIiwiZGlmZldvcmRzIiwiZGlmZldvcmRzV2l0aFNwYWNlIiwiZGlmZkxpbmVzIiwiZGlmZlRyaW1tZWRMaW5lcyIsImRpZmZTZW50ZW5jZXMiLCJkaWZmQ3NzIiwiZGlmZkpzb24iLCJkaWZmQXJyYXlzIiwic3RydWN0dXJlZFBhdGNoIiwiY3JlYXRlVHdvRmlsZXNQYXRjaCIsImNyZWF0ZVBhdGNoIiwiYXBwbHlQYXRjaCIsImFwcGx5UGF0Y2hlcyIsInBhcnNlUGF0Y2giLCJtZXJnZSIsImNvbnZlcnRDaGFuZ2VzVG9ETVAiLCJjb252ZXJ0Q2hhbmdlc1RvWE1MIiwiY2Fub25pY2FsaXplIl0sIm1hcHBpbmdzIjoiOzs7Ozt1QkFnQkE7Ozs7dUJBQ0E7O0FBQ0E7O0FBQ0E7O0FBQ0E7O0FBRUE7O0FBQ0E7O0FBRUE7O0FBRUE7O0FBQ0E7O0FBQ0E7O0FBQ0E7O0FBRUE7O0FBQ0E7Ozs7QUFqQ0E7O0FBRUE7Ozs7Ozs7Ozs7Ozs7O2dDQWtDRUEsSTt5REFFQUMsUzt5REFDQUMsUzt5REFDQUMsa0I7eURBQ0FDLFM7eURBQ0FDLGdCO3lEQUNBQyxhO3lEQUVBQyxPO3lEQUNBQyxRO3lEQUVBQyxVO3lEQUVBQyxlO3lEQUNBQyxtQjt5REFDQUMsVzt5REFDQUMsVTt5REFDQUMsWTt5REFDQUMsVTt5REFDQUMsSzt5REFDQUMsbUI7eURBQ0FDLG1CO3lEQUNBQyxZIiwiZmlsZSI6ImluZGV4LmpzIiwic291cmNlc0NvbnRlbnQiOlsiLyogU2VlIExJQ0VOU0UgZmlsZSBmb3IgdGVybXMgb2YgdXNlICovXG5cbi8qXG4gKiBUZXh0IGRpZmYgaW1wbGVtZW50YXRpb24uXG4gKlxuICogVGhpcyBsaWJyYXJ5IHN1cHBvcnRzIHRoZSBmb2xsb3dpbmcgQVBJUzpcbiAqIEpzRGlmZi5kaWZmQ2hhcnM6IENoYXJhY3RlciBieSBjaGFyYWN0ZXIgZGlmZlxuICogSnNEaWZmLmRpZmZXb3JkczogV29yZCAoYXMgZGVmaW5lZCBieSBcXGIgcmVnZXgpIGRpZmYgd2hpY2ggaWdub3JlcyB3aGl0ZXNwYWNlXG4gKiBKc0RpZmYuZGlmZkxpbmVzOiBMaW5lIGJhc2VkIGRpZmZcbiAqXG4gKiBKc0RpZmYuZGlmZkNzczogRGlmZiB0YXJnZXRlZCBhdCBDU1MgY29udGVudFxuICpcbiAqIFRoZXNlIG1ldGhvZHMgYXJlIGJhc2VkIG9uIHRoZSBpbXBsZW1lbnRhdGlvbiBwcm9wb3NlZCBpblxuICogXCJBbiBPKE5EKSBEaWZmZXJlbmNlIEFsZ29yaXRobSBhbmQgaXRzIFZhcmlhdGlvbnNcIiAoTXllcnMsIDE5ODYpLlxuICogaHR0cDovL2NpdGVzZWVyeC5pc3QucHN1LmVkdS92aWV3ZG9jL3N1bW1hcnk/ZG9pPTEwLjEuMS40LjY5MjdcbiAqL1xuaW1wb3J0IERpZmYgZnJvbSAnLi9kaWZmL2Jhc2UnO1xuaW1wb3J0IHtkaWZmQ2hhcnN9IGZyb20gJy4vZGlmZi9jaGFyYWN0ZXInO1xuaW1wb3J0IHtkaWZmV29yZHMsIGRpZmZXb3Jkc1dpdGhTcGFjZX0gZnJvbSAnLi9kaWZmL3dvcmQnO1xuaW1wb3J0IHtkaWZmTGluZXMsIGRpZmZUcmltbWVkTGluZXN9IGZyb20gJy4vZGlmZi9saW5lJztcbmltcG9ydCB7ZGlmZlNlbnRlbmNlc30gZnJvbSAnLi9kaWZmL3NlbnRlbmNlJztcblxuaW1wb3J0IHtkaWZmQ3NzfSBmcm9tICcuL2RpZmYvY3NzJztcbmltcG9ydCB7ZGlmZkpzb24sIGNhbm9uaWNhbGl6ZX0gZnJvbSAnLi9kaWZmL2pzb24nO1xuXG5pbXBvcnQge2RpZmZBcnJheXN9IGZyb20gJy4vZGlmZi9hcnJheSc7XG5cbmltcG9ydCB7YXBwbHlQYXRjaCwgYXBwbHlQYXRjaGVzfSBmcm9tICcuL3BhdGNoL2FwcGx5JztcbmltcG9ydCB7cGFyc2VQYXRjaH0gZnJvbSAnLi9wYXRjaC9wYXJzZSc7XG5pbXBvcnQge21lcmdlfSBmcm9tICcuL3BhdGNoL21lcmdlJztcbmltcG9ydCB7c3RydWN0dXJlZFBhdGNoLCBjcmVhdGVUd29GaWxlc1BhdGNoLCBjcmVhdGVQYXRjaH0gZnJvbSAnLi9wYXRjaC9jcmVhdGUnO1xuXG5pbXBvcnQge2NvbnZlcnRDaGFuZ2VzVG9ETVB9IGZyb20gJy4vY29udmVydC9kbXAnO1xuaW1wb3J0IHtjb252ZXJ0Q2hhbmdlc1RvWE1MfSBmcm9tICcuL2NvbnZlcnQveG1sJztcblxuZXhwb3J0IHtcbiAgRGlmZixcblxuICBkaWZmQ2hhcnMsXG4gIGRpZmZXb3JkcyxcbiAgZGlmZldvcmRzV2l0aFNwYWNlLFxuICBkaWZmTGluZXMsXG4gIGRpZmZUcmltbWVkTGluZXMsXG4gIGRpZmZTZW50ZW5jZXMsXG5cbiAgZGlmZkNzcyxcbiAgZGlmZkpzb24sXG5cbiAgZGlmZkFycmF5cyxcblxuICBzdHJ1Y3R1cmVkUGF0Y2gsXG4gIGNyZWF0ZVR3b0ZpbGVzUGF0Y2gsXG4gIGNyZWF0ZVBhdGNoLFxuICBhcHBseVBhdGNoLFxuICBhcHBseVBhdGNoZXMsXG4gIHBhcnNlUGF0Y2gsXG4gIG1lcmdlLFxuICBjb252ZXJ0Q2hhbmdlc1RvRE1QLFxuICBjb252ZXJ0Q2hhbmdlc1RvWE1MLFxuICBjYW5vbmljYWxpemVcbn07XG4iXX0=
diff --git a/node_modules/diff/lib/patch/apply.js b/node_modules/diff/lib/patch/apply.js
new file mode 100644
index 0000000..fa83015
--- /dev/null
+++ b/node_modules/diff/lib/patch/apply.js
@@ -0,0 +1,180 @@
+/*istanbul ignore start*/'use strict';
+
+exports.__esModule = true;
+exports. /*istanbul ignore end*/applyPatch = applyPatch;
+/*istanbul ignore start*/exports. /*istanbul ignore end*/applyPatches = applyPatches;
+
+var /*istanbul ignore start*/_parse = require('./parse') /*istanbul ignore end*/;
+
+var /*istanbul ignore start*/_distanceIterator = require('../util/distance-iterator') /*istanbul ignore end*/;
+
+/*istanbul ignore start*/var _distanceIterator2 = _interopRequireDefault(_distanceIterator);
+
+function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
+
+/*istanbul ignore end*/function applyPatch(source, uniDiff) {
+  /*istanbul ignore start*/var /*istanbul ignore end*/options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
+
+  if (typeof uniDiff === 'string') {
+    uniDiff = /*istanbul ignore start*/(0, _parse.parsePatch) /*istanbul ignore end*/(uniDiff);
+  }
+
+  if (Array.isArray(uniDiff)) {
+    if (uniDiff.length > 1) {
+      throw new Error('applyPatch only works with a single input.');
+    }
+
+    uniDiff = uniDiff[0];
+  }
+
+  // Apply the diff to the input
+  var lines = source.split(/\r\n|[\n\v\f\r\x85]/),
+      delimiters = source.match(/\r\n|[\n\v\f\r\x85]/g) || [],
+      hunks = uniDiff.hunks,
+      compareLine = options.compareLine || function (lineNumber, line, operation, patchContent) /*istanbul ignore start*/{
+    return (/*istanbul ignore end*/line === patchContent
+    );
+  },
+      errorCount = 0,
+      fuzzFactor = options.fuzzFactor || 0,
+      minLine = 0,
+      offset = 0,
+      removeEOFNL = /*istanbul ignore start*/void 0 /*istanbul ignore end*/,
+      addEOFNL = /*istanbul ignore start*/void 0 /*istanbul ignore end*/;
+
+  /**
+   * Checks if the hunk exactly fits on the provided location
+   */
+  function hunkFits(hunk, toPos) {
+    for (var j = 0; j < hunk.lines.length; j++) {
+      var line = hunk.lines[j],
+          operation = line.length > 0 ? line[0] : ' ',
+          content = line.length > 0 ? line.substr(1) : line;
+
+      if (operation === ' ' || operation === '-') {
+        // Context sanity check
+        if (!compareLine(toPos + 1, lines[toPos], operation, content)) {
+          errorCount++;
+
+          if (errorCount > fuzzFactor) {
+            return false;
+          }
+        }
+        toPos++;
+      }
+    }
+
+    return true;
+  }
+
+  // Search best fit offsets for each hunk based on the previous ones
+  for (var i = 0; i < hunks.length; i++) {
+    var hunk = hunks[i],
+        maxLine = lines.length - hunk.oldLines,
+        localOffset = 0,
+        toPos = offset + hunk.oldStart - 1;
+
+    var iterator = /*istanbul ignore start*/(0, _distanceIterator2['default']) /*istanbul ignore end*/(toPos, minLine, maxLine);
+
+    for (; localOffset !== undefined; localOffset = iterator()) {
+      if (hunkFits(hunk, toPos + localOffset)) {
+        hunk.offset = offset += localOffset;
+        break;
+      }
+    }
+
+    if (localOffset === undefined) {
+      return false;
+    }
+
+    // Set lower text limit to end of the current hunk, so next ones don't try
+    // to fit over already patched text
+    minLine = hunk.offset + hunk.oldStart + hunk.oldLines;
+  }
+
+  // Apply patch hunks
+  var diffOffset = 0;
+  for (var _i = 0; _i < hunks.length; _i++) {
+    var _hunk = hunks[_i],
+        _toPos = _hunk.oldStart + _hunk.offset + diffOffset - 1;
+    diffOffset += _hunk.newLines - _hunk.oldLines;
+
+    if (_toPos < 0) {
+      // Creating a new file
+      _toPos = 0;
+    }
+
+    for (var j = 0; j < _hunk.lines.length; j++) {
+      var line = _hunk.lines[j],
+          operation = line.length > 0 ? line[0] : ' ',
+          content = line.length > 0 ? line.substr(1) : line,
+          delimiter = _hunk.linedelimiters[j];
+
+      if (operation === ' ') {
+        _toPos++;
+      } else if (operation === '-') {
+        lines.splice(_toPos, 1);
+        delimiters.splice(_toPos, 1);
+        /* istanbul ignore else */
+      } else if (operation === '+') {
+        lines.splice(_toPos, 0, content);
+        delimiters.splice(_toPos, 0, delimiter);
+        _toPos++;
+      } else if (operation === '\\') {
+        var previousOperation = _hunk.lines[j - 1] ? _hunk.lines[j - 1][0] : null;
+        if (previousOperation === '+') {
+          removeEOFNL = true;
+        } else if (previousOperation === '-') {
+          addEOFNL = true;
+        }
+      }
+    }
+  }
+
+  // Handle EOFNL insertion/removal
+  if (removeEOFNL) {
+    while (!lines[lines.length - 1]) {
+      lines.pop();
+      delimiters.pop();
+    }
+  } else if (addEOFNL) {
+    lines.push('');
+    delimiters.push('\n');
+  }
+  for (var _k = 0; _k < lines.length - 1; _k++) {
+    lines[_k] = lines[_k] + delimiters[_k];
+  }
+  return lines.join('');
+}
+
+// Wrapper that supports multiple file patches via callbacks.
+function applyPatches(uniDiff, options) {
+  if (typeof uniDiff === 'string') {
+    uniDiff = /*istanbul ignore start*/(0, _parse.parsePatch) /*istanbul ignore end*/(uniDiff);
+  }
+
+  var currentIndex = 0;
+  function processIndex() {
+    var index = uniDiff[currentIndex++];
+    if (!index) {
+      return options.complete();
+    }
+
+    options.loadFile(index, function (err, data) {
+      if (err) {
+        return options.complete(err);
+      }
+
+      var updatedContent = applyPatch(data, index, options);
+      options.patched(index, updatedContent, function (err) {
+        if (err) {
+          return options.complete(err);
+        }
+
+        processIndex();
+      });
+    });
+  }
+  processIndex();
+}
+//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9wYXRjaC9hcHBseS5qcyJdLCJuYW1lcyI6WyJhcHBseVBhdGNoIiwiYXBwbHlQYXRjaGVzIiwic291cmNlIiwidW5pRGlmZiIsIm9wdGlvbnMiLCJBcnJheSIsImlzQXJyYXkiLCJsZW5ndGgiLCJFcnJvciIsImxpbmVzIiwic3BsaXQiLCJkZWxpbWl0ZXJzIiwibWF0Y2giLCJodW5rcyIsImNvbXBhcmVMaW5lIiwibGluZU51bWJlciIsImxpbmUiLCJvcGVyYXRpb24iLCJwYXRjaENvbnRlbnQiLCJlcnJvckNvdW50IiwiZnV6ekZhY3RvciIsIm1pbkxpbmUiLCJvZmZzZXQiLCJyZW1vdmVFT0ZOTCIsImFkZEVPRk5MIiwiaHVua0ZpdHMiLCJodW5rIiwidG9Qb3MiLCJqIiwiY29udGVudCIsInN1YnN0ciIsImkiLCJtYXhMaW5lIiwib2xkTGluZXMiLCJsb2NhbE9mZnNldCIsIm9sZFN0YXJ0IiwiaXRlcmF0b3IiLCJ1bmRlZmluZWQiLCJkaWZmT2Zmc2V0IiwibmV3TGluZXMiLCJkZWxpbWl0ZXIiLCJsaW5lZGVsaW1pdGVycyIsInNwbGljZSIsInByZXZpb3VzT3BlcmF0aW9uIiwicG9wIiwicHVzaCIsIl9rIiwiam9pbiIsImN1cnJlbnRJbmRleCIsInByb2Nlc3NJbmRleCIsImluZGV4IiwiY29tcGxldGUiLCJsb2FkRmlsZSIsImVyciIsImRhdGEiLCJ1cGRhdGVkQ29udGVudCIsInBhdGNoZWQiXSwibWFwcGluZ3MiOiI7OztnQ0FHZ0JBLFUsR0FBQUEsVTt5REFvSUFDLFksR0FBQUEsWTs7QUF2SWhCOztBQUNBOzs7Ozs7dUJBRU8sU0FBU0QsVUFBVCxDQUFvQkUsTUFBcEIsRUFBNEJDLE9BQTVCLEVBQW1EO0FBQUEsc0RBQWRDLE9BQWMsdUVBQUosRUFBSTs7QUFDeEQsTUFBSSxPQUFPRCxPQUFQLEtBQW1CLFFBQXZCLEVBQWlDO0FBQy9CQSxjQUFVLHdFQUFXQSxPQUFYLENBQVY7QUFDRDs7QUFFRCxNQUFJRSxNQUFNQyxPQUFOLENBQWNILE9BQWQsQ0FBSixFQUE0QjtBQUMxQixRQUFJQSxRQUFRSSxNQUFSLEdBQWlCLENBQXJCLEVBQXdCO0FBQ3RCLFlBQU0sSUFBSUMsS0FBSixDQUFVLDRDQUFWLENBQU47QUFDRDs7QUFFREwsY0FBVUEsUUFBUSxDQUFSLENBQVY7QUFDRDs7QUFFRDtBQUNBLE1BQUlNLFFBQVFQLE9BQU9RLEtBQVAsQ0FBYSxxQkFBYixDQUFaO0FBQUEsTUFDSUMsYUFBYVQsT0FBT1UsS0FBUCxDQUFhLHNCQUFiLEtBQXdDLEVBRHpEO0FBQUEsTUFFSUMsUUFBUVYsUUFBUVUsS0FGcEI7QUFBQSxNQUlJQyxjQUFjVixRQUFRVSxXQUFSLElBQXdCLFVBQUNDLFVBQUQsRUFBYUMsSUFBYixFQUFtQkMsU0FBbkIsRUFBOEJDLFlBQTlCO0FBQUEsbUNBQStDRixTQUFTRTtBQUF4RDtBQUFBLEdBSjFDO0FBQUEsTUFLSUMsYUFBYSxDQUxqQjtBQUFBLE1BTUlDLGFBQWFoQixRQUFRZ0IsVUFBUixJQUFzQixDQU52QztBQUFBLE1BT0lDLFVBQVUsQ0FQZDtBQUFBLE1BUUlDLFNBQVMsQ0FSYjtBQUFBLE1BVUlDLDZDQVZKO0FBQUEsTUFXSUMsMENBWEo7O0FBYUE7OztBQUdBLFdBQVNDLFFBQVQsQ0FBa0JDLElBQWxCLEVBQXdCQyxLQUF4QixFQUErQjtBQUM3QixTQUFLLElBQUlDLElBQUksQ0FBYixFQUFnQkEsSUFBSUYsS0FBS2pCLEtBQUwsQ0FBV0YsTUFBL0IsRUFBdUNxQixHQUF2QyxFQUE0QztBQUMxQyxVQUFJWixPQUFPVSxLQUFLakIsS0FBTCxDQUFXbUIsQ0FBWCxDQUFYO0FBQUEsVUFDSVgsWUFBYUQsS0FBS1QsTUFBTCxHQUFjLENBQWQsR0FBa0JTLEtBQUssQ0FBTCxDQUFsQixHQUE0QixHQUQ3QztBQUFBLFVBRUlhLFVBQVdiLEtBQUtULE1BQUwsR0FBYyxDQUFkLEdBQWtCUyxLQUFLYyxNQUFMLENBQVksQ0FBWixDQUFsQixHQUFtQ2QsSUFGbEQ7O0FBSUEsVUFBSUMsY0FBYyxHQUFkLElBQXFCQSxjQUFjLEdBQXZDLEVBQTRDO0FBQzFDO0FBQ0EsWUFBSSxDQUFDSCxZQUFZYSxRQUFRLENBQXBCLEVBQXVCbEIsTUFBTWtCLEtBQU4sQ0FBdkIsRUFBcUNWLFNBQXJDLEVBQWdEWSxPQUFoRCxDQUFMLEVBQStEO0FBQzdEVjs7QUFFQSxjQUFJQSxhQUFhQyxVQUFqQixFQUE2QjtBQUMzQixtQkFBTyxLQUFQO0FBQ0Q7QUFDRjtBQUNETztBQUNEO0FBQ0Y7O0FBRUQsV0FBTyxJQUFQO0FBQ0Q7O0FBRUQ7QUFDQSxPQUFLLElBQUlJLElBQUksQ0FBYixFQUFnQkEsSUFBSWxCLE1BQU1OLE1BQTFCLEVBQWtDd0IsR0FBbEMsRUFBdUM7QUFDckMsUUFBSUwsT0FBT2IsTUFBTWtCLENBQU4sQ0FBWDtBQUFBLFFBQ0lDLFVBQVV2QixNQUFNRixNQUFOLEdBQWVtQixLQUFLTyxRQURsQztBQUFBLFFBRUlDLGNBQWMsQ0FGbEI7QUFBQSxRQUdJUCxRQUFRTCxTQUFTSSxLQUFLUyxRQUFkLEdBQXlCLENBSHJDOztBQUtBLFFBQUlDLFdBQVcsb0ZBQWlCVCxLQUFqQixFQUF3Qk4sT0FBeEIsRUFBaUNXLE9BQWpDLENBQWY7O0FBRUEsV0FBT0UsZ0JBQWdCRyxTQUF2QixFQUFrQ0gsY0FBY0UsVUFBaEQsRUFBNEQ7QUFDMUQsVUFBSVgsU0FBU0MsSUFBVCxFQUFlQyxRQUFRTyxXQUF2QixDQUFKLEVBQXlDO0FBQ3ZDUixhQUFLSixNQUFMLEdBQWNBLFVBQVVZLFdBQXhCO0FBQ0E7QUFDRDtBQUNGOztBQUVELFFBQUlBLGdCQUFnQkcsU0FBcEIsRUFBK0I7QUFDN0IsYUFBTyxLQUFQO0FBQ0Q7O0FBRUQ7QUFDQTtBQUNBaEIsY0FBVUssS0FBS0osTUFBTCxHQUFjSSxLQUFLUyxRQUFuQixHQUE4QlQsS0FBS08sUUFBN0M7QUFDRDs7QUFFRDtBQUNBLE1BQUlLLGFBQWEsQ0FBakI7QUFDQSxPQUFLLElBQUlQLEtBQUksQ0FBYixFQUFnQkEsS0FBSWxCLE1BQU1OLE1BQTFCLEVBQWtDd0IsSUFBbEMsRUFBdUM7QUFDckMsUUFBSUwsUUFBT2IsTUFBTWtCLEVBQU4sQ0FBWDtBQUFBLFFBQ0lKLFNBQVFELE1BQUtTLFFBQUwsR0FBZ0JULE1BQUtKLE1BQXJCLEdBQThCZ0IsVUFBOUIsR0FBMkMsQ0FEdkQ7QUFFQUEsa0JBQWNaLE1BQUthLFFBQUwsR0FBZ0JiLE1BQUtPLFFBQW5DOztBQUVBLFFBQUlOLFNBQVEsQ0FBWixFQUFlO0FBQUU7QUFDZkEsZUFBUSxDQUFSO0FBQ0Q7O0FBRUQsU0FBSyxJQUFJQyxJQUFJLENBQWIsRUFBZ0JBLElBQUlGLE1BQUtqQixLQUFMLENBQVdGLE1BQS9CLEVBQXVDcUIsR0FBdkMsRUFBNEM7QUFDMUMsVUFBSVosT0FBT1UsTUFBS2pCLEtBQUwsQ0FBV21CLENBQVgsQ0FBWDtBQUFBLFVBQ0lYLFlBQWFELEtBQUtULE1BQUwsR0FBYyxDQUFkLEdBQWtCUyxLQUFLLENBQUwsQ0FBbEIsR0FBNEIsR0FEN0M7QUFBQSxVQUVJYSxVQUFXYixLQUFLVCxNQUFMLEdBQWMsQ0FBZCxHQUFrQlMsS0FBS2MsTUFBTCxDQUFZLENBQVosQ0FBbEIsR0FBbUNkLElBRmxEO0FBQUEsVUFHSXdCLFlBQVlkLE1BQUtlLGNBQUwsQ0FBb0JiLENBQXBCLENBSGhCOztBQUtBLFVBQUlYLGNBQWMsR0FBbEIsRUFBdUI7QUFDckJVO0FBQ0QsT0FGRCxNQUVPLElBQUlWLGNBQWMsR0FBbEIsRUFBdUI7QUFDNUJSLGNBQU1pQyxNQUFOLENBQWFmLE1BQWIsRUFBb0IsQ0FBcEI7QUFDQWhCLG1CQUFXK0IsTUFBWCxDQUFrQmYsTUFBbEIsRUFBeUIsQ0FBekI7QUFDRjtBQUNDLE9BSk0sTUFJQSxJQUFJVixjQUFjLEdBQWxCLEVBQXVCO0FBQzVCUixjQUFNaUMsTUFBTixDQUFhZixNQUFiLEVBQW9CLENBQXBCLEVBQXVCRSxPQUF2QjtBQUNBbEIsbUJBQVcrQixNQUFYLENBQWtCZixNQUFsQixFQUF5QixDQUF6QixFQUE0QmEsU0FBNUI7QUFDQWI7QUFDRCxPQUpNLE1BSUEsSUFBSVYsY0FBYyxJQUFsQixFQUF3QjtBQUM3QixZQUFJMEIsb0JBQW9CakIsTUFBS2pCLEtBQUwsQ0FBV21CLElBQUksQ0FBZixJQUFvQkYsTUFBS2pCLEtBQUwsQ0FBV21CLElBQUksQ0FBZixFQUFrQixDQUFsQixDQUFwQixHQUEyQyxJQUFuRTtBQUNBLFlBQUllLHNCQUFzQixHQUExQixFQUErQjtBQUM3QnBCLHdCQUFjLElBQWQ7QUFDRCxTQUZELE1BRU8sSUFBSW9CLHNCQUFzQixHQUExQixFQUErQjtBQUNwQ25CLHFCQUFXLElBQVg7QUFDRDtBQUNGO0FBQ0Y7QUFDRjs7QUFFRDtBQUNBLE1BQUlELFdBQUosRUFBaUI7QUFDZixXQUFPLENBQUNkLE1BQU1BLE1BQU1GLE1BQU4sR0FBZSxDQUFyQixDQUFSLEVBQWlDO0FBQy9CRSxZQUFNbUMsR0FBTjtBQUNBakMsaUJBQVdpQyxHQUFYO0FBQ0Q7QUFDRixHQUxELE1BS08sSUFBSXBCLFFBQUosRUFBYztBQUNuQmYsVUFBTW9DLElBQU4sQ0FBVyxFQUFYO0FBQ0FsQyxlQUFXa0MsSUFBWCxDQUFnQixJQUFoQjtBQUNEO0FBQ0QsT0FBSyxJQUFJQyxLQUFLLENBQWQsRUFBaUJBLEtBQUtyQyxNQUFNRixNQUFOLEdBQWUsQ0FBckMsRUFBd0N1QyxJQUF4QyxFQUE4QztBQUM1Q3JDLFVBQU1xQyxFQUFOLElBQVlyQyxNQUFNcUMsRUFBTixJQUFZbkMsV0FBV21DLEVBQVgsQ0FBeEI7QUFDRDtBQUNELFNBQU9yQyxNQUFNc0MsSUFBTixDQUFXLEVBQVgsQ0FBUDtBQUNEOztBQUVEO0FBQ08sU0FBUzlDLFlBQVQsQ0FBc0JFLE9BQXRCLEVBQStCQyxPQUEvQixFQUF3QztBQUM3QyxNQUFJLE9BQU9ELE9BQVAsS0FBbUIsUUFBdkIsRUFBaUM7QUFDL0JBLGNBQVUsd0VBQVdBLE9BQVgsQ0FBVjtBQUNEOztBQUVELE1BQUk2QyxlQUFlLENBQW5CO0FBQ0EsV0FBU0MsWUFBVCxHQUF3QjtBQUN0QixRQUFJQyxRQUFRL0MsUUFBUTZDLGNBQVIsQ0FBWjtBQUNBLFFBQUksQ0FBQ0UsS0FBTCxFQUFZO0FBQ1YsYUFBTzlDLFFBQVErQyxRQUFSLEVBQVA7QUFDRDs7QUFFRC9DLFlBQVFnRCxRQUFSLENBQWlCRixLQUFqQixFQUF3QixVQUFTRyxHQUFULEVBQWNDLElBQWQsRUFBb0I7QUFDMUMsVUFBSUQsR0FBSixFQUFTO0FBQ1AsZUFBT2pELFFBQVErQyxRQUFSLENBQWlCRSxHQUFqQixDQUFQO0FBQ0Q7O0FBRUQsVUFBSUUsaUJBQWlCdkQsV0FBV3NELElBQVgsRUFBaUJKLEtBQWpCLEVBQXdCOUMsT0FBeEIsQ0FBckI7QUFDQUEsY0FBUW9ELE9BQVIsQ0FBZ0JOLEtBQWhCLEVBQXVCSyxjQUF2QixFQUF1QyxVQUFTRixHQUFULEVBQWM7QUFDbkQsWUFBSUEsR0FBSixFQUFTO0FBQ1AsaUJBQU9qRCxRQUFRK0MsUUFBUixDQUFpQkUsR0FBakIsQ0FBUDtBQUNEOztBQUVESjtBQUNELE9BTkQ7QUFPRCxLQWJEO0FBY0Q7QUFDREE7QUFDRCIsImZpbGUiOiJhcHBseS5qcyIsInNvdXJjZXNDb250ZW50IjpbImltcG9ydCB7cGFyc2VQYXRjaH0gZnJvbSAnLi9wYXJzZSc7XG5pbXBvcnQgZGlzdGFuY2VJdGVyYXRvciBmcm9tICcuLi91dGlsL2Rpc3RhbmNlLWl0ZXJhdG9yJztcblxuZXhwb3J0IGZ1bmN0aW9uIGFwcGx5UGF0Y2goc291cmNlLCB1bmlEaWZmLCBvcHRpb25zID0ge30pIHtcbiAgaWYgKHR5cGVvZiB1bmlEaWZmID09PSAnc3RyaW5nJykge1xuICAgIHVuaURpZmYgPSBwYXJzZVBhdGNoKHVuaURpZmYpO1xuICB9XG5cbiAgaWYgKEFycmF5LmlzQXJyYXkodW5pRGlmZikpIHtcbiAgICBpZiAodW5pRGlmZi5sZW5ndGggPiAxKSB7XG4gICAgICB0aHJvdyBuZXcgRXJyb3IoJ2FwcGx5UGF0Y2ggb25seSB3b3JrcyB3aXRoIGEgc2luZ2xlIGlucHV0LicpO1xuICAgIH1cblxuICAgIHVuaURpZmYgPSB1bmlEaWZmWzBdO1xuICB9XG5cbiAgLy8gQXBwbHkgdGhlIGRpZmYgdG8gdGhlIGlucHV0XG4gIGxldCBsaW5lcyA9IHNvdXJjZS5zcGxpdCgvXFxyXFxufFtcXG5cXHZcXGZcXHJcXHg4NV0vKSxcbiAgICAgIGRlbGltaXRlcnMgPSBzb3VyY2UubWF0Y2goL1xcclxcbnxbXFxuXFx2XFxmXFxyXFx4ODVdL2cpIHx8IFtdLFxuICAgICAgaHVua3MgPSB1bmlEaWZmLmh1bmtzLFxuXG4gICAgICBjb21wYXJlTGluZSA9IG9wdGlvbnMuY29tcGFyZUxpbmUgfHwgKChsaW5lTnVtYmVyLCBsaW5lLCBvcGVyYXRpb24sIHBhdGNoQ29udGVudCkgPT4gbGluZSA9PT0gcGF0Y2hDb250ZW50KSxcbiAgICAgIGVycm9yQ291bnQgPSAwLFxuICAgICAgZnV6ekZhY3RvciA9IG9wdGlvbnMuZnV6ekZhY3RvciB8fCAwLFxuICAgICAgbWluTGluZSA9IDAsXG4gICAgICBvZmZzZXQgPSAwLFxuXG4gICAgICByZW1vdmVFT0ZOTCxcbiAgICAgIGFkZEVPRk5MO1xuXG4gIC8qKlxuICAgKiBDaGVja3MgaWYgdGhlIGh1bmsgZXhhY3RseSBmaXRzIG9uIHRoZSBwcm92aWRlZCBsb2NhdGlvblxuICAgKi9cbiAgZnVuY3Rpb24gaHVua0ZpdHMoaHVuaywgdG9Qb3MpIHtcbiAgICBmb3IgKGxldCBqID0gMDsgaiA8IGh1bmsubGluZXMubGVuZ3RoOyBqKyspIHtcbiAgICAgIGxldCBsaW5lID0gaHVuay5saW5lc1tqXSxcbiAgICAgICAgICBvcGVyYXRpb24gPSAobGluZS5sZW5ndGggPiAwID8gbGluZVswXSA6ICcgJyksXG4gICAgICAgICAgY29udGVudCA9IChsaW5lLmxlbmd0aCA+IDAgPyBsaW5lLnN1YnN0cigxKSA6IGxpbmUpO1xuXG4gICAgICBpZiAob3BlcmF0aW9uID09PSAnICcgfHwgb3BlcmF0aW9uID09PSAnLScpIHtcbiAgICAgICAgLy8gQ29udGV4dCBzYW5pdHkgY2hlY2tcbiAgICAgICAgaWYgKCFjb21wYXJlTGluZSh0b1BvcyArIDEsIGxpbmVzW3RvUG9zXSwgb3BlcmF0aW9uLCBjb250ZW50KSkge1xuICAgICAgICAgIGVycm9yQ291bnQrKztcblxuICAgICAgICAgIGlmIChlcnJvckNvdW50ID4gZnV6ekZhY3Rvcikge1xuICAgICAgICAgICAgcmV0dXJuIGZhbHNlO1xuICAgICAgICAgIH1cbiAgICAgICAgfVxuICAgICAgICB0b1BvcysrO1xuICAgICAgfVxuICAgIH1cblxuICAgIHJldHVybiB0cnVlO1xuICB9XG5cbiAgLy8gU2VhcmNoIGJlc3QgZml0IG9mZnNldHMgZm9yIGVhY2ggaHVuayBiYXNlZCBvbiB0aGUgcHJldmlvdXMgb25lc1xuICBmb3IgKGxldCBpID0gMDsgaSA8IGh1bmtzLmxlbmd0aDsgaSsrKSB7XG4gICAgbGV0IGh1bmsgPSBodW5rc1tpXSxcbiAgICAgICAgbWF4TGluZSA9IGxpbmVzLmxlbmd0aCAtIGh1bmsub2xkTGluZXMsXG4gICAgICAgIGxvY2FsT2Zmc2V0ID0gMCxcbiAgICAgICAgdG9Qb3MgPSBvZmZzZXQgKyBodW5rLm9sZFN0YXJ0IC0gMTtcblxuICAgIGxldCBpdGVyYXRvciA9IGRpc3RhbmNlSXRlcmF0b3IodG9Qb3MsIG1pbkxpbmUsIG1heExpbmUpO1xuXG4gICAgZm9yICg7IGxvY2FsT2Zmc2V0ICE9PSB1bmRlZmluZWQ7IGxvY2FsT2Zmc2V0ID0gaXRlcmF0b3IoKSkge1xuICAgICAgaWYgKGh1bmtGaXRzKGh1bmssIHRvUG9zICsgbG9jYWxPZmZzZXQpKSB7XG4gICAgICAgIGh1bmsub2Zmc2V0ID0gb2Zmc2V0ICs9IGxvY2FsT2Zmc2V0O1xuICAgICAgICBicmVhaztcbiAgICAgIH1cbiAgICB9XG5cbiAgICBpZiAobG9jYWxPZmZzZXQgPT09IHVuZGVmaW5lZCkge1xuICAgICAgcmV0dXJuIGZhbHNlO1xuICAgIH1cblxuICAgIC8vIFNldCBsb3dlciB0ZXh0IGxpbWl0IHRvIGVuZCBvZiB0aGUgY3VycmVudCBodW5rLCBzbyBuZXh0IG9uZXMgZG9uJ3QgdHJ5XG4gICAgLy8gdG8gZml0IG92ZXIgYWxyZWFkeSBwYXRjaGVkIHRleHRcbiAgICBtaW5MaW5lID0gaHVuay5vZmZzZXQgKyBodW5rLm9sZFN0YXJ0ICsgaHVuay5vbGRMaW5lcztcbiAgfVxuXG4gIC8vIEFwcGx5IHBhdGNoIGh1bmtzXG4gIGxldCBkaWZmT2Zmc2V0ID0gMDtcbiAgZm9yIChsZXQgaSA9IDA7IGkgPCBodW5rcy5sZW5ndGg7IGkrKykge1xuICAgIGxldCBodW5rID0gaHVua3NbaV0sXG4gICAgICAgIHRvUG9zID0gaHVuay5vbGRTdGFydCArIGh1bmsub2Zmc2V0ICsgZGlmZk9mZnNldCAtIDE7XG4gICAgZGlmZk9mZnNldCArPSBodW5rLm5ld0xpbmVzIC0gaHVuay5vbGRMaW5lcztcblxuICAgIGlmICh0b1BvcyA8IDApIHsgLy8gQ3JlYXRpbmcgYSBuZXcgZmlsZVxuICAgICAgdG9Qb3MgPSAwO1xuICAgIH1cblxuICAgIGZvciAobGV0IGogPSAwOyBqIDwgaHVuay5saW5lcy5sZW5ndGg7IGorKykge1xuICAgICAgbGV0IGxpbmUgPSBodW5rLmxpbmVzW2pdLFxuICAgICAgICAgIG9wZXJhdGlvbiA9IChsaW5lLmxlbmd0aCA+IDAgPyBsaW5lWzBdIDogJyAnKSxcbiAgICAgICAgICBjb250ZW50ID0gKGxpbmUubGVuZ3RoID4gMCA/IGxpbmUuc3Vic3RyKDEpIDogbGluZSksXG4gICAgICAgICAgZGVsaW1pdGVyID0gaHVuay5saW5lZGVsaW1pdGVyc1tqXTtcblxuICAgICAgaWYgKG9wZXJhdGlvbiA9PT0gJyAnKSB7XG4gICAgICAgIHRvUG9zKys7XG4gICAgICB9IGVsc2UgaWYgKG9wZXJhdGlvbiA9PT0gJy0nKSB7XG4gICAgICAgIGxpbmVzLnNwbGljZSh0b1BvcywgMSk7XG4gICAgICAgIGRlbGltaXRlcnMuc3BsaWNlKHRvUG9zLCAxKTtcbiAgICAgIC8qIGlzdGFuYnVsIGlnbm9yZSBlbHNlICovXG4gICAgICB9IGVsc2UgaWYgKG9wZXJhdGlvbiA9PT0gJysnKSB7XG4gICAgICAgIGxpbmVzLnNwbGljZSh0b1BvcywgMCwgY29udGVudCk7XG4gICAgICAgIGRlbGltaXRlcnMuc3BsaWNlKHRvUG9zLCAwLCBkZWxpbWl0ZXIpO1xuICAgICAgICB0b1BvcysrO1xuICAgICAgfSBlbHNlIGlmIChvcGVyYXRpb24gPT09ICdcXFxcJykge1xuICAgICAgICBsZXQgcHJldmlvdXNPcGVyYXRpb24gPSBodW5rLmxpbmVzW2ogLSAxXSA/IGh1bmsubGluZXNbaiAtIDFdWzBdIDogbnVsbDtcbiAgICAgICAgaWYgKHByZXZpb3VzT3BlcmF0aW9uID09PSAnKycpIHtcbiAgICAgICAgICByZW1vdmVFT0ZOTCA9IHRydWU7XG4gICAgICAgIH0gZWxzZSBpZiAocHJldmlvdXNPcGVyYXRpb24gPT09ICctJykge1xuICAgICAgICAgIGFkZEVPRk5MID0gdHJ1ZTtcbiAgICAgICAgfVxuICAgICAgfVxuICAgIH1cbiAgfVxuXG4gIC8vIEhhbmRsZSBFT0ZOTCBpbnNlcnRpb24vcmVtb3ZhbFxuICBpZiAocmVtb3ZlRU9GTkwpIHtcbiAgICB3aGlsZSAoIWxpbmVzW2xpbmVzLmxlbmd0aCAtIDFdKSB7XG4gICAgICBsaW5lcy5wb3AoKTtcbiAgICAgIGRlbGltaXRlcnMucG9wKCk7XG4gICAgfVxuICB9IGVsc2UgaWYgKGFkZEVPRk5MKSB7XG4gICAgbGluZXMucHVzaCgnJyk7XG4gICAgZGVsaW1pdGVycy5wdXNoKCdcXG4nKTtcbiAgfVxuICBmb3IgKGxldCBfayA9IDA7IF9rIDwgbGluZXMubGVuZ3RoIC0gMTsgX2srKykge1xuICAgIGxpbmVzW19rXSA9IGxpbmVzW19rXSArIGRlbGltaXRlcnNbX2tdO1xuICB9XG4gIHJldHVybiBsaW5lcy5qb2luKCcnKTtcbn1cblxuLy8gV3JhcHBlciB0aGF0IHN1cHBvcnRzIG11bHRpcGxlIGZpbGUgcGF0Y2hlcyB2aWEgY2FsbGJhY2tzLlxuZXhwb3J0IGZ1bmN0aW9uIGFwcGx5UGF0Y2hlcyh1bmlEaWZmLCBvcHRpb25zKSB7XG4gIGlmICh0eXBlb2YgdW5pRGlmZiA9PT0gJ3N0cmluZycpIHtcbiAgICB1bmlEaWZmID0gcGFyc2VQYXRjaCh1bmlEaWZmKTtcbiAgfVxuXG4gIGxldCBjdXJyZW50SW5kZXggPSAwO1xuICBmdW5jdGlvbiBwcm9jZXNzSW5kZXgoKSB7XG4gICAgbGV0IGluZGV4ID0gdW5pRGlmZltjdXJyZW50SW5kZXgrK107XG4gICAgaWYgKCFpbmRleCkge1xuICAgICAgcmV0dXJuIG9wdGlvbnMuY29tcGxldGUoKTtcbiAgICB9XG5cbiAgICBvcHRpb25zLmxvYWRGaWxlKGluZGV4LCBmdW5jdGlvbihlcnIsIGRhdGEpIHtcbiAgICAgIGlmIChlcnIpIHtcbiAgICAgICAgcmV0dXJuIG9wdGlvbnMuY29tcGxldGUoZXJyKTtcbiAgICAgIH1cblxuICAgICAgbGV0IHVwZGF0ZWRDb250ZW50ID0gYXBwbHlQYXRjaChkYXRhLCBpbmRleCwgb3B0aW9ucyk7XG4gICAgICBvcHRpb25zLnBhdGNoZWQoaW5kZXgsIHVwZGF0ZWRDb250ZW50LCBmdW5jdGlvbihlcnIpIHtcbiAgICAgICAgaWYgKGVycikge1xuICAgICAgICAgIHJldHVybiBvcHRpb25zLmNvbXBsZXRlKGVycik7XG4gICAgICAgIH1cblxuICAgICAgICBwcm9jZXNzSW5kZXgoKTtcbiAgICAgIH0pO1xuICAgIH0pO1xuICB9XG4gIHByb2Nlc3NJbmRleCgpO1xufVxuIl19
diff --git a/node_modules/diff/lib/patch/create.js b/node_modules/diff/lib/patch/create.js
new file mode 100644
index 0000000..be4d187
--- /dev/null
+++ b/node_modules/diff/lib/patch/create.js
@@ -0,0 +1,148 @@
+/*istanbul ignore start*/'use strict';
+
+exports.__esModule = true;
+exports. /*istanbul ignore end*/structuredPatch = structuredPatch;
+/*istanbul ignore start*/exports. /*istanbul ignore end*/createTwoFilesPatch = createTwoFilesPatch;
+/*istanbul ignore start*/exports. /*istanbul ignore end*/createPatch = createPatch;
+
+var /*istanbul ignore start*/_line = require('../diff/line') /*istanbul ignore end*/;
+
+/*istanbul ignore start*/function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
+
+/*istanbul ignore end*/function structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) {
+  if (!options) {
+    options = {};
+  }
+  if (typeof options.context === 'undefined') {
+    options.context = 4;
+  }
+
+  var diff = /*istanbul ignore start*/(0, _line.diffLines) /*istanbul ignore end*/(oldStr, newStr, options);
+  diff.push({ value: '', lines: [] }); // Append an empty value to make cleanup easier
+
+  function contextLines(lines) {
+    return lines.map(function (entry) {
+      return ' ' + entry;
+    });
+  }
+
+  var hunks = [];
+  var oldRangeStart = 0,
+      newRangeStart = 0,
+      curRange = [],
+      oldLine = 1,
+      newLine = 1;
+
+  /*istanbul ignore start*/var _loop = function _loop( /*istanbul ignore end*/i) {
+    var current = diff[i],
+        lines = current.lines || current.value.replace(/\n$/, '').split('\n');
+    current.lines = lines;
+
+    if (current.added || current.removed) {
+      /*istanbul ignore start*/var _curRange;
+
+      /*istanbul ignore end*/ // If we have previous context, start with that
+      if (!oldRangeStart) {
+        var prev = diff[i - 1];
+        oldRangeStart = oldLine;
+        newRangeStart = newLine;
+
+        if (prev) {
+          curRange = options.context > 0 ? contextLines(prev.lines.slice(-options.context)) : [];
+          oldRangeStart -= curRange.length;
+          newRangeStart -= curRange.length;
+        }
+      }
+
+      // Output our changes
+      /*istanbul ignore start*/(_curRange = /*istanbul ignore end*/curRange).push. /*istanbul ignore start*/apply /*istanbul ignore end*/( /*istanbul ignore start*/_curRange /*istanbul ignore end*/, /*istanbul ignore start*/_toConsumableArray( /*istanbul ignore end*/lines.map(function (entry) {
+        return (current.added ? '+' : '-') + entry;
+      })));
+
+      // Track the updated file position
+      if (current.added) {
+        newLine += lines.length;
+      } else {
+        oldLine += lines.length;
+      }
+    } else {
+      // Identical context lines. Track line changes
+      if (oldRangeStart) {
+        // Close out any changes that have been output (or join overlapping)
+        if (lines.length <= options.context * 2 && i < diff.length - 2) {
+          /*istanbul ignore start*/var _curRange2;
+
+          /*istanbul ignore end*/ // Overlapping
+          /*istanbul ignore start*/(_curRange2 = /*istanbul ignore end*/curRange).push. /*istanbul ignore start*/apply /*istanbul ignore end*/( /*istanbul ignore start*/_curRange2 /*istanbul ignore end*/, /*istanbul ignore start*/_toConsumableArray( /*istanbul ignore end*/contextLines(lines)));
+        } else {
+          /*istanbul ignore start*/var _curRange3;
+
+          /*istanbul ignore end*/ // end the range and output
+          var contextSize = Math.min(lines.length, options.context);
+          /*istanbul ignore start*/(_curRange3 = /*istanbul ignore end*/curRange).push. /*istanbul ignore start*/apply /*istanbul ignore end*/( /*istanbul ignore start*/_curRange3 /*istanbul ignore end*/, /*istanbul ignore start*/_toConsumableArray( /*istanbul ignore end*/contextLines(lines.slice(0, contextSize))));
+
+          var hunk = {
+            oldStart: oldRangeStart,
+            oldLines: oldLine - oldRangeStart + contextSize,
+            newStart: newRangeStart,
+            newLines: newLine - newRangeStart + contextSize,
+            lines: curRange
+          };
+          if (i >= diff.length - 2 && lines.length <= options.context) {
+            // EOF is inside this hunk
+            var oldEOFNewline = /\n$/.test(oldStr);
+            var newEOFNewline = /\n$/.test(newStr);
+            if (lines.length == 0 && !oldEOFNewline) {
+              // special case: old has no eol and no trailing context; no-nl can end up before adds
+              curRange.splice(hunk.oldLines, 0, '\\ No newline at end of file');
+            } else if (!oldEOFNewline || !newEOFNewline) {
+              curRange.push('\\ No newline at end of file');
+            }
+          }
+          hunks.push(hunk);
+
+          oldRangeStart = 0;
+          newRangeStart = 0;
+          curRange = [];
+        }
+      }
+      oldLine += lines.length;
+      newLine += lines.length;
+    }
+  };
+
+  for (var i = 0; i < diff.length; i++) {
+    /*istanbul ignore start*/_loop( /*istanbul ignore end*/i);
+  }
+
+  return {
+    oldFileName: oldFileName, newFileName: newFileName,
+    oldHeader: oldHeader, newHeader: newHeader,
+    hunks: hunks
+  };
+}
+
+function createTwoFilesPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) {
+  var diff = structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options);
+
+  var ret = [];
+  if (oldFileName == newFileName) {
+    ret.push('Index: ' + oldFileName);
+  }
+  ret.push('===================================================================');
+  ret.push('--- ' + diff.oldFileName + (typeof diff.oldHeader === 'undefined' ? '' : '\t' + diff.oldHeader));
+  ret.push('+++ ' + diff.newFileName + (typeof diff.newHeader === 'undefined' ? '' : '\t' + diff.newHeader));
+
+  for (var i = 0; i < diff.hunks.length; i++) {
+    var hunk = diff.hunks[i];
+    ret.push('@@ -' + hunk.oldStart + ',' + hunk.oldLines + ' +' + hunk.newStart + ',' + hunk.newLines + ' @@');
+    ret.push.apply(ret, hunk.lines);
+  }
+
+  return ret.join('\n') + '\n';
+}
+
+function createPatch(fileName, oldStr, newStr, oldHeader, newHeader, options) {
+  return createTwoFilesPatch(fileName, fileName, oldStr, newStr, oldHeader, newHeader, options);
+}
+//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9wYXRjaC9jcmVhdGUuanMiXSwibmFtZXMiOlsic3RydWN0dXJlZFBhdGNoIiwiY3JlYXRlVHdvRmlsZXNQYXRjaCIsImNyZWF0ZVBhdGNoIiwib2xkRmlsZU5hbWUiLCJuZXdGaWxlTmFtZSIsIm9sZFN0ciIsIm5ld1N0ciIsIm9sZEhlYWRlciIsIm5ld0hlYWRlciIsIm9wdGlvbnMiLCJjb250ZXh0IiwiZGlmZiIsInB1c2giLCJ2YWx1ZSIsImxpbmVzIiwiY29udGV4dExpbmVzIiwibWFwIiwiZW50cnkiLCJodW5rcyIsIm9sZFJhbmdlU3RhcnQiLCJuZXdSYW5nZVN0YXJ0IiwiY3VyUmFuZ2UiLCJvbGRMaW5lIiwibmV3TGluZSIsImkiLCJjdXJyZW50IiwicmVwbGFjZSIsInNwbGl0IiwiYWRkZWQiLCJyZW1vdmVkIiwicHJldiIsInNsaWNlIiwibGVuZ3RoIiwiY29udGV4dFNpemUiLCJNYXRoIiwibWluIiwiaHVuayIsIm9sZFN0YXJ0Iiwib2xkTGluZXMiLCJuZXdTdGFydCIsIm5ld0xpbmVzIiwib2xkRU9GTmV3bGluZSIsInRlc3QiLCJuZXdFT0ZOZXdsaW5lIiwic3BsaWNlIiwicmV0IiwiYXBwbHkiLCJqb2luIiwiZmlsZU5hbWUiXSwibWFwcGluZ3MiOiI7OztnQ0FFZ0JBLGUsR0FBQUEsZTt5REFpR0FDLG1CLEdBQUFBLG1CO3lEQXdCQUMsVyxHQUFBQSxXOztBQTNIaEI7Ozs7dUJBRU8sU0FBU0YsZUFBVCxDQUF5QkcsV0FBekIsRUFBc0NDLFdBQXRDLEVBQW1EQyxNQUFuRCxFQUEyREMsTUFBM0QsRUFBbUVDLFNBQW5FLEVBQThFQyxTQUE5RSxFQUF5RkMsT0FBekYsRUFBa0c7QUFDdkcsTUFBSSxDQUFDQSxPQUFMLEVBQWM7QUFDWkEsY0FBVSxFQUFWO0FBQ0Q7QUFDRCxNQUFJLE9BQU9BLFFBQVFDLE9BQWYsS0FBMkIsV0FBL0IsRUFBNEM7QUFDMUNELFlBQVFDLE9BQVIsR0FBa0IsQ0FBbEI7QUFDRDs7QUFFRCxNQUFNQyxPQUFPLHNFQUFVTixNQUFWLEVBQWtCQyxNQUFsQixFQUEwQkcsT0FBMUIsQ0FBYjtBQUNBRSxPQUFLQyxJQUFMLENBQVUsRUFBQ0MsT0FBTyxFQUFSLEVBQVlDLE9BQU8sRUFBbkIsRUFBVixFQVR1RyxDQVNsRTs7QUFFckMsV0FBU0MsWUFBVCxDQUFzQkQsS0FBdEIsRUFBNkI7QUFDM0IsV0FBT0EsTUFBTUUsR0FBTixDQUFVLFVBQVNDLEtBQVQsRUFBZ0I7QUFBRSxhQUFPLE1BQU1BLEtBQWI7QUFBcUIsS0FBakQsQ0FBUDtBQUNEOztBQUVELE1BQUlDLFFBQVEsRUFBWjtBQUNBLE1BQUlDLGdCQUFnQixDQUFwQjtBQUFBLE1BQXVCQyxnQkFBZ0IsQ0FBdkM7QUFBQSxNQUEwQ0MsV0FBVyxFQUFyRDtBQUFBLE1BQ0lDLFVBQVUsQ0FEZDtBQUFBLE1BQ2lCQyxVQUFVLENBRDNCOztBQWhCdUcsOEVBa0I5RkMsQ0FsQjhGO0FBbUJyRyxRQUFNQyxVQUFVZCxLQUFLYSxDQUFMLENBQWhCO0FBQUEsUUFDTVYsUUFBUVcsUUFBUVgsS0FBUixJQUFpQlcsUUFBUVosS0FBUixDQUFjYSxPQUFkLENBQXNCLEtBQXRCLEVBQTZCLEVBQTdCLEVBQWlDQyxLQUFqQyxDQUF1QyxJQUF2QyxDQUQvQjtBQUVBRixZQUFRWCxLQUFSLEdBQWdCQSxLQUFoQjs7QUFFQSxRQUFJVyxRQUFRRyxLQUFSLElBQWlCSCxRQUFRSSxPQUE3QixFQUFzQztBQUFBOztBQUFBLDhCQUNwQztBQUNBLFVBQUksQ0FBQ1YsYUFBTCxFQUFvQjtBQUNsQixZQUFNVyxPQUFPbkIsS0FBS2EsSUFBSSxDQUFULENBQWI7QUFDQUwsd0JBQWdCRyxPQUFoQjtBQUNBRix3QkFBZ0JHLE9BQWhCOztBQUVBLFlBQUlPLElBQUosRUFBVTtBQUNSVCxxQkFBV1osUUFBUUMsT0FBUixHQUFrQixDQUFsQixHQUFzQkssYUFBYWUsS0FBS2hCLEtBQUwsQ0FBV2lCLEtBQVgsQ0FBaUIsQ0FBQ3RCLFFBQVFDLE9BQTFCLENBQWIsQ0FBdEIsR0FBeUUsRUFBcEY7QUFDQVMsMkJBQWlCRSxTQUFTVyxNQUExQjtBQUNBWiwyQkFBaUJDLFNBQVNXLE1BQTFCO0FBQ0Q7QUFDRjs7QUFFRDtBQUNBLDZFQUFTcEIsSUFBVCwwTEFBa0JFLE1BQU1FLEdBQU4sQ0FBVSxVQUFTQyxLQUFULEVBQWdCO0FBQzFDLGVBQU8sQ0FBQ1EsUUFBUUcsS0FBUixHQUFnQixHQUFoQixHQUFzQixHQUF2QixJQUE4QlgsS0FBckM7QUFDRCxPQUZpQixDQUFsQjs7QUFJQTtBQUNBLFVBQUlRLFFBQVFHLEtBQVosRUFBbUI7QUFDakJMLG1CQUFXVCxNQUFNa0IsTUFBakI7QUFDRCxPQUZELE1BRU87QUFDTFYsbUJBQVdSLE1BQU1rQixNQUFqQjtBQUNEO0FBQ0YsS0F6QkQsTUF5Qk87QUFDTDtBQUNBLFVBQUliLGFBQUosRUFBbUI7QUFDakI7QUFDQSxZQUFJTCxNQUFNa0IsTUFBTixJQUFnQnZCLFFBQVFDLE9BQVIsR0FBa0IsQ0FBbEMsSUFBdUNjLElBQUliLEtBQUtxQixNQUFMLEdBQWMsQ0FBN0QsRUFBZ0U7QUFBQTs7QUFBQSxrQ0FDOUQ7QUFDQSxrRkFBU3BCLElBQVQsMkxBQWtCRyxhQUFhRCxLQUFiLENBQWxCO0FBQ0QsU0FIRCxNQUdPO0FBQUE7O0FBQUEsa0NBQ0w7QUFDQSxjQUFJbUIsY0FBY0MsS0FBS0MsR0FBTCxDQUFTckIsTUFBTWtCLE1BQWYsRUFBdUJ2QixRQUFRQyxPQUEvQixDQUFsQjtBQUNBLGtGQUFTRSxJQUFULDJMQUFrQkcsYUFBYUQsTUFBTWlCLEtBQU4sQ0FBWSxDQUFaLEVBQWVFLFdBQWYsQ0FBYixDQUFsQjs7QUFFQSxjQUFJRyxPQUFPO0FBQ1RDLHNCQUFVbEIsYUFERDtBQUVUbUIsc0JBQVdoQixVQUFVSCxhQUFWLEdBQTBCYyxXQUY1QjtBQUdUTSxzQkFBVW5CLGFBSEQ7QUFJVG9CLHNCQUFXakIsVUFBVUgsYUFBVixHQUEwQmEsV0FKNUI7QUFLVG5CLG1CQUFPTztBQUxFLFdBQVg7QUFPQSxjQUFJRyxLQUFLYixLQUFLcUIsTUFBTCxHQUFjLENBQW5CLElBQXdCbEIsTUFBTWtCLE1BQU4sSUFBZ0J2QixRQUFRQyxPQUFwRCxFQUE2RDtBQUMzRDtBQUNBLGdCQUFJK0IsZ0JBQWlCLE1BQU1DLElBQU4sQ0FBV3JDLE1BQVgsQ0FBckI7QUFDQSxnQkFBSXNDLGdCQUFpQixNQUFNRCxJQUFOLENBQVdwQyxNQUFYLENBQXJCO0FBQ0EsZ0JBQUlRLE1BQU1rQixNQUFOLElBQWdCLENBQWhCLElBQXFCLENBQUNTLGFBQTFCLEVBQXlDO0FBQ3ZDO0FBQ0FwQix1QkFBU3VCLE1BQVQsQ0FBZ0JSLEtBQUtFLFFBQXJCLEVBQStCLENBQS9CLEVBQWtDLDhCQUFsQztBQUNELGFBSEQsTUFHTyxJQUFJLENBQUNHLGFBQUQsSUFBa0IsQ0FBQ0UsYUFBdkIsRUFBc0M7QUFDM0N0Qix1QkFBU1QsSUFBVCxDQUFjLDhCQUFkO0FBQ0Q7QUFDRjtBQUNETSxnQkFBTU4sSUFBTixDQUFXd0IsSUFBWDs7QUFFQWpCLDBCQUFnQixDQUFoQjtBQUNBQywwQkFBZ0IsQ0FBaEI7QUFDQUMscUJBQVcsRUFBWDtBQUNEO0FBQ0Y7QUFDREMsaUJBQVdSLE1BQU1rQixNQUFqQjtBQUNBVCxpQkFBV1QsTUFBTWtCLE1BQWpCO0FBQ0Q7QUF2Rm9HOztBQWtCdkcsT0FBSyxJQUFJUixJQUFJLENBQWIsRUFBZ0JBLElBQUliLEtBQUtxQixNQUF6QixFQUFpQ1IsR0FBakMsRUFBc0M7QUFBQSwyREFBN0JBLENBQTZCO0FBc0VyQzs7QUFFRCxTQUFPO0FBQ0xyQixpQkFBYUEsV0FEUixFQUNxQkMsYUFBYUEsV0FEbEM7QUFFTEcsZUFBV0EsU0FGTixFQUVpQkMsV0FBV0EsU0FGNUI7QUFHTFUsV0FBT0E7QUFIRixHQUFQO0FBS0Q7O0FBRU0sU0FBU2pCLG1CQUFULENBQTZCRSxXQUE3QixFQUEwQ0MsV0FBMUMsRUFBdURDLE1BQXZELEVBQStEQyxNQUEvRCxFQUF1RUMsU0FBdkUsRUFBa0ZDLFNBQWxGLEVBQTZGQyxPQUE3RixFQUFzRztBQUMzRyxNQUFNRSxPQUFPWCxnQkFBZ0JHLFdBQWhCLEVBQTZCQyxXQUE3QixFQUEwQ0MsTUFBMUMsRUFBa0RDLE1BQWxELEVBQTBEQyxTQUExRCxFQUFxRUMsU0FBckUsRUFBZ0ZDLE9BQWhGLENBQWI7O0FBRUEsTUFBTW9DLE1BQU0sRUFBWjtBQUNBLE1BQUkxQyxlQUFlQyxXQUFuQixFQUFnQztBQUM5QnlDLFFBQUlqQyxJQUFKLENBQVMsWUFBWVQsV0FBckI7QUFDRDtBQUNEMEMsTUFBSWpDLElBQUosQ0FBUyxxRUFBVDtBQUNBaUMsTUFBSWpDLElBQUosQ0FBUyxTQUFTRCxLQUFLUixXQUFkLElBQTZCLE9BQU9RLEtBQUtKLFNBQVosS0FBMEIsV0FBMUIsR0FBd0MsRUFBeEMsR0FBNkMsT0FBT0ksS0FBS0osU0FBdEYsQ0FBVDtBQUNBc0MsTUFBSWpDLElBQUosQ0FBUyxTQUFTRCxLQUFLUCxXQUFkLElBQTZCLE9BQU9PLEtBQUtILFNBQVosS0FBMEIsV0FBMUIsR0FBd0MsRUFBeEMsR0FBNkMsT0FBT0csS0FBS0gsU0FBdEYsQ0FBVDs7QUFFQSxPQUFLLElBQUlnQixJQUFJLENBQWIsRUFBZ0JBLElBQUliLEtBQUtPLEtBQUwsQ0FBV2MsTUFBL0IsRUFBdUNSLEdBQXZDLEVBQTRDO0FBQzFDLFFBQU1ZLE9BQU96QixLQUFLTyxLQUFMLENBQVdNLENBQVgsQ0FBYjtBQUNBcUIsUUFBSWpDLElBQUosQ0FDRSxTQUFTd0IsS0FBS0MsUUFBZCxHQUF5QixHQUF6QixHQUErQkQsS0FBS0UsUUFBcEMsR0FDRSxJQURGLEdBQ1NGLEtBQUtHLFFBRGQsR0FDeUIsR0FEekIsR0FDK0JILEtBQUtJLFFBRHBDLEdBRUUsS0FISjtBQUtBSyxRQUFJakMsSUFBSixDQUFTa0MsS0FBVCxDQUFlRCxHQUFmLEVBQW9CVCxLQUFLdEIsS0FBekI7QUFDRDs7QUFFRCxTQUFPK0IsSUFBSUUsSUFBSixDQUFTLElBQVQsSUFBaUIsSUFBeEI7QUFDRDs7QUFFTSxTQUFTN0MsV0FBVCxDQUFxQjhDLFFBQXJCLEVBQStCM0MsTUFBL0IsRUFBdUNDLE1BQXZDLEVBQStDQyxTQUEvQyxFQUEwREMsU0FBMUQsRUFBcUVDLE9BQXJFLEVBQThFO0FBQ25GLFNBQU9SLG9CQUFvQitDLFFBQXBCLEVBQThCQSxRQUE5QixFQUF3QzNDLE1BQXhDLEVBQWdEQyxNQUFoRCxFQUF3REMsU0FBeEQsRUFBbUVDLFNBQW5FLEVBQThFQyxPQUE5RSxDQUFQO0FBQ0QiLCJmaWxlIjoiY3JlYXRlLmpzIiwic291cmNlc0NvbnRlbnQiOlsiaW1wb3J0IHtkaWZmTGluZXN9IGZyb20gJy4uL2RpZmYvbGluZSc7XG5cbmV4cG9ydCBmdW5jdGlvbiBzdHJ1Y3R1cmVkUGF0Y2gob2xkRmlsZU5hbWUsIG5ld0ZpbGVOYW1lLCBvbGRTdHIsIG5ld1N0ciwgb2xkSGVhZGVyLCBuZXdIZWFkZXIsIG9wdGlvbnMpIHtcbiAgaWYgKCFvcHRpb25zKSB7XG4gICAgb3B0aW9ucyA9IHt9O1xuICB9XG4gIGlmICh0eXBlb2Ygb3B0aW9ucy5jb250ZXh0ID09PSAndW5kZWZpbmVkJykge1xuICAgIG9wdGlvbnMuY29udGV4dCA9IDQ7XG4gIH1cblxuICBjb25zdCBkaWZmID0gZGlmZkxpbmVzKG9sZFN0ciwgbmV3U3RyLCBvcHRpb25zKTtcbiAgZGlmZi5wdXNoKHt2YWx1ZTogJycsIGxpbmVzOiBbXX0pOyAgIC8vIEFwcGVuZCBhbiBlbXB0eSB2YWx1ZSB0byBtYWtlIGNsZWFudXAgZWFzaWVyXG5cbiAgZnVuY3Rpb24gY29udGV4dExpbmVzKGxpbmVzKSB7XG4gICAgcmV0dXJuIGxpbmVzLm1hcChmdW5jdGlvbihlbnRyeSkgeyByZXR1cm4gJyAnICsgZW50cnk7IH0pO1xuICB9XG5cbiAgbGV0IGh1bmtzID0gW107XG4gIGxldCBvbGRSYW5nZVN0YXJ0ID0gMCwgbmV3UmFuZ2VTdGFydCA9IDAsIGN1clJhbmdlID0gW10sXG4gICAgICBvbGRMaW5lID0gMSwgbmV3TGluZSA9IDE7XG4gIGZvciAobGV0IGkgPSAwOyBpIDwgZGlmZi5sZW5ndGg7IGkrKykge1xuICAgIGNvbnN0IGN1cnJlbnQgPSBkaWZmW2ldLFxuICAgICAgICAgIGxpbmVzID0gY3VycmVudC5saW5lcyB8fCBjdXJyZW50LnZhbHVlLnJlcGxhY2UoL1xcbiQvLCAnJykuc3BsaXQoJ1xcbicpO1xuICAgIGN1cnJlbnQubGluZXMgPSBsaW5lcztcblxuICAgIGlmIChjdXJyZW50LmFkZGVkIHx8IGN1cnJlbnQucmVtb3ZlZCkge1xuICAgICAgLy8gSWYgd2UgaGF2ZSBwcmV2aW91cyBjb250ZXh0LCBzdGFydCB3aXRoIHRoYXRcbiAgICAgIGlmICghb2xkUmFuZ2VTdGFydCkge1xuICAgICAgICBjb25zdCBwcmV2ID0gZGlmZltpIC0gMV07XG4gICAgICAgIG9sZFJhbmdlU3RhcnQgPSBvbGRMaW5lO1xuICAgICAgICBuZXdSYW5nZVN0YXJ0ID0gbmV3TGluZTtcblxuICAgICAgICBpZiAocHJldikge1xuICAgICAgICAgIGN1clJhbmdlID0gb3B0aW9ucy5jb250ZXh0ID4gMCA/IGNvbnRleHRMaW5lcyhwcmV2LmxpbmVzLnNsaWNlKC1vcHRpb25zLmNvbnRleHQpKSA6IFtdO1xuICAgICAgICAgIG9sZFJhbmdlU3RhcnQgLT0gY3VyUmFuZ2UubGVuZ3RoO1xuICAgICAgICAgIG5ld1JhbmdlU3RhcnQgLT0gY3VyUmFuZ2UubGVuZ3RoO1xuICAgICAgICB9XG4gICAgICB9XG5cbiAgICAgIC8vIE91dHB1dCBvdXIgY2hhbmdlc1xuICAgICAgY3VyUmFuZ2UucHVzaCguLi4gbGluZXMubWFwKGZ1bmN0aW9uKGVudHJ5KSB7XG4gICAgICAgIHJldHVybiAoY3VycmVudC5hZGRlZCA/ICcrJyA6ICctJykgKyBlbnRyeTtcbiAgICAgIH0pKTtcblxuICAgICAgLy8gVHJhY2sgdGhlIHVwZGF0ZWQgZmlsZSBwb3NpdGlvblxuICAgICAgaWYgKGN1cnJlbnQuYWRkZWQpIHtcbiAgICAgICAgbmV3TGluZSArPSBsaW5lcy5sZW5ndGg7XG4gICAgICB9IGVsc2Uge1xuICAgICAgICBvbGRMaW5lICs9IGxpbmVzLmxlbmd0aDtcbiAgICAgIH1cbiAgICB9IGVsc2Uge1xuICAgICAgLy8gSWRlbnRpY2FsIGNvbnRleHQgbGluZXMuIFRyYWNrIGxpbmUgY2hhbmdlc1xuICAgICAgaWYgKG9sZFJhbmdlU3RhcnQpIHtcbiAgICAgICAgLy8gQ2xvc2Ugb3V0IGFueSBjaGFuZ2VzIHRoYXQgaGF2ZSBiZWVuIG91dHB1dCAob3Igam9pbiBvdmVybGFwcGluZylcbiAgICAgICAgaWYgKGxpbmVzLmxlbmd0aCA8PSBvcHRpb25zLmNvbnRleHQgKiAyICYmIGkgPCBkaWZmLmxlbmd0aCAtIDIpIHtcbiAgICAgICAgICAvLyBPdmVybGFwcGluZ1xuICAgICAgICAgIGN1clJhbmdlLnB1c2goLi4uIGNvbnRleHRMaW5lcyhsaW5lcykpO1xuICAgICAgICB9IGVsc2Uge1xuICAgICAgICAgIC8vIGVuZCB0aGUgcmFuZ2UgYW5kIG91dHB1dFxuICAgICAgICAgIGxldCBjb250ZXh0U2l6ZSA9IE1hdGgubWluKGxpbmVzLmxlbmd0aCwgb3B0aW9ucy5jb250ZXh0KTtcbiAgICAgICAgICBjdXJSYW5nZS5wdXNoKC4uLiBjb250ZXh0TGluZXMobGluZXMuc2xpY2UoMCwgY29udGV4dFNpemUpKSk7XG5cbiAgICAgICAgICBsZXQgaHVuayA9IHtcbiAgICAgICAgICAgIG9sZFN0YXJ0OiBvbGRSYW5nZVN0YXJ0LFxuICAgICAgICAgICAgb2xkTGluZXM6IChvbGRMaW5lIC0gb2xkUmFuZ2VTdGFydCArIGNvbnRleHRTaXplKSxcbiAgICAgICAgICAgIG5ld1N0YXJ0OiBuZXdSYW5nZVN0YXJ0LFxuICAgICAgICAgICAgbmV3TGluZXM6IChuZXdMaW5lIC0gbmV3UmFuZ2VTdGFydCArIGNvbnRleHRTaXplKSxcbiAgICAgICAgICAgIGxpbmVzOiBjdXJSYW5nZVxuICAgICAgICAgIH07XG4gICAgICAgICAgaWYgKGkgPj0gZGlmZi5sZW5ndGggLSAyICYmIGxpbmVzLmxlbmd0aCA8PSBvcHRpb25zLmNvbnRleHQpIHtcbiAgICAgICAgICAgIC8vIEVPRiBpcyBpbnNpZGUgdGhpcyBodW5rXG4gICAgICAgICAgICBsZXQgb2xkRU9GTmV3bGluZSA9ICgvXFxuJC8udGVzdChvbGRTdHIpKTtcbiAgICAgICAgICAgIGxldCBuZXdFT0ZOZXdsaW5lID0gKC9cXG4kLy50ZXN0KG5ld1N0cikpO1xuICAgICAgICAgICAgaWYgKGxpbmVzLmxlbmd0aCA9PSAwICYmICFvbGRFT0ZOZXdsaW5lKSB7XG4gICAgICAgICAgICAgIC8vIHNwZWNpYWwgY2FzZTogb2xkIGhhcyBubyBlb2wgYW5kIG5vIHRyYWlsaW5nIGNvbnRleHQ7IG5vLW5sIGNhbiBlbmQgdXAgYmVmb3JlIGFkZHNcbiAgICAgICAgICAgICAgY3VyUmFuZ2Uuc3BsaWNlKGh1bmsub2xkTGluZXMsIDAsICdcXFxcIE5vIG5ld2xpbmUgYXQgZW5kIG9mIGZpbGUnKTtcbiAgICAgICAgICAgIH0gZWxzZSBpZiAoIW9sZEVPRk5ld2xpbmUgfHwgIW5ld0VPRk5ld2xpbmUpIHtcbiAgICAgICAgICAgICAgY3VyUmFuZ2UucHVzaCgnXFxcXCBObyBuZXdsaW5lIGF0IGVuZCBvZiBmaWxlJyk7XG4gICAgICAgICAgICB9XG4gICAgICAgICAgfVxuICAgICAgICAgIGh1bmtzLnB1c2goaHVuayk7XG5cbiAgICAgICAgICBvbGRSYW5nZVN0YXJ0ID0gMDtcbiAgICAgICAgICBuZXdSYW5nZVN0YXJ0ID0gMDtcbiAgICAgICAgICBjdXJSYW5nZSA9IFtdO1xuICAgICAgICB9XG4gICAgICB9XG4gICAgICBvbGRMaW5lICs9IGxpbmVzLmxlbmd0aDtcbiAgICAgIG5ld0xpbmUgKz0gbGluZXMubGVuZ3RoO1xuICAgIH1cbiAgfVxuXG4gIHJldHVybiB7XG4gICAgb2xkRmlsZU5hbWU6IG9sZEZpbGVOYW1lLCBuZXdGaWxlTmFtZTogbmV3RmlsZU5hbWUsXG4gICAgb2xkSGVhZGVyOiBvbGRIZWFkZXIsIG5ld0hlYWRlcjogbmV3SGVhZGVyLFxuICAgIGh1bmtzOiBodW5rc1xuICB9O1xufVxuXG5leHBvcnQgZnVuY3Rpb24gY3JlYXRlVHdvRmlsZXNQYXRjaChvbGRGaWxlTmFtZSwgbmV3RmlsZU5hbWUsIG9sZFN0ciwgbmV3U3RyLCBvbGRIZWFkZXIsIG5ld0hlYWRlciwgb3B0aW9ucykge1xuICBjb25zdCBkaWZmID0gc3RydWN0dXJlZFBhdGNoKG9sZEZpbGVOYW1lLCBuZXdGaWxlTmFtZSwgb2xkU3RyLCBuZXdTdHIsIG9sZEhlYWRlciwgbmV3SGVhZGVyLCBvcHRpb25zKTtcblxuICBjb25zdCByZXQgPSBbXTtcbiAgaWYgKG9sZEZpbGVOYW1lID09IG5ld0ZpbGVOYW1lKSB7XG4gICAgcmV0LnB1c2goJ0luZGV4OiAnICsgb2xkRmlsZU5hbWUpO1xuICB9XG4gIHJldC5wdXNoKCc9PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09Jyk7XG4gIHJldC5wdXNoKCctLS0gJyArIGRpZmYub2xkRmlsZU5hbWUgKyAodHlwZW9mIGRpZmYub2xkSGVhZGVyID09PSAndW5kZWZpbmVkJyA/ICcnIDogJ1xcdCcgKyBkaWZmLm9sZEhlYWRlcikpO1xuICByZXQucHVzaCgnKysrICcgKyBkaWZmLm5ld0ZpbGVOYW1lICsgKHR5cGVvZiBkaWZmLm5ld0hlYWRlciA9PT0gJ3VuZGVmaW5lZCcgPyAnJyA6ICdcXHQnICsgZGlmZi5uZXdIZWFkZXIpKTtcblxuICBmb3IgKGxldCBpID0gMDsgaSA8IGRpZmYuaHVua3MubGVuZ3RoOyBpKyspIHtcbiAgICBjb25zdCBodW5rID0gZGlmZi5odW5rc1tpXTtcbiAgICByZXQucHVzaChcbiAgICAgICdAQCAtJyArIGh1bmsub2xkU3RhcnQgKyAnLCcgKyBodW5rLm9sZExpbmVzXG4gICAgICArICcgKycgKyBodW5rLm5ld1N0YXJ0ICsgJywnICsgaHVuay5uZXdMaW5lc1xuICAgICAgKyAnIEBAJ1xuICAgICk7XG4gICAgcmV0LnB1c2guYXBwbHkocmV0LCBodW5rLmxpbmVzKTtcbiAgfVxuXG4gIHJldHVybiByZXQuam9pbignXFxuJykgKyAnXFxuJztcbn1cblxuZXhwb3J0IGZ1bmN0aW9uIGNyZWF0ZVBhdGNoKGZpbGVOYW1lLCBvbGRTdHIsIG5ld1N0ciwgb2xkSGVhZGVyLCBuZXdIZWFkZXIsIG9wdGlvbnMpIHtcbiAgcmV0dXJuIGNyZWF0ZVR3b0ZpbGVzUGF0Y2goZmlsZU5hbWUsIGZpbGVOYW1lLCBvbGRTdHIsIG5ld1N0ciwgb2xkSGVhZGVyLCBuZXdIZWFkZXIsIG9wdGlvbnMpO1xufVxuIl19
diff --git a/node_modules/diff/lib/patch/merge.js b/node_modules/diff/lib/patch/merge.js
new file mode 100644
index 0000000..074c4bc
--- /dev/null
+++ b/node_modules/diff/lib/patch/merge.js
@@ -0,0 +1,396 @@
+/*istanbul ignore start*/'use strict';
+
+exports.__esModule = true;
+exports. /*istanbul ignore end*/calcLineCount = calcLineCount;
+/*istanbul ignore start*/exports. /*istanbul ignore end*/merge = merge;
+
+var /*istanbul ignore start*/_create = require('./create') /*istanbul ignore end*/;
+
+var /*istanbul ignore start*/_parse = require('./parse') /*istanbul ignore end*/;
+
+var /*istanbul ignore start*/_array = require('../util/array') /*istanbul ignore end*/;
+
+/*istanbul ignore start*/function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
+
+/*istanbul ignore end*/function calcLineCount(hunk) {
+  /*istanbul ignore start*/var _calcOldNewLineCount = /*istanbul ignore end*/calcOldNewLineCount(hunk.lines),
+      oldLines = _calcOldNewLineCount.oldLines,
+      newLines = _calcOldNewLineCount.newLines;
+
+  if (oldLines !== undefined) {
+    hunk.oldLines = oldLines;
+  } else {
+    delete hunk.oldLines;
+  }
+
+  if (newLines !== undefined) {
+    hunk.newLines = newLines;
+  } else {
+    delete hunk.newLines;
+  }
+}
+
+function merge(mine, theirs, base) {
+  mine = loadPatch(mine, base);
+  theirs = loadPatch(theirs, base);
+
+  var ret = {};
+
+  // For index we just let it pass through as it doesn't have any necessary meaning.
+  // Leaving sanity checks on this to the API consumer that may know more about the
+  // meaning in their own context.
+  if (mine.index || theirs.index) {
+    ret.index = mine.index || theirs.index;
+  }
+
+  if (mine.newFileName || theirs.newFileName) {
+    if (!fileNameChanged(mine)) {
+      // No header or no change in ours, use theirs (and ours if theirs does not exist)
+      ret.oldFileName = theirs.oldFileName || mine.oldFileName;
+      ret.newFileName = theirs.newFileName || mine.newFileName;
+      ret.oldHeader = theirs.oldHeader || mine.oldHeader;
+      ret.newHeader = theirs.newHeader || mine.newHeader;
+    } else if (!fileNameChanged(theirs)) {
+      // No header or no change in theirs, use ours
+      ret.oldFileName = mine.oldFileName;
+      ret.newFileName = mine.newFileName;
+      ret.oldHeader = mine.oldHeader;
+      ret.newHeader = mine.newHeader;
+    } else {
+      // Both changed... figure it out
+      ret.oldFileName = selectField(ret, mine.oldFileName, theirs.oldFileName);
+      ret.newFileName = selectField(ret, mine.newFileName, theirs.newFileName);
+      ret.oldHeader = selectField(ret, mine.oldHeader, theirs.oldHeader);
+      ret.newHeader = selectField(ret, mine.newHeader, theirs.newHeader);
+    }
+  }
+
+  ret.hunks = [];
+
+  var mineIndex = 0,
+      theirsIndex = 0,
+      mineOffset = 0,
+      theirsOffset = 0;
+
+  while (mineIndex < mine.hunks.length || theirsIndex < theirs.hunks.length) {
+    var mineCurrent = mine.hunks[mineIndex] || { oldStart: Infinity },
+        theirsCurrent = theirs.hunks[theirsIndex] || { oldStart: Infinity };
+
+    if (hunkBefore(mineCurrent, theirsCurrent)) {
+      // This patch does not overlap with any of the others, yay.
+      ret.hunks.push(cloneHunk(mineCurrent, mineOffset));
+      mineIndex++;
+      theirsOffset += mineCurrent.newLines - mineCurrent.oldLines;
+    } else if (hunkBefore(theirsCurrent, mineCurrent)) {
+      // This patch does not overlap with any of the others, yay.
+      ret.hunks.push(cloneHunk(theirsCurrent, theirsOffset));
+      theirsIndex++;
+      mineOffset += theirsCurrent.newLines - theirsCurrent.oldLines;
+    } else {
+      // Overlap, merge as best we can
+      var mergedHunk = {
+        oldStart: Math.min(mineCurrent.oldStart, theirsCurrent.oldStart),
+        oldLines: 0,
+        newStart: Math.min(mineCurrent.newStart + mineOffset, theirsCurrent.oldStart + theirsOffset),
+        newLines: 0,
+        lines: []
+      };
+      mergeLines(mergedHunk, mineCurrent.oldStart, mineCurrent.lines, theirsCurrent.oldStart, theirsCurrent.lines);
+      theirsIndex++;
+      mineIndex++;
+
+      ret.hunks.push(mergedHunk);
+    }
+  }
+
+  return ret;
+}
+
+function loadPatch(param, base) {
+  if (typeof param === 'string') {
+    if (/^@@/m.test(param) || /^Index:/m.test(param)) {
+      return (/*istanbul ignore start*/(0, _parse.parsePatch) /*istanbul ignore end*/(param)[0]
+      );
+    }
+
+    if (!base) {
+      throw new Error('Must provide a base reference or pass in a patch');
+    }
+    return (/*istanbul ignore start*/(0, _create.structuredPatch) /*istanbul ignore end*/(undefined, undefined, base, param)
+    );
+  }
+
+  return param;
+}
+
+function fileNameChanged(patch) {
+  return patch.newFileName && patch.newFileName !== patch.oldFileName;
+}
+
+function selectField(index, mine, theirs) {
+  if (mine === theirs) {
+    return mine;
+  } else {
+    index.conflict = true;
+    return { mine: mine, theirs: theirs };
+  }
+}
+
+function hunkBefore(test, check) {
+  return test.oldStart < check.oldStart && test.oldStart + test.oldLines < check.oldStart;
+}
+
+function cloneHunk(hunk, offset) {
+  return {
+    oldStart: hunk.oldStart, oldLines: hunk.oldLines,
+    newStart: hunk.newStart + offset, newLines: hunk.newLines,
+    lines: hunk.lines
+  };
+}
+
+function mergeLines(hunk, mineOffset, mineLines, theirOffset, theirLines) {
+  // This will generally result in a conflicted hunk, but there are cases where the context
+  // is the only overlap where we can successfully merge the content here.
+  var mine = { offset: mineOffset, lines: mineLines, index: 0 },
+      their = { offset: theirOffset, lines: theirLines, index: 0 };
+
+  // Handle any leading content
+  insertLeading(hunk, mine, their);
+  insertLeading(hunk, their, mine);
+
+  // Now in the overlap content. Scan through and select the best changes from each.
+  while (mine.index < mine.lines.length && their.index < their.lines.length) {
+    var mineCurrent = mine.lines[mine.index],
+        theirCurrent = their.lines[their.index];
+
+    if ((mineCurrent[0] === '-' || mineCurrent[0] === '+') && (theirCurrent[0] === '-' || theirCurrent[0] === '+')) {
+      // Both modified ...
+      mutualChange(hunk, mine, their);
+    } else if (mineCurrent[0] === '+' && theirCurrent[0] === ' ') {
+      /*istanbul ignore start*/var _hunk$lines;
+
+      /*istanbul ignore end*/ // Mine inserted
+      /*istanbul ignore start*/(_hunk$lines = /*istanbul ignore end*/hunk.lines).push. /*istanbul ignore start*/apply /*istanbul ignore end*/( /*istanbul ignore start*/_hunk$lines /*istanbul ignore end*/, /*istanbul ignore start*/_toConsumableArray( /*istanbul ignore end*/collectChange(mine)));
+    } else if (theirCurrent[0] === '+' && mineCurrent[0] === ' ') {
+      /*istanbul ignore start*/var _hunk$lines2;
+
+      /*istanbul ignore end*/ // Theirs inserted
+      /*istanbul ignore start*/(_hunk$lines2 = /*istanbul ignore end*/hunk.lines).push. /*istanbul ignore start*/apply /*istanbul ignore end*/( /*istanbul ignore start*/_hunk$lines2 /*istanbul ignore end*/, /*istanbul ignore start*/_toConsumableArray( /*istanbul ignore end*/collectChange(their)));
+    } else if (mineCurrent[0] === '-' && theirCurrent[0] === ' ') {
+      // Mine removed or edited
+      removal(hunk, mine, their);
+    } else if (theirCurrent[0] === '-' && mineCurrent[0] === ' ') {
+      // Their removed or edited
+      removal(hunk, their, mine, true);
+    } else if (mineCurrent === theirCurrent) {
+      // Context identity
+      hunk.lines.push(mineCurrent);
+      mine.index++;
+      their.index++;
+    } else {
+      // Context mismatch
+      conflict(hunk, collectChange(mine), collectChange(their));
+    }
+  }
+
+  // Now push anything that may be remaining
+  insertTrailing(hunk, mine);
+  insertTrailing(hunk, their);
+
+  calcLineCount(hunk);
+}
+
+function mutualChange(hunk, mine, their) {
+  var myChanges = collectChange(mine),
+      theirChanges = collectChange(their);
+
+  if (allRemoves(myChanges) && allRemoves(theirChanges)) {
+    // Special case for remove changes that are supersets of one another
+    if ( /*istanbul ignore start*/(0, _array.arrayStartsWith) /*istanbul ignore end*/(myChanges, theirChanges) && skipRemoveSuperset(their, myChanges, myChanges.length - theirChanges.length)) {
+      /*istanbul ignore start*/var _hunk$lines3;
+
+      /*istanbul ignore end*/ /*istanbul ignore start*/(_hunk$lines3 = /*istanbul ignore end*/hunk.lines).push. /*istanbul ignore start*/apply /*istanbul ignore end*/( /*istanbul ignore start*/_hunk$lines3 /*istanbul ignore end*/, /*istanbul ignore start*/_toConsumableArray( /*istanbul ignore end*/myChanges));
+      return;
+    } else if ( /*istanbul ignore start*/(0, _array.arrayStartsWith) /*istanbul ignore end*/(theirChanges, myChanges) && skipRemoveSuperset(mine, theirChanges, theirChanges.length - myChanges.length)) {
+      /*istanbul ignore start*/var _hunk$lines4;
+
+      /*istanbul ignore end*/ /*istanbul ignore start*/(_hunk$lines4 = /*istanbul ignore end*/hunk.lines).push. /*istanbul ignore start*/apply /*istanbul ignore end*/( /*istanbul ignore start*/_hunk$lines4 /*istanbul ignore end*/, /*istanbul ignore start*/_toConsumableArray( /*istanbul ignore end*/theirChanges));
+      return;
+    }
+  } else if ( /*istanbul ignore start*/(0, _array.arrayEqual) /*istanbul ignore end*/(myChanges, theirChanges)) {
+    /*istanbul ignore start*/var _hunk$lines5;
+
+    /*istanbul ignore end*/ /*istanbul ignore start*/(_hunk$lines5 = /*istanbul ignore end*/hunk.lines).push. /*istanbul ignore start*/apply /*istanbul ignore end*/( /*istanbul ignore start*/_hunk$lines5 /*istanbul ignore end*/, /*istanbul ignore start*/_toConsumableArray( /*istanbul ignore end*/myChanges));
+    return;
+  }
+
+  conflict(hunk, myChanges, theirChanges);
+}
+
+function removal(hunk, mine, their, swap) {
+  var myChanges = collectChange(mine),
+      theirChanges = collectContext(their, myChanges);
+  if (theirChanges.merged) {
+    /*istanbul ignore start*/var _hunk$lines6;
+
+    /*istanbul ignore end*/ /*istanbul ignore start*/(_hunk$lines6 = /*istanbul ignore end*/hunk.lines).push. /*istanbul ignore start*/apply /*istanbul ignore end*/( /*istanbul ignore start*/_hunk$lines6 /*istanbul ignore end*/, /*istanbul ignore start*/_toConsumableArray( /*istanbul ignore end*/theirChanges.merged));
+  } else {
+    conflict(hunk, swap ? theirChanges : myChanges, swap ? myChanges : theirChanges);
+  }
+}
+
+function conflict(hunk, mine, their) {
+  hunk.conflict = true;
+  hunk.lines.push({
+    conflict: true,
+    mine: mine,
+    theirs: their
+  });
+}
+
+function insertLeading(hunk, insert, their) {
+  while (insert.offset < their.offset && insert.index < insert.lines.length) {
+    var line = insert.lines[insert.index++];
+    hunk.lines.push(line);
+    insert.offset++;
+  }
+}
+function insertTrailing(hunk, insert) {
+  while (insert.index < insert.lines.length) {
+    var line = insert.lines[insert.index++];
+    hunk.lines.push(line);
+  }
+}
+
+function collectChange(state) {
+  var ret = [],
+      operation = state.lines[state.index][0];
+  while (state.index < state.lines.length) {
+    var line = state.lines[state.index];
+
+    // Group additions that are immediately after subtractions and treat them as one "atomic" modify change.
+    if (operation === '-' && line[0] === '+') {
+      operation = '+';
+    }
+
+    if (operation === line[0]) {
+      ret.push(line);
+      state.index++;
+    } else {
+      break;
+    }
+  }
+
+  return ret;
+}
+function collectContext(state, matchChanges) {
+  var changes = [],
+      merged = [],
+      matchIndex = 0,
+      contextChanges = false,
+      conflicted = false;
+  while (matchIndex < matchChanges.length && state.index < state.lines.length) {
+    var change = state.lines[state.index],
+        match = matchChanges[matchIndex];
+
+    // Once we've hit our add, then we are done
+    if (match[0] === '+') {
+      break;
+    }
+
+    contextChanges = contextChanges || change[0] !== ' ';
+
+    merged.push(match);
+    matchIndex++;
+
+    // Consume any additions in the other block as a conflict to attempt
+    // to pull in the remaining context after this
+    if (change[0] === '+') {
+      conflicted = true;
+
+      while (change[0] === '+') {
+        changes.push(change);
+        change = state.lines[++state.index];
+      }
+    }
+
+    if (match.substr(1) === change.substr(1)) {
+      changes.push(change);
+      state.index++;
+    } else {
+      conflicted = true;
+    }
+  }
+
+  if ((matchChanges[matchIndex] || '')[0] === '+' && contextChanges) {
+    conflicted = true;
+  }
+
+  if (conflicted) {
+    return changes;
+  }
+
+  while (matchIndex < matchChanges.length) {
+    merged.push(matchChanges[matchIndex++]);
+  }
+
+  return {
+    merged: merged,
+    changes: changes
+  };
+}
+
+function allRemoves(changes) {
+  return changes.reduce(function (prev, change) {
+    return prev && change[0] === '-';
+  }, true);
+}
+function skipRemoveSuperset(state, removeChanges, delta) {
+  for (var i = 0; i < delta; i++) {
+    var changeContent = removeChanges[removeChanges.length - delta + i].substr(1);
+    if (state.lines[state.index + i] !== ' ' + changeContent) {
+      return false;
+    }
+  }
+
+  state.index += delta;
+  return true;
+}
+
+function calcOldNewLineCount(lines) {
+  var oldLines = 0;
+  var newLines = 0;
+
+  lines.forEach(function (line) {
+    if (typeof line !== 'string') {
+      var myCount = calcOldNewLineCount(line.mine);
+      var theirCount = calcOldNewLineCount(line.theirs);
+
+      if (oldLines !== undefined) {
+        if (myCount.oldLines === theirCount.oldLines) {
+          oldLines += myCount.oldLines;
+        } else {
+          oldLines = undefined;
+        }
+      }
+
+      if (newLines !== undefined) {
+        if (myCount.newLines === theirCount.newLines) {
+          newLines += myCount.newLines;
+        } else {
+          newLines = undefined;
+        }
+      }
+    } else {
+      if (newLines !== undefined && (line[0] === '+' || line[0] === ' ')) {
+        newLines++;
+      }
+      if (oldLines !== undefined && (line[0] === '-' || line[0] === ' ')) {
+        oldLines++;
+      }
+    }
+  });
+
+  return { oldLines: oldLines, newLines: newLines };
+}
+//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9wYXRjaC9tZXJnZS5qcyJdLCJuYW1lcyI6WyJjYWxjTGluZUNvdW50IiwibWVyZ2UiLCJodW5rIiwiY2FsY09sZE5ld0xpbmVDb3VudCIsImxpbmVzIiwib2xkTGluZXMiLCJuZXdMaW5lcyIsInVuZGVmaW5lZCIsIm1pbmUiLCJ0aGVpcnMiLCJiYXNlIiwibG9hZFBhdGNoIiwicmV0IiwiaW5kZXgiLCJuZXdGaWxlTmFtZSIsImZpbGVOYW1lQ2hhbmdlZCIsIm9sZEZpbGVOYW1lIiwib2xkSGVhZGVyIiwibmV3SGVhZGVyIiwic2VsZWN0RmllbGQiLCJodW5rcyIsIm1pbmVJbmRleCIsInRoZWlyc0luZGV4IiwibWluZU9mZnNldCIsInRoZWlyc09mZnNldCIsImxlbmd0aCIsIm1pbmVDdXJyZW50Iiwib2xkU3RhcnQiLCJJbmZpbml0eSIsInRoZWlyc0N1cnJlbnQiLCJodW5rQmVmb3JlIiwicHVzaCIsImNsb25lSHVuayIsIm1lcmdlZEh1bmsiLCJNYXRoIiwibWluIiwibmV3U3RhcnQiLCJtZXJnZUxpbmVzIiwicGFyYW0iLCJ0ZXN0IiwiRXJyb3IiLCJwYXRjaCIsImNvbmZsaWN0IiwiY2hlY2siLCJvZmZzZXQiLCJtaW5lTGluZXMiLCJ0aGVpck9mZnNldCIsInRoZWlyTGluZXMiLCJ0aGVpciIsImluc2VydExlYWRpbmciLCJ0aGVpckN1cnJlbnQiLCJtdXR1YWxDaGFuZ2UiLCJjb2xsZWN0Q2hhbmdlIiwicmVtb3ZhbCIsImluc2VydFRyYWlsaW5nIiwibXlDaGFuZ2VzIiwidGhlaXJDaGFuZ2VzIiwiYWxsUmVtb3ZlcyIsInNraXBSZW1vdmVTdXBlcnNldCIsInN3YXAiLCJjb2xsZWN0Q29udGV4dCIsIm1lcmdlZCIsImluc2VydCIsImxpbmUiLCJzdGF0ZSIsIm9wZXJhdGlvbiIsIm1hdGNoQ2hhbmdlcyIsImNoYW5nZXMiLCJtYXRjaEluZGV4IiwiY29udGV4dENoYW5nZXMiLCJjb25mbGljdGVkIiwiY2hhbmdlIiwibWF0Y2giLCJzdWJzdHIiLCJyZWR1Y2UiLCJwcmV2IiwicmVtb3ZlQ2hhbmdlcyIsImRlbHRhIiwiaSIsImNoYW5nZUNvbnRlbnQiLCJmb3JFYWNoIiwibXlDb3VudCIsInRoZWlyQ291bnQiXSwibWFwcGluZ3MiOiI7OztnQ0FLZ0JBLGEsR0FBQUEsYTt5REFnQkFDLEssR0FBQUEsSzs7QUFyQmhCOztBQUNBOztBQUVBOzs7O3VCQUVPLFNBQVNELGFBQVQsQ0FBdUJFLElBQXZCLEVBQTZCO0FBQUEsNkVBQ0xDLG9CQUFvQkQsS0FBS0UsS0FBekIsQ0FESztBQUFBLE1BQzNCQyxRQUQyQix3QkFDM0JBLFFBRDJCO0FBQUEsTUFDakJDLFFBRGlCLHdCQUNqQkEsUUFEaUI7O0FBR2xDLE1BQUlELGFBQWFFLFNBQWpCLEVBQTRCO0FBQzFCTCxTQUFLRyxRQUFMLEdBQWdCQSxRQUFoQjtBQUNELEdBRkQsTUFFTztBQUNMLFdBQU9ILEtBQUtHLFFBQVo7QUFDRDs7QUFFRCxNQUFJQyxhQUFhQyxTQUFqQixFQUE0QjtBQUMxQkwsU0FBS0ksUUFBTCxHQUFnQkEsUUFBaEI7QUFDRCxHQUZELE1BRU87QUFDTCxXQUFPSixLQUFLSSxRQUFaO0FBQ0Q7QUFDRjs7QUFFTSxTQUFTTCxLQUFULENBQWVPLElBQWYsRUFBcUJDLE1BQXJCLEVBQTZCQyxJQUE3QixFQUFtQztBQUN4Q0YsU0FBT0csVUFBVUgsSUFBVixFQUFnQkUsSUFBaEIsQ0FBUDtBQUNBRCxXQUFTRSxVQUFVRixNQUFWLEVBQWtCQyxJQUFsQixDQUFUOztBQUVBLE1BQUlFLE1BQU0sRUFBVjs7QUFFQTtBQUNBO0FBQ0E7QUFDQSxNQUFJSixLQUFLSyxLQUFMLElBQWNKLE9BQU9JLEtBQXpCLEVBQWdDO0FBQzlCRCxRQUFJQyxLQUFKLEdBQVlMLEtBQUtLLEtBQUwsSUFBY0osT0FBT0ksS0FBakM7QUFDRDs7QUFFRCxNQUFJTCxLQUFLTSxXQUFMLElBQW9CTCxPQUFPSyxXQUEvQixFQUE0QztBQUMxQyxRQUFJLENBQUNDLGdCQUFnQlAsSUFBaEIsQ0FBTCxFQUE0QjtBQUMxQjtBQUNBSSxVQUFJSSxXQUFKLEdBQWtCUCxPQUFPTyxXQUFQLElBQXNCUixLQUFLUSxXQUE3QztBQUNBSixVQUFJRSxXQUFKLEdBQWtCTCxPQUFPSyxXQUFQLElBQXNCTixLQUFLTSxXQUE3QztBQUNBRixVQUFJSyxTQUFKLEdBQWdCUixPQUFPUSxTQUFQLElBQW9CVCxLQUFLUyxTQUF6QztBQUNBTCxVQUFJTSxTQUFKLEdBQWdCVCxPQUFPUyxTQUFQLElBQW9CVixLQUFLVSxTQUF6QztBQUNELEtBTkQsTUFNTyxJQUFJLENBQUNILGdCQUFnQk4sTUFBaEIsQ0FBTCxFQUE4QjtBQUNuQztBQUNBRyxVQUFJSSxXQUFKLEdBQWtCUixLQUFLUSxXQUF2QjtBQUNBSixVQUFJRSxXQUFKLEdBQWtCTixLQUFLTSxXQUF2QjtBQUNBRixVQUFJSyxTQUFKLEdBQWdCVCxLQUFLUyxTQUFyQjtBQUNBTCxVQUFJTSxTQUFKLEdBQWdCVixLQUFLVSxTQUFyQjtBQUNELEtBTk0sTUFNQTtBQUNMO0FBQ0FOLFVBQUlJLFdBQUosR0FBa0JHLFlBQVlQLEdBQVosRUFBaUJKLEtBQUtRLFdBQXRCLEVBQW1DUCxPQUFPTyxXQUExQyxDQUFsQjtBQUNBSixVQUFJRSxXQUFKLEdBQWtCSyxZQUFZUCxHQUFaLEVBQWlCSixLQUFLTSxXQUF0QixFQUFtQ0wsT0FBT0ssV0FBMUMsQ0FBbEI7QUFDQUYsVUFBSUssU0FBSixHQUFnQkUsWUFBWVAsR0FBWixFQUFpQkosS0FBS1MsU0FBdEIsRUFBaUNSLE9BQU9RLFNBQXhDLENBQWhCO0FBQ0FMLFVBQUlNLFNBQUosR0FBZ0JDLFlBQVlQLEdBQVosRUFBaUJKLEtBQUtVLFNBQXRCLEVBQWlDVCxPQUFPUyxTQUF4QyxDQUFoQjtBQUNEO0FBQ0Y7O0FBRUROLE1BQUlRLEtBQUosR0FBWSxFQUFaOztBQUVBLE1BQUlDLFlBQVksQ0FBaEI7QUFBQSxNQUNJQyxjQUFjLENBRGxCO0FBQUEsTUFFSUMsYUFBYSxDQUZqQjtBQUFBLE1BR0lDLGVBQWUsQ0FIbkI7O0FBS0EsU0FBT0gsWUFBWWIsS0FBS1ksS0FBTCxDQUFXSyxNQUF2QixJQUFpQ0gsY0FBY2IsT0FBT1csS0FBUCxDQUFhSyxNQUFuRSxFQUEyRTtBQUN6RSxRQUFJQyxjQUFjbEIsS0FBS1ksS0FBTCxDQUFXQyxTQUFYLEtBQXlCLEVBQUNNLFVBQVVDLFFBQVgsRUFBM0M7QUFBQSxRQUNJQyxnQkFBZ0JwQixPQUFPVyxLQUFQLENBQWFFLFdBQWIsS0FBNkIsRUFBQ0ssVUFBVUMsUUFBWCxFQURqRDs7QUFHQSxRQUFJRSxXQUFXSixXQUFYLEVBQXdCRyxhQUF4QixDQUFKLEVBQTRDO0FBQzFDO0FBQ0FqQixVQUFJUSxLQUFKLENBQVVXLElBQVYsQ0FBZUMsVUFBVU4sV0FBVixFQUF1QkgsVUFBdkIsQ0FBZjtBQUNBRjtBQUNBRyxzQkFBZ0JFLFlBQVlwQixRQUFaLEdBQXVCb0IsWUFBWXJCLFFBQW5EO0FBQ0QsS0FMRCxNQUtPLElBQUl5QixXQUFXRCxhQUFYLEVBQTBCSCxXQUExQixDQUFKLEVBQTRDO0FBQ2pEO0FBQ0FkLFVBQUlRLEtBQUosQ0FBVVcsSUFBVixDQUFlQyxVQUFVSCxhQUFWLEVBQXlCTCxZQUF6QixDQUFmO0FBQ0FGO0FBQ0FDLG9CQUFjTSxjQUFjdkIsUUFBZCxHQUF5QnVCLGNBQWN4QixRQUFyRDtBQUNELEtBTE0sTUFLQTtBQUNMO0FBQ0EsVUFBSTRCLGFBQWE7QUFDZk4sa0JBQVVPLEtBQUtDLEdBQUwsQ0FBU1QsWUFBWUMsUUFBckIsRUFBK0JFLGNBQWNGLFFBQTdDLENBREs7QUFFZnRCLGtCQUFVLENBRks7QUFHZitCLGtCQUFVRixLQUFLQyxHQUFMLENBQVNULFlBQVlVLFFBQVosR0FBdUJiLFVBQWhDLEVBQTRDTSxjQUFjRixRQUFkLEdBQXlCSCxZQUFyRSxDQUhLO0FBSWZsQixrQkFBVSxDQUpLO0FBS2ZGLGVBQU87QUFMUSxPQUFqQjtBQU9BaUMsaUJBQVdKLFVBQVgsRUFBdUJQLFlBQVlDLFFBQW5DLEVBQTZDRCxZQUFZdEIsS0FBekQsRUFBZ0V5QixjQUFjRixRQUE5RSxFQUF3RkUsY0FBY3pCLEtBQXRHO0FBQ0FrQjtBQUNBRDs7QUFFQVQsVUFBSVEsS0FBSixDQUFVVyxJQUFWLENBQWVFLFVBQWY7QUFDRDtBQUNGOztBQUVELFNBQU9yQixHQUFQO0FBQ0Q7O0FBRUQsU0FBU0QsU0FBVCxDQUFtQjJCLEtBQW5CLEVBQTBCNUIsSUFBMUIsRUFBZ0M7QUFDOUIsTUFBSSxPQUFPNEIsS0FBUCxLQUFpQixRQUFyQixFQUErQjtBQUM3QixRQUFJLE9BQU9DLElBQVAsQ0FBWUQsS0FBWixLQUF1QixXQUFXQyxJQUFYLENBQWdCRCxLQUFoQixDQUEzQixFQUFvRDtBQUNsRCxhQUFPLHlFQUFXQSxLQUFYLEVBQWtCLENBQWxCO0FBQVA7QUFDRDs7QUFFRCxRQUFJLENBQUM1QixJQUFMLEVBQVc7QUFDVCxZQUFNLElBQUk4QixLQUFKLENBQVUsa0RBQVYsQ0FBTjtBQUNEO0FBQ0QsV0FBTywrRUFBZ0JqQyxTQUFoQixFQUEyQkEsU0FBM0IsRUFBc0NHLElBQXRDLEVBQTRDNEIsS0FBNUM7QUFBUDtBQUNEOztBQUVELFNBQU9BLEtBQVA7QUFDRDs7QUFFRCxTQUFTdkIsZUFBVCxDQUF5QjBCLEtBQXpCLEVBQWdDO0FBQzlCLFNBQU9BLE1BQU0zQixXQUFOLElBQXFCMkIsTUFBTTNCLFdBQU4sS0FBc0IyQixNQUFNekIsV0FBeEQ7QUFDRDs7QUFFRCxTQUFTRyxXQUFULENBQXFCTixLQUFyQixFQUE0QkwsSUFBNUIsRUFBa0NDLE1BQWxDLEVBQTBDO0FBQ3hDLE1BQUlELFNBQVNDLE1BQWIsRUFBcUI7QUFDbkIsV0FBT0QsSUFBUDtBQUNELEdBRkQsTUFFTztBQUNMSyxVQUFNNkIsUUFBTixHQUFpQixJQUFqQjtBQUNBLFdBQU8sRUFBQ2xDLFVBQUQsRUFBT0MsY0FBUCxFQUFQO0FBQ0Q7QUFDRjs7QUFFRCxTQUFTcUIsVUFBVCxDQUFvQlMsSUFBcEIsRUFBMEJJLEtBQTFCLEVBQWlDO0FBQy9CLFNBQU9KLEtBQUtaLFFBQUwsR0FBZ0JnQixNQUFNaEIsUUFBdEIsSUFDRFksS0FBS1osUUFBTCxHQUFnQlksS0FBS2xDLFFBQXRCLEdBQWtDc0MsTUFBTWhCLFFBRDdDO0FBRUQ7O0FBRUQsU0FBU0ssU0FBVCxDQUFtQjlCLElBQW5CLEVBQXlCMEMsTUFBekIsRUFBaUM7QUFDL0IsU0FBTztBQUNMakIsY0FBVXpCLEtBQUt5QixRQURWLEVBQ29CdEIsVUFBVUgsS0FBS0csUUFEbkM7QUFFTCtCLGNBQVVsQyxLQUFLa0MsUUFBTCxHQUFnQlEsTUFGckIsRUFFNkJ0QyxVQUFVSixLQUFLSSxRQUY1QztBQUdMRixXQUFPRixLQUFLRTtBQUhQLEdBQVA7QUFLRDs7QUFFRCxTQUFTaUMsVUFBVCxDQUFvQm5DLElBQXBCLEVBQTBCcUIsVUFBMUIsRUFBc0NzQixTQUF0QyxFQUFpREMsV0FBakQsRUFBOERDLFVBQTlELEVBQTBFO0FBQ3hFO0FBQ0E7QUFDQSxNQUFJdkMsT0FBTyxFQUFDb0MsUUFBUXJCLFVBQVQsRUFBcUJuQixPQUFPeUMsU0FBNUIsRUFBdUNoQyxPQUFPLENBQTlDLEVBQVg7QUFBQSxNQUNJbUMsUUFBUSxFQUFDSixRQUFRRSxXQUFULEVBQXNCMUMsT0FBTzJDLFVBQTdCLEVBQXlDbEMsT0FBTyxDQUFoRCxFQURaOztBQUdBO0FBQ0FvQyxnQkFBYy9DLElBQWQsRUFBb0JNLElBQXBCLEVBQTBCd0MsS0FBMUI7QUFDQUMsZ0JBQWMvQyxJQUFkLEVBQW9COEMsS0FBcEIsRUFBMkJ4QyxJQUEzQjs7QUFFQTtBQUNBLFNBQU9BLEtBQUtLLEtBQUwsR0FBYUwsS0FBS0osS0FBTCxDQUFXcUIsTUFBeEIsSUFBa0N1QixNQUFNbkMsS0FBTixHQUFjbUMsTUFBTTVDLEtBQU4sQ0FBWXFCLE1BQW5FLEVBQTJFO0FBQ3pFLFFBQUlDLGNBQWNsQixLQUFLSixLQUFMLENBQVdJLEtBQUtLLEtBQWhCLENBQWxCO0FBQUEsUUFDSXFDLGVBQWVGLE1BQU01QyxLQUFOLENBQVk0QyxNQUFNbkMsS0FBbEIsQ0FEbkI7O0FBR0EsUUFBSSxDQUFDYSxZQUFZLENBQVosTUFBbUIsR0FBbkIsSUFBMEJBLFlBQVksQ0FBWixNQUFtQixHQUE5QyxNQUNJd0IsYUFBYSxDQUFiLE1BQW9CLEdBQXBCLElBQTJCQSxhQUFhLENBQWIsTUFBb0IsR0FEbkQsQ0FBSixFQUM2RDtBQUMzRDtBQUNBQyxtQkFBYWpELElBQWIsRUFBbUJNLElBQW5CLEVBQXlCd0MsS0FBekI7QUFDRCxLQUpELE1BSU8sSUFBSXRCLFlBQVksQ0FBWixNQUFtQixHQUFuQixJQUEwQndCLGFBQWEsQ0FBYixNQUFvQixHQUFsRCxFQUF1RDtBQUFBOztBQUFBLDhCQUM1RDtBQUNBLDBFQUFLOUMsS0FBTCxFQUFXMkIsSUFBWCw0TEFBb0JxQixjQUFjNUMsSUFBZCxDQUFwQjtBQUNELEtBSE0sTUFHQSxJQUFJMEMsYUFBYSxDQUFiLE1BQW9CLEdBQXBCLElBQTJCeEIsWUFBWSxDQUFaLE1BQW1CLEdBQWxELEVBQXVEO0FBQUE7O0FBQUEsOEJBQzVEO0FBQ0EsMkVBQUt0QixLQUFMLEVBQVcyQixJQUFYLDZMQUFvQnFCLGNBQWNKLEtBQWQsQ0FBcEI7QUFDRCxLQUhNLE1BR0EsSUFBSXRCLFlBQVksQ0FBWixNQUFtQixHQUFuQixJQUEwQndCLGFBQWEsQ0FBYixNQUFvQixHQUFsRCxFQUF1RDtBQUM1RDtBQUNBRyxjQUFRbkQsSUFBUixFQUFjTSxJQUFkLEVBQW9Cd0MsS0FBcEI7QUFDRCxLQUhNLE1BR0EsSUFBSUUsYUFBYSxDQUFiLE1BQW9CLEdBQXBCLElBQTJCeEIsWUFBWSxDQUFaLE1BQW1CLEdBQWxELEVBQXVEO0FBQzVEO0FBQ0EyQixjQUFRbkQsSUFBUixFQUFjOEMsS0FBZCxFQUFxQnhDLElBQXJCLEVBQTJCLElBQTNCO0FBQ0QsS0FITSxNQUdBLElBQUlrQixnQkFBZ0J3QixZQUFwQixFQUFrQztBQUN2QztBQUNBaEQsV0FBS0UsS0FBTCxDQUFXMkIsSUFBWCxDQUFnQkwsV0FBaEI7QUFDQWxCLFdBQUtLLEtBQUw7QUFDQW1DLFlBQU1uQyxLQUFOO0FBQ0QsS0FMTSxNQUtBO0FBQ0w7QUFDQTZCLGVBQVN4QyxJQUFULEVBQWVrRCxjQUFjNUMsSUFBZCxDQUFmLEVBQW9DNEMsY0FBY0osS0FBZCxDQUFwQztBQUNEO0FBQ0Y7O0FBRUQ7QUFDQU0saUJBQWVwRCxJQUFmLEVBQXFCTSxJQUFyQjtBQUNBOEMsaUJBQWVwRCxJQUFmLEVBQXFCOEMsS0FBckI7O0FBRUFoRCxnQkFBY0UsSUFBZDtBQUNEOztBQUVELFNBQVNpRCxZQUFULENBQXNCakQsSUFBdEIsRUFBNEJNLElBQTVCLEVBQWtDd0MsS0FBbEMsRUFBeUM7QUFDdkMsTUFBSU8sWUFBWUgsY0FBYzVDLElBQWQsQ0FBaEI7QUFBQSxNQUNJZ0QsZUFBZUosY0FBY0osS0FBZCxDQURuQjs7QUFHQSxNQUFJUyxXQUFXRixTQUFYLEtBQXlCRSxXQUFXRCxZQUFYLENBQTdCLEVBQXVEO0FBQ3JEO0FBQ0EsUUFBSSw4RUFBZ0JELFNBQWhCLEVBQTJCQyxZQUEzQixLQUNHRSxtQkFBbUJWLEtBQW5CLEVBQTBCTyxTQUExQixFQUFxQ0EsVUFBVTlCLE1BQVYsR0FBbUIrQixhQUFhL0IsTUFBckUsQ0FEUCxFQUNxRjtBQUFBOztBQUFBLDZCQUNuRixzRUFBS3JCLEtBQUwsRUFBVzJCLElBQVgsNkxBQW9Cd0IsU0FBcEI7QUFDQTtBQUNELEtBSkQsTUFJTyxJQUFJLDhFQUFnQkMsWUFBaEIsRUFBOEJELFNBQTlCLEtBQ0pHLG1CQUFtQmxELElBQW5CLEVBQXlCZ0QsWUFBekIsRUFBdUNBLGFBQWEvQixNQUFiLEdBQXNCOEIsVUFBVTlCLE1BQXZFLENBREEsRUFDZ0Y7QUFBQTs7QUFBQSw2QkFDckYsc0VBQUtyQixLQUFMLEVBQVcyQixJQUFYLDZMQUFvQnlCLFlBQXBCO0FBQ0E7QUFDRDtBQUNGLEdBWEQsTUFXTyxJQUFJLHlFQUFXRCxTQUFYLEVBQXNCQyxZQUF0QixDQUFKLEVBQXlDO0FBQUE7O0FBQUEsMkJBQzlDLHNFQUFLcEQsS0FBTCxFQUFXMkIsSUFBWCw2TEFBb0J3QixTQUFwQjtBQUNBO0FBQ0Q7O0FBRURiLFdBQVN4QyxJQUFULEVBQWVxRCxTQUFmLEVBQTBCQyxZQUExQjtBQUNEOztBQUVELFNBQVNILE9BQVQsQ0FBaUJuRCxJQUFqQixFQUF1Qk0sSUFBdkIsRUFBNkJ3QyxLQUE3QixFQUFvQ1csSUFBcEMsRUFBMEM7QUFDeEMsTUFBSUosWUFBWUgsY0FBYzVDLElBQWQsQ0FBaEI7QUFBQSxNQUNJZ0QsZUFBZUksZUFBZVosS0FBZixFQUFzQk8sU0FBdEIsQ0FEbkI7QUFFQSxNQUFJQyxhQUFhSyxNQUFqQixFQUF5QjtBQUFBOztBQUFBLDJCQUN2QixzRUFBS3pELEtBQUwsRUFBVzJCLElBQVgsNkxBQW9CeUIsYUFBYUssTUFBakM7QUFDRCxHQUZELE1BRU87QUFDTG5CLGFBQVN4QyxJQUFULEVBQWV5RCxPQUFPSCxZQUFQLEdBQXNCRCxTQUFyQyxFQUFnREksT0FBT0osU0FBUCxHQUFtQkMsWUFBbkU7QUFDRDtBQUNGOztBQUVELFNBQVNkLFFBQVQsQ0FBa0J4QyxJQUFsQixFQUF3Qk0sSUFBeEIsRUFBOEJ3QyxLQUE5QixFQUFxQztBQUNuQzlDLE9BQUt3QyxRQUFMLEdBQWdCLElBQWhCO0FBQ0F4QyxPQUFLRSxLQUFMLENBQVcyQixJQUFYLENBQWdCO0FBQ2RXLGNBQVUsSUFESTtBQUVkbEMsVUFBTUEsSUFGUTtBQUdkQyxZQUFRdUM7QUFITSxHQUFoQjtBQUtEOztBQUVELFNBQVNDLGFBQVQsQ0FBdUIvQyxJQUF2QixFQUE2QjRELE1BQTdCLEVBQXFDZCxLQUFyQyxFQUE0QztBQUMxQyxTQUFPYyxPQUFPbEIsTUFBUCxHQUFnQkksTUFBTUosTUFBdEIsSUFBZ0NrQixPQUFPakQsS0FBUCxHQUFlaUQsT0FBTzFELEtBQVAsQ0FBYXFCLE1BQW5FLEVBQTJFO0FBQ3pFLFFBQUlzQyxPQUFPRCxPQUFPMUQsS0FBUCxDQUFhMEQsT0FBT2pELEtBQVAsRUFBYixDQUFYO0FBQ0FYLFNBQUtFLEtBQUwsQ0FBVzJCLElBQVgsQ0FBZ0JnQyxJQUFoQjtBQUNBRCxXQUFPbEIsTUFBUDtBQUNEO0FBQ0Y7QUFDRCxTQUFTVSxjQUFULENBQXdCcEQsSUFBeEIsRUFBOEI0RCxNQUE5QixFQUFzQztBQUNwQyxTQUFPQSxPQUFPakQsS0FBUCxHQUFlaUQsT0FBTzFELEtBQVAsQ0FBYXFCLE1BQW5DLEVBQTJDO0FBQ3pDLFFBQUlzQyxPQUFPRCxPQUFPMUQsS0FBUCxDQUFhMEQsT0FBT2pELEtBQVAsRUFBYixDQUFYO0FBQ0FYLFNBQUtFLEtBQUwsQ0FBVzJCLElBQVgsQ0FBZ0JnQyxJQUFoQjtBQUNEO0FBQ0Y7O0FBRUQsU0FBU1gsYUFBVCxDQUF1QlksS0FBdkIsRUFBOEI7QUFDNUIsTUFBSXBELE1BQU0sRUFBVjtBQUFBLE1BQ0lxRCxZQUFZRCxNQUFNNUQsS0FBTixDQUFZNEQsTUFBTW5ELEtBQWxCLEVBQXlCLENBQXpCLENBRGhCO0FBRUEsU0FBT21ELE1BQU1uRCxLQUFOLEdBQWNtRCxNQUFNNUQsS0FBTixDQUFZcUIsTUFBakMsRUFBeUM7QUFDdkMsUUFBSXNDLE9BQU9DLE1BQU01RCxLQUFOLENBQVk0RCxNQUFNbkQsS0FBbEIsQ0FBWDs7QUFFQTtBQUNBLFFBQUlvRCxjQUFjLEdBQWQsSUFBcUJGLEtBQUssQ0FBTCxNQUFZLEdBQXJDLEVBQTBDO0FBQ3hDRSxrQkFBWSxHQUFaO0FBQ0Q7O0FBRUQsUUFBSUEsY0FBY0YsS0FBSyxDQUFMLENBQWxCLEVBQTJCO0FBQ3pCbkQsVUFBSW1CLElBQUosQ0FBU2dDLElBQVQ7QUFDQUMsWUFBTW5ELEtBQU47QUFDRCxLQUhELE1BR087QUFDTDtBQUNEO0FBQ0Y7O0FBRUQsU0FBT0QsR0FBUDtBQUNEO0FBQ0QsU0FBU2dELGNBQVQsQ0FBd0JJLEtBQXhCLEVBQStCRSxZQUEvQixFQUE2QztBQUMzQyxNQUFJQyxVQUFVLEVBQWQ7QUFBQSxNQUNJTixTQUFTLEVBRGI7QUFBQSxNQUVJTyxhQUFhLENBRmpCO0FBQUEsTUFHSUMsaUJBQWlCLEtBSHJCO0FBQUEsTUFJSUMsYUFBYSxLQUpqQjtBQUtBLFNBQU9GLGFBQWFGLGFBQWF6QyxNQUExQixJQUNFdUMsTUFBTW5ELEtBQU4sR0FBY21ELE1BQU01RCxLQUFOLENBQVlxQixNQURuQyxFQUMyQztBQUN6QyxRQUFJOEMsU0FBU1AsTUFBTTVELEtBQU4sQ0FBWTRELE1BQU1uRCxLQUFsQixDQUFiO0FBQUEsUUFDSTJELFFBQVFOLGFBQWFFLFVBQWIsQ0FEWjs7QUFHQTtBQUNBLFFBQUlJLE1BQU0sQ0FBTixNQUFhLEdBQWpCLEVBQXNCO0FBQ3BCO0FBQ0Q7O0FBRURILHFCQUFpQkEsa0JBQWtCRSxPQUFPLENBQVAsTUFBYyxHQUFqRDs7QUFFQVYsV0FBTzlCLElBQVAsQ0FBWXlDLEtBQVo7QUFDQUo7O0FBRUE7QUFDQTtBQUNBLFFBQUlHLE9BQU8sQ0FBUCxNQUFjLEdBQWxCLEVBQXVCO0FBQ3JCRCxtQkFBYSxJQUFiOztBQUVBLGFBQU9DLE9BQU8sQ0FBUCxNQUFjLEdBQXJCLEVBQTBCO0FBQ3hCSixnQkFBUXBDLElBQVIsQ0FBYXdDLE1BQWI7QUFDQUEsaUJBQVNQLE1BQU01RCxLQUFOLENBQVksRUFBRTRELE1BQU1uRCxLQUFwQixDQUFUO0FBQ0Q7QUFDRjs7QUFFRCxRQUFJMkQsTUFBTUMsTUFBTixDQUFhLENBQWIsTUFBb0JGLE9BQU9FLE1BQVAsQ0FBYyxDQUFkLENBQXhCLEVBQTBDO0FBQ3hDTixjQUFRcEMsSUFBUixDQUFhd0MsTUFBYjtBQUNBUCxZQUFNbkQsS0FBTjtBQUNELEtBSEQsTUFHTztBQUNMeUQsbUJBQWEsSUFBYjtBQUNEO0FBQ0Y7O0FBRUQsTUFBSSxDQUFDSixhQUFhRSxVQUFiLEtBQTRCLEVBQTdCLEVBQWlDLENBQWpDLE1BQXdDLEdBQXhDLElBQ0dDLGNBRFAsRUFDdUI7QUFDckJDLGlCQUFhLElBQWI7QUFDRDs7QUFFRCxNQUFJQSxVQUFKLEVBQWdCO0FBQ2QsV0FBT0gsT0FBUDtBQUNEOztBQUVELFNBQU9DLGFBQWFGLGFBQWF6QyxNQUFqQyxFQUF5QztBQUN2Q29DLFdBQU85QixJQUFQLENBQVltQyxhQUFhRSxZQUFiLENBQVo7QUFDRDs7QUFFRCxTQUFPO0FBQ0xQLGtCQURLO0FBRUxNO0FBRkssR0FBUDtBQUlEOztBQUVELFNBQVNWLFVBQVQsQ0FBb0JVLE9BQXBCLEVBQTZCO0FBQzNCLFNBQU9BLFFBQVFPLE1BQVIsQ0FBZSxVQUFTQyxJQUFULEVBQWVKLE1BQWYsRUFBdUI7QUFDM0MsV0FBT0ksUUFBUUosT0FBTyxDQUFQLE1BQWMsR0FBN0I7QUFDRCxHQUZNLEVBRUosSUFGSSxDQUFQO0FBR0Q7QUFDRCxTQUFTYixrQkFBVCxDQUE0Qk0sS0FBNUIsRUFBbUNZLGFBQW5DLEVBQWtEQyxLQUFsRCxFQUF5RDtBQUN2RCxPQUFLLElBQUlDLElBQUksQ0FBYixFQUFnQkEsSUFBSUQsS0FBcEIsRUFBMkJDLEdBQTNCLEVBQWdDO0FBQzlCLFFBQUlDLGdCQUFnQkgsY0FBY0EsY0FBY25ELE1BQWQsR0FBdUJvRCxLQUF2QixHQUErQkMsQ0FBN0MsRUFBZ0RMLE1BQWhELENBQXVELENBQXZELENBQXBCO0FBQ0EsUUFBSVQsTUFBTTVELEtBQU4sQ0FBWTRELE1BQU1uRCxLQUFOLEdBQWNpRSxDQUExQixNQUFpQyxNQUFNQyxhQUEzQyxFQUEwRDtBQUN4RCxhQUFPLEtBQVA7QUFDRDtBQUNGOztBQUVEZixRQUFNbkQsS0FBTixJQUFlZ0UsS0FBZjtBQUNBLFNBQU8sSUFBUDtBQUNEOztBQUVELFNBQVMxRSxtQkFBVCxDQUE2QkMsS0FBN0IsRUFBb0M7QUFDbEMsTUFBSUMsV0FBVyxDQUFmO0FBQ0EsTUFBSUMsV0FBVyxDQUFmOztBQUVBRixRQUFNNEUsT0FBTixDQUFjLFVBQVNqQixJQUFULEVBQWU7QUFDM0IsUUFBSSxPQUFPQSxJQUFQLEtBQWdCLFFBQXBCLEVBQThCO0FBQzVCLFVBQUlrQixVQUFVOUUsb0JBQW9CNEQsS0FBS3ZELElBQXpCLENBQWQ7QUFDQSxVQUFJMEUsYUFBYS9FLG9CQUFvQjRELEtBQUt0RCxNQUF6QixDQUFqQjs7QUFFQSxVQUFJSixhQUFhRSxTQUFqQixFQUE0QjtBQUMxQixZQUFJMEUsUUFBUTVFLFFBQVIsS0FBcUI2RSxXQUFXN0UsUUFBcEMsRUFBOEM7QUFDNUNBLHNCQUFZNEUsUUFBUTVFLFFBQXBCO0FBQ0QsU0FGRCxNQUVPO0FBQ0xBLHFCQUFXRSxTQUFYO0FBQ0Q7QUFDRjs7QUFFRCxVQUFJRCxhQUFhQyxTQUFqQixFQUE0QjtBQUMxQixZQUFJMEUsUUFBUTNFLFFBQVIsS0FBcUI0RSxXQUFXNUUsUUFBcEMsRUFBOEM7QUFDNUNBLHNCQUFZMkUsUUFBUTNFLFFBQXBCO0FBQ0QsU0FGRCxNQUVPO0FBQ0xBLHFCQUFXQyxTQUFYO0FBQ0Q7QUFDRjtBQUNGLEtBbkJELE1BbUJPO0FBQ0wsVUFBSUQsYUFBYUMsU0FBYixLQUEyQndELEtBQUssQ0FBTCxNQUFZLEdBQVosSUFBbUJBLEtBQUssQ0FBTCxNQUFZLEdBQTFELENBQUosRUFBb0U7QUFDbEV6RDtBQUNEO0FBQ0QsVUFBSUQsYUFBYUUsU0FBYixLQUEyQndELEtBQUssQ0FBTCxNQUFZLEdBQVosSUFBbUJBLEtBQUssQ0FBTCxNQUFZLEdBQTFELENBQUosRUFBb0U7QUFDbEUxRDtBQUNEO0FBQ0Y7QUFDRixHQTVCRDs7QUE4QkEsU0FBTyxFQUFDQSxrQkFBRCxFQUFXQyxrQkFBWCxFQUFQO0FBQ0QiLCJmaWxlIjoibWVyZ2UuanMiLCJzb3VyY2VzQ29udGVudCI6WyJpbXBvcnQge3N0cnVjdHVyZWRQYXRjaH0gZnJvbSAnLi9jcmVhdGUnO1xuaW1wb3J0IHtwYXJzZVBhdGNofSBmcm9tICcuL3BhcnNlJztcblxuaW1wb3J0IHthcnJheUVxdWFsLCBhcnJheVN0YXJ0c1dpdGh9IGZyb20gJy4uL3V0aWwvYXJyYXknO1xuXG5leHBvcnQgZnVuY3Rpb24gY2FsY0xpbmVDb3VudChodW5rKSB7XG4gIGNvbnN0IHtvbGRMaW5lcywgbmV3TGluZXN9ID0gY2FsY09sZE5ld0xpbmVDb3VudChodW5rLmxpbmVzKTtcblxuICBpZiAob2xkTGluZXMgIT09IHVuZGVmaW5lZCkge1xuICAgIGh1bmsub2xkTGluZXMgPSBvbGRMaW5lcztcbiAgfSBlbHNlIHtcbiAgICBkZWxldGUgaHVuay5vbGRMaW5lcztcbiAgfVxuXG4gIGlmIChuZXdMaW5lcyAhPT0gdW5kZWZpbmVkKSB7XG4gICAgaHVuay5uZXdMaW5lcyA9IG5ld0xpbmVzO1xuICB9IGVsc2Uge1xuICAgIGRlbGV0ZSBodW5rLm5ld0xpbmVzO1xuICB9XG59XG5cbmV4cG9ydCBmdW5jdGlvbiBtZXJnZShtaW5lLCB0aGVpcnMsIGJhc2UpIHtcbiAgbWluZSA9IGxvYWRQYXRjaChtaW5lLCBiYXNlKTtcbiAgdGhlaXJzID0gbG9hZFBhdGNoKHRoZWlycywgYmFzZSk7XG5cbiAgbGV0IHJldCA9IHt9O1xuXG4gIC8vIEZvciBpbmRleCB3ZSBqdXN0IGxldCBpdCBwYXNzIHRocm91Z2ggYXMgaXQgZG9lc24ndCBoYXZlIGFueSBuZWNlc3NhcnkgbWVhbmluZy5cbiAgLy8gTGVhdmluZyBzYW5pdHkgY2hlY2tzIG9uIHRoaXMgdG8gdGhlIEFQSSBjb25zdW1lciB0aGF0IG1heSBrbm93IG1vcmUgYWJvdXQgdGhlXG4gIC8vIG1lYW5pbmcgaW4gdGhlaXIgb3duIGNvbnRleHQuXG4gIGlmIChtaW5lLmluZGV4IHx8IHRoZWlycy5pbmRleCkge1xuICAgIHJldC5pbmRleCA9IG1pbmUuaW5kZXggfHwgdGhlaXJzLmluZGV4O1xuICB9XG5cbiAgaWYgKG1pbmUubmV3RmlsZU5hbWUgfHwgdGhlaXJzLm5ld0ZpbGVOYW1lKSB7XG4gICAgaWYgKCFmaWxlTmFtZUNoYW5nZWQobWluZSkpIHtcbiAgICAgIC8vIE5vIGhlYWRlciBvciBubyBjaGFuZ2UgaW4gb3VycywgdXNlIHRoZWlycyAoYW5kIG91cnMgaWYgdGhlaXJzIGRvZXMgbm90IGV4aXN0KVxuICAgICAgcmV0Lm9sZEZpbGVOYW1lID0gdGhlaXJzLm9sZEZpbGVOYW1lIHx8IG1pbmUub2xkRmlsZU5hbWU7XG4gICAgICByZXQubmV3RmlsZU5hbWUgPSB0aGVpcnMubmV3RmlsZU5hbWUgfHwgbWluZS5uZXdGaWxlTmFtZTtcbiAgICAgIHJldC5vbGRIZWFkZXIgPSB0aGVpcnMub2xkSGVhZGVyIHx8IG1pbmUub2xkSGVhZGVyO1xuICAgICAgcmV0Lm5ld0hlYWRlciA9IHRoZWlycy5uZXdIZWFkZXIgfHwgbWluZS5uZXdIZWFkZXI7XG4gICAgfSBlbHNlIGlmICghZmlsZU5hbWVDaGFuZ2VkKHRoZWlycykpIHtcbiAgICAgIC8vIE5vIGhlYWRlciBvciBubyBjaGFuZ2UgaW4gdGhlaXJzLCB1c2Ugb3Vyc1xuICAgICAgcmV0Lm9sZEZpbGVOYW1lID0gbWluZS5vbGRGaWxlTmFtZTtcbiAgICAgIHJldC5uZXdGaWxlTmFtZSA9IG1pbmUubmV3RmlsZU5hbWU7XG4gICAgICByZXQub2xkSGVhZGVyID0gbWluZS5vbGRIZWFkZXI7XG4gICAgICByZXQubmV3SGVhZGVyID0gbWluZS5uZXdIZWFkZXI7XG4gICAgfSBlbHNlIHtcbiAgICAgIC8vIEJvdGggY2hhbmdlZC4uLiBmaWd1cmUgaXQgb3V0XG4gICAgICByZXQub2xkRmlsZU5hbWUgPSBzZWxlY3RGaWVsZChyZXQsIG1pbmUub2xkRmlsZU5hbWUsIHRoZWlycy5vbGRGaWxlTmFtZSk7XG4gICAgICByZXQubmV3RmlsZU5hbWUgPSBzZWxlY3RGaWVsZChyZXQsIG1pbmUubmV3RmlsZU5hbWUsIHRoZWlycy5uZXdGaWxlTmFtZSk7XG4gICAgICByZXQub2xkSGVhZGVyID0gc2VsZWN0RmllbGQocmV0LCBtaW5lLm9sZEhlYWRlciwgdGhlaXJzLm9sZEhlYWRlcik7XG4gICAgICByZXQubmV3SGVhZGVyID0gc2VsZWN0RmllbGQocmV0LCBtaW5lLm5ld0hlYWRlciwgdGhlaXJzLm5ld0hlYWRlcik7XG4gICAgfVxuICB9XG5cbiAgcmV0Lmh1bmtzID0gW107XG5cbiAgbGV0IG1pbmVJbmRleCA9IDAsXG4gICAgICB0aGVpcnNJbmRleCA9IDAsXG4gICAgICBtaW5lT2Zmc2V0ID0gMCxcbiAgICAgIHRoZWlyc09mZnNldCA9IDA7XG5cbiAgd2hpbGUgKG1pbmVJbmRleCA8IG1pbmUuaHVua3MubGVuZ3RoIHx8IHRoZWlyc0luZGV4IDwgdGhlaXJzLmh1bmtzLmxlbmd0aCkge1xuICAgIGxldCBtaW5lQ3VycmVudCA9IG1pbmUuaHVua3NbbWluZUluZGV4XSB8fCB7b2xkU3RhcnQ6IEluZmluaXR5fSxcbiAgICAgICAgdGhlaXJzQ3VycmVudCA9IHRoZWlycy5odW5rc1t0aGVpcnNJbmRleF0gfHwge29sZFN0YXJ0OiBJbmZpbml0eX07XG5cbiAgICBpZiAoaHVua0JlZm9yZShtaW5lQ3VycmVudCwgdGhlaXJzQ3VycmVudCkpIHtcbiAgICAgIC8vIFRoaXMgcGF0Y2ggZG9lcyBub3Qgb3ZlcmxhcCB3aXRoIGFueSBvZiB0aGUgb3RoZXJzLCB5YXkuXG4gICAgICByZXQuaHVua3MucHVzaChjbG9uZUh1bmsobWluZUN1cnJlbnQsIG1pbmVPZmZzZXQpKTtcbiAgICAgIG1pbmVJbmRleCsrO1xuICAgICAgdGhlaXJzT2Zmc2V0ICs9IG1pbmVDdXJyZW50Lm5ld0xpbmVzIC0gbWluZUN1cnJlbnQub2xkTGluZXM7XG4gICAgfSBlbHNlIGlmIChodW5rQmVmb3JlKHRoZWlyc0N1cnJlbnQsIG1pbmVDdXJyZW50KSkge1xuICAgICAgLy8gVGhpcyBwYXRjaCBkb2VzIG5vdCBvdmVybGFwIHdpdGggYW55IG9mIHRoZSBvdGhlcnMsIHlheS5cbiAgICAgIHJldC5odW5rcy5wdXNoKGNsb25lSHVuayh0aGVpcnNDdXJyZW50LCB0aGVpcnNPZmZzZXQpKTtcbiAgICAgIHRoZWlyc0luZGV4Kys7XG4gICAgICBtaW5lT2Zmc2V0ICs9IHRoZWlyc0N1cnJlbnQubmV3TGluZXMgLSB0aGVpcnNDdXJyZW50Lm9sZExpbmVzO1xuICAgIH0gZWxzZSB7XG4gICAgICAvLyBPdmVybGFwLCBtZXJnZSBhcyBiZXN0IHdlIGNhblxuICAgICAgbGV0IG1lcmdlZEh1bmsgPSB7XG4gICAgICAgIG9sZFN0YXJ0OiBNYXRoLm1pbihtaW5lQ3VycmVudC5vbGRTdGFydCwgdGhlaXJzQ3VycmVudC5vbGRTdGFydCksXG4gICAgICAgIG9sZExpbmVzOiAwLFxuICAgICAgICBuZXdTdGFydDogTWF0aC5taW4obWluZUN1cnJlbnQubmV3U3RhcnQgKyBtaW5lT2Zmc2V0LCB0aGVpcnNDdXJyZW50Lm9sZFN0YXJ0ICsgdGhlaXJzT2Zmc2V0KSxcbiAgICAgICAgbmV3TGluZXM6IDAsXG4gICAgICAgIGxpbmVzOiBbXVxuICAgICAgfTtcbiAgICAgIG1lcmdlTGluZXMobWVyZ2VkSHVuaywgbWluZUN1cnJlbnQub2xkU3RhcnQsIG1pbmVDdXJyZW50LmxpbmVzLCB0aGVpcnNDdXJyZW50Lm9sZFN0YXJ0LCB0aGVpcnNDdXJyZW50LmxpbmVzKTtcbiAgICAgIHRoZWlyc0luZGV4Kys7XG4gICAgICBtaW5lSW5kZXgrKztcblxuICAgICAgcmV0Lmh1bmtzLnB1c2gobWVyZ2VkSHVuayk7XG4gICAgfVxuICB9XG5cbiAgcmV0dXJuIHJldDtcbn1cblxuZnVuY3Rpb24gbG9hZFBhdGNoKHBhcmFtLCBiYXNlKSB7XG4gIGlmICh0eXBlb2YgcGFyYW0gPT09ICdzdHJpbmcnKSB7XG4gICAgaWYgKC9eQEAvbS50ZXN0KHBhcmFtKSB8fCAoL15JbmRleDovbS50ZXN0KHBhcmFtKSkpIHtcbiAgICAgIHJldHVybiBwYXJzZVBhdGNoKHBhcmFtKVswXTtcbiAgICB9XG5cbiAgICBpZiAoIWJhc2UpIHtcbiAgICAgIHRocm93IG5ldyBFcnJvcignTXVzdCBwcm92aWRlIGEgYmFzZSByZWZlcmVuY2Ugb3IgcGFzcyBpbiBhIHBhdGNoJyk7XG4gICAgfVxuICAgIHJldHVybiBzdHJ1Y3R1cmVkUGF0Y2godW5kZWZpbmVkLCB1bmRlZmluZWQsIGJhc2UsIHBhcmFtKTtcbiAgfVxuXG4gIHJldHVybiBwYXJhbTtcbn1cblxuZnVuY3Rpb24gZmlsZU5hbWVDaGFuZ2VkKHBhdGNoKSB7XG4gIHJldHVybiBwYXRjaC5uZXdGaWxlTmFtZSAmJiBwYXRjaC5uZXdGaWxlTmFtZSAhPT0gcGF0Y2gub2xkRmlsZU5hbWU7XG59XG5cbmZ1bmN0aW9uIHNlbGVjdEZpZWxkKGluZGV4LCBtaW5lLCB0aGVpcnMpIHtcbiAgaWYgKG1pbmUgPT09IHRoZWlycykge1xuICAgIHJldHVybiBtaW5lO1xuICB9IGVsc2Uge1xuICAgIGluZGV4LmNvbmZsaWN0ID0gdHJ1ZTtcbiAgICByZXR1cm4ge21pbmUsIHRoZWlyc307XG4gIH1cbn1cblxuZnVuY3Rpb24gaHVua0JlZm9yZSh0ZXN0LCBjaGVjaykge1xuICByZXR1cm4gdGVzdC5vbGRTdGFydCA8IGNoZWNrLm9sZFN0YXJ0XG4gICAgJiYgKHRlc3Qub2xkU3RhcnQgKyB0ZXN0Lm9sZExpbmVzKSA8IGNoZWNrLm9sZFN0YXJ0O1xufVxuXG5mdW5jdGlvbiBjbG9uZUh1bmsoaHVuaywgb2Zmc2V0KSB7XG4gIHJldHVybiB7XG4gICAgb2xkU3RhcnQ6IGh1bmsub2xkU3RhcnQsIG9sZExpbmVzOiBodW5rLm9sZExpbmVzLFxuICAgIG5ld1N0YXJ0OiBodW5rLm5ld1N0YXJ0ICsgb2Zmc2V0LCBuZXdMaW5lczogaHVuay5uZXdMaW5lcyxcbiAgICBsaW5lczogaHVuay5saW5lc1xuICB9O1xufVxuXG5mdW5jdGlvbiBtZXJnZUxpbmVzKGh1bmssIG1pbmVPZmZzZXQsIG1pbmVMaW5lcywgdGhlaXJPZmZzZXQsIHRoZWlyTGluZXMpIHtcbiAgLy8gVGhpcyB3aWxsIGdlbmVyYWxseSByZXN1bHQgaW4gYSBjb25mbGljdGVkIGh1bmssIGJ1dCB0aGVyZSBhcmUgY2FzZXMgd2hlcmUgdGhlIGNvbnRleHRcbiAgLy8gaXMgdGhlIG9ubHkgb3ZlcmxhcCB3aGVyZSB3ZSBjYW4gc3VjY2Vzc2Z1bGx5IG1lcmdlIHRoZSBjb250ZW50IGhlcmUuXG4gIGxldCBtaW5lID0ge29mZnNldDogbWluZU9mZnNldCwgbGluZXM6IG1pbmVMaW5lcywgaW5kZXg6IDB9LFxuICAgICAgdGhlaXIgPSB7b2Zmc2V0OiB0aGVpck9mZnNldCwgbGluZXM6IHRoZWlyTGluZXMsIGluZGV4OiAwfTtcblxuICAvLyBIYW5kbGUgYW55IGxlYWRpbmcgY29udGVudFxuICBpbnNlcnRMZWFkaW5nKGh1bmssIG1pbmUsIHRoZWlyKTtcbiAgaW5zZXJ0TGVhZGluZyhodW5rLCB0aGVpciwgbWluZSk7XG5cbiAgLy8gTm93IGluIHRoZSBvdmVybGFwIGNvbnRlbnQuIFNjYW4gdGhyb3VnaCBhbmQgc2VsZWN0IHRoZSBiZXN0IGNoYW5nZXMgZnJvbSBlYWNoLlxuICB3aGlsZSAobWluZS5pbmRleCA8IG1pbmUubGluZXMubGVuZ3RoICYmIHRoZWlyLmluZGV4IDwgdGhlaXIubGluZXMubGVuZ3RoKSB7XG4gICAgbGV0IG1pbmVDdXJyZW50ID0gbWluZS5saW5lc1ttaW5lLmluZGV4XSxcbiAgICAgICAgdGhlaXJDdXJyZW50ID0gdGhlaXIubGluZXNbdGhlaXIuaW5kZXhdO1xuXG4gICAgaWYgKChtaW5lQ3VycmVudFswXSA9PT0gJy0nIHx8IG1pbmVDdXJyZW50WzBdID09PSAnKycpXG4gICAgICAgICYmICh0aGVpckN1cnJlbnRbMF0gPT09ICctJyB8fCB0aGVpckN1cnJlbnRbMF0gPT09ICcrJykpIHtcbiAgICAgIC8vIEJvdGggbW9kaWZpZWQgLi4uXG4gICAgICBtdXR1YWxDaGFuZ2UoaHVuaywgbWluZSwgdGhlaXIpO1xuICAgIH0gZWxzZSBpZiAobWluZUN1cnJlbnRbMF0gPT09ICcrJyAmJiB0aGVpckN1cnJlbnRbMF0gPT09ICcgJykge1xuICAgICAgLy8gTWluZSBpbnNlcnRlZFxuICAgICAgaHVuay5saW5lcy5wdXNoKC4uLiBjb2xsZWN0Q2hhbmdlKG1pbmUpKTtcbiAgICB9IGVsc2UgaWYgKHRoZWlyQ3VycmVudFswXSA9PT0gJysnICYmIG1pbmVDdXJyZW50WzBdID09PSAnICcpIHtcbiAgICAgIC8vIFRoZWlycyBpbnNlcnRlZFxuICAgICAgaHVuay5saW5lcy5wdXNoKC4uLiBjb2xsZWN0Q2hhbmdlKHRoZWlyKSk7XG4gICAgfSBlbHNlIGlmIChtaW5lQ3VycmVudFswXSA9PT0gJy0nICYmIHRoZWlyQ3VycmVudFswXSA9PT0gJyAnKSB7XG4gICAgICAvLyBNaW5lIHJlbW92ZWQgb3IgZWRpdGVkXG4gICAgICByZW1vdmFsKGh1bmssIG1pbmUsIHRoZWlyKTtcbiAgICB9IGVsc2UgaWYgKHRoZWlyQ3VycmVudFswXSA9PT0gJy0nICYmIG1pbmVDdXJyZW50WzBdID09PSAnICcpIHtcbiAgICAgIC8vIFRoZWlyIHJlbW92ZWQgb3IgZWRpdGVkXG4gICAgICByZW1vdmFsKGh1bmssIHRoZWlyLCBtaW5lLCB0cnVlKTtcbiAgICB9IGVsc2UgaWYgKG1pbmVDdXJyZW50ID09PSB0aGVpckN1cnJlbnQpIHtcbiAgICAgIC8vIENvbnRleHQgaWRlbnRpdHlcbiAgICAgIGh1bmsubGluZXMucHVzaChtaW5lQ3VycmVudCk7XG4gICAgICBtaW5lLmluZGV4Kys7XG4gICAgICB0aGVpci5pbmRleCsrO1xuICAgIH0gZWxzZSB7XG4gICAgICAvLyBDb250ZXh0IG1pc21hdGNoXG4gICAgICBjb25mbGljdChodW5rLCBjb2xsZWN0Q2hhbmdlKG1pbmUpLCBjb2xsZWN0Q2hhbmdlKHRoZWlyKSk7XG4gICAgfVxuICB9XG5cbiAgLy8gTm93IHB1c2ggYW55dGhpbmcgdGhhdCBtYXkgYmUgcmVtYWluaW5nXG4gIGluc2VydFRyYWlsaW5nKGh1bmssIG1pbmUpO1xuICBpbnNlcnRUcmFpbGluZyhodW5rLCB0aGVpcik7XG5cbiAgY2FsY0xpbmVDb3VudChodW5rKTtcbn1cblxuZnVuY3Rpb24gbXV0dWFsQ2hhbmdlKGh1bmssIG1pbmUsIHRoZWlyKSB7XG4gIGxldCBteUNoYW5nZXMgPSBjb2xsZWN0Q2hhbmdlKG1pbmUpLFxuICAgICAgdGhlaXJDaGFuZ2VzID0gY29sbGVjdENoYW5nZSh0aGVpcik7XG5cbiAgaWYgKGFsbFJlbW92ZXMobXlDaGFuZ2VzKSAmJiBhbGxSZW1vdmVzKHRoZWlyQ2hhbmdlcykpIHtcbiAgICAvLyBTcGVjaWFsIGNhc2UgZm9yIHJlbW92ZSBjaGFuZ2VzIHRoYXQgYXJlIHN1cGVyc2V0cyBvZiBvbmUgYW5vdGhlclxuICAgIGlmIChhcnJheVN0YXJ0c1dpdGgobXlDaGFuZ2VzLCB0aGVpckNoYW5nZXMpXG4gICAgICAgICYmIHNraXBSZW1vdmVTdXBlcnNldCh0aGVpciwgbXlDaGFuZ2VzLCBteUNoYW5nZXMubGVuZ3RoIC0gdGhlaXJDaGFuZ2VzLmxlbmd0aCkpIHtcbiAgICAgIGh1bmsubGluZXMucHVzaCguLi4gbXlDaGFuZ2VzKTtcbiAgICAgIHJldHVybjtcbiAgICB9IGVsc2UgaWYgKGFycmF5U3RhcnRzV2l0aCh0aGVpckNoYW5nZXMsIG15Q2hhbmdlcylcbiAgICAgICAgJiYgc2tpcFJlbW92ZVN1cGVyc2V0KG1pbmUsIHRoZWlyQ2hhbmdlcywgdGhlaXJDaGFuZ2VzLmxlbmd0aCAtIG15Q2hhbmdlcy5sZW5ndGgpKSB7XG4gICAgICBodW5rLmxpbmVzLnB1c2goLi4uIHRoZWlyQ2hhbmdlcyk7XG4gICAgICByZXR1cm47XG4gICAgfVxuICB9IGVsc2UgaWYgKGFycmF5RXF1YWwobXlDaGFuZ2VzLCB0aGVpckNoYW5nZXMpKSB7XG4gICAgaHVuay5saW5lcy5wdXNoKC4uLiBteUNoYW5nZXMpO1xuICAgIHJldHVybjtcbiAgfVxuXG4gIGNvbmZsaWN0KGh1bmssIG15Q2hhbmdlcywgdGhlaXJDaGFuZ2VzKTtcbn1cblxuZnVuY3Rpb24gcmVtb3ZhbChodW5rLCBtaW5lLCB0aGVpciwgc3dhcCkge1xuICBsZXQgbXlDaGFuZ2VzID0gY29sbGVjdENoYW5nZShtaW5lKSxcbiAgICAgIHRoZWlyQ2hhbmdlcyA9IGNvbGxlY3RDb250ZXh0KHRoZWlyLCBteUNoYW5nZXMpO1xuICBpZiAodGhlaXJDaGFuZ2VzLm1lcmdlZCkge1xuICAgIGh1bmsubGluZXMucHVzaCguLi4gdGhlaXJDaGFuZ2VzLm1lcmdlZCk7XG4gIH0gZWxzZSB7XG4gICAgY29uZmxpY3QoaHVuaywgc3dhcCA/IHRoZWlyQ2hhbmdlcyA6IG15Q2hhbmdlcywgc3dhcCA/IG15Q2hhbmdlcyA6IHRoZWlyQ2hhbmdlcyk7XG4gIH1cbn1cblxuZnVuY3Rpb24gY29uZmxpY3QoaHVuaywgbWluZSwgdGhlaXIpIHtcbiAgaHVuay5jb25mbGljdCA9IHRydWU7XG4gIGh1bmsubGluZXMucHVzaCh7XG4gICAgY29uZmxpY3Q6IHRydWUsXG4gICAgbWluZTogbWluZSxcbiAgICB0aGVpcnM6IHRoZWlyXG4gIH0pO1xufVxuXG5mdW5jdGlvbiBpbnNlcnRMZWFkaW5nKGh1bmssIGluc2VydCwgdGhlaXIpIHtcbiAgd2hpbGUgKGluc2VydC5vZmZzZXQgPCB0aGVpci5vZmZzZXQgJiYgaW5zZXJ0LmluZGV4IDwgaW5zZXJ0LmxpbmVzLmxlbmd0aCkge1xuICAgIGxldCBsaW5lID0gaW5zZXJ0LmxpbmVzW2luc2VydC5pbmRleCsrXTtcbiAgICBodW5rLmxpbmVzLnB1c2gobGluZSk7XG4gICAgaW5zZXJ0Lm9mZnNldCsrO1xuICB9XG59XG5mdW5jdGlvbiBpbnNlcnRUcmFpbGluZyhodW5rLCBpbnNlcnQpIHtcbiAgd2hpbGUgKGluc2VydC5pbmRleCA8IGluc2VydC5saW5lcy5sZW5ndGgpIHtcbiAgICBsZXQgbGluZSA9IGluc2VydC5saW5lc1tpbnNlcnQuaW5kZXgrK107XG4gICAgaHVuay5saW5lcy5wdXNoKGxpbmUpO1xuICB9XG59XG5cbmZ1bmN0aW9uIGNvbGxlY3RDaGFuZ2Uoc3RhdGUpIHtcbiAgbGV0IHJldCA9IFtdLFxuICAgICAgb3BlcmF0aW9uID0gc3RhdGUubGluZXNbc3RhdGUuaW5kZXhdWzBdO1xuICB3aGlsZSAoc3RhdGUuaW5kZXggPCBzdGF0ZS5saW5lcy5sZW5ndGgpIHtcbiAgICBsZXQgbGluZSA9IHN0YXRlLmxpbmVzW3N0YXRlLmluZGV4XTtcblxuICAgIC8vIEdyb3VwIGFkZGl0aW9ucyB0aGF0IGFyZSBpbW1lZGlhdGVseSBhZnRlciBzdWJ0cmFjdGlvbnMgYW5kIHRyZWF0IHRoZW0gYXMgb25lIFwiYXRvbWljXCIgbW9kaWZ5IGNoYW5nZS5cbiAgICBpZiAob3BlcmF0aW9uID09PSAnLScgJiYgbGluZVswXSA9PT0gJysnKSB7XG4gICAgICBvcGVyYXRpb24gPSAnKyc7XG4gICAgfVxuXG4gICAgaWYgKG9wZXJhdGlvbiA9PT0gbGluZVswXSkge1xuICAgICAgcmV0LnB1c2gobGluZSk7XG4gICAgICBzdGF0ZS5pbmRleCsrO1xuICAgIH0gZWxzZSB7XG4gICAgICBicmVhaztcbiAgICB9XG4gIH1cblxuICByZXR1cm4gcmV0O1xufVxuZnVuY3Rpb24gY29sbGVjdENvbnRleHQoc3RhdGUsIG1hdGNoQ2hhbmdlcykge1xuICBsZXQgY2hhbmdlcyA9IFtdLFxuICAgICAgbWVyZ2VkID0gW10sXG4gICAgICBtYXRjaEluZGV4ID0gMCxcbiAgICAgIGNvbnRleHRDaGFuZ2VzID0gZmFsc2UsXG4gICAgICBjb25mbGljdGVkID0gZmFsc2U7XG4gIHdoaWxlIChtYXRjaEluZGV4IDwgbWF0Y2hDaGFuZ2VzLmxlbmd0aFxuICAgICAgICAmJiBzdGF0ZS5pbmRleCA8IHN0YXRlLmxpbmVzLmxlbmd0aCkge1xuICAgIGxldCBjaGFuZ2UgPSBzdGF0ZS5saW5lc1tzdGF0ZS5pbmRleF0sXG4gICAgICAgIG1hdGNoID0gbWF0Y2hDaGFuZ2VzW21hdGNoSW5kZXhdO1xuXG4gICAgLy8gT25jZSB3ZSd2ZSBoaXQgb3VyIGFkZCwgdGhlbiB3ZSBhcmUgZG9uZVxuICAgIGlmIChtYXRjaFswXSA9PT0gJysnKSB7XG4gICAgICBicmVhaztcbiAgICB9XG5cbiAgICBjb250ZXh0Q2hhbmdlcyA9IGNvbnRleHRDaGFuZ2VzIHx8IGNoYW5nZVswXSAhPT0gJyAnO1xuXG4gICAgbWVyZ2VkLnB1c2gobWF0Y2gpO1xuICAgIG1hdGNoSW5kZXgrKztcblxuICAgIC8vIENvbnN1bWUgYW55IGFkZGl0aW9ucyBpbiB0aGUgb3RoZXIgYmxvY2sgYXMgYSBjb25mbGljdCB0byBhdHRlbXB0XG4gICAgLy8gdG8gcHVsbCBpbiB0aGUgcmVtYWluaW5nIGNvbnRleHQgYWZ0ZXIgdGhpc1xuICAgIGlmIChjaGFuZ2VbMF0gPT09ICcrJykge1xuICAgICAgY29uZmxpY3RlZCA9IHRydWU7XG5cbiAgICAgIHdoaWxlIChjaGFuZ2VbMF0gPT09ICcrJykge1xuICAgICAgICBjaGFuZ2VzLnB1c2goY2hhbmdlKTtcbiAgICAgICAgY2hhbmdlID0gc3RhdGUubGluZXNbKytzdGF0ZS5pbmRleF07XG4gICAgICB9XG4gICAgfVxuXG4gICAgaWYgKG1hdGNoLnN1YnN0cigxKSA9PT0gY2hhbmdlLnN1YnN0cigxKSkge1xuICAgICAgY2hhbmdlcy5wdXNoKGNoYW5nZSk7XG4gICAgICBzdGF0ZS5pbmRleCsrO1xuICAgIH0gZWxzZSB7XG4gICAgICBjb25mbGljdGVkID0gdHJ1ZTtcbiAgICB9XG4gIH1cblxuICBpZiAoKG1hdGNoQ2hhbmdlc1ttYXRjaEluZGV4XSB8fCAnJylbMF0gPT09ICcrJ1xuICAgICAgJiYgY29udGV4dENoYW5nZXMpIHtcbiAgICBjb25mbGljdGVkID0gdHJ1ZTtcbiAgfVxuXG4gIGlmIChjb25mbGljdGVkKSB7XG4gICAgcmV0dXJuIGNoYW5nZXM7XG4gIH1cblxuICB3aGlsZSAobWF0Y2hJbmRleCA8IG1hdGNoQ2hhbmdlcy5sZW5ndGgpIHtcbiAgICBtZXJnZWQucHVzaChtYXRjaENoYW5nZXNbbWF0Y2hJbmRleCsrXSk7XG4gIH1cblxuICByZXR1cm4ge1xuICAgIG1lcmdlZCxcbiAgICBjaGFuZ2VzXG4gIH07XG59XG5cbmZ1bmN0aW9uIGFsbFJlbW92ZXMoY2hhbmdlcykge1xuICByZXR1cm4gY2hhbmdlcy5yZWR1Y2UoZnVuY3Rpb24ocHJldiwgY2hhbmdlKSB7XG4gICAgcmV0dXJuIHByZXYgJiYgY2hhbmdlWzBdID09PSAnLSc7XG4gIH0sIHRydWUpO1xufVxuZnVuY3Rpb24gc2tpcFJlbW92ZVN1cGVyc2V0KHN0YXRlLCByZW1vdmVDaGFuZ2VzLCBkZWx0YSkge1xuICBmb3IgKGxldCBpID0gMDsgaSA8IGRlbHRhOyBpKyspIHtcbiAgICBsZXQgY2hhbmdlQ29udGVudCA9IHJlbW92ZUNoYW5nZXNbcmVtb3ZlQ2hhbmdlcy5sZW5ndGggLSBkZWx0YSArIGldLnN1YnN0cigxKTtcbiAgICBpZiAoc3RhdGUubGluZXNbc3RhdGUuaW5kZXggKyBpXSAhPT0gJyAnICsgY2hhbmdlQ29udGVudCkge1xuICAgICAgcmV0dXJuIGZhbHNlO1xuICAgIH1cbiAgfVxuXG4gIHN0YXRlLmluZGV4ICs9IGRlbHRhO1xuICByZXR1cm4gdHJ1ZTtcbn1cblxuZnVuY3Rpb24gY2FsY09sZE5ld0xpbmVDb3VudChsaW5lcykge1xuICBsZXQgb2xkTGluZXMgPSAwO1xuICBsZXQgbmV3TGluZXMgPSAwO1xuXG4gIGxpbmVzLmZvckVhY2goZnVuY3Rpb24obGluZSkge1xuICAgIGlmICh0eXBlb2YgbGluZSAhPT0gJ3N0cmluZycpIHtcbiAgICAgIGxldCBteUNvdW50ID0gY2FsY09sZE5ld0xpbmVDb3VudChsaW5lLm1pbmUpO1xuICAgICAgbGV0IHRoZWlyQ291bnQgPSBjYWxjT2xkTmV3TGluZUNvdW50KGxpbmUudGhlaXJzKTtcblxuICAgICAgaWYgKG9sZExpbmVzICE9PSB1bmRlZmluZWQpIHtcbiAgICAgICAgaWYgKG15Q291bnQub2xkTGluZXMgPT09IHRoZWlyQ291bnQub2xkTGluZXMpIHtcbiAgICAgICAgICBvbGRMaW5lcyArPSBteUNvdW50Lm9sZExpbmVzO1xuICAgICAgICB9IGVsc2Uge1xuICAgICAgICAgIG9sZExpbmVzID0gdW5kZWZpbmVkO1xuICAgICAgICB9XG4gICAgICB9XG5cbiAgICAgIGlmIChuZXdMaW5lcyAhPT0gdW5kZWZpbmVkKSB7XG4gICAgICAgIGlmIChteUNvdW50Lm5ld0xpbmVzID09PSB0aGVpckNvdW50Lm5ld0xpbmVzKSB7XG4gICAgICAgICAgbmV3TGluZXMgKz0gbXlDb3VudC5uZXdMaW5lcztcbiAgICAgICAgfSBlbHNlIHtcbiAgICAgICAgICBuZXdMaW5lcyA9IHVuZGVmaW5lZDtcbiAgICAgICAgfVxuICAgICAgfVxuICAgIH0gZWxzZSB7XG4gICAgICBpZiAobmV3TGluZXMgIT09IHVuZGVmaW5lZCAmJiAobGluZVswXSA9PT0gJysnIHx8IGxpbmVbMF0gPT09ICcgJykpIHtcbiAgICAgICAgbmV3TGluZXMrKztcbiAgICAgIH1cbiAgICAgIGlmIChvbGRMaW5lcyAhPT0gdW5kZWZpbmVkICYmIChsaW5lWzBdID09PSAnLScgfHwgbGluZVswXSA9PT0gJyAnKSkge1xuICAgICAgICBvbGRMaW5lcysrO1xuICAgICAgfVxuICAgIH1cbiAgfSk7XG5cbiAgcmV0dXJuIHtvbGRMaW5lcywgbmV3TGluZXN9O1xufVxuIl19
diff --git a/node_modules/diff/lib/patch/parse.js b/node_modules/diff/lib/patch/parse.js
new file mode 100644
index 0000000..e5f1730
--- /dev/null
+++ b/node_modules/diff/lib/patch/parse.js
@@ -0,0 +1,147 @@
+/*istanbul ignore start*/'use strict';
+
+exports.__esModule = true;
+exports. /*istanbul ignore end*/parsePatch = parsePatch;
+function parsePatch(uniDiff) {
+  /*istanbul ignore start*/var /*istanbul ignore end*/options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
+
+  var diffstr = uniDiff.split(/\r\n|[\n\v\f\r\x85]/),
+      delimiters = uniDiff.match(/\r\n|[\n\v\f\r\x85]/g) || [],
+      list = [],
+      i = 0;
+
+  function parseIndex() {
+    var index = {};
+    list.push(index);
+
+    // Parse diff metadata
+    while (i < diffstr.length) {
+      var line = diffstr[i];
+
+      // File header found, end parsing diff metadata
+      if (/^(\-\-\-|\+\+\+|@@)\s/.test(line)) {
+        break;
+      }
+
+      // Diff index
+      var header = /^(?:Index:|diff(?: -r \w+)+)\s+(.+?)\s*$/.exec(line);
+      if (header) {
+        index.index = header[1];
+      }
+
+      i++;
+    }
+
+    // Parse file headers if they are defined. Unified diff requires them, but
+    // there's no technical issues to have an isolated hunk without file header
+    parseFileHeader(index);
+    parseFileHeader(index);
+
+    // Parse hunks
+    index.hunks = [];
+
+    while (i < diffstr.length) {
+      var _line = diffstr[i];
+
+      if (/^(Index:|diff|\-\-\-|\+\+\+)\s/.test(_line)) {
+        break;
+      } else if (/^@@/.test(_line)) {
+        index.hunks.push(parseHunk());
+      } else if (_line && options.strict) {
+        // Ignore unexpected content unless in strict mode
+        throw new Error('Unknown line ' + (i + 1) + ' ' + JSON.stringify(_line));
+      } else {
+        i++;
+      }
+    }
+  }
+
+  // Parses the --- and +++ headers, if none are found, no lines
+  // are consumed.
+  function parseFileHeader(index) {
+    var fileHeader = /^(---|\+\+\+)\s+(.*)$/.exec(diffstr[i]);
+    if (fileHeader) {
+      var keyPrefix = fileHeader[1] === '---' ? 'old' : 'new';
+      var data = fileHeader[2].split('\t', 2);
+      var fileName = data[0].replace(/\\\\/g, '\\');
+      if (/^".*"$/.test(fileName)) {
+        fileName = fileName.substr(1, fileName.length - 2);
+      }
+      index[keyPrefix + 'FileName'] = fileName;
+      index[keyPrefix + 'Header'] = (data[1] || '').trim();
+
+      i++;
+    }
+  }
+
+  // Parses a hunk
+  // This assumes that we are at the start of a hunk.
+  function parseHunk() {
+    var chunkHeaderIndex = i,
+        chunkHeaderLine = diffstr[i++],
+        chunkHeader = chunkHeaderLine.split(/@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/);
+
+    var hunk = {
+      oldStart: +chunkHeader[1],
+      oldLines: +chunkHeader[2] || 1,
+      newStart: +chunkHeader[3],
+      newLines: +chunkHeader[4] || 1,
+      lines: [],
+      linedelimiters: []
+    };
+
+    var addCount = 0,
+        removeCount = 0;
+    for (; i < diffstr.length; i++) {
+      // Lines starting with '---' could be mistaken for the "remove line" operation
+      // But they could be the header for the next file. Therefore prune such cases out.
+      if (diffstr[i].indexOf('--- ') === 0 && i + 2 < diffstr.length && diffstr[i + 1].indexOf('+++ ') === 0 && diffstr[i + 2].indexOf('@@') === 0) {
+        break;
+      }
+      var operation = diffstr[i].length == 0 && i != diffstr.length - 1 ? ' ' : diffstr[i][0];
+
+      if (operation === '+' || operation === '-' || operation === ' ' || operation === '\\') {
+        hunk.lines.push(diffstr[i]);
+        hunk.linedelimiters.push(delimiters[i] || '\n');
+
+        if (operation === '+') {
+          addCount++;
+        } else if (operation === '-') {
+          removeCount++;
+        } else if (operation === ' ') {
+          addCount++;
+          removeCount++;
+        }
+      } else {
+        break;
+      }
+    }
+
+    // Handle the empty block count case
+    if (!addCount && hunk.newLines === 1) {
+      hunk.newLines = 0;
+    }
+    if (!removeCount && hunk.oldLines === 1) {
+      hunk.oldLines = 0;
+    }
+
+    // Perform optional sanity checking
+    if (options.strict) {
+      if (addCount !== hunk.newLines) {
+        throw new Error('Added line count did not match for hunk at line ' + (chunkHeaderIndex + 1));
+      }
+      if (removeCount !== hunk.oldLines) {
+        throw new Error('Removed line count did not match for hunk at line ' + (chunkHeaderIndex + 1));
+      }
+    }
+
+    return hunk;
+  }
+
+  while (i < diffstr.length) {
+    parseIndex();
+  }
+
+  return list;
+}
+//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9wYXRjaC9wYXJzZS5qcyJdLCJuYW1lcyI6WyJwYXJzZVBhdGNoIiwidW5pRGlmZiIsIm9wdGlvbnMiLCJkaWZmc3RyIiwic3BsaXQiLCJkZWxpbWl0ZXJzIiwibWF0Y2giLCJsaXN0IiwiaSIsInBhcnNlSW5kZXgiLCJpbmRleCIsInB1c2giLCJsZW5ndGgiLCJsaW5lIiwidGVzdCIsImhlYWRlciIsImV4ZWMiLCJwYXJzZUZpbGVIZWFkZXIiLCJodW5rcyIsInBhcnNlSHVuayIsInN0cmljdCIsIkVycm9yIiwiSlNPTiIsInN0cmluZ2lmeSIsImZpbGVIZWFkZXIiLCJrZXlQcmVmaXgiLCJkYXRhIiwiZmlsZU5hbWUiLCJyZXBsYWNlIiwic3Vic3RyIiwidHJpbSIsImNodW5rSGVhZGVySW5kZXgiLCJjaHVua0hlYWRlckxpbmUiLCJjaHVua0hlYWRlciIsImh1bmsiLCJvbGRTdGFydCIsIm9sZExpbmVzIiwibmV3U3RhcnQiLCJuZXdMaW5lcyIsImxpbmVzIiwibGluZWRlbGltaXRlcnMiLCJhZGRDb3VudCIsInJlbW92ZUNvdW50IiwiaW5kZXhPZiIsIm9wZXJhdGlvbiJdLCJtYXBwaW5ncyI6Ijs7O2dDQUFnQkEsVSxHQUFBQSxVO0FBQVQsU0FBU0EsVUFBVCxDQUFvQkMsT0FBcEIsRUFBMkM7QUFBQSxzREFBZEMsT0FBYyx1RUFBSixFQUFJOztBQUNoRCxNQUFJQyxVQUFVRixRQUFRRyxLQUFSLENBQWMscUJBQWQsQ0FBZDtBQUFBLE1BQ0lDLGFBQWFKLFFBQVFLLEtBQVIsQ0FBYyxzQkFBZCxLQUF5QyxFQUQxRDtBQUFBLE1BRUlDLE9BQU8sRUFGWDtBQUFBLE1BR0lDLElBQUksQ0FIUjs7QUFLQSxXQUFTQyxVQUFULEdBQXNCO0FBQ3BCLFFBQUlDLFFBQVEsRUFBWjtBQUNBSCxTQUFLSSxJQUFMLENBQVVELEtBQVY7O0FBRUE7QUFDQSxXQUFPRixJQUFJTCxRQUFRUyxNQUFuQixFQUEyQjtBQUN6QixVQUFJQyxPQUFPVixRQUFRSyxDQUFSLENBQVg7O0FBRUE7QUFDQSxVQUFJLHdCQUF3Qk0sSUFBeEIsQ0FBNkJELElBQTdCLENBQUosRUFBd0M7QUFDdEM7QUFDRDs7QUFFRDtBQUNBLFVBQUlFLFNBQVUsMENBQUQsQ0FBNkNDLElBQTdDLENBQWtESCxJQUFsRCxDQUFiO0FBQ0EsVUFBSUUsTUFBSixFQUFZO0FBQ1ZMLGNBQU1BLEtBQU4sR0FBY0ssT0FBTyxDQUFQLENBQWQ7QUFDRDs7QUFFRFA7QUFDRDs7QUFFRDtBQUNBO0FBQ0FTLG9CQUFnQlAsS0FBaEI7QUFDQU8sb0JBQWdCUCxLQUFoQjs7QUFFQTtBQUNBQSxVQUFNUSxLQUFOLEdBQWMsRUFBZDs7QUFFQSxXQUFPVixJQUFJTCxRQUFRUyxNQUFuQixFQUEyQjtBQUN6QixVQUFJQyxRQUFPVixRQUFRSyxDQUFSLENBQVg7O0FBRUEsVUFBSSxpQ0FBaUNNLElBQWpDLENBQXNDRCxLQUF0QyxDQUFKLEVBQWlEO0FBQy9DO0FBQ0QsT0FGRCxNQUVPLElBQUksTUFBTUMsSUFBTixDQUFXRCxLQUFYLENBQUosRUFBc0I7QUFDM0JILGNBQU1RLEtBQU4sQ0FBWVAsSUFBWixDQUFpQlEsV0FBakI7QUFDRCxPQUZNLE1BRUEsSUFBSU4sU0FBUVgsUUFBUWtCLE1BQXBCLEVBQTRCO0FBQ2pDO0FBQ0EsY0FBTSxJQUFJQyxLQUFKLENBQVUsbUJBQW1CYixJQUFJLENBQXZCLElBQTRCLEdBQTVCLEdBQWtDYyxLQUFLQyxTQUFMLENBQWVWLEtBQWYsQ0FBNUMsQ0FBTjtBQUNELE9BSE0sTUFHQTtBQUNMTDtBQUNEO0FBQ0Y7QUFDRjs7QUFFRDtBQUNBO0FBQ0EsV0FBU1MsZUFBVCxDQUF5QlAsS0FBekIsRUFBZ0M7QUFDOUIsUUFBTWMsYUFBYyx1QkFBRCxDQUEwQlIsSUFBMUIsQ0FBK0JiLFFBQVFLLENBQVIsQ0FBL0IsQ0FBbkI7QUFDQSxRQUFJZ0IsVUFBSixFQUFnQjtBQUNkLFVBQUlDLFlBQVlELFdBQVcsQ0FBWCxNQUFrQixLQUFsQixHQUEwQixLQUExQixHQUFrQyxLQUFsRDtBQUNBLFVBQU1FLE9BQU9GLFdBQVcsQ0FBWCxFQUFjcEIsS0FBZCxDQUFvQixJQUFwQixFQUEwQixDQUExQixDQUFiO0FBQ0EsVUFBSXVCLFdBQVdELEtBQUssQ0FBTCxFQUFRRSxPQUFSLENBQWdCLE9BQWhCLEVBQXlCLElBQXpCLENBQWY7QUFDQSxVQUFJLFNBQVNkLElBQVQsQ0FBY2EsUUFBZCxDQUFKLEVBQTZCO0FBQzNCQSxtQkFBV0EsU0FBU0UsTUFBVCxDQUFnQixDQUFoQixFQUFtQkYsU0FBU2YsTUFBVCxHQUFrQixDQUFyQyxDQUFYO0FBQ0Q7QUFDREYsWUFBTWUsWUFBWSxVQUFsQixJQUFnQ0UsUUFBaEM7QUFDQWpCLFlBQU1lLFlBQVksUUFBbEIsSUFBOEIsQ0FBQ0MsS0FBSyxDQUFMLEtBQVcsRUFBWixFQUFnQkksSUFBaEIsRUFBOUI7O0FBRUF0QjtBQUNEO0FBQ0Y7O0FBRUQ7QUFDQTtBQUNBLFdBQVNXLFNBQVQsR0FBcUI7QUFDbkIsUUFBSVksbUJBQW1CdkIsQ0FBdkI7QUFBQSxRQUNJd0Isa0JBQWtCN0IsUUFBUUssR0FBUixDQUR0QjtBQUFBLFFBRUl5QixjQUFjRCxnQkFBZ0I1QixLQUFoQixDQUFzQiw0Q0FBdEIsQ0FGbEI7O0FBSUEsUUFBSThCLE9BQU87QUFDVEMsZ0JBQVUsQ0FBQ0YsWUFBWSxDQUFaLENBREY7QUFFVEcsZ0JBQVUsQ0FBQ0gsWUFBWSxDQUFaLENBQUQsSUFBbUIsQ0FGcEI7QUFHVEksZ0JBQVUsQ0FBQ0osWUFBWSxDQUFaLENBSEY7QUFJVEssZ0JBQVUsQ0FBQ0wsWUFBWSxDQUFaLENBQUQsSUFBbUIsQ0FKcEI7QUFLVE0sYUFBTyxFQUxFO0FBTVRDLHNCQUFnQjtBQU5QLEtBQVg7O0FBU0EsUUFBSUMsV0FBVyxDQUFmO0FBQUEsUUFDSUMsY0FBYyxDQURsQjtBQUVBLFdBQU9sQyxJQUFJTCxRQUFRUyxNQUFuQixFQUEyQkosR0FBM0IsRUFBZ0M7QUFDOUI7QUFDQTtBQUNBLFVBQUlMLFFBQVFLLENBQVIsRUFBV21DLE9BQVgsQ0FBbUIsTUFBbkIsTUFBK0IsQ0FBL0IsSUFDTW5DLElBQUksQ0FBSixHQUFRTCxRQUFRUyxNQUR0QixJQUVLVCxRQUFRSyxJQUFJLENBQVosRUFBZW1DLE9BQWYsQ0FBdUIsTUFBdkIsTUFBbUMsQ0FGeEMsSUFHS3hDLFFBQVFLLElBQUksQ0FBWixFQUFlbUMsT0FBZixDQUF1QixJQUF2QixNQUFpQyxDQUgxQyxFQUc2QztBQUN6QztBQUNIO0FBQ0QsVUFBSUMsWUFBYXpDLFFBQVFLLENBQVIsRUFBV0ksTUFBWCxJQUFxQixDQUFyQixJQUEwQkosS0FBTUwsUUFBUVMsTUFBUixHQUFpQixDQUFsRCxHQUF3RCxHQUF4RCxHQUE4RFQsUUFBUUssQ0FBUixFQUFXLENBQVgsQ0FBOUU7O0FBRUEsVUFBSW9DLGNBQWMsR0FBZCxJQUFxQkEsY0FBYyxHQUFuQyxJQUEwQ0EsY0FBYyxHQUF4RCxJQUErREEsY0FBYyxJQUFqRixFQUF1RjtBQUNyRlYsYUFBS0ssS0FBTCxDQUFXNUIsSUFBWCxDQUFnQlIsUUFBUUssQ0FBUixDQUFoQjtBQUNBMEIsYUFBS00sY0FBTCxDQUFvQjdCLElBQXBCLENBQXlCTixXQUFXRyxDQUFYLEtBQWlCLElBQTFDOztBQUVBLFlBQUlvQyxjQUFjLEdBQWxCLEVBQXVCO0FBQ3JCSDtBQUNELFNBRkQsTUFFTyxJQUFJRyxjQUFjLEdBQWxCLEVBQXVCO0FBQzVCRjtBQUNELFNBRk0sTUFFQSxJQUFJRSxjQUFjLEdBQWxCLEVBQXVCO0FBQzVCSDtBQUNBQztBQUNEO0FBQ0YsT0FaRCxNQVlPO0FBQ0w7QUFDRDtBQUNGOztBQUVEO0FBQ0EsUUFBSSxDQUFDRCxRQUFELElBQWFQLEtBQUtJLFFBQUwsS0FBa0IsQ0FBbkMsRUFBc0M7QUFDcENKLFdBQUtJLFFBQUwsR0FBZ0IsQ0FBaEI7QUFDRDtBQUNELFFBQUksQ0FBQ0ksV0FBRCxJQUFnQlIsS0FBS0UsUUFBTCxLQUFrQixDQUF0QyxFQUF5QztBQUN2Q0YsV0FBS0UsUUFBTCxHQUFnQixDQUFoQjtBQUNEOztBQUVEO0FBQ0EsUUFBSWxDLFFBQVFrQixNQUFaLEVBQW9CO0FBQ2xCLFVBQUlxQixhQUFhUCxLQUFLSSxRQUF0QixFQUFnQztBQUM5QixjQUFNLElBQUlqQixLQUFKLENBQVUsc0RBQXNEVSxtQkFBbUIsQ0FBekUsQ0FBVixDQUFOO0FBQ0Q7QUFDRCxVQUFJVyxnQkFBZ0JSLEtBQUtFLFFBQXpCLEVBQW1DO0FBQ2pDLGNBQU0sSUFBSWYsS0FBSixDQUFVLHdEQUF3RFUsbUJBQW1CLENBQTNFLENBQVYsQ0FBTjtBQUNEO0FBQ0Y7O0FBRUQsV0FBT0csSUFBUDtBQUNEOztBQUVELFNBQU8xQixJQUFJTCxRQUFRUyxNQUFuQixFQUEyQjtBQUN6Qkg7QUFDRDs7QUFFRCxTQUFPRixJQUFQO0FBQ0QiLCJmaWxlIjoicGFyc2UuanMiLCJzb3VyY2VzQ29udGVudCI6WyJleHBvcnQgZnVuY3Rpb24gcGFyc2VQYXRjaCh1bmlEaWZmLCBvcHRpb25zID0ge30pIHtcbiAgbGV0IGRpZmZzdHIgPSB1bmlEaWZmLnNwbGl0KC9cXHJcXG58W1xcblxcdlxcZlxcclxceDg1XS8pLFxuICAgICAgZGVsaW1pdGVycyA9IHVuaURpZmYubWF0Y2goL1xcclxcbnxbXFxuXFx2XFxmXFxyXFx4ODVdL2cpIHx8IFtdLFxuICAgICAgbGlzdCA9IFtdLFxuICAgICAgaSA9IDA7XG5cbiAgZnVuY3Rpb24gcGFyc2VJbmRleCgpIHtcbiAgICBsZXQgaW5kZXggPSB7fTtcbiAgICBsaXN0LnB1c2goaW5kZXgpO1xuXG4gICAgLy8gUGFyc2UgZGlmZiBtZXRhZGF0YVxuICAgIHdoaWxlIChpIDwgZGlmZnN0ci5sZW5ndGgpIHtcbiAgICAgIGxldCBsaW5lID0gZGlmZnN0cltpXTtcblxuICAgICAgLy8gRmlsZSBoZWFkZXIgZm91bmQsIGVuZCBwYXJzaW5nIGRpZmYgbWV0YWRhdGFcbiAgICAgIGlmICgvXihcXC1cXC1cXC18XFwrXFwrXFwrfEBAKVxccy8udGVzdChsaW5lKSkge1xuICAgICAgICBicmVhaztcbiAgICAgIH1cblxuICAgICAgLy8gRGlmZiBpbmRleFxuICAgICAgbGV0IGhlYWRlciA9ICgvXig/OkluZGV4OnxkaWZmKD86IC1yIFxcdyspKylcXHMrKC4rPylcXHMqJC8pLmV4ZWMobGluZSk7XG4gICAgICBpZiAoaGVhZGVyKSB7XG4gICAgICAgIGluZGV4LmluZGV4ID0gaGVhZGVyWzFdO1xuICAgICAgfVxuXG4gICAgICBpKys7XG4gICAgfVxuXG4gICAgLy8gUGFyc2UgZmlsZSBoZWFkZXJzIGlmIHRoZXkgYXJlIGRlZmluZWQuIFVuaWZpZWQgZGlmZiByZXF1aXJlcyB0aGVtLCBidXRcbiAgICAvLyB0aGVyZSdzIG5vIHRlY2huaWNhbCBpc3N1ZXMgdG8gaGF2ZSBhbiBpc29sYXRlZCBodW5rIHdpdGhvdXQgZmlsZSBoZWFkZXJcbiAgICBwYXJzZUZpbGVIZWFkZXIoaW5kZXgpO1xuICAgIHBhcnNlRmlsZUhlYWRlcihpbmRleCk7XG5cbiAgICAvLyBQYXJzZSBodW5rc1xuICAgIGluZGV4Lmh1bmtzID0gW107XG5cbiAgICB3aGlsZSAoaSA8IGRpZmZzdHIubGVuZ3RoKSB7XG4gICAgICBsZXQgbGluZSA9IGRpZmZzdHJbaV07XG5cbiAgICAgIGlmICgvXihJbmRleDp8ZGlmZnxcXC1cXC1cXC18XFwrXFwrXFwrKVxccy8udGVzdChsaW5lKSkge1xuICAgICAgICBicmVhaztcbiAgICAgIH0gZWxzZSBpZiAoL15AQC8udGVzdChsaW5lKSkge1xuICAgICAgICBpbmRleC5odW5rcy5wdXNoKHBhcnNlSHVuaygpKTtcbiAgICAgIH0gZWxzZSBpZiAobGluZSAmJiBvcHRpb25zLnN0cmljdCkge1xuICAgICAgICAvLyBJZ25vcmUgdW5leHBlY3RlZCBjb250ZW50IHVubGVzcyBpbiBzdHJpY3QgbW9kZVxuICAgICAgICB0aHJvdyBuZXcgRXJyb3IoJ1Vua25vd24gbGluZSAnICsgKGkgKyAxKSArICcgJyArIEpTT04uc3RyaW5naWZ5KGxpbmUpKTtcbiAgICAgIH0gZWxzZSB7XG4gICAgICAgIGkrKztcbiAgICAgIH1cbiAgICB9XG4gIH1cblxuICAvLyBQYXJzZXMgdGhlIC0tLSBhbmQgKysrIGhlYWRlcnMsIGlmIG5vbmUgYXJlIGZvdW5kLCBubyBsaW5lc1xuICAvLyBhcmUgY29uc3VtZWQuXG4gIGZ1bmN0aW9uIHBhcnNlRmlsZUhlYWRlcihpbmRleCkge1xuICAgIGNvbnN0IGZpbGVIZWFkZXIgPSAoL14oLS0tfFxcK1xcK1xcKylcXHMrKC4qKSQvKS5leGVjKGRpZmZzdHJbaV0pO1xuICAgIGlmIChmaWxlSGVhZGVyKSB7XG4gICAgICBsZXQga2V5UHJlZml4ID0gZmlsZUhlYWRlclsxXSA9PT0gJy0tLScgPyAnb2xkJyA6ICduZXcnO1xuICAgICAgY29uc3QgZGF0YSA9IGZpbGVIZWFkZXJbMl0uc3BsaXQoJ1xcdCcsIDIpO1xuICAgICAgbGV0IGZpbGVOYW1lID0gZGF0YVswXS5yZXBsYWNlKC9cXFxcXFxcXC9nLCAnXFxcXCcpO1xuICAgICAgaWYgKC9eXCIuKlwiJC8udGVzdChmaWxlTmFtZSkpIHtcbiAgICAgICAgZmlsZU5hbWUgPSBmaWxlTmFtZS5zdWJzdHIoMSwgZmlsZU5hbWUubGVuZ3RoIC0gMik7XG4gICAgICB9XG4gICAgICBpbmRleFtrZXlQcmVmaXggKyAnRmlsZU5hbWUnXSA9IGZpbGVOYW1lO1xuICAgICAgaW5kZXhba2V5UHJlZml4ICsgJ0hlYWRlciddID0gKGRhdGFbMV0gfHwgJycpLnRyaW0oKTtcblxuICAgICAgaSsrO1xuICAgIH1cbiAgfVxuXG4gIC8vIFBhcnNlcyBhIGh1bmtcbiAgLy8gVGhpcyBhc3N1bWVzIHRoYXQgd2UgYXJlIGF0IHRoZSBzdGFydCBvZiBhIGh1bmsuXG4gIGZ1bmN0aW9uIHBhcnNlSHVuaygpIHtcbiAgICBsZXQgY2h1bmtIZWFkZXJJbmRleCA9IGksXG4gICAgICAgIGNodW5rSGVhZGVyTGluZSA9IGRpZmZzdHJbaSsrXSxcbiAgICAgICAgY2h1bmtIZWFkZXIgPSBjaHVua0hlYWRlckxpbmUuc3BsaXQoL0BAIC0oXFxkKykoPzosKFxcZCspKT8gXFwrKFxcZCspKD86LChcXGQrKSk/IEBALyk7XG5cbiAgICBsZXQgaHVuayA9IHtcbiAgICAgIG9sZFN0YXJ0OiArY2h1bmtIZWFkZXJbMV0sXG4gICAgICBvbGRMaW5lczogK2NodW5rSGVhZGVyWzJdIHx8IDEsXG4gICAgICBuZXdTdGFydDogK2NodW5rSGVhZGVyWzNdLFxuICAgICAgbmV3TGluZXM6ICtjaHVua0hlYWRlcls0XSB8fCAxLFxuICAgICAgbGluZXM6IFtdLFxuICAgICAgbGluZWRlbGltaXRlcnM6IFtdXG4gICAgfTtcblxuICAgIGxldCBhZGRDb3VudCA9IDAsXG4gICAgICAgIHJlbW92ZUNvdW50ID0gMDtcbiAgICBmb3IgKDsgaSA8IGRpZmZzdHIubGVuZ3RoOyBpKyspIHtcbiAgICAgIC8vIExpbmVzIHN0YXJ0aW5nIHdpdGggJy0tLScgY291bGQgYmUgbWlzdGFrZW4gZm9yIHRoZSBcInJlbW92ZSBsaW5lXCIgb3BlcmF0aW9uXG4gICAgICAvLyBCdXQgdGhleSBjb3VsZCBiZSB0aGUgaGVhZGVyIGZvciB0aGUgbmV4dCBmaWxlLiBUaGVyZWZvcmUgcHJ1bmUgc3VjaCBjYXNlcyBvdXQuXG4gICAgICBpZiAoZGlmZnN0cltpXS5pbmRleE9mKCctLS0gJykgPT09IDBcbiAgICAgICAgICAgICYmIChpICsgMiA8IGRpZmZzdHIubGVuZ3RoKVxuICAgICAgICAgICAgJiYgZGlmZnN0cltpICsgMV0uaW5kZXhPZignKysrICcpID09PSAwXG4gICAgICAgICAgICAmJiBkaWZmc3RyW2kgKyAyXS5pbmRleE9mKCdAQCcpID09PSAwKSB7XG4gICAgICAgICAgYnJlYWs7XG4gICAgICB9XG4gICAgICBsZXQgb3BlcmF0aW9uID0gKGRpZmZzdHJbaV0ubGVuZ3RoID09IDAgJiYgaSAhPSAoZGlmZnN0ci5sZW5ndGggLSAxKSkgPyAnICcgOiBkaWZmc3RyW2ldWzBdO1xuXG4gICAgICBpZiAob3BlcmF0aW9uID09PSAnKycgfHwgb3BlcmF0aW9uID09PSAnLScgfHwgb3BlcmF0aW9uID09PSAnICcgfHwgb3BlcmF0aW9uID09PSAnXFxcXCcpIHtcbiAgICAgICAgaHVuay5saW5lcy5wdXNoKGRpZmZzdHJbaV0pO1xuICAgICAgICBodW5rLmxpbmVkZWxpbWl0ZXJzLnB1c2goZGVsaW1pdGVyc1tpXSB8fCAnXFxuJyk7XG5cbiAgICAgICAgaWYgKG9wZXJhdGlvbiA9PT0gJysnKSB7XG4gICAgICAgICAgYWRkQ291bnQrKztcbiAgICAgICAgfSBlbHNlIGlmIChvcGVyYXRpb24gPT09ICctJykge1xuICAgICAgICAgIHJlbW92ZUNvdW50Kys7XG4gICAgICAgIH0gZWxzZSBpZiAob3BlcmF0aW9uID09PSAnICcpIHtcbiAgICAgICAgICBhZGRDb3VudCsrO1xuICAgICAgICAgIHJlbW92ZUNvdW50Kys7XG4gICAgICAgIH1cbiAgICAgIH0gZWxzZSB7XG4gICAgICAgIGJyZWFrO1xuICAgICAgfVxuICAgIH1cblxuICAgIC8vIEhhbmRsZSB0aGUgZW1wdHkgYmxvY2sgY291bnQgY2FzZVxuICAgIGlmICghYWRkQ291bnQgJiYgaHVuay5uZXdMaW5lcyA9PT0gMSkge1xuICAgICAgaHVuay5uZXdMaW5lcyA9IDA7XG4gICAgfVxuICAgIGlmICghcmVtb3ZlQ291bnQgJiYgaHVuay5vbGRMaW5lcyA9PT0gMSkge1xuICAgICAgaHVuay5vbGRMaW5lcyA9IDA7XG4gICAgfVxuXG4gICAgLy8gUGVyZm9ybSBvcHRpb25hbCBzYW5pdHkgY2hlY2tpbmdcbiAgICBpZiAob3B0aW9ucy5zdHJpY3QpIHtcbiAgICAgIGlmIChhZGRDb3VudCAhPT0gaHVuay5uZXdMaW5lcykge1xuICAgICAgICB0aHJvdyBuZXcgRXJyb3IoJ0FkZGVkIGxpbmUgY291bnQgZGlkIG5vdCBtYXRjaCBmb3IgaHVuayBhdCBsaW5lICcgKyAoY2h1bmtIZWFkZXJJbmRleCArIDEpKTtcbiAgICAgIH1cbiAgICAgIGlmIChyZW1vdmVDb3VudCAhPT0gaHVuay5vbGRMaW5lcykge1xuICAgICAgICB0aHJvdyBuZXcgRXJyb3IoJ1JlbW92ZWQgbGluZSBjb3VudCBkaWQgbm90IG1hdGNoIGZvciBodW5rIGF0IGxpbmUgJyArIChjaHVua0hlYWRlckluZGV4ICsgMSkpO1xuICAgICAgfVxuICAgIH1cblxuICAgIHJldHVybiBodW5rO1xuICB9XG5cbiAgd2hpbGUgKGkgPCBkaWZmc3RyLmxlbmd0aCkge1xuICAgIHBhcnNlSW5kZXgoKTtcbiAgfVxuXG4gIHJldHVybiBsaXN0O1xufVxuIl19
diff --git a/node_modules/diff/lib/util/array.js b/node_modules/diff/lib/util/array.js
new file mode 100644
index 0000000..1bb4256
--- /dev/null
+++ b/node_modules/diff/lib/util/array.js
@@ -0,0 +1,27 @@
+/*istanbul ignore start*/"use strict";
+
+exports.__esModule = true;
+exports. /*istanbul ignore end*/arrayEqual = arrayEqual;
+/*istanbul ignore start*/exports. /*istanbul ignore end*/arrayStartsWith = arrayStartsWith;
+function arrayEqual(a, b) {
+  if (a.length !== b.length) {
+    return false;
+  }
+
+  return arrayStartsWith(a, b);
+}
+
+function arrayStartsWith(array, start) {
+  if (start.length > array.length) {
+    return false;
+  }
+
+  for (var i = 0; i < start.length; i++) {
+    if (start[i] !== array[i]) {
+      return false;
+    }
+  }
+
+  return true;
+}
+//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy91dGlsL2FycmF5LmpzIl0sIm5hbWVzIjpbImFycmF5RXF1YWwiLCJhcnJheVN0YXJ0c1dpdGgiLCJhIiwiYiIsImxlbmd0aCIsImFycmF5Iiwic3RhcnQiLCJpIl0sIm1hcHBpbmdzIjoiOzs7Z0NBQWdCQSxVLEdBQUFBLFU7eURBUUFDLGUsR0FBQUEsZTtBQVJULFNBQVNELFVBQVQsQ0FBb0JFLENBQXBCLEVBQXVCQyxDQUF2QixFQUEwQjtBQUMvQixNQUFJRCxFQUFFRSxNQUFGLEtBQWFELEVBQUVDLE1BQW5CLEVBQTJCO0FBQ3pCLFdBQU8sS0FBUDtBQUNEOztBQUVELFNBQU9ILGdCQUFnQkMsQ0FBaEIsRUFBbUJDLENBQW5CLENBQVA7QUFDRDs7QUFFTSxTQUFTRixlQUFULENBQXlCSSxLQUF6QixFQUFnQ0MsS0FBaEMsRUFBdUM7QUFDNUMsTUFBSUEsTUFBTUYsTUFBTixHQUFlQyxNQUFNRCxNQUF6QixFQUFpQztBQUMvQixXQUFPLEtBQVA7QUFDRDs7QUFFRCxPQUFLLElBQUlHLElBQUksQ0FBYixFQUFnQkEsSUFBSUQsTUFBTUYsTUFBMUIsRUFBa0NHLEdBQWxDLEVBQXVDO0FBQ3JDLFFBQUlELE1BQU1DLENBQU4sTUFBYUYsTUFBTUUsQ0FBTixDQUFqQixFQUEyQjtBQUN6QixhQUFPLEtBQVA7QUFDRDtBQUNGOztBQUVELFNBQU8sSUFBUDtBQUNEIiwiZmlsZSI6ImFycmF5LmpzIiwic291cmNlc0NvbnRlbnQiOlsiZXhwb3J0IGZ1bmN0aW9uIGFycmF5RXF1YWwoYSwgYikge1xuICBpZiAoYS5sZW5ndGggIT09IGIubGVuZ3RoKSB7XG4gICAgcmV0dXJuIGZhbHNlO1xuICB9XG5cbiAgcmV0dXJuIGFycmF5U3RhcnRzV2l0aChhLCBiKTtcbn1cblxuZXhwb3J0IGZ1bmN0aW9uIGFycmF5U3RhcnRzV2l0aChhcnJheSwgc3RhcnQpIHtcbiAgaWYgKHN0YXJ0Lmxlbmd0aCA+IGFycmF5Lmxlbmd0aCkge1xuICAgIHJldHVybiBmYWxzZTtcbiAgfVxuXG4gIGZvciAobGV0IGkgPSAwOyBpIDwgc3RhcnQubGVuZ3RoOyBpKyspIHtcbiAgICBpZiAoc3RhcnRbaV0gIT09IGFycmF5W2ldKSB7XG4gICAgICByZXR1cm4gZmFsc2U7XG4gICAgfVxuICB9XG5cbiAgcmV0dXJuIHRydWU7XG59XG4iXX0=
diff --git a/node_modules/diff/lib/util/distance-iterator.js b/node_modules/diff/lib/util/distance-iterator.js
new file mode 100644
index 0000000..95e4675
--- /dev/null
+++ b/node_modules/diff/lib/util/distance-iterator.js
@@ -0,0 +1,47 @@
+/*istanbul ignore start*/"use strict";
+
+exports.__esModule = true;
+
+exports["default"] = /*istanbul ignore end*/function (start, minLine, maxLine) {
+  var wantForward = true,
+      backwardExhausted = false,
+      forwardExhausted = false,
+      localOffset = 1;
+
+  return function iterator() {
+    if (wantForward && !forwardExhausted) {
+      if (backwardExhausted) {
+        localOffset++;
+      } else {
+        wantForward = false;
+      }
+
+      // Check if trying to fit beyond text length, and if not, check it fits
+      // after offset location (or desired location on first iteration)
+      if (start + localOffset <= maxLine) {
+        return localOffset;
+      }
+
+      forwardExhausted = true;
+    }
+
+    if (!backwardExhausted) {
+      if (!forwardExhausted) {
+        wantForward = true;
+      }
+
+      // Check if trying to fit before text beginning, and if not, check it fits
+      // before offset location
+      if (minLine <= start - localOffset) {
+        return -localOffset++;
+      }
+
+      backwardExhausted = true;
+      return iterator();
+    }
+
+    // We tried to fit hunk before text beginning and beyond text length, then
+    // hunk can't fit on the text. Return undefined
+  };
+};
+//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy91dGlsL2Rpc3RhbmNlLWl0ZXJhdG9yLmpzIl0sIm5hbWVzIjpbInN0YXJ0IiwibWluTGluZSIsIm1heExpbmUiLCJ3YW50Rm9yd2FyZCIsImJhY2t3YXJkRXhoYXVzdGVkIiwiZm9yd2FyZEV4aGF1c3RlZCIsImxvY2FsT2Zmc2V0IiwiaXRlcmF0b3IiXSwibWFwcGluZ3MiOiI7Ozs7NENBR2UsVUFBU0EsS0FBVCxFQUFnQkMsT0FBaEIsRUFBeUJDLE9BQXpCLEVBQWtDO0FBQy9DLE1BQUlDLGNBQWMsSUFBbEI7QUFBQSxNQUNJQyxvQkFBb0IsS0FEeEI7QUFBQSxNQUVJQyxtQkFBbUIsS0FGdkI7QUFBQSxNQUdJQyxjQUFjLENBSGxCOztBQUtBLFNBQU8sU0FBU0MsUUFBVCxHQUFvQjtBQUN6QixRQUFJSixlQUFlLENBQUNFLGdCQUFwQixFQUFzQztBQUNwQyxVQUFJRCxpQkFBSixFQUF1QjtBQUNyQkU7QUFDRCxPQUZELE1BRU87QUFDTEgsc0JBQWMsS0FBZDtBQUNEOztBQUVEO0FBQ0E7QUFDQSxVQUFJSCxRQUFRTSxXQUFSLElBQXVCSixPQUEzQixFQUFvQztBQUNsQyxlQUFPSSxXQUFQO0FBQ0Q7O0FBRURELHlCQUFtQixJQUFuQjtBQUNEOztBQUVELFFBQUksQ0FBQ0QsaUJBQUwsRUFBd0I7QUFDdEIsVUFBSSxDQUFDQyxnQkFBTCxFQUF1QjtBQUNyQkYsc0JBQWMsSUFBZDtBQUNEOztBQUVEO0FBQ0E7QUFDQSxVQUFJRixXQUFXRCxRQUFRTSxXQUF2QixFQUFvQztBQUNsQyxlQUFPLENBQUNBLGFBQVI7QUFDRDs7QUFFREYsMEJBQW9CLElBQXBCO0FBQ0EsYUFBT0csVUFBUDtBQUNEOztBQUVEO0FBQ0E7QUFDRCxHQWxDRDtBQW1DRCxDIiwiZmlsZSI6ImRpc3RhbmNlLWl0ZXJhdG9yLmpzIiwic291cmNlc0NvbnRlbnQiOlsiLy8gSXRlcmF0b3IgdGhhdCB0cmF2ZXJzZXMgaW4gdGhlIHJhbmdlIG9mIFttaW4sIG1heF0sIHN0ZXBwaW5nXG4vLyBieSBkaXN0YW5jZSBmcm9tIGEgZ2l2ZW4gc3RhcnQgcG9zaXRpb24uIEkuZS4gZm9yIFswLCA0XSwgd2l0aFxuLy8gc3RhcnQgb2YgMiwgdGhpcyB3aWxsIGl0ZXJhdGUgMiwgMywgMSwgNCwgMC5cbmV4cG9ydCBkZWZhdWx0IGZ1bmN0aW9uKHN0YXJ0LCBtaW5MaW5lLCBtYXhMaW5lKSB7XG4gIGxldCB3YW50Rm9yd2FyZCA9IHRydWUsXG4gICAgICBiYWNrd2FyZEV4aGF1c3RlZCA9IGZhbHNlLFxuICAgICAgZm9yd2FyZEV4aGF1c3RlZCA9IGZhbHNlLFxuICAgICAgbG9jYWxPZmZzZXQgPSAxO1xuXG4gIHJldHVybiBmdW5jdGlvbiBpdGVyYXRvcigpIHtcbiAgICBpZiAod2FudEZvcndhcmQgJiYgIWZvcndhcmRFeGhhdXN0ZWQpIHtcbiAgICAgIGlmIChiYWNrd2FyZEV4aGF1c3RlZCkge1xuICAgICAgICBsb2NhbE9mZnNldCsrO1xuICAgICAgfSBlbHNlIHtcbiAgICAgICAgd2FudEZvcndhcmQgPSBmYWxzZTtcbiAgICAgIH1cblxuICAgICAgLy8gQ2hlY2sgaWYgdHJ5aW5nIHRvIGZpdCBiZXlvbmQgdGV4dCBsZW5ndGgsIGFuZCBpZiBub3QsIGNoZWNrIGl0IGZpdHNcbiAgICAgIC8vIGFmdGVyIG9mZnNldCBsb2NhdGlvbiAob3IgZGVzaXJlZCBsb2NhdGlvbiBvbiBmaXJzdCBpdGVyYXRpb24pXG4gICAgICBpZiAoc3RhcnQgKyBsb2NhbE9mZnNldCA8PSBtYXhMaW5lKSB7XG4gICAgICAgIHJldHVybiBsb2NhbE9mZnNldDtcbiAgICAgIH1cblxuICAgICAgZm9yd2FyZEV4aGF1c3RlZCA9IHRydWU7XG4gICAgfVxuXG4gICAgaWYgKCFiYWNrd2FyZEV4aGF1c3RlZCkge1xuICAgICAgaWYgKCFmb3J3YXJkRXhoYXVzdGVkKSB7XG4gICAgICAgIHdhbnRGb3J3YXJkID0gdHJ1ZTtcbiAgICAgIH1cblxuICAgICAgLy8gQ2hlY2sgaWYgdHJ5aW5nIHRvIGZpdCBiZWZvcmUgdGV4dCBiZWdpbm5pbmcsIGFuZCBpZiBub3QsIGNoZWNrIGl0IGZpdHNcbiAgICAgIC8vIGJlZm9yZSBvZmZzZXQgbG9jYXRpb25cbiAgICAgIGlmIChtaW5MaW5lIDw9IHN0YXJ0IC0gbG9jYWxPZmZzZXQpIHtcbiAgICAgICAgcmV0dXJuIC1sb2NhbE9mZnNldCsrO1xuICAgICAgfVxuXG4gICAgICBiYWNrd2FyZEV4aGF1c3RlZCA9IHRydWU7XG4gICAgICByZXR1cm4gaXRlcmF0b3IoKTtcbiAgICB9XG5cbiAgICAvLyBXZSB0cmllZCB0byBmaXQgaHVuayBiZWZvcmUgdGV4dCBiZWdpbm5pbmcgYW5kIGJleW9uZCB0ZXh0IGxlbmd0aCwgdGhlblxuICAgIC8vIGh1bmsgY2FuJ3QgZml0IG9uIHRoZSB0ZXh0LiBSZXR1cm4gdW5kZWZpbmVkXG4gIH07XG59XG4iXX0=
diff --git a/node_modules/diff/lib/util/params.js b/node_modules/diff/lib/util/params.js
new file mode 100644
index 0000000..6ff0483
--- /dev/null
+++ b/node_modules/diff/lib/util/params.js
@@ -0,0 +1,18 @@
+/*istanbul ignore start*/'use strict';
+
+exports.__esModule = true;
+exports. /*istanbul ignore end*/generateOptions = generateOptions;
+function generateOptions(options, defaults) {
+  if (typeof options === 'function') {
+    defaults.callback = options;
+  } else if (options) {
+    for (var name in options) {
+      /* istanbul ignore else */
+      if (options.hasOwnProperty(name)) {
+        defaults[name] = options[name];
+      }
+    }
+  }
+  return defaults;
+}
+//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy91dGlsL3BhcmFtcy5qcyJdLCJuYW1lcyI6WyJnZW5lcmF0ZU9wdGlvbnMiLCJvcHRpb25zIiwiZGVmYXVsdHMiLCJjYWxsYmFjayIsIm5hbWUiLCJoYXNPd25Qcm9wZXJ0eSJdLCJtYXBwaW5ncyI6Ijs7O2dDQUFnQkEsZSxHQUFBQSxlO0FBQVQsU0FBU0EsZUFBVCxDQUF5QkMsT0FBekIsRUFBa0NDLFFBQWxDLEVBQTRDO0FBQ2pELE1BQUksT0FBT0QsT0FBUCxLQUFtQixVQUF2QixFQUFtQztBQUNqQ0MsYUFBU0MsUUFBVCxHQUFvQkYsT0FBcEI7QUFDRCxHQUZELE1BRU8sSUFBSUEsT0FBSixFQUFhO0FBQ2xCLFNBQUssSUFBSUcsSUFBVCxJQUFpQkgsT0FBakIsRUFBMEI7QUFDeEI7QUFDQSxVQUFJQSxRQUFRSSxjQUFSLENBQXVCRCxJQUF2QixDQUFKLEVBQWtDO0FBQ2hDRixpQkFBU0UsSUFBVCxJQUFpQkgsUUFBUUcsSUFBUixDQUFqQjtBQUNEO0FBQ0Y7QUFDRjtBQUNELFNBQU9GLFFBQVA7QUFDRCIsImZpbGUiOiJwYXJhbXMuanMiLCJzb3VyY2VzQ29udGVudCI6WyJleHBvcnQgZnVuY3Rpb24gZ2VuZXJhdGVPcHRpb25zKG9wdGlvbnMsIGRlZmF1bHRzKSB7XG4gIGlmICh0eXBlb2Ygb3B0aW9ucyA9PT0gJ2Z1bmN0aW9uJykge1xuICAgIGRlZmF1bHRzLmNhbGxiYWNrID0gb3B0aW9ucztcbiAgfSBlbHNlIGlmIChvcHRpb25zKSB7XG4gICAgZm9yIChsZXQgbmFtZSBpbiBvcHRpb25zKSB7XG4gICAgICAvKiBpc3RhbmJ1bCBpZ25vcmUgZWxzZSAqL1xuICAgICAgaWYgKG9wdGlvbnMuaGFzT3duUHJvcGVydHkobmFtZSkpIHtcbiAgICAgICAgZGVmYXVsdHNbbmFtZV0gPSBvcHRpb25zW25hbWVdO1xuICAgICAgfVxuICAgIH1cbiAgfVxuICByZXR1cm4gZGVmYXVsdHM7XG59XG4iXX0=
diff --git a/node_modules/diff/package.json b/node_modules/diff/package.json
new file mode 100644
index 0000000..44776b6
--- /dev/null
+++ b/node_modules/diff/package.json
@@ -0,0 +1,97 @@
+{
+  "_from": "diff@3.5.0",
+  "_id": "diff@3.5.0",
+  "_inBundle": false,
+  "_integrity": "sha512-A46qtFgd+g7pDZinpnwiRJtxbC1hpgf0uzP3iG89scHk0AUC7A1TGxf5OiiOUv/JMZR8GOt8hL900hV0bOy5xA==",
+  "_location": "/diff",
+  "_phantomChildren": {},
+  "_requested": {
+    "type": "version",
+    "registry": true,
+    "raw": "diff@3.5.0",
+    "name": "diff",
+    "escapedName": "diff",
+    "rawSpec": "3.5.0",
+    "saveSpec": null,
+    "fetchSpec": "3.5.0"
+  },
+  "_requiredBy": [
+    "/mocha"
+  ],
+  "_resolved": "https://registry.npmjs.org/diff/-/diff-3.5.0.tgz",
+  "_shasum": "800c0dd1e0a8bfbc95835c202ad220fe317e5a12",
+  "_spec": "diff@3.5.0",
+  "_where": "/Users/jessitron/code/jessitron/stringify-tree/node_modules/mocha",
+  "browser": "./dist/diff.js",
+  "bugs": {
+    "url": "http://github.com/kpdecker/jsdiff/issues",
+    "email": "kpdecker@gmail.com"
+  },
+  "bundleDependencies": false,
+  "dependencies": {},
+  "deprecated": false,
+  "description": "A javascript text diff implementation.",
+  "devDependencies": {
+    "async": "^1.4.2",
+    "babel-core": "^6.0.0",
+    "babel-loader": "^6.0.0",
+    "babel-preset-es2015-mod": "^6.3.13",
+    "babel-preset-es3": "^1.0.1",
+    "chai": "^3.3.0",
+    "colors": "^1.1.2",
+    "eslint": "^1.6.0",
+    "grunt": "^0.4.5",
+    "grunt-babel": "^6.0.0",
+    "grunt-clean": "^0.4.0",
+    "grunt-cli": "^0.1.13",
+    "grunt-contrib-clean": "^1.0.0",
+    "grunt-contrib-copy": "^1.0.0",
+    "grunt-contrib-uglify": "^1.0.0",
+    "grunt-contrib-watch": "^1.0.0",
+    "grunt-eslint": "^17.3.1",
+    "grunt-karma": "^0.12.1",
+    "grunt-mocha-istanbul": "^3.0.1",
+    "grunt-mocha-test": "^0.12.7",
+    "grunt-webpack": "^1.0.11",
+    "istanbul": "github:kpdecker/istanbul",
+    "karma": "^0.13.11",
+    "karma-mocha": "^0.2.0",
+    "karma-mocha-reporter": "^2.0.0",
+    "karma-phantomjs-launcher": "^1.0.0",
+    "karma-sauce-launcher": "^0.3.0",
+    "karma-sourcemap-loader": "^0.3.6",
+    "karma-webpack": "^1.7.0",
+    "mocha": "^2.3.3",
+    "phantomjs-prebuilt": "^2.1.5",
+    "semver": "^5.0.3",
+    "webpack": "^1.12.2",
+    "webpack-dev-server": "^1.12.0"
+  },
+  "engines": {
+    "node": ">=0.3.1"
+  },
+  "homepage": "https://github.com/kpdecker/jsdiff#readme",
+  "keywords": [
+    "diff",
+    "javascript"
+  ],
+  "license": "BSD-3-Clause",
+  "main": "./lib",
+  "maintainers": [
+    {
+      "name": "Kevin Decker",
+      "email": "kpdecker@gmail.com",
+      "url": "http://incaseofstairs.com"
+    }
+  ],
+  "name": "diff",
+  "optionalDependencies": {},
+  "repository": {
+    "type": "git",
+    "url": "git://github.com/kpdecker/jsdiff.git"
+  },
+  "scripts": {
+    "test": "grunt"
+  },
+  "version": "3.5.0"
+}
diff --git a/node_modules/diff/release-notes.md b/node_modules/diff/release-notes.md
new file mode 100644
index 0000000..0116a2b
--- /dev/null
+++ b/node_modules/diff/release-notes.md
@@ -0,0 +1,247 @@
+# Release Notes
+
+## Development
+
+[Commits](https://github.com/kpdecker/jsdiff/compare/v3.5.0...master)
+
+## v3.5.0 - March 4th, 2018
+- Omit redundant slice in join method of diffArrays - 1023590
+- Support patches with empty lines - fb0f208
+- Accept a custom JSON replacer function for JSON diffing - 69c7f0a
+- Optimize parch header parser - 2aec429
+- Fix typos - e89c832
+
+[Commits](https://github.com/kpdecker/jsdiff/compare/v3.5.0...v3.5.0)
+
+## v3.5.0 - March 4th, 2018
+- Omit redundant slice in join method of diffArrays - 1023590
+- Support patches with empty lines - fb0f208
+- Accept a custom JSON replacer function for JSON diffing - 69c7f0a
+- Optimize parch header parser - 2aec429
+- Fix typos - e89c832
+
+[Commits](https://github.com/kpdecker/jsdiff/compare/v3.4.0...v3.5.0)
+
+## v3.4.0 - October 7th, 2017
+- [#183](https://github.com/kpdecker/jsdiff/issues/183) - Feature request: ability to specify a custom equality checker for `diffArrays`
+- [#173](https://github.com/kpdecker/jsdiff/issues/173) - Bug: diffArrays gives wrong result on array of booleans
+- [#158](https://github.com/kpdecker/jsdiff/issues/158) - diffArrays will not compare the empty string in array?
+- comparator for custom equality checks - 30e141e
+- count oldLines and newLines when there are conflicts - 53bf384
+- Fix: diffArrays can compare falsey items - 9e24284
+- Docs: Replace grunt with npm test - 00e2f94
+
+[Commits](https://github.com/kpdecker/jsdiff/compare/v3.3.1...v3.4.0)
+
+## v3.3.1 - September 3rd, 2017
+- [#141](https://github.com/kpdecker/jsdiff/issues/141) - Cannot apply patch because my file delimiter is "/r/n" instead of "/n"
+- [#192](https://github.com/kpdecker/jsdiff/pull/192) - Fix: Bad merge when adding new files (#189)
+- correct spelling mistake - 21fa478
+
+[Commits](https://github.com/kpdecker/jsdiff/compare/v3.3.0...v3.3.1)
+
+## v3.3.0 - July 5th, 2017
+- [#114](https://github.com/kpdecker/jsdiff/issues/114) - /patch/merge not exported
+- Gracefully accept invalid newStart in hunks, same as patch(1) does. - d8a3635
+- Use regex rather than starts/ends with for parsePatch - 6cab62c
+- Add browser flag - e64f674
+- refactor: simplified code a bit more - 8f8e0f2
+- refactor: simplified code a bit - b094a6f
+- fix: some corrections re ignoreCase option - 3c78fd0
+- ignoreCase option - 3cbfbb5
+- Sanitize filename while parsing patches - 2fe8129
+- Added better installation methods - aced50b
+- Simple export of functionality - 8690f31
+
+[Commits](https://github.com/kpdecker/jsdiff/compare/v3.2.0...v3.3.0)
+
+## v3.2.0 - December 26th, 2016
+- [#156](https://github.com/kpdecker/jsdiff/pull/156) - Add `undefinedReplacement` option to `diffJson` ([@ewnd9](https://api.github.com/users/ewnd9))
+- [#154](https://github.com/kpdecker/jsdiff/pull/154) - Add `examples` and `images` to `.npmignore`. ([@wtgtybhertgeghgtwtg](https://api.github.com/users/wtgtybhertgeghgtwtg))
+- [#153](https://github.com/kpdecker/jsdiff/pull/153) - feat(structuredPatch): Pass options to diffLines ([@Kiougar](https://api.github.com/users/Kiougar))
+
+[Commits](https://github.com/kpdecker/jsdiff/compare/v3.1.0...v3.2.0)
+
+## v3.1.0 - November 27th, 2016
+- [#146](https://github.com/kpdecker/jsdiff/pull/146) - JsDiff.diffArrays to compare arrays ([@wvanderdeijl](https://api.github.com/users/wvanderdeijl))
+- [#144](https://github.com/kpdecker/jsdiff/pull/144) - Split file using all possible line delimiter instead of hard-coded "/n" and join lines back using the original delimiters ([@soulbeing](https://api.github.com/users/soulbeing))
+
+[Commits](https://github.com/kpdecker/jsdiff/compare/v3.0.1...v3.1.0)
+
+## v3.0.1 - October 9th, 2016
+- [#139](https://github.com/kpdecker/jsdiff/pull/139) - Make README.md look nicer in npmjs.com ([@takenspc](https://api.github.com/users/takenspc))
+- [#135](https://github.com/kpdecker/jsdiff/issues/135) - parsePatch combines patches from multiple files into a single IUniDiff when there is no "Index" line ([@ramya-rao-a](https://api.github.com/users/ramya-rao-a))
+- [#124](https://github.com/kpdecker/jsdiff/issues/124) - IE7/IE8 failure since 2.0.0 ([@boneskull](https://api.github.com/users/boneskull))
+
+[Commits](https://github.com/kpdecker/jsdiff/compare/v3.0.0...v3.0.1)
+
+## v3.0.0 - August 23rd, 2016
+- [#130](https://github.com/kpdecker/jsdiff/pull/130) - Add callback argument to applyPatches `patched` option ([@piranna](https://api.github.com/users/piranna))
+- [#120](https://github.com/kpdecker/jsdiff/pull/120) - Correctly handle file names containing spaces ([@adius](https://api.github.com/users/adius))
+- [#119](https://github.com/kpdecker/jsdiff/pull/119) - Do single reflow ([@wifiextender](https://api.github.com/users/wifiextender))
+- [#117](https://github.com/kpdecker/jsdiff/pull/117) - Make more usable with long strings. ([@abnbgist](https://api.github.com/users/abnbgist))
+
+Compatibility notes:
+- applyPatches patch callback now is async and requires the callback be called to continue operation
+
+[Commits](https://github.com/kpdecker/jsdiff/compare/v2.2.3...v3.0.0)
+
+## v2.2.3 - May 31st, 2016
+- [#118](https://github.com/kpdecker/jsdiff/pull/118) - Add a fix for applying 0-length destination patches ([@chaaz](https://api.github.com/users/chaaz))
+- [#115](https://github.com/kpdecker/jsdiff/pull/115) - Fixed grammar in README ([@krizalys](https://api.github.com/users/krizalys))
+- [#113](https://github.com/kpdecker/jsdiff/pull/113) - fix typo ([@vmazare](https://api.github.com/users/vmazare))
+
+[Commits](https://github.com/kpdecker/jsdiff/compare/v2.2.2...v2.2.3)
+
+## v2.2.2 - March 13th, 2016
+- [#102](https://github.com/kpdecker/jsdiff/issues/102) - diffJson with dates, returns empty curly braces  ([@dr-dimitru](https://api.github.com/users/dr-dimitru))
+- [#97](https://github.com/kpdecker/jsdiff/issues/97) - Whitespaces & diffWords ([@faiwer](https://api.github.com/users/faiwer))
+- [#92](https://github.com/kpdecker/jsdiff/pull/92) - Fixes typo in the readme ([@bg451](https://api.github.com/users/bg451))
+
+[Commits](https://github.com/kpdecker/jsdiff/compare/v2.2.1...v2.2.2)
+
+## v2.2.1 - November 12th, 2015
+- [#89](https://github.com/kpdecker/jsdiff/pull/89) - add in display selector to readme ([@FranDias](https://api.github.com/users/FranDias))
+- [#88](https://github.com/kpdecker/jsdiff/pull/88) - Split diffs based on file headers instead of 'Index:' metadata ([@piranna](https://api.github.com/users/piranna))
+
+[Commits](https://github.com/kpdecker/jsdiff/compare/v2.2.0...v2.2.1)
+
+## v2.2.0 - October 29th, 2015
+- [#80](https://github.com/kpdecker/jsdiff/pull/80) - Fix a typo: applyPath ->  applyPatch ([@fluxxu](https://api.github.com/users/fluxxu))
+- [#83](https://github.com/kpdecker/jsdiff/pull/83) - Add basic fuzzy matching to applyPatch ([@piranna](https://github.com/piranna))
+[Commits](https://github.com/kpdecker/jsdiff/compare/v2.2.0...v2.2.0)
+
+## v2.2.0 - October 29th, 2015
+- [#80](https://github.com/kpdecker/jsdiff/pull/80) - Fix a typo: applyPath ->  applyPatch ([@fluxxu](https://api.github.com/users/fluxxu))
+- [#83](https://github.com/kpdecker/jsdiff/pull/83) - Add basic fuzzy matching to applyPatch ([@piranna](https://github.com/piranna))
+[Commits](https://github.com/kpdecker/jsdiff/compare/v2.1.3...v2.2.0)
+
+## v2.1.3 - September 30th, 2015
+- [#78](https://github.com/kpdecker/jsdiff/pull/78) - fix: error throwing when apply patch to empty string ([@21paradox](https://api.github.com/users/21paradox))
+
+[Commits](https://github.com/kpdecker/jsdiff/compare/v2.1.2...v2.1.3)
+
+## v2.1.2 - September 23rd, 2015
+- [#76](https://github.com/kpdecker/jsdiff/issues/76) - diff headers give error ([@piranna](https://api.github.com/users/piranna))
+
+[Commits](https://github.com/kpdecker/jsdiff/compare/v2.1.1...v2.1.2)
+
+## v2.1.1 - September 9th, 2015
+- [#73](https://github.com/kpdecker/jsdiff/issues/73) - Is applyPatches() exposed in the API? ([@davidparsson](https://api.github.com/users/davidparsson))
+
+[Commits](https://github.com/kpdecker/jsdiff/compare/v2.1.0...v2.1.1)
+
+## v2.1.0 - August 27th, 2015
+- [#72](https://github.com/kpdecker/jsdiff/issues/72) - Consider using options object API for flag permutations ([@kpdecker](https://api.github.com/users/kpdecker))
+- [#70](https://github.com/kpdecker/jsdiff/issues/70) - diffWords treats \n at the end as significant whitespace ([@nesQuick](https://api.github.com/users/nesQuick))
+- [#69](https://github.com/kpdecker/jsdiff/issues/69) - Missing count ([@wfalkwallace](https://api.github.com/users/wfalkwallace))
+- [#68](https://github.com/kpdecker/jsdiff/issues/68) - diffLines seems broken ([@wfalkwallace](https://api.github.com/users/wfalkwallace))
+- [#60](https://github.com/kpdecker/jsdiff/issues/60) - Support multiple diff hunks ([@piranna](https://api.github.com/users/piranna))
+- [#54](https://github.com/kpdecker/jsdiff/issues/54) - Feature Request: 3-way merge ([@mog422](https://api.github.com/users/mog422))
+- [#42](https://github.com/kpdecker/jsdiff/issues/42) - Fuzz factor for applyPatch ([@stuartpb](https://api.github.com/users/stuartpb))
+- Move whitespace ignore out of equals method - 542063c
+- Include source maps in babel output - 7f7ab21
+- Merge diff/line and diff/patch implementations - 1597705
+- Drop map utility method - 1ddc939
+- Documentation for parsePatch and applyPatches - 27c4b77
+
+Compatibility notes:
+- The undocumented ignoreWhitespace flag has been removed from the Diff equality check directly. This implementation may be copied to diff utilities if dependencies existed on this functionality.
+
+[Commits](https://github.com/kpdecker/jsdiff/compare/v2.0.2...v2.1.0)
+
+## v2.0.2 - August 8th, 2015
+- [#67](https://github.com/kpdecker/jsdiff/issues/67) - cannot require from npm module in node ([@commenthol](https://api.github.com/users/commenthol))
+- Convert to chai since we don’t support IE8 - a96bbad
+
+[Commits](https://github.com/kpdecker/jsdiff/compare/v2.0.1...v2.0.2)
+
+## v2.0.1 - August 7th, 2015
+- Add release build at proper step - 57542fd
+
+[Commits](https://github.com/kpdecker/jsdiff/compare/v2.0.0...v2.0.1)
+
+## v2.0.0 - August 7th, 2015
+- [#66](https://github.com/kpdecker/jsdiff/issues/66) - Add karma and sauce tests ([@kpdecker](https://api.github.com/users/kpdecker))
+- [#65](https://github.com/kpdecker/jsdiff/issues/65) - Create component repository for bower ([@kpdecker](https://api.github.com/users/kpdecker))
+- [#64](https://github.com/kpdecker/jsdiff/issues/64) - Automatically call removeEmpty for all tokenizer calls ([@kpdecker](https://api.github.com/users/kpdecker))
+- [#62](https://github.com/kpdecker/jsdiff/pull/62) - Allow access to structured object representation of patch data ([@bittrance](https://api.github.com/users/bittrance))
+- [#61](https://github.com/kpdecker/jsdiff/pull/61) - Use svg instead of png to get better image quality ([@PeterDaveHello](https://api.github.com/users/PeterDaveHello))
+- [#29](https://github.com/kpdecker/jsdiff/issues/29) - word tokenizer works only for 7 bit ascii ([@plasmagunman](https://api.github.com/users/plasmagunman))
+
+Compatibility notes:
+- `this.removeEmpty` is now called automatically for all instances. If this is not desired, this may be overridden on a per instance basis.
+- The library has been refactored to use some ES6 features. The external APIs should remain the same, but bower projects that directly referenced the repository will now have to point to the [components/jsdiff](https://github.com/components/jsdiff) repository.
+
+[Commits](https://github.com/kpdecker/jsdiff/compare/v1.4.0...v2.0.0)
+
+## v1.4.0 - May 6th, 2015
+- [#57](https://github.com/kpdecker/jsdiff/issues/57) - createPatch -> applyPatch failed. ([@mog422](https://api.github.com/users/mog422))
+- [#56](https://github.com/kpdecker/jsdiff/pull/56) - Two files patch ([@rgeissert](https://api.github.com/users/rgeissert))
+- [#14](https://github.com/kpdecker/jsdiff/issues/14) - Flip added and removed order? ([@jakesandlund](https://api.github.com/users/jakesandlund))
+
+[Commits](https://github.com/kpdecker/jsdiff/compare/v1.3.2...v1.4.0)
+
+## v1.3.2 - March 30th, 2015
+- [#53](https://github.com/kpdecker/jsdiff/pull/53) - Updated README.MD with Bower installation instructions ([@ofbriggs](https://api.github.com/users/ofbriggs))
+- [#49](https://github.com/kpdecker/jsdiff/issues/49) - Cannot read property 'oldlines' of undefined ([@nwtn](https://api.github.com/users/nwtn))
+- [#44](https://github.com/kpdecker/jsdiff/issues/44) - invalid-meta jsdiff is missing "main" entry in bower.json
+
+[Commits](https://github.com/kpdecker/jsdiff/compare/v1.3.1...v1.3.2)
+
+## v1.3.1 - March 13th, 2015
+- [#52](https://github.com/kpdecker/jsdiff/pull/52) - Fix for #51 Wrong result of JsDiff.diffLines ([@felicienfrancois](https://api.github.com/users/felicienfrancois))
+
+[Commits](https://github.com/kpdecker/jsdiff/compare/v1.3.0...v1.3.1)
+
+## v1.3.0 - March 2nd, 2015
+- [#47](https://github.com/kpdecker/jsdiff/pull/47) - Adding Diff Trimmed Lines ([@JamesGould123](https://api.github.com/users/JamesGould123))
+
+[Commits](https://github.com/kpdecker/jsdiff/compare/v1.2.2...v1.3.0)
+
+## v1.2.2 - January 26th, 2015
+- [#45](https://github.com/kpdecker/jsdiff/pull/45) - Fix AMD module loading ([@pedrocarrico](https://api.github.com/users/pedrocarrico))
+- [#43](https://github.com/kpdecker/jsdiff/pull/43) - added a bower file ([@nbrustein](https://api.github.com/users/nbrustein))
+
+[Commits](https://github.com/kpdecker/jsdiff/compare/v1.2.1...v1.2.2)
+
+## v1.2.1 - December 26th, 2014
+- [#41](https://github.com/kpdecker/jsdiff/pull/41) - change condition of using node export system. ([@ironhee](https://api.github.com/users/ironhee))
+
+[Commits](https://github.com/kpdecker/jsdiff/compare/v1.2.0...v1.2.1)
+
+## v1.2.0 - November 29th, 2014
+- [#37](https://github.com/kpdecker/jsdiff/pull/37) - Add support for sentences. ([@vmariano](https://api.github.com/users/vmariano))
+- [#28](https://github.com/kpdecker/jsdiff/pull/28) - Implemented diffJson ([@papandreou](https://api.github.com/users/papandreou))
+- [#27](https://github.com/kpdecker/jsdiff/issues/27) - Slow to execute over diffs with a large number of changes ([@termi](https://api.github.com/users/termi))
+- Allow for optional async diffing - 19385b9
+- Fix diffChars implementation - eaa44ed
+
+[Commits](https://github.com/kpdecker/jsdiff/compare/v1.1.0...v1.2.0)
+
+## v1.1.0 - November 25th, 2014
+- [#33](https://github.com/kpdecker/jsdiff/pull/33) - AMD and global exports ([@ovcharik](https://api.github.com/users/ovcharik))
+- [#32](https://github.com/kpdecker/jsdiff/pull/32) - Add support for component ([@vmariano](https://api.github.com/users/vmariano))
+- [#31](https://github.com/kpdecker/jsdiff/pull/31) - Don't rely on Array.prototype.map ([@papandreou](https://api.github.com/users/papandreou))
+
+[Commits](https://github.com/kpdecker/jsdiff/compare/v1.0.8...v1.1.0)
+
+## v1.0.8 - December 22nd, 2013
+- [#24](https://github.com/kpdecker/jsdiff/pull/24) - Handle windows newlines on non windows machines. ([@benogle](https://api.github.com/users/benogle))
+- [#23](https://github.com/kpdecker/jsdiff/pull/23) - Prettied up the API formatting a little, and added basic node and web examples ([@airportyh](https://api.github.com/users/airportyh))
+
+[Commits](https://github.com/kpdecker/jsdiff/compare/v1.0.7...v1.0.8)
+
+## v1.0.7 - September 11th, 2013
+
+- [#22](https://github.com/kpdecker/jsdiff/pull/22) - Added variant of WordDiff that doesn't ignore whitespace differences ([@papandreou](https://api.github.com/users/papandreou)
+
+- Add 0.10 to travis tests - 243a526
+
+[Commits](https://github.com/kpdecker/jsdiff/compare/v1.0.6...v1.0.7)
+
+## v1.0.6 - August 30th, 2013
+
+- [#19](https://github.com/kpdecker/jsdiff/pull/19) - Explicitly define contents of npm package ([@sindresorhus](https://api.github.com/users/sindresorhus)
+
+[Commits](https://github.com/kpdecker/jsdiff/compare/v1.0.5...v1.0.6)
diff --git a/node_modules/diff/runtime.js b/node_modules/diff/runtime.js
new file mode 100644
index 0000000..fd8ca6e
--- /dev/null
+++ b/node_modules/diff/runtime.js
@@ -0,0 +1,3 @@
+require('babel-core/register')({
+  ignore: /\/lib\/|\/node_modules\//
+});
diff --git a/node_modules/diff/yarn.lock b/node_modules/diff/yarn.lock
new file mode 100644
index 0000000..29e3ab3
--- /dev/null
+++ b/node_modules/diff/yarn.lock
@@ -0,0 +1,5729 @@
+# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.
+# yarn lockfile v1
+
+
+abbrev@1:
+  version "1.1.1"
+  resolved "https://registry.yarnpkg.com/abbrev/-/abbrev-1.1.1.tgz#f8f2c887ad10bf67f634f005b6987fed3179aac8"
+
+abbrev@1.0.x:
+  version "1.0.9"
+  resolved "https://registry.yarnpkg.com/abbrev/-/abbrev-1.0.9.tgz#91b4792588a7738c25f35dd6f63752a2f8776135"
+
+accepts@1.3.3:
+  version "1.3.3"
+  resolved "https://registry.yarnpkg.com/accepts/-/accepts-1.3.3.tgz#c3ca7434938648c3e0d9c1e328dd68b622c284ca"
+  dependencies:
+    mime-types "~2.1.11"
+    negotiator "0.6.1"
+
+accepts@~1.3.4:
+  version "1.3.5"
+  resolved "https://registry.yarnpkg.com/accepts/-/accepts-1.3.5.tgz#eb777df6011723a3b14e8a72c0805c8e86746bd2"
+  dependencies:
+    mime-types "~2.1.18"
+    negotiator "0.6.1"
+
+acorn@^3.0.0:
+  version "3.3.0"
+  resolved "https://registry.yarnpkg.com/acorn/-/acorn-3.3.0.tgz#45e37fb39e8da3f25baee3ff5369e2bb5f22017a"
+
+adm-zip@~0.4.3:
+  version "0.4.7"
+  resolved "https://registry.yarnpkg.com/adm-zip/-/adm-zip-0.4.7.tgz#8606c2cbf1c426ce8c8ec00174447fd49b6eafc1"
+
+after@0.8.2:
+  version "0.8.2"
+  resolved "https://registry.yarnpkg.com/after/-/after-0.8.2.tgz#fedb394f9f0e02aa9768e702bda23b505fae7e1f"
+
+agent-base@2:
+  version "2.1.1"
+  resolved "https://registry.yarnpkg.com/agent-base/-/agent-base-2.1.1.tgz#d6de10d5af6132d5bd692427d46fc538539094c7"
+  dependencies:
+    extend "~3.0.0"
+    semver "~5.0.1"
+
+ajv@^4.9.1:
+  version "4.11.8"
+  resolved "https://registry.yarnpkg.com/ajv/-/ajv-4.11.8.tgz#82ffb02b29e662ae53bdc20af15947706739c536"
+  dependencies:
+    co "^4.6.0"
+    json-stable-stringify "^1.0.1"
+
+ajv@^5.1.0:
+  version "5.5.2"
+  resolved "https://registry.yarnpkg.com/ajv/-/ajv-5.5.2.tgz#73b5eeca3fab653e3d3f9422b341ad42205dc965"
+  dependencies:
+    co "^4.6.0"
+    fast-deep-equal "^1.0.0"
+    fast-json-stable-stringify "^2.0.0"
+    json-schema-traverse "^0.3.0"
+
+align-text@^0.1.1, align-text@^0.1.3:
+  version "0.1.4"
+  resolved "https://registry.yarnpkg.com/align-text/-/align-text-0.1.4.tgz#0cd90a561093f35d0a99256c22b7069433fad117"
+  dependencies:
+    kind-of "^3.0.2"
+    longest "^1.0.1"
+    repeat-string "^1.5.2"
+
+amdefine@>=0.0.4:
+  version "1.0.1"
+  resolved "https://registry.yarnpkg.com/amdefine/-/amdefine-1.0.1.tgz#4a5282ac164729e93619bcfd3ad151f817ce91f5"
+
+ansi-escapes@^1.1.0:
+  version "1.4.0"
+  resolved "https://registry.yarnpkg.com/ansi-escapes/-/ansi-escapes-1.4.0.tgz#d3a8a83b319aa67793662b13e761c7911422306e"
+
+ansi-regex@^2.0.0:
+  version "2.1.1"
+  resolved "https://registry.yarnpkg.com/ansi-regex/-/ansi-regex-2.1.1.tgz#c3b33ab5ee360d86e0e628f0468ae7ef27d654df"
+
+ansi-regex@^3.0.0:
+  version "3.0.0"
+  resolved "https://registry.yarnpkg.com/ansi-regex/-/ansi-regex-3.0.0.tgz#ed0317c322064f79466c02966bddb605ab37d998"
+
+ansi-styles@^2.2.1:
+  version "2.2.1"
+  resolved "https://registry.yarnpkg.com/ansi-styles/-/ansi-styles-2.2.1.tgz#b432dd3358b634cf75e1e4664368240533c1ddbe"
+
+ansi-styles@^3.2.1:
+  version "3.2.1"
+  resolved "https://registry.yarnpkg.com/ansi-styles/-/ansi-styles-3.2.1.tgz#41fbb20243e50b12be0f04b8dedbf07520ce841d"
+  dependencies:
+    color-convert "^1.9.0"
+
+anymatch@^1.3.0:
+  version "1.3.2"
+  resolved "https://registry.yarnpkg.com/anymatch/-/anymatch-1.3.2.tgz#553dcb8f91e3c889845dfdba34c77721b90b9d7a"
+  dependencies:
+    micromatch "^2.1.5"
+    normalize-path "^2.0.0"
+
+append-transform@^0.4.0:
+  version "0.4.0"
+  resolved "https://registry.yarnpkg.com/append-transform/-/append-transform-0.4.0.tgz#d76ebf8ca94d276e247a36bad44a4b74ab611991"
+  dependencies:
+    default-require-extensions "^1.0.0"
+
+aproba@^1.0.3:
+  version "1.2.0"
+  resolved "https://registry.yarnpkg.com/aproba/-/aproba-1.2.0.tgz#6802e6264efd18c790a1b0d517f0f2627bf2c94a"
+
+archiver@~0.14.0:
+  version "0.14.4"
+  resolved "https://registry.yarnpkg.com/archiver/-/archiver-0.14.4.tgz#5b9ddb9f5ee1ceef21cb8f3b020e6240ecb4315c"
+  dependencies:
+    async "~0.9.0"
+    buffer-crc32 "~0.2.1"
+    glob "~4.3.0"
+    lazystream "~0.1.0"
+    lodash "~3.2.0"
+    readable-stream "~1.0.26"
+    tar-stream "~1.1.0"
+    zip-stream "~0.5.0"
+
+archy@^1.0.0:
+  version "1.0.0"
+  resolved "https://registry.yarnpkg.com/archy/-/archy-1.0.0.tgz#f9c8c13757cc1dd7bc379ac77b2c62a5c2868c40"
+
+are-we-there-yet@~1.1.2:
+  version "1.1.4"
+  resolved "https://registry.yarnpkg.com/are-we-there-yet/-/are-we-there-yet-1.1.4.tgz#bb5dca382bb94f05e15194373d16fd3ba1ca110d"
+  dependencies:
+    delegates "^1.0.0"
+    readable-stream "^2.0.6"
+
+argparse@^1.0.2, argparse@^1.0.7:
+  version "1.0.10"
+  resolved "https://registry.yarnpkg.com/argparse/-/argparse-1.0.10.tgz#bcd6791ea5ae09725e17e5ad988134cd40b3d911"
+  dependencies:
+    sprintf-js "~1.0.2"
+
+"argparse@~ 0.1.11":
+  version "0.1.16"
+  resolved "https://registry.yarnpkg.com/argparse/-/argparse-0.1.16.tgz#cfd01e0fbba3d6caed049fbd758d40f65196f57c"
+  dependencies:
+    underscore "~1.7.0"
+    underscore.string "~2.4.0"
+
+arr-diff@^2.0.0:
+  version "2.0.0"
+  resolved "https://registry.yarnpkg.com/arr-diff/-/arr-diff-2.0.0.tgz#8f3b827f955a8bd669697e4a4256ac3ceae356cf"
+  dependencies:
+    arr-flatten "^1.0.1"
+
+arr-flatten@^1.0.1:
+  version "1.1.0"
+  resolved "https://registry.yarnpkg.com/arr-flatten/-/arr-flatten-1.1.0.tgz#36048bbff4e7b47e136644316c99669ea5ae91f1"
+
+array-find-index@^1.0.1:
+  version "1.0.2"
+  resolved "https://registry.yarnpkg.com/array-find-index/-/array-find-index-1.0.2.tgz#df010aa1287e164bbda6f9723b0a96a1ec4187a1"
+
+array-flatten@1.1.1:
+  version "1.1.1"
+  resolved "https://registry.yarnpkg.com/array-flatten/-/array-flatten-1.1.1.tgz#9a5f699051b1e7073328f2a008968b64ea2955d2"
+
+array-slice@^0.2.3:
+  version "0.2.3"
+  resolved "https://registry.yarnpkg.com/array-slice/-/array-slice-0.2.3.tgz#dd3cfb80ed7973a75117cdac69b0b99ec86186f5"
+
+array-union@^1.0.1:
+  version "1.0.2"
+  resolved "https://registry.yarnpkg.com/array-union/-/array-union-1.0.2.tgz#9a34410e4f4e3da23dea375be5be70f24778ec39"
+  dependencies:
+    array-uniq "^1.0.1"
+
+array-uniq@^1.0.1:
+  version "1.0.3"
+  resolved "https://registry.yarnpkg.com/array-uniq/-/array-uniq-1.0.3.tgz#af6ac877a25cc7f74e058894753858dfdb24fdb6"
+
+array-unique@^0.2.1:
+  version "0.2.1"
+  resolved "https://registry.yarnpkg.com/array-unique/-/array-unique-0.2.1.tgz#a1d97ccafcbc2625cc70fadceb36a50c58b01a53"
+
+arraybuffer.slice@0.0.6:
+  version "0.0.6"
+  resolved "https://registry.yarnpkg.com/arraybuffer.slice/-/arraybuffer.slice-0.0.6.tgz#f33b2159f0532a3f3107a272c0ccfbd1ad2979ca"
+
+arrify@^1.0.0, arrify@^1.0.1:
+  version "1.0.1"
+  resolved "https://registry.yarnpkg.com/arrify/-/arrify-1.0.1.tgz#898508da2226f380df904728456849c1501a4b0d"
+
+asn1@0.1.11:
+  version "0.1.11"
+  resolved "https://registry.yarnpkg.com/asn1/-/asn1-0.1.11.tgz#559be18376d08a4ec4dbe80877d27818639b2df7"
+
+asn1@~0.2.3:
+  version "0.2.3"
+  resolved "https://registry.yarnpkg.com/asn1/-/asn1-0.2.3.tgz#dac8787713c9966849fc8180777ebe9c1ddf3b86"
+
+assert-plus@1.0.0, assert-plus@^1.0.0:
+  version "1.0.0"
+  resolved "https://registry.yarnpkg.com/assert-plus/-/assert-plus-1.0.0.tgz#f12e0f3c5d77b0b1cdd9146942e4e96c1e4dd525"
+
+assert-plus@^0.1.5:
+  version "0.1.5"
+  resolved "https://registry.yarnpkg.com/assert-plus/-/assert-plus-0.1.5.tgz#ee74009413002d84cec7219c6ac811812e723160"
+
+assert-plus@^0.2.0:
+  version "0.2.0"
+  resolved "https://registry.yarnpkg.com/assert-plus/-/assert-plus-0.2.0.tgz#d74e1b87e7affc0db8aadb7021f3fe48101ab234"
+
+assert@^1.1.1:
+  version "1.4.1"
+  resolved "https://registry.yarnpkg.com/assert/-/assert-1.4.1.tgz#99912d591836b5a6f5b345c0f07eefc08fc65d91"
+  dependencies:
+    util "0.10.3"
+
+assertion-error@^1.0.1:
+  version "1.1.0"
+  resolved "https://registry.yarnpkg.com/assertion-error/-/assertion-error-1.1.0.tgz#e60b6b0e8f301bd97e5375215bda406c85118c0b"
+
+async-each@^1.0.0:
+  version "1.0.1"
+  resolved "https://registry.yarnpkg.com/async-each/-/async-each-1.0.1.tgz#19d386a1d9edc6e7c1c85d388aedbcc56d33602d"
+
+async@0.1.x, async@~0.1.18, async@~0.1.22:
+  version "0.1.22"
+  resolved "https://registry.yarnpkg.com/async/-/async-0.1.22.tgz#0fc1aaa088a0e3ef0ebe2d8831bab0dcf8845061"
+
+async@1.4.0:
+  version "1.4.0"
+  resolved "https://registry.yarnpkg.com/async/-/async-1.4.0.tgz#35f86f83c59e0421d099cd9a91d8278fb578c00d"
+
+async@1.x, async@^1.3.0, async@^1.4.0, async@^1.4.2, async@^1.5.0, async@^1.5.2:
+  version "1.5.2"
+  resolved "https://registry.yarnpkg.com/async/-/async-1.5.2.tgz#ec6a61ae56480c0c3cb241c95618e20892f9672a"
+
+async@^0.9.0, async@~0.9.0:
+  version "0.9.2"
+  resolved "https://registry.yarnpkg.com/async/-/async-0.9.2.tgz#aea74d5e61c1f899613bf64bda66d4c78f2fd17d"
+
+async@~0.2.6:
+  version "0.2.10"
+  resolved "https://registry.yarnpkg.com/async/-/async-0.2.10.tgz#b6bbe0b0674b9d719708ca38de8c237cb526c3d1"
+
+async@~1.0.0:
+  version "1.0.0"
+  resolved "https://registry.yarnpkg.com/async/-/async-1.0.0.tgz#f8fc04ca3a13784ade9e1641af98578cfbd647a9"
+
+asynckit@^0.4.0:
+  version "0.4.0"
+  resolved "https://registry.yarnpkg.com/asynckit/-/asynckit-0.4.0.tgz#c79ed97f7f34cb8f2ba1bc9790bcc366474b4b79"
+
+aws-sign2@~0.5.0:
+  version "0.5.0"
+  resolved "https://registry.yarnpkg.com/aws-sign2/-/aws-sign2-0.5.0.tgz#c57103f7a17fc037f02d7c2e64b602ea223f7d63"
+
+aws-sign2@~0.6.0:
+  version "0.6.0"
+  resolved "https://registry.yarnpkg.com/aws-sign2/-/aws-sign2-0.6.0.tgz#14342dd38dbcc94d0e5b87d763cd63612c0e794f"
+
+aws-sign2@~0.7.0:
+  version "0.7.0"
+  resolved "https://registry.yarnpkg.com/aws-sign2/-/aws-sign2-0.7.0.tgz#b46e890934a9591f2d2f6f86d7e6a9f1b3fe76a8"
+
+aws4@^1.2.1, aws4@^1.6.0:
+  version "1.6.0"
+  resolved "https://registry.yarnpkg.com/aws4/-/aws4-1.6.0.tgz#83ef5ca860b2b32e4a0deedee8c771b9db57471e"
+
+babel-code-frame@^6.26.0:
+  version "6.26.0"
+  resolved "https://registry.yarnpkg.com/babel-code-frame/-/babel-code-frame-6.26.0.tgz#63fd43f7dc1e3bb7ce35947db8fe369a3f58c74b"
+  dependencies:
+    chalk "^1.1.3"
+    esutils "^2.0.2"
+    js-tokens "^3.0.2"
+
+babel-core@^6.0.0, babel-core@^6.0.12, babel-core@^6.26.0, babel-core@^6.6.5:
+  version "6.26.0"
+  resolved "https://registry.yarnpkg.com/babel-core/-/babel-core-6.26.0.tgz#af32f78b31a6fcef119c87b0fd8d9753f03a0bb8"
+  dependencies:
+    babel-code-frame "^6.26.0"
+    babel-generator "^6.26.0"
+    babel-helpers "^6.24.1"
+    babel-messages "^6.23.0"
+    babel-register "^6.26.0"
+    babel-runtime "^6.26.0"
+    babel-template "^6.26.0"
+    babel-traverse "^6.26.0"
+    babel-types "^6.26.0"
+    babylon "^6.18.0"
+    convert-source-map "^1.5.0"
+    debug "^2.6.8"
+    json5 "^0.5.1"
+    lodash "^4.17.4"
+    minimatch "^3.0.4"
+    path-is-absolute "^1.0.1"
+    private "^0.1.7"
+    slash "^1.0.0"
+    source-map "^0.5.6"
+
+babel-generator@^6.18.0, babel-generator@^6.26.0:
+  version "6.26.1"
+  resolved "https://registry.yarnpkg.com/babel-generator/-/babel-generator-6.26.1.tgz#1844408d3b8f0d35a404ea7ac180f087a601bd90"
+  dependencies:
+    babel-messages "^6.23.0"
+    babel-runtime "^6.26.0"
+    babel-types "^6.26.0"
+    detect-indent "^4.0.0"
+    jsesc "^1.3.0"
+    lodash "^4.17.4"
+    source-map "^0.5.7"
+    trim-right "^1.0.1"
+
+babel-helper-call-delegate@^6.24.1:
+  version "6.24.1"
+  resolved "https://registry.yarnpkg.com/babel-helper-call-delegate/-/babel-helper-call-delegate-6.24.1.tgz#ece6aacddc76e41c3461f88bfc575bd0daa2df8d"
+  dependencies:
+    babel-helper-hoist-variables "^6.24.1"
+    babel-runtime "^6.22.0"
+    babel-traverse "^6.24.1"
+    babel-types "^6.24.1"
+
+babel-helper-define-map@^6.24.1:
+  version "6.26.0"
+  resolved "https://registry.yarnpkg.com/babel-helper-define-map/-/babel-helper-define-map-6.26.0.tgz#a5f56dab41a25f97ecb498c7ebaca9819f95be5f"
+  dependencies:
+    babel-helper-function-name "^6.24.1"
+    babel-runtime "^6.26.0"
+    babel-types "^6.26.0"
+    lodash "^4.17.4"
+
+babel-helper-function-name@^6.24.1:
+  version "6.24.1"
+  resolved "https://registry.yarnpkg.com/babel-helper-function-name/-/babel-helper-function-name-6.24.1.tgz#d3475b8c03ed98242a25b48351ab18399d3580a9"
+  dependencies:
+    babel-helper-get-function-arity "^6.24.1"
+    babel-runtime "^6.22.0"
+    babel-template "^6.24.1"
+    babel-traverse "^6.24.1"
+    babel-types "^6.24.1"
+
+babel-helper-get-function-arity@^6.24.1:
+  version "6.24.1"
+  resolved "https://registry.yarnpkg.com/babel-helper-get-function-arity/-/babel-helper-get-function-arity-6.24.1.tgz#8f7782aa93407c41d3aa50908f89b031b1b6853d"
+  dependencies:
+    babel-runtime "^6.22.0"
+    babel-types "^6.24.1"
+
+babel-helper-hoist-variables@^6.24.1:
+  version "6.24.1"
+  resolved "https://registry.yarnpkg.com/babel-helper-hoist-variables/-/babel-helper-hoist-variables-6.24.1.tgz#1ecb27689c9d25513eadbc9914a73f5408be7a76"
+  dependencies:
+    babel-runtime "^6.22.0"
+    babel-types "^6.24.1"
+
+babel-helper-optimise-call-expression@^6.24.1:
+  version "6.24.1"
+  resolved "https://registry.yarnpkg.com/babel-helper-optimise-call-expression/-/babel-helper-optimise-call-expression-6.24.1.tgz#f7a13427ba9f73f8f4fa993c54a97882d1244257"
+  dependencies:
+    babel-runtime "^6.22.0"
+    babel-types "^6.24.1"
+
+babel-helper-regex@^6.24.1:
+  version "6.26.0"
+  resolved "https://registry.yarnpkg.com/babel-helper-regex/-/babel-helper-regex-6.26.0.tgz#325c59f902f82f24b74faceed0363954f6495e72"
+  dependencies:
+    babel-runtime "^6.26.0"
+    babel-types "^6.26.0"
+    lodash "^4.17.4"
+
+babel-helper-replace-supers@^6.24.1:
+  version "6.24.1"
+  resolved "https://registry.yarnpkg.com/babel-helper-replace-supers/-/babel-helper-replace-supers-6.24.1.tgz#bf6dbfe43938d17369a213ca8a8bf74b6a90ab1a"
+  dependencies:
+    babel-helper-optimise-call-expression "^6.24.1"
+    babel-messages "^6.23.0"
+    babel-runtime "^6.22.0"
+    babel-template "^6.24.1"
+    babel-traverse "^6.24.1"
+    babel-types "^6.24.1"
+
+babel-helpers@^6.24.1:
+  version "6.24.1"
+  resolved "https://registry.yarnpkg.com/babel-helpers/-/babel-helpers-6.24.1.tgz#3471de9caec388e5c850e597e58a26ddf37602b2"
+  dependencies:
+    babel-runtime "^6.22.0"
+    babel-template "^6.24.1"
+
+babel-loader@^6.0.0:
+  version "6.4.1"
+  resolved "https://registry.yarnpkg.com/babel-loader/-/babel-loader-6.4.1.tgz#0b34112d5b0748a8dcdbf51acf6f9bd42d50b8ca"
+  dependencies:
+    find-cache-dir "^0.1.1"
+    loader-utils "^0.2.16"
+    mkdirp "^0.5.1"
+    object-assign "^4.0.1"
+
+babel-messages@^6.23.0:
+  version "6.23.0"
+  resolved "https://registry.yarnpkg.com/babel-messages/-/babel-messages-6.23.0.tgz#f3cdf4703858035b2a2951c6ec5edf6c62f2630e"
+  dependencies:
+    babel-runtime "^6.22.0"
+
+babel-plugin-check-es2015-constants@^6.3.13:
+  version "6.22.0"
+  resolved "https://registry.yarnpkg.com/babel-plugin-check-es2015-constants/-/babel-plugin-check-es2015-constants-6.22.0.tgz#35157b101426fd2ffd3da3f75c7d1e91835bbf8a"
+  dependencies:
+    babel-runtime "^6.22.0"
+
+babel-plugin-syntax-async-functions@^6.3.13:
+  version "6.13.0"
+  resolved "https://registry.yarnpkg.com/babel-plugin-syntax-async-functions/-/babel-plugin-syntax-async-functions-6.13.0.tgz#cad9cad1191b5ad634bf30ae0872391e0647be95"
+
+babel-plugin-transform-es2015-arrow-functions@^6.3.13:
+  version "6.22.0"
+  resolved "https://registry.yarnpkg.com/babel-plugin-transform-es2015-arrow-functions/-/babel-plugin-transform-es2015-arrow-functions-6.22.0.tgz#452692cb711d5f79dc7f85e440ce41b9f244d221"
+  dependencies:
+    babel-runtime "^6.22.0"
+
+babel-plugin-transform-es2015-block-scoped-functions@^6.3.13:
+  version "6.22.0"
+  resolved "https://registry.yarnpkg.com/babel-plugin-transform-es2015-block-scoped-functions/-/babel-plugin-transform-es2015-block-scoped-functions-6.22.0.tgz#bbc51b49f964d70cb8d8e0b94e820246ce3a6141"
+  dependencies:
+    babel-runtime "^6.22.0"
+
+babel-plugin-transform-es2015-block-scoping@^6.6.0, babel-plugin-transform-es2015-block-scoping@^6.6.5:
+  version "6.26.0"
+  resolved "https://registry.yarnpkg.com/babel-plugin-transform-es2015-block-scoping/-/babel-plugin-transform-es2015-block-scoping-6.26.0.tgz#d70f5299c1308d05c12f463813b0a09e73b1895f"
+  dependencies:
+    babel-runtime "^6.26.0"
+    babel-template "^6.26.0"
+    babel-traverse "^6.26.0"
+    babel-types "^6.26.0"
+    lodash "^4.17.4"
+
+babel-plugin-transform-es2015-classes@^6.6.0:
+  version "6.24.1"
+  resolved "https://registry.yarnpkg.com/babel-plugin-transform-es2015-classes/-/babel-plugin-transform-es2015-classes-6.24.1.tgz#5a4c58a50c9c9461e564b4b2a3bfabc97a2584db"
+  dependencies:
+    babel-helper-define-map "^6.24.1"
+    babel-helper-function-name "^6.24.1"
+    babel-helper-optimise-call-expression "^6.24.1"
+    babel-helper-replace-supers "^6.24.1"
+    babel-messages "^6.23.0"
+    babel-runtime "^6.22.0"
+    babel-template "^6.24.1"
+    babel-traverse "^6.24.1"
+    babel-types "^6.24.1"
+
+babel-plugin-transform-es2015-computed-properties@^6.3.13:
+  version "6.24.1"
+  resolved "https://registry.yarnpkg.com/babel-plugin-transform-es2015-computed-properties/-/babel-plugin-transform-es2015-computed-properties-6.24.1.tgz#6fe2a8d16895d5634f4cd999b6d3480a308159b3"
+  dependencies:
+    babel-runtime "^6.22.0"
+    babel-template "^6.24.1"
+
+babel-plugin-transform-es2015-destructuring@^6.6.0:
+  version "6.23.0"
+  resolved "https://registry.yarnpkg.com/babel-plugin-transform-es2015-destructuring/-/babel-plugin-transform-es2015-destructuring-6.23.0.tgz#997bb1f1ab967f682d2b0876fe358d60e765c56d"
+  dependencies:
+    babel-runtime "^6.22.0"
+
+babel-plugin-transform-es2015-duplicate-keys@^6.6.0:
+  version "6.24.1"
+  resolved "https://registry.yarnpkg.com/babel-plugin-transform-es2015-duplicate-keys/-/babel-plugin-transform-es2015-duplicate-keys-6.24.1.tgz#73eb3d310ca969e3ef9ec91c53741a6f1576423e"
+  dependencies:
+    babel-runtime "^6.22.0"
+    babel-types "^6.24.1"
+
+babel-plugin-transform-es2015-for-of@^6.6.0:
+  version "6.23.0"
+  resolved "https://registry.yarnpkg.com/babel-plugin-transform-es2015-for-of/-/babel-plugin-transform-es2015-for-of-6.23.0.tgz#f47c95b2b613df1d3ecc2fdb7573623c75248691"
+  dependencies:
+    babel-runtime "^6.22.0"
+
+babel-plugin-transform-es2015-function-name@^6.3.13:
+  version "6.24.1"
+  resolved "https://registry.yarnpkg.com/babel-plugin-transform-es2015-function-name/-/babel-plugin-transform-es2015-function-name-6.24.1.tgz#834c89853bc36b1af0f3a4c5dbaa94fd8eacaa8b"
+  dependencies:
+    babel-helper-function-name "^6.24.1"
+    babel-runtime "^6.22.0"
+    babel-types "^6.24.1"
+
+babel-plugin-transform-es2015-literals@^6.3.13:
+  version "6.22.0"
+  resolved "https://registry.yarnpkg.com/babel-plugin-transform-es2015-literals/-/babel-plugin-transform-es2015-literals-6.22.0.tgz#4f54a02d6cd66cf915280019a31d31925377ca2e"
+  dependencies:
+    babel-runtime "^6.22.0"
+
+babel-plugin-transform-es2015-modules-commonjs@6.7.7:
+  version "6.7.7"
+  resolved "https://registry.yarnpkg.com/babel-plugin-transform-es2015-modules-commonjs/-/babel-plugin-transform-es2015-modules-commonjs-6.7.7.tgz#fa5ca2016617c4d712123d8cfc15787fcaa83f33"
+  dependencies:
+    babel-plugin-transform-strict-mode "^6.6.5"
+    babel-runtime "^5.0.0"
+    babel-template "^6.7.0"
+    babel-types "^6.7.7"
+
+babel-plugin-transform-es2015-modules-commonjs@^6.6.0:
+  version "6.26.0"
+  resolved "https://registry.yarnpkg.com/babel-plugin-transform-es2015-modules-commonjs/-/babel-plugin-transform-es2015-modules-commonjs-6.26.0.tgz#0d8394029b7dc6abe1a97ef181e00758dd2e5d8a"
+  dependencies:
+    babel-plugin-transform-strict-mode "^6.24.1"
+    babel-runtime "^6.26.0"
+    babel-template "^6.26.0"
+    babel-types "^6.26.0"
+
+babel-plugin-transform-es2015-object-super@^6.3.13:
+  version "6.24.1"
+  resolved "https://registry.yarnpkg.com/babel-plugin-transform-es2015-object-super/-/babel-plugin-transform-es2015-object-super-6.24.1.tgz#24cef69ae21cb83a7f8603dad021f572eb278f8d"
+  dependencies:
+    babel-helper-replace-supers "^6.24.1"
+    babel-runtime "^6.22.0"
+
+babel-plugin-transform-es2015-parameters@^6.6.0:
+  version "6.24.1"
+  resolved "https://registry.yarnpkg.com/babel-plugin-transform-es2015-parameters/-/babel-plugin-transform-es2015-parameters-6.24.1.tgz#57ac351ab49caf14a97cd13b09f66fdf0a625f2b"
+  dependencies:
+    babel-helper-call-delegate "^6.24.1"
+    babel-helper-get-function-arity "^6.24.1"
+    babel-runtime "^6.22.0"
+    babel-template "^6.24.1"
+    babel-traverse "^6.24.1"
+    babel-types "^6.24.1"
+
+babel-plugin-transform-es2015-shorthand-properties@^6.3.13:
+  version "6.24.1"
+  resolved "https://registry.yarnpkg.com/babel-plugin-transform-es2015-shorthand-properties/-/babel-plugin-transform-es2015-shorthand-properties-6.24.1.tgz#24f875d6721c87661bbd99a4622e51f14de38aa0"
+  dependencies:
+    babel-runtime "^6.22.0"
+    babel-types "^6.24.1"
+
+babel-plugin-transform-es2015-spread@^6.3.13:
+  version "6.22.0"
+  resolved "https://registry.yarnpkg.com/babel-plugin-transform-es2015-spread/-/babel-plugin-transform-es2015-spread-6.22.0.tgz#d6d68a99f89aedc4536c81a542e8dd9f1746f8d1"
+  dependencies:
+    babel-runtime "^6.22.0"
+
+babel-plugin-transform-es2015-sticky-regex@^6.3.13:
+  version "6.24.1"
+  resolved "https://registry.yarnpkg.com/babel-plugin-transform-es2015-sticky-regex/-/babel-plugin-transform-es2015-sticky-regex-6.24.1.tgz#00c1cdb1aca71112cdf0cf6126c2ed6b457ccdbc"
+  dependencies:
+    babel-helper-regex "^6.24.1"
+    babel-runtime "^6.22.0"
+    babel-types "^6.24.1"
+
+babel-plugin-transform-es2015-template-literals@^6.6.0:
+  version "6.22.0"
+  resolved "https://registry.yarnpkg.com/babel-plugin-transform-es2015-template-literals/-/babel-plugin-transform-es2015-template-literals-6.22.0.tgz#a84b3450f7e9f8f1f6839d6d687da84bb1236d8d"
+  dependencies:
+    babel-runtime "^6.22.0"
+
+babel-plugin-transform-es2015-typeof-symbol@^6.6.0:
+  version "6.23.0"
+  resolved "https://registry.yarnpkg.com/babel-plugin-transform-es2015-typeof-symbol/-/babel-plugin-transform-es2015-typeof-symbol-6.23.0.tgz#dec09f1cddff94b52ac73d505c84df59dcceb372"
+  dependencies:
+    babel-runtime "^6.22.0"
+
+babel-plugin-transform-es2015-unicode-regex@^6.3.13:
+  version "6.24.1"
+  resolved "https://registry.yarnpkg.com/babel-plugin-transform-es2015-unicode-regex/-/babel-plugin-transform-es2015-unicode-regex-6.24.1.tgz#d38b12f42ea7323f729387f18a7c5ae1faeb35e9"
+  dependencies:
+    babel-helper-regex "^6.24.1"
+    babel-runtime "^6.22.0"
+    regexpu-core "^2.0.0"
+
+babel-plugin-transform-es3-member-expression-literals@^6.8.0:
+  version "6.22.0"
+  resolved "https://registry.yarnpkg.com/babel-plugin-transform-es3-member-expression-literals/-/babel-plugin-transform-es3-member-expression-literals-6.22.0.tgz#733d3444f3ecc41bef8ed1a6a4e09657b8969ebb"
+  dependencies:
+    babel-runtime "^6.22.0"
+
+babel-plugin-transform-es3-property-literals@^6.8.0:
+  version "6.22.0"
+  resolved "https://registry.yarnpkg.com/babel-plugin-transform-es3-property-literals/-/babel-plugin-transform-es3-property-literals-6.22.0.tgz#b2078d5842e22abf40f73e8cde9cd3711abd5758"
+  dependencies:
+    babel-runtime "^6.22.0"
+
+babel-plugin-transform-regenerator@6.6.5:
+  version "6.6.5"
+  resolved "https://registry.yarnpkg.com/babel-plugin-transform-regenerator/-/babel-plugin-transform-regenerator-6.6.5.tgz#079a982bd56e2235e31ee3b17ad54aeba898d4e7"
+  dependencies:
+    babel-core "^6.6.5"
+    babel-plugin-syntax-async-functions "^6.3.13"
+    babel-plugin-transform-es2015-block-scoping "^6.6.5"
+    babel-plugin-transform-es2015-for-of "^6.6.0"
+    babel-runtime "^5.0.0"
+    babel-traverse "^6.6.5"
+    babel-types "^6.6.5"
+    babylon "^6.6.5"
+    private "~0.1.5"
+
+babel-plugin-transform-regenerator@^6.6.0:
+  version "6.26.0"
+  resolved "https://registry.yarnpkg.com/babel-plugin-transform-regenerator/-/babel-plugin-transform-regenerator-6.26.0.tgz#e0703696fbde27f0a3efcacf8b4dca2f7b3a8f2f"
+  dependencies:
+    regenerator-transform "^0.10.0"
+
+babel-plugin-transform-strict-mode@^6.24.1, babel-plugin-transform-strict-mode@^6.6.5:
+  version "6.24.1"
+  resolved "https://registry.yarnpkg.com/babel-plugin-transform-strict-mode/-/babel-plugin-transform-strict-mode-6.24.1.tgz#d5faf7aa578a65bbe591cf5edae04a0c67020758"
+  dependencies:
+    babel-runtime "^6.22.0"
+    babel-types "^6.24.1"
+
+babel-preset-es2015-mod@^6.3.13:
+  version "6.6.0"
+  resolved "https://registry.yarnpkg.com/babel-preset-es2015-mod/-/babel-preset-es2015-mod-6.6.0.tgz#e105b62eb7c1001090ab86225298904cf90c1e8e"
+  dependencies:
+    babel-plugin-transform-es2015-modules-commonjs "6.7.7"
+    babel-plugin-transform-regenerator "6.6.5"
+    babel-preset-es2015 "6.6.0"
+    modify-babel-preset "2.0.2"
+
+babel-preset-es2015@6.6.0:
+  version "6.6.0"
+  resolved "https://registry.yarnpkg.com/babel-preset-es2015/-/babel-preset-es2015-6.6.0.tgz#88b33e58fec94c6ebde58dc65ece5d14e0ec2568"
+  dependencies:
+    babel-plugin-check-es2015-constants "^6.3.13"
+    babel-plugin-transform-es2015-arrow-functions "^6.3.13"
+    babel-plugin-transform-es2015-block-scoped-functions "^6.3.13"
+    babel-plugin-transform-es2015-block-scoping "^6.6.0"
+    babel-plugin-transform-es2015-classes "^6.6.0"
+    babel-plugin-transform-es2015-computed-properties "^6.3.13"
+    babel-plugin-transform-es2015-destructuring "^6.6.0"
+    babel-plugin-transform-es2015-duplicate-keys "^6.6.0"
+    babel-plugin-transform-es2015-for-of "^6.6.0"
+    babel-plugin-transform-es2015-function-name "^6.3.13"
+    babel-plugin-transform-es2015-literals "^6.3.13"
+    babel-plugin-transform-es2015-modules-commonjs "^6.6.0"
+    babel-plugin-transform-es2015-object-super "^6.3.13"
+    babel-plugin-transform-es2015-parameters "^6.6.0"
+    babel-plugin-transform-es2015-shorthand-properties "^6.3.13"
+    babel-plugin-transform-es2015-spread "^6.3.13"
+    babel-plugin-transform-es2015-sticky-regex "^6.3.13"
+    babel-plugin-transform-es2015-template-literals "^6.6.0"
+    babel-plugin-transform-es2015-typeof-symbol "^6.6.0"
+    babel-plugin-transform-es2015-unicode-regex "^6.3.13"
+    babel-plugin-transform-regenerator "^6.6.0"
+
+babel-preset-es3@^1.0.1:
+  version "1.0.1"
+  resolved "https://registry.yarnpkg.com/babel-preset-es3/-/babel-preset-es3-1.0.1.tgz#e08dd950a1670dab8b50abceaa9b93d3d9accd1e"
+  dependencies:
+    babel-plugin-transform-es3-member-expression-literals "^6.8.0"
+    babel-plugin-transform-es3-property-literals "^6.8.0"
+
+babel-register@^6.26.0:
+  version "6.26.0"
+  resolved "https://registry.yarnpkg.com/babel-register/-/babel-register-6.26.0.tgz#6ed021173e2fcb486d7acb45c6009a856f647071"
+  dependencies:
+    babel-core "^6.26.0"
+    babel-runtime "^6.26.0"
+    core-js "^2.5.0"
+    home-or-tmp "^2.0.0"
+    lodash "^4.17.4"
+    mkdirp "^0.5.1"
+    source-map-support "^0.4.15"
+
+babel-runtime@^5.0.0:
+  version "5.8.38"
+  resolved "https://registry.yarnpkg.com/babel-runtime/-/babel-runtime-5.8.38.tgz#1c0b02eb63312f5f087ff20450827b425c9d4c19"
+  dependencies:
+    core-js "^1.0.0"
+
+babel-runtime@^6.18.0, babel-runtime@^6.22.0, babel-runtime@^6.26.0:
+  version "6.26.0"
+  resolved "https://registry.yarnpkg.com/babel-runtime/-/babel-runtime-6.26.0.tgz#965c7058668e82b55d7bfe04ff2337bc8b5647fe"
+  dependencies:
+    core-js "^2.4.0"
+    regenerator-runtime "^0.11.0"
+
+babel-template@^6.16.0, babel-template@^6.24.1, babel-template@^6.26.0, babel-template@^6.7.0:
+  version "6.26.0"
+  resolved "https://registry.yarnpkg.com/babel-template/-/babel-template-6.26.0.tgz#de03e2d16396b069f46dd9fff8521fb1a0e35e02"
+  dependencies:
+    babel-runtime "^6.26.0"
+    babel-traverse "^6.26.0"
+    babel-types "^6.26.0"
+    babylon "^6.18.0"
+    lodash "^4.17.4"
+
+babel-traverse@^6.18.0, babel-traverse@^6.24.1, babel-traverse@^6.26.0, babel-traverse@^6.6.5:
+  version "6.26.0"
+  resolved "https://registry.yarnpkg.com/babel-traverse/-/babel-traverse-6.26.0.tgz#46a9cbd7edcc62c8e5c064e2d2d8d0f4035766ee"
+  dependencies:
+    babel-code-frame "^6.26.0"
+    babel-messages "^6.23.0"
+    babel-runtime "^6.26.0"
+    babel-types "^6.26.0"
+    babylon "^6.18.0"
+    debug "^2.6.8"
+    globals "^9.18.0"
+    invariant "^2.2.2"
+    lodash "^4.17.4"
+
+babel-types@^6.18.0, babel-types@^6.19.0, babel-types@^6.24.1, babel-types@^6.26.0, babel-types@^6.6.5, babel-types@^6.7.7:
+  version "6.26.0"
+  resolved "https://registry.yarnpkg.com/babel-types/-/babel-types-6.26.0.tgz#a3b073f94ab49eb6fa55cd65227a334380632497"
+  dependencies:
+    babel-runtime "^6.26.0"
+    esutils "^2.0.2"
+    lodash "^4.17.4"
+    to-fast-properties "^1.0.3"
+
+babylon@^6.18.0, babylon@^6.6.5:
+  version "6.18.0"
+  resolved "https://registry.yarnpkg.com/babylon/-/babylon-6.18.0.tgz#af2f3b88fa6f5c1e4c634d1a0f8eac4f55b395e3"
+
+backo2@1.0.2:
+  version "1.0.2"
+  resolved "https://registry.yarnpkg.com/backo2/-/backo2-1.0.2.tgz#31ab1ac8b129363463e35b3ebb69f4dfcfba7947"
+
+balanced-match@^1.0.0:
+  version "1.0.0"
+  resolved "https://registry.yarnpkg.com/balanced-match/-/balanced-match-1.0.0.tgz#89b4d199ab2bee49de164ea02b89ce462d71b767"
+
+base64-arraybuffer@0.1.5:
+  version "0.1.5"
+  resolved "https://registry.yarnpkg.com/base64-arraybuffer/-/base64-arraybuffer-0.1.5.tgz#73926771923b5a19747ad666aa5cd4bf9c6e9ce8"
+
+base64-js@^1.0.2:
+  version "1.2.3"
+  resolved "https://registry.yarnpkg.com/base64-js/-/base64-js-1.2.3.tgz#fb13668233d9614cf5fb4bce95a9ba4096cdf801"
+
+base64id@1.0.0:
+  version "1.0.0"
+  resolved "https://registry.yarnpkg.com/base64id/-/base64id-1.0.0.tgz#47688cb99bb6804f0e06d3e763b1c32e57d8e6b6"
+
+batch@0.6.1:
+  version "0.6.1"
+  resolved "https://registry.yarnpkg.com/batch/-/batch-0.6.1.tgz#dc34314f4e679318093fc760272525f94bf25c16"
+
+batch@^0.5.3:
+  version "0.5.3"
+  resolved "https://registry.yarnpkg.com/batch/-/batch-0.5.3.tgz#3f3414f380321743bfc1042f9a83ff1d5824d464"
+
+bcrypt-pbkdf@^1.0.0:
+  version "1.0.1"
+  resolved "https://registry.yarnpkg.com/bcrypt-pbkdf/-/bcrypt-pbkdf-1.0.1.tgz#63bc5dcb61331b92bc05fd528953c33462a06f8d"
+  dependencies:
+    tweetnacl "^0.14.3"
+
+better-assert@~1.0.0:
+  version "1.0.2"
+  resolved "https://registry.yarnpkg.com/better-assert/-/better-assert-1.0.2.tgz#40866b9e1b9e0b55b481894311e68faffaebc522"
+  dependencies:
+    callsite "1.0.0"
+
+big.js@^3.1.3:
+  version "3.2.0"
+  resolved "https://registry.yarnpkg.com/big.js/-/big.js-3.2.0.tgz#a5fc298b81b9e0dca2e458824784b65c52ba588e"
+
+binary-extensions@^1.0.0:
+  version "1.11.0"
+  resolved "https://registry.yarnpkg.com/binary-extensions/-/binary-extensions-1.11.0.tgz#46aa1751fb6a2f93ee5e689bb1087d4b14c6c205"
+
+bind-obj-methods@^1.0.0:
+  version "1.0.0"
+  resolved "https://registry.yarnpkg.com/bind-obj-methods/-/bind-obj-methods-1.0.0.tgz#4f5979cac15793adf70e488161e463e209ca509c"
+
+bl@^0.9.0, bl@~0.9.0:
+  version "0.9.5"
+  resolved "https://registry.yarnpkg.com/bl/-/bl-0.9.5.tgz#c06b797af085ea00bc527afc8efcf11de2232054"
+  dependencies:
+    readable-stream "~1.0.26"
+
+blob@0.0.4:
+  version "0.0.4"
+  resolved "https://registry.yarnpkg.com/blob/-/blob-0.0.4.tgz#bcf13052ca54463f30f9fc7e95b9a47630a94921"
+
+block-stream@*:
+  version "0.0.9"
+  resolved "https://registry.yarnpkg.com/block-stream/-/block-stream-0.0.9.tgz#13ebfe778a03205cfe03751481ebb4b3300c126a"
+  dependencies:
+    inherits "~2.0.0"
+
+bluebird@^2.9.27, bluebird@^2.9.30:
+  version "2.11.0"
+  resolved "https://registry.yarnpkg.com/bluebird/-/bluebird-2.11.0.tgz#534b9033c022c9579c56ba3b3e5a5caafbb650e1"
+
+bluebird@^3.5.1:
+  version "3.5.1"
+  resolved "https://registry.yarnpkg.com/bluebird/-/bluebird-3.5.1.tgz#d9551f9de98f1fcda1e683d17ee91a0602ee2eb9"
+
+body-parser@1.18.2, body-parser@^1.12.4:
+  version "1.18.2"
+  resolved "https://registry.yarnpkg.com/body-parser/-/body-parser-1.18.2.tgz#87678a19d84b47d859b83199bd59bce222b10454"
+  dependencies:
+    bytes "3.0.0"
+    content-type "~1.0.4"
+    debug "2.6.9"
+    depd "~1.1.1"
+    http-errors "~1.6.2"
+    iconv-lite "0.4.19"
+    on-finished "~2.3.0"
+    qs "6.5.1"
+    raw-body "2.3.2"
+    type-is "~1.6.15"
+
+body-parser@~1.14.0:
+  version "1.14.2"
+  resolved "https://registry.yarnpkg.com/body-parser/-/body-parser-1.14.2.tgz#1015cb1fe2c443858259581db53332f8d0cf50f9"
+  dependencies:
+    bytes "2.2.0"
+    content-type "~1.0.1"
+    debug "~2.2.0"
+    depd "~1.1.0"
+    http-errors "~1.3.1"
+    iconv-lite "0.4.13"
+    on-finished "~2.3.0"
+    qs "5.2.0"
+    raw-body "~2.1.5"
+    type-is "~1.6.10"
+
+boom@2.x.x:
+  version "2.10.1"
+  resolved "https://registry.yarnpkg.com/boom/-/boom-2.10.1.tgz#39c8918ceff5799f83f9492a848f625add0c766f"
+  dependencies:
+    hoek "2.x.x"
+
+boom@4.x.x:
+  version "4.3.1"
+  resolved "https://registry.yarnpkg.com/boom/-/boom-4.3.1.tgz#4f8a3005cb4a7e3889f749030fd25b96e01d2e31"
+  dependencies:
+    hoek "4.x.x"
+
+boom@5.x.x:
+  version "5.2.0"
+  resolved "https://registry.yarnpkg.com/boom/-/boom-5.2.0.tgz#5dd9da6ee3a5f302077436290cb717d3f4a54e02"
+  dependencies:
+    hoek "4.x.x"
+
+brace-expansion@^1.0.0, brace-expansion@^1.1.7:
+  version "1.1.11"
+  resolved "https://registry.yarnpkg.com/brace-expansion/-/brace-expansion-1.1.11.tgz#3c7fcbf529d87226f3d2f52b966ff5271eb441dd"
+  dependencies:
+    balanced-match "^1.0.0"
+    concat-map "0.0.1"
+
+braces@^0.1.2:
+  version "0.1.5"
+  resolved "https://registry.yarnpkg.com/braces/-/braces-0.1.5.tgz#c085711085291d8b75fdd74eab0f8597280711e6"
+  dependencies:
+    expand-range "^0.1.0"
+
+braces@^1.8.2:
+  version "1.8.5"
+  resolved "https://registry.yarnpkg.com/braces/-/braces-1.8.5.tgz#ba77962e12dff969d6b76711e914b737857bf6a7"
+  dependencies:
+    expand-range "^1.8.1"
+    preserve "^0.2.0"
+    repeat-element "^1.1.2"
+
+browserify-aes@0.4.0:
+  version "0.4.0"
+  resolved "https://registry.yarnpkg.com/browserify-aes/-/browserify-aes-0.4.0.tgz#067149b668df31c4b58533e02d01e806d8608e2c"
+  dependencies:
+    inherits "^2.0.1"
+
+browserify-zlib@^0.1.4:
+  version "0.1.4"
+  resolved "https://registry.yarnpkg.com/browserify-zlib/-/browserify-zlib-0.1.4.tgz#bb35f8a519f600e0fa6b8485241c979d0141fb2d"
+  dependencies:
+    pako "~0.2.0"
+
+buffer-crc32@~0.2.1:
+  version "0.2.13"
+  resolved "https://registry.yarnpkg.com/buffer-crc32/-/buffer-crc32-0.2.13.tgz#0d333e3f00eac50aa1454abd30ef8c2a5d9a7242"
+
+buffer@^4.9.0:
+  version "4.9.1"
+  resolved "https://registry.yarnpkg.com/buffer/-/buffer-4.9.1.tgz#6d1bb601b07a4efced97094132093027c95bc298"
+  dependencies:
+    base64-js "^1.0.2"
+    ieee754 "^1.1.4"
+    isarray "^1.0.0"
+
+builtin-modules@^1.0.0:
+  version "1.1.1"
+  resolved "https://registry.yarnpkg.com/builtin-modules/-/builtin-modules-1.1.1.tgz#270f076c5a72c02f5b65a47df94c5fe3a278892f"
+
+builtin-status-codes@^3.0.0:
+  version "3.0.0"
+  resolved "https://registry.yarnpkg.com/builtin-status-codes/-/builtin-status-codes-3.0.0.tgz#85982878e21b98e1c66425e03d0174788f569ee8"
+
+bytes@0.1.0:
+  version "0.1.0"
+  resolved "https://registry.yarnpkg.com/bytes/-/bytes-0.1.0.tgz#c574812228126d6369d1576925a8579db3f8e5a2"
+
+bytes@2.2.0:
+  version "2.2.0"
+  resolved "https://registry.yarnpkg.com/bytes/-/bytes-2.2.0.tgz#fd35464a403f6f9117c2de3609ecff9cae000588"
+
+bytes@2.4.0:
+  version "2.4.0"
+  resolved "https://registry.yarnpkg.com/bytes/-/bytes-2.4.0.tgz#7d97196f9d5baf7f6935e25985549edd2a6c2339"
+
+bytes@3.0.0:
+  version "3.0.0"
+  resolved "https://registry.yarnpkg.com/bytes/-/bytes-3.0.0.tgz#d32815404d689699f85a4ea4fa8755dd13a96048"
+
+caching-transform@^1.0.0:
+  version "1.0.1"
+  resolved "https://registry.yarnpkg.com/caching-transform/-/caching-transform-1.0.1.tgz#6dbdb2f20f8d8fbce79f3e94e9d1742dcdf5c0a1"
+  dependencies:
+    md5-hex "^1.2.0"
+    mkdirp "^0.5.1"
+    write-file-atomic "^1.1.4"
+
+callsite@1.0.0:
+  version "1.0.0"
+  resolved "https://registry.yarnpkg.com/callsite/-/callsite-1.0.0.tgz#280398e5d664bd74038b6f0905153e6e8af1bc20"
+
+camelcase-keys@^2.0.0:
+  version "2.1.0"
+  resolved "https://registry.yarnpkg.com/camelcase-keys/-/camelcase-keys-2.1.0.tgz#308beeaffdf28119051efa1d932213c91b8f92e7"
+  dependencies:
+    camelcase "^2.0.0"
+    map-obj "^1.0.0"
+
+camelcase@^1.0.2:
+  version "1.2.1"
+  resolved "https://registry.yarnpkg.com/camelcase/-/camelcase-1.2.1.tgz#9bb5304d2e0b56698b2c758b08a3eaa9daa58a39"
+
+camelcase@^2.0.0:
+  version "2.1.1"
+  resolved "https://registry.yarnpkg.com/camelcase/-/camelcase-2.1.1.tgz#7c1d16d679a1bbe59ca02cacecfb011e201f5a1f"
+
+camelcase@^4.1.0:
+  version "4.1.0"
+  resolved "https://registry.yarnpkg.com/camelcase/-/camelcase-4.1.0.tgz#d545635be1e33c542649c69173e5de6acfae34dd"
+
+caseless@~0.11.0:
+  version "0.11.0"
+  resolved "https://registry.yarnpkg.com/caseless/-/caseless-0.11.0.tgz#715b96ea9841593cc33067923f5ec60ebda4f7d7"
+
+caseless@~0.12.0:
+  version "0.12.0"
+  resolved "https://registry.yarnpkg.com/caseless/-/caseless-0.12.0.tgz#1b681c21ff84033c826543090689420d187151dc"
+
+caseless@~0.9.0:
+  version "0.9.0"
+  resolved "https://registry.yarnpkg.com/caseless/-/caseless-0.9.0.tgz#b7b65ce6bf1413886539cfd533f0b30effa9cf88"
+
+center-align@^0.1.1:
+  version "0.1.3"
+  resolved "https://registry.yarnpkg.com/center-align/-/center-align-0.1.3.tgz#aa0d32629b6ee972200411cbd4461c907bc2b7ad"
+  dependencies:
+    align-text "^0.1.3"
+    lazy-cache "^1.0.3"
+
+chai@^3.3.0:
+  version "3.5.0"
+  resolved "https://registry.yarnpkg.com/chai/-/chai-3.5.0.tgz#4d02637b067fe958bdbfdd3a40ec56fef7373247"
+  dependencies:
+    assertion-error "^1.0.1"
+    deep-eql "^0.1.3"
+    type-detect "^1.0.0"
+
+chalk@^1.0.0, chalk@^1.1.1, chalk@^1.1.3:
+  version "1.1.3"
+  resolved "https://registry.yarnpkg.com/chalk/-/chalk-1.1.3.tgz#a8115c55e4a702fe4d150abd3872822a7e09fc98"
+  dependencies:
+    ansi-styles "^2.2.1"
+    escape-string-regexp "^1.0.2"
+    has-ansi "^2.0.0"
+    strip-ansi "^3.0.0"
+    supports-color "^2.0.0"
+
+chalk@^2.0.1, chalk@^2.1.0:
+  version "2.3.2"
+  resolved "https://registry.yarnpkg.com/chalk/-/chalk-2.3.2.tgz#250dc96b07491bfd601e648d66ddf5f60c7a5c65"
+  dependencies:
+    ansi-styles "^3.2.1"
+    escape-string-regexp "^1.0.5"
+    supports-color "^5.3.0"
+
+chokidar@^1.0.0, chokidar@^1.4.1:
+  version "1.7.0"
+  resolved "https://registry.yarnpkg.com/chokidar/-/chokidar-1.7.0.tgz#798e689778151c8076b4b360e5edd28cda2bb468"
+  dependencies:
+    anymatch "^1.3.0"
+    async-each "^1.0.0"
+    glob-parent "^2.0.0"
+    inherits "^2.0.1"
+    is-binary-path "^1.0.0"
+    is-glob "^2.0.0"
+    path-is-absolute "^1.0.0"
+    readdirp "^2.0.0"
+  optionalDependencies:
+    fsevents "^1.0.0"
+
+circular-json@^0.3.1:
+  version "0.3.3"
+  resolved "https://registry.yarnpkg.com/circular-json/-/circular-json-0.3.3.tgz#815c99ea84f6809529d2f45791bdf82711352d66"
+
+clean-yaml-object@^0.1.0:
+  version "0.1.0"
+  resolved "https://registry.yarnpkg.com/clean-yaml-object/-/clean-yaml-object-0.1.0.tgz#63fb110dc2ce1a84dc21f6d9334876d010ae8b68"
+
+cli-cursor@^1.0.1:
+  version "1.0.2"
+  resolved "https://registry.yarnpkg.com/cli-cursor/-/cli-cursor-1.0.2.tgz#64da3f7d56a54412e59794bd62dc35295e8f2987"
+  dependencies:
+    restore-cursor "^1.0.1"
+
+cli-width@^1.0.1:
+  version "1.1.1"
+  resolved "https://registry.yarnpkg.com/cli-width/-/cli-width-1.1.1.tgz#a4d293ef67ebb7b88d4a4d42c0ccf00c4d1e366d"
+
+cli@0.4.3:
+  version "0.4.3"
+  resolved "https://registry.yarnpkg.com/cli/-/cli-0.4.3.tgz#e6819c8d5faa957f64f98f66a8506268c1d1f17d"
+  dependencies:
+    glob ">= 3.1.4"
+
+cliui@^2.1.0:
+  version "2.1.0"
+  resolved "https://registry.yarnpkg.com/cliui/-/cliui-2.1.0.tgz#4b475760ff80264c762c3a1719032e91c7fea0d1"
+  dependencies:
+    center-align "^0.1.1"
+    right-align "^0.1.1"
+    wordwrap "0.0.2"
+
+cliui@^4.0.0:
+  version "4.0.0"
+  resolved "https://registry.yarnpkg.com/cliui/-/cliui-4.0.0.tgz#743d4650e05f36d1ed2575b59638d87322bfbbcc"
+  dependencies:
+    string-width "^2.1.1"
+    strip-ansi "^4.0.0"
+    wrap-ansi "^2.0.0"
+
+clone@^1.0.2:
+  version "1.0.3"
+  resolved "https://registry.yarnpkg.com/clone/-/clone-1.0.3.tgz#298d7e2231660f40c003c2ed3140decf3f53085f"
+
+co@^4.6.0:
+  version "4.6.0"
+  resolved "https://registry.yarnpkg.com/co/-/co-4.6.0.tgz#6ea6bdf3d853ae54ccb8e47bfa0bf3f9031fb184"
+
+code-point-at@^1.0.0:
+  version "1.1.0"
+  resolved "https://registry.yarnpkg.com/code-point-at/-/code-point-at-1.1.0.tgz#0d070b4d043a5bea33a2f1a40e2edb3d9a4ccf77"
+
+coffee-script@~1.3.3:
+  version "1.3.3"
+  resolved "https://registry.yarnpkg.com/coffee-script/-/coffee-script-1.3.3.tgz#150d6b4cb522894369efed6a2101c20bc7f4a4f4"
+
+color-convert@^1.9.0:
+  version "1.9.1"
+  resolved "https://registry.yarnpkg.com/color-convert/-/color-convert-1.9.1.tgz#c1261107aeb2f294ebffec9ed9ecad529a6097ed"
+  dependencies:
+    color-name "^1.1.1"
+
+color-name@^1.1.1:
+  version "1.1.3"
+  resolved "https://registry.yarnpkg.com/color-name/-/color-name-1.1.3.tgz#a7d0558bd89c42f795dd42328f740831ca53bc25"
+
+color-support@^1.1.0:
+  version "1.1.3"
+  resolved "https://registry.yarnpkg.com/color-support/-/color-support-1.1.3.tgz#93834379a1cc9a0c61f82f52f0d04322251bd5a2"
+
+colors@0.x.x, colors@~0.6.0, colors@~0.6.2:
+  version "0.6.2"
+  resolved "https://registry.yarnpkg.com/colors/-/colors-0.6.2.tgz#2423fe6678ac0c5dae8852e5d0e5be08c997abcc"
+
+colors@^1.1.0, colors@^1.1.2:
+  version "1.1.2"
+  resolved "https://registry.yarnpkg.com/colors/-/colors-1.1.2.tgz#168a4701756b6a7f51a12ce0c97bfa28c084ed63"
+
+combined-stream@1.0.6, combined-stream@^1.0.5, combined-stream@~1.0.5:
+  version "1.0.6"
+  resolved "https://registry.yarnpkg.com/combined-stream/-/combined-stream-1.0.6.tgz#723e7df6e801ac5613113a7e445a9b69cb632818"
+  dependencies:
+    delayed-stream "~1.0.0"
+
+combined-stream@~0.0.4, combined-stream@~0.0.5:
+  version "0.0.7"
+  resolved "https://registry.yarnpkg.com/combined-stream/-/combined-stream-0.0.7.tgz#0137e657baa5a7541c57ac37ac5fc07d73b4dc1f"
+  dependencies:
+    delayed-stream "0.0.5"
+
+commander@0.6.1:
+  version "0.6.1"
+  resolved "https://registry.yarnpkg.com/commander/-/commander-0.6.1.tgz#fa68a14f6a945d54dbbe50d8cdb3320e9e3b1a06"
+
+commander@2.3.0:
+  version "2.3.0"
+  resolved "https://registry.yarnpkg.com/commander/-/commander-2.3.0.tgz#fd430e889832ec353b9acd1de217c11cb3eef873"
+
+commander@^2.8.1, commander@^2.9.0:
+  version "2.14.1"
+  resolved "https://registry.yarnpkg.com/commander/-/commander-2.14.1.tgz#2235123e37af8ca3c65df45b026dbd357b01b9aa"
+
+commondir@^1.0.1:
+  version "1.0.1"
+  resolved "https://registry.yarnpkg.com/commondir/-/commondir-1.0.1.tgz#ddd800da0c66127393cca5950ea968a3aaf1253b"
+
+component-bind@1.0.0:
+  version "1.0.0"
+  resolved "https://registry.yarnpkg.com/component-bind/-/component-bind-1.0.0.tgz#00c608ab7dcd93897c0009651b1d3a8e1e73bbd1"
+
+component-emitter@1.1.2:
+  version "1.1.2"
+  resolved "https://registry.yarnpkg.com/component-emitter/-/component-emitter-1.1.2.tgz#296594f2753daa63996d2af08d15a95116c9aec3"
+
+component-emitter@1.2.1:
+  version "1.2.1"
+  resolved "https://registry.yarnpkg.com/component-emitter/-/component-emitter-1.2.1.tgz#137918d6d78283f7df7a6b7c5a63e140e69425e6"
+
+component-inherit@0.0.3:
+  version "0.0.3"
+  resolved "https://registry.yarnpkg.com/component-inherit/-/component-inherit-0.0.3.tgz#645fc4adf58b72b649d5cae65135619db26ff143"
+
+compress-commons@~0.2.0:
+  version "0.2.9"
+  resolved "https://registry.yarnpkg.com/compress-commons/-/compress-commons-0.2.9.tgz#422d927430c01abd06cd455b6dfc04cb4cf8003c"
+  dependencies:
+    buffer-crc32 "~0.2.1"
+    crc32-stream "~0.3.1"
+    node-int64 "~0.3.0"
+    readable-stream "~1.0.26"
+
+compressible@~2.0.13:
+  version "2.0.13"
+  resolved "https://registry.yarnpkg.com/compressible/-/compressible-2.0.13.tgz#0d1020ab924b2fdb4d6279875c7d6daba6baa7a9"
+  dependencies:
+    mime-db ">= 1.33.0 < 2"
+
+compression@^1.5.2:
+  version "1.7.2"
+  resolved "https://registry.yarnpkg.com/compression/-/compression-1.7.2.tgz#aaffbcd6aaf854b44ebb280353d5ad1651f59a69"
+  dependencies:
+    accepts "~1.3.4"
+    bytes "3.0.0"
+    compressible "~2.0.13"
+    debug "2.6.9"
+    on-headers "~1.0.1"
+    safe-buffer "5.1.1"
+    vary "~1.1.2"
+
+concat-map@0.0.1:
+  version "0.0.1"
+  resolved "https://registry.yarnpkg.com/concat-map/-/concat-map-0.0.1.tgz#d8a96bd77fd68df7793a73036a3ba0d5405d477b"
+
+concat-stream@1.6.0:
+  version "1.6.0"
+  resolved "https://registry.yarnpkg.com/concat-stream/-/concat-stream-1.6.0.tgz#0aac662fd52be78964d5532f694784e70110acf7"
+  dependencies:
+    inherits "^2.0.3"
+    readable-stream "^2.2.2"
+    typedarray "^0.0.6"
+
+concat-stream@^1.4.1, concat-stream@^1.4.6:
+  version "1.6.1"
+  resolved "https://registry.yarnpkg.com/concat-stream/-/concat-stream-1.6.1.tgz#261b8f518301f1d834e36342b9fea095d2620a26"
+  dependencies:
+    inherits "^2.0.3"
+    readable-stream "^2.2.2"
+    typedarray "^0.0.6"
+
+connect-history-api-fallback@^1.3.0:
+  version "1.5.0"
+  resolved "https://registry.yarnpkg.com/connect-history-api-fallback/-/connect-history-api-fallback-1.5.0.tgz#b06873934bc5e344fef611a196a6faae0aee015a"
+
+connect@^3.3.5:
+  version "3.6.6"
+  resolved "https://registry.yarnpkg.com/connect/-/connect-3.6.6.tgz#09eff6c55af7236e137135a72574858b6786f524"
+  dependencies:
+    debug "2.6.9"
+    finalhandler "1.1.0"
+    parseurl "~1.3.2"
+    utils-merge "1.0.1"
+
+connect@~2.4.4:
+  version "2.4.6"
+  resolved "https://registry.yarnpkg.com/connect/-/connect-2.4.6.tgz#012c2fe05018504ed2028668a16903199e6e7ace"
+  dependencies:
+    bytes "0.1.0"
+    cookie "0.0.4"
+    crc "0.2.0"
+    debug "*"
+    formidable "1.0.11"
+    fresh "0.1.0"
+    pause "0.0.1"
+    qs "0.5.1"
+    send "0.0.4"
+
+console-browserify@^1.1.0:
+  version "1.1.0"
+  resolved "https://registry.yarnpkg.com/console-browserify/-/console-browserify-1.1.0.tgz#f0241c45730a9fc6323b206dbf38edc741d0bb10"
+  dependencies:
+    date-now "^0.1.4"
+
+console-control-strings@^1.0.0, console-control-strings@~1.1.0:
+  version "1.1.0"
+  resolved "https://registry.yarnpkg.com/console-control-strings/-/console-control-strings-1.1.0.tgz#3d7cf4464db6446ea644bf4b39507f9851008e8e"
+
+constants-browserify@^1.0.0:
+  version "1.0.0"
+  resolved "https://registry.yarnpkg.com/constants-browserify/-/constants-browserify-1.0.0.tgz#c20b96d8c617748aaf1c16021760cd27fcb8cb75"
+
+content-disposition@0.5.2:
+  version "0.5.2"
+  resolved "https://registry.yarnpkg.com/content-disposition/-/content-disposition-0.5.2.tgz#0cf68bb9ddf5f2be7961c3a85178cb85dba78cb4"
+
+content-type@~1.0.1, content-type@~1.0.4:
+  version "1.0.4"
+  resolved "https://registry.yarnpkg.com/content-type/-/content-type-1.0.4.tgz#e138cc75e040c727b1966fe5e5f8c9aee256fe3b"
+
+convert-source-map@^1.1.1, convert-source-map@^1.3.0, convert-source-map@^1.5.0:
+  version "1.5.1"
+  resolved "https://registry.yarnpkg.com/convert-source-map/-/convert-source-map-1.5.1.tgz#b8278097b9bc229365de5c62cf5fcaed8b5599e5"
+
+cookie-signature@1.0.6:
+  version "1.0.6"
+  resolved "https://registry.yarnpkg.com/cookie-signature/-/cookie-signature-1.0.6.tgz#e303a882b342cc3ee8ca513a79999734dab3ae2c"
+
+cookie@0.0.4:
+  version "0.0.4"
+  resolved "https://registry.yarnpkg.com/cookie/-/cookie-0.0.4.tgz#5456bd47aee2666eac976ea80a6105940483fe98"
+
+cookie@0.3.1:
+  version "0.3.1"
+  resolved "https://registry.yarnpkg.com/cookie/-/cookie-0.3.1.tgz#e7e0a1f9ef43b4c8ba925c5c5a96e806d16873bb"
+
+core-js@^1.0.0:
+  version "1.2.7"
+  resolved "https://registry.yarnpkg.com/core-js/-/core-js-1.2.7.tgz#652294c14651db28fa93bd2d5ff2983a4f08c636"
+
+core-js@^2.1.0, core-js@^2.4.0, core-js@^2.5.0:
+  version "2.5.3"
+  resolved "https://registry.yarnpkg.com/core-js/-/core-js-2.5.3.tgz#8acc38345824f16d8365b7c9b4259168e8ed603e"
+
+core-util-is@1.0.2, core-util-is@~1.0.0:
+  version "1.0.2"
+  resolved "https://registry.yarnpkg.com/core-util-is/-/core-util-is-1.0.2.tgz#b5fd54220aa2bc5ab57aab7140c940754503c1a7"
+
+coveralls@^2.13.3:
+  version "2.13.3"
+  resolved "https://registry.yarnpkg.com/coveralls/-/coveralls-2.13.3.tgz#9ad7c2ae527417f361e8b626483f48ee92dd2bc7"
+  dependencies:
+    js-yaml "3.6.1"
+    lcov-parse "0.0.10"
+    log-driver "1.2.5"
+    minimist "1.2.0"
+    request "2.79.0"
+
+crc32-stream@~0.3.1:
+  version "0.3.4"
+  resolved "https://registry.yarnpkg.com/crc32-stream/-/crc32-stream-0.3.4.tgz#73bc25b45fac1db6632231a7bfce8927e9f06552"
+  dependencies:
+    buffer-crc32 "~0.2.1"
+    readable-stream "~1.0.24"
+
+"crc32@>= 0.2.2":
+  version "0.2.2"
+  resolved "https://registry.yarnpkg.com/crc32/-/crc32-0.2.2.tgz#7ad220d6ffdcd119f9fc127a7772cacea390a4ba"
+
+crc@0.2.0:
+  version "0.2.0"
+  resolved "https://registry.yarnpkg.com/crc/-/crc-0.2.0.tgz#f4486b9bf0a12df83c3fca14e31e030fdabd9454"
+
+cross-spawn@^4:
+  version "4.0.2"
+  resolved "https://registry.yarnpkg.com/cross-spawn/-/cross-spawn-4.0.2.tgz#7b9247621c23adfdd3856004a823cbe397424d41"
+  dependencies:
+    lru-cache "^4.0.1"
+    which "^1.2.9"
+
+cross-spawn@^5.0.1:
+  version "5.1.0"
+  resolved "https://registry.yarnpkg.com/cross-spawn/-/cross-spawn-5.1.0.tgz#e8bd0efee58fcff6f8f94510a0a554bbfa235449"
+  dependencies:
+    lru-cache "^4.0.1"
+    shebang-command "^1.2.0"
+    which "^1.2.9"
+
+cryptiles@2.x.x:
+  version "2.0.5"
+  resolved "https://registry.yarnpkg.com/cryptiles/-/cryptiles-2.0.5.tgz#3bdfecdc608147c1c67202fa291e7dca59eaa3b8"
+  dependencies:
+    boom "2.x.x"
+
+cryptiles@3.x.x:
+  version "3.1.2"
+  resolved "https://registry.yarnpkg.com/cryptiles/-/cryptiles-3.1.2.tgz#a89fbb220f5ce25ec56e8c4aa8a4fd7b5b0d29fe"
+  dependencies:
+    boom "5.x.x"
+
+crypto-browserify@3.3.0:
+  version "3.3.0"
+  resolved "https://registry.yarnpkg.com/crypto-browserify/-/crypto-browserify-3.3.0.tgz#b9fc75bb4a0ed61dcf1cd5dae96eb30c9c3e506c"
+  dependencies:
+    browserify-aes "0.4.0"
+    pbkdf2-compat "2.0.1"
+    ripemd160 "0.2.0"
+    sha.js "2.2.6"
+
+ctype@0.5.3:
+  version "0.5.3"
+  resolved "https://registry.yarnpkg.com/ctype/-/ctype-0.5.3.tgz#82c18c2461f74114ef16c135224ad0b9144ca12f"
+
+currently-unhandled@^0.4.1:
+  version "0.4.1"
+  resolved "https://registry.yarnpkg.com/currently-unhandled/-/currently-unhandled-0.4.1.tgz#988df33feab191ef799a61369dd76c17adf957ea"
+  dependencies:
+    array-find-index "^1.0.1"
+
+custom-event@~1.0.0:
+  version "1.0.1"
+  resolved "https://registry.yarnpkg.com/custom-event/-/custom-event-1.0.1.tgz#5d02a46850adf1b4a317946a3928fccb5bfd0425"
+
+d@1:
+  version "1.0.0"
+  resolved "https://registry.yarnpkg.com/d/-/d-1.0.0.tgz#754bb5bfe55451da69a58b94d45f4c5b0462d58f"
+  dependencies:
+    es5-ext "^0.10.9"
+
+dashdash@^1.12.0:
+  version "1.14.1"
+  resolved "https://registry.yarnpkg.com/dashdash/-/dashdash-1.14.1.tgz#853cfa0f7cbe2fed5de20326b8dd581035f6e2f0"
+  dependencies:
+    assert-plus "^1.0.0"
+
+date-now@^0.1.4:
+  version "0.1.4"
+  resolved "https://registry.yarnpkg.com/date-now/-/date-now-0.1.4.tgz#eaf439fd4d4848ad74e5cc7dbef200672b9e345b"
+
+dateformat@1.0.2-1.2.3:
+  version "1.0.2-1.2.3"
+  resolved "https://registry.yarnpkg.com/dateformat/-/dateformat-1.0.2-1.2.3.tgz#b0220c02de98617433b72851cf47de3df2cdbee9"
+
+debug-log@^1.0.1:
+  version "1.0.1"
+  resolved "https://registry.yarnpkg.com/debug-log/-/debug-log-1.0.1.tgz#2307632d4c04382b8df8a32f70b895046d52745f"
+
+debug@*, debug@^3.1.0:
+  version "3.1.0"
+  resolved "https://registry.yarnpkg.com/debug/-/debug-3.1.0.tgz#5bb5a0672628b64149566ba16819e61518c67261"
+  dependencies:
+    ms "2.0.0"
+
+debug@2, debug@2.6.9, debug@^2.1.1, debug@^2.1.3, debug@^2.2.0, debug@^2.6.6, debug@^2.6.8:
+  version "2.6.9"
+  resolved "https://registry.yarnpkg.com/debug/-/debug-2.6.9.tgz#5d128515df134ff327e90a4c93f4e077a536341f"
+  dependencies:
+    ms "2.0.0"
+
+debug@2.2.0, debug@~2.2.0:
+  version "2.2.0"
+  resolved "https://registry.yarnpkg.com/debug/-/debug-2.2.0.tgz#f87057e995b1a1f6ae6a4960664137bc56f039da"
+  dependencies:
+    ms "0.7.1"
+
+debug@2.3.3:
+  version "2.3.3"
+  resolved "https://registry.yarnpkg.com/debug/-/debug-2.3.3.tgz#40c453e67e6e13c901ddec317af8986cda9eff8c"
+  dependencies:
+    ms "0.7.2"
+
+decamelize@^1.0.0, decamelize@^1.1.1, decamelize@^1.1.2:
+  version "1.2.0"
+  resolved "https://registry.yarnpkg.com/decamelize/-/decamelize-1.2.0.tgz#f6534d15148269b20352e7bee26f501f9a191290"
+
+deep-eql@^0.1.3:
+  version "0.1.3"
+  resolved "https://registry.yarnpkg.com/deep-eql/-/deep-eql-0.1.3.tgz#ef558acab8de25206cd713906d74e56930eb69f2"
+  dependencies:
+    type-detect "0.1.1"
+
+deep-extend@~0.4.0:
+  version "0.4.2"
+  resolved "https://registry.yarnpkg.com/deep-extend/-/deep-extend-0.4.2.tgz#48b699c27e334bf89f10892be432f6e4c7d34a7f"
+
+deep-is@~0.1.2, deep-is@~0.1.3:
+  version "0.1.3"
+  resolved "https://registry.yarnpkg.com/deep-is/-/deep-is-0.1.3.tgz#b369d6fb5dbc13eecf524f91b070feedc357cf34"
+
+default-require-extensions@^1.0.0:
+  version "1.0.0"
+  resolved "https://registry.yarnpkg.com/default-require-extensions/-/default-require-extensions-1.0.0.tgz#f37ea15d3e13ffd9b437d33e1a75b5fb97874cb8"
+  dependencies:
+    strip-bom "^2.0.0"
+
+"deflate-js@>= 0.2.2":
+  version "0.2.3"
+  resolved "https://registry.yarnpkg.com/deflate-js/-/deflate-js-0.2.3.tgz#f85abb58ebc5151a306147473d57c3e4f7e4426b"
+
+del@^2.0.2:
+  version "2.2.2"
+  resolved "https://registry.yarnpkg.com/del/-/del-2.2.2.tgz#c12c981d067846c84bcaf862cff930d907ffd1a8"
+  dependencies:
+    globby "^5.0.0"
+    is-path-cwd "^1.0.0"
+    is-path-in-cwd "^1.0.0"
+    object-assign "^4.0.1"
+    pify "^2.0.0"
+    pinkie-promise "^2.0.0"
+    rimraf "^2.2.8"
+
+delayed-stream@0.0.5:
+  version "0.0.5"
+  resolved "https://registry.yarnpkg.com/delayed-stream/-/delayed-stream-0.0.5.tgz#d4b1f43a93e8296dfe02694f4680bc37a313c73f"
+
+delayed-stream@~1.0.0:
+  version "1.0.0"
+  resolved "https://registry.yarnpkg.com/delayed-stream/-/delayed-stream-1.0.0.tgz#df3ae199acadfb7d440aaae0b29e2272b24ec619"
+
+delegates@^1.0.0:
+  version "1.0.0"
+  resolved "https://registry.yarnpkg.com/delegates/-/delegates-1.0.0.tgz#84c6e159b81904fdca59a0ef44cd870d31250f9a"
+
+depd@1.1.1:
+  version "1.1.1"
+  resolved "https://registry.yarnpkg.com/depd/-/depd-1.1.1.tgz#5783b4e1c459f06fa5ca27f991f3d06e7a310359"
+
+depd@~1.1.0, depd@~1.1.1:
+  version "1.1.2"
+  resolved "https://registry.yarnpkg.com/depd/-/depd-1.1.2.tgz#9bcd52e14c097763e749b274c4346ed2e560b5a9"
+
+destroy@~1.0.4:
+  version "1.0.4"
+  resolved "https://registry.yarnpkg.com/destroy/-/destroy-1.0.4.tgz#978857442c44749e4206613e37946205826abd80"
+
+detect-indent@^4.0.0:
+  version "4.0.0"
+  resolved "https://registry.yarnpkg.com/detect-indent/-/detect-indent-4.0.0.tgz#f76d064352cdf43a1cb6ce619c4ee3a9475de208"
+  dependencies:
+    repeating "^2.0.0"
+
+detect-libc@^1.0.2:
+  version "1.0.3"
+  resolved "https://registry.yarnpkg.com/detect-libc/-/detect-libc-1.0.3.tgz#fa137c4bd698edf55cd5cd02ac559f91a4c4ba9b"
+
+di@^0.0.1:
+  version "0.0.1"
+  resolved "https://registry.yarnpkg.com/di/-/di-0.0.1.tgz#806649326ceaa7caa3306d75d985ea2748ba913c"
+
+diff@1.4.0, diff@^1.3.2:
+  version "1.4.0"
+  resolved "https://registry.yarnpkg.com/diff/-/diff-1.4.0.tgz#7f28d2eb9ee7b15a97efd89ce63dcfdaa3ccbabf"
+
+doctrine@^0.7.1:
+  version "0.7.2"
+  resolved "https://registry.yarnpkg.com/doctrine/-/doctrine-0.7.2.tgz#7cb860359ba3be90e040b26b729ce4bfa654c523"
+  dependencies:
+    esutils "^1.1.6"
+    isarray "0.0.1"
+
+dom-serialize@^2.2.0:
+  version "2.2.1"
+  resolved "https://registry.yarnpkg.com/dom-serialize/-/dom-serialize-2.2.1.tgz#562ae8999f44be5ea3076f5419dcd59eb43ac95b"
+  dependencies:
+    custom-event "~1.0.0"
+    ent "~2.2.0"
+    extend "^3.0.0"
+    void-elements "^2.0.0"
+
+domain-browser@^1.1.1:
+  version "1.2.0"
+  resolved "https://registry.yarnpkg.com/domain-browser/-/domain-browser-1.2.0.tgz#3d31f50191a6749dd1375a7f522e823d42e54eda"
+
+ecc-jsbn@~0.1.1:
+  version "0.1.1"
+  resolved "https://registry.yarnpkg.com/ecc-jsbn/-/ecc-jsbn-0.1.1.tgz#0fc73a9ed5f0d53c38193398523ef7e543777505"
+  dependencies:
+    jsbn "~0.1.0"
+
+ee-first@1.1.1:
+  version "1.1.1"
+  resolved "https://registry.yarnpkg.com/ee-first/-/ee-first-1.1.1.tgz#590c61156b0ae2f4f0255732a158b266bc56b21d"
+
+emojis-list@^2.0.0:
+  version "2.1.0"
+  resolved "https://registry.yarnpkg.com/emojis-list/-/emojis-list-2.1.0.tgz#4daa4d9db00f9819880c79fa457ae5b09a1fd389"
+
+encodeurl@~1.0.1:
+  version "1.0.2"
+  resolved "https://registry.yarnpkg.com/encodeurl/-/encodeurl-1.0.2.tgz#ad3ff4c86ec2d029322f5a02c3a9a606c95b3f59"
+
+end-of-stream@^1.0.0:
+  version "1.4.1"
+  resolved "https://registry.yarnpkg.com/end-of-stream/-/end-of-stream-1.4.1.tgz#ed29634d19baba463b6ce6b80a37213eab71ec43"
+  dependencies:
+    once "^1.4.0"
+
+engine.io-client@~1.8.4:
+  version "1.8.5"
+  resolved "https://registry.yarnpkg.com/engine.io-client/-/engine.io-client-1.8.5.tgz#fe7fb60cb0dcf2fa2859489329cb5968dedeb11f"
+  dependencies:
+    component-emitter "1.2.1"
+    component-inherit "0.0.3"
+    debug "2.3.3"
+    engine.io-parser "1.3.2"
+    has-cors "1.1.0"
+    indexof "0.0.1"
+    parsejson "0.0.3"
+    parseqs "0.0.5"
+    parseuri "0.0.5"
+    ws "~1.1.5"
+    xmlhttprequest-ssl "1.5.3"
+    yeast "0.1.2"
+
+engine.io-parser@1.3.2:
+  version "1.3.2"
+  resolved "https://registry.yarnpkg.com/engine.io-parser/-/engine.io-parser-1.3.2.tgz#937b079f0007d0893ec56d46cb220b8cb435220a"
+  dependencies:
+    after "0.8.2"
+    arraybuffer.slice "0.0.6"
+    base64-arraybuffer "0.1.5"
+    blob "0.0.4"
+    has-binary "0.1.7"
+    wtf-8 "1.0.0"
+
+engine.io@~1.8.4:
+  version "1.8.5"
+  resolved "https://registry.yarnpkg.com/engine.io/-/engine.io-1.8.5.tgz#4ebe5e75c6dc123dee4afdce6e5fdced21eb93f6"
+  dependencies:
+    accepts "1.3.3"
+    base64id "1.0.0"
+    cookie "0.3.1"
+    debug "2.3.3"
+    engine.io-parser "1.3.2"
+    ws "~1.1.5"
+
+enhanced-resolve@~0.9.0:
+  version "0.9.1"
+  resolved "https://registry.yarnpkg.com/enhanced-resolve/-/enhanced-resolve-0.9.1.tgz#4d6e689b3725f86090927ccc86cd9f1635b89e2e"
+  dependencies:
+    graceful-fs "^4.1.2"
+    memory-fs "^0.2.0"
+    tapable "^0.1.8"
+
+ent@~2.2.0:
+  version "2.2.0"
+  resolved "https://registry.yarnpkg.com/ent/-/ent-2.2.0.tgz#e964219325a21d05f44466a2f686ed6ce5f5dd1d"
+
+errno@^0.1.3:
+  version "0.1.7"
+  resolved "https://registry.yarnpkg.com/errno/-/errno-0.1.7.tgz#4684d71779ad39af177e3f007996f7c67c852618"
+  dependencies:
+    prr "~1.0.1"
+
+error-ex@^1.2.0:
+  version "1.3.1"
+  resolved "https://registry.yarnpkg.com/error-ex/-/error-ex-1.3.1.tgz#f855a86ce61adc4e8621c3cda21e7a7612c3a8dc"
+  dependencies:
+    is-arrayish "^0.2.1"
+
+es5-ext@^0.10.14, es5-ext@^0.10.35, es5-ext@^0.10.9, es5-ext@~0.10.14:
+  version "0.10.39"
+  resolved "https://registry.yarnpkg.com/es5-ext/-/es5-ext-0.10.39.tgz#fca21b67559277ca4ac1a1ed7048b107b6f76d87"
+  dependencies:
+    es6-iterator "~2.0.3"
+    es6-symbol "~3.1.1"
+
+es6-iterator@^2.0.1, es6-iterator@~2.0.1, es6-iterator@~2.0.3:
+  version "2.0.3"
+  resolved "https://registry.yarnpkg.com/es6-iterator/-/es6-iterator-2.0.3.tgz#a7de889141a05a94b0854403b2d0a0fbfa98f3b7"
+  dependencies:
+    d "1"
+    es5-ext "^0.10.35"
+    es6-symbol "^3.1.1"
+
+es6-map@^0.1.3:
+  version "0.1.5"
+  resolved "https://registry.yarnpkg.com/es6-map/-/es6-map-0.1.5.tgz#9136e0503dcc06a301690f0bb14ff4e364e949f0"
+  dependencies:
+    d "1"
+    es5-ext "~0.10.14"
+    es6-iterator "~2.0.1"
+    es6-set "~0.1.5"
+    es6-symbol "~3.1.1"
+    event-emitter "~0.3.5"
+
+es6-promise@^4.0.3:
+  version "4.2.4"
+  resolved "https://registry.yarnpkg.com/es6-promise/-/es6-promise-4.2.4.tgz#dc4221c2b16518760bd8c39a52d8f356fc00ed29"
+
+es6-set@~0.1.5:
+  version "0.1.5"
+  resolved "https://registry.yarnpkg.com/es6-set/-/es6-set-0.1.5.tgz#d2b3ec5d4d800ced818db538d28974db0a73ccb1"
+  dependencies:
+    d "1"
+    es5-ext "~0.10.14"
+    es6-iterator "~2.0.1"
+    es6-symbol "3.1.1"
+    event-emitter "~0.3.5"
+
+es6-symbol@3.1.1, es6-symbol@^3.1.1, es6-symbol@~3.1.1:
+  version "3.1.1"
+  resolved "https://registry.yarnpkg.com/es6-symbol/-/es6-symbol-3.1.1.tgz#bf00ef4fdab6ba1b46ecb7b629b4c7ed5715cc77"
+  dependencies:
+    d "1"
+    es5-ext "~0.10.14"
+
+es6-weak-map@^2.0.1:
+  version "2.0.2"
+  resolved "https://registry.yarnpkg.com/es6-weak-map/-/es6-weak-map-2.0.2.tgz#5e3ab32251ffd1538a1f8e5ffa1357772f92d96f"
+  dependencies:
+    d "1"
+    es5-ext "^0.10.14"
+    es6-iterator "^2.0.1"
+    es6-symbol "^3.1.1"
+
+escape-html@~1.0.3:
+  version "1.0.3"
+  resolved "https://registry.yarnpkg.com/escape-html/-/escape-html-1.0.3.tgz#0258eae4d3d0c0974de1c169188ef0051d1d1988"
+
+escape-string-regexp@1.0.2:
+  version "1.0.2"
+  resolved "https://registry.yarnpkg.com/escape-string-regexp/-/escape-string-regexp-1.0.2.tgz#4dbc2fe674e71949caf3fb2695ce7f2dc1d9a8d1"
+
+escape-string-regexp@^1.0.2, escape-string-regexp@^1.0.3, escape-string-regexp@^1.0.5:
+  version "1.0.5"
+  resolved "https://registry.yarnpkg.com/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz#1b61c0562190a8dff6ae3bb2cf0200ca130b86d4"
+
+escodegen@1.7.x:
+  version "1.7.1"
+  resolved "https://registry.yarnpkg.com/escodegen/-/escodegen-1.7.1.tgz#30ecfcf66ca98dc67cd2fd162abeb6eafa8ce6fc"
+  dependencies:
+    esprima "^1.2.2"
+    estraverse "^1.9.1"
+    esutils "^2.0.2"
+    optionator "^0.5.0"
+  optionalDependencies:
+    source-map "~0.2.0"
+
+escope@^3.3.0:
+  version "3.6.0"
+  resolved "https://registry.yarnpkg.com/escope/-/escope-3.6.0.tgz#e01975e812781a163a6dadfdd80398dc64c889c3"
+  dependencies:
+    es6-map "^0.1.3"
+    es6-weak-map "^2.0.1"
+    esrecurse "^4.1.0"
+    estraverse "^4.1.1"
+
+eslint@^1.5.1, eslint@^1.6.0:
+  version "1.10.3"
+  resolved "https://registry.yarnpkg.com/eslint/-/eslint-1.10.3.tgz#fb19a91b13c158082bbca294b17d979bc8353a0a"
+  dependencies:
+    chalk "^1.0.0"
+    concat-stream "^1.4.6"
+    debug "^2.1.1"
+    doctrine "^0.7.1"
+    escape-string-regexp "^1.0.2"
+    escope "^3.3.0"
+    espree "^2.2.4"
+    estraverse "^4.1.1"
+    estraverse-fb "^1.3.1"
+    esutils "^2.0.2"
+    file-entry-cache "^1.1.1"
+    glob "^5.0.14"
+    globals "^8.11.0"
+    handlebars "^4.0.0"
+    inquirer "^0.11.0"
+    is-my-json-valid "^2.10.0"
+    is-resolvable "^1.0.0"
+    js-yaml "3.4.5"
+    json-stable-stringify "^1.0.0"
+    lodash.clonedeep "^3.0.1"
+    lodash.merge "^3.3.2"
+    lodash.omit "^3.1.0"
+    minimatch "^3.0.0"
+    mkdirp "^0.5.0"
+    object-assign "^4.0.1"
+    optionator "^0.6.0"
+    path-is-absolute "^1.0.0"
+    path-is-inside "^1.0.1"
+    shelljs "^0.5.3"
+    strip-json-comments "~1.0.1"
+    text-table "~0.2.0"
+    user-home "^2.0.0"
+    xml-escape "~1.0.0"
+
+espree@^2.2.4:
+  version "2.2.5"
+  resolved "https://registry.yarnpkg.com/espree/-/espree-2.2.5.tgz#df691b9310889402aeb29cc066708c56690b854b"
+
+esprima@2.5.x:
+  version "2.5.0"
+  resolved "https://registry.yarnpkg.com/esprima/-/esprima-2.5.0.tgz#f387a46fd344c1b1a39baf8c20bfb43b6d0058cc"
+
+esprima@^1.2.2:
+  version "1.2.5"
+  resolved "https://registry.yarnpkg.com/esprima/-/esprima-1.2.5.tgz#0993502feaf668138325756f30f9a51feeec11e9"
+
+esprima@^2.6.0:
+  version "2.7.3"
+  resolved "https://registry.yarnpkg.com/esprima/-/esprima-2.7.3.tgz#96e3b70d5779f6ad49cd032673d1c312767ba581"
+
+esprima@^4.0.0:
+  version "4.0.0"
+  resolved "https://registry.yarnpkg.com/esprima/-/esprima-4.0.0.tgz#4499eddcd1110e0b218bacf2fa7f7f59f55ca804"
+
+"esprima@~ 1.0.2":
+  version "1.0.4"
+  resolved "https://registry.yarnpkg.com/esprima/-/esprima-1.0.4.tgz#9f557e08fc3b4d26ece9dd34f8fbf476b62585ad"
+
+esrecurse@^4.1.0:
+  version "4.2.1"
+  resolved "https://registry.yarnpkg.com/esrecurse/-/esrecurse-4.2.1.tgz#007a3b9fdbc2b3bb87e4879ea19c92fdbd3942cf"
+  dependencies:
+    estraverse "^4.1.0"
+
+estraverse-fb@^1.3.1:
+  version "1.3.2"
+  resolved "https://registry.yarnpkg.com/estraverse-fb/-/estraverse-fb-1.3.2.tgz#d323a4cb5e5ac331cea033413a9253e1643e07c4"
+
+estraverse@^1.9.1:
+  version "1.9.3"
+  resolved "https://registry.yarnpkg.com/estraverse/-/estraverse-1.9.3.tgz#af67f2dc922582415950926091a4005d29c9bb44"
+
+estraverse@^4.1.0, estraverse@^4.1.1:
+  version "4.2.0"
+  resolved "https://registry.yarnpkg.com/estraverse/-/estraverse-4.2.0.tgz#0dee3fed31fcd469618ce7342099fc1afa0bdb13"
+
+esutils@^1.1.6:
+  version "1.1.6"
+  resolved "https://registry.yarnpkg.com/esutils/-/esutils-1.1.6.tgz#c01ccaa9ae4b897c6d0c3e210ae52f3c7a844375"
+
+esutils@^2.0.2:
+  version "2.0.2"
+  resolved "https://registry.yarnpkg.com/esutils/-/esutils-2.0.2.tgz#0abf4f1caa5bcb1f7a9d8acc6dea4faaa04bac9b"
+
+etag@~1.8.1:
+  version "1.8.1"
+  resolved "https://registry.yarnpkg.com/etag/-/etag-1.8.1.tgz#41ae2eeb65efa62268aebfea83ac7d79299b0887"
+
+event-emitter@~0.3.5:
+  version "0.3.5"
+  resolved "https://registry.yarnpkg.com/event-emitter/-/event-emitter-0.3.5.tgz#df8c69eef1647923c7157b9ce83840610b02cc39"
+  dependencies:
+    d "1"
+    es5-ext "~0.10.14"
+
+eventemitter2@~0.4.13:
+  version "0.4.14"
+  resolved "https://registry.yarnpkg.com/eventemitter2/-/eventemitter2-0.4.14.tgz#8f61b75cde012b2e9eb284d4545583b5643b61ab"
+
+eventemitter3@1.x.x:
+  version "1.2.0"
+  resolved "https://registry.yarnpkg.com/eventemitter3/-/eventemitter3-1.2.0.tgz#1c86991d816ad1e504750e73874224ecf3bec508"
+
+events-to-array@^1.0.1:
+  version "1.1.2"
+  resolved "https://registry.yarnpkg.com/events-to-array/-/events-to-array-1.1.2.tgz#2d41f563e1fe400ed4962fe1a4d5c6a7539df7f6"
+
+events@^1.0.0:
+  version "1.1.1"
+  resolved "https://registry.yarnpkg.com/events/-/events-1.1.1.tgz#9ebdb7635ad099c70dcc4c2a1f5004288e8bd924"
+
+eventsource@0.1.6:
+  version "0.1.6"
+  resolved "https://registry.yarnpkg.com/eventsource/-/eventsource-0.1.6.tgz#0acede849ed7dd1ccc32c811bb11b944d4f29232"
+  dependencies:
+    original ">=0.0.5"
+
+execa@^0.7.0:
+  version "0.7.0"
+  resolved "https://registry.yarnpkg.com/execa/-/execa-0.7.0.tgz#944becd34cc41ee32a63a9faf27ad5a65fc59777"
+  dependencies:
+    cross-spawn "^5.0.1"
+    get-stream "^3.0.0"
+    is-stream "^1.1.0"
+    npm-run-path "^2.0.0"
+    p-finally "^1.0.0"
+    signal-exit "^3.0.0"
+    strip-eof "^1.0.0"
+
+exit-hook@^1.0.0:
+  version "1.1.1"
+  resolved "https://registry.yarnpkg.com/exit-hook/-/exit-hook-1.1.1.tgz#f05ca233b48c05d54fff07765df8507e95c02ff8"
+
+exit@~0.1.1:
+  version "0.1.2"
+  resolved "https://registry.yarnpkg.com/exit/-/exit-0.1.2.tgz#0632638f8d877cc82107d30a0fff1a17cba1cd0c"
+
+expand-braces@^0.1.1:
+  version "0.1.2"
+  resolved "https://registry.yarnpkg.com/expand-braces/-/expand-braces-0.1.2.tgz#488b1d1d2451cb3d3a6b192cfc030f44c5855fea"
+  dependencies:
+    array-slice "^0.2.3"
+    array-unique "^0.2.1"
+    braces "^0.1.2"
+
+expand-brackets@^0.1.4:
+  version "0.1.5"
+  resolved "https://registry.yarnpkg.com/expand-brackets/-/expand-brackets-0.1.5.tgz#df07284e342a807cd733ac5af72411e581d1177b"
+  dependencies:
+    is-posix-bracket "^0.1.0"
+
+expand-range@^0.1.0:
+  version "0.1.1"
+  resolved "https://registry.yarnpkg.com/expand-range/-/expand-range-0.1.1.tgz#4cb8eda0993ca56fa4f41fc42f3cbb4ccadff044"
+  dependencies:
+    is-number "^0.1.1"
+    repeat-string "^0.2.2"
+
+expand-range@^1.8.1:
+  version "1.8.2"
+  resolved "https://registry.yarnpkg.com/expand-range/-/expand-range-1.8.2.tgz#a299effd335fe2721ebae8e257ec79644fc85337"
+  dependencies:
+    fill-range "^2.1.0"
+
+express@^4.13.3:
+  version "4.16.2"
+  resolved "https://registry.yarnpkg.com/express/-/express-4.16.2.tgz#e35c6dfe2d64b7dca0a5cd4f21781be3299e076c"
+  dependencies:
+    accepts "~1.3.4"
+    array-flatten "1.1.1"
+    body-parser "1.18.2"
+    content-disposition "0.5.2"
+    content-type "~1.0.4"
+    cookie "0.3.1"
+    cookie-signature "1.0.6"
+    debug "2.6.9"
+    depd "~1.1.1"
+    encodeurl "~1.0.1"
+    escape-html "~1.0.3"
+    etag "~1.8.1"
+    finalhandler "1.1.0"
+    fresh "0.5.2"
+    merge-descriptors "1.0.1"
+    methods "~1.1.2"
+    on-finished "~2.3.0"
+    parseurl "~1.3.2"
+    path-to-regexp "0.1.7"
+    proxy-addr "~2.0.2"
+    qs "6.5.1"
+    range-parser "~1.2.0"
+    safe-buffer "5.1.1"
+    send "0.16.1"
+    serve-static "1.13.1"
+    setprototypeof "1.1.0"
+    statuses "~1.3.1"
+    type-is "~1.6.15"
+    utils-merge "1.0.1"
+    vary "~1.1.2"
+
+extend@3, extend@^3.0.0, extend@~3.0.0, extend@~3.0.1:
+  version "3.0.1"
+  resolved "https://registry.yarnpkg.com/extend/-/extend-3.0.1.tgz#a755ea7bc1adfcc5a31ce7e762dbaadc5e636444"
+
+extglob@^0.3.1:
+  version "0.3.2"
+  resolved "https://registry.yarnpkg.com/extglob/-/extglob-0.3.2.tgz#2e18ff3d2f49ab2765cec9023f011daa8d8349a1"
+  dependencies:
+    is-extglob "^1.0.0"
+
+extract-zip@^1.6.5:
+  version "1.6.6"
+  resolved "https://registry.yarnpkg.com/extract-zip/-/extract-zip-1.6.6.tgz#1290ede8d20d0872b429fd3f351ca128ec5ef85c"
+  dependencies:
+    concat-stream "1.6.0"
+    debug "2.6.9"
+    mkdirp "0.5.0"
+    yauzl "2.4.1"
+
+extsprintf@1.3.0:
+  version "1.3.0"
+  resolved "https://registry.yarnpkg.com/extsprintf/-/extsprintf-1.3.0.tgz#96918440e3041a7a414f8c52e3c574eb3c3e1e05"
+
+extsprintf@^1.2.0:
+  version "1.4.0"
+  resolved "https://registry.yarnpkg.com/extsprintf/-/extsprintf-1.4.0.tgz#e2689f8f356fad62cca65a3a91c5df5f9551692f"
+
+eyes@0.1.x:
+  version "0.1.8"
+  resolved "https://registry.yarnpkg.com/eyes/-/eyes-0.1.8.tgz#62cf120234c683785d902348a800ef3e0cc20bc0"
+
+fast-deep-equal@^1.0.0:
+  version "1.1.0"
+  resolved "https://registry.yarnpkg.com/fast-deep-equal/-/fast-deep-equal-1.1.0.tgz#c053477817c86b51daa853c81e059b733d023614"
+
+fast-json-stable-stringify@^2.0.0:
+  version "2.0.0"
+  resolved "https://registry.yarnpkg.com/fast-json-stable-stringify/-/fast-json-stable-stringify-2.0.0.tgz#d5142c0caee6b1189f87d3a76111064f86c8bbf2"
+
+fast-levenshtein@~1.0.0, fast-levenshtein@~1.0.6:
+  version "1.0.7"
+  resolved "https://registry.yarnpkg.com/fast-levenshtein/-/fast-levenshtein-1.0.7.tgz#0178dcdee023b92905193af0959e8a7639cfdcb9"
+
+faye-websocket@^0.10.0, faye-websocket@~0.10.0:
+  version "0.10.0"
+  resolved "https://registry.yarnpkg.com/faye-websocket/-/faye-websocket-0.10.0.tgz#4e492f8d04dfb6f89003507f6edbf2d501e7c6f4"
+  dependencies:
+    websocket-driver ">=0.5.1"
+
+faye-websocket@~0.11.0:
+  version "0.11.1"
+  resolved "https://registry.yarnpkg.com/faye-websocket/-/faye-websocket-0.11.1.tgz#f0efe18c4f56e4f40afc7e06c719fd5ee6188f38"
+  dependencies:
+    websocket-driver ">=0.5.1"
+
+fd-slicer@~1.0.1:
+  version "1.0.1"
+  resolved "https://registry.yarnpkg.com/fd-slicer/-/fd-slicer-1.0.1.tgz#8b5bcbd9ec327c5041bf9ab023fd6750f1177e65"
+  dependencies:
+    pend "~1.2.0"
+
+figures@^1.0.1, figures@^1.3.5:
+  version "1.7.0"
+  resolved "https://registry.yarnpkg.com/figures/-/figures-1.7.0.tgz#cbe1e3affcf1cd44b80cadfed28dc793a9701d2e"
+  dependencies:
+    escape-string-regexp "^1.0.5"
+    object-assign "^4.1.0"
+
+file-entry-cache@^1.1.1:
+  version "1.3.1"
+  resolved "https://registry.yarnpkg.com/file-entry-cache/-/file-entry-cache-1.3.1.tgz#44c61ea607ae4be9c1402f41f44270cbfe334ff8"
+  dependencies:
+    flat-cache "^1.2.1"
+    object-assign "^4.0.1"
+
+file-sync-cmp@^0.1.0:
+  version "0.1.1"
+  resolved "https://registry.yarnpkg.com/file-sync-cmp/-/file-sync-cmp-0.1.1.tgz#a5e7a8ffbfa493b43b923bbd4ca89a53b63b612b"
+
+filename-regex@^2.0.0:
+  version "2.0.1"
+  resolved "https://registry.yarnpkg.com/filename-regex/-/filename-regex-2.0.1.tgz#c1c4b9bee3e09725ddb106b75c1e301fe2f18b26"
+
+fileset@0.2.x:
+  version "0.2.1"
+  resolved "https://registry.yarnpkg.com/fileset/-/fileset-0.2.1.tgz#588ef8973c6623b2a76df465105696b96aac8067"
+  dependencies:
+    glob "5.x"
+    minimatch "2.x"
+
+fill-range@^2.1.0:
+  version "2.2.3"
+  resolved "https://registry.yarnpkg.com/fill-range/-/fill-range-2.2.3.tgz#50b77dfd7e469bc7492470963699fe7a8485a723"
+  dependencies:
+    is-number "^2.1.0"
+    isobject "^2.0.0"
+    randomatic "^1.1.3"
+    repeat-element "^1.1.2"
+    repeat-string "^1.5.2"
+
+finalhandler@1.1.0:
+  version "1.1.0"
+  resolved "https://registry.yarnpkg.com/finalhandler/-/finalhandler-1.1.0.tgz#ce0b6855b45853e791b2fcc680046d88253dd7f5"
+  dependencies:
+    debug "2.6.9"
+    encodeurl "~1.0.1"
+    escape-html "~1.0.3"
+    on-finished "~2.3.0"
+    parseurl "~1.3.2"
+    statuses "~1.3.1"
+    unpipe "~1.0.0"
+
+find-cache-dir@^0.1.1:
+  version "0.1.1"
+  resolved "https://registry.yarnpkg.com/find-cache-dir/-/find-cache-dir-0.1.1.tgz#c8defae57c8a52a8a784f9e31c57c742e993a0b9"
+  dependencies:
+    commondir "^1.0.1"
+    mkdirp "^0.5.1"
+    pkg-dir "^1.0.0"
+
+find-up@^1.0.0:
+  version "1.1.2"
+  resolved "https://registry.yarnpkg.com/find-up/-/find-up-1.1.2.tgz#6b2e9822b1a2ce0a60ab64d610eccad53cb24d0f"
+  dependencies:
+    path-exists "^2.0.0"
+    pinkie-promise "^2.0.0"
+
+find-up@^2.1.0:
+  version "2.1.0"
+  resolved "https://registry.yarnpkg.com/find-up/-/find-up-2.1.0.tgz#45d1b7e506c717ddd482775a2b77920a3c0c57a7"
+  dependencies:
+    locate-path "^2.0.0"
+
+findup-sync@~0.1.0, findup-sync@~0.1.2:
+  version "0.1.3"
+  resolved "https://registry.yarnpkg.com/findup-sync/-/findup-sync-0.1.3.tgz#7f3e7a97b82392c653bf06589bd85190e93c3683"
+  dependencies:
+    glob "~3.2.9"
+    lodash "~2.4.1"
+
+flat-cache@^1.2.1:
+  version "1.3.0"
+  resolved "https://registry.yarnpkg.com/flat-cache/-/flat-cache-1.3.0.tgz#d3030b32b38154f4e3b7e9c709f490f7ef97c481"
+  dependencies:
+    circular-json "^0.3.1"
+    del "^2.0.2"
+    graceful-fs "^4.1.2"
+    write "^0.2.1"
+
+for-in@^1.0.1:
+  version "1.0.2"
+  resolved "https://registry.yarnpkg.com/for-in/-/for-in-1.0.2.tgz#81068d295a8142ec0ac726c6e2200c30fb6d5e80"
+
+for-own@^0.1.4:
+  version "0.1.5"
+  resolved "https://registry.yarnpkg.com/for-own/-/for-own-0.1.5.tgz#5265c681a4f294dabbf17c9509b6763aa84510ce"
+  dependencies:
+    for-in "^1.0.1"
+
+foreground-child@^1.3.3, foreground-child@^1.5.3, foreground-child@^1.5.6:
+  version "1.5.6"
+  resolved "https://registry.yarnpkg.com/foreground-child/-/foreground-child-1.5.6.tgz#4fd71ad2dfde96789b980a5c0a295937cb2f5ce9"
+  dependencies:
+    cross-spawn "^4"
+    signal-exit "^3.0.0"
+
+forever-agent@~0.6.0, forever-agent@~0.6.1:
+  version "0.6.1"
+  resolved "https://registry.yarnpkg.com/forever-agent/-/forever-agent-0.6.1.tgz#fbc71f0c41adeb37f96c577ad1ed42d8fdacca91"
+
+form-data@~0.2.0:
+  version "0.2.0"
+  resolved "https://registry.yarnpkg.com/form-data/-/form-data-0.2.0.tgz#26f8bc26da6440e299cbdcfb69035c4f77a6e466"
+  dependencies:
+    async "~0.9.0"
+    combined-stream "~0.0.4"
+    mime-types "~2.0.3"
+
+form-data@~2.1.1:
+  version "2.1.4"
+  resolved "https://registry.yarnpkg.com/form-data/-/form-data-2.1.4.tgz#33c183acf193276ecaa98143a69e94bfee1750d1"
+  dependencies:
+    asynckit "^0.4.0"
+    combined-stream "^1.0.5"
+    mime-types "^2.1.12"
+
+form-data@~2.3.1:
+  version "2.3.2"
+  resolved "https://registry.yarnpkg.com/form-data/-/form-data-2.3.2.tgz#4970498be604c20c005d4f5c23aecd21d6b49099"
+  dependencies:
+    asynckit "^0.4.0"
+    combined-stream "1.0.6"
+    mime-types "^2.1.12"
+
+formidable@1.0.11:
+  version "1.0.11"
+  resolved "https://registry.yarnpkg.com/formidable/-/formidable-1.0.11.tgz#68f63325a035e644b6f7bb3d11243b9761de1b30"
+
+forwarded@~0.1.2:
+  version "0.1.2"
+  resolved "https://registry.yarnpkg.com/forwarded/-/forwarded-0.1.2.tgz#98c23dab1175657b8c0573e8ceccd91b0ff18c84"
+
+fresh@0.1.0:
+  version "0.1.0"
+  resolved "https://registry.yarnpkg.com/fresh/-/fresh-0.1.0.tgz#03e4b0178424e4c2d5d19a54d8814cdc97934850"
+
+fresh@0.5.2:
+  version "0.5.2"
+  resolved "https://registry.yarnpkg.com/fresh/-/fresh-0.5.2.tgz#3d8cadd90d976569fa835ab1f8e4b23a105605a7"
+
+fs-exists-cached@^1.0.0:
+  version "1.0.0"
+  resolved "https://registry.yarnpkg.com/fs-exists-cached/-/fs-exists-cached-1.0.0.tgz#cf25554ca050dc49ae6656b41de42258989dcbce"
+
+fs-extra@^1.0.0:
+  version "1.0.0"
+  resolved "https://registry.yarnpkg.com/fs-extra/-/fs-extra-1.0.0.tgz#cd3ce5f7e7cb6145883fcae3191e9877f8587950"
+  dependencies:
+    graceful-fs "^4.1.2"
+    jsonfile "^2.1.0"
+    klaw "^1.0.0"
+
+fs.realpath@^1.0.0:
+  version "1.0.0"
+  resolved "https://registry.yarnpkg.com/fs.realpath/-/fs.realpath-1.0.0.tgz#1504ad2523158caa40db4a2787cb01411994ea4f"
+
+fsevents@^1.0.0:
+  version "1.1.3"
+  resolved "https://registry.yarnpkg.com/fsevents/-/fsevents-1.1.3.tgz#11f82318f5fe7bb2cd22965a108e9306208216d8"
+  dependencies:
+    nan "^2.3.0"
+    node-pre-gyp "^0.6.39"
+
+fstream-ignore@^1.0.5:
+  version "1.0.5"
+  resolved "https://registry.yarnpkg.com/fstream-ignore/-/fstream-ignore-1.0.5.tgz#9c31dae34767018fe1d249b24dada67d092da105"
+  dependencies:
+    fstream "^1.0.0"
+    inherits "2"
+    minimatch "^3.0.0"
+
+fstream@^1.0.0, fstream@^1.0.10, fstream@^1.0.2:
+  version "1.0.11"
+  resolved "https://registry.yarnpkg.com/fstream/-/fstream-1.0.11.tgz#5c1fb1f117477114f0632a0eb4b71b3cb0fd3171"
+  dependencies:
+    graceful-fs "^4.1.2"
+    inherits "~2.0.0"
+    mkdirp ">=0.5 0"
+    rimraf "2"
+
+function-loop@^1.0.1:
+  version "1.0.1"
+  resolved "https://registry.yarnpkg.com/function-loop/-/function-loop-1.0.1.tgz#8076bb305e8e6a3cceee2920765f330d190f340c"
+
+gauge@~2.7.3:
+  version "2.7.4"
+  resolved "https://registry.yarnpkg.com/gauge/-/gauge-2.7.4.tgz#2c03405c7538c39d7eb37b317022e325fb018bf7"
+  dependencies:
+    aproba "^1.0.3"
+    console-control-strings "^1.0.0"
+    has-unicode "^2.0.0"
+    object-assign "^4.1.0"
+    signal-exit "^3.0.0"
+    string-width "^1.0.1"
+    strip-ansi "^3.0.1"
+    wide-align "^1.1.0"
+
+gaze@^1.0.0:
+  version "1.1.2"
+  resolved "https://registry.yarnpkg.com/gaze/-/gaze-1.1.2.tgz#847224677adb8870d679257ed3388fdb61e40105"
+  dependencies:
+    globule "^1.0.0"
+
+generate-function@^2.0.0:
+  version "2.0.0"
+  resolved "https://registry.yarnpkg.com/generate-function/-/generate-function-2.0.0.tgz#6858fe7c0969b7d4e9093337647ac79f60dfbe74"
+
+generate-object-property@^1.1.0:
+  version "1.2.0"
+  resolved "https://registry.yarnpkg.com/generate-object-property/-/generate-object-property-1.2.0.tgz#9c0e1c40308ce804f4783618b937fa88f99d50d0"
+  dependencies:
+    is-property "^1.0.0"
+
+get-caller-file@^1.0.1:
+  version "1.0.2"
+  resolved "https://registry.yarnpkg.com/get-caller-file/-/get-caller-file-1.0.2.tgz#f702e63127e7e231c160a80c1554acb70d5047e5"
+
+get-stdin@^4.0.1:
+  version "4.0.1"
+  resolved "https://registry.yarnpkg.com/get-stdin/-/get-stdin-4.0.1.tgz#b968c6b0a04384324902e8bf1a5df32579a450fe"
+
+get-stream@^3.0.0:
+  version "3.0.0"
+  resolved "https://registry.yarnpkg.com/get-stream/-/get-stream-3.0.0.tgz#8e943d1358dc37555054ecbe2edb05aa174ede14"
+
+getobject@~0.1.0:
+  version "0.1.0"
+  resolved "https://registry.yarnpkg.com/getobject/-/getobject-0.1.0.tgz#047a449789fa160d018f5486ed91320b6ec7885c"
+
+getpass@^0.1.1:
+  version "0.1.7"
+  resolved "https://registry.yarnpkg.com/getpass/-/getpass-0.1.7.tgz#5eff8e3e684d569ae4cb2b1282604e8ba62149fa"
+  dependencies:
+    assert-plus "^1.0.0"
+
+glob-base@^0.3.0:
+  version "0.3.0"
+  resolved "https://registry.yarnpkg.com/glob-base/-/glob-base-0.3.0.tgz#dbb164f6221b1c0b1ccf82aea328b497df0ea3c4"
+  dependencies:
+    glob-parent "^2.0.0"
+    is-glob "^2.0.0"
+
+glob-parent@^2.0.0:
+  version "2.0.0"
+  resolved "https://registry.yarnpkg.com/glob-parent/-/glob-parent-2.0.0.tgz#81383d72db054fcccf5336daa902f182f6edbb28"
+  dependencies:
+    is-glob "^2.0.0"
+
+glob-whatev@~0.1.4:
+  version "0.1.8"
+  resolved "https://registry.yarnpkg.com/glob-whatev/-/glob-whatev-0.1.8.tgz#a33a763262e501e851bc84fd22b5736cff3826fd"
+  dependencies:
+    minimatch "~0.2.5"
+
+glob@3.2.11, glob@~3.2.9:
+  version "3.2.11"
+  resolved "https://registry.yarnpkg.com/glob/-/glob-3.2.11.tgz#4a973f635b9190f715d10987d5c00fd2815ebe3d"
+  dependencies:
+    inherits "2"
+    minimatch "0.3"
+
+glob@5.x, glob@^5.0.14:
+  version "5.0.15"
+  resolved "https://registry.yarnpkg.com/glob/-/glob-5.0.15.tgz#1bc936b9e02f4a603fcc222ecf7633d30b8b93b1"
+  dependencies:
+    inflight "^1.0.4"
+    inherits "2"
+    minimatch "2 || 3"
+    once "^1.3.0"
+    path-is-absolute "^1.0.0"
+
+"glob@>= 3.1.4", glob@^7.0.0, glob@^7.0.3, glob@^7.0.5, glob@^7.0.6, glob@~7.1.1:
+  version "7.1.2"
+  resolved "https://registry.yarnpkg.com/glob/-/glob-7.1.2.tgz#c19c9df9a028702d678612384a6552404c636d15"
+  dependencies:
+    fs.realpath "^1.0.0"
+    inflight "^1.0.4"
+    inherits "2"
+    minimatch "^3.0.4"
+    once "^1.3.0"
+    path-is-absolute "^1.0.0"
+
+glob@~3.1.21:
+  version "3.1.21"
+  resolved "https://registry.yarnpkg.com/glob/-/glob-3.1.21.tgz#d29e0a055dea5138f4d07ed40e8982e83c2066cd"
+  dependencies:
+    graceful-fs "~1.2.0"
+    inherits "1"
+    minimatch "~0.2.11"
+
+glob@~4.3.0:
+  version "4.3.5"
+  resolved "https://registry.yarnpkg.com/glob/-/glob-4.3.5.tgz#80fbb08ca540f238acce5d11d1e9bc41e75173d3"
+  dependencies:
+    inflight "^1.0.4"
+    inherits "2"
+    minimatch "^2.0.1"
+    once "^1.3.0"
+
+globals@^8.11.0:
+  version "8.18.0"
+  resolved "https://registry.yarnpkg.com/globals/-/globals-8.18.0.tgz#93d4a62bdcac38cfafafc47d6b034768cb0ffcb4"
+
+globals@^9.18.0:
+  version "9.18.0"
+  resolved "https://registry.yarnpkg.com/globals/-/globals-9.18.0.tgz#aa3896b3e69b487f17e31ed2143d69a8e30c2d8a"
+
+globby@^5.0.0:
+  version "5.0.0"
+  resolved "https://registry.yarnpkg.com/globby/-/globby-5.0.0.tgz#ebd84667ca0dbb330b99bcfc68eac2bc54370e0d"
+  dependencies:
+    array-union "^1.0.1"
+    arrify "^1.0.0"
+    glob "^7.0.3"
+    object-assign "^4.0.1"
+    pify "^2.0.0"
+    pinkie-promise "^2.0.0"
+
+globule@^1.0.0:
+  version "1.2.0"
+  resolved "https://registry.yarnpkg.com/globule/-/globule-1.2.0.tgz#1dc49c6822dd9e8a2fa00ba2a295006e8664bd09"
+  dependencies:
+    glob "~7.1.1"
+    lodash "~4.17.4"
+    minimatch "~3.0.2"
+
+graceful-fs@^4.1.11, graceful-fs@^4.1.2, graceful-fs@^4.1.6, graceful-fs@^4.1.9:
+  version "4.1.11"
+  resolved "https://registry.yarnpkg.com/graceful-fs/-/graceful-fs-4.1.11.tgz#0e8bdfe4d1ddb8854d64e04ea7c00e2a026e5658"
+
+graceful-fs@~1.2.0:
+  version "1.2.3"
+  resolved "https://registry.yarnpkg.com/graceful-fs/-/graceful-fs-1.2.3.tgz#15a4806a57547cb2d2dbf27f42e89a8c3451b364"
+
+growl@1.9.2:
+  version "1.9.2"
+  resolved "https://registry.yarnpkg.com/growl/-/growl-1.9.2.tgz#0ea7743715db8d8de2c5ede1775e1b45ac85c02f"
+
+grunt-babel@^6.0.0:
+  version "6.0.0"
+  resolved "https://registry.yarnpkg.com/grunt-babel/-/grunt-babel-6.0.0.tgz#378189b487de1168c4c4a9fc88dd6005b35df960"
+  dependencies:
+    babel-core "^6.0.12"
+
+grunt-clean@^0.4.0:
+  version "0.4.0"
+  resolved "https://registry.yarnpkg.com/grunt-clean/-/grunt-clean-0.4.0.tgz#a7b4e188d7e94ca6c93bb88ec64096534931c40b"
+  dependencies:
+    grunt "~0.3.9"
+
+grunt-cli@^0.1.13:
+  version "0.1.13"
+  resolved "https://registry.yarnpkg.com/grunt-cli/-/grunt-cli-0.1.13.tgz#e9ebc4047631f5012d922770c39378133cad10f4"
+  dependencies:
+    findup-sync "~0.1.0"
+    nopt "~1.0.10"
+    resolve "~0.3.1"
+
+grunt-contrib-clean@^1.0.0:
+  version "1.1.0"
+  resolved "https://registry.yarnpkg.com/grunt-contrib-clean/-/grunt-contrib-clean-1.1.0.tgz#564abf2d0378a983a15b9e3f30ee75b738c40638"
+  dependencies:
+    async "^1.5.2"
+    rimraf "^2.5.1"
+
+grunt-contrib-copy@^1.0.0:
+  version "1.0.0"
+  resolved "https://registry.yarnpkg.com/grunt-contrib-copy/-/grunt-contrib-copy-1.0.0.tgz#7060c6581e904b8ab0d00f076e0a8f6e3e7c3573"
+  dependencies:
+    chalk "^1.1.1"
+    file-sync-cmp "^0.1.0"
+
+grunt-contrib-uglify@^1.0.0:
+  version "1.0.2"
+  resolved "https://registry.yarnpkg.com/grunt-contrib-uglify/-/grunt-contrib-uglify-1.0.2.tgz#ae67a46f9153edd4cb11813a55eb69c70d7db2fb"
+  dependencies:
+    chalk "^1.0.0"
+    lodash "^4.0.1"
+    maxmin "^1.1.0"
+    uglify-js "~2.6.2"
+    uri-path "^1.0.0"
+
+grunt-contrib-watch@^1.0.0:
+  version "1.0.0"
+  resolved "https://registry.yarnpkg.com/grunt-contrib-watch/-/grunt-contrib-watch-1.0.0.tgz#84a1a7a1d6abd26ed568413496c73133e990018f"
+  dependencies:
+    async "^1.5.0"
+    gaze "^1.0.0"
+    lodash "^3.10.1"
+    tiny-lr "^0.2.1"
+
+grunt-eslint@^17.3.1:
+  version "17.3.2"
+  resolved "https://registry.yarnpkg.com/grunt-eslint/-/grunt-eslint-17.3.2.tgz#36a8b3be6ccde88c8b58f909745d75db19e5d4b0"
+  dependencies:
+    chalk "^1.0.0"
+    eslint "^1.5.1"
+
+grunt-karma@^0.12.1:
+  version "0.12.2"
+  resolved "https://registry.yarnpkg.com/grunt-karma/-/grunt-karma-0.12.2.tgz#d52676ab94779e4b20052b5f3519eb32653dc566"
+  dependencies:
+    lodash "^3.10.1"
+
+grunt-legacy-log-utils@~0.1.1:
+  version "0.1.1"
+  resolved "https://registry.yarnpkg.com/grunt-legacy-log-utils/-/grunt-legacy-log-utils-0.1.1.tgz#c0706b9dd9064e116f36f23fe4e6b048672c0f7e"
+  dependencies:
+    colors "~0.6.2"
+    lodash "~2.4.1"
+    underscore.string "~2.3.3"
+
+grunt-legacy-log@~0.1.0:
+  version "0.1.3"
+  resolved "https://registry.yarnpkg.com/grunt-legacy-log/-/grunt-legacy-log-0.1.3.tgz#ec29426e803021af59029f87d2f9cd7335a05531"
+  dependencies:
+    colors "~0.6.2"
+    grunt-legacy-log-utils "~0.1.1"
+    hooker "~0.2.3"
+    lodash "~2.4.1"
+    underscore.string "~2.3.3"
+
+grunt-legacy-util@~0.2.0:
+  version "0.2.0"
+  resolved "https://registry.yarnpkg.com/grunt-legacy-util/-/grunt-legacy-util-0.2.0.tgz#93324884dbf7e37a9ff7c026dff451d94a9e554b"
+  dependencies:
+    async "~0.1.22"
+    exit "~0.1.1"
+    getobject "~0.1.0"
+    hooker "~0.2.3"
+    lodash "~0.9.2"
+    underscore.string "~2.2.1"
+    which "~1.0.5"
+
+grunt-mocha-istanbul@^3.0.1:
+  version "3.0.1"
+  resolved "https://registry.yarnpkg.com/grunt-mocha-istanbul/-/grunt-mocha-istanbul-3.0.1.tgz#a33525707b2fa82eb2f7fb3230513f7ca279bf60"
+
+grunt-mocha-test@^0.12.7:
+  version "0.12.7"
+  resolved "https://registry.yarnpkg.com/grunt-mocha-test/-/grunt-mocha-test-0.12.7.tgz#c61cdf32a6762954115fe712b983e3dd8e0c9554"
+  dependencies:
+    hooker "~0.2.3"
+    mkdirp "^0.5.0"
+
+grunt-webpack@^1.0.11:
+  version "1.0.18"
+  resolved "https://registry.yarnpkg.com/grunt-webpack/-/grunt-webpack-1.0.18.tgz#ff26c43ff35bae6cca707a93c4bcdd950a3ecbb7"
+  dependencies:
+    lodash "^4.7.0"
+
+grunt@^0.4.5:
+  version "0.4.5"
+  resolved "https://registry.yarnpkg.com/grunt/-/grunt-0.4.5.tgz#56937cd5194324adff6d207631832a9d6ba4e7f0"
+  dependencies:
+    async "~0.1.22"
+    coffee-script "~1.3.3"
+    colors "~0.6.2"
+    dateformat "1.0.2-1.2.3"
+    eventemitter2 "~0.4.13"
+    exit "~0.1.1"
+    findup-sync "~0.1.2"
+    getobject "~0.1.0"
+    glob "~3.1.21"
+    grunt-legacy-log "~0.1.0"
+    grunt-legacy-util "~0.2.0"
+    hooker "~0.2.3"
+    iconv-lite "~0.2.11"
+    js-yaml "~2.0.5"
+    lodash "~0.9.2"
+    minimatch "~0.2.12"
+    nopt "~1.0.10"
+    rimraf "~2.2.8"
+    underscore.string "~2.2.1"
+    which "~1.0.5"
+
+grunt@~0.3.9:
+  version "0.3.17"
+  resolved "https://registry.yarnpkg.com/grunt/-/grunt-0.3.17.tgz#f2e034d200befd5eeb38ba5c41d4ccd7235fd64d"
+  dependencies:
+    async "~0.1.18"
+    colors "~0.6.0"
+    connect "~2.4.4"
+    dateformat "1.0.2-1.2.3"
+    glob-whatev "~0.1.4"
+    gzip-js "~0.3.1"
+    hooker "~0.2.3"
+    jshint "~0.9.1"
+    nodeunit "~0.7.4"
+    nopt "~1.0.10"
+    prompt "~0.1.12"
+    semver "~1.0.13"
+    temporary "~0.0.4"
+    uglify-js "~1.3.3"
+    underscore "~1.2.4"
+    underscore.string "~2.1.1"
+
+gzip-js@~0.3.1:
+  version "0.3.2"
+  resolved "https://registry.yarnpkg.com/gzip-js/-/gzip-js-0.3.2.tgz#23117efeeb28cf385248deff0dffad894836d96b"
+  dependencies:
+    crc32 ">= 0.2.2"
+    deflate-js ">= 0.2.2"
+
+gzip-size@^1.0.0:
+  version "1.0.0"
+  resolved "https://registry.yarnpkg.com/gzip-size/-/gzip-size-1.0.0.tgz#66cf8b101047227b95bace6ea1da0c177ed5c22f"
+  dependencies:
+    browserify-zlib "^0.1.4"
+    concat-stream "^1.4.1"
+
+handlebars@^4.0.0, handlebars@^4.0.1, handlebars@^4.0.3:
+  version "4.0.11"
+  resolved "https://registry.yarnpkg.com/handlebars/-/handlebars-4.0.11.tgz#630a35dfe0294bc281edae6ffc5d329fc7982dcc"
+  dependencies:
+    async "^1.4.0"
+    optimist "^0.6.1"
+    source-map "^0.4.4"
+  optionalDependencies:
+    uglify-js "^2.6"
+
+har-schema@^1.0.5:
+  version "1.0.5"
+  resolved "https://registry.yarnpkg.com/har-schema/-/har-schema-1.0.5.tgz#d263135f43307c02c602afc8fe95970c0151369e"
+
+har-schema@^2.0.0:
+  version "2.0.0"
+  resolved "https://registry.yarnpkg.com/har-schema/-/har-schema-2.0.0.tgz#a94c2224ebcac04782a0d9035521f24735b7ec92"
+
+har-validator@^1.4.0:
+  version "1.8.0"
+  resolved "https://registry.yarnpkg.com/har-validator/-/har-validator-1.8.0.tgz#d83842b0eb4c435960aeb108a067a3aa94c0eeb2"
+  dependencies:
+    bluebird "^2.9.30"
+    chalk "^1.0.0"
+    commander "^2.8.1"
+    is-my-json-valid "^2.12.0"
+
+har-validator@~2.0.6:
+  version "2.0.6"
+  resolved "https://registry.yarnpkg.com/har-validator/-/har-validator-2.0.6.tgz#cdcbc08188265ad119b6a5a7c8ab70eecfb5d27d"
+  dependencies:
+    chalk "^1.1.1"
+    commander "^2.9.0"
+    is-my-json-valid "^2.12.4"
+    pinkie-promise "^2.0.0"
+
+har-validator@~4.2.1:
+  version "4.2.1"
+  resolved "https://registry.yarnpkg.com/har-validator/-/har-validator-4.2.1.tgz#33481d0f1bbff600dd203d75812a6a5fba002e2a"
+  dependencies:
+    ajv "^4.9.1"
+    har-schema "^1.0.5"
+
+har-validator@~5.0.3:
+  version "5.0.3"
+  resolved "https://registry.yarnpkg.com/har-validator/-/har-validator-5.0.3.tgz#ba402c266194f15956ef15e0fcf242993f6a7dfd"
+  dependencies:
+    ajv "^5.1.0"
+    har-schema "^2.0.0"
+
+has-ansi@^2.0.0:
+  version "2.0.0"
+  resolved "https://registry.yarnpkg.com/has-ansi/-/has-ansi-2.0.0.tgz#34f5049ce1ecdf2b0649af3ef24e45ed35416d91"
+  dependencies:
+    ansi-regex "^2.0.0"
+
+has-binary@0.1.7:
+  version "0.1.7"
+  resolved "https://registry.yarnpkg.com/has-binary/-/has-binary-0.1.7.tgz#68e61eb16210c9545a0a5cce06a873912fe1e68c"
+  dependencies:
+    isarray "0.0.1"
+
+has-cors@1.1.0:
+  version "1.1.0"
+  resolved "https://registry.yarnpkg.com/has-cors/-/has-cors-1.1.0.tgz#5e474793f7ea9843d1bb99c23eef49ff126fff39"
+
+has-flag@^1.0.0:
+  version "1.0.0"
+  resolved "https://registry.yarnpkg.com/has-flag/-/has-flag-1.0.0.tgz#9d9e793165ce017a00f00418c43f942a7b1d11fa"
+
+has-flag@^3.0.0:
+  version "3.0.0"
+  resolved "https://registry.yarnpkg.com/has-flag/-/has-flag-3.0.0.tgz#b5d454dc2199ae225699f3467e5a07f3b955bafd"
+
+has-unicode@^2.0.0:
+  version "2.0.1"
+  resolved "https://registry.yarnpkg.com/has-unicode/-/has-unicode-2.0.1.tgz#e0e6fe6a28cf51138855e086d1691e771de2a8b9"
+
+hasha@^2.2.0:
+  version "2.2.0"
+  resolved "https://registry.yarnpkg.com/hasha/-/hasha-2.2.0.tgz#78d7cbfc1e6d66303fe79837365984517b2f6ee1"
+  dependencies:
+    is-stream "^1.0.1"
+    pinkie-promise "^2.0.0"
+
+hawk@3.1.3, hawk@~3.1.3:
+  version "3.1.3"
+  resolved "https://registry.yarnpkg.com/hawk/-/hawk-3.1.3.tgz#078444bd7c1640b0fe540d2c9b73d59678e8e1c4"
+  dependencies:
+    boom "2.x.x"
+    cryptiles "2.x.x"
+    hoek "2.x.x"
+    sntp "1.x.x"
+
+hawk@~2.3.0:
+  version "2.3.1"
+  resolved "https://registry.yarnpkg.com/hawk/-/hawk-2.3.1.tgz#1e731ce39447fa1d0f6d707f7bceebec0fd1ec1f"
+  dependencies:
+    boom "2.x.x"
+    cryptiles "2.x.x"
+    hoek "2.x.x"
+    sntp "1.x.x"
+
+hawk@~6.0.2:
+  version "6.0.2"
+  resolved "https://registry.yarnpkg.com/hawk/-/hawk-6.0.2.tgz#af4d914eb065f9b5ce4d9d11c1cb2126eecc3038"
+  dependencies:
+    boom "4.x.x"
+    cryptiles "3.x.x"
+    hoek "4.x.x"
+    sntp "2.x.x"
+
+hoek@2.x.x:
+  version "2.16.3"
+  resolved "https://registry.yarnpkg.com/hoek/-/hoek-2.16.3.tgz#20bb7403d3cea398e91dc4710a8ff1b8274a25ed"
+
+hoek@4.x.x:
+  version "4.2.1"
+  resolved "https://registry.yarnpkg.com/hoek/-/hoek-4.2.1.tgz#9634502aa12c445dd5a7c5734b572bb8738aacbb"
+
+home-or-tmp@^2.0.0:
+  version "2.0.0"
+  resolved "https://registry.yarnpkg.com/home-or-tmp/-/home-or-tmp-2.0.0.tgz#e36c3f2d2cae7d746a857e38d18d5f32a7882db8"
+  dependencies:
+    os-homedir "^1.0.0"
+    os-tmpdir "^1.0.1"
+
+hooker@~0.2.3:
+  version "0.2.3"
+  resolved "https://registry.yarnpkg.com/hooker/-/hooker-0.2.3.tgz#b834f723cc4a242aa65963459df6d984c5d3d959"
+
+hosted-git-info@^2.1.4:
+  version "2.5.0"
+  resolved "https://registry.yarnpkg.com/hosted-git-info/-/hosted-git-info-2.5.0.tgz#6d60e34b3abbc8313062c3b798ef8d901a07af3c"
+
+http-errors@1.6.2, http-errors@~1.6.2:
+  version "1.6.2"
+  resolved "https://registry.yarnpkg.com/http-errors/-/http-errors-1.6.2.tgz#0a002cc85707192a7e7946ceedc11155f60ec736"
+  dependencies:
+    depd "1.1.1"
+    inherits "2.0.3"
+    setprototypeof "1.0.3"
+    statuses ">= 1.3.1 < 2"
+
+http-errors@~1.3.1:
+  version "1.3.1"
+  resolved "https://registry.yarnpkg.com/http-errors/-/http-errors-1.3.1.tgz#197e22cdebd4198585e8694ef6786197b91ed942"
+  dependencies:
+    inherits "~2.0.1"
+    statuses "1"
+
+http-parser-js@>=0.4.0:
+  version "0.4.10"
+  resolved "https://registry.yarnpkg.com/http-parser-js/-/http-parser-js-0.4.10.tgz#92c9c1374c35085f75db359ec56cc257cbb93fa4"
+
+http-proxy-middleware@~0.17.1:
+  version "0.17.4"
+  resolved "https://registry.yarnpkg.com/http-proxy-middleware/-/http-proxy-middleware-0.17.4.tgz#642e8848851d66f09d4f124912846dbaeb41b833"
+  dependencies:
+    http-proxy "^1.16.2"
+    is-glob "^3.1.0"
+    lodash "^4.17.2"
+    micromatch "^2.3.11"
+
+http-proxy@^1.13.0, http-proxy@^1.16.2:
+  version "1.16.2"
+  resolved "https://registry.yarnpkg.com/http-proxy/-/http-proxy-1.16.2.tgz#06dff292952bf64dbe8471fa9df73066d4f37742"
+  dependencies:
+    eventemitter3 "1.x.x"
+    requires-port "1.x.x"
+
+http-signature@~0.10.0:
+  version "0.10.1"
+  resolved "https://registry.yarnpkg.com/http-signature/-/http-signature-0.10.1.tgz#4fbdac132559aa8323121e540779c0a012b27e66"
+  dependencies:
+    asn1 "0.1.11"
+    assert-plus "^0.1.5"
+    ctype "0.5.3"
+
+http-signature@~1.1.0:
+  version "1.1.1"
+  resolved "https://registry.yarnpkg.com/http-signature/-/http-signature-1.1.1.tgz#df72e267066cd0ac67fb76adf8e134a8fbcf91bf"
+  dependencies:
+    assert-plus "^0.2.0"
+    jsprim "^1.2.2"
+    sshpk "^1.7.0"
+
+http-signature@~1.2.0:
+  version "1.2.0"
+  resolved "https://registry.yarnpkg.com/http-signature/-/http-signature-1.2.0.tgz#9aecd925114772f3d95b65a60abb8f7c18fbace1"
+  dependencies:
+    assert-plus "^1.0.0"
+    jsprim "^1.2.2"
+    sshpk "^1.7.0"
+
+https-browserify@0.0.1:
+  version "0.0.1"
+  resolved "https://registry.yarnpkg.com/https-browserify/-/https-browserify-0.0.1.tgz#3f91365cabe60b77ed0ebba24b454e3e09d95a82"
+
+https-proxy-agent@^1.0.0:
+  version "1.0.0"
+  resolved "https://registry.yarnpkg.com/https-proxy-agent/-/https-proxy-agent-1.0.0.tgz#35f7da6c48ce4ddbfa264891ac593ee5ff8671e6"
+  dependencies:
+    agent-base "2"
+    debug "2"
+    extend "3"
+
+iconv-lite@0.4.13:
+  version "0.4.13"
+  resolved "https://registry.yarnpkg.com/iconv-lite/-/iconv-lite-0.4.13.tgz#1f88aba4ab0b1508e8312acc39345f36e992e2f2"
+
+iconv-lite@0.4.19:
+  version "0.4.19"
+  resolved "https://registry.yarnpkg.com/iconv-lite/-/iconv-lite-0.4.19.tgz#f7468f60135f5e5dad3399c0a81be9a1603a082b"
+
+iconv-lite@~0.2.11:
+  version "0.2.11"
+  resolved "https://registry.yarnpkg.com/iconv-lite/-/iconv-lite-0.2.11.tgz#1ce60a3a57864a292d1321ff4609ca4bb965adc8"
+
+ieee754@^1.1.4:
+  version "1.1.8"
+  resolved "https://registry.yarnpkg.com/ieee754/-/ieee754-1.1.8.tgz#be33d40ac10ef1926701f6f08a2d86fbfd1ad3e4"
+
+imurmurhash@^0.1.4:
+  version "0.1.4"
+  resolved "https://registry.yarnpkg.com/imurmurhash/-/imurmurhash-0.1.4.tgz#9218b9b2b928a238b13dc4fb6b6d576f231453ea"
+
+indent-string@^2.1.0:
+  version "2.1.0"
+  resolved "https://registry.yarnpkg.com/indent-string/-/indent-string-2.1.0.tgz#8e2d48348742121b4a8218b7a137e9a52049dc80"
+  dependencies:
+    repeating "^2.0.0"
+
+indexof@0.0.1:
+  version "0.0.1"
+  resolved "https://registry.yarnpkg.com/indexof/-/indexof-0.0.1.tgz#82dc336d232b9062179d05ab3293a66059fd435d"
+
+inflight@^1.0.4:
+  version "1.0.6"
+  resolved "https://registry.yarnpkg.com/inflight/-/inflight-1.0.6.tgz#49bd6331d7d02d0c09bc910a1075ba8165b56df9"
+  dependencies:
+    once "^1.3.0"
+    wrappy "1"
+
+inherits@1:
+  version "1.0.2"
+  resolved "https://registry.yarnpkg.com/inherits/-/inherits-1.0.2.tgz#ca4309dadee6b54cc0b8d247e8d7c7a0975bdc9b"
+
+inherits@2, inherits@2.0.3, inherits@^2.0.1, inherits@^2.0.3, inherits@~2.0.0, inherits@~2.0.1, inherits@~2.0.3:
+  version "2.0.3"
+  resolved "https://registry.yarnpkg.com/inherits/-/inherits-2.0.3.tgz#633c2c83e3da42a502f52466022480f4208261de"
+
+inherits@2.0.1:
+  version "2.0.1"
+  resolved "https://registry.yarnpkg.com/inherits/-/inherits-2.0.1.tgz#b17d08d326b4423e568eff719f91b0b1cbdf69f1"
+
+ini@~1.3.0:
+  version "1.3.5"
+  resolved "https://registry.yarnpkg.com/ini/-/ini-1.3.5.tgz#eee25f56db1c9ec6085e0c22778083f596abf927"
+
+inquirer@^0.11.0:
+  version "0.11.4"
+  resolved "https://registry.yarnpkg.com/inquirer/-/inquirer-0.11.4.tgz#81e3374e8361beaff2d97016206d359d0b32fa4d"
+  dependencies:
+    ansi-escapes "^1.1.0"
+    ansi-regex "^2.0.0"
+    chalk "^1.0.0"
+    cli-cursor "^1.0.1"
+    cli-width "^1.0.1"
+    figures "^1.3.5"
+    lodash "^3.3.1"
+    readline2 "^1.0.1"
+    run-async "^0.1.0"
+    rx-lite "^3.1.2"
+    string-width "^1.0.1"
+    strip-ansi "^3.0.0"
+    through "^2.3.6"
+
+interpret@^0.6.4:
+  version "0.6.6"
+  resolved "https://registry.yarnpkg.com/interpret/-/interpret-0.6.6.tgz#fecd7a18e7ce5ca6abfb953e1f86213a49f1625b"
+
+invariant@^2.2.2:
+  version "2.2.3"
+  resolved "https://registry.yarnpkg.com/invariant/-/invariant-2.2.3.tgz#1a827dfde7dcbd7c323f0ca826be8fa7c5e9d688"
+  dependencies:
+    loose-envify "^1.0.0"
+
+invert-kv@^1.0.0:
+  version "1.0.0"
+  resolved "https://registry.yarnpkg.com/invert-kv/-/invert-kv-1.0.0.tgz#104a8e4aaca6d3d8cd157a8ef8bfab2d7a3ffdb6"
+
+ipaddr.js@1.6.0:
+  version "1.6.0"
+  resolved "https://registry.yarnpkg.com/ipaddr.js/-/ipaddr.js-1.6.0.tgz#e3fa357b773da619f26e95f049d055c72796f86b"
+
+is-arrayish@^0.2.1:
+  version "0.2.1"
+  resolved "https://registry.yarnpkg.com/is-arrayish/-/is-arrayish-0.2.1.tgz#77c99840527aa8ecb1a8ba697b80645a7a926a9d"
+
+is-binary-path@^1.0.0:
+  version "1.0.1"
+  resolved "https://registry.yarnpkg.com/is-binary-path/-/is-binary-path-1.0.1.tgz#75f16642b480f187a711c814161fd3a4a7655898"
+  dependencies:
+    binary-extensions "^1.0.0"
+
+is-buffer@^1.1.5:
+  version "1.1.6"
+  resolved "https://registry.yarnpkg.com/is-buffer/-/is-buffer-1.1.6.tgz#efaa2ea9daa0d7ab2ea13a97b2b8ad51fefbe8be"
+
+is-builtin-module@^1.0.0:
+  version "1.0.0"
+  resolved "https://registry.yarnpkg.com/is-builtin-module/-/is-builtin-module-1.0.0.tgz#540572d34f7ac3119f8f76c30cbc1b1e037affbe"
+  dependencies:
+    builtin-modules "^1.0.0"
+
+is-dotfile@^1.0.0:
+  version "1.0.3"
+  resolved "https://registry.yarnpkg.com/is-dotfile/-/is-dotfile-1.0.3.tgz#a6a2f32ffd2dfb04f5ca25ecd0f6b83cf798a1e1"
+
+is-equal-shallow@^0.1.3:
+  version "0.1.3"
+  resolved "https://registry.yarnpkg.com/is-equal-shallow/-/is-equal-shallow-0.1.3.tgz#2238098fc221de0bcfa5d9eac4c45d638aa1c534"
+  dependencies:
+    is-primitive "^2.0.0"
+
+is-extendable@^0.1.1:
+  version "0.1.1"
+  resolved "https://registry.yarnpkg.com/is-extendable/-/is-extendable-0.1.1.tgz#62b110e289a471418e3ec36a617d472e301dfc89"
+
+is-extglob@^1.0.0:
+  version "1.0.0"
+  resolved "https://registry.yarnpkg.com/is-extglob/-/is-extglob-1.0.0.tgz#ac468177c4943405a092fc8f29760c6ffc6206c0"
+
+is-extglob@^2.1.0:
+  version "2.1.1"
+  resolved "https://registry.yarnpkg.com/is-extglob/-/is-extglob-2.1.1.tgz#a88c02535791f02ed37c76a1b9ea9773c833f8c2"
+
+is-finite@^1.0.0:
+  version "1.0.2"
+  resolved "https://registry.yarnpkg.com/is-finite/-/is-finite-1.0.2.tgz#cc6677695602be550ef11e8b4aa6305342b6d0aa"
+  dependencies:
+    number-is-nan "^1.0.0"
+
+is-fullwidth-code-point@^1.0.0:
+  version "1.0.0"
+  resolved "https://registry.yarnpkg.com/is-fullwidth-code-point/-/is-fullwidth-code-point-1.0.0.tgz#ef9e31386f031a7f0d643af82fde50c457ef00cb"
+  dependencies:
+    number-is-nan "^1.0.0"
+
+is-fullwidth-code-point@^2.0.0:
+  version "2.0.0"
+  resolved "https://registry.yarnpkg.com/is-fullwidth-code-point/-/is-fullwidth-code-point-2.0.0.tgz#a3b30a5c4f199183167aaab93beefae3ddfb654f"
+
+is-glob@^2.0.0, is-glob@^2.0.1:
+  version "2.0.1"
+  resolved "https://registry.yarnpkg.com/is-glob/-/is-glob-2.0.1.tgz#d096f926a3ded5600f3fdfd91198cb0888c2d863"
+  dependencies:
+    is-extglob "^1.0.0"
+
+is-glob@^3.1.0:
+  version "3.1.0"
+  resolved "https://registry.yarnpkg.com/is-glob/-/is-glob-3.1.0.tgz#7ba5ae24217804ac70707b96922567486cc3e84a"
+  dependencies:
+    is-extglob "^2.1.0"
+
+is-my-ip-valid@^1.0.0:
+  version "1.0.0"
+  resolved "https://registry.yarnpkg.com/is-my-ip-valid/-/is-my-ip-valid-1.0.0.tgz#7b351b8e8edd4d3995d4d066680e664d94696824"
+
+is-my-json-valid@^2.10.0, is-my-json-valid@^2.12.0, is-my-json-valid@^2.12.4:
+  version "2.17.2"
+  resolved "https://registry.yarnpkg.com/is-my-json-valid/-/is-my-json-valid-2.17.2.tgz#6b2103a288e94ef3de5cf15d29dd85fc4b78d65c"
+  dependencies:
+    generate-function "^2.0.0"
+    generate-object-property "^1.1.0"
+    is-my-ip-valid "^1.0.0"
+    jsonpointer "^4.0.0"
+    xtend "^4.0.0"
+
+is-number@^0.1.1:
+  version "0.1.1"
+  resolved "https://registry.yarnpkg.com/is-number/-/is-number-0.1.1.tgz#69a7af116963d47206ec9bd9b48a14216f1e3806"
+
+is-number@^2.1.0:
+  version "2.1.0"
+  resolved "https://registry.yarnpkg.com/is-number/-/is-number-2.1.0.tgz#01fcbbb393463a548f2f466cce16dece49db908f"
+  dependencies:
+    kind-of "^3.0.2"
+
+is-number@^3.0.0:
+  version "3.0.0"
+  resolved "https://registry.yarnpkg.com/is-number/-/is-number-3.0.0.tgz#24fd6201a4782cf50561c810276afc7d12d71195"
+  dependencies:
+    kind-of "^3.0.2"
+
+is-path-cwd@^1.0.0:
+  version "1.0.0"
+  resolved "https://registry.yarnpkg.com/is-path-cwd/-/is-path-cwd-1.0.0.tgz#d225ec23132e89edd38fda767472e62e65f1106d"
+
+is-path-in-cwd@^1.0.0:
+  version "1.0.0"
+  resolved "https://registry.yarnpkg.com/is-path-in-cwd/-/is-path-in-cwd-1.0.0.tgz#6477582b8214d602346094567003be8a9eac04dc"
+  dependencies:
+    is-path-inside "^1.0.0"
+
+is-path-inside@^1.0.0:
+  version "1.0.1"
+  resolved "https://registry.yarnpkg.com/is-path-inside/-/is-path-inside-1.0.1.tgz#8ef5b7de50437a3fdca6b4e865ef7aa55cb48036"
+  dependencies:
+    path-is-inside "^1.0.1"
+
+is-posix-bracket@^0.1.0:
+  version "0.1.1"
+  resolved "https://registry.yarnpkg.com/is-posix-bracket/-/is-posix-bracket-0.1.1.tgz#3334dc79774368e92f016e6fbc0a88f5cd6e6bc4"
+
+is-primitive@^2.0.0:
+  version "2.0.0"
+  resolved "https://registry.yarnpkg.com/is-primitive/-/is-primitive-2.0.0.tgz#207bab91638499c07b2adf240a41a87210034575"
+
+is-property@^1.0.0:
+  version "1.0.2"
+  resolved "https://registry.yarnpkg.com/is-property/-/is-property-1.0.2.tgz#57fe1c4e48474edd65b09911f26b1cd4095dda84"
+
+is-resolvable@^1.0.0:
+  version "1.1.0"
+  resolved "https://registry.yarnpkg.com/is-resolvable/-/is-resolvable-1.1.0.tgz#fb18f87ce1feb925169c9a407c19318a3206ed88"
+
+is-stream@^1.0.1, is-stream@^1.1.0:
+  version "1.1.0"
+  resolved "https://registry.yarnpkg.com/is-stream/-/is-stream-1.1.0.tgz#12d4a3dd4e68e0b79ceb8dbc84173ae80d91ca44"
+
+is-typedarray@~1.0.0:
+  version "1.0.0"
+  resolved "https://registry.yarnpkg.com/is-typedarray/-/is-typedarray-1.0.0.tgz#e479c80858df0c1b11ddda6940f96011fcda4a9a"
+
+is-utf8@^0.2.0:
+  version "0.2.1"
+  resolved "https://registry.yarnpkg.com/is-utf8/-/is-utf8-0.2.1.tgz#4b0da1442104d1b336340e80797e865cf39f7d72"
+
+isarray@0.0.1:
+  version "0.0.1"
+  resolved "https://registry.yarnpkg.com/isarray/-/isarray-0.0.1.tgz#8a18acfca9a8f4177e09abfc6038939b05d1eedf"
+
+isarray@1.0.0, isarray@^1.0.0, isarray@~1.0.0:
+  version "1.0.0"
+  resolved "https://registry.yarnpkg.com/isarray/-/isarray-1.0.0.tgz#bb935d48582cba168c06834957a54a3e07124f11"
+
+isbinaryfile@^3.0.0:
+  version "3.0.2"
+  resolved "https://registry.yarnpkg.com/isbinaryfile/-/isbinaryfile-3.0.2.tgz#4a3e974ec0cba9004d3fc6cde7209ea69368a621"
+
+isexe@^2.0.0:
+  version "2.0.0"
+  resolved "https://registry.yarnpkg.com/isexe/-/isexe-2.0.0.tgz#e8fbf374dc556ff8947a10dcb0572d633f2cfa10"
+
+isobject@^2.0.0:
+  version "2.1.0"
+  resolved "https://registry.yarnpkg.com/isobject/-/isobject-2.1.0.tgz#f065561096a3f1da2ef46272f815c840d87e0c89"
+  dependencies:
+    isarray "1.0.0"
+
+isstream@~0.1.1, isstream@~0.1.2:
+  version "0.1.2"
+  resolved "https://registry.yarnpkg.com/isstream/-/isstream-0.1.2.tgz#47e63f7af55afa6f92e1500e690eb8b8529c099a"
+
+istanbul-lib-coverage@^1.1.1, istanbul-lib-coverage@^1.1.2:
+  version "1.1.2"
+  resolved "https://registry.yarnpkg.com/istanbul-lib-coverage/-/istanbul-lib-coverage-1.1.2.tgz#4113c8ff6b7a40a1ef7350b01016331f63afde14"
+
+istanbul-lib-hook@^1.1.0:
+  version "1.1.0"
+  resolved "https://registry.yarnpkg.com/istanbul-lib-hook/-/istanbul-lib-hook-1.1.0.tgz#8538d970372cb3716d53e55523dd54b557a8d89b"
+  dependencies:
+    append-transform "^0.4.0"
+
+istanbul-lib-instrument@^1.9.1:
+  version "1.9.2"
+  resolved "https://registry.yarnpkg.com/istanbul-lib-instrument/-/istanbul-lib-instrument-1.9.2.tgz#84905bf47f7e0b401d6b840da7bad67086b4aab6"
+  dependencies:
+    babel-generator "^6.18.0"
+    babel-template "^6.16.0"
+    babel-traverse "^6.18.0"
+    babel-types "^6.18.0"
+    babylon "^6.18.0"
+    istanbul-lib-coverage "^1.1.2"
+    semver "^5.3.0"
+
+istanbul-lib-report@^1.1.2:
+  version "1.1.3"
+  resolved "https://registry.yarnpkg.com/istanbul-lib-report/-/istanbul-lib-report-1.1.3.tgz#2df12188c0fa77990c0d2176d2d0ba3394188259"
+  dependencies:
+    istanbul-lib-coverage "^1.1.2"
+    mkdirp "^0.5.1"
+    path-parse "^1.0.5"
+    supports-color "^3.1.2"
+
+istanbul-lib-source-maps@^1.2.2:
+  version "1.2.3"
+  resolved "https://registry.yarnpkg.com/istanbul-lib-source-maps/-/istanbul-lib-source-maps-1.2.3.tgz#20fb54b14e14b3fb6edb6aca3571fd2143db44e6"
+  dependencies:
+    debug "^3.1.0"
+    istanbul-lib-coverage "^1.1.2"
+    mkdirp "^0.5.1"
+    rimraf "^2.6.1"
+    source-map "^0.5.3"
+
+istanbul-reports@^1.1.3:
+  version "1.1.4"
+  resolved "https://registry.yarnpkg.com/istanbul-reports/-/istanbul-reports-1.1.4.tgz#5ccba5e22b7b5a5d91d5e0a830f89be334bf97bd"
+  dependencies:
+    handlebars "^4.0.3"
+
+"istanbul@github:kpdecker/istanbul":
+  version "0.4.0"
+  resolved "https://codeload.github.com/kpdecker/istanbul/tar.gz/dd1228d2f0a6e8506cbb5dba398a8297b1dbaf22"
+  dependencies:
+    abbrev "1.0.x"
+    async "1.x"
+    convert-source-map "^1.1.1"
+    escodegen "1.7.x"
+    esprima "2.5.x"
+    fileset "0.2.x"
+    handlebars "^4.0.1"
+    js-yaml "3.x"
+    mkdirp "0.5.x"
+    nopt "3.x"
+    once "1.x"
+    resolve "1.1.x"
+    source-map "^0.4.4"
+    source-map-support "^0.3.2"
+    supports-color "^3.1.0"
+    which "^1.1.1"
+    wordwrap "^1.0.0"
+
+jade@0.26.3:
+  version "0.26.3"
+  resolved "https://registry.yarnpkg.com/jade/-/jade-0.26.3.tgz#8f10d7977d8d79f2f6ff862a81b0513ccb25686c"
+  dependencies:
+    commander "0.6.1"
+    mkdirp "0.3.0"
+
+js-tokens@^3.0.0, js-tokens@^3.0.2:
+  version "3.0.2"
+  resolved "https://registry.yarnpkg.com/js-tokens/-/js-tokens-3.0.2.tgz#9866df395102130e38f7f996bceb65443209c25b"
+
+js-yaml@3.4.5:
+  version "3.4.5"
+  resolved "https://registry.yarnpkg.com/js-yaml/-/js-yaml-3.4.5.tgz#c3403797df12b91866574f2de23646fe8cafb44d"
+  dependencies:
+    argparse "^1.0.2"
+    esprima "^2.6.0"
+
+js-yaml@3.6.1:
+  version "3.6.1"
+  resolved "https://registry.yarnpkg.com/js-yaml/-/js-yaml-3.6.1.tgz#6e5fe67d8b205ce4d22fad05b7781e8dadcc4b30"
+  dependencies:
+    argparse "^1.0.7"
+    esprima "^2.6.0"
+
+js-yaml@3.x, js-yaml@^3.10.0, js-yaml@^3.2.7, js-yaml@^3.3.1:
+  version "3.10.0"
+  resolved "https://registry.yarnpkg.com/js-yaml/-/js-yaml-3.10.0.tgz#2e78441646bd4682e963f22b6e92823c309c62dc"
+  dependencies:
+    argparse "^1.0.7"
+    esprima "^4.0.0"
+
+js-yaml@~2.0.5:
+  version "2.0.5"
+  resolved "https://registry.yarnpkg.com/js-yaml/-/js-yaml-2.0.5.tgz#a25ae6509999e97df278c6719da11bd0687743a8"
+  dependencies:
+    argparse "~ 0.1.11"
+    esprima "~ 1.0.2"
+
+jsbn@~0.1.0:
+  version "0.1.1"
+  resolved "https://registry.yarnpkg.com/jsbn/-/jsbn-0.1.1.tgz#a5e654c2e5a2deb5f201d96cefbca80c0ef2f513"
+
+jsesc@^1.3.0:
+  version "1.3.0"
+  resolved "https://registry.yarnpkg.com/jsesc/-/jsesc-1.3.0.tgz#46c3fec8c1892b12b0833db9bc7622176dbab34b"
+
+jsesc@~0.5.0:
+  version "0.5.0"
+  resolved "https://registry.yarnpkg.com/jsesc/-/jsesc-0.5.0.tgz#e7dee66e35d6fc16f710fe91d5cf69f70f08911d"
+
+jshint@~0.9.1:
+  version "0.9.1"
+  resolved "https://registry.yarnpkg.com/jshint/-/jshint-0.9.1.tgz#ff32ec7f09f84001f7498eeafd63c9e4fbb2dc0e"
+  dependencies:
+    cli "0.4.3"
+    minimatch "0.0.x"
+
+json-schema-traverse@^0.3.0:
+  version "0.3.1"
+  resolved "https://registry.yarnpkg.com/json-schema-traverse/-/json-schema-traverse-0.3.1.tgz#349a6d44c53a51de89b40805c5d5e59b417d3340"
+
+json-schema@0.2.3:
+  version "0.2.3"
+  resolved "https://registry.yarnpkg.com/json-schema/-/json-schema-0.2.3.tgz#b480c892e59a2f05954ce727bd3f2a4e882f9e13"
+
+json-stable-stringify@^1.0.0, json-stable-stringify@^1.0.1:
+  version "1.0.1"
+  resolved "https://registry.yarnpkg.com/json-stable-stringify/-/json-stable-stringify-1.0.1.tgz#9a759d39c5f2ff503fd5300646ed445f88c4f9af"
+  dependencies:
+    jsonify "~0.0.0"
+
+json-stringify-safe@~5.0.0, json-stringify-safe@~5.0.1:
+  version "5.0.1"
+  resolved "https://registry.yarnpkg.com/json-stringify-safe/-/json-stringify-safe-5.0.1.tgz#1296a2d58fd45f19a0f6ce01d65701e2c735b6eb"
+
+json3@3.3.2, json3@^3.3.2:
+  version "3.3.2"
+  resolved "https://registry.yarnpkg.com/json3/-/json3-3.3.2.tgz#3c0434743df93e2f5c42aee7b19bcb483575f4e1"
+
+json5@^0.5.0, json5@^0.5.1:
+  version "0.5.1"
+  resolved "https://registry.yarnpkg.com/json5/-/json5-0.5.1.tgz#1eade7acc012034ad84e2396767ead9fa5495821"
+
+jsonfile@^2.1.0:
+  version "2.4.0"
+  resolved "https://registry.yarnpkg.com/jsonfile/-/jsonfile-2.4.0.tgz#3736a2b428b87bbda0cc83b53fa3d633a35c2ae8"
+  optionalDependencies:
+    graceful-fs "^4.1.6"
+
+jsonify@~0.0.0:
+  version "0.0.0"
+  resolved "https://registry.yarnpkg.com/jsonify/-/jsonify-0.0.0.tgz#2c74b6ee41d93ca51b7b5aaee8f503631d252a73"
+
+jsonpointer@^4.0.0:
+  version "4.0.1"
+  resolved "https://registry.yarnpkg.com/jsonpointer/-/jsonpointer-4.0.1.tgz#4fd92cb34e0e9db3c89c8622ecf51f9b978c6cb9"
+
+jsprim@^1.2.2:
+  version "1.4.1"
+  resolved "https://registry.yarnpkg.com/jsprim/-/jsprim-1.4.1.tgz#313e66bc1e5cc06e438bc1b7499c2e5c56acb6a2"
+  dependencies:
+    assert-plus "1.0.0"
+    extsprintf "1.3.0"
+    json-schema "0.2.3"
+    verror "1.10.0"
+
+karma-mocha-reporter@^2.0.0:
+  version "2.2.5"
+  resolved "https://registry.yarnpkg.com/karma-mocha-reporter/-/karma-mocha-reporter-2.2.5.tgz#15120095e8ed819186e47a0b012f3cd741895560"
+  dependencies:
+    chalk "^2.1.0"
+    log-symbols "^2.1.0"
+    strip-ansi "^4.0.0"
+
+karma-mocha@^0.2.0:
+  version "0.2.2"
+  resolved "https://registry.yarnpkg.com/karma-mocha/-/karma-mocha-0.2.2.tgz#388ed917da15dcb196d1b915c1934ef803193f8e"
+
+karma-phantomjs-launcher@^1.0.0:
+  version "1.0.4"
+  resolved "https://registry.yarnpkg.com/karma-phantomjs-launcher/-/karma-phantomjs-launcher-1.0.4.tgz#d23ca34801bda9863ad318e3bb4bd4062b13acd2"
+  dependencies:
+    lodash "^4.0.1"
+    phantomjs-prebuilt "^2.1.7"
+
+karma-sauce-launcher@^0.3.0:
+  version "0.3.1"
+  resolved "https://registry.yarnpkg.com/karma-sauce-launcher/-/karma-sauce-launcher-0.3.1.tgz#fa41f6afd1ad6cb7610885da83cbc9921a4d334c"
+  dependencies:
+    q "^1.4.1"
+    sauce-connect-launcher "^0.13.0"
+    saucelabs "^1.0.1"
+    wd "^0.3.4"
+
+karma-sourcemap-loader@^0.3.6:
+  version "0.3.7"
+  resolved "https://registry.yarnpkg.com/karma-sourcemap-loader/-/karma-sourcemap-loader-0.3.7.tgz#91322c77f8f13d46fed062b042e1009d4c4505d8"
+  dependencies:
+    graceful-fs "^4.1.2"
+
+karma-webpack@^1.7.0:
+  version "1.8.1"
+  resolved "https://registry.yarnpkg.com/karma-webpack/-/karma-webpack-1.8.1.tgz#39d5fd2edeea3cc3ef5b405989b37d5b0e6a3b4e"
+  dependencies:
+    async "~0.9.0"
+    loader-utils "^0.2.5"
+    lodash "^3.8.0"
+    source-map "^0.1.41"
+    webpack-dev-middleware "^1.0.11"
+
+karma@^0.13.11:
+  version "0.13.22"
+  resolved "https://registry.yarnpkg.com/karma/-/karma-0.13.22.tgz#07750b1bd063d7e7e7b91bcd2e6354d8f2aa8744"
+  dependencies:
+    batch "^0.5.3"
+    bluebird "^2.9.27"
+    body-parser "^1.12.4"
+    chokidar "^1.4.1"
+    colors "^1.1.0"
+    connect "^3.3.5"
+    core-js "^2.1.0"
+    di "^0.0.1"
+    dom-serialize "^2.2.0"
+    expand-braces "^0.1.1"
+    glob "^7.0.0"
+    graceful-fs "^4.1.2"
+    http-proxy "^1.13.0"
+    isbinaryfile "^3.0.0"
+    lodash "^3.8.0"
+    log4js "^0.6.31"
+    mime "^1.3.4"
+    minimatch "^3.0.0"
+    optimist "^0.6.1"
+    rimraf "^2.3.3"
+    socket.io "^1.4.5"
+    source-map "^0.5.3"
+    useragent "^2.1.6"
+
+kew@^0.7.0:
+  version "0.7.0"
+  resolved "https://registry.yarnpkg.com/kew/-/kew-0.7.0.tgz#79d93d2d33363d6fdd2970b335d9141ad591d79b"
+
+kind-of@^3.0.2:
+  version "3.2.2"
+  resolved "https://registry.yarnpkg.com/kind-of/-/kind-of-3.2.2.tgz#31ea21a734bab9bbb0f32466d893aea51e4a3c64"
+  dependencies:
+    is-buffer "^1.1.5"
+
+kind-of@^4.0.0:
+  version "4.0.0"
+  resolved "https://registry.yarnpkg.com/kind-of/-/kind-of-4.0.0.tgz#20813df3d712928b207378691a45066fae72dd57"
+  dependencies:
+    is-buffer "^1.1.5"
+
+klaw@^1.0.0:
+  version "1.3.1"
+  resolved "https://registry.yarnpkg.com/klaw/-/klaw-1.3.1.tgz#4088433b46b3b1ba259d78785d8e96f73ba02439"
+  optionalDependencies:
+    graceful-fs "^4.1.9"
+
+lazy-cache@^1.0.3:
+  version "1.0.4"
+  resolved "https://registry.yarnpkg.com/lazy-cache/-/lazy-cache-1.0.4.tgz#a1d78fc3a50474cb80845d3b3b6e1da49a446e8e"
+
+lazystream@~0.1.0:
+  version "0.1.0"
+  resolved "https://registry.yarnpkg.com/lazystream/-/lazystream-0.1.0.tgz#1b25d63c772a4c20f0a5ed0a9d77f484b6e16920"
+  dependencies:
+    readable-stream "~1.0.2"
+
+lcid@^1.0.0:
+  version "1.0.0"
+  resolved "https://registry.yarnpkg.com/lcid/-/lcid-1.0.0.tgz#308accafa0bc483a3867b4b6f2b9506251d1b835"
+  dependencies:
+    invert-kv "^1.0.0"
+
+lcov-parse@0.0.10:
+  version "0.0.10"
+  resolved "https://registry.yarnpkg.com/lcov-parse/-/lcov-parse-0.0.10.tgz#1b0b8ff9ac9c7889250582b70b71315d9da6d9a3"
+
+levn@~0.2.5:
+  version "0.2.5"
+  resolved "https://registry.yarnpkg.com/levn/-/levn-0.2.5.tgz#ba8d339d0ca4a610e3a3f145b9caf48807155054"
+  dependencies:
+    prelude-ls "~1.1.0"
+    type-check "~0.3.1"
+
+livereload-js@^2.2.0:
+  version "2.3.0"
+  resolved "https://registry.yarnpkg.com/livereload-js/-/livereload-js-2.3.0.tgz#c3ab22e8aaf5bf3505d80d098cbad67726548c9a"
+
+load-json-file@^1.0.0:
+  version "1.1.0"
+  resolved "https://registry.yarnpkg.com/load-json-file/-/load-json-file-1.1.0.tgz#956905708d58b4bab4c2261b04f59f31c99374c0"
+  dependencies:
+    graceful-fs "^4.1.2"
+    parse-json "^2.2.0"
+    pify "^2.0.0"
+    pinkie-promise "^2.0.0"
+    strip-bom "^2.0.0"
+
+loader-utils@^0.2.11, loader-utils@^0.2.16, loader-utils@^0.2.5:
+  version "0.2.17"
+  resolved "https://registry.yarnpkg.com/loader-utils/-/loader-utils-0.2.17.tgz#f86e6374d43205a6e6c60e9196f17c0299bfb348"
+  dependencies:
+    big.js "^3.1.3"
+    emojis-list "^2.0.0"
+    json5 "^0.5.0"
+    object-assign "^4.0.1"
+
+locate-path@^2.0.0:
+  version "2.0.0"
+  resolved "https://registry.yarnpkg.com/locate-path/-/locate-path-2.0.0.tgz#2b568b265eec944c6d9c0de9c3dbbbca0354cd8e"
+  dependencies:
+    p-locate "^2.0.0"
+    path-exists "^3.0.0"
+
+lodash._arraycopy@^3.0.0:
+  version "3.0.0"
+  resolved "https://registry.yarnpkg.com/lodash._arraycopy/-/lodash._arraycopy-3.0.0.tgz#76e7b7c1f1fb92547374878a562ed06a3e50f6e1"
+
+lodash._arrayeach@^3.0.0:
+  version "3.0.0"
+  resolved "https://registry.yarnpkg.com/lodash._arrayeach/-/lodash._arrayeach-3.0.0.tgz#bab156b2a90d3f1bbd5c653403349e5e5933ef9e"
+
+lodash._arraymap@^3.0.0:
+  version "3.0.0"
+  resolved "https://registry.yarnpkg.com/lodash._arraymap/-/lodash._arraymap-3.0.0.tgz#1a8fd0f4c0df4b61dea076d717cdc97f0a3c3e66"
+
+lodash._baseassign@^3.0.0:
+  version "3.2.0"
+  resolved "https://registry.yarnpkg.com/lodash._baseassign/-/lodash._baseassign-3.2.0.tgz#8c38a099500f215ad09e59f1722fd0c52bfe0a4e"
+  dependencies:
+    lodash._basecopy "^3.0.0"
+    lodash.keys "^3.0.0"
+
+lodash._baseclone@^3.0.0:
+  version "3.3.0"
+  resolved "https://registry.yarnpkg.com/lodash._baseclone/-/lodash._baseclone-3.3.0.tgz#303519bf6393fe7e42f34d8b630ef7794e3542b7"
+  dependencies:
+    lodash._arraycopy "^3.0.0"
+    lodash._arrayeach "^3.0.0"
+    lodash._baseassign "^3.0.0"
+    lodash._basefor "^3.0.0"
+    lodash.isarray "^3.0.0"
+    lodash.keys "^3.0.0"
+
+lodash._basecopy@^3.0.0:
+  version "3.0.1"
+  resolved "https://registry.yarnpkg.com/lodash._basecopy/-/lodash._basecopy-3.0.1.tgz#8da0e6a876cf344c0ad8a54882111dd3c5c7ca36"
+
+lodash._basedifference@^3.0.0:
+  version "3.0.3"
+  resolved "https://registry.yarnpkg.com/lodash._basedifference/-/lodash._basedifference-3.0.3.tgz#f2c204296c2a78e02b389081b6edcac933cf629c"
+  dependencies:
+    lodash._baseindexof "^3.0.0"
+    lodash._cacheindexof "^3.0.0"
+    lodash._createcache "^3.0.0"
+
+lodash._baseflatten@^3.0.0:
+  version "3.1.4"
+  resolved "https://registry.yarnpkg.com/lodash._baseflatten/-/lodash._baseflatten-3.1.4.tgz#0770ff80131af6e34f3b511796a7ba5214e65ff7"
+  dependencies:
+    lodash.isarguments "^3.0.0"
+    lodash.isarray "^3.0.0"
+
+lodash._basefor@^3.0.0:
+  version "3.0.3"
+  resolved "https://registry.yarnpkg.com/lodash._basefor/-/lodash._basefor-3.0.3.tgz#7550b4e9218ef09fad24343b612021c79b4c20c2"
+
+lodash._baseindexof@^3.0.0:
+  version "3.1.0"
+  resolved "https://registry.yarnpkg.com/lodash._baseindexof/-/lodash._baseindexof-3.1.0.tgz#fe52b53a1c6761e42618d654e4a25789ed61822c"
+
+lodash._bindcallback@^3.0.0:
+  version "3.0.1"
+  resolved "https://registry.yarnpkg.com/lodash._bindcallback/-/lodash._bindcallback-3.0.1.tgz#e531c27644cf8b57a99e17ed95b35c748789392e"
+
+lodash._cacheindexof@^3.0.0:
+  version "3.0.2"
+  resolved "https://registry.yarnpkg.com/lodash._cacheindexof/-/lodash._cacheindexof-3.0.2.tgz#3dc69ac82498d2ee5e3ce56091bafd2adc7bde92"
+
+lodash._createassigner@^3.0.0:
+  version "3.1.1"
+  resolved "https://registry.yarnpkg.com/lodash._createassigner/-/lodash._createassigner-3.1.1.tgz#838a5bae2fdaca63ac22dee8e19fa4e6d6970b11"
+  dependencies:
+    lodash._bindcallback "^3.0.0"
+    lodash._isiterateecall "^3.0.0"
+    lodash.restparam "^3.0.0"
+
+lodash._createcache@^3.0.0:
+  version "3.1.2"
+  resolved "https://registry.yarnpkg.com/lodash._createcache/-/lodash._createcache-3.1.2.tgz#56d6a064017625e79ebca6b8018e17440bdcf093"
+  dependencies:
+    lodash._getnative "^3.0.0"
+
+lodash._getnative@^3.0.0:
+  version "3.9.1"
+  resolved "https://registry.yarnpkg.com/lodash._getnative/-/lodash._getnative-3.9.1.tgz#570bc7dede46d61cdcde687d65d3eecbaa3aaff5"
+
+lodash._isiterateecall@^3.0.0:
+  version "3.0.9"
+  resolved "https://registry.yarnpkg.com/lodash._isiterateecall/-/lodash._isiterateecall-3.0.9.tgz#5203ad7ba425fae842460e696db9cf3e6aac057c"
+
+lodash._pickbyarray@^3.0.0:
+  version "3.0.2"
+  resolved "https://registry.yarnpkg.com/lodash._pickbyarray/-/lodash._pickbyarray-3.0.2.tgz#1f898d9607eb560b0e167384b77c7c6d108aa4c5"
+
+lodash._pickbycallback@^3.0.0:
+  version "3.0.0"
+  resolved "https://registry.yarnpkg.com/lodash._pickbycallback/-/lodash._pickbycallback-3.0.0.tgz#ff61b9a017a7b3af7d30e6c53de28afa19b8750a"
+  dependencies:
+    lodash._basefor "^3.0.0"
+    lodash.keysin "^3.0.0"
+
+lodash.clonedeep@^3.0.1:
+  version "3.0.2"
+  resolved "https://registry.yarnpkg.com/lodash.clonedeep/-/lodash.clonedeep-3.0.2.tgz#a0a1e40d82a5ea89ff5b147b8444ed63d92827db"
+  dependencies:
+    lodash._baseclone "^3.0.0"
+    lodash._bindcallback "^3.0.0"
+
+lodash.isarguments@^3.0.0:
+  version "3.1.0"
+  resolved "https://registry.yarnpkg.com/lodash.isarguments/-/lodash.isarguments-3.1.0.tgz#2f573d85c6a24289ff00663b491c1d338ff3458a"
+
+lodash.isarray@^3.0.0:
+  version "3.0.4"
+  resolved "https://registry.yarnpkg.com/lodash.isarray/-/lodash.isarray-3.0.4.tgz#79e4eb88c36a8122af86f844aa9bcd851b5fbb55"
+
+lodash.isplainobject@^3.0.0:
+  version "3.2.0"
+  resolved "https://registry.yarnpkg.com/lodash.isplainobject/-/lodash.isplainobject-3.2.0.tgz#9a8238ae16b200432960cd7346512d0123fbf4c5"
+  dependencies:
+    lodash._basefor "^3.0.0"
+    lodash.isarguments "^3.0.0"
+    lodash.keysin "^3.0.0"
+
+lodash.istypedarray@^3.0.0:
+  version "3.0.6"
+  resolved "https://registry.yarnpkg.com/lodash.istypedarray/-/lodash.istypedarray-3.0.6.tgz#c9a477498607501d8e8494d283b87c39281cef62"
+
+lodash.keys@^3.0.0:
+  version "3.1.2"
+  resolved "https://registry.yarnpkg.com/lodash.keys/-/lodash.keys-3.1.2.tgz#4dbc0472b156be50a0b286855d1bd0b0c656098a"
+  dependencies:
+    lodash._getnative "^3.0.0"
+    lodash.isarguments "^3.0.0"
+    lodash.isarray "^3.0.0"
+
+lodash.keysin@^3.0.0:
+  version "3.0.8"
+  resolved "https://registry.yarnpkg.com/lodash.keysin/-/lodash.keysin-3.0.8.tgz#22c4493ebbedb1427962a54b445b2c8a767fb47f"
+  dependencies:
+    lodash.isarguments "^3.0.0"
+    lodash.isarray "^3.0.0"
+
+lodash.merge@^3.3.2:
+  version "3.3.2"
+  resolved "https://registry.yarnpkg.com/lodash.merge/-/lodash.merge-3.3.2.tgz#0d90d93ed637b1878437bb3e21601260d7afe994"
+  dependencies:
+    lodash._arraycopy "^3.0.0"
+    lodash._arrayeach "^3.0.0"
+    lodash._createassigner "^3.0.0"
+    lodash._getnative "^3.0.0"
+    lodash.isarguments "^3.0.0"
+    lodash.isarray "^3.0.0"
+    lodash.isplainobject "^3.0.0"
+    lodash.istypedarray "^3.0.0"
+    lodash.keys "^3.0.0"
+    lodash.keysin "^3.0.0"
+    lodash.toplainobject "^3.0.0"
+
+lodash.omit@^3.1.0:
+  version "3.1.0"
+  resolved "https://registry.yarnpkg.com/lodash.omit/-/lodash.omit-3.1.0.tgz#897fe382e6413d9ac97c61f78ed1e057a00af9f3"
+  dependencies:
+    lodash._arraymap "^3.0.0"
+    lodash._basedifference "^3.0.0"
+    lodash._baseflatten "^3.0.0"
+    lodash._bindcallback "^3.0.0"
+    lodash._pickbyarray "^3.0.0"
+    lodash._pickbycallback "^3.0.0"
+    lodash.keysin "^3.0.0"
+    lodash.restparam "^3.0.0"
+
+lodash.restparam@^3.0.0:
+  version "3.6.1"
+  resolved "https://registry.yarnpkg.com/lodash.restparam/-/lodash.restparam-3.6.1.tgz#936a4e309ef330a7645ed4145986c85ae5b20805"
+
+lodash.toplainobject@^3.0.0:
+  version "3.0.0"
+  resolved "https://registry.yarnpkg.com/lodash.toplainobject/-/lodash.toplainobject-3.0.0.tgz#28790ad942d293d78aa663a07ecf7f52ca04198d"
+  dependencies:
+    lodash._basecopy "^3.0.0"
+    lodash.keysin "^3.0.0"
+
+lodash@3.10.1, lodash@^3.10.1, lodash@^3.3.1, lodash@^3.8.0:
+  version "3.10.1"
+  resolved "https://registry.yarnpkg.com/lodash/-/lodash-3.10.1.tgz#5bf45e8e49ba4189e17d482789dfd15bd140b7b6"
+
+lodash@^4.0.1, lodash@^4.17.2, lodash@^4.17.4, lodash@^4.7.0, lodash@~4.17.4:
+  version "4.17.5"
+  resolved "https://registry.yarnpkg.com/lodash/-/lodash-4.17.5.tgz#99a92d65c0272debe8c96b6057bc8fbfa3bed511"
+
+lodash@~0.9.2:
+  version "0.9.2"
+  resolved "https://registry.yarnpkg.com/lodash/-/lodash-0.9.2.tgz#8f3499c5245d346d682e5b0d3b40767e09f1a92c"
+
+lodash@~2.4.1:
+  version "2.4.2"
+  resolved "https://registry.yarnpkg.com/lodash/-/lodash-2.4.2.tgz#fadd834b9683073da179b3eae6d9c0d15053f73e"
+
+lodash@~3.2.0:
+  version "3.2.0"
+  resolved "https://registry.yarnpkg.com/lodash/-/lodash-3.2.0.tgz#4bf50a3243f9aeb0bac41a55d3d5990675a462fb"
+
+lodash@~3.9.3:
+  version "3.9.3"
+  resolved "https://registry.yarnpkg.com/lodash/-/lodash-3.9.3.tgz#0159e86832feffc6d61d852b12a953b99496bd32"
+
+log-driver@1.2.5:
+  version "1.2.5"
+  resolved "https://registry.yarnpkg.com/log-driver/-/log-driver-1.2.5.tgz#7ae4ec257302fd790d557cb10c97100d857b0056"
+
+log-symbols@^2.1.0:
+  version "2.2.0"
+  resolved "https://registry.yarnpkg.com/log-symbols/-/log-symbols-2.2.0.tgz#5740e1c5d6f0dfda4ad9323b5332107ef6b4c40a"
+  dependencies:
+    chalk "^2.0.1"
+
+log4js@^0.6.31:
+  version "0.6.38"
+  resolved "https://registry.yarnpkg.com/log4js/-/log4js-0.6.38.tgz#2c494116695d6fb25480943d3fc872e662a522fd"
+  dependencies:
+    readable-stream "~1.0.2"
+    semver "~4.3.3"
+
+"loggly@0.3.x >=0.3.7":
+  version "0.3.11"
+  resolved "https://registry.yarnpkg.com/loggly/-/loggly-0.3.11.tgz#62c1ec3436772f0954598f26b957d2ad2986b611"
+  dependencies:
+    request "2.9.x"
+    timespan "2.x.x"
+
+longest@^1.0.1:
+  version "1.0.1"
+  resolved "https://registry.yarnpkg.com/longest/-/longest-1.0.1.tgz#30a0b2da38f73770e8294a0d22e6625ed77d0097"
+
+loose-envify@^1.0.0:
+  version "1.3.1"
+  resolved "https://registry.yarnpkg.com/loose-envify/-/loose-envify-1.3.1.tgz#d1a8ad33fa9ce0e713d65fdd0ac8b748d478c848"
+  dependencies:
+    js-tokens "^3.0.0"
+
+loud-rejection@^1.0.0:
+  version "1.6.0"
+  resolved "https://registry.yarnpkg.com/loud-rejection/-/loud-rejection-1.6.0.tgz#5b46f80147edee578870f086d04821cf998e551f"
+  dependencies:
+    currently-unhandled "^0.4.1"
+    signal-exit "^3.0.0"
+
+lru-cache@2:
+  version "2.7.3"
+  resolved "https://registry.yarnpkg.com/lru-cache/-/lru-cache-2.7.3.tgz#6d4524e8b955f95d4f5b58851ce21dd72fb4e952"
+
+lru-cache@4.1.x, lru-cache@^4.0.1:
+  version "4.1.1"
+  resolved "https://registry.yarnpkg.com/lru-cache/-/lru-cache-4.1.1.tgz#622e32e82488b49279114a4f9ecf45e7cd6bba55"
+  dependencies:
+    pseudomap "^1.0.2"
+    yallist "^2.1.2"
+
+lru-cache@~1.0.2:
+  version "1.0.6"
+  resolved "https://registry.yarnpkg.com/lru-cache/-/lru-cache-1.0.6.tgz#aa50f97047422ac72543bda177a9c9d018d98452"
+
+map-obj@^1.0.0, map-obj@^1.0.1:
+  version "1.0.1"
+  resolved "https://registry.yarnpkg.com/map-obj/-/map-obj-1.0.1.tgz#d933ceb9205d82bdcf4886f6742bdc2b4dea146d"
+
+maxmin@^1.1.0:
+  version "1.1.0"
+  resolved "https://registry.yarnpkg.com/maxmin/-/maxmin-1.1.0.tgz#71365e84a99dd8f8b3f7d5fde2f00d1e7f73be61"
+  dependencies:
+    chalk "^1.0.0"
+    figures "^1.0.1"
+    gzip-size "^1.0.0"
+    pretty-bytes "^1.0.0"
+
+md5-hex@^1.2.0:
+  version "1.3.0"
+  resolved "https://registry.yarnpkg.com/md5-hex/-/md5-hex-1.3.0.tgz#d2c4afe983c4370662179b8cad145219135046c4"
+  dependencies:
+    md5-o-matic "^0.1.1"
+
+md5-o-matic@^0.1.1:
+  version "0.1.1"
+  resolved "https://registry.yarnpkg.com/md5-o-matic/-/md5-o-matic-0.1.1.tgz#822bccd65e117c514fab176b25945d54100a03c3"
+
+media-typer@0.3.0:
+  version "0.3.0"
+  resolved "https://registry.yarnpkg.com/media-typer/-/media-typer-0.3.0.tgz#8710d7af0aa626f8fffa1ce00168545263255748"
+
+mem@^1.1.0:
+  version "1.1.0"
+  resolved "https://registry.yarnpkg.com/mem/-/mem-1.1.0.tgz#5edd52b485ca1d900fe64895505399a0dfa45f76"
+  dependencies:
+    mimic-fn "^1.0.0"
+
+memory-fs@^0.2.0:
+  version "0.2.0"
+  resolved "https://registry.yarnpkg.com/memory-fs/-/memory-fs-0.2.0.tgz#f2bb25368bc121e391c2520de92969caee0a0290"
+
+memory-fs@~0.3.0:
+  version "0.3.0"
+  resolved "https://registry.yarnpkg.com/memory-fs/-/memory-fs-0.3.0.tgz#7bcc6b629e3a43e871d7e29aca6ae8a7f15cbb20"
+  dependencies:
+    errno "^0.1.3"
+    readable-stream "^2.0.1"
+
+memory-fs@~0.4.1:
+  version "0.4.1"
+  resolved "https://registry.yarnpkg.com/memory-fs/-/memory-fs-0.4.1.tgz#3a9a20b8462523e447cfbc7e8bb80ed667bfc552"
+  dependencies:
+    errno "^0.1.3"
+    readable-stream "^2.0.1"
+
+meow@^3.1.0:
+  version "3.7.0"
+  resolved "https://registry.yarnpkg.com/meow/-/meow-3.7.0.tgz#72cb668b425228290abbfa856892587308a801fb"
+  dependencies:
+    camelcase-keys "^2.0.0"
+    decamelize "^1.1.2"
+    loud-rejection "^1.0.0"
+    map-obj "^1.0.1"
+    minimist "^1.1.3"
+    normalize-package-data "^2.3.4"
+    object-assign "^4.0.1"
+    read-pkg-up "^1.0.1"
+    redent "^1.0.0"
+    trim-newlines "^1.0.0"
+
+merge-descriptors@1.0.1:
+  version "1.0.1"
+  resolved "https://registry.yarnpkg.com/merge-descriptors/-/merge-descriptors-1.0.1.tgz#b00aaa556dd8b44568150ec9d1b953f3f90cbb61"
+
+merge-source-map@^1.0.2:
+  version "1.1.0"
+  resolved "https://registry.yarnpkg.com/merge-source-map/-/merge-source-map-1.1.0.tgz#2fdde7e6020939f70906a68f2d7ae685e4c8c646"
+  dependencies:
+    source-map "^0.6.1"
+
+methods@~1.1.2:
+  version "1.1.2"
+  resolved "https://registry.yarnpkg.com/methods/-/methods-1.1.2.tgz#5529a4d67654134edcc5266656835b0f851afcee"
+
+micromatch@^2.1.5, micromatch@^2.3.11:
+  version "2.3.11"
+  resolved "https://registry.yarnpkg.com/micromatch/-/micromatch-2.3.11.tgz#86677c97d1720b363431d04d0d15293bd38c1565"
+  dependencies:
+    arr-diff "^2.0.0"
+    array-unique "^0.2.1"
+    braces "^1.8.2"
+    expand-brackets "^0.1.4"
+    extglob "^0.3.1"
+    filename-regex "^2.0.0"
+    is-extglob "^1.0.0"
+    is-glob "^2.0.1"
+    kind-of "^3.0.2"
+    normalize-path "^2.0.1"
+    object.omit "^2.0.0"
+    parse-glob "^3.0.4"
+    regex-cache "^0.4.2"
+
+"mime-db@>= 1.33.0 < 2", mime-db@~1.33.0:
+  version "1.33.0"
+  resolved "https://registry.yarnpkg.com/mime-db/-/mime-db-1.33.0.tgz#a3492050a5cb9b63450541e39d9788d2272783db"
+
+mime-db@~1.12.0:
+  version "1.12.0"
+  resolved "https://registry.yarnpkg.com/mime-db/-/mime-db-1.12.0.tgz#3d0c63180f458eb10d325aaa37d7c58ae312e9d7"
+
+mime-types@^2.1.12, mime-types@~2.1.11, mime-types@~2.1.17, mime-types@~2.1.18, mime-types@~2.1.7:
+  version "2.1.18"
+  resolved "https://registry.yarnpkg.com/mime-types/-/mime-types-2.1.18.tgz#6f323f60a83d11146f831ff11fd66e2fe5503bb8"
+  dependencies:
+    mime-db "~1.33.0"
+
+mime-types@~2.0.1, mime-types@~2.0.3:
+  version "2.0.14"
+  resolved "https://registry.yarnpkg.com/mime-types/-/mime-types-2.0.14.tgz#310e159db23e077f8bb22b748dabfa4957140aa6"
+  dependencies:
+    mime-db "~1.12.0"
+
+mime@1.2.6:
+  version "1.2.6"
+  resolved "https://registry.yarnpkg.com/mime/-/mime-1.2.6.tgz#b1f86c768c025fa87b48075f1709f28aeaf20365"
+
+mime@1.4.1:
+  version "1.4.1"
+  resolved "https://registry.yarnpkg.com/mime/-/mime-1.4.1.tgz#121f9ebc49e3766f311a76e1fa1c8003c4b03aa6"
+
+mime@^1.3.4, mime@^1.5.0:
+  version "1.6.0"
+  resolved "https://registry.yarnpkg.com/mime/-/mime-1.6.0.tgz#32cd9e5c64553bd58d19a568af452acff04981b1"
+
+mimic-fn@^1.0.0:
+  version "1.2.0"
+  resolved "https://registry.yarnpkg.com/mimic-fn/-/mimic-fn-1.2.0.tgz#820c86a39334640e99516928bd03fca88057d022"
+
+minimatch@0.0.x:
+  version "0.0.5"
+  resolved "https://registry.yarnpkg.com/minimatch/-/minimatch-0.0.5.tgz#96bb490bbd3ba6836bbfac111adf75301b1584de"
+  dependencies:
+    lru-cache "~1.0.2"
+
+minimatch@0.3:
+  version "0.3.0"
+  resolved "https://registry.yarnpkg.com/minimatch/-/minimatch-0.3.0.tgz#275d8edaac4f1bb3326472089e7949c8394699dd"
+  dependencies:
+    lru-cache "2"
+    sigmund "~1.0.0"
+
+"minimatch@2 || 3", minimatch@^3.0.0, minimatch@^3.0.2, minimatch@^3.0.4, minimatch@~3.0.2:
+  version "3.0.4"
+  resolved "https://registry.yarnpkg.com/minimatch/-/minimatch-3.0.4.tgz#5166e286457f03306064be5497e8dbb0c3d32083"
+  dependencies:
+    brace-expansion "^1.1.7"
+
+minimatch@2.x, minimatch@^2.0.1:
+  version "2.0.10"
+  resolved "https://registry.yarnpkg.com/minimatch/-/minimatch-2.0.10.tgz#8d087c39c6b38c001b97fca7ce6d0e1e80afbac7"
+  dependencies:
+    brace-expansion "^1.0.0"
+
+minimatch@~0.2.11, minimatch@~0.2.12, minimatch@~0.2.5:
+  version "0.2.14"
+  resolved "https://registry.yarnpkg.com/minimatch/-/minimatch-0.2.14.tgz#c74e780574f63c6f9a090e90efbe6ef53a6a756a"
+  dependencies:
+    lru-cache "2"
+    sigmund "~1.0.0"
+
+minimist@0.0.8:
+  version "0.0.8"
+  resolved "https://registry.yarnpkg.com/minimist/-/minimist-0.0.8.tgz#857fcabfc3397d2625b8228262e86aa7a011b05d"
+
+minimist@1.2.0, minimist@^1.1.3, minimist@^1.2.0:
+  version "1.2.0"
+  resolved "https://registry.yarnpkg.com/minimist/-/minimist-1.2.0.tgz#a35008b20f41383eec1fb914f4cd5df79a264284"
+
+minimist@~0.0.1:
+  version "0.0.10"
+  resolved "https://registry.yarnpkg.com/minimist/-/minimist-0.0.10.tgz#de3f98543dbf96082be48ad1a0c7cda836301dcf"
+
+minipass@^2.2.0, minipass@^2.2.1:
+  version "2.2.1"
+  resolved "https://registry.yarnpkg.com/minipass/-/minipass-2.2.1.tgz#5ada97538b1027b4cf7213432428578cb564011f"
+  dependencies:
+    yallist "^3.0.0"
+
+mkdirp@0.3.0:
+  version "0.3.0"
+  resolved "https://registry.yarnpkg.com/mkdirp/-/mkdirp-0.3.0.tgz#1bbf5ab1ba827af23575143490426455f481fe1e"
+
+mkdirp@0.5.0:
+  version "0.5.0"
+  resolved "https://registry.yarnpkg.com/mkdirp/-/mkdirp-0.5.0.tgz#1d73076a6df986cd9344e15e71fcc05a4c9abf12"
+  dependencies:
+    minimist "0.0.8"
+
+mkdirp@0.5.1, mkdirp@0.5.x, "mkdirp@>=0.5 0", mkdirp@^0.5.0, mkdirp@^0.5.1, mkdirp@~0.5.0:
+  version "0.5.1"
+  resolved "https://registry.yarnpkg.com/mkdirp/-/mkdirp-0.5.1.tgz#30057438eac6cf7f8c4767f38648d6697d75c903"
+  dependencies:
+    minimist "0.0.8"
+
+mocha@^2.3.3:
+  version "2.5.3"
+  resolved "https://registry.yarnpkg.com/mocha/-/mocha-2.5.3.tgz#161be5bdeb496771eb9b35745050b622b5aefc58"
+  dependencies:
+    commander "2.3.0"
+    debug "2.2.0"
+    diff "1.4.0"
+    escape-string-regexp "1.0.2"
+    glob "3.2.11"
+    growl "1.9.2"
+    jade "0.26.3"
+    mkdirp "0.5.1"
+    supports-color "1.2.0"
+    to-iso-string "0.0.2"
+
+modify-babel-preset@2.0.2:
+  version "2.0.2"
+  resolved "https://registry.yarnpkg.com/modify-babel-preset/-/modify-babel-preset-2.0.2.tgz#bfa509669fe49f4222c0ce171ba44ed0e81551e7"
+  dependencies:
+    require-relative "^0.8.7"
+
+ms@0.7.1:
+  version "0.7.1"
+  resolved "https://registry.yarnpkg.com/ms/-/ms-0.7.1.tgz#9cd13c03adbff25b65effde7ce864ee952017098"
+
+ms@0.7.2:
+  version "0.7.2"
+  resolved "https://registry.yarnpkg.com/ms/-/ms-0.7.2.tgz#ae25cf2512b3885a1d95d7f037868d8431124765"
+
+ms@2.0.0:
+  version "2.0.0"
+  resolved "https://registry.yarnpkg.com/ms/-/ms-2.0.0.tgz#5608aeadfc00be6c2901df5f9861788de0d597c8"
+
+mute-stream@0.0.5:
+  version "0.0.5"
+  resolved "https://registry.yarnpkg.com/mute-stream/-/mute-stream-0.0.5.tgz#8fbfabb0a98a253d3184331f9e8deb7372fac6c0"
+
+nan@^2.3.0:
+  version "2.9.2"
+  resolved "https://registry.yarnpkg.com/nan/-/nan-2.9.2.tgz#f564d75f5f8f36a6d9456cca7a6c4fe488ab7866"
+
+negotiator@0.6.1:
+  version "0.6.1"
+  resolved "https://registry.yarnpkg.com/negotiator/-/negotiator-0.6.1.tgz#2b327184e8992101177b28563fb5e7102acd0ca9"
+
+node-int64@~0.3.0:
+  version "0.3.3"
+  resolved "https://registry.yarnpkg.com/node-int64/-/node-int64-0.3.3.tgz#2d6e6b2ece5de8588b43d88d1bc41b26cd1fa84d"
+
+node-libs-browser@^0.7.0:
+  version "0.7.0"
+  resolved "https://registry.yarnpkg.com/node-libs-browser/-/node-libs-browser-0.7.0.tgz#3e272c0819e308935e26674408d7af0e1491b83b"
+  dependencies:
+    assert "^1.1.1"
+    browserify-zlib "^0.1.4"
+    buffer "^4.9.0"
+    console-browserify "^1.1.0"
+    constants-browserify "^1.0.0"
+    crypto-browserify "3.3.0"
+    domain-browser "^1.1.1"
+    events "^1.0.0"
+    https-browserify "0.0.1"
+    os-browserify "^0.2.0"
+    path-browserify "0.0.0"
+    process "^0.11.0"
+    punycode "^1.2.4"
+    querystring-es3 "^0.2.0"
+    readable-stream "^2.0.5"
+    stream-browserify "^2.0.1"
+    stream-http "^2.3.1"
+    string_decoder "^0.10.25"
+    timers-browserify "^2.0.2"
+    tty-browserify "0.0.0"
+    url "^0.11.0"
+    util "^0.10.3"
+    vm-browserify "0.0.4"
+
+node-pre-gyp@^0.6.39:
+  version "0.6.39"
+  resolved "https://registry.yarnpkg.com/node-pre-gyp/-/node-pre-gyp-0.6.39.tgz#c00e96860b23c0e1420ac7befc5044e1d78d8649"
+  dependencies:
+    detect-libc "^1.0.2"
+    hawk "3.1.3"
+    mkdirp "^0.5.1"
+    nopt "^4.0.1"
+    npmlog "^4.0.2"
+    rc "^1.1.7"
+    request "2.81.0"
+    rimraf "^2.6.1"
+    semver "^5.3.0"
+    tar "^2.2.1"
+    tar-pack "^3.4.0"
+
+node-uuid@~1.4.0:
+  version "1.4.8"
+  resolved "https://registry.yarnpkg.com/node-uuid/-/node-uuid-1.4.8.tgz#b040eb0923968afabf8d32fb1f17f1167fdab907"
+
+nodeunit@~0.7.4:
+  version "0.7.4"
+  resolved "https://registry.yarnpkg.com/nodeunit/-/nodeunit-0.7.4.tgz#c908def7f299fbe65ff7ac888782955c46aae9f8"
+  dependencies:
+    tap ">=0.2.3"
+
+nopt@3.x:
+  version "3.0.6"
+  resolved "https://registry.yarnpkg.com/nopt/-/nopt-3.0.6.tgz#c6465dbf08abcd4db359317f79ac68a646b28ff9"
+  dependencies:
+    abbrev "1"
+
+nopt@^4.0.1:
+  version "4.0.1"
+  resolved "https://registry.yarnpkg.com/nopt/-/nopt-4.0.1.tgz#d0d4685afd5415193c8c7505602d0d17cd64474d"
+  dependencies:
+    abbrev "1"
+    osenv "^0.1.4"
+
+nopt@~1.0.10:
+  version "1.0.10"
+  resolved "https://registry.yarnpkg.com/nopt/-/nopt-1.0.10.tgz#6ddd21bd2a31417b92727dd585f8a6f37608ebee"
+  dependencies:
+    abbrev "1"
+
+normalize-package-data@^2.3.2, normalize-package-data@^2.3.4:
+  version "2.4.0"
+  resolved "https://registry.yarnpkg.com/normalize-package-data/-/normalize-package-data-2.4.0.tgz#12f95a307d58352075a04907b84ac8be98ac012f"
+  dependencies:
+    hosted-git-info "^2.1.4"
+    is-builtin-module "^1.0.0"
+    semver "2 || 3 || 4 || 5"
+    validate-npm-package-license "^3.0.1"
+
+normalize-path@^2.0.0, normalize-path@^2.0.1:
+  version "2.1.1"
+  resolved "https://registry.yarnpkg.com/normalize-path/-/normalize-path-2.1.1.tgz#1ab28b556e198363a8c1a6f7e6fa20137fe6aed9"
+  dependencies:
+    remove-trailing-separator "^1.0.1"
+
+npm-run-path@^2.0.0:
+  version "2.0.2"
+  resolved "https://registry.yarnpkg.com/npm-run-path/-/npm-run-path-2.0.2.tgz#35a9232dfa35d7067b4cb2ddf2357b1871536c5f"
+  dependencies:
+    path-key "^2.0.0"
+
+npmlog@^4.0.2:
+  version "4.1.2"
+  resolved "https://registry.yarnpkg.com/npmlog/-/npmlog-4.1.2.tgz#08a7f2a8bf734604779a9efa4ad5cc717abb954b"
+  dependencies:
+    are-we-there-yet "~1.1.2"
+    console-control-strings "~1.1.0"
+    gauge "~2.7.3"
+    set-blocking "~2.0.0"
+
+number-is-nan@^1.0.0:
+  version "1.0.1"
+  resolved "https://registry.yarnpkg.com/number-is-nan/-/number-is-nan-1.0.1.tgz#097b602b53422a522c1afb8790318336941a011d"
+
+nyc@^11.3.0:
+  version "11.4.1"
+  resolved "https://registry.yarnpkg.com/nyc/-/nyc-11.4.1.tgz#13fdf7e7ef22d027c61d174758f6978a68f4f5e5"
+  dependencies:
+    archy "^1.0.0"
+    arrify "^1.0.1"
+    caching-transform "^1.0.0"
+    convert-source-map "^1.3.0"
+    debug-log "^1.0.1"
+    default-require-extensions "^1.0.0"
+    find-cache-dir "^0.1.1"
+    find-up "^2.1.0"
+    foreground-child "^1.5.3"
+    glob "^7.0.6"
+    istanbul-lib-coverage "^1.1.1"
+    istanbul-lib-hook "^1.1.0"
+    istanbul-lib-instrument "^1.9.1"
+    istanbul-lib-report "^1.1.2"
+    istanbul-lib-source-maps "^1.2.2"
+    istanbul-reports "^1.1.3"
+    md5-hex "^1.2.0"
+    merge-source-map "^1.0.2"
+    micromatch "^2.3.11"
+    mkdirp "^0.5.0"
+    resolve-from "^2.0.0"
+    rimraf "^2.5.4"
+    signal-exit "^3.0.1"
+    spawn-wrap "^1.4.2"
+    test-exclude "^4.1.1"
+    yargs "^10.0.3"
+    yargs-parser "^8.0.0"
+
+oauth-sign@~0.6.0:
+  version "0.6.0"
+  resolved "https://registry.yarnpkg.com/oauth-sign/-/oauth-sign-0.6.0.tgz#7dbeae44f6ca454e1f168451d630746735813ce3"
+
+oauth-sign@~0.8.1, oauth-sign@~0.8.2:
+  version "0.8.2"
+  resolved "https://registry.yarnpkg.com/oauth-sign/-/oauth-sign-0.8.2.tgz#46a6ab7f0aead8deae9ec0565780b7d4efeb9d43"
+
+object-assign@4.1.0:
+  version "4.1.0"
+  resolved "https://registry.yarnpkg.com/object-assign/-/object-assign-4.1.0.tgz#7a3b3d0e98063d43f4c03f2e8ae6cd51a86883a0"
+
+object-assign@^4.0.1, object-assign@^4.1.0:
+  version "4.1.1"
+  resolved "https://registry.yarnpkg.com/object-assign/-/object-assign-4.1.1.tgz#2109adc7965887cfc05cbbd442cac8bfbb360863"
+
+object-component@0.0.3:
+  version "0.0.3"
+  resolved "https://registry.yarnpkg.com/object-component/-/object-component-0.0.3.tgz#f0c69aa50efc95b866c186f400a33769cb2f1291"
+
+object.omit@^2.0.0:
+  version "2.0.1"
+  resolved "https://registry.yarnpkg.com/object.omit/-/object.omit-2.0.1.tgz#1a9c744829f39dbb858c76ca3579ae2a54ebd1fa"
+  dependencies:
+    for-own "^0.1.4"
+    is-extendable "^0.1.1"
+
+on-finished@~2.3.0:
+  version "2.3.0"
+  resolved "https://registry.yarnpkg.com/on-finished/-/on-finished-2.3.0.tgz#20f1336481b083cd75337992a16971aa2d906947"
+  dependencies:
+    ee-first "1.1.1"
+
+on-headers@~1.0.1:
+  version "1.0.1"
+  resolved "https://registry.yarnpkg.com/on-headers/-/on-headers-1.0.1.tgz#928f5d0f470d49342651ea6794b0857c100693f7"
+
+once@1.x, once@^1.3.0, once@^1.3.3, once@^1.4.0:
+  version "1.4.0"
+  resolved "https://registry.yarnpkg.com/once/-/once-1.4.0.tgz#583b1aa775961d4b113ac17d9c50baef9dd76bd1"
+  dependencies:
+    wrappy "1"
+
+onetime@^1.0.0:
+  version "1.1.0"
+  resolved "https://registry.yarnpkg.com/onetime/-/onetime-1.1.0.tgz#a1f7838f8314c516f05ecefcbc4ccfe04b4ed789"
+
+open@0.0.5:
+  version "0.0.5"
+  resolved "https://registry.yarnpkg.com/open/-/open-0.0.5.tgz#42c3e18ec95466b6bf0dc42f3a2945c3f0cad8fc"
+
+opener@^1.4.1:
+  version "1.4.3"
+  resolved "https://registry.yarnpkg.com/opener/-/opener-1.4.3.tgz#5c6da2c5d7e5831e8ffa3964950f8d6674ac90b8"
+
+optimist@^0.6.1, optimist@~0.6.0, optimist@~0.6.1:
+  version "0.6.1"
+  resolved "https://registry.yarnpkg.com/optimist/-/optimist-0.6.1.tgz#da3ea74686fa21a19a111c326e90eb15a0196686"
+  dependencies:
+    minimist "~0.0.1"
+    wordwrap "~0.0.2"
+
+optionator@^0.5.0:
+  version "0.5.0"
+  resolved "https://registry.yarnpkg.com/optionator/-/optionator-0.5.0.tgz#b75a8995a2d417df25b6e4e3862f50aa88651368"
+  dependencies:
+    deep-is "~0.1.2"
+    fast-levenshtein "~1.0.0"
+    levn "~0.2.5"
+    prelude-ls "~1.1.1"
+    type-check "~0.3.1"
+    wordwrap "~0.0.2"
+
+optionator@^0.6.0:
+  version "0.6.0"
+  resolved "https://registry.yarnpkg.com/optionator/-/optionator-0.6.0.tgz#b63ecbbf0e315fad4bc9827b45dc7ba45284fcb6"
+  dependencies:
+    deep-is "~0.1.3"
+    fast-levenshtein "~1.0.6"
+    levn "~0.2.5"
+    prelude-ls "~1.1.1"
+    type-check "~0.3.1"
+    wordwrap "~0.0.2"
+
+options@>=0.0.5:
+  version "0.0.6"
+  resolved "https://registry.yarnpkg.com/options/-/options-0.0.6.tgz#ec22d312806bb53e731773e7cdaefcf1c643128f"
+
+original@>=0.0.5:
+  version "1.0.0"
+  resolved "https://registry.yarnpkg.com/original/-/original-1.0.0.tgz#9147f93fa1696d04be61e01bd50baeaca656bd3b"
+  dependencies:
+    url-parse "1.0.x"
+
+os-browserify@^0.2.0:
+  version "0.2.1"
+  resolved "https://registry.yarnpkg.com/os-browserify/-/os-browserify-0.2.1.tgz#63fc4ccee5d2d7763d26bbf8601078e6c2e0044f"
+
+os-homedir@^1.0.0, os-homedir@^1.0.1, os-homedir@^1.0.2:
+  version "1.0.2"
+  resolved "https://registry.yarnpkg.com/os-homedir/-/os-homedir-1.0.2.tgz#ffbc4988336e0e833de0c168c7ef152121aa7fb3"
+
+os-locale@^2.0.0:
+  version "2.1.0"
+  resolved "https://registry.yarnpkg.com/os-locale/-/os-locale-2.1.0.tgz#42bc2900a6b5b8bd17376c8e882b65afccf24bf2"
+  dependencies:
+    execa "^0.7.0"
+    lcid "^1.0.0"
+    mem "^1.1.0"
+
+os-tmpdir@^1.0.0, os-tmpdir@^1.0.1, os-tmpdir@~1.0.2:
+  version "1.0.2"
+  resolved "https://registry.yarnpkg.com/os-tmpdir/-/os-tmpdir-1.0.2.tgz#bbe67406c79aa85c5cfec766fe5734555dfa1274"
+
+osenv@^0.1.4:
+  version "0.1.5"
+  resolved "https://registry.yarnpkg.com/osenv/-/osenv-0.1.5.tgz#85cdfafaeb28e8677f416e287592b5f3f49ea410"
+  dependencies:
+    os-homedir "^1.0.0"
+    os-tmpdir "^1.0.0"
+
+own-or-env@^1.0.0:
+  version "1.0.1"
+  resolved "https://registry.yarnpkg.com/own-or-env/-/own-or-env-1.0.1.tgz#54ce601d3bf78236c5c65633aa1c8ec03f8007e4"
+  dependencies:
+    own-or "^1.0.0"
+
+own-or@^1.0.0:
+  version "1.0.0"
+  resolved "https://registry.yarnpkg.com/own-or/-/own-or-1.0.0.tgz#4e877fbeda9a2ec8000fbc0bcae39645ee8bf8dc"
+
+p-finally@^1.0.0:
+  version "1.0.0"
+  resolved "https://registry.yarnpkg.com/p-finally/-/p-finally-1.0.0.tgz#3fbcfb15b899a44123b34b6dcc18b724336a2cae"
+
+p-limit@^1.1.0:
+  version "1.2.0"
+  resolved "https://registry.yarnpkg.com/p-limit/-/p-limit-1.2.0.tgz#0e92b6bedcb59f022c13d0f1949dc82d15909f1c"
+  dependencies:
+    p-try "^1.0.0"
+
+p-locate@^2.0.0:
+  version "2.0.0"
+  resolved "https://registry.yarnpkg.com/p-locate/-/p-locate-2.0.0.tgz#20a0103b222a70c8fd39cc2e580680f3dde5ec43"
+  dependencies:
+    p-limit "^1.1.0"
+
+p-try@^1.0.0:
+  version "1.0.0"
+  resolved "https://registry.yarnpkg.com/p-try/-/p-try-1.0.0.tgz#cbc79cdbaf8fd4228e13f621f2b1a237c1b207b3"
+
+"package@>= 1.0.0 < 1.2.0":
+  version "1.0.1"
+  resolved "https://registry.yarnpkg.com/package/-/package-1.0.1.tgz#d25a1f99e2506dcb27d6704b83dca8a312e4edcc"
+
+pako@~0.2.0:
+  version "0.2.9"
+  resolved "https://registry.yarnpkg.com/pako/-/pako-0.2.9.tgz#f3f7522f4ef782348da8161bad9ecfd51bf83a75"
+
+parse-glob@^3.0.4:
+  version "3.0.4"
+  resolved "https://registry.yarnpkg.com/parse-glob/-/parse-glob-3.0.4.tgz#b2c376cfb11f35513badd173ef0bb6e3a388391c"
+  dependencies:
+    glob-base "^0.3.0"
+    is-dotfile "^1.0.0"
+    is-extglob "^1.0.0"
+    is-glob "^2.0.0"
+
+parse-json@^2.2.0:
+  version "2.2.0"
+  resolved "https://registry.yarnpkg.com/parse-json/-/parse-json-2.2.0.tgz#f480f40434ef80741f8469099f8dea18f55a4dc9"
+  dependencies:
+    error-ex "^1.2.0"
+
+parsejson@0.0.3:
+  version "0.0.3"
+  resolved "https://registry.yarnpkg.com/parsejson/-/parsejson-0.0.3.tgz#ab7e3759f209ece99437973f7d0f1f64ae0e64ab"
+  dependencies:
+    better-assert "~1.0.0"
+
+parseqs@0.0.5:
+  version "0.0.5"
+  resolved "https://registry.yarnpkg.com/parseqs/-/parseqs-0.0.5.tgz#d5208a3738e46766e291ba2ea173684921a8b89d"
+  dependencies:
+    better-assert "~1.0.0"
+
+parseuri@0.0.5:
+  version "0.0.5"
+  resolved "https://registry.yarnpkg.com/parseuri/-/parseuri-0.0.5.tgz#80204a50d4dbb779bfdc6ebe2778d90e4bce320a"
+  dependencies:
+    better-assert "~1.0.0"
+
+parseurl@~1.3.0, parseurl@~1.3.2:
+  version "1.3.2"
+  resolved "https://registry.yarnpkg.com/parseurl/-/parseurl-1.3.2.tgz#fc289d4ed8993119460c156253262cdc8de65bf3"
+
+path-browserify@0.0.0:
+  version "0.0.0"
+  resolved "https://registry.yarnpkg.com/path-browserify/-/path-browserify-0.0.0.tgz#a0b870729aae214005b7d5032ec2cbbb0fb4451a"
+
+path-exists@^2.0.0:
+  version "2.1.0"
+  resolved "https://registry.yarnpkg.com/path-exists/-/path-exists-2.1.0.tgz#0feb6c64f0fc518d9a754dd5efb62c7022761f4b"
+  dependencies:
+    pinkie-promise "^2.0.0"
+
+path-exists@^3.0.0:
+  version "3.0.0"
+  resolved "https://registry.yarnpkg.com/path-exists/-/path-exists-3.0.0.tgz#ce0ebeaa5f78cb18925ea7d810d7b59b010fd515"
+
+path-is-absolute@^1.0.0, path-is-absolute@^1.0.1:
+  version "1.0.1"
+  resolved "https://registry.yarnpkg.com/path-is-absolute/-/path-is-absolute-1.0.1.tgz#174b9268735534ffbc7ace6bf53a5a9e1b5c5f5f"
+
+path-is-inside@^1.0.1:
+  version "1.0.2"
+  resolved "https://registry.yarnpkg.com/path-is-inside/-/path-is-inside-1.0.2.tgz#365417dede44430d1c11af61027facf074bdfc53"
+
+path-key@^2.0.0:
+  version "2.0.1"
+  resolved "https://registry.yarnpkg.com/path-key/-/path-key-2.0.1.tgz#411cadb574c5a140d3a4b1910d40d80cc9f40b40"
+
+path-parse@^1.0.5:
+  version "1.0.5"
+  resolved "https://registry.yarnpkg.com/path-parse/-/path-parse-1.0.5.tgz#3c1adf871ea9cd6c9431b6ea2bd74a0ff055c4c1"
+
+path-to-regexp@0.1.7:
+  version "0.1.7"
+  resolved "https://registry.yarnpkg.com/path-to-regexp/-/path-to-regexp-0.1.7.tgz#df604178005f522f15eb4490e7247a1bfaa67f8c"
+
+path-type@^1.0.0:
+  version "1.1.0"
+  resolved "https://registry.yarnpkg.com/path-type/-/path-type-1.1.0.tgz#59c44f7ee491da704da415da5a4070ba4f8fe441"
+  dependencies:
+    graceful-fs "^4.1.2"
+    pify "^2.0.0"
+    pinkie-promise "^2.0.0"
+
+pause@0.0.1:
+  version "0.0.1"
+  resolved "https://registry.yarnpkg.com/pause/-/pause-0.0.1.tgz#1d408b3fdb76923b9543d96fb4c9dfd535d9cb5d"
+
+pbkdf2-compat@2.0.1:
+  version "2.0.1"
+  resolved "https://registry.yarnpkg.com/pbkdf2-compat/-/pbkdf2-compat-2.0.1.tgz#b6e0c8fa99494d94e0511575802a59a5c142f288"
+
+pend@~1.2.0:
+  version "1.2.0"
+  resolved "https://registry.yarnpkg.com/pend/-/pend-1.2.0.tgz#7a57eb550a6783f9115331fcf4663d5c8e007a50"
+
+performance-now@^0.2.0:
+  version "0.2.0"
+  resolved "https://registry.yarnpkg.com/performance-now/-/performance-now-0.2.0.tgz#33ef30c5c77d4ea21c5a53869d91b56d8f2555e5"
+
+performance-now@^2.1.0:
+  version "2.1.0"
+  resolved "https://registry.yarnpkg.com/performance-now/-/performance-now-2.1.0.tgz#6309f4e0e5fa913ec1c69307ae364b4b377c9e7b"
+
+phantomjs-prebuilt@^2.1.5, phantomjs-prebuilt@^2.1.7:
+  version "2.1.16"
+  resolved "https://registry.yarnpkg.com/phantomjs-prebuilt/-/phantomjs-prebuilt-2.1.16.tgz#efd212a4a3966d3647684ea8ba788549be2aefef"
+  dependencies:
+    es6-promise "^4.0.3"
+    extract-zip "^1.6.5"
+    fs-extra "^1.0.0"
+    hasha "^2.2.0"
+    kew "^0.7.0"
+    progress "^1.1.8"
+    request "^2.81.0"
+    request-progress "^2.0.1"
+    which "^1.2.10"
+
+pify@^2.0.0:
+  version "2.3.0"
+  resolved "https://registry.yarnpkg.com/pify/-/pify-2.3.0.tgz#ed141a6ac043a849ea588498e7dca8b15330e90c"
+
+pinkie-promise@^2.0.0:
+  version "2.0.1"
+  resolved "https://registry.yarnpkg.com/pinkie-promise/-/pinkie-promise-2.0.1.tgz#2135d6dfa7a358c069ac9b178776288228450ffa"
+  dependencies:
+    pinkie "^2.0.0"
+
+pinkie@^2.0.0:
+  version "2.0.4"
+  resolved "https://registry.yarnpkg.com/pinkie/-/pinkie-2.0.4.tgz#72556b80cfa0d48a974e80e77248e80ed4f7f870"
+
+pkg-dir@^1.0.0:
+  version "1.0.0"
+  resolved "https://registry.yarnpkg.com/pkg-dir/-/pkg-dir-1.0.0.tgz#7a4b508a8d5bb2d629d447056ff4e9c9314cf3d4"
+  dependencies:
+    find-up "^1.0.0"
+
+pkginfo@0.2.x:
+  version "0.2.3"
+  resolved "https://registry.yarnpkg.com/pkginfo/-/pkginfo-0.2.3.tgz#7239c42a5ef6c30b8f328439d9b9ff71042490f8"
+
+pkginfo@0.x.x:
+  version "0.4.1"
+  resolved "https://registry.yarnpkg.com/pkginfo/-/pkginfo-0.4.1.tgz#b5418ef0439de5425fc4995042dced14fb2a84ff"
+
+prelude-ls@~1.1.0, prelude-ls@~1.1.1, prelude-ls@~1.1.2:
+  version "1.1.2"
+  resolved "https://registry.yarnpkg.com/prelude-ls/-/prelude-ls-1.1.2.tgz#21932a549f5e52ffd9a827f570e04be62a97da54"
+
+preserve@^0.2.0:
+  version "0.2.0"
+  resolved "https://registry.yarnpkg.com/preserve/-/preserve-0.2.0.tgz#815ed1f6ebc65926f865b310c0713bcb3315ce4b"
+
+pretty-bytes@^1.0.0:
+  version "1.0.4"
+  resolved "https://registry.yarnpkg.com/pretty-bytes/-/pretty-bytes-1.0.4.tgz#0a22e8210609ad35542f8c8d5d2159aff0751c84"
+  dependencies:
+    get-stdin "^4.0.1"
+    meow "^3.1.0"
+
+private@^0.1.6, private@^0.1.7, private@~0.1.5:
+  version "0.1.8"
+  resolved "https://registry.yarnpkg.com/private/-/private-0.1.8.tgz#2381edb3689f7a53d653190060fcf822d2f368ff"
+
+process-nextick-args@~2.0.0:
+  version "2.0.0"
+  resolved "https://registry.yarnpkg.com/process-nextick-args/-/process-nextick-args-2.0.0.tgz#a37d732f4271b4ab1ad070d35508e8290788ffaa"
+
+process@^0.11.0:
+  version "0.11.10"
+  resolved "https://registry.yarnpkg.com/process/-/process-0.11.10.tgz#7332300e840161bda3e69a1d1d91a7d4bc16f182"
+
+progress@^1.1.8:
+  version "1.1.8"
+  resolved "https://registry.yarnpkg.com/progress/-/progress-1.1.8.tgz#e260c78f6161cdd9b0e56cc3e0a85de17c7a57be"
+
+prompt@~0.1.12:
+  version "0.1.12"
+  resolved "https://registry.yarnpkg.com/prompt/-/prompt-0.1.12.tgz#d3114e4fb985ac66eaa35586dcb7b3fb3b27bfc6"
+  dependencies:
+    async "0.1.x"
+    colors "0.x.x"
+    pkginfo "0.x.x"
+    winston "0.5.x"
+
+proxy-addr@~2.0.2:
+  version "2.0.3"
+  resolved "https://registry.yarnpkg.com/proxy-addr/-/proxy-addr-2.0.3.tgz#355f262505a621646b3130a728eb647e22055341"
+  dependencies:
+    forwarded "~0.1.2"
+    ipaddr.js "1.6.0"
+
+prr@~1.0.1:
+  version "1.0.1"
+  resolved "https://registry.yarnpkg.com/prr/-/prr-1.0.1.tgz#d3fc114ba06995a45ec6893f484ceb1d78f5f476"
+
+pseudomap@^1.0.2:
+  version "1.0.2"
+  resolved "https://registry.yarnpkg.com/pseudomap/-/pseudomap-1.0.2.tgz#f052a28da70e618917ef0a8ac34c1ae5a68286b3"
+
+punycode@1.3.2:
+  version "1.3.2"
+  resolved "https://registry.yarnpkg.com/punycode/-/punycode-1.3.2.tgz#9653a036fb7c1ee42342f2325cceefea3926c48d"
+
+punycode@^1.2.4, punycode@^1.3.2, punycode@^1.4.1:
+  version "1.4.1"
+  resolved "https://registry.yarnpkg.com/punycode/-/punycode-1.4.1.tgz#c0d5a63b2718800ad8e1eb0fa5269c84dd41845e"
+
+q@^1.4.1:
+  version "1.5.1"
+  resolved "https://registry.yarnpkg.com/q/-/q-1.5.1.tgz#7e32f75b41381291d04611f1bf14109ac00651d7"
+
+q@~1.4.1:
+  version "1.4.1"
+  resolved "https://registry.yarnpkg.com/q/-/q-1.4.1.tgz#55705bcd93c5f3673530c2c2cbc0c2b3addc286e"
+
+qs@0.5.1:
+  version "0.5.1"
+  resolved "https://registry.yarnpkg.com/qs/-/qs-0.5.1.tgz#9f6bf5d9ac6c76384e95d36d15b48980e5e4add0"
+
+qs@5.2.0:
+  version "5.2.0"
+  resolved "https://registry.yarnpkg.com/qs/-/qs-5.2.0.tgz#a9f31142af468cb72b25b30136ba2456834916be"
+
+qs@6.5.1, qs@~6.5.1:
+  version "6.5.1"
+  resolved "https://registry.yarnpkg.com/qs/-/qs-6.5.1.tgz#349cdf6eef89ec45c12d7d5eb3fc0c870343a6d8"
+
+qs@~2.4.0:
+  version "2.4.2"
+  resolved "https://registry.yarnpkg.com/qs/-/qs-2.4.2.tgz#f7ce788e5777df0b5010da7f7c4e73ba32470f5a"
+
+qs@~5.1.0:
+  version "5.1.0"
+  resolved "https://registry.yarnpkg.com/qs/-/qs-5.1.0.tgz#4d932e5c7ea411cca76a312d39a606200fd50cd9"
+
+qs@~6.3.0:
+  version "6.3.2"
+  resolved "https://registry.yarnpkg.com/qs/-/qs-6.3.2.tgz#e75bd5f6e268122a2a0e0bda630b2550c166502c"
+
+qs@~6.4.0:
+  version "6.4.0"
+  resolved "https://registry.yarnpkg.com/qs/-/qs-6.4.0.tgz#13e26d28ad6b0ffaa91312cd3bf708ed351e7233"
+
+querystring-es3@^0.2.0:
+  version "0.2.1"
+  resolved "https://registry.yarnpkg.com/querystring-es3/-/querystring-es3-0.2.1.tgz#9ec61f79049875707d69414596fd907a4d711e73"
+
+querystring@0.2.0:
+  version "0.2.0"
+  resolved "https://registry.yarnpkg.com/querystring/-/querystring-0.2.0.tgz#b209849203bb25df820da756e747005878521620"
+
+querystringify@0.0.x:
+  version "0.0.4"
+  resolved "https://registry.yarnpkg.com/querystringify/-/querystringify-0.0.4.tgz#0cf7f84f9463ff0ae51c4c4b142d95be37724d9c"
+
+querystringify@~1.0.0:
+  version "1.0.0"
+  resolved "https://registry.yarnpkg.com/querystringify/-/querystringify-1.0.0.tgz#6286242112c5b712fa654e526652bf6a13ff05cb"
+
+randomatic@^1.1.3:
+  version "1.1.7"
+  resolved "https://registry.yarnpkg.com/randomatic/-/randomatic-1.1.7.tgz#c7abe9cc8b87c0baa876b19fde83fd464797e38c"
+  dependencies:
+    is-number "^3.0.0"
+    kind-of "^4.0.0"
+
+range-parser@0.0.4:
+  version "0.0.4"
+  resolved "https://registry.yarnpkg.com/range-parser/-/range-parser-0.0.4.tgz#c0427ffef51c10acba0782a46c9602e744ff620b"
+
+range-parser@^1.0.3, range-parser@~1.2.0:
+  version "1.2.0"
+  resolved "https://registry.yarnpkg.com/range-parser/-/range-parser-1.2.0.tgz#f49be6b487894ddc40dcc94a322f611092e00d5e"
+
+raw-body@2.3.2:
+  version "2.3.2"
+  resolved "https://registry.yarnpkg.com/raw-body/-/raw-body-2.3.2.tgz#bcd60c77d3eb93cde0050295c3f379389bc88f89"
+  dependencies:
+    bytes "3.0.0"
+    http-errors "1.6.2"
+    iconv-lite "0.4.19"
+    unpipe "1.0.0"
+
+raw-body@~2.1.5:
+  version "2.1.7"
+  resolved "https://registry.yarnpkg.com/raw-body/-/raw-body-2.1.7.tgz#adfeace2e4fb3098058014d08c072dcc59758774"
+  dependencies:
+    bytes "2.4.0"
+    iconv-lite "0.4.13"
+    unpipe "1.0.0"
+
+rc@^1.1.7:
+  version "1.2.5"
+  resolved "https://registry.yarnpkg.com/rc/-/rc-1.2.5.tgz#275cd687f6e3b36cc756baa26dfee80a790301fd"
+  dependencies:
+    deep-extend "~0.4.0"
+    ini "~1.3.0"
+    minimist "^1.2.0"
+    strip-json-comments "~2.0.1"
+
+read-pkg-up@^1.0.1:
+  version "1.0.1"
+  resolved "https://registry.yarnpkg.com/read-pkg-up/-/read-pkg-up-1.0.1.tgz#9d63c13276c065918d57f002a57f40a1b643fb02"
+  dependencies:
+    find-up "^1.0.0"
+    read-pkg "^1.0.0"
+
+read-pkg@^1.0.0:
+  version "1.1.0"
+  resolved "https://registry.yarnpkg.com/read-pkg/-/read-pkg-1.1.0.tgz#f5ffaa5ecd29cb31c0474bca7d756b6bb29e3f28"
+  dependencies:
+    load-json-file "^1.0.0"
+    normalize-package-data "^2.3.2"
+    path-type "^1.0.0"
+
+readable-stream@^2, readable-stream@^2.0.1, readable-stream@^2.0.2, readable-stream@^2.0.5, readable-stream@^2.0.6, readable-stream@^2.1.4, readable-stream@^2.1.5, readable-stream@^2.2.2, readable-stream@^2.3.3:
+  version "2.3.5"
+  resolved "https://registry.yarnpkg.com/readable-stream/-/readable-stream-2.3.5.tgz#b4f85003a938cbb6ecbce2a124fb1012bd1a838d"
+  dependencies:
+    core-util-is "~1.0.0"
+    inherits "~2.0.3"
+    isarray "~1.0.0"
+    process-nextick-args "~2.0.0"
+    safe-buffer "~5.1.1"
+    string_decoder "~1.0.3"
+    util-deprecate "~1.0.1"
+
+readable-stream@~1.0.2, readable-stream@~1.0.24, readable-stream@~1.0.26, readable-stream@~1.0.33:
+  version "1.0.34"
+  resolved "https://registry.yarnpkg.com/readable-stream/-/readable-stream-1.0.34.tgz#125820e34bc842d2f2aaafafe4c2916ee32c157c"
+  dependencies:
+    core-util-is "~1.0.0"
+    inherits "~2.0.1"
+    isarray "0.0.1"
+    string_decoder "~0.10.x"
+
+readdirp@^2.0.0:
+  version "2.1.0"
+  resolved "https://registry.yarnpkg.com/readdirp/-/readdirp-2.1.0.tgz#4ed0ad060df3073300c48440373f72d1cc642d78"
+  dependencies:
+    graceful-fs "^4.1.2"
+    minimatch "^3.0.2"
+    readable-stream "^2.0.2"
+    set-immediate-shim "^1.0.1"
+
+readline2@^1.0.1:
+  version "1.0.1"
+  resolved "https://registry.yarnpkg.com/readline2/-/readline2-1.0.1.tgz#41059608ffc154757b715d9989d199ffbf372e35"
+  dependencies:
+    code-point-at "^1.0.0"
+    is-fullwidth-code-point "^1.0.0"
+    mute-stream "0.0.5"
+
+redent@^1.0.0:
+  version "1.0.0"
+  resolved "https://registry.yarnpkg.com/redent/-/redent-1.0.0.tgz#cf916ab1fd5f1f16dfb20822dd6ec7f730c2afde"
+  dependencies:
+    indent-string "^2.1.0"
+    strip-indent "^1.0.1"
+
+regenerate@^1.2.1:
+  version "1.3.3"
+  resolved "https://registry.yarnpkg.com/regenerate/-/regenerate-1.3.3.tgz#0c336d3980553d755c39b586ae3b20aa49c82b7f"
+
+regenerator-runtime@^0.11.0:
+  version "0.11.1"
+  resolved "https://registry.yarnpkg.com/regenerator-runtime/-/regenerator-runtime-0.11.1.tgz#be05ad7f9bf7d22e056f9726cee5017fbf19e2e9"
+
+regenerator-transform@^0.10.0:
+  version "0.10.1"
+  resolved "https://registry.yarnpkg.com/regenerator-transform/-/regenerator-transform-0.10.1.tgz#1e4996837231da8b7f3cf4114d71b5691a0680dd"
+  dependencies:
+    babel-runtime "^6.18.0"
+    babel-types "^6.19.0"
+    private "^0.1.6"
+
+regex-cache@^0.4.2:
+  version "0.4.4"
+  resolved "https://registry.yarnpkg.com/regex-cache/-/regex-cache-0.4.4.tgz#75bdc58a2a1496cec48a12835bc54c8d562336dd"
+  dependencies:
+    is-equal-shallow "^0.1.3"
+
+regexpu-core@^2.0.0:
+  version "2.0.0"
+  resolved "https://registry.yarnpkg.com/regexpu-core/-/regexpu-core-2.0.0.tgz#49d038837b8dcf8bfa5b9a42139938e6ea2ae240"
+  dependencies:
+    regenerate "^1.2.1"
+    regjsgen "^0.2.0"
+    regjsparser "^0.1.4"
+
+regjsgen@^0.2.0:
+  version "0.2.0"
+  resolved "https://registry.yarnpkg.com/regjsgen/-/regjsgen-0.2.0.tgz#6c016adeac554f75823fe37ac05b92d5a4edb1f7"
+
+regjsparser@^0.1.4:
+  version "0.1.5"
+  resolved "https://registry.yarnpkg.com/regjsparser/-/regjsparser-0.1.5.tgz#7ee8f84dc6fa792d3fd0ae228d24bd949ead205c"
+  dependencies:
+    jsesc "~0.5.0"
+
+remove-trailing-separator@^1.0.1:
+  version "1.1.0"
+  resolved "https://registry.yarnpkg.com/remove-trailing-separator/-/remove-trailing-separator-1.1.0.tgz#c24bce2a283adad5bc3f58e0d48249b92379d8ef"
+
+repeat-element@^1.1.2:
+  version "1.1.2"
+  resolved "https://registry.yarnpkg.com/repeat-element/-/repeat-element-1.1.2.tgz#ef089a178d1483baae4d93eb98b4f9e4e11d990a"
+
+repeat-string@^0.2.2:
+  version "0.2.2"
+  resolved "https://registry.yarnpkg.com/repeat-string/-/repeat-string-0.2.2.tgz#c7a8d3236068362059a7e4651fc6884e8b1fb4ae"
+
+repeat-string@^1.5.2:
+  version "1.6.1"
+  resolved "https://registry.yarnpkg.com/repeat-string/-/repeat-string-1.6.1.tgz#8dcae470e1c88abc2d600fff4a776286da75e637"
+
+repeating@^2.0.0:
+  version "2.0.1"
+  resolved "https://registry.yarnpkg.com/repeating/-/repeating-2.0.1.tgz#5214c53a926d3552707527fbab415dbc08d06dda"
+  dependencies:
+    is-finite "^1.0.0"
+
+request-progress@^2.0.1:
+  version "2.0.1"
+  resolved "https://registry.yarnpkg.com/request-progress/-/request-progress-2.0.1.tgz#5d36bb57961c673aa5b788dbc8141fdf23b44e08"
+  dependencies:
+    throttleit "^1.0.0"
+
+request@2.79.0:
+  version "2.79.0"
+  resolved "https://registry.yarnpkg.com/request/-/request-2.79.0.tgz#4dfe5bf6be8b8cdc37fcf93e04b65577722710de"
+  dependencies:
+    aws-sign2 "~0.6.0"
+    aws4 "^1.2.1"
+    caseless "~0.11.0"
+    combined-stream "~1.0.5"
+    extend "~3.0.0"
+    forever-agent "~0.6.1"
+    form-data "~2.1.1"
+    har-validator "~2.0.6"
+    hawk "~3.1.3"
+    http-signature "~1.1.0"
+    is-typedarray "~1.0.0"
+    isstream "~0.1.2"
+    json-stringify-safe "~5.0.1"
+    mime-types "~2.1.7"
+    oauth-sign "~0.8.1"
+    qs "~6.3.0"
+    stringstream "~0.0.4"
+    tough-cookie "~2.3.0"
+    tunnel-agent "~0.4.1"
+    uuid "^3.0.0"
+
+request@2.81.0:
+  version "2.81.0"
+  resolved "https://registry.yarnpkg.com/request/-/request-2.81.0.tgz#c6928946a0e06c5f8d6f8a9333469ffda46298a0"
+  dependencies:
+    aws-sign2 "~0.6.0"
+    aws4 "^1.2.1"
+    caseless "~0.12.0"
+    combined-stream "~1.0.5"
+    extend "~3.0.0"
+    forever-agent "~0.6.1"
+    form-data "~2.1.1"
+    har-validator "~4.2.1"
+    hawk "~3.1.3"
+    http-signature "~1.1.0"
+    is-typedarray "~1.0.0"
+    isstream "~0.1.2"
+    json-stringify-safe "~5.0.1"
+    mime-types "~2.1.7"
+    oauth-sign "~0.8.1"
+    performance-now "^0.2.0"
+    qs "~6.4.0"
+    safe-buffer "^5.0.1"
+    stringstream "~0.0.4"
+    tough-cookie "~2.3.0"
+    tunnel-agent "^0.6.0"
+    uuid "^3.0.0"
+
+request@2.9.x:
+  version "2.9.203"
+  resolved "https://registry.yarnpkg.com/request/-/request-2.9.203.tgz#6c1711a5407fb94a114219563e44145bcbf4723a"
+
+request@^2.81.0:
+  version "2.83.0"
+  resolved "https://registry.yarnpkg.com/request/-/request-2.83.0.tgz#ca0b65da02ed62935887808e6f510381034e3356"
+  dependencies:
+    aws-sign2 "~0.7.0"
+    aws4 "^1.6.0"
+    caseless "~0.12.0"
+    combined-stream "~1.0.5"
+    extend "~3.0.1"
+    forever-agent "~0.6.1"
+    form-data "~2.3.1"
+    har-validator "~5.0.3"
+    hawk "~6.0.2"
+    http-signature "~1.2.0"
+    is-typedarray "~1.0.0"
+    isstream "~0.1.2"
+    json-stringify-safe "~5.0.1"
+    mime-types "~2.1.17"
+    oauth-sign "~0.8.2"
+    performance-now "^2.1.0"
+    qs "~6.5.1"
+    safe-buffer "^5.1.1"
+    stringstream "~0.0.5"
+    tough-cookie "~2.3.3"
+    tunnel-agent "^0.6.0"
+    uuid "^3.1.0"
+
+request@~2.55.0:
+  version "2.55.0"
+  resolved "https://registry.yarnpkg.com/request/-/request-2.55.0.tgz#d75c1cdf679d76bb100f9bffe1fe551b5c24e93d"
+  dependencies:
+    aws-sign2 "~0.5.0"
+    bl "~0.9.0"
+    caseless "~0.9.0"
+    combined-stream "~0.0.5"
+    forever-agent "~0.6.0"
+    form-data "~0.2.0"
+    har-validator "^1.4.0"
+    hawk "~2.3.0"
+    http-signature "~0.10.0"
+    isstream "~0.1.1"
+    json-stringify-safe "~5.0.0"
+    mime-types "~2.0.1"
+    node-uuid "~1.4.0"
+    oauth-sign "~0.6.0"
+    qs "~2.4.0"
+    stringstream "~0.0.4"
+    tough-cookie ">=0.12.0"
+    tunnel-agent "~0.4.0"
+
+require-directory@^2.1.1:
+  version "2.1.1"
+  resolved "https://registry.yarnpkg.com/require-directory/-/require-directory-2.1.1.tgz#8c64ad5fd30dab1c976e2344ffe7f792a6a6df42"
+
+require-main-filename@^1.0.1:
+  version "1.0.1"
+  resolved "https://registry.yarnpkg.com/require-main-filename/-/require-main-filename-1.0.1.tgz#97f717b69d48784f5f526a6c5aa8ffdda055a4d1"
+
+require-relative@^0.8.7:
+  version "0.8.7"
+  resolved "https://registry.yarnpkg.com/require-relative/-/require-relative-0.8.7.tgz#7999539fc9e047a37928fa196f8e1563dabd36de"
+
+requires-port@1.0.x, requires-port@1.x.x, requires-port@~1.0.0:
+  version "1.0.0"
+  resolved "https://registry.yarnpkg.com/requires-port/-/requires-port-1.0.0.tgz#925d2601d39ac485e091cf0da5c6e694dc3dcaff"
+
+resolve-from@^2.0.0:
+  version "2.0.0"
+  resolved "https://registry.yarnpkg.com/resolve-from/-/resolve-from-2.0.0.tgz#9480ab20e94ffa1d9e80a804c7ea147611966b57"
+
+resolve@1.1.x:
+  version "1.1.7"
+  resolved "https://registry.yarnpkg.com/resolve/-/resolve-1.1.7.tgz#203114d82ad2c5ed9e8e0411b3932875e889e97b"
+
+resolve@~0.3.1:
+  version "0.3.1"
+  resolved "https://registry.yarnpkg.com/resolve/-/resolve-0.3.1.tgz#34c63447c664c70598d1c9b126fc43b2a24310a4"
+
+restore-cursor@^1.0.1:
+  version "1.0.1"
+  resolved "https://registry.yarnpkg.com/restore-cursor/-/restore-cursor-1.0.1.tgz#34661f46886327fed2991479152252df92daa541"
+  dependencies:
+    exit-hook "^1.0.0"
+    onetime "^1.0.0"
+
+right-align@^0.1.1:
+  version "0.1.3"
+  resolved "https://registry.yarnpkg.com/right-align/-/right-align-0.1.3.tgz#61339b722fe6a3515689210d24e14c96148613ef"
+  dependencies:
+    align-text "^0.1.1"
+
+rimraf@2, rimraf@^2.2.8, rimraf@^2.3.3, rimraf@^2.5.1, rimraf@^2.5.4, rimraf@^2.6.1, rimraf@^2.6.2:
+  version "2.6.2"
+  resolved "https://registry.yarnpkg.com/rimraf/-/rimraf-2.6.2.tgz#2ed8150d24a16ea8651e6d6ef0f47c4158ce7a36"
+  dependencies:
+    glob "^7.0.5"
+
+rimraf@2.4.3:
+  version "2.4.3"
+  resolved "https://registry.yarnpkg.com/rimraf/-/rimraf-2.4.3.tgz#e5b51c9437a4c582adb955e9f28cf8d945e272af"
+  dependencies:
+    glob "^5.0.14"
+
+rimraf@~2.2.8:
+  version "2.2.8"
+  resolved "https://registry.yarnpkg.com/rimraf/-/rimraf-2.2.8.tgz#e439be2aaee327321952730f99a8929e4fc50582"
+
+ripemd160@0.2.0:
+  version "0.2.0"
+  resolved "https://registry.yarnpkg.com/ripemd160/-/ripemd160-0.2.0.tgz#2bf198bde167cacfa51c0a928e84b68bbe171fce"
+
+run-async@^0.1.0:
+  version "0.1.0"
+  resolved "https://registry.yarnpkg.com/run-async/-/run-async-0.1.0.tgz#c8ad4a5e110661e402a7d21b530e009f25f8e389"
+  dependencies:
+    once "^1.3.0"
+
+rx-lite@^3.1.2:
+  version "3.1.2"
+  resolved "https://registry.yarnpkg.com/rx-lite/-/rx-lite-3.1.2.tgz#19ce502ca572665f3b647b10939f97fd1615f102"
+
+safe-buffer@5.1.1, safe-buffer@^5.0.1, safe-buffer@^5.1.1, safe-buffer@~5.1.0, safe-buffer@~5.1.1:
+  version "5.1.1"
+  resolved "https://registry.yarnpkg.com/safe-buffer/-/safe-buffer-5.1.1.tgz#893312af69b2123def71f57889001671eeb2c853"
+
+sauce-connect-launcher@^0.13.0:
+  version "0.13.0"
+  resolved "https://registry.yarnpkg.com/sauce-connect-launcher/-/sauce-connect-launcher-0.13.0.tgz#25d7df9da16a5ed1caa13df424cb57cb0b6d5a22"
+  dependencies:
+    adm-zip "~0.4.3"
+    async "1.4.0"
+    lodash "3.10.1"
+    rimraf "2.4.3"
+
+saucelabs@^1.0.1:
+  version "1.4.0"
+  resolved "https://registry.yarnpkg.com/saucelabs/-/saucelabs-1.4.0.tgz#b934a9af9da2874b3f40aae1fcde50a4466f5f38"
+  dependencies:
+    https-proxy-agent "^1.0.0"
+
+"semver@2 || 3 || 4 || 5", semver@^5.0.3, semver@^5.3.0:
+  version "5.5.0"
+  resolved "https://registry.yarnpkg.com/semver/-/semver-5.5.0.tgz#dc4bbc7a6ca9d916dee5d43516f0092b58f7b8ab"
+
+semver@~1.0.13:
+  version "1.0.14"
+  resolved "https://registry.yarnpkg.com/semver/-/semver-1.0.14.tgz#cac5e2d55a6fbf958cb220ae844045071c78f676"
+
+semver@~4.3.3:
+  version "4.3.6"
+  resolved "https://registry.yarnpkg.com/semver/-/semver-4.3.6.tgz#300bc6e0e86374f7ba61068b5b1ecd57fc6532da"
+
+semver@~5.0.1:
+  version "5.0.3"
+  resolved "https://registry.yarnpkg.com/semver/-/semver-5.0.3.tgz#77466de589cd5d3c95f138aa78bc569a3cb5d27a"
+
+send@0.0.4:
+  version "0.0.4"
+  resolved "https://registry.yarnpkg.com/send/-/send-0.0.4.tgz#2d4cf79b189fcd09610e1302510ac9b0e4dde800"
+  dependencies:
+    debug "*"
+    fresh "0.1.0"
+    mime "1.2.6"
+    range-parser "0.0.4"
+
+send@0.16.1:
+  version "0.16.1"
+  resolved "https://registry.yarnpkg.com/send/-/send-0.16.1.tgz#a70e1ca21d1382c11d0d9f6231deb281080d7ab3"
+  dependencies:
+    debug "2.6.9"
+    depd "~1.1.1"
+    destroy "~1.0.4"
+    encodeurl "~1.0.1"
+    escape-html "~1.0.3"
+    etag "~1.8.1"
+    fresh "0.5.2"
+    http-errors "~1.6.2"
+    mime "1.4.1"
+    ms "2.0.0"
+    on-finished "~2.3.0"
+    range-parser "~1.2.0"
+    statuses "~1.3.1"
+
+serve-index@^1.7.2:
+  version "1.9.1"
+  resolved "https://registry.yarnpkg.com/serve-index/-/serve-index-1.9.1.tgz#d3768d69b1e7d82e5ce050fff5b453bea12a9239"
+  dependencies:
+    accepts "~1.3.4"
+    batch "0.6.1"
+    debug "2.6.9"
+    escape-html "~1.0.3"
+    http-errors "~1.6.2"
+    mime-types "~2.1.17"
+    parseurl "~1.3.2"
+
+serve-static@1.13.1:
+  version "1.13.1"
+  resolved "https://registry.yarnpkg.com/serve-static/-/serve-static-1.13.1.tgz#4c57d53404a761d8f2e7c1e8a18a47dbf278a719"
+  dependencies:
+    encodeurl "~1.0.1"
+    escape-html "~1.0.3"
+    parseurl "~1.3.2"
+    send "0.16.1"
+
+set-blocking@^2.0.0, set-blocking@~2.0.0:
+  version "2.0.0"
+  resolved "https://registry.yarnpkg.com/set-blocking/-/set-blocking-2.0.0.tgz#045f9782d011ae9a6803ddd382b24392b3d890f7"
+
+set-immediate-shim@^1.0.1:
+  version "1.0.1"
+  resolved "https://registry.yarnpkg.com/set-immediate-shim/-/set-immediate-shim-1.0.1.tgz#4b2b1b27eb808a9f8dcc481a58e5e56f599f3f61"
+
+setimmediate@^1.0.4:
+  version "1.0.5"
+  resolved "https://registry.yarnpkg.com/setimmediate/-/setimmediate-1.0.5.tgz#290cbb232e306942d7d7ea9b83732ab7856f8285"
+
+setprototypeof@1.0.3:
+  version "1.0.3"
+  resolved "https://registry.yarnpkg.com/setprototypeof/-/setprototypeof-1.0.3.tgz#66567e37043eeb4f04d91bd658c0cbefb55b8e04"
+
+setprototypeof@1.1.0:
+  version "1.1.0"
+  resolved "https://registry.yarnpkg.com/setprototypeof/-/setprototypeof-1.1.0.tgz#d0bd85536887b6fe7c0d818cb962d9d91c54e656"
+
+sha.js@2.2.6:
+  version "2.2.6"
+  resolved "https://registry.yarnpkg.com/sha.js/-/sha.js-2.2.6.tgz#17ddeddc5f722fb66501658895461977867315ba"
+
+shebang-command@^1.2.0:
+  version "1.2.0"
+  resolved "https://registry.yarnpkg.com/shebang-command/-/shebang-command-1.2.0.tgz#44aac65b695b03398968c39f363fee5deafdf1ea"
+  dependencies:
+    shebang-regex "^1.0.0"
+
+shebang-regex@^1.0.0:
+  version "1.0.0"
+  resolved "https://registry.yarnpkg.com/shebang-regex/-/shebang-regex-1.0.0.tgz#da42f49740c0b42db2ca9728571cb190c98efea3"
+
+shelljs@^0.5.3:
+  version "0.5.3"
+  resolved "https://registry.yarnpkg.com/shelljs/-/shelljs-0.5.3.tgz#c54982b996c76ef0c1e6b59fbdc5825f5b713113"
+
+sigmund@~1.0.0:
+  version "1.0.1"
+  resolved "https://registry.yarnpkg.com/sigmund/-/sigmund-1.0.1.tgz#3ff21f198cad2175f9f3b781853fd94d0d19b590"
+
+signal-exit@^3.0.0, signal-exit@^3.0.1, signal-exit@^3.0.2:
+  version "3.0.2"
+  resolved "https://registry.yarnpkg.com/signal-exit/-/signal-exit-3.0.2.tgz#b5fdc08f1287ea1178628e415e25132b73646c6d"
+
+slash@^1.0.0:
+  version "1.0.0"
+  resolved "https://registry.yarnpkg.com/slash/-/slash-1.0.0.tgz#c41f2f6c39fc16d1cd17ad4b5d896114ae470d55"
+
+slide@^1.1.5:
+  version "1.1.6"
+  resolved "https://registry.yarnpkg.com/slide/-/slide-1.1.6.tgz#56eb027d65b4d2dce6cb2e2d32c4d4afc9e1d707"
+
+sntp@1.x.x:
+  version "1.0.9"
+  resolved "https://registry.yarnpkg.com/sntp/-/sntp-1.0.9.tgz#6541184cc90aeea6c6e7b35e2659082443c66198"
+  dependencies:
+    hoek "2.x.x"
+
+sntp@2.x.x:
+  version "2.1.0"
+  resolved "https://registry.yarnpkg.com/sntp/-/sntp-2.1.0.tgz#2c6cec14fedc2222739caf9b5c3d85d1cc5a2cc8"
+  dependencies:
+    hoek "4.x.x"
+
+socket.io-adapter@0.5.0:
+  version "0.5.0"
+  resolved "https://registry.yarnpkg.com/socket.io-adapter/-/socket.io-adapter-0.5.0.tgz#cb6d4bb8bec81e1078b99677f9ced0046066bb8b"
+  dependencies:
+    debug "2.3.3"
+    socket.io-parser "2.3.1"
+
+socket.io-client@1.7.4:
+  version "1.7.4"
+  resolved "https://registry.yarnpkg.com/socket.io-client/-/socket.io-client-1.7.4.tgz#ec9f820356ed99ef6d357f0756d648717bdd4281"
+  dependencies:
+    backo2 "1.0.2"
+    component-bind "1.0.0"
+    component-emitter "1.2.1"
+    debug "2.3.3"
+    engine.io-client "~1.8.4"
+    has-binary "0.1.7"
+    indexof "0.0.1"
+    object-component "0.0.3"
+    parseuri "0.0.5"
+    socket.io-parser "2.3.1"
+    to-array "0.1.4"
+
+socket.io-parser@2.3.1:
+  version "2.3.1"
+  resolved "https://registry.yarnpkg.com/socket.io-parser/-/socket.io-parser-2.3.1.tgz#dd532025103ce429697326befd64005fcfe5b4a0"
+  dependencies:
+    component-emitter "1.1.2"
+    debug "2.2.0"
+    isarray "0.0.1"
+    json3 "3.3.2"
+
+socket.io@^1.4.5:
+  version "1.7.4"
+  resolved "https://registry.yarnpkg.com/socket.io/-/socket.io-1.7.4.tgz#2f7ecedc3391bf2d5c73e291fe233e6e34d4dd00"
+  dependencies:
+    debug "2.3.3"
+    engine.io "~1.8.4"
+    has-binary "0.1.7"
+    object-assign "4.1.0"
+    socket.io-adapter "0.5.0"
+    socket.io-client "1.7.4"
+    socket.io-parser "2.3.1"
+
+sockjs-client@^1.0.3:
+  version "1.1.4"
+  resolved "https://registry.yarnpkg.com/sockjs-client/-/sockjs-client-1.1.4.tgz#5babe386b775e4cf14e7520911452654016c8b12"
+  dependencies:
+    debug "^2.6.6"
+    eventsource "0.1.6"
+    faye-websocket "~0.11.0"
+    inherits "^2.0.1"
+    json3 "^3.3.2"
+    url-parse "^1.1.8"
+
+sockjs@^0.3.15:
+  version "0.3.19"
+  resolved "https://registry.yarnpkg.com/sockjs/-/sockjs-0.3.19.tgz#d976bbe800af7bd20ae08598d582393508993c0d"
+  dependencies:
+    faye-websocket "^0.10.0"
+    uuid "^3.0.1"
+
+source-list-map@~0.1.7:
+  version "0.1.8"
+  resolved "https://registry.yarnpkg.com/source-list-map/-/source-list-map-0.1.8.tgz#c550b2ab5427f6b3f21f5afead88c4f5587b2106"
+
+source-map-support@^0.3.2:
+  version "0.3.3"
+  resolved "https://registry.yarnpkg.com/source-map-support/-/source-map-support-0.3.3.tgz#34900977d5ba3f07c7757ee72e73bb1a9b53754f"
+  dependencies:
+    source-map "0.1.32"
+
+source-map-support@^0.4.15, source-map-support@^0.4.18:
+  version "0.4.18"
+  resolved "https://registry.yarnpkg.com/source-map-support/-/source-map-support-0.4.18.tgz#0286a6de8be42641338594e97ccea75f0a2c585f"
+  dependencies:
+    source-map "^0.5.6"
+
+source-map@0.1.32:
+  version "0.1.32"
+  resolved "https://registry.yarnpkg.com/source-map/-/source-map-0.1.32.tgz#c8b6c167797ba4740a8ea33252162ff08591b266"
+  dependencies:
+    amdefine ">=0.0.4"
+
+source-map@^0.1.41:
+  version "0.1.43"
+  resolved "https://registry.yarnpkg.com/source-map/-/source-map-0.1.43.tgz#c24bc146ca517c1471f5dacbe2571b2b7f9e3346"
+  dependencies:
+    amdefine ">=0.0.4"
+
+source-map@^0.4.4, source-map@~0.4.1:
+  version "0.4.4"
+  resolved "https://registry.yarnpkg.com/source-map/-/source-map-0.4.4.tgz#eba4f5da9c0dc999de68032d8b4f76173652036b"
+  dependencies:
+    amdefine ">=0.0.4"
+
+source-map@^0.5.3, source-map@^0.5.6, source-map@^0.5.7, source-map@~0.5.1:
+  version "0.5.7"
+  resolved "https://registry.yarnpkg.com/source-map/-/source-map-0.5.7.tgz#8a039d2d1021d22d1ea14c80d8ea468ba2ef3fcc"
+
+source-map@^0.6.1:
+  version "0.6.1"
+  resolved "https://registry.yarnpkg.com/source-map/-/source-map-0.6.1.tgz#74722af32e9614e9c287a8d0bbde48b5e2f1a263"
+
+source-map@~0.2.0:
+  version "0.2.0"
+  resolved "https://registry.yarnpkg.com/source-map/-/source-map-0.2.0.tgz#dab73fbcfc2ba819b4de03bd6f6eaa48164b3f9d"
+  dependencies:
+    amdefine ">=0.0.4"
+
+spawn-wrap@^1.4.2:
+  version "1.4.2"
+  resolved "https://registry.yarnpkg.com/spawn-wrap/-/spawn-wrap-1.4.2.tgz#cff58e73a8224617b6561abdc32586ea0c82248c"
+  dependencies:
+    foreground-child "^1.5.6"
+    mkdirp "^0.5.0"
+    os-homedir "^1.0.1"
+    rimraf "^2.6.2"
+    signal-exit "^3.0.2"
+    which "^1.3.0"
+
+spdx-correct@^3.0.0:
+  version "3.0.0"
+  resolved "https://registry.yarnpkg.com/spdx-correct/-/spdx-correct-3.0.0.tgz#05a5b4d7153a195bc92c3c425b69f3b2a9524c82"
+  dependencies:
+    spdx-expression-parse "^3.0.0"
+    spdx-license-ids "^3.0.0"
+
+spdx-exceptions@^2.1.0:
+  version "2.1.0"
+  resolved "https://registry.yarnpkg.com/spdx-exceptions/-/spdx-exceptions-2.1.0.tgz#2c7ae61056c714a5b9b9b2b2af7d311ef5c78fe9"
+
+spdx-expression-parse@^3.0.0:
+  version "3.0.0"
+  resolved "https://registry.yarnpkg.com/spdx-expression-parse/-/spdx-expression-parse-3.0.0.tgz#99e119b7a5da00e05491c9fa338b7904823b41d0"
+  dependencies:
+    spdx-exceptions "^2.1.0"
+    spdx-license-ids "^3.0.0"
+
+spdx-license-ids@^3.0.0:
+  version "3.0.0"
+  resolved "https://registry.yarnpkg.com/spdx-license-ids/-/spdx-license-ids-3.0.0.tgz#7a7cd28470cc6d3a1cfe6d66886f6bc430d3ac87"
+
+sprintf-js@~1.0.2:
+  version "1.0.3"
+  resolved "https://registry.yarnpkg.com/sprintf-js/-/sprintf-js-1.0.3.tgz#04e6926f662895354f3dd015203633b857297e2c"
+
+sshpk@^1.7.0:
+  version "1.13.1"
+  resolved "https://registry.yarnpkg.com/sshpk/-/sshpk-1.13.1.tgz#512df6da6287144316dc4c18fe1cf1d940739be3"
+  dependencies:
+    asn1 "~0.2.3"
+    assert-plus "^1.0.0"
+    dashdash "^1.12.0"
+    getpass "^0.1.1"
+  optionalDependencies:
+    bcrypt-pbkdf "^1.0.0"
+    ecc-jsbn "~0.1.1"
+    jsbn "~0.1.0"
+    tweetnacl "~0.14.0"
+
+stack-trace@0.0.x:
+  version "0.0.10"
+  resolved "https://registry.yarnpkg.com/stack-trace/-/stack-trace-0.0.10.tgz#547c70b347e8d32b4e108ea1a2a159e5fdde19c0"
+
+stack-utils@^1.0.0:
+  version "1.0.1"
+  resolved "https://registry.yarnpkg.com/stack-utils/-/stack-utils-1.0.1.tgz#d4f33ab54e8e38778b0ca5cfd3b3afb12db68620"
+
+statuses@1, "statuses@>= 1.3.1 < 2":
+  version "1.4.0"
+  resolved "https://registry.yarnpkg.com/statuses/-/statuses-1.4.0.tgz#bb73d446da2796106efcc1b601a253d6c46bd087"
+
+statuses@~1.3.1:
+  version "1.3.1"
+  resolved "https://registry.yarnpkg.com/statuses/-/statuses-1.3.1.tgz#faf51b9eb74aaef3b3acf4ad5f61abf24cb7b93e"
+
+stream-browserify@^2.0.1:
+  version "2.0.1"
+  resolved "https://registry.yarnpkg.com/stream-browserify/-/stream-browserify-2.0.1.tgz#66266ee5f9bdb9940a4e4514cafb43bb71e5c9db"
+  dependencies:
+    inherits "~2.0.1"
+    readable-stream "^2.0.2"
+
+stream-cache@~0.0.1:
+  version "0.0.2"
+  resolved "https://registry.yarnpkg.com/stream-cache/-/stream-cache-0.0.2.tgz#1ac5ad6832428ca55667dbdee395dad4e6db118f"
+
+stream-http@^2.3.1:
+  version "2.8.0"
+  resolved "https://registry.yarnpkg.com/stream-http/-/stream-http-2.8.0.tgz#fd86546dac9b1c91aff8fc5d287b98fafb41bc10"
+  dependencies:
+    builtin-status-codes "^3.0.0"
+    inherits "^2.0.1"
+    readable-stream "^2.3.3"
+    to-arraybuffer "^1.0.0"
+    xtend "^4.0.0"
+
+string-width@^1.0.1, string-width@^1.0.2:
+  version "1.0.2"
+  resolved "https://registry.yarnpkg.com/string-width/-/string-width-1.0.2.tgz#118bdf5b8cdc51a2a7e70d211e07e2b0b9b107d3"
+  dependencies:
+    code-point-at "^1.0.0"
+    is-fullwidth-code-point "^1.0.0"
+    strip-ansi "^3.0.0"
+
+string-width@^2.0.0, string-width@^2.1.1:
+  version "2.1.1"
+  resolved "https://registry.yarnpkg.com/string-width/-/string-width-2.1.1.tgz#ab93f27a8dc13d28cac815c462143a6d9012ae9e"
+  dependencies:
+    is-fullwidth-code-point "^2.0.0"
+    strip-ansi "^4.0.0"
+
+string_decoder@^0.10.25, string_decoder@~0.10.x:
+  version "0.10.31"
+  resolved "https://registry.yarnpkg.com/string_decoder/-/string_decoder-0.10.31.tgz#62e203bc41766c6c28c9fc84301dab1c5310fa94"
+
+string_decoder@~1.0.3:
+  version "1.0.3"
+  resolved "https://registry.yarnpkg.com/string_decoder/-/string_decoder-1.0.3.tgz#0fc67d7c141825de94282dd536bec6b9bce860ab"
+  dependencies:
+    safe-buffer "~5.1.0"
+
+stringstream@~0.0.4, stringstream@~0.0.5:
+  version "0.0.5"
+  resolved "https://registry.yarnpkg.com/stringstream/-/stringstream-0.0.5.tgz#4e484cd4de5a0bbbee18e46307710a8a81621878"
+
+strip-ansi@^3.0.0, strip-ansi@^3.0.1:
+  version "3.0.1"
+  resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-3.0.1.tgz#6a385fb8853d952d5ff05d0e8aaf94278dc63dcf"
+  dependencies:
+    ansi-regex "^2.0.0"
+
+strip-ansi@^4.0.0:
+  version "4.0.0"
+  resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-4.0.0.tgz#a8479022eb1ac368a871389b635262c505ee368f"
+  dependencies:
+    ansi-regex "^3.0.0"
+
+strip-bom@^2.0.0:
+  version "2.0.0"
+  resolved "https://registry.yarnpkg.com/strip-bom/-/strip-bom-2.0.0.tgz#6219a85616520491f35788bdbf1447a99c7e6b0e"
+  dependencies:
+    is-utf8 "^0.2.0"
+
+strip-eof@^1.0.0:
+  version "1.0.0"
+  resolved "https://registry.yarnpkg.com/strip-eof/-/strip-eof-1.0.0.tgz#bb43ff5598a6eb05d89b59fcd129c983313606bf"
+
+strip-indent@^1.0.1:
+  version "1.0.1"
+  resolved "https://registry.yarnpkg.com/strip-indent/-/strip-indent-1.0.1.tgz#0c7962a6adefa7bbd4ac366460a638552ae1a0a2"
+  dependencies:
+    get-stdin "^4.0.1"
+
+strip-json-comments@~1.0.1:
+  version "1.0.4"
+  resolved "https://registry.yarnpkg.com/strip-json-comments/-/strip-json-comments-1.0.4.tgz#1e15fbcac97d3ee99bf2d73b4c656b082bbafb91"
+
+strip-json-comments@~2.0.1:
+  version "2.0.1"
+  resolved "https://registry.yarnpkg.com/strip-json-comments/-/strip-json-comments-2.0.1.tgz#3c531942e908c2697c0ec344858c286c7ca0a60a"
+
+supports-color@1.2.0:
+  version "1.2.0"
+  resolved "https://registry.yarnpkg.com/supports-color/-/supports-color-1.2.0.tgz#ff1ed1e61169d06b3cf2d588e188b18d8847e17e"
+
+supports-color@^2.0.0:
+  version "2.0.0"
+  resolved "https://registry.yarnpkg.com/supports-color/-/supports-color-2.0.0.tgz#535d045ce6b6363fa40117084629995e9df324c7"
+
+supports-color@^3.1.0, supports-color@^3.1.1, supports-color@^3.1.2:
+  version "3.2.3"
+  resolved "https://registry.yarnpkg.com/supports-color/-/supports-color-3.2.3.tgz#65ac0504b3954171d8a64946b2ae3cbb8a5f54f6"
+  dependencies:
+    has-flag "^1.0.0"
+
+supports-color@^5.3.0:
+  version "5.3.0"
+  resolved "https://registry.yarnpkg.com/supports-color/-/supports-color-5.3.0.tgz#5b24ac15db80fa927cf5227a4a33fd3c4c7676c0"
+  dependencies:
+    has-flag "^3.0.0"
+
+tap-mocha-reporter@^3.0.6:
+  version "3.0.6"
+  resolved "https://registry.yarnpkg.com/tap-mocha-reporter/-/tap-mocha-reporter-3.0.6.tgz#12abe97ff409a5a6ecc3d70b6dba34d82184a770"
+  dependencies:
+    color-support "^1.1.0"
+    debug "^2.1.3"
+    diff "^1.3.2"
+    escape-string-regexp "^1.0.3"
+    glob "^7.0.5"
+    js-yaml "^3.3.1"
+    tap-parser "^5.1.0"
+    unicode-length "^1.0.0"
+  optionalDependencies:
+    readable-stream "^2.1.5"
+
+tap-parser@^5.1.0:
+  version "5.4.0"
+  resolved "https://registry.yarnpkg.com/tap-parser/-/tap-parser-5.4.0.tgz#6907e89725d7b7fa6ae41ee2c464c3db43188aec"
+  dependencies:
+    events-to-array "^1.0.1"
+    js-yaml "^3.2.7"
+  optionalDependencies:
+    readable-stream "^2"
+
+tap-parser@^7.0.0:
+  version "7.0.0"
+  resolved "https://registry.yarnpkg.com/tap-parser/-/tap-parser-7.0.0.tgz#54db35302fda2c2ccc21954ad3be22b2cba42721"
+  dependencies:
+    events-to-array "^1.0.1"
+    js-yaml "^3.2.7"
+    minipass "^2.2.0"
+
+tap@>=0.2.3:
+  version "11.1.1"
+  resolved "https://registry.yarnpkg.com/tap/-/tap-11.1.1.tgz#6dbd23c487127f621a95c793f7a247fa7e2c053a"
+  dependencies:
+    bind-obj-methods "^1.0.0"
+    bluebird "^3.5.1"
+    clean-yaml-object "^0.1.0"
+    color-support "^1.1.0"
+    coveralls "^2.13.3"
+    foreground-child "^1.3.3"
+    fs-exists-cached "^1.0.0"
+    function-loop "^1.0.1"
+    glob "^7.0.0"
+    isexe "^2.0.0"
+    js-yaml "^3.10.0"
+    minipass "^2.2.1"
+    mkdirp "^0.5.1"
+    nyc "^11.3.0"
+    opener "^1.4.1"
+    os-homedir "^1.0.2"
+    own-or "^1.0.0"
+    own-or-env "^1.0.0"
+    rimraf "^2.6.2"
+    signal-exit "^3.0.0"
+    source-map-support "^0.4.18"
+    stack-utils "^1.0.0"
+    tap-mocha-reporter "^3.0.6"
+    tap-parser "^7.0.0"
+    tmatch "^3.1.0"
+    trivial-deferred "^1.0.1"
+    tsame "^1.1.2"
+    write-file-atomic "^2.3.0"
+    yapool "^1.0.0"
+
+tapable@^0.1.8, tapable@~0.1.8:
+  version "0.1.10"
+  resolved "https://registry.yarnpkg.com/tapable/-/tapable-0.1.10.tgz#29c35707c2b70e50d07482b5d202e8ed446dafd4"
+
+tar-pack@^3.4.0:
+  version "3.4.1"
+  resolved "https://registry.yarnpkg.com/tar-pack/-/tar-pack-3.4.1.tgz#e1dbc03a9b9d3ba07e896ad027317eb679a10a1f"
+  dependencies:
+    debug "^2.2.0"
+    fstream "^1.0.10"
+    fstream-ignore "^1.0.5"
+    once "^1.3.3"
+    readable-stream "^2.1.4"
+    rimraf "^2.5.1"
+    tar "^2.2.1"
+    uid-number "^0.0.6"
+
+tar-stream@~1.1.0:
+  version "1.1.5"
+  resolved "https://registry.yarnpkg.com/tar-stream/-/tar-stream-1.1.5.tgz#be9218c130c20029e107b0f967fb23de0579d13c"
+  dependencies:
+    bl "^0.9.0"
+    end-of-stream "^1.0.0"
+    readable-stream "~1.0.33"
+    xtend "^4.0.0"
+
+tar@^2.2.1:
+  version "2.2.1"
+  resolved "https://registry.yarnpkg.com/tar/-/tar-2.2.1.tgz#8e4d2a256c0e2185c6b18ad694aec968b83cb1d1"
+  dependencies:
+    block-stream "*"
+    fstream "^1.0.2"
+    inherits "2"
+
+temporary@~0.0.4:
+  version "0.0.8"
+  resolved "https://registry.yarnpkg.com/temporary/-/temporary-0.0.8.tgz#a18a981d28ba8ca36027fb3c30538c3ecb740ac0"
+  dependencies:
+    package ">= 1.0.0 < 1.2.0"
+
+test-exclude@^4.1.1:
+  version "4.2.0"
+  resolved "https://registry.yarnpkg.com/test-exclude/-/test-exclude-4.2.0.tgz#07e3613609a362c74516a717515e13322ab45b3c"
+  dependencies:
+    arrify "^1.0.1"
+    micromatch "^2.3.11"
+    object-assign "^4.1.0"
+    read-pkg-up "^1.0.1"
+    require-main-filename "^1.0.1"
+
+text-table@~0.2.0:
+  version "0.2.0"
+  resolved "https://registry.yarnpkg.com/text-table/-/text-table-0.2.0.tgz#7f5ee823ae805207c00af2df4a84ec3fcfa570b4"
+
+throttleit@^1.0.0:
+  version "1.0.0"
+  resolved "https://registry.yarnpkg.com/throttleit/-/throttleit-1.0.0.tgz#9e785836daf46743145a5984b6268d828528ac6c"
+
+through@^2.3.6:
+  version "2.3.8"
+  resolved "https://registry.yarnpkg.com/through/-/through-2.3.8.tgz#0dd4c9ffaabc357960b1b724115d7e0e86a2e1f5"
+
+time-stamp@^2.0.0:
+  version "2.0.0"
+  resolved "https://registry.yarnpkg.com/time-stamp/-/time-stamp-2.0.0.tgz#95c6a44530e15ba8d6f4a3ecb8c3a3fac46da357"
+
+timers-browserify@^2.0.2:
+  version "2.0.6"
+  resolved "https://registry.yarnpkg.com/timers-browserify/-/timers-browserify-2.0.6.tgz#241e76927d9ca05f4d959819022f5b3664b64bae"
+  dependencies:
+    setimmediate "^1.0.4"
+
+timespan@2.x.x:
+  version "2.3.0"
+  resolved "https://registry.yarnpkg.com/timespan/-/timespan-2.3.0.tgz#4902ce040bd13d845c8f59b27e9d59bad6f39929"
+
+tiny-lr@^0.2.1:
+  version "0.2.1"
+  resolved "https://registry.yarnpkg.com/tiny-lr/-/tiny-lr-0.2.1.tgz#b3fdba802e5d56a33c2f6f10794b32e477ac729d"
+  dependencies:
+    body-parser "~1.14.0"
+    debug "~2.2.0"
+    faye-websocket "~0.10.0"
+    livereload-js "^2.2.0"
+    parseurl "~1.3.0"
+    qs "~5.1.0"
+
+tmatch@^3.1.0:
+  version "3.1.0"
+  resolved "https://registry.yarnpkg.com/tmatch/-/tmatch-3.1.0.tgz#701264fd7582d0144a80c85af3358cca269c71e3"
+
+tmp@0.0.x:
+  version "0.0.33"
+  resolved "https://registry.yarnpkg.com/tmp/-/tmp-0.0.33.tgz#6d34335889768d21b2bcda0aa277ced3b1bfadf9"
+  dependencies:
+    os-tmpdir "~1.0.2"
+
+to-array@0.1.4:
+  version "0.1.4"
+  resolved "https://registry.yarnpkg.com/to-array/-/to-array-0.1.4.tgz#17e6c11f73dd4f3d74cda7a4ff3238e9ad9bf890"
+
+to-arraybuffer@^1.0.0:
+  version "1.0.1"
+  resolved "https://registry.yarnpkg.com/to-arraybuffer/-/to-arraybuffer-1.0.1.tgz#7d229b1fcc637e466ca081180836a7aabff83f43"
+
+to-fast-properties@^1.0.3:
+  version "1.0.3"
+  resolved "https://registry.yarnpkg.com/to-fast-properties/-/to-fast-properties-1.0.3.tgz#b83571fa4d8c25b82e231b06e3a3055de4ca1a47"
+
+to-iso-string@0.0.2:
+  version "0.0.2"
+  resolved "https://registry.yarnpkg.com/to-iso-string/-/to-iso-string-0.0.2.tgz#4dc19e664dfccbe25bd8db508b00c6da158255d1"
+
+tough-cookie@>=0.12.0, tough-cookie@~2.3.0, tough-cookie@~2.3.3:
+  version "2.3.4"
+  resolved "https://registry.yarnpkg.com/tough-cookie/-/tough-cookie-2.3.4.tgz#ec60cee38ac675063ffc97a5c18970578ee83655"
+  dependencies:
+    punycode "^1.4.1"
+
+trim-newlines@^1.0.0:
+  version "1.0.0"
+  resolved "https://registry.yarnpkg.com/trim-newlines/-/trim-newlines-1.0.0.tgz#5887966bb582a4503a41eb524f7d35011815a613"
+
+trim-right@^1.0.1:
+  version "1.0.1"
+  resolved "https://registry.yarnpkg.com/trim-right/-/trim-right-1.0.1.tgz#cb2e1203067e0c8de1f614094b9fe45704ea6003"
+
+trivial-deferred@^1.0.1:
+  version "1.0.1"
+  resolved "https://registry.yarnpkg.com/trivial-deferred/-/trivial-deferred-1.0.1.tgz#376d4d29d951d6368a6f7a0ae85c2f4d5e0658f3"
+
+tsame@^1.1.2:
+  version "1.1.2"
+  resolved "https://registry.yarnpkg.com/tsame/-/tsame-1.1.2.tgz#5ce0002acf685942789c63018797a2aa5e6b03c5"
+
+tty-browserify@0.0.0:
+  version "0.0.0"
+  resolved "https://registry.yarnpkg.com/tty-browserify/-/tty-browserify-0.0.0.tgz#a157ba402da24e9bf957f9aa69d524eed42901a6"
+
+tunnel-agent@^0.6.0:
+  version "0.6.0"
+  resolved "https://registry.yarnpkg.com/tunnel-agent/-/tunnel-agent-0.6.0.tgz#27a5dea06b36b04a0a9966774b290868f0fc40fd"
+  dependencies:
+    safe-buffer "^5.0.1"
+
+tunnel-agent@~0.4.0, tunnel-agent@~0.4.1:
+  version "0.4.3"
+  resolved "https://registry.yarnpkg.com/tunnel-agent/-/tunnel-agent-0.4.3.tgz#6373db76909fe570e08d73583365ed828a74eeeb"
+
+tweetnacl@^0.14.3, tweetnacl@~0.14.0:
+  version "0.14.5"
+  resolved "https://registry.yarnpkg.com/tweetnacl/-/tweetnacl-0.14.5.tgz#5ae68177f192d4456269d108afa93ff8743f4f64"
+
+type-check@~0.3.1:
+  version "0.3.2"
+  resolved "https://registry.yarnpkg.com/type-check/-/type-check-0.3.2.tgz#5884cab512cf1d355e3fb784f30804b2b520db72"
+  dependencies:
+    prelude-ls "~1.1.2"
+
+type-detect@0.1.1:
+  version "0.1.1"
+  resolved "https://registry.yarnpkg.com/type-detect/-/type-detect-0.1.1.tgz#0ba5ec2a885640e470ea4e8505971900dac58822"
+
+type-detect@^1.0.0:
+  version "1.0.0"
+  resolved "https://registry.yarnpkg.com/type-detect/-/type-detect-1.0.0.tgz#762217cc06db258ec48908a1298e8b95121e8ea2"
+
+type-is@~1.6.10, type-is@~1.6.15:
+  version "1.6.16"
+  resolved "https://registry.yarnpkg.com/type-is/-/type-is-1.6.16.tgz#f89ce341541c672b25ee7ae3c73dee3b2be50194"
+  dependencies:
+    media-typer "0.3.0"
+    mime-types "~2.1.18"
+
+typedarray@^0.0.6:
+  version "0.0.6"
+  resolved "https://registry.yarnpkg.com/typedarray/-/typedarray-0.0.6.tgz#867ac74e3864187b1d3d47d996a78ec5c8830777"
+
+uglify-js@^2.6:
+  version "2.8.29"
+  resolved "https://registry.yarnpkg.com/uglify-js/-/uglify-js-2.8.29.tgz#29c5733148057bb4e1f75df35b7a9cb72e6a59dd"
+  dependencies:
+    source-map "~0.5.1"
+    yargs "~3.10.0"
+  optionalDependencies:
+    uglify-to-browserify "~1.0.0"
+
+uglify-js@~1.3.3:
+  version "1.3.5"
+  resolved "https://registry.yarnpkg.com/uglify-js/-/uglify-js-1.3.5.tgz#4b5bfff9186effbaa888e4c9e94bd9fc4c94929d"
+
+uglify-js@~2.6.2:
+  version "2.6.4"
+  resolved "https://registry.yarnpkg.com/uglify-js/-/uglify-js-2.6.4.tgz#65ea2fb3059c9394692f15fed87c2b36c16b9adf"
+  dependencies:
+    async "~0.2.6"
+    source-map "~0.5.1"
+    uglify-to-browserify "~1.0.0"
+    yargs "~3.10.0"
+
+uglify-js@~2.7.3:
+  version "2.7.5"
+  resolved "https://registry.yarnpkg.com/uglify-js/-/uglify-js-2.7.5.tgz#4612c0c7baaee2ba7c487de4904ae122079f2ca8"
+  dependencies:
+    async "~0.2.6"
+    source-map "~0.5.1"
+    uglify-to-browserify "~1.0.0"
+    yargs "~3.10.0"
+
+uglify-to-browserify@~1.0.0:
+  version "1.0.2"
+  resolved "https://registry.yarnpkg.com/uglify-to-browserify/-/uglify-to-browserify-1.0.2.tgz#6e0924d6bda6b5afe349e39a6d632850a0f882b7"
+
+uid-number@^0.0.6:
+  version "0.0.6"
+  resolved "https://registry.yarnpkg.com/uid-number/-/uid-number-0.0.6.tgz#0ea10e8035e8eb5b8e4449f06da1c730663baa81"
+
+ultron@1.0.x:
+  version "1.0.2"
+  resolved "https://registry.yarnpkg.com/ultron/-/ultron-1.0.2.tgz#ace116ab557cd197386a4e88f4685378c8b2e4fa"
+
+underscore.string@~2.1.1:
+  version "2.1.1"
+  resolved "https://registry.yarnpkg.com/underscore.string/-/underscore.string-2.1.1.tgz#458397799114b9b67f6030bb527b0afae689c061"
+
+underscore.string@~2.2.1:
+  version "2.2.1"
+  resolved "https://registry.yarnpkg.com/underscore.string/-/underscore.string-2.2.1.tgz#d7c0fa2af5d5a1a67f4253daee98132e733f0f19"
+
+underscore.string@~2.3.3:
+  version "2.3.3"
+  resolved "https://registry.yarnpkg.com/underscore.string/-/underscore.string-2.3.3.tgz#71c08bf6b428b1133f37e78fa3a21c82f7329b0d"
+
+underscore.string@~2.4.0:
+  version "2.4.0"
+  resolved "https://registry.yarnpkg.com/underscore.string/-/underscore.string-2.4.0.tgz#8cdd8fbac4e2d2ea1e7e2e8097c42f442280f85b"
+
+underscore.string@~3.0.3:
+  version "3.0.3"
+  resolved "https://registry.yarnpkg.com/underscore.string/-/underscore.string-3.0.3.tgz#4617b8c1a250cf6e5064fbbb363d0fa96cf14552"
+
+underscore@~1.2.4:
+  version "1.2.4"
+  resolved "https://registry.yarnpkg.com/underscore/-/underscore-1.2.4.tgz#e8da6241aa06f64df2473bb2590b8c17c84c3c7e"
+
+underscore@~1.7.0:
+  version "1.7.0"
+  resolved "https://registry.yarnpkg.com/underscore/-/underscore-1.7.0.tgz#6bbaf0877500d36be34ecaa584e0db9fef035209"
+
+unicode-length@^1.0.0:
+  version "1.0.3"
+  resolved "https://registry.yarnpkg.com/unicode-length/-/unicode-length-1.0.3.tgz#5ada7a7fed51841a418a328cf149478ac8358abb"
+  dependencies:
+    punycode "^1.3.2"
+    strip-ansi "^3.0.1"
+
+unpipe@1.0.0, unpipe@~1.0.0:
+  version "1.0.0"
+  resolved "https://registry.yarnpkg.com/unpipe/-/unpipe-1.0.0.tgz#b2bf4ee8514aae6165b4817829d21b2ef49904ec"
+
+uri-path@^1.0.0:
+  version "1.0.0"
+  resolved "https://registry.yarnpkg.com/uri-path/-/uri-path-1.0.0.tgz#9747f018358933c31de0fccfd82d138e67262e32"
+
+url-parse@1.0.x:
+  version "1.0.5"
+  resolved "https://registry.yarnpkg.com/url-parse/-/url-parse-1.0.5.tgz#0854860422afdcfefeb6c965c662d4800169927b"
+  dependencies:
+    querystringify "0.0.x"
+    requires-port "1.0.x"
+
+url-parse@^1.1.8:
+  version "1.2.0"
+  resolved "https://registry.yarnpkg.com/url-parse/-/url-parse-1.2.0.tgz#3a19e8aaa6d023ddd27dcc44cb4fc8f7fec23986"
+  dependencies:
+    querystringify "~1.0.0"
+    requires-port "~1.0.0"
+
+url@^0.11.0:
+  version "0.11.0"
+  resolved "https://registry.yarnpkg.com/url/-/url-0.11.0.tgz#3838e97cfc60521eb73c525a8e55bfdd9e2e28f1"
+  dependencies:
+    punycode "1.3.2"
+    querystring "0.2.0"
+
+user-home@^2.0.0:
+  version "2.0.0"
+  resolved "https://registry.yarnpkg.com/user-home/-/user-home-2.0.0.tgz#9c70bfd8169bc1dcbf48604e0f04b8b49cde9e9f"
+  dependencies:
+    os-homedir "^1.0.0"
+
+useragent@^2.1.6:
+  version "2.3.0"
+  resolved "https://registry.yarnpkg.com/useragent/-/useragent-2.3.0.tgz#217f943ad540cb2128658ab23fc960f6a88c9972"
+  dependencies:
+    lru-cache "4.1.x"
+    tmp "0.0.x"
+
+util-deprecate@~1.0.1:
+  version "1.0.2"
+  resolved "https://registry.yarnpkg.com/util-deprecate/-/util-deprecate-1.0.2.tgz#450d4dc9fa70de732762fbd2d4a28981419a0ccf"
+
+util@0.10.3, util@^0.10.3:
+  version "0.10.3"
+  resolved "https://registry.yarnpkg.com/util/-/util-0.10.3.tgz#7afb1afe50805246489e3db7fe0ed379336ac0f9"
+  dependencies:
+    inherits "2.0.1"
+
+utils-merge@1.0.1:
+  version "1.0.1"
+  resolved "https://registry.yarnpkg.com/utils-merge/-/utils-merge-1.0.1.tgz#9f95710f50a267947b2ccc124741c1028427e713"
+
+uuid@^3.0.0, uuid@^3.0.1, uuid@^3.1.0:
+  version "3.2.1"
+  resolved "https://registry.yarnpkg.com/uuid/-/uuid-3.2.1.tgz#12c528bb9d58d0b9265d9a2f6f0fe8be17ff1f14"
+
+validate-npm-package-license@^3.0.1:
+  version "3.0.3"
+  resolved "https://registry.yarnpkg.com/validate-npm-package-license/-/validate-npm-package-license-3.0.3.tgz#81643bcbef1bdfecd4623793dc4648948ba98338"
+  dependencies:
+    spdx-correct "^3.0.0"
+    spdx-expression-parse "^3.0.0"
+
+vargs@~0.1.0:
+  version "0.1.0"
+  resolved "https://registry.yarnpkg.com/vargs/-/vargs-0.1.0.tgz#6b6184da6520cc3204ce1b407cac26d92609ebff"
+
+vary@~1.1.2:
+  version "1.1.2"
+  resolved "https://registry.yarnpkg.com/vary/-/vary-1.1.2.tgz#2299f02c6ded30d4a5961b0b9f74524a18f634fc"
+
+verror@1.10.0:
+  version "1.10.0"
+  resolved "https://registry.yarnpkg.com/verror/-/verror-1.10.0.tgz#3a105ca17053af55d6e270c1f8288682e18da400"
+  dependencies:
+    assert-plus "^1.0.0"
+    core-util-is "1.0.2"
+    extsprintf "^1.2.0"
+
+vm-browserify@0.0.4:
+  version "0.0.4"
+  resolved "https://registry.yarnpkg.com/vm-browserify/-/vm-browserify-0.0.4.tgz#5d7ea45bbef9e4a6ff65f95438e0a87c357d5a73"
+  dependencies:
+    indexof "0.0.1"
+
+void-elements@^2.0.0:
+  version "2.0.1"
+  resolved "https://registry.yarnpkg.com/void-elements/-/void-elements-2.0.1.tgz#c066afb582bb1cb4128d60ea92392e94d5e9dbec"
+
+watchpack@^0.2.1:
+  version "0.2.9"
+  resolved "https://registry.yarnpkg.com/watchpack/-/watchpack-0.2.9.tgz#62eaa4ab5e5ba35fdfc018275626e3c0f5e3fb0b"
+  dependencies:
+    async "^0.9.0"
+    chokidar "^1.0.0"
+    graceful-fs "^4.1.2"
+
+wd@^0.3.4:
+  version "0.3.12"
+  resolved "https://registry.yarnpkg.com/wd/-/wd-0.3.12.tgz#3fb4f1d759f8c85dde5393d17334ffe03e9bb329"
+  dependencies:
+    archiver "~0.14.0"
+    async "~1.0.0"
+    lodash "~3.9.3"
+    q "~1.4.1"
+    request "~2.55.0"
+    underscore.string "~3.0.3"
+    vargs "~0.1.0"
+
+webpack-core@~0.6.9:
+  version "0.6.9"
+  resolved "https://registry.yarnpkg.com/webpack-core/-/webpack-core-0.6.9.tgz#fc571588c8558da77be9efb6debdc5a3b172bdc2"
+  dependencies:
+    source-list-map "~0.1.7"
+    source-map "~0.4.1"
+
+webpack-dev-middleware@^1.0.11, webpack-dev-middleware@^1.10.2:
+  version "1.12.2"
+  resolved "https://registry.yarnpkg.com/webpack-dev-middleware/-/webpack-dev-middleware-1.12.2.tgz#f8fc1120ce3b4fc5680ceecb43d777966b21105e"
+  dependencies:
+    memory-fs "~0.4.1"
+    mime "^1.5.0"
+    path-is-absolute "^1.0.0"
+    range-parser "^1.0.3"
+    time-stamp "^2.0.0"
+
+webpack-dev-server@^1.12.0:
+  version "1.16.5"
+  resolved "https://registry.yarnpkg.com/webpack-dev-server/-/webpack-dev-server-1.16.5.tgz#0cbd5f2d2ac8d4e593aacd5c9702e7bbd5e59892"
+  dependencies:
+    compression "^1.5.2"
+    connect-history-api-fallback "^1.3.0"
+    express "^4.13.3"
+    http-proxy-middleware "~0.17.1"
+    open "0.0.5"
+    optimist "~0.6.1"
+    serve-index "^1.7.2"
+    sockjs "^0.3.15"
+    sockjs-client "^1.0.3"
+    stream-cache "~0.0.1"
+    strip-ansi "^3.0.0"
+    supports-color "^3.1.1"
+    webpack-dev-middleware "^1.10.2"
+
+webpack@^1.12.2:
+  version "1.15.0"
+  resolved "https://registry.yarnpkg.com/webpack/-/webpack-1.15.0.tgz#4ff31f53db03339e55164a9d468ee0324968fe98"
+  dependencies:
+    acorn "^3.0.0"
+    async "^1.3.0"
+    clone "^1.0.2"
+    enhanced-resolve "~0.9.0"
+    interpret "^0.6.4"
+    loader-utils "^0.2.11"
+    memory-fs "~0.3.0"
+    mkdirp "~0.5.0"
+    node-libs-browser "^0.7.0"
+    optimist "~0.6.0"
+    supports-color "^3.1.0"
+    tapable "~0.1.8"
+    uglify-js "~2.7.3"
+    watchpack "^0.2.1"
+    webpack-core "~0.6.9"
+
+websocket-driver@>=0.5.1:
+  version "0.7.0"
+  resolved "https://registry.yarnpkg.com/websocket-driver/-/websocket-driver-0.7.0.tgz#0caf9d2d755d93aee049d4bdd0d3fe2cca2a24eb"
+  dependencies:
+    http-parser-js ">=0.4.0"
+    websocket-extensions ">=0.1.1"
+
+websocket-extensions@>=0.1.1:
+  version "0.1.3"
+  resolved "https://registry.yarnpkg.com/websocket-extensions/-/websocket-extensions-0.1.3.tgz#5d2ff22977003ec687a4b87073dfbbac146ccf29"
+
+which-module@^2.0.0:
+  version "2.0.0"
+  resolved "https://registry.yarnpkg.com/which-module/-/which-module-2.0.0.tgz#d9ef07dce77b9902b8a3a8fa4b31c3e3f7e6e87a"
+
+which@^1.1.1, which@^1.2.10, which@^1.2.9, which@^1.3.0:
+  version "1.3.0"
+  resolved "https://registry.yarnpkg.com/which/-/which-1.3.0.tgz#ff04bdfc010ee547d780bec38e1ac1c2777d253a"
+  dependencies:
+    isexe "^2.0.0"
+
+which@~1.0.5:
+  version "1.0.9"
+  resolved "https://registry.yarnpkg.com/which/-/which-1.0.9.tgz#460c1da0f810103d0321a9b633af9e575e64486f"
+
+wide-align@^1.1.0:
+  version "1.1.2"
+  resolved "https://registry.yarnpkg.com/wide-align/-/wide-align-1.1.2.tgz#571e0f1b0604636ebc0dfc21b0339bbe31341710"
+  dependencies:
+    string-width "^1.0.2"
+
+window-size@0.1.0:
+  version "0.1.0"
+  resolved "https://registry.yarnpkg.com/window-size/-/window-size-0.1.0.tgz#5438cd2ea93b202efa3a19fe8887aee7c94f9c9d"
+
+winston@0.5.x:
+  version "0.5.11"
+  resolved "https://registry.yarnpkg.com/winston/-/winston-0.5.11.tgz#9d84ead981a497a92ddf76616137abef661c414f"
+  dependencies:
+    async "0.1.x"
+    colors "0.x.x"
+    eyes "0.1.x"
+    loggly "0.3.x >=0.3.7"
+    pkginfo "0.2.x"
+    stack-trace "0.0.x"
+
+wordwrap@0.0.2:
+  version "0.0.2"
+  resolved "https://registry.yarnpkg.com/wordwrap/-/wordwrap-0.0.2.tgz#b79669bb42ecb409f83d583cad52ca17eaa1643f"
+
+wordwrap@^1.0.0:
+  version "1.0.0"
+  resolved "https://registry.yarnpkg.com/wordwrap/-/wordwrap-1.0.0.tgz#27584810891456a4171c8d0226441ade90cbcaeb"
+
+wordwrap@~0.0.2:
+  version "0.0.3"
+  resolved "https://registry.yarnpkg.com/wordwrap/-/wordwrap-0.0.3.tgz#a3d5da6cd5c0bc0008d37234bbaf1bed63059107"
+
+wrap-ansi@^2.0.0:
+  version "2.1.0"
+  resolved "https://registry.yarnpkg.com/wrap-ansi/-/wrap-ansi-2.1.0.tgz#d8fc3d284dd05794fe84973caecdd1cf824fdd85"
+  dependencies:
+    string-width "^1.0.1"
+    strip-ansi "^3.0.1"
+
+wrappy@1:
+  version "1.0.2"
+  resolved "https://registry.yarnpkg.com/wrappy/-/wrappy-1.0.2.tgz#b5243d8f3ec1aa35f1364605bc0d1036e30ab69f"
+
+write-file-atomic@^1.1.4:
+  version "1.3.4"
+  resolved "https://registry.yarnpkg.com/write-file-atomic/-/write-file-atomic-1.3.4.tgz#f807a4f0b1d9e913ae7a48112e6cc3af1991b45f"
+  dependencies:
+    graceful-fs "^4.1.11"
+    imurmurhash "^0.1.4"
+    slide "^1.1.5"
+
+write-file-atomic@^2.3.0:
+  version "2.3.0"
+  resolved "https://registry.yarnpkg.com/write-file-atomic/-/write-file-atomic-2.3.0.tgz#1ff61575c2e2a4e8e510d6fa4e243cce183999ab"
+  dependencies:
+    graceful-fs "^4.1.11"
+    imurmurhash "^0.1.4"
+    signal-exit "^3.0.2"
+
+write@^0.2.1:
+  version "0.2.1"
+  resolved "https://registry.yarnpkg.com/write/-/write-0.2.1.tgz#5fc03828e264cea3fe91455476f7a3c566cb0757"
+  dependencies:
+    mkdirp "^0.5.1"
+
+ws@~1.1.5:
+  version "1.1.5"
+  resolved "https://registry.yarnpkg.com/ws/-/ws-1.1.5.tgz#cbd9e6e75e09fc5d2c90015f21f0c40875e0dd51"
+  dependencies:
+    options ">=0.0.5"
+    ultron "1.0.x"
+
+wtf-8@1.0.0:
+  version "1.0.0"
+  resolved "https://registry.yarnpkg.com/wtf-8/-/wtf-8-1.0.0.tgz#392d8ba2d0f1c34d1ee2d630f15d0efb68e1048a"
+
+xml-escape@~1.0.0:
+  version "1.0.0"
+  resolved "https://registry.yarnpkg.com/xml-escape/-/xml-escape-1.0.0.tgz#00963d697b2adf0c185c4e04e73174ba9b288eb2"
+
+xmlhttprequest-ssl@1.5.3:
+  version "1.5.3"
+  resolved "https://registry.yarnpkg.com/xmlhttprequest-ssl/-/xmlhttprequest-ssl-1.5.3.tgz#185a888c04eca46c3e4070d99f7b49de3528992d"
+
+xtend@^4.0.0:
+  version "4.0.1"
+  resolved "https://registry.yarnpkg.com/xtend/-/xtend-4.0.1.tgz#a5c6d532be656e23db820efb943a1f04998d63af"
+
+y18n@^3.2.1:
+  version "3.2.1"
+  resolved "https://registry.yarnpkg.com/y18n/-/y18n-3.2.1.tgz#6d15fba884c08679c0d77e88e7759e811e07fa41"
+
+yallist@^2.1.2:
+  version "2.1.2"
+  resolved "https://registry.yarnpkg.com/yallist/-/yallist-2.1.2.tgz#1c11f9218f076089a47dd512f93c6699a6a81d52"
+
+yallist@^3.0.0:
+  version "3.0.2"
+  resolved "https://registry.yarnpkg.com/yallist/-/yallist-3.0.2.tgz#8452b4bb7e83c7c188d8041c1a837c773d6d8bb9"
+
+yapool@^1.0.0:
+  version "1.0.0"
+  resolved "https://registry.yarnpkg.com/yapool/-/yapool-1.0.0.tgz#f693f29a315b50d9a9da2646a7a6645c96985b6a"
+
+yargs-parser@^8.0.0, yargs-parser@^8.1.0:
+  version "8.1.0"
+  resolved "https://registry.yarnpkg.com/yargs-parser/-/yargs-parser-8.1.0.tgz#f1376a33b6629a5d063782944da732631e966950"
+  dependencies:
+    camelcase "^4.1.0"
+
+yargs@^10.0.3:
+  version "10.1.2"
+  resolved "https://registry.yarnpkg.com/yargs/-/yargs-10.1.2.tgz#454d074c2b16a51a43e2fb7807e4f9de69ccb5c5"
+  dependencies:
+    cliui "^4.0.0"
+    decamelize "^1.1.1"
+    find-up "^2.1.0"
+    get-caller-file "^1.0.1"
+    os-locale "^2.0.0"
+    require-directory "^2.1.1"
+    require-main-filename "^1.0.1"
+    set-blocking "^2.0.0"
+    string-width "^2.0.0"
+    which-module "^2.0.0"
+    y18n "^3.2.1"
+    yargs-parser "^8.1.0"
+
+yargs@~3.10.0:
+  version "3.10.0"
+  resolved "https://registry.yarnpkg.com/yargs/-/yargs-3.10.0.tgz#f7ee7bd857dd7c1d2d38c0e74efbd681d1431fd1"
+  dependencies:
+    camelcase "^1.0.2"
+    cliui "^2.1.0"
+    decamelize "^1.0.0"
+    window-size "0.1.0"
+
+yauzl@2.4.1:
+  version "2.4.1"
+  resolved "https://registry.yarnpkg.com/yauzl/-/yauzl-2.4.1.tgz#9528f442dab1b2284e58b4379bb194e22e0c4005"
+  dependencies:
+    fd-slicer "~1.0.1"
+
+yeast@0.1.2:
+  version "0.1.2"
+  resolved "https://registry.yarnpkg.com/yeast/-/yeast-0.1.2.tgz#008e06d8094320c372dbc2f8ed76a0ca6c8ac419"
+
+zip-stream@~0.5.0:
+  version "0.5.2"
+  resolved "https://registry.yarnpkg.com/zip-stream/-/zip-stream-0.5.2.tgz#32dcbc506d0dab4d21372625bd7ebaac3c2fff56"
+  dependencies:
+    compress-commons "~0.2.0"
+    lodash "~3.2.0"
+    readable-stream "~1.0.26"
diff --git a/node_modules/escape-string-regexp/index.js b/node_modules/escape-string-regexp/index.js
new file mode 100644
index 0000000..7834bf9
--- /dev/null
+++ b/node_modules/escape-string-regexp/index.js
@@ -0,0 +1,11 @@
+'use strict';
+
+var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g;
+
+module.exports = function (str) {
+	if (typeof str !== 'string') {
+		throw new TypeError('Expected a string');
+	}
+
+	return str.replace(matchOperatorsRe, '\\$&');
+};
diff --git a/node_modules/escape-string-regexp/license b/node_modules/escape-string-regexp/license
new file mode 100644
index 0000000..654d0bf
--- /dev/null
+++ b/node_modules/escape-string-regexp/license
@@ -0,0 +1,21 @@
+The MIT License (MIT)
+
+Copyright (c) Sindre Sorhus  (sindresorhus.com)
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
diff --git a/node_modules/escape-string-regexp/package.json b/node_modules/escape-string-regexp/package.json
new file mode 100644
index 0000000..2e83f83
--- /dev/null
+++ b/node_modules/escape-string-regexp/package.json
@@ -0,0 +1,81 @@
+{
+  "_from": "escape-string-regexp@1.0.5",
+  "_id": "escape-string-regexp@1.0.5",
+  "_inBundle": false,
+  "_integrity": "sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=",
+  "_location": "/escape-string-regexp",
+  "_phantomChildren": {},
+  "_requested": {
+    "type": "version",
+    "registry": true,
+    "raw": "escape-string-regexp@1.0.5",
+    "name": "escape-string-regexp",
+    "escapedName": "escape-string-regexp",
+    "rawSpec": "1.0.5",
+    "saveSpec": null,
+    "fetchSpec": "1.0.5"
+  },
+  "_requiredBy": [
+    "/mocha"
+  ],
+  "_resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz",
+  "_shasum": "1b61c0562190a8dff6ae3bb2cf0200ca130b86d4",
+  "_spec": "escape-string-regexp@1.0.5",
+  "_where": "/Users/jessitron/code/jessitron/stringify-tree/node_modules/mocha",
+  "author": {
+    "name": "Sindre Sorhus",
+    "email": "sindresorhus@gmail.com",
+    "url": "sindresorhus.com"
+  },
+  "bugs": {
+    "url": "https://github.com/sindresorhus/escape-string-regexp/issues"
+  },
+  "bundleDependencies": false,
+  "deprecated": false,
+  "description": "Escape RegExp special characters",
+  "devDependencies": {
+    "ava": "*",
+    "xo": "*"
+  },
+  "engines": {
+    "node": ">=0.8.0"
+  },
+  "files": [
+    "index.js"
+  ],
+  "homepage": "https://github.com/sindresorhus/escape-string-regexp#readme",
+  "keywords": [
+    "escape",
+    "regex",
+    "regexp",
+    "re",
+    "regular",
+    "expression",
+    "string",
+    "str",
+    "special",
+    "characters"
+  ],
+  "license": "MIT",
+  "maintainers": [
+    {
+      "name": "Sindre Sorhus",
+      "email": "sindresorhus@gmail.com",
+      "url": "sindresorhus.com"
+    },
+    {
+      "name": "Joshua Boy Nicolai Appelman",
+      "email": "joshua@jbna.nl",
+      "url": "jbna.nl"
+    }
+  ],
+  "name": "escape-string-regexp",
+  "repository": {
+    "type": "git",
+    "url": "git+https://github.com/sindresorhus/escape-string-regexp.git"
+  },
+  "scripts": {
+    "test": "xo && ava"
+  },
+  "version": "1.0.5"
+}
diff --git a/node_modules/escape-string-regexp/readme.md b/node_modules/escape-string-regexp/readme.md
new file mode 100644
index 0000000..87ac82d
--- /dev/null
+++ b/node_modules/escape-string-regexp/readme.md
@@ -0,0 +1,27 @@
+# escape-string-regexp [![Build Status](https://travis-ci.org/sindresorhus/escape-string-regexp.svg?branch=master)](https://travis-ci.org/sindresorhus/escape-string-regexp)
+
+> Escape RegExp special characters
+
+
+## Install
+
+```
+$ npm install --save escape-string-regexp
+```
+
+
+## Usage
+
+```js
+const escapeStringRegexp = require('escape-string-regexp');
+
+const escapedString = escapeStringRegexp('how much $ for a unicorn?');
+//=> 'how much \$ for a unicorn\?'
+
+new RegExp(escapedString);
+```
+
+
+## License
+
+MIT © [Sindre Sorhus](http://sindresorhus.com)
diff --git a/node_modules/fs.realpath/LICENSE b/node_modules/fs.realpath/LICENSE
new file mode 100644
index 0000000..5bd884c
--- /dev/null
+++ b/node_modules/fs.realpath/LICENSE
@@ -0,0 +1,43 @@
+The ISC License
+
+Copyright (c) Isaac Z. Schlueter and Contributors
+
+Permission to use, copy, modify, and/or distribute this software for any
+purpose with or without fee is hereby granted, provided that the above
+copyright notice and this permission notice appear in all copies.
+
+THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
+IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+
+----
+
+This library bundles a version of the `fs.realpath` and `fs.realpathSync`
+methods from Node.js v0.10 under the terms of the Node.js MIT license.
+
+Node's license follows, also included at the header of `old.js` which contains
+the licensed code:
+
+  Copyright Joyent, Inc. and other Node contributors.
+
+  Permission is hereby granted, free of charge, to any person obtaining a
+  copy of this software and associated documentation files (the "Software"),
+  to deal in the Software without restriction, including without limitation
+  the rights to use, copy, modify, merge, publish, distribute, sublicense,
+  and/or sell copies of the Software, and to permit persons to whom the
+  Software is furnished to do so, subject to the following conditions:
+
+  The above copyright notice and this permission notice shall be included in
+  all copies or substantial portions of the Software.
+
+  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+  DEALINGS IN THE SOFTWARE.
diff --git a/node_modules/fs.realpath/README.md b/node_modules/fs.realpath/README.md
new file mode 100644
index 0000000..a42ceac
--- /dev/null
+++ b/node_modules/fs.realpath/README.md
@@ -0,0 +1,33 @@
+# fs.realpath
+
+A backwards-compatible fs.realpath for Node v6 and above
+
+In Node v6, the JavaScript implementation of fs.realpath was replaced
+with a faster (but less resilient) native implementation.  That raises
+new and platform-specific errors and cannot handle long or excessively
+symlink-looping paths.
+
+This module handles those cases by detecting the new errors and
+falling back to the JavaScript implementation.  On versions of Node
+prior to v6, it has no effect.
+
+## USAGE
+
+```js
+var rp = require('fs.realpath')
+
+// async version
+rp.realpath(someLongAndLoopingPath, function (er, real) {
+  // the ELOOP was handled, but it was a bit slower
+})
+
+// sync version
+var real = rp.realpathSync(someLongAndLoopingPath)
+
+// monkeypatch at your own risk!
+// This replaces the fs.realpath/fs.realpathSync builtins
+rp.monkeypatch()
+
+// un-do the monkeypatching
+rp.unmonkeypatch()
+```
diff --git a/node_modules/fs.realpath/index.js b/node_modules/fs.realpath/index.js
new file mode 100644
index 0000000..b09c7c7
--- /dev/null
+++ b/node_modules/fs.realpath/index.js
@@ -0,0 +1,66 @@
+module.exports = realpath
+realpath.realpath = realpath
+realpath.sync = realpathSync
+realpath.realpathSync = realpathSync
+realpath.monkeypatch = monkeypatch
+realpath.unmonkeypatch = unmonkeypatch
+
+var fs = require('fs')
+var origRealpath = fs.realpath
+var origRealpathSync = fs.realpathSync
+
+var version = process.version
+var ok = /^v[0-5]\./.test(version)
+var old = require('./old.js')
+
+function newError (er) {
+  return er && er.syscall === 'realpath' && (
+    er.code === 'ELOOP' ||
+    er.code === 'ENOMEM' ||
+    er.code === 'ENAMETOOLONG'
+  )
+}
+
+function realpath (p, cache, cb) {
+  if (ok) {
+    return origRealpath(p, cache, cb)
+  }
+
+  if (typeof cache === 'function') {
+    cb = cache
+    cache = null
+  }
+  origRealpath(p, cache, function (er, result) {
+    if (newError(er)) {
+      old.realpath(p, cache, cb)
+    } else {
+      cb(er, result)
+    }
+  })
+}
+
+function realpathSync (p, cache) {
+  if (ok) {
+    return origRealpathSync(p, cache)
+  }
+
+  try {
+    return origRealpathSync(p, cache)
+  } catch (er) {
+    if (newError(er)) {
+      return old.realpathSync(p, cache)
+    } else {
+      throw er
+    }
+  }
+}
+
+function monkeypatch () {
+  fs.realpath = realpath
+  fs.realpathSync = realpathSync
+}
+
+function unmonkeypatch () {
+  fs.realpath = origRealpath
+  fs.realpathSync = origRealpathSync
+}
diff --git a/node_modules/fs.realpath/old.js b/node_modules/fs.realpath/old.js
new file mode 100644
index 0000000..b40305e
--- /dev/null
+++ b/node_modules/fs.realpath/old.js
@@ -0,0 +1,303 @@
+// Copyright Joyent, Inc. and other Node contributors.
+//
+// Permission is hereby granted, free of charge, to any person obtaining a
+// copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to permit
+// persons to whom the Software is furnished to do so, subject to the
+// following conditions:
+//
+// The above copyright notice and this permission notice shall be included
+// in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
+// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
+// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
+// USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+var pathModule = require('path');
+var isWindows = process.platform === 'win32';
+var fs = require('fs');
+
+// JavaScript implementation of realpath, ported from node pre-v6
+
+var DEBUG = process.env.NODE_DEBUG && /fs/.test(process.env.NODE_DEBUG);
+
+function rethrow() {
+  // Only enable in debug mode. A backtrace uses ~1000 bytes of heap space and
+  // is fairly slow to generate.
+  var callback;
+  if (DEBUG) {
+    var backtrace = new Error;
+    callback = debugCallback;
+  } else
+    callback = missingCallback;
+
+  return callback;
+
+  function debugCallback(err) {
+    if (err) {
+      backtrace.message = err.message;
+      err = backtrace;
+      missingCallback(err);
+    }
+  }
+
+  function missingCallback(err) {
+    if (err) {
+      if (process.throwDeprecation)
+        throw err;  // Forgot a callback but don't know where? Use NODE_DEBUG=fs
+      else if (!process.noDeprecation) {
+        var msg = 'fs: missing callback ' + (err.stack || err.message);
+        if (process.traceDeprecation)
+          console.trace(msg);
+        else
+          console.error(msg);
+      }
+    }
+  }
+}
+
+function maybeCallback(cb) {
+  return typeof cb === 'function' ? cb : rethrow();
+}
+
+var normalize = pathModule.normalize;
+
+// Regexp that finds the next partion of a (partial) path
+// result is [base_with_slash, base], e.g. ['somedir/', 'somedir']
+if (isWindows) {
+  var nextPartRe = /(.*?)(?:[\/\\]+|$)/g;
+} else {
+  var nextPartRe = /(.*?)(?:[\/]+|$)/g;
+}
+
+// Regex to find the device root, including trailing slash. E.g. 'c:\\'.
+if (isWindows) {
+  var splitRootRe = /^(?:[a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/][^\\\/]+)?[\\\/]*/;
+} else {
+  var splitRootRe = /^[\/]*/;
+}
+
+exports.realpathSync = function realpathSync(p, cache) {
+  // make p is absolute
+  p = pathModule.resolve(p);
+
+  if (cache && Object.prototype.hasOwnProperty.call(cache, p)) {
+    return cache[p];
+  }
+
+  var original = p,
+      seenLinks = {},
+      knownHard = {};
+
+  // current character position in p
+  var pos;
+  // the partial path so far, including a trailing slash if any
+  var current;
+  // the partial path without a trailing slash (except when pointing at a root)
+  var base;
+  // the partial path scanned in the previous round, with slash
+  var previous;
+
+  start();
+
+  function start() {
+    // Skip over roots
+    var m = splitRootRe.exec(p);
+    pos = m[0].length;
+    current = m[0];
+    base = m[0];
+    previous = '';
+
+    // On windows, check that the root exists. On unix there is no need.
+    if (isWindows && !knownHard[base]) {
+      fs.lstatSync(base);
+      knownHard[base] = true;
+    }
+  }
+
+  // walk down the path, swapping out linked pathparts for their real
+  // values
+  // NB: p.length changes.
+  while (pos < p.length) {
+    // find the next part
+    nextPartRe.lastIndex = pos;
+    var result = nextPartRe.exec(p);
+    previous = current;
+    current += result[0];
+    base = previous + result[1];
+    pos = nextPartRe.lastIndex;
+
+    // continue if not a symlink
+    if (knownHard[base] || (cache && cache[base] === base)) {
+      continue;
+    }
+
+    var resolvedLink;
+    if (cache && Object.prototype.hasOwnProperty.call(cache, base)) {
+      // some known symbolic link.  no need to stat again.
+      resolvedLink = cache[base];
+    } else {
+      var stat = fs.lstatSync(base);
+      if (!stat.isSymbolicLink()) {
+        knownHard[base] = true;
+        if (cache) cache[base] = base;
+        continue;
+      }
+
+      // read the link if it wasn't read before
+      // dev/ino always return 0 on windows, so skip the check.
+      var linkTarget = null;
+      if (!isWindows) {
+        var id = stat.dev.toString(32) + ':' + stat.ino.toString(32);
+        if (seenLinks.hasOwnProperty(id)) {
+          linkTarget = seenLinks[id];
+        }
+      }
+      if (linkTarget === null) {
+        fs.statSync(base);
+        linkTarget = fs.readlinkSync(base);
+      }
+      resolvedLink = pathModule.resolve(previous, linkTarget);
+      // track this, if given a cache.
+      if (cache) cache[base] = resolvedLink;
+      if (!isWindows) seenLinks[id] = linkTarget;
+    }
+
+    // resolve the link, then start over
+    p = pathModule.resolve(resolvedLink, p.slice(pos));
+    start();
+  }
+
+  if (cache) cache[original] = p;
+
+  return p;
+};
+
+
+exports.realpath = function realpath(p, cache, cb) {
+  if (typeof cb !== 'function') {
+    cb = maybeCallback(cache);
+    cache = null;
+  }
+
+  // make p is absolute
+  p = pathModule.resolve(p);
+
+  if (cache && Object.prototype.hasOwnProperty.call(cache, p)) {
+    return process.nextTick(cb.bind(null, null, cache[p]));
+  }
+
+  var original = p,
+      seenLinks = {},
+      knownHard = {};
+
+  // current character position in p
+  var pos;
+  // the partial path so far, including a trailing slash if any
+  var current;
+  // the partial path without a trailing slash (except when pointing at a root)
+  var base;
+  // the partial path scanned in the previous round, with slash
+  var previous;
+
+  start();
+
+  function start() {
+    // Skip over roots
+    var m = splitRootRe.exec(p);
+    pos = m[0].length;
+    current = m[0];
+    base = m[0];
+    previous = '';
+
+    // On windows, check that the root exists. On unix there is no need.
+    if (isWindows && !knownHard[base]) {
+      fs.lstat(base, function(err) {
+        if (err) return cb(err);
+        knownHard[base] = true;
+        LOOP();
+      });
+    } else {
+      process.nextTick(LOOP);
+    }
+  }
+
+  // walk down the path, swapping out linked pathparts for their real
+  // values
+  function LOOP() {
+    // stop if scanned past end of path
+    if (pos >= p.length) {
+      if (cache) cache[original] = p;
+      return cb(null, p);
+    }
+
+    // find the next part
+    nextPartRe.lastIndex = pos;
+    var result = nextPartRe.exec(p);
+    previous = current;
+    current += result[0];
+    base = previous + result[1];
+    pos = nextPartRe.lastIndex;
+
+    // continue if not a symlink
+    if (knownHard[base] || (cache && cache[base] === base)) {
+      return process.nextTick(LOOP);
+    }
+
+    if (cache && Object.prototype.hasOwnProperty.call(cache, base)) {
+      // known symbolic link.  no need to stat again.
+      return gotResolvedLink(cache[base]);
+    }
+
+    return fs.lstat(base, gotStat);
+  }
+
+  function gotStat(err, stat) {
+    if (err) return cb(err);
+
+    // if not a symlink, skip to the next path part
+    if (!stat.isSymbolicLink()) {
+      knownHard[base] = true;
+      if (cache) cache[base] = base;
+      return process.nextTick(LOOP);
+    }
+
+    // stat & read the link if not read before
+    // call gotTarget as soon as the link target is known
+    // dev/ino always return 0 on windows, so skip the check.
+    if (!isWindows) {
+      var id = stat.dev.toString(32) + ':' + stat.ino.toString(32);
+      if (seenLinks.hasOwnProperty(id)) {
+        return gotTarget(null, seenLinks[id], base);
+      }
+    }
+    fs.stat(base, function(err) {
+      if (err) return cb(err);
+
+      fs.readlink(base, function(err, target) {
+        if (!isWindows) seenLinks[id] = target;
+        gotTarget(err, target);
+      });
+    });
+  }
+
+  function gotTarget(err, target, base) {
+    if (err) return cb(err);
+
+    var resolvedLink = pathModule.resolve(previous, target);
+    if (cache) cache[base] = resolvedLink;
+    gotResolvedLink(resolvedLink);
+  }
+
+  function gotResolvedLink(resolvedLink) {
+    // resolve the link, then start over
+    p = pathModule.resolve(resolvedLink, p.slice(pos));
+    start();
+  }
+};
diff --git a/node_modules/fs.realpath/package.json b/node_modules/fs.realpath/package.json
new file mode 100644
index 0000000..02684b5
--- /dev/null
+++ b/node_modules/fs.realpath/package.json
@@ -0,0 +1,59 @@
+{
+  "_from": "fs.realpath@^1.0.0",
+  "_id": "fs.realpath@1.0.0",
+  "_inBundle": false,
+  "_integrity": "sha1-FQStJSMVjKpA20onh8sBQRmU6k8=",
+  "_location": "/fs.realpath",
+  "_phantomChildren": {},
+  "_requested": {
+    "type": "range",
+    "registry": true,
+    "raw": "fs.realpath@^1.0.0",
+    "name": "fs.realpath",
+    "escapedName": "fs.realpath",
+    "rawSpec": "^1.0.0",
+    "saveSpec": null,
+    "fetchSpec": "^1.0.0"
+  },
+  "_requiredBy": [
+    "/glob"
+  ],
+  "_resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz",
+  "_shasum": "1504ad2523158caa40db4a2787cb01411994ea4f",
+  "_spec": "fs.realpath@^1.0.0",
+  "_where": "/Users/jessitron/code/jessitron/stringify-tree/node_modules/glob",
+  "author": {
+    "name": "Isaac Z. Schlueter",
+    "email": "i@izs.me",
+    "url": "http://blog.izs.me/"
+  },
+  "bugs": {
+    "url": "https://github.com/isaacs/fs.realpath/issues"
+  },
+  "bundleDependencies": false,
+  "dependencies": {},
+  "deprecated": false,
+  "description": "Use node's fs.realpath, but fall back to the JS implementation if the native one fails",
+  "devDependencies": {},
+  "files": [
+    "old.js",
+    "index.js"
+  ],
+  "homepage": "https://github.com/isaacs/fs.realpath#readme",
+  "keywords": [
+    "realpath",
+    "fs",
+    "polyfill"
+  ],
+  "license": "ISC",
+  "main": "index.js",
+  "name": "fs.realpath",
+  "repository": {
+    "type": "git",
+    "url": "git+https://github.com/isaacs/fs.realpath.git"
+  },
+  "scripts": {
+    "test": "tap test/*.js --cov"
+  },
+  "version": "1.0.0"
+}
diff --git a/node_modules/glob/LICENSE b/node_modules/glob/LICENSE
new file mode 100644
index 0000000..19129e3
--- /dev/null
+++ b/node_modules/glob/LICENSE
@@ -0,0 +1,15 @@
+The ISC License
+
+Copyright (c) Isaac Z. Schlueter and Contributors
+
+Permission to use, copy, modify, and/or distribute this software for any
+purpose with or without fee is hereby granted, provided that the above
+copyright notice and this permission notice appear in all copies.
+
+THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
+IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
diff --git a/node_modules/glob/README.md b/node_modules/glob/README.md
new file mode 100644
index 0000000..baa1d1b
--- /dev/null
+++ b/node_modules/glob/README.md
@@ -0,0 +1,368 @@
+# Glob
+
+Match files using the patterns the shell uses, like stars and stuff.
+
+[![Build Status](https://travis-ci.org/isaacs/node-glob.svg?branch=master)](https://travis-ci.org/isaacs/node-glob/) [![Build Status](https://ci.appveyor.com/api/projects/status/kd7f3yftf7unxlsx?svg=true)](https://ci.appveyor.com/project/isaacs/node-glob) [![Coverage Status](https://coveralls.io/repos/isaacs/node-glob/badge.svg?branch=master&service=github)](https://coveralls.io/github/isaacs/node-glob?branch=master)
+
+This is a glob implementation in JavaScript.  It uses the `minimatch`
+library to do its matching.
+
+![](oh-my-glob.gif)
+
+## Usage
+
+Install with npm
+
+```
+npm i glob
+```
+
+```javascript
+var glob = require("glob")
+
+// options is optional
+glob("**/*.js", options, function (er, files) {
+  // files is an array of filenames.
+  // If the `nonull` option is set, and nothing
+  // was found, then files is ["**/*.js"]
+  // er is an error object or null.
+})
+```
+
+## Glob Primer
+
+"Globs" are the patterns you type when you do stuff like `ls *.js` on
+the command line, or put `build/*` in a `.gitignore` file.
+
+Before parsing the path part patterns, braced sections are expanded
+into a set.  Braced sections start with `{` and end with `}`, with any
+number of comma-delimited sections within.  Braced sections may contain
+slash characters, so `a{/b/c,bcd}` would expand into `a/b/c` and `abcd`.
+
+The following characters have special magic meaning when used in a
+path portion:
+
+* `*` Matches 0 or more characters in a single path portion
+* `?` Matches 1 character
+* `[...]` Matches a range of characters, similar to a RegExp range.
+  If the first character of the range is `!` or `^` then it matches
+  any character not in the range.
+* `!(pattern|pattern|pattern)` Matches anything that does not match
+  any of the patterns provided.
+* `?(pattern|pattern|pattern)` Matches zero or one occurrence of the
+  patterns provided.
+* `+(pattern|pattern|pattern)` Matches one or more occurrences of the
+  patterns provided.
+* `*(a|b|c)` Matches zero or more occurrences of the patterns provided
+* `@(pattern|pat*|pat?erN)` Matches exactly one of the patterns
+  provided
+* `**` If a "globstar" is alone in a path portion, then it matches
+  zero or more directories and subdirectories searching for matches.
+  It does not crawl symlinked directories.
+
+### Dots
+
+If a file or directory path portion has a `.` as the first character,
+then it will not match any glob pattern unless that pattern's
+corresponding path part also has a `.` as its first character.
+
+For example, the pattern `a/.*/c` would match the file at `a/.b/c`.
+However the pattern `a/*/c` would not, because `*` does not start with
+a dot character.
+
+You can make glob treat dots as normal characters by setting
+`dot:true` in the options.
+
+### Basename Matching
+
+If you set `matchBase:true` in the options, and the pattern has no
+slashes in it, then it will seek for any file anywhere in the tree
+with a matching basename.  For example, `*.js` would match
+`test/simple/basic.js`.
+
+### Empty Sets
+
+If no matching files are found, then an empty array is returned.  This
+differs from the shell, where the pattern itself is returned.  For
+example:
+
+    $ echo a*s*d*f
+    a*s*d*f
+
+To get the bash-style behavior, set the `nonull:true` in the options.
+
+### See Also:
+
+* `man sh`
+* `man bash` (Search for "Pattern Matching")
+* `man 3 fnmatch`
+* `man 5 gitignore`
+* [minimatch documentation](https://github.com/isaacs/minimatch)
+
+## glob.hasMagic(pattern, [options])
+
+Returns `true` if there are any special characters in the pattern, and
+`false` otherwise.
+
+Note that the options affect the results.  If `noext:true` is set in
+the options object, then `+(a|b)` will not be considered a magic
+pattern.  If the pattern has a brace expansion, like `a/{b/c,x/y}`
+then that is considered magical, unless `nobrace:true` is set in the
+options.
+
+## glob(pattern, [options], cb)
+
+* `pattern` `{String}` Pattern to be matched
+* `options` `{Object}`
+* `cb` `{Function}`
+  * `err` `{Error | null}`
+  * `matches` `{Array}` filenames found matching the pattern
+
+Perform an asynchronous glob search.
+
+## glob.sync(pattern, [options])
+
+* `pattern` `{String}` Pattern to be matched
+* `options` `{Object}`
+* return: `{Array}` filenames found matching the pattern
+
+Perform a synchronous glob search.
+
+## Class: glob.Glob
+
+Create a Glob object by instantiating the `glob.Glob` class.
+
+```javascript
+var Glob = require("glob").Glob
+var mg = new Glob(pattern, options, cb)
+```
+
+It's an EventEmitter, and starts walking the filesystem to find matches
+immediately.
+
+### new glob.Glob(pattern, [options], [cb])
+
+* `pattern` `{String}` pattern to search for
+* `options` `{Object}`
+* `cb` `{Function}` Called when an error occurs, or matches are found
+  * `err` `{Error | null}`
+  * `matches` `{Array}` filenames found matching the pattern
+
+Note that if the `sync` flag is set in the options, then matches will
+be immediately available on the `g.found` member.
+
+### Properties
+
+* `minimatch` The minimatch object that the glob uses.
+* `options` The options object passed in.
+* `aborted` Boolean which is set to true when calling `abort()`.  There
+  is no way at this time to continue a glob search after aborting, but
+  you can re-use the statCache to avoid having to duplicate syscalls.
+* `cache` Convenience object.  Each field has the following possible
+  values:
+  * `false` - Path does not exist
+  * `true` - Path exists
+  * `'FILE'` - Path exists, and is not a directory
+  * `'DIR'` - Path exists, and is a directory
+  * `[file, entries, ...]` - Path exists, is a directory, and the
+    array value is the results of `fs.readdir`
+* `statCache` Cache of `fs.stat` results, to prevent statting the same
+  path multiple times.
+* `symlinks` A record of which paths are symbolic links, which is
+  relevant in resolving `**` patterns.
+* `realpathCache` An optional object which is passed to `fs.realpath`
+  to minimize unnecessary syscalls.  It is stored on the instantiated
+  Glob object, and may be re-used.
+
+### Events
+
+* `end` When the matching is finished, this is emitted with all the
+  matches found.  If the `nonull` option is set, and no match was found,
+  then the `matches` list contains the original pattern.  The matches
+  are sorted, unless the `nosort` flag is set.
+* `match` Every time a match is found, this is emitted with the specific
+  thing that matched. It is not deduplicated or resolved to a realpath.
+* `error` Emitted when an unexpected error is encountered, or whenever
+  any fs error occurs if `options.strict` is set.
+* `abort` When `abort()` is called, this event is raised.
+
+### Methods
+
+* `pause` Temporarily stop the search
+* `resume` Resume the search
+* `abort` Stop the search forever
+
+### Options
+
+All the options that can be passed to Minimatch can also be passed to
+Glob to change pattern matching behavior.  Also, some have been added,
+or have glob-specific ramifications.
+
+All options are false by default, unless otherwise noted.
+
+All options are added to the Glob object, as well.
+
+If you are running many `glob` operations, you can pass a Glob object
+as the `options` argument to a subsequent operation to shortcut some
+`stat` and `readdir` calls.  At the very least, you may pass in shared
+`symlinks`, `statCache`, `realpathCache`, and `cache` options, so that
+parallel glob operations will be sped up by sharing information about
+the filesystem.
+
+* `cwd` The current working directory in which to search.  Defaults
+  to `process.cwd()`.
+* `root` The place where patterns starting with `/` will be mounted
+  onto.  Defaults to `path.resolve(options.cwd, "/")` (`/` on Unix
+  systems, and `C:\` or some such on Windows.)
+* `dot` Include `.dot` files in normal matches and `globstar` matches.
+  Note that an explicit dot in a portion of the pattern will always
+  match dot files.
+* `nomount` By default, a pattern starting with a forward-slash will be
+  "mounted" onto the root setting, so that a valid filesystem path is
+  returned.  Set this flag to disable that behavior.
+* `mark` Add a `/` character to directory matches.  Note that this
+  requires additional stat calls.
+* `nosort` Don't sort the results.
+* `stat` Set to true to stat *all* results.  This reduces performance
+  somewhat, and is completely unnecessary, unless `readdir` is presumed
+  to be an untrustworthy indicator of file existence.
+* `silent` When an unusual error is encountered when attempting to
+  read a directory, a warning will be printed to stderr.  Set the
+  `silent` option to true to suppress these warnings.
+* `strict` When an unusual error is encountered when attempting to
+  read a directory, the process will just continue on in search of
+  other matches.  Set the `strict` option to raise an error in these
+  cases.
+* `cache` See `cache` property above.  Pass in a previously generated
+  cache object to save some fs calls.
+* `statCache` A cache of results of filesystem information, to prevent
+  unnecessary stat calls.  While it should not normally be necessary
+  to set this, you may pass the statCache from one glob() call to the
+  options object of another, if you know that the filesystem will not
+  change between calls.  (See "Race Conditions" below.)
+* `symlinks` A cache of known symbolic links.  You may pass in a
+  previously generated `symlinks` object to save `lstat` calls when
+  resolving `**` matches.
+* `sync` DEPRECATED: use `glob.sync(pattern, opts)` instead.
+* `nounique` In some cases, brace-expanded patterns can result in the
+  same file showing up multiple times in the result set.  By default,
+  this implementation prevents duplicates in the result set.  Set this
+  flag to disable that behavior.
+* `nonull` Set to never return an empty set, instead returning a set
+  containing the pattern itself.  This is the default in glob(3).
+* `debug` Set to enable debug logging in minimatch and glob.
+* `nobrace` Do not expand `{a,b}` and `{1..3}` brace sets.
+* `noglobstar` Do not match `**` against multiple filenames.  (Ie,
+  treat it as a normal `*` instead.)
+* `noext` Do not match `+(a|b)` "extglob" patterns.
+* `nocase` Perform a case-insensitive match.  Note: on
+  case-insensitive filesystems, non-magic patterns will match by
+  default, since `stat` and `readdir` will not raise errors.
+* `matchBase` Perform a basename-only match if the pattern does not
+  contain any slash characters.  That is, `*.js` would be treated as
+  equivalent to `**/*.js`, matching all js files in all directories.
+* `nodir` Do not match directories, only files.  (Note: to match
+  *only* directories, simply put a `/` at the end of the pattern.)
+* `ignore` Add a pattern or an array of glob patterns to exclude matches.
+  Note: `ignore` patterns are *always* in `dot:true` mode, regardless
+  of any other settings.
+* `follow` Follow symlinked directories when expanding `**` patterns.
+  Note that this can result in a lot of duplicate references in the
+  presence of cyclic links.
+* `realpath` Set to true to call `fs.realpath` on all of the results.
+  In the case of a symlink that cannot be resolved, the full absolute
+  path to the matched entry is returned (though it will usually be a
+  broken symlink)
+* `absolute` Set to true to always receive absolute paths for matched
+  files.  Unlike `realpath`, this also affects the values returned in
+  the `match` event.
+
+## Comparisons to other fnmatch/glob implementations
+
+While strict compliance with the existing standards is a worthwhile
+goal, some discrepancies exist between node-glob and other
+implementations, and are intentional.
+
+The double-star character `**` is supported by default, unless the
+`noglobstar` flag is set.  This is supported in the manner of bsdglob
+and bash 4.3, where `**` only has special significance if it is the only
+thing in a path part.  That is, `a/**/b` will match `a/x/y/b`, but
+`a/**b` will not.
+
+Note that symlinked directories are not crawled as part of a `**`,
+though their contents may match against subsequent portions of the
+pattern.  This prevents infinite loops and duplicates and the like.
+
+If an escaped pattern has no matches, and the `nonull` flag is set,
+then glob returns the pattern as-provided, rather than
+interpreting the character escapes.  For example,
+`glob.match([], "\\*a\\?")` will return `"\\*a\\?"` rather than
+`"*a?"`.  This is akin to setting the `nullglob` option in bash, except
+that it does not resolve escaped pattern characters.
+
+If brace expansion is not disabled, then it is performed before any
+other interpretation of the glob pattern.  Thus, a pattern like
+`+(a|{b),c)}`, which would not be valid in bash or zsh, is expanded
+**first** into the set of `+(a|b)` and `+(a|c)`, and those patterns are
+checked for validity.  Since those two are valid, matching proceeds.
+
+### Comments and Negation
+
+Previously, this module let you mark a pattern as a "comment" if it
+started with a `#` character, or a "negated" pattern if it started
+with a `!` character.
+
+These options were deprecated in version 5, and removed in version 6.
+
+To specify things that should not match, use the `ignore` option.
+
+## Windows
+
+**Please only use forward-slashes in glob expressions.**
+
+Though windows uses either `/` or `\` as its path separator, only `/`
+characters are used by this glob implementation.  You must use
+forward-slashes **only** in glob expressions.  Back-slashes will always
+be interpreted as escape characters, not path separators.
+
+Results from absolute patterns such as `/foo/*` are mounted onto the
+root setting using `path.join`.  On windows, this will by default result
+in `/foo/*` matching `C:\foo\bar.txt`.
+
+## Race Conditions
+
+Glob searching, by its very nature, is susceptible to race conditions,
+since it relies on directory walking and such.
+
+As a result, it is possible that a file that exists when glob looks for
+it may have been deleted or modified by the time it returns the result.
+
+As part of its internal implementation, this program caches all stat
+and readdir calls that it makes, in order to cut down on system
+overhead.  However, this also makes it even more susceptible to races,
+especially if the cache or statCache objects are reused between glob
+calls.
+
+Users are thus advised not to use a glob result as a guarantee of
+filesystem state in the face of rapid changes.  For the vast majority
+of operations, this is never a problem.
+
+## Contributing
+
+Any change to behavior (including bugfixes) must come with a test.
+
+Patches that fail tests or reduce performance will be rejected.
+
+```
+# to run tests
+npm test
+
+# to re-generate test fixtures
+npm run test-regen
+
+# to benchmark against bash/zsh
+npm run bench
+
+# to profile javascript
+npm run prof
+```
diff --git a/node_modules/glob/changelog.md b/node_modules/glob/changelog.md
new file mode 100644
index 0000000..4163677
--- /dev/null
+++ b/node_modules/glob/changelog.md
@@ -0,0 +1,67 @@
+## 7.0
+
+- Raise error if `options.cwd` is specified, and not a directory
+
+## 6.0
+
+- Remove comment and negation pattern support
+- Ignore patterns are always in `dot:true` mode
+
+## 5.0
+
+- Deprecate comment and negation patterns
+- Fix regression in `mark` and `nodir` options from making all cache
+  keys absolute path.
+- Abort if `fs.readdir` returns an error that's unexpected
+- Don't emit `match` events for ignored items
+- Treat ENOTSUP like ENOTDIR in readdir
+
+## 4.5
+
+- Add `options.follow` to always follow directory symlinks in globstar
+- Add `options.realpath` to call `fs.realpath` on all results
+- Always cache based on absolute path
+
+## 4.4
+
+- Add `options.ignore`
+- Fix handling of broken symlinks
+
+## 4.3
+
+- Bump minimatch to 2.x
+- Pass all tests on Windows
+
+## 4.2
+
+- Add `glob.hasMagic` function
+- Add `options.nodir` flag
+
+## 4.1
+
+- Refactor sync and async implementations for performance
+- Throw if callback provided to sync glob function
+- Treat symbolic links in globstar results the same as Bash 4.3
+
+## 4.0
+
+- Use `^` for dependency versions (bumped major because this breaks
+  older npm versions)
+- Ensure callbacks are only ever called once
+- switch to ISC license
+
+## 3.x
+
+- Rewrite in JavaScript
+- Add support for setting root, cwd, and windows support
+- Cache many fs calls
+- Add globstar support
+- emit match events
+
+## 2.x
+
+- Use `glob.h` and `fnmatch.h` from NetBSD
+
+## 1.x
+
+- `glob.h` static binding.
diff --git a/node_modules/glob/common.js b/node_modules/glob/common.js
new file mode 100644
index 0000000..66651bb
--- /dev/null
+++ b/node_modules/glob/common.js
@@ -0,0 +1,240 @@
+exports.alphasort = alphasort
+exports.alphasorti = alphasorti
+exports.setopts = setopts
+exports.ownProp = ownProp
+exports.makeAbs = makeAbs
+exports.finish = finish
+exports.mark = mark
+exports.isIgnored = isIgnored
+exports.childrenIgnored = childrenIgnored
+
+function ownProp (obj, field) {
+  return Object.prototype.hasOwnProperty.call(obj, field)
+}
+
+var path = require("path")
+var minimatch = require("minimatch")
+var isAbsolute = require("path-is-absolute")
+var Minimatch = minimatch.Minimatch
+
+function alphasorti (a, b) {
+  return a.toLowerCase().localeCompare(b.toLowerCase())
+}
+
+function alphasort (a, b) {
+  return a.localeCompare(b)
+}
+
+function setupIgnores (self, options) {
+  self.ignore = options.ignore || []
+
+  if (!Array.isArray(self.ignore))
+    self.ignore = [self.ignore]
+
+  if (self.ignore.length) {
+    self.ignore = self.ignore.map(ignoreMap)
+  }
+}
+
+// ignore patterns are always in dot:true mode.
+function ignoreMap (pattern) {
+  var gmatcher = null
+  if (pattern.slice(-3) === '/**') {
+    var gpattern = pattern.replace(/(\/\*\*)+$/, '')
+    gmatcher = new Minimatch(gpattern, { dot: true })
+  }
+
+  return {
+    matcher: new Minimatch(pattern, { dot: true }),
+    gmatcher: gmatcher
+  }
+}
+
+function setopts (self, pattern, options) {
+  if (!options)
+    options = {}
+
+  // base-matching: just use globstar for that.
+  if (options.matchBase && -1 === pattern.indexOf("/")) {
+    if (options.noglobstar) {
+      throw new Error("base matching requires globstar")
+    }
+    pattern = "**/" + pattern
+  }
+
+  self.silent = !!options.silent
+  self.pattern = pattern
+  self.strict = options.strict !== false
+  self.realpath = !!options.realpath
+  self.realpathCache = options.realpathCache || Object.create(null)
+  self.follow = !!options.follow
+  self.dot = !!options.dot
+  self.mark = !!options.mark
+  self.nodir = !!options.nodir
+  if (self.nodir)
+    self.mark = true
+  self.sync = !!options.sync
+  self.nounique = !!options.nounique
+  self.nonull = !!options.nonull
+  self.nosort = !!options.nosort
+  self.nocase = !!options.nocase
+  self.stat = !!options.stat
+  self.noprocess = !!options.noprocess
+  self.absolute = !!options.absolute
+
+  self.maxLength = options.maxLength || Infinity
+  self.cache = options.cache || Object.create(null)
+  self.statCache = options.statCache || Object.create(null)
+  self.symlinks = options.symlinks || Object.create(null)
+
+  setupIgnores(self, options)
+
+  self.changedCwd = false
+  var cwd = process.cwd()
+  if (!ownProp(options, "cwd"))
+    self.cwd = cwd
+  else {
+    self.cwd = path.resolve(options.cwd)
+    self.changedCwd = self.cwd !== cwd
+  }
+
+  self.root = options.root || path.resolve(self.cwd, "/")
+  self.root = path.resolve(self.root)
+  if (process.platform === "win32")
+    self.root = self.root.replace(/\\/g, "/")
+
+  // TODO: is an absolute `cwd` supposed to be resolved against `root`?
+  // e.g. { cwd: '/test', root: __dirname } === path.join(__dirname, '/test')
+  self.cwdAbs = isAbsolute(self.cwd) ? self.cwd : makeAbs(self, self.cwd)
+  if (process.platform === "win32")
+    self.cwdAbs = self.cwdAbs.replace(/\\/g, "/")
+  self.nomount = !!options.nomount
+
+  // disable comments and negation in Minimatch.
+  // Note that they are not supported in Glob itself anyway.
+  options.nonegate = true
+  options.nocomment = true
+
+  self.minimatch = new Minimatch(pattern, options)
+  self.options = self.minimatch.options
+}
+
+function finish (self) {
+  var nou = self.nounique
+  var all = nou ? [] : Object.create(null)
+
+  for (var i = 0, l = self.matches.length; i < l; i ++) {
+    var matches = self.matches[i]
+    if (!matches || Object.keys(matches).length === 0) {
+      if (self.nonull) {
+        // do like the shell, and spit out the literal glob
+        var literal = self.minimatch.globSet[i]
+        if (nou)
+          all.push(literal)
+        else
+          all[literal] = true
+      }
+    } else {
+      // had matches
+      var m = Object.keys(matches)
+      if (nou)
+        all.push.apply(all, m)
+      else
+        m.forEach(function (m) {
+          all[m] = true
+        })
+    }
+  }
+
+  if (!nou)
+    all = Object.keys(all)
+
+  if (!self.nosort)
+    all = all.sort(self.nocase ? alphasorti : alphasort)
+
+  // at *some* point we statted all of these
+  if (self.mark) {
+    for (var i = 0; i < all.length; i++) {
+      all[i] = self._mark(all[i])
+    }
+    if (self.nodir) {
+      all = all.filter(function (e) {
+        var notDir = !(/\/$/.test(e))
+        var c = self.cache[e] || self.cache[makeAbs(self, e)]
+        if (notDir && c)
+          notDir = c !== 'DIR' && !Array.isArray(c)
+        return notDir
+      })
+    }
+  }
+
+  if (self.ignore.length)
+    all = all.filter(function(m) {
+      return !isIgnored(self, m)
+    })
+
+  self.found = all
+}
+
+function mark (self, p) {
+  var abs = makeAbs(self, p)
+  var c = self.cache[abs]
+  var m = p
+  if (c) {
+    var isDir = c === 'DIR' || Array.isArray(c)
+    var slash = p.slice(-1) === '/'
+
+    if (isDir && !slash)
+      m += '/'
+    else if (!isDir && slash)
+      m = m.slice(0, -1)
+
+    if (m !== p) {
+      var mabs = makeAbs(self, m)
+      self.statCache[mabs] = self.statCache[abs]
+      self.cache[mabs] = self.cache[abs]
+    }
+  }
+
+  return m
+}
+
+// lotta situps...
+function makeAbs (self, f) {
+  var abs = f
+  if (f.charAt(0) === '/') {
+    abs = path.join(self.root, f)
+  } else if (isAbsolute(f) || f === '') {
+    abs = f
+  } else if (self.changedCwd) {
+    abs = path.resolve(self.cwd, f)
+  } else {
+    abs = path.resolve(f)
+  }
+
+  if (process.platform === 'win32')
+    abs = abs.replace(/\\/g, '/')
+
+  return abs
+}
+
+
+// Return true, if pattern ends with globstar '**', for the accompanying parent directory.
+// Ex:- If node_modules/** is the pattern, add 'node_modules' to ignore list along with it's contents
+function isIgnored (self, path) {
+  if (!self.ignore.length)
+    return false
+
+  return self.ignore.some(function(item) {
+    return item.matcher.match(path) || !!(item.gmatcher && item.gmatcher.match(path))
+  })
+}
+
+function childrenIgnored (self, path) {
+  if (!self.ignore.length)
+    return false
+
+  return self.ignore.some(function(item) {
+    return !!(item.gmatcher && item.gmatcher.match(path))
+  })
+}
diff --git a/node_modules/glob/glob.js b/node_modules/glob/glob.js
new file mode 100644
index 0000000..58dec0f
--- /dev/null
+++ b/node_modules/glob/glob.js
@@ -0,0 +1,790 @@
+// Approach:
+//
+// 1. Get the minimatch set
+// 2. For each pattern in the set, PROCESS(pattern, false)
+// 3. Store matches per-set, then uniq them
+//
+// PROCESS(pattern, inGlobStar)
+// Get the first [n] items from pattern that are all strings
+// Join these together.  This is PREFIX.
+//   If there is no more remaining, then stat(PREFIX) and
+//   add to matches if it succeeds.  END.
+//
+// If inGlobStar and PREFIX is symlink and points to dir
+//   set ENTRIES = []
+// else readdir(PREFIX) as ENTRIES
+//   If fail, END
+//
+// with ENTRIES
+//   If pattern[n] is GLOBSTAR
+//     // handle the case where the globstar match is empty
+//     // by pruning it out, and testing the resulting pattern
+//     PROCESS(pattern[0..n] + pattern[n+1 .. $], false)
+//     // handle other cases.
+//     for ENTRY in ENTRIES (not dotfiles)
+//       // attach globstar + tail onto the entry
+//       // Mark that this entry is a globstar match
+//       PROCESS(pattern[0..n] + ENTRY + pattern[n .. $], true)
+//
+//   else // not globstar
+//     for ENTRY in ENTRIES (not dotfiles, unless pattern[n] is dot)
+//       Test ENTRY against pattern[n]
+//       If fails, continue
+//       If passes, PROCESS(pattern[0..n] + item + pattern[n+1 .. $])
+//
+// Caveat:
+//   Cache all stats and readdirs results to minimize syscall.  Since all
+//   we ever care about is existence and directory-ness, we can just keep
+//   `true` for files, and [children,...] for directories, or `false` for
+//   things that don't exist.
+
+module.exports = glob
+
+var fs = require('fs')
+var rp = require('fs.realpath')
+var minimatch = require('minimatch')
+var Minimatch = minimatch.Minimatch
+var inherits = require('inherits')
+var EE = require('events').EventEmitter
+var path = require('path')
+var assert = require('assert')
+var isAbsolute = require('path-is-absolute')
+var globSync = require('./sync.js')
+var common = require('./common.js')
+var alphasort = common.alphasort
+var alphasorti = common.alphasorti
+var setopts = common.setopts
+var ownProp = common.ownProp
+var inflight = require('inflight')
+var util = require('util')
+var childrenIgnored = common.childrenIgnored
+var isIgnored = common.isIgnored
+
+var once = require('once')
+
+function glob (pattern, options, cb) {
+  if (typeof options === 'function') cb = options, options = {}
+  if (!options) options = {}
+
+  if (options.sync) {
+    if (cb)
+      throw new TypeError('callback provided to sync glob')
+    return globSync(pattern, options)
+  }
+
+  return new Glob(pattern, options, cb)
+}
+
+glob.sync = globSync
+var GlobSync = glob.GlobSync = globSync.GlobSync
+
+// old api surface
+glob.glob = glob
+
+function extend (origin, add) {
+  if (add === null || typeof add !== 'object') {
+    return origin
+  }
+
+  var keys = Object.keys(add)
+  var i = keys.length
+  while (i--) {
+    origin[keys[i]] = add[keys[i]]
+  }
+  return origin
+}
+
+glob.hasMagic = function (pattern, options_) {
+  var options = extend({}, options_)
+  options.noprocess = true
+
+  var g = new Glob(pattern, options)
+  var set = g.minimatch.set
+
+  if (!pattern)
+    return false
+
+  if (set.length > 1)
+    return true
+
+  for (var j = 0; j < set[0].length; j++) {
+    if (typeof set[0][j] !== 'string')
+      return true
+  }
+
+  return false
+}
+
+glob.Glob = Glob
+inherits(Glob, EE)
+function Glob (pattern, options, cb) {
+  if (typeof options === 'function') {
+    cb = options
+    options = null
+  }
+
+  if (options && options.sync) {
+    if (cb)
+      throw new TypeError('callback provided to sync glob')
+    return new GlobSync(pattern, options)
+  }
+
+  if (!(this instanceof Glob))
+    return new Glob(pattern, options, cb)
+
+  setopts(this, pattern, options)
+  this._didRealPath = false
+
+  // process each pattern in the minimatch set
+  var n = this.minimatch.set.length
+
+  // The matches are stored as {: true,...} so that
+  // duplicates are automagically pruned.
+  // Later, we do an Object.keys() on these.
+  // Keep them as a list so we can fill in when nonull is set.
+  this.matches = new Array(n)
+
+  if (typeof cb === 'function') {
+    cb = once(cb)
+    this.on('error', cb)
+    this.on('end', function (matches) {
+      cb(null, matches)
+    })
+  }
+
+  var self = this
+  this._processing = 0
+
+  this._emitQueue = []
+  this._processQueue = []
+  this.paused = false
+
+  if (this.noprocess)
+    return this
+
+  if (n === 0)
+    return done()
+
+  var sync = true
+  for (var i = 0; i < n; i ++) {
+    this._process(this.minimatch.set[i], i, false, done)
+  }
+  sync = false
+
+  function done () {
+    --self._processing
+    if (self._processing <= 0) {
+      if (sync) {
+        process.nextTick(function () {
+          self._finish()
+        })
+      } else {
+        self._finish()
+      }
+    }
+  }
+}
+
+Glob.prototype._finish = function () {
+  assert(this instanceof Glob)
+  if (this.aborted)
+    return
+
+  if (this.realpath && !this._didRealpath)
+    return this._realpath()
+
+  common.finish(this)
+  this.emit('end', this.found)
+}
+
+Glob.prototype._realpath = function () {
+  if (this._didRealpath)
+    return
+
+  this._didRealpath = true
+
+  var n = this.matches.length
+  if (n === 0)
+    return this._finish()
+
+  var self = this
+  for (var i = 0; i < this.matches.length; i++)
+    this._realpathSet(i, next)
+
+  function next () {
+    if (--n === 0)
+      self._finish()
+  }
+}
+
+Glob.prototype._realpathSet = function (index, cb) {
+  var matchset = this.matches[index]
+  if (!matchset)
+    return cb()
+
+  var found = Object.keys(matchset)
+  var self = this
+  var n = found.length
+
+  if (n === 0)
+    return cb()
+
+  var set = this.matches[index] = Object.create(null)
+  found.forEach(function (p, i) {
+    // If there's a problem with the stat, then it means that
+    // one or more of the links in the realpath couldn't be
+    // resolved.  just return the abs value in that case.
+    p = self._makeAbs(p)
+    rp.realpath(p, self.realpathCache, function (er, real) {
+      if (!er)
+        set[real] = true
+      else if (er.syscall === 'stat')
+        set[p] = true
+      else
+        self.emit('error', er) // srsly wtf right here
+
+      if (--n === 0) {
+        self.matches[index] = set
+        cb()
+      }
+    })
+  })
+}
+
+Glob.prototype._mark = function (p) {
+  return common.mark(this, p)
+}
+
+Glob.prototype._makeAbs = function (f) {
+  return common.makeAbs(this, f)
+}
+
+Glob.prototype.abort = function () {
+  this.aborted = true
+  this.emit('abort')
+}
+
+Glob.prototype.pause = function () {
+  if (!this.paused) {
+    this.paused = true
+    this.emit('pause')
+  }
+}
+
+Glob.prototype.resume = function () {
+  if (this.paused) {
+    this.emit('resume')
+    this.paused = false
+    if (this._emitQueue.length) {
+      var eq = this._emitQueue.slice(0)
+      this._emitQueue.length = 0
+      for (var i = 0; i < eq.length; i ++) {
+        var e = eq[i]
+        this._emitMatch(e[0], e[1])
+      }
+    }
+    if (this._processQueue.length) {
+      var pq = this._processQueue.slice(0)
+      this._processQueue.length = 0
+      for (var i = 0; i < pq.length; i ++) {
+        var p = pq[i]
+        this._processing--
+        this._process(p[0], p[1], p[2], p[3])
+      }
+    }
+  }
+}
+
+Glob.prototype._process = function (pattern, index, inGlobStar, cb) {
+  assert(this instanceof Glob)
+  assert(typeof cb === 'function')
+
+  if (this.aborted)
+    return
+
+  this._processing++
+  if (this.paused) {
+    this._processQueue.push([pattern, index, inGlobStar, cb])
+    return
+  }
+
+  //console.error('PROCESS %d', this._processing, pattern)
+
+  // Get the first [n] parts of pattern that are all strings.
+  var n = 0
+  while (typeof pattern[n] === 'string') {
+    n ++
+  }
+  // now n is the index of the first one that is *not* a string.
+
+  // see if there's anything else
+  var prefix
+  switch (n) {
+    // if not, then this is rather simple
+    case pattern.length:
+      this._processSimple(pattern.join('/'), index, cb)
+      return
+
+    case 0:
+      // pattern *starts* with some non-trivial item.
+      // going to readdir(cwd), but not include the prefix in matches.
+      prefix = null
+      break
+
+    default:
+      // pattern has some string bits in the front.
+      // whatever it starts with, whether that's 'absolute' like /foo/bar,
+      // or 'relative' like '../baz'
+      prefix = pattern.slice(0, n).join('/')
+      break
+  }
+
+  var remain = pattern.slice(n)
+
+  // get the list of entries.
+  var read
+  if (prefix === null)
+    read = '.'
+  else if (isAbsolute(prefix) || isAbsolute(pattern.join('/'))) {
+    if (!prefix || !isAbsolute(prefix))
+      prefix = '/' + prefix
+    read = prefix
+  } else
+    read = prefix
+
+  var abs = this._makeAbs(read)
+
+  //if ignored, skip _processing
+  if (childrenIgnored(this, read))
+    return cb()
+
+  var isGlobStar = remain[0] === minimatch.GLOBSTAR
+  if (isGlobStar)
+    this._processGlobStar(prefix, read, abs, remain, index, inGlobStar, cb)
+  else
+    this._processReaddir(prefix, read, abs, remain, index, inGlobStar, cb)
+}
+
+Glob.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar, cb) {
+  var self = this
+  this._readdir(abs, inGlobStar, function (er, entries) {
+    return self._processReaddir2(prefix, read, abs, remain, index, inGlobStar, entries, cb)
+  })
+}
+
+Glob.prototype._processReaddir2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) {
+
+  // if the abs isn't a dir, then nothing can match!
+  if (!entries)
+    return cb()
+
+  // It will only match dot entries if it starts with a dot, or if
+  // dot is set.  Stuff like @(.foo|.bar) isn't allowed.
+  var pn = remain[0]
+  var negate = !!this.minimatch.negate
+  var rawGlob = pn._glob
+  var dotOk = this.dot || rawGlob.charAt(0) === '.'
+
+  var matchedEntries = []
+  for (var i = 0; i < entries.length; i++) {
+    var e = entries[i]
+    if (e.charAt(0) !== '.' || dotOk) {
+      var m
+      if (negate && !prefix) {
+        m = !e.match(pn)
+      } else {
+        m = e.match(pn)
+      }
+      if (m)
+        matchedEntries.push(e)
+    }
+  }
+
+  //console.error('prd2', prefix, entries, remain[0]._glob, matchedEntries)
+
+  var len = matchedEntries.length
+  // If there are no matched entries, then nothing matches.
+  if (len === 0)
+    return cb()
+
+  // if this is the last remaining pattern bit, then no need for
+  // an additional stat *unless* the user has specified mark or
+  // stat explicitly.  We know they exist, since readdir returned
+  // them.
+
+  if (remain.length === 1 && !this.mark && !this.stat) {
+    if (!this.matches[index])
+      this.matches[index] = Object.create(null)
+
+    for (var i = 0; i < len; i ++) {
+      var e = matchedEntries[i]
+      if (prefix) {
+        if (prefix !== '/')
+          e = prefix + '/' + e
+        else
+          e = prefix + e
+      }
+
+      if (e.charAt(0) === '/' && !this.nomount) {
+        e = path.join(this.root, e)
+      }
+      this._emitMatch(index, e)
+    }
+    // This was the last one, and no stats were needed
+    return cb()
+  }
+
+  // now test all matched entries as stand-ins for that part
+  // of the pattern.
+  remain.shift()
+  for (var i = 0; i < len; i ++) {
+    var e = matchedEntries[i]
+    var newPattern
+    if (prefix) {
+      if (prefix !== '/')
+        e = prefix + '/' + e
+      else
+        e = prefix + e
+    }
+    this._process([e].concat(remain), index, inGlobStar, cb)
+  }
+  cb()
+}
+
+Glob.prototype._emitMatch = function (index, e) {
+  if (this.aborted)
+    return
+
+  if (isIgnored(this, e))
+    return
+
+  if (this.paused) {
+    this._emitQueue.push([index, e])
+    return
+  }
+
+  var abs = isAbsolute(e) ? e : this._makeAbs(e)
+
+  if (this.mark)
+    e = this._mark(e)
+
+  if (this.absolute)
+    e = abs
+
+  if (this.matches[index][e])
+    return
+
+  if (this.nodir) {
+    var c = this.cache[abs]
+    if (c === 'DIR' || Array.isArray(c))
+      return
+  }
+
+  this.matches[index][e] = true
+
+  var st = this.statCache[abs]
+  if (st)
+    this.emit('stat', e, st)
+
+  this.emit('match', e)
+}
+
+Glob.prototype._readdirInGlobStar = function (abs, cb) {
+  if (this.aborted)
+    return
+
+  // follow all symlinked directories forever
+  // just proceed as if this is a non-globstar situation
+  if (this.follow)
+    return this._readdir(abs, false, cb)
+
+  var lstatkey = 'lstat\0' + abs
+  var self = this
+  var lstatcb = inflight(lstatkey, lstatcb_)
+
+  if (lstatcb)
+    fs.lstat(abs, lstatcb)
+
+  function lstatcb_ (er, lstat) {
+    if (er && er.code === 'ENOENT')
+      return cb()
+
+    var isSym = lstat && lstat.isSymbolicLink()
+    self.symlinks[abs] = isSym
+
+    // If it's not a symlink or a dir, then it's definitely a regular file.
+    // don't bother doing a readdir in that case.
+    if (!isSym && lstat && !lstat.isDirectory()) {
+      self.cache[abs] = 'FILE'
+      cb()
+    } else
+      self._readdir(abs, false, cb)
+  }
+}
+
+Glob.prototype._readdir = function (abs, inGlobStar, cb) {
+  if (this.aborted)
+    return
+
+  cb = inflight('readdir\0'+abs+'\0'+inGlobStar, cb)
+  if (!cb)
+    return
+
+  //console.error('RD %j %j', +inGlobStar, abs)
+  if (inGlobStar && !ownProp(this.symlinks, abs))
+    return this._readdirInGlobStar(abs, cb)
+
+  if (ownProp(this.cache, abs)) {
+    var c = this.cache[abs]
+    if (!c || c === 'FILE')
+      return cb()
+
+    if (Array.isArray(c))
+      return cb(null, c)
+  }
+
+  var self = this
+  fs.readdir(abs, readdirCb(this, abs, cb))
+}
+
+function readdirCb (self, abs, cb) {
+  return function (er, entries) {
+    if (er)
+      self._readdirError(abs, er, cb)
+    else
+      self._readdirEntries(abs, entries, cb)
+  }
+}
+
+Glob.prototype._readdirEntries = function (abs, entries, cb) {
+  if (this.aborted)
+    return
+
+  // if we haven't asked to stat everything, then just
+  // assume that everything in there exists, so we can avoid
+  // having to stat it a second time.
+  if (!this.mark && !this.stat) {
+    for (var i = 0; i < entries.length; i ++) {
+      var e = entries[i]
+      if (abs === '/')
+        e = abs + e
+      else
+        e = abs + '/' + e
+      this.cache[e] = true
+    }
+  }
+
+  this.cache[abs] = entries
+  return cb(null, entries)
+}
+
+Glob.prototype._readdirError = function (f, er, cb) {
+  if (this.aborted)
+    return
+
+  // handle errors, and cache the information
+  switch (er.code) {
+    case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205
+    case 'ENOTDIR': // totally normal. means it *does* exist.
+      var abs = this._makeAbs(f)
+      this.cache[abs] = 'FILE'
+      if (abs === this.cwdAbs) {
+        var error = new Error(er.code + ' invalid cwd ' + this.cwd)
+        error.path = this.cwd
+        error.code = er.code
+        this.emit('error', error)
+        this.abort()
+      }
+      break
+
+    case 'ENOENT': // not terribly unusual
+    case 'ELOOP':
+    case 'ENAMETOOLONG':
+    case 'UNKNOWN':
+      this.cache[this._makeAbs(f)] = false
+      break
+
+    default: // some unusual error.  Treat as failure.
+      this.cache[this._makeAbs(f)] = false
+      if (this.strict) {
+        this.emit('error', er)
+        // If the error is handled, then we abort
+        // if not, we threw out of here
+        this.abort()
+      }
+      if (!this.silent)
+        console.error('glob error', er)
+      break
+  }
+
+  return cb()
+}
+
+Glob.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar, cb) {
+  var self = this
+  this._readdir(abs, inGlobStar, function (er, entries) {
+    self._processGlobStar2(prefix, read, abs, remain, index, inGlobStar, entries, cb)
+  })
+}
+
+
+Glob.prototype._processGlobStar2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) {
+  //console.error('pgs2', prefix, remain[0], entries)
+
+  // no entries means not a dir, so it can never have matches
+  // foo.txt/** doesn't match foo.txt
+  if (!entries)
+    return cb()
+
+  // test without the globstar, and with every child both below
+  // and replacing the globstar.
+  var remainWithoutGlobStar = remain.slice(1)
+  var gspref = prefix ? [ prefix ] : []
+  var noGlobStar = gspref.concat(remainWithoutGlobStar)
+
+  // the noGlobStar pattern exits the inGlobStar state
+  this._process(noGlobStar, index, false, cb)
+
+  var isSym = this.symlinks[abs]
+  var len = entries.length
+
+  // If it's a symlink, and we're in a globstar, then stop
+  if (isSym && inGlobStar)
+    return cb()
+
+  for (var i = 0; i < len; i++) {
+    var e = entries[i]
+    if (e.charAt(0) === '.' && !this.dot)
+      continue
+
+    // these two cases enter the inGlobStar state
+    var instead = gspref.concat(entries[i], remainWithoutGlobStar)
+    this._process(instead, index, true, cb)
+
+    var below = gspref.concat(entries[i], remain)
+    this._process(below, index, true, cb)
+  }
+
+  cb()
+}
+
+Glob.prototype._processSimple = function (prefix, index, cb) {
+  // XXX review this.  Shouldn't it be doing the mounting etc
+  // before doing stat?  kinda weird?
+  var self = this
+  this._stat(prefix, function (er, exists) {
+    self._processSimple2(prefix, index, er, exists, cb)
+  })
+}
+Glob.prototype._processSimple2 = function (prefix, index, er, exists, cb) {
+
+  //console.error('ps2', prefix, exists)
+
+  if (!this.matches[index])
+    this.matches[index] = Object.create(null)
+
+  // If it doesn't exist, then just mark the lack of results
+  if (!exists)
+    return cb()
+
+  if (prefix && isAbsolute(prefix) && !this.nomount) {
+    var trail = /[\/\\]$/.test(prefix)
+    if (prefix.charAt(0) === '/') {
+      prefix = path.join(this.root, prefix)
+    } else {
+      prefix = path.resolve(this.root, prefix)
+      if (trail)
+        prefix += '/'
+    }
+  }
+
+  if (process.platform === 'win32')
+    prefix = prefix.replace(/\\/g, '/')
+
+  // Mark this as a match
+  this._emitMatch(index, prefix)
+  cb()
+}
+
+// Returns either 'DIR', 'FILE', or false
+Glob.prototype._stat = function (f, cb) {
+  var abs = this._makeAbs(f)
+  var needDir = f.slice(-1) === '/'
+
+  if (f.length > this.maxLength)
+    return cb()
+
+  if (!this.stat && ownProp(this.cache, abs)) {
+    var c = this.cache[abs]
+
+    if (Array.isArray(c))
+      c = 'DIR'
+
+    // It exists, but maybe not how we need it
+    if (!needDir || c === 'DIR')
+      return cb(null, c)
+
+    if (needDir && c === 'FILE')
+      return cb()
+
+    // otherwise we have to stat, because maybe c=true
+    // if we know it exists, but not what it is.
+  }
+
+  var exists
+  var stat = this.statCache[abs]
+  if (stat !== undefined) {
+    if (stat === false)
+      return cb(null, stat)
+    else {
+      var type = stat.isDirectory() ? 'DIR' : 'FILE'
+      if (needDir && type === 'FILE')
+        return cb()
+      else
+        return cb(null, type, stat)
+    }
+  }
+
+  var self = this
+  var statcb = inflight('stat\0' + abs, lstatcb_)
+  if (statcb)
+    fs.lstat(abs, statcb)
+
+  function lstatcb_ (er, lstat) {
+    if (lstat && lstat.isSymbolicLink()) {
+      // If it's a symlink, then treat it as the target, unless
+      // the target does not exist, then treat it as a file.
+      return fs.stat(abs, function (er, stat) {
+        if (er)
+          self._stat2(f, abs, null, lstat, cb)
+        else
+          self._stat2(f, abs, er, stat, cb)
+      })
+    } else {
+      self._stat2(f, abs, er, lstat, cb)
+    }
+  }
+}
+
+Glob.prototype._stat2 = function (f, abs, er, stat, cb) {
+  if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) {
+    this.statCache[abs] = false
+    return cb()
+  }
+
+  var needDir = f.slice(-1) === '/'
+  this.statCache[abs] = stat
+
+  if (abs.slice(-1) === '/' && stat && !stat.isDirectory())
+    return cb(null, false, stat)
+
+  var c = true
+  if (stat)
+    c = stat.isDirectory() ? 'DIR' : 'FILE'
+  this.cache[abs] = this.cache[abs] || c
+
+  if (needDir && c === 'FILE')
+    return cb()
+
+  return cb(null, c, stat)
+}
diff --git a/node_modules/glob/package.json b/node_modules/glob/package.json
new file mode 100644
index 0000000..105127e
--- /dev/null
+++ b/node_modules/glob/package.json
@@ -0,0 +1,76 @@
+{
+  "_from": "glob@7.1.2",
+  "_id": "glob@7.1.2",
+  "_inBundle": false,
+  "_integrity": "sha512-MJTUg1kjuLeQCJ+ccE4Vpa6kKVXkPYJ2mOCQyUuKLcLQsdrMCpBPUi8qVE6+YuaJkozeA9NusTAw3hLr8Xe5EQ==",
+  "_location": "/glob",
+  "_phantomChildren": {},
+  "_requested": {
+    "type": "version",
+    "registry": true,
+    "raw": "glob@7.1.2",
+    "name": "glob",
+    "escapedName": "glob",
+    "rawSpec": "7.1.2",
+    "saveSpec": null,
+    "fetchSpec": "7.1.2"
+  },
+  "_requiredBy": [
+    "/mocha"
+  ],
+  "_resolved": "https://registry.npmjs.org/glob/-/glob-7.1.2.tgz",
+  "_shasum": "c19c9df9a028702d678612384a6552404c636d15",
+  "_spec": "glob@7.1.2",
+  "_where": "/Users/jessitron/code/jessitron/stringify-tree/node_modules/mocha",
+  "author": {
+    "name": "Isaac Z. Schlueter",
+    "email": "i@izs.me",
+    "url": "http://blog.izs.me/"
+  },
+  "bugs": {
+    "url": "https://github.com/isaacs/node-glob/issues"
+  },
+  "bundleDependencies": false,
+  "dependencies": {
+    "fs.realpath": "^1.0.0",
+    "inflight": "^1.0.4",
+    "inherits": "2",
+    "minimatch": "^3.0.4",
+    "once": "^1.3.0",
+    "path-is-absolute": "^1.0.0"
+  },
+  "deprecated": false,
+  "description": "a little globber",
+  "devDependencies": {
+    "mkdirp": "0",
+    "rimraf": "^2.2.8",
+    "tap": "^7.1.2",
+    "tick": "0.0.6"
+  },
+  "engines": {
+    "node": "*"
+  },
+  "files": [
+    "glob.js",
+    "sync.js",
+    "common.js"
+  ],
+  "homepage": "https://github.com/isaacs/node-glob#readme",
+  "license": "ISC",
+  "main": "glob.js",
+  "name": "glob",
+  "repository": {
+    "type": "git",
+    "url": "git://github.com/isaacs/node-glob.git"
+  },
+  "scripts": {
+    "bench": "bash benchmark.sh",
+    "benchclean": "node benchclean.js",
+    "prepublish": "npm run benchclean",
+    "prof": "bash prof.sh && cat profile.txt",
+    "profclean": "rm -f v8.log profile.txt",
+    "test": "tap test/*.js --cov",
+    "test-regen": "npm run profclean && TEST_REGEN=1 node test/00-setup.js"
+  },
+  "version": "7.1.2"
+}
diff --git a/node_modules/glob/sync.js b/node_modules/glob/sync.js
new file mode 100644
index 0000000..c952134
--- /dev/null
+++ b/node_modules/glob/sync.js
@@ -0,0 +1,486 @@
+module.exports = globSync
+globSync.GlobSync = GlobSync
+
+var fs = require('fs')
+var rp = require('fs.realpath')
+var minimatch = require('minimatch')
+var Minimatch = minimatch.Minimatch
+var Glob = require('./glob.js').Glob
+var util = require('util')
+var path = require('path')
+var assert = require('assert')
+var isAbsolute = require('path-is-absolute')
+var common = require('./common.js')
+var alphasort = common.alphasort
+var alphasorti = common.alphasorti
+var setopts = common.setopts
+var ownProp = common.ownProp
+var childrenIgnored = common.childrenIgnored
+var isIgnored = common.isIgnored
+
+function globSync (pattern, options) {
+  if (typeof options === 'function' || arguments.length === 3)
+    throw new TypeError('callback provided to sync glob\n'+
+                        'See: https://github.com/isaacs/node-glob/issues/167')
+
+  return new GlobSync(pattern, options).found
+}
+
+function GlobSync (pattern, options) {
+  if (!pattern)
+    throw new Error('must provide pattern')
+
+  if (typeof options === 'function' || arguments.length === 3)
+    throw new TypeError('callback provided to sync glob\n'+
+                        'See: https://github.com/isaacs/node-glob/issues/167')
+
+  if (!(this instanceof GlobSync))
+    return new GlobSync(pattern, options)
+
+  setopts(this, pattern, options)
+
+  if (this.noprocess)
+    return this
+
+  var n = this.minimatch.set.length
+  this.matches = new Array(n)
+  for (var i = 0; i < n; i ++) {
+    this._process(this.minimatch.set[i], i, false)
+  }
+  this._finish()
+}
+
+GlobSync.prototype._finish = function () {
+  assert(this instanceof GlobSync)
+  if (this.realpath) {
+    var self = this
+    this.matches.forEach(function (matchset, index) {
+      var set = self.matches[index] = Object.create(null)
+      for (var p in matchset) {
+        try {
+          p = self._makeAbs(p)
+          var real = rp.realpathSync(p, self.realpathCache)
+          set[real] = true
+        } catch (er) {
+          if (er.syscall === 'stat')
+            set[self._makeAbs(p)] = true
+          else
+            throw er
+        }
+      }
+    })
+  }
+  common.finish(this)
+}
+
+
+GlobSync.prototype._process = function (pattern, index, inGlobStar) {
+  assert(this instanceof GlobSync)
+
+  // Get the first [n] parts of pattern that are all strings.
+  var n = 0
+  while (typeof pattern[n] === 'string') {
+    n ++
+  }
+  // now n is the index of the first one that is *not* a string.
+
+  // See if there's anything else
+  var prefix
+  switch (n) {
+    // if not, then this is rather simple
+    case pattern.length:
+      this._processSimple(pattern.join('/'), index)
+      return
+
+    case 0:
+      // pattern *starts* with some non-trivial item.
+      // going to readdir(cwd), but not include the prefix in matches.
+      prefix = null
+      break
+
+    default:
+      // pattern has some string bits in the front.
+      // whatever it starts with, whether that's 'absolute' like /foo/bar,
+      // or 'relative' like '../baz'
+      prefix = pattern.slice(0, n).join('/')
+      break
+  }
+
+  var remain = pattern.slice(n)
+
+  // get the list of entries.
+  var read
+  if (prefix === null)
+    read = '.'
+  else if (isAbsolute(prefix) || isAbsolute(pattern.join('/'))) {
+    if (!prefix || !isAbsolute(prefix))
+      prefix = '/' + prefix
+    read = prefix
+  } else
+    read = prefix
+
+  var abs = this._makeAbs(read)
+
+  //if ignored, skip processing
+  if (childrenIgnored(this, read))
+    return
+
+  var isGlobStar = remain[0] === minimatch.GLOBSTAR
+  if (isGlobStar)
+    this._processGlobStar(prefix, read, abs, remain, index, inGlobStar)
+  else
+    this._processReaddir(prefix, read, abs, remain, index, inGlobStar)
+}
+
+
+GlobSync.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar) {
+  var entries = this._readdir(abs, inGlobStar)
+
+  // if the abs isn't a dir, then nothing can match!
+  if (!entries)
+    return
+
+  // It will only match dot entries if it starts with a dot, or if
+  // dot is set.  Stuff like @(.foo|.bar) isn't allowed.
+  var pn = remain[0]
+  var negate = !!this.minimatch.negate
+  var rawGlob = pn._glob
+  var dotOk = this.dot || rawGlob.charAt(0) === '.'
+
+  var matchedEntries = []
+  for (var i = 0; i < entries.length; i++) {
+    var e = entries[i]
+    if (e.charAt(0) !== '.' || dotOk) {
+      var m
+      if (negate && !prefix) {
+        m = !e.match(pn)
+      } else {
+        m = e.match(pn)
+      }
+      if (m)
+        matchedEntries.push(e)
+    }
+  }
+
+  var len = matchedEntries.length
+  // If there are no matched entries, then nothing matches.
+  if (len === 0)
+    return
+
+  // if this is the last remaining pattern bit, then no need for
+  // an additional stat *unless* the user has specified mark or
+  // stat explicitly.  We know they exist, since readdir returned
+  // them.
+
+  if (remain.length === 1 && !this.mark && !this.stat) {
+    if (!this.matches[index])
+      this.matches[index] = Object.create(null)
+
+    for (var i = 0; i < len; i ++) {
+      var e = matchedEntries[i]
+      if (prefix) {
+        if (prefix.slice(-1) !== '/')
+          e = prefix + '/' + e
+        else
+          e = prefix + e
+      }
+
+      if (e.charAt(0) === '/' && !this.nomount) {
+        e = path.join(this.root, e)
+      }
+      this._emitMatch(index, e)
+    }
+    // This was the last one, and no stats were needed
+    return
+  }
+
+  // now test all matched entries as stand-ins for that part
+  // of the pattern.
+  remain.shift()
+  for (var i = 0; i < len; i ++) {
+    var e = matchedEntries[i]
+    var newPattern
+    if (prefix)
+      newPattern = [prefix, e]
+    else
+      newPattern = [e]
+    this._process(newPattern.concat(remain), index, inGlobStar)
+  }
+}
+
+
+GlobSync.prototype._emitMatch = function (index, e) {
+  if (isIgnored(this, e))
+    return
+
+  var abs = this._makeAbs(e)
+
+  if (this.mark)
+    e = this._mark(e)
+
+  if (this.absolute) {
+    e = abs
+  }
+
+  if (this.matches[index][e])
+    return
+
+  if (this.nodir) {
+    var c = this.cache[abs]
+    if (c === 'DIR' || Array.isArray(c))
+      return
+  }
+
+  this.matches[index][e] = true
+
+  if (this.stat)
+    this._stat(e)
+}
+
+
+GlobSync.prototype._readdirInGlobStar = function (abs) {
+  // follow all symlinked directories forever
+  // just proceed as if this is a non-globstar situation
+  if (this.follow)
+    return this._readdir(abs, false)
+
+  var entries
+  var lstat
+  var stat
+  try {
+    lstat = fs.lstatSync(abs)
+  } catch (er) {
+    if (er.code === 'ENOENT') {
+      // lstat failed, doesn't exist
+      return null
+    }
+  }
+
+  var isSym = lstat && lstat.isSymbolicLink()
+  this.symlinks[abs] = isSym
+
+  // If it's not a symlink or a dir, then it's definitely a regular file.
+  // don't bother doing a readdir in that case.
+  if (!isSym && lstat && !lstat.isDirectory())
+    this.cache[abs] = 'FILE'
+  else
+    entries = this._readdir(abs, false)
+
+  return entries
+}
+
+GlobSync.prototype._readdir = function (abs, inGlobStar) {
+  var entries
+
+  if (inGlobStar && !ownProp(this.symlinks, abs))
+    return this._readdirInGlobStar(abs)
+
+  if (ownProp(this.cache, abs)) {
+    var c = this.cache[abs]
+    if (!c || c === 'FILE')
+      return null
+
+    if (Array.isArray(c))
+      return c
+  }
+
+  try {
+    return this._readdirEntries(abs, fs.readdirSync(abs))
+  } catch (er) {
+    this._readdirError(abs, er)
+    return null
+  }
+}
+
+GlobSync.prototype._readdirEntries = function (abs, entries) {
+  // if we haven't asked to stat everything, then just
+  // assume that everything in there exists, so we can avoid
+  // having to stat it a second time.
+  if (!this.mark && !this.stat) {
+    for (var i = 0; i < entries.length; i ++) {
+      var e = entries[i]
+      if (abs === '/')
+        e = abs + e
+      else
+        e = abs + '/' + e
+      this.cache[e] = true
+    }
+  }
+
+  this.cache[abs] = entries
+
+  // mark and cache dir-ness
+  return entries
+}
+
+GlobSync.prototype._readdirError = function (f, er) {
+  // handle errors, and cache the information
+  switch (er.code) {
+    case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205
+    case 'ENOTDIR': // totally normal. means it *does* exist.
+      var abs = this._makeAbs(f)
+      this.cache[abs] = 'FILE'
+      if (abs === this.cwdAbs) {
+        var error = new Error(er.code + ' invalid cwd ' + this.cwd)
+        error.path = this.cwd
+        error.code = er.code
+        throw error
+      }
+      break
+
+    case 'ENOENT': // not terribly unusual
+    case 'ELOOP':
+    case 'ENAMETOOLONG':
+    case 'UNKNOWN':
+      this.cache[this._makeAbs(f)] = false
+      break
+
+    default: // some unusual error.  Treat as failure.
+      this.cache[this._makeAbs(f)] = false
+      if (this.strict)
+        throw er
+      if (!this.silent)
+        console.error('glob error', er)
+      break
+  }
+}
+
+GlobSync.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar) {
+
+  var entries = this._readdir(abs, inGlobStar)
+
+  // no entries means not a dir, so it can never have matches
+  // foo.txt/** doesn't match foo.txt
+  if (!entries)
+    return
+
+  // test without the globstar, and with every child both below
+  // and replacing the globstar.
+  var remainWithoutGlobStar = remain.slice(1)
+  var gspref = prefix ? [ prefix ] : []
+  var noGlobStar = gspref.concat(remainWithoutGlobStar)
+
+  // the noGlobStar pattern exits the inGlobStar state
+  this._process(noGlobStar, index, false)
+
+  var len = entries.length
+  var isSym = this.symlinks[abs]
+
+  // If it's a symlink, and we're in a globstar, then stop
+  if (isSym && inGlobStar)
+    return
+
+  for (var i = 0; i < len; i++) {
+    var e = entries[i]
+    if (e.charAt(0) === '.' && !this.dot)
+      continue
+
+    // these two cases enter the inGlobStar state
+    var instead = gspref.concat(entries[i], remainWithoutGlobStar)
+    this._process(instead, index, true)
+
+    var below = gspref.concat(entries[i], remain)
+    this._process(below, index, true)
+  }
+}
+
+GlobSync.prototype._processSimple = function (prefix, index) {
+  // XXX review this.  Shouldn't it be doing the mounting etc
+  // before doing stat?  kinda weird?
+  var exists = this._stat(prefix)
+
+  if (!this.matches[index])
+    this.matches[index] = Object.create(null)
+
+  // If it doesn't exist, then just mark the lack of results
+  if (!exists)
+    return
+
+  if (prefix && isAbsolute(prefix) && !this.nomount) {
+    var trail = /[\/\\]$/.test(prefix)
+    if (prefix.charAt(0) === '/') {
+      prefix = path.join(this.root, prefix)
+    } else {
+      prefix = path.resolve(this.root, prefix)
+      if (trail)
+        prefix += '/'
+    }
+  }
+
+  if (process.platform === 'win32')
+    prefix = prefix.replace(/\\/g, '/')
+
+  // Mark this as a match
+  this._emitMatch(index, prefix)
+}
+
+// Returns either 'DIR', 'FILE', or false
+GlobSync.prototype._stat = function (f) {
+  var abs = this._makeAbs(f)
+  var needDir = f.slice(-1) === '/'
+
+  if (f.length > this.maxLength)
+    return false
+
+  if (!this.stat && ownProp(this.cache, abs)) {
+    var c = this.cache[abs]
+
+    if (Array.isArray(c))
+      c = 'DIR'
+
+    // It exists, but maybe not how we need it
+    if (!needDir || c === 'DIR')
+      return c
+
+    if (needDir && c === 'FILE')
+      return false
+
+    // otherwise we have to stat, because maybe c=true
+    // if we know it exists, but not what it is.
+  }
+
+  var exists
+  var stat = this.statCache[abs]
+  if (!stat) {
+    var lstat
+    try {
+      lstat = fs.lstatSync(abs)
+    } catch (er) {
+      if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) {
+        this.statCache[abs] = false
+        return false
+      }
+    }
+
+    if (lstat && lstat.isSymbolicLink()) {
+      try {
+        stat = fs.statSync(abs)
+      } catch (er) {
+        stat = lstat
+      }
+    } else {
+      stat = lstat
+    }
+  }
+
+  this.statCache[abs] = stat
+
+  var c = true
+  if (stat)
+    c = stat.isDirectory() ? 'DIR' : 'FILE'
+
+  this.cache[abs] = this.cache[abs] || c
+
+  if (needDir && c === 'FILE')
+    return false
+
+  return c
+}
+
+GlobSync.prototype._mark = function (p) {
+  return common.mark(this, p)
+}
+
+GlobSync.prototype._makeAbs = function (f) {
+  return common.makeAbs(this, f)
+}
diff --git a/node_modules/growl/.eslintrc.json b/node_modules/growl/.eslintrc.json
new file mode 100644
index 0000000..f067e89
--- /dev/null
+++ b/node_modules/growl/.eslintrc.json
@@ -0,0 +1,14 @@
+{
+    "extends": ["airbnb-base", "eslint:recommended", "plugin:node/recommended"],
+    "plugins": [
+        "import",
+        "node"
+    ],
+    "rules": {
+      "no-console": ["error", { "allow": ["warn", "error"] }]
+    },
+    "env": {
+        "node": true,
+        "es6": true
+    }
+}
diff --git a/node_modules/growl/.tags b/node_modules/growl/.tags
new file mode 100644
index 0000000..ce68994
--- /dev/null
+++ b/node_modules/growl/.tags
@@ -0,0 +1,195 @@
+name	/Users/timosand/Dropbox/Documents/Projects/node-growl/package.json	/^  "name": "growl",$/;"	function	line:2
+version	/Users/timosand/Dropbox/Documents/Projects/node-growl/package.json	/^  "version": "1.10.1",$/;"	function	line:3
+description	/Users/timosand/Dropbox/Documents/Projects/node-growl/package.json	/^  "description": "Growl unobtrusive notifications",$/;"	function	line:4
+author	/Users/timosand/Dropbox/Documents/Projects/node-growl/package.json	/^  "author": "TJ Holowaychuk ",$/;"	function	line:5
+maintainers	/Users/timosand/Dropbox/Documents/Projects/node-growl/package.json	/^  "maintainers": [$/;"	function	line:6
+repository	/Users/timosand/Dropbox/Documents/Projects/node-growl/package.json	/^  "repository": {$/;"	function	line:10
+type	/Users/timosand/Dropbox/Documents/Projects/node-growl/package.json	/^    "type": "git",$/;"	function	line:11
+url	/Users/timosand/Dropbox/Documents/Projects/node-growl/package.json	/^    "url": "git:\/\/github.com\/tj\/node-growl.git"$/;"	function	line:12
+main	/Users/timosand/Dropbox/Documents/Projects/node-growl/package.json	/^  "main": ".\/lib\/growl.js",$/;"	function	line:14
+license	/Users/timosand/Dropbox/Documents/Projects/node-growl/package.json	/^  "license": "MIT",$/;"	function	line:15
+devDependencies	/Users/timosand/Dropbox/Documents/Projects/node-growl/package.json	/^  "devDependencies": {$/;"	function	line:16
+eslint	/Users/timosand/Dropbox/Documents/Projects/node-growl/package.json	/^    "eslint": "^4.2.0",$/;"	function	line:17
+eslint-config-airbnb-base	/Users/timosand/Dropbox/Documents/Projects/node-growl/package.json	/^    "eslint-config-airbnb-base": "^11.2.0",$/;"	function	line:18
+eslint-plugin-import	/Users/timosand/Dropbox/Documents/Projects/node-growl/package.json	/^    "eslint-plugin-import": "^2.7.0"$/;"	function	line:19
+scripts	/Users/timosand/Dropbox/Documents/Projects/node-growl/package.json	/^  "scripts": {$/;"	function	line:21
+test	/Users/timosand/Dropbox/Documents/Projects/node-growl/package.json	/^    "test": "node test.js",$/;"	function	line:22
+lint	/Users/timosand/Dropbox/Documents/Projects/node-growl/package.json	/^    "lint": "eslint --ext js lib "$/;"	function	line:23
+engines	/Users/timosand/Dropbox/Documents/Projects/node-growl/package.json	/^  "engines": {$/;"	function	line:25
+node	/Users/timosand/Dropbox/Documents/Projects/node-growl/package.json	/^    "node": ">=4.x"$/;"	function	line:26
+extends	/Users/timosand/Dropbox/Documents/Projects/node-growl/.eslintrc.json	/^    "extends": ["airbnb-base", "eslint:recommended", "plugin:node\/recommended"],$/;"	function	line:2
+plugins	/Users/timosand/Dropbox/Documents/Projects/node-growl/.eslintrc.json	/^    "plugins": [$/;"	function	line:3
+rules	/Users/timosand/Dropbox/Documents/Projects/node-growl/.eslintrc.json	/^    "rules": {$/;"	function	line:7
+no-console	/Users/timosand/Dropbox/Documents/Projects/node-growl/.eslintrc.json	/^      "no-console": ["error", { "allow": ["warn", "error"] }]$/;"	function	line:8
+env	/Users/timosand/Dropbox/Documents/Projects/node-growl/.eslintrc.json	/^    "env": {$/;"	function	line:10
+node	/Users/timosand/Dropbox/Documents/Projects/node-growl/.eslintrc.json	/^        "node": true,$/;"	function	line:11
+es6	/Users/timosand/Dropbox/Documents/Projects/node-growl/.eslintrc.json	/^        "es6": true$/;"	function	line:12
+language	/Users/timosand/Dropbox/Documents/Projects/node-growl/.travis.yml	/^language: node_js$/;"	function	line:1
+dist	/Users/timosand/Dropbox/Documents/Projects/node-growl/.travis.yml	/^dist: trusty$/;"	function	line:2
+os	/Users/timosand/Dropbox/Documents/Projects/node-growl/.travis.yml	/^os:$/;"	function	line:3
+node_js	/Users/timosand/Dropbox/Documents/Projects/node-growl/.travis.yml	/^node_js:$/;"	function	line:6
+before_install	/Users/timosand/Dropbox/Documents/Projects/node-growl/.travis.yml	/^before_install:$/;"	function	line:12
+jobs	/Users/timosand/Dropbox/Documents/Projects/node-growl/.travis.yml	/^jobs:$/;"	function	line:14
+include	/Users/timosand/Dropbox/Documents/Projects/node-growl/.travis.yml	/^  include:$/;"	function	line:15
+script	/Users/timosand/Dropbox/Documents/Projects/node-growl/.travis.yml	/^      script: npm run lint$/;"	function	line:17
+script	/Users/timosand/Dropbox/Documents/Projects/node-growl/.travis.yml	/^      script: npm test$/;"	function	line:19
+cmd	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^let cmd;$/;"	variable	line:15
+which	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^function which(name) {$/;"	function	line:17
+loc	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^  let loc;$/;"	variable	line:19
+len	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^  for (let i = 0, len = paths.length; i < len; i += 1) {$/;"	variable	line:21
+loc	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^    loc = path.join(paths[i], name);$/;"	variable	line:22
+setupCmd	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^function setupCmd() {$/;"	function	line:28
+cmd	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^        cmd = {$/;"	object	line:32
+cmd	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^        cmd = {$/;"	variable	line:32
+type	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^          type: 'Darwin-NotificationCenter',$/;"	string	line:33
+type	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^          type: 'Darwin-NotificationCenter',$/;"	variable	line:33
+pkg	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^          pkg: 'terminal-notifier',$/;"	string	line:34
+pkg	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^          pkg: 'terminal-notifier',$/;"	variable	line:34
+msg	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^          msg: '-message',$/;"	string	line:35
+msg	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^          msg: '-message',$/;"	variable	line:35
+title	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^          title: '-title',$/;"	string	line:36
+title	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^          title: '-title',$/;"	variable	line:36
+subtitle	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^          subtitle: '-subtitle',$/;"	string	line:37
+subtitle	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^          subtitle: '-subtitle',$/;"	variable	line:37
+icon	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^          icon: '-appIcon',$/;"	string	line:38
+icon	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^          icon: '-appIcon',$/;"	variable	line:38
+sound	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^          sound: '-sound',$/;"	string	line:39
+sound	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^          sound: '-sound',$/;"	variable	line:39
+url	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^          url: '-open',$/;"	string	line:40
+url	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^          url: '-open',$/;"	variable	line:40
+priority	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^          priority: {$/;"	object	line:41
+priority	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^          priority: {$/;"	variable	line:41
+cmd	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^            cmd: '-execute',$/;"	string	line:42
+cmd	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^            cmd: '-execute',$/;"	variable	line:42
+range	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^            range: [],$/;"	array	line:43
+range	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^            range: [],$/;"	variable	line:43
+cmd	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^        cmd = {$/;"	object	line:47
+cmd	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^        cmd = {$/;"	variable	line:47
+type	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^          type: 'Darwin-Growl',$/;"	string	line:48
+type	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^          type: 'Darwin-Growl',$/;"	variable	line:48
+pkg	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^          pkg: 'growlnotify',$/;"	string	line:49
+pkg	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^          pkg: 'growlnotify',$/;"	variable	line:49
+msg	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^          msg: '-m',$/;"	string	line:50
+msg	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^          msg: '-m',$/;"	variable	line:50
+sticky	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^          sticky: '--sticky',$/;"	string	line:51
+sticky	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^          sticky: '--sticky',$/;"	variable	line:51
+url	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^          url: '--url',$/;"	string	line:52
+url	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^          url: '--url',$/;"	variable	line:52
+priority	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^          priority: {$/;"	object	line:53
+priority	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^          priority: {$/;"	variable	line:53
+cmd	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^            cmd: '--priority',$/;"	string	line:54
+cmd	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^            cmd: '--priority',$/;"	variable	line:54
+range	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^            range: [$/;"	array	line:55
+range	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^            range: [$/;"	variable	line:55
+0	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^              0,$/;"	variable	line:58
+1	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^              1,$/;"	variable	line:59
+2	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^              2,$/;"	variable	line:60
+break	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^      break;$/;"	variable	line:70
+cmd	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^        cmd = {$/;"	object	line:73
+cmd	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^        cmd = {$/;"	variable	line:73
+type	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^          type: 'Linux-Growl',$/;"	string	line:74
+type	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^          type: 'Linux-Growl',$/;"	variable	line:74
+pkg	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^          pkg: 'growl',$/;"	string	line:75
+pkg	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^          pkg: 'growl',$/;"	variable	line:75
+msg	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^          msg: '-m',$/;"	string	line:76
+msg	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^          msg: '-m',$/;"	variable	line:76
+title	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^          title: '-title',$/;"	string	line:77
+title	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^          title: '-title',$/;"	variable	line:77
+subtitle	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^          subtitle: '-subtitle',$/;"	string	line:78
+subtitle	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^          subtitle: '-subtitle',$/;"	variable	line:78
+host	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^          host: {$/;"	object	line:79
+host	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^          host: {$/;"	variable	line:79
+cmd	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^            cmd: '-H',$/;"	string	line:80
+cmd	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^            cmd: '-H',$/;"	variable	line:80
+hostname	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^            hostname: '192.168.33.1',$/;"	string	line:81
+hostname	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^            hostname: '192.168.33.1',$/;"	variable	line:81
+cmd	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^        cmd = {$/;"	object	line:85
+cmd	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^        cmd = {$/;"	variable	line:85
+type	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^          type: 'Linux',$/;"	string	line:86
+type	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^          type: 'Linux',$/;"	variable	line:86
+pkg	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^          pkg: 'notify-send',$/;"	string	line:87
+pkg	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^          pkg: 'notify-send',$/;"	variable	line:87
+msg	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^          msg: '',$/;"	string	line:88
+msg	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^          msg: '',$/;"	variable	line:88
+sticky	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^          sticky: '-t 0',$/;"	string	line:89
+sticky	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^          sticky: '-t 0',$/;"	variable	line:89
+icon	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^          icon: '-i',$/;"	string	line:90
+icon	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^          icon: '-i',$/;"	variable	line:90
+priority	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^          priority: {$/;"	object	line:91
+priority	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^          priority: {$/;"	variable	line:91
+cmd	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^            cmd: '-u',$/;"	string	line:92
+cmd	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^            cmd: '-u',$/;"	variable	line:92
+range	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^            range: [$/;"	array	line:93
+range	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^            range: [$/;"	variable	line:93
+break	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^      break;$/;"	variable	line:101
+cmd	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^      cmd = {$/;"	object	line:103
+cmd	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^      cmd = {$/;"	variable	line:103
+type	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^        type: 'Windows',$/;"	string	line:104
+type	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^        type: 'Windows',$/;"	variable	line:104
+pkg	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^        pkg: 'growlnotify',$/;"	string	line:105
+pkg	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^        pkg: 'growlnotify',$/;"	variable	line:105
+msg	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^        msg: '',$/;"	string	line:106
+msg	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^        msg: '',$/;"	variable	line:106
+sticky	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^        sticky: '\/s:true',$/;"	string	line:107
+sticky	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^        sticky: '\/s:true',$/;"	variable	line:107
+title	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^        title: '\/t:',$/;"	string	line:108
+title	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^        title: '\/t:',$/;"	variable	line:108
+icon	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^        icon: '\/i:',$/;"	string	line:109
+icon	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^        icon: '\/i:',$/;"	variable	line:109
+url	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^        url: '\/cu:',$/;"	string	line:110
+url	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^        url: '\/cu:',$/;"	variable	line:110
+priority	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^        priority: {$/;"	object	line:111
+priority	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^        priority: {$/;"	variable	line:111
+cmd	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^          cmd: '\/p:',$/;"	string	line:112
+cmd	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^          cmd: '\/p:',$/;"	variable	line:112
+range	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^          range: [$/;"	array	line:113
+range	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^          range: [$/;"	variable	line:113
+0	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^            0,$/;"	variable	line:116
+1	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^            1,$/;"	variable	line:117
+2	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^            2,$/;"	variable	line:118
+break	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^      break;$/;"	variable	line:122
+break	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^      break;$/;"	variable	line:124
+sound	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^ *   growl('5 new emails', { title: 'Thunderbird', sound: 'Purr' })$/;"	string	line:151
+sound	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^ *   growl('5 new emails', { title: 'Thunderbird', sound: 'Purr' })$/;"	variable	line:151
+opts	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^function growl(msg, opts, callback) {$/;"	variable	line:162
+growl	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^function growl(msg, opts, callback) {$/;"	function	line:162
+image	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^  let image;$/;"	variable	line:163
+noop	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^  const fn = callback || function noop() {};$/;"	function	line:165
+cmd	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^    cmd = {$/;"	object	line:170
+cmd	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^    cmd = {$/;"	variable	line:170
+type	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^      type: 'Custom',$/;"	string	line:171
+type	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^      type: 'Custom',$/;"	variable	line:171
+pkg	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^      pkg: options.exec,$/;"	variable	line:172
+range	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^      range: [],$/;"	array	line:173
+range	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^      range: [],$/;"	variable	line:173
+return	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^    return;$/;"	variable	line:180
+image	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^    image = options.image;$/;"	variable	line:186
+flag	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^        let flag;$/;"	variable	line:189
+flag	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^        flag = ext === 'icns' && 'iconpath';$/;"	variable	line:191
+flag	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^        flag = flag || (\/^[A-Z]\/.test(image) && 'appIcon');$/;"	variable	line:192
+flag	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^        flag = flag || (\/^png|gif|jpe?g$\/.test(ext) && 'image');$/;"	variable	line:193
+flag	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^        flag = flag || (ext && (image = ext) && 'icon');$/;"	variable	line:194
+flag	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^        flag = flag || 'icon';$/;"	variable	line:195
+break	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^        break;$/;"	variable	line:197
+break	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^        break;$/;"	variable	line:201
+break	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^        break;$/;"	variable	line:206
+break	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^        break;$/;"	variable	line:209
+break	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^        break;$/;"	variable	line:211
+break	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^      break;$/;"	variable	line:246
+break	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^      break;$/;"	variable	line:264
+break	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^      break;$/;"	variable	line:273
+break	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^      break;$/;"	variable	line:282
+break	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^      break;$/;"	variable	line:287
+command	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^      let command = customCmd.replace(\/(^|[^%])%s\/g, `$1${message}`);$/;"	variable	line:293
+command	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^        command = splitCmd.shift();$/;"	variable	line:296
+break	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^      break;$/;"	variable	line:303
+break	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^      break;$/;"	variable	line:306
+stdout	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^  let stdout = '';$/;"	string	line:311
+stdout	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^  let stdout = '';$/;"	variable	line:311
+stderr	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^  let stderr = '';$/;"	string	line:312
+stderr	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^  let stderr = '';$/;"	variable	line:312
+error	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^  let error;$/;"	variable	line:313
+error	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^    error = err;$/;"	variable	line:317
+error	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^    error = error || code === 0 ? null : code;$/;"	variable	line:329
+stdout	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^      fn(error, stdout, stderr);$/;"	variable	line:331
+exports	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^module.exports = growl;$/;"	variable	line:341
diff --git a/node_modules/growl/.tags1 b/node_modules/growl/.tags1
new file mode 100644
index 0000000..b68beb3
--- /dev/null
+++ b/node_modules/growl/.tags1
@@ -0,0 +1,166 @@
+!_TAG_FILE_FORMAT	2	/extended format; --format=1 will not append ;" to lines/
+!_TAG_FILE_SORTED	0	/0=unsorted, 1=sorted, 2=foldcase/
+!_TAG_PROGRAM_AUTHOR	Darren Hiebert	/dhiebert@users.sourceforge.net/
+!_TAG_PROGRAM_NAME	Exuberant Ctags	//
+!_TAG_PROGRAM_URL	http://ctags.sourceforge.net	/official site/
+!_TAG_PROGRAM_VERSION	5.8	//
+cmd	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^let cmd;$/;"	variable	line:15
+which	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^function which(name) {$/;"	function	line:17
+loc	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^  let loc;$/;"	variable	line:19
+len	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^  for (let i = 0, len = paths.length; i < len; i += 1) {$/;"	variable	line:21
+loc	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^    loc = path.join(paths[i], name);$/;"	variable	line:22
+setupCmd	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^function setupCmd() {$/;"	function	line:28
+cmd	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^        cmd = {$/;"	object	line:32
+cmd	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^        cmd = {$/;"	variable	line:32
+type	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^          type: 'Darwin-NotificationCenter',$/;"	string	line:33
+type	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^          type: 'Darwin-NotificationCenter',$/;"	variable	line:33
+pkg	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^          pkg: 'terminal-notifier',$/;"	string	line:34
+pkg	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^          pkg: 'terminal-notifier',$/;"	variable	line:34
+msg	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^          msg: '-message',$/;"	string	line:35
+msg	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^          msg: '-message',$/;"	variable	line:35
+title	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^          title: '-title',$/;"	string	line:36
+title	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^          title: '-title',$/;"	variable	line:36
+subtitle	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^          subtitle: '-subtitle',$/;"	string	line:37
+subtitle	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^          subtitle: '-subtitle',$/;"	variable	line:37
+icon	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^          icon: '-appIcon',$/;"	string	line:38
+icon	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^          icon: '-appIcon',$/;"	variable	line:38
+sound	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^          sound: '-sound',$/;"	string	line:39
+sound	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^          sound: '-sound',$/;"	variable	line:39
+url	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^          url: '-open',$/;"	string	line:40
+url	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^          url: '-open',$/;"	variable	line:40
+priority	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^          priority: {$/;"	object	line:41
+priority	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^          priority: {$/;"	variable	line:41
+cmd	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^            cmd: '-execute',$/;"	string	line:42
+cmd	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^            cmd: '-execute',$/;"	variable	line:42
+range	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^            range: [],$/;"	array	line:43
+range	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^            range: [],$/;"	variable	line:43
+cmd	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^        cmd = {$/;"	object	line:47
+cmd	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^        cmd = {$/;"	variable	line:47
+type	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^          type: 'Darwin-Growl',$/;"	string	line:48
+type	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^          type: 'Darwin-Growl',$/;"	variable	line:48
+pkg	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^          pkg: 'growlnotify',$/;"	string	line:49
+pkg	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^          pkg: 'growlnotify',$/;"	variable	line:49
+msg	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^          msg: '-m',$/;"	string	line:50
+msg	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^          msg: '-m',$/;"	variable	line:50
+sticky	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^          sticky: '--sticky',$/;"	string	line:51
+sticky	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^          sticky: '--sticky',$/;"	variable	line:51
+url	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^          url: '--url',$/;"	string	line:52
+url	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^          url: '--url',$/;"	variable	line:52
+priority	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^          priority: {$/;"	object	line:53
+priority	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^          priority: {$/;"	variable	line:53
+cmd	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^            cmd: '--priority',$/;"	string	line:54
+cmd	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^            cmd: '--priority',$/;"	variable	line:54
+range	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^            range: [$/;"	array	line:55
+range	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^            range: [$/;"	variable	line:55
+0	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^              0,$/;"	variable	line:58
+1	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^              1,$/;"	variable	line:59
+2	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^              2,$/;"	variable	line:60
+break	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^      break;$/;"	variable	line:70
+cmd	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^        cmd = {$/;"	object	line:73
+cmd	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^        cmd = {$/;"	variable	line:73
+type	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^          type: 'Linux-Growl',$/;"	string	line:74
+type	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^          type: 'Linux-Growl',$/;"	variable	line:74
+pkg	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^          pkg: 'growl',$/;"	string	line:75
+pkg	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^          pkg: 'growl',$/;"	variable	line:75
+msg	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^          msg: '-m',$/;"	string	line:76
+msg	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^          msg: '-m',$/;"	variable	line:76
+title	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^          title: '-title',$/;"	string	line:77
+title	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^          title: '-title',$/;"	variable	line:77
+subtitle	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^          subtitle: '-subtitle',$/;"	string	line:78
+subtitle	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^          subtitle: '-subtitle',$/;"	variable	line:78
+host	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^          host: {$/;"	object	line:79
+host	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^          host: {$/;"	variable	line:79
+cmd	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^            cmd: '-H',$/;"	string	line:80
+cmd	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^            cmd: '-H',$/;"	variable	line:80
+hostname	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^            hostname: '192.168.33.1',$/;"	string	line:81
+hostname	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^            hostname: '192.168.33.1',$/;"	variable	line:81
+cmd	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^        cmd = {$/;"	object	line:85
+cmd	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^        cmd = {$/;"	variable	line:85
+type	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^          type: 'Linux',$/;"	string	line:86
+type	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^          type: 'Linux',$/;"	variable	line:86
+pkg	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^          pkg: 'notify-send',$/;"	string	line:87
+pkg	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^          pkg: 'notify-send',$/;"	variable	line:87
+msg	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^          msg: '',$/;"	string	line:88
+msg	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^          msg: '',$/;"	variable	line:88
+sticky	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^          sticky: '-t 0',$/;"	string	line:89
+sticky	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^          sticky: '-t 0',$/;"	variable	line:89
+icon	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^          icon: '-i',$/;"	string	line:90
+icon	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^          icon: '-i',$/;"	variable	line:90
+priority	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^          priority: {$/;"	object	line:91
+priority	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^          priority: {$/;"	variable	line:91
+cmd	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^            cmd: '-u',$/;"	string	line:92
+cmd	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^            cmd: '-u',$/;"	variable	line:92
+range	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^            range: [$/;"	array	line:93
+range	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^            range: [$/;"	variable	line:93
+break	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^      break;$/;"	variable	line:101
+cmd	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^      cmd = {$/;"	object	line:103
+cmd	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^      cmd = {$/;"	variable	line:103
+type	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^        type: 'Windows',$/;"	string	line:104
+type	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^        type: 'Windows',$/;"	variable	line:104
+pkg	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^        pkg: 'growlnotify',$/;"	string	line:105
+pkg	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^        pkg: 'growlnotify',$/;"	variable	line:105
+msg	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^        msg: '',$/;"	string	line:106
+msg	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^        msg: '',$/;"	variable	line:106
+sticky	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^        sticky: '\/s:true',$/;"	string	line:107
+sticky	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^        sticky: '\/s:true',$/;"	variable	line:107
+title	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^        title: '\/t:',$/;"	string	line:108
+title	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^        title: '\/t:',$/;"	variable	line:108
+icon	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^        icon: '\/i:',$/;"	string	line:109
+icon	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^        icon: '\/i:',$/;"	variable	line:109
+url	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^        url: '\/cu:',$/;"	string	line:110
+url	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^        url: '\/cu:',$/;"	variable	line:110
+priority	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^        priority: {$/;"	object	line:111
+priority	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^        priority: {$/;"	variable	line:111
+cmd	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^          cmd: '\/p:',$/;"	string	line:112
+cmd	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^          cmd: '\/p:',$/;"	variable	line:112
+range	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^          range: [$/;"	array	line:113
+range	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^          range: [$/;"	variable	line:113
+0	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^            0,$/;"	variable	line:116
+1	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^            1,$/;"	variable	line:117
+2	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^            2,$/;"	variable	line:118
+break	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^      break;$/;"	variable	line:122
+break	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^      break;$/;"	variable	line:124
+sound	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^ *   growl('5 new emails', { title: 'Thunderbird', sound: 'Purr' })$/;"	string	line:151
+sound	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^ *   growl('5 new emails', { title: 'Thunderbird', sound: 'Purr' })$/;"	variable	line:151
+opts	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^function growl(msg, opts, callback) {$/;"	variable	line:162
+growl	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^function growl(msg, opts, callback) {$/;"	function	line:162
+image	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^  let image;$/;"	variable	line:163
+noop	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^  const fn = callback || function noop() {};$/;"	function	line:165
+cmd	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^    cmd = {$/;"	object	line:170
+cmd	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^    cmd = {$/;"	variable	line:170
+type	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^      type: 'Custom',$/;"	string	line:171
+type	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^      type: 'Custom',$/;"	variable	line:171
+pkg	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^      pkg: options.exec,$/;"	variable	line:172
+range	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^      range: [],$/;"	array	line:173
+range	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^      range: [],$/;"	variable	line:173
+return	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^    return;$/;"	variable	line:180
+image	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^    image = options.image;$/;"	variable	line:186
+flag	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^        let flag;$/;"	variable	line:189
+flag	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^        flag = ext === 'icns' && 'iconpath';$/;"	variable	line:191
+flag	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^        flag = flag || (\/^[A-Z]\/.test(image) && 'appIcon');$/;"	variable	line:192
+flag	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^        flag = flag || (\/^png|gif|jpe?g$\/.test(ext) && 'image');$/;"	variable	line:193
+flag	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^        flag = flag || (ext && (image = ext) && 'icon');$/;"	variable	line:194
+flag	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^        flag = flag || 'icon';$/;"	variable	line:195
+break	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^        break;$/;"	variable	line:197
+break	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^        break;$/;"	variable	line:201
+break	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^        break;$/;"	variable	line:206
+break	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^        break;$/;"	variable	line:209
+break	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^        break;$/;"	variable	line:211
+break	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^      break;$/;"	variable	line:246
+break	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^      break;$/;"	variable	line:264
+break	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^      break;$/;"	variable	line:273
+break	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^      break;$/;"	variable	line:282
+break	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^      break;$/;"	variable	line:287
+command	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^      let command = customCmd.replace(\/(^|[^%])%s\/g, `$1${message}`);$/;"	variable	line:293
+command	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^        command = splitCmd.shift();$/;"	variable	line:296
+break	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^      break;$/;"	variable	line:303
+break	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^      break;$/;"	variable	line:306
+stdout	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^  let stdout = '';$/;"	string	line:311
+stdout	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^  let stdout = '';$/;"	variable	line:311
+stderr	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^  let stderr = '';$/;"	string	line:312
+stderr	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^  let stderr = '';$/;"	variable	line:312
+error	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^  let error;$/;"	variable	line:313
+error	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^    error = err;$/;"	variable	line:317
+error	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^    error = error || code === 0 ? null : code;$/;"	variable	line:329
+stdout	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^      fn(error, stdout, stderr);$/;"	variable	line:331
+exports	/Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js	/^module.exports = growl;$/;"	variable	line:341
diff --git a/node_modules/growl/.travis.yml b/node_modules/growl/.travis.yml
new file mode 100644
index 0000000..072adfc
--- /dev/null
+++ b/node_modules/growl/.travis.yml
@@ -0,0 +1,21 @@
+language: node_js
+dist: trusty
+os:
+  - linux
+  - osx
+node_js:
+- '4'
+- '5'
+- '6'
+- '7'
+- 'node'
+before_install:
+  - npm i -g npm@latest
+  - if [[ "$TRAVIS_OS_NAME" == "linux" ]]; then sudo apt-get -qq update; fi
+  - if [[ "$TRAVIS_OS_NAME" == "linux" ]]; then sudo apt-get install -y libnotify-bin; fi
+jobs:
+  include:
+    - stage: lint
+      script: npm run lint
+    - stage: test
+      script: npm test
diff --git a/node_modules/growl/History.md b/node_modules/growl/History.md
new file mode 100644
index 0000000..dfbc2e4
--- /dev/null
+++ b/node_modules/growl/History.md
@@ -0,0 +1,77 @@
+1.10.5 / 2018-04-04
+==================
+
+* Fix callbacks not receiving errors (#72) [chadrickman]
+
+1.10.4 / 2018-01-29
+==================
+
+* Fix notifications on linux when using notify-send (#70) [hmshwt]
+
+1.9.3 / 2016-09-05
+==================
+
+  * fixed command injection vulnerability
+
+1.7.0 / 2012-12-30 
+==================
+
+  * support transient notifications in Gnome
+
+1.6.1 / 2012-09-25 
+==================
+
+  * restore compatibility with node < 0.8 [fgnass]
+
+1.6.0 / 2012-09-06 
+==================
+
+  * add notification center support [drudge]
+
+1.5.1 / 2012-04-08 
+==================
+
+  * Merge pull request #16 from KyleAMathews/patch-1
+  * Fixes #15
+
+1.5.0 / 2012-02-08 
+==================
+
+  * Added windows support [perfusorius]
+
+1.4.1 / 2011-12-28 
+==================
+
+  * Fixed: dont exit(). Closes #9
+
+1.4.0 / 2011-12-17 
+==================
+
+  * Changed API: `growl.notify()` -> `growl()`
+
+1.3.0 / 2011-12-17 
+==================
+
+  * Added support for Ubuntu/Debian/Linux users [niftylettuce]
+  * Fixed: send notifications even if title not specified [alessioalex]
+
+1.2.0 / 2011-10-06 
+==================
+
+  * Add support for priority.
+
+1.1.0 / 2011-03-15 
+==================
+
+  * Added optional callbacks
+  * Added parsing of version
+
+1.0.1 / 2010-03-26
+==================
+
+  * Fixed; sys.exec -> child_process.exec to support latest node
+
+1.0.0 / 2010-03-19
+==================
+  
+  * Initial release
diff --git a/node_modules/growl/Readme.md b/node_modules/growl/Readme.md
new file mode 100644
index 0000000..54128b4
--- /dev/null
+++ b/node_modules/growl/Readme.md
@@ -0,0 +1,109 @@
+# Growl for nodejs
+[![Build Status](https://travis-ci.org/tj/node-growl.svg?branch=master)](https://travis-ci.org/tj/node-growl)
+
+Growl support for Nodejs. This is essentially a port of my [Ruby Growl Library](http://github.com/visionmedia/growl). Ubuntu/Linux support added thanks to [@niftylettuce](http://github.com/niftylettuce).
+
+## Installation
+
+### Install
+
+### Mac OS X (Darwin):
+
+  Install [growlnotify(1)](http://growl.info/extras.php#growlnotify). On OS X 10.8, Notification Center is supported using [terminal-notifier](https://github.com/alloy/terminal-notifier). To install:
+
+    $ sudo gem install terminal-notifier
+
+  Install [npm](http://npmjs.org/) and run:
+
+    $ npm install growl
+
+### Ubuntu (Linux):
+
+  Install `notify-send` through the [libnotify-bin](http://packages.ubuntu.com/libnotify-bin) package:
+
+    $ sudo apt-get install libnotify-bin
+
+  Install [npm](http://npmjs.org/) and run:
+
+    $ npm install growl
+
+### Windows:
+
+  Download and install [Growl for Windows](http://www.growlforwindows.com/gfw/default.aspx)
+
+  Download [growlnotify](http://www.growlforwindows.com/gfw/help/growlnotify.aspx) - **IMPORTANT :** Unpack growlnotify to a folder that is present in your path!
+
+  Install [npm](http://npmjs.org/) and run:
+
+    $ npm install growl
+
+## Examples
+
+Callback functions are optional
+
+```javascript
+var growl = require('growl')
+growl('You have mail!')
+growl('5 new messages', { sticky: true })
+growl('5 new emails', { title: 'Email Client', image: 'Safari', sticky: true })
+growl('Message with title', { title: 'Title'})
+growl('Set priority', { priority: 2 })
+growl('Show Safari icon', { image: 'Safari' })
+growl('Show icon', { image: 'path/to/icon.icns' })
+growl('Show image', { image: 'path/to/my.image.png' })
+growl('Show png filesystem icon', { image: 'png' })
+growl('Show pdf filesystem icon', { image: 'article.pdf' })
+growl('Show pdf filesystem icon', { image: 'article.pdf' }, function(err){
+  // ... notified
+})
+```
+
+## Options
+
+  - title
+    - notification title
+  - name
+    - application name
+  - priority
+    - priority for the notification (default is 0)
+  - sticky
+    - weither or not the notification should remainin until closed
+  - image
+    - Auto-detects the context:
+      - path to an icon sets --iconpath
+      - path to an image sets --image
+      - capitalized word sets --appIcon
+      - filename uses extname as --icon
+      - otherwise treated as --icon
+  - exec
+    - manually specify a shell command instead
+      - appends message to end of shell command
+      - or, replaces `%s` with message
+      - optionally prepends title (example: `title: message`)
+      - examples: `{exec: 'tmux display-message'}`, `{exec: 'echo "%s" > messages.log}`
+
+## License
+
+(The MIT License)
+
+Copyright (c) 2009 TJ Holowaychuk 
+Copyright (c) 2016 Joshua Boy Nicolai Appelman 
+
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of this software and associated documentation files (the
+'Software'), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, sublicense, and/or sell copies of the Software, and to
+permit persons to whom the Software is furnished to do so, subject to
+the following conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/node_modules/growl/lib/growl.js b/node_modules/growl/lib/growl.js
new file mode 100644
index 0000000..eb4efa8
--- /dev/null
+++ b/node_modules/growl/lib/growl.js
@@ -0,0 +1,340 @@
+'use strict';
+
+// Growl - Copyright TJ Holowaychuk  (MIT Licensed)
+
+/**
+ * Module dependencies.
+ */
+
+const spawn = require('child_process').spawn;
+const fs = require('fs');
+const path = require('path');
+const os = require('os');
+
+const exists = fs.existsSync || path.existsSync;
+let cmd;
+
+function which(name) {
+  const paths = process.env.PATH.split(':');
+  let loc;
+
+  for (let i = 0, len = paths.length; i < len; i += 1) {
+    loc = path.join(paths[i], name);
+    if (exists(loc)) return loc;
+  }
+  return false;
+}
+
+function setupCmd() {
+  switch (os.type()) {
+    case 'Darwin':
+      if (which('terminal-notifier')) {
+        cmd = {
+          type: 'Darwin-NotificationCenter',
+          pkg: 'terminal-notifier',
+          msg: '-message',
+          title: '-title',
+          subtitle: '-subtitle',
+          icon: '-appIcon',
+          sound: '-sound',
+          url: '-open',
+          priority: {
+            cmd: '-execute',
+            range: [],
+          },
+        };
+      } else {
+        cmd = {
+          type: 'Darwin-Growl',
+          pkg: 'growlnotify',
+          msg: '-m',
+          sticky: '--sticky',
+          url: '--url',
+          priority: {
+            cmd: '--priority',
+            range: [
+              -2,
+              -1,
+              0,
+              1,
+              2,
+              'Very Low',
+              'Moderate',
+              'Normal',
+              'High',
+              'Emergency',
+            ],
+          },
+        };
+      }
+      break;
+    case 'Linux':
+      if (which('growl')) {
+        cmd = {
+          type: 'Linux-Growl',
+          pkg: 'growl',
+          msg: '-m',
+          title: '-title',
+          subtitle: '-subtitle',
+          host: {
+            cmd: '-H',
+            hostname: '192.168.33.1',
+          },
+        };
+      } else {
+        cmd = {
+          type: 'Linux',
+          pkg: 'notify-send',
+          msg: '',
+          sticky: '-t',
+          icon: '-i',
+          priority: {
+            cmd: '-u',
+            range: [
+              'low',
+              'normal',
+              'critical',
+            ],
+          },
+        };
+      }
+      break;
+    case 'Windows_NT':
+      cmd = {
+        type: 'Windows',
+        pkg: 'growlnotify',
+        msg: '',
+        sticky: '/s:true',
+        title: '/t:',
+        icon: '/i:',
+        url: '/cu:',
+        priority: {
+          cmd: '/p:',
+          range: [
+            -2,
+            -1,
+            0,
+            1,
+            2,
+          ],
+        },
+      };
+      break;
+    default:
+      break;
+  }
+}
+
+
+/**
+ * Send growl notification _msg_ with _options_.
+ *
+ * Options:
+ *
+ *  - title   Notification title
+ *  - sticky  Make the notification stick (defaults to false)
+ *  - priority  Specify an int or named key (default is 0)
+ *  - name    Application name (defaults to growlnotify)
+ *  - sound   Sound efect ( in OSx defined in preferences -> sound -> effects)
+ *            works only in OSX > 10.8x
+ *  - image
+ *    - path to an icon sets --iconpath
+ *    - path to an image sets --image
+ *    - capitalized word sets --appIcon
+ *    - filename uses extname as --icon
+ *    - otherwise treated as --icon
+ *
+ * Examples:
+ *
+ *   growl('New email')
+ *   growl('5 new emails', { title: 'Thunderbird' })
+ *   growl('5 new emails', { title: 'Thunderbird', sound: 'Purr' })
+ *   growl('Email sent', function(){
+ *     // ... notification sent
+ *   })
+ *
+ * @param {string} msg
+ * @param {object} opts
+ * @param {function} callback
+ * @api public
+ */
+
+function growl(msg, opts, callback) {
+  let image;
+  const options = opts || {};
+  const fn = callback || function noop() {};
+
+  setupCmd();
+
+  if (options.exec) {
+    cmd = {
+      type: 'Custom',
+      pkg: options.exec,
+      range: [],
+    };
+  }
+
+  // noop
+  if (!cmd) {
+    fn(new Error('growl not supported on this platform'));
+    return;
+  }
+  const args = [cmd.pkg];
+
+  // image
+  if (image || options.image) {
+    image = options.image;
+    switch (cmd.type) {
+      case 'Darwin-Growl': {
+        let flag;
+        const ext = path.extname(image).substr(1);
+        flag = ext === 'icns' && 'iconpath';
+        flag = flag || (/^[A-Z]/.test(image) && 'appIcon');
+        flag = flag || (/^png|gif|jpe?g$/.test(ext) && 'image');
+        flag = flag || (ext && (image = ext) && 'icon');
+        flag = flag || 'icon';
+        args.push(`--${flag}`, image);
+        break;
+      }
+      case 'Darwin-NotificationCenter':
+        args.push(cmd.icon, image);
+        break;
+      case 'Linux':
+        args.push(cmd.icon, image);
+        // libnotify defaults to sticky, set a hint for transient notifications
+        if (!options.sticky) args.push('--hint=int:transient:1');
+        break;
+      case 'Windows':
+        args.push(cmd.icon + image);
+        break;
+      default:
+        break;
+    }
+  }
+
+  // sticky
+  if (options.sticky) args.push(cmd.sticky);
+  if (options.sticky && cmd.type === 'Linux') args.push('0');
+
+  // priority
+  if (options.priority) {
+    const priority = `${options.priority}`;
+    const checkindexOf = cmd.priority.range.indexOf(priority);
+    if (checkindexOf > -1) {
+      args.push(cmd.priority, options.priority);
+    }
+  }
+
+  // sound
+  if (options.sound && cmd.type === 'Darwin-NotificationCenter') {
+    args.push(cmd.sound, options.sound);
+  }
+
+  // name
+  if (options.name && cmd.type === 'Darwin-Growl') {
+    args.push('--name', options.name);
+  }
+
+  switch (cmd.type) {
+    case 'Darwin-Growl':
+      args.push(cmd.msg);
+      args.push(msg.replace(/\\n/g, '\n'));
+      if (options.title) args.push(options.title);
+      if (options.url) {
+        args.push(cmd.url);
+        args.push(options.url);
+      }
+      break;
+    case 'Darwin-NotificationCenter': {
+      args.push(cmd.msg);
+      const stringifiedMsg = msg;
+      const escapedMsg = stringifiedMsg.replace(/\\n/g, '\n');
+      args.push(escapedMsg);
+      if (options.title) {
+        args.push(cmd.title);
+        args.push(options.title);
+      }
+      if (options.subtitle) {
+        args.push(cmd.subtitle);
+        args.push(options.subtitle);
+      }
+      if (options.url) {
+        args.push(cmd.url);
+        args.push(options.url);
+      }
+      break;
+    }
+    case 'Linux-Growl':
+      args.push(cmd.msg);
+      args.push(msg.replace(/\\n/g, '\n'));
+      if (options.title) args.push(options.title);
+      if (cmd.host) {
+        args.push(cmd.host.cmd, cmd.host.hostname);
+      }
+      break;
+    case 'Linux':
+      if (options.title) args.push(options.title);
+      args.push(msg.replace(/\\n/g, '\n'));
+      break;
+    case 'Windows':
+      args.push(msg.replace(/\\n/g, '\n'));
+      if (options.title) args.push(cmd.title + options.title);
+      if (options.url) args.push(cmd.url + options.url);
+      break;
+    case 'Custom': {
+      const customCmd = args[0];
+      const message = options.title
+        ? `${options.title}: ${msg}`
+        : msg;
+      let command = customCmd.replace(/(^|[^%])%s/g, `$1${message}`);
+      const splitCmd = command.split(' ');
+      if (splitCmd.length > 1) {
+        command = splitCmd.shift();
+        Array.prototype.push.apply(args, splitCmd);
+      }
+      if (customCmd.indexOf('%s') < 0) {
+        args.push(message);
+      }
+      args[0] = command;
+      break;
+    }
+    default:
+      break;
+  }
+  const cmdToExec = args.shift();
+
+  const child = spawn(cmdToExec, args);
+  let stdout = '';
+  let stderr = '';
+  let error;
+
+  const now = new Date();
+  const timestamp = `${now.getHours()}:${now.getMinutes()}:${now.getSeconds()}.${now.getMilliseconds()}`
+
+  stderr += `[${timestamp}][node-growl] : Executed command '${cmdToExec}' with arguments '${args}'\n[stderr] : `;
+
+  child.on('error', (err) => {
+    console.error('An error occured.', err);
+    error = err;
+  });
+
+  child.stdout.on('data', (data) => {
+    stdout += data;
+  });
+
+  child.stderr.on('data', (data) => {
+    stderr += data;
+  });
+
+  child.on('close', () => {
+    if (typeof fn === 'function') {
+      fn(error, stdout, stderr);
+    }
+  });
+}
+
+/**
+ * Expose `growl`.
+ */
+
+module.exports = growl;
diff --git a/node_modules/growl/package.json b/node_modules/growl/package.json
new file mode 100644
index 0000000..fe73ba0
--- /dev/null
+++ b/node_modules/growl/package.json
@@ -0,0 +1,67 @@
+{
+  "_from": "growl@1.10.5",
+  "_id": "growl@1.10.5",
+  "_inBundle": false,
+  "_integrity": "sha512-qBr4OuELkhPenW6goKVXiv47US3clb3/IbuWF9KNKEijAy9oeHxU9IgzjvJhHkUzhaj7rOUD7+YGWqUjLp5oSA==",
+  "_location": "/growl",
+  "_phantomChildren": {},
+  "_requested": {
+    "type": "version",
+    "registry": true,
+    "raw": "growl@1.10.5",
+    "name": "growl",
+    "escapedName": "growl",
+    "rawSpec": "1.10.5",
+    "saveSpec": null,
+    "fetchSpec": "1.10.5"
+  },
+  "_requiredBy": [
+    "/mocha"
+  ],
+  "_resolved": "https://registry.npmjs.org/growl/-/growl-1.10.5.tgz",
+  "_shasum": "f2735dc2283674fa67478b10181059355c369e5e",
+  "_spec": "growl@1.10.5",
+  "_where": "/Users/jessitron/code/jessitron/stringify-tree/node_modules/mocha",
+  "author": {
+    "name": "TJ Holowaychuk",
+    "email": "tj@vision-media.ca"
+  },
+  "bugs": {
+    "url": "https://github.com/tj/node-growl/issues"
+  },
+  "bundleDependencies": false,
+  "deprecated": false,
+  "description": "Growl unobtrusive notifications",
+  "devDependencies": {
+    "eslint": "^4.8.0",
+    "eslint-config-airbnb-base": "^12.0.1",
+    "eslint-plugin-import": "^2.7.0",
+    "eslint-plugin-node": "^5.2.0"
+  },
+  "engines": {
+    "node": ">=4.x"
+  },
+  "homepage": "https://github.com/tj/node-growl#readme",
+  "license": "MIT",
+  "main": "./lib/growl.js",
+  "maintainers": [
+    {
+      "name": "Joshua Boy Nicolai Appelman",
+      "email": "joshua@jbnicolai.nl"
+    },
+    {
+      "name": "Timo Sand",
+      "email": "timo.sand@iki.fi"
+    }
+  ],
+  "name": "growl",
+  "repository": {
+    "type": "git",
+    "url": "git://github.com/tj/node-growl.git"
+  },
+  "scripts": {
+    "lint": "eslint --ext js lib ",
+    "test": "node test.js"
+  },
+  "version": "1.10.5"
+}
diff --git a/node_modules/growl/test.js b/node_modules/growl/test.js
new file mode 100644
index 0000000..3b1d229
--- /dev/null
+++ b/node_modules/growl/test.js
@@ -0,0 +1,31 @@
+
+var growl = require('./lib/growl')
+
+growl('Support sound notifications', {title: 'Make a sound', sound: 'purr'});
+growl('You have mail!')
+growl('5 new messages', { sticky: true })
+growl('5 new emails', { title: 'Email Client', image: 'Safari', sticky: true })
+growl('Message with title', { title: 'Title'})
+growl('Set priority', { priority: 2 })
+growl('Show Safari icon', { image: 'Safari' })
+growl('Show icon', { image: 'path/to/icon.icns' })
+growl('Show image', { image: 'path/to/my.image.png' })
+growl('Show png filesystem icon', { image: 'png' })
+growl('Show pdf filesystem icon', { image: 'article.pdf' })
+growl('Show pdf filesystem icon', { image: 'article.pdf' }, function(){
+  console.log('callback');
+})
+growl('Show pdf filesystem icon', { title: 'Use show()', image: 'article.pdf' })
+growl('here \' are \n some \\ characters that " need escaping', {}, function(error, stdout, stderr) {
+  if (error) throw new Error('escaping failed:\n' + stdout + stderr);
+})
+growl('Allow custom notifiers', { exec: 'echo XXX %s' }, function(error, stdout, stderr) {
+  console.log(stdout);
+})
+growl('Allow custom notifiers', { title: 'test', exec: 'echo YYY' }, function(error, stdout, stderr) {
+  console.log(stdout);
+})
+growl('Allow custom notifiers', { title: 'test', exec: 'echo ZZZ %s' }, function(error, stdout, stderr) {
+  console.log(stdout);
+})
+growl('Open a URL', { url: 'https://npmjs.org/package/growl' });
diff --git a/node_modules/has-flag/index.js b/node_modules/has-flag/index.js
new file mode 100644
index 0000000..5139728
--- /dev/null
+++ b/node_modules/has-flag/index.js
@@ -0,0 +1,8 @@
+'use strict';
+module.exports = (flag, argv) => {
+	argv = argv || process.argv;
+	const prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--');
+	const pos = argv.indexOf(prefix + flag);
+	const terminatorPos = argv.indexOf('--');
+	return pos !== -1 && (terminatorPos === -1 ? true : pos < terminatorPos);
+};
diff --git a/node_modules/has-flag/license b/node_modules/has-flag/license
new file mode 100644
index 0000000..e7af2f7
--- /dev/null
+++ b/node_modules/has-flag/license
@@ -0,0 +1,9 @@
+MIT License
+
+Copyright (c) Sindre Sorhus  (sindresorhus.com)
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/node_modules/has-flag/package.json b/node_modules/has-flag/package.json
new file mode 100644
index 0000000..1eb8084
--- /dev/null
+++ b/node_modules/has-flag/package.json
@@ -0,0 +1,76 @@
+{
+  "_from": "has-flag@^3.0.0",
+  "_id": "has-flag@3.0.0",
+  "_inBundle": false,
+  "_integrity": "sha1-tdRU3CGZriJWmfNGfloH87lVuv0=",
+  "_location": "/has-flag",
+  "_phantomChildren": {},
+  "_requested": {
+    "type": "range",
+    "registry": true,
+    "raw": "has-flag@^3.0.0",
+    "name": "has-flag",
+    "escapedName": "has-flag",
+    "rawSpec": "^3.0.0",
+    "saveSpec": null,
+    "fetchSpec": "^3.0.0"
+  },
+  "_requiredBy": [
+    "/supports-color"
+  ],
+  "_resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz",
+  "_shasum": "b5d454dc2199ae225699f3467e5a07f3b955bafd",
+  "_spec": "has-flag@^3.0.0",
+  "_where": "/Users/jessitron/code/jessitron/stringify-tree/node_modules/supports-color",
+  "author": {
+    "name": "Sindre Sorhus",
+    "email": "sindresorhus@gmail.com",
+    "url": "sindresorhus.com"
+  },
+  "bugs": {
+    "url": "https://github.com/sindresorhus/has-flag/issues"
+  },
+  "bundleDependencies": false,
+  "deprecated": false,
+  "description": "Check if argv has a specific flag",
+  "devDependencies": {
+    "ava": "*",
+    "xo": "*"
+  },
+  "engines": {
+    "node": ">=4"
+  },
+  "files": [
+    "index.js"
+  ],
+  "homepage": "https://github.com/sindresorhus/has-flag#readme",
+  "keywords": [
+    "has",
+    "check",
+    "detect",
+    "contains",
+    "find",
+    "flag",
+    "cli",
+    "command-line",
+    "argv",
+    "process",
+    "arg",
+    "args",
+    "argument",
+    "arguments",
+    "getopt",
+    "minimist",
+    "optimist"
+  ],
+  "license": "MIT",
+  "name": "has-flag",
+  "repository": {
+    "type": "git",
+    "url": "git+https://github.com/sindresorhus/has-flag.git"
+  },
+  "scripts": {
+    "test": "xo && ava"
+  },
+  "version": "3.0.0"
+}
diff --git a/node_modules/has-flag/readme.md b/node_modules/has-flag/readme.md
new file mode 100644
index 0000000..677893c
--- /dev/null
+++ b/node_modules/has-flag/readme.md
@@ -0,0 +1,70 @@
+# has-flag [![Build Status](https://travis-ci.org/sindresorhus/has-flag.svg?branch=master)](https://travis-ci.org/sindresorhus/has-flag)
+
+> Check if [`argv`](https://nodejs.org/docs/latest/api/process.html#process_process_argv) has a specific flag
+
+Correctly stops looking after an `--` argument terminator.
+
+
+## Install
+
+```
+$ npm install has-flag
+```
+
+
+## Usage
+
+```js
+// foo.js
+const hasFlag = require('has-flag');
+
+hasFlag('unicorn');
+//=> true
+
+hasFlag('--unicorn');
+//=> true
+
+hasFlag('f');
+//=> true
+
+hasFlag('-f');
+//=> true
+
+hasFlag('foo=bar');
+//=> true
+
+hasFlag('foo');
+//=> false
+
+hasFlag('rainbow');
+//=> false
+```
+
+```
+$ node foo.js -f --unicorn --foo=bar -- --rainbow
+```
+
+
+## API
+
+### hasFlag(flag, [argv])
+
+Returns a boolean for whether the flag exists.
+
+#### flag
+
+Type: `string`
+
+CLI flag to look for. The `--` prefix is optional.
+
+#### argv
+
+Type: `string[]`
+Default: `process.argv` + +CLI arguments. + + +## License + +MIT © [Sindre Sorhus](https://sindresorhus.com) diff --git a/node_modules/he/LICENSE-MIT.txt b/node_modules/he/LICENSE-MIT.txt new file mode 100644 index 0000000..a41e0a7 --- /dev/null +++ b/node_modules/he/LICENSE-MIT.txt @@ -0,0 +1,20 @@ +Copyright Mathias Bynens + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/he/README.md b/node_modules/he/README.md new file mode 100644 index 0000000..b2223a9 --- /dev/null +++ b/node_modules/he/README.md @@ -0,0 +1,379 @@ +# he [![Build status](https://travis-ci.org/mathiasbynens/he.svg?branch=master)](https://travis-ci.org/mathiasbynens/he) [![Code coverage status](https://codecov.io/github/mathiasbynens/he/coverage.svg?branch=master)](https://codecov.io/github/mathiasbynens/he?branch=master) [![Dependency status](https://gemnasium.com/mathiasbynens/he.svg)](https://gemnasium.com/mathiasbynens/he) + +_he_ (for “HTML entities”) is a robust HTML entity encoder/decoder written in JavaScript. It supports [all standardized named character references as per HTML](https://html.spec.whatwg.org/multipage/syntax.html#named-character-references), handles [ambiguous ampersands](https://mathiasbynens.be/notes/ambiguous-ampersands) and other edge cases [just like a browser would](https://html.spec.whatwg.org/multipage/syntax.html#tokenizing-character-references), has an extensive test suite, and — contrary to many other JavaScript solutions — _he_ handles astral Unicode symbols just fine. [An online demo is available.](https://mothereff.in/html-entities) + +## Installation + +Via [npm](https://www.npmjs.com/): + +```bash +npm install he +``` + +Via [Bower](http://bower.io/): + +```bash +bower install he +``` + +Via [Component](https://github.com/component/component): + +```bash +component install mathiasbynens/he +``` + +In a browser: + +```html + +``` + +In [Node.js](https://nodejs.org/), [io.js](https://iojs.org/), [Narwhal](http://narwhaljs.org/), and [RingoJS](http://ringojs.org/): + +```js +var he = require('he'); +``` + +In [Rhino](http://www.mozilla.org/rhino/): + +```js +load('he.js'); +``` + +Using an AMD loader like [RequireJS](http://requirejs.org/): + +```js +require( + { + 'paths': { + 'he': 'path/to/he' + } + }, + ['he'], + function(he) { + console.log(he); + } +); +``` + +## API + +### `he.version` + +A string representing the semantic version number. + +### `he.encode(text, options)` + +This function takes a string of text and encodes (by default) any symbols that aren’t printable ASCII symbols and `&`, `<`, `>`, `"`, `'`, and `` ` ``, replacing them with character references. + +```js +he.encode('foo © bar ≠ baz 𝌆 qux'); +// → 'foo © bar ≠ baz 𝌆 qux' +``` + +As long as the input string contains [allowed code points](https://html.spec.whatwg.org/multipage/parsing.html#preprocessing-the-input-stream) only, the return value of this function is always valid HTML. Any [(invalid) code points that cannot be represented using a character reference](https://html.spec.whatwg.org/multipage/syntax.html#table-charref-overrides) in the input are not encoded: + +```js +he.encode('foo \0 bar'); +// → 'foo \0 bar' +``` + +However, enabling [the `strict` option](https://github.com/mathiasbynens/he#strict) causes invalid code points to throw an exception. With `strict` enabled, `he.encode` either throws (if the input contains invalid code points) or returns a string of valid HTML. + +The `options` object is optional. It recognizes the following properties: + +#### `useNamedReferences` + +The default value for the `useNamedReferences` option is `false`. This means that `encode()` will not use any named character references (e.g. `©`) in the output — hexadecimal escapes (e.g. `©`) will be used instead. Set it to `true` to enable the use of named references. + +**Note that if compatibility with older browsers is a concern, this option should remain disabled.** + +```js +// Using the global default setting (defaults to `false`): +he.encode('foo © bar ≠ baz 𝌆 qux'); +// → 'foo © bar ≠ baz 𝌆 qux' + +// Passing an `options` object to `encode`, to explicitly disallow named references: +he.encode('foo © bar ≠ baz 𝌆 qux', { + 'useNamedReferences': false +}); +// → 'foo © bar ≠ baz 𝌆 qux' + +// Passing an `options` object to `encode`, to explicitly allow named references: +he.encode('foo © bar ≠ baz 𝌆 qux', { + 'useNamedReferences': true +}); +// → 'foo © bar ≠ baz 𝌆 qux' +``` + +#### `decimal` + +The default value for the `decimal` option is `false`. If the option is enabled, `encode` will generally use decimal escapes (e.g. `©`) rather than hexadecimal escapes (e.g. `©`). Beside of this replacement, the basic behavior remains the same when combined with other options. For example: if both options `useNamedReferences` and `decimal` are enabled, named references (e.g. `©`) are used over decimal escapes. HTML entities without a named reference are encoded using decimal escapes. + +```js +// Using the global default setting (defaults to `false`): +he.encode('foo © bar ≠ baz 𝌆 qux'); +// → 'foo © bar ≠ baz 𝌆 qux' + +// Passing an `options` object to `encode`, to explicitly disable decimal escapes: +he.encode('foo © bar ≠ baz 𝌆 qux', { + 'decimal': false +}); +// → 'foo © bar ≠ baz 𝌆 qux' + +// Passing an `options` object to `encode`, to explicitly enable decimal escapes: +he.encode('foo © bar ≠ baz 𝌆 qux', { + 'decimal': true +}); +// → 'foo © bar ≠ baz 𝌆 qux' + +// Passing an `options` object to `encode`, to explicitly allow named references and decimal escapes: +he.encode('foo © bar ≠ baz 𝌆 qux', { + 'useNamedReferences': true, + 'decimal': true +}); +// → 'foo © bar ≠ baz 𝌆 qux' +``` + +#### `encodeEverything` + +The default value for the `encodeEverything` option is `false`. This means that `encode()` will not use any character references for printable ASCII symbols that don’t need escaping. Set it to `true` to encode every symbol in the input string. When set to `true`, this option takes precedence over `allowUnsafeSymbols` (i.e. setting the latter to `true` in such a case has no effect). + +```js +// Using the global default setting (defaults to `false`): +he.encode('foo © bar ≠ baz 𝌆 qux'); +// → 'foo © bar ≠ baz 𝌆 qux' + +// Passing an `options` object to `encode`, to explicitly encode all symbols: +he.encode('foo © bar ≠ baz 𝌆 qux', { + 'encodeEverything': true +}); +// → 'foo © bar ≠ baz 𝌆 qux' + +// This setting can be combined with the `useNamedReferences` option: +he.encode('foo © bar ≠ baz 𝌆 qux', { + 'encodeEverything': true, + 'useNamedReferences': true +}); +// → 'foo © bar ≠ baz 𝌆 qux' +``` + +#### `strict` + +The default value for the `strict` option is `false`. This means that `encode()` will encode any HTML text content you feed it, even if it contains any symbols that cause [parse errors](https://html.spec.whatwg.org/multipage/parsing.html#preprocessing-the-input-stream). To throw an error when such invalid HTML is encountered, set the `strict` option to `true`. This option makes it possible to use _he_ as part of HTML parsers and HTML validators. + +```js +// Using the global default setting (defaults to `false`, i.e. error-tolerant mode): +he.encode('\x01'); +// → '' + +// Passing an `options` object to `encode`, to explicitly enable error-tolerant mode: +he.encode('\x01', { + 'strict': false +}); +// → '' + +// Passing an `options` object to `encode`, to explicitly enable strict mode: +he.encode('\x01', { + 'strict': true +}); +// → Parse error +``` + +#### `allowUnsafeSymbols` + +The default value for the `allowUnsafeSymbols` option is `false`. This means that characters that are unsafe for use in HTML content (`&`, `<`, `>`, `"`, `'`, and `` ` ``) will be encoded. When set to `true`, only non-ASCII characters will be encoded. If the `encodeEverything` option is set to `true`, this option will be ignored. + +```js +he.encode('foo © and & ampersand', { + 'allowUnsafeSymbols': true +}); +// → 'foo © and & ampersand' +``` + +#### Overriding default `encode` options globally + +The global default setting can be overridden by modifying the `he.encode.options` object. This saves you from passing in an `options` object for every call to `encode` if you want to use the non-default setting. + +```js +// Read the global default setting: +he.encode.options.useNamedReferences; +// → `false` by default + +// Override the global default setting: +he.encode.options.useNamedReferences = true; + +// Using the global default setting, which is now `true`: +he.encode('foo © bar ≠ baz 𝌆 qux'); +// → 'foo © bar ≠ baz 𝌆 qux' +``` + +### `he.decode(html, options)` + +This function takes a string of HTML and decodes any named and numerical character references in it using [the algorithm described in section 12.2.4.69 of the HTML spec](https://html.spec.whatwg.org/multipage/syntax.html#tokenizing-character-references). + +```js +he.decode('foo © bar ≠ baz 𝌆 qux'); +// → 'foo © bar ≠ baz 𝌆 qux' +``` + +The `options` object is optional. It recognizes the following properties: + +#### `isAttributeValue` + +The default value for the `isAttributeValue` option is `false`. This means that `decode()` will decode the string as if it were used in [a text context in an HTML document](https://html.spec.whatwg.org/multipage/syntax.html#data-state). HTML has different rules for [parsing character references in attribute values](https://html.spec.whatwg.org/multipage/syntax.html#character-reference-in-attribute-value-state) — set this option to `true` to treat the input string as if it were used as an attribute value. + +```js +// Using the global default setting (defaults to `false`, i.e. HTML text context): +he.decode('foo&bar'); +// → 'foo&bar' + +// Passing an `options` object to `decode`, to explicitly assume an HTML text context: +he.decode('foo&bar', { + 'isAttributeValue': false +}); +// → 'foo&bar' + +// Passing an `options` object to `decode`, to explicitly assume an HTML attribute value context: +he.decode('foo&bar', { + 'isAttributeValue': true +}); +// → 'foo&bar' +``` + +#### `strict` + +The default value for the `strict` option is `false`. This means that `decode()` will decode any HTML text content you feed it, even if it contains any entities that cause [parse errors](https://html.spec.whatwg.org/multipage/syntax.html#tokenizing-character-references). To throw an error when such invalid HTML is encountered, set the `strict` option to `true`. This option makes it possible to use _he_ as part of HTML parsers and HTML validators. + +```js +// Using the global default setting (defaults to `false`, i.e. error-tolerant mode): +he.decode('foo&bar'); +// → 'foo&bar' + +// Passing an `options` object to `decode`, to explicitly enable error-tolerant mode: +he.decode('foo&bar', { + 'strict': false +}); +// → 'foo&bar' + +// Passing an `options` object to `decode`, to explicitly enable strict mode: +he.decode('foo&bar', { + 'strict': true +}); +// → Parse error +``` + +#### Overriding default `decode` options globally + +The global default settings for the `decode` function can be overridden by modifying the `he.decode.options` object. This saves you from passing in an `options` object for every call to `decode` if you want to use a non-default setting. + +```js +// Read the global default setting: +he.decode.options.isAttributeValue; +// → `false` by default + +// Override the global default setting: +he.decode.options.isAttributeValue = true; + +// Using the global default setting, which is now `true`: +he.decode('foo&bar'); +// → 'foo&bar' +``` + +### `he.escape(text)` + +This function takes a string of text and escapes it for use in text contexts in XML or HTML documents. Only the following characters are escaped: `&`, `<`, `>`, `"`, `'`, and `` ` ``. + +```js +he.escape(''); +// → '<img src='x' onerror="prompt(1)">' +``` + +### `he.unescape(html, options)` + +`he.unescape` is an alias for `he.decode`. It takes a string of HTML and decodes any named and numerical character references in it. + +### Using the `he` binary + +To use the `he` binary in your shell, simply install _he_ globally using npm: + +```bash +npm install -g he +``` + +After that you will be able to encode/decode HTML entities from the command line: + +```bash +$ he --encode 'föo ♥ bår 𝌆 baz' +föo ♥ bår 𝌆 baz + +$ he --encode --use-named-refs 'föo ♥ bår 𝌆 baz' +föo ♥ bår 𝌆 baz + +$ he --decode 'föo ♥ bår 𝌆 baz' +föo ♥ bår 𝌆 baz +``` + +Read a local text file, encode it for use in an HTML text context, and save the result to a new file: + +```bash +$ he --encode < foo.txt > foo-escaped.html +``` + +Or do the same with an online text file: + +```bash +$ curl -sL "http://git.io/HnfEaw" | he --encode > escaped.html +``` + +Or, the opposite — read a local file containing a snippet of HTML in a text context, decode it back to plain text, and save the result to a new file: + +```bash +$ he --decode < foo-escaped.html > foo.txt +``` + +Or do the same with an online HTML snippet: + +```bash +$ curl -sL "http://git.io/HnfEaw" | he --decode > decoded.txt +``` + +See `he --help` for the full list of options. + +## Support + +_he_ has been tested in at least: + +* Chrome 27-50 +* Firefox 3-45 +* Safari 4-9 +* Opera 10-12, 15–37 +* IE 6–11 +* Edge +* Narwhal 0.3.2 +* Node.js v0.10, v0.12, v4, v5 +* PhantomJS 1.9.0 +* Rhino 1.7RC4 +* RingoJS 0.8-0.11 + +## Unit tests & code coverage + +After cloning this repository, run `npm install` to install the dependencies needed for he development and testing. You may want to install Istanbul _globally_ using `npm install istanbul -g`. + +Once that’s done, you can run the unit tests in Node using `npm test` or `node tests/tests.js`. To run the tests in Rhino, Ringo, Narwhal, and web browsers as well, use `grunt test`. + +To generate the code coverage report, use `grunt cover`. + +## Acknowledgements + +Thanks to [Simon Pieters](https://simon.html5.org/) ([@zcorpan](https://twitter.com/zcorpan)) for the many suggestions. + +## Author + +| [![twitter/mathias](https://gravatar.com/avatar/24e08a9ea84deb17ae121074d0f17125?s=70)](https://twitter.com/mathias "Follow @mathias on Twitter") | +|---| +| [Mathias Bynens](https://mathiasbynens.be/) | + +## License + +_he_ is available under the [MIT](https://mths.be/mit) license. diff --git a/node_modules/he/bin/he b/node_modules/he/bin/he new file mode 100755 index 0000000..cfdfd6c --- /dev/null +++ b/node_modules/he/bin/he @@ -0,0 +1,148 @@ +#!/usr/bin/env node +(function() { + + var fs = require('fs'); + var he = require('../he.js'); + var strings = process.argv.splice(2); + var stdin = process.stdin; + var data; + var timeout; + var action; + var options = {}; + var log = console.log; + + var main = function() { + var option = strings[0]; + var count = 0; + + if (/^(?:-h|--help|undefined)$/.test(option)) { + log( + 'he v%s - https://mths.be/he', + he.version + ); + log([ + '\nUsage:\n', + '\the [--escape] string', + '\the [--encode] [--use-named-refs] [--everything] [--allow-unsafe] [--decimal] string', + '\the [--decode] [--attribute] [--strict] string', + '\the [-v | --version]', + '\the [-h | --help]', + '\nExamples:\n', + '\the --escape \\', + '\techo \'© 𝌆\' | he --decode' + ].join('\n')); + return process.exit(option ? 0 : 1); + } + + if (/^(?:-v|--version)$/.test(option)) { + log('v%s', he.version); + return process.exit(0); + } + + strings.forEach(function(string) { + // Process options + if (string == '--escape') { + action = 'escape'; + return; + } + if (string == '--encode') { + action = 'encode'; + return; + } + if (string == '--use-named-refs') { + action = 'encode'; + options.useNamedReferences = true; + return; + } + if (string == '--everything') { + action = 'encode'; + options.encodeEverything = true; + return; + } + if (string == '--allow-unsafe') { + action = 'encode'; + options.allowUnsafeSymbols = true; + return; + } + if (string == '--decimal') { + action = 'encode'; + options.decimal = true; + return; + } + if (string == '--decode') { + action = 'decode'; + return; + } + if (string == '--attribute') { + action = 'decode'; + options.isAttributeValue = true; + return; + } + if (string == '--strict') { + action = 'decode'; + options.strict = true; + return; + } + // Process string(s) + var result; + if (!action) { + log('Error: he requires at least one option and a string argument.'); + log('Try `he --help` for more information.'); + return process.exit(1); + } + try { + result = he[action](string, options); + log(result); + count++; + } catch(error) { + log(error.message + '\n'); + log('Error: failed to %s.', action); + log('If you think this is a bug in he, please report it:'); + log('https://github.com/mathiasbynens/he/issues/new'); + log( + '\nStack trace using he@%s:\n', + he.version + ); + log(error.stack); + return process.exit(1); + } + }); + if (!count) { + log('Error: he requires a string argument.'); + log('Try `he --help` for more information.'); + return process.exit(1); + } + // Return with exit status 0 outside of the `forEach` loop, in case + // multiple strings were passed in. + return process.exit(0); + }; + + if (stdin.isTTY) { + // handle shell arguments + main(); + } else { + // Either the script is called from within a non-TTY context, or `stdin` + // content is being piped in. + if (!process.stdout.isTTY) { + // The script was called from a non-TTY context. This is a rather uncommon + // use case we don’t actively support. However, we don’t want the script + // to wait forever in such cases, so… + timeout = setTimeout(function() { + // …if no piped data arrived after a whole minute, handle shell + // arguments instead. + main(); + }, 60000); + } + data = ''; + stdin.on('data', function(chunk) { + clearTimeout(timeout); + data += chunk; + }); + stdin.on('end', function() { + strings.push(data.trim()); + main(); + }); + stdin.resume(); + } + +}()); diff --git a/node_modules/he/he.js b/node_modules/he/he.js new file mode 100644 index 0000000..f80078b --- /dev/null +++ b/node_modules/he/he.js @@ -0,0 +1,342 @@ +/*! https://mths.be/he v1.1.1 by @mathias | MIT license */ +;(function(root) { + + // Detect free variables `exports`. + var freeExports = typeof exports == 'object' && exports; + + // Detect free variable `module`. + var freeModule = typeof module == 'object' && module && + module.exports == freeExports && module; + + // Detect free variable `global`, from Node.js or Browserified code, + // and use it as `root`. + var freeGlobal = typeof global == 'object' && global; + if (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal) { + root = freeGlobal; + } + + /*--------------------------------------------------------------------------*/ + + // All astral symbols. + var regexAstralSymbols = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g; + // All ASCII symbols (not just printable ASCII) except those listed in the + // first column of the overrides table. + // https://html.spec.whatwg.org/multipage/syntax.html#table-charref-overrides + var regexAsciiWhitelist = /[\x01-\x7F]/g; + // All BMP symbols that are not ASCII newlines, printable ASCII symbols, or + // code points listed in the first column of the overrides table on + // https://html.spec.whatwg.org/multipage/syntax.html#table-charref-overrides. + var regexBmpWhitelist = /[\x01-\t\x0B\f\x0E-\x1F\x7F\x81\x8D\x8F\x90\x9D\xA0-\uFFFF]/g; + + var regexEncodeNonAscii = /<\u20D2|=\u20E5|>\u20D2|\u205F\u200A|\u219D\u0338|\u2202\u0338|\u2220\u20D2|\u2229\uFE00|\u222A\uFE00|\u223C\u20D2|\u223D\u0331|\u223E\u0333|\u2242\u0338|\u224B\u0338|\u224D\u20D2|\u224E\u0338|\u224F\u0338|\u2250\u0338|\u2261\u20E5|\u2264\u20D2|\u2265\u20D2|\u2266\u0338|\u2267\u0338|\u2268\uFE00|\u2269\uFE00|\u226A\u0338|\u226A\u20D2|\u226B\u0338|\u226B\u20D2|\u227F\u0338|\u2282\u20D2|\u2283\u20D2|\u228A\uFE00|\u228B\uFE00|\u228F\u0338|\u2290\u0338|\u2293\uFE00|\u2294\uFE00|\u22B4\u20D2|\u22B5\u20D2|\u22D8\u0338|\u22D9\u0338|\u22DA\uFE00|\u22DB\uFE00|\u22F5\u0338|\u22F9\u0338|\u2933\u0338|\u29CF\u0338|\u29D0\u0338|\u2A6D\u0338|\u2A70\u0338|\u2A7D\u0338|\u2A7E\u0338|\u2AA1\u0338|\u2AA2\u0338|\u2AAC\uFE00|\u2AAD\uFE00|\u2AAF\u0338|\u2AB0\u0338|\u2AC5\u0338|\u2AC6\u0338|\u2ACB\uFE00|\u2ACC\uFE00|\u2AFD\u20E5|[\xA0-\u0113\u0116-\u0122\u0124-\u012B\u012E-\u014D\u0150-\u017E\u0192\u01B5\u01F5\u0237\u02C6\u02C7\u02D8-\u02DD\u0311\u0391-\u03A1\u03A3-\u03A9\u03B1-\u03C9\u03D1\u03D2\u03D5\u03D6\u03DC\u03DD\u03F0\u03F1\u03F5\u03F6\u0401-\u040C\u040E-\u044F\u0451-\u045C\u045E\u045F\u2002-\u2005\u2007-\u2010\u2013-\u2016\u2018-\u201A\u201C-\u201E\u2020-\u2022\u2025\u2026\u2030-\u2035\u2039\u203A\u203E\u2041\u2043\u2044\u204F\u2057\u205F-\u2063\u20AC\u20DB\u20DC\u2102\u2105\u210A-\u2113\u2115-\u211E\u2122\u2124\u2127-\u2129\u212C\u212D\u212F-\u2131\u2133-\u2138\u2145-\u2148\u2153-\u215E\u2190-\u219B\u219D-\u21A7\u21A9-\u21AE\u21B0-\u21B3\u21B5-\u21B7\u21BA-\u21DB\u21DD\u21E4\u21E5\u21F5\u21FD-\u2205\u2207-\u2209\u220B\u220C\u220F-\u2214\u2216-\u2218\u221A\u221D-\u2238\u223A-\u2257\u2259\u225A\u225C\u225F-\u2262\u2264-\u228B\u228D-\u229B\u229D-\u22A5\u22A7-\u22B0\u22B2-\u22BB\u22BD-\u22DB\u22DE-\u22E3\u22E6-\u22F7\u22F9-\u22FE\u2305\u2306\u2308-\u2310\u2312\u2313\u2315\u2316\u231C-\u231F\u2322\u2323\u232D\u232E\u2336\u233D\u233F\u237C\u23B0\u23B1\u23B4-\u23B6\u23DC-\u23DF\u23E2\u23E7\u2423\u24C8\u2500\u2502\u250C\u2510\u2514\u2518\u251C\u2524\u252C\u2534\u253C\u2550-\u256C\u2580\u2584\u2588\u2591-\u2593\u25A1\u25AA\u25AB\u25AD\u25AE\u25B1\u25B3-\u25B5\u25B8\u25B9\u25BD-\u25BF\u25C2\u25C3\u25CA\u25CB\u25EC\u25EF\u25F8-\u25FC\u2605\u2606\u260E\u2640\u2642\u2660\u2663\u2665\u2666\u266A\u266D-\u266F\u2713\u2717\u2720\u2736\u2758\u2772\u2773\u27C8\u27C9\u27E6-\u27ED\u27F5-\u27FA\u27FC\u27FF\u2902-\u2905\u290C-\u2913\u2916\u2919-\u2920\u2923-\u292A\u2933\u2935-\u2939\u293C\u293D\u2945\u2948-\u294B\u294E-\u2976\u2978\u2979\u297B-\u297F\u2985\u2986\u298B-\u2996\u299A\u299C\u299D\u29A4-\u29B7\u29B9\u29BB\u29BC\u29BE-\u29C5\u29C9\u29CD-\u29D0\u29DC-\u29DE\u29E3-\u29E5\u29EB\u29F4\u29F6\u2A00-\u2A02\u2A04\u2A06\u2A0C\u2A0D\u2A10-\u2A17\u2A22-\u2A27\u2A29\u2A2A\u2A2D-\u2A31\u2A33-\u2A3C\u2A3F\u2A40\u2A42-\u2A4D\u2A50\u2A53-\u2A58\u2A5A-\u2A5D\u2A5F\u2A66\u2A6A\u2A6D-\u2A75\u2A77-\u2A9A\u2A9D-\u2AA2\u2AA4-\u2AB0\u2AB3-\u2AC8\u2ACB\u2ACC\u2ACF-\u2ADB\u2AE4\u2AE6-\u2AE9\u2AEB-\u2AF3\u2AFD\uFB00-\uFB04]|\uD835[\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDCCF\uDD04\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDD6B]/g; + var encodeMap = {'\xAD':'shy','\u200C':'zwnj','\u200D':'zwj','\u200E':'lrm','\u2063':'ic','\u2062':'it','\u2061':'af','\u200F':'rlm','\u200B':'ZeroWidthSpace','\u2060':'NoBreak','\u0311':'DownBreve','\u20DB':'tdot','\u20DC':'DotDot','\t':'Tab','\n':'NewLine','\u2008':'puncsp','\u205F':'MediumSpace','\u2009':'thinsp','\u200A':'hairsp','\u2004':'emsp13','\u2002':'ensp','\u2005':'emsp14','\u2003':'emsp','\u2007':'numsp','\xA0':'nbsp','\u205F\u200A':'ThickSpace','\u203E':'oline','_':'lowbar','\u2010':'dash','\u2013':'ndash','\u2014':'mdash','\u2015':'horbar',',':'comma',';':'semi','\u204F':'bsemi',':':'colon','\u2A74':'Colone','!':'excl','\xA1':'iexcl','?':'quest','\xBF':'iquest','.':'period','\u2025':'nldr','\u2026':'mldr','\xB7':'middot','\'':'apos','\u2018':'lsquo','\u2019':'rsquo','\u201A':'sbquo','\u2039':'lsaquo','\u203A':'rsaquo','"':'quot','\u201C':'ldquo','\u201D':'rdquo','\u201E':'bdquo','\xAB':'laquo','\xBB':'raquo','(':'lpar',')':'rpar','[':'lsqb',']':'rsqb','{':'lcub','}':'rcub','\u2308':'lceil','\u2309':'rceil','\u230A':'lfloor','\u230B':'rfloor','\u2985':'lopar','\u2986':'ropar','\u298B':'lbrke','\u298C':'rbrke','\u298D':'lbrkslu','\u298E':'rbrksld','\u298F':'lbrksld','\u2990':'rbrkslu','\u2991':'langd','\u2992':'rangd','\u2993':'lparlt','\u2994':'rpargt','\u2995':'gtlPar','\u2996':'ltrPar','\u27E6':'lobrk','\u27E7':'robrk','\u27E8':'lang','\u27E9':'rang','\u27EA':'Lang','\u27EB':'Rang','\u27EC':'loang','\u27ED':'roang','\u2772':'lbbrk','\u2773':'rbbrk','\u2016':'Vert','\xA7':'sect','\xB6':'para','@':'commat','*':'ast','/':'sol','undefined':null,'&':'amp','#':'num','%':'percnt','\u2030':'permil','\u2031':'pertenk','\u2020':'dagger','\u2021':'Dagger','\u2022':'bull','\u2043':'hybull','\u2032':'prime','\u2033':'Prime','\u2034':'tprime','\u2057':'qprime','\u2035':'bprime','\u2041':'caret','`':'grave','\xB4':'acute','\u02DC':'tilde','^':'Hat','\xAF':'macr','\u02D8':'breve','\u02D9':'dot','\xA8':'die','\u02DA':'ring','\u02DD':'dblac','\xB8':'cedil','\u02DB':'ogon','\u02C6':'circ','\u02C7':'caron','\xB0':'deg','\xA9':'copy','\xAE':'reg','\u2117':'copysr','\u2118':'wp','\u211E':'rx','\u2127':'mho','\u2129':'iiota','\u2190':'larr','\u219A':'nlarr','\u2192':'rarr','\u219B':'nrarr','\u2191':'uarr','\u2193':'darr','\u2194':'harr','\u21AE':'nharr','\u2195':'varr','\u2196':'nwarr','\u2197':'nearr','\u2198':'searr','\u2199':'swarr','\u219D':'rarrw','\u219D\u0338':'nrarrw','\u219E':'Larr','\u219F':'Uarr','\u21A0':'Rarr','\u21A1':'Darr','\u21A2':'larrtl','\u21A3':'rarrtl','\u21A4':'mapstoleft','\u21A5':'mapstoup','\u21A6':'map','\u21A7':'mapstodown','\u21A9':'larrhk','\u21AA':'rarrhk','\u21AB':'larrlp','\u21AC':'rarrlp','\u21AD':'harrw','\u21B0':'lsh','\u21B1':'rsh','\u21B2':'ldsh','\u21B3':'rdsh','\u21B5':'crarr','\u21B6':'cularr','\u21B7':'curarr','\u21BA':'olarr','\u21BB':'orarr','\u21BC':'lharu','\u21BD':'lhard','\u21BE':'uharr','\u21BF':'uharl','\u21C0':'rharu','\u21C1':'rhard','\u21C2':'dharr','\u21C3':'dharl','\u21C4':'rlarr','\u21C5':'udarr','\u21C6':'lrarr','\u21C7':'llarr','\u21C8':'uuarr','\u21C9':'rrarr','\u21CA':'ddarr','\u21CB':'lrhar','\u21CC':'rlhar','\u21D0':'lArr','\u21CD':'nlArr','\u21D1':'uArr','\u21D2':'rArr','\u21CF':'nrArr','\u21D3':'dArr','\u21D4':'iff','\u21CE':'nhArr','\u21D5':'vArr','\u21D6':'nwArr','\u21D7':'neArr','\u21D8':'seArr','\u21D9':'swArr','\u21DA':'lAarr','\u21DB':'rAarr','\u21DD':'zigrarr','\u21E4':'larrb','\u21E5':'rarrb','\u21F5':'duarr','\u21FD':'loarr','\u21FE':'roarr','\u21FF':'hoarr','\u2200':'forall','\u2201':'comp','\u2202':'part','\u2202\u0338':'npart','\u2203':'exist','\u2204':'nexist','\u2205':'empty','\u2207':'Del','\u2208':'in','\u2209':'notin','\u220B':'ni','\u220C':'notni','\u03F6':'bepsi','\u220F':'prod','\u2210':'coprod','\u2211':'sum','+':'plus','\xB1':'pm','\xF7':'div','\xD7':'times','<':'lt','\u226E':'nlt','<\u20D2':'nvlt','=':'equals','\u2260':'ne','=\u20E5':'bne','\u2A75':'Equal','>':'gt','\u226F':'ngt','>\u20D2':'nvgt','\xAC':'not','|':'vert','\xA6':'brvbar','\u2212':'minus','\u2213':'mp','\u2214':'plusdo','\u2044':'frasl','\u2216':'setmn','\u2217':'lowast','\u2218':'compfn','\u221A':'Sqrt','\u221D':'prop','\u221E':'infin','\u221F':'angrt','\u2220':'ang','\u2220\u20D2':'nang','\u2221':'angmsd','\u2222':'angsph','\u2223':'mid','\u2224':'nmid','\u2225':'par','\u2226':'npar','\u2227':'and','\u2228':'or','\u2229':'cap','\u2229\uFE00':'caps','\u222A':'cup','\u222A\uFE00':'cups','\u222B':'int','\u222C':'Int','\u222D':'tint','\u2A0C':'qint','\u222E':'oint','\u222F':'Conint','\u2230':'Cconint','\u2231':'cwint','\u2232':'cwconint','\u2233':'awconint','\u2234':'there4','\u2235':'becaus','\u2236':'ratio','\u2237':'Colon','\u2238':'minusd','\u223A':'mDDot','\u223B':'homtht','\u223C':'sim','\u2241':'nsim','\u223C\u20D2':'nvsim','\u223D':'bsim','\u223D\u0331':'race','\u223E':'ac','\u223E\u0333':'acE','\u223F':'acd','\u2240':'wr','\u2242':'esim','\u2242\u0338':'nesim','\u2243':'sime','\u2244':'nsime','\u2245':'cong','\u2247':'ncong','\u2246':'simne','\u2248':'ap','\u2249':'nap','\u224A':'ape','\u224B':'apid','\u224B\u0338':'napid','\u224C':'bcong','\u224D':'CupCap','\u226D':'NotCupCap','\u224D\u20D2':'nvap','\u224E':'bump','\u224E\u0338':'nbump','\u224F':'bumpe','\u224F\u0338':'nbumpe','\u2250':'doteq','\u2250\u0338':'nedot','\u2251':'eDot','\u2252':'efDot','\u2253':'erDot','\u2254':'colone','\u2255':'ecolon','\u2256':'ecir','\u2257':'cire','\u2259':'wedgeq','\u225A':'veeeq','\u225C':'trie','\u225F':'equest','\u2261':'equiv','\u2262':'nequiv','\u2261\u20E5':'bnequiv','\u2264':'le','\u2270':'nle','\u2264\u20D2':'nvle','\u2265':'ge','\u2271':'nge','\u2265\u20D2':'nvge','\u2266':'lE','\u2266\u0338':'nlE','\u2267':'gE','\u2267\u0338':'ngE','\u2268\uFE00':'lvnE','\u2268':'lnE','\u2269':'gnE','\u2269\uFE00':'gvnE','\u226A':'ll','\u226A\u0338':'nLtv','\u226A\u20D2':'nLt','\u226B':'gg','\u226B\u0338':'nGtv','\u226B\u20D2':'nGt','\u226C':'twixt','\u2272':'lsim','\u2274':'nlsim','\u2273':'gsim','\u2275':'ngsim','\u2276':'lg','\u2278':'ntlg','\u2277':'gl','\u2279':'ntgl','\u227A':'pr','\u2280':'npr','\u227B':'sc','\u2281':'nsc','\u227C':'prcue','\u22E0':'nprcue','\u227D':'sccue','\u22E1':'nsccue','\u227E':'prsim','\u227F':'scsim','\u227F\u0338':'NotSucceedsTilde','\u2282':'sub','\u2284':'nsub','\u2282\u20D2':'vnsub','\u2283':'sup','\u2285':'nsup','\u2283\u20D2':'vnsup','\u2286':'sube','\u2288':'nsube','\u2287':'supe','\u2289':'nsupe','\u228A\uFE00':'vsubne','\u228A':'subne','\u228B\uFE00':'vsupne','\u228B':'supne','\u228D':'cupdot','\u228E':'uplus','\u228F':'sqsub','\u228F\u0338':'NotSquareSubset','\u2290':'sqsup','\u2290\u0338':'NotSquareSuperset','\u2291':'sqsube','\u22E2':'nsqsube','\u2292':'sqsupe','\u22E3':'nsqsupe','\u2293':'sqcap','\u2293\uFE00':'sqcaps','\u2294':'sqcup','\u2294\uFE00':'sqcups','\u2295':'oplus','\u2296':'ominus','\u2297':'otimes','\u2298':'osol','\u2299':'odot','\u229A':'ocir','\u229B':'oast','\u229D':'odash','\u229E':'plusb','\u229F':'minusb','\u22A0':'timesb','\u22A1':'sdotb','\u22A2':'vdash','\u22AC':'nvdash','\u22A3':'dashv','\u22A4':'top','\u22A5':'bot','\u22A7':'models','\u22A8':'vDash','\u22AD':'nvDash','\u22A9':'Vdash','\u22AE':'nVdash','\u22AA':'Vvdash','\u22AB':'VDash','\u22AF':'nVDash','\u22B0':'prurel','\u22B2':'vltri','\u22EA':'nltri','\u22B3':'vrtri','\u22EB':'nrtri','\u22B4':'ltrie','\u22EC':'nltrie','\u22B4\u20D2':'nvltrie','\u22B5':'rtrie','\u22ED':'nrtrie','\u22B5\u20D2':'nvrtrie','\u22B6':'origof','\u22B7':'imof','\u22B8':'mumap','\u22B9':'hercon','\u22BA':'intcal','\u22BB':'veebar','\u22BD':'barvee','\u22BE':'angrtvb','\u22BF':'lrtri','\u22C0':'Wedge','\u22C1':'Vee','\u22C2':'xcap','\u22C3':'xcup','\u22C4':'diam','\u22C5':'sdot','\u22C6':'Star','\u22C7':'divonx','\u22C8':'bowtie','\u22C9':'ltimes','\u22CA':'rtimes','\u22CB':'lthree','\u22CC':'rthree','\u22CD':'bsime','\u22CE':'cuvee','\u22CF':'cuwed','\u22D0':'Sub','\u22D1':'Sup','\u22D2':'Cap','\u22D3':'Cup','\u22D4':'fork','\u22D5':'epar','\u22D6':'ltdot','\u22D7':'gtdot','\u22D8':'Ll','\u22D8\u0338':'nLl','\u22D9':'Gg','\u22D9\u0338':'nGg','\u22DA\uFE00':'lesg','\u22DA':'leg','\u22DB':'gel','\u22DB\uFE00':'gesl','\u22DE':'cuepr','\u22DF':'cuesc','\u22E6':'lnsim','\u22E7':'gnsim','\u22E8':'prnsim','\u22E9':'scnsim','\u22EE':'vellip','\u22EF':'ctdot','\u22F0':'utdot','\u22F1':'dtdot','\u22F2':'disin','\u22F3':'isinsv','\u22F4':'isins','\u22F5':'isindot','\u22F5\u0338':'notindot','\u22F6':'notinvc','\u22F7':'notinvb','\u22F9':'isinE','\u22F9\u0338':'notinE','\u22FA':'nisd','\u22FB':'xnis','\u22FC':'nis','\u22FD':'notnivc','\u22FE':'notnivb','\u2305':'barwed','\u2306':'Barwed','\u230C':'drcrop','\u230D':'dlcrop','\u230E':'urcrop','\u230F':'ulcrop','\u2310':'bnot','\u2312':'profline','\u2313':'profsurf','\u2315':'telrec','\u2316':'target','\u231C':'ulcorn','\u231D':'urcorn','\u231E':'dlcorn','\u231F':'drcorn','\u2322':'frown','\u2323':'smile','\u232D':'cylcty','\u232E':'profalar','\u2336':'topbot','\u233D':'ovbar','\u233F':'solbar','\u237C':'angzarr','\u23B0':'lmoust','\u23B1':'rmoust','\u23B4':'tbrk','\u23B5':'bbrk','\u23B6':'bbrktbrk','\u23DC':'OverParenthesis','\u23DD':'UnderParenthesis','\u23DE':'OverBrace','\u23DF':'UnderBrace','\u23E2':'trpezium','\u23E7':'elinters','\u2423':'blank','\u2500':'boxh','\u2502':'boxv','\u250C':'boxdr','\u2510':'boxdl','\u2514':'boxur','\u2518':'boxul','\u251C':'boxvr','\u2524':'boxvl','\u252C':'boxhd','\u2534':'boxhu','\u253C':'boxvh','\u2550':'boxH','\u2551':'boxV','\u2552':'boxdR','\u2553':'boxDr','\u2554':'boxDR','\u2555':'boxdL','\u2556':'boxDl','\u2557':'boxDL','\u2558':'boxuR','\u2559':'boxUr','\u255A':'boxUR','\u255B':'boxuL','\u255C':'boxUl','\u255D':'boxUL','\u255E':'boxvR','\u255F':'boxVr','\u2560':'boxVR','\u2561':'boxvL','\u2562':'boxVl','\u2563':'boxVL','\u2564':'boxHd','\u2565':'boxhD','\u2566':'boxHD','\u2567':'boxHu','\u2568':'boxhU','\u2569':'boxHU','\u256A':'boxvH','\u256B':'boxVh','\u256C':'boxVH','\u2580':'uhblk','\u2584':'lhblk','\u2588':'block','\u2591':'blk14','\u2592':'blk12','\u2593':'blk34','\u25A1':'squ','\u25AA':'squf','\u25AB':'EmptyVerySmallSquare','\u25AD':'rect','\u25AE':'marker','\u25B1':'fltns','\u25B3':'xutri','\u25B4':'utrif','\u25B5':'utri','\u25B8':'rtrif','\u25B9':'rtri','\u25BD':'xdtri','\u25BE':'dtrif','\u25BF':'dtri','\u25C2':'ltrif','\u25C3':'ltri','\u25CA':'loz','\u25CB':'cir','\u25EC':'tridot','\u25EF':'xcirc','\u25F8':'ultri','\u25F9':'urtri','\u25FA':'lltri','\u25FB':'EmptySmallSquare','\u25FC':'FilledSmallSquare','\u2605':'starf','\u2606':'star','\u260E':'phone','\u2640':'female','\u2642':'male','\u2660':'spades','\u2663':'clubs','\u2665':'hearts','\u2666':'diams','\u266A':'sung','\u2713':'check','\u2717':'cross','\u2720':'malt','\u2736':'sext','\u2758':'VerticalSeparator','\u27C8':'bsolhsub','\u27C9':'suphsol','\u27F5':'xlarr','\u27F6':'xrarr','\u27F7':'xharr','\u27F8':'xlArr','\u27F9':'xrArr','\u27FA':'xhArr','\u27FC':'xmap','\u27FF':'dzigrarr','\u2902':'nvlArr','\u2903':'nvrArr','\u2904':'nvHarr','\u2905':'Map','\u290C':'lbarr','\u290D':'rbarr','\u290E':'lBarr','\u290F':'rBarr','\u2910':'RBarr','\u2911':'DDotrahd','\u2912':'UpArrowBar','\u2913':'DownArrowBar','\u2916':'Rarrtl','\u2919':'latail','\u291A':'ratail','\u291B':'lAtail','\u291C':'rAtail','\u291D':'larrfs','\u291E':'rarrfs','\u291F':'larrbfs','\u2920':'rarrbfs','\u2923':'nwarhk','\u2924':'nearhk','\u2925':'searhk','\u2926':'swarhk','\u2927':'nwnear','\u2928':'toea','\u2929':'tosa','\u292A':'swnwar','\u2933':'rarrc','\u2933\u0338':'nrarrc','\u2935':'cudarrr','\u2936':'ldca','\u2937':'rdca','\u2938':'cudarrl','\u2939':'larrpl','\u293C':'curarrm','\u293D':'cularrp','\u2945':'rarrpl','\u2948':'harrcir','\u2949':'Uarrocir','\u294A':'lurdshar','\u294B':'ldrushar','\u294E':'LeftRightVector','\u294F':'RightUpDownVector','\u2950':'DownLeftRightVector','\u2951':'LeftUpDownVector','\u2952':'LeftVectorBar','\u2953':'RightVectorBar','\u2954':'RightUpVectorBar','\u2955':'RightDownVectorBar','\u2956':'DownLeftVectorBar','\u2957':'DownRightVectorBar','\u2958':'LeftUpVectorBar','\u2959':'LeftDownVectorBar','\u295A':'LeftTeeVector','\u295B':'RightTeeVector','\u295C':'RightUpTeeVector','\u295D':'RightDownTeeVector','\u295E':'DownLeftTeeVector','\u295F':'DownRightTeeVector','\u2960':'LeftUpTeeVector','\u2961':'LeftDownTeeVector','\u2962':'lHar','\u2963':'uHar','\u2964':'rHar','\u2965':'dHar','\u2966':'luruhar','\u2967':'ldrdhar','\u2968':'ruluhar','\u2969':'rdldhar','\u296A':'lharul','\u296B':'llhard','\u296C':'rharul','\u296D':'lrhard','\u296E':'udhar','\u296F':'duhar','\u2970':'RoundImplies','\u2971':'erarr','\u2972':'simrarr','\u2973':'larrsim','\u2974':'rarrsim','\u2975':'rarrap','\u2976':'ltlarr','\u2978':'gtrarr','\u2979':'subrarr','\u297B':'suplarr','\u297C':'lfisht','\u297D':'rfisht','\u297E':'ufisht','\u297F':'dfisht','\u299A':'vzigzag','\u299C':'vangrt','\u299D':'angrtvbd','\u29A4':'ange','\u29A5':'range','\u29A6':'dwangle','\u29A7':'uwangle','\u29A8':'angmsdaa','\u29A9':'angmsdab','\u29AA':'angmsdac','\u29AB':'angmsdad','\u29AC':'angmsdae','\u29AD':'angmsdaf','\u29AE':'angmsdag','\u29AF':'angmsdah','\u29B0':'bemptyv','\u29B1':'demptyv','\u29B2':'cemptyv','\u29B3':'raemptyv','\u29B4':'laemptyv','\u29B5':'ohbar','\u29B6':'omid','\u29B7':'opar','\u29B9':'operp','\u29BB':'olcross','\u29BC':'odsold','\u29BE':'olcir','\u29BF':'ofcir','\u29C0':'olt','\u29C1':'ogt','\u29C2':'cirscir','\u29C3':'cirE','\u29C4':'solb','\u29C5':'bsolb','\u29C9':'boxbox','\u29CD':'trisb','\u29CE':'rtriltri','\u29CF':'LeftTriangleBar','\u29CF\u0338':'NotLeftTriangleBar','\u29D0':'RightTriangleBar','\u29D0\u0338':'NotRightTriangleBar','\u29DC':'iinfin','\u29DD':'infintie','\u29DE':'nvinfin','\u29E3':'eparsl','\u29E4':'smeparsl','\u29E5':'eqvparsl','\u29EB':'lozf','\u29F4':'RuleDelayed','\u29F6':'dsol','\u2A00':'xodot','\u2A01':'xoplus','\u2A02':'xotime','\u2A04':'xuplus','\u2A06':'xsqcup','\u2A0D':'fpartint','\u2A10':'cirfnint','\u2A11':'awint','\u2A12':'rppolint','\u2A13':'scpolint','\u2A14':'npolint','\u2A15':'pointint','\u2A16':'quatint','\u2A17':'intlarhk','\u2A22':'pluscir','\u2A23':'plusacir','\u2A24':'simplus','\u2A25':'plusdu','\u2A26':'plussim','\u2A27':'plustwo','\u2A29':'mcomma','\u2A2A':'minusdu','\u2A2D':'loplus','\u2A2E':'roplus','\u2A2F':'Cross','\u2A30':'timesd','\u2A31':'timesbar','\u2A33':'smashp','\u2A34':'lotimes','\u2A35':'rotimes','\u2A36':'otimesas','\u2A37':'Otimes','\u2A38':'odiv','\u2A39':'triplus','\u2A3A':'triminus','\u2A3B':'tritime','\u2A3C':'iprod','\u2A3F':'amalg','\u2A40':'capdot','\u2A42':'ncup','\u2A43':'ncap','\u2A44':'capand','\u2A45':'cupor','\u2A46':'cupcap','\u2A47':'capcup','\u2A48':'cupbrcap','\u2A49':'capbrcup','\u2A4A':'cupcup','\u2A4B':'capcap','\u2A4C':'ccups','\u2A4D':'ccaps','\u2A50':'ccupssm','\u2A53':'And','\u2A54':'Or','\u2A55':'andand','\u2A56':'oror','\u2A57':'orslope','\u2A58':'andslope','\u2A5A':'andv','\u2A5B':'orv','\u2A5C':'andd','\u2A5D':'ord','\u2A5F':'wedbar','\u2A66':'sdote','\u2A6A':'simdot','\u2A6D':'congdot','\u2A6D\u0338':'ncongdot','\u2A6E':'easter','\u2A6F':'apacir','\u2A70':'apE','\u2A70\u0338':'napE','\u2A71':'eplus','\u2A72':'pluse','\u2A73':'Esim','\u2A77':'eDDot','\u2A78':'equivDD','\u2A79':'ltcir','\u2A7A':'gtcir','\u2A7B':'ltquest','\u2A7C':'gtquest','\u2A7D':'les','\u2A7D\u0338':'nles','\u2A7E':'ges','\u2A7E\u0338':'nges','\u2A7F':'lesdot','\u2A80':'gesdot','\u2A81':'lesdoto','\u2A82':'gesdoto','\u2A83':'lesdotor','\u2A84':'gesdotol','\u2A85':'lap','\u2A86':'gap','\u2A87':'lne','\u2A88':'gne','\u2A89':'lnap','\u2A8A':'gnap','\u2A8B':'lEg','\u2A8C':'gEl','\u2A8D':'lsime','\u2A8E':'gsime','\u2A8F':'lsimg','\u2A90':'gsiml','\u2A91':'lgE','\u2A92':'glE','\u2A93':'lesges','\u2A94':'gesles','\u2A95':'els','\u2A96':'egs','\u2A97':'elsdot','\u2A98':'egsdot','\u2A99':'el','\u2A9A':'eg','\u2A9D':'siml','\u2A9E':'simg','\u2A9F':'simlE','\u2AA0':'simgE','\u2AA1':'LessLess','\u2AA1\u0338':'NotNestedLessLess','\u2AA2':'GreaterGreater','\u2AA2\u0338':'NotNestedGreaterGreater','\u2AA4':'glj','\u2AA5':'gla','\u2AA6':'ltcc','\u2AA7':'gtcc','\u2AA8':'lescc','\u2AA9':'gescc','\u2AAA':'smt','\u2AAB':'lat','\u2AAC':'smte','\u2AAC\uFE00':'smtes','\u2AAD':'late','\u2AAD\uFE00':'lates','\u2AAE':'bumpE','\u2AAF':'pre','\u2AAF\u0338':'npre','\u2AB0':'sce','\u2AB0\u0338':'nsce','\u2AB3':'prE','\u2AB4':'scE','\u2AB5':'prnE','\u2AB6':'scnE','\u2AB7':'prap','\u2AB8':'scap','\u2AB9':'prnap','\u2ABA':'scnap','\u2ABB':'Pr','\u2ABC':'Sc','\u2ABD':'subdot','\u2ABE':'supdot','\u2ABF':'subplus','\u2AC0':'supplus','\u2AC1':'submult','\u2AC2':'supmult','\u2AC3':'subedot','\u2AC4':'supedot','\u2AC5':'subE','\u2AC5\u0338':'nsubE','\u2AC6':'supE','\u2AC6\u0338':'nsupE','\u2AC7':'subsim','\u2AC8':'supsim','\u2ACB\uFE00':'vsubnE','\u2ACB':'subnE','\u2ACC\uFE00':'vsupnE','\u2ACC':'supnE','\u2ACF':'csub','\u2AD0':'csup','\u2AD1':'csube','\u2AD2':'csupe','\u2AD3':'subsup','\u2AD4':'supsub','\u2AD5':'subsub','\u2AD6':'supsup','\u2AD7':'suphsub','\u2AD8':'supdsub','\u2AD9':'forkv','\u2ADA':'topfork','\u2ADB':'mlcp','\u2AE4':'Dashv','\u2AE6':'Vdashl','\u2AE7':'Barv','\u2AE8':'vBar','\u2AE9':'vBarv','\u2AEB':'Vbar','\u2AEC':'Not','\u2AED':'bNot','\u2AEE':'rnmid','\u2AEF':'cirmid','\u2AF0':'midcir','\u2AF1':'topcir','\u2AF2':'nhpar','\u2AF3':'parsim','\u2AFD':'parsl','\u2AFD\u20E5':'nparsl','\u266D':'flat','\u266E':'natur','\u266F':'sharp','\xA4':'curren','\xA2':'cent','$':'dollar','\xA3':'pound','\xA5':'yen','\u20AC':'euro','\xB9':'sup1','\xBD':'half','\u2153':'frac13','\xBC':'frac14','\u2155':'frac15','\u2159':'frac16','\u215B':'frac18','\xB2':'sup2','\u2154':'frac23','\u2156':'frac25','\xB3':'sup3','\xBE':'frac34','\u2157':'frac35','\u215C':'frac38','\u2158':'frac45','\u215A':'frac56','\u215D':'frac58','\u215E':'frac78','\uD835\uDCB6':'ascr','\uD835\uDD52':'aopf','\uD835\uDD1E':'afr','\uD835\uDD38':'Aopf','\uD835\uDD04':'Afr','\uD835\uDC9C':'Ascr','\xAA':'ordf','\xE1':'aacute','\xC1':'Aacute','\xE0':'agrave','\xC0':'Agrave','\u0103':'abreve','\u0102':'Abreve','\xE2':'acirc','\xC2':'Acirc','\xE5':'aring','\xC5':'angst','\xE4':'auml','\xC4':'Auml','\xE3':'atilde','\xC3':'Atilde','\u0105':'aogon','\u0104':'Aogon','\u0101':'amacr','\u0100':'Amacr','\xE6':'aelig','\xC6':'AElig','\uD835\uDCB7':'bscr','\uD835\uDD53':'bopf','\uD835\uDD1F':'bfr','\uD835\uDD39':'Bopf','\u212C':'Bscr','\uD835\uDD05':'Bfr','\uD835\uDD20':'cfr','\uD835\uDCB8':'cscr','\uD835\uDD54':'copf','\u212D':'Cfr','\uD835\uDC9E':'Cscr','\u2102':'Copf','\u0107':'cacute','\u0106':'Cacute','\u0109':'ccirc','\u0108':'Ccirc','\u010D':'ccaron','\u010C':'Ccaron','\u010B':'cdot','\u010A':'Cdot','\xE7':'ccedil','\xC7':'Ccedil','\u2105':'incare','\uD835\uDD21':'dfr','\u2146':'dd','\uD835\uDD55':'dopf','\uD835\uDCB9':'dscr','\uD835\uDC9F':'Dscr','\uD835\uDD07':'Dfr','\u2145':'DD','\uD835\uDD3B':'Dopf','\u010F':'dcaron','\u010E':'Dcaron','\u0111':'dstrok','\u0110':'Dstrok','\xF0':'eth','\xD0':'ETH','\u2147':'ee','\u212F':'escr','\uD835\uDD22':'efr','\uD835\uDD56':'eopf','\u2130':'Escr','\uD835\uDD08':'Efr','\uD835\uDD3C':'Eopf','\xE9':'eacute','\xC9':'Eacute','\xE8':'egrave','\xC8':'Egrave','\xEA':'ecirc','\xCA':'Ecirc','\u011B':'ecaron','\u011A':'Ecaron','\xEB':'euml','\xCB':'Euml','\u0117':'edot','\u0116':'Edot','\u0119':'eogon','\u0118':'Eogon','\u0113':'emacr','\u0112':'Emacr','\uD835\uDD23':'ffr','\uD835\uDD57':'fopf','\uD835\uDCBB':'fscr','\uD835\uDD09':'Ffr','\uD835\uDD3D':'Fopf','\u2131':'Fscr','\uFB00':'fflig','\uFB03':'ffilig','\uFB04':'ffllig','\uFB01':'filig','fj':'fjlig','\uFB02':'fllig','\u0192':'fnof','\u210A':'gscr','\uD835\uDD58':'gopf','\uD835\uDD24':'gfr','\uD835\uDCA2':'Gscr','\uD835\uDD3E':'Gopf','\uD835\uDD0A':'Gfr','\u01F5':'gacute','\u011F':'gbreve','\u011E':'Gbreve','\u011D':'gcirc','\u011C':'Gcirc','\u0121':'gdot','\u0120':'Gdot','\u0122':'Gcedil','\uD835\uDD25':'hfr','\u210E':'planckh','\uD835\uDCBD':'hscr','\uD835\uDD59':'hopf','\u210B':'Hscr','\u210C':'Hfr','\u210D':'Hopf','\u0125':'hcirc','\u0124':'Hcirc','\u210F':'hbar','\u0127':'hstrok','\u0126':'Hstrok','\uD835\uDD5A':'iopf','\uD835\uDD26':'ifr','\uD835\uDCBE':'iscr','\u2148':'ii','\uD835\uDD40':'Iopf','\u2110':'Iscr','\u2111':'Im','\xED':'iacute','\xCD':'Iacute','\xEC':'igrave','\xCC':'Igrave','\xEE':'icirc','\xCE':'Icirc','\xEF':'iuml','\xCF':'Iuml','\u0129':'itilde','\u0128':'Itilde','\u0130':'Idot','\u012F':'iogon','\u012E':'Iogon','\u012B':'imacr','\u012A':'Imacr','\u0133':'ijlig','\u0132':'IJlig','\u0131':'imath','\uD835\uDCBF':'jscr','\uD835\uDD5B':'jopf','\uD835\uDD27':'jfr','\uD835\uDCA5':'Jscr','\uD835\uDD0D':'Jfr','\uD835\uDD41':'Jopf','\u0135':'jcirc','\u0134':'Jcirc','\u0237':'jmath','\uD835\uDD5C':'kopf','\uD835\uDCC0':'kscr','\uD835\uDD28':'kfr','\uD835\uDCA6':'Kscr','\uD835\uDD42':'Kopf','\uD835\uDD0E':'Kfr','\u0137':'kcedil','\u0136':'Kcedil','\uD835\uDD29':'lfr','\uD835\uDCC1':'lscr','\u2113':'ell','\uD835\uDD5D':'lopf','\u2112':'Lscr','\uD835\uDD0F':'Lfr','\uD835\uDD43':'Lopf','\u013A':'lacute','\u0139':'Lacute','\u013E':'lcaron','\u013D':'Lcaron','\u013C':'lcedil','\u013B':'Lcedil','\u0142':'lstrok','\u0141':'Lstrok','\u0140':'lmidot','\u013F':'Lmidot','\uD835\uDD2A':'mfr','\uD835\uDD5E':'mopf','\uD835\uDCC2':'mscr','\uD835\uDD10':'Mfr','\uD835\uDD44':'Mopf','\u2133':'Mscr','\uD835\uDD2B':'nfr','\uD835\uDD5F':'nopf','\uD835\uDCC3':'nscr','\u2115':'Nopf','\uD835\uDCA9':'Nscr','\uD835\uDD11':'Nfr','\u0144':'nacute','\u0143':'Nacute','\u0148':'ncaron','\u0147':'Ncaron','\xF1':'ntilde','\xD1':'Ntilde','\u0146':'ncedil','\u0145':'Ncedil','\u2116':'numero','\u014B':'eng','\u014A':'ENG','\uD835\uDD60':'oopf','\uD835\uDD2C':'ofr','\u2134':'oscr','\uD835\uDCAA':'Oscr','\uD835\uDD12':'Ofr','\uD835\uDD46':'Oopf','\xBA':'ordm','\xF3':'oacute','\xD3':'Oacute','\xF2':'ograve','\xD2':'Ograve','\xF4':'ocirc','\xD4':'Ocirc','\xF6':'ouml','\xD6':'Ouml','\u0151':'odblac','\u0150':'Odblac','\xF5':'otilde','\xD5':'Otilde','\xF8':'oslash','\xD8':'Oslash','\u014D':'omacr','\u014C':'Omacr','\u0153':'oelig','\u0152':'OElig','\uD835\uDD2D':'pfr','\uD835\uDCC5':'pscr','\uD835\uDD61':'popf','\u2119':'Popf','\uD835\uDD13':'Pfr','\uD835\uDCAB':'Pscr','\uD835\uDD62':'qopf','\uD835\uDD2E':'qfr','\uD835\uDCC6':'qscr','\uD835\uDCAC':'Qscr','\uD835\uDD14':'Qfr','\u211A':'Qopf','\u0138':'kgreen','\uD835\uDD2F':'rfr','\uD835\uDD63':'ropf','\uD835\uDCC7':'rscr','\u211B':'Rscr','\u211C':'Re','\u211D':'Ropf','\u0155':'racute','\u0154':'Racute','\u0159':'rcaron','\u0158':'Rcaron','\u0157':'rcedil','\u0156':'Rcedil','\uD835\uDD64':'sopf','\uD835\uDCC8':'sscr','\uD835\uDD30':'sfr','\uD835\uDD4A':'Sopf','\uD835\uDD16':'Sfr','\uD835\uDCAE':'Sscr','\u24C8':'oS','\u015B':'sacute','\u015A':'Sacute','\u015D':'scirc','\u015C':'Scirc','\u0161':'scaron','\u0160':'Scaron','\u015F':'scedil','\u015E':'Scedil','\xDF':'szlig','\uD835\uDD31':'tfr','\uD835\uDCC9':'tscr','\uD835\uDD65':'topf','\uD835\uDCAF':'Tscr','\uD835\uDD17':'Tfr','\uD835\uDD4B':'Topf','\u0165':'tcaron','\u0164':'Tcaron','\u0163':'tcedil','\u0162':'Tcedil','\u2122':'trade','\u0167':'tstrok','\u0166':'Tstrok','\uD835\uDCCA':'uscr','\uD835\uDD66':'uopf','\uD835\uDD32':'ufr','\uD835\uDD4C':'Uopf','\uD835\uDD18':'Ufr','\uD835\uDCB0':'Uscr','\xFA':'uacute','\xDA':'Uacute','\xF9':'ugrave','\xD9':'Ugrave','\u016D':'ubreve','\u016C':'Ubreve','\xFB':'ucirc','\xDB':'Ucirc','\u016F':'uring','\u016E':'Uring','\xFC':'uuml','\xDC':'Uuml','\u0171':'udblac','\u0170':'Udblac','\u0169':'utilde','\u0168':'Utilde','\u0173':'uogon','\u0172':'Uogon','\u016B':'umacr','\u016A':'Umacr','\uD835\uDD33':'vfr','\uD835\uDD67':'vopf','\uD835\uDCCB':'vscr','\uD835\uDD19':'Vfr','\uD835\uDD4D':'Vopf','\uD835\uDCB1':'Vscr','\uD835\uDD68':'wopf','\uD835\uDCCC':'wscr','\uD835\uDD34':'wfr','\uD835\uDCB2':'Wscr','\uD835\uDD4E':'Wopf','\uD835\uDD1A':'Wfr','\u0175':'wcirc','\u0174':'Wcirc','\uD835\uDD35':'xfr','\uD835\uDCCD':'xscr','\uD835\uDD69':'xopf','\uD835\uDD4F':'Xopf','\uD835\uDD1B':'Xfr','\uD835\uDCB3':'Xscr','\uD835\uDD36':'yfr','\uD835\uDCCE':'yscr','\uD835\uDD6A':'yopf','\uD835\uDCB4':'Yscr','\uD835\uDD1C':'Yfr','\uD835\uDD50':'Yopf','\xFD':'yacute','\xDD':'Yacute','\u0177':'ycirc','\u0176':'Ycirc','\xFF':'yuml','\u0178':'Yuml','\uD835\uDCCF':'zscr','\uD835\uDD37':'zfr','\uD835\uDD6B':'zopf','\u2128':'Zfr','\u2124':'Zopf','\uD835\uDCB5':'Zscr','\u017A':'zacute','\u0179':'Zacute','\u017E':'zcaron','\u017D':'Zcaron','\u017C':'zdot','\u017B':'Zdot','\u01B5':'imped','\xFE':'thorn','\xDE':'THORN','\u0149':'napos','\u03B1':'alpha','\u0391':'Alpha','\u03B2':'beta','\u0392':'Beta','\u03B3':'gamma','\u0393':'Gamma','\u03B4':'delta','\u0394':'Delta','\u03B5':'epsi','\u03F5':'epsiv','\u0395':'Epsilon','\u03DD':'gammad','\u03DC':'Gammad','\u03B6':'zeta','\u0396':'Zeta','\u03B7':'eta','\u0397':'Eta','\u03B8':'theta','\u03D1':'thetav','\u0398':'Theta','\u03B9':'iota','\u0399':'Iota','\u03BA':'kappa','\u03F0':'kappav','\u039A':'Kappa','\u03BB':'lambda','\u039B':'Lambda','\u03BC':'mu','\xB5':'micro','\u039C':'Mu','\u03BD':'nu','\u039D':'Nu','\u03BE':'xi','\u039E':'Xi','\u03BF':'omicron','\u039F':'Omicron','\u03C0':'pi','\u03D6':'piv','\u03A0':'Pi','\u03C1':'rho','\u03F1':'rhov','\u03A1':'Rho','\u03C3':'sigma','\u03A3':'Sigma','\u03C2':'sigmaf','\u03C4':'tau','\u03A4':'Tau','\u03C5':'upsi','\u03A5':'Upsilon','\u03D2':'Upsi','\u03C6':'phi','\u03D5':'phiv','\u03A6':'Phi','\u03C7':'chi','\u03A7':'Chi','\u03C8':'psi','\u03A8':'Psi','\u03C9':'omega','\u03A9':'ohm','\u0430':'acy','\u0410':'Acy','\u0431':'bcy','\u0411':'Bcy','\u0432':'vcy','\u0412':'Vcy','\u0433':'gcy','\u0413':'Gcy','\u0453':'gjcy','\u0403':'GJcy','\u0434':'dcy','\u0414':'Dcy','\u0452':'djcy','\u0402':'DJcy','\u0435':'iecy','\u0415':'IEcy','\u0451':'iocy','\u0401':'IOcy','\u0454':'jukcy','\u0404':'Jukcy','\u0436':'zhcy','\u0416':'ZHcy','\u0437':'zcy','\u0417':'Zcy','\u0455':'dscy','\u0405':'DScy','\u0438':'icy','\u0418':'Icy','\u0456':'iukcy','\u0406':'Iukcy','\u0457':'yicy','\u0407':'YIcy','\u0439':'jcy','\u0419':'Jcy','\u0458':'jsercy','\u0408':'Jsercy','\u043A':'kcy','\u041A':'Kcy','\u045C':'kjcy','\u040C':'KJcy','\u043B':'lcy','\u041B':'Lcy','\u0459':'ljcy','\u0409':'LJcy','\u043C':'mcy','\u041C':'Mcy','\u043D':'ncy','\u041D':'Ncy','\u045A':'njcy','\u040A':'NJcy','\u043E':'ocy','\u041E':'Ocy','\u043F':'pcy','\u041F':'Pcy','\u0440':'rcy','\u0420':'Rcy','\u0441':'scy','\u0421':'Scy','\u0442':'tcy','\u0422':'Tcy','\u045B':'tshcy','\u040B':'TSHcy','\u0443':'ucy','\u0423':'Ucy','\u045E':'ubrcy','\u040E':'Ubrcy','\u0444':'fcy','\u0424':'Fcy','\u0445':'khcy','\u0425':'KHcy','\u0446':'tscy','\u0426':'TScy','\u0447':'chcy','\u0427':'CHcy','\u045F':'dzcy','\u040F':'DZcy','\u0448':'shcy','\u0428':'SHcy','\u0449':'shchcy','\u0429':'SHCHcy','\u044A':'hardcy','\u042A':'HARDcy','\u044B':'ycy','\u042B':'Ycy','\u044C':'softcy','\u042C':'SOFTcy','\u044D':'ecy','\u042D':'Ecy','\u044E':'yucy','\u042E':'YUcy','\u044F':'yacy','\u042F':'YAcy','\u2135':'aleph','\u2136':'beth','\u2137':'gimel','\u2138':'daleth'}; + + var regexEscape = /["&'<>`]/g; + var escapeMap = { + '"': '"', + '&': '&', + '\'': ''', + '<': '<', + // See https://mathiasbynens.be/notes/ambiguous-ampersands: in HTML, the + // following is not strictly necessary unless it’s part of a tag or an + // unquoted attribute value. We’re only escaping it to support those + // situations, and for XML support. + '>': '>', + // In Internet Explorer ≤ 8, the backtick character can be used + // to break out of (un)quoted attribute values or HTML comments. + // See http://html5sec.org/#102, http://html5sec.org/#108, and + // http://html5sec.org/#133. + '`': '`' + }; + + var regexInvalidEntity = /&#(?:[xX][^a-fA-F0-9]|[^0-9xX])/; + var regexInvalidRawCodePoint = /[\0-\x08\x0B\x0E-\x1F\x7F-\x9F\uFDD0-\uFDEF\uFFFE\uFFFF]|[\uD83F\uD87F\uD8BF\uD8FF\uD93F\uD97F\uD9BF\uD9FF\uDA3F\uDA7F\uDABF\uDAFF\uDB3F\uDB7F\uDBBF\uDBFF][\uDFFE\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/; + var regexDecode = /&#([0-9]+)(;?)|&#[xX]([a-fA-F0-9]+)(;?)|&([0-9a-zA-Z]+);|&(Aacute|Agrave|Atilde|Ccedil|Eacute|Egrave|Iacute|Igrave|Ntilde|Oacute|Ograve|Oslash|Otilde|Uacute|Ugrave|Yacute|aacute|agrave|atilde|brvbar|ccedil|curren|divide|eacute|egrave|frac12|frac14|frac34|iacute|igrave|iquest|middot|ntilde|oacute|ograve|oslash|otilde|plusmn|uacute|ugrave|yacute|AElig|Acirc|Aring|Ecirc|Icirc|Ocirc|THORN|Ucirc|acirc|acute|aelig|aring|cedil|ecirc|icirc|iexcl|laquo|micro|ocirc|pound|raquo|szlig|thorn|times|ucirc|Auml|COPY|Euml|Iuml|Ouml|QUOT|Uuml|auml|cent|copy|euml|iuml|macr|nbsp|ordf|ordm|ouml|para|quot|sect|sup1|sup2|sup3|uuml|yuml|AMP|ETH|REG|amp|deg|eth|not|reg|shy|uml|yen|GT|LT|gt|lt)([=a-zA-Z0-9])?/g; + var decodeMap = {'aacute':'\xE1','Aacute':'\xC1','abreve':'\u0103','Abreve':'\u0102','ac':'\u223E','acd':'\u223F','acE':'\u223E\u0333','acirc':'\xE2','Acirc':'\xC2','acute':'\xB4','acy':'\u0430','Acy':'\u0410','aelig':'\xE6','AElig':'\xC6','af':'\u2061','afr':'\uD835\uDD1E','Afr':'\uD835\uDD04','agrave':'\xE0','Agrave':'\xC0','alefsym':'\u2135','aleph':'\u2135','alpha':'\u03B1','Alpha':'\u0391','amacr':'\u0101','Amacr':'\u0100','amalg':'\u2A3F','amp':'&','AMP':'&','and':'\u2227','And':'\u2A53','andand':'\u2A55','andd':'\u2A5C','andslope':'\u2A58','andv':'\u2A5A','ang':'\u2220','ange':'\u29A4','angle':'\u2220','angmsd':'\u2221','angmsdaa':'\u29A8','angmsdab':'\u29A9','angmsdac':'\u29AA','angmsdad':'\u29AB','angmsdae':'\u29AC','angmsdaf':'\u29AD','angmsdag':'\u29AE','angmsdah':'\u29AF','angrt':'\u221F','angrtvb':'\u22BE','angrtvbd':'\u299D','angsph':'\u2222','angst':'\xC5','angzarr':'\u237C','aogon':'\u0105','Aogon':'\u0104','aopf':'\uD835\uDD52','Aopf':'\uD835\uDD38','ap':'\u2248','apacir':'\u2A6F','ape':'\u224A','apE':'\u2A70','apid':'\u224B','apos':'\'','ApplyFunction':'\u2061','approx':'\u2248','approxeq':'\u224A','aring':'\xE5','Aring':'\xC5','ascr':'\uD835\uDCB6','Ascr':'\uD835\uDC9C','Assign':'\u2254','ast':'*','asymp':'\u2248','asympeq':'\u224D','atilde':'\xE3','Atilde':'\xC3','auml':'\xE4','Auml':'\xC4','awconint':'\u2233','awint':'\u2A11','backcong':'\u224C','backepsilon':'\u03F6','backprime':'\u2035','backsim':'\u223D','backsimeq':'\u22CD','Backslash':'\u2216','Barv':'\u2AE7','barvee':'\u22BD','barwed':'\u2305','Barwed':'\u2306','barwedge':'\u2305','bbrk':'\u23B5','bbrktbrk':'\u23B6','bcong':'\u224C','bcy':'\u0431','Bcy':'\u0411','bdquo':'\u201E','becaus':'\u2235','because':'\u2235','Because':'\u2235','bemptyv':'\u29B0','bepsi':'\u03F6','bernou':'\u212C','Bernoullis':'\u212C','beta':'\u03B2','Beta':'\u0392','beth':'\u2136','between':'\u226C','bfr':'\uD835\uDD1F','Bfr':'\uD835\uDD05','bigcap':'\u22C2','bigcirc':'\u25EF','bigcup':'\u22C3','bigodot':'\u2A00','bigoplus':'\u2A01','bigotimes':'\u2A02','bigsqcup':'\u2A06','bigstar':'\u2605','bigtriangledown':'\u25BD','bigtriangleup':'\u25B3','biguplus':'\u2A04','bigvee':'\u22C1','bigwedge':'\u22C0','bkarow':'\u290D','blacklozenge':'\u29EB','blacksquare':'\u25AA','blacktriangle':'\u25B4','blacktriangledown':'\u25BE','blacktriangleleft':'\u25C2','blacktriangleright':'\u25B8','blank':'\u2423','blk12':'\u2592','blk14':'\u2591','blk34':'\u2593','block':'\u2588','bne':'=\u20E5','bnequiv':'\u2261\u20E5','bnot':'\u2310','bNot':'\u2AED','bopf':'\uD835\uDD53','Bopf':'\uD835\uDD39','bot':'\u22A5','bottom':'\u22A5','bowtie':'\u22C8','boxbox':'\u29C9','boxdl':'\u2510','boxdL':'\u2555','boxDl':'\u2556','boxDL':'\u2557','boxdr':'\u250C','boxdR':'\u2552','boxDr':'\u2553','boxDR':'\u2554','boxh':'\u2500','boxH':'\u2550','boxhd':'\u252C','boxhD':'\u2565','boxHd':'\u2564','boxHD':'\u2566','boxhu':'\u2534','boxhU':'\u2568','boxHu':'\u2567','boxHU':'\u2569','boxminus':'\u229F','boxplus':'\u229E','boxtimes':'\u22A0','boxul':'\u2518','boxuL':'\u255B','boxUl':'\u255C','boxUL':'\u255D','boxur':'\u2514','boxuR':'\u2558','boxUr':'\u2559','boxUR':'\u255A','boxv':'\u2502','boxV':'\u2551','boxvh':'\u253C','boxvH':'\u256A','boxVh':'\u256B','boxVH':'\u256C','boxvl':'\u2524','boxvL':'\u2561','boxVl':'\u2562','boxVL':'\u2563','boxvr':'\u251C','boxvR':'\u255E','boxVr':'\u255F','boxVR':'\u2560','bprime':'\u2035','breve':'\u02D8','Breve':'\u02D8','brvbar':'\xA6','bscr':'\uD835\uDCB7','Bscr':'\u212C','bsemi':'\u204F','bsim':'\u223D','bsime':'\u22CD','bsol':'\\','bsolb':'\u29C5','bsolhsub':'\u27C8','bull':'\u2022','bullet':'\u2022','bump':'\u224E','bumpe':'\u224F','bumpE':'\u2AAE','bumpeq':'\u224F','Bumpeq':'\u224E','cacute':'\u0107','Cacute':'\u0106','cap':'\u2229','Cap':'\u22D2','capand':'\u2A44','capbrcup':'\u2A49','capcap':'\u2A4B','capcup':'\u2A47','capdot':'\u2A40','CapitalDifferentialD':'\u2145','caps':'\u2229\uFE00','caret':'\u2041','caron':'\u02C7','Cayleys':'\u212D','ccaps':'\u2A4D','ccaron':'\u010D','Ccaron':'\u010C','ccedil':'\xE7','Ccedil':'\xC7','ccirc':'\u0109','Ccirc':'\u0108','Cconint':'\u2230','ccups':'\u2A4C','ccupssm':'\u2A50','cdot':'\u010B','Cdot':'\u010A','cedil':'\xB8','Cedilla':'\xB8','cemptyv':'\u29B2','cent':'\xA2','centerdot':'\xB7','CenterDot':'\xB7','cfr':'\uD835\uDD20','Cfr':'\u212D','chcy':'\u0447','CHcy':'\u0427','check':'\u2713','checkmark':'\u2713','chi':'\u03C7','Chi':'\u03A7','cir':'\u25CB','circ':'\u02C6','circeq':'\u2257','circlearrowleft':'\u21BA','circlearrowright':'\u21BB','circledast':'\u229B','circledcirc':'\u229A','circleddash':'\u229D','CircleDot':'\u2299','circledR':'\xAE','circledS':'\u24C8','CircleMinus':'\u2296','CirclePlus':'\u2295','CircleTimes':'\u2297','cire':'\u2257','cirE':'\u29C3','cirfnint':'\u2A10','cirmid':'\u2AEF','cirscir':'\u29C2','ClockwiseContourIntegral':'\u2232','CloseCurlyDoubleQuote':'\u201D','CloseCurlyQuote':'\u2019','clubs':'\u2663','clubsuit':'\u2663','colon':':','Colon':'\u2237','colone':'\u2254','Colone':'\u2A74','coloneq':'\u2254','comma':',','commat':'@','comp':'\u2201','compfn':'\u2218','complement':'\u2201','complexes':'\u2102','cong':'\u2245','congdot':'\u2A6D','Congruent':'\u2261','conint':'\u222E','Conint':'\u222F','ContourIntegral':'\u222E','copf':'\uD835\uDD54','Copf':'\u2102','coprod':'\u2210','Coproduct':'\u2210','copy':'\xA9','COPY':'\xA9','copysr':'\u2117','CounterClockwiseContourIntegral':'\u2233','crarr':'\u21B5','cross':'\u2717','Cross':'\u2A2F','cscr':'\uD835\uDCB8','Cscr':'\uD835\uDC9E','csub':'\u2ACF','csube':'\u2AD1','csup':'\u2AD0','csupe':'\u2AD2','ctdot':'\u22EF','cudarrl':'\u2938','cudarrr':'\u2935','cuepr':'\u22DE','cuesc':'\u22DF','cularr':'\u21B6','cularrp':'\u293D','cup':'\u222A','Cup':'\u22D3','cupbrcap':'\u2A48','cupcap':'\u2A46','CupCap':'\u224D','cupcup':'\u2A4A','cupdot':'\u228D','cupor':'\u2A45','cups':'\u222A\uFE00','curarr':'\u21B7','curarrm':'\u293C','curlyeqprec':'\u22DE','curlyeqsucc':'\u22DF','curlyvee':'\u22CE','curlywedge':'\u22CF','curren':'\xA4','curvearrowleft':'\u21B6','curvearrowright':'\u21B7','cuvee':'\u22CE','cuwed':'\u22CF','cwconint':'\u2232','cwint':'\u2231','cylcty':'\u232D','dagger':'\u2020','Dagger':'\u2021','daleth':'\u2138','darr':'\u2193','dArr':'\u21D3','Darr':'\u21A1','dash':'\u2010','dashv':'\u22A3','Dashv':'\u2AE4','dbkarow':'\u290F','dblac':'\u02DD','dcaron':'\u010F','Dcaron':'\u010E','dcy':'\u0434','Dcy':'\u0414','dd':'\u2146','DD':'\u2145','ddagger':'\u2021','ddarr':'\u21CA','DDotrahd':'\u2911','ddotseq':'\u2A77','deg':'\xB0','Del':'\u2207','delta':'\u03B4','Delta':'\u0394','demptyv':'\u29B1','dfisht':'\u297F','dfr':'\uD835\uDD21','Dfr':'\uD835\uDD07','dHar':'\u2965','dharl':'\u21C3','dharr':'\u21C2','DiacriticalAcute':'\xB4','DiacriticalDot':'\u02D9','DiacriticalDoubleAcute':'\u02DD','DiacriticalGrave':'`','DiacriticalTilde':'\u02DC','diam':'\u22C4','diamond':'\u22C4','Diamond':'\u22C4','diamondsuit':'\u2666','diams':'\u2666','die':'\xA8','DifferentialD':'\u2146','digamma':'\u03DD','disin':'\u22F2','div':'\xF7','divide':'\xF7','divideontimes':'\u22C7','divonx':'\u22C7','djcy':'\u0452','DJcy':'\u0402','dlcorn':'\u231E','dlcrop':'\u230D','dollar':'$','dopf':'\uD835\uDD55','Dopf':'\uD835\uDD3B','dot':'\u02D9','Dot':'\xA8','DotDot':'\u20DC','doteq':'\u2250','doteqdot':'\u2251','DotEqual':'\u2250','dotminus':'\u2238','dotplus':'\u2214','dotsquare':'\u22A1','doublebarwedge':'\u2306','DoubleContourIntegral':'\u222F','DoubleDot':'\xA8','DoubleDownArrow':'\u21D3','DoubleLeftArrow':'\u21D0','DoubleLeftRightArrow':'\u21D4','DoubleLeftTee':'\u2AE4','DoubleLongLeftArrow':'\u27F8','DoubleLongLeftRightArrow':'\u27FA','DoubleLongRightArrow':'\u27F9','DoubleRightArrow':'\u21D2','DoubleRightTee':'\u22A8','DoubleUpArrow':'\u21D1','DoubleUpDownArrow':'\u21D5','DoubleVerticalBar':'\u2225','downarrow':'\u2193','Downarrow':'\u21D3','DownArrow':'\u2193','DownArrowBar':'\u2913','DownArrowUpArrow':'\u21F5','DownBreve':'\u0311','downdownarrows':'\u21CA','downharpoonleft':'\u21C3','downharpoonright':'\u21C2','DownLeftRightVector':'\u2950','DownLeftTeeVector':'\u295E','DownLeftVector':'\u21BD','DownLeftVectorBar':'\u2956','DownRightTeeVector':'\u295F','DownRightVector':'\u21C1','DownRightVectorBar':'\u2957','DownTee':'\u22A4','DownTeeArrow':'\u21A7','drbkarow':'\u2910','drcorn':'\u231F','drcrop':'\u230C','dscr':'\uD835\uDCB9','Dscr':'\uD835\uDC9F','dscy':'\u0455','DScy':'\u0405','dsol':'\u29F6','dstrok':'\u0111','Dstrok':'\u0110','dtdot':'\u22F1','dtri':'\u25BF','dtrif':'\u25BE','duarr':'\u21F5','duhar':'\u296F','dwangle':'\u29A6','dzcy':'\u045F','DZcy':'\u040F','dzigrarr':'\u27FF','eacute':'\xE9','Eacute':'\xC9','easter':'\u2A6E','ecaron':'\u011B','Ecaron':'\u011A','ecir':'\u2256','ecirc':'\xEA','Ecirc':'\xCA','ecolon':'\u2255','ecy':'\u044D','Ecy':'\u042D','eDDot':'\u2A77','edot':'\u0117','eDot':'\u2251','Edot':'\u0116','ee':'\u2147','efDot':'\u2252','efr':'\uD835\uDD22','Efr':'\uD835\uDD08','eg':'\u2A9A','egrave':'\xE8','Egrave':'\xC8','egs':'\u2A96','egsdot':'\u2A98','el':'\u2A99','Element':'\u2208','elinters':'\u23E7','ell':'\u2113','els':'\u2A95','elsdot':'\u2A97','emacr':'\u0113','Emacr':'\u0112','empty':'\u2205','emptyset':'\u2205','EmptySmallSquare':'\u25FB','emptyv':'\u2205','EmptyVerySmallSquare':'\u25AB','emsp':'\u2003','emsp13':'\u2004','emsp14':'\u2005','eng':'\u014B','ENG':'\u014A','ensp':'\u2002','eogon':'\u0119','Eogon':'\u0118','eopf':'\uD835\uDD56','Eopf':'\uD835\uDD3C','epar':'\u22D5','eparsl':'\u29E3','eplus':'\u2A71','epsi':'\u03B5','epsilon':'\u03B5','Epsilon':'\u0395','epsiv':'\u03F5','eqcirc':'\u2256','eqcolon':'\u2255','eqsim':'\u2242','eqslantgtr':'\u2A96','eqslantless':'\u2A95','Equal':'\u2A75','equals':'=','EqualTilde':'\u2242','equest':'\u225F','Equilibrium':'\u21CC','equiv':'\u2261','equivDD':'\u2A78','eqvparsl':'\u29E5','erarr':'\u2971','erDot':'\u2253','escr':'\u212F','Escr':'\u2130','esdot':'\u2250','esim':'\u2242','Esim':'\u2A73','eta':'\u03B7','Eta':'\u0397','eth':'\xF0','ETH':'\xD0','euml':'\xEB','Euml':'\xCB','euro':'\u20AC','excl':'!','exist':'\u2203','Exists':'\u2203','expectation':'\u2130','exponentiale':'\u2147','ExponentialE':'\u2147','fallingdotseq':'\u2252','fcy':'\u0444','Fcy':'\u0424','female':'\u2640','ffilig':'\uFB03','fflig':'\uFB00','ffllig':'\uFB04','ffr':'\uD835\uDD23','Ffr':'\uD835\uDD09','filig':'\uFB01','FilledSmallSquare':'\u25FC','FilledVerySmallSquare':'\u25AA','fjlig':'fj','flat':'\u266D','fllig':'\uFB02','fltns':'\u25B1','fnof':'\u0192','fopf':'\uD835\uDD57','Fopf':'\uD835\uDD3D','forall':'\u2200','ForAll':'\u2200','fork':'\u22D4','forkv':'\u2AD9','Fouriertrf':'\u2131','fpartint':'\u2A0D','frac12':'\xBD','frac13':'\u2153','frac14':'\xBC','frac15':'\u2155','frac16':'\u2159','frac18':'\u215B','frac23':'\u2154','frac25':'\u2156','frac34':'\xBE','frac35':'\u2157','frac38':'\u215C','frac45':'\u2158','frac56':'\u215A','frac58':'\u215D','frac78':'\u215E','frasl':'\u2044','frown':'\u2322','fscr':'\uD835\uDCBB','Fscr':'\u2131','gacute':'\u01F5','gamma':'\u03B3','Gamma':'\u0393','gammad':'\u03DD','Gammad':'\u03DC','gap':'\u2A86','gbreve':'\u011F','Gbreve':'\u011E','Gcedil':'\u0122','gcirc':'\u011D','Gcirc':'\u011C','gcy':'\u0433','Gcy':'\u0413','gdot':'\u0121','Gdot':'\u0120','ge':'\u2265','gE':'\u2267','gel':'\u22DB','gEl':'\u2A8C','geq':'\u2265','geqq':'\u2267','geqslant':'\u2A7E','ges':'\u2A7E','gescc':'\u2AA9','gesdot':'\u2A80','gesdoto':'\u2A82','gesdotol':'\u2A84','gesl':'\u22DB\uFE00','gesles':'\u2A94','gfr':'\uD835\uDD24','Gfr':'\uD835\uDD0A','gg':'\u226B','Gg':'\u22D9','ggg':'\u22D9','gimel':'\u2137','gjcy':'\u0453','GJcy':'\u0403','gl':'\u2277','gla':'\u2AA5','glE':'\u2A92','glj':'\u2AA4','gnap':'\u2A8A','gnapprox':'\u2A8A','gne':'\u2A88','gnE':'\u2269','gneq':'\u2A88','gneqq':'\u2269','gnsim':'\u22E7','gopf':'\uD835\uDD58','Gopf':'\uD835\uDD3E','grave':'`','GreaterEqual':'\u2265','GreaterEqualLess':'\u22DB','GreaterFullEqual':'\u2267','GreaterGreater':'\u2AA2','GreaterLess':'\u2277','GreaterSlantEqual':'\u2A7E','GreaterTilde':'\u2273','gscr':'\u210A','Gscr':'\uD835\uDCA2','gsim':'\u2273','gsime':'\u2A8E','gsiml':'\u2A90','gt':'>','Gt':'\u226B','GT':'>','gtcc':'\u2AA7','gtcir':'\u2A7A','gtdot':'\u22D7','gtlPar':'\u2995','gtquest':'\u2A7C','gtrapprox':'\u2A86','gtrarr':'\u2978','gtrdot':'\u22D7','gtreqless':'\u22DB','gtreqqless':'\u2A8C','gtrless':'\u2277','gtrsim':'\u2273','gvertneqq':'\u2269\uFE00','gvnE':'\u2269\uFE00','Hacek':'\u02C7','hairsp':'\u200A','half':'\xBD','hamilt':'\u210B','hardcy':'\u044A','HARDcy':'\u042A','harr':'\u2194','hArr':'\u21D4','harrcir':'\u2948','harrw':'\u21AD','Hat':'^','hbar':'\u210F','hcirc':'\u0125','Hcirc':'\u0124','hearts':'\u2665','heartsuit':'\u2665','hellip':'\u2026','hercon':'\u22B9','hfr':'\uD835\uDD25','Hfr':'\u210C','HilbertSpace':'\u210B','hksearow':'\u2925','hkswarow':'\u2926','hoarr':'\u21FF','homtht':'\u223B','hookleftarrow':'\u21A9','hookrightarrow':'\u21AA','hopf':'\uD835\uDD59','Hopf':'\u210D','horbar':'\u2015','HorizontalLine':'\u2500','hscr':'\uD835\uDCBD','Hscr':'\u210B','hslash':'\u210F','hstrok':'\u0127','Hstrok':'\u0126','HumpDownHump':'\u224E','HumpEqual':'\u224F','hybull':'\u2043','hyphen':'\u2010','iacute':'\xED','Iacute':'\xCD','ic':'\u2063','icirc':'\xEE','Icirc':'\xCE','icy':'\u0438','Icy':'\u0418','Idot':'\u0130','iecy':'\u0435','IEcy':'\u0415','iexcl':'\xA1','iff':'\u21D4','ifr':'\uD835\uDD26','Ifr':'\u2111','igrave':'\xEC','Igrave':'\xCC','ii':'\u2148','iiiint':'\u2A0C','iiint':'\u222D','iinfin':'\u29DC','iiota':'\u2129','ijlig':'\u0133','IJlig':'\u0132','Im':'\u2111','imacr':'\u012B','Imacr':'\u012A','image':'\u2111','ImaginaryI':'\u2148','imagline':'\u2110','imagpart':'\u2111','imath':'\u0131','imof':'\u22B7','imped':'\u01B5','Implies':'\u21D2','in':'\u2208','incare':'\u2105','infin':'\u221E','infintie':'\u29DD','inodot':'\u0131','int':'\u222B','Int':'\u222C','intcal':'\u22BA','integers':'\u2124','Integral':'\u222B','intercal':'\u22BA','Intersection':'\u22C2','intlarhk':'\u2A17','intprod':'\u2A3C','InvisibleComma':'\u2063','InvisibleTimes':'\u2062','iocy':'\u0451','IOcy':'\u0401','iogon':'\u012F','Iogon':'\u012E','iopf':'\uD835\uDD5A','Iopf':'\uD835\uDD40','iota':'\u03B9','Iota':'\u0399','iprod':'\u2A3C','iquest':'\xBF','iscr':'\uD835\uDCBE','Iscr':'\u2110','isin':'\u2208','isindot':'\u22F5','isinE':'\u22F9','isins':'\u22F4','isinsv':'\u22F3','isinv':'\u2208','it':'\u2062','itilde':'\u0129','Itilde':'\u0128','iukcy':'\u0456','Iukcy':'\u0406','iuml':'\xEF','Iuml':'\xCF','jcirc':'\u0135','Jcirc':'\u0134','jcy':'\u0439','Jcy':'\u0419','jfr':'\uD835\uDD27','Jfr':'\uD835\uDD0D','jmath':'\u0237','jopf':'\uD835\uDD5B','Jopf':'\uD835\uDD41','jscr':'\uD835\uDCBF','Jscr':'\uD835\uDCA5','jsercy':'\u0458','Jsercy':'\u0408','jukcy':'\u0454','Jukcy':'\u0404','kappa':'\u03BA','Kappa':'\u039A','kappav':'\u03F0','kcedil':'\u0137','Kcedil':'\u0136','kcy':'\u043A','Kcy':'\u041A','kfr':'\uD835\uDD28','Kfr':'\uD835\uDD0E','kgreen':'\u0138','khcy':'\u0445','KHcy':'\u0425','kjcy':'\u045C','KJcy':'\u040C','kopf':'\uD835\uDD5C','Kopf':'\uD835\uDD42','kscr':'\uD835\uDCC0','Kscr':'\uD835\uDCA6','lAarr':'\u21DA','lacute':'\u013A','Lacute':'\u0139','laemptyv':'\u29B4','lagran':'\u2112','lambda':'\u03BB','Lambda':'\u039B','lang':'\u27E8','Lang':'\u27EA','langd':'\u2991','langle':'\u27E8','lap':'\u2A85','Laplacetrf':'\u2112','laquo':'\xAB','larr':'\u2190','lArr':'\u21D0','Larr':'\u219E','larrb':'\u21E4','larrbfs':'\u291F','larrfs':'\u291D','larrhk':'\u21A9','larrlp':'\u21AB','larrpl':'\u2939','larrsim':'\u2973','larrtl':'\u21A2','lat':'\u2AAB','latail':'\u2919','lAtail':'\u291B','late':'\u2AAD','lates':'\u2AAD\uFE00','lbarr':'\u290C','lBarr':'\u290E','lbbrk':'\u2772','lbrace':'{','lbrack':'[','lbrke':'\u298B','lbrksld':'\u298F','lbrkslu':'\u298D','lcaron':'\u013E','Lcaron':'\u013D','lcedil':'\u013C','Lcedil':'\u013B','lceil':'\u2308','lcub':'{','lcy':'\u043B','Lcy':'\u041B','ldca':'\u2936','ldquo':'\u201C','ldquor':'\u201E','ldrdhar':'\u2967','ldrushar':'\u294B','ldsh':'\u21B2','le':'\u2264','lE':'\u2266','LeftAngleBracket':'\u27E8','leftarrow':'\u2190','Leftarrow':'\u21D0','LeftArrow':'\u2190','LeftArrowBar':'\u21E4','LeftArrowRightArrow':'\u21C6','leftarrowtail':'\u21A2','LeftCeiling':'\u2308','LeftDoubleBracket':'\u27E6','LeftDownTeeVector':'\u2961','LeftDownVector':'\u21C3','LeftDownVectorBar':'\u2959','LeftFloor':'\u230A','leftharpoondown':'\u21BD','leftharpoonup':'\u21BC','leftleftarrows':'\u21C7','leftrightarrow':'\u2194','Leftrightarrow':'\u21D4','LeftRightArrow':'\u2194','leftrightarrows':'\u21C6','leftrightharpoons':'\u21CB','leftrightsquigarrow':'\u21AD','LeftRightVector':'\u294E','LeftTee':'\u22A3','LeftTeeArrow':'\u21A4','LeftTeeVector':'\u295A','leftthreetimes':'\u22CB','LeftTriangle':'\u22B2','LeftTriangleBar':'\u29CF','LeftTriangleEqual':'\u22B4','LeftUpDownVector':'\u2951','LeftUpTeeVector':'\u2960','LeftUpVector':'\u21BF','LeftUpVectorBar':'\u2958','LeftVector':'\u21BC','LeftVectorBar':'\u2952','leg':'\u22DA','lEg':'\u2A8B','leq':'\u2264','leqq':'\u2266','leqslant':'\u2A7D','les':'\u2A7D','lescc':'\u2AA8','lesdot':'\u2A7F','lesdoto':'\u2A81','lesdotor':'\u2A83','lesg':'\u22DA\uFE00','lesges':'\u2A93','lessapprox':'\u2A85','lessdot':'\u22D6','lesseqgtr':'\u22DA','lesseqqgtr':'\u2A8B','LessEqualGreater':'\u22DA','LessFullEqual':'\u2266','LessGreater':'\u2276','lessgtr':'\u2276','LessLess':'\u2AA1','lesssim':'\u2272','LessSlantEqual':'\u2A7D','LessTilde':'\u2272','lfisht':'\u297C','lfloor':'\u230A','lfr':'\uD835\uDD29','Lfr':'\uD835\uDD0F','lg':'\u2276','lgE':'\u2A91','lHar':'\u2962','lhard':'\u21BD','lharu':'\u21BC','lharul':'\u296A','lhblk':'\u2584','ljcy':'\u0459','LJcy':'\u0409','ll':'\u226A','Ll':'\u22D8','llarr':'\u21C7','llcorner':'\u231E','Lleftarrow':'\u21DA','llhard':'\u296B','lltri':'\u25FA','lmidot':'\u0140','Lmidot':'\u013F','lmoust':'\u23B0','lmoustache':'\u23B0','lnap':'\u2A89','lnapprox':'\u2A89','lne':'\u2A87','lnE':'\u2268','lneq':'\u2A87','lneqq':'\u2268','lnsim':'\u22E6','loang':'\u27EC','loarr':'\u21FD','lobrk':'\u27E6','longleftarrow':'\u27F5','Longleftarrow':'\u27F8','LongLeftArrow':'\u27F5','longleftrightarrow':'\u27F7','Longleftrightarrow':'\u27FA','LongLeftRightArrow':'\u27F7','longmapsto':'\u27FC','longrightarrow':'\u27F6','Longrightarrow':'\u27F9','LongRightArrow':'\u27F6','looparrowleft':'\u21AB','looparrowright':'\u21AC','lopar':'\u2985','lopf':'\uD835\uDD5D','Lopf':'\uD835\uDD43','loplus':'\u2A2D','lotimes':'\u2A34','lowast':'\u2217','lowbar':'_','LowerLeftArrow':'\u2199','LowerRightArrow':'\u2198','loz':'\u25CA','lozenge':'\u25CA','lozf':'\u29EB','lpar':'(','lparlt':'\u2993','lrarr':'\u21C6','lrcorner':'\u231F','lrhar':'\u21CB','lrhard':'\u296D','lrm':'\u200E','lrtri':'\u22BF','lsaquo':'\u2039','lscr':'\uD835\uDCC1','Lscr':'\u2112','lsh':'\u21B0','Lsh':'\u21B0','lsim':'\u2272','lsime':'\u2A8D','lsimg':'\u2A8F','lsqb':'[','lsquo':'\u2018','lsquor':'\u201A','lstrok':'\u0142','Lstrok':'\u0141','lt':'<','Lt':'\u226A','LT':'<','ltcc':'\u2AA6','ltcir':'\u2A79','ltdot':'\u22D6','lthree':'\u22CB','ltimes':'\u22C9','ltlarr':'\u2976','ltquest':'\u2A7B','ltri':'\u25C3','ltrie':'\u22B4','ltrif':'\u25C2','ltrPar':'\u2996','lurdshar':'\u294A','luruhar':'\u2966','lvertneqq':'\u2268\uFE00','lvnE':'\u2268\uFE00','macr':'\xAF','male':'\u2642','malt':'\u2720','maltese':'\u2720','map':'\u21A6','Map':'\u2905','mapsto':'\u21A6','mapstodown':'\u21A7','mapstoleft':'\u21A4','mapstoup':'\u21A5','marker':'\u25AE','mcomma':'\u2A29','mcy':'\u043C','Mcy':'\u041C','mdash':'\u2014','mDDot':'\u223A','measuredangle':'\u2221','MediumSpace':'\u205F','Mellintrf':'\u2133','mfr':'\uD835\uDD2A','Mfr':'\uD835\uDD10','mho':'\u2127','micro':'\xB5','mid':'\u2223','midast':'*','midcir':'\u2AF0','middot':'\xB7','minus':'\u2212','minusb':'\u229F','minusd':'\u2238','minusdu':'\u2A2A','MinusPlus':'\u2213','mlcp':'\u2ADB','mldr':'\u2026','mnplus':'\u2213','models':'\u22A7','mopf':'\uD835\uDD5E','Mopf':'\uD835\uDD44','mp':'\u2213','mscr':'\uD835\uDCC2','Mscr':'\u2133','mstpos':'\u223E','mu':'\u03BC','Mu':'\u039C','multimap':'\u22B8','mumap':'\u22B8','nabla':'\u2207','nacute':'\u0144','Nacute':'\u0143','nang':'\u2220\u20D2','nap':'\u2249','napE':'\u2A70\u0338','napid':'\u224B\u0338','napos':'\u0149','napprox':'\u2249','natur':'\u266E','natural':'\u266E','naturals':'\u2115','nbsp':'\xA0','nbump':'\u224E\u0338','nbumpe':'\u224F\u0338','ncap':'\u2A43','ncaron':'\u0148','Ncaron':'\u0147','ncedil':'\u0146','Ncedil':'\u0145','ncong':'\u2247','ncongdot':'\u2A6D\u0338','ncup':'\u2A42','ncy':'\u043D','Ncy':'\u041D','ndash':'\u2013','ne':'\u2260','nearhk':'\u2924','nearr':'\u2197','neArr':'\u21D7','nearrow':'\u2197','nedot':'\u2250\u0338','NegativeMediumSpace':'\u200B','NegativeThickSpace':'\u200B','NegativeThinSpace':'\u200B','NegativeVeryThinSpace':'\u200B','nequiv':'\u2262','nesear':'\u2928','nesim':'\u2242\u0338','NestedGreaterGreater':'\u226B','NestedLessLess':'\u226A','NewLine':'\n','nexist':'\u2204','nexists':'\u2204','nfr':'\uD835\uDD2B','Nfr':'\uD835\uDD11','nge':'\u2271','ngE':'\u2267\u0338','ngeq':'\u2271','ngeqq':'\u2267\u0338','ngeqslant':'\u2A7E\u0338','nges':'\u2A7E\u0338','nGg':'\u22D9\u0338','ngsim':'\u2275','ngt':'\u226F','nGt':'\u226B\u20D2','ngtr':'\u226F','nGtv':'\u226B\u0338','nharr':'\u21AE','nhArr':'\u21CE','nhpar':'\u2AF2','ni':'\u220B','nis':'\u22FC','nisd':'\u22FA','niv':'\u220B','njcy':'\u045A','NJcy':'\u040A','nlarr':'\u219A','nlArr':'\u21CD','nldr':'\u2025','nle':'\u2270','nlE':'\u2266\u0338','nleftarrow':'\u219A','nLeftarrow':'\u21CD','nleftrightarrow':'\u21AE','nLeftrightarrow':'\u21CE','nleq':'\u2270','nleqq':'\u2266\u0338','nleqslant':'\u2A7D\u0338','nles':'\u2A7D\u0338','nless':'\u226E','nLl':'\u22D8\u0338','nlsim':'\u2274','nlt':'\u226E','nLt':'\u226A\u20D2','nltri':'\u22EA','nltrie':'\u22EC','nLtv':'\u226A\u0338','nmid':'\u2224','NoBreak':'\u2060','NonBreakingSpace':'\xA0','nopf':'\uD835\uDD5F','Nopf':'\u2115','not':'\xAC','Not':'\u2AEC','NotCongruent':'\u2262','NotCupCap':'\u226D','NotDoubleVerticalBar':'\u2226','NotElement':'\u2209','NotEqual':'\u2260','NotEqualTilde':'\u2242\u0338','NotExists':'\u2204','NotGreater':'\u226F','NotGreaterEqual':'\u2271','NotGreaterFullEqual':'\u2267\u0338','NotGreaterGreater':'\u226B\u0338','NotGreaterLess':'\u2279','NotGreaterSlantEqual':'\u2A7E\u0338','NotGreaterTilde':'\u2275','NotHumpDownHump':'\u224E\u0338','NotHumpEqual':'\u224F\u0338','notin':'\u2209','notindot':'\u22F5\u0338','notinE':'\u22F9\u0338','notinva':'\u2209','notinvb':'\u22F7','notinvc':'\u22F6','NotLeftTriangle':'\u22EA','NotLeftTriangleBar':'\u29CF\u0338','NotLeftTriangleEqual':'\u22EC','NotLess':'\u226E','NotLessEqual':'\u2270','NotLessGreater':'\u2278','NotLessLess':'\u226A\u0338','NotLessSlantEqual':'\u2A7D\u0338','NotLessTilde':'\u2274','NotNestedGreaterGreater':'\u2AA2\u0338','NotNestedLessLess':'\u2AA1\u0338','notni':'\u220C','notniva':'\u220C','notnivb':'\u22FE','notnivc':'\u22FD','NotPrecedes':'\u2280','NotPrecedesEqual':'\u2AAF\u0338','NotPrecedesSlantEqual':'\u22E0','NotReverseElement':'\u220C','NotRightTriangle':'\u22EB','NotRightTriangleBar':'\u29D0\u0338','NotRightTriangleEqual':'\u22ED','NotSquareSubset':'\u228F\u0338','NotSquareSubsetEqual':'\u22E2','NotSquareSuperset':'\u2290\u0338','NotSquareSupersetEqual':'\u22E3','NotSubset':'\u2282\u20D2','NotSubsetEqual':'\u2288','NotSucceeds':'\u2281','NotSucceedsEqual':'\u2AB0\u0338','NotSucceedsSlantEqual':'\u22E1','NotSucceedsTilde':'\u227F\u0338','NotSuperset':'\u2283\u20D2','NotSupersetEqual':'\u2289','NotTilde':'\u2241','NotTildeEqual':'\u2244','NotTildeFullEqual':'\u2247','NotTildeTilde':'\u2249','NotVerticalBar':'\u2224','npar':'\u2226','nparallel':'\u2226','nparsl':'\u2AFD\u20E5','npart':'\u2202\u0338','npolint':'\u2A14','npr':'\u2280','nprcue':'\u22E0','npre':'\u2AAF\u0338','nprec':'\u2280','npreceq':'\u2AAF\u0338','nrarr':'\u219B','nrArr':'\u21CF','nrarrc':'\u2933\u0338','nrarrw':'\u219D\u0338','nrightarrow':'\u219B','nRightarrow':'\u21CF','nrtri':'\u22EB','nrtrie':'\u22ED','nsc':'\u2281','nsccue':'\u22E1','nsce':'\u2AB0\u0338','nscr':'\uD835\uDCC3','Nscr':'\uD835\uDCA9','nshortmid':'\u2224','nshortparallel':'\u2226','nsim':'\u2241','nsime':'\u2244','nsimeq':'\u2244','nsmid':'\u2224','nspar':'\u2226','nsqsube':'\u22E2','nsqsupe':'\u22E3','nsub':'\u2284','nsube':'\u2288','nsubE':'\u2AC5\u0338','nsubset':'\u2282\u20D2','nsubseteq':'\u2288','nsubseteqq':'\u2AC5\u0338','nsucc':'\u2281','nsucceq':'\u2AB0\u0338','nsup':'\u2285','nsupe':'\u2289','nsupE':'\u2AC6\u0338','nsupset':'\u2283\u20D2','nsupseteq':'\u2289','nsupseteqq':'\u2AC6\u0338','ntgl':'\u2279','ntilde':'\xF1','Ntilde':'\xD1','ntlg':'\u2278','ntriangleleft':'\u22EA','ntrianglelefteq':'\u22EC','ntriangleright':'\u22EB','ntrianglerighteq':'\u22ED','nu':'\u03BD','Nu':'\u039D','num':'#','numero':'\u2116','numsp':'\u2007','nvap':'\u224D\u20D2','nvdash':'\u22AC','nvDash':'\u22AD','nVdash':'\u22AE','nVDash':'\u22AF','nvge':'\u2265\u20D2','nvgt':'>\u20D2','nvHarr':'\u2904','nvinfin':'\u29DE','nvlArr':'\u2902','nvle':'\u2264\u20D2','nvlt':'<\u20D2','nvltrie':'\u22B4\u20D2','nvrArr':'\u2903','nvrtrie':'\u22B5\u20D2','nvsim':'\u223C\u20D2','nwarhk':'\u2923','nwarr':'\u2196','nwArr':'\u21D6','nwarrow':'\u2196','nwnear':'\u2927','oacute':'\xF3','Oacute':'\xD3','oast':'\u229B','ocir':'\u229A','ocirc':'\xF4','Ocirc':'\xD4','ocy':'\u043E','Ocy':'\u041E','odash':'\u229D','odblac':'\u0151','Odblac':'\u0150','odiv':'\u2A38','odot':'\u2299','odsold':'\u29BC','oelig':'\u0153','OElig':'\u0152','ofcir':'\u29BF','ofr':'\uD835\uDD2C','Ofr':'\uD835\uDD12','ogon':'\u02DB','ograve':'\xF2','Ograve':'\xD2','ogt':'\u29C1','ohbar':'\u29B5','ohm':'\u03A9','oint':'\u222E','olarr':'\u21BA','olcir':'\u29BE','olcross':'\u29BB','oline':'\u203E','olt':'\u29C0','omacr':'\u014D','Omacr':'\u014C','omega':'\u03C9','Omega':'\u03A9','omicron':'\u03BF','Omicron':'\u039F','omid':'\u29B6','ominus':'\u2296','oopf':'\uD835\uDD60','Oopf':'\uD835\uDD46','opar':'\u29B7','OpenCurlyDoubleQuote':'\u201C','OpenCurlyQuote':'\u2018','operp':'\u29B9','oplus':'\u2295','or':'\u2228','Or':'\u2A54','orarr':'\u21BB','ord':'\u2A5D','order':'\u2134','orderof':'\u2134','ordf':'\xAA','ordm':'\xBA','origof':'\u22B6','oror':'\u2A56','orslope':'\u2A57','orv':'\u2A5B','oS':'\u24C8','oscr':'\u2134','Oscr':'\uD835\uDCAA','oslash':'\xF8','Oslash':'\xD8','osol':'\u2298','otilde':'\xF5','Otilde':'\xD5','otimes':'\u2297','Otimes':'\u2A37','otimesas':'\u2A36','ouml':'\xF6','Ouml':'\xD6','ovbar':'\u233D','OverBar':'\u203E','OverBrace':'\u23DE','OverBracket':'\u23B4','OverParenthesis':'\u23DC','par':'\u2225','para':'\xB6','parallel':'\u2225','parsim':'\u2AF3','parsl':'\u2AFD','part':'\u2202','PartialD':'\u2202','pcy':'\u043F','Pcy':'\u041F','percnt':'%','period':'.','permil':'\u2030','perp':'\u22A5','pertenk':'\u2031','pfr':'\uD835\uDD2D','Pfr':'\uD835\uDD13','phi':'\u03C6','Phi':'\u03A6','phiv':'\u03D5','phmmat':'\u2133','phone':'\u260E','pi':'\u03C0','Pi':'\u03A0','pitchfork':'\u22D4','piv':'\u03D6','planck':'\u210F','planckh':'\u210E','plankv':'\u210F','plus':'+','plusacir':'\u2A23','plusb':'\u229E','pluscir':'\u2A22','plusdo':'\u2214','plusdu':'\u2A25','pluse':'\u2A72','PlusMinus':'\xB1','plusmn':'\xB1','plussim':'\u2A26','plustwo':'\u2A27','pm':'\xB1','Poincareplane':'\u210C','pointint':'\u2A15','popf':'\uD835\uDD61','Popf':'\u2119','pound':'\xA3','pr':'\u227A','Pr':'\u2ABB','prap':'\u2AB7','prcue':'\u227C','pre':'\u2AAF','prE':'\u2AB3','prec':'\u227A','precapprox':'\u2AB7','preccurlyeq':'\u227C','Precedes':'\u227A','PrecedesEqual':'\u2AAF','PrecedesSlantEqual':'\u227C','PrecedesTilde':'\u227E','preceq':'\u2AAF','precnapprox':'\u2AB9','precneqq':'\u2AB5','precnsim':'\u22E8','precsim':'\u227E','prime':'\u2032','Prime':'\u2033','primes':'\u2119','prnap':'\u2AB9','prnE':'\u2AB5','prnsim':'\u22E8','prod':'\u220F','Product':'\u220F','profalar':'\u232E','profline':'\u2312','profsurf':'\u2313','prop':'\u221D','Proportion':'\u2237','Proportional':'\u221D','propto':'\u221D','prsim':'\u227E','prurel':'\u22B0','pscr':'\uD835\uDCC5','Pscr':'\uD835\uDCAB','psi':'\u03C8','Psi':'\u03A8','puncsp':'\u2008','qfr':'\uD835\uDD2E','Qfr':'\uD835\uDD14','qint':'\u2A0C','qopf':'\uD835\uDD62','Qopf':'\u211A','qprime':'\u2057','qscr':'\uD835\uDCC6','Qscr':'\uD835\uDCAC','quaternions':'\u210D','quatint':'\u2A16','quest':'?','questeq':'\u225F','quot':'"','QUOT':'"','rAarr':'\u21DB','race':'\u223D\u0331','racute':'\u0155','Racute':'\u0154','radic':'\u221A','raemptyv':'\u29B3','rang':'\u27E9','Rang':'\u27EB','rangd':'\u2992','range':'\u29A5','rangle':'\u27E9','raquo':'\xBB','rarr':'\u2192','rArr':'\u21D2','Rarr':'\u21A0','rarrap':'\u2975','rarrb':'\u21E5','rarrbfs':'\u2920','rarrc':'\u2933','rarrfs':'\u291E','rarrhk':'\u21AA','rarrlp':'\u21AC','rarrpl':'\u2945','rarrsim':'\u2974','rarrtl':'\u21A3','Rarrtl':'\u2916','rarrw':'\u219D','ratail':'\u291A','rAtail':'\u291C','ratio':'\u2236','rationals':'\u211A','rbarr':'\u290D','rBarr':'\u290F','RBarr':'\u2910','rbbrk':'\u2773','rbrace':'}','rbrack':']','rbrke':'\u298C','rbrksld':'\u298E','rbrkslu':'\u2990','rcaron':'\u0159','Rcaron':'\u0158','rcedil':'\u0157','Rcedil':'\u0156','rceil':'\u2309','rcub':'}','rcy':'\u0440','Rcy':'\u0420','rdca':'\u2937','rdldhar':'\u2969','rdquo':'\u201D','rdquor':'\u201D','rdsh':'\u21B3','Re':'\u211C','real':'\u211C','realine':'\u211B','realpart':'\u211C','reals':'\u211D','rect':'\u25AD','reg':'\xAE','REG':'\xAE','ReverseElement':'\u220B','ReverseEquilibrium':'\u21CB','ReverseUpEquilibrium':'\u296F','rfisht':'\u297D','rfloor':'\u230B','rfr':'\uD835\uDD2F','Rfr':'\u211C','rHar':'\u2964','rhard':'\u21C1','rharu':'\u21C0','rharul':'\u296C','rho':'\u03C1','Rho':'\u03A1','rhov':'\u03F1','RightAngleBracket':'\u27E9','rightarrow':'\u2192','Rightarrow':'\u21D2','RightArrow':'\u2192','RightArrowBar':'\u21E5','RightArrowLeftArrow':'\u21C4','rightarrowtail':'\u21A3','RightCeiling':'\u2309','RightDoubleBracket':'\u27E7','RightDownTeeVector':'\u295D','RightDownVector':'\u21C2','RightDownVectorBar':'\u2955','RightFloor':'\u230B','rightharpoondown':'\u21C1','rightharpoonup':'\u21C0','rightleftarrows':'\u21C4','rightleftharpoons':'\u21CC','rightrightarrows':'\u21C9','rightsquigarrow':'\u219D','RightTee':'\u22A2','RightTeeArrow':'\u21A6','RightTeeVector':'\u295B','rightthreetimes':'\u22CC','RightTriangle':'\u22B3','RightTriangleBar':'\u29D0','RightTriangleEqual':'\u22B5','RightUpDownVector':'\u294F','RightUpTeeVector':'\u295C','RightUpVector':'\u21BE','RightUpVectorBar':'\u2954','RightVector':'\u21C0','RightVectorBar':'\u2953','ring':'\u02DA','risingdotseq':'\u2253','rlarr':'\u21C4','rlhar':'\u21CC','rlm':'\u200F','rmoust':'\u23B1','rmoustache':'\u23B1','rnmid':'\u2AEE','roang':'\u27ED','roarr':'\u21FE','robrk':'\u27E7','ropar':'\u2986','ropf':'\uD835\uDD63','Ropf':'\u211D','roplus':'\u2A2E','rotimes':'\u2A35','RoundImplies':'\u2970','rpar':')','rpargt':'\u2994','rppolint':'\u2A12','rrarr':'\u21C9','Rrightarrow':'\u21DB','rsaquo':'\u203A','rscr':'\uD835\uDCC7','Rscr':'\u211B','rsh':'\u21B1','Rsh':'\u21B1','rsqb':']','rsquo':'\u2019','rsquor':'\u2019','rthree':'\u22CC','rtimes':'\u22CA','rtri':'\u25B9','rtrie':'\u22B5','rtrif':'\u25B8','rtriltri':'\u29CE','RuleDelayed':'\u29F4','ruluhar':'\u2968','rx':'\u211E','sacute':'\u015B','Sacute':'\u015A','sbquo':'\u201A','sc':'\u227B','Sc':'\u2ABC','scap':'\u2AB8','scaron':'\u0161','Scaron':'\u0160','sccue':'\u227D','sce':'\u2AB0','scE':'\u2AB4','scedil':'\u015F','Scedil':'\u015E','scirc':'\u015D','Scirc':'\u015C','scnap':'\u2ABA','scnE':'\u2AB6','scnsim':'\u22E9','scpolint':'\u2A13','scsim':'\u227F','scy':'\u0441','Scy':'\u0421','sdot':'\u22C5','sdotb':'\u22A1','sdote':'\u2A66','searhk':'\u2925','searr':'\u2198','seArr':'\u21D8','searrow':'\u2198','sect':'\xA7','semi':';','seswar':'\u2929','setminus':'\u2216','setmn':'\u2216','sext':'\u2736','sfr':'\uD835\uDD30','Sfr':'\uD835\uDD16','sfrown':'\u2322','sharp':'\u266F','shchcy':'\u0449','SHCHcy':'\u0429','shcy':'\u0448','SHcy':'\u0428','ShortDownArrow':'\u2193','ShortLeftArrow':'\u2190','shortmid':'\u2223','shortparallel':'\u2225','ShortRightArrow':'\u2192','ShortUpArrow':'\u2191','shy':'\xAD','sigma':'\u03C3','Sigma':'\u03A3','sigmaf':'\u03C2','sigmav':'\u03C2','sim':'\u223C','simdot':'\u2A6A','sime':'\u2243','simeq':'\u2243','simg':'\u2A9E','simgE':'\u2AA0','siml':'\u2A9D','simlE':'\u2A9F','simne':'\u2246','simplus':'\u2A24','simrarr':'\u2972','slarr':'\u2190','SmallCircle':'\u2218','smallsetminus':'\u2216','smashp':'\u2A33','smeparsl':'\u29E4','smid':'\u2223','smile':'\u2323','smt':'\u2AAA','smte':'\u2AAC','smtes':'\u2AAC\uFE00','softcy':'\u044C','SOFTcy':'\u042C','sol':'/','solb':'\u29C4','solbar':'\u233F','sopf':'\uD835\uDD64','Sopf':'\uD835\uDD4A','spades':'\u2660','spadesuit':'\u2660','spar':'\u2225','sqcap':'\u2293','sqcaps':'\u2293\uFE00','sqcup':'\u2294','sqcups':'\u2294\uFE00','Sqrt':'\u221A','sqsub':'\u228F','sqsube':'\u2291','sqsubset':'\u228F','sqsubseteq':'\u2291','sqsup':'\u2290','sqsupe':'\u2292','sqsupset':'\u2290','sqsupseteq':'\u2292','squ':'\u25A1','square':'\u25A1','Square':'\u25A1','SquareIntersection':'\u2293','SquareSubset':'\u228F','SquareSubsetEqual':'\u2291','SquareSuperset':'\u2290','SquareSupersetEqual':'\u2292','SquareUnion':'\u2294','squarf':'\u25AA','squf':'\u25AA','srarr':'\u2192','sscr':'\uD835\uDCC8','Sscr':'\uD835\uDCAE','ssetmn':'\u2216','ssmile':'\u2323','sstarf':'\u22C6','star':'\u2606','Star':'\u22C6','starf':'\u2605','straightepsilon':'\u03F5','straightphi':'\u03D5','strns':'\xAF','sub':'\u2282','Sub':'\u22D0','subdot':'\u2ABD','sube':'\u2286','subE':'\u2AC5','subedot':'\u2AC3','submult':'\u2AC1','subne':'\u228A','subnE':'\u2ACB','subplus':'\u2ABF','subrarr':'\u2979','subset':'\u2282','Subset':'\u22D0','subseteq':'\u2286','subseteqq':'\u2AC5','SubsetEqual':'\u2286','subsetneq':'\u228A','subsetneqq':'\u2ACB','subsim':'\u2AC7','subsub':'\u2AD5','subsup':'\u2AD3','succ':'\u227B','succapprox':'\u2AB8','succcurlyeq':'\u227D','Succeeds':'\u227B','SucceedsEqual':'\u2AB0','SucceedsSlantEqual':'\u227D','SucceedsTilde':'\u227F','succeq':'\u2AB0','succnapprox':'\u2ABA','succneqq':'\u2AB6','succnsim':'\u22E9','succsim':'\u227F','SuchThat':'\u220B','sum':'\u2211','Sum':'\u2211','sung':'\u266A','sup':'\u2283','Sup':'\u22D1','sup1':'\xB9','sup2':'\xB2','sup3':'\xB3','supdot':'\u2ABE','supdsub':'\u2AD8','supe':'\u2287','supE':'\u2AC6','supedot':'\u2AC4','Superset':'\u2283','SupersetEqual':'\u2287','suphsol':'\u27C9','suphsub':'\u2AD7','suplarr':'\u297B','supmult':'\u2AC2','supne':'\u228B','supnE':'\u2ACC','supplus':'\u2AC0','supset':'\u2283','Supset':'\u22D1','supseteq':'\u2287','supseteqq':'\u2AC6','supsetneq':'\u228B','supsetneqq':'\u2ACC','supsim':'\u2AC8','supsub':'\u2AD4','supsup':'\u2AD6','swarhk':'\u2926','swarr':'\u2199','swArr':'\u21D9','swarrow':'\u2199','swnwar':'\u292A','szlig':'\xDF','Tab':'\t','target':'\u2316','tau':'\u03C4','Tau':'\u03A4','tbrk':'\u23B4','tcaron':'\u0165','Tcaron':'\u0164','tcedil':'\u0163','Tcedil':'\u0162','tcy':'\u0442','Tcy':'\u0422','tdot':'\u20DB','telrec':'\u2315','tfr':'\uD835\uDD31','Tfr':'\uD835\uDD17','there4':'\u2234','therefore':'\u2234','Therefore':'\u2234','theta':'\u03B8','Theta':'\u0398','thetasym':'\u03D1','thetav':'\u03D1','thickapprox':'\u2248','thicksim':'\u223C','ThickSpace':'\u205F\u200A','thinsp':'\u2009','ThinSpace':'\u2009','thkap':'\u2248','thksim':'\u223C','thorn':'\xFE','THORN':'\xDE','tilde':'\u02DC','Tilde':'\u223C','TildeEqual':'\u2243','TildeFullEqual':'\u2245','TildeTilde':'\u2248','times':'\xD7','timesb':'\u22A0','timesbar':'\u2A31','timesd':'\u2A30','tint':'\u222D','toea':'\u2928','top':'\u22A4','topbot':'\u2336','topcir':'\u2AF1','topf':'\uD835\uDD65','Topf':'\uD835\uDD4B','topfork':'\u2ADA','tosa':'\u2929','tprime':'\u2034','trade':'\u2122','TRADE':'\u2122','triangle':'\u25B5','triangledown':'\u25BF','triangleleft':'\u25C3','trianglelefteq':'\u22B4','triangleq':'\u225C','triangleright':'\u25B9','trianglerighteq':'\u22B5','tridot':'\u25EC','trie':'\u225C','triminus':'\u2A3A','TripleDot':'\u20DB','triplus':'\u2A39','trisb':'\u29CD','tritime':'\u2A3B','trpezium':'\u23E2','tscr':'\uD835\uDCC9','Tscr':'\uD835\uDCAF','tscy':'\u0446','TScy':'\u0426','tshcy':'\u045B','TSHcy':'\u040B','tstrok':'\u0167','Tstrok':'\u0166','twixt':'\u226C','twoheadleftarrow':'\u219E','twoheadrightarrow':'\u21A0','uacute':'\xFA','Uacute':'\xDA','uarr':'\u2191','uArr':'\u21D1','Uarr':'\u219F','Uarrocir':'\u2949','ubrcy':'\u045E','Ubrcy':'\u040E','ubreve':'\u016D','Ubreve':'\u016C','ucirc':'\xFB','Ucirc':'\xDB','ucy':'\u0443','Ucy':'\u0423','udarr':'\u21C5','udblac':'\u0171','Udblac':'\u0170','udhar':'\u296E','ufisht':'\u297E','ufr':'\uD835\uDD32','Ufr':'\uD835\uDD18','ugrave':'\xF9','Ugrave':'\xD9','uHar':'\u2963','uharl':'\u21BF','uharr':'\u21BE','uhblk':'\u2580','ulcorn':'\u231C','ulcorner':'\u231C','ulcrop':'\u230F','ultri':'\u25F8','umacr':'\u016B','Umacr':'\u016A','uml':'\xA8','UnderBar':'_','UnderBrace':'\u23DF','UnderBracket':'\u23B5','UnderParenthesis':'\u23DD','Union':'\u22C3','UnionPlus':'\u228E','uogon':'\u0173','Uogon':'\u0172','uopf':'\uD835\uDD66','Uopf':'\uD835\uDD4C','uparrow':'\u2191','Uparrow':'\u21D1','UpArrow':'\u2191','UpArrowBar':'\u2912','UpArrowDownArrow':'\u21C5','updownarrow':'\u2195','Updownarrow':'\u21D5','UpDownArrow':'\u2195','UpEquilibrium':'\u296E','upharpoonleft':'\u21BF','upharpoonright':'\u21BE','uplus':'\u228E','UpperLeftArrow':'\u2196','UpperRightArrow':'\u2197','upsi':'\u03C5','Upsi':'\u03D2','upsih':'\u03D2','upsilon':'\u03C5','Upsilon':'\u03A5','UpTee':'\u22A5','UpTeeArrow':'\u21A5','upuparrows':'\u21C8','urcorn':'\u231D','urcorner':'\u231D','urcrop':'\u230E','uring':'\u016F','Uring':'\u016E','urtri':'\u25F9','uscr':'\uD835\uDCCA','Uscr':'\uD835\uDCB0','utdot':'\u22F0','utilde':'\u0169','Utilde':'\u0168','utri':'\u25B5','utrif':'\u25B4','uuarr':'\u21C8','uuml':'\xFC','Uuml':'\xDC','uwangle':'\u29A7','vangrt':'\u299C','varepsilon':'\u03F5','varkappa':'\u03F0','varnothing':'\u2205','varphi':'\u03D5','varpi':'\u03D6','varpropto':'\u221D','varr':'\u2195','vArr':'\u21D5','varrho':'\u03F1','varsigma':'\u03C2','varsubsetneq':'\u228A\uFE00','varsubsetneqq':'\u2ACB\uFE00','varsupsetneq':'\u228B\uFE00','varsupsetneqq':'\u2ACC\uFE00','vartheta':'\u03D1','vartriangleleft':'\u22B2','vartriangleright':'\u22B3','vBar':'\u2AE8','Vbar':'\u2AEB','vBarv':'\u2AE9','vcy':'\u0432','Vcy':'\u0412','vdash':'\u22A2','vDash':'\u22A8','Vdash':'\u22A9','VDash':'\u22AB','Vdashl':'\u2AE6','vee':'\u2228','Vee':'\u22C1','veebar':'\u22BB','veeeq':'\u225A','vellip':'\u22EE','verbar':'|','Verbar':'\u2016','vert':'|','Vert':'\u2016','VerticalBar':'\u2223','VerticalLine':'|','VerticalSeparator':'\u2758','VerticalTilde':'\u2240','VeryThinSpace':'\u200A','vfr':'\uD835\uDD33','Vfr':'\uD835\uDD19','vltri':'\u22B2','vnsub':'\u2282\u20D2','vnsup':'\u2283\u20D2','vopf':'\uD835\uDD67','Vopf':'\uD835\uDD4D','vprop':'\u221D','vrtri':'\u22B3','vscr':'\uD835\uDCCB','Vscr':'\uD835\uDCB1','vsubne':'\u228A\uFE00','vsubnE':'\u2ACB\uFE00','vsupne':'\u228B\uFE00','vsupnE':'\u2ACC\uFE00','Vvdash':'\u22AA','vzigzag':'\u299A','wcirc':'\u0175','Wcirc':'\u0174','wedbar':'\u2A5F','wedge':'\u2227','Wedge':'\u22C0','wedgeq':'\u2259','weierp':'\u2118','wfr':'\uD835\uDD34','Wfr':'\uD835\uDD1A','wopf':'\uD835\uDD68','Wopf':'\uD835\uDD4E','wp':'\u2118','wr':'\u2240','wreath':'\u2240','wscr':'\uD835\uDCCC','Wscr':'\uD835\uDCB2','xcap':'\u22C2','xcirc':'\u25EF','xcup':'\u22C3','xdtri':'\u25BD','xfr':'\uD835\uDD35','Xfr':'\uD835\uDD1B','xharr':'\u27F7','xhArr':'\u27FA','xi':'\u03BE','Xi':'\u039E','xlarr':'\u27F5','xlArr':'\u27F8','xmap':'\u27FC','xnis':'\u22FB','xodot':'\u2A00','xopf':'\uD835\uDD69','Xopf':'\uD835\uDD4F','xoplus':'\u2A01','xotime':'\u2A02','xrarr':'\u27F6','xrArr':'\u27F9','xscr':'\uD835\uDCCD','Xscr':'\uD835\uDCB3','xsqcup':'\u2A06','xuplus':'\u2A04','xutri':'\u25B3','xvee':'\u22C1','xwedge':'\u22C0','yacute':'\xFD','Yacute':'\xDD','yacy':'\u044F','YAcy':'\u042F','ycirc':'\u0177','Ycirc':'\u0176','ycy':'\u044B','Ycy':'\u042B','yen':'\xA5','yfr':'\uD835\uDD36','Yfr':'\uD835\uDD1C','yicy':'\u0457','YIcy':'\u0407','yopf':'\uD835\uDD6A','Yopf':'\uD835\uDD50','yscr':'\uD835\uDCCE','Yscr':'\uD835\uDCB4','yucy':'\u044E','YUcy':'\u042E','yuml':'\xFF','Yuml':'\u0178','zacute':'\u017A','Zacute':'\u0179','zcaron':'\u017E','Zcaron':'\u017D','zcy':'\u0437','Zcy':'\u0417','zdot':'\u017C','Zdot':'\u017B','zeetrf':'\u2128','ZeroWidthSpace':'\u200B','zeta':'\u03B6','Zeta':'\u0396','zfr':'\uD835\uDD37','Zfr':'\u2128','zhcy':'\u0436','ZHcy':'\u0416','zigrarr':'\u21DD','zopf':'\uD835\uDD6B','Zopf':'\u2124','zscr':'\uD835\uDCCF','Zscr':'\uD835\uDCB5','zwj':'\u200D','zwnj':'\u200C'}; + var decodeMapLegacy = {'aacute':'\xE1','Aacute':'\xC1','acirc':'\xE2','Acirc':'\xC2','acute':'\xB4','aelig':'\xE6','AElig':'\xC6','agrave':'\xE0','Agrave':'\xC0','amp':'&','AMP':'&','aring':'\xE5','Aring':'\xC5','atilde':'\xE3','Atilde':'\xC3','auml':'\xE4','Auml':'\xC4','brvbar':'\xA6','ccedil':'\xE7','Ccedil':'\xC7','cedil':'\xB8','cent':'\xA2','copy':'\xA9','COPY':'\xA9','curren':'\xA4','deg':'\xB0','divide':'\xF7','eacute':'\xE9','Eacute':'\xC9','ecirc':'\xEA','Ecirc':'\xCA','egrave':'\xE8','Egrave':'\xC8','eth':'\xF0','ETH':'\xD0','euml':'\xEB','Euml':'\xCB','frac12':'\xBD','frac14':'\xBC','frac34':'\xBE','gt':'>','GT':'>','iacute':'\xED','Iacute':'\xCD','icirc':'\xEE','Icirc':'\xCE','iexcl':'\xA1','igrave':'\xEC','Igrave':'\xCC','iquest':'\xBF','iuml':'\xEF','Iuml':'\xCF','laquo':'\xAB','lt':'<','LT':'<','macr':'\xAF','micro':'\xB5','middot':'\xB7','nbsp':'\xA0','not':'\xAC','ntilde':'\xF1','Ntilde':'\xD1','oacute':'\xF3','Oacute':'\xD3','ocirc':'\xF4','Ocirc':'\xD4','ograve':'\xF2','Ograve':'\xD2','ordf':'\xAA','ordm':'\xBA','oslash':'\xF8','Oslash':'\xD8','otilde':'\xF5','Otilde':'\xD5','ouml':'\xF6','Ouml':'\xD6','para':'\xB6','plusmn':'\xB1','pound':'\xA3','quot':'"','QUOT':'"','raquo':'\xBB','reg':'\xAE','REG':'\xAE','sect':'\xA7','shy':'\xAD','sup1':'\xB9','sup2':'\xB2','sup3':'\xB3','szlig':'\xDF','thorn':'\xFE','THORN':'\xDE','times':'\xD7','uacute':'\xFA','Uacute':'\xDA','ucirc':'\xFB','Ucirc':'\xDB','ugrave':'\xF9','Ugrave':'\xD9','uml':'\xA8','uuml':'\xFC','Uuml':'\xDC','yacute':'\xFD','Yacute':'\xDD','yen':'\xA5','yuml':'\xFF'}; + var decodeMapNumeric = {'0':'\uFFFD','128':'\u20AC','130':'\u201A','131':'\u0192','132':'\u201E','133':'\u2026','134':'\u2020','135':'\u2021','136':'\u02C6','137':'\u2030','138':'\u0160','139':'\u2039','140':'\u0152','142':'\u017D','145':'\u2018','146':'\u2019','147':'\u201C','148':'\u201D','149':'\u2022','150':'\u2013','151':'\u2014','152':'\u02DC','153':'\u2122','154':'\u0161','155':'\u203A','156':'\u0153','158':'\u017E','159':'\u0178'}; + var invalidReferenceCodePoints = [1,2,3,4,5,6,7,8,11,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,64976,64977,64978,64979,64980,64981,64982,64983,64984,64985,64986,64987,64988,64989,64990,64991,64992,64993,64994,64995,64996,64997,64998,64999,65000,65001,65002,65003,65004,65005,65006,65007,65534,65535,131070,131071,196606,196607,262142,262143,327678,327679,393214,393215,458750,458751,524286,524287,589822,589823,655358,655359,720894,720895,786430,786431,851966,851967,917502,917503,983038,983039,1048574,1048575,1114110,1114111]; + + /*--------------------------------------------------------------------------*/ + + var stringFromCharCode = String.fromCharCode; + + var object = {}; + var hasOwnProperty = object.hasOwnProperty; + var has = function(object, propertyName) { + return hasOwnProperty.call(object, propertyName); + }; + + var contains = function(array, value) { + var index = -1; + var length = array.length; + while (++index < length) { + if (array[index] == value) { + return true; + } + } + return false; + }; + + var merge = function(options, defaults) { + if (!options) { + return defaults; + } + var result = {}; + var key; + for (key in defaults) { + // A `hasOwnProperty` check is not needed here, since only recognized + // option names are used anyway. Any others are ignored. + result[key] = has(options, key) ? options[key] : defaults[key]; + } + return result; + }; + + // Modified version of `ucs2encode`; see https://mths.be/punycode. + var codePointToSymbol = function(codePoint, strict) { + var output = ''; + if ((codePoint >= 0xD800 && codePoint <= 0xDFFF) || codePoint > 0x10FFFF) { + // See issue #4: + // “Otherwise, if the number is in the range 0xD800 to 0xDFFF or is + // greater than 0x10FFFF, then this is a parse error. Return a U+FFFD + // REPLACEMENT CHARACTER.” + if (strict) { + parseError('character reference outside the permissible Unicode range'); + } + return '\uFFFD'; + } + if (has(decodeMapNumeric, codePoint)) { + if (strict) { + parseError('disallowed character reference'); + } + return decodeMapNumeric[codePoint]; + } + if (strict && contains(invalidReferenceCodePoints, codePoint)) { + parseError('disallowed character reference'); + } + if (codePoint > 0xFFFF) { + codePoint -= 0x10000; + output += stringFromCharCode(codePoint >>> 10 & 0x3FF | 0xD800); + codePoint = 0xDC00 | codePoint & 0x3FF; + } + output += stringFromCharCode(codePoint); + return output; + }; + + var hexEscape = function(codePoint) { + return '&#x' + codePoint.toString(16).toUpperCase() + ';'; + }; + + var decEscape = function(codePoint) { + return '&#' + codePoint + ';'; + }; + + var parseError = function(message) { + throw Error('Parse error: ' + message); + }; + + /*--------------------------------------------------------------------------*/ + + var encode = function(string, options) { + options = merge(options, encode.options); + var strict = options.strict; + if (strict && regexInvalidRawCodePoint.test(string)) { + parseError('forbidden code point'); + } + var encodeEverything = options.encodeEverything; + var useNamedReferences = options.useNamedReferences; + var allowUnsafeSymbols = options.allowUnsafeSymbols; + var escapeCodePoint = options.decimal ? decEscape : hexEscape; + + var escapeBmpSymbol = function(symbol) { + return escapeCodePoint(symbol.charCodeAt(0)); + }; + + if (encodeEverything) { + // Encode ASCII symbols. + string = string.replace(regexAsciiWhitelist, function(symbol) { + // Use named references if requested & possible. + if (useNamedReferences && has(encodeMap, symbol)) { + return '&' + encodeMap[symbol] + ';'; + } + return escapeBmpSymbol(symbol); + }); + // Shorten a few escapes that represent two symbols, of which at least one + // is within the ASCII range. + if (useNamedReferences) { + string = string + .replace(/>\u20D2/g, '>⃒') + .replace(/<\u20D2/g, '<⃒') + .replace(/fj/g, 'fj'); + } + // Encode non-ASCII symbols. + if (useNamedReferences) { + // Encode non-ASCII symbols that can be replaced with a named reference. + string = string.replace(regexEncodeNonAscii, function(string) { + // Note: there is no need to check `has(encodeMap, string)` here. + return '&' + encodeMap[string] + ';'; + }); + } + // Note: any remaining non-ASCII symbols are handled outside of the `if`. + } else if (useNamedReferences) { + // Apply named character references. + // Encode `<>"'&` using named character references. + if (!allowUnsafeSymbols) { + string = string.replace(regexEscape, function(string) { + return '&' + encodeMap[string] + ';'; // no need to check `has()` here + }); + } + // Shorten escapes that represent two symbols, of which at least one is + // `<>"'&`. + string = string + .replace(/>\u20D2/g, '>⃒') + .replace(/<\u20D2/g, '<⃒'); + // Encode non-ASCII symbols that can be replaced with a named reference. + string = string.replace(regexEncodeNonAscii, function(string) { + // Note: there is no need to check `has(encodeMap, string)` here. + return '&' + encodeMap[string] + ';'; + }); + } else if (!allowUnsafeSymbols) { + // Encode `<>"'&` using hexadecimal escapes, now that they’re not handled + // using named character references. + string = string.replace(regexEscape, escapeBmpSymbol); + } + return string + // Encode astral symbols. + .replace(regexAstralSymbols, function($0) { + // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae + var high = $0.charCodeAt(0); + var low = $0.charCodeAt(1); + var codePoint = (high - 0xD800) * 0x400 + low - 0xDC00 + 0x10000; + return escapeCodePoint(codePoint); + }) + // Encode any remaining BMP symbols that are not printable ASCII symbols + // using a hexadecimal escape. + .replace(regexBmpWhitelist, escapeBmpSymbol); + }; + // Expose default options (so they can be overridden globally). + encode.options = { + 'allowUnsafeSymbols': false, + 'encodeEverything': false, + 'strict': false, + 'useNamedReferences': false, + 'decimal' : false + }; + + var decode = function(html, options) { + options = merge(options, decode.options); + var strict = options.strict; + if (strict && regexInvalidEntity.test(html)) { + parseError('malformed character reference'); + } + return html.replace(regexDecode, function($0, $1, $2, $3, $4, $5, $6, $7) { + var codePoint; + var semicolon; + var decDigits; + var hexDigits; + var reference; + var next; + if ($1) { + // Decode decimal escapes, e.g. `𝌆`. + decDigits = $1; + semicolon = $2; + if (strict && !semicolon) { + parseError('character reference was not terminated by a semicolon'); + } + codePoint = parseInt(decDigits, 10); + return codePointToSymbol(codePoint, strict); + } + if ($3) { + // Decode hexadecimal escapes, e.g. `𝌆`. + hexDigits = $3; + semicolon = $4; + if (strict && !semicolon) { + parseError('character reference was not terminated by a semicolon'); + } + codePoint = parseInt(hexDigits, 16); + return codePointToSymbol(codePoint, strict); + } + if ($5) { + // Decode named character references with trailing `;`, e.g. `©`. + reference = $5; + if (has(decodeMap, reference)) { + return decodeMap[reference]; + } else { + // Ambiguous ampersand. https://mths.be/notes/ambiguous-ampersands + if (strict) { + parseError( + 'named character reference was not terminated by a semicolon' + ); + } + return $0; + } + } + // If we’re still here, it’s a legacy reference for sure. No need for an + // extra `if` check. + // Decode named character references without trailing `;`, e.g. `&` + // This is only a parse error if it gets converted to `&`, or if it is + // followed by `=` in an attribute context. + reference = $6; + next = $7; + if (next && options.isAttributeValue) { + if (strict && next == '=') { + parseError('`&` did not start a character reference'); + } + return $0; + } else { + if (strict) { + parseError( + 'named character reference was not terminated by a semicolon' + ); + } + // Note: there is no need to check `has(decodeMapLegacy, reference)`. + return decodeMapLegacy[reference] + (next || ''); + } + }); + }; + // Expose default options (so they can be overridden globally). + decode.options = { + 'isAttributeValue': false, + 'strict': false + }; + + var escape = function(string) { + return string.replace(regexEscape, function($0) { + // Note: there is no need to check `has(escapeMap, $0)` here. + return escapeMap[$0]; + }); + }; + + /*--------------------------------------------------------------------------*/ + + var he = { + 'version': '1.1.1', + 'encode': encode, + 'decode': decode, + 'escape': escape, + 'unescape': decode + }; + + // Some AMD build optimizers, like r.js, check for specific condition patterns + // like the following: + if ( + typeof define == 'function' && + typeof define.amd == 'object' && + define.amd + ) { + define(function() { + return he; + }); + } else if (freeExports && !freeExports.nodeType) { + if (freeModule) { // in Node.js, io.js, or RingoJS v0.8.0+ + freeModule.exports = he; + } else { // in Narwhal or RingoJS v0.7.0- + for (var key in he) { + has(he, key) && (freeExports[key] = he[key]); + } + } + } else { // in Rhino or a web browser + root.he = he; + } + +}(this)); diff --git a/node_modules/he/man/he.1 b/node_modules/he/man/he.1 new file mode 100644 index 0000000..7696628 --- /dev/null +++ b/node_modules/he/man/he.1 @@ -0,0 +1,78 @@ +.Dd April 5, 2016 +.Dt he 1 +.Sh NAME +.Nm he +.Nd encode/decode HTML entities just like a browser would +.Sh SYNOPSIS +.Nm +.Op Fl -escape Ar string +.br +.Op Fl -encode Ar string +.br +.Op Fl -encode Fl -use-named-refs Fl -everything Fl -allow-unsafe Ar string +.br +.Op Fl -decode Ar string +.br +.Op Fl -decode Fl -attribute Ar string +.br +.Op Fl -decode Fl -strict Ar string +.br +.Op Fl v | -version +.br +.Op Fl h | -help +.Sh DESCRIPTION +.Nm +encodes/decodes HTML entities in strings just like a browser would. +.Sh OPTIONS +.Bl -ohang -offset +.It Sy "--escape" +Take a string of text and escape it for use in text contexts in XML or HTML documents. Only the following characters are escaped: `&`, `<`, `>`, `"`, and `'`. +.It Sy "--encode" +Take a string of text and encode any symbols that aren't printable ASCII symbols and that can be replaced with character references. For example, it would turn `©` into `©`, but it wouldn't turn `+` into `+` since there is no point in doing so. Additionally, it replaces any remaining non-ASCII symbols with a hexadecimal escape sequence (e.g. `𝌆`). The return value of this function is always valid HTML. +.It Sy "--encode --use-named-refs" +Enable the use of named character references (like `©`) in the output. If compatibility with older browsers is a concern, don't use this option. +.It Sy "--encode --everything" +Encode every symbol in the input string, even safe printable ASCII symbols. +.It Sy "--encode --allow-unsafe" +Encode non-ASCII characters only. This leaves unsafe HTML/XML symbols like `&`, `<`, `>`, `"`, and `'` intact. +.It Sy "--encode --decimal" +Use decimal digits rather than hexadecimal digits for encoded character references, e.g. output `©` instead of `©`. +.It Sy "--decode" +Takes a string of HTML and decode any named and numerical character references in it using the algorithm described in the HTML spec. +.It Sy "--decode --attribute" +Parse the input as if it was an HTML attribute value rather than a string in an HTML text content. +.It Sy "--decode --strict" +Throw an error if an invalid character reference is encountered. +.It Sy "-v, --version" +Print he's version. +.It Sy "-h, --help" +Show the help screen. +.El +.Sh EXIT STATUS +The +.Nm he +utility exits with one of the following values: +.Pp +.Bl -tag -width flag -compact +.It Li 0 +.Nm +did what it was instructed to do successfully; either it encoded/decoded the input and printed the result, or it printed the version or usage message. +.It Li 1 +.Nm +encountered an error. +.El +.Sh EXAMPLES +.Bl -ohang -offset +.It Sy "he --escape ''" +Print an escaped version of the given string that is safe for use in HTML text contexts, escaping only `&`, `<`, `>`, `"`, and `'`. +.It Sy "he --decode '©𝌆'" +Print the decoded version of the given HTML string. +.It Sy "echo\ '©𝌆'\ |\ he --decode" +Print the decoded version of the HTML string that gets piped in. +.El +.Sh BUGS +he's bug tracker is located at . +.Sh AUTHOR +Mathias Bynens +.Sh WWW + diff --git a/node_modules/he/package.json b/node_modules/he/package.json new file mode 100644 index 0000000..8c51175 --- /dev/null +++ b/node_modules/he/package.json @@ -0,0 +1,88 @@ +{ + "_from": "he@1.1.1", + "_id": "he@1.1.1", + "_inBundle": false, + "_integrity": "sha1-k0EP0hsAlzUVH4howvJx80J+I/0=", + "_location": "/he", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "he@1.1.1", + "name": "he", + "escapedName": "he", + "rawSpec": "1.1.1", + "saveSpec": null, + "fetchSpec": "1.1.1" + }, + "_requiredBy": [ + "/mocha" + ], + "_resolved": "https://registry.npmjs.org/he/-/he-1.1.1.tgz", + "_shasum": "93410fd21b009735151f8868c2f271f3427e23fd", + "_spec": "he@1.1.1", + "_where": "/Users/jessitron/code/jessitron/stringify-tree/node_modules/mocha", + "author": { + "name": "Mathias Bynens", + "url": "https://mathiasbynens.be/" + }, + "bin": { + "he": "bin/he" + }, + "bugs": { + "url": "https://github.com/mathiasbynens/he/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "A robust HTML entities encoder/decoder with full Unicode support.", + "devDependencies": { + "codecov.io": "^0.1.6", + "grunt": "^0.4.5", + "grunt-shell": "^1.1.1", + "grunt-template": "^0.2.3", + "istanbul": "^0.4.2", + "jsesc": "^1.0.0", + "lodash": "^4.8.2", + "qunit-extras": "^1.4.5", + "qunitjs": "~1.11.0", + "regenerate": "^1.2.1", + "requirejs": "^2.1.22", + "sort-object": "^3.0.2" + }, + "directories": { + "bin": "bin", + "man": "man", + "test": "tests" + }, + "files": [ + "LICENSE-MIT.txt", + "he.js", + "bin/", + "man/" + ], + "homepage": "https://mths.be/he", + "keywords": [ + "string", + "entities", + "entity", + "html", + "encode", + "decode", + "unicode" + ], + "license": "MIT", + "main": "he.js", + "man": [ + "/Users/jessitron/code/jessitron/stringify-tree/node_modules/he/man/he.1" + ], + "name": "he", + "repository": { + "type": "git", + "url": "git+https://github.com/mathiasbynens/he.git" + }, + "scripts": { + "build": "grunt build", + "test": "node tests/tests.js" + }, + "version": "1.1.1" +} diff --git a/node_modules/inflight/LICENSE b/node_modules/inflight/LICENSE new file mode 100644 index 0000000..05eeeb8 --- /dev/null +++ b/node_modules/inflight/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/inflight/README.md b/node_modules/inflight/README.md new file mode 100644 index 0000000..6dc8929 --- /dev/null +++ b/node_modules/inflight/README.md @@ -0,0 +1,37 @@ +# inflight + +Add callbacks to requests in flight to avoid async duplication + +## USAGE + +```javascript +var inflight = require('inflight') + +// some request that does some stuff +function req(key, callback) { + // key is any random string. like a url or filename or whatever. + // + // will return either a falsey value, indicating that the + // request for this key is already in flight, or a new callback + // which when called will call all callbacks passed to inflightk + // with the same key + callback = inflight(key, callback) + + // If we got a falsey value back, then there's already a req going + if (!callback) return + + // this is where you'd fetch the url or whatever + // callback is also once()-ified, so it can safely be assigned + // to multiple events etc. First call wins. + setTimeout(function() { + callback(null, key) + }, 100) +} + +// only assigns a single setTimeout +// when it dings, all cbs get called +req('foo', cb1) +req('foo', cb2) +req('foo', cb3) +req('foo', cb4) +``` diff --git a/node_modules/inflight/inflight.js b/node_modules/inflight/inflight.js new file mode 100644 index 0000000..48202b3 --- /dev/null +++ b/node_modules/inflight/inflight.js @@ -0,0 +1,54 @@ +var wrappy = require('wrappy') +var reqs = Object.create(null) +var once = require('once') + +module.exports = wrappy(inflight) + +function inflight (key, cb) { + if (reqs[key]) { + reqs[key].push(cb) + return null + } else { + reqs[key] = [cb] + return makeres(key) + } +} + +function makeres (key) { + return once(function RES () { + var cbs = reqs[key] + var len = cbs.length + var args = slice(arguments) + + // XXX It's somewhat ambiguous whether a new callback added in this + // pass should be queued for later execution if something in the + // list of callbacks throws, or if it should just be discarded. + // However, it's such an edge case that it hardly matters, and either + // choice is likely as surprising as the other. + // As it happens, we do go ahead and schedule it for later execution. + try { + for (var i = 0; i < len; i++) { + cbs[i].apply(null, args) + } + } finally { + if (cbs.length > len) { + // added more in the interim. + // de-zalgo, just in case, but don't call again. + cbs.splice(0, len) + process.nextTick(function () { + RES.apply(null, args) + }) + } else { + delete reqs[key] + } + } + }) +} + +function slice (args) { + var length = args.length + var array = [] + + for (var i = 0; i < length; i++) array[i] = args[i] + return array +} diff --git a/node_modules/inflight/package.json b/node_modules/inflight/package.json new file mode 100644 index 0000000..37dc612 --- /dev/null +++ b/node_modules/inflight/package.json @@ -0,0 +1,58 @@ +{ + "_from": "inflight@^1.0.4", + "_id": "inflight@1.0.6", + "_inBundle": false, + "_integrity": "sha1-Sb1jMdfQLQwJvJEKEHW6gWW1bfk=", + "_location": "/inflight", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "inflight@^1.0.4", + "name": "inflight", + "escapedName": "inflight", + "rawSpec": "^1.0.4", + "saveSpec": null, + "fetchSpec": "^1.0.4" + }, + "_requiredBy": [ + "/glob" + ], + "_resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", + "_shasum": "49bd6331d7d02d0c09bc910a1075ba8165b56df9", + "_spec": "inflight@^1.0.4", + "_where": "/Users/jessitron/code/jessitron/stringify-tree/node_modules/glob", + "author": { + "name": "Isaac Z. Schlueter", + "email": "i@izs.me", + "url": "http://blog.izs.me/" + }, + "bugs": { + "url": "https://github.com/isaacs/inflight/issues" + }, + "bundleDependencies": false, + "dependencies": { + "once": "^1.3.0", + "wrappy": "1" + }, + "deprecated": false, + "description": "Add callbacks to requests in flight to avoid async duplication", + "devDependencies": { + "tap": "^7.1.2" + }, + "files": [ + "inflight.js" + ], + "homepage": "https://github.com/isaacs/inflight", + "license": "ISC", + "main": "inflight.js", + "name": "inflight", + "repository": { + "type": "git", + "url": "git+https://github.com/npm/inflight.git" + }, + "scripts": { + "test": "tap test.js --100" + }, + "version": "1.0.6" +} diff --git a/node_modules/inherits/LICENSE b/node_modules/inherits/LICENSE new file mode 100644 index 0000000..dea3013 --- /dev/null +++ b/node_modules/inherits/LICENSE @@ -0,0 +1,16 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. + diff --git a/node_modules/inherits/README.md b/node_modules/inherits/README.md new file mode 100644 index 0000000..b1c5665 --- /dev/null +++ b/node_modules/inherits/README.md @@ -0,0 +1,42 @@ +Browser-friendly inheritance fully compatible with standard node.js +[inherits](http://nodejs.org/api/util.html#util_util_inherits_constructor_superconstructor). + +This package exports standard `inherits` from node.js `util` module in +node environment, but also provides alternative browser-friendly +implementation through [browser +field](https://gist.github.com/shtylman/4339901). Alternative +implementation is a literal copy of standard one located in standalone +module to avoid requiring of `util`. It also has a shim for old +browsers with no `Object.create` support. + +While keeping you sure you are using standard `inherits` +implementation in node.js environment, it allows bundlers such as +[browserify](https://github.com/substack/node-browserify) to not +include full `util` package to your client code if all you need is +just `inherits` function. It worth, because browser shim for `util` +package is large and `inherits` is often the single function you need +from it. + +It's recommended to use this package instead of +`require('util').inherits` for any code that has chances to be used +not only in node.js but in browser too. + +## usage + +```js +var inherits = require('inherits'); +// then use exactly as the standard one +``` + +## note on version ~1.0 + +Version ~1.0 had completely different motivation and is not compatible +neither with 2.0 nor with standard node.js `inherits`. + +If you are using version ~1.0 and planning to switch to ~2.0, be +careful: + +* new version uses `super_` instead of `super` for referencing + superclass +* new version overwrites current prototype while old one preserves any + existing fields on it diff --git a/node_modules/inherits/inherits.js b/node_modules/inherits/inherits.js new file mode 100644 index 0000000..3b94763 --- /dev/null +++ b/node_modules/inherits/inherits.js @@ -0,0 +1,7 @@ +try { + var util = require('util'); + if (typeof util.inherits !== 'function') throw ''; + module.exports = util.inherits; +} catch (e) { + module.exports = require('./inherits_browser.js'); +} diff --git a/node_modules/inherits/inherits_browser.js b/node_modules/inherits/inherits_browser.js new file mode 100644 index 0000000..c1e78a7 --- /dev/null +++ b/node_modules/inherits/inherits_browser.js @@ -0,0 +1,23 @@ +if (typeof Object.create === 'function') { + // implementation from standard node.js 'util' module + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); + }; +} else { + // old school shim for old browsers + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + var TempCtor = function () {} + TempCtor.prototype = superCtor.prototype + ctor.prototype = new TempCtor() + ctor.prototype.constructor = ctor + } +} diff --git a/node_modules/inherits/package.json b/node_modules/inherits/package.json new file mode 100644 index 0000000..9aaa3ea --- /dev/null +++ b/node_modules/inherits/package.json @@ -0,0 +1,61 @@ +{ + "_from": "inherits@2", + "_id": "inherits@2.0.3", + "_inBundle": false, + "_integrity": "sha1-Yzwsg+PaQqUC9SRmAiSA9CCCYd4=", + "_location": "/inherits", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "inherits@2", + "name": "inherits", + "escapedName": "inherits", + "rawSpec": "2", + "saveSpec": null, + "fetchSpec": "2" + }, + "_requiredBy": [ + "/glob" + ], + "_resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.3.tgz", + "_shasum": "633c2c83e3da42a502f52466022480f4208261de", + "_spec": "inherits@2", + "_where": "/Users/jessitron/code/jessitron/stringify-tree/node_modules/glob", + "browser": "./inherits_browser.js", + "bugs": { + "url": "https://github.com/isaacs/inherits/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "Browser-friendly inheritance fully compatible with standard node.js inherits()", + "devDependencies": { + "tap": "^7.1.0" + }, + "files": [ + "inherits.js", + "inherits_browser.js" + ], + "homepage": "https://github.com/isaacs/inherits#readme", + "keywords": [ + "inheritance", + "class", + "klass", + "oop", + "object-oriented", + "inherits", + "browser", + "browserify" + ], + "license": "ISC", + "main": "./inherits.js", + "name": "inherits", + "repository": { + "type": "git", + "url": "git://github.com/isaacs/inherits.git" + }, + "scripts": { + "test": "node test" + }, + "version": "2.0.3" +} diff --git a/node_modules/lodash.flatten/LICENSE b/node_modules/lodash.flatten/LICENSE new file mode 100644 index 0000000..e0c69d5 --- /dev/null +++ b/node_modules/lodash.flatten/LICENSE @@ -0,0 +1,47 @@ +Copyright jQuery Foundation and other contributors + +Based on Underscore.js, copyright Jeremy Ashkenas, +DocumentCloud and Investigative Reporters & Editors + +This software consists of voluntary contributions made by many +individuals. For exact contribution history, see the revision history +available at https://github.com/lodash/lodash + +The following license applies to all parts of this software except as +documented below: + +==== + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +==== + +Copyright and related rights for sample code are waived via CC0. Sample +code is defined as all source code displayed within the prose of the +documentation. + +CC0: http://creativecommons.org/publicdomain/zero/1.0/ + +==== + +Files located in the node_modules and vendor directories are externally +maintained libraries used by this software which have their own +licenses; we recommend you read them, as their terms may differ from the +terms above. diff --git a/node_modules/lodash.flatten/README.md b/node_modules/lodash.flatten/README.md new file mode 100644 index 0000000..526fa73 --- /dev/null +++ b/node_modules/lodash.flatten/README.md @@ -0,0 +1,18 @@ +# lodash.flatten v4.4.0 + +The [lodash](https://lodash.com/) method `_.flatten` exported as a [Node.js](https://nodejs.org/) module. + +## Installation + +Using npm: +```bash +$ {sudo -H} npm i -g npm +$ npm i --save lodash.flatten +``` + +In Node.js: +```js +var flatten = require('lodash.flatten'); +``` + +See the [documentation](https://lodash.com/docs#flatten) or [package source](https://github.com/lodash/lodash/blob/4.4.0-npm-packages/lodash.flatten) for more details. diff --git a/node_modules/lodash.flatten/index.js b/node_modules/lodash.flatten/index.js new file mode 100644 index 0000000..09ae7a6 --- /dev/null +++ b/node_modules/lodash.flatten/index.js @@ -0,0 +1,349 @@ +/** + * lodash (Custom Build) + * Build: `lodash modularize exports="npm" -o ./` + * Copyright jQuery Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + */ + +/** Used as references for various `Number` constants. */ +var MAX_SAFE_INTEGER = 9007199254740991; + +/** `Object#toString` result references. */ +var argsTag = '[object Arguments]', + funcTag = '[object Function]', + genTag = '[object GeneratorFunction]'; + +/** Detect free variable `global` from Node.js. */ +var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; + +/** Detect free variable `self`. */ +var freeSelf = typeof self == 'object' && self && self.Object === Object && self; + +/** Used as a reference to the global object. */ +var root = freeGlobal || freeSelf || Function('return this')(); + +/** + * Appends the elements of `values` to `array`. + * + * @private + * @param {Array} array The array to modify. + * @param {Array} values The values to append. + * @returns {Array} Returns `array`. + */ +function arrayPush(array, values) { + var index = -1, + length = values.length, + offset = array.length; + + while (++index < length) { + array[offset + index] = values[index]; + } + return array; +} + +/** Used for built-in method references. */ +var objectProto = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; + +/** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ +var objectToString = objectProto.toString; + +/** Built-in value references. */ +var Symbol = root.Symbol, + propertyIsEnumerable = objectProto.propertyIsEnumerable, + spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined; + +/** + * The base implementation of `_.flatten` with support for restricting flattening. + * + * @private + * @param {Array} array The array to flatten. + * @param {number} depth The maximum recursion depth. + * @param {boolean} [predicate=isFlattenable] The function invoked per iteration. + * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks. + * @param {Array} [result=[]] The initial result value. + * @returns {Array} Returns the new flattened array. + */ +function baseFlatten(array, depth, predicate, isStrict, result) { + var index = -1, + length = array.length; + + predicate || (predicate = isFlattenable); + result || (result = []); + + while (++index < length) { + var value = array[index]; + if (depth > 0 && predicate(value)) { + if (depth > 1) { + // Recursively flatten arrays (susceptible to call stack limits). + baseFlatten(value, depth - 1, predicate, isStrict, result); + } else { + arrayPush(result, value); + } + } else if (!isStrict) { + result[result.length] = value; + } + } + return result; +} + +/** + * Checks if `value` is a flattenable `arguments` object or array. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is flattenable, else `false`. + */ +function isFlattenable(value) { + return isArray(value) || isArguments(value) || + !!(spreadableSymbol && value && value[spreadableSymbol]); +} + +/** + * Flattens `array` a single level deep. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to flatten. + * @returns {Array} Returns the new flattened array. + * @example + * + * _.flatten([1, [2, [3, [4]], 5]]); + * // => [1, 2, [3, [4]], 5] + */ +function flatten(array) { + var length = array ? array.length : 0; + return length ? baseFlatten(array, 1) : []; +} + +/** + * Checks if `value` is likely an `arguments` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an `arguments` object, + * else `false`. + * @example + * + * _.isArguments(function() { return arguments; }()); + * // => true + * + * _.isArguments([1, 2, 3]); + * // => false + */ +function isArguments(value) { + // Safari 8.1 makes `arguments.callee` enumerable in strict mode. + return isArrayLikeObject(value) && hasOwnProperty.call(value, 'callee') && + (!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag); +} + +/** + * Checks if `value` is classified as an `Array` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array, else `false`. + * @example + * + * _.isArray([1, 2, 3]); + * // => true + * + * _.isArray(document.body.children); + * // => false + * + * _.isArray('abc'); + * // => false + * + * _.isArray(_.noop); + * // => false + */ +var isArray = Array.isArray; + +/** + * Checks if `value` is array-like. A value is considered array-like if it's + * not a function and has a `value.length` that's an integer greater than or + * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is array-like, else `false`. + * @example + * + * _.isArrayLike([1, 2, 3]); + * // => true + * + * _.isArrayLike(document.body.children); + * // => true + * + * _.isArrayLike('abc'); + * // => true + * + * _.isArrayLike(_.noop); + * // => false + */ +function isArrayLike(value) { + return value != null && isLength(value.length) && !isFunction(value); +} + +/** + * This method is like `_.isArrayLike` except that it also checks if `value` + * is an object. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array-like object, + * else `false`. + * @example + * + * _.isArrayLikeObject([1, 2, 3]); + * // => true + * + * _.isArrayLikeObject(document.body.children); + * // => true + * + * _.isArrayLikeObject('abc'); + * // => false + * + * _.isArrayLikeObject(_.noop); + * // => false + */ +function isArrayLikeObject(value) { + return isObjectLike(value) && isArrayLike(value); +} + +/** + * Checks if `value` is classified as a `Function` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a function, else `false`. + * @example + * + * _.isFunction(_); + * // => true + * + * _.isFunction(/abc/); + * // => false + */ +function isFunction(value) { + // The use of `Object#toString` avoids issues with the `typeof` operator + // in Safari 8-9 which returns 'object' for typed array and other constructors. + var tag = isObject(value) ? objectToString.call(value) : ''; + return tag == funcTag || tag == genTag; +} + +/** + * Checks if `value` is a valid array-like length. + * + * **Note:** This method is loosely based on + * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. + * @example + * + * _.isLength(3); + * // => true + * + * _.isLength(Number.MIN_VALUE); + * // => false + * + * _.isLength(Infinity); + * // => false + * + * _.isLength('3'); + * // => false + */ +function isLength(value) { + return typeof value == 'number' && + value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; +} + +/** + * Checks if `value` is the + * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) + * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an object, else `false`. + * @example + * + * _.isObject({}); + * // => true + * + * _.isObject([1, 2, 3]); + * // => true + * + * _.isObject(_.noop); + * // => true + * + * _.isObject(null); + * // => false + */ +function isObject(value) { + var type = typeof value; + return !!value && (type == 'object' || type == 'function'); +} + +/** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ +function isObjectLike(value) { + return !!value && typeof value == 'object'; +} + +module.exports = flatten; diff --git a/node_modules/lodash.flatten/package.json b/node_modules/lodash.flatten/package.json new file mode 100644 index 0000000..4012a72 --- /dev/null +++ b/node_modules/lodash.flatten/package.json @@ -0,0 +1,70 @@ +{ + "_from": "lodash.flatten", + "_id": "lodash.flatten@4.4.0", + "_inBundle": false, + "_integrity": "sha1-8xwiIlqWMtK7+OSt2+8kCqdlph8=", + "_location": "/lodash.flatten", + "_phantomChildren": {}, + "_requested": { + "type": "tag", + "registry": true, + "raw": "lodash.flatten", + "name": "lodash.flatten", + "escapedName": "lodash.flatten", + "rawSpec": "", + "saveSpec": null, + "fetchSpec": "latest" + }, + "_requiredBy": [ + "#USER", + "/" + ], + "_resolved": "https://registry.npmjs.org/lodash.flatten/-/lodash.flatten-4.4.0.tgz", + "_shasum": "f31c22225a9632d2bbf8e4addbef240aa765a61f", + "_spec": "lodash.flatten", + "_where": "/Users/jessitron/code/jessitron/stringify-tree", + "author": { + "name": "John-David Dalton", + "email": "john.david.dalton@gmail.com", + "url": "http://allyoucanleet.com/" + }, + "bugs": { + "url": "https://github.com/lodash/lodash/issues" + }, + "bundleDependencies": false, + "contributors": [ + { + "name": "John-David Dalton", + "email": "john.david.dalton@gmail.com", + "url": "http://allyoucanleet.com/" + }, + { + "name": "Blaine Bublitz", + "email": "blaine.bublitz@gmail.com", + "url": "https://github.com/phated" + }, + { + "name": "Mathias Bynens", + "email": "mathias@qiwi.be", + "url": "https://mathiasbynens.be/" + } + ], + "deprecated": false, + "description": "The lodash method `_.flatten` exported as a module.", + "homepage": "https://lodash.com/", + "icon": "https://lodash.com/icon.svg", + "keywords": [ + "lodash-modularized", + "flatten" + ], + "license": "MIT", + "name": "lodash.flatten", + "repository": { + "type": "git", + "url": "git+https://github.com/lodash/lodash.git" + }, + "scripts": { + "test": "echo \"See https://travis-ci.org/lodash/lodash-cli for testing details.\"" + }, + "version": "4.4.0" +} diff --git a/node_modules/make-error/LICENSE b/node_modules/make-error/LICENSE new file mode 100644 index 0000000..9dcf797 --- /dev/null +++ b/node_modules/make-error/LICENSE @@ -0,0 +1,5 @@ +Copyright 2014 Julien Fontanet + +Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/make-error/README.md b/node_modules/make-error/README.md new file mode 100644 index 0000000..66d6ffa --- /dev/null +++ b/node_modules/make-error/README.md @@ -0,0 +1,111 @@ +# make-error [![Build Status](https://img.shields.io/travis/JsCommunity/make-error/master.svg)](http://travis-ci.org/JsCommunity/make-error) + +> Make your own error types! + + +## Features + +- Compatible Node & browsers +- `instanceof` support +- `error.name` & `error.stack` support +- compatible with [CSP](https://en.wikipedia.org/wiki/Content_Security_Policy) (i.e. no `eval()`) + +## Installation + +### Node & [Browserify](http://browserify.org/)/[Webpack](https://webpack.js.org/) + +Installation of the [npm package](https://npmjs.org/package/make-error): + +``` +> npm install --save make-error +``` + +Then require the package: + +```javascript +var makeError = require('make-error'); +``` + +### Browser + +You can directly use the build provided at [unpkg.com](https://unpkg.com): + +```html + +``` + +## Usage + +### Basic named error + +```javascript +var CustomError = makeError('CustomError') + +// Parameters are forwarded to the super class (here Error). +throw new CustomError('a message') +``` + +### Advanced error class + +```javascript +function CustomError (customValue) { + CustomError.super.call(this, 'custom error message') + + this.customValue = customValue +} +makeError(CustomError) + +// Feel free to extend the prototype. +CustomError.prototype.myMethod = function CustomError$myMethod () { + console.log('CustomError.myMethod (%s, %s)', this.code, this.message) +} + +//----- + +try { + throw new CustomError(42) +} catch (error) { + error.myMethod() +} +``` + +### Specialized error + +```javascript +var SpecializedError = makeError('SpecializedError', CustomError); + +throw new SpecializedError(42); +``` + +### Inheritance + +> Best for ES2015+. + +```javascript +import {BaseError} from 'make-error' + +class CustomError extends BaseError { + constructor () { + super('custom error message') + } +} +``` + +## Related + +- [make-error-cause](https://www.npmjs.com/package/make-error-cause): Make your own error types, with a cause! + +## Contributions + +Contributions are *very* welcomed, either on the documentation or on +the code. + +You may: + +- report any [issue](https://github.com/JsCommunity/make-error/issues) + you've encountered; +- fork and create a pull request. + +## License + +ISC © [Julien Fontanet](http://julien.isonoe.net) diff --git a/node_modules/make-error/dist/make-error.js b/node_modules/make-error/dist/make-error.js new file mode 100644 index 0000000..7068a7e --- /dev/null +++ b/node_modules/make-error/dist/make-error.js @@ -0,0 +1 @@ +!function(f){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=f();else if("function"==typeof define&&define.amd)define([],f);else{("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).makeError=f()}}(function(){return function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a="function"==typeof require&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n||e)},l,l.exports,e,t,n,r)}return n[o].exports}for(var i="function"==typeof require&&require,o=0;o; + +/** + * Set the constructor prototype to `BaseError`. + */ +declare function makeError(super_: { new (...args: any[]): T }): makeError.Constructor; + +/** + * Create a specialized error instance. + */ +declare function makeError(name: string | Function, super_: K): K & makeError.SpecializedConstructor; + +declare module makeError { + /** + * Use with ES2015+ inheritance. + */ + export class BaseError implements Error { + message: string; + name: string; + stack: string; + + constructor(message?: string); + } + + export interface Constructor { + new (message?: string): T; + super_: any + prototype: T + } + + export interface SpecializedConstructor { + super_: any + prototype: T + } +} + +export = makeError; diff --git a/node_modules/make-error/index.js b/node_modules/make-error/index.js new file mode 100644 index 0000000..9fbf6f0 --- /dev/null +++ b/node_modules/make-error/index.js @@ -0,0 +1,147 @@ +// ISC @ Julien Fontanet + +'use strict' + +// =================================================================== + +var construct = typeof Reflect !== 'undefined' ? Reflect.construct : undefined +var defineProperty = Object.defineProperty + +// ------------------------------------------------------------------- + +var captureStackTrace = Error.captureStackTrace +if (captureStackTrace === undefined) { + captureStackTrace = function captureStackTrace (error) { + var container = new Error() + + defineProperty(error, 'stack', { + configurable: true, + get: function getStack () { + var stack = container.stack + + // Replace property with value for faster future accesses. + defineProperty(this, 'stack', { + configurable: true, + value: stack, + writable: true + }) + + return stack + }, + set: function setStack (stack) { + defineProperty(error, 'stack', { + configurable: true, + value: stack, + writable: true + }) + } + }) + } +} + +// ------------------------------------------------------------------- + +function BaseError (message) { + if (message !== undefined) { + defineProperty(this, 'message', { + configurable: true, + value: message, + writable: true + }) + } + + var cname = this.constructor.name + if ( + cname !== undefined && + cname !== this.name + ) { + defineProperty(this, 'name', { + configurable: true, + value: cname, + writable: true + }) + } + + captureStackTrace(this, this.constructor) +} + +BaseError.prototype = Object.create(Error.prototype, { + // See: https://github.com/JsCommunity/make-error/issues/4 + constructor: { + configurable: true, + value: BaseError, + writable: true + } +}) + +// ------------------------------------------------------------------- + +// Sets the name of a function if possible (depends of the JS engine). +var setFunctionName = (function () { + function setFunctionName (fn, name) { + return defineProperty(fn, 'name', { + configurable: true, + value: name + }) + } + try { + var f = function () {} + setFunctionName(f, 'foo') + if (f.name === 'foo') { + return setFunctionName + } + } catch (_) {} +})() + +// ------------------------------------------------------------------- + +function makeError (constructor, super_) { + if (super_ == null || super_ === Error) { + super_ = BaseError + } else if (typeof super_ !== 'function') { + throw new TypeError('super_ should be a function') + } + + var name + if (typeof constructor === 'string') { + name = constructor + constructor = construct !== undefined + ? function () { return construct(super_, arguments, this.constructor) } + : function () { super_.apply(this, arguments) } + + // If the name can be set, do it once and for all. + if (setFunctionName !== undefined) { + setFunctionName(constructor, name) + name = undefined + } + } else if (typeof constructor !== 'function') { + throw new TypeError('constructor should be either a string or a function') + } + + // Also register the super constructor also as `constructor.super_` just + // like Node's `util.inherits()`. + constructor.super_ = constructor['super'] = super_ + + var properties = { + constructor: { + configurable: true, + value: constructor, + writable: true + } + } + + // If the name could not be set on the constructor, set it on the + // prototype. + if (name !== undefined) { + properties.name = { + configurable: true, + value: name, + writable: true + } + } + constructor.prototype = Object.create(super_.prototype, properties) + + return constructor +} +exports = module.exports = makeError +exports.BaseError = BaseError diff --git a/node_modules/make-error/package.json b/node_modules/make-error/package.json new file mode 100644 index 0000000..bdbf4e0 --- /dev/null +++ b/node_modules/make-error/package.json @@ -0,0 +1,80 @@ +{ + "_from": "make-error@^1.1.1", + "_id": "make-error@1.3.5", + "_inBundle": false, + "_integrity": "sha512-c3sIjNUow0+8swNwVpqoH4YCShKNFkMaw6oH1mNS2haDZQqkeZFlHS3dhoeEbKKmJB4vXpJucU6oH75aDYeE9g==", + "_location": "/make-error", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "make-error@^1.1.1", + "name": "make-error", + "escapedName": "make-error", + "rawSpec": "^1.1.1", + "saveSpec": null, + "fetchSpec": "^1.1.1" + }, + "_requiredBy": [ + "/ts-node" + ], + "_resolved": "https://registry.npmjs.org/make-error/-/make-error-1.3.5.tgz", + "_shasum": "efe4e81f6db28cadd605c70f29c831b58ef776c8", + "_spec": "make-error@^1.1.1", + "_where": "/Users/jessitron/code/jessitron/stringify-tree/node_modules/ts-node", + "author": { + "name": "Julien Fontanet", + "email": "julien.fontanet@isonoe.net" + }, + "bugs": { + "url": "https://github.com/JsCommunity/make-error/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "Make your own error types!", + "devDependencies": { + "browserify": "^14.5.0", + "husky": "^0.14.3", + "jest": "^20", + "standard": "^10.0.3", + "uglify-js": "^3.3.2" + }, + "files": [ + "dist/", + "index.js", + "index.d.ts" + ], + "homepage": "https://github.com/JsCommunity/make-error", + "jest": { + "testEnvironment": "node" + }, + "keywords": [ + "create", + "custom", + "derive", + "error", + "errors", + "extend", + "extending", + "extension", + "factory", + "inherit", + "make", + "subclass" + ], + "license": "ISC", + "main": "index.js", + "name": "make-error", + "repository": { + "type": "git", + "url": "git://github.com/JsCommunity/make-error.git" + }, + "scripts": { + "commitmsg": "yarn test", + "dev-test": "jest --watch", + "prepublishOnly": "mkdir -p dist && browserify -s makeError index.js | uglifyjs -c > dist/make-error.js", + "pretest": "standard", + "test": "jest" + }, + "version": "1.3.5" +} diff --git a/node_modules/minimatch/LICENSE b/node_modules/minimatch/LICENSE new file mode 100644 index 0000000..19129e3 --- /dev/null +++ b/node_modules/minimatch/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/minimatch/README.md b/node_modules/minimatch/README.md new file mode 100644 index 0000000..ad72b81 --- /dev/null +++ b/node_modules/minimatch/README.md @@ -0,0 +1,209 @@ +# minimatch + +A minimal matching utility. + +[![Build Status](https://secure.travis-ci.org/isaacs/minimatch.svg)](http://travis-ci.org/isaacs/minimatch) + + +This is the matching library used internally by npm. + +It works by converting glob expressions into JavaScript `RegExp` +objects. + +## Usage + +```javascript +var minimatch = require("minimatch") + +minimatch("bar.foo", "*.foo") // true! +minimatch("bar.foo", "*.bar") // false! +minimatch("bar.foo", "*.+(bar|foo)", { debug: true }) // true, and noisy! +``` + +## Features + +Supports these glob features: + +* Brace Expansion +* Extended glob matching +* "Globstar" `**` matching + +See: + +* `man sh` +* `man bash` +* `man 3 fnmatch` +* `man 5 gitignore` + +## Minimatch Class + +Create a minimatch object by instantiating the `minimatch.Minimatch` class. + +```javascript +var Minimatch = require("minimatch").Minimatch +var mm = new Minimatch(pattern, options) +``` + +### Properties + +* `pattern` The original pattern the minimatch object represents. +* `options` The options supplied to the constructor. +* `set` A 2-dimensional array of regexp or string expressions. + Each row in the + array corresponds to a brace-expanded pattern. Each item in the row + corresponds to a single path-part. For example, the pattern + `{a,b/c}/d` would expand to a set of patterns like: + + [ [ a, d ] + , [ b, c, d ] ] + + If a portion of the pattern doesn't have any "magic" in it + (that is, it's something like `"foo"` rather than `fo*o?`), then it + will be left as a string rather than converted to a regular + expression. + +* `regexp` Created by the `makeRe` method. A single regular expression + expressing the entire pattern. This is useful in cases where you wish + to use the pattern somewhat like `fnmatch(3)` with `FNM_PATH` enabled. +* `negate` True if the pattern is negated. +* `comment` True if the pattern is a comment. +* `empty` True if the pattern is `""`. + +### Methods + +* `makeRe` Generate the `regexp` member if necessary, and return it. + Will return `false` if the pattern is invalid. +* `match(fname)` Return true if the filename matches the pattern, or + false otherwise. +* `matchOne(fileArray, patternArray, partial)` Take a `/`-split + filename, and match it against a single row in the `regExpSet`. This + method is mainly for internal use, but is exposed so that it can be + used by a glob-walker that needs to avoid excessive filesystem calls. + +All other methods are internal, and will be called as necessary. + +### minimatch(path, pattern, options) + +Main export. Tests a path against the pattern using the options. + +```javascript +var isJS = minimatch(file, "*.js", { matchBase: true }) +``` + +### minimatch.filter(pattern, options) + +Returns a function that tests its +supplied argument, suitable for use with `Array.filter`. Example: + +```javascript +var javascripts = fileList.filter(minimatch.filter("*.js", {matchBase: true})) +``` + +### minimatch.match(list, pattern, options) + +Match against the list of +files, in the style of fnmatch or glob. If nothing is matched, and +options.nonull is set, then return a list containing the pattern itself. + +```javascript +var javascripts = minimatch.match(fileList, "*.js", {matchBase: true})) +``` + +### minimatch.makeRe(pattern, options) + +Make a regular expression object from the pattern. + +## Options + +All options are `false` by default. + +### debug + +Dump a ton of stuff to stderr. + +### nobrace + +Do not expand `{a,b}` and `{1..3}` brace sets. + +### noglobstar + +Disable `**` matching against multiple folder names. + +### dot + +Allow patterns to match filenames starting with a period, even if +the pattern does not explicitly have a period in that spot. + +Note that by default, `a/**/b` will **not** match `a/.d/b`, unless `dot` +is set. + +### noext + +Disable "extglob" style patterns like `+(a|b)`. + +### nocase + +Perform a case-insensitive match. + +### nonull + +When a match is not found by `minimatch.match`, return a list containing +the pattern itself if this option is set. When not set, an empty list +is returned if there are no matches. + +### matchBase + +If set, then patterns without slashes will be matched +against the basename of the path if it contains slashes. For example, +`a?b` would match the path `/xyz/123/acb`, but not `/xyz/acb/123`. + +### nocomment + +Suppress the behavior of treating `#` at the start of a pattern as a +comment. + +### nonegate + +Suppress the behavior of treating a leading `!` character as negation. + +### flipNegate + +Returns from negate expressions the same as if they were not negated. +(Ie, true on a hit, false on a miss.) + + +## Comparisons to other fnmatch/glob implementations + +While strict compliance with the existing standards is a worthwhile +goal, some discrepancies exist between minimatch and other +implementations, and are intentional. + +If the pattern starts with a `!` character, then it is negated. Set the +`nonegate` flag to suppress this behavior, and treat leading `!` +characters normally. This is perhaps relevant if you wish to start the +pattern with a negative extglob pattern like `!(a|B)`. Multiple `!` +characters at the start of a pattern will negate the pattern multiple +times. + +If a pattern starts with `#`, then it is treated as a comment, and +will not match anything. Use `\#` to match a literal `#` at the +start of a line, or set the `nocomment` flag to suppress this behavior. + +The double-star character `**` is supported by default, unless the +`noglobstar` flag is set. This is supported in the manner of bsdglob +and bash 4.1, where `**` only has special significance if it is the only +thing in a path part. That is, `a/**/b` will match `a/x/y/b`, but +`a/**b` will not. + +If an escaped pattern has no matches, and the `nonull` flag is set, +then minimatch.match returns the pattern as-provided, rather than +interpreting the character escapes. For example, +`minimatch.match([], "\\*a\\?")` will return `"\\*a\\?"` rather than +`"*a?"`. This is akin to setting the `nullglob` option in bash, except +that it does not resolve escaped pattern characters. + +If brace expansion is not disabled, then it is performed before any +other interpretation of the glob pattern. Thus, a pattern like +`+(a|{b),c)}`, which would not be valid in bash or zsh, is expanded +**first** into the set of `+(a|b)` and `+(a|c)`, and those patterns are +checked for validity. Since those two are valid, matching proceeds. diff --git a/node_modules/minimatch/minimatch.js b/node_modules/minimatch/minimatch.js new file mode 100644 index 0000000..5b5f8cf --- /dev/null +++ b/node_modules/minimatch/minimatch.js @@ -0,0 +1,923 @@ +module.exports = minimatch +minimatch.Minimatch = Minimatch + +var path = { sep: '/' } +try { + path = require('path') +} catch (er) {} + +var GLOBSTAR = minimatch.GLOBSTAR = Minimatch.GLOBSTAR = {} +var expand = require('brace-expansion') + +var plTypes = { + '!': { open: '(?:(?!(?:', close: '))[^/]*?)'}, + '?': { open: '(?:', close: ')?' }, + '+': { open: '(?:', close: ')+' }, + '*': { open: '(?:', close: ')*' }, + '@': { open: '(?:', close: ')' } +} + +// any single thing other than / +// don't need to escape / when using new RegExp() +var qmark = '[^/]' + +// * => any number of characters +var star = qmark + '*?' + +// ** when dots are allowed. Anything goes, except .. and . +// not (^ or / followed by one or two dots followed by $ or /), +// followed by anything, any number of times. +var twoStarDot = '(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?' + +// not a ^ or / followed by a dot, +// followed by anything, any number of times. +var twoStarNoDot = '(?:(?!(?:\\\/|^)\\.).)*?' + +// characters that need to be escaped in RegExp. +var reSpecials = charSet('().*{}+?[]^$\\!') + +// "abc" -> { a:true, b:true, c:true } +function charSet (s) { + return s.split('').reduce(function (set, c) { + set[c] = true + return set + }, {}) +} + +// normalizes slashes. +var slashSplit = /\/+/ + +minimatch.filter = filter +function filter (pattern, options) { + options = options || {} + return function (p, i, list) { + return minimatch(p, pattern, options) + } +} + +function ext (a, b) { + a = a || {} + b = b || {} + var t = {} + Object.keys(b).forEach(function (k) { + t[k] = b[k] + }) + Object.keys(a).forEach(function (k) { + t[k] = a[k] + }) + return t +} + +minimatch.defaults = function (def) { + if (!def || !Object.keys(def).length) return minimatch + + var orig = minimatch + + var m = function minimatch (p, pattern, options) { + return orig.minimatch(p, pattern, ext(def, options)) + } + + m.Minimatch = function Minimatch (pattern, options) { + return new orig.Minimatch(pattern, ext(def, options)) + } + + return m +} + +Minimatch.defaults = function (def) { + if (!def || !Object.keys(def).length) return Minimatch + return minimatch.defaults(def).Minimatch +} + +function minimatch (p, pattern, options) { + if (typeof pattern !== 'string') { + throw new TypeError('glob pattern string required') + } + + if (!options) options = {} + + // shortcut: comments match nothing. + if (!options.nocomment && pattern.charAt(0) === '#') { + return false + } + + // "" only matches "" + if (pattern.trim() === '') return p === '' + + return new Minimatch(pattern, options).match(p) +} + +function Minimatch (pattern, options) { + if (!(this instanceof Minimatch)) { + return new Minimatch(pattern, options) + } + + if (typeof pattern !== 'string') { + throw new TypeError('glob pattern string required') + } + + if (!options) options = {} + pattern = pattern.trim() + + // windows support: need to use /, not \ + if (path.sep !== '/') { + pattern = pattern.split(path.sep).join('/') + } + + this.options = options + this.set = [] + this.pattern = pattern + this.regexp = null + this.negate = false + this.comment = false + this.empty = false + + // make the set of regexps etc. + this.make() +} + +Minimatch.prototype.debug = function () {} + +Minimatch.prototype.make = make +function make () { + // don't do it more than once. + if (this._made) return + + var pattern = this.pattern + var options = this.options + + // empty patterns and comments match nothing. + if (!options.nocomment && pattern.charAt(0) === '#') { + this.comment = true + return + } + if (!pattern) { + this.empty = true + return + } + + // step 1: figure out negation, etc. + this.parseNegate() + + // step 2: expand braces + var set = this.globSet = this.braceExpand() + + if (options.debug) this.debug = console.error + + this.debug(this.pattern, set) + + // step 3: now we have a set, so turn each one into a series of path-portion + // matching patterns. + // These will be regexps, except in the case of "**", which is + // set to the GLOBSTAR object for globstar behavior, + // and will not contain any / characters + set = this.globParts = set.map(function (s) { + return s.split(slashSplit) + }) + + this.debug(this.pattern, set) + + // glob --> regexps + set = set.map(function (s, si, set) { + return s.map(this.parse, this) + }, this) + + this.debug(this.pattern, set) + + // filter out everything that didn't compile properly. + set = set.filter(function (s) { + return s.indexOf(false) === -1 + }) + + this.debug(this.pattern, set) + + this.set = set +} + +Minimatch.prototype.parseNegate = parseNegate +function parseNegate () { + var pattern = this.pattern + var negate = false + var options = this.options + var negateOffset = 0 + + if (options.nonegate) return + + for (var i = 0, l = pattern.length + ; i < l && pattern.charAt(i) === '!' + ; i++) { + negate = !negate + negateOffset++ + } + + if (negateOffset) this.pattern = pattern.substr(negateOffset) + this.negate = negate +} + +// Brace expansion: +// a{b,c}d -> abd acd +// a{b,}c -> abc ac +// a{0..3}d -> a0d a1d a2d a3d +// a{b,c{d,e}f}g -> abg acdfg acefg +// a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg +// +// Invalid sets are not expanded. +// a{2..}b -> a{2..}b +// a{b}c -> a{b}c +minimatch.braceExpand = function (pattern, options) { + return braceExpand(pattern, options) +} + +Minimatch.prototype.braceExpand = braceExpand + +function braceExpand (pattern, options) { + if (!options) { + if (this instanceof Minimatch) { + options = this.options + } else { + options = {} + } + } + + pattern = typeof pattern === 'undefined' + ? this.pattern : pattern + + if (typeof pattern === 'undefined') { + throw new TypeError('undefined pattern') + } + + if (options.nobrace || + !pattern.match(/\{.*\}/)) { + // shortcut. no need to expand. + return [pattern] + } + + return expand(pattern) +} + +// parse a component of the expanded set. +// At this point, no pattern may contain "/" in it +// so we're going to return a 2d array, where each entry is the full +// pattern, split on '/', and then turned into a regular expression. +// A regexp is made at the end which joins each array with an +// escaped /, and another full one which joins each regexp with |. +// +// Following the lead of Bash 4.1, note that "**" only has special meaning +// when it is the *only* thing in a path portion. Otherwise, any series +// of * is equivalent to a single *. Globstar behavior is enabled by +// default, and can be disabled by setting options.noglobstar. +Minimatch.prototype.parse = parse +var SUBPARSE = {} +function parse (pattern, isSub) { + if (pattern.length > 1024 * 64) { + throw new TypeError('pattern is too long') + } + + var options = this.options + + // shortcuts + if (!options.noglobstar && pattern === '**') return GLOBSTAR + if (pattern === '') return '' + + var re = '' + var hasMagic = !!options.nocase + var escaping = false + // ? => one single character + var patternListStack = [] + var negativeLists = [] + var stateChar + var inClass = false + var reClassStart = -1 + var classStart = -1 + // . and .. never match anything that doesn't start with ., + // even when options.dot is set. + var patternStart = pattern.charAt(0) === '.' ? '' // anything + // not (start or / followed by . or .. followed by / or end) + : options.dot ? '(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))' + : '(?!\\.)' + var self = this + + function clearStateChar () { + if (stateChar) { + // we had some state-tracking character + // that wasn't consumed by this pass. + switch (stateChar) { + case '*': + re += star + hasMagic = true + break + case '?': + re += qmark + hasMagic = true + break + default: + re += '\\' + stateChar + break + } + self.debug('clearStateChar %j %j', stateChar, re) + stateChar = false + } + } + + for (var i = 0, len = pattern.length, c + ; (i < len) && (c = pattern.charAt(i)) + ; i++) { + this.debug('%s\t%s %s %j', pattern, i, re, c) + + // skip over any that are escaped. + if (escaping && reSpecials[c]) { + re += '\\' + c + escaping = false + continue + } + + switch (c) { + case '/': + // completely not allowed, even escaped. + // Should already be path-split by now. + return false + + case '\\': + clearStateChar() + escaping = true + continue + + // the various stateChar values + // for the "extglob" stuff. + case '?': + case '*': + case '+': + case '@': + case '!': + this.debug('%s\t%s %s %j <-- stateChar', pattern, i, re, c) + + // all of those are literals inside a class, except that + // the glob [!a] means [^a] in regexp + if (inClass) { + this.debug(' in class') + if (c === '!' && i === classStart + 1) c = '^' + re += c + continue + } + + // if we already have a stateChar, then it means + // that there was something like ** or +? in there. + // Handle the stateChar, then proceed with this one. + self.debug('call clearStateChar %j', stateChar) + clearStateChar() + stateChar = c + // if extglob is disabled, then +(asdf|foo) isn't a thing. + // just clear the statechar *now*, rather than even diving into + // the patternList stuff. + if (options.noext) clearStateChar() + continue + + case '(': + if (inClass) { + re += '(' + continue + } + + if (!stateChar) { + re += '\\(' + continue + } + + patternListStack.push({ + type: stateChar, + start: i - 1, + reStart: re.length, + open: plTypes[stateChar].open, + close: plTypes[stateChar].close + }) + // negation is (?:(?!js)[^/]*) + re += stateChar === '!' ? '(?:(?!(?:' : '(?:' + this.debug('plType %j %j', stateChar, re) + stateChar = false + continue + + case ')': + if (inClass || !patternListStack.length) { + re += '\\)' + continue + } + + clearStateChar() + hasMagic = true + var pl = patternListStack.pop() + // negation is (?:(?!js)[^/]*) + // The others are (?:) + re += pl.close + if (pl.type === '!') { + negativeLists.push(pl) + } + pl.reEnd = re.length + continue + + case '|': + if (inClass || !patternListStack.length || escaping) { + re += '\\|' + escaping = false + continue + } + + clearStateChar() + re += '|' + continue + + // these are mostly the same in regexp and glob + case '[': + // swallow any state-tracking char before the [ + clearStateChar() + + if (inClass) { + re += '\\' + c + continue + } + + inClass = true + classStart = i + reClassStart = re.length + re += c + continue + + case ']': + // a right bracket shall lose its special + // meaning and represent itself in + // a bracket expression if it occurs + // first in the list. -- POSIX.2 2.8.3.2 + if (i === classStart + 1 || !inClass) { + re += '\\' + c + escaping = false + continue + } + + // handle the case where we left a class open. + // "[z-a]" is valid, equivalent to "\[z-a\]" + if (inClass) { + // split where the last [ was, make sure we don't have + // an invalid re. if so, re-walk the contents of the + // would-be class to re-translate any characters that + // were passed through as-is + // TODO: It would probably be faster to determine this + // without a try/catch and a new RegExp, but it's tricky + // to do safely. For now, this is safe and works. + var cs = pattern.substring(classStart + 1, i) + try { + RegExp('[' + cs + ']') + } catch (er) { + // not a valid class! + var sp = this.parse(cs, SUBPARSE) + re = re.substr(0, reClassStart) + '\\[' + sp[0] + '\\]' + hasMagic = hasMagic || sp[1] + inClass = false + continue + } + } + + // finish up the class. + hasMagic = true + inClass = false + re += c + continue + + default: + // swallow any state char that wasn't consumed + clearStateChar() + + if (escaping) { + // no need + escaping = false + } else if (reSpecials[c] + && !(c === '^' && inClass)) { + re += '\\' + } + + re += c + + } // switch + } // for + + // handle the case where we left a class open. + // "[abc" is valid, equivalent to "\[abc" + if (inClass) { + // split where the last [ was, and escape it + // this is a huge pita. We now have to re-walk + // the contents of the would-be class to re-translate + // any characters that were passed through as-is + cs = pattern.substr(classStart + 1) + sp = this.parse(cs, SUBPARSE) + re = re.substr(0, reClassStart) + '\\[' + sp[0] + hasMagic = hasMagic || sp[1] + } + + // handle the case where we had a +( thing at the *end* + // of the pattern. + // each pattern list stack adds 3 chars, and we need to go through + // and escape any | chars that were passed through as-is for the regexp. + // Go through and escape them, taking care not to double-escape any + // | chars that were already escaped. + for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) { + var tail = re.slice(pl.reStart + pl.open.length) + this.debug('setting tail', re, pl) + // maybe some even number of \, then maybe 1 \, followed by a | + tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, function (_, $1, $2) { + if (!$2) { + // the | isn't already escaped, so escape it. + $2 = '\\' + } + + // need to escape all those slashes *again*, without escaping the + // one that we need for escaping the | character. As it works out, + // escaping an even number of slashes can be done by simply repeating + // it exactly after itself. That's why this trick works. + // + // I am sorry that you have to see this. + return $1 + $1 + $2 + '|' + }) + + this.debug('tail=%j\n %s', tail, tail, pl, re) + var t = pl.type === '*' ? star + : pl.type === '?' ? qmark + : '\\' + pl.type + + hasMagic = true + re = re.slice(0, pl.reStart) + t + '\\(' + tail + } + + // handle trailing things that only matter at the very end. + clearStateChar() + if (escaping) { + // trailing \\ + re += '\\\\' + } + + // only need to apply the nodot start if the re starts with + // something that could conceivably capture a dot + var addPatternStart = false + switch (re.charAt(0)) { + case '.': + case '[': + case '(': addPatternStart = true + } + + // Hack to work around lack of negative lookbehind in JS + // A pattern like: *.!(x).!(y|z) needs to ensure that a name + // like 'a.xyz.yz' doesn't match. So, the first negative + // lookahead, has to look ALL the way ahead, to the end of + // the pattern. + for (var n = negativeLists.length - 1; n > -1; n--) { + var nl = negativeLists[n] + + var nlBefore = re.slice(0, nl.reStart) + var nlFirst = re.slice(nl.reStart, nl.reEnd - 8) + var nlLast = re.slice(nl.reEnd - 8, nl.reEnd) + var nlAfter = re.slice(nl.reEnd) + + nlLast += nlAfter + + // Handle nested stuff like *(*.js|!(*.json)), where open parens + // mean that we should *not* include the ) in the bit that is considered + // "after" the negated section. + var openParensBefore = nlBefore.split('(').length - 1 + var cleanAfter = nlAfter + for (i = 0; i < openParensBefore; i++) { + cleanAfter = cleanAfter.replace(/\)[+*?]?/, '') + } + nlAfter = cleanAfter + + var dollar = '' + if (nlAfter === '' && isSub !== SUBPARSE) { + dollar = '$' + } + var newRe = nlBefore + nlFirst + nlAfter + dollar + nlLast + re = newRe + } + + // if the re is not "" at this point, then we need to make sure + // it doesn't match against an empty path part. + // Otherwise a/* will match a/, which it should not. + if (re !== '' && hasMagic) { + re = '(?=.)' + re + } + + if (addPatternStart) { + re = patternStart + re + } + + // parsing just a piece of a larger pattern. + if (isSub === SUBPARSE) { + return [re, hasMagic] + } + + // skip the regexp for non-magical patterns + // unescape anything in it, though, so that it'll be + // an exact match against a file etc. + if (!hasMagic) { + return globUnescape(pattern) + } + + var flags = options.nocase ? 'i' : '' + try { + var regExp = new RegExp('^' + re + '$', flags) + } catch (er) { + // If it was an invalid regular expression, then it can't match + // anything. This trick looks for a character after the end of + // the string, which is of course impossible, except in multi-line + // mode, but it's not a /m regex. + return new RegExp('$.') + } + + regExp._glob = pattern + regExp._src = re + + return regExp +} + +minimatch.makeRe = function (pattern, options) { + return new Minimatch(pattern, options || {}).makeRe() +} + +Minimatch.prototype.makeRe = makeRe +function makeRe () { + if (this.regexp || this.regexp === false) return this.regexp + + // at this point, this.set is a 2d array of partial + // pattern strings, or "**". + // + // It's better to use .match(). This function shouldn't + // be used, really, but it's pretty convenient sometimes, + // when you just want to work with a regex. + var set = this.set + + if (!set.length) { + this.regexp = false + return this.regexp + } + var options = this.options + + var twoStar = options.noglobstar ? star + : options.dot ? twoStarDot + : twoStarNoDot + var flags = options.nocase ? 'i' : '' + + var re = set.map(function (pattern) { + return pattern.map(function (p) { + return (p === GLOBSTAR) ? twoStar + : (typeof p === 'string') ? regExpEscape(p) + : p._src + }).join('\\\/') + }).join('|') + + // must match entire pattern + // ending in a * or ** will make it less strict. + re = '^(?:' + re + ')$' + + // can match anything, as long as it's not this. + if (this.negate) re = '^(?!' + re + ').*$' + + try { + this.regexp = new RegExp(re, flags) + } catch (ex) { + this.regexp = false + } + return this.regexp +} + +minimatch.match = function (list, pattern, options) { + options = options || {} + var mm = new Minimatch(pattern, options) + list = list.filter(function (f) { + return mm.match(f) + }) + if (mm.options.nonull && !list.length) { + list.push(pattern) + } + return list +} + +Minimatch.prototype.match = match +function match (f, partial) { + this.debug('match', f, this.pattern) + // short-circuit in the case of busted things. + // comments, etc. + if (this.comment) return false + if (this.empty) return f === '' + + if (f === '/' && partial) return true + + var options = this.options + + // windows: need to use /, not \ + if (path.sep !== '/') { + f = f.split(path.sep).join('/') + } + + // treat the test path as a set of pathparts. + f = f.split(slashSplit) + this.debug(this.pattern, 'split', f) + + // just ONE of the pattern sets in this.set needs to match + // in order for it to be valid. If negating, then just one + // match means that we have failed. + // Either way, return on the first hit. + + var set = this.set + this.debug(this.pattern, 'set', set) + + // Find the basename of the path by looking for the last non-empty segment + var filename + var i + for (i = f.length - 1; i >= 0; i--) { + filename = f[i] + if (filename) break + } + + for (i = 0; i < set.length; i++) { + var pattern = set[i] + var file = f + if (options.matchBase && pattern.length === 1) { + file = [filename] + } + var hit = this.matchOne(file, pattern, partial) + if (hit) { + if (options.flipNegate) return true + return !this.negate + } + } + + // didn't get any hits. this is success if it's a negative + // pattern, failure otherwise. + if (options.flipNegate) return false + return this.negate +} + +// set partial to true to test if, for example, +// "/a/b" matches the start of "/*/b/*/d" +// Partial means, if you run out of file before you run +// out of pattern, then that's fine, as long as all +// the parts match. +Minimatch.prototype.matchOne = function (file, pattern, partial) { + var options = this.options + + this.debug('matchOne', + { 'this': this, file: file, pattern: pattern }) + + this.debug('matchOne', file.length, pattern.length) + + for (var fi = 0, + pi = 0, + fl = file.length, + pl = pattern.length + ; (fi < fl) && (pi < pl) + ; fi++, pi++) { + this.debug('matchOne loop') + var p = pattern[pi] + var f = file[fi] + + this.debug(pattern, p, f) + + // should be impossible. + // some invalid regexp stuff in the set. + if (p === false) return false + + if (p === GLOBSTAR) { + this.debug('GLOBSTAR', [pattern, p, f]) + + // "**" + // a/**/b/**/c would match the following: + // a/b/x/y/z/c + // a/x/y/z/b/c + // a/b/x/b/x/c + // a/b/c + // To do this, take the rest of the pattern after + // the **, and see if it would match the file remainder. + // If so, return success. + // If not, the ** "swallows" a segment, and try again. + // This is recursively awful. + // + // a/**/b/**/c matching a/b/x/y/z/c + // - a matches a + // - doublestar + // - matchOne(b/x/y/z/c, b/**/c) + // - b matches b + // - doublestar + // - matchOne(x/y/z/c, c) -> no + // - matchOne(y/z/c, c) -> no + // - matchOne(z/c, c) -> no + // - matchOne(c, c) yes, hit + var fr = fi + var pr = pi + 1 + if (pr === pl) { + this.debug('** at the end') + // a ** at the end will just swallow the rest. + // We have found a match. + // however, it will not swallow /.x, unless + // options.dot is set. + // . and .. are *never* matched by **, for explosively + // exponential reasons. + for (; fi < fl; fi++) { + if (file[fi] === '.' || file[fi] === '..' || + (!options.dot && file[fi].charAt(0) === '.')) return false + } + return true + } + + // ok, let's see if we can swallow whatever we can. + while (fr < fl) { + var swallowee = file[fr] + + this.debug('\nglobstar while', file, fr, pattern, pr, swallowee) + + // XXX remove this slice. Just pass the start index. + if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) { + this.debug('globstar found match!', fr, fl, swallowee) + // found a match. + return true + } else { + // can't swallow "." or ".." ever. + // can only swallow ".foo" when explicitly asked. + if (swallowee === '.' || swallowee === '..' || + (!options.dot && swallowee.charAt(0) === '.')) { + this.debug('dot detected!', file, fr, pattern, pr) + break + } + + // ** swallows a segment, and continue. + this.debug('globstar swallow a segment, and continue') + fr++ + } + } + + // no match was found. + // However, in partial mode, we can't say this is necessarily over. + // If there's more *pattern* left, then + if (partial) { + // ran out of file + this.debug('\n>>> no match, partial?', file, fr, pattern, pr) + if (fr === fl) return true + } + return false + } + + // something other than ** + // non-magic patterns just have to match exactly + // patterns with magic have been turned into regexps. + var hit + if (typeof p === 'string') { + if (options.nocase) { + hit = f.toLowerCase() === p.toLowerCase() + } else { + hit = f === p + } + this.debug('string match', p, f, hit) + } else { + hit = f.match(p) + this.debug('pattern match', p, f, hit) + } + + if (!hit) return false + } + + // Note: ending in / means that we'll get a final "" + // at the end of the pattern. This can only match a + // corresponding "" at the end of the file. + // If the file ends in /, then it can only match a + // a pattern that ends in /, unless the pattern just + // doesn't have any more for it. But, a/b/ should *not* + // match "a/b/*", even though "" matches against the + // [^/]*? pattern, except in partial mode, where it might + // simply not be reached yet. + // However, a/b/ should still satisfy a/* + + // now either we fell off the end of the pattern, or we're done. + if (fi === fl && pi === pl) { + // ran out of pattern and filename at the same time. + // an exact hit! + return true + } else if (fi === fl) { + // ran out of file, but still had pattern left. + // this is ok if we're doing the match as part of + // a glob fs traversal. + return partial + } else if (pi === pl) { + // ran out of pattern, still have file left. + // this is only acceptable if we're on the very last + // empty segment of a file with a trailing slash. + // a/* should match a/b/ + var emptyFileEnd = (fi === fl - 1) && (file[fi] === '') + return emptyFileEnd + } + + // should be unreachable. + throw new Error('wtf?') +} + +// replace stuff like \* with * +function globUnescape (s) { + return s.replace(/\\(.)/g, '$1') +} + +function regExpEscape (s) { + return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&') +} diff --git a/node_modules/minimatch/package.json b/node_modules/minimatch/package.json new file mode 100644 index 0000000..975989e --- /dev/null +++ b/node_modules/minimatch/package.json @@ -0,0 +1,64 @@ +{ + "_from": "minimatch@3.0.4", + "_id": "minimatch@3.0.4", + "_inBundle": false, + "_integrity": "sha512-yJHVQEhyqPLUTgt9B83PXu6W3rx4MvvHvSUvToogpwoGDOUQ+yDrR0HRot+yOCdCO7u4hX3pWft6kWBBcqh0UA==", + "_location": "/minimatch", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "minimatch@3.0.4", + "name": "minimatch", + "escapedName": "minimatch", + "rawSpec": "3.0.4", + "saveSpec": null, + "fetchSpec": "3.0.4" + }, + "_requiredBy": [ + "/glob", + "/mocha" + ], + "_resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.0.4.tgz", + "_shasum": "5166e286457f03306064be5497e8dbb0c3d32083", + "_spec": "minimatch@3.0.4", + "_where": "/Users/jessitron/code/jessitron/stringify-tree/node_modules/mocha", + "author": { + "name": "Isaac Z. Schlueter", + "email": "i@izs.me", + "url": "http://blog.izs.me" + }, + "bugs": { + "url": "https://github.com/isaacs/minimatch/issues" + }, + "bundleDependencies": false, + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "deprecated": false, + "description": "a glob matcher in javascript", + "devDependencies": { + "tap": "^10.3.2" + }, + "engines": { + "node": "*" + }, + "files": [ + "minimatch.js" + ], + "homepage": "https://github.com/isaacs/minimatch#readme", + "license": "ISC", + "main": "minimatch.js", + "name": "minimatch", + "repository": { + "type": "git", + "url": "git://github.com/isaacs/minimatch.git" + }, + "scripts": { + "postpublish": "git push origin --all; git push origin --tags", + "postversion": "npm publish", + "preversion": "npm test", + "test": "tap test/*.js --cov" + }, + "version": "3.0.4" +} diff --git a/node_modules/minimist/.travis.yml b/node_modules/minimist/.travis.yml new file mode 100644 index 0000000..cc4dba2 --- /dev/null +++ b/node_modules/minimist/.travis.yml @@ -0,0 +1,4 @@ +language: node_js +node_js: + - "0.8" + - "0.10" diff --git a/node_modules/minimist/LICENSE b/node_modules/minimist/LICENSE new file mode 100644 index 0000000..ee27ba4 --- /dev/null +++ b/node_modules/minimist/LICENSE @@ -0,0 +1,18 @@ +This software is released under the MIT license: + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/minimist/example/parse.js b/node_modules/minimist/example/parse.js new file mode 100644 index 0000000..abff3e8 --- /dev/null +++ b/node_modules/minimist/example/parse.js @@ -0,0 +1,2 @@ +var argv = require('../')(process.argv.slice(2)); +console.dir(argv); diff --git a/node_modules/minimist/index.js b/node_modules/minimist/index.js new file mode 100644 index 0000000..584f551 --- /dev/null +++ b/node_modules/minimist/index.js @@ -0,0 +1,187 @@ +module.exports = function (args, opts) { + if (!opts) opts = {}; + + var flags = { bools : {}, strings : {} }; + + [].concat(opts['boolean']).filter(Boolean).forEach(function (key) { + flags.bools[key] = true; + }); + + [].concat(opts.string).filter(Boolean).forEach(function (key) { + flags.strings[key] = true; + }); + + var aliases = {}; + Object.keys(opts.alias || {}).forEach(function (key) { + aliases[key] = [].concat(opts.alias[key]); + aliases[key].forEach(function (x) { + aliases[x] = [key].concat(aliases[key].filter(function (y) { + return x !== y; + })); + }); + }); + + var defaults = opts['default'] || {}; + + var argv = { _ : [] }; + Object.keys(flags.bools).forEach(function (key) { + setArg(key, defaults[key] === undefined ? false : defaults[key]); + }); + + var notFlags = []; + + if (args.indexOf('--') !== -1) { + notFlags = args.slice(args.indexOf('--')+1); + args = args.slice(0, args.indexOf('--')); + } + + function setArg (key, val) { + var value = !flags.strings[key] && isNumber(val) + ? Number(val) : val + ; + setKey(argv, key.split('.'), value); + + (aliases[key] || []).forEach(function (x) { + setKey(argv, x.split('.'), value); + }); + } + + for (var i = 0; i < args.length; i++) { + var arg = args[i]; + + if (/^--.+=/.test(arg)) { + // Using [\s\S] instead of . because js doesn't support the + // 'dotall' regex modifier. See: + // http://stackoverflow.com/a/1068308/13216 + var m = arg.match(/^--([^=]+)=([\s\S]*)$/); + setArg(m[1], m[2]); + } + else if (/^--no-.+/.test(arg)) { + var key = arg.match(/^--no-(.+)/)[1]; + setArg(key, false); + } + else if (/^--.+/.test(arg)) { + var key = arg.match(/^--(.+)/)[1]; + var next = args[i + 1]; + if (next !== undefined && !/^-/.test(next) + && !flags.bools[key] + && (aliases[key] ? !flags.bools[aliases[key]] : true)) { + setArg(key, next); + i++; + } + else if (/^(true|false)$/.test(next)) { + setArg(key, next === 'true'); + i++; + } + else { + setArg(key, flags.strings[key] ? '' : true); + } + } + else if (/^-[^-]+/.test(arg)) { + var letters = arg.slice(1,-1).split(''); + + var broken = false; + for (var j = 0; j < letters.length; j++) { + var next = arg.slice(j+2); + + if (next === '-') { + setArg(letters[j], next) + continue; + } + + if (/[A-Za-z]/.test(letters[j]) + && /-?\d+(\.\d*)?(e-?\d+)?$/.test(next)) { + setArg(letters[j], next); + broken = true; + break; + } + + if (letters[j+1] && letters[j+1].match(/\W/)) { + setArg(letters[j], arg.slice(j+2)); + broken = true; + break; + } + else { + setArg(letters[j], flags.strings[letters[j]] ? '' : true); + } + } + + var key = arg.slice(-1)[0]; + if (!broken && key !== '-') { + if (args[i+1] && !/^(-|--)[^-]/.test(args[i+1]) + && !flags.bools[key] + && (aliases[key] ? !flags.bools[aliases[key]] : true)) { + setArg(key, args[i+1]); + i++; + } + else if (args[i+1] && /true|false/.test(args[i+1])) { + setArg(key, args[i+1] === 'true'); + i++; + } + else { + setArg(key, flags.strings[key] ? '' : true); + } + } + } + else { + argv._.push( + flags.strings['_'] || !isNumber(arg) ? arg : Number(arg) + ); + } + } + + Object.keys(defaults).forEach(function (key) { + if (!hasKey(argv, key.split('.'))) { + setKey(argv, key.split('.'), defaults[key]); + + (aliases[key] || []).forEach(function (x) { + setKey(argv, x.split('.'), defaults[key]); + }); + } + }); + + notFlags.forEach(function(key) { + argv._.push(key); + }); + + return argv; +}; + +function hasKey (obj, keys) { + var o = obj; + keys.slice(0,-1).forEach(function (key) { + o = (o[key] || {}); + }); + + var key = keys[keys.length - 1]; + return key in o; +} + +function setKey (obj, keys, value) { + var o = obj; + keys.slice(0,-1).forEach(function (key) { + if (o[key] === undefined) o[key] = {}; + o = o[key]; + }); + + var key = keys[keys.length - 1]; + if (o[key] === undefined || typeof o[key] === 'boolean') { + o[key] = value; + } + else if (Array.isArray(o[key])) { + o[key].push(value); + } + else { + o[key] = [ o[key], value ]; + } +} + +function isNumber (x) { + if (typeof x === 'number') return true; + if (/^0x[0-9a-f]+$/i.test(x)) return true; + return /^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x); +} + +function longest (xs) { + return Math.max.apply(null, xs.map(function (x) { return x.length })); +} diff --git a/node_modules/minimist/package.json b/node_modules/minimist/package.json new file mode 100644 index 0000000..d5c5403 --- /dev/null +++ b/node_modules/minimist/package.json @@ -0,0 +1,71 @@ +{ + "_from": "minimist@0.0.8", + "_id": "minimist@0.0.8", + "_inBundle": false, + "_integrity": "sha1-hX/Kv8M5fSYluCKCYuhqp6ARsF0=", + "_location": "/minimist", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "minimist@0.0.8", + "name": "minimist", + "escapedName": "minimist", + "rawSpec": "0.0.8", + "saveSpec": null, + "fetchSpec": "0.0.8" + }, + "_requiredBy": [ + "/mkdirp" + ], + "_resolved": "http://registry.npmjs.org/minimist/-/minimist-0.0.8.tgz", + "_shasum": "857fcabfc3397d2625b8228262e86aa7a011b05d", + "_spec": "minimist@0.0.8", + "_where": "/Users/jessitron/code/jessitron/stringify-tree/node_modules/mkdirp", + "author": { + "name": "James Halliday", + "email": "mail@substack.net", + "url": "http://substack.net" + }, + "bugs": { + "url": "https://github.com/substack/minimist/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "parse argument options", + "devDependencies": { + "tap": "~0.4.0", + "tape": "~1.0.4" + }, + "homepage": "https://github.com/substack/minimist", + "keywords": [ + "argv", + "getopt", + "parser", + "optimist" + ], + "license": "MIT", + "main": "index.js", + "name": "minimist", + "repository": { + "type": "git", + "url": "git://github.com/substack/minimist.git" + }, + "scripts": { + "test": "tap test/*.js" + }, + "testling": { + "files": "test/*.js", + "browsers": [ + "ie/6..latest", + "ff/5", + "firefox/latest", + "chrome/10", + "chrome/latest", + "safari/5.1", + "safari/latest", + "opera/12" + ] + }, + "version": "0.0.8" +} diff --git a/node_modules/minimist/readme.markdown b/node_modules/minimist/readme.markdown new file mode 100644 index 0000000..c256353 --- /dev/null +++ b/node_modules/minimist/readme.markdown @@ -0,0 +1,73 @@ +# minimist + +parse argument options + +This module is the guts of optimist's argument parser without all the +fanciful decoration. + +[![browser support](https://ci.testling.com/substack/minimist.png)](http://ci.testling.com/substack/minimist) + +[![build status](https://secure.travis-ci.org/substack/minimist.png)](http://travis-ci.org/substack/minimist) + +# example + +``` js +var argv = require('minimist')(process.argv.slice(2)); +console.dir(argv); +``` + +``` +$ node example/parse.js -a beep -b boop +{ _: [], a: 'beep', b: 'boop' } +``` + +``` +$ node example/parse.js -x 3 -y 4 -n5 -abc --beep=boop foo bar baz +{ _: [ 'foo', 'bar', 'baz' ], + x: 3, + y: 4, + n: 5, + a: true, + b: true, + c: true, + beep: 'boop' } +``` + +# methods + +``` js +var parseArgs = require('minimist') +``` + +## var argv = parseArgs(args, opts={}) + +Return an argument object `argv` populated with the array arguments from `args`. + +`argv._` contains all the arguments that didn't have an option associated with +them. + +Numeric-looking arguments will be returned as numbers unless `opts.string` or +`opts.boolean` is set for that argument name. + +Any arguments after `'--'` will not be parsed and will end up in `argv._`. + +options can be: + +* `opts.string` - a string or array of strings argument names to always treat as +strings +* `opts.boolean` - a string or array of strings to always treat as booleans +* `opts.alias` - an object mapping string names to strings or arrays of string +argument names to use as aliases +* `opts.default` - an object mapping string argument names to default values + +# install + +With [npm](https://npmjs.org) do: + +``` +npm install minimist +``` + +# license + +MIT diff --git a/node_modules/minimist/test/dash.js b/node_modules/minimist/test/dash.js new file mode 100644 index 0000000..8b034b9 --- /dev/null +++ b/node_modules/minimist/test/dash.js @@ -0,0 +1,24 @@ +var parse = require('../'); +var test = require('tape'); + +test('-', function (t) { + t.plan(5); + t.deepEqual(parse([ '-n', '-' ]), { n: '-', _: [] }); + t.deepEqual(parse([ '-' ]), { _: [ '-' ] }); + t.deepEqual(parse([ '-f-' ]), { f: '-', _: [] }); + t.deepEqual( + parse([ '-b', '-' ], { boolean: 'b' }), + { b: true, _: [ '-' ] } + ); + t.deepEqual( + parse([ '-s', '-' ], { string: 's' }), + { s: '-', _: [] } + ); +}); + +test('-a -- b', function (t) { + t.plan(3); + t.deepEqual(parse([ '-a', '--', 'b' ]), { a: true, _: [ 'b' ] }); + t.deepEqual(parse([ '--a', '--', 'b' ]), { a: true, _: [ 'b' ] }); + t.deepEqual(parse([ '--a', '--', 'b' ]), { a: true, _: [ 'b' ] }); +}); diff --git a/node_modules/minimist/test/default_bool.js b/node_modules/minimist/test/default_bool.js new file mode 100644 index 0000000..f0041ee --- /dev/null +++ b/node_modules/minimist/test/default_bool.js @@ -0,0 +1,20 @@ +var test = require('tape'); +var parse = require('../'); + +test('boolean default true', function (t) { + var argv = parse([], { + boolean: 'sometrue', + default: { sometrue: true } + }); + t.equal(argv.sometrue, true); + t.end(); +}); + +test('boolean default false', function (t) { + var argv = parse([], { + boolean: 'somefalse', + default: { somefalse: false } + }); + t.equal(argv.somefalse, false); + t.end(); +}); diff --git a/node_modules/minimist/test/dotted.js b/node_modules/minimist/test/dotted.js new file mode 100644 index 0000000..ef0ae34 --- /dev/null +++ b/node_modules/minimist/test/dotted.js @@ -0,0 +1,16 @@ +var parse = require('../'); +var test = require('tape'); + +test('dotted alias', function (t) { + var argv = parse(['--a.b', '22'], {default: {'a.b': 11}, alias: {'a.b': 'aa.bb'}}); + t.equal(argv.a.b, 22); + t.equal(argv.aa.bb, 22); + t.end(); +}); + +test('dotted default', function (t) { + var argv = parse('', {default: {'a.b': 11}, alias: {'a.b': 'aa.bb'}}); + t.equal(argv.a.b, 11); + t.equal(argv.aa.bb, 11); + t.end(); +}); diff --git a/node_modules/minimist/test/long.js b/node_modules/minimist/test/long.js new file mode 100644 index 0000000..5d3a1e0 --- /dev/null +++ b/node_modules/minimist/test/long.js @@ -0,0 +1,31 @@ +var test = require('tape'); +var parse = require('../'); + +test('long opts', function (t) { + t.deepEqual( + parse([ '--bool' ]), + { bool : true, _ : [] }, + 'long boolean' + ); + t.deepEqual( + parse([ '--pow', 'xixxle' ]), + { pow : 'xixxle', _ : [] }, + 'long capture sp' + ); + t.deepEqual( + parse([ '--pow=xixxle' ]), + { pow : 'xixxle', _ : [] }, + 'long capture eq' + ); + t.deepEqual( + parse([ '--host', 'localhost', '--port', '555' ]), + { host : 'localhost', port : 555, _ : [] }, + 'long captures sp' + ); + t.deepEqual( + parse([ '--host=localhost', '--port=555' ]), + { host : 'localhost', port : 555, _ : [] }, + 'long captures eq' + ); + t.end(); +}); diff --git a/node_modules/minimist/test/parse.js b/node_modules/minimist/test/parse.js new file mode 100644 index 0000000..8a90646 --- /dev/null +++ b/node_modules/minimist/test/parse.js @@ -0,0 +1,318 @@ +var parse = require('../'); +var test = require('tape'); + +test('parse args', function (t) { + t.deepEqual( + parse([ '--no-moo' ]), + { moo : false, _ : [] }, + 'no' + ); + t.deepEqual( + parse([ '-v', 'a', '-v', 'b', '-v', 'c' ]), + { v : ['a','b','c'], _ : [] }, + 'multi' + ); + t.end(); +}); + +test('comprehensive', function (t) { + t.deepEqual( + parse([ + '--name=meowmers', 'bare', '-cats', 'woo', + '-h', 'awesome', '--multi=quux', + '--key', 'value', + '-b', '--bool', '--no-meep', '--multi=baz', + '--', '--not-a-flag', 'eek' + ]), + { + c : true, + a : true, + t : true, + s : 'woo', + h : 'awesome', + b : true, + bool : true, + key : 'value', + multi : [ 'quux', 'baz' ], + meep : false, + name : 'meowmers', + _ : [ 'bare', '--not-a-flag', 'eek' ] + } + ); + t.end(); +}); + +test('nums', function (t) { + var argv = parse([ + '-x', '1234', + '-y', '5.67', + '-z', '1e7', + '-w', '10f', + '--hex', '0xdeadbeef', + '789' + ]); + t.deepEqual(argv, { + x : 1234, + y : 5.67, + z : 1e7, + w : '10f', + hex : 0xdeadbeef, + _ : [ 789 ] + }); + t.deepEqual(typeof argv.x, 'number'); + t.deepEqual(typeof argv.y, 'number'); + t.deepEqual(typeof argv.z, 'number'); + t.deepEqual(typeof argv.w, 'string'); + t.deepEqual(typeof argv.hex, 'number'); + t.deepEqual(typeof argv._[0], 'number'); + t.end(); +}); + +test('flag boolean', function (t) { + var argv = parse([ '-t', 'moo' ], { boolean: 't' }); + t.deepEqual(argv, { t : true, _ : [ 'moo' ] }); + t.deepEqual(typeof argv.t, 'boolean'); + t.end(); +}); + +test('flag boolean value', function (t) { + var argv = parse(['--verbose', 'false', 'moo', '-t', 'true'], { + boolean: [ 't', 'verbose' ], + default: { verbose: true } + }); + + t.deepEqual(argv, { + verbose: false, + t: true, + _: ['moo'] + }); + + t.deepEqual(typeof argv.verbose, 'boolean'); + t.deepEqual(typeof argv.t, 'boolean'); + t.end(); +}); + +test('flag boolean default false', function (t) { + var argv = parse(['moo'], { + boolean: ['t', 'verbose'], + default: { verbose: false, t: false } + }); + + t.deepEqual(argv, { + verbose: false, + t: false, + _: ['moo'] + }); + + t.deepEqual(typeof argv.verbose, 'boolean'); + t.deepEqual(typeof argv.t, 'boolean'); + t.end(); + +}); + +test('boolean groups', function (t) { + var argv = parse([ '-x', '-z', 'one', 'two', 'three' ], { + boolean: ['x','y','z'] + }); + + t.deepEqual(argv, { + x : true, + y : false, + z : true, + _ : [ 'one', 'two', 'three' ] + }); + + t.deepEqual(typeof argv.x, 'boolean'); + t.deepEqual(typeof argv.y, 'boolean'); + t.deepEqual(typeof argv.z, 'boolean'); + t.end(); +}); + +test('newlines in params' , function (t) { + var args = parse([ '-s', "X\nX" ]) + t.deepEqual(args, { _ : [], s : "X\nX" }); + + // reproduce in bash: + // VALUE="new + // line" + // node program.js --s="$VALUE" + args = parse([ "--s=X\nX" ]) + t.deepEqual(args, { _ : [], s : "X\nX" }); + t.end(); +}); + +test('strings' , function (t) { + var s = parse([ '-s', '0001234' ], { string: 's' }).s; + t.equal(s, '0001234'); + t.equal(typeof s, 'string'); + + var x = parse([ '-x', '56' ], { string: 'x' }).x; + t.equal(x, '56'); + t.equal(typeof x, 'string'); + t.end(); +}); + +test('stringArgs', function (t) { + var s = parse([ ' ', ' ' ], { string: '_' })._; + t.same(s.length, 2); + t.same(typeof s[0], 'string'); + t.same(s[0], ' '); + t.same(typeof s[1], 'string'); + t.same(s[1], ' '); + t.end(); +}); + +test('empty strings', function(t) { + var s = parse([ '-s' ], { string: 's' }).s; + t.equal(s, ''); + t.equal(typeof s, 'string'); + + var str = parse([ '--str' ], { string: 'str' }).str; + t.equal(str, ''); + t.equal(typeof str, 'string'); + + var letters = parse([ '-art' ], { + string: [ 'a', 't' ] + }); + + t.equal(letters.a, ''); + t.equal(letters.r, true); + t.equal(letters.t, ''); + + t.end(); +}); + + +test('slashBreak', function (t) { + t.same( + parse([ '-I/foo/bar/baz' ]), + { I : '/foo/bar/baz', _ : [] } + ); + t.same( + parse([ '-xyz/foo/bar/baz' ]), + { x : true, y : true, z : '/foo/bar/baz', _ : [] } + ); + t.end(); +}); + +test('alias', function (t) { + var argv = parse([ '-f', '11', '--zoom', '55' ], { + alias: { z: 'zoom' } + }); + t.equal(argv.zoom, 55); + t.equal(argv.z, argv.zoom); + t.equal(argv.f, 11); + t.end(); +}); + +test('multiAlias', function (t) { + var argv = parse([ '-f', '11', '--zoom', '55' ], { + alias: { z: [ 'zm', 'zoom' ] } + }); + t.equal(argv.zoom, 55); + t.equal(argv.z, argv.zoom); + t.equal(argv.z, argv.zm); + t.equal(argv.f, 11); + t.end(); +}); + +test('nested dotted objects', function (t) { + var argv = parse([ + '--foo.bar', '3', '--foo.baz', '4', + '--foo.quux.quibble', '5', '--foo.quux.o_O', + '--beep.boop' + ]); + + t.same(argv.foo, { + bar : 3, + baz : 4, + quux : { + quibble : 5, + o_O : true + } + }); + t.same(argv.beep, { boop : true }); + t.end(); +}); + +test('boolean and alias with chainable api', function (t) { + var aliased = [ '-h', 'derp' ]; + var regular = [ '--herp', 'derp' ]; + var opts = { + herp: { alias: 'h', boolean: true } + }; + var aliasedArgv = parse(aliased, { + boolean: 'herp', + alias: { h: 'herp' } + }); + var propertyArgv = parse(regular, { + boolean: 'herp', + alias: { h: 'herp' } + }); + var expected = { + herp: true, + h: true, + '_': [ 'derp' ] + }; + + t.same(aliasedArgv, expected); + t.same(propertyArgv, expected); + t.end(); +}); + +test('boolean and alias with options hash', function (t) { + var aliased = [ '-h', 'derp' ]; + var regular = [ '--herp', 'derp' ]; + var opts = { + alias: { 'h': 'herp' }, + boolean: 'herp' + }; + var aliasedArgv = parse(aliased, opts); + var propertyArgv = parse(regular, opts); + var expected = { + herp: true, + h: true, + '_': [ 'derp' ] + }; + t.same(aliasedArgv, expected); + t.same(propertyArgv, expected); + t.end(); +}); + +test('boolean and alias using explicit true', function (t) { + var aliased = [ '-h', 'true' ]; + var regular = [ '--herp', 'true' ]; + var opts = { + alias: { h: 'herp' }, + boolean: 'h' + }; + var aliasedArgv = parse(aliased, opts); + var propertyArgv = parse(regular, opts); + var expected = { + herp: true, + h: true, + '_': [ ] + }; + + t.same(aliasedArgv, expected); + t.same(propertyArgv, expected); + t.end(); +}); + +// regression, see https://github.com/substack/node-optimist/issues/71 +test('boolean and --x=true', function(t) { + var parsed = parse(['--boool', '--other=true'], { + boolean: 'boool' + }); + + t.same(parsed.boool, true); + t.same(parsed.other, 'true'); + + parsed = parse(['--boool', '--other=false'], { + boolean: 'boool' + }); + + t.same(parsed.boool, true); + t.same(parsed.other, 'false'); + t.end(); +}); diff --git a/node_modules/minimist/test/parse_modified.js b/node_modules/minimist/test/parse_modified.js new file mode 100644 index 0000000..21851b0 --- /dev/null +++ b/node_modules/minimist/test/parse_modified.js @@ -0,0 +1,9 @@ +var parse = require('../'); +var test = require('tape'); + +test('parse with modifier functions' , function (t) { + t.plan(1); + + var argv = parse([ '-b', '123' ], { boolean: 'b' }); + t.deepEqual(argv, { b: true, _: ['123'] }); +}); diff --git a/node_modules/minimist/test/short.js b/node_modules/minimist/test/short.js new file mode 100644 index 0000000..d513a1c --- /dev/null +++ b/node_modules/minimist/test/short.js @@ -0,0 +1,67 @@ +var parse = require('../'); +var test = require('tape'); + +test('numeric short args', function (t) { + t.plan(2); + t.deepEqual(parse([ '-n123' ]), { n: 123, _: [] }); + t.deepEqual( + parse([ '-123', '456' ]), + { 1: true, 2: true, 3: 456, _: [] } + ); +}); + +test('short', function (t) { + t.deepEqual( + parse([ '-b' ]), + { b : true, _ : [] }, + 'short boolean' + ); + t.deepEqual( + parse([ 'foo', 'bar', 'baz' ]), + { _ : [ 'foo', 'bar', 'baz' ] }, + 'bare' + ); + t.deepEqual( + parse([ '-cats' ]), + { c : true, a : true, t : true, s : true, _ : [] }, + 'group' + ); + t.deepEqual( + parse([ '-cats', 'meow' ]), + { c : true, a : true, t : true, s : 'meow', _ : [] }, + 'short group next' + ); + t.deepEqual( + parse([ '-h', 'localhost' ]), + { h : 'localhost', _ : [] }, + 'short capture' + ); + t.deepEqual( + parse([ '-h', 'localhost', '-p', '555' ]), + { h : 'localhost', p : 555, _ : [] }, + 'short captures' + ); + t.end(); +}); + +test('mixed short bool and capture', function (t) { + t.same( + parse([ '-h', 'localhost', '-fp', '555', 'script.js' ]), + { + f : true, p : 555, h : 'localhost', + _ : [ 'script.js' ] + } + ); + t.end(); +}); + +test('short and long', function (t) { + t.deepEqual( + parse([ '-h', 'localhost', '-fp', '555', 'script.js' ]), + { + f : true, p : 555, h : 'localhost', + _ : [ 'script.js' ] + } + ); + t.end(); +}); diff --git a/node_modules/minimist/test/whitespace.js b/node_modules/minimist/test/whitespace.js new file mode 100644 index 0000000..8a52a58 --- /dev/null +++ b/node_modules/minimist/test/whitespace.js @@ -0,0 +1,8 @@ +var parse = require('../'); +var test = require('tape'); + +test('whitespace should be whitespace' , function (t) { + t.plan(1); + var x = parse([ '-x', '\t' ]).x; + t.equal(x, '\t'); +}); diff --git a/node_modules/mkdirp/.travis.yml b/node_modules/mkdirp/.travis.yml new file mode 100644 index 0000000..74c57bf --- /dev/null +++ b/node_modules/mkdirp/.travis.yml @@ -0,0 +1,8 @@ +language: node_js +node_js: + - "0.8" + - "0.10" + - "0.12" + - "iojs" +before_install: + - npm install -g npm@~1.4.6 diff --git a/node_modules/mkdirp/LICENSE b/node_modules/mkdirp/LICENSE new file mode 100644 index 0000000..432d1ae --- /dev/null +++ b/node_modules/mkdirp/LICENSE @@ -0,0 +1,21 @@ +Copyright 2010 James Halliday (mail@substack.net) + +This project is free software released under the MIT/X11 license: + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/mkdirp/bin/cmd.js b/node_modules/mkdirp/bin/cmd.js new file mode 100755 index 0000000..d95de15 --- /dev/null +++ b/node_modules/mkdirp/bin/cmd.js @@ -0,0 +1,33 @@ +#!/usr/bin/env node + +var mkdirp = require('../'); +var minimist = require('minimist'); +var fs = require('fs'); + +var argv = minimist(process.argv.slice(2), { + alias: { m: 'mode', h: 'help' }, + string: [ 'mode' ] +}); +if (argv.help) { + fs.createReadStream(__dirname + '/usage.txt').pipe(process.stdout); + return; +} + +var paths = argv._.slice(); +var mode = argv.mode ? parseInt(argv.mode, 8) : undefined; + +(function next () { + if (paths.length === 0) return; + var p = paths.shift(); + + if (mode === undefined) mkdirp(p, cb) + else mkdirp(p, mode, cb) + + function cb (err) { + if (err) { + console.error(err.message); + process.exit(1); + } + else next(); + } +})(); diff --git a/node_modules/mkdirp/bin/usage.txt b/node_modules/mkdirp/bin/usage.txt new file mode 100644 index 0000000..f952aa2 --- /dev/null +++ b/node_modules/mkdirp/bin/usage.txt @@ -0,0 +1,12 @@ +usage: mkdirp [DIR1,DIR2..] {OPTIONS} + + Create each supplied directory including any necessary parent directories that + don't yet exist. + + If the directory already exists, do nothing. + +OPTIONS are: + + -m, --mode If a directory needs to be created, set the mode as an octal + permission string. + diff --git a/node_modules/mkdirp/examples/pow.js b/node_modules/mkdirp/examples/pow.js new file mode 100644 index 0000000..e692421 --- /dev/null +++ b/node_modules/mkdirp/examples/pow.js @@ -0,0 +1,6 @@ +var mkdirp = require('mkdirp'); + +mkdirp('/tmp/foo/bar/baz', function (err) { + if (err) console.error(err) + else console.log('pow!') +}); diff --git a/node_modules/mkdirp/index.js b/node_modules/mkdirp/index.js new file mode 100644 index 0000000..6ce241b --- /dev/null +++ b/node_modules/mkdirp/index.js @@ -0,0 +1,98 @@ +var path = require('path'); +var fs = require('fs'); +var _0777 = parseInt('0777', 8); + +module.exports = mkdirP.mkdirp = mkdirP.mkdirP = mkdirP; + +function mkdirP (p, opts, f, made) { + if (typeof opts === 'function') { + f = opts; + opts = {}; + } + else if (!opts || typeof opts !== 'object') { + opts = { mode: opts }; + } + + var mode = opts.mode; + var xfs = opts.fs || fs; + + if (mode === undefined) { + mode = _0777 & (~process.umask()); + } + if (!made) made = null; + + var cb = f || function () {}; + p = path.resolve(p); + + xfs.mkdir(p, mode, function (er) { + if (!er) { + made = made || p; + return cb(null, made); + } + switch (er.code) { + case 'ENOENT': + mkdirP(path.dirname(p), opts, function (er, made) { + if (er) cb(er, made); + else mkdirP(p, opts, cb, made); + }); + break; + + // In the case of any other error, just see if there's a dir + // there already. If so, then hooray! If not, then something + // is borked. + default: + xfs.stat(p, function (er2, stat) { + // if the stat fails, then that's super weird. + // let the original error be the failure reason. + if (er2 || !stat.isDirectory()) cb(er, made) + else cb(null, made); + }); + break; + } + }); +} + +mkdirP.sync = function sync (p, opts, made) { + if (!opts || typeof opts !== 'object') { + opts = { mode: opts }; + } + + var mode = opts.mode; + var xfs = opts.fs || fs; + + if (mode === undefined) { + mode = _0777 & (~process.umask()); + } + if (!made) made = null; + + p = path.resolve(p); + + try { + xfs.mkdirSync(p, mode); + made = made || p; + } + catch (err0) { + switch (err0.code) { + case 'ENOENT' : + made = sync(path.dirname(p), opts, made); + sync(p, opts, made); + break; + + // In the case of any other error, just see if there's a dir + // there already. If so, then hooray! If not, then something + // is borked. + default: + var stat; + try { + stat = xfs.statSync(p); + } + catch (err1) { + throw err0; + } + if (!stat.isDirectory()) throw err0; + break; + } + } + + return made; +}; diff --git a/node_modules/mkdirp/package.json b/node_modules/mkdirp/package.json new file mode 100644 index 0000000..a3e5d22 --- /dev/null +++ b/node_modules/mkdirp/package.json @@ -0,0 +1,62 @@ +{ + "_from": "mkdirp@0.5.1", + "_id": "mkdirp@0.5.1", + "_inBundle": false, + "_integrity": "sha1-MAV0OOrGz3+MR2fzhkjWaX11yQM=", + "_location": "/mkdirp", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "mkdirp@0.5.1", + "name": "mkdirp", + "escapedName": "mkdirp", + "rawSpec": "0.5.1", + "saveSpec": null, + "fetchSpec": "0.5.1" + }, + "_requiredBy": [ + "/mocha" + ], + "_resolved": "http://registry.npmjs.org/mkdirp/-/mkdirp-0.5.1.tgz", + "_shasum": "30057438eac6cf7f8c4767f38648d6697d75c903", + "_spec": "mkdirp@0.5.1", + "_where": "/Users/jessitron/code/jessitron/stringify-tree/node_modules/mocha", + "author": { + "name": "James Halliday", + "email": "mail@substack.net", + "url": "http://substack.net" + }, + "bin": { + "mkdirp": "bin/cmd.js" + }, + "bugs": { + "url": "https://github.com/substack/node-mkdirp/issues" + }, + "bundleDependencies": false, + "dependencies": { + "minimist": "0.0.8" + }, + "deprecated": false, + "description": "Recursively mkdir, like `mkdir -p`", + "devDependencies": { + "mock-fs": "2 >=2.7.0", + "tap": "1" + }, + "homepage": "https://github.com/substack/node-mkdirp#readme", + "keywords": [ + "mkdir", + "directory" + ], + "license": "MIT", + "main": "index.js", + "name": "mkdirp", + "repository": { + "type": "git", + "url": "git+https://github.com/substack/node-mkdirp.git" + }, + "scripts": { + "test": "tap test/*.js" + }, + "version": "0.5.1" +} diff --git a/node_modules/mkdirp/readme.markdown b/node_modules/mkdirp/readme.markdown new file mode 100644 index 0000000..3cc1315 --- /dev/null +++ b/node_modules/mkdirp/readme.markdown @@ -0,0 +1,100 @@ +# mkdirp + +Like `mkdir -p`, but in node.js! + +[![build status](https://secure.travis-ci.org/substack/node-mkdirp.png)](http://travis-ci.org/substack/node-mkdirp) + +# example + +## pow.js + +```js +var mkdirp = require('mkdirp'); + +mkdirp('/tmp/foo/bar/baz', function (err) { + if (err) console.error(err) + else console.log('pow!') +}); +``` + +Output + +``` +pow! +``` + +And now /tmp/foo/bar/baz exists, huzzah! + +# methods + +```js +var mkdirp = require('mkdirp'); +``` + +## mkdirp(dir, opts, cb) + +Create a new directory and any necessary subdirectories at `dir` with octal +permission string `opts.mode`. If `opts` is a non-object, it will be treated as +the `opts.mode`. + +If `opts.mode` isn't specified, it defaults to `0777 & (~process.umask())`. + +`cb(err, made)` fires with the error or the first directory `made` +that had to be created, if any. + +You can optionally pass in an alternate `fs` implementation by passing in +`opts.fs`. Your implementation should have `opts.fs.mkdir(path, mode, cb)` and +`opts.fs.stat(path, cb)`. + +## mkdirp.sync(dir, opts) + +Synchronously create a new directory and any necessary subdirectories at `dir` +with octal permission string `opts.mode`. If `opts` is a non-object, it will be +treated as the `opts.mode`. + +If `opts.mode` isn't specified, it defaults to `0777 & (~process.umask())`. + +Returns the first directory that had to be created, if any. + +You can optionally pass in an alternate `fs` implementation by passing in +`opts.fs`. Your implementation should have `opts.fs.mkdirSync(path, mode)` and +`opts.fs.statSync(path)`. + +# usage + +This package also ships with a `mkdirp` command. + +``` +usage: mkdirp [DIR1,DIR2..] {OPTIONS} + + Create each supplied directory including any necessary parent directories that + don't yet exist. + + If the directory already exists, do nothing. + +OPTIONS are: + + -m, --mode If a directory needs to be created, set the mode as an octal + permission string. + +``` + +# install + +With [npm](http://npmjs.org) do: + +``` +npm install mkdirp +``` + +to get the library, or + +``` +npm install -g mkdirp +``` + +to get the command. + +# license + +MIT diff --git a/node_modules/mkdirp/test/chmod.js b/node_modules/mkdirp/test/chmod.js new file mode 100644 index 0000000..6a404b9 --- /dev/null +++ b/node_modules/mkdirp/test/chmod.js @@ -0,0 +1,41 @@ +var mkdirp = require('../').mkdirp; +var path = require('path'); +var fs = require('fs'); +var test = require('tap').test; +var _0777 = parseInt('0777', 8); +var _0755 = parseInt('0755', 8); +var _0744 = parseInt('0744', 8); + +var ps = [ '', 'tmp' ]; + +for (var i = 0; i < 25; i++) { + var dir = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + ps.push(dir); +} + +var file = ps.join('/'); + +test('chmod-pre', function (t) { + var mode = _0744 + mkdirp(file, mode, function (er) { + t.ifError(er, 'should not error'); + fs.stat(file, function (er, stat) { + t.ifError(er, 'should exist'); + t.ok(stat && stat.isDirectory(), 'should be directory'); + t.equal(stat && stat.mode & _0777, mode, 'should be 0744'); + t.end(); + }); + }); +}); + +test('chmod', function (t) { + var mode = _0755 + mkdirp(file, mode, function (er) { + t.ifError(er, 'should not error'); + fs.stat(file, function (er, stat) { + t.ifError(er, 'should exist'); + t.ok(stat && stat.isDirectory(), 'should be directory'); + t.end(); + }); + }); +}); diff --git a/node_modules/mkdirp/test/clobber.js b/node_modules/mkdirp/test/clobber.js new file mode 100644 index 0000000..2433b9a --- /dev/null +++ b/node_modules/mkdirp/test/clobber.js @@ -0,0 +1,38 @@ +var mkdirp = require('../').mkdirp; +var path = require('path'); +var fs = require('fs'); +var test = require('tap').test; +var _0755 = parseInt('0755', 8); + +var ps = [ '', 'tmp' ]; + +for (var i = 0; i < 25; i++) { + var dir = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + ps.push(dir); +} + +var file = ps.join('/'); + +// a file in the way +var itw = ps.slice(0, 3).join('/'); + + +test('clobber-pre', function (t) { + console.error("about to write to "+itw) + fs.writeFileSync(itw, 'I AM IN THE WAY, THE TRUTH, AND THE LIGHT.'); + + fs.stat(itw, function (er, stat) { + t.ifError(er) + t.ok(stat && stat.isFile(), 'should be file') + t.end() + }) +}) + +test('clobber', function (t) { + t.plan(2); + mkdirp(file, _0755, function (err) { + t.ok(err); + t.equal(err.code, 'ENOTDIR'); + t.end(); + }); +}); diff --git a/node_modules/mkdirp/test/mkdirp.js b/node_modules/mkdirp/test/mkdirp.js new file mode 100644 index 0000000..eaa8921 --- /dev/null +++ b/node_modules/mkdirp/test/mkdirp.js @@ -0,0 +1,28 @@ +var mkdirp = require('../'); +var path = require('path'); +var fs = require('fs'); +var exists = fs.exists || path.exists; +var test = require('tap').test; +var _0777 = parseInt('0777', 8); +var _0755 = parseInt('0755', 8); + +test('woo', function (t) { + t.plan(5); + var x = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + var y = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + var z = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + + var file = '/tmp/' + [x,y,z].join('/'); + + mkdirp(file, _0755, function (err) { + t.ifError(err); + exists(file, function (ex) { + t.ok(ex, 'file created'); + fs.stat(file, function (err, stat) { + t.ifError(err); + t.equal(stat.mode & _0777, _0755); + t.ok(stat.isDirectory(), 'target not a directory'); + }) + }) + }); +}); diff --git a/node_modules/mkdirp/test/opts_fs.js b/node_modules/mkdirp/test/opts_fs.js new file mode 100644 index 0000000..97186b6 --- /dev/null +++ b/node_modules/mkdirp/test/opts_fs.js @@ -0,0 +1,29 @@ +var mkdirp = require('../'); +var path = require('path'); +var test = require('tap').test; +var mockfs = require('mock-fs'); +var _0777 = parseInt('0777', 8); +var _0755 = parseInt('0755', 8); + +test('opts.fs', function (t) { + t.plan(5); + + var x = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + var y = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + var z = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + + var file = '/beep/boop/' + [x,y,z].join('/'); + var xfs = mockfs.fs(); + + mkdirp(file, { fs: xfs, mode: _0755 }, function (err) { + t.ifError(err); + xfs.exists(file, function (ex) { + t.ok(ex, 'created file'); + xfs.stat(file, function (err, stat) { + t.ifError(err); + t.equal(stat.mode & _0777, _0755); + t.ok(stat.isDirectory(), 'target not a directory'); + }); + }); + }); +}); diff --git a/node_modules/mkdirp/test/opts_fs_sync.js b/node_modules/mkdirp/test/opts_fs_sync.js new file mode 100644 index 0000000..6c370aa --- /dev/null +++ b/node_modules/mkdirp/test/opts_fs_sync.js @@ -0,0 +1,27 @@ +var mkdirp = require('../'); +var path = require('path'); +var test = require('tap').test; +var mockfs = require('mock-fs'); +var _0777 = parseInt('0777', 8); +var _0755 = parseInt('0755', 8); + +test('opts.fs sync', function (t) { + t.plan(4); + + var x = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + var y = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + var z = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + + var file = '/beep/boop/' + [x,y,z].join('/'); + var xfs = mockfs.fs(); + + mkdirp.sync(file, { fs: xfs, mode: _0755 }); + xfs.exists(file, function (ex) { + t.ok(ex, 'created file'); + xfs.stat(file, function (err, stat) { + t.ifError(err); + t.equal(stat.mode & _0777, _0755); + t.ok(stat.isDirectory(), 'target not a directory'); + }); + }); +}); diff --git a/node_modules/mkdirp/test/perm.js b/node_modules/mkdirp/test/perm.js new file mode 100644 index 0000000..fbce44b --- /dev/null +++ b/node_modules/mkdirp/test/perm.js @@ -0,0 +1,32 @@ +var mkdirp = require('../'); +var path = require('path'); +var fs = require('fs'); +var exists = fs.exists || path.exists; +var test = require('tap').test; +var _0777 = parseInt('0777', 8); +var _0755 = parseInt('0755', 8); + +test('async perm', function (t) { + t.plan(5); + var file = '/tmp/' + (Math.random() * (1<<30)).toString(16); + + mkdirp(file, _0755, function (err) { + t.ifError(err); + exists(file, function (ex) { + t.ok(ex, 'file created'); + fs.stat(file, function (err, stat) { + t.ifError(err); + t.equal(stat.mode & _0777, _0755); + t.ok(stat.isDirectory(), 'target not a directory'); + }) + }) + }); +}); + +test('async root perm', function (t) { + mkdirp('/tmp', _0755, function (err) { + if (err) t.fail(err); + t.end(); + }); + t.end(); +}); diff --git a/node_modules/mkdirp/test/perm_sync.js b/node_modules/mkdirp/test/perm_sync.js new file mode 100644 index 0000000..398229f --- /dev/null +++ b/node_modules/mkdirp/test/perm_sync.js @@ -0,0 +1,36 @@ +var mkdirp = require('../'); +var path = require('path'); +var fs = require('fs'); +var exists = fs.exists || path.exists; +var test = require('tap').test; +var _0777 = parseInt('0777', 8); +var _0755 = parseInt('0755', 8); + +test('sync perm', function (t) { + t.plan(4); + var file = '/tmp/' + (Math.random() * (1<<30)).toString(16) + '.json'; + + mkdirp.sync(file, _0755); + exists(file, function (ex) { + t.ok(ex, 'file created'); + fs.stat(file, function (err, stat) { + t.ifError(err); + t.equal(stat.mode & _0777, _0755); + t.ok(stat.isDirectory(), 'target not a directory'); + }); + }); +}); + +test('sync root perm', function (t) { + t.plan(3); + + var file = '/tmp'; + mkdirp.sync(file, _0755); + exists(file, function (ex) { + t.ok(ex, 'file created'); + fs.stat(file, function (err, stat) { + t.ifError(err); + t.ok(stat.isDirectory(), 'target not a directory'); + }) + }); +}); diff --git a/node_modules/mkdirp/test/race.js b/node_modules/mkdirp/test/race.js new file mode 100644 index 0000000..b0b9e18 --- /dev/null +++ b/node_modules/mkdirp/test/race.js @@ -0,0 +1,37 @@ +var mkdirp = require('../').mkdirp; +var path = require('path'); +var fs = require('fs'); +var exists = fs.exists || path.exists; +var test = require('tap').test; +var _0777 = parseInt('0777', 8); +var _0755 = parseInt('0755', 8); + +test('race', function (t) { + t.plan(10); + var ps = [ '', 'tmp' ]; + + for (var i = 0; i < 25; i++) { + var dir = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + ps.push(dir); + } + var file = ps.join('/'); + + var res = 2; + mk(file); + + mk(file); + + function mk (file, cb) { + mkdirp(file, _0755, function (err) { + t.ifError(err); + exists(file, function (ex) { + t.ok(ex, 'file created'); + fs.stat(file, function (err, stat) { + t.ifError(err); + t.equal(stat.mode & _0777, _0755); + t.ok(stat.isDirectory(), 'target not a directory'); + }); + }) + }); + } +}); diff --git a/node_modules/mkdirp/test/rel.js b/node_modules/mkdirp/test/rel.js new file mode 100644 index 0000000..4ddb342 --- /dev/null +++ b/node_modules/mkdirp/test/rel.js @@ -0,0 +1,32 @@ +var mkdirp = require('../'); +var path = require('path'); +var fs = require('fs'); +var exists = fs.exists || path.exists; +var test = require('tap').test; +var _0777 = parseInt('0777', 8); +var _0755 = parseInt('0755', 8); + +test('rel', function (t) { + t.plan(5); + var x = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + var y = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + var z = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + + var cwd = process.cwd(); + process.chdir('/tmp'); + + var file = [x,y,z].join('/'); + + mkdirp(file, _0755, function (err) { + t.ifError(err); + exists(file, function (ex) { + t.ok(ex, 'file created'); + fs.stat(file, function (err, stat) { + t.ifError(err); + process.chdir(cwd); + t.equal(stat.mode & _0777, _0755); + t.ok(stat.isDirectory(), 'target not a directory'); + }) + }) + }); +}); diff --git a/node_modules/mkdirp/test/return.js b/node_modules/mkdirp/test/return.js new file mode 100644 index 0000000..bce68e5 --- /dev/null +++ b/node_modules/mkdirp/test/return.js @@ -0,0 +1,25 @@ +var mkdirp = require('../'); +var path = require('path'); +var fs = require('fs'); +var test = require('tap').test; + +test('return value', function (t) { + t.plan(4); + var x = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + var y = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + var z = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + + var file = '/tmp/' + [x,y,z].join('/'); + + // should return the first dir created. + // By this point, it would be profoundly surprising if /tmp didn't + // already exist, since every other test makes things in there. + mkdirp(file, function (err, made) { + t.ifError(err); + t.equal(made, '/tmp/' + x); + mkdirp(file, function (err, made) { + t.ifError(err); + t.equal(made, null); + }); + }); +}); diff --git a/node_modules/mkdirp/test/return_sync.js b/node_modules/mkdirp/test/return_sync.js new file mode 100644 index 0000000..7c222d3 --- /dev/null +++ b/node_modules/mkdirp/test/return_sync.js @@ -0,0 +1,24 @@ +var mkdirp = require('../'); +var path = require('path'); +var fs = require('fs'); +var test = require('tap').test; + +test('return value', function (t) { + t.plan(2); + var x = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + var y = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + var z = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + + var file = '/tmp/' + [x,y,z].join('/'); + + // should return the first dir created. + // By this point, it would be profoundly surprising if /tmp didn't + // already exist, since every other test makes things in there. + // Note that this will throw on failure, which will fail the test. + var made = mkdirp.sync(file); + t.equal(made, '/tmp/' + x); + + // making the same file again should have no effect. + made = mkdirp.sync(file); + t.equal(made, null); +}); diff --git a/node_modules/mkdirp/test/root.js b/node_modules/mkdirp/test/root.js new file mode 100644 index 0000000..9e7d079 --- /dev/null +++ b/node_modules/mkdirp/test/root.js @@ -0,0 +1,19 @@ +var mkdirp = require('../'); +var path = require('path'); +var fs = require('fs'); +var test = require('tap').test; +var _0755 = parseInt('0755', 8); + +test('root', function (t) { + // '/' on unix, 'c:/' on windows. + var file = path.resolve('/'); + + mkdirp(file, _0755, function (err) { + if (err) throw err + fs.stat(file, function (er, stat) { + if (er) throw er + t.ok(stat.isDirectory(), 'target is a directory'); + t.end(); + }) + }); +}); diff --git a/node_modules/mkdirp/test/sync.js b/node_modules/mkdirp/test/sync.js new file mode 100644 index 0000000..8c8dc93 --- /dev/null +++ b/node_modules/mkdirp/test/sync.js @@ -0,0 +1,32 @@ +var mkdirp = require('../'); +var path = require('path'); +var fs = require('fs'); +var exists = fs.exists || path.exists; +var test = require('tap').test; +var _0777 = parseInt('0777', 8); +var _0755 = parseInt('0755', 8); + +test('sync', function (t) { + t.plan(4); + var x = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + var y = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + var z = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + + var file = '/tmp/' + [x,y,z].join('/'); + + try { + mkdirp.sync(file, _0755); + } catch (err) { + t.fail(err); + return t.end(); + } + + exists(file, function (ex) { + t.ok(ex, 'file created'); + fs.stat(file, function (err, stat) { + t.ifError(err); + t.equal(stat.mode & _0777, _0755); + t.ok(stat.isDirectory(), 'target not a directory'); + }); + }); +}); diff --git a/node_modules/mkdirp/test/umask.js b/node_modules/mkdirp/test/umask.js new file mode 100644 index 0000000..2033c63 --- /dev/null +++ b/node_modules/mkdirp/test/umask.js @@ -0,0 +1,28 @@ +var mkdirp = require('../'); +var path = require('path'); +var fs = require('fs'); +var exists = fs.exists || path.exists; +var test = require('tap').test; +var _0777 = parseInt('0777', 8); +var _0755 = parseInt('0755', 8); + +test('implicit mode from umask', function (t) { + t.plan(5); + var x = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + var y = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + var z = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + + var file = '/tmp/' + [x,y,z].join('/'); + + mkdirp(file, function (err) { + t.ifError(err); + exists(file, function (ex) { + t.ok(ex, 'file created'); + fs.stat(file, function (err, stat) { + t.ifError(err); + t.equal(stat.mode & _0777, _0777 & (~process.umask())); + t.ok(stat.isDirectory(), 'target not a directory'); + }); + }) + }); +}); diff --git a/node_modules/mkdirp/test/umask_sync.js b/node_modules/mkdirp/test/umask_sync.js new file mode 100644 index 0000000..11a7614 --- /dev/null +++ b/node_modules/mkdirp/test/umask_sync.js @@ -0,0 +1,32 @@ +var mkdirp = require('../'); +var path = require('path'); +var fs = require('fs'); +var exists = fs.exists || path.exists; +var test = require('tap').test; +var _0777 = parseInt('0777', 8); +var _0755 = parseInt('0755', 8); + +test('umask sync modes', function (t) { + t.plan(4); + var x = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + var y = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + var z = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + + var file = '/tmp/' + [x,y,z].join('/'); + + try { + mkdirp.sync(file); + } catch (err) { + t.fail(err); + return t.end(); + } + + exists(file, function (ex) { + t.ok(ex, 'file created'); + fs.stat(file, function (err, stat) { + t.ifError(err); + t.equal(stat.mode & _0777, (_0777 & (~process.umask()))); + t.ok(stat.isDirectory(), 'target not a directory'); + }); + }); +}); diff --git a/node_modules/mocha/CHANGELOG.md b/node_modules/mocha/CHANGELOG.md new file mode 100644 index 0000000..5e44bb6 --- /dev/null +++ b/node_modules/mocha/CHANGELOG.md @@ -0,0 +1,2000 @@ +# 5.2.0 / 2018-05-18 + +## :tada: Enhancements + +- [#3375]: Add support for comments in `mocha.opts` ([@plroebuck]) + +## :bug: Fixes + +- [#3346]: Exit correctly from `before` hooks when using `--bail` ([@outsideris]) + +## :book: Documentation + +- [#3328]: Mocha-flavored [API docs](https://mochajs.org/api/)! ([@Munter]) + +## :nut_and_bolt: Other + +- [#3330]: Use `Buffer.from()` ([@harrysarson]) +- [#3295]: Remove redundant folder ([@DavNej]) +- [#3356]: Refactoring ([@plroebuck]) + +[#3375]: https://github.com/mochajs/mocha/pull/3375 +[#3346]: https://github.com/mochajs/mocha/pull/3346 +[#3328]: https://github.com/mochajs/mocha/pull/3328 +[#3330]: https://github.com/mochajs/mocha/pull/3330 +[#3295]: https://github.com/mochajs/mocha/pull/3295 +[#3356]: https://github.com/mochajs/mocha/pull/3356 + +[@plroebuck]: https://github.com/plroebuck +[@harrysarson]: https://github.com/harrysarson +[@outsideris]: https://github.com/outsideris +[@Munter]: https://github.com/Munter + +# 5.1.1 / 2018-04-18 + +## :bug: Fixes + +- [#3325]: Revert change which broke `--watch` ([@boneskull]) + +[#3325]: https://github.com/mochajs/mocha/issues/3325 + +# 5.1.0 / 2018-04-12 + +## :tada: Enhancements + +- [#3210]: Add `--exclude` option ([@metalex9]) + +## :bug: Fixes + +- [#3318]: Fix failures in circular objects in JSON reporter ([@jeversmann], [@boneskull]) + +## :book: Documentation + +- [#3323]: Publish actual [API documentation](https://mochajs.org/api/)! ([@dfberry], [@Munter]) +- [#3299]: Improve docs around exclusive tests ([@nicgirault]) + +## :nut_and_bolt: Other + +- [#3302], [#3308], [#3310], [#3315], [#3316]: Build matrix improvements ([more info](https://boneskull.com/mocha-and-travis-ci-build-stages/)) ([@outsideris], [@boneskull]) +- [#3272]: Refactor reporter tests ([@jMuzsik]) + +[#3210]: https://github.com/mochajs/mocha/pull/3210 +[#3318]: https://github.com/mochajs/mocha/pull/3318 +[#3323]: https://github.com/mochajs/mocha/pull/3323 +[#3299]: https://github.com/mochajs/mocha/pull/3299 +[#3302]: https://github.com/mochajs/mocha/pull/3302 +[#3308]: https://github.com/mochajs/mocha/pull/3308 +[#3310]: https://github.com/mochajs/mocha/pull/3310 +[#3315]: https://github.com/mochajs/mocha/pull/3315 +[#3316]: https://github.com/mochajs/mocha/pull/3316 +[#3272]: https://github.com/mochajs/mocha/pull/3272 +[@metalex9]: https://github.com/metalex9 +[@jeversmann]: https://github.com/jeversmann +[@dfberry]: https://github.com/dfberry +[@nicgirault]: https://github.com/nicgirault +[@jMuzsik]: https://github.com/jMuzsik + +# 5.0.5 / 2018-03-22 + +Welcome [@outsideris] to the team! + +## :bug: Fixes + +- [#3096]: Fix `--bail` failing to bail within hooks ([@outsideris]) +- [#3184]: Don't skip too many suites (using `describe.skip()`) ([@outsideris]) + +## :book: Documentation + +- [#3133]: Improve docs regarding "pending" behavior ([@ematicipo]) +- [#3276], [#3274]: Fix broken stuff in `CHANGELOG.md` ([@tagoro9], [@honzajavorek]) + +## :nut_and_bolt: Other + +- [#3208]: Improve test coverage for AMD users ([@outsideris]) +- [#3267]: Remove vestiges of PhantomJS from CI ([@anishkny]) +- [#2952]: Fix a debug message ([@boneskull]) + +[#3096]: https://github.com/mochajs/mocha/issues/3096 +[#3184]: https://github.com/mochajs/mocha/issues/3184 +[#3133]: https://github.com/mochajs/mocha/issues/3133 +[#3276]: https://github.com/mochajs/mocha/pull/3276 +[#3274]: https://github.com/mochajs/mocha/pull/3274 +[#3208]: https://github.com/mochajs/mocha/issues/3208 +[#2952]: https://github.com/mochajs/mocha/issues/2952 +[#3267]: https://github.com/mochajs/mocha/pull/3267 + +[@ematicipo]: https://github.com/ematicipo +[@tagoro9]: https://github.com/tagoro9 +[@honzajavorek]: https://github.com/honajavorek +[@anishkny]: https://github.com/anishkny + +# 5.0.4 / 2018-03-07 + +## :bug: Fixes + +- [#3265]: Fixes regression in "watch" functionality introduced in v5.0.2 ([@outsideris]) + +[#3265]: https://github.com/mochajs/mocha/issues/3265 + +# 5.0.3 / 2018-03-06 + +This patch features a fix to address a potential "low severity" [ReDoS vulnerability](https://snyk.io/vuln/npm:diff:20180305) in the [diff](https://npm.im/diff) package (a dependency of Mocha). + +## :lock: Security Fixes + +- [#3266]: Bump `diff` to v3.5.0 ([@anishkny]) + +## :nut_and_bolt: Other + +- [#3011]: Expose `generateDiff()` in `Base` reporter ([@harrysarson]) + +[#3266]: https://github.com/mochajs/mocha/pull/3266 +[#3011]: https://github.com/mochajs/mocha/issues/3011 + +[@anishkny]: https://github.com/anishkny +[@harrysarson]: https://github.com/harrysarson + +# 5.0.2 / 2018-03-05 + +This release fixes a class of tests which report as *false positives*. **Certain tests will now break**, though they would have previously been reported as passing. Details below. Sorry for the inconvenience! + +## :bug: Fixes + +- [#3226]: Do not swallow errors that are thrown asynchronously from passing tests ([@boneskull]). Example: + + ```js + it('should actually fail, sorry!', function (done) { + // passing assertion + assert(true === true); + + // test complete & is marked as passing + done(); + + // ...but something evil lurks within + setTimeout(() => { + throw new Error('chaos!'); + }, 100); + }); + ``` + + Previously to this version, Mocha would have *silently swallowed* the `chaos!` exception, and you wouldn't know. Well, *now you know*. Mocha cannot recover from this gracefully, so it will exit with a nonzero code. + + **Maintainers of external reporters**: *If* a test of this class is encountered, the `Runner` instance will emit the `end` event *twice*; you *may* need to change your reporter to use `runner.once('end')` intead of `runner.on('end')`. +- [#3093]: Fix stack trace reformatting problem ([@outsideris]) + +## :nut_and_bolt: Other + +- [#3248]: Update `browser-stdout` to v1.3.1 ([@honzajavorek]) + +[#3248]: https://github.com/mochajs/mocha/issues/3248 +[#3226]: https://github.com/mochajs/mocha/issues/3226 +[#3093]: https://github.com/mochajs/mocha/issues/3093 +[@honzajavorek]: https://github.com/honzajavorek + +# 5.0.1 / 2018-02-07 + +...your garden-variety patch release. + +Special thanks to [Wallaby.js](https://wallabyjs.com) for their continued support! :heart: + +## :bug: Fixes + +- [#1838]: `--delay` now works with `.only()` ([@silviom]) +- [#3119]: Plug memory leak present in v8 ([@boneskull]) + +## :book: Documentation + +- [#3132], [#3098]: Update `--glob` docs ([@outsideris]) +- [#3212]: Update [Wallaby.js](https://wallabyjs.com)-related docs ([@ArtemGovorov]) +- [#3205]: Remove outdated cruft ([@boneskull]) + +## :nut_and_bolt: Other + +- [#3224]: Add proper Wallaby.js config ([@ArtemGovorov]) +- [#3230]: Update copyright year ([@josephlin55555]) + +[#1838]: https://github.com/mochajs/mocha/issues/1838 +[#3119]: https://github.com/mochajs/mocha/issues/3119 +[#3132]: https://github.com/mochajs/mocha/issues/3132 +[#3098]: https://github.com/mochajs/mocha/issues/3098 +[#3212]: https://github.com/mochajs/mocha/pull/3212 +[#3205]: https://github.com/mochajs/mocha/pull/3205 +[#3224]: https://github.com/mochajs/mocha/pull/3224 +[#3230]: https://github.com/mochajs/mocha/pull/3230 +[@silviom]: https://github.com/silviom +[@outsideris]: https://github.com/outsideris +[@ArtemGovorov]: https://github.com/ArtemGovorov +[@josephlin55555]: https://github.com/josephlin55555 + +# 5.0.0 / 2018-01-17 + +Mocha starts off 2018 right by again dropping support for *unmaintained rubbish*. + +Welcome [@vkarpov15] to the team! + +## :boom: Breaking Changes + +- **[#3148]: Drop support for IE9 and IE10** ([@Bamieh]) + Practically speaking, only code which consumes (through bundling or otherwise) the userland [buffer](https://npm.im/buffer) module should be affected. However, Mocha will no longer test against these browsers, nor apply fixes for them. + +## :tada: Enhancements + +- [#3181]: Add useful new `--file` command line argument ([documentation](https://mochajs.org/#--file-file)) ([@hswolff]) + +## :bug: Fixes + +- [#3187]: Fix inaccurate test duration reporting ([@FND]) +- [#3202]: Fix bad markup in HTML reporter ([@DanielRuf]) + +## :sunglasses: Developer Experience + +- [#2352]: Ditch GNU Make for [nps](https://npm.im/nps) to manage scripts ([@TedYav]) + +## :book: Documentation + +- [#3137]: Add missing `--no-timeouts` docs ([@dfberry]) +- [#3134]: Improve `done()` callback docs ([@maraisr]) +- [#3135]: Fix cross-references ([@vkarpov15]) +- [#3163]: Fix tpyos ([@tbroadley]) +- [#3177]: Tweak `README.md` organization ([@xxczaki]) +- Misc updates ([@boneskull]) + +## :nut_and_bolt: Other + +- [#3118]: Move TextMate Integration to [its own repo](https://github.com/mochajs/mocha.tmbundle) ([@Bamieh]) +- [#3185]: Add Node.js v9 to build matrix; remove v7 ([@xxczaki]) +- [#3172]: Markdown linting ([@boneskull]) +- Test & Netlify updates ([@Munter], [@boneskull]) + +[#3148]: https://github.com/mochajs/mocha/issues/3148 +[#3181]: https://github.com/mochajs/mocha/issues/3181 +[#3187]: https://github.com/mochajs/mocha/issues/3187 +[#3202]: https://github.com/mochajs/mocha/pull/3202 +[#2352]: https://github.com/mochajs/mocha/issues/2352 +[#3137]: https://github.com/mochajs/mocha/issues/3137 +[#3134]: https://github.com/mochajs/mocha/issues/3134 +[#3135]: https://github.com/mochajs/mocha/issues/3135 +[#3163]: https://github.com/mochajs/mocha/pull/3163 +[#3177]: https://github.com/mochajs/mocha/pull/3177 +[#3118]: https://github.com/mochajs/mocha/issues/3118 +[#3185]: https://github.com/mochajs/mocha/issues/3185 +[#3172]: https://github.com/mochajs/mocha/issues/3172 +[@hswolff]: https://github.com/hswolff +[@FND]: https://github.com/FND +[@DanielRuf]: https://github.com/DanielRuf +[@TedYav]: https://github.com/TedYav +[@dfberry]: https://github.com/dfberry +[@maraisr]: https://github.com/maraisr +[@vkarpov15]: https://github.com/vkarpov15 +[@tbroadley]: https://github.com/tbroadley + +# 4.1.0 / 2017-12-28 + +This is mainly a "housekeeping" release. + +Welcome [@Bamieh] and [@xxczaki] to the team! + +## :bug: Fixes + +- [#2661]: `progress` reporter now accepts reporter options ([@canoztokmak]) +- [#3142]: `xit` in `bdd` interface now properly returns its `Test` object ([@Bamieh]) +- [#3075]: Diffs now computed eagerly to avoid misinformation when reported ([@abrady0]) +- [#2745]: `--help` will now help you even if you have a `mocha.opts` ([@Zarel]) + +## :tada: Enhancements + +- [#2514]: The `--no-diff` flag will completely disable diff output ([@CapacitorSet]) +- [#3058]: All "setters" in Mocha's API are now also "getters" if called without arguments ([@makepanic]) + +## :book: Documentation + +- [#3170]: Optimization and site speed improvements ([@Munter]) +- [#2987]: Moved the old [site repo](https://github.com/mochajs/mochajs.github.io) into the main repo under `docs/` ([@boneskull]) +- [#2896]: Add [maintainer guide](https://github.com/mochajs/mocha/blob/master/MAINTAINERS.md) ([@boneskull]) +- Various fixes and updates ([@xxczaki], [@maty21], [@leedm777]) + +## :nut_and_bolt: Other + +- Test improvements and fixes ([@eugenet8k], [@ngeor], [@38elements], [@Gerhut], [@ScottFreeCode], [@boneskull]) +- Refactoring and cruft excision ([@38elements], [@Bamieh], [@finnigantime], [@boneskull]) + +[#2661]: https://github.com/mochajs/mocha/issues/2661 +[#3142]: https://github.com/mochajs/mocha/issues/3142 +[#3075]: https://github.com/mochajs/mocha/pull/3075 +[#2745]: https://github.com/mochajs/mocha/issues/2745 +[#2514]: https://github.com/mochajs/mocha/issues/2514 +[#3058]: https://github.com/mochajs/mocha/issues/3058 +[#3170]: https://github.com/mochajs/mocha/pull/3170 +[#2987]: https://github.com/mochajs/mocha/issues/2987 +[#2896]: https://github.com/mochajs/mocha/issues/2896 +[@canoztokmak]: https://github.com/canoztokmak +[@Bamieh]: https://github.com/Bamieh +[@abrady0]: https://github.com/abrady0 +[@Zarel]: https://github.com/Zarel +[@CapacitorSet]: https://github.com/CapacitorSet +[@xxczaki]: https://github.com/xxczaki +[@maty21]: https://github.com/maty21 +[@leedm777]: https://github.com/leedm777 +[@eugenet8k]: https://github.com/eugenet8k +[@38elements]: https://github.com/38elements +[@Gerhut]: https://github.com/Gerhut +[@finnigantime]: https://github.com/finnigantime + +# 4.0.1 / 2017-10-05 + +## :bug: Fixes + +- [#3051]: Upgrade Growl to v1.10.3 to fix its [peer dep problems](https://github.com/tj/node-growl/pull/68) ([@dpogue]) + +[#3051]: https://github.com/mochajs/mocha/pull/3051 +[@dpogue]: https://github.com/dpogue + +# 4.0.0 / 2017-10-02 + +You might want to read this before filing a new bug! :stuck_out_tongue_closed_eyes: + +## :boom: Breaking Changes + +For more info, please [read this article](https://boneskull.com/mocha-v4-nears-release/). + +### Compatibility + +- [#3016]: Drop support for unmaintained versions of Node.js ([@boneskull]): + - 0.10.x + - 0.11.x + - 0.12.x + - iojs (any) + - 5.x.x +- [#2979]: Drop support for non-ES5-compliant browsers ([@boneskull]): + - IE7 + - IE8 + - PhantomJS 1.x +- [#2615]: Drop Bower support; old versions (3.x, etc.) will remain available ([@ScottFreeCode], [@boneskull]) + +### Default Behavior + +- [#2879]: By default, Mocha will no longer force the process to exit once all tests complete. This means any test code (or code under test) which would normally prevent `node` from exiting will do so when run in Mocha. Supply the `--exit` flag to revert to pre-v4.0.0 behavior ([@ScottFreeCode], [@boneskull]) + +### Reporter Output + +- [#2095]: Remove `stdout:` prefix from browser reporter logs ([@skeggse]) +- [#2295]: Add separator in "unified diff" output ([@olsonpm]) +- [#2686]: Print failure message when `--forbid-pending` or `--forbid-only` is specified ([@ScottFreeCode]) +- [#2814]: Indent contexts for better readability when reporting failures ([@charlierudolph]) + +## :-1: Deprecations + +- [#2493]: The `--compilers` command-line option is now soft-deprecated and will emit a warning on `STDERR`. Read [this](https://github.com/mochajs/mocha/wiki/compilers-deprecation) for more info and workarounds ([@ScottFreeCode], [@boneskull]) + +## :tada: Enhancements + +- [#2628]: Allow override of default test suite name in XUnit reporter ([@ngeor]) + +## :book: Documentation + +- [#3020]: Link to CLA in `README.md` and `CONTRIBUTING.md` ([@skeggse]) + +## :nut_and_bolt: Other + +- [#2890]: Speed up build by (re-)consolidating SauceLabs tests ([@boneskull]) + +[#3016]: https://github.com/mochajs/mocha/issues/3016 +[#2979]: https://github.com/mochajs/mocha/issues/2979 +[#2615]: https://github.com/mochajs/mocha/issues/2615 +[#2879]: https://github.com/mochajs/mocha/issues/2879 +[#2095]: https://github.com/mochajs/mocha/issues/2095 +[#2295]: https://github.com/mochajs/mocha/issues/2295 +[#2686]: https://github.com/mochajs/mocha/issues/2686 +[#2814]: https://github.com/mochajs/mocha/pull/2814 +[#2493]: https://github.com/mochajs/mocha/issues/2493 +[#2628]: https://github.com/mochajs/mocha/issues/2628 +[#3020]: https://github.com/mochajs/mocha/pull/3020 +[#2890]: https://github.com/mochajs/mocha/issues/2890 +[@skeggse]: https://github.com/skeggse +[@olsonpm]: https://github.com/olsonpm +[@ngeor]: https://github.com/ngeor + +# 3.5.3 / 2017-09-11 + +## :bug: Fixes + +- [#3003]: Fix invalid entities in xUnit reporter first appearing in v3.5.1 ([@jkrems]) + +[#3003]: https://github.com/mochajs/mocha/pull/3003 + +# 3.5.2 / 2017-09-10 + +## :bug: Fixes + +- [#3001]: Fix AMD-related failures first appearing in v3.5.1 ([@boneskull]) + +[#3001]: https://github.com/mochajs/mocha/pull/3001 + +# 3.5.1 / 2017-09-09 + +## :newspaper: News + +- :mega: Mocha is now sponsoring [PDXNode](http://pdxnode.org)! If you're in the [Portland](https://wikipedia.org/wiki/Portland,_Oregon) area, come check out the monthly talks and hack nights! + +## :bug: Fixes + +- [#2997]: Fix missing `xit` export for "require" interface ([@solodynamo]) +- [#2957]: Fix unicode character handling in XUnit reporter failures ([@jkrems]) + +## :nut_and_bolt: Other + +- [#2986]: Add issue and PR templates ([@kungapal]) +- [#2918]: Drop bash dependency for glob-related tests ([@ScottFreeCode]) +- [#2922]: Improve `--compilers` coverage ([@ScottFreeCode]) +- [#2981]: Fix tpyos and spelling errors ([@jsoref]) + +[#2997]: https://github.com/mochajs/mocha/pull/2997 +[#2957]: https://github.com/mochajs/mocha/pull/2957 +[#2918]: https://github.com/mochajs/mocha/pull/2918 +[#2986]: https://github.com/mochajs/mocha/pull/2986 +[#2922]: https://github.com/mochajs/mocha/pull/2922 +[#2981]: https://github.com/mochajs/mocha/pull/2981 +[@solodynamo]: https://github.com/solodynamo +[@jkrems]: https://github.com/jkrems +[@jsoref]: https://github.com/jsoref + +# 3.5.0 / 2017-07-31 + +## :newspaper: News + +- Mocha now has a [code of conduct](https://github.com/mochajs/mocha/blob/master/.github/CODE_OF_CONDUCT.md) (thanks [@kungapal]!). +- Old issues and PRs are now being marked "stale" by [Probot's "Stale" plugin](https://github.com/probot/stale). If an issue is marked as such, and you would like to see it remain open, simply add a new comment to the ticket or PR. +- **WARNING**: Support for non-ES5-compliant environments will be dropped starting with version 4.0.0 of Mocha! + +## :lock: Security Fixes + +- [#2860]: Address [CVE-2015-8315](https://nodesecurity.io/advisories/46) via upgrade of [debug](https://npm.im/debug) ([@boneskull]) + +## :tada: Enhancements + +- [#2696]: Add `--forbid-only` and `--forbid-pending` flags. Use these in CI or hooks to ensure tests aren't accidentally being skipped! ([@charlierudolph]) +- [#2813]: Support Node.js 8's `--napi-modules` flag ([@jupp0r]) + +## :nut_and_bolt: Other + +- Various CI-and-test-related fixes and improvements ([@boneskull], [@dasilvacontin], [@PopradiArpad], [@Munter], [@ScottFreeCode]) +- "Officially" support Node.js 8 ([@elergy]) + +[#2860]: https://github.com/mochajs/mocha/pull/2860 +[#2696]: https://github.com/mochajs/mocha/pull/2696 +[#2813]: https://github.com/mochajs/mocha/pull/2813 +[@charlierudolph]: https://github.com/charlierudolph +[@PopradiArpad]: https://github.com/PopradiArpad +[@kungapal]: https://github.com/kungapal +[@elergy]: https://github.com/elergy +[@jupp0r]: https://github.com/jupp0r + +# 3.4.2 / 2017-05-24 + +## :bug: Fixes + +- [#2802]: Remove call to deprecated `os.tmpDir` ([@makepanic]) +- [#2820]: Eagerly set `process.exitCode` ([@chrisleck]) + +## :nut_and_bolt: Other + +- [#2778]: Move linting into an npm script ([@Munter]) + +[@chrisleck]: https://github.com/chrisleck +[@makepanic]: https://github.com/makepanic +[@Munter]: https://github.com/Munter + +[#2778]: https://github.com/mochajs/mocha/pull/2778 +[#2802]: https://github.com/mochajs/mocha/issues/2802 +[#2820]: https://github.com/mochajs/mocha/pull/2820 + +# 3.4.1 / 2017-05-14 + +Fixed a publishing mishap with git's autocrlf settings. + +# 3.4.0 / 2017-05-14 + +Mocha is now moving to a quicker release schedule: when non-breaking changes are merged, a release should happen that week. + +This week's highlights: + +- `allowUncaught` added to commandline as `--allow-uncaught` (and bugfixed) +- warning-related Node flags + +## :tada: Enhancements + +- [#2793], [#2697]: add --allowUncaught to Node.js ([@lrowe]) +- [#2733]: Add `--no-warnings` and `--trace-warnings` flags ([@sonicdoe]) + +## :bug: Fixes + +- [#2793], [#2697]: fix broken allowUncaught ([@lrowe]) + +## :nut_and_bolt: Other + +- [#2778]: Add license report and scan status ([@xizhao]) +- [#2794]: no special case for macOS running Karma locally ([@boneskull]) +- [#2795]: reverts use of semistandard directly ([#2648]) ([@boneskull]) + +[@lrowe]: https://github.com/lrowe +[@sonicdoe]: https://github.com/sonicdoe +[@xizhao]: https://github.com/xizhao +[@boneskull]: https://github.com/boneskull + +[#2795]: https://github.com/mochajs/mocha/pull/2795 +[#2733]: https://github.com/mochajs/mocha/pull/2733 +[#2793]: https://github.com/mochajs/mocha/pull/2793 +[#2697]: https://github.com/mochajs/mocha/pull/2697 +[#2778]: https://github.com/mochajs/mocha/pull/2778 +[#2794]: https://github.com/mochajs/mocha/pull/2794 + +# 3.3.0 / 2017-04-24 + +Thanks to all our contributors, maintainers, sponsors, and users! ❤️ + +As highlights: + +- We've got coverage now! +- Testing is looking less flaky \o/. +- No more nitpicking about "mocha.js" build on PRs. + +## :tada: Enhancements + +- [#2659]: Adds support for loading reporter from an absolute or relative path ([@sul4bh]) +- [#2769]: Support `--inspect-brk` on command-line ([@igwejk]) + +## :bug: Fixes + +- [#2662]: Replace unicode chars w/ hex codes in HTML reporter ([@rotemdan]) + +## :mag: Coverage + +- [#2672]: Add coverage for node tests ([@c089], [@Munter]) +- [#2680]: Increase tests coverage for base reporter ([@epallerols]) +- [#2690]: Increase tests coverage for doc reporter ([@craigtaub]) +- [#2701]: Increase tests coverage for landing, min, tap and list reporters ([@craigtaub]) +- [#2691]: Increase tests coverage for spec + dot reporters ([@craigtaub]) +- [#2698]: Increase tests coverage for xunit reporter ([@craigtaub]) +- [#2699]: Increase tests coverage for json-stream, markdown and progress reporters ([@craigtaub]) +- [#2703]: Cover .some() function in utils.js with tests ([@seppevs]) +- [#2773]: Add tests for loading reporters w/ relative/absolute paths ([@sul4bh]) + +## :nut_and_bolt: Other + +- Remove bin/.eslintrc; ensure execs are linted ([@boneskull]) +- [#2542]: Expand CONTRIBUTING.md ([@boneskull]) +- [#2660]: Double timeouts on integration tests ([@Munter]) +- [#2653]: Update copyright year ([@Scottkao85], [@Munter]) +- [#2621]: Update dependencies to enable Greenkeeper ([@boneskull], [@greenkeeper]) +- [#2625]: Use trusty container in travis-ci; use "artifacts" addon ([@boneskull]) +- [#2670]: doc(CONTRIBUTING): fix link to org members ([@coderbyheart]) +- Add Mocha propaganda to README.md ([@boneskull]) +- [#2470]: Avoid test flake in "delay" test ([@boneskull]) +- [#2675]: Limit browser concurrency on sauce ([@boneskull]) +- [#2669]: Use temporary test-only build of mocha.js for browsers tests ([@Munter]) +- Fix "projects" link in README.md ([@boneskull]) +- [#2678]: Chore(Saucelabs): test on IE9, IE10 and IE11 ([@coderbyheart]) +- [#2648]: Use `semistandard` directly ([@kt3k]) +- [#2727]: Make the build reproducible ([@lamby]) + +[@boneskull]: https://github.com/boneskull +[@c089]: https://github.com/c089 +[@coderbyheart]: https://github.com/coderbyheart +[@craigtaub]: https://github.com/craigtaub +[@epallerols]: https://github.com/epallerols +[@greenkeeper]: https://github.com/greenkeeper +[@igwejk]: https://github.com/igwejk +[@kt3k]: https://github.com/kt3k +[@lamby]: https://github.com/lamby +[@Munter]: https://github.com/Munter +[@rotemdan]: https://github.com/rotemdan +[@seppevs]: https://github.com/seppevs +[@sul4bh]: https://github.com/sul4bh + +[#2470]: https://github.com/mochajs/mocha/pull/2470 +[#2542]: https://github.com/mochajs/mocha/issues/2542 +[#2621]: https://github.com/mochajs/mocha/pull/2621 +[#2625]: https://github.com/mochajs/mocha/pull/2625 +[#2648]: https://github.com/mochajs/mocha/pull/2648 +[#2653]: https://github.com/mochajs/mocha/pull/2653 +[#2659]: https://github.com/mochajs/mocha/pull/2659 +[#2660]: https://github.com/mochajs/mocha/pull/2660 +[#2662]: https://github.com/mochajs/mocha/pull/2662 +[#2669]: https://github.com/mochajs/mocha/pull/2669 +[#2670]: https://github.com/mochajs/mocha/pull/2670 +[#2672]: https://github.com/mochajs/mocha/pull/2672 +[#2675]: https://github.com/mochajs/mocha/pull/2675 +[#2678]: https://github.com/mochajs/mocha/pull/2678 +[#2680]: https://github.com/mochajs/mocha/pull/2680 +[#2690]: https://github.com/mochajs/mocha/pull/2690 +[#2691]: https://github.com/mochajs/mocha/pull/2691 +[#2698]: https://github.com/mochajs/mocha/pull/2698 +[#2699]: https://github.com/mochajs/mocha/pull/2699 +[#2701]: https://github.com/mochajs/mocha/pull/2701 +[#2703]: https://github.com/mochajs/mocha/pull/2703 +[#2727]: https://github.com/mochajs/mocha/pull/2727 +[#2769]: https://github.com/mochajs/mocha/pull/2769 +[#2773]: https://github.com/mochajs/mocha/pull/2773 + +# 3.2.0 / 2016-11-24 + +## :newspaper: News + +### Mocha is now a JS Foundation Project! + +Mocha is proud to have joined the [JS Foundation](https://js.foundation). For more information, [read the announcement](https://js.foundation/announcements/2016/10/17/Linux-Foundation-Unites-JavaScript-Community-Open-Web-Development/). + +### Contributor License Agreement + +Under the foundation, all contributors to Mocha must sign the [JS Foundation CLA](https://js.foundation/CLA/) before their code can be merged. When sending a PR--if you have not already signed the CLA--a friendly bot will ask you to do so. + +Mocha remains licensed under the [MIT license](https://github.com/mochajs/mocha/blob/master/LICENSE). + +## :bug: Bug Fix + +- [#2535]: Fix crash when `--watch` encounters broken symlinks ([@villesau]) +- [#2593]: Fix (old) regression; incorrect symbol shown in `list` reporter ([@Aldaviva]) +- [#2584]: Fix potential error when running XUnit reporter ([@vobujs]) + +## :tada: Enhancement + +- [#2294]: Improve timeout error messaging ([@jeversmann], [@boneskull]) +- [#2520]: Add info about `--inspect` flag to CLI help ([@ughitsaaron]) + +## :nut_and_bolt: Other + +- [#2570]: Use [karma-mocha](https://npmjs.com/package/karma-mocha) proper ([@boneskull]) +- Licenses updated to reflect new copyright, add link to license and browser matrix to `README.md` ([@boneskull], [@ScottFreeCode], [@dasilvacontin]) + +[#2294]: https://github.com/mochajs/mocha/issues/2294 +[#2535]: https://github.com/mochajs/mocha/issues/2535 +[#2520]: https://github.com/mochajs/mocha/pull/2520 +[#2593]: https://github.com/mochajs/mocha/pull/2593 +[#2584]: https://github.com/mochajs/mocha/issues/2584 +[#2570]: https://github.com/mochajs/mocha/issues/2570 +[@Aldaviva]: https://github.com/Aldaviva +[@jeversmann]: https://github.com/jeversmann +[@ughitsaaron]: https://github.com/ughitsaaron +[@villesau]: https://github.com/villesau +[@vobujs]: https://github.com/vobujs + +Thanks to all our contributors, sponsors and backers! Keep on the lookout for a public roadmap and new contribution guide coming soon. + +# 3.1.2 / 2016-10-10 + +## :bug: Bug Fix + +- [#2528]: Recovery gracefully if an `Error`'s `stack` property isn't writable ([@boneskull]) + +[#2528]: https://github.com/mochajs/mocha/issues/2528 + +# 3.1.1 / 2016-10-09 + +## :bug: Bug Fix + +- [#1417]: Don't report `done()` was called multiple times when it wasn't ([@frankleonrose]) + +## :nut_and_bolt: Other + +- [#2490]: Lint with [semistandard](https://npmjs.com/package/semistandard) config ([@makepanic]) +- [#2525]: Lint all `.js` files ([@boneskull]) +- [#2524]: Provide workaround for developers unable to run browser tests on macOS Sierra ([@boneskull]) + +[#1417]: https://github.com/mochajs/mocha/issues/1417 +[#2490]: https://github.com/mochajs/mocha/issues/2490 +[#2525]: https://github.com/mochajs/mocha/issues/2525 +[#2524]: https://github.com/mochajs/mocha/issues/2524 +[@makepanic]: https://github.com/makepanic +[@frankleonrose]: https://github.com/frankleonrose + +# 3.1.0 / 2016-09-27 + +## :tada: Enhancement + +- [#2357]: Support `--inspect` on command-line ([@simov]) +- [#2194]: Human-friendly error if no files are matched on command-line ([@Munter]) +- [#1744]: Human-friendly error if a Suite has no callback (BDD/TDD only) ([@anton]) + +## :bug: Bug Fix + +- [#2488]: Fix case in which *variables beginning with lowercase "D"* may not have been reported properly as global leaks ([@JustATrick]) :laughing: +- [#2465]: Always halt execution in async function when `this.skip()` is called ([@boneskull]) +- [#2445]: Exits with expected code 130 when `SIGINT` encountered; exit code can no longer rollover at 256 ([@Munter]) +- [#2315]: Fix uncaught TypeError thrown from callback stack ([@1999]) +- Fix broken `only()`/`skip()` in IE7/IE8 ([@boneskull]) +- [#2502]: Fix broken stack trace filter on Node.js under Windows ([@boneskull]) +- [#2496]: Fix diff output for objects instantiated with `String` constructor ([more](https://youtrack.jetbrains.com/issue/WEB-23383)) ([@boneskull]) + +[#2496]: https://github.com/mochajs/mocha/issues/2496 +[#2502]: https://github.com/mochajs/mocha/issues/2502 +[#2315]: https://github.com/mochajs/mocha/issues/2315 +[#2445]: https://github.com/mochajs/mocha/pull/2445 +[#2465]: https://github.com/mochajs/mocha/issues/2465 +[#2488]: https://github.com/mochajs/mocha/issues/2488 +[#1744]: https://github.com/mochajs/mocha/issues/1744 +[#2194]: https://github.com/mochajs/mocha/issues/2194 +[#2357]: https://github.com/mochajs/mocha/issues/2357 +[@1999]: https://github.com/1999 +[@JustATrick]: https://github.com/JustATrick +[@anton]: https://github.com/anton +[@simov]: https://github.com/simov + +# 3.0.2 / 2016-08-08 + +## :bug: Bug Fix + +- [#2424]: Fix error loading Mocha via Require.js ([@boneskull]) +- [#2417]: Fix execution of *deeply* nested `describe.only()` suites ([@not-an-aardvark]) +- Remove references to `json-cov` and `html-cov` reporters in CLI ([@boneskull]) + +[#2417]: https://github.com/mochajs/mocha/issues/2417 +[#2424]: https://github.com/mochajs/mocha/issues/2424 + +# 3.0.1 / 2016-08-03 + +## :bug: Bug Fix + +- [#2406]: Restore execution of nested `describe.only()` suites ([@not-an-aardvark]) + +[#2406]: https://github.com/mochajs/mocha/issues/2406 +[@not-an-aardvark]: https://github.com/not-an-aardvark + +# 3.0.0 / 2016-07-31 + +## :boom: Breaking Changes + +- :warning: Due to the increasing difficulty of applying security patches made within its dependency tree, as well as looming incompatibilities with Node.js v7.0, **Mocha no longer supports Node.js v0.8**. +- :warning: **Mocha may no longer be installed by versions of `npm` less than `1.4.0`.** Previously, this requirement only affected Mocha's development dependencies. In short, this allows Mocha to depend on packages which have dependencies fixed to major versions (`^`). +- `.only()` is no longer "fuzzy", can be used multiple times, and generally just works like you think it should. :joy: +- To avoid common bugs, when a test injects a callback function (suggesting asynchronous execution), calls it, *and* returns a `Promise`, Mocha will now throw an exception: + + ```js + const assert = require('assert'); + + it('should complete this test', function (done) { + return new Promise(function (resolve) { + assert.ok(true); + resolve(); + }) + .then(done); + }); + ``` + + The above test will fail with `Error: Resolution method is overspecified. Specify a callback *or* return a Promise; not both.`. +- When a test timeout value *greater than* `2147483648` is specified in any context (`--timeout`, `mocha.setup()`, per-suite, per-test, etc.), the timeout will be *disabled* and the test(s) will be allowed to run indefinitely. This is equivalent to specifying a timeout value of `0`. See [MDN](https://developer.mozilla.org/docs/Web/API/WindowTimers/setTimeout#Maximum_delay_value) for reasoning. +- The `dot` reporter now uses more visually distinctive characters when indicating "pending" and "failed" tests. +- Mocha no longer supports [component](https://www.npmjs.com/package/component). +- The long-forsaken `HTMLCov` and `JSONCov` reporters--and any relationship to the "node-jscoverage" project--have been removed. +- `spec` reporter now omits leading carriage returns (`\r`) in non-TTY environment. + +## :tada: Enhancements + +- [#808]: Allow regular-expression-like strings in `--grep` and browser's `grep` querystring; enables flags such as `i` for case-insensitive matches and `u` for unicode. ([@a8m]) +- [#2000]: Use distinctive characters in `dot` reporter; `,` will denote a "pending" test and `!` will denote a "failing" test. ([@elliottcable]) +- [#1632]: Throw a useful exception when a suite or test lacks a title. ([@a8m]) +- [#1481]: Better `.only()` behavior. ([@a8m]) +- [#2334]: Allow `this.skip()` in async tests and hooks. ([@boneskull]) +- [#1320]: Throw a useful exception when test resolution method is overspecified. ([@jugglinmike]) +- [#2364]: Support `--preserve-symlinks`. ([@rosswarren]) + +## :bug: Bug Fixes + +- [#2259]: Restore ES3 compatibility. Specifically, support an environment lacking `Date.prototype.toISOString()`, `JSON`, or has a non-standard implementation of `JSON`. ([@ndhoule], [@boneskull]) +- [#2286]: Fix `after()` failing to execute if test skipped using `this.skip()` in `beforeEach()`; no longer marks the entire suite as "pending". ([@dasilvacontin], [@boneskull]) +- [#2208]: Fix function name display in `markdown` and `html` (browser) reporters. ([@ScottFreeCode]) +- [#2299]: Fix progress bar in `html` (browser) reporter. ([@AviVahl]) +- [#2307]: Fix `doc` reporter crashing when test fails. ([@jleyba]) +- [#2323]: Ensure browser entry point (`browser-entry.js`) is published to npm (for use with bundlers). ([@boneskull]) +- [#2310]: Ensure custom reporter with an absolute path works in Windows. ([@silentcloud]) +- [#2311]: Fix problem wherein calling `this.slow()` without a value would blast any previously set value. ([@boneskull]) +- [#1813]: Ensure Mocha's own test suite will run in Windows. ([@tswaters], [@TimothyGu], [@boneskull]) +- [#2317]: Ensure all interfaces are displayed in `--help` on CLI. ([@ScottFreeCode]) +- [#1644]: Don't exhibit undefined behavior when calling `this.timeout()` with very large values ([@callumacrae], [@boneskull]) +- [#2361]: Don't truncate name of thrown anonymous exception. ([@boneskull]) +- [#2367]: Fix invalid CSS. ([@bensontrent]) +- [#2401]: Remove carriage return before each test line in spec reporter. ([@Munter]) + +## :nut_and_bolt: Other + +- Upgrade production dependencies to address security advisories (and because now we can): `glob`, `commander`, `escape-string-regexp`, and `supports-color`. ([@boneskull], [@RobLoach]) +- Add Windows to CI. ([@boneskull], [@TimothyGu]) +- Ensure appropriate `engines` field in `package.json`. ([@shinnn], [@boneskull]) +- [#2348]: Upgrade ESLint to v2 ([@anthony-redfox]) + +We :heart: our [backers and sponsors](https://opencollective.com/mochajs)! + +:shipit: + +[#2401]: https://github.com/mochajs/mocha/pull/2401 +[#2348]: https://github.com/mochajs/mocha/issues/2348 +[#808]: https://github.com/mochajs/mocha/issues/808 +[#2361]: https://github.com/mochajs/mocha/pull/2361 +[#2367]: https://github.com/mochajs/mocha/pull/2367 +[#2364]: https://github.com/mochajs/mocha/pull/2364 +[#1320]: https://github.com/mochajs/mocha/pull/1320 +[#2307]: https://github.com/mochajs/mocha/pull/2307 +[#2259]: https://github.com/mochajs/mocha/pull/2259 +[#2208]: https://github.com/mochajs/mocha/pull/2208 +[#2299]: https://github.com/mochajs/mocha/pull/2299 +[#2286]: https://github.com/mochajs/mocha/issues/2286 +[#1644]: https://github.com/mochajs/mocha/issues/1644 +[#2310]: https://github.com/mochajs/mocha/issues/2310 +[#2311]: https://github.com/mochajs/mocha/issues/2311 +[#2323]: https://github.com/mochajs/mocha/issues/2323 +[#2000]: https://github.com/mochajs/mocha/pull/2000 +[#1632]: https://github.com/mochajs/mocha/issues/1632 +[#1813]: https://github.com/mochajs/mocha/issues/1813 +[#2334]: https://github.com/mochajs/mocha/issues/2334 +[#2317]: https://github.com/mochajs/mocha/issues/2317 +[#1481]: https://github.com/mochajs/mocha/issues/1481 +[@elliottcable]: https://github.com/elliottcable +[@RobLoach]: https://github.com/robloach +[@AviVahl]: https://github.com/avivahl +[@silentcloud]: https://github.com/silentcloud +[@tswaters]: https://github.com/tswaters +[@jleyba]: https://github.com/jleyba +[@TimothyGu]: https://github.com/timothygu +[@callumacrae]: https://github.com/callumacrae +[@shinnn]: https://github.com/shinnn +[@bensontrent]: https://github.com/bensontrent +[@jugglinmike]: https://github.com/jugglinmike +[@rosswarren]: https://github.com/rosswarren +[@anthony-redfox]: https://github.com/anthony-redfox +[@Munter]: https://github.com/munter + +# 2.5.3 / 2016-05-25 + +- [#2112] - Fix HTML reporter regression causing duplicate error output ([@danielstjules] via 6d24063) +- [#2119] - Make HTML reporter failure/passed links preventDefault to avoid SPA's hash navigation ([@jimenglish81] via 9e93efc) + +[@danielstjules]: https://github.com/danielstjules +[@jimenglish81]: https://github.com/jimenglish81 +[#2112]: https://github.com/mochajs/mocha/pull/2112 +[#2119]: https://github.com/mochajs/mocha/pull/2119 + +# 2.5.2 / 2016-05-24 + +- [#2178] - Avoid double and triple xUnit XML escaping ([@graingert] via 49b5ff1) + +[@graingert]: https://github.com/graingert +[#2178]: https://github.com/mochajs/mocha/pull/2178 + +# 2.5.1 / 2016-05-23 + +- Fix [to-iso-string](https://npmjs.com/package/to-iso-string) dependency ([@boneskull] via bd9450b) + +Thanks @entertainyou, @SimenB, @just-paja for the heads-up. + +# 2.5.0 / 2016-05-23 + +This has been awhile coming! We needed to feel confident that the next release wouldn't break browser compatibility (e.g. the last few patch releases). + +## Browser Tests in CI + +We now run unit tests against PhantomJS v1.x and an assortment of browsers on [SauceLabs](https://saucelabs.com), including: + +- Internet Explorer v8.0 +- Chrome (latest) +- Firefox (latest) +- Safari (latest) +- Microsoft Edge (latest) + +To accomplish this, we now run Mocha's unit tests (and a handful of integration tests) via [Karma](https://npmjs.com/package/karma) and a modified [karma-mocha](https://npmjs.com/package/karma-mocha). Along the way, we had to solve issue [#880] (apologies to @mderijcke and @sukima who had PRs addressing this), as well as replace most usages of [should](https://npmjs.com/package/should) with [expect.js](https://npmjs.com/package/expect.js) for IE8. + +Going forward, when sending PRs, your code will *only* run against PhantomJS v1.x (and not hit SauceLabs) [because security](https://docs.travis-ci.com/user/pull-requests/#Security-Restrictions-when-testing-Pull-Requests). + +## Node.js 6.x + + Node.js 6.x "just worked" before, but now it's in the CI matrix, so it's "officially" supported. Mocha *still retains support* for Node.js 0.8.x. + +## "Minor" Release + +You'll see mostly bug fixes below, but also a couple features--as such, it's a "minor" release. + +## TYVM + +Thanks to everyone who contributed, and our fabulous [sponsors and backers](https://opencollective.com/mochajs)! + +- [#2079] - Add browser checks to CI; update [browserify](https://npmjs.com/package/browserify) to v13.0.0 ([@dasilvacontin], [@ScottFreeCode], [@boneskull] via c04c1d7, 0b1e9b3, 0dde0fa, f8a3d86, 9e8cbaa) +- [#880] - Make Mocha browserifyable ([@boneskull] via 524862b) +- [#2121] - Update [glob](https://npmjs.com/package/glob) to v3.2.11 ([@astorije] via 7920fc4) +- [#2126] - Fix dupe error messages in stack trace filter ([@Turbo87] via 4301caa) +- [#2109] - Fix certain diffs when objects cannot be coerced into primitives ([@joshlory] via 61fbb7f) +- [#1827] - Fix TWBS/`mocha.css` collisions ([@irnc] via 0543798) +- [#1760], [#1936] - Fix `this.skip()` in HTML reporter ([@mislav] via cb4248b) +- [#2115] - Fix exceptions thrown from hooks in HTML reporter ([@danielstjules] via e290bc0) +- [#2089] - Handle Symbol values in `util.stringify()` ([@ryym] via ea61d05) +- [#2097] - Fix diff for objects overriding `Object.prototype.hasOwnProperty` ([@mantoni] via b20fdfe) +- [#2101] - Properly handle non-string "messages" thrown from assertion libraries ([@jkimbo] via 9c41051) +- [#2124] - Update [growl](https://npmjs.com/package/growl) ([@benjamine] via 9ae6a85) +- [#2162], [#2205] - JSDoc fixes ([@OlegTsyba] via 8031f20, [@ScottFreeCode] via f83b1d9) +- [#2132] - Remove Growl-related cruft ([@julienw] via 00d6469) +- [#2172] - Add [OpenCollective](https://opencollective.com) badge, sponsors & backers ([@xdamman], [@boneskull] via caee94f) +- [#1841] - Add new logo, banner assets ([@dasilvacontin] via 00fd0e1) +- [#2214] - Update `README.md` header ([@dasilvacontin] via c0f9be2) +- [#2236] - Better checks for Node.js v0.8 compatibility in CI ([@dasilvacontin] via ba5637d) +- [#2239] - Add Node.js v6.x to CI matrix ([@boneskull] via 3904da4) + +[#880]: https://github.com/mochajs/mocha/issues/880 +[#1841]: https://github.com/mochajs/mocha/pull/1841 +[#2239]: https://github.com/mochajs/mocha/issues/2239 +[#2153]: https://github.com/mochajs/mocha/pull/2153 +[#2214]: https://github.com/mochajs/mocha/pull/2214 +[#2236]: https://github.com/mochajs/mocha/pull/2236 +[#2079]: https://github.com/mochajs/mocha/issues/2079 +[#2231]: https://github.com/mochajs/mocha/pull/2231 +[#2089]: https://github.com/mochajs/mocha/issues/2089 +[#2097]: https://github.com/mochajs/mocha/pull/2097 +[#1760]: https://github.com/mochajs/mocha/issues/1760 +[#1936]: https://github.com/mochajs/mocha/issues/1936 +[#2115]: https://github.com/mochajs/mocha/pull/2115 +[#1827]: https://github.com/mochajs/mocha/pull/1827 +[#2101]: https://github.com/mochajs/mocha/pull/2101 +[#2124]: https://github.com/mochajs/mocha/pull/2124 +[#2109]: https://github.com/mochajs/mocha/issues/2109 +[#2162]: https://github.com/mochajs/mocha/pull/2162 +[#2132]: https://github.com/mochajs/mocha/issues/2132 +[#2126]: https://github.com/mochajs/mocha/issues/2126 +[#2121]: https://github.com/mochajs/mocha/issues/2121 +[#2205]: https://github.com/mochajs/mocha/pull/2205 +[#2172]: https://github.com/mochajs/mocha/pull/2172 +[@xdamman]: https://github.com/xdamman +[@Turbo87]: https://github.com/Turbo87 +[@OlegTsyba]: https://github.com/OlegTsyba +[@ryym]: https://github.com/ryym +[@mantoni]: https://github.com/mantoni +[@mislav]: https://github.com/mislav +[@irnc]: https://github.com/irnc +[@jkimbo]: https://github.com/jkimbo +[@benjamine]: https://github.com/benjamine +[@joshlory]: https://github.com/joshlory +[@julienw]: https://github.com/julienw +[@ScottFreeCode]: https://github.com/ScottFreeCode +[@astorije]: https://github.com/astorije +[@dasilvacontin]: https://github.com/dasilvacontin + +# 2.4.5 / 2016-01-28 + +- [#2080], [#2078], [#2072], [#2073], [#1200] - Revert changes to console colors in changeset [1192914](https://github.com/mochajs/mocha/commit/119291449cd03a11cdeda9e37cf718a69a012896) and subsequent related changes thereafter. Restores compatibility with IE8 & PhantomJS. See also [mantoni/mochify.js#129](https://github.com/mantoni/mochify.js/issues/129) and [openlayers/ol3#4746](https://github.com/openlayers/ol3/pull/4746) ([@boneskull]) +- [#2082] - Fix several test assertions ([@mislav]) + +[#1200]: https://github.com/mochajs/mocha/issues/1200 +[#2082]: https://github.com/mochajs/mocha/pull/2082 + +# 2.4.4 / 2016-01-27 + +- [#2080] - Fix broken RequireJS compatibility ([@boneskull]) + +[#2080]: https://github.com/mochajs/mocha/issues/2080 + +# 2.4.3 / 2016-01-27 + +- [#2078] - Fix broken IE8 ([@boneskull]) + +[#2078]: https://github.com/mochajs/mocha/issues/2078 + +# 2.4.2 / 2016-01-26 + +- [#2053] - Fix web worker compatibility ([@mislav]) +- [#2072] - Fix Windows color output ([@thedark1337]) +- [#2073] - Fix colors in `progress` and `landing` reporters ([@gyandeeps]) + +[#2053]: https://github.com/mochajs/mocha/pull/2053 +[#2072]: https://github.com/mochajs/mocha/pull/2072 +[#2073]: https://github.com/mochajs/mocha/pull/2073 +[@gyandeeps]: https://github.com/gyandeeps +[@thedark1337]: https://github.com/thedark1337 + +# 2.4.1 / 2016-01-26 + +- [#2067] - Fix HTML/doc reporter regressions ([@danielstjules]) + +[#2067]: https://github.com/mochajs/mocha/pull/2067 + +# 2.4.0 / 2016-01-25 + +- [#1945] - Correctly skip tests when skipping in suite's before() ([@ryanshawty]) +- [#2056] - chore(license): update license year to 2016 ([@pra85]) +- [#2048] - Fix `this.skip` from spec with HTML reporter ([@mislav]) +- [#2033] - Update tests for newer versions of should.js ([@tomhughes]) +- [#2037] - Fix for memory leak caused by referenced to deferred test ([@bd82]) +- [#2038] - Also run Travis-CI on node.js 4 & 5 ([@bd82]) +- [#2028] - Remove reference to test before afterAll hook runs ([@stonelgh]) +- Bump mkdirp to 0.5.1 to support strict mode ([@danielstjules]) +- [#1977] - safely stringify PhantomJS undefined value ([@ahamid]) +- Add the ability to retry tests ([@@longlho]) +- [#1982] - Enable --log-timer-events option [@Alaneor] +- Fix #1980: Load mocha.opts from bin/mocha and bin/_mocha ([@danielstjules]) +- [#1976] - Simplify function call ([@iclanzan]) +- [#1963] - Add support --perf-basic-prof ([@robraux]) +- [#1981] - Fix HTML reporter handling of done and exceptions ([@Standard8]) +- [#1993] - propagate "file" property for "exports" interface ([@segrey]) +- [#1999] - Add support for strict mode ([@tmont]) +- [#2005] - XUnit Reporter Writes to stdout, falls back to console.log ([@jonnyreeves]) +- [#2021] - Fix non ES5 compliant regexp ([@zetaben]) +- [#1965] - Don't double install BDD UI ([@cowboyd]) +- [#1995] - Make sure the xunit output dir exists before writing to it ([@ianwremmel]) +- Use chalk for the base reporter colors; closes #1200 ([@boneskull]) +- Fix requiring custom interfaces ([@jgkim]) +- [#1967] Silence Bluebird js warnings ([@krisr]) + +[#1945]: https://github.com/mochajs/mocha/pull/1945 +[#2056]: https://github.com/mochajs/mocha/pull/2056 +[#2048]: https://github.com/mochajs/mocha/pull/2048 +[#2033]: https://github.com/mochajs/mocha/pull/2033 +[#2037]: https://github.com/mochajs/mocha/pull/2037 +[#2038]: https://github.com/mochajs/mocha/pull/2038 +[#2028]: https://github.com/mochajs/mocha/pull/2028 +[#1977]: https://github.com/mochajs/mocha/pull/1977 +[#1982]: https://github.com/mochajs/mocha/pull/1982 +[#1976]: https://github.com/mochajs/mocha/pull/1976 +[#1963]: https://github.com/mochajs/mocha/pull/1963 +[#1981]: https://github.com/mochajs/mocha/pull/1981 +[#1993]: https://github.com/mochajs/mocha/pull/1993 +[#1999]: https://github.com/mochajs/mocha/pull/1999 +[#2005]: https://github.com/mochajs/mocha/pull/2005 +[#2021]: https://github.com/mochajs/mocha/pull/2021 +[1965#]: https://github.com/mochajs/mocha/pull/1965 +[#1995]: https://github.com/mochajs/mocha/pull/1995 +[#1967]: https://github.com/mochajs/mocha/pull/1967 +[@ryanshawty]: https://github.com/ryanshawty +[@pra85]: https://github.com/pra85 +[@mislav]: https://github.com/mislav +[@tomhughes]: https://github.com/tomhughes +[@bd82]: https://github.com/bd82 +[@stonelgh]: https://github.com/stonelgh +[@danielstjules]: https://github.com/danielstjules +[@ahamid]: https://github.com/ahamid +[@longlho]: https://github.com/longlho +[@Alaneor]: https://github.com/Alaneor +[@iclanzan]: https://github.com/iclanzan +[@robraux]: https://github.com/robraux +[@Standard8]: https://github.com/Standard8 +[@segrey]: https://github.com/segrey +[@tmont]: https://github.com/tmont +[@jonnyreeves]: https://github.com/jonnyreeves +[@zetaben]: https://github.com/zetaben +[@cowboyd]: https://github.com/cowboyd +[@ianwremmel]: https://github.com/ianwremmel +[@boneskull]: https://github.com/boneskull +[@jgkim]: https://github.com/jgkim +[@krisr]: https://github.com/krisr + +# 2.3.4 / 2015-11-15 + +- Update debug dependency to 2.2.0 +- remove duplication of mocha.opts on process.argv +- Fix typo in test/reporters/nyan.js + +# 2.3.3 / 2015-09-19 + +- [#1875] - Fix Markdown reporter exceeds maximum call stack size ([@danielstjules]) +- [#1864] - Fix xunit missing output with --reporter-options output ([@danielstjules]) +- [#1846] - Support all harmony flags ([@danielstjules]) +- Fix fragile xunit reporter spec ([@danielstjules]) +- [#1669] - Fix catch uncaught errors outside test suite execution ([@danielstjules]) +- [#1868] - Revert jade to support npm < v1.3.7 ([@danielstjules]) +- [#1766] - Don't remove modules/components from stack trace in the browser ([@danielstjules]) +- [#1798] - Fix correctly attribute mutiple done err with hooks ([@danielstjules]) +- Fix use utils.reduce for IE8 compatibility ([@wsw0108]) +- Some linting errors fixed by [@danielstjules] +- Call the inspect() function if message is not set ([@kevinburke]) + +[#1875]: https://github.com/mochajs/mocha/issues/1875 +[#1864]: https://github.com/mochajs/mocha/issues/1864 +[#1846]: https://github.com/mochajs/mocha/issues/1846 +[#1669]: https://github.com/mochajs/mocha/issues/1669 +[#1868]: https://github.com/mochajs/mocha/issues/1868 +[#1766]: https://github.com/mochajs/mocha/issues/1766 +[#1798]: https://github.com/mochajs/mocha/issues/1798 +[@danielstjules]: https://github.com/danielstjules +[@wsw0108]: https://github.com/wsw0108 +[@kevinburke]: https://github.com/kevinburke + +# 2.3.2 / 2015-09-07 + +- [#1868] - Fix compatibility with older versions of NPM ([@boneskull]) + + [#1868]: https://github.com/mochajs/mocha/issues/1868 + +# 2.3.1 / 2015-09-06 + +- [#1812] - Fix: Bail flag causes before() hooks to be run even after a failure ([@aaroncrows]) + + [#1812]: https://github.com/mochajs/mocha/issues/1812 + [aaroncrows]: https://github.com/aaroncrows + +# 2.3.0 / 2015-08-30 + +- [#553] - added --allowUncaught option ([@amsul]) +- [#1490] - Allow --async-only to be satisfied by returning a promise ([@jlai]) +- [#1829] - support --max-old-space-size ([@gigadude]) +- [#1811] - upgrade Jade dependency ([@outsideris]) +- [#1769] - Fix async hook error handling ([@ajaykodali]) +- [#1230] - More descriptive beforeEach/afterEach messages ([@duncanbeevers]) +- [#1787] - Scope loading behaviour instead of using early return ([@aryeguy]) +- [#1789] - Fix: html-runner crashing ([@sunesimonsen]) +- [#1749] - Fix maximum call stack error on large amount of tests ([@tinganho]) +- [#1230] - Decorate failed hook titles with test title ([@duncanbeevers]) +- [#1260] - Build using Browserify ([@ndhoule]) +- [#1728] - Don't use `__proto__` ([@ndhoule]) +- [#1781] - Fix hook error tests ([@glenjamin]) +- [#1754] - Allow boolean --reporter-options ([@papandreou]) +- [#1766] - Fix overly aggressive stack suppression ([@moll]) +- [#1752] - Avoid potential infinite loop ([@gsilk]) +- [#1761] - Fix problems running under PhantomJS ([@chromakode]) +- [#1700] - Fix more problems running under PhantomJS ([@jbnicolai]) +- [#1774] - Support escaped spaces in CLI options ([@adamgruber]) +- [#1687] - Fix HTML reporter links with special chars ([@benvinegar]) +- [#1359] - Adopt code style and enforce it using ESLint ([@ndhoule] w/ assist from [@jbnicolai] & [@boneskull]) +- various refactors ([@jbnicolai]) +- [#1758] - Add cross-frame compatible Error checking ([@outdooricon]) +- [#1741] - Remove moot `version` property from bower.json ([@kkirsche]) +- [#1739] - Improve `HISTORY.md` ([@rstacruz]) +- [#1730] - Support more io.js flags ([@ryedog]) +- [#1349] - Allow HTML in HTML reporter errors ([@papandreou] / [@sunesimonsen]) +- [#1572] - Prevent default browser behavior for failure/pass links ([@jschilli]) +- [#1630] - Support underscored harmony flags ([@dominicbarnes]) +- [#1718] - Support more harmony flags ([@slyg]) +- [#1689] - Add stack to JSON-stream reporter ([@jonathandelgado]) +- [#1654] - Fix `ReferenceError` "location is not defined" ([@jakemmarsh]) + + [#553]: https://github.com/mochajs/mocha/issues/553 + [#1490]: https://github.com/mochajs/mocha/issues/1490 + [#1829]: https://github.com/mochajs/mocha/issues/1829 + [#1811]: https://github.com/mochajs/mocha/issues/1811 + [#1769]: https://github.com/mochajs/mocha/issues/1769 + [#1230]: https://github.com/mochajs/mocha/issues/1230 + [#1787]: https://github.com/mochajs/mocha/issues/1787 + [#1789]: https://github.com/mochajs/mocha/issues/1789 + [#1749]: https://github.com/mochajs/mocha/issues/1749 + [#1230]: https://github.com/mochajs/mocha/issues/1230 + [#1260]: https://github.com/mochajs/mocha/issues/1260 + [#1728]: https://github.com/mochajs/mocha/issues/1728 + [#1781]: https://github.com/mochajs/mocha/issues/1781 + [#1754]: https://github.com/mochajs/mocha/issues/1754 + [#1766]: https://github.com/mochajs/mocha/issues/1766 + [#1752]: https://github.com/mochajs/mocha/issues/1752 + [#1761]: https://github.com/mochajs/mocha/issues/1761 + [#1700]: https://github.com/mochajs/mocha/issues/1700 + [#1774]: https://github.com/mochajs/mocha/issues/1774 + [#1687]: https://github.com/mochajs/mocha/issues/1687 + [#1359]: https://github.com/mochajs/mocha/issues/1359 + [#1758]: https://github.com/mochajs/mocha/issues/1758 + [#1741]: https://github.com/mochajs/mocha/issues/1741 + [#1739]: https://github.com/mochajs/mocha/issues/1739 + [#1730]: https://github.com/mochajs/mocha/issues/1730 + [#1349]: https://github.com/mochajs/mocha/issues/1349 + [#1572]: https://github.com/mochajs/mocha/issues/1572 + [#1630]: https://github.com/mochajs/mocha/issues/1630 + [#1718]: https://github.com/mochajs/mocha/issues/1718 + [#1689]: https://github.com/mochajs/mocha/issues/1689 + [#1654]: https://github.com/mochajs/mocha/issues/1654 + [@adamgruber]: https://github.com/adamgruber + [@ajaykodali]: https://github.com/ajaykodali + [@amsul]: https://github.com/amsul + [@aryeguy]: https://github.com/aryeguy + [@benvinegar]: https://github.com/benvinegar + [@boneskull]: https://github.com/boneskull + [@chromakode]: https://github.com/chromakode + [@dominicbarnes]: https://github.com/dominicbarnes + [@duncanbeevers]: https://github.com/duncanbeevers + [@gigadude]: https://github.com/gigadude + [@glenjamin]: https://github.com/glenjamin + [@gsilk]: https://github.com/gsilk + [@jakemmarsh]: https://github.com/jakemmarsh + [@jbnicolai]: https://github.com/jbnicolai + [@jlai]: https://github.com/jlai + [@jonathandelgado]: https://github.com/jonathandelgado + [@jschilli]: https://github.com/jschilli + [@kkirsche]: https://github.com/kkirsche + [@moll]: https://github.com/moll + [@ndhoule]: https://github.com/ndhoule + [@outdooricon]: https://github.com/outdooricon + [@outsideris]: https://github.com/outsideris + [@papandreou]: https://github.com/papandreou + [@rstacruz]: https://github.com/rstacruz + [@ryedog]: https://github.com/ryedog + [@slyg]: https://github.com/slyg + [@sunesimonsen]: https://github.com/sunesimonsen + [@tinganho]: https://github.com/tinganho + +# 2.2.5 / 2015-05-14 + +- [#1699] - Upgrade jsdiff to v1.4.0 ([@nylen]) +- [#1648] - fix diff background colors in the console ([@nylen]) +- [#1327] - fix tests running twice, a regression issue. ([#1686], [@danielstjules]) +- [#1675] - add integration tests ([@danielstjules]) +- [#1682] - use a valid SPDX license identifier in package.json ([@kemitchell]) +- [#1660] - fix assertion of invalid dates ([#1661], [@a8m]) +- [#1241] - fix issue with multiline diffs appearing as single line ([#1655], [@a8m]) + +[#1699]: https://github.com/mochajs/mocha/issues/1699 +[#1648]: https://github.com/mochajs/mocha/issues/1648 +[#1327]: https://github.com/mochajs/mocha/issues/1327 +[#1686]: https://github.com/mochajs/mocha/issues/1686 +[#1675]: https://github.com/mochajs/mocha/issues/1675 +[#1682]: https://github.com/mochajs/mocha/issues/1682 +[#1660]: https://github.com/mochajs/mocha/issues/1660 +[#1661]: https://github.com/mochajs/mocha/issues/1661 +[#1241]: https://github.com/mochajs/mocha/issues/1241 +[#1655]: https://github.com/mochajs/mocha/issues/1655 +[@nylen]: https://github.com/nylen +[@danielstjules]: https://github.com/danielstjules +[@kemitchell]: https://github.com/kemitchell +[@a8m]: https://github.com/a8m + +# 2.2.4 / 2015-04-08 + +- Load mocha.opts in _mocha for now (close #1645) + +# 2.2.3 / 2015-04-07 + +- fix(reporter/base): string diff - issue #1241 +- fix(reporter/base): string diff - issue #1241 +- fix(reporter/base): don't show diffs for errors without expectation +- fix(reporter/base): don't assume error message is first line of stack +- improve: dry up reporter/base test +- fix(reporter/base): explicitly ignore showDiff #1614 +- Add iojs to travis build +- Pass `--allow-natives-syntax` flag to node. +- Support --harmony_classes flag for io.js +- Fix 1556: Update utils.clean to handle newlines in func declarations +- Fix 1606: fix err handling in IE <= 8 and non-ES5 browsers +- Fix 1585: make _mocha executable again +- chore(package.json): add a8m as a contributor +- Fixed broken link on html-cov reporter +- support --es_staging flag +- fix issue where menu overlaps content. +- update contributors in package.json +- Remove trailing whitespace from reporter output +- Remove contributors list from readme +- log third-party reporter errors +- [Fix] Exclude not own properties when looping on options +- fix: support node args in mocha.opts (close #1573) +- fix(reporter/base): string diff - issue #1241 + +# 2.2.1 / 2015-03-09 + +- Fix passing of args intended for node/iojs. + +# 2.2.0 / 2015-03-06 + +- Update mocha.js +- Add --fgrep. Use grep for RegExp, fgrep for str +- Ignore async global errors after spec resolution +- Fixing errors that prevent mocha.js from loading in the browser - fixes #1558 +- fix(utils): issue #1558 + make +- add ability to delay root suite; closes #362, closes #1124 +- fix insanity in http tests +- update travis: add node 0.12, add gitter, remove slack +- building +- resolve #1548: ensure the environment's "node" executable is used +- reporters/base: use supports-color to detect colorable term +- travis: use docker containers +- small fix: commander option for --expose-gc +- Ignore asynchronous errors after global failure +- Improve error output when a test fails with a non-error +- updated travis badge, uses svg instead of img +- Allow skip from test context for #332 +- [JSHINT] Unnecessary semicolon fixed in bin/_mocha +- Added a reminder about the done() callback to test timeout error messages +- fixes #1496, in Mocha.run(fn), check if fn exists before executing it, added tests too +- Add Harmony Proxy flag for iojs +- test(utils|ms|*): test existing units +- add support for some iojs flags +- fix(utils.stringify): issue #1229, diff viewer +- Remove slack link +- Prevent multiple 'grep=' querystring params in html reporter +- Use grep as regexp (close #1381) +- utils.stringify should handle objects without an Object prototype +- in runnable test, comparing to undefined error's message rather than a literal +- Fix test running output truncation on async STDIO +- amended for deprecated customFds option in child_process + +# 2.1.0 / 2014-12-23 + +- showDiff: don’t stringify strings +- Clean up unused module dependencies. +- Filter zero-length strings from mocha.opts +- only write to stdout in reporters +- Revert "only write to stdout in reporters" +- Print colored output only to a tty +- update summary in README.md +- rename Readme.md/History.md to README.md/HISTORY.md because neurotic +- add .mailmap to fix "git shortlog" or "git summary" output +- fixes #1461: nyan-reporter now respects Base.useColors, fixed bug where Base.color would not return a string when str wasn't a string. +- Use existing test URL builder in failed replay links +- modify .travis.yml: use travis_retry; closes #1449 +- fix -t 0 behavior; closes #1446 +- fix tests (whoops) +- improve diff behavior +- Preserve pathname when linking to individual tests +- Fix test +- Tiny typo in comments fixed +- after hooks now being called on failed tests when using bail, fixes #1093 +- fix throwing undefined/null now makes tests fail, fixes #1395 +- compiler extensions are added as watched extensions, removed non-standard extensions from watch regex, resolves #1221 +- prefix/namespace for suite titles in markdown reporter, fixes #554 +- fix more bad markdown in CONTRIBUTING.md +- fix bad markdown in CONTRIBUTING.md +- add setImmediate/clearImmediate to globals; closes #1435 +- Fix buffer diffs (closes #1132, closes #1433) +- add a CONTRIBUTING.md. closes #882 +- fix intermittent build failures (maybe). closes #1407 +- add Slack notification to .travis.yml +- Fix slack link +- Add slack room to readme +- Update maintainers +- update maintainers and contributors +- resolves #1393: kill children with more effort on SIGINT +- xunit reporter support for optionally writing to a file +- if a reporter has a .done method, call it before exiting +- add support for reporter options +- only write to stdout in reporters + +# 2.0.0 / 2014-10-21 + +- remove: support for node 0.6.x, 0.4.x +- fix: landing reporter with non ansi characters (#211) +- fix: html reporter - preserve query params when navigating to suites/tests (#1358) +- fix: json stream reporter add error message to failed test +- fix: fixes for visionmedia -> mochajs +- fix: use stdio, fixes node deprecation warnings (#1391) + +# 1.21.5 / 2014-10-11 + +- fix: build for NodeJS v0.6.x +- fix: do not attempt to highlight syntax when non-HTML reporter is used +- update: escape-string-regexp to 1.0.2. +- fix: botched indentation in canonicalize() +- fix: .gitignore: ignore .patch and .diff files +- fix: changed 'Catched' to 'Caught' in uncaught exception error handler messages +- add: `pending` field for json reporter +- fix: Runner.prototype.uncaught: don't double-end runnables that already have a state. +- fix: --recursive, broken by f0facd2e +- update: replaces escapeRegexp with the escape-string-regexp package. +- update: commander to 2.3.0. +- update: diff to 1.0.8. +- fix: ability to disable syntax highlighting (#1329) +- fix: added empty object to errorJSON() call to catch when no error is present +- fix: never time out after calling enableTimeouts(false) +- fix: timeout(0) will work at suite level (#1300) +- Fix for --watch+only() issue (#888 ) +- fix: respect err.showDiff, add Base reporter test (#810) + +# 1.22.1-3 / 2014-07-27 + +- fix: disabling timeouts with this.timeout(0) (#1301) + +# 1.22.1-3 / 2014-07-27 + +- fix: local uis and reporters (#1288) +- fix: building 1.21.0's changes in the browser (#1284) + +# 1.21.0 / 2014-07-23 + +- add: --no-timeouts option (#1262, #1268) +- add: --*- deprecation node flags (#1217) +- add: --watch-extensions argument (#1247) +- change: spec reporter is default (#1228) +- fix: diff output showing incorrect +/- (#1182) +- fix: diffs of circular structures (#1179) +- fix: re-render the progress bar when progress has changed only (#1151) +- fix support for environments with global and window (#1159) +- fix: reverting to previously defined onerror handler (#1178) +- fix: stringify non error objects passed to done() (#1270) +- fix: using local ui, reporters (#1267) +- fix: cleaning es6 arrows (#1176) +- fix: don't include attrs in failure tag for xunit (#1244) +- fix: fail tests that return a promise if promise is rejected w/o a reason (#1224) +- fix: showing failed tests in doc reporter (#1117) +- fix: dot reporter dots being off (#1204) +- fix: catch empty throws (#1219) +- fix: honoring timeout for sync operations (#1242) +- update: growl to 1.8.0 + +# 1.20.1 / 2014-06-03 + +- update: should dev dependency to ~4.0.0 (#1231) + +# 1.20.0 / 2014-05-28 + +- add: filenames to suite objects (#1222) + +# 1.19.0 / 2014-05-17 + +- add: browser script option to package.json +- add: export file in Mocha.Test objects (#1174) +- add: add docs for wrapped node flags +- fix: mocha.run() to return error status in browser (#1216) +- fix: clean() to show failure details (#1205) +- fix: regex that generates html for new keyword (#1201) +- fix: sibling suites have inherited but separate contexts (#1164) + +# 1.18.2 / 2014-03-18 + +- fix: html runner was prevented from using #mocha as the default root el (#1162) + +# 1.18.1 / 2014-03-18 + +- fix: named before/after hooks in bdd, tdd, qunit interfaces (#1161) + +# 1.18.0 / 2014-03-13 + +- add: promise support (#329) +- add: named before/after hooks (#966) + +# 1.17.1 / 2014-01-22 + +- fix: expected messages in should.js (should.js#168) +- fix: expect errno global in node versions < v0.9.11 (#1111) +- fix: unreliable checkGlobals optimization (#1110) + +# 1.17.0 / 2014-01-09 + +- add: able to require globals (describe, it, etc.) through mocha (#1077) +- fix: abort previous run on --watch change (#1100) +- fix: reset context for each --watch triggered run (#1099) +- fix: error when cli can't resolve path or pattern (#799) +- fix: canonicalize objects before stringifying and diffing them (#1079) +- fix: make CR call behave like carriage return for non tty (#1087) + +# 1.16.2 / 2013-12-23 + +- fix: couple issues with ie 8 (#1082, #1081) +- fix: issue running the xunit reporter in browsers (#1068) +- fix: issue with firefox < 3.5 (#725) + +# 1.16.1 / 2013-12-19 + +- fix: recompiled for missed changes from the last release + +# 1.16.0 / 2013-12-19 + +- add: Runnable.globals(arr) for per test global whitelist (#1046) +- add: mocha.throwError(err) for assertion libs to call (#985) +- remove: --watch's spinner (#806) +- fix: duplicate test output for multi-line specs in spec reporter (#1006) +- fix: gracefully exit on SIGINT (#1063) +- fix expose the specified ui only in the browser (#984) +- fix: ensure process exit code is preserved when using --no-exit (#1059) +- fix: return true from window.onerror handler (#868) +- fix: xunit reporter to use process.stdout.write (#1068) +- fix: utils.clean(str) indentation (#761) +- fix: xunit reporter returning test duration a NaN (#1039) + +# 1.15.1 / 2013-12-03 + +- fix: recompiled for missed changes from the last release + +# 1.15.0 / 2013-12-02 + +- add: `--no-exit` to prevent `process.exit()` (#1018) +- fix: using inline diffs (#1044) +- fix: show pending test details in xunit reporter (#1051) +- fix: faster global leak detection (#1024) +- fix: yui compression (#1035) +- fix: wrapping long lines in test results (#1030, #1031) +- fix: handle errors in hooks (#1043) + +# 1.14.0 / 2013-11-02 + +- add: unified diff (#862) +- add: set MOCHA_COLORS env var to use colors (#965) +- add: able to override tests links in html reporters (#776) +- remove: teamcity reporter (#954) +- update: commander dependency to 2.0.0 (#1010) +- fix: mocha --ui will try to require the ui if not built in, as --reporter does (#1022) +- fix: send cursor commands only if isatty (#184, #1003) +- fix: include assertion message in base reporter (#993, #991) +- fix: consistent return of it, it.only, and describe, describe.only (#840) + +# 1.13.0 / 2013-09-15 + +- add: sort test files with --sort (#813) +- update: diff dependency to 1.0.7 +- update: glob dependency to 3.2.3 (#927) +- fix: diffs show whitespace differences (#976) +- fix: improve global leaks (#783) +- fix: firefox window.getInterface leak +- fix: accessing iframe via window[iframeIndex] leak +- fix: faster global leak checking +- fix: reporter pending css selector (#970) + +# 1.12.1 / 2013-08-29 + +- remove test.js from .gitignore +- update included version of ms.js + +# 1.12.0 / 2013-07-01 + +- add: prevent diffs for differing types. Closes #900 +- add `Mocha.process` hack for phantomjs +- fix: use compilers with requires +- fix regexps in diffs. Closes #890 +- fix xunit NaN on failure. Closes #894 +- fix: strip tab indentation in `clean` utility method +- fix: textmate bundle installation + +# 1.11.0 / 2013-06-12 + +- add --prof support +- add --harmony support +- add --harmony-generators support +- add "Uncaught " prefix to uncaught exceptions +- add web workers support +- add `suite.skip()` +- change to output # of pending / passing even on failures. Closes #872 +- fix: prevent hooks from being called if we are bailing +- fix `this.timeout(0)` + +# 1.10.0 / 2013-05-21 + +- add add better globbing support for windows via `glob` module +- add support to pass through flags such as --debug-brk=1234. Closes #852 +- add test.only, test.skip to qunit interface +- change to always use word-based diffs for now. Closes #733 +- change `mocha init` tests.html to index.html +- fix `process` global leak in the browser +- fix: use resolve() instead of join() for --require +- fix: filterLeaks() condition to not consider indices in global object as leaks +- fix: restrict mocha.css styling to #mocha id +- fix: save timer references to avoid Sinon interfering in the browser build. + +# 1.9.0 / 2013-04-03 + +- add improved setImmediate implementation +- replace --ignore-leaks with --check-leaks +- change default of ignoreLeaks to true. Closes #791 +- remove scrolling for HTML reporter +- fix retina support +- fix tmbundle, restrict to js scope + +# 1.8.2 / 2013-03-11 + +- add `setImmediate` support for 0.10.x +- fix mocha -w spinner on windows + +# 1.8.1 / 2013-01-09 + +- fix .bail() arity check causing it to default to true + +# 1.8.0 / 2013-01-08 + +- add Mocha() options bail support +- add `Mocha#bail()` method +- add instanceof check back for inheriting from Error +- add component.json +- add diff.js to browser build +- update growl +- fix TAP reporter failures comment :D + +# 1.7.4 / 2012-12-06 + +- add total number of passes and failures to TAP +- remove .bind() calls. re #680 +- fix indexOf. Closes #680 + +# 1.7.3 / 2012-11-30 + +- fix uncaught error support for the browser +- revert uncaught "fix" which breaks node + +# 1.7.2 / 2012-11-28 + +- fix uncaught errors to expose the original error message + +# 1.7.0 / 2012-11-07 + +- add `--async-only` support to prevent false positives for missing `done()` +- add sorting by filename in code coverage +- add HTML 5 doctype to browser template. +- add play button to html reporter to rerun a single test +- add `this.timeout(ms)` as Suite#timeout(ms). Closes #599 +- update growl dependency to 1.6.x +- fix encoding of test-case ?grep. Closes #637 +- fix unicode chars on windows +- fix dom globals in Opera/IE. Closes #243 +- fix markdown reporter a tags +- fix `this.timeout("5s")` support + +# 1.6.0 / 2012-10-02 + +- add object diffs when `err.showDiff` is present +- add hiding of empty suites when pass/failures are toggled +- add faster `.length` checks to `checkGlobals()` before performing the filter + +# 1.5.0 / 2012-09-21 + +- add `ms()` to `.slow()` and `.timeout()` +- add `Mocha#checkLeaks()` to re-enable global leak checks +- add `this.slow()` option [aheckmann] +- add tab, CR, LF to error diffs for now +- add faster `.checkGlobals()` solution [guille] +- remove `fn.call()` from reduce util +- remove `fn.call()` from filter util +- fix forEach. Closes #582 +- fix relaying of signals [TooTallNate] +- fix TAP reporter grep number + +# 1.4.2 / 2012-09-01 + +- add support to multiple `Mocha#globals()` calls, and strings +- add `mocha.reporter()` constructor support [jfirebaugh] +- add `mocha.timeout()` +- move query-string parser to utils.js +- move highlight code to utils.js +- fix third-party reporter support [exogen] +- fix client-side API to match node-side [jfirebaugh] +- fix mocha in iframe [joliss] + +# 1.4.1 / 2012-08-28 + +- add missing `Markdown` export +- fix `Mocha#grep()`, escape regexp strings +- fix reference error when `devicePixelRatio` is not defined. Closes #549 + +# 1.4.0 / 2012-08-22 + +- add mkdir -p to `mocha init`. Closes #539 +- add `.only()`. Closes #524 +- add `.skip()`. Closes #524 +- change str.trim() to use utils.trim(). Closes #533 +- fix HTML progress indicator retina display +- fix url-encoding of click-to-grep HTML functionality + +# 1.3.2 / 2012-08-01 + +- fix exports double-execution regression. Closes #531 + +# 1.3.1 / 2012-08-01 + +- add passes/failures toggling to HTML reporter +- add pending state to `xit()` and `xdescribe()` [Brian Moore] +- add the @charset "UTF-8"; to fix #522 with FireFox. [Jonathan Creamer] +- add border-bottom to #stats links +- add check for runnable in `Runner#uncaught()`. Closes #494 +- add 0.4 and 0.6 back to travis.yml +- add `-E, --growl-errors` to growl on failures only +- add prefixes to debug() names. Closes #497 +- add `Mocha#invert()` to js api +- change dot reporter to use sexy unicode dots +- fix error when clicking pending test in HTML reporter +- fix `make tm` + +# 1.3.0 / 2012-07-05 + +- add window scrolling to `HTML` reporter +- add v8 `--trace-*` option support +- add support for custom reports via `--reporter MODULE` +- add `--invert` switch to invert `--grep` matches +- fix export of `Nyan` reporter. Closes #495 +- fix escaping of `HTML` suite titles. Closes #486 +- fix `done()` called multiple times with an error test +- change `--grep` - regexp escape the input + +# 1.2.2 / 2012-06-28 + +- Added 0.8.0 support + +# 1.2.1 / 2012-06-25 + +- Added `this.test.error(err)` support to after each hooks. Closes #287 +- Added: export top-level suite on global mocha object (mocha.suite). Closes #448 +- Fixed `js` code block format error in markdown reporter +- Fixed deprecation warning when using `path.existsSync` +- Fixed --globals with wildcard +- Fixed chars in nyan when his head moves back +- Remove `--growl` from test/mocha.opts. Closes #289 + +# 1.2.0 / 2012-06-17 + +- Added `nyan` reporter [Atsuya Takagi] +- Added `mocha init ` to copy client files +- Added "specify" synonym for "it" [domenic] +- Added global leak wildcard support [nathanbowser] +- Fixed runner emitter leak. closes #432 +- Fixed omission of .js extension. Closes #454 + +# 1.1.0 / 2012-05-30 + +- Added: check each `mocha(1)` arg for directories to walk +- Added `--recursive` [tricknotes] +- Added `context` for BDD [hokaccha] +- Added styling for new clickable titles +- Added clickable suite titles to HTML reporter +- Added warning when strings are thrown as errors +- Changed: green arrows again in HTML reporter styling +- Changed ul/li elements instead of divs for better copy-and-pasting [joliss] +- Fixed issue #325 - add better grep support to js api +- Fixed: save timer references to avoid Sinon interfering. + +# 1.0.3 / 2012-04-30 + +- Fixed string diff newlines +- Fixed: removed mocha.css target. Closes #401 + +# 1.0.2 / 2012-04-25 + +- Added HTML reporter duration. Closes #47 +- Fixed: one postMessage event listener [exogen] +- Fixed: allow --globals to be used multiple times. Closes #100 [brendannee] +- Fixed #158: removes jquery include from browser tests +- Fixed grep. Closes #372 [brendannee] +- Fixed #166 - When grepping don't display the empty suites +- Removed test/browser/style.css. Closes #385 + +# 1.0.1 / 2012-04-04 + +- Fixed `.timeout()` in hooks +- Fixed: allow callback for `mocha.run()` in client version +- Fixed browser hook error display. Closes #361 + +# 1.0.0 / 2012-03-24 + +- Added js API. Closes #265 +- Added: initial run of tests with `--watch`. Closes #345 +- Added: mark `location` as a global on the CS. Closes #311 +- Added `markdown` reporter (github flavour) +- Added: scrolling menu to coverage.html. Closes #335 +- Added source line to html report for Safari [Tyson Tate] +- Added "min" reporter, useful for `--watch` [Jakub Nešetřil] +- Added support for arbitrary compilers via . Closes #338 [Ian Young] +- Added Teamcity export to lib/reporters/index [Michael Riley] +- Fixed chopping of first char in error reporting. Closes #334 [reported by topfunky] +- Fixed terrible FF / Opera stack traces + +# 0.14.1 / 2012-03-06 + +- Added lib-cov to _.npmignore_ +- Added reporter to `mocha.run([reporter])` as argument +- Added some margin-top to the HTML reporter +- Removed jQuery dependency +- Fixed `--watch`: purge require cache. Closes #266 + +# 0.14.0 / 2012-03-01 + +- Added string diff support for terminal reporters + +# 0.13.0 / 2012-02-23 + +- Added preliminary test coverage support. Closes #5 +- Added `HTMLCov` reporter +- Added `JSONCov` reporter [kunklejr] +- Added `xdescribe()` and `xit()` to the BDD interface. Closes #263 (docs * Changed: make json reporter output pretty json +- Fixed node-inspector support, swapped `--debug` for `debug` to match node. Closes #247 + +# 0.12.1 / 2012-02-14 + +- Added `npm docs mocha` support [TooTallNate] +- Added a `Context` object used for hook and test-case this. Closes #253 +- Fixed `Suite#clone()` `.ctx` reference. Closes #262 + +# 0.12.0 / 2012-02-02 + +- Added .coffee `--watch` support. Closes #242 +- Added support to `--require` files relative to the CWD. Closes #241 +- Added quick n dirty syntax highlighting. Closes #248 +- Changed: made HTML progress indicator smaller +- Fixed xunit errors attribute [dhendo] + +# 0.10.2 / 2012-01-21 + +- Fixed suite count in reporter stats. Closes #222 +- Fixed `done()` after timeout error reporting [Phil Sung] +- Changed the 0-based errors to 1 + +# 0.10.1 / 2012-01-17 + +- Added support for node 0.7.x +- Fixed absolute path support. Closes #215 [kompiro] +- Fixed `--no-colors` option [Jussi Virtanen] +- Fixed Arial CSS typo in the correct file + +# 0.10.0 / 2012-01-13 + +- Added `-b, --bail` to exit on first exception [guillermo] +- Added support for `-gc` / `--expose-gc` [TooTallNate] +- Added `qunit`-inspired interface +- Added MIT LICENSE. Closes #194 +- Added: `--watch` all .js in the CWD. Closes #139 +- Fixed `self.test` reference in runner. Closes #189 +- Fixed double reporting of uncaught exceptions after timeout. Closes #195 + +# 0.8.2 / 2012-01-05 + +- Added test-case context support. Closes #113 +- Fixed exit status. Closes #187 +- Update commander. Closes #190 + +# 0.8.1 / 2011-12-30 + +- Fixed reporting of uncaught exceptions. Closes #183 +- Fixed error message defaulting [indutny] +- Changed mocha(1) from bash to node for windows [Nathan Rajlich] + +# 0.8.0 / 2011-12-28 + +- Added `XUnit` reporter [FeeFighters/visionmedia] +- Added `say(1)` notification support [Maciej Małecki] +- Changed: fail when done() is invoked with a non-Error. Closes #171 +- Fixed `err.stack`, defaulting to message. Closes #180 +- Fixed: `make tm` mkdir -p the dest. Closes #137 +- Fixed mocha(1) --help bin name +- Fixed `-d` for `--debug` support + +# 0.7.1 / 2011-12-22 + +- Removed `mocha-debug(1)`, use `mocha --debug` +- Fixed CWD relative requires +- Fixed growl issue on windows [Raynos] +- Fixed: platform specific line endings [TooTallNate] +- Fixed: escape strings in HTML reporter. Closes #164 + +# 0.7.0 / 2011-12-18 + +- Added support for IE{7,8} [guille] +- Changed: better browser nextTick implementation [guille] + +# 0.6.0 / 2011-12-18 + +- Added setZeroTimeout timeout for browser (nicer stack traces). Closes #153 +- Added "view source" on hover for HTML reporter to make it obvious +- Changed: replace custom growl with growl lib +- Fixed duplicate reporting for HTML reporter. Closes #154 +- Fixed silent hook errors in the HTML reporter. Closes #150 + +# 0.5.0 / 2011-12-14 + +- Added: push node_modules directory onto module.paths for relative require Closes #93 +- Added teamcity reporter [blindsey] +- Fixed: recover from uncaught exceptions for tests. Closes #94 +- Fixed: only emit "test end" for uncaught within test, not hook + +# 0.4.0 / 2011-12-14 + +- Added support for test-specific timeouts via `this.timeout(0)`. Closes #134 +- Added guillermo's client-side EventEmitter. Closes #132 +- Added progress indicator to the HTML reporter +- Fixed slow browser tests. Closes #135 +- Fixed "suite" color for light terminals +- Fixed `require()` leak spotted by [guillermo] + +# 0.3.6 / 2011-12-09 + +- Removed suite merging (for now) + +# 0.3.5 / 2011-12-08 + +- Added support for `window.onerror` [guillermo] +- Fixed: clear timeout on uncaught exceptions. Closes #131 [guillermo] +- Added `mocha.css` to PHONY list. +- Added `mocha.js` to PHONY list. + +# 0.3.4 / 2011-12-08 + +- Added: allow `done()` to be called with non-Error +- Added: return Runner from `mocha.run()`. Closes #126 +- Fixed: run afterEach even on failures. Closes #125 +- Fixed clobbering of current runnable. Closes #121 + +# 0.3.3 / 2011-12-08 + +- Fixed hook timeouts. Closes #120 +- Fixed uncaught exceptions in hooks + +# 0.3.2 / 2011-12-05 + +- Fixed weird reporting when `err.message` is not present + +# 0.3.1 / 2011-12-04 + +- Fixed hook event emitter leak. Closes #117 +- Fixed: export `Spec` constructor. Closes #116 + +# 0.3.0 / 2011-12-04 + +- Added `-w, --watch`. Closes #72 +- Added `--ignore-leaks` to ignore global leak checking +- Added browser `?grep=pattern` support +- Added `--globals ` to specify accepted globals. Closes #99 +- Fixed `mocha-debug(1)` on some systems. Closes #232 +- Fixed growl total, use `runner.total` + +# 0.2.0 / 2011-11-30 + +- Added `--globals ` to specify accepted globals. Closes #99 +- Fixed funky highlighting of messages. Closes #97 +- Fixed `mocha-debug(1)`. Closes #232 +- Fixed growl total, use runner.total + +# 0.1.0 / 2011-11-29 + +- Added `suiteSetup` and `suiteTeardown` to TDD interface [David Henderson] +- Added growl icons. Closes #84 +- Fixed coffee-script support + +# 0.0.8 / 2011-11-25 + +- Fixed: use `Runner#total` for accurate reporting + +# 0.0.7 / 2011-11-25 + +- Added `Hook` +- Added `Runnable` +- Changed: `Test` is `Runnable` +- Fixed global leak reporting in hooks +- Fixed: > 2 calls to done() only report the error once +- Fixed: clear timer on failure. Closes #80 + +# 0.0.6 / 2011-11-25 + +- Fixed return on immediate async error. Closes #80 + +# 0.0.5 / 2011-11-24 + +- Fixed: make mocha.opts whitespace less picky [kkaefer] + +# 0.0.4 / 2011-11-24 + +- Added `--interfaces` +- Added `--reporters` +- Added `-c, --colors`. Closes #69 +- Fixed hook timeouts + +# 0.0.3 / 2011-11-23 + +- Added `-C, --no-colors` to explicitly disable +- Added coffee-script support + +# 0.0.2 / 2011-11-22 + +- Fixed global leak detection due to Safari bind() change +- Fixed: escape html entities in Doc reporter +- Fixed: escape html entities in HTML reporter +- Fixed pending test support for HTML reporter. Closes #66 + +# 0.0.1 / 2011-11-22 + +- Added `--timeout` second shorthand support, ex `--timeout 3s`. +- Fixed "test end" event for uncaughtExceptions. Closes #61 + +# 0.0.1-alpha6 / 2011-11-19 + +- Added travis CI support (needs enabling when public) +- Added preliminary browser support +- Added `make mocha.css` target. Closes #45 +- Added stack trace to TAP errors. Closes #52 +- Renamed tearDown to teardown. Closes #49 +- Fixed: cascading hooksc. Closes #30 +- Fixed some colors for non-tty +- Fixed errors thrown in sync test-cases due to nextTick +- Fixed Base.window.width... again give precedence to 0.6.x + +# 0.0.1-alpha5 / 2011-11-17 + +- Added `doc` reporter. Closes #33 +- Added suite merging. Closes #28 +- Added TextMate bundle and `make tm`. Closes #20 + +# 0.0.1-alpha4 / 2011-11-15 + +- Fixed getWindowSize() for 0.4.x + +# 0.0.1-alpha3 / 2011-11-15 + +- Added `-s, --slow ` to specify "slow" test threshold +- Added `mocha-debug(1)` +- Added `mocha.opts` support. Closes #31 +- Added: default [files] to _test/*.js_ +- Added protection against multiple calls to `done()`. Closes #35 +- Changed: bright yellow for slow Dot reporter tests + +# 0.0.1-alpha2 / 2011-11-08 + +- Missed this one :) + +# 0.0.1-alpha1 / 2011-11-08 + +- Initial release diff --git a/node_modules/mocha/LICENSE b/node_modules/mocha/LICENSE new file mode 100644 index 0000000..9ab23f6 --- /dev/null +++ b/node_modules/mocha/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2011-2018 JS Foundation and contributors, https://js.foundation + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/mocha/README.md b/node_modules/mocha/README.md new file mode 100644 index 0000000..9655920 --- /dev/null +++ b/node_modules/mocha/README.md @@ -0,0 +1,104 @@ +

+ Mocha test framework +

+ +

:coffee: Simple, flexible, fun JavaScript test framework for Node.js & The Browser :coffee:

+ +

Build Status Coverage Status FOSSA Status Gitter OpenCollective OpenCollective +

+ +


Mocha Browser Support h/t SauceLabs

+ +## Links + +- **[Documentation](https://mochajs.org)** +- **[Release Notes / History / Changes](https://github.com/mochajs/mocha/blob/master/CHANGELOG.md)** +- [Code of Conduct](https://github.com/mochajs/mocha/blob/master/.github/CODE_OF_CONDUCT.md) +- [Gitter Chatroom](https://gitter.im/mochajs/mocha) (ask questions here!) +- [Google Group](https://groups.google.com/group/mochajs) +- [Issue Tracker](https://github.com/mochajs/mocha/issues) + +## Backers + +[Become a backer](https://opencollective.com/mochajs#backer) and show your support to our open source project. + +[![MochaJS Backer](https://opencollective.com/mochajs/backer/0/avatar)](https://opencollective.com/mochajs/backer/0/website) +[![MochaJS Backer](https://opencollective.com/mochajs/backer/1/avatar)](https://opencollective.com/mochajs/backer/1/website) +[![MochaJS Backer](https://opencollective.com/mochajs/backer/2/avatar)](https://opencollective.com/mochajs/backer/2/website) +[![MochaJS Backer](https://opencollective.com/mochajs/backer/3/avatar)](https://opencollective.com/mochajs/backer/3/website) +[![MochaJS Backer](https://opencollective.com/mochajs/backer/4/avatar)](https://opencollective.com/mochajs/backer/4/website) +[![MochaJS Backer](https://opencollective.com/mochajs/backer/5/avatar)](https://opencollective.com/mochajs/backer/5/website) +[![MochaJS Backer](https://opencollective.com/mochajs/backer/6/avatar)](https://opencollective.com/mochajs/backer/6/website) +[![MochaJS Backer](https://opencollective.com/mochajs/backer/7/avatar)](https://opencollective.com/mochajs/backer/7/website) +[![MochaJS Backer](https://opencollective.com/mochajs/backer/8/avatar)](https://opencollective.com/mochajs/backer/8/website) +[![MochaJS Backer](https://opencollective.com/mochajs/backer/9/avatar)](https://opencollective.com/mochajs/backer/9/website) +[![MochaJS Backer](https://opencollective.com/mochajs/backer/10/avatar)](https://opencollective.com/mochajs/backer/10/website) +[![MochaJS Backer](https://opencollective.com/mochajs/backer/11/avatar)](https://opencollective.com/mochajs/backer/11/website) +[![MochaJS Backer](https://opencollective.com/mochajs/backer/12/avatar)](https://opencollective.com/mochajs/backer/12/website) +[![MochaJS Backer](https://opencollective.com/mochajs/backer/13/avatar)](https://opencollective.com/mochajs/backer/13/website) +[![MochaJS Backer](https://opencollective.com/mochajs/backer/14/avatar)](https://opencollective.com/mochajs/backer/14/website) +[![MochaJS Backer](https://opencollective.com/mochajs/backer/15/avatar)](https://opencollective.com/mochajs/backer/15/website) +[![MochaJS Backer](https://opencollective.com/mochajs/backer/16/avatar)](https://opencollective.com/mochajs/backer/16/website) +[![MochaJS Backer](https://opencollective.com/mochajs/backer/17/avatar)](https://opencollective.com/mochajs/backer/17/website) +[![MochaJS Backer](https://opencollective.com/mochajs/backer/18/avatar)](https://opencollective.com/mochajs/backer/18/website) +[![MochaJS Backer](https://opencollective.com/mochajs/backer/19/avatar)](https://opencollective.com/mochajs/backer/19/website) +[![MochaJS Backer](https://opencollective.com/mochajs/backer/20/avatar)](https://opencollective.com/mochajs/backer/20/website) +[![MochaJS Backer](https://opencollective.com/mochajs/backer/21/avatar)](https://opencollective.com/mochajs/backer/21/website) +[![MochaJS Backer](https://opencollective.com/mochajs/backer/22/avatar)](https://opencollective.com/mochajs/backer/22/website) +[![MochaJS Backer](https://opencollective.com/mochajs/backer/23/avatar)](https://opencollective.com/mochajs/backer/23/website) +[![MochaJS Backer](https://opencollective.com/mochajs/backer/24/avatar)](https://opencollective.com/mochajs/backer/24/website) +[![MochaJS Backer](https://opencollective.com/mochajs/backer/25/avatar)](https://opencollective.com/mochajs/backer/25/website) +[![MochaJS Backer](https://opencollective.com/mochajs/backer/26/avatar)](https://opencollective.com/mochajs/backer/26/website) +[![MochaJS Backer](https://opencollective.com/mochajs/backer/27/avatar)](https://opencollective.com/mochajs/backer/27/website) +[![MochaJS Backer](https://opencollective.com/mochajs/backer/28/avatar)](https://opencollective.com/mochajs/backer/28/website) +[![MochaJS Backer](https://opencollective.com/mochajs/backer/29/avatar)](https://opencollective.com/mochajs/backer/29/website) + +## Sponsors + +Does your company use Mocha? Ask your manager or marketing team if your company would be interested in supporting our project. Support will allow the maintainers to dedicate more time for maintenance and new features for everyone. Also, your company's logo will show [on GitHub](https://github.com/mochajs/mocha#readme) and on [our site](https://mochajs.org) - who doesn't want a little extra exposure? [Here's the info](https://opencollective.com/mochajs#sponsor). + +[![MochaJS Backer](https://opencollective.com/mochajs/sponsor/0/avatar)](https://opencollective.com/mochajs/sponsor/0/website) +[![MochaJS Backer](https://opencollective.com/mochajs/sponsor/1/avatar)](https://opencollective.com/mochajs/sponsor/1/website) +[![MochaJS Backer](https://opencollective.com/mochajs/sponsor/2/avatar)](https://opencollective.com/mochajs/sponsor/2/website) +[![MochaJS Backer](https://opencollective.com/mochajs/sponsor/3/avatar)](https://opencollective.com/mochajs/sponsor/3/website) +[![MochaJS Backer](https://opencollective.com/mochajs/sponsor/4/avatar)](https://opencollective.com/mochajs/sponsor/4/website) +[![MochaJS Backer](https://opencollective.com/mochajs/sponsor/5/avatar)](https://opencollective.com/mochajs/sponsor/5/website) +[![MochaJS Backer](https://opencollective.com/mochajs/sponsor/6/avatar)](https://opencollective.com/mochajs/sponsor/6/website) +[![MochaJS Backer](https://opencollective.com/mochajs/sponsor/7/avatar)](https://opencollective.com/mochajs/sponsor/7/website) +[![MochaJS Backer](https://opencollective.com/mochajs/sponsor/8/avatar)](https://opencollective.com/mochajs/sponsor/8/website) +[![MochaJS Backer](https://opencollective.com/mochajs/sponsor/9/avatar)](https://opencollective.com/mochajs/sponsor/9/website) +[![MochaJS Backer](https://opencollective.com/mochajs/sponsor/10/avatar)](https://opencollective.com/mochajs/sponsor/10/website) +[![MochaJS Backer](https://opencollective.com/mochajs/sponsor/11/avatar)](https://opencollective.com/mochajs/sponsor/11/website) +[![MochaJS Backer](https://opencollective.com/mochajs/sponsor/12/avatar)](https://opencollective.com/mochajs/sponsor/12/website) +[![MochaJS Backer](https://opencollective.com/mochajs/sponsor/13/avatar)](https://opencollective.com/mochajs/sponsor/13/website) +[![MochaJS Backer](https://opencollective.com/mochajs/sponsor/14/avatar)](https://opencollective.com/mochajs/sponsor/14/website) +[![MochaJS Backer](https://opencollective.com/mochajs/sponsor/15/avatar)](https://opencollective.com/mochajs/sponsor/15/website) +[![MochaJS Backer](https://opencollective.com/mochajs/sponsor/16/avatar)](https://opencollective.com/mochajs/sponsor/16/website) +[![MochaJS Backer](https://opencollective.com/mochajs/sponsor/17/avatar)](https://opencollective.com/mochajs/sponsor/17/website) +[![MochaJS Backer](https://opencollective.com/mochajs/sponsor/18/avatar)](https://opencollective.com/mochajs/sponsor/18/website) +[![MochaJS Backer](https://opencollective.com/mochajs/sponsor/19/avatar)](https://opencollective.com/mochajs/sponsor/19/website) + +## Development + +You might want to know that: + +- Mocha is the *most-depended-upon* module on npm (source: [libraries.io](https://libraries.io/search?order=desc&platforms=NPM&sort=dependents_count)), and +- Mocha is an *independent* open-source project, maintained exclusively by volunteers. + +You might want to help: + +- New to contributing to Mocha? Check out this list of [good first issues](https://github.com/mochajs/mocha/issues?q=is%3Aissue+is%3Aopen+label%3Agood-first-issue) +- Mocha could use a hand with [these issues](https://github.com/mochajs/mocha/issues?q=is%3Aissue+is%3Aopen+label%3A%22help+wanted%22) +- The [maintainer's handbook](https://github.com/mochajs/mocha/blob/master/MAINTAINERS.md) explains how things get done + +Finally, come [chat with the maintainers](https://gitter.im/mochajs/contributors) on Gitter if you want to help with: + +- Triaging issues, answering questions +- Review, merging, and closing pull requests +- Other project-maintenance-y things + +## License + +[MIT](LICENSE) + +[![FOSSA Status](https://app.fossa.io/api/projects/git%2Bhttps%3A%2F%2Fgithub.com%2Fmochajs%2Fmocha.svg?type=large)](https://app.fossa.io/projects/git%2Bhttps%3A%2F%2Fgithub.com%2Fmochajs%2Fmocha?ref=badge_large) diff --git a/node_modules/mocha/bin/_mocha b/node_modules/mocha/bin/_mocha new file mode 100755 index 0000000..7e2a47a --- /dev/null +++ b/node_modules/mocha/bin/_mocha @@ -0,0 +1,647 @@ +#!/usr/bin/env node +'use strict'; + +/* eslint no-unused-vars: off */ + +/** + * Module dependencies. + */ + +const program = require('commander'); +const path = require('path'); +const fs = require('fs'); +const minimatch = require('minimatch'); +const resolve = path.resolve; +const exists = fs.existsSync; +const Mocha = require('../'); +const utils = Mocha.utils; +const interfaceNames = Object.keys(Mocha.interfaces); +const join = path.join; +const cwd = process.cwd(); +const getOptions = require('./options'); +const mocha = new Mocha(); + +/** + * Save timer references to avoid Sinon interfering (see GH-237). + */ + +const Date = global.Date; +const setTimeout = global.setTimeout; +const setInterval = global.setInterval; +const clearTimeout = global.clearTimeout; +const clearInterval = global.clearInterval; + +/** + * Exits Mocha when tests + code under test has finished execution (default) + * @param {number} code - Exit code; typically # of failures + */ +const exitLater = code => { + process.on('exit', () => { + process.exit(Math.min(code, 255)); + }); +}; + +/** + * Exits Mocha when Mocha itself has finished execution, regardless of + * what the tests or code under test is doing. + * @param {number} code - Exit code; typically # of failures + */ +const exit = code => { + const clampedCode = Math.min(code, 255); + let draining = 0; + + // Eagerly set the process's exit code in case stream.write doesn't + // execute its callback before the process terminates. + process.exitCode = clampedCode; + + // flush output for Node.js Windows pipe bug + // https://github.com/joyent/node/issues/6247 is just one bug example + // https://github.com/visionmedia/mocha/issues/333 has a good discussion + const done = () => { + if (!draining--) { + process.exit(clampedCode); + } + }; + + const streams = [process.stdout, process.stderr]; + + streams.forEach(stream => { + // submit empty write request and wait for completion + draining += 1; + stream.write('', done); + }); + + done(); +}; + +/** + * Parse list. + */ +const list = str => str.split(/ *, */); + +/** + * Parse multiple flag. + */ +const collect = (val, memo) => memo.concat(val); + +/** + * Hide the cursor. + */ +const hideCursor = () => { + process.stdout.write('\u001b[?25l'); +}; + +/** + * Show the cursor. + */ +const showCursor = () => { + process.stdout.write('\u001b[?25h'); +}; + +/** + * Stop play()ing. + */ +const stop = () => { + process.stdout.write('\u001b[2K'); + clearInterval(play.timer); +}; + +/** + * Play the given array of strings. + */ +const play = (arr, interval) => { + const len = arr.length; + interval = interval || 100; + let i = 0; + + play.timer = setInterval(() => { + const str = arr[i++ % len]; + process.stdout.write(`\u001b[0G${str}`); + }, interval); +}; + +/** + * Files. + */ + +let files = []; + +/** + * Globals. + */ + +let globals = []; + +/** + * Requires. + */ + +const requires = []; + +/** + * Images. + */ + +const images = { + fail: path.join(__dirname, '..', 'assets', 'growl', 'error.png'), + pass: path.join(__dirname, '..', 'assets', 'growl', 'ok.png') +}; + +// options + +program + .version( + JSON.parse( + fs.readFileSync(path.join(__dirname, '..', 'package.json'), 'utf8') + ).version + ) + .usage('[debug] [options] [files]') + .option( + '-A, --async-only', + 'force all tests to take a callback (async) or return a promise' + ) + .option('-c, --colors', 'force enabling of colors') + .option('-C, --no-colors', 'force disabling of colors') + .option('-G, --growl', 'enable growl notification support') + .option('-O, --reporter-options ', 'reporter-specific options') + .option('-R, --reporter ', 'specify the reporter to use', 'spec') + .option('-S, --sort', 'sort test files') + .option('-b, --bail', 'bail after first test failure') + .option('-d, --debug', "enable node's debugger, synonym for node --debug") + .option('-g, --grep ', 'only run tests matching ') + .option('-f, --fgrep ', 'only run tests containing ') + .option('-gc, --expose-gc', 'expose gc extension') + .option('-i, --invert', 'inverts --grep and --fgrep matches') + .option('-r, --require ', 'require the given module') + .option('-s, --slow ', '"slow" test threshold in milliseconds [75]') + .option('-t, --timeout ', 'set test-case timeout in milliseconds [2000]') + .option( + '-u, --ui ', + `specify user-interface (${interfaceNames.join('|')})`, + 'bdd' + ) + .option('-w, --watch', 'watch files for changes') + .option('--check-leaks', 'check for global variable leaks') + .option('--full-trace', 'display the full stack trace') + .option( + '--compilers :,...', + 'use the given module(s) to compile files', + list, + [] + ) + .option('--debug-brk', "enable node's debugger breaking on the first line") + .option( + '--globals ', + 'allow the given comma-delimited global [names]', + list, + [] + ) + .option('--es_staging', 'enable all staged features') + .option( + '--harmony<_classes,_generators,...>', + 'all node --harmony* flags are available' + ) + .option( + '--preserve-symlinks', + 'Instructs the module loader to preserve symbolic links when resolving and caching modules' + ) + .option('--icu-data-dir', 'include ICU data') + .option( + '--inline-diffs', + 'display actual/expected differences inline within each string' + ) + .option('--no-diff', 'do not show a diff on failure') + .option('--inspect', 'activate devtools in chrome') + .option( + '--inspect-brk', + 'activate devtools in chrome and break on the first line' + ) + .option('--interfaces', 'display available interfaces') + .option('--no-deprecation', 'silence deprecation warnings') + .option( + '--exit', + 'force shutdown of the event loop after test run: mocha will call process.exit' + ) + .option('--no-timeouts', 'disables timeouts, given implicitly with --debug') + .option('--no-warnings', 'silence all node process warnings') + .option('--opts ', 'specify opts path', 'test/mocha.opts') + .option('--perf-basic-prof', 'enable perf linux profiler (basic support)') + .option('--napi-modules', 'enable experimental NAPI modules') + .option('--prof', 'log statistical profiling information') + .option('--log-timer-events', 'Time events including external callbacks') + .option('--recursive', 'include sub directories') + .option('--reporters', 'display available reporters') + .option( + '--retries ', + 'set numbers of time to retry a failed test case' + ) + .option( + '--throw-deprecation', + 'throw an exception anytime a deprecated function is used' + ) + .option('--trace', 'trace function calls') + .option('--trace-deprecation', 'show stack traces on deprecations') + .option('--trace-warnings', 'show stack traces on node process warnings') + .option('--use_strict', 'enforce strict mode') + .option( + '--watch-extensions ,...', + 'additional extensions to monitor with --watch', + list, + ['js'] + ) + .option('--delay', 'wait for async suite definition') + .option('--allow-uncaught', 'enable uncaught errors to propagate') + .option('--forbid-only', 'causes test marked with only to fail the suite') + .option( + '--forbid-pending', + 'causes pending tests and test marked with skip to fail the suite' + ) + .option( + '--file ', + 'include a file to be ran during the suite', + collect, + [] + ) + .option('--exclude ', 'a file or glob pattern to ignore', collect, []); + +program._name = 'mocha'; + +// init command + +program + .command('init ') + .description('initialize a client-side mocha setup at ') + .action(path => { + const mkdir = require('mkdirp'); + mkdir.sync(path); + const css = fs.readFileSync(join(__dirname, '..', 'mocha.css')); + const js = fs.readFileSync(join(__dirname, '..', 'mocha.js')); + const tmpl = fs.readFileSync(join(__dirname, '..', 'lib/template.html')); + fs.writeFileSync(join(path, 'mocha.css'), css); + fs.writeFileSync(join(path, 'mocha.js'), js); + fs.writeFileSync(join(path, 'tests.js'), ''); + fs.writeFileSync(join(path, 'index.html'), tmpl); + process.exit(0); + }); + +// --globals + +program.on('option:globals', val => { + globals = globals.concat(list(val)); +}); + +// --reporters + +program.on('option:reporters', () => { + console.log(); + console.log(' dot - dot matrix'); + console.log(' doc - html documentation'); + console.log(' spec - hierarchical spec list'); + console.log(' json - single json object'); + console.log(' progress - progress bar'); + console.log(' list - spec-style listing'); + console.log(' tap - test-anything-protocol'); + console.log(' landing - unicode landing strip'); + console.log(' xunit - xunit reporter'); + console.log(' min - minimal reporter (great with --watch)'); + console.log(' json-stream - newline delimited json events'); + console.log(' markdown - markdown documentation (github flavour)'); + console.log(' nyan - nyan cat!'); + console.log(); + process.exit(); +}); + +// --interfaces + +program.on('option:interfaces', () => { + console.log(''); + interfaceNames.forEach(interfaceName => { + console.log(` ${interfaceName}`); + }); + console.log(''); + process.exit(); +}); + +// -r, --require + +module.paths.push(cwd, join(cwd, 'node_modules')); + +program.on('option:require', mod => { + const abs = exists(mod) || exists(`${mod}.js`); + if (abs) { + mod = resolve(mod); + } + requires.push(mod); +}); + +// If not already done, load mocha.opts +if (!process.env.LOADED_MOCHA_OPTS) { + getOptions(); +} + +// parse args + +program.parse(process.argv); + +// infinite stack traces + +Error.stackTraceLimit = Infinity; // TODO: config + +// reporter options + +const reporterOptions = {}; +if (program.reporterOptions !== undefined) { + program.reporterOptions.split(',').forEach(opt => { + const L = opt.split('='); + if (L.length > 2 || L.length === 0) { + throw new Error(`invalid reporter option '${opt}'`); + } else if (L.length === 2) { + reporterOptions[L[0]] = L[1]; + } else { + reporterOptions[L[0]] = true; + } + }); +} + +// reporter + +mocha.reporter(program.reporter, reporterOptions); + +// --no-colors + +if (!program.colors) { + mocha.useColors(false); +} + +// --colors + +if (~process.argv.indexOf('--colors') || ~process.argv.indexOf('-c')) { + mocha.useColors(true); +} + +// --inline-diffs + +if (program.inlineDiffs) { + mocha.useInlineDiffs(true); +} + +// --no-diff + +if (process.argv.indexOf('--no-diff') !== -1) { + mocha.hideDiff(true); +} + +// --slow + +if (program.slow) { + mocha.suite.slow(program.slow); +} + +// --no-timeouts + +if (!program.timeouts) { + mocha.enableTimeouts(false); +} + +// --timeout + +if (program.timeout) { + mocha.suite.timeout(program.timeout); +} + +// --bail + +mocha.suite.bail(program.bail); + +// --grep + +if (program.grep) { + mocha.grep(program.grep); +} + +// --fgrep + +if (program.fgrep) { + mocha.fgrep(program.fgrep); +} + +// --invert + +if (program.invert) { + mocha.invert(); +} + +// --check-leaks + +if (program.checkLeaks) { + mocha.checkLeaks(); +} + +// --stack-trace + +if (program.fullTrace) { + mocha.fullTrace(); +} + +// --growl + +if (program.growl) { + mocha.growl(); +} + +// --async-only + +if (program.asyncOnly) { + mocha.asyncOnly(); +} + +// --delay + +if (program.delay) { + mocha.delay(); +} + +// --allow-uncaught + +if (program.allowUncaught) { + mocha.allowUncaught(); +} + +// --globals + +mocha.globals(globals); + +// --retries + +if (program.retries) { + mocha.suite.retries(program.retries); +} + +// --forbid-only + +if (program.forbidOnly) mocha.forbidOnly(); + +// --forbid-pending + +if (program.forbidPending) mocha.forbidPending(); + +// custom compiler support + +if (program.compilers.length > 0) { + require('util').deprecate(() => {}, + '"--compilers" will be removed in a future version of Mocha; see https://git.io/vdcSr for more info')(); +} +const extensions = ['js']; +program.compilers.forEach(c => { + const idx = c.indexOf(':'); + const ext = c.slice(0, idx); + let mod = c.slice(idx + 1); + + if (mod[0] === '.') { + mod = join(process.cwd(), mod); + } + require(mod); + extensions.push(ext); + program.watchExtensions.push(ext); +}); + +// requires + +requires.forEach(mod => { + require(mod); +}); + +// interface + +mocha.ui(program.ui); + +// args + +const args = program.args; + +// default files to test/*.{js,coffee} + +if (!args.length) { + args.push('test'); +} + +args.forEach(arg => { + let newFiles; + try { + newFiles = utils.lookupFiles(arg, extensions, program.recursive); + } catch (err) { + if (err.message.indexOf('cannot resolve path') === 0) { + console.error( + `Warning: Could not find any test files matching pattern: ${arg}` + ); + return; + } + + throw err; + } + + if (typeof newFiles !== 'undefined') { + if (typeof newFiles === 'string') { + newFiles = [newFiles]; + } + newFiles = newFiles.filter(fileName => + program.exclude.every(pattern => !minimatch(fileName, pattern)) + ); + } + + files = files.concat(newFiles); +}); + +if (!files.length) { + console.error('No test files found'); + process.exit(1); +} + +// resolve +let fileArgs = program.file.map(path => resolve(path)); +files = files.map(path => resolve(path)); + +if (program.sort) { + files.sort(); +} + +// add files given through --file to be ran first +files = fileArgs.concat(files); + +// --watch + +let runner; +let loadAndRun; +let purge; +let rerun; + +if (program.watch) { + console.log(); + hideCursor(); + process.on('SIGINT', () => { + showCursor(); + console.log('\n'); + process.exit(130); + }); + + const watchFiles = utils.files(cwd, ['js'].concat(program.watchExtensions)); + let runAgain = false; + + loadAndRun = () => { + try { + mocha.files = files; + runAgain = false; + runner = mocha.run(() => { + runner = null; + if (runAgain) { + rerun(); + } + }); + } catch (e) { + console.log(e.stack); + } + }; + + purge = () => { + watchFiles.forEach(file => { + delete require.cache[file]; + }); + }; + + loadAndRun(); + + rerun = () => { + purge(); + stop(); + if (!program.grep) { + mocha.grep(null); + } + mocha.suite = mocha.suite.clone(); + mocha.suite.ctx = new Mocha.Context(); + mocha.ui(program.ui); + loadAndRun(); + }; + + utils.watch(watchFiles, () => { + runAgain = true; + if (runner) { + runner.abort(); + } else { + rerun(); + } + }); +} else { + // load + + mocha.files = files; + runner = mocha.run(program.exit ? exit : exitLater); +} + +process.on('SIGINT', () => { + runner.abort(); + + // This is a hack: + // Instead of `process.exit(130)`, set runner.failures to 130 (exit code for SIGINT) + // The amount of failures will be emitted as error code later + runner.failures = 130; +}); diff --git a/node_modules/mocha/bin/mocha b/node_modules/mocha/bin/mocha new file mode 100755 index 0000000..38d09fb --- /dev/null +++ b/node_modules/mocha/bin/mocha @@ -0,0 +1,89 @@ +#!/usr/bin/env node + +'use strict'; + +/** + * This tiny wrapper file checks for known node flags and appends them + * when found, before invoking the "real" _mocha(1) executable. + */ + +const spawn = require('child_process').spawn; +const path = require('path'); +const getOptions = require('./options'); +const args = [path.join(__dirname, '_mocha')]; + +// Load mocha.opts into process.argv +// Must be loaded here to handle node-specific options +getOptions(); + +process.argv.slice(2).forEach(arg => { + const flag = arg.split('=')[0]; + + switch (flag) { + case '-d': + args.unshift('--debug'); + args.push('--no-timeouts'); + break; + case 'debug': + case '--debug': + case '--debug-brk': + case '--inspect': + case '--inspect-brk': + args.unshift(arg); + args.push('--no-timeouts'); + break; + case '-gc': + case '--expose-gc': + args.unshift('--expose-gc'); + break; + case '--gc-global': + case '--es_staging': + case '--no-deprecation': + case '--no-warnings': + case '--prof': + case '--log-timer-events': + case '--throw-deprecation': + case '--trace-deprecation': + case '--trace-warnings': + case '--use_strict': + case '--allow-natives-syntax': + case '--perf-basic-prof': + case '--napi-modules': + args.unshift(arg); + break; + default: + if (arg.indexOf('--harmony') === 0) { + args.unshift(arg); + } else if (arg.indexOf('--trace') === 0) { + args.unshift(arg); + } else if (arg.indexOf('--icu-data-dir') === 0) { + args.unshift(arg); + } else if (arg.indexOf('--max-old-space-size') === 0) { + args.unshift(arg); + } else if (arg.indexOf('--preserve-symlinks') === 0) { + args.unshift(arg); + } else { + args.push(arg); + } + break; + } +}); + +const proc = spawn(process.execPath, args, { + stdio: 'inherit' +}); +proc.on('exit', (code, signal) => { + process.on('exit', () => { + if (signal) { + process.kill(process.pid, signal); + } else { + process.exit(code); + } + }); +}); + +// terminate children. +process.on('SIGINT', () => { + proc.kill('SIGINT'); // calls runner.abort() + proc.kill('SIGTERM'); // if that didn't work, we're probably in an infinite loop, so make it die. +}); diff --git a/node_modules/mocha/bin/options.js b/node_modules/mocha/bin/options.js new file mode 100644 index 0000000..a25a18e --- /dev/null +++ b/node_modules/mocha/bin/options.js @@ -0,0 +1,49 @@ +'use strict'; + +/** + * Dependencies. + */ + +const fs = require('fs'); + +/** + * Export `getOptions`. + */ + +module.exports = getOptions; + +/** + * Get options. + */ + +function getOptions() { + if ( + process.argv.length === 3 && + (process.argv[2] === '-h' || process.argv[2] === '--help') + ) { + return; + } + + const optsPath = + process.argv.indexOf('--opts') === -1 + ? 'test/mocha.opts' + : process.argv[process.argv.indexOf('--opts') + 1]; + + try { + const opts = fs + .readFileSync(optsPath, 'utf8') + .replace(/^#.*$/gm, '') + .replace(/\\\s/g, '%20') + .split(/\s/) + .filter(Boolean) + .map(value => value.replace(/%20/g, ' ')); + + process.argv = process.argv + .slice(0, 2) + .concat(opts.concat(process.argv.slice(2))); + } catch (ignore) { + // NOTE: should console.error() and throw the error + } + + process.env.LOADED_MOCHA_OPTS = true; +} diff --git a/node_modules/mocha/browser-entry.js b/node_modules/mocha/browser-entry.js new file mode 100644 index 0000000..ad422e6 --- /dev/null +++ b/node_modules/mocha/browser-entry.js @@ -0,0 +1,191 @@ +'use strict'; + +/* eslint no-unused-vars: off */ +/* eslint-env commonjs */ + +/** + * Shim process.stdout. + */ + +process.stdout = require('browser-stdout')({level: false}); + +var Mocha = require('./lib/mocha'); + +/** + * Create a Mocha instance. + * + * @return {undefined} + */ + +var mocha = new Mocha({reporter: 'html'}); + +/** + * Save timer references to avoid Sinon interfering (see GH-237). + */ + +var Date = global.Date; +var setTimeout = global.setTimeout; +var setInterval = global.setInterval; +var clearTimeout = global.clearTimeout; +var clearInterval = global.clearInterval; + +var uncaughtExceptionHandlers = []; + +var originalOnerrorHandler = global.onerror; + +/** + * Remove uncaughtException listener. + * Revert to original onerror handler if previously defined. + */ + +process.removeListener = function(e, fn) { + if (e === 'uncaughtException') { + if (originalOnerrorHandler) { + global.onerror = originalOnerrorHandler; + } else { + global.onerror = function() {}; + } + var i = uncaughtExceptionHandlers.indexOf(fn); + if (i !== -1) { + uncaughtExceptionHandlers.splice(i, 1); + } + } +}; + +/** + * Implements uncaughtException listener. + */ + +process.on = function(e, fn) { + if (e === 'uncaughtException') { + global.onerror = function(err, url, line) { + fn(new Error(err + ' (' + url + ':' + line + ')')); + return !mocha.allowUncaught; + }; + uncaughtExceptionHandlers.push(fn); + } +}; + +// The BDD UI is registered by default, but no UI will be functional in the +// browser without an explicit call to the overridden `mocha.ui` (see below). +// Ensure that this default UI does not expose its methods to the global scope. +mocha.suite.removeAllListeners('pre-require'); + +var immediateQueue = []; +var immediateTimeout; + +function timeslice() { + var immediateStart = new Date().getTime(); + while (immediateQueue.length && new Date().getTime() - immediateStart < 100) { + immediateQueue.shift()(); + } + if (immediateQueue.length) { + immediateTimeout = setTimeout(timeslice, 0); + } else { + immediateTimeout = null; + } +} + +/** + * High-performance override of Runner.immediately. + */ + +Mocha.Runner.immediately = function(callback) { + immediateQueue.push(callback); + if (!immediateTimeout) { + immediateTimeout = setTimeout(timeslice, 0); + } +}; + +/** + * Function to allow assertion libraries to throw errors directly into mocha. + * This is useful when running tests in a browser because window.onerror will + * only receive the 'message' attribute of the Error. + */ +mocha.throwError = function(err) { + uncaughtExceptionHandlers.forEach(function(fn) { + fn(err); + }); + throw err; +}; + +/** + * Override ui to ensure that the ui functions are initialized. + * Normally this would happen in Mocha.prototype.loadFiles. + */ + +mocha.ui = function(ui) { + Mocha.prototype.ui.call(this, ui); + this.suite.emit('pre-require', global, null, this); + return this; +}; + +/** + * Setup mocha with the given setting options. + */ + +mocha.setup = function(opts) { + if (typeof opts === 'string') { + opts = {ui: opts}; + } + for (var opt in opts) { + if (opts.hasOwnProperty(opt)) { + this[opt](opts[opt]); + } + } + return this; +}; + +/** + * Run mocha, returning the Runner. + */ + +mocha.run = function(fn) { + var options = mocha.options; + mocha.globals('location'); + + var query = Mocha.utils.parseQuery(global.location.search || ''); + if (query.grep) { + mocha.grep(query.grep); + } + if (query.fgrep) { + mocha.fgrep(query.fgrep); + } + if (query.invert) { + mocha.invert(); + } + + return Mocha.prototype.run.call(mocha, function(err) { + // The DOM Document is not available in Web Workers. + var document = global.document; + if ( + document && + document.getElementById('mocha') && + options.noHighlighting !== true + ) { + Mocha.utils.highlightTags('code'); + } + if (fn) { + fn(err); + } + }); +}; + +/** + * Expose the process shim. + * https://github.com/mochajs/mocha/pull/916 + */ + +Mocha.process = process; + +/** + * Expose mocha. + */ + +global.Mocha = Mocha; +global.mocha = mocha; + +// this allows test/acceptance/required-tokens.js to pass; thus, +// you can now do `const describe = require('mocha').describe` in a +// browser context (assuming browserification). should fix #880 +module.exports = global; diff --git a/node_modules/mocha/index.js b/node_modules/mocha/index.js new file mode 100644 index 0000000..d2b7d19 --- /dev/null +++ b/node_modules/mocha/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./lib/mocha'); diff --git a/node_modules/mocha/lib/browser/growl.js b/node_modules/mocha/lib/browser/growl.js new file mode 100644 index 0000000..28c62ef --- /dev/null +++ b/node_modules/mocha/lib/browser/growl.js @@ -0,0 +1,5 @@ +'use strict'; + +// just stub out growl + +module.exports = require('../utils').noop; diff --git a/node_modules/mocha/lib/browser/progress.js b/node_modules/mocha/lib/browser/progress.js new file mode 100644 index 0000000..7bf400b --- /dev/null +++ b/node_modules/mocha/lib/browser/progress.js @@ -0,0 +1,119 @@ +'use strict'; + +/** + * Expose `Progress`. + */ + +module.exports = Progress; + +/** + * Initialize a new `Progress` indicator. + */ +function Progress() { + this.percent = 0; + this.size(0); + this.fontSize(11); + this.font('helvetica, arial, sans-serif'); +} + +/** + * Set progress size to `size`. + * + * @api public + * @param {number} size + * @return {Progress} Progress instance. + */ +Progress.prototype.size = function(size) { + this._size = size; + return this; +}; + +/** + * Set text to `text`. + * + * @api public + * @param {string} text + * @return {Progress} Progress instance. + */ +Progress.prototype.text = function(text) { + this._text = text; + return this; +}; + +/** + * Set font size to `size`. + * + * @api public + * @param {number} size + * @return {Progress} Progress instance. + */ +Progress.prototype.fontSize = function(size) { + this._fontSize = size; + return this; +}; + +/** + * Set font to `family`. + * + * @param {string} family + * @return {Progress} Progress instance. + */ +Progress.prototype.font = function(family) { + this._font = family; + return this; +}; + +/** + * Update percentage to `n`. + * + * @param {number} n + * @return {Progress} Progress instance. + */ +Progress.prototype.update = function(n) { + this.percent = n; + return this; +}; + +/** + * Draw on `ctx`. + * + * @param {CanvasRenderingContext2d} ctx + * @return {Progress} Progress instance. + */ +Progress.prototype.draw = function(ctx) { + try { + var percent = Math.min(this.percent, 100); + var size = this._size; + var half = size / 2; + var x = half; + var y = half; + var rad = half - 1; + var fontSize = this._fontSize; + + ctx.font = fontSize + 'px ' + this._font; + + var angle = Math.PI * 2 * (percent / 100); + ctx.clearRect(0, 0, size, size); + + // outer circle + ctx.strokeStyle = '#9f9f9f'; + ctx.beginPath(); + ctx.arc(x, y, rad, 0, angle, false); + ctx.stroke(); + + // inner circle + ctx.strokeStyle = '#eee'; + ctx.beginPath(); + ctx.arc(x, y, rad - 1, 0, angle, true); + ctx.stroke(); + + // text + var text = this._text || (percent | 0) + '%'; + var w = ctx.measureText(text).width; + + ctx.fillText(text, x - w / 2 + 1, y + fontSize / 2 - 1); + } catch (ignore) { + // don't fail if we can't render progress + } + return this; +}; diff --git a/node_modules/mocha/lib/browser/tty.js b/node_modules/mocha/lib/browser/tty.js new file mode 100644 index 0000000..e903365 --- /dev/null +++ b/node_modules/mocha/lib/browser/tty.js @@ -0,0 +1,13 @@ +'use strict'; + +exports.isatty = function isatty() { + return true; +}; + +exports.getWindowSize = function getWindowSize() { + if ('innerHeight' in global) { + return [global.innerHeight, global.innerWidth]; + } + // In a Web Worker, the DOM Window is not available. + return [640, 480]; +}; diff --git a/node_modules/mocha/lib/context.js b/node_modules/mocha/lib/context.js new file mode 100644 index 0000000..812162b --- /dev/null +++ b/node_modules/mocha/lib/context.js @@ -0,0 +1,101 @@ +'use strict'; +/** + * @module Context + */ +/** + * Expose `Context`. + */ + +module.exports = Context; + +/** + * Initialize a new `Context`. + * + * @api private + */ +function Context() {} + +/** + * Set or get the context `Runnable` to `runnable`. + * + * @api private + * @param {Runnable} runnable + * @return {Context} context + */ +Context.prototype.runnable = function(runnable) { + if (!arguments.length) { + return this._runnable; + } + this.test = this._runnable = runnable; + return this; +}; + +/** + * Set or get test timeout `ms`. + * + * @api private + * @param {number} ms + * @return {Context} self + */ +Context.prototype.timeout = function(ms) { + if (!arguments.length) { + return this.runnable().timeout(); + } + this.runnable().timeout(ms); + return this; +}; + +/** + * Set test timeout `enabled`. + * + * @api private + * @param {boolean} enabled + * @return {Context} self + */ +Context.prototype.enableTimeouts = function(enabled) { + if (!arguments.length) { + return this.runnable().enableTimeouts(); + } + this.runnable().enableTimeouts(enabled); + return this; +}; + +/** + * Set or get test slowness threshold `ms`. + * + * @api private + * @param {number} ms + * @return {Context} self + */ +Context.prototype.slow = function(ms) { + if (!arguments.length) { + return this.runnable().slow(); + } + this.runnable().slow(ms); + return this; +}; + +/** + * Mark a test as skipped. + * + * @api private + * @throws Pending + */ +Context.prototype.skip = function() { + this.runnable().skip(); +}; + +/** + * Set or get a number of allowed retries on failed tests + * + * @api private + * @param {number} n + * @return {Context} self + */ +Context.prototype.retries = function(n) { + if (!arguments.length) { + return this.runnable().retries(); + } + this.runnable().retries(n); + return this; +}; diff --git a/node_modules/mocha/lib/hook.js b/node_modules/mocha/lib/hook.js new file mode 100644 index 0000000..71440d2 --- /dev/null +++ b/node_modules/mocha/lib/hook.js @@ -0,0 +1,46 @@ +'use strict'; + +var Runnable = require('./runnable'); +var inherits = require('./utils').inherits; + +/** + * Expose `Hook`. + */ + +module.exports = Hook; + +/** + * Initialize a new `Hook` with the given `title` and callback `fn` + * + * @class + * @extends Runnable + * @param {String} title + * @param {Function} fn + */ +function Hook(title, fn) { + Runnable.call(this, title, fn); + this.type = 'hook'; +} + +/** + * Inherit from `Runnable.prototype`. + */ +inherits(Hook, Runnable); + +/** + * Get or set the test `err`. + * + * @memberof Hook + * @public + * @param {Error} err + * @return {Error} + */ +Hook.prototype.error = function(err) { + if (!arguments.length) { + err = this._error; + this._error = null; + return err; + } + + this._error = err; +}; diff --git a/node_modules/mocha/lib/interfaces/bdd.js b/node_modules/mocha/lib/interfaces/bdd.js new file mode 100644 index 0000000..730e67e --- /dev/null +++ b/node_modules/mocha/lib/interfaces/bdd.js @@ -0,0 +1,114 @@ +'use strict'; + +var Test = require('../test'); + +/** + * BDD-style interface: + * + * describe('Array', function() { + * describe('#indexOf()', function() { + * it('should return -1 when not present', function() { + * // ... + * }); + * + * it('should return the index when present', function() { + * // ... + * }); + * }); + * }); + * + * @param {Suite} suite Root suite. + */ +module.exports = function bddInterface(suite) { + var suites = [suite]; + + suite.on('pre-require', function(context, file, mocha) { + var common = require('./common')(suites, context, mocha); + + context.before = common.before; + context.after = common.after; + context.beforeEach = common.beforeEach; + context.afterEach = common.afterEach; + context.run = mocha.options.delay && common.runWithSuite(suite); + /** + * Describe a "suite" with the given `title` + * and callback `fn` containing nested suites + * and/or tests. + */ + + context.describe = context.context = function(title, fn) { + return common.suite.create({ + title: title, + file: file, + fn: fn + }); + }; + + /** + * Pending describe. + */ + + context.xdescribe = context.xcontext = context.describe.skip = function( + title, + fn + ) { + return common.suite.skip({ + title: title, + file: file, + fn: fn + }); + }; + + /** + * Exclusive suite. + */ + + context.describe.only = function(title, fn) { + return common.suite.only({ + title: title, + file: file, + fn: fn + }); + }; + + /** + * Describe a specification or test-case + * with the given `title` and callback `fn` + * acting as a thunk. + */ + + context.it = context.specify = function(title, fn) { + var suite = suites[0]; + if (suite.isPending()) { + fn = null; + } + var test = new Test(title, fn); + test.file = file; + suite.addTest(test); + return test; + }; + + /** + * Exclusive test-case. + */ + + context.it.only = function(title, fn) { + return common.test.only(mocha, context.it(title, fn)); + }; + + /** + * Pending test case. + */ + + context.xit = context.xspecify = context.it.skip = function(title) { + return context.it(title); + }; + + /** + * Number of attempts to retry. + */ + context.it.retries = function(n) { + context.retries(n); + }; + }); +}; diff --git a/node_modules/mocha/lib/interfaces/common.js b/node_modules/mocha/lib/interfaces/common.js new file mode 100644 index 0000000..4ca340a --- /dev/null +++ b/node_modules/mocha/lib/interfaces/common.js @@ -0,0 +1,160 @@ +'use strict'; + +var Suite = require('../suite'); + +/** + * Functions common to more than one interface. + * + * @param {Suite[]} suites + * @param {Context} context + * @param {Mocha} mocha + * @return {Object} An object containing common functions. + */ +module.exports = function(suites, context, mocha) { + return { + /** + * This is only present if flag --delay is passed into Mocha. It triggers + * root suite execution. + * + * @param {Suite} suite The root suite. + * @return {Function} A function which runs the root suite + */ + runWithSuite: function runWithSuite(suite) { + return function run() { + suite.run(); + }; + }, + + /** + * Execute before running tests. + * + * @param {string} name + * @param {Function} fn + */ + before: function(name, fn) { + suites[0].beforeAll(name, fn); + }, + + /** + * Execute after running tests. + * + * @param {string} name + * @param {Function} fn + */ + after: function(name, fn) { + suites[0].afterAll(name, fn); + }, + + /** + * Execute before each test case. + * + * @param {string} name + * @param {Function} fn + */ + beforeEach: function(name, fn) { + suites[0].beforeEach(name, fn); + }, + + /** + * Execute after each test case. + * + * @param {string} name + * @param {Function} fn + */ + afterEach: function(name, fn) { + suites[0].afterEach(name, fn); + }, + + suite: { + /** + * Create an exclusive Suite; convenience function + * See docstring for create() below. + * + * @param {Object} opts + * @returns {Suite} + */ + only: function only(opts) { + opts.isOnly = true; + return this.create(opts); + }, + + /** + * Create a Suite, but skip it; convenience function + * See docstring for create() below. + * + * @param {Object} opts + * @returns {Suite} + */ + skip: function skip(opts) { + opts.pending = true; + return this.create(opts); + }, + + /** + * Creates a suite. + * @param {Object} opts Options + * @param {string} opts.title Title of Suite + * @param {Function} [opts.fn] Suite Function (not always applicable) + * @param {boolean} [opts.pending] Is Suite pending? + * @param {string} [opts.file] Filepath where this Suite resides + * @param {boolean} [opts.isOnly] Is Suite exclusive? + * @returns {Suite} + */ + create: function create(opts) { + var suite = Suite.create(suites[0], opts.title); + suite.pending = Boolean(opts.pending); + suite.file = opts.file; + suites.unshift(suite); + if (opts.isOnly) { + suite.parent._onlySuites = suite.parent._onlySuites.concat(suite); + } + if (typeof opts.fn === 'function') { + opts.fn.call(suite); + suites.shift(); + } else if (typeof opts.fn === 'undefined' && !suite.pending) { + throw new Error( + 'Suite "' + + suite.fullTitle() + + '" was defined but no callback was supplied. Supply a callback or explicitly skip the suite.' + ); + } else if (!opts.fn && suite.pending) { + suites.shift(); + } + + return suite; + } + }, + + test: { + /** + * Exclusive test-case. + * + * @param {Object} mocha + * @param {Function} test + * @returns {*} + */ + only: function(mocha, test) { + test.parent._onlyTests = test.parent._onlyTests.concat(test); + return test; + }, + + /** + * Pending test case. + * + * @param {string} title + */ + skip: function(title) { + context.test(title); + }, + + /** + * Number of retry attempts + * + * @param {number} n + */ + retries: function(n) { + context.retries(n); + } + } + }; +}; diff --git a/node_modules/mocha/lib/interfaces/exports.js b/node_modules/mocha/lib/interfaces/exports.js new file mode 100644 index 0000000..1a5c5bb --- /dev/null +++ b/node_modules/mocha/lib/interfaces/exports.js @@ -0,0 +1,58 @@ +'use strict'; +var Suite = require('../suite'); +var Test = require('../test'); + +/** + * Exports-style (as Node.js module) interface: + * + * exports.Array = { + * '#indexOf()': { + * 'should return -1 when the value is not present': function() { + * + * }, + * + * 'should return the correct index when the value is present': function() { + * + * } + * } + * }; + * + * @param {Suite} suite Root suite. + */ +module.exports = function(suite) { + var suites = [suite]; + + suite.on('require', visit); + + function visit(obj, file) { + var suite; + for (var key in obj) { + if (typeof obj[key] === 'function') { + var fn = obj[key]; + switch (key) { + case 'before': + suites[0].beforeAll(fn); + break; + case 'after': + suites[0].afterAll(fn); + break; + case 'beforeEach': + suites[0].beforeEach(fn); + break; + case 'afterEach': + suites[0].afterEach(fn); + break; + default: + var test = new Test(key, fn); + test.file = file; + suites[0].addTest(test); + } + } else { + suite = Suite.create(suites[0], key); + suites.unshift(suite); + visit(obj[key], file); + suites.shift(); + } + } + } +}; diff --git a/node_modules/mocha/lib/interfaces/index.js b/node_modules/mocha/lib/interfaces/index.js new file mode 100644 index 0000000..0bd810a --- /dev/null +++ b/node_modules/mocha/lib/interfaces/index.js @@ -0,0 +1,6 @@ +'use strict'; + +exports.bdd = require('./bdd'); +exports.tdd = require('./tdd'); +exports.qunit = require('./qunit'); +exports.exports = require('./exports'); diff --git a/node_modules/mocha/lib/interfaces/qunit.js b/node_modules/mocha/lib/interfaces/qunit.js new file mode 100644 index 0000000..ad3c900 --- /dev/null +++ b/node_modules/mocha/lib/interfaces/qunit.js @@ -0,0 +1,95 @@ +'use strict'; + +var Test = require('../test'); + +/** + * QUnit-style interface: + * + * suite('Array'); + * + * test('#length', function() { + * var arr = [1,2,3]; + * ok(arr.length == 3); + * }); + * + * test('#indexOf()', function() { + * var arr = [1,2,3]; + * ok(arr.indexOf(1) == 0); + * ok(arr.indexOf(2) == 1); + * ok(arr.indexOf(3) == 2); + * }); + * + * suite('String'); + * + * test('#length', function() { + * ok('foo'.length == 3); + * }); + * + * @param {Suite} suite Root suite. + */ +module.exports = function qUnitInterface(suite) { + var suites = [suite]; + + suite.on('pre-require', function(context, file, mocha) { + var common = require('./common')(suites, context, mocha); + + context.before = common.before; + context.after = common.after; + context.beforeEach = common.beforeEach; + context.afterEach = common.afterEach; + context.run = mocha.options.delay && common.runWithSuite(suite); + /** + * Describe a "suite" with the given `title`. + */ + + context.suite = function(title) { + if (suites.length > 1) { + suites.shift(); + } + return common.suite.create({ + title: title, + file: file, + fn: false + }); + }; + + /** + * Exclusive Suite. + */ + + context.suite.only = function(title) { + if (suites.length > 1) { + suites.shift(); + } + return common.suite.only({ + title: title, + file: file, + fn: false + }); + }; + + /** + * Describe a specification or test-case + * with the given `title` and callback `fn` + * acting as a thunk. + */ + + context.test = function(title, fn) { + var test = new Test(title, fn); + test.file = file; + suites[0].addTest(test); + return test; + }; + + /** + * Exclusive test-case. + */ + + context.test.only = function(title, fn) { + return common.test.only(mocha, context.test(title, fn)); + }; + + context.test.skip = common.test.skip; + context.test.retries = common.test.retries; + }); +}; diff --git a/node_modules/mocha/lib/interfaces/tdd.js b/node_modules/mocha/lib/interfaces/tdd.js new file mode 100644 index 0000000..1e72cf7 --- /dev/null +++ b/node_modules/mocha/lib/interfaces/tdd.js @@ -0,0 +1,102 @@ +'use strict'; + +var Test = require('../test'); + +/** + * TDD-style interface: + * + * suite('Array', function() { + * suite('#indexOf()', function() { + * suiteSetup(function() { + * + * }); + * + * test('should return -1 when not present', function() { + * + * }); + * + * test('should return the index when present', function() { + * + * }); + * + * suiteTeardown(function() { + * + * }); + * }); + * }); + * + * @param {Suite} suite Root suite. + */ +module.exports = function(suite) { + var suites = [suite]; + + suite.on('pre-require', function(context, file, mocha) { + var common = require('./common')(suites, context, mocha); + + context.setup = common.beforeEach; + context.teardown = common.afterEach; + context.suiteSetup = common.before; + context.suiteTeardown = common.after; + context.run = mocha.options.delay && common.runWithSuite(suite); + + /** + * Describe a "suite" with the given `title` and callback `fn` containing + * nested suites and/or tests. + */ + context.suite = function(title, fn) { + return common.suite.create({ + title: title, + file: file, + fn: fn + }); + }; + + /** + * Pending suite. + */ + context.suite.skip = function(title, fn) { + return common.suite.skip({ + title: title, + file: file, + fn: fn + }); + }; + + /** + * Exclusive test-case. + */ + context.suite.only = function(title, fn) { + return common.suite.only({ + title: title, + file: file, + fn: fn + }); + }; + + /** + * Describe a specification or test-case with the given `title` and + * callback `fn` acting as a thunk. + */ + context.test = function(title, fn) { + var suite = suites[0]; + if (suite.isPending()) { + fn = null; + } + var test = new Test(title, fn); + test.file = file; + suite.addTest(test); + return test; + }; + + /** + * Exclusive test-case. + */ + + context.test.only = function(title, fn) { + return common.test.only(mocha, context.test(title, fn)); + }; + + context.test.skip = common.test.skip; + context.test.retries = common.test.retries; + }); +}; diff --git a/node_modules/mocha/lib/mocha.js b/node_modules/mocha/lib/mocha.js new file mode 100644 index 0000000..673dbec --- /dev/null +++ b/node_modules/mocha/lib/mocha.js @@ -0,0 +1,613 @@ +'use strict'; + +/*! + * mocha + * Copyright(c) 2011 TJ Holowaychuk + * MIT Licensed + */ + +var escapeRe = require('escape-string-regexp'); +var path = require('path'); +var reporters = require('./reporters'); +var utils = require('./utils'); + +exports = module.exports = Mocha; + +/** + * To require local UIs and reporters when running in node. + */ + +if (!process.browser) { + var cwd = process.cwd(); + module.paths.push(cwd, path.join(cwd, 'node_modules')); +} + +/** + * Expose internals. + */ + +/** + * @public + * @class utils + * @memberof Mocha + */ +exports.utils = utils; +exports.interfaces = require('./interfaces'); +/** + * + * @memberof Mocha + * @public + */ +exports.reporters = reporters; +exports.Runnable = require('./runnable'); +exports.Context = require('./context'); +/** + * + * @memberof Mocha + */ +exports.Runner = require('./runner'); +exports.Suite = require('./suite'); +exports.Hook = require('./hook'); +exports.Test = require('./test'); + +/** + * Return image `name` path. + * + * @private + * @param {string} name + * @return {string} + */ +function image(name) { + return path.join(__dirname, '..', 'assets', 'growl', name + '.png'); +} + +/** + * Set up mocha with `options`. + * + * Options: + * + * - `ui` name "bdd", "tdd", "exports" etc + * - `reporter` reporter instance, defaults to `mocha.reporters.spec` + * - `globals` array of accepted globals + * - `timeout` timeout in milliseconds + * - `retries` number of times to retry failed tests + * - `bail` bail on the first test failure + * - `slow` milliseconds to wait before considering a test slow + * - `ignoreLeaks` ignore global leaks + * - `fullTrace` display the full stack-trace on failing + * - `grep` string or regexp to filter tests with + * + * @class Mocha + * @param {Object} options + */ +function Mocha(options) { + options = options || {}; + this.files = []; + this.options = options; + if (options.grep) { + this.grep(new RegExp(options.grep)); + } + if (options.fgrep) { + this.fgrep(options.fgrep); + } + this.suite = new exports.Suite('', new exports.Context()); + this.ui(options.ui); + this.bail(options.bail); + this.reporter(options.reporter, options.reporterOptions); + if (typeof options.timeout !== 'undefined' && options.timeout !== null) { + this.timeout(options.timeout); + } + if (typeof options.retries !== 'undefined' && options.retries !== null) { + this.retries(options.retries); + } + this.useColors(options.useColors); + if (options.enableTimeouts !== null) { + this.enableTimeouts(options.enableTimeouts); + } + if (options.slow) { + this.slow(options.slow); + } +} + +/** + * Enable or disable bailing on the first failure. + * + * @public + * @api public + * @param {boolean} [bail] + */ +Mocha.prototype.bail = function(bail) { + if (!arguments.length) { + bail = true; + } + this.suite.bail(bail); + return this; +}; + +/** + * Add test `file`. + * + * @public + * @api public + * @param {string} file + */ +Mocha.prototype.addFile = function(file) { + this.files.push(file); + return this; +}; + +/** + * Set reporter to `reporter`, defaults to "spec". + * + * @public + * @param {String|Function} reporter name or constructor + * @param {Object} reporterOptions optional options + * @api public + * @param {string|Function} reporter name or constructor + * @param {Object} reporterOptions optional options + */ +Mocha.prototype.reporter = function(reporter, reporterOptions) { + if (typeof reporter === 'function') { + this._reporter = reporter; + } else { + reporter = reporter || 'spec'; + var _reporter; + // Try to load a built-in reporter. + if (reporters[reporter]) { + _reporter = reporters[reporter]; + } + // Try to load reporters from process.cwd() and node_modules + if (!_reporter) { + try { + _reporter = require(reporter); + } catch (err) { + if (err.message.indexOf('Cannot find module') !== -1) { + // Try to load reporters from a path (absolute or relative) + try { + _reporter = require(path.resolve(process.cwd(), reporter)); + } catch (_err) { + err.message.indexOf('Cannot find module') !== -1 + ? console.warn('"' + reporter + '" reporter not found') + : console.warn( + '"' + + reporter + + '" reporter blew up with error:\n' + + err.stack + ); + } + } else { + console.warn( + '"' + reporter + '" reporter blew up with error:\n' + err.stack + ); + } + } + } + if (!_reporter && reporter === 'teamcity') { + console.warn( + 'The Teamcity reporter was moved to a package named ' + + 'mocha-teamcity-reporter ' + + '(https://npmjs.org/package/mocha-teamcity-reporter).' + ); + } + if (!_reporter) { + throw new Error('invalid reporter "' + reporter + '"'); + } + this._reporter = _reporter; + } + this.options.reporterOptions = reporterOptions; + return this; +}; + +/** + * Set test UI `name`, defaults to "bdd". + * @public + * @api public + * @param {string} bdd + */ +Mocha.prototype.ui = function(name) { + name = name || 'bdd'; + this._ui = exports.interfaces[name]; + if (!this._ui) { + try { + this._ui = require(name); + } catch (err) { + throw new Error('invalid interface "' + name + '"'); + } + } + this._ui = this._ui(this.suite); + + this.suite.on('pre-require', function(context) { + exports.afterEach = context.afterEach || context.teardown; + exports.after = context.after || context.suiteTeardown; + exports.beforeEach = context.beforeEach || context.setup; + exports.before = context.before || context.suiteSetup; + exports.describe = context.describe || context.suite; + exports.it = context.it || context.test; + exports.xit = context.xit || context.test.skip; + exports.setup = context.setup || context.beforeEach; + exports.suiteSetup = context.suiteSetup || context.before; + exports.suiteTeardown = context.suiteTeardown || context.after; + exports.suite = context.suite || context.describe; + exports.teardown = context.teardown || context.afterEach; + exports.test = context.test || context.it; + exports.run = context.run; + }); + + return this; +}; + +/** + * Load registered files. + * + * @api private + */ +Mocha.prototype.loadFiles = function(fn) { + var self = this; + var suite = this.suite; + this.files.forEach(function(file) { + file = path.resolve(file); + suite.emit('pre-require', global, file, self); + suite.emit('require', require(file), file, self); + suite.emit('post-require', global, file, self); + }); + fn && fn(); +}; + +/** + * Enable growl support. + * + * @api private + */ +Mocha.prototype._growl = function(runner, reporter) { + var notify = require('growl'); + + runner.on('end', function() { + var stats = reporter.stats; + if (stats.failures) { + var msg = stats.failures + ' of ' + runner.total + ' tests failed'; + notify(msg, {name: 'mocha', title: 'Failed', image: image('error')}); + } else { + notify(stats.passes + ' tests passed in ' + stats.duration + 'ms', { + name: 'mocha', + title: 'Passed', + image: image('ok') + }); + } + }); +}; + +/** + * Escape string and add it to grep as a regexp. + * + * @public + * @api public + * @param str + * @returns {Mocha} + */ +Mocha.prototype.fgrep = function(str) { + return this.grep(new RegExp(escapeRe(str))); +}; + +/** + * Add regexp to grep, if `re` is a string it is escaped. + * + * @public + * @param {RegExp|String} re + * @return {Mocha} + * @api public + * @param {RegExp|string} re + * @return {Mocha} + */ +Mocha.prototype.grep = function(re) { + if (utils.isString(re)) { + // extract args if it's regex-like, i.e: [string, pattern, flag] + var arg = re.match(/^\/(.*)\/(g|i|)$|.*/); + this.options.grep = new RegExp(arg[1] || arg[0], arg[2]); + } else { + this.options.grep = re; + } + return this; +}; +/** + * Invert `.grep()` matches. + * + * @public + * @return {Mocha} + * @api public + */ +Mocha.prototype.invert = function() { + this.options.invert = true; + return this; +}; + +/** + * Ignore global leaks. + * + * @public + * @param {Boolean} ignore + * @return {Mocha} + * @api public + * @param {boolean} ignore + * @return {Mocha} + */ +Mocha.prototype.ignoreLeaks = function(ignore) { + this.options.ignoreLeaks = Boolean(ignore); + return this; +}; + +/** + * Enable global leak checking. + * + * @return {Mocha} + * @api public + * @public + */ +Mocha.prototype.checkLeaks = function() { + this.options.ignoreLeaks = false; + return this; +}; + +/** + * Display long stack-trace on failing + * + * @return {Mocha} + * @api public + * @public + */ +Mocha.prototype.fullTrace = function() { + this.options.fullStackTrace = true; + return this; +}; + +/** + * Enable growl support. + * + * @return {Mocha} + * @api public + * @public + */ +Mocha.prototype.growl = function() { + this.options.growl = true; + return this; +}; + +/** + * Ignore `globals` array or string. + * + * @param {Array|String} globals + * @return {Mocha} + * @api public + * @public + * @param {Array|string} globals + * @return {Mocha} + */ +Mocha.prototype.globals = function(globals) { + this.options.globals = (this.options.globals || []).concat(globals); + return this; +}; + +/** + * Emit color output. + * + * @param {Boolean} colors + * @return {Mocha} + * @api public + * @public + * @param {boolean} colors + * @return {Mocha} + */ +Mocha.prototype.useColors = function(colors) { + if (colors !== undefined) { + this.options.useColors = colors; + } + return this; +}; + +/** + * Use inline diffs rather than +/-. + * + * @param {Boolean} inlineDiffs + * @return {Mocha} + * @api public + * @public + * @param {boolean} inlineDiffs + * @return {Mocha} + */ +Mocha.prototype.useInlineDiffs = function(inlineDiffs) { + this.options.useInlineDiffs = inlineDiffs !== undefined && inlineDiffs; + return this; +}; + +/** + * Do not show diffs at all. + * + * @param {Boolean} hideDiff + * @return {Mocha} + * @api public + * @public + * @param {boolean} hideDiff + * @return {Mocha} + */ +Mocha.prototype.hideDiff = function(hideDiff) { + this.options.hideDiff = hideDiff !== undefined && hideDiff; + return this; +}; + +/** + * Set the timeout in milliseconds. + * + * @param {Number} timeout + * @return {Mocha} + * @api public + * @public + * @param {number} timeout + * @return {Mocha} + */ +Mocha.prototype.timeout = function(timeout) { + this.suite.timeout(timeout); + return this; +}; + +/** + * Set the number of times to retry failed tests. + * + * @param {Number} retry times + * @return {Mocha} + * @api public + * @public + */ +Mocha.prototype.retries = function(n) { + this.suite.retries(n); + return this; +}; + +/** + * Set slowness threshold in milliseconds. + * + * @param {Number} slow + * @return {Mocha} + * @api public + * @public + * @param {number} slow + * @return {Mocha} + */ +Mocha.prototype.slow = function(slow) { + this.suite.slow(slow); + return this; +}; + +/** + * Enable timeouts. + * + * @param {Boolean} enabled + * @return {Mocha} + * @api public + * @public + * @param {boolean} enabled + * @return {Mocha} + */ +Mocha.prototype.enableTimeouts = function(enabled) { + this.suite.enableTimeouts( + arguments.length && enabled !== undefined ? enabled : true + ); + return this; +}; + +/** + * Makes all tests async (accepting a callback) + * + * @return {Mocha} + * @api public + * @public + */ +Mocha.prototype.asyncOnly = function() { + this.options.asyncOnly = true; + return this; +}; + +/** + * Disable syntax highlighting (in browser). + * + * @api public + * @public + */ +Mocha.prototype.noHighlighting = function() { + this.options.noHighlighting = true; + return this; +}; + +/** + * Enable uncaught errors to propagate (in browser). + * + * @return {Mocha} + * @api public + * @public + */ +Mocha.prototype.allowUncaught = function() { + this.options.allowUncaught = true; + return this; +}; + +/** + * Delay root suite execution. + * @returns {Mocha} + */ +Mocha.prototype.delay = function delay() { + this.options.delay = true; + return this; +}; + +/** + * Tests marked only fail the suite + * @returns {Mocha} + */ +Mocha.prototype.forbidOnly = function() { + this.options.forbidOnly = true; + return this; +}; + +/** + * Pending tests and tests marked skip fail the suite + * @returns {Mocha} + */ +Mocha.prototype.forbidPending = function() { + this.options.forbidPending = true; + return this; +}; + +/** + * Run tests and invoke `fn()` when complete. + * + * Note that `loadFiles` relies on Node's `require` to execute + * the test interface functions and will be subject to the + * cache - if the files are already in the `require` cache, + * they will effectively be skipped. Therefore, to run tests + * multiple times or to run tests in files that are already + * in the `require` cache, make sure to clear them from the + * cache first in whichever manner best suits your needs. + * + * @api public + * @public + * @param {Function} fn + * @return {Runner} + */ +Mocha.prototype.run = function(fn) { + if (this.files.length) { + this.loadFiles(); + } + var suite = this.suite; + var options = this.options; + options.files = this.files; + var runner = new exports.Runner(suite, options.delay); + var reporter = new this._reporter(runner, options); + runner.ignoreLeaks = options.ignoreLeaks !== false; + runner.fullStackTrace = options.fullStackTrace; + runner.asyncOnly = options.asyncOnly; + runner.allowUncaught = options.allowUncaught; + runner.forbidOnly = options.forbidOnly; + runner.forbidPending = options.forbidPending; + if (options.grep) { + runner.grep(options.grep, options.invert); + } + if (options.globals) { + runner.globals(options.globals); + } + if (options.growl) { + this._growl(runner, reporter); + } + if (options.useColors !== undefined) { + exports.reporters.Base.useColors = options.useColors; + } + exports.reporters.Base.inlineDiffs = options.useInlineDiffs; + exports.reporters.Base.hideDiff = options.hideDiff; + + function done(failures) { + if (reporter.done) { + reporter.done(failures, fn); + } else { + fn && fn(failures); + } + } + + return runner.run(done); +}; diff --git a/node_modules/mocha/lib/ms.js b/node_modules/mocha/lib/ms.js new file mode 100644 index 0000000..91c55af --- /dev/null +++ b/node_modules/mocha/lib/ms.js @@ -0,0 +1,96 @@ +'use strict'; +/** + * @module milliseconds + */ +/** + * Helpers. + */ + +var s = 1000; +var m = s * 60; +var h = m * 60; +var d = h * 24; +var y = d * 365.25; + +/** + * Parse or format the given `val`. + * + * @memberof Mocha + * @public + * @api public + * @param {string|number} val + * @return {string|number} + */ +module.exports = function(val) { + if (typeof val === 'string') { + return parse(val); + } + return format(val); +}; + +/** + * Parse the given `str` and return milliseconds. + * + * @api private + * @param {string} str + * @return {number} + */ +function parse(str) { + var match = /^((?:\d+)?\.?\d+) *(ms|seconds?|s|minutes?|m|hours?|h|days?|d|years?|y)?$/i.exec( + str + ); + if (!match) { + return; + } + var n = parseFloat(match[1]); + var type = (match[2] || 'ms').toLowerCase(); + switch (type) { + case 'years': + case 'year': + case 'y': + return n * y; + case 'days': + case 'day': + case 'd': + return n * d; + case 'hours': + case 'hour': + case 'h': + return n * h; + case 'minutes': + case 'minute': + case 'm': + return n * m; + case 'seconds': + case 'second': + case 's': + return n * s; + case 'ms': + return n; + default: + // No default case + } +} + +/** + * Format for `ms`. + * + * @api private + * @param {number} ms + * @return {string} + */ +function format(ms) { + if (ms >= d) { + return Math.round(ms / d) + 'd'; + } + if (ms >= h) { + return Math.round(ms / h) + 'h'; + } + if (ms >= m) { + return Math.round(ms / m) + 'm'; + } + if (ms >= s) { + return Math.round(ms / s) + 's'; + } + return ms + 'ms'; +} diff --git a/node_modules/mocha/lib/pending.js b/node_modules/mocha/lib/pending.js new file mode 100644 index 0000000..bb9a505 --- /dev/null +++ b/node_modules/mocha/lib/pending.js @@ -0,0 +1,12 @@ +'use strict'; + +module.exports = Pending; + +/** + * Initialize a new `Pending` error with the given message. + * + * @param {string} message + */ +function Pending(message) { + this.message = message; +} diff --git a/node_modules/mocha/lib/reporters/base.js b/node_modules/mocha/lib/reporters/base.js new file mode 100644 index 0000000..fd72c17 --- /dev/null +++ b/node_modules/mocha/lib/reporters/base.js @@ -0,0 +1,540 @@ +'use strict'; +/** + * @module Base + */ +/** + * Module dependencies. + */ + +var tty = require('tty'); +var diff = require('diff'); +var ms = require('../ms'); +var utils = require('../utils'); +var supportsColor = process.browser ? null : require('supports-color'); + +/** + * Expose `Base`. + */ + +exports = module.exports = Base; + +/** + * Save timer references to avoid Sinon interfering. + * See: https://github.com/mochajs/mocha/issues/237 + */ + +/* eslint-disable no-unused-vars, no-native-reassign */ +var Date = global.Date; +var setTimeout = global.setTimeout; +var setInterval = global.setInterval; +var clearTimeout = global.clearTimeout; +var clearInterval = global.clearInterval; +/* eslint-enable no-unused-vars, no-native-reassign */ + +/** + * Check if both stdio streams are associated with a tty. + */ + +var isatty = tty.isatty(1) && tty.isatty(2); + +/** + * Enable coloring by default, except in the browser interface. + */ + +exports.useColors = + !process.browser && + (supportsColor.stdout || process.env.MOCHA_COLORS !== undefined); + +/** + * Inline diffs instead of +/- + */ + +exports.inlineDiffs = false; + +/** + * Default color map. + */ + +exports.colors = { + pass: 90, + fail: 31, + 'bright pass': 92, + 'bright fail': 91, + 'bright yellow': 93, + pending: 36, + suite: 0, + 'error title': 0, + 'error message': 31, + 'error stack': 90, + checkmark: 32, + fast: 90, + medium: 33, + slow: 31, + green: 32, + light: 90, + 'diff gutter': 90, + 'diff added': 32, + 'diff removed': 31 +}; + +/** + * Default symbol map. + */ + +exports.symbols = { + ok: '✓', + err: '✖', + dot: '․', + comma: ',', + bang: '!' +}; + +// With node.js on Windows: use symbols available in terminal default fonts +if (process.platform === 'win32') { + exports.symbols.ok = '\u221A'; + exports.symbols.err = '\u00D7'; + exports.symbols.dot = '.'; +} + +/** + * Color `str` with the given `type`, + * allowing colors to be disabled, + * as well as user-defined color + * schemes. + * + * @param {string} type + * @param {string} str + * @return {string} + * @api private + */ +var color = (exports.color = function(type, str) { + if (!exports.useColors) { + return String(str); + } + return '\u001b[' + exports.colors[type] + 'm' + str + '\u001b[0m'; +}); + +/** + * Expose term window size, with some defaults for when stderr is not a tty. + */ + +exports.window = { + width: 75 +}; + +if (isatty) { + exports.window.width = process.stdout.getWindowSize + ? process.stdout.getWindowSize(1)[0] + : tty.getWindowSize()[1]; +} + +/** + * Expose some basic cursor interactions that are common among reporters. + */ + +exports.cursor = { + hide: function() { + isatty && process.stdout.write('\u001b[?25l'); + }, + + show: function() { + isatty && process.stdout.write('\u001b[?25h'); + }, + + deleteLine: function() { + isatty && process.stdout.write('\u001b[2K'); + }, + + beginningOfLine: function() { + isatty && process.stdout.write('\u001b[0G'); + }, + + CR: function() { + if (isatty) { + exports.cursor.deleteLine(); + exports.cursor.beginningOfLine(); + } else { + process.stdout.write('\r'); + } + } +}; + +function showDiff(err) { + return ( + err && + err.showDiff !== false && + sameType(err.actual, err.expected) && + err.expected !== undefined + ); +} + +function stringifyDiffObjs(err) { + if (!utils.isString(err.actual) || !utils.isString(err.expected)) { + err.actual = utils.stringify(err.actual); + err.expected = utils.stringify(err.expected); + } +} + +/** + * Returns a diff between 2 strings with coloured ANSI output. + * + * The diff will be either inline or unified dependant on the value + * of `Base.inlineDiff`. + * + * @param {string} actual + * @param {string} expected + * @return {string} Diff + */ +var generateDiff = (exports.generateDiff = function(actual, expected) { + return exports.inlineDiffs + ? inlineDiff(actual, expected) + : unifiedDiff(actual, expected); +}); + +/** + * Output the given `failures` as a list. + * + * @public + * @memberof Mocha.reporters.Base + * @variation 1 + * @param {Array} failures + * @api public + */ + +exports.list = function(failures) { + console.log(); + failures.forEach(function(test, i) { + // format + var fmt = + color('error title', ' %s) %s:\n') + + color('error message', ' %s') + + color('error stack', '\n%s\n'); + + // msg + var msg; + var err = test.err; + var message; + if (err.message && typeof err.message.toString === 'function') { + message = err.message + ''; + } else if (typeof err.inspect === 'function') { + message = err.inspect() + ''; + } else { + message = ''; + } + var stack = err.stack || message; + var index = message ? stack.indexOf(message) : -1; + + if (index === -1) { + msg = message; + } else { + index += message.length; + msg = stack.slice(0, index); + // remove msg from stack + stack = stack.slice(index + 1); + } + + // uncaught + if (err.uncaught) { + msg = 'Uncaught ' + msg; + } + // explicitly show diff + if (!exports.hideDiff && showDiff(err)) { + stringifyDiffObjs(err); + fmt = + color('error title', ' %s) %s:\n%s') + color('error stack', '\n%s\n'); + var match = message.match(/^([^:]+): expected/); + msg = '\n ' + color('error message', match ? match[1] : msg); + + msg += generateDiff(err.actual, err.expected); + } + + // indent stack trace + stack = stack.replace(/^/gm, ' '); + + // indented test title + var testTitle = ''; + test.titlePath().forEach(function(str, index) { + if (index !== 0) { + testTitle += '\n '; + } + for (var i = 0; i < index; i++) { + testTitle += ' '; + } + testTitle += str; + }); + + console.log(fmt, i + 1, testTitle, msg, stack); + }); +}; + +/** + * Initialize a new `Base` reporter. + * + * All other reporters generally + * inherit from this reporter, providing + * stats such as test duration, number + * of tests passed / failed etc. + * + * @memberof Mocha.reporters + * @public + * @class + * @param {Runner} runner + * @api public + */ + +function Base(runner) { + var stats = (this.stats = { + suites: 0, + tests: 0, + passes: 0, + pending: 0, + failures: 0 + }); + var failures = (this.failures = []); + + if (!runner) { + return; + } + this.runner = runner; + + runner.stats = stats; + + runner.on('start', function() { + stats.start = new Date(); + }); + + runner.on('suite', function(suite) { + stats.suites = stats.suites || 0; + suite.root || stats.suites++; + }); + + runner.on('test end', function() { + stats.tests = stats.tests || 0; + stats.tests++; + }); + + runner.on('pass', function(test) { + stats.passes = stats.passes || 0; + + if (test.duration > test.slow()) { + test.speed = 'slow'; + } else if (test.duration > test.slow() / 2) { + test.speed = 'medium'; + } else { + test.speed = 'fast'; + } + + stats.passes++; + }); + + runner.on('fail', function(test, err) { + stats.failures = stats.failures || 0; + stats.failures++; + if (showDiff(err)) { + stringifyDiffObjs(err); + } + test.err = err; + failures.push(test); + }); + + runner.once('end', function() { + stats.end = new Date(); + stats.duration = stats.end - stats.start; + }); + + runner.on('pending', function() { + stats.pending++; + }); +} + +/** + * Output common epilogue used by many of + * the bundled reporters. + * + * @memberof Mocha.reporters.Base + * @public + * @api public + */ +Base.prototype.epilogue = function() { + var stats = this.stats; + var fmt; + + console.log(); + + // passes + fmt = + color('bright pass', ' ') + + color('green', ' %d passing') + + color('light', ' (%s)'); + + console.log(fmt, stats.passes || 0, ms(stats.duration)); + + // pending + if (stats.pending) { + fmt = color('pending', ' ') + color('pending', ' %d pending'); + + console.log(fmt, stats.pending); + } + + // failures + if (stats.failures) { + fmt = color('fail', ' %d failing'); + + console.log(fmt, stats.failures); + + Base.list(this.failures); + console.log(); + } + + console.log(); +}; + +/** + * Pad the given `str` to `len`. + * + * @api private + * @param {string} str + * @param {string} len + * @return {string} + */ +function pad(str, len) { + str = String(str); + return Array(len - str.length + 1).join(' ') + str; +} + +/** + * Returns an inline diff between 2 strings with coloured ANSI output. + * + * @api private + * @param {String} actual + * @param {String} expected + * @return {string} Diff + */ +function inlineDiff(actual, expected) { + var msg = errorDiff(actual, expected); + + // linenos + var lines = msg.split('\n'); + if (lines.length > 4) { + var width = String(lines.length).length; + msg = lines + .map(function(str, i) { + return pad(++i, width) + ' |' + ' ' + str; + }) + .join('\n'); + } + + // legend + msg = + '\n' + + color('diff removed', 'actual') + + ' ' + + color('diff added', 'expected') + + '\n\n' + + msg + + '\n'; + + // indent + msg = msg.replace(/^/gm, ' '); + return msg; +} + +/** + * Returns a unified diff between two strings with coloured ANSI output. + * + * @api private + * @param {String} actual + * @param {String} expected + * @return {string} The diff. + */ +function unifiedDiff(actual, expected) { + var indent = ' '; + function cleanUp(line) { + if (line[0] === '+') { + return indent + colorLines('diff added', line); + } + if (line[0] === '-') { + return indent + colorLines('diff removed', line); + } + if (line.match(/@@/)) { + return '--'; + } + if (line.match(/\\ No newline/)) { + return null; + } + return indent + line; + } + function notBlank(line) { + return typeof line !== 'undefined' && line !== null; + } + var msg = diff.createPatch('string', actual, expected); + var lines = msg.split('\n').splice(5); + return ( + '\n ' + + colorLines('diff added', '+ expected') + + ' ' + + colorLines('diff removed', '- actual') + + '\n\n' + + lines + .map(cleanUp) + .filter(notBlank) + .join('\n') + ); +} + +/** + * Return a character diff for `err`. + * + * @api private + * @param {String} actual + * @param {String} expected + * @return {string} the diff + */ +function errorDiff(actual, expected) { + return diff + .diffWordsWithSpace(actual, expected) + .map(function(str) { + if (str.added) { + return colorLines('diff added', str.value); + } + if (str.removed) { + return colorLines('diff removed', str.value); + } + return str.value; + }) + .join(''); +} + +/** + * Color lines for `str`, using the color `name`. + * + * @api private + * @param {string} name + * @param {string} str + * @return {string} + */ +function colorLines(name, str) { + return str + .split('\n') + .map(function(str) { + return color(name, str); + }) + .join('\n'); +} + +/** + * Object#toString reference. + */ +var objToString = Object.prototype.toString; + +/** + * Check that a / b have the same type. + * + * @api private + * @param {Object} a + * @param {Object} b + * @return {boolean} + */ +function sameType(a, b) { + return objToString.call(a) === objToString.call(b); +} diff --git a/node_modules/mocha/lib/reporters/base.js.orig b/node_modules/mocha/lib/reporters/base.js.orig new file mode 100644 index 0000000..4b7411f --- /dev/null +++ b/node_modules/mocha/lib/reporters/base.js.orig @@ -0,0 +1,498 @@ +'use strict'; + +/** + * Module dependencies. + */ + +var tty = require('tty'); +var diff = require('diff'); +var ms = require('../ms'); +var utils = require('../utils'); +var supportsColor = process.browser ? null : require('supports-color'); + +/** + * Expose `Base`. + */ + +exports = module.exports = Base; + +/** + * Save timer references to avoid Sinon interfering. + * See: https://github.com/mochajs/mocha/issues/237 + */ + +/* eslint-disable no-unused-vars, no-native-reassign */ +var Date = global.Date; +var setTimeout = global.setTimeout; +var setInterval = global.setInterval; +var clearTimeout = global.clearTimeout; +var clearInterval = global.clearInterval; +/* eslint-enable no-unused-vars, no-native-reassign */ + +/** + * Check if both stdio streams are associated with a tty. + */ + +var isatty = tty.isatty(1) && tty.isatty(2); + +/** + * Enable coloring by default, except in the browser interface. + */ + +exports.useColors = !process.browser && (supportsColor || (process.env.MOCHA_COLORS !== undefined)); + +/** + * Inline diffs instead of +/- + */ + +exports.inlineDiffs = false; + +/** + * Default color map. + */ + +exports.colors = { + pass: 90, + fail: 31, + 'bright pass': 92, + 'bright fail': 91, + 'bright yellow': 93, + pending: 36, + suite: 0, + 'error title': 0, + 'error message': 31, + 'error stack': 90, + checkmark: 32, + fast: 90, + medium: 33, + slow: 31, + green: 32, + light: 90, + 'diff gutter': 90, + 'diff added': 32, + 'diff removed': 31 +}; + +/** + * Default symbol map. + */ + +exports.symbols = { + ok: '✓', + err: '✖', + dot: '․', + comma: ',', + bang: '!' +}; + +// With node.js on Windows: use symbols available in terminal default fonts +if (process.platform === 'win32') { + exports.symbols.ok = '\u221A'; + exports.symbols.err = '\u00D7'; + exports.symbols.dot = '.'; +} + +/** + * Color `str` with the given `type`, + * allowing colors to be disabled, + * as well as user-defined color + * schemes. + * + * @param {string} type + * @param {string} str + * @return {string} + * @api private + */ +var color = exports.color = function (type, str) { + if (!exports.useColors) { + return String(str); + } + return '\u001b[' + exports.colors[type] + 'm' + str + '\u001b[0m'; +}; + +/** + * Expose term window size, with some defaults for when stderr is not a tty. + */ + +exports.window = { + width: 75 +}; + +if (isatty) { + exports.window.width = process.stdout.getWindowSize + ? process.stdout.getWindowSize(1)[0] + : tty.getWindowSize()[1]; +} + +/** + * Expose some basic cursor interactions that are common among reporters. + */ + +exports.cursor = { + hide: function () { + isatty && process.stdout.write('\u001b[?25l'); + }, + + show: function () { + isatty && process.stdout.write('\u001b[?25h'); + }, + + deleteLine: function () { + isatty && process.stdout.write('\u001b[2K'); + }, + + beginningOfLine: function () { + isatty && process.stdout.write('\u001b[0G'); + }, + + CR: function () { + if (isatty) { + exports.cursor.deleteLine(); + exports.cursor.beginningOfLine(); + } else { + process.stdout.write('\r'); + } + } +}; + +function showDiff (err) { + return err && err.showDiff !== false && sameType(err.actual, err.expected) && err.expected !== undefined; +} + +function stringifyDiffObjs (err) { + if (!utils.isString(err.actual) || !utils.isString(err.expected)) { + err.actual = utils.stringify(err.actual); + err.expected = utils.stringify(err.expected); + } +} + +/** + * Output the given `failures` as a list. + * + * @param {Array} failures + * @api public + */ + +exports.list = function (failures) { + console.log(); + failures.forEach(function (test, i) { + // format + var fmt = color('error title', ' %s) %s:\n') + + color('error message', ' %s') + + color('error stack', '\n%s\n'); + + // msg + var msg; + var err = test.err; + var message; + if (err.message && typeof err.message.toString === 'function') { + message = err.message + ''; + } else if (typeof err.inspect === 'function') { + message = err.inspect() + ''; + } else { + message = ''; + } + var stack = err.stack || message; + var index = message ? stack.indexOf(message) : -1; + + if (index === -1) { + msg = message; + } else { + index += message.length; + msg = stack.slice(0, index); + // remove msg from stack + stack = stack.slice(index + 1); + } + + // uncaught + if (err.uncaught) { + msg = 'Uncaught ' + msg; + } + + // explicitly show diff +<<<<<<< HEAD + if (showDiff(err)) { + stringifyDiffObjs(err); +======= + if (exports.hideDiff !== true && err.showDiff !== false && sameType(actual, expected) && expected !== undefined) { + escape = false; + if (!(utils.isString(actual) && utils.isString(expected))) { + err.actual = actual = utils.stringify(actual); + err.expected = expected = utils.stringify(expected); + } + +>>>>>>> Add --no-diff option (fixes mochajs/mocha#2514) + fmt = color('error title', ' %s) %s:\n%s') + color('error stack', '\n%s\n'); + var match = message.match(/^([^:]+): expected/); + msg = '\n ' + color('error message', match ? match[1] : msg); + + if (exports.inlineDiffs) { + msg += inlineDiff(err); + } else { + msg += unifiedDiff(err); + } + } + + // indent stack trace + stack = stack.replace(/^/gm, ' '); + + // indented test title + var testTitle = ''; + test.titlePath().forEach(function (str, index) { + if (index !== 0) { + testTitle += '\n '; + } + for (var i = 0; i < index; i++) { + testTitle += ' '; + } + testTitle += str; + }); + + console.log(fmt, (i + 1), testTitle, msg, stack); + }); +}; + +/** + * Initialize a new `Base` reporter. + * + * All other reporters generally + * inherit from this reporter, providing + * stats such as test duration, number + * of tests passed / failed etc. + * + * @param {Runner} runner + * @api public + */ + +function Base (runner) { + var stats = this.stats = { suites: 0, tests: 0, passes: 0, pending: 0, failures: 0 }; + var failures = this.failures = []; + + if (!runner) { + return; + } + this.runner = runner; + + runner.stats = stats; + + runner.on('start', function () { + stats.start = new Date(); + }); + + runner.on('suite', function (suite) { + stats.suites = stats.suites || 0; + suite.root || stats.suites++; + }); + + runner.on('test end', function () { + stats.tests = stats.tests || 0; + stats.tests++; + }); + + runner.on('pass', function (test) { + stats.passes = stats.passes || 0; + + if (test.duration > test.slow()) { + test.speed = 'slow'; + } else if (test.duration > test.slow() / 2) { + test.speed = 'medium'; + } else { + test.speed = 'fast'; + } + + stats.passes++; + }); + + runner.on('fail', function (test, err) { + stats.failures = stats.failures || 0; + stats.failures++; + if (showDiff(err)) { + stringifyDiffObjs(err); + } + test.err = err; + failures.push(test); + }); + + runner.on('end', function () { + stats.end = new Date(); + stats.duration = new Date() - stats.start; + }); + + runner.on('pending', function () { + stats.pending++; + }); +} + +/** + * Output common epilogue used by many of + * the bundled reporters. + * + * @api public + */ +Base.prototype.epilogue = function () { + var stats = this.stats; + var fmt; + + console.log(); + + // passes + fmt = color('bright pass', ' ') + + color('green', ' %d passing') + + color('light', ' (%s)'); + + console.log(fmt, + stats.passes || 0, + ms(stats.duration)); + + // pending + if (stats.pending) { + fmt = color('pending', ' ') + + color('pending', ' %d pending'); + + console.log(fmt, stats.pending); + } + + // failures + if (stats.failures) { + fmt = color('fail', ' %d failing'); + + console.log(fmt, stats.failures); + + Base.list(this.failures); + console.log(); + } + + console.log(); +}; + +/** + * Pad the given `str` to `len`. + * + * @api private + * @param {string} str + * @param {string} len + * @return {string} + */ +function pad (str, len) { + str = String(str); + return Array(len - str.length + 1).join(' ') + str; +} + +/** + * Returns an inline diff between 2 strings with coloured ANSI output + * + * @api private + * @param {Error} err with actual/expected + * @return {string} Diff + */ +function inlineDiff (err) { + var msg = errorDiff(err); + + // linenos + var lines = msg.split('\n'); + if (lines.length > 4) { + var width = String(lines.length).length; + msg = lines.map(function (str, i) { + return pad(++i, width) + ' |' + ' ' + str; + }).join('\n'); + } + + // legend + msg = '\n' + + color('diff removed', 'actual') + + ' ' + + color('diff added', 'expected') + + '\n\n' + + msg + + '\n'; + + // indent + msg = msg.replace(/^/gm, ' '); + return msg; +} + +/** + * Returns a unified diff between two strings. + * + * @api private + * @param {Error} err with actual/expected + * @return {string} The diff. + */ +function unifiedDiff (err) { + var indent = ' '; + function cleanUp (line) { + if (line[0] === '+') { + return indent + colorLines('diff added', line); + } + if (line[0] === '-') { + return indent + colorLines('diff removed', line); + } + if (line.match(/@@/)) { + return '--'; + } + if (line.match(/\\ No newline/)) { + return null; + } + return indent + line; + } + function notBlank (line) { + return typeof line !== 'undefined' && line !== null; + } + var msg = diff.createPatch('string', err.actual, err.expected); + var lines = msg.split('\n').splice(5); + return '\n ' + + colorLines('diff added', '+ expected') + ' ' + + colorLines('diff removed', '- actual') + + '\n\n' + + lines.map(cleanUp).filter(notBlank).join('\n'); +} + +/** + * Return a character diff for `err`. + * + * @api private + * @param {Error} err + * @return {string} + */ +function errorDiff (err) { + return diff.diffWordsWithSpace(err.actual, err.expected).map(function (str) { + if (str.added) { + return colorLines('diff added', str.value); + } + if (str.removed) { + return colorLines('diff removed', str.value); + } + return str.value; + }).join(''); +} + +/** + * Color lines for `str`, using the color `name`. + * + * @api private + * @param {string} name + * @param {string} str + * @return {string} + */ +function colorLines (name, str) { + return str.split('\n').map(function (str) { + return color(name, str); + }).join('\n'); +} + +/** + * Object#toString reference. + */ +var objToString = Object.prototype.toString; + +/** + * Check that a / b have the same type. + * + * @api private + * @param {Object} a + * @param {Object} b + * @return {boolean} + */ +function sameType (a, b) { + return objToString.call(a) === objToString.call(b); +} diff --git a/node_modules/mocha/lib/reporters/doc.js b/node_modules/mocha/lib/reporters/doc.js new file mode 100644 index 0000000..5cb0bda --- /dev/null +++ b/node_modules/mocha/lib/reporters/doc.js @@ -0,0 +1,78 @@ +'use strict'; +/** + * @module Doc + */ +/** + * Module dependencies. + */ + +var Base = require('./base'); +var utils = require('../utils'); + +/** + * Expose `Doc`. + */ + +exports = module.exports = Doc; + +/** + * Initialize a new `Doc` reporter. + * + * @class + * @memberof Mocha.reporters + * @extends {Base} + * @public + * @param {Runner} runner + * @api public + */ +function Doc(runner) { + Base.call(this, runner); + + var indents = 2; + + function indent() { + return Array(indents).join(' '); + } + + runner.on('suite', function(suite) { + if (suite.root) { + return; + } + ++indents; + console.log('%s
', indent()); + ++indents; + console.log('%s

%s

', indent(), utils.escape(suite.title)); + console.log('%s
', indent()); + }); + + runner.on('suite end', function(suite) { + if (suite.root) { + return; + } + console.log('%s
', indent()); + --indents; + console.log('%s
', indent()); + --indents; + }); + + runner.on('pass', function(test) { + console.log('%s
%s
', indent(), utils.escape(test.title)); + var code = utils.escape(utils.clean(test.body)); + console.log('%s
%s
', indent(), code); + }); + + runner.on('fail', function(test, err) { + console.log( + '%s
%s
', + indent(), + utils.escape(test.title) + ); + var code = utils.escape(utils.clean(test.body)); + console.log( + '%s
%s
', + indent(), + code + ); + console.log('%s
%s
', indent(), utils.escape(err)); + }); +} diff --git a/node_modules/mocha/lib/reporters/dot.js b/node_modules/mocha/lib/reporters/dot.js new file mode 100644 index 0000000..22320e3 --- /dev/null +++ b/node_modules/mocha/lib/reporters/dot.js @@ -0,0 +1,74 @@ +'use strict'; +/** + * @module Dot + */ +/** + * Module dependencies. + */ + +var Base = require('./base'); +var inherits = require('../utils').inherits; +var color = Base.color; + +/** + * Expose `Dot`. + */ + +exports = module.exports = Dot; + +/** + * Initialize a new `Dot` matrix test reporter. + * + * @class + * @memberof Mocha.reporters + * @extends Mocha.reporters.Base + * @public + * @api public + * @param {Runner} runner + */ +function Dot(runner) { + Base.call(this, runner); + + var self = this; + var width = (Base.window.width * 0.75) | 0; + var n = -1; + + runner.on('start', function() { + process.stdout.write('\n'); + }); + + runner.on('pending', function() { + if (++n % width === 0) { + process.stdout.write('\n '); + } + process.stdout.write(color('pending', Base.symbols.comma)); + }); + + runner.on('pass', function(test) { + if (++n % width === 0) { + process.stdout.write('\n '); + } + if (test.speed === 'slow') { + process.stdout.write(color('bright yellow', Base.symbols.dot)); + } else { + process.stdout.write(color(test.speed, Base.symbols.dot)); + } + }); + + runner.on('fail', function() { + if (++n % width === 0) { + process.stdout.write('\n '); + } + process.stdout.write(color('fail', Base.symbols.bang)); + }); + + runner.once('end', function() { + console.log(); + self.epilogue(); + }); +} + +/** + * Inherit from `Base.prototype`. + */ +inherits(Dot, Base); diff --git a/node_modules/mocha/lib/reporters/html.js b/node_modules/mocha/lib/reporters/html.js new file mode 100644 index 0000000..85a5b1b --- /dev/null +++ b/node_modules/mocha/lib/reporters/html.js @@ -0,0 +1,388 @@ +'use strict'; + +/* eslint-env browser */ +/** + * @module HTML + */ +/** + * Module dependencies. + */ + +var Base = require('./base'); +var utils = require('../utils'); +var Progress = require('../browser/progress'); +var escapeRe = require('escape-string-regexp'); +var escape = utils.escape; + +/** + * Save timer references to avoid Sinon interfering (see GH-237). + */ + +/* eslint-disable no-unused-vars, no-native-reassign */ +var Date = global.Date; +var setTimeout = global.setTimeout; +var setInterval = global.setInterval; +var clearTimeout = global.clearTimeout; +var clearInterval = global.clearInterval; +/* eslint-enable no-unused-vars, no-native-reassign */ + +/** + * Expose `HTML`. + */ + +exports = module.exports = HTML; + +/** + * Stats template. + */ + +var statsTemplate = + ''; + +var playIcon = '‣'; + +/** + * Initialize a new `HTML` reporter. + * + * @public + * @class + * @memberof Mocha.reporters + * @extends Mocha.reporters.Base + * @api public + * @param {Runner} runner + */ +function HTML(runner) { + Base.call(this, runner); + + var self = this; + var stats = this.stats; + var stat = fragment(statsTemplate); + var items = stat.getElementsByTagName('li'); + var passes = items[1].getElementsByTagName('em')[0]; + var passesLink = items[1].getElementsByTagName('a')[0]; + var failures = items[2].getElementsByTagName('em')[0]; + var failuresLink = items[2].getElementsByTagName('a')[0]; + var duration = items[3].getElementsByTagName('em')[0]; + var canvas = stat.getElementsByTagName('canvas')[0]; + var report = fragment('
    '); + var stack = [report]; + var progress; + var ctx; + var root = document.getElementById('mocha'); + + if (canvas.getContext) { + var ratio = window.devicePixelRatio || 1; + canvas.style.width = canvas.width; + canvas.style.height = canvas.height; + canvas.width *= ratio; + canvas.height *= ratio; + ctx = canvas.getContext('2d'); + ctx.scale(ratio, ratio); + progress = new Progress(); + } + + if (!root) { + return error('#mocha div missing, add it to your document'); + } + + // pass toggle + on(passesLink, 'click', function(evt) { + evt.preventDefault(); + unhide(); + var name = /pass/.test(report.className) ? '' : ' pass'; + report.className = report.className.replace(/fail|pass/g, '') + name; + if (report.className.trim()) { + hideSuitesWithout('test pass'); + } + }); + + // failure toggle + on(failuresLink, 'click', function(evt) { + evt.preventDefault(); + unhide(); + var name = /fail/.test(report.className) ? '' : ' fail'; + report.className = report.className.replace(/fail|pass/g, '') + name; + if (report.className.trim()) { + hideSuitesWithout('test fail'); + } + }); + + root.appendChild(stat); + root.appendChild(report); + + if (progress) { + progress.size(40); + } + + runner.on('suite', function(suite) { + if (suite.root) { + return; + } + + // suite + var url = self.suiteURL(suite); + var el = fragment( + '
  • %s

  • ', + url, + escape(suite.title) + ); + + // container + stack[0].appendChild(el); + stack.unshift(document.createElement('ul')); + el.appendChild(stack[0]); + }); + + runner.on('suite end', function(suite) { + if (suite.root) { + updateStats(); + return; + } + stack.shift(); + }); + + runner.on('pass', function(test) { + var url = self.testURL(test); + var markup = + '
  • %e%ems ' + + '' + + playIcon + + '

  • '; + var el = fragment(markup, test.speed, test.title, test.duration, url); + self.addCodeToggle(el, test.body); + appendToStack(el); + updateStats(); + }); + + runner.on('fail', function(test) { + var el = fragment( + '
  • %e ' + + playIcon + + '

  • ', + test.title, + self.testURL(test) + ); + var stackString; // Note: Includes leading newline + var message = test.err.toString(); + + // <=IE7 stringifies to [Object Error]. Since it can be overloaded, we + // check for the result of the stringifying. + if (message === '[object Error]') { + message = test.err.message; + } + + if (test.err.stack) { + var indexOfMessage = test.err.stack.indexOf(test.err.message); + if (indexOfMessage === -1) { + stackString = test.err.stack; + } else { + stackString = test.err.stack.substr( + test.err.message.length + indexOfMessage + ); + } + } else if (test.err.sourceURL && test.err.line !== undefined) { + // Safari doesn't give you a stack. Let's at least provide a source line. + stackString = '\n(' + test.err.sourceURL + ':' + test.err.line + ')'; + } + + stackString = stackString || ''; + + if (test.err.htmlMessage && stackString) { + el.appendChild( + fragment( + '
    %s\n
    %e
    ', + test.err.htmlMessage, + stackString + ) + ); + } else if (test.err.htmlMessage) { + el.appendChild( + fragment('
    %s
    ', test.err.htmlMessage) + ); + } else { + el.appendChild( + fragment('
    %e%e
    ', message, stackString) + ); + } + + self.addCodeToggle(el, test.body); + appendToStack(el); + updateStats(); + }); + + runner.on('pending', function(test) { + var el = fragment( + '
  • %e

  • ', + test.title + ); + appendToStack(el); + updateStats(); + }); + + function appendToStack(el) { + // Don't call .appendChild if #mocha-report was already .shift()'ed off the stack. + if (stack[0]) { + stack[0].appendChild(el); + } + } + + function updateStats() { + // TODO: add to stats + var percent = (stats.tests / runner.total * 100) | 0; + if (progress) { + progress.update(percent).draw(ctx); + } + + // update stats + var ms = new Date() - stats.start; + text(passes, stats.passes); + text(failures, stats.failures); + text(duration, (ms / 1000).toFixed(2)); + } +} + +/** + * Makes a URL, preserving querystring ("search") parameters. + * + * @param {string} s + * @return {string} A new URL. + */ +function makeUrl(s) { + var search = window.location.search; + + // Remove previous grep query parameter if present + if (search) { + search = search.replace(/[?&]grep=[^&\s]*/g, '').replace(/^&/, '?'); + } + + return ( + window.location.pathname + + (search ? search + '&' : '?') + + 'grep=' + + encodeURIComponent(escapeRe(s)) + ); +} + +/** + * Provide suite URL. + * + * @param {Object} [suite] + */ +HTML.prototype.suiteURL = function(suite) { + return makeUrl(suite.fullTitle()); +}; + +/** + * Provide test URL. + * + * @param {Object} [test] + */ +HTML.prototype.testURL = function(test) { + return makeUrl(test.fullTitle()); +}; + +/** + * Adds code toggle functionality for the provided test's list element. + * + * @param {HTMLLIElement} el + * @param {string} contents + */ +HTML.prototype.addCodeToggle = function(el, contents) { + var h2 = el.getElementsByTagName('h2')[0]; + + on(h2, 'click', function() { + pre.style.display = pre.style.display === 'none' ? 'block' : 'none'; + }); + + var pre = fragment('
    %e
    ', utils.clean(contents)); + el.appendChild(pre); + pre.style.display = 'none'; +}; + +/** + * Display error `msg`. + * + * @param {string} msg + */ +function error(msg) { + document.body.appendChild(fragment('
    %s
    ', msg)); +} + +/** + * Return a DOM fragment from `html`. + * + * @param {string} html + */ +function fragment(html) { + var args = arguments; + var div = document.createElement('div'); + var i = 1; + + div.innerHTML = html.replace(/%([se])/g, function(_, type) { + switch (type) { + case 's': + return String(args[i++]); + case 'e': + return escape(args[i++]); + // no default + } + }); + + return div.firstChild; +} + +/** + * Check for suites that do not have elements + * with `classname`, and hide them. + * + * @param {text} classname + */ +function hideSuitesWithout(classname) { + var suites = document.getElementsByClassName('suite'); + for (var i = 0; i < suites.length; i++) { + var els = suites[i].getElementsByClassName(classname); + if (!els.length) { + suites[i].className += ' hidden'; + } + } +} + +/** + * Unhide .hidden suites. + */ +function unhide() { + var els = document.getElementsByClassName('suite hidden'); + for (var i = 0; i < els.length; ++i) { + els[i].className = els[i].className.replace('suite hidden', 'suite'); + } +} + +/** + * Set an element's text contents. + * + * @param {HTMLElement} el + * @param {string} contents + */ +function text(el, contents) { + if (el.textContent) { + el.textContent = contents; + } else { + el.innerText = contents; + } +} + +/** + * Listen on `event` with callback `fn`. + */ +function on(el, event, fn) { + if (el.addEventListener) { + el.addEventListener(event, fn, false); + } else { + el.attachEvent('on' + event, fn); + } +} diff --git a/node_modules/mocha/lib/reporters/index.js b/node_modules/mocha/lib/reporters/index.js new file mode 100644 index 0000000..d3b5481 --- /dev/null +++ b/node_modules/mocha/lib/reporters/index.js @@ -0,0 +1,19 @@ +'use strict'; + +// Alias exports to a their normalized format Mocha#reporter to prevent a need +// for dynamic (try/catch) requires, which Browserify doesn't handle. +exports.Base = exports.base = require('./base'); +exports.Dot = exports.dot = require('./dot'); +exports.Doc = exports.doc = require('./doc'); +exports.TAP = exports.tap = require('./tap'); +exports.JSON = exports.json = require('./json'); +exports.HTML = exports.html = require('./html'); +exports.List = exports.list = require('./list'); +exports.Min = exports.min = require('./min'); +exports.Spec = exports.spec = require('./spec'); +exports.Nyan = exports.nyan = require('./nyan'); +exports.XUnit = exports.xunit = require('./xunit'); +exports.Markdown = exports.markdown = require('./markdown'); +exports.Progress = exports.progress = require('./progress'); +exports.Landing = exports.landing = require('./landing'); +exports.JSONStream = exports['json-stream'] = require('./json-stream'); diff --git a/node_modules/mocha/lib/reporters/json-stream.js b/node_modules/mocha/lib/reporters/json-stream.js new file mode 100644 index 0000000..0edd0cb --- /dev/null +++ b/node_modules/mocha/lib/reporters/json-stream.js @@ -0,0 +1,69 @@ +'use strict'; +/** + * @module JSONStream + */ +/** + * Module dependencies. + */ + +var Base = require('./base'); + +/** + * Expose `List`. + */ + +exports = module.exports = List; + +/** + * Initialize a new `JSONStream` test reporter. + * + * @public + * @name JSONStream + * @class JSONStream + * @memberof Mocha.reporters + * @extends Mocha.reporters.Base + * @api public + * @param {Runner} runner + */ +function List(runner) { + Base.call(this, runner); + + var self = this; + var total = runner.total; + + runner.on('start', function() { + console.log(JSON.stringify(['start', {total: total}])); + }); + + runner.on('pass', function(test) { + console.log(JSON.stringify(['pass', clean(test)])); + }); + + runner.on('fail', function(test, err) { + test = clean(test); + test.err = err.message; + test.stack = err.stack || null; + console.log(JSON.stringify(['fail', test])); + }); + + runner.once('end', function() { + process.stdout.write(JSON.stringify(['end', self.stats])); + }); +} + +/** + * Return a plain-object representation of `test` + * free of cyclic properties etc. + * + * @api private + * @param {Object} test + * @return {Object} + */ +function clean(test) { + return { + title: test.title, + fullTitle: test.fullTitle(), + duration: test.duration, + currentRetry: test.currentRetry() + }; +} diff --git a/node_modules/mocha/lib/reporters/json.js b/node_modules/mocha/lib/reporters/json.js new file mode 100644 index 0000000..046e4ba --- /dev/null +++ b/node_modules/mocha/lib/reporters/json.js @@ -0,0 +1,127 @@ +'use strict'; +/** + * @module JSON + */ +/** + * Module dependencies. + */ + +var Base = require('./base'); + +/** + * Expose `JSON`. + */ + +exports = module.exports = JSONReporter; + +/** + * Initialize a new `JSON` reporter. + * + * @public + * @class JSON + * @memberof Mocha.reporters + * @extends Mocha.reporters.Base + * @api public + * @param {Runner} runner + */ +function JSONReporter(runner) { + Base.call(this, runner); + + var self = this; + var tests = []; + var pending = []; + var failures = []; + var passes = []; + + runner.on('test end', function(test) { + tests.push(test); + }); + + runner.on('pass', function(test) { + passes.push(test); + }); + + runner.on('fail', function(test) { + failures.push(test); + }); + + runner.on('pending', function(test) { + pending.push(test); + }); + + runner.once('end', function() { + var obj = { + stats: self.stats, + tests: tests.map(clean), + pending: pending.map(clean), + failures: failures.map(clean), + passes: passes.map(clean) + }; + + runner.testResults = obj; + + process.stdout.write(JSON.stringify(obj, null, 2)); + }); +} + +/** + * Return a plain-object representation of `test` + * free of cyclic properties etc. + * + * @api private + * @param {Object} test + * @return {Object} + */ +function clean(test) { + var err = test.err || {}; + if (err instanceof Error) { + err = errorJSON(err); + } + + return { + title: test.title, + fullTitle: test.fullTitle(), + duration: test.duration, + currentRetry: test.currentRetry(), + err: cleanCycles(err) + }; +} + +/** + * Replaces any circular references inside `obj` with '[object Object]' + * + * @api private + * @param {Object} obj + * @return {Object} + */ +function cleanCycles(obj) { + var cache = []; + return JSON.parse( + JSON.stringify(obj, function(key, value) { + if (typeof value === 'object' && value !== null) { + if (cache.indexOf(value) !== -1) { + // Instead of going in a circle, we'll print [object Object] + return '' + value; + } + cache.push(value); + } + + return value; + }) + ); +} + +/** + * Transform an Error object into a JSON object. + * + * @api private + * @param {Error} err + * @return {Object} + */ +function errorJSON(err) { + var res = {}; + Object.getOwnPropertyNames(err).forEach(function(key) { + res[key] = err[key]; + }, err); + return res; +} diff --git a/node_modules/mocha/lib/reporters/json.js.orig b/node_modules/mocha/lib/reporters/json.js.orig new file mode 100644 index 0000000..0745b8c --- /dev/null +++ b/node_modules/mocha/lib/reporters/json.js.orig @@ -0,0 +1,128 @@ +'use strict'; + +/** + * Module dependencies. + */ + +var Base = require('./base'); + +/** + * Expose `JSON`. + */ + +exports = module.exports = JSONReporter; + +/** + * Initialize a new `JSON` reporter. + * + * @api public + * @param {Runner} runner + * @param {options} mocha invocation options. Invoking + * `mocha -R --reporter-options output-file=asdf` yields options like: + * { ... reporterOptions: { "output-file": "asdf" } ... } + */ +function JSONReporter (runner, options) { +<<<<<<< HEAD +======= + options = options || {}; + var reptOptions = options.reporterOptions || {}; +>>>>>>> + json ouput controls: output-file, output-object + Base.call(this, runner); + + var self = this; + var tests = []; + var pending = []; + var failures = []; + var passes = []; + + runner.on('test end', function (test) { + tests.push(test); + }); + + runner.on('pass', function (test) { + passes.push(test); + }); + + runner.on('fail', function (test) { + failures.push(test); + }); + + runner.on('pending', function (test) { + pending.push(test); + }); + + runner.once('end', function () { + var obj = { + stats: self.stats, + tests: tests.map(clean), + pending: pending.map(clean), + failures: failures.map(clean), + passes: passes.map(clean) + }; + + runner.testResults = obj; +<<<<<<< HEAD + if ('output-object' in options.reporterOptions) { + // Pass to reporter with: reporter("json", {"output-object": myObject}) + Object.assign(options.reporterOptions['output-object'], obj); + } else { + var text = JSON.stringify(obj, null, 2); + if ('output-file' in options.reporterOptions) { + // Direct output with `mocha -R --reporter-options output-file=rpt.json` + try { + require('fs').writeFileSync(options.reporterOptions['output-file'], text); + } catch (e) { + console.warn('error writing to ' + options.reporterOptions.output + ':', e); +======= + if ('output-object' in reptOptions) { + // Pass to reporter with: reporter("json", {"output-object": myObject}) + Object.assign(reptOptions['output-object'], obj); + } else { + var text = JSON.stringify(obj, null, 2); + if ('output-file' in reptOptions) { + // Direct output with `mocha -R --reporter-options output-file=rpt.json` + try { + require('fs').writeFileSync(reptOptions['output-file'], text); + } catch (e) { + console.warn('error writing to ' + reptOptions.output + ':', e); +>>>>>>> + json ouput controls: output-file, output-object + } + } else { + process.stdout.write(text); + } + } + }); +} + +/** + * Return a plain-object representation of `test` + * free of cyclic properties etc. + * + * @api private + * @param {Object} test + * @return {Object} + */ +function clean (test) { + return { + title: test.title, + fullTitle: test.fullTitle(), + duration: test.duration, + currentRetry: test.currentRetry(), + err: errorJSON(test.err || {}) + }; +} + +/** + * Transform `error` into a JSON object. + * + * @api private + * @param {Error} err + * @return {Object} + */ +function errorJSON (err) { + var res = {}; + Object.getOwnPropertyNames(err).forEach(function (key) { + res[key] = err[key]; + }, err); + return res; +} diff --git a/node_modules/mocha/lib/reporters/landing.js b/node_modules/mocha/lib/reporters/landing.js new file mode 100644 index 0000000..b0a9fb2 --- /dev/null +++ b/node_modules/mocha/lib/reporters/landing.js @@ -0,0 +1,100 @@ +'use strict'; +/** + * @module Landing + */ +/** + * Module dependencies. + */ + +var Base = require('./base'); +var inherits = require('../utils').inherits; +var cursor = Base.cursor; +var color = Base.color; + +/** + * Expose `Landing`. + */ + +exports = module.exports = Landing; + +/** + * Airplane color. + */ + +Base.colors.plane = 0; + +/** + * Airplane crash color. + */ + +Base.colors['plane crash'] = 31; + +/** + * Runway color. + */ + +Base.colors.runway = 90; + +/** + * Initialize a new `Landing` reporter. + * + * @public + * @class + * @memberof Mocha.reporters + * @extends Mocha.reporters.Base + * @api public + * @param {Runner} runner + */ +function Landing(runner) { + Base.call(this, runner); + + var self = this; + var width = (Base.window.width * 0.75) | 0; + var total = runner.total; + var stream = process.stdout; + var plane = color('plane', '✈'); + var crashed = -1; + var n = 0; + + function runway() { + var buf = Array(width).join('-'); + return ' ' + color('runway', buf); + } + + runner.on('start', function() { + stream.write('\n\n\n '); + cursor.hide(); + }); + + runner.on('test end', function(test) { + // check if the plane crashed + var col = crashed === -1 ? (width * ++n / total) | 0 : crashed; + + // show the crash + if (test.state === 'failed') { + plane = color('plane crash', '✈'); + crashed = col; + } + + // render landing strip + stream.write('\u001b[' + (width + 1) + 'D\u001b[2A'); + stream.write(runway()); + stream.write('\n '); + stream.write(color('runway', Array(col).join('⋅'))); + stream.write(plane); + stream.write(color('runway', Array(width - col).join('⋅') + '\n')); + stream.write(runway()); + stream.write('\u001b[0m'); + }); + + runner.once('end', function() { + cursor.show(); + console.log(); + self.epilogue(); + }); +} + +/** + * Inherit from `Base.prototype`. + */ +inherits(Landing, Base); diff --git a/node_modules/mocha/lib/reporters/list.js b/node_modules/mocha/lib/reporters/list.js new file mode 100644 index 0000000..29ce74a --- /dev/null +++ b/node_modules/mocha/lib/reporters/list.js @@ -0,0 +1,69 @@ +'use strict'; +/** + * @module List + */ +/** + * Module dependencies. + */ + +var Base = require('./base'); +var inherits = require('../utils').inherits; +var color = Base.color; +var cursor = Base.cursor; + +/** + * Expose `List`. + */ + +exports = module.exports = List; + +/** + * Initialize a new `List` test reporter. + * + * @public + * @class + * @memberof Mocha.reporters + * @extends Mocha.reporters.Base + * @api public + * @param {Runner} runner + */ +function List(runner) { + Base.call(this, runner); + + var self = this; + var n = 0; + + runner.on('start', function() { + console.log(); + }); + + runner.on('test', function(test) { + process.stdout.write(color('pass', ' ' + test.fullTitle() + ': ')); + }); + + runner.on('pending', function(test) { + var fmt = color('checkmark', ' -') + color('pending', ' %s'); + console.log(fmt, test.fullTitle()); + }); + + runner.on('pass', function(test) { + var fmt = + color('checkmark', ' ' + Base.symbols.ok) + + color('pass', ' %s: ') + + color(test.speed, '%dms'); + cursor.CR(); + console.log(fmt, test.fullTitle(), test.duration); + }); + + runner.on('fail', function(test) { + cursor.CR(); + console.log(color('fail', ' %d) %s'), ++n, test.fullTitle()); + }); + + runner.once('end', self.epilogue.bind(self)); +} + +/** + * Inherit from `Base.prototype`. + */ +inherits(List, Base); diff --git a/node_modules/mocha/lib/reporters/markdown.js b/node_modules/mocha/lib/reporters/markdown.js new file mode 100644 index 0000000..ff75ee4 --- /dev/null +++ b/node_modules/mocha/lib/reporters/markdown.js @@ -0,0 +1,105 @@ +'use strict'; +/** + * @module Markdown + */ +/** + * Module dependencies. + */ + +var Base = require('./base'); +var utils = require('../utils'); + +/** + * Constants + */ + +var SUITE_PREFIX = '$'; + +/** + * Expose `Markdown`. + */ + +exports = module.exports = Markdown; + +/** + * Initialize a new `Markdown` reporter. + * + * @public + * @class + * @memberof Mocha.reporters + * @extends Mocha.reporters.Base + * @api public + * @param {Runner} runner + */ +function Markdown(runner) { + Base.call(this, runner); + + var level = 0; + var buf = ''; + + function title(str) { + return Array(level).join('#') + ' ' + str; + } + + function mapTOC(suite, obj) { + var ret = obj; + var key = SUITE_PREFIX + suite.title; + + obj = obj[key] = obj[key] || {suite: suite}; + suite.suites.forEach(function(suite) { + mapTOC(suite, obj); + }); + + return ret; + } + + function stringifyTOC(obj, level) { + ++level; + var buf = ''; + var link; + for (var key in obj) { + if (key === 'suite') { + continue; + } + if (key !== SUITE_PREFIX) { + link = ' - [' + key.substring(1) + ']'; + link += '(#' + utils.slug(obj[key].suite.fullTitle()) + ')\n'; + buf += Array(level).join(' ') + link; + } + buf += stringifyTOC(obj[key], level); + } + return buf; + } + + function generateTOC(suite) { + var obj = mapTOC(suite, {}); + return stringifyTOC(obj, 0); + } + + generateTOC(runner.suite); + + runner.on('suite', function(suite) { + ++level; + var slug = utils.slug(suite.fullTitle()); + buf += '' + '\n'; + buf += title(suite.title) + '\n'; + }); + + runner.on('suite end', function() { + --level; + }); + + runner.on('pass', function(test) { + var code = utils.clean(test.body); + buf += test.title + '.\n'; + buf += '\n```js\n'; + buf += code + '\n'; + buf += '```\n\n'; + }); + + runner.once('end', function() { + process.stdout.write('# TOC\n'); + process.stdout.write(generateTOC(runner.suite)); + process.stdout.write(buf); + }); +} diff --git a/node_modules/mocha/lib/reporters/min.js b/node_modules/mocha/lib/reporters/min.js new file mode 100644 index 0000000..2a91a3c --- /dev/null +++ b/node_modules/mocha/lib/reporters/min.js @@ -0,0 +1,44 @@ +'use strict'; +/** + * @module Min + */ +/** + * Module dependencies. + */ + +var Base = require('./base'); +var inherits = require('../utils').inherits; + +/** + * Expose `Min`. + */ + +exports = module.exports = Min; + +/** + * Initialize a new `Min` minimal test reporter (best used with --watch). + * + * @public + * @class + * @memberof Mocha.reporters + * @extends Mocha.reporters.Base + * @api public + * @param {Runner} runner + */ +function Min(runner) { + Base.call(this, runner); + + runner.on('start', function() { + // clear screen + process.stdout.write('\u001b[2J'); + // set cursor position + process.stdout.write('\u001b[1;3H'); + }); + + runner.once('end', this.epilogue.bind(this)); +} + +/** + * Inherit from `Base.prototype`. + */ +inherits(Min, Base); diff --git a/node_modules/mocha/lib/reporters/nyan.js b/node_modules/mocha/lib/reporters/nyan.js new file mode 100644 index 0000000..164a3fa --- /dev/null +++ b/node_modules/mocha/lib/reporters/nyan.js @@ -0,0 +1,269 @@ +'use strict'; +/** + * @module Nyan + */ +/** + * Module dependencies. + */ + +var Base = require('./base'); +var inherits = require('../utils').inherits; + +/** + * Expose `Dot`. + */ + +exports = module.exports = NyanCat; + +/** + * Initialize a new `Dot` matrix test reporter. + * + * @param {Runner} runner + * @api public + * @public + * @class Nyan + * @memberof Mocha.reporters + * @extends Mocha.reporters.Base + */ + +function NyanCat(runner) { + Base.call(this, runner); + + var self = this; + var width = (Base.window.width * 0.75) | 0; + var nyanCatWidth = (this.nyanCatWidth = 11); + + this.colorIndex = 0; + this.numberOfLines = 4; + this.rainbowColors = self.generateColors(); + this.scoreboardWidth = 5; + this.tick = 0; + this.trajectories = [[], [], [], []]; + this.trajectoryWidthMax = width - nyanCatWidth; + + runner.on('start', function() { + Base.cursor.hide(); + self.draw(); + }); + + runner.on('pending', function() { + self.draw(); + }); + + runner.on('pass', function() { + self.draw(); + }); + + runner.on('fail', function() { + self.draw(); + }); + + runner.once('end', function() { + Base.cursor.show(); + for (var i = 0; i < self.numberOfLines; i++) { + write('\n'); + } + self.epilogue(); + }); +} + +/** + * Inherit from `Base.prototype`. + */ +inherits(NyanCat, Base); + +/** + * Draw the nyan cat + * + * @api private + */ + +NyanCat.prototype.draw = function() { + this.appendRainbow(); + this.drawScoreboard(); + this.drawRainbow(); + this.drawNyanCat(); + this.tick = !this.tick; +}; + +/** + * Draw the "scoreboard" showing the number + * of passes, failures and pending tests. + * + * @api private + */ + +NyanCat.prototype.drawScoreboard = function() { + var stats = this.stats; + + function draw(type, n) { + write(' '); + write(Base.color(type, n)); + write('\n'); + } + + draw('green', stats.passes); + draw('fail', stats.failures); + draw('pending', stats.pending); + write('\n'); + + this.cursorUp(this.numberOfLines); +}; + +/** + * Append the rainbow. + * + * @api private + */ + +NyanCat.prototype.appendRainbow = function() { + var segment = this.tick ? '_' : '-'; + var rainbowified = this.rainbowify(segment); + + for (var index = 0; index < this.numberOfLines; index++) { + var trajectory = this.trajectories[index]; + if (trajectory.length >= this.trajectoryWidthMax) { + trajectory.shift(); + } + trajectory.push(rainbowified); + } +}; + +/** + * Draw the rainbow. + * + * @api private + */ + +NyanCat.prototype.drawRainbow = function() { + var self = this; + + this.trajectories.forEach(function(line) { + write('\u001b[' + self.scoreboardWidth + 'C'); + write(line.join('')); + write('\n'); + }); + + this.cursorUp(this.numberOfLines); +}; + +/** + * Draw the nyan cat + * + * @api private + */ +NyanCat.prototype.drawNyanCat = function() { + var self = this; + var startWidth = this.scoreboardWidth + this.trajectories[0].length; + var dist = '\u001b[' + startWidth + 'C'; + var padding = ''; + + write(dist); + write('_,------,'); + write('\n'); + + write(dist); + padding = self.tick ? ' ' : ' '; + write('_|' + padding + '/\\_/\\ '); + write('\n'); + + write(dist); + padding = self.tick ? '_' : '__'; + var tail = self.tick ? '~' : '^'; + write(tail + '|' + padding + this.face() + ' '); + write('\n'); + + write(dist); + padding = self.tick ? ' ' : ' '; + write(padding + '"" "" '); + write('\n'); + + this.cursorUp(this.numberOfLines); +}; + +/** + * Draw nyan cat face. + * + * @api private + * @return {string} + */ + +NyanCat.prototype.face = function() { + var stats = this.stats; + if (stats.failures) { + return '( x .x)'; + } else if (stats.pending) { + return '( o .o)'; + } else if (stats.passes) { + return '( ^ .^)'; + } + return '( - .-)'; +}; + +/** + * Move cursor up `n`. + * + * @api private + * @param {number} n + */ + +NyanCat.prototype.cursorUp = function(n) { + write('\u001b[' + n + 'A'); +}; + +/** + * Move cursor down `n`. + * + * @api private + * @param {number} n + */ + +NyanCat.prototype.cursorDown = function(n) { + write('\u001b[' + n + 'B'); +}; + +/** + * Generate rainbow colors. + * + * @api private + * @return {Array} + */ +NyanCat.prototype.generateColors = function() { + var colors = []; + + for (var i = 0; i < 6 * 7; i++) { + var pi3 = Math.floor(Math.PI / 3); + var n = i * (1.0 / 6); + var r = Math.floor(3 * Math.sin(n) + 3); + var g = Math.floor(3 * Math.sin(n + 2 * pi3) + 3); + var b = Math.floor(3 * Math.sin(n + 4 * pi3) + 3); + colors.push(36 * r + 6 * g + b + 16); + } + + return colors; +}; + +/** + * Apply rainbow to the given `str`. + * + * @api private + * @param {string} str + * @return {string} + */ +NyanCat.prototype.rainbowify = function(str) { + if (!Base.useColors) { + return str; + } + var color = this.rainbowColors[this.colorIndex % this.rainbowColors.length]; + this.colorIndex += 1; + return '\u001b[38;5;' + color + 'm' + str + '\u001b[0m'; +}; + +/** + * Stdout helper. + * + * @param {string} string A message to write to stdout. + */ +function write(string) { + process.stdout.write(string); +} diff --git a/node_modules/mocha/lib/reporters/progress.js b/node_modules/mocha/lib/reporters/progress.js new file mode 100644 index 0000000..042fc1b --- /dev/null +++ b/node_modules/mocha/lib/reporters/progress.js @@ -0,0 +1,99 @@ +'use strict'; +/** + * @module Progress + */ +/** + * Module dependencies. + */ + +var Base = require('./base'); +var inherits = require('../utils').inherits; +var color = Base.color; +var cursor = Base.cursor; + +/** + * Expose `Progress`. + */ + +exports = module.exports = Progress; + +/** + * General progress bar color. + */ + +Base.colors.progress = 90; + +/** + * Initialize a new `Progress` bar test reporter. + * + * @public + * @class + * @memberof Mocha.reporters + * @extends Mocha.reporters.Base + * @api public + * @param {Runner} runner + * @param {Object} options + */ +function Progress(runner, options) { + Base.call(this, runner); + + var self = this; + var width = (Base.window.width * 0.5) | 0; + var total = runner.total; + var complete = 0; + var lastN = -1; + + // default chars + options = options || {}; + var reporterOptions = options.reporterOptions || {}; + + options.open = reporterOptions.open || '['; + options.complete = reporterOptions.complete || '▬'; + options.incomplete = reporterOptions.incomplete || Base.symbols.dot; + options.close = reporterOptions.close || ']'; + options.verbose = reporterOptions.verbose || false; + + // tests started + runner.on('start', function() { + console.log(); + cursor.hide(); + }); + + // tests complete + runner.on('test end', function() { + complete++; + + var percent = complete / total; + var n = (width * percent) | 0; + var i = width - n; + + if (n === lastN && !options.verbose) { + // Don't re-render the line if it hasn't changed + return; + } + lastN = n; + + cursor.CR(); + process.stdout.write('\u001b[J'); + process.stdout.write(color('progress', ' ' + options.open)); + process.stdout.write(Array(n).join(options.complete)); + process.stdout.write(Array(i).join(options.incomplete)); + process.stdout.write(color('progress', options.close)); + if (options.verbose) { + process.stdout.write(color('progress', ' ' + complete + ' of ' + total)); + } + }); + + // tests are complete, output some stats + // and the failures if any + runner.once('end', function() { + cursor.show(); + console.log(); + self.epilogue(); + }); +} + +/** + * Inherit from `Base.prototype`. + */ +inherits(Progress, Base); diff --git a/node_modules/mocha/lib/reporters/spec.js b/node_modules/mocha/lib/reporters/spec.js new file mode 100644 index 0000000..75e6dda --- /dev/null +++ b/node_modules/mocha/lib/reporters/spec.js @@ -0,0 +1,89 @@ +'use strict'; +/** + * @module Spec + */ +/** + * Module dependencies. + */ + +var Base = require('./base'); +var inherits = require('../utils').inherits; +var color = Base.color; + +/** + * Expose `Spec`. + */ + +exports = module.exports = Spec; + +/** + * Initialize a new `Spec` test reporter. + * + * @public + * @class + * @memberof Mocha.reporters + * @extends Mocha.reporters.Base + * @api public + * @param {Runner} runner + */ +function Spec(runner) { + Base.call(this, runner); + + var self = this; + var indents = 0; + var n = 0; + + function indent() { + return Array(indents).join(' '); + } + + runner.on('start', function() { + console.log(); + }); + + runner.on('suite', function(suite) { + ++indents; + console.log(color('suite', '%s%s'), indent(), suite.title); + }); + + runner.on('suite end', function() { + --indents; + if (indents === 1) { + console.log(); + } + }); + + runner.on('pending', function(test) { + var fmt = indent() + color('pending', ' - %s'); + console.log(fmt, test.title); + }); + + runner.on('pass', function(test) { + var fmt; + if (test.speed === 'fast') { + fmt = + indent() + + color('checkmark', ' ' + Base.symbols.ok) + + color('pass', ' %s'); + console.log(fmt, test.title); + } else { + fmt = + indent() + + color('checkmark', ' ' + Base.symbols.ok) + + color('pass', ' %s') + + color(test.speed, ' (%dms)'); + console.log(fmt, test.title, test.duration); + } + }); + + runner.on('fail', function(test) { + console.log(indent() + color('fail', ' %d) %s'), ++n, test.title); + }); + + runner.once('end', self.epilogue.bind(self)); +} + +/** + * Inherit from `Base.prototype`. + */ +inherits(Spec, Base); diff --git a/node_modules/mocha/lib/reporters/tap.js b/node_modules/mocha/lib/reporters/tap.js new file mode 100644 index 0000000..299dc66 --- /dev/null +++ b/node_modules/mocha/lib/reporters/tap.js @@ -0,0 +1,76 @@ +'use strict'; +/** + * @module TAP + */ +/** + * Module dependencies. + */ + +var Base = require('./base'); + +/** + * Expose `TAP`. + */ + +exports = module.exports = TAP; + +/** + * Initialize a new `TAP` reporter. + * + * @public + * @class + * @memberof Mocha.reporters + * @extends Mocha.reporters.Base + * @api public + * @param {Runner} runner + */ +function TAP(runner) { + Base.call(this, runner); + + var n = 1; + var passes = 0; + var failures = 0; + + runner.on('start', function() { + var total = runner.grepTotal(runner.suite); + console.log('%d..%d', 1, total); + }); + + runner.on('test end', function() { + ++n; + }); + + runner.on('pending', function(test) { + console.log('ok %d %s # SKIP -', n, title(test)); + }); + + runner.on('pass', function(test) { + passes++; + console.log('ok %d %s', n, title(test)); + }); + + runner.on('fail', function(test, err) { + failures++; + console.log('not ok %d %s', n, title(test)); + if (err.stack) { + console.log(err.stack.replace(/^/gm, ' ')); + } + }); + + runner.once('end', function() { + console.log('# tests ' + (passes + failures)); + console.log('# pass ' + passes); + console.log('# fail ' + failures); + }); +} + +/** + * Return a TAP-safe title of `test` + * + * @api private + * @param {Object} test + * @return {String} + */ +function title(test) { + return test.fullTitle().replace(/#/g, ''); +} diff --git a/node_modules/mocha/lib/reporters/xunit.js b/node_modules/mocha/lib/reporters/xunit.js new file mode 100644 index 0000000..c1a930d --- /dev/null +++ b/node_modules/mocha/lib/reporters/xunit.js @@ -0,0 +1,207 @@ +'use strict'; +/** + * @module XUnit + */ +/** + * Module dependencies. + */ + +var Base = require('./base'); +var utils = require('../utils'); +var inherits = utils.inherits; +var fs = require('fs'); +var escape = utils.escape; +var mkdirp = require('mkdirp'); +var path = require('path'); + +/** + * Save timer references to avoid Sinon interfering (see GH-237). + */ + +/* eslint-disable no-unused-vars, no-native-reassign */ +var Date = global.Date; +var setTimeout = global.setTimeout; +var setInterval = global.setInterval; +var clearTimeout = global.clearTimeout; +var clearInterval = global.clearInterval; +/* eslint-enable no-unused-vars, no-native-reassign */ + +/** + * Expose `XUnit`. + */ + +exports = module.exports = XUnit; + +/** + * Initialize a new `XUnit` reporter. + * + * @public + * @class + * @memberof Mocha.reporters + * @extends Mocha.reporters.Base + * @api public + * @param {Runner} runner + */ +function XUnit(runner, options) { + Base.call(this, runner); + + var stats = this.stats; + var tests = []; + var self = this; + + // the name of the test suite, as it will appear in the resulting XML file + var suiteName; + + // the default name of the test suite if none is provided + var DEFAULT_SUITE_NAME = 'Mocha Tests'; + + if (options && options.reporterOptions) { + if (options.reporterOptions.output) { + if (!fs.createWriteStream) { + throw new Error('file output not supported in browser'); + } + + mkdirp.sync(path.dirname(options.reporterOptions.output)); + self.fileStream = fs.createWriteStream(options.reporterOptions.output); + } + + // get the suite name from the reporter options (if provided) + suiteName = options.reporterOptions.suiteName; + } + + // fall back to the default suite name + suiteName = suiteName || DEFAULT_SUITE_NAME; + + runner.on('pending', function(test) { + tests.push(test); + }); + + runner.on('pass', function(test) { + tests.push(test); + }); + + runner.on('fail', function(test) { + tests.push(test); + }); + + runner.once('end', function() { + self.write( + tag( + 'testsuite', + { + name: suiteName, + tests: stats.tests, + failures: stats.failures, + errors: stats.failures, + skipped: stats.tests - stats.failures - stats.passes, + timestamp: new Date().toUTCString(), + time: stats.duration / 1000 || 0 + }, + false + ) + ); + + tests.forEach(function(t) { + self.test(t); + }); + + self.write(''); + }); +} + +/** + * Inherit from `Base.prototype`. + */ +inherits(XUnit, Base); + +/** + * Override done to close the stream (if it's a file). + * + * @param failures + * @param {Function} fn + */ +XUnit.prototype.done = function(failures, fn) { + if (this.fileStream) { + this.fileStream.end(function() { + fn(failures); + }); + } else { + fn(failures); + } +}; + +/** + * Write out the given line. + * + * @param {string} line + */ +XUnit.prototype.write = function(line) { + if (this.fileStream) { + this.fileStream.write(line + '\n'); + } else if (typeof process === 'object' && process.stdout) { + process.stdout.write(line + '\n'); + } else { + console.log(line); + } +}; + +/** + * Output tag for the given `test.` + * + * @param {Test} test + */ +XUnit.prototype.test = function(test) { + var attrs = { + classname: test.parent.fullTitle(), + name: test.title, + time: test.duration / 1000 || 0 + }; + + if (test.state === 'failed') { + var err = test.err; + this.write( + tag( + 'testcase', + attrs, + false, + tag( + 'failure', + {}, + false, + escape(err.message) + '\n' + escape(err.stack) + ) + ) + ); + } else if (test.isPending()) { + this.write(tag('testcase', attrs, false, tag('skipped', {}, true))); + } else { + this.write(tag('testcase', attrs, true)); + } +}; + +/** + * HTML tag helper. + * + * @param name + * @param attrs + * @param close + * @param content + * @return {string} + */ +function tag(name, attrs, close, content) { + var end = close ? '/>' : '>'; + var pairs = []; + var tag; + + for (var key in attrs) { + if (Object.prototype.hasOwnProperty.call(attrs, key)) { + pairs.push(key + '="' + escape(attrs[key]) + '"'); + } + } + + tag = '<' + name + (pairs.length ? ' ' + pairs.join(' ') : '') + end; + if (content) { + tag += content + ' Math.pow(2, 31)) { + this._enableTimeouts = false; + } + if (typeof ms === 'string') { + ms = milliseconds(ms); + } + debug('timeout %d', ms); + this._timeout = ms; + if (this.timer) { + this.resetTimeout(); + } + return this; +}; + +/** + * Set or get slow `ms`. + * + * @api private + * @param {number|string} ms + * @return {Runnable|number} ms or Runnable instance. + */ +Runnable.prototype.slow = function(ms) { + if (!arguments.length || typeof ms === 'undefined') { + return this._slow; + } + if (typeof ms === 'string') { + ms = milliseconds(ms); + } + debug('slow %d', ms); + this._slow = ms; + return this; +}; + +/** + * Set and get whether timeout is `enabled`. + * + * @api private + * @param {boolean} enabled + * @return {Runnable|boolean} enabled or Runnable instance. + */ +Runnable.prototype.enableTimeouts = function(enabled) { + if (!arguments.length) { + return this._enableTimeouts; + } + debug('enableTimeouts %s', enabled); + this._enableTimeouts = enabled; + return this; +}; + +/** + * Halt and mark as pending. + * + * @memberof Mocha.Runnable + * @public + * @api public + */ +Runnable.prototype.skip = function() { + throw new Pending('sync skip'); +}; + +/** + * Check if this runnable or its parent suite is marked as pending. + * + * @api private + */ +Runnable.prototype.isPending = function() { + return this.pending || (this.parent && this.parent.isPending()); +}; + +/** + * Return `true` if this Runnable has failed. + * @return {boolean} + * @private + */ +Runnable.prototype.isFailed = function() { + return !this.isPending() && this.state === 'failed'; +}; + +/** + * Return `true` if this Runnable has passed. + * @return {boolean} + * @private + */ +Runnable.prototype.isPassed = function() { + return !this.isPending() && this.state === 'passed'; +}; + +/** + * Set or get number of retries. + * + * @api private + */ +Runnable.prototype.retries = function(n) { + if (!arguments.length) { + return this._retries; + } + this._retries = n; +}; + +/** + * Set or get current retry + * + * @api private + */ +Runnable.prototype.currentRetry = function(n) { + if (!arguments.length) { + return this._currentRetry; + } + this._currentRetry = n; +}; + +/** + * Return the full title generated by recursively concatenating the parent's + * full title. + * + * @memberof Mocha.Runnable + * @public + * @api public + * @return {string} + */ +Runnable.prototype.fullTitle = function() { + return this.titlePath().join(' '); +}; + +/** + * Return the title path generated by concatenating the parent's title path with the title. + * + * @memberof Mocha.Runnable + * @public + * @api public + * @return {string} + */ +Runnable.prototype.titlePath = function() { + return this.parent.titlePath().concat([this.title]); +}; + +/** + * Clear the timeout. + * + * @api private + */ +Runnable.prototype.clearTimeout = function() { + clearTimeout(this.timer); +}; + +/** + * Inspect the runnable void of private properties. + * + * @api private + * @return {string} + */ +Runnable.prototype.inspect = function() { + return JSON.stringify( + this, + function(key, val) { + if (key[0] === '_') { + return; + } + if (key === 'parent') { + return '#'; + } + if (key === 'ctx') { + return '#'; + } + return val; + }, + 2 + ); +}; + +/** + * Reset the timeout. + * + * @api private + */ +Runnable.prototype.resetTimeout = function() { + var self = this; + var ms = this.timeout() || 1e9; + + if (!this._enableTimeouts) { + return; + } + this.clearTimeout(); + this.timer = setTimeout(function() { + if (!self._enableTimeouts) { + return; + } + self.callback(self._timeoutError(ms)); + self.timedOut = true; + }, ms); +}; + +/** + * Set or get a list of whitelisted globals for this test run. + * + * @api private + * @param {string[]} globals + */ +Runnable.prototype.globals = function(globals) { + if (!arguments.length) { + return this._allowedGlobals; + } + this._allowedGlobals = globals; +}; + +/** + * Run the test and invoke `fn(err)`. + * + * @param {Function} fn + * @api private + */ +Runnable.prototype.run = function(fn) { + var self = this; + var start = new Date(); + var ctx = this.ctx; + var finished; + var emitted; + + // Sometimes the ctx exists, but it is not runnable + if (ctx && ctx.runnable) { + ctx.runnable(this); + } + + // called multiple times + function multiple(err) { + if (emitted) { + return; + } + emitted = true; + var msg = 'done() called multiple times'; + if (err && err.message) { + err.message += " (and Mocha's " + msg + ')'; + self.emit('error', err); + } else { + self.emit('error', new Error(msg)); + } + } + + // finished + function done(err) { + var ms = self.timeout(); + if (self.timedOut) { + return; + } + + if (finished) { + return multiple(err); + } + + self.clearTimeout(); + self.duration = new Date() - start; + finished = true; + if (!err && self.duration > ms && self._enableTimeouts) { + err = self._timeoutError(ms); + } + fn(err); + } + + // for .resetTimeout() + this.callback = done; + + // explicit async with `done` argument + if (this.async) { + this.resetTimeout(); + + // allows skip() to be used in an explicit async context + this.skip = function asyncSkip() { + done(new Pending('async skip call')); + // halt execution. the Runnable will be marked pending + // by the previous call, and the uncaught handler will ignore + // the failure. + throw new Pending('async skip; aborting execution'); + }; + + if (this.allowUncaught) { + return callFnAsync(this.fn); + } + try { + callFnAsync(this.fn); + } catch (err) { + emitted = true; + done(utils.getError(err)); + } + return; + } + + if (this.allowUncaught) { + if (this.isPending()) { + done(); + } else { + callFn(this.fn); + } + return; + } + + // sync or promise-returning + try { + if (this.isPending()) { + done(); + } else { + callFn(this.fn); + } + } catch (err) { + emitted = true; + done(utils.getError(err)); + } + + function callFn(fn) { + var result = fn.call(ctx); + if (result && typeof result.then === 'function') { + self.resetTimeout(); + result.then( + function() { + done(); + // Return null so libraries like bluebird do not warn about + // subsequently constructed Promises. + return null; + }, + function(reason) { + done(reason || new Error('Promise rejected with no or falsy reason')); + } + ); + } else { + if (self.asyncOnly) { + return done( + new Error( + '--async-only option in use without declaring `done()` or returning a promise' + ) + ); + } + + done(); + } + } + + function callFnAsync(fn) { + var result = fn.call(ctx, function(err) { + if (err instanceof Error || toString.call(err) === '[object Error]') { + return done(err); + } + if (err) { + if (Object.prototype.toString.call(err) === '[object Object]') { + return done( + new Error('done() invoked with non-Error: ' + JSON.stringify(err)) + ); + } + return done(new Error('done() invoked with non-Error: ' + err)); + } + if (result && utils.isPromise(result)) { + return done( + new Error( + 'Resolution method is overspecified. Specify a callback *or* return a Promise; not both.' + ) + ); + } + + done(); + }); + } +}; + +/** + * Instantiates a "timeout" error + * + * @param {number} ms - Timeout (in milliseconds) + * @returns {Error} a "timeout" error + * @private + */ +Runnable.prototype._timeoutError = function(ms) { + var msg = + 'Timeout of ' + + ms + + 'ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves.'; + if (this.file) { + msg += ' (' + this.file + ')'; + } + return new Error(msg); +}; diff --git a/node_modules/mocha/lib/runner.js b/node_modules/mocha/lib/runner.js new file mode 100644 index 0000000..6aefb34 --- /dev/null +++ b/node_modules/mocha/lib/runner.js @@ -0,0 +1,1009 @@ +'use strict'; + +/** + * @module Runner + */ +/** + * Module dependencies. + */ +var EventEmitter = require('events').EventEmitter; +var Pending = require('./pending'); +var utils = require('./utils'); +var inherits = utils.inherits; +var debug = require('debug')('mocha:runner'); +var Runnable = require('./runnable'); +var stackFilter = utils.stackTraceFilter(); +var stringify = utils.stringify; +var type = utils.type; +var undefinedError = utils.undefinedError; + +/** + * Non-enumerable globals. + */ + +var globals = [ + 'setTimeout', + 'clearTimeout', + 'setInterval', + 'clearInterval', + 'XMLHttpRequest', + 'Date', + 'setImmediate', + 'clearImmediate' +]; + +/** + * Expose `Runner`. + */ + +module.exports = Runner; + +/** + * Initialize a `Runner` for the given `suite`. Derived from [EventEmitter](https://nodejs.org/api/events.html#events_class_eventemitter) + * + * Events: + * + * - `start` execution started + * - `end` execution complete + * - `suite` (suite) test suite execution started + * - `suite end` (suite) all tests (and sub-suites) have finished + * - `test` (test) test execution started + * - `test end` (test) test completed + * - `hook` (hook) hook execution started + * - `hook end` (hook) hook complete + * - `pass` (test) test passed + * - `fail` (test, err) test failed + * - `pending` (test) test pending + * + * @memberof Mocha + * @public + * @class + * @api public + * @param {Suite} [suite] Root suite + * @param {boolean} [delay] Whether or not to delay execution of root suite + * until ready. + */ +function Runner(suite, delay) { + var self = this; + this._globals = []; + this._abort = false; + this._delay = delay; + this.suite = suite; + this.started = false; + this.total = suite.total(); + this.failures = 0; + this.on('test end', function(test) { + self.checkGlobals(test); + }); + this.on('hook end', function(hook) { + self.checkGlobals(hook); + }); + this._defaultGrep = /.*/; + this.grep(this._defaultGrep); + this.globals(this.globalProps().concat(extraGlobals())); +} + +/** + * Wrapper for setImmediate, process.nextTick, or browser polyfill. + * + * @param {Function} fn + * @api private + */ +Runner.immediately = global.setImmediate || process.nextTick; + +/** + * Inherit from `EventEmitter.prototype`. + */ +inherits(Runner, EventEmitter); + +/** + * Run tests with full titles matching `re`. Updates runner.total + * with number of tests matched. + * + * @api public + * @public + * @memberof Mocha.Runner + * @param {RegExp} re + * @param {boolean} invert + * @return {Runner} Runner instance. + */ +Runner.prototype.grep = function(re, invert) { + debug('grep %s', re); + this._grep = re; + this._invert = invert; + this.total = this.grepTotal(this.suite); + return this; +}; + +/** + * Returns the number of tests matching the grep search for the + * given suite. + * + * @memberof Mocha.Runner + * @api public + * @public + * @param {Suite} suite + * @return {number} + */ +Runner.prototype.grepTotal = function(suite) { + var self = this; + var total = 0; + + suite.eachTest(function(test) { + var match = self._grep.test(test.fullTitle()); + if (self._invert) { + match = !match; + } + if (match) { + total++; + } + }); + + return total; +}; + +/** + * Return a list of global properties. + * + * @return {Array} + * @api private + */ +Runner.prototype.globalProps = function() { + var props = Object.keys(global); + + // non-enumerables + for (var i = 0; i < globals.length; ++i) { + if (~props.indexOf(globals[i])) { + continue; + } + props.push(globals[i]); + } + + return props; +}; + +/** + * Allow the given `arr` of globals. + * + * @api public + * @public + * @memberof Mocha.Runner + * @param {Array} arr + * @return {Runner} Runner instance. + */ +Runner.prototype.globals = function(arr) { + if (!arguments.length) { + return this._globals; + } + debug('globals %j', arr); + this._globals = this._globals.concat(arr); + return this; +}; + +/** + * Check for global variable leaks. + * + * @api private + */ +Runner.prototype.checkGlobals = function(test) { + if (this.ignoreLeaks) { + return; + } + var ok = this._globals; + + var globals = this.globalProps(); + var leaks; + + if (test) { + ok = ok.concat(test._allowedGlobals || []); + } + + if (this.prevGlobalsLength === globals.length) { + return; + } + this.prevGlobalsLength = globals.length; + + leaks = filterLeaks(ok, globals); + this._globals = this._globals.concat(leaks); + + if (leaks.length > 1) { + this.fail( + test, + new Error('global leaks detected: ' + leaks.join(', ') + '') + ); + } else if (leaks.length) { + this.fail(test, new Error('global leak detected: ' + leaks[0])); + } +}; + +/** + * Fail the given `test`. + * + * @api private + * @param {Test} test + * @param {Error} err + */ +Runner.prototype.fail = function(test, err) { + if (test.isPending()) { + return; + } + + ++this.failures; + test.state = 'failed'; + + if (!(err instanceof Error || (err && typeof err.message === 'string'))) { + err = new Error( + 'the ' + + type(err) + + ' ' + + stringify(err) + + ' was thrown, throw an Error :)' + ); + } + + try { + err.stack = + this.fullStackTrace || !err.stack ? err.stack : stackFilter(err.stack); + } catch (ignore) { + // some environments do not take kindly to monkeying with the stack + } + + this.emit('fail', test, err); + if (this.suite.bail()) { + this.emit('end'); + } +}; + +/** + * Fail the given `hook` with `err`. + * + * Hook failures work in the following pattern: + * - If bail, then exit + * - Failed `before` hook skips all tests in a suite and subsuites, + * but jumps to corresponding `after` hook + * - Failed `before each` hook skips remaining tests in a + * suite and jumps to corresponding `after each` hook, + * which is run only once + * - Failed `after` hook does not alter + * execution order + * - Failed `after each` hook skips remaining tests in a + * suite and subsuites, but executes other `after each` + * hooks + * + * @api private + * @param {Hook} hook + * @param {Error} err + */ +Runner.prototype.failHook = function(hook, err) { + if (hook.ctx && hook.ctx.currentTest) { + hook.originalTitle = hook.originalTitle || hook.title; + hook.title = + hook.originalTitle + ' for "' + hook.ctx.currentTest.title + '"'; + } + + this.fail(hook, err); +}; + +/** + * Run hook `name` callbacks and then invoke `fn()`. + * + * @api private + * @param {string} name + * @param {Function} fn + */ + +Runner.prototype.hook = function(name, fn) { + var suite = this.suite; + var hooks = suite['_' + name]; + var self = this; + + function next(i) { + var hook = hooks[i]; + if (!hook) { + return fn(); + } + self.currentRunnable = hook; + + hook.ctx.currentTest = self.test; + + self.emit('hook', hook); + + if (!hook.listeners('error').length) { + hook.on('error', function(err) { + self.failHook(hook, err); + }); + } + + hook.run(function(err) { + var testError = hook.error(); + if (testError) { + self.fail(self.test, testError); + } + if (err) { + if (err instanceof Pending) { + if (name === 'beforeEach' || name === 'afterEach') { + self.test.pending = true; + } else { + suite.tests.forEach(function(test) { + test.pending = true; + }); + // a pending hook won't be executed twice. + hook.pending = true; + } + } else { + self.failHook(hook, err); + + // stop executing hooks, notify callee of hook err + return fn(err); + } + } + self.emit('hook end', hook); + delete hook.ctx.currentTest; + next(++i); + }); + } + + Runner.immediately(function() { + next(0); + }); +}; + +/** + * Run hook `name` for the given array of `suites` + * in order, and callback `fn(err, errSuite)`. + * + * @api private + * @param {string} name + * @param {Array} suites + * @param {Function} fn + */ +Runner.prototype.hooks = function(name, suites, fn) { + var self = this; + var orig = this.suite; + + function next(suite) { + self.suite = suite; + + if (!suite) { + self.suite = orig; + return fn(); + } + + self.hook(name, function(err) { + if (err) { + var errSuite = self.suite; + self.suite = orig; + return fn(err, errSuite); + } + + next(suites.pop()); + }); + } + + next(suites.pop()); +}; + +/** + * Run hooks from the top level down. + * + * @param {String} name + * @param {Function} fn + * @api private + */ +Runner.prototype.hookUp = function(name, fn) { + var suites = [this.suite].concat(this.parents()).reverse(); + this.hooks(name, suites, fn); +}; + +/** + * Run hooks from the bottom up. + * + * @param {String} name + * @param {Function} fn + * @api private + */ +Runner.prototype.hookDown = function(name, fn) { + var suites = [this.suite].concat(this.parents()); + this.hooks(name, suites, fn); +}; + +/** + * Return an array of parent Suites from + * closest to furthest. + * + * @return {Array} + * @api private + */ +Runner.prototype.parents = function() { + var suite = this.suite; + var suites = []; + while (suite.parent) { + suite = suite.parent; + suites.push(suite); + } + return suites; +}; + +/** + * Run the current test and callback `fn(err)`. + * + * @param {Function} fn + * @api private + */ +Runner.prototype.runTest = function(fn) { + var self = this; + var test = this.test; + + if (!test) { + return; + } + if (this.forbidOnly && hasOnly(this.parents().reverse()[0] || this.suite)) { + fn(new Error('`.only` forbidden')); + return; + } + if (this.asyncOnly) { + test.asyncOnly = true; + } + test.on('error', function(err) { + self.fail(test, err); + }); + if (this.allowUncaught) { + test.allowUncaught = true; + return test.run(fn); + } + try { + test.run(fn); + } catch (err) { + fn(err); + } +}; + +/** + * Run tests in the given `suite` and invoke the callback `fn()` when complete. + * + * @api private + * @param {Suite} suite + * @param {Function} fn + */ +Runner.prototype.runTests = function(suite, fn) { + var self = this; + var tests = suite.tests.slice(); + var test; + + function hookErr(_, errSuite, after) { + // before/after Each hook for errSuite failed: + var orig = self.suite; + + // for failed 'after each' hook start from errSuite parent, + // otherwise start from errSuite itself + self.suite = after ? errSuite.parent : errSuite; + + if (self.suite) { + // call hookUp afterEach + self.hookUp('afterEach', function(err2, errSuite2) { + self.suite = orig; + // some hooks may fail even now + if (err2) { + return hookErr(err2, errSuite2, true); + } + // report error suite + fn(errSuite); + }); + } else { + // there is no need calling other 'after each' hooks + self.suite = orig; + fn(errSuite); + } + } + + function next(err, errSuite) { + // if we bail after first err + if (self.failures && suite._bail) { + return fn(); + } + + if (self._abort) { + return fn(); + } + + if (err) { + return hookErr(err, errSuite, true); + } + + // next test + test = tests.shift(); + + // all done + if (!test) { + return fn(); + } + + // grep + var match = self._grep.test(test.fullTitle()); + if (self._invert) { + match = !match; + } + if (!match) { + // Run immediately only if we have defined a grep. When we + // define a grep — It can cause maximum callstack error if + // the grep is doing a large recursive loop by neglecting + // all tests. The run immediately function also comes with + // a performance cost. So we don't want to run immediately + // if we run the whole test suite, because running the whole + // test suite don't do any immediate recursive loops. Thus, + // allowing a JS runtime to breathe. + if (self._grep !== self._defaultGrep) { + Runner.immediately(next); + } else { + next(); + } + return; + } + + if (test.isPending()) { + if (self.forbidPending) { + test.isPending = alwaysFalse; + self.fail(test, new Error('Pending test forbidden')); + delete test.isPending; + } else { + self.emit('pending', test); + } + self.emit('test end', test); + return next(); + } + + // execute test and hook(s) + self.emit('test', (self.test = test)); + self.hookDown('beforeEach', function(err, errSuite) { + if (test.isPending()) { + if (self.forbidPending) { + test.isPending = alwaysFalse; + self.fail(test, new Error('Pending test forbidden')); + delete test.isPending; + } else { + self.emit('pending', test); + } + self.emit('test end', test); + return next(); + } + if (err) { + return hookErr(err, errSuite, false); + } + self.currentRunnable = self.test; + self.runTest(function(err) { + test = self.test; + if (err) { + var retry = test.currentRetry(); + if (err instanceof Pending && self.forbidPending) { + self.fail(test, new Error('Pending test forbidden')); + } else if (err instanceof Pending) { + test.pending = true; + self.emit('pending', test); + } else if (retry < test.retries()) { + var clonedTest = test.clone(); + clonedTest.currentRetry(retry + 1); + tests.unshift(clonedTest); + + // Early return + hook trigger so that it doesn't + // increment the count wrong + return self.hookUp('afterEach', next); + } else { + self.fail(test, err); + } + self.emit('test end', test); + + if (err instanceof Pending) { + return next(); + } + + return self.hookUp('afterEach', next); + } + + test.state = 'passed'; + self.emit('pass', test); + self.emit('test end', test); + self.hookUp('afterEach', next); + }); + }); + } + + this.next = next; + this.hookErr = hookErr; + next(); +}; + +function alwaysFalse() { + return false; +} + +/** + * Run the given `suite` and invoke the callback `fn()` when complete. + * + * @api private + * @param {Suite} suite + * @param {Function} fn + */ +Runner.prototype.runSuite = function(suite, fn) { + var i = 0; + var self = this; + var total = this.grepTotal(suite); + var afterAllHookCalled = false; + + debug('run suite %s', suite.fullTitle()); + + if (!total || (self.failures && suite._bail)) { + return fn(); + } + + this.emit('suite', (this.suite = suite)); + + function next(errSuite) { + if (errSuite) { + // current suite failed on a hook from errSuite + if (errSuite === suite) { + // if errSuite is current suite + // continue to the next sibling suite + return done(); + } + // errSuite is among the parents of current suite + // stop execution of errSuite and all sub-suites + return done(errSuite); + } + + if (self._abort) { + return done(); + } + + var curr = suite.suites[i++]; + if (!curr) { + return done(); + } + + // Avoid grep neglecting large number of tests causing a + // huge recursive loop and thus a maximum call stack error. + // See comment in `this.runTests()` for more information. + if (self._grep !== self._defaultGrep) { + Runner.immediately(function() { + self.runSuite(curr, next); + }); + } else { + self.runSuite(curr, next); + } + } + + function done(errSuite) { + self.suite = suite; + self.nextSuite = next; + + if (afterAllHookCalled) { + fn(errSuite); + } else { + // mark that the afterAll block has been called once + // and so can be skipped if there is an error in it. + afterAllHookCalled = true; + + // remove reference to test + delete self.test; + + self.hook('afterAll', function() { + self.emit('suite end', suite); + fn(errSuite); + }); + } + } + + this.nextSuite = next; + + this.hook('beforeAll', function(err) { + if (err) { + return done(); + } + self.runTests(suite, next); + }); +}; + +/** + * Handle uncaught exceptions. + * + * @param {Error} err + * @api private + */ +Runner.prototype.uncaught = function(err) { + if (err) { + debug( + 'uncaught exception %s', + err === + function() { + return this; + }.call(err) + ? err.message || err + : err + ); + } else { + debug('uncaught undefined exception'); + err = undefinedError(); + } + err.uncaught = true; + + var runnable = this.currentRunnable; + + if (!runnable) { + runnable = new Runnable('Uncaught error outside test suite'); + runnable.parent = this.suite; + + if (this.started) { + this.fail(runnable, err); + } else { + // Can't recover from this failure + this.emit('start'); + this.fail(runnable, err); + this.emit('end'); + } + + return; + } + + runnable.clearTimeout(); + + // Ignore errors if already failed or pending + // See #3226 + if (runnable.isFailed() || runnable.isPending()) { + return; + } + // we cannot recover gracefully if a Runnable has already passed + // then fails asynchronously + var alreadyPassed = runnable.isPassed(); + // this will change the state to "failed" regardless of the current value + this.fail(runnable, err); + if (!alreadyPassed) { + // recover from test + if (runnable.type === 'test') { + this.emit('test end', runnable); + this.hookUp('afterEach', this.next); + return; + } + + // recover from hooks + var errSuite = this.suite; + // if hook failure is in afterEach block + if (runnable.fullTitle().indexOf('after each') > -1) { + return this.hookErr(err, errSuite, true); + } + // if hook failure is in beforeEach block + if (runnable.fullTitle().indexOf('before each') > -1) { + return this.hookErr(err, errSuite, false); + } + // if hook failure is in after or before blocks + return this.nextSuite(errSuite); + } + + // bail + this.emit('end'); +}; + +/** + * Cleans up the references to all the deferred functions + * (before/after/beforeEach/afterEach) and tests of a Suite. + * These must be deleted otherwise a memory leak can happen, + * as those functions may reference variables from closures, + * thus those variables can never be garbage collected as long + * as the deferred functions exist. + * + * @param {Suite} suite + */ +function cleanSuiteReferences(suite) { + function cleanArrReferences(arr) { + for (var i = 0; i < arr.length; i++) { + delete arr[i].fn; + } + } + + if (Array.isArray(suite._beforeAll)) { + cleanArrReferences(suite._beforeAll); + } + + if (Array.isArray(suite._beforeEach)) { + cleanArrReferences(suite._beforeEach); + } + + if (Array.isArray(suite._afterAll)) { + cleanArrReferences(suite._afterAll); + } + + if (Array.isArray(suite._afterEach)) { + cleanArrReferences(suite._afterEach); + } + + for (var i = 0; i < suite.tests.length; i++) { + delete suite.tests[i].fn; + } +} + +/** + * Run the root suite and invoke `fn(failures)` + * on completion. + * + * @api public + * @public + * @memberof Mocha.Runner + * @param {Function} fn + * @return {Runner} Runner instance. + */ +Runner.prototype.run = function(fn) { + var self = this; + var rootSuite = this.suite; + + fn = fn || function() {}; + + function uncaught(err) { + self.uncaught(err); + } + + function start() { + // If there is an `only` filter + if (hasOnly(rootSuite)) { + filterOnly(rootSuite); + } + self.started = true; + self.emit('start'); + self.runSuite(rootSuite, function() { + debug('finished running'); + self.emit('end'); + }); + } + + debug('start'); + + // references cleanup to avoid memory leaks + this.on('suite end', cleanSuiteReferences); + + // callback + this.on('end', function() { + debug('end'); + process.removeListener('uncaughtException', uncaught); + fn(self.failures); + }); + + // uncaught exception + process.on('uncaughtException', uncaught); + + if (this._delay) { + // for reporters, I guess. + // might be nice to debounce some dots while we wait. + this.emit('waiting', rootSuite); + rootSuite.once('run', start); + } else { + start(); + } + + return this; +}; + +/** + * Cleanly abort execution. + * + * @memberof Mocha.Runner + * @public + * @api public + * @return {Runner} Runner instance. + */ +Runner.prototype.abort = function() { + debug('aborting'); + this._abort = true; + + return this; +}; + +/** + * Filter suites based on `isOnly` logic. + * + * @param {Array} suite + * @returns {Boolean} + * @api private + */ +function filterOnly(suite) { + if (suite._onlyTests.length) { + // If the suite contains `only` tests, run those and ignore any nested suites. + suite.tests = suite._onlyTests; + suite.suites = []; + } else { + // Otherwise, do not run any of the tests in this suite. + suite.tests = []; + suite._onlySuites.forEach(function(onlySuite) { + // If there are other `only` tests/suites nested in the current `only` suite, then filter that `only` suite. + // Otherwise, all of the tests on this `only` suite should be run, so don't filter it. + if (hasOnly(onlySuite)) { + filterOnly(onlySuite); + } + }); + // Run the `only` suites, as well as any other suites that have `only` tests/suites as descendants. + suite.suites = suite.suites.filter(function(childSuite) { + return ( + suite._onlySuites.indexOf(childSuite) !== -1 || filterOnly(childSuite) + ); + }); + } + // Keep the suite only if there is something to run + return suite.tests.length || suite.suites.length; +} + +/** + * Determines whether a suite has an `only` test or suite as a descendant. + * + * @param {Array} suite + * @returns {Boolean} + * @api private + */ +function hasOnly(suite) { + return ( + suite._onlyTests.length || + suite._onlySuites.length || + suite.suites.some(hasOnly) + ); +} + +/** + * Filter leaks with the given globals flagged as `ok`. + * + * @api private + * @param {Array} ok + * @param {Array} globals + * @return {Array} + */ +function filterLeaks(ok, globals) { + return globals.filter(function(key) { + // Firefox and Chrome exposes iframes as index inside the window object + if (/^\d+/.test(key)) { + return false; + } + + // in firefox + // if runner runs in an iframe, this iframe's window.getInterface method + // not init at first it is assigned in some seconds + if (global.navigator && /^getInterface/.test(key)) { + return false; + } + + // an iframe could be approached by window[iframeIndex] + // in ie6,7,8 and opera, iframeIndex is enumerable, this could cause leak + if (global.navigator && /^\d+/.test(key)) { + return false; + } + + // Opera and IE expose global variables for HTML element IDs (issue #243) + if (/^mocha-/.test(key)) { + return false; + } + + var matched = ok.filter(function(ok) { + if (~ok.indexOf('*')) { + return key.indexOf(ok.split('*')[0]) === 0; + } + return key === ok; + }); + return !matched.length && (!global.navigator || key !== 'onerror'); + }); +} + +/** + * Array of globals dependent on the environment. + * + * @return {Array} + * @api private + */ +function extraGlobals() { + if (typeof process === 'object' && typeof process.version === 'string') { + var parts = process.version.split('.'); + var nodeVersion = parts.reduce(function(a, v) { + return (a << 8) | v; + }); + + // 'errno' was renamed to process._errno in v0.9.11. + + if (nodeVersion < 0x00090b) { + return ['errno']; + } + } + + return []; +} diff --git a/node_modules/mocha/lib/suite.js b/node_modules/mocha/lib/suite.js new file mode 100644 index 0000000..91832ba --- /dev/null +++ b/node_modules/mocha/lib/suite.js @@ -0,0 +1,427 @@ +'use strict'; +/** + * @module Suite + */ + +/** + * Module dependencies. + */ +var EventEmitter = require('events').EventEmitter; +var Hook = require('./hook'); +var utils = require('./utils'); +var inherits = utils.inherits; +var debug = require('debug')('mocha:suite'); +var milliseconds = require('./ms'); + +/** + * Expose `Suite`. + */ + +exports = module.exports = Suite; + +/** + * Create a new `Suite` with the given `title` and parent `Suite`. When a suite + * with the same title is already present, that suite is returned to provide + * nicer reporter and more flexible meta-testing. + * + * @memberof Mocha + * @public + * @api public + * @param {Suite} parent + * @param {string} title + * @return {Suite} + */ +exports.create = function(parent, title) { + var suite = new Suite(title, parent.ctx); + suite.parent = parent; + title = suite.fullTitle(); + parent.addSuite(suite); + return suite; +}; + +/** + * Initialize a new `Suite` with the given `title` and `ctx`. Derived from [EventEmitter](https://nodejs.org/api/events.html#events_class_eventemitter) + * + * @memberof Mocha + * @public + * @class + * @param {string} title + * @param {Context} parentContext + */ +function Suite(title, parentContext) { + if (!utils.isString(title)) { + throw new Error( + 'Suite `title` should be a "string" but "' + + typeof title + + '" was given instead.' + ); + } + this.title = title; + function Context() {} + Context.prototype = parentContext; + this.ctx = new Context(); + this.suites = []; + this.tests = []; + this.pending = false; + this._beforeEach = []; + this._beforeAll = []; + this._afterEach = []; + this._afterAll = []; + this.root = !title; + this._timeout = 2000; + this._enableTimeouts = true; + this._slow = 75; + this._bail = false; + this._retries = -1; + this._onlyTests = []; + this._onlySuites = []; + this.delayed = false; +} + +/** + * Inherit from `EventEmitter.prototype`. + */ +inherits(Suite, EventEmitter); + +/** + * Return a clone of this `Suite`. + * + * @api private + * @return {Suite} + */ +Suite.prototype.clone = function() { + var suite = new Suite(this.title); + debug('clone'); + suite.ctx = this.ctx; + suite.timeout(this.timeout()); + suite.retries(this.retries()); + suite.enableTimeouts(this.enableTimeouts()); + suite.slow(this.slow()); + suite.bail(this.bail()); + return suite; +}; + +/** + * Set or get timeout `ms` or short-hand such as "2s". + * + * @api private + * @param {number|string} ms + * @return {Suite|number} for chaining + */ +Suite.prototype.timeout = function(ms) { + if (!arguments.length) { + return this._timeout; + } + if (ms.toString() === '0') { + this._enableTimeouts = false; + } + if (typeof ms === 'string') { + ms = milliseconds(ms); + } + debug('timeout %d', ms); + this._timeout = parseInt(ms, 10); + return this; +}; + +/** + * Set or get number of times to retry a failed test. + * + * @api private + * @param {number|string} n + * @return {Suite|number} for chaining + */ +Suite.prototype.retries = function(n) { + if (!arguments.length) { + return this._retries; + } + debug('retries %d', n); + this._retries = parseInt(n, 10) || 0; + return this; +}; + +/** + * Set or get timeout to `enabled`. + * + * @api private + * @param {boolean} enabled + * @return {Suite|boolean} self or enabled + */ +Suite.prototype.enableTimeouts = function(enabled) { + if (!arguments.length) { + return this._enableTimeouts; + } + debug('enableTimeouts %s', enabled); + this._enableTimeouts = enabled; + return this; +}; + +/** + * Set or get slow `ms` or short-hand such as "2s". + * + * @api private + * @param {number|string} ms + * @return {Suite|number} for chaining + */ +Suite.prototype.slow = function(ms) { + if (!arguments.length) { + return this._slow; + } + if (typeof ms === 'string') { + ms = milliseconds(ms); + } + debug('slow %d', ms); + this._slow = ms; + return this; +}; + +/** + * Set or get whether to bail after first error. + * + * @api private + * @param {boolean} bail + * @return {Suite|number} for chaining + */ +Suite.prototype.bail = function(bail) { + if (!arguments.length) { + return this._bail; + } + debug('bail %s', bail); + this._bail = bail; + return this; +}; + +/** + * Check if this suite or its parent suite is marked as pending. + * + * @api private + */ +Suite.prototype.isPending = function() { + return this.pending || (this.parent && this.parent.isPending()); +}; + +/** + * Generic hook-creator. + * @private + * @param {string} title - Title of hook + * @param {Function} fn - Hook callback + * @returns {Hook} A new hook + */ +Suite.prototype._createHook = function(title, fn) { + var hook = new Hook(title, fn); + hook.parent = this; + hook.timeout(this.timeout()); + hook.retries(this.retries()); + hook.enableTimeouts(this.enableTimeouts()); + hook.slow(this.slow()); + hook.ctx = this.ctx; + hook.file = this.file; + return hook; +}; + +/** + * Run `fn(test[, done])` before running tests. + * + * @api private + * @param {string} title + * @param {Function} fn + * @return {Suite} for chaining + */ +Suite.prototype.beforeAll = function(title, fn) { + if (this.isPending()) { + return this; + } + if (typeof title === 'function') { + fn = title; + title = fn.name; + } + title = '"before all" hook' + (title ? ': ' + title : ''); + + var hook = this._createHook(title, fn); + this._beforeAll.push(hook); + this.emit('beforeAll', hook); + return this; +}; + +/** + * Run `fn(test[, done])` after running tests. + * + * @api private + * @param {string} title + * @param {Function} fn + * @return {Suite} for chaining + */ +Suite.prototype.afterAll = function(title, fn) { + if (this.isPending()) { + return this; + } + if (typeof title === 'function') { + fn = title; + title = fn.name; + } + title = '"after all" hook' + (title ? ': ' + title : ''); + + var hook = this._createHook(title, fn); + this._afterAll.push(hook); + this.emit('afterAll', hook); + return this; +}; + +/** + * Run `fn(test[, done])` before each test case. + * + * @api private + * @param {string} title + * @param {Function} fn + * @return {Suite} for chaining + */ +Suite.prototype.beforeEach = function(title, fn) { + if (this.isPending()) { + return this; + } + if (typeof title === 'function') { + fn = title; + title = fn.name; + } + title = '"before each" hook' + (title ? ': ' + title : ''); + + var hook = this._createHook(title, fn); + this._beforeEach.push(hook); + this.emit('beforeEach', hook); + return this; +}; + +/** + * Run `fn(test[, done])` after each test case. + * + * @api private + * @param {string} title + * @param {Function} fn + * @return {Suite} for chaining + */ +Suite.prototype.afterEach = function(title, fn) { + if (this.isPending()) { + return this; + } + if (typeof title === 'function') { + fn = title; + title = fn.name; + } + title = '"after each" hook' + (title ? ': ' + title : ''); + + var hook = this._createHook(title, fn); + this._afterEach.push(hook); + this.emit('afterEach', hook); + return this; +}; + +/** + * Add a test `suite`. + * + * @api private + * @param {Suite} suite + * @return {Suite} for chaining + */ +Suite.prototype.addSuite = function(suite) { + suite.parent = this; + suite.timeout(this.timeout()); + suite.retries(this.retries()); + suite.enableTimeouts(this.enableTimeouts()); + suite.slow(this.slow()); + suite.bail(this.bail()); + this.suites.push(suite); + this.emit('suite', suite); + return this; +}; + +/** + * Add a `test` to this suite. + * + * @api private + * @param {Test} test + * @return {Suite} for chaining + */ +Suite.prototype.addTest = function(test) { + test.parent = this; + test.timeout(this.timeout()); + test.retries(this.retries()); + test.enableTimeouts(this.enableTimeouts()); + test.slow(this.slow()); + test.ctx = this.ctx; + this.tests.push(test); + this.emit('test', test); + return this; +}; + +/** + * Return the full title generated by recursively concatenating the parent's + * full title. + * + * @memberof Mocha.Suite + * @public + * @api public + * @return {string} + */ +Suite.prototype.fullTitle = function() { + return this.titlePath().join(' '); +}; + +/** + * Return the title path generated by recursively concatenating the parent's + * title path. + * + * @memberof Mocha.Suite + * @public + * @api public + * @return {string} + */ +Suite.prototype.titlePath = function() { + var result = []; + if (this.parent) { + result = result.concat(this.parent.titlePath()); + } + if (!this.root) { + result.push(this.title); + } + return result; +}; + +/** + * Return the total number of tests. + * + * @memberof Mocha.Suite + * @public + * @api public + * @return {number} + */ +Suite.prototype.total = function() { + return ( + this.suites.reduce(function(sum, suite) { + return sum + suite.total(); + }, 0) + this.tests.length + ); +}; + +/** + * Iterates through each suite recursively to find all tests. Applies a + * function in the format `fn(test)`. + * + * @api private + * @param {Function} fn + * @return {Suite} + */ +Suite.prototype.eachTest = function(fn) { + this.tests.forEach(fn); + this.suites.forEach(function(suite) { + suite.eachTest(fn); + }); + return this; +}; + +/** + * This will run the root suite if we happen to be running in delayed mode. + */ +Suite.prototype.run = function run() { + if (this.root) { + this.emit('run'); + } +}; diff --git a/node_modules/mocha/lib/template.html b/node_modules/mocha/lib/template.html new file mode 100644 index 0000000..36c5e0b --- /dev/null +++ b/node_modules/mocha/lib/template.html @@ -0,0 +1,18 @@ + + + + Mocha + + + + + +
    + + + + + + diff --git a/node_modules/mocha/lib/test.js b/node_modules/mocha/lib/test.js new file mode 100644 index 0000000..d8233a3 --- /dev/null +++ b/node_modules/mocha/lib/test.js @@ -0,0 +1,46 @@ +'use strict'; +var Runnable = require('./runnable'); +var utils = require('./utils'); +var isString = utils.isString; + +module.exports = Test; + +/** + * Initialize a new `Test` with the given `title` and callback `fn`. + * + * @class + * @extends Runnable + * @param {String} title + * @param {Function} fn + */ +function Test(title, fn) { + if (!isString(title)) { + throw new Error( + 'Test `title` should be a "string" but "' + + typeof title + + '" was given instead.' + ); + } + Runnable.call(this, title, fn); + this.pending = !fn; + this.type = 'test'; +} + +/** + * Inherit from `Runnable.prototype`. + */ +utils.inherits(Test, Runnable); + +Test.prototype.clone = function() { + var test = new Test(this.title, this.fn); + test.timeout(this.timeout()); + test.slow(this.slow()); + test.enableTimeouts(this.enableTimeouts()); + test.retries(this.retries()); + test.currentRetry(this.currentRetry()); + test.globals(this.globals()); + test.parent = this.parent; + test.file = this.file; + test.ctx = this.ctx; + return test; +}; diff --git a/node_modules/mocha/lib/utils.js b/node_modules/mocha/lib/utils.js new file mode 100644 index 0000000..e67bf74 --- /dev/null +++ b/node_modules/mocha/lib/utils.js @@ -0,0 +1,670 @@ +'use strict'; + +/** + * @module + */ + +/** + * Module dependencies. + */ + +var debug = require('debug')('mocha:watch'); +var fs = require('fs'); +var glob = require('glob'); +var path = require('path'); +var join = path.join; +var he = require('he'); + +/** + * Ignored directories. + */ + +var ignore = ['node_modules', '.git']; + +exports.inherits = require('util').inherits; + +/** + * Escape special characters in the given string of html. + * + * @api private + * @param {string} html + * @return {string} + */ +exports.escape = function(html) { + return he.encode(String(html), {useNamedReferences: false}); +}; + +/** + * Test if the given obj is type of string. + * + * @api private + * @param {Object} obj + * @return {boolean} + */ +exports.isString = function(obj) { + return typeof obj === 'string'; +}; + +/** + * Watch the given `files` for changes + * and invoke `fn(file)` on modification. + * + * @api private + * @param {Array} files + * @param {Function} fn + */ +exports.watch = function(files, fn) { + var options = {interval: 100}; + files.forEach(function(file) { + debug('file %s', file); + fs.watchFile(file, options, function(curr, prev) { + if (prev.mtime < curr.mtime) { + fn(file); + } + }); + }); +}; + +/** + * Ignored files. + * + * @api private + * @param {string} path + * @return {boolean} + */ +function ignored(path) { + return !~ignore.indexOf(path); +} + +/** + * Lookup files in the given `dir`. + * + * @api private + * @param {string} dir + * @param {string[]} [ext=['.js']] + * @param {Array} [ret=[]] + * @return {Array} + */ +exports.files = function(dir, ext, ret) { + ret = ret || []; + ext = ext || ['js']; + + var re = new RegExp('\\.(' + ext.join('|') + ')$'); + + fs + .readdirSync(dir) + .filter(ignored) + .forEach(function(path) { + path = join(dir, path); + if (fs.lstatSync(path).isDirectory()) { + exports.files(path, ext, ret); + } else if (path.match(re)) { + ret.push(path); + } + }); + + return ret; +}; + +/** + * Compute a slug from the given `str`. + * + * @api private + * @param {string} str + * @return {string} + */ +exports.slug = function(str) { + return str + .toLowerCase() + .replace(/ +/g, '-') + .replace(/[^-\w]/g, ''); +}; + +/** + * Strip the function definition from `str`, and re-indent for pre whitespace. + * + * @param {string} str + * @return {string} + */ +exports.clean = function(str) { + str = str + .replace(/\r\n?|[\n\u2028\u2029]/g, '\n') + .replace(/^\uFEFF/, '') + // (traditional)-> space/name parameters body (lambda)-> parameters body multi-statement/single keep body content + .replace( + /^function(?:\s*|\s+[^(]*)\([^)]*\)\s*\{((?:.|\n)*?)\s*\}$|^\([^)]*\)\s*=>\s*(?:\{((?:.|\n)*?)\s*\}|((?:.|\n)*))$/, + '$1$2$3' + ); + + var spaces = str.match(/^\n?( *)/)[1].length; + var tabs = str.match(/^\n?(\t*)/)[1].length; + var re = new RegExp( + '^\n?' + (tabs ? '\t' : ' ') + '{' + (tabs || spaces) + '}', + 'gm' + ); + + str = str.replace(re, ''); + + return str.trim(); +}; + +/** + * Parse the given `qs`. + * + * @api private + * @param {string} qs + * @return {Object} + */ +exports.parseQuery = function(qs) { + return qs + .replace('?', '') + .split('&') + .reduce(function(obj, pair) { + var i = pair.indexOf('='); + var key = pair.slice(0, i); + var val = pair.slice(++i); + + // Due to how the URLSearchParams API treats spaces + obj[key] = decodeURIComponent(val.replace(/\+/g, '%20')); + + return obj; + }, {}); +}; + +/** + * Highlight the given string of `js`. + * + * @api private + * @param {string} js + * @return {string} + */ +function highlight(js) { + return js + .replace(//g, '>') + .replace(/\/\/(.*)/gm, '//$1') + .replace(/('.*?')/gm, '$1') + .replace(/(\d+\.\d+)/gm, '$1') + .replace(/(\d+)/gm, '$1') + .replace( + /\bnew[ \t]+(\w+)/gm, + 'new $1' + ) + .replace( + /\b(function|new|throw|return|var|if|else)\b/gm, + '$1' + ); +} + +/** + * Highlight the contents of tag `name`. + * + * @api private + * @param {string} name + */ +exports.highlightTags = function(name) { + var code = document.getElementById('mocha').getElementsByTagName(name); + for (var i = 0, len = code.length; i < len; ++i) { + code[i].innerHTML = highlight(code[i].innerHTML); + } +}; + +/** + * If a value could have properties, and has none, this function is called, + * which returns a string representation of the empty value. + * + * Functions w/ no properties return `'[Function]'` + * Arrays w/ length === 0 return `'[]'` + * Objects w/ no properties return `'{}'` + * All else: return result of `value.toString()` + * + * @api private + * @param {*} value The value to inspect. + * @param {string} typeHint The type of the value + * @returns {string} + */ +function emptyRepresentation(value, typeHint) { + switch (typeHint) { + case 'function': + return '[Function]'; + case 'object': + return '{}'; + case 'array': + return '[]'; + default: + return value.toString(); + } +} + +/** + * Takes some variable and asks `Object.prototype.toString()` what it thinks it + * is. + * + * @api private + * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/toString + * @param {*} value The value to test. + * @returns {string} Computed type + * @example + * type({}) // 'object' + * type([]) // 'array' + * type(1) // 'number' + * type(false) // 'boolean' + * type(Infinity) // 'number' + * type(null) // 'null' + * type(new Date()) // 'date' + * type(/foo/) // 'regexp' + * type('type') // 'string' + * type(global) // 'global' + * type(new String('foo') // 'object' + */ +var type = (exports.type = function type(value) { + if (value === undefined) { + return 'undefined'; + } else if (value === null) { + return 'null'; + } else if (Buffer.isBuffer(value)) { + return 'buffer'; + } + return Object.prototype.toString + .call(value) + .replace(/^\[.+\s(.+?)]$/, '$1') + .toLowerCase(); +}); + +/** + * Stringify `value`. Different behavior depending on type of value: + * + * - If `value` is undefined or null, return `'[undefined]'` or `'[null]'`, respectively. + * - If `value` is not an object, function or array, return result of `value.toString()` wrapped in double-quotes. + * - If `value` is an *empty* object, function, or array, return result of function + * {@link emptyRepresentation}. + * - If `value` has properties, call {@link exports.canonicalize} on it, then return result of + * JSON.stringify(). + * + * @api private + * @see exports.type + * @param {*} value + * @return {string} + */ +exports.stringify = function(value) { + var typeHint = type(value); + + if (!~['object', 'array', 'function'].indexOf(typeHint)) { + if (typeHint === 'buffer') { + var json = Buffer.prototype.toJSON.call(value); + // Based on the toJSON result + return jsonStringify( + json.data && json.type ? json.data : json, + 2 + ).replace(/,(\n|$)/g, '$1'); + } + + // IE7/IE8 has a bizarre String constructor; needs to be coerced + // into an array and back to obj. + if (typeHint === 'string' && typeof value === 'object') { + value = value.split('').reduce(function(acc, char, idx) { + acc[idx] = char; + return acc; + }, {}); + typeHint = 'object'; + } else { + return jsonStringify(value); + } + } + + for (var prop in value) { + if (Object.prototype.hasOwnProperty.call(value, prop)) { + return jsonStringify( + exports.canonicalize(value, null, typeHint), + 2 + ).replace(/,(\n|$)/g, '$1'); + } + } + + return emptyRepresentation(value, typeHint); +}; + +/** + * like JSON.stringify but more sense. + * + * @api private + * @param {Object} object + * @param {number=} spaces + * @param {number=} depth + * @returns {*} + */ +function jsonStringify(object, spaces, depth) { + if (typeof spaces === 'undefined') { + // primitive types + return _stringify(object); + } + + depth = depth || 1; + var space = spaces * depth; + var str = Array.isArray(object) ? '[' : '{'; + var end = Array.isArray(object) ? ']' : '}'; + var length = + typeof object.length === 'number' + ? object.length + : Object.keys(object).length; + // `.repeat()` polyfill + function repeat(s, n) { + return new Array(n).join(s); + } + + function _stringify(val) { + switch (type(val)) { + case 'null': + case 'undefined': + val = '[' + val + ']'; + break; + case 'array': + case 'object': + val = jsonStringify(val, spaces, depth + 1); + break; + case 'boolean': + case 'regexp': + case 'symbol': + case 'number': + val = + val === 0 && 1 / val === -Infinity // `-0` + ? '-0' + : val.toString(); + break; + case 'date': + var sDate = isNaN(val.getTime()) ? val.toString() : val.toISOString(); + val = '[Date: ' + sDate + ']'; + break; + case 'buffer': + var json = val.toJSON(); + // Based on the toJSON result + json = json.data && json.type ? json.data : json; + val = '[Buffer: ' + jsonStringify(json, 2, depth + 1) + ']'; + break; + default: + val = + val === '[Function]' || val === '[Circular]' + ? val + : JSON.stringify(val); // string + } + return val; + } + + for (var i in object) { + if (!Object.prototype.hasOwnProperty.call(object, i)) { + continue; // not my business + } + --length; + str += + '\n ' + + repeat(' ', space) + + (Array.isArray(object) ? '' : '"' + i + '": ') + // key + _stringify(object[i]) + // value + (length ? ',' : ''); // comma + } + + return ( + str + + // [], {} + (str.length !== 1 ? '\n' + repeat(' ', --space) + end : end) + ); +} + +/** + * Return a new Thing that has the keys in sorted order. Recursive. + * + * If the Thing... + * - has already been seen, return string `'[Circular]'` + * - is `undefined`, return string `'[undefined]'` + * - is `null`, return value `null` + * - is some other primitive, return the value + * - is not a primitive or an `Array`, `Object`, or `Function`, return the value of the Thing's `toString()` method + * - is a non-empty `Array`, `Object`, or `Function`, return the result of calling this function again. + * - is an empty `Array`, `Object`, or `Function`, return the result of calling `emptyRepresentation()` + * + * @api private + * @see {@link exports.stringify} + * @param {*} value Thing to inspect. May or may not have properties. + * @param {Array} [stack=[]] Stack of seen values + * @param {string} [typeHint] Type hint + * @return {(Object|Array|Function|string|undefined)} + */ +exports.canonicalize = function canonicalize(value, stack, typeHint) { + var canonicalizedObj; + /* eslint-disable no-unused-vars */ + var prop; + /* eslint-enable no-unused-vars */ + typeHint = typeHint || type(value); + function withStack(value, fn) { + stack.push(value); + fn(); + stack.pop(); + } + + stack = stack || []; + + if (stack.indexOf(value) !== -1) { + return '[Circular]'; + } + + switch (typeHint) { + case 'undefined': + case 'buffer': + case 'null': + canonicalizedObj = value; + break; + case 'array': + withStack(value, function() { + canonicalizedObj = value.map(function(item) { + return exports.canonicalize(item, stack); + }); + }); + break; + case 'function': + /* eslint-disable guard-for-in */ + for (prop in value) { + canonicalizedObj = {}; + break; + } + /* eslint-enable guard-for-in */ + if (!canonicalizedObj) { + canonicalizedObj = emptyRepresentation(value, typeHint); + break; + } + /* falls through */ + case 'object': + canonicalizedObj = canonicalizedObj || {}; + withStack(value, function() { + Object.keys(value) + .sort() + .forEach(function(key) { + canonicalizedObj[key] = exports.canonicalize(value[key], stack); + }); + }); + break; + case 'date': + case 'number': + case 'regexp': + case 'boolean': + case 'symbol': + canonicalizedObj = value; + break; + default: + canonicalizedObj = value + ''; + } + + return canonicalizedObj; +}; + +/** + * Lookup file names at the given `path`. + * + * @memberof Mocha.utils + * @public + * @api public + * @param {string} filepath Base path to start searching from. + * @param {string[]} extensions File extensions to look for. + * @param {boolean} recursive Whether or not to recurse into subdirectories. + * @return {string[]} An array of paths. + */ +exports.lookupFiles = function lookupFiles(filepath, extensions, recursive) { + var files = []; + + if (!fs.existsSync(filepath)) { + if (fs.existsSync(filepath + '.js')) { + filepath += '.js'; + } else { + files = glob.sync(filepath); + if (!files.length) { + throw new Error("cannot resolve path (or pattern) '" + filepath + "'"); + } + return files; + } + } + + try { + var stat = fs.statSync(filepath); + if (stat.isFile()) { + return filepath; + } + } catch (err) { + // ignore error + return; + } + + fs.readdirSync(filepath).forEach(function(file) { + file = path.join(filepath, file); + try { + var stat = fs.statSync(file); + if (stat.isDirectory()) { + if (recursive) { + files = files.concat(lookupFiles(file, extensions, recursive)); + } + return; + } + } catch (err) { + // ignore error + return; + } + if (!extensions) { + throw new Error( + 'extensions parameter required when filepath is a directory' + ); + } + var re = new RegExp('\\.(?:' + extensions.join('|') + ')$'); + if (!stat.isFile() || !re.test(file) || path.basename(file)[0] === '.') { + return; + } + files.push(file); + }); + + return files; +}; + +/** + * Generate an undefined error with a message warning the user. + * + * @return {Error} + */ + +exports.undefinedError = function() { + return new Error( + 'Caught undefined error, did you throw without specifying what?' + ); +}; + +/** + * Generate an undefined error if `err` is not defined. + * + * @param {Error} err + * @return {Error} + */ + +exports.getError = function(err) { + return err || exports.undefinedError(); +}; + +/** + * @summary + * This Filter based on `mocha-clean` module.(see: `github.com/rstacruz/mocha-clean`) + * @description + * When invoking this function you get a filter function that get the Error.stack as an input, + * and return a prettify output. + * (i.e: strip Mocha and internal node functions from stack trace). + * @returns {Function} + */ +exports.stackTraceFilter = function() { + // TODO: Replace with `process.browser` + var is = typeof document === 'undefined' ? {node: true} : {browser: true}; + var slash = path.sep; + var cwd; + if (is.node) { + cwd = process.cwd() + slash; + } else { + cwd = (typeof location === 'undefined' + ? window.location + : location + ).href.replace(/\/[^/]*$/, '/'); + slash = '/'; + } + + function isMochaInternal(line) { + return ( + ~line.indexOf('node_modules' + slash + 'mocha' + slash) || + ~line.indexOf('node_modules' + slash + 'mocha.js') || + ~line.indexOf('bower_components' + slash + 'mocha.js') || + ~line.indexOf(slash + 'mocha.js') + ); + } + + function isNodeInternal(line) { + return ( + ~line.indexOf('(timers.js:') || + ~line.indexOf('(events.js:') || + ~line.indexOf('(node.js:') || + ~line.indexOf('(module.js:') || + ~line.indexOf('GeneratorFunctionPrototype.next (native)') || + false + ); + } + + return function(stack) { + stack = stack.split('\n'); + + stack = stack.reduce(function(list, line) { + if (isMochaInternal(line)) { + return list; + } + + if (is.node && isNodeInternal(line)) { + return list; + } + + // Clean up cwd(absolute) + if (/\(?.+:\d+:\d+\)?$/.test(line)) { + line = line.replace('(' + cwd, '('); + } + + list.push(line); + return list; + }, []); + + return stack.join('\n'); + }; +}; + +/** + * Crude, but effective. + * @api + * @param {*} value + * @returns {boolean} Whether or not `value` is a Promise + */ +exports.isPromise = function isPromise(value) { + return typeof value === 'object' && typeof value.then === 'function'; +}; + +/** + * It's a noop. + * @api + */ +exports.noop = function() {}; diff --git a/node_modules/mocha/mocha.css b/node_modules/mocha/mocha.css new file mode 100644 index 0000000..ec96b00 --- /dev/null +++ b/node_modules/mocha/mocha.css @@ -0,0 +1,326 @@ +@charset "utf-8"; + +body { + margin:0; +} + +#mocha { + font: 20px/1.5 "Helvetica Neue", Helvetica, Arial, sans-serif; + margin: 60px 50px; +} + +#mocha ul, +#mocha li { + margin: 0; + padding: 0; +} + +#mocha ul { + list-style: none; +} + +#mocha h1, +#mocha h2 { + margin: 0; +} + +#mocha h1 { + margin-top: 15px; + font-size: 1em; + font-weight: 200; +} + +#mocha h1 a { + text-decoration: none; + color: inherit; +} + +#mocha h1 a:hover { + text-decoration: underline; +} + +#mocha .suite .suite h1 { + margin-top: 0; + font-size: .8em; +} + +#mocha .hidden { + display: none; +} + +#mocha h2 { + font-size: 12px; + font-weight: normal; + cursor: pointer; +} + +#mocha .suite { + margin-left: 15px; +} + +#mocha .test { + margin-left: 15px; + overflow: hidden; +} + +#mocha .test.pending:hover h2::after { + content: '(pending)'; + font-family: arial, sans-serif; +} + +#mocha .test.pass.medium .duration { + background: #c09853; +} + +#mocha .test.pass.slow .duration { + background: #b94a48; +} + +#mocha .test.pass::before { + content: '✓'; + font-size: 12px; + display: block; + float: left; + margin-right: 5px; + color: #00d6b2; +} + +#mocha .test.pass .duration { + font-size: 9px; + margin-left: 5px; + padding: 2px 5px; + color: #fff; + -webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,.2); + -moz-box-shadow: inset 0 1px 1px rgba(0,0,0,.2); + box-shadow: inset 0 1px 1px rgba(0,0,0,.2); + -webkit-border-radius: 5px; + -moz-border-radius: 5px; + -ms-border-radius: 5px; + -o-border-radius: 5px; + border-radius: 5px; +} + +#mocha .test.pass.fast .duration { + display: none; +} + +#mocha .test.pending { + color: #0b97c4; +} + +#mocha .test.pending::before { + content: '◦'; + color: #0b97c4; +} + +#mocha .test.fail { + color: #c00; +} + +#mocha .test.fail pre { + color: black; +} + +#mocha .test.fail::before { + content: '✖'; + font-size: 12px; + display: block; + float: left; + margin-right: 5px; + color: #c00; +} + +#mocha .test pre.error { + color: #c00; + max-height: 300px; + overflow: auto; +} + +#mocha .test .html-error { + overflow: auto; + color: black; + line-height: 1.5; + display: block; + float: left; + clear: left; + font: 12px/1.5 monaco, monospace; + margin: 5px; + padding: 15px; + border: 1px solid #eee; + max-width: 85%; /*(1)*/ + max-width: -webkit-calc(100% - 42px); + max-width: -moz-calc(100% - 42px); + max-width: calc(100% - 42px); /*(2)*/ + max-height: 300px; + word-wrap: break-word; + border-bottom-color: #ddd; + -webkit-box-shadow: 0 1px 3px #eee; + -moz-box-shadow: 0 1px 3px #eee; + box-shadow: 0 1px 3px #eee; + -webkit-border-radius: 3px; + -moz-border-radius: 3px; + border-radius: 3px; +} + +#mocha .test .html-error pre.error { + border: none; + -webkit-border-radius: 0; + -moz-border-radius: 0; + border-radius: 0; + -webkit-box-shadow: 0; + -moz-box-shadow: 0; + box-shadow: 0; + padding: 0; + margin: 0; + margin-top: 18px; + max-height: none; +} + +/** + * (1): approximate for browsers not supporting calc + * (2): 42 = 2*15 + 2*10 + 2*1 (padding + margin + border) + * ^^ seriously + */ +#mocha .test pre { + display: block; + float: left; + clear: left; + font: 12px/1.5 monaco, monospace; + margin: 5px; + padding: 15px; + border: 1px solid #eee; + max-width: 85%; /*(1)*/ + max-width: -webkit-calc(100% - 42px); + max-width: -moz-calc(100% - 42px); + max-width: calc(100% - 42px); /*(2)*/ + word-wrap: break-word; + border-bottom-color: #ddd; + -webkit-box-shadow: 0 1px 3px #eee; + -moz-box-shadow: 0 1px 3px #eee; + box-shadow: 0 1px 3px #eee; + -webkit-border-radius: 3px; + -moz-border-radius: 3px; + border-radius: 3px; +} + +#mocha .test h2 { + position: relative; +} + +#mocha .test a.replay { + position: absolute; + top: 3px; + right: 0; + text-decoration: none; + vertical-align: middle; + display: block; + width: 15px; + height: 15px; + line-height: 15px; + text-align: center; + background: #eee; + font-size: 15px; + -webkit-border-radius: 15px; + -moz-border-radius: 15px; + border-radius: 15px; + -webkit-transition:opacity 200ms; + -moz-transition:opacity 200ms; + -o-transition:opacity 200ms; + transition: opacity 200ms; + opacity: 0.3; + color: #888; +} + +#mocha .test:hover a.replay { + opacity: 1; +} + +#mocha-report.pass .test.fail { + display: none; +} + +#mocha-report.fail .test.pass { + display: none; +} + +#mocha-report.pending .test.pass, +#mocha-report.pending .test.fail { + display: none; +} +#mocha-report.pending .test.pass.pending { + display: block; +} + +#mocha-error { + color: #c00; + font-size: 1.5em; + font-weight: 100; + letter-spacing: 1px; +} + +#mocha-stats { + position: fixed; + top: 15px; + right: 10px; + font-size: 12px; + margin: 0; + color: #888; + z-index: 1; +} + +#mocha-stats .progress { + float: right; + padding-top: 0; + + /** + * Set safe initial values, so mochas .progress does not inherit these + * properties from Bootstrap .progress (which causes .progress height to + * equal line height set in Bootstrap). + */ + height: auto; + -webkit-box-shadow: none; + -moz-box-shadow: none; + box-shadow: none; + background-color: initial; +} + +#mocha-stats em { + color: black; +} + +#mocha-stats a { + text-decoration: none; + color: inherit; +} + +#mocha-stats a:hover { + border-bottom: 1px solid #eee; +} + +#mocha-stats li { + display: inline-block; + margin: 0 5px; + list-style: none; + padding-top: 11px; +} + +#mocha-stats canvas { + width: 40px; + height: 40px; +} + +#mocha code .comment { color: #ddd; } +#mocha code .init { color: #2f6fad; } +#mocha code .string { color: #5890ad; } +#mocha code .keyword { color: #8a6343; } +#mocha code .number { color: #2f6fad; } + +@media screen and (max-device-width: 480px) { + #mocha { + margin: 60px 0px; + } + + #mocha #stats { + position: absolute; + } +} diff --git a/node_modules/mocha/mocha.js b/node_modules/mocha/mocha.js new file mode 100644 index 0000000..bfe8127 --- /dev/null +++ b/node_modules/mocha/mocha.js @@ -0,0 +1,16046 @@ +(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i 1) { + suites.shift(); + } + return common.suite.create({ + title: title, + file: file, + fn: false + }); + }; + + /** + * Exclusive Suite. + */ + + context.suite.only = function(title) { + if (suites.length > 1) { + suites.shift(); + } + return common.suite.only({ + title: title, + file: file, + fn: false + }); + }; + + /** + * Describe a specification or test-case + * with the given `title` and callback `fn` + * acting as a thunk. + */ + + context.test = function(title, fn) { + var test = new Test(title, fn); + test.file = file; + suites[0].addTest(test); + return test; + }; + + /** + * Exclusive test-case. + */ + + context.test.only = function(title, fn) { + return common.test.only(mocha, context.test(title, fn)); + }; + + context.test.skip = common.test.skip; + context.test.retries = common.test.retries; + }); +}; + +},{"../test":35,"./common":8}],12:[function(require,module,exports){ +'use strict'; + +var Test = require('../test'); + +/** + * TDD-style interface: + * + * suite('Array', function() { + * suite('#indexOf()', function() { + * suiteSetup(function() { + * + * }); + * + * test('should return -1 when not present', function() { + * + * }); + * + * test('should return the index when present', function() { + * + * }); + * + * suiteTeardown(function() { + * + * }); + * }); + * }); + * + * @param {Suite} suite Root suite. + */ +module.exports = function(suite) { + var suites = [suite]; + + suite.on('pre-require', function(context, file, mocha) { + var common = require('./common')(suites, context, mocha); + + context.setup = common.beforeEach; + context.teardown = common.afterEach; + context.suiteSetup = common.before; + context.suiteTeardown = common.after; + context.run = mocha.options.delay && common.runWithSuite(suite); + + /** + * Describe a "suite" with the given `title` and callback `fn` containing + * nested suites and/or tests. + */ + context.suite = function(title, fn) { + return common.suite.create({ + title: title, + file: file, + fn: fn + }); + }; + + /** + * Pending suite. + */ + context.suite.skip = function(title, fn) { + return common.suite.skip({ + title: title, + file: file, + fn: fn + }); + }; + + /** + * Exclusive test-case. + */ + context.suite.only = function(title, fn) { + return common.suite.only({ + title: title, + file: file, + fn: fn + }); + }; + + /** + * Describe a specification or test-case with the given `title` and + * callback `fn` acting as a thunk. + */ + context.test = function(title, fn) { + var suite = suites[0]; + if (suite.isPending()) { + fn = null; + } + var test = new Test(title, fn); + test.file = file; + suite.addTest(test); + return test; + }; + + /** + * Exclusive test-case. + */ + + context.test.only = function(title, fn) { + return common.test.only(mocha, context.test(title, fn)); + }; + + context.test.skip = common.test.skip; + context.test.retries = common.test.retries; + }); +}; + +},{"../test":35,"./common":8}],13:[function(require,module,exports){ +(function (process,global,__dirname){ +'use strict'; + +/*! + * mocha + * Copyright(c) 2011 TJ Holowaychuk + * MIT Licensed + */ + +var escapeRe = require('escape-string-regexp'); +var path = require('path'); +var reporters = require('./reporters'); +var utils = require('./utils'); + +exports = module.exports = Mocha; + +/** + * To require local UIs and reporters when running in node. + */ + +if (!process.browser) { + var cwd = process.cwd(); + module.paths.push(cwd, path.join(cwd, 'node_modules')); +} + +/** + * Expose internals. + */ + +/** + * @public + * @class utils + * @memberof Mocha + */ +exports.utils = utils; +exports.interfaces = require('./interfaces'); +/** + * + * @memberof Mocha + * @public + */ +exports.reporters = reporters; +exports.Runnable = require('./runnable'); +exports.Context = require('./context'); +/** + * + * @memberof Mocha + */ +exports.Runner = require('./runner'); +exports.Suite = require('./suite'); +exports.Hook = require('./hook'); +exports.Test = require('./test'); + +/** + * Return image `name` path. + * + * @private + * @param {string} name + * @return {string} + */ +function image(name) { + return path.join(__dirname, '..', 'assets', 'growl', name + '.png'); +} + +/** + * Set up mocha with `options`. + * + * Options: + * + * - `ui` name "bdd", "tdd", "exports" etc + * - `reporter` reporter instance, defaults to `mocha.reporters.spec` + * - `globals` array of accepted globals + * - `timeout` timeout in milliseconds + * - `retries` number of times to retry failed tests + * - `bail` bail on the first test failure + * - `slow` milliseconds to wait before considering a test slow + * - `ignoreLeaks` ignore global leaks + * - `fullTrace` display the full stack-trace on failing + * - `grep` string or regexp to filter tests with + * + * @class Mocha + * @param {Object} options + */ +function Mocha(options) { + options = options || {}; + this.files = []; + this.options = options; + if (options.grep) { + this.grep(new RegExp(options.grep)); + } + if (options.fgrep) { + this.fgrep(options.fgrep); + } + this.suite = new exports.Suite('', new exports.Context()); + this.ui(options.ui); + this.bail(options.bail); + this.reporter(options.reporter, options.reporterOptions); + if (typeof options.timeout !== 'undefined' && options.timeout !== null) { + this.timeout(options.timeout); + } + if (typeof options.retries !== 'undefined' && options.retries !== null) { + this.retries(options.retries); + } + this.useColors(options.useColors); + if (options.enableTimeouts !== null) { + this.enableTimeouts(options.enableTimeouts); + } + if (options.slow) { + this.slow(options.slow); + } +} + +/** + * Enable or disable bailing on the first failure. + * + * @public + * @api public + * @param {boolean} [bail] + */ +Mocha.prototype.bail = function(bail) { + if (!arguments.length) { + bail = true; + } + this.suite.bail(bail); + return this; +}; + +/** + * Add test `file`. + * + * @public + * @api public + * @param {string} file + */ +Mocha.prototype.addFile = function(file) { + this.files.push(file); + return this; +}; + +/** + * Set reporter to `reporter`, defaults to "spec". + * + * @public + * @param {String|Function} reporter name or constructor + * @param {Object} reporterOptions optional options + * @api public + * @param {string|Function} reporter name or constructor + * @param {Object} reporterOptions optional options + */ +Mocha.prototype.reporter = function(reporter, reporterOptions) { + if (typeof reporter === 'function') { + this._reporter = reporter; + } else { + reporter = reporter || 'spec'; + var _reporter; + // Try to load a built-in reporter. + if (reporters[reporter]) { + _reporter = reporters[reporter]; + } + // Try to load reporters from process.cwd() and node_modules + if (!_reporter) { + try { + _reporter = require(reporter); + } catch (err) { + if (err.message.indexOf('Cannot find module') !== -1) { + // Try to load reporters from a path (absolute or relative) + try { + _reporter = require(path.resolve(process.cwd(), reporter)); + } catch (_err) { + err.message.indexOf('Cannot find module') !== -1 + ? console.warn('"' + reporter + '" reporter not found') + : console.warn( + '"' + + reporter + + '" reporter blew up with error:\n' + + err.stack + ); + } + } else { + console.warn( + '"' + reporter + '" reporter blew up with error:\n' + err.stack + ); + } + } + } + if (!_reporter && reporter === 'teamcity') { + console.warn( + 'The Teamcity reporter was moved to a package named ' + + 'mocha-teamcity-reporter ' + + '(https://npmjs.org/package/mocha-teamcity-reporter).' + ); + } + if (!_reporter) { + throw new Error('invalid reporter "' + reporter + '"'); + } + this._reporter = _reporter; + } + this.options.reporterOptions = reporterOptions; + return this; +}; + +/** + * Set test UI `name`, defaults to "bdd". + * @public + * @api public + * @param {string} bdd + */ +Mocha.prototype.ui = function(name) { + name = name || 'bdd'; + this._ui = exports.interfaces[name]; + if (!this._ui) { + try { + this._ui = require(name); + } catch (err) { + throw new Error('invalid interface "' + name + '"'); + } + } + this._ui = this._ui(this.suite); + + this.suite.on('pre-require', function(context) { + exports.afterEach = context.afterEach || context.teardown; + exports.after = context.after || context.suiteTeardown; + exports.beforeEach = context.beforeEach || context.setup; + exports.before = context.before || context.suiteSetup; + exports.describe = context.describe || context.suite; + exports.it = context.it || context.test; + exports.xit = context.xit || context.test.skip; + exports.setup = context.setup || context.beforeEach; + exports.suiteSetup = context.suiteSetup || context.before; + exports.suiteTeardown = context.suiteTeardown || context.after; + exports.suite = context.suite || context.describe; + exports.teardown = context.teardown || context.afterEach; + exports.test = context.test || context.it; + exports.run = context.run; + }); + + return this; +}; + +/** + * Load registered files. + * + * @api private + */ +Mocha.prototype.loadFiles = function(fn) { + var self = this; + var suite = this.suite; + this.files.forEach(function(file) { + file = path.resolve(file); + suite.emit('pre-require', global, file, self); + suite.emit('require', require(file), file, self); + suite.emit('post-require', global, file, self); + }); + fn && fn(); +}; + +/** + * Enable growl support. + * + * @api private + */ +Mocha.prototype._growl = function(runner, reporter) { + var notify = require('growl'); + + runner.on('end', function() { + var stats = reporter.stats; + if (stats.failures) { + var msg = stats.failures + ' of ' + runner.total + ' tests failed'; + notify(msg, {name: 'mocha', title: 'Failed', image: image('error')}); + } else { + notify(stats.passes + ' tests passed in ' + stats.duration + 'ms', { + name: 'mocha', + title: 'Passed', + image: image('ok') + }); + } + }); +}; + +/** + * Escape string and add it to grep as a regexp. + * + * @public + * @api public + * @param str + * @returns {Mocha} + */ +Mocha.prototype.fgrep = function(str) { + return this.grep(new RegExp(escapeRe(str))); +}; + +/** + * Add regexp to grep, if `re` is a string it is escaped. + * + * @public + * @param {RegExp|String} re + * @return {Mocha} + * @api public + * @param {RegExp|string} re + * @return {Mocha} + */ +Mocha.prototype.grep = function(re) { + if (utils.isString(re)) { + // extract args if it's regex-like, i.e: [string, pattern, flag] + var arg = re.match(/^\/(.*)\/(g|i|)$|.*/); + this.options.grep = new RegExp(arg[1] || arg[0], arg[2]); + } else { + this.options.grep = re; + } + return this; +}; +/** + * Invert `.grep()` matches. + * + * @public + * @return {Mocha} + * @api public + */ +Mocha.prototype.invert = function() { + this.options.invert = true; + return this; +}; + +/** + * Ignore global leaks. + * + * @public + * @param {Boolean} ignore + * @return {Mocha} + * @api public + * @param {boolean} ignore + * @return {Mocha} + */ +Mocha.prototype.ignoreLeaks = function(ignore) { + this.options.ignoreLeaks = Boolean(ignore); + return this; +}; + +/** + * Enable global leak checking. + * + * @return {Mocha} + * @api public + * @public + */ +Mocha.prototype.checkLeaks = function() { + this.options.ignoreLeaks = false; + return this; +}; + +/** + * Display long stack-trace on failing + * + * @return {Mocha} + * @api public + * @public + */ +Mocha.prototype.fullTrace = function() { + this.options.fullStackTrace = true; + return this; +}; + +/** + * Enable growl support. + * + * @return {Mocha} + * @api public + * @public + */ +Mocha.prototype.growl = function() { + this.options.growl = true; + return this; +}; + +/** + * Ignore `globals` array or string. + * + * @param {Array|String} globals + * @return {Mocha} + * @api public + * @public + * @param {Array|string} globals + * @return {Mocha} + */ +Mocha.prototype.globals = function(globals) { + this.options.globals = (this.options.globals || []).concat(globals); + return this; +}; + +/** + * Emit color output. + * + * @param {Boolean} colors + * @return {Mocha} + * @api public + * @public + * @param {boolean} colors + * @return {Mocha} + */ +Mocha.prototype.useColors = function(colors) { + if (colors !== undefined) { + this.options.useColors = colors; + } + return this; +}; + +/** + * Use inline diffs rather than +/-. + * + * @param {Boolean} inlineDiffs + * @return {Mocha} + * @api public + * @public + * @param {boolean} inlineDiffs + * @return {Mocha} + */ +Mocha.prototype.useInlineDiffs = function(inlineDiffs) { + this.options.useInlineDiffs = inlineDiffs !== undefined && inlineDiffs; + return this; +}; + +/** + * Do not show diffs at all. + * + * @param {Boolean} hideDiff + * @return {Mocha} + * @api public + * @public + * @param {boolean} hideDiff + * @return {Mocha} + */ +Mocha.prototype.hideDiff = function(hideDiff) { + this.options.hideDiff = hideDiff !== undefined && hideDiff; + return this; +}; + +/** + * Set the timeout in milliseconds. + * + * @param {Number} timeout + * @return {Mocha} + * @api public + * @public + * @param {number} timeout + * @return {Mocha} + */ +Mocha.prototype.timeout = function(timeout) { + this.suite.timeout(timeout); + return this; +}; + +/** + * Set the number of times to retry failed tests. + * + * @param {Number} retry times + * @return {Mocha} + * @api public + * @public + */ +Mocha.prototype.retries = function(n) { + this.suite.retries(n); + return this; +}; + +/** + * Set slowness threshold in milliseconds. + * + * @param {Number} slow + * @return {Mocha} + * @api public + * @public + * @param {number} slow + * @return {Mocha} + */ +Mocha.prototype.slow = function(slow) { + this.suite.slow(slow); + return this; +}; + +/** + * Enable timeouts. + * + * @param {Boolean} enabled + * @return {Mocha} + * @api public + * @public + * @param {boolean} enabled + * @return {Mocha} + */ +Mocha.prototype.enableTimeouts = function(enabled) { + this.suite.enableTimeouts( + arguments.length && enabled !== undefined ? enabled : true + ); + return this; +}; + +/** + * Makes all tests async (accepting a callback) + * + * @return {Mocha} + * @api public + * @public + */ +Mocha.prototype.asyncOnly = function() { + this.options.asyncOnly = true; + return this; +}; + +/** + * Disable syntax highlighting (in browser). + * + * @api public + * @public + */ +Mocha.prototype.noHighlighting = function() { + this.options.noHighlighting = true; + return this; +}; + +/** + * Enable uncaught errors to propagate (in browser). + * + * @return {Mocha} + * @api public + * @public + */ +Mocha.prototype.allowUncaught = function() { + this.options.allowUncaught = true; + return this; +}; + +/** + * Delay root suite execution. + * @returns {Mocha} + */ +Mocha.prototype.delay = function delay() { + this.options.delay = true; + return this; +}; + +/** + * Tests marked only fail the suite + * @returns {Mocha} + */ +Mocha.prototype.forbidOnly = function() { + this.options.forbidOnly = true; + return this; +}; + +/** + * Pending tests and tests marked skip fail the suite + * @returns {Mocha} + */ +Mocha.prototype.forbidPending = function() { + this.options.forbidPending = true; + return this; +}; + +/** + * Run tests and invoke `fn()` when complete. + * + * Note that `loadFiles` relies on Node's `require` to execute + * the test interface functions and will be subject to the + * cache - if the files are already in the `require` cache, + * they will effectively be skipped. Therefore, to run tests + * multiple times or to run tests in files that are already + * in the `require` cache, make sure to clear them from the + * cache first in whichever manner best suits your needs. + * + * @api public + * @public + * @param {Function} fn + * @return {Runner} + */ +Mocha.prototype.run = function(fn) { + if (this.files.length) { + this.loadFiles(); + } + var suite = this.suite; + var options = this.options; + options.files = this.files; + var runner = new exports.Runner(suite, options.delay); + var reporter = new this._reporter(runner, options); + runner.ignoreLeaks = options.ignoreLeaks !== false; + runner.fullStackTrace = options.fullStackTrace; + runner.asyncOnly = options.asyncOnly; + runner.allowUncaught = options.allowUncaught; + runner.forbidOnly = options.forbidOnly; + runner.forbidPending = options.forbidPending; + if (options.grep) { + runner.grep(options.grep, options.invert); + } + if (options.globals) { + runner.globals(options.globals); + } + if (options.growl) { + this._growl(runner, reporter); + } + if (options.useColors !== undefined) { + exports.reporters.Base.useColors = options.useColors; + } + exports.reporters.Base.inlineDiffs = options.useInlineDiffs; + exports.reporters.Base.hideDiff = options.hideDiff; + + function done(failures) { + if (reporter.done) { + reporter.done(failures, fn); + } else { + fn && fn(failures); + } + } + + return runner.run(done); +}; + +}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},"/lib") +},{"./context":5,"./hook":6,"./interfaces":10,"./reporters":20,"./runnable":32,"./runner":33,"./suite":34,"./test":35,"./utils":36,"_process":56,"escape-string-regexp":46,"growl":2,"path":40}],14:[function(require,module,exports){ +'use strict'; +/** + * @module milliseconds + */ +/** + * Helpers. + */ + +var s = 1000; +var m = s * 60; +var h = m * 60; +var d = h * 24; +var y = d * 365.25; + +/** + * Parse or format the given `val`. + * + * @memberof Mocha + * @public + * @api public + * @param {string|number} val + * @return {string|number} + */ +module.exports = function(val) { + if (typeof val === 'string') { + return parse(val); + } + return format(val); +}; + +/** + * Parse the given `str` and return milliseconds. + * + * @api private + * @param {string} str + * @return {number} + */ +function parse(str) { + var match = /^((?:\d+)?\.?\d+) *(ms|seconds?|s|minutes?|m|hours?|h|days?|d|years?|y)?$/i.exec( + str + ); + if (!match) { + return; + } + var n = parseFloat(match[1]); + var type = (match[2] || 'ms').toLowerCase(); + switch (type) { + case 'years': + case 'year': + case 'y': + return n * y; + case 'days': + case 'day': + case 'd': + return n * d; + case 'hours': + case 'hour': + case 'h': + return n * h; + case 'minutes': + case 'minute': + case 'm': + return n * m; + case 'seconds': + case 'second': + case 's': + return n * s; + case 'ms': + return n; + default: + // No default case + } +} + +/** + * Format for `ms`. + * + * @api private + * @param {number} ms + * @return {string} + */ +function format(ms) { + if (ms >= d) { + return Math.round(ms / d) + 'd'; + } + if (ms >= h) { + return Math.round(ms / h) + 'h'; + } + if (ms >= m) { + return Math.round(ms / m) + 'm'; + } + if (ms >= s) { + return Math.round(ms / s) + 's'; + } + return ms + 'ms'; +} + +},{}],15:[function(require,module,exports){ +'use strict'; + +module.exports = Pending; + +/** + * Initialize a new `Pending` error with the given message. + * + * @param {string} message + */ +function Pending(message) { + this.message = message; +} + +},{}],16:[function(require,module,exports){ +(function (process,global){ +'use strict'; +/** + * @module Base + */ +/** + * Module dependencies. + */ + +var tty = require('tty'); +var diff = require('diff'); +var ms = require('../ms'); +var utils = require('../utils'); +var supportsColor = process.browser ? null : require('supports-color'); + +/** + * Expose `Base`. + */ + +exports = module.exports = Base; + +/** + * Save timer references to avoid Sinon interfering. + * See: https://github.com/mochajs/mocha/issues/237 + */ + +/* eslint-disable no-unused-vars, no-native-reassign */ +var Date = global.Date; +var setTimeout = global.setTimeout; +var setInterval = global.setInterval; +var clearTimeout = global.clearTimeout; +var clearInterval = global.clearInterval; +/* eslint-enable no-unused-vars, no-native-reassign */ + +/** + * Check if both stdio streams are associated with a tty. + */ + +var isatty = tty.isatty(1) && tty.isatty(2); + +/** + * Enable coloring by default, except in the browser interface. + */ + +exports.useColors = + !process.browser && + (supportsColor.stdout || process.env.MOCHA_COLORS !== undefined); + +/** + * Inline diffs instead of +/- + */ + +exports.inlineDiffs = false; + +/** + * Default color map. + */ + +exports.colors = { + pass: 90, + fail: 31, + 'bright pass': 92, + 'bright fail': 91, + 'bright yellow': 93, + pending: 36, + suite: 0, + 'error title': 0, + 'error message': 31, + 'error stack': 90, + checkmark: 32, + fast: 90, + medium: 33, + slow: 31, + green: 32, + light: 90, + 'diff gutter': 90, + 'diff added': 32, + 'diff removed': 31 +}; + +/** + * Default symbol map. + */ + +exports.symbols = { + ok: '✓', + err: '✖', + dot: '․', + comma: ',', + bang: '!' +}; + +// With node.js on Windows: use symbols available in terminal default fonts +if (process.platform === 'win32') { + exports.symbols.ok = '\u221A'; + exports.symbols.err = '\u00D7'; + exports.symbols.dot = '.'; +} + +/** + * Color `str` with the given `type`, + * allowing colors to be disabled, + * as well as user-defined color + * schemes. + * + * @param {string} type + * @param {string} str + * @return {string} + * @api private + */ +var color = (exports.color = function(type, str) { + if (!exports.useColors) { + return String(str); + } + return '\u001b[' + exports.colors[type] + 'm' + str + '\u001b[0m'; +}); + +/** + * Expose term window size, with some defaults for when stderr is not a tty. + */ + +exports.window = { + width: 75 +}; + +if (isatty) { + exports.window.width = process.stdout.getWindowSize + ? process.stdout.getWindowSize(1)[0] + : tty.getWindowSize()[1]; +} + +/** + * Expose some basic cursor interactions that are common among reporters. + */ + +exports.cursor = { + hide: function() { + isatty && process.stdout.write('\u001b[?25l'); + }, + + show: function() { + isatty && process.stdout.write('\u001b[?25h'); + }, + + deleteLine: function() { + isatty && process.stdout.write('\u001b[2K'); + }, + + beginningOfLine: function() { + isatty && process.stdout.write('\u001b[0G'); + }, + + CR: function() { + if (isatty) { + exports.cursor.deleteLine(); + exports.cursor.beginningOfLine(); + } else { + process.stdout.write('\r'); + } + } +}; + +function showDiff(err) { + return ( + err && + err.showDiff !== false && + sameType(err.actual, err.expected) && + err.expected !== undefined + ); +} + +function stringifyDiffObjs(err) { + if (!utils.isString(err.actual) || !utils.isString(err.expected)) { + err.actual = utils.stringify(err.actual); + err.expected = utils.stringify(err.expected); + } +} + +/** + * Returns a diff between 2 strings with coloured ANSI output. + * + * The diff will be either inline or unified dependant on the value + * of `Base.inlineDiff`. + * + * @param {string} actual + * @param {string} expected + * @return {string} Diff + */ +var generateDiff = (exports.generateDiff = function(actual, expected) { + return exports.inlineDiffs + ? inlineDiff(actual, expected) + : unifiedDiff(actual, expected); +}); + +/** + * Output the given `failures` as a list. + * + * @public + * @memberof Mocha.reporters.Base + * @variation 1 + * @param {Array} failures + * @api public + */ + +exports.list = function(failures) { + console.log(); + failures.forEach(function(test, i) { + // format + var fmt = + color('error title', ' %s) %s:\n') + + color('error message', ' %s') + + color('error stack', '\n%s\n'); + + // msg + var msg; + var err = test.err; + var message; + if (err.message && typeof err.message.toString === 'function') { + message = err.message + ''; + } else if (typeof err.inspect === 'function') { + message = err.inspect() + ''; + } else { + message = ''; + } + var stack = err.stack || message; + var index = message ? stack.indexOf(message) : -1; + + if (index === -1) { + msg = message; + } else { + index += message.length; + msg = stack.slice(0, index); + // remove msg from stack + stack = stack.slice(index + 1); + } + + // uncaught + if (err.uncaught) { + msg = 'Uncaught ' + msg; + } + // explicitly show diff + if (!exports.hideDiff && showDiff(err)) { + stringifyDiffObjs(err); + fmt = + color('error title', ' %s) %s:\n%s') + color('error stack', '\n%s\n'); + var match = message.match(/^([^:]+): expected/); + msg = '\n ' + color('error message', match ? match[1] : msg); + + msg += generateDiff(err.actual, err.expected); + } + + // indent stack trace + stack = stack.replace(/^/gm, ' '); + + // indented test title + var testTitle = ''; + test.titlePath().forEach(function(str, index) { + if (index !== 0) { + testTitle += '\n '; + } + for (var i = 0; i < index; i++) { + testTitle += ' '; + } + testTitle += str; + }); + + console.log(fmt, i + 1, testTitle, msg, stack); + }); +}; + +/** + * Initialize a new `Base` reporter. + * + * All other reporters generally + * inherit from this reporter, providing + * stats such as test duration, number + * of tests passed / failed etc. + * + * @memberof Mocha.reporters + * @public + * @class + * @param {Runner} runner + * @api public + */ + +function Base(runner) { + var stats = (this.stats = { + suites: 0, + tests: 0, + passes: 0, + pending: 0, + failures: 0 + }); + var failures = (this.failures = []); + + if (!runner) { + return; + } + this.runner = runner; + + runner.stats = stats; + + runner.on('start', function() { + stats.start = new Date(); + }); + + runner.on('suite', function(suite) { + stats.suites = stats.suites || 0; + suite.root || stats.suites++; + }); + + runner.on('test end', function() { + stats.tests = stats.tests || 0; + stats.tests++; + }); + + runner.on('pass', function(test) { + stats.passes = stats.passes || 0; + + if (test.duration > test.slow()) { + test.speed = 'slow'; + } else if (test.duration > test.slow() / 2) { + test.speed = 'medium'; + } else { + test.speed = 'fast'; + } + + stats.passes++; + }); + + runner.on('fail', function(test, err) { + stats.failures = stats.failures || 0; + stats.failures++; + if (showDiff(err)) { + stringifyDiffObjs(err); + } + test.err = err; + failures.push(test); + }); + + runner.once('end', function() { + stats.end = new Date(); + stats.duration = stats.end - stats.start; + }); + + runner.on('pending', function() { + stats.pending++; + }); +} + +/** + * Output common epilogue used by many of + * the bundled reporters. + * + * @memberof Mocha.reporters.Base + * @public + * @api public + */ +Base.prototype.epilogue = function() { + var stats = this.stats; + var fmt; + + console.log(); + + // passes + fmt = + color('bright pass', ' ') + + color('green', ' %d passing') + + color('light', ' (%s)'); + + console.log(fmt, stats.passes || 0, ms(stats.duration)); + + // pending + if (stats.pending) { + fmt = color('pending', ' ') + color('pending', ' %d pending'); + + console.log(fmt, stats.pending); + } + + // failures + if (stats.failures) { + fmt = color('fail', ' %d failing'); + + console.log(fmt, stats.failures); + + Base.list(this.failures); + console.log(); + } + + console.log(); +}; + +/** + * Pad the given `str` to `len`. + * + * @api private + * @param {string} str + * @param {string} len + * @return {string} + */ +function pad(str, len) { + str = String(str); + return Array(len - str.length + 1).join(' ') + str; +} + +/** + * Returns an inline diff between 2 strings with coloured ANSI output. + * + * @api private + * @param {String} actual + * @param {String} expected + * @return {string} Diff + */ +function inlineDiff(actual, expected) { + var msg = errorDiff(actual, expected); + + // linenos + var lines = msg.split('\n'); + if (lines.length > 4) { + var width = String(lines.length).length; + msg = lines + .map(function(str, i) { + return pad(++i, width) + ' |' + ' ' + str; + }) + .join('\n'); + } + + // legend + msg = + '\n' + + color('diff removed', 'actual') + + ' ' + + color('diff added', 'expected') + + '\n\n' + + msg + + '\n'; + + // indent + msg = msg.replace(/^/gm, ' '); + return msg; +} + +/** + * Returns a unified diff between two strings with coloured ANSI output. + * + * @api private + * @param {String} actual + * @param {String} expected + * @return {string} The diff. + */ +function unifiedDiff(actual, expected) { + var indent = ' '; + function cleanUp(line) { + if (line[0] === '+') { + return indent + colorLines('diff added', line); + } + if (line[0] === '-') { + return indent + colorLines('diff removed', line); + } + if (line.match(/@@/)) { + return '--'; + } + if (line.match(/\\ No newline/)) { + return null; + } + return indent + line; + } + function notBlank(line) { + return typeof line !== 'undefined' && line !== null; + } + var msg = diff.createPatch('string', actual, expected); + var lines = msg.split('\n').splice(5); + return ( + '\n ' + + colorLines('diff added', '+ expected') + + ' ' + + colorLines('diff removed', '- actual') + + '\n\n' + + lines + .map(cleanUp) + .filter(notBlank) + .join('\n') + ); +} + +/** + * Return a character diff for `err`. + * + * @api private + * @param {String} actual + * @param {String} expected + * @return {string} the diff + */ +function errorDiff(actual, expected) { + return diff + .diffWordsWithSpace(actual, expected) + .map(function(str) { + if (str.added) { + return colorLines('diff added', str.value); + } + if (str.removed) { + return colorLines('diff removed', str.value); + } + return str.value; + }) + .join(''); +} + +/** + * Color lines for `str`, using the color `name`. + * + * @api private + * @param {string} name + * @param {string} str + * @return {string} + */ +function colorLines(name, str) { + return str + .split('\n') + .map(function(str) { + return color(name, str); + }) + .join('\n'); +} + +/** + * Object#toString reference. + */ +var objToString = Object.prototype.toString; + +/** + * Check that a / b have the same type. + * + * @api private + * @param {Object} a + * @param {Object} b + * @return {boolean} + */ +function sameType(a, b) { + return objToString.call(a) === objToString.call(b); +} + +}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"../ms":14,"../utils":36,"_process":56,"diff":45,"supports-color":40,"tty":4}],17:[function(require,module,exports){ +'use strict'; +/** + * @module Doc + */ +/** + * Module dependencies. + */ + +var Base = require('./base'); +var utils = require('../utils'); + +/** + * Expose `Doc`. + */ + +exports = module.exports = Doc; + +/** + * Initialize a new `Doc` reporter. + * + * @class + * @memberof Mocha.reporters + * @extends {Base} + * @public + * @param {Runner} runner + * @api public + */ +function Doc(runner) { + Base.call(this, runner); + + var indents = 2; + + function indent() { + return Array(indents).join(' '); + } + + runner.on('suite', function(suite) { + if (suite.root) { + return; + } + ++indents; + console.log('%s
    ', indent()); + ++indents; + console.log('%s

    %s

    ', indent(), utils.escape(suite.title)); + console.log('%s
    ', indent()); + }); + + runner.on('suite end', function(suite) { + if (suite.root) { + return; + } + console.log('%s
    ', indent()); + --indents; + console.log('%s
    ', indent()); + --indents; + }); + + runner.on('pass', function(test) { + console.log('%s
    %s
    ', indent(), utils.escape(test.title)); + var code = utils.escape(utils.clean(test.body)); + console.log('%s
    %s
    ', indent(), code); + }); + + runner.on('fail', function(test, err) { + console.log( + '%s
    %s
    ', + indent(), + utils.escape(test.title) + ); + var code = utils.escape(utils.clean(test.body)); + console.log( + '%s
    %s
    ', + indent(), + code + ); + console.log('%s
    %s
    ', indent(), utils.escape(err)); + }); +} + +},{"../utils":36,"./base":16}],18:[function(require,module,exports){ +(function (process){ +'use strict'; +/** + * @module Dot + */ +/** + * Module dependencies. + */ + +var Base = require('./base'); +var inherits = require('../utils').inherits; +var color = Base.color; + +/** + * Expose `Dot`. + */ + +exports = module.exports = Dot; + +/** + * Initialize a new `Dot` matrix test reporter. + * + * @class + * @memberof Mocha.reporters + * @extends Mocha.reporters.Base + * @public + * @api public + * @param {Runner} runner + */ +function Dot(runner) { + Base.call(this, runner); + + var self = this; + var width = (Base.window.width * 0.75) | 0; + var n = -1; + + runner.on('start', function() { + process.stdout.write('\n'); + }); + + runner.on('pending', function() { + if (++n % width === 0) { + process.stdout.write('\n '); + } + process.stdout.write(color('pending', Base.symbols.comma)); + }); + + runner.on('pass', function(test) { + if (++n % width === 0) { + process.stdout.write('\n '); + } + if (test.speed === 'slow') { + process.stdout.write(color('bright yellow', Base.symbols.dot)); + } else { + process.stdout.write(color(test.speed, Base.symbols.dot)); + } + }); + + runner.on('fail', function() { + if (++n % width === 0) { + process.stdout.write('\n '); + } + process.stdout.write(color('fail', Base.symbols.bang)); + }); + + runner.once('end', function() { + console.log(); + self.epilogue(); + }); +} + +/** + * Inherit from `Base.prototype`. + */ +inherits(Dot, Base); + +}).call(this,require('_process')) +},{"../utils":36,"./base":16,"_process":56}],19:[function(require,module,exports){ +(function (global){ +'use strict'; + +/* eslint-env browser */ +/** + * @module HTML + */ +/** + * Module dependencies. + */ + +var Base = require('./base'); +var utils = require('../utils'); +var Progress = require('../browser/progress'); +var escapeRe = require('escape-string-regexp'); +var escape = utils.escape; + +/** + * Save timer references to avoid Sinon interfering (see GH-237). + */ + +/* eslint-disable no-unused-vars, no-native-reassign */ +var Date = global.Date; +var setTimeout = global.setTimeout; +var setInterval = global.setInterval; +var clearTimeout = global.clearTimeout; +var clearInterval = global.clearInterval; +/* eslint-enable no-unused-vars, no-native-reassign */ + +/** + * Expose `HTML`. + */ + +exports = module.exports = HTML; + +/** + * Stats template. + */ + +var statsTemplate = + ''; + +var playIcon = '‣'; + +/** + * Initialize a new `HTML` reporter. + * + * @public + * @class + * @memberof Mocha.reporters + * @extends Mocha.reporters.Base + * @api public + * @param {Runner} runner + */ +function HTML(runner) { + Base.call(this, runner); + + var self = this; + var stats = this.stats; + var stat = fragment(statsTemplate); + var items = stat.getElementsByTagName('li'); + var passes = items[1].getElementsByTagName('em')[0]; + var passesLink = items[1].getElementsByTagName('a')[0]; + var failures = items[2].getElementsByTagName('em')[0]; + var failuresLink = items[2].getElementsByTagName('a')[0]; + var duration = items[3].getElementsByTagName('em')[0]; + var canvas = stat.getElementsByTagName('canvas')[0]; + var report = fragment('
      '); + var stack = [report]; + var progress; + var ctx; + var root = document.getElementById('mocha'); + + if (canvas.getContext) { + var ratio = window.devicePixelRatio || 1; + canvas.style.width = canvas.width; + canvas.style.height = canvas.height; + canvas.width *= ratio; + canvas.height *= ratio; + ctx = canvas.getContext('2d'); + ctx.scale(ratio, ratio); + progress = new Progress(); + } + + if (!root) { + return error('#mocha div missing, add it to your document'); + } + + // pass toggle + on(passesLink, 'click', function(evt) { + evt.preventDefault(); + unhide(); + var name = /pass/.test(report.className) ? '' : ' pass'; + report.className = report.className.replace(/fail|pass/g, '') + name; + if (report.className.trim()) { + hideSuitesWithout('test pass'); + } + }); + + // failure toggle + on(failuresLink, 'click', function(evt) { + evt.preventDefault(); + unhide(); + var name = /fail/.test(report.className) ? '' : ' fail'; + report.className = report.className.replace(/fail|pass/g, '') + name; + if (report.className.trim()) { + hideSuitesWithout('test fail'); + } + }); + + root.appendChild(stat); + root.appendChild(report); + + if (progress) { + progress.size(40); + } + + runner.on('suite', function(suite) { + if (suite.root) { + return; + } + + // suite + var url = self.suiteURL(suite); + var el = fragment( + '
    • %s

    • ', + url, + escape(suite.title) + ); + + // container + stack[0].appendChild(el); + stack.unshift(document.createElement('ul')); + el.appendChild(stack[0]); + }); + + runner.on('suite end', function(suite) { + if (suite.root) { + updateStats(); + return; + } + stack.shift(); + }); + + runner.on('pass', function(test) { + var url = self.testURL(test); + var markup = + '
    • %e%ems ' + + '' + + playIcon + + '

    • '; + var el = fragment(markup, test.speed, test.title, test.duration, url); + self.addCodeToggle(el, test.body); + appendToStack(el); + updateStats(); + }); + + runner.on('fail', function(test) { + var el = fragment( + '
    • %e ' + + playIcon + + '

    • ', + test.title, + self.testURL(test) + ); + var stackString; // Note: Includes leading newline + var message = test.err.toString(); + + // <=IE7 stringifies to [Object Error]. Since it can be overloaded, we + // check for the result of the stringifying. + if (message === '[object Error]') { + message = test.err.message; + } + + if (test.err.stack) { + var indexOfMessage = test.err.stack.indexOf(test.err.message); + if (indexOfMessage === -1) { + stackString = test.err.stack; + } else { + stackString = test.err.stack.substr( + test.err.message.length + indexOfMessage + ); + } + } else if (test.err.sourceURL && test.err.line !== undefined) { + // Safari doesn't give you a stack. Let's at least provide a source line. + stackString = '\n(' + test.err.sourceURL + ':' + test.err.line + ')'; + } + + stackString = stackString || ''; + + if (test.err.htmlMessage && stackString) { + el.appendChild( + fragment( + '
      %s\n
      %e
      ', + test.err.htmlMessage, + stackString + ) + ); + } else if (test.err.htmlMessage) { + el.appendChild( + fragment('
      %s
      ', test.err.htmlMessage) + ); + } else { + el.appendChild( + fragment('
      %e%e
      ', message, stackString) + ); + } + + self.addCodeToggle(el, test.body); + appendToStack(el); + updateStats(); + }); + + runner.on('pending', function(test) { + var el = fragment( + '
    • %e

    • ', + test.title + ); + appendToStack(el); + updateStats(); + }); + + function appendToStack(el) { + // Don't call .appendChild if #mocha-report was already .shift()'ed off the stack. + if (stack[0]) { + stack[0].appendChild(el); + } + } + + function updateStats() { + // TODO: add to stats + var percent = (stats.tests / runner.total * 100) | 0; + if (progress) { + progress.update(percent).draw(ctx); + } + + // update stats + var ms = new Date() - stats.start; + text(passes, stats.passes); + text(failures, stats.failures); + text(duration, (ms / 1000).toFixed(2)); + } +} + +/** + * Makes a URL, preserving querystring ("search") parameters. + * + * @param {string} s + * @return {string} A new URL. + */ +function makeUrl(s) { + var search = window.location.search; + + // Remove previous grep query parameter if present + if (search) { + search = search.replace(/[?&]grep=[^&\s]*/g, '').replace(/^&/, '?'); + } + + return ( + window.location.pathname + + (search ? search + '&' : '?') + + 'grep=' + + encodeURIComponent(escapeRe(s)) + ); +} + +/** + * Provide suite URL. + * + * @param {Object} [suite] + */ +HTML.prototype.suiteURL = function(suite) { + return makeUrl(suite.fullTitle()); +}; + +/** + * Provide test URL. + * + * @param {Object} [test] + */ +HTML.prototype.testURL = function(test) { + return makeUrl(test.fullTitle()); +}; + +/** + * Adds code toggle functionality for the provided test's list element. + * + * @param {HTMLLIElement} el + * @param {string} contents + */ +HTML.prototype.addCodeToggle = function(el, contents) { + var h2 = el.getElementsByTagName('h2')[0]; + + on(h2, 'click', function() { + pre.style.display = pre.style.display === 'none' ? 'block' : 'none'; + }); + + var pre = fragment('
      %e
      ', utils.clean(contents)); + el.appendChild(pre); + pre.style.display = 'none'; +}; + +/** + * Display error `msg`. + * + * @param {string} msg + */ +function error(msg) { + document.body.appendChild(fragment('
      %s
      ', msg)); +} + +/** + * Return a DOM fragment from `html`. + * + * @param {string} html + */ +function fragment(html) { + var args = arguments; + var div = document.createElement('div'); + var i = 1; + + div.innerHTML = html.replace(/%([se])/g, function(_, type) { + switch (type) { + case 's': + return String(args[i++]); + case 'e': + return escape(args[i++]); + // no default + } + }); + + return div.firstChild; +} + +/** + * Check for suites that do not have elements + * with `classname`, and hide them. + * + * @param {text} classname + */ +function hideSuitesWithout(classname) { + var suites = document.getElementsByClassName('suite'); + for (var i = 0; i < suites.length; i++) { + var els = suites[i].getElementsByClassName(classname); + if (!els.length) { + suites[i].className += ' hidden'; + } + } +} + +/** + * Unhide .hidden suites. + */ +function unhide() { + var els = document.getElementsByClassName('suite hidden'); + for (var i = 0; i < els.length; ++i) { + els[i].className = els[i].className.replace('suite hidden', 'suite'); + } +} + +/** + * Set an element's text contents. + * + * @param {HTMLElement} el + * @param {string} contents + */ +function text(el, contents) { + if (el.textContent) { + el.textContent = contents; + } else { + el.innerText = contents; + } +} + +/** + * Listen on `event` with callback `fn`. + */ +function on(el, event, fn) { + if (el.addEventListener) { + el.addEventListener(event, fn, false); + } else { + el.attachEvent('on' + event, fn); + } +} + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"../browser/progress":3,"../utils":36,"./base":16,"escape-string-regexp":46}],20:[function(require,module,exports){ +'use strict'; + +// Alias exports to a their normalized format Mocha#reporter to prevent a need +// for dynamic (try/catch) requires, which Browserify doesn't handle. +exports.Base = exports.base = require('./base'); +exports.Dot = exports.dot = require('./dot'); +exports.Doc = exports.doc = require('./doc'); +exports.TAP = exports.tap = require('./tap'); +exports.JSON = exports.json = require('./json'); +exports.HTML = exports.html = require('./html'); +exports.List = exports.list = require('./list'); +exports.Min = exports.min = require('./min'); +exports.Spec = exports.spec = require('./spec'); +exports.Nyan = exports.nyan = require('./nyan'); +exports.XUnit = exports.xunit = require('./xunit'); +exports.Markdown = exports.markdown = require('./markdown'); +exports.Progress = exports.progress = require('./progress'); +exports.Landing = exports.landing = require('./landing'); +exports.JSONStream = exports['json-stream'] = require('./json-stream'); + +},{"./base":16,"./doc":17,"./dot":18,"./html":19,"./json":22,"./json-stream":21,"./landing":23,"./list":24,"./markdown":25,"./min":26,"./nyan":27,"./progress":28,"./spec":29,"./tap":30,"./xunit":31}],21:[function(require,module,exports){ +(function (process){ +'use strict'; +/** + * @module JSONStream + */ +/** + * Module dependencies. + */ + +var Base = require('./base'); + +/** + * Expose `List`. + */ + +exports = module.exports = List; + +/** + * Initialize a new `JSONStream` test reporter. + * + * @public + * @name JSONStream + * @class JSONStream + * @memberof Mocha.reporters + * @extends Mocha.reporters.Base + * @api public + * @param {Runner} runner + */ +function List(runner) { + Base.call(this, runner); + + var self = this; + var total = runner.total; + + runner.on('start', function() { + console.log(JSON.stringify(['start', {total: total}])); + }); + + runner.on('pass', function(test) { + console.log(JSON.stringify(['pass', clean(test)])); + }); + + runner.on('fail', function(test, err) { + test = clean(test); + test.err = err.message; + test.stack = err.stack || null; + console.log(JSON.stringify(['fail', test])); + }); + + runner.once('end', function() { + process.stdout.write(JSON.stringify(['end', self.stats])); + }); +} + +/** + * Return a plain-object representation of `test` + * free of cyclic properties etc. + * + * @api private + * @param {Object} test + * @return {Object} + */ +function clean(test) { + return { + title: test.title, + fullTitle: test.fullTitle(), + duration: test.duration, + currentRetry: test.currentRetry() + }; +} + +}).call(this,require('_process')) +},{"./base":16,"_process":56}],22:[function(require,module,exports){ +(function (process){ +'use strict'; +/** + * @module JSON + */ +/** + * Module dependencies. + */ + +var Base = require('./base'); + +/** + * Expose `JSON`. + */ + +exports = module.exports = JSONReporter; + +/** + * Initialize a new `JSON` reporter. + * + * @public + * @class JSON + * @memberof Mocha.reporters + * @extends Mocha.reporters.Base + * @api public + * @param {Runner} runner + */ +function JSONReporter(runner) { + Base.call(this, runner); + + var self = this; + var tests = []; + var pending = []; + var failures = []; + var passes = []; + + runner.on('test end', function(test) { + tests.push(test); + }); + + runner.on('pass', function(test) { + passes.push(test); + }); + + runner.on('fail', function(test) { + failures.push(test); + }); + + runner.on('pending', function(test) { + pending.push(test); + }); + + runner.once('end', function() { + var obj = { + stats: self.stats, + tests: tests.map(clean), + pending: pending.map(clean), + failures: failures.map(clean), + passes: passes.map(clean) + }; + + runner.testResults = obj; + + process.stdout.write(JSON.stringify(obj, null, 2)); + }); +} + +/** + * Return a plain-object representation of `test` + * free of cyclic properties etc. + * + * @api private + * @param {Object} test + * @return {Object} + */ +function clean(test) { + var err = test.err || {}; + if (err instanceof Error) { + err = errorJSON(err); + } + + return { + title: test.title, + fullTitle: test.fullTitle(), + duration: test.duration, + currentRetry: test.currentRetry(), + err: cleanCycles(err) + }; +} + +/** + * Replaces any circular references inside `obj` with '[object Object]' + * + * @api private + * @param {Object} obj + * @return {Object} + */ +function cleanCycles(obj) { + var cache = []; + return JSON.parse( + JSON.stringify(obj, function(key, value) { + if (typeof value === 'object' && value !== null) { + if (cache.indexOf(value) !== -1) { + // Instead of going in a circle, we'll print [object Object] + return '' + value; + } + cache.push(value); + } + + return value; + }) + ); +} + +/** + * Transform an Error object into a JSON object. + * + * @api private + * @param {Error} err + * @return {Object} + */ +function errorJSON(err) { + var res = {}; + Object.getOwnPropertyNames(err).forEach(function(key) { + res[key] = err[key]; + }, err); + return res; +} + +}).call(this,require('_process')) +},{"./base":16,"_process":56}],23:[function(require,module,exports){ +(function (process){ +'use strict'; +/** + * @module Landing + */ +/** + * Module dependencies. + */ + +var Base = require('./base'); +var inherits = require('../utils').inherits; +var cursor = Base.cursor; +var color = Base.color; + +/** + * Expose `Landing`. + */ + +exports = module.exports = Landing; + +/** + * Airplane color. + */ + +Base.colors.plane = 0; + +/** + * Airplane crash color. + */ + +Base.colors['plane crash'] = 31; + +/** + * Runway color. + */ + +Base.colors.runway = 90; + +/** + * Initialize a new `Landing` reporter. + * + * @public + * @class + * @memberof Mocha.reporters + * @extends Mocha.reporters.Base + * @api public + * @param {Runner} runner + */ +function Landing(runner) { + Base.call(this, runner); + + var self = this; + var width = (Base.window.width * 0.75) | 0; + var total = runner.total; + var stream = process.stdout; + var plane = color('plane', '✈'); + var crashed = -1; + var n = 0; + + function runway() { + var buf = Array(width).join('-'); + return ' ' + color('runway', buf); + } + + runner.on('start', function() { + stream.write('\n\n\n '); + cursor.hide(); + }); + + runner.on('test end', function(test) { + // check if the plane crashed + var col = crashed === -1 ? (width * ++n / total) | 0 : crashed; + + // show the crash + if (test.state === 'failed') { + plane = color('plane crash', '✈'); + crashed = col; + } + + // render landing strip + stream.write('\u001b[' + (width + 1) + 'D\u001b[2A'); + stream.write(runway()); + stream.write('\n '); + stream.write(color('runway', Array(col).join('⋅'))); + stream.write(plane); + stream.write(color('runway', Array(width - col).join('⋅') + '\n')); + stream.write(runway()); + stream.write('\u001b[0m'); + }); + + runner.once('end', function() { + cursor.show(); + console.log(); + self.epilogue(); + }); +} + +/** + * Inherit from `Base.prototype`. + */ +inherits(Landing, Base); + +}).call(this,require('_process')) +},{"../utils":36,"./base":16,"_process":56}],24:[function(require,module,exports){ +(function (process){ +'use strict'; +/** + * @module List + */ +/** + * Module dependencies. + */ + +var Base = require('./base'); +var inherits = require('../utils').inherits; +var color = Base.color; +var cursor = Base.cursor; + +/** + * Expose `List`. + */ + +exports = module.exports = List; + +/** + * Initialize a new `List` test reporter. + * + * @public + * @class + * @memberof Mocha.reporters + * @extends Mocha.reporters.Base + * @api public + * @param {Runner} runner + */ +function List(runner) { + Base.call(this, runner); + + var self = this; + var n = 0; + + runner.on('start', function() { + console.log(); + }); + + runner.on('test', function(test) { + process.stdout.write(color('pass', ' ' + test.fullTitle() + ': ')); + }); + + runner.on('pending', function(test) { + var fmt = color('checkmark', ' -') + color('pending', ' %s'); + console.log(fmt, test.fullTitle()); + }); + + runner.on('pass', function(test) { + var fmt = + color('checkmark', ' ' + Base.symbols.ok) + + color('pass', ' %s: ') + + color(test.speed, '%dms'); + cursor.CR(); + console.log(fmt, test.fullTitle(), test.duration); + }); + + runner.on('fail', function(test) { + cursor.CR(); + console.log(color('fail', ' %d) %s'), ++n, test.fullTitle()); + }); + + runner.once('end', self.epilogue.bind(self)); +} + +/** + * Inherit from `Base.prototype`. + */ +inherits(List, Base); + +}).call(this,require('_process')) +},{"../utils":36,"./base":16,"_process":56}],25:[function(require,module,exports){ +(function (process){ +'use strict'; +/** + * @module Markdown + */ +/** + * Module dependencies. + */ + +var Base = require('./base'); +var utils = require('../utils'); + +/** + * Constants + */ + +var SUITE_PREFIX = '$'; + +/** + * Expose `Markdown`. + */ + +exports = module.exports = Markdown; + +/** + * Initialize a new `Markdown` reporter. + * + * @public + * @class + * @memberof Mocha.reporters + * @extends Mocha.reporters.Base + * @api public + * @param {Runner} runner + */ +function Markdown(runner) { + Base.call(this, runner); + + var level = 0; + var buf = ''; + + function title(str) { + return Array(level).join('#') + ' ' + str; + } + + function mapTOC(suite, obj) { + var ret = obj; + var key = SUITE_PREFIX + suite.title; + + obj = obj[key] = obj[key] || {suite: suite}; + suite.suites.forEach(function(suite) { + mapTOC(suite, obj); + }); + + return ret; + } + + function stringifyTOC(obj, level) { + ++level; + var buf = ''; + var link; + for (var key in obj) { + if (key === 'suite') { + continue; + } + if (key !== SUITE_PREFIX) { + link = ' - [' + key.substring(1) + ']'; + link += '(#' + utils.slug(obj[key].suite.fullTitle()) + ')\n'; + buf += Array(level).join(' ') + link; + } + buf += stringifyTOC(obj[key], level); + } + return buf; + } + + function generateTOC(suite) { + var obj = mapTOC(suite, {}); + return stringifyTOC(obj, 0); + } + + generateTOC(runner.suite); + + runner.on('suite', function(suite) { + ++level; + var slug = utils.slug(suite.fullTitle()); + buf += '' + '\n'; + buf += title(suite.title) + '\n'; + }); + + runner.on('suite end', function() { + --level; + }); + + runner.on('pass', function(test) { + var code = utils.clean(test.body); + buf += test.title + '.\n'; + buf += '\n```js\n'; + buf += code + '\n'; + buf += '```\n\n'; + }); + + runner.once('end', function() { + process.stdout.write('# TOC\n'); + process.stdout.write(generateTOC(runner.suite)); + process.stdout.write(buf); + }); +} + +}).call(this,require('_process')) +},{"../utils":36,"./base":16,"_process":56}],26:[function(require,module,exports){ +(function (process){ +'use strict'; +/** + * @module Min + */ +/** + * Module dependencies. + */ + +var Base = require('./base'); +var inherits = require('../utils').inherits; + +/** + * Expose `Min`. + */ + +exports = module.exports = Min; + +/** + * Initialize a new `Min` minimal test reporter (best used with --watch). + * + * @public + * @class + * @memberof Mocha.reporters + * @extends Mocha.reporters.Base + * @api public + * @param {Runner} runner + */ +function Min(runner) { + Base.call(this, runner); + + runner.on('start', function() { + // clear screen + process.stdout.write('\u001b[2J'); + // set cursor position + process.stdout.write('\u001b[1;3H'); + }); + + runner.once('end', this.epilogue.bind(this)); +} + +/** + * Inherit from `Base.prototype`. + */ +inherits(Min, Base); + +}).call(this,require('_process')) +},{"../utils":36,"./base":16,"_process":56}],27:[function(require,module,exports){ +(function (process){ +'use strict'; +/** + * @module Nyan + */ +/** + * Module dependencies. + */ + +var Base = require('./base'); +var inherits = require('../utils').inherits; + +/** + * Expose `Dot`. + */ + +exports = module.exports = NyanCat; + +/** + * Initialize a new `Dot` matrix test reporter. + * + * @param {Runner} runner + * @api public + * @public + * @class Nyan + * @memberof Mocha.reporters + * @extends Mocha.reporters.Base + */ + +function NyanCat(runner) { + Base.call(this, runner); + + var self = this; + var width = (Base.window.width * 0.75) | 0; + var nyanCatWidth = (this.nyanCatWidth = 11); + + this.colorIndex = 0; + this.numberOfLines = 4; + this.rainbowColors = self.generateColors(); + this.scoreboardWidth = 5; + this.tick = 0; + this.trajectories = [[], [], [], []]; + this.trajectoryWidthMax = width - nyanCatWidth; + + runner.on('start', function() { + Base.cursor.hide(); + self.draw(); + }); + + runner.on('pending', function() { + self.draw(); + }); + + runner.on('pass', function() { + self.draw(); + }); + + runner.on('fail', function() { + self.draw(); + }); + + runner.once('end', function() { + Base.cursor.show(); + for (var i = 0; i < self.numberOfLines; i++) { + write('\n'); + } + self.epilogue(); + }); +} + +/** + * Inherit from `Base.prototype`. + */ +inherits(NyanCat, Base); + +/** + * Draw the nyan cat + * + * @api private + */ + +NyanCat.prototype.draw = function() { + this.appendRainbow(); + this.drawScoreboard(); + this.drawRainbow(); + this.drawNyanCat(); + this.tick = !this.tick; +}; + +/** + * Draw the "scoreboard" showing the number + * of passes, failures and pending tests. + * + * @api private + */ + +NyanCat.prototype.drawScoreboard = function() { + var stats = this.stats; + + function draw(type, n) { + write(' '); + write(Base.color(type, n)); + write('\n'); + } + + draw('green', stats.passes); + draw('fail', stats.failures); + draw('pending', stats.pending); + write('\n'); + + this.cursorUp(this.numberOfLines); +}; + +/** + * Append the rainbow. + * + * @api private + */ + +NyanCat.prototype.appendRainbow = function() { + var segment = this.tick ? '_' : '-'; + var rainbowified = this.rainbowify(segment); + + for (var index = 0; index < this.numberOfLines; index++) { + var trajectory = this.trajectories[index]; + if (trajectory.length >= this.trajectoryWidthMax) { + trajectory.shift(); + } + trajectory.push(rainbowified); + } +}; + +/** + * Draw the rainbow. + * + * @api private + */ + +NyanCat.prototype.drawRainbow = function() { + var self = this; + + this.trajectories.forEach(function(line) { + write('\u001b[' + self.scoreboardWidth + 'C'); + write(line.join('')); + write('\n'); + }); + + this.cursorUp(this.numberOfLines); +}; + +/** + * Draw the nyan cat + * + * @api private + */ +NyanCat.prototype.drawNyanCat = function() { + var self = this; + var startWidth = this.scoreboardWidth + this.trajectories[0].length; + var dist = '\u001b[' + startWidth + 'C'; + var padding = ''; + + write(dist); + write('_,------,'); + write('\n'); + + write(dist); + padding = self.tick ? ' ' : ' '; + write('_|' + padding + '/\\_/\\ '); + write('\n'); + + write(dist); + padding = self.tick ? '_' : '__'; + var tail = self.tick ? '~' : '^'; + write(tail + '|' + padding + this.face() + ' '); + write('\n'); + + write(dist); + padding = self.tick ? ' ' : ' '; + write(padding + '"" "" '); + write('\n'); + + this.cursorUp(this.numberOfLines); +}; + +/** + * Draw nyan cat face. + * + * @api private + * @return {string} + */ + +NyanCat.prototype.face = function() { + var stats = this.stats; + if (stats.failures) { + return '( x .x)'; + } else if (stats.pending) { + return '( o .o)'; + } else if (stats.passes) { + return '( ^ .^)'; + } + return '( - .-)'; +}; + +/** + * Move cursor up `n`. + * + * @api private + * @param {number} n + */ + +NyanCat.prototype.cursorUp = function(n) { + write('\u001b[' + n + 'A'); +}; + +/** + * Move cursor down `n`. + * + * @api private + * @param {number} n + */ + +NyanCat.prototype.cursorDown = function(n) { + write('\u001b[' + n + 'B'); +}; + +/** + * Generate rainbow colors. + * + * @api private + * @return {Array} + */ +NyanCat.prototype.generateColors = function() { + var colors = []; + + for (var i = 0; i < 6 * 7; i++) { + var pi3 = Math.floor(Math.PI / 3); + var n = i * (1.0 / 6); + var r = Math.floor(3 * Math.sin(n) + 3); + var g = Math.floor(3 * Math.sin(n + 2 * pi3) + 3); + var b = Math.floor(3 * Math.sin(n + 4 * pi3) + 3); + colors.push(36 * r + 6 * g + b + 16); + } + + return colors; +}; + +/** + * Apply rainbow to the given `str`. + * + * @api private + * @param {string} str + * @return {string} + */ +NyanCat.prototype.rainbowify = function(str) { + if (!Base.useColors) { + return str; + } + var color = this.rainbowColors[this.colorIndex % this.rainbowColors.length]; + this.colorIndex += 1; + return '\u001b[38;5;' + color + 'm' + str + '\u001b[0m'; +}; + +/** + * Stdout helper. + * + * @param {string} string A message to write to stdout. + */ +function write(string) { + process.stdout.write(string); +} + +}).call(this,require('_process')) +},{"../utils":36,"./base":16,"_process":56}],28:[function(require,module,exports){ +(function (process){ +'use strict'; +/** + * @module Progress + */ +/** + * Module dependencies. + */ + +var Base = require('./base'); +var inherits = require('../utils').inherits; +var color = Base.color; +var cursor = Base.cursor; + +/** + * Expose `Progress`. + */ + +exports = module.exports = Progress; + +/** + * General progress bar color. + */ + +Base.colors.progress = 90; + +/** + * Initialize a new `Progress` bar test reporter. + * + * @public + * @class + * @memberof Mocha.reporters + * @extends Mocha.reporters.Base + * @api public + * @param {Runner} runner + * @param {Object} options + */ +function Progress(runner, options) { + Base.call(this, runner); + + var self = this; + var width = (Base.window.width * 0.5) | 0; + var total = runner.total; + var complete = 0; + var lastN = -1; + + // default chars + options = options || {}; + var reporterOptions = options.reporterOptions || {}; + + options.open = reporterOptions.open || '['; + options.complete = reporterOptions.complete || '▬'; + options.incomplete = reporterOptions.incomplete || Base.symbols.dot; + options.close = reporterOptions.close || ']'; + options.verbose = reporterOptions.verbose || false; + + // tests started + runner.on('start', function() { + console.log(); + cursor.hide(); + }); + + // tests complete + runner.on('test end', function() { + complete++; + + var percent = complete / total; + var n = (width * percent) | 0; + var i = width - n; + + if (n === lastN && !options.verbose) { + // Don't re-render the line if it hasn't changed + return; + } + lastN = n; + + cursor.CR(); + process.stdout.write('\u001b[J'); + process.stdout.write(color('progress', ' ' + options.open)); + process.stdout.write(Array(n).join(options.complete)); + process.stdout.write(Array(i).join(options.incomplete)); + process.stdout.write(color('progress', options.close)); + if (options.verbose) { + process.stdout.write(color('progress', ' ' + complete + ' of ' + total)); + } + }); + + // tests are complete, output some stats + // and the failures if any + runner.once('end', function() { + cursor.show(); + console.log(); + self.epilogue(); + }); +} + +/** + * Inherit from `Base.prototype`. + */ +inherits(Progress, Base); + +}).call(this,require('_process')) +},{"../utils":36,"./base":16,"_process":56}],29:[function(require,module,exports){ +'use strict'; +/** + * @module Spec + */ +/** + * Module dependencies. + */ + +var Base = require('./base'); +var inherits = require('../utils').inherits; +var color = Base.color; + +/** + * Expose `Spec`. + */ + +exports = module.exports = Spec; + +/** + * Initialize a new `Spec` test reporter. + * + * @public + * @class + * @memberof Mocha.reporters + * @extends Mocha.reporters.Base + * @api public + * @param {Runner} runner + */ +function Spec(runner) { + Base.call(this, runner); + + var self = this; + var indents = 0; + var n = 0; + + function indent() { + return Array(indents).join(' '); + } + + runner.on('start', function() { + console.log(); + }); + + runner.on('suite', function(suite) { + ++indents; + console.log(color('suite', '%s%s'), indent(), suite.title); + }); + + runner.on('suite end', function() { + --indents; + if (indents === 1) { + console.log(); + } + }); + + runner.on('pending', function(test) { + var fmt = indent() + color('pending', ' - %s'); + console.log(fmt, test.title); + }); + + runner.on('pass', function(test) { + var fmt; + if (test.speed === 'fast') { + fmt = + indent() + + color('checkmark', ' ' + Base.symbols.ok) + + color('pass', ' %s'); + console.log(fmt, test.title); + } else { + fmt = + indent() + + color('checkmark', ' ' + Base.symbols.ok) + + color('pass', ' %s') + + color(test.speed, ' (%dms)'); + console.log(fmt, test.title, test.duration); + } + }); + + runner.on('fail', function(test) { + console.log(indent() + color('fail', ' %d) %s'), ++n, test.title); + }); + + runner.once('end', self.epilogue.bind(self)); +} + +/** + * Inherit from `Base.prototype`. + */ +inherits(Spec, Base); + +},{"../utils":36,"./base":16}],30:[function(require,module,exports){ +'use strict'; +/** + * @module TAP + */ +/** + * Module dependencies. + */ + +var Base = require('./base'); + +/** + * Expose `TAP`. + */ + +exports = module.exports = TAP; + +/** + * Initialize a new `TAP` reporter. + * + * @public + * @class + * @memberof Mocha.reporters + * @extends Mocha.reporters.Base + * @api public + * @param {Runner} runner + */ +function TAP(runner) { + Base.call(this, runner); + + var n = 1; + var passes = 0; + var failures = 0; + + runner.on('start', function() { + var total = runner.grepTotal(runner.suite); + console.log('%d..%d', 1, total); + }); + + runner.on('test end', function() { + ++n; + }); + + runner.on('pending', function(test) { + console.log('ok %d %s # SKIP -', n, title(test)); + }); + + runner.on('pass', function(test) { + passes++; + console.log('ok %d %s', n, title(test)); + }); + + runner.on('fail', function(test, err) { + failures++; + console.log('not ok %d %s', n, title(test)); + if (err.stack) { + console.log(err.stack.replace(/^/gm, ' ')); + } + }); + + runner.once('end', function() { + console.log('# tests ' + (passes + failures)); + console.log('# pass ' + passes); + console.log('# fail ' + failures); + }); +} + +/** + * Return a TAP-safe title of `test` + * + * @api private + * @param {Object} test + * @return {String} + */ +function title(test) { + return test.fullTitle().replace(/#/g, ''); +} + +},{"./base":16}],31:[function(require,module,exports){ +(function (process,global){ +'use strict'; +/** + * @module XUnit + */ +/** + * Module dependencies. + */ + +var Base = require('./base'); +var utils = require('../utils'); +var inherits = utils.inherits; +var fs = require('fs'); +var escape = utils.escape; +var mkdirp = require('mkdirp'); +var path = require('path'); + +/** + * Save timer references to avoid Sinon interfering (see GH-237). + */ + +/* eslint-disable no-unused-vars, no-native-reassign */ +var Date = global.Date; +var setTimeout = global.setTimeout; +var setInterval = global.setInterval; +var clearTimeout = global.clearTimeout; +var clearInterval = global.clearInterval; +/* eslint-enable no-unused-vars, no-native-reassign */ + +/** + * Expose `XUnit`. + */ + +exports = module.exports = XUnit; + +/** + * Initialize a new `XUnit` reporter. + * + * @public + * @class + * @memberof Mocha.reporters + * @extends Mocha.reporters.Base + * @api public + * @param {Runner} runner + */ +function XUnit(runner, options) { + Base.call(this, runner); + + var stats = this.stats; + var tests = []; + var self = this; + + // the name of the test suite, as it will appear in the resulting XML file + var suiteName; + + // the default name of the test suite if none is provided + var DEFAULT_SUITE_NAME = 'Mocha Tests'; + + if (options && options.reporterOptions) { + if (options.reporterOptions.output) { + if (!fs.createWriteStream) { + throw new Error('file output not supported in browser'); + } + + mkdirp.sync(path.dirname(options.reporterOptions.output)); + self.fileStream = fs.createWriteStream(options.reporterOptions.output); + } + + // get the suite name from the reporter options (if provided) + suiteName = options.reporterOptions.suiteName; + } + + // fall back to the default suite name + suiteName = suiteName || DEFAULT_SUITE_NAME; + + runner.on('pending', function(test) { + tests.push(test); + }); + + runner.on('pass', function(test) { + tests.push(test); + }); + + runner.on('fail', function(test) { + tests.push(test); + }); + + runner.once('end', function() { + self.write( + tag( + 'testsuite', + { + name: suiteName, + tests: stats.tests, + failures: stats.failures, + errors: stats.failures, + skipped: stats.tests - stats.failures - stats.passes, + timestamp: new Date().toUTCString(), + time: stats.duration / 1000 || 0 + }, + false + ) + ); + + tests.forEach(function(t) { + self.test(t); + }); + + self.write(''); + }); +} + +/** + * Inherit from `Base.prototype`. + */ +inherits(XUnit, Base); + +/** + * Override done to close the stream (if it's a file). + * + * @param failures + * @param {Function} fn + */ +XUnit.prototype.done = function(failures, fn) { + if (this.fileStream) { + this.fileStream.end(function() { + fn(failures); + }); + } else { + fn(failures); + } +}; + +/** + * Write out the given line. + * + * @param {string} line + */ +XUnit.prototype.write = function(line) { + if (this.fileStream) { + this.fileStream.write(line + '\n'); + } else if (typeof process === 'object' && process.stdout) { + process.stdout.write(line + '\n'); + } else { + console.log(line); + } +}; + +/** + * Output tag for the given `test.` + * + * @param {Test} test + */ +XUnit.prototype.test = function(test) { + var attrs = { + classname: test.parent.fullTitle(), + name: test.title, + time: test.duration / 1000 || 0 + }; + + if (test.state === 'failed') { + var err = test.err; + this.write( + tag( + 'testcase', + attrs, + false, + tag( + 'failure', + {}, + false, + escape(err.message) + '\n' + escape(err.stack) + ) + ) + ); + } else if (test.isPending()) { + this.write(tag('testcase', attrs, false, tag('skipped', {}, true))); + } else { + this.write(tag('testcase', attrs, true)); + } +}; + +/** + * HTML tag helper. + * + * @param name + * @param attrs + * @param close + * @param content + * @return {string} + */ +function tag(name, attrs, close, content) { + var end = close ? '/>' : '>'; + var pairs = []; + var tag; + + for (var key in attrs) { + if (Object.prototype.hasOwnProperty.call(attrs, key)) { + pairs.push(key + '="' + escape(attrs[key]) + '"'); + } + } + + tag = '<' + name + (pairs.length ? ' ' + pairs.join(' ') : '') + end; + if (content) { + tag += content + ' Math.pow(2, 31)) { + this._enableTimeouts = false; + } + if (typeof ms === 'string') { + ms = milliseconds(ms); + } + debug('timeout %d', ms); + this._timeout = ms; + if (this.timer) { + this.resetTimeout(); + } + return this; +}; + +/** + * Set or get slow `ms`. + * + * @api private + * @param {number|string} ms + * @return {Runnable|number} ms or Runnable instance. + */ +Runnable.prototype.slow = function(ms) { + if (!arguments.length || typeof ms === 'undefined') { + return this._slow; + } + if (typeof ms === 'string') { + ms = milliseconds(ms); + } + debug('slow %d', ms); + this._slow = ms; + return this; +}; + +/** + * Set and get whether timeout is `enabled`. + * + * @api private + * @param {boolean} enabled + * @return {Runnable|boolean} enabled or Runnable instance. + */ +Runnable.prototype.enableTimeouts = function(enabled) { + if (!arguments.length) { + return this._enableTimeouts; + } + debug('enableTimeouts %s', enabled); + this._enableTimeouts = enabled; + return this; +}; + +/** + * Halt and mark as pending. + * + * @memberof Mocha.Runnable + * @public + * @api public + */ +Runnable.prototype.skip = function() { + throw new Pending('sync skip'); +}; + +/** + * Check if this runnable or its parent suite is marked as pending. + * + * @api private + */ +Runnable.prototype.isPending = function() { + return this.pending || (this.parent && this.parent.isPending()); +}; + +/** + * Return `true` if this Runnable has failed. + * @return {boolean} + * @private + */ +Runnable.prototype.isFailed = function() { + return !this.isPending() && this.state === 'failed'; +}; + +/** + * Return `true` if this Runnable has passed. + * @return {boolean} + * @private + */ +Runnable.prototype.isPassed = function() { + return !this.isPending() && this.state === 'passed'; +}; + +/** + * Set or get number of retries. + * + * @api private + */ +Runnable.prototype.retries = function(n) { + if (!arguments.length) { + return this._retries; + } + this._retries = n; +}; + +/** + * Set or get current retry + * + * @api private + */ +Runnable.prototype.currentRetry = function(n) { + if (!arguments.length) { + return this._currentRetry; + } + this._currentRetry = n; +}; + +/** + * Return the full title generated by recursively concatenating the parent's + * full title. + * + * @memberof Mocha.Runnable + * @public + * @api public + * @return {string} + */ +Runnable.prototype.fullTitle = function() { + return this.titlePath().join(' '); +}; + +/** + * Return the title path generated by concatenating the parent's title path with the title. + * + * @memberof Mocha.Runnable + * @public + * @api public + * @return {string} + */ +Runnable.prototype.titlePath = function() { + return this.parent.titlePath().concat([this.title]); +}; + +/** + * Clear the timeout. + * + * @api private + */ +Runnable.prototype.clearTimeout = function() { + clearTimeout(this.timer); +}; + +/** + * Inspect the runnable void of private properties. + * + * @api private + * @return {string} + */ +Runnable.prototype.inspect = function() { + return JSON.stringify( + this, + function(key, val) { + if (key[0] === '_') { + return; + } + if (key === 'parent') { + return '#'; + } + if (key === 'ctx') { + return '#'; + } + return val; + }, + 2 + ); +}; + +/** + * Reset the timeout. + * + * @api private + */ +Runnable.prototype.resetTimeout = function() { + var self = this; + var ms = this.timeout() || 1e9; + + if (!this._enableTimeouts) { + return; + } + this.clearTimeout(); + this.timer = setTimeout(function() { + if (!self._enableTimeouts) { + return; + } + self.callback(self._timeoutError(ms)); + self.timedOut = true; + }, ms); +}; + +/** + * Set or get a list of whitelisted globals for this test run. + * + * @api private + * @param {string[]} globals + */ +Runnable.prototype.globals = function(globals) { + if (!arguments.length) { + return this._allowedGlobals; + } + this._allowedGlobals = globals; +}; + +/** + * Run the test and invoke `fn(err)`. + * + * @param {Function} fn + * @api private + */ +Runnable.prototype.run = function(fn) { + var self = this; + var start = new Date(); + var ctx = this.ctx; + var finished; + var emitted; + + // Sometimes the ctx exists, but it is not runnable + if (ctx && ctx.runnable) { + ctx.runnable(this); + } + + // called multiple times + function multiple(err) { + if (emitted) { + return; + } + emitted = true; + var msg = 'done() called multiple times'; + if (err && err.message) { + err.message += " (and Mocha's " + msg + ')'; + self.emit('error', err); + } else { + self.emit('error', new Error(msg)); + } + } + + // finished + function done(err) { + var ms = self.timeout(); + if (self.timedOut) { + return; + } + + if (finished) { + return multiple(err); + } + + self.clearTimeout(); + self.duration = new Date() - start; + finished = true; + if (!err && self.duration > ms && self._enableTimeouts) { + err = self._timeoutError(ms); + } + fn(err); + } + + // for .resetTimeout() + this.callback = done; + + // explicit async with `done` argument + if (this.async) { + this.resetTimeout(); + + // allows skip() to be used in an explicit async context + this.skip = function asyncSkip() { + done(new Pending('async skip call')); + // halt execution. the Runnable will be marked pending + // by the previous call, and the uncaught handler will ignore + // the failure. + throw new Pending('async skip; aborting execution'); + }; + + if (this.allowUncaught) { + return callFnAsync(this.fn); + } + try { + callFnAsync(this.fn); + } catch (err) { + emitted = true; + done(utils.getError(err)); + } + return; + } + + if (this.allowUncaught) { + if (this.isPending()) { + done(); + } else { + callFn(this.fn); + } + return; + } + + // sync or promise-returning + try { + if (this.isPending()) { + done(); + } else { + callFn(this.fn); + } + } catch (err) { + emitted = true; + done(utils.getError(err)); + } + + function callFn(fn) { + var result = fn.call(ctx); + if (result && typeof result.then === 'function') { + self.resetTimeout(); + result.then( + function() { + done(); + // Return null so libraries like bluebird do not warn about + // subsequently constructed Promises. + return null; + }, + function(reason) { + done(reason || new Error('Promise rejected with no or falsy reason')); + } + ); + } else { + if (self.asyncOnly) { + return done( + new Error( + '--async-only option in use without declaring `done()` or returning a promise' + ) + ); + } + + done(); + } + } + + function callFnAsync(fn) { + var result = fn.call(ctx, function(err) { + if (err instanceof Error || toString.call(err) === '[object Error]') { + return done(err); + } + if (err) { + if (Object.prototype.toString.call(err) === '[object Object]') { + return done( + new Error('done() invoked with non-Error: ' + JSON.stringify(err)) + ); + } + return done(new Error('done() invoked with non-Error: ' + err)); + } + if (result && utils.isPromise(result)) { + return done( + new Error( + 'Resolution method is overspecified. Specify a callback *or* return a Promise; not both.' + ) + ); + } + + done(); + }); + } +}; + +/** + * Instantiates a "timeout" error + * + * @param {number} ms - Timeout (in milliseconds) + * @returns {Error} a "timeout" error + * @private + */ +Runnable.prototype._timeoutError = function(ms) { + var msg = + 'Timeout of ' + + ms + + 'ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves.'; + if (this.file) { + msg += ' (' + this.file + ')'; + } + return new Error(msg); +}; + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"./ms":14,"./pending":15,"./utils":36,"debug":43,"events":47}],33:[function(require,module,exports){ +(function (process,global){ +'use strict'; + +/** + * @module Runner + */ +/** + * Module dependencies. + */ +var EventEmitter = require('events').EventEmitter; +var Pending = require('./pending'); +var utils = require('./utils'); +var inherits = utils.inherits; +var debug = require('debug')('mocha:runner'); +var Runnable = require('./runnable'); +var stackFilter = utils.stackTraceFilter(); +var stringify = utils.stringify; +var type = utils.type; +var undefinedError = utils.undefinedError; + +/** + * Non-enumerable globals. + */ + +var globals = [ + 'setTimeout', + 'clearTimeout', + 'setInterval', + 'clearInterval', + 'XMLHttpRequest', + 'Date', + 'setImmediate', + 'clearImmediate' +]; + +/** + * Expose `Runner`. + */ + +module.exports = Runner; + +/** + * Initialize a `Runner` for the given `suite`. Derived from [EventEmitter](https://nodejs.org/api/events.html#events_class_eventemitter) + * + * Events: + * + * - `start` execution started + * - `end` execution complete + * - `suite` (suite) test suite execution started + * - `suite end` (suite) all tests (and sub-suites) have finished + * - `test` (test) test execution started + * - `test end` (test) test completed + * - `hook` (hook) hook execution started + * - `hook end` (hook) hook complete + * - `pass` (test) test passed + * - `fail` (test, err) test failed + * - `pending` (test) test pending + * + * @memberof Mocha + * @public + * @class + * @api public + * @param {Suite} [suite] Root suite + * @param {boolean} [delay] Whether or not to delay execution of root suite + * until ready. + */ +function Runner(suite, delay) { + var self = this; + this._globals = []; + this._abort = false; + this._delay = delay; + this.suite = suite; + this.started = false; + this.total = suite.total(); + this.failures = 0; + this.on('test end', function(test) { + self.checkGlobals(test); + }); + this.on('hook end', function(hook) { + self.checkGlobals(hook); + }); + this._defaultGrep = /.*/; + this.grep(this._defaultGrep); + this.globals(this.globalProps().concat(extraGlobals())); +} + +/** + * Wrapper for setImmediate, process.nextTick, or browser polyfill. + * + * @param {Function} fn + * @api private + */ +Runner.immediately = global.setImmediate || process.nextTick; + +/** + * Inherit from `EventEmitter.prototype`. + */ +inherits(Runner, EventEmitter); + +/** + * Run tests with full titles matching `re`. Updates runner.total + * with number of tests matched. + * + * @api public + * @public + * @memberof Mocha.Runner + * @param {RegExp} re + * @param {boolean} invert + * @return {Runner} Runner instance. + */ +Runner.prototype.grep = function(re, invert) { + debug('grep %s', re); + this._grep = re; + this._invert = invert; + this.total = this.grepTotal(this.suite); + return this; +}; + +/** + * Returns the number of tests matching the grep search for the + * given suite. + * + * @memberof Mocha.Runner + * @api public + * @public + * @param {Suite} suite + * @return {number} + */ +Runner.prototype.grepTotal = function(suite) { + var self = this; + var total = 0; + + suite.eachTest(function(test) { + var match = self._grep.test(test.fullTitle()); + if (self._invert) { + match = !match; + } + if (match) { + total++; + } + }); + + return total; +}; + +/** + * Return a list of global properties. + * + * @return {Array} + * @api private + */ +Runner.prototype.globalProps = function() { + var props = Object.keys(global); + + // non-enumerables + for (var i = 0; i < globals.length; ++i) { + if (~props.indexOf(globals[i])) { + continue; + } + props.push(globals[i]); + } + + return props; +}; + +/** + * Allow the given `arr` of globals. + * + * @api public + * @public + * @memberof Mocha.Runner + * @param {Array} arr + * @return {Runner} Runner instance. + */ +Runner.prototype.globals = function(arr) { + if (!arguments.length) { + return this._globals; + } + debug('globals %j', arr); + this._globals = this._globals.concat(arr); + return this; +}; + +/** + * Check for global variable leaks. + * + * @api private + */ +Runner.prototype.checkGlobals = function(test) { + if (this.ignoreLeaks) { + return; + } + var ok = this._globals; + + var globals = this.globalProps(); + var leaks; + + if (test) { + ok = ok.concat(test._allowedGlobals || []); + } + + if (this.prevGlobalsLength === globals.length) { + return; + } + this.prevGlobalsLength = globals.length; + + leaks = filterLeaks(ok, globals); + this._globals = this._globals.concat(leaks); + + if (leaks.length > 1) { + this.fail( + test, + new Error('global leaks detected: ' + leaks.join(', ') + '') + ); + } else if (leaks.length) { + this.fail(test, new Error('global leak detected: ' + leaks[0])); + } +}; + +/** + * Fail the given `test`. + * + * @api private + * @param {Test} test + * @param {Error} err + */ +Runner.prototype.fail = function(test, err) { + if (test.isPending()) { + return; + } + + ++this.failures; + test.state = 'failed'; + + if (!(err instanceof Error || (err && typeof err.message === 'string'))) { + err = new Error( + 'the ' + + type(err) + + ' ' + + stringify(err) + + ' was thrown, throw an Error :)' + ); + } + + try { + err.stack = + this.fullStackTrace || !err.stack ? err.stack : stackFilter(err.stack); + } catch (ignore) { + // some environments do not take kindly to monkeying with the stack + } + + this.emit('fail', test, err); + if (this.suite.bail()) { + this.emit('end'); + } +}; + +/** + * Fail the given `hook` with `err`. + * + * Hook failures work in the following pattern: + * - If bail, then exit + * - Failed `before` hook skips all tests in a suite and subsuites, + * but jumps to corresponding `after` hook + * - Failed `before each` hook skips remaining tests in a + * suite and jumps to corresponding `after each` hook, + * which is run only once + * - Failed `after` hook does not alter + * execution order + * - Failed `after each` hook skips remaining tests in a + * suite and subsuites, but executes other `after each` + * hooks + * + * @api private + * @param {Hook} hook + * @param {Error} err + */ +Runner.prototype.failHook = function(hook, err) { + if (hook.ctx && hook.ctx.currentTest) { + hook.originalTitle = hook.originalTitle || hook.title; + hook.title = + hook.originalTitle + ' for "' + hook.ctx.currentTest.title + '"'; + } + + this.fail(hook, err); +}; + +/** + * Run hook `name` callbacks and then invoke `fn()`. + * + * @api private + * @param {string} name + * @param {Function} fn + */ + +Runner.prototype.hook = function(name, fn) { + var suite = this.suite; + var hooks = suite['_' + name]; + var self = this; + + function next(i) { + var hook = hooks[i]; + if (!hook) { + return fn(); + } + self.currentRunnable = hook; + + hook.ctx.currentTest = self.test; + + self.emit('hook', hook); + + if (!hook.listeners('error').length) { + hook.on('error', function(err) { + self.failHook(hook, err); + }); + } + + hook.run(function(err) { + var testError = hook.error(); + if (testError) { + self.fail(self.test, testError); + } + if (err) { + if (err instanceof Pending) { + if (name === 'beforeEach' || name === 'afterEach') { + self.test.pending = true; + } else { + suite.tests.forEach(function(test) { + test.pending = true; + }); + // a pending hook won't be executed twice. + hook.pending = true; + } + } else { + self.failHook(hook, err); + + // stop executing hooks, notify callee of hook err + return fn(err); + } + } + self.emit('hook end', hook); + delete hook.ctx.currentTest; + next(++i); + }); + } + + Runner.immediately(function() { + next(0); + }); +}; + +/** + * Run hook `name` for the given array of `suites` + * in order, and callback `fn(err, errSuite)`. + * + * @api private + * @param {string} name + * @param {Array} suites + * @param {Function} fn + */ +Runner.prototype.hooks = function(name, suites, fn) { + var self = this; + var orig = this.suite; + + function next(suite) { + self.suite = suite; + + if (!suite) { + self.suite = orig; + return fn(); + } + + self.hook(name, function(err) { + if (err) { + var errSuite = self.suite; + self.suite = orig; + return fn(err, errSuite); + } + + next(suites.pop()); + }); + } + + next(suites.pop()); +}; + +/** + * Run hooks from the top level down. + * + * @param {String} name + * @param {Function} fn + * @api private + */ +Runner.prototype.hookUp = function(name, fn) { + var suites = [this.suite].concat(this.parents()).reverse(); + this.hooks(name, suites, fn); +}; + +/** + * Run hooks from the bottom up. + * + * @param {String} name + * @param {Function} fn + * @api private + */ +Runner.prototype.hookDown = function(name, fn) { + var suites = [this.suite].concat(this.parents()); + this.hooks(name, suites, fn); +}; + +/** + * Return an array of parent Suites from + * closest to furthest. + * + * @return {Array} + * @api private + */ +Runner.prototype.parents = function() { + var suite = this.suite; + var suites = []; + while (suite.parent) { + suite = suite.parent; + suites.push(suite); + } + return suites; +}; + +/** + * Run the current test and callback `fn(err)`. + * + * @param {Function} fn + * @api private + */ +Runner.prototype.runTest = function(fn) { + var self = this; + var test = this.test; + + if (!test) { + return; + } + if (this.forbidOnly && hasOnly(this.parents().reverse()[0] || this.suite)) { + fn(new Error('`.only` forbidden')); + return; + } + if (this.asyncOnly) { + test.asyncOnly = true; + } + test.on('error', function(err) { + self.fail(test, err); + }); + if (this.allowUncaught) { + test.allowUncaught = true; + return test.run(fn); + } + try { + test.run(fn); + } catch (err) { + fn(err); + } +}; + +/** + * Run tests in the given `suite` and invoke the callback `fn()` when complete. + * + * @api private + * @param {Suite} suite + * @param {Function} fn + */ +Runner.prototype.runTests = function(suite, fn) { + var self = this; + var tests = suite.tests.slice(); + var test; + + function hookErr(_, errSuite, after) { + // before/after Each hook for errSuite failed: + var orig = self.suite; + + // for failed 'after each' hook start from errSuite parent, + // otherwise start from errSuite itself + self.suite = after ? errSuite.parent : errSuite; + + if (self.suite) { + // call hookUp afterEach + self.hookUp('afterEach', function(err2, errSuite2) { + self.suite = orig; + // some hooks may fail even now + if (err2) { + return hookErr(err2, errSuite2, true); + } + // report error suite + fn(errSuite); + }); + } else { + // there is no need calling other 'after each' hooks + self.suite = orig; + fn(errSuite); + } + } + + function next(err, errSuite) { + // if we bail after first err + if (self.failures && suite._bail) { + return fn(); + } + + if (self._abort) { + return fn(); + } + + if (err) { + return hookErr(err, errSuite, true); + } + + // next test + test = tests.shift(); + + // all done + if (!test) { + return fn(); + } + + // grep + var match = self._grep.test(test.fullTitle()); + if (self._invert) { + match = !match; + } + if (!match) { + // Run immediately only if we have defined a grep. When we + // define a grep — It can cause maximum callstack error if + // the grep is doing a large recursive loop by neglecting + // all tests. The run immediately function also comes with + // a performance cost. So we don't want to run immediately + // if we run the whole test suite, because running the whole + // test suite don't do any immediate recursive loops. Thus, + // allowing a JS runtime to breathe. + if (self._grep !== self._defaultGrep) { + Runner.immediately(next); + } else { + next(); + } + return; + } + + if (test.isPending()) { + if (self.forbidPending) { + test.isPending = alwaysFalse; + self.fail(test, new Error('Pending test forbidden')); + delete test.isPending; + } else { + self.emit('pending', test); + } + self.emit('test end', test); + return next(); + } + + // execute test and hook(s) + self.emit('test', (self.test = test)); + self.hookDown('beforeEach', function(err, errSuite) { + if (test.isPending()) { + if (self.forbidPending) { + test.isPending = alwaysFalse; + self.fail(test, new Error('Pending test forbidden')); + delete test.isPending; + } else { + self.emit('pending', test); + } + self.emit('test end', test); + return next(); + } + if (err) { + return hookErr(err, errSuite, false); + } + self.currentRunnable = self.test; + self.runTest(function(err) { + test = self.test; + if (err) { + var retry = test.currentRetry(); + if (err instanceof Pending && self.forbidPending) { + self.fail(test, new Error('Pending test forbidden')); + } else if (err instanceof Pending) { + test.pending = true; + self.emit('pending', test); + } else if (retry < test.retries()) { + var clonedTest = test.clone(); + clonedTest.currentRetry(retry + 1); + tests.unshift(clonedTest); + + // Early return + hook trigger so that it doesn't + // increment the count wrong + return self.hookUp('afterEach', next); + } else { + self.fail(test, err); + } + self.emit('test end', test); + + if (err instanceof Pending) { + return next(); + } + + return self.hookUp('afterEach', next); + } + + test.state = 'passed'; + self.emit('pass', test); + self.emit('test end', test); + self.hookUp('afterEach', next); + }); + }); + } + + this.next = next; + this.hookErr = hookErr; + next(); +}; + +function alwaysFalse() { + return false; +} + +/** + * Run the given `suite` and invoke the callback `fn()` when complete. + * + * @api private + * @param {Suite} suite + * @param {Function} fn + */ +Runner.prototype.runSuite = function(suite, fn) { + var i = 0; + var self = this; + var total = this.grepTotal(suite); + var afterAllHookCalled = false; + + debug('run suite %s', suite.fullTitle()); + + if (!total || (self.failures && suite._bail)) { + return fn(); + } + + this.emit('suite', (this.suite = suite)); + + function next(errSuite) { + if (errSuite) { + // current suite failed on a hook from errSuite + if (errSuite === suite) { + // if errSuite is current suite + // continue to the next sibling suite + return done(); + } + // errSuite is among the parents of current suite + // stop execution of errSuite and all sub-suites + return done(errSuite); + } + + if (self._abort) { + return done(); + } + + var curr = suite.suites[i++]; + if (!curr) { + return done(); + } + + // Avoid grep neglecting large number of tests causing a + // huge recursive loop and thus a maximum call stack error. + // See comment in `this.runTests()` for more information. + if (self._grep !== self._defaultGrep) { + Runner.immediately(function() { + self.runSuite(curr, next); + }); + } else { + self.runSuite(curr, next); + } + } + + function done(errSuite) { + self.suite = suite; + self.nextSuite = next; + + if (afterAllHookCalled) { + fn(errSuite); + } else { + // mark that the afterAll block has been called once + // and so can be skipped if there is an error in it. + afterAllHookCalled = true; + + // remove reference to test + delete self.test; + + self.hook('afterAll', function() { + self.emit('suite end', suite); + fn(errSuite); + }); + } + } + + this.nextSuite = next; + + this.hook('beforeAll', function(err) { + if (err) { + return done(); + } + self.runTests(suite, next); + }); +}; + +/** + * Handle uncaught exceptions. + * + * @param {Error} err + * @api private + */ +Runner.prototype.uncaught = function(err) { + if (err) { + debug( + 'uncaught exception %s', + err === + function() { + return this; + }.call(err) + ? err.message || err + : err + ); + } else { + debug('uncaught undefined exception'); + err = undefinedError(); + } + err.uncaught = true; + + var runnable = this.currentRunnable; + + if (!runnable) { + runnable = new Runnable('Uncaught error outside test suite'); + runnable.parent = this.suite; + + if (this.started) { + this.fail(runnable, err); + } else { + // Can't recover from this failure + this.emit('start'); + this.fail(runnable, err); + this.emit('end'); + } + + return; + } + + runnable.clearTimeout(); + + // Ignore errors if already failed or pending + // See #3226 + if (runnable.isFailed() || runnable.isPending()) { + return; + } + // we cannot recover gracefully if a Runnable has already passed + // then fails asynchronously + var alreadyPassed = runnable.isPassed(); + // this will change the state to "failed" regardless of the current value + this.fail(runnable, err); + if (!alreadyPassed) { + // recover from test + if (runnable.type === 'test') { + this.emit('test end', runnable); + this.hookUp('afterEach', this.next); + return; + } + + // recover from hooks + var errSuite = this.suite; + // if hook failure is in afterEach block + if (runnable.fullTitle().indexOf('after each') > -1) { + return this.hookErr(err, errSuite, true); + } + // if hook failure is in beforeEach block + if (runnable.fullTitle().indexOf('before each') > -1) { + return this.hookErr(err, errSuite, false); + } + // if hook failure is in after or before blocks + return this.nextSuite(errSuite); + } + + // bail + this.emit('end'); +}; + +/** + * Cleans up the references to all the deferred functions + * (before/after/beforeEach/afterEach) and tests of a Suite. + * These must be deleted otherwise a memory leak can happen, + * as those functions may reference variables from closures, + * thus those variables can never be garbage collected as long + * as the deferred functions exist. + * + * @param {Suite} suite + */ +function cleanSuiteReferences(suite) { + function cleanArrReferences(arr) { + for (var i = 0; i < arr.length; i++) { + delete arr[i].fn; + } + } + + if (Array.isArray(suite._beforeAll)) { + cleanArrReferences(suite._beforeAll); + } + + if (Array.isArray(suite._beforeEach)) { + cleanArrReferences(suite._beforeEach); + } + + if (Array.isArray(suite._afterAll)) { + cleanArrReferences(suite._afterAll); + } + + if (Array.isArray(suite._afterEach)) { + cleanArrReferences(suite._afterEach); + } + + for (var i = 0; i < suite.tests.length; i++) { + delete suite.tests[i].fn; + } +} + +/** + * Run the root suite and invoke `fn(failures)` + * on completion. + * + * @api public + * @public + * @memberof Mocha.Runner + * @param {Function} fn + * @return {Runner} Runner instance. + */ +Runner.prototype.run = function(fn) { + var self = this; + var rootSuite = this.suite; + + fn = fn || function() {}; + + function uncaught(err) { + self.uncaught(err); + } + + function start() { + // If there is an `only` filter + if (hasOnly(rootSuite)) { + filterOnly(rootSuite); + } + self.started = true; + self.emit('start'); + self.runSuite(rootSuite, function() { + debug('finished running'); + self.emit('end'); + }); + } + + debug('start'); + + // references cleanup to avoid memory leaks + this.on('suite end', cleanSuiteReferences); + + // callback + this.on('end', function() { + debug('end'); + process.removeListener('uncaughtException', uncaught); + fn(self.failures); + }); + + // uncaught exception + process.on('uncaughtException', uncaught); + + if (this._delay) { + // for reporters, I guess. + // might be nice to debounce some dots while we wait. + this.emit('waiting', rootSuite); + rootSuite.once('run', start); + } else { + start(); + } + + return this; +}; + +/** + * Cleanly abort execution. + * + * @memberof Mocha.Runner + * @public + * @api public + * @return {Runner} Runner instance. + */ +Runner.prototype.abort = function() { + debug('aborting'); + this._abort = true; + + return this; +}; + +/** + * Filter suites based on `isOnly` logic. + * + * @param {Array} suite + * @returns {Boolean} + * @api private + */ +function filterOnly(suite) { + if (suite._onlyTests.length) { + // If the suite contains `only` tests, run those and ignore any nested suites. + suite.tests = suite._onlyTests; + suite.suites = []; + } else { + // Otherwise, do not run any of the tests in this suite. + suite.tests = []; + suite._onlySuites.forEach(function(onlySuite) { + // If there are other `only` tests/suites nested in the current `only` suite, then filter that `only` suite. + // Otherwise, all of the tests on this `only` suite should be run, so don't filter it. + if (hasOnly(onlySuite)) { + filterOnly(onlySuite); + } + }); + // Run the `only` suites, as well as any other suites that have `only` tests/suites as descendants. + suite.suites = suite.suites.filter(function(childSuite) { + return ( + suite._onlySuites.indexOf(childSuite) !== -1 || filterOnly(childSuite) + ); + }); + } + // Keep the suite only if there is something to run + return suite.tests.length || suite.suites.length; +} + +/** + * Determines whether a suite has an `only` test or suite as a descendant. + * + * @param {Array} suite + * @returns {Boolean} + * @api private + */ +function hasOnly(suite) { + return ( + suite._onlyTests.length || + suite._onlySuites.length || + suite.suites.some(hasOnly) + ); +} + +/** + * Filter leaks with the given globals flagged as `ok`. + * + * @api private + * @param {Array} ok + * @param {Array} globals + * @return {Array} + */ +function filterLeaks(ok, globals) { + return globals.filter(function(key) { + // Firefox and Chrome exposes iframes as index inside the window object + if (/^\d+/.test(key)) { + return false; + } + + // in firefox + // if runner runs in an iframe, this iframe's window.getInterface method + // not init at first it is assigned in some seconds + if (global.navigator && /^getInterface/.test(key)) { + return false; + } + + // an iframe could be approached by window[iframeIndex] + // in ie6,7,8 and opera, iframeIndex is enumerable, this could cause leak + if (global.navigator && /^\d+/.test(key)) { + return false; + } + + // Opera and IE expose global variables for HTML element IDs (issue #243) + if (/^mocha-/.test(key)) { + return false; + } + + var matched = ok.filter(function(ok) { + if (~ok.indexOf('*')) { + return key.indexOf(ok.split('*')[0]) === 0; + } + return key === ok; + }); + return !matched.length && (!global.navigator || key !== 'onerror'); + }); +} + +/** + * Array of globals dependent on the environment. + * + * @return {Array} + * @api private + */ +function extraGlobals() { + if (typeof process === 'object' && typeof process.version === 'string') { + var parts = process.version.split('.'); + var nodeVersion = parts.reduce(function(a, v) { + return (a << 8) | v; + }); + + // 'errno' was renamed to process._errno in v0.9.11. + + if (nodeVersion < 0x00090b) { + return ['errno']; + } + } + + return []; +} + +}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"./pending":15,"./runnable":32,"./utils":36,"_process":56,"debug":43,"events":47}],34:[function(require,module,exports){ +'use strict'; +/** + * @module Suite + */ + +/** + * Module dependencies. + */ +var EventEmitter = require('events').EventEmitter; +var Hook = require('./hook'); +var utils = require('./utils'); +var inherits = utils.inherits; +var debug = require('debug')('mocha:suite'); +var milliseconds = require('./ms'); + +/** + * Expose `Suite`. + */ + +exports = module.exports = Suite; + +/** + * Create a new `Suite` with the given `title` and parent `Suite`. When a suite + * with the same title is already present, that suite is returned to provide + * nicer reporter and more flexible meta-testing. + * + * @memberof Mocha + * @public + * @api public + * @param {Suite} parent + * @param {string} title + * @return {Suite} + */ +exports.create = function(parent, title) { + var suite = new Suite(title, parent.ctx); + suite.parent = parent; + title = suite.fullTitle(); + parent.addSuite(suite); + return suite; +}; + +/** + * Initialize a new `Suite` with the given `title` and `ctx`. Derived from [EventEmitter](https://nodejs.org/api/events.html#events_class_eventemitter) + * + * @memberof Mocha + * @public + * @class + * @param {string} title + * @param {Context} parentContext + */ +function Suite(title, parentContext) { + if (!utils.isString(title)) { + throw new Error( + 'Suite `title` should be a "string" but "' + + typeof title + + '" was given instead.' + ); + } + this.title = title; + function Context() {} + Context.prototype = parentContext; + this.ctx = new Context(); + this.suites = []; + this.tests = []; + this.pending = false; + this._beforeEach = []; + this._beforeAll = []; + this._afterEach = []; + this._afterAll = []; + this.root = !title; + this._timeout = 2000; + this._enableTimeouts = true; + this._slow = 75; + this._bail = false; + this._retries = -1; + this._onlyTests = []; + this._onlySuites = []; + this.delayed = false; +} + +/** + * Inherit from `EventEmitter.prototype`. + */ +inherits(Suite, EventEmitter); + +/** + * Return a clone of this `Suite`. + * + * @api private + * @return {Suite} + */ +Suite.prototype.clone = function() { + var suite = new Suite(this.title); + debug('clone'); + suite.ctx = this.ctx; + suite.timeout(this.timeout()); + suite.retries(this.retries()); + suite.enableTimeouts(this.enableTimeouts()); + suite.slow(this.slow()); + suite.bail(this.bail()); + return suite; +}; + +/** + * Set or get timeout `ms` or short-hand such as "2s". + * + * @api private + * @param {number|string} ms + * @return {Suite|number} for chaining + */ +Suite.prototype.timeout = function(ms) { + if (!arguments.length) { + return this._timeout; + } + if (ms.toString() === '0') { + this._enableTimeouts = false; + } + if (typeof ms === 'string') { + ms = milliseconds(ms); + } + debug('timeout %d', ms); + this._timeout = parseInt(ms, 10); + return this; +}; + +/** + * Set or get number of times to retry a failed test. + * + * @api private + * @param {number|string} n + * @return {Suite|number} for chaining + */ +Suite.prototype.retries = function(n) { + if (!arguments.length) { + return this._retries; + } + debug('retries %d', n); + this._retries = parseInt(n, 10) || 0; + return this; +}; + +/** + * Set or get timeout to `enabled`. + * + * @api private + * @param {boolean} enabled + * @return {Suite|boolean} self or enabled + */ +Suite.prototype.enableTimeouts = function(enabled) { + if (!arguments.length) { + return this._enableTimeouts; + } + debug('enableTimeouts %s', enabled); + this._enableTimeouts = enabled; + return this; +}; + +/** + * Set or get slow `ms` or short-hand such as "2s". + * + * @api private + * @param {number|string} ms + * @return {Suite|number} for chaining + */ +Suite.prototype.slow = function(ms) { + if (!arguments.length) { + return this._slow; + } + if (typeof ms === 'string') { + ms = milliseconds(ms); + } + debug('slow %d', ms); + this._slow = ms; + return this; +}; + +/** + * Set or get whether to bail after first error. + * + * @api private + * @param {boolean} bail + * @return {Suite|number} for chaining + */ +Suite.prototype.bail = function(bail) { + if (!arguments.length) { + return this._bail; + } + debug('bail %s', bail); + this._bail = bail; + return this; +}; + +/** + * Check if this suite or its parent suite is marked as pending. + * + * @api private + */ +Suite.prototype.isPending = function() { + return this.pending || (this.parent && this.parent.isPending()); +}; + +/** + * Generic hook-creator. + * @private + * @param {string} title - Title of hook + * @param {Function} fn - Hook callback + * @returns {Hook} A new hook + */ +Suite.prototype._createHook = function(title, fn) { + var hook = new Hook(title, fn); + hook.parent = this; + hook.timeout(this.timeout()); + hook.retries(this.retries()); + hook.enableTimeouts(this.enableTimeouts()); + hook.slow(this.slow()); + hook.ctx = this.ctx; + hook.file = this.file; + return hook; +}; + +/** + * Run `fn(test[, done])` before running tests. + * + * @api private + * @param {string} title + * @param {Function} fn + * @return {Suite} for chaining + */ +Suite.prototype.beforeAll = function(title, fn) { + if (this.isPending()) { + return this; + } + if (typeof title === 'function') { + fn = title; + title = fn.name; + } + title = '"before all" hook' + (title ? ': ' + title : ''); + + var hook = this._createHook(title, fn); + this._beforeAll.push(hook); + this.emit('beforeAll', hook); + return this; +}; + +/** + * Run `fn(test[, done])` after running tests. + * + * @api private + * @param {string} title + * @param {Function} fn + * @return {Suite} for chaining + */ +Suite.prototype.afterAll = function(title, fn) { + if (this.isPending()) { + return this; + } + if (typeof title === 'function') { + fn = title; + title = fn.name; + } + title = '"after all" hook' + (title ? ': ' + title : ''); + + var hook = this._createHook(title, fn); + this._afterAll.push(hook); + this.emit('afterAll', hook); + return this; +}; + +/** + * Run `fn(test[, done])` before each test case. + * + * @api private + * @param {string} title + * @param {Function} fn + * @return {Suite} for chaining + */ +Suite.prototype.beforeEach = function(title, fn) { + if (this.isPending()) { + return this; + } + if (typeof title === 'function') { + fn = title; + title = fn.name; + } + title = '"before each" hook' + (title ? ': ' + title : ''); + + var hook = this._createHook(title, fn); + this._beforeEach.push(hook); + this.emit('beforeEach', hook); + return this; +}; + +/** + * Run `fn(test[, done])` after each test case. + * + * @api private + * @param {string} title + * @param {Function} fn + * @return {Suite} for chaining + */ +Suite.prototype.afterEach = function(title, fn) { + if (this.isPending()) { + return this; + } + if (typeof title === 'function') { + fn = title; + title = fn.name; + } + title = '"after each" hook' + (title ? ': ' + title : ''); + + var hook = this._createHook(title, fn); + this._afterEach.push(hook); + this.emit('afterEach', hook); + return this; +}; + +/** + * Add a test `suite`. + * + * @api private + * @param {Suite} suite + * @return {Suite} for chaining + */ +Suite.prototype.addSuite = function(suite) { + suite.parent = this; + suite.timeout(this.timeout()); + suite.retries(this.retries()); + suite.enableTimeouts(this.enableTimeouts()); + suite.slow(this.slow()); + suite.bail(this.bail()); + this.suites.push(suite); + this.emit('suite', suite); + return this; +}; + +/** + * Add a `test` to this suite. + * + * @api private + * @param {Test} test + * @return {Suite} for chaining + */ +Suite.prototype.addTest = function(test) { + test.parent = this; + test.timeout(this.timeout()); + test.retries(this.retries()); + test.enableTimeouts(this.enableTimeouts()); + test.slow(this.slow()); + test.ctx = this.ctx; + this.tests.push(test); + this.emit('test', test); + return this; +}; + +/** + * Return the full title generated by recursively concatenating the parent's + * full title. + * + * @memberof Mocha.Suite + * @public + * @api public + * @return {string} + */ +Suite.prototype.fullTitle = function() { + return this.titlePath().join(' '); +}; + +/** + * Return the title path generated by recursively concatenating the parent's + * title path. + * + * @memberof Mocha.Suite + * @public + * @api public + * @return {string} + */ +Suite.prototype.titlePath = function() { + var result = []; + if (this.parent) { + result = result.concat(this.parent.titlePath()); + } + if (!this.root) { + result.push(this.title); + } + return result; +}; + +/** + * Return the total number of tests. + * + * @memberof Mocha.Suite + * @public + * @api public + * @return {number} + */ +Suite.prototype.total = function() { + return ( + this.suites.reduce(function(sum, suite) { + return sum + suite.total(); + }, 0) + this.tests.length + ); +}; + +/** + * Iterates through each suite recursively to find all tests. Applies a + * function in the format `fn(test)`. + * + * @api private + * @param {Function} fn + * @return {Suite} + */ +Suite.prototype.eachTest = function(fn) { + this.tests.forEach(fn); + this.suites.forEach(function(suite) { + suite.eachTest(fn); + }); + return this; +}; + +/** + * This will run the root suite if we happen to be running in delayed mode. + */ +Suite.prototype.run = function run() { + if (this.root) { + this.emit('run'); + } +}; + +},{"./hook":6,"./ms":14,"./utils":36,"debug":43,"events":47}],35:[function(require,module,exports){ +'use strict'; +var Runnable = require('./runnable'); +var utils = require('./utils'); +var isString = utils.isString; + +module.exports = Test; + +/** + * Initialize a new `Test` with the given `title` and callback `fn`. + * + * @class + * @extends Runnable + * @param {String} title + * @param {Function} fn + */ +function Test(title, fn) { + if (!isString(title)) { + throw new Error( + 'Test `title` should be a "string" but "' + + typeof title + + '" was given instead.' + ); + } + Runnable.call(this, title, fn); + this.pending = !fn; + this.type = 'test'; +} + +/** + * Inherit from `Runnable.prototype`. + */ +utils.inherits(Test, Runnable); + +Test.prototype.clone = function() { + var test = new Test(this.title, this.fn); + test.timeout(this.timeout()); + test.slow(this.slow()); + test.enableTimeouts(this.enableTimeouts()); + test.retries(this.retries()); + test.currentRetry(this.currentRetry()); + test.globals(this.globals()); + test.parent = this.parent; + test.file = this.file; + test.ctx = this.ctx; + return test; +}; + +},{"./runnable":32,"./utils":36}],36:[function(require,module,exports){ +(function (process,Buffer){ +'use strict'; + +/** + * @module + */ + +/** + * Module dependencies. + */ + +var debug = require('debug')('mocha:watch'); +var fs = require('fs'); +var glob = require('glob'); +var path = require('path'); +var join = path.join; +var he = require('he'); + +/** + * Ignored directories. + */ + +var ignore = ['node_modules', '.git']; + +exports.inherits = require('util').inherits; + +/** + * Escape special characters in the given string of html. + * + * @api private + * @param {string} html + * @return {string} + */ +exports.escape = function(html) { + return he.encode(String(html), {useNamedReferences: false}); +}; + +/** + * Test if the given obj is type of string. + * + * @api private + * @param {Object} obj + * @return {boolean} + */ +exports.isString = function(obj) { + return typeof obj === 'string'; +}; + +/** + * Watch the given `files` for changes + * and invoke `fn(file)` on modification. + * + * @api private + * @param {Array} files + * @param {Function} fn + */ +exports.watch = function(files, fn) { + var options = {interval: 100}; + files.forEach(function(file) { + debug('file %s', file); + fs.watchFile(file, options, function(curr, prev) { + if (prev.mtime < curr.mtime) { + fn(file); + } + }); + }); +}; + +/** + * Ignored files. + * + * @api private + * @param {string} path + * @return {boolean} + */ +function ignored(path) { + return !~ignore.indexOf(path); +} + +/** + * Lookup files in the given `dir`. + * + * @api private + * @param {string} dir + * @param {string[]} [ext=['.js']] + * @param {Array} [ret=[]] + * @return {Array} + */ +exports.files = function(dir, ext, ret) { + ret = ret || []; + ext = ext || ['js']; + + var re = new RegExp('\\.(' + ext.join('|') + ')$'); + + fs + .readdirSync(dir) + .filter(ignored) + .forEach(function(path) { + path = join(dir, path); + if (fs.lstatSync(path).isDirectory()) { + exports.files(path, ext, ret); + } else if (path.match(re)) { + ret.push(path); + } + }); + + return ret; +}; + +/** + * Compute a slug from the given `str`. + * + * @api private + * @param {string} str + * @return {string} + */ +exports.slug = function(str) { + return str + .toLowerCase() + .replace(/ +/g, '-') + .replace(/[^-\w]/g, ''); +}; + +/** + * Strip the function definition from `str`, and re-indent for pre whitespace. + * + * @param {string} str + * @return {string} + */ +exports.clean = function(str) { + str = str + .replace(/\r\n?|[\n\u2028\u2029]/g, '\n') + .replace(/^\uFEFF/, '') + // (traditional)-> space/name parameters body (lambda)-> parameters body multi-statement/single keep body content + .replace( + /^function(?:\s*|\s+[^(]*)\([^)]*\)\s*\{((?:.|\n)*?)\s*\}$|^\([^)]*\)\s*=>\s*(?:\{((?:.|\n)*?)\s*\}|((?:.|\n)*))$/, + '$1$2$3' + ); + + var spaces = str.match(/^\n?( *)/)[1].length; + var tabs = str.match(/^\n?(\t*)/)[1].length; + var re = new RegExp( + '^\n?' + (tabs ? '\t' : ' ') + '{' + (tabs || spaces) + '}', + 'gm' + ); + + str = str.replace(re, ''); + + return str.trim(); +}; + +/** + * Parse the given `qs`. + * + * @api private + * @param {string} qs + * @return {Object} + */ +exports.parseQuery = function(qs) { + return qs + .replace('?', '') + .split('&') + .reduce(function(obj, pair) { + var i = pair.indexOf('='); + var key = pair.slice(0, i); + var val = pair.slice(++i); + + // Due to how the URLSearchParams API treats spaces + obj[key] = decodeURIComponent(val.replace(/\+/g, '%20')); + + return obj; + }, {}); +}; + +/** + * Highlight the given string of `js`. + * + * @api private + * @param {string} js + * @return {string} + */ +function highlight(js) { + return js + .replace(//g, '>') + .replace(/\/\/(.*)/gm, '//$1') + .replace(/('.*?')/gm, '$1') + .replace(/(\d+\.\d+)/gm, '$1') + .replace(/(\d+)/gm, '$1') + .replace( + /\bnew[ \t]+(\w+)/gm, + 'new $1' + ) + .replace( + /\b(function|new|throw|return|var|if|else)\b/gm, + '$1' + ); +} + +/** + * Highlight the contents of tag `name`. + * + * @api private + * @param {string} name + */ +exports.highlightTags = function(name) { + var code = document.getElementById('mocha').getElementsByTagName(name); + for (var i = 0, len = code.length; i < len; ++i) { + code[i].innerHTML = highlight(code[i].innerHTML); + } +}; + +/** + * If a value could have properties, and has none, this function is called, + * which returns a string representation of the empty value. + * + * Functions w/ no properties return `'[Function]'` + * Arrays w/ length === 0 return `'[]'` + * Objects w/ no properties return `'{}'` + * All else: return result of `value.toString()` + * + * @api private + * @param {*} value The value to inspect. + * @param {string} typeHint The type of the value + * @returns {string} + */ +function emptyRepresentation(value, typeHint) { + switch (typeHint) { + case 'function': + return '[Function]'; + case 'object': + return '{}'; + case 'array': + return '[]'; + default: + return value.toString(); + } +} + +/** + * Takes some variable and asks `Object.prototype.toString()` what it thinks it + * is. + * + * @api private + * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/toString + * @param {*} value The value to test. + * @returns {string} Computed type + * @example + * type({}) // 'object' + * type([]) // 'array' + * type(1) // 'number' + * type(false) // 'boolean' + * type(Infinity) // 'number' + * type(null) // 'null' + * type(new Date()) // 'date' + * type(/foo/) // 'regexp' + * type('type') // 'string' + * type(global) // 'global' + * type(new String('foo') // 'object' + */ +var type = (exports.type = function type(value) { + if (value === undefined) { + return 'undefined'; + } else if (value === null) { + return 'null'; + } else if (Buffer.isBuffer(value)) { + return 'buffer'; + } + return Object.prototype.toString + .call(value) + .replace(/^\[.+\s(.+?)]$/, '$1') + .toLowerCase(); +}); + +/** + * Stringify `value`. Different behavior depending on type of value: + * + * - If `value` is undefined or null, return `'[undefined]'` or `'[null]'`, respectively. + * - If `value` is not an object, function or array, return result of `value.toString()` wrapped in double-quotes. + * - If `value` is an *empty* object, function, or array, return result of function + * {@link emptyRepresentation}. + * - If `value` has properties, call {@link exports.canonicalize} on it, then return result of + * JSON.stringify(). + * + * @api private + * @see exports.type + * @param {*} value + * @return {string} + */ +exports.stringify = function(value) { + var typeHint = type(value); + + if (!~['object', 'array', 'function'].indexOf(typeHint)) { + if (typeHint === 'buffer') { + var json = Buffer.prototype.toJSON.call(value); + // Based on the toJSON result + return jsonStringify( + json.data && json.type ? json.data : json, + 2 + ).replace(/,(\n|$)/g, '$1'); + } + + // IE7/IE8 has a bizarre String constructor; needs to be coerced + // into an array and back to obj. + if (typeHint === 'string' && typeof value === 'object') { + value = value.split('').reduce(function(acc, char, idx) { + acc[idx] = char; + return acc; + }, {}); + typeHint = 'object'; + } else { + return jsonStringify(value); + } + } + + for (var prop in value) { + if (Object.prototype.hasOwnProperty.call(value, prop)) { + return jsonStringify( + exports.canonicalize(value, null, typeHint), + 2 + ).replace(/,(\n|$)/g, '$1'); + } + } + + return emptyRepresentation(value, typeHint); +}; + +/** + * like JSON.stringify but more sense. + * + * @api private + * @param {Object} object + * @param {number=} spaces + * @param {number=} depth + * @returns {*} + */ +function jsonStringify(object, spaces, depth) { + if (typeof spaces === 'undefined') { + // primitive types + return _stringify(object); + } + + depth = depth || 1; + var space = spaces * depth; + var str = Array.isArray(object) ? '[' : '{'; + var end = Array.isArray(object) ? ']' : '}'; + var length = + typeof object.length === 'number' + ? object.length + : Object.keys(object).length; + // `.repeat()` polyfill + function repeat(s, n) { + return new Array(n).join(s); + } + + function _stringify(val) { + switch (type(val)) { + case 'null': + case 'undefined': + val = '[' + val + ']'; + break; + case 'array': + case 'object': + val = jsonStringify(val, spaces, depth + 1); + break; + case 'boolean': + case 'regexp': + case 'symbol': + case 'number': + val = + val === 0 && 1 / val === -Infinity // `-0` + ? '-0' + : val.toString(); + break; + case 'date': + var sDate = isNaN(val.getTime()) ? val.toString() : val.toISOString(); + val = '[Date: ' + sDate + ']'; + break; + case 'buffer': + var json = val.toJSON(); + // Based on the toJSON result + json = json.data && json.type ? json.data : json; + val = '[Buffer: ' + jsonStringify(json, 2, depth + 1) + ']'; + break; + default: + val = + val === '[Function]' || val === '[Circular]' + ? val + : JSON.stringify(val); // string + } + return val; + } + + for (var i in object) { + if (!Object.prototype.hasOwnProperty.call(object, i)) { + continue; // not my business + } + --length; + str += + '\n ' + + repeat(' ', space) + + (Array.isArray(object) ? '' : '"' + i + '": ') + // key + _stringify(object[i]) + // value + (length ? ',' : ''); // comma + } + + return ( + str + + // [], {} + (str.length !== 1 ? '\n' + repeat(' ', --space) + end : end) + ); +} + +/** + * Return a new Thing that has the keys in sorted order. Recursive. + * + * If the Thing... + * - has already been seen, return string `'[Circular]'` + * - is `undefined`, return string `'[undefined]'` + * - is `null`, return value `null` + * - is some other primitive, return the value + * - is not a primitive or an `Array`, `Object`, or `Function`, return the value of the Thing's `toString()` method + * - is a non-empty `Array`, `Object`, or `Function`, return the result of calling this function again. + * - is an empty `Array`, `Object`, or `Function`, return the result of calling `emptyRepresentation()` + * + * @api private + * @see {@link exports.stringify} + * @param {*} value Thing to inspect. May or may not have properties. + * @param {Array} [stack=[]] Stack of seen values + * @param {string} [typeHint] Type hint + * @return {(Object|Array|Function|string|undefined)} + */ +exports.canonicalize = function canonicalize(value, stack, typeHint) { + var canonicalizedObj; + /* eslint-disable no-unused-vars */ + var prop; + /* eslint-enable no-unused-vars */ + typeHint = typeHint || type(value); + function withStack(value, fn) { + stack.push(value); + fn(); + stack.pop(); + } + + stack = stack || []; + + if (stack.indexOf(value) !== -1) { + return '[Circular]'; + } + + switch (typeHint) { + case 'undefined': + case 'buffer': + case 'null': + canonicalizedObj = value; + break; + case 'array': + withStack(value, function() { + canonicalizedObj = value.map(function(item) { + return exports.canonicalize(item, stack); + }); + }); + break; + case 'function': + /* eslint-disable guard-for-in */ + for (prop in value) { + canonicalizedObj = {}; + break; + } + /* eslint-enable guard-for-in */ + if (!canonicalizedObj) { + canonicalizedObj = emptyRepresentation(value, typeHint); + break; + } + /* falls through */ + case 'object': + canonicalizedObj = canonicalizedObj || {}; + withStack(value, function() { + Object.keys(value) + .sort() + .forEach(function(key) { + canonicalizedObj[key] = exports.canonicalize(value[key], stack); + }); + }); + break; + case 'date': + case 'number': + case 'regexp': + case 'boolean': + case 'symbol': + canonicalizedObj = value; + break; + default: + canonicalizedObj = value + ''; + } + + return canonicalizedObj; +}; + +/** + * Lookup file names at the given `path`. + * + * @memberof Mocha.utils + * @public + * @api public + * @param {string} filepath Base path to start searching from. + * @param {string[]} extensions File extensions to look for. + * @param {boolean} recursive Whether or not to recurse into subdirectories. + * @return {string[]} An array of paths. + */ +exports.lookupFiles = function lookupFiles(filepath, extensions, recursive) { + var files = []; + + if (!fs.existsSync(filepath)) { + if (fs.existsSync(filepath + '.js')) { + filepath += '.js'; + } else { + files = glob.sync(filepath); + if (!files.length) { + throw new Error("cannot resolve path (or pattern) '" + filepath + "'"); + } + return files; + } + } + + try { + var stat = fs.statSync(filepath); + if (stat.isFile()) { + return filepath; + } + } catch (err) { + // ignore error + return; + } + + fs.readdirSync(filepath).forEach(function(file) { + file = path.join(filepath, file); + try { + var stat = fs.statSync(file); + if (stat.isDirectory()) { + if (recursive) { + files = files.concat(lookupFiles(file, extensions, recursive)); + } + return; + } + } catch (err) { + // ignore error + return; + } + if (!extensions) { + throw new Error( + 'extensions parameter required when filepath is a directory' + ); + } + var re = new RegExp('\\.(?:' + extensions.join('|') + ')$'); + if (!stat.isFile() || !re.test(file) || path.basename(file)[0] === '.') { + return; + } + files.push(file); + }); + + return files; +}; + +/** + * Generate an undefined error with a message warning the user. + * + * @return {Error} + */ + +exports.undefinedError = function() { + return new Error( + 'Caught undefined error, did you throw without specifying what?' + ); +}; + +/** + * Generate an undefined error if `err` is not defined. + * + * @param {Error} err + * @return {Error} + */ + +exports.getError = function(err) { + return err || exports.undefinedError(); +}; + +/** + * @summary + * This Filter based on `mocha-clean` module.(see: `github.com/rstacruz/mocha-clean`) + * @description + * When invoking this function you get a filter function that get the Error.stack as an input, + * and return a prettify output. + * (i.e: strip Mocha and internal node functions from stack trace). + * @returns {Function} + */ +exports.stackTraceFilter = function() { + // TODO: Replace with `process.browser` + var is = typeof document === 'undefined' ? {node: true} : {browser: true}; + var slash = path.sep; + var cwd; + if (is.node) { + cwd = process.cwd() + slash; + } else { + cwd = (typeof location === 'undefined' + ? window.location + : location + ).href.replace(/\/[^/]*$/, '/'); + slash = '/'; + } + + function isMochaInternal(line) { + return ( + ~line.indexOf('node_modules' + slash + 'mocha' + slash) || + ~line.indexOf('node_modules' + slash + 'mocha.js') || + ~line.indexOf('bower_components' + slash + 'mocha.js') || + ~line.indexOf(slash + 'mocha.js') + ); + } + + function isNodeInternal(line) { + return ( + ~line.indexOf('(timers.js:') || + ~line.indexOf('(events.js:') || + ~line.indexOf('(node.js:') || + ~line.indexOf('(module.js:') || + ~line.indexOf('GeneratorFunctionPrototype.next (native)') || + false + ); + } + + return function(stack) { + stack = stack.split('\n'); + + stack = stack.reduce(function(list, line) { + if (isMochaInternal(line)) { + return list; + } + + if (is.node && isNodeInternal(line)) { + return list; + } + + // Clean up cwd(absolute) + if (/\(?.+:\d+:\d+\)?$/.test(line)) { + line = line.replace('(' + cwd, '('); + } + + list.push(line); + return list; + }, []); + + return stack.join('\n'); + }; +}; + +/** + * Crude, but effective. + * @api + * @param {*} value + * @returns {boolean} Whether or not `value` is a Promise + */ +exports.isPromise = function isPromise(value) { + return typeof value === 'object' && typeof value.then === 'function'; +}; + +/** + * It's a noop. + * @api + */ +exports.noop = function() {}; + +}).call(this,require('_process'),require("buffer").Buffer) +},{"_process":56,"buffer":41,"debug":43,"fs":40,"glob":40,"he":48,"path":40,"util":76}],37:[function(require,module,exports){ +'use strict' + +exports.byteLength = byteLength +exports.toByteArray = toByteArray +exports.fromByteArray = fromByteArray + +var lookup = [] +var revLookup = [] +var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array + +var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' +for (var i = 0, len = code.length; i < len; ++i) { + lookup[i] = code[i] + revLookup[code.charCodeAt(i)] = i +} + +// Support decoding URL-safe base64 strings, as Node.js does. +// See: https://en.wikipedia.org/wiki/Base64#URL_applications +revLookup['-'.charCodeAt(0)] = 62 +revLookup['_'.charCodeAt(0)] = 63 + +function getLens (b64) { + var len = b64.length + + if (len % 4 > 0) { + throw new Error('Invalid string. Length must be a multiple of 4') + } + + // Trim off extra bytes after placeholder bytes are found + // See: https://github.com/beatgammit/base64-js/issues/42 + var validLen = b64.indexOf('=') + if (validLen === -1) validLen = len + + var placeHoldersLen = validLen === len + ? 0 + : 4 - (validLen % 4) + + return [validLen, placeHoldersLen] +} + +// base64 is 4/3 + up to two characters of the original data +function byteLength (b64) { + var lens = getLens(b64) + var validLen = lens[0] + var placeHoldersLen = lens[1] + return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen +} + +function _byteLength (b64, validLen, placeHoldersLen) { + return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen +} + +function toByteArray (b64) { + var tmp + var lens = getLens(b64) + var validLen = lens[0] + var placeHoldersLen = lens[1] + + var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen)) + + var curByte = 0 + + // if there are placeholders, only get up to the last complete 4 chars + var len = placeHoldersLen > 0 + ? validLen - 4 + : validLen + + for (var i = 0; i < len; i += 4) { + tmp = + (revLookup[b64.charCodeAt(i)] << 18) | + (revLookup[b64.charCodeAt(i + 1)] << 12) | + (revLookup[b64.charCodeAt(i + 2)] << 6) | + revLookup[b64.charCodeAt(i + 3)] + arr[curByte++] = (tmp >> 16) & 0xFF + arr[curByte++] = (tmp >> 8) & 0xFF + arr[curByte++] = tmp & 0xFF + } + + if (placeHoldersLen === 2) { + tmp = + (revLookup[b64.charCodeAt(i)] << 2) | + (revLookup[b64.charCodeAt(i + 1)] >> 4) + arr[curByte++] = tmp & 0xFF + } + + if (placeHoldersLen === 1) { + tmp = + (revLookup[b64.charCodeAt(i)] << 10) | + (revLookup[b64.charCodeAt(i + 1)] << 4) | + (revLookup[b64.charCodeAt(i + 2)] >> 2) + arr[curByte++] = (tmp >> 8) & 0xFF + arr[curByte++] = tmp & 0xFF + } + + return arr +} + +function tripletToBase64 (num) { + return lookup[num >> 18 & 0x3F] + + lookup[num >> 12 & 0x3F] + + lookup[num >> 6 & 0x3F] + + lookup[num & 0x3F] +} + +function encodeChunk (uint8, start, end) { + var tmp + var output = [] + for (var i = start; i < end; i += 3) { + tmp = + ((uint8[i] << 16) & 0xFF0000) + + ((uint8[i + 1] << 8) & 0xFF00) + + (uint8[i + 2] & 0xFF) + output.push(tripletToBase64(tmp)) + } + return output.join('') +} + +function fromByteArray (uint8) { + var tmp + var len = uint8.length + var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes + var parts = [] + var maxChunkLength = 16383 // must be multiple of 3 + + // go through the array every three bytes, we'll deal with trailing stuff later + for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { + parts.push(encodeChunk( + uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength) + )) + } + + // pad the end with zeros, but make sure to not forget the extra bytes + if (extraBytes === 1) { + tmp = uint8[len - 1] + parts.push( + lookup[tmp >> 2] + + lookup[(tmp << 4) & 0x3F] + + '==' + ) + } else if (extraBytes === 2) { + tmp = (uint8[len - 2] << 8) + uint8[len - 1] + parts.push( + lookup[tmp >> 10] + + lookup[(tmp >> 4) & 0x3F] + + lookup[(tmp << 2) & 0x3F] + + '=' + ) + } + + return parts.join('') +} + +},{}],38:[function(require,module,exports){ + +},{}],39:[function(require,module,exports){ +(function (process){ +var WritableStream = require('stream').Writable +var inherits = require('util').inherits + +module.exports = BrowserStdout + + +inherits(BrowserStdout, WritableStream) + +function BrowserStdout(opts) { + if (!(this instanceof BrowserStdout)) return new BrowserStdout(opts) + + opts = opts || {} + WritableStream.call(this, opts) + this.label = (opts.label !== undefined) ? opts.label : 'stdout' +} + +BrowserStdout.prototype._write = function(chunks, encoding, cb) { + var output = chunks.toString ? chunks.toString() : chunks + if (this.label === false) { + console.log(output) + } else { + console.log(this.label+':', output) + } + process.nextTick(cb) +} + +}).call(this,require('_process')) +},{"_process":56,"stream":71,"util":76}],40:[function(require,module,exports){ +arguments[4][38][0].apply(exports,arguments) +},{"dup":38}],41:[function(require,module,exports){ +/*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh + * @license MIT + */ +/* eslint-disable no-proto */ + +'use strict' + +var base64 = require('base64-js') +var ieee754 = require('ieee754') + +exports.Buffer = Buffer +exports.SlowBuffer = SlowBuffer +exports.INSPECT_MAX_BYTES = 50 + +var K_MAX_LENGTH = 0x7fffffff +exports.kMaxLength = K_MAX_LENGTH + +/** + * If `Buffer.TYPED_ARRAY_SUPPORT`: + * === true Use Uint8Array implementation (fastest) + * === false Print warning and recommend using `buffer` v4.x which has an Object + * implementation (most compatible, even IE6) + * + * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, + * Opera 11.6+, iOS 4.2+. + * + * We report that the browser does not support typed arrays if the are not subclassable + * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array` + * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support + * for __proto__ and has a buggy typed array implementation. + */ +Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport() + +if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' && + typeof console.error === 'function') { + console.error( + 'This browser lacks typed array (Uint8Array) support which is required by ' + + '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.' + ) +} + +function typedArraySupport () { + // Can typed array instances can be augmented? + try { + var arr = new Uint8Array(1) + arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }} + return arr.foo() === 42 + } catch (e) { + return false + } +} + +Object.defineProperty(Buffer.prototype, 'parent', { + get: function () { + if (!(this instanceof Buffer)) { + return undefined + } + return this.buffer + } +}) + +Object.defineProperty(Buffer.prototype, 'offset', { + get: function () { + if (!(this instanceof Buffer)) { + return undefined + } + return this.byteOffset + } +}) + +function createBuffer (length) { + if (length > K_MAX_LENGTH) { + throw new RangeError('Invalid typed array length') + } + // Return an augmented `Uint8Array` instance + var buf = new Uint8Array(length) + buf.__proto__ = Buffer.prototype + return buf +} + +/** + * The Buffer constructor returns instances of `Uint8Array` that have their + * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of + * `Uint8Array`, so the returned instances will have all the node `Buffer` methods + * and the `Uint8Array` methods. Square bracket notation works as expected -- it + * returns a single octet. + * + * The `Uint8Array` prototype remains unmodified. + */ + +function Buffer (arg, encodingOrOffset, length) { + // Common case. + if (typeof arg === 'number') { + if (typeof encodingOrOffset === 'string') { + throw new Error( + 'If encoding is specified then the first argument must be a string' + ) + } + return allocUnsafe(arg) + } + return from(arg, encodingOrOffset, length) +} + +// Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97 +if (typeof Symbol !== 'undefined' && Symbol.species && + Buffer[Symbol.species] === Buffer) { + Object.defineProperty(Buffer, Symbol.species, { + value: null, + configurable: true, + enumerable: false, + writable: false + }) +} + +Buffer.poolSize = 8192 // not used by this implementation + +function from (value, encodingOrOffset, length) { + if (typeof value === 'number') { + throw new TypeError('"value" argument must not be a number') + } + + if (isArrayBuffer(value) || (value && isArrayBuffer(value.buffer))) { + return fromArrayBuffer(value, encodingOrOffset, length) + } + + if (typeof value === 'string') { + return fromString(value, encodingOrOffset) + } + + return fromObject(value) +} + +/** + * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError + * if value is a number. + * Buffer.from(str[, encoding]) + * Buffer.from(array) + * Buffer.from(buffer) + * Buffer.from(arrayBuffer[, byteOffset[, length]]) + **/ +Buffer.from = function (value, encodingOrOffset, length) { + return from(value, encodingOrOffset, length) +} + +// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug: +// https://github.com/feross/buffer/pull/148 +Buffer.prototype.__proto__ = Uint8Array.prototype +Buffer.__proto__ = Uint8Array + +function assertSize (size) { + if (typeof size !== 'number') { + throw new TypeError('"size" argument must be of type number') + } else if (size < 0) { + throw new RangeError('"size" argument must not be negative') + } +} + +function alloc (size, fill, encoding) { + assertSize(size) + if (size <= 0) { + return createBuffer(size) + } + if (fill !== undefined) { + // Only pay attention to encoding if it's a string. This + // prevents accidentally sending in a number that would + // be interpretted as a start offset. + return typeof encoding === 'string' + ? createBuffer(size).fill(fill, encoding) + : createBuffer(size).fill(fill) + } + return createBuffer(size) +} + +/** + * Creates a new filled Buffer instance. + * alloc(size[, fill[, encoding]]) + **/ +Buffer.alloc = function (size, fill, encoding) { + return alloc(size, fill, encoding) +} + +function allocUnsafe (size) { + assertSize(size) + return createBuffer(size < 0 ? 0 : checked(size) | 0) +} + +/** + * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. + * */ +Buffer.allocUnsafe = function (size) { + return allocUnsafe(size) +} +/** + * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. + */ +Buffer.allocUnsafeSlow = function (size) { + return allocUnsafe(size) +} + +function fromString (string, encoding) { + if (typeof encoding !== 'string' || encoding === '') { + encoding = 'utf8' + } + + if (!Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } + + var length = byteLength(string, encoding) | 0 + var buf = createBuffer(length) + + var actual = buf.write(string, encoding) + + if (actual !== length) { + // Writing a hex string, for example, that contains invalid characters will + // cause everything after the first invalid character to be ignored. (e.g. + // 'abxxcd' will be treated as 'ab') + buf = buf.slice(0, actual) + } + + return buf +} + +function fromArrayLike (array) { + var length = array.length < 0 ? 0 : checked(array.length) | 0 + var buf = createBuffer(length) + for (var i = 0; i < length; i += 1) { + buf[i] = array[i] & 255 + } + return buf +} + +function fromArrayBuffer (array, byteOffset, length) { + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError('"offset" is outside of buffer bounds') + } + + if (array.byteLength < byteOffset + (length || 0)) { + throw new RangeError('"length" is outside of buffer bounds') + } + + var buf + if (byteOffset === undefined && length === undefined) { + buf = new Uint8Array(array) + } else if (length === undefined) { + buf = new Uint8Array(array, byteOffset) + } else { + buf = new Uint8Array(array, byteOffset, length) + } + + // Return an augmented `Uint8Array` instance + buf.__proto__ = Buffer.prototype + return buf +} + +function fromObject (obj) { + if (Buffer.isBuffer(obj)) { + var len = checked(obj.length) | 0 + var buf = createBuffer(len) + + if (buf.length === 0) { + return buf + } + + obj.copy(buf, 0, 0, len) + return buf + } + + if (obj) { + if (ArrayBuffer.isView(obj) || 'length' in obj) { + if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) { + return createBuffer(0) + } + return fromArrayLike(obj) + } + + if (obj.type === 'Buffer' && Array.isArray(obj.data)) { + return fromArrayLike(obj.data) + } + } + + throw new TypeError('The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object.') +} + +function checked (length) { + // Note: cannot use `length < K_MAX_LENGTH` here because that fails when + // length is NaN (which is otherwise coerced to zero.) + if (length >= K_MAX_LENGTH) { + throw new RangeError('Attempt to allocate Buffer larger than maximum ' + + 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes') + } + return length | 0 +} + +function SlowBuffer (length) { + if (+length != length) { // eslint-disable-line eqeqeq + length = 0 + } + return Buffer.alloc(+length) +} + +Buffer.isBuffer = function isBuffer (b) { + return b != null && b._isBuffer === true +} + +Buffer.compare = function compare (a, b) { + if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { + throw new TypeError('Arguments must be Buffers') + } + + if (a === b) return 0 + + var x = a.length + var y = b.length + + for (var i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i] + y = b[i] + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 +} + +Buffer.isEncoding = function isEncoding (encoding) { + switch (String(encoding).toLowerCase()) { + case 'hex': + case 'utf8': + case 'utf-8': + case 'ascii': + case 'latin1': + case 'binary': + case 'base64': + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return true + default: + return false + } +} + +Buffer.concat = function concat (list, length) { + if (!Array.isArray(list)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + + if (list.length === 0) { + return Buffer.alloc(0) + } + + var i + if (length === undefined) { + length = 0 + for (i = 0; i < list.length; ++i) { + length += list[i].length + } + } + + var buffer = Buffer.allocUnsafe(length) + var pos = 0 + for (i = 0; i < list.length; ++i) { + var buf = list[i] + if (ArrayBuffer.isView(buf)) { + buf = Buffer.from(buf) + } + if (!Buffer.isBuffer(buf)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + buf.copy(buffer, pos) + pos += buf.length + } + return buffer +} + +function byteLength (string, encoding) { + if (Buffer.isBuffer(string)) { + return string.length + } + if (ArrayBuffer.isView(string) || isArrayBuffer(string)) { + return string.byteLength + } + if (typeof string !== 'string') { + string = '' + string + } + + var len = string.length + if (len === 0) return 0 + + // Use a for loop to avoid recursion + var loweredCase = false + for (;;) { + switch (encoding) { + case 'ascii': + case 'latin1': + case 'binary': + return len + case 'utf8': + case 'utf-8': + case undefined: + return utf8ToBytes(string).length + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return len * 2 + case 'hex': + return len >>> 1 + case 'base64': + return base64ToBytes(string).length + default: + if (loweredCase) return utf8ToBytes(string).length // assume utf8 + encoding = ('' + encoding).toLowerCase() + loweredCase = true + } + } +} +Buffer.byteLength = byteLength + +function slowToString (encoding, start, end) { + var loweredCase = false + + // No need to verify that "this.length <= MAX_UINT32" since it's a read-only + // property of a typed array. + + // This behaves neither like String nor Uint8Array in that we set start/end + // to their upper/lower bounds if the value passed is out of range. + // undefined is handled specially as per ECMA-262 6th Edition, + // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. + if (start === undefined || start < 0) { + start = 0 + } + // Return early if start > this.length. Done here to prevent potential uint32 + // coercion fail below. + if (start > this.length) { + return '' + } + + if (end === undefined || end > this.length) { + end = this.length + } + + if (end <= 0) { + return '' + } + + // Force coersion to uint32. This will also coerce falsey/NaN values to 0. + end >>>= 0 + start >>>= 0 + + if (end <= start) { + return '' + } + + if (!encoding) encoding = 'utf8' + + while (true) { + switch (encoding) { + case 'hex': + return hexSlice(this, start, end) + + case 'utf8': + case 'utf-8': + return utf8Slice(this, start, end) + + case 'ascii': + return asciiSlice(this, start, end) + + case 'latin1': + case 'binary': + return latin1Slice(this, start, end) + + case 'base64': + return base64Slice(this, start, end) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return utf16leSlice(this, start, end) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = (encoding + '').toLowerCase() + loweredCase = true + } + } +} + +// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package) +// to detect a Buffer instance. It's not possible to use `instanceof Buffer` +// reliably in a browserify context because there could be multiple different +// copies of the 'buffer' package in use. This method works even for Buffer +// instances that were created from another copy of the `buffer` package. +// See: https://github.com/feross/buffer/issues/154 +Buffer.prototype._isBuffer = true + +function swap (b, n, m) { + var i = b[n] + b[n] = b[m] + b[m] = i +} + +Buffer.prototype.swap16 = function swap16 () { + var len = this.length + if (len % 2 !== 0) { + throw new RangeError('Buffer size must be a multiple of 16-bits') + } + for (var i = 0; i < len; i += 2) { + swap(this, i, i + 1) + } + return this +} + +Buffer.prototype.swap32 = function swap32 () { + var len = this.length + if (len % 4 !== 0) { + throw new RangeError('Buffer size must be a multiple of 32-bits') + } + for (var i = 0; i < len; i += 4) { + swap(this, i, i + 3) + swap(this, i + 1, i + 2) + } + return this +} + +Buffer.prototype.swap64 = function swap64 () { + var len = this.length + if (len % 8 !== 0) { + throw new RangeError('Buffer size must be a multiple of 64-bits') + } + for (var i = 0; i < len; i += 8) { + swap(this, i, i + 7) + swap(this, i + 1, i + 6) + swap(this, i + 2, i + 5) + swap(this, i + 3, i + 4) + } + return this +} + +Buffer.prototype.toString = function toString () { + var length = this.length + if (length === 0) return '' + if (arguments.length === 0) return utf8Slice(this, 0, length) + return slowToString.apply(this, arguments) +} + +Buffer.prototype.toLocaleString = Buffer.prototype.toString + +Buffer.prototype.equals = function equals (b) { + if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') + if (this === b) return true + return Buffer.compare(this, b) === 0 +} + +Buffer.prototype.inspect = function inspect () { + var str = '' + var max = exports.INSPECT_MAX_BYTES + if (this.length > 0) { + str = this.toString('hex', 0, max).match(/.{2}/g).join(' ') + if (this.length > max) str += ' ... ' + } + return '' +} + +Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { + if (!Buffer.isBuffer(target)) { + throw new TypeError('Argument must be a Buffer') + } + + if (start === undefined) { + start = 0 + } + if (end === undefined) { + end = target ? target.length : 0 + } + if (thisStart === undefined) { + thisStart = 0 + } + if (thisEnd === undefined) { + thisEnd = this.length + } + + if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { + throw new RangeError('out of range index') + } + + if (thisStart >= thisEnd && start >= end) { + return 0 + } + if (thisStart >= thisEnd) { + return -1 + } + if (start >= end) { + return 1 + } + + start >>>= 0 + end >>>= 0 + thisStart >>>= 0 + thisEnd >>>= 0 + + if (this === target) return 0 + + var x = thisEnd - thisStart + var y = end - start + var len = Math.min(x, y) + + var thisCopy = this.slice(thisStart, thisEnd) + var targetCopy = target.slice(start, end) + + for (var i = 0; i < len; ++i) { + if (thisCopy[i] !== targetCopy[i]) { + x = thisCopy[i] + y = targetCopy[i] + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 +} + +// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, +// OR the last index of `val` in `buffer` at offset <= `byteOffset`. +// +// Arguments: +// - buffer - a Buffer to search +// - val - a string, Buffer, or number +// - byteOffset - an index into `buffer`; will be clamped to an int32 +// - encoding - an optional encoding, relevant is val is a string +// - dir - true for indexOf, false for lastIndexOf +function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { + // Empty buffer means no match + if (buffer.length === 0) return -1 + + // Normalize byteOffset + if (typeof byteOffset === 'string') { + encoding = byteOffset + byteOffset = 0 + } else if (byteOffset > 0x7fffffff) { + byteOffset = 0x7fffffff + } else if (byteOffset < -0x80000000) { + byteOffset = -0x80000000 + } + byteOffset = +byteOffset // Coerce to Number. + if (numberIsNaN(byteOffset)) { + // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer + byteOffset = dir ? 0 : (buffer.length - 1) + } + + // Normalize byteOffset: negative offsets start from the end of the buffer + if (byteOffset < 0) byteOffset = buffer.length + byteOffset + if (byteOffset >= buffer.length) { + if (dir) return -1 + else byteOffset = buffer.length - 1 + } else if (byteOffset < 0) { + if (dir) byteOffset = 0 + else return -1 + } + + // Normalize val + if (typeof val === 'string') { + val = Buffer.from(val, encoding) + } + + // Finally, search either indexOf (if dir is true) or lastIndexOf + if (Buffer.isBuffer(val)) { + // Special case: looking for empty string/buffer always fails + if (val.length === 0) { + return -1 + } + return arrayIndexOf(buffer, val, byteOffset, encoding, dir) + } else if (typeof val === 'number') { + val = val & 0xFF // Search for a byte value [0-255] + if (typeof Uint8Array.prototype.indexOf === 'function') { + if (dir) { + return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) + } else { + return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) + } + } + return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) + } + + throw new TypeError('val must be string, number or Buffer') +} + +function arrayIndexOf (arr, val, byteOffset, encoding, dir) { + var indexSize = 1 + var arrLength = arr.length + var valLength = val.length + + if (encoding !== undefined) { + encoding = String(encoding).toLowerCase() + if (encoding === 'ucs2' || encoding === 'ucs-2' || + encoding === 'utf16le' || encoding === 'utf-16le') { + if (arr.length < 2 || val.length < 2) { + return -1 + } + indexSize = 2 + arrLength /= 2 + valLength /= 2 + byteOffset /= 2 + } + } + + function read (buf, i) { + if (indexSize === 1) { + return buf[i] + } else { + return buf.readUInt16BE(i * indexSize) + } + } + + var i + if (dir) { + var foundIndex = -1 + for (i = byteOffset; i < arrLength; i++) { + if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { + if (foundIndex === -1) foundIndex = i + if (i - foundIndex + 1 === valLength) return foundIndex * indexSize + } else { + if (foundIndex !== -1) i -= i - foundIndex + foundIndex = -1 + } + } + } else { + if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength + for (i = byteOffset; i >= 0; i--) { + var found = true + for (var j = 0; j < valLength; j++) { + if (read(arr, i + j) !== read(val, j)) { + found = false + break + } + } + if (found) return i + } + } + + return -1 +} + +Buffer.prototype.includes = function includes (val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1 +} + +Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, true) +} + +Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, false) +} + +function hexWrite (buf, string, offset, length) { + offset = Number(offset) || 0 + var remaining = buf.length - offset + if (!length) { + length = remaining + } else { + length = Number(length) + if (length > remaining) { + length = remaining + } + } + + var strLen = string.length + + if (length > strLen / 2) { + length = strLen / 2 + } + for (var i = 0; i < length; ++i) { + var parsed = parseInt(string.substr(i * 2, 2), 16) + if (numberIsNaN(parsed)) return i + buf[offset + i] = parsed + } + return i +} + +function utf8Write (buf, string, offset, length) { + return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) +} + +function asciiWrite (buf, string, offset, length) { + return blitBuffer(asciiToBytes(string), buf, offset, length) +} + +function latin1Write (buf, string, offset, length) { + return asciiWrite(buf, string, offset, length) +} + +function base64Write (buf, string, offset, length) { + return blitBuffer(base64ToBytes(string), buf, offset, length) +} + +function ucs2Write (buf, string, offset, length) { + return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) +} + +Buffer.prototype.write = function write (string, offset, length, encoding) { + // Buffer#write(string) + if (offset === undefined) { + encoding = 'utf8' + length = this.length + offset = 0 + // Buffer#write(string, encoding) + } else if (length === undefined && typeof offset === 'string') { + encoding = offset + length = this.length + offset = 0 + // Buffer#write(string, offset[, length][, encoding]) + } else if (isFinite(offset)) { + offset = offset >>> 0 + if (isFinite(length)) { + length = length >>> 0 + if (encoding === undefined) encoding = 'utf8' + } else { + encoding = length + length = undefined + } + } else { + throw new Error( + 'Buffer.write(string, encoding, offset[, length]) is no longer supported' + ) + } + + var remaining = this.length - offset + if (length === undefined || length > remaining) length = remaining + + if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { + throw new RangeError('Attempt to write outside buffer bounds') + } + + if (!encoding) encoding = 'utf8' + + var loweredCase = false + for (;;) { + switch (encoding) { + case 'hex': + return hexWrite(this, string, offset, length) + + case 'utf8': + case 'utf-8': + return utf8Write(this, string, offset, length) + + case 'ascii': + return asciiWrite(this, string, offset, length) + + case 'latin1': + case 'binary': + return latin1Write(this, string, offset, length) + + case 'base64': + // Warning: maxLength not taken into account in base64Write + return base64Write(this, string, offset, length) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return ucs2Write(this, string, offset, length) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = ('' + encoding).toLowerCase() + loweredCase = true + } + } +} + +Buffer.prototype.toJSON = function toJSON () { + return { + type: 'Buffer', + data: Array.prototype.slice.call(this._arr || this, 0) + } +} + +function base64Slice (buf, start, end) { + if (start === 0 && end === buf.length) { + return base64.fromByteArray(buf) + } else { + return base64.fromByteArray(buf.slice(start, end)) + } +} + +function utf8Slice (buf, start, end) { + end = Math.min(buf.length, end) + var res = [] + + var i = start + while (i < end) { + var firstByte = buf[i] + var codePoint = null + var bytesPerSequence = (firstByte > 0xEF) ? 4 + : (firstByte > 0xDF) ? 3 + : (firstByte > 0xBF) ? 2 + : 1 + + if (i + bytesPerSequence <= end) { + var secondByte, thirdByte, fourthByte, tempCodePoint + + switch (bytesPerSequence) { + case 1: + if (firstByte < 0x80) { + codePoint = firstByte + } + break + case 2: + secondByte = buf[i + 1] + if ((secondByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F) + if (tempCodePoint > 0x7F) { + codePoint = tempCodePoint + } + } + break + case 3: + secondByte = buf[i + 1] + thirdByte = buf[i + 2] + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F) + if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { + codePoint = tempCodePoint + } + } + break + case 4: + secondByte = buf[i + 1] + thirdByte = buf[i + 2] + fourthByte = buf[i + 3] + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F) + if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { + codePoint = tempCodePoint + } + } + } + } + + if (codePoint === null) { + // we did not generate a valid codePoint so insert a + // replacement char (U+FFFD) and advance only 1 byte + codePoint = 0xFFFD + bytesPerSequence = 1 + } else if (codePoint > 0xFFFF) { + // encode to utf16 (surrogate pair dance) + codePoint -= 0x10000 + res.push(codePoint >>> 10 & 0x3FF | 0xD800) + codePoint = 0xDC00 | codePoint & 0x3FF + } + + res.push(codePoint) + i += bytesPerSequence + } + + return decodeCodePointsArray(res) +} + +// Based on http://stackoverflow.com/a/22747272/680742, the browser with +// the lowest limit is Chrome, with 0x10000 args. +// We go 1 magnitude less, for safety +var MAX_ARGUMENTS_LENGTH = 0x1000 + +function decodeCodePointsArray (codePoints) { + var len = codePoints.length + if (len <= MAX_ARGUMENTS_LENGTH) { + return String.fromCharCode.apply(String, codePoints) // avoid extra slice() + } + + // Decode in chunks to avoid "call stack size exceeded". + var res = '' + var i = 0 + while (i < len) { + res += String.fromCharCode.apply( + String, + codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) + ) + } + return res +} + +function asciiSlice (buf, start, end) { + var ret = '' + end = Math.min(buf.length, end) + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i] & 0x7F) + } + return ret +} + +function latin1Slice (buf, start, end) { + var ret = '' + end = Math.min(buf.length, end) + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i]) + } + return ret +} + +function hexSlice (buf, start, end) { + var len = buf.length + + if (!start || start < 0) start = 0 + if (!end || end < 0 || end > len) end = len + + var out = '' + for (var i = start; i < end; ++i) { + out += toHex(buf[i]) + } + return out +} + +function utf16leSlice (buf, start, end) { + var bytes = buf.slice(start, end) + var res = '' + for (var i = 0; i < bytes.length; i += 2) { + res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256)) + } + return res +} + +Buffer.prototype.slice = function slice (start, end) { + var len = this.length + start = ~~start + end = end === undefined ? len : ~~end + + if (start < 0) { + start += len + if (start < 0) start = 0 + } else if (start > len) { + start = len + } + + if (end < 0) { + end += len + if (end < 0) end = 0 + } else if (end > len) { + end = len + } + + if (end < start) end = start + + var newBuf = this.subarray(start, end) + // Return an augmented `Uint8Array` instance + newBuf.__proto__ = Buffer.prototype + return newBuf +} + +/* + * Need to make sure that buffer isn't trying to write out of bounds. + */ +function checkOffset (offset, ext, length) { + if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') + if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') +} + +Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + var val = this[offset] + var mul = 1 + var i = 0 + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul + } + + return val +} + +Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) { + checkOffset(offset, byteLength, this.length) + } + + var val = this[offset + --byteLength] + var mul = 1 + while (byteLength > 0 && (mul *= 0x100)) { + val += this[offset + --byteLength] * mul + } + + return val +} + +Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 1, this.length) + return this[offset] +} + +Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 2, this.length) + return this[offset] | (this[offset + 1] << 8) +} + +Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 2, this.length) + return (this[offset] << 8) | this[offset + 1] +} + +Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + + return ((this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16)) + + (this[offset + 3] * 0x1000000) +} + +Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset] * 0x1000000) + + ((this[offset + 1] << 16) | + (this[offset + 2] << 8) | + this[offset + 3]) +} + +Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + var val = this[offset] + var mul = 1 + var i = 0 + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul + } + mul *= 0x80 + + if (val >= mul) val -= Math.pow(2, 8 * byteLength) + + return val +} + +Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + var i = byteLength + var mul = 1 + var val = this[offset + --i] + while (i > 0 && (mul *= 0x100)) { + val += this[offset + --i] * mul + } + mul *= 0x80 + + if (val >= mul) val -= Math.pow(2, 8 * byteLength) + + return val +} + +Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 1, this.length) + if (!(this[offset] & 0x80)) return (this[offset]) + return ((0xff - this[offset] + 1) * -1) +} + +Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 2, this.length) + var val = this[offset] | (this[offset + 1] << 8) + return (val & 0x8000) ? val | 0xFFFF0000 : val +} + +Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 2, this.length) + var val = this[offset + 1] | (this[offset] << 8) + return (val & 0x8000) ? val | 0xFFFF0000 : val +} + +Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16) | + (this[offset + 3] << 24) +} + +Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset] << 24) | + (this[offset + 1] << 16) | + (this[offset + 2] << 8) | + (this[offset + 3]) +} + +Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + return ieee754.read(this, offset, true, 23, 4) +} + +Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + return ieee754.read(this, offset, false, 23, 4) +} + +Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 8, this.length) + return ieee754.read(this, offset, true, 52, 8) +} + +Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 8, this.length) + return ieee754.read(this, offset, false, 52, 8) +} + +function checkInt (buf, value, offset, ext, max, min) { + if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') + if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') + if (offset + ext > buf.length) throw new RangeError('Index out of range') +} + +Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1 + checkInt(this, value, offset, byteLength, maxBytes, 0) + } + + var mul = 1 + var i = 0 + this[offset] = value & 0xFF + while (++i < byteLength && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1 + checkInt(this, value, offset, byteLength, maxBytes, 0) + } + + var i = byteLength - 1 + var mul = 1 + this[offset + i] = value & 0xFF + while (--i >= 0 && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) + this[offset] = (value & 0xff) + return offset + 1 +} + +Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + return offset + 2 +} + +Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) + this[offset] = (value >>> 8) + this[offset + 1] = (value & 0xff) + return offset + 2 +} + +Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) + this[offset + 3] = (value >>> 24) + this[offset + 2] = (value >>> 16) + this[offset + 1] = (value >>> 8) + this[offset] = (value & 0xff) + return offset + 4 +} + +Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) + this[offset] = (value >>> 24) + this[offset + 1] = (value >>> 16) + this[offset + 2] = (value >>> 8) + this[offset + 3] = (value & 0xff) + return offset + 4 +} + +Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) { + var limit = Math.pow(2, (8 * byteLength) - 1) + + checkInt(this, value, offset, byteLength, limit - 1, -limit) + } + + var i = 0 + var mul = 1 + var sub = 0 + this[offset] = value & 0xFF + while (++i < byteLength && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { + sub = 1 + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) { + var limit = Math.pow(2, (8 * byteLength) - 1) + + checkInt(this, value, offset, byteLength, limit - 1, -limit) + } + + var i = byteLength - 1 + var mul = 1 + var sub = 0 + this[offset + i] = value & 0xFF + while (--i >= 0 && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { + sub = 1 + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) + if (value < 0) value = 0xff + value + 1 + this[offset] = (value & 0xff) + return offset + 1 +} + +Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + return offset + 2 +} + +Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) + this[offset] = (value >>> 8) + this[offset + 1] = (value & 0xff) + return offset + 2 +} + +Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + this[offset + 2] = (value >>> 16) + this[offset + 3] = (value >>> 24) + return offset + 4 +} + +Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) + if (value < 0) value = 0xffffffff + value + 1 + this[offset] = (value >>> 24) + this[offset + 1] = (value >>> 16) + this[offset + 2] = (value >>> 8) + this[offset + 3] = (value & 0xff) + return offset + 4 +} + +function checkIEEE754 (buf, value, offset, ext, max, min) { + if (offset + ext > buf.length) throw new RangeError('Index out of range') + if (offset < 0) throw new RangeError('Index out of range') +} + +function writeFloat (buf, value, offset, littleEndian, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) { + checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) + } + ieee754.write(buf, value, offset, littleEndian, 23, 4) + return offset + 4 +} + +Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { + return writeFloat(this, value, offset, true, noAssert) +} + +Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { + return writeFloat(this, value, offset, false, noAssert) +} + +function writeDouble (buf, value, offset, littleEndian, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) { + checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) + } + ieee754.write(buf, value, offset, littleEndian, 52, 8) + return offset + 8 +} + +Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { + return writeDouble(this, value, offset, true, noAssert) +} + +Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { + return writeDouble(this, value, offset, false, noAssert) +} + +// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) +Buffer.prototype.copy = function copy (target, targetStart, start, end) { + if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer') + if (!start) start = 0 + if (!end && end !== 0) end = this.length + if (targetStart >= target.length) targetStart = target.length + if (!targetStart) targetStart = 0 + if (end > 0 && end < start) end = start + + // Copy 0 bytes; we're done + if (end === start) return 0 + if (target.length === 0 || this.length === 0) return 0 + + // Fatal error conditions + if (targetStart < 0) { + throw new RangeError('targetStart out of bounds') + } + if (start < 0 || start >= this.length) throw new RangeError('Index out of range') + if (end < 0) throw new RangeError('sourceEnd out of bounds') + + // Are we oob? + if (end > this.length) end = this.length + if (target.length - targetStart < end - start) { + end = target.length - targetStart + start + } + + var len = end - start + + if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') { + // Use built-in when available, missing from IE11 + this.copyWithin(targetStart, start, end) + } else if (this === target && start < targetStart && targetStart < end) { + // descending copy from end + for (var i = len - 1; i >= 0; --i) { + target[i + targetStart] = this[i + start] + } + } else { + Uint8Array.prototype.set.call( + target, + this.subarray(start, end), + targetStart + ) + } + + return len +} + +// Usage: +// buffer.fill(number[, offset[, end]]) +// buffer.fill(buffer[, offset[, end]]) +// buffer.fill(string[, offset[, end]][, encoding]) +Buffer.prototype.fill = function fill (val, start, end, encoding) { + // Handle string cases: + if (typeof val === 'string') { + if (typeof start === 'string') { + encoding = start + start = 0 + end = this.length + } else if (typeof end === 'string') { + encoding = end + end = this.length + } + if (encoding !== undefined && typeof encoding !== 'string') { + throw new TypeError('encoding must be a string') + } + if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } + if (val.length === 1) { + var code = val.charCodeAt(0) + if ((encoding === 'utf8' && code < 128) || + encoding === 'latin1') { + // Fast path: If `val` fits into a single byte, use that numeric value. + val = code + } + } + } else if (typeof val === 'number') { + val = val & 255 + } + + // Invalid ranges are not set to a default, so can range check early. + if (start < 0 || this.length < start || this.length < end) { + throw new RangeError('Out of range index') + } + + if (end <= start) { + return this + } + + start = start >>> 0 + end = end === undefined ? this.length : end >>> 0 + + if (!val) val = 0 + + var i + if (typeof val === 'number') { + for (i = start; i < end; ++i) { + this[i] = val + } + } else { + var bytes = Buffer.isBuffer(val) + ? val + : new Buffer(val, encoding) + var len = bytes.length + if (len === 0) { + throw new TypeError('The value "' + val + + '" is invalid for argument "value"') + } + for (i = 0; i < end - start; ++i) { + this[i + start] = bytes[i % len] + } + } + + return this +} + +// HELPER FUNCTIONS +// ================ + +var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g + +function base64clean (str) { + // Node takes equal signs as end of the Base64 encoding + str = str.split('=')[0] + // Node strips out invalid characters like \n and \t from the string, base64-js does not + str = str.trim().replace(INVALID_BASE64_RE, '') + // Node converts strings with length < 2 to '' + if (str.length < 2) return '' + // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not + while (str.length % 4 !== 0) { + str = str + '=' + } + return str +} + +function toHex (n) { + if (n < 16) return '0' + n.toString(16) + return n.toString(16) +} + +function utf8ToBytes (string, units) { + units = units || Infinity + var codePoint + var length = string.length + var leadSurrogate = null + var bytes = [] + + for (var i = 0; i < length; ++i) { + codePoint = string.charCodeAt(i) + + // is surrogate component + if (codePoint > 0xD7FF && codePoint < 0xE000) { + // last char was a lead + if (!leadSurrogate) { + // no lead yet + if (codePoint > 0xDBFF) { + // unexpected trail + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + continue + } else if (i + 1 === length) { + // unpaired lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + continue + } + + // valid lead + leadSurrogate = codePoint + + continue + } + + // 2 leads in a row + if (codePoint < 0xDC00) { + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + leadSurrogate = codePoint + continue + } + + // valid surrogate pair + codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000 + } else if (leadSurrogate) { + // valid bmp char, but last char was a lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + } + + leadSurrogate = null + + // encode utf8 + if (codePoint < 0x80) { + if ((units -= 1) < 0) break + bytes.push(codePoint) + } else if (codePoint < 0x800) { + if ((units -= 2) < 0) break + bytes.push( + codePoint >> 0x6 | 0xC0, + codePoint & 0x3F | 0x80 + ) + } else if (codePoint < 0x10000) { + if ((units -= 3) < 0) break + bytes.push( + codePoint >> 0xC | 0xE0, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ) + } else if (codePoint < 0x110000) { + if ((units -= 4) < 0) break + bytes.push( + codePoint >> 0x12 | 0xF0, + codePoint >> 0xC & 0x3F | 0x80, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ) + } else { + throw new Error('Invalid code point') + } + } + + return bytes +} + +function asciiToBytes (str) { + var byteArray = [] + for (var i = 0; i < str.length; ++i) { + // Node's code seems to be doing this and not & 0x7F.. + byteArray.push(str.charCodeAt(i) & 0xFF) + } + return byteArray +} + +function utf16leToBytes (str, units) { + var c, hi, lo + var byteArray = [] + for (var i = 0; i < str.length; ++i) { + if ((units -= 2) < 0) break + + c = str.charCodeAt(i) + hi = c >> 8 + lo = c % 256 + byteArray.push(lo) + byteArray.push(hi) + } + + return byteArray +} + +function base64ToBytes (str) { + return base64.toByteArray(base64clean(str)) +} + +function blitBuffer (src, dst, offset, length) { + for (var i = 0; i < length; ++i) { + if ((i + offset >= dst.length) || (i >= src.length)) break + dst[i + offset] = src[i] + } + return i +} + +// ArrayBuffers from another context (i.e. an iframe) do not pass the `instanceof` check +// but they should be treated as valid. See: https://github.com/feross/buffer/issues/166 +function isArrayBuffer (obj) { + return obj instanceof ArrayBuffer || + (obj != null && obj.constructor != null && obj.constructor.name === 'ArrayBuffer' && + typeof obj.byteLength === 'number') +} + +function numberIsNaN (obj) { + return obj !== obj // eslint-disable-line no-self-compare +} + +},{"base64-js":37,"ieee754":49}],42:[function(require,module,exports){ +(function (Buffer){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// NOTE: These type checking functions intentionally don't use `instanceof` +// because it is fragile and can be easily faked with `Object.create()`. + +function isArray(arg) { + if (Array.isArray) { + return Array.isArray(arg); + } + return objectToString(arg) === '[object Array]'; +} +exports.isArray = isArray; + +function isBoolean(arg) { + return typeof arg === 'boolean'; +} +exports.isBoolean = isBoolean; + +function isNull(arg) { + return arg === null; +} +exports.isNull = isNull; + +function isNullOrUndefined(arg) { + return arg == null; +} +exports.isNullOrUndefined = isNullOrUndefined; + +function isNumber(arg) { + return typeof arg === 'number'; +} +exports.isNumber = isNumber; + +function isString(arg) { + return typeof arg === 'string'; +} +exports.isString = isString; + +function isSymbol(arg) { + return typeof arg === 'symbol'; +} +exports.isSymbol = isSymbol; + +function isUndefined(arg) { + return arg === void 0; +} +exports.isUndefined = isUndefined; + +function isRegExp(re) { + return objectToString(re) === '[object RegExp]'; +} +exports.isRegExp = isRegExp; + +function isObject(arg) { + return typeof arg === 'object' && arg !== null; +} +exports.isObject = isObject; + +function isDate(d) { + return objectToString(d) === '[object Date]'; +} +exports.isDate = isDate; + +function isError(e) { + return (objectToString(e) === '[object Error]' || e instanceof Error); +} +exports.isError = isError; + +function isFunction(arg) { + return typeof arg === 'function'; +} +exports.isFunction = isFunction; + +function isPrimitive(arg) { + return arg === null || + typeof arg === 'boolean' || + typeof arg === 'number' || + typeof arg === 'string' || + typeof arg === 'symbol' || // ES6 symbol + typeof arg === 'undefined'; +} +exports.isPrimitive = isPrimitive; + +exports.isBuffer = Buffer.isBuffer; + +function objectToString(o) { + return Object.prototype.toString.call(o); +} + +}).call(this,{"isBuffer":require("../../is-buffer/index.js")}) +},{"../../is-buffer/index.js":51}],43:[function(require,module,exports){ +(function (process){ +/** + * This is the web browser implementation of `debug()`. + * + * Expose `debug()` as the module. + */ + +exports = module.exports = require('./debug'); +exports.log = log; +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; +exports.storage = 'undefined' != typeof chrome + && 'undefined' != typeof chrome.storage + ? chrome.storage.local + : localstorage(); + +/** + * Colors. + */ + +exports.colors = [ + '#0000CC', '#0000FF', '#0033CC', '#0033FF', '#0066CC', '#0066FF', '#0099CC', + '#0099FF', '#00CC00', '#00CC33', '#00CC66', '#00CC99', '#00CCCC', '#00CCFF', + '#3300CC', '#3300FF', '#3333CC', '#3333FF', '#3366CC', '#3366FF', '#3399CC', + '#3399FF', '#33CC00', '#33CC33', '#33CC66', '#33CC99', '#33CCCC', '#33CCFF', + '#6600CC', '#6600FF', '#6633CC', '#6633FF', '#66CC00', '#66CC33', '#9900CC', + '#9900FF', '#9933CC', '#9933FF', '#99CC00', '#99CC33', '#CC0000', '#CC0033', + '#CC0066', '#CC0099', '#CC00CC', '#CC00FF', '#CC3300', '#CC3333', '#CC3366', + '#CC3399', '#CC33CC', '#CC33FF', '#CC6600', '#CC6633', '#CC9900', '#CC9933', + '#CCCC00', '#CCCC33', '#FF0000', '#FF0033', '#FF0066', '#FF0099', '#FF00CC', + '#FF00FF', '#FF3300', '#FF3333', '#FF3366', '#FF3399', '#FF33CC', '#FF33FF', + '#FF6600', '#FF6633', '#FF9900', '#FF9933', '#FFCC00', '#FFCC33' +]; + +/** + * Currently only WebKit-based Web Inspectors, Firefox >= v31, + * and the Firebug extension (any Firefox version) are known + * to support "%c" CSS customizations. + * + * TODO: add a `localStorage` variable to explicitly enable/disable colors + */ + +function useColors() { + // NB: In an Electron preload script, document will be defined but not fully + // initialized. Since we know we're in Chrome, we'll just detect this case + // explicitly + if (typeof window !== 'undefined' && window.process && window.process.type === 'renderer') { + return true; + } + + // Internet Explorer and Edge do not support colors. + if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { + return false; + } + + // is webkit? http://stackoverflow.com/a/16459606/376773 + // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 + return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || + // is firebug? http://stackoverflow.com/a/398120/376773 + (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || + // is firefox >= v31? + // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || + // double check webkit in userAgent just in case we are in a worker + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); +} + +/** + * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. + */ + +exports.formatters.j = function(v) { + try { + return JSON.stringify(v); + } catch (err) { + return '[UnexpectedJSONParseError]: ' + err.message; + } +}; + + +/** + * Colorize log arguments if enabled. + * + * @api public + */ + +function formatArgs(args) { + var useColors = this.useColors; + + args[0] = (useColors ? '%c' : '') + + this.namespace + + (useColors ? ' %c' : ' ') + + args[0] + + (useColors ? '%c ' : ' ') + + '+' + exports.humanize(this.diff); + + if (!useColors) return; + + var c = 'color: ' + this.color; + args.splice(1, 0, c, 'color: inherit') + + // the final "%c" is somewhat tricky, because there could be other + // arguments passed either before or after the %c, so we need to + // figure out the correct index to insert the CSS into + var index = 0; + var lastC = 0; + args[0].replace(/%[a-zA-Z%]/g, function(match) { + if ('%%' === match) return; + index++; + if ('%c' === match) { + // we only are interested in the *last* %c + // (the user may have provided their own) + lastC = index; + } + }); + + args.splice(lastC, 0, c); +} + +/** + * Invokes `console.log()` when available. + * No-op when `console.log` is not a "function". + * + * @api public + */ + +function log() { + // this hackery is required for IE8/9, where + // the `console.log` function doesn't have 'apply' + return 'object' === typeof console + && console.log + && Function.prototype.apply.call(console.log, console, arguments); +} + +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ + +function save(namespaces) { + try { + if (null == namespaces) { + exports.storage.removeItem('debug'); + } else { + exports.storage.debug = namespaces; + } + } catch(e) {} +} + +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ + +function load() { + var r; + try { + r = exports.storage.debug; + } catch(e) {} + + // If debug isn't set in LS, and we're in Electron, try to load $DEBUG + if (!r && typeof process !== 'undefined' && 'env' in process) { + r = process.env.DEBUG; + } + + return r; +} + +/** + * Enable namespaces listed in `localStorage.debug` initially. + */ + +exports.enable(load()); + +/** + * Localstorage attempts to return the localstorage. + * + * This is necessary because safari throws + * when a user disables cookies/localstorage + * and you attempt to access it. + * + * @return {LocalStorage} + * @api private + */ + +function localstorage() { + try { + return window.localStorage; + } catch (e) {} +} + +}).call(this,require('_process')) +},{"./debug":44,"_process":56}],44:[function(require,module,exports){ + +/** + * This is the common logic for both the Node.js and web browser + * implementations of `debug()`. + * + * Expose `debug()` as the module. + */ + +exports = module.exports = createDebug.debug = createDebug['default'] = createDebug; +exports.coerce = coerce; +exports.disable = disable; +exports.enable = enable; +exports.enabled = enabled; +exports.humanize = require('ms'); + +/** + * Active `debug` instances. + */ +exports.instances = []; + +/** + * The currently active debug mode names, and names to skip. + */ + +exports.names = []; +exports.skips = []; + +/** + * Map of special "%n" handling functions, for the debug "format" argument. + * + * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". + */ + +exports.formatters = {}; + +/** + * Select a color. + * @param {String} namespace + * @return {Number} + * @api private + */ + +function selectColor(namespace) { + var hash = 0, i; + + for (i in namespace) { + hash = ((hash << 5) - hash) + namespace.charCodeAt(i); + hash |= 0; // Convert to 32bit integer + } + + return exports.colors[Math.abs(hash) % exports.colors.length]; +} + +/** + * Create a debugger with the given `namespace`. + * + * @param {String} namespace + * @return {Function} + * @api public + */ + +function createDebug(namespace) { + + var prevTime; + + function debug() { + // disabled? + if (!debug.enabled) return; + + var self = debug; + + // set `diff` timestamp + var curr = +new Date(); + var ms = curr - (prevTime || curr); + self.diff = ms; + self.prev = prevTime; + self.curr = curr; + prevTime = curr; + + // turn the `arguments` into a proper Array + var args = new Array(arguments.length); + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i]; + } + + args[0] = exports.coerce(args[0]); + + if ('string' !== typeof args[0]) { + // anything else let's inspect with %O + args.unshift('%O'); + } + + // apply any `formatters` transformations + var index = 0; + args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) { + // if we encounter an escaped % then don't increase the array index + if (match === '%%') return match; + index++; + var formatter = exports.formatters[format]; + if ('function' === typeof formatter) { + var val = args[index]; + match = formatter.call(self, val); + + // now we need to remove `args[index]` since it's inlined in the `format` + args.splice(index, 1); + index--; + } + return match; + }); + + // apply env-specific formatting (colors, etc.) + exports.formatArgs.call(self, args); + + var logFn = debug.log || exports.log || console.log.bind(console); + logFn.apply(self, args); + } + + debug.namespace = namespace; + debug.enabled = exports.enabled(namespace); + debug.useColors = exports.useColors(); + debug.color = selectColor(namespace); + debug.destroy = destroy; + + // env-specific initialization logic for debug instances + if ('function' === typeof exports.init) { + exports.init(debug); + } + + exports.instances.push(debug); + + return debug; +} + +function destroy () { + var index = exports.instances.indexOf(this); + if (index !== -1) { + exports.instances.splice(index, 1); + return true; + } else { + return false; + } +} + +/** + * Enables a debug mode by namespaces. This can include modes + * separated by a colon and wildcards. + * + * @param {String} namespaces + * @api public + */ + +function enable(namespaces) { + exports.save(namespaces); + + exports.names = []; + exports.skips = []; + + var i; + var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); + var len = split.length; + + for (i = 0; i < len; i++) { + if (!split[i]) continue; // ignore empty strings + namespaces = split[i].replace(/\*/g, '.*?'); + if (namespaces[0] === '-') { + exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); + } else { + exports.names.push(new RegExp('^' + namespaces + '$')); + } + } + + for (i = 0; i < exports.instances.length; i++) { + var instance = exports.instances[i]; + instance.enabled = exports.enabled(instance.namespace); + } +} + +/** + * Disable debug output. + * + * @api public + */ + +function disable() { + exports.enable(''); +} + +/** + * Returns true if the given mode name is enabled, false otherwise. + * + * @param {String} name + * @return {Boolean} + * @api public + */ + +function enabled(name) { + if (name[name.length - 1] === '*') { + return true; + } + var i, len; + for (i = 0, len = exports.skips.length; i < len; i++) { + if (exports.skips[i].test(name)) { + return false; + } + } + for (i = 0, len = exports.names.length; i < len; i++) { + if (exports.names[i].test(name)) { + return true; + } + } + return false; +} + +/** + * Coerce `val`. + * + * @param {Mixed} val + * @return {Mixed} + * @api private + */ + +function coerce(val) { + if (val instanceof Error) return val.stack || val.message; + return val; +} + +},{"ms":54}],45:[function(require,module,exports){ +/*! + + diff v3.5.0 + +Software License Agreement (BSD License) + +Copyright (c) 2009-2015, Kevin Decker + +All rights reserved. + +Redistribution and use of this software in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above + copyright notice, this list of conditions and the + following disclaimer. + +* Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the + following disclaimer in the documentation and/or other + materials provided with the distribution. + +* Neither the name of Kevin Decker nor the names of its + contributors may be used to endorse or promote products + derived from this software without specific prior + written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +@license +*/ +(function webpackUniversalModuleDefinition(root, factory) { + if(typeof exports === 'object' && typeof module === 'object') + module.exports = factory(); + else if(false) + define([], factory); + else if(typeof exports === 'object') + exports["JsDiff"] = factory(); + else + root["JsDiff"] = factory(); +})(this, function() { +return /******/ (function(modules) { // webpackBootstrap +/******/ // The module cache +/******/ var installedModules = {}; + +/******/ // The require function +/******/ function __webpack_require__(moduleId) { + +/******/ // Check if module is in cache +/******/ if(installedModules[moduleId]) +/******/ return installedModules[moduleId].exports; + +/******/ // Create a new module (and put it into the cache) +/******/ var module = installedModules[moduleId] = { +/******/ exports: {}, +/******/ id: moduleId, +/******/ loaded: false +/******/ }; + +/******/ // Execute the module function +/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); + +/******/ // Flag the module as loaded +/******/ module.loaded = true; + +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } + + +/******/ // expose the modules object (__webpack_modules__) +/******/ __webpack_require__.m = modules; + +/******/ // expose the module cache +/******/ __webpack_require__.c = installedModules; + +/******/ // __webpack_public_path__ +/******/ __webpack_require__.p = ""; + +/******/ // Load entry module and return exports +/******/ return __webpack_require__(0); +/******/ }) +/************************************************************************/ +/******/ ([ +/* 0 */ +/***/ (function(module, exports, __webpack_require__) { + + /*istanbul ignore start*/'use strict'; + + exports.__esModule = true; + exports.canonicalize = exports.convertChangesToXML = exports.convertChangesToDMP = exports.merge = exports.parsePatch = exports.applyPatches = exports.applyPatch = exports.createPatch = exports.createTwoFilesPatch = exports.structuredPatch = exports.diffArrays = exports.diffJson = exports.diffCss = exports.diffSentences = exports.diffTrimmedLines = exports.diffLines = exports.diffWordsWithSpace = exports.diffWords = exports.diffChars = exports.Diff = undefined; + + /*istanbul ignore end*/var /*istanbul ignore start*/_base = __webpack_require__(1) /*istanbul ignore end*/; + + /*istanbul ignore start*/var _base2 = _interopRequireDefault(_base); + + /*istanbul ignore end*/var /*istanbul ignore start*/_character = __webpack_require__(2) /*istanbul ignore end*/; + + var /*istanbul ignore start*/_word = __webpack_require__(3) /*istanbul ignore end*/; + + var /*istanbul ignore start*/_line = __webpack_require__(5) /*istanbul ignore end*/; + + var /*istanbul ignore start*/_sentence = __webpack_require__(6) /*istanbul ignore end*/; + + var /*istanbul ignore start*/_css = __webpack_require__(7) /*istanbul ignore end*/; + + var /*istanbul ignore start*/_json = __webpack_require__(8) /*istanbul ignore end*/; + + var /*istanbul ignore start*/_array = __webpack_require__(9) /*istanbul ignore end*/; + + var /*istanbul ignore start*/_apply = __webpack_require__(10) /*istanbul ignore end*/; + + var /*istanbul ignore start*/_parse = __webpack_require__(11) /*istanbul ignore end*/; + + var /*istanbul ignore start*/_merge = __webpack_require__(13) /*istanbul ignore end*/; + + var /*istanbul ignore start*/_create = __webpack_require__(14) /*istanbul ignore end*/; + + var /*istanbul ignore start*/_dmp = __webpack_require__(16) /*istanbul ignore end*/; + + var /*istanbul ignore start*/_xml = __webpack_require__(17) /*istanbul ignore end*/; + + /*istanbul ignore start*/function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + + /* See LICENSE file for terms of use */ + + /* + * Text diff implementation. + * + * This library supports the following APIS: + * JsDiff.diffChars: Character by character diff + * JsDiff.diffWords: Word (as defined by \b regex) diff which ignores whitespace + * JsDiff.diffLines: Line based diff + * + * JsDiff.diffCss: Diff targeted at CSS content + * + * These methods are based on the implementation proposed in + * "An O(ND) Difference Algorithm and its Variations" (Myers, 1986). + * http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.4.6927 + */ + exports. /*istanbul ignore end*/Diff = _base2['default']; + /*istanbul ignore start*/exports. /*istanbul ignore end*/diffChars = _character.diffChars; + /*istanbul ignore start*/exports. /*istanbul ignore end*/diffWords = _word.diffWords; + /*istanbul ignore start*/exports. /*istanbul ignore end*/diffWordsWithSpace = _word.diffWordsWithSpace; + /*istanbul ignore start*/exports. /*istanbul ignore end*/diffLines = _line.diffLines; + /*istanbul ignore start*/exports. /*istanbul ignore end*/diffTrimmedLines = _line.diffTrimmedLines; + /*istanbul ignore start*/exports. /*istanbul ignore end*/diffSentences = _sentence.diffSentences; + /*istanbul ignore start*/exports. /*istanbul ignore end*/diffCss = _css.diffCss; + /*istanbul ignore start*/exports. /*istanbul ignore end*/diffJson = _json.diffJson; + /*istanbul ignore start*/exports. /*istanbul ignore end*/diffArrays = _array.diffArrays; + /*istanbul ignore start*/exports. /*istanbul ignore end*/structuredPatch = _create.structuredPatch; + /*istanbul ignore start*/exports. /*istanbul ignore end*/createTwoFilesPatch = _create.createTwoFilesPatch; + /*istanbul ignore start*/exports. /*istanbul ignore end*/createPatch = _create.createPatch; + /*istanbul ignore start*/exports. /*istanbul ignore end*/applyPatch = _apply.applyPatch; + /*istanbul ignore start*/exports. /*istanbul ignore end*/applyPatches = _apply.applyPatches; + /*istanbul ignore start*/exports. /*istanbul ignore end*/parsePatch = _parse.parsePatch; + /*istanbul ignore start*/exports. /*istanbul ignore end*/merge = _merge.merge; + /*istanbul ignore start*/exports. /*istanbul ignore end*/convertChangesToDMP = _dmp.convertChangesToDMP; + /*istanbul ignore start*/exports. /*istanbul ignore end*/convertChangesToXML = _xml.convertChangesToXML; + /*istanbul ignore start*/exports. /*istanbul ignore end*/canonicalize = _json.canonicalize; + + + +/***/ }), +/* 1 */ +/***/ (function(module, exports) { + + /*istanbul ignore start*/'use strict'; + + exports.__esModule = true; + exports['default'] = /*istanbul ignore end*/Diff; + function Diff() {} + + Diff.prototype = { + /*istanbul ignore start*/ /*istanbul ignore end*/diff: function diff(oldString, newString) { + /*istanbul ignore start*/var /*istanbul ignore end*/options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + + var callback = options.callback; + if (typeof options === 'function') { + callback = options; + options = {}; + } + this.options = options; + + var self = this; + + function done(value) { + if (callback) { + setTimeout(function () { + callback(undefined, value); + }, 0); + return true; + } else { + return value; + } + } + + // Allow subclasses to massage the input prior to running + oldString = this.castInput(oldString); + newString = this.castInput(newString); + + oldString = this.removeEmpty(this.tokenize(oldString)); + newString = this.removeEmpty(this.tokenize(newString)); + + var newLen = newString.length, + oldLen = oldString.length; + var editLength = 1; + var maxEditLength = newLen + oldLen; + var bestPath = [{ newPos: -1, components: [] }]; + + // Seed editLength = 0, i.e. the content starts with the same values + var oldPos = this.extractCommon(bestPath[0], newString, oldString, 0); + if (bestPath[0].newPos + 1 >= newLen && oldPos + 1 >= oldLen) { + // Identity per the equality and tokenizer + return done([{ value: this.join(newString), count: newString.length }]); + } + + // Main worker method. checks all permutations of a given edit length for acceptance. + function execEditLength() { + for (var diagonalPath = -1 * editLength; diagonalPath <= editLength; diagonalPath += 2) { + var basePath = /*istanbul ignore start*/void 0 /*istanbul ignore end*/; + var addPath = bestPath[diagonalPath - 1], + removePath = bestPath[diagonalPath + 1], + _oldPos = (removePath ? removePath.newPos : 0) - diagonalPath; + if (addPath) { + // No one else is going to attempt to use this value, clear it + bestPath[diagonalPath - 1] = undefined; + } + + var canAdd = addPath && addPath.newPos + 1 < newLen, + canRemove = removePath && 0 <= _oldPos && _oldPos < oldLen; + if (!canAdd && !canRemove) { + // If this path is a terminal then prune + bestPath[diagonalPath] = undefined; + continue; + } + + // Select the diagonal that we want to branch from. We select the prior + // path whose position in the new string is the farthest from the origin + // and does not pass the bounds of the diff graph + if (!canAdd || canRemove && addPath.newPos < removePath.newPos) { + basePath = clonePath(removePath); + self.pushComponent(basePath.components, undefined, true); + } else { + basePath = addPath; // No need to clone, we've pulled it from the list + basePath.newPos++; + self.pushComponent(basePath.components, true, undefined); + } + + _oldPos = self.extractCommon(basePath, newString, oldString, diagonalPath); + + // If we have hit the end of both strings, then we are done + if (basePath.newPos + 1 >= newLen && _oldPos + 1 >= oldLen) { + return done(buildValues(self, basePath.components, newString, oldString, self.useLongestToken)); + } else { + // Otherwise track this path as a potential candidate and continue. + bestPath[diagonalPath] = basePath; + } + } + + editLength++; + } + + // Performs the length of edit iteration. Is a bit fugly as this has to support the + // sync and async mode which is never fun. Loops over execEditLength until a value + // is produced. + if (callback) { + (function exec() { + setTimeout(function () { + // This should not happen, but we want to be safe. + /* istanbul ignore next */ + if (editLength > maxEditLength) { + return callback(); + } + + if (!execEditLength()) { + exec(); + } + }, 0); + })(); + } else { + while (editLength <= maxEditLength) { + var ret = execEditLength(); + if (ret) { + return ret; + } + } + } + }, + /*istanbul ignore start*/ /*istanbul ignore end*/pushComponent: function pushComponent(components, added, removed) { + var last = components[components.length - 1]; + if (last && last.added === added && last.removed === removed) { + // We need to clone here as the component clone operation is just + // as shallow array clone + components[components.length - 1] = { count: last.count + 1, added: added, removed: removed }; + } else { + components.push({ count: 1, added: added, removed: removed }); + } + }, + /*istanbul ignore start*/ /*istanbul ignore end*/extractCommon: function extractCommon(basePath, newString, oldString, diagonalPath) { + var newLen = newString.length, + oldLen = oldString.length, + newPos = basePath.newPos, + oldPos = newPos - diagonalPath, + commonCount = 0; + while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(newString[newPos + 1], oldString[oldPos + 1])) { + newPos++; + oldPos++; + commonCount++; + } + + if (commonCount) { + basePath.components.push({ count: commonCount }); + } + + basePath.newPos = newPos; + return oldPos; + }, + /*istanbul ignore start*/ /*istanbul ignore end*/equals: function equals(left, right) { + if (this.options.comparator) { + return this.options.comparator(left, right); + } else { + return left === right || this.options.ignoreCase && left.toLowerCase() === right.toLowerCase(); + } + }, + /*istanbul ignore start*/ /*istanbul ignore end*/removeEmpty: function removeEmpty(array) { + var ret = []; + for (var i = 0; i < array.length; i++) { + if (array[i]) { + ret.push(array[i]); + } + } + return ret; + }, + /*istanbul ignore start*/ /*istanbul ignore end*/castInput: function castInput(value) { + return value; + }, + /*istanbul ignore start*/ /*istanbul ignore end*/tokenize: function tokenize(value) { + return value.split(''); + }, + /*istanbul ignore start*/ /*istanbul ignore end*/join: function join(chars) { + return chars.join(''); + } + }; + + function buildValues(diff, components, newString, oldString, useLongestToken) { + var componentPos = 0, + componentLen = components.length, + newPos = 0, + oldPos = 0; + + for (; componentPos < componentLen; componentPos++) { + var component = components[componentPos]; + if (!component.removed) { + if (!component.added && useLongestToken) { + var value = newString.slice(newPos, newPos + component.count); + value = value.map(function (value, i) { + var oldValue = oldString[oldPos + i]; + return oldValue.length > value.length ? oldValue : value; + }); + + component.value = diff.join(value); + } else { + component.value = diff.join(newString.slice(newPos, newPos + component.count)); + } + newPos += component.count; + + // Common case + if (!component.added) { + oldPos += component.count; + } + } else { + component.value = diff.join(oldString.slice(oldPos, oldPos + component.count)); + oldPos += component.count; + + // Reverse add and remove so removes are output first to match common convention + // The diffing algorithm is tied to add then remove output and this is the simplest + // route to get the desired output with minimal overhead. + if (componentPos && components[componentPos - 1].added) { + var tmp = components[componentPos - 1]; + components[componentPos - 1] = components[componentPos]; + components[componentPos] = tmp; + } + } + } + + // Special case handle for when one terminal is ignored (i.e. whitespace). + // For this case we merge the terminal into the prior string and drop the change. + // This is only available for string mode. + var lastComponent = components[componentLen - 1]; + if (componentLen > 1 && typeof lastComponent.value === 'string' && (lastComponent.added || lastComponent.removed) && diff.equals('', lastComponent.value)) { + components[componentLen - 2].value += lastComponent.value; + components.pop(); + } + + return components; + } + + function clonePath(path) { + return { newPos: path.newPos, components: path.components.slice(0) }; + } + + + +/***/ }), +/* 2 */ +/***/ (function(module, exports, __webpack_require__) { + + /*istanbul ignore start*/'use strict'; + + exports.__esModule = true; + exports.characterDiff = undefined; + exports. /*istanbul ignore end*/diffChars = diffChars; + + var /*istanbul ignore start*/_base = __webpack_require__(1) /*istanbul ignore end*/; + + /*istanbul ignore start*/var _base2 = _interopRequireDefault(_base); + + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + + /*istanbul ignore end*/var characterDiff = /*istanbul ignore start*/exports. /*istanbul ignore end*/characterDiff = new /*istanbul ignore start*/_base2['default'] /*istanbul ignore end*/(); + function diffChars(oldStr, newStr, options) { + return characterDiff.diff(oldStr, newStr, options); + } + + + +/***/ }), +/* 3 */ +/***/ (function(module, exports, __webpack_require__) { + + /*istanbul ignore start*/'use strict'; + + exports.__esModule = true; + exports.wordDiff = undefined; + exports. /*istanbul ignore end*/diffWords = diffWords; + /*istanbul ignore start*/exports. /*istanbul ignore end*/diffWordsWithSpace = diffWordsWithSpace; + + var /*istanbul ignore start*/_base = __webpack_require__(1) /*istanbul ignore end*/; + + /*istanbul ignore start*/var _base2 = _interopRequireDefault(_base); + + /*istanbul ignore end*/var /*istanbul ignore start*/_params = __webpack_require__(4) /*istanbul ignore end*/; + + /*istanbul ignore start*/function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + + /*istanbul ignore end*/ // Based on https://en.wikipedia.org/wiki/Latin_script_in_Unicode + // + // Ranges and exceptions: + // Latin-1 Supplement, 0080–00FF + // - U+00D7 × Multiplication sign + // - U+00F7 ÷ Division sign + // Latin Extended-A, 0100–017F + // Latin Extended-B, 0180–024F + // IPA Extensions, 0250–02AF + // Spacing Modifier Letters, 02B0–02FF + // - U+02C7 ˇ ˇ Caron + // - U+02D8 ˘ ˘ Breve + // - U+02D9 ˙ ˙ Dot Above + // - U+02DA ˚ ˚ Ring Above + // - U+02DB ˛ ˛ Ogonek + // - U+02DC ˜ ˜ Small Tilde + // - U+02DD ˝ ˝ Double Acute Accent + // Latin Extended Additional, 1E00–1EFF + var extendedWordChars = /^[A-Za-z\xC0-\u02C6\u02C8-\u02D7\u02DE-\u02FF\u1E00-\u1EFF]+$/; + + var reWhitespace = /\S/; + + var wordDiff = /*istanbul ignore start*/exports. /*istanbul ignore end*/wordDiff = new /*istanbul ignore start*/_base2['default'] /*istanbul ignore end*/(); + wordDiff.equals = function (left, right) { + if (this.options.ignoreCase) { + left = left.toLowerCase(); + right = right.toLowerCase(); + } + return left === right || this.options.ignoreWhitespace && !reWhitespace.test(left) && !reWhitespace.test(right); + }; + wordDiff.tokenize = function (value) { + var tokens = value.split(/(\s+|\b)/); + + // Join the boundary splits that we do not consider to be boundaries. This is primarily the extended Latin character set. + for (var i = 0; i < tokens.length - 1; i++) { + // If we have an empty string in the next field and we have only word chars before and after, merge + if (!tokens[i + 1] && tokens[i + 2] && extendedWordChars.test(tokens[i]) && extendedWordChars.test(tokens[i + 2])) { + tokens[i] += tokens[i + 2]; + tokens.splice(i + 1, 2); + i--; + } + } + + return tokens; + }; + + function diffWords(oldStr, newStr, options) { + options = /*istanbul ignore start*/(0, _params.generateOptions) /*istanbul ignore end*/(options, { ignoreWhitespace: true }); + return wordDiff.diff(oldStr, newStr, options); + } + + function diffWordsWithSpace(oldStr, newStr, options) { + return wordDiff.diff(oldStr, newStr, options); + } + + + +/***/ }), +/* 4 */ +/***/ (function(module, exports) { + + /*istanbul ignore start*/'use strict'; + + exports.__esModule = true; + exports. /*istanbul ignore end*/generateOptions = generateOptions; + function generateOptions(options, defaults) { + if (typeof options === 'function') { + defaults.callback = options; + } else if (options) { + for (var name in options) { + /* istanbul ignore else */ + if (options.hasOwnProperty(name)) { + defaults[name] = options[name]; + } + } + } + return defaults; + } + + + +/***/ }), +/* 5 */ +/***/ (function(module, exports, __webpack_require__) { + + /*istanbul ignore start*/'use strict'; + + exports.__esModule = true; + exports.lineDiff = undefined; + exports. /*istanbul ignore end*/diffLines = diffLines; + /*istanbul ignore start*/exports. /*istanbul ignore end*/diffTrimmedLines = diffTrimmedLines; + + var /*istanbul ignore start*/_base = __webpack_require__(1) /*istanbul ignore end*/; + + /*istanbul ignore start*/var _base2 = _interopRequireDefault(_base); + + /*istanbul ignore end*/var /*istanbul ignore start*/_params = __webpack_require__(4) /*istanbul ignore end*/; + + /*istanbul ignore start*/function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + + /*istanbul ignore end*/var lineDiff = /*istanbul ignore start*/exports. /*istanbul ignore end*/lineDiff = new /*istanbul ignore start*/_base2['default'] /*istanbul ignore end*/(); + lineDiff.tokenize = function (value) { + var retLines = [], + linesAndNewlines = value.split(/(\n|\r\n)/); + + // Ignore the final empty token that occurs if the string ends with a new line + if (!linesAndNewlines[linesAndNewlines.length - 1]) { + linesAndNewlines.pop(); + } + + // Merge the content and line separators into single tokens + for (var i = 0; i < linesAndNewlines.length; i++) { + var line = linesAndNewlines[i]; + + if (i % 2 && !this.options.newlineIsToken) { + retLines[retLines.length - 1] += line; + } else { + if (this.options.ignoreWhitespace) { + line = line.trim(); + } + retLines.push(line); + } + } + + return retLines; + }; + + function diffLines(oldStr, newStr, callback) { + return lineDiff.diff(oldStr, newStr, callback); + } + function diffTrimmedLines(oldStr, newStr, callback) { + var options = /*istanbul ignore start*/(0, _params.generateOptions) /*istanbul ignore end*/(callback, { ignoreWhitespace: true }); + return lineDiff.diff(oldStr, newStr, options); + } + + + +/***/ }), +/* 6 */ +/***/ (function(module, exports, __webpack_require__) { + + /*istanbul ignore start*/'use strict'; + + exports.__esModule = true; + exports.sentenceDiff = undefined; + exports. /*istanbul ignore end*/diffSentences = diffSentences; + + var /*istanbul ignore start*/_base = __webpack_require__(1) /*istanbul ignore end*/; + + /*istanbul ignore start*/var _base2 = _interopRequireDefault(_base); + + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + + /*istanbul ignore end*/var sentenceDiff = /*istanbul ignore start*/exports. /*istanbul ignore end*/sentenceDiff = new /*istanbul ignore start*/_base2['default'] /*istanbul ignore end*/(); + sentenceDiff.tokenize = function (value) { + return value.split(/(\S.+?[.!?])(?=\s+|$)/); + }; + + function diffSentences(oldStr, newStr, callback) { + return sentenceDiff.diff(oldStr, newStr, callback); + } + + + +/***/ }), +/* 7 */ +/***/ (function(module, exports, __webpack_require__) { + + /*istanbul ignore start*/'use strict'; + + exports.__esModule = true; + exports.cssDiff = undefined; + exports. /*istanbul ignore end*/diffCss = diffCss; + + var /*istanbul ignore start*/_base = __webpack_require__(1) /*istanbul ignore end*/; + + /*istanbul ignore start*/var _base2 = _interopRequireDefault(_base); + + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + + /*istanbul ignore end*/var cssDiff = /*istanbul ignore start*/exports. /*istanbul ignore end*/cssDiff = new /*istanbul ignore start*/_base2['default'] /*istanbul ignore end*/(); + cssDiff.tokenize = function (value) { + return value.split(/([{}:;,]|\s+)/); + }; + + function diffCss(oldStr, newStr, callback) { + return cssDiff.diff(oldStr, newStr, callback); + } + + + +/***/ }), +/* 8 */ +/***/ (function(module, exports, __webpack_require__) { + + /*istanbul ignore start*/'use strict'; + + exports.__esModule = true; + exports.jsonDiff = undefined; + + var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; + + exports. /*istanbul ignore end*/diffJson = diffJson; + /*istanbul ignore start*/exports. /*istanbul ignore end*/canonicalize = canonicalize; + + var /*istanbul ignore start*/_base = __webpack_require__(1) /*istanbul ignore end*/; + + /*istanbul ignore start*/var _base2 = _interopRequireDefault(_base); + + /*istanbul ignore end*/var /*istanbul ignore start*/_line = __webpack_require__(5) /*istanbul ignore end*/; + + /*istanbul ignore start*/function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + + /*istanbul ignore end*/var objectPrototypeToString = Object.prototype.toString; + + var jsonDiff = /*istanbul ignore start*/exports. /*istanbul ignore end*/jsonDiff = new /*istanbul ignore start*/_base2['default'] /*istanbul ignore end*/(); + // Discriminate between two lines of pretty-printed, serialized JSON where one of them has a + // dangling comma and the other doesn't. Turns out including the dangling comma yields the nicest output: + jsonDiff.useLongestToken = true; + + jsonDiff.tokenize = /*istanbul ignore start*/_line.lineDiff /*istanbul ignore end*/.tokenize; + jsonDiff.castInput = function (value) { + /*istanbul ignore start*/var _options = /*istanbul ignore end*/this.options, + undefinedReplacement = _options.undefinedReplacement, + _options$stringifyRep = _options.stringifyReplacer, + stringifyReplacer = _options$stringifyRep === undefined ? function (k, v) /*istanbul ignore start*/{ + return (/*istanbul ignore end*/typeof v === 'undefined' ? undefinedReplacement : v + ); + } : _options$stringifyRep; + + + return typeof value === 'string' ? value : JSON.stringify(canonicalize(value, null, null, stringifyReplacer), stringifyReplacer, ' '); + }; + jsonDiff.equals = function (left, right) { + return (/*istanbul ignore start*/_base2['default'] /*istanbul ignore end*/.prototype.equals.call(jsonDiff, left.replace(/,([\r\n])/g, '$1'), right.replace(/,([\r\n])/g, '$1')) + ); + }; + + function diffJson(oldObj, newObj, options) { + return jsonDiff.diff(oldObj, newObj, options); + } + + // This function handles the presence of circular references by bailing out when encountering an + // object that is already on the "stack" of items being processed. Accepts an optional replacer + function canonicalize(obj, stack, replacementStack, replacer, key) { + stack = stack || []; + replacementStack = replacementStack || []; + + if (replacer) { + obj = replacer(key, obj); + } + + var i = /*istanbul ignore start*/void 0 /*istanbul ignore end*/; + + for (i = 0; i < stack.length; i += 1) { + if (stack[i] === obj) { + return replacementStack[i]; + } + } + + var canonicalizedObj = /*istanbul ignore start*/void 0 /*istanbul ignore end*/; + + if ('[object Array]' === objectPrototypeToString.call(obj)) { + stack.push(obj); + canonicalizedObj = new Array(obj.length); + replacementStack.push(canonicalizedObj); + for (i = 0; i < obj.length; i += 1) { + canonicalizedObj[i] = canonicalize(obj[i], stack, replacementStack, replacer, key); + } + stack.pop(); + replacementStack.pop(); + return canonicalizedObj; + } + + if (obj && obj.toJSON) { + obj = obj.toJSON(); + } + + if ( /*istanbul ignore start*/(typeof /*istanbul ignore end*/obj === 'undefined' ? 'undefined' : _typeof(obj)) === 'object' && obj !== null) { + stack.push(obj); + canonicalizedObj = {}; + replacementStack.push(canonicalizedObj); + var sortedKeys = [], + _key = /*istanbul ignore start*/void 0 /*istanbul ignore end*/; + for (_key in obj) { + /* istanbul ignore else */ + if (obj.hasOwnProperty(_key)) { + sortedKeys.push(_key); + } + } + sortedKeys.sort(); + for (i = 0; i < sortedKeys.length; i += 1) { + _key = sortedKeys[i]; + canonicalizedObj[_key] = canonicalize(obj[_key], stack, replacementStack, replacer, _key); + } + stack.pop(); + replacementStack.pop(); + } else { + canonicalizedObj = obj; + } + return canonicalizedObj; + } + + + +/***/ }), +/* 9 */ +/***/ (function(module, exports, __webpack_require__) { + + /*istanbul ignore start*/'use strict'; + + exports.__esModule = true; + exports.arrayDiff = undefined; + exports. /*istanbul ignore end*/diffArrays = diffArrays; + + var /*istanbul ignore start*/_base = __webpack_require__(1) /*istanbul ignore end*/; + + /*istanbul ignore start*/var _base2 = _interopRequireDefault(_base); + + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + + /*istanbul ignore end*/var arrayDiff = /*istanbul ignore start*/exports. /*istanbul ignore end*/arrayDiff = new /*istanbul ignore start*/_base2['default'] /*istanbul ignore end*/(); + arrayDiff.tokenize = function (value) { + return value.slice(); + }; + arrayDiff.join = arrayDiff.removeEmpty = function (value) { + return value; + }; + + function diffArrays(oldArr, newArr, callback) { + return arrayDiff.diff(oldArr, newArr, callback); + } + + + +/***/ }), +/* 10 */ +/***/ (function(module, exports, __webpack_require__) { + + /*istanbul ignore start*/'use strict'; + + exports.__esModule = true; + exports. /*istanbul ignore end*/applyPatch = applyPatch; + /*istanbul ignore start*/exports. /*istanbul ignore end*/applyPatches = applyPatches; + + var /*istanbul ignore start*/_parse = __webpack_require__(11) /*istanbul ignore end*/; + + var /*istanbul ignore start*/_distanceIterator = __webpack_require__(12) /*istanbul ignore end*/; + + /*istanbul ignore start*/var _distanceIterator2 = _interopRequireDefault(_distanceIterator); + + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + + /*istanbul ignore end*/function applyPatch(source, uniDiff) { + /*istanbul ignore start*/var /*istanbul ignore end*/options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + + if (typeof uniDiff === 'string') { + uniDiff = /*istanbul ignore start*/(0, _parse.parsePatch) /*istanbul ignore end*/(uniDiff); + } + + if (Array.isArray(uniDiff)) { + if (uniDiff.length > 1) { + throw new Error('applyPatch only works with a single input.'); + } + + uniDiff = uniDiff[0]; + } + + // Apply the diff to the input + var lines = source.split(/\r\n|[\n\v\f\r\x85]/), + delimiters = source.match(/\r\n|[\n\v\f\r\x85]/g) || [], + hunks = uniDiff.hunks, + compareLine = options.compareLine || function (lineNumber, line, operation, patchContent) /*istanbul ignore start*/{ + return (/*istanbul ignore end*/line === patchContent + ); + }, + errorCount = 0, + fuzzFactor = options.fuzzFactor || 0, + minLine = 0, + offset = 0, + removeEOFNL = /*istanbul ignore start*/void 0 /*istanbul ignore end*/, + addEOFNL = /*istanbul ignore start*/void 0 /*istanbul ignore end*/; + + /** + * Checks if the hunk exactly fits on the provided location + */ + function hunkFits(hunk, toPos) { + for (var j = 0; j < hunk.lines.length; j++) { + var line = hunk.lines[j], + operation = line.length > 0 ? line[0] : ' ', + content = line.length > 0 ? line.substr(1) : line; + + if (operation === ' ' || operation === '-') { + // Context sanity check + if (!compareLine(toPos + 1, lines[toPos], operation, content)) { + errorCount++; + + if (errorCount > fuzzFactor) { + return false; + } + } + toPos++; + } + } + + return true; + } + + // Search best fit offsets for each hunk based on the previous ones + for (var i = 0; i < hunks.length; i++) { + var hunk = hunks[i], + maxLine = lines.length - hunk.oldLines, + localOffset = 0, + toPos = offset + hunk.oldStart - 1; + + var iterator = /*istanbul ignore start*/(0, _distanceIterator2['default']) /*istanbul ignore end*/(toPos, minLine, maxLine); + + for (; localOffset !== undefined; localOffset = iterator()) { + if (hunkFits(hunk, toPos + localOffset)) { + hunk.offset = offset += localOffset; + break; + } + } + + if (localOffset === undefined) { + return false; + } + + // Set lower text limit to end of the current hunk, so next ones don't try + // to fit over already patched text + minLine = hunk.offset + hunk.oldStart + hunk.oldLines; + } + + // Apply patch hunks + var diffOffset = 0; + for (var _i = 0; _i < hunks.length; _i++) { + var _hunk = hunks[_i], + _toPos = _hunk.oldStart + _hunk.offset + diffOffset - 1; + diffOffset += _hunk.newLines - _hunk.oldLines; + + if (_toPos < 0) { + // Creating a new file + _toPos = 0; + } + + for (var j = 0; j < _hunk.lines.length; j++) { + var line = _hunk.lines[j], + operation = line.length > 0 ? line[0] : ' ', + content = line.length > 0 ? line.substr(1) : line, + delimiter = _hunk.linedelimiters[j]; + + if (operation === ' ') { + _toPos++; + } else if (operation === '-') { + lines.splice(_toPos, 1); + delimiters.splice(_toPos, 1); + /* istanbul ignore else */ + } else if (operation === '+') { + lines.splice(_toPos, 0, content); + delimiters.splice(_toPos, 0, delimiter); + _toPos++; + } else if (operation === '\\') { + var previousOperation = _hunk.lines[j - 1] ? _hunk.lines[j - 1][0] : null; + if (previousOperation === '+') { + removeEOFNL = true; + } else if (previousOperation === '-') { + addEOFNL = true; + } + } + } + } + + // Handle EOFNL insertion/removal + if (removeEOFNL) { + while (!lines[lines.length - 1]) { + lines.pop(); + delimiters.pop(); + } + } else if (addEOFNL) { + lines.push(''); + delimiters.push('\n'); + } + for (var _k = 0; _k < lines.length - 1; _k++) { + lines[_k] = lines[_k] + delimiters[_k]; + } + return lines.join(''); + } + + // Wrapper that supports multiple file patches via callbacks. + function applyPatches(uniDiff, options) { + if (typeof uniDiff === 'string') { + uniDiff = /*istanbul ignore start*/(0, _parse.parsePatch) /*istanbul ignore end*/(uniDiff); + } + + var currentIndex = 0; + function processIndex() { + var index = uniDiff[currentIndex++]; + if (!index) { + return options.complete(); + } + + options.loadFile(index, function (err, data) { + if (err) { + return options.complete(err); + } + + var updatedContent = applyPatch(data, index, options); + options.patched(index, updatedContent, function (err) { + if (err) { + return options.complete(err); + } + + processIndex(); + }); + }); + } + processIndex(); + } + + + +/***/ }), +/* 11 */ +/***/ (function(module, exports) { + + /*istanbul ignore start*/'use strict'; + + exports.__esModule = true; + exports. /*istanbul ignore end*/parsePatch = parsePatch; + function parsePatch(uniDiff) { + /*istanbul ignore start*/var /*istanbul ignore end*/options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + var diffstr = uniDiff.split(/\r\n|[\n\v\f\r\x85]/), + delimiters = uniDiff.match(/\r\n|[\n\v\f\r\x85]/g) || [], + list = [], + i = 0; + + function parseIndex() { + var index = {}; + list.push(index); + + // Parse diff metadata + while (i < diffstr.length) { + var line = diffstr[i]; + + // File header found, end parsing diff metadata + if (/^(\-\-\-|\+\+\+|@@)\s/.test(line)) { + break; + } + + // Diff index + var header = /^(?:Index:|diff(?: -r \w+)+)\s+(.+?)\s*$/.exec(line); + if (header) { + index.index = header[1]; + } + + i++; + } + + // Parse file headers if they are defined. Unified diff requires them, but + // there's no technical issues to have an isolated hunk without file header + parseFileHeader(index); + parseFileHeader(index); + + // Parse hunks + index.hunks = []; + + while (i < diffstr.length) { + var _line = diffstr[i]; + + if (/^(Index:|diff|\-\-\-|\+\+\+)\s/.test(_line)) { + break; + } else if (/^@@/.test(_line)) { + index.hunks.push(parseHunk()); + } else if (_line && options.strict) { + // Ignore unexpected content unless in strict mode + throw new Error('Unknown line ' + (i + 1) + ' ' + JSON.stringify(_line)); + } else { + i++; + } + } + } + + // Parses the --- and +++ headers, if none are found, no lines + // are consumed. + function parseFileHeader(index) { + var fileHeader = /^(---|\+\+\+)\s+(.*)$/.exec(diffstr[i]); + if (fileHeader) { + var keyPrefix = fileHeader[1] === '---' ? 'old' : 'new'; + var data = fileHeader[2].split('\t', 2); + var fileName = data[0].replace(/\\\\/g, '\\'); + if (/^".*"$/.test(fileName)) { + fileName = fileName.substr(1, fileName.length - 2); + } + index[keyPrefix + 'FileName'] = fileName; + index[keyPrefix + 'Header'] = (data[1] || '').trim(); + + i++; + } + } + + // Parses a hunk + // This assumes that we are at the start of a hunk. + function parseHunk() { + var chunkHeaderIndex = i, + chunkHeaderLine = diffstr[i++], + chunkHeader = chunkHeaderLine.split(/@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/); + + var hunk = { + oldStart: +chunkHeader[1], + oldLines: +chunkHeader[2] || 1, + newStart: +chunkHeader[3], + newLines: +chunkHeader[4] || 1, + lines: [], + linedelimiters: [] + }; + + var addCount = 0, + removeCount = 0; + for (; i < diffstr.length; i++) { + // Lines starting with '---' could be mistaken for the "remove line" operation + // But they could be the header for the next file. Therefore prune such cases out. + if (diffstr[i].indexOf('--- ') === 0 && i + 2 < diffstr.length && diffstr[i + 1].indexOf('+++ ') === 0 && diffstr[i + 2].indexOf('@@') === 0) { + break; + } + var operation = diffstr[i].length == 0 && i != diffstr.length - 1 ? ' ' : diffstr[i][0]; + + if (operation === '+' || operation === '-' || operation === ' ' || operation === '\\') { + hunk.lines.push(diffstr[i]); + hunk.linedelimiters.push(delimiters[i] || '\n'); + + if (operation === '+') { + addCount++; + } else if (operation === '-') { + removeCount++; + } else if (operation === ' ') { + addCount++; + removeCount++; + } + } else { + break; + } + } + + // Handle the empty block count case + if (!addCount && hunk.newLines === 1) { + hunk.newLines = 0; + } + if (!removeCount && hunk.oldLines === 1) { + hunk.oldLines = 0; + } + + // Perform optional sanity checking + if (options.strict) { + if (addCount !== hunk.newLines) { + throw new Error('Added line count did not match for hunk at line ' + (chunkHeaderIndex + 1)); + } + if (removeCount !== hunk.oldLines) { + throw new Error('Removed line count did not match for hunk at line ' + (chunkHeaderIndex + 1)); + } + } + + return hunk; + } + + while (i < diffstr.length) { + parseIndex(); + } + + return list; + } + + + +/***/ }), +/* 12 */ +/***/ (function(module, exports) { + + /*istanbul ignore start*/"use strict"; + + exports.__esModule = true; + + exports["default"] = /*istanbul ignore end*/function (start, minLine, maxLine) { + var wantForward = true, + backwardExhausted = false, + forwardExhausted = false, + localOffset = 1; + + return function iterator() { + if (wantForward && !forwardExhausted) { + if (backwardExhausted) { + localOffset++; + } else { + wantForward = false; + } + + // Check if trying to fit beyond text length, and if not, check it fits + // after offset location (or desired location on first iteration) + if (start + localOffset <= maxLine) { + return localOffset; + } + + forwardExhausted = true; + } + + if (!backwardExhausted) { + if (!forwardExhausted) { + wantForward = true; + } + + // Check if trying to fit before text beginning, and if not, check it fits + // before offset location + if (minLine <= start - localOffset) { + return -localOffset++; + } + + backwardExhausted = true; + return iterator(); + } + + // We tried to fit hunk before text beginning and beyond text length, then + // hunk can't fit on the text. Return undefined + }; + }; + + + +/***/ }), +/* 13 */ +/***/ (function(module, exports, __webpack_require__) { + + /*istanbul ignore start*/'use strict'; + + exports.__esModule = true; + exports. /*istanbul ignore end*/calcLineCount = calcLineCount; + /*istanbul ignore start*/exports. /*istanbul ignore end*/merge = merge; + + var /*istanbul ignore start*/_create = __webpack_require__(14) /*istanbul ignore end*/; + + var /*istanbul ignore start*/_parse = __webpack_require__(11) /*istanbul ignore end*/; + + var /*istanbul ignore start*/_array = __webpack_require__(15) /*istanbul ignore end*/; + + /*istanbul ignore start*/function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } } + + /*istanbul ignore end*/function calcLineCount(hunk) { + /*istanbul ignore start*/var _calcOldNewLineCount = /*istanbul ignore end*/calcOldNewLineCount(hunk.lines), + oldLines = _calcOldNewLineCount.oldLines, + newLines = _calcOldNewLineCount.newLines; + + if (oldLines !== undefined) { + hunk.oldLines = oldLines; + } else { + delete hunk.oldLines; + } + + if (newLines !== undefined) { + hunk.newLines = newLines; + } else { + delete hunk.newLines; + } + } + + function merge(mine, theirs, base) { + mine = loadPatch(mine, base); + theirs = loadPatch(theirs, base); + + var ret = {}; + + // For index we just let it pass through as it doesn't have any necessary meaning. + // Leaving sanity checks on this to the API consumer that may know more about the + // meaning in their own context. + if (mine.index || theirs.index) { + ret.index = mine.index || theirs.index; + } + + if (mine.newFileName || theirs.newFileName) { + if (!fileNameChanged(mine)) { + // No header or no change in ours, use theirs (and ours if theirs does not exist) + ret.oldFileName = theirs.oldFileName || mine.oldFileName; + ret.newFileName = theirs.newFileName || mine.newFileName; + ret.oldHeader = theirs.oldHeader || mine.oldHeader; + ret.newHeader = theirs.newHeader || mine.newHeader; + } else if (!fileNameChanged(theirs)) { + // No header or no change in theirs, use ours + ret.oldFileName = mine.oldFileName; + ret.newFileName = mine.newFileName; + ret.oldHeader = mine.oldHeader; + ret.newHeader = mine.newHeader; + } else { + // Both changed... figure it out + ret.oldFileName = selectField(ret, mine.oldFileName, theirs.oldFileName); + ret.newFileName = selectField(ret, mine.newFileName, theirs.newFileName); + ret.oldHeader = selectField(ret, mine.oldHeader, theirs.oldHeader); + ret.newHeader = selectField(ret, mine.newHeader, theirs.newHeader); + } + } + + ret.hunks = []; + + var mineIndex = 0, + theirsIndex = 0, + mineOffset = 0, + theirsOffset = 0; + + while (mineIndex < mine.hunks.length || theirsIndex < theirs.hunks.length) { + var mineCurrent = mine.hunks[mineIndex] || { oldStart: Infinity }, + theirsCurrent = theirs.hunks[theirsIndex] || { oldStart: Infinity }; + + if (hunkBefore(mineCurrent, theirsCurrent)) { + // This patch does not overlap with any of the others, yay. + ret.hunks.push(cloneHunk(mineCurrent, mineOffset)); + mineIndex++; + theirsOffset += mineCurrent.newLines - mineCurrent.oldLines; + } else if (hunkBefore(theirsCurrent, mineCurrent)) { + // This patch does not overlap with any of the others, yay. + ret.hunks.push(cloneHunk(theirsCurrent, theirsOffset)); + theirsIndex++; + mineOffset += theirsCurrent.newLines - theirsCurrent.oldLines; + } else { + // Overlap, merge as best we can + var mergedHunk = { + oldStart: Math.min(mineCurrent.oldStart, theirsCurrent.oldStart), + oldLines: 0, + newStart: Math.min(mineCurrent.newStart + mineOffset, theirsCurrent.oldStart + theirsOffset), + newLines: 0, + lines: [] + }; + mergeLines(mergedHunk, mineCurrent.oldStart, mineCurrent.lines, theirsCurrent.oldStart, theirsCurrent.lines); + theirsIndex++; + mineIndex++; + + ret.hunks.push(mergedHunk); + } + } + + return ret; + } + + function loadPatch(param, base) { + if (typeof param === 'string') { + if (/^@@/m.test(param) || /^Index:/m.test(param)) { + return (/*istanbul ignore start*/(0, _parse.parsePatch) /*istanbul ignore end*/(param)[0] + ); + } + + if (!base) { + throw new Error('Must provide a base reference or pass in a patch'); + } + return (/*istanbul ignore start*/(0, _create.structuredPatch) /*istanbul ignore end*/(undefined, undefined, base, param) + ); + } + + return param; + } + + function fileNameChanged(patch) { + return patch.newFileName && patch.newFileName !== patch.oldFileName; + } + + function selectField(index, mine, theirs) { + if (mine === theirs) { + return mine; + } else { + index.conflict = true; + return { mine: mine, theirs: theirs }; + } + } + + function hunkBefore(test, check) { + return test.oldStart < check.oldStart && test.oldStart + test.oldLines < check.oldStart; + } + + function cloneHunk(hunk, offset) { + return { + oldStart: hunk.oldStart, oldLines: hunk.oldLines, + newStart: hunk.newStart + offset, newLines: hunk.newLines, + lines: hunk.lines + }; + } + + function mergeLines(hunk, mineOffset, mineLines, theirOffset, theirLines) { + // This will generally result in a conflicted hunk, but there are cases where the context + // is the only overlap where we can successfully merge the content here. + var mine = { offset: mineOffset, lines: mineLines, index: 0 }, + their = { offset: theirOffset, lines: theirLines, index: 0 }; + + // Handle any leading content + insertLeading(hunk, mine, their); + insertLeading(hunk, their, mine); + + // Now in the overlap content. Scan through and select the best changes from each. + while (mine.index < mine.lines.length && their.index < their.lines.length) { + var mineCurrent = mine.lines[mine.index], + theirCurrent = their.lines[their.index]; + + if ((mineCurrent[0] === '-' || mineCurrent[0] === '+') && (theirCurrent[0] === '-' || theirCurrent[0] === '+')) { + // Both modified ... + mutualChange(hunk, mine, their); + } else if (mineCurrent[0] === '+' && theirCurrent[0] === ' ') { + /*istanbul ignore start*/var _hunk$lines; + + /*istanbul ignore end*/ // Mine inserted + /*istanbul ignore start*/(_hunk$lines = /*istanbul ignore end*/hunk.lines).push. /*istanbul ignore start*/apply /*istanbul ignore end*/( /*istanbul ignore start*/_hunk$lines /*istanbul ignore end*/, /*istanbul ignore start*/_toConsumableArray( /*istanbul ignore end*/collectChange(mine))); + } else if (theirCurrent[0] === '+' && mineCurrent[0] === ' ') { + /*istanbul ignore start*/var _hunk$lines2; + + /*istanbul ignore end*/ // Theirs inserted + /*istanbul ignore start*/(_hunk$lines2 = /*istanbul ignore end*/hunk.lines).push. /*istanbul ignore start*/apply /*istanbul ignore end*/( /*istanbul ignore start*/_hunk$lines2 /*istanbul ignore end*/, /*istanbul ignore start*/_toConsumableArray( /*istanbul ignore end*/collectChange(their))); + } else if (mineCurrent[0] === '-' && theirCurrent[0] === ' ') { + // Mine removed or edited + removal(hunk, mine, their); + } else if (theirCurrent[0] === '-' && mineCurrent[0] === ' ') { + // Their removed or edited + removal(hunk, their, mine, true); + } else if (mineCurrent === theirCurrent) { + // Context identity + hunk.lines.push(mineCurrent); + mine.index++; + their.index++; + } else { + // Context mismatch + conflict(hunk, collectChange(mine), collectChange(their)); + } + } + + // Now push anything that may be remaining + insertTrailing(hunk, mine); + insertTrailing(hunk, their); + + calcLineCount(hunk); + } + + function mutualChange(hunk, mine, their) { + var myChanges = collectChange(mine), + theirChanges = collectChange(their); + + if (allRemoves(myChanges) && allRemoves(theirChanges)) { + // Special case for remove changes that are supersets of one another + if ( /*istanbul ignore start*/(0, _array.arrayStartsWith) /*istanbul ignore end*/(myChanges, theirChanges) && skipRemoveSuperset(their, myChanges, myChanges.length - theirChanges.length)) { + /*istanbul ignore start*/var _hunk$lines3; + + /*istanbul ignore end*/ /*istanbul ignore start*/(_hunk$lines3 = /*istanbul ignore end*/hunk.lines).push. /*istanbul ignore start*/apply /*istanbul ignore end*/( /*istanbul ignore start*/_hunk$lines3 /*istanbul ignore end*/, /*istanbul ignore start*/_toConsumableArray( /*istanbul ignore end*/myChanges)); + return; + } else if ( /*istanbul ignore start*/(0, _array.arrayStartsWith) /*istanbul ignore end*/(theirChanges, myChanges) && skipRemoveSuperset(mine, theirChanges, theirChanges.length - myChanges.length)) { + /*istanbul ignore start*/var _hunk$lines4; + + /*istanbul ignore end*/ /*istanbul ignore start*/(_hunk$lines4 = /*istanbul ignore end*/hunk.lines).push. /*istanbul ignore start*/apply /*istanbul ignore end*/( /*istanbul ignore start*/_hunk$lines4 /*istanbul ignore end*/, /*istanbul ignore start*/_toConsumableArray( /*istanbul ignore end*/theirChanges)); + return; + } + } else if ( /*istanbul ignore start*/(0, _array.arrayEqual) /*istanbul ignore end*/(myChanges, theirChanges)) { + /*istanbul ignore start*/var _hunk$lines5; + + /*istanbul ignore end*/ /*istanbul ignore start*/(_hunk$lines5 = /*istanbul ignore end*/hunk.lines).push. /*istanbul ignore start*/apply /*istanbul ignore end*/( /*istanbul ignore start*/_hunk$lines5 /*istanbul ignore end*/, /*istanbul ignore start*/_toConsumableArray( /*istanbul ignore end*/myChanges)); + return; + } + + conflict(hunk, myChanges, theirChanges); + } + + function removal(hunk, mine, their, swap) { + var myChanges = collectChange(mine), + theirChanges = collectContext(their, myChanges); + if (theirChanges.merged) { + /*istanbul ignore start*/var _hunk$lines6; + + /*istanbul ignore end*/ /*istanbul ignore start*/(_hunk$lines6 = /*istanbul ignore end*/hunk.lines).push. /*istanbul ignore start*/apply /*istanbul ignore end*/( /*istanbul ignore start*/_hunk$lines6 /*istanbul ignore end*/, /*istanbul ignore start*/_toConsumableArray( /*istanbul ignore end*/theirChanges.merged)); + } else { + conflict(hunk, swap ? theirChanges : myChanges, swap ? myChanges : theirChanges); + } + } + + function conflict(hunk, mine, their) { + hunk.conflict = true; + hunk.lines.push({ + conflict: true, + mine: mine, + theirs: their + }); + } + + function insertLeading(hunk, insert, their) { + while (insert.offset < their.offset && insert.index < insert.lines.length) { + var line = insert.lines[insert.index++]; + hunk.lines.push(line); + insert.offset++; + } + } + function insertTrailing(hunk, insert) { + while (insert.index < insert.lines.length) { + var line = insert.lines[insert.index++]; + hunk.lines.push(line); + } + } + + function collectChange(state) { + var ret = [], + operation = state.lines[state.index][0]; + while (state.index < state.lines.length) { + var line = state.lines[state.index]; + + // Group additions that are immediately after subtractions and treat them as one "atomic" modify change. + if (operation === '-' && line[0] === '+') { + operation = '+'; + } + + if (operation === line[0]) { + ret.push(line); + state.index++; + } else { + break; + } + } + + return ret; + } + function collectContext(state, matchChanges) { + var changes = [], + merged = [], + matchIndex = 0, + contextChanges = false, + conflicted = false; + while (matchIndex < matchChanges.length && state.index < state.lines.length) { + var change = state.lines[state.index], + match = matchChanges[matchIndex]; + + // Once we've hit our add, then we are done + if (match[0] === '+') { + break; + } + + contextChanges = contextChanges || change[0] !== ' '; + + merged.push(match); + matchIndex++; + + // Consume any additions in the other block as a conflict to attempt + // to pull in the remaining context after this + if (change[0] === '+') { + conflicted = true; + + while (change[0] === '+') { + changes.push(change); + change = state.lines[++state.index]; + } + } + + if (match.substr(1) === change.substr(1)) { + changes.push(change); + state.index++; + } else { + conflicted = true; + } + } + + if ((matchChanges[matchIndex] || '')[0] === '+' && contextChanges) { + conflicted = true; + } + + if (conflicted) { + return changes; + } + + while (matchIndex < matchChanges.length) { + merged.push(matchChanges[matchIndex++]); + } + + return { + merged: merged, + changes: changes + }; + } + + function allRemoves(changes) { + return changes.reduce(function (prev, change) { + return prev && change[0] === '-'; + }, true); + } + function skipRemoveSuperset(state, removeChanges, delta) { + for (var i = 0; i < delta; i++) { + var changeContent = removeChanges[removeChanges.length - delta + i].substr(1); + if (state.lines[state.index + i] !== ' ' + changeContent) { + return false; + } + } + + state.index += delta; + return true; + } + + function calcOldNewLineCount(lines) { + var oldLines = 0; + var newLines = 0; + + lines.forEach(function (line) { + if (typeof line !== 'string') { + var myCount = calcOldNewLineCount(line.mine); + var theirCount = calcOldNewLineCount(line.theirs); + + if (oldLines !== undefined) { + if (myCount.oldLines === theirCount.oldLines) { + oldLines += myCount.oldLines; + } else { + oldLines = undefined; + } + } + + if (newLines !== undefined) { + if (myCount.newLines === theirCount.newLines) { + newLines += myCount.newLines; + } else { + newLines = undefined; + } + } + } else { + if (newLines !== undefined && (line[0] === '+' || line[0] === ' ')) { + newLines++; + } + if (oldLines !== undefined && (line[0] === '-' || line[0] === ' ')) { + oldLines++; + } + } + }); + + return { oldLines: oldLines, newLines: newLines }; + } + + + +/***/ }), +/* 14 */ +/***/ (function(module, exports, __webpack_require__) { + + /*istanbul ignore start*/'use strict'; + + exports.__esModule = true; + exports. /*istanbul ignore end*/structuredPatch = structuredPatch; + /*istanbul ignore start*/exports. /*istanbul ignore end*/createTwoFilesPatch = createTwoFilesPatch; + /*istanbul ignore start*/exports. /*istanbul ignore end*/createPatch = createPatch; + + var /*istanbul ignore start*/_line = __webpack_require__(5) /*istanbul ignore end*/; + + /*istanbul ignore start*/function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } } + + /*istanbul ignore end*/function structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) { + if (!options) { + options = {}; + } + if (typeof options.context === 'undefined') { + options.context = 4; + } + + var diff = /*istanbul ignore start*/(0, _line.diffLines) /*istanbul ignore end*/(oldStr, newStr, options); + diff.push({ value: '', lines: [] }); // Append an empty value to make cleanup easier + + function contextLines(lines) { + return lines.map(function (entry) { + return ' ' + entry; + }); + } + + var hunks = []; + var oldRangeStart = 0, + newRangeStart = 0, + curRange = [], + oldLine = 1, + newLine = 1; + + /*istanbul ignore start*/var _loop = function _loop( /*istanbul ignore end*/i) { + var current = diff[i], + lines = current.lines || current.value.replace(/\n$/, '').split('\n'); + current.lines = lines; + + if (current.added || current.removed) { + /*istanbul ignore start*/var _curRange; + + /*istanbul ignore end*/ // If we have previous context, start with that + if (!oldRangeStart) { + var prev = diff[i - 1]; + oldRangeStart = oldLine; + newRangeStart = newLine; + + if (prev) { + curRange = options.context > 0 ? contextLines(prev.lines.slice(-options.context)) : []; + oldRangeStart -= curRange.length; + newRangeStart -= curRange.length; + } + } + + // Output our changes + /*istanbul ignore start*/(_curRange = /*istanbul ignore end*/curRange).push. /*istanbul ignore start*/apply /*istanbul ignore end*/( /*istanbul ignore start*/_curRange /*istanbul ignore end*/, /*istanbul ignore start*/_toConsumableArray( /*istanbul ignore end*/lines.map(function (entry) { + return (current.added ? '+' : '-') + entry; + }))); + + // Track the updated file position + if (current.added) { + newLine += lines.length; + } else { + oldLine += lines.length; + } + } else { + // Identical context lines. Track line changes + if (oldRangeStart) { + // Close out any changes that have been output (or join overlapping) + if (lines.length <= options.context * 2 && i < diff.length - 2) { + /*istanbul ignore start*/var _curRange2; + + /*istanbul ignore end*/ // Overlapping + /*istanbul ignore start*/(_curRange2 = /*istanbul ignore end*/curRange).push. /*istanbul ignore start*/apply /*istanbul ignore end*/( /*istanbul ignore start*/_curRange2 /*istanbul ignore end*/, /*istanbul ignore start*/_toConsumableArray( /*istanbul ignore end*/contextLines(lines))); + } else { + /*istanbul ignore start*/var _curRange3; + + /*istanbul ignore end*/ // end the range and output + var contextSize = Math.min(lines.length, options.context); + /*istanbul ignore start*/(_curRange3 = /*istanbul ignore end*/curRange).push. /*istanbul ignore start*/apply /*istanbul ignore end*/( /*istanbul ignore start*/_curRange3 /*istanbul ignore end*/, /*istanbul ignore start*/_toConsumableArray( /*istanbul ignore end*/contextLines(lines.slice(0, contextSize)))); + + var hunk = { + oldStart: oldRangeStart, + oldLines: oldLine - oldRangeStart + contextSize, + newStart: newRangeStart, + newLines: newLine - newRangeStart + contextSize, + lines: curRange + }; + if (i >= diff.length - 2 && lines.length <= options.context) { + // EOF is inside this hunk + var oldEOFNewline = /\n$/.test(oldStr); + var newEOFNewline = /\n$/.test(newStr); + if (lines.length == 0 && !oldEOFNewline) { + // special case: old has no eol and no trailing context; no-nl can end up before adds + curRange.splice(hunk.oldLines, 0, '\\ No newline at end of file'); + } else if (!oldEOFNewline || !newEOFNewline) { + curRange.push('\\ No newline at end of file'); + } + } + hunks.push(hunk); + + oldRangeStart = 0; + newRangeStart = 0; + curRange = []; + } + } + oldLine += lines.length; + newLine += lines.length; + } + }; + + for (var i = 0; i < diff.length; i++) { + /*istanbul ignore start*/_loop( /*istanbul ignore end*/i); + } + + return { + oldFileName: oldFileName, newFileName: newFileName, + oldHeader: oldHeader, newHeader: newHeader, + hunks: hunks + }; + } + + function createTwoFilesPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) { + var diff = structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options); + + var ret = []; + if (oldFileName == newFileName) { + ret.push('Index: ' + oldFileName); + } + ret.push('==================================================================='); + ret.push('--- ' + diff.oldFileName + (typeof diff.oldHeader === 'undefined' ? '' : '\t' + diff.oldHeader)); + ret.push('+++ ' + diff.newFileName + (typeof diff.newHeader === 'undefined' ? '' : '\t' + diff.newHeader)); + + for (var i = 0; i < diff.hunks.length; i++) { + var hunk = diff.hunks[i]; + ret.push('@@ -' + hunk.oldStart + ',' + hunk.oldLines + ' +' + hunk.newStart + ',' + hunk.newLines + ' @@'); + ret.push.apply(ret, hunk.lines); + } + + return ret.join('\n') + '\n'; + } + + function createPatch(fileName, oldStr, newStr, oldHeader, newHeader, options) { + return createTwoFilesPatch(fileName, fileName, oldStr, newStr, oldHeader, newHeader, options); + } + + + +/***/ }), +/* 15 */ +/***/ (function(module, exports) { + + /*istanbul ignore start*/"use strict"; + + exports.__esModule = true; + exports. /*istanbul ignore end*/arrayEqual = arrayEqual; + /*istanbul ignore start*/exports. /*istanbul ignore end*/arrayStartsWith = arrayStartsWith; + function arrayEqual(a, b) { + if (a.length !== b.length) { + return false; + } + + return arrayStartsWith(a, b); + } + + function arrayStartsWith(array, start) { + if (start.length > array.length) { + return false; + } + + for (var i = 0; i < start.length; i++) { + if (start[i] !== array[i]) { + return false; + } + } + + return true; + } + + + +/***/ }), +/* 16 */ +/***/ (function(module, exports) { + + /*istanbul ignore start*/"use strict"; + + exports.__esModule = true; + exports. /*istanbul ignore end*/convertChangesToDMP = convertChangesToDMP; + // See: http://code.google.com/p/google-diff-match-patch/wiki/API + function convertChangesToDMP(changes) { + var ret = [], + change = /*istanbul ignore start*/void 0 /*istanbul ignore end*/, + operation = /*istanbul ignore start*/void 0 /*istanbul ignore end*/; + for (var i = 0; i < changes.length; i++) { + change = changes[i]; + if (change.added) { + operation = 1; + } else if (change.removed) { + operation = -1; + } else { + operation = 0; + } + + ret.push([operation, change.value]); + } + return ret; + } + + + +/***/ }), +/* 17 */ +/***/ (function(module, exports) { + + /*istanbul ignore start*/'use strict'; + + exports.__esModule = true; + exports. /*istanbul ignore end*/convertChangesToXML = convertChangesToXML; + function convertChangesToXML(changes) { + var ret = []; + for (var i = 0; i < changes.length; i++) { + var change = changes[i]; + if (change.added) { + ret.push(''); + } else if (change.removed) { + ret.push(''); + } + + ret.push(escapeHTML(change.value)); + + if (change.added) { + ret.push(''); + } else if (change.removed) { + ret.push(''); + } + } + return ret.join(''); + } + + function escapeHTML(s) { + var n = s; + n = n.replace(/&/g, '&'); + n = n.replace(//g, '>'); + n = n.replace(/"/g, '"'); + + return n; + } + + + +/***/ }) +/******/ ]) +}); +; +},{}],46:[function(require,module,exports){ +'use strict'; + +var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g; + +module.exports = function (str) { + if (typeof str !== 'string') { + throw new TypeError('Expected a string'); + } + + return str.replace(matchOperatorsRe, '\\$&'); +}; + +},{}],47:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var objectCreate = Object.create || objectCreatePolyfill +var objectKeys = Object.keys || objectKeysPolyfill +var bind = Function.prototype.bind || functionBindPolyfill + +function EventEmitter() { + if (!this._events || !Object.prototype.hasOwnProperty.call(this, '_events')) { + this._events = objectCreate(null); + this._eventsCount = 0; + } + + this._maxListeners = this._maxListeners || undefined; +} +module.exports = EventEmitter; + +// Backwards-compat with node 0.10.x +EventEmitter.EventEmitter = EventEmitter; + +EventEmitter.prototype._events = undefined; +EventEmitter.prototype._maxListeners = undefined; + +// By default EventEmitters will print a warning if more than 10 listeners are +// added to it. This is a useful default which helps finding memory leaks. +var defaultMaxListeners = 10; + +var hasDefineProperty; +try { + var o = {}; + if (Object.defineProperty) Object.defineProperty(o, 'x', { value: 0 }); + hasDefineProperty = o.x === 0; +} catch (err) { hasDefineProperty = false } +if (hasDefineProperty) { + Object.defineProperty(EventEmitter, 'defaultMaxListeners', { + enumerable: true, + get: function() { + return defaultMaxListeners; + }, + set: function(arg) { + // check whether the input is a positive number (whose value is zero or + // greater and not a NaN). + if (typeof arg !== 'number' || arg < 0 || arg !== arg) + throw new TypeError('"defaultMaxListeners" must be a positive number'); + defaultMaxListeners = arg; + } + }); +} else { + EventEmitter.defaultMaxListeners = defaultMaxListeners; +} + +// Obviously not all Emitters should be limited to 10. This function allows +// that to be increased. Set to zero for unlimited. +EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) { + if (typeof n !== 'number' || n < 0 || isNaN(n)) + throw new TypeError('"n" argument must be a positive number'); + this._maxListeners = n; + return this; +}; + +function $getMaxListeners(that) { + if (that._maxListeners === undefined) + return EventEmitter.defaultMaxListeners; + return that._maxListeners; +} + +EventEmitter.prototype.getMaxListeners = function getMaxListeners() { + return $getMaxListeners(this); +}; + +// These standalone emit* functions are used to optimize calling of event +// handlers for fast cases because emit() itself often has a variable number of +// arguments and can be deoptimized because of that. These functions always have +// the same number of arguments and thus do not get deoptimized, so the code +// inside them can execute faster. +function emitNone(handler, isFn, self) { + if (isFn) + handler.call(self); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self); + } +} +function emitOne(handler, isFn, self, arg1) { + if (isFn) + handler.call(self, arg1); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self, arg1); + } +} +function emitTwo(handler, isFn, self, arg1, arg2) { + if (isFn) + handler.call(self, arg1, arg2); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self, arg1, arg2); + } +} +function emitThree(handler, isFn, self, arg1, arg2, arg3) { + if (isFn) + handler.call(self, arg1, arg2, arg3); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self, arg1, arg2, arg3); + } +} + +function emitMany(handler, isFn, self, args) { + if (isFn) + handler.apply(self, args); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].apply(self, args); + } +} + +EventEmitter.prototype.emit = function emit(type) { + var er, handler, len, args, i, events; + var doError = (type === 'error'); + + events = this._events; + if (events) + doError = (doError && events.error == null); + else if (!doError) + return false; + + // If there is no 'error' event listener then throw. + if (doError) { + if (arguments.length > 1) + er = arguments[1]; + if (er instanceof Error) { + throw er; // Unhandled 'error' event + } else { + // At least give some kind of context to the user + var err = new Error('Unhandled "error" event. (' + er + ')'); + err.context = er; + throw err; + } + return false; + } + + handler = events[type]; + + if (!handler) + return false; + + var isFn = typeof handler === 'function'; + len = arguments.length; + switch (len) { + // fast cases + case 1: + emitNone(handler, isFn, this); + break; + case 2: + emitOne(handler, isFn, this, arguments[1]); + break; + case 3: + emitTwo(handler, isFn, this, arguments[1], arguments[2]); + break; + case 4: + emitThree(handler, isFn, this, arguments[1], arguments[2], arguments[3]); + break; + // slower + default: + args = new Array(len - 1); + for (i = 1; i < len; i++) + args[i - 1] = arguments[i]; + emitMany(handler, isFn, this, args); + } + + return true; +}; + +function _addListener(target, type, listener, prepend) { + var m; + var events; + var existing; + + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + + events = target._events; + if (!events) { + events = target._events = objectCreate(null); + target._eventsCount = 0; + } else { + // To avoid recursion in the case that type === "newListener"! Before + // adding it to the listeners, first emit "newListener". + if (events.newListener) { + target.emit('newListener', type, + listener.listener ? listener.listener : listener); + + // Re-assign `events` because a newListener handler could have caused the + // this._events to be assigned to a new object + events = target._events; + } + existing = events[type]; + } + + if (!existing) { + // Optimize the case of one listener. Don't need the extra array object. + existing = events[type] = listener; + ++target._eventsCount; + } else { + if (typeof existing === 'function') { + // Adding the second element, need to change to array. + existing = events[type] = + prepend ? [listener, existing] : [existing, listener]; + } else { + // If we've already got an array, just append. + if (prepend) { + existing.unshift(listener); + } else { + existing.push(listener); + } + } + + // Check for listener leak + if (!existing.warned) { + m = $getMaxListeners(target); + if (m && m > 0 && existing.length > m) { + existing.warned = true; + var w = new Error('Possible EventEmitter memory leak detected. ' + + existing.length + ' "' + String(type) + '" listeners ' + + 'added. Use emitter.setMaxListeners() to ' + + 'increase limit.'); + w.name = 'MaxListenersExceededWarning'; + w.emitter = target; + w.type = type; + w.count = existing.length; + if (typeof console === 'object' && console.warn) { + console.warn('%s: %s', w.name, w.message); + } + } + } + } + + return target; +} + +EventEmitter.prototype.addListener = function addListener(type, listener) { + return _addListener(this, type, listener, false); +}; + +EventEmitter.prototype.on = EventEmitter.prototype.addListener; + +EventEmitter.prototype.prependListener = + function prependListener(type, listener) { + return _addListener(this, type, listener, true); + }; + +function onceWrapper() { + if (!this.fired) { + this.target.removeListener(this.type, this.wrapFn); + this.fired = true; + switch (arguments.length) { + case 0: + return this.listener.call(this.target); + case 1: + return this.listener.call(this.target, arguments[0]); + case 2: + return this.listener.call(this.target, arguments[0], arguments[1]); + case 3: + return this.listener.call(this.target, arguments[0], arguments[1], + arguments[2]); + default: + var args = new Array(arguments.length); + for (var i = 0; i < args.length; ++i) + args[i] = arguments[i]; + this.listener.apply(this.target, args); + } + } +} + +function _onceWrap(target, type, listener) { + var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener }; + var wrapped = bind.call(onceWrapper, state); + wrapped.listener = listener; + state.wrapFn = wrapped; + return wrapped; +} + +EventEmitter.prototype.once = function once(type, listener) { + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + this.on(type, _onceWrap(this, type, listener)); + return this; +}; + +EventEmitter.prototype.prependOnceListener = + function prependOnceListener(type, listener) { + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + this.prependListener(type, _onceWrap(this, type, listener)); + return this; + }; + +// Emits a 'removeListener' event if and only if the listener was removed. +EventEmitter.prototype.removeListener = + function removeListener(type, listener) { + var list, events, position, i, originalListener; + + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + + events = this._events; + if (!events) + return this; + + list = events[type]; + if (!list) + return this; + + if (list === listener || list.listener === listener) { + if (--this._eventsCount === 0) + this._events = objectCreate(null); + else { + delete events[type]; + if (events.removeListener) + this.emit('removeListener', type, list.listener || listener); + } + } else if (typeof list !== 'function') { + position = -1; + + for (i = list.length - 1; i >= 0; i--) { + if (list[i] === listener || list[i].listener === listener) { + originalListener = list[i].listener; + position = i; + break; + } + } + + if (position < 0) + return this; + + if (position === 0) + list.shift(); + else + spliceOne(list, position); + + if (list.length === 1) + events[type] = list[0]; + + if (events.removeListener) + this.emit('removeListener', type, originalListener || listener); + } + + return this; + }; + +EventEmitter.prototype.removeAllListeners = + function removeAllListeners(type) { + var listeners, events, i; + + events = this._events; + if (!events) + return this; + + // not listening for removeListener, no need to emit + if (!events.removeListener) { + if (arguments.length === 0) { + this._events = objectCreate(null); + this._eventsCount = 0; + } else if (events[type]) { + if (--this._eventsCount === 0) + this._events = objectCreate(null); + else + delete events[type]; + } + return this; + } + + // emit removeListener for all listeners on all events + if (arguments.length === 0) { + var keys = objectKeys(events); + var key; + for (i = 0; i < keys.length; ++i) { + key = keys[i]; + if (key === 'removeListener') continue; + this.removeAllListeners(key); + } + this.removeAllListeners('removeListener'); + this._events = objectCreate(null); + this._eventsCount = 0; + return this; + } + + listeners = events[type]; + + if (typeof listeners === 'function') { + this.removeListener(type, listeners); + } else if (listeners) { + // LIFO order + for (i = listeners.length - 1; i >= 0; i--) { + this.removeListener(type, listeners[i]); + } + } + + return this; + }; + +EventEmitter.prototype.listeners = function listeners(type) { + var evlistener; + var ret; + var events = this._events; + + if (!events) + ret = []; + else { + evlistener = events[type]; + if (!evlistener) + ret = []; + else if (typeof evlistener === 'function') + ret = [evlistener.listener || evlistener]; + else + ret = unwrapListeners(evlistener); + } + + return ret; +}; + +EventEmitter.listenerCount = function(emitter, type) { + if (typeof emitter.listenerCount === 'function') { + return emitter.listenerCount(type); + } else { + return listenerCount.call(emitter, type); + } +}; + +EventEmitter.prototype.listenerCount = listenerCount; +function listenerCount(type) { + var events = this._events; + + if (events) { + var evlistener = events[type]; + + if (typeof evlistener === 'function') { + return 1; + } else if (evlistener) { + return evlistener.length; + } + } + + return 0; +} + +EventEmitter.prototype.eventNames = function eventNames() { + return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : []; +}; + +// About 1.5x faster than the two-arg version of Array#splice(). +function spliceOne(list, index) { + for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1) + list[i] = list[k]; + list.pop(); +} + +function arrayClone(arr, n) { + var copy = new Array(n); + for (var i = 0; i < n; ++i) + copy[i] = arr[i]; + return copy; +} + +function unwrapListeners(arr) { + var ret = new Array(arr.length); + for (var i = 0; i < ret.length; ++i) { + ret[i] = arr[i].listener || arr[i]; + } + return ret; +} + +function objectCreatePolyfill(proto) { + var F = function() {}; + F.prototype = proto; + return new F; +} +function objectKeysPolyfill(obj) { + var keys = []; + for (var k in obj) if (Object.prototype.hasOwnProperty.call(obj, k)) { + keys.push(k); + } + return k; +} +function functionBindPolyfill(context) { + var fn = this; + return function () { + return fn.apply(context, arguments); + }; +} + +},{}],48:[function(require,module,exports){ +(function (global){ +/*! https://mths.be/he v1.1.1 by @mathias | MIT license */ +;(function(root) { + + // Detect free variables `exports`. + var freeExports = typeof exports == 'object' && exports; + + // Detect free variable `module`. + var freeModule = typeof module == 'object' && module && + module.exports == freeExports && module; + + // Detect free variable `global`, from Node.js or Browserified code, + // and use it as `root`. + var freeGlobal = typeof global == 'object' && global; + if (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal) { + root = freeGlobal; + } + + /*--------------------------------------------------------------------------*/ + + // All astral symbols. + var regexAstralSymbols = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g; + // All ASCII symbols (not just printable ASCII) except those listed in the + // first column of the overrides table. + // https://html.spec.whatwg.org/multipage/syntax.html#table-charref-overrides + var regexAsciiWhitelist = /[\x01-\x7F]/g; + // All BMP symbols that are not ASCII newlines, printable ASCII symbols, or + // code points listed in the first column of the overrides table on + // https://html.spec.whatwg.org/multipage/syntax.html#table-charref-overrides. + var regexBmpWhitelist = /[\x01-\t\x0B\f\x0E-\x1F\x7F\x81\x8D\x8F\x90\x9D\xA0-\uFFFF]/g; + + var regexEncodeNonAscii = /<\u20D2|=\u20E5|>\u20D2|\u205F\u200A|\u219D\u0338|\u2202\u0338|\u2220\u20D2|\u2229\uFE00|\u222A\uFE00|\u223C\u20D2|\u223D\u0331|\u223E\u0333|\u2242\u0338|\u224B\u0338|\u224D\u20D2|\u224E\u0338|\u224F\u0338|\u2250\u0338|\u2261\u20E5|\u2264\u20D2|\u2265\u20D2|\u2266\u0338|\u2267\u0338|\u2268\uFE00|\u2269\uFE00|\u226A\u0338|\u226A\u20D2|\u226B\u0338|\u226B\u20D2|\u227F\u0338|\u2282\u20D2|\u2283\u20D2|\u228A\uFE00|\u228B\uFE00|\u228F\u0338|\u2290\u0338|\u2293\uFE00|\u2294\uFE00|\u22B4\u20D2|\u22B5\u20D2|\u22D8\u0338|\u22D9\u0338|\u22DA\uFE00|\u22DB\uFE00|\u22F5\u0338|\u22F9\u0338|\u2933\u0338|\u29CF\u0338|\u29D0\u0338|\u2A6D\u0338|\u2A70\u0338|\u2A7D\u0338|\u2A7E\u0338|\u2AA1\u0338|\u2AA2\u0338|\u2AAC\uFE00|\u2AAD\uFE00|\u2AAF\u0338|\u2AB0\u0338|\u2AC5\u0338|\u2AC6\u0338|\u2ACB\uFE00|\u2ACC\uFE00|\u2AFD\u20E5|[\xA0-\u0113\u0116-\u0122\u0124-\u012B\u012E-\u014D\u0150-\u017E\u0192\u01B5\u01F5\u0237\u02C6\u02C7\u02D8-\u02DD\u0311\u0391-\u03A1\u03A3-\u03A9\u03B1-\u03C9\u03D1\u03D2\u03D5\u03D6\u03DC\u03DD\u03F0\u03F1\u03F5\u03F6\u0401-\u040C\u040E-\u044F\u0451-\u045C\u045E\u045F\u2002-\u2005\u2007-\u2010\u2013-\u2016\u2018-\u201A\u201C-\u201E\u2020-\u2022\u2025\u2026\u2030-\u2035\u2039\u203A\u203E\u2041\u2043\u2044\u204F\u2057\u205F-\u2063\u20AC\u20DB\u20DC\u2102\u2105\u210A-\u2113\u2115-\u211E\u2122\u2124\u2127-\u2129\u212C\u212D\u212F-\u2131\u2133-\u2138\u2145-\u2148\u2153-\u215E\u2190-\u219B\u219D-\u21A7\u21A9-\u21AE\u21B0-\u21B3\u21B5-\u21B7\u21BA-\u21DB\u21DD\u21E4\u21E5\u21F5\u21FD-\u2205\u2207-\u2209\u220B\u220C\u220F-\u2214\u2216-\u2218\u221A\u221D-\u2238\u223A-\u2257\u2259\u225A\u225C\u225F-\u2262\u2264-\u228B\u228D-\u229B\u229D-\u22A5\u22A7-\u22B0\u22B2-\u22BB\u22BD-\u22DB\u22DE-\u22E3\u22E6-\u22F7\u22F9-\u22FE\u2305\u2306\u2308-\u2310\u2312\u2313\u2315\u2316\u231C-\u231F\u2322\u2323\u232D\u232E\u2336\u233D\u233F\u237C\u23B0\u23B1\u23B4-\u23B6\u23DC-\u23DF\u23E2\u23E7\u2423\u24C8\u2500\u2502\u250C\u2510\u2514\u2518\u251C\u2524\u252C\u2534\u253C\u2550-\u256C\u2580\u2584\u2588\u2591-\u2593\u25A1\u25AA\u25AB\u25AD\u25AE\u25B1\u25B3-\u25B5\u25B8\u25B9\u25BD-\u25BF\u25C2\u25C3\u25CA\u25CB\u25EC\u25EF\u25F8-\u25FC\u2605\u2606\u260E\u2640\u2642\u2660\u2663\u2665\u2666\u266A\u266D-\u266F\u2713\u2717\u2720\u2736\u2758\u2772\u2773\u27C8\u27C9\u27E6-\u27ED\u27F5-\u27FA\u27FC\u27FF\u2902-\u2905\u290C-\u2913\u2916\u2919-\u2920\u2923-\u292A\u2933\u2935-\u2939\u293C\u293D\u2945\u2948-\u294B\u294E-\u2976\u2978\u2979\u297B-\u297F\u2985\u2986\u298B-\u2996\u299A\u299C\u299D\u29A4-\u29B7\u29B9\u29BB\u29BC\u29BE-\u29C5\u29C9\u29CD-\u29D0\u29DC-\u29DE\u29E3-\u29E5\u29EB\u29F4\u29F6\u2A00-\u2A02\u2A04\u2A06\u2A0C\u2A0D\u2A10-\u2A17\u2A22-\u2A27\u2A29\u2A2A\u2A2D-\u2A31\u2A33-\u2A3C\u2A3F\u2A40\u2A42-\u2A4D\u2A50\u2A53-\u2A58\u2A5A-\u2A5D\u2A5F\u2A66\u2A6A\u2A6D-\u2A75\u2A77-\u2A9A\u2A9D-\u2AA2\u2AA4-\u2AB0\u2AB3-\u2AC8\u2ACB\u2ACC\u2ACF-\u2ADB\u2AE4\u2AE6-\u2AE9\u2AEB-\u2AF3\u2AFD\uFB00-\uFB04]|\uD835[\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDCCF\uDD04\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDD6B]/g; + var encodeMap = {'\xAD':'shy','\u200C':'zwnj','\u200D':'zwj','\u200E':'lrm','\u2063':'ic','\u2062':'it','\u2061':'af','\u200F':'rlm','\u200B':'ZeroWidthSpace','\u2060':'NoBreak','\u0311':'DownBreve','\u20DB':'tdot','\u20DC':'DotDot','\t':'Tab','\n':'NewLine','\u2008':'puncsp','\u205F':'MediumSpace','\u2009':'thinsp','\u200A':'hairsp','\u2004':'emsp13','\u2002':'ensp','\u2005':'emsp14','\u2003':'emsp','\u2007':'numsp','\xA0':'nbsp','\u205F\u200A':'ThickSpace','\u203E':'oline','_':'lowbar','\u2010':'dash','\u2013':'ndash','\u2014':'mdash','\u2015':'horbar',',':'comma',';':'semi','\u204F':'bsemi',':':'colon','\u2A74':'Colone','!':'excl','\xA1':'iexcl','?':'quest','\xBF':'iquest','.':'period','\u2025':'nldr','\u2026':'mldr','\xB7':'middot','\'':'apos','\u2018':'lsquo','\u2019':'rsquo','\u201A':'sbquo','\u2039':'lsaquo','\u203A':'rsaquo','"':'quot','\u201C':'ldquo','\u201D':'rdquo','\u201E':'bdquo','\xAB':'laquo','\xBB':'raquo','(':'lpar',')':'rpar','[':'lsqb',']':'rsqb','{':'lcub','}':'rcub','\u2308':'lceil','\u2309':'rceil','\u230A':'lfloor','\u230B':'rfloor','\u2985':'lopar','\u2986':'ropar','\u298B':'lbrke','\u298C':'rbrke','\u298D':'lbrkslu','\u298E':'rbrksld','\u298F':'lbrksld','\u2990':'rbrkslu','\u2991':'langd','\u2992':'rangd','\u2993':'lparlt','\u2994':'rpargt','\u2995':'gtlPar','\u2996':'ltrPar','\u27E6':'lobrk','\u27E7':'robrk','\u27E8':'lang','\u27E9':'rang','\u27EA':'Lang','\u27EB':'Rang','\u27EC':'loang','\u27ED':'roang','\u2772':'lbbrk','\u2773':'rbbrk','\u2016':'Vert','\xA7':'sect','\xB6':'para','@':'commat','*':'ast','/':'sol','undefined':null,'&':'amp','#':'num','%':'percnt','\u2030':'permil','\u2031':'pertenk','\u2020':'dagger','\u2021':'Dagger','\u2022':'bull','\u2043':'hybull','\u2032':'prime','\u2033':'Prime','\u2034':'tprime','\u2057':'qprime','\u2035':'bprime','\u2041':'caret','`':'grave','\xB4':'acute','\u02DC':'tilde','^':'Hat','\xAF':'macr','\u02D8':'breve','\u02D9':'dot','\xA8':'die','\u02DA':'ring','\u02DD':'dblac','\xB8':'cedil','\u02DB':'ogon','\u02C6':'circ','\u02C7':'caron','\xB0':'deg','\xA9':'copy','\xAE':'reg','\u2117':'copysr','\u2118':'wp','\u211E':'rx','\u2127':'mho','\u2129':'iiota','\u2190':'larr','\u219A':'nlarr','\u2192':'rarr','\u219B':'nrarr','\u2191':'uarr','\u2193':'darr','\u2194':'harr','\u21AE':'nharr','\u2195':'varr','\u2196':'nwarr','\u2197':'nearr','\u2198':'searr','\u2199':'swarr','\u219D':'rarrw','\u219D\u0338':'nrarrw','\u219E':'Larr','\u219F':'Uarr','\u21A0':'Rarr','\u21A1':'Darr','\u21A2':'larrtl','\u21A3':'rarrtl','\u21A4':'mapstoleft','\u21A5':'mapstoup','\u21A6':'map','\u21A7':'mapstodown','\u21A9':'larrhk','\u21AA':'rarrhk','\u21AB':'larrlp','\u21AC':'rarrlp','\u21AD':'harrw','\u21B0':'lsh','\u21B1':'rsh','\u21B2':'ldsh','\u21B3':'rdsh','\u21B5':'crarr','\u21B6':'cularr','\u21B7':'curarr','\u21BA':'olarr','\u21BB':'orarr','\u21BC':'lharu','\u21BD':'lhard','\u21BE':'uharr','\u21BF':'uharl','\u21C0':'rharu','\u21C1':'rhard','\u21C2':'dharr','\u21C3':'dharl','\u21C4':'rlarr','\u21C5':'udarr','\u21C6':'lrarr','\u21C7':'llarr','\u21C8':'uuarr','\u21C9':'rrarr','\u21CA':'ddarr','\u21CB':'lrhar','\u21CC':'rlhar','\u21D0':'lArr','\u21CD':'nlArr','\u21D1':'uArr','\u21D2':'rArr','\u21CF':'nrArr','\u21D3':'dArr','\u21D4':'iff','\u21CE':'nhArr','\u21D5':'vArr','\u21D6':'nwArr','\u21D7':'neArr','\u21D8':'seArr','\u21D9':'swArr','\u21DA':'lAarr','\u21DB':'rAarr','\u21DD':'zigrarr','\u21E4':'larrb','\u21E5':'rarrb','\u21F5':'duarr','\u21FD':'loarr','\u21FE':'roarr','\u21FF':'hoarr','\u2200':'forall','\u2201':'comp','\u2202':'part','\u2202\u0338':'npart','\u2203':'exist','\u2204':'nexist','\u2205':'empty','\u2207':'Del','\u2208':'in','\u2209':'notin','\u220B':'ni','\u220C':'notni','\u03F6':'bepsi','\u220F':'prod','\u2210':'coprod','\u2211':'sum','+':'plus','\xB1':'pm','\xF7':'div','\xD7':'times','<':'lt','\u226E':'nlt','<\u20D2':'nvlt','=':'equals','\u2260':'ne','=\u20E5':'bne','\u2A75':'Equal','>':'gt','\u226F':'ngt','>\u20D2':'nvgt','\xAC':'not','|':'vert','\xA6':'brvbar','\u2212':'minus','\u2213':'mp','\u2214':'plusdo','\u2044':'frasl','\u2216':'setmn','\u2217':'lowast','\u2218':'compfn','\u221A':'Sqrt','\u221D':'prop','\u221E':'infin','\u221F':'angrt','\u2220':'ang','\u2220\u20D2':'nang','\u2221':'angmsd','\u2222':'angsph','\u2223':'mid','\u2224':'nmid','\u2225':'par','\u2226':'npar','\u2227':'and','\u2228':'or','\u2229':'cap','\u2229\uFE00':'caps','\u222A':'cup','\u222A\uFE00':'cups','\u222B':'int','\u222C':'Int','\u222D':'tint','\u2A0C':'qint','\u222E':'oint','\u222F':'Conint','\u2230':'Cconint','\u2231':'cwint','\u2232':'cwconint','\u2233':'awconint','\u2234':'there4','\u2235':'becaus','\u2236':'ratio','\u2237':'Colon','\u2238':'minusd','\u223A':'mDDot','\u223B':'homtht','\u223C':'sim','\u2241':'nsim','\u223C\u20D2':'nvsim','\u223D':'bsim','\u223D\u0331':'race','\u223E':'ac','\u223E\u0333':'acE','\u223F':'acd','\u2240':'wr','\u2242':'esim','\u2242\u0338':'nesim','\u2243':'sime','\u2244':'nsime','\u2245':'cong','\u2247':'ncong','\u2246':'simne','\u2248':'ap','\u2249':'nap','\u224A':'ape','\u224B':'apid','\u224B\u0338':'napid','\u224C':'bcong','\u224D':'CupCap','\u226D':'NotCupCap','\u224D\u20D2':'nvap','\u224E':'bump','\u224E\u0338':'nbump','\u224F':'bumpe','\u224F\u0338':'nbumpe','\u2250':'doteq','\u2250\u0338':'nedot','\u2251':'eDot','\u2252':'efDot','\u2253':'erDot','\u2254':'colone','\u2255':'ecolon','\u2256':'ecir','\u2257':'cire','\u2259':'wedgeq','\u225A':'veeeq','\u225C':'trie','\u225F':'equest','\u2261':'equiv','\u2262':'nequiv','\u2261\u20E5':'bnequiv','\u2264':'le','\u2270':'nle','\u2264\u20D2':'nvle','\u2265':'ge','\u2271':'nge','\u2265\u20D2':'nvge','\u2266':'lE','\u2266\u0338':'nlE','\u2267':'gE','\u2267\u0338':'ngE','\u2268\uFE00':'lvnE','\u2268':'lnE','\u2269':'gnE','\u2269\uFE00':'gvnE','\u226A':'ll','\u226A\u0338':'nLtv','\u226A\u20D2':'nLt','\u226B':'gg','\u226B\u0338':'nGtv','\u226B\u20D2':'nGt','\u226C':'twixt','\u2272':'lsim','\u2274':'nlsim','\u2273':'gsim','\u2275':'ngsim','\u2276':'lg','\u2278':'ntlg','\u2277':'gl','\u2279':'ntgl','\u227A':'pr','\u2280':'npr','\u227B':'sc','\u2281':'nsc','\u227C':'prcue','\u22E0':'nprcue','\u227D':'sccue','\u22E1':'nsccue','\u227E':'prsim','\u227F':'scsim','\u227F\u0338':'NotSucceedsTilde','\u2282':'sub','\u2284':'nsub','\u2282\u20D2':'vnsub','\u2283':'sup','\u2285':'nsup','\u2283\u20D2':'vnsup','\u2286':'sube','\u2288':'nsube','\u2287':'supe','\u2289':'nsupe','\u228A\uFE00':'vsubne','\u228A':'subne','\u228B\uFE00':'vsupne','\u228B':'supne','\u228D':'cupdot','\u228E':'uplus','\u228F':'sqsub','\u228F\u0338':'NotSquareSubset','\u2290':'sqsup','\u2290\u0338':'NotSquareSuperset','\u2291':'sqsube','\u22E2':'nsqsube','\u2292':'sqsupe','\u22E3':'nsqsupe','\u2293':'sqcap','\u2293\uFE00':'sqcaps','\u2294':'sqcup','\u2294\uFE00':'sqcups','\u2295':'oplus','\u2296':'ominus','\u2297':'otimes','\u2298':'osol','\u2299':'odot','\u229A':'ocir','\u229B':'oast','\u229D':'odash','\u229E':'plusb','\u229F':'minusb','\u22A0':'timesb','\u22A1':'sdotb','\u22A2':'vdash','\u22AC':'nvdash','\u22A3':'dashv','\u22A4':'top','\u22A5':'bot','\u22A7':'models','\u22A8':'vDash','\u22AD':'nvDash','\u22A9':'Vdash','\u22AE':'nVdash','\u22AA':'Vvdash','\u22AB':'VDash','\u22AF':'nVDash','\u22B0':'prurel','\u22B2':'vltri','\u22EA':'nltri','\u22B3':'vrtri','\u22EB':'nrtri','\u22B4':'ltrie','\u22EC':'nltrie','\u22B4\u20D2':'nvltrie','\u22B5':'rtrie','\u22ED':'nrtrie','\u22B5\u20D2':'nvrtrie','\u22B6':'origof','\u22B7':'imof','\u22B8':'mumap','\u22B9':'hercon','\u22BA':'intcal','\u22BB':'veebar','\u22BD':'barvee','\u22BE':'angrtvb','\u22BF':'lrtri','\u22C0':'Wedge','\u22C1':'Vee','\u22C2':'xcap','\u22C3':'xcup','\u22C4':'diam','\u22C5':'sdot','\u22C6':'Star','\u22C7':'divonx','\u22C8':'bowtie','\u22C9':'ltimes','\u22CA':'rtimes','\u22CB':'lthree','\u22CC':'rthree','\u22CD':'bsime','\u22CE':'cuvee','\u22CF':'cuwed','\u22D0':'Sub','\u22D1':'Sup','\u22D2':'Cap','\u22D3':'Cup','\u22D4':'fork','\u22D5':'epar','\u22D6':'ltdot','\u22D7':'gtdot','\u22D8':'Ll','\u22D8\u0338':'nLl','\u22D9':'Gg','\u22D9\u0338':'nGg','\u22DA\uFE00':'lesg','\u22DA':'leg','\u22DB':'gel','\u22DB\uFE00':'gesl','\u22DE':'cuepr','\u22DF':'cuesc','\u22E6':'lnsim','\u22E7':'gnsim','\u22E8':'prnsim','\u22E9':'scnsim','\u22EE':'vellip','\u22EF':'ctdot','\u22F0':'utdot','\u22F1':'dtdot','\u22F2':'disin','\u22F3':'isinsv','\u22F4':'isins','\u22F5':'isindot','\u22F5\u0338':'notindot','\u22F6':'notinvc','\u22F7':'notinvb','\u22F9':'isinE','\u22F9\u0338':'notinE','\u22FA':'nisd','\u22FB':'xnis','\u22FC':'nis','\u22FD':'notnivc','\u22FE':'notnivb','\u2305':'barwed','\u2306':'Barwed','\u230C':'drcrop','\u230D':'dlcrop','\u230E':'urcrop','\u230F':'ulcrop','\u2310':'bnot','\u2312':'profline','\u2313':'profsurf','\u2315':'telrec','\u2316':'target','\u231C':'ulcorn','\u231D':'urcorn','\u231E':'dlcorn','\u231F':'drcorn','\u2322':'frown','\u2323':'smile','\u232D':'cylcty','\u232E':'profalar','\u2336':'topbot','\u233D':'ovbar','\u233F':'solbar','\u237C':'angzarr','\u23B0':'lmoust','\u23B1':'rmoust','\u23B4':'tbrk','\u23B5':'bbrk','\u23B6':'bbrktbrk','\u23DC':'OverParenthesis','\u23DD':'UnderParenthesis','\u23DE':'OverBrace','\u23DF':'UnderBrace','\u23E2':'trpezium','\u23E7':'elinters','\u2423':'blank','\u2500':'boxh','\u2502':'boxv','\u250C':'boxdr','\u2510':'boxdl','\u2514':'boxur','\u2518':'boxul','\u251C':'boxvr','\u2524':'boxvl','\u252C':'boxhd','\u2534':'boxhu','\u253C':'boxvh','\u2550':'boxH','\u2551':'boxV','\u2552':'boxdR','\u2553':'boxDr','\u2554':'boxDR','\u2555':'boxdL','\u2556':'boxDl','\u2557':'boxDL','\u2558':'boxuR','\u2559':'boxUr','\u255A':'boxUR','\u255B':'boxuL','\u255C':'boxUl','\u255D':'boxUL','\u255E':'boxvR','\u255F':'boxVr','\u2560':'boxVR','\u2561':'boxvL','\u2562':'boxVl','\u2563':'boxVL','\u2564':'boxHd','\u2565':'boxhD','\u2566':'boxHD','\u2567':'boxHu','\u2568':'boxhU','\u2569':'boxHU','\u256A':'boxvH','\u256B':'boxVh','\u256C':'boxVH','\u2580':'uhblk','\u2584':'lhblk','\u2588':'block','\u2591':'blk14','\u2592':'blk12','\u2593':'blk34','\u25A1':'squ','\u25AA':'squf','\u25AB':'EmptyVerySmallSquare','\u25AD':'rect','\u25AE':'marker','\u25B1':'fltns','\u25B3':'xutri','\u25B4':'utrif','\u25B5':'utri','\u25B8':'rtrif','\u25B9':'rtri','\u25BD':'xdtri','\u25BE':'dtrif','\u25BF':'dtri','\u25C2':'ltrif','\u25C3':'ltri','\u25CA':'loz','\u25CB':'cir','\u25EC':'tridot','\u25EF':'xcirc','\u25F8':'ultri','\u25F9':'urtri','\u25FA':'lltri','\u25FB':'EmptySmallSquare','\u25FC':'FilledSmallSquare','\u2605':'starf','\u2606':'star','\u260E':'phone','\u2640':'female','\u2642':'male','\u2660':'spades','\u2663':'clubs','\u2665':'hearts','\u2666':'diams','\u266A':'sung','\u2713':'check','\u2717':'cross','\u2720':'malt','\u2736':'sext','\u2758':'VerticalSeparator','\u27C8':'bsolhsub','\u27C9':'suphsol','\u27F5':'xlarr','\u27F6':'xrarr','\u27F7':'xharr','\u27F8':'xlArr','\u27F9':'xrArr','\u27FA':'xhArr','\u27FC':'xmap','\u27FF':'dzigrarr','\u2902':'nvlArr','\u2903':'nvrArr','\u2904':'nvHarr','\u2905':'Map','\u290C':'lbarr','\u290D':'rbarr','\u290E':'lBarr','\u290F':'rBarr','\u2910':'RBarr','\u2911':'DDotrahd','\u2912':'UpArrowBar','\u2913':'DownArrowBar','\u2916':'Rarrtl','\u2919':'latail','\u291A':'ratail','\u291B':'lAtail','\u291C':'rAtail','\u291D':'larrfs','\u291E':'rarrfs','\u291F':'larrbfs','\u2920':'rarrbfs','\u2923':'nwarhk','\u2924':'nearhk','\u2925':'searhk','\u2926':'swarhk','\u2927':'nwnear','\u2928':'toea','\u2929':'tosa','\u292A':'swnwar','\u2933':'rarrc','\u2933\u0338':'nrarrc','\u2935':'cudarrr','\u2936':'ldca','\u2937':'rdca','\u2938':'cudarrl','\u2939':'larrpl','\u293C':'curarrm','\u293D':'cularrp','\u2945':'rarrpl','\u2948':'harrcir','\u2949':'Uarrocir','\u294A':'lurdshar','\u294B':'ldrushar','\u294E':'LeftRightVector','\u294F':'RightUpDownVector','\u2950':'DownLeftRightVector','\u2951':'LeftUpDownVector','\u2952':'LeftVectorBar','\u2953':'RightVectorBar','\u2954':'RightUpVectorBar','\u2955':'RightDownVectorBar','\u2956':'DownLeftVectorBar','\u2957':'DownRightVectorBar','\u2958':'LeftUpVectorBar','\u2959':'LeftDownVectorBar','\u295A':'LeftTeeVector','\u295B':'RightTeeVector','\u295C':'RightUpTeeVector','\u295D':'RightDownTeeVector','\u295E':'DownLeftTeeVector','\u295F':'DownRightTeeVector','\u2960':'LeftUpTeeVector','\u2961':'LeftDownTeeVector','\u2962':'lHar','\u2963':'uHar','\u2964':'rHar','\u2965':'dHar','\u2966':'luruhar','\u2967':'ldrdhar','\u2968':'ruluhar','\u2969':'rdldhar','\u296A':'lharul','\u296B':'llhard','\u296C':'rharul','\u296D':'lrhard','\u296E':'udhar','\u296F':'duhar','\u2970':'RoundImplies','\u2971':'erarr','\u2972':'simrarr','\u2973':'larrsim','\u2974':'rarrsim','\u2975':'rarrap','\u2976':'ltlarr','\u2978':'gtrarr','\u2979':'subrarr','\u297B':'suplarr','\u297C':'lfisht','\u297D':'rfisht','\u297E':'ufisht','\u297F':'dfisht','\u299A':'vzigzag','\u299C':'vangrt','\u299D':'angrtvbd','\u29A4':'ange','\u29A5':'range','\u29A6':'dwangle','\u29A7':'uwangle','\u29A8':'angmsdaa','\u29A9':'angmsdab','\u29AA':'angmsdac','\u29AB':'angmsdad','\u29AC':'angmsdae','\u29AD':'angmsdaf','\u29AE':'angmsdag','\u29AF':'angmsdah','\u29B0':'bemptyv','\u29B1':'demptyv','\u29B2':'cemptyv','\u29B3':'raemptyv','\u29B4':'laemptyv','\u29B5':'ohbar','\u29B6':'omid','\u29B7':'opar','\u29B9':'operp','\u29BB':'olcross','\u29BC':'odsold','\u29BE':'olcir','\u29BF':'ofcir','\u29C0':'olt','\u29C1':'ogt','\u29C2':'cirscir','\u29C3':'cirE','\u29C4':'solb','\u29C5':'bsolb','\u29C9':'boxbox','\u29CD':'trisb','\u29CE':'rtriltri','\u29CF':'LeftTriangleBar','\u29CF\u0338':'NotLeftTriangleBar','\u29D0':'RightTriangleBar','\u29D0\u0338':'NotRightTriangleBar','\u29DC':'iinfin','\u29DD':'infintie','\u29DE':'nvinfin','\u29E3':'eparsl','\u29E4':'smeparsl','\u29E5':'eqvparsl','\u29EB':'lozf','\u29F4':'RuleDelayed','\u29F6':'dsol','\u2A00':'xodot','\u2A01':'xoplus','\u2A02':'xotime','\u2A04':'xuplus','\u2A06':'xsqcup','\u2A0D':'fpartint','\u2A10':'cirfnint','\u2A11':'awint','\u2A12':'rppolint','\u2A13':'scpolint','\u2A14':'npolint','\u2A15':'pointint','\u2A16':'quatint','\u2A17':'intlarhk','\u2A22':'pluscir','\u2A23':'plusacir','\u2A24':'simplus','\u2A25':'plusdu','\u2A26':'plussim','\u2A27':'plustwo','\u2A29':'mcomma','\u2A2A':'minusdu','\u2A2D':'loplus','\u2A2E':'roplus','\u2A2F':'Cross','\u2A30':'timesd','\u2A31':'timesbar','\u2A33':'smashp','\u2A34':'lotimes','\u2A35':'rotimes','\u2A36':'otimesas','\u2A37':'Otimes','\u2A38':'odiv','\u2A39':'triplus','\u2A3A':'triminus','\u2A3B':'tritime','\u2A3C':'iprod','\u2A3F':'amalg','\u2A40':'capdot','\u2A42':'ncup','\u2A43':'ncap','\u2A44':'capand','\u2A45':'cupor','\u2A46':'cupcap','\u2A47':'capcup','\u2A48':'cupbrcap','\u2A49':'capbrcup','\u2A4A':'cupcup','\u2A4B':'capcap','\u2A4C':'ccups','\u2A4D':'ccaps','\u2A50':'ccupssm','\u2A53':'And','\u2A54':'Or','\u2A55':'andand','\u2A56':'oror','\u2A57':'orslope','\u2A58':'andslope','\u2A5A':'andv','\u2A5B':'orv','\u2A5C':'andd','\u2A5D':'ord','\u2A5F':'wedbar','\u2A66':'sdote','\u2A6A':'simdot','\u2A6D':'congdot','\u2A6D\u0338':'ncongdot','\u2A6E':'easter','\u2A6F':'apacir','\u2A70':'apE','\u2A70\u0338':'napE','\u2A71':'eplus','\u2A72':'pluse','\u2A73':'Esim','\u2A77':'eDDot','\u2A78':'equivDD','\u2A79':'ltcir','\u2A7A':'gtcir','\u2A7B':'ltquest','\u2A7C':'gtquest','\u2A7D':'les','\u2A7D\u0338':'nles','\u2A7E':'ges','\u2A7E\u0338':'nges','\u2A7F':'lesdot','\u2A80':'gesdot','\u2A81':'lesdoto','\u2A82':'gesdoto','\u2A83':'lesdotor','\u2A84':'gesdotol','\u2A85':'lap','\u2A86':'gap','\u2A87':'lne','\u2A88':'gne','\u2A89':'lnap','\u2A8A':'gnap','\u2A8B':'lEg','\u2A8C':'gEl','\u2A8D':'lsime','\u2A8E':'gsime','\u2A8F':'lsimg','\u2A90':'gsiml','\u2A91':'lgE','\u2A92':'glE','\u2A93':'lesges','\u2A94':'gesles','\u2A95':'els','\u2A96':'egs','\u2A97':'elsdot','\u2A98':'egsdot','\u2A99':'el','\u2A9A':'eg','\u2A9D':'siml','\u2A9E':'simg','\u2A9F':'simlE','\u2AA0':'simgE','\u2AA1':'LessLess','\u2AA1\u0338':'NotNestedLessLess','\u2AA2':'GreaterGreater','\u2AA2\u0338':'NotNestedGreaterGreater','\u2AA4':'glj','\u2AA5':'gla','\u2AA6':'ltcc','\u2AA7':'gtcc','\u2AA8':'lescc','\u2AA9':'gescc','\u2AAA':'smt','\u2AAB':'lat','\u2AAC':'smte','\u2AAC\uFE00':'smtes','\u2AAD':'late','\u2AAD\uFE00':'lates','\u2AAE':'bumpE','\u2AAF':'pre','\u2AAF\u0338':'npre','\u2AB0':'sce','\u2AB0\u0338':'nsce','\u2AB3':'prE','\u2AB4':'scE','\u2AB5':'prnE','\u2AB6':'scnE','\u2AB7':'prap','\u2AB8':'scap','\u2AB9':'prnap','\u2ABA':'scnap','\u2ABB':'Pr','\u2ABC':'Sc','\u2ABD':'subdot','\u2ABE':'supdot','\u2ABF':'subplus','\u2AC0':'supplus','\u2AC1':'submult','\u2AC2':'supmult','\u2AC3':'subedot','\u2AC4':'supedot','\u2AC5':'subE','\u2AC5\u0338':'nsubE','\u2AC6':'supE','\u2AC6\u0338':'nsupE','\u2AC7':'subsim','\u2AC8':'supsim','\u2ACB\uFE00':'vsubnE','\u2ACB':'subnE','\u2ACC\uFE00':'vsupnE','\u2ACC':'supnE','\u2ACF':'csub','\u2AD0':'csup','\u2AD1':'csube','\u2AD2':'csupe','\u2AD3':'subsup','\u2AD4':'supsub','\u2AD5':'subsub','\u2AD6':'supsup','\u2AD7':'suphsub','\u2AD8':'supdsub','\u2AD9':'forkv','\u2ADA':'topfork','\u2ADB':'mlcp','\u2AE4':'Dashv','\u2AE6':'Vdashl','\u2AE7':'Barv','\u2AE8':'vBar','\u2AE9':'vBarv','\u2AEB':'Vbar','\u2AEC':'Not','\u2AED':'bNot','\u2AEE':'rnmid','\u2AEF':'cirmid','\u2AF0':'midcir','\u2AF1':'topcir','\u2AF2':'nhpar','\u2AF3':'parsim','\u2AFD':'parsl','\u2AFD\u20E5':'nparsl','\u266D':'flat','\u266E':'natur','\u266F':'sharp','\xA4':'curren','\xA2':'cent','$':'dollar','\xA3':'pound','\xA5':'yen','\u20AC':'euro','\xB9':'sup1','\xBD':'half','\u2153':'frac13','\xBC':'frac14','\u2155':'frac15','\u2159':'frac16','\u215B':'frac18','\xB2':'sup2','\u2154':'frac23','\u2156':'frac25','\xB3':'sup3','\xBE':'frac34','\u2157':'frac35','\u215C':'frac38','\u2158':'frac45','\u215A':'frac56','\u215D':'frac58','\u215E':'frac78','\uD835\uDCB6':'ascr','\uD835\uDD52':'aopf','\uD835\uDD1E':'afr','\uD835\uDD38':'Aopf','\uD835\uDD04':'Afr','\uD835\uDC9C':'Ascr','\xAA':'ordf','\xE1':'aacute','\xC1':'Aacute','\xE0':'agrave','\xC0':'Agrave','\u0103':'abreve','\u0102':'Abreve','\xE2':'acirc','\xC2':'Acirc','\xE5':'aring','\xC5':'angst','\xE4':'auml','\xC4':'Auml','\xE3':'atilde','\xC3':'Atilde','\u0105':'aogon','\u0104':'Aogon','\u0101':'amacr','\u0100':'Amacr','\xE6':'aelig','\xC6':'AElig','\uD835\uDCB7':'bscr','\uD835\uDD53':'bopf','\uD835\uDD1F':'bfr','\uD835\uDD39':'Bopf','\u212C':'Bscr','\uD835\uDD05':'Bfr','\uD835\uDD20':'cfr','\uD835\uDCB8':'cscr','\uD835\uDD54':'copf','\u212D':'Cfr','\uD835\uDC9E':'Cscr','\u2102':'Copf','\u0107':'cacute','\u0106':'Cacute','\u0109':'ccirc','\u0108':'Ccirc','\u010D':'ccaron','\u010C':'Ccaron','\u010B':'cdot','\u010A':'Cdot','\xE7':'ccedil','\xC7':'Ccedil','\u2105':'incare','\uD835\uDD21':'dfr','\u2146':'dd','\uD835\uDD55':'dopf','\uD835\uDCB9':'dscr','\uD835\uDC9F':'Dscr','\uD835\uDD07':'Dfr','\u2145':'DD','\uD835\uDD3B':'Dopf','\u010F':'dcaron','\u010E':'Dcaron','\u0111':'dstrok','\u0110':'Dstrok','\xF0':'eth','\xD0':'ETH','\u2147':'ee','\u212F':'escr','\uD835\uDD22':'efr','\uD835\uDD56':'eopf','\u2130':'Escr','\uD835\uDD08':'Efr','\uD835\uDD3C':'Eopf','\xE9':'eacute','\xC9':'Eacute','\xE8':'egrave','\xC8':'Egrave','\xEA':'ecirc','\xCA':'Ecirc','\u011B':'ecaron','\u011A':'Ecaron','\xEB':'euml','\xCB':'Euml','\u0117':'edot','\u0116':'Edot','\u0119':'eogon','\u0118':'Eogon','\u0113':'emacr','\u0112':'Emacr','\uD835\uDD23':'ffr','\uD835\uDD57':'fopf','\uD835\uDCBB':'fscr','\uD835\uDD09':'Ffr','\uD835\uDD3D':'Fopf','\u2131':'Fscr','\uFB00':'fflig','\uFB03':'ffilig','\uFB04':'ffllig','\uFB01':'filig','fj':'fjlig','\uFB02':'fllig','\u0192':'fnof','\u210A':'gscr','\uD835\uDD58':'gopf','\uD835\uDD24':'gfr','\uD835\uDCA2':'Gscr','\uD835\uDD3E':'Gopf','\uD835\uDD0A':'Gfr','\u01F5':'gacute','\u011F':'gbreve','\u011E':'Gbreve','\u011D':'gcirc','\u011C':'Gcirc','\u0121':'gdot','\u0120':'Gdot','\u0122':'Gcedil','\uD835\uDD25':'hfr','\u210E':'planckh','\uD835\uDCBD':'hscr','\uD835\uDD59':'hopf','\u210B':'Hscr','\u210C':'Hfr','\u210D':'Hopf','\u0125':'hcirc','\u0124':'Hcirc','\u210F':'hbar','\u0127':'hstrok','\u0126':'Hstrok','\uD835\uDD5A':'iopf','\uD835\uDD26':'ifr','\uD835\uDCBE':'iscr','\u2148':'ii','\uD835\uDD40':'Iopf','\u2110':'Iscr','\u2111':'Im','\xED':'iacute','\xCD':'Iacute','\xEC':'igrave','\xCC':'Igrave','\xEE':'icirc','\xCE':'Icirc','\xEF':'iuml','\xCF':'Iuml','\u0129':'itilde','\u0128':'Itilde','\u0130':'Idot','\u012F':'iogon','\u012E':'Iogon','\u012B':'imacr','\u012A':'Imacr','\u0133':'ijlig','\u0132':'IJlig','\u0131':'imath','\uD835\uDCBF':'jscr','\uD835\uDD5B':'jopf','\uD835\uDD27':'jfr','\uD835\uDCA5':'Jscr','\uD835\uDD0D':'Jfr','\uD835\uDD41':'Jopf','\u0135':'jcirc','\u0134':'Jcirc','\u0237':'jmath','\uD835\uDD5C':'kopf','\uD835\uDCC0':'kscr','\uD835\uDD28':'kfr','\uD835\uDCA6':'Kscr','\uD835\uDD42':'Kopf','\uD835\uDD0E':'Kfr','\u0137':'kcedil','\u0136':'Kcedil','\uD835\uDD29':'lfr','\uD835\uDCC1':'lscr','\u2113':'ell','\uD835\uDD5D':'lopf','\u2112':'Lscr','\uD835\uDD0F':'Lfr','\uD835\uDD43':'Lopf','\u013A':'lacute','\u0139':'Lacute','\u013E':'lcaron','\u013D':'Lcaron','\u013C':'lcedil','\u013B':'Lcedil','\u0142':'lstrok','\u0141':'Lstrok','\u0140':'lmidot','\u013F':'Lmidot','\uD835\uDD2A':'mfr','\uD835\uDD5E':'mopf','\uD835\uDCC2':'mscr','\uD835\uDD10':'Mfr','\uD835\uDD44':'Mopf','\u2133':'Mscr','\uD835\uDD2B':'nfr','\uD835\uDD5F':'nopf','\uD835\uDCC3':'nscr','\u2115':'Nopf','\uD835\uDCA9':'Nscr','\uD835\uDD11':'Nfr','\u0144':'nacute','\u0143':'Nacute','\u0148':'ncaron','\u0147':'Ncaron','\xF1':'ntilde','\xD1':'Ntilde','\u0146':'ncedil','\u0145':'Ncedil','\u2116':'numero','\u014B':'eng','\u014A':'ENG','\uD835\uDD60':'oopf','\uD835\uDD2C':'ofr','\u2134':'oscr','\uD835\uDCAA':'Oscr','\uD835\uDD12':'Ofr','\uD835\uDD46':'Oopf','\xBA':'ordm','\xF3':'oacute','\xD3':'Oacute','\xF2':'ograve','\xD2':'Ograve','\xF4':'ocirc','\xD4':'Ocirc','\xF6':'ouml','\xD6':'Ouml','\u0151':'odblac','\u0150':'Odblac','\xF5':'otilde','\xD5':'Otilde','\xF8':'oslash','\xD8':'Oslash','\u014D':'omacr','\u014C':'Omacr','\u0153':'oelig','\u0152':'OElig','\uD835\uDD2D':'pfr','\uD835\uDCC5':'pscr','\uD835\uDD61':'popf','\u2119':'Popf','\uD835\uDD13':'Pfr','\uD835\uDCAB':'Pscr','\uD835\uDD62':'qopf','\uD835\uDD2E':'qfr','\uD835\uDCC6':'qscr','\uD835\uDCAC':'Qscr','\uD835\uDD14':'Qfr','\u211A':'Qopf','\u0138':'kgreen','\uD835\uDD2F':'rfr','\uD835\uDD63':'ropf','\uD835\uDCC7':'rscr','\u211B':'Rscr','\u211C':'Re','\u211D':'Ropf','\u0155':'racute','\u0154':'Racute','\u0159':'rcaron','\u0158':'Rcaron','\u0157':'rcedil','\u0156':'Rcedil','\uD835\uDD64':'sopf','\uD835\uDCC8':'sscr','\uD835\uDD30':'sfr','\uD835\uDD4A':'Sopf','\uD835\uDD16':'Sfr','\uD835\uDCAE':'Sscr','\u24C8':'oS','\u015B':'sacute','\u015A':'Sacute','\u015D':'scirc','\u015C':'Scirc','\u0161':'scaron','\u0160':'Scaron','\u015F':'scedil','\u015E':'Scedil','\xDF':'szlig','\uD835\uDD31':'tfr','\uD835\uDCC9':'tscr','\uD835\uDD65':'topf','\uD835\uDCAF':'Tscr','\uD835\uDD17':'Tfr','\uD835\uDD4B':'Topf','\u0165':'tcaron','\u0164':'Tcaron','\u0163':'tcedil','\u0162':'Tcedil','\u2122':'trade','\u0167':'tstrok','\u0166':'Tstrok','\uD835\uDCCA':'uscr','\uD835\uDD66':'uopf','\uD835\uDD32':'ufr','\uD835\uDD4C':'Uopf','\uD835\uDD18':'Ufr','\uD835\uDCB0':'Uscr','\xFA':'uacute','\xDA':'Uacute','\xF9':'ugrave','\xD9':'Ugrave','\u016D':'ubreve','\u016C':'Ubreve','\xFB':'ucirc','\xDB':'Ucirc','\u016F':'uring','\u016E':'Uring','\xFC':'uuml','\xDC':'Uuml','\u0171':'udblac','\u0170':'Udblac','\u0169':'utilde','\u0168':'Utilde','\u0173':'uogon','\u0172':'Uogon','\u016B':'umacr','\u016A':'Umacr','\uD835\uDD33':'vfr','\uD835\uDD67':'vopf','\uD835\uDCCB':'vscr','\uD835\uDD19':'Vfr','\uD835\uDD4D':'Vopf','\uD835\uDCB1':'Vscr','\uD835\uDD68':'wopf','\uD835\uDCCC':'wscr','\uD835\uDD34':'wfr','\uD835\uDCB2':'Wscr','\uD835\uDD4E':'Wopf','\uD835\uDD1A':'Wfr','\u0175':'wcirc','\u0174':'Wcirc','\uD835\uDD35':'xfr','\uD835\uDCCD':'xscr','\uD835\uDD69':'xopf','\uD835\uDD4F':'Xopf','\uD835\uDD1B':'Xfr','\uD835\uDCB3':'Xscr','\uD835\uDD36':'yfr','\uD835\uDCCE':'yscr','\uD835\uDD6A':'yopf','\uD835\uDCB4':'Yscr','\uD835\uDD1C':'Yfr','\uD835\uDD50':'Yopf','\xFD':'yacute','\xDD':'Yacute','\u0177':'ycirc','\u0176':'Ycirc','\xFF':'yuml','\u0178':'Yuml','\uD835\uDCCF':'zscr','\uD835\uDD37':'zfr','\uD835\uDD6B':'zopf','\u2128':'Zfr','\u2124':'Zopf','\uD835\uDCB5':'Zscr','\u017A':'zacute','\u0179':'Zacute','\u017E':'zcaron','\u017D':'Zcaron','\u017C':'zdot','\u017B':'Zdot','\u01B5':'imped','\xFE':'thorn','\xDE':'THORN','\u0149':'napos','\u03B1':'alpha','\u0391':'Alpha','\u03B2':'beta','\u0392':'Beta','\u03B3':'gamma','\u0393':'Gamma','\u03B4':'delta','\u0394':'Delta','\u03B5':'epsi','\u03F5':'epsiv','\u0395':'Epsilon','\u03DD':'gammad','\u03DC':'Gammad','\u03B6':'zeta','\u0396':'Zeta','\u03B7':'eta','\u0397':'Eta','\u03B8':'theta','\u03D1':'thetav','\u0398':'Theta','\u03B9':'iota','\u0399':'Iota','\u03BA':'kappa','\u03F0':'kappav','\u039A':'Kappa','\u03BB':'lambda','\u039B':'Lambda','\u03BC':'mu','\xB5':'micro','\u039C':'Mu','\u03BD':'nu','\u039D':'Nu','\u03BE':'xi','\u039E':'Xi','\u03BF':'omicron','\u039F':'Omicron','\u03C0':'pi','\u03D6':'piv','\u03A0':'Pi','\u03C1':'rho','\u03F1':'rhov','\u03A1':'Rho','\u03C3':'sigma','\u03A3':'Sigma','\u03C2':'sigmaf','\u03C4':'tau','\u03A4':'Tau','\u03C5':'upsi','\u03A5':'Upsilon','\u03D2':'Upsi','\u03C6':'phi','\u03D5':'phiv','\u03A6':'Phi','\u03C7':'chi','\u03A7':'Chi','\u03C8':'psi','\u03A8':'Psi','\u03C9':'omega','\u03A9':'ohm','\u0430':'acy','\u0410':'Acy','\u0431':'bcy','\u0411':'Bcy','\u0432':'vcy','\u0412':'Vcy','\u0433':'gcy','\u0413':'Gcy','\u0453':'gjcy','\u0403':'GJcy','\u0434':'dcy','\u0414':'Dcy','\u0452':'djcy','\u0402':'DJcy','\u0435':'iecy','\u0415':'IEcy','\u0451':'iocy','\u0401':'IOcy','\u0454':'jukcy','\u0404':'Jukcy','\u0436':'zhcy','\u0416':'ZHcy','\u0437':'zcy','\u0417':'Zcy','\u0455':'dscy','\u0405':'DScy','\u0438':'icy','\u0418':'Icy','\u0456':'iukcy','\u0406':'Iukcy','\u0457':'yicy','\u0407':'YIcy','\u0439':'jcy','\u0419':'Jcy','\u0458':'jsercy','\u0408':'Jsercy','\u043A':'kcy','\u041A':'Kcy','\u045C':'kjcy','\u040C':'KJcy','\u043B':'lcy','\u041B':'Lcy','\u0459':'ljcy','\u0409':'LJcy','\u043C':'mcy','\u041C':'Mcy','\u043D':'ncy','\u041D':'Ncy','\u045A':'njcy','\u040A':'NJcy','\u043E':'ocy','\u041E':'Ocy','\u043F':'pcy','\u041F':'Pcy','\u0440':'rcy','\u0420':'Rcy','\u0441':'scy','\u0421':'Scy','\u0442':'tcy','\u0422':'Tcy','\u045B':'tshcy','\u040B':'TSHcy','\u0443':'ucy','\u0423':'Ucy','\u045E':'ubrcy','\u040E':'Ubrcy','\u0444':'fcy','\u0424':'Fcy','\u0445':'khcy','\u0425':'KHcy','\u0446':'tscy','\u0426':'TScy','\u0447':'chcy','\u0427':'CHcy','\u045F':'dzcy','\u040F':'DZcy','\u0448':'shcy','\u0428':'SHcy','\u0449':'shchcy','\u0429':'SHCHcy','\u044A':'hardcy','\u042A':'HARDcy','\u044B':'ycy','\u042B':'Ycy','\u044C':'softcy','\u042C':'SOFTcy','\u044D':'ecy','\u042D':'Ecy','\u044E':'yucy','\u042E':'YUcy','\u044F':'yacy','\u042F':'YAcy','\u2135':'aleph','\u2136':'beth','\u2137':'gimel','\u2138':'daleth'}; + + var regexEscape = /["&'<>`]/g; + var escapeMap = { + '"': '"', + '&': '&', + '\'': ''', + '<': '<', + // See https://mathiasbynens.be/notes/ambiguous-ampersands: in HTML, the + // following is not strictly necessary unless it’s part of a tag or an + // unquoted attribute value. We’re only escaping it to support those + // situations, and for XML support. + '>': '>', + // In Internet Explorer ≤ 8, the backtick character can be used + // to break out of (un)quoted attribute values or HTML comments. + // See http://html5sec.org/#102, http://html5sec.org/#108, and + // http://html5sec.org/#133. + '`': '`' + }; + + var regexInvalidEntity = /&#(?:[xX][^a-fA-F0-9]|[^0-9xX])/; + var regexInvalidRawCodePoint = /[\0-\x08\x0B\x0E-\x1F\x7F-\x9F\uFDD0-\uFDEF\uFFFE\uFFFF]|[\uD83F\uD87F\uD8BF\uD8FF\uD93F\uD97F\uD9BF\uD9FF\uDA3F\uDA7F\uDABF\uDAFF\uDB3F\uDB7F\uDBBF\uDBFF][\uDFFE\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/; + var regexDecode = /&#([0-9]+)(;?)|&#[xX]([a-fA-F0-9]+)(;?)|&([0-9a-zA-Z]+);|&(Aacute|Agrave|Atilde|Ccedil|Eacute|Egrave|Iacute|Igrave|Ntilde|Oacute|Ograve|Oslash|Otilde|Uacute|Ugrave|Yacute|aacute|agrave|atilde|brvbar|ccedil|curren|divide|eacute|egrave|frac12|frac14|frac34|iacute|igrave|iquest|middot|ntilde|oacute|ograve|oslash|otilde|plusmn|uacute|ugrave|yacute|AElig|Acirc|Aring|Ecirc|Icirc|Ocirc|THORN|Ucirc|acirc|acute|aelig|aring|cedil|ecirc|icirc|iexcl|laquo|micro|ocirc|pound|raquo|szlig|thorn|times|ucirc|Auml|COPY|Euml|Iuml|Ouml|QUOT|Uuml|auml|cent|copy|euml|iuml|macr|nbsp|ordf|ordm|ouml|para|quot|sect|sup1|sup2|sup3|uuml|yuml|AMP|ETH|REG|amp|deg|eth|not|reg|shy|uml|yen|GT|LT|gt|lt)([=a-zA-Z0-9])?/g; + var decodeMap = {'aacute':'\xE1','Aacute':'\xC1','abreve':'\u0103','Abreve':'\u0102','ac':'\u223E','acd':'\u223F','acE':'\u223E\u0333','acirc':'\xE2','Acirc':'\xC2','acute':'\xB4','acy':'\u0430','Acy':'\u0410','aelig':'\xE6','AElig':'\xC6','af':'\u2061','afr':'\uD835\uDD1E','Afr':'\uD835\uDD04','agrave':'\xE0','Agrave':'\xC0','alefsym':'\u2135','aleph':'\u2135','alpha':'\u03B1','Alpha':'\u0391','amacr':'\u0101','Amacr':'\u0100','amalg':'\u2A3F','amp':'&','AMP':'&','and':'\u2227','And':'\u2A53','andand':'\u2A55','andd':'\u2A5C','andslope':'\u2A58','andv':'\u2A5A','ang':'\u2220','ange':'\u29A4','angle':'\u2220','angmsd':'\u2221','angmsdaa':'\u29A8','angmsdab':'\u29A9','angmsdac':'\u29AA','angmsdad':'\u29AB','angmsdae':'\u29AC','angmsdaf':'\u29AD','angmsdag':'\u29AE','angmsdah':'\u29AF','angrt':'\u221F','angrtvb':'\u22BE','angrtvbd':'\u299D','angsph':'\u2222','angst':'\xC5','angzarr':'\u237C','aogon':'\u0105','Aogon':'\u0104','aopf':'\uD835\uDD52','Aopf':'\uD835\uDD38','ap':'\u2248','apacir':'\u2A6F','ape':'\u224A','apE':'\u2A70','apid':'\u224B','apos':'\'','ApplyFunction':'\u2061','approx':'\u2248','approxeq':'\u224A','aring':'\xE5','Aring':'\xC5','ascr':'\uD835\uDCB6','Ascr':'\uD835\uDC9C','Assign':'\u2254','ast':'*','asymp':'\u2248','asympeq':'\u224D','atilde':'\xE3','Atilde':'\xC3','auml':'\xE4','Auml':'\xC4','awconint':'\u2233','awint':'\u2A11','backcong':'\u224C','backepsilon':'\u03F6','backprime':'\u2035','backsim':'\u223D','backsimeq':'\u22CD','Backslash':'\u2216','Barv':'\u2AE7','barvee':'\u22BD','barwed':'\u2305','Barwed':'\u2306','barwedge':'\u2305','bbrk':'\u23B5','bbrktbrk':'\u23B6','bcong':'\u224C','bcy':'\u0431','Bcy':'\u0411','bdquo':'\u201E','becaus':'\u2235','because':'\u2235','Because':'\u2235','bemptyv':'\u29B0','bepsi':'\u03F6','bernou':'\u212C','Bernoullis':'\u212C','beta':'\u03B2','Beta':'\u0392','beth':'\u2136','between':'\u226C','bfr':'\uD835\uDD1F','Bfr':'\uD835\uDD05','bigcap':'\u22C2','bigcirc':'\u25EF','bigcup':'\u22C3','bigodot':'\u2A00','bigoplus':'\u2A01','bigotimes':'\u2A02','bigsqcup':'\u2A06','bigstar':'\u2605','bigtriangledown':'\u25BD','bigtriangleup':'\u25B3','biguplus':'\u2A04','bigvee':'\u22C1','bigwedge':'\u22C0','bkarow':'\u290D','blacklozenge':'\u29EB','blacksquare':'\u25AA','blacktriangle':'\u25B4','blacktriangledown':'\u25BE','blacktriangleleft':'\u25C2','blacktriangleright':'\u25B8','blank':'\u2423','blk12':'\u2592','blk14':'\u2591','blk34':'\u2593','block':'\u2588','bne':'=\u20E5','bnequiv':'\u2261\u20E5','bnot':'\u2310','bNot':'\u2AED','bopf':'\uD835\uDD53','Bopf':'\uD835\uDD39','bot':'\u22A5','bottom':'\u22A5','bowtie':'\u22C8','boxbox':'\u29C9','boxdl':'\u2510','boxdL':'\u2555','boxDl':'\u2556','boxDL':'\u2557','boxdr':'\u250C','boxdR':'\u2552','boxDr':'\u2553','boxDR':'\u2554','boxh':'\u2500','boxH':'\u2550','boxhd':'\u252C','boxhD':'\u2565','boxHd':'\u2564','boxHD':'\u2566','boxhu':'\u2534','boxhU':'\u2568','boxHu':'\u2567','boxHU':'\u2569','boxminus':'\u229F','boxplus':'\u229E','boxtimes':'\u22A0','boxul':'\u2518','boxuL':'\u255B','boxUl':'\u255C','boxUL':'\u255D','boxur':'\u2514','boxuR':'\u2558','boxUr':'\u2559','boxUR':'\u255A','boxv':'\u2502','boxV':'\u2551','boxvh':'\u253C','boxvH':'\u256A','boxVh':'\u256B','boxVH':'\u256C','boxvl':'\u2524','boxvL':'\u2561','boxVl':'\u2562','boxVL':'\u2563','boxvr':'\u251C','boxvR':'\u255E','boxVr':'\u255F','boxVR':'\u2560','bprime':'\u2035','breve':'\u02D8','Breve':'\u02D8','brvbar':'\xA6','bscr':'\uD835\uDCB7','Bscr':'\u212C','bsemi':'\u204F','bsim':'\u223D','bsime':'\u22CD','bsol':'\\','bsolb':'\u29C5','bsolhsub':'\u27C8','bull':'\u2022','bullet':'\u2022','bump':'\u224E','bumpe':'\u224F','bumpE':'\u2AAE','bumpeq':'\u224F','Bumpeq':'\u224E','cacute':'\u0107','Cacute':'\u0106','cap':'\u2229','Cap':'\u22D2','capand':'\u2A44','capbrcup':'\u2A49','capcap':'\u2A4B','capcup':'\u2A47','capdot':'\u2A40','CapitalDifferentialD':'\u2145','caps':'\u2229\uFE00','caret':'\u2041','caron':'\u02C7','Cayleys':'\u212D','ccaps':'\u2A4D','ccaron':'\u010D','Ccaron':'\u010C','ccedil':'\xE7','Ccedil':'\xC7','ccirc':'\u0109','Ccirc':'\u0108','Cconint':'\u2230','ccups':'\u2A4C','ccupssm':'\u2A50','cdot':'\u010B','Cdot':'\u010A','cedil':'\xB8','Cedilla':'\xB8','cemptyv':'\u29B2','cent':'\xA2','centerdot':'\xB7','CenterDot':'\xB7','cfr':'\uD835\uDD20','Cfr':'\u212D','chcy':'\u0447','CHcy':'\u0427','check':'\u2713','checkmark':'\u2713','chi':'\u03C7','Chi':'\u03A7','cir':'\u25CB','circ':'\u02C6','circeq':'\u2257','circlearrowleft':'\u21BA','circlearrowright':'\u21BB','circledast':'\u229B','circledcirc':'\u229A','circleddash':'\u229D','CircleDot':'\u2299','circledR':'\xAE','circledS':'\u24C8','CircleMinus':'\u2296','CirclePlus':'\u2295','CircleTimes':'\u2297','cire':'\u2257','cirE':'\u29C3','cirfnint':'\u2A10','cirmid':'\u2AEF','cirscir':'\u29C2','ClockwiseContourIntegral':'\u2232','CloseCurlyDoubleQuote':'\u201D','CloseCurlyQuote':'\u2019','clubs':'\u2663','clubsuit':'\u2663','colon':':','Colon':'\u2237','colone':'\u2254','Colone':'\u2A74','coloneq':'\u2254','comma':',','commat':'@','comp':'\u2201','compfn':'\u2218','complement':'\u2201','complexes':'\u2102','cong':'\u2245','congdot':'\u2A6D','Congruent':'\u2261','conint':'\u222E','Conint':'\u222F','ContourIntegral':'\u222E','copf':'\uD835\uDD54','Copf':'\u2102','coprod':'\u2210','Coproduct':'\u2210','copy':'\xA9','COPY':'\xA9','copysr':'\u2117','CounterClockwiseContourIntegral':'\u2233','crarr':'\u21B5','cross':'\u2717','Cross':'\u2A2F','cscr':'\uD835\uDCB8','Cscr':'\uD835\uDC9E','csub':'\u2ACF','csube':'\u2AD1','csup':'\u2AD0','csupe':'\u2AD2','ctdot':'\u22EF','cudarrl':'\u2938','cudarrr':'\u2935','cuepr':'\u22DE','cuesc':'\u22DF','cularr':'\u21B6','cularrp':'\u293D','cup':'\u222A','Cup':'\u22D3','cupbrcap':'\u2A48','cupcap':'\u2A46','CupCap':'\u224D','cupcup':'\u2A4A','cupdot':'\u228D','cupor':'\u2A45','cups':'\u222A\uFE00','curarr':'\u21B7','curarrm':'\u293C','curlyeqprec':'\u22DE','curlyeqsucc':'\u22DF','curlyvee':'\u22CE','curlywedge':'\u22CF','curren':'\xA4','curvearrowleft':'\u21B6','curvearrowright':'\u21B7','cuvee':'\u22CE','cuwed':'\u22CF','cwconint':'\u2232','cwint':'\u2231','cylcty':'\u232D','dagger':'\u2020','Dagger':'\u2021','daleth':'\u2138','darr':'\u2193','dArr':'\u21D3','Darr':'\u21A1','dash':'\u2010','dashv':'\u22A3','Dashv':'\u2AE4','dbkarow':'\u290F','dblac':'\u02DD','dcaron':'\u010F','Dcaron':'\u010E','dcy':'\u0434','Dcy':'\u0414','dd':'\u2146','DD':'\u2145','ddagger':'\u2021','ddarr':'\u21CA','DDotrahd':'\u2911','ddotseq':'\u2A77','deg':'\xB0','Del':'\u2207','delta':'\u03B4','Delta':'\u0394','demptyv':'\u29B1','dfisht':'\u297F','dfr':'\uD835\uDD21','Dfr':'\uD835\uDD07','dHar':'\u2965','dharl':'\u21C3','dharr':'\u21C2','DiacriticalAcute':'\xB4','DiacriticalDot':'\u02D9','DiacriticalDoubleAcute':'\u02DD','DiacriticalGrave':'`','DiacriticalTilde':'\u02DC','diam':'\u22C4','diamond':'\u22C4','Diamond':'\u22C4','diamondsuit':'\u2666','diams':'\u2666','die':'\xA8','DifferentialD':'\u2146','digamma':'\u03DD','disin':'\u22F2','div':'\xF7','divide':'\xF7','divideontimes':'\u22C7','divonx':'\u22C7','djcy':'\u0452','DJcy':'\u0402','dlcorn':'\u231E','dlcrop':'\u230D','dollar':'$','dopf':'\uD835\uDD55','Dopf':'\uD835\uDD3B','dot':'\u02D9','Dot':'\xA8','DotDot':'\u20DC','doteq':'\u2250','doteqdot':'\u2251','DotEqual':'\u2250','dotminus':'\u2238','dotplus':'\u2214','dotsquare':'\u22A1','doublebarwedge':'\u2306','DoubleContourIntegral':'\u222F','DoubleDot':'\xA8','DoubleDownArrow':'\u21D3','DoubleLeftArrow':'\u21D0','DoubleLeftRightArrow':'\u21D4','DoubleLeftTee':'\u2AE4','DoubleLongLeftArrow':'\u27F8','DoubleLongLeftRightArrow':'\u27FA','DoubleLongRightArrow':'\u27F9','DoubleRightArrow':'\u21D2','DoubleRightTee':'\u22A8','DoubleUpArrow':'\u21D1','DoubleUpDownArrow':'\u21D5','DoubleVerticalBar':'\u2225','downarrow':'\u2193','Downarrow':'\u21D3','DownArrow':'\u2193','DownArrowBar':'\u2913','DownArrowUpArrow':'\u21F5','DownBreve':'\u0311','downdownarrows':'\u21CA','downharpoonleft':'\u21C3','downharpoonright':'\u21C2','DownLeftRightVector':'\u2950','DownLeftTeeVector':'\u295E','DownLeftVector':'\u21BD','DownLeftVectorBar':'\u2956','DownRightTeeVector':'\u295F','DownRightVector':'\u21C1','DownRightVectorBar':'\u2957','DownTee':'\u22A4','DownTeeArrow':'\u21A7','drbkarow':'\u2910','drcorn':'\u231F','drcrop':'\u230C','dscr':'\uD835\uDCB9','Dscr':'\uD835\uDC9F','dscy':'\u0455','DScy':'\u0405','dsol':'\u29F6','dstrok':'\u0111','Dstrok':'\u0110','dtdot':'\u22F1','dtri':'\u25BF','dtrif':'\u25BE','duarr':'\u21F5','duhar':'\u296F','dwangle':'\u29A6','dzcy':'\u045F','DZcy':'\u040F','dzigrarr':'\u27FF','eacute':'\xE9','Eacute':'\xC9','easter':'\u2A6E','ecaron':'\u011B','Ecaron':'\u011A','ecir':'\u2256','ecirc':'\xEA','Ecirc':'\xCA','ecolon':'\u2255','ecy':'\u044D','Ecy':'\u042D','eDDot':'\u2A77','edot':'\u0117','eDot':'\u2251','Edot':'\u0116','ee':'\u2147','efDot':'\u2252','efr':'\uD835\uDD22','Efr':'\uD835\uDD08','eg':'\u2A9A','egrave':'\xE8','Egrave':'\xC8','egs':'\u2A96','egsdot':'\u2A98','el':'\u2A99','Element':'\u2208','elinters':'\u23E7','ell':'\u2113','els':'\u2A95','elsdot':'\u2A97','emacr':'\u0113','Emacr':'\u0112','empty':'\u2205','emptyset':'\u2205','EmptySmallSquare':'\u25FB','emptyv':'\u2205','EmptyVerySmallSquare':'\u25AB','emsp':'\u2003','emsp13':'\u2004','emsp14':'\u2005','eng':'\u014B','ENG':'\u014A','ensp':'\u2002','eogon':'\u0119','Eogon':'\u0118','eopf':'\uD835\uDD56','Eopf':'\uD835\uDD3C','epar':'\u22D5','eparsl':'\u29E3','eplus':'\u2A71','epsi':'\u03B5','epsilon':'\u03B5','Epsilon':'\u0395','epsiv':'\u03F5','eqcirc':'\u2256','eqcolon':'\u2255','eqsim':'\u2242','eqslantgtr':'\u2A96','eqslantless':'\u2A95','Equal':'\u2A75','equals':'=','EqualTilde':'\u2242','equest':'\u225F','Equilibrium':'\u21CC','equiv':'\u2261','equivDD':'\u2A78','eqvparsl':'\u29E5','erarr':'\u2971','erDot':'\u2253','escr':'\u212F','Escr':'\u2130','esdot':'\u2250','esim':'\u2242','Esim':'\u2A73','eta':'\u03B7','Eta':'\u0397','eth':'\xF0','ETH':'\xD0','euml':'\xEB','Euml':'\xCB','euro':'\u20AC','excl':'!','exist':'\u2203','Exists':'\u2203','expectation':'\u2130','exponentiale':'\u2147','ExponentialE':'\u2147','fallingdotseq':'\u2252','fcy':'\u0444','Fcy':'\u0424','female':'\u2640','ffilig':'\uFB03','fflig':'\uFB00','ffllig':'\uFB04','ffr':'\uD835\uDD23','Ffr':'\uD835\uDD09','filig':'\uFB01','FilledSmallSquare':'\u25FC','FilledVerySmallSquare':'\u25AA','fjlig':'fj','flat':'\u266D','fllig':'\uFB02','fltns':'\u25B1','fnof':'\u0192','fopf':'\uD835\uDD57','Fopf':'\uD835\uDD3D','forall':'\u2200','ForAll':'\u2200','fork':'\u22D4','forkv':'\u2AD9','Fouriertrf':'\u2131','fpartint':'\u2A0D','frac12':'\xBD','frac13':'\u2153','frac14':'\xBC','frac15':'\u2155','frac16':'\u2159','frac18':'\u215B','frac23':'\u2154','frac25':'\u2156','frac34':'\xBE','frac35':'\u2157','frac38':'\u215C','frac45':'\u2158','frac56':'\u215A','frac58':'\u215D','frac78':'\u215E','frasl':'\u2044','frown':'\u2322','fscr':'\uD835\uDCBB','Fscr':'\u2131','gacute':'\u01F5','gamma':'\u03B3','Gamma':'\u0393','gammad':'\u03DD','Gammad':'\u03DC','gap':'\u2A86','gbreve':'\u011F','Gbreve':'\u011E','Gcedil':'\u0122','gcirc':'\u011D','Gcirc':'\u011C','gcy':'\u0433','Gcy':'\u0413','gdot':'\u0121','Gdot':'\u0120','ge':'\u2265','gE':'\u2267','gel':'\u22DB','gEl':'\u2A8C','geq':'\u2265','geqq':'\u2267','geqslant':'\u2A7E','ges':'\u2A7E','gescc':'\u2AA9','gesdot':'\u2A80','gesdoto':'\u2A82','gesdotol':'\u2A84','gesl':'\u22DB\uFE00','gesles':'\u2A94','gfr':'\uD835\uDD24','Gfr':'\uD835\uDD0A','gg':'\u226B','Gg':'\u22D9','ggg':'\u22D9','gimel':'\u2137','gjcy':'\u0453','GJcy':'\u0403','gl':'\u2277','gla':'\u2AA5','glE':'\u2A92','glj':'\u2AA4','gnap':'\u2A8A','gnapprox':'\u2A8A','gne':'\u2A88','gnE':'\u2269','gneq':'\u2A88','gneqq':'\u2269','gnsim':'\u22E7','gopf':'\uD835\uDD58','Gopf':'\uD835\uDD3E','grave':'`','GreaterEqual':'\u2265','GreaterEqualLess':'\u22DB','GreaterFullEqual':'\u2267','GreaterGreater':'\u2AA2','GreaterLess':'\u2277','GreaterSlantEqual':'\u2A7E','GreaterTilde':'\u2273','gscr':'\u210A','Gscr':'\uD835\uDCA2','gsim':'\u2273','gsime':'\u2A8E','gsiml':'\u2A90','gt':'>','Gt':'\u226B','GT':'>','gtcc':'\u2AA7','gtcir':'\u2A7A','gtdot':'\u22D7','gtlPar':'\u2995','gtquest':'\u2A7C','gtrapprox':'\u2A86','gtrarr':'\u2978','gtrdot':'\u22D7','gtreqless':'\u22DB','gtreqqless':'\u2A8C','gtrless':'\u2277','gtrsim':'\u2273','gvertneqq':'\u2269\uFE00','gvnE':'\u2269\uFE00','Hacek':'\u02C7','hairsp':'\u200A','half':'\xBD','hamilt':'\u210B','hardcy':'\u044A','HARDcy':'\u042A','harr':'\u2194','hArr':'\u21D4','harrcir':'\u2948','harrw':'\u21AD','Hat':'^','hbar':'\u210F','hcirc':'\u0125','Hcirc':'\u0124','hearts':'\u2665','heartsuit':'\u2665','hellip':'\u2026','hercon':'\u22B9','hfr':'\uD835\uDD25','Hfr':'\u210C','HilbertSpace':'\u210B','hksearow':'\u2925','hkswarow':'\u2926','hoarr':'\u21FF','homtht':'\u223B','hookleftarrow':'\u21A9','hookrightarrow':'\u21AA','hopf':'\uD835\uDD59','Hopf':'\u210D','horbar':'\u2015','HorizontalLine':'\u2500','hscr':'\uD835\uDCBD','Hscr':'\u210B','hslash':'\u210F','hstrok':'\u0127','Hstrok':'\u0126','HumpDownHump':'\u224E','HumpEqual':'\u224F','hybull':'\u2043','hyphen':'\u2010','iacute':'\xED','Iacute':'\xCD','ic':'\u2063','icirc':'\xEE','Icirc':'\xCE','icy':'\u0438','Icy':'\u0418','Idot':'\u0130','iecy':'\u0435','IEcy':'\u0415','iexcl':'\xA1','iff':'\u21D4','ifr':'\uD835\uDD26','Ifr':'\u2111','igrave':'\xEC','Igrave':'\xCC','ii':'\u2148','iiiint':'\u2A0C','iiint':'\u222D','iinfin':'\u29DC','iiota':'\u2129','ijlig':'\u0133','IJlig':'\u0132','Im':'\u2111','imacr':'\u012B','Imacr':'\u012A','image':'\u2111','ImaginaryI':'\u2148','imagline':'\u2110','imagpart':'\u2111','imath':'\u0131','imof':'\u22B7','imped':'\u01B5','Implies':'\u21D2','in':'\u2208','incare':'\u2105','infin':'\u221E','infintie':'\u29DD','inodot':'\u0131','int':'\u222B','Int':'\u222C','intcal':'\u22BA','integers':'\u2124','Integral':'\u222B','intercal':'\u22BA','Intersection':'\u22C2','intlarhk':'\u2A17','intprod':'\u2A3C','InvisibleComma':'\u2063','InvisibleTimes':'\u2062','iocy':'\u0451','IOcy':'\u0401','iogon':'\u012F','Iogon':'\u012E','iopf':'\uD835\uDD5A','Iopf':'\uD835\uDD40','iota':'\u03B9','Iota':'\u0399','iprod':'\u2A3C','iquest':'\xBF','iscr':'\uD835\uDCBE','Iscr':'\u2110','isin':'\u2208','isindot':'\u22F5','isinE':'\u22F9','isins':'\u22F4','isinsv':'\u22F3','isinv':'\u2208','it':'\u2062','itilde':'\u0129','Itilde':'\u0128','iukcy':'\u0456','Iukcy':'\u0406','iuml':'\xEF','Iuml':'\xCF','jcirc':'\u0135','Jcirc':'\u0134','jcy':'\u0439','Jcy':'\u0419','jfr':'\uD835\uDD27','Jfr':'\uD835\uDD0D','jmath':'\u0237','jopf':'\uD835\uDD5B','Jopf':'\uD835\uDD41','jscr':'\uD835\uDCBF','Jscr':'\uD835\uDCA5','jsercy':'\u0458','Jsercy':'\u0408','jukcy':'\u0454','Jukcy':'\u0404','kappa':'\u03BA','Kappa':'\u039A','kappav':'\u03F0','kcedil':'\u0137','Kcedil':'\u0136','kcy':'\u043A','Kcy':'\u041A','kfr':'\uD835\uDD28','Kfr':'\uD835\uDD0E','kgreen':'\u0138','khcy':'\u0445','KHcy':'\u0425','kjcy':'\u045C','KJcy':'\u040C','kopf':'\uD835\uDD5C','Kopf':'\uD835\uDD42','kscr':'\uD835\uDCC0','Kscr':'\uD835\uDCA6','lAarr':'\u21DA','lacute':'\u013A','Lacute':'\u0139','laemptyv':'\u29B4','lagran':'\u2112','lambda':'\u03BB','Lambda':'\u039B','lang':'\u27E8','Lang':'\u27EA','langd':'\u2991','langle':'\u27E8','lap':'\u2A85','Laplacetrf':'\u2112','laquo':'\xAB','larr':'\u2190','lArr':'\u21D0','Larr':'\u219E','larrb':'\u21E4','larrbfs':'\u291F','larrfs':'\u291D','larrhk':'\u21A9','larrlp':'\u21AB','larrpl':'\u2939','larrsim':'\u2973','larrtl':'\u21A2','lat':'\u2AAB','latail':'\u2919','lAtail':'\u291B','late':'\u2AAD','lates':'\u2AAD\uFE00','lbarr':'\u290C','lBarr':'\u290E','lbbrk':'\u2772','lbrace':'{','lbrack':'[','lbrke':'\u298B','lbrksld':'\u298F','lbrkslu':'\u298D','lcaron':'\u013E','Lcaron':'\u013D','lcedil':'\u013C','Lcedil':'\u013B','lceil':'\u2308','lcub':'{','lcy':'\u043B','Lcy':'\u041B','ldca':'\u2936','ldquo':'\u201C','ldquor':'\u201E','ldrdhar':'\u2967','ldrushar':'\u294B','ldsh':'\u21B2','le':'\u2264','lE':'\u2266','LeftAngleBracket':'\u27E8','leftarrow':'\u2190','Leftarrow':'\u21D0','LeftArrow':'\u2190','LeftArrowBar':'\u21E4','LeftArrowRightArrow':'\u21C6','leftarrowtail':'\u21A2','LeftCeiling':'\u2308','LeftDoubleBracket':'\u27E6','LeftDownTeeVector':'\u2961','LeftDownVector':'\u21C3','LeftDownVectorBar':'\u2959','LeftFloor':'\u230A','leftharpoondown':'\u21BD','leftharpoonup':'\u21BC','leftleftarrows':'\u21C7','leftrightarrow':'\u2194','Leftrightarrow':'\u21D4','LeftRightArrow':'\u2194','leftrightarrows':'\u21C6','leftrightharpoons':'\u21CB','leftrightsquigarrow':'\u21AD','LeftRightVector':'\u294E','LeftTee':'\u22A3','LeftTeeArrow':'\u21A4','LeftTeeVector':'\u295A','leftthreetimes':'\u22CB','LeftTriangle':'\u22B2','LeftTriangleBar':'\u29CF','LeftTriangleEqual':'\u22B4','LeftUpDownVector':'\u2951','LeftUpTeeVector':'\u2960','LeftUpVector':'\u21BF','LeftUpVectorBar':'\u2958','LeftVector':'\u21BC','LeftVectorBar':'\u2952','leg':'\u22DA','lEg':'\u2A8B','leq':'\u2264','leqq':'\u2266','leqslant':'\u2A7D','les':'\u2A7D','lescc':'\u2AA8','lesdot':'\u2A7F','lesdoto':'\u2A81','lesdotor':'\u2A83','lesg':'\u22DA\uFE00','lesges':'\u2A93','lessapprox':'\u2A85','lessdot':'\u22D6','lesseqgtr':'\u22DA','lesseqqgtr':'\u2A8B','LessEqualGreater':'\u22DA','LessFullEqual':'\u2266','LessGreater':'\u2276','lessgtr':'\u2276','LessLess':'\u2AA1','lesssim':'\u2272','LessSlantEqual':'\u2A7D','LessTilde':'\u2272','lfisht':'\u297C','lfloor':'\u230A','lfr':'\uD835\uDD29','Lfr':'\uD835\uDD0F','lg':'\u2276','lgE':'\u2A91','lHar':'\u2962','lhard':'\u21BD','lharu':'\u21BC','lharul':'\u296A','lhblk':'\u2584','ljcy':'\u0459','LJcy':'\u0409','ll':'\u226A','Ll':'\u22D8','llarr':'\u21C7','llcorner':'\u231E','Lleftarrow':'\u21DA','llhard':'\u296B','lltri':'\u25FA','lmidot':'\u0140','Lmidot':'\u013F','lmoust':'\u23B0','lmoustache':'\u23B0','lnap':'\u2A89','lnapprox':'\u2A89','lne':'\u2A87','lnE':'\u2268','lneq':'\u2A87','lneqq':'\u2268','lnsim':'\u22E6','loang':'\u27EC','loarr':'\u21FD','lobrk':'\u27E6','longleftarrow':'\u27F5','Longleftarrow':'\u27F8','LongLeftArrow':'\u27F5','longleftrightarrow':'\u27F7','Longleftrightarrow':'\u27FA','LongLeftRightArrow':'\u27F7','longmapsto':'\u27FC','longrightarrow':'\u27F6','Longrightarrow':'\u27F9','LongRightArrow':'\u27F6','looparrowleft':'\u21AB','looparrowright':'\u21AC','lopar':'\u2985','lopf':'\uD835\uDD5D','Lopf':'\uD835\uDD43','loplus':'\u2A2D','lotimes':'\u2A34','lowast':'\u2217','lowbar':'_','LowerLeftArrow':'\u2199','LowerRightArrow':'\u2198','loz':'\u25CA','lozenge':'\u25CA','lozf':'\u29EB','lpar':'(','lparlt':'\u2993','lrarr':'\u21C6','lrcorner':'\u231F','lrhar':'\u21CB','lrhard':'\u296D','lrm':'\u200E','lrtri':'\u22BF','lsaquo':'\u2039','lscr':'\uD835\uDCC1','Lscr':'\u2112','lsh':'\u21B0','Lsh':'\u21B0','lsim':'\u2272','lsime':'\u2A8D','lsimg':'\u2A8F','lsqb':'[','lsquo':'\u2018','lsquor':'\u201A','lstrok':'\u0142','Lstrok':'\u0141','lt':'<','Lt':'\u226A','LT':'<','ltcc':'\u2AA6','ltcir':'\u2A79','ltdot':'\u22D6','lthree':'\u22CB','ltimes':'\u22C9','ltlarr':'\u2976','ltquest':'\u2A7B','ltri':'\u25C3','ltrie':'\u22B4','ltrif':'\u25C2','ltrPar':'\u2996','lurdshar':'\u294A','luruhar':'\u2966','lvertneqq':'\u2268\uFE00','lvnE':'\u2268\uFE00','macr':'\xAF','male':'\u2642','malt':'\u2720','maltese':'\u2720','map':'\u21A6','Map':'\u2905','mapsto':'\u21A6','mapstodown':'\u21A7','mapstoleft':'\u21A4','mapstoup':'\u21A5','marker':'\u25AE','mcomma':'\u2A29','mcy':'\u043C','Mcy':'\u041C','mdash':'\u2014','mDDot':'\u223A','measuredangle':'\u2221','MediumSpace':'\u205F','Mellintrf':'\u2133','mfr':'\uD835\uDD2A','Mfr':'\uD835\uDD10','mho':'\u2127','micro':'\xB5','mid':'\u2223','midast':'*','midcir':'\u2AF0','middot':'\xB7','minus':'\u2212','minusb':'\u229F','minusd':'\u2238','minusdu':'\u2A2A','MinusPlus':'\u2213','mlcp':'\u2ADB','mldr':'\u2026','mnplus':'\u2213','models':'\u22A7','mopf':'\uD835\uDD5E','Mopf':'\uD835\uDD44','mp':'\u2213','mscr':'\uD835\uDCC2','Mscr':'\u2133','mstpos':'\u223E','mu':'\u03BC','Mu':'\u039C','multimap':'\u22B8','mumap':'\u22B8','nabla':'\u2207','nacute':'\u0144','Nacute':'\u0143','nang':'\u2220\u20D2','nap':'\u2249','napE':'\u2A70\u0338','napid':'\u224B\u0338','napos':'\u0149','napprox':'\u2249','natur':'\u266E','natural':'\u266E','naturals':'\u2115','nbsp':'\xA0','nbump':'\u224E\u0338','nbumpe':'\u224F\u0338','ncap':'\u2A43','ncaron':'\u0148','Ncaron':'\u0147','ncedil':'\u0146','Ncedil':'\u0145','ncong':'\u2247','ncongdot':'\u2A6D\u0338','ncup':'\u2A42','ncy':'\u043D','Ncy':'\u041D','ndash':'\u2013','ne':'\u2260','nearhk':'\u2924','nearr':'\u2197','neArr':'\u21D7','nearrow':'\u2197','nedot':'\u2250\u0338','NegativeMediumSpace':'\u200B','NegativeThickSpace':'\u200B','NegativeThinSpace':'\u200B','NegativeVeryThinSpace':'\u200B','nequiv':'\u2262','nesear':'\u2928','nesim':'\u2242\u0338','NestedGreaterGreater':'\u226B','NestedLessLess':'\u226A','NewLine':'\n','nexist':'\u2204','nexists':'\u2204','nfr':'\uD835\uDD2B','Nfr':'\uD835\uDD11','nge':'\u2271','ngE':'\u2267\u0338','ngeq':'\u2271','ngeqq':'\u2267\u0338','ngeqslant':'\u2A7E\u0338','nges':'\u2A7E\u0338','nGg':'\u22D9\u0338','ngsim':'\u2275','ngt':'\u226F','nGt':'\u226B\u20D2','ngtr':'\u226F','nGtv':'\u226B\u0338','nharr':'\u21AE','nhArr':'\u21CE','nhpar':'\u2AF2','ni':'\u220B','nis':'\u22FC','nisd':'\u22FA','niv':'\u220B','njcy':'\u045A','NJcy':'\u040A','nlarr':'\u219A','nlArr':'\u21CD','nldr':'\u2025','nle':'\u2270','nlE':'\u2266\u0338','nleftarrow':'\u219A','nLeftarrow':'\u21CD','nleftrightarrow':'\u21AE','nLeftrightarrow':'\u21CE','nleq':'\u2270','nleqq':'\u2266\u0338','nleqslant':'\u2A7D\u0338','nles':'\u2A7D\u0338','nless':'\u226E','nLl':'\u22D8\u0338','nlsim':'\u2274','nlt':'\u226E','nLt':'\u226A\u20D2','nltri':'\u22EA','nltrie':'\u22EC','nLtv':'\u226A\u0338','nmid':'\u2224','NoBreak':'\u2060','NonBreakingSpace':'\xA0','nopf':'\uD835\uDD5F','Nopf':'\u2115','not':'\xAC','Not':'\u2AEC','NotCongruent':'\u2262','NotCupCap':'\u226D','NotDoubleVerticalBar':'\u2226','NotElement':'\u2209','NotEqual':'\u2260','NotEqualTilde':'\u2242\u0338','NotExists':'\u2204','NotGreater':'\u226F','NotGreaterEqual':'\u2271','NotGreaterFullEqual':'\u2267\u0338','NotGreaterGreater':'\u226B\u0338','NotGreaterLess':'\u2279','NotGreaterSlantEqual':'\u2A7E\u0338','NotGreaterTilde':'\u2275','NotHumpDownHump':'\u224E\u0338','NotHumpEqual':'\u224F\u0338','notin':'\u2209','notindot':'\u22F5\u0338','notinE':'\u22F9\u0338','notinva':'\u2209','notinvb':'\u22F7','notinvc':'\u22F6','NotLeftTriangle':'\u22EA','NotLeftTriangleBar':'\u29CF\u0338','NotLeftTriangleEqual':'\u22EC','NotLess':'\u226E','NotLessEqual':'\u2270','NotLessGreater':'\u2278','NotLessLess':'\u226A\u0338','NotLessSlantEqual':'\u2A7D\u0338','NotLessTilde':'\u2274','NotNestedGreaterGreater':'\u2AA2\u0338','NotNestedLessLess':'\u2AA1\u0338','notni':'\u220C','notniva':'\u220C','notnivb':'\u22FE','notnivc':'\u22FD','NotPrecedes':'\u2280','NotPrecedesEqual':'\u2AAF\u0338','NotPrecedesSlantEqual':'\u22E0','NotReverseElement':'\u220C','NotRightTriangle':'\u22EB','NotRightTriangleBar':'\u29D0\u0338','NotRightTriangleEqual':'\u22ED','NotSquareSubset':'\u228F\u0338','NotSquareSubsetEqual':'\u22E2','NotSquareSuperset':'\u2290\u0338','NotSquareSupersetEqual':'\u22E3','NotSubset':'\u2282\u20D2','NotSubsetEqual':'\u2288','NotSucceeds':'\u2281','NotSucceedsEqual':'\u2AB0\u0338','NotSucceedsSlantEqual':'\u22E1','NotSucceedsTilde':'\u227F\u0338','NotSuperset':'\u2283\u20D2','NotSupersetEqual':'\u2289','NotTilde':'\u2241','NotTildeEqual':'\u2244','NotTildeFullEqual':'\u2247','NotTildeTilde':'\u2249','NotVerticalBar':'\u2224','npar':'\u2226','nparallel':'\u2226','nparsl':'\u2AFD\u20E5','npart':'\u2202\u0338','npolint':'\u2A14','npr':'\u2280','nprcue':'\u22E0','npre':'\u2AAF\u0338','nprec':'\u2280','npreceq':'\u2AAF\u0338','nrarr':'\u219B','nrArr':'\u21CF','nrarrc':'\u2933\u0338','nrarrw':'\u219D\u0338','nrightarrow':'\u219B','nRightarrow':'\u21CF','nrtri':'\u22EB','nrtrie':'\u22ED','nsc':'\u2281','nsccue':'\u22E1','nsce':'\u2AB0\u0338','nscr':'\uD835\uDCC3','Nscr':'\uD835\uDCA9','nshortmid':'\u2224','nshortparallel':'\u2226','nsim':'\u2241','nsime':'\u2244','nsimeq':'\u2244','nsmid':'\u2224','nspar':'\u2226','nsqsube':'\u22E2','nsqsupe':'\u22E3','nsub':'\u2284','nsube':'\u2288','nsubE':'\u2AC5\u0338','nsubset':'\u2282\u20D2','nsubseteq':'\u2288','nsubseteqq':'\u2AC5\u0338','nsucc':'\u2281','nsucceq':'\u2AB0\u0338','nsup':'\u2285','nsupe':'\u2289','nsupE':'\u2AC6\u0338','nsupset':'\u2283\u20D2','nsupseteq':'\u2289','nsupseteqq':'\u2AC6\u0338','ntgl':'\u2279','ntilde':'\xF1','Ntilde':'\xD1','ntlg':'\u2278','ntriangleleft':'\u22EA','ntrianglelefteq':'\u22EC','ntriangleright':'\u22EB','ntrianglerighteq':'\u22ED','nu':'\u03BD','Nu':'\u039D','num':'#','numero':'\u2116','numsp':'\u2007','nvap':'\u224D\u20D2','nvdash':'\u22AC','nvDash':'\u22AD','nVdash':'\u22AE','nVDash':'\u22AF','nvge':'\u2265\u20D2','nvgt':'>\u20D2','nvHarr':'\u2904','nvinfin':'\u29DE','nvlArr':'\u2902','nvle':'\u2264\u20D2','nvlt':'<\u20D2','nvltrie':'\u22B4\u20D2','nvrArr':'\u2903','nvrtrie':'\u22B5\u20D2','nvsim':'\u223C\u20D2','nwarhk':'\u2923','nwarr':'\u2196','nwArr':'\u21D6','nwarrow':'\u2196','nwnear':'\u2927','oacute':'\xF3','Oacute':'\xD3','oast':'\u229B','ocir':'\u229A','ocirc':'\xF4','Ocirc':'\xD4','ocy':'\u043E','Ocy':'\u041E','odash':'\u229D','odblac':'\u0151','Odblac':'\u0150','odiv':'\u2A38','odot':'\u2299','odsold':'\u29BC','oelig':'\u0153','OElig':'\u0152','ofcir':'\u29BF','ofr':'\uD835\uDD2C','Ofr':'\uD835\uDD12','ogon':'\u02DB','ograve':'\xF2','Ograve':'\xD2','ogt':'\u29C1','ohbar':'\u29B5','ohm':'\u03A9','oint':'\u222E','olarr':'\u21BA','olcir':'\u29BE','olcross':'\u29BB','oline':'\u203E','olt':'\u29C0','omacr':'\u014D','Omacr':'\u014C','omega':'\u03C9','Omega':'\u03A9','omicron':'\u03BF','Omicron':'\u039F','omid':'\u29B6','ominus':'\u2296','oopf':'\uD835\uDD60','Oopf':'\uD835\uDD46','opar':'\u29B7','OpenCurlyDoubleQuote':'\u201C','OpenCurlyQuote':'\u2018','operp':'\u29B9','oplus':'\u2295','or':'\u2228','Or':'\u2A54','orarr':'\u21BB','ord':'\u2A5D','order':'\u2134','orderof':'\u2134','ordf':'\xAA','ordm':'\xBA','origof':'\u22B6','oror':'\u2A56','orslope':'\u2A57','orv':'\u2A5B','oS':'\u24C8','oscr':'\u2134','Oscr':'\uD835\uDCAA','oslash':'\xF8','Oslash':'\xD8','osol':'\u2298','otilde':'\xF5','Otilde':'\xD5','otimes':'\u2297','Otimes':'\u2A37','otimesas':'\u2A36','ouml':'\xF6','Ouml':'\xD6','ovbar':'\u233D','OverBar':'\u203E','OverBrace':'\u23DE','OverBracket':'\u23B4','OverParenthesis':'\u23DC','par':'\u2225','para':'\xB6','parallel':'\u2225','parsim':'\u2AF3','parsl':'\u2AFD','part':'\u2202','PartialD':'\u2202','pcy':'\u043F','Pcy':'\u041F','percnt':'%','period':'.','permil':'\u2030','perp':'\u22A5','pertenk':'\u2031','pfr':'\uD835\uDD2D','Pfr':'\uD835\uDD13','phi':'\u03C6','Phi':'\u03A6','phiv':'\u03D5','phmmat':'\u2133','phone':'\u260E','pi':'\u03C0','Pi':'\u03A0','pitchfork':'\u22D4','piv':'\u03D6','planck':'\u210F','planckh':'\u210E','plankv':'\u210F','plus':'+','plusacir':'\u2A23','plusb':'\u229E','pluscir':'\u2A22','plusdo':'\u2214','plusdu':'\u2A25','pluse':'\u2A72','PlusMinus':'\xB1','plusmn':'\xB1','plussim':'\u2A26','plustwo':'\u2A27','pm':'\xB1','Poincareplane':'\u210C','pointint':'\u2A15','popf':'\uD835\uDD61','Popf':'\u2119','pound':'\xA3','pr':'\u227A','Pr':'\u2ABB','prap':'\u2AB7','prcue':'\u227C','pre':'\u2AAF','prE':'\u2AB3','prec':'\u227A','precapprox':'\u2AB7','preccurlyeq':'\u227C','Precedes':'\u227A','PrecedesEqual':'\u2AAF','PrecedesSlantEqual':'\u227C','PrecedesTilde':'\u227E','preceq':'\u2AAF','precnapprox':'\u2AB9','precneqq':'\u2AB5','precnsim':'\u22E8','precsim':'\u227E','prime':'\u2032','Prime':'\u2033','primes':'\u2119','prnap':'\u2AB9','prnE':'\u2AB5','prnsim':'\u22E8','prod':'\u220F','Product':'\u220F','profalar':'\u232E','profline':'\u2312','profsurf':'\u2313','prop':'\u221D','Proportion':'\u2237','Proportional':'\u221D','propto':'\u221D','prsim':'\u227E','prurel':'\u22B0','pscr':'\uD835\uDCC5','Pscr':'\uD835\uDCAB','psi':'\u03C8','Psi':'\u03A8','puncsp':'\u2008','qfr':'\uD835\uDD2E','Qfr':'\uD835\uDD14','qint':'\u2A0C','qopf':'\uD835\uDD62','Qopf':'\u211A','qprime':'\u2057','qscr':'\uD835\uDCC6','Qscr':'\uD835\uDCAC','quaternions':'\u210D','quatint':'\u2A16','quest':'?','questeq':'\u225F','quot':'"','QUOT':'"','rAarr':'\u21DB','race':'\u223D\u0331','racute':'\u0155','Racute':'\u0154','radic':'\u221A','raemptyv':'\u29B3','rang':'\u27E9','Rang':'\u27EB','rangd':'\u2992','range':'\u29A5','rangle':'\u27E9','raquo':'\xBB','rarr':'\u2192','rArr':'\u21D2','Rarr':'\u21A0','rarrap':'\u2975','rarrb':'\u21E5','rarrbfs':'\u2920','rarrc':'\u2933','rarrfs':'\u291E','rarrhk':'\u21AA','rarrlp':'\u21AC','rarrpl':'\u2945','rarrsim':'\u2974','rarrtl':'\u21A3','Rarrtl':'\u2916','rarrw':'\u219D','ratail':'\u291A','rAtail':'\u291C','ratio':'\u2236','rationals':'\u211A','rbarr':'\u290D','rBarr':'\u290F','RBarr':'\u2910','rbbrk':'\u2773','rbrace':'}','rbrack':']','rbrke':'\u298C','rbrksld':'\u298E','rbrkslu':'\u2990','rcaron':'\u0159','Rcaron':'\u0158','rcedil':'\u0157','Rcedil':'\u0156','rceil':'\u2309','rcub':'}','rcy':'\u0440','Rcy':'\u0420','rdca':'\u2937','rdldhar':'\u2969','rdquo':'\u201D','rdquor':'\u201D','rdsh':'\u21B3','Re':'\u211C','real':'\u211C','realine':'\u211B','realpart':'\u211C','reals':'\u211D','rect':'\u25AD','reg':'\xAE','REG':'\xAE','ReverseElement':'\u220B','ReverseEquilibrium':'\u21CB','ReverseUpEquilibrium':'\u296F','rfisht':'\u297D','rfloor':'\u230B','rfr':'\uD835\uDD2F','Rfr':'\u211C','rHar':'\u2964','rhard':'\u21C1','rharu':'\u21C0','rharul':'\u296C','rho':'\u03C1','Rho':'\u03A1','rhov':'\u03F1','RightAngleBracket':'\u27E9','rightarrow':'\u2192','Rightarrow':'\u21D2','RightArrow':'\u2192','RightArrowBar':'\u21E5','RightArrowLeftArrow':'\u21C4','rightarrowtail':'\u21A3','RightCeiling':'\u2309','RightDoubleBracket':'\u27E7','RightDownTeeVector':'\u295D','RightDownVector':'\u21C2','RightDownVectorBar':'\u2955','RightFloor':'\u230B','rightharpoondown':'\u21C1','rightharpoonup':'\u21C0','rightleftarrows':'\u21C4','rightleftharpoons':'\u21CC','rightrightarrows':'\u21C9','rightsquigarrow':'\u219D','RightTee':'\u22A2','RightTeeArrow':'\u21A6','RightTeeVector':'\u295B','rightthreetimes':'\u22CC','RightTriangle':'\u22B3','RightTriangleBar':'\u29D0','RightTriangleEqual':'\u22B5','RightUpDownVector':'\u294F','RightUpTeeVector':'\u295C','RightUpVector':'\u21BE','RightUpVectorBar':'\u2954','RightVector':'\u21C0','RightVectorBar':'\u2953','ring':'\u02DA','risingdotseq':'\u2253','rlarr':'\u21C4','rlhar':'\u21CC','rlm':'\u200F','rmoust':'\u23B1','rmoustache':'\u23B1','rnmid':'\u2AEE','roang':'\u27ED','roarr':'\u21FE','robrk':'\u27E7','ropar':'\u2986','ropf':'\uD835\uDD63','Ropf':'\u211D','roplus':'\u2A2E','rotimes':'\u2A35','RoundImplies':'\u2970','rpar':')','rpargt':'\u2994','rppolint':'\u2A12','rrarr':'\u21C9','Rrightarrow':'\u21DB','rsaquo':'\u203A','rscr':'\uD835\uDCC7','Rscr':'\u211B','rsh':'\u21B1','Rsh':'\u21B1','rsqb':']','rsquo':'\u2019','rsquor':'\u2019','rthree':'\u22CC','rtimes':'\u22CA','rtri':'\u25B9','rtrie':'\u22B5','rtrif':'\u25B8','rtriltri':'\u29CE','RuleDelayed':'\u29F4','ruluhar':'\u2968','rx':'\u211E','sacute':'\u015B','Sacute':'\u015A','sbquo':'\u201A','sc':'\u227B','Sc':'\u2ABC','scap':'\u2AB8','scaron':'\u0161','Scaron':'\u0160','sccue':'\u227D','sce':'\u2AB0','scE':'\u2AB4','scedil':'\u015F','Scedil':'\u015E','scirc':'\u015D','Scirc':'\u015C','scnap':'\u2ABA','scnE':'\u2AB6','scnsim':'\u22E9','scpolint':'\u2A13','scsim':'\u227F','scy':'\u0441','Scy':'\u0421','sdot':'\u22C5','sdotb':'\u22A1','sdote':'\u2A66','searhk':'\u2925','searr':'\u2198','seArr':'\u21D8','searrow':'\u2198','sect':'\xA7','semi':';','seswar':'\u2929','setminus':'\u2216','setmn':'\u2216','sext':'\u2736','sfr':'\uD835\uDD30','Sfr':'\uD835\uDD16','sfrown':'\u2322','sharp':'\u266F','shchcy':'\u0449','SHCHcy':'\u0429','shcy':'\u0448','SHcy':'\u0428','ShortDownArrow':'\u2193','ShortLeftArrow':'\u2190','shortmid':'\u2223','shortparallel':'\u2225','ShortRightArrow':'\u2192','ShortUpArrow':'\u2191','shy':'\xAD','sigma':'\u03C3','Sigma':'\u03A3','sigmaf':'\u03C2','sigmav':'\u03C2','sim':'\u223C','simdot':'\u2A6A','sime':'\u2243','simeq':'\u2243','simg':'\u2A9E','simgE':'\u2AA0','siml':'\u2A9D','simlE':'\u2A9F','simne':'\u2246','simplus':'\u2A24','simrarr':'\u2972','slarr':'\u2190','SmallCircle':'\u2218','smallsetminus':'\u2216','smashp':'\u2A33','smeparsl':'\u29E4','smid':'\u2223','smile':'\u2323','smt':'\u2AAA','smte':'\u2AAC','smtes':'\u2AAC\uFE00','softcy':'\u044C','SOFTcy':'\u042C','sol':'/','solb':'\u29C4','solbar':'\u233F','sopf':'\uD835\uDD64','Sopf':'\uD835\uDD4A','spades':'\u2660','spadesuit':'\u2660','spar':'\u2225','sqcap':'\u2293','sqcaps':'\u2293\uFE00','sqcup':'\u2294','sqcups':'\u2294\uFE00','Sqrt':'\u221A','sqsub':'\u228F','sqsube':'\u2291','sqsubset':'\u228F','sqsubseteq':'\u2291','sqsup':'\u2290','sqsupe':'\u2292','sqsupset':'\u2290','sqsupseteq':'\u2292','squ':'\u25A1','square':'\u25A1','Square':'\u25A1','SquareIntersection':'\u2293','SquareSubset':'\u228F','SquareSubsetEqual':'\u2291','SquareSuperset':'\u2290','SquareSupersetEqual':'\u2292','SquareUnion':'\u2294','squarf':'\u25AA','squf':'\u25AA','srarr':'\u2192','sscr':'\uD835\uDCC8','Sscr':'\uD835\uDCAE','ssetmn':'\u2216','ssmile':'\u2323','sstarf':'\u22C6','star':'\u2606','Star':'\u22C6','starf':'\u2605','straightepsilon':'\u03F5','straightphi':'\u03D5','strns':'\xAF','sub':'\u2282','Sub':'\u22D0','subdot':'\u2ABD','sube':'\u2286','subE':'\u2AC5','subedot':'\u2AC3','submult':'\u2AC1','subne':'\u228A','subnE':'\u2ACB','subplus':'\u2ABF','subrarr':'\u2979','subset':'\u2282','Subset':'\u22D0','subseteq':'\u2286','subseteqq':'\u2AC5','SubsetEqual':'\u2286','subsetneq':'\u228A','subsetneqq':'\u2ACB','subsim':'\u2AC7','subsub':'\u2AD5','subsup':'\u2AD3','succ':'\u227B','succapprox':'\u2AB8','succcurlyeq':'\u227D','Succeeds':'\u227B','SucceedsEqual':'\u2AB0','SucceedsSlantEqual':'\u227D','SucceedsTilde':'\u227F','succeq':'\u2AB0','succnapprox':'\u2ABA','succneqq':'\u2AB6','succnsim':'\u22E9','succsim':'\u227F','SuchThat':'\u220B','sum':'\u2211','Sum':'\u2211','sung':'\u266A','sup':'\u2283','Sup':'\u22D1','sup1':'\xB9','sup2':'\xB2','sup3':'\xB3','supdot':'\u2ABE','supdsub':'\u2AD8','supe':'\u2287','supE':'\u2AC6','supedot':'\u2AC4','Superset':'\u2283','SupersetEqual':'\u2287','suphsol':'\u27C9','suphsub':'\u2AD7','suplarr':'\u297B','supmult':'\u2AC2','supne':'\u228B','supnE':'\u2ACC','supplus':'\u2AC0','supset':'\u2283','Supset':'\u22D1','supseteq':'\u2287','supseteqq':'\u2AC6','supsetneq':'\u228B','supsetneqq':'\u2ACC','supsim':'\u2AC8','supsub':'\u2AD4','supsup':'\u2AD6','swarhk':'\u2926','swarr':'\u2199','swArr':'\u21D9','swarrow':'\u2199','swnwar':'\u292A','szlig':'\xDF','Tab':'\t','target':'\u2316','tau':'\u03C4','Tau':'\u03A4','tbrk':'\u23B4','tcaron':'\u0165','Tcaron':'\u0164','tcedil':'\u0163','Tcedil':'\u0162','tcy':'\u0442','Tcy':'\u0422','tdot':'\u20DB','telrec':'\u2315','tfr':'\uD835\uDD31','Tfr':'\uD835\uDD17','there4':'\u2234','therefore':'\u2234','Therefore':'\u2234','theta':'\u03B8','Theta':'\u0398','thetasym':'\u03D1','thetav':'\u03D1','thickapprox':'\u2248','thicksim':'\u223C','ThickSpace':'\u205F\u200A','thinsp':'\u2009','ThinSpace':'\u2009','thkap':'\u2248','thksim':'\u223C','thorn':'\xFE','THORN':'\xDE','tilde':'\u02DC','Tilde':'\u223C','TildeEqual':'\u2243','TildeFullEqual':'\u2245','TildeTilde':'\u2248','times':'\xD7','timesb':'\u22A0','timesbar':'\u2A31','timesd':'\u2A30','tint':'\u222D','toea':'\u2928','top':'\u22A4','topbot':'\u2336','topcir':'\u2AF1','topf':'\uD835\uDD65','Topf':'\uD835\uDD4B','topfork':'\u2ADA','tosa':'\u2929','tprime':'\u2034','trade':'\u2122','TRADE':'\u2122','triangle':'\u25B5','triangledown':'\u25BF','triangleleft':'\u25C3','trianglelefteq':'\u22B4','triangleq':'\u225C','triangleright':'\u25B9','trianglerighteq':'\u22B5','tridot':'\u25EC','trie':'\u225C','triminus':'\u2A3A','TripleDot':'\u20DB','triplus':'\u2A39','trisb':'\u29CD','tritime':'\u2A3B','trpezium':'\u23E2','tscr':'\uD835\uDCC9','Tscr':'\uD835\uDCAF','tscy':'\u0446','TScy':'\u0426','tshcy':'\u045B','TSHcy':'\u040B','tstrok':'\u0167','Tstrok':'\u0166','twixt':'\u226C','twoheadleftarrow':'\u219E','twoheadrightarrow':'\u21A0','uacute':'\xFA','Uacute':'\xDA','uarr':'\u2191','uArr':'\u21D1','Uarr':'\u219F','Uarrocir':'\u2949','ubrcy':'\u045E','Ubrcy':'\u040E','ubreve':'\u016D','Ubreve':'\u016C','ucirc':'\xFB','Ucirc':'\xDB','ucy':'\u0443','Ucy':'\u0423','udarr':'\u21C5','udblac':'\u0171','Udblac':'\u0170','udhar':'\u296E','ufisht':'\u297E','ufr':'\uD835\uDD32','Ufr':'\uD835\uDD18','ugrave':'\xF9','Ugrave':'\xD9','uHar':'\u2963','uharl':'\u21BF','uharr':'\u21BE','uhblk':'\u2580','ulcorn':'\u231C','ulcorner':'\u231C','ulcrop':'\u230F','ultri':'\u25F8','umacr':'\u016B','Umacr':'\u016A','uml':'\xA8','UnderBar':'_','UnderBrace':'\u23DF','UnderBracket':'\u23B5','UnderParenthesis':'\u23DD','Union':'\u22C3','UnionPlus':'\u228E','uogon':'\u0173','Uogon':'\u0172','uopf':'\uD835\uDD66','Uopf':'\uD835\uDD4C','uparrow':'\u2191','Uparrow':'\u21D1','UpArrow':'\u2191','UpArrowBar':'\u2912','UpArrowDownArrow':'\u21C5','updownarrow':'\u2195','Updownarrow':'\u21D5','UpDownArrow':'\u2195','UpEquilibrium':'\u296E','upharpoonleft':'\u21BF','upharpoonright':'\u21BE','uplus':'\u228E','UpperLeftArrow':'\u2196','UpperRightArrow':'\u2197','upsi':'\u03C5','Upsi':'\u03D2','upsih':'\u03D2','upsilon':'\u03C5','Upsilon':'\u03A5','UpTee':'\u22A5','UpTeeArrow':'\u21A5','upuparrows':'\u21C8','urcorn':'\u231D','urcorner':'\u231D','urcrop':'\u230E','uring':'\u016F','Uring':'\u016E','urtri':'\u25F9','uscr':'\uD835\uDCCA','Uscr':'\uD835\uDCB0','utdot':'\u22F0','utilde':'\u0169','Utilde':'\u0168','utri':'\u25B5','utrif':'\u25B4','uuarr':'\u21C8','uuml':'\xFC','Uuml':'\xDC','uwangle':'\u29A7','vangrt':'\u299C','varepsilon':'\u03F5','varkappa':'\u03F0','varnothing':'\u2205','varphi':'\u03D5','varpi':'\u03D6','varpropto':'\u221D','varr':'\u2195','vArr':'\u21D5','varrho':'\u03F1','varsigma':'\u03C2','varsubsetneq':'\u228A\uFE00','varsubsetneqq':'\u2ACB\uFE00','varsupsetneq':'\u228B\uFE00','varsupsetneqq':'\u2ACC\uFE00','vartheta':'\u03D1','vartriangleleft':'\u22B2','vartriangleright':'\u22B3','vBar':'\u2AE8','Vbar':'\u2AEB','vBarv':'\u2AE9','vcy':'\u0432','Vcy':'\u0412','vdash':'\u22A2','vDash':'\u22A8','Vdash':'\u22A9','VDash':'\u22AB','Vdashl':'\u2AE6','vee':'\u2228','Vee':'\u22C1','veebar':'\u22BB','veeeq':'\u225A','vellip':'\u22EE','verbar':'|','Verbar':'\u2016','vert':'|','Vert':'\u2016','VerticalBar':'\u2223','VerticalLine':'|','VerticalSeparator':'\u2758','VerticalTilde':'\u2240','VeryThinSpace':'\u200A','vfr':'\uD835\uDD33','Vfr':'\uD835\uDD19','vltri':'\u22B2','vnsub':'\u2282\u20D2','vnsup':'\u2283\u20D2','vopf':'\uD835\uDD67','Vopf':'\uD835\uDD4D','vprop':'\u221D','vrtri':'\u22B3','vscr':'\uD835\uDCCB','Vscr':'\uD835\uDCB1','vsubne':'\u228A\uFE00','vsubnE':'\u2ACB\uFE00','vsupne':'\u228B\uFE00','vsupnE':'\u2ACC\uFE00','Vvdash':'\u22AA','vzigzag':'\u299A','wcirc':'\u0175','Wcirc':'\u0174','wedbar':'\u2A5F','wedge':'\u2227','Wedge':'\u22C0','wedgeq':'\u2259','weierp':'\u2118','wfr':'\uD835\uDD34','Wfr':'\uD835\uDD1A','wopf':'\uD835\uDD68','Wopf':'\uD835\uDD4E','wp':'\u2118','wr':'\u2240','wreath':'\u2240','wscr':'\uD835\uDCCC','Wscr':'\uD835\uDCB2','xcap':'\u22C2','xcirc':'\u25EF','xcup':'\u22C3','xdtri':'\u25BD','xfr':'\uD835\uDD35','Xfr':'\uD835\uDD1B','xharr':'\u27F7','xhArr':'\u27FA','xi':'\u03BE','Xi':'\u039E','xlarr':'\u27F5','xlArr':'\u27F8','xmap':'\u27FC','xnis':'\u22FB','xodot':'\u2A00','xopf':'\uD835\uDD69','Xopf':'\uD835\uDD4F','xoplus':'\u2A01','xotime':'\u2A02','xrarr':'\u27F6','xrArr':'\u27F9','xscr':'\uD835\uDCCD','Xscr':'\uD835\uDCB3','xsqcup':'\u2A06','xuplus':'\u2A04','xutri':'\u25B3','xvee':'\u22C1','xwedge':'\u22C0','yacute':'\xFD','Yacute':'\xDD','yacy':'\u044F','YAcy':'\u042F','ycirc':'\u0177','Ycirc':'\u0176','ycy':'\u044B','Ycy':'\u042B','yen':'\xA5','yfr':'\uD835\uDD36','Yfr':'\uD835\uDD1C','yicy':'\u0457','YIcy':'\u0407','yopf':'\uD835\uDD6A','Yopf':'\uD835\uDD50','yscr':'\uD835\uDCCE','Yscr':'\uD835\uDCB4','yucy':'\u044E','YUcy':'\u042E','yuml':'\xFF','Yuml':'\u0178','zacute':'\u017A','Zacute':'\u0179','zcaron':'\u017E','Zcaron':'\u017D','zcy':'\u0437','Zcy':'\u0417','zdot':'\u017C','Zdot':'\u017B','zeetrf':'\u2128','ZeroWidthSpace':'\u200B','zeta':'\u03B6','Zeta':'\u0396','zfr':'\uD835\uDD37','Zfr':'\u2128','zhcy':'\u0436','ZHcy':'\u0416','zigrarr':'\u21DD','zopf':'\uD835\uDD6B','Zopf':'\u2124','zscr':'\uD835\uDCCF','Zscr':'\uD835\uDCB5','zwj':'\u200D','zwnj':'\u200C'}; + var decodeMapLegacy = {'aacute':'\xE1','Aacute':'\xC1','acirc':'\xE2','Acirc':'\xC2','acute':'\xB4','aelig':'\xE6','AElig':'\xC6','agrave':'\xE0','Agrave':'\xC0','amp':'&','AMP':'&','aring':'\xE5','Aring':'\xC5','atilde':'\xE3','Atilde':'\xC3','auml':'\xE4','Auml':'\xC4','brvbar':'\xA6','ccedil':'\xE7','Ccedil':'\xC7','cedil':'\xB8','cent':'\xA2','copy':'\xA9','COPY':'\xA9','curren':'\xA4','deg':'\xB0','divide':'\xF7','eacute':'\xE9','Eacute':'\xC9','ecirc':'\xEA','Ecirc':'\xCA','egrave':'\xE8','Egrave':'\xC8','eth':'\xF0','ETH':'\xD0','euml':'\xEB','Euml':'\xCB','frac12':'\xBD','frac14':'\xBC','frac34':'\xBE','gt':'>','GT':'>','iacute':'\xED','Iacute':'\xCD','icirc':'\xEE','Icirc':'\xCE','iexcl':'\xA1','igrave':'\xEC','Igrave':'\xCC','iquest':'\xBF','iuml':'\xEF','Iuml':'\xCF','laquo':'\xAB','lt':'<','LT':'<','macr':'\xAF','micro':'\xB5','middot':'\xB7','nbsp':'\xA0','not':'\xAC','ntilde':'\xF1','Ntilde':'\xD1','oacute':'\xF3','Oacute':'\xD3','ocirc':'\xF4','Ocirc':'\xD4','ograve':'\xF2','Ograve':'\xD2','ordf':'\xAA','ordm':'\xBA','oslash':'\xF8','Oslash':'\xD8','otilde':'\xF5','Otilde':'\xD5','ouml':'\xF6','Ouml':'\xD6','para':'\xB6','plusmn':'\xB1','pound':'\xA3','quot':'"','QUOT':'"','raquo':'\xBB','reg':'\xAE','REG':'\xAE','sect':'\xA7','shy':'\xAD','sup1':'\xB9','sup2':'\xB2','sup3':'\xB3','szlig':'\xDF','thorn':'\xFE','THORN':'\xDE','times':'\xD7','uacute':'\xFA','Uacute':'\xDA','ucirc':'\xFB','Ucirc':'\xDB','ugrave':'\xF9','Ugrave':'\xD9','uml':'\xA8','uuml':'\xFC','Uuml':'\xDC','yacute':'\xFD','Yacute':'\xDD','yen':'\xA5','yuml':'\xFF'}; + var decodeMapNumeric = {'0':'\uFFFD','128':'\u20AC','130':'\u201A','131':'\u0192','132':'\u201E','133':'\u2026','134':'\u2020','135':'\u2021','136':'\u02C6','137':'\u2030','138':'\u0160','139':'\u2039','140':'\u0152','142':'\u017D','145':'\u2018','146':'\u2019','147':'\u201C','148':'\u201D','149':'\u2022','150':'\u2013','151':'\u2014','152':'\u02DC','153':'\u2122','154':'\u0161','155':'\u203A','156':'\u0153','158':'\u017E','159':'\u0178'}; + var invalidReferenceCodePoints = [1,2,3,4,5,6,7,8,11,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,64976,64977,64978,64979,64980,64981,64982,64983,64984,64985,64986,64987,64988,64989,64990,64991,64992,64993,64994,64995,64996,64997,64998,64999,65000,65001,65002,65003,65004,65005,65006,65007,65534,65535,131070,131071,196606,196607,262142,262143,327678,327679,393214,393215,458750,458751,524286,524287,589822,589823,655358,655359,720894,720895,786430,786431,851966,851967,917502,917503,983038,983039,1048574,1048575,1114110,1114111]; + + /*--------------------------------------------------------------------------*/ + + var stringFromCharCode = String.fromCharCode; + + var object = {}; + var hasOwnProperty = object.hasOwnProperty; + var has = function(object, propertyName) { + return hasOwnProperty.call(object, propertyName); + }; + + var contains = function(array, value) { + var index = -1; + var length = array.length; + while (++index < length) { + if (array[index] == value) { + return true; + } + } + return false; + }; + + var merge = function(options, defaults) { + if (!options) { + return defaults; + } + var result = {}; + var key; + for (key in defaults) { + // A `hasOwnProperty` check is not needed here, since only recognized + // option names are used anyway. Any others are ignored. + result[key] = has(options, key) ? options[key] : defaults[key]; + } + return result; + }; + + // Modified version of `ucs2encode`; see https://mths.be/punycode. + var codePointToSymbol = function(codePoint, strict) { + var output = ''; + if ((codePoint >= 0xD800 && codePoint <= 0xDFFF) || codePoint > 0x10FFFF) { + // See issue #4: + // “Otherwise, if the number is in the range 0xD800 to 0xDFFF or is + // greater than 0x10FFFF, then this is a parse error. Return a U+FFFD + // REPLACEMENT CHARACTER.” + if (strict) { + parseError('character reference outside the permissible Unicode range'); + } + return '\uFFFD'; + } + if (has(decodeMapNumeric, codePoint)) { + if (strict) { + parseError('disallowed character reference'); + } + return decodeMapNumeric[codePoint]; + } + if (strict && contains(invalidReferenceCodePoints, codePoint)) { + parseError('disallowed character reference'); + } + if (codePoint > 0xFFFF) { + codePoint -= 0x10000; + output += stringFromCharCode(codePoint >>> 10 & 0x3FF | 0xD800); + codePoint = 0xDC00 | codePoint & 0x3FF; + } + output += stringFromCharCode(codePoint); + return output; + }; + + var hexEscape = function(codePoint) { + return '&#x' + codePoint.toString(16).toUpperCase() + ';'; + }; + + var decEscape = function(codePoint) { + return '&#' + codePoint + ';'; + }; + + var parseError = function(message) { + throw Error('Parse error: ' + message); + }; + + /*--------------------------------------------------------------------------*/ + + var encode = function(string, options) { + options = merge(options, encode.options); + var strict = options.strict; + if (strict && regexInvalidRawCodePoint.test(string)) { + parseError('forbidden code point'); + } + var encodeEverything = options.encodeEverything; + var useNamedReferences = options.useNamedReferences; + var allowUnsafeSymbols = options.allowUnsafeSymbols; + var escapeCodePoint = options.decimal ? decEscape : hexEscape; + + var escapeBmpSymbol = function(symbol) { + return escapeCodePoint(symbol.charCodeAt(0)); + }; + + if (encodeEverything) { + // Encode ASCII symbols. + string = string.replace(regexAsciiWhitelist, function(symbol) { + // Use named references if requested & possible. + if (useNamedReferences && has(encodeMap, symbol)) { + return '&' + encodeMap[symbol] + ';'; + } + return escapeBmpSymbol(symbol); + }); + // Shorten a few escapes that represent two symbols, of which at least one + // is within the ASCII range. + if (useNamedReferences) { + string = string + .replace(/>\u20D2/g, '>⃒') + .replace(/<\u20D2/g, '<⃒') + .replace(/fj/g, 'fj'); + } + // Encode non-ASCII symbols. + if (useNamedReferences) { + // Encode non-ASCII symbols that can be replaced with a named reference. + string = string.replace(regexEncodeNonAscii, function(string) { + // Note: there is no need to check `has(encodeMap, string)` here. + return '&' + encodeMap[string] + ';'; + }); + } + // Note: any remaining non-ASCII symbols are handled outside of the `if`. + } else if (useNamedReferences) { + // Apply named character references. + // Encode `<>"'&` using named character references. + if (!allowUnsafeSymbols) { + string = string.replace(regexEscape, function(string) { + return '&' + encodeMap[string] + ';'; // no need to check `has()` here + }); + } + // Shorten escapes that represent two symbols, of which at least one is + // `<>"'&`. + string = string + .replace(/>\u20D2/g, '>⃒') + .replace(/<\u20D2/g, '<⃒'); + // Encode non-ASCII symbols that can be replaced with a named reference. + string = string.replace(regexEncodeNonAscii, function(string) { + // Note: there is no need to check `has(encodeMap, string)` here. + return '&' + encodeMap[string] + ';'; + }); + } else if (!allowUnsafeSymbols) { + // Encode `<>"'&` using hexadecimal escapes, now that they’re not handled + // using named character references. + string = string.replace(regexEscape, escapeBmpSymbol); + } + return string + // Encode astral symbols. + .replace(regexAstralSymbols, function($0) { + // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae + var high = $0.charCodeAt(0); + var low = $0.charCodeAt(1); + var codePoint = (high - 0xD800) * 0x400 + low - 0xDC00 + 0x10000; + return escapeCodePoint(codePoint); + }) + // Encode any remaining BMP symbols that are not printable ASCII symbols + // using a hexadecimal escape. + .replace(regexBmpWhitelist, escapeBmpSymbol); + }; + // Expose default options (so they can be overridden globally). + encode.options = { + 'allowUnsafeSymbols': false, + 'encodeEverything': false, + 'strict': false, + 'useNamedReferences': false, + 'decimal' : false + }; + + var decode = function(html, options) { + options = merge(options, decode.options); + var strict = options.strict; + if (strict && regexInvalidEntity.test(html)) { + parseError('malformed character reference'); + } + return html.replace(regexDecode, function($0, $1, $2, $3, $4, $5, $6, $7) { + var codePoint; + var semicolon; + var decDigits; + var hexDigits; + var reference; + var next; + if ($1) { + // Decode decimal escapes, e.g. `𝌆`. + decDigits = $1; + semicolon = $2; + if (strict && !semicolon) { + parseError('character reference was not terminated by a semicolon'); + } + codePoint = parseInt(decDigits, 10); + return codePointToSymbol(codePoint, strict); + } + if ($3) { + // Decode hexadecimal escapes, e.g. `𝌆`. + hexDigits = $3; + semicolon = $4; + if (strict && !semicolon) { + parseError('character reference was not terminated by a semicolon'); + } + codePoint = parseInt(hexDigits, 16); + return codePointToSymbol(codePoint, strict); + } + if ($5) { + // Decode named character references with trailing `;`, e.g. `©`. + reference = $5; + if (has(decodeMap, reference)) { + return decodeMap[reference]; + } else { + // Ambiguous ampersand. https://mths.be/notes/ambiguous-ampersands + if (strict) { + parseError( + 'named character reference was not terminated by a semicolon' + ); + } + return $0; + } + } + // If we’re still here, it’s a legacy reference for sure. No need for an + // extra `if` check. + // Decode named character references without trailing `;`, e.g. `&` + // This is only a parse error if it gets converted to `&`, or if it is + // followed by `=` in an attribute context. + reference = $6; + next = $7; + if (next && options.isAttributeValue) { + if (strict && next == '=') { + parseError('`&` did not start a character reference'); + } + return $0; + } else { + if (strict) { + parseError( + 'named character reference was not terminated by a semicolon' + ); + } + // Note: there is no need to check `has(decodeMapLegacy, reference)`. + return decodeMapLegacy[reference] + (next || ''); + } + }); + }; + // Expose default options (so they can be overridden globally). + decode.options = { + 'isAttributeValue': false, + 'strict': false + }; + + var escape = function(string) { + return string.replace(regexEscape, function($0) { + // Note: there is no need to check `has(escapeMap, $0)` here. + return escapeMap[$0]; + }); + }; + + /*--------------------------------------------------------------------------*/ + + var he = { + 'version': '1.1.1', + 'encode': encode, + 'decode': decode, + 'escape': escape, + 'unescape': decode + }; + + // Some AMD build optimizers, like r.js, check for specific condition patterns + // like the following: + if ( + false + ) { + define(function() { + return he; + }); + } else if (freeExports && !freeExports.nodeType) { + if (freeModule) { // in Node.js, io.js, or RingoJS v0.8.0+ + freeModule.exports = he; + } else { // in Narwhal or RingoJS v0.7.0- + for (var key in he) { + has(he, key) && (freeExports[key] = he[key]); + } + } + } else { // in Rhino or a web browser + root.he = he; + } + +}(this)); + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{}],49:[function(require,module,exports){ +exports.read = function (buffer, offset, isLE, mLen, nBytes) { + var e, m + var eLen = (nBytes * 8) - mLen - 1 + var eMax = (1 << eLen) - 1 + var eBias = eMax >> 1 + var nBits = -7 + var i = isLE ? (nBytes - 1) : 0 + var d = isLE ? -1 : 1 + var s = buffer[offset + i] + + i += d + + e = s & ((1 << (-nBits)) - 1) + s >>= (-nBits) + nBits += eLen + for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {} + + m = e & ((1 << (-nBits)) - 1) + e >>= (-nBits) + nBits += mLen + for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {} + + if (e === 0) { + e = 1 - eBias + } else if (e === eMax) { + return m ? NaN : ((s ? -1 : 1) * Infinity) + } else { + m = m + Math.pow(2, mLen) + e = e - eBias + } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen) +} + +exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { + var e, m, c + var eLen = (nBytes * 8) - mLen - 1 + var eMax = (1 << eLen) - 1 + var eBias = eMax >> 1 + var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0) + var i = isLE ? 0 : (nBytes - 1) + var d = isLE ? 1 : -1 + var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0 + + value = Math.abs(value) + + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0 + e = eMax + } else { + e = Math.floor(Math.log(value) / Math.LN2) + if (value * (c = Math.pow(2, -e)) < 1) { + e-- + c *= 2 + } + if (e + eBias >= 1) { + value += rt / c + } else { + value += rt * Math.pow(2, 1 - eBias) + } + if (value * c >= 2) { + e++ + c /= 2 + } + + if (e + eBias >= eMax) { + m = 0 + e = eMax + } else if (e + eBias >= 1) { + m = ((value * c) - 1) * Math.pow(2, mLen) + e = e + eBias + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen) + e = 0 + } + } + + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} + + e = (e << mLen) | m + eLen += mLen + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} + + buffer[offset + i - d] |= s * 128 +} + +},{}],50:[function(require,module,exports){ +if (typeof Object.create === 'function') { + // implementation from standard node.js 'util' module + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); + }; +} else { + // old school shim for old browsers + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + var TempCtor = function () {} + TempCtor.prototype = superCtor.prototype + ctor.prototype = new TempCtor() + ctor.prototype.constructor = ctor + } +} + +},{}],51:[function(require,module,exports){ +/*! + * Determine if an object is a Buffer + * + * @author Feross Aboukhadijeh + * @license MIT + */ + +// The _isBuffer check is for Safari 5-7 support, because it's missing +// Object.prototype.constructor. Remove this eventually +module.exports = function (obj) { + return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer) +} + +function isBuffer (obj) { + return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj) +} + +// For Node v0.10 support. Remove this eventually. +function isSlowBuffer (obj) { + return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0)) +} + +},{}],52:[function(require,module,exports){ +var toString = {}.toString; + +module.exports = Array.isArray || function (arr) { + return toString.call(arr) == '[object Array]'; +}; + +},{}],53:[function(require,module,exports){ +(function (process){ +var path = require('path'); +var fs = require('fs'); +var _0777 = parseInt('0777', 8); + +module.exports = mkdirP.mkdirp = mkdirP.mkdirP = mkdirP; + +function mkdirP (p, opts, f, made) { + if (typeof opts === 'function') { + f = opts; + opts = {}; + } + else if (!opts || typeof opts !== 'object') { + opts = { mode: opts }; + } + + var mode = opts.mode; + var xfs = opts.fs || fs; + + if (mode === undefined) { + mode = _0777 & (~process.umask()); + } + if (!made) made = null; + + var cb = f || function () {}; + p = path.resolve(p); + + xfs.mkdir(p, mode, function (er) { + if (!er) { + made = made || p; + return cb(null, made); + } + switch (er.code) { + case 'ENOENT': + mkdirP(path.dirname(p), opts, function (er, made) { + if (er) cb(er, made); + else mkdirP(p, opts, cb, made); + }); + break; + + // In the case of any other error, just see if there's a dir + // there already. If so, then hooray! If not, then something + // is borked. + default: + xfs.stat(p, function (er2, stat) { + // if the stat fails, then that's super weird. + // let the original error be the failure reason. + if (er2 || !stat.isDirectory()) cb(er, made) + else cb(null, made); + }); + break; + } + }); +} + +mkdirP.sync = function sync (p, opts, made) { + if (!opts || typeof opts !== 'object') { + opts = { mode: opts }; + } + + var mode = opts.mode; + var xfs = opts.fs || fs; + + if (mode === undefined) { + mode = _0777 & (~process.umask()); + } + if (!made) made = null; + + p = path.resolve(p); + + try { + xfs.mkdirSync(p, mode); + made = made || p; + } + catch (err0) { + switch (err0.code) { + case 'ENOENT' : + made = sync(path.dirname(p), opts, made); + sync(p, opts, made); + break; + + // In the case of any other error, just see if there's a dir + // there already. If so, then hooray! If not, then something + // is borked. + default: + var stat; + try { + stat = xfs.statSync(p); + } + catch (err1) { + throw err0; + } + if (!stat.isDirectory()) throw err0; + break; + } + } + + return made; +}; + +}).call(this,require('_process')) +},{"_process":56,"fs":40,"path":40}],54:[function(require,module,exports){ +/** + * Helpers. + */ + +var s = 1000; +var m = s * 60; +var h = m * 60; +var d = h * 24; +var y = d * 365.25; + +/** + * Parse or format the given `val`. + * + * Options: + * + * - `long` verbose formatting [false] + * + * @param {String|Number} val + * @param {Object} [options] + * @throws {Error} throw an error if val is not a non-empty string or a number + * @return {String|Number} + * @api public + */ + +module.exports = function(val, options) { + options = options || {}; + var type = typeof val; + if (type === 'string' && val.length > 0) { + return parse(val); + } else if (type === 'number' && isNaN(val) === false) { + return options.long ? fmtLong(val) : fmtShort(val); + } + throw new Error( + 'val is not a non-empty string or a valid number. val=' + + JSON.stringify(val) + ); +}; + +/** + * Parse the given `str` and return milliseconds. + * + * @param {String} str + * @return {Number} + * @api private + */ + +function parse(str) { + str = String(str); + if (str.length > 100) { + return; + } + var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec( + str + ); + if (!match) { + return; + } + var n = parseFloat(match[1]); + var type = (match[2] || 'ms').toLowerCase(); + switch (type) { + case 'years': + case 'year': + case 'yrs': + case 'yr': + case 'y': + return n * y; + case 'days': + case 'day': + case 'd': + return n * d; + case 'hours': + case 'hour': + case 'hrs': + case 'hr': + case 'h': + return n * h; + case 'minutes': + case 'minute': + case 'mins': + case 'min': + case 'm': + return n * m; + case 'seconds': + case 'second': + case 'secs': + case 'sec': + case 's': + return n * s; + case 'milliseconds': + case 'millisecond': + case 'msecs': + case 'msec': + case 'ms': + return n; + default: + return undefined; + } +} + +/** + * Short format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + +function fmtShort(ms) { + if (ms >= d) { + return Math.round(ms / d) + 'd'; + } + if (ms >= h) { + return Math.round(ms / h) + 'h'; + } + if (ms >= m) { + return Math.round(ms / m) + 'm'; + } + if (ms >= s) { + return Math.round(ms / s) + 's'; + } + return ms + 'ms'; +} + +/** + * Long format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + +function fmtLong(ms) { + return plural(ms, d, 'day') || + plural(ms, h, 'hour') || + plural(ms, m, 'minute') || + plural(ms, s, 'second') || + ms + ' ms'; +} + +/** + * Pluralization helper. + */ + +function plural(ms, n, name) { + if (ms < n) { + return; + } + if (ms < n * 1.5) { + return Math.floor(ms / n) + ' ' + name; + } + return Math.ceil(ms / n) + ' ' + name + 's'; +} + +},{}],55:[function(require,module,exports){ +(function (process){ +'use strict'; + +if (!process.version || + process.version.indexOf('v0.') === 0 || + process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) { + module.exports = { nextTick: nextTick }; +} else { + module.exports = process +} + +function nextTick(fn, arg1, arg2, arg3) { + if (typeof fn !== 'function') { + throw new TypeError('"callback" argument must be a function'); + } + var len = arguments.length; + var args, i; + switch (len) { + case 0: + case 1: + return process.nextTick(fn); + case 2: + return process.nextTick(function afterTickOne() { + fn.call(null, arg1); + }); + case 3: + return process.nextTick(function afterTickTwo() { + fn.call(null, arg1, arg2); + }); + case 4: + return process.nextTick(function afterTickThree() { + fn.call(null, arg1, arg2, arg3); + }); + default: + args = new Array(len - 1); + i = 0; + while (i < args.length) { + args[i++] = arguments[i]; + } + return process.nextTick(function afterTick() { + fn.apply(null, args); + }); + } +} + + +}).call(this,require('_process')) +},{"_process":56}],56:[function(require,module,exports){ +// shim for using process in browser +var process = module.exports = {}; + +// cached from whatever global is present so that test runners that stub it +// don't break things. But we need to wrap it in a try catch in case it is +// wrapped in strict mode code which doesn't define any globals. It's inside a +// function because try/catches deoptimize in certain engines. + +var cachedSetTimeout; +var cachedClearTimeout; + +function defaultSetTimout() { + throw new Error('setTimeout has not been defined'); +} +function defaultClearTimeout () { + throw new Error('clearTimeout has not been defined'); +} +(function () { + try { + if (typeof setTimeout === 'function') { + cachedSetTimeout = setTimeout; + } else { + cachedSetTimeout = defaultSetTimout; + } + } catch (e) { + cachedSetTimeout = defaultSetTimout; + } + try { + if (typeof clearTimeout === 'function') { + cachedClearTimeout = clearTimeout; + } else { + cachedClearTimeout = defaultClearTimeout; + } + } catch (e) { + cachedClearTimeout = defaultClearTimeout; + } +} ()) +function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0); + } + // if setTimeout wasn't available but was latter defined + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout(fun, 0); + } catch(e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout.call(null, fun, 0); + } catch(e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error + return cachedSetTimeout.call(this, fun, 0); + } + } + + +} +function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker); + } + // if clearTimeout wasn't available but was latter defined + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout(marker); + } catch (e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedClearTimeout.call(null, marker); + } catch (e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout.call(this, marker); + } + } + + + +} +var queue = []; +var draining = false; +var currentQueue; +var queueIndex = -1; + +function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); + } +} + +function drainQueue() { + if (draining) { + return; + } + var timeout = runTimeout(cleanUpNextTick); + draining = true; + + var len = queue.length; + while(len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); + } + } + queueIndex = -1; + len = queue.length; + } + currentQueue = null; + draining = false; + runClearTimeout(timeout); +} + +process.nextTick = function (fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + } + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } +}; + +// v8 likes predictible objects +function Item(fun, array) { + this.fun = fun; + this.array = array; +} +Item.prototype.run = function () { + this.fun.apply(null, this.array); +}; +process.title = 'browser'; +process.browser = true; +process.env = {}; +process.argv = []; +process.version = ''; // empty string to avoid regexp issues +process.versions = {}; + +function noop() {} + +process.on = noop; +process.addListener = noop; +process.once = noop; +process.off = noop; +process.removeListener = noop; +process.removeAllListeners = noop; +process.emit = noop; +process.prependListener = noop; +process.prependOnceListener = noop; + +process.listeners = function (name) { return [] } + +process.binding = function (name) { + throw new Error('process.binding is not supported'); +}; + +process.cwd = function () { return '/' }; +process.chdir = function (dir) { + throw new Error('process.chdir is not supported'); +}; +process.umask = function() { return 0; }; + +},{}],57:[function(require,module,exports){ +module.exports = require('./lib/_stream_duplex.js'); + +},{"./lib/_stream_duplex.js":58}],58:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// a duplex stream is just a stream that is both readable and writable. +// Since JS doesn't have multiple prototypal inheritance, this class +// prototypally inherits from Readable, and then parasitically from +// Writable. + +'use strict'; + +/**/ + +var pna = require('process-nextick-args'); +/**/ + +/**/ +var objectKeys = Object.keys || function (obj) { + var keys = []; + for (var key in obj) { + keys.push(key); + }return keys; +}; +/**/ + +module.exports = Duplex; + +/**/ +var util = require('core-util-is'); +util.inherits = require('inherits'); +/**/ + +var Readable = require('./_stream_readable'); +var Writable = require('./_stream_writable'); + +util.inherits(Duplex, Readable); + +{ + // avoid scope creep, the keys array can then be collected + var keys = objectKeys(Writable.prototype); + for (var v = 0; v < keys.length; v++) { + var method = keys[v]; + if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; + } +} + +function Duplex(options) { + if (!(this instanceof Duplex)) return new Duplex(options); + + Readable.call(this, options); + Writable.call(this, options); + + if (options && options.readable === false) this.readable = false; + + if (options && options.writable === false) this.writable = false; + + this.allowHalfOpen = true; + if (options && options.allowHalfOpen === false) this.allowHalfOpen = false; + + this.once('end', onend); +} + +Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function () { + return this._writableState.highWaterMark; + } +}); + +// the no-half-open enforcer +function onend() { + // if we allow half-open state, or if the writable side ended, + // then we're ok. + if (this.allowHalfOpen || this._writableState.ended) return; + + // no more data can be written. + // But allow more writes to happen in this tick. + pna.nextTick(onEndNT, this); +} + +function onEndNT(self) { + self.end(); +} + +Object.defineProperty(Duplex.prototype, 'destroyed', { + get: function () { + if (this._readableState === undefined || this._writableState === undefined) { + return false; + } + return this._readableState.destroyed && this._writableState.destroyed; + }, + set: function (value) { + // we ignore the value if the stream + // has not been initialized yet + if (this._readableState === undefined || this._writableState === undefined) { + return; + } + + // backward compatibility, the user is explicitly + // managing destroyed + this._readableState.destroyed = value; + this._writableState.destroyed = value; + } +}); + +Duplex.prototype._destroy = function (err, cb) { + this.push(null); + this.end(); + + pna.nextTick(cb, err); +}; +},{"./_stream_readable":60,"./_stream_writable":62,"core-util-is":42,"inherits":50,"process-nextick-args":55}],59:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// a passthrough stream. +// basically just the most minimal sort of Transform stream. +// Every written chunk gets output as-is. + +'use strict'; + +module.exports = PassThrough; + +var Transform = require('./_stream_transform'); + +/**/ +var util = require('core-util-is'); +util.inherits = require('inherits'); +/**/ + +util.inherits(PassThrough, Transform); + +function PassThrough(options) { + if (!(this instanceof PassThrough)) return new PassThrough(options); + + Transform.call(this, options); +} + +PassThrough.prototype._transform = function (chunk, encoding, cb) { + cb(null, chunk); +}; +},{"./_stream_transform":61,"core-util-is":42,"inherits":50}],60:[function(require,module,exports){ +(function (process,global){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +'use strict'; + +/**/ + +var pna = require('process-nextick-args'); +/**/ + +module.exports = Readable; + +/**/ +var isArray = require('isarray'); +/**/ + +/**/ +var Duplex; +/**/ + +Readable.ReadableState = ReadableState; + +/**/ +var EE = require('events').EventEmitter; + +var EElistenerCount = function (emitter, type) { + return emitter.listeners(type).length; +}; +/**/ + +/**/ +var Stream = require('./internal/streams/stream'); +/**/ + +/**/ + +var Buffer = require('safe-buffer').Buffer; +var OurUint8Array = global.Uint8Array || function () {}; +function _uint8ArrayToBuffer(chunk) { + return Buffer.from(chunk); +} +function _isUint8Array(obj) { + return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; +} + +/**/ + +/**/ +var util = require('core-util-is'); +util.inherits = require('inherits'); +/**/ + +/**/ +var debugUtil = require('util'); +var debug = void 0; +if (debugUtil && debugUtil.debuglog) { + debug = debugUtil.debuglog('stream'); +} else { + debug = function () {}; +} +/**/ + +var BufferList = require('./internal/streams/BufferList'); +var destroyImpl = require('./internal/streams/destroy'); +var StringDecoder; + +util.inherits(Readable, Stream); + +var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; + +function prependListener(emitter, event, fn) { + // Sadly this is not cacheable as some libraries bundle their own + // event emitter implementation with them. + if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); + + // This is a hack to make sure that our error handler is attached before any + // userland ones. NEVER DO THIS. This is here only because this code needs + // to continue to work with older versions of Node.js that do not include + // the prependListener() method. The goal is to eventually remove this hack. + if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; +} + +function ReadableState(options, stream) { + Duplex = Duplex || require('./_stream_duplex'); + + options = options || {}; + + // Duplex streams are both readable and writable, but share + // the same options object. + // However, some cases require setting options to different + // values for the readable and the writable sides of the duplex stream. + // These options can be provided separately as readableXXX and writableXXX. + var isDuplex = stream instanceof Duplex; + + // object stream flag. Used to make read(n) ignore n and to + // make all the buffer merging and length checks go away + this.objectMode = !!options.objectMode; + + if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; + + // the point at which it stops calling _read() to fill the buffer + // Note: 0 is a valid value, means "don't call _read preemptively ever" + var hwm = options.highWaterMark; + var readableHwm = options.readableHighWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + + if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (readableHwm || readableHwm === 0)) this.highWaterMark = readableHwm;else this.highWaterMark = defaultHwm; + + // cast to ints. + this.highWaterMark = Math.floor(this.highWaterMark); + + // A linked list is used to store data chunks instead of an array because the + // linked list can remove elements from the beginning faster than + // array.shift() + this.buffer = new BufferList(); + this.length = 0; + this.pipes = null; + this.pipesCount = 0; + this.flowing = null; + this.ended = false; + this.endEmitted = false; + this.reading = false; + + // a flag to be able to tell if the event 'readable'/'data' is emitted + // immediately, or on a later tick. We set this to true at first, because + // any actions that shouldn't happen until "later" should generally also + // not happen before the first read call. + this.sync = true; + + // whenever we return null, then we set a flag to say + // that we're awaiting a 'readable' event emission. + this.needReadable = false; + this.emittedReadable = false; + this.readableListening = false; + this.resumeScheduled = false; + + // has it been destroyed + this.destroyed = false; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // the number of writers that are awaiting a drain event in .pipe()s + this.awaitDrain = 0; + + // if true, a maybeReadMore has been scheduled + this.readingMore = false; + + this.decoder = null; + this.encoding = null; + if (options.encoding) { + if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; + this.decoder = new StringDecoder(options.encoding); + this.encoding = options.encoding; + } +} + +function Readable(options) { + Duplex = Duplex || require('./_stream_duplex'); + + if (!(this instanceof Readable)) return new Readable(options); + + this._readableState = new ReadableState(options, this); + + // legacy + this.readable = true; + + if (options) { + if (typeof options.read === 'function') this._read = options.read; + + if (typeof options.destroy === 'function') this._destroy = options.destroy; + } + + Stream.call(this); +} + +Object.defineProperty(Readable.prototype, 'destroyed', { + get: function () { + if (this._readableState === undefined) { + return false; + } + return this._readableState.destroyed; + }, + set: function (value) { + // we ignore the value if the stream + // has not been initialized yet + if (!this._readableState) { + return; + } + + // backward compatibility, the user is explicitly + // managing destroyed + this._readableState.destroyed = value; + } +}); + +Readable.prototype.destroy = destroyImpl.destroy; +Readable.prototype._undestroy = destroyImpl.undestroy; +Readable.prototype._destroy = function (err, cb) { + this.push(null); + cb(err); +}; + +// Manually shove something into the read() buffer. +// This returns true if the highWaterMark has not been hit yet, +// similar to how Writable.write() returns true if you should +// write() some more. +Readable.prototype.push = function (chunk, encoding) { + var state = this._readableState; + var skipChunkCheck; + + if (!state.objectMode) { + if (typeof chunk === 'string') { + encoding = encoding || state.defaultEncoding; + if (encoding !== state.encoding) { + chunk = Buffer.from(chunk, encoding); + encoding = ''; + } + skipChunkCheck = true; + } + } else { + skipChunkCheck = true; + } + + return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); +}; + +// Unshift should *always* be something directly out of read() +Readable.prototype.unshift = function (chunk) { + return readableAddChunk(this, chunk, null, true, false); +}; + +function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { + var state = stream._readableState; + if (chunk === null) { + state.reading = false; + onEofChunk(stream, state); + } else { + var er; + if (!skipChunkCheck) er = chunkInvalid(state, chunk); + if (er) { + stream.emit('error', er); + } else if (state.objectMode || chunk && chunk.length > 0) { + if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) { + chunk = _uint8ArrayToBuffer(chunk); + } + + if (addToFront) { + if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true); + } else if (state.ended) { + stream.emit('error', new Error('stream.push() after EOF')); + } else { + state.reading = false; + if (state.decoder && !encoding) { + chunk = state.decoder.write(chunk); + if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state); + } else { + addChunk(stream, state, chunk, false); + } + } + } else if (!addToFront) { + state.reading = false; + } + } + + return needMoreData(state); +} + +function addChunk(stream, state, chunk, addToFront) { + if (state.flowing && state.length === 0 && !state.sync) { + stream.emit('data', chunk); + stream.read(0); + } else { + // update the buffer info. + state.length += state.objectMode ? 1 : chunk.length; + if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); + + if (state.needReadable) emitReadable(stream); + } + maybeReadMore(stream, state); +} + +function chunkInvalid(state, chunk) { + var er; + if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + return er; +} + +// if it's past the high water mark, we can push in some more. +// Also, if we have no data yet, we can stand some +// more bytes. This is to work around cases where hwm=0, +// such as the repl. Also, if the push() triggered a +// readable event, and the user called read(largeNumber) such that +// needReadable was set, then we ought to push more, so that another +// 'readable' event will be triggered. +function needMoreData(state) { + return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0); +} + +Readable.prototype.isPaused = function () { + return this._readableState.flowing === false; +}; + +// backwards compatibility. +Readable.prototype.setEncoding = function (enc) { + if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; + this._readableState.decoder = new StringDecoder(enc); + this._readableState.encoding = enc; + return this; +}; + +// Don't raise the hwm > 8MB +var MAX_HWM = 0x800000; +function computeNewHighWaterMark(n) { + if (n >= MAX_HWM) { + n = MAX_HWM; + } else { + // Get the next highest power of 2 to prevent increasing hwm excessively in + // tiny amounts + n--; + n |= n >>> 1; + n |= n >>> 2; + n |= n >>> 4; + n |= n >>> 8; + n |= n >>> 16; + n++; + } + return n; +} + +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function howMuchToRead(n, state) { + if (n <= 0 || state.length === 0 && state.ended) return 0; + if (state.objectMode) return 1; + if (n !== n) { + // Only flow one buffer at a time + if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; + } + // If we're asking for more than the current hwm, then raise the hwm. + if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); + if (n <= state.length) return n; + // Don't have enough + if (!state.ended) { + state.needReadable = true; + return 0; + } + return state.length; +} + +// you can override either this method, or the async _read(n) below. +Readable.prototype.read = function (n) { + debug('read', n); + n = parseInt(n, 10); + var state = this._readableState; + var nOrig = n; + + if (n !== 0) state.emittedReadable = false; + + // if we're doing read(0) to trigger a readable event, but we + // already have a bunch of data in the buffer, then just trigger + // the 'readable' event and move on. + if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) { + debug('read: emitReadable', state.length, state.ended); + if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); + return null; + } + + n = howMuchToRead(n, state); + + // if we've ended, and we're now clear, then finish it up. + if (n === 0 && state.ended) { + if (state.length === 0) endReadable(this); + return null; + } + + // All the actual chunk generation logic needs to be + // *below* the call to _read. The reason is that in certain + // synthetic stream cases, such as passthrough streams, _read + // may be a completely synchronous operation which may change + // the state of the read buffer, providing enough data when + // before there was *not* enough. + // + // So, the steps are: + // 1. Figure out what the state of things will be after we do + // a read from the buffer. + // + // 2. If that resulting state will trigger a _read, then call _read. + // Note that this may be asynchronous, or synchronous. Yes, it is + // deeply ugly to write APIs this way, but that still doesn't mean + // that the Readable class should behave improperly, as streams are + // designed to be sync/async agnostic. + // Take note if the _read call is sync or async (ie, if the read call + // has returned yet), so that we know whether or not it's safe to emit + // 'readable' etc. + // + // 3. Actually pull the requested chunks out of the buffer and return. + + // if we need a readable event, then we need to do some reading. + var doRead = state.needReadable; + debug('need readable', doRead); + + // if we currently have less than the highWaterMark, then also read some + if (state.length === 0 || state.length - n < state.highWaterMark) { + doRead = true; + debug('length less than watermark', doRead); + } + + // however, if we've ended, then there's no point, and if we're already + // reading, then it's unnecessary. + if (state.ended || state.reading) { + doRead = false; + debug('reading or ended', doRead); + } else if (doRead) { + debug('do read'); + state.reading = true; + state.sync = true; + // if the length is currently zero, then we *need* a readable event. + if (state.length === 0) state.needReadable = true; + // call internal read method + this._read(state.highWaterMark); + state.sync = false; + // If _read pushed data synchronously, then `reading` will be false, + // and we need to re-evaluate how much data we can return to the user. + if (!state.reading) n = howMuchToRead(nOrig, state); + } + + var ret; + if (n > 0) ret = fromList(n, state);else ret = null; + + if (ret === null) { + state.needReadable = true; + n = 0; + } else { + state.length -= n; + } + + if (state.length === 0) { + // If we have nothing in the buffer, then we want to know + // as soon as we *do* get something into the buffer. + if (!state.ended) state.needReadable = true; + + // If we tried to read() past the EOF, then emit end on the next tick. + if (nOrig !== n && state.ended) endReadable(this); + } + + if (ret !== null) this.emit('data', ret); + + return ret; +}; + +function onEofChunk(stream, state) { + if (state.ended) return; + if (state.decoder) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) { + state.buffer.push(chunk); + state.length += state.objectMode ? 1 : chunk.length; + } + } + state.ended = true; + + // emit 'readable' now to make sure it gets picked up. + emitReadable(stream); +} + +// Don't emit readable right away in sync mode, because this can trigger +// another read() call => stack overflow. This way, it might trigger +// a nextTick recursion warning, but that's not so bad. +function emitReadable(stream) { + var state = stream._readableState; + state.needReadable = false; + if (!state.emittedReadable) { + debug('emitReadable', state.flowing); + state.emittedReadable = true; + if (state.sync) pna.nextTick(emitReadable_, stream);else emitReadable_(stream); + } +} + +function emitReadable_(stream) { + debug('emit readable'); + stream.emit('readable'); + flow(stream); +} + +// at this point, the user has presumably seen the 'readable' event, +// and called read() to consume some data. that may have triggered +// in turn another _read(n) call, in which case reading = true if +// it's in progress. +// However, if we're not ended, or reading, and the length < hwm, +// then go ahead and try to read some more preemptively. +function maybeReadMore(stream, state) { + if (!state.readingMore) { + state.readingMore = true; + pna.nextTick(maybeReadMore_, stream, state); + } +} + +function maybeReadMore_(stream, state) { + var len = state.length; + while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) { + debug('maybeReadMore read 0'); + stream.read(0); + if (len === state.length) + // didn't get any data, stop spinning. + break;else len = state.length; + } + state.readingMore = false; +} + +// abstract method. to be overridden in specific implementation classes. +// call cb(er, data) where data is <= n in length. +// for virtual (non-string, non-buffer) streams, "length" is somewhat +// arbitrary, and perhaps not very meaningful. +Readable.prototype._read = function (n) { + this.emit('error', new Error('_read() is not implemented')); +}; + +Readable.prototype.pipe = function (dest, pipeOpts) { + var src = this; + var state = this._readableState; + + switch (state.pipesCount) { + case 0: + state.pipes = dest; + break; + case 1: + state.pipes = [state.pipes, dest]; + break; + default: + state.pipes.push(dest); + break; + } + state.pipesCount += 1; + debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); + + var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; + + var endFn = doEnd ? onend : unpipe; + if (state.endEmitted) pna.nextTick(endFn);else src.once('end', endFn); + + dest.on('unpipe', onunpipe); + function onunpipe(readable, unpipeInfo) { + debug('onunpipe'); + if (readable === src) { + if (unpipeInfo && unpipeInfo.hasUnpiped === false) { + unpipeInfo.hasUnpiped = true; + cleanup(); + } + } + } + + function onend() { + debug('onend'); + dest.end(); + } + + // when the dest drains, it reduces the awaitDrain counter + // on the source. This would be more elegant with a .once() + // handler in flow(), but adding and removing repeatedly is + // too slow. + var ondrain = pipeOnDrain(src); + dest.on('drain', ondrain); + + var cleanedUp = false; + function cleanup() { + debug('cleanup'); + // cleanup event handlers once the pipe is broken + dest.removeListener('close', onclose); + dest.removeListener('finish', onfinish); + dest.removeListener('drain', ondrain); + dest.removeListener('error', onerror); + dest.removeListener('unpipe', onunpipe); + src.removeListener('end', onend); + src.removeListener('end', unpipe); + src.removeListener('data', ondata); + + cleanedUp = true; + + // if the reader is waiting for a drain event from this + // specific writer, then it would cause it to never start + // flowing again. + // So, if this is awaiting a drain, then we just call it now. + // If we don't know, then assume that we are waiting for one. + if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); + } + + // If the user pushes more data while we're writing to dest then we'll end up + // in ondata again. However, we only want to increase awaitDrain once because + // dest will only emit one 'drain' event for the multiple writes. + // => Introduce a guard on increasing awaitDrain. + var increasedAwaitDrain = false; + src.on('data', ondata); + function ondata(chunk) { + debug('ondata'); + increasedAwaitDrain = false; + var ret = dest.write(chunk); + if (false === ret && !increasedAwaitDrain) { + // If the user unpiped during `dest.write()`, it is possible + // to get stuck in a permanently paused state if that write + // also returned false. + // => Check whether `dest` is still a piping destination. + if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { + debug('false write response, pause', src._readableState.awaitDrain); + src._readableState.awaitDrain++; + increasedAwaitDrain = true; + } + src.pause(); + } + } + + // if the dest has an error, then stop piping into it. + // however, don't suppress the throwing behavior for this. + function onerror(er) { + debug('onerror', er); + unpipe(); + dest.removeListener('error', onerror); + if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er); + } + + // Make sure our error handler is attached before userland ones. + prependListener(dest, 'error', onerror); + + // Both close and finish should trigger unpipe, but only once. + function onclose() { + dest.removeListener('finish', onfinish); + unpipe(); + } + dest.once('close', onclose); + function onfinish() { + debug('onfinish'); + dest.removeListener('close', onclose); + unpipe(); + } + dest.once('finish', onfinish); + + function unpipe() { + debug('unpipe'); + src.unpipe(dest); + } + + // tell the dest that it's being piped to + dest.emit('pipe', src); + + // start the flow if it hasn't been started already. + if (!state.flowing) { + debug('pipe resume'); + src.resume(); + } + + return dest; +}; + +function pipeOnDrain(src) { + return function () { + var state = src._readableState; + debug('pipeOnDrain', state.awaitDrain); + if (state.awaitDrain) state.awaitDrain--; + if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { + state.flowing = true; + flow(src); + } + }; +} + +Readable.prototype.unpipe = function (dest) { + var state = this._readableState; + var unpipeInfo = { hasUnpiped: false }; + + // if we're not piping anywhere, then do nothing. + if (state.pipesCount === 0) return this; + + // just one destination. most common case. + if (state.pipesCount === 1) { + // passed in one, but it's not the right one. + if (dest && dest !== state.pipes) return this; + + if (!dest) dest = state.pipes; + + // got a match. + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + if (dest) dest.emit('unpipe', this, unpipeInfo); + return this; + } + + // slow case. multiple pipe destinations. + + if (!dest) { + // remove all. + var dests = state.pipes; + var len = state.pipesCount; + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + + for (var i = 0; i < len; i++) { + dests[i].emit('unpipe', this, unpipeInfo); + }return this; + } + + // try to find the right one. + var index = indexOf(state.pipes, dest); + if (index === -1) return this; + + state.pipes.splice(index, 1); + state.pipesCount -= 1; + if (state.pipesCount === 1) state.pipes = state.pipes[0]; + + dest.emit('unpipe', this, unpipeInfo); + + return this; +}; + +// set up data events if they are asked for +// Ensure readable listeners eventually get something +Readable.prototype.on = function (ev, fn) { + var res = Stream.prototype.on.call(this, ev, fn); + + if (ev === 'data') { + // Start flowing on next tick if stream isn't explicitly paused + if (this._readableState.flowing !== false) this.resume(); + } else if (ev === 'readable') { + var state = this._readableState; + if (!state.endEmitted && !state.readableListening) { + state.readableListening = state.needReadable = true; + state.emittedReadable = false; + if (!state.reading) { + pna.nextTick(nReadingNextTick, this); + } else if (state.length) { + emitReadable(this); + } + } + } + + return res; +}; +Readable.prototype.addListener = Readable.prototype.on; + +function nReadingNextTick(self) { + debug('readable nexttick read 0'); + self.read(0); +} + +// pause() and resume() are remnants of the legacy readable stream API +// If the user uses them, then switch into old mode. +Readable.prototype.resume = function () { + var state = this._readableState; + if (!state.flowing) { + debug('resume'); + state.flowing = true; + resume(this, state); + } + return this; +}; + +function resume(stream, state) { + if (!state.resumeScheduled) { + state.resumeScheduled = true; + pna.nextTick(resume_, stream, state); + } +} + +function resume_(stream, state) { + if (!state.reading) { + debug('resume read 0'); + stream.read(0); + } + + state.resumeScheduled = false; + state.awaitDrain = 0; + stream.emit('resume'); + flow(stream); + if (state.flowing && !state.reading) stream.read(0); +} + +Readable.prototype.pause = function () { + debug('call pause flowing=%j', this._readableState.flowing); + if (false !== this._readableState.flowing) { + debug('pause'); + this._readableState.flowing = false; + this.emit('pause'); + } + return this; +}; + +function flow(stream) { + var state = stream._readableState; + debug('flow', state.flowing); + while (state.flowing && stream.read() !== null) {} +} + +// wrap an old-style stream as the async data source. +// This is *not* part of the readable stream interface. +// It is an ugly unfortunate mess of history. +Readable.prototype.wrap = function (stream) { + var _this = this; + + var state = this._readableState; + var paused = false; + + stream.on('end', function () { + debug('wrapped end'); + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) _this.push(chunk); + } + + _this.push(null); + }); + + stream.on('data', function (chunk) { + debug('wrapped data'); + if (state.decoder) chunk = state.decoder.write(chunk); + + // don't skip over falsy values in objectMode + if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; + + var ret = _this.push(chunk); + if (!ret) { + paused = true; + stream.pause(); + } + }); + + // proxy all the other methods. + // important when wrapping filters and duplexes. + for (var i in stream) { + if (this[i] === undefined && typeof stream[i] === 'function') { + this[i] = function (method) { + return function () { + return stream[method].apply(stream, arguments); + }; + }(i); + } + } + + // proxy certain important events. + for (var n = 0; n < kProxyEvents.length; n++) { + stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n])); + } + + // when we try to consume some more bytes, simply unpause the + // underlying stream. + this._read = function (n) { + debug('wrapped _read', n); + if (paused) { + paused = false; + stream.resume(); + } + }; + + return this; +}; + +Object.defineProperty(Readable.prototype, 'readableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function () { + return this._readableState.highWaterMark; + } +}); + +// exposed for testing purposes only. +Readable._fromList = fromList; + +// Pluck off n bytes from an array of buffers. +// Length is the combined lengths of all the buffers in the list. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function fromList(n, state) { + // nothing buffered + if (state.length === 0) return null; + + var ret; + if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { + // read it all, truncate the list + if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length); + state.buffer.clear(); + } else { + // read part of list + ret = fromListPartial(n, state.buffer, state.decoder); + } + + return ret; +} + +// Extracts only enough buffered data to satisfy the amount requested. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function fromListPartial(n, list, hasStrings) { + var ret; + if (n < list.head.data.length) { + // slice is the same for buffers and strings + ret = list.head.data.slice(0, n); + list.head.data = list.head.data.slice(n); + } else if (n === list.head.data.length) { + // first chunk is a perfect match + ret = list.shift(); + } else { + // result spans more than one buffer + ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list); + } + return ret; +} + +// Copies a specified amount of characters from the list of buffered data +// chunks. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function copyFromBufferString(n, list) { + var p = list.head; + var c = 1; + var ret = p.data; + n -= ret.length; + while (p = p.next) { + var str = p.data; + var nb = n > str.length ? str.length : n; + if (nb === str.length) ret += str;else ret += str.slice(0, n); + n -= nb; + if (n === 0) { + if (nb === str.length) { + ++c; + if (p.next) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = str.slice(nb); + } + break; + } + ++c; + } + list.length -= c; + return ret; +} + +// Copies a specified amount of bytes from the list of buffered data chunks. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function copyFromBuffer(n, list) { + var ret = Buffer.allocUnsafe(n); + var p = list.head; + var c = 1; + p.data.copy(ret); + n -= p.data.length; + while (p = p.next) { + var buf = p.data; + var nb = n > buf.length ? buf.length : n; + buf.copy(ret, ret.length - n, 0, nb); + n -= nb; + if (n === 0) { + if (nb === buf.length) { + ++c; + if (p.next) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = buf.slice(nb); + } + break; + } + ++c; + } + list.length -= c; + return ret; +} + +function endReadable(stream) { + var state = stream._readableState; + + // If we get here before consuming all the bytes, then that is a + // bug in node. Should never happen. + if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream'); + + if (!state.endEmitted) { + state.ended = true; + pna.nextTick(endReadableNT, state, stream); + } +} + +function endReadableNT(state, stream) { + // Check that we didn't get one last unshift. + if (!state.endEmitted && state.length === 0) { + state.endEmitted = true; + stream.readable = false; + stream.emit('end'); + } +} + +function indexOf(xs, x) { + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) return i; + } + return -1; +} +}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"./_stream_duplex":58,"./internal/streams/BufferList":63,"./internal/streams/destroy":64,"./internal/streams/stream":65,"_process":56,"core-util-is":42,"events":47,"inherits":50,"isarray":52,"process-nextick-args":55,"safe-buffer":70,"string_decoder/":72,"util":38}],61:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// a transform stream is a readable/writable stream where you do +// something with the data. Sometimes it's called a "filter", +// but that's not a great name for it, since that implies a thing where +// some bits pass through, and others are simply ignored. (That would +// be a valid example of a transform, of course.) +// +// While the output is causally related to the input, it's not a +// necessarily symmetric or synchronous transformation. For example, +// a zlib stream might take multiple plain-text writes(), and then +// emit a single compressed chunk some time in the future. +// +// Here's how this works: +// +// The Transform stream has all the aspects of the readable and writable +// stream classes. When you write(chunk), that calls _write(chunk,cb) +// internally, and returns false if there's a lot of pending writes +// buffered up. When you call read(), that calls _read(n) until +// there's enough pending readable data buffered up. +// +// In a transform stream, the written data is placed in a buffer. When +// _read(n) is called, it transforms the queued up data, calling the +// buffered _write cb's as it consumes chunks. If consuming a single +// written chunk would result in multiple output chunks, then the first +// outputted bit calls the readcb, and subsequent chunks just go into +// the read buffer, and will cause it to emit 'readable' if necessary. +// +// This way, back-pressure is actually determined by the reading side, +// since _read has to be called to start processing a new chunk. However, +// a pathological inflate type of transform can cause excessive buffering +// here. For example, imagine a stream where every byte of input is +// interpreted as an integer from 0-255, and then results in that many +// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in +// 1kb of data being output. In this case, you could write a very small +// amount of input, and end up with a very large amount of output. In +// such a pathological inflating mechanism, there'd be no way to tell +// the system to stop doing the transform. A single 4MB write could +// cause the system to run out of memory. +// +// However, even in such a pathological case, only a single written chunk +// would be consumed, and then the rest would wait (un-transformed) until +// the results of the previous transformed chunk were consumed. + +'use strict'; + +module.exports = Transform; + +var Duplex = require('./_stream_duplex'); + +/**/ +var util = require('core-util-is'); +util.inherits = require('inherits'); +/**/ + +util.inherits(Transform, Duplex); + +function afterTransform(er, data) { + var ts = this._transformState; + ts.transforming = false; + + var cb = ts.writecb; + + if (!cb) { + return this.emit('error', new Error('write callback called multiple times')); + } + + ts.writechunk = null; + ts.writecb = null; + + if (data != null) // single equals check for both `null` and `undefined` + this.push(data); + + cb(er); + + var rs = this._readableState; + rs.reading = false; + if (rs.needReadable || rs.length < rs.highWaterMark) { + this._read(rs.highWaterMark); + } +} + +function Transform(options) { + if (!(this instanceof Transform)) return new Transform(options); + + Duplex.call(this, options); + + this._transformState = { + afterTransform: afterTransform.bind(this), + needTransform: false, + transforming: false, + writecb: null, + writechunk: null, + writeencoding: null + }; + + // start out asking for a readable event once data is transformed. + this._readableState.needReadable = true; + + // we have implemented the _read method, and done the other things + // that Readable wants before the first _read call, so unset the + // sync guard flag. + this._readableState.sync = false; + + if (options) { + if (typeof options.transform === 'function') this._transform = options.transform; + + if (typeof options.flush === 'function') this._flush = options.flush; + } + + // When the writable side finishes, then flush out anything remaining. + this.on('prefinish', prefinish); +} + +function prefinish() { + var _this = this; + + if (typeof this._flush === 'function') { + this._flush(function (er, data) { + done(_this, er, data); + }); + } else { + done(this, null, null); + } +} + +Transform.prototype.push = function (chunk, encoding) { + this._transformState.needTransform = false; + return Duplex.prototype.push.call(this, chunk, encoding); +}; + +// This is the part where you do stuff! +// override this function in implementation classes. +// 'chunk' is an input chunk. +// +// Call `push(newChunk)` to pass along transformed output +// to the readable side. You may call 'push' zero or more times. +// +// Call `cb(err)` when you are done with this chunk. If you pass +// an error, then that'll put the hurt on the whole operation. If you +// never call cb(), then you'll never get another chunk. +Transform.prototype._transform = function (chunk, encoding, cb) { + throw new Error('_transform() is not implemented'); +}; + +Transform.prototype._write = function (chunk, encoding, cb) { + var ts = this._transformState; + ts.writecb = cb; + ts.writechunk = chunk; + ts.writeencoding = encoding; + if (!ts.transforming) { + var rs = this._readableState; + if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); + } +}; + +// Doesn't matter what the args are here. +// _transform does all the work. +// That we got here means that the readable side wants more data. +Transform.prototype._read = function (n) { + var ts = this._transformState; + + if (ts.writechunk !== null && ts.writecb && !ts.transforming) { + ts.transforming = true; + this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); + } else { + // mark that we need a transform, so that any data that comes in + // will get processed, now that we've asked for it. + ts.needTransform = true; + } +}; + +Transform.prototype._destroy = function (err, cb) { + var _this2 = this; + + Duplex.prototype._destroy.call(this, err, function (err2) { + cb(err2); + _this2.emit('close'); + }); +}; + +function done(stream, er, data) { + if (er) return stream.emit('error', er); + + if (data != null) // single equals check for both `null` and `undefined` + stream.push(data); + + // if there's nothing in the write buffer, then that means + // that nothing more will ever be provided + if (stream._writableState.length) throw new Error('Calling transform done when ws.length != 0'); + + if (stream._transformState.transforming) throw new Error('Calling transform done when still transforming'); + + return stream.push(null); +} +},{"./_stream_duplex":58,"core-util-is":42,"inherits":50}],62:[function(require,module,exports){ +(function (process,global){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// A bit simpler than readable streams. +// Implement an async ._write(chunk, encoding, cb), and it'll handle all +// the drain event emission and buffering. + +'use strict'; + +/**/ + +var pna = require('process-nextick-args'); +/**/ + +module.exports = Writable; + +/* */ +function WriteReq(chunk, encoding, cb) { + this.chunk = chunk; + this.encoding = encoding; + this.callback = cb; + this.next = null; +} + +// It seems a linked list but it is not +// there will be only 2 of these for each stream +function CorkedRequest(state) { + var _this = this; + + this.next = null; + this.entry = null; + this.finish = function () { + onCorkedFinish(_this, state); + }; +} +/* */ + +/**/ +var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : pna.nextTick; +/**/ + +/**/ +var Duplex; +/**/ + +Writable.WritableState = WritableState; + +/**/ +var util = require('core-util-is'); +util.inherits = require('inherits'); +/**/ + +/**/ +var internalUtil = { + deprecate: require('util-deprecate') +}; +/**/ + +/**/ +var Stream = require('./internal/streams/stream'); +/**/ + +/**/ + +var Buffer = require('safe-buffer').Buffer; +var OurUint8Array = global.Uint8Array || function () {}; +function _uint8ArrayToBuffer(chunk) { + return Buffer.from(chunk); +} +function _isUint8Array(obj) { + return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; +} + +/**/ + +var destroyImpl = require('./internal/streams/destroy'); + +util.inherits(Writable, Stream); + +function nop() {} + +function WritableState(options, stream) { + Duplex = Duplex || require('./_stream_duplex'); + + options = options || {}; + + // Duplex streams are both readable and writable, but share + // the same options object. + // However, some cases require setting options to different + // values for the readable and the writable sides of the duplex stream. + // These options can be provided separately as readableXXX and writableXXX. + var isDuplex = stream instanceof Duplex; + + // object stream flag to indicate whether or not this stream + // contains buffers or objects. + this.objectMode = !!options.objectMode; + + if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; + + // the point at which write() starts returning false + // Note: 0 is a valid value, means that we always return false if + // the entire buffer is not flushed immediately on write() + var hwm = options.highWaterMark; + var writableHwm = options.writableHighWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + + if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (writableHwm || writableHwm === 0)) this.highWaterMark = writableHwm;else this.highWaterMark = defaultHwm; + + // cast to ints. + this.highWaterMark = Math.floor(this.highWaterMark); + + // if _final has been called + this.finalCalled = false; + + // drain event flag. + this.needDrain = false; + // at the start of calling end() + this.ending = false; + // when end() has been called, and returned + this.ended = false; + // when 'finish' is emitted + this.finished = false; + + // has it been destroyed + this.destroyed = false; + + // should we decode strings into buffers before passing to _write? + // this is here so that some node-core streams can optimize string + // handling at a lower level. + var noDecode = options.decodeStrings === false; + this.decodeStrings = !noDecode; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // not an actual buffer we keep track of, but a measurement + // of how much we're waiting to get pushed to some underlying + // socket or file. + this.length = 0; + + // a flag to see when we're in the middle of a write. + this.writing = false; + + // when true all writes will be buffered until .uncork() call + this.corked = 0; + + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; + + // a flag to know if we're processing previously buffered items, which + // may call the _write() callback in the same tick, so that we don't + // end up in an overlapped onwrite situation. + this.bufferProcessing = false; + + // the callback that's passed to _write(chunk,cb) + this.onwrite = function (er) { + onwrite(stream, er); + }; + + // the callback that the user supplies to write(chunk,encoding,cb) + this.writecb = null; + + // the amount that is being written when _write is called. + this.writelen = 0; + + this.bufferedRequest = null; + this.lastBufferedRequest = null; + + // number of pending user-supplied write callbacks + // this must be 0 before 'finish' can be emitted + this.pendingcb = 0; + + // emit prefinish if the only thing we're waiting for is _write cbs + // This is relevant for synchronous Transform streams + this.prefinished = false; + + // True if the error was already emitted and should not be thrown again + this.errorEmitted = false; + + // count buffered requests + this.bufferedRequestCount = 0; + + // allocate the first CorkedRequest, there is always + // one allocated and free to use, and we maintain at most two + this.corkedRequestsFree = new CorkedRequest(this); +} + +WritableState.prototype.getBuffer = function getBuffer() { + var current = this.bufferedRequest; + var out = []; + while (current) { + out.push(current); + current = current.next; + } + return out; +}; + +(function () { + try { + Object.defineProperty(WritableState.prototype, 'buffer', { + get: internalUtil.deprecate(function () { + return this.getBuffer(); + }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003') + }); + } catch (_) {} +})(); + +// Test _writableState for inheritance to account for Duplex streams, +// whose prototype chain only points to Readable. +var realHasInstance; +if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') { + realHasInstance = Function.prototype[Symbol.hasInstance]; + Object.defineProperty(Writable, Symbol.hasInstance, { + value: function (object) { + if (realHasInstance.call(this, object)) return true; + if (this !== Writable) return false; + + return object && object._writableState instanceof WritableState; + } + }); +} else { + realHasInstance = function (object) { + return object instanceof this; + }; +} + +function Writable(options) { + Duplex = Duplex || require('./_stream_duplex'); + + // Writable ctor is applied to Duplexes, too. + // `realHasInstance` is necessary because using plain `instanceof` + // would return false, as no `_writableState` property is attached. + + // Trying to use the custom `instanceof` for Writable here will also break the + // Node.js LazyTransform implementation, which has a non-trivial getter for + // `_writableState` that would lead to infinite recursion. + if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) { + return new Writable(options); + } + + this._writableState = new WritableState(options, this); + + // legacy. + this.writable = true; + + if (options) { + if (typeof options.write === 'function') this._write = options.write; + + if (typeof options.writev === 'function') this._writev = options.writev; + + if (typeof options.destroy === 'function') this._destroy = options.destroy; + + if (typeof options.final === 'function') this._final = options.final; + } + + Stream.call(this); +} + +// Otherwise people can pipe Writable streams, which is just wrong. +Writable.prototype.pipe = function () { + this.emit('error', new Error('Cannot pipe, not readable')); +}; + +function writeAfterEnd(stream, cb) { + var er = new Error('write after end'); + // TODO: defer error events consistently everywhere, not just the cb + stream.emit('error', er); + pna.nextTick(cb, er); +} + +// Checks that a user-supplied chunk is valid, especially for the particular +// mode the stream is in. Currently this means that `null` is never accepted +// and undefined/non-string values are only allowed in object mode. +function validChunk(stream, state, chunk, cb) { + var valid = true; + var er = false; + + if (chunk === null) { + er = new TypeError('May not write null values to stream'); + } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + if (er) { + stream.emit('error', er); + pna.nextTick(cb, er); + valid = false; + } + return valid; +} + +Writable.prototype.write = function (chunk, encoding, cb) { + var state = this._writableState; + var ret = false; + var isBuf = !state.objectMode && _isUint8Array(chunk); + + if (isBuf && !Buffer.isBuffer(chunk)) { + chunk = _uint8ArrayToBuffer(chunk); + } + + if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; + + if (typeof cb !== 'function') cb = nop; + + if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) { + state.pendingcb++; + ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); + } + + return ret; +}; + +Writable.prototype.cork = function () { + var state = this._writableState; + + state.corked++; +}; + +Writable.prototype.uncork = function () { + var state = this._writableState; + + if (state.corked) { + state.corked--; + + if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); + } +}; + +Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { + // node::ParseEncoding() requires lower case. + if (typeof encoding === 'string') encoding = encoding.toLowerCase(); + if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding); + this._writableState.defaultEncoding = encoding; + return this; +}; + +function decodeChunk(state, chunk, encoding) { + if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { + chunk = Buffer.from(chunk, encoding); + } + return chunk; +} + +Object.defineProperty(Writable.prototype, 'writableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function () { + return this._writableState.highWaterMark; + } +}); + +// if we're already writing something, then just put this +// in the queue, and wait our turn. Otherwise, call _write +// If we return false, then we need a drain event, so set that flag. +function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { + if (!isBuf) { + var newChunk = decodeChunk(state, chunk, encoding); + if (chunk !== newChunk) { + isBuf = true; + encoding = 'buffer'; + chunk = newChunk; + } + } + var len = state.objectMode ? 1 : chunk.length; + + state.length += len; + + var ret = state.length < state.highWaterMark; + // we must ensure that previous needDrain will not be reset to false. + if (!ret) state.needDrain = true; + + if (state.writing || state.corked) { + var last = state.lastBufferedRequest; + state.lastBufferedRequest = { + chunk: chunk, + encoding: encoding, + isBuf: isBuf, + callback: cb, + next: null + }; + if (last) { + last.next = state.lastBufferedRequest; + } else { + state.bufferedRequest = state.lastBufferedRequest; + } + state.bufferedRequestCount += 1; + } else { + doWrite(stream, state, false, len, chunk, encoding, cb); + } + + return ret; +} + +function doWrite(stream, state, writev, len, chunk, encoding, cb) { + state.writelen = len; + state.writecb = cb; + state.writing = true; + state.sync = true; + if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); + state.sync = false; +} + +function onwriteError(stream, state, sync, er, cb) { + --state.pendingcb; + + if (sync) { + // defer the callback if we are being called synchronously + // to avoid piling up things on the stack + pna.nextTick(cb, er); + // this can emit finish, and it will always happen + // after error + pna.nextTick(finishMaybe, stream, state); + stream._writableState.errorEmitted = true; + stream.emit('error', er); + } else { + // the caller expect this to happen before if + // it is async + cb(er); + stream._writableState.errorEmitted = true; + stream.emit('error', er); + // this can emit finish, but finish must + // always follow error + finishMaybe(stream, state); + } +} + +function onwriteStateUpdate(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; +} + +function onwrite(stream, er) { + var state = stream._writableState; + var sync = state.sync; + var cb = state.writecb; + + onwriteStateUpdate(state); + + if (er) onwriteError(stream, state, sync, er, cb);else { + // Check if we're actually ready to finish, but don't emit yet + var finished = needFinish(state); + + if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { + clearBuffer(stream, state); + } + + if (sync) { + /**/ + asyncWrite(afterWrite, stream, state, finished, cb); + /**/ + } else { + afterWrite(stream, state, finished, cb); + } + } +} + +function afterWrite(stream, state, finished, cb) { + if (!finished) onwriteDrain(stream, state); + state.pendingcb--; + cb(); + finishMaybe(stream, state); +} + +// Must force callback to be called on nextTick, so that we don't +// emit 'drain' before the write() consumer gets the 'false' return +// value, and has a chance to attach a 'drain' listener. +function onwriteDrain(stream, state) { + if (state.length === 0 && state.needDrain) { + state.needDrain = false; + stream.emit('drain'); + } +} + +// if there's something in the buffer waiting, then process it +function clearBuffer(stream, state) { + state.bufferProcessing = true; + var entry = state.bufferedRequest; + + if (stream._writev && entry && entry.next) { + // Fast case, write everything using _writev() + var l = state.bufferedRequestCount; + var buffer = new Array(l); + var holder = state.corkedRequestsFree; + holder.entry = entry; + + var count = 0; + var allBuffers = true; + while (entry) { + buffer[count] = entry; + if (!entry.isBuf) allBuffers = false; + entry = entry.next; + count += 1; + } + buffer.allBuffers = allBuffers; + + doWrite(stream, state, true, state.length, buffer, '', holder.finish); + + // doWrite is almost always async, defer these to save a bit of time + // as the hot path ends with doWrite + state.pendingcb++; + state.lastBufferedRequest = null; + if (holder.next) { + state.corkedRequestsFree = holder.next; + holder.next = null; + } else { + state.corkedRequestsFree = new CorkedRequest(state); + } + state.bufferedRequestCount = 0; + } else { + // Slow case, write chunks one-by-one + while (entry) { + var chunk = entry.chunk; + var encoding = entry.encoding; + var cb = entry.callback; + var len = state.objectMode ? 1 : chunk.length; + + doWrite(stream, state, false, len, chunk, encoding, cb); + entry = entry.next; + state.bufferedRequestCount--; + // if we didn't call the onwrite immediately, then + // it means that we need to wait until it does. + // also, that means that the chunk and cb are currently + // being processed, so move the buffer counter past them. + if (state.writing) { + break; + } + } + + if (entry === null) state.lastBufferedRequest = null; + } + + state.bufferedRequest = entry; + state.bufferProcessing = false; +} + +Writable.prototype._write = function (chunk, encoding, cb) { + cb(new Error('_write() is not implemented')); +}; + +Writable.prototype._writev = null; + +Writable.prototype.end = function (chunk, encoding, cb) { + var state = this._writableState; + + if (typeof chunk === 'function') { + cb = chunk; + chunk = null; + encoding = null; + } else if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); + + // .end() fully uncorks + if (state.corked) { + state.corked = 1; + this.uncork(); + } + + // ignore unnecessary end() calls. + if (!state.ending && !state.finished) endWritable(this, state, cb); +}; + +function needFinish(state) { + return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; +} +function callFinal(stream, state) { + stream._final(function (err) { + state.pendingcb--; + if (err) { + stream.emit('error', err); + } + state.prefinished = true; + stream.emit('prefinish'); + finishMaybe(stream, state); + }); +} +function prefinish(stream, state) { + if (!state.prefinished && !state.finalCalled) { + if (typeof stream._final === 'function') { + state.pendingcb++; + state.finalCalled = true; + pna.nextTick(callFinal, stream, state); + } else { + state.prefinished = true; + stream.emit('prefinish'); + } + } +} + +function finishMaybe(stream, state) { + var need = needFinish(state); + if (need) { + prefinish(stream, state); + if (state.pendingcb === 0) { + state.finished = true; + stream.emit('finish'); + } + } + return need; +} + +function endWritable(stream, state, cb) { + state.ending = true; + finishMaybe(stream, state); + if (cb) { + if (state.finished) pna.nextTick(cb);else stream.once('finish', cb); + } + state.ended = true; + stream.writable = false; +} + +function onCorkedFinish(corkReq, state, err) { + var entry = corkReq.entry; + corkReq.entry = null; + while (entry) { + var cb = entry.callback; + state.pendingcb--; + cb(err); + entry = entry.next; + } + if (state.corkedRequestsFree) { + state.corkedRequestsFree.next = corkReq; + } else { + state.corkedRequestsFree = corkReq; + } +} + +Object.defineProperty(Writable.prototype, 'destroyed', { + get: function () { + if (this._writableState === undefined) { + return false; + } + return this._writableState.destroyed; + }, + set: function (value) { + // we ignore the value if the stream + // has not been initialized yet + if (!this._writableState) { + return; + } + + // backward compatibility, the user is explicitly + // managing destroyed + this._writableState.destroyed = value; + } +}); + +Writable.prototype.destroy = destroyImpl.destroy; +Writable.prototype._undestroy = destroyImpl.undestroy; +Writable.prototype._destroy = function (err, cb) { + this.end(); + cb(err); +}; +}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"./_stream_duplex":58,"./internal/streams/destroy":64,"./internal/streams/stream":65,"_process":56,"core-util-is":42,"inherits":50,"process-nextick-args":55,"safe-buffer":70,"util-deprecate":73}],63:[function(require,module,exports){ +'use strict'; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var Buffer = require('safe-buffer').Buffer; +var util = require('util'); + +function copyBuffer(src, target, offset) { + src.copy(target, offset); +} + +module.exports = function () { + function BufferList() { + _classCallCheck(this, BufferList); + + this.head = null; + this.tail = null; + this.length = 0; + } + + BufferList.prototype.push = function push(v) { + var entry = { data: v, next: null }; + if (this.length > 0) this.tail.next = entry;else this.head = entry; + this.tail = entry; + ++this.length; + }; + + BufferList.prototype.unshift = function unshift(v) { + var entry = { data: v, next: this.head }; + if (this.length === 0) this.tail = entry; + this.head = entry; + ++this.length; + }; + + BufferList.prototype.shift = function shift() { + if (this.length === 0) return; + var ret = this.head.data; + if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; + --this.length; + return ret; + }; + + BufferList.prototype.clear = function clear() { + this.head = this.tail = null; + this.length = 0; + }; + + BufferList.prototype.join = function join(s) { + if (this.length === 0) return ''; + var p = this.head; + var ret = '' + p.data; + while (p = p.next) { + ret += s + p.data; + }return ret; + }; + + BufferList.prototype.concat = function concat(n) { + if (this.length === 0) return Buffer.alloc(0); + if (this.length === 1) return this.head.data; + var ret = Buffer.allocUnsafe(n >>> 0); + var p = this.head; + var i = 0; + while (p) { + copyBuffer(p.data, ret, i); + i += p.data.length; + p = p.next; + } + return ret; + }; + + return BufferList; +}(); + +if (util && util.inspect && util.inspect.custom) { + module.exports.prototype[util.inspect.custom] = function () { + var obj = util.inspect({ length: this.length }); + return this.constructor.name + ' ' + obj; + }; +} +},{"safe-buffer":70,"util":38}],64:[function(require,module,exports){ +'use strict'; + +/**/ + +var pna = require('process-nextick-args'); +/**/ + +// undocumented cb() API, needed for core, not for public API +function destroy(err, cb) { + var _this = this; + + var readableDestroyed = this._readableState && this._readableState.destroyed; + var writableDestroyed = this._writableState && this._writableState.destroyed; + + if (readableDestroyed || writableDestroyed) { + if (cb) { + cb(err); + } else if (err && (!this._writableState || !this._writableState.errorEmitted)) { + pna.nextTick(emitErrorNT, this, err); + } + return this; + } + + // we set destroyed to true before firing error callbacks in order + // to make it re-entrance safe in case destroy() is called within callbacks + + if (this._readableState) { + this._readableState.destroyed = true; + } + + // if this is a duplex stream mark the writable part as destroyed as well + if (this._writableState) { + this._writableState.destroyed = true; + } + + this._destroy(err || null, function (err) { + if (!cb && err) { + pna.nextTick(emitErrorNT, _this, err); + if (_this._writableState) { + _this._writableState.errorEmitted = true; + } + } else if (cb) { + cb(err); + } + }); + + return this; +} + +function undestroy() { + if (this._readableState) { + this._readableState.destroyed = false; + this._readableState.reading = false; + this._readableState.ended = false; + this._readableState.endEmitted = false; + } + + if (this._writableState) { + this._writableState.destroyed = false; + this._writableState.ended = false; + this._writableState.ending = false; + this._writableState.finished = false; + this._writableState.errorEmitted = false; + } +} + +function emitErrorNT(self, err) { + self.emit('error', err); +} + +module.exports = { + destroy: destroy, + undestroy: undestroy +}; +},{"process-nextick-args":55}],65:[function(require,module,exports){ +module.exports = require('events').EventEmitter; + +},{"events":47}],66:[function(require,module,exports){ +module.exports = require('./readable').PassThrough + +},{"./readable":67}],67:[function(require,module,exports){ +exports = module.exports = require('./lib/_stream_readable.js'); +exports.Stream = exports; +exports.Readable = exports; +exports.Writable = require('./lib/_stream_writable.js'); +exports.Duplex = require('./lib/_stream_duplex.js'); +exports.Transform = require('./lib/_stream_transform.js'); +exports.PassThrough = require('./lib/_stream_passthrough.js'); + +},{"./lib/_stream_duplex.js":58,"./lib/_stream_passthrough.js":59,"./lib/_stream_readable.js":60,"./lib/_stream_transform.js":61,"./lib/_stream_writable.js":62}],68:[function(require,module,exports){ +module.exports = require('./readable').Transform + +},{"./readable":67}],69:[function(require,module,exports){ +module.exports = require('./lib/_stream_writable.js'); + +},{"./lib/_stream_writable.js":62}],70:[function(require,module,exports){ +/* eslint-disable node/no-deprecated-api */ +var buffer = require('buffer') +var Buffer = buffer.Buffer + +// alternative to using Object.keys for old browsers +function copyProps (src, dst) { + for (var key in src) { + dst[key] = src[key] + } +} +if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { + module.exports = buffer +} else { + // Copy properties from require('buffer') + copyProps(buffer, exports) + exports.Buffer = SafeBuffer +} + +function SafeBuffer (arg, encodingOrOffset, length) { + return Buffer(arg, encodingOrOffset, length) +} + +// Copy static methods from Buffer +copyProps(Buffer, SafeBuffer) + +SafeBuffer.from = function (arg, encodingOrOffset, length) { + if (typeof arg === 'number') { + throw new TypeError('Argument must not be a number') + } + return Buffer(arg, encodingOrOffset, length) +} + +SafeBuffer.alloc = function (size, fill, encoding) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + var buf = Buffer(size) + if (fill !== undefined) { + if (typeof encoding === 'string') { + buf.fill(fill, encoding) + } else { + buf.fill(fill) + } + } else { + buf.fill(0) + } + return buf +} + +SafeBuffer.allocUnsafe = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return Buffer(size) +} + +SafeBuffer.allocUnsafeSlow = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return buffer.SlowBuffer(size) +} + +},{"buffer":41}],71:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +module.exports = Stream; + +var EE = require('events').EventEmitter; +var inherits = require('inherits'); + +inherits(Stream, EE); +Stream.Readable = require('readable-stream/readable.js'); +Stream.Writable = require('readable-stream/writable.js'); +Stream.Duplex = require('readable-stream/duplex.js'); +Stream.Transform = require('readable-stream/transform.js'); +Stream.PassThrough = require('readable-stream/passthrough.js'); + +// Backwards-compat with node 0.4.x +Stream.Stream = Stream; + + + +// old-style streams. Note that the pipe method (the only relevant +// part of this class) is overridden in the Readable class. + +function Stream() { + EE.call(this); +} + +Stream.prototype.pipe = function(dest, options) { + var source = this; + + function ondata(chunk) { + if (dest.writable) { + if (false === dest.write(chunk) && source.pause) { + source.pause(); + } + } + } + + source.on('data', ondata); + + function ondrain() { + if (source.readable && source.resume) { + source.resume(); + } + } + + dest.on('drain', ondrain); + + // If the 'end' option is not supplied, dest.end() will be called when + // source gets the 'end' or 'close' events. Only dest.end() once. + if (!dest._isStdio && (!options || options.end !== false)) { + source.on('end', onend); + source.on('close', onclose); + } + + var didOnEnd = false; + function onend() { + if (didOnEnd) return; + didOnEnd = true; + + dest.end(); + } + + + function onclose() { + if (didOnEnd) return; + didOnEnd = true; + + if (typeof dest.destroy === 'function') dest.destroy(); + } + + // don't leave dangling pipes when there are errors. + function onerror(er) { + cleanup(); + if (EE.listenerCount(this, 'error') === 0) { + throw er; // Unhandled stream error in pipe. + } + } + + source.on('error', onerror); + dest.on('error', onerror); + + // remove all the event listeners that were added. + function cleanup() { + source.removeListener('data', ondata); + dest.removeListener('drain', ondrain); + + source.removeListener('end', onend); + source.removeListener('close', onclose); + + source.removeListener('error', onerror); + dest.removeListener('error', onerror); + + source.removeListener('end', cleanup); + source.removeListener('close', cleanup); + + dest.removeListener('close', cleanup); + } + + source.on('end', cleanup); + source.on('close', cleanup); + + dest.on('close', cleanup); + + dest.emit('pipe', source); + + // Allow for unix-like usage: A.pipe(B).pipe(C) + return dest; +}; + +},{"events":47,"inherits":50,"readable-stream/duplex.js":57,"readable-stream/passthrough.js":66,"readable-stream/readable.js":67,"readable-stream/transform.js":68,"readable-stream/writable.js":69}],72:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +'use strict'; + +/**/ + +var Buffer = require('safe-buffer').Buffer; +/**/ + +var isEncoding = Buffer.isEncoding || function (encoding) { + encoding = '' + encoding; + switch (encoding && encoding.toLowerCase()) { + case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw': + return true; + default: + return false; + } +}; + +function _normalizeEncoding(enc) { + if (!enc) return 'utf8'; + var retried; + while (true) { + switch (enc) { + case 'utf8': + case 'utf-8': + return 'utf8'; + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return 'utf16le'; + case 'latin1': + case 'binary': + return 'latin1'; + case 'base64': + case 'ascii': + case 'hex': + return enc; + default: + if (retried) return; // undefined + enc = ('' + enc).toLowerCase(); + retried = true; + } + } +}; + +// Do not cache `Buffer.isEncoding` when checking encoding names as some +// modules monkey-patch it to support additional encodings +function normalizeEncoding(enc) { + var nenc = _normalizeEncoding(enc); + if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc); + return nenc || enc; +} + +// StringDecoder provides an interface for efficiently splitting a series of +// buffers into a series of JS strings without breaking apart multi-byte +// characters. +exports.StringDecoder = StringDecoder; +function StringDecoder(encoding) { + this.encoding = normalizeEncoding(encoding); + var nb; + switch (this.encoding) { + case 'utf16le': + this.text = utf16Text; + this.end = utf16End; + nb = 4; + break; + case 'utf8': + this.fillLast = utf8FillLast; + nb = 4; + break; + case 'base64': + this.text = base64Text; + this.end = base64End; + nb = 3; + break; + default: + this.write = simpleWrite; + this.end = simpleEnd; + return; + } + this.lastNeed = 0; + this.lastTotal = 0; + this.lastChar = Buffer.allocUnsafe(nb); +} + +StringDecoder.prototype.write = function (buf) { + if (buf.length === 0) return ''; + var r; + var i; + if (this.lastNeed) { + r = this.fillLast(buf); + if (r === undefined) return ''; + i = this.lastNeed; + this.lastNeed = 0; + } else { + i = 0; + } + if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i); + return r || ''; +}; + +StringDecoder.prototype.end = utf8End; + +// Returns only complete characters in a Buffer +StringDecoder.prototype.text = utf8Text; + +// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer +StringDecoder.prototype.fillLast = function (buf) { + if (this.lastNeed <= buf.length) { + buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed); + return this.lastChar.toString(this.encoding, 0, this.lastTotal); + } + buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length); + this.lastNeed -= buf.length; +}; + +// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a +// continuation byte. If an invalid byte is detected, -2 is returned. +function utf8CheckByte(byte) { + if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4; + return byte >> 6 === 0x02 ? -1 : -2; +} + +// Checks at most 3 bytes at the end of a Buffer in order to detect an +// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4) +// needed to complete the UTF-8 character (if applicable) are returned. +function utf8CheckIncomplete(self, buf, i) { + var j = buf.length - 1; + if (j < i) return 0; + var nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) self.lastNeed = nb - 1; + return nb; + } + if (--j < i || nb === -2) return 0; + nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) self.lastNeed = nb - 2; + return nb; + } + if (--j < i || nb === -2) return 0; + nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) { + if (nb === 2) nb = 0;else self.lastNeed = nb - 3; + } + return nb; + } + return 0; +} + +// Validates as many continuation bytes for a multi-byte UTF-8 character as +// needed or are available. If we see a non-continuation byte where we expect +// one, we "replace" the validated continuation bytes we've seen so far with +// a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding +// behavior. The continuation byte check is included three times in the case +// where all of the continuation bytes for a character exist in the same buffer. +// It is also done this way as a slight performance increase instead of using a +// loop. +function utf8CheckExtraBytes(self, buf, p) { + if ((buf[0] & 0xC0) !== 0x80) { + self.lastNeed = 0; + return '\ufffd'; + } + if (self.lastNeed > 1 && buf.length > 1) { + if ((buf[1] & 0xC0) !== 0x80) { + self.lastNeed = 1; + return '\ufffd'; + } + if (self.lastNeed > 2 && buf.length > 2) { + if ((buf[2] & 0xC0) !== 0x80) { + self.lastNeed = 2; + return '\ufffd'; + } + } + } +} + +// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer. +function utf8FillLast(buf) { + var p = this.lastTotal - this.lastNeed; + var r = utf8CheckExtraBytes(this, buf, p); + if (r !== undefined) return r; + if (this.lastNeed <= buf.length) { + buf.copy(this.lastChar, p, 0, this.lastNeed); + return this.lastChar.toString(this.encoding, 0, this.lastTotal); + } + buf.copy(this.lastChar, p, 0, buf.length); + this.lastNeed -= buf.length; +} + +// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a +// partial character, the character's bytes are buffered until the required +// number of bytes are available. +function utf8Text(buf, i) { + var total = utf8CheckIncomplete(this, buf, i); + if (!this.lastNeed) return buf.toString('utf8', i); + this.lastTotal = total; + var end = buf.length - (total - this.lastNeed); + buf.copy(this.lastChar, 0, end); + return buf.toString('utf8', i, end); +} + +// For UTF-8, a replacement character is added when ending on a partial +// character. +function utf8End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) return r + '\ufffd'; + return r; +} + +// UTF-16LE typically needs two bytes per character, but even if we have an even +// number of bytes available, we need to check if we end on a leading/high +// surrogate. In that case, we need to wait for the next two bytes in order to +// decode the last character properly. +function utf16Text(buf, i) { + if ((buf.length - i) % 2 === 0) { + var r = buf.toString('utf16le', i); + if (r) { + var c = r.charCodeAt(r.length - 1); + if (c >= 0xD800 && c <= 0xDBFF) { + this.lastNeed = 2; + this.lastTotal = 4; + this.lastChar[0] = buf[buf.length - 2]; + this.lastChar[1] = buf[buf.length - 1]; + return r.slice(0, -1); + } + } + return r; + } + this.lastNeed = 1; + this.lastTotal = 2; + this.lastChar[0] = buf[buf.length - 1]; + return buf.toString('utf16le', i, buf.length - 1); +} + +// For UTF-16LE we do not explicitly append special replacement characters if we +// end on a partial character, we simply let v8 handle that. +function utf16End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) { + var end = this.lastTotal - this.lastNeed; + return r + this.lastChar.toString('utf16le', 0, end); + } + return r; +} + +function base64Text(buf, i) { + var n = (buf.length - i) % 3; + if (n === 0) return buf.toString('base64', i); + this.lastNeed = 3 - n; + this.lastTotal = 3; + if (n === 1) { + this.lastChar[0] = buf[buf.length - 1]; + } else { + this.lastChar[0] = buf[buf.length - 2]; + this.lastChar[1] = buf[buf.length - 1]; + } + return buf.toString('base64', i, buf.length - n); +} + +function base64End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed); + return r; +} + +// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex) +function simpleWrite(buf) { + return buf.toString(this.encoding); +} + +function simpleEnd(buf) { + return buf && buf.length ? this.write(buf) : ''; +} +},{"safe-buffer":70}],73:[function(require,module,exports){ +(function (global){ + +/** + * Module exports. + */ + +module.exports = deprecate; + +/** + * Mark that a method should not be used. + * Returns a modified function which warns once by default. + * + * If `localStorage.noDeprecation = true` is set, then it is a no-op. + * + * If `localStorage.throwDeprecation = true` is set, then deprecated functions + * will throw an Error when invoked. + * + * If `localStorage.traceDeprecation = true` is set, then deprecated functions + * will invoke `console.trace()` instead of `console.error()`. + * + * @param {Function} fn - the function to deprecate + * @param {String} msg - the string to print to the console when `fn` is invoked + * @returns {Function} a new "deprecated" version of `fn` + * @api public + */ + +function deprecate (fn, msg) { + if (config('noDeprecation')) { + return fn; + } + + var warned = false; + function deprecated() { + if (!warned) { + if (config('throwDeprecation')) { + throw new Error(msg); + } else if (config('traceDeprecation')) { + console.trace(msg); + } else { + console.warn(msg); + } + warned = true; + } + return fn.apply(this, arguments); + } + + return deprecated; +} + +/** + * Checks `localStorage` for boolean values for the given `name`. + * + * @param {String} name + * @returns {Boolean} + * @api private + */ + +function config (name) { + // accessing global.localStorage can trigger a DOMException in sandboxed iframes + try { + if (!global.localStorage) return false; + } catch (_) { + return false; + } + var val = global.localStorage[name]; + if (null == val) return false; + return String(val).toLowerCase() === 'true'; +} + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{}],74:[function(require,module,exports){ +arguments[4][50][0].apply(exports,arguments) +},{"dup":50}],75:[function(require,module,exports){ +module.exports = function isBuffer(arg) { + return arg && typeof arg === 'object' + && typeof arg.copy === 'function' + && typeof arg.fill === 'function' + && typeof arg.readUInt8 === 'function'; +} +},{}],76:[function(require,module,exports){ +(function (process,global){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var formatRegExp = /%[sdj%]/g; +exports.format = function(f) { + if (!isString(f)) { + var objects = []; + for (var i = 0; i < arguments.length; i++) { + objects.push(inspect(arguments[i])); + } + return objects.join(' '); + } + + var i = 1; + var args = arguments; + var len = args.length; + var str = String(f).replace(formatRegExp, function(x) { + if (x === '%%') return '%'; + if (i >= len) return x; + switch (x) { + case '%s': return String(args[i++]); + case '%d': return Number(args[i++]); + case '%j': + try { + return JSON.stringify(args[i++]); + } catch (_) { + return '[Circular]'; + } + default: + return x; + } + }); + for (var x = args[i]; i < len; x = args[++i]) { + if (isNull(x) || !isObject(x)) { + str += ' ' + x; + } else { + str += ' ' + inspect(x); + } + } + return str; +}; + + +// Mark that a method should not be used. +// Returns a modified function which warns once by default. +// If --no-deprecation is set, then it is a no-op. +exports.deprecate = function(fn, msg) { + // Allow for deprecating things in the process of starting up. + if (isUndefined(global.process)) { + return function() { + return exports.deprecate(fn, msg).apply(this, arguments); + }; + } + + if (process.noDeprecation === true) { + return fn; + } + + var warned = false; + function deprecated() { + if (!warned) { + if (process.throwDeprecation) { + throw new Error(msg); + } else if (process.traceDeprecation) { + console.trace(msg); + } else { + console.error(msg); + } + warned = true; + } + return fn.apply(this, arguments); + } + + return deprecated; +}; + + +var debugs = {}; +var debugEnviron; +exports.debuglog = function(set) { + if (isUndefined(debugEnviron)) + debugEnviron = process.env.NODE_DEBUG || ''; + set = set.toUpperCase(); + if (!debugs[set]) { + if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { + var pid = process.pid; + debugs[set] = function() { + var msg = exports.format.apply(exports, arguments); + console.error('%s %d: %s', set, pid, msg); + }; + } else { + debugs[set] = function() {}; + } + } + return debugs[set]; +}; + + +/** + * Echos the value of a value. Trys to print the value out + * in the best way possible given the different types. + * + * @param {Object} obj The object to print out. + * @param {Object} opts Optional options object that alters the output. + */ +/* legacy: obj, showHidden, depth, colors*/ +function inspect(obj, opts) { + // default options + var ctx = { + seen: [], + stylize: stylizeNoColor + }; + // legacy... + if (arguments.length >= 3) ctx.depth = arguments[2]; + if (arguments.length >= 4) ctx.colors = arguments[3]; + if (isBoolean(opts)) { + // legacy... + ctx.showHidden = opts; + } else if (opts) { + // got an "options" object + exports._extend(ctx, opts); + } + // set default options + if (isUndefined(ctx.showHidden)) ctx.showHidden = false; + if (isUndefined(ctx.depth)) ctx.depth = 2; + if (isUndefined(ctx.colors)) ctx.colors = false; + if (isUndefined(ctx.customInspect)) ctx.customInspect = true; + if (ctx.colors) ctx.stylize = stylizeWithColor; + return formatValue(ctx, obj, ctx.depth); +} +exports.inspect = inspect; + + +// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics +inspect.colors = { + 'bold' : [1, 22], + 'italic' : [3, 23], + 'underline' : [4, 24], + 'inverse' : [7, 27], + 'white' : [37, 39], + 'grey' : [90, 39], + 'black' : [30, 39], + 'blue' : [34, 39], + 'cyan' : [36, 39], + 'green' : [32, 39], + 'magenta' : [35, 39], + 'red' : [31, 39], + 'yellow' : [33, 39] +}; + +// Don't use 'blue' not visible on cmd.exe +inspect.styles = { + 'special': 'cyan', + 'number': 'yellow', + 'boolean': 'yellow', + 'undefined': 'grey', + 'null': 'bold', + 'string': 'green', + 'date': 'magenta', + // "name": intentionally not styling + 'regexp': 'red' +}; + + +function stylizeWithColor(str, styleType) { + var style = inspect.styles[styleType]; + + if (style) { + return '\u001b[' + inspect.colors[style][0] + 'm' + str + + '\u001b[' + inspect.colors[style][1] + 'm'; + } else { + return str; + } +} + + +function stylizeNoColor(str, styleType) { + return str; +} + + +function arrayToHash(array) { + var hash = {}; + + array.forEach(function(val, idx) { + hash[val] = true; + }); + + return hash; +} + + +function formatValue(ctx, value, recurseTimes) { + // Provide a hook for user-specified inspect functions. + // Check that value is an object with an inspect function on it + if (ctx.customInspect && + value && + isFunction(value.inspect) && + // Filter out the util module, it's inspect function is special + value.inspect !== exports.inspect && + // Also filter out any prototype objects using the circular check. + !(value.constructor && value.constructor.prototype === value)) { + var ret = value.inspect(recurseTimes, ctx); + if (!isString(ret)) { + ret = formatValue(ctx, ret, recurseTimes); + } + return ret; + } + + // Primitive types cannot have properties + var primitive = formatPrimitive(ctx, value); + if (primitive) { + return primitive; + } + + // Look up the keys of the object. + var keys = Object.keys(value); + var visibleKeys = arrayToHash(keys); + + if (ctx.showHidden) { + keys = Object.getOwnPropertyNames(value); + } + + // IE doesn't make error fields non-enumerable + // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx + if (isError(value) + && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { + return formatError(value); + } + + // Some type of object without properties can be shortcutted. + if (keys.length === 0) { + if (isFunction(value)) { + var name = value.name ? ': ' + value.name : ''; + return ctx.stylize('[Function' + name + ']', 'special'); + } + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } + if (isDate(value)) { + return ctx.stylize(Date.prototype.toString.call(value), 'date'); + } + if (isError(value)) { + return formatError(value); + } + } + + var base = '', array = false, braces = ['{', '}']; + + // Make Array say that they are Array + if (isArray(value)) { + array = true; + braces = ['[', ']']; + } + + // Make functions say that they are functions + if (isFunction(value)) { + var n = value.name ? ': ' + value.name : ''; + base = ' [Function' + n + ']'; + } + + // Make RegExps say that they are RegExps + if (isRegExp(value)) { + base = ' ' + RegExp.prototype.toString.call(value); + } + + // Make dates with properties first say the date + if (isDate(value)) { + base = ' ' + Date.prototype.toUTCString.call(value); + } + + // Make error with message first say the error + if (isError(value)) { + base = ' ' + formatError(value); + } + + if (keys.length === 0 && (!array || value.length == 0)) { + return braces[0] + base + braces[1]; + } + + if (recurseTimes < 0) { + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } else { + return ctx.stylize('[Object]', 'special'); + } + } + + ctx.seen.push(value); + + var output; + if (array) { + output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); + } else { + output = keys.map(function(key) { + return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); + }); + } + + ctx.seen.pop(); + + return reduceToSingleString(output, base, braces); +} + + +function formatPrimitive(ctx, value) { + if (isUndefined(value)) + return ctx.stylize('undefined', 'undefined'); + if (isString(value)) { + var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') + .replace(/'/g, "\\'") + .replace(/\\"/g, '"') + '\''; + return ctx.stylize(simple, 'string'); + } + if (isNumber(value)) + return ctx.stylize('' + value, 'number'); + if (isBoolean(value)) + return ctx.stylize('' + value, 'boolean'); + // For some reason typeof null is "object", so special case here. + if (isNull(value)) + return ctx.stylize('null', 'null'); +} + + +function formatError(value) { + return '[' + Error.prototype.toString.call(value) + ']'; +} + + +function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { + var output = []; + for (var i = 0, l = value.length; i < l; ++i) { + if (hasOwnProperty(value, String(i))) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + String(i), true)); + } else { + output.push(''); + } + } + keys.forEach(function(key) { + if (!key.match(/^\d+$/)) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + key, true)); + } + }); + return output; +} + + +function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { + var name, str, desc; + desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; + if (desc.get) { + if (desc.set) { + str = ctx.stylize('[Getter/Setter]', 'special'); + } else { + str = ctx.stylize('[Getter]', 'special'); + } + } else { + if (desc.set) { + str = ctx.stylize('[Setter]', 'special'); + } + } + if (!hasOwnProperty(visibleKeys, key)) { + name = '[' + key + ']'; + } + if (!str) { + if (ctx.seen.indexOf(desc.value) < 0) { + if (isNull(recurseTimes)) { + str = formatValue(ctx, desc.value, null); + } else { + str = formatValue(ctx, desc.value, recurseTimes - 1); + } + if (str.indexOf('\n') > -1) { + if (array) { + str = str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n').substr(2); + } else { + str = '\n' + str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n'); + } + } + } else { + str = ctx.stylize('[Circular]', 'special'); + } + } + if (isUndefined(name)) { + if (array && key.match(/^\d+$/)) { + return str; + } + name = JSON.stringify('' + key); + if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { + name = name.substr(1, name.length - 2); + name = ctx.stylize(name, 'name'); + } else { + name = name.replace(/'/g, "\\'") + .replace(/\\"/g, '"') + .replace(/(^"|"$)/g, "'"); + name = ctx.stylize(name, 'string'); + } + } + + return name + ': ' + str; +} + + +function reduceToSingleString(output, base, braces) { + var numLinesEst = 0; + var length = output.reduce(function(prev, cur) { + numLinesEst++; + if (cur.indexOf('\n') >= 0) numLinesEst++; + return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; + }, 0); + + if (length > 60) { + return braces[0] + + (base === '' ? '' : base + '\n ') + + ' ' + + output.join(',\n ') + + ' ' + + braces[1]; + } + + return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; +} + + +// NOTE: These type checking functions intentionally don't use `instanceof` +// because it is fragile and can be easily faked with `Object.create()`. +function isArray(ar) { + return Array.isArray(ar); +} +exports.isArray = isArray; + +function isBoolean(arg) { + return typeof arg === 'boolean'; +} +exports.isBoolean = isBoolean; + +function isNull(arg) { + return arg === null; +} +exports.isNull = isNull; + +function isNullOrUndefined(arg) { + return arg == null; +} +exports.isNullOrUndefined = isNullOrUndefined; + +function isNumber(arg) { + return typeof arg === 'number'; +} +exports.isNumber = isNumber; + +function isString(arg) { + return typeof arg === 'string'; +} +exports.isString = isString; + +function isSymbol(arg) { + return typeof arg === 'symbol'; +} +exports.isSymbol = isSymbol; + +function isUndefined(arg) { + return arg === void 0; +} +exports.isUndefined = isUndefined; + +function isRegExp(re) { + return isObject(re) && objectToString(re) === '[object RegExp]'; +} +exports.isRegExp = isRegExp; + +function isObject(arg) { + return typeof arg === 'object' && arg !== null; +} +exports.isObject = isObject; + +function isDate(d) { + return isObject(d) && objectToString(d) === '[object Date]'; +} +exports.isDate = isDate; + +function isError(e) { + return isObject(e) && + (objectToString(e) === '[object Error]' || e instanceof Error); +} +exports.isError = isError; + +function isFunction(arg) { + return typeof arg === 'function'; +} +exports.isFunction = isFunction; + +function isPrimitive(arg) { + return arg === null || + typeof arg === 'boolean' || + typeof arg === 'number' || + typeof arg === 'string' || + typeof arg === 'symbol' || // ES6 symbol + typeof arg === 'undefined'; +} +exports.isPrimitive = isPrimitive; + +exports.isBuffer = require('./support/isBuffer'); + +function objectToString(o) { + return Object.prototype.toString.call(o); +} + + +function pad(n) { + return n < 10 ? '0' + n.toString(10) : n.toString(10); +} + + +var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', + 'Oct', 'Nov', 'Dec']; + +// 26 Feb 16:19:34 +function timestamp() { + var d = new Date(); + var time = [pad(d.getHours()), + pad(d.getMinutes()), + pad(d.getSeconds())].join(':'); + return [d.getDate(), months[d.getMonth()], time].join(' '); +} + + +// log is just a thin wrapper to console.log that prepends a timestamp +exports.log = function() { + console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); +}; + + +/** + * Inherit the prototype methods from one constructor into another. + * + * The Function.prototype.inherits from lang.js rewritten as a standalone + * function (not on Function.prototype). NOTE: If this file is to be loaded + * during bootstrapping this function needs to be rewritten using some native + * functions as prototype setup using normal JavaScript does not work as + * expected during bootstrapping (see mirror.js in r114903). + * + * @param {function} ctor Constructor function which needs to inherit the + * prototype. + * @param {function} superCtor Constructor function to inherit prototype from. + */ +exports.inherits = require('inherits'); + +exports._extend = function(origin, add) { + // Don't do anything if add isn't an object + if (!add || !isObject(add)) return origin; + + var keys = Object.keys(add); + var i = keys.length; + while (i--) { + origin[keys[i]] = add[keys[i]]; + } + return origin; +}; + +function hasOwnProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); +} + +}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"./support/isBuffer":75,"_process":56,"inherits":74}]},{},[1]); diff --git a/node_modules/mocha/package.json b/node_modules/mocha/package.json new file mode 100644 index 0000000..6f00990 --- /dev/null +++ b/node_modules/mocha/package.json @@ -0,0 +1,1849 @@ +{ + "_from": "mocha", + "_id": "mocha@5.2.0", + "_inBundle": false, + "_integrity": "sha512-2IUgKDhc3J7Uug+FxMXuqIyYzH7gJjXECKe/w43IGgQHTSj3InJi+yAA7T24L9bQMRKiUEHxEX37G5JpVUGLcQ==", + "_location": "/mocha", + "_phantomChildren": {}, + "_requested": { + "type": "tag", + "registry": true, + "raw": "mocha", + "name": "mocha", + "escapedName": "mocha", + "rawSpec": "", + "saveSpec": null, + "fetchSpec": "latest" + }, + "_requiredBy": [ + "#DEV:/", + "#USER" + ], + "_resolved": "https://registry.npmjs.org/mocha/-/mocha-5.2.0.tgz", + "_shasum": "6d8ae508f59167f940f2b5b3c4a612ae50c90ae6", + "_spec": "mocha", + "_where": "/Users/jessitron/code/jessitron/stringify-tree", + "author": { + "name": "TJ Holowaychuk", + "email": "tj@vision-media.ca" + }, + "bin": { + "mocha": "./bin/mocha", + "_mocha": "./bin/_mocha" + }, + "browser": { + "growl": "./lib/browser/growl.js", + "tty": "./lib/browser/tty.js", + "./index.js": "./browser-entry.js", + "fs": false, + "glob": false, + "path": false, + "supports-color": false + }, + "bugs": { + "url": "https://github.com/mochajs/mocha/issues" + }, + "bundleDependencies": false, + "contributors": [ + { + "name": "38elements", + "email": "mh19820223@gmail.com" + }, + { + "name": "Aaron Brady", + "email": "aaron@mori.com" + }, + { + "name": "Aaron Hamid", + "email": "aaron.hamid@gmail.com" + }, + { + "name": "Aaron Heckmann", + "email": "aaron.heckmann+github@gmail.com" + }, + { + "name": "Aaron Krause", + "email": "aaronjkrause@gmail.com" + }, + { + "name": "Aaron Petcoff", + "email": "hello@aaronpetcoff.me" + }, + { + "name": "abrkn", + "email": "a@abrkn.com" + }, + { + "name": "Adam Crabtree", + "email": "adam.crabtree@redrobotlabs.com" + }, + { + "name": "Adam Gruber", + "email": "talknmime@gmail.com" + }, + { + "name": "Adrian Ludwig", + "email": "me@adrianludwig.pl" + }, + { + "name": "Ahmad Bamieh", + "email": "ahmadbamieh@gmail.com" + }, + { + "name": "airportyh", + "email": "airportyh@gmail.com" + }, + { + "name": "Ajay Kodali", + "email": "ajay.kodali@citrix.com" + }, + { + "name": "Al Scott", + "email": "al.scott@atomicobject.com" + }, + { + "name": "Alex Bainter", + "email": "metalex9@users.noreply.github.com" + }, + { + "name": "Alexander Early", + "email": "alexander.early@gmail.com" + }, + { + "name": "Alexander Shepelin", + "email": "Brightcor@gmail.com" + }, + { + "name": "Alhadis", + "email": "gardnerjohng@gmail.com" + }, + { + "name": "amsul", + "email": "reach@amsul.ca" + }, + { + "name": "Anders Olsen Sandvik", + "email": "Andersos@users.noreply.github.com" + }, + { + "name": "Andreas Brekken", + "email": "andreas@opuno.com" + }, + { + "name": "Andreas Lind Petersen", + "email": "andreas@one.com" + }, + { + "name": "Andrew Krawchyk", + "email": "903716+akrawchyk@users.noreply.github.com" + }, + { + "name": "Andrew Nesbitt", + "email": "andrewnez@gmail.com" + }, + { + "name": "Andrey Popp", + "email": "8mayday@gmail.com" + }, + { + "name": "Andrii Shumada", + "email": "eagleeyes91@gmail.com" + }, + { + "name": "andy matthews", + "email": "andy@commadelimited.com" + }, + { + "name": "Angelica Valenta", + "email": "angelicavalenta@gmail.com" + }, + { + "name": "Anis Safine", + "email": "anis.safine.ext@francetv.fr" + }, + { + "name": "Anish Karandikar", + "email": "anishkny@gmail.com" + }, + { + "name": "Anthony", + "email": "keppi@o2.pl" + }, + { + "name": "Anton", + "email": "anton.redfox@gmail.com" + }, + { + "name": "anton", + "email": "anton.valickij@gmail.com" + }, + { + "name": "APerson", + "email": "danielhglus@gmail.com" + }, + { + "name": "Arian Stolwijk", + "email": "arian@aryweb.nl" + }, + { + "name": "Ariel Mashraki", + "email": "ariel@mashraki.co.il" + }, + { + "name": "Arnaud Brousseau", + "email": "arnaud.brousseau@gmail.com" + }, + { + "name": "Artem Govorov", + "email": "artem.govorov@gmail.com" + }, + { + "name": "Atsuya Takagi", + "email": "asoftonight@gmail.com" + }, + { + "name": "Attila Domokos", + "email": "adomokos@gmail.com" + }, + { + "name": "Austin Birch", + "email": "mraustinbirch@gmail.com" + }, + { + "name": "Avi Vahl", + "email": "avi.vahl@wix.com" + }, + { + "name": "badunk", + "email": "baduncaduncan@gmail.com" + }, + { + "name": "Bamieh", + "email": "ahmadbamieh@gmail.com" + }, + { + "name": "Ben Bradley", + "email": "ben@bradleyit.com" + }, + { + "name": "Ben Harris", + "email": "benhdev@gmail.com" + }, + { + "name": "Ben Hutchison", + "email": "ben@aldaviva.com" + }, + { + "name": "Ben Lindsey", + "email": "ben.lindsey@vungle.com" + }, + { + "name": "Ben Noordhuis", + "email": "info@bnoordhuis.nl" + }, + { + "name": "Ben Vinegar", + "email": "ben@benv.ca" + }, + { + "name": "Benjamin Eidelman", + "email": "beneidel@gmail.com" + }, + { + "name": "Benjie Gillam", + "email": "benjie@jemjie.com" + }, + { + "name": "Benoit Larroque", + "email": "zeta.ben@gmail.com" + }, + { + "name": "Benoît Zugmeyer", + "email": "bzugmeyer@gmail.com" + }, + { + "name": "Benson Trent", + "email": "bensontrent@gmail.com" + }, + { + "name": "Berker Peksag", + "email": "berker.peksag@gmail.com" + }, + { + "name": "berni", + "email": "berni@extensa.pl" + }, + { + "name": "Bjørge Næss", + "email": "bjoerge@origo.no" + }, + { + "name": "Brendan Nee", + "email": "brendan.nee@gmail.com" + }, + { + "name": "Brian Beck", + "email": "exogen@gmail.com" + }, + { + "name": "Brian Lalor", + "email": "blalor@bravo5.org" + }, + { + "name": "Brian M. Carlson", + "email": "brian.m.carlson@gmail.com" + }, + { + "name": "Brian Moore", + "email": "guardbionic-github@yahoo.com" + }, + { + "name": "Bryan Donovan", + "email": "bdondo@gmail.com" + }, + { + "name": "Buck Doyle", + "email": "b@chromatin.ca" + }, + { + "name": "C. Scott Ananian", + "email": "cscott@cscott.net" + }, + { + "name": "Callum Macrae", + "email": "callum@macr.ae" + }, + { + "name": "Can Oztokmak", + "email": "can@zeplin.io" + }, + { + "name": "Capacitor Set", + "email": "CapacitorSet@users.noreply.github.com" + }, + { + "name": "Casey Foster", + "email": "casey@caseywebdev.com" + }, + { + "name": "Charles Lowell", + "email": "cowboyd@frontside.io" + }, + { + "name": "Charles Merriam", + "email": "charles.merriam@gmail.com" + }, + { + "name": "Charlie Rudolph", + "email": "charles.w.rudolph@gmail.com" + }, + { + "name": "Chris", + "email": "chrisleck@users.noreply.github.com" + }, + { + "name": "Chris Buckley", + "email": "chris@cmbuckley.co.uk" + }, + { + "name": "Chris Lamb", + "email": "chris@chris-lamb.co.uk" + }, + { + "name": "Christian", + "email": "me@rndm.de" + }, + { + "name": "Christoffer Hallas", + "email": "christoffer.hallas@gmail.com" + }, + { + "name": "Christoph Neuroth", + "email": "christoph.neuroth@gmail.com" + }, + { + "name": "Christopher Hiller", + "email": "boneskull@boneskull.com" + }, + { + "name": "ChrisWren", + "email": "cthewren@gmail.com" + }, + { + "name": "claudyus", + "email": "claudyus@HEX.(none)", + "url": "none" + }, + { + "name": "Connor Dunn", + "email": "connorhd@gmail.com" + }, + { + "name": "Corey Butler", + "email": "corey@coreybutler.com" + }, + { + "name": "Cory Thomas", + "email": "cory.thomas@bazaarvoice.com" + }, + { + "name": "Craig Taub", + "email": "craigtaub@gmail.com" + }, + { + "name": "Cube", + "email": "maty21@gmail.com" + }, + { + "name": "Daniel Ruf", + "email": "daniel@daniel-ruf.de" + }, + { + "name": "Daniel St. Jules", + "email": "danielst.jules@gmail.com" + }, + { + "name": "Daniel Stockman", + "email": "daniel.stockman@gmail.com" + }, + { + "name": "Darryl Pogue", + "email": "dvpdiner2@gmail.com" + }, + { + "name": "Dave McKenna", + "email": "davemckenna01@gmail.com" + }, + { + "name": "David da Silva Contín", + "email": "dasilvacontin@gmail.com" + }, + { + "name": "David Henderson", + "email": "david.henderson@triggeredmessaging.com" + }, + { + "name": "David M. Lee", + "email": "leedm777@yahoo.com" + }, + { + "name": "David Neubauer", + "email": "davidneub@gmail.com" + }, + { + "name": "DavNej", + "email": "davnej.dev@gmail.com" + }, + { + "name": "Denis Bardadym", + "email": "bardadymchik@gmail.com" + }, + { + "name": "Devin Weaver", + "email": "suki@tritarget.org" + }, + { + "name": "dfberry", + "email": "dinaberry@outlook.com" + }, + { + "name": "Di Wu", + "email": "dwu@palantir.com" + }, + { + "name": "Dina Berry", + "email": "dfberry@users.noreply.github.com" + }, + { + "name": "Diogo Monteiro", + "email": "diogo.gmt@gmail.com" + }, + { + "name": "Dmitriy Simushev", + "email": "simushevds@gmail.com" + }, + { + "name": "Dmitry Shirokov", + "email": "deadrunk@gmail.com" + }, + { + "name": "Dmitry Sorin", + "email": "info@staypositive.ru" + }, + { + "name": "Domenic Denicola", + "email": "domenic@domenicdenicola.com" + }, + { + "name": "Dominic Barnes", + "email": "dominic@dbarnes.info" + }, + { + "name": "Dominique Quatravaux", + "email": "dominique@quatravaux.org" + }, + { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + }, + { + "name": "Duncan Beevers", + "email": "duncan@dweebd.com" + }, + { + "name": "eiji.ienaga", + "email": "eiji.ienaga@gmail.com" + }, + { + "name": "elergy", + "email": "elergy@yandex-team.ru" + }, + { + "name": "Eli Skeggs", + "email": "skeggse@users.noreply.github.com" + }, + { + "name": "ELLIOTTCABLE", + "email": "me@ell.io" + }, + { + "name": "Emanuele", + "email": "my.burning@gmail.com" + }, + { + "name": "Enric Pallerols", + "email": "enric@pallerols.cat" + }, + { + "name": "Erik Eng", + "email": "mail@ptz0n.se" + }, + { + "name": "Eugene Tiutiunnyk", + "email": "eugene.tiutiunnyk@lookout.com" + }, + { + "name": "Fabio M. Costa", + "email": "fabiomcosta@gmail.com" + }, + { + "name": "Fagner Brack", + "email": "github3@fagnermartins.com" + }, + { + "name": "FARKAS Máté", + "email": "mate.farkas@virtual-call-center.eu" + }, + { + "name": "fcrisci", + "email": "fabio.crisci@amadeus.com" + }, + { + "name": "Fede Ramirez", + "email": "i@2fd.me" + }, + { + "name": "Fedor Indutny", + "email": "fedor.indutny@gmail.com" + }, + { + "name": "fengmk2", + "email": "fengmk2@gmail.com" + }, + { + "name": "Florian Margaine", + "email": "florian@margaine.com" + }, + { + "name": "FND", + "email": "FND@users.noreply.github.com" + }, + { + "name": "fool2fish", + "email": "fool2fish@gmail.com" + }, + { + "name": "Forbes Lindesay", + "email": "forbes@lindesay.co.uk" + }, + { + "name": "Frank Leon Rose", + "email": "frankleonrose@gmail.com" + }, + { + "name": "Frederico Silva", + "email": "frederico.silva@gmail.com" + }, + { + "name": "Fredrik Enestad", + "email": "fredrik@devloop.se" + }, + { + "name": "Fredrik Lindin", + "email": "fredriklindin@gmail.com" + }, + { + "name": "Fumiaki MATSUSHIMA", + "email": "mtsmfm@gmail.com" + }, + { + "name": "Gabriel Silk", + "email": "gabesilk@gmail.com" + }, + { + "name": "Gareth Aye", + "email": "gaye@mozilla.com" + }, + { + "name": "Gareth Murphy", + "email": "gareth.cpm@gmail.com" + }, + { + "name": "Gavin Mogan", + "email": "GavinM@airg.com" + }, + { + "name": "gaye", + "email": "gaye@mozilla.com" + }, + { + "name": "gigadude", + "email": "gigadude@users.noreply.github.com" + }, + { + "name": "Giovanni Bassi", + "email": "giggio@giggio.net" + }, + { + "name": "Glen Huang", + "email": "curvedmark@gmail.com" + }, + { + "name": "Glen Mailer", + "email": "glenjamin@gmail.com" + }, + { + "name": "grasGendarme", + "email": "me@grasgendar.me" + }, + { + "name": "Greg Perkins", + "email": "gregperkins@alum.mit.edu" + }, + { + "name": "Guangcong Luo", + "email": "guangcongluo@gmail.com" + }, + { + "name": "Guillermo Rauch", + "email": "rauchg@gmail.com" + }, + { + "name": "Guy Arye", + "email": "arye.guy@gmail.com" + }, + { + "name": "Gyandeep Singh", + "email": "gyandeeps@gmail.com" + }, + { + "name": "Harish", + "email": "hyeluri@gmail.com" + }, + { + "name": "Harry Brundage", + "email": "harry.brundage@gmail.com" + }, + { + "name": "Harry Sarson", + "email": "harry.sarson@hotmail.co.uk" + }, + { + "name": "Harry Wolff", + "email": "hswolff@users.noreply.github.com" + }, + { + "name": "Herman Junge", + "email": "herman@geekli.st" + }, + { + "name": "hokaccha", + "email": "k.hokamura@gmail.com" + }, + { + "name": "Honza Javorek", + "email": "mail@honzajavorek.cz" + }, + { + "name": "Hugo Giraudel", + "email": "hugo.giraudel@gmail.com" + }, + { + "name": "Ian Storm Taylor", + "email": "ian@ianstormtaylor.com" + }, + { + "name": "Ian W. Remmel", + "email": "design@ianwremmel.com" + }, + { + "name": "Ian Young", + "email": "ian.greenleaf@gmail.com" + }, + { + "name": "Ian Zamojc", + "email": "ian@thesecretlocation.net" + }, + { + "name": "Igwe Kalu", + "email": "igwe.kalu@live.com" + }, + { + "name": "ImgBot", + "email": "31427850+ImgBotApp@users.noreply.github.com" + }, + { + "name": "inxorable", + "email": "inxorable@codewren.ch" + }, + { + "name": "Ivan", + "email": "ivan@kinvey.com" + }, + { + "name": "Jaakko Salonen", + "email": "jaakko.salonen@iki.fi" + }, + { + "name": "Jacob Wejendorp", + "email": "jacob@wejendorp.dk" + }, + { + "name": "Jake Craige", + "email": "james.craige@gmail.com" + }, + { + "name": "Jake Marsh", + "email": "jakemmarsh@gmail.com" + }, + { + "name": "Jakob Krigovsky", + "email": "jakob@krigovsky.com" + }, + { + "name": "Jakub Nešetřil", + "email": "jakub@apiary.io" + }, + { + "name": "James Bowes", + "email": "jbowes@repl.ca" + }, + { + "name": "James Carr", + "email": "james.r.carr@gmail.com" + }, + { + "name": "James G. Kim", + "email": "jgkim@jayg.org" + }, + { + "name": "James Lal", + "email": "james@lightsofapollo.com" + }, + { + "name": "James Nylen", + "email": "jnylen@gmail.com" + }, + { + "name": "Jan Kopriva", + "email": "jan.kopriva@gooddata.com" + }, + { + "name": "Jan Krems", + "email": "jan.krems@groupon.com" + }, + { + "name": "Jan Lehnardt", + "email": "jan@apache.org" + }, + { + "name": "Jason Barry", + "email": "jay@jcbarry.com" + }, + { + "name": "Jason Lai", + "email": "jason@getpebble.com" + }, + { + "name": "Jason Leyba", + "email": "jmleyba@gmail.com" + }, + { + "name": "Javier Aranda", + "email": "javierav@javierav.com" + }, + { + "name": "Jean Ponchon", + "email": "gelule@gmail.com" + }, + { + "name": "Jeff Kunkle", + "email": "jeff.kunkle@nearinfinity.com" + }, + { + "name": "Jeff Schilling", + "email": "jeff.schilling@q2ebanking.com" + }, + { + "name": "JeongHoon Byun", + "email": "outsideris@gmail.com", + "url": "aka Outsider" + }, + { + "name": "Jérémie Astori", + "email": "jeremie@astori.fr" + }, + { + "name": "Jeremy Martin", + "email": "jmar777@gmail.com" + }, + { + "name": "Jerry Muzsik", + "email": "jerrymuzsik@icloud.com" + }, + { + "name": "Jesse Dailey", + "email": "jesse.dailey@gmail.com" + }, + { + "name": "jimenglish81", + "email": "jimenglish81@gmail.com" + }, + { + "name": "Jimmy Cuadra", + "email": "jimmy@jimmycuadra.com" + }, + { + "name": "Jo Liss", + "email": "joliss42@gmail.com" + }, + { + "name": "Joao Moreno", + "email": "mail@joaomoreno.com" + }, + { + "name": "Joel Kemp", + "email": "mrjoelkemp@gmail.com" + }, + { + "name": "Joey Cozza", + "email": "joey@grow.com" + }, + { + "name": "John Doty", + "email": "jrhdoty@gmail.com" + }, + { + "name": "John Firebaugh", + "email": "john.firebaugh@gmail.com" + }, + { + "name": "John Reeves", + "email": "github@jonnyreeves.co.uk" + }, + { + "name": "Johnathon Sanders", + "email": "outdooricon@gmail.com" + }, + { + "name": "Jon Surrell", + "email": "jon.surrell@automattic.com" + }, + { + "name": "Jonas Dohse", + "email": "jonas@mbr-targeting.com" + }, + { + "name": "Jonas Westerlund", + "email": "jonas.westerlund@me.com" + }, + { + "name": "Jonathan Creamer", + "email": "matrixhasyou2k4@gmail.com" + }, + { + "name": "Jonathan Delgado", + "email": "jdelgado@rewip.com" + }, + { + "name": "Jonathan Kim", + "email": "jkimbo@gmail.com" + }, + { + "name": "Jonathan Ong", + "email": "jonathanrichardong@gmail.com" + }, + { + "name": "Jonathan Park", + "email": "jpark@daptiv.com" + }, + { + "name": "Jonathan Rajavuori", + "email": "jrajav@gmail.com" + }, + { + "name": "Jordan Sexton", + "email": "jordan@jordansexton.com" + }, + { + "name": "Joseph Lin", + "email": "josephlin55555@gmail.com" + }, + { + "name": "Josh Eversmann", + "email": "josh.eversmann@gmail.com" + }, + { + "name": "Josh Lory", + "email": "josh.lory@code.org" + }, + { + "name": "Josh Soref", + "email": "jsoref@users.noreply.github.com" + }, + { + "name": "Joshua Appelman", + "email": "jappelman@xebia.com" + }, + { + "name": "Joshua Krall", + "email": "joshuakrall@pobox.com" + }, + { + "name": "JP Bochi", + "email": "jpbochi@gmail.com" + }, + { + "name": "jsdevel", + "email": "js.developer.undefined@gmail.com" + }, + { + "name": "Julien Wajsberg", + "email": "felash@gmail.com" + }, + { + "name": "Jupp Müller", + "email": "jupp0r@gmail.com" + }, + { + "name": "Jussi Virtanen", + "email": "jussi.k.virtanen@gmail.com" + }, + { + "name": "Justin DuJardin", + "email": "justin.dujardin@sococo.com" + }, + { + "name": "Juzer Ali", + "email": "er.juzerali@gmail.com" + }, + { + "name": "Katie Gengler", + "email": "katiegengler@gmail.com" + }, + { + "name": "kavun", + "email": "kevin.a.reed@gmail.com" + }, + { + "name": "Kazuhito Hokamura", + "email": "k.hokamura@gmail.com" + }, + { + "name": "Keith Cirkel", + "email": "github@keithcirkel.co.uk" + }, + { + "name": "Kelong Wang", + "email": "buaawkl@gmail.com" + }, + { + "name": "Kent C. Dodds", + "email": "kent+github@doddsfamily.us" + }, + { + "name": "Kevin Burke", + "email": "kev@inburke.com" + }, + { + "name": "Kevin Conway", + "email": "kevinjacobconway@gmail.com" + }, + { + "name": "Kevin Kirsche", + "email": "Kev.Kirsche+GitHub@gmail.com" + }, + { + "name": "Kevin Partington", + "email": "platinum.azure@kernelpanicstudios.com" + }, + { + "name": "Kevin Wang", + "email": "kevin@fossa.io" + }, + { + "name": "Kirill Korolyov", + "email": "kirill.korolyov@gmail.com" + }, + { + "name": "klaemo", + "email": "klaemo@fastmail.fm" + }, + { + "name": "Koen Punt", + "email": "koen@koenpunt.nl" + }, + { + "name": "Konstantin Käfer", + "email": "github@kkaefer.com" + }, + { + "name": "Kris Rasmussen", + "email": "kristopher.rasmussen@gmail.com" + }, + { + "name": "Kunal Nagpal", + "email": "kunagpal@users.noreply.github.com" + }, + { + "name": "Kyle Mitchell", + "email": "kyle@kemitchell.com" + }, + { + "name": "lakmeer", + "email": "lakmeerkravid@gmail.com" + }, + { + "name": "Lane Kelly", + "email": "lanekelly16@gmail.com" + }, + { + "name": "László Bácsi", + "email": "lackac@lackac.hu" + }, + { + "name": "Laurence Rowe", + "email": "lrowe@netflix.com" + }, + { + "name": "Liam Newman", + "email": "bitwiseman@gmail.com" + }, + { + "name": "Linus Unnebäck", + "email": "linus@folkdatorn.se" + }, + { + "name": "lodr", + "email": "salva@unoyunodiez.com" + }, + { + "name": "Long Ho", + "email": "longlho@users.noreply.github.com" + }, + { + "name": "Maciej Małecki", + "email": "maciej.malecki@notimplemented.org" + }, + { + "name": "Mal Graty", + "email": "mal.graty@googlemail.com" + }, + { + "name": "Marais Rossouw", + "email": "me@maraisr.com" + }, + { + "name": "Marc Kuo", + "email": "kuomarc2@gmail.com" + }, + { + "name": "Marcello Bastea-Forte", + "email": "marcello@cellosoft.com" + }, + { + "name": "Mark Banner", + "email": "standard8@mozilla.com" + }, + { + "name": "Markus Tacker", + "email": "m@coderbyheart.com" + }, + { + "name": "Martin Marko", + "email": "marcus@gratex.com" + }, + { + "name": "Mathieu Desvé", + "email": "mathieudesve@MacBook-Pro-de-Mathieu.local" + }, + { + "name": "Matija Marohnić", + "email": "matija.marohnic@gmail.com" + }, + { + "name": "Matt Bierner", + "email": "mattbierner@gmail.com" + }, + { + "name": "Matt Giles", + "email": "matt.giles@cerner.com" + }, + { + "name": "Matt Robenolt", + "email": "matt@ydekproductions.com" + }, + { + "name": "Matt Smith", + "email": "matthewgarysmith@gmail.com" + }, + { + "name": "Matthew Shanley", + "email": "matthewshanley@littlesecretsrecords.com" + }, + { + "name": "Mattias Tidlund", + "email": "mattias.tidlund@learningwell.se" + }, + { + "name": "Max Goodman", + "email": "c@chromakode.com" + }, + { + "name": "Maximilian Antoni", + "email": "mail@maxantoni.de" + }, + { + "name": "Merrick Christensen", + "email": "merrick.christensen@gmail.com" + }, + { + "name": "Michael Demmer", + "email": "demmer@jut.io" + }, + { + "name": "Michael Jackson", + "email": "mjijackson@gmail.com" + }, + { + "name": "Michael Olson", + "email": "mwolson@member.fsf.org" + }, + { + "name": "Michael Riley", + "email": "michael.riley@autodesk.com" + }, + { + "name": "Michael Schoonmaker", + "email": "michael.r.schoonmaker@gmail.com" + }, + { + "name": "Michal Charemza", + "email": "michalcharemza@gmail.com" + }, + { + "name": "Michiel de Jong", + "email": "michiel@unhosted.org" + }, + { + "name": "Mick Brooks", + "email": "mick.brooks@sinking.in" + }, + { + "name": "Mike Pennisi", + "email": "mike@mikepennisi.com" + }, + { + "name": "Mislav Marohnić", + "email": "mislav.marohnic@gmail.com" + }, + { + "name": "monowerker", + "email": "monowerker@gmail.com" + }, + { + "name": "Moshe Kolodny", + "email": "mkolodny@integralads.com" + }, + { + "name": "mrShturman", + "email": "mrshturman@gmail.com" + }, + { + "name": "Nathan Alderson", + "email": "nathan.alderson@adtran.com" + }, + { + "name": "Nathan Black", + "email": "nathan@nathanblack.org" + }, + { + "name": "Nathan Bowser", + "email": "nathan.bowser@spiderstrategies.com" + }, + { + "name": "Nathan Houle", + "email": "nathan@nathanhoule.com" + }, + { + "name": "Nathan Rajlich", + "email": "nathan@tootallnate.net" + }, + { + "name": "nexdrew", + "email": "andrew.goode@nextraq.com" + }, + { + "name": "Nick Fitzgerald", + "email": "fitzgen@gmail.com" + }, + { + "name": "Nicolas Girault", + "email": "nic.girault@gmail.com" + }, + { + "name": "Nicolo Taddei", + "email": "taddei.uk@gmail.com" + }, + { + "name": "Nik Nyby", + "email": "nnyby@columbia.edu" + }, + { + "name": "Nikolaos Georgiou", + "email": "Nikolaos.Georgiou@gmail.com" + }, + { + "name": "nishigori", + "email": "Takuya_Nishigori@voyagegroup.com" + }, + { + "name": "Noshir Patel", + "email": "nosh@blackpiano.com" + }, + { + "name": "not-an-aardvark", + "email": "not-an-aardvark@users.noreply.github.com" + }, + { + "name": "OlegTsyba", + "email": "oleg.tsyba.ua@gmail.com" + }, + { + "name": "olsonpm", + "email": "olsonpm@users.noreply.github.com" + }, + { + "name": "omardelarosa", + "email": "thedelarosa@gmail.com" + }, + { + "name": "Oscar Godson", + "email": "oscargodson@outlook.com" + }, + { + "name": "Outsider", + "email": "outsideris@gmail.com" + }, + { + "name": "oveddan", + "email": "stangogh@gmail.com" + }, + { + "name": "Panu Horsmalahti", + "email": "panu.horsmalahti@iki.fi" + }, + { + "name": "Parker Moore", + "email": "parkrmoore@gmail.com" + }, + { + "name": "Pat Finnigan", + "email": "patrick.k.finnigan@gmail.com" + }, + { + "name": "Paul Armstrong", + "email": "paul@paularmstrongdesigns.com" + }, + { + "name": "Paul Miller", + "email": "paul@paulmillr.com" + }, + { + "name": "Pavel Zubkou", + "email": "pavel.zubkou@gmail.com" + }, + { + "name": "Pete Hawkins", + "email": "pete@petes-imac.frontinternal.net" + }, + { + "name": "Peter Müller", + "email": "munter@fumle.dk" + }, + { + "name": "Peter Rust", + "email": "peter@cornerstonenw.com" + }, + { + "name": "Phil Sung", + "email": "psung@dnanexus.com" + }, + { + "name": "Philip M. White", + "email": "philip@mailworks.org" + }, + { + "name": "PoppinL", + "email": "poppinlp@gmail.com" + }, + { + "name": "Poprádi Árpád", + "email": "popradi.arpad11@gmail.com" + }, + { + "name": "Prayag Verma", + "email": "prayag.verma@gmail.com" + }, + { + "name": "qiuzuhui", + "email": "qiuzuhui@users.noreply.github.com" + }, + { + "name": "Quang Van", + "email": "quangvvv@gmail.com" + }, + { + "name": "Quanlong He", + "email": "kyan.ql.he@gmail.com" + }, + { + "name": "R56", + "email": "rviskus@gmail.com" + }, + { + "name": "Raynos", + "email": "raynos2@gmail.com" + }, + { + "name": "Refael Ackermann", + "email": "refael@empeeric.com" + }, + { + "name": "Rich Trott", + "email": "rtrott@gmail.com" + }, + { + "name": "Richard Dingwall", + "email": "rdingwall@gmail.com" + }, + { + "name": "Richard Knop", + "email": "RichardKnop@users.noreply.github.com" + }, + { + "name": "Rico Sta. Cruz", + "email": "rstacruz@users.noreply.github.com" + }, + { + "name": "rmacklin", + "email": "richard.github@nrm.com" + }, + { + "name": "Rob Loach", + "email": "robloach@gmail.com" + }, + { + "name": "Rob Raux", + "email": "rraux@peachworks.com" + }, + { + "name": "Rob Wu", + "email": "rob@robwu.nl" + }, + { + "name": "Robert Rossmann", + "email": "rr.rossmann@me.com" + }, + { + "name": "Romain Prieto", + "email": "romain.prieto@gmail.com" + }, + { + "name": "Roman Neuhauser", + "email": "rneuhauser@suse.cz" + }, + { + "name": "Roman Shtylman", + "email": "shtylman@gmail.com" + }, + { + "name": "Ross Warren", + "email": "rosswarren4@gmail.com" + }, + { + "name": "rotemdan", + "email": "rotemdan@gmail.com" + }, + { + "name": "Russ Bradberry", + "email": "devdazed@me.com" + }, + { + "name": "Russell Munson", + "email": "rmunson@github.com" + }, + { + "name": "Rustem Mustafin", + "email": "mustafin.rustem@gmail.com" + }, + { + "name": "Ryan Hubbard", + "email": "ryanmhubbard@gmail.com" + }, + { + "name": "Ryan Shaw", + "email": "ryan.shaw@min.vc" + }, + { + "name": "Ryan Tablada", + "email": "ryan.tablada@gmail.com" + }, + { + "name": "Ryunosuke SATO", + "email": "tricknotes.rs@gmail.com" + }, + { + "name": "ryym", + "email": "ryym.64@gmail.com" + }, + { + "name": "Salehen Shovon Rahman", + "email": "salehen.rahman@gmail.com" + }, + { + "name": "Sam Mussell", + "email": "smussell@gmail.com" + }, + { + "name": "samuel goldszmidt", + "email": "samuel.goldszmidt@gmail.com" + }, + { + "name": "sarehag", + "email": "joakim.sarehag@gmail.com" + }, + { + "name": "Sasha Koss", + "email": "koss@nocorp.me" + }, + { + "name": "Scott Kao", + "email": "Scottkao85@users.noreply.github.com" + }, + { + "name": "Scott Santucci", + "email": "ScottFreeCode@users.noreply.github.com" + }, + { + "name": "ScottFreeCode", + "email": "ScottFreeCode@users.noreply.github.com" + }, + { + "name": "Sean Lang", + "email": "slang800@gmail.com" + }, + { + "name": "Sebastian Van Sande", + "email": "sebastian@vansande.org" + }, + { + "name": "sebv", + "email": "seb.vincent@gmail.com" + }, + { + "name": "Seiya Konno", + "email": "nulltask@gmail.com" + }, + { + "name": "Sergey Simonchik", + "email": "sergey.simonchik@jetbrains.com" + }, + { + "name": "Sergio Santoro", + "email": "santoro.srg@gmail.com" + }, + { + "name": "Shaine Hatch", + "email": "shaine@squidtree.com" + }, + { + "name": "Shawn Krisman", + "email": "telaviv@github" + }, + { + "name": "Shinnosuke Watanabe", + "email": "snnskwtnb@gmail.com" + }, + { + "name": "silentcloud", + "email": "rjmuqiang@gmail.com" + }, + { + "name": "Silvio Massari", + "email": "silvio.massari@auth0.com" + }, + { + "name": "Simon Gaeremynck", + "email": "gaeremyncks@gmail.com" + }, + { + "name": "Simon Goumaz", + "email": "simon@attentif.ch" + }, + { + "name": "simov", + "email": "simeonvelichkov@gmail.com" + }, + { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com" + }, + { + "name": "Slobodan Mišković", + "email": "slobodan@miskovic.ca" + }, + { + "name": "slyg", + "email": "syl.faucherand@gmail.com" + }, + { + "name": "Soel", + "email": "shachar.soel@sap.com" + }, + { + "name": "solodynamo", + "email": "bittuf3@gmail.com" + }, + { + "name": "Sorin Iclanzan", + "email": "sorin@iclanzan.com" + }, + { + "name": "Standa Opichal", + "email": "opichals@gmail.com" + }, + { + "name": "startswithaj", + "email": "jake.mc@icloud.com" + }, + { + "name": "Stephen Mathieson", + "email": "smath23@gmail.com" + }, + { + "name": "Steve Mason", + "email": "stevem@brandwatch.com" + }, + { + "name": "Stewart Taylor", + "email": "stewart.taylor1@gmail.com" + }, + { + "name": "Stone", + "email": "baoshi.li@adleida.com" + }, + { + "name": "Sulabh Bista", + "email": "sul4bh@gmail.com" + }, + { + "name": "Sune Simonsen", + "email": "sune@we-knowhow.dk" + }, + { + "name": "Tapiwa Kelvin", + "email": "tapiwa@munzwa.tk" + }, + { + "name": "Ted Yavuzkurt", + "email": "hello@TedY.io" + }, + { + "name": "Teddy Zeenny", + "email": "teddyzeenny@gmail.com" + }, + { + "name": "tgautier@yahoo.com", + "email": "tgautier@gmail.com" + }, + { + "name": "Thedark1337", + "email": "thedark1337@thedark1337.com" + }, + { + "name": "Thomas Broadley", + "email": "buriedunderbooks@hotmail.com" + }, + { + "name": "Thomas Grainger", + "email": "tagrain@gmail.com" + }, + { + "name": "Thomas Vantuycom", + "email": "thomasvantuycom@protonmail.com" + }, + { + "name": "Tim Ehat", + "email": "timehat@gmail.com" + }, + { + "name": "Timo Tijhof", + "email": "krinklemail@gmail.com" + }, + { + "name": "Timothy Gu", + "email": "timothygu99@gmail.com" + }, + { + "name": "Tingan Ho", + "email": "tingan87@gmail.com" + }, + { + "name": "tmont", + "email": "tommy.mont@gmail.com" + }, + { + "name": "Tobias Bieniek", + "email": "tobias.bieniek@gmail.com" + }, + { + "name": "Todd Agulnick", + "email": "tagulnick@onjack.com" + }, + { + "name": "Tom Coquereau", + "email": "tom@thau.me" + }, + { + "name": "Tom Hughes", + "email": "tom@compton.nu" + }, + { + "name": "Tomer Eskenazi", + "email": "tomer.eskenazi@ironsrc.com" + }, + { + "name": "traleig1", + "email": "darkphoenix739@gmail.com" + }, + { + "name": "Travis Jeffery", + "email": "tj@travisjeffery.com" + }, + { + "name": "tripu", + "email": "t@tripu.info" + }, + { + "name": "Tyson Tate", + "email": "tyson@tysontate.com" + }, + { + "name": "Vadim Nikitin", + "email": "vnikiti@ncsu.edu" + }, + { + "name": "Valentin Agachi", + "email": "github.com@agachi.name" + }, + { + "name": "Valeri Karpov", + "email": "val@karpov.io" + }, + { + "name": "Victor", + "email": "victor@turo.com" + }, + { + "name": "Victor Costan", + "email": "costan@gmail.com" + }, + { + "name": "Ville Saukkonen", + "email": "villesau@users.noreply.github.com" + }, + { + "name": "Vivek Ganesan", + "email": "caliberoviv@gmail.com" + }, + { + "name": "vlad", + "email": "iamvlad@gmail.com" + }, + { + "name": "Vlad Magdalin", + "email": "vlad@webflow.com" + }, + { + "name": "Volker Buzek", + "email": "volker.buzek@sap.com" + }, + { + "name": "Wil Moore III", + "email": "wil.moore@wilmoore.com" + }, + { + "name": "Will Langstroth", + "email": "will@langstroth.com" + }, + { + "name": "wsw", + "email": "wsw0108@gmail.com" + }, + { + "name": "Xavier Antoviaque", + "email": "xavier@antoviaque.org" + }, + { + "name": "Xavier Damman", + "email": "xdamman@gmail.com" + }, + { + "name": "XhmikosR", + "email": "xhmikosr@users.sourceforge.net" + }, + { + "name": "Yanis Wang", + "email": "yanis.wang@gmail.com" + }, + { + "name": "yehiyam", + "email": "yehiyam@users.noreply.github.com" + }, + { + "name": "Yoshiya Hinosawa", + "email": "hinosawa@waku-2.com" + }, + { + "name": "Yuest Wang", + "email": "yuestwang@gmail.com" + }, + { + "name": "yuitest", + "email": "yuitest@cjhat.net" + }, + { + "name": "zhiyelee", + "email": "zhiyelee@gmail.com" + }, + { + "name": "Zsolt Takács", + "email": "zsolt@takacs.cc" + }, + { + "name": "现充", + "email": "qixiang.cqx@alibaba-inc.com" + } + ], + "dependencies": { + "browser-stdout": "1.3.1", + "commander": "2.15.1", + "debug": "3.1.0", + "diff": "3.5.0", + "escape-string-regexp": "1.0.5", + "glob": "7.1.2", + "growl": "1.10.5", + "he": "1.1.1", + "minimatch": "3.0.4", + "mkdirp": "0.5.1", + "supports-color": "5.4.0" + }, + "deprecated": false, + "description": "simple, flexible, fun test framework", + "devDependencies": { + "@mocha/docdash": "^1.0.1", + "assetgraph-builder": "^6.2.0", + "browserify": "^16.2.2", + "chai": "^4.1.2", + "coffee-script": "^1.10.0", + "coveralls": "^3.0.1", + "cross-spawn": "^6.0.5", + "eslint": "^4.19.1", + "eslint-config-prettier": "^2.9.0", + "eslint-config-semistandard": "^12.0.1", + "eslint-config-standard": "^11.0.0", + "eslint-plugin-import": "^2.11.0", + "eslint-plugin-node": "^6.0.1", + "eslint-plugin-prettier": "^2.6.0", + "eslint-plugin-promise": "^3.7.0", + "eslint-plugin-standard": "^3.0.1", + "husky": "^0.14.3", + "jsdoc": "^3.5.5", + "karma": "^2.0.2", + "karma-browserify": "^5.0.5", + "karma-chrome-launcher": "^2.0.0", + "karma-mocha": "^1.3.0", + "karma-mocha-reporter": "^2.2.4", + "karma-sauce-launcher": "^1.2.0", + "lint-staged": "^7.1.0", + "markdown-toc": "^1.2.0", + "markdownlint-cli": "^0.8.1", + "nps": "^5.7.1", + "nyc": "^11.7.3", + "prettier-eslint-cli": "^4.7.1", + "rimraf": "^2.5.2", + "svgo": "^1.0.5", + "through2": "^2.0.1", + "unexpected": "^10.37.7", + "watchify": "^3.7.0" + }, + "engines": { + "node": ">= 4.0.0" + }, + "files": [ + "bin", + "images", + "lib", + "index.js", + "mocha.css", + "mocha.js", + "browser-entry.js" + ], + "homepage": "https://mochajs.org", + "keywords": [ + "mocha", + "test", + "bdd", + "tdd", + "tap" + ], + "license": "MIT", + "logo": "https://cldup.com/S9uQ-cOLYz.svg", + "name": "mocha", + "prettier": { + "singleQuote": true, + "bracketSpacing": false + }, + "repository": { + "type": "git", + "url": "git+https://github.com/mochajs/mocha.git" + }, + "scripts": { + "precommit": "lint-staged", + "prepublishOnly": "nps test clean build", + "start": "nps", + "test": "nps test" + }, + "version": "5.2.0" +} diff --git a/node_modules/ms/index.js b/node_modules/ms/index.js new file mode 100644 index 0000000..6a522b1 --- /dev/null +++ b/node_modules/ms/index.js @@ -0,0 +1,152 @@ +/** + * Helpers. + */ + +var s = 1000; +var m = s * 60; +var h = m * 60; +var d = h * 24; +var y = d * 365.25; + +/** + * Parse or format the given `val`. + * + * Options: + * + * - `long` verbose formatting [false] + * + * @param {String|Number} val + * @param {Object} [options] + * @throws {Error} throw an error if val is not a non-empty string or a number + * @return {String|Number} + * @api public + */ + +module.exports = function(val, options) { + options = options || {}; + var type = typeof val; + if (type === 'string' && val.length > 0) { + return parse(val); + } else if (type === 'number' && isNaN(val) === false) { + return options.long ? fmtLong(val) : fmtShort(val); + } + throw new Error( + 'val is not a non-empty string or a valid number. val=' + + JSON.stringify(val) + ); +}; + +/** + * Parse the given `str` and return milliseconds. + * + * @param {String} str + * @return {Number} + * @api private + */ + +function parse(str) { + str = String(str); + if (str.length > 100) { + return; + } + var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec( + str + ); + if (!match) { + return; + } + var n = parseFloat(match[1]); + var type = (match[2] || 'ms').toLowerCase(); + switch (type) { + case 'years': + case 'year': + case 'yrs': + case 'yr': + case 'y': + return n * y; + case 'days': + case 'day': + case 'd': + return n * d; + case 'hours': + case 'hour': + case 'hrs': + case 'hr': + case 'h': + return n * h; + case 'minutes': + case 'minute': + case 'mins': + case 'min': + case 'm': + return n * m; + case 'seconds': + case 'second': + case 'secs': + case 'sec': + case 's': + return n * s; + case 'milliseconds': + case 'millisecond': + case 'msecs': + case 'msec': + case 'ms': + return n; + default: + return undefined; + } +} + +/** + * Short format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + +function fmtShort(ms) { + if (ms >= d) { + return Math.round(ms / d) + 'd'; + } + if (ms >= h) { + return Math.round(ms / h) + 'h'; + } + if (ms >= m) { + return Math.round(ms / m) + 'm'; + } + if (ms >= s) { + return Math.round(ms / s) + 's'; + } + return ms + 'ms'; +} + +/** + * Long format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + +function fmtLong(ms) { + return plural(ms, d, 'day') || + plural(ms, h, 'hour') || + plural(ms, m, 'minute') || + plural(ms, s, 'second') || + ms + ' ms'; +} + +/** + * Pluralization helper. + */ + +function plural(ms, n, name) { + if (ms < n) { + return; + } + if (ms < n * 1.5) { + return Math.floor(ms / n) + ' ' + name; + } + return Math.ceil(ms / n) + ' ' + name + 's'; +} diff --git a/node_modules/ms/license.md b/node_modules/ms/license.md new file mode 100644 index 0000000..69b6125 --- /dev/null +++ b/node_modules/ms/license.md @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2016 Zeit, Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/ms/package.json b/node_modules/ms/package.json new file mode 100644 index 0000000..e7f5487 --- /dev/null +++ b/node_modules/ms/package.json @@ -0,0 +1,69 @@ +{ + "_from": "ms@2.0.0", + "_id": "ms@2.0.0", + "_inBundle": false, + "_integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", + "_location": "/ms", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "ms@2.0.0", + "name": "ms", + "escapedName": "ms", + "rawSpec": "2.0.0", + "saveSpec": null, + "fetchSpec": "2.0.0" + }, + "_requiredBy": [ + "/debug" + ], + "_resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "_shasum": "5608aeadfc00be6c2901df5f9861788de0d597c8", + "_spec": "ms@2.0.0", + "_where": "/Users/jessitron/code/jessitron/stringify-tree/node_modules/debug", + "bugs": { + "url": "https://github.com/zeit/ms/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "Tiny milisecond conversion utility", + "devDependencies": { + "eslint": "3.19.0", + "expect.js": "0.3.1", + "husky": "0.13.3", + "lint-staged": "3.4.1", + "mocha": "3.4.1" + }, + "eslintConfig": { + "extends": "eslint:recommended", + "env": { + "node": true, + "es6": true + } + }, + "files": [ + "index.js" + ], + "homepage": "https://github.com/zeit/ms#readme", + "license": "MIT", + "lint-staged": { + "*.js": [ + "npm run lint", + "prettier --single-quote --write", + "git add" + ] + }, + "main": "./index", + "name": "ms", + "repository": { + "type": "git", + "url": "git+https://github.com/zeit/ms.git" + }, + "scripts": { + "lint": "eslint lib/* bin/*", + "precommit": "lint-staged", + "test": "mocha tests.js" + }, + "version": "2.0.0" +} diff --git a/node_modules/ms/readme.md b/node_modules/ms/readme.md new file mode 100644 index 0000000..84a9974 --- /dev/null +++ b/node_modules/ms/readme.md @@ -0,0 +1,51 @@ +# ms + +[![Build Status](https://travis-ci.org/zeit/ms.svg?branch=master)](https://travis-ci.org/zeit/ms) +[![Slack Channel](http://zeit-slackin.now.sh/badge.svg)](https://zeit.chat/) + +Use this package to easily convert various time formats to milliseconds. + +## Examples + +```js +ms('2 days') // 172800000 +ms('1d') // 86400000 +ms('10h') // 36000000 +ms('2.5 hrs') // 9000000 +ms('2h') // 7200000 +ms('1m') // 60000 +ms('5s') // 5000 +ms('1y') // 31557600000 +ms('100') // 100 +``` + +### Convert from milliseconds + +```js +ms(60000) // "1m" +ms(2 * 60000) // "2m" +ms(ms('10 hours')) // "10h" +``` + +### Time format written-out + +```js +ms(60000, { long: true }) // "1 minute" +ms(2 * 60000, { long: true }) // "2 minutes" +ms(ms('10 hours'), { long: true }) // "10 hours" +``` + +## Features + +- Works both in [node](https://nodejs.org) and in the browser. +- If a number is supplied to `ms`, a string with a unit is returned. +- If a string that contains the number is supplied, it returns it as a number (e.g.: it returns `100` for `'100'`). +- If you pass a string with a number and a valid unit, the number of equivalent ms is returned. + +## Caught a bug? + +1. [Fork](https://help.github.com/articles/fork-a-repo/) this repository to your own GitHub account and then [clone](https://help.github.com/articles/cloning-a-repository/) it to your local device +2. Link the package to the global module directory: `npm link` +3. Within the module you want to test your local development instance of ms, just link it to the dependencies: `npm link ms`. Instead of the default one from npm, node will now use your clone of ms! + +As always, you can run the tests using: `npm test` diff --git a/node_modules/once/LICENSE b/node_modules/once/LICENSE new file mode 100644 index 0000000..19129e3 --- /dev/null +++ b/node_modules/once/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/once/README.md b/node_modules/once/README.md new file mode 100644 index 0000000..1f1ffca --- /dev/null +++ b/node_modules/once/README.md @@ -0,0 +1,79 @@ +# once + +Only call a function once. + +## usage + +```javascript +var once = require('once') + +function load (file, cb) { + cb = once(cb) + loader.load('file') + loader.once('load', cb) + loader.once('error', cb) +} +``` + +Or add to the Function.prototype in a responsible way: + +```javascript +// only has to be done once +require('once').proto() + +function load (file, cb) { + cb = cb.once() + loader.load('file') + loader.once('load', cb) + loader.once('error', cb) +} +``` + +Ironically, the prototype feature makes this module twice as +complicated as necessary. + +To check whether you function has been called, use `fn.called`. Once the +function is called for the first time the return value of the original +function is saved in `fn.value` and subsequent calls will continue to +return this value. + +```javascript +var once = require('once') + +function load (cb) { + cb = once(cb) + var stream = createStream() + stream.once('data', cb) + stream.once('end', function () { + if (!cb.called) cb(new Error('not found')) + }) +} +``` + +## `once.strict(func)` + +Throw an error if the function is called twice. + +Some functions are expected to be called only once. Using `once` for them would +potentially hide logical errors. + +In the example below, the `greet` function has to call the callback only once: + +```javascript +function greet (name, cb) { + // return is missing from the if statement + // when no name is passed, the callback is called twice + if (!name) cb('Hello anonymous') + cb('Hello ' + name) +} + +function log (msg) { + console.log(msg) +} + +// this will print 'Hello anonymous' but the logical error will be missed +greet(null, once(msg)) + +// once.strict will print 'Hello anonymous' and throw an error when the callback will be called the second time +greet(null, once.strict(msg)) +``` diff --git a/node_modules/once/once.js b/node_modules/once/once.js new file mode 100644 index 0000000..2354067 --- /dev/null +++ b/node_modules/once/once.js @@ -0,0 +1,42 @@ +var wrappy = require('wrappy') +module.exports = wrappy(once) +module.exports.strict = wrappy(onceStrict) + +once.proto = once(function () { + Object.defineProperty(Function.prototype, 'once', { + value: function () { + return once(this) + }, + configurable: true + }) + + Object.defineProperty(Function.prototype, 'onceStrict', { + value: function () { + return onceStrict(this) + }, + configurable: true + }) +}) + +function once (fn) { + var f = function () { + if (f.called) return f.value + f.called = true + return f.value = fn.apply(this, arguments) + } + f.called = false + return f +} + +function onceStrict (fn) { + var f = function () { + if (f.called) + throw new Error(f.onceError) + f.called = true + return f.value = fn.apply(this, arguments) + } + var name = fn.name || 'Function wrapped with `once`' + f.onceError = name + " shouldn't be called more than once" + f.called = false + return f +} diff --git a/node_modules/once/package.json b/node_modules/once/package.json new file mode 100644 index 0000000..3711cb2 --- /dev/null +++ b/node_modules/once/package.json @@ -0,0 +1,67 @@ +{ + "_from": "once@^1.3.0", + "_id": "once@1.4.0", + "_inBundle": false, + "_integrity": "sha1-WDsap3WWHUsROsF9nFC6753Xa9E=", + "_location": "/once", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "once@^1.3.0", + "name": "once", + "escapedName": "once", + "rawSpec": "^1.3.0", + "saveSpec": null, + "fetchSpec": "^1.3.0" + }, + "_requiredBy": [ + "/glob", + "/inflight" + ], + "_resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "_shasum": "583b1aa775961d4b113ac17d9c50baef9dd76bd1", + "_spec": "once@^1.3.0", + "_where": "/Users/jessitron/code/jessitron/stringify-tree/node_modules/glob", + "author": { + "name": "Isaac Z. Schlueter", + "email": "i@izs.me", + "url": "http://blog.izs.me/" + }, + "bugs": { + "url": "https://github.com/isaacs/once/issues" + }, + "bundleDependencies": false, + "dependencies": { + "wrappy": "1" + }, + "deprecated": false, + "description": "Run a function exactly one time", + "devDependencies": { + "tap": "^7.0.1" + }, + "directories": { + "test": "test" + }, + "files": [ + "once.js" + ], + "homepage": "https://github.com/isaacs/once#readme", + "keywords": [ + "once", + "function", + "one", + "single" + ], + "license": "ISC", + "main": "once.js", + "name": "once", + "repository": { + "type": "git", + "url": "git://github.com/isaacs/once.git" + }, + "scripts": { + "test": "tap test/*.js" + }, + "version": "1.4.0" +} diff --git a/node_modules/path-is-absolute/index.js b/node_modules/path-is-absolute/index.js new file mode 100644 index 0000000..22aa6c3 --- /dev/null +++ b/node_modules/path-is-absolute/index.js @@ -0,0 +1,20 @@ +'use strict'; + +function posix(path) { + return path.charAt(0) === '/'; +} + +function win32(path) { + // https://github.com/nodejs/node/blob/b3fcc245fb25539909ef1d5eaa01dbf92e168633/lib/path.js#L56 + var splitDeviceRe = /^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/; + var result = splitDeviceRe.exec(path); + var device = result[1] || ''; + var isUnc = Boolean(device && device.charAt(1) !== ':'); + + // UNC paths are always absolute + return Boolean(result[2] || isUnc); +} + +module.exports = process.platform === 'win32' ? win32 : posix; +module.exports.posix = posix; +module.exports.win32 = win32; diff --git a/node_modules/path-is-absolute/license b/node_modules/path-is-absolute/license new file mode 100644 index 0000000..654d0bf --- /dev/null +++ b/node_modules/path-is-absolute/license @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/path-is-absolute/package.json b/node_modules/path-is-absolute/package.json new file mode 100644 index 0000000..c6a38a7 --- /dev/null +++ b/node_modules/path-is-absolute/package.json @@ -0,0 +1,75 @@ +{ + "_from": "path-is-absolute@^1.0.0", + "_id": "path-is-absolute@1.0.1", + "_inBundle": false, + "_integrity": "sha1-F0uSaHNVNP+8es5r9TpanhtcX18=", + "_location": "/path-is-absolute", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "path-is-absolute@^1.0.0", + "name": "path-is-absolute", + "escapedName": "path-is-absolute", + "rawSpec": "^1.0.0", + "saveSpec": null, + "fetchSpec": "^1.0.0" + }, + "_requiredBy": [ + "/glob" + ], + "_resolved": "http://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", + "_shasum": "174b9268735534ffbc7ace6bf53a5a9e1b5c5f5f", + "_spec": "path-is-absolute@^1.0.0", + "_where": "/Users/jessitron/code/jessitron/stringify-tree/node_modules/glob", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "bugs": { + "url": "https://github.com/sindresorhus/path-is-absolute/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "Node.js 0.12 path.isAbsolute() ponyfill", + "devDependencies": { + "xo": "^0.16.0" + }, + "engines": { + "node": ">=0.10.0" + }, + "files": [ + "index.js" + ], + "homepage": "https://github.com/sindresorhus/path-is-absolute#readme", + "keywords": [ + "path", + "paths", + "file", + "dir", + "absolute", + "isabsolute", + "is-absolute", + "built-in", + "util", + "utils", + "core", + "ponyfill", + "polyfill", + "shim", + "is", + "detect", + "check" + ], + "license": "MIT", + "name": "path-is-absolute", + "repository": { + "type": "git", + "url": "git+https://github.com/sindresorhus/path-is-absolute.git" + }, + "scripts": { + "test": "xo && node test.js" + }, + "version": "1.0.1" +} diff --git a/node_modules/path-is-absolute/readme.md b/node_modules/path-is-absolute/readme.md new file mode 100644 index 0000000..8dbdf5f --- /dev/null +++ b/node_modules/path-is-absolute/readme.md @@ -0,0 +1,59 @@ +# path-is-absolute [![Build Status](https://travis-ci.org/sindresorhus/path-is-absolute.svg?branch=master)](https://travis-ci.org/sindresorhus/path-is-absolute) + +> Node.js 0.12 [`path.isAbsolute()`](http://nodejs.org/api/path.html#path_path_isabsolute_path) [ponyfill](https://ponyfill.com) + + +## Install + +``` +$ npm install --save path-is-absolute +``` + + +## Usage + +```js +const pathIsAbsolute = require('path-is-absolute'); + +// Running on Linux +pathIsAbsolute('/home/foo'); +//=> true +pathIsAbsolute('C:/Users/foo'); +//=> false + +// Running on Windows +pathIsAbsolute('C:/Users/foo'); +//=> true +pathIsAbsolute('/home/foo'); +//=> false + +// Running on any OS +pathIsAbsolute.posix('/home/foo'); +//=> true +pathIsAbsolute.posix('C:/Users/foo'); +//=> false +pathIsAbsolute.win32('C:/Users/foo'); +//=> true +pathIsAbsolute.win32('/home/foo'); +//=> false +``` + + +## API + +See the [`path.isAbsolute()` docs](http://nodejs.org/api/path.html#path_path_isabsolute_path). + +### pathIsAbsolute(path) + +### pathIsAbsolute.posix(path) + +POSIX specific version. + +### pathIsAbsolute.win32(path) + +Windows specific version. + + +## License + +MIT © [Sindre Sorhus](https://sindresorhus.com) diff --git a/node_modules/source-map-support/LICENSE.md b/node_modules/source-map-support/LICENSE.md new file mode 100644 index 0000000..6247ca9 --- /dev/null +++ b/node_modules/source-map-support/LICENSE.md @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014 Evan Wallace + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/source-map-support/README.md b/node_modules/source-map-support/README.md new file mode 100644 index 0000000..0e85cc1 --- /dev/null +++ b/node_modules/source-map-support/README.md @@ -0,0 +1,261 @@ +# Source Map Support +[![Build Status](https://travis-ci.org/evanw/node-source-map-support.svg?branch=master)](https://travis-ci.org/evanw/node-source-map-support) + +This module provides source map support for stack traces in node via the [V8 stack trace API](https://github.com/v8/v8/wiki/Stack-Trace-API). It uses the [source-map](https://github.com/mozilla/source-map) module to replace the paths and line numbers of source-mapped files with their original paths and line numbers. The output mimics node's stack trace format with the goal of making every compile-to-JS language more of a first-class citizen. Source maps are completely general (not specific to any one language) so you can use source maps with multiple compile-to-JS languages in the same node process. + +## Installation and Usage + +#### Node support + +``` +$ npm install source-map-support +``` + +Source maps can be generated using libraries such as [source-map-index-generator](https://github.com/twolfson/source-map-index-generator). Once you have a valid source map, place a source mapping comment somewhere in the file (usually done automatically or with an option by your transpiler): + +``` +//# sourceMappingURL=path/to/source.map +``` + +If multiple sourceMappingURL comments exist in one file, the last sourceMappingURL comment will be +respected (e.g. if a file mentions the comment in code, or went through multiple transpilers). +The path should either be absolute or relative to the compiled file. + +From here you have two options. + +##### CLI Usage + +```bash +node -r source-map-support/register compiled.js +``` + +##### Programmatic Usage + +Put the following line at the top of the compiled file. + +```js +require('source-map-support').install(); +``` + +It is also possible to install the source map support directly by +requiring the `register` module which can be handy with ES6: + +```js +import 'source-map-support/register' + +// Instead of: +import sourceMapSupport from 'source-map-support' +sourceMapSupport.install() +``` +Note: if you're using babel-register, it includes source-map-support already. + +It is also very useful with Mocha: + +``` +$ mocha --require source-map-support/register tests/ +``` + +#### Browser support + +This library also works in Chrome. While the DevTools console already supports source maps, the V8 engine doesn't and `Error.prototype.stack` will be incorrect without this library. Everything will just work if you deploy your source files using [browserify](http://browserify.org/). Just make sure to pass the `--debug` flag to the browserify command so your source maps are included in the bundled code. + +This library also works if you use another build process or just include the source files directly. In this case, include the file `browser-source-map-support.js` in your page and call `sourceMapSupport.install()`. It contains the whole library already bundled for the browser using browserify. + +```html + + +``` + +This library also works if you use AMD (Asynchronous Module Definition), which is used in tools like [RequireJS](http://requirejs.org/). Just list `browser-source-map-support` as a dependency: + +```html + +``` + +## Options + +This module installs two things: a change to the `stack` property on `Error` objects and a handler for uncaught exceptions that mimics node's default exception handler (the handler can be seen in the demos below). You may want to disable the handler if you have your own uncaught exception handler. This can be done by passing an argument to the installer: + +```js +require('source-map-support').install({ + handleUncaughtExceptions: false +}); +``` + +This module loads source maps from the filesystem by default. You can provide alternate loading behavior through a callback as shown below. For example, [Meteor](https://github.com/meteor) keeps all source maps cached in memory to avoid disk access. + +```js +require('source-map-support').install({ + retrieveSourceMap: function(source) { + if (source === 'compiled.js') { + return { + url: 'original.js', + map: fs.readFileSync('compiled.js.map', 'utf8') + }; + } + return null; + } +}); +``` + +The module will by default assume a browser environment if XMLHttpRequest and window are defined. If either of these do not exist it will instead assume a node environment. +In some rare cases, e.g. when running a browser emulation and where both variables are also set, you can explictly specify the environment to be either 'browser' or 'node'. + +```js +require('source-map-support').install({ + environment: 'node' +}); +``` + +To support files with inline source maps, the `hookRequire` options can be specified, which will monitor all source files for inline source maps. + + +```js +require('source-map-support').install({ + hookRequire: true +}); +``` + +This monkey patches the `require` module loading chain, so is not enabled by default and is not recommended for any sort of production usage. + +## Demos + +#### Basic Demo + +original.js: + +```js +throw new Error('test'); // This is the original code +``` + +compiled.js: + +```js +require('source-map-support').install(); + +throw new Error('test'); // This is the compiled code +// The next line defines the sourceMapping. +//# sourceMappingURL=compiled.js.map +``` + +compiled.js.map: + +```json +{ + "version": 3, + "file": "compiled.js", + "sources": ["original.js"], + "names": [], + "mappings": ";;AAAA,MAAM,IAAI" +} +``` + +Run compiled.js using node (notice how the stack trace uses original.js instead of compiled.js): + +``` +$ node compiled.js + +original.js:1 +throw new Error('test'); // This is the original code + ^ +Error: test + at Object. (original.js:1:7) + at Module._compile (module.js:456:26) + at Object.Module._extensions..js (module.js:474:10) + at Module.load (module.js:356:32) + at Function.Module._load (module.js:312:12) + at Function.Module.runMain (module.js:497:10) + at startup (node.js:119:16) + at node.js:901:3 +``` + +#### TypeScript Demo + +demo.ts: + +```typescript +declare function require(name: string); +require('source-map-support').install(); +class Foo { + constructor() { this.bar(); } + bar() { throw new Error('this is a demo'); } +} +new Foo(); +``` + +Compile and run the file using the TypeScript compiler from the terminal: + +``` +$ npm install source-map-support typescript +$ node_modules/typescript/bin/tsc -sourcemap demo.ts +$ node demo.js + +demo.ts:5 + bar() { throw new Error('this is a demo'); } + ^ +Error: this is a demo + at Foo.bar (demo.ts:5:17) + at new Foo (demo.ts:4:24) + at Object. (demo.ts:7:1) + at Module._compile (module.js:456:26) + at Object.Module._extensions..js (module.js:474:10) + at Module.load (module.js:356:32) + at Function.Module._load (module.js:312:12) + at Function.Module.runMain (module.js:497:10) + at startup (node.js:119:16) + at node.js:901:3 +``` + +#### CoffeeScript Demo + +demo.coffee: + +```coffee +require('source-map-support').install() +foo = -> + bar = -> throw new Error 'this is a demo' + bar() +foo() +``` + +Compile and run the file using the CoffeeScript compiler from the terminal: + +```sh +$ npm install source-map-support coffee-script +$ node_modules/coffee-script/bin/coffee --map --compile demo.coffee +$ node demo.js + +demo.coffee:3 + bar = -> throw new Error 'this is a demo' + ^ +Error: this is a demo + at bar (demo.coffee:3:22) + at foo (demo.coffee:4:3) + at Object. (demo.coffee:5:1) + at Object. (demo.coffee:1:1) + at Module._compile (module.js:456:26) + at Object.Module._extensions..js (module.js:474:10) + at Module.load (module.js:356:32) + at Function.Module._load (module.js:312:12) + at Function.Module.runMain (module.js:497:10) + at startup (node.js:119:16) +``` + +## Tests + +This repo contains both automated tests for node and manual tests for the browser. The automated tests can be run using mocha (type `mocha` in the root directory). To run the manual tests: + +* Build the tests using `build.js` +* Launch the HTTP server (`npm run serve-tests`) and visit + * http://127.0.0.1:1336/amd-test + * http://127.0.0.1:1336/browser-test + * http://127.0.0.1:1336/browserify-test - **Currently not working** due to a bug with browserify (see [pull request #66](https://github.com/evanw/node-source-map-support/pull/66) for details). +* For `header-test`, run `server.js` inside that directory and visit http://127.0.0.1:1337/ + +## License + +This code is available under the [MIT license](http://opensource.org/licenses/MIT). diff --git a/node_modules/source-map-support/browser-source-map-support.js b/node_modules/source-map-support/browser-source-map-support.js new file mode 100644 index 0000000..afa56e3 --- /dev/null +++ b/node_modules/source-map-support/browser-source-map-support.js @@ -0,0 +1,115 @@ +/* + * Support for source maps in V8 stack traces + * https://github.com/evanw/node-source-map-support + */ +/* + The buffer module from node.js, for the browser. + + @author Feross Aboukhadijeh + license MIT +*/ +(this.define||function(N,O){this.sourceMapSupport=O()})("browser-source-map-support",function(N){(function b(p,v,m){function f(d,a){if(!v[d]){if(!p[d]){var l="function"==typeof require&&require;if(!a&&l)return l(d,!0);if(k)return k(d,!0);throw Error("Cannot find module '"+d+"'");}l=v[d]={exports:{}};p[d][0].call(l.exports,function(a){var b=p[d][1][a];return f(b?b:a)},l,l.exports,b,p,v,m)}return v[d].exports}for(var k="function"==typeof require&&require,h=0;hb)return-1;if(58>b)return b-48+52;if(91>b)return b-65;if(123>b)return b-97+26}var k="undefined"!==typeof Uint8Array?Uint8Array:Array;b.toByteArray=function(b){function d(a){u[t++]=a}if(0>16);d((h&65280)>>8);d(h&255)}2===l?(h=f(b.charAt(a))<<2|f(b.charAt(a+1))>>4,d(h&255)):1===l&&(h=f(b.charAt(a))<<10|f(b.charAt(a+1))<<4|f(b.charAt(a+2))>>2,d(h>>8&255),d(h&255));return u};b.fromByteArray=function(b){var d=b.length%3,a="",l;var f=0;for(l=b.length-d;f>18&63)+"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(r>>12&63)+"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(r>>6&63)+"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(r&63);a+=r}switch(d){case 1:r=b[b.length-1];a+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(r>>2);a+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(r<< +4&63);a+="==";break;case 2:r=(b[b.length-2]<<8)+b[b.length-1],a+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(r>>10),a+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(r>>4&63),a+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(r<<2&63),a+="="}return a}})("undefined"===typeof m?this.base64js={}:m)},{}],3:[function(p,v,m){},{}],4:[function(p,v,m){(function(b){var f=Object.prototype.toString,k="function"===typeof b.alloc&& +"function"===typeof b.allocUnsafe&&"function"===typeof b.from;v.exports=function(h,d,a){if("number"===typeof h)throw new TypeError('"value" argument must not be a number');if("ArrayBuffer"===f.call(h).slice(8,-1)){d>>>=0;var l=h.byteLength-d;if(0>l)throw new RangeError("'offset' is out of bounds");if(void 0===a)a=l;else if(a>>>=0,a>l)throw new RangeError("'length' is out of bounds");return k?b.from(h.slice(d,d+a)):new b(new Uint8Array(h.slice(d,d+a)))}if("string"===typeof h){a=d;if("string"!==typeof a|| +""===a)a="utf8";if(!b.isEncoding(a))throw new TypeError('"encoding" must be a valid string encoding');return k?b.from(h,a):new b(h,a)}return k?b.from(h):new b(h)}}).call(this,p("buffer").Buffer)},{buffer:5}],5:[function(p,v,m){function b(e,g,y){if(!(this instanceof b))return new b(e,g,y);var a=typeof e;if("base64"===g&&"string"===a)for(e=e.trim?e.trim():e.replace(/^\s+|\s+$/g,"");0!==e.length%4;)e+="=";if("number"===a)var c=I(e);else if("string"===a)c=b.byteLength(e,g);else if("object"===a)c=I(e.length); +else throw Error("First argument needs to be a number, array or string.");if(b._useTypedArrays)var d=b._augment(new Uint8Array(c));else d=this,d.length=c,d._isBuffer=!0;if(b._useTypedArrays&&"number"===typeof e.byteLength)d._set(e);else{var n=e;if(M(n)||b.isBuffer(n)||n&&"object"===typeof n&&"number"===typeof n.length)for(g=0;g=a))return y?(y=e[g],g+1=a)){var c;y?(g+2>>0)):(g+1>>0);return c}}function d(e,g,a,c){c||(q("boolean"===typeof a,"missing or invalid endian"),q(void 0!==g&&null!==g,"missing offset"),q(g+1=e.length))return e=k(e,g,a,!0),e&32768?-1*(65535-e+1):e}function a(e,g,a,c){c||(q("boolean"===typeof a,"missing or invalid endian"), +q(void 0!==g&&null!==g,"missing offset"),q(g+3=e.length))return e=h(e,g,a,!0),e&2147483648?-1*(4294967295-e+1):e}function l(e,g,a,c){c||(q("boolean"===typeof a,"missing or invalid endian"),q(g+3=y))for(b=0,y=Math.min(y-a,2);b>>8*(c?b:1-b)}function t(e,g,a,c,b){b||(q(void 0!==g&&null!==g,"missing value"),q("boolean"===typeof c,"missing or invalid endian"),q(void 0!==a&&null!==a,"missing offset"),q(a+3=y))for(b=0,y=Math.min(y-a,4);b>>8*(c?b:3-b)&255}function z(e,g,a,c,b){b||(q(void 0!==g&&null!==g,"missing value"),q("boolean"===typeof c,"missing or invalid endian"),q(void 0!==a&&null!==a,"missing offset"),q(a+1=e.length||(0<=g?r(e,g,a,c,b):r(e,65535+g+1,a,c,b))}function c(e,g,a,c,b){b||(q(void 0!==g&&null!==g,"missing value"),q("boolean"===typeof c,"missing or invalid endian"), +q(void 0!==a&&null!==a,"missing offset"),q(a+3=e.length||(0<=g?t(e,g,a,c,b):t(e,4294967295+g+1,a,c,b))}function n(e,g,a,c,b){b||(q(void 0!==g&&null!==g,"missing value"),q("boolean"===typeof c,"missing or invalid endian"),q(void 0!==a&&null!==a,"missing offset"),q(a+3=e.length||G.write(e,g,a,c,23,4)}function x(e,g,a, +c,b){b||(q(void 0!==g&&null!==g,"missing value"),q("boolean"===typeof c,"missing or invalid endian"),q(void 0!==a&&null!==a,"missing offset"),q(a+7=e.length||G.write(e,g,a,c,52,8)}function B(e,g,a){if("number"!==typeof e)return a;e=~~e;if(e>=g)return g;if(0<=e)return e;e+=g;return 0<=e?e:0}function I(e){e=~~Math.ceil(+e);return 0>e?0:e}function M(e){return(Array.isArray||function(e){return"[object Array]"=== +Object.prototype.toString.call(e)})(e)}function K(e){return 16>e?"0"+e.toString(16):e.toString(16)}function L(e){for(var g=[],a=0;a=c)g.push(e.charCodeAt(a));else{var b=a;55296<=c&&57343>=c&&a++;c=encodeURIComponent(e.slice(b,a+1)).substr(1).split("%");for(b=0;b=a.length||g>=e.length);g++)a[g+ +c]=e[g];return g}function F(e){try{return decodeURIComponent(e)}catch(g){return String.fromCharCode(65533)}}function H(e,a){q("number"===typeof e,"cannot write a non-number as a number");q(0<=e,"specified a negative value for writing an unsigned value");q(e<=a,"value is larger than maximum value for type");q(Math.floor(e)===e,"value has a fractional component")}function A(e,a,c){q("number"===typeof e,"cannot write a non-number as a number");q(e<=a,"value larger than maximum allowed value");q(e>=c, +"value smaller than minimum allowed value");q(Math.floor(e)===e,"value has a fractional component")}function D(e,a,c){q("number"===typeof e,"cannot write a non-number as a number");q(e<=a,"value larger than maximum allowed value");q(e>=c,"value smaller than minimum allowed value")}function q(e,a){if(!e)throw Error(a||"Failed assertion");}var E=p("base64-js"),G=p("ieee754");m.Buffer=b;m.SlowBuffer=b;m.INSPECT_MAX_BYTES=50;b.poolSize=8192;b._useTypedArrays=function(){try{var e=new ArrayBuffer(0),a= +new Uint8Array(e);a.foo=function(){return 42};return 42===a.foo()&&"function"===typeof a.subarray}catch(y){return!1}}();b.isEncoding=function(e){switch(String(e).toLowerCase()){case "hex":case "utf8":case "utf-8":case "ascii":case "binary":case "base64":case "raw":case "ucs2":case "ucs-2":case "utf16le":case "utf-16le":return!0;default:return!1}};b.isBuffer=function(e){return!(null===e||void 0===e||!e._isBuffer)};b.byteLength=function(e,a){e+="";switch(a||"utf8"){case "hex":var g=e.length/2;break; +case "utf8":case "utf-8":g=L(e).length;break;case "ascii":case "binary":case "raw":g=e.length;break;case "base64":g=E.toByteArray(e).length;break;case "ucs2":case "ucs-2":case "utf16le":case "utf-16le":g=2*e.length;break;default:throw Error("Unknown encoding");}return g};b.concat=function(e,a){q(M(e),"Usage: Buffer.concat(list, [totalLength])\nlist should be an Array.");if(0===e.length)return new b(0);if(1===e.length)return e[0];var g;if("number"!==typeof a)for(g=a=0;gg&&(c=g)):c=g;d=String(d||"utf8").toLowerCase();switch(d){case "hex":a=Number(a)||0;d=this.length-a;c?(c=Number(c),c>d&&(c=d)):c=d;d=e.length;q(0===d%2,"Invalid hex string");c>d/2&&(c=d/2);for(d=0;d>8;y%=256;g.push(y);g.push(d)}e=b._charsWritten=C(g,this,a,c);break;default:throw Error("Unknown encoding"); +}return e};b.prototype.toString=function(e,a,c){e=String(e||"utf8").toLowerCase();a=Number(a)||0;c=void 0!==c?Number(c):c=this.length;if(c===a)return"";switch(e){case "hex":e=this.length;if(!a||0>a)a=0;if(!c||0>c||c>e)c=e;for(e="";a=this[a]?(e+=F(g)+String.fromCharCode(this[a]),g=""):g+="%"+this[a].toString(16);c=e+F(g);break;case "ascii":c=f(this,a,c);break;case "binary":c=f(this,a,c);break; +case "base64":c=0===a&&c===this.length?E.fromByteArray(this):E.fromByteArray(this.slice(a,c));break;case "ucs2":case "ucs-2":case "utf16le":case "utf-16le":c=this.slice(a,c);a="";for(e=0;e=c,"sourceEnd < sourceStart"),q(0<=a&&athis.length&&(d=this.length),e.length-ad||!b._useTypedArrays)for(var g=0;g=this.length))return this[e]}; +b.prototype.readUInt16LE=function(e,a){return k(this,e,!0,a)};b.prototype.readUInt16BE=function(e,a){return k(this,e,!1,a)};b.prototype.readUInt32LE=function(e,a){return h(this,e,!0,a)};b.prototype.readUInt32BE=function(e,a){return h(this,e,!1,a)};b.prototype.readInt8=function(e,a){a||(q(void 0!==e&&null!==e,"missing offset"),q(e=this.length))return this[e]&128?-1*(255-this[e]+1):this[e]};b.prototype.readInt16LE=function(e,a){return d(this, +e,!0,a)};b.prototype.readInt16BE=function(e,a){return d(this,e,!1,a)};b.prototype.readInt32LE=function(e,c){return a(this,e,!0,c)};b.prototype.readInt32BE=function(e,c){return a(this,e,!1,c)};b.prototype.readFloatLE=function(e,a){return l(this,e,!0,a)};b.prototype.readFloatBE=function(e,a){return l(this,e,!1,a)};b.prototype.readDoubleLE=function(e,a){return u(this,e,!0,a)};b.prototype.readDoubleBE=function(e,a){return u(this,e,!1,a)};b.prototype.writeUInt8=function(e,a,c){c||(q(void 0!==e&&null!== +e,"missing value"),q(void 0!==a&&null!==a,"missing offset"),q(a=this.length||(this[a]=e)};b.prototype.writeUInt16LE=function(a,c,b){r(this,a,c,!0,b)};b.prototype.writeUInt16BE=function(a,c,b){r(this,a,c,!1,b)};b.prototype.writeUInt32LE=function(a,c,b){t(this,a,c,!0,b)};b.prototype.writeUInt32BE=function(a,c,b){t(this,a,c,!1,b)};b.prototype.writeInt8=function(a,c,b){b||(q(void 0!==a&&null!==a,"missing value"),q(void 0!==c&&null!==c,"missing offset"), +q(c=this.length||(0<=a?this.writeUInt8(a,c,b):this.writeUInt8(255+a+1,c,b))};b.prototype.writeInt16LE=function(a,c,b){z(this,a,c,!0,b)};b.prototype.writeInt16BE=function(a,c,b){z(this,a,c,!1,b)};b.prototype.writeInt32LE=function(a,b,d){c(this,a,b,!0,d)};b.prototype.writeInt32BE=function(a,b,d){c(this,a,b,!1,d)};b.prototype.writeFloatLE=function(a,c,b){n(this,a,c,!0,b)};b.prototype.writeFloatBE=function(a,c,b){n(this,a,c,!1,b)}; +b.prototype.writeDoubleLE=function(a,c,b){x(this,a,c,!0,b)};b.prototype.writeDoubleBE=function(a,c,b){x(this,a,c,!1,b)};b.prototype.fill=function(a,c,b){a||(a=0);c||(c=0);b||(b=this.length);"string"===typeof a&&(a=a.charCodeAt(0));q("number"===typeof a&&!isNaN(a),"value is not a number");q(b>=c,"end < start");if(b!==c&&0!==this.length)for(q(0<=c&&c"};b.prototype.toArrayBuffer=function(){if("undefined"!==typeof Uint8Array){if(b._useTypedArrays)return(new b(this)).buffer;for(var a=new Uint8Array(this.length),c=0,d=a.length;c>1,r=-7;d=k?d-1:0;var t=k?-1:1,z=b[f+d];d+=t;k=z&(1<<-r)-1;z>>=-r;for(r+=a;0>=-r;for(r+=h;0>1,z=23===d?Math.pow(2,-24)-Math.pow(2,-77):0;a=h?0:a-1;var c=h?1:-1, +n=0>f||0===f&&0>1/f?1:0;f=Math.abs(f);isNaN(f)||Infinity===f?(f=isNaN(f)?1:0,h=r):(h=Math.floor(Math.log(f)/Math.LN2),1>f*(l=Math.pow(2,-h))&&(h--,l*=2),f=1<=h+t?f+z/l:f+z*Math.pow(2,1-t),2<=f*l&&(h++,l/=2),h+t>=r?(f=0,h=r):1<=h+t?(f=(f*l-1)*Math.pow(2,d),h+=t):(f=f*Math.pow(2,t-1)*Math.pow(2,d),h=0));for(;8<=d;b[k+a]=f&255,a+=c,f/=256,d-=8);h=h<b?[]:a.slice(c,b-c+1)}a=m.resolve(a).substr(1);b=m.resolve(b).substr(1);for(var l=d(a.split("/")),t=d(b.split("/")),f=Math.min(l.length,t.length),c=f,n=0;nb&&(b=a.length+b);return a.substr(b,d)}}).call(this,p("node_modules/process/browser.js"))},{"node_modules/process/browser.js":8}],8:[function(p,v,m){function b(){}p=v.exports= +{};p.nextTick=function(){if("undefined"!==typeof window&&window.setImmediate)return function(b){return window.setImmediate(b)};if("undefined"!==typeof window&&window.postMessage&&window.addEventListener){var b=[];window.addEventListener("message",function(f){var k=f.source;k!==window&&null!==k||"process-tick"!==f.data||(f.stopPropagation(),0f?(-f<<1)+1:f<<1;do f=h&31,h>>>=5,0=d)throw Error("Expected more digits in base 64 VLQ value."); +var u=b.decode(f.charCodeAt(k++));if(-1===u)throw Error("Invalid base64 digit: "+f.charAt(k-1));var r=!!(u&32);u&=31;a+=u<>1;h.value=1===(a&1)?-f:f;h.rest=k}},{"./base64":11}],11:[function(p,v,m){var b="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split("");m.encode=function(f){if(0<=f&&f=b?b-65:97<=b&&122>=b?b-97+26:48<=b&&57>=b?b-48+52:43==b? +62:47==b?63:-1}},{}],12:[function(p,v,m){function b(f,k,h,d,a,l){var u=Math.floor((k-f)/2)+f,r=a(h,d[u],!0);return 0===r?u:0f?-1:f}m.GREATEST_LOWER_BOUND=1;m.LEAST_UPPER_BOUND=2;m.search=function(f,k,h,d){if(0===k.length)return-1;f=b(-1,k.length,f,k,h,d||m.GREATEST_LOWER_BOUND);if(0>f)return-1;for(;0<=f-1&&0===h(k[f],k[f-1],!0);)--f;return f}},{}],13:[function(p,v,m){function b(){this._array= +[];this._sorted=!0;this._last={generatedLine:-1,generatedColumn:0}}var f=p("./util");b.prototype.unsortedForEach=function(b,f){this._array.forEach(b,f)};b.prototype.add=function(b){var k=this._last,d=k.generatedLine,a=b.generatedLine,l=k.generatedColumn,u=b.generatedColumn;a>d||a==d&&u>=l||0>=f.compareByGeneratedPositionsInflated(k,b)?this._last=b:this._sorted=!1;this._array.push(b)};b.prototype.toArray=function(){this._sorted||(this._array.sort(f.compareByGeneratedPositionsInflated),this._sorted= +!0);return this._array};m.MappingList=b},{"./util":18}],14:[function(p,v,m){function b(b,f,d){var a=b[f];b[f]=b[d];b[d]=a}function f(k,h,d,a){if(d=h(k[r],u)&&(l+=1,b(k,l,r));b(k,l+1,r);l+=1;f(k,h,d,l-1);f(k,h,l+1,a)}}m.quickSort=function(b,h){f(b,h,0,b.length-1)}},{}],15:[function(p,v,m){function b(a,b){var c=a;"string"===typeof a&&(c=d.parseSourceMapInput(a));return null!=c.sections?new h(c,b):new f(c,b)}function f(a, +b){var c=a;"string"===typeof a&&(c=d.parseSourceMapInput(a));var n=d.getArg(c,"version"),t=d.getArg(c,"sources"),f=d.getArg(c,"names",[]),r=d.getArg(c,"sourceRoot",null),k=d.getArg(c,"sourcesContent",null),u=d.getArg(c,"mappings");c=d.getArg(c,"file",null);if(n!=this._version)throw Error("Unsupported version: "+n);r&&(r=d.normalize(r));t=t.map(String).map(d.normalize).map(function(a){return r&&d.isAbsolute(r)&&d.isAbsolute(a)?d.relative(r,a):a});this._names=l.fromArray(f.map(String),!0);this._sources= +l.fromArray(t,!0);this.sourceRoot=r;this.sourcesContent=k;this._mappings=u;this._sourceMapURL=b;this.file=c}function k(){this.generatedColumn=this.generatedLine=0;this.name=this.originalColumn=this.originalLine=this.source=null}function h(a,f){var c=a;"string"===typeof a&&(c=d.parseSourceMapInput(a));var n=d.getArg(c,"version");c=d.getArg(c,"sections");if(n!=this._version)throw Error("Unsupported version: "+n);this._sources=new l;this._names=new l;var t={line:-1,column:0};this._sections=c.map(function(a){if(a.url)throw Error("Support for url field in sections not implemented."); +var c=d.getArg(a,"offset"),n=d.getArg(c,"line"),l=d.getArg(c,"column");if(n=b[c])throw new TypeError("Line must be greater than or equal to 1, got "+b[c]);if(0>b[n])throw new TypeError("Column must be greater than or equal to 0, got "+b[n]);return a.search(b,d,f,l)};f.prototype.computeColumnSpans=function(){for(var a=0;a=this._sources.size()&&!this.sourcesContent.some(function(a){return null== +a}):!1};f.prototype.sourceContentFor=function(a,b){if(!this.sourcesContent)return null;var c=a;null!=this.sourceRoot&&(c=d.relative(this.sourceRoot,c));if(this._sources.has(c))return this.sourcesContent[this._sources.indexOf(c)];var n=this.sources,f;for(f=0;fb||95!==a.charCodeAt(b-1)||95!==a.charCodeAt(b-2)||111!==a.charCodeAt(b-3)||116!==a.charCodeAt(b-4)||111!==a.charCodeAt(b-5)||114!==a.charCodeAt(b-6)||112!==a.charCodeAt(b-7)||95!==a.charCodeAt(b-8)||95!==a.charCodeAt(b-9))return!1;for(b-=10;0<=b;b--)if(36!==a.charCodeAt(b))return!1;return!0}function r(a,b){return a===b?0:null===a?1:null===b?-1:a>b?1:-1}m.getArg=function(a,b,d){if(b in +a)return a[b];if(3===arguments.length)return d;throw Error('"'+b+'" is a required argument.');};var t=/^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/,z=/^data:.+,.+$/;m.urlParse=b;m.urlGenerate=f;m.normalize=k;m.join=h;m.isAbsolute=function(a){return"/"===a.charAt(0)||t.test(a)};m.relative=function(a,b){""===a&&(a=".");a=a.replace(/\/$/,"");for(var c=0;0!==b.indexOf(a+"/");){var d=a.lastIndexOf("/");if(0>d)return b;a=a.slice(0,d);if(a.match(/^([^\/]+:\/)?\/*$/))return b;++c}return Array(c+ +1).join("../")+b.substr(a.length+1)};p=!("__proto__"in Object.create(null));m.toSetString=p?d:a;m.fromSetString=p?d:l;m.compareByOriginalPositions=function(a,b,d){var c=r(a.source,b.source);if(0!==c)return c;c=a.originalLine-b.originalLine;if(0!==c)return c;c=a.originalColumn-b.originalColumn;if(0!==c||d)return c;c=a.generatedColumn-b.generatedColumn;if(0!==c)return c;c=a.generatedLine-b.generatedLine;return 0!==c?c:r(a.name,b.name)};m.compareByGeneratedPositionsDeflated=function(a,b,d){var c=a.generatedLine- +b.generatedLine;if(0!==c)return c;c=a.generatedColumn-b.generatedColumn;if(0!==c||d)return c;c=r(a.source,b.source);if(0!==c)return c;c=a.originalLine-b.originalLine;if(0!==c)return c;c=a.originalColumn-b.originalColumn;return 0!==c?c:r(a.name,b.name)};m.compareByGeneratedPositionsInflated=function(a,b){var c=a.generatedLine-b.generatedLine;if(0!==c)return c;c=a.generatedColumn-b.generatedColumn;if(0!==c)return c;c=r(a.source,b.source);if(0!==c)return c;c=a.originalLine-b.originalLine;if(0!==c)return c; +c=a.originalColumn-b.originalColumn;return 0!==c?c:r(a.name,b.name)};m.parseSourceMapInput=function(a){return JSON.parse(a.replace(/^\)]}'[^\n]*\n/,""))};m.computeSourceURL=function(a,d,l){d=d||"";a&&("/"!==a[a.length-1]&&"/"!==d[0]&&(a+="/"),d=a+d);if(l){a=b(l);if(!a)throw Error("sourceMapURL could not be parsed");a.path&&(l=a.path.lastIndexOf("/"),0<=l&&(a.path=a.path.substring(0,l+1)));d=h(f(a),d)}return k(d)}},{}],19:[function(p,v,m){m.SourceMapGenerator=p("./lib/source-map-generator").SourceMapGenerator; +m.SourceMapConsumer=p("./lib/source-map-consumer").SourceMapConsumer;m.SourceNode=p("./lib/source-node").SourceNode},{"./lib/source-map-consumer":15,"./lib/source-map-generator":16,"./lib/source-node":17}],20:[function(p,v,m){(function(b){function f(){return"browser"===J?!0:"node"===J?!1:"undefined"!==typeof window&&"function"===typeof XMLHttpRequest&&!(window.require&&window.module&&window.process&&"renderer"===window.process.type)}function k(a){return function(b){for(var c=0;c";b=this.getLineNumber();null!=b&&(a+=":"+b,(b=this.getColumnNumber())&&(a+=":"+b))}b="";var c=this.getFunctionName(),d=!0,f=this.isConstructor();if(this.isToplevel()||f)f?b+="new "+(c||""):c?b+=c:(b+=a,d=!1);else{f=this.getTypeName();"[object Object]"===f&&(f="null");var h=this.getMethodName();c?(f&&0!=c.indexOf(f)&&(b+=f+"."),b+=c,h&&c.indexOf("."+h)!=c.length-h.length-1&&(b+=" [as "+h+"]")):b+=f+"."+(h||"")}d&&(b+=" ("+a+")");return b}function u(a){var b= +{};Object.getOwnPropertyNames(Object.getPrototypeOf(a)).forEach(function(c){b[c]=/^(?:is|get)/.test(c)?function(){return a[c].call(a)}:a[c]});b.toString=l;return b}function r(b){if(b.isNative())return b;var c=b.getFileName()||b.getScriptNameOrSourceURL();if(c){var e=b.getLineNumber(),h=b.getColumnNumber()-1;1===e&&62 C:/dir/file + '/'; // file:///root-dir/file -> /root-dir/file + }); + } + if (path in fileContentsCache) { + return fileContentsCache[path]; + } + + var contents = ''; + try { + if (!fs) { + // Use SJAX if we are in the browser + var xhr = new XMLHttpRequest(); + xhr.open('GET', path, /** async */ false); + xhr.send(null); + if (xhr.readyState === 4 && xhr.status === 200) { + contents = xhr.responseText; + } + } else if (fs.existsSync(path)) { + // Otherwise, use the filesystem + contents = fs.readFileSync(path, 'utf8'); + } + } catch (er) { + /* ignore any errors */ + } + + return fileContentsCache[path] = contents; +}); + +// Support URLs relative to a directory, but be careful about a protocol prefix +// in case we are in the browser (i.e. directories may start with "http://" or "file:///") +function supportRelativeURL(file, url) { + if (!file) return url; + var dir = path.dirname(file); + var match = /^\w+:\/\/[^\/]*/.exec(dir); + var protocol = match ? match[0] : ''; + var startPath = dir.slice(protocol.length); + if (protocol && /^\/\w\:/.test(startPath)) { + // handle file:///C:/ paths + protocol += '/'; + return protocol + path.resolve(dir.slice(protocol.length), url).replace(/\\/g, '/'); + } + return protocol + path.resolve(dir.slice(protocol.length), url); +} + +function retrieveSourceMapURL(source) { + var fileData; + + if (isInBrowser()) { + try { + var xhr = new XMLHttpRequest(); + xhr.open('GET', source, false); + xhr.send(null); + fileData = xhr.readyState === 4 ? xhr.responseText : null; + + // Support providing a sourceMappingURL via the SourceMap header + var sourceMapHeader = xhr.getResponseHeader("SourceMap") || + xhr.getResponseHeader("X-SourceMap"); + if (sourceMapHeader) { + return sourceMapHeader; + } + } catch (e) { + } + } + + // Get the URL of the source map + fileData = retrieveFile(source); + var re = /(?:\/\/[@#][ \t]+sourceMappingURL=([^\s'"]+?)[ \t]*$)|(?:\/\*[@#][ \t]+sourceMappingURL=([^\*]+?)[ \t]*(?:\*\/)[ \t]*$)/mg; + // Keep executing the search to find the *last* sourceMappingURL to avoid + // picking up sourceMappingURLs from comments, strings, etc. + var lastMatch, match; + while (match = re.exec(fileData)) lastMatch = match; + if (!lastMatch) return null; + return lastMatch[1]; +}; + +// Can be overridden by the retrieveSourceMap option to install. Takes a +// generated source filename; returns a {map, optional url} object, or null if +// there is no source map. The map field may be either a string or the parsed +// JSON object (ie, it must be a valid argument to the SourceMapConsumer +// constructor). +var retrieveSourceMap = handlerExec(retrieveMapHandlers); +retrieveMapHandlers.push(function(source) { + var sourceMappingURL = retrieveSourceMapURL(source); + if (!sourceMappingURL) return null; + + // Read the contents of the source map + var sourceMapData; + if (reSourceMap.test(sourceMappingURL)) { + // Support source map URL as a data url + var rawData = sourceMappingURL.slice(sourceMappingURL.indexOf(',') + 1); + sourceMapData = bufferFrom(rawData, "base64").toString(); + sourceMappingURL = source; + } else { + // Support source map URLs relative to the source URL + sourceMappingURL = supportRelativeURL(source, sourceMappingURL); + sourceMapData = retrieveFile(sourceMappingURL); + } + + if (!sourceMapData) { + return null; + } + + return { + url: sourceMappingURL, + map: sourceMapData + }; +}); + +function mapSourcePosition(position) { + var sourceMap = sourceMapCache[position.source]; + if (!sourceMap) { + // Call the (overrideable) retrieveSourceMap function to get the source map. + var urlAndMap = retrieveSourceMap(position.source); + if (urlAndMap) { + sourceMap = sourceMapCache[position.source] = { + url: urlAndMap.url, + map: new SourceMapConsumer(urlAndMap.map) + }; + + // Load all sources stored inline with the source map into the file cache + // to pretend like they are already loaded. They may not exist on disk. + if (sourceMap.map.sourcesContent) { + sourceMap.map.sources.forEach(function(source, i) { + var contents = sourceMap.map.sourcesContent[i]; + if (contents) { + var url = supportRelativeURL(sourceMap.url, source); + fileContentsCache[url] = contents; + } + }); + } + } else { + sourceMap = sourceMapCache[position.source] = { + url: null, + map: null + }; + } + } + + // Resolve the source URL relative to the URL of the source map + if (sourceMap && sourceMap.map) { + var originalPosition = sourceMap.map.originalPositionFor(position); + + // Only return the original position if a matching line was found. If no + // matching line is found then we return position instead, which will cause + // the stack trace to print the path and line for the compiled file. It is + // better to give a precise location in the compiled file than a vague + // location in the original file. + if (originalPosition.source !== null) { + originalPosition.source = supportRelativeURL( + sourceMap.url, originalPosition.source); + return originalPosition; + } + } + + return position; +} + +// Parses code generated by FormatEvalOrigin(), a function inside V8: +// https://code.google.com/p/v8/source/browse/trunk/src/messages.js +function mapEvalOrigin(origin) { + // Most eval() calls are in this format + var match = /^eval at ([^(]+) \((.+):(\d+):(\d+)\)$/.exec(origin); + if (match) { + var position = mapSourcePosition({ + source: match[2], + line: +match[3], + column: match[4] - 1 + }); + return 'eval at ' + match[1] + ' (' + position.source + ':' + + position.line + ':' + (position.column + 1) + ')'; + } + + // Parse nested eval() calls using recursion + match = /^eval at ([^(]+) \((.+)\)$/.exec(origin); + if (match) { + return 'eval at ' + match[1] + ' (' + mapEvalOrigin(match[2]) + ')'; + } + + // Make sure we still return useful information if we didn't find anything + return origin; +} + +// This is copied almost verbatim from the V8 source code at +// https://code.google.com/p/v8/source/browse/trunk/src/messages.js. The +// implementation of wrapCallSite() used to just forward to the actual source +// code of CallSite.prototype.toString but unfortunately a new release of V8 +// did something to the prototype chain and broke the shim. The only fix I +// could find was copy/paste. +function CallSiteToString() { + var fileName; + var fileLocation = ""; + if (this.isNative()) { + fileLocation = "native"; + } else { + fileName = this.getScriptNameOrSourceURL(); + if (!fileName && this.isEval()) { + fileLocation = this.getEvalOrigin(); + fileLocation += ", "; // Expecting source position to follow. + } + + if (fileName) { + fileLocation += fileName; + } else { + // Source code does not originate from a file and is not native, but we + // can still get the source position inside the source string, e.g. in + // an eval string. + fileLocation += ""; + } + var lineNumber = this.getLineNumber(); + if (lineNumber != null) { + fileLocation += ":" + lineNumber; + var columnNumber = this.getColumnNumber(); + if (columnNumber) { + fileLocation += ":" + columnNumber; + } + } + } + + var line = ""; + var functionName = this.getFunctionName(); + var addSuffix = true; + var isConstructor = this.isConstructor(); + var isMethodCall = !(this.isToplevel() || isConstructor); + if (isMethodCall) { + var typeName = this.getTypeName(); + // Fixes shim to be backward compatable with Node v0 to v4 + if (typeName === "[object Object]") { + typeName = "null"; + } + var methodName = this.getMethodName(); + if (functionName) { + if (typeName && functionName.indexOf(typeName) != 0) { + line += typeName + "."; + } + line += functionName; + if (methodName && functionName.indexOf("." + methodName) != functionName.length - methodName.length - 1) { + line += " [as " + methodName + "]"; + } + } else { + line += typeName + "." + (methodName || ""); + } + } else if (isConstructor) { + line += "new " + (functionName || ""); + } else if (functionName) { + line += functionName; + } else { + line += fileLocation; + addSuffix = false; + } + if (addSuffix) { + line += " (" + fileLocation + ")"; + } + return line; +} + +function cloneCallSite(frame) { + var object = {}; + Object.getOwnPropertyNames(Object.getPrototypeOf(frame)).forEach(function(name) { + object[name] = /^(?:is|get)/.test(name) ? function() { return frame[name].call(frame); } : frame[name]; + }); + object.toString = CallSiteToString; + return object; +} + +function wrapCallSite(frame) { + if(frame.isNative()) { + return frame; + } + + // Most call sites will return the source file from getFileName(), but code + // passed to eval() ending in "//# sourceURL=..." will return the source file + // from getScriptNameOrSourceURL() instead + var source = frame.getFileName() || frame.getScriptNameOrSourceURL(); + if (source) { + var line = frame.getLineNumber(); + var column = frame.getColumnNumber() - 1; + + // Fix position in Node where some (internal) code is prepended. + // See https://github.com/evanw/node-source-map-support/issues/36 + var headerLength = 62; + if (line === 1 && column > headerLength && !isInBrowser() && !frame.isEval()) { + column -= headerLength; + } + + var position = mapSourcePosition({ + source: source, + line: line, + column: column + }); + frame = cloneCallSite(frame); + var originalFunctionName = frame.getFunctionName; + frame.getFunctionName = function() { return position.name || originalFunctionName(); }; + frame.getFileName = function() { return position.source; }; + frame.getLineNumber = function() { return position.line; }; + frame.getColumnNumber = function() { return position.column + 1; }; + frame.getScriptNameOrSourceURL = function() { return position.source; }; + return frame; + } + + // Code called using eval() needs special handling + var origin = frame.isEval() && frame.getEvalOrigin(); + if (origin) { + origin = mapEvalOrigin(origin); + frame = cloneCallSite(frame); + frame.getEvalOrigin = function() { return origin; }; + return frame; + } + + // If we get here then we were unable to change the source position + return frame; +} + +// This function is part of the V8 stack trace API, for more info see: +// http://code.google.com/p/v8/wiki/JavaScriptStackTraceApi +function prepareStackTrace(error, stack) { + if (emptyCacheBetweenOperations) { + fileContentsCache = {}; + sourceMapCache = {}; + } + + return error + stack.map(function(frame) { + return '\n at ' + wrapCallSite(frame); + }).join(''); +} + +// Generate position and snippet of original source with pointer +function getErrorSource(error) { + var match = /\n at [^(]+ \((.*):(\d+):(\d+)\)/.exec(error.stack); + if (match) { + var source = match[1]; + var line = +match[2]; + var column = +match[3]; + + // Support the inline sourceContents inside the source map + var contents = fileContentsCache[source]; + + // Support files on disk + if (!contents && fs && fs.existsSync(source)) { + try { + contents = fs.readFileSync(source, 'utf8'); + } catch (er) { + contents = ''; + } + } + + // Format the line from the original source code like node does + if (contents) { + var code = contents.split(/(?:\r\n|\r|\n)/)[line - 1]; + if (code) { + return source + ':' + line + '\n' + code + '\n' + + new Array(column).join(' ') + '^'; + } + } + } + return null; +} + +function printErrorAndExit (error) { + var source = getErrorSource(error); + + // Ensure error is printed synchronously and not truncated + if (process.stderr._handle && process.stderr._handle.setBlocking) { + process.stderr._handle.setBlocking(true); + } + + if (source) { + console.error(); + console.error(source); + } + + console.error(error.stack); + process.exit(1); +} + +function shimEmitUncaughtException () { + var origEmit = process.emit; + + process.emit = function (type) { + if (type === 'uncaughtException') { + var hasStack = (arguments[1] && arguments[1].stack); + var hasListeners = (this.listeners(type).length > 0); + + if (hasStack && !hasListeners) { + return printErrorAndExit(arguments[1]); + } + } + + return origEmit.apply(this, arguments); + }; +} + +var originalRetrieveFileHandlers = retrieveFileHandlers.slice(0); +var originalRetrieveMapHandlers = retrieveMapHandlers.slice(0); + +exports.wrapCallSite = wrapCallSite; +exports.getErrorSource = getErrorSource; +exports.mapSourcePosition = mapSourcePosition; +exports.retrieveSourceMap = retrieveSourceMap; + +exports.install = function(options) { + options = options || {}; + + if (options.environment) { + environment = options.environment; + if (["node", "browser", "auto"].indexOf(environment) === -1) { + throw new Error("environment " + environment + " was unknown. Available options are {auto, browser, node}") + } + } + + // Allow sources to be found by methods other than reading the files + // directly from disk. + if (options.retrieveFile) { + if (options.overrideRetrieveFile) { + retrieveFileHandlers.length = 0; + } + + retrieveFileHandlers.unshift(options.retrieveFile); + } + + // Allow source maps to be found by methods other than reading the files + // directly from disk. + if (options.retrieveSourceMap) { + if (options.overrideRetrieveSourceMap) { + retrieveMapHandlers.length = 0; + } + + retrieveMapHandlers.unshift(options.retrieveSourceMap); + } + + // Support runtime transpilers that include inline source maps + if (options.hookRequire && !isInBrowser()) { + var Module; + try { + Module = require('module'); + } catch (err) { + // NOP: Loading in catch block to convert webpack error to warning. + } + var $compile = Module.prototype._compile; + + if (!$compile.__sourceMapSupport) { + Module.prototype._compile = function(content, filename) { + fileContentsCache[filename] = content; + sourceMapCache[filename] = undefined; + return $compile.call(this, content, filename); + }; + + Module.prototype._compile.__sourceMapSupport = true; + } + } + + // Configure options + if (!emptyCacheBetweenOperations) { + emptyCacheBetweenOperations = 'emptyCacheBetweenOperations' in options ? + options.emptyCacheBetweenOperations : false; + } + + // Install the error reformatter + if (!errorFormatterInstalled) { + errorFormatterInstalled = true; + Error.prepareStackTrace = prepareStackTrace; + } + + if (!uncaughtShimInstalled) { + var installHandler = 'handleUncaughtExceptions' in options ? + options.handleUncaughtExceptions : true; + + // Provide the option to not install the uncaught exception handler. This is + // to support other uncaught exception handlers (in test frameworks, for + // example). If this handler is not installed and there are no other uncaught + // exception handlers, uncaught exceptions will be caught by node's built-in + // exception handler and the process will still be terminated. However, the + // generated JavaScript code will be shown above the stack trace instead of + // the original source code. + if (installHandler && hasGlobalProcessEventEmitter()) { + uncaughtShimInstalled = true; + shimEmitUncaughtException(); + } + } +}; + +exports.resetRetrieveHandlers = function() { + retrieveFileHandlers.length = 0; + retrieveMapHandlers.length = 0; + + retrieveFileHandlers = originalRetrieveFileHandlers.slice(0); + retrieveMapHandlers = originalRetrieveMapHandlers.slice(0); +} diff --git a/node_modules/source-map/CHANGELOG.md b/node_modules/source-map/CHANGELOG.md new file mode 100644 index 0000000..3a8c066 --- /dev/null +++ b/node_modules/source-map/CHANGELOG.md @@ -0,0 +1,301 @@ +# Change Log + +## 0.5.6 + +* Fix for regression when people were using numbers as names in source maps. See + #236. + +## 0.5.5 + +* Fix "regression" of unsupported, implementation behavior that half the world + happens to have come to depend on. See #235. + +* Fix regression involving function hoisting in SpiderMonkey. See #233. + +## 0.5.4 + +* Large performance improvements to source-map serialization. See #228 and #229. + +## 0.5.3 + +* Do not include unnecessary distribution files. See + commit ef7006f8d1647e0a83fdc60f04f5a7ca54886f86. + +## 0.5.2 + +* Include browser distributions of the library in package.json's `files`. See + issue #212. + +## 0.5.1 + +* Fix latent bugs in IndexedSourceMapConsumer.prototype._parseMappings. See + ff05274becc9e6e1295ed60f3ea090d31d843379. + +## 0.5.0 + +* Node 0.8 is no longer supported. + +* Use webpack instead of dryice for bundling. + +* Big speedups serializing source maps. See pull request #203. + +* Fix a bug with `SourceMapConsumer.prototype.sourceContentFor` and sources that + explicitly start with the source root. See issue #199. + +## 0.4.4 + +* Fix an issue where using a `SourceMapGenerator` after having created a + `SourceMapConsumer` from it via `SourceMapConsumer.fromSourceMap` failed. See + issue #191. + +* Fix an issue with where `SourceMapGenerator` would mistakenly consider + different mappings as duplicates of each other and avoid generating them. See + issue #192. + +## 0.4.3 + +* A very large number of performance improvements, particularly when parsing + source maps. Collectively about 75% of time shaved off of the source map + parsing benchmark! + +* Fix a bug in `SourceMapConsumer.prototype.allGeneratedPositionsFor` and fuzzy + searching in the presence of a column option. See issue #177. + +* Fix a bug with joining a source and its source root when the source is above + the root. See issue #182. + +* Add the `SourceMapConsumer.prototype.hasContentsOfAllSources` method to + determine when all sources' contents are inlined into the source map. See + issue #190. + +## 0.4.2 + +* Add an `.npmignore` file so that the benchmarks aren't pulled down by + dependent projects. Issue #169. + +* Add an optional `column` argument to + `SourceMapConsumer.prototype.allGeneratedPositionsFor` and better handle lines + with no mappings. Issues #172 and #173. + +## 0.4.1 + +* Fix accidentally defining a global variable. #170. + +## 0.4.0 + +* The default direction for fuzzy searching was changed back to its original + direction. See #164. + +* There is now a `bias` option you can supply to `SourceMapConsumer` to control + the fuzzy searching direction. See #167. + +* About an 8% speed up in parsing source maps. See #159. + +* Added a benchmark for parsing and generating source maps. + +## 0.3.0 + +* Change the default direction that searching for positions fuzzes when there is + not an exact match. See #154. + +* Support for environments using json2.js for JSON serialization. See #156. + +## 0.2.0 + +* Support for consuming "indexed" source maps which do not have any remote + sections. See pull request #127. This introduces a minor backwards + incompatibility if you are monkey patching `SourceMapConsumer.prototype` + methods. + +## 0.1.43 + +* Performance improvements for `SourceMapGenerator` and `SourceNode`. See issue + #148 for some discussion and issues #150, #151, and #152 for implementations. + +## 0.1.42 + +* Fix an issue where `SourceNode`s from different versions of the source-map + library couldn't be used in conjunction with each other. See issue #142. + +## 0.1.41 + +* Fix a bug with getting the source content of relative sources with a "./" + prefix. See issue #145 and [Bug 1090768](bugzil.la/1090768). + +* Add the `SourceMapConsumer.prototype.computeColumnSpans` method to compute the + column span of each mapping. + +* Add the `SourceMapConsumer.prototype.allGeneratedPositionsFor` method to find + all generated positions associated with a given original source and line. + +## 0.1.40 + +* Performance improvements for parsing source maps in SourceMapConsumer. + +## 0.1.39 + +* Fix a bug where setting a source's contents to null before any source content + had been set before threw a TypeError. See issue #131. + +## 0.1.38 + +* Fix a bug where finding relative paths from an empty path were creating + absolute paths. See issue #129. + +## 0.1.37 + +* Fix a bug where if the source root was an empty string, relative source paths + would turn into absolute source paths. Issue #124. + +## 0.1.36 + +* Allow the `names` mapping property to be an empty string. Issue #121. + +## 0.1.35 + +* A third optional parameter was added to `SourceNode.fromStringWithSourceMap` + to specify a path that relative sources in the second parameter should be + relative to. Issue #105. + +* If no file property is given to a `SourceMapGenerator`, then the resulting + source map will no longer have a `null` file property. The property will + simply not exist. Issue #104. + +* Fixed a bug where consecutive newlines were ignored in `SourceNode`s. + Issue #116. + +## 0.1.34 + +* Make `SourceNode` work with windows style ("\r\n") newlines. Issue #103. + +* Fix bug involving source contents and the + `SourceMapGenerator.prototype.applySourceMap`. Issue #100. + +## 0.1.33 + +* Fix some edge cases surrounding path joining and URL resolution. + +* Add a third parameter for relative path to + `SourceMapGenerator.prototype.applySourceMap`. + +* Fix issues with mappings and EOLs. + +## 0.1.32 + +* Fixed a bug where SourceMapConsumer couldn't handle negative relative columns + (issue 92). + +* Fixed test runner to actually report number of failed tests as its process + exit code. + +* Fixed a typo when reporting bad mappings (issue 87). + +## 0.1.31 + +* Delay parsing the mappings in SourceMapConsumer until queried for a source + location. + +* Support Sass source maps (which at the time of writing deviate from the spec + in small ways) in SourceMapConsumer. + +## 0.1.30 + +* Do not join source root with a source, when the source is a data URI. + +* Extend the test runner to allow running single specific test files at a time. + +* Performance improvements in `SourceNode.prototype.walk` and + `SourceMapConsumer.prototype.eachMapping`. + +* Source map browser builds will now work inside Workers. + +* Better error messages when attempting to add an invalid mapping to a + `SourceMapGenerator`. + +## 0.1.29 + +* Allow duplicate entries in the `names` and `sources` arrays of source maps + (usually from TypeScript) we are parsing. Fixes github issue 72. + +## 0.1.28 + +* Skip duplicate mappings when creating source maps from SourceNode; github + issue 75. + +## 0.1.27 + +* Don't throw an error when the `file` property is missing in SourceMapConsumer, + we don't use it anyway. + +## 0.1.26 + +* Fix SourceNode.fromStringWithSourceMap for empty maps. Fixes github issue 70. + +## 0.1.25 + +* Make compatible with browserify + +## 0.1.24 + +* Fix issue with absolute paths and `file://` URIs. See + https://bugzilla.mozilla.org/show_bug.cgi?id=885597 + +## 0.1.23 + +* Fix issue with absolute paths and sourcesContent, github issue 64. + +## 0.1.22 + +* Ignore duplicate mappings in SourceMapGenerator. Fixes github issue 21. + +## 0.1.21 + +* Fixed handling of sources that start with a slash so that they are relative to + the source root's host. + +## 0.1.20 + +* Fixed github issue #43: absolute URLs aren't joined with the source root + anymore. + +## 0.1.19 + +* Using Travis CI to run tests. + +## 0.1.18 + +* Fixed a bug in the handling of sourceRoot. + +## 0.1.17 + +* Added SourceNode.fromStringWithSourceMap. + +## 0.1.16 + +* Added missing documentation. + +* Fixed the generating of empty mappings in SourceNode. + +## 0.1.15 + +* Added SourceMapGenerator.applySourceMap. + +## 0.1.14 + +* The sourceRoot is now handled consistently. + +## 0.1.13 + +* Added SourceMapGenerator.fromSourceMap. + +## 0.1.12 + +* SourceNode now generates empty mappings too. + +## 0.1.11 + +* Added name support to SourceNode. + +## 0.1.10 + +* Added sourcesContent support to the customer and generator. diff --git a/node_modules/source-map/LICENSE b/node_modules/source-map/LICENSE new file mode 100644 index 0000000..ed1b7cf --- /dev/null +++ b/node_modules/source-map/LICENSE @@ -0,0 +1,28 @@ + +Copyright (c) 2009-2011, Mozilla Foundation and contributors +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +* Neither the names of the Mozilla Foundation nor the names of project + contributors may be used to endorse or promote products derived from this + software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/node_modules/source-map/README.md b/node_modules/source-map/README.md new file mode 100644 index 0000000..fea4beb --- /dev/null +++ b/node_modules/source-map/README.md @@ -0,0 +1,742 @@ +# Source Map + +[![Build Status](https://travis-ci.org/mozilla/source-map.png?branch=master)](https://travis-ci.org/mozilla/source-map) + +[![NPM](https://nodei.co/npm/source-map.png?downloads=true&downloadRank=true)](https://www.npmjs.com/package/source-map) + +This is a library to generate and consume the source map format +[described here][format]. + +[format]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit + +## Use with Node + + $ npm install source-map + +## Use on the Web + + + +-------------------------------------------------------------------------------- + + + + + +## Table of Contents + +- [Examples](#examples) + - [Consuming a source map](#consuming-a-source-map) + - [Generating a source map](#generating-a-source-map) + - [With SourceNode (high level API)](#with-sourcenode-high-level-api) + - [With SourceMapGenerator (low level API)](#with-sourcemapgenerator-low-level-api) +- [API](#api) + - [SourceMapConsumer](#sourcemapconsumer) + - [new SourceMapConsumer(rawSourceMap)](#new-sourcemapconsumerrawsourcemap) + - [SourceMapConsumer.prototype.computeColumnSpans()](#sourcemapconsumerprototypecomputecolumnspans) + - [SourceMapConsumer.prototype.originalPositionFor(generatedPosition)](#sourcemapconsumerprototypeoriginalpositionforgeneratedposition) + - [SourceMapConsumer.prototype.generatedPositionFor(originalPosition)](#sourcemapconsumerprototypegeneratedpositionfororiginalposition) + - [SourceMapConsumer.prototype.allGeneratedPositionsFor(originalPosition)](#sourcemapconsumerprototypeallgeneratedpositionsfororiginalposition) + - [SourceMapConsumer.prototype.hasContentsOfAllSources()](#sourcemapconsumerprototypehascontentsofallsources) + - [SourceMapConsumer.prototype.sourceContentFor(source[, returnNullOnMissing])](#sourcemapconsumerprototypesourcecontentforsource-returnnullonmissing) + - [SourceMapConsumer.prototype.eachMapping(callback, context, order)](#sourcemapconsumerprototypeeachmappingcallback-context-order) + - [SourceMapGenerator](#sourcemapgenerator) + - [new SourceMapGenerator([startOfSourceMap])](#new-sourcemapgeneratorstartofsourcemap) + - [SourceMapGenerator.fromSourceMap(sourceMapConsumer)](#sourcemapgeneratorfromsourcemapsourcemapconsumer) + - [SourceMapGenerator.prototype.addMapping(mapping)](#sourcemapgeneratorprototypeaddmappingmapping) + - [SourceMapGenerator.prototype.setSourceContent(sourceFile, sourceContent)](#sourcemapgeneratorprototypesetsourcecontentsourcefile-sourcecontent) + - [SourceMapGenerator.prototype.applySourceMap(sourceMapConsumer[, sourceFile[, sourceMapPath]])](#sourcemapgeneratorprototypeapplysourcemapsourcemapconsumer-sourcefile-sourcemappath) + - [SourceMapGenerator.prototype.toString()](#sourcemapgeneratorprototypetostring) + - [SourceNode](#sourcenode) + - [new SourceNode([line, column, source[, chunk[, name]]])](#new-sourcenodeline-column-source-chunk-name) + - [SourceNode.fromStringWithSourceMap(code, sourceMapConsumer[, relativePath])](#sourcenodefromstringwithsourcemapcode-sourcemapconsumer-relativepath) + - [SourceNode.prototype.add(chunk)](#sourcenodeprototypeaddchunk) + - [SourceNode.prototype.prepend(chunk)](#sourcenodeprototypeprependchunk) + - [SourceNode.prototype.setSourceContent(sourceFile, sourceContent)](#sourcenodeprototypesetsourcecontentsourcefile-sourcecontent) + - [SourceNode.prototype.walk(fn)](#sourcenodeprototypewalkfn) + - [SourceNode.prototype.walkSourceContents(fn)](#sourcenodeprototypewalksourcecontentsfn) + - [SourceNode.prototype.join(sep)](#sourcenodeprototypejoinsep) + - [SourceNode.prototype.replaceRight(pattern, replacement)](#sourcenodeprototypereplacerightpattern-replacement) + - [SourceNode.prototype.toString()](#sourcenodeprototypetostring) + - [SourceNode.prototype.toStringWithSourceMap([startOfSourceMap])](#sourcenodeprototypetostringwithsourcemapstartofsourcemap) + + + +## Examples + +### Consuming a source map + +```js +var rawSourceMap = { + version: 3, + file: 'min.js', + names: ['bar', 'baz', 'n'], + sources: ['one.js', 'two.js'], + sourceRoot: 'http://example.com/www/js/', + mappings: 'CAAC,IAAI,IAAM,SAAUA,GAClB,OAAOC,IAAID;CCDb,IAAI,IAAM,SAAUE,GAClB,OAAOA' +}; + +var smc = new SourceMapConsumer(rawSourceMap); + +console.log(smc.sources); +// [ 'http://example.com/www/js/one.js', +// 'http://example.com/www/js/two.js' ] + +console.log(smc.originalPositionFor({ + line: 2, + column: 28 +})); +// { source: 'http://example.com/www/js/two.js', +// line: 2, +// column: 10, +// name: 'n' } + +console.log(smc.generatedPositionFor({ + source: 'http://example.com/www/js/two.js', + line: 2, + column: 10 +})); +// { line: 2, column: 28 } + +smc.eachMapping(function (m) { + // ... +}); +``` + +### Generating a source map + +In depth guide: +[**Compiling to JavaScript, and Debugging with Source Maps**](https://hacks.mozilla.org/2013/05/compiling-to-javascript-and-debugging-with-source-maps/) + +#### With SourceNode (high level API) + +```js +function compile(ast) { + switch (ast.type) { + case 'BinaryExpression': + return new SourceNode( + ast.location.line, + ast.location.column, + ast.location.source, + [compile(ast.left), " + ", compile(ast.right)] + ); + case 'Literal': + return new SourceNode( + ast.location.line, + ast.location.column, + ast.location.source, + String(ast.value) + ); + // ... + default: + throw new Error("Bad AST"); + } +} + +var ast = parse("40 + 2", "add.js"); +console.log(compile(ast).toStringWithSourceMap({ + file: 'add.js' +})); +// { code: '40 + 2', +// map: [object SourceMapGenerator] } +``` + +#### With SourceMapGenerator (low level API) + +```js +var map = new SourceMapGenerator({ + file: "source-mapped.js" +}); + +map.addMapping({ + generated: { + line: 10, + column: 35 + }, + source: "foo.js", + original: { + line: 33, + column: 2 + }, + name: "christopher" +}); + +console.log(map.toString()); +// '{"version":3,"file":"source-mapped.js","sources":["foo.js"],"names":["christopher"],"mappings":";;;;;;;;;mCAgCEA"}' +``` + +## API + +Get a reference to the module: + +```js +// Node.js +var sourceMap = require('source-map'); + +// Browser builds +var sourceMap = window.sourceMap; + +// Inside Firefox +const sourceMap = require("devtools/toolkit/sourcemap/source-map.js"); +``` + +### SourceMapConsumer + +A SourceMapConsumer instance represents a parsed source map which we can query +for information about the original file positions by giving it a file position +in the generated source. + +#### new SourceMapConsumer(rawSourceMap) + +The only parameter is the raw source map (either as a string which can be +`JSON.parse`'d, or an object). According to the spec, source maps have the +following attributes: + +* `version`: Which version of the source map spec this map is following. + +* `sources`: An array of URLs to the original source files. + +* `names`: An array of identifiers which can be referenced by individual + mappings. + +* `sourceRoot`: Optional. The URL root from which all sources are relative. + +* `sourcesContent`: Optional. An array of contents of the original source files. + +* `mappings`: A string of base64 VLQs which contain the actual mappings. + +* `file`: Optional. The generated filename this source map is associated with. + +```js +var consumer = new sourceMap.SourceMapConsumer(rawSourceMapJsonData); +``` + +#### SourceMapConsumer.prototype.computeColumnSpans() + +Compute the last column for each generated mapping. The last column is +inclusive. + +```js +// Before: +consumer.allGeneratedPositionsFor({ line: 2, source: "foo.coffee" }) +// [ { line: 2, +// column: 1 }, +// { line: 2, +// column: 10 }, +// { line: 2, +// column: 20 } ] + +consumer.computeColumnSpans(); + +// After: +consumer.allGeneratedPositionsFor({ line: 2, source: "foo.coffee" }) +// [ { line: 2, +// column: 1, +// lastColumn: 9 }, +// { line: 2, +// column: 10, +// lastColumn: 19 }, +// { line: 2, +// column: 20, +// lastColumn: Infinity } ] + +``` + +#### SourceMapConsumer.prototype.originalPositionFor(generatedPosition) + +Returns the original source, line, and column information for the generated +source's line and column positions provided. The only argument is an object with +the following properties: + +* `line`: The line number in the generated source. Line numbers in + this library are 1-based (note that the underlying source map + specification uses 0-based line numbers -- this library handles the + translation). + +* `column`: The column number in the generated source. Column numbers + in this library are 0-based. + +* `bias`: Either `SourceMapConsumer.GREATEST_LOWER_BOUND` or + `SourceMapConsumer.LEAST_UPPER_BOUND`. Specifies whether to return the closest + element that is smaller than or greater than the one we are searching for, + respectively, if the exact element cannot be found. Defaults to + `SourceMapConsumer.GREATEST_LOWER_BOUND`. + +and an object is returned with the following properties: + +* `source`: The original source file, or null if this information is not + available. + +* `line`: The line number in the original source, or null if this information is + not available. The line number is 1-based. + +* `column`: The column number in the original source, or null if this + information is not available. The column number is 0-based. + +* `name`: The original identifier, or null if this information is not available. + +```js +consumer.originalPositionFor({ line: 2, column: 10 }) +// { source: 'foo.coffee', +// line: 2, +// column: 2, +// name: null } + +consumer.originalPositionFor({ line: 99999999999999999, column: 999999999999999 }) +// { source: null, +// line: null, +// column: null, +// name: null } +``` + +#### SourceMapConsumer.prototype.generatedPositionFor(originalPosition) + +Returns the generated line and column information for the original source, +line, and column positions provided. The only argument is an object with +the following properties: + +* `source`: The filename of the original source. + +* `line`: The line number in the original source. The line number is + 1-based. + +* `column`: The column number in the original source. The column + number is 0-based. + +and an object is returned with the following properties: + +* `line`: The line number in the generated source, or null. The line + number is 1-based. + +* `column`: The column number in the generated source, or null. The + column number is 0-based. + +```js +consumer.generatedPositionFor({ source: "example.js", line: 2, column: 10 }) +// { line: 1, +// column: 56 } +``` + +#### SourceMapConsumer.prototype.allGeneratedPositionsFor(originalPosition) + +Returns all generated line and column information for the original source, line, +and column provided. If no column is provided, returns all mappings +corresponding to a either the line we are searching for or the next closest line +that has any mappings. Otherwise, returns all mappings corresponding to the +given line and either the column we are searching for or the next closest column +that has any offsets. + +The only argument is an object with the following properties: + +* `source`: The filename of the original source. + +* `line`: The line number in the original source. The line number is + 1-based. + +* `column`: Optional. The column number in the original source. The + column number is 0-based. + +and an array of objects is returned, each with the following properties: + +* `line`: The line number in the generated source, or null. The line + number is 1-based. + +* `column`: The column number in the generated source, or null. The + column number is 0-based. + +```js +consumer.allGeneratedpositionsfor({ line: 2, source: "foo.coffee" }) +// [ { line: 2, +// column: 1 }, +// { line: 2, +// column: 10 }, +// { line: 2, +// column: 20 } ] +``` + +#### SourceMapConsumer.prototype.hasContentsOfAllSources() + +Return true if we have the embedded source content for every source listed in +the source map, false otherwise. + +In other words, if this method returns `true`, then +`consumer.sourceContentFor(s)` will succeed for every source `s` in +`consumer.sources`. + +```js +// ... +if (consumer.hasContentsOfAllSources()) { + consumerReadyCallback(consumer); +} else { + fetchSources(consumer, consumerReadyCallback); +} +// ... +``` + +#### SourceMapConsumer.prototype.sourceContentFor(source[, returnNullOnMissing]) + +Returns the original source content for the source provided. The only +argument is the URL of the original source file. + +If the source content for the given source is not found, then an error is +thrown. Optionally, pass `true` as the second param to have `null` returned +instead. + +```js +consumer.sources +// [ "my-cool-lib.clj" ] + +consumer.sourceContentFor("my-cool-lib.clj") +// "..." + +consumer.sourceContentFor("this is not in the source map"); +// Error: "this is not in the source map" is not in the source map + +consumer.sourceContentFor("this is not in the source map", true); +// null +``` + +#### SourceMapConsumer.prototype.eachMapping(callback, context, order) + +Iterate over each mapping between an original source/line/column and a +generated line/column in this source map. + +* `callback`: The function that is called with each mapping. Mappings have the + form `{ source, generatedLine, generatedColumn, originalLine, originalColumn, + name }` + +* `context`: Optional. If specified, this object will be the value of `this` + every time that `callback` is called. + +* `order`: Either `SourceMapConsumer.GENERATED_ORDER` or + `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to iterate over + the mappings sorted by the generated file's line/column order or the + original's source/line/column order, respectively. Defaults to + `SourceMapConsumer.GENERATED_ORDER`. + +```js +consumer.eachMapping(function (m) { console.log(m); }) +// ... +// { source: 'illmatic.js', +// generatedLine: 1, +// generatedColumn: 0, +// originalLine: 1, +// originalColumn: 0, +// name: null } +// { source: 'illmatic.js', +// generatedLine: 2, +// generatedColumn: 0, +// originalLine: 2, +// originalColumn: 0, +// name: null } +// ... +``` +### SourceMapGenerator + +An instance of the SourceMapGenerator represents a source map which is being +built incrementally. + +#### new SourceMapGenerator([startOfSourceMap]) + +You may pass an object with the following properties: + +* `file`: The filename of the generated source that this source map is + associated with. + +* `sourceRoot`: A root for all relative URLs in this source map. + +* `skipValidation`: Optional. When `true`, disables validation of mappings as + they are added. This can improve performance but should be used with + discretion, as a last resort. Even then, one should avoid using this flag when + running tests, if possible. + +```js +var generator = new sourceMap.SourceMapGenerator({ + file: "my-generated-javascript-file.js", + sourceRoot: "http://example.com/app/js/" +}); +``` + +#### SourceMapGenerator.fromSourceMap(sourceMapConsumer) + +Creates a new `SourceMapGenerator` from an existing `SourceMapConsumer` instance. + +* `sourceMapConsumer` The SourceMap. + +```js +var generator = sourceMap.SourceMapGenerator.fromSourceMap(consumer); +``` + +#### SourceMapGenerator.prototype.addMapping(mapping) + +Add a single mapping from original source line and column to the generated +source's line and column for this source map being created. The mapping object +should have the following properties: + +* `generated`: An object with the generated line and column positions. + +* `original`: An object with the original line and column positions. + +* `source`: The original source file (relative to the sourceRoot). + +* `name`: An optional original token name for this mapping. + +```js +generator.addMapping({ + source: "module-one.scm", + original: { line: 128, column: 0 }, + generated: { line: 3, column: 456 } +}) +``` + +#### SourceMapGenerator.prototype.setSourceContent(sourceFile, sourceContent) + +Set the source content for an original source file. + +* `sourceFile` the URL of the original source file. + +* `sourceContent` the content of the source file. + +```js +generator.setSourceContent("module-one.scm", + fs.readFileSync("path/to/module-one.scm")) +``` + +#### SourceMapGenerator.prototype.applySourceMap(sourceMapConsumer[, sourceFile[, sourceMapPath]]) + +Applies a SourceMap for a source file to the SourceMap. +Each mapping to the supplied source file is rewritten using the +supplied SourceMap. Note: The resolution for the resulting mappings +is the minimum of this map and the supplied map. + +* `sourceMapConsumer`: The SourceMap to be applied. + +* `sourceFile`: Optional. The filename of the source file. + If omitted, sourceMapConsumer.file will be used, if it exists. + Otherwise an error will be thrown. + +* `sourceMapPath`: Optional. The dirname of the path to the SourceMap + to be applied. If relative, it is relative to the SourceMap. + + This parameter is needed when the two SourceMaps aren't in the same + directory, and the SourceMap to be applied contains relative source + paths. If so, those relative source paths need to be rewritten + relative to the SourceMap. + + If omitted, it is assumed that both SourceMaps are in the same directory, + thus not needing any rewriting. (Supplying `'.'` has the same effect.) + +#### SourceMapGenerator.prototype.toString() + +Renders the source map being generated to a string. + +```js +generator.toString() +// '{"version":3,"sources":["module-one.scm"],"names":[],"mappings":"...snip...","file":"my-generated-javascript-file.js","sourceRoot":"http://example.com/app/js/"}' +``` + +### SourceNode + +SourceNodes provide a way to abstract over interpolating and/or concatenating +snippets of generated JavaScript source code, while maintaining the line and +column information associated between those snippets and the original source +code. This is useful as the final intermediate representation a compiler might +use before outputting the generated JS and source map. + +#### new SourceNode([line, column, source[, chunk[, name]]]) + +* `line`: The original line number associated with this source node, or null if + it isn't associated with an original line. The line number is 1-based. + +* `column`: The original column number associated with this source node, or null + if it isn't associated with an original column. The column number + is 0-based. + +* `source`: The original source's filename; null if no filename is provided. + +* `chunk`: Optional. Is immediately passed to `SourceNode.prototype.add`, see + below. + +* `name`: Optional. The original identifier. + +```js +var node = new SourceNode(1, 2, "a.cpp", [ + new SourceNode(3, 4, "b.cpp", "extern int status;\n"), + new SourceNode(5, 6, "c.cpp", "std::string* make_string(size_t n);\n"), + new SourceNode(7, 8, "d.cpp", "int main(int argc, char** argv) {}\n"), +]); +``` + +#### SourceNode.fromStringWithSourceMap(code, sourceMapConsumer[, relativePath]) + +Creates a SourceNode from generated code and a SourceMapConsumer. + +* `code`: The generated code + +* `sourceMapConsumer` The SourceMap for the generated code + +* `relativePath` The optional path that relative sources in `sourceMapConsumer` + should be relative to. + +```js +var consumer = new SourceMapConsumer(fs.readFileSync("path/to/my-file.js.map", "utf8")); +var node = SourceNode.fromStringWithSourceMap(fs.readFileSync("path/to/my-file.js"), + consumer); +``` + +#### SourceNode.prototype.add(chunk) + +Add a chunk of generated JS to this source node. + +* `chunk`: A string snippet of generated JS code, another instance of + `SourceNode`, or an array where each member is one of those things. + +```js +node.add(" + "); +node.add(otherNode); +node.add([leftHandOperandNode, " + ", rightHandOperandNode]); +``` + +#### SourceNode.prototype.prepend(chunk) + +Prepend a chunk of generated JS to this source node. + +* `chunk`: A string snippet of generated JS code, another instance of + `SourceNode`, or an array where each member is one of those things. + +```js +node.prepend("/** Build Id: f783haef86324gf **/\n\n"); +``` + +#### SourceNode.prototype.setSourceContent(sourceFile, sourceContent) + +Set the source content for a source file. This will be added to the +`SourceMap` in the `sourcesContent` field. + +* `sourceFile`: The filename of the source file + +* `sourceContent`: The content of the source file + +```js +node.setSourceContent("module-one.scm", + fs.readFileSync("path/to/module-one.scm")) +``` + +#### SourceNode.prototype.walk(fn) + +Walk over the tree of JS snippets in this node and its children. The walking +function is called once for each snippet of JS and is passed that snippet and +the its original associated source's line/column location. + +* `fn`: The traversal function. + +```js +var node = new SourceNode(1, 2, "a.js", [ + new SourceNode(3, 4, "b.js", "uno"), + "dos", + [ + "tres", + new SourceNode(5, 6, "c.js", "quatro") + ] +]); + +node.walk(function (code, loc) { console.log("WALK:", code, loc); }) +// WALK: uno { source: 'b.js', line: 3, column: 4, name: null } +// WALK: dos { source: 'a.js', line: 1, column: 2, name: null } +// WALK: tres { source: 'a.js', line: 1, column: 2, name: null } +// WALK: quatro { source: 'c.js', line: 5, column: 6, name: null } +``` + +#### SourceNode.prototype.walkSourceContents(fn) + +Walk over the tree of SourceNodes. The walking function is called for each +source file content and is passed the filename and source content. + +* `fn`: The traversal function. + +```js +var a = new SourceNode(1, 2, "a.js", "generated from a"); +a.setSourceContent("a.js", "original a"); +var b = new SourceNode(1, 2, "b.js", "generated from b"); +b.setSourceContent("b.js", "original b"); +var c = new SourceNode(1, 2, "c.js", "generated from c"); +c.setSourceContent("c.js", "original c"); + +var node = new SourceNode(null, null, null, [a, b, c]); +node.walkSourceContents(function (source, contents) { console.log("WALK:", source, ":", contents); }) +// WALK: a.js : original a +// WALK: b.js : original b +// WALK: c.js : original c +``` + +#### SourceNode.prototype.join(sep) + +Like `Array.prototype.join` except for SourceNodes. Inserts the separator +between each of this source node's children. + +* `sep`: The separator. + +```js +var lhs = new SourceNode(1, 2, "a.rs", "my_copy"); +var operand = new SourceNode(3, 4, "a.rs", "="); +var rhs = new SourceNode(5, 6, "a.rs", "orig.clone()"); + +var node = new SourceNode(null, null, null, [ lhs, operand, rhs ]); +var joinedNode = node.join(" "); +``` + +#### SourceNode.prototype.replaceRight(pattern, replacement) + +Call `String.prototype.replace` on the very right-most source snippet. Useful +for trimming white space from the end of a source node, etc. + +* `pattern`: The pattern to replace. + +* `replacement`: The thing to replace the pattern with. + +```js +// Trim trailing white space. +node.replaceRight(/\s*$/, ""); +``` + +#### SourceNode.prototype.toString() + +Return the string representation of this source node. Walks over the tree and +concatenates all the various snippets together to one string. + +```js +var node = new SourceNode(1, 2, "a.js", [ + new SourceNode(3, 4, "b.js", "uno"), + "dos", + [ + "tres", + new SourceNode(5, 6, "c.js", "quatro") + ] +]); + +node.toString() +// 'unodostresquatro' +``` + +#### SourceNode.prototype.toStringWithSourceMap([startOfSourceMap]) + +Returns the string representation of this tree of source nodes, plus a +SourceMapGenerator which contains all the mappings between the generated and +original sources. + +The arguments are the same as those to `new SourceMapGenerator`. + +```js +var node = new SourceNode(1, 2, "a.js", [ + new SourceNode(3, 4, "b.js", "uno"), + "dos", + [ + "tres", + new SourceNode(5, 6, "c.js", "quatro") + ] +]); + +node.toStringWithSourceMap({ file: "my-output-file.js" }) +// { code: 'unodostresquatro', +// map: [object SourceMapGenerator] } +``` diff --git a/node_modules/source-map/dist/source-map.debug.js b/node_modules/source-map/dist/source-map.debug.js new file mode 100644 index 0000000..aad0620 --- /dev/null +++ b/node_modules/source-map/dist/source-map.debug.js @@ -0,0 +1,3234 @@ +(function webpackUniversalModuleDefinition(root, factory) { + if(typeof exports === 'object' && typeof module === 'object') + module.exports = factory(); + else if(typeof define === 'function' && define.amd) + define([], factory); + else if(typeof exports === 'object') + exports["sourceMap"] = factory(); + else + root["sourceMap"] = factory(); +})(this, function() { +return /******/ (function(modules) { // webpackBootstrap +/******/ // The module cache +/******/ var installedModules = {}; +/******/ +/******/ // The require function +/******/ function __webpack_require__(moduleId) { +/******/ +/******/ // Check if module is in cache +/******/ if(installedModules[moduleId]) +/******/ return installedModules[moduleId].exports; +/******/ +/******/ // Create a new module (and put it into the cache) +/******/ var module = installedModules[moduleId] = { +/******/ exports: {}, +/******/ id: moduleId, +/******/ loaded: false +/******/ }; +/******/ +/******/ // Execute the module function +/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); +/******/ +/******/ // Flag the module as loaded +/******/ module.loaded = true; +/******/ +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } +/******/ +/******/ +/******/ // expose the modules object (__webpack_modules__) +/******/ __webpack_require__.m = modules; +/******/ +/******/ // expose the module cache +/******/ __webpack_require__.c = installedModules; +/******/ +/******/ // __webpack_public_path__ +/******/ __webpack_require__.p = ""; +/******/ +/******/ // Load entry module and return exports +/******/ return __webpack_require__(0); +/******/ }) +/************************************************************************/ +/******/ ([ +/* 0 */ +/***/ (function(module, exports, __webpack_require__) { + + /* + * Copyright 2009-2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE.txt or: + * http://opensource.org/licenses/BSD-3-Clause + */ + exports.SourceMapGenerator = __webpack_require__(1).SourceMapGenerator; + exports.SourceMapConsumer = __webpack_require__(7).SourceMapConsumer; + exports.SourceNode = __webpack_require__(10).SourceNode; + + +/***/ }), +/* 1 */ +/***/ (function(module, exports, __webpack_require__) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + var base64VLQ = __webpack_require__(2); + var util = __webpack_require__(4); + var ArraySet = __webpack_require__(5).ArraySet; + var MappingList = __webpack_require__(6).MappingList; + + /** + * An instance of the SourceMapGenerator represents a source map which is + * being built incrementally. You may pass an object with the following + * properties: + * + * - file: The filename of the generated source. + * - sourceRoot: A root for all relative URLs in this source map. + */ + function SourceMapGenerator(aArgs) { + if (!aArgs) { + aArgs = {}; + } + this._file = util.getArg(aArgs, 'file', null); + this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null); + this._skipValidation = util.getArg(aArgs, 'skipValidation', false); + this._sources = new ArraySet(); + this._names = new ArraySet(); + this._mappings = new MappingList(); + this._sourcesContents = null; + } + + SourceMapGenerator.prototype._version = 3; + + /** + * Creates a new SourceMapGenerator based on a SourceMapConsumer + * + * @param aSourceMapConsumer The SourceMap. + */ + SourceMapGenerator.fromSourceMap = + function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) { + var sourceRoot = aSourceMapConsumer.sourceRoot; + var generator = new SourceMapGenerator({ + file: aSourceMapConsumer.file, + sourceRoot: sourceRoot + }); + aSourceMapConsumer.eachMapping(function (mapping) { + var newMapping = { + generated: { + line: mapping.generatedLine, + column: mapping.generatedColumn + } + }; + + if (mapping.source != null) { + newMapping.source = mapping.source; + if (sourceRoot != null) { + newMapping.source = util.relative(sourceRoot, newMapping.source); + } + + newMapping.original = { + line: mapping.originalLine, + column: mapping.originalColumn + }; + + if (mapping.name != null) { + newMapping.name = mapping.name; + } + } + + generator.addMapping(newMapping); + }); + aSourceMapConsumer.sources.forEach(function (sourceFile) { + var sourceRelative = sourceFile; + if (sourceRoot !== null) { + sourceRelative = util.relative(sourceRoot, sourceFile); + } + + if (!generator._sources.has(sourceRelative)) { + generator._sources.add(sourceRelative); + } + + var content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content != null) { + generator.setSourceContent(sourceFile, content); + } + }); + return generator; + }; + + /** + * Add a single mapping from original source line and column to the generated + * source's line and column for this source map being created. The mapping + * object should have the following properties: + * + * - generated: An object with the generated line and column positions. + * - original: An object with the original line and column positions. + * - source: The original source file (relative to the sourceRoot). + * - name: An optional original token name for this mapping. + */ + SourceMapGenerator.prototype.addMapping = + function SourceMapGenerator_addMapping(aArgs) { + var generated = util.getArg(aArgs, 'generated'); + var original = util.getArg(aArgs, 'original', null); + var source = util.getArg(aArgs, 'source', null); + var name = util.getArg(aArgs, 'name', null); + + if (!this._skipValidation) { + this._validateMapping(generated, original, source, name); + } + + if (source != null) { + source = String(source); + if (!this._sources.has(source)) { + this._sources.add(source); + } + } + + if (name != null) { + name = String(name); + if (!this._names.has(name)) { + this._names.add(name); + } + } + + this._mappings.add({ + generatedLine: generated.line, + generatedColumn: generated.column, + originalLine: original != null && original.line, + originalColumn: original != null && original.column, + source: source, + name: name + }); + }; + + /** + * Set the source content for a source file. + */ + SourceMapGenerator.prototype.setSourceContent = + function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) { + var source = aSourceFile; + if (this._sourceRoot != null) { + source = util.relative(this._sourceRoot, source); + } + + if (aSourceContent != null) { + // Add the source content to the _sourcesContents map. + // Create a new _sourcesContents map if the property is null. + if (!this._sourcesContents) { + this._sourcesContents = Object.create(null); + } + this._sourcesContents[util.toSetString(source)] = aSourceContent; + } else if (this._sourcesContents) { + // Remove the source file from the _sourcesContents map. + // If the _sourcesContents map is empty, set the property to null. + delete this._sourcesContents[util.toSetString(source)]; + if (Object.keys(this._sourcesContents).length === 0) { + this._sourcesContents = null; + } + } + }; + + /** + * Applies the mappings of a sub-source-map for a specific source file to the + * source map being generated. Each mapping to the supplied source file is + * rewritten using the supplied source map. Note: The resolution for the + * resulting mappings is the minimium of this map and the supplied map. + * + * @param aSourceMapConsumer The source map to be applied. + * @param aSourceFile Optional. The filename of the source file. + * If omitted, SourceMapConsumer's file property will be used. + * @param aSourceMapPath Optional. The dirname of the path to the source map + * to be applied. If relative, it is relative to the SourceMapConsumer. + * This parameter is needed when the two source maps aren't in the same + * directory, and the source map to be applied contains relative source + * paths. If so, those relative source paths need to be rewritten + * relative to the SourceMapGenerator. + */ + SourceMapGenerator.prototype.applySourceMap = + function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) { + var sourceFile = aSourceFile; + // If aSourceFile is omitted, we will use the file property of the SourceMap + if (aSourceFile == null) { + if (aSourceMapConsumer.file == null) { + throw new Error( + 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' + + 'or the source map\'s "file" property. Both were omitted.' + ); + } + sourceFile = aSourceMapConsumer.file; + } + var sourceRoot = this._sourceRoot; + // Make "sourceFile" relative if an absolute Url is passed. + if (sourceRoot != null) { + sourceFile = util.relative(sourceRoot, sourceFile); + } + // Applying the SourceMap can add and remove items from the sources and + // the names array. + var newSources = new ArraySet(); + var newNames = new ArraySet(); + + // Find mappings for the "sourceFile" + this._mappings.unsortedForEach(function (mapping) { + if (mapping.source === sourceFile && mapping.originalLine != null) { + // Check if it can be mapped by the source map, then update the mapping. + var original = aSourceMapConsumer.originalPositionFor({ + line: mapping.originalLine, + column: mapping.originalColumn + }); + if (original.source != null) { + // Copy mapping + mapping.source = original.source; + if (aSourceMapPath != null) { + mapping.source = util.join(aSourceMapPath, mapping.source) + } + if (sourceRoot != null) { + mapping.source = util.relative(sourceRoot, mapping.source); + } + mapping.originalLine = original.line; + mapping.originalColumn = original.column; + if (original.name != null) { + mapping.name = original.name; + } + } + } + + var source = mapping.source; + if (source != null && !newSources.has(source)) { + newSources.add(source); + } + + var name = mapping.name; + if (name != null && !newNames.has(name)) { + newNames.add(name); + } + + }, this); + this._sources = newSources; + this._names = newNames; + + // Copy sourcesContents of applied map. + aSourceMapConsumer.sources.forEach(function (sourceFile) { + var content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content != null) { + if (aSourceMapPath != null) { + sourceFile = util.join(aSourceMapPath, sourceFile); + } + if (sourceRoot != null) { + sourceFile = util.relative(sourceRoot, sourceFile); + } + this.setSourceContent(sourceFile, content); + } + }, this); + }; + + /** + * A mapping can have one of the three levels of data: + * + * 1. Just the generated position. + * 2. The Generated position, original position, and original source. + * 3. Generated and original position, original source, as well as a name + * token. + * + * To maintain consistency, we validate that any new mapping being added falls + * in to one of these categories. + */ + SourceMapGenerator.prototype._validateMapping = + function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource, + aName) { + // When aOriginal is truthy but has empty values for .line and .column, + // it is most likely a programmer error. In this case we throw a very + // specific error message to try to guide them the right way. + // For example: https://github.com/Polymer/polymer-bundler/pull/519 + if (aOriginal && typeof aOriginal.line !== 'number' && typeof aOriginal.column !== 'number') { + throw new Error( + 'original.line and original.column are not numbers -- you probably meant to omit ' + + 'the original mapping entirely and only map the generated position. If so, pass ' + + 'null for the original mapping instead of an object with empty or null values.' + ); + } + + if (aGenerated && 'line' in aGenerated && 'column' in aGenerated + && aGenerated.line > 0 && aGenerated.column >= 0 + && !aOriginal && !aSource && !aName) { + // Case 1. + return; + } + else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated + && aOriginal && 'line' in aOriginal && 'column' in aOriginal + && aGenerated.line > 0 && aGenerated.column >= 0 + && aOriginal.line > 0 && aOriginal.column >= 0 + && aSource) { + // Cases 2 and 3. + return; + } + else { + throw new Error('Invalid mapping: ' + JSON.stringify({ + generated: aGenerated, + source: aSource, + original: aOriginal, + name: aName + })); + } + }; + + /** + * Serialize the accumulated mappings in to the stream of base 64 VLQs + * specified by the source map format. + */ + SourceMapGenerator.prototype._serializeMappings = + function SourceMapGenerator_serializeMappings() { + var previousGeneratedColumn = 0; + var previousGeneratedLine = 1; + var previousOriginalColumn = 0; + var previousOriginalLine = 0; + var previousName = 0; + var previousSource = 0; + var result = ''; + var next; + var mapping; + var nameIdx; + var sourceIdx; + + var mappings = this._mappings.toArray(); + for (var i = 0, len = mappings.length; i < len; i++) { + mapping = mappings[i]; + next = '' + + if (mapping.generatedLine !== previousGeneratedLine) { + previousGeneratedColumn = 0; + while (mapping.generatedLine !== previousGeneratedLine) { + next += ';'; + previousGeneratedLine++; + } + } + else { + if (i > 0) { + if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) { + continue; + } + next += ','; + } + } + + next += base64VLQ.encode(mapping.generatedColumn + - previousGeneratedColumn); + previousGeneratedColumn = mapping.generatedColumn; + + if (mapping.source != null) { + sourceIdx = this._sources.indexOf(mapping.source); + next += base64VLQ.encode(sourceIdx - previousSource); + previousSource = sourceIdx; + + // lines are stored 0-based in SourceMap spec version 3 + next += base64VLQ.encode(mapping.originalLine - 1 + - previousOriginalLine); + previousOriginalLine = mapping.originalLine - 1; + + next += base64VLQ.encode(mapping.originalColumn + - previousOriginalColumn); + previousOriginalColumn = mapping.originalColumn; + + if (mapping.name != null) { + nameIdx = this._names.indexOf(mapping.name); + next += base64VLQ.encode(nameIdx - previousName); + previousName = nameIdx; + } + } + + result += next; + } + + return result; + }; + + SourceMapGenerator.prototype._generateSourcesContent = + function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) { + return aSources.map(function (source) { + if (!this._sourcesContents) { + return null; + } + if (aSourceRoot != null) { + source = util.relative(aSourceRoot, source); + } + var key = util.toSetString(source); + return Object.prototype.hasOwnProperty.call(this._sourcesContents, key) + ? this._sourcesContents[key] + : null; + }, this); + }; + + /** + * Externalize the source map. + */ + SourceMapGenerator.prototype.toJSON = + function SourceMapGenerator_toJSON() { + var map = { + version: this._version, + sources: this._sources.toArray(), + names: this._names.toArray(), + mappings: this._serializeMappings() + }; + if (this._file != null) { + map.file = this._file; + } + if (this._sourceRoot != null) { + map.sourceRoot = this._sourceRoot; + } + if (this._sourcesContents) { + map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot); + } + + return map; + }; + + /** + * Render the source map being generated to a string. + */ + SourceMapGenerator.prototype.toString = + function SourceMapGenerator_toString() { + return JSON.stringify(this.toJSON()); + }; + + exports.SourceMapGenerator = SourceMapGenerator; + + +/***/ }), +/* 2 */ +/***/ (function(module, exports, __webpack_require__) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + * + * Based on the Base 64 VLQ implementation in Closure Compiler: + * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java + * + * Copyright 2011 The Closure Compiler Authors. All rights reserved. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + + var base64 = __webpack_require__(3); + + // A single base 64 digit can contain 6 bits of data. For the base 64 variable + // length quantities we use in the source map spec, the first bit is the sign, + // the next four bits are the actual value, and the 6th bit is the + // continuation bit. The continuation bit tells us whether there are more + // digits in this value following this digit. + // + // Continuation + // | Sign + // | | + // V V + // 101011 + + var VLQ_BASE_SHIFT = 5; + + // binary: 100000 + var VLQ_BASE = 1 << VLQ_BASE_SHIFT; + + // binary: 011111 + var VLQ_BASE_MASK = VLQ_BASE - 1; + + // binary: 100000 + var VLQ_CONTINUATION_BIT = VLQ_BASE; + + /** + * Converts from a two-complement value to a value where the sign bit is + * placed in the least significant bit. For example, as decimals: + * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary) + * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary) + */ + function toVLQSigned(aValue) { + return aValue < 0 + ? ((-aValue) << 1) + 1 + : (aValue << 1) + 0; + } + + /** + * Converts to a two-complement value from a value where the sign bit is + * placed in the least significant bit. For example, as decimals: + * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1 + * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2 + */ + function fromVLQSigned(aValue) { + var isNegative = (aValue & 1) === 1; + var shifted = aValue >> 1; + return isNegative + ? -shifted + : shifted; + } + + /** + * Returns the base 64 VLQ encoded value. + */ + exports.encode = function base64VLQ_encode(aValue) { + var encoded = ""; + var digit; + + var vlq = toVLQSigned(aValue); + + do { + digit = vlq & VLQ_BASE_MASK; + vlq >>>= VLQ_BASE_SHIFT; + if (vlq > 0) { + // There are still more digits in this value, so we must make sure the + // continuation bit is marked. + digit |= VLQ_CONTINUATION_BIT; + } + encoded += base64.encode(digit); + } while (vlq > 0); + + return encoded; + }; + + /** + * Decodes the next base 64 VLQ value from the given string and returns the + * value and the rest of the string via the out parameter. + */ + exports.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) { + var strLen = aStr.length; + var result = 0; + var shift = 0; + var continuation, digit; + + do { + if (aIndex >= strLen) { + throw new Error("Expected more digits in base 64 VLQ value."); + } + + digit = base64.decode(aStr.charCodeAt(aIndex++)); + if (digit === -1) { + throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1)); + } + + continuation = !!(digit & VLQ_CONTINUATION_BIT); + digit &= VLQ_BASE_MASK; + result = result + (digit << shift); + shift += VLQ_BASE_SHIFT; + } while (continuation); + + aOutParam.value = fromVLQSigned(result); + aOutParam.rest = aIndex; + }; + + +/***/ }), +/* 3 */ +/***/ (function(module, exports) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + var intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split(''); + + /** + * Encode an integer in the range of 0 to 63 to a single base 64 digit. + */ + exports.encode = function (number) { + if (0 <= number && number < intToCharMap.length) { + return intToCharMap[number]; + } + throw new TypeError("Must be between 0 and 63: " + number); + }; + + /** + * Decode a single base 64 character code digit to an integer. Returns -1 on + * failure. + */ + exports.decode = function (charCode) { + var bigA = 65; // 'A' + var bigZ = 90; // 'Z' + + var littleA = 97; // 'a' + var littleZ = 122; // 'z' + + var zero = 48; // '0' + var nine = 57; // '9' + + var plus = 43; // '+' + var slash = 47; // '/' + + var littleOffset = 26; + var numberOffset = 52; + + // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ + if (bigA <= charCode && charCode <= bigZ) { + return (charCode - bigA); + } + + // 26 - 51: abcdefghijklmnopqrstuvwxyz + if (littleA <= charCode && charCode <= littleZ) { + return (charCode - littleA + littleOffset); + } + + // 52 - 61: 0123456789 + if (zero <= charCode && charCode <= nine) { + return (charCode - zero + numberOffset); + } + + // 62: + + if (charCode == plus) { + return 62; + } + + // 63: / + if (charCode == slash) { + return 63; + } + + // Invalid base64 digit. + return -1; + }; + + +/***/ }), +/* 4 */ +/***/ (function(module, exports) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + /** + * This is a helper function for getting values from parameter/options + * objects. + * + * @param args The object we are extracting values from + * @param name The name of the property we are getting. + * @param defaultValue An optional value to return if the property is missing + * from the object. If this is not specified and the property is missing, an + * error will be thrown. + */ + function getArg(aArgs, aName, aDefaultValue) { + if (aName in aArgs) { + return aArgs[aName]; + } else if (arguments.length === 3) { + return aDefaultValue; + } else { + throw new Error('"' + aName + '" is a required argument.'); + } + } + exports.getArg = getArg; + + var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/; + var dataUrlRegexp = /^data:.+\,.+$/; + + function urlParse(aUrl) { + var match = aUrl.match(urlRegexp); + if (!match) { + return null; + } + return { + scheme: match[1], + auth: match[2], + host: match[3], + port: match[4], + path: match[5] + }; + } + exports.urlParse = urlParse; + + function urlGenerate(aParsedUrl) { + var url = ''; + if (aParsedUrl.scheme) { + url += aParsedUrl.scheme + ':'; + } + url += '//'; + if (aParsedUrl.auth) { + url += aParsedUrl.auth + '@'; + } + if (aParsedUrl.host) { + url += aParsedUrl.host; + } + if (aParsedUrl.port) { + url += ":" + aParsedUrl.port + } + if (aParsedUrl.path) { + url += aParsedUrl.path; + } + return url; + } + exports.urlGenerate = urlGenerate; + + /** + * Normalizes a path, or the path portion of a URL: + * + * - Replaces consecutive slashes with one slash. + * - Removes unnecessary '.' parts. + * - Removes unnecessary '/..' parts. + * + * Based on code in the Node.js 'path' core module. + * + * @param aPath The path or url to normalize. + */ + function normalize(aPath) { + var path = aPath; + var url = urlParse(aPath); + if (url) { + if (!url.path) { + return aPath; + } + path = url.path; + } + var isAbsolute = exports.isAbsolute(path); + + var parts = path.split(/\/+/); + for (var part, up = 0, i = parts.length - 1; i >= 0; i--) { + part = parts[i]; + if (part === '.') { + parts.splice(i, 1); + } else if (part === '..') { + up++; + } else if (up > 0) { + if (part === '') { + // The first part is blank if the path is absolute. Trying to go + // above the root is a no-op. Therefore we can remove all '..' parts + // directly after the root. + parts.splice(i + 1, up); + up = 0; + } else { + parts.splice(i, 2); + up--; + } + } + } + path = parts.join('/'); + + if (path === '') { + path = isAbsolute ? '/' : '.'; + } + + if (url) { + url.path = path; + return urlGenerate(url); + } + return path; + } + exports.normalize = normalize; + + /** + * Joins two paths/URLs. + * + * @param aRoot The root path or URL. + * @param aPath The path or URL to be joined with the root. + * + * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a + * scheme-relative URL: Then the scheme of aRoot, if any, is prepended + * first. + * - Otherwise aPath is a path. If aRoot is a URL, then its path portion + * is updated with the result and aRoot is returned. Otherwise the result + * is returned. + * - If aPath is absolute, the result is aPath. + * - Otherwise the two paths are joined with a slash. + * - Joining for example 'http://' and 'www.example.com' is also supported. + */ + function join(aRoot, aPath) { + if (aRoot === "") { + aRoot = "."; + } + if (aPath === "") { + aPath = "."; + } + var aPathUrl = urlParse(aPath); + var aRootUrl = urlParse(aRoot); + if (aRootUrl) { + aRoot = aRootUrl.path || '/'; + } + + // `join(foo, '//www.example.org')` + if (aPathUrl && !aPathUrl.scheme) { + if (aRootUrl) { + aPathUrl.scheme = aRootUrl.scheme; + } + return urlGenerate(aPathUrl); + } + + if (aPathUrl || aPath.match(dataUrlRegexp)) { + return aPath; + } + + // `join('http://', 'www.example.com')` + if (aRootUrl && !aRootUrl.host && !aRootUrl.path) { + aRootUrl.host = aPath; + return urlGenerate(aRootUrl); + } + + var joined = aPath.charAt(0) === '/' + ? aPath + : normalize(aRoot.replace(/\/+$/, '') + '/' + aPath); + + if (aRootUrl) { + aRootUrl.path = joined; + return urlGenerate(aRootUrl); + } + return joined; + } + exports.join = join; + + exports.isAbsolute = function (aPath) { + return aPath.charAt(0) === '/' || urlRegexp.test(aPath); + }; + + /** + * Make a path relative to a URL or another path. + * + * @param aRoot The root path or URL. + * @param aPath The path or URL to be made relative to aRoot. + */ + function relative(aRoot, aPath) { + if (aRoot === "") { + aRoot = "."; + } + + aRoot = aRoot.replace(/\/$/, ''); + + // It is possible for the path to be above the root. In this case, simply + // checking whether the root is a prefix of the path won't work. Instead, we + // need to remove components from the root one by one, until either we find + // a prefix that fits, or we run out of components to remove. + var level = 0; + while (aPath.indexOf(aRoot + '/') !== 0) { + var index = aRoot.lastIndexOf("/"); + if (index < 0) { + return aPath; + } + + // If the only part of the root that is left is the scheme (i.e. http://, + // file:///, etc.), one or more slashes (/), or simply nothing at all, we + // have exhausted all components, so the path is not relative to the root. + aRoot = aRoot.slice(0, index); + if (aRoot.match(/^([^\/]+:\/)?\/*$/)) { + return aPath; + } + + ++level; + } + + // Make sure we add a "../" for each component we removed from the root. + return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1); + } + exports.relative = relative; + + var supportsNullProto = (function () { + var obj = Object.create(null); + return !('__proto__' in obj); + }()); + + function identity (s) { + return s; + } + + /** + * Because behavior goes wacky when you set `__proto__` on objects, we + * have to prefix all the strings in our set with an arbitrary character. + * + * See https://github.com/mozilla/source-map/pull/31 and + * https://github.com/mozilla/source-map/issues/30 + * + * @param String aStr + */ + function toSetString(aStr) { + if (isProtoString(aStr)) { + return '$' + aStr; + } + + return aStr; + } + exports.toSetString = supportsNullProto ? identity : toSetString; + + function fromSetString(aStr) { + if (isProtoString(aStr)) { + return aStr.slice(1); + } + + return aStr; + } + exports.fromSetString = supportsNullProto ? identity : fromSetString; + + function isProtoString(s) { + if (!s) { + return false; + } + + var length = s.length; + + if (length < 9 /* "__proto__".length */) { + return false; + } + + if (s.charCodeAt(length - 1) !== 95 /* '_' */ || + s.charCodeAt(length - 2) !== 95 /* '_' */ || + s.charCodeAt(length - 3) !== 111 /* 'o' */ || + s.charCodeAt(length - 4) !== 116 /* 't' */ || + s.charCodeAt(length - 5) !== 111 /* 'o' */ || + s.charCodeAt(length - 6) !== 114 /* 'r' */ || + s.charCodeAt(length - 7) !== 112 /* 'p' */ || + s.charCodeAt(length - 8) !== 95 /* '_' */ || + s.charCodeAt(length - 9) !== 95 /* '_' */) { + return false; + } + + for (var i = length - 10; i >= 0; i--) { + if (s.charCodeAt(i) !== 36 /* '$' */) { + return false; + } + } + + return true; + } + + /** + * Comparator between two mappings where the original positions are compared. + * + * Optionally pass in `true` as `onlyCompareGenerated` to consider two + * mappings with the same original source/line/column, but different generated + * line and column the same. Useful when searching for a mapping with a + * stubbed out mapping. + */ + function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) { + var cmp = strcmp(mappingA.source, mappingB.source); + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0 || onlyCompareOriginal) { + return cmp; + } + + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } + + return strcmp(mappingA.name, mappingB.name); + } + exports.compareByOriginalPositions = compareByOriginalPositions; + + /** + * Comparator between two mappings with deflated source and name indices where + * the generated positions are compared. + * + * Optionally pass in `true` as `onlyCompareGenerated` to consider two + * mappings with the same generated line and column, but different + * source/name/original line and column the same. Useful when searching for a + * mapping with a stubbed out mapping. + */ + function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) { + var cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0 || onlyCompareGenerated) { + return cmp; + } + + cmp = strcmp(mappingA.source, mappingB.source); + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0) { + return cmp; + } + + return strcmp(mappingA.name, mappingB.name); + } + exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated; + + function strcmp(aStr1, aStr2) { + if (aStr1 === aStr2) { + return 0; + } + + if (aStr1 === null) { + return 1; // aStr2 !== null + } + + if (aStr2 === null) { + return -1; // aStr1 !== null + } + + if (aStr1 > aStr2) { + return 1; + } + + return -1; + } + + /** + * Comparator between two mappings with inflated source and name strings where + * the generated positions are compared. + */ + function compareByGeneratedPositionsInflated(mappingA, mappingB) { + var cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0) { + return cmp; + } + + cmp = strcmp(mappingA.source, mappingB.source); + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0) { + return cmp; + } + + return strcmp(mappingA.name, mappingB.name); + } + exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated; + + /** + * Strip any JSON XSSI avoidance prefix from the string (as documented + * in the source maps specification), and then parse the string as + * JSON. + */ + function parseSourceMapInput(str) { + return JSON.parse(str.replace(/^\)]}'[^\n]*\n/, '')); + } + exports.parseSourceMapInput = parseSourceMapInput; + + /** + * Compute the URL of a source given the the source root, the source's + * URL, and the source map's URL. + */ + function computeSourceURL(sourceRoot, sourceURL, sourceMapURL) { + sourceURL = sourceURL || ''; + + if (sourceRoot) { + // This follows what Chrome does. + if (sourceRoot[sourceRoot.length - 1] !== '/' && sourceURL[0] !== '/') { + sourceRoot += '/'; + } + // The spec says: + // Line 4: An optional source root, useful for relocating source + // files on a server or removing repeated values in the + // “sources” entry. This value is prepended to the individual + // entries in the “source” field. + sourceURL = sourceRoot + sourceURL; + } + + // Historically, SourceMapConsumer did not take the sourceMapURL as + // a parameter. This mode is still somewhat supported, which is why + // this code block is conditional. However, it's preferable to pass + // the source map URL to SourceMapConsumer, so that this function + // can implement the source URL resolution algorithm as outlined in + // the spec. This block is basically the equivalent of: + // new URL(sourceURL, sourceMapURL).toString() + // ... except it avoids using URL, which wasn't available in the + // older releases of node still supported by this library. + // + // The spec says: + // If the sources are not absolute URLs after prepending of the + // “sourceRoot”, the sources are resolved relative to the + // SourceMap (like resolving script src in a html document). + if (sourceMapURL) { + var parsed = urlParse(sourceMapURL); + if (!parsed) { + throw new Error("sourceMapURL could not be parsed"); + } + if (parsed.path) { + // Strip the last path component, but keep the "/". + var index = parsed.path.lastIndexOf('/'); + if (index >= 0) { + parsed.path = parsed.path.substring(0, index + 1); + } + } + sourceURL = join(urlGenerate(parsed), sourceURL); + } + + return normalize(sourceURL); + } + exports.computeSourceURL = computeSourceURL; + + +/***/ }), +/* 5 */ +/***/ (function(module, exports, __webpack_require__) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + var util = __webpack_require__(4); + var has = Object.prototype.hasOwnProperty; + var hasNativeMap = typeof Map !== "undefined"; + + /** + * A data structure which is a combination of an array and a set. Adding a new + * member is O(1), testing for membership is O(1), and finding the index of an + * element is O(1). Removing elements from the set is not supported. Only + * strings are supported for membership. + */ + function ArraySet() { + this._array = []; + this._set = hasNativeMap ? new Map() : Object.create(null); + } + + /** + * Static method for creating ArraySet instances from an existing array. + */ + ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) { + var set = new ArraySet(); + for (var i = 0, len = aArray.length; i < len; i++) { + set.add(aArray[i], aAllowDuplicates); + } + return set; + }; + + /** + * Return how many unique items are in this ArraySet. If duplicates have been + * added, than those do not count towards the size. + * + * @returns Number + */ + ArraySet.prototype.size = function ArraySet_size() { + return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length; + }; + + /** + * Add the given string to this set. + * + * @param String aStr + */ + ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) { + var sStr = hasNativeMap ? aStr : util.toSetString(aStr); + var isDuplicate = hasNativeMap ? this.has(aStr) : has.call(this._set, sStr); + var idx = this._array.length; + if (!isDuplicate || aAllowDuplicates) { + this._array.push(aStr); + } + if (!isDuplicate) { + if (hasNativeMap) { + this._set.set(aStr, idx); + } else { + this._set[sStr] = idx; + } + } + }; + + /** + * Is the given string a member of this set? + * + * @param String aStr + */ + ArraySet.prototype.has = function ArraySet_has(aStr) { + if (hasNativeMap) { + return this._set.has(aStr); + } else { + var sStr = util.toSetString(aStr); + return has.call(this._set, sStr); + } + }; + + /** + * What is the index of the given string in the array? + * + * @param String aStr + */ + ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) { + if (hasNativeMap) { + var idx = this._set.get(aStr); + if (idx >= 0) { + return idx; + } + } else { + var sStr = util.toSetString(aStr); + if (has.call(this._set, sStr)) { + return this._set[sStr]; + } + } + + throw new Error('"' + aStr + '" is not in the set.'); + }; + + /** + * What is the element at the given index? + * + * @param Number aIdx + */ + ArraySet.prototype.at = function ArraySet_at(aIdx) { + if (aIdx >= 0 && aIdx < this._array.length) { + return this._array[aIdx]; + } + throw new Error('No element indexed by ' + aIdx); + }; + + /** + * Returns the array representation of this set (which has the proper indices + * indicated by indexOf). Note that this is a copy of the internal array used + * for storing the members so that no one can mess with internal state. + */ + ArraySet.prototype.toArray = function ArraySet_toArray() { + return this._array.slice(); + }; + + exports.ArraySet = ArraySet; + + +/***/ }), +/* 6 */ +/***/ (function(module, exports, __webpack_require__) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2014 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + var util = __webpack_require__(4); + + /** + * Determine whether mappingB is after mappingA with respect to generated + * position. + */ + function generatedPositionAfter(mappingA, mappingB) { + // Optimized for most common case + var lineA = mappingA.generatedLine; + var lineB = mappingB.generatedLine; + var columnA = mappingA.generatedColumn; + var columnB = mappingB.generatedColumn; + return lineB > lineA || lineB == lineA && columnB >= columnA || + util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0; + } + + /** + * A data structure to provide a sorted view of accumulated mappings in a + * performance conscious manner. It trades a neglibable overhead in general + * case for a large speedup in case of mappings being added in order. + */ + function MappingList() { + this._array = []; + this._sorted = true; + // Serves as infimum + this._last = {generatedLine: -1, generatedColumn: 0}; + } + + /** + * Iterate through internal items. This method takes the same arguments that + * `Array.prototype.forEach` takes. + * + * NOTE: The order of the mappings is NOT guaranteed. + */ + MappingList.prototype.unsortedForEach = + function MappingList_forEach(aCallback, aThisArg) { + this._array.forEach(aCallback, aThisArg); + }; + + /** + * Add the given source mapping. + * + * @param Object aMapping + */ + MappingList.prototype.add = function MappingList_add(aMapping) { + if (generatedPositionAfter(this._last, aMapping)) { + this._last = aMapping; + this._array.push(aMapping); + } else { + this._sorted = false; + this._array.push(aMapping); + } + }; + + /** + * Returns the flat, sorted array of mappings. The mappings are sorted by + * generated position. + * + * WARNING: This method returns internal data without copying, for + * performance. The return value must NOT be mutated, and should be treated as + * an immutable borrow. If you want to take ownership, you must make your own + * copy. + */ + MappingList.prototype.toArray = function MappingList_toArray() { + if (!this._sorted) { + this._array.sort(util.compareByGeneratedPositionsInflated); + this._sorted = true; + } + return this._array; + }; + + exports.MappingList = MappingList; + + +/***/ }), +/* 7 */ +/***/ (function(module, exports, __webpack_require__) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + var util = __webpack_require__(4); + var binarySearch = __webpack_require__(8); + var ArraySet = __webpack_require__(5).ArraySet; + var base64VLQ = __webpack_require__(2); + var quickSort = __webpack_require__(9).quickSort; + + function SourceMapConsumer(aSourceMap, aSourceMapURL) { + var sourceMap = aSourceMap; + if (typeof aSourceMap === 'string') { + sourceMap = util.parseSourceMapInput(aSourceMap); + } + + return sourceMap.sections != null + ? new IndexedSourceMapConsumer(sourceMap, aSourceMapURL) + : new BasicSourceMapConsumer(sourceMap, aSourceMapURL); + } + + SourceMapConsumer.fromSourceMap = function(aSourceMap, aSourceMapURL) { + return BasicSourceMapConsumer.fromSourceMap(aSourceMap, aSourceMapURL); + } + + /** + * The version of the source mapping spec that we are consuming. + */ + SourceMapConsumer.prototype._version = 3; + + // `__generatedMappings` and `__originalMappings` are arrays that hold the + // parsed mapping coordinates from the source map's "mappings" attribute. They + // are lazily instantiated, accessed via the `_generatedMappings` and + // `_originalMappings` getters respectively, and we only parse the mappings + // and create these arrays once queried for a source location. We jump through + // these hoops because there can be many thousands of mappings, and parsing + // them is expensive, so we only want to do it if we must. + // + // Each object in the arrays is of the form: + // + // { + // generatedLine: The line number in the generated code, + // generatedColumn: The column number in the generated code, + // source: The path to the original source file that generated this + // chunk of code, + // originalLine: The line number in the original source that + // corresponds to this chunk of generated code, + // originalColumn: The column number in the original source that + // corresponds to this chunk of generated code, + // name: The name of the original symbol which generated this chunk of + // code. + // } + // + // All properties except for `generatedLine` and `generatedColumn` can be + // `null`. + // + // `_generatedMappings` is ordered by the generated positions. + // + // `_originalMappings` is ordered by the original positions. + + SourceMapConsumer.prototype.__generatedMappings = null; + Object.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', { + configurable: true, + enumerable: true, + get: function () { + if (!this.__generatedMappings) { + this._parseMappings(this._mappings, this.sourceRoot); + } + + return this.__generatedMappings; + } + }); + + SourceMapConsumer.prototype.__originalMappings = null; + Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', { + configurable: true, + enumerable: true, + get: function () { + if (!this.__originalMappings) { + this._parseMappings(this._mappings, this.sourceRoot); + } + + return this.__originalMappings; + } + }); + + SourceMapConsumer.prototype._charIsMappingSeparator = + function SourceMapConsumer_charIsMappingSeparator(aStr, index) { + var c = aStr.charAt(index); + return c === ";" || c === ","; + }; + + /** + * Parse the mappings in a string in to a data structure which we can easily + * query (the ordered arrays in the `this.__generatedMappings` and + * `this.__originalMappings` properties). + */ + SourceMapConsumer.prototype._parseMappings = + function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { + throw new Error("Subclasses must implement _parseMappings"); + }; + + SourceMapConsumer.GENERATED_ORDER = 1; + SourceMapConsumer.ORIGINAL_ORDER = 2; + + SourceMapConsumer.GREATEST_LOWER_BOUND = 1; + SourceMapConsumer.LEAST_UPPER_BOUND = 2; + + /** + * Iterate over each mapping between an original source/line/column and a + * generated line/column in this source map. + * + * @param Function aCallback + * The function that is called with each mapping. + * @param Object aContext + * Optional. If specified, this object will be the value of `this` every + * time that `aCallback` is called. + * @param aOrder + * Either `SourceMapConsumer.GENERATED_ORDER` or + * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to + * iterate over the mappings sorted by the generated file's line/column + * order or the original's source/line/column order, respectively. Defaults to + * `SourceMapConsumer.GENERATED_ORDER`. + */ + SourceMapConsumer.prototype.eachMapping = + function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) { + var context = aContext || null; + var order = aOrder || SourceMapConsumer.GENERATED_ORDER; + + var mappings; + switch (order) { + case SourceMapConsumer.GENERATED_ORDER: + mappings = this._generatedMappings; + break; + case SourceMapConsumer.ORIGINAL_ORDER: + mappings = this._originalMappings; + break; + default: + throw new Error("Unknown order of iteration."); + } + + var sourceRoot = this.sourceRoot; + mappings.map(function (mapping) { + var source = mapping.source === null ? null : this._sources.at(mapping.source); + source = util.computeSourceURL(sourceRoot, source, this._sourceMapURL); + return { + source: source, + generatedLine: mapping.generatedLine, + generatedColumn: mapping.generatedColumn, + originalLine: mapping.originalLine, + originalColumn: mapping.originalColumn, + name: mapping.name === null ? null : this._names.at(mapping.name) + }; + }, this).forEach(aCallback, context); + }; + + /** + * Returns all generated line and column information for the original source, + * line, and column provided. If no column is provided, returns all mappings + * corresponding to a either the line we are searching for or the next + * closest line that has any mappings. Otherwise, returns all mappings + * corresponding to the given line and either the column we are searching for + * or the next closest column that has any offsets. + * + * The only argument is an object with the following properties: + * + * - source: The filename of the original source. + * - line: The line number in the original source. The line number is 1-based. + * - column: Optional. the column number in the original source. + * The column number is 0-based. + * + * and an array of objects is returned, each with the following properties: + * + * - line: The line number in the generated source, or null. The + * line number is 1-based. + * - column: The column number in the generated source, or null. + * The column number is 0-based. + */ + SourceMapConsumer.prototype.allGeneratedPositionsFor = + function SourceMapConsumer_allGeneratedPositionsFor(aArgs) { + var line = util.getArg(aArgs, 'line'); + + // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping + // returns the index of the closest mapping less than the needle. By + // setting needle.originalColumn to 0, we thus find the last mapping for + // the given line, provided such a mapping exists. + var needle = { + source: util.getArg(aArgs, 'source'), + originalLine: line, + originalColumn: util.getArg(aArgs, 'column', 0) + }; + + needle.source = this._findSourceIndex(needle.source); + if (needle.source < 0) { + return []; + } + + var mappings = []; + + var index = this._findMapping(needle, + this._originalMappings, + "originalLine", + "originalColumn", + util.compareByOriginalPositions, + binarySearch.LEAST_UPPER_BOUND); + if (index >= 0) { + var mapping = this._originalMappings[index]; + + if (aArgs.column === undefined) { + var originalLine = mapping.originalLine; + + // Iterate until either we run out of mappings, or we run into + // a mapping for a different line than the one we found. Since + // mappings are sorted, this is guaranteed to find all mappings for + // the line we found. + while (mapping && mapping.originalLine === originalLine) { + mappings.push({ + line: util.getArg(mapping, 'generatedLine', null), + column: util.getArg(mapping, 'generatedColumn', null), + lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) + }); + + mapping = this._originalMappings[++index]; + } + } else { + var originalColumn = mapping.originalColumn; + + // Iterate until either we run out of mappings, or we run into + // a mapping for a different line than the one we were searching for. + // Since mappings are sorted, this is guaranteed to find all mappings for + // the line we are searching for. + while (mapping && + mapping.originalLine === line && + mapping.originalColumn == originalColumn) { + mappings.push({ + line: util.getArg(mapping, 'generatedLine', null), + column: util.getArg(mapping, 'generatedColumn', null), + lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) + }); + + mapping = this._originalMappings[++index]; + } + } + } + + return mappings; + }; + + exports.SourceMapConsumer = SourceMapConsumer; + + /** + * A BasicSourceMapConsumer instance represents a parsed source map which we can + * query for information about the original file positions by giving it a file + * position in the generated source. + * + * The first parameter is the raw source map (either as a JSON string, or + * already parsed to an object). According to the spec, source maps have the + * following attributes: + * + * - version: Which version of the source map spec this map is following. + * - sources: An array of URLs to the original source files. + * - names: An array of identifiers which can be referrenced by individual mappings. + * - sourceRoot: Optional. The URL root from which all sources are relative. + * - sourcesContent: Optional. An array of contents of the original source files. + * - mappings: A string of base64 VLQs which contain the actual mappings. + * - file: Optional. The generated file this source map is associated with. + * + * Here is an example source map, taken from the source map spec[0]: + * + * { + * version : 3, + * file: "out.js", + * sourceRoot : "", + * sources: ["foo.js", "bar.js"], + * names: ["src", "maps", "are", "fun"], + * mappings: "AA,AB;;ABCDE;" + * } + * + * The second parameter, if given, is a string whose value is the URL + * at which the source map was found. This URL is used to compute the + * sources array. + * + * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1# + */ + function BasicSourceMapConsumer(aSourceMap, aSourceMapURL) { + var sourceMap = aSourceMap; + if (typeof aSourceMap === 'string') { + sourceMap = util.parseSourceMapInput(aSourceMap); + } + + var version = util.getArg(sourceMap, 'version'); + var sources = util.getArg(sourceMap, 'sources'); + // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which + // requires the array) to play nice here. + var names = util.getArg(sourceMap, 'names', []); + var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null); + var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null); + var mappings = util.getArg(sourceMap, 'mappings'); + var file = util.getArg(sourceMap, 'file', null); + + // Once again, Sass deviates from the spec and supplies the version as a + // string rather than a number, so we use loose equality checking here. + if (version != this._version) { + throw new Error('Unsupported version: ' + version); + } + + if (sourceRoot) { + sourceRoot = util.normalize(sourceRoot); + } + + sources = sources + .map(String) + // Some source maps produce relative source paths like "./foo.js" instead of + // "foo.js". Normalize these first so that future comparisons will succeed. + // See bugzil.la/1090768. + .map(util.normalize) + // Always ensure that absolute sources are internally stored relative to + // the source root, if the source root is absolute. Not doing this would + // be particularly problematic when the source root is a prefix of the + // source (valid, but why??). See github issue #199 and bugzil.la/1188982. + .map(function (source) { + return sourceRoot && util.isAbsolute(sourceRoot) && util.isAbsolute(source) + ? util.relative(sourceRoot, source) + : source; + }); + + // Pass `true` below to allow duplicate names and sources. While source maps + // are intended to be compressed and deduplicated, the TypeScript compiler + // sometimes generates source maps with duplicates in them. See Github issue + // #72 and bugzil.la/889492. + this._names = ArraySet.fromArray(names.map(String), true); + this._sources = ArraySet.fromArray(sources, true); + + this._absoluteSources = this._sources.toArray().map(function (s) { + return util.computeSourceURL(sourceRoot, s, aSourceMapURL); + }); + + this.sourceRoot = sourceRoot; + this.sourcesContent = sourcesContent; + this._mappings = mappings; + this._sourceMapURL = aSourceMapURL; + this.file = file; + } + + BasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype); + BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer; + + /** + * Utility function to find the index of a source. Returns -1 if not + * found. + */ + BasicSourceMapConsumer.prototype._findSourceIndex = function(aSource) { + var relativeSource = aSource; + if (this.sourceRoot != null) { + relativeSource = util.relative(this.sourceRoot, relativeSource); + } + + if (this._sources.has(relativeSource)) { + return this._sources.indexOf(relativeSource); + } + + // Maybe aSource is an absolute URL as returned by |sources|. In + // this case we can't simply undo the transform. + var i; + for (i = 0; i < this._absoluteSources.length; ++i) { + if (this._absoluteSources[i] == aSource) { + return i; + } + } + + return -1; + }; + + /** + * Create a BasicSourceMapConsumer from a SourceMapGenerator. + * + * @param SourceMapGenerator aSourceMap + * The source map that will be consumed. + * @param String aSourceMapURL + * The URL at which the source map can be found (optional) + * @returns BasicSourceMapConsumer + */ + BasicSourceMapConsumer.fromSourceMap = + function SourceMapConsumer_fromSourceMap(aSourceMap, aSourceMapURL) { + var smc = Object.create(BasicSourceMapConsumer.prototype); + + var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true); + var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true); + smc.sourceRoot = aSourceMap._sourceRoot; + smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(), + smc.sourceRoot); + smc.file = aSourceMap._file; + smc._sourceMapURL = aSourceMapURL; + smc._absoluteSources = smc._sources.toArray().map(function (s) { + return util.computeSourceURL(smc.sourceRoot, s, aSourceMapURL); + }); + + // Because we are modifying the entries (by converting string sources and + // names to indices into the sources and names ArraySets), we have to make + // a copy of the entry or else bad things happen. Shared mutable state + // strikes again! See github issue #191. + + var generatedMappings = aSourceMap._mappings.toArray().slice(); + var destGeneratedMappings = smc.__generatedMappings = []; + var destOriginalMappings = smc.__originalMappings = []; + + for (var i = 0, length = generatedMappings.length; i < length; i++) { + var srcMapping = generatedMappings[i]; + var destMapping = new Mapping; + destMapping.generatedLine = srcMapping.generatedLine; + destMapping.generatedColumn = srcMapping.generatedColumn; + + if (srcMapping.source) { + destMapping.source = sources.indexOf(srcMapping.source); + destMapping.originalLine = srcMapping.originalLine; + destMapping.originalColumn = srcMapping.originalColumn; + + if (srcMapping.name) { + destMapping.name = names.indexOf(srcMapping.name); + } + + destOriginalMappings.push(destMapping); + } + + destGeneratedMappings.push(destMapping); + } + + quickSort(smc.__originalMappings, util.compareByOriginalPositions); + + return smc; + }; + + /** + * The version of the source mapping spec that we are consuming. + */ + BasicSourceMapConsumer.prototype._version = 3; + + /** + * The list of original sources. + */ + Object.defineProperty(BasicSourceMapConsumer.prototype, 'sources', { + get: function () { + return this._absoluteSources.slice(); + } + }); + + /** + * Provide the JIT with a nice shape / hidden class. + */ + function Mapping() { + this.generatedLine = 0; + this.generatedColumn = 0; + this.source = null; + this.originalLine = null; + this.originalColumn = null; + this.name = null; + } + + /** + * Parse the mappings in a string in to a data structure which we can easily + * query (the ordered arrays in the `this.__generatedMappings` and + * `this.__originalMappings` properties). + */ + BasicSourceMapConsumer.prototype._parseMappings = + function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { + var generatedLine = 1; + var previousGeneratedColumn = 0; + var previousOriginalLine = 0; + var previousOriginalColumn = 0; + var previousSource = 0; + var previousName = 0; + var length = aStr.length; + var index = 0; + var cachedSegments = {}; + var temp = {}; + var originalMappings = []; + var generatedMappings = []; + var mapping, str, segment, end, value; + + while (index < length) { + if (aStr.charAt(index) === ';') { + generatedLine++; + index++; + previousGeneratedColumn = 0; + } + else if (aStr.charAt(index) === ',') { + index++; + } + else { + mapping = new Mapping(); + mapping.generatedLine = generatedLine; + + // Because each offset is encoded relative to the previous one, + // many segments often have the same encoding. We can exploit this + // fact by caching the parsed variable length fields of each segment, + // allowing us to avoid a second parse if we encounter the same + // segment again. + for (end = index; end < length; end++) { + if (this._charIsMappingSeparator(aStr, end)) { + break; + } + } + str = aStr.slice(index, end); + + segment = cachedSegments[str]; + if (segment) { + index += str.length; + } else { + segment = []; + while (index < end) { + base64VLQ.decode(aStr, index, temp); + value = temp.value; + index = temp.rest; + segment.push(value); + } + + if (segment.length === 2) { + throw new Error('Found a source, but no line and column'); + } + + if (segment.length === 3) { + throw new Error('Found a source and line, but no column'); + } + + cachedSegments[str] = segment; + } + + // Generated column. + mapping.generatedColumn = previousGeneratedColumn + segment[0]; + previousGeneratedColumn = mapping.generatedColumn; + + if (segment.length > 1) { + // Original source. + mapping.source = previousSource + segment[1]; + previousSource += segment[1]; + + // Original line. + mapping.originalLine = previousOriginalLine + segment[2]; + previousOriginalLine = mapping.originalLine; + // Lines are stored 0-based + mapping.originalLine += 1; + + // Original column. + mapping.originalColumn = previousOriginalColumn + segment[3]; + previousOriginalColumn = mapping.originalColumn; + + if (segment.length > 4) { + // Original name. + mapping.name = previousName + segment[4]; + previousName += segment[4]; + } + } + + generatedMappings.push(mapping); + if (typeof mapping.originalLine === 'number') { + originalMappings.push(mapping); + } + } + } + + quickSort(generatedMappings, util.compareByGeneratedPositionsDeflated); + this.__generatedMappings = generatedMappings; + + quickSort(originalMappings, util.compareByOriginalPositions); + this.__originalMappings = originalMappings; + }; + + /** + * Find the mapping that best matches the hypothetical "needle" mapping that + * we are searching for in the given "haystack" of mappings. + */ + BasicSourceMapConsumer.prototype._findMapping = + function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName, + aColumnName, aComparator, aBias) { + // To return the position we are searching for, we must first find the + // mapping for the given position and then return the opposite position it + // points to. Because the mappings are sorted, we can use binary search to + // find the best mapping. + + if (aNeedle[aLineName] <= 0) { + throw new TypeError('Line must be greater than or equal to 1, got ' + + aNeedle[aLineName]); + } + if (aNeedle[aColumnName] < 0) { + throw new TypeError('Column must be greater than or equal to 0, got ' + + aNeedle[aColumnName]); + } + + return binarySearch.search(aNeedle, aMappings, aComparator, aBias); + }; + + /** + * Compute the last column for each generated mapping. The last column is + * inclusive. + */ + BasicSourceMapConsumer.prototype.computeColumnSpans = + function SourceMapConsumer_computeColumnSpans() { + for (var index = 0; index < this._generatedMappings.length; ++index) { + var mapping = this._generatedMappings[index]; + + // Mappings do not contain a field for the last generated columnt. We + // can come up with an optimistic estimate, however, by assuming that + // mappings are contiguous (i.e. given two consecutive mappings, the + // first mapping ends where the second one starts). + if (index + 1 < this._generatedMappings.length) { + var nextMapping = this._generatedMappings[index + 1]; + + if (mapping.generatedLine === nextMapping.generatedLine) { + mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1; + continue; + } + } + + // The last mapping for each line spans the entire line. + mapping.lastGeneratedColumn = Infinity; + } + }; + + /** + * Returns the original source, line, and column information for the generated + * source's line and column positions provided. The only argument is an object + * with the following properties: + * + * - line: The line number in the generated source. The line number + * is 1-based. + * - column: The column number in the generated source. The column + * number is 0-based. + * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or + * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. + * + * and an object is returned with the following properties: + * + * - source: The original source file, or null. + * - line: The line number in the original source, or null. The + * line number is 1-based. + * - column: The column number in the original source, or null. The + * column number is 0-based. + * - name: The original identifier, or null. + */ + BasicSourceMapConsumer.prototype.originalPositionFor = + function SourceMapConsumer_originalPositionFor(aArgs) { + var needle = { + generatedLine: util.getArg(aArgs, 'line'), + generatedColumn: util.getArg(aArgs, 'column') + }; + + var index = this._findMapping( + needle, + this._generatedMappings, + "generatedLine", + "generatedColumn", + util.compareByGeneratedPositionsDeflated, + util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND) + ); + + if (index >= 0) { + var mapping = this._generatedMappings[index]; + + if (mapping.generatedLine === needle.generatedLine) { + var source = util.getArg(mapping, 'source', null); + if (source !== null) { + source = this._sources.at(source); + source = util.computeSourceURL(this.sourceRoot, source, this._sourceMapURL); + } + var name = util.getArg(mapping, 'name', null); + if (name !== null) { + name = this._names.at(name); + } + return { + source: source, + line: util.getArg(mapping, 'originalLine', null), + column: util.getArg(mapping, 'originalColumn', null), + name: name + }; + } + } + + return { + source: null, + line: null, + column: null, + name: null + }; + }; + + /** + * Return true if we have the source content for every source in the source + * map, false otherwise. + */ + BasicSourceMapConsumer.prototype.hasContentsOfAllSources = + function BasicSourceMapConsumer_hasContentsOfAllSources() { + if (!this.sourcesContent) { + return false; + } + return this.sourcesContent.length >= this._sources.size() && + !this.sourcesContent.some(function (sc) { return sc == null; }); + }; + + /** + * Returns the original source content. The only argument is the url of the + * original source file. Returns null if no original source content is + * available. + */ + BasicSourceMapConsumer.prototype.sourceContentFor = + function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { + if (!this.sourcesContent) { + return null; + } + + var index = this._findSourceIndex(aSource); + if (index >= 0) { + return this.sourcesContent[index]; + } + + var relativeSource = aSource; + if (this.sourceRoot != null) { + relativeSource = util.relative(this.sourceRoot, relativeSource); + } + + var url; + if (this.sourceRoot != null + && (url = util.urlParse(this.sourceRoot))) { + // XXX: file:// URIs and absolute paths lead to unexpected behavior for + // many users. We can help them out when they expect file:// URIs to + // behave like it would if they were running a local HTTP server. See + // https://bugzilla.mozilla.org/show_bug.cgi?id=885597. + var fileUriAbsPath = relativeSource.replace(/^file:\/\//, ""); + if (url.scheme == "file" + && this._sources.has(fileUriAbsPath)) { + return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)] + } + + if ((!url.path || url.path == "/") + && this._sources.has("/" + relativeSource)) { + return this.sourcesContent[this._sources.indexOf("/" + relativeSource)]; + } + } + + // This function is used recursively from + // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we + // don't want to throw if we can't find the source - we just want to + // return null, so we provide a flag to exit gracefully. + if (nullOnMissing) { + return null; + } + else { + throw new Error('"' + relativeSource + '" is not in the SourceMap.'); + } + }; + + /** + * Returns the generated line and column information for the original source, + * line, and column positions provided. The only argument is an object with + * the following properties: + * + * - source: The filename of the original source. + * - line: The line number in the original source. The line number + * is 1-based. + * - column: The column number in the original source. The column + * number is 0-based. + * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or + * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. + * + * and an object is returned with the following properties: + * + * - line: The line number in the generated source, or null. The + * line number is 1-based. + * - column: The column number in the generated source, or null. + * The column number is 0-based. + */ + BasicSourceMapConsumer.prototype.generatedPositionFor = + function SourceMapConsumer_generatedPositionFor(aArgs) { + var source = util.getArg(aArgs, 'source'); + source = this._findSourceIndex(source); + if (source < 0) { + return { + line: null, + column: null, + lastColumn: null + }; + } + + var needle = { + source: source, + originalLine: util.getArg(aArgs, 'line'), + originalColumn: util.getArg(aArgs, 'column') + }; + + var index = this._findMapping( + needle, + this._originalMappings, + "originalLine", + "originalColumn", + util.compareByOriginalPositions, + util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND) + ); + + if (index >= 0) { + var mapping = this._originalMappings[index]; + + if (mapping.source === needle.source) { + return { + line: util.getArg(mapping, 'generatedLine', null), + column: util.getArg(mapping, 'generatedColumn', null), + lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) + }; + } + } + + return { + line: null, + column: null, + lastColumn: null + }; + }; + + exports.BasicSourceMapConsumer = BasicSourceMapConsumer; + + /** + * An IndexedSourceMapConsumer instance represents a parsed source map which + * we can query for information. It differs from BasicSourceMapConsumer in + * that it takes "indexed" source maps (i.e. ones with a "sections" field) as + * input. + * + * The first parameter is a raw source map (either as a JSON string, or already + * parsed to an object). According to the spec for indexed source maps, they + * have the following attributes: + * + * - version: Which version of the source map spec this map is following. + * - file: Optional. The generated file this source map is associated with. + * - sections: A list of section definitions. + * + * Each value under the "sections" field has two fields: + * - offset: The offset into the original specified at which this section + * begins to apply, defined as an object with a "line" and "column" + * field. + * - map: A source map definition. This source map could also be indexed, + * but doesn't have to be. + * + * Instead of the "map" field, it's also possible to have a "url" field + * specifying a URL to retrieve a source map from, but that's currently + * unsupported. + * + * Here's an example source map, taken from the source map spec[0], but + * modified to omit a section which uses the "url" field. + * + * { + * version : 3, + * file: "app.js", + * sections: [{ + * offset: {line:100, column:10}, + * map: { + * version : 3, + * file: "section.js", + * sources: ["foo.js", "bar.js"], + * names: ["src", "maps", "are", "fun"], + * mappings: "AAAA,E;;ABCDE;" + * } + * }], + * } + * + * The second parameter, if given, is a string whose value is the URL + * at which the source map was found. This URL is used to compute the + * sources array. + * + * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt + */ + function IndexedSourceMapConsumer(aSourceMap, aSourceMapURL) { + var sourceMap = aSourceMap; + if (typeof aSourceMap === 'string') { + sourceMap = util.parseSourceMapInput(aSourceMap); + } + + var version = util.getArg(sourceMap, 'version'); + var sections = util.getArg(sourceMap, 'sections'); + + if (version != this._version) { + throw new Error('Unsupported version: ' + version); + } + + this._sources = new ArraySet(); + this._names = new ArraySet(); + + var lastOffset = { + line: -1, + column: 0 + }; + this._sections = sections.map(function (s) { + if (s.url) { + // The url field will require support for asynchronicity. + // See https://github.com/mozilla/source-map/issues/16 + throw new Error('Support for url field in sections not implemented.'); + } + var offset = util.getArg(s, 'offset'); + var offsetLine = util.getArg(offset, 'line'); + var offsetColumn = util.getArg(offset, 'column'); + + if (offsetLine < lastOffset.line || + (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) { + throw new Error('Section offsets must be ordered and non-overlapping.'); + } + lastOffset = offset; + + return { + generatedOffset: { + // The offset fields are 0-based, but we use 1-based indices when + // encoding/decoding from VLQ. + generatedLine: offsetLine + 1, + generatedColumn: offsetColumn + 1 + }, + consumer: new SourceMapConsumer(util.getArg(s, 'map'), aSourceMapURL) + } + }); + } + + IndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype); + IndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer; + + /** + * The version of the source mapping spec that we are consuming. + */ + IndexedSourceMapConsumer.prototype._version = 3; + + /** + * The list of original sources. + */ + Object.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', { + get: function () { + var sources = []; + for (var i = 0; i < this._sections.length; i++) { + for (var j = 0; j < this._sections[i].consumer.sources.length; j++) { + sources.push(this._sections[i].consumer.sources[j]); + } + } + return sources; + } + }); + + /** + * Returns the original source, line, and column information for the generated + * source's line and column positions provided. The only argument is an object + * with the following properties: + * + * - line: The line number in the generated source. The line number + * is 1-based. + * - column: The column number in the generated source. The column + * number is 0-based. + * + * and an object is returned with the following properties: + * + * - source: The original source file, or null. + * - line: The line number in the original source, or null. The + * line number is 1-based. + * - column: The column number in the original source, or null. The + * column number is 0-based. + * - name: The original identifier, or null. + */ + IndexedSourceMapConsumer.prototype.originalPositionFor = + function IndexedSourceMapConsumer_originalPositionFor(aArgs) { + var needle = { + generatedLine: util.getArg(aArgs, 'line'), + generatedColumn: util.getArg(aArgs, 'column') + }; + + // Find the section containing the generated position we're trying to map + // to an original position. + var sectionIndex = binarySearch.search(needle, this._sections, + function(needle, section) { + var cmp = needle.generatedLine - section.generatedOffset.generatedLine; + if (cmp) { + return cmp; + } + + return (needle.generatedColumn - + section.generatedOffset.generatedColumn); + }); + var section = this._sections[sectionIndex]; + + if (!section) { + return { + source: null, + line: null, + column: null, + name: null + }; + } + + return section.consumer.originalPositionFor({ + line: needle.generatedLine - + (section.generatedOffset.generatedLine - 1), + column: needle.generatedColumn - + (section.generatedOffset.generatedLine === needle.generatedLine + ? section.generatedOffset.generatedColumn - 1 + : 0), + bias: aArgs.bias + }); + }; + + /** + * Return true if we have the source content for every source in the source + * map, false otherwise. + */ + IndexedSourceMapConsumer.prototype.hasContentsOfAllSources = + function IndexedSourceMapConsumer_hasContentsOfAllSources() { + return this._sections.every(function (s) { + return s.consumer.hasContentsOfAllSources(); + }); + }; + + /** + * Returns the original source content. The only argument is the url of the + * original source file. Returns null if no original source content is + * available. + */ + IndexedSourceMapConsumer.prototype.sourceContentFor = + function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { + for (var i = 0; i < this._sections.length; i++) { + var section = this._sections[i]; + + var content = section.consumer.sourceContentFor(aSource, true); + if (content) { + return content; + } + } + if (nullOnMissing) { + return null; + } + else { + throw new Error('"' + aSource + '" is not in the SourceMap.'); + } + }; + + /** + * Returns the generated line and column information for the original source, + * line, and column positions provided. The only argument is an object with + * the following properties: + * + * - source: The filename of the original source. + * - line: The line number in the original source. The line number + * is 1-based. + * - column: The column number in the original source. The column + * number is 0-based. + * + * and an object is returned with the following properties: + * + * - line: The line number in the generated source, or null. The + * line number is 1-based. + * - column: The column number in the generated source, or null. + * The column number is 0-based. + */ + IndexedSourceMapConsumer.prototype.generatedPositionFor = + function IndexedSourceMapConsumer_generatedPositionFor(aArgs) { + for (var i = 0; i < this._sections.length; i++) { + var section = this._sections[i]; + + // Only consider this section if the requested source is in the list of + // sources of the consumer. + if (section.consumer._findSourceIndex(util.getArg(aArgs, 'source')) === -1) { + continue; + } + var generatedPosition = section.consumer.generatedPositionFor(aArgs); + if (generatedPosition) { + var ret = { + line: generatedPosition.line + + (section.generatedOffset.generatedLine - 1), + column: generatedPosition.column + + (section.generatedOffset.generatedLine === generatedPosition.line + ? section.generatedOffset.generatedColumn - 1 + : 0) + }; + return ret; + } + } + + return { + line: null, + column: null + }; + }; + + /** + * Parse the mappings in a string in to a data structure which we can easily + * query (the ordered arrays in the `this.__generatedMappings` and + * `this.__originalMappings` properties). + */ + IndexedSourceMapConsumer.prototype._parseMappings = + function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) { + this.__generatedMappings = []; + this.__originalMappings = []; + for (var i = 0; i < this._sections.length; i++) { + var section = this._sections[i]; + var sectionMappings = section.consumer._generatedMappings; + for (var j = 0; j < sectionMappings.length; j++) { + var mapping = sectionMappings[j]; + + var source = section.consumer._sources.at(mapping.source); + source = util.computeSourceURL(section.consumer.sourceRoot, source, this._sourceMapURL); + this._sources.add(source); + source = this._sources.indexOf(source); + + var name = null; + if (mapping.name) { + name = section.consumer._names.at(mapping.name); + this._names.add(name); + name = this._names.indexOf(name); + } + + // The mappings coming from the consumer for the section have + // generated positions relative to the start of the section, so we + // need to offset them to be relative to the start of the concatenated + // generated file. + var adjustedMapping = { + source: source, + generatedLine: mapping.generatedLine + + (section.generatedOffset.generatedLine - 1), + generatedColumn: mapping.generatedColumn + + (section.generatedOffset.generatedLine === mapping.generatedLine + ? section.generatedOffset.generatedColumn - 1 + : 0), + originalLine: mapping.originalLine, + originalColumn: mapping.originalColumn, + name: name + }; + + this.__generatedMappings.push(adjustedMapping); + if (typeof adjustedMapping.originalLine === 'number') { + this.__originalMappings.push(adjustedMapping); + } + } + } + + quickSort(this.__generatedMappings, util.compareByGeneratedPositionsDeflated); + quickSort(this.__originalMappings, util.compareByOriginalPositions); + }; + + exports.IndexedSourceMapConsumer = IndexedSourceMapConsumer; + + +/***/ }), +/* 8 */ +/***/ (function(module, exports) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + exports.GREATEST_LOWER_BOUND = 1; + exports.LEAST_UPPER_BOUND = 2; + + /** + * Recursive implementation of binary search. + * + * @param aLow Indices here and lower do not contain the needle. + * @param aHigh Indices here and higher do not contain the needle. + * @param aNeedle The element being searched for. + * @param aHaystack The non-empty array being searched. + * @param aCompare Function which takes two elements and returns -1, 0, or 1. + * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or + * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + */ + function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) { + // This function terminates when one of the following is true: + // + // 1. We find the exact element we are looking for. + // + // 2. We did not find the exact element, but we can return the index of + // the next-closest element. + // + // 3. We did not find the exact element, and there is no next-closest + // element than the one we are searching for, so we return -1. + var mid = Math.floor((aHigh - aLow) / 2) + aLow; + var cmp = aCompare(aNeedle, aHaystack[mid], true); + if (cmp === 0) { + // Found the element we are looking for. + return mid; + } + else if (cmp > 0) { + // Our needle is greater than aHaystack[mid]. + if (aHigh - mid > 1) { + // The element is in the upper half. + return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias); + } + + // The exact needle element was not found in this haystack. Determine if + // we are in termination case (3) or (2) and return the appropriate thing. + if (aBias == exports.LEAST_UPPER_BOUND) { + return aHigh < aHaystack.length ? aHigh : -1; + } else { + return mid; + } + } + else { + // Our needle is less than aHaystack[mid]. + if (mid - aLow > 1) { + // The element is in the lower half. + return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias); + } + + // we are in termination case (3) or (2) and return the appropriate thing. + if (aBias == exports.LEAST_UPPER_BOUND) { + return mid; + } else { + return aLow < 0 ? -1 : aLow; + } + } + } + + /** + * This is an implementation of binary search which will always try and return + * the index of the closest element if there is no exact hit. This is because + * mappings between original and generated line/col pairs are single points, + * and there is an implicit region between each of them, so a miss just means + * that you aren't on the very start of a region. + * + * @param aNeedle The element you are looking for. + * @param aHaystack The array that is being searched. + * @param aCompare A function which takes the needle and an element in the + * array and returns -1, 0, or 1 depending on whether the needle is less + * than, equal to, or greater than the element, respectively. + * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or + * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'. + */ + exports.search = function search(aNeedle, aHaystack, aCompare, aBias) { + if (aHaystack.length === 0) { + return -1; + } + + var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack, + aCompare, aBias || exports.GREATEST_LOWER_BOUND); + if (index < 0) { + return -1; + } + + // We have found either the exact element, or the next-closest element than + // the one we are searching for. However, there may be more than one such + // element. Make sure we always return the smallest of these. + while (index - 1 >= 0) { + if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) { + break; + } + --index; + } + + return index; + }; + + +/***/ }), +/* 9 */ +/***/ (function(module, exports) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + // It turns out that some (most?) JavaScript engines don't self-host + // `Array.prototype.sort`. This makes sense because C++ will likely remain + // faster than JS when doing raw CPU-intensive sorting. However, when using a + // custom comparator function, calling back and forth between the VM's C++ and + // JIT'd JS is rather slow *and* loses JIT type information, resulting in + // worse generated code for the comparator function than would be optimal. In + // fact, when sorting with a comparator, these costs outweigh the benefits of + // sorting in C++. By using our own JS-implemented Quick Sort (below), we get + // a ~3500ms mean speed-up in `bench/bench.html`. + + /** + * Swap the elements indexed by `x` and `y` in the array `ary`. + * + * @param {Array} ary + * The array. + * @param {Number} x + * The index of the first item. + * @param {Number} y + * The index of the second item. + */ + function swap(ary, x, y) { + var temp = ary[x]; + ary[x] = ary[y]; + ary[y] = temp; + } + + /** + * Returns a random integer within the range `low .. high` inclusive. + * + * @param {Number} low + * The lower bound on the range. + * @param {Number} high + * The upper bound on the range. + */ + function randomIntInRange(low, high) { + return Math.round(low + (Math.random() * (high - low))); + } + + /** + * The Quick Sort algorithm. + * + * @param {Array} ary + * An array to sort. + * @param {function} comparator + * Function to use to compare two items. + * @param {Number} p + * Start index of the array + * @param {Number} r + * End index of the array + */ + function doQuickSort(ary, comparator, p, r) { + // If our lower bound is less than our upper bound, we (1) partition the + // array into two pieces and (2) recurse on each half. If it is not, this is + // the empty array and our base case. + + if (p < r) { + // (1) Partitioning. + // + // The partitioning chooses a pivot between `p` and `r` and moves all + // elements that are less than or equal to the pivot to the before it, and + // all the elements that are greater than it after it. The effect is that + // once partition is done, the pivot is in the exact place it will be when + // the array is put in sorted order, and it will not need to be moved + // again. This runs in O(n) time. + + // Always choose a random pivot so that an input array which is reverse + // sorted does not cause O(n^2) running time. + var pivotIndex = randomIntInRange(p, r); + var i = p - 1; + + swap(ary, pivotIndex, r); + var pivot = ary[r]; + + // Immediately after `j` is incremented in this loop, the following hold + // true: + // + // * Every element in `ary[p .. i]` is less than or equal to the pivot. + // + // * Every element in `ary[i+1 .. j-1]` is greater than the pivot. + for (var j = p; j < r; j++) { + if (comparator(ary[j], pivot) <= 0) { + i += 1; + swap(ary, i, j); + } + } + + swap(ary, i + 1, j); + var q = i + 1; + + // (2) Recurse on each half. + + doQuickSort(ary, comparator, p, q - 1); + doQuickSort(ary, comparator, q + 1, r); + } + } + + /** + * Sort the given array in-place with the given comparator function. + * + * @param {Array} ary + * An array to sort. + * @param {function} comparator + * Function to use to compare two items. + */ + exports.quickSort = function (ary, comparator) { + doQuickSort(ary, comparator, 0, ary.length - 1); + }; + + +/***/ }), +/* 10 */ +/***/ (function(module, exports, __webpack_require__) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + var SourceMapGenerator = __webpack_require__(1).SourceMapGenerator; + var util = __webpack_require__(4); + + // Matches a Windows-style `\r\n` newline or a `\n` newline used by all other + // operating systems these days (capturing the result). + var REGEX_NEWLINE = /(\r?\n)/; + + // Newline character code for charCodeAt() comparisons + var NEWLINE_CODE = 10; + + // Private symbol for identifying `SourceNode`s when multiple versions of + // the source-map library are loaded. This MUST NOT CHANGE across + // versions! + var isSourceNode = "$$$isSourceNode$$$"; + + /** + * SourceNodes provide a way to abstract over interpolating/concatenating + * snippets of generated JavaScript source code while maintaining the line and + * column information associated with the original source code. + * + * @param aLine The original line number. + * @param aColumn The original column number. + * @param aSource The original source's filename. + * @param aChunks Optional. An array of strings which are snippets of + * generated JS, or other SourceNodes. + * @param aName The original identifier. + */ + function SourceNode(aLine, aColumn, aSource, aChunks, aName) { + this.children = []; + this.sourceContents = {}; + this.line = aLine == null ? null : aLine; + this.column = aColumn == null ? null : aColumn; + this.source = aSource == null ? null : aSource; + this.name = aName == null ? null : aName; + this[isSourceNode] = true; + if (aChunks != null) this.add(aChunks); + } + + /** + * Creates a SourceNode from generated code and a SourceMapConsumer. + * + * @param aGeneratedCode The generated code + * @param aSourceMapConsumer The SourceMap for the generated code + * @param aRelativePath Optional. The path that relative sources in the + * SourceMapConsumer should be relative to. + */ + SourceNode.fromStringWithSourceMap = + function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) { + // The SourceNode we want to fill with the generated code + // and the SourceMap + var node = new SourceNode(); + + // All even indices of this array are one line of the generated code, + // while all odd indices are the newlines between two adjacent lines + // (since `REGEX_NEWLINE` captures its match). + // Processed fragments are accessed by calling `shiftNextLine`. + var remainingLines = aGeneratedCode.split(REGEX_NEWLINE); + var remainingLinesIndex = 0; + var shiftNextLine = function() { + var lineContents = getNextLine(); + // The last line of a file might not have a newline. + var newLine = getNextLine() || ""; + return lineContents + newLine; + + function getNextLine() { + return remainingLinesIndex < remainingLines.length ? + remainingLines[remainingLinesIndex++] : undefined; + } + }; + + // We need to remember the position of "remainingLines" + var lastGeneratedLine = 1, lastGeneratedColumn = 0; + + // The generate SourceNodes we need a code range. + // To extract it current and last mapping is used. + // Here we store the last mapping. + var lastMapping = null; + + aSourceMapConsumer.eachMapping(function (mapping) { + if (lastMapping !== null) { + // We add the code from "lastMapping" to "mapping": + // First check if there is a new line in between. + if (lastGeneratedLine < mapping.generatedLine) { + // Associate first line with "lastMapping" + addMappingWithCode(lastMapping, shiftNextLine()); + lastGeneratedLine++; + lastGeneratedColumn = 0; + // The remaining code is added without mapping + } else { + // There is no new line in between. + // Associate the code between "lastGeneratedColumn" and + // "mapping.generatedColumn" with "lastMapping" + var nextLine = remainingLines[remainingLinesIndex] || ''; + var code = nextLine.substr(0, mapping.generatedColumn - + lastGeneratedColumn); + remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn - + lastGeneratedColumn); + lastGeneratedColumn = mapping.generatedColumn; + addMappingWithCode(lastMapping, code); + // No more remaining code, continue + lastMapping = mapping; + return; + } + } + // We add the generated code until the first mapping + // to the SourceNode without any mapping. + // Each line is added as separate string. + while (lastGeneratedLine < mapping.generatedLine) { + node.add(shiftNextLine()); + lastGeneratedLine++; + } + if (lastGeneratedColumn < mapping.generatedColumn) { + var nextLine = remainingLines[remainingLinesIndex] || ''; + node.add(nextLine.substr(0, mapping.generatedColumn)); + remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn); + lastGeneratedColumn = mapping.generatedColumn; + } + lastMapping = mapping; + }, this); + // We have processed all mappings. + if (remainingLinesIndex < remainingLines.length) { + if (lastMapping) { + // Associate the remaining code in the current line with "lastMapping" + addMappingWithCode(lastMapping, shiftNextLine()); + } + // and add the remaining lines without any mapping + node.add(remainingLines.splice(remainingLinesIndex).join("")); + } + + // Copy sourcesContent into SourceNode + aSourceMapConsumer.sources.forEach(function (sourceFile) { + var content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content != null) { + if (aRelativePath != null) { + sourceFile = util.join(aRelativePath, sourceFile); + } + node.setSourceContent(sourceFile, content); + } + }); + + return node; + + function addMappingWithCode(mapping, code) { + if (mapping === null || mapping.source === undefined) { + node.add(code); + } else { + var source = aRelativePath + ? util.join(aRelativePath, mapping.source) + : mapping.source; + node.add(new SourceNode(mapping.originalLine, + mapping.originalColumn, + source, + code, + mapping.name)); + } + } + }; + + /** + * Add a chunk of generated JS to this source node. + * + * @param aChunk A string snippet of generated JS code, another instance of + * SourceNode, or an array where each member is one of those things. + */ + SourceNode.prototype.add = function SourceNode_add(aChunk) { + if (Array.isArray(aChunk)) { + aChunk.forEach(function (chunk) { + this.add(chunk); + }, this); + } + else if (aChunk[isSourceNode] || typeof aChunk === "string") { + if (aChunk) { + this.children.push(aChunk); + } + } + else { + throw new TypeError( + "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk + ); + } + return this; + }; + + /** + * Add a chunk of generated JS to the beginning of this source node. + * + * @param aChunk A string snippet of generated JS code, another instance of + * SourceNode, or an array where each member is one of those things. + */ + SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) { + if (Array.isArray(aChunk)) { + for (var i = aChunk.length-1; i >= 0; i--) { + this.prepend(aChunk[i]); + } + } + else if (aChunk[isSourceNode] || typeof aChunk === "string") { + this.children.unshift(aChunk); + } + else { + throw new TypeError( + "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk + ); + } + return this; + }; + + /** + * Walk over the tree of JS snippets in this node and its children. The + * walking function is called once for each snippet of JS and is passed that + * snippet and the its original associated source's line/column location. + * + * @param aFn The traversal function. + */ + SourceNode.prototype.walk = function SourceNode_walk(aFn) { + var chunk; + for (var i = 0, len = this.children.length; i < len; i++) { + chunk = this.children[i]; + if (chunk[isSourceNode]) { + chunk.walk(aFn); + } + else { + if (chunk !== '') { + aFn(chunk, { source: this.source, + line: this.line, + column: this.column, + name: this.name }); + } + } + } + }; + + /** + * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between + * each of `this.children`. + * + * @param aSep The separator. + */ + SourceNode.prototype.join = function SourceNode_join(aSep) { + var newChildren; + var i; + var len = this.children.length; + if (len > 0) { + newChildren = []; + for (i = 0; i < len-1; i++) { + newChildren.push(this.children[i]); + newChildren.push(aSep); + } + newChildren.push(this.children[i]); + this.children = newChildren; + } + return this; + }; + + /** + * Call String.prototype.replace on the very right-most source snippet. Useful + * for trimming whitespace from the end of a source node, etc. + * + * @param aPattern The pattern to replace. + * @param aReplacement The thing to replace the pattern with. + */ + SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) { + var lastChild = this.children[this.children.length - 1]; + if (lastChild[isSourceNode]) { + lastChild.replaceRight(aPattern, aReplacement); + } + else if (typeof lastChild === 'string') { + this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement); + } + else { + this.children.push(''.replace(aPattern, aReplacement)); + } + return this; + }; + + /** + * Set the source content for a source file. This will be added to the SourceMapGenerator + * in the sourcesContent field. + * + * @param aSourceFile The filename of the source file + * @param aSourceContent The content of the source file + */ + SourceNode.prototype.setSourceContent = + function SourceNode_setSourceContent(aSourceFile, aSourceContent) { + this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent; + }; + + /** + * Walk over the tree of SourceNodes. The walking function is called for each + * source file content and is passed the filename and source content. + * + * @param aFn The traversal function. + */ + SourceNode.prototype.walkSourceContents = + function SourceNode_walkSourceContents(aFn) { + for (var i = 0, len = this.children.length; i < len; i++) { + if (this.children[i][isSourceNode]) { + this.children[i].walkSourceContents(aFn); + } + } + + var sources = Object.keys(this.sourceContents); + for (var i = 0, len = sources.length; i < len; i++) { + aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]); + } + }; + + /** + * Return the string representation of this source node. Walks over the tree + * and concatenates all the various snippets together to one string. + */ + SourceNode.prototype.toString = function SourceNode_toString() { + var str = ""; + this.walk(function (chunk) { + str += chunk; + }); + return str; + }; + + /** + * Returns the string representation of this source node along with a source + * map. + */ + SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) { + var generated = { + code: "", + line: 1, + column: 0 + }; + var map = new SourceMapGenerator(aArgs); + var sourceMappingActive = false; + var lastOriginalSource = null; + var lastOriginalLine = null; + var lastOriginalColumn = null; + var lastOriginalName = null; + this.walk(function (chunk, original) { + generated.code += chunk; + if (original.source !== null + && original.line !== null + && original.column !== null) { + if(lastOriginalSource !== original.source + || lastOriginalLine !== original.line + || lastOriginalColumn !== original.column + || lastOriginalName !== original.name) { + map.addMapping({ + source: original.source, + original: { + line: original.line, + column: original.column + }, + generated: { + line: generated.line, + column: generated.column + }, + name: original.name + }); + } + lastOriginalSource = original.source; + lastOriginalLine = original.line; + lastOriginalColumn = original.column; + lastOriginalName = original.name; + sourceMappingActive = true; + } else if (sourceMappingActive) { + map.addMapping({ + generated: { + line: generated.line, + column: generated.column + } + }); + lastOriginalSource = null; + sourceMappingActive = false; + } + for (var idx = 0, length = chunk.length; idx < length; idx++) { + if (chunk.charCodeAt(idx) === NEWLINE_CODE) { + generated.line++; + generated.column = 0; + // Mappings end at eol + if (idx + 1 === length) { + lastOriginalSource = null; + sourceMappingActive = false; + } else if (sourceMappingActive) { + map.addMapping({ + source: original.source, + original: { + line: original.line, + column: original.column + }, + generated: { + line: generated.line, + column: generated.column + }, + name: original.name + }); + } + } else { + generated.column++; + } + } + }); + this.walkSourceContents(function (sourceFile, sourceContent) { + map.setSourceContent(sourceFile, sourceContent); + }); + + return { code: generated.code, map: map }; + }; + + exports.SourceNode = SourceNode; + + +/***/ }) +/******/ ]) +}); +; +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIndlYnBhY2s6Ly8vd2VicGFjay91bml2ZXJzYWxNb2R1bGVEZWZpbml0aW9uIiwid2VicGFjazovLy93ZWJwYWNrL2Jvb3RzdHJhcCAxNjI0YzcyOTliODg3ZjdiZGY2NCIsIndlYnBhY2s6Ly8vLi9zb3VyY2UtbWFwLmpzIiwid2VicGFjazovLy8uL2xpYi9zb3VyY2UtbWFwLWdlbmVyYXRvci5qcyIsIndlYnBhY2s6Ly8vLi9saWIvYmFzZTY0LXZscS5qcyIsIndlYnBhY2s6Ly8vLi9saWIvYmFzZTY0LmpzIiwid2VicGFjazovLy8uL2xpYi91dGlsLmpzIiwid2VicGFjazovLy8uL2xpYi9hcnJheS1zZXQuanMiLCJ3ZWJwYWNrOi8vLy4vbGliL21hcHBpbmctbGlzdC5qcyIsIndlYnBhY2s6Ly8vLi9saWIvc291cmNlLW1hcC1jb25zdW1lci5qcyIsIndlYnBhY2s6Ly8vLi9saWIvYmluYXJ5LXNlYXJjaC5qcyIsIndlYnBhY2s6Ly8vLi9saWIvcXVpY2stc29ydC5qcyIsIndlYnBhY2s6Ly8vLi9saWIvc291cmNlLW5vZGUuanMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IkFBQUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsQ0FBQztBQUNELE87QUNWQTtBQUNBOztBQUVBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQSx1QkFBZTtBQUNmO0FBQ0E7QUFDQTs7QUFFQTtBQUNBOztBQUVBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBOzs7QUFHQTtBQUNBOztBQUVBO0FBQ0E7O0FBRUE7QUFDQTs7QUFFQTtBQUNBOzs7Ozs7O0FDdENBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7Ozs7Ozs7QUNQQSxpQkFBZ0Isb0JBQW9CO0FBQ3BDO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsTUFBSztBQUNMO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQSxNQUFLO0FBQ0w7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQSxNQUFLO0FBQ0w7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLE1BQUs7QUFDTDs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSxNQUFLO0FBQ0w7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsVUFBUztBQUNUO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBOztBQUVBLE1BQUs7QUFDTDtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLE1BQUs7QUFDTDs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsUUFBTztBQUNQO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBLDJDQUEwQyxTQUFTO0FBQ25EO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0EscUJBQW9CO0FBQ3BCO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTs7QUFFQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsTUFBSztBQUNMOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTs7Ozs7OztBQ3hhQSxpQkFBZ0Isb0JBQW9CO0FBQ3BDO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSw0REFBMkQ7QUFDM0QscUJBQW9CO0FBQ3BCO0FBQ0E7QUFDQTtBQUNBOztBQUVBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7O0FBRUE7QUFDQTs7QUFFQTtBQUNBOztBQUVBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsSUFBRzs7QUFFSDtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLElBQUc7O0FBRUg7QUFDQTtBQUNBOzs7Ozs7O0FDM0lBLGlCQUFnQixvQkFBb0I7QUFDcEM7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLGlCQUFnQjtBQUNoQixpQkFBZ0I7O0FBRWhCLG9CQUFtQjtBQUNuQixxQkFBb0I7O0FBRXBCLGlCQUFnQjtBQUNoQixpQkFBZ0I7O0FBRWhCLGlCQUFnQjtBQUNoQixrQkFBaUI7O0FBRWpCO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBOzs7Ozs7O0FDbEVBLGlCQUFnQixvQkFBb0I7QUFDcEM7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLElBQUc7QUFDSDtBQUNBLElBQUc7QUFDSDtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBLCtDQUE4QyxRQUFRO0FBQ3REO0FBQ0E7QUFDQTtBQUNBLE1BQUs7QUFDTDtBQUNBLE1BQUs7QUFDTDtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSxRQUFPO0FBQ1A7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0EsRUFBQzs7QUFFRDtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTs7QUFFQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQSw0QkFBMkIsUUFBUTtBQUNuQztBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBLGNBQWE7QUFDYjs7QUFFQTtBQUNBLGVBQWM7QUFDZDs7QUFFQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLHVDQUFzQztBQUN0QztBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBOzs7Ozs7O0FDdmVBLGlCQUFnQixvQkFBb0I7QUFDcEM7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLHVDQUFzQyxTQUFTO0FBQy9DO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSxNQUFLO0FBQ0w7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLElBQUc7QUFDSDtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsSUFBRztBQUNIO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7Ozs7Ozs7QUN4SEEsaUJBQWdCLG9CQUFvQjtBQUNwQztBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLGlCQUFnQjtBQUNoQjs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSxJQUFHO0FBQ0g7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7Ozs7Ozs7QUM5RUEsaUJBQWdCLG9CQUFvQjtBQUNwQztBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQSxFQUFDOztBQUVEO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBLEVBQUM7O0FBRUQ7QUFDQTtBQUNBO0FBQ0Esb0JBQW1CO0FBQ25COztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBOztBQUVBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLE1BQUs7QUFDTDs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLFlBQVc7O0FBRVg7QUFDQTtBQUNBLFFBQU87QUFDUDs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsWUFBVzs7QUFFWDtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBOztBQUVBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsNEJBQTJCLE1BQU07QUFDakM7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSxNQUFLOztBQUVMO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0EsSUFBRzs7QUFFSDtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBLGNBQWEsa0NBQWtDO0FBQy9DO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLE1BQUs7O0FBRUw7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBOztBQUVBLHVEQUFzRCxZQUFZO0FBQ2xFO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBOztBQUVBO0FBQ0E7O0FBRUE7O0FBRUE7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLEVBQUM7O0FBRUQ7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0Esb0NBQW1DO0FBQ25DO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSwwQkFBeUIsY0FBYztBQUN2QztBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBLFVBQVM7QUFDVDtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBOztBQUVBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0Esd0JBQXVCLHdDQUF3QztBQUMvRDs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLGdEQUErQyxtQkFBbUIsRUFBRTtBQUNwRTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSxrQkFBaUIsb0JBQW9CO0FBQ3JDO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSw4QkFBNkIsTUFBTTtBQUNuQztBQUNBLFFBQU87QUFDUDtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsUUFBTztBQUNQO0FBQ0E7QUFDQSxJQUFHO0FBQ0g7O0FBRUE7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSxvQkFBbUIsMkJBQTJCO0FBQzlDLHNCQUFxQiwrQ0FBK0M7QUFDcEU7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLEVBQUM7O0FBRUQ7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0EsUUFBTztBQUNQOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLE1BQUs7QUFDTDs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsTUFBSztBQUNMOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0Esb0JBQW1CLDJCQUEyQjtBQUM5Qzs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLG9CQUFtQiwyQkFBMkI7QUFDOUM7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0Esb0JBQW1CLDJCQUEyQjtBQUM5QztBQUNBO0FBQ0Esc0JBQXFCLDRCQUE0QjtBQUNqRDs7QUFFQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTs7QUFFQTs7Ozs7OztBQ3huQ0EsaUJBQWdCLG9CQUFvQjtBQUNwQztBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLE1BQUs7QUFDTDtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0EsTUFBSztBQUNMO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7Ozs7Ozs7QUM5R0EsaUJBQWdCLG9CQUFvQjtBQUNwQztBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQSxZQUFXLE1BQU07QUFDakI7QUFDQSxZQUFXLE9BQU87QUFDbEI7QUFDQSxZQUFXLE9BQU87QUFDbEI7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0EsWUFBVyxPQUFPO0FBQ2xCO0FBQ0EsWUFBVyxPQUFPO0FBQ2xCO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0EsWUFBVyxNQUFNO0FBQ2pCO0FBQ0EsWUFBVyxTQUFTO0FBQ3BCO0FBQ0EsWUFBVyxPQUFPO0FBQ2xCO0FBQ0EsWUFBVyxPQUFPO0FBQ2xCO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSxvQkFBbUIsT0FBTztBQUMxQjtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7O0FBRUE7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0EsWUFBVyxNQUFNO0FBQ2pCO0FBQ0EsWUFBVyxTQUFTO0FBQ3BCO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7Ozs7Ozs7QUNqSEEsaUJBQWdCLG9CQUFvQjtBQUNwQztBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBOztBQUVBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSxVQUFTO0FBQ1Q7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLE1BQUs7QUFDTDtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsTUFBSzs7QUFFTDs7QUFFQTtBQUNBO0FBQ0E7QUFDQSxRQUFPO0FBQ1A7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLE1BQUs7QUFDTDtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0Esa0NBQWlDLFFBQVE7QUFDekM7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsOENBQTZDLFNBQVM7QUFDdEQ7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EscUJBQW9CO0FBQ3BCO0FBQ0E7QUFDQSx1Q0FBc0M7QUFDdEM7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsZ0JBQWUsV0FBVztBQUMxQjtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsZ0RBQStDLFNBQVM7QUFDeEQ7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQSwwQ0FBeUMsU0FBUztBQUNsRDtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLElBQUc7QUFDSDtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLFlBQVc7QUFDWDtBQUNBO0FBQ0E7QUFDQSxZQUFXO0FBQ1g7QUFDQSxVQUFTO0FBQ1Q7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsTUFBSztBQUNMO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSxRQUFPO0FBQ1A7QUFDQTtBQUNBO0FBQ0EsNkNBQTRDLGNBQWM7QUFDMUQ7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSxVQUFTO0FBQ1Q7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLGNBQWE7QUFDYjtBQUNBO0FBQ0E7QUFDQSxjQUFhO0FBQ2I7QUFDQSxZQUFXO0FBQ1g7QUFDQSxRQUFPO0FBQ1A7QUFDQTtBQUNBO0FBQ0EsSUFBRztBQUNIO0FBQ0E7QUFDQSxJQUFHOztBQUVILFdBQVU7QUFDVjs7QUFFQSIsImZpbGUiOiJzb3VyY2UtbWFwLmRlYnVnLmpzIiwic291cmNlc0NvbnRlbnQiOlsiKGZ1bmN0aW9uIHdlYnBhY2tVbml2ZXJzYWxNb2R1bGVEZWZpbml0aW9uKHJvb3QsIGZhY3RvcnkpIHtcblx0aWYodHlwZW9mIGV4cG9ydHMgPT09ICdvYmplY3QnICYmIHR5cGVvZiBtb2R1bGUgPT09ICdvYmplY3QnKVxuXHRcdG1vZHVsZS5leHBvcnRzID0gZmFjdG9yeSgpO1xuXHRlbHNlIGlmKHR5cGVvZiBkZWZpbmUgPT09ICdmdW5jdGlvbicgJiYgZGVmaW5lLmFtZClcblx0XHRkZWZpbmUoW10sIGZhY3RvcnkpO1xuXHRlbHNlIGlmKHR5cGVvZiBleHBvcnRzID09PSAnb2JqZWN0Jylcblx0XHRleHBvcnRzW1wic291cmNlTWFwXCJdID0gZmFjdG9yeSgpO1xuXHRlbHNlXG5cdFx0cm9vdFtcInNvdXJjZU1hcFwiXSA9IGZhY3RvcnkoKTtcbn0pKHRoaXMsIGZ1bmN0aW9uKCkge1xucmV0dXJuIFxuXG5cbi8vIFdFQlBBQ0sgRk9PVEVSIC8vXG4vLyB3ZWJwYWNrL3VuaXZlcnNhbE1vZHVsZURlZmluaXRpb24iLCIgXHQvLyBUaGUgbW9kdWxlIGNhY2hlXG4gXHR2YXIgaW5zdGFsbGVkTW9kdWxlcyA9IHt9O1xuXG4gXHQvLyBUaGUgcmVxdWlyZSBmdW5jdGlvblxuIFx0ZnVuY3Rpb24gX193ZWJwYWNrX3JlcXVpcmVfXyhtb2R1bGVJZCkge1xuXG4gXHRcdC8vIENoZWNrIGlmIG1vZHVsZSBpcyBpbiBjYWNoZVxuIFx0XHRpZihpbnN0YWxsZWRNb2R1bGVzW21vZHVsZUlkXSlcbiBcdFx0XHRyZXR1cm4gaW5zdGFsbGVkTW9kdWxlc1ttb2R1bGVJZF0uZXhwb3J0cztcblxuIFx0XHQvLyBDcmVhdGUgYSBuZXcgbW9kdWxlIChhbmQgcHV0IGl0IGludG8gdGhlIGNhY2hlKVxuIFx0XHR2YXIgbW9kdWxlID0gaW5zdGFsbGVkTW9kdWxlc1ttb2R1bGVJZF0gPSB7XG4gXHRcdFx0ZXhwb3J0czoge30sXG4gXHRcdFx0aWQ6IG1vZHVsZUlkLFxuIFx0XHRcdGxvYWRlZDogZmFsc2VcbiBcdFx0fTtcblxuIFx0XHQvLyBFeGVjdXRlIHRoZSBtb2R1bGUgZnVuY3Rpb25cbiBcdFx0bW9kdWxlc1ttb2R1bGVJZF0uY2FsbChtb2R1bGUuZXhwb3J0cywgbW9kdWxlLCBtb2R1bGUuZXhwb3J0cywgX193ZWJwYWNrX3JlcXVpcmVfXyk7XG5cbiBcdFx0Ly8gRmxhZyB0aGUgbW9kdWxlIGFzIGxvYWRlZFxuIFx0XHRtb2R1bGUubG9hZGVkID0gdHJ1ZTtcblxuIFx0XHQvLyBSZXR1cm4gdGhlIGV4cG9ydHMgb2YgdGhlIG1vZHVsZVxuIFx0XHRyZXR1cm4gbW9kdWxlLmV4cG9ydHM7XG4gXHR9XG5cblxuIFx0Ly8gZXhwb3NlIHRoZSBtb2R1bGVzIG9iamVjdCAoX193ZWJwYWNrX21vZHVsZXNfXylcbiBcdF9fd2VicGFja19yZXF1aXJlX18ubSA9IG1vZHVsZXM7XG5cbiBcdC8vIGV4cG9zZSB0aGUgbW9kdWxlIGNhY2hlXG4gXHRfX3dlYnBhY2tfcmVxdWlyZV9fLmMgPSBpbnN0YWxsZWRNb2R1bGVzO1xuXG4gXHQvLyBfX3dlYnBhY2tfcHVibGljX3BhdGhfX1xuIFx0X193ZWJwYWNrX3JlcXVpcmVfXy5wID0gXCJcIjtcblxuIFx0Ly8gTG9hZCBlbnRyeSBtb2R1bGUgYW5kIHJldHVybiBleHBvcnRzXG4gXHRyZXR1cm4gX193ZWJwYWNrX3JlcXVpcmVfXygwKTtcblxuXG5cbi8vIFdFQlBBQ0sgRk9PVEVSIC8vXG4vLyB3ZWJwYWNrL2Jvb3RzdHJhcCAxNjI0YzcyOTliODg3ZjdiZGY2NCIsIi8qXG4gKiBDb3B5cmlnaHQgMjAwOS0yMDExIE1vemlsbGEgRm91bmRhdGlvbiBhbmQgY29udHJpYnV0b3JzXG4gKiBMaWNlbnNlZCB1bmRlciB0aGUgTmV3IEJTRCBsaWNlbnNlLiBTZWUgTElDRU5TRS50eHQgb3I6XG4gKiBodHRwOi8vb3BlbnNvdXJjZS5vcmcvbGljZW5zZXMvQlNELTMtQ2xhdXNlXG4gKi9cbmV4cG9ydHMuU291cmNlTWFwR2VuZXJhdG9yID0gcmVxdWlyZSgnLi9saWIvc291cmNlLW1hcC1nZW5lcmF0b3InKS5Tb3VyY2VNYXBHZW5lcmF0b3I7XG5leHBvcnRzLlNvdXJjZU1hcENvbnN1bWVyID0gcmVxdWlyZSgnLi9saWIvc291cmNlLW1hcC1jb25zdW1lcicpLlNvdXJjZU1hcENvbnN1bWVyO1xuZXhwb3J0cy5Tb3VyY2VOb2RlID0gcmVxdWlyZSgnLi9saWIvc291cmNlLW5vZGUnKS5Tb3VyY2VOb2RlO1xuXG5cblxuLy8vLy8vLy8vLy8vLy8vLy8vXG4vLyBXRUJQQUNLIEZPT1RFUlxuLy8gLi9zb3VyY2UtbWFwLmpzXG4vLyBtb2R1bGUgaWQgPSAwXG4vLyBtb2R1bGUgY2h1bmtzID0gMCIsIi8qIC0qLSBNb2RlOiBqczsganMtaW5kZW50LWxldmVsOiAyOyAtKi0gKi9cbi8qXG4gKiBDb3B5cmlnaHQgMjAxMSBNb3ppbGxhIEZvdW5kYXRpb24gYW5kIGNvbnRyaWJ1dG9yc1xuICogTGljZW5zZWQgdW5kZXIgdGhlIE5ldyBCU0QgbGljZW5zZS4gU2VlIExJQ0VOU0Ugb3I6XG4gKiBodHRwOi8vb3BlbnNvdXJjZS5vcmcvbGljZW5zZXMvQlNELTMtQ2xhdXNlXG4gKi9cblxudmFyIGJhc2U2NFZMUSA9IHJlcXVpcmUoJy4vYmFzZTY0LXZscScpO1xudmFyIHV0aWwgPSByZXF1aXJlKCcuL3V0aWwnKTtcbnZhciBBcnJheVNldCA9IHJlcXVpcmUoJy4vYXJyYXktc2V0JykuQXJyYXlTZXQ7XG52YXIgTWFwcGluZ0xpc3QgPSByZXF1aXJlKCcuL21hcHBpbmctbGlzdCcpLk1hcHBpbmdMaXN0O1xuXG4vKipcbiAqIEFuIGluc3RhbmNlIG9mIHRoZSBTb3VyY2VNYXBHZW5lcmF0b3IgcmVwcmVzZW50cyBhIHNvdXJjZSBtYXAgd2hpY2ggaXNcbiAqIGJlaW5nIGJ1aWx0IGluY3JlbWVudGFsbHkuIFlvdSBtYXkgcGFzcyBhbiBvYmplY3Qgd2l0aCB0aGUgZm9sbG93aW5nXG4gKiBwcm9wZXJ0aWVzOlxuICpcbiAqICAgLSBmaWxlOiBUaGUgZmlsZW5hbWUgb2YgdGhlIGdlbmVyYXRlZCBzb3VyY2UuXG4gKiAgIC0gc291cmNlUm9vdDogQSByb290IGZvciBhbGwgcmVsYXRpdmUgVVJMcyBpbiB0aGlzIHNvdXJjZSBtYXAuXG4gKi9cbmZ1bmN0aW9uIFNvdXJjZU1hcEdlbmVyYXRvcihhQXJncykge1xuICBpZiAoIWFBcmdzKSB7XG4gICAgYUFyZ3MgPSB7fTtcbiAgfVxuICB0aGlzLl9maWxlID0gdXRpbC5nZXRBcmcoYUFyZ3MsICdmaWxlJywgbnVsbCk7XG4gIHRoaXMuX3NvdXJjZVJvb3QgPSB1dGlsLmdldEFyZyhhQXJncywgJ3NvdXJjZVJvb3QnLCBudWxsKTtcbiAgdGhpcy5fc2tpcFZhbGlkYXRpb24gPSB1dGlsLmdldEFyZyhhQXJncywgJ3NraXBWYWxpZGF0aW9uJywgZmFsc2UpO1xuICB0aGlzLl9zb3VyY2VzID0gbmV3IEFycmF5U2V0KCk7XG4gIHRoaXMuX25hbWVzID0gbmV3IEFycmF5U2V0KCk7XG4gIHRoaXMuX21hcHBpbmdzID0gbmV3IE1hcHBpbmdMaXN0KCk7XG4gIHRoaXMuX3NvdXJjZXNDb250ZW50cyA9IG51bGw7XG59XG5cblNvdXJjZU1hcEdlbmVyYXRvci5wcm90b3R5cGUuX3ZlcnNpb24gPSAzO1xuXG4vKipcbiAqIENyZWF0ZXMgYSBuZXcgU291cmNlTWFwR2VuZXJhdG9yIGJhc2VkIG9uIGEgU291cmNlTWFwQ29uc3VtZXJcbiAqXG4gKiBAcGFyYW0gYVNvdXJjZU1hcENvbnN1bWVyIFRoZSBTb3VyY2VNYXAuXG4gKi9cblNvdXJjZU1hcEdlbmVyYXRvci5mcm9tU291cmNlTWFwID1cbiAgZnVuY3Rpb24gU291cmNlTWFwR2VuZXJhdG9yX2Zyb21Tb3VyY2VNYXAoYVNvdXJjZU1hcENvbnN1bWVyKSB7XG4gICAgdmFyIHNvdXJjZVJvb3QgPSBhU291cmNlTWFwQ29uc3VtZXIuc291cmNlUm9vdDtcbiAgICB2YXIgZ2VuZXJhdG9yID0gbmV3IFNvdXJjZU1hcEdlbmVyYXRvcih7XG4gICAgICBmaWxlOiBhU291cmNlTWFwQ29uc3VtZXIuZmlsZSxcbiAgICAgIHNvdXJjZVJvb3Q6IHNvdXJjZVJvb3RcbiAgICB9KTtcbiAgICBhU291cmNlTWFwQ29uc3VtZXIuZWFjaE1hcHBpbmcoZnVuY3Rpb24gKG1hcHBpbmcpIHtcbiAgICAgIHZhciBuZXdNYXBwaW5nID0ge1xuICAgICAgICBnZW5lcmF0ZWQ6IHtcbiAgICAgICAgICBsaW5lOiBtYXBwaW5nLmdlbmVyYXRlZExpbmUsXG4gICAgICAgICAgY29sdW1uOiBtYXBwaW5nLmdlbmVyYXRlZENvbHVtblxuICAgICAgICB9XG4gICAgICB9O1xuXG4gICAgICBpZiAobWFwcGluZy5zb3VyY2UgIT0gbnVsbCkge1xuICAgICAgICBuZXdNYXBwaW5nLnNvdXJjZSA9IG1hcHBpbmcuc291cmNlO1xuICAgICAgICBpZiAoc291cmNlUm9vdCAhPSBudWxsKSB7XG4gICAgICAgICAgbmV3TWFwcGluZy5zb3VyY2UgPSB1dGlsLnJlbGF0aXZlKHNvdXJjZVJvb3QsIG5ld01hcHBpbmcuc291cmNlKTtcbiAgICAgICAgfVxuXG4gICAgICAgIG5ld01hcHBpbmcub3JpZ2luYWwgPSB7XG4gICAgICAgICAgbGluZTogbWFwcGluZy5vcmlnaW5hbExpbmUsXG4gICAgICAgICAgY29sdW1uOiBtYXBwaW5nLm9yaWdpbmFsQ29sdW1uXG4gICAgICAgIH07XG5cbiAgICAgICAgaWYgKG1hcHBpbmcubmFtZSAhPSBudWxsKSB7XG4gICAgICAgICAgbmV3TWFwcGluZy5uYW1lID0gbWFwcGluZy5uYW1lO1xuICAgICAgICB9XG4gICAgICB9XG5cbiAgICAgIGdlbmVyYXRvci5hZGRNYXBwaW5nKG5ld01hcHBpbmcpO1xuICAgIH0pO1xuICAgIGFTb3VyY2VNYXBDb25zdW1lci5zb3VyY2VzLmZvckVhY2goZnVuY3Rpb24gKHNvdXJjZUZpbGUpIHtcbiAgICAgIHZhciBzb3VyY2VSZWxhdGl2ZSA9IHNvdXJjZUZpbGU7XG4gICAgICBpZiAoc291cmNlUm9vdCAhPT0gbnVsbCkge1xuICAgICAgICBzb3VyY2VSZWxhdGl2ZSA9IHV0aWwucmVsYXRpdmUoc291cmNlUm9vdCwgc291cmNlRmlsZSk7XG4gICAgICB9XG5cbiAgICAgIGlmICghZ2VuZXJhdG9yLl9zb3VyY2VzLmhhcyhzb3VyY2VSZWxhdGl2ZSkpIHtcbiAgICAgICAgZ2VuZXJhdG9yLl9zb3VyY2VzLmFkZChzb3VyY2VSZWxhdGl2ZSk7XG4gICAgICB9XG5cbiAgICAgIHZhciBjb250ZW50ID0gYVNvdXJjZU1hcENvbnN1bWVyLnNvdXJjZUNvbnRlbnRGb3Ioc291cmNlRmlsZSk7XG4gICAgICBpZiAoY29udGVudCAhPSBudWxsKSB7XG4gICAgICAgIGdlbmVyYXRvci5zZXRTb3VyY2VDb250ZW50KHNvdXJjZUZpbGUsIGNvbnRlbnQpO1xuICAgICAgfVxuICAgIH0pO1xuICAgIHJldHVybiBnZW5lcmF0b3I7XG4gIH07XG5cbi8qKlxuICogQWRkIGEgc2luZ2xlIG1hcHBpbmcgZnJvbSBvcmlnaW5hbCBzb3VyY2UgbGluZSBhbmQgY29sdW1uIHRvIHRoZSBnZW5lcmF0ZWRcbiAqIHNvdXJjZSdzIGxpbmUgYW5kIGNvbHVtbiBmb3IgdGhpcyBzb3VyY2UgbWFwIGJlaW5nIGNyZWF0ZWQuIFRoZSBtYXBwaW5nXG4gKiBvYmplY3Qgc2hvdWxkIGhhdmUgdGhlIGZvbGxvd2luZyBwcm9wZXJ0aWVzOlxuICpcbiAqICAgLSBnZW5lcmF0ZWQ6IEFuIG9iamVjdCB3aXRoIHRoZSBnZW5lcmF0ZWQgbGluZSBhbmQgY29sdW1uIHBvc2l0aW9ucy5cbiAqICAgLSBvcmlnaW5hbDogQW4gb2JqZWN0IHdpdGggdGhlIG9yaWdpbmFsIGxpbmUgYW5kIGNvbHVtbiBwb3NpdGlvbnMuXG4gKiAgIC0gc291cmNlOiBUaGUgb3JpZ2luYWwgc291cmNlIGZpbGUgKHJlbGF0aXZlIHRvIHRoZSBzb3VyY2VSb290KS5cbiAqICAgLSBuYW1lOiBBbiBvcHRpb25hbCBvcmlnaW5hbCB0b2tlbiBuYW1lIGZvciB0aGlzIG1hcHBpbmcuXG4gKi9cblNvdXJjZU1hcEdlbmVyYXRvci5wcm90b3R5cGUuYWRkTWFwcGluZyA9XG4gIGZ1bmN0aW9uIFNvdXJjZU1hcEdlbmVyYXRvcl9hZGRNYXBwaW5nKGFBcmdzKSB7XG4gICAgdmFyIGdlbmVyYXRlZCA9IHV0aWwuZ2V0QXJnKGFBcmdzLCAnZ2VuZXJhdGVkJyk7XG4gICAgdmFyIG9yaWdpbmFsID0gdXRpbC5nZXRBcmcoYUFyZ3MsICdvcmlnaW5hbCcsIG51bGwpO1xuICAgIHZhciBzb3VyY2UgPSB1dGlsLmdldEFyZyhhQXJncywgJ3NvdXJjZScsIG51bGwpO1xuICAgIHZhciBuYW1lID0gdXRpbC5nZXRBcmcoYUFyZ3MsICduYW1lJywgbnVsbCk7XG5cbiAgICBpZiAoIXRoaXMuX3NraXBWYWxpZGF0aW9uKSB7XG4gICAgICB0aGlzLl92YWxpZGF0ZU1hcHBpbmcoZ2VuZXJhdGVkLCBvcmlnaW5hbCwgc291cmNlLCBuYW1lKTtcbiAgICB9XG5cbiAgICBpZiAoc291cmNlICE9IG51bGwpIHtcbiAgICAgIHNvdXJjZSA9IFN0cmluZyhzb3VyY2UpO1xuICAgICAgaWYgKCF0aGlzLl9zb3VyY2VzLmhhcyhzb3VyY2UpKSB7XG4gICAgICAgIHRoaXMuX3NvdXJjZXMuYWRkKHNvdXJjZSk7XG4gICAgICB9XG4gICAgfVxuXG4gICAgaWYgKG5hbWUgIT0gbnVsbCkge1xuICAgICAgbmFtZSA9IFN0cmluZyhuYW1lKTtcbiAgICAgIGlmICghdGhpcy5fbmFtZXMuaGFzKG5hbWUpKSB7XG4gICAgICAgIHRoaXMuX25hbWVzLmFkZChuYW1lKTtcbiAgICAgIH1cbiAgICB9XG5cbiAgICB0aGlzLl9tYXBwaW5ncy5hZGQoe1xuICAgICAgZ2VuZXJhdGVkTGluZTogZ2VuZXJhdGVkLmxpbmUsXG4gICAgICBnZW5lcmF0ZWRDb2x1bW46IGdlbmVyYXRlZC5jb2x1bW4sXG4gICAgICBvcmlnaW5hbExpbmU6IG9yaWdpbmFsICE9IG51bGwgJiYgb3JpZ2luYWwubGluZSxcbiAgICAgIG9yaWdpbmFsQ29sdW1uOiBvcmlnaW5hbCAhPSBudWxsICYmIG9yaWdpbmFsLmNvbHVtbixcbiAgICAgIHNvdXJjZTogc291cmNlLFxuICAgICAgbmFtZTogbmFtZVxuICAgIH0pO1xuICB9O1xuXG4vKipcbiAqIFNldCB0aGUgc291cmNlIGNvbnRlbnQgZm9yIGEgc291cmNlIGZpbGUuXG4gKi9cblNvdXJjZU1hcEdlbmVyYXRvci5wcm90b3R5cGUuc2V0U291cmNlQ29udGVudCA9XG4gIGZ1bmN0aW9uIFNvdXJjZU1hcEdlbmVyYXRvcl9zZXRTb3VyY2VDb250ZW50KGFTb3VyY2VGaWxlLCBhU291cmNlQ29udGVudCkge1xuICAgIHZhciBzb3VyY2UgPSBhU291cmNlRmlsZTtcbiAgICBpZiAodGhpcy5fc291cmNlUm9vdCAhPSBudWxsKSB7XG4gICAgICBzb3VyY2UgPSB1dGlsLnJlbGF0aXZlKHRoaXMuX3NvdXJjZVJvb3QsIHNvdXJjZSk7XG4gICAgfVxuXG4gICAgaWYgKGFTb3VyY2VDb250ZW50ICE9IG51bGwpIHtcbiAgICAgIC8vIEFkZCB0aGUgc291cmNlIGNvbnRlbnQgdG8gdGhlIF9zb3VyY2VzQ29udGVudHMgbWFwLlxuICAgICAgLy8gQ3JlYXRlIGEgbmV3IF9zb3VyY2VzQ29udGVudHMgbWFwIGlmIHRoZSBwcm9wZXJ0eSBpcyBudWxsLlxuICAgICAgaWYgKCF0aGlzLl9zb3VyY2VzQ29udGVudHMpIHtcbiAgICAgICAgdGhpcy5fc291cmNlc0NvbnRlbnRzID0gT2JqZWN0LmNyZWF0ZShudWxsKTtcbiAgICAgIH1cbiAgICAgIHRoaXMuX3NvdXJjZXNDb250ZW50c1t1dGlsLnRvU2V0U3RyaW5nKHNvdXJjZSldID0gYVNvdXJjZUNvbnRlbnQ7XG4gICAgfSBlbHNlIGlmICh0aGlzLl9zb3VyY2VzQ29udGVudHMpIHtcbiAgICAgIC8vIFJlbW92ZSB0aGUgc291cmNlIGZpbGUgZnJvbSB0aGUgX3NvdXJjZXNDb250ZW50cyBtYXAuXG4gICAgICAvLyBJZiB0aGUgX3NvdXJjZXNDb250ZW50cyBtYXAgaXMgZW1wdHksIHNldCB0aGUgcHJvcGVydHkgdG8gbnVsbC5cbiAgICAgIGRlbGV0ZSB0aGlzLl9zb3VyY2VzQ29udGVudHNbdXRpbC50b1NldFN0cmluZyhzb3VyY2UpXTtcbiAgICAgIGlmIChPYmplY3Qua2V5cyh0aGlzLl9zb3VyY2VzQ29udGVudHMpLmxlbmd0aCA9PT0gMCkge1xuICAgICAgICB0aGlzLl9zb3VyY2VzQ29udGVudHMgPSBudWxsO1xuICAgICAgfVxuICAgIH1cbiAgfTtcblxuLyoqXG4gKiBBcHBsaWVzIHRoZSBtYXBwaW5ncyBvZiBhIHN1Yi1zb3VyY2UtbWFwIGZvciBhIHNwZWNpZmljIHNvdXJjZSBmaWxlIHRvIHRoZVxuICogc291cmNlIG1hcCBiZWluZyBnZW5lcmF0ZWQuIEVhY2ggbWFwcGluZyB0byB0aGUgc3VwcGxpZWQgc291cmNlIGZpbGUgaXNcbiAqIHJld3JpdHRlbiB1c2luZyB0aGUgc3VwcGxpZWQgc291cmNlIG1hcC4gTm90ZTogVGhlIHJlc29sdXRpb24gZm9yIHRoZVxuICogcmVzdWx0aW5nIG1hcHBpbmdzIGlzIHRoZSBtaW5pbWl1bSBvZiB0aGlzIG1hcCBhbmQgdGhlIHN1cHBsaWVkIG1hcC5cbiAqXG4gKiBAcGFyYW0gYVNvdXJjZU1hcENvbnN1bWVyIFRoZSBzb3VyY2UgbWFwIHRvIGJlIGFwcGxpZWQuXG4gKiBAcGFyYW0gYVNvdXJjZUZpbGUgT3B0aW9uYWwuIFRoZSBmaWxlbmFtZSBvZiB0aGUgc291cmNlIGZpbGUuXG4gKiAgICAgICAgSWYgb21pdHRlZCwgU291cmNlTWFwQ29uc3VtZXIncyBmaWxlIHByb3BlcnR5IHdpbGwgYmUgdXNlZC5cbiAqIEBwYXJhbSBhU291cmNlTWFwUGF0aCBPcHRpb25hbC4gVGhlIGRpcm5hbWUgb2YgdGhlIHBhdGggdG8gdGhlIHNvdXJjZSBtYXBcbiAqICAgICAgICB0byBiZSBhcHBsaWVkLiBJZiByZWxhdGl2ZSwgaXQgaXMgcmVsYXRpdmUgdG8gdGhlIFNvdXJjZU1hcENvbnN1bWVyLlxuICogICAgICAgIFRoaXMgcGFyYW1ldGVyIGlzIG5lZWRlZCB3aGVuIHRoZSB0d28gc291cmNlIG1hcHMgYXJlbid0IGluIHRoZSBzYW1lXG4gKiAgICAgICAgZGlyZWN0b3J5LCBhbmQgdGhlIHNvdXJjZSBtYXAgdG8gYmUgYXBwbGllZCBjb250YWlucyByZWxhdGl2ZSBzb3VyY2VcbiAqICAgICAgICBwYXRocy4gSWYgc28sIHRob3NlIHJlbGF0aXZlIHNvdXJjZSBwYXRocyBuZWVkIHRvIGJlIHJld3JpdHRlblxuICogICAgICAgIHJlbGF0aXZlIHRvIHRoZSBTb3VyY2VNYXBHZW5lcmF0b3IuXG4gKi9cblNvdXJjZU1hcEdlbmVyYXRvci5wcm90b3R5cGUuYXBwbHlTb3VyY2VNYXAgPVxuICBmdW5jdGlvbiBTb3VyY2VNYXBHZW5lcmF0b3JfYXBwbHlTb3VyY2VNYXAoYVNvdXJjZU1hcENvbnN1bWVyLCBhU291cmNlRmlsZSwgYVNvdXJjZU1hcFBhdGgpIHtcbiAgICB2YXIgc291cmNlRmlsZSA9IGFTb3VyY2VGaWxlO1xuICAgIC8vIElmIGFTb3VyY2VGaWxlIGlzIG9taXR0ZWQsIHdlIHdpbGwgdXNlIHRoZSBmaWxlIHByb3BlcnR5IG9mIHRoZSBTb3VyY2VNYXBcbiAgICBpZiAoYVNvdXJjZUZpbGUgPT0gbnVsbCkge1xuICAgICAgaWYgKGFTb3VyY2VNYXBDb25zdW1lci5maWxlID09IG51bGwpIHtcbiAgICAgICAgdGhyb3cgbmV3IEVycm9yKFxuICAgICAgICAgICdTb3VyY2VNYXBHZW5lcmF0b3IucHJvdG90eXBlLmFwcGx5U291cmNlTWFwIHJlcXVpcmVzIGVpdGhlciBhbiBleHBsaWNpdCBzb3VyY2UgZmlsZSwgJyArXG4gICAgICAgICAgJ29yIHRoZSBzb3VyY2UgbWFwXFwncyBcImZpbGVcIiBwcm9wZXJ0eS4gQm90aCB3ZXJlIG9taXR0ZWQuJ1xuICAgICAgICApO1xuICAgICAgfVxuICAgICAgc291cmNlRmlsZSA9IGFTb3VyY2VNYXBDb25zdW1lci5maWxlO1xuICAgIH1cbiAgICB2YXIgc291cmNlUm9vdCA9IHRoaXMuX3NvdXJjZVJvb3Q7XG4gICAgLy8gTWFrZSBcInNvdXJjZUZpbGVcIiByZWxhdGl2ZSBpZiBhbiBhYnNvbHV0ZSBVcmwgaXMgcGFzc2VkLlxuICAgIGlmIChzb3VyY2VSb290ICE9IG51bGwpIHtcbiAgICAgIHNvdXJjZUZpbGUgPSB1dGlsLnJlbGF0aXZlKHNvdXJjZVJvb3QsIHNvdXJjZUZpbGUpO1xuICAgIH1cbiAgICAvLyBBcHBseWluZyB0aGUgU291cmNlTWFwIGNhbiBhZGQgYW5kIHJlbW92ZSBpdGVtcyBmcm9tIHRoZSBzb3VyY2VzIGFuZFxuICAgIC8vIHRoZSBuYW1lcyBhcnJheS5cbiAgICB2YXIgbmV3U291cmNlcyA9IG5ldyBBcnJheVNldCgpO1xuICAgIHZhciBuZXdOYW1lcyA9IG5ldyBBcnJheVNldCgpO1xuXG4gICAgLy8gRmluZCBtYXBwaW5ncyBmb3IgdGhlIFwic291cmNlRmlsZVwiXG4gICAgdGhpcy5fbWFwcGluZ3MudW5zb3J0ZWRGb3JFYWNoKGZ1bmN0aW9uIChtYXBwaW5nKSB7XG4gICAgICBpZiAobWFwcGluZy5zb3VyY2UgPT09IHNvdXJjZUZpbGUgJiYgbWFwcGluZy5vcmlnaW5hbExpbmUgIT0gbnVsbCkge1xuICAgICAgICAvLyBDaGVjayBpZiBpdCBjYW4gYmUgbWFwcGVkIGJ5IHRoZSBzb3VyY2UgbWFwLCB0aGVuIHVwZGF0ZSB0aGUgbWFwcGluZy5cbiAgICAgICAgdmFyIG9yaWdpbmFsID0gYVNvdXJjZU1hcENvbnN1bWVyLm9yaWdpbmFsUG9zaXRpb25Gb3Ioe1xuICAgICAgICAgIGxpbmU6IG1hcHBpbmcub3JpZ2luYWxMaW5lLFxuICAgICAgICAgIGNvbHVtbjogbWFwcGluZy5vcmlnaW5hbENvbHVtblxuICAgICAgICB9KTtcbiAgICAgICAgaWYgKG9yaWdpbmFsLnNvdXJjZSAhPSBudWxsKSB7XG4gICAgICAgICAgLy8gQ29weSBtYXBwaW5nXG4gICAgICAgICAgbWFwcGluZy5zb3VyY2UgPSBvcmlnaW5hbC5zb3VyY2U7XG4gICAgICAgICAgaWYgKGFTb3VyY2VNYXBQYXRoICE9IG51bGwpIHtcbiAgICAgICAgICAgIG1hcHBpbmcuc291cmNlID0gdXRpbC5qb2luKGFTb3VyY2VNYXBQYXRoLCBtYXBwaW5nLnNvdXJjZSlcbiAgICAgICAgICB9XG4gICAgICAgICAgaWYgKHNvdXJjZVJvb3QgIT0gbnVsbCkge1xuICAgICAgICAgICAgbWFwcGluZy5zb3VyY2UgPSB1dGlsLnJlbGF0aXZlKHNvdXJjZVJvb3QsIG1hcHBpbmcuc291cmNlKTtcbiAgICAgICAgICB9XG4gICAgICAgICAgbWFwcGluZy5vcmlnaW5hbExpbmUgPSBvcmlnaW5hbC5saW5lO1xuICAgICAgICAgIG1hcHBpbmcub3JpZ2luYWxDb2x1bW4gPSBvcmlnaW5hbC5jb2x1bW47XG4gICAgICAgICAgaWYgKG9yaWdpbmFsLm5hbWUgIT0gbnVsbCkge1xuICAgICAgICAgICAgbWFwcGluZy5uYW1lID0gb3JpZ2luYWwubmFtZTtcbiAgICAgICAgICB9XG4gICAgICAgIH1cbiAgICAgIH1cblxuICAgICAgdmFyIHNvdXJjZSA9IG1hcHBpbmcuc291cmNlO1xuICAgICAgaWYgKHNvdXJjZSAhPSBudWxsICYmICFuZXdTb3VyY2VzLmhhcyhzb3VyY2UpKSB7XG4gICAgICAgIG5ld1NvdXJjZXMuYWRkKHNvdXJjZSk7XG4gICAgICB9XG5cbiAgICAgIHZhciBuYW1lID0gbWFwcGluZy5uYW1lO1xuICAgICAgaWYgKG5hbWUgIT0gbnVsbCAmJiAhbmV3TmFtZXMuaGFzKG5hbWUpKSB7XG4gICAgICAgIG5ld05hbWVzLmFkZChuYW1lKTtcbiAgICAgIH1cblxuICAgIH0sIHRoaXMpO1xuICAgIHRoaXMuX3NvdXJjZXMgPSBuZXdTb3VyY2VzO1xuICAgIHRoaXMuX25hbWVzID0gbmV3TmFtZXM7XG5cbiAgICAvLyBDb3B5IHNvdXJjZXNDb250ZW50cyBvZiBhcHBsaWVkIG1hcC5cbiAgICBhU291cmNlTWFwQ29uc3VtZXIuc291cmNlcy5mb3JFYWNoKGZ1bmN0aW9uIChzb3VyY2VGaWxlKSB7XG4gICAgICB2YXIgY29udGVudCA9IGFTb3VyY2VNYXBDb25zdW1lci5zb3VyY2VDb250ZW50Rm9yKHNvdXJjZUZpbGUpO1xuICAgICAgaWYgKGNvbnRlbnQgIT0gbnVsbCkge1xuICAgICAgICBpZiAoYVNvdXJjZU1hcFBhdGggIT0gbnVsbCkge1xuICAgICAgICAgIHNvdXJjZUZpbGUgPSB1dGlsLmpvaW4oYVNvdXJjZU1hcFBhdGgsIHNvdXJjZUZpbGUpO1xuICAgICAgICB9XG4gICAgICAgIGlmIChzb3VyY2VSb290ICE9IG51bGwpIHtcbiAgICAgICAgICBzb3VyY2VGaWxlID0gdXRpbC5yZWxhdGl2ZShzb3VyY2VSb290LCBzb3VyY2VGaWxlKTtcbiAgICAgICAgfVxuICAgICAgICB0aGlzLnNldFNvdXJjZUNvbnRlbnQoc291cmNlRmlsZSwgY29udGVudCk7XG4gICAgICB9XG4gICAgfSwgdGhpcyk7XG4gIH07XG5cbi8qKlxuICogQSBtYXBwaW5nIGNhbiBoYXZlIG9uZSBvZiB0aGUgdGhyZWUgbGV2ZWxzIG9mIGRhdGE6XG4gKlxuICogICAxLiBKdXN0IHRoZSBnZW5lcmF0ZWQgcG9zaXRpb24uXG4gKiAgIDIuIFRoZSBHZW5lcmF0ZWQgcG9zaXRpb24sIG9yaWdpbmFsIHBvc2l0aW9uLCBhbmQgb3JpZ2luYWwgc291cmNlLlxuICogICAzLiBHZW5lcmF0ZWQgYW5kIG9yaWdpbmFsIHBvc2l0aW9uLCBvcmlnaW5hbCBzb3VyY2UsIGFzIHdlbGwgYXMgYSBuYW1lXG4gKiAgICAgIHRva2VuLlxuICpcbiAqIFRvIG1haW50YWluIGNvbnNpc3RlbmN5LCB3ZSB2YWxpZGF0ZSB0aGF0IGFueSBuZXcgbWFwcGluZyBiZWluZyBhZGRlZCBmYWxsc1xuICogaW4gdG8gb25lIG9mIHRoZXNlIGNhdGVnb3JpZXMuXG4gKi9cblNvdXJjZU1hcEdlbmVyYXRvci5wcm90b3R5cGUuX3ZhbGlkYXRlTWFwcGluZyA9XG4gIGZ1bmN0aW9uIFNvdXJjZU1hcEdlbmVyYXRvcl92YWxpZGF0ZU1hcHBpbmcoYUdlbmVyYXRlZCwgYU9yaWdpbmFsLCBhU291cmNlLFxuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIGFOYW1lKSB7XG4gICAgLy8gV2hlbiBhT3JpZ2luYWwgaXMgdHJ1dGh5IGJ1dCBoYXMgZW1wdHkgdmFsdWVzIGZvciAubGluZSBhbmQgLmNvbHVtbixcbiAgICAvLyBpdCBpcyBtb3N0IGxpa2VseSBhIHByb2dyYW1tZXIgZXJyb3IuIEluIHRoaXMgY2FzZSB3ZSB0aHJvdyBhIHZlcnlcbiAgICAvLyBzcGVjaWZpYyBlcnJvciBtZXNzYWdlIHRvIHRyeSB0byBndWlkZSB0aGVtIHRoZSByaWdodCB3YXkuXG4gICAgLy8gRm9yIGV4YW1wbGU6IGh0dHBzOi8vZ2l0aHViLmNvbS9Qb2x5bWVyL3BvbHltZXItYnVuZGxlci9wdWxsLzUxOVxuICAgIGlmIChhT3JpZ2luYWwgJiYgdHlwZW9mIGFPcmlnaW5hbC5saW5lICE9PSAnbnVtYmVyJyAmJiB0eXBlb2YgYU9yaWdpbmFsLmNvbHVtbiAhPT0gJ251bWJlcicpIHtcbiAgICAgICAgdGhyb3cgbmV3IEVycm9yKFxuICAgICAgICAgICAgJ29yaWdpbmFsLmxpbmUgYW5kIG9yaWdpbmFsLmNvbHVtbiBhcmUgbm90IG51bWJlcnMgLS0geW91IHByb2JhYmx5IG1lYW50IHRvIG9taXQgJyArXG4gICAgICAgICAgICAndGhlIG9yaWdpbmFsIG1hcHBpbmcgZW50aXJlbHkgYW5kIG9ubHkgbWFwIHRoZSBnZW5lcmF0ZWQgcG9zaXRpb24uIElmIHNvLCBwYXNzICcgK1xuICAgICAgICAgICAgJ251bGwgZm9yIHRoZSBvcmlnaW5hbCBtYXBwaW5nIGluc3RlYWQgb2YgYW4gb2JqZWN0IHdpdGggZW1wdHkgb3IgbnVsbCB2YWx1ZXMuJ1xuICAgICAgICApO1xuICAgIH1cblxuICAgIGlmIChhR2VuZXJhdGVkICYmICdsaW5lJyBpbiBhR2VuZXJhdGVkICYmICdjb2x1bW4nIGluIGFHZW5lcmF0ZWRcbiAgICAgICAgJiYgYUdlbmVyYXRlZC5saW5lID4gMCAmJiBhR2VuZXJhdGVkLmNvbHVtbiA+PSAwXG4gICAgICAgICYmICFhT3JpZ2luYWwgJiYgIWFTb3VyY2UgJiYgIWFOYW1lKSB7XG4gICAgICAvLyBDYXNlIDEuXG4gICAgICByZXR1cm47XG4gICAgfVxuICAgIGVsc2UgaWYgKGFHZW5lcmF0ZWQgJiYgJ2xpbmUnIGluIGFHZW5lcmF0ZWQgJiYgJ2NvbHVtbicgaW4gYUdlbmVyYXRlZFxuICAgICAgICAgICAgICYmIGFPcmlnaW5hbCAmJiAnbGluZScgaW4gYU9yaWdpbmFsICYmICdjb2x1bW4nIGluIGFPcmlnaW5hbFxuICAgICAgICAgICAgICYmIGFHZW5lcmF0ZWQubGluZSA+IDAgJiYgYUdlbmVyYXRlZC5jb2x1bW4gPj0gMFxuICAgICAgICAgICAgICYmIGFPcmlnaW5hbC5saW5lID4gMCAmJiBhT3JpZ2luYWwuY29sdW1uID49IDBcbiAgICAgICAgICAgICAmJiBhU291cmNlKSB7XG4gICAgICAvLyBDYXNlcyAyIGFuZCAzLlxuICAgICAgcmV0dXJuO1xuICAgIH1cbiAgICBlbHNlIHtcbiAgICAgIHRocm93IG5ldyBFcnJvcignSW52YWxpZCBtYXBwaW5nOiAnICsgSlNPTi5zdHJpbmdpZnkoe1xuICAgICAgICBnZW5lcmF0ZWQ6IGFHZW5lcmF0ZWQsXG4gICAgICAgIHNvdXJjZTogYVNvdXJjZSxcbiAgICAgICAgb3JpZ2luYWw6IGFPcmlnaW5hbCxcbiAgICAgICAgbmFtZTogYU5hbWVcbiAgICAgIH0pKTtcbiAgICB9XG4gIH07XG5cbi8qKlxuICogU2VyaWFsaXplIHRoZSBhY2N1bXVsYXRlZCBtYXBwaW5ncyBpbiB0byB0aGUgc3RyZWFtIG9mIGJhc2UgNjQgVkxRc1xuICogc3BlY2lmaWVkIGJ5IHRoZSBzb3VyY2UgbWFwIGZvcm1hdC5cbiAqL1xuU291cmNlTWFwR2VuZXJhdG9yLnByb3RvdHlwZS5fc2VyaWFsaXplTWFwcGluZ3MgPVxuICBmdW5jdGlvbiBTb3VyY2VNYXBHZW5lcmF0b3Jfc2VyaWFsaXplTWFwcGluZ3MoKSB7XG4gICAgdmFyIHByZXZpb3VzR2VuZXJhdGVkQ29sdW1uID0gMDtcbiAgICB2YXIgcHJldmlvdXNHZW5lcmF0ZWRMaW5lID0gMTtcbiAgICB2YXIgcHJldmlvdXNPcmlnaW5hbENvbHVtbiA9IDA7XG4gICAgdmFyIHByZXZpb3VzT3JpZ2luYWxMaW5lID0gMDtcbiAgICB2YXIgcHJldmlvdXNOYW1lID0gMDtcbiAgICB2YXIgcHJldmlvdXNTb3VyY2UgPSAwO1xuICAgIHZhciByZXN1bHQgPSAnJztcbiAgICB2YXIgbmV4dDtcbiAgICB2YXIgbWFwcGluZztcbiAgICB2YXIgbmFtZUlkeDtcbiAgICB2YXIgc291cmNlSWR4O1xuXG4gICAgdmFyIG1hcHBpbmdzID0gdGhpcy5fbWFwcGluZ3MudG9BcnJheSgpO1xuICAgIGZvciAodmFyIGkgPSAwLCBsZW4gPSBtYXBwaW5ncy5sZW5ndGg7IGkgPCBsZW47IGkrKykge1xuICAgICAgbWFwcGluZyA9IG1hcHBpbmdzW2ldO1xuICAgICAgbmV4dCA9ICcnXG5cbiAgICAgIGlmIChtYXBwaW5nLmdlbmVyYXRlZExpbmUgIT09IHByZXZpb3VzR2VuZXJhdGVkTGluZSkge1xuICAgICAgICBwcmV2aW91c0dlbmVyYXRlZENvbHVtbiA9IDA7XG4gICAgICAgIHdoaWxlIChtYXBwaW5nLmdlbmVyYXRlZExpbmUgIT09IHByZXZpb3VzR2VuZXJhdGVkTGluZSkge1xuICAgICAgICAgIG5leHQgKz0gJzsnO1xuICAgICAgICAgIHByZXZpb3VzR2VuZXJhdGVkTGluZSsrO1xuICAgICAgICB9XG4gICAgICB9XG4gICAgICBlbHNlIHtcbiAgICAgICAgaWYgKGkgPiAwKSB7XG4gICAgICAgICAgaWYgKCF1dGlsLmNvbXBhcmVCeUdlbmVyYXRlZFBvc2l0aW9uc0luZmxhdGVkKG1hcHBpbmcsIG1hcHBpbmdzW2kgLSAxXSkpIHtcbiAgICAgICAgICAgIGNvbnRpbnVlO1xuICAgICAgICAgIH1cbiAgICAgICAgICBuZXh0ICs9ICcsJztcbiAgICAgICAgfVxuICAgICAgfVxuXG4gICAgICBuZXh0ICs9IGJhc2U2NFZMUS5lbmNvZGUobWFwcGluZy5nZW5lcmF0ZWRDb2x1bW5cbiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIC0gcHJldmlvdXNHZW5lcmF0ZWRDb2x1bW4pO1xuICAgICAgcHJldmlvdXNHZW5lcmF0ZWRDb2x1bW4gPSBtYXBwaW5nLmdlbmVyYXRlZENvbHVtbjtcblxuICAgICAgaWYgKG1hcHBpbmcuc291cmNlICE9IG51bGwpIHtcbiAgICAgICAgc291cmNlSWR4ID0gdGhpcy5fc291cmNlcy5pbmRleE9mKG1hcHBpbmcuc291cmNlKTtcbiAgICAgICAgbmV4dCArPSBiYXNlNjRWTFEuZW5jb2RlKHNvdXJjZUlkeCAtIHByZXZpb3VzU291cmNlKTtcbiAgICAgICAgcHJldmlvdXNTb3VyY2UgPSBzb3VyY2VJZHg7XG5cbiAgICAgICAgLy8gbGluZXMgYXJlIHN0b3JlZCAwLWJhc2VkIGluIFNvdXJjZU1hcCBzcGVjIHZlcnNpb24gM1xuICAgICAgICBuZXh0ICs9IGJhc2U2NFZMUS5lbmNvZGUobWFwcGluZy5vcmlnaW5hbExpbmUgLSAxXG4gICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIC0gcHJldmlvdXNPcmlnaW5hbExpbmUpO1xuICAgICAgICBwcmV2aW91c09yaWdpbmFsTGluZSA9IG1hcHBpbmcub3JpZ2luYWxMaW5lIC0gMTtcblxuICAgICAgICBuZXh0ICs9IGJhc2U2NFZMUS5lbmNvZGUobWFwcGluZy5vcmlnaW5hbENvbHVtblxuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAtIHByZXZpb3VzT3JpZ2luYWxDb2x1bW4pO1xuICAgICAgICBwcmV2aW91c09yaWdpbmFsQ29sdW1uID0gbWFwcGluZy5vcmlnaW5hbENvbHVtbjtcblxuICAgICAgICBpZiAobWFwcGluZy5uYW1lICE9IG51bGwpIHtcbiAgICAgICAgICBuYW1lSWR4ID0gdGhpcy5fbmFtZXMuaW5kZXhPZihtYXBwaW5nLm5hbWUpO1xuICAgICAgICAgIG5leHQgKz0gYmFzZTY0VkxRLmVuY29kZShuYW1lSWR4IC0gcHJldmlvdXNOYW1lKTtcbiAgICAgICAgICBwcmV2aW91c05hbWUgPSBuYW1lSWR4O1xuICAgICAgICB9XG4gICAgICB9XG5cbiAgICAgIHJlc3VsdCArPSBuZXh0O1xuICAgIH1cblxuICAgIHJldHVybiByZXN1bHQ7XG4gIH07XG5cblNvdXJjZU1hcEdlbmVyYXRvci5wcm90b3R5cGUuX2dlbmVyYXRlU291cmNlc0NvbnRlbnQgPVxuICBmdW5jdGlvbiBTb3VyY2VNYXBHZW5lcmF0b3JfZ2VuZXJhdGVTb3VyY2VzQ29udGVudChhU291cmNlcywgYVNvdXJjZVJvb3QpIHtcbiAgICByZXR1cm4gYVNvdXJjZXMubWFwKGZ1bmN0aW9uIChzb3VyY2UpIHtcbiAgICAgIGlmICghdGhpcy5fc291cmNlc0NvbnRlbnRzKSB7XG4gICAgICAgIHJldHVybiBudWxsO1xuICAgICAgfVxuICAgICAgaWYgKGFTb3VyY2VSb290ICE9IG51bGwpIHtcbiAgICAgICAgc291cmNlID0gdXRpbC5yZWxhdGl2ZShhU291cmNlUm9vdCwgc291cmNlKTtcbiAgICAgIH1cbiAgICAgIHZhciBrZXkgPSB1dGlsLnRvU2V0U3RyaW5nKHNvdXJjZSk7XG4gICAgICByZXR1cm4gT2JqZWN0LnByb3RvdHlwZS5oYXNPd25Qcm9wZXJ0eS5jYWxsKHRoaXMuX3NvdXJjZXNDb250ZW50cywga2V5KVxuICAgICAgICA/IHRoaXMuX3NvdXJjZXNDb250ZW50c1trZXldXG4gICAgICAgIDogbnVsbDtcbiAgICB9LCB0aGlzKTtcbiAgfTtcblxuLyoqXG4gKiBFeHRlcm5hbGl6ZSB0aGUgc291cmNlIG1hcC5cbiAqL1xuU291cmNlTWFwR2VuZXJhdG9yLnByb3RvdHlwZS50b0pTT04gPVxuICBmdW5jdGlvbiBTb3VyY2VNYXBHZW5lcmF0b3JfdG9KU09OKCkge1xuICAgIHZhciBtYXAgPSB7XG4gICAgICB2ZXJzaW9uOiB0aGlzLl92ZXJzaW9uLFxuICAgICAgc291cmNlczogdGhpcy5fc291cmNlcy50b0FycmF5KCksXG4gICAgICBuYW1lczogdGhpcy5fbmFtZXMudG9BcnJheSgpLFxuICAgICAgbWFwcGluZ3M6IHRoaXMuX3NlcmlhbGl6ZU1hcHBpbmdzKClcbiAgICB9O1xuICAgIGlmICh0aGlzLl9maWxlICE9IG51bGwpIHtcbiAgICAgIG1hcC5maWxlID0gdGhpcy5fZmlsZTtcbiAgICB9XG4gICAgaWYgKHRoaXMuX3NvdXJjZVJvb3QgIT0gbnVsbCkge1xuICAgICAgbWFwLnNvdXJjZVJvb3QgPSB0aGlzLl9zb3VyY2VSb290O1xuICAgIH1cbiAgICBpZiAodGhpcy5fc291cmNlc0NvbnRlbnRzKSB7XG4gICAgICBtYXAuc291cmNlc0NvbnRlbnQgPSB0aGlzLl9nZW5lcmF0ZVNvdXJjZXNDb250ZW50KG1hcC5zb3VyY2VzLCBtYXAuc291cmNlUm9vdCk7XG4gICAgfVxuXG4gICAgcmV0dXJuIG1hcDtcbiAgfTtcblxuLyoqXG4gKiBSZW5kZXIgdGhlIHNvdXJjZSBtYXAgYmVpbmcgZ2VuZXJhdGVkIHRvIGEgc3RyaW5nLlxuICovXG5Tb3VyY2VNYXBHZW5lcmF0b3IucHJvdG90eXBlLnRvU3RyaW5nID1cbiAgZnVuY3Rpb24gU291cmNlTWFwR2VuZXJhdG9yX3RvU3RyaW5nKCkge1xuICAgIHJldHVybiBKU09OLnN0cmluZ2lmeSh0aGlzLnRvSlNPTigpKTtcbiAgfTtcblxuZXhwb3J0cy5Tb3VyY2VNYXBHZW5lcmF0b3IgPSBTb3VyY2VNYXBHZW5lcmF0b3I7XG5cblxuXG4vLy8vLy8vLy8vLy8vLy8vLy9cbi8vIFdFQlBBQ0sgRk9PVEVSXG4vLyAuL2xpYi9zb3VyY2UtbWFwLWdlbmVyYXRvci5qc1xuLy8gbW9kdWxlIGlkID0gMVxuLy8gbW9kdWxlIGNodW5rcyA9IDAiLCIvKiAtKi0gTW9kZToganM7IGpzLWluZGVudC1sZXZlbDogMjsgLSotICovXG4vKlxuICogQ29weXJpZ2h0IDIwMTEgTW96aWxsYSBGb3VuZGF0aW9uIGFuZCBjb250cmlidXRvcnNcbiAqIExpY2Vuc2VkIHVuZGVyIHRoZSBOZXcgQlNEIGxpY2Vuc2UuIFNlZSBMSUNFTlNFIG9yOlxuICogaHR0cDovL29wZW5zb3VyY2Uub3JnL2xpY2Vuc2VzL0JTRC0zLUNsYXVzZVxuICpcbiAqIEJhc2VkIG9uIHRoZSBCYXNlIDY0IFZMUSBpbXBsZW1lbnRhdGlvbiBpbiBDbG9zdXJlIENvbXBpbGVyOlxuICogaHR0cHM6Ly9jb2RlLmdvb2dsZS5jb20vcC9jbG9zdXJlLWNvbXBpbGVyL3NvdXJjZS9icm93c2UvdHJ1bmsvc3JjL2NvbS9nb29nbGUvZGVidWdnaW5nL3NvdXJjZW1hcC9CYXNlNjRWTFEuamF2YVxuICpcbiAqIENvcHlyaWdodCAyMDExIFRoZSBDbG9zdXJlIENvbXBpbGVyIEF1dGhvcnMuIEFsbCByaWdodHMgcmVzZXJ2ZWQuXG4gKiBSZWRpc3RyaWJ1dGlvbiBhbmQgdXNlIGluIHNvdXJjZSBhbmQgYmluYXJ5IGZvcm1zLCB3aXRoIG9yIHdpdGhvdXRcbiAqIG1vZGlmaWNhdGlvbiwgYXJlIHBlcm1pdHRlZCBwcm92aWRlZCB0aGF0IHRoZSBmb2xsb3dpbmcgY29uZGl0aW9ucyBhcmVcbiAqIG1ldDpcbiAqXG4gKiAgKiBSZWRpc3RyaWJ1dGlvbnMgb2Ygc291cmNlIGNvZGUgbXVzdCByZXRhaW4gdGhlIGFib3ZlIGNvcHlyaWdodFxuICogICAgbm90aWNlLCB0aGlzIGxpc3Qgb2YgY29uZGl0aW9ucyBhbmQgdGhlIGZvbGxvd2luZyBkaXNjbGFpbWVyLlxuICogICogUmVkaXN0cmlidXRpb25zIGluIGJpbmFyeSBmb3JtIG11c3QgcmVwcm9kdWNlIHRoZSBhYm92ZVxuICogICAgY29weXJpZ2h0IG5vdGljZSwgdGhpcyBsaXN0IG9mIGNvbmRpdGlvbnMgYW5kIHRoZSBmb2xsb3dpbmdcbiAqICAgIGRpc2NsYWltZXIgaW4gdGhlIGRvY3VtZW50YXRpb24gYW5kL29yIG90aGVyIG1hdGVyaWFscyBwcm92aWRlZFxuICogICAgd2l0aCB0aGUgZGlzdHJpYnV0aW9uLlxuICogICogTmVpdGhlciB0aGUgbmFtZSBvZiBHb29nbGUgSW5jLiBub3IgdGhlIG5hbWVzIG9mIGl0c1xuICogICAgY29udHJpYnV0b3JzIG1heSBiZSB1c2VkIHRvIGVuZG9yc2Ugb3IgcHJvbW90ZSBwcm9kdWN0cyBkZXJpdmVkXG4gKiAgICBmcm9tIHRoaXMgc29mdHdhcmUgd2l0aG91dCBzcGVjaWZpYyBwcmlvciB3cml0dGVuIHBlcm1pc3Npb24uXG4gKlxuICogVEhJUyBTT0ZUV0FSRSBJUyBQUk9WSURFRCBCWSBUSEUgQ09QWVJJR0hUIEhPTERFUlMgQU5EIENPTlRSSUJVVE9SU1xuICogXCJBUyBJU1wiIEFORCBBTlkgRVhQUkVTUyBPUiBJTVBMSUVEIFdBUlJBTlRJRVMsIElOQ0xVRElORywgQlVUIE5PVFxuICogTElNSVRFRCBUTywgVEhFIElNUExJRUQgV0FSUkFOVElFUyBPRiBNRVJDSEFOVEFCSUxJVFkgQU5EIEZJVE5FU1MgRk9SXG4gKiBBIFBBUlRJQ1VMQVIgUFVSUE9TRSBBUkUgRElTQ0xBSU1FRC4gSU4gTk8gRVZFTlQgU0hBTEwgVEhFIENPUFlSSUdIVFxuICogT1dORVIgT1IgQ09OVFJJQlVUT1JTIEJFIExJQUJMRSBGT1IgQU5ZIERJUkVDVCwgSU5ESVJFQ1QsIElOQ0lERU5UQUwsXG4gKiBTUEVDSUFMLCBFWEVNUExBUlksIE9SIENPTlNFUVVFTlRJQUwgREFNQUdFUyAoSU5DTFVESU5HLCBCVVQgTk9UXG4gKiBMSU1JVEVEIFRPLCBQUk9DVVJFTUVOVCBPRiBTVUJTVElUVVRFIEdPT0RTIE9SIFNFUlZJQ0VTOyBMT1NTIE9GIFVTRSxcbiAqIERBVEEsIE9SIFBST0ZJVFM7IE9SIEJVU0lORVNTIElOVEVSUlVQVElPTikgSE9XRVZFUiBDQVVTRUQgQU5EIE9OIEFOWVxuICogVEhFT1JZIE9GIExJQUJJTElUWSwgV0hFVEhFUiBJTiBDT05UUkFDVCwgU1RSSUNUIExJQUJJTElUWSwgT1IgVE9SVFxuICogKElOQ0xVRElORyBORUdMSUdFTkNFIE9SIE9USEVSV0lTRSkgQVJJU0lORyBJTiBBTlkgV0FZIE9VVCBPRiBUSEUgVVNFXG4gKiBPRiBUSElTIFNPRlRXQVJFLCBFVkVOIElGIEFEVklTRUQgT0YgVEhFIFBPU1NJQklMSVRZIE9GIFNVQ0ggREFNQUdFLlxuICovXG5cbnZhciBiYXNlNjQgPSByZXF1aXJlKCcuL2Jhc2U2NCcpO1xuXG4vLyBBIHNpbmdsZSBiYXNlIDY0IGRpZ2l0IGNhbiBjb250YWluIDYgYml0cyBvZiBkYXRhLiBGb3IgdGhlIGJhc2UgNjQgdmFyaWFibGVcbi8vIGxlbmd0aCBxdWFudGl0aWVzIHdlIHVzZSBpbiB0aGUgc291cmNlIG1hcCBzcGVjLCB0aGUgZmlyc3QgYml0IGlzIHRoZSBzaWduLFxuLy8gdGhlIG5leHQgZm91ciBiaXRzIGFyZSB0aGUgYWN0dWFsIHZhbHVlLCBhbmQgdGhlIDZ0aCBiaXQgaXMgdGhlXG4vLyBjb250aW51YXRpb24gYml0LiBUaGUgY29udGludWF0aW9uIGJpdCB0ZWxscyB1cyB3aGV0aGVyIHRoZXJlIGFyZSBtb3JlXG4vLyBkaWdpdHMgaW4gdGhpcyB2YWx1ZSBmb2xsb3dpbmcgdGhpcyBkaWdpdC5cbi8vXG4vLyAgIENvbnRpbnVhdGlvblxuLy8gICB8ICAgIFNpZ25cbi8vICAgfCAgICB8XG4vLyAgIFYgICAgVlxuLy8gICAxMDEwMTFcblxudmFyIFZMUV9CQVNFX1NISUZUID0gNTtcblxuLy8gYmluYXJ5OiAxMDAwMDBcbnZhciBWTFFfQkFTRSA9IDEgPDwgVkxRX0JBU0VfU0hJRlQ7XG5cbi8vIGJpbmFyeTogMDExMTExXG52YXIgVkxRX0JBU0VfTUFTSyA9IFZMUV9CQVNFIC0gMTtcblxuLy8gYmluYXJ5OiAxMDAwMDBcbnZhciBWTFFfQ09OVElOVUFUSU9OX0JJVCA9IFZMUV9CQVNFO1xuXG4vKipcbiAqIENvbnZlcnRzIGZyb20gYSB0d28tY29tcGxlbWVudCB2YWx1ZSB0byBhIHZhbHVlIHdoZXJlIHRoZSBzaWduIGJpdCBpc1xuICogcGxhY2VkIGluIHRoZSBsZWFzdCBzaWduaWZpY2FudCBiaXQuICBGb3IgZXhhbXBsZSwgYXMgZGVjaW1hbHM6XG4gKiAgIDEgYmVjb21lcyAyICgxMCBiaW5hcnkpLCAtMSBiZWNvbWVzIDMgKDExIGJpbmFyeSlcbiAqICAgMiBiZWNvbWVzIDQgKDEwMCBiaW5hcnkpLCAtMiBiZWNvbWVzIDUgKDEwMSBiaW5hcnkpXG4gKi9cbmZ1bmN0aW9uIHRvVkxRU2lnbmVkKGFWYWx1ZSkge1xuICByZXR1cm4gYVZhbHVlIDwgMFxuICAgID8gKCgtYVZhbHVlKSA8PCAxKSArIDFcbiAgICA6IChhVmFsdWUgPDwgMSkgKyAwO1xufVxuXG4vKipcbiAqIENvbnZlcnRzIHRvIGEgdHdvLWNvbXBsZW1lbnQgdmFsdWUgZnJvbSBhIHZhbHVlIHdoZXJlIHRoZSBzaWduIGJpdCBpc1xuICogcGxhY2VkIGluIHRoZSBsZWFzdCBzaWduaWZpY2FudCBiaXQuICBGb3IgZXhhbXBsZSwgYXMgZGVjaW1hbHM6XG4gKiAgIDIgKDEwIGJpbmFyeSkgYmVjb21lcyAxLCAzICgxMSBiaW5hcnkpIGJlY29tZXMgLTFcbiAqICAgNCAoMTAwIGJpbmFyeSkgYmVjb21lcyAyLCA1ICgxMDEgYmluYXJ5KSBiZWNvbWVzIC0yXG4gKi9cbmZ1bmN0aW9uIGZyb21WTFFTaWduZWQoYVZhbHVlKSB7XG4gIHZhciBpc05lZ2F0aXZlID0gKGFWYWx1ZSAmIDEpID09PSAxO1xuICB2YXIgc2hpZnRlZCA9IGFWYWx1ZSA+PiAxO1xuICByZXR1cm4gaXNOZWdhdGl2ZVxuICAgID8gLXNoaWZ0ZWRcbiAgICA6IHNoaWZ0ZWQ7XG59XG5cbi8qKlxuICogUmV0dXJucyB0aGUgYmFzZSA2NCBWTFEgZW5jb2RlZCB2YWx1ZS5cbiAqL1xuZXhwb3J0cy5lbmNvZGUgPSBmdW5jdGlvbiBiYXNlNjRWTFFfZW5jb2RlKGFWYWx1ZSkge1xuICB2YXIgZW5jb2RlZCA9IFwiXCI7XG4gIHZhciBkaWdpdDtcblxuICB2YXIgdmxxID0gdG9WTFFTaWduZWQoYVZhbHVlKTtcblxuICBkbyB7XG4gICAgZGlnaXQgPSB2bHEgJiBWTFFfQkFTRV9NQVNLO1xuICAgIHZscSA+Pj49IFZMUV9CQVNFX1NISUZUO1xuICAgIGlmICh2bHEgPiAwKSB7XG4gICAgICAvLyBUaGVyZSBhcmUgc3RpbGwgbW9yZSBkaWdpdHMgaW4gdGhpcyB2YWx1ZSwgc28gd2UgbXVzdCBtYWtlIHN1cmUgdGhlXG4gICAgICAvLyBjb250aW51YXRpb24gYml0IGlzIG1hcmtlZC5cbiAgICAgIGRpZ2l0IHw9IFZMUV9DT05USU5VQVRJT05fQklUO1xuICAgIH1cbiAgICBlbmNvZGVkICs9IGJhc2U2NC5lbmNvZGUoZGlnaXQpO1xuICB9IHdoaWxlICh2bHEgPiAwKTtcblxuICByZXR1cm4gZW5jb2RlZDtcbn07XG5cbi8qKlxuICogRGVjb2RlcyB0aGUgbmV4dCBiYXNlIDY0IFZMUSB2YWx1ZSBmcm9tIHRoZSBnaXZlbiBzdHJpbmcgYW5kIHJldHVybnMgdGhlXG4gKiB2YWx1ZSBhbmQgdGhlIHJlc3Qgb2YgdGhlIHN0cmluZyB2aWEgdGhlIG91dCBwYXJhbWV0ZXIuXG4gKi9cbmV4cG9ydHMuZGVjb2RlID0gZnVuY3Rpb24gYmFzZTY0VkxRX2RlY29kZShhU3RyLCBhSW5kZXgsIGFPdXRQYXJhbSkge1xuICB2YXIgc3RyTGVuID0gYVN0ci5sZW5ndGg7XG4gIHZhciByZXN1bHQgPSAwO1xuICB2YXIgc2hpZnQgPSAwO1xuICB2YXIgY29udGludWF0aW9uLCBkaWdpdDtcblxuICBkbyB7XG4gICAgaWYgKGFJbmRleCA+PSBzdHJMZW4pIHtcbiAgICAgIHRocm93IG5ldyBFcnJvcihcIkV4cGVjdGVkIG1vcmUgZGlnaXRzIGluIGJhc2UgNjQgVkxRIHZhbHVlLlwiKTtcbiAgICB9XG5cbiAgICBkaWdpdCA9IGJhc2U2NC5kZWNvZGUoYVN0ci5jaGFyQ29kZUF0KGFJbmRleCsrKSk7XG4gICAgaWYgKGRpZ2l0ID09PSAtMSkge1xuICAgICAgdGhyb3cgbmV3IEVycm9yKFwiSW52YWxpZCBiYXNlNjQgZGlnaXQ6IFwiICsgYVN0ci5jaGFyQXQoYUluZGV4IC0gMSkpO1xuICAgIH1cblxuICAgIGNvbnRpbnVhdGlvbiA9ICEhKGRpZ2l0ICYgVkxRX0NPTlRJTlVBVElPTl9CSVQpO1xuICAgIGRpZ2l0ICY9IFZMUV9CQVNFX01BU0s7XG4gICAgcmVzdWx0ID0gcmVzdWx0ICsgKGRpZ2l0IDw8IHNoaWZ0KTtcbiAgICBzaGlmdCArPSBWTFFfQkFTRV9TSElGVDtcbiAgfSB3aGlsZSAoY29udGludWF0aW9uKTtcblxuICBhT3V0UGFyYW0udmFsdWUgPSBmcm9tVkxRU2lnbmVkKHJlc3VsdCk7XG4gIGFPdXRQYXJhbS5yZXN0ID0gYUluZGV4O1xufTtcblxuXG5cbi8vLy8vLy8vLy8vLy8vLy8vL1xuLy8gV0VCUEFDSyBGT09URVJcbi8vIC4vbGliL2Jhc2U2NC12bHEuanNcbi8vIG1vZHVsZSBpZCA9IDJcbi8vIG1vZHVsZSBjaHVua3MgPSAwIiwiLyogLSotIE1vZGU6IGpzOyBqcy1pbmRlbnQtbGV2ZWw6IDI7IC0qLSAqL1xuLypcbiAqIENvcHlyaWdodCAyMDExIE1vemlsbGEgRm91bmRhdGlvbiBhbmQgY29udHJpYnV0b3JzXG4gKiBMaWNlbnNlZCB1bmRlciB0aGUgTmV3IEJTRCBsaWNlbnNlLiBTZWUgTElDRU5TRSBvcjpcbiAqIGh0dHA6Ly9vcGVuc291cmNlLm9yZy9saWNlbnNlcy9CU0QtMy1DbGF1c2VcbiAqL1xuXG52YXIgaW50VG9DaGFyTWFwID0gJ0FCQ0RFRkdISUpLTE1OT1BRUlNUVVZXWFlaYWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXowMTIzNDU2Nzg5Ky8nLnNwbGl0KCcnKTtcblxuLyoqXG4gKiBFbmNvZGUgYW4gaW50ZWdlciBpbiB0aGUgcmFuZ2Ugb2YgMCB0byA2MyB0byBhIHNpbmdsZSBiYXNlIDY0IGRpZ2l0LlxuICovXG5leHBvcnRzLmVuY29kZSA9IGZ1bmN0aW9uIChudW1iZXIpIHtcbiAgaWYgKDAgPD0gbnVtYmVyICYmIG51bWJlciA8IGludFRvQ2hhck1hcC5sZW5ndGgpIHtcbiAgICByZXR1cm4gaW50VG9DaGFyTWFwW251bWJlcl07XG4gIH1cbiAgdGhyb3cgbmV3IFR5cGVFcnJvcihcIk11c3QgYmUgYmV0d2VlbiAwIGFuZCA2MzogXCIgKyBudW1iZXIpO1xufTtcblxuLyoqXG4gKiBEZWNvZGUgYSBzaW5nbGUgYmFzZSA2NCBjaGFyYWN0ZXIgY29kZSBkaWdpdCB0byBhbiBpbnRlZ2VyLiBSZXR1cm5zIC0xIG9uXG4gKiBmYWlsdXJlLlxuICovXG5leHBvcnRzLmRlY29kZSA9IGZ1bmN0aW9uIChjaGFyQ29kZSkge1xuICB2YXIgYmlnQSA9IDY1OyAgICAgLy8gJ0EnXG4gIHZhciBiaWdaID0gOTA7ICAgICAvLyAnWidcblxuICB2YXIgbGl0dGxlQSA9IDk3OyAgLy8gJ2EnXG4gIHZhciBsaXR0bGVaID0gMTIyOyAvLyAneidcblxuICB2YXIgemVybyA9IDQ4OyAgICAgLy8gJzAnXG4gIHZhciBuaW5lID0gNTc7ICAgICAvLyAnOSdcblxuICB2YXIgcGx1cyA9IDQzOyAgICAgLy8gJysnXG4gIHZhciBzbGFzaCA9IDQ3OyAgICAvLyAnLydcblxuICB2YXIgbGl0dGxlT2Zmc2V0ID0gMjY7XG4gIHZhciBudW1iZXJPZmZzZXQgPSA1MjtcblxuICAvLyAwIC0gMjU6IEFCQ0RFRkdISUpLTE1OT1BRUlNUVVZXWFlaXG4gIGlmIChiaWdBIDw9IGNoYXJDb2RlICYmIGNoYXJDb2RlIDw9IGJpZ1opIHtcbiAgICByZXR1cm4gKGNoYXJDb2RlIC0gYmlnQSk7XG4gIH1cblxuICAvLyAyNiAtIDUxOiBhYmNkZWZnaGlqa2xtbm9wcXJzdHV2d3h5elxuICBpZiAobGl0dGxlQSA8PSBjaGFyQ29kZSAmJiBjaGFyQ29kZSA8PSBsaXR0bGVaKSB7XG4gICAgcmV0dXJuIChjaGFyQ29kZSAtIGxpdHRsZUEgKyBsaXR0bGVPZmZzZXQpO1xuICB9XG5cbiAgLy8gNTIgLSA2MTogMDEyMzQ1Njc4OVxuICBpZiAoemVybyA8PSBjaGFyQ29kZSAmJiBjaGFyQ29kZSA8PSBuaW5lKSB7XG4gICAgcmV0dXJuIChjaGFyQ29kZSAtIHplcm8gKyBudW1iZXJPZmZzZXQpO1xuICB9XG5cbiAgLy8gNjI6ICtcbiAgaWYgKGNoYXJDb2RlID09IHBsdXMpIHtcbiAgICByZXR1cm4gNjI7XG4gIH1cblxuICAvLyA2MzogL1xuICBpZiAoY2hhckNvZGUgPT0gc2xhc2gpIHtcbiAgICByZXR1cm4gNjM7XG4gIH1cblxuICAvLyBJbnZhbGlkIGJhc2U2NCBkaWdpdC5cbiAgcmV0dXJuIC0xO1xufTtcblxuXG5cbi8vLy8vLy8vLy8vLy8vLy8vL1xuLy8gV0VCUEFDSyBGT09URVJcbi8vIC4vbGliL2Jhc2U2NC5qc1xuLy8gbW9kdWxlIGlkID0gM1xuLy8gbW9kdWxlIGNodW5rcyA9IDAiLCIvKiAtKi0gTW9kZToganM7IGpzLWluZGVudC1sZXZlbDogMjsgLSotICovXG4vKlxuICogQ29weXJpZ2h0IDIwMTEgTW96aWxsYSBGb3VuZGF0aW9uIGFuZCBjb250cmlidXRvcnNcbiAqIExpY2Vuc2VkIHVuZGVyIHRoZSBOZXcgQlNEIGxpY2Vuc2UuIFNlZSBMSUNFTlNFIG9yOlxuICogaHR0cDovL29wZW5zb3VyY2Uub3JnL2xpY2Vuc2VzL0JTRC0zLUNsYXVzZVxuICovXG5cbi8qKlxuICogVGhpcyBpcyBhIGhlbHBlciBmdW5jdGlvbiBmb3IgZ2V0dGluZyB2YWx1ZXMgZnJvbSBwYXJhbWV0ZXIvb3B0aW9uc1xuICogb2JqZWN0cy5cbiAqXG4gKiBAcGFyYW0gYXJncyBUaGUgb2JqZWN0IHdlIGFyZSBleHRyYWN0aW5nIHZhbHVlcyBmcm9tXG4gKiBAcGFyYW0gbmFtZSBUaGUgbmFtZSBvZiB0aGUgcHJvcGVydHkgd2UgYXJlIGdldHRpbmcuXG4gKiBAcGFyYW0gZGVmYXVsdFZhbHVlIEFuIG9wdGlvbmFsIHZhbHVlIHRvIHJldHVybiBpZiB0aGUgcHJvcGVydHkgaXMgbWlzc2luZ1xuICogZnJvbSB0aGUgb2JqZWN0LiBJZiB0aGlzIGlzIG5vdCBzcGVjaWZpZWQgYW5kIHRoZSBwcm9wZXJ0eSBpcyBtaXNzaW5nLCBhblxuICogZXJyb3Igd2lsbCBiZSB0aHJvd24uXG4gKi9cbmZ1bmN0aW9uIGdldEFyZyhhQXJncywgYU5hbWUsIGFEZWZhdWx0VmFsdWUpIHtcbiAgaWYgKGFOYW1lIGluIGFBcmdzKSB7XG4gICAgcmV0dXJuIGFBcmdzW2FOYW1lXTtcbiAgfSBlbHNlIGlmIChhcmd1bWVudHMubGVuZ3RoID09PSAzKSB7XG4gICAgcmV0dXJuIGFEZWZhdWx0VmFsdWU7XG4gIH0gZWxzZSB7XG4gICAgdGhyb3cgbmV3IEVycm9yKCdcIicgKyBhTmFtZSArICdcIiBpcyBhIHJlcXVpcmVkIGFyZ3VtZW50LicpO1xuICB9XG59XG5leHBvcnRzLmdldEFyZyA9IGdldEFyZztcblxudmFyIHVybFJlZ2V4cCA9IC9eKD86KFtcXHcrXFwtLl0rKTopP1xcL1xcLyg/OihcXHcrOlxcdyspQCk/KFtcXHcuLV0qKSg/OjooXFxkKykpPyguKikkLztcbnZhciBkYXRhVXJsUmVnZXhwID0gL15kYXRhOi4rXFwsLiskLztcblxuZnVuY3Rpb24gdXJsUGFyc2UoYVVybCkge1xuICB2YXIgbWF0Y2ggPSBhVXJsLm1hdGNoKHVybFJlZ2V4cCk7XG4gIGlmICghbWF0Y2gpIHtcbiAgICByZXR1cm4gbnVsbDtcbiAgfVxuICByZXR1cm4ge1xuICAgIHNjaGVtZTogbWF0Y2hbMV0sXG4gICAgYXV0aDogbWF0Y2hbMl0sXG4gICAgaG9zdDogbWF0Y2hbM10sXG4gICAgcG9ydDogbWF0Y2hbNF0sXG4gICAgcGF0aDogbWF0Y2hbNV1cbiAgfTtcbn1cbmV4cG9ydHMudXJsUGFyc2UgPSB1cmxQYXJzZTtcblxuZnVuY3Rpb24gdXJsR2VuZXJhdGUoYVBhcnNlZFVybCkge1xuICB2YXIgdXJsID0gJyc7XG4gIGlmIChhUGFyc2VkVXJsLnNjaGVtZSkge1xuICAgIHVybCArPSBhUGFyc2VkVXJsLnNjaGVtZSArICc6JztcbiAgfVxuICB1cmwgKz0gJy8vJztcbiAgaWYgKGFQYXJzZWRVcmwuYXV0aCkge1xuICAgIHVybCArPSBhUGFyc2VkVXJsLmF1dGggKyAnQCc7XG4gIH1cbiAgaWYgKGFQYXJzZWRVcmwuaG9zdCkge1xuICAgIHVybCArPSBhUGFyc2VkVXJsLmhvc3Q7XG4gIH1cbiAgaWYgKGFQYXJzZWRVcmwucG9ydCkge1xuICAgIHVybCArPSBcIjpcIiArIGFQYXJzZWRVcmwucG9ydFxuICB9XG4gIGlmIChhUGFyc2VkVXJsLnBhdGgpIHtcbiAgICB1cmwgKz0gYVBhcnNlZFVybC5wYXRoO1xuICB9XG4gIHJldHVybiB1cmw7XG59XG5leHBvcnRzLnVybEdlbmVyYXRlID0gdXJsR2VuZXJhdGU7XG5cbi8qKlxuICogTm9ybWFsaXplcyBhIHBhdGgsIG9yIHRoZSBwYXRoIHBvcnRpb24gb2YgYSBVUkw6XG4gKlxuICogLSBSZXBsYWNlcyBjb25zZWN1dGl2ZSBzbGFzaGVzIHdpdGggb25lIHNsYXNoLlxuICogLSBSZW1vdmVzIHVubmVjZXNzYXJ5ICcuJyBwYXJ0cy5cbiAqIC0gUmVtb3ZlcyB1bm5lY2Vzc2FyeSAnPGRpcj4vLi4nIHBhcnRzLlxuICpcbiAqIEJhc2VkIG9uIGNvZGUgaW4gdGhlIE5vZGUuanMgJ3BhdGgnIGNvcmUgbW9kdWxlLlxuICpcbiAqIEBwYXJhbSBhUGF0aCBUaGUgcGF0aCBvciB1cmwgdG8gbm9ybWFsaXplLlxuICovXG5mdW5jdGlvbiBub3JtYWxpemUoYVBhdGgpIHtcbiAgdmFyIHBhdGggPSBhUGF0aDtcbiAgdmFyIHVybCA9IHVybFBhcnNlKGFQYXRoKTtcbiAgaWYgKHVybCkge1xuICAgIGlmICghdXJsLnBhdGgpIHtcbiAgICAgIHJldHVybiBhUGF0aDtcbiAgICB9XG4gICAgcGF0aCA9IHVybC5wYXRoO1xuICB9XG4gIHZhciBpc0Fic29sdXRlID0gZXhwb3J0cy5pc0Fic29sdXRlKHBhdGgpO1xuXG4gIHZhciBwYXJ0cyA9IHBhdGguc3BsaXQoL1xcLysvKTtcbiAgZm9yICh2YXIgcGFydCwgdXAgPSAwLCBpID0gcGFydHMubGVuZ3RoIC0gMTsgaSA+PSAwOyBpLS0pIHtcbiAgICBwYXJ0ID0gcGFydHNbaV07XG4gICAgaWYgKHBhcnQgPT09ICcuJykge1xuICAgICAgcGFydHMuc3BsaWNlKGksIDEpO1xuICAgIH0gZWxzZSBpZiAocGFydCA9PT0gJy4uJykge1xuICAgICAgdXArKztcbiAgICB9IGVsc2UgaWYgKHVwID4gMCkge1xuICAgICAgaWYgKHBhcnQgPT09ICcnKSB7XG4gICAgICAgIC8vIFRoZSBmaXJzdCBwYXJ0IGlzIGJsYW5rIGlmIHRoZSBwYXRoIGlzIGFic29sdXRlLiBUcnlpbmcgdG8gZ29cbiAgICAgICAgLy8gYWJvdmUgdGhlIHJvb3QgaXMgYSBuby1vcC4gVGhlcmVmb3JlIHdlIGNhbiByZW1vdmUgYWxsICcuLicgcGFydHNcbiAgICAgICAgLy8gZGlyZWN0bHkgYWZ0ZXIgdGhlIHJvb3QuXG4gICAgICAgIHBhcnRzLnNwbGljZShpICsgMSwgdXApO1xuICAgICAgICB1cCA9IDA7XG4gICAgICB9IGVsc2Uge1xuICAgICAgICBwYXJ0cy5zcGxpY2UoaSwgMik7XG4gICAgICAgIHVwLS07XG4gICAgICB9XG4gICAgfVxuICB9XG4gIHBhdGggPSBwYXJ0cy5qb2luKCcvJyk7XG5cbiAgaWYgKHBhdGggPT09ICcnKSB7XG4gICAgcGF0aCA9IGlzQWJzb2x1dGUgPyAnLycgOiAnLic7XG4gIH1cblxuICBpZiAodXJsKSB7XG4gICAgdXJsLnBhdGggPSBwYXRoO1xuICAgIHJldHVybiB1cmxHZW5lcmF0ZSh1cmwpO1xuICB9XG4gIHJldHVybiBwYXRoO1xufVxuZXhwb3J0cy5ub3JtYWxpemUgPSBub3JtYWxpemU7XG5cbi8qKlxuICogSm9pbnMgdHdvIHBhdGhzL1VSTHMuXG4gKlxuICogQHBhcmFtIGFSb290IFRoZSByb290IHBhdGggb3IgVVJMLlxuICogQHBhcmFtIGFQYXRoIFRoZSBwYXRoIG9yIFVSTCB0byBiZSBqb2luZWQgd2l0aCB0aGUgcm9vdC5cbiAqXG4gKiAtIElmIGFQYXRoIGlzIGEgVVJMIG9yIGEgZGF0YSBVUkksIGFQYXRoIGlzIHJldHVybmVkLCB1bmxlc3MgYVBhdGggaXMgYVxuICogICBzY2hlbWUtcmVsYXRpdmUgVVJMOiBUaGVuIHRoZSBzY2hlbWUgb2YgYVJvb3QsIGlmIGFueSwgaXMgcHJlcGVuZGVkXG4gKiAgIGZpcnN0LlxuICogLSBPdGhlcndpc2UgYVBhdGggaXMgYSBwYXRoLiBJZiBhUm9vdCBpcyBhIFVSTCwgdGhlbiBpdHMgcGF0aCBwb3J0aW9uXG4gKiAgIGlzIHVwZGF0ZWQgd2l0aCB0aGUgcmVzdWx0IGFuZCBhUm9vdCBpcyByZXR1cm5lZC4gT3RoZXJ3aXNlIHRoZSByZXN1bHRcbiAqICAgaXMgcmV0dXJuZWQuXG4gKiAgIC0gSWYgYVBhdGggaXMgYWJzb2x1dGUsIHRoZSByZXN1bHQgaXMgYVBhdGguXG4gKiAgIC0gT3RoZXJ3aXNlIHRoZSB0d28gcGF0aHMgYXJlIGpvaW5lZCB3aXRoIGEgc2xhc2guXG4gKiAtIEpvaW5pbmcgZm9yIGV4YW1wbGUgJ2h0dHA6Ly8nIGFuZCAnd3d3LmV4YW1wbGUuY29tJyBpcyBhbHNvIHN1cHBvcnRlZC5cbiAqL1xuZnVuY3Rpb24gam9pbihhUm9vdCwgYVBhdGgpIHtcbiAgaWYgKGFSb290ID09PSBcIlwiKSB7XG4gICAgYVJvb3QgPSBcIi5cIjtcbiAgfVxuICBpZiAoYVBhdGggPT09IFwiXCIpIHtcbiAgICBhUGF0aCA9IFwiLlwiO1xuICB9XG4gIHZhciBhUGF0aFVybCA9IHVybFBhcnNlKGFQYXRoKTtcbiAgdmFyIGFSb290VXJsID0gdXJsUGFyc2UoYVJvb3QpO1xuICBpZiAoYVJvb3RVcmwpIHtcbiAgICBhUm9vdCA9IGFSb290VXJsLnBhdGggfHwgJy8nO1xuICB9XG5cbiAgLy8gYGpvaW4oZm9vLCAnLy93d3cuZXhhbXBsZS5vcmcnKWBcbiAgaWYgKGFQYXRoVXJsICYmICFhUGF0aFVybC5zY2hlbWUpIHtcbiAgICBpZiAoYVJvb3RVcmwpIHtcbiAgICAgIGFQYXRoVXJsLnNjaGVtZSA9IGFSb290VXJsLnNjaGVtZTtcbiAgICB9XG4gICAgcmV0dXJuIHVybEdlbmVyYXRlKGFQYXRoVXJsKTtcbiAgfVxuXG4gIGlmIChhUGF0aFVybCB8fCBhUGF0aC5tYXRjaChkYXRhVXJsUmVnZXhwKSkge1xuICAgIHJldHVybiBhUGF0aDtcbiAgfVxuXG4gIC8vIGBqb2luKCdodHRwOi8vJywgJ3d3dy5leGFtcGxlLmNvbScpYFxuICBpZiAoYVJvb3RVcmwgJiYgIWFSb290VXJsLmhvc3QgJiYgIWFSb290VXJsLnBhdGgpIHtcbiAgICBhUm9vdFVybC5ob3N0ID0gYVBhdGg7XG4gICAgcmV0dXJuIHVybEdlbmVyYXRlKGFSb290VXJsKTtcbiAgfVxuXG4gIHZhciBqb2luZWQgPSBhUGF0aC5jaGFyQXQoMCkgPT09ICcvJ1xuICAgID8gYVBhdGhcbiAgICA6IG5vcm1hbGl6ZShhUm9vdC5yZXBsYWNlKC9cXC8rJC8sICcnKSArICcvJyArIGFQYXRoKTtcblxuICBpZiAoYVJvb3RVcmwpIHtcbiAgICBhUm9vdFVybC5wYXRoID0gam9pbmVkO1xuICAgIHJldHVybiB1cmxHZW5lcmF0ZShhUm9vdFVybCk7XG4gIH1cbiAgcmV0dXJuIGpvaW5lZDtcbn1cbmV4cG9ydHMuam9pbiA9IGpvaW47XG5cbmV4cG9ydHMuaXNBYnNvbHV0ZSA9IGZ1bmN0aW9uIChhUGF0aCkge1xuICByZXR1cm4gYVBhdGguY2hhckF0KDApID09PSAnLycgfHwgdXJsUmVnZXhwLnRlc3QoYVBhdGgpO1xufTtcblxuLyoqXG4gKiBNYWtlIGEgcGF0aCByZWxhdGl2ZSB0byBhIFVSTCBvciBhbm90aGVyIHBhdGguXG4gKlxuICogQHBhcmFtIGFSb290IFRoZSByb290IHBhdGggb3IgVVJMLlxuICogQHBhcmFtIGFQYXRoIFRoZSBwYXRoIG9yIFVSTCB0byBiZSBtYWRlIHJlbGF0aXZlIHRvIGFSb290LlxuICovXG5mdW5jdGlvbiByZWxhdGl2ZShhUm9vdCwgYVBhdGgpIHtcbiAgaWYgKGFSb290ID09PSBcIlwiKSB7XG4gICAgYVJvb3QgPSBcIi5cIjtcbiAgfVxuXG4gIGFSb290ID0gYVJvb3QucmVwbGFjZSgvXFwvJC8sICcnKTtcblxuICAvLyBJdCBpcyBwb3NzaWJsZSBmb3IgdGhlIHBhdGggdG8gYmUgYWJvdmUgdGhlIHJvb3QuIEluIHRoaXMgY2FzZSwgc2ltcGx5XG4gIC8vIGNoZWNraW5nIHdoZXRoZXIgdGhlIHJvb3QgaXMgYSBwcmVmaXggb2YgdGhlIHBhdGggd29uJ3Qgd29yay4gSW5zdGVhZCwgd2VcbiAgLy8gbmVlZCB0byByZW1vdmUgY29tcG9uZW50cyBmcm9tIHRoZSByb290IG9uZSBieSBvbmUsIHVudGlsIGVpdGhlciB3ZSBmaW5kXG4gIC8vIGEgcHJlZml4IHRoYXQgZml0cywgb3Igd2UgcnVuIG91dCBvZiBjb21wb25lbnRzIHRvIHJlbW92ZS5cbiAgdmFyIGxldmVsID0gMDtcbiAgd2hpbGUgKGFQYXRoLmluZGV4T2YoYVJvb3QgKyAnLycpICE9PSAwKSB7XG4gICAgdmFyIGluZGV4ID0gYVJvb3QubGFzdEluZGV4T2YoXCIvXCIpO1xuICAgIGlmIChpbmRleCA8IDApIHtcbiAgICAgIHJldHVybiBhUGF0aDtcbiAgICB9XG5cbiAgICAvLyBJZiB0aGUgb25seSBwYXJ0IG9mIHRoZSByb290IHRoYXQgaXMgbGVmdCBpcyB0aGUgc2NoZW1lIChpLmUuIGh0dHA6Ly8sXG4gICAgLy8gZmlsZTovLy8sIGV0Yy4pLCBvbmUgb3IgbW9yZSBzbGFzaGVzICgvKSwgb3Igc2ltcGx5IG5vdGhpbmcgYXQgYWxsLCB3ZVxuICAgIC8vIGhhdmUgZXhoYXVzdGVkIGFsbCBjb21wb25lbnRzLCBzbyB0aGUgcGF0aCBpcyBub3QgcmVsYXRpdmUgdG8gdGhlIHJvb3QuXG4gICAgYVJvb3QgPSBhUm9vdC5zbGljZSgwLCBpbmRleCk7XG4gICAgaWYgKGFSb290Lm1hdGNoKC9eKFteXFwvXSs6XFwvKT9cXC8qJC8pKSB7XG4gICAgICByZXR1cm4gYVBhdGg7XG4gICAgfVxuXG4gICAgKytsZXZlbDtcbiAgfVxuXG4gIC8vIE1ha2Ugc3VyZSB3ZSBhZGQgYSBcIi4uL1wiIGZvciBlYWNoIGNvbXBvbmVudCB3ZSByZW1vdmVkIGZyb20gdGhlIHJvb3QuXG4gIHJldHVybiBBcnJheShsZXZlbCArIDEpLmpvaW4oXCIuLi9cIikgKyBhUGF0aC5zdWJzdHIoYVJvb3QubGVuZ3RoICsgMSk7XG59XG5leHBvcnRzLnJlbGF0aXZlID0gcmVsYXRpdmU7XG5cbnZhciBzdXBwb3J0c051bGxQcm90byA9IChmdW5jdGlvbiAoKSB7XG4gIHZhciBvYmogPSBPYmplY3QuY3JlYXRlKG51bGwpO1xuICByZXR1cm4gISgnX19wcm90b19fJyBpbiBvYmopO1xufSgpKTtcblxuZnVuY3Rpb24gaWRlbnRpdHkgKHMpIHtcbiAgcmV0dXJuIHM7XG59XG5cbi8qKlxuICogQmVjYXVzZSBiZWhhdmlvciBnb2VzIHdhY2t5IHdoZW4geW91IHNldCBgX19wcm90b19fYCBvbiBvYmplY3RzLCB3ZVxuICogaGF2ZSB0byBwcmVmaXggYWxsIHRoZSBzdHJpbmdzIGluIG91ciBzZXQgd2l0aCBhbiBhcmJpdHJhcnkgY2hhcmFjdGVyLlxuICpcbiAqIFNlZSBodHRwczovL2dpdGh1Yi5jb20vbW96aWxsYS9zb3VyY2UtbWFwL3B1bGwvMzEgYW5kXG4gKiBodHRwczovL2dpdGh1Yi5jb20vbW96aWxsYS9zb3VyY2UtbWFwL2lzc3Vlcy8zMFxuICpcbiAqIEBwYXJhbSBTdHJpbmcgYVN0clxuICovXG5mdW5jdGlvbiB0b1NldFN0cmluZyhhU3RyKSB7XG4gIGlmIChpc1Byb3RvU3RyaW5nKGFTdHIpKSB7XG4gICAgcmV0dXJuICckJyArIGFTdHI7XG4gIH1cblxuICByZXR1cm4gYVN0cjtcbn1cbmV4cG9ydHMudG9TZXRTdHJpbmcgPSBzdXBwb3J0c051bGxQcm90byA/IGlkZW50aXR5IDogdG9TZXRTdHJpbmc7XG5cbmZ1bmN0aW9uIGZyb21TZXRTdHJpbmcoYVN0cikge1xuICBpZiAoaXNQcm90b1N0cmluZyhhU3RyKSkge1xuICAgIHJldHVybiBhU3RyLnNsaWNlKDEpO1xuICB9XG5cbiAgcmV0dXJuIGFTdHI7XG59XG5leHBvcnRzLmZyb21TZXRTdHJpbmcgPSBzdXBwb3J0c051bGxQcm90byA/IGlkZW50aXR5IDogZnJvbVNldFN0cmluZztcblxuZnVuY3Rpb24gaXNQcm90b1N0cmluZyhzKSB7XG4gIGlmICghcykge1xuICAgIHJldHVybiBmYWxzZTtcbiAgfVxuXG4gIHZhciBsZW5ndGggPSBzLmxlbmd0aDtcblxuICBpZiAobGVuZ3RoIDwgOSAvKiBcIl9fcHJvdG9fX1wiLmxlbmd0aCAqLykge1xuICAgIHJldHVybiBmYWxzZTtcbiAgfVxuXG4gIGlmIChzLmNoYXJDb2RlQXQobGVuZ3RoIC0gMSkgIT09IDk1ICAvKiAnXycgKi8gfHxcbiAgICAgIHMuY2hhckNvZGVBdChsZW5ndGggLSAyKSAhPT0gOTUgIC8qICdfJyAqLyB8fFxuICAgICAgcy5jaGFyQ29kZUF0KGxlbmd0aCAtIDMpICE9PSAxMTEgLyogJ28nICovIHx8XG4gICAgICBzLmNoYXJDb2RlQXQobGVuZ3RoIC0gNCkgIT09IDExNiAvKiAndCcgKi8gfHxcbiAgICAgIHMuY2hhckNvZGVBdChsZW5ndGggLSA1KSAhPT0gMTExIC8qICdvJyAqLyB8fFxuICAgICAgcy5jaGFyQ29kZUF0KGxlbmd0aCAtIDYpICE9PSAxMTQgLyogJ3InICovIHx8XG4gICAgICBzLmNoYXJDb2RlQXQobGVuZ3RoIC0gNykgIT09IDExMiAvKiAncCcgKi8gfHxcbiAgICAgIHMuY2hhckNvZGVBdChsZW5ndGggLSA4KSAhPT0gOTUgIC8qICdfJyAqLyB8fFxuICAgICAgcy5jaGFyQ29kZUF0KGxlbmd0aCAtIDkpICE9PSA5NSAgLyogJ18nICovKSB7XG4gICAgcmV0dXJuIGZhbHNlO1xuICB9XG5cbiAgZm9yICh2YXIgaSA9IGxlbmd0aCAtIDEwOyBpID49IDA7IGktLSkge1xuICAgIGlmIChzLmNoYXJDb2RlQXQoaSkgIT09IDM2IC8qICckJyAqLykge1xuICAgICAgcmV0dXJuIGZhbHNlO1xuICAgIH1cbiAgfVxuXG4gIHJldHVybiB0cnVlO1xufVxuXG4vKipcbiAqIENvbXBhcmF0b3IgYmV0d2VlbiB0d28gbWFwcGluZ3Mgd2hlcmUgdGhlIG9yaWdpbmFsIHBvc2l0aW9ucyBhcmUgY29tcGFyZWQuXG4gKlxuICogT3B0aW9uYWxseSBwYXNzIGluIGB0cnVlYCBhcyBgb25seUNvbXBhcmVHZW5lcmF0ZWRgIHRvIGNvbnNpZGVyIHR3b1xuICogbWFwcGluZ3Mgd2l0aCB0aGUgc2FtZSBvcmlnaW5hbCBzb3VyY2UvbGluZS9jb2x1bW4sIGJ1dCBkaWZmZXJlbnQgZ2VuZXJhdGVkXG4gKiBsaW5lIGFuZCBjb2x1bW4gdGhlIHNhbWUuIFVzZWZ1bCB3aGVuIHNlYXJjaGluZyBmb3IgYSBtYXBwaW5nIHdpdGggYVxuICogc3R1YmJlZCBvdXQgbWFwcGluZy5cbiAqL1xuZnVuY3Rpb24gY29tcGFyZUJ5T3JpZ2luYWxQb3NpdGlvbnMobWFwcGluZ0EsIG1hcHBpbmdCLCBvbmx5Q29tcGFyZU9yaWdpbmFsKSB7XG4gIHZhciBjbXAgPSBzdHJjbXAobWFwcGluZ0Euc291cmNlLCBtYXBwaW5nQi5zb3VyY2UpO1xuICBpZiAoY21wICE9PSAwKSB7XG4gICAgcmV0dXJuIGNtcDtcbiAgfVxuXG4gIGNtcCA9IG1hcHBpbmdBLm9yaWdpbmFsTGluZSAtIG1hcHBpbmdCLm9yaWdpbmFsTGluZTtcbiAgaWYgKGNtcCAhPT0gMCkge1xuICAgIHJldHVybiBjbXA7XG4gIH1cblxuICBjbXAgPSBtYXBwaW5nQS5vcmlnaW5hbENvbHVtbiAtIG1hcHBpbmdCLm9yaWdpbmFsQ29sdW1uO1xuICBpZiAoY21wICE9PSAwIHx8IG9ubHlDb21wYXJlT3JpZ2luYWwpIHtcbiAgICByZXR1cm4gY21wO1xuICB9XG5cbiAgY21wID0gbWFwcGluZ0EuZ2VuZXJhdGVkQ29sdW1uIC0gbWFwcGluZ0IuZ2VuZXJhdGVkQ29sdW1uO1xuICBpZiAoY21wICE9PSAwKSB7XG4gICAgcmV0dXJuIGNtcDtcbiAgfVxuXG4gIGNtcCA9IG1hcHBpbmdBLmdlbmVyYXRlZExpbmUgLSBtYXBwaW5nQi5nZW5lcmF0ZWRMaW5lO1xuICBpZiAoY21wICE9PSAwKSB7XG4gICAgcmV0dXJuIGNtcDtcbiAgfVxuXG4gIHJldHVybiBzdHJjbXAobWFwcGluZ0EubmFtZSwgbWFwcGluZ0IubmFtZSk7XG59XG5leHBvcnRzLmNvbXBhcmVCeU9yaWdpbmFsUG9zaXRpb25zID0gY29tcGFyZUJ5T3JpZ2luYWxQb3NpdGlvbnM7XG5cbi8qKlxuICogQ29tcGFyYXRvciBiZXR3ZWVuIHR3byBtYXBwaW5ncyB3aXRoIGRlZmxhdGVkIHNvdXJjZSBhbmQgbmFtZSBpbmRpY2VzIHdoZXJlXG4gKiB0aGUgZ2VuZXJhdGVkIHBvc2l0aW9ucyBhcmUgY29tcGFyZWQuXG4gKlxuICogT3B0aW9uYWxseSBwYXNzIGluIGB0cnVlYCBhcyBgb25seUNvbXBhcmVHZW5lcmF0ZWRgIHRvIGNvbnNpZGVyIHR3b1xuICogbWFwcGluZ3Mgd2l0aCB0aGUgc2FtZSBnZW5lcmF0ZWQgbGluZSBhbmQgY29sdW1uLCBidXQgZGlmZmVyZW50XG4gKiBzb3VyY2UvbmFtZS9vcmlnaW5hbCBsaW5lIGFuZCBjb2x1bW4gdGhlIHNhbWUuIFVzZWZ1bCB3aGVuIHNlYXJjaGluZyBmb3IgYVxuICogbWFwcGluZyB3aXRoIGEgc3R1YmJlZCBvdXQgbWFwcGluZy5cbiAqL1xuZnVuY3Rpb24gY29tcGFyZUJ5R2VuZXJhdGVkUG9zaXRpb25zRGVmbGF0ZWQobWFwcGluZ0EsIG1hcHBpbmdCLCBvbmx5Q29tcGFyZUdlbmVyYXRlZCkge1xuICB2YXIgY21wID0gbWFwcGluZ0EuZ2VuZXJhdGVkTGluZSAtIG1hcHBpbmdCLmdlbmVyYXRlZExpbmU7XG4gIGlmIChjbXAgIT09IDApIHtcbiAgICByZXR1cm4gY21wO1xuICB9XG5cbiAgY21wID0gbWFwcGluZ0EuZ2VuZXJhdGVkQ29sdW1uIC0gbWFwcGluZ0IuZ2VuZXJhdGVkQ29sdW1uO1xuICBpZiAoY21wICE9PSAwIHx8IG9ubHlDb21wYXJlR2VuZXJhdGVkKSB7XG4gICAgcmV0dXJuIGNtcDtcbiAgfVxuXG4gIGNtcCA9IHN0cmNtcChtYXBwaW5nQS5zb3VyY2UsIG1hcHBpbmdCLnNvdXJjZSk7XG4gIGlmIChjbXAgIT09IDApIHtcbiAgICByZXR1cm4gY21wO1xuICB9XG5cbiAgY21wID0gbWFwcGluZ0Eub3JpZ2luYWxMaW5lIC0gbWFwcGluZ0Iub3JpZ2luYWxMaW5lO1xuICBpZiAoY21wICE9PSAwKSB7XG4gICAgcmV0dXJuIGNtcDtcbiAgfVxuXG4gIGNtcCA9IG1hcHBpbmdBLm9yaWdpbmFsQ29sdW1uIC0gbWFwcGluZ0Iub3JpZ2luYWxDb2x1bW47XG4gIGlmIChjbXAgIT09IDApIHtcbiAgICByZXR1cm4gY21wO1xuICB9XG5cbiAgcmV0dXJuIHN0cmNtcChtYXBwaW5nQS5uYW1lLCBtYXBwaW5nQi5uYW1lKTtcbn1cbmV4cG9ydHMuY29tcGFyZUJ5R2VuZXJhdGVkUG9zaXRpb25zRGVmbGF0ZWQgPSBjb21wYXJlQnlHZW5lcmF0ZWRQb3NpdGlvbnNEZWZsYXRlZDtcblxuZnVuY3Rpb24gc3RyY21wKGFTdHIxLCBhU3RyMikge1xuICBpZiAoYVN0cjEgPT09IGFTdHIyKSB7XG4gICAgcmV0dXJuIDA7XG4gIH1cblxuICBpZiAoYVN0cjEgPT09IG51bGwpIHtcbiAgICByZXR1cm4gMTsgLy8gYVN0cjIgIT09IG51bGxcbiAgfVxuXG4gIGlmIChhU3RyMiA9PT0gbnVsbCkge1xuICAgIHJldHVybiAtMTsgLy8gYVN0cjEgIT09IG51bGxcbiAgfVxuXG4gIGlmIChhU3RyMSA+IGFTdHIyKSB7XG4gICAgcmV0dXJuIDE7XG4gIH1cblxuICByZXR1cm4gLTE7XG59XG5cbi8qKlxuICogQ29tcGFyYXRvciBiZXR3ZWVuIHR3byBtYXBwaW5ncyB3aXRoIGluZmxhdGVkIHNvdXJjZSBhbmQgbmFtZSBzdHJpbmdzIHdoZXJlXG4gKiB0aGUgZ2VuZXJhdGVkIHBvc2l0aW9ucyBhcmUgY29tcGFyZWQuXG4gKi9cbmZ1bmN0aW9uIGNvbXBhcmVCeUdlbmVyYXRlZFBvc2l0aW9uc0luZmxhdGVkKG1hcHBpbmdBLCBtYXBwaW5nQikge1xuICB2YXIgY21wID0gbWFwcGluZ0EuZ2VuZXJhdGVkTGluZSAtIG1hcHBpbmdCLmdlbmVyYXRlZExpbmU7XG4gIGlmIChjbXAgIT09IDApIHtcbiAgICByZXR1cm4gY21wO1xuICB9XG5cbiAgY21wID0gbWFwcGluZ0EuZ2VuZXJhdGVkQ29sdW1uIC0gbWFwcGluZ0IuZ2VuZXJhdGVkQ29sdW1uO1xuICBpZiAoY21wICE9PSAwKSB7XG4gICAgcmV0dXJuIGNtcDtcbiAgfVxuXG4gIGNtcCA9IHN0cmNtcChtYXBwaW5nQS5zb3VyY2UsIG1hcHBpbmdCLnNvdXJjZSk7XG4gIGlmIChjbXAgIT09IDApIHtcbiAgICByZXR1cm4gY21wO1xuICB9XG5cbiAgY21wID0gbWFwcGluZ0Eub3JpZ2luYWxMaW5lIC0gbWFwcGluZ0Iub3JpZ2luYWxMaW5lO1xuICBpZiAoY21wICE9PSAwKSB7XG4gICAgcmV0dXJuIGNtcDtcbiAgfVxuXG4gIGNtcCA9IG1hcHBpbmdBLm9yaWdpbmFsQ29sdW1uIC0gbWFwcGluZ0Iub3JpZ2luYWxDb2x1bW47XG4gIGlmIChjbXAgIT09IDApIHtcbiAgICByZXR1cm4gY21wO1xuICB9XG5cbiAgcmV0dXJuIHN0cmNtcChtYXBwaW5nQS5uYW1lLCBtYXBwaW5nQi5uYW1lKTtcbn1cbmV4cG9ydHMuY29tcGFyZUJ5R2VuZXJhdGVkUG9zaXRpb25zSW5mbGF0ZWQgPSBjb21wYXJlQnlHZW5lcmF0ZWRQb3NpdGlvbnNJbmZsYXRlZDtcblxuLyoqXG4gKiBTdHJpcCBhbnkgSlNPTiBYU1NJIGF2b2lkYW5jZSBwcmVmaXggZnJvbSB0aGUgc3RyaW5nIChhcyBkb2N1bWVudGVkXG4gKiBpbiB0aGUgc291cmNlIG1hcHMgc3BlY2lmaWNhdGlvbiksIGFuZCB0aGVuIHBhcnNlIHRoZSBzdHJpbmcgYXNcbiAqIEpTT04uXG4gKi9cbmZ1bmN0aW9uIHBhcnNlU291cmNlTWFwSW5wdXQoc3RyKSB7XG4gIHJldHVybiBKU09OLnBhcnNlKHN0ci5yZXBsYWNlKC9eXFwpXX0nW15cXG5dKlxcbi8sICcnKSk7XG59XG5leHBvcnRzLnBhcnNlU291cmNlTWFwSW5wdXQgPSBwYXJzZVNvdXJjZU1hcElucHV0O1xuXG4vKipcbiAqIENvbXB1dGUgdGhlIFVSTCBvZiBhIHNvdXJjZSBnaXZlbiB0aGUgdGhlIHNvdXJjZSByb290LCB0aGUgc291cmNlJ3NcbiAqIFVSTCwgYW5kIHRoZSBzb3VyY2UgbWFwJ3MgVVJMLlxuICovXG5mdW5jdGlvbiBjb21wdXRlU291cmNlVVJMKHNvdXJjZVJvb3QsIHNvdXJjZVVSTCwgc291cmNlTWFwVVJMKSB7XG4gIHNvdXJjZVVSTCA9IHNvdXJjZVVSTCB8fCAnJztcblxuICBpZiAoc291cmNlUm9vdCkge1xuICAgIC8vIFRoaXMgZm9sbG93cyB3aGF0IENocm9tZSBkb2VzLlxuICAgIGlmIChzb3VyY2VSb290W3NvdXJjZVJvb3QubGVuZ3RoIC0gMV0gIT09ICcvJyAmJiBzb3VyY2VVUkxbMF0gIT09ICcvJykge1xuICAgICAgc291cmNlUm9vdCArPSAnLyc7XG4gICAgfVxuICAgIC8vIFRoZSBzcGVjIHNheXM6XG4gICAgLy8gICBMaW5lIDQ6IEFuIG9wdGlvbmFsIHNvdXJjZSByb290LCB1c2VmdWwgZm9yIHJlbG9jYXRpbmcgc291cmNlXG4gICAgLy8gICBmaWxlcyBvbiBhIHNlcnZlciBvciByZW1vdmluZyByZXBlYXRlZCB2YWx1ZXMgaW4gdGhlXG4gICAgLy8gICDigJxzb3VyY2Vz4oCdIGVudHJ5LiAgVGhpcyB2YWx1ZSBpcyBwcmVwZW5kZWQgdG8gdGhlIGluZGl2aWR1YWxcbiAgICAvLyAgIGVudHJpZXMgaW4gdGhlIOKAnHNvdXJjZeKAnSBmaWVsZC5cbiAgICBzb3VyY2VVUkwgPSBzb3VyY2VSb290ICsgc291cmNlVVJMO1xuICB9XG5cbiAgLy8gSGlzdG9yaWNhbGx5LCBTb3VyY2VNYXBDb25zdW1lciBkaWQgbm90IHRha2UgdGhlIHNvdXJjZU1hcFVSTCBhc1xuICAvLyBhIHBhcmFtZXRlci4gIFRoaXMgbW9kZSBpcyBzdGlsbCBzb21ld2hhdCBzdXBwb3J0ZWQsIHdoaWNoIGlzIHdoeVxuICAvLyB0aGlzIGNvZGUgYmxvY2sgaXMgY29uZGl0aW9uYWwuICBIb3dldmVyLCBpdCdzIHByZWZlcmFibGUgdG8gcGFzc1xuICAvLyB0aGUgc291cmNlIG1hcCBVUkwgdG8gU291cmNlTWFwQ29uc3VtZXIsIHNvIHRoYXQgdGhpcyBmdW5jdGlvblxuICAvLyBjYW4gaW1wbGVtZW50IHRoZSBzb3VyY2UgVVJMIHJlc29sdXRpb24gYWxnb3JpdGhtIGFzIG91dGxpbmVkIGluXG4gIC8vIHRoZSBzcGVjLiAgVGhpcyBibG9jayBpcyBiYXNpY2FsbHkgdGhlIGVxdWl2YWxlbnQgb2Y6XG4gIC8vICAgIG5ldyBVUkwoc291cmNlVVJMLCBzb3VyY2VNYXBVUkwpLnRvU3RyaW5nKClcbiAgLy8gLi4uIGV4Y2VwdCBpdCBhdm9pZHMgdXNpbmcgVVJMLCB3aGljaCB3YXNuJ3QgYXZhaWxhYmxlIGluIHRoZVxuICAvLyBvbGRlciByZWxlYXNlcyBvZiBub2RlIHN0aWxsIHN1cHBvcnRlZCBieSB0aGlzIGxpYnJhcnkuXG4gIC8vXG4gIC8vIFRoZSBzcGVjIHNheXM6XG4gIC8vICAgSWYgdGhlIHNvdXJjZXMgYXJlIG5vdCBhYnNvbHV0ZSBVUkxzIGFmdGVyIHByZXBlbmRpbmcgb2YgdGhlXG4gIC8vICAg4oCcc291cmNlUm9vdOKAnSwgdGhlIHNvdXJjZXMgYXJlIHJlc29sdmVkIHJlbGF0aXZlIHRvIHRoZVxuICAvLyAgIFNvdXJjZU1hcCAobGlrZSByZXNvbHZpbmcgc2NyaXB0IHNyYyBpbiBhIGh0bWwgZG9jdW1lbnQpLlxuICBpZiAoc291cmNlTWFwVVJMKSB7XG4gICAgdmFyIHBhcnNlZCA9IHVybFBhcnNlKHNvdXJjZU1hcFVSTCk7XG4gICAgaWYgKCFwYXJzZWQpIHtcbiAgICAgIHRocm93IG5ldyBFcnJvcihcInNvdXJjZU1hcFVSTCBjb3VsZCBub3QgYmUgcGFyc2VkXCIpO1xuICAgIH1cbiAgICBpZiAocGFyc2VkLnBhdGgpIHtcbiAgICAgIC8vIFN0cmlwIHRoZSBsYXN0IHBhdGggY29tcG9uZW50LCBidXQga2VlcCB0aGUgXCIvXCIuXG4gICAgICB2YXIgaW5kZXggPSBwYXJzZWQucGF0aC5sYXN0SW5kZXhPZignLycpO1xuICAgICAgaWYgKGluZGV4ID49IDApIHtcbiAgICAgICAgcGFyc2VkLnBhdGggPSBwYXJzZWQucGF0aC5zdWJzdHJpbmcoMCwgaW5kZXggKyAxKTtcbiAgICAgIH1cbiAgICB9XG4gICAgc291cmNlVVJMID0gam9pbih1cmxHZW5lcmF0ZShwYXJzZWQpLCBzb3VyY2VVUkwpO1xuICB9XG5cbiAgcmV0dXJuIG5vcm1hbGl6ZShzb3VyY2VVUkwpO1xufVxuZXhwb3J0cy5jb21wdXRlU291cmNlVVJMID0gY29tcHV0ZVNvdXJjZVVSTDtcblxuXG5cbi8vLy8vLy8vLy8vLy8vLy8vL1xuLy8gV0VCUEFDSyBGT09URVJcbi8vIC4vbGliL3V0aWwuanNcbi8vIG1vZHVsZSBpZCA9IDRcbi8vIG1vZHVsZSBjaHVua3MgPSAwIiwiLyogLSotIE1vZGU6IGpzOyBqcy1pbmRlbnQtbGV2ZWw6IDI7IC0qLSAqL1xuLypcbiAqIENvcHlyaWdodCAyMDExIE1vemlsbGEgRm91bmRhdGlvbiBhbmQgY29udHJpYnV0b3JzXG4gKiBMaWNlbnNlZCB1bmRlciB0aGUgTmV3IEJTRCBsaWNlbnNlLiBTZWUgTElDRU5TRSBvcjpcbiAqIGh0dHA6Ly9vcGVuc291cmNlLm9yZy9saWNlbnNlcy9CU0QtMy1DbGF1c2VcbiAqL1xuXG52YXIgdXRpbCA9IHJlcXVpcmUoJy4vdXRpbCcpO1xudmFyIGhhcyA9IE9iamVjdC5wcm90b3R5cGUuaGFzT3duUHJvcGVydHk7XG52YXIgaGFzTmF0aXZlTWFwID0gdHlwZW9mIE1hcCAhPT0gXCJ1bmRlZmluZWRcIjtcblxuLyoqXG4gKiBBIGRhdGEgc3RydWN0dXJlIHdoaWNoIGlzIGEgY29tYmluYXRpb24gb2YgYW4gYXJyYXkgYW5kIGEgc2V0LiBBZGRpbmcgYSBuZXdcbiAqIG1lbWJlciBpcyBPKDEpLCB0ZXN0aW5nIGZvciBtZW1iZXJzaGlwIGlzIE8oMSksIGFuZCBmaW5kaW5nIHRoZSBpbmRleCBvZiBhblxuICogZWxlbWVudCBpcyBPKDEpLiBSZW1vdmluZyBlbGVtZW50cyBmcm9tIHRoZSBzZXQgaXMgbm90IHN1cHBvcnRlZC4gT25seVxuICogc3RyaW5ncyBhcmUgc3VwcG9ydGVkIGZvciBtZW1iZXJzaGlwLlxuICovXG5mdW5jdGlvbiBBcnJheVNldCgpIHtcbiAgdGhpcy5fYXJyYXkgPSBbXTtcbiAgdGhpcy5fc2V0ID0gaGFzTmF0aXZlTWFwID8gbmV3IE1hcCgpIDogT2JqZWN0LmNyZWF0ZShudWxsKTtcbn1cblxuLyoqXG4gKiBTdGF0aWMgbWV0aG9kIGZvciBjcmVhdGluZyBBcnJheVNldCBpbnN0YW5jZXMgZnJvbSBhbiBleGlzdGluZyBhcnJheS5cbiAqL1xuQXJyYXlTZXQuZnJvbUFycmF5ID0gZnVuY3Rpb24gQXJyYXlTZXRfZnJvbUFycmF5KGFBcnJheSwgYUFsbG93RHVwbGljYXRlcykge1xuICB2YXIgc2V0ID0gbmV3IEFycmF5U2V0KCk7XG4gIGZvciAodmFyIGkgPSAwLCBsZW4gPSBhQXJyYXkubGVuZ3RoOyBpIDwgbGVuOyBpKyspIHtcbiAgICBzZXQuYWRkKGFBcnJheVtpXSwgYUFsbG93RHVwbGljYXRlcyk7XG4gIH1cbiAgcmV0dXJuIHNldDtcbn07XG5cbi8qKlxuICogUmV0dXJuIGhvdyBtYW55IHVuaXF1ZSBpdGVtcyBhcmUgaW4gdGhpcyBBcnJheVNldC4gSWYgZHVwbGljYXRlcyBoYXZlIGJlZW5cbiAqIGFkZGVkLCB0aGFuIHRob3NlIGRvIG5vdCBjb3VudCB0b3dhcmRzIHRoZSBzaXplLlxuICpcbiAqIEByZXR1cm5zIE51bWJlclxuICovXG5BcnJheVNldC5wcm90b3R5cGUuc2l6ZSA9IGZ1bmN0aW9uIEFycmF5U2V0X3NpemUoKSB7XG4gIHJldHVybiBoYXNOYXRpdmVNYXAgPyB0aGlzLl9zZXQuc2l6ZSA6IE9iamVjdC5nZXRPd25Qcm9wZXJ0eU5hbWVzKHRoaXMuX3NldCkubGVuZ3RoO1xufTtcblxuLyoqXG4gKiBBZGQgdGhlIGdpdmVuIHN0cmluZyB0byB0aGlzIHNldC5cbiAqXG4gKiBAcGFyYW0gU3RyaW5nIGFTdHJcbiAqL1xuQXJyYXlTZXQucHJvdG90eXBlLmFkZCA9IGZ1bmN0aW9uIEFycmF5U2V0X2FkZChhU3RyLCBhQWxsb3dEdXBsaWNhdGVzKSB7XG4gIHZhciBzU3RyID0gaGFzTmF0aXZlTWFwID8gYVN0ciA6IHV0aWwudG9TZXRTdHJpbmcoYVN0cik7XG4gIHZhciBpc0R1cGxpY2F0ZSA9IGhhc05hdGl2ZU1hcCA/IHRoaXMuaGFzKGFTdHIpIDogaGFzLmNhbGwodGhpcy5fc2V0LCBzU3RyKTtcbiAgdmFyIGlkeCA9IHRoaXMuX2FycmF5Lmxlbmd0aDtcbiAgaWYgKCFpc0R1cGxpY2F0ZSB8fCBhQWxsb3dEdXBsaWNhdGVzKSB7XG4gICAgdGhpcy5fYXJyYXkucHVzaChhU3RyKTtcbiAgfVxuICBpZiAoIWlzRHVwbGljYXRlKSB7XG4gICAgaWYgKGhhc05hdGl2ZU1hcCkge1xuICAgICAgdGhpcy5fc2V0LnNldChhU3RyLCBpZHgpO1xuICAgIH0gZWxzZSB7XG4gICAgICB0aGlzLl9zZXRbc1N0cl0gPSBpZHg7XG4gICAgfVxuICB9XG59O1xuXG4vKipcbiAqIElzIHRoZSBnaXZlbiBzdHJpbmcgYSBtZW1iZXIgb2YgdGhpcyBzZXQ/XG4gKlxuICogQHBhcmFtIFN0cmluZyBhU3RyXG4gKi9cbkFycmF5U2V0LnByb3RvdHlwZS5oYXMgPSBmdW5jdGlvbiBBcnJheVNldF9oYXMoYVN0cikge1xuICBpZiAoaGFzTmF0aXZlTWFwKSB7XG4gICAgcmV0dXJuIHRoaXMuX3NldC5oYXMoYVN0cik7XG4gIH0gZWxzZSB7XG4gICAgdmFyIHNTdHIgPSB1dGlsLnRvU2V0U3RyaW5nKGFTdHIpO1xuICAgIHJldHVybiBoYXMuY2FsbCh0aGlzLl9zZXQsIHNTdHIpO1xuICB9XG59O1xuXG4vKipcbiAqIFdoYXQgaXMgdGhlIGluZGV4IG9mIHRoZSBnaXZlbiBzdHJpbmcgaW4gdGhlIGFycmF5P1xuICpcbiAqIEBwYXJhbSBTdHJpbmcgYVN0clxuICovXG5BcnJheVNldC5wcm90b3R5cGUuaW5kZXhPZiA9IGZ1bmN0aW9uIEFycmF5U2V0X2luZGV4T2YoYVN0cikge1xuICBpZiAoaGFzTmF0aXZlTWFwKSB7XG4gICAgdmFyIGlkeCA9IHRoaXMuX3NldC5nZXQoYVN0cik7XG4gICAgaWYgKGlkeCA+PSAwKSB7XG4gICAgICAgIHJldHVybiBpZHg7XG4gICAgfVxuICB9IGVsc2Uge1xuICAgIHZhciBzU3RyID0gdXRpbC50b1NldFN0cmluZyhhU3RyKTtcbiAgICBpZiAoaGFzLmNhbGwodGhpcy5fc2V0LCBzU3RyKSkge1xuICAgICAgcmV0dXJuIHRoaXMuX3NldFtzU3RyXTtcbiAgICB9XG4gIH1cblxuICB0aHJvdyBuZXcgRXJyb3IoJ1wiJyArIGFTdHIgKyAnXCIgaXMgbm90IGluIHRoZSBzZXQuJyk7XG59O1xuXG4vKipcbiAqIFdoYXQgaXMgdGhlIGVsZW1lbnQgYXQgdGhlIGdpdmVuIGluZGV4P1xuICpcbiAqIEBwYXJhbSBOdW1iZXIgYUlkeFxuICovXG5BcnJheVNldC5wcm90b3R5cGUuYXQgPSBmdW5jdGlvbiBBcnJheVNldF9hdChhSWR4KSB7XG4gIGlmIChhSWR4ID49IDAgJiYgYUlkeCA8IHRoaXMuX2FycmF5Lmxlbmd0aCkge1xuICAgIHJldHVybiB0aGlzLl9hcnJheVthSWR4XTtcbiAgfVxuICB0aHJvdyBuZXcgRXJyb3IoJ05vIGVsZW1lbnQgaW5kZXhlZCBieSAnICsgYUlkeCk7XG59O1xuXG4vKipcbiAqIFJldHVybnMgdGhlIGFycmF5IHJlcHJlc2VudGF0aW9uIG9mIHRoaXMgc2V0ICh3aGljaCBoYXMgdGhlIHByb3BlciBpbmRpY2VzXG4gKiBpbmRpY2F0ZWQgYnkgaW5kZXhPZikuIE5vdGUgdGhhdCB0aGlzIGlzIGEgY29weSBvZiB0aGUgaW50ZXJuYWwgYXJyYXkgdXNlZFxuICogZm9yIHN0b3JpbmcgdGhlIG1lbWJlcnMgc28gdGhhdCBubyBvbmUgY2FuIG1lc3Mgd2l0aCBpbnRlcm5hbCBzdGF0ZS5cbiAqL1xuQXJyYXlTZXQucHJvdG90eXBlLnRvQXJyYXkgPSBmdW5jdGlvbiBBcnJheVNldF90b0FycmF5KCkge1xuICByZXR1cm4gdGhpcy5fYXJyYXkuc2xpY2UoKTtcbn07XG5cbmV4cG9ydHMuQXJyYXlTZXQgPSBBcnJheVNldDtcblxuXG5cbi8vLy8vLy8vLy8vLy8vLy8vL1xuLy8gV0VCUEFDSyBGT09URVJcbi8vIC4vbGliL2FycmF5LXNldC5qc1xuLy8gbW9kdWxlIGlkID0gNVxuLy8gbW9kdWxlIGNodW5rcyA9IDAiLCIvKiAtKi0gTW9kZToganM7IGpzLWluZGVudC1sZXZlbDogMjsgLSotICovXG4vKlxuICogQ29weXJpZ2h0IDIwMTQgTW96aWxsYSBGb3VuZGF0aW9uIGFuZCBjb250cmlidXRvcnNcbiAqIExpY2Vuc2VkIHVuZGVyIHRoZSBOZXcgQlNEIGxpY2Vuc2UuIFNlZSBMSUNFTlNFIG9yOlxuICogaHR0cDovL29wZW5zb3VyY2Uub3JnL2xpY2Vuc2VzL0JTRC0zLUNsYXVzZVxuICovXG5cbnZhciB1dGlsID0gcmVxdWlyZSgnLi91dGlsJyk7XG5cbi8qKlxuICogRGV0ZXJtaW5lIHdoZXRoZXIgbWFwcGluZ0IgaXMgYWZ0ZXIgbWFwcGluZ0Egd2l0aCByZXNwZWN0IHRvIGdlbmVyYXRlZFxuICogcG9zaXRpb24uXG4gKi9cbmZ1bmN0aW9uIGdlbmVyYXRlZFBvc2l0aW9uQWZ0ZXIobWFwcGluZ0EsIG1hcHBpbmdCKSB7XG4gIC8vIE9wdGltaXplZCBmb3IgbW9zdCBjb21tb24gY2FzZVxuICB2YXIgbGluZUEgPSBtYXBwaW5nQS5nZW5lcmF0ZWRMaW5lO1xuICB2YXIgbGluZUIgPSBtYXBwaW5nQi5nZW5lcmF0ZWRMaW5lO1xuICB2YXIgY29sdW1uQSA9IG1hcHBpbmdBLmdlbmVyYXRlZENvbHVtbjtcbiAgdmFyIGNvbHVtbkIgPSBtYXBwaW5nQi5nZW5lcmF0ZWRDb2x1bW47XG4gIHJldHVybiBsaW5lQiA+IGxpbmVBIHx8IGxpbmVCID09IGxpbmVBICYmIGNvbHVtbkIgPj0gY29sdW1uQSB8fFxuICAgICAgICAgdXRpbC5jb21wYXJlQnlHZW5lcmF0ZWRQb3NpdGlvbnNJbmZsYXRlZChtYXBwaW5nQSwgbWFwcGluZ0IpIDw9IDA7XG59XG5cbi8qKlxuICogQSBkYXRhIHN0cnVjdHVyZSB0byBwcm92aWRlIGEgc29ydGVkIHZpZXcgb2YgYWNjdW11bGF0ZWQgbWFwcGluZ3MgaW4gYVxuICogcGVyZm9ybWFuY2UgY29uc2Npb3VzIG1hbm5lci4gSXQgdHJhZGVzIGEgbmVnbGliYWJsZSBvdmVyaGVhZCBpbiBnZW5lcmFsXG4gKiBjYXNlIGZvciBhIGxhcmdlIHNwZWVkdXAgaW4gY2FzZSBvZiBtYXBwaW5ncyBiZWluZyBhZGRlZCBpbiBvcmRlci5cbiAqL1xuZnVuY3Rpb24gTWFwcGluZ0xpc3QoKSB7XG4gIHRoaXMuX2FycmF5ID0gW107XG4gIHRoaXMuX3NvcnRlZCA9IHRydWU7XG4gIC8vIFNlcnZlcyBhcyBpbmZpbXVtXG4gIHRoaXMuX2xhc3QgPSB7Z2VuZXJhdGVkTGluZTogLTEsIGdlbmVyYXRlZENvbHVtbjogMH07XG59XG5cbi8qKlxuICogSXRlcmF0ZSB0aHJvdWdoIGludGVybmFsIGl0ZW1zLiBUaGlzIG1ldGhvZCB0YWtlcyB0aGUgc2FtZSBhcmd1bWVudHMgdGhhdFxuICogYEFycmF5LnByb3RvdHlwZS5mb3JFYWNoYCB0YWtlcy5cbiAqXG4gKiBOT1RFOiBUaGUgb3JkZXIgb2YgdGhlIG1hcHBpbmdzIGlzIE5PVCBndWFyYW50ZWVkLlxuICovXG5NYXBwaW5nTGlzdC5wcm90b3R5cGUudW5zb3J0ZWRGb3JFYWNoID1cbiAgZnVuY3Rpb24gTWFwcGluZ0xpc3RfZm9yRWFjaChhQ2FsbGJhY2ssIGFUaGlzQXJnKSB7XG4gICAgdGhpcy5fYXJyYXkuZm9yRWFjaChhQ2FsbGJhY2ssIGFUaGlzQXJnKTtcbiAgfTtcblxuLyoqXG4gKiBBZGQgdGhlIGdpdmVuIHNvdXJjZSBtYXBwaW5nLlxuICpcbiAqIEBwYXJhbSBPYmplY3QgYU1hcHBpbmdcbiAqL1xuTWFwcGluZ0xpc3QucHJvdG90eXBlLmFkZCA9IGZ1bmN0aW9uIE1hcHBpbmdMaXN0X2FkZChhTWFwcGluZykge1xuICBpZiAoZ2VuZXJhdGVkUG9zaXRpb25BZnRlcih0aGlzLl9sYXN0LCBhTWFwcGluZykpIHtcbiAgICB0aGlzLl9sYXN0ID0gYU1hcHBpbmc7XG4gICAgdGhpcy5fYXJyYXkucHVzaChhTWFwcGluZyk7XG4gIH0gZWxzZSB7XG4gICAgdGhpcy5fc29ydGVkID0gZmFsc2U7XG4gICAgdGhpcy5fYXJyYXkucHVzaChhTWFwcGluZyk7XG4gIH1cbn07XG5cbi8qKlxuICogUmV0dXJucyB0aGUgZmxhdCwgc29ydGVkIGFycmF5IG9mIG1hcHBpbmdzLiBUaGUgbWFwcGluZ3MgYXJlIHNvcnRlZCBieVxuICogZ2VuZXJhdGVkIHBvc2l0aW9uLlxuICpcbiAqIFdBUk5JTkc6IFRoaXMgbWV0aG9kIHJldHVybnMgaW50ZXJuYWwgZGF0YSB3aXRob3V0IGNvcHlpbmcsIGZvclxuICogcGVyZm9ybWFuY2UuIFRoZSByZXR1cm4gdmFsdWUgbXVzdCBOT1QgYmUgbXV0YXRlZCwgYW5kIHNob3VsZCBiZSB0cmVhdGVkIGFzXG4gKiBhbiBpbW11dGFibGUgYm9ycm93LiBJZiB5b3Ugd2FudCB0byB0YWtlIG93bmVyc2hpcCwgeW91IG11c3QgbWFrZSB5b3VyIG93blxuICogY29weS5cbiAqL1xuTWFwcGluZ0xpc3QucHJvdG90eXBlLnRvQXJyYXkgPSBmdW5jdGlvbiBNYXBwaW5nTGlzdF90b0FycmF5KCkge1xuICBpZiAoIXRoaXMuX3NvcnRlZCkge1xuICAgIHRoaXMuX2FycmF5LnNvcnQodXRpbC5jb21wYXJlQnlHZW5lcmF0ZWRQb3NpdGlvbnNJbmZsYXRlZCk7XG4gICAgdGhpcy5fc29ydGVkID0gdHJ1ZTtcbiAgfVxuICByZXR1cm4gdGhpcy5fYXJyYXk7XG59O1xuXG5leHBvcnRzLk1hcHBpbmdMaXN0ID0gTWFwcGluZ0xpc3Q7XG5cblxuXG4vLy8vLy8vLy8vLy8vLy8vLy9cbi8vIFdFQlBBQ0sgRk9PVEVSXG4vLyAuL2xpYi9tYXBwaW5nLWxpc3QuanNcbi8vIG1vZHVsZSBpZCA9IDZcbi8vIG1vZHVsZSBjaHVua3MgPSAwIiwiLyogLSotIE1vZGU6IGpzOyBqcy1pbmRlbnQtbGV2ZWw6IDI7IC0qLSAqL1xuLypcbiAqIENvcHlyaWdodCAyMDExIE1vemlsbGEgRm91bmRhdGlvbiBhbmQgY29udHJpYnV0b3JzXG4gKiBMaWNlbnNlZCB1bmRlciB0aGUgTmV3IEJTRCBsaWNlbnNlLiBTZWUgTElDRU5TRSBvcjpcbiAqIGh0dHA6Ly9vcGVuc291cmNlLm9yZy9saWNlbnNlcy9CU0QtMy1DbGF1c2VcbiAqL1xuXG52YXIgdXRpbCA9IHJlcXVpcmUoJy4vdXRpbCcpO1xudmFyIGJpbmFyeVNlYXJjaCA9IHJlcXVpcmUoJy4vYmluYXJ5LXNlYXJjaCcpO1xudmFyIEFycmF5U2V0ID0gcmVxdWlyZSgnLi9hcnJheS1zZXQnKS5BcnJheVNldDtcbnZhciBiYXNlNjRWTFEgPSByZXF1aXJlKCcuL2Jhc2U2NC12bHEnKTtcbnZhciBxdWlja1NvcnQgPSByZXF1aXJlKCcuL3F1aWNrLXNvcnQnKS5xdWlja1NvcnQ7XG5cbmZ1bmN0aW9uIFNvdXJjZU1hcENvbnN1bWVyKGFTb3VyY2VNYXAsIGFTb3VyY2VNYXBVUkwpIHtcbiAgdmFyIHNvdXJjZU1hcCA9IGFTb3VyY2VNYXA7XG4gIGlmICh0eXBlb2YgYVNvdXJjZU1hcCA9PT0gJ3N0cmluZycpIHtcbiAgICBzb3VyY2VNYXAgPSB1dGlsLnBhcnNlU291cmNlTWFwSW5wdXQoYVNvdXJjZU1hcCk7XG4gIH1cblxuICByZXR1cm4gc291cmNlTWFwLnNlY3Rpb25zICE9IG51bGxcbiAgICA/IG5ldyBJbmRleGVkU291cmNlTWFwQ29uc3VtZXIoc291cmNlTWFwLCBhU291cmNlTWFwVVJMKVxuICAgIDogbmV3IEJhc2ljU291cmNlTWFwQ29uc3VtZXIoc291cmNlTWFwLCBhU291cmNlTWFwVVJMKTtcbn1cblxuU291cmNlTWFwQ29uc3VtZXIuZnJvbVNvdXJjZU1hcCA9IGZ1bmN0aW9uKGFTb3VyY2VNYXAsIGFTb3VyY2VNYXBVUkwpIHtcbiAgcmV0dXJuIEJhc2ljU291cmNlTWFwQ29uc3VtZXIuZnJvbVNvdXJjZU1hcChhU291cmNlTWFwLCBhU291cmNlTWFwVVJMKTtcbn1cblxuLyoqXG4gKiBUaGUgdmVyc2lvbiBvZiB0aGUgc291cmNlIG1hcHBpbmcgc3BlYyB0aGF0IHdlIGFyZSBjb25zdW1pbmcuXG4gKi9cblNvdXJjZU1hcENvbnN1bWVyLnByb3RvdHlwZS5fdmVyc2lvbiA9IDM7XG5cbi8vIGBfX2dlbmVyYXRlZE1hcHBpbmdzYCBhbmQgYF9fb3JpZ2luYWxNYXBwaW5nc2AgYXJlIGFycmF5cyB0aGF0IGhvbGQgdGhlXG4vLyBwYXJzZWQgbWFwcGluZyBjb29yZGluYXRlcyBmcm9tIHRoZSBzb3VyY2UgbWFwJ3MgXCJtYXBwaW5nc1wiIGF0dHJpYnV0ZS4gVGhleVxuLy8gYXJlIGxhemlseSBpbnN0YW50aWF0ZWQsIGFjY2Vzc2VkIHZpYSB0aGUgYF9nZW5lcmF0ZWRNYXBwaW5nc2AgYW5kXG4vLyBgX29yaWdpbmFsTWFwcGluZ3NgIGdldHRlcnMgcmVzcGVjdGl2ZWx5LCBhbmQgd2Ugb25seSBwYXJzZSB0aGUgbWFwcGluZ3Ncbi8vIGFuZCBjcmVhdGUgdGhlc2UgYXJyYXlzIG9uY2UgcXVlcmllZCBmb3IgYSBzb3VyY2UgbG9jYXRpb24uIFdlIGp1bXAgdGhyb3VnaFxuLy8gdGhlc2UgaG9vcHMgYmVjYXVzZSB0aGVyZSBjYW4gYmUgbWFueSB0aG91c2FuZHMgb2YgbWFwcGluZ3MsIGFuZCBwYXJzaW5nXG4vLyB0aGVtIGlzIGV4cGVuc2l2ZSwgc28gd2Ugb25seSB3YW50IHRvIGRvIGl0IGlmIHdlIG11c3QuXG4vL1xuLy8gRWFjaCBvYmplY3QgaW4gdGhlIGFycmF5cyBpcyBvZiB0aGUgZm9ybTpcbi8vXG4vLyAgICAge1xuLy8gICAgICAgZ2VuZXJhdGVkTGluZTogVGhlIGxpbmUgbnVtYmVyIGluIHRoZSBnZW5lcmF0ZWQgY29kZSxcbi8vICAgICAgIGdlbmVyYXRlZENvbHVtbjogVGhlIGNvbHVtbiBudW1iZXIgaW4gdGhlIGdlbmVyYXRlZCBjb2RlLFxuLy8gICAgICAgc291cmNlOiBUaGUgcGF0aCB0byB0aGUgb3JpZ2luYWwgc291cmNlIGZpbGUgdGhhdCBnZW5lcmF0ZWQgdGhpc1xuLy8gICAgICAgICAgICAgICBjaHVuayBvZiBjb2RlLFxuLy8gICAgICAgb3JpZ2luYWxMaW5lOiBUaGUgbGluZSBudW1iZXIgaW4gdGhlIG9yaWdpbmFsIHNvdXJjZSB0aGF0XG4vLyAgICAgICAgICAgICAgICAgICAgIGNvcnJlc3BvbmRzIHRvIHRoaXMgY2h1bmsgb2YgZ2VuZXJhdGVkIGNvZGUsXG4vLyAgICAgICBvcmlnaW5hbENvbHVtbjogVGhlIGNvbHVtbiBudW1iZXIgaW4gdGhlIG9yaWdpbmFsIHNvdXJjZSB0aGF0XG4vLyAgICAgICAgICAgICAgICAgICAgICAgY29ycmVzcG9uZHMgdG8gdGhpcyBjaHVuayBvZiBnZW5lcmF0ZWQgY29kZSxcbi8vICAgICAgIG5hbWU6IFRoZSBuYW1lIG9mIHRoZSBvcmlnaW5hbCBzeW1ib2wgd2hpY2ggZ2VuZXJhdGVkIHRoaXMgY2h1bmsgb2Zcbi8vICAgICAgICAgICAgIGNvZGUuXG4vLyAgICAgfVxuLy9cbi8vIEFsbCBwcm9wZXJ0aWVzIGV4Y2VwdCBmb3IgYGdlbmVyYXRlZExpbmVgIGFuZCBgZ2VuZXJhdGVkQ29sdW1uYCBjYW4gYmVcbi8vIGBudWxsYC5cbi8vXG4vLyBgX2dlbmVyYXRlZE1hcHBpbmdzYCBpcyBvcmRlcmVkIGJ5IHRoZSBnZW5lcmF0ZWQgcG9zaXRpb25zLlxuLy9cbi8vIGBfb3JpZ2luYWxNYXBwaW5nc2AgaXMgb3JkZXJlZCBieSB0aGUgb3JpZ2luYWwgcG9zaXRpb25zLlxuXG5Tb3VyY2VNYXBDb25zdW1lci5wcm90b3R5cGUuX19nZW5lcmF0ZWRNYXBwaW5ncyA9IG51bGw7XG5PYmplY3QuZGVmaW5lUHJvcGVydHkoU291cmNlTWFwQ29uc3VtZXIucHJvdG90eXBlLCAnX2dlbmVyYXRlZE1hcHBpbmdzJywge1xuICBjb25maWd1cmFibGU6IHRydWUsXG4gIGVudW1lcmFibGU6IHRydWUsXG4gIGdldDogZnVuY3Rpb24gKCkge1xuICAgIGlmICghdGhpcy5fX2dlbmVyYXRlZE1hcHBpbmdzKSB7XG4gICAgICB0aGlzLl9wYXJzZU1hcHBpbmdzKHRoaXMuX21hcHBpbmdzLCB0aGlzLnNvdXJjZVJvb3QpO1xuICAgIH1cblxuICAgIHJldHVybiB0aGlzLl9fZ2VuZXJhdGVkTWFwcGluZ3M7XG4gIH1cbn0pO1xuXG5Tb3VyY2VNYXBDb25zdW1lci5wcm90b3R5cGUuX19vcmlnaW5hbE1hcHBpbmdzID0gbnVsbDtcbk9iamVjdC5kZWZpbmVQcm9wZXJ0eShTb3VyY2VNYXBDb25zdW1lci5wcm90b3R5cGUsICdfb3JpZ2luYWxNYXBwaW5ncycsIHtcbiAgY29uZmlndXJhYmxlOiB0cnVlLFxuICBlbnVtZXJhYmxlOiB0cnVlLFxuICBnZXQ6IGZ1bmN0aW9uICgpIHtcbiAgICBpZiAoIXRoaXMuX19vcmlnaW5hbE1hcHBpbmdzKSB7XG4gICAgICB0aGlzLl9wYXJzZU1hcHBpbmdzKHRoaXMuX21hcHBpbmdzLCB0aGlzLnNvdXJjZVJvb3QpO1xuICAgIH1cblxuICAgIHJldHVybiB0aGlzLl9fb3JpZ2luYWxNYXBwaW5ncztcbiAgfVxufSk7XG5cblNvdXJjZU1hcENvbnN1bWVyLnByb3RvdHlwZS5fY2hhcklzTWFwcGluZ1NlcGFyYXRvciA9XG4gIGZ1bmN0aW9uIFNvdXJjZU1hcENvbnN1bWVyX2NoYXJJc01hcHBpbmdTZXBhcmF0b3IoYVN0ciwgaW5kZXgpIHtcbiAgICB2YXIgYyA9IGFTdHIuY2hhckF0KGluZGV4KTtcbiAgICByZXR1cm4gYyA9PT0gXCI7XCIgfHwgYyA9PT0gXCIsXCI7XG4gIH07XG5cbi8qKlxuICogUGFyc2UgdGhlIG1hcHBpbmdzIGluIGEgc3RyaW5nIGluIHRvIGEgZGF0YSBzdHJ1Y3R1cmUgd2hpY2ggd2UgY2FuIGVhc2lseVxuICogcXVlcnkgKHRoZSBvcmRlcmVkIGFycmF5cyBpbiB0aGUgYHRoaXMuX19nZW5lcmF0ZWRNYXBwaW5nc2AgYW5kXG4gKiBgdGhpcy5fX29yaWdpbmFsTWFwcGluZ3NgIHByb3BlcnRpZXMpLlxuICovXG5Tb3VyY2VNYXBDb25zdW1lci5wcm90b3R5cGUuX3BhcnNlTWFwcGluZ3MgPVxuICBmdW5jdGlvbiBTb3VyY2VNYXBDb25zdW1lcl9wYXJzZU1hcHBpbmdzKGFTdHIsIGFTb3VyY2VSb290KSB7XG4gICAgdGhyb3cgbmV3IEVycm9yKFwiU3ViY2xhc3NlcyBtdXN0IGltcGxlbWVudCBfcGFyc2VNYXBwaW5nc1wiKTtcbiAgfTtcblxuU291cmNlTWFwQ29uc3VtZXIuR0VORVJBVEVEX09SREVSID0gMTtcblNvdXJjZU1hcENvbnN1bWVyLk9SSUdJTkFMX09SREVSID0gMjtcblxuU291cmNlTWFwQ29uc3VtZXIuR1JFQVRFU1RfTE9XRVJfQk9VTkQgPSAxO1xuU291cmNlTWFwQ29uc3VtZXIuTEVBU1RfVVBQRVJfQk9VTkQgPSAyO1xuXG4vKipcbiAqIEl0ZXJhdGUgb3ZlciBlYWNoIG1hcHBpbmcgYmV0d2VlbiBhbiBvcmlnaW5hbCBzb3VyY2UvbGluZS9jb2x1bW4gYW5kIGFcbiAqIGdlbmVyYXRlZCBsaW5lL2NvbHVtbiBpbiB0aGlzIHNvdXJjZSBtYXAuXG4gKlxuICogQHBhcmFtIEZ1bmN0aW9uIGFDYWxsYmFja1xuICogICAgICAgIFRoZSBmdW5jdGlvbiB0aGF0IGlzIGNhbGxlZCB3aXRoIGVhY2ggbWFwcGluZy5cbiAqIEBwYXJhbSBPYmplY3QgYUNvbnRleHRcbiAqICAgICAgICBPcHRpb25hbC4gSWYgc3BlY2lmaWVkLCB0aGlzIG9iamVjdCB3aWxsIGJlIHRoZSB2YWx1ZSBvZiBgdGhpc2AgZXZlcnlcbiAqICAgICAgICB0aW1lIHRoYXQgYGFDYWxsYmFja2AgaXMgY2FsbGVkLlxuICogQHBhcmFtIGFPcmRlclxuICogICAgICAgIEVpdGhlciBgU291cmNlTWFwQ29uc3VtZXIuR0VORVJBVEVEX09SREVSYCBvclxuICogICAgICAgIGBTb3VyY2VNYXBDb25zdW1lci5PUklHSU5BTF9PUkRFUmAuIFNwZWNpZmllcyB3aGV0aGVyIHlvdSB3YW50IHRvXG4gKiAgICAgICAgaXRlcmF0ZSBvdmVyIHRoZSBtYXBwaW5ncyBzb3J0ZWQgYnkgdGhlIGdlbmVyYXRlZCBmaWxlJ3MgbGluZS9jb2x1bW5cbiAqICAgICAgICBvcmRlciBvciB0aGUgb3JpZ2luYWwncyBzb3VyY2UvbGluZS9jb2x1bW4gb3JkZXIsIHJlc3BlY3RpdmVseS4gRGVmYXVsdHMgdG9cbiAqICAgICAgICBgU291cmNlTWFwQ29uc3VtZXIuR0VORVJBVEVEX09SREVSYC5cbiAqL1xuU291cmNlTWFwQ29uc3VtZXIucHJvdG90eXBlLmVhY2hNYXBwaW5nID1cbiAgZnVuY3Rpb24gU291cmNlTWFwQ29uc3VtZXJfZWFjaE1hcHBpbmcoYUNhbGxiYWNrLCBhQ29udGV4dCwgYU9yZGVyKSB7XG4gICAgdmFyIGNvbnRleHQgPSBhQ29udGV4dCB8fCBudWxsO1xuICAgIHZhciBvcmRlciA9IGFPcmRlciB8fCBTb3VyY2VNYXBDb25zdW1lci5HRU5FUkFURURfT1JERVI7XG5cbiAgICB2YXIgbWFwcGluZ3M7XG4gICAgc3dpdGNoIChvcmRlcikge1xuICAgIGNhc2UgU291cmNlTWFwQ29uc3VtZXIuR0VORVJBVEVEX09SREVSOlxuICAgICAgbWFwcGluZ3MgPSB0aGlzLl9nZW5lcmF0ZWRNYXBwaW5ncztcbiAgICAgIGJyZWFrO1xuICAgIGNhc2UgU291cmNlTWFwQ29uc3VtZXIuT1JJR0lOQUxfT1JERVI6XG4gICAgICBtYXBwaW5ncyA9IHRoaXMuX29yaWdpbmFsTWFwcGluZ3M7XG4gICAgICBicmVhaztcbiAgICBkZWZhdWx0OlxuICAgICAgdGhyb3cgbmV3IEVycm9yKFwiVW5rbm93biBvcmRlciBvZiBpdGVyYXRpb24uXCIpO1xuICAgIH1cblxuICAgIHZhciBzb3VyY2VSb290ID0gdGhpcy5zb3VyY2VSb290O1xuICAgIG1hcHBpbmdzLm1hcChmdW5jdGlvbiAobWFwcGluZykge1xuICAgICAgdmFyIHNvdXJjZSA9IG1hcHBpbmcuc291cmNlID09PSBudWxsID8gbnVsbCA6IHRoaXMuX3NvdXJjZXMuYXQobWFwcGluZy5zb3VyY2UpO1xuICAgICAgc291cmNlID0gdXRpbC5jb21wdXRlU291cmNlVVJMKHNvdXJjZVJvb3QsIHNvdXJjZSwgdGhpcy5fc291cmNlTWFwVVJMKTtcbiAgICAgIHJldHVybiB7XG4gICAgICAgIHNvdXJjZTogc291cmNlLFxuICAgICAgICBnZW5lcmF0ZWRMaW5lOiBtYXBwaW5nLmdlbmVyYXRlZExpbmUsXG4gICAgICAgIGdlbmVyYXRlZENvbHVtbjogbWFwcGluZy5nZW5lcmF0ZWRDb2x1bW4sXG4gICAgICAgIG9yaWdpbmFsTGluZTogbWFwcGluZy5vcmlnaW5hbExpbmUsXG4gICAgICAgIG9yaWdpbmFsQ29sdW1uOiBtYXBwaW5nLm9yaWdpbmFsQ29sdW1uLFxuICAgICAgICBuYW1lOiBtYXBwaW5nLm5hbWUgPT09IG51bGwgPyBudWxsIDogdGhpcy5fbmFtZXMuYXQobWFwcGluZy5uYW1lKVxuICAgICAgfTtcbiAgICB9LCB0aGlzKS5mb3JFYWNoKGFDYWxsYmFjaywgY29udGV4dCk7XG4gIH07XG5cbi8qKlxuICogUmV0dXJucyBhbGwgZ2VuZXJhdGVkIGxpbmUgYW5kIGNvbHVtbiBpbmZvcm1hdGlvbiBmb3IgdGhlIG9yaWdpbmFsIHNvdXJjZSxcbiAqIGxpbmUsIGFuZCBjb2x1bW4gcHJvdmlkZWQuIElmIG5vIGNvbHVtbiBpcyBwcm92aWRlZCwgcmV0dXJucyBhbGwgbWFwcGluZ3NcbiAqIGNvcnJlc3BvbmRpbmcgdG8gYSBlaXRoZXIgdGhlIGxpbmUgd2UgYXJlIHNlYXJjaGluZyBmb3Igb3IgdGhlIG5leHRcbiAqIGNsb3Nlc3QgbGluZSB0aGF0IGhhcyBhbnkgbWFwcGluZ3MuIE90aGVyd2lzZSwgcmV0dXJucyBhbGwgbWFwcGluZ3NcbiAqIGNvcnJlc3BvbmRpbmcgdG8gdGhlIGdpdmVuIGxpbmUgYW5kIGVpdGhlciB0aGUgY29sdW1uIHdlIGFyZSBzZWFyY2hpbmcgZm9yXG4gKiBvciB0aGUgbmV4dCBjbG9zZXN0IGNvbHVtbiB0aGF0IGhhcyBhbnkgb2Zmc2V0cy5cbiAqXG4gKiBUaGUgb25seSBhcmd1bWVudCBpcyBhbiBvYmplY3Qgd2l0aCB0aGUgZm9sbG93aW5nIHByb3BlcnRpZXM6XG4gKlxuICogICAtIHNvdXJjZTogVGhlIGZpbGVuYW1lIG9mIHRoZSBvcmlnaW5hbCBzb3VyY2UuXG4gKiAgIC0gbGluZTogVGhlIGxpbmUgbnVtYmVyIGluIHRoZSBvcmlnaW5hbCBzb3VyY2UuICBUaGUgbGluZSBudW1iZXIgaXMgMS1iYXNlZC5cbiAqICAgLSBjb2x1bW46IE9wdGlvbmFsLiB0aGUgY29sdW1uIG51bWJlciBpbiB0aGUgb3JpZ2luYWwgc291cmNlLlxuICogICAgVGhlIGNvbHVtbiBudW1iZXIgaXMgMC1iYXNlZC5cbiAqXG4gKiBhbmQgYW4gYXJyYXkgb2Ygb2JqZWN0cyBpcyByZXR1cm5lZCwgZWFjaCB3aXRoIHRoZSBmb2xsb3dpbmcgcHJvcGVydGllczpcbiAqXG4gKiAgIC0gbGluZTogVGhlIGxpbmUgbnVtYmVyIGluIHRoZSBnZW5lcmF0ZWQgc291cmNlLCBvciBudWxsLiAgVGhlXG4gKiAgICBsaW5lIG51bWJlciBpcyAxLWJhc2VkLlxuICogICAtIGNvbHVtbjogVGhlIGNvbHVtbiBudW1iZXIgaW4gdGhlIGdlbmVyYXRlZCBzb3VyY2UsIG9yIG51bGwuXG4gKiAgICBUaGUgY29sdW1uIG51bWJlciBpcyAwLWJhc2VkLlxuICovXG5Tb3VyY2VNYXBDb25zdW1lci5wcm90b3R5cGUuYWxsR2VuZXJhdGVkUG9zaXRpb25zRm9yID1cbiAgZnVuY3Rpb24gU291cmNlTWFwQ29uc3VtZXJfYWxsR2VuZXJhdGVkUG9zaXRpb25zRm9yKGFBcmdzKSB7XG4gICAgdmFyIGxpbmUgPSB1dGlsLmdldEFyZyhhQXJncywgJ2xpbmUnKTtcblxuICAgIC8vIFdoZW4gdGhlcmUgaXMgbm8gZXhhY3QgbWF0Y2gsIEJhc2ljU291cmNlTWFwQ29uc3VtZXIucHJvdG90eXBlLl9maW5kTWFwcGluZ1xuICAgIC8vIHJldHVybnMgdGhlIGluZGV4IG9mIHRoZSBjbG9zZXN0IG1hcHBpbmcgbGVzcyB0aGFuIHRoZSBuZWVkbGUuIEJ5XG4gICAgLy8gc2V0dGluZyBuZWVkbGUub3JpZ2luYWxDb2x1bW4gdG8gMCwgd2UgdGh1cyBmaW5kIHRoZSBsYXN0IG1hcHBpbmcgZm9yXG4gICAgLy8gdGhlIGdpdmVuIGxpbmUsIHByb3ZpZGVkIHN1Y2ggYSBtYXBwaW5nIGV4aXN0cy5cbiAgICB2YXIgbmVlZGxlID0ge1xuICAgICAgc291cmNlOiB1dGlsLmdldEFyZyhhQXJncywgJ3NvdXJjZScpLFxuICAgICAgb3JpZ2luYWxMaW5lOiBsaW5lLFxuICAgICAgb3JpZ2luYWxDb2x1bW46IHV0aWwuZ2V0QXJnKGFBcmdzLCAnY29sdW1uJywgMClcbiAgICB9O1xuXG4gICAgbmVlZGxlLnNvdXJjZSA9IHRoaXMuX2ZpbmRTb3VyY2VJbmRleChuZWVkbGUuc291cmNlKTtcbiAgICBpZiAobmVlZGxlLnNvdXJjZSA8IDApIHtcbiAgICAgIHJldHVybiBbXTtcbiAgICB9XG5cbiAgICB2YXIgbWFwcGluZ3MgPSBbXTtcblxuICAgIHZhciBpbmRleCA9IHRoaXMuX2ZpbmRNYXBwaW5nKG5lZWRsZSxcbiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICB0aGlzLl9vcmlnaW5hbE1hcHBpbmdzLFxuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIFwib3JpZ2luYWxMaW5lXCIsXG4gICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgXCJvcmlnaW5hbENvbHVtblwiLFxuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIHV0aWwuY29tcGFyZUJ5T3JpZ2luYWxQb3NpdGlvbnMsXG4gICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgYmluYXJ5U2VhcmNoLkxFQVNUX1VQUEVSX0JPVU5EKTtcbiAgICBpZiAoaW5kZXggPj0gMCkge1xuICAgICAgdmFyIG1hcHBpbmcgPSB0aGlzLl9vcmlnaW5hbE1hcHBpbmdzW2luZGV4XTtcblxuICAgICAgaWYgKGFBcmdzLmNvbHVtbiA9PT0gdW5kZWZpbmVkKSB7XG4gICAgICAgIHZhciBvcmlnaW5hbExpbmUgPSBtYXBwaW5nLm9yaWdpbmFsTGluZTtcblxuICAgICAgICAvLyBJdGVyYXRlIHVudGlsIGVpdGhlciB3ZSBydW4gb3V0IG9mIG1hcHBpbmdzLCBvciB3ZSBydW4gaW50b1xuICAgICAgICAvLyBhIG1hcHBpbmcgZm9yIGEgZGlmZmVyZW50IGxpbmUgdGhhbiB0aGUgb25lIHdlIGZvdW5kLiBTaW5jZVxuICAgICAgICAvLyBtYXBwaW5ncyBhcmUgc29ydGVkLCB0aGlzIGlzIGd1YXJhbnRlZWQgdG8gZmluZCBhbGwgbWFwcGluZ3MgZm9yXG4gICAgICAgIC8vIHRoZSBsaW5lIHdlIGZvdW5kLlxuICAgICAgICB3aGlsZSAobWFwcGluZyAmJiBtYXBwaW5nLm9yaWdpbmFsTGluZSA9PT0gb3JpZ2luYWxMaW5lKSB7XG4gICAgICAgICAgbWFwcGluZ3MucHVzaCh7XG4gICAgICAgICAgICBsaW5lOiB1dGlsLmdldEFyZyhtYXBwaW5nLCAnZ2VuZXJhdGVkTGluZScsIG51bGwpLFxuICAgICAgICAgICAgY29sdW1uOiB1dGlsLmdldEFyZyhtYXBwaW5nLCAnZ2VuZXJhdGVkQ29sdW1uJywgbnVsbCksXG4gICAgICAgICAgICBsYXN0Q29sdW1uOiB1dGlsLmdldEFyZyhtYXBwaW5nLCAnbGFzdEdlbmVyYXRlZENvbHVtbicsIG51bGwpXG4gICAgICAgICAgfSk7XG5cbiAgICAgICAgICBtYXBwaW5nID0gdGhpcy5fb3JpZ2luYWxNYXBwaW5nc1srK2luZGV4XTtcbiAgICAgICAgfVxuICAgICAgfSBlbHNlIHtcbiAgICAgICAgdmFyIG9yaWdpbmFsQ29sdW1uID0gbWFwcGluZy5vcmlnaW5hbENvbHVtbjtcblxuICAgICAgICAvLyBJdGVyYXRlIHVudGlsIGVpdGhlciB3ZSBydW4gb3V0IG9mIG1hcHBpbmdzLCBvciB3ZSBydW4gaW50b1xuICAgICAgICAvLyBhIG1hcHBpbmcgZm9yIGEgZGlmZmVyZW50IGxpbmUgdGhhbiB0aGUgb25lIHdlIHdlcmUgc2VhcmNoaW5nIGZvci5cbiAgICAgICAgLy8gU2luY2UgbWFwcGluZ3MgYXJlIHNvcnRlZCwgdGhpcyBpcyBndWFyYW50ZWVkIHRvIGZpbmQgYWxsIG1hcHBpbmdzIGZvclxuICAgICAgICAvLyB0aGUgbGluZSB3ZSBhcmUgc2VhcmNoaW5nIGZvci5cbiAgICAgICAgd2hpbGUgKG1hcHBpbmcgJiZcbiAgICAgICAgICAgICAgIG1hcHBpbmcub3JpZ2luYWxMaW5lID09PSBsaW5lICYmXG4gICAgICAgICAgICAgICBtYXBwaW5nLm9yaWdpbmFsQ29sdW1uID09IG9yaWdpbmFsQ29sdW1uKSB7XG4gICAgICAgICAgbWFwcGluZ3MucHVzaCh7XG4gICAgICAgICAgICBsaW5lOiB1dGlsLmdldEFyZyhtYXBwaW5nLCAnZ2VuZXJhdGVkTGluZScsIG51bGwpLFxuICAgICAgICAgICAgY29sdW1uOiB1dGlsLmdldEFyZyhtYXBwaW5nLCAnZ2VuZXJhdGVkQ29sdW1uJywgbnVsbCksXG4gICAgICAgICAgICBsYXN0Q29sdW1uOiB1dGlsLmdldEFyZyhtYXBwaW5nLCAnbGFzdEdlbmVyYXRlZENvbHVtbicsIG51bGwpXG4gICAgICAgICAgfSk7XG5cbiAgICAgICAgICBtYXBwaW5nID0gdGhpcy5fb3JpZ2luYWxNYXBwaW5nc1srK2luZGV4XTtcbiAgICAgICAgfVxuICAgICAgfVxuICAgIH1cblxuICAgIHJldHVybiBtYXBwaW5ncztcbiAgfTtcblxuZXhwb3J0cy5Tb3VyY2VNYXBDb25zdW1lciA9IFNvdXJjZU1hcENvbnN1bWVyO1xuXG4vKipcbiAqIEEgQmFzaWNTb3VyY2VNYXBDb25zdW1lciBpbnN0YW5jZSByZXByZXNlbnRzIGEgcGFyc2VkIHNvdXJjZSBtYXAgd2hpY2ggd2UgY2FuXG4gKiBxdWVyeSBmb3IgaW5mb3JtYXRpb24gYWJvdXQgdGhlIG9yaWdpbmFsIGZpbGUgcG9zaXRpb25zIGJ5IGdpdmluZyBpdCBhIGZpbGVcbiAqIHBvc2l0aW9uIGluIHRoZSBnZW5lcmF0ZWQgc291cmNlLlxuICpcbiAqIFRoZSBmaXJzdCBwYXJhbWV0ZXIgaXMgdGhlIHJhdyBzb3VyY2UgbWFwIChlaXRoZXIgYXMgYSBKU09OIHN0cmluZywgb3JcbiAqIGFscmVhZHkgcGFyc2VkIHRvIGFuIG9iamVjdCkuIEFjY29yZGluZyB0byB0aGUgc3BlYywgc291cmNlIG1hcHMgaGF2ZSB0aGVcbiAqIGZvbGxvd2luZyBhdHRyaWJ1dGVzOlxuICpcbiAqICAgLSB2ZXJzaW9uOiBXaGljaCB2ZXJzaW9uIG9mIHRoZSBzb3VyY2UgbWFwIHNwZWMgdGhpcyBtYXAgaXMgZm9sbG93aW5nLlxuICogICAtIHNvdXJjZXM6IEFuIGFycmF5IG9mIFVSTHMgdG8gdGhlIG9yaWdpbmFsIHNvdXJjZSBmaWxlcy5cbiAqICAgLSBuYW1lczogQW4gYXJyYXkgb2YgaWRlbnRpZmllcnMgd2hpY2ggY2FuIGJlIHJlZmVycmVuY2VkIGJ5IGluZGl2aWR1YWwgbWFwcGluZ3MuXG4gKiAgIC0gc291cmNlUm9vdDogT3B0aW9uYWwuIFRoZSBVUkwgcm9vdCBmcm9tIHdoaWNoIGFsbCBzb3VyY2VzIGFyZSByZWxhdGl2ZS5cbiAqICAgLSBzb3VyY2VzQ29udGVudDogT3B0aW9uYWwuIEFuIGFycmF5IG9mIGNvbnRlbnRzIG9mIHRoZSBvcmlnaW5hbCBzb3VyY2UgZmlsZXMuXG4gKiAgIC0gbWFwcGluZ3M6IEEgc3RyaW5nIG9mIGJhc2U2NCBWTFFzIHdoaWNoIGNvbnRhaW4gdGhlIGFjdHVhbCBtYXBwaW5ncy5cbiAqICAgLSBmaWxlOiBPcHRpb25hbC4gVGhlIGdlbmVyYXRlZCBmaWxlIHRoaXMgc291cmNlIG1hcCBpcyBhc3NvY2lhdGVkIHdpdGguXG4gKlxuICogSGVyZSBpcyBhbiBleGFtcGxlIHNvdXJjZSBtYXAsIHRha2VuIGZyb20gdGhlIHNvdXJjZSBtYXAgc3BlY1swXTpcbiAqXG4gKiAgICAge1xuICogICAgICAgdmVyc2lvbiA6IDMsXG4gKiAgICAgICBmaWxlOiBcIm91dC5qc1wiLFxuICogICAgICAgc291cmNlUm9vdCA6IFwiXCIsXG4gKiAgICAgICBzb3VyY2VzOiBbXCJmb28uanNcIiwgXCJiYXIuanNcIl0sXG4gKiAgICAgICBuYW1lczogW1wic3JjXCIsIFwibWFwc1wiLCBcImFyZVwiLCBcImZ1blwiXSxcbiAqICAgICAgIG1hcHBpbmdzOiBcIkFBLEFCOztBQkNERTtcIlxuICogICAgIH1cbiAqXG4gKiBUaGUgc2Vjb25kIHBhcmFtZXRlciwgaWYgZ2l2ZW4sIGlzIGEgc3RyaW5nIHdob3NlIHZhbHVlIGlzIHRoZSBVUkxcbiAqIGF0IHdoaWNoIHRoZSBzb3VyY2UgbWFwIHdhcyBmb3VuZC4gIFRoaXMgVVJMIGlzIHVzZWQgdG8gY29tcHV0ZSB0aGVcbiAqIHNvdXJjZXMgYXJyYXkuXG4gKlxuICogWzBdOiBodHRwczovL2RvY3MuZ29vZ2xlLmNvbS9kb2N1bWVudC9kLzFVMVJHQWVoUXdSeXBVVG92RjFLUmxwaU9GemUwYi1fMmdjNmZBSDBLWTBrL2VkaXQ/cGxpPTEjXG4gKi9cbmZ1bmN0aW9uIEJhc2ljU291cmNlTWFwQ29uc3VtZXIoYVNvdXJjZU1hcCwgYVNvdXJjZU1hcFVSTCkge1xuICB2YXIgc291cmNlTWFwID0gYVNvdXJjZU1hcDtcbiAgaWYgKHR5cGVvZiBhU291cmNlTWFwID09PSAnc3RyaW5nJykge1xuICAgIHNvdXJjZU1hcCA9IHV0aWwucGFyc2VTb3VyY2VNYXBJbnB1dChhU291cmNlTWFwKTtcbiAgfVxuXG4gIHZhciB2ZXJzaW9uID0gdXRpbC5nZXRBcmcoc291cmNlTWFwLCAndmVyc2lvbicpO1xuICB2YXIgc291cmNlcyA9IHV0aWwuZ2V0QXJnKHNvdXJjZU1hcCwgJ3NvdXJjZXMnKTtcbiAgLy8gU2FzcyAzLjMgbGVhdmVzIG91dCB0aGUgJ25hbWVzJyBhcnJheSwgc28gd2UgZGV2aWF0ZSBmcm9tIHRoZSBzcGVjICh3aGljaFxuICAvLyByZXF1aXJlcyB0aGUgYXJyYXkpIHRvIHBsYXkgbmljZSBoZXJlLlxuICB2YXIgbmFtZXMgPSB1dGlsLmdldEFyZyhzb3VyY2VNYXAsICduYW1lcycsIFtdKTtcbiAgdmFyIHNvdXJjZVJvb3QgPSB1dGlsLmdldEFyZyhzb3VyY2VNYXAsICdzb3VyY2VSb290JywgbnVsbCk7XG4gIHZhciBzb3VyY2VzQ29udGVudCA9IHV0aWwuZ2V0QXJnKHNvdXJjZU1hcCwgJ3NvdXJjZXNDb250ZW50JywgbnVsbCk7XG4gIHZhciBtYXBwaW5ncyA9IHV0aWwuZ2V0QXJnKHNvdXJjZU1hcCwgJ21hcHBpbmdzJyk7XG4gIHZhciBmaWxlID0gdXRpbC5nZXRBcmcoc291cmNlTWFwLCAnZmlsZScsIG51bGwpO1xuXG4gIC8vIE9uY2UgYWdhaW4sIFNhc3MgZGV2aWF0ZXMgZnJvbSB0aGUgc3BlYyBhbmQgc3VwcGxpZXMgdGhlIHZlcnNpb24gYXMgYVxuICAvLyBzdHJpbmcgcmF0aGVyIHRoYW4gYSBudW1iZXIsIHNvIHdlIHVzZSBsb29zZSBlcXVhbGl0eSBjaGVja2luZyBoZXJlLlxuICBpZiAodmVyc2lvbiAhPSB0aGlzLl92ZXJzaW9uKSB7XG4gICAgdGhyb3cgbmV3IEVycm9yKCdVbnN1cHBvcnRlZCB2ZXJzaW9uOiAnICsgdmVyc2lvbik7XG4gIH1cblxuICBpZiAoc291cmNlUm9vdCkge1xuICAgIHNvdXJjZVJvb3QgPSB1dGlsLm5vcm1hbGl6ZShzb3VyY2VSb290KTtcbiAgfVxuXG4gIHNvdXJjZXMgPSBzb3VyY2VzXG4gICAgLm1hcChTdHJpbmcpXG4gICAgLy8gU29tZSBzb3VyY2UgbWFwcyBwcm9kdWNlIHJlbGF0aXZlIHNvdXJjZSBwYXRocyBsaWtlIFwiLi9mb28uanNcIiBpbnN0ZWFkIG9mXG4gICAgLy8gXCJmb28uanNcIi4gIE5vcm1hbGl6ZSB0aGVzZSBmaXJzdCBzbyB0aGF0IGZ1dHVyZSBjb21wYXJpc29ucyB3aWxsIHN1Y2NlZWQuXG4gICAgLy8gU2VlIGJ1Z3ppbC5sYS8xMDkwNzY4LlxuICAgIC5tYXAodXRpbC5ub3JtYWxpemUpXG4gICAgLy8gQWx3YXlzIGVuc3VyZSB0aGF0IGFic29sdXRlIHNvdXJjZXMgYXJlIGludGVybmFsbHkgc3RvcmVkIHJlbGF0aXZlIHRvXG4gICAgLy8gdGhlIHNvdXJjZSByb290LCBpZiB0aGUgc291cmNlIHJvb3QgaXMgYWJzb2x1dGUuIE5vdCBkb2luZyB0aGlzIHdvdWxkXG4gICAgLy8gYmUgcGFydGljdWxhcmx5IHByb2JsZW1hdGljIHdoZW4gdGhlIHNvdXJjZSByb290IGlzIGEgcHJlZml4IG9mIHRoZVxuICAgIC8vIHNvdXJjZSAodmFsaWQsIGJ1dCB3aHk/PykuIFNlZSBnaXRodWIgaXNzdWUgIzE5OSBhbmQgYnVnemlsLmxhLzExODg5ODIuXG4gICAgLm1hcChmdW5jdGlvbiAoc291cmNlKSB7XG4gICAgICByZXR1cm4gc291cmNlUm9vdCAmJiB1dGlsLmlzQWJzb2x1dGUoc291cmNlUm9vdCkgJiYgdXRpbC5pc0Fic29sdXRlKHNvdXJjZSlcbiAgICAgICAgPyB1dGlsLnJlbGF0aXZlKHNvdXJjZVJvb3QsIHNvdXJjZSlcbiAgICAgICAgOiBzb3VyY2U7XG4gICAgfSk7XG5cbiAgLy8gUGFzcyBgdHJ1ZWAgYmVsb3cgdG8gYWxsb3cgZHVwbGljYXRlIG5hbWVzIGFuZCBzb3VyY2VzLiBXaGlsZSBzb3VyY2UgbWFwc1xuICAvLyBhcmUgaW50ZW5kZWQgdG8gYmUgY29tcHJlc3NlZCBhbmQgZGVkdXBsaWNhdGVkLCB0aGUgVHlwZVNjcmlwdCBjb21waWxlclxuICAvLyBzb21ldGltZXMgZ2VuZXJhdGVzIHNvdXJjZSBtYXBzIHdpdGggZHVwbGljYXRlcyBpbiB0aGVtLiBTZWUgR2l0aHViIGlzc3VlXG4gIC8vICM3MiBhbmQgYnVnemlsLmxhLzg4OTQ5Mi5cbiAgdGhpcy5fbmFtZXMgPSBBcnJheVNldC5mcm9tQXJyYXkobmFtZXMubWFwKFN0cmluZyksIHRydWUpO1xuICB0aGlzLl9zb3VyY2VzID0gQXJyYXlTZXQuZnJvbUFycmF5KHNvdXJjZXMsIHRydWUpO1xuXG4gIHRoaXMuX2Fic29sdXRlU291cmNlcyA9IHRoaXMuX3NvdXJjZXMudG9BcnJheSgpLm1hcChmdW5jdGlvbiAocykge1xuICAgIHJldHVybiB1dGlsLmNvbXB1dGVTb3VyY2VVUkwoc291cmNlUm9vdCwgcywgYVNvdXJjZU1hcFVSTCk7XG4gIH0pO1xuXG4gIHRoaXMuc291cmNlUm9vdCA9IHNvdXJjZVJvb3Q7XG4gIHRoaXMuc291cmNlc0NvbnRlbnQgPSBzb3VyY2VzQ29udGVudDtcbiAgdGhpcy5fbWFwcGluZ3MgPSBtYXBwaW5ncztcbiAgdGhpcy5fc291cmNlTWFwVVJMID0gYVNvdXJjZU1hcFVSTDtcbiAgdGhpcy5maWxlID0gZmlsZTtcbn1cblxuQmFzaWNTb3VyY2VNYXBDb25zdW1lci5wcm90b3R5cGUgPSBPYmplY3QuY3JlYXRlKFNvdXJjZU1hcENvbnN1bWVyLnByb3RvdHlwZSk7XG5CYXNpY1NvdXJjZU1hcENvbnN1bWVyLnByb3RvdHlwZS5jb25zdW1lciA9IFNvdXJjZU1hcENvbnN1bWVyO1xuXG4vKipcbiAqIFV0aWxpdHkgZnVuY3Rpb24gdG8gZmluZCB0aGUgaW5kZXggb2YgYSBzb3VyY2UuICBSZXR1cm5zIC0xIGlmIG5vdFxuICogZm91bmQuXG4gKi9cbkJhc2ljU291cmNlTWFwQ29uc3VtZXIucHJvdG90eXBlLl9maW5kU291cmNlSW5kZXggPSBmdW5jdGlvbihhU291cmNlKSB7XG4gIHZhciByZWxhdGl2ZVNvdXJjZSA9IGFTb3VyY2U7XG4gIGlmICh0aGlzLnNvdXJjZVJvb3QgIT0gbnVsbCkge1xuICAgIHJlbGF0aXZlU291cmNlID0gdXRpbC5yZWxhdGl2ZSh0aGlzLnNvdXJjZVJvb3QsIHJlbGF0aXZlU291cmNlKTtcbiAgfVxuXG4gIGlmICh0aGlzLl9zb3VyY2VzLmhhcyhyZWxhdGl2ZVNvdXJjZSkpIHtcbiAgICByZXR1cm4gdGhpcy5fc291cmNlcy5pbmRleE9mKHJlbGF0aXZlU291cmNlKTtcbiAgfVxuXG4gIC8vIE1heWJlIGFTb3VyY2UgaXMgYW4gYWJzb2x1dGUgVVJMIGFzIHJldHVybmVkIGJ5IHxzb3VyY2VzfC4gIEluXG4gIC8vIHRoaXMgY2FzZSB3ZSBjYW4ndCBzaW1wbHkgdW5kbyB0aGUgdHJhbnNmb3JtLlxuICB2YXIgaTtcbiAgZm9yIChpID0gMDsgaSA8IHRoaXMuX2Fic29sdXRlU291cmNlcy5sZW5ndGg7ICsraSkge1xuICAgIGlmICh0aGlzLl9hYnNvbHV0ZVNvdXJjZXNbaV0gPT0gYVNvdXJjZSkge1xuICAgICAgcmV0dXJuIGk7XG4gICAgfVxuICB9XG5cbiAgcmV0dXJuIC0xO1xufTtcblxuLyoqXG4gKiBDcmVhdGUgYSBCYXNpY1NvdXJjZU1hcENvbnN1bWVyIGZyb20gYSBTb3VyY2VNYXBHZW5lcmF0b3IuXG4gKlxuICogQHBhcmFtIFNvdXJjZU1hcEdlbmVyYXRvciBhU291cmNlTWFwXG4gKiAgICAgICAgVGhlIHNvdXJjZSBtYXAgdGhhdCB3aWxsIGJlIGNvbnN1bWVkLlxuICogQHBhcmFtIFN0cmluZyBhU291cmNlTWFwVVJMXG4gKiAgICAgICAgVGhlIFVSTCBhdCB3aGljaCB0aGUgc291cmNlIG1hcCBjYW4gYmUgZm91bmQgKG9wdGlvbmFsKVxuICogQHJldHVybnMgQmFzaWNTb3VyY2VNYXBDb25zdW1lclxuICovXG5CYXNpY1NvdXJjZU1hcENvbnN1bWVyLmZyb21Tb3VyY2VNYXAgPVxuICBmdW5jdGlvbiBTb3VyY2VNYXBDb25zdW1lcl9mcm9tU291cmNlTWFwKGFTb3VyY2VNYXAsIGFTb3VyY2VNYXBVUkwpIHtcbiAgICB2YXIgc21jID0gT2JqZWN0LmNyZWF0ZShCYXNpY1NvdXJjZU1hcENvbnN1bWVyLnByb3RvdHlwZSk7XG5cbiAgICB2YXIgbmFtZXMgPSBzbWMuX25hbWVzID0gQXJyYXlTZXQuZnJvbUFycmF5KGFTb3VyY2VNYXAuX25hbWVzLnRvQXJyYXkoKSwgdHJ1ZSk7XG4gICAgdmFyIHNvdXJjZXMgPSBzbWMuX3NvdXJjZXMgPSBBcnJheVNldC5mcm9tQXJyYXkoYVNvdXJjZU1hcC5fc291cmNlcy50b0FycmF5KCksIHRydWUpO1xuICAgIHNtYy5zb3VyY2VSb290ID0gYVNvdXJjZU1hcC5fc291cmNlUm9vdDtcbiAgICBzbWMuc291cmNlc0NvbnRlbnQgPSBhU291cmNlTWFwLl9nZW5lcmF0ZVNvdXJjZXNDb250ZW50KHNtYy5fc291cmNlcy50b0FycmF5KCksXG4gICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICBzbWMuc291cmNlUm9vdCk7XG4gICAgc21jLmZpbGUgPSBhU291cmNlTWFwLl9maWxlO1xuICAgIHNtYy5fc291cmNlTWFwVVJMID0gYVNvdXJjZU1hcFVSTDtcbiAgICBzbWMuX2Fic29sdXRlU291cmNlcyA9IHNtYy5fc291cmNlcy50b0FycmF5KCkubWFwKGZ1bmN0aW9uIChzKSB7XG4gICAgICByZXR1cm4gdXRpbC5jb21wdXRlU291cmNlVVJMKHNtYy5zb3VyY2VSb290LCBzLCBhU291cmNlTWFwVVJMKTtcbiAgICB9KTtcblxuICAgIC8vIEJlY2F1c2Ugd2UgYXJlIG1vZGlmeWluZyB0aGUgZW50cmllcyAoYnkgY29udmVydGluZyBzdHJpbmcgc291cmNlcyBhbmRcbiAgICAvLyBuYW1lcyB0byBpbmRpY2VzIGludG8gdGhlIHNvdXJjZXMgYW5kIG5hbWVzIEFycmF5U2V0cyksIHdlIGhhdmUgdG8gbWFrZVxuICAgIC8vIGEgY29weSBvZiB0aGUgZW50cnkgb3IgZWxzZSBiYWQgdGhpbmdzIGhhcHBlbi4gU2hhcmVkIG11dGFibGUgc3RhdGVcbiAgICAvLyBzdHJpa2VzIGFnYWluISBTZWUgZ2l0aHViIGlzc3VlICMxOTEuXG5cbiAgICB2YXIgZ2VuZXJhdGVkTWFwcGluZ3MgPSBhU291cmNlTWFwLl9tYXBwaW5ncy50b0FycmF5KCkuc2xpY2UoKTtcbiAgICB2YXIgZGVzdEdlbmVyYXRlZE1hcHBpbmdzID0gc21jLl9fZ2VuZXJhdGVkTWFwcGluZ3MgPSBbXTtcbiAgICB2YXIgZGVzdE9yaWdpbmFsTWFwcGluZ3MgPSBzbWMuX19vcmlnaW5hbE1hcHBpbmdzID0gW107XG5cbiAgICBmb3IgKHZhciBpID0gMCwgbGVuZ3RoID0gZ2VuZXJhdGVkTWFwcGluZ3MubGVuZ3RoOyBpIDwgbGVuZ3RoOyBpKyspIHtcbiAgICAgIHZhciBzcmNNYXBwaW5nID0gZ2VuZXJhdGVkTWFwcGluZ3NbaV07XG4gICAgICB2YXIgZGVzdE1hcHBpbmcgPSBuZXcgTWFwcGluZztcbiAgICAgIGRlc3RNYXBwaW5nLmdlbmVyYXRlZExpbmUgPSBzcmNNYXBwaW5nLmdlbmVyYXRlZExpbmU7XG4gICAgICBkZXN0TWFwcGluZy5nZW5lcmF0ZWRDb2x1bW4gPSBzcmNNYXBwaW5nLmdlbmVyYXRlZENvbHVtbjtcblxuICAgICAgaWYgKHNyY01hcHBpbmcuc291cmNlKSB7XG4gICAgICAgIGRlc3RNYXBwaW5nLnNvdXJjZSA9IHNvdXJjZXMuaW5kZXhPZihzcmNNYXBwaW5nLnNvdXJjZSk7XG4gICAgICAgIGRlc3RNYXBwaW5nLm9yaWdpbmFsTGluZSA9IHNyY01hcHBpbmcub3JpZ2luYWxMaW5lO1xuICAgICAgICBkZXN0TWFwcGluZy5vcmlnaW5hbENvbHVtbiA9IHNyY01hcHBpbmcub3JpZ2luYWxDb2x1bW47XG5cbiAgICAgICAgaWYgKHNyY01hcHBpbmcubmFtZSkge1xuICAgICAgICAgIGRlc3RNYXBwaW5nLm5hbWUgPSBuYW1lcy5pbmRleE9mKHNyY01hcHBpbmcubmFtZSk7XG4gICAgICAgIH1cblxuICAgICAgICBkZXN0T3JpZ2luYWxNYXBwaW5ncy5wdXNoKGRlc3RNYXBwaW5nKTtcbiAgICAgIH1cblxuICAgICAgZGVzdEdlbmVyYXRlZE1hcHBpbmdzLnB1c2goZGVzdE1hcHBpbmcpO1xuICAgIH1cblxuICAgIHF1aWNrU29ydChzbWMuX19vcmlnaW5hbE1hcHBpbmdzLCB1dGlsLmNvbXBhcmVCeU9yaWdpbmFsUG9zaXRpb25zKTtcblxuICAgIHJldHVybiBzbWM7XG4gIH07XG5cbi8qKlxuICogVGhlIHZlcnNpb24gb2YgdGhlIHNvdXJjZSBtYXBwaW5nIHNwZWMgdGhhdCB3ZSBhcmUgY29uc3VtaW5nLlxuICovXG5CYXNpY1NvdXJjZU1hcENvbnN1bWVyLnByb3RvdHlwZS5fdmVyc2lvbiA9IDM7XG5cbi8qKlxuICogVGhlIGxpc3Qgb2Ygb3JpZ2luYWwgc291cmNlcy5cbiAqL1xuT2JqZWN0LmRlZmluZVByb3BlcnR5KEJhc2ljU291cmNlTWFwQ29uc3VtZXIucHJvdG90eXBlLCAnc291cmNlcycsIHtcbiAgZ2V0OiBmdW5jdGlvbiAoKSB7XG4gICAgcmV0dXJuIHRoaXMuX2Fic29sdXRlU291cmNlcy5zbGljZSgpO1xuICB9XG59KTtcblxuLyoqXG4gKiBQcm92aWRlIHRoZSBKSVQgd2l0aCBhIG5pY2Ugc2hhcGUgLyBoaWRkZW4gY2xhc3MuXG4gKi9cbmZ1bmN0aW9uIE1hcHBpbmcoKSB7XG4gIHRoaXMuZ2VuZXJhdGVkTGluZSA9IDA7XG4gIHRoaXMuZ2VuZXJhdGVkQ29sdW1uID0gMDtcbiAgdGhpcy5zb3VyY2UgPSBudWxsO1xuICB0aGlzLm9yaWdpbmFsTGluZSA9IG51bGw7XG4gIHRoaXMub3JpZ2luYWxDb2x1bW4gPSBudWxsO1xuICB0aGlzLm5hbWUgPSBudWxsO1xufVxuXG4vKipcbiAqIFBhcnNlIHRoZSBtYXBwaW5ncyBpbiBhIHN0cmluZyBpbiB0byBhIGRhdGEgc3RydWN0dXJlIHdoaWNoIHdlIGNhbiBlYXNpbHlcbiAqIHF1ZXJ5ICh0aGUgb3JkZXJlZCBhcnJheXMgaW4gdGhlIGB0aGlzLl9fZ2VuZXJhdGVkTWFwcGluZ3NgIGFuZFxuICogYHRoaXMuX19vcmlnaW5hbE1hcHBpbmdzYCBwcm9wZXJ0aWVzKS5cbiAqL1xuQmFzaWNTb3VyY2VNYXBDb25zdW1lci5wcm90b3R5cGUuX3BhcnNlTWFwcGluZ3MgPVxuICBmdW5jdGlvbiBTb3VyY2VNYXBDb25zdW1lcl9wYXJzZU1hcHBpbmdzKGFTdHIsIGFTb3VyY2VSb290KSB7XG4gICAgdmFyIGdlbmVyYXRlZExpbmUgPSAxO1xuICAgIHZhciBwcmV2aW91c0dlbmVyYXRlZENvbHVtbiA9IDA7XG4gICAgdmFyIHByZXZpb3VzT3JpZ2luYWxMaW5lID0gMDtcbiAgICB2YXIgcHJldmlvdXNPcmlnaW5hbENvbHVtbiA9IDA7XG4gICAgdmFyIHByZXZpb3VzU291cmNlID0gMDtcbiAgICB2YXIgcHJldmlvdXNOYW1lID0gMDtcbiAgICB2YXIgbGVuZ3RoID0gYVN0ci5sZW5ndGg7XG4gICAgdmFyIGluZGV4ID0gMDtcbiAgICB2YXIgY2FjaGVkU2VnbWVudHMgPSB7fTtcbiAgICB2YXIgdGVtcCA9IHt9O1xuICAgIHZhciBvcmlnaW5hbE1hcHBpbmdzID0gW107XG4gICAgdmFyIGdlbmVyYXRlZE1hcHBpbmdzID0gW107XG4gICAgdmFyIG1hcHBpbmcsIHN0ciwgc2VnbWVudCwgZW5kLCB2YWx1ZTtcblxuICAgIHdoaWxlIChpbmRleCA8IGxlbmd0aCkge1xuICAgICAgaWYgKGFTdHIuY2hhckF0KGluZGV4KSA9PT0gJzsnKSB7XG4gICAgICAgIGdlbmVyYXRlZExpbmUrKztcbiAgICAgICAgaW5kZXgrKztcbiAgICAgICAgcHJldmlvdXNHZW5lcmF0ZWRDb2x1bW4gPSAwO1xuICAgICAgfVxuICAgICAgZWxzZSBpZiAoYVN0ci5jaGFyQXQoaW5kZXgpID09PSAnLCcpIHtcbiAgICAgICAgaW5kZXgrKztcbiAgICAgIH1cbiAgICAgIGVsc2Uge1xuICAgICAgICBtYXBwaW5nID0gbmV3IE1hcHBpbmcoKTtcbiAgICAgICAgbWFwcGluZy5nZW5lcmF0ZWRMaW5lID0gZ2VuZXJhdGVkTGluZTtcblxuICAgICAgICAvLyBCZWNhdXNlIGVhY2ggb2Zmc2V0IGlzIGVuY29kZWQgcmVsYXRpdmUgdG8gdGhlIHByZXZpb3VzIG9uZSxcbiAgICAgICAgLy8gbWFueSBzZWdtZW50cyBvZnRlbiBoYXZlIHRoZSBzYW1lIGVuY29kaW5nLiBXZSBjYW4gZXhwbG9pdCB0aGlzXG4gICAgICAgIC8vIGZhY3QgYnkgY2FjaGluZyB0aGUgcGFyc2VkIHZhcmlhYmxlIGxlbmd0aCBmaWVsZHMgb2YgZWFjaCBzZWdtZW50LFxuICAgICAgICAvLyBhbGxvd2luZyB1cyB0byBhdm9pZCBhIHNlY29uZCBwYXJzZSBpZiB3ZSBlbmNvdW50ZXIgdGhlIHNhbWVcbiAgICAgICAgLy8gc2VnbWVudCBhZ2Fpbi5cbiAgICAgICAgZm9yIChlbmQgPSBpbmRleDsgZW5kIDwgbGVuZ3RoOyBlbmQrKykge1xuICAgICAgICAgIGlmICh0aGlzLl9jaGFySXNNYXBwaW5nU2VwYXJhdG9yKGFTdHIsIGVuZCkpIHtcbiAgICAgICAgICAgIGJyZWFrO1xuICAgICAgICAgIH1cbiAgICAgICAgfVxuICAgICAgICBzdHIgPSBhU3RyLnNsaWNlKGluZGV4LCBlbmQpO1xuXG4gICAgICAgIHNlZ21lbnQgPSBjYWNoZWRTZWdtZW50c1tzdHJdO1xuICAgICAgICBpZiAoc2VnbWVudCkge1xuICAgICAgICAgIGluZGV4ICs9IHN0ci5sZW5ndGg7XG4gICAgICAgIH0gZWxzZSB7XG4gICAgICAgICAgc2VnbWVudCA9IFtdO1xuICAgICAgICAgIHdoaWxlIChpbmRleCA8IGVuZCkge1xuICAgICAgICAgICAgYmFzZTY0VkxRLmRlY29kZShhU3RyLCBpbmRleCwgdGVtcCk7XG4gICAgICAgICAgICB2YWx1ZSA9IHRlbXAudmFsdWU7XG4gICAgICAgICAgICBpbmRleCA9IHRlbXAucmVzdDtcbiAgICAgICAgICAgIHNlZ21lbnQucHVzaCh2YWx1ZSk7XG4gICAgICAgICAgfVxuXG4gICAgICAgICAgaWYgKHNlZ21lbnQubGVuZ3RoID09PSAyKSB7XG4gICAgICAgICAgICB0aHJvdyBuZXcgRXJyb3IoJ0ZvdW5kIGEgc291cmNlLCBidXQgbm8gbGluZSBhbmQgY29sdW1uJyk7XG4gICAgICAgICAgfVxuXG4gICAgICAgICAgaWYgKHNlZ21lbnQubGVuZ3RoID09PSAzKSB7XG4gICAgICAgICAgICB0aHJvdyBuZXcgRXJyb3IoJ0ZvdW5kIGEgc291cmNlIGFuZCBsaW5lLCBidXQgbm8gY29sdW1uJyk7XG4gICAgICAgICAgfVxuXG4gICAgICAgICAgY2FjaGVkU2VnbWVudHNbc3RyXSA9IHNlZ21lbnQ7XG4gICAgICAgIH1cblxuICAgICAgICAvLyBHZW5lcmF0ZWQgY29sdW1uLlxuICAgICAgICBtYXBwaW5nLmdlbmVyYXRlZENvbHVtbiA9IHByZXZpb3VzR2VuZXJhdGVkQ29sdW1uICsgc2VnbWVudFswXTtcbiAgICAgICAgcHJldmlvdXNHZW5lcmF0ZWRDb2x1bW4gPSBtYXBwaW5nLmdlbmVyYXRlZENvbHVtbjtcblxuICAgICAgICBpZiAoc2VnbWVudC5sZW5ndGggPiAxKSB7XG4gICAgICAgICAgLy8gT3JpZ2luYWwgc291cmNlLlxuICAgICAgICAgIG1hcHBpbmcuc291cmNlID0gcHJldmlvdXNTb3VyY2UgKyBzZWdtZW50WzFdO1xuICAgICAgICAgIHByZXZpb3VzU291cmNlICs9IHNlZ21lbnRbMV07XG5cbiAgICAgICAgICAvLyBPcmlnaW5hbCBsaW5lLlxuICAgICAgICAgIG1hcHBpbmcub3JpZ2luYWxMaW5lID0gcHJldmlvdXNPcmlnaW5hbExpbmUgKyBzZWdtZW50WzJdO1xuICAgICAgICAgIHByZXZpb3VzT3JpZ2luYWxMaW5lID0gbWFwcGluZy5vcmlnaW5hbExpbmU7XG4gICAgICAgICAgLy8gTGluZXMgYXJlIHN0b3JlZCAwLWJhc2VkXG4gICAgICAgICAgbWFwcGluZy5vcmlnaW5hbExpbmUgKz0gMTtcblxuICAgICAgICAgIC8vIE9yaWdpbmFsIGNvbHVtbi5cbiAgICAgICAgICBtYXBwaW5nLm9yaWdpbmFsQ29sdW1uID0gcHJldmlvdXNPcmlnaW5hbENvbHVtbiArIHNlZ21lbnRbM107XG4gICAgICAgICAgcHJldmlvdXNPcmlnaW5hbENvbHVtbiA9IG1hcHBpbmcub3JpZ2luYWxDb2x1bW47XG5cbiAgICAgICAgICBpZiAoc2VnbWVudC5sZW5ndGggPiA0KSB7XG4gICAgICAgICAgICAvLyBPcmlnaW5hbCBuYW1lLlxuICAgICAgICAgICAgbWFwcGluZy5uYW1lID0gcHJldmlvdXNOYW1lICsgc2VnbWVudFs0XTtcbiAgICAgICAgICAgIHByZXZpb3VzTmFtZSArPSBzZWdtZW50WzRdO1xuICAgICAgICAgIH1cbiAgICAgICAgfVxuXG4gICAgICAgIGdlbmVyYXRlZE1hcHBpbmdzLnB1c2gobWFwcGluZyk7XG4gICAgICAgIGlmICh0eXBlb2YgbWFwcGluZy5vcmlnaW5hbExpbmUgPT09ICdudW1iZXInKSB7XG4gICAgICAgICAgb3JpZ2luYWxNYXBwaW5ncy5wdXNoKG1hcHBpbmcpO1xuICAgICAgICB9XG4gICAgICB9XG4gICAgfVxuXG4gICAgcXVpY2tTb3J0KGdlbmVyYXRlZE1hcHBpbmdzLCB1dGlsLmNvbXBhcmVCeUdlbmVyYXRlZFBvc2l0aW9uc0RlZmxhdGVkKTtcbiAgICB0aGlzLl9fZ2VuZXJhdGVkTWFwcGluZ3MgPSBnZW5lcmF0ZWRNYXBwaW5ncztcblxuICAgIHF1aWNrU29ydChvcmlnaW5hbE1hcHBpbmdzLCB1dGlsLmNvbXBhcmVCeU9yaWdpbmFsUG9zaXRpb25zKTtcbiAgICB0aGlzLl9fb3JpZ2luYWxNYXBwaW5ncyA9IG9yaWdpbmFsTWFwcGluZ3M7XG4gIH07XG5cbi8qKlxuICogRmluZCB0aGUgbWFwcGluZyB0aGF0IGJlc3QgbWF0Y2hlcyB0aGUgaHlwb3RoZXRpY2FsIFwibmVlZGxlXCIgbWFwcGluZyB0aGF0XG4gKiB3ZSBhcmUgc2VhcmNoaW5nIGZvciBpbiB0aGUgZ2l2ZW4gXCJoYXlzdGFja1wiIG9mIG1hcHBpbmdzLlxuICovXG5CYXNpY1NvdXJjZU1hcENvbnN1bWVyLnByb3RvdHlwZS5fZmluZE1hcHBpbmcgPVxuICBmdW5jdGlvbiBTb3VyY2VNYXBDb25zdW1lcl9maW5kTWFwcGluZyhhTmVlZGxlLCBhTWFwcGluZ3MsIGFMaW5lTmFtZSxcbiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgYUNvbHVtbk5hbWUsIGFDb21wYXJhdG9yLCBhQmlhcykge1xuICAgIC8vIFRvIHJldHVybiB0aGUgcG9zaXRpb24gd2UgYXJlIHNlYXJjaGluZyBmb3IsIHdlIG11c3QgZmlyc3QgZmluZCB0aGVcbiAgICAvLyBtYXBwaW5nIGZvciB0aGUgZ2l2ZW4gcG9zaXRpb24gYW5kIHRoZW4gcmV0dXJuIHRoZSBvcHBvc2l0ZSBwb3NpdGlvbiBpdFxuICAgIC8vIHBvaW50cyB0by4gQmVjYXVzZSB0aGUgbWFwcGluZ3MgYXJlIHNvcnRlZCwgd2UgY2FuIHVzZSBiaW5hcnkgc2VhcmNoIHRvXG4gICAgLy8gZmluZCB0aGUgYmVzdCBtYXBwaW5nLlxuXG4gICAgaWYgKGFOZWVkbGVbYUxpbmVOYW1lXSA8PSAwKSB7XG4gICAgICB0aHJvdyBuZXcgVHlwZUVycm9yKCdMaW5lIG11c3QgYmUgZ3JlYXRlciB0aGFuIG9yIGVxdWFsIHRvIDEsIGdvdCAnXG4gICAgICAgICAgICAgICAgICAgICAgICAgICsgYU5lZWRsZVthTGluZU5hbWVdKTtcbiAgICB9XG4gICAgaWYgKGFOZWVkbGVbYUNvbHVtbk5hbWVdIDwgMCkge1xuICAgICAgdGhyb3cgbmV3IFR5cGVFcnJvcignQ29sdW1uIG11c3QgYmUgZ3JlYXRlciB0aGFuIG9yIGVxdWFsIHRvIDAsIGdvdCAnXG4gICAgICAgICAgICAgICAgICAgICAgICAgICsgYU5lZWRsZVthQ29sdW1uTmFtZV0pO1xuICAgIH1cblxuICAgIHJldHVybiBiaW5hcnlTZWFyY2guc2VhcmNoKGFOZWVkbGUsIGFNYXBwaW5ncywgYUNvbXBhcmF0b3IsIGFCaWFzKTtcbiAgfTtcblxuLyoqXG4gKiBDb21wdXRlIHRoZSBsYXN0IGNvbHVtbiBmb3IgZWFjaCBnZW5lcmF0ZWQgbWFwcGluZy4gVGhlIGxhc3QgY29sdW1uIGlzXG4gKiBpbmNsdXNpdmUuXG4gKi9cbkJhc2ljU291cmNlTWFwQ29uc3VtZXIucHJvdG90eXBlLmNvbXB1dGVDb2x1bW5TcGFucyA9XG4gIGZ1bmN0aW9uIFNvdXJjZU1hcENvbnN1bWVyX2NvbXB1dGVDb2x1bW5TcGFucygpIHtcbiAgICBmb3IgKHZhciBpbmRleCA9IDA7IGluZGV4IDwgdGhpcy5fZ2VuZXJhdGVkTWFwcGluZ3MubGVuZ3RoOyArK2luZGV4KSB7XG4gICAgICB2YXIgbWFwcGluZyA9IHRoaXMuX2dlbmVyYXRlZE1hcHBpbmdzW2luZGV4XTtcblxuICAgICAgLy8gTWFwcGluZ3MgZG8gbm90IGNvbnRhaW4gYSBmaWVsZCBmb3IgdGhlIGxhc3QgZ2VuZXJhdGVkIGNvbHVtbnQuIFdlXG4gICAgICAvLyBjYW4gY29tZSB1cCB3aXRoIGFuIG9wdGltaXN0aWMgZXN0aW1hdGUsIGhvd2V2ZXIsIGJ5IGFzc3VtaW5nIHRoYXRcbiAgICAgIC8vIG1hcHBpbmdzIGFyZSBjb250aWd1b3VzIChpLmUuIGdpdmVuIHR3byBjb25zZWN1dGl2ZSBtYXBwaW5ncywgdGhlXG4gICAgICAvLyBmaXJzdCBtYXBwaW5nIGVuZHMgd2hlcmUgdGhlIHNlY29uZCBvbmUgc3RhcnRzKS5cbiAgICAgIGlmIChpbmRleCArIDEgPCB0aGlzLl9nZW5lcmF0ZWRNYXBwaW5ncy5sZW5ndGgpIHtcbiAgICAgICAgdmFyIG5leHRNYXBwaW5nID0gdGhpcy5fZ2VuZXJhdGVkTWFwcGluZ3NbaW5kZXggKyAxXTtcblxuICAgICAgICBpZiAobWFwcGluZy5nZW5lcmF0ZWRMaW5lID09PSBuZXh0TWFwcGluZy5nZW5lcmF0ZWRMaW5lKSB7XG4gICAgICAgICAgbWFwcGluZy5sYXN0R2VuZXJhdGVkQ29sdW1uID0gbmV4dE1hcHBpbmcuZ2VuZXJhdGVkQ29sdW1uIC0gMTtcbiAgICAgICAgICBjb250aW51ZTtcbiAgICAgICAgfVxuICAgICAgfVxuXG4gICAgICAvLyBUaGUgbGFzdCBtYXBwaW5nIGZvciBlYWNoIGxpbmUgc3BhbnMgdGhlIGVudGlyZSBsaW5lLlxuICAgICAgbWFwcGluZy5sYXN0R2VuZXJhdGVkQ29sdW1uID0gSW5maW5pdHk7XG4gICAgfVxuICB9O1xuXG4vKipcbiAqIFJldHVybnMgdGhlIG9yaWdpbmFsIHNvdXJjZSwgbGluZSwgYW5kIGNvbHVtbiBpbmZvcm1hdGlvbiBmb3IgdGhlIGdlbmVyYXRlZFxuICogc291cmNlJ3MgbGluZSBhbmQgY29sdW1uIHBvc2l0aW9ucyBwcm92aWRlZC4gVGhlIG9ubHkgYXJndW1lbnQgaXMgYW4gb2JqZWN0XG4gKiB3aXRoIHRoZSBmb2xsb3dpbmcgcHJvcGVydGllczpcbiAqXG4gKiAgIC0gbGluZTogVGhlIGxpbmUgbnVtYmVyIGluIHRoZSBnZW5lcmF0ZWQgc291cmNlLiAgVGhlIGxpbmUgbnVtYmVyXG4gKiAgICAgaXMgMS1iYXNlZC5cbiAqICAgLSBjb2x1bW46IFRoZSBjb2x1bW4gbnVtYmVyIGluIHRoZSBnZW5lcmF0ZWQgc291cmNlLiAgVGhlIGNvbHVtblxuICogICAgIG51bWJlciBpcyAwLWJhc2VkLlxuICogICAtIGJpYXM6IEVpdGhlciAnU291cmNlTWFwQ29uc3VtZXIuR1JFQVRFU1RfTE9XRVJfQk9VTkQnIG9yXG4gKiAgICAgJ1NvdXJjZU1hcENvbnN1bWVyLkxFQVNUX1VQUEVSX0JPVU5EJy4gU3BlY2lmaWVzIHdoZXRoZXIgdG8gcmV0dXJuIHRoZVxuICogICAgIGNsb3Nlc3QgZWxlbWVudCB0aGF0IGlzIHNtYWxsZXIgdGhhbiBvciBncmVhdGVyIHRoYW4gdGhlIG9uZSB3ZSBhcmVcbiAqICAgICBzZWFyY2hpbmcgZm9yLCByZXNwZWN0aXZlbHksIGlmIHRoZSBleGFjdCBlbGVtZW50IGNhbm5vdCBiZSBmb3VuZC5cbiAqICAgICBEZWZhdWx0cyB0byAnU291cmNlTWFwQ29uc3VtZXIuR1JFQVRFU1RfTE9XRVJfQk9VTkQnLlxuICpcbiAqIGFuZCBhbiBvYmplY3QgaXMgcmV0dXJuZWQgd2l0aCB0aGUgZm9sbG93aW5nIHByb3BlcnRpZXM6XG4gKlxuICogICAtIHNvdXJjZTogVGhlIG9yaWdpbmFsIHNvdXJjZSBmaWxlLCBvciBudWxsLlxuICogICAtIGxpbmU6IFRoZSBsaW5lIG51bWJlciBpbiB0aGUgb3JpZ2luYWwgc291cmNlLCBvciBudWxsLiAgVGhlXG4gKiAgICAgbGluZSBudW1iZXIgaXMgMS1iYXNlZC5cbiAqICAgLSBjb2x1bW46IFRoZSBjb2x1bW4gbnVtYmVyIGluIHRoZSBvcmlnaW5hbCBzb3VyY2UsIG9yIG51bGwuICBUaGVcbiAqICAgICBjb2x1bW4gbnVtYmVyIGlzIDAtYmFzZWQuXG4gKiAgIC0gbmFtZTogVGhlIG9yaWdpbmFsIGlkZW50aWZpZXIsIG9yIG51bGwuXG4gKi9cbkJhc2ljU291cmNlTWFwQ29uc3VtZXIucHJvdG90eXBlLm9yaWdpbmFsUG9zaXRpb25Gb3IgPVxuICBmdW5jdGlvbiBTb3VyY2VNYXBDb25zdW1lcl9vcmlnaW5hbFBvc2l0aW9uRm9yKGFBcmdzKSB7XG4gICAgdmFyIG5lZWRsZSA9IHtcbiAgICAgIGdlbmVyYXRlZExpbmU6IHV0aWwuZ2V0QXJnKGFBcmdzLCAnbGluZScpLFxuICAgICAgZ2VuZXJhdGVkQ29sdW1uOiB1dGlsLmdldEFyZyhhQXJncywgJ2NvbHVtbicpXG4gICAgfTtcblxuICAgIHZhciBpbmRleCA9IHRoaXMuX2ZpbmRNYXBwaW5nKFxuICAgICAgbmVlZGxlLFxuICAgICAgdGhpcy5fZ2VuZXJhdGVkTWFwcGluZ3MsXG4gICAgICBcImdlbmVyYXRlZExpbmVcIixcbiAgICAgIFwiZ2VuZXJhdGVkQ29sdW1uXCIsXG4gICAgICB1dGlsLmNvbXBhcmVCeUdlbmVyYXRlZFBvc2l0aW9uc0RlZmxhdGVkLFxuICAgICAgdXRpbC5nZXRBcmcoYUFyZ3MsICdiaWFzJywgU291cmNlTWFwQ29uc3VtZXIuR1JFQVRFU1RfTE9XRVJfQk9VTkQpXG4gICAgKTtcblxuICAgIGlmIChpbmRleCA+PSAwKSB7XG4gICAgICB2YXIgbWFwcGluZyA9IHRoaXMuX2dlbmVyYXRlZE1hcHBpbmdzW2luZGV4XTtcblxuICAgICAgaWYgKG1hcHBpbmcuZ2VuZXJhdGVkTGluZSA9PT0gbmVlZGxlLmdlbmVyYXRlZExpbmUpIHtcbiAgICAgICAgdmFyIHNvdXJjZSA9IHV0aWwuZ2V0QXJnKG1hcHBpbmcsICdzb3VyY2UnLCBudWxsKTtcbiAgICAgICAgaWYgKHNvdXJjZSAhPT0gbnVsbCkge1xuICAgICAgICAgIHNvdXJjZSA9IHRoaXMuX3NvdXJjZXMuYXQoc291cmNlKTtcbiAgICAgICAgICBzb3VyY2UgPSB1dGlsLmNvbXB1dGVTb3VyY2VVUkwodGhpcy5zb3VyY2VSb290LCBzb3VyY2UsIHRoaXMuX3NvdXJjZU1hcFVSTCk7XG4gICAgICAgIH1cbiAgICAgICAgdmFyIG5hbWUgPSB1dGlsLmdldEFyZyhtYXBwaW5nLCAnbmFtZScsIG51bGwpO1xuICAgICAgICBpZiAobmFtZSAhPT0gbnVsbCkge1xuICAgICAgICAgIG5hbWUgPSB0aGlzLl9uYW1lcy5hdChuYW1lKTtcbiAgICAgICAgfVxuICAgICAgICByZXR1cm4ge1xuICAgICAgICAgIHNvdXJjZTogc291cmNlLFxuICAgICAgICAgIGxpbmU6IHV0aWwuZ2V0QXJnKG1hcHBpbmcsICdvcmlnaW5hbExpbmUnLCBudWxsKSxcbiAgICAgICAgICBjb2x1bW46IHV0aWwuZ2V0QXJnKG1hcHBpbmcsICdvcmlnaW5hbENvbHVtbicsIG51bGwpLFxuICAgICAgICAgIG5hbWU6IG5hbWVcbiAgICAgICAgfTtcbiAgICAgIH1cbiAgICB9XG5cbiAgICByZXR1cm4ge1xuICAgICAgc291cmNlOiBudWxsLFxuICAgICAgbGluZTogbnVsbCxcbiAgICAgIGNvbHVtbjogbnVsbCxcbiAgICAgIG5hbWU6IG51bGxcbiAgICB9O1xuICB9O1xuXG4vKipcbiAqIFJldHVybiB0cnVlIGlmIHdlIGhhdmUgdGhlIHNvdXJjZSBjb250ZW50IGZvciBldmVyeSBzb3VyY2UgaW4gdGhlIHNvdXJjZVxuICogbWFwLCBmYWxzZSBvdGhlcndpc2UuXG4gKi9cbkJhc2ljU291cmNlTWFwQ29uc3VtZXIucHJvdG90eXBlLmhhc0NvbnRlbnRzT2ZBbGxTb3VyY2VzID1cbiAgZnVuY3Rpb24gQmFzaWNTb3VyY2VNYXBDb25zdW1lcl9oYXNDb250ZW50c09mQWxsU291cmNlcygpIHtcbiAgICBpZiAoIXRoaXMuc291cmNlc0NvbnRlbnQpIHtcbiAgICAgIHJldHVybiBmYWxzZTtcbiAgICB9XG4gICAgcmV0dXJuIHRoaXMuc291cmNlc0NvbnRlbnQubGVuZ3RoID49IHRoaXMuX3NvdXJjZXMuc2l6ZSgpICYmXG4gICAgICAhdGhpcy5zb3VyY2VzQ29udGVudC5zb21lKGZ1bmN0aW9uIChzYykgeyByZXR1cm4gc2MgPT0gbnVsbDsgfSk7XG4gIH07XG5cbi8qKlxuICogUmV0dXJucyB0aGUgb3JpZ2luYWwgc291cmNlIGNvbnRlbnQuIFRoZSBvbmx5IGFyZ3VtZW50IGlzIHRoZSB1cmwgb2YgdGhlXG4gKiBvcmlnaW5hbCBzb3VyY2UgZmlsZS4gUmV0dXJucyBudWxsIGlmIG5vIG9yaWdpbmFsIHNvdXJjZSBjb250ZW50IGlzXG4gKiBhdmFpbGFibGUuXG4gKi9cbkJhc2ljU291cmNlTWFwQ29uc3VtZXIucHJvdG90eXBlLnNvdXJjZUNvbnRlbnRGb3IgPVxuICBmdW5jdGlvbiBTb3VyY2VNYXBDb25zdW1lcl9zb3VyY2VDb250ZW50Rm9yKGFTb3VyY2UsIG51bGxPbk1pc3NpbmcpIHtcbiAgICBpZiAoIXRoaXMuc291cmNlc0NvbnRlbnQpIHtcbiAgICAgIHJldHVybiBudWxsO1xuICAgIH1cblxuICAgIHZhciBpbmRleCA9IHRoaXMuX2ZpbmRTb3VyY2VJbmRleChhU291cmNlKTtcbiAgICBpZiAoaW5kZXggPj0gMCkge1xuICAgICAgcmV0dXJuIHRoaXMuc291cmNlc0NvbnRlbnRbaW5kZXhdO1xuICAgIH1cblxuICAgIHZhciByZWxhdGl2ZVNvdXJjZSA9IGFTb3VyY2U7XG4gICAgaWYgKHRoaXMuc291cmNlUm9vdCAhPSBudWxsKSB7XG4gICAgICByZWxhdGl2ZVNvdXJjZSA9IHV0aWwucmVsYXRpdmUodGhpcy5zb3VyY2VSb290LCByZWxhdGl2ZVNvdXJjZSk7XG4gICAgfVxuXG4gICAgdmFyIHVybDtcbiAgICBpZiAodGhpcy5zb3VyY2VSb290ICE9IG51bGxcbiAgICAgICAgJiYgKHVybCA9IHV0aWwudXJsUGFyc2UodGhpcy5zb3VyY2VSb290KSkpIHtcbiAgICAgIC8vIFhYWDogZmlsZTovLyBVUklzIGFuZCBhYnNvbHV0ZSBwYXRocyBsZWFkIHRvIHVuZXhwZWN0ZWQgYmVoYXZpb3IgZm9yXG4gICAgICAvLyBtYW55IHVzZXJzLiBXZSBjYW4gaGVscCB0aGVtIG91dCB3aGVuIHRoZXkgZXhwZWN0IGZpbGU6Ly8gVVJJcyB0b1xuICAgICAgLy8gYmVoYXZlIGxpa2UgaXQgd291bGQgaWYgdGhleSB3ZXJlIHJ1bm5pbmcgYSBsb2NhbCBIVFRQIHNlcnZlci4gU2VlXG4gICAgICAvLyBodHRwczovL2J1Z3ppbGxhLm1vemlsbGEub3JnL3Nob3dfYnVnLmNnaT9pZD04ODU1OTcuXG4gICAgICB2YXIgZmlsZVVyaUFic1BhdGggPSByZWxhdGl2ZVNvdXJjZS5yZXBsYWNlKC9eZmlsZTpcXC9cXC8vLCBcIlwiKTtcbiAgICAgIGlmICh1cmwuc2NoZW1lID09IFwiZmlsZVwiXG4gICAgICAgICAgJiYgdGhpcy5fc291cmNlcy5oYXMoZmlsZVVyaUFic1BhdGgpKSB7XG4gICAgICAgIHJldHVybiB0aGlzLnNvdXJjZXNDb250ZW50W3RoaXMuX3NvdXJjZXMuaW5kZXhPZihmaWxlVXJpQWJzUGF0aCldXG4gICAgICB9XG5cbiAgICAgIGlmICgoIXVybC5wYXRoIHx8IHVybC5wYXRoID09IFwiL1wiKVxuICAgICAgICAgICYmIHRoaXMuX3NvdXJjZXMuaGFzKFwiL1wiICsgcmVsYXRpdmVTb3VyY2UpKSB7XG4gICAgICAgIHJldHVybiB0aGlzLnNvdXJjZXNDb250ZW50W3RoaXMuX3NvdXJjZXMuaW5kZXhPZihcIi9cIiArIHJlbGF0aXZlU291cmNlKV07XG4gICAgICB9XG4gICAgfVxuXG4gICAgLy8gVGhpcyBmdW5jdGlvbiBpcyB1c2VkIHJlY3Vyc2l2ZWx5IGZyb21cbiAgICAvLyBJbmRleGVkU291cmNlTWFwQ29uc3VtZXIucHJvdG90eXBlLnNvdXJjZUNvbnRlbnRGb3IuIEluIHRoYXQgY2FzZSwgd2VcbiAgICAvLyBkb24ndCB3YW50IHRvIHRocm93IGlmIHdlIGNhbid0IGZpbmQgdGhlIHNvdXJjZSAtIHdlIGp1c3Qgd2FudCB0b1xuICAgIC8vIHJldHVybiBudWxsLCBzbyB3ZSBwcm92aWRlIGEgZmxhZyB0byBleGl0IGdyYWNlZnVsbHkuXG4gICAgaWYgKG51bGxPbk1pc3NpbmcpIHtcbiAgICAgIHJldHVybiBudWxsO1xuICAgIH1cbiAgICBlbHNlIHtcbiAgICAgIHRocm93IG5ldyBFcnJvcignXCInICsgcmVsYXRpdmVTb3VyY2UgKyAnXCIgaXMgbm90IGluIHRoZSBTb3VyY2VNYXAuJyk7XG4gICAgfVxuICB9O1xuXG4vKipcbiAqIFJldHVybnMgdGhlIGdlbmVyYXRlZCBsaW5lIGFuZCBjb2x1bW4gaW5mb3JtYXRpb24gZm9yIHRoZSBvcmlnaW5hbCBzb3VyY2UsXG4gKiBsaW5lLCBhbmQgY29sdW1uIHBvc2l0aW9ucyBwcm92aWRlZC4gVGhlIG9ubHkgYXJndW1lbnQgaXMgYW4gb2JqZWN0IHdpdGhcbiAqIHRoZSBmb2xsb3dpbmcgcHJvcGVydGllczpcbiAqXG4gKiAgIC0gc291cmNlOiBUaGUgZmlsZW5hbWUgb2YgdGhlIG9yaWdpbmFsIHNvdXJjZS5cbiAqICAgLSBsaW5lOiBUaGUgbGluZSBudW1iZXIgaW4gdGhlIG9yaWdpbmFsIHNvdXJjZS4gIFRoZSBsaW5lIG51bWJlclxuICogICAgIGlzIDEtYmFzZWQuXG4gKiAgIC0gY29sdW1uOiBUaGUgY29sdW1uIG51bWJlciBpbiB0aGUgb3JpZ2luYWwgc291cmNlLiAgVGhlIGNvbHVtblxuICogICAgIG51bWJlciBpcyAwLWJhc2VkLlxuICogICAtIGJpYXM6IEVpdGhlciAnU291cmNlTWFwQ29uc3VtZXIuR1JFQVRFU1RfTE9XRVJfQk9VTkQnIG9yXG4gKiAgICAgJ1NvdXJjZU1hcENvbnN1bWVyLkxFQVNUX1VQUEVSX0JPVU5EJy4gU3BlY2lmaWVzIHdoZXRoZXIgdG8gcmV0dXJuIHRoZVxuICogICAgIGNsb3Nlc3QgZWxlbWVudCB0aGF0IGlzIHNtYWxsZXIgdGhhbiBvciBncmVhdGVyIHRoYW4gdGhlIG9uZSB3ZSBhcmVcbiAqICAgICBzZWFyY2hpbmcgZm9yLCByZXNwZWN0aXZlbHksIGlmIHRoZSBleGFjdCBlbGVtZW50IGNhbm5vdCBiZSBmb3VuZC5cbiAqICAgICBEZWZhdWx0cyB0byAnU291cmNlTWFwQ29uc3VtZXIuR1JFQVRFU1RfTE9XRVJfQk9VTkQnLlxuICpcbiAqIGFuZCBhbiBvYmplY3QgaXMgcmV0dXJuZWQgd2l0aCB0aGUgZm9sbG93aW5nIHByb3BlcnRpZXM6XG4gKlxuICogICAtIGxpbmU6IFRoZSBsaW5lIG51bWJlciBpbiB0aGUgZ2VuZXJhdGVkIHNvdXJjZSwgb3IgbnVsbC4gIFRoZVxuICogICAgIGxpbmUgbnVtYmVyIGlzIDEtYmFzZWQuXG4gKiAgIC0gY29sdW1uOiBUaGUgY29sdW1uIG51bWJlciBpbiB0aGUgZ2VuZXJhdGVkIHNvdXJjZSwgb3IgbnVsbC5cbiAqICAgICBUaGUgY29sdW1uIG51bWJlciBpcyAwLWJhc2VkLlxuICovXG5CYXNpY1NvdXJjZU1hcENvbnN1bWVyLnByb3RvdHlwZS5nZW5lcmF0ZWRQb3NpdGlvbkZvciA9XG4gIGZ1bmN0aW9uIFNvdXJjZU1hcENvbnN1bWVyX2dlbmVyYXRlZFBvc2l0aW9uRm9yKGFBcmdzKSB7XG4gICAgdmFyIHNvdXJjZSA9IHV0aWwuZ2V0QXJnKGFBcmdzLCAnc291cmNlJyk7XG4gICAgc291cmNlID0gdGhpcy5fZmluZFNvdXJjZUluZGV4KHNvdXJjZSk7XG4gICAgaWYgKHNvdXJjZSA8IDApIHtcbiAgICAgIHJldHVybiB7XG4gICAgICAgIGxpbmU6IG51bGwsXG4gICAgICAgIGNvbHVtbjogbnVsbCxcbiAgICAgICAgbGFzdENvbHVtbjogbnVsbFxuICAgICAgfTtcbiAgICB9XG5cbiAgICB2YXIgbmVlZGxlID0ge1xuICAgICAgc291cmNlOiBzb3VyY2UsXG4gICAgICBvcmlnaW5hbExpbmU6IHV0aWwuZ2V0QXJnKGFBcmdzLCAnbGluZScpLFxuICAgICAgb3JpZ2luYWxDb2x1bW46IHV0aWwuZ2V0QXJnKGFBcmdzLCAnY29sdW1uJylcbiAgICB9O1xuXG4gICAgdmFyIGluZGV4ID0gdGhpcy5fZmluZE1hcHBpbmcoXG4gICAgICBuZWVkbGUsXG4gICAgICB0aGlzLl9vcmlnaW5hbE1hcHBpbmdzLFxuICAgICAgXCJvcmlnaW5hbExpbmVcIixcbiAgICAgIFwib3JpZ2luYWxDb2x1bW5cIixcbiAgICAgIHV0aWwuY29tcGFyZUJ5T3JpZ2luYWxQb3NpdGlvbnMsXG4gICAgICB1dGlsLmdldEFyZyhhQXJncywgJ2JpYXMnLCBTb3VyY2VNYXBDb25zdW1lci5HUkVBVEVTVF9MT1dFUl9CT1VORClcbiAgICApO1xuXG4gICAgaWYgKGluZGV4ID49IDApIHtcbiAgICAgIHZhciBtYXBwaW5nID0gdGhpcy5fb3JpZ2luYWxNYXBwaW5nc1tpbmRleF07XG5cbiAgICAgIGlmIChtYXBwaW5nLnNvdXJjZSA9PT0gbmVlZGxlLnNvdXJjZSkge1xuICAgICAgICByZXR1cm4ge1xuICAgICAgICAgIGxpbmU6IHV0aWwuZ2V0QXJnKG1hcHBpbmcsICdnZW5lcmF0ZWRMaW5lJywgbnVsbCksXG4gICAgICAgICAgY29sdW1uOiB1dGlsLmdldEFyZyhtYXBwaW5nLCAnZ2VuZXJhdGVkQ29sdW1uJywgbnVsbCksXG4gICAgICAgICAgbGFzdENvbHVtbjogdXRpbC5nZXRBcmcobWFwcGluZywgJ2xhc3RHZW5lcmF0ZWRDb2x1bW4nLCBudWxsKVxuICAgICAgICB9O1xuICAgICAgfVxuICAgIH1cblxuICAgIHJldHVybiB7XG4gICAgICBsaW5lOiBudWxsLFxuICAgICAgY29sdW1uOiBudWxsLFxuICAgICAgbGFzdENvbHVtbjogbnVsbFxuICAgIH07XG4gIH07XG5cbmV4cG9ydHMuQmFzaWNTb3VyY2VNYXBDb25zdW1lciA9IEJhc2ljU291cmNlTWFwQ29uc3VtZXI7XG5cbi8qKlxuICogQW4gSW5kZXhlZFNvdXJjZU1hcENvbnN1bWVyIGluc3RhbmNlIHJlcHJlc2VudHMgYSBwYXJzZWQgc291cmNlIG1hcCB3aGljaFxuICogd2UgY2FuIHF1ZXJ5IGZvciBpbmZvcm1hdGlvbi4gSXQgZGlmZmVycyBmcm9tIEJhc2ljU291cmNlTWFwQ29uc3VtZXIgaW5cbiAqIHRoYXQgaXQgdGFrZXMgXCJpbmRleGVkXCIgc291cmNlIG1hcHMgKGkuZS4gb25lcyB3aXRoIGEgXCJzZWN0aW9uc1wiIGZpZWxkKSBhc1xuICogaW5wdXQuXG4gKlxuICogVGhlIGZpcnN0IHBhcmFtZXRlciBpcyBhIHJhdyBzb3VyY2UgbWFwIChlaXRoZXIgYXMgYSBKU09OIHN0cmluZywgb3IgYWxyZWFkeVxuICogcGFyc2VkIHRvIGFuIG9iamVjdCkuIEFjY29yZGluZyB0byB0aGUgc3BlYyBmb3IgaW5kZXhlZCBzb3VyY2UgbWFwcywgdGhleVxuICogaGF2ZSB0aGUgZm9sbG93aW5nIGF0dHJpYnV0ZXM6XG4gKlxuICogICAtIHZlcnNpb246IFdoaWNoIHZlcnNpb24gb2YgdGhlIHNvdXJjZSBtYXAgc3BlYyB0aGlzIG1hcCBpcyBmb2xsb3dpbmcuXG4gKiAgIC0gZmlsZTogT3B0aW9uYWwuIFRoZSBnZW5lcmF0ZWQgZmlsZSB0aGlzIHNvdXJjZSBtYXAgaXMgYXNzb2NpYXRlZCB3aXRoLlxuICogICAtIHNlY3Rpb25zOiBBIGxpc3Qgb2Ygc2VjdGlvbiBkZWZpbml0aW9ucy5cbiAqXG4gKiBFYWNoIHZhbHVlIHVuZGVyIHRoZSBcInNlY3Rpb25zXCIgZmllbGQgaGFzIHR3byBmaWVsZHM6XG4gKiAgIC0gb2Zmc2V0OiBUaGUgb2Zmc2V0IGludG8gdGhlIG9yaWdpbmFsIHNwZWNpZmllZCBhdCB3aGljaCB0aGlzIHNlY3Rpb25cbiAqICAgICAgIGJlZ2lucyB0byBhcHBseSwgZGVmaW5lZCBhcyBhbiBvYmplY3Qgd2l0aCBhIFwibGluZVwiIGFuZCBcImNvbHVtblwiXG4gKiAgICAgICBmaWVsZC5cbiAqICAgLSBtYXA6IEEgc291cmNlIG1hcCBkZWZpbml0aW9uLiBUaGlzIHNvdXJjZSBtYXAgY291bGQgYWxzbyBiZSBpbmRleGVkLFxuICogICAgICAgYnV0IGRvZXNuJ3QgaGF2ZSB0byBiZS5cbiAqXG4gKiBJbnN0ZWFkIG9mIHRoZSBcIm1hcFwiIGZpZWxkLCBpdCdzIGFsc28gcG9zc2libGUgdG8gaGF2ZSBhIFwidXJsXCIgZmllbGRcbiAqIHNwZWNpZnlpbmcgYSBVUkwgdG8gcmV0cmlldmUgYSBzb3VyY2UgbWFwIGZyb20sIGJ1dCB0aGF0J3MgY3VycmVudGx5XG4gKiB1bnN1cHBvcnRlZC5cbiAqXG4gKiBIZXJlJ3MgYW4gZXhhbXBsZSBzb3VyY2UgbWFwLCB0YWtlbiBmcm9tIHRoZSBzb3VyY2UgbWFwIHNwZWNbMF0sIGJ1dFxuICogbW9kaWZpZWQgdG8gb21pdCBhIHNlY3Rpb24gd2hpY2ggdXNlcyB0aGUgXCJ1cmxcIiBmaWVsZC5cbiAqXG4gKiAge1xuICogICAgdmVyc2lvbiA6IDMsXG4gKiAgICBmaWxlOiBcImFwcC5qc1wiLFxuICogICAgc2VjdGlvbnM6IFt7XG4gKiAgICAgIG9mZnNldDoge2xpbmU6MTAwLCBjb2x1bW46MTB9LFxuICogICAgICBtYXA6IHtcbiAqICAgICAgICB2ZXJzaW9uIDogMyxcbiAqICAgICAgICBmaWxlOiBcInNlY3Rpb24uanNcIixcbiAqICAgICAgICBzb3VyY2VzOiBbXCJmb28uanNcIiwgXCJiYXIuanNcIl0sXG4gKiAgICAgICAgbmFtZXM6IFtcInNyY1wiLCBcIm1hcHNcIiwgXCJhcmVcIiwgXCJmdW5cIl0sXG4gKiAgICAgICAgbWFwcGluZ3M6IFwiQUFBQSxFOztBQkNERTtcIlxuICogICAgICB9XG4gKiAgICB9XSxcbiAqICB9XG4gKlxuICogVGhlIHNlY29uZCBwYXJhbWV0ZXIsIGlmIGdpdmVuLCBpcyBhIHN0cmluZyB3aG9zZSB2YWx1ZSBpcyB0aGUgVVJMXG4gKiBhdCB3aGljaCB0aGUgc291cmNlIG1hcCB3YXMgZm91bmQuICBUaGlzIFVSTCBpcyB1c2VkIHRvIGNvbXB1dGUgdGhlXG4gKiBzb3VyY2VzIGFycmF5LlxuICpcbiAqIFswXTogaHR0cHM6Ly9kb2NzLmdvb2dsZS5jb20vZG9jdW1lbnQvZC8xVTFSR0FlaFF3UnlwVVRvdkYxS1JscGlPRnplMGItXzJnYzZmQUgwS1kway9lZGl0I2hlYWRpbmc9aC41MzVlczN4ZXByZ3RcbiAqL1xuZnVuY3Rpb24gSW5kZXhlZFNvdXJjZU1hcENvbnN1bWVyKGFTb3VyY2VNYXAsIGFTb3VyY2VNYXBVUkwpIHtcbiAgdmFyIHNvdXJjZU1hcCA9IGFTb3VyY2VNYXA7XG4gIGlmICh0eXBlb2YgYVNvdXJjZU1hcCA9PT0gJ3N0cmluZycpIHtcbiAgICBzb3VyY2VNYXAgPSB1dGlsLnBhcnNlU291cmNlTWFwSW5wdXQoYVNvdXJjZU1hcCk7XG4gIH1cblxuICB2YXIgdmVyc2lvbiA9IHV0aWwuZ2V0QXJnKHNvdXJjZU1hcCwgJ3ZlcnNpb24nKTtcbiAgdmFyIHNlY3Rpb25zID0gdXRpbC5nZXRBcmcoc291cmNlTWFwLCAnc2VjdGlvbnMnKTtcblxuICBpZiAodmVyc2lvbiAhPSB0aGlzLl92ZXJzaW9uKSB7XG4gICAgdGhyb3cgbmV3IEVycm9yKCdVbnN1cHBvcnRlZCB2ZXJzaW9uOiAnICsgdmVyc2lvbik7XG4gIH1cblxuICB0aGlzLl9zb3VyY2VzID0gbmV3IEFycmF5U2V0KCk7XG4gIHRoaXMuX25hbWVzID0gbmV3IEFycmF5U2V0KCk7XG5cbiAgdmFyIGxhc3RPZmZzZXQgPSB7XG4gICAgbGluZTogLTEsXG4gICAgY29sdW1uOiAwXG4gIH07XG4gIHRoaXMuX3NlY3Rpb25zID0gc2VjdGlvbnMubWFwKGZ1bmN0aW9uIChzKSB7XG4gICAgaWYgKHMudXJsKSB7XG4gICAgICAvLyBUaGUgdXJsIGZpZWxkIHdpbGwgcmVxdWlyZSBzdXBwb3J0IGZvciBhc3luY2hyb25pY2l0eS5cbiAgICAgIC8vIFNlZSBodHRwczovL2dpdGh1Yi5jb20vbW96aWxsYS9zb3VyY2UtbWFwL2lzc3Vlcy8xNlxuICAgICAgdGhyb3cgbmV3IEVycm9yKCdTdXBwb3J0IGZvciB1cmwgZmllbGQgaW4gc2VjdGlvbnMgbm90IGltcGxlbWVudGVkLicpO1xuICAgIH1cbiAgICB2YXIgb2Zmc2V0ID0gdXRpbC5nZXRBcmcocywgJ29mZnNldCcpO1xuICAgIHZhciBvZmZzZXRMaW5lID0gdXRpbC5nZXRBcmcob2Zmc2V0LCAnbGluZScpO1xuICAgIHZhciBvZmZzZXRDb2x1bW4gPSB1dGlsLmdldEFyZyhvZmZzZXQsICdjb2x1bW4nKTtcblxuICAgIGlmIChvZmZzZXRMaW5lIDwgbGFzdE9mZnNldC5saW5lIHx8XG4gICAgICAgIChvZmZzZXRMaW5lID09PSBsYXN0T2Zmc2V0LmxpbmUgJiYgb2Zmc2V0Q29sdW1uIDwgbGFzdE9mZnNldC5jb2x1bW4pKSB7XG4gICAgICB0aHJvdyBuZXcgRXJyb3IoJ1NlY3Rpb24gb2Zmc2V0cyBtdXN0IGJlIG9yZGVyZWQgYW5kIG5vbi1vdmVybGFwcGluZy4nKTtcbiAgICB9XG4gICAgbGFzdE9mZnNldCA9IG9mZnNldDtcblxuICAgIHJldHVybiB7XG4gICAgICBnZW5lcmF0ZWRPZmZzZXQ6IHtcbiAgICAgICAgLy8gVGhlIG9mZnNldCBmaWVsZHMgYXJlIDAtYmFzZWQsIGJ1dCB3ZSB1c2UgMS1iYXNlZCBpbmRpY2VzIHdoZW5cbiAgICAgICAgLy8gZW5jb2RpbmcvZGVjb2RpbmcgZnJvbSBWTFEuXG4gICAgICAgIGdlbmVyYXRlZExpbmU6IG9mZnNldExpbmUgKyAxLFxuICAgICAgICBnZW5lcmF0ZWRDb2x1bW46IG9mZnNldENvbHVtbiArIDFcbiAgICAgIH0sXG4gICAgICBjb25zdW1lcjogbmV3IFNvdXJjZU1hcENvbnN1bWVyKHV0aWwuZ2V0QXJnKHMsICdtYXAnKSwgYVNvdXJjZU1hcFVSTClcbiAgICB9XG4gIH0pO1xufVxuXG5JbmRleGVkU291cmNlTWFwQ29uc3VtZXIucHJvdG90eXBlID0gT2JqZWN0LmNyZWF0ZShTb3VyY2VNYXBDb25zdW1lci5wcm90b3R5cGUpO1xuSW5kZXhlZFNvdXJjZU1hcENvbnN1bWVyLnByb3RvdHlwZS5jb25zdHJ1Y3RvciA9IFNvdXJjZU1hcENvbnN1bWVyO1xuXG4vKipcbiAqIFRoZSB2ZXJzaW9uIG9mIHRoZSBzb3VyY2UgbWFwcGluZyBzcGVjIHRoYXQgd2UgYXJlIGNvbnN1bWluZy5cbiAqL1xuSW5kZXhlZFNvdXJjZU1hcENvbnN1bWVyLnByb3RvdHlwZS5fdmVyc2lvbiA9IDM7XG5cbi8qKlxuICogVGhlIGxpc3Qgb2Ygb3JpZ2luYWwgc291cmNlcy5cbiAqL1xuT2JqZWN0LmRlZmluZVByb3BlcnR5KEluZGV4ZWRTb3VyY2VNYXBDb25zdW1lci5wcm90b3R5cGUsICdzb3VyY2VzJywge1xuICBnZXQ6IGZ1bmN0aW9uICgpIHtcbiAgICB2YXIgc291cmNlcyA9IFtdO1xuICAgIGZvciAodmFyIGkgPSAwOyBpIDwgdGhpcy5fc2VjdGlvbnMubGVuZ3RoOyBpKyspIHtcbiAgICAgIGZvciAodmFyIGogPSAwOyBqIDwgdGhpcy5fc2VjdGlvbnNbaV0uY29uc3VtZXIuc291cmNlcy5sZW5ndGg7IGorKykge1xuICAgICAgICBzb3VyY2VzLnB1c2godGhpcy5fc2VjdGlvbnNbaV0uY29uc3VtZXIuc291cmNlc1tqXSk7XG4gICAgICB9XG4gICAgfVxuICAgIHJldHVybiBzb3VyY2VzO1xuICB9XG59KTtcblxuLyoqXG4gKiBSZXR1cm5zIHRoZSBvcmlnaW5hbCBzb3VyY2UsIGxpbmUsIGFuZCBjb2x1bW4gaW5mb3JtYXRpb24gZm9yIHRoZSBnZW5lcmF0ZWRcbiAqIHNvdXJjZSdzIGxpbmUgYW5kIGNvbHVtbiBwb3NpdGlvbnMgcHJvdmlkZWQuIFRoZSBvbmx5IGFyZ3VtZW50IGlzIGFuIG9iamVjdFxuICogd2l0aCB0aGUgZm9sbG93aW5nIHByb3BlcnRpZXM6XG4gKlxuICogICAtIGxpbmU6IFRoZSBsaW5lIG51bWJlciBpbiB0aGUgZ2VuZXJhdGVkIHNvdXJjZS4gIFRoZSBsaW5lIG51bWJlclxuICogICAgIGlzIDEtYmFzZWQuXG4gKiAgIC0gY29sdW1uOiBUaGUgY29sdW1uIG51bWJlciBpbiB0aGUgZ2VuZXJhdGVkIHNvdXJjZS4gIFRoZSBjb2x1bW5cbiAqICAgICBudW1iZXIgaXMgMC1iYXNlZC5cbiAqXG4gKiBhbmQgYW4gb2JqZWN0IGlzIHJldHVybmVkIHdpdGggdGhlIGZvbGxvd2luZyBwcm9wZXJ0aWVzOlxuICpcbiAqICAgLSBzb3VyY2U6IFRoZSBvcmlnaW5hbCBzb3VyY2UgZmlsZSwgb3IgbnVsbC5cbiAqICAgLSBsaW5lOiBUaGUgbGluZSBudW1iZXIgaW4gdGhlIG9yaWdpbmFsIHNvdXJjZSwgb3IgbnVsbC4gIFRoZVxuICogICAgIGxpbmUgbnVtYmVyIGlzIDEtYmFzZWQuXG4gKiAgIC0gY29sdW1uOiBUaGUgY29sdW1uIG51bWJlciBpbiB0aGUgb3JpZ2luYWwgc291cmNlLCBvciBudWxsLiAgVGhlXG4gKiAgICAgY29sdW1uIG51bWJlciBpcyAwLWJhc2VkLlxuICogICAtIG5hbWU6IFRoZSBvcmlnaW5hbCBpZGVudGlmaWVyLCBvciBudWxsLlxuICovXG5JbmRleGVkU291cmNlTWFwQ29uc3VtZXIucHJvdG90eXBlLm9yaWdpbmFsUG9zaXRpb25Gb3IgPVxuICBmdW5jdGlvbiBJbmRleGVkU291cmNlTWFwQ29uc3VtZXJfb3JpZ2luYWxQb3NpdGlvbkZvcihhQXJncykge1xuICAgIHZhciBuZWVkbGUgPSB7XG4gICAgICBnZW5lcmF0ZWRMaW5lOiB1dGlsLmdldEFyZyhhQXJncywgJ2xpbmUnKSxcbiAgICAgIGdlbmVyYXRlZENvbHVtbjogdXRpbC5nZXRBcmcoYUFyZ3MsICdjb2x1bW4nKVxuICAgIH07XG5cbiAgICAvLyBGaW5kIHRoZSBzZWN0aW9uIGNvbnRhaW5pbmcgdGhlIGdlbmVyYXRlZCBwb3NpdGlvbiB3ZSdyZSB0cnlpbmcgdG8gbWFwXG4gICAgLy8gdG8gYW4gb3JpZ2luYWwgcG9zaXRpb24uXG4gICAgdmFyIHNlY3Rpb25JbmRleCA9IGJpbmFyeVNlYXJjaC5zZWFyY2gobmVlZGxlLCB0aGlzLl9zZWN0aW9ucyxcbiAgICAgIGZ1bmN0aW9uKG5lZWRsZSwgc2VjdGlvbikge1xuICAgICAgICB2YXIgY21wID0gbmVlZGxlLmdlbmVyYXRlZExpbmUgLSBzZWN0aW9uLmdlbmVyYXRlZE9mZnNldC5nZW5lcmF0ZWRMaW5lO1xuICAgICAgICBpZiAoY21wKSB7XG4gICAgICAgICAgcmV0dXJuIGNtcDtcbiAgICAgICAgfVxuXG4gICAgICAgIHJldHVybiAobmVlZGxlLmdlbmVyYXRlZENvbHVtbiAtXG4gICAgICAgICAgICAgICAgc2VjdGlvbi5nZW5lcmF0ZWRPZmZzZXQuZ2VuZXJhdGVkQ29sdW1uKTtcbiAgICAgIH0pO1xuICAgIHZhciBzZWN0aW9uID0gdGhpcy5fc2VjdGlvbnNbc2VjdGlvbkluZGV4XTtcblxuICAgIGlmICghc2VjdGlvbikge1xuICAgICAgcmV0dXJuIHtcbiAgICAgICAgc291cmNlOiBudWxsLFxuICAgICAgICBsaW5lOiBudWxsLFxuICAgICAgICBjb2x1bW46IG51bGwsXG4gICAgICAgIG5hbWU6IG51bGxcbiAgICAgIH07XG4gICAgfVxuXG4gICAgcmV0dXJuIHNlY3Rpb24uY29uc3VtZXIub3JpZ2luYWxQb3NpdGlvbkZvcih7XG4gICAgICBsaW5lOiBuZWVkbGUuZ2VuZXJhdGVkTGluZSAtXG4gICAgICAgIChzZWN0aW9uLmdlbmVyYXRlZE9mZnNldC5nZW5lcmF0ZWRMaW5lIC0gMSksXG4gICAgICBjb2x1bW46IG5lZWRsZS5nZW5lcmF0ZWRDb2x1bW4gLVxuICAgICAgICAoc2VjdGlvbi5nZW5lcmF0ZWRPZmZzZXQuZ2VuZXJhdGVkTGluZSA9PT0gbmVlZGxlLmdlbmVyYXRlZExpbmVcbiAgICAgICAgID8gc2VjdGlvbi5nZW5lcmF0ZWRPZmZzZXQuZ2VuZXJhdGVkQ29sdW1uIC0gMVxuICAgICAgICAgOiAwKSxcbiAgICAgIGJpYXM6IGFBcmdzLmJpYXNcbiAgICB9KTtcbiAgfTtcblxuLyoqXG4gKiBSZXR1cm4gdHJ1ZSBpZiB3ZSBoYXZlIHRoZSBzb3VyY2UgY29udGVudCBmb3IgZXZlcnkgc291cmNlIGluIHRoZSBzb3VyY2VcbiAqIG1hcCwgZmFsc2Ugb3RoZXJ3aXNlLlxuICovXG5JbmRleGVkU291cmNlTWFwQ29uc3VtZXIucHJvdG90eXBlLmhhc0NvbnRlbnRzT2ZBbGxTb3VyY2VzID1cbiAgZnVuY3Rpb24gSW5kZXhlZFNvdXJjZU1hcENvbnN1bWVyX2hhc0NvbnRlbnRzT2ZBbGxTb3VyY2VzKCkge1xuICAgIHJldHVybiB0aGlzLl9zZWN0aW9ucy5ldmVyeShmdW5jdGlvbiAocykge1xuICAgICAgcmV0dXJuIHMuY29uc3VtZXIuaGFzQ29udGVudHNPZkFsbFNvdXJjZXMoKTtcbiAgICB9KTtcbiAgfTtcblxuLyoqXG4gKiBSZXR1cm5zIHRoZSBvcmlnaW5hbCBzb3VyY2UgY29udGVudC4gVGhlIG9ubHkgYXJndW1lbnQgaXMgdGhlIHVybCBvZiB0aGVcbiAqIG9yaWdpbmFsIHNvdXJjZSBmaWxlLiBSZXR1cm5zIG51bGwgaWYgbm8gb3JpZ2luYWwgc291cmNlIGNvbnRlbnQgaXNcbiAqIGF2YWlsYWJsZS5cbiAqL1xuSW5kZXhlZFNvdXJjZU1hcENvbnN1bWVyLnByb3RvdHlwZS5zb3VyY2VDb250ZW50Rm9yID1cbiAgZnVuY3Rpb24gSW5kZXhlZFNvdXJjZU1hcENvbnN1bWVyX3NvdXJjZUNvbnRlbnRGb3IoYVNvdXJjZSwgbnVsbE9uTWlzc2luZykge1xuICAgIGZvciAodmFyIGkgPSAwOyBpIDwgdGhpcy5fc2VjdGlvbnMubGVuZ3RoOyBpKyspIHtcbiAgICAgIHZhciBzZWN0aW9uID0gdGhpcy5fc2VjdGlvbnNbaV07XG5cbiAgICAgIHZhciBjb250ZW50ID0gc2VjdGlvbi5jb25zdW1lci5zb3VyY2VDb250ZW50Rm9yKGFTb3VyY2UsIHRydWUpO1xuICAgICAgaWYgKGNvbnRlbnQpIHtcbiAgICAgICAgcmV0dXJuIGNvbnRlbnQ7XG4gICAgICB9XG4gICAgfVxuICAgIGlmIChudWxsT25NaXNzaW5nKSB7XG4gICAgICByZXR1cm4gbnVsbDtcbiAgICB9XG4gICAgZWxzZSB7XG4gICAgICB0aHJvdyBuZXcgRXJyb3IoJ1wiJyArIGFTb3VyY2UgKyAnXCIgaXMgbm90IGluIHRoZSBTb3VyY2VNYXAuJyk7XG4gICAgfVxuICB9O1xuXG4vKipcbiAqIFJldHVybnMgdGhlIGdlbmVyYXRlZCBsaW5lIGFuZCBjb2x1bW4gaW5mb3JtYXRpb24gZm9yIHRoZSBvcmlnaW5hbCBzb3VyY2UsXG4gKiBsaW5lLCBhbmQgY29sdW1uIHBvc2l0aW9ucyBwcm92aWRlZC4gVGhlIG9ubHkgYXJndW1lbnQgaXMgYW4gb2JqZWN0IHdpdGhcbiAqIHRoZSBmb2xsb3dpbmcgcHJvcGVydGllczpcbiAqXG4gKiAgIC0gc291cmNlOiBUaGUgZmlsZW5hbWUgb2YgdGhlIG9yaWdpbmFsIHNvdXJjZS5cbiAqICAgLSBsaW5lOiBUaGUgbGluZSBudW1iZXIgaW4gdGhlIG9yaWdpbmFsIHNvdXJjZS4gIFRoZSBsaW5lIG51bWJlclxuICogICAgIGlzIDEtYmFzZWQuXG4gKiAgIC0gY29sdW1uOiBUaGUgY29sdW1uIG51bWJlciBpbiB0aGUgb3JpZ2luYWwgc291cmNlLiAgVGhlIGNvbHVtblxuICogICAgIG51bWJlciBpcyAwLWJhc2VkLlxuICpcbiAqIGFuZCBhbiBvYmplY3QgaXMgcmV0dXJuZWQgd2l0aCB0aGUgZm9sbG93aW5nIHByb3BlcnRpZXM6XG4gKlxuICogICAtIGxpbmU6IFRoZSBsaW5lIG51bWJlciBpbiB0aGUgZ2VuZXJhdGVkIHNvdXJjZSwgb3IgbnVsbC4gIFRoZVxuICogICAgIGxpbmUgbnVtYmVyIGlzIDEtYmFzZWQuIFxuICogICAtIGNvbHVtbjogVGhlIGNvbHVtbiBudW1iZXIgaW4gdGhlIGdlbmVyYXRlZCBzb3VyY2UsIG9yIG51bGwuXG4gKiAgICAgVGhlIGNvbHVtbiBudW1iZXIgaXMgMC1iYXNlZC5cbiAqL1xuSW5kZXhlZFNvdXJjZU1hcENvbnN1bWVyLnByb3RvdHlwZS5nZW5lcmF0ZWRQb3NpdGlvbkZvciA9XG4gIGZ1bmN0aW9uIEluZGV4ZWRTb3VyY2VNYXBDb25zdW1lcl9nZW5lcmF0ZWRQb3NpdGlvbkZvcihhQXJncykge1xuICAgIGZvciAodmFyIGkgPSAwOyBpIDwgdGhpcy5fc2VjdGlvbnMubGVuZ3RoOyBpKyspIHtcbiAgICAgIHZhciBzZWN0aW9uID0gdGhpcy5fc2VjdGlvbnNbaV07XG5cbiAgICAgIC8vIE9ubHkgY29uc2lkZXIgdGhpcyBzZWN0aW9uIGlmIHRoZSByZXF1ZXN0ZWQgc291cmNlIGlzIGluIHRoZSBsaXN0IG9mXG4gICAgICAvLyBzb3VyY2VzIG9mIHRoZSBjb25zdW1lci5cbiAgICAgIGlmIChzZWN0aW9uLmNvbnN1bWVyLl9maW5kU291cmNlSW5kZXgodXRpbC5nZXRBcmcoYUFyZ3MsICdzb3VyY2UnKSkgPT09IC0xKSB7XG4gICAgICAgIGNvbnRpbnVlO1xuICAgICAgfVxuICAgICAgdmFyIGdlbmVyYXRlZFBvc2l0aW9uID0gc2VjdGlvbi5jb25zdW1lci5nZW5lcmF0ZWRQb3NpdGlvbkZvcihhQXJncyk7XG4gICAgICBpZiAoZ2VuZXJhdGVkUG9zaXRpb24pIHtcbiAgICAgICAgdmFyIHJldCA9IHtcbiAgICAgICAgICBsaW5lOiBnZW5lcmF0ZWRQb3NpdGlvbi5saW5lICtcbiAgICAgICAgICAgIChzZWN0aW9uLmdlbmVyYXRlZE9mZnNldC5nZW5lcmF0ZWRMaW5lIC0gMSksXG4gICAgICAgICAgY29sdW1uOiBnZW5lcmF0ZWRQb3NpdGlvbi5jb2x1bW4gK1xuICAgICAgICAgICAgKHNlY3Rpb24uZ2VuZXJhdGVkT2Zmc2V0LmdlbmVyYXRlZExpbmUgPT09IGdlbmVyYXRlZFBvc2l0aW9uLmxpbmVcbiAgICAgICAgICAgICA/IHNlY3Rpb24uZ2VuZXJhdGVkT2Zmc2V0LmdlbmVyYXRlZENvbHVtbiAtIDFcbiAgICAgICAgICAgICA6IDApXG4gICAgICAgIH07XG4gICAgICAgIHJldHVybiByZXQ7XG4gICAgICB9XG4gICAgfVxuXG4gICAgcmV0dXJuIHtcbiAgICAgIGxpbmU6IG51bGwsXG4gICAgICBjb2x1bW46IG51bGxcbiAgICB9O1xuICB9O1xuXG4vKipcbiAqIFBhcnNlIHRoZSBtYXBwaW5ncyBpbiBhIHN0cmluZyBpbiB0byBhIGRhdGEgc3RydWN0dXJlIHdoaWNoIHdlIGNhbiBlYXNpbHlcbiAqIHF1ZXJ5ICh0aGUgb3JkZXJlZCBhcnJheXMgaW4gdGhlIGB0aGlzLl9fZ2VuZXJhdGVkTWFwcGluZ3NgIGFuZFxuICogYHRoaXMuX19vcmlnaW5hbE1hcHBpbmdzYCBwcm9wZXJ0aWVzKS5cbiAqL1xuSW5kZXhlZFNvdXJjZU1hcENvbnN1bWVyLnByb3RvdHlwZS5fcGFyc2VNYXBwaW5ncyA9XG4gIGZ1bmN0aW9uIEluZGV4ZWRTb3VyY2VNYXBDb25zdW1lcl9wYXJzZU1hcHBpbmdzKGFTdHIsIGFTb3VyY2VSb290KSB7XG4gICAgdGhpcy5fX2dlbmVyYXRlZE1hcHBpbmdzID0gW107XG4gICAgdGhpcy5fX29yaWdpbmFsTWFwcGluZ3MgPSBbXTtcbiAgICBmb3IgKHZhciBpID0gMDsgaSA8IHRoaXMuX3NlY3Rpb25zLmxlbmd0aDsgaSsrKSB7XG4gICAgICB2YXIgc2VjdGlvbiA9IHRoaXMuX3NlY3Rpb25zW2ldO1xuICAgICAgdmFyIHNlY3Rpb25NYXBwaW5ncyA9IHNlY3Rpb24uY29uc3VtZXIuX2dlbmVyYXRlZE1hcHBpbmdzO1xuICAgICAgZm9yICh2YXIgaiA9IDA7IGogPCBzZWN0aW9uTWFwcGluZ3MubGVuZ3RoOyBqKyspIHtcbiAgICAgICAgdmFyIG1hcHBpbmcgPSBzZWN0aW9uTWFwcGluZ3Nbal07XG5cbiAgICAgICAgdmFyIHNvdXJjZSA9IHNlY3Rpb24uY29uc3VtZXIuX3NvdXJjZXMuYXQobWFwcGluZy5zb3VyY2UpO1xuICAgICAgICBzb3VyY2UgPSB1dGlsLmNvbXB1dGVTb3VyY2VVUkwoc2VjdGlvbi5jb25zdW1lci5zb3VyY2VSb290LCBzb3VyY2UsIHRoaXMuX3NvdXJjZU1hcFVSTCk7XG4gICAgICAgIHRoaXMuX3NvdXJjZXMuYWRkKHNvdXJjZSk7XG4gICAgICAgIHNvdXJjZSA9IHRoaXMuX3NvdXJjZXMuaW5kZXhPZihzb3VyY2UpO1xuXG4gICAgICAgIHZhciBuYW1lID0gbnVsbDtcbiAgICAgICAgaWYgKG1hcHBpbmcubmFtZSkge1xuICAgICAgICAgIG5hbWUgPSBzZWN0aW9uLmNvbnN1bWVyLl9uYW1lcy5hdChtYXBwaW5nLm5hbWUpO1xuICAgICAgICAgIHRoaXMuX25hbWVzLmFkZChuYW1lKTtcbiAgICAgICAgICBuYW1lID0gdGhpcy5fbmFtZXMuaW5kZXhPZihuYW1lKTtcbiAgICAgICAgfVxuXG4gICAgICAgIC8vIFRoZSBtYXBwaW5ncyBjb21pbmcgZnJvbSB0aGUgY29uc3VtZXIgZm9yIHRoZSBzZWN0aW9uIGhhdmVcbiAgICAgICAgLy8gZ2VuZXJhdGVkIHBvc2l0aW9ucyByZWxhdGl2ZSB0byB0aGUgc3RhcnQgb2YgdGhlIHNlY3Rpb24sIHNvIHdlXG4gICAgICAgIC8vIG5lZWQgdG8gb2Zmc2V0IHRoZW0gdG8gYmUgcmVsYXRpdmUgdG8gdGhlIHN0YXJ0IG9mIHRoZSBjb25jYXRlbmF0ZWRcbiAgICAgICAgLy8gZ2VuZXJhdGVkIGZpbGUuXG4gICAgICAgIHZhciBhZGp1c3RlZE1hcHBpbmcgPSB7XG4gICAgICAgICAgc291cmNlOiBzb3VyY2UsXG4gICAgICAgICAgZ2VuZXJhdGVkTGluZTogbWFwcGluZy5nZW5lcmF0ZWRMaW5lICtcbiAgICAgICAgICAgIChzZWN0aW9uLmdlbmVyYXRlZE9mZnNldC5nZW5lcmF0ZWRMaW5lIC0gMSksXG4gICAgICAgICAgZ2VuZXJhdGVkQ29sdW1uOiBtYXBwaW5nLmdlbmVyYXRlZENvbHVtbiArXG4gICAgICAgICAgICAoc2VjdGlvbi5nZW5lcmF0ZWRPZmZzZXQuZ2VuZXJhdGVkTGluZSA9PT0gbWFwcGluZy5nZW5lcmF0ZWRMaW5lXG4gICAgICAgICAgICA/IHNlY3Rpb24uZ2VuZXJhdGVkT2Zmc2V0LmdlbmVyYXRlZENvbHVtbiAtIDFcbiAgICAgICAgICAgIDogMCksXG4gICAgICAgICAgb3JpZ2luYWxMaW5lOiBtYXBwaW5nLm9yaWdpbmFsTGluZSxcbiAgICAgICAgICBvcmlnaW5hbENvbHVtbjogbWFwcGluZy5vcmlnaW5hbENvbHVtbixcbiAgICAgICAgICBuYW1lOiBuYW1lXG4gICAgICAgIH07XG5cbiAgICAgICAgdGhpcy5fX2dlbmVyYXRlZE1hcHBpbmdzLnB1c2goYWRqdXN0ZWRNYXBwaW5nKTtcbiAgICAgICAgaWYgKHR5cGVvZiBhZGp1c3RlZE1hcHBpbmcub3JpZ2luYWxMaW5lID09PSAnbnVtYmVyJykge1xuICAgICAgICAgIHRoaXMuX19vcmlnaW5hbE1hcHBpbmdzLnB1c2goYWRqdXN0ZWRNYXBwaW5nKTtcbiAgICAgICAgfVxuICAgICAgfVxuICAgIH1cblxuICAgIHF1aWNrU29ydCh0aGlzLl9fZ2VuZXJhdGVkTWFwcGluZ3MsIHV0aWwuY29tcGFyZUJ5R2VuZXJhdGVkUG9zaXRpb25zRGVmbGF0ZWQpO1xuICAgIHF1aWNrU29ydCh0aGlzLl9fb3JpZ2luYWxNYXBwaW5ncywgdXRpbC5jb21wYXJlQnlPcmlnaW5hbFBvc2l0aW9ucyk7XG4gIH07XG5cbmV4cG9ydHMuSW5kZXhlZFNvdXJjZU1hcENvbnN1bWVyID0gSW5kZXhlZFNvdXJjZU1hcENvbnN1bWVyO1xuXG5cblxuLy8vLy8vLy8vLy8vLy8vLy8vXG4vLyBXRUJQQUNLIEZPT1RFUlxuLy8gLi9saWIvc291cmNlLW1hcC1jb25zdW1lci5qc1xuLy8gbW9kdWxlIGlkID0gN1xuLy8gbW9kdWxlIGNodW5rcyA9IDAiLCIvKiAtKi0gTW9kZToganM7IGpzLWluZGVudC1sZXZlbDogMjsgLSotICovXG4vKlxuICogQ29weXJpZ2h0IDIwMTEgTW96aWxsYSBGb3VuZGF0aW9uIGFuZCBjb250cmlidXRvcnNcbiAqIExpY2Vuc2VkIHVuZGVyIHRoZSBOZXcgQlNEIGxpY2Vuc2UuIFNlZSBMSUNFTlNFIG9yOlxuICogaHR0cDovL29wZW5zb3VyY2Uub3JnL2xpY2Vuc2VzL0JTRC0zLUNsYXVzZVxuICovXG5cbmV4cG9ydHMuR1JFQVRFU1RfTE9XRVJfQk9VTkQgPSAxO1xuZXhwb3J0cy5MRUFTVF9VUFBFUl9CT1VORCA9IDI7XG5cbi8qKlxuICogUmVjdXJzaXZlIGltcGxlbWVudGF0aW9uIG9mIGJpbmFyeSBzZWFyY2guXG4gKlxuICogQHBhcmFtIGFMb3cgSW5kaWNlcyBoZXJlIGFuZCBsb3dlciBkbyBub3QgY29udGFpbiB0aGUgbmVlZGxlLlxuICogQHBhcmFtIGFIaWdoIEluZGljZXMgaGVyZSBhbmQgaGlnaGVyIGRvIG5vdCBjb250YWluIHRoZSBuZWVkbGUuXG4gKiBAcGFyYW0gYU5lZWRsZSBUaGUgZWxlbWVudCBiZWluZyBzZWFyY2hlZCBmb3IuXG4gKiBAcGFyYW0gYUhheXN0YWNrIFRoZSBub24tZW1wdHkgYXJyYXkgYmVpbmcgc2VhcmNoZWQuXG4gKiBAcGFyYW0gYUNvbXBhcmUgRnVuY3Rpb24gd2hpY2ggdGFrZXMgdHdvIGVsZW1lbnRzIGFuZCByZXR1cm5zIC0xLCAwLCBvciAxLlxuICogQHBhcmFtIGFCaWFzIEVpdGhlciAnYmluYXJ5U2VhcmNoLkdSRUFURVNUX0xPV0VSX0JPVU5EJyBvclxuICogICAgICdiaW5hcnlTZWFyY2guTEVBU1RfVVBQRVJfQk9VTkQnLiBTcGVjaWZpZXMgd2hldGhlciB0byByZXR1cm4gdGhlXG4gKiAgICAgY2xvc2VzdCBlbGVtZW50IHRoYXQgaXMgc21hbGxlciB0aGFuIG9yIGdyZWF0ZXIgdGhhbiB0aGUgb25lIHdlIGFyZVxuICogICAgIHNlYXJjaGluZyBmb3IsIHJlc3BlY3RpdmVseSwgaWYgdGhlIGV4YWN0IGVsZW1lbnQgY2Fubm90IGJlIGZvdW5kLlxuICovXG5mdW5jdGlvbiByZWN1cnNpdmVTZWFyY2goYUxvdywgYUhpZ2gsIGFOZWVkbGUsIGFIYXlzdGFjaywgYUNvbXBhcmUsIGFCaWFzKSB7XG4gIC8vIFRoaXMgZnVuY3Rpb24gdGVybWluYXRlcyB3aGVuIG9uZSBvZiB0aGUgZm9sbG93aW5nIGlzIHRydWU6XG4gIC8vXG4gIC8vICAgMS4gV2UgZmluZCB0aGUgZXhhY3QgZWxlbWVudCB3ZSBhcmUgbG9va2luZyBmb3IuXG4gIC8vXG4gIC8vICAgMi4gV2UgZGlkIG5vdCBmaW5kIHRoZSBleGFjdCBlbGVtZW50LCBidXQgd2UgY2FuIHJldHVybiB0aGUgaW5kZXggb2ZcbiAgLy8gICAgICB0aGUgbmV4dC1jbG9zZXN0IGVsZW1lbnQuXG4gIC8vXG4gIC8vICAgMy4gV2UgZGlkIG5vdCBmaW5kIHRoZSBleGFjdCBlbGVtZW50LCBhbmQgdGhlcmUgaXMgbm8gbmV4dC1jbG9zZXN0XG4gIC8vICAgICAgZWxlbWVudCB0aGFuIHRoZSBvbmUgd2UgYXJlIHNlYXJjaGluZyBmb3IsIHNvIHdlIHJldHVybiAtMS5cbiAgdmFyIG1pZCA9IE1hdGguZmxvb3IoKGFIaWdoIC0gYUxvdykgLyAyKSArIGFMb3c7XG4gIHZhciBjbXAgPSBhQ29tcGFyZShhTmVlZGxlLCBhSGF5c3RhY2tbbWlkXSwgdHJ1ZSk7XG4gIGlmIChjbXAgPT09IDApIHtcbiAgICAvLyBGb3VuZCB0aGUgZWxlbWVudCB3ZSBhcmUgbG9va2luZyBmb3IuXG4gICAgcmV0dXJuIG1pZDtcbiAgfVxuICBlbHNlIGlmIChjbXAgPiAwKSB7XG4gICAgLy8gT3VyIG5lZWRsZSBpcyBncmVhdGVyIHRoYW4gYUhheXN0YWNrW21pZF0uXG4gICAgaWYgKGFIaWdoIC0gbWlkID4gMSkge1xuICAgICAgLy8gVGhlIGVsZW1lbnQgaXMgaW4gdGhlIHVwcGVyIGhhbGYuXG4gICAgICByZXR1cm4gcmVjdXJzaXZlU2VhcmNoKG1pZCwgYUhpZ2gsIGFOZWVkbGUsIGFIYXlzdGFjaywgYUNvbXBhcmUsIGFCaWFzKTtcbiAgICB9XG5cbiAgICAvLyBUaGUgZXhhY3QgbmVlZGxlIGVsZW1lbnQgd2FzIG5vdCBmb3VuZCBpbiB0aGlzIGhheXN0YWNrLiBEZXRlcm1pbmUgaWZcbiAgICAvLyB3ZSBhcmUgaW4gdGVybWluYXRpb24gY2FzZSAoMykgb3IgKDIpIGFuZCByZXR1cm4gdGhlIGFwcHJvcHJpYXRlIHRoaW5nLlxuICAgIGlmIChhQmlhcyA9PSBleHBvcnRzLkxFQVNUX1VQUEVSX0JPVU5EKSB7XG4gICAgICByZXR1cm4gYUhpZ2ggPCBhSGF5c3RhY2subGVuZ3RoID8gYUhpZ2ggOiAtMTtcbiAgICB9IGVsc2Uge1xuICAgICAgcmV0dXJuIG1pZDtcbiAgICB9XG4gIH1cbiAgZWxzZSB7XG4gICAgLy8gT3VyIG5lZWRsZSBpcyBsZXNzIHRoYW4gYUhheXN0YWNrW21pZF0uXG4gICAgaWYgKG1pZCAtIGFMb3cgPiAxKSB7XG4gICAgICAvLyBUaGUgZWxlbWVudCBpcyBpbiB0aGUgbG93ZXIgaGFsZi5cbiAgICAgIHJldHVybiByZWN1cnNpdmVTZWFyY2goYUxvdywgbWlkLCBhTmVlZGxlLCBhSGF5c3RhY2ssIGFDb21wYXJlLCBhQmlhcyk7XG4gICAgfVxuXG4gICAgLy8gd2UgYXJlIGluIHRlcm1pbmF0aW9uIGNhc2UgKDMpIG9yICgyKSBhbmQgcmV0dXJuIHRoZSBhcHByb3ByaWF0ZSB0aGluZy5cbiAgICBpZiAoYUJpYXMgPT0gZXhwb3J0cy5MRUFTVF9VUFBFUl9CT1VORCkge1xuICAgICAgcmV0dXJuIG1pZDtcbiAgICB9IGVsc2Uge1xuICAgICAgcmV0dXJuIGFMb3cgPCAwID8gLTEgOiBhTG93O1xuICAgIH1cbiAgfVxufVxuXG4vKipcbiAqIFRoaXMgaXMgYW4gaW1wbGVtZW50YXRpb24gb2YgYmluYXJ5IHNlYXJjaCB3aGljaCB3aWxsIGFsd2F5cyB0cnkgYW5kIHJldHVyblxuICogdGhlIGluZGV4IG9mIHRoZSBjbG9zZXN0IGVsZW1lbnQgaWYgdGhlcmUgaXMgbm8gZXhhY3QgaGl0LiBUaGlzIGlzIGJlY2F1c2VcbiAqIG1hcHBpbmdzIGJldHdlZW4gb3JpZ2luYWwgYW5kIGdlbmVyYXRlZCBsaW5lL2NvbCBwYWlycyBhcmUgc2luZ2xlIHBvaW50cyxcbiAqIGFuZCB0aGVyZSBpcyBhbiBpbXBsaWNpdCByZWdpb24gYmV0d2VlbiBlYWNoIG9mIHRoZW0sIHNvIGEgbWlzcyBqdXN0IG1lYW5zXG4gKiB0aGF0IHlvdSBhcmVuJ3Qgb24gdGhlIHZlcnkgc3RhcnQgb2YgYSByZWdpb24uXG4gKlxuICogQHBhcmFtIGFOZWVkbGUgVGhlIGVsZW1lbnQgeW91IGFyZSBsb29raW5nIGZvci5cbiAqIEBwYXJhbSBhSGF5c3RhY2sgVGhlIGFycmF5IHRoYXQgaXMgYmVpbmcgc2VhcmNoZWQuXG4gKiBAcGFyYW0gYUNvbXBhcmUgQSBmdW5jdGlvbiB3aGljaCB0YWtlcyB0aGUgbmVlZGxlIGFuZCBhbiBlbGVtZW50IGluIHRoZVxuICogICAgIGFycmF5IGFuZCByZXR1cm5zIC0xLCAwLCBvciAxIGRlcGVuZGluZyBvbiB3aGV0aGVyIHRoZSBuZWVkbGUgaXMgbGVzc1xuICogICAgIHRoYW4sIGVxdWFsIHRvLCBvciBncmVhdGVyIHRoYW4gdGhlIGVsZW1lbnQsIHJlc3BlY3RpdmVseS5cbiAqIEBwYXJhbSBhQmlhcyBFaXRoZXIgJ2JpbmFyeVNlYXJjaC5HUkVBVEVTVF9MT1dFUl9CT1VORCcgb3JcbiAqICAgICAnYmluYXJ5U2VhcmNoLkxFQVNUX1VQUEVSX0JPVU5EJy4gU3BlY2lmaWVzIHdoZXRoZXIgdG8gcmV0dXJuIHRoZVxuICogICAgIGNsb3Nlc3QgZWxlbWVudCB0aGF0IGlzIHNtYWxsZXIgdGhhbiBvciBncmVhdGVyIHRoYW4gdGhlIG9uZSB3ZSBhcmVcbiAqICAgICBzZWFyY2hpbmcgZm9yLCByZXNwZWN0aXZlbHksIGlmIHRoZSBleGFjdCBlbGVtZW50IGNhbm5vdCBiZSBmb3VuZC5cbiAqICAgICBEZWZhdWx0cyB0byAnYmluYXJ5U2VhcmNoLkdSRUFURVNUX0xPV0VSX0JPVU5EJy5cbiAqL1xuZXhwb3J0cy5zZWFyY2ggPSBmdW5jdGlvbiBzZWFyY2goYU5lZWRsZSwgYUhheXN0YWNrLCBhQ29tcGFyZSwgYUJpYXMpIHtcbiAgaWYgKGFIYXlzdGFjay5sZW5ndGggPT09IDApIHtcbiAgICByZXR1cm4gLTE7XG4gIH1cblxuICB2YXIgaW5kZXggPSByZWN1cnNpdmVTZWFyY2goLTEsIGFIYXlzdGFjay5sZW5ndGgsIGFOZWVkbGUsIGFIYXlzdGFjayxcbiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIGFDb21wYXJlLCBhQmlhcyB8fCBleHBvcnRzLkdSRUFURVNUX0xPV0VSX0JPVU5EKTtcbiAgaWYgKGluZGV4IDwgMCkge1xuICAgIHJldHVybiAtMTtcbiAgfVxuXG4gIC8vIFdlIGhhdmUgZm91bmQgZWl0aGVyIHRoZSBleGFjdCBlbGVtZW50LCBvciB0aGUgbmV4dC1jbG9zZXN0IGVsZW1lbnQgdGhhblxuICAvLyB0aGUgb25lIHdlIGFyZSBzZWFyY2hpbmcgZm9yLiBIb3dldmVyLCB0aGVyZSBtYXkgYmUgbW9yZSB0aGFuIG9uZSBzdWNoXG4gIC8vIGVsZW1lbnQuIE1ha2Ugc3VyZSB3ZSBhbHdheXMgcmV0dXJuIHRoZSBzbWFsbGVzdCBvZiB0aGVzZS5cbiAgd2hpbGUgKGluZGV4IC0gMSA+PSAwKSB7XG4gICAgaWYgKGFDb21wYXJlKGFIYXlzdGFja1tpbmRleF0sIGFIYXlzdGFja1tpbmRleCAtIDFdLCB0cnVlKSAhPT0gMCkge1xuICAgICAgYnJlYWs7XG4gICAgfVxuICAgIC0taW5kZXg7XG4gIH1cblxuICByZXR1cm4gaW5kZXg7XG59O1xuXG5cblxuLy8vLy8vLy8vLy8vLy8vLy8vXG4vLyBXRUJQQUNLIEZPT1RFUlxuLy8gLi9saWIvYmluYXJ5LXNlYXJjaC5qc1xuLy8gbW9kdWxlIGlkID0gOFxuLy8gbW9kdWxlIGNodW5rcyA9IDAiLCIvKiAtKi0gTW9kZToganM7IGpzLWluZGVudC1sZXZlbDogMjsgLSotICovXG4vKlxuICogQ29weXJpZ2h0IDIwMTEgTW96aWxsYSBGb3VuZGF0aW9uIGFuZCBjb250cmlidXRvcnNcbiAqIExpY2Vuc2VkIHVuZGVyIHRoZSBOZXcgQlNEIGxpY2Vuc2UuIFNlZSBMSUNFTlNFIG9yOlxuICogaHR0cDovL29wZW5zb3VyY2Uub3JnL2xpY2Vuc2VzL0JTRC0zLUNsYXVzZVxuICovXG5cbi8vIEl0IHR1cm5zIG91dCB0aGF0IHNvbWUgKG1vc3Q/KSBKYXZhU2NyaXB0IGVuZ2luZXMgZG9uJ3Qgc2VsZi1ob3N0XG4vLyBgQXJyYXkucHJvdG90eXBlLnNvcnRgLiBUaGlzIG1ha2VzIHNlbnNlIGJlY2F1c2UgQysrIHdpbGwgbGlrZWx5IHJlbWFpblxuLy8gZmFzdGVyIHRoYW4gSlMgd2hlbiBkb2luZyByYXcgQ1BVLWludGVuc2l2ZSBzb3J0aW5nLiBIb3dldmVyLCB3aGVuIHVzaW5nIGFcbi8vIGN1c3RvbSBjb21wYXJhdG9yIGZ1bmN0aW9uLCBjYWxsaW5nIGJhY2sgYW5kIGZvcnRoIGJldHdlZW4gdGhlIFZNJ3MgQysrIGFuZFxuLy8gSklUJ2QgSlMgaXMgcmF0aGVyIHNsb3cgKmFuZCogbG9zZXMgSklUIHR5cGUgaW5mb3JtYXRpb24sIHJlc3VsdGluZyBpblxuLy8gd29yc2UgZ2VuZXJhdGVkIGNvZGUgZm9yIHRoZSBjb21wYXJhdG9yIGZ1bmN0aW9uIHRoYW4gd291bGQgYmUgb3B0aW1hbC4gSW5cbi8vIGZhY3QsIHdoZW4gc29ydGluZyB3aXRoIGEgY29tcGFyYXRvciwgdGhlc2UgY29zdHMgb3V0d2VpZ2ggdGhlIGJlbmVmaXRzIG9mXG4vLyBzb3J0aW5nIGluIEMrKy4gQnkgdXNpbmcgb3VyIG93biBKUy1pbXBsZW1lbnRlZCBRdWljayBTb3J0IChiZWxvdyksIHdlIGdldFxuLy8gYSB+MzUwMG1zIG1lYW4gc3BlZWQtdXAgaW4gYGJlbmNoL2JlbmNoLmh0bWxgLlxuXG4vKipcbiAqIFN3YXAgdGhlIGVsZW1lbnRzIGluZGV4ZWQgYnkgYHhgIGFuZCBgeWAgaW4gdGhlIGFycmF5IGBhcnlgLlxuICpcbiAqIEBwYXJhbSB7QXJyYXl9IGFyeVxuICogICAgICAgIFRoZSBhcnJheS5cbiAqIEBwYXJhbSB7TnVtYmVyfSB4XG4gKiAgICAgICAgVGhlIGluZGV4IG9mIHRoZSBmaXJzdCBpdGVtLlxuICogQHBhcmFtIHtOdW1iZXJ9IHlcbiAqICAgICAgICBUaGUgaW5kZXggb2YgdGhlIHNlY29uZCBpdGVtLlxuICovXG5mdW5jdGlvbiBzd2FwKGFyeSwgeCwgeSkge1xuICB2YXIgdGVtcCA9IGFyeVt4XTtcbiAgYXJ5W3hdID0gYXJ5W3ldO1xuICBhcnlbeV0gPSB0ZW1wO1xufVxuXG4vKipcbiAqIFJldHVybnMgYSByYW5kb20gaW50ZWdlciB3aXRoaW4gdGhlIHJhbmdlIGBsb3cgLi4gaGlnaGAgaW5jbHVzaXZlLlxuICpcbiAqIEBwYXJhbSB7TnVtYmVyfSBsb3dcbiAqICAgICAgICBUaGUgbG93ZXIgYm91bmQgb24gdGhlIHJhbmdlLlxuICogQHBhcmFtIHtOdW1iZXJ9IGhpZ2hcbiAqICAgICAgICBUaGUgdXBwZXIgYm91bmQgb24gdGhlIHJhbmdlLlxuICovXG5mdW5jdGlvbiByYW5kb21JbnRJblJhbmdlKGxvdywgaGlnaCkge1xuICByZXR1cm4gTWF0aC5yb3VuZChsb3cgKyAoTWF0aC5yYW5kb20oKSAqIChoaWdoIC0gbG93KSkpO1xufVxuXG4vKipcbiAqIFRoZSBRdWljayBTb3J0IGFsZ29yaXRobS5cbiAqXG4gKiBAcGFyYW0ge0FycmF5fSBhcnlcbiAqICAgICAgICBBbiBhcnJheSB0byBzb3J0LlxuICogQHBhcmFtIHtmdW5jdGlvbn0gY29tcGFyYXRvclxuICogICAgICAgIEZ1bmN0aW9uIHRvIHVzZSB0byBjb21wYXJlIHR3byBpdGVtcy5cbiAqIEBwYXJhbSB7TnVtYmVyfSBwXG4gKiAgICAgICAgU3RhcnQgaW5kZXggb2YgdGhlIGFycmF5XG4gKiBAcGFyYW0ge051bWJlcn0gclxuICogICAgICAgIEVuZCBpbmRleCBvZiB0aGUgYXJyYXlcbiAqL1xuZnVuY3Rpb24gZG9RdWlja1NvcnQoYXJ5LCBjb21wYXJhdG9yLCBwLCByKSB7XG4gIC8vIElmIG91ciBsb3dlciBib3VuZCBpcyBsZXNzIHRoYW4gb3VyIHVwcGVyIGJvdW5kLCB3ZSAoMSkgcGFydGl0aW9uIHRoZVxuICAvLyBhcnJheSBpbnRvIHR3byBwaWVjZXMgYW5kICgyKSByZWN1cnNlIG9uIGVhY2ggaGFsZi4gSWYgaXQgaXMgbm90LCB0aGlzIGlzXG4gIC8vIHRoZSBlbXB0eSBhcnJheSBhbmQgb3VyIGJhc2UgY2FzZS5cblxuICBpZiAocCA8IHIpIHtcbiAgICAvLyAoMSkgUGFydGl0aW9uaW5nLlxuICAgIC8vXG4gICAgLy8gVGhlIHBhcnRpdGlvbmluZyBjaG9vc2VzIGEgcGl2b3QgYmV0d2VlbiBgcGAgYW5kIGByYCBhbmQgbW92ZXMgYWxsXG4gICAgLy8gZWxlbWVudHMgdGhhdCBhcmUgbGVzcyB0aGFuIG9yIGVxdWFsIHRvIHRoZSBwaXZvdCB0byB0aGUgYmVmb3JlIGl0LCBhbmRcbiAgICAvLyBhbGwgdGhlIGVsZW1lbnRzIHRoYXQgYXJlIGdyZWF0ZXIgdGhhbiBpdCBhZnRlciBpdC4gVGhlIGVmZmVjdCBpcyB0aGF0XG4gICAgLy8gb25jZSBwYXJ0aXRpb24gaXMgZG9uZSwgdGhlIHBpdm90IGlzIGluIHRoZSBleGFjdCBwbGFjZSBpdCB3aWxsIGJlIHdoZW5cbiAgICAvLyB0aGUgYXJyYXkgaXMgcHV0IGluIHNvcnRlZCBvcmRlciwgYW5kIGl0IHdpbGwgbm90IG5lZWQgdG8gYmUgbW92ZWRcbiAgICAvLyBhZ2Fpbi4gVGhpcyBydW5zIGluIE8obikgdGltZS5cblxuICAgIC8vIEFsd2F5cyBjaG9vc2UgYSByYW5kb20gcGl2b3Qgc28gdGhhdCBhbiBpbnB1dCBhcnJheSB3aGljaCBpcyByZXZlcnNlXG4gICAgLy8gc29ydGVkIGRvZXMgbm90IGNhdXNlIE8obl4yKSBydW5uaW5nIHRpbWUuXG4gICAgdmFyIHBpdm90SW5kZXggPSByYW5kb21JbnRJblJhbmdlKHAsIHIpO1xuICAgIHZhciBpID0gcCAtIDE7XG5cbiAgICBzd2FwKGFyeSwgcGl2b3RJbmRleCwgcik7XG4gICAgdmFyIHBpdm90ID0gYXJ5W3JdO1xuXG4gICAgLy8gSW1tZWRpYXRlbHkgYWZ0ZXIgYGpgIGlzIGluY3JlbWVudGVkIGluIHRoaXMgbG9vcCwgdGhlIGZvbGxvd2luZyBob2xkXG4gICAgLy8gdHJ1ZTpcbiAgICAvL1xuICAgIC8vICAgKiBFdmVyeSBlbGVtZW50IGluIGBhcnlbcCAuLiBpXWAgaXMgbGVzcyB0aGFuIG9yIGVxdWFsIHRvIHRoZSBwaXZvdC5cbiAgICAvL1xuICAgIC8vICAgKiBFdmVyeSBlbGVtZW50IGluIGBhcnlbaSsxIC4uIGotMV1gIGlzIGdyZWF0ZXIgdGhhbiB0aGUgcGl2b3QuXG4gICAgZm9yICh2YXIgaiA9IHA7IGogPCByOyBqKyspIHtcbiAgICAgIGlmIChjb21wYXJhdG9yKGFyeVtqXSwgcGl2b3QpIDw9IDApIHtcbiAgICAgICAgaSArPSAxO1xuICAgICAgICBzd2FwKGFyeSwgaSwgaik7XG4gICAgICB9XG4gICAgfVxuXG4gICAgc3dhcChhcnksIGkgKyAxLCBqKTtcbiAgICB2YXIgcSA9IGkgKyAxO1xuXG4gICAgLy8gKDIpIFJlY3Vyc2Ugb24gZWFjaCBoYWxmLlxuXG4gICAgZG9RdWlja1NvcnQoYXJ5LCBjb21wYXJhdG9yLCBwLCBxIC0gMSk7XG4gICAgZG9RdWlja1NvcnQoYXJ5LCBjb21wYXJhdG9yLCBxICsgMSwgcik7XG4gIH1cbn1cblxuLyoqXG4gKiBTb3J0IHRoZSBnaXZlbiBhcnJheSBpbi1wbGFjZSB3aXRoIHRoZSBnaXZlbiBjb21wYXJhdG9yIGZ1bmN0aW9uLlxuICpcbiAqIEBwYXJhbSB7QXJyYXl9IGFyeVxuICogICAgICAgIEFuIGFycmF5IHRvIHNvcnQuXG4gKiBAcGFyYW0ge2Z1bmN0aW9ufSBjb21wYXJhdG9yXG4gKiAgICAgICAgRnVuY3Rpb24gdG8gdXNlIHRvIGNvbXBhcmUgdHdvIGl0ZW1zLlxuICovXG5leHBvcnRzLnF1aWNrU29ydCA9IGZ1bmN0aW9uIChhcnksIGNvbXBhcmF0b3IpIHtcbiAgZG9RdWlja1NvcnQoYXJ5LCBjb21wYXJhdG9yLCAwLCBhcnkubGVuZ3RoIC0gMSk7XG59O1xuXG5cblxuLy8vLy8vLy8vLy8vLy8vLy8vXG4vLyBXRUJQQUNLIEZPT1RFUlxuLy8gLi9saWIvcXVpY2stc29ydC5qc1xuLy8gbW9kdWxlIGlkID0gOVxuLy8gbW9kdWxlIGNodW5rcyA9IDAiLCIvKiAtKi0gTW9kZToganM7IGpzLWluZGVudC1sZXZlbDogMjsgLSotICovXG4vKlxuICogQ29weXJpZ2h0IDIwMTEgTW96aWxsYSBGb3VuZGF0aW9uIGFuZCBjb250cmlidXRvcnNcbiAqIExpY2Vuc2VkIHVuZGVyIHRoZSBOZXcgQlNEIGxpY2Vuc2UuIFNlZSBMSUNFTlNFIG9yOlxuICogaHR0cDovL29wZW5zb3VyY2Uub3JnL2xpY2Vuc2VzL0JTRC0zLUNsYXVzZVxuICovXG5cbnZhciBTb3VyY2VNYXBHZW5lcmF0b3IgPSByZXF1aXJlKCcuL3NvdXJjZS1tYXAtZ2VuZXJhdG9yJykuU291cmNlTWFwR2VuZXJhdG9yO1xudmFyIHV0aWwgPSByZXF1aXJlKCcuL3V0aWwnKTtcblxuLy8gTWF0Y2hlcyBhIFdpbmRvd3Mtc3R5bGUgYFxcclxcbmAgbmV3bGluZSBvciBhIGBcXG5gIG5ld2xpbmUgdXNlZCBieSBhbGwgb3RoZXJcbi8vIG9wZXJhdGluZyBzeXN0ZW1zIHRoZXNlIGRheXMgKGNhcHR1cmluZyB0aGUgcmVzdWx0KS5cbnZhciBSRUdFWF9ORVdMSU5FID0gLyhcXHI/XFxuKS87XG5cbi8vIE5ld2xpbmUgY2hhcmFjdGVyIGNvZGUgZm9yIGNoYXJDb2RlQXQoKSBjb21wYXJpc29uc1xudmFyIE5FV0xJTkVfQ09ERSA9IDEwO1xuXG4vLyBQcml2YXRlIHN5bWJvbCBmb3IgaWRlbnRpZnlpbmcgYFNvdXJjZU5vZGVgcyB3aGVuIG11bHRpcGxlIHZlcnNpb25zIG9mXG4vLyB0aGUgc291cmNlLW1hcCBsaWJyYXJ5IGFyZSBsb2FkZWQuIFRoaXMgTVVTVCBOT1QgQ0hBTkdFIGFjcm9zc1xuLy8gdmVyc2lvbnMhXG52YXIgaXNTb3VyY2VOb2RlID0gXCIkJCRpc1NvdXJjZU5vZGUkJCRcIjtcblxuLyoqXG4gKiBTb3VyY2VOb2RlcyBwcm92aWRlIGEgd2F5IHRvIGFic3RyYWN0IG92ZXIgaW50ZXJwb2xhdGluZy9jb25jYXRlbmF0aW5nXG4gKiBzbmlwcGV0cyBvZiBnZW5lcmF0ZWQgSmF2YVNjcmlwdCBzb3VyY2UgY29kZSB3aGlsZSBtYWludGFpbmluZyB0aGUgbGluZSBhbmRcbiAqIGNvbHVtbiBpbmZvcm1hdGlvbiBhc3NvY2lhdGVkIHdpdGggdGhlIG9yaWdpbmFsIHNvdXJjZSBjb2RlLlxuICpcbiAqIEBwYXJhbSBhTGluZSBUaGUgb3JpZ2luYWwgbGluZSBudW1iZXIuXG4gKiBAcGFyYW0gYUNvbHVtbiBUaGUgb3JpZ2luYWwgY29sdW1uIG51bWJlci5cbiAqIEBwYXJhbSBhU291cmNlIFRoZSBvcmlnaW5hbCBzb3VyY2UncyBmaWxlbmFtZS5cbiAqIEBwYXJhbSBhQ2h1bmtzIE9wdGlvbmFsLiBBbiBhcnJheSBvZiBzdHJpbmdzIHdoaWNoIGFyZSBzbmlwcGV0cyBvZlxuICogICAgICAgIGdlbmVyYXRlZCBKUywgb3Igb3RoZXIgU291cmNlTm9kZXMuXG4gKiBAcGFyYW0gYU5hbWUgVGhlIG9yaWdpbmFsIGlkZW50aWZpZXIuXG4gKi9cbmZ1bmN0aW9uIFNvdXJjZU5vZGUoYUxpbmUsIGFDb2x1bW4sIGFTb3VyY2UsIGFDaHVua3MsIGFOYW1lKSB7XG4gIHRoaXMuY2hpbGRyZW4gPSBbXTtcbiAgdGhpcy5zb3VyY2VDb250ZW50cyA9IHt9O1xuICB0aGlzLmxpbmUgPSBhTGluZSA9PSBudWxsID8gbnVsbCA6IGFMaW5lO1xuICB0aGlzLmNvbHVtbiA9IGFDb2x1bW4gPT0gbnVsbCA/IG51bGwgOiBhQ29sdW1uO1xuICB0aGlzLnNvdXJjZSA9IGFTb3VyY2UgPT0gbnVsbCA/IG51bGwgOiBhU291cmNlO1xuICB0aGlzLm5hbWUgPSBhTmFtZSA9PSBudWxsID8gbnVsbCA6IGFOYW1lO1xuICB0aGlzW2lzU291cmNlTm9kZV0gPSB0cnVlO1xuICBpZiAoYUNodW5rcyAhPSBudWxsKSB0aGlzLmFkZChhQ2h1bmtzKTtcbn1cblxuLyoqXG4gKiBDcmVhdGVzIGEgU291cmNlTm9kZSBmcm9tIGdlbmVyYXRlZCBjb2RlIGFuZCBhIFNvdXJjZU1hcENvbnN1bWVyLlxuICpcbiAqIEBwYXJhbSBhR2VuZXJhdGVkQ29kZSBUaGUgZ2VuZXJhdGVkIGNvZGVcbiAqIEBwYXJhbSBhU291cmNlTWFwQ29uc3VtZXIgVGhlIFNvdXJjZU1hcCBmb3IgdGhlIGdlbmVyYXRlZCBjb2RlXG4gKiBAcGFyYW0gYVJlbGF0aXZlUGF0aCBPcHRpb25hbC4gVGhlIHBhdGggdGhhdCByZWxhdGl2ZSBzb3VyY2VzIGluIHRoZVxuICogICAgICAgIFNvdXJjZU1hcENvbnN1bWVyIHNob3VsZCBiZSByZWxhdGl2ZSB0by5cbiAqL1xuU291cmNlTm9kZS5mcm9tU3RyaW5nV2l0aFNvdXJjZU1hcCA9XG4gIGZ1bmN0aW9uIFNvdXJjZU5vZGVfZnJvbVN0cmluZ1dpdGhTb3VyY2VNYXAoYUdlbmVyYXRlZENvZGUsIGFTb3VyY2VNYXBDb25zdW1lciwgYVJlbGF0aXZlUGF0aCkge1xuICAgIC8vIFRoZSBTb3VyY2VOb2RlIHdlIHdhbnQgdG8gZmlsbCB3aXRoIHRoZSBnZW5lcmF0ZWQgY29kZVxuICAgIC8vIGFuZCB0aGUgU291cmNlTWFwXG4gICAgdmFyIG5vZGUgPSBuZXcgU291cmNlTm9kZSgpO1xuXG4gICAgLy8gQWxsIGV2ZW4gaW5kaWNlcyBvZiB0aGlzIGFycmF5IGFyZSBvbmUgbGluZSBvZiB0aGUgZ2VuZXJhdGVkIGNvZGUsXG4gICAgLy8gd2hpbGUgYWxsIG9kZCBpbmRpY2VzIGFyZSB0aGUgbmV3bGluZXMgYmV0d2VlbiB0d28gYWRqYWNlbnQgbGluZXNcbiAgICAvLyAoc2luY2UgYFJFR0VYX05FV0xJTkVgIGNhcHR1cmVzIGl0cyBtYXRjaCkuXG4gICAgLy8gUHJvY2Vzc2VkIGZyYWdtZW50cyBhcmUgYWNjZXNzZWQgYnkgY2FsbGluZyBgc2hpZnROZXh0TGluZWAuXG4gICAgdmFyIHJlbWFpbmluZ0xpbmVzID0gYUdlbmVyYXRlZENvZGUuc3BsaXQoUkVHRVhfTkVXTElORSk7XG4gICAgdmFyIHJlbWFpbmluZ0xpbmVzSW5kZXggPSAwO1xuICAgIHZhciBzaGlmdE5leHRMaW5lID0gZnVuY3Rpb24oKSB7XG4gICAgICB2YXIgbGluZUNvbnRlbnRzID0gZ2V0TmV4dExpbmUoKTtcbiAgICAgIC8vIFRoZSBsYXN0IGxpbmUgb2YgYSBmaWxlIG1pZ2h0IG5vdCBoYXZlIGEgbmV3bGluZS5cbiAgICAgIHZhciBuZXdMaW5lID0gZ2V0TmV4dExpbmUoKSB8fCBcIlwiO1xuICAgICAgcmV0dXJuIGxpbmVDb250ZW50cyArIG5ld0xpbmU7XG5cbiAgICAgIGZ1bmN0aW9uIGdldE5leHRMaW5lKCkge1xuICAgICAgICByZXR1cm4gcmVtYWluaW5nTGluZXNJbmRleCA8IHJlbWFpbmluZ0xpbmVzLmxlbmd0aCA/XG4gICAgICAgICAgICByZW1haW5pbmdMaW5lc1tyZW1haW5pbmdMaW5lc0luZGV4KytdIDogdW5kZWZpbmVkO1xuICAgICAgfVxuICAgIH07XG5cbiAgICAvLyBXZSBuZWVkIHRvIHJlbWVtYmVyIHRoZSBwb3NpdGlvbiBvZiBcInJlbWFpbmluZ0xpbmVzXCJcbiAgICB2YXIgbGFzdEdlbmVyYXRlZExpbmUgPSAxLCBsYXN0R2VuZXJhdGVkQ29sdW1uID0gMDtcblxuICAgIC8vIFRoZSBnZW5lcmF0ZSBTb3VyY2VOb2RlcyB3ZSBuZWVkIGEgY29kZSByYW5nZS5cbiAgICAvLyBUbyBleHRyYWN0IGl0IGN1cnJlbnQgYW5kIGxhc3QgbWFwcGluZyBpcyB1c2VkLlxuICAgIC8vIEhlcmUgd2Ugc3RvcmUgdGhlIGxhc3QgbWFwcGluZy5cbiAgICB2YXIgbGFzdE1hcHBpbmcgPSBudWxsO1xuXG4gICAgYVNvdXJjZU1hcENvbnN1bWVyLmVhY2hNYXBwaW5nKGZ1bmN0aW9uIChtYXBwaW5nKSB7XG4gICAgICBpZiAobGFzdE1hcHBpbmcgIT09IG51bGwpIHtcbiAgICAgICAgLy8gV2UgYWRkIHRoZSBjb2RlIGZyb20gXCJsYXN0TWFwcGluZ1wiIHRvIFwibWFwcGluZ1wiOlxuICAgICAgICAvLyBGaXJzdCBjaGVjayBpZiB0aGVyZSBpcyBhIG5ldyBsaW5lIGluIGJldHdlZW4uXG4gICAgICAgIGlmIChsYXN0R2VuZXJhdGVkTGluZSA8IG1hcHBpbmcuZ2VuZXJhdGVkTGluZSkge1xuICAgICAgICAgIC8vIEFzc29jaWF0ZSBmaXJzdCBsaW5lIHdpdGggXCJsYXN0TWFwcGluZ1wiXG4gICAgICAgICAgYWRkTWFwcGluZ1dpdGhDb2RlKGxhc3RNYXBwaW5nLCBzaGlmdE5leHRMaW5lKCkpO1xuICAgICAgICAgIGxhc3RHZW5lcmF0ZWRMaW5lKys7XG4gICAgICAgICAgbGFzdEdlbmVyYXRlZENvbHVtbiA9IDA7XG4gICAgICAgICAgLy8gVGhlIHJlbWFpbmluZyBjb2RlIGlzIGFkZGVkIHdpdGhvdXQgbWFwcGluZ1xuICAgICAgICB9IGVsc2Uge1xuICAgICAgICAgIC8vIFRoZXJlIGlzIG5vIG5ldyBsaW5lIGluIGJldHdlZW4uXG4gICAgICAgICAgLy8gQXNzb2NpYXRlIHRoZSBjb2RlIGJldHdlZW4gXCJsYXN0R2VuZXJhdGVkQ29sdW1uXCIgYW5kXG4gICAgICAgICAgLy8gXCJtYXBwaW5nLmdlbmVyYXRlZENvbHVtblwiIHdpdGggXCJsYXN0TWFwcGluZ1wiXG4gICAgICAgICAgdmFyIG5leHRMaW5lID0gcmVtYWluaW5nTGluZXNbcmVtYWluaW5nTGluZXNJbmRleF0gfHwgJyc7XG4gICAgICAgICAgdmFyIGNvZGUgPSBuZXh0TGluZS5zdWJzdHIoMCwgbWFwcGluZy5nZW5lcmF0ZWRDb2x1bW4gLVxuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIGxhc3RHZW5lcmF0ZWRDb2x1bW4pO1xuICAgICAgICAgIHJlbWFpbmluZ0xpbmVzW3JlbWFpbmluZ0xpbmVzSW5kZXhdID0gbmV4dExpbmUuc3Vic3RyKG1hcHBpbmcuZ2VuZXJhdGVkQ29sdW1uIC1cbiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICBsYXN0R2VuZXJhdGVkQ29sdW1uKTtcbiAgICAgICAgICBsYXN0R2VuZXJhdGVkQ29sdW1uID0gbWFwcGluZy5nZW5lcmF0ZWRDb2x1bW47XG4gICAgICAgICAgYWRkTWFwcGluZ1dpdGhDb2RlKGxhc3RNYXBwaW5nLCBjb2RlKTtcbiAgICAgICAgICAvLyBObyBtb3JlIHJlbWFpbmluZyBjb2RlLCBjb250aW51ZVxuICAgICAgICAgIGxhc3RNYXBwaW5nID0gbWFwcGluZztcbiAgICAgICAgICByZXR1cm47XG4gICAgICAgIH1cbiAgICAgIH1cbiAgICAgIC8vIFdlIGFkZCB0aGUgZ2VuZXJhdGVkIGNvZGUgdW50aWwgdGhlIGZpcnN0IG1hcHBpbmdcbiAgICAgIC8vIHRvIHRoZSBTb3VyY2VOb2RlIHdpdGhvdXQgYW55IG1hcHBpbmcuXG4gICAgICAvLyBFYWNoIGxpbmUgaXMgYWRkZWQgYXMgc2VwYXJhdGUgc3RyaW5nLlxuICAgICAgd2hpbGUgKGxhc3RHZW5lcmF0ZWRMaW5lIDwgbWFwcGluZy5nZW5lcmF0ZWRMaW5lKSB7XG4gICAgICAgIG5vZGUuYWRkKHNoaWZ0TmV4dExpbmUoKSk7XG4gICAgICAgIGxhc3RHZW5lcmF0ZWRMaW5lKys7XG4gICAgICB9XG4gICAgICBpZiAobGFzdEdlbmVyYXRlZENvbHVtbiA8IG1hcHBpbmcuZ2VuZXJhdGVkQ29sdW1uKSB7XG4gICAgICAgIHZhciBuZXh0TGluZSA9IHJlbWFpbmluZ0xpbmVzW3JlbWFpbmluZ0xpbmVzSW5kZXhdIHx8ICcnO1xuICAgICAgICBub2RlLmFkZChuZXh0TGluZS5zdWJzdHIoMCwgbWFwcGluZy5nZW5lcmF0ZWRDb2x1bW4pKTtcbiAgICAgICAgcmVtYWluaW5nTGluZXNbcmVtYWluaW5nTGluZXNJbmRleF0gPSBuZXh0TGluZS5zdWJzdHIobWFwcGluZy5nZW5lcmF0ZWRDb2x1bW4pO1xuICAgICAgICBsYXN0R2VuZXJhdGVkQ29sdW1uID0gbWFwcGluZy5nZW5lcmF0ZWRDb2x1bW47XG4gICAgICB9XG4gICAgICBsYXN0TWFwcGluZyA9IG1hcHBpbmc7XG4gICAgfSwgdGhpcyk7XG4gICAgLy8gV2UgaGF2ZSBwcm9jZXNzZWQgYWxsIG1hcHBpbmdzLlxuICAgIGlmIChyZW1haW5pbmdMaW5lc0luZGV4IDwgcmVtYWluaW5nTGluZXMubGVuZ3RoKSB7XG4gICAgICBpZiAobGFzdE1hcHBpbmcpIHtcbiAgICAgICAgLy8gQXNzb2NpYXRlIHRoZSByZW1haW5pbmcgY29kZSBpbiB0aGUgY3VycmVudCBsaW5lIHdpdGggXCJsYXN0TWFwcGluZ1wiXG4gICAgICAgIGFkZE1hcHBpbmdXaXRoQ29kZShsYXN0TWFwcGluZywgc2hpZnROZXh0TGluZSgpKTtcbiAgICAgIH1cbiAgICAgIC8vIGFuZCBhZGQgdGhlIHJlbWFpbmluZyBsaW5lcyB3aXRob3V0IGFueSBtYXBwaW5nXG4gICAgICBub2RlLmFkZChyZW1haW5pbmdMaW5lcy5zcGxpY2UocmVtYWluaW5nTGluZXNJbmRleCkuam9pbihcIlwiKSk7XG4gICAgfVxuXG4gICAgLy8gQ29weSBzb3VyY2VzQ29udGVudCBpbnRvIFNvdXJjZU5vZGVcbiAgICBhU291cmNlTWFwQ29uc3VtZXIuc291cmNlcy5mb3JFYWNoKGZ1bmN0aW9uIChzb3VyY2VGaWxlKSB7XG4gICAgICB2YXIgY29udGVudCA9IGFTb3VyY2VNYXBDb25zdW1lci5zb3VyY2VDb250ZW50Rm9yKHNvdXJjZUZpbGUpO1xuICAgICAgaWYgKGNvbnRlbnQgIT0gbnVsbCkge1xuICAgICAgICBpZiAoYVJlbGF0aXZlUGF0aCAhPSBudWxsKSB7XG4gICAgICAgICAgc291cmNlRmlsZSA9IHV0aWwuam9pbihhUmVsYXRpdmVQYXRoLCBzb3VyY2VGaWxlKTtcbiAgICAgICAgfVxuICAgICAgICBub2RlLnNldFNvdXJjZUNvbnRlbnQoc291cmNlRmlsZSwgY29udGVudCk7XG4gICAgICB9XG4gICAgfSk7XG5cbiAgICByZXR1cm4gbm9kZTtcblxuICAgIGZ1bmN0aW9uIGFkZE1hcHBpbmdXaXRoQ29kZShtYXBwaW5nLCBjb2RlKSB7XG4gICAgICBpZiAobWFwcGluZyA9PT0gbnVsbCB8fCBtYXBwaW5nLnNvdXJjZSA9PT0gdW5kZWZpbmVkKSB7XG4gICAgICAgIG5vZGUuYWRkKGNvZGUpO1xuICAgICAgfSBlbHNlIHtcbiAgICAgICAgdmFyIHNvdXJjZSA9IGFSZWxhdGl2ZVBhdGhcbiAgICAgICAgICA/IHV0aWwuam9pbihhUmVsYXRpdmVQYXRoLCBtYXBwaW5nLnNvdXJjZSlcbiAgICAgICAgICA6IG1hcHBpbmcuc291cmNlO1xuICAgICAgICBub2RlLmFkZChuZXcgU291cmNlTm9kZShtYXBwaW5nLm9yaWdpbmFsTGluZSxcbiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgbWFwcGluZy5vcmlnaW5hbENvbHVtbixcbiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgc291cmNlLFxuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICBjb2RlLFxuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICBtYXBwaW5nLm5hbWUpKTtcbiAgICAgIH1cbiAgICB9XG4gIH07XG5cbi8qKlxuICogQWRkIGEgY2h1bmsgb2YgZ2VuZXJhdGVkIEpTIHRvIHRoaXMgc291cmNlIG5vZGUuXG4gKlxuICogQHBhcmFtIGFDaHVuayBBIHN0cmluZyBzbmlwcGV0IG9mIGdlbmVyYXRlZCBKUyBjb2RlLCBhbm90aGVyIGluc3RhbmNlIG9mXG4gKiAgICAgICAgU291cmNlTm9kZSwgb3IgYW4gYXJyYXkgd2hlcmUgZWFjaCBtZW1iZXIgaXMgb25lIG9mIHRob3NlIHRoaW5ncy5cbiAqL1xuU291cmNlTm9kZS5wcm90b3R5cGUuYWRkID0gZnVuY3Rpb24gU291cmNlTm9kZV9hZGQoYUNodW5rKSB7XG4gIGlmIChBcnJheS5pc0FycmF5KGFDaHVuaykpIHtcbiAgICBhQ2h1bmsuZm9yRWFjaChmdW5jdGlvbiAoY2h1bmspIHtcbiAgICAgIHRoaXMuYWRkKGNodW5rKTtcbiAgICB9LCB0aGlzKTtcbiAgfVxuICBlbHNlIGlmIChhQ2h1bmtbaXNTb3VyY2VOb2RlXSB8fCB0eXBlb2YgYUNodW5rID09PSBcInN0cmluZ1wiKSB7XG4gICAgaWYgKGFDaHVuaykge1xuICAgICAgdGhpcy5jaGlsZHJlbi5wdXNoKGFDaHVuayk7XG4gICAgfVxuICB9XG4gIGVsc2Uge1xuICAgIHRocm93IG5ldyBUeXBlRXJyb3IoXG4gICAgICBcIkV4cGVjdGVkIGEgU291cmNlTm9kZSwgc3RyaW5nLCBvciBhbiBhcnJheSBvZiBTb3VyY2VOb2RlcyBhbmQgc3RyaW5ncy4gR290IFwiICsgYUNodW5rXG4gICAgKTtcbiAgfVxuICByZXR1cm4gdGhpcztcbn07XG5cbi8qKlxuICogQWRkIGEgY2h1bmsgb2YgZ2VuZXJhdGVkIEpTIHRvIHRoZSBiZWdpbm5pbmcgb2YgdGhpcyBzb3VyY2Ugbm9kZS5cbiAqXG4gKiBAcGFyYW0gYUNodW5rIEEgc3RyaW5nIHNuaXBwZXQgb2YgZ2VuZXJhdGVkIEpTIGNvZGUsIGFub3RoZXIgaW5zdGFuY2Ugb2ZcbiAqICAgICAgICBTb3VyY2VOb2RlLCBvciBhbiBhcnJheSB3aGVyZSBlYWNoIG1lbWJlciBpcyBvbmUgb2YgdGhvc2UgdGhpbmdzLlxuICovXG5Tb3VyY2VOb2RlLnByb3RvdHlwZS5wcmVwZW5kID0gZnVuY3Rpb24gU291cmNlTm9kZV9wcmVwZW5kKGFDaHVuaykge1xuICBpZiAoQXJyYXkuaXNBcnJheShhQ2h1bmspKSB7XG4gICAgZm9yICh2YXIgaSA9IGFDaHVuay5sZW5ndGgtMTsgaSA+PSAwOyBpLS0pIHtcbiAgICAgIHRoaXMucHJlcGVuZChhQ2h1bmtbaV0pO1xuICAgIH1cbiAgfVxuICBlbHNlIGlmIChhQ2h1bmtbaXNTb3VyY2VOb2RlXSB8fCB0eXBlb2YgYUNodW5rID09PSBcInN0cmluZ1wiKSB7XG4gICAgdGhpcy5jaGlsZHJlbi51bnNoaWZ0KGFDaHVuayk7XG4gIH1cbiAgZWxzZSB7XG4gICAgdGhyb3cgbmV3IFR5cGVFcnJvcihcbiAgICAgIFwiRXhwZWN0ZWQgYSBTb3VyY2VOb2RlLCBzdHJpbmcsIG9yIGFuIGFycmF5IG9mIFNvdXJjZU5vZGVzIGFuZCBzdHJpbmdzLiBHb3QgXCIgKyBhQ2h1bmtcbiAgICApO1xuICB9XG4gIHJldHVybiB0aGlzO1xufTtcblxuLyoqXG4gKiBXYWxrIG92ZXIgdGhlIHRyZWUgb2YgSlMgc25pcHBldHMgaW4gdGhpcyBub2RlIGFuZCBpdHMgY2hpbGRyZW4uIFRoZVxuICogd2Fsa2luZyBmdW5jdGlvbiBpcyBjYWxsZWQgb25jZSBmb3IgZWFjaCBzbmlwcGV0IG9mIEpTIGFuZCBpcyBwYXNzZWQgdGhhdFxuICogc25pcHBldCBhbmQgdGhlIGl0cyBvcmlnaW5hbCBhc3NvY2lhdGVkIHNvdXJjZSdzIGxpbmUvY29sdW1uIGxvY2F0aW9uLlxuICpcbiAqIEBwYXJhbSBhRm4gVGhlIHRyYXZlcnNhbCBmdW5jdGlvbi5cbiAqL1xuU291cmNlTm9kZS5wcm90b3R5cGUud2FsayA9IGZ1bmN0aW9uIFNvdXJjZU5vZGVfd2FsayhhRm4pIHtcbiAgdmFyIGNodW5rO1xuICBmb3IgKHZhciBpID0gMCwgbGVuID0gdGhpcy5jaGlsZHJlbi5sZW5ndGg7IGkgPCBsZW47IGkrKykge1xuICAgIGNodW5rID0gdGhpcy5jaGlsZHJlbltpXTtcbiAgICBpZiAoY2h1bmtbaXNTb3VyY2VOb2RlXSkge1xuICAgICAgY2h1bmsud2FsayhhRm4pO1xuICAgIH1cbiAgICBlbHNlIHtcbiAgICAgIGlmIChjaHVuayAhPT0gJycpIHtcbiAgICAgICAgYUZuKGNodW5rLCB7IHNvdXJjZTogdGhpcy5zb3VyY2UsXG4gICAgICAgICAgICAgICAgICAgICBsaW5lOiB0aGlzLmxpbmUsXG4gICAgICAgICAgICAgICAgICAgICBjb2x1bW46IHRoaXMuY29sdW1uLFxuICAgICAgICAgICAgICAgICAgICAgbmFtZTogdGhpcy5uYW1lIH0pO1xuICAgICAgfVxuICAgIH1cbiAgfVxufTtcblxuLyoqXG4gKiBMaWtlIGBTdHJpbmcucHJvdG90eXBlLmpvaW5gIGV4Y2VwdCBmb3IgU291cmNlTm9kZXMuIEluc2VydHMgYGFTdHJgIGJldHdlZW5cbiAqIGVhY2ggb2YgYHRoaXMuY2hpbGRyZW5gLlxuICpcbiAqIEBwYXJhbSBhU2VwIFRoZSBzZXBhcmF0b3IuXG4gKi9cblNvdXJjZU5vZGUucHJvdG90eXBlLmpvaW4gPSBmdW5jdGlvbiBTb3VyY2VOb2RlX2pvaW4oYVNlcCkge1xuICB2YXIgbmV3Q2hpbGRyZW47XG4gIHZhciBpO1xuICB2YXIgbGVuID0gdGhpcy5jaGlsZHJlbi5sZW5ndGg7XG4gIGlmIChsZW4gPiAwKSB7XG4gICAgbmV3Q2hpbGRyZW4gPSBbXTtcbiAgICBmb3IgKGkgPSAwOyBpIDwgbGVuLTE7IGkrKykge1xuICAgICAgbmV3Q2hpbGRyZW4ucHVzaCh0aGlzLmNoaWxkcmVuW2ldKTtcbiAgICAgIG5ld0NoaWxkcmVuLnB1c2goYVNlcCk7XG4gICAgfVxuICAgIG5ld0NoaWxkcmVuLnB1c2godGhpcy5jaGlsZHJlbltpXSk7XG4gICAgdGhpcy5jaGlsZHJlbiA9IG5ld0NoaWxkcmVuO1xuICB9XG4gIHJldHVybiB0aGlzO1xufTtcblxuLyoqXG4gKiBDYWxsIFN0cmluZy5wcm90b3R5cGUucmVwbGFjZSBvbiB0aGUgdmVyeSByaWdodC1tb3N0IHNvdXJjZSBzbmlwcGV0LiBVc2VmdWxcbiAqIGZvciB0cmltbWluZyB3aGl0ZXNwYWNlIGZyb20gdGhlIGVuZCBvZiBhIHNvdXJjZSBub2RlLCBldGMuXG4gKlxuICogQHBhcmFtIGFQYXR0ZXJuIFRoZSBwYXR0ZXJuIHRvIHJlcGxhY2UuXG4gKiBAcGFyYW0gYVJlcGxhY2VtZW50IFRoZSB0aGluZyB0byByZXBsYWNlIHRoZSBwYXR0ZXJuIHdpdGguXG4gKi9cblNvdXJjZU5vZGUucHJvdG90eXBlLnJlcGxhY2VSaWdodCA9IGZ1bmN0aW9uIFNvdXJjZU5vZGVfcmVwbGFjZVJpZ2h0KGFQYXR0ZXJuLCBhUmVwbGFjZW1lbnQpIHtcbiAgdmFyIGxhc3RDaGlsZCA9IHRoaXMuY2hpbGRyZW5bdGhpcy5jaGlsZHJlbi5sZW5ndGggLSAxXTtcbiAgaWYgKGxhc3RDaGlsZFtpc1NvdXJjZU5vZGVdKSB7XG4gICAgbGFzdENoaWxkLnJlcGxhY2VSaWdodChhUGF0dGVybiwgYVJlcGxhY2VtZW50KTtcbiAgfVxuICBlbHNlIGlmICh0eXBlb2YgbGFzdENoaWxkID09PSAnc3RyaW5nJykge1xuICAgIHRoaXMuY2hpbGRyZW5bdGhpcy5jaGlsZHJlbi5sZW5ndGggLSAxXSA9IGxhc3RDaGlsZC5yZXBsYWNlKGFQYXR0ZXJuLCBhUmVwbGFjZW1lbnQpO1xuICB9XG4gIGVsc2Uge1xuICAgIHRoaXMuY2hpbGRyZW4ucHVzaCgnJy5yZXBsYWNlKGFQYXR0ZXJuLCBhUmVwbGFjZW1lbnQpKTtcbiAgfVxuICByZXR1cm4gdGhpcztcbn07XG5cbi8qKlxuICogU2V0IHRoZSBzb3VyY2UgY29udGVudCBmb3IgYSBzb3VyY2UgZmlsZS4gVGhpcyB3aWxsIGJlIGFkZGVkIHRvIHRoZSBTb3VyY2VNYXBHZW5lcmF0b3JcbiAqIGluIHRoZSBzb3VyY2VzQ29udGVudCBmaWVsZC5cbiAqXG4gKiBAcGFyYW0gYVNvdXJjZUZpbGUgVGhlIGZpbGVuYW1lIG9mIHRoZSBzb3VyY2UgZmlsZVxuICogQHBhcmFtIGFTb3VyY2VDb250ZW50IFRoZSBjb250ZW50IG9mIHRoZSBzb3VyY2UgZmlsZVxuICovXG5Tb3VyY2VOb2RlLnByb3RvdHlwZS5zZXRTb3VyY2VDb250ZW50ID1cbiAgZnVuY3Rpb24gU291cmNlTm9kZV9zZXRTb3VyY2VDb250ZW50KGFTb3VyY2VGaWxlLCBhU291cmNlQ29udGVudCkge1xuICAgIHRoaXMuc291cmNlQ29udGVudHNbdXRpbC50b1NldFN0cmluZyhhU291cmNlRmlsZSldID0gYVNvdXJjZUNvbnRlbnQ7XG4gIH07XG5cbi8qKlxuICogV2FsayBvdmVyIHRoZSB0cmVlIG9mIFNvdXJjZU5vZGVzLiBUaGUgd2Fsa2luZyBmdW5jdGlvbiBpcyBjYWxsZWQgZm9yIGVhY2hcbiAqIHNvdXJjZSBmaWxlIGNvbnRlbnQgYW5kIGlzIHBhc3NlZCB0aGUgZmlsZW5hbWUgYW5kIHNvdXJjZSBjb250ZW50LlxuICpcbiAqIEBwYXJhbSBhRm4gVGhlIHRyYXZlcnNhbCBmdW5jdGlvbi5cbiAqL1xuU291cmNlTm9kZS5wcm90b3R5cGUud2Fsa1NvdXJjZUNvbnRlbnRzID1cbiAgZnVuY3Rpb24gU291cmNlTm9kZV93YWxrU291cmNlQ29udGVudHMoYUZuKSB7XG4gICAgZm9yICh2YXIgaSA9IDAsIGxlbiA9IHRoaXMuY2hpbGRyZW4ubGVuZ3RoOyBpIDwgbGVuOyBpKyspIHtcbiAgICAgIGlmICh0aGlzLmNoaWxkcmVuW2ldW2lzU291cmNlTm9kZV0pIHtcbiAgICAgICAgdGhpcy5jaGlsZHJlbltpXS53YWxrU291cmNlQ29udGVudHMoYUZuKTtcbiAgICAgIH1cbiAgICB9XG5cbiAgICB2YXIgc291cmNlcyA9IE9iamVjdC5rZXlzKHRoaXMuc291cmNlQ29udGVudHMpO1xuICAgIGZvciAodmFyIGkgPSAwLCBsZW4gPSBzb3VyY2VzLmxlbmd0aDsgaSA8IGxlbjsgaSsrKSB7XG4gICAgICBhRm4odXRpbC5mcm9tU2V0U3RyaW5nKHNvdXJjZXNbaV0pLCB0aGlzLnNvdXJjZUNvbnRlbnRzW3NvdXJjZXNbaV1dKTtcbiAgICB9XG4gIH07XG5cbi8qKlxuICogUmV0dXJuIHRoZSBzdHJpbmcgcmVwcmVzZW50YXRpb24gb2YgdGhpcyBzb3VyY2Ugbm9kZS4gV2Fsa3Mgb3ZlciB0aGUgdHJlZVxuICogYW5kIGNvbmNhdGVuYXRlcyBhbGwgdGhlIHZhcmlvdXMgc25pcHBldHMgdG9nZXRoZXIgdG8gb25lIHN0cmluZy5cbiAqL1xuU291cmNlTm9kZS5wcm90b3R5cGUudG9TdHJpbmcgPSBmdW5jdGlvbiBTb3VyY2VOb2RlX3RvU3RyaW5nKCkge1xuICB2YXIgc3RyID0gXCJcIjtcbiAgdGhpcy53YWxrKGZ1bmN0aW9uIChjaHVuaykge1xuICAgIHN0ciArPSBjaHVuaztcbiAgfSk7XG4gIHJldHVybiBzdHI7XG59O1xuXG4vKipcbiAqIFJldHVybnMgdGhlIHN0cmluZyByZXByZXNlbnRhdGlvbiBvZiB0aGlzIHNvdXJjZSBub2RlIGFsb25nIHdpdGggYSBzb3VyY2VcbiAqIG1hcC5cbiAqL1xuU291cmNlTm9kZS5wcm90b3R5cGUudG9TdHJpbmdXaXRoU291cmNlTWFwID0gZnVuY3Rpb24gU291cmNlTm9kZV90b1N0cmluZ1dpdGhTb3VyY2VNYXAoYUFyZ3MpIHtcbiAgdmFyIGdlbmVyYXRlZCA9IHtcbiAgICBjb2RlOiBcIlwiLFxuICAgIGxpbmU6IDEsXG4gICAgY29sdW1uOiAwXG4gIH07XG4gIHZhciBtYXAgPSBuZXcgU291cmNlTWFwR2VuZXJhdG9yKGFBcmdzKTtcbiAgdmFyIHNvdXJjZU1hcHBpbmdBY3RpdmUgPSBmYWxzZTtcbiAgdmFyIGxhc3RPcmlnaW5hbFNvdXJjZSA9IG51bGw7XG4gIHZhciBsYXN0T3JpZ2luYWxMaW5lID0gbnVsbDtcbiAgdmFyIGxhc3RPcmlnaW5hbENvbHVtbiA9IG51bGw7XG4gIHZhciBsYXN0T3JpZ2luYWxOYW1lID0gbnVsbDtcbiAgdGhpcy53YWxrKGZ1bmN0aW9uIChjaHVuaywgb3JpZ2luYWwpIHtcbiAgICBnZW5lcmF0ZWQuY29kZSArPSBjaHVuaztcbiAgICBpZiAob3JpZ2luYWwuc291cmNlICE9PSBudWxsXG4gICAgICAgICYmIG9yaWdpbmFsLmxpbmUgIT09IG51bGxcbiAgICAgICAgJiYgb3JpZ2luYWwuY29sdW1uICE9PSBudWxsKSB7XG4gICAgICBpZihsYXN0T3JpZ2luYWxTb3VyY2UgIT09IG9yaWdpbmFsLnNvdXJjZVxuICAgICAgICAgfHwgbGFzdE9yaWdpbmFsTGluZSAhPT0gb3JpZ2luYWwubGluZVxuICAgICAgICAgfHwgbGFzdE9yaWdpbmFsQ29sdW1uICE9PSBvcmlnaW5hbC5jb2x1bW5cbiAgICAgICAgIHx8IGxhc3RPcmlnaW5hbE5hbWUgIT09IG9yaWdpbmFsLm5hbWUpIHtcbiAgICAgICAgbWFwLmFkZE1hcHBpbmcoe1xuICAgICAgICAgIHNvdXJjZTogb3JpZ2luYWwuc291cmNlLFxuICAgICAgICAgIG9yaWdpbmFsOiB7XG4gICAgICAgICAgICBsaW5lOiBvcmlnaW5hbC5saW5lLFxuICAgICAgICAgICAgY29sdW1uOiBvcmlnaW5hbC5jb2x1bW5cbiAgICAgICAgICB9LFxuICAgICAgICAgIGdlbmVyYXRlZDoge1xuICAgICAgICAgICAgbGluZTogZ2VuZXJhdGVkLmxpbmUsXG4gICAgICAgICAgICBjb2x1bW46IGdlbmVyYXRlZC5jb2x1bW5cbiAgICAgICAgICB9LFxuICAgICAgICAgIG5hbWU6IG9yaWdpbmFsLm5hbWVcbiAgICAgICAgfSk7XG4gICAgICB9XG4gICAgICBsYXN0T3JpZ2luYWxTb3VyY2UgPSBvcmlnaW5hbC5zb3VyY2U7XG4gICAgICBsYXN0T3JpZ2luYWxMaW5lID0gb3JpZ2luYWwubGluZTtcbiAgICAgIGxhc3RPcmlnaW5hbENvbHVtbiA9IG9yaWdpbmFsLmNvbHVtbjtcbiAgICAgIGxhc3RPcmlnaW5hbE5hbWUgPSBvcmlnaW5hbC5uYW1lO1xuICAgICAgc291cmNlTWFwcGluZ0FjdGl2ZSA9IHRydWU7XG4gICAgfSBlbHNlIGlmIChzb3VyY2VNYXBwaW5nQWN0aXZlKSB7XG4gICAgICBtYXAuYWRkTWFwcGluZyh7XG4gICAgICAgIGdlbmVyYXRlZDoge1xuICAgICAgICAgIGxpbmU6IGdlbmVyYXRlZC5saW5lLFxuICAgICAgICAgIGNvbHVtbjogZ2VuZXJhdGVkLmNvbHVtblxuICAgICAgICB9XG4gICAgICB9KTtcbiAgICAgIGxhc3RPcmlnaW5hbFNvdXJjZSA9IG51bGw7XG4gICAgICBzb3VyY2VNYXBwaW5nQWN0aXZlID0gZmFsc2U7XG4gICAgfVxuICAgIGZvciAodmFyIGlkeCA9IDAsIGxlbmd0aCA9IGNodW5rLmxlbmd0aDsgaWR4IDwgbGVuZ3RoOyBpZHgrKykge1xuICAgICAgaWYgKGNodW5rLmNoYXJDb2RlQXQoaWR4KSA9PT0gTkVXTElORV9DT0RFKSB7XG4gICAgICAgIGdlbmVyYXRlZC5saW5lKys7XG4gICAgICAgIGdlbmVyYXRlZC5jb2x1bW4gPSAwO1xuICAgICAgICAvLyBNYXBwaW5ncyBlbmQgYXQgZW9sXG4gICAgICAgIGlmIChpZHggKyAxID09PSBsZW5ndGgpIHtcbiAgICAgICAgICBsYXN0T3JpZ2luYWxTb3VyY2UgPSBudWxsO1xuICAgICAgICAgIHNvdXJjZU1hcHBpbmdBY3RpdmUgPSBmYWxzZTtcbiAgICAgICAgfSBlbHNlIGlmIChzb3VyY2VNYXBwaW5nQWN0aXZlKSB7XG4gICAgICAgICAgbWFwLmFkZE1hcHBpbmcoe1xuICAgICAgICAgICAgc291cmNlOiBvcmlnaW5hbC5zb3VyY2UsXG4gICAgICAgICAgICBvcmlnaW5hbDoge1xuICAgICAgICAgICAgICBsaW5lOiBvcmlnaW5hbC5saW5lLFxuICAgICAgICAgICAgICBjb2x1bW46IG9yaWdpbmFsLmNvbHVtblxuICAgICAgICAgICAgfSxcbiAgICAgICAgICAgIGdlbmVyYXRlZDoge1xuICAgICAgICAgICAgICBsaW5lOiBnZW5lcmF0ZWQubGluZSxcbiAgICAgICAgICAgICAgY29sdW1uOiBnZW5lcmF0ZWQuY29sdW1uXG4gICAgICAgICAgICB9LFxuICAgICAgICAgICAgbmFtZTogb3JpZ2luYWwubmFtZVxuICAgICAgICAgIH0pO1xuICAgICAgICB9XG4gICAgICB9IGVsc2Uge1xuICAgICAgICBnZW5lcmF0ZWQuY29sdW1uKys7XG4gICAgICB9XG4gICAgfVxuICB9KTtcbiAgdGhpcy53YWxrU291cmNlQ29udGVudHMoZnVuY3Rpb24gKHNvdXJjZUZpbGUsIHNvdXJjZUNvbnRlbnQpIHtcbiAgICBtYXAuc2V0U291cmNlQ29udGVudChzb3VyY2VGaWxlLCBzb3VyY2VDb250ZW50KTtcbiAgfSk7XG5cbiAgcmV0dXJuIHsgY29kZTogZ2VuZXJhdGVkLmNvZGUsIG1hcDogbWFwIH07XG59O1xuXG5leHBvcnRzLlNvdXJjZU5vZGUgPSBTb3VyY2VOb2RlO1xuXG5cblxuLy8vLy8vLy8vLy8vLy8vLy8vXG4vLyBXRUJQQUNLIEZPT1RFUlxuLy8gLi9saWIvc291cmNlLW5vZGUuanNcbi8vIG1vZHVsZSBpZCA9IDEwXG4vLyBtb2R1bGUgY2h1bmtzID0gMCJdLCJzb3VyY2VSb290IjoiIn0= \ No newline at end of file diff --git a/node_modules/source-map/dist/source-map.js b/node_modules/source-map/dist/source-map.js new file mode 100644 index 0000000..b4eb087 --- /dev/null +++ b/node_modules/source-map/dist/source-map.js @@ -0,0 +1,3233 @@ +(function webpackUniversalModuleDefinition(root, factory) { + if(typeof exports === 'object' && typeof module === 'object') + module.exports = factory(); + else if(typeof define === 'function' && define.amd) + define([], factory); + else if(typeof exports === 'object') + exports["sourceMap"] = factory(); + else + root["sourceMap"] = factory(); +})(this, function() { +return /******/ (function(modules) { // webpackBootstrap +/******/ // The module cache +/******/ var installedModules = {}; + +/******/ // The require function +/******/ function __webpack_require__(moduleId) { + +/******/ // Check if module is in cache +/******/ if(installedModules[moduleId]) +/******/ return installedModules[moduleId].exports; + +/******/ // Create a new module (and put it into the cache) +/******/ var module = installedModules[moduleId] = { +/******/ exports: {}, +/******/ id: moduleId, +/******/ loaded: false +/******/ }; + +/******/ // Execute the module function +/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); + +/******/ // Flag the module as loaded +/******/ module.loaded = true; + +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } + + +/******/ // expose the modules object (__webpack_modules__) +/******/ __webpack_require__.m = modules; + +/******/ // expose the module cache +/******/ __webpack_require__.c = installedModules; + +/******/ // __webpack_public_path__ +/******/ __webpack_require__.p = ""; + +/******/ // Load entry module and return exports +/******/ return __webpack_require__(0); +/******/ }) +/************************************************************************/ +/******/ ([ +/* 0 */ +/***/ (function(module, exports, __webpack_require__) { + + /* + * Copyright 2009-2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE.txt or: + * http://opensource.org/licenses/BSD-3-Clause + */ + exports.SourceMapGenerator = __webpack_require__(1).SourceMapGenerator; + exports.SourceMapConsumer = __webpack_require__(7).SourceMapConsumer; + exports.SourceNode = __webpack_require__(10).SourceNode; + + +/***/ }), +/* 1 */ +/***/ (function(module, exports, __webpack_require__) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + var base64VLQ = __webpack_require__(2); + var util = __webpack_require__(4); + var ArraySet = __webpack_require__(5).ArraySet; + var MappingList = __webpack_require__(6).MappingList; + + /** + * An instance of the SourceMapGenerator represents a source map which is + * being built incrementally. You may pass an object with the following + * properties: + * + * - file: The filename of the generated source. + * - sourceRoot: A root for all relative URLs in this source map. + */ + function SourceMapGenerator(aArgs) { + if (!aArgs) { + aArgs = {}; + } + this._file = util.getArg(aArgs, 'file', null); + this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null); + this._skipValidation = util.getArg(aArgs, 'skipValidation', false); + this._sources = new ArraySet(); + this._names = new ArraySet(); + this._mappings = new MappingList(); + this._sourcesContents = null; + } + + SourceMapGenerator.prototype._version = 3; + + /** + * Creates a new SourceMapGenerator based on a SourceMapConsumer + * + * @param aSourceMapConsumer The SourceMap. + */ + SourceMapGenerator.fromSourceMap = + function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) { + var sourceRoot = aSourceMapConsumer.sourceRoot; + var generator = new SourceMapGenerator({ + file: aSourceMapConsumer.file, + sourceRoot: sourceRoot + }); + aSourceMapConsumer.eachMapping(function (mapping) { + var newMapping = { + generated: { + line: mapping.generatedLine, + column: mapping.generatedColumn + } + }; + + if (mapping.source != null) { + newMapping.source = mapping.source; + if (sourceRoot != null) { + newMapping.source = util.relative(sourceRoot, newMapping.source); + } + + newMapping.original = { + line: mapping.originalLine, + column: mapping.originalColumn + }; + + if (mapping.name != null) { + newMapping.name = mapping.name; + } + } + + generator.addMapping(newMapping); + }); + aSourceMapConsumer.sources.forEach(function (sourceFile) { + var sourceRelative = sourceFile; + if (sourceRoot !== null) { + sourceRelative = util.relative(sourceRoot, sourceFile); + } + + if (!generator._sources.has(sourceRelative)) { + generator._sources.add(sourceRelative); + } + + var content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content != null) { + generator.setSourceContent(sourceFile, content); + } + }); + return generator; + }; + + /** + * Add a single mapping from original source line and column to the generated + * source's line and column for this source map being created. The mapping + * object should have the following properties: + * + * - generated: An object with the generated line and column positions. + * - original: An object with the original line and column positions. + * - source: The original source file (relative to the sourceRoot). + * - name: An optional original token name for this mapping. + */ + SourceMapGenerator.prototype.addMapping = + function SourceMapGenerator_addMapping(aArgs) { + var generated = util.getArg(aArgs, 'generated'); + var original = util.getArg(aArgs, 'original', null); + var source = util.getArg(aArgs, 'source', null); + var name = util.getArg(aArgs, 'name', null); + + if (!this._skipValidation) { + this._validateMapping(generated, original, source, name); + } + + if (source != null) { + source = String(source); + if (!this._sources.has(source)) { + this._sources.add(source); + } + } + + if (name != null) { + name = String(name); + if (!this._names.has(name)) { + this._names.add(name); + } + } + + this._mappings.add({ + generatedLine: generated.line, + generatedColumn: generated.column, + originalLine: original != null && original.line, + originalColumn: original != null && original.column, + source: source, + name: name + }); + }; + + /** + * Set the source content for a source file. + */ + SourceMapGenerator.prototype.setSourceContent = + function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) { + var source = aSourceFile; + if (this._sourceRoot != null) { + source = util.relative(this._sourceRoot, source); + } + + if (aSourceContent != null) { + // Add the source content to the _sourcesContents map. + // Create a new _sourcesContents map if the property is null. + if (!this._sourcesContents) { + this._sourcesContents = Object.create(null); + } + this._sourcesContents[util.toSetString(source)] = aSourceContent; + } else if (this._sourcesContents) { + // Remove the source file from the _sourcesContents map. + // If the _sourcesContents map is empty, set the property to null. + delete this._sourcesContents[util.toSetString(source)]; + if (Object.keys(this._sourcesContents).length === 0) { + this._sourcesContents = null; + } + } + }; + + /** + * Applies the mappings of a sub-source-map for a specific source file to the + * source map being generated. Each mapping to the supplied source file is + * rewritten using the supplied source map. Note: The resolution for the + * resulting mappings is the minimium of this map and the supplied map. + * + * @param aSourceMapConsumer The source map to be applied. + * @param aSourceFile Optional. The filename of the source file. + * If omitted, SourceMapConsumer's file property will be used. + * @param aSourceMapPath Optional. The dirname of the path to the source map + * to be applied. If relative, it is relative to the SourceMapConsumer. + * This parameter is needed when the two source maps aren't in the same + * directory, and the source map to be applied contains relative source + * paths. If so, those relative source paths need to be rewritten + * relative to the SourceMapGenerator. + */ + SourceMapGenerator.prototype.applySourceMap = + function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) { + var sourceFile = aSourceFile; + // If aSourceFile is omitted, we will use the file property of the SourceMap + if (aSourceFile == null) { + if (aSourceMapConsumer.file == null) { + throw new Error( + 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' + + 'or the source map\'s "file" property. Both were omitted.' + ); + } + sourceFile = aSourceMapConsumer.file; + } + var sourceRoot = this._sourceRoot; + // Make "sourceFile" relative if an absolute Url is passed. + if (sourceRoot != null) { + sourceFile = util.relative(sourceRoot, sourceFile); + } + // Applying the SourceMap can add and remove items from the sources and + // the names array. + var newSources = new ArraySet(); + var newNames = new ArraySet(); + + // Find mappings for the "sourceFile" + this._mappings.unsortedForEach(function (mapping) { + if (mapping.source === sourceFile && mapping.originalLine != null) { + // Check if it can be mapped by the source map, then update the mapping. + var original = aSourceMapConsumer.originalPositionFor({ + line: mapping.originalLine, + column: mapping.originalColumn + }); + if (original.source != null) { + // Copy mapping + mapping.source = original.source; + if (aSourceMapPath != null) { + mapping.source = util.join(aSourceMapPath, mapping.source) + } + if (sourceRoot != null) { + mapping.source = util.relative(sourceRoot, mapping.source); + } + mapping.originalLine = original.line; + mapping.originalColumn = original.column; + if (original.name != null) { + mapping.name = original.name; + } + } + } + + var source = mapping.source; + if (source != null && !newSources.has(source)) { + newSources.add(source); + } + + var name = mapping.name; + if (name != null && !newNames.has(name)) { + newNames.add(name); + } + + }, this); + this._sources = newSources; + this._names = newNames; + + // Copy sourcesContents of applied map. + aSourceMapConsumer.sources.forEach(function (sourceFile) { + var content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content != null) { + if (aSourceMapPath != null) { + sourceFile = util.join(aSourceMapPath, sourceFile); + } + if (sourceRoot != null) { + sourceFile = util.relative(sourceRoot, sourceFile); + } + this.setSourceContent(sourceFile, content); + } + }, this); + }; + + /** + * A mapping can have one of the three levels of data: + * + * 1. Just the generated position. + * 2. The Generated position, original position, and original source. + * 3. Generated and original position, original source, as well as a name + * token. + * + * To maintain consistency, we validate that any new mapping being added falls + * in to one of these categories. + */ + SourceMapGenerator.prototype._validateMapping = + function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource, + aName) { + // When aOriginal is truthy but has empty values for .line and .column, + // it is most likely a programmer error. In this case we throw a very + // specific error message to try to guide them the right way. + // For example: https://github.com/Polymer/polymer-bundler/pull/519 + if (aOriginal && typeof aOriginal.line !== 'number' && typeof aOriginal.column !== 'number') { + throw new Error( + 'original.line and original.column are not numbers -- you probably meant to omit ' + + 'the original mapping entirely and only map the generated position. If so, pass ' + + 'null for the original mapping instead of an object with empty or null values.' + ); + } + + if (aGenerated && 'line' in aGenerated && 'column' in aGenerated + && aGenerated.line > 0 && aGenerated.column >= 0 + && !aOriginal && !aSource && !aName) { + // Case 1. + return; + } + else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated + && aOriginal && 'line' in aOriginal && 'column' in aOriginal + && aGenerated.line > 0 && aGenerated.column >= 0 + && aOriginal.line > 0 && aOriginal.column >= 0 + && aSource) { + // Cases 2 and 3. + return; + } + else { + throw new Error('Invalid mapping: ' + JSON.stringify({ + generated: aGenerated, + source: aSource, + original: aOriginal, + name: aName + })); + } + }; + + /** + * Serialize the accumulated mappings in to the stream of base 64 VLQs + * specified by the source map format. + */ + SourceMapGenerator.prototype._serializeMappings = + function SourceMapGenerator_serializeMappings() { + var previousGeneratedColumn = 0; + var previousGeneratedLine = 1; + var previousOriginalColumn = 0; + var previousOriginalLine = 0; + var previousName = 0; + var previousSource = 0; + var result = ''; + var next; + var mapping; + var nameIdx; + var sourceIdx; + + var mappings = this._mappings.toArray(); + for (var i = 0, len = mappings.length; i < len; i++) { + mapping = mappings[i]; + next = '' + + if (mapping.generatedLine !== previousGeneratedLine) { + previousGeneratedColumn = 0; + while (mapping.generatedLine !== previousGeneratedLine) { + next += ';'; + previousGeneratedLine++; + } + } + else { + if (i > 0) { + if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) { + continue; + } + next += ','; + } + } + + next += base64VLQ.encode(mapping.generatedColumn + - previousGeneratedColumn); + previousGeneratedColumn = mapping.generatedColumn; + + if (mapping.source != null) { + sourceIdx = this._sources.indexOf(mapping.source); + next += base64VLQ.encode(sourceIdx - previousSource); + previousSource = sourceIdx; + + // lines are stored 0-based in SourceMap spec version 3 + next += base64VLQ.encode(mapping.originalLine - 1 + - previousOriginalLine); + previousOriginalLine = mapping.originalLine - 1; + + next += base64VLQ.encode(mapping.originalColumn + - previousOriginalColumn); + previousOriginalColumn = mapping.originalColumn; + + if (mapping.name != null) { + nameIdx = this._names.indexOf(mapping.name); + next += base64VLQ.encode(nameIdx - previousName); + previousName = nameIdx; + } + } + + result += next; + } + + return result; + }; + + SourceMapGenerator.prototype._generateSourcesContent = + function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) { + return aSources.map(function (source) { + if (!this._sourcesContents) { + return null; + } + if (aSourceRoot != null) { + source = util.relative(aSourceRoot, source); + } + var key = util.toSetString(source); + return Object.prototype.hasOwnProperty.call(this._sourcesContents, key) + ? this._sourcesContents[key] + : null; + }, this); + }; + + /** + * Externalize the source map. + */ + SourceMapGenerator.prototype.toJSON = + function SourceMapGenerator_toJSON() { + var map = { + version: this._version, + sources: this._sources.toArray(), + names: this._names.toArray(), + mappings: this._serializeMappings() + }; + if (this._file != null) { + map.file = this._file; + } + if (this._sourceRoot != null) { + map.sourceRoot = this._sourceRoot; + } + if (this._sourcesContents) { + map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot); + } + + return map; + }; + + /** + * Render the source map being generated to a string. + */ + SourceMapGenerator.prototype.toString = + function SourceMapGenerator_toString() { + return JSON.stringify(this.toJSON()); + }; + + exports.SourceMapGenerator = SourceMapGenerator; + + +/***/ }), +/* 2 */ +/***/ (function(module, exports, __webpack_require__) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + * + * Based on the Base 64 VLQ implementation in Closure Compiler: + * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java + * + * Copyright 2011 The Closure Compiler Authors. All rights reserved. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + + var base64 = __webpack_require__(3); + + // A single base 64 digit can contain 6 bits of data. For the base 64 variable + // length quantities we use in the source map spec, the first bit is the sign, + // the next four bits are the actual value, and the 6th bit is the + // continuation bit. The continuation bit tells us whether there are more + // digits in this value following this digit. + // + // Continuation + // | Sign + // | | + // V V + // 101011 + + var VLQ_BASE_SHIFT = 5; + + // binary: 100000 + var VLQ_BASE = 1 << VLQ_BASE_SHIFT; + + // binary: 011111 + var VLQ_BASE_MASK = VLQ_BASE - 1; + + // binary: 100000 + var VLQ_CONTINUATION_BIT = VLQ_BASE; + + /** + * Converts from a two-complement value to a value where the sign bit is + * placed in the least significant bit. For example, as decimals: + * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary) + * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary) + */ + function toVLQSigned(aValue) { + return aValue < 0 + ? ((-aValue) << 1) + 1 + : (aValue << 1) + 0; + } + + /** + * Converts to a two-complement value from a value where the sign bit is + * placed in the least significant bit. For example, as decimals: + * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1 + * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2 + */ + function fromVLQSigned(aValue) { + var isNegative = (aValue & 1) === 1; + var shifted = aValue >> 1; + return isNegative + ? -shifted + : shifted; + } + + /** + * Returns the base 64 VLQ encoded value. + */ + exports.encode = function base64VLQ_encode(aValue) { + var encoded = ""; + var digit; + + var vlq = toVLQSigned(aValue); + + do { + digit = vlq & VLQ_BASE_MASK; + vlq >>>= VLQ_BASE_SHIFT; + if (vlq > 0) { + // There are still more digits in this value, so we must make sure the + // continuation bit is marked. + digit |= VLQ_CONTINUATION_BIT; + } + encoded += base64.encode(digit); + } while (vlq > 0); + + return encoded; + }; + + /** + * Decodes the next base 64 VLQ value from the given string and returns the + * value and the rest of the string via the out parameter. + */ + exports.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) { + var strLen = aStr.length; + var result = 0; + var shift = 0; + var continuation, digit; + + do { + if (aIndex >= strLen) { + throw new Error("Expected more digits in base 64 VLQ value."); + } + + digit = base64.decode(aStr.charCodeAt(aIndex++)); + if (digit === -1) { + throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1)); + } + + continuation = !!(digit & VLQ_CONTINUATION_BIT); + digit &= VLQ_BASE_MASK; + result = result + (digit << shift); + shift += VLQ_BASE_SHIFT; + } while (continuation); + + aOutParam.value = fromVLQSigned(result); + aOutParam.rest = aIndex; + }; + + +/***/ }), +/* 3 */ +/***/ (function(module, exports) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + var intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split(''); + + /** + * Encode an integer in the range of 0 to 63 to a single base 64 digit. + */ + exports.encode = function (number) { + if (0 <= number && number < intToCharMap.length) { + return intToCharMap[number]; + } + throw new TypeError("Must be between 0 and 63: " + number); + }; + + /** + * Decode a single base 64 character code digit to an integer. Returns -1 on + * failure. + */ + exports.decode = function (charCode) { + var bigA = 65; // 'A' + var bigZ = 90; // 'Z' + + var littleA = 97; // 'a' + var littleZ = 122; // 'z' + + var zero = 48; // '0' + var nine = 57; // '9' + + var plus = 43; // '+' + var slash = 47; // '/' + + var littleOffset = 26; + var numberOffset = 52; + + // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ + if (bigA <= charCode && charCode <= bigZ) { + return (charCode - bigA); + } + + // 26 - 51: abcdefghijklmnopqrstuvwxyz + if (littleA <= charCode && charCode <= littleZ) { + return (charCode - littleA + littleOffset); + } + + // 52 - 61: 0123456789 + if (zero <= charCode && charCode <= nine) { + return (charCode - zero + numberOffset); + } + + // 62: + + if (charCode == plus) { + return 62; + } + + // 63: / + if (charCode == slash) { + return 63; + } + + // Invalid base64 digit. + return -1; + }; + + +/***/ }), +/* 4 */ +/***/ (function(module, exports) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + /** + * This is a helper function for getting values from parameter/options + * objects. + * + * @param args The object we are extracting values from + * @param name The name of the property we are getting. + * @param defaultValue An optional value to return if the property is missing + * from the object. If this is not specified and the property is missing, an + * error will be thrown. + */ + function getArg(aArgs, aName, aDefaultValue) { + if (aName in aArgs) { + return aArgs[aName]; + } else if (arguments.length === 3) { + return aDefaultValue; + } else { + throw new Error('"' + aName + '" is a required argument.'); + } + } + exports.getArg = getArg; + + var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/; + var dataUrlRegexp = /^data:.+\,.+$/; + + function urlParse(aUrl) { + var match = aUrl.match(urlRegexp); + if (!match) { + return null; + } + return { + scheme: match[1], + auth: match[2], + host: match[3], + port: match[4], + path: match[5] + }; + } + exports.urlParse = urlParse; + + function urlGenerate(aParsedUrl) { + var url = ''; + if (aParsedUrl.scheme) { + url += aParsedUrl.scheme + ':'; + } + url += '//'; + if (aParsedUrl.auth) { + url += aParsedUrl.auth + '@'; + } + if (aParsedUrl.host) { + url += aParsedUrl.host; + } + if (aParsedUrl.port) { + url += ":" + aParsedUrl.port + } + if (aParsedUrl.path) { + url += aParsedUrl.path; + } + return url; + } + exports.urlGenerate = urlGenerate; + + /** + * Normalizes a path, or the path portion of a URL: + * + * - Replaces consecutive slashes with one slash. + * - Removes unnecessary '.' parts. + * - Removes unnecessary '/..' parts. + * + * Based on code in the Node.js 'path' core module. + * + * @param aPath The path or url to normalize. + */ + function normalize(aPath) { + var path = aPath; + var url = urlParse(aPath); + if (url) { + if (!url.path) { + return aPath; + } + path = url.path; + } + var isAbsolute = exports.isAbsolute(path); + + var parts = path.split(/\/+/); + for (var part, up = 0, i = parts.length - 1; i >= 0; i--) { + part = parts[i]; + if (part === '.') { + parts.splice(i, 1); + } else if (part === '..') { + up++; + } else if (up > 0) { + if (part === '') { + // The first part is blank if the path is absolute. Trying to go + // above the root is a no-op. Therefore we can remove all '..' parts + // directly after the root. + parts.splice(i + 1, up); + up = 0; + } else { + parts.splice(i, 2); + up--; + } + } + } + path = parts.join('/'); + + if (path === '') { + path = isAbsolute ? '/' : '.'; + } + + if (url) { + url.path = path; + return urlGenerate(url); + } + return path; + } + exports.normalize = normalize; + + /** + * Joins two paths/URLs. + * + * @param aRoot The root path or URL. + * @param aPath The path or URL to be joined with the root. + * + * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a + * scheme-relative URL: Then the scheme of aRoot, if any, is prepended + * first. + * - Otherwise aPath is a path. If aRoot is a URL, then its path portion + * is updated with the result and aRoot is returned. Otherwise the result + * is returned. + * - If aPath is absolute, the result is aPath. + * - Otherwise the two paths are joined with a slash. + * - Joining for example 'http://' and 'www.example.com' is also supported. + */ + function join(aRoot, aPath) { + if (aRoot === "") { + aRoot = "."; + } + if (aPath === "") { + aPath = "."; + } + var aPathUrl = urlParse(aPath); + var aRootUrl = urlParse(aRoot); + if (aRootUrl) { + aRoot = aRootUrl.path || '/'; + } + + // `join(foo, '//www.example.org')` + if (aPathUrl && !aPathUrl.scheme) { + if (aRootUrl) { + aPathUrl.scheme = aRootUrl.scheme; + } + return urlGenerate(aPathUrl); + } + + if (aPathUrl || aPath.match(dataUrlRegexp)) { + return aPath; + } + + // `join('http://', 'www.example.com')` + if (aRootUrl && !aRootUrl.host && !aRootUrl.path) { + aRootUrl.host = aPath; + return urlGenerate(aRootUrl); + } + + var joined = aPath.charAt(0) === '/' + ? aPath + : normalize(aRoot.replace(/\/+$/, '') + '/' + aPath); + + if (aRootUrl) { + aRootUrl.path = joined; + return urlGenerate(aRootUrl); + } + return joined; + } + exports.join = join; + + exports.isAbsolute = function (aPath) { + return aPath.charAt(0) === '/' || urlRegexp.test(aPath); + }; + + /** + * Make a path relative to a URL or another path. + * + * @param aRoot The root path or URL. + * @param aPath The path or URL to be made relative to aRoot. + */ + function relative(aRoot, aPath) { + if (aRoot === "") { + aRoot = "."; + } + + aRoot = aRoot.replace(/\/$/, ''); + + // It is possible for the path to be above the root. In this case, simply + // checking whether the root is a prefix of the path won't work. Instead, we + // need to remove components from the root one by one, until either we find + // a prefix that fits, or we run out of components to remove. + var level = 0; + while (aPath.indexOf(aRoot + '/') !== 0) { + var index = aRoot.lastIndexOf("/"); + if (index < 0) { + return aPath; + } + + // If the only part of the root that is left is the scheme (i.e. http://, + // file:///, etc.), one or more slashes (/), or simply nothing at all, we + // have exhausted all components, so the path is not relative to the root. + aRoot = aRoot.slice(0, index); + if (aRoot.match(/^([^\/]+:\/)?\/*$/)) { + return aPath; + } + + ++level; + } + + // Make sure we add a "../" for each component we removed from the root. + return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1); + } + exports.relative = relative; + + var supportsNullProto = (function () { + var obj = Object.create(null); + return !('__proto__' in obj); + }()); + + function identity (s) { + return s; + } + + /** + * Because behavior goes wacky when you set `__proto__` on objects, we + * have to prefix all the strings in our set with an arbitrary character. + * + * See https://github.com/mozilla/source-map/pull/31 and + * https://github.com/mozilla/source-map/issues/30 + * + * @param String aStr + */ + function toSetString(aStr) { + if (isProtoString(aStr)) { + return '$' + aStr; + } + + return aStr; + } + exports.toSetString = supportsNullProto ? identity : toSetString; + + function fromSetString(aStr) { + if (isProtoString(aStr)) { + return aStr.slice(1); + } + + return aStr; + } + exports.fromSetString = supportsNullProto ? identity : fromSetString; + + function isProtoString(s) { + if (!s) { + return false; + } + + var length = s.length; + + if (length < 9 /* "__proto__".length */) { + return false; + } + + if (s.charCodeAt(length - 1) !== 95 /* '_' */ || + s.charCodeAt(length - 2) !== 95 /* '_' */ || + s.charCodeAt(length - 3) !== 111 /* 'o' */ || + s.charCodeAt(length - 4) !== 116 /* 't' */ || + s.charCodeAt(length - 5) !== 111 /* 'o' */ || + s.charCodeAt(length - 6) !== 114 /* 'r' */ || + s.charCodeAt(length - 7) !== 112 /* 'p' */ || + s.charCodeAt(length - 8) !== 95 /* '_' */ || + s.charCodeAt(length - 9) !== 95 /* '_' */) { + return false; + } + + for (var i = length - 10; i >= 0; i--) { + if (s.charCodeAt(i) !== 36 /* '$' */) { + return false; + } + } + + return true; + } + + /** + * Comparator between two mappings where the original positions are compared. + * + * Optionally pass in `true` as `onlyCompareGenerated` to consider two + * mappings with the same original source/line/column, but different generated + * line and column the same. Useful when searching for a mapping with a + * stubbed out mapping. + */ + function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) { + var cmp = strcmp(mappingA.source, mappingB.source); + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0 || onlyCompareOriginal) { + return cmp; + } + + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } + + return strcmp(mappingA.name, mappingB.name); + } + exports.compareByOriginalPositions = compareByOriginalPositions; + + /** + * Comparator between two mappings with deflated source and name indices where + * the generated positions are compared. + * + * Optionally pass in `true` as `onlyCompareGenerated` to consider two + * mappings with the same generated line and column, but different + * source/name/original line and column the same. Useful when searching for a + * mapping with a stubbed out mapping. + */ + function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) { + var cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0 || onlyCompareGenerated) { + return cmp; + } + + cmp = strcmp(mappingA.source, mappingB.source); + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0) { + return cmp; + } + + return strcmp(mappingA.name, mappingB.name); + } + exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated; + + function strcmp(aStr1, aStr2) { + if (aStr1 === aStr2) { + return 0; + } + + if (aStr1 === null) { + return 1; // aStr2 !== null + } + + if (aStr2 === null) { + return -1; // aStr1 !== null + } + + if (aStr1 > aStr2) { + return 1; + } + + return -1; + } + + /** + * Comparator between two mappings with inflated source and name strings where + * the generated positions are compared. + */ + function compareByGeneratedPositionsInflated(mappingA, mappingB) { + var cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0) { + return cmp; + } + + cmp = strcmp(mappingA.source, mappingB.source); + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0) { + return cmp; + } + + return strcmp(mappingA.name, mappingB.name); + } + exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated; + + /** + * Strip any JSON XSSI avoidance prefix from the string (as documented + * in the source maps specification), and then parse the string as + * JSON. + */ + function parseSourceMapInput(str) { + return JSON.parse(str.replace(/^\)]}'[^\n]*\n/, '')); + } + exports.parseSourceMapInput = parseSourceMapInput; + + /** + * Compute the URL of a source given the the source root, the source's + * URL, and the source map's URL. + */ + function computeSourceURL(sourceRoot, sourceURL, sourceMapURL) { + sourceURL = sourceURL || ''; + + if (sourceRoot) { + // This follows what Chrome does. + if (sourceRoot[sourceRoot.length - 1] !== '/' && sourceURL[0] !== '/') { + sourceRoot += '/'; + } + // The spec says: + // Line 4: An optional source root, useful for relocating source + // files on a server or removing repeated values in the + // “sources” entry. This value is prepended to the individual + // entries in the “source” field. + sourceURL = sourceRoot + sourceURL; + } + + // Historically, SourceMapConsumer did not take the sourceMapURL as + // a parameter. This mode is still somewhat supported, which is why + // this code block is conditional. However, it's preferable to pass + // the source map URL to SourceMapConsumer, so that this function + // can implement the source URL resolution algorithm as outlined in + // the spec. This block is basically the equivalent of: + // new URL(sourceURL, sourceMapURL).toString() + // ... except it avoids using URL, which wasn't available in the + // older releases of node still supported by this library. + // + // The spec says: + // If the sources are not absolute URLs after prepending of the + // “sourceRoot”, the sources are resolved relative to the + // SourceMap (like resolving script src in a html document). + if (sourceMapURL) { + var parsed = urlParse(sourceMapURL); + if (!parsed) { + throw new Error("sourceMapURL could not be parsed"); + } + if (parsed.path) { + // Strip the last path component, but keep the "/". + var index = parsed.path.lastIndexOf('/'); + if (index >= 0) { + parsed.path = parsed.path.substring(0, index + 1); + } + } + sourceURL = join(urlGenerate(parsed), sourceURL); + } + + return normalize(sourceURL); + } + exports.computeSourceURL = computeSourceURL; + + +/***/ }), +/* 5 */ +/***/ (function(module, exports, __webpack_require__) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + var util = __webpack_require__(4); + var has = Object.prototype.hasOwnProperty; + var hasNativeMap = typeof Map !== "undefined"; + + /** + * A data structure which is a combination of an array and a set. Adding a new + * member is O(1), testing for membership is O(1), and finding the index of an + * element is O(1). Removing elements from the set is not supported. Only + * strings are supported for membership. + */ + function ArraySet() { + this._array = []; + this._set = hasNativeMap ? new Map() : Object.create(null); + } + + /** + * Static method for creating ArraySet instances from an existing array. + */ + ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) { + var set = new ArraySet(); + for (var i = 0, len = aArray.length; i < len; i++) { + set.add(aArray[i], aAllowDuplicates); + } + return set; + }; + + /** + * Return how many unique items are in this ArraySet. If duplicates have been + * added, than those do not count towards the size. + * + * @returns Number + */ + ArraySet.prototype.size = function ArraySet_size() { + return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length; + }; + + /** + * Add the given string to this set. + * + * @param String aStr + */ + ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) { + var sStr = hasNativeMap ? aStr : util.toSetString(aStr); + var isDuplicate = hasNativeMap ? this.has(aStr) : has.call(this._set, sStr); + var idx = this._array.length; + if (!isDuplicate || aAllowDuplicates) { + this._array.push(aStr); + } + if (!isDuplicate) { + if (hasNativeMap) { + this._set.set(aStr, idx); + } else { + this._set[sStr] = idx; + } + } + }; + + /** + * Is the given string a member of this set? + * + * @param String aStr + */ + ArraySet.prototype.has = function ArraySet_has(aStr) { + if (hasNativeMap) { + return this._set.has(aStr); + } else { + var sStr = util.toSetString(aStr); + return has.call(this._set, sStr); + } + }; + + /** + * What is the index of the given string in the array? + * + * @param String aStr + */ + ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) { + if (hasNativeMap) { + var idx = this._set.get(aStr); + if (idx >= 0) { + return idx; + } + } else { + var sStr = util.toSetString(aStr); + if (has.call(this._set, sStr)) { + return this._set[sStr]; + } + } + + throw new Error('"' + aStr + '" is not in the set.'); + }; + + /** + * What is the element at the given index? + * + * @param Number aIdx + */ + ArraySet.prototype.at = function ArraySet_at(aIdx) { + if (aIdx >= 0 && aIdx < this._array.length) { + return this._array[aIdx]; + } + throw new Error('No element indexed by ' + aIdx); + }; + + /** + * Returns the array representation of this set (which has the proper indices + * indicated by indexOf). Note that this is a copy of the internal array used + * for storing the members so that no one can mess with internal state. + */ + ArraySet.prototype.toArray = function ArraySet_toArray() { + return this._array.slice(); + }; + + exports.ArraySet = ArraySet; + + +/***/ }), +/* 6 */ +/***/ (function(module, exports, __webpack_require__) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2014 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + var util = __webpack_require__(4); + + /** + * Determine whether mappingB is after mappingA with respect to generated + * position. + */ + function generatedPositionAfter(mappingA, mappingB) { + // Optimized for most common case + var lineA = mappingA.generatedLine; + var lineB = mappingB.generatedLine; + var columnA = mappingA.generatedColumn; + var columnB = mappingB.generatedColumn; + return lineB > lineA || lineB == lineA && columnB >= columnA || + util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0; + } + + /** + * A data structure to provide a sorted view of accumulated mappings in a + * performance conscious manner. It trades a neglibable overhead in general + * case for a large speedup in case of mappings being added in order. + */ + function MappingList() { + this._array = []; + this._sorted = true; + // Serves as infimum + this._last = {generatedLine: -1, generatedColumn: 0}; + } + + /** + * Iterate through internal items. This method takes the same arguments that + * `Array.prototype.forEach` takes. + * + * NOTE: The order of the mappings is NOT guaranteed. + */ + MappingList.prototype.unsortedForEach = + function MappingList_forEach(aCallback, aThisArg) { + this._array.forEach(aCallback, aThisArg); + }; + + /** + * Add the given source mapping. + * + * @param Object aMapping + */ + MappingList.prototype.add = function MappingList_add(aMapping) { + if (generatedPositionAfter(this._last, aMapping)) { + this._last = aMapping; + this._array.push(aMapping); + } else { + this._sorted = false; + this._array.push(aMapping); + } + }; + + /** + * Returns the flat, sorted array of mappings. The mappings are sorted by + * generated position. + * + * WARNING: This method returns internal data without copying, for + * performance. The return value must NOT be mutated, and should be treated as + * an immutable borrow. If you want to take ownership, you must make your own + * copy. + */ + MappingList.prototype.toArray = function MappingList_toArray() { + if (!this._sorted) { + this._array.sort(util.compareByGeneratedPositionsInflated); + this._sorted = true; + } + return this._array; + }; + + exports.MappingList = MappingList; + + +/***/ }), +/* 7 */ +/***/ (function(module, exports, __webpack_require__) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + var util = __webpack_require__(4); + var binarySearch = __webpack_require__(8); + var ArraySet = __webpack_require__(5).ArraySet; + var base64VLQ = __webpack_require__(2); + var quickSort = __webpack_require__(9).quickSort; + + function SourceMapConsumer(aSourceMap, aSourceMapURL) { + var sourceMap = aSourceMap; + if (typeof aSourceMap === 'string') { + sourceMap = util.parseSourceMapInput(aSourceMap); + } + + return sourceMap.sections != null + ? new IndexedSourceMapConsumer(sourceMap, aSourceMapURL) + : new BasicSourceMapConsumer(sourceMap, aSourceMapURL); + } + + SourceMapConsumer.fromSourceMap = function(aSourceMap, aSourceMapURL) { + return BasicSourceMapConsumer.fromSourceMap(aSourceMap, aSourceMapURL); + } + + /** + * The version of the source mapping spec that we are consuming. + */ + SourceMapConsumer.prototype._version = 3; + + // `__generatedMappings` and `__originalMappings` are arrays that hold the + // parsed mapping coordinates from the source map's "mappings" attribute. They + // are lazily instantiated, accessed via the `_generatedMappings` and + // `_originalMappings` getters respectively, and we only parse the mappings + // and create these arrays once queried for a source location. We jump through + // these hoops because there can be many thousands of mappings, and parsing + // them is expensive, so we only want to do it if we must. + // + // Each object in the arrays is of the form: + // + // { + // generatedLine: The line number in the generated code, + // generatedColumn: The column number in the generated code, + // source: The path to the original source file that generated this + // chunk of code, + // originalLine: The line number in the original source that + // corresponds to this chunk of generated code, + // originalColumn: The column number in the original source that + // corresponds to this chunk of generated code, + // name: The name of the original symbol which generated this chunk of + // code. + // } + // + // All properties except for `generatedLine` and `generatedColumn` can be + // `null`. + // + // `_generatedMappings` is ordered by the generated positions. + // + // `_originalMappings` is ordered by the original positions. + + SourceMapConsumer.prototype.__generatedMappings = null; + Object.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', { + configurable: true, + enumerable: true, + get: function () { + if (!this.__generatedMappings) { + this._parseMappings(this._mappings, this.sourceRoot); + } + + return this.__generatedMappings; + } + }); + + SourceMapConsumer.prototype.__originalMappings = null; + Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', { + configurable: true, + enumerable: true, + get: function () { + if (!this.__originalMappings) { + this._parseMappings(this._mappings, this.sourceRoot); + } + + return this.__originalMappings; + } + }); + + SourceMapConsumer.prototype._charIsMappingSeparator = + function SourceMapConsumer_charIsMappingSeparator(aStr, index) { + var c = aStr.charAt(index); + return c === ";" || c === ","; + }; + + /** + * Parse the mappings in a string in to a data structure which we can easily + * query (the ordered arrays in the `this.__generatedMappings` and + * `this.__originalMappings` properties). + */ + SourceMapConsumer.prototype._parseMappings = + function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { + throw new Error("Subclasses must implement _parseMappings"); + }; + + SourceMapConsumer.GENERATED_ORDER = 1; + SourceMapConsumer.ORIGINAL_ORDER = 2; + + SourceMapConsumer.GREATEST_LOWER_BOUND = 1; + SourceMapConsumer.LEAST_UPPER_BOUND = 2; + + /** + * Iterate over each mapping between an original source/line/column and a + * generated line/column in this source map. + * + * @param Function aCallback + * The function that is called with each mapping. + * @param Object aContext + * Optional. If specified, this object will be the value of `this` every + * time that `aCallback` is called. + * @param aOrder + * Either `SourceMapConsumer.GENERATED_ORDER` or + * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to + * iterate over the mappings sorted by the generated file's line/column + * order or the original's source/line/column order, respectively. Defaults to + * `SourceMapConsumer.GENERATED_ORDER`. + */ + SourceMapConsumer.prototype.eachMapping = + function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) { + var context = aContext || null; + var order = aOrder || SourceMapConsumer.GENERATED_ORDER; + + var mappings; + switch (order) { + case SourceMapConsumer.GENERATED_ORDER: + mappings = this._generatedMappings; + break; + case SourceMapConsumer.ORIGINAL_ORDER: + mappings = this._originalMappings; + break; + default: + throw new Error("Unknown order of iteration."); + } + + var sourceRoot = this.sourceRoot; + mappings.map(function (mapping) { + var source = mapping.source === null ? null : this._sources.at(mapping.source); + source = util.computeSourceURL(sourceRoot, source, this._sourceMapURL); + return { + source: source, + generatedLine: mapping.generatedLine, + generatedColumn: mapping.generatedColumn, + originalLine: mapping.originalLine, + originalColumn: mapping.originalColumn, + name: mapping.name === null ? null : this._names.at(mapping.name) + }; + }, this).forEach(aCallback, context); + }; + + /** + * Returns all generated line and column information for the original source, + * line, and column provided. If no column is provided, returns all mappings + * corresponding to a either the line we are searching for or the next + * closest line that has any mappings. Otherwise, returns all mappings + * corresponding to the given line and either the column we are searching for + * or the next closest column that has any offsets. + * + * The only argument is an object with the following properties: + * + * - source: The filename of the original source. + * - line: The line number in the original source. The line number is 1-based. + * - column: Optional. the column number in the original source. + * The column number is 0-based. + * + * and an array of objects is returned, each with the following properties: + * + * - line: The line number in the generated source, or null. The + * line number is 1-based. + * - column: The column number in the generated source, or null. + * The column number is 0-based. + */ + SourceMapConsumer.prototype.allGeneratedPositionsFor = + function SourceMapConsumer_allGeneratedPositionsFor(aArgs) { + var line = util.getArg(aArgs, 'line'); + + // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping + // returns the index of the closest mapping less than the needle. By + // setting needle.originalColumn to 0, we thus find the last mapping for + // the given line, provided such a mapping exists. + var needle = { + source: util.getArg(aArgs, 'source'), + originalLine: line, + originalColumn: util.getArg(aArgs, 'column', 0) + }; + + needle.source = this._findSourceIndex(needle.source); + if (needle.source < 0) { + return []; + } + + var mappings = []; + + var index = this._findMapping(needle, + this._originalMappings, + "originalLine", + "originalColumn", + util.compareByOriginalPositions, + binarySearch.LEAST_UPPER_BOUND); + if (index >= 0) { + var mapping = this._originalMappings[index]; + + if (aArgs.column === undefined) { + var originalLine = mapping.originalLine; + + // Iterate until either we run out of mappings, or we run into + // a mapping for a different line than the one we found. Since + // mappings are sorted, this is guaranteed to find all mappings for + // the line we found. + while (mapping && mapping.originalLine === originalLine) { + mappings.push({ + line: util.getArg(mapping, 'generatedLine', null), + column: util.getArg(mapping, 'generatedColumn', null), + lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) + }); + + mapping = this._originalMappings[++index]; + } + } else { + var originalColumn = mapping.originalColumn; + + // Iterate until either we run out of mappings, or we run into + // a mapping for a different line than the one we were searching for. + // Since mappings are sorted, this is guaranteed to find all mappings for + // the line we are searching for. + while (mapping && + mapping.originalLine === line && + mapping.originalColumn == originalColumn) { + mappings.push({ + line: util.getArg(mapping, 'generatedLine', null), + column: util.getArg(mapping, 'generatedColumn', null), + lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) + }); + + mapping = this._originalMappings[++index]; + } + } + } + + return mappings; + }; + + exports.SourceMapConsumer = SourceMapConsumer; + + /** + * A BasicSourceMapConsumer instance represents a parsed source map which we can + * query for information about the original file positions by giving it a file + * position in the generated source. + * + * The first parameter is the raw source map (either as a JSON string, or + * already parsed to an object). According to the spec, source maps have the + * following attributes: + * + * - version: Which version of the source map spec this map is following. + * - sources: An array of URLs to the original source files. + * - names: An array of identifiers which can be referrenced by individual mappings. + * - sourceRoot: Optional. The URL root from which all sources are relative. + * - sourcesContent: Optional. An array of contents of the original source files. + * - mappings: A string of base64 VLQs which contain the actual mappings. + * - file: Optional. The generated file this source map is associated with. + * + * Here is an example source map, taken from the source map spec[0]: + * + * { + * version : 3, + * file: "out.js", + * sourceRoot : "", + * sources: ["foo.js", "bar.js"], + * names: ["src", "maps", "are", "fun"], + * mappings: "AA,AB;;ABCDE;" + * } + * + * The second parameter, if given, is a string whose value is the URL + * at which the source map was found. This URL is used to compute the + * sources array. + * + * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1# + */ + function BasicSourceMapConsumer(aSourceMap, aSourceMapURL) { + var sourceMap = aSourceMap; + if (typeof aSourceMap === 'string') { + sourceMap = util.parseSourceMapInput(aSourceMap); + } + + var version = util.getArg(sourceMap, 'version'); + var sources = util.getArg(sourceMap, 'sources'); + // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which + // requires the array) to play nice here. + var names = util.getArg(sourceMap, 'names', []); + var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null); + var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null); + var mappings = util.getArg(sourceMap, 'mappings'); + var file = util.getArg(sourceMap, 'file', null); + + // Once again, Sass deviates from the spec and supplies the version as a + // string rather than a number, so we use loose equality checking here. + if (version != this._version) { + throw new Error('Unsupported version: ' + version); + } + + if (sourceRoot) { + sourceRoot = util.normalize(sourceRoot); + } + + sources = sources + .map(String) + // Some source maps produce relative source paths like "./foo.js" instead of + // "foo.js". Normalize these first so that future comparisons will succeed. + // See bugzil.la/1090768. + .map(util.normalize) + // Always ensure that absolute sources are internally stored relative to + // the source root, if the source root is absolute. Not doing this would + // be particularly problematic when the source root is a prefix of the + // source (valid, but why??). See github issue #199 and bugzil.la/1188982. + .map(function (source) { + return sourceRoot && util.isAbsolute(sourceRoot) && util.isAbsolute(source) + ? util.relative(sourceRoot, source) + : source; + }); + + // Pass `true` below to allow duplicate names and sources. While source maps + // are intended to be compressed and deduplicated, the TypeScript compiler + // sometimes generates source maps with duplicates in them. See Github issue + // #72 and bugzil.la/889492. + this._names = ArraySet.fromArray(names.map(String), true); + this._sources = ArraySet.fromArray(sources, true); + + this._absoluteSources = this._sources.toArray().map(function (s) { + return util.computeSourceURL(sourceRoot, s, aSourceMapURL); + }); + + this.sourceRoot = sourceRoot; + this.sourcesContent = sourcesContent; + this._mappings = mappings; + this._sourceMapURL = aSourceMapURL; + this.file = file; + } + + BasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype); + BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer; + + /** + * Utility function to find the index of a source. Returns -1 if not + * found. + */ + BasicSourceMapConsumer.prototype._findSourceIndex = function(aSource) { + var relativeSource = aSource; + if (this.sourceRoot != null) { + relativeSource = util.relative(this.sourceRoot, relativeSource); + } + + if (this._sources.has(relativeSource)) { + return this._sources.indexOf(relativeSource); + } + + // Maybe aSource is an absolute URL as returned by |sources|. In + // this case we can't simply undo the transform. + var i; + for (i = 0; i < this._absoluteSources.length; ++i) { + if (this._absoluteSources[i] == aSource) { + return i; + } + } + + return -1; + }; + + /** + * Create a BasicSourceMapConsumer from a SourceMapGenerator. + * + * @param SourceMapGenerator aSourceMap + * The source map that will be consumed. + * @param String aSourceMapURL + * The URL at which the source map can be found (optional) + * @returns BasicSourceMapConsumer + */ + BasicSourceMapConsumer.fromSourceMap = + function SourceMapConsumer_fromSourceMap(aSourceMap, aSourceMapURL) { + var smc = Object.create(BasicSourceMapConsumer.prototype); + + var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true); + var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true); + smc.sourceRoot = aSourceMap._sourceRoot; + smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(), + smc.sourceRoot); + smc.file = aSourceMap._file; + smc._sourceMapURL = aSourceMapURL; + smc._absoluteSources = smc._sources.toArray().map(function (s) { + return util.computeSourceURL(smc.sourceRoot, s, aSourceMapURL); + }); + + // Because we are modifying the entries (by converting string sources and + // names to indices into the sources and names ArraySets), we have to make + // a copy of the entry or else bad things happen. Shared mutable state + // strikes again! See github issue #191. + + var generatedMappings = aSourceMap._mappings.toArray().slice(); + var destGeneratedMappings = smc.__generatedMappings = []; + var destOriginalMappings = smc.__originalMappings = []; + + for (var i = 0, length = generatedMappings.length; i < length; i++) { + var srcMapping = generatedMappings[i]; + var destMapping = new Mapping; + destMapping.generatedLine = srcMapping.generatedLine; + destMapping.generatedColumn = srcMapping.generatedColumn; + + if (srcMapping.source) { + destMapping.source = sources.indexOf(srcMapping.source); + destMapping.originalLine = srcMapping.originalLine; + destMapping.originalColumn = srcMapping.originalColumn; + + if (srcMapping.name) { + destMapping.name = names.indexOf(srcMapping.name); + } + + destOriginalMappings.push(destMapping); + } + + destGeneratedMappings.push(destMapping); + } + + quickSort(smc.__originalMappings, util.compareByOriginalPositions); + + return smc; + }; + + /** + * The version of the source mapping spec that we are consuming. + */ + BasicSourceMapConsumer.prototype._version = 3; + + /** + * The list of original sources. + */ + Object.defineProperty(BasicSourceMapConsumer.prototype, 'sources', { + get: function () { + return this._absoluteSources.slice(); + } + }); + + /** + * Provide the JIT with a nice shape / hidden class. + */ + function Mapping() { + this.generatedLine = 0; + this.generatedColumn = 0; + this.source = null; + this.originalLine = null; + this.originalColumn = null; + this.name = null; + } + + /** + * Parse the mappings in a string in to a data structure which we can easily + * query (the ordered arrays in the `this.__generatedMappings` and + * `this.__originalMappings` properties). + */ + BasicSourceMapConsumer.prototype._parseMappings = + function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { + var generatedLine = 1; + var previousGeneratedColumn = 0; + var previousOriginalLine = 0; + var previousOriginalColumn = 0; + var previousSource = 0; + var previousName = 0; + var length = aStr.length; + var index = 0; + var cachedSegments = {}; + var temp = {}; + var originalMappings = []; + var generatedMappings = []; + var mapping, str, segment, end, value; + + while (index < length) { + if (aStr.charAt(index) === ';') { + generatedLine++; + index++; + previousGeneratedColumn = 0; + } + else if (aStr.charAt(index) === ',') { + index++; + } + else { + mapping = new Mapping(); + mapping.generatedLine = generatedLine; + + // Because each offset is encoded relative to the previous one, + // many segments often have the same encoding. We can exploit this + // fact by caching the parsed variable length fields of each segment, + // allowing us to avoid a second parse if we encounter the same + // segment again. + for (end = index; end < length; end++) { + if (this._charIsMappingSeparator(aStr, end)) { + break; + } + } + str = aStr.slice(index, end); + + segment = cachedSegments[str]; + if (segment) { + index += str.length; + } else { + segment = []; + while (index < end) { + base64VLQ.decode(aStr, index, temp); + value = temp.value; + index = temp.rest; + segment.push(value); + } + + if (segment.length === 2) { + throw new Error('Found a source, but no line and column'); + } + + if (segment.length === 3) { + throw new Error('Found a source and line, but no column'); + } + + cachedSegments[str] = segment; + } + + // Generated column. + mapping.generatedColumn = previousGeneratedColumn + segment[0]; + previousGeneratedColumn = mapping.generatedColumn; + + if (segment.length > 1) { + // Original source. + mapping.source = previousSource + segment[1]; + previousSource += segment[1]; + + // Original line. + mapping.originalLine = previousOriginalLine + segment[2]; + previousOriginalLine = mapping.originalLine; + // Lines are stored 0-based + mapping.originalLine += 1; + + // Original column. + mapping.originalColumn = previousOriginalColumn + segment[3]; + previousOriginalColumn = mapping.originalColumn; + + if (segment.length > 4) { + // Original name. + mapping.name = previousName + segment[4]; + previousName += segment[4]; + } + } + + generatedMappings.push(mapping); + if (typeof mapping.originalLine === 'number') { + originalMappings.push(mapping); + } + } + } + + quickSort(generatedMappings, util.compareByGeneratedPositionsDeflated); + this.__generatedMappings = generatedMappings; + + quickSort(originalMappings, util.compareByOriginalPositions); + this.__originalMappings = originalMappings; + }; + + /** + * Find the mapping that best matches the hypothetical "needle" mapping that + * we are searching for in the given "haystack" of mappings. + */ + BasicSourceMapConsumer.prototype._findMapping = + function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName, + aColumnName, aComparator, aBias) { + // To return the position we are searching for, we must first find the + // mapping for the given position and then return the opposite position it + // points to. Because the mappings are sorted, we can use binary search to + // find the best mapping. + + if (aNeedle[aLineName] <= 0) { + throw new TypeError('Line must be greater than or equal to 1, got ' + + aNeedle[aLineName]); + } + if (aNeedle[aColumnName] < 0) { + throw new TypeError('Column must be greater than or equal to 0, got ' + + aNeedle[aColumnName]); + } + + return binarySearch.search(aNeedle, aMappings, aComparator, aBias); + }; + + /** + * Compute the last column for each generated mapping. The last column is + * inclusive. + */ + BasicSourceMapConsumer.prototype.computeColumnSpans = + function SourceMapConsumer_computeColumnSpans() { + for (var index = 0; index < this._generatedMappings.length; ++index) { + var mapping = this._generatedMappings[index]; + + // Mappings do not contain a field for the last generated columnt. We + // can come up with an optimistic estimate, however, by assuming that + // mappings are contiguous (i.e. given two consecutive mappings, the + // first mapping ends where the second one starts). + if (index + 1 < this._generatedMappings.length) { + var nextMapping = this._generatedMappings[index + 1]; + + if (mapping.generatedLine === nextMapping.generatedLine) { + mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1; + continue; + } + } + + // The last mapping for each line spans the entire line. + mapping.lastGeneratedColumn = Infinity; + } + }; + + /** + * Returns the original source, line, and column information for the generated + * source's line and column positions provided. The only argument is an object + * with the following properties: + * + * - line: The line number in the generated source. The line number + * is 1-based. + * - column: The column number in the generated source. The column + * number is 0-based. + * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or + * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. + * + * and an object is returned with the following properties: + * + * - source: The original source file, or null. + * - line: The line number in the original source, or null. The + * line number is 1-based. + * - column: The column number in the original source, or null. The + * column number is 0-based. + * - name: The original identifier, or null. + */ + BasicSourceMapConsumer.prototype.originalPositionFor = + function SourceMapConsumer_originalPositionFor(aArgs) { + var needle = { + generatedLine: util.getArg(aArgs, 'line'), + generatedColumn: util.getArg(aArgs, 'column') + }; + + var index = this._findMapping( + needle, + this._generatedMappings, + "generatedLine", + "generatedColumn", + util.compareByGeneratedPositionsDeflated, + util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND) + ); + + if (index >= 0) { + var mapping = this._generatedMappings[index]; + + if (mapping.generatedLine === needle.generatedLine) { + var source = util.getArg(mapping, 'source', null); + if (source !== null) { + source = this._sources.at(source); + source = util.computeSourceURL(this.sourceRoot, source, this._sourceMapURL); + } + var name = util.getArg(mapping, 'name', null); + if (name !== null) { + name = this._names.at(name); + } + return { + source: source, + line: util.getArg(mapping, 'originalLine', null), + column: util.getArg(mapping, 'originalColumn', null), + name: name + }; + } + } + + return { + source: null, + line: null, + column: null, + name: null + }; + }; + + /** + * Return true if we have the source content for every source in the source + * map, false otherwise. + */ + BasicSourceMapConsumer.prototype.hasContentsOfAllSources = + function BasicSourceMapConsumer_hasContentsOfAllSources() { + if (!this.sourcesContent) { + return false; + } + return this.sourcesContent.length >= this._sources.size() && + !this.sourcesContent.some(function (sc) { return sc == null; }); + }; + + /** + * Returns the original source content. The only argument is the url of the + * original source file. Returns null if no original source content is + * available. + */ + BasicSourceMapConsumer.prototype.sourceContentFor = + function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { + if (!this.sourcesContent) { + return null; + } + + var index = this._findSourceIndex(aSource); + if (index >= 0) { + return this.sourcesContent[index]; + } + + var relativeSource = aSource; + if (this.sourceRoot != null) { + relativeSource = util.relative(this.sourceRoot, relativeSource); + } + + var url; + if (this.sourceRoot != null + && (url = util.urlParse(this.sourceRoot))) { + // XXX: file:// URIs and absolute paths lead to unexpected behavior for + // many users. We can help them out when they expect file:// URIs to + // behave like it would if they were running a local HTTP server. See + // https://bugzilla.mozilla.org/show_bug.cgi?id=885597. + var fileUriAbsPath = relativeSource.replace(/^file:\/\//, ""); + if (url.scheme == "file" + && this._sources.has(fileUriAbsPath)) { + return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)] + } + + if ((!url.path || url.path == "/") + && this._sources.has("/" + relativeSource)) { + return this.sourcesContent[this._sources.indexOf("/" + relativeSource)]; + } + } + + // This function is used recursively from + // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we + // don't want to throw if we can't find the source - we just want to + // return null, so we provide a flag to exit gracefully. + if (nullOnMissing) { + return null; + } + else { + throw new Error('"' + relativeSource + '" is not in the SourceMap.'); + } + }; + + /** + * Returns the generated line and column information for the original source, + * line, and column positions provided. The only argument is an object with + * the following properties: + * + * - source: The filename of the original source. + * - line: The line number in the original source. The line number + * is 1-based. + * - column: The column number in the original source. The column + * number is 0-based. + * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or + * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. + * + * and an object is returned with the following properties: + * + * - line: The line number in the generated source, or null. The + * line number is 1-based. + * - column: The column number in the generated source, or null. + * The column number is 0-based. + */ + BasicSourceMapConsumer.prototype.generatedPositionFor = + function SourceMapConsumer_generatedPositionFor(aArgs) { + var source = util.getArg(aArgs, 'source'); + source = this._findSourceIndex(source); + if (source < 0) { + return { + line: null, + column: null, + lastColumn: null + }; + } + + var needle = { + source: source, + originalLine: util.getArg(aArgs, 'line'), + originalColumn: util.getArg(aArgs, 'column') + }; + + var index = this._findMapping( + needle, + this._originalMappings, + "originalLine", + "originalColumn", + util.compareByOriginalPositions, + util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND) + ); + + if (index >= 0) { + var mapping = this._originalMappings[index]; + + if (mapping.source === needle.source) { + return { + line: util.getArg(mapping, 'generatedLine', null), + column: util.getArg(mapping, 'generatedColumn', null), + lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) + }; + } + } + + return { + line: null, + column: null, + lastColumn: null + }; + }; + + exports.BasicSourceMapConsumer = BasicSourceMapConsumer; + + /** + * An IndexedSourceMapConsumer instance represents a parsed source map which + * we can query for information. It differs from BasicSourceMapConsumer in + * that it takes "indexed" source maps (i.e. ones with a "sections" field) as + * input. + * + * The first parameter is a raw source map (either as a JSON string, or already + * parsed to an object). According to the spec for indexed source maps, they + * have the following attributes: + * + * - version: Which version of the source map spec this map is following. + * - file: Optional. The generated file this source map is associated with. + * - sections: A list of section definitions. + * + * Each value under the "sections" field has two fields: + * - offset: The offset into the original specified at which this section + * begins to apply, defined as an object with a "line" and "column" + * field. + * - map: A source map definition. This source map could also be indexed, + * but doesn't have to be. + * + * Instead of the "map" field, it's also possible to have a "url" field + * specifying a URL to retrieve a source map from, but that's currently + * unsupported. + * + * Here's an example source map, taken from the source map spec[0], but + * modified to omit a section which uses the "url" field. + * + * { + * version : 3, + * file: "app.js", + * sections: [{ + * offset: {line:100, column:10}, + * map: { + * version : 3, + * file: "section.js", + * sources: ["foo.js", "bar.js"], + * names: ["src", "maps", "are", "fun"], + * mappings: "AAAA,E;;ABCDE;" + * } + * }], + * } + * + * The second parameter, if given, is a string whose value is the URL + * at which the source map was found. This URL is used to compute the + * sources array. + * + * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt + */ + function IndexedSourceMapConsumer(aSourceMap, aSourceMapURL) { + var sourceMap = aSourceMap; + if (typeof aSourceMap === 'string') { + sourceMap = util.parseSourceMapInput(aSourceMap); + } + + var version = util.getArg(sourceMap, 'version'); + var sections = util.getArg(sourceMap, 'sections'); + + if (version != this._version) { + throw new Error('Unsupported version: ' + version); + } + + this._sources = new ArraySet(); + this._names = new ArraySet(); + + var lastOffset = { + line: -1, + column: 0 + }; + this._sections = sections.map(function (s) { + if (s.url) { + // The url field will require support for asynchronicity. + // See https://github.com/mozilla/source-map/issues/16 + throw new Error('Support for url field in sections not implemented.'); + } + var offset = util.getArg(s, 'offset'); + var offsetLine = util.getArg(offset, 'line'); + var offsetColumn = util.getArg(offset, 'column'); + + if (offsetLine < lastOffset.line || + (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) { + throw new Error('Section offsets must be ordered and non-overlapping.'); + } + lastOffset = offset; + + return { + generatedOffset: { + // The offset fields are 0-based, but we use 1-based indices when + // encoding/decoding from VLQ. + generatedLine: offsetLine + 1, + generatedColumn: offsetColumn + 1 + }, + consumer: new SourceMapConsumer(util.getArg(s, 'map'), aSourceMapURL) + } + }); + } + + IndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype); + IndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer; + + /** + * The version of the source mapping spec that we are consuming. + */ + IndexedSourceMapConsumer.prototype._version = 3; + + /** + * The list of original sources. + */ + Object.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', { + get: function () { + var sources = []; + for (var i = 0; i < this._sections.length; i++) { + for (var j = 0; j < this._sections[i].consumer.sources.length; j++) { + sources.push(this._sections[i].consumer.sources[j]); + } + } + return sources; + } + }); + + /** + * Returns the original source, line, and column information for the generated + * source's line and column positions provided. The only argument is an object + * with the following properties: + * + * - line: The line number in the generated source. The line number + * is 1-based. + * - column: The column number in the generated source. The column + * number is 0-based. + * + * and an object is returned with the following properties: + * + * - source: The original source file, or null. + * - line: The line number in the original source, or null. The + * line number is 1-based. + * - column: The column number in the original source, or null. The + * column number is 0-based. + * - name: The original identifier, or null. + */ + IndexedSourceMapConsumer.prototype.originalPositionFor = + function IndexedSourceMapConsumer_originalPositionFor(aArgs) { + var needle = { + generatedLine: util.getArg(aArgs, 'line'), + generatedColumn: util.getArg(aArgs, 'column') + }; + + // Find the section containing the generated position we're trying to map + // to an original position. + var sectionIndex = binarySearch.search(needle, this._sections, + function(needle, section) { + var cmp = needle.generatedLine - section.generatedOffset.generatedLine; + if (cmp) { + return cmp; + } + + return (needle.generatedColumn - + section.generatedOffset.generatedColumn); + }); + var section = this._sections[sectionIndex]; + + if (!section) { + return { + source: null, + line: null, + column: null, + name: null + }; + } + + return section.consumer.originalPositionFor({ + line: needle.generatedLine - + (section.generatedOffset.generatedLine - 1), + column: needle.generatedColumn - + (section.generatedOffset.generatedLine === needle.generatedLine + ? section.generatedOffset.generatedColumn - 1 + : 0), + bias: aArgs.bias + }); + }; + + /** + * Return true if we have the source content for every source in the source + * map, false otherwise. + */ + IndexedSourceMapConsumer.prototype.hasContentsOfAllSources = + function IndexedSourceMapConsumer_hasContentsOfAllSources() { + return this._sections.every(function (s) { + return s.consumer.hasContentsOfAllSources(); + }); + }; + + /** + * Returns the original source content. The only argument is the url of the + * original source file. Returns null if no original source content is + * available. + */ + IndexedSourceMapConsumer.prototype.sourceContentFor = + function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { + for (var i = 0; i < this._sections.length; i++) { + var section = this._sections[i]; + + var content = section.consumer.sourceContentFor(aSource, true); + if (content) { + return content; + } + } + if (nullOnMissing) { + return null; + } + else { + throw new Error('"' + aSource + '" is not in the SourceMap.'); + } + }; + + /** + * Returns the generated line and column information for the original source, + * line, and column positions provided. The only argument is an object with + * the following properties: + * + * - source: The filename of the original source. + * - line: The line number in the original source. The line number + * is 1-based. + * - column: The column number in the original source. The column + * number is 0-based. + * + * and an object is returned with the following properties: + * + * - line: The line number in the generated source, or null. The + * line number is 1-based. + * - column: The column number in the generated source, or null. + * The column number is 0-based. + */ + IndexedSourceMapConsumer.prototype.generatedPositionFor = + function IndexedSourceMapConsumer_generatedPositionFor(aArgs) { + for (var i = 0; i < this._sections.length; i++) { + var section = this._sections[i]; + + // Only consider this section if the requested source is in the list of + // sources of the consumer. + if (section.consumer._findSourceIndex(util.getArg(aArgs, 'source')) === -1) { + continue; + } + var generatedPosition = section.consumer.generatedPositionFor(aArgs); + if (generatedPosition) { + var ret = { + line: generatedPosition.line + + (section.generatedOffset.generatedLine - 1), + column: generatedPosition.column + + (section.generatedOffset.generatedLine === generatedPosition.line + ? section.generatedOffset.generatedColumn - 1 + : 0) + }; + return ret; + } + } + + return { + line: null, + column: null + }; + }; + + /** + * Parse the mappings in a string in to a data structure which we can easily + * query (the ordered arrays in the `this.__generatedMappings` and + * `this.__originalMappings` properties). + */ + IndexedSourceMapConsumer.prototype._parseMappings = + function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) { + this.__generatedMappings = []; + this.__originalMappings = []; + for (var i = 0; i < this._sections.length; i++) { + var section = this._sections[i]; + var sectionMappings = section.consumer._generatedMappings; + for (var j = 0; j < sectionMappings.length; j++) { + var mapping = sectionMappings[j]; + + var source = section.consumer._sources.at(mapping.source); + source = util.computeSourceURL(section.consumer.sourceRoot, source, this._sourceMapURL); + this._sources.add(source); + source = this._sources.indexOf(source); + + var name = null; + if (mapping.name) { + name = section.consumer._names.at(mapping.name); + this._names.add(name); + name = this._names.indexOf(name); + } + + // The mappings coming from the consumer for the section have + // generated positions relative to the start of the section, so we + // need to offset them to be relative to the start of the concatenated + // generated file. + var adjustedMapping = { + source: source, + generatedLine: mapping.generatedLine + + (section.generatedOffset.generatedLine - 1), + generatedColumn: mapping.generatedColumn + + (section.generatedOffset.generatedLine === mapping.generatedLine + ? section.generatedOffset.generatedColumn - 1 + : 0), + originalLine: mapping.originalLine, + originalColumn: mapping.originalColumn, + name: name + }; + + this.__generatedMappings.push(adjustedMapping); + if (typeof adjustedMapping.originalLine === 'number') { + this.__originalMappings.push(adjustedMapping); + } + } + } + + quickSort(this.__generatedMappings, util.compareByGeneratedPositionsDeflated); + quickSort(this.__originalMappings, util.compareByOriginalPositions); + }; + + exports.IndexedSourceMapConsumer = IndexedSourceMapConsumer; + + +/***/ }), +/* 8 */ +/***/ (function(module, exports) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + exports.GREATEST_LOWER_BOUND = 1; + exports.LEAST_UPPER_BOUND = 2; + + /** + * Recursive implementation of binary search. + * + * @param aLow Indices here and lower do not contain the needle. + * @param aHigh Indices here and higher do not contain the needle. + * @param aNeedle The element being searched for. + * @param aHaystack The non-empty array being searched. + * @param aCompare Function which takes two elements and returns -1, 0, or 1. + * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or + * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + */ + function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) { + // This function terminates when one of the following is true: + // + // 1. We find the exact element we are looking for. + // + // 2. We did not find the exact element, but we can return the index of + // the next-closest element. + // + // 3. We did not find the exact element, and there is no next-closest + // element than the one we are searching for, so we return -1. + var mid = Math.floor((aHigh - aLow) / 2) + aLow; + var cmp = aCompare(aNeedle, aHaystack[mid], true); + if (cmp === 0) { + // Found the element we are looking for. + return mid; + } + else if (cmp > 0) { + // Our needle is greater than aHaystack[mid]. + if (aHigh - mid > 1) { + // The element is in the upper half. + return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias); + } + + // The exact needle element was not found in this haystack. Determine if + // we are in termination case (3) or (2) and return the appropriate thing. + if (aBias == exports.LEAST_UPPER_BOUND) { + return aHigh < aHaystack.length ? aHigh : -1; + } else { + return mid; + } + } + else { + // Our needle is less than aHaystack[mid]. + if (mid - aLow > 1) { + // The element is in the lower half. + return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias); + } + + // we are in termination case (3) or (2) and return the appropriate thing. + if (aBias == exports.LEAST_UPPER_BOUND) { + return mid; + } else { + return aLow < 0 ? -1 : aLow; + } + } + } + + /** + * This is an implementation of binary search which will always try and return + * the index of the closest element if there is no exact hit. This is because + * mappings between original and generated line/col pairs are single points, + * and there is an implicit region between each of them, so a miss just means + * that you aren't on the very start of a region. + * + * @param aNeedle The element you are looking for. + * @param aHaystack The array that is being searched. + * @param aCompare A function which takes the needle and an element in the + * array and returns -1, 0, or 1 depending on whether the needle is less + * than, equal to, or greater than the element, respectively. + * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or + * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'. + */ + exports.search = function search(aNeedle, aHaystack, aCompare, aBias) { + if (aHaystack.length === 0) { + return -1; + } + + var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack, + aCompare, aBias || exports.GREATEST_LOWER_BOUND); + if (index < 0) { + return -1; + } + + // We have found either the exact element, or the next-closest element than + // the one we are searching for. However, there may be more than one such + // element. Make sure we always return the smallest of these. + while (index - 1 >= 0) { + if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) { + break; + } + --index; + } + + return index; + }; + + +/***/ }), +/* 9 */ +/***/ (function(module, exports) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + // It turns out that some (most?) JavaScript engines don't self-host + // `Array.prototype.sort`. This makes sense because C++ will likely remain + // faster than JS when doing raw CPU-intensive sorting. However, when using a + // custom comparator function, calling back and forth between the VM's C++ and + // JIT'd JS is rather slow *and* loses JIT type information, resulting in + // worse generated code for the comparator function than would be optimal. In + // fact, when sorting with a comparator, these costs outweigh the benefits of + // sorting in C++. By using our own JS-implemented Quick Sort (below), we get + // a ~3500ms mean speed-up in `bench/bench.html`. + + /** + * Swap the elements indexed by `x` and `y` in the array `ary`. + * + * @param {Array} ary + * The array. + * @param {Number} x + * The index of the first item. + * @param {Number} y + * The index of the second item. + */ + function swap(ary, x, y) { + var temp = ary[x]; + ary[x] = ary[y]; + ary[y] = temp; + } + + /** + * Returns a random integer within the range `low .. high` inclusive. + * + * @param {Number} low + * The lower bound on the range. + * @param {Number} high + * The upper bound on the range. + */ + function randomIntInRange(low, high) { + return Math.round(low + (Math.random() * (high - low))); + } + + /** + * The Quick Sort algorithm. + * + * @param {Array} ary + * An array to sort. + * @param {function} comparator + * Function to use to compare two items. + * @param {Number} p + * Start index of the array + * @param {Number} r + * End index of the array + */ + function doQuickSort(ary, comparator, p, r) { + // If our lower bound is less than our upper bound, we (1) partition the + // array into two pieces and (2) recurse on each half. If it is not, this is + // the empty array and our base case. + + if (p < r) { + // (1) Partitioning. + // + // The partitioning chooses a pivot between `p` and `r` and moves all + // elements that are less than or equal to the pivot to the before it, and + // all the elements that are greater than it after it. The effect is that + // once partition is done, the pivot is in the exact place it will be when + // the array is put in sorted order, and it will not need to be moved + // again. This runs in O(n) time. + + // Always choose a random pivot so that an input array which is reverse + // sorted does not cause O(n^2) running time. + var pivotIndex = randomIntInRange(p, r); + var i = p - 1; + + swap(ary, pivotIndex, r); + var pivot = ary[r]; + + // Immediately after `j` is incremented in this loop, the following hold + // true: + // + // * Every element in `ary[p .. i]` is less than or equal to the pivot. + // + // * Every element in `ary[i+1 .. j-1]` is greater than the pivot. + for (var j = p; j < r; j++) { + if (comparator(ary[j], pivot) <= 0) { + i += 1; + swap(ary, i, j); + } + } + + swap(ary, i + 1, j); + var q = i + 1; + + // (2) Recurse on each half. + + doQuickSort(ary, comparator, p, q - 1); + doQuickSort(ary, comparator, q + 1, r); + } + } + + /** + * Sort the given array in-place with the given comparator function. + * + * @param {Array} ary + * An array to sort. + * @param {function} comparator + * Function to use to compare two items. + */ + exports.quickSort = function (ary, comparator) { + doQuickSort(ary, comparator, 0, ary.length - 1); + }; + + +/***/ }), +/* 10 */ +/***/ (function(module, exports, __webpack_require__) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + var SourceMapGenerator = __webpack_require__(1).SourceMapGenerator; + var util = __webpack_require__(4); + + // Matches a Windows-style `\r\n` newline or a `\n` newline used by all other + // operating systems these days (capturing the result). + var REGEX_NEWLINE = /(\r?\n)/; + + // Newline character code for charCodeAt() comparisons + var NEWLINE_CODE = 10; + + // Private symbol for identifying `SourceNode`s when multiple versions of + // the source-map library are loaded. This MUST NOT CHANGE across + // versions! + var isSourceNode = "$$$isSourceNode$$$"; + + /** + * SourceNodes provide a way to abstract over interpolating/concatenating + * snippets of generated JavaScript source code while maintaining the line and + * column information associated with the original source code. + * + * @param aLine The original line number. + * @param aColumn The original column number. + * @param aSource The original source's filename. + * @param aChunks Optional. An array of strings which are snippets of + * generated JS, or other SourceNodes. + * @param aName The original identifier. + */ + function SourceNode(aLine, aColumn, aSource, aChunks, aName) { + this.children = []; + this.sourceContents = {}; + this.line = aLine == null ? null : aLine; + this.column = aColumn == null ? null : aColumn; + this.source = aSource == null ? null : aSource; + this.name = aName == null ? null : aName; + this[isSourceNode] = true; + if (aChunks != null) this.add(aChunks); + } + + /** + * Creates a SourceNode from generated code and a SourceMapConsumer. + * + * @param aGeneratedCode The generated code + * @param aSourceMapConsumer The SourceMap for the generated code + * @param aRelativePath Optional. The path that relative sources in the + * SourceMapConsumer should be relative to. + */ + SourceNode.fromStringWithSourceMap = + function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) { + // The SourceNode we want to fill with the generated code + // and the SourceMap + var node = new SourceNode(); + + // All even indices of this array are one line of the generated code, + // while all odd indices are the newlines between two adjacent lines + // (since `REGEX_NEWLINE` captures its match). + // Processed fragments are accessed by calling `shiftNextLine`. + var remainingLines = aGeneratedCode.split(REGEX_NEWLINE); + var remainingLinesIndex = 0; + var shiftNextLine = function() { + var lineContents = getNextLine(); + // The last line of a file might not have a newline. + var newLine = getNextLine() || ""; + return lineContents + newLine; + + function getNextLine() { + return remainingLinesIndex < remainingLines.length ? + remainingLines[remainingLinesIndex++] : undefined; + } + }; + + // We need to remember the position of "remainingLines" + var lastGeneratedLine = 1, lastGeneratedColumn = 0; + + // The generate SourceNodes we need a code range. + // To extract it current and last mapping is used. + // Here we store the last mapping. + var lastMapping = null; + + aSourceMapConsumer.eachMapping(function (mapping) { + if (lastMapping !== null) { + // We add the code from "lastMapping" to "mapping": + // First check if there is a new line in between. + if (lastGeneratedLine < mapping.generatedLine) { + // Associate first line with "lastMapping" + addMappingWithCode(lastMapping, shiftNextLine()); + lastGeneratedLine++; + lastGeneratedColumn = 0; + // The remaining code is added without mapping + } else { + // There is no new line in between. + // Associate the code between "lastGeneratedColumn" and + // "mapping.generatedColumn" with "lastMapping" + var nextLine = remainingLines[remainingLinesIndex] || ''; + var code = nextLine.substr(0, mapping.generatedColumn - + lastGeneratedColumn); + remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn - + lastGeneratedColumn); + lastGeneratedColumn = mapping.generatedColumn; + addMappingWithCode(lastMapping, code); + // No more remaining code, continue + lastMapping = mapping; + return; + } + } + // We add the generated code until the first mapping + // to the SourceNode without any mapping. + // Each line is added as separate string. + while (lastGeneratedLine < mapping.generatedLine) { + node.add(shiftNextLine()); + lastGeneratedLine++; + } + if (lastGeneratedColumn < mapping.generatedColumn) { + var nextLine = remainingLines[remainingLinesIndex] || ''; + node.add(nextLine.substr(0, mapping.generatedColumn)); + remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn); + lastGeneratedColumn = mapping.generatedColumn; + } + lastMapping = mapping; + }, this); + // We have processed all mappings. + if (remainingLinesIndex < remainingLines.length) { + if (lastMapping) { + // Associate the remaining code in the current line with "lastMapping" + addMappingWithCode(lastMapping, shiftNextLine()); + } + // and add the remaining lines without any mapping + node.add(remainingLines.splice(remainingLinesIndex).join("")); + } + + // Copy sourcesContent into SourceNode + aSourceMapConsumer.sources.forEach(function (sourceFile) { + var content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content != null) { + if (aRelativePath != null) { + sourceFile = util.join(aRelativePath, sourceFile); + } + node.setSourceContent(sourceFile, content); + } + }); + + return node; + + function addMappingWithCode(mapping, code) { + if (mapping === null || mapping.source === undefined) { + node.add(code); + } else { + var source = aRelativePath + ? util.join(aRelativePath, mapping.source) + : mapping.source; + node.add(new SourceNode(mapping.originalLine, + mapping.originalColumn, + source, + code, + mapping.name)); + } + } + }; + + /** + * Add a chunk of generated JS to this source node. + * + * @param aChunk A string snippet of generated JS code, another instance of + * SourceNode, or an array where each member is one of those things. + */ + SourceNode.prototype.add = function SourceNode_add(aChunk) { + if (Array.isArray(aChunk)) { + aChunk.forEach(function (chunk) { + this.add(chunk); + }, this); + } + else if (aChunk[isSourceNode] || typeof aChunk === "string") { + if (aChunk) { + this.children.push(aChunk); + } + } + else { + throw new TypeError( + "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk + ); + } + return this; + }; + + /** + * Add a chunk of generated JS to the beginning of this source node. + * + * @param aChunk A string snippet of generated JS code, another instance of + * SourceNode, or an array where each member is one of those things. + */ + SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) { + if (Array.isArray(aChunk)) { + for (var i = aChunk.length-1; i >= 0; i--) { + this.prepend(aChunk[i]); + } + } + else if (aChunk[isSourceNode] || typeof aChunk === "string") { + this.children.unshift(aChunk); + } + else { + throw new TypeError( + "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk + ); + } + return this; + }; + + /** + * Walk over the tree of JS snippets in this node and its children. The + * walking function is called once for each snippet of JS and is passed that + * snippet and the its original associated source's line/column location. + * + * @param aFn The traversal function. + */ + SourceNode.prototype.walk = function SourceNode_walk(aFn) { + var chunk; + for (var i = 0, len = this.children.length; i < len; i++) { + chunk = this.children[i]; + if (chunk[isSourceNode]) { + chunk.walk(aFn); + } + else { + if (chunk !== '') { + aFn(chunk, { source: this.source, + line: this.line, + column: this.column, + name: this.name }); + } + } + } + }; + + /** + * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between + * each of `this.children`. + * + * @param aSep The separator. + */ + SourceNode.prototype.join = function SourceNode_join(aSep) { + var newChildren; + var i; + var len = this.children.length; + if (len > 0) { + newChildren = []; + for (i = 0; i < len-1; i++) { + newChildren.push(this.children[i]); + newChildren.push(aSep); + } + newChildren.push(this.children[i]); + this.children = newChildren; + } + return this; + }; + + /** + * Call String.prototype.replace on the very right-most source snippet. Useful + * for trimming whitespace from the end of a source node, etc. + * + * @param aPattern The pattern to replace. + * @param aReplacement The thing to replace the pattern with. + */ + SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) { + var lastChild = this.children[this.children.length - 1]; + if (lastChild[isSourceNode]) { + lastChild.replaceRight(aPattern, aReplacement); + } + else if (typeof lastChild === 'string') { + this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement); + } + else { + this.children.push(''.replace(aPattern, aReplacement)); + } + return this; + }; + + /** + * Set the source content for a source file. This will be added to the SourceMapGenerator + * in the sourcesContent field. + * + * @param aSourceFile The filename of the source file + * @param aSourceContent The content of the source file + */ + SourceNode.prototype.setSourceContent = + function SourceNode_setSourceContent(aSourceFile, aSourceContent) { + this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent; + }; + + /** + * Walk over the tree of SourceNodes. The walking function is called for each + * source file content and is passed the filename and source content. + * + * @param aFn The traversal function. + */ + SourceNode.prototype.walkSourceContents = + function SourceNode_walkSourceContents(aFn) { + for (var i = 0, len = this.children.length; i < len; i++) { + if (this.children[i][isSourceNode]) { + this.children[i].walkSourceContents(aFn); + } + } + + var sources = Object.keys(this.sourceContents); + for (var i = 0, len = sources.length; i < len; i++) { + aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]); + } + }; + + /** + * Return the string representation of this source node. Walks over the tree + * and concatenates all the various snippets together to one string. + */ + SourceNode.prototype.toString = function SourceNode_toString() { + var str = ""; + this.walk(function (chunk) { + str += chunk; + }); + return str; + }; + + /** + * Returns the string representation of this source node along with a source + * map. + */ + SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) { + var generated = { + code: "", + line: 1, + column: 0 + }; + var map = new SourceMapGenerator(aArgs); + var sourceMappingActive = false; + var lastOriginalSource = null; + var lastOriginalLine = null; + var lastOriginalColumn = null; + var lastOriginalName = null; + this.walk(function (chunk, original) { + generated.code += chunk; + if (original.source !== null + && original.line !== null + && original.column !== null) { + if(lastOriginalSource !== original.source + || lastOriginalLine !== original.line + || lastOriginalColumn !== original.column + || lastOriginalName !== original.name) { + map.addMapping({ + source: original.source, + original: { + line: original.line, + column: original.column + }, + generated: { + line: generated.line, + column: generated.column + }, + name: original.name + }); + } + lastOriginalSource = original.source; + lastOriginalLine = original.line; + lastOriginalColumn = original.column; + lastOriginalName = original.name; + sourceMappingActive = true; + } else if (sourceMappingActive) { + map.addMapping({ + generated: { + line: generated.line, + column: generated.column + } + }); + lastOriginalSource = null; + sourceMappingActive = false; + } + for (var idx = 0, length = chunk.length; idx < length; idx++) { + if (chunk.charCodeAt(idx) === NEWLINE_CODE) { + generated.line++; + generated.column = 0; + // Mappings end at eol + if (idx + 1 === length) { + lastOriginalSource = null; + sourceMappingActive = false; + } else if (sourceMappingActive) { + map.addMapping({ + source: original.source, + original: { + line: original.line, + column: original.column + }, + generated: { + line: generated.line, + column: generated.column + }, + name: original.name + }); + } + } else { + generated.column++; + } + } + }); + this.walkSourceContents(function (sourceFile, sourceContent) { + map.setSourceContent(sourceFile, sourceContent); + }); + + return { code: generated.code, map: map }; + }; + + exports.SourceNode = SourceNode; + + +/***/ }) +/******/ ]) +}); +; \ No newline at end of file diff --git a/node_modules/source-map/dist/source-map.min.js b/node_modules/source-map/dist/source-map.min.js new file mode 100644 index 0000000..c7c72da --- /dev/null +++ b/node_modules/source-map/dist/source-map.min.js @@ -0,0 +1,2 @@ +!function(e,n){"object"==typeof exports&&"object"==typeof module?module.exports=n():"function"==typeof define&&define.amd?define([],n):"object"==typeof exports?exports.sourceMap=n():e.sourceMap=n()}(this,function(){return function(e){function n(t){if(r[t])return r[t].exports;var o=r[t]={exports:{},id:t,loaded:!1};return e[t].call(o.exports,o,o.exports,n),o.loaded=!0,o.exports}var r={};return n.m=e,n.c=r,n.p="",n(0)}([function(e,n,r){n.SourceMapGenerator=r(1).SourceMapGenerator,n.SourceMapConsumer=r(7).SourceMapConsumer,n.SourceNode=r(10).SourceNode},function(e,n,r){function t(e){e||(e={}),this._file=i.getArg(e,"file",null),this._sourceRoot=i.getArg(e,"sourceRoot",null),this._skipValidation=i.getArg(e,"skipValidation",!1),this._sources=new s,this._names=new s,this._mappings=new a,this._sourcesContents=null}var o=r(2),i=r(4),s=r(5).ArraySet,a=r(6).MappingList;t.prototype._version=3,t.fromSourceMap=function(e){var n=e.sourceRoot,r=new t({file:e.file,sourceRoot:n});return e.eachMapping(function(e){var t={generated:{line:e.generatedLine,column:e.generatedColumn}};null!=e.source&&(t.source=e.source,null!=n&&(t.source=i.relative(n,t.source)),t.original={line:e.originalLine,column:e.originalColumn},null!=e.name&&(t.name=e.name)),r.addMapping(t)}),e.sources.forEach(function(t){var o=t;null!==n&&(o=i.relative(n,t)),r._sources.has(o)||r._sources.add(o);var s=e.sourceContentFor(t);null!=s&&r.setSourceContent(t,s)}),r},t.prototype.addMapping=function(e){var n=i.getArg(e,"generated"),r=i.getArg(e,"original",null),t=i.getArg(e,"source",null),o=i.getArg(e,"name",null);this._skipValidation||this._validateMapping(n,r,t,o),null!=t&&(t=String(t),this._sources.has(t)||this._sources.add(t)),null!=o&&(o=String(o),this._names.has(o)||this._names.add(o)),this._mappings.add({generatedLine:n.line,generatedColumn:n.column,originalLine:null!=r&&r.line,originalColumn:null!=r&&r.column,source:t,name:o})},t.prototype.setSourceContent=function(e,n){var r=e;null!=this._sourceRoot&&(r=i.relative(this._sourceRoot,r)),null!=n?(this._sourcesContents||(this._sourcesContents=Object.create(null)),this._sourcesContents[i.toSetString(r)]=n):this._sourcesContents&&(delete this._sourcesContents[i.toSetString(r)],0===Object.keys(this._sourcesContents).length&&(this._sourcesContents=null))},t.prototype.applySourceMap=function(e,n,r){var t=n;if(null==n){if(null==e.file)throw new Error('SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, or the source map\'s "file" property. Both were omitted.');t=e.file}var o=this._sourceRoot;null!=o&&(t=i.relative(o,t));var a=new s,u=new s;this._mappings.unsortedForEach(function(n){if(n.source===t&&null!=n.originalLine){var s=e.originalPositionFor({line:n.originalLine,column:n.originalColumn});null!=s.source&&(n.source=s.source,null!=r&&(n.source=i.join(r,n.source)),null!=o&&(n.source=i.relative(o,n.source)),n.originalLine=s.line,n.originalColumn=s.column,null!=s.name&&(n.name=s.name))}var l=n.source;null==l||a.has(l)||a.add(l);var c=n.name;null==c||u.has(c)||u.add(c)},this),this._sources=a,this._names=u,e.sources.forEach(function(n){var t=e.sourceContentFor(n);null!=t&&(null!=r&&(n=i.join(r,n)),null!=o&&(n=i.relative(o,n)),this.setSourceContent(n,t))},this)},t.prototype._validateMapping=function(e,n,r,t){if(n&&"number"!=typeof n.line&&"number"!=typeof n.column)throw new Error("original.line and original.column are not numbers -- you probably meant to omit the original mapping entirely and only map the generated position. If so, pass null for the original mapping instead of an object with empty or null values.");if((!(e&&"line"in e&&"column"in e&&e.line>0&&e.column>=0)||n||r||t)&&!(e&&"line"in e&&"column"in e&&n&&"line"in n&&"column"in n&&e.line>0&&e.column>=0&&n.line>0&&n.column>=0&&r))throw new Error("Invalid mapping: "+JSON.stringify({generated:e,source:r,original:n,name:t}))},t.prototype._serializeMappings=function(){for(var e,n,r,t,s=0,a=1,u=0,l=0,c=0,g=0,p="",h=this._mappings.toArray(),f=0,d=h.length;f0){if(!i.compareByGeneratedPositionsInflated(n,h[f-1]))continue;e+=","}e+=o.encode(n.generatedColumn-s),s=n.generatedColumn,null!=n.source&&(t=this._sources.indexOf(n.source),e+=o.encode(t-g),g=t,e+=o.encode(n.originalLine-1-l),l=n.originalLine-1,e+=o.encode(n.originalColumn-u),u=n.originalColumn,null!=n.name&&(r=this._names.indexOf(n.name),e+=o.encode(r-c),c=r)),p+=e}return p},t.prototype._generateSourcesContent=function(e,n){return e.map(function(e){if(!this._sourcesContents)return null;null!=n&&(e=i.relative(n,e));var r=i.toSetString(e);return Object.prototype.hasOwnProperty.call(this._sourcesContents,r)?this._sourcesContents[r]:null},this)},t.prototype.toJSON=function(){var e={version:this._version,sources:this._sources.toArray(),names:this._names.toArray(),mappings:this._serializeMappings()};return null!=this._file&&(e.file=this._file),null!=this._sourceRoot&&(e.sourceRoot=this._sourceRoot),this._sourcesContents&&(e.sourcesContent=this._generateSourcesContent(e.sources,e.sourceRoot)),e},t.prototype.toString=function(){return JSON.stringify(this.toJSON())},n.SourceMapGenerator=t},function(e,n,r){function t(e){return e<0?(-e<<1)+1:(e<<1)+0}function o(e){var n=1===(1&e),r=e>>1;return n?-r:r}var i=r(3),s=5,a=1<>>=s,o>0&&(n|=l),r+=i.encode(n);while(o>0);return r},n.decode=function(e,n,r){var t,a,c=e.length,g=0,p=0;do{if(n>=c)throw new Error("Expected more digits in base 64 VLQ value.");if(a=i.decode(e.charCodeAt(n++)),a===-1)throw new Error("Invalid base64 digit: "+e.charAt(n-1));t=!!(a&l),a&=u,g+=a<=0;c--)s=u[c],"."===s?u.splice(c,1):".."===s?l++:l>0&&(""===s?(u.splice(c+1,l),l=0):(u.splice(c,2),l--));return r=u.join("/"),""===r&&(r=a?"/":"."),i?(i.path=r,o(i)):r}function s(e,n){""===e&&(e="."),""===n&&(n=".");var r=t(n),s=t(e);if(s&&(e=s.path||"/"),r&&!r.scheme)return s&&(r.scheme=s.scheme),o(r);if(r||n.match(y))return n;if(s&&!s.host&&!s.path)return s.host=n,o(s);var a="/"===n.charAt(0)?n:i(e.replace(/\/+$/,"")+"/"+n);return s?(s.path=a,o(s)):a}function a(e,n){""===e&&(e="."),e=e.replace(/\/$/,"");for(var r=0;0!==n.indexOf(e+"/");){var t=e.lastIndexOf("/");if(t<0)return n;if(e=e.slice(0,t),e.match(/^([^\/]+:\/)?\/*$/))return n;++r}return Array(r+1).join("../")+n.substr(e.length+1)}function u(e){return e}function l(e){return g(e)?"$"+e:e}function c(e){return g(e)?e.slice(1):e}function g(e){if(!e)return!1;var n=e.length;if(n<9)return!1;if(95!==e.charCodeAt(n-1)||95!==e.charCodeAt(n-2)||111!==e.charCodeAt(n-3)||116!==e.charCodeAt(n-4)||111!==e.charCodeAt(n-5)||114!==e.charCodeAt(n-6)||112!==e.charCodeAt(n-7)||95!==e.charCodeAt(n-8)||95!==e.charCodeAt(n-9))return!1;for(var r=n-10;r>=0;r--)if(36!==e.charCodeAt(r))return!1;return!0}function p(e,n,r){var t=f(e.source,n.source);return 0!==t?t:(t=e.originalLine-n.originalLine,0!==t?t:(t=e.originalColumn-n.originalColumn,0!==t||r?t:(t=e.generatedColumn-n.generatedColumn,0!==t?t:(t=e.generatedLine-n.generatedLine,0!==t?t:f(e.name,n.name)))))}function h(e,n,r){var t=e.generatedLine-n.generatedLine;return 0!==t?t:(t=e.generatedColumn-n.generatedColumn,0!==t||r?t:(t=f(e.source,n.source),0!==t?t:(t=e.originalLine-n.originalLine,0!==t?t:(t=e.originalColumn-n.originalColumn,0!==t?t:f(e.name,n.name)))))}function f(e,n){return e===n?0:null===e?1:null===n?-1:e>n?1:-1}function d(e,n){var r=e.generatedLine-n.generatedLine;return 0!==r?r:(r=e.generatedColumn-n.generatedColumn,0!==r?r:(r=f(e.source,n.source),0!==r?r:(r=e.originalLine-n.originalLine,0!==r?r:(r=e.originalColumn-n.originalColumn,0!==r?r:f(e.name,n.name)))))}function m(e){return JSON.parse(e.replace(/^\)]}'[^\n]*\n/,""))}function _(e,n,r){if(n=n||"",e&&("/"!==e[e.length-1]&&"/"!==n[0]&&(e+="/"),n=e+n),r){var a=t(r);if(!a)throw new Error("sourceMapURL could not be parsed");if(a.path){var u=a.path.lastIndexOf("/");u>=0&&(a.path=a.path.substring(0,u+1))}n=s(o(a),n)}return i(n)}n.getArg=r;var v=/^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/,y=/^data:.+\,.+$/;n.urlParse=t,n.urlGenerate=o,n.normalize=i,n.join=s,n.isAbsolute=function(e){return"/"===e.charAt(0)||v.test(e)},n.relative=a;var C=function(){var e=Object.create(null);return!("__proto__"in e)}();n.toSetString=C?u:l,n.fromSetString=C?u:c,n.compareByOriginalPositions=p,n.compareByGeneratedPositionsDeflated=h,n.compareByGeneratedPositionsInflated=d,n.parseSourceMapInput=m,n.computeSourceURL=_},function(e,n,r){function t(){this._array=[],this._set=s?new Map:Object.create(null)}var o=r(4),i=Object.prototype.hasOwnProperty,s="undefined"!=typeof Map;t.fromArray=function(e,n){for(var r=new t,o=0,i=e.length;o=0)return n}else{var r=o.toSetString(e);if(i.call(this._set,r))return this._set[r]}throw new Error('"'+e+'" is not in the set.')},t.prototype.at=function(e){if(e>=0&&er||t==r&&s>=o||i.compareByGeneratedPositionsInflated(e,n)<=0}function o(){this._array=[],this._sorted=!0,this._last={generatedLine:-1,generatedColumn:0}}var i=r(4);o.prototype.unsortedForEach=function(e,n){this._array.forEach(e,n)},o.prototype.add=function(e){t(this._last,e)?(this._last=e,this._array.push(e)):(this._sorted=!1,this._array.push(e))},o.prototype.toArray=function(){return this._sorted||(this._array.sort(i.compareByGeneratedPositionsInflated),this._sorted=!0),this._array},n.MappingList=o},function(e,n,r){function t(e,n){var r=e;return"string"==typeof e&&(r=a.parseSourceMapInput(e)),null!=r.sections?new s(r,n):new o(r,n)}function o(e,n){var r=e;"string"==typeof e&&(r=a.parseSourceMapInput(e));var t=a.getArg(r,"version"),o=a.getArg(r,"sources"),i=a.getArg(r,"names",[]),s=a.getArg(r,"sourceRoot",null),u=a.getArg(r,"sourcesContent",null),c=a.getArg(r,"mappings"),g=a.getArg(r,"file",null);if(t!=this._version)throw new Error("Unsupported version: "+t);s&&(s=a.normalize(s)),o=o.map(String).map(a.normalize).map(function(e){return s&&a.isAbsolute(s)&&a.isAbsolute(e)?a.relative(s,e):e}),this._names=l.fromArray(i.map(String),!0),this._sources=l.fromArray(o,!0),this._absoluteSources=this._sources.toArray().map(function(e){return a.computeSourceURL(s,e,n)}),this.sourceRoot=s,this.sourcesContent=u,this._mappings=c,this._sourceMapURL=n,this.file=g}function i(){this.generatedLine=0,this.generatedColumn=0,this.source=null,this.originalLine=null,this.originalColumn=null,this.name=null}function s(e,n){var r=e;"string"==typeof e&&(r=a.parseSourceMapInput(e));var o=a.getArg(r,"version"),i=a.getArg(r,"sections");if(o!=this._version)throw new Error("Unsupported version: "+o);this._sources=new l,this._names=new l;var s={line:-1,column:0};this._sections=i.map(function(e){if(e.url)throw new Error("Support for url field in sections not implemented.");var r=a.getArg(e,"offset"),o=a.getArg(r,"line"),i=a.getArg(r,"column");if(o=0){var i=this._originalMappings[o];if(void 0===e.column)for(var s=i.originalLine;i&&i.originalLine===s;)t.push({line:a.getArg(i,"generatedLine",null),column:a.getArg(i,"generatedColumn",null),lastColumn:a.getArg(i,"lastGeneratedColumn",null)}),i=this._originalMappings[++o];else for(var l=i.originalColumn;i&&i.originalLine===n&&i.originalColumn==l;)t.push({line:a.getArg(i,"generatedLine",null),column:a.getArg(i,"generatedColumn",null),lastColumn:a.getArg(i,"lastGeneratedColumn",null)}),i=this._originalMappings[++o]}return t},n.SourceMapConsumer=t,o.prototype=Object.create(t.prototype),o.prototype.consumer=t,o.prototype._findSourceIndex=function(e){var n=e;if(null!=this.sourceRoot&&(n=a.relative(this.sourceRoot,n)),this._sources.has(n))return this._sources.indexOf(n);var r;for(r=0;r1&&(r.source=d+o[1],d+=o[1],r.originalLine=h+o[2],h=r.originalLine,r.originalLine+=1,r.originalColumn=f+o[3],f=r.originalColumn,o.length>4&&(r.name=m+o[4],m+=o[4])),A.push(r),"number"==typeof r.originalLine&&S.push(r)}g(A,a.compareByGeneratedPositionsDeflated),this.__generatedMappings=A,g(S,a.compareByOriginalPositions),this.__originalMappings=S},o.prototype._findMapping=function(e,n,r,t,o,i){if(e[r]<=0)throw new TypeError("Line must be greater than or equal to 1, got "+e[r]);if(e[t]<0)throw new TypeError("Column must be greater than or equal to 0, got "+e[t]);return u.search(e,n,o,i)},o.prototype.computeColumnSpans=function(){for(var e=0;e=0){var o=this._generatedMappings[r];if(o.generatedLine===n.generatedLine){var i=a.getArg(o,"source",null);null!==i&&(i=this._sources.at(i),i=a.computeSourceURL(this.sourceRoot,i,this._sourceMapURL));var s=a.getArg(o,"name",null);return null!==s&&(s=this._names.at(s)),{source:i,line:a.getArg(o,"originalLine",null),column:a.getArg(o,"originalColumn",null),name:s}}}return{source:null,line:null,column:null,name:null}},o.prototype.hasContentsOfAllSources=function(){return!!this.sourcesContent&&(this.sourcesContent.length>=this._sources.size()&&!this.sourcesContent.some(function(e){return null==e}))},o.prototype.sourceContentFor=function(e,n){if(!this.sourcesContent)return null;var r=this._findSourceIndex(e);if(r>=0)return this.sourcesContent[r];var t=e;null!=this.sourceRoot&&(t=a.relative(this.sourceRoot,t));var o;if(null!=this.sourceRoot&&(o=a.urlParse(this.sourceRoot))){var i=t.replace(/^file:\/\//,"");if("file"==o.scheme&&this._sources.has(i))return this.sourcesContent[this._sources.indexOf(i)];if((!o.path||"/"==o.path)&&this._sources.has("/"+t))return this.sourcesContent[this._sources.indexOf("/"+t)]}if(n)return null;throw new Error('"'+t+'" is not in the SourceMap.')},o.prototype.generatedPositionFor=function(e){var n=a.getArg(e,"source");if(n=this._findSourceIndex(n),n<0)return{line:null,column:null,lastColumn:null};var r={source:n,originalLine:a.getArg(e,"line"),originalColumn:a.getArg(e,"column")},o=this._findMapping(r,this._originalMappings,"originalLine","originalColumn",a.compareByOriginalPositions,a.getArg(e,"bias",t.GREATEST_LOWER_BOUND));if(o>=0){var i=this._originalMappings[o];if(i.source===r.source)return{line:a.getArg(i,"generatedLine",null),column:a.getArg(i,"generatedColumn",null),lastColumn:a.getArg(i,"lastGeneratedColumn",null)}}return{line:null,column:null,lastColumn:null}},n.BasicSourceMapConsumer=o,s.prototype=Object.create(t.prototype),s.prototype.constructor=t,s.prototype._version=3,Object.defineProperty(s.prototype,"sources",{get:function(){for(var e=[],n=0;n0?t-u>1?r(u,t,o,i,s,a):a==n.LEAST_UPPER_BOUND?t1?r(e,u,o,i,s,a):a==n.LEAST_UPPER_BOUND?u:e<0?-1:e}n.GREATEST_LOWER_BOUND=1,n.LEAST_UPPER_BOUND=2,n.search=function(e,t,o,i){if(0===t.length)return-1;var s=r(-1,t.length,e,t,o,i||n.GREATEST_LOWER_BOUND);if(s<0)return-1;for(;s-1>=0&&0===o(t[s],t[s-1],!0);)--s;return s}},function(e,n){function r(e,n,r){var t=e[n];e[n]=e[r],e[r]=t}function t(e,n){return Math.round(e+Math.random()*(n-e))}function o(e,n,i,s){if(i=0;n--)this.prepend(e[n]);else{if(!e[u]&&"string"!=typeof e)throw new TypeError("Expected a SourceNode, string, or an array of SourceNodes and strings. Got "+e);this.children.unshift(e)}return this},t.prototype.walk=function(e){for(var n,r=0,t=this.children.length;r0){for(n=[],r=0;r 0 && aGenerated.column >= 0\n\t && !aOriginal && !aSource && !aName) {\n\t // Case 1.\n\t return;\n\t }\n\t else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated\n\t && aOriginal && 'line' in aOriginal && 'column' in aOriginal\n\t && aGenerated.line > 0 && aGenerated.column >= 0\n\t && aOriginal.line > 0 && aOriginal.column >= 0\n\t && aSource) {\n\t // Cases 2 and 3.\n\t return;\n\t }\n\t else {\n\t throw new Error('Invalid mapping: ' + JSON.stringify({\n\t generated: aGenerated,\n\t source: aSource,\n\t original: aOriginal,\n\t name: aName\n\t }));\n\t }\n\t };\n\t\n\t/**\n\t * Serialize the accumulated mappings in to the stream of base 64 VLQs\n\t * specified by the source map format.\n\t */\n\tSourceMapGenerator.prototype._serializeMappings =\n\t function SourceMapGenerator_serializeMappings() {\n\t var previousGeneratedColumn = 0;\n\t var previousGeneratedLine = 1;\n\t var previousOriginalColumn = 0;\n\t var previousOriginalLine = 0;\n\t var previousName = 0;\n\t var previousSource = 0;\n\t var result = '';\n\t var next;\n\t var mapping;\n\t var nameIdx;\n\t var sourceIdx;\n\t\n\t var mappings = this._mappings.toArray();\n\t for (var i = 0, len = mappings.length; i < len; i++) {\n\t mapping = mappings[i];\n\t next = ''\n\t\n\t if (mapping.generatedLine !== previousGeneratedLine) {\n\t previousGeneratedColumn = 0;\n\t while (mapping.generatedLine !== previousGeneratedLine) {\n\t next += ';';\n\t previousGeneratedLine++;\n\t }\n\t }\n\t else {\n\t if (i > 0) {\n\t if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) {\n\t continue;\n\t }\n\t next += ',';\n\t }\n\t }\n\t\n\t next += base64VLQ.encode(mapping.generatedColumn\n\t - previousGeneratedColumn);\n\t previousGeneratedColumn = mapping.generatedColumn;\n\t\n\t if (mapping.source != null) {\n\t sourceIdx = this._sources.indexOf(mapping.source);\n\t next += base64VLQ.encode(sourceIdx - previousSource);\n\t previousSource = sourceIdx;\n\t\n\t // lines are stored 0-based in SourceMap spec version 3\n\t next += base64VLQ.encode(mapping.originalLine - 1\n\t - previousOriginalLine);\n\t previousOriginalLine = mapping.originalLine - 1;\n\t\n\t next += base64VLQ.encode(mapping.originalColumn\n\t - previousOriginalColumn);\n\t previousOriginalColumn = mapping.originalColumn;\n\t\n\t if (mapping.name != null) {\n\t nameIdx = this._names.indexOf(mapping.name);\n\t next += base64VLQ.encode(nameIdx - previousName);\n\t previousName = nameIdx;\n\t }\n\t }\n\t\n\t result += next;\n\t }\n\t\n\t return result;\n\t };\n\t\n\tSourceMapGenerator.prototype._generateSourcesContent =\n\t function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) {\n\t return aSources.map(function (source) {\n\t if (!this._sourcesContents) {\n\t return null;\n\t }\n\t if (aSourceRoot != null) {\n\t source = util.relative(aSourceRoot, source);\n\t }\n\t var key = util.toSetString(source);\n\t return Object.prototype.hasOwnProperty.call(this._sourcesContents, key)\n\t ? this._sourcesContents[key]\n\t : null;\n\t }, this);\n\t };\n\t\n\t/**\n\t * Externalize the source map.\n\t */\n\tSourceMapGenerator.prototype.toJSON =\n\t function SourceMapGenerator_toJSON() {\n\t var map = {\n\t version: this._version,\n\t sources: this._sources.toArray(),\n\t names: this._names.toArray(),\n\t mappings: this._serializeMappings()\n\t };\n\t if (this._file != null) {\n\t map.file = this._file;\n\t }\n\t if (this._sourceRoot != null) {\n\t map.sourceRoot = this._sourceRoot;\n\t }\n\t if (this._sourcesContents) {\n\t map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot);\n\t }\n\t\n\t return map;\n\t };\n\t\n\t/**\n\t * Render the source map being generated to a string.\n\t */\n\tSourceMapGenerator.prototype.toString =\n\t function SourceMapGenerator_toString() {\n\t return JSON.stringify(this.toJSON());\n\t };\n\t\n\texports.SourceMapGenerator = SourceMapGenerator;\n\n\n/***/ }),\n/* 2 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\t/* -*- Mode: js; js-indent-level: 2; -*- */\n\t/*\n\t * Copyright 2011 Mozilla Foundation and contributors\n\t * Licensed under the New BSD license. See LICENSE or:\n\t * http://opensource.org/licenses/BSD-3-Clause\n\t *\n\t * Based on the Base 64 VLQ implementation in Closure Compiler:\n\t * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java\n\t *\n\t * Copyright 2011 The Closure Compiler Authors. All rights reserved.\n\t * Redistribution and use in source and binary forms, with or without\n\t * modification, are permitted provided that the following conditions are\n\t * met:\n\t *\n\t * * Redistributions of source code must retain the above copyright\n\t * notice, this list of conditions and the following disclaimer.\n\t * * Redistributions in binary form must reproduce the above\n\t * copyright notice, this list of conditions and the following\n\t * disclaimer in the documentation and/or other materials provided\n\t * with the distribution.\n\t * * Neither the name of Google Inc. nor the names of its\n\t * contributors may be used to endorse or promote products derived\n\t * from this software without specific prior written permission.\n\t *\n\t * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\t * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\t * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n\t * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n\t * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n\t * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n\t * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n\t * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n\t * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\t * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\t * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\t */\n\t\n\tvar base64 = __webpack_require__(3);\n\t\n\t// A single base 64 digit can contain 6 bits of data. For the base 64 variable\n\t// length quantities we use in the source map spec, the first bit is the sign,\n\t// the next four bits are the actual value, and the 6th bit is the\n\t// continuation bit. The continuation bit tells us whether there are more\n\t// digits in this value following this digit.\n\t//\n\t// Continuation\n\t// | Sign\n\t// | |\n\t// V V\n\t// 101011\n\t\n\tvar VLQ_BASE_SHIFT = 5;\n\t\n\t// binary: 100000\n\tvar VLQ_BASE = 1 << VLQ_BASE_SHIFT;\n\t\n\t// binary: 011111\n\tvar VLQ_BASE_MASK = VLQ_BASE - 1;\n\t\n\t// binary: 100000\n\tvar VLQ_CONTINUATION_BIT = VLQ_BASE;\n\t\n\t/**\n\t * Converts from a two-complement value to a value where the sign bit is\n\t * placed in the least significant bit. For example, as decimals:\n\t * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary)\n\t * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary)\n\t */\n\tfunction toVLQSigned(aValue) {\n\t return aValue < 0\n\t ? ((-aValue) << 1) + 1\n\t : (aValue << 1) + 0;\n\t}\n\t\n\t/**\n\t * Converts to a two-complement value from a value where the sign bit is\n\t * placed in the least significant bit. For example, as decimals:\n\t * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1\n\t * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2\n\t */\n\tfunction fromVLQSigned(aValue) {\n\t var isNegative = (aValue & 1) === 1;\n\t var shifted = aValue >> 1;\n\t return isNegative\n\t ? -shifted\n\t : shifted;\n\t}\n\t\n\t/**\n\t * Returns the base 64 VLQ encoded value.\n\t */\n\texports.encode = function base64VLQ_encode(aValue) {\n\t var encoded = \"\";\n\t var digit;\n\t\n\t var vlq = toVLQSigned(aValue);\n\t\n\t do {\n\t digit = vlq & VLQ_BASE_MASK;\n\t vlq >>>= VLQ_BASE_SHIFT;\n\t if (vlq > 0) {\n\t // There are still more digits in this value, so we must make sure the\n\t // continuation bit is marked.\n\t digit |= VLQ_CONTINUATION_BIT;\n\t }\n\t encoded += base64.encode(digit);\n\t } while (vlq > 0);\n\t\n\t return encoded;\n\t};\n\t\n\t/**\n\t * Decodes the next base 64 VLQ value from the given string and returns the\n\t * value and the rest of the string via the out parameter.\n\t */\n\texports.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) {\n\t var strLen = aStr.length;\n\t var result = 0;\n\t var shift = 0;\n\t var continuation, digit;\n\t\n\t do {\n\t if (aIndex >= strLen) {\n\t throw new Error(\"Expected more digits in base 64 VLQ value.\");\n\t }\n\t\n\t digit = base64.decode(aStr.charCodeAt(aIndex++));\n\t if (digit === -1) {\n\t throw new Error(\"Invalid base64 digit: \" + aStr.charAt(aIndex - 1));\n\t }\n\t\n\t continuation = !!(digit & VLQ_CONTINUATION_BIT);\n\t digit &= VLQ_BASE_MASK;\n\t result = result + (digit << shift);\n\t shift += VLQ_BASE_SHIFT;\n\t } while (continuation);\n\t\n\t aOutParam.value = fromVLQSigned(result);\n\t aOutParam.rest = aIndex;\n\t};\n\n\n/***/ }),\n/* 3 */\n/***/ (function(module, exports) {\n\n\t/* -*- Mode: js; js-indent-level: 2; -*- */\n\t/*\n\t * Copyright 2011 Mozilla Foundation and contributors\n\t * Licensed under the New BSD license. See LICENSE or:\n\t * http://opensource.org/licenses/BSD-3-Clause\n\t */\n\t\n\tvar intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split('');\n\t\n\t/**\n\t * Encode an integer in the range of 0 to 63 to a single base 64 digit.\n\t */\n\texports.encode = function (number) {\n\t if (0 <= number && number < intToCharMap.length) {\n\t return intToCharMap[number];\n\t }\n\t throw new TypeError(\"Must be between 0 and 63: \" + number);\n\t};\n\t\n\t/**\n\t * Decode a single base 64 character code digit to an integer. Returns -1 on\n\t * failure.\n\t */\n\texports.decode = function (charCode) {\n\t var bigA = 65; // 'A'\n\t var bigZ = 90; // 'Z'\n\t\n\t var littleA = 97; // 'a'\n\t var littleZ = 122; // 'z'\n\t\n\t var zero = 48; // '0'\n\t var nine = 57; // '9'\n\t\n\t var plus = 43; // '+'\n\t var slash = 47; // '/'\n\t\n\t var littleOffset = 26;\n\t var numberOffset = 52;\n\t\n\t // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ\n\t if (bigA <= charCode && charCode <= bigZ) {\n\t return (charCode - bigA);\n\t }\n\t\n\t // 26 - 51: abcdefghijklmnopqrstuvwxyz\n\t if (littleA <= charCode && charCode <= littleZ) {\n\t return (charCode - littleA + littleOffset);\n\t }\n\t\n\t // 52 - 61: 0123456789\n\t if (zero <= charCode && charCode <= nine) {\n\t return (charCode - zero + numberOffset);\n\t }\n\t\n\t // 62: +\n\t if (charCode == plus) {\n\t return 62;\n\t }\n\t\n\t // 63: /\n\t if (charCode == slash) {\n\t return 63;\n\t }\n\t\n\t // Invalid base64 digit.\n\t return -1;\n\t};\n\n\n/***/ }),\n/* 4 */\n/***/ (function(module, exports) {\n\n\t/* -*- Mode: js; js-indent-level: 2; -*- */\n\t/*\n\t * Copyright 2011 Mozilla Foundation and contributors\n\t * Licensed under the New BSD license. See LICENSE or:\n\t * http://opensource.org/licenses/BSD-3-Clause\n\t */\n\t\n\t/**\n\t * This is a helper function for getting values from parameter/options\n\t * objects.\n\t *\n\t * @param args The object we are extracting values from\n\t * @param name The name of the property we are getting.\n\t * @param defaultValue An optional value to return if the property is missing\n\t * from the object. If this is not specified and the property is missing, an\n\t * error will be thrown.\n\t */\n\tfunction getArg(aArgs, aName, aDefaultValue) {\n\t if (aName in aArgs) {\n\t return aArgs[aName];\n\t } else if (arguments.length === 3) {\n\t return aDefaultValue;\n\t } else {\n\t throw new Error('\"' + aName + '\" is a required argument.');\n\t }\n\t}\n\texports.getArg = getArg;\n\t\n\tvar urlRegexp = /^(?:([\\w+\\-.]+):)?\\/\\/(?:(\\w+:\\w+)@)?([\\w.-]*)(?::(\\d+))?(.*)$/;\n\tvar dataUrlRegexp = /^data:.+\\,.+$/;\n\t\n\tfunction urlParse(aUrl) {\n\t var match = aUrl.match(urlRegexp);\n\t if (!match) {\n\t return null;\n\t }\n\t return {\n\t scheme: match[1],\n\t auth: match[2],\n\t host: match[3],\n\t port: match[4],\n\t path: match[5]\n\t };\n\t}\n\texports.urlParse = urlParse;\n\t\n\tfunction urlGenerate(aParsedUrl) {\n\t var url = '';\n\t if (aParsedUrl.scheme) {\n\t url += aParsedUrl.scheme + ':';\n\t }\n\t url += '//';\n\t if (aParsedUrl.auth) {\n\t url += aParsedUrl.auth + '@';\n\t }\n\t if (aParsedUrl.host) {\n\t url += aParsedUrl.host;\n\t }\n\t if (aParsedUrl.port) {\n\t url += \":\" + aParsedUrl.port\n\t }\n\t if (aParsedUrl.path) {\n\t url += aParsedUrl.path;\n\t }\n\t return url;\n\t}\n\texports.urlGenerate = urlGenerate;\n\t\n\t/**\n\t * Normalizes a path, or the path portion of a URL:\n\t *\n\t * - Replaces consecutive slashes with one slash.\n\t * - Removes unnecessary '.' parts.\n\t * - Removes unnecessary '/..' parts.\n\t *\n\t * Based on code in the Node.js 'path' core module.\n\t *\n\t * @param aPath The path or url to normalize.\n\t */\n\tfunction normalize(aPath) {\n\t var path = aPath;\n\t var url = urlParse(aPath);\n\t if (url) {\n\t if (!url.path) {\n\t return aPath;\n\t }\n\t path = url.path;\n\t }\n\t var isAbsolute = exports.isAbsolute(path);\n\t\n\t var parts = path.split(/\\/+/);\n\t for (var part, up = 0, i = parts.length - 1; i >= 0; i--) {\n\t part = parts[i];\n\t if (part === '.') {\n\t parts.splice(i, 1);\n\t } else if (part === '..') {\n\t up++;\n\t } else if (up > 0) {\n\t if (part === '') {\n\t // The first part is blank if the path is absolute. Trying to go\n\t // above the root is a no-op. Therefore we can remove all '..' parts\n\t // directly after the root.\n\t parts.splice(i + 1, up);\n\t up = 0;\n\t } else {\n\t parts.splice(i, 2);\n\t up--;\n\t }\n\t }\n\t }\n\t path = parts.join('/');\n\t\n\t if (path === '') {\n\t path = isAbsolute ? '/' : '.';\n\t }\n\t\n\t if (url) {\n\t url.path = path;\n\t return urlGenerate(url);\n\t }\n\t return path;\n\t}\n\texports.normalize = normalize;\n\t\n\t/**\n\t * Joins two paths/URLs.\n\t *\n\t * @param aRoot The root path or URL.\n\t * @param aPath The path or URL to be joined with the root.\n\t *\n\t * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a\n\t * scheme-relative URL: Then the scheme of aRoot, if any, is prepended\n\t * first.\n\t * - Otherwise aPath is a path. If aRoot is a URL, then its path portion\n\t * is updated with the result and aRoot is returned. Otherwise the result\n\t * is returned.\n\t * - If aPath is absolute, the result is aPath.\n\t * - Otherwise the two paths are joined with a slash.\n\t * - Joining for example 'http://' and 'www.example.com' is also supported.\n\t */\n\tfunction join(aRoot, aPath) {\n\t if (aRoot === \"\") {\n\t aRoot = \".\";\n\t }\n\t if (aPath === \"\") {\n\t aPath = \".\";\n\t }\n\t var aPathUrl = urlParse(aPath);\n\t var aRootUrl = urlParse(aRoot);\n\t if (aRootUrl) {\n\t aRoot = aRootUrl.path || '/';\n\t }\n\t\n\t // `join(foo, '//www.example.org')`\n\t if (aPathUrl && !aPathUrl.scheme) {\n\t if (aRootUrl) {\n\t aPathUrl.scheme = aRootUrl.scheme;\n\t }\n\t return urlGenerate(aPathUrl);\n\t }\n\t\n\t if (aPathUrl || aPath.match(dataUrlRegexp)) {\n\t return aPath;\n\t }\n\t\n\t // `join('http://', 'www.example.com')`\n\t if (aRootUrl && !aRootUrl.host && !aRootUrl.path) {\n\t aRootUrl.host = aPath;\n\t return urlGenerate(aRootUrl);\n\t }\n\t\n\t var joined = aPath.charAt(0) === '/'\n\t ? aPath\n\t : normalize(aRoot.replace(/\\/+$/, '') + '/' + aPath);\n\t\n\t if (aRootUrl) {\n\t aRootUrl.path = joined;\n\t return urlGenerate(aRootUrl);\n\t }\n\t return joined;\n\t}\n\texports.join = join;\n\t\n\texports.isAbsolute = function (aPath) {\n\t return aPath.charAt(0) === '/' || urlRegexp.test(aPath);\n\t};\n\t\n\t/**\n\t * Make a path relative to a URL or another path.\n\t *\n\t * @param aRoot The root path or URL.\n\t * @param aPath The path or URL to be made relative to aRoot.\n\t */\n\tfunction relative(aRoot, aPath) {\n\t if (aRoot === \"\") {\n\t aRoot = \".\";\n\t }\n\t\n\t aRoot = aRoot.replace(/\\/$/, '');\n\t\n\t // It is possible for the path to be above the root. In this case, simply\n\t // checking whether the root is a prefix of the path won't work. Instead, we\n\t // need to remove components from the root one by one, until either we find\n\t // a prefix that fits, or we run out of components to remove.\n\t var level = 0;\n\t while (aPath.indexOf(aRoot + '/') !== 0) {\n\t var index = aRoot.lastIndexOf(\"/\");\n\t if (index < 0) {\n\t return aPath;\n\t }\n\t\n\t // If the only part of the root that is left is the scheme (i.e. http://,\n\t // file:///, etc.), one or more slashes (/), or simply nothing at all, we\n\t // have exhausted all components, so the path is not relative to the root.\n\t aRoot = aRoot.slice(0, index);\n\t if (aRoot.match(/^([^\\/]+:\\/)?\\/*$/)) {\n\t return aPath;\n\t }\n\t\n\t ++level;\n\t }\n\t\n\t // Make sure we add a \"../\" for each component we removed from the root.\n\t return Array(level + 1).join(\"../\") + aPath.substr(aRoot.length + 1);\n\t}\n\texports.relative = relative;\n\t\n\tvar supportsNullProto = (function () {\n\t var obj = Object.create(null);\n\t return !('__proto__' in obj);\n\t}());\n\t\n\tfunction identity (s) {\n\t return s;\n\t}\n\t\n\t/**\n\t * Because behavior goes wacky when you set `__proto__` on objects, we\n\t * have to prefix all the strings in our set with an arbitrary character.\n\t *\n\t * See https://github.com/mozilla/source-map/pull/31 and\n\t * https://github.com/mozilla/source-map/issues/30\n\t *\n\t * @param String aStr\n\t */\n\tfunction toSetString(aStr) {\n\t if (isProtoString(aStr)) {\n\t return '$' + aStr;\n\t }\n\t\n\t return aStr;\n\t}\n\texports.toSetString = supportsNullProto ? identity : toSetString;\n\t\n\tfunction fromSetString(aStr) {\n\t if (isProtoString(aStr)) {\n\t return aStr.slice(1);\n\t }\n\t\n\t return aStr;\n\t}\n\texports.fromSetString = supportsNullProto ? identity : fromSetString;\n\t\n\tfunction isProtoString(s) {\n\t if (!s) {\n\t return false;\n\t }\n\t\n\t var length = s.length;\n\t\n\t if (length < 9 /* \"__proto__\".length */) {\n\t return false;\n\t }\n\t\n\t if (s.charCodeAt(length - 1) !== 95 /* '_' */ ||\n\t s.charCodeAt(length - 2) !== 95 /* '_' */ ||\n\t s.charCodeAt(length - 3) !== 111 /* 'o' */ ||\n\t s.charCodeAt(length - 4) !== 116 /* 't' */ ||\n\t s.charCodeAt(length - 5) !== 111 /* 'o' */ ||\n\t s.charCodeAt(length - 6) !== 114 /* 'r' */ ||\n\t s.charCodeAt(length - 7) !== 112 /* 'p' */ ||\n\t s.charCodeAt(length - 8) !== 95 /* '_' */ ||\n\t s.charCodeAt(length - 9) !== 95 /* '_' */) {\n\t return false;\n\t }\n\t\n\t for (var i = length - 10; i >= 0; i--) {\n\t if (s.charCodeAt(i) !== 36 /* '$' */) {\n\t return false;\n\t }\n\t }\n\t\n\t return true;\n\t}\n\t\n\t/**\n\t * Comparator between two mappings where the original positions are compared.\n\t *\n\t * Optionally pass in `true` as `onlyCompareGenerated` to consider two\n\t * mappings with the same original source/line/column, but different generated\n\t * line and column the same. Useful when searching for a mapping with a\n\t * stubbed out mapping.\n\t */\n\tfunction compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) {\n\t var cmp = strcmp(mappingA.source, mappingB.source);\n\t if (cmp !== 0) {\n\t return cmp;\n\t }\n\t\n\t cmp = mappingA.originalLine - mappingB.originalLine;\n\t if (cmp !== 0) {\n\t return cmp;\n\t }\n\t\n\t cmp = mappingA.originalColumn - mappingB.originalColumn;\n\t if (cmp !== 0 || onlyCompareOriginal) {\n\t return cmp;\n\t }\n\t\n\t cmp = mappingA.generatedColumn - mappingB.generatedColumn;\n\t if (cmp !== 0) {\n\t return cmp;\n\t }\n\t\n\t cmp = mappingA.generatedLine - mappingB.generatedLine;\n\t if (cmp !== 0) {\n\t return cmp;\n\t }\n\t\n\t return strcmp(mappingA.name, mappingB.name);\n\t}\n\texports.compareByOriginalPositions = compareByOriginalPositions;\n\t\n\t/**\n\t * Comparator between two mappings with deflated source and name indices where\n\t * the generated positions are compared.\n\t *\n\t * Optionally pass in `true` as `onlyCompareGenerated` to consider two\n\t * mappings with the same generated line and column, but different\n\t * source/name/original line and column the same. Useful when searching for a\n\t * mapping with a stubbed out mapping.\n\t */\n\tfunction compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) {\n\t var cmp = mappingA.generatedLine - mappingB.generatedLine;\n\t if (cmp !== 0) {\n\t return cmp;\n\t }\n\t\n\t cmp = mappingA.generatedColumn - mappingB.generatedColumn;\n\t if (cmp !== 0 || onlyCompareGenerated) {\n\t return cmp;\n\t }\n\t\n\t cmp = strcmp(mappingA.source, mappingB.source);\n\t if (cmp !== 0) {\n\t return cmp;\n\t }\n\t\n\t cmp = mappingA.originalLine - mappingB.originalLine;\n\t if (cmp !== 0) {\n\t return cmp;\n\t }\n\t\n\t cmp = mappingA.originalColumn - mappingB.originalColumn;\n\t if (cmp !== 0) {\n\t return cmp;\n\t }\n\t\n\t return strcmp(mappingA.name, mappingB.name);\n\t}\n\texports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated;\n\t\n\tfunction strcmp(aStr1, aStr2) {\n\t if (aStr1 === aStr2) {\n\t return 0;\n\t }\n\t\n\t if (aStr1 === null) {\n\t return 1; // aStr2 !== null\n\t }\n\t\n\t if (aStr2 === null) {\n\t return -1; // aStr1 !== null\n\t }\n\t\n\t if (aStr1 > aStr2) {\n\t return 1;\n\t }\n\t\n\t return -1;\n\t}\n\t\n\t/**\n\t * Comparator between two mappings with inflated source and name strings where\n\t * the generated positions are compared.\n\t */\n\tfunction compareByGeneratedPositionsInflated(mappingA, mappingB) {\n\t var cmp = mappingA.generatedLine - mappingB.generatedLine;\n\t if (cmp !== 0) {\n\t return cmp;\n\t }\n\t\n\t cmp = mappingA.generatedColumn - mappingB.generatedColumn;\n\t if (cmp !== 0) {\n\t return cmp;\n\t }\n\t\n\t cmp = strcmp(mappingA.source, mappingB.source);\n\t if (cmp !== 0) {\n\t return cmp;\n\t }\n\t\n\t cmp = mappingA.originalLine - mappingB.originalLine;\n\t if (cmp !== 0) {\n\t return cmp;\n\t }\n\t\n\t cmp = mappingA.originalColumn - mappingB.originalColumn;\n\t if (cmp !== 0) {\n\t return cmp;\n\t }\n\t\n\t return strcmp(mappingA.name, mappingB.name);\n\t}\n\texports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated;\n\t\n\t/**\n\t * Strip any JSON XSSI avoidance prefix from the string (as documented\n\t * in the source maps specification), and then parse the string as\n\t * JSON.\n\t */\n\tfunction parseSourceMapInput(str) {\n\t return JSON.parse(str.replace(/^\\)]}'[^\\n]*\\n/, ''));\n\t}\n\texports.parseSourceMapInput = parseSourceMapInput;\n\t\n\t/**\n\t * Compute the URL of a source given the the source root, the source's\n\t * URL, and the source map's URL.\n\t */\n\tfunction computeSourceURL(sourceRoot, sourceURL, sourceMapURL) {\n\t sourceURL = sourceURL || '';\n\t\n\t if (sourceRoot) {\n\t // This follows what Chrome does.\n\t if (sourceRoot[sourceRoot.length - 1] !== '/' && sourceURL[0] !== '/') {\n\t sourceRoot += '/';\n\t }\n\t // The spec says:\n\t // Line 4: An optional source root, useful for relocating source\n\t // files on a server or removing repeated values in the\n\t // “sources” entry. This value is prepended to the individual\n\t // entries in the “source” field.\n\t sourceURL = sourceRoot + sourceURL;\n\t }\n\t\n\t // Historically, SourceMapConsumer did not take the sourceMapURL as\n\t // a parameter. This mode is still somewhat supported, which is why\n\t // this code block is conditional. However, it's preferable to pass\n\t // the source map URL to SourceMapConsumer, so that this function\n\t // can implement the source URL resolution algorithm as outlined in\n\t // the spec. This block is basically the equivalent of:\n\t // new URL(sourceURL, sourceMapURL).toString()\n\t // ... except it avoids using URL, which wasn't available in the\n\t // older releases of node still supported by this library.\n\t //\n\t // The spec says:\n\t // If the sources are not absolute URLs after prepending of the\n\t // “sourceRoot”, the sources are resolved relative to the\n\t // SourceMap (like resolving script src in a html document).\n\t if (sourceMapURL) {\n\t var parsed = urlParse(sourceMapURL);\n\t if (!parsed) {\n\t throw new Error(\"sourceMapURL could not be parsed\");\n\t }\n\t if (parsed.path) {\n\t // Strip the last path component, but keep the \"/\".\n\t var index = parsed.path.lastIndexOf('/');\n\t if (index >= 0) {\n\t parsed.path = parsed.path.substring(0, index + 1);\n\t }\n\t }\n\t sourceURL = join(urlGenerate(parsed), sourceURL);\n\t }\n\t\n\t return normalize(sourceURL);\n\t}\n\texports.computeSourceURL = computeSourceURL;\n\n\n/***/ }),\n/* 5 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\t/* -*- Mode: js; js-indent-level: 2; -*- */\n\t/*\n\t * Copyright 2011 Mozilla Foundation and contributors\n\t * Licensed under the New BSD license. See LICENSE or:\n\t * http://opensource.org/licenses/BSD-3-Clause\n\t */\n\t\n\tvar util = __webpack_require__(4);\n\tvar has = Object.prototype.hasOwnProperty;\n\tvar hasNativeMap = typeof Map !== \"undefined\";\n\t\n\t/**\n\t * A data structure which is a combination of an array and a set. Adding a new\n\t * member is O(1), testing for membership is O(1), and finding the index of an\n\t * element is O(1). Removing elements from the set is not supported. Only\n\t * strings are supported for membership.\n\t */\n\tfunction ArraySet() {\n\t this._array = [];\n\t this._set = hasNativeMap ? new Map() : Object.create(null);\n\t}\n\t\n\t/**\n\t * Static method for creating ArraySet instances from an existing array.\n\t */\n\tArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) {\n\t var set = new ArraySet();\n\t for (var i = 0, len = aArray.length; i < len; i++) {\n\t set.add(aArray[i], aAllowDuplicates);\n\t }\n\t return set;\n\t};\n\t\n\t/**\n\t * Return how many unique items are in this ArraySet. If duplicates have been\n\t * added, than those do not count towards the size.\n\t *\n\t * @returns Number\n\t */\n\tArraySet.prototype.size = function ArraySet_size() {\n\t return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length;\n\t};\n\t\n\t/**\n\t * Add the given string to this set.\n\t *\n\t * @param String aStr\n\t */\n\tArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) {\n\t var sStr = hasNativeMap ? aStr : util.toSetString(aStr);\n\t var isDuplicate = hasNativeMap ? this.has(aStr) : has.call(this._set, sStr);\n\t var idx = this._array.length;\n\t if (!isDuplicate || aAllowDuplicates) {\n\t this._array.push(aStr);\n\t }\n\t if (!isDuplicate) {\n\t if (hasNativeMap) {\n\t this._set.set(aStr, idx);\n\t } else {\n\t this._set[sStr] = idx;\n\t }\n\t }\n\t};\n\t\n\t/**\n\t * Is the given string a member of this set?\n\t *\n\t * @param String aStr\n\t */\n\tArraySet.prototype.has = function ArraySet_has(aStr) {\n\t if (hasNativeMap) {\n\t return this._set.has(aStr);\n\t } else {\n\t var sStr = util.toSetString(aStr);\n\t return has.call(this._set, sStr);\n\t }\n\t};\n\t\n\t/**\n\t * What is the index of the given string in the array?\n\t *\n\t * @param String aStr\n\t */\n\tArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) {\n\t if (hasNativeMap) {\n\t var idx = this._set.get(aStr);\n\t if (idx >= 0) {\n\t return idx;\n\t }\n\t } else {\n\t var sStr = util.toSetString(aStr);\n\t if (has.call(this._set, sStr)) {\n\t return this._set[sStr];\n\t }\n\t }\n\t\n\t throw new Error('\"' + aStr + '\" is not in the set.');\n\t};\n\t\n\t/**\n\t * What is the element at the given index?\n\t *\n\t * @param Number aIdx\n\t */\n\tArraySet.prototype.at = function ArraySet_at(aIdx) {\n\t if (aIdx >= 0 && aIdx < this._array.length) {\n\t return this._array[aIdx];\n\t }\n\t throw new Error('No element indexed by ' + aIdx);\n\t};\n\t\n\t/**\n\t * Returns the array representation of this set (which has the proper indices\n\t * indicated by indexOf). Note that this is a copy of the internal array used\n\t * for storing the members so that no one can mess with internal state.\n\t */\n\tArraySet.prototype.toArray = function ArraySet_toArray() {\n\t return this._array.slice();\n\t};\n\t\n\texports.ArraySet = ArraySet;\n\n\n/***/ }),\n/* 6 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\t/* -*- Mode: js; js-indent-level: 2; -*- */\n\t/*\n\t * Copyright 2014 Mozilla Foundation and contributors\n\t * Licensed under the New BSD license. See LICENSE or:\n\t * http://opensource.org/licenses/BSD-3-Clause\n\t */\n\t\n\tvar util = __webpack_require__(4);\n\t\n\t/**\n\t * Determine whether mappingB is after mappingA with respect to generated\n\t * position.\n\t */\n\tfunction generatedPositionAfter(mappingA, mappingB) {\n\t // Optimized for most common case\n\t var lineA = mappingA.generatedLine;\n\t var lineB = mappingB.generatedLine;\n\t var columnA = mappingA.generatedColumn;\n\t var columnB = mappingB.generatedColumn;\n\t return lineB > lineA || lineB == lineA && columnB >= columnA ||\n\t util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0;\n\t}\n\t\n\t/**\n\t * A data structure to provide a sorted view of accumulated mappings in a\n\t * performance conscious manner. It trades a neglibable overhead in general\n\t * case for a large speedup in case of mappings being added in order.\n\t */\n\tfunction MappingList() {\n\t this._array = [];\n\t this._sorted = true;\n\t // Serves as infimum\n\t this._last = {generatedLine: -1, generatedColumn: 0};\n\t}\n\t\n\t/**\n\t * Iterate through internal items. This method takes the same arguments that\n\t * `Array.prototype.forEach` takes.\n\t *\n\t * NOTE: The order of the mappings is NOT guaranteed.\n\t */\n\tMappingList.prototype.unsortedForEach =\n\t function MappingList_forEach(aCallback, aThisArg) {\n\t this._array.forEach(aCallback, aThisArg);\n\t };\n\t\n\t/**\n\t * Add the given source mapping.\n\t *\n\t * @param Object aMapping\n\t */\n\tMappingList.prototype.add = function MappingList_add(aMapping) {\n\t if (generatedPositionAfter(this._last, aMapping)) {\n\t this._last = aMapping;\n\t this._array.push(aMapping);\n\t } else {\n\t this._sorted = false;\n\t this._array.push(aMapping);\n\t }\n\t};\n\t\n\t/**\n\t * Returns the flat, sorted array of mappings. The mappings are sorted by\n\t * generated position.\n\t *\n\t * WARNING: This method returns internal data without copying, for\n\t * performance. The return value must NOT be mutated, and should be treated as\n\t * an immutable borrow. If you want to take ownership, you must make your own\n\t * copy.\n\t */\n\tMappingList.prototype.toArray = function MappingList_toArray() {\n\t if (!this._sorted) {\n\t this._array.sort(util.compareByGeneratedPositionsInflated);\n\t this._sorted = true;\n\t }\n\t return this._array;\n\t};\n\t\n\texports.MappingList = MappingList;\n\n\n/***/ }),\n/* 7 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\t/* -*- Mode: js; js-indent-level: 2; -*- */\n\t/*\n\t * Copyright 2011 Mozilla Foundation and contributors\n\t * Licensed under the New BSD license. See LICENSE or:\n\t * http://opensource.org/licenses/BSD-3-Clause\n\t */\n\t\n\tvar util = __webpack_require__(4);\n\tvar binarySearch = __webpack_require__(8);\n\tvar ArraySet = __webpack_require__(5).ArraySet;\n\tvar base64VLQ = __webpack_require__(2);\n\tvar quickSort = __webpack_require__(9).quickSort;\n\t\n\tfunction SourceMapConsumer(aSourceMap, aSourceMapURL) {\n\t var sourceMap = aSourceMap;\n\t if (typeof aSourceMap === 'string') {\n\t sourceMap = util.parseSourceMapInput(aSourceMap);\n\t }\n\t\n\t return sourceMap.sections != null\n\t ? new IndexedSourceMapConsumer(sourceMap, aSourceMapURL)\n\t : new BasicSourceMapConsumer(sourceMap, aSourceMapURL);\n\t}\n\t\n\tSourceMapConsumer.fromSourceMap = function(aSourceMap, aSourceMapURL) {\n\t return BasicSourceMapConsumer.fromSourceMap(aSourceMap, aSourceMapURL);\n\t}\n\t\n\t/**\n\t * The version of the source mapping spec that we are consuming.\n\t */\n\tSourceMapConsumer.prototype._version = 3;\n\t\n\t// `__generatedMappings` and `__originalMappings` are arrays that hold the\n\t// parsed mapping coordinates from the source map's \"mappings\" attribute. They\n\t// are lazily instantiated, accessed via the `_generatedMappings` and\n\t// `_originalMappings` getters respectively, and we only parse the mappings\n\t// and create these arrays once queried for a source location. We jump through\n\t// these hoops because there can be many thousands of mappings, and parsing\n\t// them is expensive, so we only want to do it if we must.\n\t//\n\t// Each object in the arrays is of the form:\n\t//\n\t// {\n\t// generatedLine: The line number in the generated code,\n\t// generatedColumn: The column number in the generated code,\n\t// source: The path to the original source file that generated this\n\t// chunk of code,\n\t// originalLine: The line number in the original source that\n\t// corresponds to this chunk of generated code,\n\t// originalColumn: The column number in the original source that\n\t// corresponds to this chunk of generated code,\n\t// name: The name of the original symbol which generated this chunk of\n\t// code.\n\t// }\n\t//\n\t// All properties except for `generatedLine` and `generatedColumn` can be\n\t// `null`.\n\t//\n\t// `_generatedMappings` is ordered by the generated positions.\n\t//\n\t// `_originalMappings` is ordered by the original positions.\n\t\n\tSourceMapConsumer.prototype.__generatedMappings = null;\n\tObject.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', {\n\t configurable: true,\n\t enumerable: true,\n\t get: function () {\n\t if (!this.__generatedMappings) {\n\t this._parseMappings(this._mappings, this.sourceRoot);\n\t }\n\t\n\t return this.__generatedMappings;\n\t }\n\t});\n\t\n\tSourceMapConsumer.prototype.__originalMappings = null;\n\tObject.defineProperty(SourceMapConsumer.prototype, '_originalMappings', {\n\t configurable: true,\n\t enumerable: true,\n\t get: function () {\n\t if (!this.__originalMappings) {\n\t this._parseMappings(this._mappings, this.sourceRoot);\n\t }\n\t\n\t return this.__originalMappings;\n\t }\n\t});\n\t\n\tSourceMapConsumer.prototype._charIsMappingSeparator =\n\t function SourceMapConsumer_charIsMappingSeparator(aStr, index) {\n\t var c = aStr.charAt(index);\n\t return c === \";\" || c === \",\";\n\t };\n\t\n\t/**\n\t * Parse the mappings in a string in to a data structure which we can easily\n\t * query (the ordered arrays in the `this.__generatedMappings` and\n\t * `this.__originalMappings` properties).\n\t */\n\tSourceMapConsumer.prototype._parseMappings =\n\t function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {\n\t throw new Error(\"Subclasses must implement _parseMappings\");\n\t };\n\t\n\tSourceMapConsumer.GENERATED_ORDER = 1;\n\tSourceMapConsumer.ORIGINAL_ORDER = 2;\n\t\n\tSourceMapConsumer.GREATEST_LOWER_BOUND = 1;\n\tSourceMapConsumer.LEAST_UPPER_BOUND = 2;\n\t\n\t/**\n\t * Iterate over each mapping between an original source/line/column and a\n\t * generated line/column in this source map.\n\t *\n\t * @param Function aCallback\n\t * The function that is called with each mapping.\n\t * @param Object aContext\n\t * Optional. If specified, this object will be the value of `this` every\n\t * time that `aCallback` is called.\n\t * @param aOrder\n\t * Either `SourceMapConsumer.GENERATED_ORDER` or\n\t * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to\n\t * iterate over the mappings sorted by the generated file's line/column\n\t * order or the original's source/line/column order, respectively. Defaults to\n\t * `SourceMapConsumer.GENERATED_ORDER`.\n\t */\n\tSourceMapConsumer.prototype.eachMapping =\n\t function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) {\n\t var context = aContext || null;\n\t var order = aOrder || SourceMapConsumer.GENERATED_ORDER;\n\t\n\t var mappings;\n\t switch (order) {\n\t case SourceMapConsumer.GENERATED_ORDER:\n\t mappings = this._generatedMappings;\n\t break;\n\t case SourceMapConsumer.ORIGINAL_ORDER:\n\t mappings = this._originalMappings;\n\t break;\n\t default:\n\t throw new Error(\"Unknown order of iteration.\");\n\t }\n\t\n\t var sourceRoot = this.sourceRoot;\n\t mappings.map(function (mapping) {\n\t var source = mapping.source === null ? null : this._sources.at(mapping.source);\n\t source = util.computeSourceURL(sourceRoot, source, this._sourceMapURL);\n\t return {\n\t source: source,\n\t generatedLine: mapping.generatedLine,\n\t generatedColumn: mapping.generatedColumn,\n\t originalLine: mapping.originalLine,\n\t originalColumn: mapping.originalColumn,\n\t name: mapping.name === null ? null : this._names.at(mapping.name)\n\t };\n\t }, this).forEach(aCallback, context);\n\t };\n\t\n\t/**\n\t * Returns all generated line and column information for the original source,\n\t * line, and column provided. If no column is provided, returns all mappings\n\t * corresponding to a either the line we are searching for or the next\n\t * closest line that has any mappings. Otherwise, returns all mappings\n\t * corresponding to the given line and either the column we are searching for\n\t * or the next closest column that has any offsets.\n\t *\n\t * The only argument is an object with the following properties:\n\t *\n\t * - source: The filename of the original source.\n\t * - line: The line number in the original source. The line number is 1-based.\n\t * - column: Optional. the column number in the original source.\n\t * The column number is 0-based.\n\t *\n\t * and an array of objects is returned, each with the following properties:\n\t *\n\t * - line: The line number in the generated source, or null. The\n\t * line number is 1-based.\n\t * - column: The column number in the generated source, or null.\n\t * The column number is 0-based.\n\t */\n\tSourceMapConsumer.prototype.allGeneratedPositionsFor =\n\t function SourceMapConsumer_allGeneratedPositionsFor(aArgs) {\n\t var line = util.getArg(aArgs, 'line');\n\t\n\t // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping\n\t // returns the index of the closest mapping less than the needle. By\n\t // setting needle.originalColumn to 0, we thus find the last mapping for\n\t // the given line, provided such a mapping exists.\n\t var needle = {\n\t source: util.getArg(aArgs, 'source'),\n\t originalLine: line,\n\t originalColumn: util.getArg(aArgs, 'column', 0)\n\t };\n\t\n\t needle.source = this._findSourceIndex(needle.source);\n\t if (needle.source < 0) {\n\t return [];\n\t }\n\t\n\t var mappings = [];\n\t\n\t var index = this._findMapping(needle,\n\t this._originalMappings,\n\t \"originalLine\",\n\t \"originalColumn\",\n\t util.compareByOriginalPositions,\n\t binarySearch.LEAST_UPPER_BOUND);\n\t if (index >= 0) {\n\t var mapping = this._originalMappings[index];\n\t\n\t if (aArgs.column === undefined) {\n\t var originalLine = mapping.originalLine;\n\t\n\t // Iterate until either we run out of mappings, or we run into\n\t // a mapping for a different line than the one we found. Since\n\t // mappings are sorted, this is guaranteed to find all mappings for\n\t // the line we found.\n\t while (mapping && mapping.originalLine === originalLine) {\n\t mappings.push({\n\t line: util.getArg(mapping, 'generatedLine', null),\n\t column: util.getArg(mapping, 'generatedColumn', null),\n\t lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)\n\t });\n\t\n\t mapping = this._originalMappings[++index];\n\t }\n\t } else {\n\t var originalColumn = mapping.originalColumn;\n\t\n\t // Iterate until either we run out of mappings, or we run into\n\t // a mapping for a different line than the one we were searching for.\n\t // Since mappings are sorted, this is guaranteed to find all mappings for\n\t // the line we are searching for.\n\t while (mapping &&\n\t mapping.originalLine === line &&\n\t mapping.originalColumn == originalColumn) {\n\t mappings.push({\n\t line: util.getArg(mapping, 'generatedLine', null),\n\t column: util.getArg(mapping, 'generatedColumn', null),\n\t lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)\n\t });\n\t\n\t mapping = this._originalMappings[++index];\n\t }\n\t }\n\t }\n\t\n\t return mappings;\n\t };\n\t\n\texports.SourceMapConsumer = SourceMapConsumer;\n\t\n\t/**\n\t * A BasicSourceMapConsumer instance represents a parsed source map which we can\n\t * query for information about the original file positions by giving it a file\n\t * position in the generated source.\n\t *\n\t * The first parameter is the raw source map (either as a JSON string, or\n\t * already parsed to an object). According to the spec, source maps have the\n\t * following attributes:\n\t *\n\t * - version: Which version of the source map spec this map is following.\n\t * - sources: An array of URLs to the original source files.\n\t * - names: An array of identifiers which can be referrenced by individual mappings.\n\t * - sourceRoot: Optional. The URL root from which all sources are relative.\n\t * - sourcesContent: Optional. An array of contents of the original source files.\n\t * - mappings: A string of base64 VLQs which contain the actual mappings.\n\t * - file: Optional. The generated file this source map is associated with.\n\t *\n\t * Here is an example source map, taken from the source map spec[0]:\n\t *\n\t * {\n\t * version : 3,\n\t * file: \"out.js\",\n\t * sourceRoot : \"\",\n\t * sources: [\"foo.js\", \"bar.js\"],\n\t * names: [\"src\", \"maps\", \"are\", \"fun\"],\n\t * mappings: \"AA,AB;;ABCDE;\"\n\t * }\n\t *\n\t * The second parameter, if given, is a string whose value is the URL\n\t * at which the source map was found. This URL is used to compute the\n\t * sources array.\n\t *\n\t * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1#\n\t */\n\tfunction BasicSourceMapConsumer(aSourceMap, aSourceMapURL) {\n\t var sourceMap = aSourceMap;\n\t if (typeof aSourceMap === 'string') {\n\t sourceMap = util.parseSourceMapInput(aSourceMap);\n\t }\n\t\n\t var version = util.getArg(sourceMap, 'version');\n\t var sources = util.getArg(sourceMap, 'sources');\n\t // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which\n\t // requires the array) to play nice here.\n\t var names = util.getArg(sourceMap, 'names', []);\n\t var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null);\n\t var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null);\n\t var mappings = util.getArg(sourceMap, 'mappings');\n\t var file = util.getArg(sourceMap, 'file', null);\n\t\n\t // Once again, Sass deviates from the spec and supplies the version as a\n\t // string rather than a number, so we use loose equality checking here.\n\t if (version != this._version) {\n\t throw new Error('Unsupported version: ' + version);\n\t }\n\t\n\t if (sourceRoot) {\n\t sourceRoot = util.normalize(sourceRoot);\n\t }\n\t\n\t sources = sources\n\t .map(String)\n\t // Some source maps produce relative source paths like \"./foo.js\" instead of\n\t // \"foo.js\". Normalize these first so that future comparisons will succeed.\n\t // See bugzil.la/1090768.\n\t .map(util.normalize)\n\t // Always ensure that absolute sources are internally stored relative to\n\t // the source root, if the source root is absolute. Not doing this would\n\t // be particularly problematic when the source root is a prefix of the\n\t // source (valid, but why??). See github issue #199 and bugzil.la/1188982.\n\t .map(function (source) {\n\t return sourceRoot && util.isAbsolute(sourceRoot) && util.isAbsolute(source)\n\t ? util.relative(sourceRoot, source)\n\t : source;\n\t });\n\t\n\t // Pass `true` below to allow duplicate names and sources. While source maps\n\t // are intended to be compressed and deduplicated, the TypeScript compiler\n\t // sometimes generates source maps with duplicates in them. See Github issue\n\t // #72 and bugzil.la/889492.\n\t this._names = ArraySet.fromArray(names.map(String), true);\n\t this._sources = ArraySet.fromArray(sources, true);\n\t\n\t this._absoluteSources = this._sources.toArray().map(function (s) {\n\t return util.computeSourceURL(sourceRoot, s, aSourceMapURL);\n\t });\n\t\n\t this.sourceRoot = sourceRoot;\n\t this.sourcesContent = sourcesContent;\n\t this._mappings = mappings;\n\t this._sourceMapURL = aSourceMapURL;\n\t this.file = file;\n\t}\n\t\n\tBasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);\n\tBasicSourceMapConsumer.prototype.consumer = SourceMapConsumer;\n\t\n\t/**\n\t * Utility function to find the index of a source. Returns -1 if not\n\t * found.\n\t */\n\tBasicSourceMapConsumer.prototype._findSourceIndex = function(aSource) {\n\t var relativeSource = aSource;\n\t if (this.sourceRoot != null) {\n\t relativeSource = util.relative(this.sourceRoot, relativeSource);\n\t }\n\t\n\t if (this._sources.has(relativeSource)) {\n\t return this._sources.indexOf(relativeSource);\n\t }\n\t\n\t // Maybe aSource is an absolute URL as returned by |sources|. In\n\t // this case we can't simply undo the transform.\n\t var i;\n\t for (i = 0; i < this._absoluteSources.length; ++i) {\n\t if (this._absoluteSources[i] == aSource) {\n\t return i;\n\t }\n\t }\n\t\n\t return -1;\n\t};\n\t\n\t/**\n\t * Create a BasicSourceMapConsumer from a SourceMapGenerator.\n\t *\n\t * @param SourceMapGenerator aSourceMap\n\t * The source map that will be consumed.\n\t * @param String aSourceMapURL\n\t * The URL at which the source map can be found (optional)\n\t * @returns BasicSourceMapConsumer\n\t */\n\tBasicSourceMapConsumer.fromSourceMap =\n\t function SourceMapConsumer_fromSourceMap(aSourceMap, aSourceMapURL) {\n\t var smc = Object.create(BasicSourceMapConsumer.prototype);\n\t\n\t var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true);\n\t var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true);\n\t smc.sourceRoot = aSourceMap._sourceRoot;\n\t smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(),\n\t smc.sourceRoot);\n\t smc.file = aSourceMap._file;\n\t smc._sourceMapURL = aSourceMapURL;\n\t smc._absoluteSources = smc._sources.toArray().map(function (s) {\n\t return util.computeSourceURL(smc.sourceRoot, s, aSourceMapURL);\n\t });\n\t\n\t // Because we are modifying the entries (by converting string sources and\n\t // names to indices into the sources and names ArraySets), we have to make\n\t // a copy of the entry or else bad things happen. Shared mutable state\n\t // strikes again! See github issue #191.\n\t\n\t var generatedMappings = aSourceMap._mappings.toArray().slice();\n\t var destGeneratedMappings = smc.__generatedMappings = [];\n\t var destOriginalMappings = smc.__originalMappings = [];\n\t\n\t for (var i = 0, length = generatedMappings.length; i < length; i++) {\n\t var srcMapping = generatedMappings[i];\n\t var destMapping = new Mapping;\n\t destMapping.generatedLine = srcMapping.generatedLine;\n\t destMapping.generatedColumn = srcMapping.generatedColumn;\n\t\n\t if (srcMapping.source) {\n\t destMapping.source = sources.indexOf(srcMapping.source);\n\t destMapping.originalLine = srcMapping.originalLine;\n\t destMapping.originalColumn = srcMapping.originalColumn;\n\t\n\t if (srcMapping.name) {\n\t destMapping.name = names.indexOf(srcMapping.name);\n\t }\n\t\n\t destOriginalMappings.push(destMapping);\n\t }\n\t\n\t destGeneratedMappings.push(destMapping);\n\t }\n\t\n\t quickSort(smc.__originalMappings, util.compareByOriginalPositions);\n\t\n\t return smc;\n\t };\n\t\n\t/**\n\t * The version of the source mapping spec that we are consuming.\n\t */\n\tBasicSourceMapConsumer.prototype._version = 3;\n\t\n\t/**\n\t * The list of original sources.\n\t */\n\tObject.defineProperty(BasicSourceMapConsumer.prototype, 'sources', {\n\t get: function () {\n\t return this._absoluteSources.slice();\n\t }\n\t});\n\t\n\t/**\n\t * Provide the JIT with a nice shape / hidden class.\n\t */\n\tfunction Mapping() {\n\t this.generatedLine = 0;\n\t this.generatedColumn = 0;\n\t this.source = null;\n\t this.originalLine = null;\n\t this.originalColumn = null;\n\t this.name = null;\n\t}\n\t\n\t/**\n\t * Parse the mappings in a string in to a data structure which we can easily\n\t * query (the ordered arrays in the `this.__generatedMappings` and\n\t * `this.__originalMappings` properties).\n\t */\n\tBasicSourceMapConsumer.prototype._parseMappings =\n\t function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {\n\t var generatedLine = 1;\n\t var previousGeneratedColumn = 0;\n\t var previousOriginalLine = 0;\n\t var previousOriginalColumn = 0;\n\t var previousSource = 0;\n\t var previousName = 0;\n\t var length = aStr.length;\n\t var index = 0;\n\t var cachedSegments = {};\n\t var temp = {};\n\t var originalMappings = [];\n\t var generatedMappings = [];\n\t var mapping, str, segment, end, value;\n\t\n\t while (index < length) {\n\t if (aStr.charAt(index) === ';') {\n\t generatedLine++;\n\t index++;\n\t previousGeneratedColumn = 0;\n\t }\n\t else if (aStr.charAt(index) === ',') {\n\t index++;\n\t }\n\t else {\n\t mapping = new Mapping();\n\t mapping.generatedLine = generatedLine;\n\t\n\t // Because each offset is encoded relative to the previous one,\n\t // many segments often have the same encoding. We can exploit this\n\t // fact by caching the parsed variable length fields of each segment,\n\t // allowing us to avoid a second parse if we encounter the same\n\t // segment again.\n\t for (end = index; end < length; end++) {\n\t if (this._charIsMappingSeparator(aStr, end)) {\n\t break;\n\t }\n\t }\n\t str = aStr.slice(index, end);\n\t\n\t segment = cachedSegments[str];\n\t if (segment) {\n\t index += str.length;\n\t } else {\n\t segment = [];\n\t while (index < end) {\n\t base64VLQ.decode(aStr, index, temp);\n\t value = temp.value;\n\t index = temp.rest;\n\t segment.push(value);\n\t }\n\t\n\t if (segment.length === 2) {\n\t throw new Error('Found a source, but no line and column');\n\t }\n\t\n\t if (segment.length === 3) {\n\t throw new Error('Found a source and line, but no column');\n\t }\n\t\n\t cachedSegments[str] = segment;\n\t }\n\t\n\t // Generated column.\n\t mapping.generatedColumn = previousGeneratedColumn + segment[0];\n\t previousGeneratedColumn = mapping.generatedColumn;\n\t\n\t if (segment.length > 1) {\n\t // Original source.\n\t mapping.source = previousSource + segment[1];\n\t previousSource += segment[1];\n\t\n\t // Original line.\n\t mapping.originalLine = previousOriginalLine + segment[2];\n\t previousOriginalLine = mapping.originalLine;\n\t // Lines are stored 0-based\n\t mapping.originalLine += 1;\n\t\n\t // Original column.\n\t mapping.originalColumn = previousOriginalColumn + segment[3];\n\t previousOriginalColumn = mapping.originalColumn;\n\t\n\t if (segment.length > 4) {\n\t // Original name.\n\t mapping.name = previousName + segment[4];\n\t previousName += segment[4];\n\t }\n\t }\n\t\n\t generatedMappings.push(mapping);\n\t if (typeof mapping.originalLine === 'number') {\n\t originalMappings.push(mapping);\n\t }\n\t }\n\t }\n\t\n\t quickSort(generatedMappings, util.compareByGeneratedPositionsDeflated);\n\t this.__generatedMappings = generatedMappings;\n\t\n\t quickSort(originalMappings, util.compareByOriginalPositions);\n\t this.__originalMappings = originalMappings;\n\t };\n\t\n\t/**\n\t * Find the mapping that best matches the hypothetical \"needle\" mapping that\n\t * we are searching for in the given \"haystack\" of mappings.\n\t */\n\tBasicSourceMapConsumer.prototype._findMapping =\n\t function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName,\n\t aColumnName, aComparator, aBias) {\n\t // To return the position we are searching for, we must first find the\n\t // mapping for the given position and then return the opposite position it\n\t // points to. Because the mappings are sorted, we can use binary search to\n\t // find the best mapping.\n\t\n\t if (aNeedle[aLineName] <= 0) {\n\t throw new TypeError('Line must be greater than or equal to 1, got '\n\t + aNeedle[aLineName]);\n\t }\n\t if (aNeedle[aColumnName] < 0) {\n\t throw new TypeError('Column must be greater than or equal to 0, got '\n\t + aNeedle[aColumnName]);\n\t }\n\t\n\t return binarySearch.search(aNeedle, aMappings, aComparator, aBias);\n\t };\n\t\n\t/**\n\t * Compute the last column for each generated mapping. The last column is\n\t * inclusive.\n\t */\n\tBasicSourceMapConsumer.prototype.computeColumnSpans =\n\t function SourceMapConsumer_computeColumnSpans() {\n\t for (var index = 0; index < this._generatedMappings.length; ++index) {\n\t var mapping = this._generatedMappings[index];\n\t\n\t // Mappings do not contain a field for the last generated columnt. We\n\t // can come up with an optimistic estimate, however, by assuming that\n\t // mappings are contiguous (i.e. given two consecutive mappings, the\n\t // first mapping ends where the second one starts).\n\t if (index + 1 < this._generatedMappings.length) {\n\t var nextMapping = this._generatedMappings[index + 1];\n\t\n\t if (mapping.generatedLine === nextMapping.generatedLine) {\n\t mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1;\n\t continue;\n\t }\n\t }\n\t\n\t // The last mapping for each line spans the entire line.\n\t mapping.lastGeneratedColumn = Infinity;\n\t }\n\t };\n\t\n\t/**\n\t * Returns the original source, line, and column information for the generated\n\t * source's line and column positions provided. The only argument is an object\n\t * with the following properties:\n\t *\n\t * - line: The line number in the generated source. The line number\n\t * is 1-based.\n\t * - column: The column number in the generated source. The column\n\t * number is 0-based.\n\t * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or\n\t * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the\n\t * closest element that is smaller than or greater than the one we are\n\t * searching for, respectively, if the exact element cannot be found.\n\t * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.\n\t *\n\t * and an object is returned with the following properties:\n\t *\n\t * - source: The original source file, or null.\n\t * - line: The line number in the original source, or null. The\n\t * line number is 1-based.\n\t * - column: The column number in the original source, or null. The\n\t * column number is 0-based.\n\t * - name: The original identifier, or null.\n\t */\n\tBasicSourceMapConsumer.prototype.originalPositionFor =\n\t function SourceMapConsumer_originalPositionFor(aArgs) {\n\t var needle = {\n\t generatedLine: util.getArg(aArgs, 'line'),\n\t generatedColumn: util.getArg(aArgs, 'column')\n\t };\n\t\n\t var index = this._findMapping(\n\t needle,\n\t this._generatedMappings,\n\t \"generatedLine\",\n\t \"generatedColumn\",\n\t util.compareByGeneratedPositionsDeflated,\n\t util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)\n\t );\n\t\n\t if (index >= 0) {\n\t var mapping = this._generatedMappings[index];\n\t\n\t if (mapping.generatedLine === needle.generatedLine) {\n\t var source = util.getArg(mapping, 'source', null);\n\t if (source !== null) {\n\t source = this._sources.at(source);\n\t source = util.computeSourceURL(this.sourceRoot, source, this._sourceMapURL);\n\t }\n\t var name = util.getArg(mapping, 'name', null);\n\t if (name !== null) {\n\t name = this._names.at(name);\n\t }\n\t return {\n\t source: source,\n\t line: util.getArg(mapping, 'originalLine', null),\n\t column: util.getArg(mapping, 'originalColumn', null),\n\t name: name\n\t };\n\t }\n\t }\n\t\n\t return {\n\t source: null,\n\t line: null,\n\t column: null,\n\t name: null\n\t };\n\t };\n\t\n\t/**\n\t * Return true if we have the source content for every source in the source\n\t * map, false otherwise.\n\t */\n\tBasicSourceMapConsumer.prototype.hasContentsOfAllSources =\n\t function BasicSourceMapConsumer_hasContentsOfAllSources() {\n\t if (!this.sourcesContent) {\n\t return false;\n\t }\n\t return this.sourcesContent.length >= this._sources.size() &&\n\t !this.sourcesContent.some(function (sc) { return sc == null; });\n\t };\n\t\n\t/**\n\t * Returns the original source content. The only argument is the url of the\n\t * original source file. Returns null if no original source content is\n\t * available.\n\t */\n\tBasicSourceMapConsumer.prototype.sourceContentFor =\n\t function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {\n\t if (!this.sourcesContent) {\n\t return null;\n\t }\n\t\n\t var index = this._findSourceIndex(aSource);\n\t if (index >= 0) {\n\t return this.sourcesContent[index];\n\t }\n\t\n\t var relativeSource = aSource;\n\t if (this.sourceRoot != null) {\n\t relativeSource = util.relative(this.sourceRoot, relativeSource);\n\t }\n\t\n\t var url;\n\t if (this.sourceRoot != null\n\t && (url = util.urlParse(this.sourceRoot))) {\n\t // XXX: file:// URIs and absolute paths lead to unexpected behavior for\n\t // many users. We can help them out when they expect file:// URIs to\n\t // behave like it would if they were running a local HTTP server. See\n\t // https://bugzilla.mozilla.org/show_bug.cgi?id=885597.\n\t var fileUriAbsPath = relativeSource.replace(/^file:\\/\\//, \"\");\n\t if (url.scheme == \"file\"\n\t && this._sources.has(fileUriAbsPath)) {\n\t return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)]\n\t }\n\t\n\t if ((!url.path || url.path == \"/\")\n\t && this._sources.has(\"/\" + relativeSource)) {\n\t return this.sourcesContent[this._sources.indexOf(\"/\" + relativeSource)];\n\t }\n\t }\n\t\n\t // This function is used recursively from\n\t // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we\n\t // don't want to throw if we can't find the source - we just want to\n\t // return null, so we provide a flag to exit gracefully.\n\t if (nullOnMissing) {\n\t return null;\n\t }\n\t else {\n\t throw new Error('\"' + relativeSource + '\" is not in the SourceMap.');\n\t }\n\t };\n\t\n\t/**\n\t * Returns the generated line and column information for the original source,\n\t * line, and column positions provided. The only argument is an object with\n\t * the following properties:\n\t *\n\t * - source: The filename of the original source.\n\t * - line: The line number in the original source. The line number\n\t * is 1-based.\n\t * - column: The column number in the original source. The column\n\t * number is 0-based.\n\t * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or\n\t * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the\n\t * closest element that is smaller than or greater than the one we are\n\t * searching for, respectively, if the exact element cannot be found.\n\t * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.\n\t *\n\t * and an object is returned with the following properties:\n\t *\n\t * - line: The line number in the generated source, or null. The\n\t * line number is 1-based.\n\t * - column: The column number in the generated source, or null.\n\t * The column number is 0-based.\n\t */\n\tBasicSourceMapConsumer.prototype.generatedPositionFor =\n\t function SourceMapConsumer_generatedPositionFor(aArgs) {\n\t var source = util.getArg(aArgs, 'source');\n\t source = this._findSourceIndex(source);\n\t if (source < 0) {\n\t return {\n\t line: null,\n\t column: null,\n\t lastColumn: null\n\t };\n\t }\n\t\n\t var needle = {\n\t source: source,\n\t originalLine: util.getArg(aArgs, 'line'),\n\t originalColumn: util.getArg(aArgs, 'column')\n\t };\n\t\n\t var index = this._findMapping(\n\t needle,\n\t this._originalMappings,\n\t \"originalLine\",\n\t \"originalColumn\",\n\t util.compareByOriginalPositions,\n\t util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)\n\t );\n\t\n\t if (index >= 0) {\n\t var mapping = this._originalMappings[index];\n\t\n\t if (mapping.source === needle.source) {\n\t return {\n\t line: util.getArg(mapping, 'generatedLine', null),\n\t column: util.getArg(mapping, 'generatedColumn', null),\n\t lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)\n\t };\n\t }\n\t }\n\t\n\t return {\n\t line: null,\n\t column: null,\n\t lastColumn: null\n\t };\n\t };\n\t\n\texports.BasicSourceMapConsumer = BasicSourceMapConsumer;\n\t\n\t/**\n\t * An IndexedSourceMapConsumer instance represents a parsed source map which\n\t * we can query for information. It differs from BasicSourceMapConsumer in\n\t * that it takes \"indexed\" source maps (i.e. ones with a \"sections\" field) as\n\t * input.\n\t *\n\t * The first parameter is a raw source map (either as a JSON string, or already\n\t * parsed to an object). According to the spec for indexed source maps, they\n\t * have the following attributes:\n\t *\n\t * - version: Which version of the source map spec this map is following.\n\t * - file: Optional. The generated file this source map is associated with.\n\t * - sections: A list of section definitions.\n\t *\n\t * Each value under the \"sections\" field has two fields:\n\t * - offset: The offset into the original specified at which this section\n\t * begins to apply, defined as an object with a \"line\" and \"column\"\n\t * field.\n\t * - map: A source map definition. This source map could also be indexed,\n\t * but doesn't have to be.\n\t *\n\t * Instead of the \"map\" field, it's also possible to have a \"url\" field\n\t * specifying a URL to retrieve a source map from, but that's currently\n\t * unsupported.\n\t *\n\t * Here's an example source map, taken from the source map spec[0], but\n\t * modified to omit a section which uses the \"url\" field.\n\t *\n\t * {\n\t * version : 3,\n\t * file: \"app.js\",\n\t * sections: [{\n\t * offset: {line:100, column:10},\n\t * map: {\n\t * version : 3,\n\t * file: \"section.js\",\n\t * sources: [\"foo.js\", \"bar.js\"],\n\t * names: [\"src\", \"maps\", \"are\", \"fun\"],\n\t * mappings: \"AAAA,E;;ABCDE;\"\n\t * }\n\t * }],\n\t * }\n\t *\n\t * The second parameter, if given, is a string whose value is the URL\n\t * at which the source map was found. This URL is used to compute the\n\t * sources array.\n\t *\n\t * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt\n\t */\n\tfunction IndexedSourceMapConsumer(aSourceMap, aSourceMapURL) {\n\t var sourceMap = aSourceMap;\n\t if (typeof aSourceMap === 'string') {\n\t sourceMap = util.parseSourceMapInput(aSourceMap);\n\t }\n\t\n\t var version = util.getArg(sourceMap, 'version');\n\t var sections = util.getArg(sourceMap, 'sections');\n\t\n\t if (version != this._version) {\n\t throw new Error('Unsupported version: ' + version);\n\t }\n\t\n\t this._sources = new ArraySet();\n\t this._names = new ArraySet();\n\t\n\t var lastOffset = {\n\t line: -1,\n\t column: 0\n\t };\n\t this._sections = sections.map(function (s) {\n\t if (s.url) {\n\t // The url field will require support for asynchronicity.\n\t // See https://github.com/mozilla/source-map/issues/16\n\t throw new Error('Support for url field in sections not implemented.');\n\t }\n\t var offset = util.getArg(s, 'offset');\n\t var offsetLine = util.getArg(offset, 'line');\n\t var offsetColumn = util.getArg(offset, 'column');\n\t\n\t if (offsetLine < lastOffset.line ||\n\t (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) {\n\t throw new Error('Section offsets must be ordered and non-overlapping.');\n\t }\n\t lastOffset = offset;\n\t\n\t return {\n\t generatedOffset: {\n\t // The offset fields are 0-based, but we use 1-based indices when\n\t // encoding/decoding from VLQ.\n\t generatedLine: offsetLine + 1,\n\t generatedColumn: offsetColumn + 1\n\t },\n\t consumer: new SourceMapConsumer(util.getArg(s, 'map'), aSourceMapURL)\n\t }\n\t });\n\t}\n\t\n\tIndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);\n\tIndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer;\n\t\n\t/**\n\t * The version of the source mapping spec that we are consuming.\n\t */\n\tIndexedSourceMapConsumer.prototype._version = 3;\n\t\n\t/**\n\t * The list of original sources.\n\t */\n\tObject.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', {\n\t get: function () {\n\t var sources = [];\n\t for (var i = 0; i < this._sections.length; i++) {\n\t for (var j = 0; j < this._sections[i].consumer.sources.length; j++) {\n\t sources.push(this._sections[i].consumer.sources[j]);\n\t }\n\t }\n\t return sources;\n\t }\n\t});\n\t\n\t/**\n\t * Returns the original source, line, and column information for the generated\n\t * source's line and column positions provided. The only argument is an object\n\t * with the following properties:\n\t *\n\t * - line: The line number in the generated source. The line number\n\t * is 1-based.\n\t * - column: The column number in the generated source. The column\n\t * number is 0-based.\n\t *\n\t * and an object is returned with the following properties:\n\t *\n\t * - source: The original source file, or null.\n\t * - line: The line number in the original source, or null. The\n\t * line number is 1-based.\n\t * - column: The column number in the original source, or null. The\n\t * column number is 0-based.\n\t * - name: The original identifier, or null.\n\t */\n\tIndexedSourceMapConsumer.prototype.originalPositionFor =\n\t function IndexedSourceMapConsumer_originalPositionFor(aArgs) {\n\t var needle = {\n\t generatedLine: util.getArg(aArgs, 'line'),\n\t generatedColumn: util.getArg(aArgs, 'column')\n\t };\n\t\n\t // Find the section containing the generated position we're trying to map\n\t // to an original position.\n\t var sectionIndex = binarySearch.search(needle, this._sections,\n\t function(needle, section) {\n\t var cmp = needle.generatedLine - section.generatedOffset.generatedLine;\n\t if (cmp) {\n\t return cmp;\n\t }\n\t\n\t return (needle.generatedColumn -\n\t section.generatedOffset.generatedColumn);\n\t });\n\t var section = this._sections[sectionIndex];\n\t\n\t if (!section) {\n\t return {\n\t source: null,\n\t line: null,\n\t column: null,\n\t name: null\n\t };\n\t }\n\t\n\t return section.consumer.originalPositionFor({\n\t line: needle.generatedLine -\n\t (section.generatedOffset.generatedLine - 1),\n\t column: needle.generatedColumn -\n\t (section.generatedOffset.generatedLine === needle.generatedLine\n\t ? section.generatedOffset.generatedColumn - 1\n\t : 0),\n\t bias: aArgs.bias\n\t });\n\t };\n\t\n\t/**\n\t * Return true if we have the source content for every source in the source\n\t * map, false otherwise.\n\t */\n\tIndexedSourceMapConsumer.prototype.hasContentsOfAllSources =\n\t function IndexedSourceMapConsumer_hasContentsOfAllSources() {\n\t return this._sections.every(function (s) {\n\t return s.consumer.hasContentsOfAllSources();\n\t });\n\t };\n\t\n\t/**\n\t * Returns the original source content. The only argument is the url of the\n\t * original source file. Returns null if no original source content is\n\t * available.\n\t */\n\tIndexedSourceMapConsumer.prototype.sourceContentFor =\n\t function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {\n\t for (var i = 0; i < this._sections.length; i++) {\n\t var section = this._sections[i];\n\t\n\t var content = section.consumer.sourceContentFor(aSource, true);\n\t if (content) {\n\t return content;\n\t }\n\t }\n\t if (nullOnMissing) {\n\t return null;\n\t }\n\t else {\n\t throw new Error('\"' + aSource + '\" is not in the SourceMap.');\n\t }\n\t };\n\t\n\t/**\n\t * Returns the generated line and column information for the original source,\n\t * line, and column positions provided. The only argument is an object with\n\t * the following properties:\n\t *\n\t * - source: The filename of the original source.\n\t * - line: The line number in the original source. The line number\n\t * is 1-based.\n\t * - column: The column number in the original source. The column\n\t * number is 0-based.\n\t *\n\t * and an object is returned with the following properties:\n\t *\n\t * - line: The line number in the generated source, or null. The\n\t * line number is 1-based. \n\t * - column: The column number in the generated source, or null.\n\t * The column number is 0-based.\n\t */\n\tIndexedSourceMapConsumer.prototype.generatedPositionFor =\n\t function IndexedSourceMapConsumer_generatedPositionFor(aArgs) {\n\t for (var i = 0; i < this._sections.length; i++) {\n\t var section = this._sections[i];\n\t\n\t // Only consider this section if the requested source is in the list of\n\t // sources of the consumer.\n\t if (section.consumer._findSourceIndex(util.getArg(aArgs, 'source')) === -1) {\n\t continue;\n\t }\n\t var generatedPosition = section.consumer.generatedPositionFor(aArgs);\n\t if (generatedPosition) {\n\t var ret = {\n\t line: generatedPosition.line +\n\t (section.generatedOffset.generatedLine - 1),\n\t column: generatedPosition.column +\n\t (section.generatedOffset.generatedLine === generatedPosition.line\n\t ? section.generatedOffset.generatedColumn - 1\n\t : 0)\n\t };\n\t return ret;\n\t }\n\t }\n\t\n\t return {\n\t line: null,\n\t column: null\n\t };\n\t };\n\t\n\t/**\n\t * Parse the mappings in a string in to a data structure which we can easily\n\t * query (the ordered arrays in the `this.__generatedMappings` and\n\t * `this.__originalMappings` properties).\n\t */\n\tIndexedSourceMapConsumer.prototype._parseMappings =\n\t function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) {\n\t this.__generatedMappings = [];\n\t this.__originalMappings = [];\n\t for (var i = 0; i < this._sections.length; i++) {\n\t var section = this._sections[i];\n\t var sectionMappings = section.consumer._generatedMappings;\n\t for (var j = 0; j < sectionMappings.length; j++) {\n\t var mapping = sectionMappings[j];\n\t\n\t var source = section.consumer._sources.at(mapping.source);\n\t source = util.computeSourceURL(section.consumer.sourceRoot, source, this._sourceMapURL);\n\t this._sources.add(source);\n\t source = this._sources.indexOf(source);\n\t\n\t var name = null;\n\t if (mapping.name) {\n\t name = section.consumer._names.at(mapping.name);\n\t this._names.add(name);\n\t name = this._names.indexOf(name);\n\t }\n\t\n\t // The mappings coming from the consumer for the section have\n\t // generated positions relative to the start of the section, so we\n\t // need to offset them to be relative to the start of the concatenated\n\t // generated file.\n\t var adjustedMapping = {\n\t source: source,\n\t generatedLine: mapping.generatedLine +\n\t (section.generatedOffset.generatedLine - 1),\n\t generatedColumn: mapping.generatedColumn +\n\t (section.generatedOffset.generatedLine === mapping.generatedLine\n\t ? section.generatedOffset.generatedColumn - 1\n\t : 0),\n\t originalLine: mapping.originalLine,\n\t originalColumn: mapping.originalColumn,\n\t name: name\n\t };\n\t\n\t this.__generatedMappings.push(adjustedMapping);\n\t if (typeof adjustedMapping.originalLine === 'number') {\n\t this.__originalMappings.push(adjustedMapping);\n\t }\n\t }\n\t }\n\t\n\t quickSort(this.__generatedMappings, util.compareByGeneratedPositionsDeflated);\n\t quickSort(this.__originalMappings, util.compareByOriginalPositions);\n\t };\n\t\n\texports.IndexedSourceMapConsumer = IndexedSourceMapConsumer;\n\n\n/***/ }),\n/* 8 */\n/***/ (function(module, exports) {\n\n\t/* -*- Mode: js; js-indent-level: 2; -*- */\n\t/*\n\t * Copyright 2011 Mozilla Foundation and contributors\n\t * Licensed under the New BSD license. See LICENSE or:\n\t * http://opensource.org/licenses/BSD-3-Clause\n\t */\n\t\n\texports.GREATEST_LOWER_BOUND = 1;\n\texports.LEAST_UPPER_BOUND = 2;\n\t\n\t/**\n\t * Recursive implementation of binary search.\n\t *\n\t * @param aLow Indices here and lower do not contain the needle.\n\t * @param aHigh Indices here and higher do not contain the needle.\n\t * @param aNeedle The element being searched for.\n\t * @param aHaystack The non-empty array being searched.\n\t * @param aCompare Function which takes two elements and returns -1, 0, or 1.\n\t * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or\n\t * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the\n\t * closest element that is smaller than or greater than the one we are\n\t * searching for, respectively, if the exact element cannot be found.\n\t */\n\tfunction recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) {\n\t // This function terminates when one of the following is true:\n\t //\n\t // 1. We find the exact element we are looking for.\n\t //\n\t // 2. We did not find the exact element, but we can return the index of\n\t // the next-closest element.\n\t //\n\t // 3. We did not find the exact element, and there is no next-closest\n\t // element than the one we are searching for, so we return -1.\n\t var mid = Math.floor((aHigh - aLow) / 2) + aLow;\n\t var cmp = aCompare(aNeedle, aHaystack[mid], true);\n\t if (cmp === 0) {\n\t // Found the element we are looking for.\n\t return mid;\n\t }\n\t else if (cmp > 0) {\n\t // Our needle is greater than aHaystack[mid].\n\t if (aHigh - mid > 1) {\n\t // The element is in the upper half.\n\t return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias);\n\t }\n\t\n\t // The exact needle element was not found in this haystack. Determine if\n\t // we are in termination case (3) or (2) and return the appropriate thing.\n\t if (aBias == exports.LEAST_UPPER_BOUND) {\n\t return aHigh < aHaystack.length ? aHigh : -1;\n\t } else {\n\t return mid;\n\t }\n\t }\n\t else {\n\t // Our needle is less than aHaystack[mid].\n\t if (mid - aLow > 1) {\n\t // The element is in the lower half.\n\t return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias);\n\t }\n\t\n\t // we are in termination case (3) or (2) and return the appropriate thing.\n\t if (aBias == exports.LEAST_UPPER_BOUND) {\n\t return mid;\n\t } else {\n\t return aLow < 0 ? -1 : aLow;\n\t }\n\t }\n\t}\n\t\n\t/**\n\t * This is an implementation of binary search which will always try and return\n\t * the index of the closest element if there is no exact hit. This is because\n\t * mappings between original and generated line/col pairs are single points,\n\t * and there is an implicit region between each of them, so a miss just means\n\t * that you aren't on the very start of a region.\n\t *\n\t * @param aNeedle The element you are looking for.\n\t * @param aHaystack The array that is being searched.\n\t * @param aCompare A function which takes the needle and an element in the\n\t * array and returns -1, 0, or 1 depending on whether the needle is less\n\t * than, equal to, or greater than the element, respectively.\n\t * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or\n\t * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the\n\t * closest element that is smaller than or greater than the one we are\n\t * searching for, respectively, if the exact element cannot be found.\n\t * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'.\n\t */\n\texports.search = function search(aNeedle, aHaystack, aCompare, aBias) {\n\t if (aHaystack.length === 0) {\n\t return -1;\n\t }\n\t\n\t var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack,\n\t aCompare, aBias || exports.GREATEST_LOWER_BOUND);\n\t if (index < 0) {\n\t return -1;\n\t }\n\t\n\t // We have found either the exact element, or the next-closest element than\n\t // the one we are searching for. However, there may be more than one such\n\t // element. Make sure we always return the smallest of these.\n\t while (index - 1 >= 0) {\n\t if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) {\n\t break;\n\t }\n\t --index;\n\t }\n\t\n\t return index;\n\t};\n\n\n/***/ }),\n/* 9 */\n/***/ (function(module, exports) {\n\n\t/* -*- Mode: js; js-indent-level: 2; -*- */\n\t/*\n\t * Copyright 2011 Mozilla Foundation and contributors\n\t * Licensed under the New BSD license. See LICENSE or:\n\t * http://opensource.org/licenses/BSD-3-Clause\n\t */\n\t\n\t// It turns out that some (most?) JavaScript engines don't self-host\n\t// `Array.prototype.sort`. This makes sense because C++ will likely remain\n\t// faster than JS when doing raw CPU-intensive sorting. However, when using a\n\t// custom comparator function, calling back and forth between the VM's C++ and\n\t// JIT'd JS is rather slow *and* loses JIT type information, resulting in\n\t// worse generated code for the comparator function than would be optimal. In\n\t// fact, when sorting with a comparator, these costs outweigh the benefits of\n\t// sorting in C++. By using our own JS-implemented Quick Sort (below), we get\n\t// a ~3500ms mean speed-up in `bench/bench.html`.\n\t\n\t/**\n\t * Swap the elements indexed by `x` and `y` in the array `ary`.\n\t *\n\t * @param {Array} ary\n\t * The array.\n\t * @param {Number} x\n\t * The index of the first item.\n\t * @param {Number} y\n\t * The index of the second item.\n\t */\n\tfunction swap(ary, x, y) {\n\t var temp = ary[x];\n\t ary[x] = ary[y];\n\t ary[y] = temp;\n\t}\n\t\n\t/**\n\t * Returns a random integer within the range `low .. high` inclusive.\n\t *\n\t * @param {Number} low\n\t * The lower bound on the range.\n\t * @param {Number} high\n\t * The upper bound on the range.\n\t */\n\tfunction randomIntInRange(low, high) {\n\t return Math.round(low + (Math.random() * (high - low)));\n\t}\n\t\n\t/**\n\t * The Quick Sort algorithm.\n\t *\n\t * @param {Array} ary\n\t * An array to sort.\n\t * @param {function} comparator\n\t * Function to use to compare two items.\n\t * @param {Number} p\n\t * Start index of the array\n\t * @param {Number} r\n\t * End index of the array\n\t */\n\tfunction doQuickSort(ary, comparator, p, r) {\n\t // If our lower bound is less than our upper bound, we (1) partition the\n\t // array into two pieces and (2) recurse on each half. If it is not, this is\n\t // the empty array and our base case.\n\t\n\t if (p < r) {\n\t // (1) Partitioning.\n\t //\n\t // The partitioning chooses a pivot between `p` and `r` and moves all\n\t // elements that are less than or equal to the pivot to the before it, and\n\t // all the elements that are greater than it after it. The effect is that\n\t // once partition is done, the pivot is in the exact place it will be when\n\t // the array is put in sorted order, and it will not need to be moved\n\t // again. This runs in O(n) time.\n\t\n\t // Always choose a random pivot so that an input array which is reverse\n\t // sorted does not cause O(n^2) running time.\n\t var pivotIndex = randomIntInRange(p, r);\n\t var i = p - 1;\n\t\n\t swap(ary, pivotIndex, r);\n\t var pivot = ary[r];\n\t\n\t // Immediately after `j` is incremented in this loop, the following hold\n\t // true:\n\t //\n\t // * Every element in `ary[p .. i]` is less than or equal to the pivot.\n\t //\n\t // * Every element in `ary[i+1 .. j-1]` is greater than the pivot.\n\t for (var j = p; j < r; j++) {\n\t if (comparator(ary[j], pivot) <= 0) {\n\t i += 1;\n\t swap(ary, i, j);\n\t }\n\t }\n\t\n\t swap(ary, i + 1, j);\n\t var q = i + 1;\n\t\n\t // (2) Recurse on each half.\n\t\n\t doQuickSort(ary, comparator, p, q - 1);\n\t doQuickSort(ary, comparator, q + 1, r);\n\t }\n\t}\n\t\n\t/**\n\t * Sort the given array in-place with the given comparator function.\n\t *\n\t * @param {Array} ary\n\t * An array to sort.\n\t * @param {function} comparator\n\t * Function to use to compare two items.\n\t */\n\texports.quickSort = function (ary, comparator) {\n\t doQuickSort(ary, comparator, 0, ary.length - 1);\n\t};\n\n\n/***/ }),\n/* 10 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\t/* -*- Mode: js; js-indent-level: 2; -*- */\n\t/*\n\t * Copyright 2011 Mozilla Foundation and contributors\n\t * Licensed under the New BSD license. See LICENSE or:\n\t * http://opensource.org/licenses/BSD-3-Clause\n\t */\n\t\n\tvar SourceMapGenerator = __webpack_require__(1).SourceMapGenerator;\n\tvar util = __webpack_require__(4);\n\t\n\t// Matches a Windows-style `\\r\\n` newline or a `\\n` newline used by all other\n\t// operating systems these days (capturing the result).\n\tvar REGEX_NEWLINE = /(\\r?\\n)/;\n\t\n\t// Newline character code for charCodeAt() comparisons\n\tvar NEWLINE_CODE = 10;\n\t\n\t// Private symbol for identifying `SourceNode`s when multiple versions of\n\t// the source-map library are loaded. This MUST NOT CHANGE across\n\t// versions!\n\tvar isSourceNode = \"$$$isSourceNode$$$\";\n\t\n\t/**\n\t * SourceNodes provide a way to abstract over interpolating/concatenating\n\t * snippets of generated JavaScript source code while maintaining the line and\n\t * column information associated with the original source code.\n\t *\n\t * @param aLine The original line number.\n\t * @param aColumn The original column number.\n\t * @param aSource The original source's filename.\n\t * @param aChunks Optional. An array of strings which are snippets of\n\t * generated JS, or other SourceNodes.\n\t * @param aName The original identifier.\n\t */\n\tfunction SourceNode(aLine, aColumn, aSource, aChunks, aName) {\n\t this.children = [];\n\t this.sourceContents = {};\n\t this.line = aLine == null ? null : aLine;\n\t this.column = aColumn == null ? null : aColumn;\n\t this.source = aSource == null ? null : aSource;\n\t this.name = aName == null ? null : aName;\n\t this[isSourceNode] = true;\n\t if (aChunks != null) this.add(aChunks);\n\t}\n\t\n\t/**\n\t * Creates a SourceNode from generated code and a SourceMapConsumer.\n\t *\n\t * @param aGeneratedCode The generated code\n\t * @param aSourceMapConsumer The SourceMap for the generated code\n\t * @param aRelativePath Optional. The path that relative sources in the\n\t * SourceMapConsumer should be relative to.\n\t */\n\tSourceNode.fromStringWithSourceMap =\n\t function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) {\n\t // The SourceNode we want to fill with the generated code\n\t // and the SourceMap\n\t var node = new SourceNode();\n\t\n\t // All even indices of this array are one line of the generated code,\n\t // while all odd indices are the newlines between two adjacent lines\n\t // (since `REGEX_NEWLINE` captures its match).\n\t // Processed fragments are accessed by calling `shiftNextLine`.\n\t var remainingLines = aGeneratedCode.split(REGEX_NEWLINE);\n\t var remainingLinesIndex = 0;\n\t var shiftNextLine = function() {\n\t var lineContents = getNextLine();\n\t // The last line of a file might not have a newline.\n\t var newLine = getNextLine() || \"\";\n\t return lineContents + newLine;\n\t\n\t function getNextLine() {\n\t return remainingLinesIndex < remainingLines.length ?\n\t remainingLines[remainingLinesIndex++] : undefined;\n\t }\n\t };\n\t\n\t // We need to remember the position of \"remainingLines\"\n\t var lastGeneratedLine = 1, lastGeneratedColumn = 0;\n\t\n\t // The generate SourceNodes we need a code range.\n\t // To extract it current and last mapping is used.\n\t // Here we store the last mapping.\n\t var lastMapping = null;\n\t\n\t aSourceMapConsumer.eachMapping(function (mapping) {\n\t if (lastMapping !== null) {\n\t // We add the code from \"lastMapping\" to \"mapping\":\n\t // First check if there is a new line in between.\n\t if (lastGeneratedLine < mapping.generatedLine) {\n\t // Associate first line with \"lastMapping\"\n\t addMappingWithCode(lastMapping, shiftNextLine());\n\t lastGeneratedLine++;\n\t lastGeneratedColumn = 0;\n\t // The remaining code is added without mapping\n\t } else {\n\t // There is no new line in between.\n\t // Associate the code between \"lastGeneratedColumn\" and\n\t // \"mapping.generatedColumn\" with \"lastMapping\"\n\t var nextLine = remainingLines[remainingLinesIndex] || '';\n\t var code = nextLine.substr(0, mapping.generatedColumn -\n\t lastGeneratedColumn);\n\t remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn -\n\t lastGeneratedColumn);\n\t lastGeneratedColumn = mapping.generatedColumn;\n\t addMappingWithCode(lastMapping, code);\n\t // No more remaining code, continue\n\t lastMapping = mapping;\n\t return;\n\t }\n\t }\n\t // We add the generated code until the first mapping\n\t // to the SourceNode without any mapping.\n\t // Each line is added as separate string.\n\t while (lastGeneratedLine < mapping.generatedLine) {\n\t node.add(shiftNextLine());\n\t lastGeneratedLine++;\n\t }\n\t if (lastGeneratedColumn < mapping.generatedColumn) {\n\t var nextLine = remainingLines[remainingLinesIndex] || '';\n\t node.add(nextLine.substr(0, mapping.generatedColumn));\n\t remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn);\n\t lastGeneratedColumn = mapping.generatedColumn;\n\t }\n\t lastMapping = mapping;\n\t }, this);\n\t // We have processed all mappings.\n\t if (remainingLinesIndex < remainingLines.length) {\n\t if (lastMapping) {\n\t // Associate the remaining code in the current line with \"lastMapping\"\n\t addMappingWithCode(lastMapping, shiftNextLine());\n\t }\n\t // and add the remaining lines without any mapping\n\t node.add(remainingLines.splice(remainingLinesIndex).join(\"\"));\n\t }\n\t\n\t // Copy sourcesContent into SourceNode\n\t aSourceMapConsumer.sources.forEach(function (sourceFile) {\n\t var content = aSourceMapConsumer.sourceContentFor(sourceFile);\n\t if (content != null) {\n\t if (aRelativePath != null) {\n\t sourceFile = util.join(aRelativePath, sourceFile);\n\t }\n\t node.setSourceContent(sourceFile, content);\n\t }\n\t });\n\t\n\t return node;\n\t\n\t function addMappingWithCode(mapping, code) {\n\t if (mapping === null || mapping.source === undefined) {\n\t node.add(code);\n\t } else {\n\t var source = aRelativePath\n\t ? util.join(aRelativePath, mapping.source)\n\t : mapping.source;\n\t node.add(new SourceNode(mapping.originalLine,\n\t mapping.originalColumn,\n\t source,\n\t code,\n\t mapping.name));\n\t }\n\t }\n\t };\n\t\n\t/**\n\t * Add a chunk of generated JS to this source node.\n\t *\n\t * @param aChunk A string snippet of generated JS code, another instance of\n\t * SourceNode, or an array where each member is one of those things.\n\t */\n\tSourceNode.prototype.add = function SourceNode_add(aChunk) {\n\t if (Array.isArray(aChunk)) {\n\t aChunk.forEach(function (chunk) {\n\t this.add(chunk);\n\t }, this);\n\t }\n\t else if (aChunk[isSourceNode] || typeof aChunk === \"string\") {\n\t if (aChunk) {\n\t this.children.push(aChunk);\n\t }\n\t }\n\t else {\n\t throw new TypeError(\n\t \"Expected a SourceNode, string, or an array of SourceNodes and strings. Got \" + aChunk\n\t );\n\t }\n\t return this;\n\t};\n\t\n\t/**\n\t * Add a chunk of generated JS to the beginning of this source node.\n\t *\n\t * @param aChunk A string snippet of generated JS code, another instance of\n\t * SourceNode, or an array where each member is one of those things.\n\t */\n\tSourceNode.prototype.prepend = function SourceNode_prepend(aChunk) {\n\t if (Array.isArray(aChunk)) {\n\t for (var i = aChunk.length-1; i >= 0; i--) {\n\t this.prepend(aChunk[i]);\n\t }\n\t }\n\t else if (aChunk[isSourceNode] || typeof aChunk === \"string\") {\n\t this.children.unshift(aChunk);\n\t }\n\t else {\n\t throw new TypeError(\n\t \"Expected a SourceNode, string, or an array of SourceNodes and strings. Got \" + aChunk\n\t );\n\t }\n\t return this;\n\t};\n\t\n\t/**\n\t * Walk over the tree of JS snippets in this node and its children. The\n\t * walking function is called once for each snippet of JS and is passed that\n\t * snippet and the its original associated source's line/column location.\n\t *\n\t * @param aFn The traversal function.\n\t */\n\tSourceNode.prototype.walk = function SourceNode_walk(aFn) {\n\t var chunk;\n\t for (var i = 0, len = this.children.length; i < len; i++) {\n\t chunk = this.children[i];\n\t if (chunk[isSourceNode]) {\n\t chunk.walk(aFn);\n\t }\n\t else {\n\t if (chunk !== '') {\n\t aFn(chunk, { source: this.source,\n\t line: this.line,\n\t column: this.column,\n\t name: this.name });\n\t }\n\t }\n\t }\n\t};\n\t\n\t/**\n\t * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between\n\t * each of `this.children`.\n\t *\n\t * @param aSep The separator.\n\t */\n\tSourceNode.prototype.join = function SourceNode_join(aSep) {\n\t var newChildren;\n\t var i;\n\t var len = this.children.length;\n\t if (len > 0) {\n\t newChildren = [];\n\t for (i = 0; i < len-1; i++) {\n\t newChildren.push(this.children[i]);\n\t newChildren.push(aSep);\n\t }\n\t newChildren.push(this.children[i]);\n\t this.children = newChildren;\n\t }\n\t return this;\n\t};\n\t\n\t/**\n\t * Call String.prototype.replace on the very right-most source snippet. Useful\n\t * for trimming whitespace from the end of a source node, etc.\n\t *\n\t * @param aPattern The pattern to replace.\n\t * @param aReplacement The thing to replace the pattern with.\n\t */\n\tSourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) {\n\t var lastChild = this.children[this.children.length - 1];\n\t if (lastChild[isSourceNode]) {\n\t lastChild.replaceRight(aPattern, aReplacement);\n\t }\n\t else if (typeof lastChild === 'string') {\n\t this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement);\n\t }\n\t else {\n\t this.children.push(''.replace(aPattern, aReplacement));\n\t }\n\t return this;\n\t};\n\t\n\t/**\n\t * Set the source content for a source file. This will be added to the SourceMapGenerator\n\t * in the sourcesContent field.\n\t *\n\t * @param aSourceFile The filename of the source file\n\t * @param aSourceContent The content of the source file\n\t */\n\tSourceNode.prototype.setSourceContent =\n\t function SourceNode_setSourceContent(aSourceFile, aSourceContent) {\n\t this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent;\n\t };\n\t\n\t/**\n\t * Walk over the tree of SourceNodes. The walking function is called for each\n\t * source file content and is passed the filename and source content.\n\t *\n\t * @param aFn The traversal function.\n\t */\n\tSourceNode.prototype.walkSourceContents =\n\t function SourceNode_walkSourceContents(aFn) {\n\t for (var i = 0, len = this.children.length; i < len; i++) {\n\t if (this.children[i][isSourceNode]) {\n\t this.children[i].walkSourceContents(aFn);\n\t }\n\t }\n\t\n\t var sources = Object.keys(this.sourceContents);\n\t for (var i = 0, len = sources.length; i < len; i++) {\n\t aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]);\n\t }\n\t };\n\t\n\t/**\n\t * Return the string representation of this source node. Walks over the tree\n\t * and concatenates all the various snippets together to one string.\n\t */\n\tSourceNode.prototype.toString = function SourceNode_toString() {\n\t var str = \"\";\n\t this.walk(function (chunk) {\n\t str += chunk;\n\t });\n\t return str;\n\t};\n\t\n\t/**\n\t * Returns the string representation of this source node along with a source\n\t * map.\n\t */\n\tSourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) {\n\t var generated = {\n\t code: \"\",\n\t line: 1,\n\t column: 0\n\t };\n\t var map = new SourceMapGenerator(aArgs);\n\t var sourceMappingActive = false;\n\t var lastOriginalSource = null;\n\t var lastOriginalLine = null;\n\t var lastOriginalColumn = null;\n\t var lastOriginalName = null;\n\t this.walk(function (chunk, original) {\n\t generated.code += chunk;\n\t if (original.source !== null\n\t && original.line !== null\n\t && original.column !== null) {\n\t if(lastOriginalSource !== original.source\n\t || lastOriginalLine !== original.line\n\t || lastOriginalColumn !== original.column\n\t || lastOriginalName !== original.name) {\n\t map.addMapping({\n\t source: original.source,\n\t original: {\n\t line: original.line,\n\t column: original.column\n\t },\n\t generated: {\n\t line: generated.line,\n\t column: generated.column\n\t },\n\t name: original.name\n\t });\n\t }\n\t lastOriginalSource = original.source;\n\t lastOriginalLine = original.line;\n\t lastOriginalColumn = original.column;\n\t lastOriginalName = original.name;\n\t sourceMappingActive = true;\n\t } else if (sourceMappingActive) {\n\t map.addMapping({\n\t generated: {\n\t line: generated.line,\n\t column: generated.column\n\t }\n\t });\n\t lastOriginalSource = null;\n\t sourceMappingActive = false;\n\t }\n\t for (var idx = 0, length = chunk.length; idx < length; idx++) {\n\t if (chunk.charCodeAt(idx) === NEWLINE_CODE) {\n\t generated.line++;\n\t generated.column = 0;\n\t // Mappings end at eol\n\t if (idx + 1 === length) {\n\t lastOriginalSource = null;\n\t sourceMappingActive = false;\n\t } else if (sourceMappingActive) {\n\t map.addMapping({\n\t source: original.source,\n\t original: {\n\t line: original.line,\n\t column: original.column\n\t },\n\t generated: {\n\t line: generated.line,\n\t column: generated.column\n\t },\n\t name: original.name\n\t });\n\t }\n\t } else {\n\t generated.column++;\n\t }\n\t }\n\t });\n\t this.walkSourceContents(function (sourceFile, sourceContent) {\n\t map.setSourceContent(sourceFile, sourceContent);\n\t });\n\t\n\t return { code: generated.code, map: map };\n\t};\n\t\n\texports.SourceNode = SourceNode;\n\n\n/***/ })\n/******/ ])\n});\n;\n\n\n// WEBPACK FOOTER //\n// source-map.min.js"," \t// The module cache\n \tvar installedModules = {};\n\n \t// The require function\n \tfunction __webpack_require__(moduleId) {\n\n \t\t// Check if module is in cache\n \t\tif(installedModules[moduleId])\n \t\t\treturn installedModules[moduleId].exports;\n\n \t\t// Create a new module (and put it into the cache)\n \t\tvar module = installedModules[moduleId] = {\n \t\t\texports: {},\n \t\t\tid: moduleId,\n \t\t\tloaded: false\n \t\t};\n\n \t\t// Execute the module function\n \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n \t\t// Flag the module as loaded\n \t\tmodule.loaded = true;\n\n \t\t// Return the exports of the module\n \t\treturn module.exports;\n \t}\n\n\n \t// expose the modules object (__webpack_modules__)\n \t__webpack_require__.m = modules;\n\n \t// expose the module cache\n \t__webpack_require__.c = installedModules;\n\n \t// __webpack_public_path__\n \t__webpack_require__.p = \"\";\n\n \t// Load entry module and return exports\n \treturn __webpack_require__(0);\n\n\n\n// WEBPACK FOOTER //\n// webpack/bootstrap 0fd5815da764db5fb9fe","/*\n * Copyright 2009-2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE.txt or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\nexports.SourceMapGenerator = require('./lib/source-map-generator').SourceMapGenerator;\nexports.SourceMapConsumer = require('./lib/source-map-consumer').SourceMapConsumer;\nexports.SourceNode = require('./lib/source-node').SourceNode;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./source-map.js\n// module id = 0\n// module chunks = 0","/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\nvar base64VLQ = require('./base64-vlq');\nvar util = require('./util');\nvar ArraySet = require('./array-set').ArraySet;\nvar MappingList = require('./mapping-list').MappingList;\n\n/**\n * An instance of the SourceMapGenerator represents a source map which is\n * being built incrementally. You may pass an object with the following\n * properties:\n *\n * - file: The filename of the generated source.\n * - sourceRoot: A root for all relative URLs in this source map.\n */\nfunction SourceMapGenerator(aArgs) {\n if (!aArgs) {\n aArgs = {};\n }\n this._file = util.getArg(aArgs, 'file', null);\n this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null);\n this._skipValidation = util.getArg(aArgs, 'skipValidation', false);\n this._sources = new ArraySet();\n this._names = new ArraySet();\n this._mappings = new MappingList();\n this._sourcesContents = null;\n}\n\nSourceMapGenerator.prototype._version = 3;\n\n/**\n * Creates a new SourceMapGenerator based on a SourceMapConsumer\n *\n * @param aSourceMapConsumer The SourceMap.\n */\nSourceMapGenerator.fromSourceMap =\n function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) {\n var sourceRoot = aSourceMapConsumer.sourceRoot;\n var generator = new SourceMapGenerator({\n file: aSourceMapConsumer.file,\n sourceRoot: sourceRoot\n });\n aSourceMapConsumer.eachMapping(function (mapping) {\n var newMapping = {\n generated: {\n line: mapping.generatedLine,\n column: mapping.generatedColumn\n }\n };\n\n if (mapping.source != null) {\n newMapping.source = mapping.source;\n if (sourceRoot != null) {\n newMapping.source = util.relative(sourceRoot, newMapping.source);\n }\n\n newMapping.original = {\n line: mapping.originalLine,\n column: mapping.originalColumn\n };\n\n if (mapping.name != null) {\n newMapping.name = mapping.name;\n }\n }\n\n generator.addMapping(newMapping);\n });\n aSourceMapConsumer.sources.forEach(function (sourceFile) {\n var sourceRelative = sourceFile;\n if (sourceRoot !== null) {\n sourceRelative = util.relative(sourceRoot, sourceFile);\n }\n\n if (!generator._sources.has(sourceRelative)) {\n generator._sources.add(sourceRelative);\n }\n\n var content = aSourceMapConsumer.sourceContentFor(sourceFile);\n if (content != null) {\n generator.setSourceContent(sourceFile, content);\n }\n });\n return generator;\n };\n\n/**\n * Add a single mapping from original source line and column to the generated\n * source's line and column for this source map being created. The mapping\n * object should have the following properties:\n *\n * - generated: An object with the generated line and column positions.\n * - original: An object with the original line and column positions.\n * - source: The original source file (relative to the sourceRoot).\n * - name: An optional original token name for this mapping.\n */\nSourceMapGenerator.prototype.addMapping =\n function SourceMapGenerator_addMapping(aArgs) {\n var generated = util.getArg(aArgs, 'generated');\n var original = util.getArg(aArgs, 'original', null);\n var source = util.getArg(aArgs, 'source', null);\n var name = util.getArg(aArgs, 'name', null);\n\n if (!this._skipValidation) {\n this._validateMapping(generated, original, source, name);\n }\n\n if (source != null) {\n source = String(source);\n if (!this._sources.has(source)) {\n this._sources.add(source);\n }\n }\n\n if (name != null) {\n name = String(name);\n if (!this._names.has(name)) {\n this._names.add(name);\n }\n }\n\n this._mappings.add({\n generatedLine: generated.line,\n generatedColumn: generated.column,\n originalLine: original != null && original.line,\n originalColumn: original != null && original.column,\n source: source,\n name: name\n });\n };\n\n/**\n * Set the source content for a source file.\n */\nSourceMapGenerator.prototype.setSourceContent =\n function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) {\n var source = aSourceFile;\n if (this._sourceRoot != null) {\n source = util.relative(this._sourceRoot, source);\n }\n\n if (aSourceContent != null) {\n // Add the source content to the _sourcesContents map.\n // Create a new _sourcesContents map if the property is null.\n if (!this._sourcesContents) {\n this._sourcesContents = Object.create(null);\n }\n this._sourcesContents[util.toSetString(source)] = aSourceContent;\n } else if (this._sourcesContents) {\n // Remove the source file from the _sourcesContents map.\n // If the _sourcesContents map is empty, set the property to null.\n delete this._sourcesContents[util.toSetString(source)];\n if (Object.keys(this._sourcesContents).length === 0) {\n this._sourcesContents = null;\n }\n }\n };\n\n/**\n * Applies the mappings of a sub-source-map for a specific source file to the\n * source map being generated. Each mapping to the supplied source file is\n * rewritten using the supplied source map. Note: The resolution for the\n * resulting mappings is the minimium of this map and the supplied map.\n *\n * @param aSourceMapConsumer The source map to be applied.\n * @param aSourceFile Optional. The filename of the source file.\n * If omitted, SourceMapConsumer's file property will be used.\n * @param aSourceMapPath Optional. The dirname of the path to the source map\n * to be applied. If relative, it is relative to the SourceMapConsumer.\n * This parameter is needed when the two source maps aren't in the same\n * directory, and the source map to be applied contains relative source\n * paths. If so, those relative source paths need to be rewritten\n * relative to the SourceMapGenerator.\n */\nSourceMapGenerator.prototype.applySourceMap =\n function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) {\n var sourceFile = aSourceFile;\n // If aSourceFile is omitted, we will use the file property of the SourceMap\n if (aSourceFile == null) {\n if (aSourceMapConsumer.file == null) {\n throw new Error(\n 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' +\n 'or the source map\\'s \"file\" property. Both were omitted.'\n );\n }\n sourceFile = aSourceMapConsumer.file;\n }\n var sourceRoot = this._sourceRoot;\n // Make \"sourceFile\" relative if an absolute Url is passed.\n if (sourceRoot != null) {\n sourceFile = util.relative(sourceRoot, sourceFile);\n }\n // Applying the SourceMap can add and remove items from the sources and\n // the names array.\n var newSources = new ArraySet();\n var newNames = new ArraySet();\n\n // Find mappings for the \"sourceFile\"\n this._mappings.unsortedForEach(function (mapping) {\n if (mapping.source === sourceFile && mapping.originalLine != null) {\n // Check if it can be mapped by the source map, then update the mapping.\n var original = aSourceMapConsumer.originalPositionFor({\n line: mapping.originalLine,\n column: mapping.originalColumn\n });\n if (original.source != null) {\n // Copy mapping\n mapping.source = original.source;\n if (aSourceMapPath != null) {\n mapping.source = util.join(aSourceMapPath, mapping.source)\n }\n if (sourceRoot != null) {\n mapping.source = util.relative(sourceRoot, mapping.source);\n }\n mapping.originalLine = original.line;\n mapping.originalColumn = original.column;\n if (original.name != null) {\n mapping.name = original.name;\n }\n }\n }\n\n var source = mapping.source;\n if (source != null && !newSources.has(source)) {\n newSources.add(source);\n }\n\n var name = mapping.name;\n if (name != null && !newNames.has(name)) {\n newNames.add(name);\n }\n\n }, this);\n this._sources = newSources;\n this._names = newNames;\n\n // Copy sourcesContents of applied map.\n aSourceMapConsumer.sources.forEach(function (sourceFile) {\n var content = aSourceMapConsumer.sourceContentFor(sourceFile);\n if (content != null) {\n if (aSourceMapPath != null) {\n sourceFile = util.join(aSourceMapPath, sourceFile);\n }\n if (sourceRoot != null) {\n sourceFile = util.relative(sourceRoot, sourceFile);\n }\n this.setSourceContent(sourceFile, content);\n }\n }, this);\n };\n\n/**\n * A mapping can have one of the three levels of data:\n *\n * 1. Just the generated position.\n * 2. The Generated position, original position, and original source.\n * 3. Generated and original position, original source, as well as a name\n * token.\n *\n * To maintain consistency, we validate that any new mapping being added falls\n * in to one of these categories.\n */\nSourceMapGenerator.prototype._validateMapping =\n function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource,\n aName) {\n // When aOriginal is truthy but has empty values for .line and .column,\n // it is most likely a programmer error. In this case we throw a very\n // specific error message to try to guide them the right way.\n // For example: https://github.com/Polymer/polymer-bundler/pull/519\n if (aOriginal && typeof aOriginal.line !== 'number' && typeof aOriginal.column !== 'number') {\n throw new Error(\n 'original.line and original.column are not numbers -- you probably meant to omit ' +\n 'the original mapping entirely and only map the generated position. If so, pass ' +\n 'null for the original mapping instead of an object with empty or null values.'\n );\n }\n\n if (aGenerated && 'line' in aGenerated && 'column' in aGenerated\n && aGenerated.line > 0 && aGenerated.column >= 0\n && !aOriginal && !aSource && !aName) {\n // Case 1.\n return;\n }\n else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated\n && aOriginal && 'line' in aOriginal && 'column' in aOriginal\n && aGenerated.line > 0 && aGenerated.column >= 0\n && aOriginal.line > 0 && aOriginal.column >= 0\n && aSource) {\n // Cases 2 and 3.\n return;\n }\n else {\n throw new Error('Invalid mapping: ' + JSON.stringify({\n generated: aGenerated,\n source: aSource,\n original: aOriginal,\n name: aName\n }));\n }\n };\n\n/**\n * Serialize the accumulated mappings in to the stream of base 64 VLQs\n * specified by the source map format.\n */\nSourceMapGenerator.prototype._serializeMappings =\n function SourceMapGenerator_serializeMappings() {\n var previousGeneratedColumn = 0;\n var previousGeneratedLine = 1;\n var previousOriginalColumn = 0;\n var previousOriginalLine = 0;\n var previousName = 0;\n var previousSource = 0;\n var result = '';\n var next;\n var mapping;\n var nameIdx;\n var sourceIdx;\n\n var mappings = this._mappings.toArray();\n for (var i = 0, len = mappings.length; i < len; i++) {\n mapping = mappings[i];\n next = ''\n\n if (mapping.generatedLine !== previousGeneratedLine) {\n previousGeneratedColumn = 0;\n while (mapping.generatedLine !== previousGeneratedLine) {\n next += ';';\n previousGeneratedLine++;\n }\n }\n else {\n if (i > 0) {\n if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) {\n continue;\n }\n next += ',';\n }\n }\n\n next += base64VLQ.encode(mapping.generatedColumn\n - previousGeneratedColumn);\n previousGeneratedColumn = mapping.generatedColumn;\n\n if (mapping.source != null) {\n sourceIdx = this._sources.indexOf(mapping.source);\n next += base64VLQ.encode(sourceIdx - previousSource);\n previousSource = sourceIdx;\n\n // lines are stored 0-based in SourceMap spec version 3\n next += base64VLQ.encode(mapping.originalLine - 1\n - previousOriginalLine);\n previousOriginalLine = mapping.originalLine - 1;\n\n next += base64VLQ.encode(mapping.originalColumn\n - previousOriginalColumn);\n previousOriginalColumn = mapping.originalColumn;\n\n if (mapping.name != null) {\n nameIdx = this._names.indexOf(mapping.name);\n next += base64VLQ.encode(nameIdx - previousName);\n previousName = nameIdx;\n }\n }\n\n result += next;\n }\n\n return result;\n };\n\nSourceMapGenerator.prototype._generateSourcesContent =\n function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) {\n return aSources.map(function (source) {\n if (!this._sourcesContents) {\n return null;\n }\n if (aSourceRoot != null) {\n source = util.relative(aSourceRoot, source);\n }\n var key = util.toSetString(source);\n return Object.prototype.hasOwnProperty.call(this._sourcesContents, key)\n ? this._sourcesContents[key]\n : null;\n }, this);\n };\n\n/**\n * Externalize the source map.\n */\nSourceMapGenerator.prototype.toJSON =\n function SourceMapGenerator_toJSON() {\n var map = {\n version: this._version,\n sources: this._sources.toArray(),\n names: this._names.toArray(),\n mappings: this._serializeMappings()\n };\n if (this._file != null) {\n map.file = this._file;\n }\n if (this._sourceRoot != null) {\n map.sourceRoot = this._sourceRoot;\n }\n if (this._sourcesContents) {\n map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot);\n }\n\n return map;\n };\n\n/**\n * Render the source map being generated to a string.\n */\nSourceMapGenerator.prototype.toString =\n function SourceMapGenerator_toString() {\n return JSON.stringify(this.toJSON());\n };\n\nexports.SourceMapGenerator = SourceMapGenerator;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./lib/source-map-generator.js\n// module id = 1\n// module chunks = 0","/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n *\n * Based on the Base 64 VLQ implementation in Closure Compiler:\n * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java\n *\n * Copyright 2011 The Closure Compiler Authors. All rights reserved.\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following\n * disclaimer in the documentation and/or other materials provided\n * with the distribution.\n * * Neither the name of Google Inc. nor the names of its\n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\nvar base64 = require('./base64');\n\n// A single base 64 digit can contain 6 bits of data. For the base 64 variable\n// length quantities we use in the source map spec, the first bit is the sign,\n// the next four bits are the actual value, and the 6th bit is the\n// continuation bit. The continuation bit tells us whether there are more\n// digits in this value following this digit.\n//\n// Continuation\n// | Sign\n// | |\n// V V\n// 101011\n\nvar VLQ_BASE_SHIFT = 5;\n\n// binary: 100000\nvar VLQ_BASE = 1 << VLQ_BASE_SHIFT;\n\n// binary: 011111\nvar VLQ_BASE_MASK = VLQ_BASE - 1;\n\n// binary: 100000\nvar VLQ_CONTINUATION_BIT = VLQ_BASE;\n\n/**\n * Converts from a two-complement value to a value where the sign bit is\n * placed in the least significant bit. For example, as decimals:\n * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary)\n * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary)\n */\nfunction toVLQSigned(aValue) {\n return aValue < 0\n ? ((-aValue) << 1) + 1\n : (aValue << 1) + 0;\n}\n\n/**\n * Converts to a two-complement value from a value where the sign bit is\n * placed in the least significant bit. For example, as decimals:\n * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1\n * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2\n */\nfunction fromVLQSigned(aValue) {\n var isNegative = (aValue & 1) === 1;\n var shifted = aValue >> 1;\n return isNegative\n ? -shifted\n : shifted;\n}\n\n/**\n * Returns the base 64 VLQ encoded value.\n */\nexports.encode = function base64VLQ_encode(aValue) {\n var encoded = \"\";\n var digit;\n\n var vlq = toVLQSigned(aValue);\n\n do {\n digit = vlq & VLQ_BASE_MASK;\n vlq >>>= VLQ_BASE_SHIFT;\n if (vlq > 0) {\n // There are still more digits in this value, so we must make sure the\n // continuation bit is marked.\n digit |= VLQ_CONTINUATION_BIT;\n }\n encoded += base64.encode(digit);\n } while (vlq > 0);\n\n return encoded;\n};\n\n/**\n * Decodes the next base 64 VLQ value from the given string and returns the\n * value and the rest of the string via the out parameter.\n */\nexports.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) {\n var strLen = aStr.length;\n var result = 0;\n var shift = 0;\n var continuation, digit;\n\n do {\n if (aIndex >= strLen) {\n throw new Error(\"Expected more digits in base 64 VLQ value.\");\n }\n\n digit = base64.decode(aStr.charCodeAt(aIndex++));\n if (digit === -1) {\n throw new Error(\"Invalid base64 digit: \" + aStr.charAt(aIndex - 1));\n }\n\n continuation = !!(digit & VLQ_CONTINUATION_BIT);\n digit &= VLQ_BASE_MASK;\n result = result + (digit << shift);\n shift += VLQ_BASE_SHIFT;\n } while (continuation);\n\n aOutParam.value = fromVLQSigned(result);\n aOutParam.rest = aIndex;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./lib/base64-vlq.js\n// module id = 2\n// module chunks = 0","/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\nvar intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split('');\n\n/**\n * Encode an integer in the range of 0 to 63 to a single base 64 digit.\n */\nexports.encode = function (number) {\n if (0 <= number && number < intToCharMap.length) {\n return intToCharMap[number];\n }\n throw new TypeError(\"Must be between 0 and 63: \" + number);\n};\n\n/**\n * Decode a single base 64 character code digit to an integer. Returns -1 on\n * failure.\n */\nexports.decode = function (charCode) {\n var bigA = 65; // 'A'\n var bigZ = 90; // 'Z'\n\n var littleA = 97; // 'a'\n var littleZ = 122; // 'z'\n\n var zero = 48; // '0'\n var nine = 57; // '9'\n\n var plus = 43; // '+'\n var slash = 47; // '/'\n\n var littleOffset = 26;\n var numberOffset = 52;\n\n // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ\n if (bigA <= charCode && charCode <= bigZ) {\n return (charCode - bigA);\n }\n\n // 26 - 51: abcdefghijklmnopqrstuvwxyz\n if (littleA <= charCode && charCode <= littleZ) {\n return (charCode - littleA + littleOffset);\n }\n\n // 52 - 61: 0123456789\n if (zero <= charCode && charCode <= nine) {\n return (charCode - zero + numberOffset);\n }\n\n // 62: +\n if (charCode == plus) {\n return 62;\n }\n\n // 63: /\n if (charCode == slash) {\n return 63;\n }\n\n // Invalid base64 digit.\n return -1;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./lib/base64.js\n// module id = 3\n// module chunks = 0","/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\n/**\n * This is a helper function for getting values from parameter/options\n * objects.\n *\n * @param args The object we are extracting values from\n * @param name The name of the property we are getting.\n * @param defaultValue An optional value to return if the property is missing\n * from the object. If this is not specified and the property is missing, an\n * error will be thrown.\n */\nfunction getArg(aArgs, aName, aDefaultValue) {\n if (aName in aArgs) {\n return aArgs[aName];\n } else if (arguments.length === 3) {\n return aDefaultValue;\n } else {\n throw new Error('\"' + aName + '\" is a required argument.');\n }\n}\nexports.getArg = getArg;\n\nvar urlRegexp = /^(?:([\\w+\\-.]+):)?\\/\\/(?:(\\w+:\\w+)@)?([\\w.-]*)(?::(\\d+))?(.*)$/;\nvar dataUrlRegexp = /^data:.+\\,.+$/;\n\nfunction urlParse(aUrl) {\n var match = aUrl.match(urlRegexp);\n if (!match) {\n return null;\n }\n return {\n scheme: match[1],\n auth: match[2],\n host: match[3],\n port: match[4],\n path: match[5]\n };\n}\nexports.urlParse = urlParse;\n\nfunction urlGenerate(aParsedUrl) {\n var url = '';\n if (aParsedUrl.scheme) {\n url += aParsedUrl.scheme + ':';\n }\n url += '//';\n if (aParsedUrl.auth) {\n url += aParsedUrl.auth + '@';\n }\n if (aParsedUrl.host) {\n url += aParsedUrl.host;\n }\n if (aParsedUrl.port) {\n url += \":\" + aParsedUrl.port\n }\n if (aParsedUrl.path) {\n url += aParsedUrl.path;\n }\n return url;\n}\nexports.urlGenerate = urlGenerate;\n\n/**\n * Normalizes a path, or the path portion of a URL:\n *\n * - Replaces consecutive slashes with one slash.\n * - Removes unnecessary '.' parts.\n * - Removes unnecessary '/..' parts.\n *\n * Based on code in the Node.js 'path' core module.\n *\n * @param aPath The path or url to normalize.\n */\nfunction normalize(aPath) {\n var path = aPath;\n var url = urlParse(aPath);\n if (url) {\n if (!url.path) {\n return aPath;\n }\n path = url.path;\n }\n var isAbsolute = exports.isAbsolute(path);\n\n var parts = path.split(/\\/+/);\n for (var part, up = 0, i = parts.length - 1; i >= 0; i--) {\n part = parts[i];\n if (part === '.') {\n parts.splice(i, 1);\n } else if (part === '..') {\n up++;\n } else if (up > 0) {\n if (part === '') {\n // The first part is blank if the path is absolute. Trying to go\n // above the root is a no-op. Therefore we can remove all '..' parts\n // directly after the root.\n parts.splice(i + 1, up);\n up = 0;\n } else {\n parts.splice(i, 2);\n up--;\n }\n }\n }\n path = parts.join('/');\n\n if (path === '') {\n path = isAbsolute ? '/' : '.';\n }\n\n if (url) {\n url.path = path;\n return urlGenerate(url);\n }\n return path;\n}\nexports.normalize = normalize;\n\n/**\n * Joins two paths/URLs.\n *\n * @param aRoot The root path or URL.\n * @param aPath The path or URL to be joined with the root.\n *\n * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a\n * scheme-relative URL: Then the scheme of aRoot, if any, is prepended\n * first.\n * - Otherwise aPath is a path. If aRoot is a URL, then its path portion\n * is updated with the result and aRoot is returned. Otherwise the result\n * is returned.\n * - If aPath is absolute, the result is aPath.\n * - Otherwise the two paths are joined with a slash.\n * - Joining for example 'http://' and 'www.example.com' is also supported.\n */\nfunction join(aRoot, aPath) {\n if (aRoot === \"\") {\n aRoot = \".\";\n }\n if (aPath === \"\") {\n aPath = \".\";\n }\n var aPathUrl = urlParse(aPath);\n var aRootUrl = urlParse(aRoot);\n if (aRootUrl) {\n aRoot = aRootUrl.path || '/';\n }\n\n // `join(foo, '//www.example.org')`\n if (aPathUrl && !aPathUrl.scheme) {\n if (aRootUrl) {\n aPathUrl.scheme = aRootUrl.scheme;\n }\n return urlGenerate(aPathUrl);\n }\n\n if (aPathUrl || aPath.match(dataUrlRegexp)) {\n return aPath;\n }\n\n // `join('http://', 'www.example.com')`\n if (aRootUrl && !aRootUrl.host && !aRootUrl.path) {\n aRootUrl.host = aPath;\n return urlGenerate(aRootUrl);\n }\n\n var joined = aPath.charAt(0) === '/'\n ? aPath\n : normalize(aRoot.replace(/\\/+$/, '') + '/' + aPath);\n\n if (aRootUrl) {\n aRootUrl.path = joined;\n return urlGenerate(aRootUrl);\n }\n return joined;\n}\nexports.join = join;\n\nexports.isAbsolute = function (aPath) {\n return aPath.charAt(0) === '/' || urlRegexp.test(aPath);\n};\n\n/**\n * Make a path relative to a URL or another path.\n *\n * @param aRoot The root path or URL.\n * @param aPath The path or URL to be made relative to aRoot.\n */\nfunction relative(aRoot, aPath) {\n if (aRoot === \"\") {\n aRoot = \".\";\n }\n\n aRoot = aRoot.replace(/\\/$/, '');\n\n // It is possible for the path to be above the root. In this case, simply\n // checking whether the root is a prefix of the path won't work. Instead, we\n // need to remove components from the root one by one, until either we find\n // a prefix that fits, or we run out of components to remove.\n var level = 0;\n while (aPath.indexOf(aRoot + '/') !== 0) {\n var index = aRoot.lastIndexOf(\"/\");\n if (index < 0) {\n return aPath;\n }\n\n // If the only part of the root that is left is the scheme (i.e. http://,\n // file:///, etc.), one or more slashes (/), or simply nothing at all, we\n // have exhausted all components, so the path is not relative to the root.\n aRoot = aRoot.slice(0, index);\n if (aRoot.match(/^([^\\/]+:\\/)?\\/*$/)) {\n return aPath;\n }\n\n ++level;\n }\n\n // Make sure we add a \"../\" for each component we removed from the root.\n return Array(level + 1).join(\"../\") + aPath.substr(aRoot.length + 1);\n}\nexports.relative = relative;\n\nvar supportsNullProto = (function () {\n var obj = Object.create(null);\n return !('__proto__' in obj);\n}());\n\nfunction identity (s) {\n return s;\n}\n\n/**\n * Because behavior goes wacky when you set `__proto__` on objects, we\n * have to prefix all the strings in our set with an arbitrary character.\n *\n * See https://github.com/mozilla/source-map/pull/31 and\n * https://github.com/mozilla/source-map/issues/30\n *\n * @param String aStr\n */\nfunction toSetString(aStr) {\n if (isProtoString(aStr)) {\n return '$' + aStr;\n }\n\n return aStr;\n}\nexports.toSetString = supportsNullProto ? identity : toSetString;\n\nfunction fromSetString(aStr) {\n if (isProtoString(aStr)) {\n return aStr.slice(1);\n }\n\n return aStr;\n}\nexports.fromSetString = supportsNullProto ? identity : fromSetString;\n\nfunction isProtoString(s) {\n if (!s) {\n return false;\n }\n\n var length = s.length;\n\n if (length < 9 /* \"__proto__\".length */) {\n return false;\n }\n\n if (s.charCodeAt(length - 1) !== 95 /* '_' */ ||\n s.charCodeAt(length - 2) !== 95 /* '_' */ ||\n s.charCodeAt(length - 3) !== 111 /* 'o' */ ||\n s.charCodeAt(length - 4) !== 116 /* 't' */ ||\n s.charCodeAt(length - 5) !== 111 /* 'o' */ ||\n s.charCodeAt(length - 6) !== 114 /* 'r' */ ||\n s.charCodeAt(length - 7) !== 112 /* 'p' */ ||\n s.charCodeAt(length - 8) !== 95 /* '_' */ ||\n s.charCodeAt(length - 9) !== 95 /* '_' */) {\n return false;\n }\n\n for (var i = length - 10; i >= 0; i--) {\n if (s.charCodeAt(i) !== 36 /* '$' */) {\n return false;\n }\n }\n\n return true;\n}\n\n/**\n * Comparator between two mappings where the original positions are compared.\n *\n * Optionally pass in `true` as `onlyCompareGenerated` to consider two\n * mappings with the same original source/line/column, but different generated\n * line and column the same. Useful when searching for a mapping with a\n * stubbed out mapping.\n */\nfunction compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) {\n var cmp = strcmp(mappingA.source, mappingB.source);\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = mappingA.originalLine - mappingB.originalLine;\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = mappingA.originalColumn - mappingB.originalColumn;\n if (cmp !== 0 || onlyCompareOriginal) {\n return cmp;\n }\n\n cmp = mappingA.generatedColumn - mappingB.generatedColumn;\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = mappingA.generatedLine - mappingB.generatedLine;\n if (cmp !== 0) {\n return cmp;\n }\n\n return strcmp(mappingA.name, mappingB.name);\n}\nexports.compareByOriginalPositions = compareByOriginalPositions;\n\n/**\n * Comparator between two mappings with deflated source and name indices where\n * the generated positions are compared.\n *\n * Optionally pass in `true` as `onlyCompareGenerated` to consider two\n * mappings with the same generated line and column, but different\n * source/name/original line and column the same. Useful when searching for a\n * mapping with a stubbed out mapping.\n */\nfunction compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) {\n var cmp = mappingA.generatedLine - mappingB.generatedLine;\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = mappingA.generatedColumn - mappingB.generatedColumn;\n if (cmp !== 0 || onlyCompareGenerated) {\n return cmp;\n }\n\n cmp = strcmp(mappingA.source, mappingB.source);\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = mappingA.originalLine - mappingB.originalLine;\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = mappingA.originalColumn - mappingB.originalColumn;\n if (cmp !== 0) {\n return cmp;\n }\n\n return strcmp(mappingA.name, mappingB.name);\n}\nexports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated;\n\nfunction strcmp(aStr1, aStr2) {\n if (aStr1 === aStr2) {\n return 0;\n }\n\n if (aStr1 === null) {\n return 1; // aStr2 !== null\n }\n\n if (aStr2 === null) {\n return -1; // aStr1 !== null\n }\n\n if (aStr1 > aStr2) {\n return 1;\n }\n\n return -1;\n}\n\n/**\n * Comparator between two mappings with inflated source and name strings where\n * the generated positions are compared.\n */\nfunction compareByGeneratedPositionsInflated(mappingA, mappingB) {\n var cmp = mappingA.generatedLine - mappingB.generatedLine;\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = mappingA.generatedColumn - mappingB.generatedColumn;\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = strcmp(mappingA.source, mappingB.source);\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = mappingA.originalLine - mappingB.originalLine;\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = mappingA.originalColumn - mappingB.originalColumn;\n if (cmp !== 0) {\n return cmp;\n }\n\n return strcmp(mappingA.name, mappingB.name);\n}\nexports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated;\n\n/**\n * Strip any JSON XSSI avoidance prefix from the string (as documented\n * in the source maps specification), and then parse the string as\n * JSON.\n */\nfunction parseSourceMapInput(str) {\n return JSON.parse(str.replace(/^\\)]}'[^\\n]*\\n/, ''));\n}\nexports.parseSourceMapInput = parseSourceMapInput;\n\n/**\n * Compute the URL of a source given the the source root, the source's\n * URL, and the source map's URL.\n */\nfunction computeSourceURL(sourceRoot, sourceURL, sourceMapURL) {\n sourceURL = sourceURL || '';\n\n if (sourceRoot) {\n // This follows what Chrome does.\n if (sourceRoot[sourceRoot.length - 1] !== '/' && sourceURL[0] !== '/') {\n sourceRoot += '/';\n }\n // The spec says:\n // Line 4: An optional source root, useful for relocating source\n // files on a server or removing repeated values in the\n // “sources” entry. This value is prepended to the individual\n // entries in the “source” field.\n sourceURL = sourceRoot + sourceURL;\n }\n\n // Historically, SourceMapConsumer did not take the sourceMapURL as\n // a parameter. This mode is still somewhat supported, which is why\n // this code block is conditional. However, it's preferable to pass\n // the source map URL to SourceMapConsumer, so that this function\n // can implement the source URL resolution algorithm as outlined in\n // the spec. This block is basically the equivalent of:\n // new URL(sourceURL, sourceMapURL).toString()\n // ... except it avoids using URL, which wasn't available in the\n // older releases of node still supported by this library.\n //\n // The spec says:\n // If the sources are not absolute URLs after prepending of the\n // “sourceRoot”, the sources are resolved relative to the\n // SourceMap (like resolving script src in a html document).\n if (sourceMapURL) {\n var parsed = urlParse(sourceMapURL);\n if (!parsed) {\n throw new Error(\"sourceMapURL could not be parsed\");\n }\n if (parsed.path) {\n // Strip the last path component, but keep the \"/\".\n var index = parsed.path.lastIndexOf('/');\n if (index >= 0) {\n parsed.path = parsed.path.substring(0, index + 1);\n }\n }\n sourceURL = join(urlGenerate(parsed), sourceURL);\n }\n\n return normalize(sourceURL);\n}\nexports.computeSourceURL = computeSourceURL;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./lib/util.js\n// module id = 4\n// module chunks = 0","/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\nvar util = require('./util');\nvar has = Object.prototype.hasOwnProperty;\nvar hasNativeMap = typeof Map !== \"undefined\";\n\n/**\n * A data structure which is a combination of an array and a set. Adding a new\n * member is O(1), testing for membership is O(1), and finding the index of an\n * element is O(1). Removing elements from the set is not supported. Only\n * strings are supported for membership.\n */\nfunction ArraySet() {\n this._array = [];\n this._set = hasNativeMap ? new Map() : Object.create(null);\n}\n\n/**\n * Static method for creating ArraySet instances from an existing array.\n */\nArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) {\n var set = new ArraySet();\n for (var i = 0, len = aArray.length; i < len; i++) {\n set.add(aArray[i], aAllowDuplicates);\n }\n return set;\n};\n\n/**\n * Return how many unique items are in this ArraySet. If duplicates have been\n * added, than those do not count towards the size.\n *\n * @returns Number\n */\nArraySet.prototype.size = function ArraySet_size() {\n return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length;\n};\n\n/**\n * Add the given string to this set.\n *\n * @param String aStr\n */\nArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) {\n var sStr = hasNativeMap ? aStr : util.toSetString(aStr);\n var isDuplicate = hasNativeMap ? this.has(aStr) : has.call(this._set, sStr);\n var idx = this._array.length;\n if (!isDuplicate || aAllowDuplicates) {\n this._array.push(aStr);\n }\n if (!isDuplicate) {\n if (hasNativeMap) {\n this._set.set(aStr, idx);\n } else {\n this._set[sStr] = idx;\n }\n }\n};\n\n/**\n * Is the given string a member of this set?\n *\n * @param String aStr\n */\nArraySet.prototype.has = function ArraySet_has(aStr) {\n if (hasNativeMap) {\n return this._set.has(aStr);\n } else {\n var sStr = util.toSetString(aStr);\n return has.call(this._set, sStr);\n }\n};\n\n/**\n * What is the index of the given string in the array?\n *\n * @param String aStr\n */\nArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) {\n if (hasNativeMap) {\n var idx = this._set.get(aStr);\n if (idx >= 0) {\n return idx;\n }\n } else {\n var sStr = util.toSetString(aStr);\n if (has.call(this._set, sStr)) {\n return this._set[sStr];\n }\n }\n\n throw new Error('\"' + aStr + '\" is not in the set.');\n};\n\n/**\n * What is the element at the given index?\n *\n * @param Number aIdx\n */\nArraySet.prototype.at = function ArraySet_at(aIdx) {\n if (aIdx >= 0 && aIdx < this._array.length) {\n return this._array[aIdx];\n }\n throw new Error('No element indexed by ' + aIdx);\n};\n\n/**\n * Returns the array representation of this set (which has the proper indices\n * indicated by indexOf). Note that this is a copy of the internal array used\n * for storing the members so that no one can mess with internal state.\n */\nArraySet.prototype.toArray = function ArraySet_toArray() {\n return this._array.slice();\n};\n\nexports.ArraySet = ArraySet;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./lib/array-set.js\n// module id = 5\n// module chunks = 0","/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2014 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\nvar util = require('./util');\n\n/**\n * Determine whether mappingB is after mappingA with respect to generated\n * position.\n */\nfunction generatedPositionAfter(mappingA, mappingB) {\n // Optimized for most common case\n var lineA = mappingA.generatedLine;\n var lineB = mappingB.generatedLine;\n var columnA = mappingA.generatedColumn;\n var columnB = mappingB.generatedColumn;\n return lineB > lineA || lineB == lineA && columnB >= columnA ||\n util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0;\n}\n\n/**\n * A data structure to provide a sorted view of accumulated mappings in a\n * performance conscious manner. It trades a neglibable overhead in general\n * case for a large speedup in case of mappings being added in order.\n */\nfunction MappingList() {\n this._array = [];\n this._sorted = true;\n // Serves as infimum\n this._last = {generatedLine: -1, generatedColumn: 0};\n}\n\n/**\n * Iterate through internal items. This method takes the same arguments that\n * `Array.prototype.forEach` takes.\n *\n * NOTE: The order of the mappings is NOT guaranteed.\n */\nMappingList.prototype.unsortedForEach =\n function MappingList_forEach(aCallback, aThisArg) {\n this._array.forEach(aCallback, aThisArg);\n };\n\n/**\n * Add the given source mapping.\n *\n * @param Object aMapping\n */\nMappingList.prototype.add = function MappingList_add(aMapping) {\n if (generatedPositionAfter(this._last, aMapping)) {\n this._last = aMapping;\n this._array.push(aMapping);\n } else {\n this._sorted = false;\n this._array.push(aMapping);\n }\n};\n\n/**\n * Returns the flat, sorted array of mappings. The mappings are sorted by\n * generated position.\n *\n * WARNING: This method returns internal data without copying, for\n * performance. The return value must NOT be mutated, and should be treated as\n * an immutable borrow. If you want to take ownership, you must make your own\n * copy.\n */\nMappingList.prototype.toArray = function MappingList_toArray() {\n if (!this._sorted) {\n this._array.sort(util.compareByGeneratedPositionsInflated);\n this._sorted = true;\n }\n return this._array;\n};\n\nexports.MappingList = MappingList;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./lib/mapping-list.js\n// module id = 6\n// module chunks = 0","/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\nvar util = require('./util');\nvar binarySearch = require('./binary-search');\nvar ArraySet = require('./array-set').ArraySet;\nvar base64VLQ = require('./base64-vlq');\nvar quickSort = require('./quick-sort').quickSort;\n\nfunction SourceMapConsumer(aSourceMap, aSourceMapURL) {\n var sourceMap = aSourceMap;\n if (typeof aSourceMap === 'string') {\n sourceMap = util.parseSourceMapInput(aSourceMap);\n }\n\n return sourceMap.sections != null\n ? new IndexedSourceMapConsumer(sourceMap, aSourceMapURL)\n : new BasicSourceMapConsumer(sourceMap, aSourceMapURL);\n}\n\nSourceMapConsumer.fromSourceMap = function(aSourceMap, aSourceMapURL) {\n return BasicSourceMapConsumer.fromSourceMap(aSourceMap, aSourceMapURL);\n}\n\n/**\n * The version of the source mapping spec that we are consuming.\n */\nSourceMapConsumer.prototype._version = 3;\n\n// `__generatedMappings` and `__originalMappings` are arrays that hold the\n// parsed mapping coordinates from the source map's \"mappings\" attribute. They\n// are lazily instantiated, accessed via the `_generatedMappings` and\n// `_originalMappings` getters respectively, and we only parse the mappings\n// and create these arrays once queried for a source location. We jump through\n// these hoops because there can be many thousands of mappings, and parsing\n// them is expensive, so we only want to do it if we must.\n//\n// Each object in the arrays is of the form:\n//\n// {\n// generatedLine: The line number in the generated code,\n// generatedColumn: The column number in the generated code,\n// source: The path to the original source file that generated this\n// chunk of code,\n// originalLine: The line number in the original source that\n// corresponds to this chunk of generated code,\n// originalColumn: The column number in the original source that\n// corresponds to this chunk of generated code,\n// name: The name of the original symbol which generated this chunk of\n// code.\n// }\n//\n// All properties except for `generatedLine` and `generatedColumn` can be\n// `null`.\n//\n// `_generatedMappings` is ordered by the generated positions.\n//\n// `_originalMappings` is ordered by the original positions.\n\nSourceMapConsumer.prototype.__generatedMappings = null;\nObject.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', {\n configurable: true,\n enumerable: true,\n get: function () {\n if (!this.__generatedMappings) {\n this._parseMappings(this._mappings, this.sourceRoot);\n }\n\n return this.__generatedMappings;\n }\n});\n\nSourceMapConsumer.prototype.__originalMappings = null;\nObject.defineProperty(SourceMapConsumer.prototype, '_originalMappings', {\n configurable: true,\n enumerable: true,\n get: function () {\n if (!this.__originalMappings) {\n this._parseMappings(this._mappings, this.sourceRoot);\n }\n\n return this.__originalMappings;\n }\n});\n\nSourceMapConsumer.prototype._charIsMappingSeparator =\n function SourceMapConsumer_charIsMappingSeparator(aStr, index) {\n var c = aStr.charAt(index);\n return c === \";\" || c === \",\";\n };\n\n/**\n * Parse the mappings in a string in to a data structure which we can easily\n * query (the ordered arrays in the `this.__generatedMappings` and\n * `this.__originalMappings` properties).\n */\nSourceMapConsumer.prototype._parseMappings =\n function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {\n throw new Error(\"Subclasses must implement _parseMappings\");\n };\n\nSourceMapConsumer.GENERATED_ORDER = 1;\nSourceMapConsumer.ORIGINAL_ORDER = 2;\n\nSourceMapConsumer.GREATEST_LOWER_BOUND = 1;\nSourceMapConsumer.LEAST_UPPER_BOUND = 2;\n\n/**\n * Iterate over each mapping between an original source/line/column and a\n * generated line/column in this source map.\n *\n * @param Function aCallback\n * The function that is called with each mapping.\n * @param Object aContext\n * Optional. If specified, this object will be the value of `this` every\n * time that `aCallback` is called.\n * @param aOrder\n * Either `SourceMapConsumer.GENERATED_ORDER` or\n * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to\n * iterate over the mappings sorted by the generated file's line/column\n * order or the original's source/line/column order, respectively. Defaults to\n * `SourceMapConsumer.GENERATED_ORDER`.\n */\nSourceMapConsumer.prototype.eachMapping =\n function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) {\n var context = aContext || null;\n var order = aOrder || SourceMapConsumer.GENERATED_ORDER;\n\n var mappings;\n switch (order) {\n case SourceMapConsumer.GENERATED_ORDER:\n mappings = this._generatedMappings;\n break;\n case SourceMapConsumer.ORIGINAL_ORDER:\n mappings = this._originalMappings;\n break;\n default:\n throw new Error(\"Unknown order of iteration.\");\n }\n\n var sourceRoot = this.sourceRoot;\n mappings.map(function (mapping) {\n var source = mapping.source === null ? null : this._sources.at(mapping.source);\n source = util.computeSourceURL(sourceRoot, source, this._sourceMapURL);\n return {\n source: source,\n generatedLine: mapping.generatedLine,\n generatedColumn: mapping.generatedColumn,\n originalLine: mapping.originalLine,\n originalColumn: mapping.originalColumn,\n name: mapping.name === null ? null : this._names.at(mapping.name)\n };\n }, this).forEach(aCallback, context);\n };\n\n/**\n * Returns all generated line and column information for the original source,\n * line, and column provided. If no column is provided, returns all mappings\n * corresponding to a either the line we are searching for or the next\n * closest line that has any mappings. Otherwise, returns all mappings\n * corresponding to the given line and either the column we are searching for\n * or the next closest column that has any offsets.\n *\n * The only argument is an object with the following properties:\n *\n * - source: The filename of the original source.\n * - line: The line number in the original source. The line number is 1-based.\n * - column: Optional. the column number in the original source.\n * The column number is 0-based.\n *\n * and an array of objects is returned, each with the following properties:\n *\n * - line: The line number in the generated source, or null. The\n * line number is 1-based.\n * - column: The column number in the generated source, or null.\n * The column number is 0-based.\n */\nSourceMapConsumer.prototype.allGeneratedPositionsFor =\n function SourceMapConsumer_allGeneratedPositionsFor(aArgs) {\n var line = util.getArg(aArgs, 'line');\n\n // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping\n // returns the index of the closest mapping less than the needle. By\n // setting needle.originalColumn to 0, we thus find the last mapping for\n // the given line, provided such a mapping exists.\n var needle = {\n source: util.getArg(aArgs, 'source'),\n originalLine: line,\n originalColumn: util.getArg(aArgs, 'column', 0)\n };\n\n needle.source = this._findSourceIndex(needle.source);\n if (needle.source < 0) {\n return [];\n }\n\n var mappings = [];\n\n var index = this._findMapping(needle,\n this._originalMappings,\n \"originalLine\",\n \"originalColumn\",\n util.compareByOriginalPositions,\n binarySearch.LEAST_UPPER_BOUND);\n if (index >= 0) {\n var mapping = this._originalMappings[index];\n\n if (aArgs.column === undefined) {\n var originalLine = mapping.originalLine;\n\n // Iterate until either we run out of mappings, or we run into\n // a mapping for a different line than the one we found. Since\n // mappings are sorted, this is guaranteed to find all mappings for\n // the line we found.\n while (mapping && mapping.originalLine === originalLine) {\n mappings.push({\n line: util.getArg(mapping, 'generatedLine', null),\n column: util.getArg(mapping, 'generatedColumn', null),\n lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)\n });\n\n mapping = this._originalMappings[++index];\n }\n } else {\n var originalColumn = mapping.originalColumn;\n\n // Iterate until either we run out of mappings, or we run into\n // a mapping for a different line than the one we were searching for.\n // Since mappings are sorted, this is guaranteed to find all mappings for\n // the line we are searching for.\n while (mapping &&\n mapping.originalLine === line &&\n mapping.originalColumn == originalColumn) {\n mappings.push({\n line: util.getArg(mapping, 'generatedLine', null),\n column: util.getArg(mapping, 'generatedColumn', null),\n lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)\n });\n\n mapping = this._originalMappings[++index];\n }\n }\n }\n\n return mappings;\n };\n\nexports.SourceMapConsumer = SourceMapConsumer;\n\n/**\n * A BasicSourceMapConsumer instance represents a parsed source map which we can\n * query for information about the original file positions by giving it a file\n * position in the generated source.\n *\n * The first parameter is the raw source map (either as a JSON string, or\n * already parsed to an object). According to the spec, source maps have the\n * following attributes:\n *\n * - version: Which version of the source map spec this map is following.\n * - sources: An array of URLs to the original source files.\n * - names: An array of identifiers which can be referrenced by individual mappings.\n * - sourceRoot: Optional. The URL root from which all sources are relative.\n * - sourcesContent: Optional. An array of contents of the original source files.\n * - mappings: A string of base64 VLQs which contain the actual mappings.\n * - file: Optional. The generated file this source map is associated with.\n *\n * Here is an example source map, taken from the source map spec[0]:\n *\n * {\n * version : 3,\n * file: \"out.js\",\n * sourceRoot : \"\",\n * sources: [\"foo.js\", \"bar.js\"],\n * names: [\"src\", \"maps\", \"are\", \"fun\"],\n * mappings: \"AA,AB;;ABCDE;\"\n * }\n *\n * The second parameter, if given, is a string whose value is the URL\n * at which the source map was found. This URL is used to compute the\n * sources array.\n *\n * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1#\n */\nfunction BasicSourceMapConsumer(aSourceMap, aSourceMapURL) {\n var sourceMap = aSourceMap;\n if (typeof aSourceMap === 'string') {\n sourceMap = util.parseSourceMapInput(aSourceMap);\n }\n\n var version = util.getArg(sourceMap, 'version');\n var sources = util.getArg(sourceMap, 'sources');\n // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which\n // requires the array) to play nice here.\n var names = util.getArg(sourceMap, 'names', []);\n var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null);\n var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null);\n var mappings = util.getArg(sourceMap, 'mappings');\n var file = util.getArg(sourceMap, 'file', null);\n\n // Once again, Sass deviates from the spec and supplies the version as a\n // string rather than a number, so we use loose equality checking here.\n if (version != this._version) {\n throw new Error('Unsupported version: ' + version);\n }\n\n if (sourceRoot) {\n sourceRoot = util.normalize(sourceRoot);\n }\n\n sources = sources\n .map(String)\n // Some source maps produce relative source paths like \"./foo.js\" instead of\n // \"foo.js\". Normalize these first so that future comparisons will succeed.\n // See bugzil.la/1090768.\n .map(util.normalize)\n // Always ensure that absolute sources are internally stored relative to\n // the source root, if the source root is absolute. Not doing this would\n // be particularly problematic when the source root is a prefix of the\n // source (valid, but why??). See github issue #199 and bugzil.la/1188982.\n .map(function (source) {\n return sourceRoot && util.isAbsolute(sourceRoot) && util.isAbsolute(source)\n ? util.relative(sourceRoot, source)\n : source;\n });\n\n // Pass `true` below to allow duplicate names and sources. While source maps\n // are intended to be compressed and deduplicated, the TypeScript compiler\n // sometimes generates source maps with duplicates in them. See Github issue\n // #72 and bugzil.la/889492.\n this._names = ArraySet.fromArray(names.map(String), true);\n this._sources = ArraySet.fromArray(sources, true);\n\n this._absoluteSources = this._sources.toArray().map(function (s) {\n return util.computeSourceURL(sourceRoot, s, aSourceMapURL);\n });\n\n this.sourceRoot = sourceRoot;\n this.sourcesContent = sourcesContent;\n this._mappings = mappings;\n this._sourceMapURL = aSourceMapURL;\n this.file = file;\n}\n\nBasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);\nBasicSourceMapConsumer.prototype.consumer = SourceMapConsumer;\n\n/**\n * Utility function to find the index of a source. Returns -1 if not\n * found.\n */\nBasicSourceMapConsumer.prototype._findSourceIndex = function(aSource) {\n var relativeSource = aSource;\n if (this.sourceRoot != null) {\n relativeSource = util.relative(this.sourceRoot, relativeSource);\n }\n\n if (this._sources.has(relativeSource)) {\n return this._sources.indexOf(relativeSource);\n }\n\n // Maybe aSource is an absolute URL as returned by |sources|. In\n // this case we can't simply undo the transform.\n var i;\n for (i = 0; i < this._absoluteSources.length; ++i) {\n if (this._absoluteSources[i] == aSource) {\n return i;\n }\n }\n\n return -1;\n};\n\n/**\n * Create a BasicSourceMapConsumer from a SourceMapGenerator.\n *\n * @param SourceMapGenerator aSourceMap\n * The source map that will be consumed.\n * @param String aSourceMapURL\n * The URL at which the source map can be found (optional)\n * @returns BasicSourceMapConsumer\n */\nBasicSourceMapConsumer.fromSourceMap =\n function SourceMapConsumer_fromSourceMap(aSourceMap, aSourceMapURL) {\n var smc = Object.create(BasicSourceMapConsumer.prototype);\n\n var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true);\n var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true);\n smc.sourceRoot = aSourceMap._sourceRoot;\n smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(),\n smc.sourceRoot);\n smc.file = aSourceMap._file;\n smc._sourceMapURL = aSourceMapURL;\n smc._absoluteSources = smc._sources.toArray().map(function (s) {\n return util.computeSourceURL(smc.sourceRoot, s, aSourceMapURL);\n });\n\n // Because we are modifying the entries (by converting string sources and\n // names to indices into the sources and names ArraySets), we have to make\n // a copy of the entry or else bad things happen. Shared mutable state\n // strikes again! See github issue #191.\n\n var generatedMappings = aSourceMap._mappings.toArray().slice();\n var destGeneratedMappings = smc.__generatedMappings = [];\n var destOriginalMappings = smc.__originalMappings = [];\n\n for (var i = 0, length = generatedMappings.length; i < length; i++) {\n var srcMapping = generatedMappings[i];\n var destMapping = new Mapping;\n destMapping.generatedLine = srcMapping.generatedLine;\n destMapping.generatedColumn = srcMapping.generatedColumn;\n\n if (srcMapping.source) {\n destMapping.source = sources.indexOf(srcMapping.source);\n destMapping.originalLine = srcMapping.originalLine;\n destMapping.originalColumn = srcMapping.originalColumn;\n\n if (srcMapping.name) {\n destMapping.name = names.indexOf(srcMapping.name);\n }\n\n destOriginalMappings.push(destMapping);\n }\n\n destGeneratedMappings.push(destMapping);\n }\n\n quickSort(smc.__originalMappings, util.compareByOriginalPositions);\n\n return smc;\n };\n\n/**\n * The version of the source mapping spec that we are consuming.\n */\nBasicSourceMapConsumer.prototype._version = 3;\n\n/**\n * The list of original sources.\n */\nObject.defineProperty(BasicSourceMapConsumer.prototype, 'sources', {\n get: function () {\n return this._absoluteSources.slice();\n }\n});\n\n/**\n * Provide the JIT with a nice shape / hidden class.\n */\nfunction Mapping() {\n this.generatedLine = 0;\n this.generatedColumn = 0;\n this.source = null;\n this.originalLine = null;\n this.originalColumn = null;\n this.name = null;\n}\n\n/**\n * Parse the mappings in a string in to a data structure which we can easily\n * query (the ordered arrays in the `this.__generatedMappings` and\n * `this.__originalMappings` properties).\n */\nBasicSourceMapConsumer.prototype._parseMappings =\n function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {\n var generatedLine = 1;\n var previousGeneratedColumn = 0;\n var previousOriginalLine = 0;\n var previousOriginalColumn = 0;\n var previousSource = 0;\n var previousName = 0;\n var length = aStr.length;\n var index = 0;\n var cachedSegments = {};\n var temp = {};\n var originalMappings = [];\n var generatedMappings = [];\n var mapping, str, segment, end, value;\n\n while (index < length) {\n if (aStr.charAt(index) === ';') {\n generatedLine++;\n index++;\n previousGeneratedColumn = 0;\n }\n else if (aStr.charAt(index) === ',') {\n index++;\n }\n else {\n mapping = new Mapping();\n mapping.generatedLine = generatedLine;\n\n // Because each offset is encoded relative to the previous one,\n // many segments often have the same encoding. We can exploit this\n // fact by caching the parsed variable length fields of each segment,\n // allowing us to avoid a second parse if we encounter the same\n // segment again.\n for (end = index; end < length; end++) {\n if (this._charIsMappingSeparator(aStr, end)) {\n break;\n }\n }\n str = aStr.slice(index, end);\n\n segment = cachedSegments[str];\n if (segment) {\n index += str.length;\n } else {\n segment = [];\n while (index < end) {\n base64VLQ.decode(aStr, index, temp);\n value = temp.value;\n index = temp.rest;\n segment.push(value);\n }\n\n if (segment.length === 2) {\n throw new Error('Found a source, but no line and column');\n }\n\n if (segment.length === 3) {\n throw new Error('Found a source and line, but no column');\n }\n\n cachedSegments[str] = segment;\n }\n\n // Generated column.\n mapping.generatedColumn = previousGeneratedColumn + segment[0];\n previousGeneratedColumn = mapping.generatedColumn;\n\n if (segment.length > 1) {\n // Original source.\n mapping.source = previousSource + segment[1];\n previousSource += segment[1];\n\n // Original line.\n mapping.originalLine = previousOriginalLine + segment[2];\n previousOriginalLine = mapping.originalLine;\n // Lines are stored 0-based\n mapping.originalLine += 1;\n\n // Original column.\n mapping.originalColumn = previousOriginalColumn + segment[3];\n previousOriginalColumn = mapping.originalColumn;\n\n if (segment.length > 4) {\n // Original name.\n mapping.name = previousName + segment[4];\n previousName += segment[4];\n }\n }\n\n generatedMappings.push(mapping);\n if (typeof mapping.originalLine === 'number') {\n originalMappings.push(mapping);\n }\n }\n }\n\n quickSort(generatedMappings, util.compareByGeneratedPositionsDeflated);\n this.__generatedMappings = generatedMappings;\n\n quickSort(originalMappings, util.compareByOriginalPositions);\n this.__originalMappings = originalMappings;\n };\n\n/**\n * Find the mapping that best matches the hypothetical \"needle\" mapping that\n * we are searching for in the given \"haystack\" of mappings.\n */\nBasicSourceMapConsumer.prototype._findMapping =\n function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName,\n aColumnName, aComparator, aBias) {\n // To return the position we are searching for, we must first find the\n // mapping for the given position and then return the opposite position it\n // points to. Because the mappings are sorted, we can use binary search to\n // find the best mapping.\n\n if (aNeedle[aLineName] <= 0) {\n throw new TypeError('Line must be greater than or equal to 1, got '\n + aNeedle[aLineName]);\n }\n if (aNeedle[aColumnName] < 0) {\n throw new TypeError('Column must be greater than or equal to 0, got '\n + aNeedle[aColumnName]);\n }\n\n return binarySearch.search(aNeedle, aMappings, aComparator, aBias);\n };\n\n/**\n * Compute the last column for each generated mapping. The last column is\n * inclusive.\n */\nBasicSourceMapConsumer.prototype.computeColumnSpans =\n function SourceMapConsumer_computeColumnSpans() {\n for (var index = 0; index < this._generatedMappings.length; ++index) {\n var mapping = this._generatedMappings[index];\n\n // Mappings do not contain a field for the last generated columnt. We\n // can come up with an optimistic estimate, however, by assuming that\n // mappings are contiguous (i.e. given two consecutive mappings, the\n // first mapping ends where the second one starts).\n if (index + 1 < this._generatedMappings.length) {\n var nextMapping = this._generatedMappings[index + 1];\n\n if (mapping.generatedLine === nextMapping.generatedLine) {\n mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1;\n continue;\n }\n }\n\n // The last mapping for each line spans the entire line.\n mapping.lastGeneratedColumn = Infinity;\n }\n };\n\n/**\n * Returns the original source, line, and column information for the generated\n * source's line and column positions provided. The only argument is an object\n * with the following properties:\n *\n * - line: The line number in the generated source. The line number\n * is 1-based.\n * - column: The column number in the generated source. The column\n * number is 0-based.\n * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or\n * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the\n * closest element that is smaller than or greater than the one we are\n * searching for, respectively, if the exact element cannot be found.\n * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.\n *\n * and an object is returned with the following properties:\n *\n * - source: The original source file, or null.\n * - line: The line number in the original source, or null. The\n * line number is 1-based.\n * - column: The column number in the original source, or null. The\n * column number is 0-based.\n * - name: The original identifier, or null.\n */\nBasicSourceMapConsumer.prototype.originalPositionFor =\n function SourceMapConsumer_originalPositionFor(aArgs) {\n var needle = {\n generatedLine: util.getArg(aArgs, 'line'),\n generatedColumn: util.getArg(aArgs, 'column')\n };\n\n var index = this._findMapping(\n needle,\n this._generatedMappings,\n \"generatedLine\",\n \"generatedColumn\",\n util.compareByGeneratedPositionsDeflated,\n util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)\n );\n\n if (index >= 0) {\n var mapping = this._generatedMappings[index];\n\n if (mapping.generatedLine === needle.generatedLine) {\n var source = util.getArg(mapping, 'source', null);\n if (source !== null) {\n source = this._sources.at(source);\n source = util.computeSourceURL(this.sourceRoot, source, this._sourceMapURL);\n }\n var name = util.getArg(mapping, 'name', null);\n if (name !== null) {\n name = this._names.at(name);\n }\n return {\n source: source,\n line: util.getArg(mapping, 'originalLine', null),\n column: util.getArg(mapping, 'originalColumn', null),\n name: name\n };\n }\n }\n\n return {\n source: null,\n line: null,\n column: null,\n name: null\n };\n };\n\n/**\n * Return true if we have the source content for every source in the source\n * map, false otherwise.\n */\nBasicSourceMapConsumer.prototype.hasContentsOfAllSources =\n function BasicSourceMapConsumer_hasContentsOfAllSources() {\n if (!this.sourcesContent) {\n return false;\n }\n return this.sourcesContent.length >= this._sources.size() &&\n !this.sourcesContent.some(function (sc) { return sc == null; });\n };\n\n/**\n * Returns the original source content. The only argument is the url of the\n * original source file. Returns null if no original source content is\n * available.\n */\nBasicSourceMapConsumer.prototype.sourceContentFor =\n function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {\n if (!this.sourcesContent) {\n return null;\n }\n\n var index = this._findSourceIndex(aSource);\n if (index >= 0) {\n return this.sourcesContent[index];\n }\n\n var relativeSource = aSource;\n if (this.sourceRoot != null) {\n relativeSource = util.relative(this.sourceRoot, relativeSource);\n }\n\n var url;\n if (this.sourceRoot != null\n && (url = util.urlParse(this.sourceRoot))) {\n // XXX: file:// URIs and absolute paths lead to unexpected behavior for\n // many users. We can help them out when they expect file:// URIs to\n // behave like it would if they were running a local HTTP server. See\n // https://bugzilla.mozilla.org/show_bug.cgi?id=885597.\n var fileUriAbsPath = relativeSource.replace(/^file:\\/\\//, \"\");\n if (url.scheme == \"file\"\n && this._sources.has(fileUriAbsPath)) {\n return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)]\n }\n\n if ((!url.path || url.path == \"/\")\n && this._sources.has(\"/\" + relativeSource)) {\n return this.sourcesContent[this._sources.indexOf(\"/\" + relativeSource)];\n }\n }\n\n // This function is used recursively from\n // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we\n // don't want to throw if we can't find the source - we just want to\n // return null, so we provide a flag to exit gracefully.\n if (nullOnMissing) {\n return null;\n }\n else {\n throw new Error('\"' + relativeSource + '\" is not in the SourceMap.');\n }\n };\n\n/**\n * Returns the generated line and column information for the original source,\n * line, and column positions provided. The only argument is an object with\n * the following properties:\n *\n * - source: The filename of the original source.\n * - line: The line number in the original source. The line number\n * is 1-based.\n * - column: The column number in the original source. The column\n * number is 0-based.\n * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or\n * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the\n * closest element that is smaller than or greater than the one we are\n * searching for, respectively, if the exact element cannot be found.\n * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.\n *\n * and an object is returned with the following properties:\n *\n * - line: The line number in the generated source, or null. The\n * line number is 1-based.\n * - column: The column number in the generated source, or null.\n * The column number is 0-based.\n */\nBasicSourceMapConsumer.prototype.generatedPositionFor =\n function SourceMapConsumer_generatedPositionFor(aArgs) {\n var source = util.getArg(aArgs, 'source');\n source = this._findSourceIndex(source);\n if (source < 0) {\n return {\n line: null,\n column: null,\n lastColumn: null\n };\n }\n\n var needle = {\n source: source,\n originalLine: util.getArg(aArgs, 'line'),\n originalColumn: util.getArg(aArgs, 'column')\n };\n\n var index = this._findMapping(\n needle,\n this._originalMappings,\n \"originalLine\",\n \"originalColumn\",\n util.compareByOriginalPositions,\n util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)\n );\n\n if (index >= 0) {\n var mapping = this._originalMappings[index];\n\n if (mapping.source === needle.source) {\n return {\n line: util.getArg(mapping, 'generatedLine', null),\n column: util.getArg(mapping, 'generatedColumn', null),\n lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)\n };\n }\n }\n\n return {\n line: null,\n column: null,\n lastColumn: null\n };\n };\n\nexports.BasicSourceMapConsumer = BasicSourceMapConsumer;\n\n/**\n * An IndexedSourceMapConsumer instance represents a parsed source map which\n * we can query for information. It differs from BasicSourceMapConsumer in\n * that it takes \"indexed\" source maps (i.e. ones with a \"sections\" field) as\n * input.\n *\n * The first parameter is a raw source map (either as a JSON string, or already\n * parsed to an object). According to the spec for indexed source maps, they\n * have the following attributes:\n *\n * - version: Which version of the source map spec this map is following.\n * - file: Optional. The generated file this source map is associated with.\n * - sections: A list of section definitions.\n *\n * Each value under the \"sections\" field has two fields:\n * - offset: The offset into the original specified at which this section\n * begins to apply, defined as an object with a \"line\" and \"column\"\n * field.\n * - map: A source map definition. This source map could also be indexed,\n * but doesn't have to be.\n *\n * Instead of the \"map\" field, it's also possible to have a \"url\" field\n * specifying a URL to retrieve a source map from, but that's currently\n * unsupported.\n *\n * Here's an example source map, taken from the source map spec[0], but\n * modified to omit a section which uses the \"url\" field.\n *\n * {\n * version : 3,\n * file: \"app.js\",\n * sections: [{\n * offset: {line:100, column:10},\n * map: {\n * version : 3,\n * file: \"section.js\",\n * sources: [\"foo.js\", \"bar.js\"],\n * names: [\"src\", \"maps\", \"are\", \"fun\"],\n * mappings: \"AAAA,E;;ABCDE;\"\n * }\n * }],\n * }\n *\n * The second parameter, if given, is a string whose value is the URL\n * at which the source map was found. This URL is used to compute the\n * sources array.\n *\n * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt\n */\nfunction IndexedSourceMapConsumer(aSourceMap, aSourceMapURL) {\n var sourceMap = aSourceMap;\n if (typeof aSourceMap === 'string') {\n sourceMap = util.parseSourceMapInput(aSourceMap);\n }\n\n var version = util.getArg(sourceMap, 'version');\n var sections = util.getArg(sourceMap, 'sections');\n\n if (version != this._version) {\n throw new Error('Unsupported version: ' + version);\n }\n\n this._sources = new ArraySet();\n this._names = new ArraySet();\n\n var lastOffset = {\n line: -1,\n column: 0\n };\n this._sections = sections.map(function (s) {\n if (s.url) {\n // The url field will require support for asynchronicity.\n // See https://github.com/mozilla/source-map/issues/16\n throw new Error('Support for url field in sections not implemented.');\n }\n var offset = util.getArg(s, 'offset');\n var offsetLine = util.getArg(offset, 'line');\n var offsetColumn = util.getArg(offset, 'column');\n\n if (offsetLine < lastOffset.line ||\n (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) {\n throw new Error('Section offsets must be ordered and non-overlapping.');\n }\n lastOffset = offset;\n\n return {\n generatedOffset: {\n // The offset fields are 0-based, but we use 1-based indices when\n // encoding/decoding from VLQ.\n generatedLine: offsetLine + 1,\n generatedColumn: offsetColumn + 1\n },\n consumer: new SourceMapConsumer(util.getArg(s, 'map'), aSourceMapURL)\n }\n });\n}\n\nIndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);\nIndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer;\n\n/**\n * The version of the source mapping spec that we are consuming.\n */\nIndexedSourceMapConsumer.prototype._version = 3;\n\n/**\n * The list of original sources.\n */\nObject.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', {\n get: function () {\n var sources = [];\n for (var i = 0; i < this._sections.length; i++) {\n for (var j = 0; j < this._sections[i].consumer.sources.length; j++) {\n sources.push(this._sections[i].consumer.sources[j]);\n }\n }\n return sources;\n }\n});\n\n/**\n * Returns the original source, line, and column information for the generated\n * source's line and column positions provided. The only argument is an object\n * with the following properties:\n *\n * - line: The line number in the generated source. The line number\n * is 1-based.\n * - column: The column number in the generated source. The column\n * number is 0-based.\n *\n * and an object is returned with the following properties:\n *\n * - source: The original source file, or null.\n * - line: The line number in the original source, or null. The\n * line number is 1-based.\n * - column: The column number in the original source, or null. The\n * column number is 0-based.\n * - name: The original identifier, or null.\n */\nIndexedSourceMapConsumer.prototype.originalPositionFor =\n function IndexedSourceMapConsumer_originalPositionFor(aArgs) {\n var needle = {\n generatedLine: util.getArg(aArgs, 'line'),\n generatedColumn: util.getArg(aArgs, 'column')\n };\n\n // Find the section containing the generated position we're trying to map\n // to an original position.\n var sectionIndex = binarySearch.search(needle, this._sections,\n function(needle, section) {\n var cmp = needle.generatedLine - section.generatedOffset.generatedLine;\n if (cmp) {\n return cmp;\n }\n\n return (needle.generatedColumn -\n section.generatedOffset.generatedColumn);\n });\n var section = this._sections[sectionIndex];\n\n if (!section) {\n return {\n source: null,\n line: null,\n column: null,\n name: null\n };\n }\n\n return section.consumer.originalPositionFor({\n line: needle.generatedLine -\n (section.generatedOffset.generatedLine - 1),\n column: needle.generatedColumn -\n (section.generatedOffset.generatedLine === needle.generatedLine\n ? section.generatedOffset.generatedColumn - 1\n : 0),\n bias: aArgs.bias\n });\n };\n\n/**\n * Return true if we have the source content for every source in the source\n * map, false otherwise.\n */\nIndexedSourceMapConsumer.prototype.hasContentsOfAllSources =\n function IndexedSourceMapConsumer_hasContentsOfAllSources() {\n return this._sections.every(function (s) {\n return s.consumer.hasContentsOfAllSources();\n });\n };\n\n/**\n * Returns the original source content. The only argument is the url of the\n * original source file. Returns null if no original source content is\n * available.\n */\nIndexedSourceMapConsumer.prototype.sourceContentFor =\n function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {\n for (var i = 0; i < this._sections.length; i++) {\n var section = this._sections[i];\n\n var content = section.consumer.sourceContentFor(aSource, true);\n if (content) {\n return content;\n }\n }\n if (nullOnMissing) {\n return null;\n }\n else {\n throw new Error('\"' + aSource + '\" is not in the SourceMap.');\n }\n };\n\n/**\n * Returns the generated line and column information for the original source,\n * line, and column positions provided. The only argument is an object with\n * the following properties:\n *\n * - source: The filename of the original source.\n * - line: The line number in the original source. The line number\n * is 1-based.\n * - column: The column number in the original source. The column\n * number is 0-based.\n *\n * and an object is returned with the following properties:\n *\n * - line: The line number in the generated source, or null. The\n * line number is 1-based. \n * - column: The column number in the generated source, or null.\n * The column number is 0-based.\n */\nIndexedSourceMapConsumer.prototype.generatedPositionFor =\n function IndexedSourceMapConsumer_generatedPositionFor(aArgs) {\n for (var i = 0; i < this._sections.length; i++) {\n var section = this._sections[i];\n\n // Only consider this section if the requested source is in the list of\n // sources of the consumer.\n if (section.consumer._findSourceIndex(util.getArg(aArgs, 'source')) === -1) {\n continue;\n }\n var generatedPosition = section.consumer.generatedPositionFor(aArgs);\n if (generatedPosition) {\n var ret = {\n line: generatedPosition.line +\n (section.generatedOffset.generatedLine - 1),\n column: generatedPosition.column +\n (section.generatedOffset.generatedLine === generatedPosition.line\n ? section.generatedOffset.generatedColumn - 1\n : 0)\n };\n return ret;\n }\n }\n\n return {\n line: null,\n column: null\n };\n };\n\n/**\n * Parse the mappings in a string in to a data structure which we can easily\n * query (the ordered arrays in the `this.__generatedMappings` and\n * `this.__originalMappings` properties).\n */\nIndexedSourceMapConsumer.prototype._parseMappings =\n function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) {\n this.__generatedMappings = [];\n this.__originalMappings = [];\n for (var i = 0; i < this._sections.length; i++) {\n var section = this._sections[i];\n var sectionMappings = section.consumer._generatedMappings;\n for (var j = 0; j < sectionMappings.length; j++) {\n var mapping = sectionMappings[j];\n\n var source = section.consumer._sources.at(mapping.source);\n source = util.computeSourceURL(section.consumer.sourceRoot, source, this._sourceMapURL);\n this._sources.add(source);\n source = this._sources.indexOf(source);\n\n var name = null;\n if (mapping.name) {\n name = section.consumer._names.at(mapping.name);\n this._names.add(name);\n name = this._names.indexOf(name);\n }\n\n // The mappings coming from the consumer for the section have\n // generated positions relative to the start of the section, so we\n // need to offset them to be relative to the start of the concatenated\n // generated file.\n var adjustedMapping = {\n source: source,\n generatedLine: mapping.generatedLine +\n (section.generatedOffset.generatedLine - 1),\n generatedColumn: mapping.generatedColumn +\n (section.generatedOffset.generatedLine === mapping.generatedLine\n ? section.generatedOffset.generatedColumn - 1\n : 0),\n originalLine: mapping.originalLine,\n originalColumn: mapping.originalColumn,\n name: name\n };\n\n this.__generatedMappings.push(adjustedMapping);\n if (typeof adjustedMapping.originalLine === 'number') {\n this.__originalMappings.push(adjustedMapping);\n }\n }\n }\n\n quickSort(this.__generatedMappings, util.compareByGeneratedPositionsDeflated);\n quickSort(this.__originalMappings, util.compareByOriginalPositions);\n };\n\nexports.IndexedSourceMapConsumer = IndexedSourceMapConsumer;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./lib/source-map-consumer.js\n// module id = 7\n// module chunks = 0","/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\nexports.GREATEST_LOWER_BOUND = 1;\nexports.LEAST_UPPER_BOUND = 2;\n\n/**\n * Recursive implementation of binary search.\n *\n * @param aLow Indices here and lower do not contain the needle.\n * @param aHigh Indices here and higher do not contain the needle.\n * @param aNeedle The element being searched for.\n * @param aHaystack The non-empty array being searched.\n * @param aCompare Function which takes two elements and returns -1, 0, or 1.\n * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or\n * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the\n * closest element that is smaller than or greater than the one we are\n * searching for, respectively, if the exact element cannot be found.\n */\nfunction recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) {\n // This function terminates when one of the following is true:\n //\n // 1. We find the exact element we are looking for.\n //\n // 2. We did not find the exact element, but we can return the index of\n // the next-closest element.\n //\n // 3. We did not find the exact element, and there is no next-closest\n // element than the one we are searching for, so we return -1.\n var mid = Math.floor((aHigh - aLow) / 2) + aLow;\n var cmp = aCompare(aNeedle, aHaystack[mid], true);\n if (cmp === 0) {\n // Found the element we are looking for.\n return mid;\n }\n else if (cmp > 0) {\n // Our needle is greater than aHaystack[mid].\n if (aHigh - mid > 1) {\n // The element is in the upper half.\n return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias);\n }\n\n // The exact needle element was not found in this haystack. Determine if\n // we are in termination case (3) or (2) and return the appropriate thing.\n if (aBias == exports.LEAST_UPPER_BOUND) {\n return aHigh < aHaystack.length ? aHigh : -1;\n } else {\n return mid;\n }\n }\n else {\n // Our needle is less than aHaystack[mid].\n if (mid - aLow > 1) {\n // The element is in the lower half.\n return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias);\n }\n\n // we are in termination case (3) or (2) and return the appropriate thing.\n if (aBias == exports.LEAST_UPPER_BOUND) {\n return mid;\n } else {\n return aLow < 0 ? -1 : aLow;\n }\n }\n}\n\n/**\n * This is an implementation of binary search which will always try and return\n * the index of the closest element if there is no exact hit. This is because\n * mappings between original and generated line/col pairs are single points,\n * and there is an implicit region between each of them, so a miss just means\n * that you aren't on the very start of a region.\n *\n * @param aNeedle The element you are looking for.\n * @param aHaystack The array that is being searched.\n * @param aCompare A function which takes the needle and an element in the\n * array and returns -1, 0, or 1 depending on whether the needle is less\n * than, equal to, or greater than the element, respectively.\n * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or\n * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the\n * closest element that is smaller than or greater than the one we are\n * searching for, respectively, if the exact element cannot be found.\n * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'.\n */\nexports.search = function search(aNeedle, aHaystack, aCompare, aBias) {\n if (aHaystack.length === 0) {\n return -1;\n }\n\n var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack,\n aCompare, aBias || exports.GREATEST_LOWER_BOUND);\n if (index < 0) {\n return -1;\n }\n\n // We have found either the exact element, or the next-closest element than\n // the one we are searching for. However, there may be more than one such\n // element. Make sure we always return the smallest of these.\n while (index - 1 >= 0) {\n if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) {\n break;\n }\n --index;\n }\n\n return index;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./lib/binary-search.js\n// module id = 8\n// module chunks = 0","/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\n// It turns out that some (most?) JavaScript engines don't self-host\n// `Array.prototype.sort`. This makes sense because C++ will likely remain\n// faster than JS when doing raw CPU-intensive sorting. However, when using a\n// custom comparator function, calling back and forth between the VM's C++ and\n// JIT'd JS is rather slow *and* loses JIT type information, resulting in\n// worse generated code for the comparator function than would be optimal. In\n// fact, when sorting with a comparator, these costs outweigh the benefits of\n// sorting in C++. By using our own JS-implemented Quick Sort (below), we get\n// a ~3500ms mean speed-up in `bench/bench.html`.\n\n/**\n * Swap the elements indexed by `x` and `y` in the array `ary`.\n *\n * @param {Array} ary\n * The array.\n * @param {Number} x\n * The index of the first item.\n * @param {Number} y\n * The index of the second item.\n */\nfunction swap(ary, x, y) {\n var temp = ary[x];\n ary[x] = ary[y];\n ary[y] = temp;\n}\n\n/**\n * Returns a random integer within the range `low .. high` inclusive.\n *\n * @param {Number} low\n * The lower bound on the range.\n * @param {Number} high\n * The upper bound on the range.\n */\nfunction randomIntInRange(low, high) {\n return Math.round(low + (Math.random() * (high - low)));\n}\n\n/**\n * The Quick Sort algorithm.\n *\n * @param {Array} ary\n * An array to sort.\n * @param {function} comparator\n * Function to use to compare two items.\n * @param {Number} p\n * Start index of the array\n * @param {Number} r\n * End index of the array\n */\nfunction doQuickSort(ary, comparator, p, r) {\n // If our lower bound is less than our upper bound, we (1) partition the\n // array into two pieces and (2) recurse on each half. If it is not, this is\n // the empty array and our base case.\n\n if (p < r) {\n // (1) Partitioning.\n //\n // The partitioning chooses a pivot between `p` and `r` and moves all\n // elements that are less than or equal to the pivot to the before it, and\n // all the elements that are greater than it after it. The effect is that\n // once partition is done, the pivot is in the exact place it will be when\n // the array is put in sorted order, and it will not need to be moved\n // again. This runs in O(n) time.\n\n // Always choose a random pivot so that an input array which is reverse\n // sorted does not cause O(n^2) running time.\n var pivotIndex = randomIntInRange(p, r);\n var i = p - 1;\n\n swap(ary, pivotIndex, r);\n var pivot = ary[r];\n\n // Immediately after `j` is incremented in this loop, the following hold\n // true:\n //\n // * Every element in `ary[p .. i]` is less than or equal to the pivot.\n //\n // * Every element in `ary[i+1 .. j-1]` is greater than the pivot.\n for (var j = p; j < r; j++) {\n if (comparator(ary[j], pivot) <= 0) {\n i += 1;\n swap(ary, i, j);\n }\n }\n\n swap(ary, i + 1, j);\n var q = i + 1;\n\n // (2) Recurse on each half.\n\n doQuickSort(ary, comparator, p, q - 1);\n doQuickSort(ary, comparator, q + 1, r);\n }\n}\n\n/**\n * Sort the given array in-place with the given comparator function.\n *\n * @param {Array} ary\n * An array to sort.\n * @param {function} comparator\n * Function to use to compare two items.\n */\nexports.quickSort = function (ary, comparator) {\n doQuickSort(ary, comparator, 0, ary.length - 1);\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./lib/quick-sort.js\n// module id = 9\n// module chunks = 0","/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\nvar SourceMapGenerator = require('./source-map-generator').SourceMapGenerator;\nvar util = require('./util');\n\n// Matches a Windows-style `\\r\\n` newline or a `\\n` newline used by all other\n// operating systems these days (capturing the result).\nvar REGEX_NEWLINE = /(\\r?\\n)/;\n\n// Newline character code for charCodeAt() comparisons\nvar NEWLINE_CODE = 10;\n\n// Private symbol for identifying `SourceNode`s when multiple versions of\n// the source-map library are loaded. This MUST NOT CHANGE across\n// versions!\nvar isSourceNode = \"$$$isSourceNode$$$\";\n\n/**\n * SourceNodes provide a way to abstract over interpolating/concatenating\n * snippets of generated JavaScript source code while maintaining the line and\n * column information associated with the original source code.\n *\n * @param aLine The original line number.\n * @param aColumn The original column number.\n * @param aSource The original source's filename.\n * @param aChunks Optional. An array of strings which are snippets of\n * generated JS, or other SourceNodes.\n * @param aName The original identifier.\n */\nfunction SourceNode(aLine, aColumn, aSource, aChunks, aName) {\n this.children = [];\n this.sourceContents = {};\n this.line = aLine == null ? null : aLine;\n this.column = aColumn == null ? null : aColumn;\n this.source = aSource == null ? null : aSource;\n this.name = aName == null ? null : aName;\n this[isSourceNode] = true;\n if (aChunks != null) this.add(aChunks);\n}\n\n/**\n * Creates a SourceNode from generated code and a SourceMapConsumer.\n *\n * @param aGeneratedCode The generated code\n * @param aSourceMapConsumer The SourceMap for the generated code\n * @param aRelativePath Optional. The path that relative sources in the\n * SourceMapConsumer should be relative to.\n */\nSourceNode.fromStringWithSourceMap =\n function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) {\n // The SourceNode we want to fill with the generated code\n // and the SourceMap\n var node = new SourceNode();\n\n // All even indices of this array are one line of the generated code,\n // while all odd indices are the newlines between two adjacent lines\n // (since `REGEX_NEWLINE` captures its match).\n // Processed fragments are accessed by calling `shiftNextLine`.\n var remainingLines = aGeneratedCode.split(REGEX_NEWLINE);\n var remainingLinesIndex = 0;\n var shiftNextLine = function() {\n var lineContents = getNextLine();\n // The last line of a file might not have a newline.\n var newLine = getNextLine() || \"\";\n return lineContents + newLine;\n\n function getNextLine() {\n return remainingLinesIndex < remainingLines.length ?\n remainingLines[remainingLinesIndex++] : undefined;\n }\n };\n\n // We need to remember the position of \"remainingLines\"\n var lastGeneratedLine = 1, lastGeneratedColumn = 0;\n\n // The generate SourceNodes we need a code range.\n // To extract it current and last mapping is used.\n // Here we store the last mapping.\n var lastMapping = null;\n\n aSourceMapConsumer.eachMapping(function (mapping) {\n if (lastMapping !== null) {\n // We add the code from \"lastMapping\" to \"mapping\":\n // First check if there is a new line in between.\n if (lastGeneratedLine < mapping.generatedLine) {\n // Associate first line with \"lastMapping\"\n addMappingWithCode(lastMapping, shiftNextLine());\n lastGeneratedLine++;\n lastGeneratedColumn = 0;\n // The remaining code is added without mapping\n } else {\n // There is no new line in between.\n // Associate the code between \"lastGeneratedColumn\" and\n // \"mapping.generatedColumn\" with \"lastMapping\"\n var nextLine = remainingLines[remainingLinesIndex] || '';\n var code = nextLine.substr(0, mapping.generatedColumn -\n lastGeneratedColumn);\n remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn -\n lastGeneratedColumn);\n lastGeneratedColumn = mapping.generatedColumn;\n addMappingWithCode(lastMapping, code);\n // No more remaining code, continue\n lastMapping = mapping;\n return;\n }\n }\n // We add the generated code until the first mapping\n // to the SourceNode without any mapping.\n // Each line is added as separate string.\n while (lastGeneratedLine < mapping.generatedLine) {\n node.add(shiftNextLine());\n lastGeneratedLine++;\n }\n if (lastGeneratedColumn < mapping.generatedColumn) {\n var nextLine = remainingLines[remainingLinesIndex] || '';\n node.add(nextLine.substr(0, mapping.generatedColumn));\n remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn);\n lastGeneratedColumn = mapping.generatedColumn;\n }\n lastMapping = mapping;\n }, this);\n // We have processed all mappings.\n if (remainingLinesIndex < remainingLines.length) {\n if (lastMapping) {\n // Associate the remaining code in the current line with \"lastMapping\"\n addMappingWithCode(lastMapping, shiftNextLine());\n }\n // and add the remaining lines without any mapping\n node.add(remainingLines.splice(remainingLinesIndex).join(\"\"));\n }\n\n // Copy sourcesContent into SourceNode\n aSourceMapConsumer.sources.forEach(function (sourceFile) {\n var content = aSourceMapConsumer.sourceContentFor(sourceFile);\n if (content != null) {\n if (aRelativePath != null) {\n sourceFile = util.join(aRelativePath, sourceFile);\n }\n node.setSourceContent(sourceFile, content);\n }\n });\n\n return node;\n\n function addMappingWithCode(mapping, code) {\n if (mapping === null || mapping.source === undefined) {\n node.add(code);\n } else {\n var source = aRelativePath\n ? util.join(aRelativePath, mapping.source)\n : mapping.source;\n node.add(new SourceNode(mapping.originalLine,\n mapping.originalColumn,\n source,\n code,\n mapping.name));\n }\n }\n };\n\n/**\n * Add a chunk of generated JS to this source node.\n *\n * @param aChunk A string snippet of generated JS code, another instance of\n * SourceNode, or an array where each member is one of those things.\n */\nSourceNode.prototype.add = function SourceNode_add(aChunk) {\n if (Array.isArray(aChunk)) {\n aChunk.forEach(function (chunk) {\n this.add(chunk);\n }, this);\n }\n else if (aChunk[isSourceNode] || typeof aChunk === \"string\") {\n if (aChunk) {\n this.children.push(aChunk);\n }\n }\n else {\n throw new TypeError(\n \"Expected a SourceNode, string, or an array of SourceNodes and strings. Got \" + aChunk\n );\n }\n return this;\n};\n\n/**\n * Add a chunk of generated JS to the beginning of this source node.\n *\n * @param aChunk A string snippet of generated JS code, another instance of\n * SourceNode, or an array where each member is one of those things.\n */\nSourceNode.prototype.prepend = function SourceNode_prepend(aChunk) {\n if (Array.isArray(aChunk)) {\n for (var i = aChunk.length-1; i >= 0; i--) {\n this.prepend(aChunk[i]);\n }\n }\n else if (aChunk[isSourceNode] || typeof aChunk === \"string\") {\n this.children.unshift(aChunk);\n }\n else {\n throw new TypeError(\n \"Expected a SourceNode, string, or an array of SourceNodes and strings. Got \" + aChunk\n );\n }\n return this;\n};\n\n/**\n * Walk over the tree of JS snippets in this node and its children. The\n * walking function is called once for each snippet of JS and is passed that\n * snippet and the its original associated source's line/column location.\n *\n * @param aFn The traversal function.\n */\nSourceNode.prototype.walk = function SourceNode_walk(aFn) {\n var chunk;\n for (var i = 0, len = this.children.length; i < len; i++) {\n chunk = this.children[i];\n if (chunk[isSourceNode]) {\n chunk.walk(aFn);\n }\n else {\n if (chunk !== '') {\n aFn(chunk, { source: this.source,\n line: this.line,\n column: this.column,\n name: this.name });\n }\n }\n }\n};\n\n/**\n * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between\n * each of `this.children`.\n *\n * @param aSep The separator.\n */\nSourceNode.prototype.join = function SourceNode_join(aSep) {\n var newChildren;\n var i;\n var len = this.children.length;\n if (len > 0) {\n newChildren = [];\n for (i = 0; i < len-1; i++) {\n newChildren.push(this.children[i]);\n newChildren.push(aSep);\n }\n newChildren.push(this.children[i]);\n this.children = newChildren;\n }\n return this;\n};\n\n/**\n * Call String.prototype.replace on the very right-most source snippet. Useful\n * for trimming whitespace from the end of a source node, etc.\n *\n * @param aPattern The pattern to replace.\n * @param aReplacement The thing to replace the pattern with.\n */\nSourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) {\n var lastChild = this.children[this.children.length - 1];\n if (lastChild[isSourceNode]) {\n lastChild.replaceRight(aPattern, aReplacement);\n }\n else if (typeof lastChild === 'string') {\n this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement);\n }\n else {\n this.children.push(''.replace(aPattern, aReplacement));\n }\n return this;\n};\n\n/**\n * Set the source content for a source file. This will be added to the SourceMapGenerator\n * in the sourcesContent field.\n *\n * @param aSourceFile The filename of the source file\n * @param aSourceContent The content of the source file\n */\nSourceNode.prototype.setSourceContent =\n function SourceNode_setSourceContent(aSourceFile, aSourceContent) {\n this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent;\n };\n\n/**\n * Walk over the tree of SourceNodes. The walking function is called for each\n * source file content and is passed the filename and source content.\n *\n * @param aFn The traversal function.\n */\nSourceNode.prototype.walkSourceContents =\n function SourceNode_walkSourceContents(aFn) {\n for (var i = 0, len = this.children.length; i < len; i++) {\n if (this.children[i][isSourceNode]) {\n this.children[i].walkSourceContents(aFn);\n }\n }\n\n var sources = Object.keys(this.sourceContents);\n for (var i = 0, len = sources.length; i < len; i++) {\n aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]);\n }\n };\n\n/**\n * Return the string representation of this source node. Walks over the tree\n * and concatenates all the various snippets together to one string.\n */\nSourceNode.prototype.toString = function SourceNode_toString() {\n var str = \"\";\n this.walk(function (chunk) {\n str += chunk;\n });\n return str;\n};\n\n/**\n * Returns the string representation of this source node along with a source\n * map.\n */\nSourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) {\n var generated = {\n code: \"\",\n line: 1,\n column: 0\n };\n var map = new SourceMapGenerator(aArgs);\n var sourceMappingActive = false;\n var lastOriginalSource = null;\n var lastOriginalLine = null;\n var lastOriginalColumn = null;\n var lastOriginalName = null;\n this.walk(function (chunk, original) {\n generated.code += chunk;\n if (original.source !== null\n && original.line !== null\n && original.column !== null) {\n if(lastOriginalSource !== original.source\n || lastOriginalLine !== original.line\n || lastOriginalColumn !== original.column\n || lastOriginalName !== original.name) {\n map.addMapping({\n source: original.source,\n original: {\n line: original.line,\n column: original.column\n },\n generated: {\n line: generated.line,\n column: generated.column\n },\n name: original.name\n });\n }\n lastOriginalSource = original.source;\n lastOriginalLine = original.line;\n lastOriginalColumn = original.column;\n lastOriginalName = original.name;\n sourceMappingActive = true;\n } else if (sourceMappingActive) {\n map.addMapping({\n generated: {\n line: generated.line,\n column: generated.column\n }\n });\n lastOriginalSource = null;\n sourceMappingActive = false;\n }\n for (var idx = 0, length = chunk.length; idx < length; idx++) {\n if (chunk.charCodeAt(idx) === NEWLINE_CODE) {\n generated.line++;\n generated.column = 0;\n // Mappings end at eol\n if (idx + 1 === length) {\n lastOriginalSource = null;\n sourceMappingActive = false;\n } else if (sourceMappingActive) {\n map.addMapping({\n source: original.source,\n original: {\n line: original.line,\n column: original.column\n },\n generated: {\n line: generated.line,\n column: generated.column\n },\n name: original.name\n });\n }\n } else {\n generated.column++;\n }\n }\n });\n this.walkSourceContents(function (sourceFile, sourceContent) {\n map.setSourceContent(sourceFile, sourceContent);\n });\n\n return { code: generated.code, map: map };\n};\n\nexports.SourceNode = SourceNode;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./lib/source-node.js\n// module id = 10\n// module chunks = 0"],"sourceRoot":""} \ No newline at end of file diff --git a/node_modules/source-map/lib/array-set.js b/node_modules/source-map/lib/array-set.js new file mode 100644 index 0000000..fbd5c81 --- /dev/null +++ b/node_modules/source-map/lib/array-set.js @@ -0,0 +1,121 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +var util = require('./util'); +var has = Object.prototype.hasOwnProperty; +var hasNativeMap = typeof Map !== "undefined"; + +/** + * A data structure which is a combination of an array and a set. Adding a new + * member is O(1), testing for membership is O(1), and finding the index of an + * element is O(1). Removing elements from the set is not supported. Only + * strings are supported for membership. + */ +function ArraySet() { + this._array = []; + this._set = hasNativeMap ? new Map() : Object.create(null); +} + +/** + * Static method for creating ArraySet instances from an existing array. + */ +ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) { + var set = new ArraySet(); + for (var i = 0, len = aArray.length; i < len; i++) { + set.add(aArray[i], aAllowDuplicates); + } + return set; +}; + +/** + * Return how many unique items are in this ArraySet. If duplicates have been + * added, than those do not count towards the size. + * + * @returns Number + */ +ArraySet.prototype.size = function ArraySet_size() { + return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length; +}; + +/** + * Add the given string to this set. + * + * @param String aStr + */ +ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) { + var sStr = hasNativeMap ? aStr : util.toSetString(aStr); + var isDuplicate = hasNativeMap ? this.has(aStr) : has.call(this._set, sStr); + var idx = this._array.length; + if (!isDuplicate || aAllowDuplicates) { + this._array.push(aStr); + } + if (!isDuplicate) { + if (hasNativeMap) { + this._set.set(aStr, idx); + } else { + this._set[sStr] = idx; + } + } +}; + +/** + * Is the given string a member of this set? + * + * @param String aStr + */ +ArraySet.prototype.has = function ArraySet_has(aStr) { + if (hasNativeMap) { + return this._set.has(aStr); + } else { + var sStr = util.toSetString(aStr); + return has.call(this._set, sStr); + } +}; + +/** + * What is the index of the given string in the array? + * + * @param String aStr + */ +ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) { + if (hasNativeMap) { + var idx = this._set.get(aStr); + if (idx >= 0) { + return idx; + } + } else { + var sStr = util.toSetString(aStr); + if (has.call(this._set, sStr)) { + return this._set[sStr]; + } + } + + throw new Error('"' + aStr + '" is not in the set.'); +}; + +/** + * What is the element at the given index? + * + * @param Number aIdx + */ +ArraySet.prototype.at = function ArraySet_at(aIdx) { + if (aIdx >= 0 && aIdx < this._array.length) { + return this._array[aIdx]; + } + throw new Error('No element indexed by ' + aIdx); +}; + +/** + * Returns the array representation of this set (which has the proper indices + * indicated by indexOf). Note that this is a copy of the internal array used + * for storing the members so that no one can mess with internal state. + */ +ArraySet.prototype.toArray = function ArraySet_toArray() { + return this._array.slice(); +}; + +exports.ArraySet = ArraySet; diff --git a/node_modules/source-map/lib/base64-vlq.js b/node_modules/source-map/lib/base64-vlq.js new file mode 100644 index 0000000..612b404 --- /dev/null +++ b/node_modules/source-map/lib/base64-vlq.js @@ -0,0 +1,140 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + * + * Based on the Base 64 VLQ implementation in Closure Compiler: + * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java + * + * Copyright 2011 The Closure Compiler Authors. All rights reserved. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +var base64 = require('./base64'); + +// A single base 64 digit can contain 6 bits of data. For the base 64 variable +// length quantities we use in the source map spec, the first bit is the sign, +// the next four bits are the actual value, and the 6th bit is the +// continuation bit. The continuation bit tells us whether there are more +// digits in this value following this digit. +// +// Continuation +// | Sign +// | | +// V V +// 101011 + +var VLQ_BASE_SHIFT = 5; + +// binary: 100000 +var VLQ_BASE = 1 << VLQ_BASE_SHIFT; + +// binary: 011111 +var VLQ_BASE_MASK = VLQ_BASE - 1; + +// binary: 100000 +var VLQ_CONTINUATION_BIT = VLQ_BASE; + +/** + * Converts from a two-complement value to a value where the sign bit is + * placed in the least significant bit. For example, as decimals: + * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary) + * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary) + */ +function toVLQSigned(aValue) { + return aValue < 0 + ? ((-aValue) << 1) + 1 + : (aValue << 1) + 0; +} + +/** + * Converts to a two-complement value from a value where the sign bit is + * placed in the least significant bit. For example, as decimals: + * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1 + * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2 + */ +function fromVLQSigned(aValue) { + var isNegative = (aValue & 1) === 1; + var shifted = aValue >> 1; + return isNegative + ? -shifted + : shifted; +} + +/** + * Returns the base 64 VLQ encoded value. + */ +exports.encode = function base64VLQ_encode(aValue) { + var encoded = ""; + var digit; + + var vlq = toVLQSigned(aValue); + + do { + digit = vlq & VLQ_BASE_MASK; + vlq >>>= VLQ_BASE_SHIFT; + if (vlq > 0) { + // There are still more digits in this value, so we must make sure the + // continuation bit is marked. + digit |= VLQ_CONTINUATION_BIT; + } + encoded += base64.encode(digit); + } while (vlq > 0); + + return encoded; +}; + +/** + * Decodes the next base 64 VLQ value from the given string and returns the + * value and the rest of the string via the out parameter. + */ +exports.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) { + var strLen = aStr.length; + var result = 0; + var shift = 0; + var continuation, digit; + + do { + if (aIndex >= strLen) { + throw new Error("Expected more digits in base 64 VLQ value."); + } + + digit = base64.decode(aStr.charCodeAt(aIndex++)); + if (digit === -1) { + throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1)); + } + + continuation = !!(digit & VLQ_CONTINUATION_BIT); + digit &= VLQ_BASE_MASK; + result = result + (digit << shift); + shift += VLQ_BASE_SHIFT; + } while (continuation); + + aOutParam.value = fromVLQSigned(result); + aOutParam.rest = aIndex; +}; diff --git a/node_modules/source-map/lib/base64.js b/node_modules/source-map/lib/base64.js new file mode 100644 index 0000000..8aa86b3 --- /dev/null +++ b/node_modules/source-map/lib/base64.js @@ -0,0 +1,67 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +var intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split(''); + +/** + * Encode an integer in the range of 0 to 63 to a single base 64 digit. + */ +exports.encode = function (number) { + if (0 <= number && number < intToCharMap.length) { + return intToCharMap[number]; + } + throw new TypeError("Must be between 0 and 63: " + number); +}; + +/** + * Decode a single base 64 character code digit to an integer. Returns -1 on + * failure. + */ +exports.decode = function (charCode) { + var bigA = 65; // 'A' + var bigZ = 90; // 'Z' + + var littleA = 97; // 'a' + var littleZ = 122; // 'z' + + var zero = 48; // '0' + var nine = 57; // '9' + + var plus = 43; // '+' + var slash = 47; // '/' + + var littleOffset = 26; + var numberOffset = 52; + + // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ + if (bigA <= charCode && charCode <= bigZ) { + return (charCode - bigA); + } + + // 26 - 51: abcdefghijklmnopqrstuvwxyz + if (littleA <= charCode && charCode <= littleZ) { + return (charCode - littleA + littleOffset); + } + + // 52 - 61: 0123456789 + if (zero <= charCode && charCode <= nine) { + return (charCode - zero + numberOffset); + } + + // 62: + + if (charCode == plus) { + return 62; + } + + // 63: / + if (charCode == slash) { + return 63; + } + + // Invalid base64 digit. + return -1; +}; diff --git a/node_modules/source-map/lib/binary-search.js b/node_modules/source-map/lib/binary-search.js new file mode 100644 index 0000000..010ac94 --- /dev/null +++ b/node_modules/source-map/lib/binary-search.js @@ -0,0 +1,111 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +exports.GREATEST_LOWER_BOUND = 1; +exports.LEAST_UPPER_BOUND = 2; + +/** + * Recursive implementation of binary search. + * + * @param aLow Indices here and lower do not contain the needle. + * @param aHigh Indices here and higher do not contain the needle. + * @param aNeedle The element being searched for. + * @param aHaystack The non-empty array being searched. + * @param aCompare Function which takes two elements and returns -1, 0, or 1. + * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or + * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + */ +function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) { + // This function terminates when one of the following is true: + // + // 1. We find the exact element we are looking for. + // + // 2. We did not find the exact element, but we can return the index of + // the next-closest element. + // + // 3. We did not find the exact element, and there is no next-closest + // element than the one we are searching for, so we return -1. + var mid = Math.floor((aHigh - aLow) / 2) + aLow; + var cmp = aCompare(aNeedle, aHaystack[mid], true); + if (cmp === 0) { + // Found the element we are looking for. + return mid; + } + else if (cmp > 0) { + // Our needle is greater than aHaystack[mid]. + if (aHigh - mid > 1) { + // The element is in the upper half. + return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias); + } + + // The exact needle element was not found in this haystack. Determine if + // we are in termination case (3) or (2) and return the appropriate thing. + if (aBias == exports.LEAST_UPPER_BOUND) { + return aHigh < aHaystack.length ? aHigh : -1; + } else { + return mid; + } + } + else { + // Our needle is less than aHaystack[mid]. + if (mid - aLow > 1) { + // The element is in the lower half. + return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias); + } + + // we are in termination case (3) or (2) and return the appropriate thing. + if (aBias == exports.LEAST_UPPER_BOUND) { + return mid; + } else { + return aLow < 0 ? -1 : aLow; + } + } +} + +/** + * This is an implementation of binary search which will always try and return + * the index of the closest element if there is no exact hit. This is because + * mappings between original and generated line/col pairs are single points, + * and there is an implicit region between each of them, so a miss just means + * that you aren't on the very start of a region. + * + * @param aNeedle The element you are looking for. + * @param aHaystack The array that is being searched. + * @param aCompare A function which takes the needle and an element in the + * array and returns -1, 0, or 1 depending on whether the needle is less + * than, equal to, or greater than the element, respectively. + * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or + * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'. + */ +exports.search = function search(aNeedle, aHaystack, aCompare, aBias) { + if (aHaystack.length === 0) { + return -1; + } + + var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack, + aCompare, aBias || exports.GREATEST_LOWER_BOUND); + if (index < 0) { + return -1; + } + + // We have found either the exact element, or the next-closest element than + // the one we are searching for. However, there may be more than one such + // element. Make sure we always return the smallest of these. + while (index - 1 >= 0) { + if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) { + break; + } + --index; + } + + return index; +}; diff --git a/node_modules/source-map/lib/mapping-list.js b/node_modules/source-map/lib/mapping-list.js new file mode 100644 index 0000000..06d1274 --- /dev/null +++ b/node_modules/source-map/lib/mapping-list.js @@ -0,0 +1,79 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2014 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +var util = require('./util'); + +/** + * Determine whether mappingB is after mappingA with respect to generated + * position. + */ +function generatedPositionAfter(mappingA, mappingB) { + // Optimized for most common case + var lineA = mappingA.generatedLine; + var lineB = mappingB.generatedLine; + var columnA = mappingA.generatedColumn; + var columnB = mappingB.generatedColumn; + return lineB > lineA || lineB == lineA && columnB >= columnA || + util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0; +} + +/** + * A data structure to provide a sorted view of accumulated mappings in a + * performance conscious manner. It trades a neglibable overhead in general + * case for a large speedup in case of mappings being added in order. + */ +function MappingList() { + this._array = []; + this._sorted = true; + // Serves as infimum + this._last = {generatedLine: -1, generatedColumn: 0}; +} + +/** + * Iterate through internal items. This method takes the same arguments that + * `Array.prototype.forEach` takes. + * + * NOTE: The order of the mappings is NOT guaranteed. + */ +MappingList.prototype.unsortedForEach = + function MappingList_forEach(aCallback, aThisArg) { + this._array.forEach(aCallback, aThisArg); + }; + +/** + * Add the given source mapping. + * + * @param Object aMapping + */ +MappingList.prototype.add = function MappingList_add(aMapping) { + if (generatedPositionAfter(this._last, aMapping)) { + this._last = aMapping; + this._array.push(aMapping); + } else { + this._sorted = false; + this._array.push(aMapping); + } +}; + +/** + * Returns the flat, sorted array of mappings. The mappings are sorted by + * generated position. + * + * WARNING: This method returns internal data without copying, for + * performance. The return value must NOT be mutated, and should be treated as + * an immutable borrow. If you want to take ownership, you must make your own + * copy. + */ +MappingList.prototype.toArray = function MappingList_toArray() { + if (!this._sorted) { + this._array.sort(util.compareByGeneratedPositionsInflated); + this._sorted = true; + } + return this._array; +}; + +exports.MappingList = MappingList; diff --git a/node_modules/source-map/lib/quick-sort.js b/node_modules/source-map/lib/quick-sort.js new file mode 100644 index 0000000..6a7caad --- /dev/null +++ b/node_modules/source-map/lib/quick-sort.js @@ -0,0 +1,114 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +// It turns out that some (most?) JavaScript engines don't self-host +// `Array.prototype.sort`. This makes sense because C++ will likely remain +// faster than JS when doing raw CPU-intensive sorting. However, when using a +// custom comparator function, calling back and forth between the VM's C++ and +// JIT'd JS is rather slow *and* loses JIT type information, resulting in +// worse generated code for the comparator function than would be optimal. In +// fact, when sorting with a comparator, these costs outweigh the benefits of +// sorting in C++. By using our own JS-implemented Quick Sort (below), we get +// a ~3500ms mean speed-up in `bench/bench.html`. + +/** + * Swap the elements indexed by `x` and `y` in the array `ary`. + * + * @param {Array} ary + * The array. + * @param {Number} x + * The index of the first item. + * @param {Number} y + * The index of the second item. + */ +function swap(ary, x, y) { + var temp = ary[x]; + ary[x] = ary[y]; + ary[y] = temp; +} + +/** + * Returns a random integer within the range `low .. high` inclusive. + * + * @param {Number} low + * The lower bound on the range. + * @param {Number} high + * The upper bound on the range. + */ +function randomIntInRange(low, high) { + return Math.round(low + (Math.random() * (high - low))); +} + +/** + * The Quick Sort algorithm. + * + * @param {Array} ary + * An array to sort. + * @param {function} comparator + * Function to use to compare two items. + * @param {Number} p + * Start index of the array + * @param {Number} r + * End index of the array + */ +function doQuickSort(ary, comparator, p, r) { + // If our lower bound is less than our upper bound, we (1) partition the + // array into two pieces and (2) recurse on each half. If it is not, this is + // the empty array and our base case. + + if (p < r) { + // (1) Partitioning. + // + // The partitioning chooses a pivot between `p` and `r` and moves all + // elements that are less than or equal to the pivot to the before it, and + // all the elements that are greater than it after it. The effect is that + // once partition is done, the pivot is in the exact place it will be when + // the array is put in sorted order, and it will not need to be moved + // again. This runs in O(n) time. + + // Always choose a random pivot so that an input array which is reverse + // sorted does not cause O(n^2) running time. + var pivotIndex = randomIntInRange(p, r); + var i = p - 1; + + swap(ary, pivotIndex, r); + var pivot = ary[r]; + + // Immediately after `j` is incremented in this loop, the following hold + // true: + // + // * Every element in `ary[p .. i]` is less than or equal to the pivot. + // + // * Every element in `ary[i+1 .. j-1]` is greater than the pivot. + for (var j = p; j < r; j++) { + if (comparator(ary[j], pivot) <= 0) { + i += 1; + swap(ary, i, j); + } + } + + swap(ary, i + 1, j); + var q = i + 1; + + // (2) Recurse on each half. + + doQuickSort(ary, comparator, p, q - 1); + doQuickSort(ary, comparator, q + 1, r); + } +} + +/** + * Sort the given array in-place with the given comparator function. + * + * @param {Array} ary + * An array to sort. + * @param {function} comparator + * Function to use to compare two items. + */ +exports.quickSort = function (ary, comparator) { + doQuickSort(ary, comparator, 0, ary.length - 1); +}; diff --git a/node_modules/source-map/lib/source-map-consumer.js b/node_modules/source-map/lib/source-map-consumer.js new file mode 100644 index 0000000..7b99d1d --- /dev/null +++ b/node_modules/source-map/lib/source-map-consumer.js @@ -0,0 +1,1145 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +var util = require('./util'); +var binarySearch = require('./binary-search'); +var ArraySet = require('./array-set').ArraySet; +var base64VLQ = require('./base64-vlq'); +var quickSort = require('./quick-sort').quickSort; + +function SourceMapConsumer(aSourceMap, aSourceMapURL) { + var sourceMap = aSourceMap; + if (typeof aSourceMap === 'string') { + sourceMap = util.parseSourceMapInput(aSourceMap); + } + + return sourceMap.sections != null + ? new IndexedSourceMapConsumer(sourceMap, aSourceMapURL) + : new BasicSourceMapConsumer(sourceMap, aSourceMapURL); +} + +SourceMapConsumer.fromSourceMap = function(aSourceMap, aSourceMapURL) { + return BasicSourceMapConsumer.fromSourceMap(aSourceMap, aSourceMapURL); +} + +/** + * The version of the source mapping spec that we are consuming. + */ +SourceMapConsumer.prototype._version = 3; + +// `__generatedMappings` and `__originalMappings` are arrays that hold the +// parsed mapping coordinates from the source map's "mappings" attribute. They +// are lazily instantiated, accessed via the `_generatedMappings` and +// `_originalMappings` getters respectively, and we only parse the mappings +// and create these arrays once queried for a source location. We jump through +// these hoops because there can be many thousands of mappings, and parsing +// them is expensive, so we only want to do it if we must. +// +// Each object in the arrays is of the form: +// +// { +// generatedLine: The line number in the generated code, +// generatedColumn: The column number in the generated code, +// source: The path to the original source file that generated this +// chunk of code, +// originalLine: The line number in the original source that +// corresponds to this chunk of generated code, +// originalColumn: The column number in the original source that +// corresponds to this chunk of generated code, +// name: The name of the original symbol which generated this chunk of +// code. +// } +// +// All properties except for `generatedLine` and `generatedColumn` can be +// `null`. +// +// `_generatedMappings` is ordered by the generated positions. +// +// `_originalMappings` is ordered by the original positions. + +SourceMapConsumer.prototype.__generatedMappings = null; +Object.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', { + configurable: true, + enumerable: true, + get: function () { + if (!this.__generatedMappings) { + this._parseMappings(this._mappings, this.sourceRoot); + } + + return this.__generatedMappings; + } +}); + +SourceMapConsumer.prototype.__originalMappings = null; +Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', { + configurable: true, + enumerable: true, + get: function () { + if (!this.__originalMappings) { + this._parseMappings(this._mappings, this.sourceRoot); + } + + return this.__originalMappings; + } +}); + +SourceMapConsumer.prototype._charIsMappingSeparator = + function SourceMapConsumer_charIsMappingSeparator(aStr, index) { + var c = aStr.charAt(index); + return c === ";" || c === ","; + }; + +/** + * Parse the mappings in a string in to a data structure which we can easily + * query (the ordered arrays in the `this.__generatedMappings` and + * `this.__originalMappings` properties). + */ +SourceMapConsumer.prototype._parseMappings = + function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { + throw new Error("Subclasses must implement _parseMappings"); + }; + +SourceMapConsumer.GENERATED_ORDER = 1; +SourceMapConsumer.ORIGINAL_ORDER = 2; + +SourceMapConsumer.GREATEST_LOWER_BOUND = 1; +SourceMapConsumer.LEAST_UPPER_BOUND = 2; + +/** + * Iterate over each mapping between an original source/line/column and a + * generated line/column in this source map. + * + * @param Function aCallback + * The function that is called with each mapping. + * @param Object aContext + * Optional. If specified, this object will be the value of `this` every + * time that `aCallback` is called. + * @param aOrder + * Either `SourceMapConsumer.GENERATED_ORDER` or + * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to + * iterate over the mappings sorted by the generated file's line/column + * order or the original's source/line/column order, respectively. Defaults to + * `SourceMapConsumer.GENERATED_ORDER`. + */ +SourceMapConsumer.prototype.eachMapping = + function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) { + var context = aContext || null; + var order = aOrder || SourceMapConsumer.GENERATED_ORDER; + + var mappings; + switch (order) { + case SourceMapConsumer.GENERATED_ORDER: + mappings = this._generatedMappings; + break; + case SourceMapConsumer.ORIGINAL_ORDER: + mappings = this._originalMappings; + break; + default: + throw new Error("Unknown order of iteration."); + } + + var sourceRoot = this.sourceRoot; + mappings.map(function (mapping) { + var source = mapping.source === null ? null : this._sources.at(mapping.source); + source = util.computeSourceURL(sourceRoot, source, this._sourceMapURL); + return { + source: source, + generatedLine: mapping.generatedLine, + generatedColumn: mapping.generatedColumn, + originalLine: mapping.originalLine, + originalColumn: mapping.originalColumn, + name: mapping.name === null ? null : this._names.at(mapping.name) + }; + }, this).forEach(aCallback, context); + }; + +/** + * Returns all generated line and column information for the original source, + * line, and column provided. If no column is provided, returns all mappings + * corresponding to a either the line we are searching for or the next + * closest line that has any mappings. Otherwise, returns all mappings + * corresponding to the given line and either the column we are searching for + * or the next closest column that has any offsets. + * + * The only argument is an object with the following properties: + * + * - source: The filename of the original source. + * - line: The line number in the original source. The line number is 1-based. + * - column: Optional. the column number in the original source. + * The column number is 0-based. + * + * and an array of objects is returned, each with the following properties: + * + * - line: The line number in the generated source, or null. The + * line number is 1-based. + * - column: The column number in the generated source, or null. + * The column number is 0-based. + */ +SourceMapConsumer.prototype.allGeneratedPositionsFor = + function SourceMapConsumer_allGeneratedPositionsFor(aArgs) { + var line = util.getArg(aArgs, 'line'); + + // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping + // returns the index of the closest mapping less than the needle. By + // setting needle.originalColumn to 0, we thus find the last mapping for + // the given line, provided such a mapping exists. + var needle = { + source: util.getArg(aArgs, 'source'), + originalLine: line, + originalColumn: util.getArg(aArgs, 'column', 0) + }; + + needle.source = this._findSourceIndex(needle.source); + if (needle.source < 0) { + return []; + } + + var mappings = []; + + var index = this._findMapping(needle, + this._originalMappings, + "originalLine", + "originalColumn", + util.compareByOriginalPositions, + binarySearch.LEAST_UPPER_BOUND); + if (index >= 0) { + var mapping = this._originalMappings[index]; + + if (aArgs.column === undefined) { + var originalLine = mapping.originalLine; + + // Iterate until either we run out of mappings, or we run into + // a mapping for a different line than the one we found. Since + // mappings are sorted, this is guaranteed to find all mappings for + // the line we found. + while (mapping && mapping.originalLine === originalLine) { + mappings.push({ + line: util.getArg(mapping, 'generatedLine', null), + column: util.getArg(mapping, 'generatedColumn', null), + lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) + }); + + mapping = this._originalMappings[++index]; + } + } else { + var originalColumn = mapping.originalColumn; + + // Iterate until either we run out of mappings, or we run into + // a mapping for a different line than the one we were searching for. + // Since mappings are sorted, this is guaranteed to find all mappings for + // the line we are searching for. + while (mapping && + mapping.originalLine === line && + mapping.originalColumn == originalColumn) { + mappings.push({ + line: util.getArg(mapping, 'generatedLine', null), + column: util.getArg(mapping, 'generatedColumn', null), + lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) + }); + + mapping = this._originalMappings[++index]; + } + } + } + + return mappings; + }; + +exports.SourceMapConsumer = SourceMapConsumer; + +/** + * A BasicSourceMapConsumer instance represents a parsed source map which we can + * query for information about the original file positions by giving it a file + * position in the generated source. + * + * The first parameter is the raw source map (either as a JSON string, or + * already parsed to an object). According to the spec, source maps have the + * following attributes: + * + * - version: Which version of the source map spec this map is following. + * - sources: An array of URLs to the original source files. + * - names: An array of identifiers which can be referrenced by individual mappings. + * - sourceRoot: Optional. The URL root from which all sources are relative. + * - sourcesContent: Optional. An array of contents of the original source files. + * - mappings: A string of base64 VLQs which contain the actual mappings. + * - file: Optional. The generated file this source map is associated with. + * + * Here is an example source map, taken from the source map spec[0]: + * + * { + * version : 3, + * file: "out.js", + * sourceRoot : "", + * sources: ["foo.js", "bar.js"], + * names: ["src", "maps", "are", "fun"], + * mappings: "AA,AB;;ABCDE;" + * } + * + * The second parameter, if given, is a string whose value is the URL + * at which the source map was found. This URL is used to compute the + * sources array. + * + * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1# + */ +function BasicSourceMapConsumer(aSourceMap, aSourceMapURL) { + var sourceMap = aSourceMap; + if (typeof aSourceMap === 'string') { + sourceMap = util.parseSourceMapInput(aSourceMap); + } + + var version = util.getArg(sourceMap, 'version'); + var sources = util.getArg(sourceMap, 'sources'); + // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which + // requires the array) to play nice here. + var names = util.getArg(sourceMap, 'names', []); + var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null); + var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null); + var mappings = util.getArg(sourceMap, 'mappings'); + var file = util.getArg(sourceMap, 'file', null); + + // Once again, Sass deviates from the spec and supplies the version as a + // string rather than a number, so we use loose equality checking here. + if (version != this._version) { + throw new Error('Unsupported version: ' + version); + } + + if (sourceRoot) { + sourceRoot = util.normalize(sourceRoot); + } + + sources = sources + .map(String) + // Some source maps produce relative source paths like "./foo.js" instead of + // "foo.js". Normalize these first so that future comparisons will succeed. + // See bugzil.la/1090768. + .map(util.normalize) + // Always ensure that absolute sources are internally stored relative to + // the source root, if the source root is absolute. Not doing this would + // be particularly problematic when the source root is a prefix of the + // source (valid, but why??). See github issue #199 and bugzil.la/1188982. + .map(function (source) { + return sourceRoot && util.isAbsolute(sourceRoot) && util.isAbsolute(source) + ? util.relative(sourceRoot, source) + : source; + }); + + // Pass `true` below to allow duplicate names and sources. While source maps + // are intended to be compressed and deduplicated, the TypeScript compiler + // sometimes generates source maps with duplicates in them. See Github issue + // #72 and bugzil.la/889492. + this._names = ArraySet.fromArray(names.map(String), true); + this._sources = ArraySet.fromArray(sources, true); + + this._absoluteSources = this._sources.toArray().map(function (s) { + return util.computeSourceURL(sourceRoot, s, aSourceMapURL); + }); + + this.sourceRoot = sourceRoot; + this.sourcesContent = sourcesContent; + this._mappings = mappings; + this._sourceMapURL = aSourceMapURL; + this.file = file; +} + +BasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype); +BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer; + +/** + * Utility function to find the index of a source. Returns -1 if not + * found. + */ +BasicSourceMapConsumer.prototype._findSourceIndex = function(aSource) { + var relativeSource = aSource; + if (this.sourceRoot != null) { + relativeSource = util.relative(this.sourceRoot, relativeSource); + } + + if (this._sources.has(relativeSource)) { + return this._sources.indexOf(relativeSource); + } + + // Maybe aSource is an absolute URL as returned by |sources|. In + // this case we can't simply undo the transform. + var i; + for (i = 0; i < this._absoluteSources.length; ++i) { + if (this._absoluteSources[i] == aSource) { + return i; + } + } + + return -1; +}; + +/** + * Create a BasicSourceMapConsumer from a SourceMapGenerator. + * + * @param SourceMapGenerator aSourceMap + * The source map that will be consumed. + * @param String aSourceMapURL + * The URL at which the source map can be found (optional) + * @returns BasicSourceMapConsumer + */ +BasicSourceMapConsumer.fromSourceMap = + function SourceMapConsumer_fromSourceMap(aSourceMap, aSourceMapURL) { + var smc = Object.create(BasicSourceMapConsumer.prototype); + + var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true); + var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true); + smc.sourceRoot = aSourceMap._sourceRoot; + smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(), + smc.sourceRoot); + smc.file = aSourceMap._file; + smc._sourceMapURL = aSourceMapURL; + smc._absoluteSources = smc._sources.toArray().map(function (s) { + return util.computeSourceURL(smc.sourceRoot, s, aSourceMapURL); + }); + + // Because we are modifying the entries (by converting string sources and + // names to indices into the sources and names ArraySets), we have to make + // a copy of the entry or else bad things happen. Shared mutable state + // strikes again! See github issue #191. + + var generatedMappings = aSourceMap._mappings.toArray().slice(); + var destGeneratedMappings = smc.__generatedMappings = []; + var destOriginalMappings = smc.__originalMappings = []; + + for (var i = 0, length = generatedMappings.length; i < length; i++) { + var srcMapping = generatedMappings[i]; + var destMapping = new Mapping; + destMapping.generatedLine = srcMapping.generatedLine; + destMapping.generatedColumn = srcMapping.generatedColumn; + + if (srcMapping.source) { + destMapping.source = sources.indexOf(srcMapping.source); + destMapping.originalLine = srcMapping.originalLine; + destMapping.originalColumn = srcMapping.originalColumn; + + if (srcMapping.name) { + destMapping.name = names.indexOf(srcMapping.name); + } + + destOriginalMappings.push(destMapping); + } + + destGeneratedMappings.push(destMapping); + } + + quickSort(smc.__originalMappings, util.compareByOriginalPositions); + + return smc; + }; + +/** + * The version of the source mapping spec that we are consuming. + */ +BasicSourceMapConsumer.prototype._version = 3; + +/** + * The list of original sources. + */ +Object.defineProperty(BasicSourceMapConsumer.prototype, 'sources', { + get: function () { + return this._absoluteSources.slice(); + } +}); + +/** + * Provide the JIT with a nice shape / hidden class. + */ +function Mapping() { + this.generatedLine = 0; + this.generatedColumn = 0; + this.source = null; + this.originalLine = null; + this.originalColumn = null; + this.name = null; +} + +/** + * Parse the mappings in a string in to a data structure which we can easily + * query (the ordered arrays in the `this.__generatedMappings` and + * `this.__originalMappings` properties). + */ +BasicSourceMapConsumer.prototype._parseMappings = + function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { + var generatedLine = 1; + var previousGeneratedColumn = 0; + var previousOriginalLine = 0; + var previousOriginalColumn = 0; + var previousSource = 0; + var previousName = 0; + var length = aStr.length; + var index = 0; + var cachedSegments = {}; + var temp = {}; + var originalMappings = []; + var generatedMappings = []; + var mapping, str, segment, end, value; + + while (index < length) { + if (aStr.charAt(index) === ';') { + generatedLine++; + index++; + previousGeneratedColumn = 0; + } + else if (aStr.charAt(index) === ',') { + index++; + } + else { + mapping = new Mapping(); + mapping.generatedLine = generatedLine; + + // Because each offset is encoded relative to the previous one, + // many segments often have the same encoding. We can exploit this + // fact by caching the parsed variable length fields of each segment, + // allowing us to avoid a second parse if we encounter the same + // segment again. + for (end = index; end < length; end++) { + if (this._charIsMappingSeparator(aStr, end)) { + break; + } + } + str = aStr.slice(index, end); + + segment = cachedSegments[str]; + if (segment) { + index += str.length; + } else { + segment = []; + while (index < end) { + base64VLQ.decode(aStr, index, temp); + value = temp.value; + index = temp.rest; + segment.push(value); + } + + if (segment.length === 2) { + throw new Error('Found a source, but no line and column'); + } + + if (segment.length === 3) { + throw new Error('Found a source and line, but no column'); + } + + cachedSegments[str] = segment; + } + + // Generated column. + mapping.generatedColumn = previousGeneratedColumn + segment[0]; + previousGeneratedColumn = mapping.generatedColumn; + + if (segment.length > 1) { + // Original source. + mapping.source = previousSource + segment[1]; + previousSource += segment[1]; + + // Original line. + mapping.originalLine = previousOriginalLine + segment[2]; + previousOriginalLine = mapping.originalLine; + // Lines are stored 0-based + mapping.originalLine += 1; + + // Original column. + mapping.originalColumn = previousOriginalColumn + segment[3]; + previousOriginalColumn = mapping.originalColumn; + + if (segment.length > 4) { + // Original name. + mapping.name = previousName + segment[4]; + previousName += segment[4]; + } + } + + generatedMappings.push(mapping); + if (typeof mapping.originalLine === 'number') { + originalMappings.push(mapping); + } + } + } + + quickSort(generatedMappings, util.compareByGeneratedPositionsDeflated); + this.__generatedMappings = generatedMappings; + + quickSort(originalMappings, util.compareByOriginalPositions); + this.__originalMappings = originalMappings; + }; + +/** + * Find the mapping that best matches the hypothetical "needle" mapping that + * we are searching for in the given "haystack" of mappings. + */ +BasicSourceMapConsumer.prototype._findMapping = + function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName, + aColumnName, aComparator, aBias) { + // To return the position we are searching for, we must first find the + // mapping for the given position and then return the opposite position it + // points to. Because the mappings are sorted, we can use binary search to + // find the best mapping. + + if (aNeedle[aLineName] <= 0) { + throw new TypeError('Line must be greater than or equal to 1, got ' + + aNeedle[aLineName]); + } + if (aNeedle[aColumnName] < 0) { + throw new TypeError('Column must be greater than or equal to 0, got ' + + aNeedle[aColumnName]); + } + + return binarySearch.search(aNeedle, aMappings, aComparator, aBias); + }; + +/** + * Compute the last column for each generated mapping. The last column is + * inclusive. + */ +BasicSourceMapConsumer.prototype.computeColumnSpans = + function SourceMapConsumer_computeColumnSpans() { + for (var index = 0; index < this._generatedMappings.length; ++index) { + var mapping = this._generatedMappings[index]; + + // Mappings do not contain a field for the last generated columnt. We + // can come up with an optimistic estimate, however, by assuming that + // mappings are contiguous (i.e. given two consecutive mappings, the + // first mapping ends where the second one starts). + if (index + 1 < this._generatedMappings.length) { + var nextMapping = this._generatedMappings[index + 1]; + + if (mapping.generatedLine === nextMapping.generatedLine) { + mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1; + continue; + } + } + + // The last mapping for each line spans the entire line. + mapping.lastGeneratedColumn = Infinity; + } + }; + +/** + * Returns the original source, line, and column information for the generated + * source's line and column positions provided. The only argument is an object + * with the following properties: + * + * - line: The line number in the generated source. The line number + * is 1-based. + * - column: The column number in the generated source. The column + * number is 0-based. + * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or + * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. + * + * and an object is returned with the following properties: + * + * - source: The original source file, or null. + * - line: The line number in the original source, or null. The + * line number is 1-based. + * - column: The column number in the original source, or null. The + * column number is 0-based. + * - name: The original identifier, or null. + */ +BasicSourceMapConsumer.prototype.originalPositionFor = + function SourceMapConsumer_originalPositionFor(aArgs) { + var needle = { + generatedLine: util.getArg(aArgs, 'line'), + generatedColumn: util.getArg(aArgs, 'column') + }; + + var index = this._findMapping( + needle, + this._generatedMappings, + "generatedLine", + "generatedColumn", + util.compareByGeneratedPositionsDeflated, + util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND) + ); + + if (index >= 0) { + var mapping = this._generatedMappings[index]; + + if (mapping.generatedLine === needle.generatedLine) { + var source = util.getArg(mapping, 'source', null); + if (source !== null) { + source = this._sources.at(source); + source = util.computeSourceURL(this.sourceRoot, source, this._sourceMapURL); + } + var name = util.getArg(mapping, 'name', null); + if (name !== null) { + name = this._names.at(name); + } + return { + source: source, + line: util.getArg(mapping, 'originalLine', null), + column: util.getArg(mapping, 'originalColumn', null), + name: name + }; + } + } + + return { + source: null, + line: null, + column: null, + name: null + }; + }; + +/** + * Return true if we have the source content for every source in the source + * map, false otherwise. + */ +BasicSourceMapConsumer.prototype.hasContentsOfAllSources = + function BasicSourceMapConsumer_hasContentsOfAllSources() { + if (!this.sourcesContent) { + return false; + } + return this.sourcesContent.length >= this._sources.size() && + !this.sourcesContent.some(function (sc) { return sc == null; }); + }; + +/** + * Returns the original source content. The only argument is the url of the + * original source file. Returns null if no original source content is + * available. + */ +BasicSourceMapConsumer.prototype.sourceContentFor = + function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { + if (!this.sourcesContent) { + return null; + } + + var index = this._findSourceIndex(aSource); + if (index >= 0) { + return this.sourcesContent[index]; + } + + var relativeSource = aSource; + if (this.sourceRoot != null) { + relativeSource = util.relative(this.sourceRoot, relativeSource); + } + + var url; + if (this.sourceRoot != null + && (url = util.urlParse(this.sourceRoot))) { + // XXX: file:// URIs and absolute paths lead to unexpected behavior for + // many users. We can help them out when they expect file:// URIs to + // behave like it would if they were running a local HTTP server. See + // https://bugzilla.mozilla.org/show_bug.cgi?id=885597. + var fileUriAbsPath = relativeSource.replace(/^file:\/\//, ""); + if (url.scheme == "file" + && this._sources.has(fileUriAbsPath)) { + return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)] + } + + if ((!url.path || url.path == "/") + && this._sources.has("/" + relativeSource)) { + return this.sourcesContent[this._sources.indexOf("/" + relativeSource)]; + } + } + + // This function is used recursively from + // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we + // don't want to throw if we can't find the source - we just want to + // return null, so we provide a flag to exit gracefully. + if (nullOnMissing) { + return null; + } + else { + throw new Error('"' + relativeSource + '" is not in the SourceMap.'); + } + }; + +/** + * Returns the generated line and column information for the original source, + * line, and column positions provided. The only argument is an object with + * the following properties: + * + * - source: The filename of the original source. + * - line: The line number in the original source. The line number + * is 1-based. + * - column: The column number in the original source. The column + * number is 0-based. + * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or + * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. + * + * and an object is returned with the following properties: + * + * - line: The line number in the generated source, or null. The + * line number is 1-based. + * - column: The column number in the generated source, or null. + * The column number is 0-based. + */ +BasicSourceMapConsumer.prototype.generatedPositionFor = + function SourceMapConsumer_generatedPositionFor(aArgs) { + var source = util.getArg(aArgs, 'source'); + source = this._findSourceIndex(source); + if (source < 0) { + return { + line: null, + column: null, + lastColumn: null + }; + } + + var needle = { + source: source, + originalLine: util.getArg(aArgs, 'line'), + originalColumn: util.getArg(aArgs, 'column') + }; + + var index = this._findMapping( + needle, + this._originalMappings, + "originalLine", + "originalColumn", + util.compareByOriginalPositions, + util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND) + ); + + if (index >= 0) { + var mapping = this._originalMappings[index]; + + if (mapping.source === needle.source) { + return { + line: util.getArg(mapping, 'generatedLine', null), + column: util.getArg(mapping, 'generatedColumn', null), + lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) + }; + } + } + + return { + line: null, + column: null, + lastColumn: null + }; + }; + +exports.BasicSourceMapConsumer = BasicSourceMapConsumer; + +/** + * An IndexedSourceMapConsumer instance represents a parsed source map which + * we can query for information. It differs from BasicSourceMapConsumer in + * that it takes "indexed" source maps (i.e. ones with a "sections" field) as + * input. + * + * The first parameter is a raw source map (either as a JSON string, or already + * parsed to an object). According to the spec for indexed source maps, they + * have the following attributes: + * + * - version: Which version of the source map spec this map is following. + * - file: Optional. The generated file this source map is associated with. + * - sections: A list of section definitions. + * + * Each value under the "sections" field has two fields: + * - offset: The offset into the original specified at which this section + * begins to apply, defined as an object with a "line" and "column" + * field. + * - map: A source map definition. This source map could also be indexed, + * but doesn't have to be. + * + * Instead of the "map" field, it's also possible to have a "url" field + * specifying a URL to retrieve a source map from, but that's currently + * unsupported. + * + * Here's an example source map, taken from the source map spec[0], but + * modified to omit a section which uses the "url" field. + * + * { + * version : 3, + * file: "app.js", + * sections: [{ + * offset: {line:100, column:10}, + * map: { + * version : 3, + * file: "section.js", + * sources: ["foo.js", "bar.js"], + * names: ["src", "maps", "are", "fun"], + * mappings: "AAAA,E;;ABCDE;" + * } + * }], + * } + * + * The second parameter, if given, is a string whose value is the URL + * at which the source map was found. This URL is used to compute the + * sources array. + * + * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt + */ +function IndexedSourceMapConsumer(aSourceMap, aSourceMapURL) { + var sourceMap = aSourceMap; + if (typeof aSourceMap === 'string') { + sourceMap = util.parseSourceMapInput(aSourceMap); + } + + var version = util.getArg(sourceMap, 'version'); + var sections = util.getArg(sourceMap, 'sections'); + + if (version != this._version) { + throw new Error('Unsupported version: ' + version); + } + + this._sources = new ArraySet(); + this._names = new ArraySet(); + + var lastOffset = { + line: -1, + column: 0 + }; + this._sections = sections.map(function (s) { + if (s.url) { + // The url field will require support for asynchronicity. + // See https://github.com/mozilla/source-map/issues/16 + throw new Error('Support for url field in sections not implemented.'); + } + var offset = util.getArg(s, 'offset'); + var offsetLine = util.getArg(offset, 'line'); + var offsetColumn = util.getArg(offset, 'column'); + + if (offsetLine < lastOffset.line || + (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) { + throw new Error('Section offsets must be ordered and non-overlapping.'); + } + lastOffset = offset; + + return { + generatedOffset: { + // The offset fields are 0-based, but we use 1-based indices when + // encoding/decoding from VLQ. + generatedLine: offsetLine + 1, + generatedColumn: offsetColumn + 1 + }, + consumer: new SourceMapConsumer(util.getArg(s, 'map'), aSourceMapURL) + } + }); +} + +IndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype); +IndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer; + +/** + * The version of the source mapping spec that we are consuming. + */ +IndexedSourceMapConsumer.prototype._version = 3; + +/** + * The list of original sources. + */ +Object.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', { + get: function () { + var sources = []; + for (var i = 0; i < this._sections.length; i++) { + for (var j = 0; j < this._sections[i].consumer.sources.length; j++) { + sources.push(this._sections[i].consumer.sources[j]); + } + } + return sources; + } +}); + +/** + * Returns the original source, line, and column information for the generated + * source's line and column positions provided. The only argument is an object + * with the following properties: + * + * - line: The line number in the generated source. The line number + * is 1-based. + * - column: The column number in the generated source. The column + * number is 0-based. + * + * and an object is returned with the following properties: + * + * - source: The original source file, or null. + * - line: The line number in the original source, or null. The + * line number is 1-based. + * - column: The column number in the original source, or null. The + * column number is 0-based. + * - name: The original identifier, or null. + */ +IndexedSourceMapConsumer.prototype.originalPositionFor = + function IndexedSourceMapConsumer_originalPositionFor(aArgs) { + var needle = { + generatedLine: util.getArg(aArgs, 'line'), + generatedColumn: util.getArg(aArgs, 'column') + }; + + // Find the section containing the generated position we're trying to map + // to an original position. + var sectionIndex = binarySearch.search(needle, this._sections, + function(needle, section) { + var cmp = needle.generatedLine - section.generatedOffset.generatedLine; + if (cmp) { + return cmp; + } + + return (needle.generatedColumn - + section.generatedOffset.generatedColumn); + }); + var section = this._sections[sectionIndex]; + + if (!section) { + return { + source: null, + line: null, + column: null, + name: null + }; + } + + return section.consumer.originalPositionFor({ + line: needle.generatedLine - + (section.generatedOffset.generatedLine - 1), + column: needle.generatedColumn - + (section.generatedOffset.generatedLine === needle.generatedLine + ? section.generatedOffset.generatedColumn - 1 + : 0), + bias: aArgs.bias + }); + }; + +/** + * Return true if we have the source content for every source in the source + * map, false otherwise. + */ +IndexedSourceMapConsumer.prototype.hasContentsOfAllSources = + function IndexedSourceMapConsumer_hasContentsOfAllSources() { + return this._sections.every(function (s) { + return s.consumer.hasContentsOfAllSources(); + }); + }; + +/** + * Returns the original source content. The only argument is the url of the + * original source file. Returns null if no original source content is + * available. + */ +IndexedSourceMapConsumer.prototype.sourceContentFor = + function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { + for (var i = 0; i < this._sections.length; i++) { + var section = this._sections[i]; + + var content = section.consumer.sourceContentFor(aSource, true); + if (content) { + return content; + } + } + if (nullOnMissing) { + return null; + } + else { + throw new Error('"' + aSource + '" is not in the SourceMap.'); + } + }; + +/** + * Returns the generated line and column information for the original source, + * line, and column positions provided. The only argument is an object with + * the following properties: + * + * - source: The filename of the original source. + * - line: The line number in the original source. The line number + * is 1-based. + * - column: The column number in the original source. The column + * number is 0-based. + * + * and an object is returned with the following properties: + * + * - line: The line number in the generated source, or null. The + * line number is 1-based. + * - column: The column number in the generated source, or null. + * The column number is 0-based. + */ +IndexedSourceMapConsumer.prototype.generatedPositionFor = + function IndexedSourceMapConsumer_generatedPositionFor(aArgs) { + for (var i = 0; i < this._sections.length; i++) { + var section = this._sections[i]; + + // Only consider this section if the requested source is in the list of + // sources of the consumer. + if (section.consumer._findSourceIndex(util.getArg(aArgs, 'source')) === -1) { + continue; + } + var generatedPosition = section.consumer.generatedPositionFor(aArgs); + if (generatedPosition) { + var ret = { + line: generatedPosition.line + + (section.generatedOffset.generatedLine - 1), + column: generatedPosition.column + + (section.generatedOffset.generatedLine === generatedPosition.line + ? section.generatedOffset.generatedColumn - 1 + : 0) + }; + return ret; + } + } + + return { + line: null, + column: null + }; + }; + +/** + * Parse the mappings in a string in to a data structure which we can easily + * query (the ordered arrays in the `this.__generatedMappings` and + * `this.__originalMappings` properties). + */ +IndexedSourceMapConsumer.prototype._parseMappings = + function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) { + this.__generatedMappings = []; + this.__originalMappings = []; + for (var i = 0; i < this._sections.length; i++) { + var section = this._sections[i]; + var sectionMappings = section.consumer._generatedMappings; + for (var j = 0; j < sectionMappings.length; j++) { + var mapping = sectionMappings[j]; + + var source = section.consumer._sources.at(mapping.source); + source = util.computeSourceURL(section.consumer.sourceRoot, source, this._sourceMapURL); + this._sources.add(source); + source = this._sources.indexOf(source); + + var name = null; + if (mapping.name) { + name = section.consumer._names.at(mapping.name); + this._names.add(name); + name = this._names.indexOf(name); + } + + // The mappings coming from the consumer for the section have + // generated positions relative to the start of the section, so we + // need to offset them to be relative to the start of the concatenated + // generated file. + var adjustedMapping = { + source: source, + generatedLine: mapping.generatedLine + + (section.generatedOffset.generatedLine - 1), + generatedColumn: mapping.generatedColumn + + (section.generatedOffset.generatedLine === mapping.generatedLine + ? section.generatedOffset.generatedColumn - 1 + : 0), + originalLine: mapping.originalLine, + originalColumn: mapping.originalColumn, + name: name + }; + + this.__generatedMappings.push(adjustedMapping); + if (typeof adjustedMapping.originalLine === 'number') { + this.__originalMappings.push(adjustedMapping); + } + } + } + + quickSort(this.__generatedMappings, util.compareByGeneratedPositionsDeflated); + quickSort(this.__originalMappings, util.compareByOriginalPositions); + }; + +exports.IndexedSourceMapConsumer = IndexedSourceMapConsumer; diff --git a/node_modules/source-map/lib/source-map-generator.js b/node_modules/source-map/lib/source-map-generator.js new file mode 100644 index 0000000..508bcfb --- /dev/null +++ b/node_modules/source-map/lib/source-map-generator.js @@ -0,0 +1,425 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +var base64VLQ = require('./base64-vlq'); +var util = require('./util'); +var ArraySet = require('./array-set').ArraySet; +var MappingList = require('./mapping-list').MappingList; + +/** + * An instance of the SourceMapGenerator represents a source map which is + * being built incrementally. You may pass an object with the following + * properties: + * + * - file: The filename of the generated source. + * - sourceRoot: A root for all relative URLs in this source map. + */ +function SourceMapGenerator(aArgs) { + if (!aArgs) { + aArgs = {}; + } + this._file = util.getArg(aArgs, 'file', null); + this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null); + this._skipValidation = util.getArg(aArgs, 'skipValidation', false); + this._sources = new ArraySet(); + this._names = new ArraySet(); + this._mappings = new MappingList(); + this._sourcesContents = null; +} + +SourceMapGenerator.prototype._version = 3; + +/** + * Creates a new SourceMapGenerator based on a SourceMapConsumer + * + * @param aSourceMapConsumer The SourceMap. + */ +SourceMapGenerator.fromSourceMap = + function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) { + var sourceRoot = aSourceMapConsumer.sourceRoot; + var generator = new SourceMapGenerator({ + file: aSourceMapConsumer.file, + sourceRoot: sourceRoot + }); + aSourceMapConsumer.eachMapping(function (mapping) { + var newMapping = { + generated: { + line: mapping.generatedLine, + column: mapping.generatedColumn + } + }; + + if (mapping.source != null) { + newMapping.source = mapping.source; + if (sourceRoot != null) { + newMapping.source = util.relative(sourceRoot, newMapping.source); + } + + newMapping.original = { + line: mapping.originalLine, + column: mapping.originalColumn + }; + + if (mapping.name != null) { + newMapping.name = mapping.name; + } + } + + generator.addMapping(newMapping); + }); + aSourceMapConsumer.sources.forEach(function (sourceFile) { + var sourceRelative = sourceFile; + if (sourceRoot !== null) { + sourceRelative = util.relative(sourceRoot, sourceFile); + } + + if (!generator._sources.has(sourceRelative)) { + generator._sources.add(sourceRelative); + } + + var content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content != null) { + generator.setSourceContent(sourceFile, content); + } + }); + return generator; + }; + +/** + * Add a single mapping from original source line and column to the generated + * source's line and column for this source map being created. The mapping + * object should have the following properties: + * + * - generated: An object with the generated line and column positions. + * - original: An object with the original line and column positions. + * - source: The original source file (relative to the sourceRoot). + * - name: An optional original token name for this mapping. + */ +SourceMapGenerator.prototype.addMapping = + function SourceMapGenerator_addMapping(aArgs) { + var generated = util.getArg(aArgs, 'generated'); + var original = util.getArg(aArgs, 'original', null); + var source = util.getArg(aArgs, 'source', null); + var name = util.getArg(aArgs, 'name', null); + + if (!this._skipValidation) { + this._validateMapping(generated, original, source, name); + } + + if (source != null) { + source = String(source); + if (!this._sources.has(source)) { + this._sources.add(source); + } + } + + if (name != null) { + name = String(name); + if (!this._names.has(name)) { + this._names.add(name); + } + } + + this._mappings.add({ + generatedLine: generated.line, + generatedColumn: generated.column, + originalLine: original != null && original.line, + originalColumn: original != null && original.column, + source: source, + name: name + }); + }; + +/** + * Set the source content for a source file. + */ +SourceMapGenerator.prototype.setSourceContent = + function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) { + var source = aSourceFile; + if (this._sourceRoot != null) { + source = util.relative(this._sourceRoot, source); + } + + if (aSourceContent != null) { + // Add the source content to the _sourcesContents map. + // Create a new _sourcesContents map if the property is null. + if (!this._sourcesContents) { + this._sourcesContents = Object.create(null); + } + this._sourcesContents[util.toSetString(source)] = aSourceContent; + } else if (this._sourcesContents) { + // Remove the source file from the _sourcesContents map. + // If the _sourcesContents map is empty, set the property to null. + delete this._sourcesContents[util.toSetString(source)]; + if (Object.keys(this._sourcesContents).length === 0) { + this._sourcesContents = null; + } + } + }; + +/** + * Applies the mappings of a sub-source-map for a specific source file to the + * source map being generated. Each mapping to the supplied source file is + * rewritten using the supplied source map. Note: The resolution for the + * resulting mappings is the minimium of this map and the supplied map. + * + * @param aSourceMapConsumer The source map to be applied. + * @param aSourceFile Optional. The filename of the source file. + * If omitted, SourceMapConsumer's file property will be used. + * @param aSourceMapPath Optional. The dirname of the path to the source map + * to be applied. If relative, it is relative to the SourceMapConsumer. + * This parameter is needed when the two source maps aren't in the same + * directory, and the source map to be applied contains relative source + * paths. If so, those relative source paths need to be rewritten + * relative to the SourceMapGenerator. + */ +SourceMapGenerator.prototype.applySourceMap = + function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) { + var sourceFile = aSourceFile; + // If aSourceFile is omitted, we will use the file property of the SourceMap + if (aSourceFile == null) { + if (aSourceMapConsumer.file == null) { + throw new Error( + 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' + + 'or the source map\'s "file" property. Both were omitted.' + ); + } + sourceFile = aSourceMapConsumer.file; + } + var sourceRoot = this._sourceRoot; + // Make "sourceFile" relative if an absolute Url is passed. + if (sourceRoot != null) { + sourceFile = util.relative(sourceRoot, sourceFile); + } + // Applying the SourceMap can add and remove items from the sources and + // the names array. + var newSources = new ArraySet(); + var newNames = new ArraySet(); + + // Find mappings for the "sourceFile" + this._mappings.unsortedForEach(function (mapping) { + if (mapping.source === sourceFile && mapping.originalLine != null) { + // Check if it can be mapped by the source map, then update the mapping. + var original = aSourceMapConsumer.originalPositionFor({ + line: mapping.originalLine, + column: mapping.originalColumn + }); + if (original.source != null) { + // Copy mapping + mapping.source = original.source; + if (aSourceMapPath != null) { + mapping.source = util.join(aSourceMapPath, mapping.source) + } + if (sourceRoot != null) { + mapping.source = util.relative(sourceRoot, mapping.source); + } + mapping.originalLine = original.line; + mapping.originalColumn = original.column; + if (original.name != null) { + mapping.name = original.name; + } + } + } + + var source = mapping.source; + if (source != null && !newSources.has(source)) { + newSources.add(source); + } + + var name = mapping.name; + if (name != null && !newNames.has(name)) { + newNames.add(name); + } + + }, this); + this._sources = newSources; + this._names = newNames; + + // Copy sourcesContents of applied map. + aSourceMapConsumer.sources.forEach(function (sourceFile) { + var content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content != null) { + if (aSourceMapPath != null) { + sourceFile = util.join(aSourceMapPath, sourceFile); + } + if (sourceRoot != null) { + sourceFile = util.relative(sourceRoot, sourceFile); + } + this.setSourceContent(sourceFile, content); + } + }, this); + }; + +/** + * A mapping can have one of the three levels of data: + * + * 1. Just the generated position. + * 2. The Generated position, original position, and original source. + * 3. Generated and original position, original source, as well as a name + * token. + * + * To maintain consistency, we validate that any new mapping being added falls + * in to one of these categories. + */ +SourceMapGenerator.prototype._validateMapping = + function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource, + aName) { + // When aOriginal is truthy but has empty values for .line and .column, + // it is most likely a programmer error. In this case we throw a very + // specific error message to try to guide them the right way. + // For example: https://github.com/Polymer/polymer-bundler/pull/519 + if (aOriginal && typeof aOriginal.line !== 'number' && typeof aOriginal.column !== 'number') { + throw new Error( + 'original.line and original.column are not numbers -- you probably meant to omit ' + + 'the original mapping entirely and only map the generated position. If so, pass ' + + 'null for the original mapping instead of an object with empty or null values.' + ); + } + + if (aGenerated && 'line' in aGenerated && 'column' in aGenerated + && aGenerated.line > 0 && aGenerated.column >= 0 + && !aOriginal && !aSource && !aName) { + // Case 1. + return; + } + else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated + && aOriginal && 'line' in aOriginal && 'column' in aOriginal + && aGenerated.line > 0 && aGenerated.column >= 0 + && aOriginal.line > 0 && aOriginal.column >= 0 + && aSource) { + // Cases 2 and 3. + return; + } + else { + throw new Error('Invalid mapping: ' + JSON.stringify({ + generated: aGenerated, + source: aSource, + original: aOriginal, + name: aName + })); + } + }; + +/** + * Serialize the accumulated mappings in to the stream of base 64 VLQs + * specified by the source map format. + */ +SourceMapGenerator.prototype._serializeMappings = + function SourceMapGenerator_serializeMappings() { + var previousGeneratedColumn = 0; + var previousGeneratedLine = 1; + var previousOriginalColumn = 0; + var previousOriginalLine = 0; + var previousName = 0; + var previousSource = 0; + var result = ''; + var next; + var mapping; + var nameIdx; + var sourceIdx; + + var mappings = this._mappings.toArray(); + for (var i = 0, len = mappings.length; i < len; i++) { + mapping = mappings[i]; + next = '' + + if (mapping.generatedLine !== previousGeneratedLine) { + previousGeneratedColumn = 0; + while (mapping.generatedLine !== previousGeneratedLine) { + next += ';'; + previousGeneratedLine++; + } + } + else { + if (i > 0) { + if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) { + continue; + } + next += ','; + } + } + + next += base64VLQ.encode(mapping.generatedColumn + - previousGeneratedColumn); + previousGeneratedColumn = mapping.generatedColumn; + + if (mapping.source != null) { + sourceIdx = this._sources.indexOf(mapping.source); + next += base64VLQ.encode(sourceIdx - previousSource); + previousSource = sourceIdx; + + // lines are stored 0-based in SourceMap spec version 3 + next += base64VLQ.encode(mapping.originalLine - 1 + - previousOriginalLine); + previousOriginalLine = mapping.originalLine - 1; + + next += base64VLQ.encode(mapping.originalColumn + - previousOriginalColumn); + previousOriginalColumn = mapping.originalColumn; + + if (mapping.name != null) { + nameIdx = this._names.indexOf(mapping.name); + next += base64VLQ.encode(nameIdx - previousName); + previousName = nameIdx; + } + } + + result += next; + } + + return result; + }; + +SourceMapGenerator.prototype._generateSourcesContent = + function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) { + return aSources.map(function (source) { + if (!this._sourcesContents) { + return null; + } + if (aSourceRoot != null) { + source = util.relative(aSourceRoot, source); + } + var key = util.toSetString(source); + return Object.prototype.hasOwnProperty.call(this._sourcesContents, key) + ? this._sourcesContents[key] + : null; + }, this); + }; + +/** + * Externalize the source map. + */ +SourceMapGenerator.prototype.toJSON = + function SourceMapGenerator_toJSON() { + var map = { + version: this._version, + sources: this._sources.toArray(), + names: this._names.toArray(), + mappings: this._serializeMappings() + }; + if (this._file != null) { + map.file = this._file; + } + if (this._sourceRoot != null) { + map.sourceRoot = this._sourceRoot; + } + if (this._sourcesContents) { + map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot); + } + + return map; + }; + +/** + * Render the source map being generated to a string. + */ +SourceMapGenerator.prototype.toString = + function SourceMapGenerator_toString() { + return JSON.stringify(this.toJSON()); + }; + +exports.SourceMapGenerator = SourceMapGenerator; diff --git a/node_modules/source-map/lib/source-node.js b/node_modules/source-map/lib/source-node.js new file mode 100644 index 0000000..8bcdbe3 --- /dev/null +++ b/node_modules/source-map/lib/source-node.js @@ -0,0 +1,413 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +var SourceMapGenerator = require('./source-map-generator').SourceMapGenerator; +var util = require('./util'); + +// Matches a Windows-style `\r\n` newline or a `\n` newline used by all other +// operating systems these days (capturing the result). +var REGEX_NEWLINE = /(\r?\n)/; + +// Newline character code for charCodeAt() comparisons +var NEWLINE_CODE = 10; + +// Private symbol for identifying `SourceNode`s when multiple versions of +// the source-map library are loaded. This MUST NOT CHANGE across +// versions! +var isSourceNode = "$$$isSourceNode$$$"; + +/** + * SourceNodes provide a way to abstract over interpolating/concatenating + * snippets of generated JavaScript source code while maintaining the line and + * column information associated with the original source code. + * + * @param aLine The original line number. + * @param aColumn The original column number. + * @param aSource The original source's filename. + * @param aChunks Optional. An array of strings which are snippets of + * generated JS, or other SourceNodes. + * @param aName The original identifier. + */ +function SourceNode(aLine, aColumn, aSource, aChunks, aName) { + this.children = []; + this.sourceContents = {}; + this.line = aLine == null ? null : aLine; + this.column = aColumn == null ? null : aColumn; + this.source = aSource == null ? null : aSource; + this.name = aName == null ? null : aName; + this[isSourceNode] = true; + if (aChunks != null) this.add(aChunks); +} + +/** + * Creates a SourceNode from generated code and a SourceMapConsumer. + * + * @param aGeneratedCode The generated code + * @param aSourceMapConsumer The SourceMap for the generated code + * @param aRelativePath Optional. The path that relative sources in the + * SourceMapConsumer should be relative to. + */ +SourceNode.fromStringWithSourceMap = + function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) { + // The SourceNode we want to fill with the generated code + // and the SourceMap + var node = new SourceNode(); + + // All even indices of this array are one line of the generated code, + // while all odd indices are the newlines between two adjacent lines + // (since `REGEX_NEWLINE` captures its match). + // Processed fragments are accessed by calling `shiftNextLine`. + var remainingLines = aGeneratedCode.split(REGEX_NEWLINE); + var remainingLinesIndex = 0; + var shiftNextLine = function() { + var lineContents = getNextLine(); + // The last line of a file might not have a newline. + var newLine = getNextLine() || ""; + return lineContents + newLine; + + function getNextLine() { + return remainingLinesIndex < remainingLines.length ? + remainingLines[remainingLinesIndex++] : undefined; + } + }; + + // We need to remember the position of "remainingLines" + var lastGeneratedLine = 1, lastGeneratedColumn = 0; + + // The generate SourceNodes we need a code range. + // To extract it current and last mapping is used. + // Here we store the last mapping. + var lastMapping = null; + + aSourceMapConsumer.eachMapping(function (mapping) { + if (lastMapping !== null) { + // We add the code from "lastMapping" to "mapping": + // First check if there is a new line in between. + if (lastGeneratedLine < mapping.generatedLine) { + // Associate first line with "lastMapping" + addMappingWithCode(lastMapping, shiftNextLine()); + lastGeneratedLine++; + lastGeneratedColumn = 0; + // The remaining code is added without mapping + } else { + // There is no new line in between. + // Associate the code between "lastGeneratedColumn" and + // "mapping.generatedColumn" with "lastMapping" + var nextLine = remainingLines[remainingLinesIndex] || ''; + var code = nextLine.substr(0, mapping.generatedColumn - + lastGeneratedColumn); + remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn - + lastGeneratedColumn); + lastGeneratedColumn = mapping.generatedColumn; + addMappingWithCode(lastMapping, code); + // No more remaining code, continue + lastMapping = mapping; + return; + } + } + // We add the generated code until the first mapping + // to the SourceNode without any mapping. + // Each line is added as separate string. + while (lastGeneratedLine < mapping.generatedLine) { + node.add(shiftNextLine()); + lastGeneratedLine++; + } + if (lastGeneratedColumn < mapping.generatedColumn) { + var nextLine = remainingLines[remainingLinesIndex] || ''; + node.add(nextLine.substr(0, mapping.generatedColumn)); + remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn); + lastGeneratedColumn = mapping.generatedColumn; + } + lastMapping = mapping; + }, this); + // We have processed all mappings. + if (remainingLinesIndex < remainingLines.length) { + if (lastMapping) { + // Associate the remaining code in the current line with "lastMapping" + addMappingWithCode(lastMapping, shiftNextLine()); + } + // and add the remaining lines without any mapping + node.add(remainingLines.splice(remainingLinesIndex).join("")); + } + + // Copy sourcesContent into SourceNode + aSourceMapConsumer.sources.forEach(function (sourceFile) { + var content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content != null) { + if (aRelativePath != null) { + sourceFile = util.join(aRelativePath, sourceFile); + } + node.setSourceContent(sourceFile, content); + } + }); + + return node; + + function addMappingWithCode(mapping, code) { + if (mapping === null || mapping.source === undefined) { + node.add(code); + } else { + var source = aRelativePath + ? util.join(aRelativePath, mapping.source) + : mapping.source; + node.add(new SourceNode(mapping.originalLine, + mapping.originalColumn, + source, + code, + mapping.name)); + } + } + }; + +/** + * Add a chunk of generated JS to this source node. + * + * @param aChunk A string snippet of generated JS code, another instance of + * SourceNode, or an array where each member is one of those things. + */ +SourceNode.prototype.add = function SourceNode_add(aChunk) { + if (Array.isArray(aChunk)) { + aChunk.forEach(function (chunk) { + this.add(chunk); + }, this); + } + else if (aChunk[isSourceNode] || typeof aChunk === "string") { + if (aChunk) { + this.children.push(aChunk); + } + } + else { + throw new TypeError( + "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk + ); + } + return this; +}; + +/** + * Add a chunk of generated JS to the beginning of this source node. + * + * @param aChunk A string snippet of generated JS code, another instance of + * SourceNode, or an array where each member is one of those things. + */ +SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) { + if (Array.isArray(aChunk)) { + for (var i = aChunk.length-1; i >= 0; i--) { + this.prepend(aChunk[i]); + } + } + else if (aChunk[isSourceNode] || typeof aChunk === "string") { + this.children.unshift(aChunk); + } + else { + throw new TypeError( + "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk + ); + } + return this; +}; + +/** + * Walk over the tree of JS snippets in this node and its children. The + * walking function is called once for each snippet of JS and is passed that + * snippet and the its original associated source's line/column location. + * + * @param aFn The traversal function. + */ +SourceNode.prototype.walk = function SourceNode_walk(aFn) { + var chunk; + for (var i = 0, len = this.children.length; i < len; i++) { + chunk = this.children[i]; + if (chunk[isSourceNode]) { + chunk.walk(aFn); + } + else { + if (chunk !== '') { + aFn(chunk, { source: this.source, + line: this.line, + column: this.column, + name: this.name }); + } + } + } +}; + +/** + * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between + * each of `this.children`. + * + * @param aSep The separator. + */ +SourceNode.prototype.join = function SourceNode_join(aSep) { + var newChildren; + var i; + var len = this.children.length; + if (len > 0) { + newChildren = []; + for (i = 0; i < len-1; i++) { + newChildren.push(this.children[i]); + newChildren.push(aSep); + } + newChildren.push(this.children[i]); + this.children = newChildren; + } + return this; +}; + +/** + * Call String.prototype.replace on the very right-most source snippet. Useful + * for trimming whitespace from the end of a source node, etc. + * + * @param aPattern The pattern to replace. + * @param aReplacement The thing to replace the pattern with. + */ +SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) { + var lastChild = this.children[this.children.length - 1]; + if (lastChild[isSourceNode]) { + lastChild.replaceRight(aPattern, aReplacement); + } + else if (typeof lastChild === 'string') { + this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement); + } + else { + this.children.push(''.replace(aPattern, aReplacement)); + } + return this; +}; + +/** + * Set the source content for a source file. This will be added to the SourceMapGenerator + * in the sourcesContent field. + * + * @param aSourceFile The filename of the source file + * @param aSourceContent The content of the source file + */ +SourceNode.prototype.setSourceContent = + function SourceNode_setSourceContent(aSourceFile, aSourceContent) { + this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent; + }; + +/** + * Walk over the tree of SourceNodes. The walking function is called for each + * source file content and is passed the filename and source content. + * + * @param aFn The traversal function. + */ +SourceNode.prototype.walkSourceContents = + function SourceNode_walkSourceContents(aFn) { + for (var i = 0, len = this.children.length; i < len; i++) { + if (this.children[i][isSourceNode]) { + this.children[i].walkSourceContents(aFn); + } + } + + var sources = Object.keys(this.sourceContents); + for (var i = 0, len = sources.length; i < len; i++) { + aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]); + } + }; + +/** + * Return the string representation of this source node. Walks over the tree + * and concatenates all the various snippets together to one string. + */ +SourceNode.prototype.toString = function SourceNode_toString() { + var str = ""; + this.walk(function (chunk) { + str += chunk; + }); + return str; +}; + +/** + * Returns the string representation of this source node along with a source + * map. + */ +SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) { + var generated = { + code: "", + line: 1, + column: 0 + }; + var map = new SourceMapGenerator(aArgs); + var sourceMappingActive = false; + var lastOriginalSource = null; + var lastOriginalLine = null; + var lastOriginalColumn = null; + var lastOriginalName = null; + this.walk(function (chunk, original) { + generated.code += chunk; + if (original.source !== null + && original.line !== null + && original.column !== null) { + if(lastOriginalSource !== original.source + || lastOriginalLine !== original.line + || lastOriginalColumn !== original.column + || lastOriginalName !== original.name) { + map.addMapping({ + source: original.source, + original: { + line: original.line, + column: original.column + }, + generated: { + line: generated.line, + column: generated.column + }, + name: original.name + }); + } + lastOriginalSource = original.source; + lastOriginalLine = original.line; + lastOriginalColumn = original.column; + lastOriginalName = original.name; + sourceMappingActive = true; + } else if (sourceMappingActive) { + map.addMapping({ + generated: { + line: generated.line, + column: generated.column + } + }); + lastOriginalSource = null; + sourceMappingActive = false; + } + for (var idx = 0, length = chunk.length; idx < length; idx++) { + if (chunk.charCodeAt(idx) === NEWLINE_CODE) { + generated.line++; + generated.column = 0; + // Mappings end at eol + if (idx + 1 === length) { + lastOriginalSource = null; + sourceMappingActive = false; + } else if (sourceMappingActive) { + map.addMapping({ + source: original.source, + original: { + line: original.line, + column: original.column + }, + generated: { + line: generated.line, + column: generated.column + }, + name: original.name + }); + } + } else { + generated.column++; + } + } + }); + this.walkSourceContents(function (sourceFile, sourceContent) { + map.setSourceContent(sourceFile, sourceContent); + }); + + return { code: generated.code, map: map }; +}; + +exports.SourceNode = SourceNode; diff --git a/node_modules/source-map/lib/util.js b/node_modules/source-map/lib/util.js new file mode 100644 index 0000000..3ca92e5 --- /dev/null +++ b/node_modules/source-map/lib/util.js @@ -0,0 +1,488 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +/** + * This is a helper function for getting values from parameter/options + * objects. + * + * @param args The object we are extracting values from + * @param name The name of the property we are getting. + * @param defaultValue An optional value to return if the property is missing + * from the object. If this is not specified and the property is missing, an + * error will be thrown. + */ +function getArg(aArgs, aName, aDefaultValue) { + if (aName in aArgs) { + return aArgs[aName]; + } else if (arguments.length === 3) { + return aDefaultValue; + } else { + throw new Error('"' + aName + '" is a required argument.'); + } +} +exports.getArg = getArg; + +var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/; +var dataUrlRegexp = /^data:.+\,.+$/; + +function urlParse(aUrl) { + var match = aUrl.match(urlRegexp); + if (!match) { + return null; + } + return { + scheme: match[1], + auth: match[2], + host: match[3], + port: match[4], + path: match[5] + }; +} +exports.urlParse = urlParse; + +function urlGenerate(aParsedUrl) { + var url = ''; + if (aParsedUrl.scheme) { + url += aParsedUrl.scheme + ':'; + } + url += '//'; + if (aParsedUrl.auth) { + url += aParsedUrl.auth + '@'; + } + if (aParsedUrl.host) { + url += aParsedUrl.host; + } + if (aParsedUrl.port) { + url += ":" + aParsedUrl.port + } + if (aParsedUrl.path) { + url += aParsedUrl.path; + } + return url; +} +exports.urlGenerate = urlGenerate; + +/** + * Normalizes a path, or the path portion of a URL: + * + * - Replaces consecutive slashes with one slash. + * - Removes unnecessary '.' parts. + * - Removes unnecessary '/..' parts. + * + * Based on code in the Node.js 'path' core module. + * + * @param aPath The path or url to normalize. + */ +function normalize(aPath) { + var path = aPath; + var url = urlParse(aPath); + if (url) { + if (!url.path) { + return aPath; + } + path = url.path; + } + var isAbsolute = exports.isAbsolute(path); + + var parts = path.split(/\/+/); + for (var part, up = 0, i = parts.length - 1; i >= 0; i--) { + part = parts[i]; + if (part === '.') { + parts.splice(i, 1); + } else if (part === '..') { + up++; + } else if (up > 0) { + if (part === '') { + // The first part is blank if the path is absolute. Trying to go + // above the root is a no-op. Therefore we can remove all '..' parts + // directly after the root. + parts.splice(i + 1, up); + up = 0; + } else { + parts.splice(i, 2); + up--; + } + } + } + path = parts.join('/'); + + if (path === '') { + path = isAbsolute ? '/' : '.'; + } + + if (url) { + url.path = path; + return urlGenerate(url); + } + return path; +} +exports.normalize = normalize; + +/** + * Joins two paths/URLs. + * + * @param aRoot The root path or URL. + * @param aPath The path or URL to be joined with the root. + * + * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a + * scheme-relative URL: Then the scheme of aRoot, if any, is prepended + * first. + * - Otherwise aPath is a path. If aRoot is a URL, then its path portion + * is updated with the result and aRoot is returned. Otherwise the result + * is returned. + * - If aPath is absolute, the result is aPath. + * - Otherwise the two paths are joined with a slash. + * - Joining for example 'http://' and 'www.example.com' is also supported. + */ +function join(aRoot, aPath) { + if (aRoot === "") { + aRoot = "."; + } + if (aPath === "") { + aPath = "."; + } + var aPathUrl = urlParse(aPath); + var aRootUrl = urlParse(aRoot); + if (aRootUrl) { + aRoot = aRootUrl.path || '/'; + } + + // `join(foo, '//www.example.org')` + if (aPathUrl && !aPathUrl.scheme) { + if (aRootUrl) { + aPathUrl.scheme = aRootUrl.scheme; + } + return urlGenerate(aPathUrl); + } + + if (aPathUrl || aPath.match(dataUrlRegexp)) { + return aPath; + } + + // `join('http://', 'www.example.com')` + if (aRootUrl && !aRootUrl.host && !aRootUrl.path) { + aRootUrl.host = aPath; + return urlGenerate(aRootUrl); + } + + var joined = aPath.charAt(0) === '/' + ? aPath + : normalize(aRoot.replace(/\/+$/, '') + '/' + aPath); + + if (aRootUrl) { + aRootUrl.path = joined; + return urlGenerate(aRootUrl); + } + return joined; +} +exports.join = join; + +exports.isAbsolute = function (aPath) { + return aPath.charAt(0) === '/' || urlRegexp.test(aPath); +}; + +/** + * Make a path relative to a URL or another path. + * + * @param aRoot The root path or URL. + * @param aPath The path or URL to be made relative to aRoot. + */ +function relative(aRoot, aPath) { + if (aRoot === "") { + aRoot = "."; + } + + aRoot = aRoot.replace(/\/$/, ''); + + // It is possible for the path to be above the root. In this case, simply + // checking whether the root is a prefix of the path won't work. Instead, we + // need to remove components from the root one by one, until either we find + // a prefix that fits, or we run out of components to remove. + var level = 0; + while (aPath.indexOf(aRoot + '/') !== 0) { + var index = aRoot.lastIndexOf("/"); + if (index < 0) { + return aPath; + } + + // If the only part of the root that is left is the scheme (i.e. http://, + // file:///, etc.), one or more slashes (/), or simply nothing at all, we + // have exhausted all components, so the path is not relative to the root. + aRoot = aRoot.slice(0, index); + if (aRoot.match(/^([^\/]+:\/)?\/*$/)) { + return aPath; + } + + ++level; + } + + // Make sure we add a "../" for each component we removed from the root. + return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1); +} +exports.relative = relative; + +var supportsNullProto = (function () { + var obj = Object.create(null); + return !('__proto__' in obj); +}()); + +function identity (s) { + return s; +} + +/** + * Because behavior goes wacky when you set `__proto__` on objects, we + * have to prefix all the strings in our set with an arbitrary character. + * + * See https://github.com/mozilla/source-map/pull/31 and + * https://github.com/mozilla/source-map/issues/30 + * + * @param String aStr + */ +function toSetString(aStr) { + if (isProtoString(aStr)) { + return '$' + aStr; + } + + return aStr; +} +exports.toSetString = supportsNullProto ? identity : toSetString; + +function fromSetString(aStr) { + if (isProtoString(aStr)) { + return aStr.slice(1); + } + + return aStr; +} +exports.fromSetString = supportsNullProto ? identity : fromSetString; + +function isProtoString(s) { + if (!s) { + return false; + } + + var length = s.length; + + if (length < 9 /* "__proto__".length */) { + return false; + } + + if (s.charCodeAt(length - 1) !== 95 /* '_' */ || + s.charCodeAt(length - 2) !== 95 /* '_' */ || + s.charCodeAt(length - 3) !== 111 /* 'o' */ || + s.charCodeAt(length - 4) !== 116 /* 't' */ || + s.charCodeAt(length - 5) !== 111 /* 'o' */ || + s.charCodeAt(length - 6) !== 114 /* 'r' */ || + s.charCodeAt(length - 7) !== 112 /* 'p' */ || + s.charCodeAt(length - 8) !== 95 /* '_' */ || + s.charCodeAt(length - 9) !== 95 /* '_' */) { + return false; + } + + for (var i = length - 10; i >= 0; i--) { + if (s.charCodeAt(i) !== 36 /* '$' */) { + return false; + } + } + + return true; +} + +/** + * Comparator between two mappings where the original positions are compared. + * + * Optionally pass in `true` as `onlyCompareGenerated` to consider two + * mappings with the same original source/line/column, but different generated + * line and column the same. Useful when searching for a mapping with a + * stubbed out mapping. + */ +function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) { + var cmp = strcmp(mappingA.source, mappingB.source); + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0 || onlyCompareOriginal) { + return cmp; + } + + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } + + return strcmp(mappingA.name, mappingB.name); +} +exports.compareByOriginalPositions = compareByOriginalPositions; + +/** + * Comparator between two mappings with deflated source and name indices where + * the generated positions are compared. + * + * Optionally pass in `true` as `onlyCompareGenerated` to consider two + * mappings with the same generated line and column, but different + * source/name/original line and column the same. Useful when searching for a + * mapping with a stubbed out mapping. + */ +function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) { + var cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0 || onlyCompareGenerated) { + return cmp; + } + + cmp = strcmp(mappingA.source, mappingB.source); + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0) { + return cmp; + } + + return strcmp(mappingA.name, mappingB.name); +} +exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated; + +function strcmp(aStr1, aStr2) { + if (aStr1 === aStr2) { + return 0; + } + + if (aStr1 === null) { + return 1; // aStr2 !== null + } + + if (aStr2 === null) { + return -1; // aStr1 !== null + } + + if (aStr1 > aStr2) { + return 1; + } + + return -1; +} + +/** + * Comparator between two mappings with inflated source and name strings where + * the generated positions are compared. + */ +function compareByGeneratedPositionsInflated(mappingA, mappingB) { + var cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0) { + return cmp; + } + + cmp = strcmp(mappingA.source, mappingB.source); + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0) { + return cmp; + } + + return strcmp(mappingA.name, mappingB.name); +} +exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated; + +/** + * Strip any JSON XSSI avoidance prefix from the string (as documented + * in the source maps specification), and then parse the string as + * JSON. + */ +function parseSourceMapInput(str) { + return JSON.parse(str.replace(/^\)]}'[^\n]*\n/, '')); +} +exports.parseSourceMapInput = parseSourceMapInput; + +/** + * Compute the URL of a source given the the source root, the source's + * URL, and the source map's URL. + */ +function computeSourceURL(sourceRoot, sourceURL, sourceMapURL) { + sourceURL = sourceURL || ''; + + if (sourceRoot) { + // This follows what Chrome does. + if (sourceRoot[sourceRoot.length - 1] !== '/' && sourceURL[0] !== '/') { + sourceRoot += '/'; + } + // The spec says: + // Line 4: An optional source root, useful for relocating source + // files on a server or removing repeated values in the + // “sources” entry. This value is prepended to the individual + // entries in the “source” field. + sourceURL = sourceRoot + sourceURL; + } + + // Historically, SourceMapConsumer did not take the sourceMapURL as + // a parameter. This mode is still somewhat supported, which is why + // this code block is conditional. However, it's preferable to pass + // the source map URL to SourceMapConsumer, so that this function + // can implement the source URL resolution algorithm as outlined in + // the spec. This block is basically the equivalent of: + // new URL(sourceURL, sourceMapURL).toString() + // ... except it avoids using URL, which wasn't available in the + // older releases of node still supported by this library. + // + // The spec says: + // If the sources are not absolute URLs after prepending of the + // “sourceRoot”, the sources are resolved relative to the + // SourceMap (like resolving script src in a html document). + if (sourceMapURL) { + var parsed = urlParse(sourceMapURL); + if (!parsed) { + throw new Error("sourceMapURL could not be parsed"); + } + if (parsed.path) { + // Strip the last path component, but keep the "/". + var index = parsed.path.lastIndexOf('/'); + if (index >= 0) { + parsed.path = parsed.path.substring(0, index + 1); + } + } + sourceURL = join(urlGenerate(parsed), sourceURL); + } + + return normalize(sourceURL); +} +exports.computeSourceURL = computeSourceURL; diff --git a/node_modules/source-map/package.json b/node_modules/source-map/package.json new file mode 100644 index 0000000..68e480d --- /dev/null +++ b/node_modules/source-map/package.json @@ -0,0 +1,212 @@ +{ + "_from": "source-map@^0.6.0", + "_id": "source-map@0.6.1", + "_inBundle": false, + "_integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", + "_location": "/source-map", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "source-map@^0.6.0", + "name": "source-map", + "escapedName": "source-map", + "rawSpec": "^0.6.0", + "saveSpec": null, + "fetchSpec": "^0.6.0" + }, + "_requiredBy": [ + "/source-map-support" + ], + "_resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "_shasum": "74722af32e9614e9c287a8d0bbde48b5e2f1a263", + "_spec": "source-map@^0.6.0", + "_where": "/Users/jessitron/code/jessitron/stringify-tree/node_modules/source-map-support", + "author": { + "name": "Nick Fitzgerald", + "email": "nfitzgerald@mozilla.com" + }, + "bugs": { + "url": "https://github.com/mozilla/source-map/issues" + }, + "bundleDependencies": false, + "contributors": [ + { + "name": "Tobias Koppers", + "email": "tobias.koppers@googlemail.com" + }, + { + "name": "Duncan Beevers", + "email": "duncan@dweebd.com" + }, + { + "name": "Stephen Crane", + "email": "scrane@mozilla.com" + }, + { + "name": "Ryan Seddon", + "email": "seddon.ryan@gmail.com" + }, + { + "name": "Miles Elam", + "email": "miles.elam@deem.com" + }, + { + "name": "Mihai Bazon", + "email": "mihai.bazon@gmail.com" + }, + { + "name": "Michael Ficarra", + "email": "github.public.email@michael.ficarra.me" + }, + { + "name": "Todd Wolfson", + "email": "todd@twolfson.com" + }, + { + "name": "Alexander Solovyov", + "email": "alexander@solovyov.net" + }, + { + "name": "Felix Gnass", + "email": "fgnass@gmail.com" + }, + { + "name": "Conrad Irwin", + "email": "conrad.irwin@gmail.com" + }, + { + "name": "usrbincc", + "email": "usrbincc@yahoo.com" + }, + { + "name": "David Glasser", + "email": "glasser@davidglasser.net" + }, + { + "name": "Chase Douglas", + "email": "chase@newrelic.com" + }, + { + "name": "Evan Wallace", + "email": "evan.exe@gmail.com" + }, + { + "name": "Heather Arthur", + "email": "fayearthur@gmail.com" + }, + { + "name": "Hugh Kennedy", + "email": "hughskennedy@gmail.com" + }, + { + "name": "David Glasser", + "email": "glasser@davidglasser.net" + }, + { + "name": "Simon Lydell", + "email": "simon.lydell@gmail.com" + }, + { + "name": "Jmeas Smith", + "email": "jellyes2@gmail.com" + }, + { + "name": "Michael Z Goddard", + "email": "mzgoddard@gmail.com" + }, + { + "name": "azu", + "email": "azu@users.noreply.github.com" + }, + { + "name": "John Gozde", + "email": "john@gozde.ca" + }, + { + "name": "Adam Kirkton", + "email": "akirkton@truefitinnovation.com" + }, + { + "name": "Chris Montgomery", + "email": "christopher.montgomery@dowjones.com" + }, + { + "name": "J. Ryan Stinnett", + "email": "jryans@gmail.com" + }, + { + "name": "Jack Herrington", + "email": "jherrington@walmartlabs.com" + }, + { + "name": "Chris Truter", + "email": "jeffpalentine@gmail.com" + }, + { + "name": "Daniel Espeset", + "email": "daniel@danielespeset.com" + }, + { + "name": "Jamie Wong", + "email": "jamie.lf.wong@gmail.com" + }, + { + "name": "Eddy Bruël", + "email": "ejpbruel@mozilla.com" + }, + { + "name": "Hawken Rives", + "email": "hawkrives@gmail.com" + }, + { + "name": "Gilad Peleg", + "email": "giladp007@gmail.com" + }, + { + "name": "djchie", + "email": "djchie.dev@gmail.com" + }, + { + "name": "Gary Ye", + "email": "garysye@gmail.com" + }, + { + "name": "Nicolas Lalevée", + "email": "nicolas.lalevee@hibnet.org" + } + ], + "deprecated": false, + "description": "Generates and consumes source maps", + "devDependencies": { + "doctoc": "^0.15.0", + "webpack": "^1.12.0" + }, + "engines": { + "node": ">=0.10.0" + }, + "files": [ + "source-map.js", + "source-map.d.ts", + "lib/", + "dist/source-map.debug.js", + "dist/source-map.js", + "dist/source-map.min.js", + "dist/source-map.min.js.map" + ], + "homepage": "https://github.com/mozilla/source-map", + "license": "BSD-3-Clause", + "main": "./source-map.js", + "name": "source-map", + "repository": { + "type": "git", + "url": "git+ssh://git@github.com/mozilla/source-map.git" + }, + "scripts": { + "build": "webpack --color", + "test": "npm run build && node test/run-tests.js", + "toc": "doctoc --title '## Table of Contents' README.md && doctoc --title '## Table of Contents' CONTRIBUTING.md" + }, + "typings": "source-map", + "version": "0.6.1" +} diff --git a/node_modules/source-map/source-map.d.ts b/node_modules/source-map/source-map.d.ts new file mode 100644 index 0000000..8f972b0 --- /dev/null +++ b/node_modules/source-map/source-map.d.ts @@ -0,0 +1,98 @@ +export interface StartOfSourceMap { + file?: string; + sourceRoot?: string; +} + +export interface RawSourceMap extends StartOfSourceMap { + version: string; + sources: string[]; + names: string[]; + sourcesContent?: string[]; + mappings: string; +} + +export interface Position { + line: number; + column: number; +} + +export interface LineRange extends Position { + lastColumn: number; +} + +export interface FindPosition extends Position { + // SourceMapConsumer.GREATEST_LOWER_BOUND or SourceMapConsumer.LEAST_UPPER_BOUND + bias?: number; +} + +export interface SourceFindPosition extends FindPosition { + source: string; +} + +export interface MappedPosition extends Position { + source: string; + name?: string; +} + +export interface MappingItem { + source: string; + generatedLine: number; + generatedColumn: number; + originalLine: number; + originalColumn: number; + name: string; +} + +export class SourceMapConsumer { + static GENERATED_ORDER: number; + static ORIGINAL_ORDER: number; + + static GREATEST_LOWER_BOUND: number; + static LEAST_UPPER_BOUND: number; + + constructor(rawSourceMap: RawSourceMap); + computeColumnSpans(): void; + originalPositionFor(generatedPosition: FindPosition): MappedPosition; + generatedPositionFor(originalPosition: SourceFindPosition): LineRange; + allGeneratedPositionsFor(originalPosition: MappedPosition): Position[]; + hasContentsOfAllSources(): boolean; + sourceContentFor(source: string, returnNullOnMissing?: boolean): string; + eachMapping(callback: (mapping: MappingItem) => void, context?: any, order?: number): void; +} + +export interface Mapping { + generated: Position; + original: Position; + source: string; + name?: string; +} + +export class SourceMapGenerator { + constructor(startOfSourceMap?: StartOfSourceMap); + static fromSourceMap(sourceMapConsumer: SourceMapConsumer): SourceMapGenerator; + addMapping(mapping: Mapping): void; + setSourceContent(sourceFile: string, sourceContent: string): void; + applySourceMap(sourceMapConsumer: SourceMapConsumer, sourceFile?: string, sourceMapPath?: string): void; + toString(): string; +} + +export interface CodeWithSourceMap { + code: string; + map: SourceMapGenerator; +} + +export class SourceNode { + constructor(); + constructor(line: number, column: number, source: string); + constructor(line: number, column: number, source: string, chunk?: string, name?: string); + static fromStringWithSourceMap(code: string, sourceMapConsumer: SourceMapConsumer, relativePath?: string): SourceNode; + add(chunk: string): void; + prepend(chunk: string): void; + setSourceContent(sourceFile: string, sourceContent: string): void; + walk(fn: (chunk: string, mapping: MappedPosition) => void): void; + walkSourceContents(fn: (file: string, content: string) => void): void; + join(sep: string): SourceNode; + replaceRight(pattern: string, replacement: string): SourceNode; + toString(): string; + toStringWithSourceMap(startOfSourceMap?: StartOfSourceMap): CodeWithSourceMap; +} diff --git a/node_modules/source-map/source-map.js b/node_modules/source-map/source-map.js new file mode 100644 index 0000000..bc88fe8 --- /dev/null +++ b/node_modules/source-map/source-map.js @@ -0,0 +1,8 @@ +/* + * Copyright 2009-2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE.txt or: + * http://opensource.org/licenses/BSD-3-Clause + */ +exports.SourceMapGenerator = require('./lib/source-map-generator').SourceMapGenerator; +exports.SourceMapConsumer = require('./lib/source-map-consumer').SourceMapConsumer; +exports.SourceNode = require('./lib/source-node').SourceNode; diff --git a/node_modules/supports-color/browser.js b/node_modules/supports-color/browser.js new file mode 100644 index 0000000..62afa3a --- /dev/null +++ b/node_modules/supports-color/browser.js @@ -0,0 +1,5 @@ +'use strict'; +module.exports = { + stdout: false, + stderr: false +}; diff --git a/node_modules/supports-color/index.js b/node_modules/supports-color/index.js new file mode 100644 index 0000000..62d14de --- /dev/null +++ b/node_modules/supports-color/index.js @@ -0,0 +1,131 @@ +'use strict'; +const os = require('os'); +const hasFlag = require('has-flag'); + +const env = process.env; + +let forceColor; +if (hasFlag('no-color') || + hasFlag('no-colors') || + hasFlag('color=false')) { + forceColor = false; +} else if (hasFlag('color') || + hasFlag('colors') || + hasFlag('color=true') || + hasFlag('color=always')) { + forceColor = true; +} +if ('FORCE_COLOR' in env) { + forceColor = env.FORCE_COLOR.length === 0 || parseInt(env.FORCE_COLOR, 10) !== 0; +} + +function translateLevel(level) { + if (level === 0) { + return false; + } + + return { + level, + hasBasic: true, + has256: level >= 2, + has16m: level >= 3 + }; +} + +function supportsColor(stream) { + if (forceColor === false) { + return 0; + } + + if (hasFlag('color=16m') || + hasFlag('color=full') || + hasFlag('color=truecolor')) { + return 3; + } + + if (hasFlag('color=256')) { + return 2; + } + + if (stream && !stream.isTTY && forceColor !== true) { + return 0; + } + + const min = forceColor ? 1 : 0; + + if (process.platform === 'win32') { + // Node.js 7.5.0 is the first version of Node.js to include a patch to + // libuv that enables 256 color output on Windows. Anything earlier and it + // won't work. However, here we target Node.js 8 at minimum as it is an LTS + // release, and Node.js 7 is not. Windows 10 build 10586 is the first Windows + // release that supports 256 colors. Windows 10 build 14931 is the first release + // that supports 16m/TrueColor. + const osRelease = os.release().split('.'); + if ( + Number(process.versions.node.split('.')[0]) >= 8 && + Number(osRelease[0]) >= 10 && + Number(osRelease[2]) >= 10586 + ) { + return Number(osRelease[2]) >= 14931 ? 3 : 2; + } + + return 1; + } + + if ('CI' in env) { + if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(sign => sign in env) || env.CI_NAME === 'codeship') { + return 1; + } + + return min; + } + + if ('TEAMCITY_VERSION' in env) { + return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0; + } + + if (env.COLORTERM === 'truecolor') { + return 3; + } + + if ('TERM_PROGRAM' in env) { + const version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10); + + switch (env.TERM_PROGRAM) { + case 'iTerm.app': + return version >= 3 ? 3 : 2; + case 'Apple_Terminal': + return 2; + // No default + } + } + + if (/-256(color)?$/i.test(env.TERM)) { + return 2; + } + + if (/^screen|^xterm|^vt100|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) { + return 1; + } + + if ('COLORTERM' in env) { + return 1; + } + + if (env.TERM === 'dumb') { + return min; + } + + return min; +} + +function getSupportLevel(stream) { + const level = supportsColor(stream); + return translateLevel(level); +} + +module.exports = { + supportsColor: getSupportLevel, + stdout: getSupportLevel(process.stdout), + stderr: getSupportLevel(process.stderr) +}; diff --git a/node_modules/supports-color/license b/node_modules/supports-color/license new file mode 100644 index 0000000..e7af2f7 --- /dev/null +++ b/node_modules/supports-color/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/supports-color/package.json b/node_modules/supports-color/package.json new file mode 100644 index 0000000..cb0eec6 --- /dev/null +++ b/node_modules/supports-color/package.json @@ -0,0 +1,85 @@ +{ + "_from": "supports-color@5.4.0", + "_id": "supports-color@5.4.0", + "_inBundle": false, + "_integrity": "sha512-zjaXglF5nnWpsq470jSv6P9DwPvgLkuapYmfDm3JWOm0vkNTVF2tI4UrN2r6jH1qM/uc/WtxYY1hYoA2dOKj5w==", + "_location": "/supports-color", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "supports-color@5.4.0", + "name": "supports-color", + "escapedName": "supports-color", + "rawSpec": "5.4.0", + "saveSpec": null, + "fetchSpec": "5.4.0" + }, + "_requiredBy": [ + "/mocha" + ], + "_resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.4.0.tgz", + "_shasum": "1c6b337402c2137605efe19f10fec390f6faab54", + "_spec": "supports-color@5.4.0", + "_where": "/Users/jessitron/code/jessitron/stringify-tree/node_modules/mocha", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "browser": "browser.js", + "bugs": { + "url": "https://github.com/chalk/supports-color/issues" + }, + "bundleDependencies": false, + "dependencies": { + "has-flag": "^3.0.0" + }, + "deprecated": false, + "description": "Detect whether a terminal supports color", + "devDependencies": { + "ava": "*", + "import-fresh": "^2.0.0", + "xo": "*" + }, + "engines": { + "node": ">=4" + }, + "files": [ + "index.js", + "browser.js" + ], + "homepage": "https://github.com/chalk/supports-color#readme", + "keywords": [ + "color", + "colour", + "colors", + "terminal", + "console", + "cli", + "ansi", + "styles", + "tty", + "rgb", + "256", + "shell", + "xterm", + "command-line", + "support", + "supports", + "capability", + "detect", + "truecolor", + "16m" + ], + "license": "MIT", + "name": "supports-color", + "repository": { + "type": "git", + "url": "git+https://github.com/chalk/supports-color.git" + }, + "scripts": { + "test": "xo && ava" + }, + "version": "5.4.0" +} diff --git a/node_modules/supports-color/readme.md b/node_modules/supports-color/readme.md new file mode 100644 index 0000000..f6e4019 --- /dev/null +++ b/node_modules/supports-color/readme.md @@ -0,0 +1,66 @@ +# supports-color [![Build Status](https://travis-ci.org/chalk/supports-color.svg?branch=master)](https://travis-ci.org/chalk/supports-color) + +> Detect whether a terminal supports color + + +## Install + +``` +$ npm install supports-color +``` + + +## Usage + +```js +const supportsColor = require('supports-color'); + +if (supportsColor.stdout) { + console.log('Terminal stdout supports color'); +} + +if (supportsColor.stdout.has256) { + console.log('Terminal stdout supports 256 colors'); +} + +if (supportsColor.stderr.has16m) { + console.log('Terminal stderr supports 16 million colors (truecolor)'); +} +``` + + +## API + +Returns an `Object` with a `stdout` and `stderr` property for testing either streams. Each property is an `Object`, or `false` if color is not supported. + +The `stdout`/`stderr` objects specifies a level of support for color through a `.level` property and a corresponding flag: + +- `.level = 1` and `.hasBasic = true`: Basic color support (16 colors) +- `.level = 2` and `.has256 = true`: 256 color support +- `.level = 3` and `.has16m = true`: Truecolor support (16 million colors) + + +## Info + +It obeys the `--color` and `--no-color` CLI flags. + +Can be overridden by the user with the flags `--color` and `--no-color`. For situations where using `--color` is not possible, add the environment variable `FORCE_COLOR=1` to forcefully enable color or `FORCE_COLOR=0` to forcefully disable. The use of `FORCE_COLOR` overrides all other color support checks. + +Explicit 256/Truecolor mode can be enabled using the `--color=256` and `--color=16m` flags, respectively. + + +## Related + +- [supports-color-cli](https://github.com/chalk/supports-color-cli) - CLI for this module +- [chalk](https://github.com/chalk/chalk) - Terminal string styling done right + + +## Maintainers + +- [Sindre Sorhus](https://github.com/sindresorhus) +- [Josh Junon](https://github.com/qix-) + + +## License + +MIT diff --git a/node_modules/ts-node/LICENSE b/node_modules/ts-node/LICENSE new file mode 100644 index 0000000..983fbe8 --- /dev/null +++ b/node_modules/ts-node/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014 Blake Embrey (hello@blakeembrey.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/ts-node/README.md b/node_modules/ts-node/README.md new file mode 100644 index 0000000..9ccc4b1 --- /dev/null +++ b/node_modules/ts-node/README.md @@ -0,0 +1,194 @@ +# ![TypeScript Node](logo.svg) + +[![NPM version][npm-image]][npm-url] +[![NPM downloads][downloads-image]][downloads-url] +[![Build status][travis-image]][travis-url] +[![Test coverage][coveralls-image]][coveralls-url] + +> TypeScript execution and REPL for node.js, with source map support. **Works with `typescript@>=2.0`**. + +## Installation + +```sh +# Locally in your project +npm install -D ts-node +npm install -D typescript + +# Or globally (not recommended) +npm install -g ts-node +npm install -g typescript +``` + +**Tip:** Installing modules locally allows you to control and share the versions through `package.json`. + +## Usage + +```sh +# Execute a script as `node` + `tsc`. +ts-node script.ts + +# Starts a TypeScript REPL. +ts-node + +# Execute code with TypeScript. +ts-node -e 'console.log("Hello, world!")' + +# Execute, and print, code with TypeScript. +ts-node -p '"Hello, world!"' + +# Pipe scripts to execute with TypeScript. +echo "console.log('Hello, world!')" | ts-node +``` + +![TypeScript REPL](https://github.com/TypeStrong/ts-node/raw/master/screenshot.png) + +### Programmatic + +You can require `ts-node` and register the loader for future requires by using `require('ts-node').register({ /* options */ })`. You can also use file shortcuts - `node -r ts-node/register` or `node -r ts-node/register/transpile-only` - depending on your preferences. + +**Note:** If you need to use advanced node.js CLI arguments (e.g. `--inspect`), use them with `node -r ts-node/register` instead of the `ts-node` CLI. + +### Mocha + +```sh +mocha --require ts-node/register --watch-extensions ts,tsx "test/**/*.{ts,tsx}" [...args] +``` + +**Note:** `--watch-extensions` is only used in `--watch` mode. + +### Tape + +```sh +ts-node node_modules/tape/bin/tape [...args] +``` + +### Gulp + +```sh +# Create a `gulpfile.ts` and run `gulp`. +gulp +``` + +### Visual Studio Code + +Create a new node.js configuration, add `-r ts-node/register` to node args and move the `program` to the `args` list (so VS Code doesn't look for `outFiles`). + +```json +{ + "type": "node", + "request": "launch", + "name": "Launch Program", + "runtimeArgs": [ + "-r", + "ts-node/register" + ], + "args": [ + "${workspaceFolder}/index.ts" + ] +} +``` + +## How It Works + +**TypeScript Node** works by registering the TypeScript compiler for `.tsx?` and `.jsx?` (when `allowJs == true`) extensions. When node.js has an extension registered (via `require.extensions`), it will use the extension internally for module resolution. When an extension is unknown to node.js, it handles the file as `.js` (JavaScript). By default, **TypeScript Node** avoids compiling files in `/node_modules/` for three reasons: + +1. Modules should always be published in a format node.js can consume +2. Transpiling the entire dependency tree will make your project slower +3. Differing behaviours between TypeScript and node.js (e.g. ES2015 modules) can result in a project that works until you decide to support a feature natively from node.js + +**P.S.** This means if you don't register an extension, it is compiled as JavaScript. When `ts-node` is used with `allowJs`, JavaScript files are transpiled using the TypeScript compiler. + +## Loading `tsconfig.json` + +**Typescript Node** loads `tsconfig.json` automatically. Use `--skip-project` to the loading `tsconfig.json`. + +**Tip**: You can use `ts-node` together with [tsconfig-paths](https://www.npmjs.com/package/tsconfig-paths) to load modules according to the `paths` section in `tsconfig.json`. + +## Configuration Options + +You can set options by passing them before the script path, via programmatic usage or via environment variables. + +```sh +ts-node --compiler ntypescript --project src/tsconfig.json hello-world.ts +``` + +### CLI Options + +Supports `--print`, `--eval` and `--require` from [node.js CLI options](https://nodejs.org/api/cli.html). + +* `--help` Prints help text +* `--version` Prints version information + +### CLI and Programmatic Options + +_Environment variable denoted in parentheses._ + +* `-T, --transpileOnly` Use TypeScript's faster `transpileModule` (`TS_NODE_TRANSPILE_ONLY`, default: `false`) +* `--cacheDirectory` Configure the output file cache directory (`TS_NODE_CACHE_DIRECTORY`) +* `-I, --ignore [pattern]` Override the path patterns to skip compilation (`TS_NODE_IGNORE`, default: `/node_modules/`) +* `-P, --project [path]` Path to TypeScript JSON project file (`TS_NODE_PROJECT`) +* `-C, --compiler [name]` Specify a custom TypeScript compiler (`TS_NODE_COMPILER`, default: `typescript`) +* `-D, --ignoreDiagnostics [code]` Ignore TypeScript warnings by diagnostic code (`TS_NODE_IGNORE_DIAGNOSTICS`) +* `-O, --compilerOptions [opts]` JSON object to merge with compiler options (`TS_NODE_COMPILER_OPTIONS`) +* `--files` Load files from `tsconfig.json` on startup (`TS_NODE_FILES`, default: `false`) +* `--pretty` Use pretty diagnostic formatter (`TS_NODE_PRETTY`, default: `false`) +* `--no-cache` Disable the local TypeScript Node cache (`TS_NODE_CACHE`, default: `true`) +* `--skip-project` Skip project config resolution and loading (`TS_NODE_SKIP_PROJECT`, default: `false`) +* `--skip-ignore` Skip ignore checks (`TS_NODE_SKIP_IGNORE`, default: `false`) + +### Programmatic Only Options + +* `transformers` An array of transformers to pass to TypeScript +* `readFile` Custom TypeScript-compatible file reading function +* `fileExists` Custom TypeScript-compatible file existence function + +## Help! My Types Are Missing! + +**TypeScript Node** does _not_ use `files`, `include` or `exclude`, by default. This is because a large majority projects do not use all of the files in a project directory (e.g. `Gulpfile.ts`, runtime vs tests) and parsing every file for types slows startup time. Instead, `ts-node` starts with the script file (e.g. `ts-node index.ts`) and TypeScript resolves dependencies based on imports and references. + +For global definitions, you can use [`typeRoots`](https://www.typescriptlang.org/docs/handbook/tsconfig-json.html#types-typeroots-and-types): + +```json +{ + "compilerOptions": { + "typeRoots" : ["./node_modules/@types", "./typings"] + } +} +``` + +> A types package is a folder with a file called `index.d.ts` or a folder with a `package.json` that has a types field. +> -- [TypeScript Handbook](https://www.typescriptlang.org/docs/handbook/tsconfig-json.html#types-typeroots-and-types) + +For module definitions, you can use [`paths`](https://www.typescriptlang.org/docs/handbook/module-resolution.html#path-mapping): + +```json +{ + "compilerOptions": { + "baseUrl": ".", + "paths": { + "custom-module-type": ["types/custom-module-type"] + } + } +} +``` + +**Tip:** If you _must_ use `files`, enable `--files` flags or set `TS_NODE_FILES=true`. + +## Watching and Restarting + +**TypeScript Node** compiles source code via `require()`, watching files and code reloads are out of scope for the project. If you want to restart the `ts-node` process on file change, existing node.js tools such as [nodemon](https://github.com/remy/nodemon), [onchange](https://github.com/Qard/onchange) and [node-dev](https://github.com/fgnass/node-dev) work. + +There's also [`ts-node-dev`](https://github.com/whitecolor/ts-node-dev), a modified version of [`node-dev`](https://github.com/fgnass/node-dev) using `ts-node` for compilation and won't restart the process on file change. + +## License + +MIT + +[npm-image]: https://img.shields.io/npm/v/ts-node.svg?style=flat +[npm-url]: https://npmjs.org/package/ts-node +[downloads-image]: https://img.shields.io/npm/dm/ts-node.svg?style=flat +[downloads-url]: https://npmjs.org/package/ts-node +[travis-image]: https://img.shields.io/travis/TypeStrong/ts-node.svg?style=flat +[travis-url]: https://travis-ci.org/TypeStrong/ts-node +[coveralls-image]: https://img.shields.io/coveralls/TypeStrong/ts-node.svg?style=flat +[coveralls-url]: https://coveralls.io/r/TypeStrong/ts-node?branch=master diff --git a/node_modules/ts-node/dist/bin.d.ts b/node_modules/ts-node/dist/bin.d.ts new file mode 100644 index 0000000..b798801 --- /dev/null +++ b/node_modules/ts-node/dist/bin.d.ts @@ -0,0 +1,2 @@ +#!/usr/bin/env node +export {}; diff --git a/node_modules/ts-node/dist/bin.js b/node_modules/ts-node/dist/bin.js new file mode 100755 index 0000000..cb130dd --- /dev/null +++ b/node_modules/ts-node/dist/bin.js @@ -0,0 +1,317 @@ +#!/usr/bin/env node +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +var path_1 = require("path"); +var repl_1 = require("repl"); +var util_1 = require("util"); +var arrify = require("arrify"); +var Module = require("module"); +var minimist = require("minimist"); +var diff_1 = require("diff"); +var vm_1 = require("vm"); +var fs_1 = require("fs"); +var index_1 = require("./index"); +var argv = minimist(process.argv.slice(2), { + stopEarly: true, + string: ['eval', 'print', 'compiler', 'project', 'ignoreDiagnostics', 'require', 'cacheDirectory', 'ignore'], + boolean: ['help', 'transpileOnly', 'typeCheck', 'version', 'files', 'cache', 'pretty', 'skipProject', 'skipIgnore'], + alias: { + eval: ['e'], + print: ['p'], + require: ['r'], + help: ['h'], + version: ['v'], + typeCheck: ['type-check'], + transpileOnly: ['T', 'transpile-only'], + cacheDirectory: ['cache-directory'], + ignore: ['I'], + project: ['P'], + skipIgnore: ['skip-ignore'], + skipProject: ['skip-project'], + compiler: ['C'], + ignoreDiagnostics: ['D', 'ignore-diagnostics'], + compilerOptions: ['O', 'compiler-options'] + }, + default: { + cache: index_1.DEFAULTS.cache, + files: index_1.DEFAULTS.files, + pretty: index_1.DEFAULTS.pretty, + typeCheck: index_1.DEFAULTS.typeCheck, + transpileOnly: index_1.DEFAULTS.transpileOnly, + cacheDirectory: index_1.DEFAULTS.cacheDirectory, + ignore: index_1.DEFAULTS.ignore, + project: index_1.DEFAULTS.project, + skipIgnore: index_1.DEFAULTS.skipIgnore, + skipProject: index_1.DEFAULTS.skipProject, + compiler: index_1.DEFAULTS.compiler, + ignoreDiagnostics: index_1.DEFAULTS.ignoreDiagnostics + } +}); +if (argv.help) { + console.log("\nUsage: ts-node [options] [ -e script | script.ts ] [arguments]\n\nOptions:\n\n -e, --eval [code] Evaluate code\n -p, --print [code] Evaluate code and print result\n -r, --require [path] Require a node module before execution\n\n -h, --help Print CLI usage\n -v, --version Print module version information\n\n -T, --transpile-only Use TypeScript's faster `transpileModule`\n --cache-directory Configure the output file cache directory\n -I, --ignore [pattern] Override the path patterns to skip compilation\n -P, --project [path] Path to TypeScript JSON project file\n -C, --compiler [name] Specify a custom TypeScript compiler\n -D, --ignoreDiagnostics [code] Ignore TypeScript warnings by diagnostic code\n -O, --compilerOptions [opts] JSON object to merge with compiler options\n\n --files Load files from `tsconfig.json` on startup\n --pretty Use pretty diagnostic formatter\n --no-cache Disable the local TypeScript Node cache\n --skip-project Skip reading `tsconfig.json`\n --skip-ignore Skip `--ignore` checks\n"); + process.exit(0); +} +var cwd = process.cwd(); +var code = argv.eval === undefined ? argv.print : argv.eval; +var isEval = typeof argv.eval === 'string' || !!argv.print; // Minimist struggles with empty strings. +var isPrinted = argv.print !== undefined; +// Register the TypeScript compiler instance. +var service = index_1.register({ + files: argv.files, + pretty: argv.pretty, + typeCheck: argv.typeCheck, + transpileOnly: argv.transpileOnly, + cache: argv.cache, + cacheDirectory: argv.cacheDirectory, + ignore: argv.ignore, + project: argv.project, + skipIgnore: argv.skipIgnore, + skipProject: argv.skipProject, + compiler: argv.compiler, + ignoreDiagnostics: argv.ignoreDiagnostics, + compilerOptions: index_1.parse(argv.compilerOptions) || index_1.DEFAULTS.compilerOptions, + readFile: isEval ? readFileEval : undefined, + fileExists: isEval ? fileExistsEval : undefined +}); +// Output project information. +if (argv.version) { + console.log("ts-node v" + index_1.VERSION); + console.log("node " + process.version); + console.log("typescript v" + service.ts.version); + console.log("cache " + JSON.stringify(service.cachedir)); + process.exit(0); +} +// Require specified modules before start-up. +Module._preloadModules(arrify(argv.require)); +/** + * Eval helpers. + */ +var EVAL_FILENAME = "[eval].ts"; +var EVAL_PATH = path_1.join(cwd, EVAL_FILENAME); +var EVAL_INSTANCE = { input: '', output: '', version: 0, lines: 0 }; +// Execute the main contents (either eval, script or piped). +if (isEval) { + evalAndExit(code, isPrinted); +} +else { + if (argv._.length) { + process.argv = ['node'].concat(path_1.resolve(cwd, argv._[0])).concat(argv._.slice(1)); + process.execArgv.unshift(__filename); + Module.runMain(); + } + else { + // Piping of execution _only_ occurs when no other script is specified. + if (process.stdin.isTTY) { + startRepl(); + } + else { + var code_1 = ''; + process.stdin.on('data', function (chunk) { return code_1 += chunk; }); + process.stdin.on('end', function () { return evalAndExit(code_1, isPrinted); }); + } + } +} +/** + * Evaluate a script. + */ +function evalAndExit(code, isPrinted) { + var module = new Module(EVAL_FILENAME); + module.filename = EVAL_FILENAME; + module.paths = Module._nodeModulePaths(cwd); + global.__filename = EVAL_FILENAME; + global.__dirname = cwd; + global.exports = module.exports; + global.module = module; + global.require = module.require.bind(module); + var result; + try { + result = _eval(code); + } + catch (error) { + if (error instanceof index_1.TSError) { + console.error(error.diagnosticText); + process.exit(1); + } + throw error; + } + if (isPrinted) { + console.log(typeof result === 'string' ? result : util_1.inspect(result)); + } +} +/** + * Evaluate the code snippet. + */ +function _eval(input) { + var lines = EVAL_INSTANCE.lines; + var isCompletion = !/\n$/.test(input); + var undo = appendEval(input); + var output; + try { + output = service.compile(EVAL_INSTANCE.input, EVAL_PATH, -lines); + } + catch (err) { + undo(); + throw err; + } + // Use `diff` to check for new JavaScript to execute. + var changes = diff_1.diffLines(EVAL_INSTANCE.output, output); + if (isCompletion) { + undo(); + } + else { + EVAL_INSTANCE.output = output; + } + return changes.reduce(function (result, change) { + return change.added ? exec(change.value, EVAL_FILENAME) : result; + }, undefined); +} +/** + * Execute some code. + */ +function exec(code, filename) { + var script = new vm_1.Script(code, { filename: filename }); + return script.runInThisContext(); +} +/** + * Start a CLI REPL. + */ +function startRepl() { + var repl = repl_1.start({ + prompt: '> ', + input: process.stdin, + output: process.stdout, + terminal: process.stdout.isTTY, + eval: replEval, + useGlobal: true + }); + // Bookmark the point where we should reset the REPL state. + var resetEval = appendEval(''); + function reset() { + resetEval(); + // Hard fix for TypeScript forcing `Object.defineProperty(exports, ...)`. + exec('exports = module.exports', EVAL_FILENAME); + } + reset(); + repl.on('reset', reset); + repl.defineCommand('type', { + help: 'Check the type of a TypeScript identifier', + action: function (identifier) { + if (!identifier) { + repl.displayPrompt(); + return; + } + var undo = appendEval(identifier); + var _a = service.getTypeInfo(EVAL_INSTANCE.input, EVAL_PATH, EVAL_INSTANCE.input.length), name = _a.name, comment = _a.comment; + undo(); + repl.outputStream.write(name + "\n" + (comment ? comment + "\n" : '')); + repl.displayPrompt(); + } + }); +} +/** + * Eval code from the REPL. + */ +function replEval(code, _context, _filename, callback) { + var err; + var result; + // TODO: Figure out how to handle completion here. + if (code === '.scope') { + callback(); + return; + } + try { + result = _eval(code); + } + catch (error) { + if (error instanceof index_1.TSError) { + // Support recoverable compilations using >= node 6. + if (repl_1.Recoverable && isRecoverable(error)) { + err = new repl_1.Recoverable(error); + } + else { + console.error(error.diagnosticText); + err = undefined; + } + } + else { + err = error; + } + } + callback(err, result); +} +/** + * Append to the eval instance and return an undo function. + */ +function appendEval(input) { + var undoInput = EVAL_INSTANCE.input; + var undoVersion = EVAL_INSTANCE.version; + var undoOutput = EVAL_INSTANCE.output; + var undoLines = EVAL_INSTANCE.lines; + // Handle ASI issues with TypeScript re-evaluation. + if (undoInput.charAt(undoInput.length - 1) === '\n' && /^\s*[\[\(\`]/.test(input) && !/;\s*$/.test(undoInput)) { + EVAL_INSTANCE.input = EVAL_INSTANCE.input.slice(0, -1) + ";\n"; + } + EVAL_INSTANCE.input += input; + EVAL_INSTANCE.lines += lineCount(input); + EVAL_INSTANCE.version++; + return function () { + EVAL_INSTANCE.input = undoInput; + EVAL_INSTANCE.output = undoOutput; + EVAL_INSTANCE.version = undoVersion; + EVAL_INSTANCE.lines = undoLines; + }; +} +/** + * Count the number of lines. + */ +function lineCount(value) { + var count = 0; + for (var _i = 0, value_1 = value; _i < value_1.length; _i++) { + var char = value_1[_i]; + if (char === '\n') { + count++; + } + } + return count; +} +/** + * Get the file text, checking for eval first. + */ +function readFileEval(path) { + if (path === EVAL_PATH) + return EVAL_INSTANCE.input; + try { + return fs_1.readFileSync(path, 'utf8'); + } + catch (err) { /* Ignore. */ } +} +/** + * Get whether the file exists. + */ +function fileExistsEval(path) { + if (path === EVAL_PATH) + return true; + try { + var stats = fs_1.statSync(path); + return stats.isFile() || stats.isFIFO(); + } + catch (err) { + return false; + } +} +var RECOVERY_CODES = new Set([ + 1003, + 1005, + 1109, + 1126, + 1160, + 1161, + 2355 // "A function whose declared type is neither 'void' nor 'any' must return a value." +]); +/** + * Check if a function can recover gracefully. + */ +function isRecoverable(error) { + return error.diagnosticCodes.every(function (code) { return RECOVERY_CODES.has(code); }); +} +//# sourceMappingURL=bin.js.map \ No newline at end of file diff --git a/node_modules/ts-node/dist/bin.js.map b/node_modules/ts-node/dist/bin.js.map new file mode 100644 index 0000000..d0f7893 --- /dev/null +++ b/node_modules/ts-node/dist/bin.js.map @@ -0,0 +1 @@ +{"version":3,"file":"bin.js","sourceRoot":"","sources":["../src/bin.ts"],"names":[],"mappings":";;;AAEA,6BAAoC;AACpC,6BAAyC;AACzC,6BAA8B;AAC9B,+BAAiC;AACjC,+BAAiC;AACjC,mCAAqC;AACrC,6BAAgC;AAChC,yBAA2B;AAC3B,yBAA2C;AAC3C,iCAAqE;AA2BrE,IAAM,IAAI,GAAG,QAAQ,CAAO,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE;IACjD,SAAS,EAAE,IAAI;IACf,MAAM,EAAE,CAAC,MAAM,EAAE,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,mBAAmB,EAAE,SAAS,EAAE,gBAAgB,EAAE,QAAQ,CAAC;IAC5G,OAAO,EAAE,CAAC,MAAM,EAAE,eAAe,EAAE,WAAW,EAAE,SAAS,EAAE,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE,aAAa,EAAE,YAAY,CAAC;IACnH,KAAK,EAAE;QACL,IAAI,EAAE,CAAC,GAAG,CAAC;QACX,KAAK,EAAE,CAAC,GAAG,CAAC;QACZ,OAAO,EAAE,CAAC,GAAG,CAAC;QACd,IAAI,EAAE,CAAC,GAAG,CAAC;QACX,OAAO,EAAE,CAAC,GAAG,CAAC;QACd,SAAS,EAAE,CAAC,YAAY,CAAC;QACzB,aAAa,EAAE,CAAC,GAAG,EAAE,gBAAgB,CAAC;QACtC,cAAc,EAAE,CAAC,iBAAiB,CAAC;QACnC,MAAM,EAAE,CAAC,GAAG,CAAC;QACb,OAAO,EAAE,CAAC,GAAG,CAAC;QACd,UAAU,EAAE,CAAC,aAAa,CAAC;QAC3B,WAAW,EAAE,CAAC,cAAc,CAAC;QAC7B,QAAQ,EAAE,CAAC,GAAG,CAAC;QACf,iBAAiB,EAAE,CAAC,GAAG,EAAE,oBAAoB,CAAC;QAC9C,eAAe,EAAE,CAAC,GAAG,EAAE,kBAAkB,CAAC;KAC3C;IACD,OAAO,EAAE;QACP,KAAK,EAAE,gBAAQ,CAAC,KAAK;QACrB,KAAK,EAAE,gBAAQ,CAAC,KAAK;QACrB,MAAM,EAAE,gBAAQ,CAAC,MAAM;QACvB,SAAS,EAAE,gBAAQ,CAAC,SAAS;QAC7B,aAAa,EAAE,gBAAQ,CAAC,aAAa;QACrC,cAAc,EAAE,gBAAQ,CAAC,cAAc;QACvC,MAAM,EAAE,gBAAQ,CAAC,MAAM;QACvB,OAAO,EAAE,gBAAQ,CAAC,OAAO;QACzB,UAAU,EAAE,gBAAQ,CAAC,UAAU;QAC/B,WAAW,EAAE,gBAAQ,CAAC,WAAW;QACjC,QAAQ,EAAE,gBAAQ,CAAC,QAAQ;QAC3B,iBAAiB,EAAE,gBAAQ,CAAC,iBAAiB;KAC9C;CACF,CAAC,CAAA;AAEF,IAAI,IAAI,CAAC,IAAI,EAAE;IACb,OAAO,CAAC,GAAG,CAAC,4uCAyBb,CAAC,CAAA;IAEA,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAA;CAChB;AAED,IAAM,GAAG,GAAG,OAAO,CAAC,GAAG,EAAE,CAAA;AACzB,IAAM,IAAI,GAAG,IAAI,CAAC,IAAI,KAAK,SAAS,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAA;AAC7D,IAAM,MAAM,GAAG,OAAO,IAAI,CAAC,IAAI,KAAK,QAAQ,IAAI,CAAC,CAAC,IAAI,CAAC,KAAK,CAAA,CAAC,yCAAyC;AACtG,IAAM,SAAS,GAAG,IAAI,CAAC,KAAK,KAAK,SAAS,CAAA;AAE1C,6CAA6C;AAC7C,IAAM,OAAO,GAAG,gBAAQ,CAAC;IACvB,KAAK,EAAE,IAAI,CAAC,KAAK;IACjB,MAAM,EAAE,IAAI,CAAC,MAAM;IACnB,SAAS,EAAE,IAAI,CAAC,SAAS;IACzB,aAAa,EAAE,IAAI,CAAC,aAAa;IACjC,KAAK,EAAE,IAAI,CAAC,KAAK;IACjB,cAAc,EAAE,IAAI,CAAC,cAAc;IACnC,MAAM,EAAE,IAAI,CAAC,MAAM;IACnB,OAAO,EAAE,IAAI,CAAC,OAAO;IACrB,UAAU,EAAE,IAAI,CAAC,UAAU;IAC3B,WAAW,EAAE,IAAI,CAAC,WAAW;IAC7B,QAAQ,EAAE,IAAI,CAAC,QAAQ;IACvB,iBAAiB,EAAE,IAAI,CAAC,iBAAiB;IACzC,eAAe,EAAE,aAAK,CAAC,IAAI,CAAC,eAAe,CAAC,IAAI,gBAAQ,CAAC,eAAe;IACxE,QAAQ,EAAE,MAAM,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC,CAAC,SAAS;IAC3C,UAAU,EAAE,MAAM,CAAC,CAAC,CAAC,cAAc,CAAC,CAAC,CAAC,SAAS;CAChD,CAAC,CAAA;AAEF,8BAA8B;AAC9B,IAAI,IAAI,CAAC,OAAO,EAAE;IAChB,OAAO,CAAC,GAAG,CAAC,cAAY,eAAS,CAAC,CAAA;IAClC,OAAO,CAAC,GAAG,CAAC,UAAQ,OAAO,CAAC,OAAS,CAAC,CAAA;IACtC,OAAO,CAAC,GAAG,CAAC,iBAAe,OAAO,CAAC,EAAE,CAAC,OAAS,CAAC,CAAA;IAChD,OAAO,CAAC,GAAG,CAAC,WAAS,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,QAAQ,CAAG,CAAC,CAAA;IACxD,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAA;CAChB;AAED,6CAA6C;AAC5C,MAAc,CAAC,eAAe,CAAC,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,CAAA;AAErD;;GAEG;AACH,IAAM,aAAa,GAAG,WAAW,CAAA;AACjC,IAAM,SAAS,GAAG,WAAI,CAAC,GAAG,EAAE,aAAa,CAAC,CAAA;AAC1C,IAAM,aAAa,GAAG,EAAE,KAAK,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,OAAO,EAAE,CAAC,EAAE,KAAK,EAAE,CAAC,EAAE,CAAA;AAErE,4DAA4D;AAC5D,IAAI,MAAM,EAAE;IACV,WAAW,CAAC,IAAc,EAAE,SAAS,CAAC,CAAA;CACvC;KAAM;IACL,IAAI,IAAI,CAAC,CAAC,CAAC,MAAM,EAAE;QACjB,OAAO,CAAC,IAAI,GAAG,CAAC,MAAM,CAAC,CAAC,MAAM,CAAC,cAAO,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAA;QAC/E,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAC,UAAU,CAAC,CAAA;QACpC,MAAM,CAAC,OAAO,EAAE,CAAA;KACjB;SAAM;QACL,uEAAuE;QACvE,IAAK,OAAO,CAAC,KAAa,CAAC,KAAK,EAAE;YAChC,SAAS,EAAE,CAAA;SACZ;aAAM;YACL,IAAI,MAAI,GAAG,EAAE,CAAA;YACb,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC,MAAM,EAAE,UAAC,KAAa,IAAK,OAAA,MAAI,IAAI,KAAK,EAAb,CAAa,CAAC,CAAA;YAC1D,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC,KAAK,EAAE,cAAM,OAAA,WAAW,CAAC,MAAI,EAAE,SAAS,CAAC,EAA5B,CAA4B,CAAC,CAAA;SAC5D;KACF;CACF;AAED;;GAEG;AACH,qBAAsB,IAAY,EAAE,SAAkB;IACpD,IAAM,MAAM,GAAG,IAAI,MAAM,CAAC,aAAa,CAAC,CAAA;IACxC,MAAM,CAAC,QAAQ,GAAG,aAAa,CAAA;IAC/B,MAAM,CAAC,KAAK,GAAI,MAAc,CAAC,gBAAgB,CAAC,GAAG,CAAC,CAEnD;IAAC,MAAc,CAAC,UAAU,GAAG,aAAa,CAC1C;IAAC,MAAc,CAAC,SAAS,GAAG,GAAG,CAC/B;IAAC,MAAc,CAAC,OAAO,GAAG,MAAM,CAAC,OAAO,CACxC;IAAC,MAAc,CAAC,MAAM,GAAG,MAAM,CAC/B;IAAC,MAAc,CAAC,OAAO,GAAG,MAAM,CAAC,OAAO,CAAC,IAAI,CAAC,MAAM,CAAC,CAAA;IAEtD,IAAI,MAAW,CAAA;IAEf,IAAI;QACF,MAAM,GAAG,KAAK,CAAC,IAAI,CAAC,CAAA;KACrB;IAAC,OAAO,KAAK,EAAE;QACd,IAAI,KAAK,YAAY,eAAO,EAAE;YAC5B,OAAO,CAAC,KAAK,CAAC,KAAK,CAAC,cAAc,CAAC,CAAA;YACnC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAA;SAChB;QAED,MAAM,KAAK,CAAA;KACZ;IAED,IAAI,SAAS,EAAE;QACb,OAAO,CAAC,GAAG,CAAC,OAAO,MAAM,KAAK,QAAQ,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,cAAO,CAAC,MAAM,CAAC,CAAC,CAAA;KACnE;AACH,CAAC;AAED;;GAEG;AACH,eAAgB,KAAa;IAC3B,IAAM,KAAK,GAAG,aAAa,CAAC,KAAK,CAAA;IACjC,IAAM,YAAY,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,CAAA;IACvC,IAAM,IAAI,GAAG,UAAU,CAAC,KAAK,CAAC,CAAA;IAC9B,IAAI,MAAc,CAAA;IAElB,IAAI;QACF,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,aAAa,CAAC,KAAK,EAAE,SAAS,EAAE,CAAC,KAAK,CAAC,CAAA;KACjE;IAAC,OAAO,GAAG,EAAE;QACZ,IAAI,EAAE,CAAA;QACN,MAAM,GAAG,CAAA;KACV;IAED,qDAAqD;IACrD,IAAM,OAAO,GAAG,gBAAS,CAAC,aAAa,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;IAEvD,IAAI,YAAY,EAAE;QAChB,IAAI,EAAE,CAAA;KACP;SAAM;QACL,aAAa,CAAC,MAAM,GAAG,MAAM,CAAA;KAC9B;IAED,OAAO,OAAO,CAAC,MAAM,CAAC,UAAC,MAAM,EAAE,MAAM;QACnC,OAAO,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,KAAK,EAAE,aAAa,CAAC,CAAC,CAAC,CAAC,MAAM,CAAA;IAClE,CAAC,EAAE,SAAS,CAAC,CAAA;AACf,CAAC;AAED;;GAEG;AACH,cAAe,IAAY,EAAE,QAAgB;IAC3C,IAAM,MAAM,GAAG,IAAI,WAAM,CAAC,IAAI,EAAE,EAAE,QAAQ,EAAE,QAAQ,EAAE,CAAC,CAAA;IAEvD,OAAO,MAAM,CAAC,gBAAgB,EAAE,CAAA;AAClC,CAAC;AAED;;GAEG;AACH;IACE,IAAM,IAAI,GAAG,YAAK,CAAC;QACjB,MAAM,EAAE,IAAI;QACZ,KAAK,EAAE,OAAO,CAAC,KAAK;QACpB,MAAM,EAAE,OAAO,CAAC,MAAM;QACtB,QAAQ,EAAE,OAAO,CAAC,MAAM,CAAC,KAAK;QAC9B,IAAI,EAAE,QAAQ;QACd,SAAS,EAAE,IAAI;KAChB,CAAC,CAAA;IAEF,2DAA2D;IAC3D,IAAM,SAAS,GAAG,UAAU,CAAC,EAAE,CAAC,CAAA;IAEhC;QACE,SAAS,EAAE,CAAA;QAEX,yEAAyE;QACzE,IAAI,CAAC,0BAA0B,EAAE,aAAa,CAAC,CAAA;IACjD,CAAC;IAED,KAAK,EAAE,CAAA;IACP,IAAI,CAAC,EAAE,CAAC,OAAO,EAAE,KAAK,CAAC,CAAA;IAEvB,IAAI,CAAC,aAAa,CAAC,MAAM,EAAE;QACzB,IAAI,EAAE,2CAA2C;QACjD,MAAM,EAAE,UAAU,UAAkB;YAClC,IAAI,CAAC,UAAU,EAAE;gBACf,IAAI,CAAC,aAAa,EAAE,CAAA;gBACpB,OAAM;aACP;YAED,IAAM,IAAI,GAAG,UAAU,CAAC,UAAU,CAAC,CAAA;YAC7B,IAAA,oFAAmG,EAAjG,cAAI,EAAE,oBAAO,CAAoF;YAEzG,IAAI,EAAE,CAAA;YAEN,IAAI,CAAC,YAAY,CAAC,KAAK,CAAI,IAAI,WAAK,OAAO,CAAC,CAAC,CAAI,OAAO,OAAI,CAAC,CAAC,CAAC,EAAE,CAAE,CAAC,CAAA;YACpE,IAAI,CAAC,aAAa,EAAE,CAAA;QACtB,CAAC;KACF,CAAC,CAAA;AACJ,CAAC;AAED;;GAEG;AACH,kBAAmB,IAAY,EAAE,QAAa,EAAE,SAAiB,EAAE,QAA4C;IAC7G,IAAI,GAAsB,CAAA;IAC1B,IAAI,MAAW,CAAA;IAEf,kDAAkD;IAClD,IAAI,IAAI,KAAK,QAAQ,EAAE;QACrB,QAAQ,EAAE,CAAA;QACV,OAAM;KACP;IAED,IAAI;QACF,MAAM,GAAG,KAAK,CAAC,IAAI,CAAC,CAAA;KACrB;IAAC,OAAO,KAAK,EAAE;QACd,IAAI,KAAK,YAAY,eAAO,EAAE;YAC5B,oDAAoD;YACpD,IAAI,kBAAW,IAAI,aAAa,CAAC,KAAK,CAAC,EAAE;gBACvC,GAAG,GAAG,IAAI,kBAAW,CAAC,KAAK,CAAC,CAAA;aAC7B;iBAAM;gBACL,OAAO,CAAC,KAAK,CAAC,KAAK,CAAC,cAAc,CAAC,CAAA;gBACnC,GAAG,GAAG,SAAS,CAAA;aAChB;SACF;aAAM;YACL,GAAG,GAAG,KAAK,CAAA;SACZ;KACF;IAED,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC,CAAA;AACvB,CAAC;AAED;;GAEG;AACH,oBAAqB,KAAa;IAChC,IAAM,SAAS,GAAG,aAAa,CAAC,KAAK,CAAA;IACrC,IAAM,WAAW,GAAG,aAAa,CAAC,OAAO,CAAA;IACzC,IAAM,UAAU,GAAG,aAAa,CAAC,MAAM,CAAA;IACvC,IAAM,SAAS,GAAG,aAAa,CAAC,KAAK,CAAA;IAErC,mDAAmD;IACnD,IAAI,SAAS,CAAC,MAAM,CAAC,SAAS,CAAC,MAAM,GAAG,CAAC,CAAC,KAAK,IAAI,IAAI,cAAc,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,SAAS,CAAC,EAAE;QAC7G,aAAa,CAAC,KAAK,GAAM,aAAa,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,QAAK,CAAA;KAC/D;IAED,aAAa,CAAC,KAAK,IAAI,KAAK,CAAA;IAC5B,aAAa,CAAC,KAAK,IAAI,SAAS,CAAC,KAAK,CAAC,CAAA;IACvC,aAAa,CAAC,OAAO,EAAE,CAAA;IAEvB,OAAO;QACL,aAAa,CAAC,KAAK,GAAG,SAAS,CAAA;QAC/B,aAAa,CAAC,MAAM,GAAG,UAAU,CAAA;QACjC,aAAa,CAAC,OAAO,GAAG,WAAW,CAAA;QACnC,aAAa,CAAC,KAAK,GAAG,SAAS,CAAA;IACjC,CAAC,CAAA;AACH,CAAC;AAED;;GAEG;AACH,mBAAoB,KAAa;IAC/B,IAAI,KAAK,GAAG,CAAC,CAAA;IAEb,KAAmB,UAAK,EAAL,eAAK,EAAL,mBAAK,EAAL,IAAK,EAAE;QAArB,IAAM,IAAI,cAAA;QACb,IAAI,IAAI,KAAK,IAAI,EAAE;YACjB,KAAK,EAAE,CAAA;SACR;KACF;IAED,OAAO,KAAK,CAAA;AACd,CAAC;AAED;;GAEG;AACH,sBAAuB,IAAY;IACjC,IAAI,IAAI,KAAK,SAAS;QAAE,OAAO,aAAa,CAAC,KAAK,CAAA;IAElD,IAAI;QACF,OAAO,iBAAY,CAAC,IAAI,EAAE,MAAM,CAAC,CAAA;KAClC;IAAC,OAAO,GAAG,EAAE,EAAC,aAAa,EAAC;AAC/B,CAAC;AAED;;GAEG;AACH,wBAAyB,IAAY;IACnC,IAAI,IAAI,KAAK,SAAS;QAAE,OAAO,IAAI,CAAA;IAEnC,IAAI;QACF,IAAM,KAAK,GAAG,aAAQ,CAAC,IAAI,CAAC,CAAA;QAC5B,OAAO,KAAK,CAAC,MAAM,EAAE,IAAI,KAAK,CAAC,MAAM,EAAE,CAAA;KACxC;IAAC,OAAO,GAAG,EAAE;QACZ,OAAO,KAAK,CAAA;KACb;AACH,CAAC;AAED,IAAM,cAAc,GAAgB,IAAI,GAAG,CAAC;IAC1C,IAAI;IACJ,IAAI;IACJ,IAAI;IACJ,IAAI;IACJ,IAAI;IACJ,IAAI;IACJ,IAAI,CAAC,oFAAoF;CAC1F,CAAC,CAAA;AAEF;;GAEG;AACH,uBAAwB,KAAc;IACpC,OAAO,KAAK,CAAC,eAAe,CAAC,KAAK,CAAC,UAAA,IAAI,IAAI,OAAA,cAAc,CAAC,GAAG,CAAC,IAAI,CAAC,EAAxB,CAAwB,CAAC,CAAA;AACtE,CAAC","sourcesContent":["#!/usr/bin/env node\n\nimport { join, resolve } from 'path'\nimport { start, Recoverable } from 'repl'\nimport { inspect } from 'util'\nimport arrify = require('arrify')\nimport Module = require('module')\nimport minimist = require('minimist')\nimport { diffLines } from 'diff'\nimport { Script } from 'vm'\nimport { readFileSync, statSync } from 'fs'\nimport { register, VERSION, DEFAULTS, TSError, parse } from './index'\n\ninterface Argv {\n // Node.js-like options.\n eval?: string\n print?: string\n require?: string | string[]\n // CLI options.\n help?: boolean\n version?: boolean\n // Register options.\n pretty?: boolean\n typeCheck?: boolean\n transpileOnly?: boolean\n files?: boolean\n cache?: boolean\n cacheDirectory?: string\n compiler?: string\n ignore?: string | string[]\n project?: string\n skipIgnore?: boolean\n skipProject?: boolean\n ignoreDiagnostics?: string | string[]\n compilerOptions?: string\n _: string[]\n}\n\nconst argv = minimist(process.argv.slice(2), {\n stopEarly: true,\n string: ['eval', 'print', 'compiler', 'project', 'ignoreDiagnostics', 'require', 'cacheDirectory', 'ignore'],\n boolean: ['help', 'transpileOnly', 'typeCheck', 'version', 'files', 'cache', 'pretty', 'skipProject', 'skipIgnore'],\n alias: {\n eval: ['e'],\n print: ['p'],\n require: ['r'],\n help: ['h'],\n version: ['v'],\n typeCheck: ['type-check'],\n transpileOnly: ['T', 'transpile-only'],\n cacheDirectory: ['cache-directory'],\n ignore: ['I'],\n project: ['P'],\n skipIgnore: ['skip-ignore'],\n skipProject: ['skip-project'],\n compiler: ['C'],\n ignoreDiagnostics: ['D', 'ignore-diagnostics'],\n compilerOptions: ['O', 'compiler-options']\n },\n default: {\n cache: DEFAULTS.cache,\n files: DEFAULTS.files,\n pretty: DEFAULTS.pretty,\n typeCheck: DEFAULTS.typeCheck,\n transpileOnly: DEFAULTS.transpileOnly,\n cacheDirectory: DEFAULTS.cacheDirectory,\n ignore: DEFAULTS.ignore,\n project: DEFAULTS.project,\n skipIgnore: DEFAULTS.skipIgnore,\n skipProject: DEFAULTS.skipProject,\n compiler: DEFAULTS.compiler,\n ignoreDiagnostics: DEFAULTS.ignoreDiagnostics\n }\n})\n\nif (argv.help) {\n console.log(`\nUsage: ts-node [options] [ -e script | script.ts ] [arguments]\n\nOptions:\n\n -e, --eval [code] Evaluate code\n -p, --print [code] Evaluate code and print result\n -r, --require [path] Require a node module before execution\n\n -h, --help Print CLI usage\n -v, --version Print module version information\n\n -T, --transpile-only Use TypeScript's faster \\`transpileModule\\`\n --cache-directory Configure the output file cache directory\n -I, --ignore [pattern] Override the path patterns to skip compilation\n -P, --project [path] Path to TypeScript JSON project file\n -C, --compiler [name] Specify a custom TypeScript compiler\n -D, --ignoreDiagnostics [code] Ignore TypeScript warnings by diagnostic code\n -O, --compilerOptions [opts] JSON object to merge with compiler options\n\n --files Load files from \\`tsconfig.json\\` on startup\n --pretty Use pretty diagnostic formatter\n --no-cache Disable the local TypeScript Node cache\n --skip-project Skip reading \\`tsconfig.json\\`\n --skip-ignore Skip \\`--ignore\\` checks\n`)\n\n process.exit(0)\n}\n\nconst cwd = process.cwd()\nconst code = argv.eval === undefined ? argv.print : argv.eval\nconst isEval = typeof argv.eval === 'string' || !!argv.print // Minimist struggles with empty strings.\nconst isPrinted = argv.print !== undefined\n\n// Register the TypeScript compiler instance.\nconst service = register({\n files: argv.files,\n pretty: argv.pretty,\n typeCheck: argv.typeCheck,\n transpileOnly: argv.transpileOnly,\n cache: argv.cache,\n cacheDirectory: argv.cacheDirectory,\n ignore: argv.ignore,\n project: argv.project,\n skipIgnore: argv.skipIgnore,\n skipProject: argv.skipProject,\n compiler: argv.compiler,\n ignoreDiagnostics: argv.ignoreDiagnostics,\n compilerOptions: parse(argv.compilerOptions) || DEFAULTS.compilerOptions,\n readFile: isEval ? readFileEval : undefined,\n fileExists: isEval ? fileExistsEval : undefined\n})\n\n// Output project information.\nif (argv.version) {\n console.log(`ts-node v${VERSION}`)\n console.log(`node ${process.version}`)\n console.log(`typescript v${service.ts.version}`)\n console.log(`cache ${JSON.stringify(service.cachedir)}`)\n process.exit(0)\n}\n\n// Require specified modules before start-up.\n(Module as any)._preloadModules(arrify(argv.require))\n\n/**\n * Eval helpers.\n */\nconst EVAL_FILENAME = `[eval].ts`\nconst EVAL_PATH = join(cwd, EVAL_FILENAME)\nconst EVAL_INSTANCE = { input: '', output: '', version: 0, lines: 0 }\n\n// Execute the main contents (either eval, script or piped).\nif (isEval) {\n evalAndExit(code as string, isPrinted)\n} else {\n if (argv._.length) {\n process.argv = ['node'].concat(resolve(cwd, argv._[0])).concat(argv._.slice(1))\n process.execArgv.unshift(__filename)\n Module.runMain()\n } else {\n // Piping of execution _only_ occurs when no other script is specified.\n if ((process.stdin as any).isTTY) {\n startRepl()\n } else {\n let code = ''\n process.stdin.on('data', (chunk: Buffer) => code += chunk)\n process.stdin.on('end', () => evalAndExit(code, isPrinted))\n }\n }\n}\n\n/**\n * Evaluate a script.\n */\nfunction evalAndExit (code: string, isPrinted: boolean) {\n const module = new Module(EVAL_FILENAME)\n module.filename = EVAL_FILENAME\n module.paths = (Module as any)._nodeModulePaths(cwd)\n\n ;(global as any).__filename = EVAL_FILENAME\n ;(global as any).__dirname = cwd\n ;(global as any).exports = module.exports\n ;(global as any).module = module\n ;(global as any).require = module.require.bind(module)\n\n let result: any\n\n try {\n result = _eval(code)\n } catch (error) {\n if (error instanceof TSError) {\n console.error(error.diagnosticText)\n process.exit(1)\n }\n\n throw error\n }\n\n if (isPrinted) {\n console.log(typeof result === 'string' ? result : inspect(result))\n }\n}\n\n/**\n * Evaluate the code snippet.\n */\nfunction _eval (input: string) {\n const lines = EVAL_INSTANCE.lines\n const isCompletion = !/\\n$/.test(input)\n const undo = appendEval(input)\n let output: string\n\n try {\n output = service.compile(EVAL_INSTANCE.input, EVAL_PATH, -lines)\n } catch (err) {\n undo()\n throw err\n }\n\n // Use `diff` to check for new JavaScript to execute.\n const changes = diffLines(EVAL_INSTANCE.output, output)\n\n if (isCompletion) {\n undo()\n } else {\n EVAL_INSTANCE.output = output\n }\n\n return changes.reduce((result, change) => {\n return change.added ? exec(change.value, EVAL_FILENAME) : result\n }, undefined)\n}\n\n/**\n * Execute some code.\n */\nfunction exec (code: string, filename: string) {\n const script = new Script(code, { filename: filename })\n\n return script.runInThisContext()\n}\n\n/**\n * Start a CLI REPL.\n */\nfunction startRepl () {\n const repl = start({\n prompt: '> ',\n input: process.stdin,\n output: process.stdout,\n terminal: process.stdout.isTTY,\n eval: replEval,\n useGlobal: true\n })\n\n // Bookmark the point where we should reset the REPL state.\n const resetEval = appendEval('')\n\n function reset () {\n resetEval()\n\n // Hard fix for TypeScript forcing `Object.defineProperty(exports, ...)`.\n exec('exports = module.exports', EVAL_FILENAME)\n }\n\n reset()\n repl.on('reset', reset)\n\n repl.defineCommand('type', {\n help: 'Check the type of a TypeScript identifier',\n action: function (identifier: string) {\n if (!identifier) {\n repl.displayPrompt()\n return\n }\n\n const undo = appendEval(identifier)\n const { name, comment } = service.getTypeInfo(EVAL_INSTANCE.input, EVAL_PATH, EVAL_INSTANCE.input.length)\n\n undo()\n\n repl.outputStream.write(`${name}\\n${comment ? `${comment}\\n` : ''}`)\n repl.displayPrompt()\n }\n })\n}\n\n/**\n * Eval code from the REPL.\n */\nfunction replEval (code: string, _context: any, _filename: string, callback: (err?: Error, result?: any) => any) {\n let err: Error | undefined\n let result: any\n\n // TODO: Figure out how to handle completion here.\n if (code === '.scope') {\n callback()\n return\n }\n\n try {\n result = _eval(code)\n } catch (error) {\n if (error instanceof TSError) {\n // Support recoverable compilations using >= node 6.\n if (Recoverable && isRecoverable(error)) {\n err = new Recoverable(error)\n } else {\n console.error(error.diagnosticText)\n err = undefined\n }\n } else {\n err = error\n }\n }\n\n callback(err, result)\n}\n\n/**\n * Append to the eval instance and return an undo function.\n */\nfunction appendEval (input: string) {\n const undoInput = EVAL_INSTANCE.input\n const undoVersion = EVAL_INSTANCE.version\n const undoOutput = EVAL_INSTANCE.output\n const undoLines = EVAL_INSTANCE.lines\n\n // Handle ASI issues with TypeScript re-evaluation.\n if (undoInput.charAt(undoInput.length - 1) === '\\n' && /^\\s*[\\[\\(\\`]/.test(input) && !/;\\s*$/.test(undoInput)) {\n EVAL_INSTANCE.input = `${EVAL_INSTANCE.input.slice(0, -1)};\\n`\n }\n\n EVAL_INSTANCE.input += input\n EVAL_INSTANCE.lines += lineCount(input)\n EVAL_INSTANCE.version++\n\n return function () {\n EVAL_INSTANCE.input = undoInput\n EVAL_INSTANCE.output = undoOutput\n EVAL_INSTANCE.version = undoVersion\n EVAL_INSTANCE.lines = undoLines\n }\n}\n\n/**\n * Count the number of lines.\n */\nfunction lineCount (value: string) {\n let count = 0\n\n for (const char of value) {\n if (char === '\\n') {\n count++\n }\n }\n\n return count\n}\n\n/**\n * Get the file text, checking for eval first.\n */\nfunction readFileEval (path: string) {\n if (path === EVAL_PATH) return EVAL_INSTANCE.input\n\n try {\n return readFileSync(path, 'utf8')\n } catch (err) {/* Ignore. */}\n}\n\n/**\n * Get whether the file exists.\n */\nfunction fileExistsEval (path: string) {\n if (path === EVAL_PATH) return true\n\n try {\n const stats = statSync(path)\n return stats.isFile() || stats.isFIFO()\n } catch (err) {\n return false\n }\n}\n\nconst RECOVERY_CODES: Set = new Set([\n 1003, // \"Identifier expected.\"\n 1005, // \"')' expected.\"\n 1109, // \"Expression expected.\"\n 1126, // \"Unexpected end of text.\"\n 1160, // \"Unterminated template literal.\"\n 1161, // \"Unterminated regular expression literal.\"\n 2355 // \"A function whose declared type is neither 'void' nor 'any' must return a value.\"\n])\n\n/**\n * Check if a function can recover gracefully.\n */\nfunction isRecoverable (error: TSError) {\n return error.diagnosticCodes.every(code => RECOVERY_CODES.has(code))\n}\n"]} \ No newline at end of file diff --git a/node_modules/ts-node/dist/index.d.ts b/node_modules/ts-node/dist/index.d.ts new file mode 100644 index 0000000..8e65f86 --- /dev/null +++ b/node_modules/ts-node/dist/index.d.ts @@ -0,0 +1,99 @@ +import { BaseError } from 'make-error'; +import * as _ts from 'typescript'; +/** + * @internal + */ +export declare const INSPECT_CUSTOM: symbol; +/** + * Common TypeScript interfaces between versions. + */ +export interface TSCommon { + version: typeof _ts.version; + sys: typeof _ts.sys; + ScriptSnapshot: typeof _ts.ScriptSnapshot; + displayPartsToString: typeof _ts.displayPartsToString; + createLanguageService: typeof _ts.createLanguageService; + getDefaultLibFilePath: typeof _ts.getDefaultLibFilePath; + getPreEmitDiagnostics: typeof _ts.getPreEmitDiagnostics; + flattenDiagnosticMessageText: typeof _ts.flattenDiagnosticMessageText; + transpileModule: typeof _ts.transpileModule; + ModuleKind: typeof _ts.ModuleKind; + ScriptTarget: typeof _ts.ScriptTarget; + findConfigFile: typeof _ts.findConfigFile; + readConfigFile: typeof _ts.readConfigFile; + parseJsonConfigFileContent: typeof _ts.parseJsonConfigFileContent; + formatDiagnostics: typeof _ts.formatDiagnostics; + formatDiagnosticsWithColorAndContext: typeof _ts.formatDiagnosticsWithColorAndContext; +} +/** + * Export the current version. + */ +export declare const VERSION: any; +/** + * Registration options. + */ +export interface Options { + pretty?: boolean | null; + typeCheck?: boolean | null; + transpileOnly?: boolean | null; + files?: boolean | null; + cache?: boolean | null; + cacheDirectory?: string; + compiler?: string; + ignore?: string | string[]; + project?: string; + skipIgnore?: boolean | null; + skipProject?: boolean | null; + compilerOptions?: object; + ignoreDiagnostics?: number | string | Array; + readFile?: (path: string) => string | undefined; + fileExists?: (path: string) => boolean; + transformers?: _ts.CustomTransformers; +} +/** + * Information retrieved from type info check. + */ +export interface TypeInfo { + name: string; + comment: string; +} +/** + * Default register options. + */ +export declare const DEFAULTS: Options; +/** + * Split a string array of values. + */ +export declare function split(value: string | undefined): string[] | undefined; +/** + * Parse a string as JSON. + */ +export declare function parse(value: string | undefined): object | undefined; +/** + * Replace backslashes with forward slashes. + */ +export declare function normalizeSlashes(value: string): string; +/** + * TypeScript diagnostics error. + */ +export declare class TSError extends BaseError { + diagnosticText: string; + diagnosticCodes: number[]; + name: string; + constructor(diagnosticText: string, diagnosticCodes: number[]); +} +/** + * Return type for registering `ts-node`. + */ +export interface Register { + cwd: string; + extensions: string[]; + cachedir: string; + ts: TSCommon; + compile(code: string, fileName: string, lineOffset?: number): string; + getTypeInfo(code: string, fileName: string, position: number): TypeInfo; +} +/** + * Register TypeScript compiler. + */ +export declare function register(opts?: Options): Register; diff --git a/node_modules/ts-node/dist/index.js b/node_modules/ts-node/dist/index.js new file mode 100644 index 0000000..1c984fe --- /dev/null +++ b/node_modules/ts-node/dist/index.js @@ -0,0 +1,462 @@ +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var path_1 = require("path"); +var fs_1 = require("fs"); +var os_1 = require("os"); +var sourceMapSupport = require("source-map-support"); +var mkdirp = require("mkdirp"); +var crypto = require("crypto"); +var yn = require("yn"); +var arrify = require("arrify"); +var bufferFrom = require("buffer-from"); +var make_error_1 = require("make-error"); +var util = require("util"); +/** + * @internal + */ +exports.INSPECT_CUSTOM = util.inspect.custom || 'inspect'; +/** + * Debugging `ts-node`. + */ +var shouldDebug = yn(process.env.TS_NODE_DEBUG); +var debug = shouldDebug ? console.log.bind(console, 'ts-node') : function () { return undefined; }; +var debugFn = shouldDebug ? + function (key, fn) { + return function (x) { + debug(key, x); + return fn(x); + }; + } : + function (_, fn) { return fn; }; +/** + * Export the current version. + */ +exports.VERSION = require('../package.json').version; +/** + * Default register options. + */ +exports.DEFAULTS = { + files: yn(process.env['TS_NODE_FILES']), + cache: yn(process.env['TS_NODE_CACHE'], { default: true }), + pretty: yn(process.env['TS_NODE_PRETTY']), + cacheDirectory: process.env['TS_NODE_CACHE_DIRECTORY'], + compiler: process.env['TS_NODE_COMPILER'], + compilerOptions: parse(process.env['TS_NODE_COMPILER_OPTIONS']), + ignore: split(process.env['TS_NODE_IGNORE']), + project: process.env['TS_NODE_PROJECT'], + skipIgnore: yn(process.env['TS_NODE_SKIP_IGNORE']), + skipProject: yn(process.env['TS_NODE_SKIP_PROJECT']), + ignoreDiagnostics: split(process.env['TS_NODE_IGNORE_DIAGNOSTICS']), + typeCheck: yn(process.env['TS_NODE_TYPE_CHECK']), + transpileOnly: yn(process.env['TS_NODE_TRANSPILE_ONLY']) +}; +/** + * Default TypeScript compiler options required by `ts-node`. + */ +var DEFAULT_COMPILER_OPTIONS = { + sourceMap: true, + inlineSourceMap: false, + inlineSources: true, + declaration: false, + noEmit: false, + outDir: '$$ts-node$$' +}; +/** + * Split a string array of values. + */ +function split(value) { + return typeof value === 'string' ? value.split(/ *, */g) : undefined; +} +exports.split = split; +/** + * Parse a string as JSON. + */ +function parse(value) { + return typeof value === 'string' ? JSON.parse(value) : undefined; +} +exports.parse = parse; +/** + * Replace backslashes with forward slashes. + */ +function normalizeSlashes(value) { + return value.replace(/\\/g, '/'); +} +exports.normalizeSlashes = normalizeSlashes; +/** + * TypeScript diagnostics error. + */ +var TSError = /** @class */ (function (_super) { + __extends(TSError, _super); + function TSError(diagnosticText, diagnosticCodes) { + var _this = _super.call(this, "\u2A2F Unable to compile TypeScript:\n" + diagnosticText) || this; + _this.diagnosticText = diagnosticText; + _this.diagnosticCodes = diagnosticCodes; + _this.name = 'TSError'; + return _this; + } + /** + * @internal + */ + TSError.prototype[exports.INSPECT_CUSTOM] = function () { + return this.diagnosticText; + }; + return TSError; +}(make_error_1.BaseError)); +exports.TSError = TSError; +/** + * Return a default temp directory based on home directory of user. + */ +function getTmpDir() { + var hash = crypto.createHash('sha256').update(os_1.homedir(), 'utf8').digest('hex'); + return path_1.join(os_1.tmpdir(), "ts-node-" + hash); +} +/** + * Register TypeScript compiler. + */ +function register(opts) { + if (opts === void 0) { opts = {}; } + var options = Object.assign({}, exports.DEFAULTS, opts); + var cacheDirectory = options.cacheDirectory || getTmpDir(); + var originalJsHandler = require.extensions['.js']; + var ignoreDiagnostics = arrify(options.ignoreDiagnostics).concat([ + 6059, + 18002, + 18003 // "No inputs were found in config file." + ]).map(Number); + var memoryCache = { + contents: Object.create(null), + versions: Object.create(null), + outputs: Object.create(null) + }; + var ignore = options.skipIgnore ? [] : arrify(options.ignore || '/node_modules/').map(function (str) { return new RegExp(str); }); + // Install source map support and read from memory cache. + sourceMapSupport.install({ + environment: 'node', + retrieveFile: function (path) { + return memoryCache.outputs[path]; + } + }); + // Require the TypeScript compiler and configuration. + var cwd = process.cwd(); + var compilerOptions = options.compilerOptions, project = options.project, skipProject = options.skipProject; + var compiler = options.compiler || 'typescript'; + var typeCheck = options.typeCheck === true || options.transpileOnly !== true; + var ts = require(compiler); + var transformers = options.transformers || undefined; + var readFile = options.readFile || ts.sys.readFile; + var fileExists = options.fileExists || ts.sys.fileExists; + var config = readConfig(cwd, ts, fileExists, readFile, compilerOptions, project, skipProject); + var configDiagnosticList = filterDiagnostics(config.errors, ignoreDiagnostics); + var extensions = ['.ts', '.tsx']; + var fileNames = options.files ? config.fileNames : []; + var cachedir = path_1.join(path_1.resolve(cwd, cacheDirectory), getCompilerDigest({ + version: ts.version, + options: config.options, + fileNames: fileNames, + typeCheck: typeCheck, + ignoreDiagnostics: ignoreDiagnostics, + compiler: compiler + })); + var diagnosticHost = { + getNewLine: function () { return os_1.EOL; }, + getCurrentDirectory: function () { return cwd; }, + getCanonicalFileName: function (path) { return path; } + }; + var formatDiagnostics = options.pretty + ? ts.formatDiagnosticsWithColorAndContext + : ts.formatDiagnostics; + function createTSError(diagnostics) { + var diagnosticText = formatDiagnostics(diagnostics, diagnosticHost); + var diagnosticCodes = diagnostics.map(function (x) { return x.code; }); + return new TSError(diagnosticText, diagnosticCodes); + } + // Render the configuration errors and exit the script. + if (configDiagnosticList.length) + throw createTSError(configDiagnosticList); + // Enable `allowJs` when flag is set. + if (config.options.allowJs) { + extensions.push('.js'); + extensions.push('.jsx'); + } + // Initialize files from TypeScript into project. + for (var _i = 0, fileNames_1 = fileNames; _i < fileNames_1.length; _i++) { + var path = fileNames_1[_i]; + memoryCache.versions[path] = 1; + } + /** + * Get the extension for a transpiled file. + */ + var getExtension = config.options.jsx === ts.JsxEmit.Preserve ? + (function (path) { return /\.[tj]sx$/.test(path) ? '.jsx' : '.js'; }) : + (function (_) { return '.js'; }); + /** + * Create the basic required function using transpile mode. + */ + var getOutput = function (code, fileName, lineOffset) { + if (lineOffset === void 0) { lineOffset = 0; } + var result = ts.transpileModule(code, { + fileName: fileName, + transformers: transformers, + compilerOptions: config.options, + reportDiagnostics: true + }); + var diagnosticList = result.diagnostics ? + filterDiagnostics(result.diagnostics, ignoreDiagnostics) : + []; + if (diagnosticList.length) + throw createTSError(diagnosticList); + return [result.outputText, result.sourceMapText]; + }; + var getTypeInfo = function (_code, _fileName, _position) { + throw new TypeError("Type information is unavailable without \"--type-check\""); + }; + // Use full language services when the fast option is disabled. + if (typeCheck) { + // Set the file contents into cache. + var updateMemoryCache_1 = function (code, fileName) { + if (memoryCache.contents[fileName] !== code) { + memoryCache.contents[fileName] = code; + memoryCache.versions[fileName] = (memoryCache.versions[fileName] || 0) + 1; + } + }; + // Create the compiler host for type checking. + var serviceHost = { + getScriptFileNames: function () { return Object.keys(memoryCache.versions); }, + getScriptVersion: function (fileName) { + var version = memoryCache.versions[fileName]; + // We need to return `undefined` and not a string here because TypeScript will use + // `getScriptVersion` and compare against their own version - which can be `undefined`. + // If we don't return `undefined` it results in `undefined === "undefined"` and run + // `createProgram` again (which is very slow). Using a `string` assertion here to avoid + // TypeScript errors from the function signature (expects `(x: string) => string`). + return version === undefined ? undefined : String(version); + }, + getScriptSnapshot: function (fileName) { + // Read contents into TypeScript memory cache. + if (!Object.prototype.hasOwnProperty.call(memoryCache.contents, fileName)) { + memoryCache.contents[fileName] = readFile(fileName); + } + var contents = memoryCache.contents[fileName]; + if (contents === undefined) + return; + return ts.ScriptSnapshot.fromString(contents); + }, + fileExists: debugFn('fileExists', fileExists), + readFile: debugFn('readFile', readFile), + readDirectory: debugFn('readDirectory', ts.sys.readDirectory), + getDirectories: debugFn('getDirectories', ts.sys.getDirectories), + directoryExists: debugFn('directoryExists', ts.sys.directoryExists), + getNewLine: function () { return os_1.EOL; }, + getCurrentDirectory: function () { return cwd; }, + getCompilationSettings: function () { return config.options; }, + getDefaultLibFileName: function () { return ts.getDefaultLibFilePath(config.options); }, + getCustomTransformers: function () { return transformers; } + }; + var service_1 = ts.createLanguageService(serviceHost); + getOutput = function (code, fileName, lineOffset) { + if (lineOffset === void 0) { lineOffset = 0; } + // Must set memory cache before attempting to read file. + updateMemoryCache_1(code, fileName); + var output = service_1.getEmitOutput(fileName); + // Get the relevant diagnostics - this is 3x faster than `getPreEmitDiagnostics`. + var diagnostics = service_1.getCompilerOptionsDiagnostics() + .concat(service_1.getSyntacticDiagnostics(fileName)) + .concat(service_1.getSemanticDiagnostics(fileName)); + var diagnosticList = filterDiagnostics(diagnostics, ignoreDiagnostics); + if (diagnosticList.length) + throw createTSError(diagnosticList); + if (output.emitSkipped) { + throw new TypeError(path_1.relative(cwd, fileName) + ": Emit skipped"); + } + // Throw an error when requiring `.d.ts` files. + if (output.outputFiles.length === 0) { + throw new TypeError('Unable to require `.d.ts` file.\n' + + 'This is usually the result of a faulty configuration or import. ' + + 'Make sure there is a `.js`, `.json` or another executable extension and ' + + 'loader (attached before `ts-node`) available alongside ' + + ("`" + path_1.basename(fileName) + "`.")); + } + return [output.outputFiles[1].text, output.outputFiles[0].text]; + }; + getTypeInfo = function (code, fileName, position) { + updateMemoryCache_1(code, fileName); + var info = service_1.getQuickInfoAtPosition(fileName, position); + var name = ts.displayPartsToString(info ? info.displayParts : []); + var comment = ts.displayPartsToString(info ? info.documentation : []); + return { name: name, comment: comment }; + }; + } + var compile = readThrough(cachedir, options.cache === true, memoryCache, getOutput, getExtension); + var register = { cwd: cwd, compile: compile, getTypeInfo: getTypeInfo, extensions: extensions, cachedir: cachedir, ts: ts }; + // Register the extensions. + extensions.forEach(function (extension) { + registerExtension(extension, ignore, register, originalJsHandler); + }); + return register; +} +exports.register = register; +/** + * Check if the filename should be ignored. + */ +function shouldIgnore(filename, ignore) { + var relname = normalizeSlashes(filename); + return ignore.some(function (x) { return x.test(relname); }); +} +/** + * Register the extension for node. + */ +function registerExtension(ext, ignore, register, originalHandler) { + var old = require.extensions[ext] || originalHandler; + require.extensions[ext] = function (m, filename) { + if (shouldIgnore(filename, ignore)) { + return old(m, filename); + } + var _compile = m._compile; + m._compile = function (code, fileName) { + debug('module._compile', fileName); + return _compile.call(this, register.compile(code, fileName), fileName); + }; + return old(m, filename); + }; +} +/** + * Do post-processing on config options to support `ts-node`. + */ +function fixConfig(ts, config) { + // Delete options that *should not* be passed through. + delete config.options.out; + delete config.options.outFile; + delete config.options.composite; + delete config.options.declarationDir; + delete config.options.declarationMap; + delete config.options.emitDeclarationOnly; + // Target ES5 output by default (instead of ES3). + if (config.options.target === undefined) { + config.options.target = ts.ScriptTarget.ES5; + } + // Target CommonJS modules by default (instead of magically switching to ES6 when the target is ES6). + if (config.options.module === undefined) { + config.options.module = ts.ModuleKind.CommonJS; + } + return config; +} +/** + * Load TypeScript configuration. + */ +function readConfig(cwd, ts, fileExists, readFile, compilerOptions, project, noProject) { + var config = { compilerOptions: {} }; + var basePath = normalizeSlashes(cwd); + var configFileName = undefined; + // Read project configuration when available. + if (!noProject) { + configFileName = project + ? normalizeSlashes(path_1.resolve(cwd, project)) + : ts.findConfigFile(normalizeSlashes(cwd), fileExists); + if (configFileName) { + var result = ts.readConfigFile(configFileName, readFile); + // Return diagnostics. + if (result.error) { + return { errors: [result.error], fileNames: [], options: {} }; + } + config = result.config; + basePath = normalizeSlashes(path_1.dirname(configFileName)); + } + } + // Override default configuration options `ts-node` requires. + config.compilerOptions = Object.assign({}, config.compilerOptions, compilerOptions, DEFAULT_COMPILER_OPTIONS); + return fixConfig(ts, ts.parseJsonConfigFileContent(config, ts.sys, basePath, undefined, configFileName)); +} +/** + * Wrap the function with caching. + */ +function readThrough(cachedir, shouldCache, memoryCache, compile, getExtension) { + if (shouldCache === false) { + return function (code, fileName, lineOffset) { + debug('readThrough', fileName); + var _a = compile(code, fileName, lineOffset), value = _a[0], sourceMap = _a[1]; + var output = updateOutput(value, fileName, sourceMap, getExtension); + memoryCache.outputs[fileName] = output; + return output; + }; + } + // Make sure the cache directory exists before continuing. + mkdirp.sync(cachedir); + return function (code, fileName, lineOffset) { + debug('readThrough', fileName); + var cachePath = path_1.join(cachedir, getCacheName(code, fileName)); + var extension = getExtension(fileName); + var outputPath = "" + cachePath + extension; + try { + var output_1 = fs_1.readFileSync(outputPath, 'utf8'); + if (isValidCacheContent(output_1)) { + memoryCache.outputs[fileName] = output_1; + return output_1; + } + } + catch (err) { /* Ignore. */ } + var _a = compile(code, fileName, lineOffset), value = _a[0], sourceMap = _a[1]; + var output = updateOutput(value, fileName, sourceMap, getExtension); + memoryCache.outputs[fileName] = output; + fs_1.writeFileSync(outputPath, output); + return output; + }; +} +/** + * Update the output remapping the source map. + */ +function updateOutput(outputText, fileName, sourceMap, getExtension) { + var base64Map = bufferFrom(updateSourceMap(sourceMap, fileName), 'utf8').toString('base64'); + var sourceMapContent = "data:application/json;charset=utf-8;base64," + base64Map; + var sourceMapLength = (path_1.basename(fileName) + ".map").length + (getExtension(fileName).length - path_1.extname(fileName).length); + return outputText.slice(0, -sourceMapLength) + sourceMapContent; +} +/** + * Update the source map contents for improved output. + */ +function updateSourceMap(sourceMapText, fileName) { + var sourceMap = JSON.parse(sourceMapText); + sourceMap.file = fileName; + sourceMap.sources = [fileName]; + delete sourceMap.sourceRoot; + return JSON.stringify(sourceMap); +} +/** + * Get the file name for the cache entry. + */ +function getCacheName(sourceCode, fileName) { + return crypto.createHash('sha256') + .update(path_1.extname(fileName), 'utf8') + .update('\x00', 'utf8') + .update(sourceCode, 'utf8') + .digest('hex'); +} +/** + * Ensure the given cached content is valid by sniffing for a base64 encoded '}' + * at the end of the content, which should exist if there is a valid sourceMap present. + */ +function isValidCacheContent(contents) { + return /(?:9|0=|Q==)$/.test(contents.slice(-3)); +} +/** + * Create a hash of the current configuration. + */ +function getCompilerDigest(obj) { + return crypto.createHash('sha256').update(JSON.stringify(obj), 'utf8').digest('hex'); +} +/** + * Filter diagnostics. + */ +function filterDiagnostics(diagnostics, ignore) { + return diagnostics.filter(function (x) { return ignore.indexOf(x.code) === -1; }); +} +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/ts-node/dist/index.js.map b/node_modules/ts-node/dist/index.js.map new file mode 100644 index 0000000..623382d --- /dev/null +++ b/node_modules/ts-node/dist/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,6BAA0E;AAC1E,yBAAgD;AAChD,yBAAyC;AACzC,qDAAuD;AACvD,+BAAiC;AACjC,+BAAiC;AACjC,uBAAyB;AACzB,+BAAiC;AACjC,wCAA0C;AAC1C,yCAAsC;AACtC,2BAA4B;AAG5B;;GAEG;AACU,QAAA,cAAc,GAAG,IAAI,CAAC,OAAO,CAAC,MAAM,IAAI,SAAS,CAAA;AAE9D;;GAEG;AACH,IAAM,WAAW,GAAG,EAAE,CAAC,OAAO,CAAC,GAAG,CAAC,aAAa,CAAC,CAAA;AACjD,IAAM,KAAK,GAAG,WAAW,CAAC,CAAC,CAAC,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,OAAO,EAAE,SAAS,CAAC,CAAC,CAAC,CAAC,cAAM,OAAA,SAAS,EAAT,CAAS,CAAA;AAClF,IAAM,OAAO,GAAG,WAAW,CAAC,CAAC;IAC3B,UAAQ,GAAW,EAAE,EAAiB;QACpC,OAAO,UAAC,CAAI;YACV,KAAK,CAAC,GAAG,EAAE,CAAC,CAAC,CAAA;YACb,OAAO,EAAE,CAAC,CAAC,CAAC,CAAA;QACd,CAAC,CAAA;IACH,CAAC,CAAC,CAAC;IACH,UAAQ,CAAS,EAAE,EAAiB,IAAK,OAAA,EAAE,EAAF,CAAE,CAAA;AAwB7C;;GAEG;AACU,QAAA,OAAO,GAAG,OAAO,CAAC,iBAAiB,CAAC,CAAC,OAAO,CAAA;AAyCzD;;GAEG;AACU,QAAA,QAAQ,GAAY;IAC/B,KAAK,EAAE,EAAE,CAAC,OAAO,CAAC,GAAG,CAAC,eAAe,CAAC,CAAC;IACvC,KAAK,EAAE,EAAE,CAAC,OAAO,CAAC,GAAG,CAAC,eAAe,CAAC,EAAE,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC;IAC1D,MAAM,EAAE,EAAE,CAAC,OAAO,CAAC,GAAG,CAAC,gBAAgB,CAAC,CAAC;IACzC,cAAc,EAAE,OAAO,CAAC,GAAG,CAAC,yBAAyB,CAAC;IACtD,QAAQ,EAAE,OAAO,CAAC,GAAG,CAAC,kBAAkB,CAAC;IACzC,eAAe,EAAE,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC,0BAA0B,CAAC,CAAC;IAC/D,MAAM,EAAE,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC,gBAAgB,CAAC,CAAC;IAC5C,OAAO,EAAE,OAAO,CAAC,GAAG,CAAC,iBAAiB,CAAC;IACvC,UAAU,EAAE,EAAE,CAAC,OAAO,CAAC,GAAG,CAAC,qBAAqB,CAAC,CAAC;IAClD,WAAW,EAAE,EAAE,CAAC,OAAO,CAAC,GAAG,CAAC,sBAAsB,CAAC,CAAC;IACpD,iBAAiB,EAAE,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC,4BAA4B,CAAC,CAAC;IACnE,SAAS,EAAE,EAAE,CAAC,OAAO,CAAC,GAAG,CAAC,oBAAoB,CAAC,CAAC;IAChD,aAAa,EAAE,EAAE,CAAC,OAAO,CAAC,GAAG,CAAC,wBAAwB,CAAC,CAAC;CACzD,CAAA;AAED;;GAEG;AACH,IAAM,wBAAwB,GAAG;IAC/B,SAAS,EAAE,IAAI;IACf,eAAe,EAAE,KAAK;IACtB,aAAa,EAAE,IAAI;IACnB,WAAW,EAAE,KAAK;IAClB,MAAM,EAAE,KAAK;IACb,MAAM,EAAE,aAAa;CACtB,CAAA;AAED;;GAEG;AACH,eAAuB,KAAyB;IAC9C,OAAO,OAAO,KAAK,KAAK,QAAQ,CAAC,CAAC,CAAC,KAAK,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,SAAS,CAAA;AACtE,CAAC;AAFD,sBAEC;AAED;;GAEG;AACH,eAAuB,KAAyB;IAC9C,OAAO,OAAO,KAAK,KAAK,QAAQ,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,SAAS,CAAA;AAClE,CAAC;AAFD,sBAEC;AAED;;GAEG;AACH,0BAAkC,KAAa;IAC7C,OAAO,KAAK,CAAC,OAAO,CAAC,KAAK,EAAE,GAAG,CAAC,CAAA;AAClC,CAAC;AAFD,4CAEC;AAED;;GAEG;AACH;IAA6B,2BAAS;IAGpC,iBAAoB,cAAsB,EAAS,eAAyB;QAA5E,YACE,kBAAM,2CAAoC,cAAgB,CAAC,SAC5D;QAFmB,oBAAc,GAAd,cAAc,CAAQ;QAAS,qBAAe,GAAf,eAAe,CAAU;QAF5E,UAAI,GAAG,SAAS,CAAA;;IAIhB,CAAC;IAED;;OAEG;IACH,kBAAC,sBAAc,CAAC,GAAhB;QACE,OAAO,IAAI,CAAC,cAAc,CAAA;IAC5B,CAAC;IACH,cAAC;AAAD,CAAC,AAbD,CAA6B,sBAAS,GAarC;AAbY,0BAAO;AA2BpB;;GAEG;AACH;IACE,IAAM,IAAI,GAAG,MAAM,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAC,MAAM,CAAC,YAAO,EAAE,EAAE,MAAM,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAA;IAEhF,OAAO,WAAI,CAAC,WAAM,EAAE,EAAE,aAAW,IAAM,CAAC,CAAA;AAC1C,CAAC;AAED;;GAEG;AACH,kBAA0B,IAAkB;IAAlB,qBAAA,EAAA,SAAkB;IAC1C,IAAM,OAAO,GAAG,MAAM,CAAC,MAAM,CAAC,EAAE,EAAE,gBAAQ,EAAE,IAAI,CAAC,CAAA;IACjD,IAAM,cAAc,GAAG,OAAO,CAAC,cAAc,IAAI,SAAS,EAAE,CAAA;IAC5D,IAAM,iBAAiB,GAAG,OAAO,CAAC,UAAU,CAAC,KAAK,CAAC,CAAA;IAEnD,IAAM,iBAAiB,GAAG,MAAM,CAAC,OAAO,CAAC,iBAAiB,CAAC,CAAC,MAAM,CAAC;QACjE,IAAI;QACJ,KAAK;QACL,KAAK,CAAC,yCAAyC;KAChD,CAAC,CAAC,GAAG,CAAC,MAAM,CAAC,CAAA;IAEd,IAAM,WAAW,GAAgB;QAC/B,QAAQ,EAAE,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC;QAC7B,QAAQ,EAAE,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC;QAC7B,OAAO,EAAE,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC;KAC7B,CAAA;IAED,IAAM,MAAM,GAAG,OAAO,CAAC,UAAU,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,MAAM,CAC7C,OAAO,CAAC,MAAM,IAAI,gBAAgB,CACnC,CAAC,GAAG,CAAC,UAAA,GAAG,IAAI,OAAA,IAAI,MAAM,CAAC,GAAG,CAAC,EAAf,CAAe,CAAC,CAAA;IAE7B,yDAAyD;IACzD,gBAAgB,CAAC,OAAO,CAAC;QACvB,WAAW,EAAE,MAAM;QACnB,YAAY,YAAE,IAAY;YACxB,OAAO,WAAW,CAAC,OAAO,CAAC,IAAI,CAAC,CAAA;QAClC,CAAC;KACF,CAAC,CAAA;IAEF,qDAAqD;IACrD,IAAM,GAAG,GAAG,OAAO,CAAC,GAAG,EAAE,CAAA;IACjB,IAAA,yCAAe,EAAE,yBAAO,EAAE,iCAAW,CAAY;IACzD,IAAM,QAAQ,GAAG,OAAO,CAAC,QAAQ,IAAI,YAAY,CAAA;IACjD,IAAM,SAAS,GAAG,OAAO,CAAC,SAAS,KAAK,IAAI,IAAI,OAAO,CAAC,aAAa,KAAK,IAAI,CAAA;IAC9E,IAAM,EAAE,GAAe,OAAO,CAAC,QAAQ,CAAC,CAAA;IACxC,IAAM,YAAY,GAAG,OAAO,CAAC,YAAY,IAAI,SAAS,CAAA;IACtD,IAAM,QAAQ,GAAG,OAAO,CAAC,QAAQ,IAAI,EAAE,CAAC,GAAG,CAAC,QAAQ,CAAA;IACpD,IAAM,UAAU,GAAG,OAAO,CAAC,UAAU,IAAI,EAAE,CAAC,GAAG,CAAC,UAAU,CAAA;IAC1D,IAAM,MAAM,GAAG,UAAU,CAAC,GAAG,EAAE,EAAE,EAAE,UAAU,EAAE,QAAQ,EAAE,eAAe,EAAE,OAAO,EAAE,WAAW,CAAC,CAAA;IAC/F,IAAM,oBAAoB,GAAG,iBAAiB,CAAC,MAAM,CAAC,MAAM,EAAE,iBAAiB,CAAC,CAAA;IAChF,IAAM,UAAU,GAAG,CAAC,KAAK,EAAE,MAAM,CAAC,CAAA;IAClC,IAAM,SAAS,GAAG,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC,CAAC,EAAE,CAAA;IAEvD,IAAM,QAAQ,GAAG,WAAI,CACnB,cAAO,CAAC,GAAG,EAAE,cAAc,CAAC,EAC5B,iBAAiB,CAAC;QAChB,OAAO,EAAE,EAAE,CAAC,OAAO;QACnB,OAAO,EAAE,MAAM,CAAC,OAAO;QACvB,SAAS,WAAA;QACT,SAAS,WAAA;QACT,iBAAiB,mBAAA;QACjB,QAAQ,UAAA;KACT,CAAC,CACH,CAAA;IAED,IAAM,cAAc,GAA8B;QAChD,UAAU,EAAE,cAAM,OAAA,QAAG,EAAH,CAAG;QACrB,mBAAmB,EAAE,cAAM,OAAA,GAAG,EAAH,CAAG;QAC9B,oBAAoB,EAAE,UAAC,IAAI,IAAK,OAAA,IAAI,EAAJ,CAAI;KACrC,CAAA;IAED,IAAM,iBAAiB,GAAG,OAAO,CAAC,MAAM;QACtC,CAAC,CAAC,EAAE,CAAC,oCAAoC;QACzC,CAAC,CAAC,EAAE,CAAC,iBAAiB,CAAA;IAExB,uBAAwB,WAA0C;QAChE,IAAM,cAAc,GAAG,iBAAiB,CAAC,WAAW,EAAE,cAAc,CAAC,CAAA;QACrE,IAAM,eAAe,GAAG,WAAW,CAAC,GAAG,CAAC,UAAA,CAAC,IAAI,OAAA,CAAC,CAAC,IAAI,EAAN,CAAM,CAAC,CAAA;QACpD,OAAO,IAAI,OAAO,CAAC,cAAc,EAAE,eAAe,CAAC,CAAA;IACrD,CAAC;IAED,uDAAuD;IACvD,IAAI,oBAAoB,CAAC,MAAM;QAAE,MAAM,aAAa,CAAC,oBAAoB,CAAC,CAAA;IAE1E,qCAAqC;IACrC,IAAI,MAAM,CAAC,OAAO,CAAC,OAAO,EAAE;QAC1B,UAAU,CAAC,IAAI,CAAC,KAAK,CAAC,CAAA;QACtB,UAAU,CAAC,IAAI,CAAC,MAAM,CAAC,CAAA;KACxB;IAED,iDAAiD;IACjD,KAAmB,UAAS,EAAT,uBAAS,EAAT,uBAAS,EAAT,IAAS;QAAvB,IAAM,IAAI,kBAAA;QAAe,WAAW,CAAC,QAAQ,CAAC,IAAI,CAAC,GAAG,CAAC,CAAA;KAAA;IAE5D;;OAEG;IACH,IAAM,YAAY,GAAG,MAAM,CAAC,OAAO,CAAC,GAAG,KAAK,EAAE,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC;QAC/D,CAAC,UAAC,IAAY,IAAK,OAAA,WAAW,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,KAAK,EAAvC,CAAuC,CAAC,CAAC,CAAC;QAC7D,CAAC,UAAC,CAAS,IAAK,OAAA,KAAK,EAAL,CAAK,CAAC,CAAA;IAExB;;OAEG;IACH,IAAI,SAAS,GAAG,UAAU,IAAY,EAAE,QAAgB,EAAE,UAAc;QAAd,2BAAA,EAAA,cAAc;QACtE,IAAM,MAAM,GAAG,EAAE,CAAC,eAAe,CAAC,IAAI,EAAE;YACtC,QAAQ,UAAA;YACR,YAAY,cAAA;YACZ,eAAe,EAAE,MAAM,CAAC,OAAO;YAC/B,iBAAiB,EAAE,IAAI;SACxB,CAAC,CAAA;QAEF,IAAM,cAAc,GAAG,MAAM,CAAC,WAAW,CAAC,CAAC;YACzC,iBAAiB,CAAC,MAAM,CAAC,WAAW,EAAE,iBAAiB,CAAC,CAAC,CAAC;YAC1D,EAAE,CAAA;QAEJ,IAAI,cAAc,CAAC,MAAM;YAAE,MAAM,aAAa,CAAC,cAAc,CAAC,CAAA;QAE9D,OAAO,CAAC,MAAM,CAAC,UAAU,EAAE,MAAM,CAAC,aAAuB,CAAC,CAAA;IAC5D,CAAC,CAAA;IAED,IAAI,WAAW,GAAG,UAAU,KAAa,EAAE,SAAiB,EAAE,SAAiB;QAC7E,MAAM,IAAI,SAAS,CAAC,0DAAwD,CAAC,CAAA;IAC/E,CAAC,CAAA;IAED,+DAA+D;IAC/D,IAAI,SAAS,EAAE;QACb,oCAAoC;QACpC,IAAM,mBAAiB,GAAG,UAAU,IAAY,EAAE,QAAgB;YAChE,IAAI,WAAW,CAAC,QAAQ,CAAC,QAAQ,CAAC,KAAK,IAAI,EAAE;gBAC3C,WAAW,CAAC,QAAQ,CAAC,QAAQ,CAAC,GAAG,IAAI,CAAA;gBACrC,WAAW,CAAC,QAAQ,CAAC,QAAQ,CAAC,GAAG,CAAC,WAAW,CAAC,QAAQ,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,CAAA;aAC3E;QACH,CAAC,CAAA;QAED,8CAA8C;QAC9C,IAAM,WAAW,GAAG;YAClB,kBAAkB,EAAE,cAAM,OAAA,MAAM,CAAC,IAAI,CAAC,WAAW,CAAC,QAAQ,CAAC,EAAjC,CAAiC;YAC3D,gBAAgB,EAAE,UAAC,QAAgB;gBACjC,IAAM,OAAO,GAAG,WAAW,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAA;gBAE9C,kFAAkF;gBAClF,uFAAuF;gBACvF,mFAAmF;gBACnF,uFAAuF;gBACvF,mFAAmF;gBACnF,OAAO,OAAO,KAAK,SAAS,CAAC,CAAC,CAAC,SAA0B,CAAC,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,CAAA;YAC7E,CAAC;YACD,iBAAiB,YAAE,QAAgB;gBACjC,8CAA8C;gBAC9C,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,cAAc,CAAC,IAAI,CAAC,WAAW,CAAC,QAAQ,EAAE,QAAQ,CAAC,EAAE;oBACzE,WAAW,CAAC,QAAQ,CAAC,QAAQ,CAAC,GAAG,QAAQ,CAAC,QAAQ,CAAC,CAAA;iBACpD;gBAED,IAAM,QAAQ,GAAG,WAAW,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAA;gBAC/C,IAAI,QAAQ,KAAK,SAAS;oBAAE,OAAM;gBAClC,OAAO,EAAE,CAAC,cAAc,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAA;YAC/C,CAAC;YACD,UAAU,EAAE,OAAO,CAAC,YAAY,EAAE,UAAU,CAAC;YAC7C,QAAQ,EAAE,OAAO,CAAC,UAAU,EAAE,QAAQ,CAAC;YACvC,aAAa,EAAE,OAAO,CAAC,eAAe,EAAE,EAAE,CAAC,GAAG,CAAC,aAAa,CAAC;YAC7D,cAAc,EAAE,OAAO,CAAC,gBAAgB,EAAE,EAAE,CAAC,GAAG,CAAC,cAAc,CAAC;YAChE,eAAe,EAAE,OAAO,CAAC,iBAAiB,EAAE,EAAE,CAAC,GAAG,CAAC,eAAe,CAAC;YACnE,UAAU,EAAE,cAAM,OAAA,QAAG,EAAH,CAAG;YACrB,mBAAmB,EAAE,cAAM,OAAA,GAAG,EAAH,CAAG;YAC9B,sBAAsB,EAAE,cAAM,OAAA,MAAM,CAAC,OAAO,EAAd,CAAc;YAC5C,qBAAqB,EAAE,cAAM,OAAA,EAAE,CAAC,qBAAqB,CAAC,MAAM,CAAC,OAAO,CAAC,EAAxC,CAAwC;YACrE,qBAAqB,EAAE,cAAM,OAAA,YAAY,EAAZ,CAAY;SAC1C,CAAA;QAED,IAAM,SAAO,GAAG,EAAE,CAAC,qBAAqB,CAAC,WAAW,CAAC,CAAA;QAErD,SAAS,GAAG,UAAU,IAAY,EAAE,QAAgB,EAAE,UAAsB;YAAtB,2BAAA,EAAA,cAAsB;YAC1E,wDAAwD;YACxD,mBAAiB,CAAC,IAAI,EAAE,QAAQ,CAAC,CAAA;YAEjC,IAAM,MAAM,GAAG,SAAO,CAAC,aAAa,CAAC,QAAQ,CAAC,CAAA;YAE9C,iFAAiF;YACjF,IAAM,WAAW,GAAG,SAAO,CAAC,6BAA6B,EAAE;iBACxD,MAAM,CAAC,SAAO,CAAC,uBAAuB,CAAC,QAAQ,CAAC,CAAC;iBACjD,MAAM,CAAC,SAAO,CAAC,sBAAsB,CAAC,QAAQ,CAAC,CAAC,CAAA;YAEnD,IAAM,cAAc,GAAG,iBAAiB,CAAC,WAAW,EAAE,iBAAiB,CAAC,CAAA;YAExE,IAAI,cAAc,CAAC,MAAM;gBAAE,MAAM,aAAa,CAAC,cAAc,CAAC,CAAA;YAE9D,IAAI,MAAM,CAAC,WAAW,EAAE;gBACtB,MAAM,IAAI,SAAS,CAAI,eAAQ,CAAC,GAAG,EAAE,QAAQ,CAAC,mBAAgB,CAAC,CAAA;aAChE;YAED,+CAA+C;YAC/C,IAAI,MAAM,CAAC,WAAW,CAAC,MAAM,KAAK,CAAC,EAAE;gBACnC,MAAM,IAAI,SAAS,CACjB,mCAAmC;oBACnC,kEAAkE;oBAClE,0EAA0E;oBAC1E,yDAAyD;qBACzD,MAAK,eAAQ,CAAC,QAAQ,CAAC,OAAK,CAAA,CAC7B,CAAA;aACF;YAED,OAAO,CAAC,MAAM,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,IAAI,EAAE,MAAM,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAA;QACjE,CAAC,CAAA;QAED,WAAW,GAAG,UAAU,IAAY,EAAE,QAAgB,EAAE,QAAgB;YACtE,mBAAiB,CAAC,IAAI,EAAE,QAAQ,CAAC,CAAA;YAEjC,IAAM,IAAI,GAAG,SAAO,CAAC,sBAAsB,CAAC,QAAQ,EAAE,QAAQ,CAAC,CAAA;YAC/D,IAAM,IAAI,GAAG,EAAE,CAAC,oBAAoB,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC,CAAC,EAAE,CAAC,CAAA;YACnE,IAAM,OAAO,GAAG,EAAE,CAAC,oBAAoB,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,aAAa,CAAC,CAAC,CAAC,EAAE,CAAC,CAAA;YAEvE,OAAO,EAAE,IAAI,MAAA,EAAE,OAAO,SAAA,EAAE,CAAA;QAC1B,CAAC,CAAA;KACF;IAED,IAAM,OAAO,GAAG,WAAW,CAAC,QAAQ,EAAE,OAAO,CAAC,KAAK,KAAK,IAAI,EAAE,WAAW,EAAE,SAAS,EAAE,YAAY,CAAC,CAAA;IACnG,IAAM,QAAQ,GAAa,EAAE,GAAG,KAAA,EAAE,OAAO,SAAA,EAAE,WAAW,aAAA,EAAE,UAAU,YAAA,EAAE,QAAQ,UAAA,EAAE,EAAE,IAAA,EAAE,CAAA;IAElF,2BAA2B;IAC3B,UAAU,CAAC,OAAO,CAAC,UAAA,SAAS;QAC1B,iBAAiB,CAAC,SAAS,EAAE,MAAM,EAAE,QAAQ,EAAE,iBAAiB,CAAC,CAAA;IACnE,CAAC,CAAC,CAAA;IAEF,OAAO,QAAQ,CAAA;AACjB,CAAC;AAtND,4BAsNC;AAED;;GAEG;AACH,sBAAuB,QAAgB,EAAE,MAAgB;IACvD,IAAM,OAAO,GAAG,gBAAgB,CAAC,QAAQ,CAAC,CAAA;IAE1C,OAAO,MAAM,CAAC,IAAI,CAAC,UAAA,CAAC,IAAI,OAAA,CAAC,CAAC,IAAI,CAAC,OAAO,CAAC,EAAf,CAAe,CAAC,CAAA;AAC1C,CAAC;AAED;;GAEG;AACH,2BACE,GAAW,EACX,MAAgB,EAChB,QAAkB,EAClB,eAAyD;IAEzD,IAAM,GAAG,GAAG,OAAO,CAAC,UAAU,CAAC,GAAG,CAAC,IAAI,eAAe,CAAA;IAEtD,OAAO,CAAC,UAAU,CAAC,GAAG,CAAC,GAAG,UAAU,CAAM,EAAE,QAAQ;QAClD,IAAI,YAAY,CAAC,QAAQ,EAAE,MAAM,CAAC,EAAE;YAClC,OAAO,GAAG,CAAC,CAAC,EAAE,QAAQ,CAAC,CAAA;SACxB;QAED,IAAM,QAAQ,GAAG,CAAC,CAAC,QAAQ,CAAA;QAE3B,CAAC,CAAC,QAAQ,GAAG,UAAU,IAAY,EAAE,QAAgB;YACnD,KAAK,CAAC,iBAAiB,EAAE,QAAQ,CAAC,CAAA;YAElC,OAAO,QAAQ,CAAC,IAAI,CAAC,IAAI,EAAE,QAAQ,CAAC,OAAO,CAAC,IAAI,EAAE,QAAQ,CAAC,EAAE,QAAQ,CAAC,CAAA;QACxE,CAAC,CAAA;QAED,OAAO,GAAG,CAAC,CAAC,EAAE,QAAQ,CAAC,CAAA;IACzB,CAAC,CAAA;AACH,CAAC;AAED;;GAEG;AACH,mBAAoB,EAAY,EAAE,MAA6B;IAC7D,sDAAsD;IACtD,OAAO,MAAM,CAAC,OAAO,CAAC,GAAG,CAAA;IACzB,OAAO,MAAM,CAAC,OAAO,CAAC,OAAO,CAAA;IAC7B,OAAO,MAAM,CAAC,OAAO,CAAC,SAAS,CAAA;IAC/B,OAAO,MAAM,CAAC,OAAO,CAAC,cAAc,CAAA;IACpC,OAAO,MAAM,CAAC,OAAO,CAAC,cAAc,CAAA;IACpC,OAAO,MAAM,CAAC,OAAO,CAAC,mBAAmB,CAAA;IAEzC,iDAAiD;IACjD,IAAI,MAAM,CAAC,OAAO,CAAC,MAAM,KAAK,SAAS,EAAE;QACvC,MAAM,CAAC,OAAO,CAAC,MAAM,GAAG,EAAE,CAAC,YAAY,CAAC,GAAG,CAAA;KAC5C;IAED,qGAAqG;IACrG,IAAI,MAAM,CAAC,OAAO,CAAC,MAAM,KAAK,SAAS,EAAE;QACvC,MAAM,CAAC,OAAO,CAAC,MAAM,GAAG,EAAE,CAAC,UAAU,CAAC,QAAQ,CAAA;KAC/C;IAED,OAAO,MAAM,CAAA;AACf,CAAC;AAED;;GAEG;AACH,oBACE,GAAW,EACX,EAAY,EACZ,UAAqC,EACrC,QAA8C,EAC9C,eAAwB,EACxB,OAAuB,EACvB,SAA0B;IAE1B,IAAI,MAAM,GAAG,EAAE,eAAe,EAAE,EAAE,EAAE,CAAA;IACpC,IAAI,QAAQ,GAAG,gBAAgB,CAAC,GAAG,CAAC,CAAA;IACpC,IAAI,cAAc,GAAuB,SAAS,CAAA;IAElD,6CAA6C;IAC7C,IAAI,CAAC,SAAS,EAAE;QACd,cAAc,GAAG,OAAO;YACtB,CAAC,CAAC,gBAAgB,CAAC,cAAO,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC;YACzC,CAAC,CAAC,EAAE,CAAC,cAAc,CAAC,gBAAgB,CAAC,GAAG,CAAC,EAAE,UAAU,CAAC,CAAA;QAExD,IAAI,cAAc,EAAE;YAClB,IAAM,MAAM,GAAG,EAAE,CAAC,cAAc,CAAC,cAAc,EAAE,QAAQ,CAAC,CAAA;YAE1D,sBAAsB;YACtB,IAAI,MAAM,CAAC,KAAK,EAAE;gBAChB,OAAO,EAAE,MAAM,EAAE,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE,SAAS,EAAE,EAAE,EAAE,OAAO,EAAE,EAAE,EAAE,CAAA;aAC9D;YAED,MAAM,GAAG,MAAM,CAAC,MAAM,CAAA;YACtB,QAAQ,GAAG,gBAAgB,CAAC,cAAO,CAAC,cAAc,CAAC,CAAC,CAAA;SACrD;KACF;IAED,6DAA6D;IAC7D,MAAM,CAAC,eAAe,GAAG,MAAM,CAAC,MAAM,CAAC,EAAE,EAAE,MAAM,CAAC,eAAe,EAAE,eAAe,EAAE,wBAAwB,CAAC,CAAA;IAE7G,OAAO,SAAS,CAAC,EAAE,EAAE,EAAE,CAAC,0BAA0B,CAAC,MAAM,EAAE,EAAE,CAAC,GAAG,EAAE,QAAQ,EAAE,SAAS,EAAE,cAAc,CAAC,CAAC,CAAA;AAC1G,CAAC;AAOD;;GAEG;AACH,qBACE,QAAgB,EAChB,WAAoB,EACpB,WAAwB,EACxB,OAA8E,EAC9E,YAA0C;IAE1C,IAAI,WAAW,KAAK,KAAK,EAAE;QACzB,OAAO,UAAU,IAAY,EAAE,QAAgB,EAAE,UAAmB;YAClE,KAAK,CAAC,aAAa,EAAE,QAAQ,CAAC,CAAA;YAExB,IAAA,wCAAwD,EAAvD,aAAK,EAAE,iBAAS,CAAuC;YAC9D,IAAM,MAAM,GAAG,YAAY,CAAC,KAAK,EAAE,QAAQ,EAAE,SAAS,EAAE,YAAY,CAAC,CAAA;YAErE,WAAW,CAAC,OAAO,CAAC,QAAQ,CAAC,GAAG,MAAM,CAAA;YAEtC,OAAO,MAAM,CAAA;QACf,CAAC,CAAA;KACF;IAED,0DAA0D;IAC1D,MAAM,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAA;IAErB,OAAO,UAAU,IAAY,EAAE,QAAgB,EAAE,UAAmB;QAClE,KAAK,CAAC,aAAa,EAAE,QAAQ,CAAC,CAAA;QAE9B,IAAM,SAAS,GAAG,WAAI,CAAC,QAAQ,EAAE,YAAY,CAAC,IAAI,EAAE,QAAQ,CAAC,CAAC,CAAA;QAC9D,IAAM,SAAS,GAAG,YAAY,CAAC,QAAQ,CAAC,CAAA;QACxC,IAAM,UAAU,GAAG,KAAG,SAAS,GAAG,SAAW,CAAA;QAE7C,IAAI;YACF,IAAM,QAAM,GAAG,iBAAY,CAAC,UAAU,EAAE,MAAM,CAAC,CAAA;YAC/C,IAAI,mBAAmB,CAAC,QAAM,CAAC,EAAE;gBAC/B,WAAW,CAAC,OAAO,CAAC,QAAQ,CAAC,GAAG,QAAM,CAAA;gBACtC,OAAO,QAAM,CAAA;aACd;SACF;QAAC,OAAO,GAAG,EAAE,EAAC,aAAa,EAAC;QAEvB,IAAA,wCAAwD,EAAvD,aAAK,EAAE,iBAAS,CAAuC;QAC9D,IAAM,MAAM,GAAG,YAAY,CAAC,KAAK,EAAE,QAAQ,EAAE,SAAS,EAAE,YAAY,CAAC,CAAA;QAErE,WAAW,CAAC,OAAO,CAAC,QAAQ,CAAC,GAAG,MAAM,CAAA;QACtC,kBAAa,CAAC,UAAU,EAAE,MAAM,CAAC,CAAA;QAEjC,OAAO,MAAM,CAAA;IACf,CAAC,CAAA;AACH,CAAC;AAED;;GAEG;AACH,sBAAuB,UAAkB,EAAE,QAAgB,EAAE,SAAiB,EAAE,YAA0C;IACxH,IAAM,SAAS,GAAG,UAAU,CAAC,eAAe,CAAC,SAAS,EAAE,QAAQ,CAAC,EAAE,MAAM,CAAC,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAA;IAC7F,IAAM,gBAAgB,GAAG,gDAA8C,SAAW,CAAA;IAClF,IAAM,eAAe,GAAG,CAAG,eAAQ,CAAC,QAAQ,CAAC,SAAM,CAAA,CAAC,MAAM,GAAG,CAAC,YAAY,CAAC,QAAQ,CAAC,CAAC,MAAM,GAAG,cAAO,CAAC,QAAQ,CAAC,CAAC,MAAM,CAAC,CAAA;IAEvH,OAAO,UAAU,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,eAAe,CAAC,GAAG,gBAAgB,CAAA;AACjE,CAAC;AAED;;GAEG;AACH,yBAA0B,aAAqB,EAAE,QAAgB;IAC/D,IAAM,SAAS,GAAG,IAAI,CAAC,KAAK,CAAC,aAAa,CAAC,CAAA;IAC3C,SAAS,CAAC,IAAI,GAAG,QAAQ,CAAA;IACzB,SAAS,CAAC,OAAO,GAAG,CAAC,QAAQ,CAAC,CAAA;IAC9B,OAAO,SAAS,CAAC,UAAU,CAAA;IAC3B,OAAO,IAAI,CAAC,SAAS,CAAC,SAAS,CAAC,CAAA;AAClC,CAAC;AAED;;GAEG;AACH,sBAAuB,UAAkB,EAAE,QAAgB;IACzD,OAAO,MAAM,CAAC,UAAU,CAAC,QAAQ,CAAC;SAC/B,MAAM,CAAC,cAAO,CAAC,QAAQ,CAAC,EAAE,MAAM,CAAC;SACjC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC;SACtB,MAAM,CAAC,UAAU,EAAE,MAAM,CAAC;SAC1B,MAAM,CAAC,KAAK,CAAC,CAAA;AAClB,CAAC;AAED;;;GAGG;AACH,6BAA8B,QAAgB;IAC5C,OAAO,eAAe,CAAC,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAA;AACjD,CAAC;AAED;;GAEG;AACH,2BAA4B,GAAW;IACrC,OAAO,MAAM,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,EAAE,MAAM,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAA;AACtF,CAAC;AAED;;GAEG;AACH,2BAA4B,WAA6B,EAAE,MAAgB;IACzE,OAAO,WAAW,CAAC,MAAM,CAAC,UAAA,CAAC,IAAI,OAAA,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,EAA7B,CAA6B,CAAC,CAAA;AAC/D,CAAC","sourcesContent":["import { relative, basename, extname, resolve, dirname, join } from 'path'\nimport { readFileSync, writeFileSync } from 'fs'\nimport { EOL, tmpdir, homedir } from 'os'\nimport sourceMapSupport = require('source-map-support')\nimport mkdirp = require('mkdirp')\nimport crypto = require('crypto')\nimport yn = require('yn')\nimport arrify = require('arrify')\nimport bufferFrom = require('buffer-from')\nimport { BaseError } from 'make-error'\nimport * as util from 'util'\nimport * as _ts from 'typescript'\n\n/**\n * @internal\n */\nexport const INSPECT_CUSTOM = util.inspect.custom || 'inspect'\n\n/**\n * Debugging `ts-node`.\n */\nconst shouldDebug = yn(process.env.TS_NODE_DEBUG)\nconst debug = shouldDebug ? console.log.bind(console, 'ts-node') : () => undefined\nconst debugFn = shouldDebug ?\n (key: string, fn: (arg: T) => U) => {\n return (x: T) => {\n debug(key, x)\n return fn(x)\n }\n } :\n (_: string, fn: (arg: T) => U) => fn\n\n/**\n * Common TypeScript interfaces between versions.\n */\nexport interface TSCommon {\n version: typeof _ts.version\n sys: typeof _ts.sys\n ScriptSnapshot: typeof _ts.ScriptSnapshot\n displayPartsToString: typeof _ts.displayPartsToString\n createLanguageService: typeof _ts.createLanguageService\n getDefaultLibFilePath: typeof _ts.getDefaultLibFilePath\n getPreEmitDiagnostics: typeof _ts.getPreEmitDiagnostics\n flattenDiagnosticMessageText: typeof _ts.flattenDiagnosticMessageText\n transpileModule: typeof _ts.transpileModule\n ModuleKind: typeof _ts.ModuleKind\n ScriptTarget: typeof _ts.ScriptTarget\n findConfigFile: typeof _ts.findConfigFile\n readConfigFile: typeof _ts.readConfigFile\n parseJsonConfigFileContent: typeof _ts.parseJsonConfigFileContent\n formatDiagnostics: typeof _ts.formatDiagnostics\n formatDiagnosticsWithColorAndContext: typeof _ts.formatDiagnosticsWithColorAndContext\n}\n\n/**\n * Export the current version.\n */\nexport const VERSION = require('../package.json').version\n\n/**\n * Registration options.\n */\nexport interface Options {\n pretty?: boolean | null\n typeCheck?: boolean | null\n transpileOnly?: boolean | null\n files?: boolean | null\n cache?: boolean | null\n cacheDirectory?: string\n compiler?: string\n ignore?: string | string[]\n project?: string\n skipIgnore?: boolean | null\n skipProject?: boolean | null\n compilerOptions?: object\n ignoreDiagnostics?: number | string | Array\n readFile?: (path: string) => string | undefined\n fileExists?: (path: string) => boolean\n transformers?: _ts.CustomTransformers\n}\n\n/**\n * Track the project information.\n */\ninterface MemoryCache {\n contents: { [path: string]: string | undefined }\n versions: { [path: string]: number | undefined }\n outputs: { [path: string]: string }\n}\n\n/**\n * Information retrieved from type info check.\n */\nexport interface TypeInfo {\n name: string\n comment: string\n}\n\n/**\n * Default register options.\n */\nexport const DEFAULTS: Options = {\n files: yn(process.env['TS_NODE_FILES']),\n cache: yn(process.env['TS_NODE_CACHE'], { default: true }),\n pretty: yn(process.env['TS_NODE_PRETTY']),\n cacheDirectory: process.env['TS_NODE_CACHE_DIRECTORY'],\n compiler: process.env['TS_NODE_COMPILER'],\n compilerOptions: parse(process.env['TS_NODE_COMPILER_OPTIONS']),\n ignore: split(process.env['TS_NODE_IGNORE']),\n project: process.env['TS_NODE_PROJECT'],\n skipIgnore: yn(process.env['TS_NODE_SKIP_IGNORE']),\n skipProject: yn(process.env['TS_NODE_SKIP_PROJECT']),\n ignoreDiagnostics: split(process.env['TS_NODE_IGNORE_DIAGNOSTICS']),\n typeCheck: yn(process.env['TS_NODE_TYPE_CHECK']),\n transpileOnly: yn(process.env['TS_NODE_TRANSPILE_ONLY'])\n}\n\n/**\n * Default TypeScript compiler options required by `ts-node`.\n */\nconst DEFAULT_COMPILER_OPTIONS = {\n sourceMap: true,\n inlineSourceMap: false,\n inlineSources: true,\n declaration: false,\n noEmit: false,\n outDir: '$$ts-node$$'\n}\n\n/**\n * Split a string array of values.\n */\nexport function split (value: string | undefined) {\n return typeof value === 'string' ? value.split(/ *, */g) : undefined\n}\n\n/**\n * Parse a string as JSON.\n */\nexport function parse (value: string | undefined): object | undefined {\n return typeof value === 'string' ? JSON.parse(value) : undefined\n}\n\n/**\n * Replace backslashes with forward slashes.\n */\nexport function normalizeSlashes (value: string): string {\n return value.replace(/\\\\/g, '/')\n}\n\n/**\n * TypeScript diagnostics error.\n */\nexport class TSError extends BaseError {\n name = 'TSError'\n\n constructor (public diagnosticText: string, public diagnosticCodes: number[]) {\n super(`⨯ Unable to compile TypeScript:\\n${diagnosticText}`)\n }\n\n /**\n * @internal\n */\n [INSPECT_CUSTOM] () {\n return this.diagnosticText\n }\n}\n\n/**\n * Return type for registering `ts-node`.\n */\nexport interface Register {\n cwd: string\n extensions: string[]\n cachedir: string\n ts: TSCommon\n compile (code: string, fileName: string, lineOffset?: number): string\n getTypeInfo (code: string, fileName: string, position: number): TypeInfo\n}\n\n/**\n * Return a default temp directory based on home directory of user.\n */\nfunction getTmpDir (): string {\n const hash = crypto.createHash('sha256').update(homedir(), 'utf8').digest('hex')\n\n return join(tmpdir(), `ts-node-${hash}`)\n}\n\n/**\n * Register TypeScript compiler.\n */\nexport function register (opts: Options = {}): Register {\n const options = Object.assign({}, DEFAULTS, opts)\n const cacheDirectory = options.cacheDirectory || getTmpDir()\n const originalJsHandler = require.extensions['.js']\n\n const ignoreDiagnostics = arrify(options.ignoreDiagnostics).concat([\n 6059, // \"'rootDir' is expected to contain all source files.\"\n 18002, // \"The 'files' list in config file is empty.\"\n 18003 // \"No inputs were found in config file.\"\n ]).map(Number)\n\n const memoryCache: MemoryCache = {\n contents: Object.create(null),\n versions: Object.create(null),\n outputs: Object.create(null)\n }\n\n const ignore = options.skipIgnore ? [] : arrify(\n options.ignore || '/node_modules/'\n ).map(str => new RegExp(str))\n\n // Install source map support and read from memory cache.\n sourceMapSupport.install({\n environment: 'node',\n retrieveFile (path: string) {\n return memoryCache.outputs[path]\n }\n })\n\n // Require the TypeScript compiler and configuration.\n const cwd = process.cwd()\n const { compilerOptions, project, skipProject } = options\n const compiler = options.compiler || 'typescript'\n const typeCheck = options.typeCheck === true || options.transpileOnly !== true\n const ts: typeof _ts = require(compiler)\n const transformers = options.transformers || undefined\n const readFile = options.readFile || ts.sys.readFile\n const fileExists = options.fileExists || ts.sys.fileExists\n const config = readConfig(cwd, ts, fileExists, readFile, compilerOptions, project, skipProject)\n const configDiagnosticList = filterDiagnostics(config.errors, ignoreDiagnostics)\n const extensions = ['.ts', '.tsx']\n const fileNames = options.files ? config.fileNames : []\n\n const cachedir = join(\n resolve(cwd, cacheDirectory),\n getCompilerDigest({\n version: ts.version,\n options: config.options,\n fileNames,\n typeCheck,\n ignoreDiagnostics,\n compiler\n })\n )\n\n const diagnosticHost: _ts.FormatDiagnosticsHost = {\n getNewLine: () => EOL,\n getCurrentDirectory: () => cwd,\n getCanonicalFileName: (path) => path\n }\n\n const formatDiagnostics = options.pretty\n ? ts.formatDiagnosticsWithColorAndContext\n : ts.formatDiagnostics\n\n function createTSError (diagnostics: ReadonlyArray<_ts.Diagnostic>) {\n const diagnosticText = formatDiagnostics(diagnostics, diagnosticHost)\n const diagnosticCodes = diagnostics.map(x => x.code)\n return new TSError(diagnosticText, diagnosticCodes)\n }\n\n // Render the configuration errors and exit the script.\n if (configDiagnosticList.length) throw createTSError(configDiagnosticList)\n\n // Enable `allowJs` when flag is set.\n if (config.options.allowJs) {\n extensions.push('.js')\n extensions.push('.jsx')\n }\n\n // Initialize files from TypeScript into project.\n for (const path of fileNames) memoryCache.versions[path] = 1\n\n /**\n * Get the extension for a transpiled file.\n */\n const getExtension = config.options.jsx === ts.JsxEmit.Preserve ?\n ((path: string) => /\\.[tj]sx$/.test(path) ? '.jsx' : '.js') :\n ((_: string) => '.js')\n\n /**\n * Create the basic required function using transpile mode.\n */\n let getOutput = function (code: string, fileName: string, lineOffset = 0): SourceOutput {\n const result = ts.transpileModule(code, {\n fileName,\n transformers,\n compilerOptions: config.options,\n reportDiagnostics: true\n })\n\n const diagnosticList = result.diagnostics ?\n filterDiagnostics(result.diagnostics, ignoreDiagnostics) :\n []\n\n if (diagnosticList.length) throw createTSError(diagnosticList)\n\n return [result.outputText, result.sourceMapText as string]\n }\n\n let getTypeInfo = function (_code: string, _fileName: string, _position: number): TypeInfo {\n throw new TypeError(`Type information is unavailable without \"--type-check\"`)\n }\n\n // Use full language services when the fast option is disabled.\n if (typeCheck) {\n // Set the file contents into cache.\n const updateMemoryCache = function (code: string, fileName: string) {\n if (memoryCache.contents[fileName] !== code) {\n memoryCache.contents[fileName] = code\n memoryCache.versions[fileName] = (memoryCache.versions[fileName] || 0) + 1\n }\n }\n\n // Create the compiler host for type checking.\n const serviceHost = {\n getScriptFileNames: () => Object.keys(memoryCache.versions),\n getScriptVersion: (fileName: string) => {\n const version = memoryCache.versions[fileName]\n\n // We need to return `undefined` and not a string here because TypeScript will use\n // `getScriptVersion` and compare against their own version - which can be `undefined`.\n // If we don't return `undefined` it results in `undefined === \"undefined\"` and run\n // `createProgram` again (which is very slow). Using a `string` assertion here to avoid\n // TypeScript errors from the function signature (expects `(x: string) => string`).\n return version === undefined ? undefined as any as string : String(version)\n },\n getScriptSnapshot (fileName: string) {\n // Read contents into TypeScript memory cache.\n if (!Object.prototype.hasOwnProperty.call(memoryCache.contents, fileName)) {\n memoryCache.contents[fileName] = readFile(fileName)\n }\n\n const contents = memoryCache.contents[fileName]\n if (contents === undefined) return\n return ts.ScriptSnapshot.fromString(contents)\n },\n fileExists: debugFn('fileExists', fileExists),\n readFile: debugFn('readFile', readFile),\n readDirectory: debugFn('readDirectory', ts.sys.readDirectory),\n getDirectories: debugFn('getDirectories', ts.sys.getDirectories),\n directoryExists: debugFn('directoryExists', ts.sys.directoryExists),\n getNewLine: () => EOL,\n getCurrentDirectory: () => cwd,\n getCompilationSettings: () => config.options,\n getDefaultLibFileName: () => ts.getDefaultLibFilePath(config.options),\n getCustomTransformers: () => transformers\n }\n\n const service = ts.createLanguageService(serviceHost)\n\n getOutput = function (code: string, fileName: string, lineOffset: number = 0) {\n // Must set memory cache before attempting to read file.\n updateMemoryCache(code, fileName)\n\n const output = service.getEmitOutput(fileName)\n\n // Get the relevant diagnostics - this is 3x faster than `getPreEmitDiagnostics`.\n const diagnostics = service.getCompilerOptionsDiagnostics()\n .concat(service.getSyntacticDiagnostics(fileName))\n .concat(service.getSemanticDiagnostics(fileName))\n\n const diagnosticList = filterDiagnostics(diagnostics, ignoreDiagnostics)\n\n if (diagnosticList.length) throw createTSError(diagnosticList)\n\n if (output.emitSkipped) {\n throw new TypeError(`${relative(cwd, fileName)}: Emit skipped`)\n }\n\n // Throw an error when requiring `.d.ts` files.\n if (output.outputFiles.length === 0) {\n throw new TypeError(\n 'Unable to require `.d.ts` file.\\n' +\n 'This is usually the result of a faulty configuration or import. ' +\n 'Make sure there is a `.js`, `.json` or another executable extension and ' +\n 'loader (attached before `ts-node`) available alongside ' +\n `\\`${basename(fileName)}\\`.`\n )\n }\n\n return [output.outputFiles[1].text, output.outputFiles[0].text]\n }\n\n getTypeInfo = function (code: string, fileName: string, position: number) {\n updateMemoryCache(code, fileName)\n\n const info = service.getQuickInfoAtPosition(fileName, position)\n const name = ts.displayPartsToString(info ? info.displayParts : [])\n const comment = ts.displayPartsToString(info ? info.documentation : [])\n\n return { name, comment }\n }\n }\n\n const compile = readThrough(cachedir, options.cache === true, memoryCache, getOutput, getExtension)\n const register: Register = { cwd, compile, getTypeInfo, extensions, cachedir, ts }\n\n // Register the extensions.\n extensions.forEach(extension => {\n registerExtension(extension, ignore, register, originalJsHandler)\n })\n\n return register\n}\n\n/**\n * Check if the filename should be ignored.\n */\nfunction shouldIgnore (filename: string, ignore: RegExp[]) {\n const relname = normalizeSlashes(filename)\n\n return ignore.some(x => x.test(relname))\n}\n\n/**\n * Register the extension for node.\n */\nfunction registerExtension (\n ext: string,\n ignore: RegExp[],\n register: Register,\n originalHandler: (m: NodeModule, filename: string) => any\n) {\n const old = require.extensions[ext] || originalHandler\n\n require.extensions[ext] = function (m: any, filename) {\n if (shouldIgnore(filename, ignore)) {\n return old(m, filename)\n }\n\n const _compile = m._compile\n\n m._compile = function (code: string, fileName: string) {\n debug('module._compile', fileName)\n\n return _compile.call(this, register.compile(code, fileName), fileName)\n }\n\n return old(m, filename)\n }\n}\n\n/**\n * Do post-processing on config options to support `ts-node`.\n */\nfunction fixConfig (ts: TSCommon, config: _ts.ParsedCommandLine) {\n // Delete options that *should not* be passed through.\n delete config.options.out\n delete config.options.outFile\n delete config.options.composite\n delete config.options.declarationDir\n delete config.options.declarationMap\n delete config.options.emitDeclarationOnly\n\n // Target ES5 output by default (instead of ES3).\n if (config.options.target === undefined) {\n config.options.target = ts.ScriptTarget.ES5\n }\n\n // Target CommonJS modules by default (instead of magically switching to ES6 when the target is ES6).\n if (config.options.module === undefined) {\n config.options.module = ts.ModuleKind.CommonJS\n }\n\n return config\n}\n\n/**\n * Load TypeScript configuration.\n */\nfunction readConfig (\n cwd: string,\n ts: TSCommon,\n fileExists: (path: string) => boolean,\n readFile: (path: string) => string | undefined,\n compilerOptions?: object,\n project?: string | null,\n noProject?: boolean | null\n): _ts.ParsedCommandLine {\n let config = { compilerOptions: {} }\n let basePath = normalizeSlashes(cwd)\n let configFileName: string | undefined = undefined\n\n // Read project configuration when available.\n if (!noProject) {\n configFileName = project\n ? normalizeSlashes(resolve(cwd, project))\n : ts.findConfigFile(normalizeSlashes(cwd), fileExists)\n\n if (configFileName) {\n const result = ts.readConfigFile(configFileName, readFile)\n\n // Return diagnostics.\n if (result.error) {\n return { errors: [result.error], fileNames: [], options: {} }\n }\n\n config = result.config\n basePath = normalizeSlashes(dirname(configFileName))\n }\n }\n\n // Override default configuration options `ts-node` requires.\n config.compilerOptions = Object.assign({}, config.compilerOptions, compilerOptions, DEFAULT_COMPILER_OPTIONS)\n\n return fixConfig(ts, ts.parseJsonConfigFileContent(config, ts.sys, basePath, undefined, configFileName))\n}\n\n/**\n * Internal source output.\n */\ntype SourceOutput = [string, string]\n\n/**\n * Wrap the function with caching.\n */\nfunction readThrough (\n cachedir: string,\n shouldCache: boolean,\n memoryCache: MemoryCache,\n compile: (code: string, fileName: string, lineOffset?: number) => SourceOutput,\n getExtension: (fileName: string) => string\n) {\n if (shouldCache === false) {\n return function (code: string, fileName: string, lineOffset?: number) {\n debug('readThrough', fileName)\n\n const [value, sourceMap] = compile(code, fileName, lineOffset)\n const output = updateOutput(value, fileName, sourceMap, getExtension)\n\n memoryCache.outputs[fileName] = output\n\n return output\n }\n }\n\n // Make sure the cache directory exists before continuing.\n mkdirp.sync(cachedir)\n\n return function (code: string, fileName: string, lineOffset?: number) {\n debug('readThrough', fileName)\n\n const cachePath = join(cachedir, getCacheName(code, fileName))\n const extension = getExtension(fileName)\n const outputPath = `${cachePath}${extension}`\n\n try {\n const output = readFileSync(outputPath, 'utf8')\n if (isValidCacheContent(output)) {\n memoryCache.outputs[fileName] = output\n return output\n }\n } catch (err) {/* Ignore. */}\n\n const [value, sourceMap] = compile(code, fileName, lineOffset)\n const output = updateOutput(value, fileName, sourceMap, getExtension)\n\n memoryCache.outputs[fileName] = output\n writeFileSync(outputPath, output)\n\n return output\n }\n}\n\n/**\n * Update the output remapping the source map.\n */\nfunction updateOutput (outputText: string, fileName: string, sourceMap: string, getExtension: (fileName: string) => string) {\n const base64Map = bufferFrom(updateSourceMap(sourceMap, fileName), 'utf8').toString('base64')\n const sourceMapContent = `data:application/json;charset=utf-8;base64,${base64Map}`\n const sourceMapLength = `${basename(fileName)}.map`.length + (getExtension(fileName).length - extname(fileName).length)\n\n return outputText.slice(0, -sourceMapLength) + sourceMapContent\n}\n\n/**\n * Update the source map contents for improved output.\n */\nfunction updateSourceMap (sourceMapText: string, fileName: string) {\n const sourceMap = JSON.parse(sourceMapText)\n sourceMap.file = fileName\n sourceMap.sources = [fileName]\n delete sourceMap.sourceRoot\n return JSON.stringify(sourceMap)\n}\n\n/**\n * Get the file name for the cache entry.\n */\nfunction getCacheName (sourceCode: string, fileName: string) {\n return crypto.createHash('sha256')\n .update(extname(fileName), 'utf8')\n .update('\\x00', 'utf8')\n .update(sourceCode, 'utf8')\n .digest('hex')\n}\n\n/**\n * Ensure the given cached content is valid by sniffing for a base64 encoded '}'\n * at the end of the content, which should exist if there is a valid sourceMap present.\n */\nfunction isValidCacheContent (contents: string) {\n return /(?:9|0=|Q==)$/.test(contents.slice(-3))\n}\n\n/**\n * Create a hash of the current configuration.\n */\nfunction getCompilerDigest (obj: object) {\n return crypto.createHash('sha256').update(JSON.stringify(obj), 'utf8').digest('hex')\n}\n\n/**\n * Filter diagnostics.\n */\nfunction filterDiagnostics (diagnostics: _ts.Diagnostic[], ignore: number[]) {\n return diagnostics.filter(x => ignore.indexOf(x.code) === -1)\n}\n"]} \ No newline at end of file diff --git a/node_modules/ts-node/dist/index.spec.d.ts b/node_modules/ts-node/dist/index.spec.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/node_modules/ts-node/dist/index.spec.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/node_modules/ts-node/dist/index.spec.js b/node_modules/ts-node/dist/index.spec.js new file mode 100644 index 0000000..28c2388 --- /dev/null +++ b/node_modules/ts-node/dist/index.spec.js @@ -0,0 +1,259 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +var chai_1 = require("chai"); +var child_process_1 = require("child_process"); +var path_1 = require("path"); +var semver = require("semver"); +var ts = require("typescript"); +var proxyquire = require("proxyquire"); +var index_1 = require("./index"); +var testDir = path_1.join(__dirname, '../tests'); +var EXEC_PATH = path_1.join(__dirname, '../dist/bin'); +var BIN_EXEC = "node \"" + EXEC_PATH + "\" --project \"" + testDir + "/tsconfig.json\""; +var SOURCE_MAP_REGEXP = /\/\/# sourceMappingURL=data:application\/json;charset=utf\-8;base64,[\w\+]+=*$/; +describe('ts-node', function () { + this.timeout(10000); + it('should export the correct version', function () { + chai_1.expect(index_1.VERSION).to.equal(require('../package.json').version); + }); + describe('cli', function () { + this.slow(1000); + it('should execute cli', function (done) { + child_process_1.exec(BIN_EXEC + " tests/hello-world", function (err, stdout) { + chai_1.expect(err).to.equal(null); + chai_1.expect(stdout).to.equal('Hello, world!\n'); + return done(); + }); + }); + it('should register via cli', function (done) { + child_process_1.exec("node -r ../register hello-world.ts", { + cwd: testDir + }, function (err, stdout) { + chai_1.expect(err).to.equal(null); + chai_1.expect(stdout).to.equal('Hello, world!\n'); + return done(); + }); + }); + it('should execute cli with absolute path', function (done) { + child_process_1.exec(BIN_EXEC + " \"" + path_1.join(testDir, 'hello-world') + "\"", function (err, stdout) { + chai_1.expect(err).to.equal(null); + chai_1.expect(stdout).to.equal('Hello, world!\n'); + return done(); + }); + }); + it('should print scripts', function (done) { + child_process_1.exec(BIN_EXEC + " -p \"import { example } from './tests/complex/index';example()\"", function (err, stdout) { + chai_1.expect(err).to.equal(null); + chai_1.expect(stdout).to.equal('example\n'); + return done(); + }); + }); + if (semver.gte(ts.version, '1.8.0')) { + it('should allow js', function (done) { + child_process_1.exec([ + BIN_EXEC, + '-O "{\\\"allowJs\\\":true}"', + '-p "import { main } from \'./tests/allow-js/run\';main()"' + ].join(' '), function (err, stdout) { + chai_1.expect(err).to.equal(null); + chai_1.expect(stdout).to.equal('hello world\n'); + return done(); + }); + }); + it('should include jsx when `allow-js` true', function (done) { + child_process_1.exec([ + BIN_EXEC, + '-O "{\\\"allowJs\\\":true}"', + '-p "import { Foo2 } from \'./tests/allow-js/with-jsx\'; Foo2.sayHi()"' + ].join(' '), function (err, stdout) { + chai_1.expect(err).to.equal(null); + chai_1.expect(stdout).to.equal('hello world\n'); + return done(); + }); + }); + } + it('should eval code', function (done) { + child_process_1.exec(BIN_EXEC + " -e \"import * as m from './tests/module';console.log(m.example('test'))\"", function (err, stdout) { + chai_1.expect(err).to.equal(null); + chai_1.expect(stdout).to.equal('TEST\n'); + return done(); + }); + }); + it('should import empty files', function (done) { + child_process_1.exec(BIN_EXEC + " -e \"import './tests/empty'\"", function (err, stdout) { + chai_1.expect(err).to.equal(null); + chai_1.expect(stdout).to.equal(''); + return done(); + }); + }); + it('should throw errors', function (done) { + child_process_1.exec(BIN_EXEC + " -e \"import * as m from './tests/module';console.log(m.example(123))\"", function (err) { + if (err === null) { + return done('Command was expected to fail, but it succeeded.'); + } + chai_1.expect(err.message).to.match(new RegExp('TS2345: Argument of type \'(?:number|123)\' ' + + 'is not assignable to parameter of type \'string\'\\.')); + return done(); + }); + }); + it('should be able to ignore diagnostic', function (done) { + child_process_1.exec(BIN_EXEC + " --ignoreDiagnostics 2345 -e \"import * as m from './tests/module';console.log(m.example(123))\"", function (err) { + if (err === null) { + return done('Command was expected to fail, but it succeeded.'); + } + chai_1.expect(err.message).to.match(/TypeError: (?:(?:undefined|foo\.toUpperCase) is not a function|.*has no method \'toUpperCase\')/); + return done(); + }); + }); + it('should work with source maps', function (done) { + child_process_1.exec(BIN_EXEC + " tests/throw", function (err) { + if (err === null) { + return done('Command was expected to fail, but it succeeded.'); + } + chai_1.expect(err.message).to.contain([ + path_1.join(__dirname, '../tests/throw.ts') + ":3", + ' bar () { throw new Error(\'this is a demo\') }', + ' ^', + 'Error: this is a demo' + ].join('\n')); + return done(); + }); + }); + it.skip('eval should work with source maps', function (done) { + child_process_1.exec(BIN_EXEC + " -p \"import './tests/throw'\"", function (err) { + if (err === null) { + return done('Command was expected to fail, but it succeeded.'); + } + chai_1.expect(err.message).to.contain([ + path_1.join(__dirname, '../tests/throw.ts') + ":3", + ' bar () { throw new Error(\'this is a demo\') }', + ' ^' + ].join('\n')); + return done(); + }); + }); + it('should support transpile only mode', function (done) { + child_process_1.exec(BIN_EXEC + " --transpileOnly -p \"x\"", function (err) { + if (err === null) { + return done('Command was expected to fail, but it succeeded.'); + } + chai_1.expect(err.message).to.contain('ReferenceError: x is not defined'); + return done(); + }); + }); + it('should pipe into `ts-node` and evaluate', function (done) { + var cp = child_process_1.exec(BIN_EXEC, function (err, stdout) { + chai_1.expect(err).to.equal(null); + chai_1.expect(stdout).to.equal('hello\n'); + return done(); + }); + cp.stdin.end("console.log('hello')"); + }); + it('should pipe into `ts-node`', function (done) { + var cp = child_process_1.exec(BIN_EXEC + " -p", function (err, stdout) { + chai_1.expect(err).to.equal(null); + chai_1.expect(stdout).to.equal('true\n'); + return done(); + }); + cp.stdin.end('true'); + }); + it('should pipe into an eval script', function (done) { + var cp = child_process_1.exec(BIN_EXEC + " --fast -p 'process.stdin.isTTY'", function (err, stdout) { + chai_1.expect(err).to.equal(null); + chai_1.expect(stdout).to.equal('undefined\n'); + return done(); + }); + cp.stdin.end('true'); + }); + it('should support require flags', function (done) { + child_process_1.exec(BIN_EXEC + " -r ./tests/hello-world -p \"console.log('success')\"", function (err, stdout) { + chai_1.expect(err).to.equal(null); + chai_1.expect(stdout).to.equal('Hello, world!\nsuccess\nundefined\n'); + return done(); + }); + }); + it('should support require from node modules', function (done) { + child_process_1.exec(BIN_EXEC + " -r typescript -e \"console.log('success')\"", function (err, stdout) { + chai_1.expect(err).to.equal(null); + chai_1.expect(stdout).to.equal('success\n'); + return done(); + }); + }); + it.skip('should use source maps with react tsx', function (done) { + child_process_1.exec(BIN_EXEC + " -r ./tests/emit-compiled.ts tests/jsx-react.tsx", function (err, stdout) { + chai_1.expect(err).to.equal(null); + chai_1.expect(stdout).to.equal('todo'); + return done(); + }); + }); + it('should allow custom typings', function (done) { + child_process_1.exec(BIN_EXEC + " tests/custom-types", function (err, stdout) { + chai_1.expect(err).to.match(/Error: Cannot find module 'does-not-exist'/); + return done(); + }); + }); + }); + describe('register', function () { + index_1.register({ + project: path_1.join(testDir, 'tsconfig.json'), + compilerOptions: { + jsx: 'preserve' + } + }); + it('should be able to require typescript', function () { + var m = require('../tests/module'); + chai_1.expect(m.example('foo')).to.equal('FOO'); + }); + it('should compile through js and ts', function () { + var m = require('../tests/complex'); + chai_1.expect(m.example()).to.equal('example'); + }); + it('should work with proxyquire', function () { + var m = proxyquire('../tests/complex', { + './example': 'hello' + }); + chai_1.expect(m.example()).to.equal('hello'); + }); + it('should use source maps', function (done) { + try { + require('../tests/throw'); + } + catch (error) { + chai_1.expect(error.stack).to.contain([ + 'Error: this is a demo', + " at Foo.bar (" + path_1.join(__dirname, '../tests/throw.ts') + ":3:18)" + ].join('\n')); + done(); + } + }); + describe('JSX preserve', function () { + var old = require.extensions['.tsx']; + var compiled; + before(function () { + var _this = this; + require.extensions['.tsx'] = function (m, fileName) { + var _compile = m._compile; + m._compile = function (code, fileName) { + compiled = code; + return _compile.call(_this, code, fileName); + }; + return old(m, fileName); + }; + }); + after(function () { + require.extensions['.tsx'] = old; + }); + it('should use source maps', function (done) { + try { + require('../tests/with-jsx.tsx'); + } + catch (error) { + chai_1.expect(error.stack).to.contain('SyntaxError: Unexpected token <\n'); + } + chai_1.expect(compiled).to.match(SOURCE_MAP_REGEXP); + done(); + }); + }); + }); +}); +//# sourceMappingURL=index.spec.js.map \ No newline at end of file diff --git a/node_modules/ts-node/dist/index.spec.js.map b/node_modules/ts-node/dist/index.spec.js.map new file mode 100644 index 0000000..62cdad2 --- /dev/null +++ b/node_modules/ts-node/dist/index.spec.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.spec.js","sourceRoot":"","sources":["../src/index.spec.ts"],"names":[],"mappings":";;AAAA,6BAA6B;AAC7B,+CAAoC;AACpC,6BAA2B;AAC3B,+BAAiC;AACjC,+BAAiC;AACjC,uCAAyC;AACzC,iCAA2C;AAE3C,IAAM,OAAO,GAAG,WAAI,CAAC,SAAS,EAAE,UAAU,CAAC,CAAA;AAC3C,IAAM,SAAS,GAAG,WAAI,CAAC,SAAS,EAAE,aAAa,CAAC,CAAA;AAChD,IAAM,QAAQ,GAAG,YAAS,SAAS,uBAAgB,OAAO,qBAAiB,CAAA;AAE3E,IAAM,iBAAiB,GAAG,gFAAgF,CAAA;AAE1G,QAAQ,CAAC,SAAS,EAAE;IAClB,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,CAAA;IAEnB,EAAE,CAAC,mCAAmC,EAAE;QACtC,aAAM,CAAC,eAAO,CAAC,CAAC,EAAE,CAAC,KAAK,CAAC,OAAO,CAAC,iBAAiB,CAAC,CAAC,OAAO,CAAC,CAAA;IAC9D,CAAC,CAAC,CAAA;IAEF,QAAQ,CAAC,KAAK,EAAE;QACd,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,CAAA;QAEf,EAAE,CAAC,oBAAoB,EAAE,UAAU,IAAI;YACrC,oBAAI,CAAI,QAAQ,uBAAoB,EAAE,UAAU,GAAG,EAAE,MAAM;gBACzD,aAAM,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC,KAAK,CAAC,IAAI,CAAC,CAAA;gBAC1B,aAAM,CAAC,MAAM,CAAC,CAAC,EAAE,CAAC,KAAK,CAAC,iBAAiB,CAAC,CAAA;gBAE1C,OAAO,IAAI,EAAE,CAAA;YACf,CAAC,CAAC,CAAA;QACJ,CAAC,CAAC,CAAA;QAEF,EAAE,CAAC,yBAAyB,EAAE,UAAU,IAAI;YAC1C,oBAAI,CAAC,oCAAoC,EAAE;gBACzC,GAAG,EAAE,OAAO;aACb,EAAE,UAAU,GAAG,EAAE,MAAM;gBACtB,aAAM,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC,KAAK,CAAC,IAAI,CAAC,CAAA;gBAC1B,aAAM,CAAC,MAAM,CAAC,CAAC,EAAE,CAAC,KAAK,CAAC,iBAAiB,CAAC,CAAA;gBAE1C,OAAO,IAAI,EAAE,CAAA;YACf,CAAC,CAAC,CAAA;QACJ,CAAC,CAAC,CAAA;QAEF,EAAE,CAAC,uCAAuC,EAAE,UAAU,IAAI;YACxD,oBAAI,CAAI,QAAQ,WAAK,WAAI,CAAC,OAAO,EAAE,aAAa,CAAC,OAAG,EAAE,UAAU,GAAG,EAAE,MAAM;gBACzE,aAAM,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC,KAAK,CAAC,IAAI,CAAC,CAAA;gBAC1B,aAAM,CAAC,MAAM,CAAC,CAAC,EAAE,CAAC,KAAK,CAAC,iBAAiB,CAAC,CAAA;gBAE1C,OAAO,IAAI,EAAE,CAAA;YACf,CAAC,CAAC,CAAA;QACJ,CAAC,CAAC,CAAA;QAEF,EAAE,CAAC,sBAAsB,EAAE,UAAU,IAAI;YACvC,oBAAI,CAAI,QAAQ,sEAAiE,EAAE,UAAU,GAAG,EAAE,MAAM;gBACtG,aAAM,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC,KAAK,CAAC,IAAI,CAAC,CAAA;gBAC1B,aAAM,CAAC,MAAM,CAAC,CAAC,EAAE,CAAC,KAAK,CAAC,WAAW,CAAC,CAAA;gBAEpC,OAAO,IAAI,EAAE,CAAA;YACf,CAAC,CAAC,CAAA;QACJ,CAAC,CAAC,CAAA;QAEF,IAAI,MAAM,CAAC,GAAG,CAAC,EAAE,CAAC,OAAO,EAAE,OAAO,CAAC,EAAE;YACnC,EAAE,CAAC,iBAAiB,EAAE,UAAU,IAAI;gBAClC,oBAAI,CACF;oBACE,QAAQ;oBACR,6BAA6B;oBAC7B,2DAA2D;iBAC5D,CAAC,IAAI,CAAC,GAAG,CAAC,EACX,UAAU,GAAG,EAAE,MAAM;oBACnB,aAAM,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC,KAAK,CAAC,IAAI,CAAC,CAAA;oBAC1B,aAAM,CAAC,MAAM,CAAC,CAAC,EAAE,CAAC,KAAK,CAAC,eAAe,CAAC,CAAA;oBAExC,OAAO,IAAI,EAAE,CAAA;gBACf,CAAC,CACF,CAAA;YACH,CAAC,CAAC,CAAA;YAEF,EAAE,CAAC,yCAAyC,EAAE,UAAU,IAAI;gBAC1D,oBAAI,CACF;oBACE,QAAQ;oBACR,6BAA6B;oBAC7B,uEAAuE;iBACxE,CAAC,IAAI,CAAC,GAAG,CAAC,EACX,UAAU,GAAG,EAAE,MAAM;oBACnB,aAAM,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC,KAAK,CAAC,IAAI,CAAC,CAAA;oBAC1B,aAAM,CAAC,MAAM,CAAC,CAAC,EAAE,CAAC,KAAK,CAAC,eAAe,CAAC,CAAA;oBAExC,OAAO,IAAI,EAAE,CAAA;gBACf,CAAC,CACF,CAAA;YACH,CAAC,CAAC,CAAA;SACH;QAED,EAAE,CAAC,kBAAkB,EAAE,UAAU,IAAI;YACnC,oBAAI,CACC,QAAQ,+EAA0E,EACrF,UAAU,GAAG,EAAE,MAAM;gBACnB,aAAM,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC,KAAK,CAAC,IAAI,CAAC,CAAA;gBAC1B,aAAM,CAAC,MAAM,CAAC,CAAC,EAAE,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAA;gBAEjC,OAAO,IAAI,EAAE,CAAA;YACf,CAAC,CACF,CAAA;QACH,CAAC,CAAC,CAAA;QAEF,EAAE,CAAC,2BAA2B,EAAE,UAAU,IAAI;YAC5C,oBAAI,CAAI,QAAQ,mCAA8B,EAAE,UAAU,GAAG,EAAE,MAAM;gBACnE,aAAM,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC,KAAK,CAAC,IAAI,CAAC,CAAA;gBAC1B,aAAM,CAAC,MAAM,CAAC,CAAC,EAAE,CAAC,KAAK,CAAC,EAAE,CAAC,CAAA;gBAE3B,OAAO,IAAI,EAAE,CAAA;YACf,CAAC,CAAC,CAAA;QACJ,CAAC,CAAC,CAAA;QAEF,EAAE,CAAC,qBAAqB,EAAE,UAAU,IAAI;YACtC,oBAAI,CAAI,QAAQ,4EAAuE,EAAE,UAAU,GAAG;gBACpG,IAAI,GAAG,KAAK,IAAI,EAAE;oBAChB,OAAO,IAAI,CAAC,iDAAiD,CAAC,CAAA;iBAC/D;gBAED,aAAM,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,EAAE,CAAC,KAAK,CAAC,IAAI,MAAM,CACrC,8CAA8C;oBAC9C,sDAAsD,CACvD,CAAC,CAAA;gBAEF,OAAO,IAAI,EAAE,CAAA;YACf,CAAC,CAAC,CAAA;QACJ,CAAC,CAAC,CAAA;QAEF,EAAE,CAAC,qCAAqC,EAAE,UAAU,IAAI;YACtD,oBAAI,CACC,QAAQ,qGAAgG,EAC3G,UAAU,GAAG;gBACX,IAAI,GAAG,KAAK,IAAI,EAAE;oBAChB,OAAO,IAAI,CAAC,iDAAiD,CAAC,CAAA;iBAC/D;gBAED,aAAM,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,EAAE,CAAC,KAAK,CAC1B,iGAAiG,CAClG,CAAA;gBAED,OAAO,IAAI,EAAE,CAAA;YACf,CAAC,CACF,CAAA;QACH,CAAC,CAAC,CAAA;QAEF,EAAE,CAAC,8BAA8B,EAAE,UAAU,IAAI;YAC/C,oBAAI,CAAI,QAAQ,iBAAc,EAAE,UAAU,GAAG;gBAC3C,IAAI,GAAG,KAAK,IAAI,EAAE;oBAChB,OAAO,IAAI,CAAC,iDAAiD,CAAC,CAAA;iBAC/D;gBAED,aAAM,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,EAAE,CAAC,OAAO,CAAC;oBAC1B,WAAI,CAAC,SAAS,EAAE,mBAAmB,CAAC,OAAI;oBAC3C,kDAAkD;oBAClD,oBAAoB;oBACpB,uBAAuB;iBACxB,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAA;gBAEb,OAAO,IAAI,EAAE,CAAA;YACf,CAAC,CAAC,CAAA;QACJ,CAAC,CAAC,CAAA;QAEF,EAAE,CAAC,IAAI,CAAC,mCAAmC,EAAE,UAAU,IAAI;YACzD,oBAAI,CAAI,QAAQ,mCAA8B,EAAE,UAAU,GAAG;gBAC3D,IAAI,GAAG,KAAK,IAAI,EAAE;oBAChB,OAAO,IAAI,CAAC,iDAAiD,CAAC,CAAA;iBAC/D;gBAED,aAAM,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,EAAE,CAAC,OAAO,CAAC;oBAC1B,WAAI,CAAC,SAAS,EAAE,mBAAmB,CAAC,OAAI;oBAC3C,kDAAkD;oBAClD,oBAAoB;iBACrB,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAA;gBAEb,OAAO,IAAI,EAAE,CAAA;YACf,CAAC,CAAC,CAAA;QACJ,CAAC,CAAC,CAAA;QAEF,EAAE,CAAC,oCAAoC,EAAE,UAAU,IAAI;YACrD,oBAAI,CAAI,QAAQ,8BAAyB,EAAE,UAAU,GAAG;gBACtD,IAAI,GAAG,KAAK,IAAI,EAAE;oBAChB,OAAO,IAAI,CAAC,iDAAiD,CAAC,CAAA;iBAC/D;gBAED,aAAM,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,EAAE,CAAC,OAAO,CAAC,kCAAkC,CAAC,CAAA;gBAElE,OAAO,IAAI,EAAE,CAAA;YACf,CAAC,CAAC,CAAA;QACJ,CAAC,CAAC,CAAA;QAEF,EAAE,CAAC,yCAAyC,EAAE,UAAU,IAAI;YAC1D,IAAM,EAAE,GAAG,oBAAI,CAAC,QAAQ,EAAE,UAAU,GAAG,EAAE,MAAM;gBAC7C,aAAM,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC,KAAK,CAAC,IAAI,CAAC,CAAA;gBAC1B,aAAM,CAAC,MAAM,CAAC,CAAC,EAAE,CAAC,KAAK,CAAC,SAAS,CAAC,CAAA;gBAElC,OAAO,IAAI,EAAE,CAAA;YACf,CAAC,CAAC,CAAA;YAEF,EAAE,CAAC,KAAK,CAAC,GAAG,CAAC,sBAAsB,CAAC,CAAA;QACtC,CAAC,CAAC,CAAA;QAEF,EAAE,CAAC,4BAA4B,EAAE,UAAU,IAAI;YAC7C,IAAM,EAAE,GAAG,oBAAI,CAAI,QAAQ,QAAK,EAAE,UAAU,GAAG,EAAE,MAAM;gBACrD,aAAM,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC,KAAK,CAAC,IAAI,CAAC,CAAA;gBAC1B,aAAM,CAAC,MAAM,CAAC,CAAC,EAAE,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAA;gBAEjC,OAAO,IAAI,EAAE,CAAA;YACf,CAAC,CAAC,CAAA;YAEF,EAAE,CAAC,KAAK,CAAC,GAAG,CAAC,MAAM,CAAC,CAAA;QACtB,CAAC,CAAC,CAAA;QAEF,EAAE,CAAC,iCAAiC,EAAE,UAAU,IAAI;YAClD,IAAM,EAAE,GAAG,oBAAI,CAAI,QAAQ,qCAAkC,EAAE,UAAU,GAAG,EAAE,MAAM;gBAClF,aAAM,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC,KAAK,CAAC,IAAI,CAAC,CAAA;gBAC1B,aAAM,CAAC,MAAM,CAAC,CAAC,EAAE,CAAC,KAAK,CAAC,aAAa,CAAC,CAAA;gBAEtC,OAAO,IAAI,EAAE,CAAA;YACf,CAAC,CAAC,CAAA;YAEF,EAAE,CAAC,KAAK,CAAC,GAAG,CAAC,MAAM,CAAC,CAAA;QACtB,CAAC,CAAC,CAAA;QAEF,EAAE,CAAC,8BAA8B,EAAE,UAAU,IAAI;YAC/C,oBAAI,CAAI,QAAQ,0DAAqD,EAAE,UAAU,GAAG,EAAE,MAAM;gBAC1F,aAAM,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC,KAAK,CAAC,IAAI,CAAC,CAAA;gBAC1B,aAAM,CAAC,MAAM,CAAC,CAAC,EAAE,CAAC,KAAK,CAAC,qCAAqC,CAAC,CAAA;gBAE9D,OAAO,IAAI,EAAE,CAAA;YACf,CAAC,CAAC,CAAA;QACJ,CAAC,CAAC,CAAA;QAEF,EAAE,CAAC,0CAA0C,EAAE,UAAU,IAAI;YAC3D,oBAAI,CAAI,QAAQ,iDAA4C,EAAE,UAAU,GAAG,EAAE,MAAM;gBACjF,aAAM,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC,KAAK,CAAC,IAAI,CAAC,CAAA;gBAC1B,aAAM,CAAC,MAAM,CAAC,CAAC,EAAE,CAAC,KAAK,CAAC,WAAW,CAAC,CAAA;gBAEpC,OAAO,IAAI,EAAE,CAAA;YACf,CAAC,CAAC,CAAA;QACJ,CAAC,CAAC,CAAA;QAEF,EAAE,CAAC,IAAI,CAAC,uCAAuC,EAAE,UAAU,IAAI;YAC7D,oBAAI,CAAI,QAAQ,qDAAkD,EAAE,UAAU,GAAG,EAAE,MAAM;gBACvF,aAAM,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC,KAAK,CAAC,IAAI,CAAC,CAAA;gBAC1B,aAAM,CAAC,MAAM,CAAC,CAAC,EAAE,CAAC,KAAK,CAAC,MAAM,CAAC,CAAA;gBAE/B,OAAO,IAAI,EAAE,CAAA;YACf,CAAC,CAAC,CAAA;QACJ,CAAC,CAAC,CAAA;QAEF,EAAE,CAAC,6BAA6B,EAAE,UAAU,IAAI;YAC9C,oBAAI,CAAI,QAAQ,wBAAqB,EAAE,UAAU,GAAG,EAAE,MAAM;gBAC1D,aAAM,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC,KAAK,CAAC,4CAA4C,CAAC,CAAA;gBAElE,OAAO,IAAI,EAAE,CAAA;YACf,CAAC,CAAC,CAAA;QACJ,CAAC,CAAC,CAAA;IACJ,CAAC,CAAC,CAAA;IAEF,QAAQ,CAAC,UAAU,EAAE;QACnB,gBAAQ,CAAC;YACP,OAAO,EAAE,WAAI,CAAC,OAAO,EAAE,eAAe,CAAC;YACvC,eAAe,EAAE;gBACf,GAAG,EAAE,UAAU;aAChB;SACF,CAAC,CAAA;QAEF,EAAE,CAAC,sCAAsC,EAAE;YACzC,IAAM,CAAC,GAAG,OAAO,CAAC,iBAAiB,CAAC,CAAA;YAEpC,aAAM,CAAC,CAAC,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,CAAC,KAAK,CAAC,KAAK,CAAC,CAAA;QAC1C,CAAC,CAAC,CAAA;QAEF,EAAE,CAAC,kCAAkC,EAAE;YACrC,IAAM,CAAC,GAAG,OAAO,CAAC,kBAAkB,CAAC,CAAA;YAErC,aAAM,CAAC,CAAC,CAAC,OAAO,EAAE,CAAC,CAAC,EAAE,CAAC,KAAK,CAAC,SAAS,CAAC,CAAA;QACzC,CAAC,CAAC,CAAA;QAEF,EAAE,CAAC,6BAA6B,EAAE;YAChC,IAAM,CAAC,GAAG,UAAU,CAAC,kBAAkB,EAAE;gBACvC,WAAW,EAAE,OAAO;aACrB,CAAC,CAAA;YAEF,aAAM,CAAC,CAAC,CAAC,OAAO,EAAE,CAAC,CAAC,EAAE,CAAC,KAAK,CAAC,OAAO,CAAC,CAAA;QACvC,CAAC,CAAC,CAAA;QAEF,EAAE,CAAC,wBAAwB,EAAE,UAAU,IAAI;YACzC,IAAI;gBACF,OAAO,CAAC,gBAAgB,CAAC,CAAA;aAC1B;YAAC,OAAO,KAAK,EAAE;gBACd,aAAM,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,OAAO,CAAC;oBAC7B,uBAAuB;oBACvB,qBAAmB,WAAI,CAAC,SAAS,EAAE,mBAAmB,CAAC,WAAQ;iBAChE,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAA;gBAEb,IAAI,EAAE,CAAA;aACP;QACH,CAAC,CAAC,CAAA;QAEF,QAAQ,CAAC,cAAc,EAAE;YACvB,IAAI,GAAG,GAAG,OAAO,CAAC,UAAU,CAAC,MAAM,CAAC,CAAA;YACpC,IAAI,QAAgB,CAAA;YAEpB,MAAM,CAAC;gBAAA,iBAWN;gBAVC,OAAO,CAAC,UAAU,CAAC,MAAM,CAAC,GAAG,UAAC,CAAM,EAAE,QAAQ;oBAC5C,IAAM,QAAQ,GAAG,CAAC,CAAC,QAAQ,CAAA;oBAE3B,CAAC,CAAC,QAAQ,GAAG,UAAC,IAAY,EAAE,QAAgB;wBAC1C,QAAQ,GAAG,IAAI,CAAA;wBACf,OAAO,QAAQ,CAAC,IAAI,CAAC,KAAI,EAAE,IAAI,EAAE,QAAQ,CAAC,CAAA;oBAC5C,CAAC,CAAA;oBAED,OAAO,GAAG,CAAC,CAAC,EAAE,QAAQ,CAAC,CAAA;gBACzB,CAAC,CAAA;YACH,CAAC,CAAC,CAAA;YAEF,KAAK,CAAC;gBACJ,OAAO,CAAC,UAAU,CAAC,MAAM,CAAC,GAAG,GAAG,CAAA;YAClC,CAAC,CAAC,CAAA;YAEF,EAAE,CAAC,wBAAwB,EAAE,UAAU,IAAI;gBACzC,IAAI;oBACF,OAAO,CAAC,uBAAuB,CAAC,CAAA;iBACjC;gBAAC,OAAO,KAAK,EAAE;oBACd,aAAM,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,OAAO,CAAC,mCAAmC,CAAC,CAAA;iBACpE;gBAED,aAAM,CAAC,QAAQ,CAAC,CAAC,EAAE,CAAC,KAAK,CAAC,iBAAiB,CAAC,CAAA;gBAE5C,IAAI,EAAE,CAAA;YACR,CAAC,CAAC,CAAA;QACJ,CAAC,CAAC,CAAA;IACJ,CAAC,CAAC,CAAA;AACJ,CAAC,CAAC,CAAA","sourcesContent":["import { expect } from 'chai'\nimport { exec } from 'child_process'\nimport { join } from 'path'\nimport semver = require('semver')\nimport ts = require('typescript')\nimport proxyquire = require('proxyquire')\nimport { register, VERSION } from './index'\n\nconst testDir = join(__dirname, '../tests')\nconst EXEC_PATH = join(__dirname, '../dist/bin')\nconst BIN_EXEC = `node \"${EXEC_PATH}\" --project \"${testDir}/tsconfig.json\"`\n\nconst SOURCE_MAP_REGEXP = /\\/\\/# sourceMappingURL=data:application\\/json;charset=utf\\-8;base64,[\\w\\+]+=*$/\n\ndescribe('ts-node', function () {\n this.timeout(10000)\n\n it('should export the correct version', function () {\n expect(VERSION).to.equal(require('../package.json').version)\n })\n\n describe('cli', function () {\n this.slow(1000)\n\n it('should execute cli', function (done) {\n exec(`${BIN_EXEC} tests/hello-world`, function (err, stdout) {\n expect(err).to.equal(null)\n expect(stdout).to.equal('Hello, world!\\n')\n\n return done()\n })\n })\n\n it('should register via cli', function (done) {\n exec(`node -r ../register hello-world.ts`, {\n cwd: testDir\n }, function (err, stdout) {\n expect(err).to.equal(null)\n expect(stdout).to.equal('Hello, world!\\n')\n\n return done()\n })\n })\n\n it('should execute cli with absolute path', function (done) {\n exec(`${BIN_EXEC} \"${join(testDir, 'hello-world')}\"`, function (err, stdout) {\n expect(err).to.equal(null)\n expect(stdout).to.equal('Hello, world!\\n')\n\n return done()\n })\n })\n\n it('should print scripts', function (done) {\n exec(`${BIN_EXEC} -p \"import { example } from './tests/complex/index';example()\"`, function (err, stdout) {\n expect(err).to.equal(null)\n expect(stdout).to.equal('example\\n')\n\n return done()\n })\n })\n\n if (semver.gte(ts.version, '1.8.0')) {\n it('should allow js', function (done) {\n exec(\n [\n BIN_EXEC,\n '-O \"{\\\\\\\"allowJs\\\\\\\":true}\"',\n '-p \"import { main } from \\'./tests/allow-js/run\\';main()\"'\n ].join(' '),\n function (err, stdout) {\n expect(err).to.equal(null)\n expect(stdout).to.equal('hello world\\n')\n\n return done()\n }\n )\n })\n\n it('should include jsx when `allow-js` true', function (done) {\n exec(\n [\n BIN_EXEC,\n '-O \"{\\\\\\\"allowJs\\\\\\\":true}\"',\n '-p \"import { Foo2 } from \\'./tests/allow-js/with-jsx\\'; Foo2.sayHi()\"'\n ].join(' '),\n function (err, stdout) {\n expect(err).to.equal(null)\n expect(stdout).to.equal('hello world\\n')\n\n return done()\n }\n )\n })\n }\n\n it('should eval code', function (done) {\n exec(\n `${BIN_EXEC} -e \"import * as m from './tests/module';console.log(m.example('test'))\"`,\n function (err, stdout) {\n expect(err).to.equal(null)\n expect(stdout).to.equal('TEST\\n')\n\n return done()\n }\n )\n })\n\n it('should import empty files', function (done) {\n exec(`${BIN_EXEC} -e \"import './tests/empty'\"`, function (err, stdout) {\n expect(err).to.equal(null)\n expect(stdout).to.equal('')\n\n return done()\n })\n })\n\n it('should throw errors', function (done) {\n exec(`${BIN_EXEC} -e \"import * as m from './tests/module';console.log(m.example(123))\"`, function (err) {\n if (err === null) {\n return done('Command was expected to fail, but it succeeded.')\n }\n\n expect(err.message).to.match(new RegExp(\n 'TS2345: Argument of type \\'(?:number|123)\\' ' +\n 'is not assignable to parameter of type \\'string\\'\\\\.'\n ))\n\n return done()\n })\n })\n\n it('should be able to ignore diagnostic', function (done) {\n exec(\n `${BIN_EXEC} --ignoreDiagnostics 2345 -e \"import * as m from './tests/module';console.log(m.example(123))\"`,\n function (err) {\n if (err === null) {\n return done('Command was expected to fail, but it succeeded.')\n }\n\n expect(err.message).to.match(\n /TypeError: (?:(?:undefined|foo\\.toUpperCase) is not a function|.*has no method \\'toUpperCase\\')/\n )\n\n return done()\n }\n )\n })\n\n it('should work with source maps', function (done) {\n exec(`${BIN_EXEC} tests/throw`, function (err) {\n if (err === null) {\n return done('Command was expected to fail, but it succeeded.')\n }\n\n expect(err.message).to.contain([\n `${join(__dirname, '../tests/throw.ts')}:3`,\n ' bar () { throw new Error(\\'this is a demo\\') }',\n ' ^',\n 'Error: this is a demo'\n ].join('\\n'))\n\n return done()\n })\n })\n\n it.skip('eval should work with source maps', function (done) {\n exec(`${BIN_EXEC} -p \"import './tests/throw'\"`, function (err) {\n if (err === null) {\n return done('Command was expected to fail, but it succeeded.')\n }\n\n expect(err.message).to.contain([\n `${join(__dirname, '../tests/throw.ts')}:3`,\n ' bar () { throw new Error(\\'this is a demo\\') }',\n ' ^'\n ].join('\\n'))\n\n return done()\n })\n })\n\n it('should support transpile only mode', function (done) {\n exec(`${BIN_EXEC} --transpileOnly -p \"x\"`, function (err) {\n if (err === null) {\n return done('Command was expected to fail, but it succeeded.')\n }\n\n expect(err.message).to.contain('ReferenceError: x is not defined')\n\n return done()\n })\n })\n\n it('should pipe into `ts-node` and evaluate', function (done) {\n const cp = exec(BIN_EXEC, function (err, stdout) {\n expect(err).to.equal(null)\n expect(stdout).to.equal('hello\\n')\n\n return done()\n })\n\n cp.stdin.end(\"console.log('hello')\")\n })\n\n it('should pipe into `ts-node`', function (done) {\n const cp = exec(`${BIN_EXEC} -p`, function (err, stdout) {\n expect(err).to.equal(null)\n expect(stdout).to.equal('true\\n')\n\n return done()\n })\n\n cp.stdin.end('true')\n })\n\n it('should pipe into an eval script', function (done) {\n const cp = exec(`${BIN_EXEC} --fast -p 'process.stdin.isTTY'`, function (err, stdout) {\n expect(err).to.equal(null)\n expect(stdout).to.equal('undefined\\n')\n\n return done()\n })\n\n cp.stdin.end('true')\n })\n\n it('should support require flags', function (done) {\n exec(`${BIN_EXEC} -r ./tests/hello-world -p \"console.log('success')\"`, function (err, stdout) {\n expect(err).to.equal(null)\n expect(stdout).to.equal('Hello, world!\\nsuccess\\nundefined\\n')\n\n return done()\n })\n })\n\n it('should support require from node modules', function (done) {\n exec(`${BIN_EXEC} -r typescript -e \"console.log('success')\"`, function (err, stdout) {\n expect(err).to.equal(null)\n expect(stdout).to.equal('success\\n')\n\n return done()\n })\n })\n\n it.skip('should use source maps with react tsx', function (done) {\n exec(`${BIN_EXEC} -r ./tests/emit-compiled.ts tests/jsx-react.tsx`, function (err, stdout) {\n expect(err).to.equal(null)\n expect(stdout).to.equal('todo')\n\n return done()\n })\n })\n\n it('should allow custom typings', function (done) {\n exec(`${BIN_EXEC} tests/custom-types`, function (err, stdout) {\n expect(err).to.match(/Error: Cannot find module 'does-not-exist'/)\n\n return done()\n })\n })\n })\n\n describe('register', function () {\n register({\n project: join(testDir, 'tsconfig.json'),\n compilerOptions: {\n jsx: 'preserve'\n }\n })\n\n it('should be able to require typescript', function () {\n const m = require('../tests/module')\n\n expect(m.example('foo')).to.equal('FOO')\n })\n\n it('should compile through js and ts', function () {\n const m = require('../tests/complex')\n\n expect(m.example()).to.equal('example')\n })\n\n it('should work with proxyquire', function () {\n const m = proxyquire('../tests/complex', {\n './example': 'hello'\n })\n\n expect(m.example()).to.equal('hello')\n })\n\n it('should use source maps', function (done) {\n try {\n require('../tests/throw')\n } catch (error) {\n expect(error.stack).to.contain([\n 'Error: this is a demo',\n ` at Foo.bar (${join(__dirname, '../tests/throw.ts')}:3:18)`\n ].join('\\n'))\n\n done()\n }\n })\n\n describe('JSX preserve', () => {\n let old = require.extensions['.tsx']\n let compiled: string\n\n before(function () {\n require.extensions['.tsx'] = (m: any, fileName) => {\n const _compile = m._compile\n\n m._compile = (code: string, fileName: string) => {\n compiled = code\n return _compile.call(this, code, fileName)\n }\n\n return old(m, fileName)\n }\n })\n\n after(function () {\n require.extensions['.tsx'] = old\n })\n\n it('should use source maps', function (done) {\n try {\n require('../tests/with-jsx.tsx')\n } catch (error) {\n expect(error.stack).to.contain('SyntaxError: Unexpected token <\\n')\n }\n\n expect(compiled).to.match(SOURCE_MAP_REGEXP)\n\n done()\n })\n })\n })\n})\n"]} \ No newline at end of file diff --git a/node_modules/ts-node/node_modules/minimist/.travis.yml b/node_modules/ts-node/node_modules/minimist/.travis.yml new file mode 100644 index 0000000..74c57bf --- /dev/null +++ b/node_modules/ts-node/node_modules/minimist/.travis.yml @@ -0,0 +1,8 @@ +language: node_js +node_js: + - "0.8" + - "0.10" + - "0.12" + - "iojs" +before_install: + - npm install -g npm@~1.4.6 diff --git a/node_modules/ts-node/node_modules/minimist/LICENSE b/node_modules/ts-node/node_modules/minimist/LICENSE new file mode 100644 index 0000000..ee27ba4 --- /dev/null +++ b/node_modules/ts-node/node_modules/minimist/LICENSE @@ -0,0 +1,18 @@ +This software is released under the MIT license: + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/ts-node/node_modules/minimist/example/parse.js b/node_modules/ts-node/node_modules/minimist/example/parse.js new file mode 100644 index 0000000..abff3e8 --- /dev/null +++ b/node_modules/ts-node/node_modules/minimist/example/parse.js @@ -0,0 +1,2 @@ +var argv = require('../')(process.argv.slice(2)); +console.dir(argv); diff --git a/node_modules/ts-node/node_modules/minimist/index.js b/node_modules/ts-node/node_modules/minimist/index.js new file mode 100644 index 0000000..6a0559d --- /dev/null +++ b/node_modules/ts-node/node_modules/minimist/index.js @@ -0,0 +1,236 @@ +module.exports = function (args, opts) { + if (!opts) opts = {}; + + var flags = { bools : {}, strings : {}, unknownFn: null }; + + if (typeof opts['unknown'] === 'function') { + flags.unknownFn = opts['unknown']; + } + + if (typeof opts['boolean'] === 'boolean' && opts['boolean']) { + flags.allBools = true; + } else { + [].concat(opts['boolean']).filter(Boolean).forEach(function (key) { + flags.bools[key] = true; + }); + } + + var aliases = {}; + Object.keys(opts.alias || {}).forEach(function (key) { + aliases[key] = [].concat(opts.alias[key]); + aliases[key].forEach(function (x) { + aliases[x] = [key].concat(aliases[key].filter(function (y) { + return x !== y; + })); + }); + }); + + [].concat(opts.string).filter(Boolean).forEach(function (key) { + flags.strings[key] = true; + if (aliases[key]) { + flags.strings[aliases[key]] = true; + } + }); + + var defaults = opts['default'] || {}; + + var argv = { _ : [] }; + Object.keys(flags.bools).forEach(function (key) { + setArg(key, defaults[key] === undefined ? false : defaults[key]); + }); + + var notFlags = []; + + if (args.indexOf('--') !== -1) { + notFlags = args.slice(args.indexOf('--')+1); + args = args.slice(0, args.indexOf('--')); + } + + function argDefined(key, arg) { + return (flags.allBools && /^--[^=]+$/.test(arg)) || + flags.strings[key] || flags.bools[key] || aliases[key]; + } + + function setArg (key, val, arg) { + if (arg && flags.unknownFn && !argDefined(key, arg)) { + if (flags.unknownFn(arg) === false) return; + } + + var value = !flags.strings[key] && isNumber(val) + ? Number(val) : val + ; + setKey(argv, key.split('.'), value); + + (aliases[key] || []).forEach(function (x) { + setKey(argv, x.split('.'), value); + }); + } + + function setKey (obj, keys, value) { + var o = obj; + keys.slice(0,-1).forEach(function (key) { + if (o[key] === undefined) o[key] = {}; + o = o[key]; + }); + + var key = keys[keys.length - 1]; + if (o[key] === undefined || flags.bools[key] || typeof o[key] === 'boolean') { + o[key] = value; + } + else if (Array.isArray(o[key])) { + o[key].push(value); + } + else { + o[key] = [ o[key], value ]; + } + } + + function aliasIsBoolean(key) { + return aliases[key].some(function (x) { + return flags.bools[x]; + }); + } + + for (var i = 0; i < args.length; i++) { + var arg = args[i]; + + if (/^--.+=/.test(arg)) { + // Using [\s\S] instead of . because js doesn't support the + // 'dotall' regex modifier. See: + // http://stackoverflow.com/a/1068308/13216 + var m = arg.match(/^--([^=]+)=([\s\S]*)$/); + var key = m[1]; + var value = m[2]; + if (flags.bools[key]) { + value = value !== 'false'; + } + setArg(key, value, arg); + } + else if (/^--no-.+/.test(arg)) { + var key = arg.match(/^--no-(.+)/)[1]; + setArg(key, false, arg); + } + else if (/^--.+/.test(arg)) { + var key = arg.match(/^--(.+)/)[1]; + var next = args[i + 1]; + if (next !== undefined && !/^-/.test(next) + && !flags.bools[key] + && !flags.allBools + && (aliases[key] ? !aliasIsBoolean(key) : true)) { + setArg(key, next, arg); + i++; + } + else if (/^(true|false)$/.test(next)) { + setArg(key, next === 'true', arg); + i++; + } + else { + setArg(key, flags.strings[key] ? '' : true, arg); + } + } + else if (/^-[^-]+/.test(arg)) { + var letters = arg.slice(1,-1).split(''); + + var broken = false; + for (var j = 0; j < letters.length; j++) { + var next = arg.slice(j+2); + + if (next === '-') { + setArg(letters[j], next, arg) + continue; + } + + if (/[A-Za-z]/.test(letters[j]) && /=/.test(next)) { + setArg(letters[j], next.split('=')[1], arg); + broken = true; + break; + } + + if (/[A-Za-z]/.test(letters[j]) + && /-?\d+(\.\d*)?(e-?\d+)?$/.test(next)) { + setArg(letters[j], next, arg); + broken = true; + break; + } + + if (letters[j+1] && letters[j+1].match(/\W/)) { + setArg(letters[j], arg.slice(j+2), arg); + broken = true; + break; + } + else { + setArg(letters[j], flags.strings[letters[j]] ? '' : true, arg); + } + } + + var key = arg.slice(-1)[0]; + if (!broken && key !== '-') { + if (args[i+1] && !/^(-|--)[^-]/.test(args[i+1]) + && !flags.bools[key] + && (aliases[key] ? !aliasIsBoolean(key) : true)) { + setArg(key, args[i+1], arg); + i++; + } + else if (args[i+1] && /true|false/.test(args[i+1])) { + setArg(key, args[i+1] === 'true', arg); + i++; + } + else { + setArg(key, flags.strings[key] ? '' : true, arg); + } + } + } + else { + if (!flags.unknownFn || flags.unknownFn(arg) !== false) { + argv._.push( + flags.strings['_'] || !isNumber(arg) ? arg : Number(arg) + ); + } + if (opts.stopEarly) { + argv._.push.apply(argv._, args.slice(i + 1)); + break; + } + } + } + + Object.keys(defaults).forEach(function (key) { + if (!hasKey(argv, key.split('.'))) { + setKey(argv, key.split('.'), defaults[key]); + + (aliases[key] || []).forEach(function (x) { + setKey(argv, x.split('.'), defaults[key]); + }); + } + }); + + if (opts['--']) { + argv['--'] = new Array(); + notFlags.forEach(function(key) { + argv['--'].push(key); + }); + } + else { + notFlags.forEach(function(key) { + argv._.push(key); + }); + } + + return argv; +}; + +function hasKey (obj, keys) { + var o = obj; + keys.slice(0,-1).forEach(function (key) { + o = (o[key] || {}); + }); + + var key = keys[keys.length - 1]; + return key in o; +} + +function isNumber (x) { + if (typeof x === 'number') return true; + if (/^0x[0-9a-f]+$/i.test(x)) return true; + return /^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x); +} + diff --git a/node_modules/ts-node/node_modules/minimist/package.json b/node_modules/ts-node/node_modules/minimist/package.json new file mode 100644 index 0000000..a621195 --- /dev/null +++ b/node_modules/ts-node/node_modules/minimist/package.json @@ -0,0 +1,73 @@ +{ + "_from": "minimist@^1.2.0", + "_id": "minimist@1.2.0", + "_inBundle": false, + "_integrity": "sha1-o1AIsg9BOD7sH7kU9M1d95omQoQ=", + "_location": "/ts-node/minimist", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "minimist@^1.2.0", + "name": "minimist", + "escapedName": "minimist", + "rawSpec": "^1.2.0", + "saveSpec": null, + "fetchSpec": "^1.2.0" + }, + "_requiredBy": [ + "/ts-node" + ], + "_resolved": "http://registry.npmjs.org/minimist/-/minimist-1.2.0.tgz", + "_shasum": "a35008b20f41383eec1fb914f4cd5df79a264284", + "_spec": "minimist@^1.2.0", + "_where": "/Users/jessitron/code/jessitron/stringify-tree/node_modules/ts-node", + "author": { + "name": "James Halliday", + "email": "mail@substack.net", + "url": "http://substack.net" + }, + "bugs": { + "url": "https://github.com/substack/minimist/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "parse argument options", + "devDependencies": { + "covert": "^1.0.0", + "tap": "~0.4.0", + "tape": "^3.5.0" + }, + "homepage": "https://github.com/substack/minimist", + "keywords": [ + "argv", + "getopt", + "parser", + "optimist" + ], + "license": "MIT", + "main": "index.js", + "name": "minimist", + "repository": { + "type": "git", + "url": "git://github.com/substack/minimist.git" + }, + "scripts": { + "coverage": "covert test/*.js", + "test": "tap test/*.js" + }, + "testling": { + "files": "test/*.js", + "browsers": [ + "ie/6..latest", + "ff/5", + "firefox/latest", + "chrome/10", + "chrome/latest", + "safari/5.1", + "safari/latest", + "opera/12" + ] + }, + "version": "1.2.0" +} diff --git a/node_modules/ts-node/node_modules/minimist/readme.markdown b/node_modules/ts-node/node_modules/minimist/readme.markdown new file mode 100644 index 0000000..30a74cf --- /dev/null +++ b/node_modules/ts-node/node_modules/minimist/readme.markdown @@ -0,0 +1,91 @@ +# minimist + +parse argument options + +This module is the guts of optimist's argument parser without all the +fanciful decoration. + +[![browser support](https://ci.testling.com/substack/minimist.png)](http://ci.testling.com/substack/minimist) + +[![build status](https://secure.travis-ci.org/substack/minimist.png)](http://travis-ci.org/substack/minimist) + +# example + +``` js +var argv = require('minimist')(process.argv.slice(2)); +console.dir(argv); +``` + +``` +$ node example/parse.js -a beep -b boop +{ _: [], a: 'beep', b: 'boop' } +``` + +``` +$ node example/parse.js -x 3 -y 4 -n5 -abc --beep=boop foo bar baz +{ _: [ 'foo', 'bar', 'baz' ], + x: 3, + y: 4, + n: 5, + a: true, + b: true, + c: true, + beep: 'boop' } +``` + +# methods + +``` js +var parseArgs = require('minimist') +``` + +## var argv = parseArgs(args, opts={}) + +Return an argument object `argv` populated with the array arguments from `args`. + +`argv._` contains all the arguments that didn't have an option associated with +them. + +Numeric-looking arguments will be returned as numbers unless `opts.string` or +`opts.boolean` is set for that argument name. + +Any arguments after `'--'` will not be parsed and will end up in `argv._`. + +options can be: + +* `opts.string` - a string or array of strings argument names to always treat as +strings +* `opts.boolean` - a boolean, string or array of strings to always treat as +booleans. if `true` will treat all double hyphenated arguments without equal signs +as boolean (e.g. affects `--foo`, not `-f` or `--foo=bar`) +* `opts.alias` - an object mapping string names to strings or arrays of string +argument names to use as aliases +* `opts.default` - an object mapping string argument names to default values +* `opts.stopEarly` - when true, populate `argv._` with everything after the +first non-option +* `opts['--']` - when true, populate `argv._` with everything before the `--` +and `argv['--']` with everything after the `--`. Here's an example: +* `opts.unknown` - a function which is invoked with a command line parameter not +defined in the `opts` configuration object. If the function returns `false`, the +unknown option is not added to `argv`. + +``` +> require('./')('one two three -- four five --six'.split(' '), { '--': true }) +{ _: [ 'one', 'two', 'three' ], + '--': [ 'four', 'five', '--six' ] } +``` + +Note that with `opts['--']` set, parsing for arguments still stops after the +`--`. + +# install + +With [npm](https://npmjs.org) do: + +``` +npm install minimist +``` + +# license + +MIT diff --git a/node_modules/ts-node/node_modules/minimist/test/all_bool.js b/node_modules/ts-node/node_modules/minimist/test/all_bool.js new file mode 100644 index 0000000..ac83548 --- /dev/null +++ b/node_modules/ts-node/node_modules/minimist/test/all_bool.js @@ -0,0 +1,32 @@ +var parse = require('../'); +var test = require('tape'); + +test('flag boolean true (default all --args to boolean)', function (t) { + var argv = parse(['moo', '--honk', 'cow'], { + boolean: true + }); + + t.deepEqual(argv, { + honk: true, + _: ['moo', 'cow'] + }); + + t.deepEqual(typeof argv.honk, 'boolean'); + t.end(); +}); + +test('flag boolean true only affects double hyphen arguments without equals signs', function (t) { + var argv = parse(['moo', '--honk', 'cow', '-p', '55', '--tacos=good'], { + boolean: true + }); + + t.deepEqual(argv, { + honk: true, + tacos: 'good', + p: 55, + _: ['moo', 'cow'] + }); + + t.deepEqual(typeof argv.honk, 'boolean'); + t.end(); +}); diff --git a/node_modules/ts-node/node_modules/minimist/test/bool.js b/node_modules/ts-node/node_modules/minimist/test/bool.js new file mode 100644 index 0000000..14b0717 --- /dev/null +++ b/node_modules/ts-node/node_modules/minimist/test/bool.js @@ -0,0 +1,166 @@ +var parse = require('../'); +var test = require('tape'); + +test('flag boolean default false', function (t) { + var argv = parse(['moo'], { + boolean: ['t', 'verbose'], + default: { verbose: false, t: false } + }); + + t.deepEqual(argv, { + verbose: false, + t: false, + _: ['moo'] + }); + + t.deepEqual(typeof argv.verbose, 'boolean'); + t.deepEqual(typeof argv.t, 'boolean'); + t.end(); + +}); + +test('boolean groups', function (t) { + var argv = parse([ '-x', '-z', 'one', 'two', 'three' ], { + boolean: ['x','y','z'] + }); + + t.deepEqual(argv, { + x : true, + y : false, + z : true, + _ : [ 'one', 'two', 'three' ] + }); + + t.deepEqual(typeof argv.x, 'boolean'); + t.deepEqual(typeof argv.y, 'boolean'); + t.deepEqual(typeof argv.z, 'boolean'); + t.end(); +}); +test('boolean and alias with chainable api', function (t) { + var aliased = [ '-h', 'derp' ]; + var regular = [ '--herp', 'derp' ]; + var opts = { + herp: { alias: 'h', boolean: true } + }; + var aliasedArgv = parse(aliased, { + boolean: 'herp', + alias: { h: 'herp' } + }); + var propertyArgv = parse(regular, { + boolean: 'herp', + alias: { h: 'herp' } + }); + var expected = { + herp: true, + h: true, + '_': [ 'derp' ] + }; + + t.same(aliasedArgv, expected); + t.same(propertyArgv, expected); + t.end(); +}); + +test('boolean and alias with options hash', function (t) { + var aliased = [ '-h', 'derp' ]; + var regular = [ '--herp', 'derp' ]; + var opts = { + alias: { 'h': 'herp' }, + boolean: 'herp' + }; + var aliasedArgv = parse(aliased, opts); + var propertyArgv = parse(regular, opts); + var expected = { + herp: true, + h: true, + '_': [ 'derp' ] + }; + t.same(aliasedArgv, expected); + t.same(propertyArgv, expected); + t.end(); +}); + +test('boolean and alias array with options hash', function (t) { + var aliased = [ '-h', 'derp' ]; + var regular = [ '--herp', 'derp' ]; + var alt = [ '--harp', 'derp' ]; + var opts = { + alias: { 'h': ['herp', 'harp'] }, + boolean: 'h' + }; + var aliasedArgv = parse(aliased, opts); + var propertyArgv = parse(regular, opts); + var altPropertyArgv = parse(alt, opts); + var expected = { + harp: true, + herp: true, + h: true, + '_': [ 'derp' ] + }; + t.same(aliasedArgv, expected); + t.same(propertyArgv, expected); + t.same(altPropertyArgv, expected); + t.end(); +}); + +test('boolean and alias using explicit true', function (t) { + var aliased = [ '-h', 'true' ]; + var regular = [ '--herp', 'true' ]; + var opts = { + alias: { h: 'herp' }, + boolean: 'h' + }; + var aliasedArgv = parse(aliased, opts); + var propertyArgv = parse(regular, opts); + var expected = { + herp: true, + h: true, + '_': [ ] + }; + + t.same(aliasedArgv, expected); + t.same(propertyArgv, expected); + t.end(); +}); + +// regression, see https://github.com/substack/node-optimist/issues/71 +test('boolean and --x=true', function(t) { + var parsed = parse(['--boool', '--other=true'], { + boolean: 'boool' + }); + + t.same(parsed.boool, true); + t.same(parsed.other, 'true'); + + parsed = parse(['--boool', '--other=false'], { + boolean: 'boool' + }); + + t.same(parsed.boool, true); + t.same(parsed.other, 'false'); + t.end(); +}); + +test('boolean --boool=true', function (t) { + var parsed = parse(['--boool=true'], { + default: { + boool: false + }, + boolean: ['boool'] + }); + + t.same(parsed.boool, true); + t.end(); +}); + +test('boolean --boool=false', function (t) { + var parsed = parse(['--boool=false'], { + default: { + boool: true + }, + boolean: ['boool'] + }); + + t.same(parsed.boool, false); + t.end(); +}); diff --git a/node_modules/ts-node/node_modules/minimist/test/dash.js b/node_modules/ts-node/node_modules/minimist/test/dash.js new file mode 100644 index 0000000..5a4fa5b --- /dev/null +++ b/node_modules/ts-node/node_modules/minimist/test/dash.js @@ -0,0 +1,31 @@ +var parse = require('../'); +var test = require('tape'); + +test('-', function (t) { + t.plan(5); + t.deepEqual(parse([ '-n', '-' ]), { n: '-', _: [] }); + t.deepEqual(parse([ '-' ]), { _: [ '-' ] }); + t.deepEqual(parse([ '-f-' ]), { f: '-', _: [] }); + t.deepEqual( + parse([ '-b', '-' ], { boolean: 'b' }), + { b: true, _: [ '-' ] } + ); + t.deepEqual( + parse([ '-s', '-' ], { string: 's' }), + { s: '-', _: [] } + ); +}); + +test('-a -- b', function (t) { + t.plan(3); + t.deepEqual(parse([ '-a', '--', 'b' ]), { a: true, _: [ 'b' ] }); + t.deepEqual(parse([ '--a', '--', 'b' ]), { a: true, _: [ 'b' ] }); + t.deepEqual(parse([ '--a', '--', 'b' ]), { a: true, _: [ 'b' ] }); +}); + +test('move arguments after the -- into their own `--` array', function(t) { + t.plan(1); + t.deepEqual( + parse([ '--name', 'John', 'before', '--', 'after' ], { '--': true }), + { name: 'John', _: [ 'before' ], '--': [ 'after' ] }); +}); diff --git a/node_modules/ts-node/node_modules/minimist/test/default_bool.js b/node_modules/ts-node/node_modules/minimist/test/default_bool.js new file mode 100644 index 0000000..780a311 --- /dev/null +++ b/node_modules/ts-node/node_modules/minimist/test/default_bool.js @@ -0,0 +1,35 @@ +var test = require('tape'); +var parse = require('../'); + +test('boolean default true', function (t) { + var argv = parse([], { + boolean: 'sometrue', + default: { sometrue: true } + }); + t.equal(argv.sometrue, true); + t.end(); +}); + +test('boolean default false', function (t) { + var argv = parse([], { + boolean: 'somefalse', + default: { somefalse: false } + }); + t.equal(argv.somefalse, false); + t.end(); +}); + +test('boolean default to null', function (t) { + var argv = parse([], { + boolean: 'maybe', + default: { maybe: null } + }); + t.equal(argv.maybe, null); + var argv = parse(['--maybe'], { + boolean: 'maybe', + default: { maybe: null } + }); + t.equal(argv.maybe, true); + t.end(); + +}) diff --git a/node_modules/ts-node/node_modules/minimist/test/dotted.js b/node_modules/ts-node/node_modules/minimist/test/dotted.js new file mode 100644 index 0000000..d8b3e85 --- /dev/null +++ b/node_modules/ts-node/node_modules/minimist/test/dotted.js @@ -0,0 +1,22 @@ +var parse = require('../'); +var test = require('tape'); + +test('dotted alias', function (t) { + var argv = parse(['--a.b', '22'], {default: {'a.b': 11}, alias: {'a.b': 'aa.bb'}}); + t.equal(argv.a.b, 22); + t.equal(argv.aa.bb, 22); + t.end(); +}); + +test('dotted default', function (t) { + var argv = parse('', {default: {'a.b': 11}, alias: {'a.b': 'aa.bb'}}); + t.equal(argv.a.b, 11); + t.equal(argv.aa.bb, 11); + t.end(); +}); + +test('dotted default with no alias', function (t) { + var argv = parse('', {default: {'a.b': 11}}); + t.equal(argv.a.b, 11); + t.end(); +}); diff --git a/node_modules/ts-node/node_modules/minimist/test/kv_short.js b/node_modules/ts-node/node_modules/minimist/test/kv_short.js new file mode 100644 index 0000000..f813b30 --- /dev/null +++ b/node_modules/ts-node/node_modules/minimist/test/kv_short.js @@ -0,0 +1,16 @@ +var parse = require('../'); +var test = require('tape'); + +test('short -k=v' , function (t) { + t.plan(1); + + var argv = parse([ '-b=123' ]); + t.deepEqual(argv, { b: 123, _: [] }); +}); + +test('multi short -k=v' , function (t) { + t.plan(1); + + var argv = parse([ '-a=whatever', '-b=robots' ]); + t.deepEqual(argv, { a: 'whatever', b: 'robots', _: [] }); +}); diff --git a/node_modules/ts-node/node_modules/minimist/test/long.js b/node_modules/ts-node/node_modules/minimist/test/long.js new file mode 100644 index 0000000..5d3a1e0 --- /dev/null +++ b/node_modules/ts-node/node_modules/minimist/test/long.js @@ -0,0 +1,31 @@ +var test = require('tape'); +var parse = require('../'); + +test('long opts', function (t) { + t.deepEqual( + parse([ '--bool' ]), + { bool : true, _ : [] }, + 'long boolean' + ); + t.deepEqual( + parse([ '--pow', 'xixxle' ]), + { pow : 'xixxle', _ : [] }, + 'long capture sp' + ); + t.deepEqual( + parse([ '--pow=xixxle' ]), + { pow : 'xixxle', _ : [] }, + 'long capture eq' + ); + t.deepEqual( + parse([ '--host', 'localhost', '--port', '555' ]), + { host : 'localhost', port : 555, _ : [] }, + 'long captures sp' + ); + t.deepEqual( + parse([ '--host=localhost', '--port=555' ]), + { host : 'localhost', port : 555, _ : [] }, + 'long captures eq' + ); + t.end(); +}); diff --git a/node_modules/ts-node/node_modules/minimist/test/num.js b/node_modules/ts-node/node_modules/minimist/test/num.js new file mode 100644 index 0000000..2cc77f4 --- /dev/null +++ b/node_modules/ts-node/node_modules/minimist/test/num.js @@ -0,0 +1,36 @@ +var parse = require('../'); +var test = require('tape'); + +test('nums', function (t) { + var argv = parse([ + '-x', '1234', + '-y', '5.67', + '-z', '1e7', + '-w', '10f', + '--hex', '0xdeadbeef', + '789' + ]); + t.deepEqual(argv, { + x : 1234, + y : 5.67, + z : 1e7, + w : '10f', + hex : 0xdeadbeef, + _ : [ 789 ] + }); + t.deepEqual(typeof argv.x, 'number'); + t.deepEqual(typeof argv.y, 'number'); + t.deepEqual(typeof argv.z, 'number'); + t.deepEqual(typeof argv.w, 'string'); + t.deepEqual(typeof argv.hex, 'number'); + t.deepEqual(typeof argv._[0], 'number'); + t.end(); +}); + +test('already a number', function (t) { + var argv = parse([ '-x', 1234, 789 ]); + t.deepEqual(argv, { x : 1234, _ : [ 789 ] }); + t.deepEqual(typeof argv.x, 'number'); + t.deepEqual(typeof argv._[0], 'number'); + t.end(); +}); diff --git a/node_modules/ts-node/node_modules/minimist/test/parse.js b/node_modules/ts-node/node_modules/minimist/test/parse.js new file mode 100644 index 0000000..7b4a2a1 --- /dev/null +++ b/node_modules/ts-node/node_modules/minimist/test/parse.js @@ -0,0 +1,197 @@ +var parse = require('../'); +var test = require('tape'); + +test('parse args', function (t) { + t.deepEqual( + parse([ '--no-moo' ]), + { moo : false, _ : [] }, + 'no' + ); + t.deepEqual( + parse([ '-v', 'a', '-v', 'b', '-v', 'c' ]), + { v : ['a','b','c'], _ : [] }, + 'multi' + ); + t.end(); +}); + +test('comprehensive', function (t) { + t.deepEqual( + parse([ + '--name=meowmers', 'bare', '-cats', 'woo', + '-h', 'awesome', '--multi=quux', + '--key', 'value', + '-b', '--bool', '--no-meep', '--multi=baz', + '--', '--not-a-flag', 'eek' + ]), + { + c : true, + a : true, + t : true, + s : 'woo', + h : 'awesome', + b : true, + bool : true, + key : 'value', + multi : [ 'quux', 'baz' ], + meep : false, + name : 'meowmers', + _ : [ 'bare', '--not-a-flag', 'eek' ] + } + ); + t.end(); +}); + +test('flag boolean', function (t) { + var argv = parse([ '-t', 'moo' ], { boolean: 't' }); + t.deepEqual(argv, { t : true, _ : [ 'moo' ] }); + t.deepEqual(typeof argv.t, 'boolean'); + t.end(); +}); + +test('flag boolean value', function (t) { + var argv = parse(['--verbose', 'false', 'moo', '-t', 'true'], { + boolean: [ 't', 'verbose' ], + default: { verbose: true } + }); + + t.deepEqual(argv, { + verbose: false, + t: true, + _: ['moo'] + }); + + t.deepEqual(typeof argv.verbose, 'boolean'); + t.deepEqual(typeof argv.t, 'boolean'); + t.end(); +}); + +test('newlines in params' , function (t) { + var args = parse([ '-s', "X\nX" ]) + t.deepEqual(args, { _ : [], s : "X\nX" }); + + // reproduce in bash: + // VALUE="new + // line" + // node program.js --s="$VALUE" + args = parse([ "--s=X\nX" ]) + t.deepEqual(args, { _ : [], s : "X\nX" }); + t.end(); +}); + +test('strings' , function (t) { + var s = parse([ '-s', '0001234' ], { string: 's' }).s; + t.equal(s, '0001234'); + t.equal(typeof s, 'string'); + + var x = parse([ '-x', '56' ], { string: 'x' }).x; + t.equal(x, '56'); + t.equal(typeof x, 'string'); + t.end(); +}); + +test('stringArgs', function (t) { + var s = parse([ ' ', ' ' ], { string: '_' })._; + t.same(s.length, 2); + t.same(typeof s[0], 'string'); + t.same(s[0], ' '); + t.same(typeof s[1], 'string'); + t.same(s[1], ' '); + t.end(); +}); + +test('empty strings', function(t) { + var s = parse([ '-s' ], { string: 's' }).s; + t.equal(s, ''); + t.equal(typeof s, 'string'); + + var str = parse([ '--str' ], { string: 'str' }).str; + t.equal(str, ''); + t.equal(typeof str, 'string'); + + var letters = parse([ '-art' ], { + string: [ 'a', 't' ] + }); + + t.equal(letters.a, ''); + t.equal(letters.r, true); + t.equal(letters.t, ''); + + t.end(); +}); + + +test('string and alias', function(t) { + var x = parse([ '--str', '000123' ], { + string: 's', + alias: { s: 'str' } + }); + + t.equal(x.str, '000123'); + t.equal(typeof x.str, 'string'); + t.equal(x.s, '000123'); + t.equal(typeof x.s, 'string'); + + var y = parse([ '-s', '000123' ], { + string: 'str', + alias: { str: 's' } + }); + + t.equal(y.str, '000123'); + t.equal(typeof y.str, 'string'); + t.equal(y.s, '000123'); + t.equal(typeof y.s, 'string'); + t.end(); +}); + +test('slashBreak', function (t) { + t.same( + parse([ '-I/foo/bar/baz' ]), + { I : '/foo/bar/baz', _ : [] } + ); + t.same( + parse([ '-xyz/foo/bar/baz' ]), + { x : true, y : true, z : '/foo/bar/baz', _ : [] } + ); + t.end(); +}); + +test('alias', function (t) { + var argv = parse([ '-f', '11', '--zoom', '55' ], { + alias: { z: 'zoom' } + }); + t.equal(argv.zoom, 55); + t.equal(argv.z, argv.zoom); + t.equal(argv.f, 11); + t.end(); +}); + +test('multiAlias', function (t) { + var argv = parse([ '-f', '11', '--zoom', '55' ], { + alias: { z: [ 'zm', 'zoom' ] } + }); + t.equal(argv.zoom, 55); + t.equal(argv.z, argv.zoom); + t.equal(argv.z, argv.zm); + t.equal(argv.f, 11); + t.end(); +}); + +test('nested dotted objects', function (t) { + var argv = parse([ + '--foo.bar', '3', '--foo.baz', '4', + '--foo.quux.quibble', '5', '--foo.quux.o_O', + '--beep.boop' + ]); + + t.same(argv.foo, { + bar : 3, + baz : 4, + quux : { + quibble : 5, + o_O : true + } + }); + t.same(argv.beep, { boop : true }); + t.end(); +}); diff --git a/node_modules/ts-node/node_modules/minimist/test/parse_modified.js b/node_modules/ts-node/node_modules/minimist/test/parse_modified.js new file mode 100644 index 0000000..ab620dc --- /dev/null +++ b/node_modules/ts-node/node_modules/minimist/test/parse_modified.js @@ -0,0 +1,9 @@ +var parse = require('../'); +var test = require('tape'); + +test('parse with modifier functions' , function (t) { + t.plan(1); + + var argv = parse([ '-b', '123' ], { boolean: 'b' }); + t.deepEqual(argv, { b: true, _: [123] }); +}); diff --git a/node_modules/ts-node/node_modules/minimist/test/short.js b/node_modules/ts-node/node_modules/minimist/test/short.js new file mode 100644 index 0000000..d513a1c --- /dev/null +++ b/node_modules/ts-node/node_modules/minimist/test/short.js @@ -0,0 +1,67 @@ +var parse = require('../'); +var test = require('tape'); + +test('numeric short args', function (t) { + t.plan(2); + t.deepEqual(parse([ '-n123' ]), { n: 123, _: [] }); + t.deepEqual( + parse([ '-123', '456' ]), + { 1: true, 2: true, 3: 456, _: [] } + ); +}); + +test('short', function (t) { + t.deepEqual( + parse([ '-b' ]), + { b : true, _ : [] }, + 'short boolean' + ); + t.deepEqual( + parse([ 'foo', 'bar', 'baz' ]), + { _ : [ 'foo', 'bar', 'baz' ] }, + 'bare' + ); + t.deepEqual( + parse([ '-cats' ]), + { c : true, a : true, t : true, s : true, _ : [] }, + 'group' + ); + t.deepEqual( + parse([ '-cats', 'meow' ]), + { c : true, a : true, t : true, s : 'meow', _ : [] }, + 'short group next' + ); + t.deepEqual( + parse([ '-h', 'localhost' ]), + { h : 'localhost', _ : [] }, + 'short capture' + ); + t.deepEqual( + parse([ '-h', 'localhost', '-p', '555' ]), + { h : 'localhost', p : 555, _ : [] }, + 'short captures' + ); + t.end(); +}); + +test('mixed short bool and capture', function (t) { + t.same( + parse([ '-h', 'localhost', '-fp', '555', 'script.js' ]), + { + f : true, p : 555, h : 'localhost', + _ : [ 'script.js' ] + } + ); + t.end(); +}); + +test('short and long', function (t) { + t.deepEqual( + parse([ '-h', 'localhost', '-fp', '555', 'script.js' ]), + { + f : true, p : 555, h : 'localhost', + _ : [ 'script.js' ] + } + ); + t.end(); +}); diff --git a/node_modules/ts-node/node_modules/minimist/test/stop_early.js b/node_modules/ts-node/node_modules/minimist/test/stop_early.js new file mode 100644 index 0000000..bdf9fbc --- /dev/null +++ b/node_modules/ts-node/node_modules/minimist/test/stop_early.js @@ -0,0 +1,15 @@ +var parse = require('../'); +var test = require('tape'); + +test('stops parsing on the first non-option when stopEarly is set', function (t) { + var argv = parse(['--aaa', 'bbb', 'ccc', '--ddd'], { + stopEarly: true + }); + + t.deepEqual(argv, { + aaa: 'bbb', + _: ['ccc', '--ddd'] + }); + + t.end(); +}); diff --git a/node_modules/ts-node/node_modules/minimist/test/unknown.js b/node_modules/ts-node/node_modules/minimist/test/unknown.js new file mode 100644 index 0000000..462a36b --- /dev/null +++ b/node_modules/ts-node/node_modules/minimist/test/unknown.js @@ -0,0 +1,102 @@ +var parse = require('../'); +var test = require('tape'); + +test('boolean and alias is not unknown', function (t) { + var unknown = []; + function unknownFn(arg) { + unknown.push(arg); + return false; + } + var aliased = [ '-h', 'true', '--derp', 'true' ]; + var regular = [ '--herp', 'true', '-d', 'true' ]; + var opts = { + alias: { h: 'herp' }, + boolean: 'h', + unknown: unknownFn + }; + var aliasedArgv = parse(aliased, opts); + var propertyArgv = parse(regular, opts); + + t.same(unknown, ['--derp', '-d']); + t.end(); +}); + +test('flag boolean true any double hyphen argument is not unknown', function (t) { + var unknown = []; + function unknownFn(arg) { + unknown.push(arg); + return false; + } + var argv = parse(['--honk', '--tacos=good', 'cow', '-p', '55'], { + boolean: true, + unknown: unknownFn + }); + t.same(unknown, ['--tacos=good', 'cow', '-p']); + t.same(argv, { + honk: true, + _: [] + }); + t.end(); +}); + +test('string and alias is not unknown', function (t) { + var unknown = []; + function unknownFn(arg) { + unknown.push(arg); + return false; + } + var aliased = [ '-h', 'hello', '--derp', 'goodbye' ]; + var regular = [ '--herp', 'hello', '-d', 'moon' ]; + var opts = { + alias: { h: 'herp' }, + string: 'h', + unknown: unknownFn + }; + var aliasedArgv = parse(aliased, opts); + var propertyArgv = parse(regular, opts); + + t.same(unknown, ['--derp', '-d']); + t.end(); +}); + +test('default and alias is not unknown', function (t) { + var unknown = []; + function unknownFn(arg) { + unknown.push(arg); + return false; + } + var aliased = [ '-h', 'hello' ]; + var regular = [ '--herp', 'hello' ]; + var opts = { + default: { 'h': 'bar' }, + alias: { 'h': 'herp' }, + unknown: unknownFn + }; + var aliasedArgv = parse(aliased, opts); + var propertyArgv = parse(regular, opts); + + t.same(unknown, []); + t.end(); + unknownFn(); // exercise fn for 100% coverage +}); + +test('value following -- is not unknown', function (t) { + var unknown = []; + function unknownFn(arg) { + unknown.push(arg); + return false; + } + var aliased = [ '--bad', '--', 'good', 'arg' ]; + var opts = { + '--': true, + unknown: unknownFn + }; + var argv = parse(aliased, opts); + + t.same(unknown, ['--bad']); + t.same(argv, { + '--': ['good', 'arg'], + '_': [] + }) + t.end(); +}); diff --git a/node_modules/ts-node/node_modules/minimist/test/whitespace.js b/node_modules/ts-node/node_modules/minimist/test/whitespace.js new file mode 100644 index 0000000..8a52a58 --- /dev/null +++ b/node_modules/ts-node/node_modules/minimist/test/whitespace.js @@ -0,0 +1,8 @@ +var parse = require('../'); +var test = require('tape'); + +test('whitespace should be whitespace' , function (t) { + t.plan(1); + var x = parse([ '-x', '\t' ]).x; + t.equal(x, '\t'); +}); diff --git a/node_modules/ts-node/package.json b/node_modules/ts-node/package.json new file mode 100644 index 0000000..8dea527 --- /dev/null +++ b/node_modules/ts-node/package.json @@ -0,0 +1,112 @@ +{ + "_from": "ts-node", + "_id": "ts-node@7.0.1", + "_inBundle": false, + "_integrity": "sha512-BVwVbPJRspzNh2yfslyT1PSbl5uIk03EZlb493RKHN4qej/D06n1cEhjlOJG69oFsE7OT8XjpTUcYf6pKTLMhw==", + "_location": "/ts-node", + "_phantomChildren": {}, + "_requested": { + "type": "tag", + "registry": true, + "raw": "ts-node", + "name": "ts-node", + "escapedName": "ts-node", + "rawSpec": "", + "saveSpec": null, + "fetchSpec": "latest" + }, + "_requiredBy": [ + "#DEV:/", + "#USER" + ], + "_resolved": "https://registry.npmjs.org/ts-node/-/ts-node-7.0.1.tgz", + "_shasum": "9562dc2d1e6d248d24bc55f773e3f614337d9baf", + "_spec": "ts-node", + "_where": "/Users/jessitron/code/jessitron/stringify-tree", + "author": { + "name": "Blake Embrey", + "email": "hello@blakeembrey.com", + "url": "http://blakeembrey.me" + }, + "bin": { + "ts-node": "dist/bin.js" + }, + "bugs": { + "url": "https://github.com/TypeStrong/ts-node/issues" + }, + "bundleDependencies": false, + "dependencies": { + "arrify": "^1.0.0", + "buffer-from": "^1.1.0", + "diff": "^3.1.0", + "make-error": "^1.1.1", + "minimist": "^1.2.0", + "mkdirp": "^0.5.1", + "source-map-support": "^0.5.6", + "yn": "^2.0.0" + }, + "deprecated": false, + "description": "TypeScript execution environment and REPL for node.js, with source map support", + "devDependencies": { + "@types/arrify": "^1.0.1", + "@types/buffer-from": "^1.1.0", + "@types/chai": "^4.0.4", + "@types/diff": "^3.2.1", + "@types/minimist": "^1.2.0", + "@types/mkdirp": "^0.5.0", + "@types/mocha": "^5.0.0", + "@types/node": "^10.0.3", + "@types/proxyquire": "^1.3.28", + "@types/react": "^16.0.2", + "@types/semver": "^5.3.34", + "@types/source-map-support": "^0.4.0", + "@types/yn": "github:types/npm-yn#ca75f6c82940fae6a06fb41d2d37a6aa9b4ea8e9", + "chai": "^4.0.1", + "istanbul": "^0.4.0", + "mocha": "^5.0.1", + "ntypescript": "^1.201507091536.1", + "proxyquire": "^2.0.0", + "react": "^16.0.0", + "rimraf": "^2.5.4", + "semver": "^5.1.0", + "tslint": "^5.0.0", + "tslint-config-standard": "^7.0.0", + "typescript": "^2.8.3" + }, + "engines": { + "node": ">=4.2.0" + }, + "files": [ + "dist/", + "register/", + "LICENSE" + ], + "homepage": "https://github.com/TypeStrong/ts-node", + "keywords": [ + "typescript", + "node", + "runtime", + "environment", + "ts", + "compiler" + ], + "license": "MIT", + "main": "dist/index.js", + "name": "ts-node", + "repository": { + "type": "git", + "url": "git://github.com/TypeStrong/ts-node.git" + }, + "scripts": { + "build": "npm run clean && npm run tsc", + "clean": "rimraf dist", + "lint": "tslint \"src/**/*.ts\" --project tsconfig.json", + "prepublish": "npm run build", + "test": "npm run build && npm run lint && npm run test-cov", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- \"dist/**/*.spec.js\" -R spec --bail", + "test-spec": "mocha dist/**/*.spec.js -R spec --bail", + "tsc": "tsc" + }, + "types": "dist/index.d.ts", + "version": "7.0.1" +} diff --git a/node_modules/ts-node/register/index.js b/node_modules/ts-node/register/index.js new file mode 100644 index 0000000..63ec2ce --- /dev/null +++ b/node_modules/ts-node/register/index.js @@ -0,0 +1 @@ +require('../').register() diff --git a/node_modules/ts-node/register/transpile-only.js b/node_modules/ts-node/register/transpile-only.js new file mode 100644 index 0000000..a42dc27 --- /dev/null +++ b/node_modules/ts-node/register/transpile-only.js @@ -0,0 +1,3 @@ +require('../').register({ + transpileOnly: true +}) diff --git a/node_modules/ts-node/register/type-check.js b/node_modules/ts-node/register/type-check.js new file mode 100644 index 0000000..08b4102 --- /dev/null +++ b/node_modules/ts-node/register/type-check.js @@ -0,0 +1,3 @@ +require('../').register({ + typeCheck: true +}) diff --git a/node_modules/typescript/.failed-tests b/node_modules/typescript/.failed-tests new file mode 100644 index 0000000..655db24 --- /dev/null +++ b/node_modules/typescript/.failed-tests @@ -0,0 +1,3 @@ +compiler tests compiler tests for tests/cases/compiler/unionTypeWithRecursiveSubtypeReduction2.ts Correct errors for tests/cases/compiler/unionTypeWithRecursiveSubtypeReduction2.ts +conformance tests conformance tests for tests/cases/conformance/types/intersection/intersectionAndUnionTypes.ts Correct errors for tests/cases/conformance/types/intersection/intersectionAndUnionTypes.ts +conformance tests conformance tests for tests/cases/conformance/types/union/contextualTypeWithUnionTypeObjectLiteral.ts Correct errors for tests/cases/conformance/types/union/contextualTypeWithUnionTypeObjectLiteral.ts \ No newline at end of file diff --git a/node_modules/typescript/AUTHORS.md b/node_modules/typescript/AUTHORS.md new file mode 100644 index 0000000..1c565ba --- /dev/null +++ b/node_modules/typescript/AUTHORS.md @@ -0,0 +1,349 @@ +TypeScript is authored by: +* Aaron Holmes +* Abubaker Bashir +* Adam Freidin +* Adi Dahiya +* Aditya Daflapurkar +* Adnan Chowdhury +* Adrian Leonhard +* Adrien Gibrat +* Ahmad Farid +* Akshar Patel +* Alan Agius +* Alex Chugaev +* Alex Eagle +* Alex Khomchenko +* Alex Ryan +* Alexander Kuvaev +* Alexander Rusakov +* Alexander Tarasyuk +* Ali Sabzevari +* Aliaksandr Radzivanovich +* Aluan Haddad +* Anatoly Ressin +* Anders Hejlsberg +* Andreas Martin +* Andrej Baran +* Andrew Casey +* Andrew Faulkner +* Andrew Ochsner +* Andrew Stegmaier +* Andrew Z Allen +* András Parditka +* Andy Hanson +* Anil Anar +* Anton Khlynovskiy +* Anton Tolmachev +* Anubha Mathur +* Armando Aguirre +* Arnaud Tournier +* Arnav Singh +* Artem Tyurin +* Arthur Ozga +* Asad Saeeduddin +* Avery Morin +* Basarat Ali Syed +* @begincalendar +* Ben Duffield +* Ben Mosher +* Benjamin Bock +* Benjamin Lichtman +* Benny Neugebauer +* Bill Ticehurst +* Blaine Bublitz +* Blake Embrey +* @bluelovers +* @bootstraponline +* Bowden Kelly +* Bowden Kenny +* Brandon Slade +* Brett Mayen +* Bryan Forbes +* Caitlin Potter +* Cameron Taggart +* @cedvdb +* Charles Pierce +* Charly POLY +* Chris Bubernak +* Christophe Vidal +* Chuck Jazdzewski +* Colby Russell +* Colin Snover +* Cotton Hou +* Cyrus Najmabadi +* Dafrok Zhang +* Dahan Gong +* Dan Corder +* Dan Freeman +* Dan Quirk +* Daniel Gooss +* Daniel Hollocher +* Daniel Król +* Daniel Lehenbauer +* Daniel Rosenwasser +* David Kmenta +* David Li +* David Sheldrick +* David Sherret +* David Souther +* David Staheli +* Denis Nedelyaev +* Derek P Sifford +* Dhruv Rajvanshi +* Dick van den Brink +* Diogo Franco (Kovensky) +* Dirk Bäumer +* Dirk Holtwick +* Dom Chen +* Donald Pipowitch +* Doug Ilijev +* @e-cloud +* Ecole Keine +* Elisée Maurer +* Elizabeth Dinella +* Emilio García-Pumarino +* Eric Grube +* Eric Tsang +* Erik Edrosa +* Erik McClenney +* Esakki Raj +* Ethan Resnick +* Ethan Rubio +* Eugene Timokhov +* Evan Martin +* Evan Sebastian +* Eyas Sharaiha +* Fabian Cook +* @falsandtru +* Filipe Silva +* @flowmemo +* Francois Wouts +* Frank Wallis +* Franklin Tse +* František Žiacik +* Gabe Moothart +* Gabriel Isenberg +* Gilad Peleg +* Godfrey Chan +* Graeme Wicksted +* Guilherme Oenning +* Guillaume Salles +* Guy Bedford +* Halasi Tamás +* Harald Niesche +* Hendrik Liebau +* Henry Mercer +* Herrington Darkholme +* Holger Jeromin +* Homa Wong +* Iain Monro +* @IdeaHunter +* Igor Novozhilov +* Ika +* Ingvar Stepanyan +* Isiah Meadows +* Ivan Enderlin +* Ivo Gabe de Wolff +* Iwata Hidetaka +* Jack Williams +* Jakub Korzeniowski +* Jakub Młokosiewicz +* James Henry +* James Whitney +* Jan Melcher +* Jason Freeman +* Jason Jarrett +* Jason Killian +* Jason Ramsay +* JBerger +* Jed Mao +* Jeffrey Morlan +* Jesse Schalken +* Jing Ma +* Jiri Tobisek +* Joe Calzaretta +* Joe Chung +* Joel Day +* Joey Wilson +* Johannes Rieken +* John Doe +* John Vilk +* Jonathan Bond-Caron +* Jonathan Park +* Jonathan Toland +* Jonathan Turner +* Jonathon Smith +* Jordi Oliveras Rovira +* Joscha Feth +* Josh Abernathy +* Josh Goldberg +* Josh Kalderimis +* Josh Soref +* Juan Luis Boya García +* Julian Williams +* Justin Bay +* Justin Johansson +* K. Preißer +* Kagami Sascha Rosylight +* Kanchalai Tanglertsampan +* Kate Miháliková +* Keith Mashinter +* Ken Howard +* Kenji Imamula +* Kerem Kat +* Kevin Donnelly +* Kevin Gibbons +* Kevin Lang +* Khải +* Kitson Kelly +* Klaus Meinhardt +* Kris Zyp +* Kyle Kelley +* Kārlis Gaņģis +* Lorant Pinter +* Lucien Greathouse +* Lukas Elmer +* Maarten Sijm +* Magnus Hiie +* Magnus Kulke +* Manish Giri +* Marin Marinov +* Marius Schulz +* Markus Johnsson +* Martin Hiller +* Martin Probst +* Martin Vseticka +* Martyn Janes +* Masahiro Wakame +* Mateusz Burzyński +* Matt Bierner +* Matt McCutchen +* Matt Mitchell +* Mattias Buelens +* Mattias Buelens +* Max Deepfield +* Maxwell Paul Brickner +* @meyer +* Micah Zoltu +* @micbou +* Michael +* Michael Bromley +* Mike Busyrev +* Mike Morearty +* Mine Starks +* Mohamed Hegazy +* Mohsen Azimi +* Myles Megyesi +* Nathan Shively-Sanders +* Nathan Yee +* Nicolas Henry +* Nicu Micleușanu +* @nieltg +* Nima Zahedi +* Noah Chen +* Noel Varanda +* Noj Vek +* Oleg Mihailik +* Oleksandr Chekhovskyi +* Omer Sheikh +* Orta Therox +* Oskar Segersva¨rd +* Oussama Ben Brahim +* Patrick Zhong +* Paul Jolly +* Paul Koerbitz +* Paul van Brenk +* @pcbro +* Pedro Maltez +* Perry Jiang +* Peter Burns +* Philip Bulley +* Philippe Voinov +* Pi Lanningham +* Piero Cangianiello +* @piloopin +* Prayag Verma +* Priyantha Lankapura +* @progre +* Punya Biswal +* Rado Kirov +* Raj Dosanjh +* Reiner Dolp +* Remo H. Jansen +* @rflorian +* @rhysd +* Ricardo N Feliciano +* Richard Karmazín +* Richard Knoll +* Richard Sentino +* Robert Coie +* Rohit Verma +* Ron Buckton +* Rostislav Galimsky +* Rowan Wyborn +* Ryan Cavanaugh +* Ryohei Ikegami +* Sam Bostock +* Sam El-Husseini +* Sarangan Rajamanickam +* Sean Barag +* Sergey Rubanov +* Sergey Shandar +* Sergii Bezliudnyi +* Sharon Rolel +* Sheetal Nandi +* Shengping Zhong +* Shyyko Serhiy +* Simon Hürlimann +* Slawomir Sadziak +* Solal Pirelli +* Soo Jae Hwang +* Stan Thomas +* Stanislav Iliev +* Stanislav Sysoev +* Stas Vilchik +* Stephan Ginthör +* Steve Lucco +* @styfle +* Sudheesh Singanamalla +* Sébastien Arod +* @T18970237136 +* @t_ +* Taras Mankovski +* Tarik Ozket +* Tetsuharu Ohzeki +* Thomas den Hollander +* Thomas Loubiou +* Tien Hoanhtien +* Tim Lancina +* Tim Perry +* Tim Viiding-Spader +* Tingan Ho +* Todd Thomson +* togru +* Tomas Grubliauskas +* Torben Fitschen +* @TravCav +* TruongSinh Tran-Nguyen +* Tycho Grouwstra +* Vadi Taslim +* Vakhurin Sergey +* Vidar Tonaas Fauske +* Viktor Zozulyak +* Vilic Vane +* Vimal Raghubir +* Vladimir Kurchatkin +* Vladimir Matveev +* Vyacheslav Pukhanov +* Wenlu Wang +* Wesley Wigham +* William Orr +* Wilson Hobbs +* York Yao +* @yortus +* Yuichi Nukiyama +* Yuval Greenfield +* Zeeshan Ahmed +* Zev Spitz +* Zhengbo Li +* @Zzzen \ No newline at end of file diff --git a/node_modules/typescript/CODE_OF_CONDUCT.md b/node_modules/typescript/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..65c8a42 --- /dev/null +++ b/node_modules/typescript/CODE_OF_CONDUCT.md @@ -0,0 +1 @@ +This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments. diff --git a/node_modules/typescript/CopyrightNotice.txt b/node_modules/typescript/CopyrightNotice.txt new file mode 100644 index 0000000..884a031 --- /dev/null +++ b/node_modules/typescript/CopyrightNotice.txt @@ -0,0 +1,15 @@ +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + diff --git a/node_modules/typescript/LICENSE.txt b/node_modules/typescript/LICENSE.txt new file mode 100644 index 0000000..8746124 --- /dev/null +++ b/node_modules/typescript/LICENSE.txt @@ -0,0 +1,55 @@ +Apache License + +Version 2.0, January 2004 + +http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + +"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. + +"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. + +"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. + +"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. + +"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. + +"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. + +"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). + +"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. + +"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." + +"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: + +You must give any other recipients of the Work or Derivative Works a copy of this License; and + +You must cause any modified files to carry prominent notices stating that You changed the files; and + +You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and + +If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS diff --git a/node_modules/typescript/README.md b/node_modules/typescript/README.md new file mode 100644 index 0000000..a722266 --- /dev/null +++ b/node_modules/typescript/README.md @@ -0,0 +1,99 @@ +[![Build Status](https://travis-ci.org/Microsoft/TypeScript.svg?branch=master)](https://travis-ci.org/Microsoft/TypeScript) +[![VSTS Build Status](https://typescript.visualstudio.com/_apis/public/build/definitions/cf7ac146-d525-443c-b23c-0d58337efebc/4/badge)](https://typescript.visualstudio.com/TypeScript/_build/latest?definitionId=4&view=logs) +[![npm version](https://badge.fury.io/js/typescript.svg)](https://www.npmjs.com/package/typescript) +[![Downloads](https://img.shields.io/npm/dm/typescript.svg)](https://www.npmjs.com/package/typescript) + +# TypeScript + +[![Join the chat at https://gitter.im/Microsoft/TypeScript](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/Microsoft/TypeScript?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) + +[TypeScript](https://www.typescriptlang.org/) is a language for application-scale JavaScript. TypeScript adds optional types to JavaScript that support tools for large-scale JavaScript applications for any browser, for any host, on any OS. TypeScript compiles to readable, standards-based JavaScript. Try it out at the [playground](https://www.typescriptlang.org/play/), and stay up to date via [our blog](https://blogs.msdn.microsoft.com/typescript) and [Twitter account](https://twitter.com/typescriptlang). + +## Installing + +For the latest stable version: + +```bash +npm install -g typescript +``` + +For our nightly builds: + +```bash +npm install -g typescript@next +``` + +## Contribute + +There are many ways to [contribute](https://github.com/Microsoft/TypeScript/blob/master/CONTRIBUTING.md) to TypeScript. +* [Submit bugs](https://github.com/Microsoft/TypeScript/issues) and help us verify fixes as they are checked in. +* Review the [source code changes](https://github.com/Microsoft/TypeScript/pulls). +* Engage with other TypeScript users and developers on [StackOverflow](https://stackoverflow.com/questions/tagged/typescript). +* Join the [#typescript](https://twitter.com/search?q=%23TypeScript) discussion on Twitter. +* [Contribute bug fixes](https://github.com/Microsoft/TypeScript/blob/master/CONTRIBUTING.md). +* Read the language specification ([docx](https://github.com/Microsoft/TypeScript/blob/master/doc/TypeScript%20Language%20Specification.docx?raw=true), + [pdf](https://github.com/Microsoft/TypeScript/blob/master/doc/TypeScript%20Language%20Specification.pdf?raw=true), [md](https://github.com/Microsoft/TypeScript/blob/master/doc/spec.md)). + +This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more information see +the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) +with any additional questions or comments. + +## Documentation + +* [Quick tutorial](https://www.typescriptlang.org/docs/tutorial.html) +* [Programming handbook](https://www.typescriptlang.org/docs/handbook/basic-types.html) +* [Language specification](https://github.com/Microsoft/TypeScript/blob/master/doc/spec.md) +* [Homepage](https://www.typescriptlang.org/) + +## Building + +In order to build the TypeScript compiler, ensure that you have [Git](https://git-scm.com/downloads) and [Node.js](https://nodejs.org/) installed. + +Clone a copy of the repo: + +```bash +git clone https://github.com/Microsoft/TypeScript.git +``` + +Change to the TypeScript directory: + +```bash +cd TypeScript +``` + +Install [Jake](http://jakejs.com/) tools and dev dependencies: + +```bash +npm install -g jake +npm install +``` + +Use one of the following to build and test: + +``` +jake local # Build the compiler into built/local +jake clean # Delete the built compiler +jake LKG # Replace the last known good with the built one. + # Bootstrapping step to be executed when the built compiler reaches a stable state. +jake tests # Build the test infrastructure using the built compiler. +jake runtests # Run tests using the built compiler and test infrastructure. + # You can override the host or specify a test for this command. + # Use host= or tests=. +jake runtests-browser # Runs the tests using the built run.js file. Syntax is jake runtests. Optional + parameters 'host=', 'tests=[regex], reporter=[list|spec|json|]'. +jake baseline-accept # This replaces the baseline test results with the results obtained from jake runtests. +jake lint # Runs tslint on the TypeScript source. +jake help # List the above commands. +``` + + +## Usage + +```bash +node built/local/tsc.js hello.ts +``` + + +## Roadmap + +For details on our planned features and future direction please refer to our [roadmap](https://github.com/Microsoft/TypeScript/wiki/Roadmap). diff --git a/node_modules/typescript/ThirdPartyNoticeText.txt b/node_modules/typescript/ThirdPartyNoticeText.txt new file mode 100644 index 0000000..26aa57f --- /dev/null +++ b/node_modules/typescript/ThirdPartyNoticeText.txt @@ -0,0 +1,193 @@ +/*!----------------- TypeScript ThirdPartyNotices ------------------------------------------------------- + +The TypeScript software incorporates third party material from the projects listed below. The original copyright notice and the license under which Microsoft received such third party material are set forth below. Microsoft reserves all other rights not expressly granted, whether by implication, estoppel or otherwise. + +--------------------------------------------- +Third Party Code Components +-------------------------------------------- + +------------------- DefinitelyTyped -------------------- +This file is based on or incorporates material from the projects listed below (collectively "Third Party Code"). Microsoft is not the original author of the Third Party Code. The original copyright notice and the license, under which Microsoft received such Third Party Code, are set forth below. Such licenses and notices are provided for informational purposes only. Microsoft, not the third party, licenses the Third Party Code to you under the terms set forth in the EULA for the Microsoft Product. Microsoft reserves all other rights not expressly granted under this agreement, whether by implication, estoppel or otherwise. +DefinitelyTyped +This project is licensed under the MIT license. Copyrights are respective of each contributor listed at the beginning of each definition file. Provided for Informational Purposes Only + +MIT License +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the ""Software""), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +-------------------------------------------------------------------------------------- + +------------------- Unicode -------------------- +UNICODE, INC. LICENSE AGREEMENT - DATA FILES AND SOFTWARE + +Unicode Data Files include all data files under the directories +http://www.unicode.org/Public/, http://www.unicode.org/reports/, +http://www.unicode.org/cldr/data/, http://source.icu-project.org/repos/icu/, and +http://www.unicode.org/utility/trac/browser/. + +Unicode Data Files do not include PDF online code charts under the +directory http://www.unicode.org/Public/. + +Software includes any source code published in the Unicode Standard +or under the directories +http://www.unicode.org/Public/, http://www.unicode.org/reports/, +http://www.unicode.org/cldr/data/, http://source.icu-project.org/repos/icu/, and +http://www.unicode.org/utility/trac/browser/. + +NOTICE TO USER: Carefully read the following legal agreement. +BY DOWNLOADING, INSTALLING, COPYING OR OTHERWISE USING UNICODE INC.'S +DATA FILES ("DATA FILES"), AND/OR SOFTWARE ("SOFTWARE"), +YOU UNEQUIVOCALLY ACCEPT, AND AGREE TO BE BOUND BY, ALL OF THE +TERMS AND CONDITIONS OF THIS AGREEMENT. +IF YOU DO NOT AGREE, DO NOT DOWNLOAD, INSTALL, COPY, DISTRIBUTE OR USE +THE DATA FILES OR SOFTWARE. + +COPYRIGHT AND PERMISSION NOTICE + +Copyright (c) 1991-2017 Unicode, Inc. All rights reserved. +Distributed under the Terms of Use in http://www.unicode.org/copyright.html. + +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Unicode data files and any associated documentation +(the "Data Files") or Unicode software and any associated documentation +(the "Software") to deal in the Data Files or Software +without restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, and/or sell copies of +the Data Files or Software, and to permit persons to whom the Data Files +or Software are furnished to do so, provided that either +(a) this copyright and permission notice appear with all copies +of the Data Files or Software, or +(b) this copyright and permission notice appear in associated +Documentation. + +THE DATA FILES AND SOFTWARE ARE PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE +WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT OF THIRD PARTY RIGHTS. +IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS +NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL +DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, +DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER +TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THE DATA FILES OR SOFTWARE. + +Except as contained in this notice, the name of a copyright holder +shall not be used in advertising or otherwise to promote the sale, +use or other dealings in these Data Files or Software without prior +written authorization of the copyright holder. +------------------------------------------------------------------------------------- + +-------------------Document Object Model----------------------------- +DOM + +W3C License +This work is being provided by the copyright holders under the following license. +By obtaining and/or copying this work, you (the licensee) agree that you have read, understood, and will comply with the following terms and conditions. +Permission to copy, modify, and distribute this work, with or without modification,�for any purpose and without fee or royalty is hereby granted, provided that you include the following +on ALL copies of the work or portions thereof, including modifications: +* The full text of this NOTICE in a location viewable to users of the redistributed or derivative work. +* Any pre-existing intellectual property disclaimers, notices, or terms and conditions. If none exist, the W3C Software and Document Short Notice should be included. +* Notice of any changes or modifications, through a copyright statement on the new code or document such as "This software or document includes material copied from or derived +from [title and URI of the W3C document]. Copyright � [YEAR] W3C� (MIT, ERCIM, Keio, Beihang)." +Disclaimers +THIS WORK IS PROVIDED "AS IS," AND COPYRIGHT HOLDERS MAKE NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY OR +FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE SOFTWARE OR DOCUMENT WILL NOT INFRINGE ANY THIRD PARTY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS. +COPYRIGHT HOLDERS WILL NOT BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF ANY USE OF THE SOFTWARE OR DOCUMENT. +The name and trademarks of copyright holders may NOT be used in advertising or publicity pertaining to the work without specific, written prior permission. +Title to copyright in this work will at all times remain with copyright holders. + +--------- + +DOM +Copyright � 2018 WHATWG (Apple, Google, Mozilla, Microsoft). This work is licensed under a Creative Commons Attribution 4.0 International License: Attribution 4.0 International +======================================================================= +Creative Commons Corporation ("Creative Commons") is not a law firm and does not provide legal services or legal advice. Distribution of Creative Commons public licenses does not create a lawyer-client or other relationship. Creative Commons makes its licenses and related information available on an "as-is" basis. Creative Commons gives no warranties regarding its licenses, any material licensed under their terms and conditions, or any related information. Creative Commons disclaims all liability for damages resulting from their use to the fullest extent possible. Using Creative Commons Public Licenses Creative Commons public licenses provide a standard set of terms and conditions that creators and other rights holders may use to share original works of authorship and other material subject to copyright and certain other rights specified in the public license below. The following considerations are for informational purposes only, are not exhaustive, and do not form part of our licenses. Considerations for licensors: Our public licenses are intended for use by those authorized to give the public permission to use material in ways otherwise restricted by copyright and certain other rights. Our licenses are irrevocable. Licensors should read and understand the terms and conditions of the license they choose before applying it. Licensors should also secure all rights necessary before applying our licenses so that the public can reuse the material as expected. Licensors should clearly mark any material not subject to the license. This includes other CC- licensed material, or material used under an exception or limitation to copyright. More considerations for licensors: + +wiki.creativecommons.org/Considerations_for_licensors Considerations for the public: By using one of our public licenses, a licensor grants the public permission to use the licensed material under specified terms and conditions. If the licensor's permission is not necessary for any reason--for example, because of any applicable exception or limitation to copyright--then that use is not regulated by the license. Our licenses grant only permissions under copyright and certain other rights that a licensor has authority to grant. Use of the licensed material may still be restricted for other reasons, including because others have copyright or other rights in the material. A licensor may make special requests, such as asking that all changes be marked or described. Although not required by our licenses, you are encouraged to respect those requests where reasonable. More_considerations for the public: wiki.creativecommons.org/Considerations_for_licensees ======================================================================= +Creative Commons Attribution 4.0 International Public License By exercising the Licensed Rights (defined below), You accept and agree to be bound by the terms and conditions of this Creative Commons Attribution 4.0 International Public License ("Public License"). To the extent this Public License may be interpreted as a contract, You are granted the Licensed Rights in consideration of Your acceptance of these terms and conditions, and the Licensor grants You such rights in consideration of benefits the Licensor receives from making the Licensed Material available under these terms and conditions. Section 1 -- Definitions. a. Adapted Material means material subject to Copyright and Similar Rights that is derived from or based upon the Licensed Material and in which the Licensed Material is translated, altered, arranged, transformed, or otherwise modified in a manner requiring permission under the Copyright and Similar Rights held by the Licensor. For purposes of this Public License, where the Licensed Material is a musical work, performance, or sound recording, Adapted Material is always produced where the Licensed Material is synched in timed relation with a moving image. b. Adapter's License means the license You apply to Your Copyright and Similar Rights in Your contributions to Adapted Material in accordance with the terms and conditions of this Public License. c. Copyright and Similar Rights means copyright and/or similar rights closely related to copyright including, without limitation, performance, broadcast, sound recording, and Sui Generis Database Rights, without regard to how the rights are labeled or categorized. For purposes of this Public License, the rights specified in Section 2(b)(1)-(2) are not Copyright and Similar Rights. d. Effective Technological Measures means those measures that, in the absence of proper authority, may not be circumvented under laws fulfilling obligations under Article 11 of the WIPO Copyright Treaty adopted on December 20, 1996, and/or similar international agreements. e. Exceptions and Limitations means fair use, fair dealing, and/or any other exception or limitation to Copyright and Similar Rights that applies to Your use of the Licensed Material. f. Licensed Material means the artistic or literary work, database, or other material to which the Licensor applied this Public License. g. Licensed Rights means the rights granted to You subject to the terms and conditions of this Public License, which are limited to all Copyright and Similar Rights that apply to Your use of the Licensed Material and that the Licensor has authority to license. h. Licensor means the individual(s) or entity(ies) granting rights under this Public License. i. Share means to provide material to the public by any means or process that requires permission under the Licensed Rights, such as reproduction, public display, public performance, distribution, dissemination, communication, or importation, and to make material available to the public including in ways that members of the public may access the material from a place and at a time individually chosen by them. j. Sui Generis Database Rights means rights other than copyright resulting from Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, as amended and/or succeeded, as well as other essentially equivalent rights anywhere in the world. k. You means the individual or entity exercising the Licensed Rights under this Public License. Your has a corresponding meaning. Section 2 -- Scope. a. License grant. 1. Subject to the terms and conditions of this Public License, the Licensor hereby grants You a worldwide, royalty-free, non-sublicensable, non-exclusive, irrevocable license to exercise the Licensed Rights in the Licensed Material to: a. reproduce and Share the Licensed Material, in whole or in part; and b. produce, reproduce, and Share Adapted Material. 2. Exceptions and Limitations. For the avoidance of doubt, where Exceptions and Limitations apply to Your use, this Public License does not apply, and You do not need to comply with its terms and conditions. 3. Term. The term of this Public License is specified in Section 6(a). 4. Media and formats; technical modifications allowed. The Licensor authorizes You to exercise the Licensed Rights in all media and formats whether now known or hereafter created, and to make technical modifications necessary to do so. The Licensor waives and/or agrees not to assert any right or authority to forbid You from making technical modifications necessary to exercise the Licensed Rights, including technical modifications necessary to circumvent Effective Technological Measures. For purposes of this Public License, simply making modifications authorized by this Section 2(a) (4) never produces Adapted Material. 5. Downstream recipients. a. Offer from the Licensor -- Licensed Material. Every recipient of the Licensed Material automatically receives an offer from the Licensor to exercise the Licensed Rights under the terms and conditions of this Public License. b. No downstream restrictions. You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, the Licensed Material if doing so restricts exercise of the Licensed Rights by any recipient of the Licensed Material. 6. No endorsement. Nothing in this Public License constitutes or may be construed as permission to assert or imply that You are, or that Your use of the Licensed Material is, connected with, or sponsored, endorsed, or granted official status by, the Licensor or others designated to receive attribution as provided in Section 3(a)(1)(A)(i). b. Other rights. 1. Moral rights, such as the right of integrity, are not licensed under this Public License, nor are publicity, privacy, and/or other similar personality rights; however, to the extent possible, the Licensor waives and/or agrees not to assert any such rights held by the Licensor to the limited extent necessary to allow You to exercise the Licensed Rights, but not otherwise. 2. Patent and trademark rights are not licensed under this Public License. 3. To the extent possible, the Licensor waives any right to collect royalties from You for the exercise of the Licensed Rights, whether directly or through a collecting society under any voluntary or waivable statutory or compulsory licensing scheme. In all other cases the Licensor expressly reserves any right to collect such royalties. Section 3 -- License Conditions. Your exercise of the Licensed Rights is expressly made subject to the following conditions. a. Attribution. 1. If You Share the Licensed Material (including in modified form), You must: a. retain the following if it is supplied by the Licensor with the Licensed Material: i. identification of the creator(s) of the Licensed Material and any others designated to receive attribution, in any reasonable manner requested by the Licensor (including by pseudonym if designated); ii. a copyright notice; iii. a notice that refers to this Public License; iv. a notice that refers to the disclaimer of warranties; v. a URI or hyperlink to the Licensed Material to the extent reasonably practicable; b. indicate if You modified the Licensed Material and retain an indication of any previous modifications; and c. indicate the Licensed Material is licensed under this Public License, and include the text of, or the URI or hyperlink to, this Public License. 2. You may satisfy the conditions in Section 3(a)(1) in any reasonable manner based on the medium, means, and context in which You Share the Licensed Material. For example, it may be reasonable to satisfy the conditions by providing a URI or hyperlink to a resource that includes the required information. 3. If requested by the Licensor, You must remove any of the information required by Section 3(a)(1)(A) to the extent reasonably practicable. 4. If You Share Adapted Material You produce, the Adapter's License You apply must not prevent recipients of the Adapted Material from complying with this Public License. Section 4 -- Sui Generis Database Rights. Where the Licensed Rights include Sui Generis Database Rights that apply to Your use of the Licensed Material: a. for the avoidance of doubt, Section 2(a)(1) grants You the right to extract, reuse, reproduce, and Share all or a substantial portion of the contents of the database; b. if You include all or a substantial portion of the database contents in a database in which You have Sui Generis Database Rights, then the database in which You have Sui Generis Database Rights (but not its individual contents) is Adapted Material; and c. You must comply with the conditions in Section 3(a) if You Share all or a substantial portion of the contents of the database. For the avoidance of doubt, this Section 4 supplements and does not replace Your obligations under this Public License where the Licensed Rights include other Copyright and Similar Rights. Section 5 -- Disclaimer of Warranties and Limitation of Liability. a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS, IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION, WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS, ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU. b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION, NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT, INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES, COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR IN PART, THIS LIMITATION MAY NOT APPLY TO YOU. c. The disclaimer of warranties and limitation of liability provided above shall be interpreted in a manner that, to the extent possible, most closely approximates an absolute disclaimer and waiver of all liability. Section 6 -- Term and Termination. a. This Public License applies for the term of the Copyright and Similar Rights licensed here. However, if You fail to comply with this Public License, then Your rights under this Public License terminate automatically. b. Where Your right to use the Licensed Material has terminated under Section 6(a), it reinstates: 1. automatically as of the date the violation is cured, provided it is cured within 30 days of Your discovery of the violation; or 2. upon express reinstatement by the Licensor. For the avoidance of doubt, this Section 6(b) does not affect any right the Licensor may have to seek remedies for Your violations of this Public License. c. For the avoidance of doubt, the Licensor may also offer the Licensed Material under separate terms or conditions or stop distributing the Licensed Material at any time; however, doing so will not terminate this Public License. d. Sections 1, 5, 6, 7, and 8 survive termination of this Public License. Section 7 -- Other Terms and Conditions. a. The Licensor shall not be bound by any additional or different terms or conditions communicated by You unless expressly agreed. b. Any arrangements, understandings, or agreements regarding the Licensed Material not stated herein are separate from and independent of the terms and conditions of this Public License. Section 8 -- Interpretation. a. For the avoidance of doubt, this Public License does not, and shall not be interpreted to, reduce, limit, restrict, or impose conditions on any use of the Licensed Material that could lawfully be made without permission under this Public License. b. To the extent possible, if any provision of this Public License is deemed unenforceable, it shall be automatically reformed to the minimum extent necessary to make it enforceable. If the provision cannot be reformed, it shall be severed from this Public License without affecting the enforceability of the remaining terms and conditions. c. No term or condition of this Public License will be waived and no failure to comply consented to unless expressly agreed to by the Licensor. d. Nothing in this Public License constitutes or may be interpreted as a limitation upon, or waiver of, any privileges and immunities that apply to the Licensor or You, including from the legal processes of any jurisdiction or authority. ======================================================================= Creative Commons is not a party to its public licenses. Notwithstanding, Creative Commons may elect to apply one of its public licenses to material it publishes and in those instances will be considered the "Licensor." Except for the limited purpose of indicating that material is shared under a Creative Commons public license or as otherwise permitted by the Creative Commons policies published at creativecommons.org/policies, Creative Commons does not authorize the use of the trademark "Creative Commons" or any other trademark or logo of Creative Commons without its prior written consent including, without limitation, in connection with any unauthorized modifications to any of its public licenses or any other arrangements, understandings, or agreements concerning use of licensed material. For the avoidance of doubt, this paragraph does not form part of the public licenses. Creative Commons may be contacted at creativecommons.org. + +-------------------------------------------------------------------------------- + +----------------------Web Background Synchronization------------------------------ + +Web Background Synchronization Specification +Portions of spec � by W3C + +W3C Community Final Specification Agreement +To secure commitments from participants for the full text of a Community or Business Group Report, the group may call for voluntary commitments to the following terms; a "summary" is +available. See also the related "W3C Community Contributor License Agreement". +1. The Purpose of this Agreement. +This Agreement sets forth the terms under which I make certain copyright and patent rights available to you for your implementation of the Specification. +Any other capitalized terms not specifically defined herein have the same meaning as those terms have in the "W3C Patent Policy", and if not defined there, in the "W3C Process Document". +2. Copyrights. +2.1. Copyright Grant. I grant to you a perpetual (for the duration of the applicable copyright), worldwide, non-exclusive, no-charge, royalty-free, copyright license, without any obligation for accounting to me, to reproduce, prepare derivative works of, publicly display, publicly perform, sublicense, distribute, and implement the Specification to the full extent of my copyright interest in the Specification. +2.2. Attribution. As a condition of the copyright grant, you must include an attribution to the Specification in any derivative work you make based on the Specification. That attribution must include, at minimum, the Specification name and version number. +3. Patents. +3.1. Patent Licensing Commitment. I agree to license my Essential Claims under the W3C Community RF Licensing Requirements. This requirement includes Essential Claims that I own and any that I have the right to license without obligation of payment or other consideration to an unrelated third party. W3C Community RF Licensing Requirements obligations made concerning the Specification and described in this policy are binding on me for the life of the patents in question and encumber the patents containing Essential Claims, regardless of changes in participation status or W3C Membership. I also agree to license my Essential Claims under the W3C Community RF Licensing Requirements in derivative works of the Specification so long as all normative portions of the Specification are maintained and that this licensing commitment does not extend to any portion of the derivative work that was not included in the Specification. +3.2. Optional, Additional Patent Grant. In addition to the provisions of Section 3.1, I may also, at my option, make certain intellectual property rights infringed by implementations of the Specification, including Essential Claims, available by providing those terms via the W3C Web site. +4. No Other Rights. Except as specifically set forth in this Agreement, no other express or implied patent, trademark, copyright, or other property rights are granted under this Agreement, including by implication, waiver, or estoppel. +5. Antitrust Compliance. I acknowledge that I may compete with other participants, that I am under no obligation to implement the Specification, that each participant is free to develop competing technologies and standards, and that each party is free to license its patent rights to third parties, including for the purpose of enabling competing technologies and standards. +6. Non-Circumvention. I agree that I will not intentionally take or willfully assist any third party to take any action for the purpose of circumventing my obligations under this Agreement. +7. Transition to W3C Recommendation Track. The Specification developed by the Project may transition to the W3C Recommendation Track. The W3C Team is responsible for notifying me that a Corresponding Working Group has been chartered. I have no obligation to join the Corresponding Working Group. If the Specification developed by the Project transitions to the W3C Recommendation Track, the following terms apply: +7.1. If I join the Corresponding Working Group. If I join the Corresponding Working Group, I will be subject to all W3C rules, obligations, licensing commitments, and policies that govern that Corresponding Working Group. +7.2. If I Do Not Join the Corresponding Working Group. +7.2.1. Licensing Obligations to Resulting Specification. If I do not join the Corresponding Working Group, I agree to offer patent licenses according to the W3C Royalty-Free licensing requirements described in Section 5 of the W3C Patent Policy for the portions of the Specification included in the resulting Recommendation. This licensing commitment does not extend to any portion of an implementation of the Recommendation that was not included in the Specification. This licensing commitment may not be revoked but may be modified through the exclusion process defined in Section 4 of the W3C Patent Policy. I am not required to join the Corresponding Working Group to exclude patents from the W3C Royalty-Free licensing commitment, but must otherwise follow the normal exclusion procedures defined by the W3C Patent Policy. The W3C Team will notify me of any Call for Exclusion in the Corresponding Working Group as set forth in Section 4.5 of the W3C Patent Policy. +7.2.2. No Disclosure Obligation. If I do not join the Corresponding Working Group, I have no patent disclosure obligations outside of those set forth in Section 6 of the W3C Patent Policy. +8. Conflict of Interest. I will disclose significant relationships when those relationships might reasonably be perceived as creating a conflict of interest with my role. I will notify W3C of any change in my affiliation using W3C-provided mechanisms. +9. Representations, Warranties and Disclaimers. I represent and warrant that I am legally entitled to grant the rights and promises set forth in this Agreement. IN ALL OTHER RESPECTS THE SPECIFICATION IS PROVIDED �AS IS.� The entire risk as to implementing or otherwise using the Specification is assumed by the implementer and user. Except as stated herein, I expressly disclaim any warranties (express, implied, or otherwise), including implied warranties of merchantability, non-infringement, fitness for a particular purpose, or title, related to the Specification. IN NO EVENT WILL ANY PARTY BE LIABLE TO ANY OTHER PARTY FOR LOST PROFITS OR ANY FORM OF INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES OF ANY CHARACTER FROM ANY CAUSES OF ACTION OF ANY KIND WITH RESPECT TO THIS AGREEMENT, WHETHER BASED ON BREACH OF CONTRACT, TORT (INCLUDING NEGLIGENCE), OR OTHERWISE, AND WHETHER OR NOT THE OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. All of my obligations under Section 3 regarding the transfer, successors in interest, or assignment of Granted Claims will be satisfied if I notify the transferee or assignee of any patent that I know contains Granted Claims of the obligations under Section 3. Nothing in this Agreement requires me to undertake a patent search. +10. Definitions. +10.1. Agreement. �Agreement� means this W3C Community Final Specification Agreement. +10.2. Corresponding Working Group. �Corresponding Working Group� is a W3C Working Group that is chartered to develop a Recommendation, as defined in the W3C Process Document, that takes the Specification as an input. +10.3. Essential Claims. �Essential Claims� shall mean all claims in any patent or patent application in any jurisdiction in the world that would necessarily be infringed by implementation of the Specification. A claim is necessarily infringed hereunder only when it is not possible to avoid infringing it because there is no non-infringing alternative for implementing the normative portions of the Specification. Existence of a non-infringing alternative shall be judged based on the state of the art at the time of the publication of the Specification. The following are expressly excluded from and shall not be deemed to constitute Essential Claims: +10.3.1. any claims other than as set forth above even if contained in the same patent as Essential Claims; and +10.3.2. claims which would be infringed only by: +portions of an implementation that are not specified in the normative portions of the Specification, or +enabling technologies that may be necessary to make or use any product or portion thereof that complies with the Specification and are not themselves expressly set forth in the Specification (e.g., semiconductor manufacturing technology, compiler technology, object-oriented technology, basic operating system technology, and the like); or +the implementation of technology developed elsewhere and merely incorporated by reference in the body of the Specification. +10.3.3. design patents and design registrations. +For purposes of this definition, the normative portions of the Specification shall be deemed to include only architectural and interoperability requirements. Optional features in the RFC 2119 sense are considered normative unless they are specifically identified as informative. Implementation examples or any other material that merely illustrate the requirements of the Specification are informative, rather than normative. +10.4. I, Me, or My. �I,� �me,� or �my� refers to the signatory. +10.5 Project. �Project� means the W3C Community Group or Business Group for which I executed this Agreement. +10.6. Specification. �Specification� means the Specification identified by the Project as the target of this agreement in a call for Final Specification Commitments. W3C shall provide the authoritative mechanisms for the identification of this Specification. +10.7. W3C Community RF Licensing Requirements. �W3C Community RF Licensing Requirements� license shall mean a non-assignable, non-sublicensable license to make, have made, use, sell, have sold, offer to sell, import, and distribute and dispose of implementations of the Specification that: +10.7.1. shall be available to all, worldwide, whether or not they are W3C Members; +10.7.2. shall extend to all Essential Claims owned or controlled by me; +10.7.3. may be limited to implementations of the Specification, and to what is required by the Specification; +10.7.4. may be conditioned on a grant of a reciprocal RF license (as defined in this policy) to all Essential Claims owned or controlled by the licensee. A reciprocal license may be required to be available to all, and a reciprocal license may itself be conditioned on a further reciprocal license from all. +10.7.5. may not be conditioned on payment of royalties, fees or other consideration; +10.7.6. may be suspended with respect to any licensee when licensor issued by licensee for infringement of claims essential to implement the Specification or any W3C Recommendation; +10.7.7. may not impose any further conditions or restrictions on the use of any technology, intellectual property rights, or other restrictions on behavior of the licensee, but may include reasonable, customary terms relating to operation or maintenance of the license relationship such as the following: choice of law and dispute resolution; +10.7.8. shall not be considered accepted by an implementer who manifests an intent not to accept the terms of the W3C Community RF Licensing Requirements license as offered by the licensor. +10.7.9. The RF license conforming to the requirements in this policy shall be made available by the licensor as long as the Specification is in effect. The term of such license shall be for the life of the patents in question. +I am encouraged to provide a contact from which licensing information can be obtained and other relevant licensing information. Any such information will be made publicly available. +10.8. You or Your. �You,� �you,� or �your� means any person or entity who exercises copyright or patent rights granted under this Agreement, and any person that person or entity controls. + +------------------------------------------------------------------------------------- + +------------------- WebGL ----------------------------- +Copyright (c) 2018 The Khronos Group Inc. + +Permission is hereby granted, free of charge, to any person obtaining a +copy of this software and/or associated documentation files (the +"Materials"), to deal in the Materials without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Materials, and to +permit persons to whom the Materials are furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be included +in all copies or substantial portions of the Materials. + +THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. +------------------------------------------------------ + +------------- End of ThirdPartyNotices ------------------------------------------- */ + diff --git a/node_modules/typescript/bin/tsc b/node_modules/typescript/bin/tsc new file mode 100755 index 0000000..19c62bf --- /dev/null +++ b/node_modules/typescript/bin/tsc @@ -0,0 +1,2 @@ +#!/usr/bin/env node +require('../lib/tsc.js') diff --git a/node_modules/typescript/bin/tsserver b/node_modules/typescript/bin/tsserver new file mode 100755 index 0000000..7143b6a --- /dev/null +++ b/node_modules/typescript/bin/tsserver @@ -0,0 +1,2 @@ +#!/usr/bin/env node +require('../lib/tsserver.js') diff --git a/node_modules/typescript/lib/README.md b/node_modules/typescript/lib/README.md new file mode 100644 index 0000000..0a85a9e --- /dev/null +++ b/node_modules/typescript/lib/README.md @@ -0,0 +1,5 @@ +# Read This! + +**These files are not meant to be edited by hand.** +If you need to make modifications, the respective files should be changed within the repository's top-level `src` directory. +Running `jake LKG` will then appropriately update the files in this directory. diff --git a/node_modules/typescript/lib/cancellationToken.js b/node_modules/typescript/lib/cancellationToken.js new file mode 100644 index 0000000..e0f05eb --- /dev/null +++ b/node_modules/typescript/lib/cancellationToken.js @@ -0,0 +1,73 @@ +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + + +"use strict"; +var fs = require("fs"); +function pipeExists(name) { + try { + fs.statSync(name); + return true; + } + catch (e) { + return false; + } +} +function createCancellationToken(args) { + var cancellationPipeName; + for (var i = 0; i < args.length - 1; i++) { + if (args[i] === "--cancellationPipeName") { + cancellationPipeName = args[i + 1]; + break; + } + } + if (!cancellationPipeName) { + return { + isCancellationRequested: function () { return false; }, + setRequest: function (_requestId) { return void 0; }, + resetRequest: function (_requestId) { return void 0; } + }; + } + if (cancellationPipeName.charAt(cancellationPipeName.length - 1) === "*") { + var namePrefix_1 = cancellationPipeName.slice(0, -1); + if (namePrefix_1.length === 0 || namePrefix_1.indexOf("*") >= 0) { + throw new Error("Invalid name for template cancellation pipe: it should have length greater than 2 characters and contain only one '*'."); + } + var perRequestPipeName_1; + var currentRequestId_1; + return { + isCancellationRequested: function () { return perRequestPipeName_1 !== undefined && pipeExists(perRequestPipeName_1); }, + setRequest: function (requestId) { + currentRequestId_1 = requestId; + perRequestPipeName_1 = namePrefix_1 + requestId; + }, + resetRequest: function (requestId) { + if (currentRequestId_1 !== requestId) { + throw new Error("Mismatched request id, expected " + currentRequestId_1 + ", actual " + requestId); + } + perRequestPipeName_1 = undefined; + } + }; + } + else { + return { + isCancellationRequested: function () { return pipeExists(cancellationPipeName); }, + setRequest: function (_requestId) { return void 0; }, + resetRequest: function (_requestId) { return void 0; } + }; + } +} +module.exports = createCancellationToken; +//# sourceMappingURL=cancellationToken.js.map \ No newline at end of file diff --git a/node_modules/typescript/lib/cs/diagnosticMessages.generated.json b/node_modules/typescript/lib/cs/diagnosticMessages.generated.json new file mode 100644 index 0000000..32a067f --- /dev/null +++ b/node_modules/typescript/lib/cs/diagnosticMessages.generated.json @@ -0,0 +1,1101 @@ +{ + "A_0_modifier_cannot_be_used_with_an_import_declaration_1079": "Modifikátor {0} nejde použít s deklarací import.", + "A_0_modifier_cannot_be_used_with_an_interface_declaration_1045": "Modifikátor {0} nejde použít s deklarací interface.", + "A_0_parameter_must_be_the_first_parameter_2680": "Parametr {0} musí být prvním parametrem.", + "A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature_2463": "Parametr vzoru vazby nemůže být u podpisu implementace nepovinný.", + "A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement_1105": "Příkaz break se dá použít jenom uvnitř nadřazené iterace nebo příkazu switch.", + "A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement_1116": "Příkaz break může skočit jenom na popisek nadřazeného příkazu.", + "A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments_2500": "Třída může implementovat jenom identifikátor nebo kvalifikovaný název s volitelnými argumenty typu.", + "A_class_declaration_without_the_default_modifier_must_have_a_name_1211": "Deklarace třídy bez modifikátoru default musí mít název.", + "A_class_may_only_extend_another_class_2311": "Třída může rozšířit jenom jinou třídu.", + "A_class_may_only_implement_another_class_or_interface_2422": "Třída může implementovat jenom jinou třídu nebo rozhraní.", + "A_class_member_cannot_have_the_0_keyword_1248": "Člen třídy nemůže mít klíčové slovo {0}.", + "A_comma_expression_is_not_allowed_in_a_computed_property_name_1171": "Výraz s čárkou není v názvu počítané vlastnosti povolený.", + "A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type_2467": "Název počítané vlastnosti nemůže odkazovat na parametr typu z jeho nadřazeného typu.", + "A_computed_property_name_in_a_class_property_declaration_must_refer_to_an_expression_whose_type_is_a_1166": "Název počítané vlastnosti v deklaraci vlastnosti třídy musí přímo odkazovat na výraz, jehož typ je literál nebo unique symbol.", + "A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_ty_1168": "Název počítané vlastnosti v přetížené metodě musí odkazovat na výraz, jehož typ je literál nebo unique symbol.", + "A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type__1170": "Název počítané vlastnosti v literálu typu musí odkazovat na výraz, jehož typ je literál nebo unique symbol.", + "A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_t_1165": "Název počítané vlastnosti v ambientním kontextu musí odkazovat na výraz, jehož typ je literál nebo unique symbol.", + "A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_1169": "Název počítané vlastnosti v rozhraní musí odkazovat na výraz, jehož typ je literál nebo unique symbol.", + "A_computed_property_name_must_be_of_type_string_number_symbol_or_any_2464": "Název počítané vlastnosti musí být typu string, number, symbol nebo any.", + "A_computed_property_name_of_the_form_0_must_be_of_type_symbol_2471": "Název počítané vlastnosti ve formátu {0} musí být typu symbol.", + "A_const_enum_member_can_only_be_accessed_using_a_string_literal_2476": "Ke členu konstantního výčtu se dá získat přístup jenom pomocí řetězcového literálu.", + "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_1254": "Inicializátor const v ambientním kontextu musí být řetězec (string) nebo číselný literál.", + "A_constructor_cannot_contain_a_super_call_when_its_class_extends_null_17005": "Konstruktor nemůže obsahovat volání super, pokud jeho třída rozšiřuje null.", + "A_constructor_cannot_have_a_this_parameter_2681": "Konstruktor nemůže mít parametr this.", + "A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement_1104": "Příkaz continue se dá použít jenom uvnitř příkazu nadřazené iterace.", + "A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement_1115": "Příkaz continue může přejít jenom na popisek příkazu nadřazené iterace.", + "A_declare_modifier_cannot_be_used_in_an_already_ambient_context_1038": "Modifikátor declare se nedá použít v kontextu, který už je ambientní.", + "A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file_1046": "Pro deklaraci na nejvyšší úrovni v souboru .d.ts se vyžaduje modifikátor declare.", + "A_decorator_can_only_decorate_a_method_implementation_not_an_overload_1249": "Dekorátor může dekorovat jenom implementaci metody, ne přetížení.", + "A_default_clause_cannot_appear_more_than_once_in_a_switch_statement_1113": "Klauzule default nemůže být v příkazu switch víc než jednou.", + "A_default_export_can_only_be_used_in_an_ECMAScript_style_module_1319": "V modulu ve stylu ECMAScriptu se dá použít jenom výchozí export.", + "A_definite_assignment_assertion_is_not_permitted_in_this_context_1255": "Určitý kontrolní výraz přiřazení '!' není v tomto kontextu povolený.", + "A_destructuring_declaration_must_have_an_initializer_1182": "Destrukturační deklarace musí obsahovat inicializátor.", + "A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declarat_2712": "Volání dynamického importu v ES5/ES3 vyžaduje konstruktor Promise. Ujistěte se, že máte deklaraci konstruktoru Promise, nebo do možnosti --lib přidejte ES2015.", + "A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES20_2711": "Volání dynamického importu vrací Promise. Ujistěte se, že pro ni máte deklaraci, nebo do možnosti --lib přidejte ES2015.", + "A_file_cannot_have_a_reference_to_itself_1006": "Soubor nemůže odkazovat sám na sebe.", + "A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator_1103": "Příkaz for-await-of se povoluje jenom v asynchronní funkci nebo asynchronním generátoru.", + "A_function_returning_never_cannot_have_a_reachable_end_point_2534": "Funkce, která vrací hodnotu never, nemůže mít dosažitelný koncový bod.", + "A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void_2679": "Funkce volaná klíčovým slovem new nemůže mít typ this, který je void.", + "A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value_2355": "Funkce, jejíž deklarovaný typ není void ani any, musí vracet hodnotu.", + "A_generator_cannot_have_a_void_type_annotation_2505": "Generátor nemůže mít anotaci typu void.", + "A_get_accessor_cannot_have_parameters_1054": "Přístupový objekt get nemůže obsahovat parametry.", + "A_get_accessor_must_return_a_value_2378": "Přístupový objekt get musí vracet hodnotu.", + "A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_memb_2651": "Inicializátor členu v deklaraci výčtu nemůže odkazovat na členy deklarované až po výčtu, a to ani členy definované v jiných výčtech.", + "A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any_2545": "Třída mixin musí mít konstruktor s jediným parametrem rest typu any[].", + "A_module_cannot_have_multiple_default_exports_2528": "Modul nemůže mít víc výchozích exportů.", + "A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merg_2433": "Deklarace oboru názvů nemůže být v jiném souboru než třída nebo funkce, se kterou se slučuje.", + "A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged_2434": "Deklarace oboru názvů nemůže být umístěná před třídou nebo funkcí, se kterou se slučuje.", + "A_namespace_declaration_is_only_allowed_in_a_namespace_or_module_1235": "Deklarace oboru názvů je povolená jenom v oboru názvů nebo v modulu.", + "A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_7038": "Import stylu oboru názvů není možné vyvolat nebo konstruovat a způsobí selhání za běhu.", + "A_non_dry_build_would_build_project_0_6357": "Build bez příznaku -dry by vytvořil projekt {0}.", + "A_non_dry_build_would_delete_the_following_files_Colon_0_6356": "Build bez příznaku -dry by odstranil následující soubory: {0}", + "A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation_2371": "Inicializátor parametru je povolený jenom v implementaci funkce nebo konstruktoru.", + "A_parameter_property_cannot_be_declared_using_a_rest_parameter_1317": "Vlastnost parametru se nedá deklarovat pomocí parametru rest.", + "A_parameter_property_is_only_allowed_in_a_constructor_implementation_2369": "Vlastnost parametru je povolená jenom v implementaci konstruktoru.", + "A_parameter_property_may_not_be_declared_using_a_binding_pattern_1187": "Vlastnost parametru se nedá deklarovat pomocí vzoru vazby.", + "A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not_18001": "Cesta v možnosti extends musí být relativní nebo mít kořen, ale {0} nic z toho nesplňuje.", + "A_promise_must_have_a_then_method_1059": "Příslib musí mít metodu then.", + "A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly_1331": "Vlastnost třídy, jejíž typ je unique symbol, musí být static a readonly.", + "A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly_1330": "Vlastnost rozhraní nebo literálu typu, jehož typ je unique symbol, musí být readonly.", + "A_required_parameter_cannot_follow_an_optional_parameter_1016": "Povinný parametr nemůže následovat po nepovinném parametru.", + "A_rest_element_cannot_contain_a_binding_pattern_2501": "Element rest nemůže obsahovat vzor vazby.", + "A_rest_element_cannot_have_a_property_name_2566": "Element rest nemůže mít název vlastnosti.", + "A_rest_element_cannot_have_an_initializer_1186": "Element rest nemůže obsahovat inicializátor.", + "A_rest_element_must_be_last_in_a_destructuring_pattern_2462": "Element rest musí být ve vzoru destrukturalizace poslední.", + "A_rest_parameter_cannot_be_optional_1047": "Parametr rest nemůže být nepovinný.", + "A_rest_parameter_cannot_have_an_initializer_1048": "Parametr rest nemůže obsahovat inicializátor.", + "A_rest_parameter_must_be_last_in_a_parameter_list_1014": "Parametr rest musí být posledním v seznamu parametrů.", + "A_rest_parameter_must_be_of_an_array_type_2370": "Parametr rest musí být typu pole.", + "A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma_1013": "Parametr rest nebo vzor vazby nesmí mít na konci čárku.", + "A_return_statement_can_only_be_used_within_a_function_body_1108": "Příkaz return se dá použít jenom v těle funkce.", + "A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl_6167": "Řada záznamů, které mění mapování importů do umístění vyhledávání relativních vůči baseUrl.", + "A_set_accessor_cannot_have_a_return_type_annotation_1095": "Přístupový objekt set nemůže obsahovat anotaci návratového typu.", + "A_set_accessor_cannot_have_an_optional_parameter_1051": "Přístupový objekt set nemůže obsahovat nepovinný parametr.", + "A_set_accessor_cannot_have_rest_parameter_1053": "Přístupový objekt get nemůže obsahovat parametr rest.", + "A_set_accessor_must_have_exactly_one_parameter_1049": "Přístupový objekt set musí obsahovat přesně jeden parametr.", + "A_set_accessor_parameter_cannot_have_an_initializer_1052": "Parametr přístupového objektu set nemůže obsahovat inicializátor.", + "A_signature_with_an_implementation_cannot_use_a_string_literal_type_2381": "Podpis s implementací nemůže používat typ řetězcového literálu.", + "A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_proper_2376": "Pokud třída obsahuje inicializované vlastnosti nebo má vlastnosti parametru, musí být volání super první příkaz v konstruktoru.", + "A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard_2518": "Ochrana typu this není kompatibilní s ochranou typu založeného na parametru.", + "A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface_2526": "Typ this je k dispozici jenom v nestatických členech třídy nebo rozhraní.", + "A_tsconfig_json_file_is_already_defined_at_Colon_0_5054": "Soubor tsconfig.json je už v {0} definovaný.", + "A_tuple_type_element_list_cannot_be_empty_1122": "Seznam elementů typu řazené kolekce členů nemůže být prázdný.", + "A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Con_17007": "Výraz potvrzení typu se na levé straně výrazu umocnění nepovoluje. Zvažte možnost uzavření výrazu do závorek.", + "A_type_literal_property_cannot_have_an_initializer_1247": "Vlastnost literálu typu nemůže mít inicializátor.", + "A_type_predicate_cannot_reference_a_rest_parameter_1229": "Predikát typu nemůže odkazovat na parametr rest.", + "A_type_predicate_cannot_reference_element_0_in_a_binding_pattern_1230": "Predikát typu nemůže odkazovat na element {0} ve vzoru vazby.", + "A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods_1228": "Predikát typu je povolený jenom na pozici návratového typu funkcí a metod.", + "A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type_2677": "Typ predikátu typu musí být přiřaditelný k typu jeho parametru.", + "A_variable_whose_type_is_a_unique_symbol_type_must_be_const_1332": "Proměnná, jejíž typ je unique symbol, musí být const.", + "A_yield_expression_is_only_allowed_in_a_generator_body_1163": "Výraz yield je povolený jenom v těle generátoru.", + "Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression_2513": "K abstraktní metodě {0} ve třídě {1} nejde získat přístup prostřednictvím výrazu super.", + "Abstract_methods_can_only_appear_within_an_abstract_class_1244": "Abstraktní metody se můžou vyskytovat jenom v abstraktní třídě.", + "Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor_2715": "K abstraktní vlastnosti {0} ve třídě {1} nelze získat přístup v konstruktoru.", + "Accessibility_modifier_already_seen_1028": "Modifikátor dostupnosti se už jednou vyskytl.", + "Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher_1056": "Přístupové objekty jsou dostupné, jenom když je cílem ECMAScript 5 a vyšší verze.", + "Accessors_must_both_be_abstract_or_non_abstract_2676": "Přistupující objekty musí být abstraktní nebo neabstraktní.", + "Add_0_to_existing_import_declaration_from_1_90015": "Přidat {0} k existující deklaraci importu z {1}", + "Add_0_to_unresolved_variable_90008": "Přidat {0}. k nerozpoznané proměnné", + "Add_all_missing_async_modifiers_95041": "Přidat všechny chybějící modifikátory async", + "Add_all_missing_members_95022": "Přidat všechny chybějící členy", + "Add_all_missing_super_calls_95039": "Přidat všechna chybějící volání pomocí super", + "Add_async_modifier_to_containing_function_90029": "Přidat modifikátor async do obsahující funkce", + "Add_braces_to_arrow_function_95059": "Přidat složené závorky k funkci šipky", + "Add_definite_assignment_assertion_to_property_0_95020": "Přidat kontrolní výraz jednoznačného přiřazení k vlastnosti {0}", + "Add_definite_assignment_assertions_to_all_uninitialized_properties_95028": "Přidat kontrolní výrazy jednoznačného přiřazení do všech neinicializovaných vlastností", + "Add_index_signature_for_property_0_90017": "Přidat signaturu indexu pro vlastnost {0}", + "Add_initializer_to_property_0_95019": "Přidat inicializační výraz k vlastnosti {0}", + "Add_initializers_to_all_uninitialized_properties_95027": "Přidat inicializátory do všech neinicializovaných vlastností", + "Add_missing_super_call_90001": "Přidat chybějící volání metody super()", + "Add_missing_typeof_95052": "Přidat chybějící typeof", + "Add_or_remove_braces_in_an_arrow_function_95058": "Přidat nebo odebrat složené závorky ve funkci šipky", + "Add_qualifier_to_all_unresolved_variables_matching_a_member_name_95037": "Přidat kvalifikátor do všech nerozpoznaných proměnných odpovídajících názvu členu", + "Add_to_all_uncalled_decorators_95044": "Přidat () do všech nevolaných dekorátorů", + "Add_ts_ignore_to_all_error_messages_95042": "Přidat @ts-ignore do všech chybových zpráv", + "Add_undefined_type_to_all_uninitialized_properties_95029": "Přidat nedefinovaný typ do všech neinicializovaných vlastností", + "Add_undefined_type_to_property_0_95018": "Přidat typ undefined k vlastnosti {0}", + "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068": "Přidání souboru tsconfig.json vám pomůže uspořádat projekty, které obsahují jak soubory TypeScript, tak soubory JavaScript. Další informace najdete na adrese https://aka.ms/tsconfig.", + "Additional_Checks_6176": "Další kontroly", + "Advanced_Options_6178": "Upřesnit možnosti", + "All_declarations_of_0_must_have_identical_modifiers_2687": "Všechny deklarace {0} musí mít stejné modifikátory.", + "All_declarations_of_0_must_have_identical_type_parameters_2428": "Všechny deklarace {0} musí mít stejné parametry typu.", + "All_declarations_of_an_abstract_method_must_be_consecutive_2516": "Všechny deklarace abstraktní metody musí jít po sobě.", + "All_destructured_elements_are_unused_6198": "Žádný z destrukturovaných elementů se nepoužívá.", + "All_imports_in_import_declaration_are_unused_6192": "Žádné importy z deklarace importu se nepoužívají.", + "All_variables_are_unused_6199": "Žádná z proměnných se nepoužívá.", + "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011": "Povolte výchozí importy z modulů bez výchozího exportu. Nebude to mít vliv na generování kódu, jenom na kontrolu typů.", + "Allow_javascript_files_to_be_compiled_6102": "Povolí kompilaci souborů javascript.", + "Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided_1209": "Když se zadá příznak --isolatedModules, nepovolují se ambientní výčty.", + "Ambient_module_declaration_cannot_specify_relative_module_name_2436": "Deklarace ambientního modulu nemůže uvádět relativní název modulu.", + "Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces_2435": "Ambientní moduly se nedají zanořovat do jiných modulů nebo oborů názvů.", + "An_AMD_module_cannot_have_multiple_name_assignments_2458": "Modul AMD nemůže obsahovat víc přiřazení názvů.", + "An_abstract_accessor_cannot_have_an_implementation_1318": "Abstraktní přístupový objekt nemůže mít implementaci.", + "An_accessor_cannot_be_declared_in_an_ambient_context_1086": "Přístupový objekt nemůže být deklarovaný v ambientním kontextu.", + "An_accessor_cannot_have_type_parameters_1094": "Přístupový objekt nemůže obsahovat parametry typu.", + "An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file_1234": "Deklarace ambientního modulu je povolená jenom na nejvyšší úrovni v souboru.", + "An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type_2356": "Aritmetický operand musí být typu any, number nebo typu výčtu.", + "An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_de_2705": "Asynchronní funkce nebo metoda v ES5/ES3 vyžaduje konstruktor Promise. Ujistěte se, že máte deklaraci konstruktoru Promise, nebo do možnosti --lib přidejte ES2015.", + "An_async_function_or_method_must_have_a_valid_awaitable_return_type_1057": "Funkce nebo metoda async musí mít platný návratový typ pro await.", + "An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_in_2697": "Asynchronní funkce nebo metoda musí vracet hodnotu příslibu. Přesvědčte se, že pro ni máte deklaraci, nebo zahrňte ES2015 do možnosti --lib.", + "An_async_iterator_must_have_a_next_method_2519": "Asynchronní iterátor musí mít metodu next().", + "An_element_access_expression_should_take_an_argument_1011": "Výraz přístupu k elementu by měl přijímat argument.", + "An_enum_member_cannot_have_a_numeric_name_2452": "Člen výčtu nemůže mít číselný název.", + "An_export_assignment_can_only_be_used_in_a_module_1231": "Přiřazení exportu jde použít jenom v modulu.", + "An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements_2309": "Přiřazení exportu se nedá použít v modulu s jinými exportovanými elementy.", + "An_export_assignment_cannot_be_used_in_a_namespace_1063": "Přiřazení exportu se nedá používat v oboru názvů.", + "An_export_assignment_cannot_have_modifiers_1120": "Přiřazení exportu nemůže mít modifikátory.", + "An_export_declaration_can_only_be_used_in_a_module_1233": "Deklarace exportu jde použít jenom v modulu.", + "An_export_declaration_cannot_have_modifiers_1193": "Deklarace exportu nemůže mít modifikátory.", + "An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive_1198": "Rozšířená řídicí hodnota Unicode musí být mezi 0x0 a 0x10FFFF (včetně).", + "An_implementation_cannot_be_declared_in_ambient_contexts_1183": "Implementace se nedá deklarovat v ambientních kontextech.", + "An_import_declaration_can_only_be_used_in_a_namespace_or_module_1232": "Deklarace importu jde použít jenom v oboru názvů nebo modulu.", + "An_import_declaration_cannot_have_modifiers_1191": "Deklarace importu nemůže mít modifikátory.", + "An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead_2691": "Cesta pro import nemůže končit příponou {0}. Zvažte možnost importovat místo toho {1}.", + "An_index_expression_argument_must_be_of_type_string_number_symbol_or_any_2342": "Argument výrazu indexu musí být typu string, number, symbol nebo any.", + "An_index_signature_cannot_have_a_rest_parameter_1017": "Signatura indexu indexu nemůže obsahovat parametr rest.", + "An_index_signature_must_have_a_type_annotation_1021": "Signatura indexu musí mít anotaci typu.", + "An_index_signature_must_have_exactly_one_parameter_1096": "Signatura indexu musí mít právě jeden parametr.", + "An_index_signature_parameter_cannot_have_a_question_mark_1019": "V parametru signatury indexu nemůže být otazník.", + "An_index_signature_parameter_cannot_have_an_accessibility_modifier_1018": "V parametru signatury indexu nemůže být modifikátor přístupnosti.", + "An_index_signature_parameter_cannot_have_an_initializer_1020": "V parametru signatury indexu nemůže být inicializátor.", + "An_index_signature_parameter_must_have_a_type_annotation_1022": "V parametru signatury indexu nemůže být anotace typu.", + "An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead_1336": "Typ parametru signatury indexu nemůže být alias typu. Místo toho zvažte toto zadání: [{0}: {1}]: {2}.", + "An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead_1337": "Typ parametru signatury indexu nemůže být typ sjednocení. Místo toho zvažte použití namapovaného typu objektu.", + "An_index_signature_parameter_type_must_be_string_or_number_1023": "Parametr signatury indexu musí být typu string nebo number.", + "An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments_2499": "Rozhraní může rozšířit jenom identifikátor nebo kvalifikovaný název s volitelnými argumenty typu.", + "An_interface_may_only_extend_a_class_or_another_interface_2312": "Rozhraní může rozšiřovat jenom třídu nebo jiné rozhraní.", + "An_interface_property_cannot_have_an_initializer_1246": "Vlastnost rozhraní nemůže mít inicializátor.", + "An_iterator_must_have_a_next_method_2489": "Iterátor musí mít metodu next().", + "An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name_1118": "Literál objektu nemůže obsahovat několik přístupových objektů get/set se stejným názvem.", + "An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode_1117": "Literál objektu nemůže mít víc vlastností se stejným názvem ve striktním režimu.", + "An_object_literal_cannot_have_property_and_accessor_with_the_same_name_1119": "Literál objektu nemůže obsahovat vlastnost a přístupový objekt se stejným názvem.", + "An_object_member_cannot_be_declared_optional_1162": "Člen objektu nemůže být deklarovaný jako nepovinný.", + "An_overload_signature_cannot_be_declared_as_a_generator_1222": "Signatura přetížení nemůže být deklarovaný jako generátor.", + "An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_ex_17006": "Unární výraz s operátorem {0} se na levé straně výrazu umocnění nepovoluje. Zvažte možnost uzavření výrazu do závorek.", + "Annotate_everything_with_types_from_JSDoc_95043": "Vše s typy z JSDoc opatřit poznámkami", + "Annotate_with_type_from_JSDoc_95009": "Přidat poznámku s typem z JSDoc", + "Annotate_with_types_from_JSDoc_95010": "Přidat poznámky s typy z JSDoc", + "Argument_expression_expected_1135": "Očekává se výraz argumentu.", + "Argument_for_0_option_must_be_Colon_1_6046": "Argument možnosti {0} musí být {1}.", + "Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_2345": "Argument typu {0} nejde přiřadit k parametru typu {1}.", + "Array_element_destructuring_pattern_expected_1181": "Očekával se destrukturační vzor elementu pole.", + "Asterisk_Slash_expected_1010": "Očekával se znak */.", + "Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_2669": "Rozšíření pro globální rozsah může být jenom přímo vnořené v externích modulech nebo deklaracích ambientního modulu.", + "Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambien_2670": "Rozšíření pro globální rozsah by měla mít modifikátor declare, pokud se neobjeví v kontextu, který je už ambientní.", + "Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using__6140": "Automatické zjišťování pro psaní je povolené v projektu {0}. Spouští se speciální průchod řešení pro modul {1} prostřednictvím umístění mezipaměti {2}.", + "Base_class_expressions_cannot_reference_class_type_parameters_2562": "Výrazy základní třídy nemůžou odkazovat na parametry typu třídy.", + "Base_constructor_return_type_0_is_not_a_class_or_interface_type_2509": "Návratový typ {0} základního konstruktoru není typu třída ani rozhraní.", + "Base_constructors_must_all_have_the_same_return_type_2510": "Všechny základní konstruktory musí mít stejný návratový typ.", + "Base_directory_to_resolve_non_absolute_module_names_6083": "Základní adresář pro překlad neabsolutních názvů modulů.", + "Basic_Options_6172": "Základní možnosti", + "Binary_digit_expected_1177": "Očekává se binární číslice.", + "Binding_element_0_implicitly_has_an_1_type_7031": "Element vazby {0} má implicitně typ {1}.", + "Block_scoped_variable_0_used_before_its_declaration_2448": "Proměnná bloku {0} se používá před vlastní deklarací.", + "Build_all_projects_including_those_that_appear_to_be_up_to_date_6368": "Sestavit všechny projekty včetně těch, které se zdají aktuální", + "Build_one_or_more_projects_and_their_dependencies_if_out_of_date_6364": "Sestavit jeden nebo více projektů a jejich závislosti, pokud jsou zastaralé", + "Building_project_0_6358": "Sestavuje se projekt {0}...", + "Call_decorator_expression_90028": "Zavolat výraz dekorátoru", + "Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7020": "Signatura volání s chybějící anotací návratového typu má implicitně návratový typ any.", + "Call_target_does_not_contain_any_signatures_2346": "Cíl volání neobsahuje žádné signatury.", + "Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_p_2713": "K {0}.{1} nelze získat přístup, protože {0} je typ, nikoli názvový prostor. Chtěli jste načíst typ vlastnosti {1} v {0} pomocí {0}[{1}]?", + "Cannot_assign_a_0_constructor_type_to_a_1_constructor_type_2672": "Typ konstruktoru {0} se nedá přiřadit k typu konstruktoru {1}.", + "Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type_2517": "Abstraktní typ konstruktoru nejde přiřadit neabstraktnímu typu konstruktoru.", + "Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property_2540": "Nejde přiřadit k vlastnosti {0}, protože je konstantní nebo jen pro čtení.", + "Cannot_assign_to_0_because_it_is_not_a_variable_2539": "Nejde přiřadit k položce {0}, to není proměnná.", + "Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity_2671": "Modul {0} se nedá rozšířit, protože se překládá do entity, která není modul.", + "Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity_2649": "Modul {0} se nedá rozšířit, protože se překládá na entitu, která není modul.", + "Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system_6131": "Moduly nejde kompilovat pomocí možnosti {0}, pokud příznak --module nemá hodnotu amd nebo system.", + "Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided_1208": "Když se zadá příznak --isolatedModules, nejde kompilovat obory názvů.", + "Cannot_create_an_instance_of_an_abstract_class_2511": "Nejde vytvořit instance abstraktní třídy.", + "Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module_2661": "{0} se nedá exportovat. Z modulu je možné exportovat jenom místní deklarace.", + "Cannot_extend_a_class_0_Class_constructor_is_marked_as_private_2675": "Třída {0} se nedá rozšířit. Konstruktor třídy je označený jako privátní.", + "Cannot_extend_an_interface_0_Did_you_mean_implements_2689": "Nejde rozšířit rozhraní {0}. Měli jste na mysli 'implements'?", + "Cannot_find_a_tsconfig_json_file_at_the_specified_directory_Colon_0_5057": "Soubor tsconfig.json nejde najít v zadaném adresáři: {0}", + "Cannot_find_global_type_0_2318": "Globální typ {0} se nenašel.", + "Cannot_find_global_value_0_2468": "Globální hodnota {0} se nenašla.", + "Cannot_find_lib_definition_for_0_2726": "Nepovedlo se najít definici knihovny pro {0}.", + "Cannot_find_lib_definition_for_0_Did_you_mean_1_2727": "Nepovedlo se najít definici knihovny pro {0}. Neměli jste na mysli spíš {1}?", + "Cannot_find_module_0_2307": "Nenašel se modul {0}.", + "Cannot_find_name_0_2304": "Název {0} se nenašel.", + "Cannot_find_name_0_Did_you_mean_1_2552": "Nepovedlo se najít název {0}. Měli jste na mysli {1}?", + "Cannot_find_name_0_Did_you_mean_the_instance_member_this_0_2663": "Název {0} se nedá najít. Měli jste na mysli člena instance this.{0}?", + "Cannot_find_name_0_Did_you_mean_the_static_member_1_0_2662": "Název {0} se nedá najít. Měli jste na mysli statický člen {1}.{0}?", + "Cannot_find_namespace_0_2503": "Nenašel se obor názvů {0}.", + "Cannot_find_parameter_0_1225": "Nenašel se parametr {0}.", + "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009": "Nenašla se společná cesta podadresářů pro vstupní soubory.", + "Cannot_find_type_definition_file_for_0_2688": "Nejde najít soubor definice pro {0}.", + "Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1_6137": "Soubory deklarací typů nejde importovat. Zvažte možnost místo {1} naimportovat {0}.", + "Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1_2481": "Proměnnou {0} s vnějším oborem nejde inicializovat ve stejném oboru jako deklaraci {1} s oborem bloku.", + "Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatur_2349": "Nejde vyvolat výraz, v jehož typu chybí signatura volání. Typ {0} nemá žádné kompatibilní signatury volání.", + "Cannot_invoke_an_object_which_is_possibly_null_2721": "Nejde vyvolat objekt, který může být null.", + "Cannot_invoke_an_object_which_is_possibly_null_or_undefined_2723": "Nejde vyvolat objekt, který může být null nebo nedefinovaný.", + "Cannot_invoke_an_object_which_is_possibly_undefined_2722": "Nejde vyvolat objekt, který může být nedefinovaný.", + "Cannot_prepend_project_0_because_it_does_not_have_outFile_set_6308": "Projekt {0} se nedá předřadit, protože nemá nastavenou hodnotu outFile.", + "Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205": "Typ nejde znovu exportovat, pokud je zadaný příznak --isolatedModules.", + "Cannot_read_file_0_Colon_1_5012": "Nejde číst soubor {0}: {1}", + "Cannot_redeclare_block_scoped_variable_0_2451": "Nejde předeklarovat proměnnou bloku {0}.", + "Cannot_redeclare_exported_variable_0_2323": "Exportovanou proměnnou {0} není možné znovu deklarovat.", + "Cannot_redeclare_identifier_0_in_catch_clause_2492": "Nejde předeklarovat identifikátor {0} v klauzuli catch.", + "Cannot_use_JSX_unless_the_jsx_flag_is_provided_17004": "Pokud se nezadá příznak -jsx, nepůjde JSX použít.", + "Cannot_use_imports_exports_or_module_augmentations_when_module_is_none_1148": "Nejde používat importy, exporty nebo rozšíření modulu, pokud má příznak --module hodnotu none.", + "Cannot_use_namespace_0_as_a_type_2709": "Obor názvů {0} nejde použít jako typ.", + "Cannot_use_namespace_0_as_a_value_2708": "Obor názvů {0} nejde použít jako hodnotu.", + "Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature_2351": "Nejde použít new s výrazem, kterému v typu chybí volání nebo signatura konstruktu.", + "Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files_5056": "Do souboru {0} se nedá zapisovat, protože by se přepsal více vstupními soubory.", + "Cannot_write_file_0_because_it_would_overwrite_input_file_5055": "Do souboru {0} se nedá zapisovat, protože by přepsal vstupní soubor.", + "Catch_clause_variable_cannot_have_a_type_annotation_1196": "Proměnná klauzule catch nemůže mít anotaci typu.", + "Catch_clause_variable_cannot_have_an_initializer_1197": "Proměnná klauzule catch nemůže mít inicializátor.", + "Change_0_to_1_90014": "Změnit {0} na {1}", + "Change_all_extended_interfaces_to_implements_95038": "Změnit všechna rozšířená rozhraní na implements", + "Change_all_jsdoc_style_types_to_TypeScript_95030": "Změnit všechny typy jsdoc-style na TypeScript", + "Change_all_jsdoc_style_types_to_TypeScript_and_add_undefined_to_nullable_types_95031": "Změnit všechny typy jsdoc-style na TypeScript (a přidat | undefined do typů s možnou hodnotou null)", + "Change_extends_to_implements_90003": "Změnit extends na implements", + "Change_spelling_to_0_90022": "Změnit pravopis na {0}", + "Checking_if_0_is_the_longest_matching_prefix_for_1_2_6104": "Kontroluje se, jestli je {0} nejdelší odpovídající předpona pro {1}–{2}.", + "Circular_definition_of_import_alias_0_2303": "Cyklická definice aliasu importu {0}", + "Circularity_detected_while_resolving_configuration_Colon_0_18000": "Při překladu konfigurace se zjistila cykličnost: {0}.", + "Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_functi_2426": "Třída {0} definuje členský přístupový objekt instance {1}, ale rozšířená třída {2} ho definuje jako členskou funkci instance.", + "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_access_2423": "Třída {0} definuje členskou funkci instance {1}, ale rozšířená třída {2} ji definuje jako členský přístupový objekt instance.", + "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_proper_2424": "Třída {0} definuje členskou funkci instance {1}, ale rozšířená třída {2} ji definuje jako vlastnost člena instance.", + "Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_functi_2425": "Třída {0} definuje vlastnost člena instance {1}, ale rozšířená třída {2} ji definuje jako členskou funkci instance.", + "Class_0_incorrectly_extends_base_class_1_2415": "Třída {0} nesprávně rozšiřuje základní třídu {1}.", + "Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclas_2720": "Třída {0} nesprávně implementuje třídu {1}. Nechtěli jste rozšířit třídu {1} a dědit její členy jako podtřídu?", + "Class_0_incorrectly_implements_interface_1_2420": "Třída {0} nesprávně implementuje rozhraní {1}.", + "Class_0_used_before_its_declaration_2449": "Třída {0} se používá dříve, než se deklaruje.", + "Class_declarations_cannot_have_more_than_one_augments_or_extends_tag_8025": "Deklarace tříd nemůžou mít více než jednu značku @augments nebo @extends.", + "Class_name_cannot_be_0_2414": "Třída nemůže mít název {0}.", + "Class_name_cannot_be_Object_when_targeting_ES5_with_module_0_2725": "Když se cílí na ES5 s modulem {0}, název třídy nemůže být Object.", + "Class_static_side_0_incorrectly_extends_base_class_static_side_1_2417": "Statická strana třídy {0} nesprávně rozšiřuje statickou stranu základní třídy {1}.", + "Classes_can_only_extend_a_single_class_1174": "Třídy můžou rozšířit jenom jednu třídu.", + "Classes_containing_abstract_methods_must_be_marked_abstract_2514": "Třídy obsahující abstraktní metody musí být označené jako abstraktní.", + "Command_line_Options_6171": "Možnosti příkazového řádku", + "Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json_6020": "Zkompilujte projekt podle cesty k jeho konfiguračnímu souboru nebo do složky se souborem tsconfig.json.", + "Compiler_option_0_expects_an_argument_6044": "Parametr kompilátoru {0} očekává argument.", + "Compiler_option_0_requires_a_value_of_type_1_5024": "Parametr kompilátoru {0} vyžaduje hodnotu typu {1}.", + "Composite_projects_may_not_disable_declaration_emit_6304": "Složené projekty nemůžou zakázat generování deklarací.", + "Computed_property_names_are_not_allowed_in_enums_1164": "Názvy počítaných vlastností se ve výčtech nepovolují.", + "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553": "Ve výčtu, jehož členy mají hodnoty typu string, se nepovolují vypočítané hodnoty.", + "Concatenate_and_emit_output_to_single_file_6001": "Zřetězit a generovat výstup do jednoho souboru", + "Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_librar_4090": "Našly se konfliktní definice pro: {0} v {1} a {2}. Zvažte možnost nainstalovat specifickou verzi této knihovny, aby se konflikt vyřešil.", + "Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7013": "Podpis konstruktoru s chybějící anotací návratového typu má implicitně návratový typ any.", + "Constructor_implementation_is_missing_2390": "Chybí implementace konstruktoru.", + "Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration_2673": "Konstruktor třídy {0} je privátní a dostupný jenom v rámci deklarace třídy.", + "Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration_2674": "Konstruktor třídy {0} je chráněný a dostupný jenom v rámci deklarace třídy.", + "Constructors_for_derived_classes_must_contain_a_super_call_2377": "Konstruktory odvozených tříd musí obsahovat volání příkazu super.", + "Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126": "Není zadaný obsažený soubor a nedá se určit kořenový adresář – přeskakuje se vyhledávání ve složce node_modules.", + "Convert_0_to_mapped_object_type_95055": "Převést {0} na typ mapovaného objektu", + "Convert_all_constructor_functions_to_classes_95045": "Převést všechny funkce konstruktoru na třídy", + "Convert_all_require_to_import_95048": "Převést všechna volání require na import", + "Convert_all_to_default_imports_95035": "Převést vše na výchozí importy", + "Convert_function_0_to_class_95002": "Převést funkci {0} na třídu", + "Convert_function_to_an_ES2015_class_95001": "Převést funkci na třídu ES2015", + "Convert_named_imports_to_namespace_import_95057": "Převést pojmenované importy na import oboru názvů", + "Convert_namespace_import_to_named_imports_95056": "Převést import oboru názvů na pojmenované importy", + "Convert_require_to_import_95047": "Převést require na import", + "Convert_to_ES6_module_95017": "Převést na modul ES6", + "Convert_to_default_import_95013": "Převést na výchozí import", + "Corrupted_locale_file_0_6051": "Soubor národního prostředí {0} je poškozený.", + "Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type_7016": "Nenašel se soubor deklarací pro modul {0}. {1} má implicitně typ any.", + "Could_not_write_file_0_Colon_1_5033": "Nedá se zapisovat do souboru {0}: {1}", + "DIRECTORY_6038": "ADRESÁŘ", + "Declaration_expected_1146": "Očekává se deklarace.", + "Declaration_name_conflicts_with_built_in_global_identifier_0_2397": "Název deklarace je v konfliktu s integrovaným globálním identifikátorem {0}.", + "Declaration_or_statement_expected_1128": "Očekává se deklarace nebo příkaz.", + "Declare_method_0_90023": "Deklarovat metodu {0}", + "Declare_property_0_90016": "Deklarovat vlastnost {0}", + "Declare_static_method_0_90024": "Deklarovat statickou metodu {0}", + "Declare_static_property_0_90027": "Deklarovat statickou vlastnost {0}", + "Decorators_are_not_valid_here_1206": "Dekorátory tady nejsou platné.", + "Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name_1207": "Dekorátory nejde použít na víc přístupových objektů get/set se stejným názvem.", + "Default_export_of_the_module_has_or_is_using_private_name_0_4082": "Výchozí export modulu má nebo používá privátní název {0}.", + "Delete_all_unused_declarations_95024": "Odstranit všechny nepoužívané deklarace", + "Delete_the_outputs_of_all_projects_6365": "Odstranit výstupy všech projektů", + "Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react__6084": "[Zastaralé] Použijte místo toho --jsxFactory. Určí objekt vyvolaný pro createElement při cílení na generování JSX react.", + "Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file_6170": "[Zastaralé] Použijte místo toho --outFile. Zřetězí a vygeneruje výstup do jednoho souboru.", + "Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files_6160": "[Zastaralé] Použijte místo toho --skipLibCheck. Přeskočí kontrolu typů výchozích souborů deklarací knihovny.", + "Digit_expected_1124": "Očekává se číslice.", + "Directory_0_does_not_exist_skipping_all_lookups_in_it_6148": "Adresář {0} neexistuje. Všechna vyhledávání v něm se přeskočí.", + "Disable_checking_for_this_file_90018": "Zakázat kontrolu tohoto souboru", + "Disable_size_limitations_on_JavaScript_projects_6162": "Zakázat omezení velikosti v projektech JavaScriptu", + "Disable_strict_checking_of_generic_signatures_in_function_types_6185": "Zakáže striktní kontroly generických signatur v typech funkcí.", + "Disallow_inconsistently_cased_references_to_the_same_file_6078": "Zakažte odkazy na stejný soubor s nekonzistentně použitými malými a velkými písmeny.", + "Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files_6159": "Nepřidávat odkazy se třemi lomítky nebo importované moduly do seznamu kompilovaných souborů", + "Do_not_emit_comments_to_output_6009": "Negenerovat komentáře pro výstup", + "Do_not_emit_declarations_for_code_that_has_an_internal_annotation_6056": "Negenerovat deklarace pro kód s anotací @internal", + "Do_not_emit_outputs_6010": "Negenerovat výstupy", + "Do_not_emit_outputs_if_any_errors_were_reported_6008": "Negenerovat výstupy, pokud byly oznámeny chyby", + "Do_not_emit_use_strict_directives_in_module_output_6112": "Negenerujte direktivy use strict ve výstupu modulu.", + "Do_not_erase_const_enum_declarations_in_generated_code_6007": "Nemazat deklarace konstantního výčtu v generovaném kódu", + "Do_not_generate_custom_helper_functions_like_extends_in_compiled_output_6157": "Negenerovat v kompilovaném výstupu vlastní pomocné funkce jako __extends", + "Do_not_include_the_default_library_file_lib_d_ts_6158": "Nezahrnovat výchozí soubor knihovny (lib.d.ts)", + "Do_not_report_errors_on_unreachable_code_6077": "Neoznamují se chyby v nedosažitelném kódu.", + "Do_not_report_errors_on_unused_labels_6074": "Neoznamují se chyby v nepoužívaných popiscích.", + "Do_not_resolve_the_real_path_of_symlinks_6013": "Nepřekládat skutečnou cestu symbolických odkazů", + "Do_not_truncate_error_messages_6165": "Nezkracovat chybové zprávy", + "Duplicate_declaration_0_2718": "Duplicitní deklarace pro: {0}", + "Duplicate_function_implementation_2393": "Duplicitní implementace funkce", + "Duplicate_identifier_0_2300": "Duplicitní identifikátor {0}", + "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_2441": "Duplicitní identifikátor {0}. Kompilátor si vyhrazuje název {1} v oboru nejvyšší úrovně pro daný modul.", + "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_func_2529": "Duplicitní identifikátor {0}. Kompilátor rezervuje název {1} v oboru nejvyšší úrovně modulu, který obsahuje asynchronní funkce.", + "Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions_2520": "Duplicitní identifikátor {0}. Kompilátor používá deklaraci {1} pro podporu asynchronních funkcí.", + "Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters_2396": "Duplicitní identifikátor arguments. Kompilátor pomocí identifikátoru arguments inicializuje parametry rest.", + "Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_me_2543": "Duplicitní identifikátor _newTarget. Kompilátor používá deklaraci proměnné _newTarget k zachycení odkazu na metavlastnost new.target.", + "Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference_2401": "Duplicitní identifikátor _super. Kompilátor pomocí identifikátoru _super zaznamenává odkaz na základní třídu.", + "Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference_2399": "Duplicitní identifikátor _this. Kompilátor pomocí deklarace proměnné _this zaznamenává odkaz na příkaz this.", + "Duplicate_label_0_1114": "Duplicitní popisek {0}", + "Duplicate_number_index_signature_2375": "Duplicitní podpis číselného indexu", + "Duplicate_string_index_signature_2374": "Duplicitní signatury řetězcového indexu", + "Dynamic_import_cannot_have_type_arguments_1326": "Dynamický import nemůže mít argumenty typu.", + "Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext_1323": "Dynamický import se podporuje jenom tehdy, když je příznak --module nastavený na commonjs nebo esNext.", + "Dynamic_import_must_have_one_specifier_as_an_argument_1324": "Dynamický import musí mít jako argument jeden specifikátor.", + "Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036": "Specifikátor dynamického importu musí být typu string, ale tady má typ {0}.", + "Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015": "Element má implicitně typ any, protože indexový výraz není typu number.", + "Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature_7017": "Element má implicitně typ any, protože typ {0} nemá žádnou signaturu indexu.", + "Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files_6164": "Vygeneruje na začátku výstupních souborů značku pořadí bajtů ve formátu UTF-8.", + "Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file_6151": "Vygeneruje jediný soubor se zdrojovými mapováními namísto samostatného souboru.", + "Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap__6152": "Vygeneruje zdroj spolu se zdrojovými mapováními v jednom souboru. Vyžaduje, aby byla nastavená možnost --inlineSourceMap nebo --sourceMap.", + "Enable_all_strict_type_checking_options_6180": "Povolí všechny možnosti striktní kontroly typů.", + "Enable_project_compilation_6302": "Povolit kompilování projektu", + "Enable_strict_checking_of_function_types_6186": "Povolí striktní kontrolu typů funkcí.", + "Enable_strict_checking_of_property_initialization_in_classes_6187": "Povolí striktní kontrolu inicializace vlastností ve třídách.", + "Enable_strict_null_checks_6113": "Povolte striktní kontroly hodnot null.", + "Enable_tracing_of_the_name_resolution_process_6085": "Povolte trasování procesu překladu IP adres.", + "Enable_verbose_logging_6366": "Povolit podrobné protokolování", + "Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for__7037": "Povolí interoperabilitu generování mezi moduly CommonJS a ES prostřednictvím vytváření objektů oboru názvů pro všechny importy. Implikuje allowSyntheticDefaultImports.", + "Enables_experimental_support_for_ES7_async_functions_6068": "Zapíná experimentální podporu asynchronních funkcí ES7.", + "Enables_experimental_support_for_ES7_decorators_6065": "Povolí experimentální podporu pro dekorátory ES7.", + "Enables_experimental_support_for_emitting_type_metadata_for_decorators_6066": "Povolí experimentální podporu pro generování metadat typu pro dekorátory.", + "Enum_0_used_before_its_declaration_2450": "Výčet {0} se používá dříve, než se deklaruje.", + "Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations_2567": "Deklarace výčtu jdou sloučit jenom s oborem názvů nebo jinými deklaracemi výčtu.", + "Enum_declarations_must_all_be_const_or_non_const_2473": "Všechny deklarace výčtu musí být konstantní nebo nekonstantní.", + "Enum_member_expected_1132": "Očekává se člen výčtu.", + "Enum_member_must_have_initializer_1061": "Člen výčtu musí mít inicializátor.", + "Enum_name_cannot_be_0_2431": "Název výčtu nemůže být {0}.", + "Enum_type_0_has_members_with_initializers_that_are_not_literals_2535": "Typ výčtu {0} má členy s inicializátory, které nejsou literály.", + "Examples_Colon_0_6026": "Příklady: {0}", + "Excessive_stack_depth_comparing_types_0_and_1_2321": "Nadměrná hloubka zásobníku při porovnávání typů {0} a {1}", + "Expected_0_1_type_arguments_provide_these_with_an_extends_tag_8027": "Očekávané argumenty typu {0}–{1}; zadejte je se značkou @extends.", + "Expected_0_arguments_but_got_1_2554": "Očekával se tento počet argumentů: {0}. Počet předaných argumentů: {1}", + "Expected_0_arguments_but_got_1_or_more_2556": "Očekával se tento počet argumentů: {0}. Počet předaných argumentů: {1} nebo více.", + "Expected_0_type_arguments_but_got_1_2558": "Očekávaly se argumenty typu {0}, ale předaly se argumenty typu {1}.", + "Expected_0_type_arguments_provide_these_with_an_extends_tag_8026": "Očekávané argumenty typu {0}; zadejte je se značkou @extends.", + "Expected_at_least_0_arguments_but_got_1_2555": "Očekával se aspoň tento počet argumentů: {0}. Počet předaných argumentů: {1}", + "Expected_at_least_0_arguments_but_got_1_or_more_2557": "Očekával se aspoň tento počet argumentů: {0}. Počet předaných argumentů: {1} nebo více.", + "Expected_corresponding_JSX_closing_tag_for_0_17002": "Očekávala se odpovídající ukončující značka JSX pro {0}.", + "Expected_corresponding_closing_tag_for_JSX_fragment_17015": "Pro fragment JSX se očekávala odpovídající uzavírací značka.", + "Expected_type_of_0_field_in_package_json_to_be_string_got_1_6105": "Očekávaný typ pole {0} v souboru package.json byl string, obdržený je {1}.", + "Experimental_Options_6177": "Experimentální možnosti", + "Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_t_1219": "Experimentální podpora dekorátorů je funkce, která se v budoucím vydání změní. Toto upozornění odstraníte nastavením možnosti experimentalDecorators.", + "Explicitly_specified_module_resolution_kind_Colon_0_6087": "Explicitně zadaný druh překladu modulu: {0}.", + "Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or__1203": "Přiřazení exportu nelze použít, pokud jsou cílem moduly ECMAScript. Zkuste místo toho použít export default nebo jiný formát modulu.", + "Export_assignment_is_not_supported_when_module_flag_is_system_1218": "Když má příznak --module hodnotu system, nepodporuje se přiřazení exportu.", + "Export_declaration_conflicts_with_exported_declaration_of_0_2484": "Konflikty deklarace exportu s exportovanou deklarací {0}", + "Export_declarations_are_not_permitted_in_a_namespace_1194": "Deklarace exportu nejsou povolené v oboru názvů.", + "Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_2656": "Soubor exportovaného úseku kódu externího balíčku {0} není modul. Kontaktuje prosím autora balíčku, aby aktualizoval jeho definici.", + "Exported_external_package_typings_file_cannot_contain_tripleslash_references_Please_contact_the_pack_2654": "Soubor exportovaného úseku kódu externího balíčku nemůže obsahovat odkazy se třemi lomítky. Kontaktuje prosím autora balíčku, aby aktualizoval jeho definici.", + "Exported_type_alias_0_has_or_is_using_private_name_1_4081": "Alias exportovaného typu {0} má nebo používá privátní název {1}.", + "Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4023": "Exportovaná proměnná {0} má nebo používá název {1} z externího modulu {2}, ale nedá se pojmenovat.", + "Exported_variable_0_has_or_is_using_name_1_from_private_module_2_4024": "Exportovaná proměnná {0} má nebo používá název {1} z privátního modulu {2}.", + "Exported_variable_0_has_or_is_using_private_name_1_4025": "Exportovaná proměnná {0} má nebo používá privátní název {1}.", + "Exports_and_export_assignments_are_not_permitted_in_module_augmentations_2666": "Exporty a přiřazení exportů nejsou povolené v rozšířeních modulů.", + "Expression_expected_1109": "Očekával se výraz.", + "Expression_or_comma_expected_1137": "Očekával se výraz nebo čárka.", + "Expression_resolves_to_super_that_compiler_uses_to_capture_base_class_reference_2402": "Výraz se přeloží na identifikátor _super, pomocí kterého kompilátor zaznamenává odkaz na základní třídu.", + "Expression_resolves_to_variable_declaration_0_that_compiler_uses_to_support_async_functions_2521": "Výraz se přeloží na deklaraci proměnné {0}, kterou kompilátor používá pro podporu asynchronních funkcí.", + "Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta__2544": "Výraz se vyhodnocuje na deklaraci proměnné _newTarget, kterou kompilátor používá k zachycení odkazu na metavlastnost new.target.", + "Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference_2400": "Výraz se přeloží na deklaraci proměnné _this, pomocí které kompilátor zaznamenává odkazy na příkaz this.", + "Extract_constant_95006": "Extrahovat konstantu", + "Extract_function_95005": "Extrahovat funkci", + "Extract_to_0_in_1_95004": "Extrahovat do {0} v {1}", + "Extract_to_0_in_1_scope_95008": "Extrahovat do {0} v oboru {1}", + "Extract_to_0_in_enclosing_scope_95007": "Extrahovat do {0} v nadřazeném oboru", + "FILE_6035": "SOUBOR", + "FILE_OR_DIRECTORY_6040": "SOUBOR NEBO ADRESÁŘ", + "Failed_to_parse_file_0_Colon_1_5014": "Nepovedlo se parsovat soubor {0}: {1}.", + "Fallthrough_case_in_switch_7029": "Případ Fallthrough v příkazu switch", + "File_0_does_not_exist_6096": "Soubor {0} neexistuje.", + "File_0_exist_use_it_as_a_name_resolution_result_6097": "Soubor {0} existuje – použijte ho jako výsledek překladu IP adres.", + "File_0_has_an_unsupported_extension_so_skipping_it_6081": "Soubor {0} má nepodporovanou příponu, a proto se přeskočí.", + "File_0_has_unsupported_extension_The_only_supported_extensions_are_1_6054": "Soubor {0} má nepodporovanou příponu. Jediné podporované přípony jsou {1}.", + "File_0_is_not_a_module_2306": "Soubor {0} není modul.", + "File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern_6307": "Soubor {0} se nenachází v seznamu souborů projektu. Projekty musí uvádět všechny soubory nebo používat vzor include.", + "File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files_6059": "Soubor {0} není pod kořenovým adresářem rootDir {1}. Očekává se, že rootDir bude obsahovat všechny zdrojové soubory.", + "File_0_not_found_6053": "Soubor {0} se nenašel.", + "File_change_detected_Starting_incremental_compilation_6032": "Zjistila se změna souboru. Spouští se přírůstková kompilace...", + "File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module_80001": "Soubor je modul CommonJS; může se převést na modul ES6.", + "File_name_0_differs_from_already_included_file_name_1_only_in_casing_1149": "Název souboru {0} se od už zahrnutého názvu souboru {1} liší jenom velikostí písmen.", + "File_name_0_has_a_1_extension_stripping_it_6132": "Název souboru {0} má příponu {1} – odstraňuje se", + "File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildca_5065": "Specifikace souboru nemůže obsahovat nadřazený adresář (..), který se vyskytuje za rekurzivním zástupným znakem adresáře (**): {0}.", + "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010": "Specifikace souboru nemůže končit rekurzivním zástupným znakem adresáře (**): {0}.", + "Fix_all_detected_spelling_errors_95026": "Opravit všechny zjištěné pravopisné chyby", + "Found_0_errors_Watching_for_file_changes_6194": "Byl nalezen tento počet chyb: {0}. Sledují se změny souborů.", + "Found_1_error_Watching_for_file_changes_6193": "Byla nalezena 1 chyba. Sledují se změny souborů.", + "Found_package_json_at_0_6099": "Soubor package.json se našel v {0}.", + "Found_package_json_at_0_Package_ID_is_1_6190": "V {0} se našel soubor package.json. ID balíčku je {1}.", + "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_1250": "Deklarace funkcí nejsou povolené uvnitř bloků ve striktním režimu, pokud je cíl ES3 nebo ES5.", + "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_d_1251": "Deklarace funkcí nejsou povolené uvnitř bloků ve striktním režimu, pokud je cíl ES3 nebo ES5. Definice tříd jsou automaticky ve striktním režimu.", + "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_1252": "Deklarace funkcí nejsou povolené uvnitř bloků ve striktním režimu, pokud je cíl ES3 nebo ES5. Moduly jsou automaticky ve striktním režimu.", + "Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type_7011": "Výraz funkce s chybějící anotací návratového typu má implicitně návratový typ {0}.", + "Function_implementation_is_missing_or_not_immediately_following_the_declaration_2391": "Implementace funkce chybí nebo nenásleduje hned po deklaraci.", + "Function_implementation_name_must_be_0_2389": "Název implementace funkce musí být {0}.", + "Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_ref_7024": "Funkce implicitně obsahuje návratový typ any, protože neobsahuje anotaci návratového typu a odkazuje se na ni přímo nebo nepřímo v jednom z jejích návratových výrazů.", + "Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined_2366": "Ve funkci chybí koncový návratový příkaz a návratový typ neobsahuje undefined.", + "Function_overload_must_be_static_2387": "Přetížení funkce musí být statické.", + "Function_overload_must_not_be_static_2388": "Přetížení funkce nesmí být statické.", + "Generate_get_and_set_accessors_95046": "Generovat přístupové objekty get a set", + "Generates_a_sourcemap_for_each_corresponding_d_ts_file_6000": "Pro každý odpovídající soubor .d.ts vygeneruje sourcemap.", + "Generates_corresponding_d_ts_file_6002": "Generuje odpovídající soubor .d.ts.", + "Generates_corresponding_map_file_6043": "Generuje odpovídající soubor .map.", + "Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_typ_7025": "Generátor má implicitně typ {0}, protože nevydává žádné hodnoty. Zvažte možnost přidání návratového typu.", + "Generators_are_not_allowed_in_an_ambient_context_1221": "Generátory nejsou v ambientním kontextu povolené.", + "Generators_are_only_available_when_targeting_ECMAScript_2015_or_higher_1220": "Generátory jsou dostupné jenom při cílení na ECMAScript 2015 nebo novější.", + "Generic_type_0_requires_1_type_argument_s_2314": "Obecný typ {0} vyžaduje argumenty typu {1}.", + "Generic_type_0_requires_between_1_and_2_type_arguments_2707": "Obecný typ {0} vyžaduje konkrétní počet argumentů ({1} až {2}).", + "Generic_type_instantiation_is_excessively_deep_and_possibly_infinite_2550": "Vytvoření instance generického typu jde příliš hluboko a může být nekonečné.", + "Getter_and_setter_accessors_do_not_agree_in_visibility_2379": "Viditelnost přístupových objektů getter a setter vzájemně nesouhlasí.", + "Global_module_exports_may_only_appear_at_top_level_1316": "Exporty globálního modulu se můžou objevit jenom na nejvyšší úrovni.", + "Global_module_exports_may_only_appear_in_declaration_files_1315": "Exporty globálního modulu se můžou objevit jenom v souborech deklarací.", + "Global_module_exports_may_only_appear_in_module_files_1314": "Exporty globálního modulu se můžou objevit jenom v souborech modulů.", + "Global_type_0_must_be_a_class_or_interface_type_2316": "Globální typ {0} musí být typu třída nebo rozhraní.", + "Global_type_0_must_have_1_type_parameter_s_2317": "Globální typ {0} musí mít parametry typu {1}.", + "Hexadecimal_digit_expected_1125": "Očekávala se šestnáctková číslice.", + "Identifier_expected_0_is_a_reserved_word_in_strict_mode_1212": "Očekával se identifikátor. Ve striktním režimu je {0} rezervované slovo.", + "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_stric_1213": "Očekával se identifikátor. Ve striktním režimu je {0} rezervované slovo. Definice tříd jsou automaticky ve striktním režimu.", + "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode_1214": "Očekával se identifikátor. Ve striktním režimu je {0} rezervované slovo. Moduly jsou automaticky ve striktním režimu.", + "Identifier_expected_1003": "Očekával se identifikátor.", + "Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules_1216": "Očekává se identifikátor. __esModule je při transformaci modulů ECMAScript rezervované jako označení exportu.", + "Ignore_this_error_message_90019": "Ignorovat tuto chybovou zprávu", + "Implement_all_inherited_abstract_classes_95040": "Implementovat všechny zděděné abstraktní třídy", + "Implement_all_unimplemented_interfaces_95032": "Implementovat všechna neimplementovaná rozhraní", + "Implement_inherited_abstract_class_90007": "Implementovat zděděnou abstraktní třídu", + "Implement_interface_0_90006": "Implementovat rozhraní {0}", + "Implements_clause_of_exported_class_0_has_or_is_using_private_name_1_4019": "Klauzule implements exportované třídy {0} má nebo používá privátní název {1}.", + "Import_0_from_module_1_90013": "Importovat {0} z modulu {1}", + "Import_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_import_Asterisk_as_1202": "Přiřazení importu nelze použít, pokud jsou cílem moduly ECMAScript. Zkuste místo toho použít import * as ns from \"mod\", import {a} from \"mod\", import d from \"mod\" nebo jiný formát modulu.", + "Import_declaration_0_is_using_private_name_1_4000": "Deklarace importu {0} používá privátní název {1}.", + "Import_declaration_conflicts_with_local_declaration_of_0_2440": "Deklarace importu je v konfliktu s místní deklarací {0}.", + "Import_declarations_in_a_namespace_cannot_reference_a_module_1147": "Deklarace importu v oboru názvů nemůžou odkazovat na modul.", + "Import_emit_helpers_from_tslib_6139": "Importovat pomocné rutiny pro generování z tslib", + "Import_may_be_converted_to_a_default_import_80003": "Import se může převést na výchozí import.", + "Import_name_cannot_be_0_2438": "Název importu nemůže být {0}.", + "Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relati_2439": "Deklarace importu nebo exportu v deklaraci ambientního modulu nemůže odkazovat na modul pomocí jeho relativního názvu.", + "Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_mod_2667": "Importy nejsou povolené v rozšířeních modulů. Zvažte jejich přesunutí do uzavírajícího externího modulu.", + "In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066": "Inicializátor členu v deklaracích ambientního výčtu musí být konstantní výraz.", + "In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enu_2432": "Ve výčtu s víc deklaracemi může být jenom u jedné deklarace vynechaný inicializátor u prvního elementu výčtu.", + "In_const_enum_declarations_member_initializer_must_be_constant_expression_2474": "V inicializátoru člena deklarací výčtu const musí být konstantní výraz.", + "Include_modules_imported_with_json_extension_6197": "Zahrnout moduly importované s příponou .json", + "Index_signature_in_type_0_only_permits_reading_2542": "Signatura indexu v typu {0} povoluje jen čtení.", + "Index_signature_is_missing_in_type_0_2329": "V typu {0} chybí signatura indexu.", + "Index_signatures_are_incompatible_2330": "Signatury indexu jsou nekompatibilní.", + "Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local_2395": "Jednotlivé deklarace ve sloučené deklaraci {0} musí být všechny exportované nebo všechny místní.", + "Infer_all_types_from_usage_95023": "Odvodit všechny typy z použití", + "Infer_parameter_types_from_usage_95012": "Odvodit typy parametrů z využití", + "Infer_type_of_0_from_usage_95011": "Odvodit typ {0} z využití", + "Initialize_property_0_in_the_constructor_90020": "Inicializovat vlastnost {0} v konstruktoru", + "Initialize_static_property_0_90021": "Inicializovat statickou vlastnost {0}", + "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301": "Inicializátor instance členské proměnné {0} nemůže odkazovat na identifikátor {1} deklarovaný v konstruktoru.", + "Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it_2373": "Inicializátor parametru {0} nemůže odkazovat na identifikátor {1} deklarovaný po něm.", + "Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value_2525": "Inicializátor tomuto elementu vazby neposkytuje žádnou hodnotu. Element vazby nemá žádnou výchozí hodnotu.", + "Initializers_are_not_allowed_in_ambient_contexts_1039": "Inicializátory nejsou povolené v ambientních kontextech.", + "Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file_6070": "Inicializuje projekt TypeScript a vytvoří soubor tsconfig.json.", + "Insert_command_line_options_and_files_from_a_file_6030": "Vložte parametry příkazového řádku a soubory ze souboru.", + "Install_0_95014": "Nainstalovat {0}", + "Install_all_missing_types_packages_95033": "Nainstalovat všechny chybějící balíčky typů", + "Interface_0_cannot_simultaneously_extend_types_1_and_2_2320": "Rozhraní {0} nemůže současně rozšiřovat typ {1} i {2}.", + "Interface_0_incorrectly_extends_interface_1_2430": "Rozhraní {0} nesprávně rozšiřuje rozhraní {1}.", + "Interface_declaration_cannot_have_implements_clause_1176": "Deklarace rozhraní nemůže obsahovat klauzuli implements.", + "Interface_name_cannot_be_0_2427": "Název rozhraní nemůže být {0}.", + "Invalid_character_1127": "Neplatný znak", + "Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augm_2665": "Neplatný název modulu v rozšíření. Modul {0} se převede na netypový modul v {1}, který se nedá rozšířit.", + "Invalid_module_name_in_augmentation_module_0_cannot_be_found_2664": "V rozšíření je neplatný název modulu, modul {0} se nedá najít.", + "Invalid_reference_directive_syntax_1084": "Neplatná syntaxe direktivy reference", + "Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode_1210": "Neplatné použití {0}. Definice tříd jsou automaticky ve striktním režimu.", + "Invalid_use_of_0_Modules_are_automatically_in_strict_mode_1215": "Neplatné použití {0}. Moduly jsou automaticky ve striktním režimu.", + "Invalid_use_of_0_in_strict_mode_1100": "Neplatné použití {0} ve striktním režimu", + "Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name_5067": "Neplatná hodnota pro jsxFactory. {0} není platný identifikátor nebo kvalifikovaný název.", + "Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier_5059": "Neplatná hodnota --reactNamespace. {0} není platný identifikátor.", + "JSDoc_0_1_does_not_match_the_extends_2_clause_8023": "Značka JSDoc @{0} {1} neodpovídá klauzuli extends {2}.", + "JSDoc_0_is_not_attached_to_a_class_8022": "Značka JSDoc @{0} není připojená k třídě.", + "JSDoc_may_only_appear_in_the_last_parameter_of_a_signature_8028": "JSDoc ... se může nacházet jen v posledním parametru signatury.", + "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_8024": "Značka JSDoc @param má název {0}, ale neexistuje žádný parametr s tímto názvem.", + "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_h_8029": "Značka JSDoc @param má název {0}, ale žádný parametr s tímto názvem neexistuje. Musí odpovídat hodnotě arguments, pokud má typ pole.", + "JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags_8021": "Značka JSDoc @typedef by měla mít poznámku k typu nebo by za ní měly následovat značky @property nebo @member.", + "JSDoc_types_can_only_be_used_inside_documentation_comments_8020": "Typy JSDoc se můžou používat jenom v dokumentačních komentářích.", + "JSDoc_types_may_be_moved_to_TypeScript_types_80004": "Typy JSDoc se můžou přesunout na typy TypeScript.", + "JSX_attribute_expected_17003": "Očekával se atribut JSX.", + "JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000": "Atributy JSX musí mít přiřazený neprázdný výraz.", + "JSX_element_0_has_no_corresponding_closing_tag_17008": "Element JSX {0} nemá odpovídající uzavírací značku.", + "JSX_element_attributes_type_0_may_not_be_a_union_type_2600": "Typ atributů elementu JSX {0} nemůže být typ sjednocení.", + "JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property_2607": "Třída elementu JSX nepodporuje atributy, protože nemá vlastnost {0}.", + "JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists_7026": "Element JSX má implicitně typ any, protože neexistuje žádné rozhraní JSX.{0}.", + "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602": "Element JSX má implicitně typ any, protože neexistuje globální typ JSX.Element.", + "JSX_element_type_0_does_not_have_any_construct_or_call_signatures_2604": "Typ elementu JSX {0} nemá žádnou signaturu konstrukce nebo volání.", + "JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements_2605": "Typ elementu JSX {0} není funkce konstruktoru pro elementy JSX.", + "JSX_elements_cannot_have_multiple_attributes_with_the_same_name_17001": "Elementy JSX nemůžou mít víc atributů se stejným názvem.", + "JSX_expressions_must_have_one_parent_element_2657": "Výrazy JSX musí mít jeden nadřazený element.", + "JSX_fragment_has_no_corresponding_closing_tag_17014": "Fragment JSX nemá odpovídající uzavírací značku.", + "JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma_17017": "Při použití vložené direktivy pragma objektu pro vytváření JSX se nepodporuje fragment JSX.", + "JSX_fragment_is_not_supported_when_using_jsxFactory_17016": "Při použití --jsxFactory se nepodporuje fragment JSX.", + "JSX_spread_child_must_be_an_array_type_2609": "Podřízený objekt JSX spread musí být typu pole.", + "Jump_target_cannot_cross_function_boundary_1107": "Cíl odkazu nemůže překročit hranici funkce.", + "KIND_6034": "DRUH", + "LOCATION_6037": "UMÍSTĚNÍ", + "Language_service_is_disabled_9004": "Služba jazyka je zakázaná.", + "Left_side_of_comma_operator_is_unused_and_has_no_side_effects_2695": "Levá strana operátoru čárky se nepoužívá a nemá žádné vedlejší účinky.", + "Line_break_not_permitted_here_1142": "Na tomto místě se konec řádku nepovoluje.", + "Line_terminator_not_permitted_before_arrow_1200": "Konec řádku před šipkou se nepovoluje.", + "List_of_folders_to_include_type_definitions_from_6161": "Seznam složek, ze kterých se zahrnou definice typů", + "List_of_language_service_plugins_6181": "Seznam modulů plug-in služby jazyka", + "List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime_6168": "Seznam kořenových složek, jejichž kombinovaný obsah představuje strukturu projektu za běhu", + "Loading_0_from_the_root_dir_1_candidate_location_2_6109": "Načítá se {0} z kořenového adresáře {1}, umístění kandidáta {2}.", + "Loading_module_0_from_node_modules_folder_target_file_type_1_6098": "Načítá se modul {0} ze složky node_modules. Cílový typ souboru je {1}.", + "Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1_6095": "Načítá se modul jako soubor/složka, umístění kandidátského modulu: {0}, cílový typ souboru: {1}.", + "Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1_6048": "Národní prostředí musí mít tvar nebo . Třeba {0} nebo {1}.", + "Longest_matching_prefix_for_0_is_1_6108": "Nejdelší odpovídající předpona pro {0} je {1}.", + "Looking_up_in_node_modules_folder_initial_location_0_6125": "Hledání ve složce node_modules, počáteční umístění {0}", + "Make_all_super_calls_the_first_statement_in_their_constructor_95036": "Nastavit všechna volání metody super() prvním příkazem v jejich konstruktoru", + "Make_super_call_the_first_statement_in_the_constructor_90002": "Nastavit volání metody super() jako první příkaz v konstruktoru", + "Mapped_object_type_implicitly_has_an_any_template_type_7039": "Typu mapovaného objektu má implicitně typ šablony any.", + "Member_0_implicitly_has_an_1_type_7008": "Člen {0} má implicitně typ {1}.", + "Merge_conflict_marker_encountered_1185": "Zjistila se značka konfliktu sloučení.", + "Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_d_2652": "Spojená deklarace {0} nemůže obsahovat výchozí deklaraci exportu. Zvažte namísto toho možnost přidat samostatnou deklaraci export default {0}.", + "Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constru_17013": "Metavlastnost {0} je povolená jenom v těle deklarace funkce, výrazu funkce nebo konstruktoru.", + "Method_0_cannot_have_an_implementation_because_it_is_marked_abstract_1245": "Metoda {0} nemůže mít implementaci, protože je označená jako abstraktní.", + "Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4101": "Metoda {0} z exportovaného rozhraní má nebo používá název {1} z privátního modulu {2}.", + "Method_0_of_exported_interface_has_or_is_using_private_name_1_4102": "Metoda {0} z exportovaného rozhraní má nebo používá privátní název {1}.", + "Modifiers_cannot_appear_here_1184": "Tady nejde použít modifikátory.", + "Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_1340": "Modul {0} neodkazuje na typ, ale používá se tady jako typ.", + "Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here_1339": "Modul {0} neodkazuje na hodnotu, ale používá se tady jako hodnota.", + "Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambig_2308": "Modul {0} už exportoval člena s názvem {1}. Zvažte možnost vyřešení nejednoznačnosti explicitním opakováním exportu.", + "Module_0_has_no_default_export_1192": "Modul {0} nemá žádný výchozí export.", + "Module_0_has_no_exported_member_1_2305": "V modulu {0} není žádný exportovaný člen {1}.", + "Module_0_has_no_exported_member_1_Did_you_mean_2_2724": "Modul {0} nemá žádný exportovaný člen {1}. Neměli jste na mysli {2}?", + "Module_0_is_hidden_by_a_local_declaration_with_the_same_name_2437": "Modul {0} je skrytý místní deklarací se stejným názvem.", + "Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct_2497": "Modul {0} se překládá na nemodulovou entitu a nedá se importovat pomocí tohoto konstruktoru.", + "Module_0_uses_export_and_cannot_be_used_with_export_Asterisk_2498": "Modul {0} používá export = a nedá se použít s možností export *.", + "Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified_6145": "Modul {0} se převedl jako ambientní modul deklarovaný v {1}, protože tento soubor nebyl upraven.", + "Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1_6144": "Modul {0} se převedl jako lokálně deklarovaný ambientní modul v souboru {1}.", + "Module_0_was_resolved_to_1_but_jsx_is_not_set_6142": "Modul {0} se přeložil na {1}, není ale nastavená možnost --jsx.", + "Module_Resolution_Options_6174": "Možnosti překladu modulů", + "Module_name_0_matched_pattern_1_6092": "Název modulu {0}, odpovídající vzor {1}", + "Module_name_0_was_not_resolved_6090": "======== Název modulu {0} nebyl přeložen. ========", + "Module_name_0_was_successfully_resolved_to_1_6089": "======== Název modulu {0} byl úspěšně přeložen na {1}. ========", + "Module_resolution_kind_is_not_specified_using_0_6088": "Druh překladu modulu nebyl určen, použije se {0}.", + "Module_resolution_using_rootDirs_has_failed_6111": "Překlad modulu pomocí rootDirs se nepovedl.", + "Move_to_a_new_file_95049": "Přesunout do nového souboru", + "Multiple_consecutive_numeric_separators_are_not_permitted_6189": "Více po sobě jdoucích číselných oddělovačů se nepovoluje.", + "Multiple_constructor_implementations_are_not_allowed_2392": "Víc implementací konstruktoru se nepovoluje.", + "NEWLINE_6061": "NOVÝ ŘÁDEK", + "Named_property_0_of_types_1_and_2_are_not_identical_2319": "Pojmenovaná vlastnost {0} není u typu {1} stejná jako u typu {2}.", + "Namespace_0_has_no_exported_member_1_2694": "Obor názvů {0} nemá žádný exportovaný člen {1}.", + "No_base_constructor_has_the_specified_number_of_type_arguments_2508": "Žádný základní konstruktor nemá zadaný počet argumentů typu.", + "No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2_18003": "V konfiguračním souboru {0} se nenašly žádné vstupy. Pro zahrnutí jsou zadané tyto cesty: {1} a pro vyloučení tyto cesty: {2}.", + "Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2_2515": "Neabstraktní třída {0} neimplementuje zděděného abstraktního člena {1} ze třídy {2}.", + "Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1_2653": "Výraz neabstraktní třídy neimplementuje zděděný abstraktní člen {0} z třídy {1}.", + "Not_all_code_paths_return_a_value_7030": "Ne všechny cesty kódu vracejí hodnotu.", + "Numeric_index_type_0_is_not_assignable_to_string_index_type_1_2413": "Typ číselného indexu {0} se nedá přiřadit k typu indexu řetězce {1}.", + "Numeric_separators_are_not_allowed_here_6188": "Číselné oddělovače tady nejsou povolené.", + "Object_is_of_type_unknown_2571": "Objekt je typu Neznámý.", + "Object_is_possibly_null_2531": "Objekt je pravděpodobně null.", + "Object_is_possibly_null_or_undefined_2533": "Objekt je pravděpodobně null nebo undefined.", + "Object_is_possibly_undefined_2532": "Objekt je pravděpodobně undefined.", + "Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1_2353": "Literál objektu může specifikovat jenom známé vlastnosti a {0} v typu {1} neexistuje.", + "Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_writ_2561": "Literál objektu může určovat jenom známé vlastnosti, ale {0} v typu {1} neexistuje. Chtěli jste zapsat {2}?", + "Object_literal_s_property_0_implicitly_has_an_1_type_7018": "Vlastnost {0} literálu objektu má implicitně typ {1}.", + "Octal_digit_expected_1178": "Očekává se osmičková číslice.", + "Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0_8017": "Osmičkové literální typy musí používat syntaxi ES2015. Použijte syntaxi {0}.", + "Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0_8018": "Osmičkové literály nejsou povolené v inicializátoru členů výčtů. Použijte syntaxi {0}.", + "Octal_literals_are_not_allowed_in_strict_mode_1121": "Osmičkové literály nejsou ve striktním režimu povolené.", + "Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0_1085": "Osmičkové literály nejsou dostupné při cílení na ECMAScript 5 a vyšší. Použijte syntaxi {0}.", + "Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement_1091": "V příkazu for...in se povoluje deklarovat jenom jednu proměnnou.", + "Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement_1188": "V příkazu for...of se povoluje deklarovat jenom jednu proměnnou.", + "Only_a_void_function_can_be_called_with_the_new_keyword_2350": "Klíčovým slovem new se dá volat jenom funkce void.", + "Only_ambient_modules_can_use_quoted_names_1035": "Názvy v uvozovkách můžou mít jenom ambientní moduly.", + "Only_amd_and_system_modules_are_supported_alongside_0_6082": "Spolu s --{0} se podporují jenom moduly amd a system.", + "Only_emit_d_ts_declaration_files_6014": "Bude vydávat jen soubory deklarací .d.ts.", + "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002": "V klauzuli třídy extends se aktuálně podporují jenom identifikátory nebo kvalifikované názvy s volitelnými argumenty typu.", + "Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword_2340": "Prostřednictvím klíčového slova super jsou přístupné jenom veřejné a chráněné metody základní třídy.", + "Operator_0_cannot_be_applied_to_types_1_and_2_2365": "Operátor {0} nejde použít u typů {1} a {2}.", + "Option_0_can_only_be_specified_in_tsconfig_json_file_6064": "Možnost {0} je možné zadat jenom v souboru tsconfig.json.", + "Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided_5051": "Možnost {0} jde použít jenom při zadání možnosti --inlineSourceMap nebo možnosti --sourceMap.", + "Option_0_cannot_be_specified_with_option_1_5053": "Možnosti {0} a {1} nejde zadat zároveň.", + "Option_0_cannot_be_specified_without_specifying_option_1_5052": "Možnost {0} nejde zadat bez možnosti {1}.", + "Option_0_cannot_be_specified_without_specifying_option_1_or_option_2_5069": "Možnost {0} nejde zadat bez možnosti {1} nebo {2}.", + "Option_0_should_have_array_of_strings_as_a_value_6103": "Hodnota možnosti {0} by měla být pole řetězců.", + "Option_build_must_be_the_first_command_line_argument_6369": "Možnost --build musí být prvním argumentem příkazového řádku.", + "Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES_5047": "Možnost isolatedModules jde použít jenom v případě, že je poskytnutá možnost --module nebo že možnost target je ES2015 nebo vyšší verze.", + "Option_paths_cannot_be_used_without_specifying_baseUrl_option_5060": "Možnost paths se nedá použít bez zadání možnosti --baseUrl.", + "Option_project_cannot_be_mixed_with_source_files_on_a_command_line_5042": "Možnost project se na příkazovém řádku nedá kombinovat se zdrojovým souborem.", + "Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070": "Možnost --resolveJsonModule se nedá zadat bez strategie překladu modulu node.", + "Options_0_and_1_cannot_be_combined_6370": "Možnosti {0} a {1} nejde kombinovat.", + "Options_Colon_6027": "Možnosti:", + "Output_directory_for_generated_declaration_files_6166": "Výstupní adresář pro vygenerované soubory deklarace", + "Output_file_0_from_project_1_does_not_exist_6309": "Výstupní soubor {0} z projektu {1} neexistuje.", + "Output_file_0_has_not_been_built_from_source_file_1_6305": "Výstupní soubor {0} se nesestavil ze zdrojového souboru {1}.", + "Overload_signature_is_not_compatible_with_function_implementation_2394": "Signatura přetížení není kompatibilní s implementací funkce.", + "Overload_signatures_must_all_be_abstract_or_non_abstract_2512": "Signatury přetížení musí být všechny abstraktní nebo neabstraktní.", + "Overload_signatures_must_all_be_ambient_or_non_ambient_2384": "Signatury přetížení musí být všechny ambientní nebo neambientní.", + "Overload_signatures_must_all_be_exported_or_non_exported_2383": "Signatury přetížení musí být všechny exportované nebo neexportované.", + "Overload_signatures_must_all_be_optional_or_required_2386": "Signatury přetížení musí být všechny nepovinné nebo povinné.", + "Overload_signatures_must_all_be_public_private_or_protected_2385": "Signatury přetížení musí být všechny veřejné, privátní nebo chráněné.", + "Parameter_0_cannot_be_referenced_in_its_initializer_2372": "Parametr {0} se nedá odkazovat v jeho vlastním inicializátoru.", + "Parameter_0_implicitly_has_an_1_type_7006": "Parametr {0} má implicitně typ {1}.", + "Parameter_0_is_not_in_the_same_position_as_parameter_1_1227": "Parametr {0} není na stejné pozici jako parametr {1}.", + "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4066": "Parametr {0} signatury volání z exportovaného rozhraní má nebo používá název {1} z privátního modulu {2}.", + "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4067": "Parametr {0} signatury volání z exportovaného rozhraní má nebo používá privátní název {1}.", + "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_can_4061": "Parametr {0} konstruktoru z exportované třídy má nebo používá název {1} z externího modulu {2}, ale nedá se pojmenovat.", + "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2_4062": "Parametr {0} konstruktoru z exportované třídy má nebo používá název {1} z privátního modulu {2}.", + "Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1_4063": "Parametr {0} konstruktoru z exportované třídy má nebo používá privátní název {1}.", + "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_mod_4064": "Parametr {0} signatury konstruktoru z exportovaného rozhraní má nebo používá název {1} z privátního modulu {2}.", + "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4065": "Parametr {0} signatury konstruktoru z exportovaného rozhraní má nebo používá privátní název {1}.", + "Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4076": "Parametr {0} exportované funkce má nebo používá název {1} z externího modulu {2}, ale nedá se pojmenovat.", + "Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2_4077": "Parametr {0} exportované funkce má nebo používá název {1} z privátního modulu {2}.", + "Parameter_0_of_exported_function_has_or_is_using_private_name_1_4078": "Parametr {0} exportované funkce má nebo používá privátní název {1}.", + "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4091": "Parametr {0} signatury indexu z exportovaného rozhraní má nebo používá název {1} z privátního modulu {2}.", + "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1_4092": "Parametr {0} signatury indexu z exportovaného rozhraní má nebo používá privátní název {1}.", + "Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4074": "Parametr {0} metody z exportovaného rozhraní má nebo používá název {1} z privátního modulu {2}.", + "Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4075": "Parametr {0} metody z exportovaného rozhraní má nebo používá privátní název {1}.", + "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_c_4071": "Parametr {0} veřejné metody z exportované třídy má nebo používá název {1} z externího modulu {2}, ale nedá se pojmenovat.", + "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4072": "Parametr {0} veřejné metody z exportované třídy má nebo používá název {1} z privátního modulu {2}.", + "Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4073": "Parametr {0} veřejné metody z exportované třídy má nebo používá privátní název {1}.", + "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module__4068": "Parametr {0} veřejné statické metody z exportované třídy má nebo používá název {1} z externího modulu {2}, ale nedá se pojmenovat.", + "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4069": "Parametr {0} veřejné statické metody z exportované třídy má nebo používá název {1} z privátního modulu {2}.", + "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4070": "Parametr {0} veřejné statické metody z exportované třídy má nebo používá privátní název {1}.", + "Parameter_cannot_have_question_mark_and_initializer_1015": "Parametr nemůže obsahovat otazník a inicializátor.", + "Parameter_declaration_expected_1138": "Očekává se deklarace parametru.", + "Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2_4036": "Typ parametru veřejné metody setter {0} z exportované třídy má nebo používá název {1} z privátního modulu {2}.", + "Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_private_name_1_4037": "Typ parametru veřejné metody setter {0} z exportované třídy má nebo používá privátní název {1}.", + "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_name_1_from_private_mod_4034": "Typ parametru veřejné statické metody setter {0} z exportované třídy má nebo používá název {1} z privátního modulu {2}.", + "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1_4035": "Typ parametru veřejné statické metody setter {0} z exportované třídy má nebo používá privátní název {1}.", + "Parse_in_strict_mode_and_emit_use_strict_for_each_source_file_6141": "Parsovat ve striktním režimu a generovat striktní používání pro každý zdrojový soubor", + "Pattern_0_can_have_at_most_one_Asterisk_character_5061": "Vzor {0} může obsahovat nanejvýš jeden znak * (hvězdička).", + "Prefix_0_with_an_underscore_90025": "Předpona {0} s podtržítkem", + "Prefix_all_unused_declarations_with_where_possible_95025": "Přidat příponu _ ke všem nepoužívaným deklaracím tam, kde je to možné", + "Print_names_of_files_part_of_the_compilation_6155": "Část kompilace, při které se vypisují názvy souborů", + "Print_names_of_generated_files_part_of_the_compilation_6154": "Část kompilace, při které se vypisují názvy generovaných souborů", + "Print_the_compiler_s_version_6019": "Vytisknout verzi kompilátoru", + "Print_this_message_6017": "Vytisknout tuto zprávu", + "Project_0_can_t_be_built_because_its_dependency_1_has_errors_6363": "Projekt {0} nejde sestavit, protože jeho závislost {1} obsahuje chyby.", + "Project_0_is_out_of_date_because_its_dependency_1_is_out_of_date_6353": "Projekt {0} je zastaralý, protože jeho závislost {1} je zastaralá.", + "Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2_6350": "Projekt {0} je zastaralý, protože nejstarší výstup {1} je starší než nejnovější vstup {2}.", + "Project_0_is_out_of_date_because_output_file_1_does_not_exist_6352": "Projekt {0} je zastaralý, protože výstupní soubor {1} neexistuje.", + "Project_0_is_up_to_date_6361": "Projekt {0} je aktuální.", + "Project_0_is_up_to_date_because_newest_input_1_is_older_than_oldest_output_2_6351": "Projekt {0} je aktuální, protože nejnovější vstup {1} je starší než nejstarší výstup {2}.", + "Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies_6354": "Projekt {0} je aktualizovaný soubory .d.ts z jeho závislostí.", + "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202": "Odkazy projektu nemůžou tvořit cyklický graf. Zjistil se cyklus: {0}", + "Projects_in_this_build_Colon_0_6355": "Projekty v tomto sestavení: {0}", + "Projects_to_reference_6300": "Projekty, které se mají odkazovat", + "Property_0_does_not_exist_on_const_enum_1_2479": "Vlastnost {0} ve výčtu const {1} neexistuje.", + "Property_0_does_not_exist_on_type_1_2339": "Vlastnost {0} v typu {1} neexistuje.", + "Property_0_does_not_exist_on_type_1_Did_you_forget_to_use_await_2570": "Vlastnost {0} v typu {1} neexistuje. Nezapomněli jste použít await?", + "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551": "Vlastnost {0} v typu {1} neexistuje. Měli jste na mysli {2}?", + "Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1_2546": "Vlastnost {0} má konfliktní deklarace a v typu {1} není přístupná.", + "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor_2564": "Vlastnost {0} nemá žádný inicializátor a není jednoznačně přiřazena v konstruktoru.", + "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033": "Vlastnost {0} má implicitně typ any, protože její přistupující objekt get nemá anotaci návratového typu.", + "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032": "Vlastnost {0} má implicitně typ any, protože její přistupující objekt set nemá anotaci parametrového typu.", + "Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2_2416": "Vlastnost {0} v typu {1} nejde přiřadit ke stejné vlastnosti v základním typu {2}.", + "Property_0_in_type_1_is_not_assignable_to_type_2_2603": "Vlastnost {0} v typu {1} nejde přiřadit typu {2}.", + "Property_0_is_declared_but_its_value_is_never_read_6138": "Deklaruje se vlastnost {0}, ale její hodnota se vůbec nečte.", + "Property_0_is_incompatible_with_index_signature_2530": "Vlastnost {0} není kompatibilní se signaturou indexu.", + "Property_0_is_missing_in_type_1_2324": "Vlastnost {0} v typu {1} chybí.", + "Property_0_is_optional_in_type_1_but_required_in_type_2_2327": "Vlastnost {0} je v typu {1} nepovinná, ale vyžaduje se v typu {2}.", + "Property_0_is_private_and_only_accessible_within_class_1_2341": "Vlastnost {0} je privátní a dostupná jenom ve třídě {1}.", + "Property_0_is_private_in_type_1_but_not_in_type_2_2325": "Vlastnost {0} je v typu {1} privátní, ale v typu {2} ne.", + "Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1_2446": "Vlastnost {0} je chráněná a je dostupná jenom přes instanci třídy {1}.", + "Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses_2445": "Vlastnost {0} je chráněná a je dostupná jenom ve třídě {1} a jejích podtřídách.", + "Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2_2443": "Vlastnost {0} je chráněná, ale typ {1} není třída odvozená od {2}.", + "Property_0_is_protected_in_type_1_but_public_in_type_2_2444": "Vlastnost {0} je v typu {1} chráněná, ale v typu {2} veřejná.", + "Property_0_is_used_before_being_assigned_2565": "Vlastnost {0} je použitá před přiřazením.", + "Property_0_of_JSX_spread_attribute_is_not_assignable_to_target_property_2606": "Vlastnost {0} rozšířeného atributu JSX nejde přiřadit cílové vlastnosti.", + "Property_0_of_exported_class_expression_may_not_be_private_or_protected_4094": "Vlastnost {0} exportovaného výrazu třídy nesmí být privátní nebo chráněná.", + "Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4032": "Vlastnost {0} exportovaného rozhraní má nebo používá název {1} z privátního modulu {2}.", + "Property_0_of_exported_interface_has_or_is_using_private_name_1_4033": "Vlastnost {0} exportovaného rozhraní má nebo používá privátní název {1}.", + "Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2_2412": "Vlastnost {0} typu {1} se nedá přiřadit k typu číselného indexu {2}.", + "Property_0_of_type_1_is_not_assignable_to_string_index_type_2_2411": "Vlastnost {0} typu {1} se nedá přiřadit k typu indexu řetězce {2}.", + "Property_assignment_expected_1136": "Očekává se přiřazení vlastnosti.", + "Property_destructuring_pattern_expected_1180": "Očekává se vzor destruktoru vlastnosti.", + "Property_or_signature_expected_1131": "Očekává se vlastnost nebo podpis.", + "Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_li_1328": "Hodnota vlastnosti může být jenom řetězcový literál, číselný literál, true, false, null, literál objektu nebo literál pole.", + "Provide_full_support_for_iterables_in_for_of_spread_and_destructuring_when_targeting_ES5_or_ES3_6179": "Při cílení na ES5 nebo ES3 poskytněte plnou podporu iterovatelných proměnných ve for-of, rozšíření a destrukturování.", + "Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4098": "Veřejná metoda {0} z exportované třídy má nebo používá název {1} z externího modulu {2}, ale nedá se pojmenovat.", + "Public_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4099": "Veřejná metoda {0} z exportované třídy má nebo používá název {1} z privátního modulu {2}.", + "Public_method_0_of_exported_class_has_or_is_using_private_name_1_4100": "Veřejná metoda {0} z exportované třídy má nebo používá privátní název {1}.", + "Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_name_4029": "Veřejná vlastnost {0} exportované třídy má nebo používá název {1} z externího modulu {2}, ale nedá se pojmenovat.", + "Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4030": "Veřejná vlastnost {0} exportované třídy má nebo používá název {1} z privátního modulu {2}.", + "Public_property_0_of_exported_class_has_or_is_using_private_name_1_4031": "Veřejná vlastnost {0} exportované třídy má nebo používá privátní název {1}.", + "Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_4095": "Veřejná statická metoda {0} z exportované třídy má nebo používá název {1} z externího modulu {2}, ale nedá se pojmenovat.", + "Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4096": "Veřejná statická metoda {0} z exportované třídy má nebo používá název {1} z privátního modulu {2}.", + "Public_static_method_0_of_exported_class_has_or_is_using_private_name_1_4097": "Veřejná statická metoda {0} z exportované třídy má nebo používá privátní název {1}.", + "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot__4026": "Veřejná statická vlastnost {0} exportované třídy má nebo používá název {1} z externího modulu {2}, ale nedá se pojmenovat.", + "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4027": "Veřejná statická vlastnost {0} exportované třídy má nebo používá název {1} z privátního modulu {2}.", + "Public_static_property_0_of_exported_class_has_or_is_using_private_name_1_4028": "Veřejná statická vlastnost {0} exportované třídy má nebo používá privátní název {1}.", + "Raise_error_on_expressions_and_declarations_with_an_implied_any_type_6052": "Vyvolat chybu u výrazů a deklarací s implikovaným typem any", + "Raise_error_on_this_expressions_with_an_implied_any_type_6115": "Vyvolá chybu u výrazů this s implikovaným typem any.", + "Redirect_output_structure_to_the_directory_6006": "Přesměrování výstupní struktury do adresáře", + "Referenced_project_0_must_have_setting_composite_Colon_true_6306": "Odkazovaný projekt {0} musí mít nastavení \"composite\": true.", + "Remove_all_unreachable_code_95051": "Odebrat veškerý nedosažitelný kód", + "Remove_all_unused_labels_95054": "Odebrat všechny nepoužívané popisky", + "Remove_braces_from_arrow_function_95060": "Odebrat složené závorky z funkce šipky", + "Remove_declaration_for_Colon_0_90004": "Odebrat deklaraci pro {0}", + "Remove_destructuring_90009": "Odebrat destrukci", + "Remove_import_from_0_90005": "Odebrat import z {0}", + "Remove_unreachable_code_95050": "Odebrat nedosažitelný kód", + "Remove_unused_label_95053": "Odebrat nepoužitý popisek", + "Remove_variable_statement_90010": "Odebrat příkaz proměnné", + "Replace_import_with_0_95015": "Nahradí import použitím: {0}.", + "Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "Oznámí se chyba, když některé cesty kódu ve funkci nevracejí hodnotu.", + "Report_errors_for_fallthrough_cases_in_switch_statement_6076": "Oznámí se chyby v případech fallthrough v příkazu switch.", + "Report_errors_in_js_files_8019": "Ohlásit chyby v souborech .js", + "Report_errors_on_unused_locals_6134": "Umožňuje nahlásit chyby u nevyužitých místních hodnot.", + "Report_errors_on_unused_parameters_6135": "Umožňuje nahlásit chyby u nevyužitých parametrů.", + "Required_type_parameters_may_not_follow_optional_type_parameters_2706": "Požadované parametry typu nemůžou být až za volitelnými parametry typu.", + "Resolution_for_module_0_was_found_in_cache_from_location_1_6147": "Překlad pro modul {0} se našel v mezipaměti umístění {1}.", + "Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols_6195": "keyof překládejte jen na názvy vlastností s hodnotami typu string (ne čísla ani symboly).", + "Resolving_from_node_modules_folder_6118": "Překládá se ze složky node_modules...", + "Resolving_module_0_from_1_6086": "======== Překládá se modul {0} z {1}. ========", + "Resolving_module_name_0_relative_to_base_url_1_2_6094": "Překládá se název modulu {0} relativní k základní adrese URL {1}–{2}.", + "Resolving_real_path_for_0_result_1_6130": "Překládá se skutečná cesta pro {0}, výsledek {1}.", + "Resolving_type_reference_directive_0_containing_file_1_root_directory_2_6116": "======== Překládá se direktiva reference typu {0}, obsažený soubor {1}, kořenový adresář {2}. ========", + "Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set_6123": "======== Překládá se direktiva reference typu {0}, obsažený soubor {1}, kořenový adresář není nastavený. ========", + "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1_6127": "======== Překládá se direktiva reference typu {0}, obsažený soubor není nastavený, kořenový adresář {1}. ========", + "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set_6128": "======== Překládá se direktiva reference typu {0}, obsažený soubor není nastavený, kořenový adresář není nastavený. ========", + "Resolving_using_primary_search_paths_6117": "Překládá se pomocí primárních cest hledání...", + "Resolving_with_primary_search_path_0_6121": "Probíhá překlad pomocí primární cesty hledání {0}.", + "Rest_parameter_0_implicitly_has_an_any_type_7019": "Parametr rest {0} implicitně obsahuje typ any[].", + "Rest_types_may_only_be_created_from_object_types_2700": "Typy rest se dají vytvářet jenom z typů object.", + "Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4046": "Návratový typ signatury volání z exportovaného rozhraní má nebo používá název {0} z privátního modulu {1}.", + "Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0_4047": "Návratový typ signatury volání z exportovaného rozhraní má nebo používá privátní název {0}.", + "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_mod_4044": "Návratový typ signatury konstruktoru z exportovaného rozhraní má nebo používá název {0} z privátního modulu {1}.", + "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0_4045": "Návratový typ signatury konstruktoru z exportovaného rozhraní má nebo používá privátní název {0}.", + "Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class_2409": "Návratový typ signatury konstruktoru musí jít přiřadit k typu instance třídy.", + "Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named_4058": "Návratový typ exportované funkce má nebo používá název {0} z externího modulu {1}, ale nedá se pojmenovat.", + "Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1_4059": "Návratový typ exportované funkce má nebo používá název {0} z privátního modulu {1}.", + "Return_type_of_exported_function_has_or_is_using_private_name_0_4060": "Návratový typ exportované funkce má nebo používá privátní název {0}.", + "Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4048": "Návratový typ signatury indexu z exportovaného rozhraní má nebo používá název {0} z privátního modulu {1}.", + "Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0_4049": "Návratový typ signatury indexu z exportovaného rozhraní má nebo používá privátní název {0}.", + "Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4056": "Návratový typ metody z exportovaného rozhraní má nebo používá název {0} z privátního modulu {1}.", + "Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0_4057": "Návratový typ metody z exportovaného rozhraní má nebo používá privátní název {0}.", + "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_4041": "Návratový typ veřejné metody getter {0} z exportované třídy má nebo používá název {1} z externího modulu {2}, ale nedá se pojmenovat.", + "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2_4042": "Návratový typ veřejné metody getter {0} z exportované třídy má nebo používá název {1} z privátního modulu {2}.", + "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_private_name_1_4043": "Návratový typ veřejné metody getter {0} z exportované třídy má nebo používá privátní název {1}.", + "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_c_4053": "Návratový typ veřejné metody z exportované třídy má nebo používá název {0} z externího modulu {1}, ale nedá se pojmenovat.", + "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4054": "Návratový typ veřejné metody z exportované třídy má nebo používá název {0} z privátního modulu {1}.", + "Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0_4055": "Návratový typ veřejné metody z exportované třídy má nebo používá privátní název {0}.", + "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_external_modul_4038": "Návratový typ veřejné statické metody getter {0} z exportované třídy má nebo používá název {1} z externího modulu {2}, ale nedá se pojmenovat.", + "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_4039": "Návratový typ veřejné statické metody getter {0} z exportované třídy má nebo používá název {1} z privátního modulu {2}.", + "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_private_name_1_4040": "Návratový typ veřejné statické metody getter {0} z exportované třídy má nebo používá privátní název {1}.", + "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module__4050": "Návratový typ veřejné statické metody z exportované třídy má nebo používá název {0} z externího modulu {1}, ale nedá se pojmenovat.", + "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4051": "Návratový typ veřejné statické metody z exportované třídy má nebo používá název {0} z privátního modulu {1}.", + "Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0_4052": "Návratový typ veřejné statické metody z exportované třídy má nebo používá privátní název {0}.", + "Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program_6184": "Znovu se používají vyhodnocení modulu z {0}, protože vyhodnocení se oproti původnímu programu nezměnila.", + "Reusing_resolution_of_module_0_to_file_1_from_old_program_6183": "Znovu se používá vyhodnocení modulu {0} do souboru {1} z původního programu.", + "Rewrite_all_as_indexed_access_types_95034": "Přepsat vše jako indexované typy přístupu", + "Rewrite_as_the_indexed_access_type_0_90026": "Přepsat jako indexovaný typ přístupu {0}", + "Root_directory_cannot_be_determined_skipping_primary_search_paths_6122": "Nedá se určit kořenový adresář, přeskakují se primární cesty hledání.", + "STRATEGY_6039": "STRATEGIE", + "Scoped_package_detected_looking_in_0_6182": "Zjištěn balíček v oboru, hledání v: {0}", + "Setters_cannot_return_a_value_2408": "Metody setter nemůžou vracet hodnotu.", + "Show_all_compiler_options_6169": "Zobrazí všechny možnosti kompilátoru.", + "Show_diagnostic_information_6149": "Zobrazí diagnostické informace.", + "Show_verbose_diagnostic_information_6150": "Zobrazí podrobné diagnostické informace.", + "Show_what_would_be_built_or_deleted_if_specified_with_clean_6367": "Zobrazit, co by se sestavilo (nebo odstranilo, pokud je zadaná možnost --clean)", + "Signature_0_must_be_a_type_predicate_1224": "Signatura {0} musí být predikát typu.", + "Skip_type_checking_of_declaration_files_6012": "Přeskočit kontrolu typu souborů deklarace", + "Skipping_build_of_project_0_because_its_dependency_1_has_errors_6362": "Sestavení projektu {0} se přeskakuje, protože jeho závislost {1} obsahuje chyby.", + "Skipping_clean_because_not_all_projects_could_be_located_6371": "Vyčištění se přeskakuje, protože některé projekty se nepodařilo najít.", + "Source_Map_Options_6175": "Možnosti zdrojového mapování", + "Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature_2382": "Specializovaná signatura přetížení nejde přiřadit žádnému nespecializovanému podpisu.", + "Specifier_of_dynamic_import_cannot_be_spread_element_1325": "Specifikátor dynamického importu nemůže být elementem Spread.", + "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_or_ESNEXT_6015": "Zadejte cílovou verzi ECMAScriptu: ES3 (výchozí), ES5, ES2015, ES2016, ES2017, ES2018 nebo ESNEXT.", + "Specify_JSX_code_generation_Colon_preserve_react_native_or_react_6080": "Zadejte generování kódu JSX: preserve, react-native, nebo react.", + "Specify_library_files_to_be_included_in_the_compilation_6079": "Zadejte soubory knihovny, které se mají zahrnout do kompilace.", + "Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext_6016": "Určete generování kódu modulu: none, commonjs, amd, system, umd, es2015 nebo ESNext.", + "Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6_6069": "Zadejte strategii překladu modulu: node (Node.js) nebo classic (TypeScript verze nižší než 1.6).", + "Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h_6146": "Zadejte funkci objektu pro vytváření JSX, která se použije při zaměření na generování JSX react, např. React.createElement nebo h.", + "Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix_6060": "Zdejte sekvenci konce řádku, která se má použít při generování souborů: CRLF (dos) nebo LF (unix).", + "Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations_6004": "Zadejte umístění, ve kterém by měl ladicí program najít soubory TypeScript namísto umístění zdroje.", + "Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations_6003": "Zadejte umístění, ve kterém by měl ladicí program najít soubory mapy namísto generovaných umístění.", + "Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir_6058": "Zadejte kořenový adresář vstupních souborů. Slouží ke kontrole struktury výstupního adresáře pomocí --outDir.", + "Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher_2472": "Operátor rozšíření ve výrazech new je dostupný jenom při cílení na verzi ECMAScript 5 a vyšší.", + "Spread_types_may_only_be_created_from_object_types_2698": "Typy spread se dají vytvářet jenom z typů object.", + "Starting_compilation_in_watch_mode_6031": "Spouští se kompilace v režimu sledování...", + "Statement_expected_1129": "Očekává se příkaz.", + "Statements_are_not_allowed_in_ambient_contexts_1036": "Příkazy se nepovolují v ambientních kontextech.", + "Static_members_cannot_reference_class_type_parameters_2302": "Statické členy nemůžou odkazovat na parametry typu třídy.", + "Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1_2699": "Statická vlastnost {0} je v konfliktu s předdefinovanou vlastností Function.{0} funkce konstruktoru {1}.", + "Strict_Type_Checking_Options_6173": "Možnosti striktní kontroly typů", + "String_literal_expected_1141": "Očekává se řetězcový literál.", + "String_literal_with_double_quotes_expected_1327": "Očekával se řetězcový literál s dvojitými uvozovkami.", + "Stylize_errors_and_messages_using_color_and_context_experimental_6073": "Stylizujte chyby a zprávy pomocí barev a kontextu (experimentální).", + "Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_t_2717": "Deklarace následných vlastností musí obsahovat stejný typ. Vlastnost {0} musí být typu {1}, ale tady je typu {2}.", + "Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_t_2403": "Deklarace následných proměnných musí obsahovat stejný typ. Proměnná {0} musí být typu {1}, ale tady je typu {2}.", + "Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2_5064": "Nahrazení {0} za vzor {1} má nesprávný typ, očekával se typ string, obdržený je {2}.", + "Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character_5062": "Nahrazení {0} ve vzoru {1} může obsahovat nanejvýš jeden znak * (hvězdička).", + "Substitutions_for_pattern_0_should_be_an_array_5063": "Náhrady vzoru {0} by měly být pole.", + "Substitutions_for_pattern_0_shouldn_t_be_an_empty_array_5066": "Nahrazení vzoru {0} nesmí být prázdné pole.", + "Successfully_created_a_tsconfig_json_file_6071": "Soubor tsconfig.json se úspěšně vytvořil.", + "Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors_2337": "Volání pomocí super se nepovolují mimo konstruktory a ve funkcích vnořených v konstruktorech.", + "Suppress_excess_property_checks_for_object_literals_6072": "Potlačit nadměrné kontroly vlastností pro literály objektů", + "Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures_6055": "Potlačit chyby noImplicitAny u objektů indexování bez signatur indexu", + "Symbol_reference_does_not_refer_to_the_global_Symbol_constructor_object_2470": "Odkaz Symbol neodkazuje na globální objekt konstruktoru Symbol.", + "Syntax_Colon_0_6023": "Syntaxe: {0}", + "The_0_operator_cannot_be_applied_to_type_symbol_2469": "Operátor {0} nejde použít u typu symbol.", + "The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead_2447": "Operátor {0} není u logických typů povolený. Můžete ale použít {1}.", + "The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead_2696": "Typ Object se dá přiřadit jen k malému počtu dalších typů. Nechtěli jste místo toho použít typ any?", + "The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_stand_2496": "Funkce šipky v ES3 a ES5 nemůže odkazovat na objekt arguments. Zvažte použití standardního výrazu funkce.", + "The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_usi_2522": "V ES3 a ES5 se na objekt arguments nedá odkazovat v asynchronní funkci nebo metodě. Zvažte možnost použít standardní funkci nebo metodu.", + "The_body_of_an_if_statement_cannot_be_the_empty_statement_1313": "Tělo příkazu if nemůže být prázdný příkaz.", + "The_character_set_of_the_input_files_6163": "Znaková sada vstupních souborů", + "The_containing_function_or_module_body_is_too_large_for_control_flow_analysis_2563": "Text obsahující funkce nebo modulu je pro analýzu toku řízení příliš dlouhý.", + "The_current_host_does_not_support_the_0_option_5001": "Aktuální hostitel nepodporuje možnost {0}.", + "The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context_2714": "Výraz přiřazení exportu musí být identifikátor nebo kvalifikovaný název v ambientním kontextu.", + "The_files_list_in_config_file_0_is_empty_18002": "Seznam files v konfiguračním souboru {0} je prázdný.", + "The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback_1060": "První parametr metody then příslibu musí být zpětné volání.", + "The_global_type_JSX_0_may_not_have_more_than_one_property_2608": "Globální typ JSX.{0} by neměl mít více než jednu vlastnost.", + "The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_option_1343": "Metavlastnost import.meta je povolená, jenom když se pro možnosti kompilátoru target a module použije ESNext.", + "The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary_2527": "Odvozený typ {0} odkazuje na nepřístupný typ {1}. Musí se použít anotace typu.", + "The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern_2491": "Levá strana příkazu for...in nemůže být destrukturačním vzorem.", + "The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation_2404": "Levá strana příkazu for...in nemůže používat anotaci typu.", + "The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access_2406": "Levá strana příkazu for..n musí být proměnná nebo přístup k vlastnosti.", + "The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any_2405": "Levá strana příkazu for...in musí být typu string nebo any.", + "The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation_2483": "Levá strana příkazu for...of nemůže používat anotaci typu.", + "The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access_2487": "Levá strana příkazu for...of musí být proměnná nebo přístup k vlastnosti.", + "The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type_2362": "Levá strana aritmetické operace musí mít typ any, number nebo být typu výčtu.", + "The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access_2364": "Levá strana výrazu přiřazení musí být proměnná nebo přístup k vlastnosti.", + "The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol_2360": "Levá strana výrazu in musí být typu any, string, number nebo symbol.", + "The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_paramete_2358": "Levá strana výrazu instanceof musí být typu any, typem objektu nebo parametrem typu.", + "The_locale_used_when_displaying_messages_to_the_user_e_g_en_us_6156": "Národní prostředí, které se používá při zobrazování zpráv uživateli (třeba cs-CZ)", + "The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files_6136": "Maximální hloubka závislostí pro vyhledávání pod node_modules a načítání javascriptových souborů", + "The_operand_of_a_delete_operator_cannot_be_a_read_only_property_2704": "Operandem operátoru delete nemůže být vlastnost určená jen pro čtení.", + "The_operand_of_a_delete_operator_must_be_a_property_reference_2703": "Operandem operátoru delete musí být odkaz na vlastnost.", + "The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access_2357": "Operand operátoru inkrementace nebo dekrementace musí být proměnná nebo přístup k vlastnosti.", + "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601": "Návratový typ konstruktoru elementu JSX musí vracet objektový typ.", + "The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any_1237": "Návratový typ funkce dekorátoru parametru funkce musí být void nebo any.", + "The_return_type_of_a_property_decorator_function_must_be_either_void_or_any_1236": "Návratový typ funkce dekorátoru vlastnosti musí být void nebo any.", + "The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_t_1058": "Návratový typ asynchronní funkce musí být buď platný příslib, nebo nesmí obsahovat člen then, který se dá volat.", + "The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_1064": "Návratový typ asynchronní funkce nebo metody musí být globální typ Promise.", + "The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_but_2407": "Pravá strana příkazu for...in musí být typu any, typem objektu nebo parametrem typu, ale tady má typ {0}.", + "The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type_2363": "Pravá strana aritmetické operace musí mít typ any, number nebo být typu výčtu.", + "The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter_2361": "Pravá strana výrazu in musí být typu any, objektového typu nebo parametrem typu.", + "The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_F_2359": "Pravá strana výrazu instanceof musí mít typ any nebo typ, který se dá přiřadit k typu rozhraní Function.", + "The_specified_path_does_not_exist_Colon_0_5058": "Zadaná cesta neexistuje: {0}", + "The_target_of_an_assignment_must_be_a_variable_or_a_property_access_2541": "Cíl přiřazení musí být proměnná nebo přístup k vlastnosti.", + "The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access_2701": "Cílem přiřazení zbytku objektu musí být proměnná nebo přístup k vlastnosti.", + "The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1_2684": "Kontext this typu {0} se nedá přiřadit k možnosti this metody typu {1}.", + "The_this_types_of_each_signature_are_incompatible_2685": "Typy this jednotlivých signatur nejsou kompatibilní.", + "The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_typ_2453": "Argument typu pro parametr typu {0} se nemůže odvozovat z využití. Argumenty typu ale můžete zadat explicitně.", + "The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value__2547": "Typ vrácený metodou next() asynchronního iterátoru musí být příslib pro typ s vlastností value.", + "The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property_2490": "Typ vrácený metodou next() iterátoru musí obsahovat vlastnost value.", + "The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer_1189": "Deklarace proměnné příkazu for...in nemůže obsahovat inicializátor.", + "The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer_1190": "Deklarace proměnné příkazu for...of nemůže obsahovat inicializátor.", + "The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any_2410": "Příkaz with není podporovaný. Všechny symboly s blokem with budou typu any.", + "This_constructor_function_may_be_converted_to_a_class_declaration_80002": "Tato funkce konstruktoru se může převést na deklaraci třídy.", + "This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found_2354": "Tato syntaxe vyžaduje importovanou podpůrnou aplikaci, ale modul {0} se nenašel.", + "This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1_2343": "Tato syntaxe vyžaduje importovanou podpůrnou aplikaci s názvem {1}, ale modul {0} nemá žádného exportovaného člena {1}.", + "Trailing_comma_not_allowed_1009": "Čárka na konci není povolená.", + "Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule_6153": "Transpiluje každý soubor jako samostatný modul (podobné jako ts.transpileModule).", + "Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_mod_7035": "Vyzkoušejte deklaraci `npm install @types/{0}`, pokud existuje, nebo přidejte nový soubor deklarací (.d.ts) s deklarací `declare module '{0}';`.", + "Trying_other_entries_in_rootDirs_6110": "Zkoušejí se další položky v rootDirs.", + "Trying_substitution_0_candidate_module_location_Colon_1_6093": "Zkouší se nahrazení {0}, umístění modulu kandidáta: {1}.", + "Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2_2493": "Typ řazené kolekce členů {0} o délce {1} se nedá přiřadit k řazené kolekci členů o délce {2}.", + "Type_0_cannot_be_converted_to_type_1_2352": "Typ {0} se nedá převést na typ {1}.", + "Type_0_cannot_be_used_as_an_index_type_2538": "Typ {0} se nedá použít jako typ indexu.", + "Type_0_cannot_be_used_to_index_type_1_2536": "Typ {0} nejde použít k indexování typu {1}.", + "Type_0_does_not_satisfy_the_constraint_1_2344": "Typ {0} nevyhovuje omezení {1}.", + "Type_0_has_no_matching_index_signature_for_type_1_2537": "Typ {0} nemá odpovídající signaturu indexu pro typ {1}.", + "Type_0_has_no_properties_in_common_with_type_1_2559": "Typ {0} nemá žádné vlastnosti společné s typem {1}.", + "Type_0_has_no_property_1_2460": "V typu {0} není žádná vlastnost {1}.", + "Type_0_has_no_property_1_and_no_string_index_signature_2459": "V typu {0} není žádná vlastnost {1} ani žádná signatura indexu řetězce.", + "Type_0_is_not_a_constructor_function_type_2507": "Typ {0} není typ funkce konstruktoru.", + "Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Prom_1055": "Typ {0} nepředstavuje platný návratový typ asynchronní funkce v ES5/ES3, protože neodkazuje na hodnotu konstruktoru kompatibilní s příslibem.", + "Type_0_is_not_an_array_type_2461": "Typ {0} není typ pole.", + "Type_0_is_not_an_array_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators_2568": "Typ {0} není typem pole. Pokud chcete povolit iteraci iterátorů, použijte možnost kompilátoru --downlevelIteration.", + "Type_0_is_not_an_array_type_or_a_string_type_2495": "Typ {0} není typem pole nebo řetězce.", + "Type_0_is_not_an_array_type_or_a_string_type_Use_compiler_option_downlevelIteration_to_allow_iterati_2569": "Typ {0} není typem pole ani typem řetězce. Pokud chcete povolit iteraci iterátorů, použijte možnost kompilátoru --downlevelIteration.", + "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549": "Typ {0} není typem pole nebo řetězce, nebo nemá metodu [Symbol.iterator](), která vrací iterátor.", + "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548": "Typ {0} není typem pole, nebo nemá metodu [Symbol.iterator](), která vrací iterátor.", + "Type_0_is_not_assignable_to_type_1_2322": "Typ {0} nejde přiřadit typu {1}.", + "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_2719": "Typ {0} se nedá přiřadit typu {1}. Existují dva různé typy s tímto názvem, ale nesouvisí spolu.", + "Type_0_is_not_comparable_to_type_1_2678": "Typ {0} se nedá porovnat s typem {1}.", + "Type_0_is_not_generic_2315": "Typ {0} není obecný.", + "Type_0_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator_2504": "Typ {0} musí mít metodu [Symbol.asyncIterator](), která vrací asynchronní iterátor.", + "Type_0_must_have_a_Symbol_iterator_method_that_returns_an_iterator_2488": "Typ {0} musí mít metodu [Symbol.iterator](), která vrací iterátor.", + "Type_0_provides_no_match_for_the_signature_1_2658": "Typ {0} neposkytuje žádnou shodu pro podpis {1}.", + "Type_0_recursively_references_itself_as_a_base_type_2310": "Typ {0} odkazuje rekurzivně sám na sebe jako na základní typ.", + "Type_alias_0_circularly_references_itself_2456": "Alias typu {0} odkazuje cyklicky sám na sebe.", + "Type_alias_name_cannot_be_0_2457": "Název aliasu typu nemůže být {0}.", + "Type_annotation_cannot_appear_on_a_constructor_declaration_1093": "V deklaraci konstruktoru se nemůže objevit anotace typu.", + "Type_argument_candidate_1_is_not_a_valid_type_argument_because_it_is_not_a_supertype_of_candidate_0_2455": "Kandidát na argument typu {1} není platným argumentem typu, protože není nadtypem kandidáta {0}.", + "Type_argument_expected_1140": "Očekává se argument typu.", + "Type_argument_list_cannot_be_empty_1099": "Seznam argumentů typu nemůže být prázdný.", + "Type_arguments_cannot_be_used_here_1342": "Argumenty typu tady nejde použít.", + "Type_declaration_files_to_be_included_in_compilation_6124": "Soubory deklarace typu, které se mají zahrnout do kompilace", + "Type_expected_1110": "Očekával se typ.", + "Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method_1062": "Typ se přímo nebo nepřímo odkazuje ve zpětném volání jeho vlastní metody then při splnění.", + "Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member_1320": "Typ operandu await musí být buď platný příslib, nebo nesmí obsahovat člen then, který se dá volat.", + "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322": "Typ iterovaných elementů yield* musí být buď platný příslib, nebo nesmí obsahovat člen then, který se dá volat.", + "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321": "Typ operandu yield v asynchronním generátoru musí být buď platný příslib, nebo nesmí obsahovat člen then, který se dá volat.", + "Type_parameter_0_has_a_circular_constraint_2313": "Parametr typu {0} má cyklické omezení.", + "Type_parameter_0_has_a_circular_default_2716": "Parametr typu {0} má cyklickou výchozí hodnotu.", + "Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4008": "Parametr typu {0} signatury volání z exportovaného rozhraní má nebo používá privátní název {1}.", + "Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4006": "Parametr typu {0} signatury konstruktoru z exportovaného rozhraní má nebo používá privátní název {1}.", + "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002": "Parametr typu {0} exportované třídy má nebo používá privátní název {1}.", + "Type_parameter_0_of_exported_function_has_or_is_using_private_name_1_4016": "Parametr typu {0} exportované funkce má nebo používá privátní název {1}.", + "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004": "Parametr typu {0} exportovaného rozhraní má nebo používá privátní název {1}.", + "Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1_4083": "Parametr typu {0} exportovaného aliasu typu má nebo používá privátní název {1}.", + "Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4014": "Parametr typu {0} metody z exportovaného rozhraní má nebo používá privátní název {1}.", + "Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4012": "Parametr typu {0} veřejné metody z exportované třídy má nebo používá privátní název {1}.", + "Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4010": "Parametr typu {0} veřejné statické metody z exportované třídy má nebo používá privátní název {1}.", + "Type_parameter_declaration_expected_1139": "Očekává se deklarace parametru typu.", + "Type_parameter_list_cannot_be_empty_1098": "Seznam parametrů typu nemůže být prázdný.", + "Type_parameter_name_cannot_be_0_2368": "Název parametru typu nemůže být {0}.", + "Type_parameters_cannot_appear_on_a_constructor_declaration_1092": "Parametry typu se nemůžou vyskytovat v deklaraci konstruktoru.", + "Type_predicate_0_is_not_assignable_to_1_1226": "Predikát typu {0} nejde přiřadit {1}.", + "Type_reference_directive_0_was_not_resolved_6120": "======== Direktiva odkazu na typ {0} se nepřeložila. ========", + "Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2_6119": "======== Direktiva odkazu na typ {0} se úspěšně přeložila na {1}, primární: {2}. ========", + "Types_have_separate_declarations_of_a_private_property_0_2442": "Typy mají samostatné deklarace privátní vlastnosti {0}.", + "Types_of_parameters_0_and_1_are_incompatible_2328": "Typy parametrů {0} a {1} jsou nekompatibilní.", + "Types_of_property_0_are_incompatible_2326": "Typy vlastnosti {0} nejsou kompatibilní.", + "Unable_to_open_file_0_6050": "Soubor {0} nejde otevřít.", + "Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression_1238": "Když se podpis dekorátoru třídy volá jako výraz, nejde přeložit.", + "Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression_1241": "Když se podpis dekorátoru metody volá jako výraz, nejde přeložit.", + "Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression_1239": "Když se podpis dekorátoru parametru volá jako výraz, nejde přeložit.", + "Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression_1240": "Když se podpis dekorátoru vlastnosti volá jako výraz, nejde přeložit.", + "Unexpected_end_of_text_1126": "Neočekávaný konec textu", + "Unexpected_token_1012": "Neočekávaný token", + "Unexpected_token_A_constructor_method_accessor_or_property_was_expected_1068": "Neočekávaný token. Očekával se konstruktor, metoda, přístupový objekt nebo vlastnost.", + "Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces_1069": "Neočekávaný token. Očekával se název parametru typu bez složených závorek.", + "Unexpected_token_expected_1179": "Neočekávaný token. Očekává se znak {.", + "Unknown_compiler_option_0_5023": "Neznámá možnost kompilátoru {0}", + "Unknown_option_excludes_Did_you_mean_exclude_6114": "Neznámá možnost excludes. Měli jste na mysli exclude?", + "Unknown_type_acquisition_option_0_17010": "Neznámá možnost získání typu {0}", + "Unreachable_code_detected_7027": "Zjistil se nedosažitelný kód.", + "Unsupported_locale_0_6049": "Nepodporované národní prostředí {0}", + "Unterminated_Unicode_escape_sequence_1199": "Neukončená řídicí sekvence Unicode", + "Unterminated_quoted_string_in_response_file_0_6045": "Neukončený řetězec v uvozovkách v souboru odezvy {0}", + "Unterminated_regular_expression_literal_1161": "Neukončený literál regulárního výrazu", + "Unterminated_string_literal_1002": "Neukončený řetězcový literál", + "Unterminated_template_literal_1160": "Neukončený literál šablony", + "Untyped_function_calls_may_not_accept_type_arguments_2347": "Volání netypové funkce nemusí přijmout argumenty typu.", + "Unused_label_7028": "Nepoužívaný popisek", + "Updating_output_timestamps_of_project_0_6359": "Aktualizují se výstupní časová razítka projektu {0}...", + "Use_synthetic_default_member_95016": "Použije syntetického výchozího člena.", + "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494": "Použití řetězce v příkazu for...of se podporuje jenom v ECMAScript 5 nebo vyšší verzi.", + "VERSION_6036": "VERZE", + "Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it_2560": "Hodnota typu {0} nemá žádné vlastnosti společné s typem {1}. Chtěli jste ji volat?", + "Value_of_type_0_is_not_callable_Did_you_mean_to_include_new_2348": "Hodnota typu {0} se nedá volat. Nechtěli jste zahrnout new?", + "Variable_0_implicitly_has_an_1_type_7005": "Proměnná {0} má implicitně typ {1}.", + "Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined_7034": "V některých umístěních, kde se nedá určit typ proměnné, má proměnná {0} implicitně typ {1}.", + "Variable_0_is_used_before_being_assigned_2454": "Proměnná {0} je použitá před přiřazením.", + "Variable_declaration_expected_1134": "Očekává se deklarace proměnné.", + "Variable_declaration_list_cannot_be_empty_1123": "Seznam deklarací proměnných nemůže být prázdný.", + "Version_0_6029": "Verze {0}", + "Watch_input_files_6005": "Sledovat vstupní soubory", + "Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen_6191": "Určuje, jestli se místo vymazání obrazovky má zachovat zastaralý výstup konzoly v režimu sledování.", + "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001": "Nejde přejmenovat elementy definované ve standardní knihovně TypeScriptu.", + "You_cannot_rename_this_element_8000": "Tento element nejde přejmenovat.", + "_0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write__1329": "Objekt {0} přijímá málo argumentů k tomu, aby se dal použít jako dekoratér. Nechtěli jste ho nejprve volat a napsat @{0}()?", + "_0_are_specified_twice_The_attribute_named_0_will_be_overwritten_2710": "Položka {0} je zadána dvakrát. Atribut s názvem {0} se přepíše.", + "_0_can_only_be_used_in_a_ts_file_8009": "{0} se dá použít jenom v souboru .ts.", + "_0_expected_1005": "Očekával se: {0}.", + "_0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_reference_7023": "{0} obsahuje implicitně návratový typ any, protože neobsahuje anotaci návratového typu a přímo nebo nepřímo se odkazuje v jednom ze svých návratových výrazů.", + "_0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or__7022": "{0} má implicitně typ any, protože nemá anotaci typu a odkazuje se přímo nebo nepřímo v jeho vlastním inicializátoru.", + "_0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible_2692": "{0} je primitivum, ale {1} je obálkový objekt. Pokud je to možné, použijte raději {0}.", + "_0_is_declared_but_its_value_is_never_read_6133": "Deklaruje se {0}, ale jeho hodnota se vůbec nečte.", + "_0_is_declared_but_never_used_6196": "{0} se nadeklarovalo, ale nepoužilo.", + "_0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2_17012": "{0} není platnou metavlastností pro klíčové slovo {1}. Měli jste na mysli {2}?", + "_0_is_referenced_directly_or_indirectly_in_its_own_base_expression_2506": "Na {0} se přímo nebo nepřímo odkazuje ve vlastním základním výrazu.", + "_0_is_referenced_directly_or_indirectly_in_its_own_type_annotation_2502": "Na {0} se odkazuje přímo nebo nepřímo v jeho vlastní anotaci typu.", + "_0_list_cannot_be_empty_1097": "Seznam {0} nemůže být prázdný.", + "_0_modifier_already_seen_1030": "Modifikátor {0} se už jednou vyskytl.", + "_0_modifier_cannot_appear_on_a_class_element_1031": "Modifikátor {0} se nemůže objevit v elementu třídy.", + "_0_modifier_cannot_appear_on_a_constructor_declaration_1089": "Modifikátor {0} se nemůže objevit v deklaraci konstruktoru.", + "_0_modifier_cannot_appear_on_a_data_property_1043": "Modifikátor {0} nejde použít u vlastnosti dat.", + "_0_modifier_cannot_appear_on_a_module_or_namespace_element_1044": "Modifikátor {0} se nemůže objevit v elementu modulu nebo oboru názvů.", + "_0_modifier_cannot_appear_on_a_parameter_1090": "Modifikátor {0} se nemůže objevit v parametru.", + "_0_modifier_cannot_appear_on_a_type_member_1070": "Modifikátor {0} se nemůže objevit u člena typu.", + "_0_modifier_cannot_appear_on_an_index_signature_1071": "Modifikátor {0} se nemůže objevit v signatuře indexu.", + "_0_modifier_cannot_be_used_here_1042": "Modifikátor {0} tady nejde použít.", + "_0_modifier_cannot_be_used_in_an_ambient_context_1040": "Modifikátor {0} nejde použít v ambientním kontextu.", + "_0_modifier_cannot_be_used_with_1_modifier_1243": "Modifikátor {0} nejde použít s modifikátorem {1}.", + "_0_modifier_cannot_be_used_with_a_class_declaration_1041": "Modifikátor {0} nejde použít s deklarací třídy.", + "_0_modifier_must_precede_1_modifier_1029": "Modifikátor {0} se musí vyskytovat před modifikátorem {1}.", + "_0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here_2702": "{0} jenom odkazuje na typ, ale tady se používá jako obor názvů.", + "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_2693": "{0} odkazuje jenom na typ, ale používá se tady jako hodnota.", + "_0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead_2686": "{0} odkazuje na globální UMD, ale aktuální soubor je modul. Zvažte raději přidání importu.", + "_0_tag_already_specified_1223": "Značka {0} se už specifikovala.", + "_0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag_1253": "Značku {0} nejde používat nezávisle jako značku JSDoc nejvyšší úrovně.", + "_0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type_7010": "{0} s chybějící anotací návratového typu má implicitně návratový typ {1}.", + "abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration_1242": "Modifikátor abstract se může objevit jenom v deklaraci třídy, metody nebo vlastnosti.", + "await_expression_is_only_allowed_within_an_async_function_1308": "Výraz await se povoluje jenom ve funkci async.", + "await_expressions_cannot_be_used_in_a_parameter_initializer_2524": "Výrazy await nejdou použít v inicializátoru parametru.", + "baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1_6106": "Možnost baseUrl je nastavená na {0}, pomocí této hodnoty se přeloží název modulu {1}, který není relativní.", + "can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment_1312": "= jde použít jenom ve vlastnosti literálu objektu uvnitř destrukturujícího přiřazení.", + "case_or_default_expected_1130": "Očekává se case nebo default.", + "class_expressions_are_not_currently_supported_9003": "Výrazy class se v současnosti nepodporují.", + "const_declarations_can_only_be_declared_inside_a_block_1156": "Deklarace const se dají deklarovat jenom uvnitř bloku.", + "const_declarations_must_be_initialized_1155": "Deklarace const se musejí inicializovat.", + "const_enum_member_initializer_was_evaluated_to_a_non_finite_value_2477": "Inicializátor člena výčtu const se vyhodnotil na nekonečnou hodnotu.", + "const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN_2478": "Inicializátor člena výčtu const se vyhodnotil na nepovolenou hodnotu NaN.", + "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475": "Výčty const se dají použít jenom ve výrazech přístupu k vlastnosti nebo indexu nebo na pravé straně deklarace importu, přiřazení exportu nebo dotazu na typ.", + "delete_cannot_be_called_on_an_identifier_in_strict_mode_1102": "Příkaz delete nejde volat u identifikátoru ve striktním režimu.", + "delete_this_Project_0_is_up_to_date_because_it_was_previously_built_6360": "odstranit toto – projekt {0} je aktuální, protože byl sestaven dříve", + "enum_declarations_can_only_be_used_in_a_ts_file_8015": "Deklarace enum se dají použít jen v souboru .ts.", + "export_can_only_be_used_in_a_ts_file_8003": "Možnost export= se dá použít jenom v souboru .ts.", + "export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always__2668": "Modifikátor export se nedá použít u ambientních modulů a rozšíření modulů, protože jsou vždy viditelné.", + "extends_clause_already_seen_1172": "Klauzule extends se už jednou vyskytla.", + "extends_clause_must_precede_implements_clause_1173": "Klauzule extends se musí vyskytovat před klauzulí implements.", + "extends_clause_of_exported_class_0_has_or_is_using_private_name_1_4020": "Klauzule extends exportované třídy {0} má nebo používá privátní název {1}.", + "extends_clause_of_exported_interface_0_has_or_is_using_private_name_1_4022": "Klauzule extends exportovaného rozhraní {0} má nebo používá privátní název {1}.", + "file_6025": "soubor", + "get_and_set_accessor_must_have_the_same_this_type_2682": "Přístupové objekty get a set musí mít stejný typ this.", + "get_and_set_accessor_must_have_the_same_type_2380": "Přístupový objekt get a set musí obsahovat stejný typ.", + "implements_clause_already_seen_1175": "Klauzule implements se už jednou vyskytla.", + "implements_clauses_can_only_be_used_in_a_ts_file_8005": "Klauzule implements se dají použít jenom v souboru .ts.", + "import_can_only_be_used_in_a_ts_file_8002": "Možnost import ... = se dá použít jenom v souboru .ts.", + "infer_declarations_are_only_permitted_in_the_extends_clause_of_a_conditional_type_1338": "Deklarace infer jsou povolené jenom v klauzuli extends podmíněného typu.", + "interface_declarations_can_only_be_used_in_a_ts_file_8006": "Deklarace rozhraní se dají použít jenom v souboru .ts.", + "let_declarations_can_only_be_declared_inside_a_block_1157": "Deklarace let je možné deklarovat jenom uvnitř bloku.", + "let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations_2480": "Nepovoluje se používat let jako název v deklaracích let nebo const.", + "module_declarations_can_only_be_used_in_a_ts_file_8007": "Deklarace modulů se dají použít jenom v souboru .ts.", + "new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead_1150": "Pole nejde vytvořit příkazem new T[]. Použijte syntaxi new Array().", + "new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type_7009": "Výraz new s chybějící signaturou konstruktoru v cíli má implicitně typ any.", + "non_null_assertions_can_only_be_used_in_a_ts_file_8013": "Kontrolní výrazy nenabývající hodnoty null lze použít jen v souboru .ts.", + "options_6024": "možnosti", + "or_expected_1144": "Očekává se znak { nebo ;.", + "package_json_does_not_have_a_0_field_6100": "Soubor package.json neobsahuje pole {0}.", + "package_json_has_0_field_1_that_references_2_6101": "Soubor package.json má pole {0} {1}, které odkazuje na {2}.", + "parameter_modifiers_can_only_be_used_in_a_ts_file_8012": "Modifikátory parametrů se dají použít jenom v souboru .ts.", + "paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0_6091": "Je zadaná možnost paths, hledá se vzor, který odpovídá názvu modulu {0}.", + "readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024": "Modifikátor readonly se může objevit jenom v deklaraci vlastnosti nebo signatuře indexu.", + "require_call_may_be_converted_to_an_import_80005": "Volání require se dá převést na import.", + "rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107": "Je nastavená možnost rootDirs, použije se k překladu relativního názvu modulu {0}.", + "super_can_only_be_referenced_in_a_derived_class_2335": "Na vlastnost super se dá odkazovat jenom v odvozené třídě.", + "super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions_2660": "Na možnost super je možné odkazovat jenom ve členech odvozených tříd nebo výrazů literálu objektu.", + "super_cannot_be_referenced_in_a_computed_property_name_2466": "Na vlastnost super se nedá odkazovat v názvu počítané vlastnosti.", + "super_cannot_be_referenced_in_constructor_arguments_2336": "Na vlastnost super se nedá odkazovat v argumentech konstruktoru.", + "super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_highe_2659": "Možnost super je povolená jenom ve členech výrazů literálu objektu, pokud je možnost target ES2015 nebo vyšší.", + "super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class_17011": "Před přístupem k vlastnosti super v konstruktoru odvozené třídy se musí zavolat super.", + "super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class_17009": "Možnost super se musí volat před přístupem k this v konstruktoru odvozené třídy.", + "super_must_be_followed_by_an_argument_list_or_member_access_1034": "Po vlastnosti super musí následovat seznam argumentů nebo přístup ke členu.", + "super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_der_2338": "Přístup k vlastnostem pomocí super je povolený jenom v konstruktoru, členské funkci nebo členském přístupovém objektu odvozené třídy.", + "this_cannot_be_referenced_in_a_computed_property_name_2465": "Na vlastnost this se nedá odkazovat v názvu počítaného prostředku.", + "this_cannot_be_referenced_in_a_module_or_namespace_body_2331": "Na vlastnost this se nedá odkazovat v modulu nebo těle oboru názvů.", + "this_cannot_be_referenced_in_a_static_property_initializer_2334": "Na vlastnost this se nedá odkazovat v inicializátoru statické vlastnosti.", + "this_cannot_be_referenced_in_constructor_arguments_2333": "Na vlastnost this se nedá odkazovat v argumentech konstruktoru.", + "this_cannot_be_referenced_in_current_location_2332": "Na vlastnost this se nedá odkazovat v aktuálním umístění.", + "this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_2683": "Možnost this má implicitně typ any, protože nemá anotaci typu.", + "type_aliases_can_only_be_used_in_a_ts_file_8008": "Aliasy typu se dají použít jenom v souboru .ts.", + "type_arguments_can_only_be_used_in_a_ts_file_8011": "Argumenty typu se dají použít jenom v souboru .ts.", + "type_assertion_expressions_can_only_be_used_in_a_ts_file_8016": "Výrazy potvrzení typu se dají použít jenom v souboru .ts.", + "type_parameter_declarations_can_only_be_used_in_a_ts_file_8004": "Deklarace parametru typu se dají použít jenom v souboru .ts.", + "types_can_only_be_used_in_a_ts_file_8010": "Typy se dají použít jenom v souboru .ts.", + "unique_symbol_types_are_not_allowed_here_1335": "Typy unique symbol tady nejsou povolené.", + "unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement_1334": "Typy unique symbol jsou povolené jen u proměnných v příkazu proměnné.", + "unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name_1333": "Typy unique symbol nejde použít v deklaraci proměnné s názvem vazby.", + "with_statements_are_not_allowed_in_an_async_function_block_1300": "Příkazy with se ve funkčním bloku async nepovolují.", + "with_statements_are_not_allowed_in_strict_mode_1101": "Příkazy with se ve striktním režimu nepovolují.", + "yield_expressions_cannot_be_used_in_a_parameter_initializer_2523": "Výrazy yield nejde použít v inicializátoru parametru." +} \ No newline at end of file diff --git a/node_modules/typescript/lib/de/diagnosticMessages.generated.json b/node_modules/typescript/lib/de/diagnosticMessages.generated.json new file mode 100644 index 0000000..f7bf53b --- /dev/null +++ b/node_modules/typescript/lib/de/diagnosticMessages.generated.json @@ -0,0 +1,1101 @@ +{ + "A_0_modifier_cannot_be_used_with_an_import_declaration_1079": "Ein Modifizierer \"{0}\" darf nicht mit einer Importdeklaration verwendet werden.", + "A_0_modifier_cannot_be_used_with_an_interface_declaration_1045": "Ein Modifizierer \"{0}\" darf nicht mit einer Schnittstellendeklaration verwendet werden.", + "A_0_parameter_must_be_the_first_parameter_2680": "Ein \"{0}\"-Parameter muss der erste Parameter sein.", + "A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature_2463": "Ein Bindungsmusterparameter darf in einer Implementierungssignatur nicht optional sein.", + "A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement_1105": "Eine break-Anweisung darf nur in einer einschließenden iteration- oder switch-Anweisung verwendet werden.", + "A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement_1116": "Eine break-Anweisung kann nur zu einer Bezeichnung einer einschließenden Anweisung springen.", + "A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments_2500": "Eine Klasse kann nur einen Bezeichner/\"qualified-name\" mit optionalen Typargumenten implementieren.", + "A_class_declaration_without_the_default_modifier_must_have_a_name_1211": "Eine Klassendeklaration ohne den default-Modifizierer muss einen Namen besitzen.", + "A_class_may_only_extend_another_class_2311": "Eine Klasse kann nur eine andere Klasse erweitern.", + "A_class_may_only_implement_another_class_or_interface_2422": "Eine Klasse kann nur eine andere Klasse oder Schnittstelle implementieren.", + "A_class_member_cannot_have_the_0_keyword_1248": "Ein Klassenmember darf nicht das Schlüsselwort \"{0}\" aufweisen.", + "A_comma_expression_is_not_allowed_in_a_computed_property_name_1171": "Ein Kommaausdruck ist in einem berechneten Eigenschaftennamen unzulässig.", + "A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type_2467": "Ein berechneter Eigenschaftenname kann nicht aus seinem enthaltenden Typ auf einen Typparameter verweisen.", + "A_computed_property_name_in_a_class_property_declaration_must_refer_to_an_expression_whose_type_is_a_1166": "Ein berechneter Eigenschaftenname in einer Deklaration einer Klasseneigenschaft muss auf einen Ausdruck verweisen, dessen Typ ein Literal oder ein \"unique symbol\"-Typ ist.", + "A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_ty_1168": "Ein berechneter Eigenschaftenname in einer Methodenüberladung muss auf einen Ausdruck verweisen, dessen Typ ein Literal oder ein \"unique symbol\"-Typ ist.", + "A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type__1170": "Ein berechneter Eigenschaftenname in einem Typliteral muss auf einen Ausdruck verweisen, dessen Typ ein Literal oder ein \"unique symbol\"-Typ ist.", + "A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_t_1165": "Ein berechneter Eigenschaftenname in einem Umgebungskontext muss auf einen Ausdruck verweisen, dessen Typ ein Literal oder ein \"unique symbol\"-Typ ist.", + "A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_1169": "Ein berechneter Eigenschaftenname in einer Schnittstelle muss auf einen Ausdruck verweisen, dessen Typ ein Literal oder ein \"unique symbol\"-Typ ist.", + "A_computed_property_name_must_be_of_type_string_number_symbol_or_any_2464": "Ein berechneter Eigenschaftenname muss vom Typ \"string\", \"number\", \"symbol\" oder \"any\" sein.", + "A_computed_property_name_of_the_form_0_must_be_of_type_symbol_2471": "Ein berechneter Eigenschaftenname in der Form \"{0}\" muss vom Typ \"symbol\" sein.", + "A_const_enum_member_can_only_be_accessed_using_a_string_literal_2476": "Auf einen const-Enumerationsmember kann nur mithilfe eines Zeichenfolgenliterals zugegriffen werden.", + "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_1254": "Bei einem const-Initialisierer in einem Umgebungskontext muss es sich um eine Zeichenfolge oder um ein numerisches Literal handeln.", + "A_constructor_cannot_contain_a_super_call_when_its_class_extends_null_17005": "Ein Konstruktor darf keinen super-Aufruf enthalten, wenn seine Klasse \"null\" erweitert.", + "A_constructor_cannot_have_a_this_parameter_2681": "Ein Konstruktor darf keinen \"this\"-Parameter aufweisen.", + "A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement_1104": "Eine continue-Anweisung darf nur in einer einschließenden iteration-Anweisung verwendet werden.", + "A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement_1115": "Eine continue-Anweisung kann nur zu einer Bezeichnung einer einschließenden Iterationsanweisung springen.", + "A_declare_modifier_cannot_be_used_in_an_already_ambient_context_1038": "Ein declare-Modifizierer darf nicht in einem Kontext verwendet werden, der bereits ein Umgebungskontext ist.", + "A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file_1046": "Ein declare-Modifizierer ist für eine Deklaration auf oberster Ebene in einer .d.ts-Datei erforderlich.", + "A_decorator_can_only_decorate_a_method_implementation_not_an_overload_1249": "Ein Decorator-Element kann nur für eine Methodenimplementierung und nicht für eine Überladung verwendet werden.", + "A_default_clause_cannot_appear_more_than_once_in_a_switch_statement_1113": "Eine default-Klausel darf nicht mehrmals in einer switch-Anweisung auftreten.", + "A_default_export_can_only_be_used_in_an_ECMAScript_style_module_1319": "Ein Standardexport kann nur in einem Modul des Typs ECMAScript verwendet werden.", + "A_definite_assignment_assertion_is_not_permitted_in_this_context_1255": "Eine definitive Zuweisungsassertion \"!\" ist in diesem Kontext nicht zulässig.", + "A_destructuring_declaration_must_have_an_initializer_1182": "Eine destrukturierende Deklaration muss einen Initialisierer besitzen.", + "A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declarat_2712": "Ein dynamischer Importaufruf in ES5/ES3 erfordert den Konstruktor \"Promise\". Stellen Sie sicher, dass Sie über eine Deklaration für den Konstruktor \"Promise\" verfügen, oder schließen Sie \"ES2015\" in Ihre Option \"--lib\" ein.", + "A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES20_2711": "Ein dynamischer Importaufruf gibt \"Promise\" zurück. Stellen Sie sicher, dass Sie über eine Deklaration für \"Promise\" verfügen, oder schließen Sie ES2015 in Ihre Option \"--lib\" ein.", + "A_file_cannot_have_a_reference_to_itself_1006": "Eine Datei darf keinen Verweis auf sich selbst enthalten.", + "A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator_1103": "Eine \"for-await-of\"-Aussage ist nur innerhalb einer Async-Funktion oder eines Async-Generators zulässig.", + "A_function_returning_never_cannot_have_a_reachable_end_point_2534": "Eine Funktion, die \"never\" zurückgibt, kann keinen erreichbaren Endpunkt besitzen.", + "A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void_2679": "Eine Funktion, die mit dem Schlüsselwort \"new\" aufgerufen wird, darf keinen \"this\"-Typ aufweisen, der \"void\" ist.", + "A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value_2355": "Eine Funktion, deren Typ weder als \"void\" noch als \"any\" deklariert ist, muss einen Wert zurückgeben.", + "A_generator_cannot_have_a_void_type_annotation_2505": "Ein Generator darf keine void-Typanmerkung aufweisen.", + "A_get_accessor_cannot_have_parameters_1054": "Eine get-Zugriffsmethode darf keine Parameter haben.", + "A_get_accessor_must_return_a_value_2378": "Eine get-Zugriffsmethode muss einen Wert zurückgeben.", + "A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_memb_2651": "Ein Memberinitialisierer in einer Enumerationsdeklaration darf nicht auf Member verweisen, die anschließend deklariert werden (einschließlich Member, die in anderen Enumerationen definiert sind).", + "A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any_2545": "Eine Mixin-Klasse benötigt einen Konstruktor mit einem einzelnen REST-Parameter des Typs \"any[]\".", + "A_module_cannot_have_multiple_default_exports_2528": "Ein Modul darf nicht mehrere Standardexporte aufweisen.", + "A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merg_2433": "Eine Namespacedeklaration darf sich nicht in einer anderen Datei als die Klasse oder Funktion befinden, mit der sie zusammengeführt wird.", + "A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged_2434": "Eine Namespacedeklaration darf nicht vor der Klasse oder Funktion positioniert werden, mit der sie zusammengeführt wird.", + "A_namespace_declaration_is_only_allowed_in_a_namespace_or_module_1235": "Eine Namespacedeklaration ist nur in einem Namespace oder Modul zulässig.", + "A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_7038": "Ein Import im Namespacestil kann nicht aufgerufen oder erstellt werden und verursacht zur Laufzeit einen Fehler.", + "A_non_dry_build_would_build_project_0_6357": "Bei einem Build ohne das Flag \"-dry\" würde das Projekt \"{0}\" erstellt.", + "A_non_dry_build_would_delete_the_following_files_Colon_0_6356": "Bei einem Build ohne das Flag \"-dry\" würden die folgenden Dateien gelöscht: {0}", + "A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation_2371": "Ein Parameterinitialisierer ist nur in einer Funktions- oder Konstruktorimplementierung zulässig.", + "A_parameter_property_cannot_be_declared_using_a_rest_parameter_1317": "Eine Parametereigenschaft darf nicht mithilfe eines rest-Parameters deklariert werden.", + "A_parameter_property_is_only_allowed_in_a_constructor_implementation_2369": "Eine Parametereigenschaft ist nur in einer Konstruktorimplementierung zulässig.", + "A_parameter_property_may_not_be_declared_using_a_binding_pattern_1187": "Eine Parametereigenschaft darf nicht mithilfe eines Bindungsmusters deklariert werden.", + "A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not_18001": "Ein Pfad in einer extends-Option muss ein relativer Pfad oder ein Stammpfad sein, aber dies trifft auf \"{0}\" nicht zu.", + "A_promise_must_have_a_then_method_1059": "Ein Zusage muss eine \"then\"-Methode aufweisen.", + "A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly_1331": "Eine Eigenschaft einer Klasse, deren Typ ein \"unique symbol\"-Typ ist, muss sowohl \"static\" als auch \"readonly\" sein.", + "A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly_1330": "Eine Eigenschaft einer Schnittstelle oder eines Typliterals, deren Typ ein \"unique symbol\"-Typ ist, muss \"readonly\" sein.", + "A_required_parameter_cannot_follow_an_optional_parameter_1016": "Ein erforderlicher Parameter darf nicht auf einen optionalen Parameter folgen.", + "A_rest_element_cannot_contain_a_binding_pattern_2501": "Ein rest-Element darf kein Bindungsmuster enthalten.", + "A_rest_element_cannot_have_a_property_name_2566": "Ein rest-Element darf keinen Eigenschaftennamen aufweisen.", + "A_rest_element_cannot_have_an_initializer_1186": "Ein rest-Element darf keinen Initialisierer aufweisen.", + "A_rest_element_must_be_last_in_a_destructuring_pattern_2462": "Ein rest-Element muss das letzte Element in einem Destrukturierungsmuster sein.", + "A_rest_parameter_cannot_be_optional_1047": "Ein rest-Parameter darf nicht optional sein.", + "A_rest_parameter_cannot_have_an_initializer_1048": "Ein rest-Parameter darf keinen Initialisierer aufweisen.", + "A_rest_parameter_must_be_last_in_a_parameter_list_1014": "Ein rest-Parameter muss in einer Parameterliste der letzte Eintrag sein.", + "A_rest_parameter_must_be_of_an_array_type_2370": "Ein rest-Parameter muss ein Arraytyp sein.", + "A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma_1013": "Ein rest-Parameter oder ein Bindungsmuster dürfen kein nachgestelltes Komma aufweisen.", + "A_return_statement_can_only_be_used_within_a_function_body_1108": "Eine return-Anweisung kann nur in einem Funktionstext verwendet werden.", + "A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl_6167": "Eine Reihe von Einträgen, die Importe zum Nachschlagen von Speicherorten in Bezug auf die \"baseUrl\" neu zuordnen.", + "A_set_accessor_cannot_have_a_return_type_annotation_1095": "Eine set-Zugriffsmethode darf keine Rückgabetypanmerkung aufweisen.", + "A_set_accessor_cannot_have_an_optional_parameter_1051": "Eine set-Zugriffsmethode darf keinen optionalen Parameter aufweisen.", + "A_set_accessor_cannot_have_rest_parameter_1053": "Eine set-Zugriffsmethode darf keinen rest-Parameter aufweisen.", + "A_set_accessor_must_have_exactly_one_parameter_1049": "Eine set-Zugriffsmethode muss genau einen Parameter aufweisen.", + "A_set_accessor_parameter_cannot_have_an_initializer_1052": "Ein set-Zugriffsmethodenparameter darf keinen Initialisierer aufweisen.", + "A_signature_with_an_implementation_cannot_use_a_string_literal_type_2381": "Eine Signatur mit einer Implementierung darf keinen Zeichenfolgen-Literaltyp verwenden.", + "A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_proper_2376": "Ein super-Aufruf muss die erste Anweisung im Konstruktor sein, wenn eine Klasse initialisierte Eigenschaften oder Parametereigenschaften enthält.", + "A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard_2518": "Ein auf \"this\" basierender Typwächter ist nicht mit einem parameterbasierten Typwächter kompatibel.", + "A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface_2526": "Ein this-Typ ist nur in einem nicht statischen Member einer Klasse oder Schnittstelle verfügbar.", + "A_tsconfig_json_file_is_already_defined_at_Colon_0_5054": "Eine Datei \"tsconfig.json\" ist bereits definiert unter: \"{0}\".", + "A_tuple_type_element_list_cannot_be_empty_1122": "Eine Tupeltyp-Elementliste darf nicht leer sein.", + "A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Con_17007": "Typassertionsausdrücke sind in der linken Seite von Potenzierungsausdrücken nicht zulässig. Erwägen Sie, den Ausdruck in Klammern zu setzen.", + "A_type_literal_property_cannot_have_an_initializer_1247": "Typliteraleigenschaften können keinen Initialisierer aufweisen.", + "A_type_predicate_cannot_reference_a_rest_parameter_1229": "Ein Typprädikat darf nicht auf einen rest-Parameter verweisen.", + "A_type_predicate_cannot_reference_element_0_in_a_binding_pattern_1230": "Ein Typprädikat darf nicht auf ein Element \"{0}\" in einem Bindungsmuster verweisen.", + "A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods_1228": "Ein Typprädikat ist nur an der Rückgabetypposition für Funktionen und Methoden zulässig.", + "A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type_2677": "Der Typ eines Typprädikats muss dem Typ seines Parameters zugewiesen werden können.", + "A_variable_whose_type_is_a_unique_symbol_type_must_be_const_1332": "Eine Variable, deren Typ ein \"unique symbol\"-Typ ist, muss \"const\" sein.", + "A_yield_expression_is_only_allowed_in_a_generator_body_1163": "Ein yield-Ausdruck ist nur in einem Generatortext zulässig.", + "Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression_2513": "Auf die abstrakte Methode \"{0}\" in der Klasse \"{1}\" kann nicht über den super-Ausdruck zugegriffen werden.", + "Abstract_methods_can_only_appear_within_an_abstract_class_1244": "Abstrakte Methoden können nur in einer abstrakten Klasse verwendet werden.", + "Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor_2715": "Auf die abstrakte Eigenschaft \"{0}\" in der Klasse \"{1}\" kann im Konstruktor nicht zugegriffen werden.", + "Accessibility_modifier_already_seen_1028": "Der Zugriffsmodifizierer ist bereits vorhanden.", + "Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher_1056": "Zugriffsmethoden sind nur verfügbar, wenn das Ziel ECMAScript 5 oder höher ist.", + "Accessors_must_both_be_abstract_or_non_abstract_2676": "Beide Accessoren müssen abstrakt oder nicht abstrakt sein.", + "Add_0_to_existing_import_declaration_from_1_90015": "\"{0}\" der vorhandenen Importdeklaration aus \"{1}\" hinzufügen", + "Add_0_to_unresolved_variable_90008": "Der nicht aufgelösten Variablen \"{0}.\" hinzufügen", + "Add_all_missing_async_modifiers_95041": "Alle fehlenden async-Modifizierer hinzufügen", + "Add_all_missing_members_95022": "Alle fehlenden Member hinzufügen", + "Add_all_missing_super_calls_95039": "Alle fehlenden super-Aufrufe hinzufügen", + "Add_async_modifier_to_containing_function_90029": "Async-Modifizierer zur enthaltenden Funktion hinzufügen", + "Add_braces_to_arrow_function_95059": "Geschweifte Klammern zu Pfeilfunktion hinzufügen", + "Add_definite_assignment_assertion_to_property_0_95020": "Definitive Zuweisungsassertion zu Eigenschaft \"{0}\" hinzufügen", + "Add_definite_assignment_assertions_to_all_uninitialized_properties_95028": "Allen nicht initialisierten Eigenschaften definitive Zuweisungsassertionen hinzufügen", + "Add_index_signature_for_property_0_90017": "Indexsignatur für die Eigenschaft \"{0}\" hinzufügen", + "Add_initializer_to_property_0_95019": "Initialisierer zu Eigenschaft \"{0}\" hinzufügen", + "Add_initializers_to_all_uninitialized_properties_95027": "Allen nicht initialisierten Eigenschaften Initialisierer hinzufügen", + "Add_missing_super_call_90001": "Fehlenden super()-Aufruf hinzufügen", + "Add_missing_typeof_95052": "Fehlenden \"typeof\" hinzufügen", + "Add_or_remove_braces_in_an_arrow_function_95058": "Geschweifte Klammern zu einer Pfeilfunktion hinzufügen oder daraus entfernen", + "Add_qualifier_to_all_unresolved_variables_matching_a_member_name_95037": "Allen nicht aufgelösten Variablen, die einem Membernamen entsprechen, Qualifizierer hinzufügen", + "Add_to_all_uncalled_decorators_95044": "Allen nicht aufgerufenen Decorators \"()\" hinzufügen", + "Add_ts_ignore_to_all_error_messages_95042": "Allen Fehlermeldungen \"@ts-ignore\" hinzufügen", + "Add_undefined_type_to_all_uninitialized_properties_95029": "Allen nicht initialisierten Eigenschaften einen nicht definierten Typ hinzufügen", + "Add_undefined_type_to_property_0_95018": "undefined-Typ zu Eigenschaft \"{0}\" hinzufügen", + "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068": "Das Hinzufügen einer \"tsconfig.json\"-Datei erleichtert die Organisation von Projekten, die sowohl TypeScript- als auch JavaScript-Dateien enthalten. Weitere Informationen finden Sie unter https://aka.ms/tsconfig.", + "Additional_Checks_6176": "Zusätzliche Überprüfungen", + "Advanced_Options_6178": "Erweiterte Optionen", + "All_declarations_of_0_must_have_identical_modifiers_2687": "Alle Deklarationen von \"{0}\" müssen identische Modifizierer aufweisen.", + "All_declarations_of_0_must_have_identical_type_parameters_2428": "Alle Deklarationen von \"{0}\" müssen identische Typparameter aufweisen.", + "All_declarations_of_an_abstract_method_must_be_consecutive_2516": "Alle Deklarationen einer abstrakten Methode müssen aufeinanderfolgend sein.", + "All_destructured_elements_are_unused_6198": "Alle destrukturierten Elemente werden nicht verwendet.", + "All_imports_in_import_declaration_are_unused_6192": "Keiner der Importe in der Importdeklaration wird verwendet.", + "All_variables_are_unused_6199": "Alle Variablen werden nicht verwendet.", + "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011": "Standardimporte von Modulen ohne Standardexport zulassen. Dies wirkt sich nicht auf die Codeausgabe aus, lediglich auf die Typprüfung.", + "Allow_javascript_files_to_be_compiled_6102": "Kompilierung von JavaScript-Dateien zulassen.", + "Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided_1209": "const-Umgebungsenumerationen sind unzulässig, wenn das Flag \"-isolatedModules\" angegeben wird.", + "Ambient_module_declaration_cannot_specify_relative_module_name_2436": "Die Umgebungsmoduldeklaration darf keinen relativen Modulnamen angeben.", + "Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces_2435": "Umgebungsmodule dürfen nicht in andere Module oder Namespaces geschachtelt werden.", + "An_AMD_module_cannot_have_multiple_name_assignments_2458": "Ein AMD-Modul darf nicht mehrere Namenzuweisungen aufweisen.", + "An_abstract_accessor_cannot_have_an_implementation_1318": "Ein abstrakter Accessor kann keine Implementierung aufweisen.", + "An_accessor_cannot_be_declared_in_an_ambient_context_1086": "Eine Zugriffsmethode darf nicht in einem Umgebungskontext deklariert werden.", + "An_accessor_cannot_have_type_parameters_1094": "Eine Zugriffsmethode darf keine Typparameter aufweisen.", + "An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file_1234": "Eine Umgebungsmoduldeklaration ist nur auf der obersten Ebene in einer Datei zulässig.", + "An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type_2356": "Ein arithmetischer Operand muss vom Typ \"any\" bzw. \"number\" oder ein Enumerationstyp sein.", + "An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_de_2705": "Eine Async-Funktion oder -Methode in ES5/ES3 erfordert den Konstruktur \"Promise\". Stellen Sie sicher, dass Sie über eine Deklaration für den Konstruktor \"Promise\" verfügen, oder schließen Sie \"ES2015\" in Ihre Option \"--lib\" ein.", + "An_async_function_or_method_must_have_a_valid_awaitable_return_type_1057": "Eine asynchrone Funktion oder Methode muss einen gültigen awaitable-Rückgabetyp aufweisen.", + "An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_in_2697": "Eine asynchrone Funktion oder Methode muss \"Promise\" zurückgeben. Stellen Sie sicher, dass Sie über eine Deklaration für \"Promise\" verfügen, oder schließen Sie ES2015 in Ihrer Option \"--lib\" ein.", + "An_async_iterator_must_have_a_next_method_2519": "Ein Async-Iterator muss eine \"next()\"-Async-Methode aufweisen.", + "An_element_access_expression_should_take_an_argument_1011": "Ein Ausdruck für einen Elementzugriff muss ein Argument verwenden.", + "An_enum_member_cannot_have_a_numeric_name_2452": "Ein Enumerationsmember darf keinen numerischen Namen besitzen.", + "An_export_assignment_can_only_be_used_in_a_module_1231": "Eine Exportzuweisung kann nur in einem Modul verwendet werden.", + "An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements_2309": "Eine Exportzuweisung darf nicht in einem Modul mit anderen exportierten Elementen verwendet werden.", + "An_export_assignment_cannot_be_used_in_a_namespace_1063": "Eine Exportzuweisung darf nicht in einem Namespace verwendet werden.", + "An_export_assignment_cannot_have_modifiers_1120": "Eine Exportzuweisung darf keine Modifizierer besitzen.", + "An_export_declaration_can_only_be_used_in_a_module_1233": "Eine Exportdeklaration kann nur in einem Modul verwendet werden.", + "An_export_declaration_cannot_have_modifiers_1193": "Eine Exportdeklaration darf keine Modifizierer besitzen.", + "An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive_1198": "Ein erweiterter Unicode-Escapewert muss zwischen 0x0 und 0x10FFFF (einschließlich) liegen.", + "An_implementation_cannot_be_declared_in_ambient_contexts_1183": "Eine Implementierung darf nicht in Umgebungskontexten deklariert werden.", + "An_import_declaration_can_only_be_used_in_a_namespace_or_module_1232": "Eine Importdeklaration darf nur in einem Namespace oder Modul verwendet werden.", + "An_import_declaration_cannot_have_modifiers_1191": "Eine Importdeklaration darf keine Modifizierer besitzen.", + "An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead_2691": "Ein Importpfad darf nicht mit einer Erweiterung \"{0}\" enden. Importieren Sie ggf. stattdessen \"{1}\".", + "An_index_expression_argument_must_be_of_type_string_number_symbol_or_any_2342": "Ein Indexausdrucksargument muss vom Typ \"string\", \"number\", \"symbol\" oder \"any\" sein.", + "An_index_signature_cannot_have_a_rest_parameter_1017": "Eine Indexsignatur darf keinen rest-Parameter besitzen.", + "An_index_signature_must_have_a_type_annotation_1021": "Eine Indexsignatur muss eine Typanmerkung besitzen.", + "An_index_signature_must_have_exactly_one_parameter_1096": "Eine Indexsignatur muss genau einen Parameter besitzen.", + "An_index_signature_parameter_cannot_have_a_question_mark_1019": "Ein Indexsignaturparameter darf kein Fragezeichen aufweisen.", + "An_index_signature_parameter_cannot_have_an_accessibility_modifier_1018": "Ein Indexsignaturparameter darf keinen Zugriffsmodifizierer besitzen.", + "An_index_signature_parameter_cannot_have_an_initializer_1020": "Ein Indexsignaturparameter darf keinen Initialisierer besitzen.", + "An_index_signature_parameter_must_have_a_type_annotation_1022": "Ein Indexsignaturparameter muss eine Typanmerkung besitzen.", + "An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead_1336": "Ein Indexsignaturparametertyp darf kein Typalias sein. Erwägen Sie stattdessen die Schreibung \"[{0}: {1}]: {2}\".", + "An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead_1337": "Ein Indexsignaturparametertyp darf kein Union-Typ sein. Erwägen Sie stattdessen die Verwendung eines zugeordneten Objekttyps.", + "An_index_signature_parameter_type_must_be_string_or_number_1023": "Ein Indexsignaturparameter-Typ muss \"string\" oder \"number\" sein.", + "An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments_2499": "Eine Schnittstelle kann nur einen Bezeichner/\"qualified-name\" mit optionalen Typargumenten erweitern.", + "An_interface_may_only_extend_a_class_or_another_interface_2312": "Eine Schnittstelle kann nur eine Klasse oder eine andere Schnittstelle erweitern.", + "An_interface_property_cannot_have_an_initializer_1246": "Schnittstelleneigenschaften können keinen Initialisierer aufweisen.", + "An_iterator_must_have_a_next_method_2489": "Ein Iterator muss eine Methode \"next()\" besitzen.", + "An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name_1118": "Ein Objektliteral darf nicht mehrere get-/set-Zugriffsmethoden mit dem gleichen Namen besitzen.", + "An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode_1117": "Ein Objektliteral darf im Strict-Modus nicht mehrere Eigenschaften mit dem gleichen Namen besitzen.", + "An_object_literal_cannot_have_property_and_accessor_with_the_same_name_1119": "Ein Objektliteral darf nicht eine Eigenschaft und eine Zugriffsmethode mit demselben Namen besitzen.", + "An_object_member_cannot_be_declared_optional_1162": "Ein Objektmember darf nicht als optional deklariert werden.", + "An_overload_signature_cannot_be_declared_as_a_generator_1222": "Eine Überladungssignatur darf nicht als ein Generator deklariert werden.", + "An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_ex_17006": "Unäre Ausdrücke mit dem Operator \"{0}\" sind auf der linken Seite von Potenzierungsausdrücken nicht zulässig. Erwägen Sie, den Ausdruck in Klammern zu setzen.", + "Annotate_everything_with_types_from_JSDoc_95043": "Alle Funktionen mit Typen aus JSDoc kommentieren", + "Annotate_with_type_from_JSDoc_95009": "Mit Typ aus JSDoc kommentieren", + "Annotate_with_types_from_JSDoc_95010": "Mit Typen aus JSDoc kommentieren", + "Argument_expression_expected_1135": "Es wurde ein Argumentausdruck erwartet.", + "Argument_for_0_option_must_be_Colon_1_6046": "Das Argument für die Option \"{0}\" muss \"{1}\" sein.", + "Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_2345": "Das Argument vom Typ \"{0}\" kann dem Parameter vom Typ \"{1}\" nicht zugewiesen werden.", + "Array_element_destructuring_pattern_expected_1181": "Ein Arrayelement-Destrukturierungsmuster wurde erwartet.", + "Asterisk_Slash_expected_1010": "\"*/\" wurde erwartet.", + "Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_2669": "Erweiterungen für den globalen Bereich können nur in externen Modulen oder Umgebungsmoduldeklarationen direkt geschachtelt werden.", + "Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambien_2670": "Erweiterungen für den globalen Bereich sollten den Modifizierer \"declare\" aufweisen, wenn sie nicht bereits in einem Umgebungskontext auftreten.", + "Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using__6140": "In Projekt \"{0}\" ist die automatische Erkennung von Eingaben aktiviert. Es wird ein zusätzlicher Auflösungsdurchlauf für das Modul \"{1}\" unter Verwendung von Cachespeicherort \"{2}\" ausgeführt.", + "Base_class_expressions_cannot_reference_class_type_parameters_2562": "Basisklassenausdrücke können nicht auf Klassentypparameter verweisen.", + "Base_constructor_return_type_0_is_not_a_class_or_interface_type_2509": "Der Rückgabetyp \"{0}\" des Basiskonstruktors ist keine Klasse oder kein Schnittstellentyp.", + "Base_constructors_must_all_have_the_same_return_type_2510": "Basiskonstruktoren müssen alle den gleichen Rückgabetyp aufweisen.", + "Base_directory_to_resolve_non_absolute_module_names_6083": "Das Basisverzeichnis zum Auflösen nicht absoluter Modulnamen.", + "Basic_Options_6172": "Standardoptionen", + "Binary_digit_expected_1177": "Es wurde eine Binärzahl erwartet.", + "Binding_element_0_implicitly_has_an_1_type_7031": "Das Bindungselement \"{0}\" weist implizit einen Typ \"{1}\" auf.", + "Block_scoped_variable_0_used_before_its_declaration_2448": "Die blockbezogene Variable \"{0}\" wurde vor ihrer Deklaration verwendet.", + "Build_all_projects_including_those_that_appear_to_be_up_to_date_6368": "Alle Projekte erstellen, einschließlich solcher, die anscheinend auf dem neuesten Stand sind", + "Build_one_or_more_projects_and_their_dependencies_if_out_of_date_6364": "Mindestens ein Projekt und die zugehörigen Abhängigkeiten erstellen, wenn veraltet", + "Building_project_0_6358": "Projekt \"{0}\" wird erstellt...", + "Call_decorator_expression_90028": "Decorator-Ausdruck aufrufen", + "Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7020": "Eine Aufrufsignatur ohne Rückgabetypanmerkung weist implizit einen any-Rückgabetyp auf.", + "Call_target_does_not_contain_any_signatures_2346": "Das Aufrufziel enthält keine Signaturen.", + "Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_p_2713": "Der Zugriff auf \"{0}.{1}\" ist nicht möglich, da \"{0}\" ein Typ ist, aber kein Namespace. Wollten Sie den Typ der Eigenschaft \"{1}\" in \"{0}\" mit \"{0}[\"{1}\"]\" abrufen?", + "Cannot_assign_a_0_constructor_type_to_a_1_constructor_type_2672": "Ein Konstruktortyp \"{0}\" kann nicht einem Konstruktortyp \"{1}\" zugewiesen werden.", + "Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type_2517": "Ein abstrakter Konstruktortyp kann nicht einem nicht abstrakten Konstruktortyp zugewiesen werden.", + "Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property_2540": "Eine Zuweisung zu \"{0}\" ist nicht möglich, weil es sich um eine Konstante oder eine schreibgeschützte Eigenschaft handelt.", + "Cannot_assign_to_0_because_it_is_not_a_variable_2539": "Eine Zuweisung zu \"{0}\" ist nicht möglich, weil es sich nicht um eine Variable handelt.", + "Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity_2671": "Das Modul \"{0}\" kann nicht erweitert werden, weil es in eine Nicht-Modulentität aufgelöst wird.", + "Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity_2649": "Das Modul \"{0}\" kann nicht mit Wertexporten vergrößert werden, da es zu einer Entität aufgelöst wird, die kein Modul darstellt.", + "Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system_6131": "Module können nur mithilfe der Option \"{0}\" kompiliert werden, wenn die Kennzeichnung \"-module\" den Wert \"amd\" oder \"system\" aufweist.", + "Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided_1208": "Namespaces können nicht kompiliert werden, wenn das Flag \"-isolatedModules\" angegeben wird.", + "Cannot_create_an_instance_of_an_abstract_class_2511": "Eine Instanz der abstrakten Klasse kann nicht erstellt werden.", + "Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module_2661": "\"{0}\" kann nicht exportiert werden. Nur lokale Deklarationen können aus einem Modul exportiert werden.", + "Cannot_extend_a_class_0_Class_constructor_is_marked_as_private_2675": "Eine Klasse \"{0}\" kann nicht erweitert werden. Der Klassenkonstruktor ist als privat markiert.", + "Cannot_extend_an_interface_0_Did_you_mean_implements_2689": "Eine Schnittstelle \"{0}\" kann nicht erweitert werden. Meinten Sie \"implements\"?", + "Cannot_find_a_tsconfig_json_file_at_the_specified_directory_Colon_0_5057": "Im angegebenen Verzeichnis \"{0}\" wurde keine \"tsconfig.json\"-Datei gefunden.", + "Cannot_find_global_type_0_2318": "Der globale Typ \"{0}\" wurde nicht gefunden.", + "Cannot_find_global_value_0_2468": "Der globale Wert \"{0}\" wurde nicht gefunden.", + "Cannot_find_lib_definition_for_0_2726": "Die Bibliotheksdefinition für \"{0}\" wurde nicht gefunden.", + "Cannot_find_lib_definition_for_0_Did_you_mean_1_2727": "Die Bibliotheksdefinition für \"{0}\" wurde nicht gefunden. Meinten Sie \"{1}\"?", + "Cannot_find_module_0_2307": "Das Modul \"{0}\" wurde nicht gefunden.", + "Cannot_find_name_0_2304": "Der Name \"{0}\" wurde nicht gefunden.", + "Cannot_find_name_0_Did_you_mean_1_2552": "Der Name \"{0}\" wurde nicht gefunden. Meinten Sie \"{1}\"?", + "Cannot_find_name_0_Did_you_mean_the_instance_member_this_0_2663": "Der Name \"{0}\" wurde nicht gefunden. Meinten Sie den Instanzmember \"this.{0}\"?", + "Cannot_find_name_0_Did_you_mean_the_static_member_1_0_2662": "Der Name \"{0}\" wurde nicht gefunden. Meinten Sie den statischen Member \"{1}.{0}\"?", + "Cannot_find_namespace_0_2503": "Der Namespace \"{0}\" wurde nicht gefunden.", + "Cannot_find_parameter_0_1225": "Der Parameter \"{0}\" wurde nicht gefunden.", + "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009": "Das gemeinsame Unterverzeichnis für die Eingabedateien wurde nicht gefunden.", + "Cannot_find_type_definition_file_for_0_2688": "Die Typdefinitionsdatei für \"{0}\" wurde nicht gefunden.", + "Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1_6137": "Typdeklarationsdateien können nicht importiert werden. Importieren Sie ggf. \"{0}\" anstelle von \"{1}\".", + "Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1_2481": "Die Variable \"{0}\" mit dem äußeren Bereich im gleichen Bereich wie die Deklaration \"{1}\" mit dem Blockbereich kann nicht initialisiert werden.", + "Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatur_2349": "Ein Ausdruck, dessen Typ eine Aufrufsignatur fehlt, kann nicht aufgerufen werden. Der Typ \"{0}\" weist keine kompatiblen Aufrufsignaturen auf.", + "Cannot_invoke_an_object_which_is_possibly_null_2721": "Ein Objekt, das möglicherweise NULL ist, kann nicht aufgerufen werden.", + "Cannot_invoke_an_object_which_is_possibly_null_or_undefined_2723": "Ein Objekt, das möglicherweise NULL oder nicht definiert ist, kann nicht aufgerufen werden.", + "Cannot_invoke_an_object_which_is_possibly_undefined_2722": "Ein Objekt, das möglicherweise nicht definiert ist, kann nicht aufgerufen werden.", + "Cannot_prepend_project_0_because_it_does_not_have_outFile_set_6308": "Das Projekt \"{0}\" kann nicht vorgestellt werden, weil \"outFile\" nicht festgelegt wurde.", + "Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205": "Ein Typ kann nicht erneut exportiert werden, wenn das Flag \"--isolatedModules\" angegeben ist.", + "Cannot_read_file_0_Colon_1_5012": "Die Datei \"{0}\" kann nicht gelesen werden: {1}", + "Cannot_redeclare_block_scoped_variable_0_2451": "Die blockbezogene Variable \"{0}\" Blockbereich kann nicht erneut deklariert werden.", + "Cannot_redeclare_exported_variable_0_2323": "Die exportierte Variable \"{0}\" kann nicht erneut deklariert werden.", + "Cannot_redeclare_identifier_0_in_catch_clause_2492": "Der Bezeichner \"{0}\" in der Catch-Klausel kann nicht erneut deklariert werden.", + "Cannot_use_JSX_unless_the_jsx_flag_is_provided_17004": "JSX kann nur verwendet werden, wenn das Flag \"-jsx\" angegeben wird.", + "Cannot_use_imports_exports_or_module_augmentations_when_module_is_none_1148": "Es können keine imports-, exports- oder module-Erweiterungen verwendet werden, wenn \"-module\" den Wert \"none\" aufweist.", + "Cannot_use_namespace_0_as_a_type_2709": "Der Namespace \"{0}\" kann nicht als Typ verwendet werden.", + "Cannot_use_namespace_0_as_a_value_2708": "Der Namespace \"{0}\" kann nicht als Wert verwendet werden.", + "Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature_2351": "\"new\" darf nicht mit einem Ausdruck verwendet werden, in dessen Typ eine Aufruf- oder Konstruktsignatur fehlt.", + "Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files_5056": "Die Datei \"{0}\" kann nicht geschrieben werden, da sie durch mehrere Eingabedateien überschrieben würde.", + "Cannot_write_file_0_because_it_would_overwrite_input_file_5055": "Die Datei \"{0}\" kann nicht geschrieben werden, da sie eine Eingabedatei überschreiben würde.", + "Catch_clause_variable_cannot_have_a_type_annotation_1196": "Die Variable der Catch-Klausel darf keine Typanmerkung aufweisen.", + "Catch_clause_variable_cannot_have_an_initializer_1197": "Die Variable der Catch-Klausel darf keinen Initialisierer aufweisen.", + "Change_0_to_1_90014": "\"{0}\" in \"{1}\" ändern", + "Change_all_extended_interfaces_to_implements_95038": "Alle erweiterten Schnittstellen in \"implements\" ändern", + "Change_all_jsdoc_style_types_to_TypeScript_95030": "Alle jsdoc-style-Typen in TypeScript ändern", + "Change_all_jsdoc_style_types_to_TypeScript_and_add_undefined_to_nullable_types_95031": "Alle jsdoc-style-Typen in TypeScript ändern (und Nullable-Typen \"| undefined\" hinzufügen)", + "Change_extends_to_implements_90003": "\"extends\" in \"implements\" ändern", + "Change_spelling_to_0_90022": "Schreibweise in \"{0}\" ändern", + "Checking_if_0_is_the_longest_matching_prefix_for_1_2_6104": "Es wird überprüft, ob \"{0}\" das längste übereinstimmende Präfix für \"{1}\"–\"{2}\" ist.", + "Circular_definition_of_import_alias_0_2303": "Zirkuläre Definition des Importalias \"{0}\".", + "Circularity_detected_while_resolving_configuration_Colon_0_18000": "Eine Zirkularität wurde beim Auflösen der Konfiguration erkannt: {0}", + "Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_functi_2426": "Die Klasse \"{0}\" definiert die Instanzmember-Zugriffsmethode \"{1}\", die erweiterte Klasse \"{2}\" definiert diesen jedoch als Instanzmemberfunktion.", + "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_access_2423": "Die Klasse \"{0}\" definiert die Instanzmember-Zugriffsmethode \"{1}\", die erweiterte Klasse \"{2}\" definiert diese jedoch als Instanzmember-Zugriffsmethode.", + "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_proper_2424": "Die Klasse \"{0}\" definiert die Instanzmemberfunktion \"{1}\", die erweiterte Klasse \"{2}\" definiert diese jedoch als Membereigenschaft.", + "Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_functi_2425": "Die Klasse \"{0}\" definiert die Instanzmembereigenschaft \"{1}\", die erweiterte Klasse \"{2}\" definiert diese jedoch als Instanzmemberfunktion.", + "Class_0_incorrectly_extends_base_class_1_2415": "Die Klasse \"{0}\" erweitert fälschlicherweise die Basisklasse \"{1}\".", + "Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclas_2720": "Die Klasse \"{0}\" implementiert fälschlicherweise die Klasse \"{1}\". Wollten Sie \"{1}\" erweitern und ihre Member als Unterklasse vererben?", + "Class_0_incorrectly_implements_interface_1_2420": "Die Klasse \"{0}\" implementiert fälschlicherweise die Schnittstelle \"{1}\".", + "Class_0_used_before_its_declaration_2449": "Klasse \"{0}\", die vor der Deklaration verwendet wurde.", + "Class_declarations_cannot_have_more_than_one_augments_or_extends_tag_8025": "Klassendeklarationen dürfen maximal ein \"@augments\"- oder \"@extends\"-Tag aufweisen.", + "Class_name_cannot_be_0_2414": "Der Klassenname darf nicht \"{0}\" sein.", + "Class_name_cannot_be_Object_when_targeting_ES5_with_module_0_2725": "Der Klassenname darf nicht \"Object\" lauten, wenn ES5 mit Modul \"{0}\" als Ziel verwendet wird.", + "Class_static_side_0_incorrectly_extends_base_class_static_side_1_2417": "Die statische Seite der Klasse \"{0}\" erweitert fälschlicherweise die statische Seite der Basisklasse \"{1}\".", + "Classes_can_only_extend_a_single_class_1174": "Klassen dürfen nur eine einzelne Klasse erweitern.", + "Classes_containing_abstract_methods_must_be_marked_abstract_2514": "Klassen, die abstrakte Methoden enthalten, müssen als abstrakt markiert werden.", + "Command_line_Options_6171": "Befehlszeilenoptionen", + "Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json_6020": "Kompilieren Sie das dem Pfad zugewiesene Projekt zu dessen Konfigurationsdatei oder zu einem Ordner mit der Datei \"tsconfig.json\".", + "Compiler_option_0_expects_an_argument_6044": "Die Compileroption \"{0}\" erwartet ein Argument.", + "Compiler_option_0_requires_a_value_of_type_1_5024": "Die Compileroption \"{0}\" erfordert einen Wert vom Typ \"{1}\".", + "Composite_projects_may_not_disable_declaration_emit_6304": "In zusammengesetzten Projekten kann die Deklarationsausgabe nicht deaktiviert werden.", + "Computed_property_names_are_not_allowed_in_enums_1164": "Berechnete Eigenschaftennamen sind in Enumerationen unzulässig.", + "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553": "Berechnete Werte sind in einer Enumeration mit Membern mit Zeichenfolgenwerten nicht zulässig.", + "Concatenate_and_emit_output_to_single_file_6001": "Verketten und Ausgabe in einer Datei speichern.", + "Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_librar_4090": "In Konflikt stehende Definitionen für \"{0}\" wurden unter \"{1}\" und \"{2}\" gefunden. Installieren Sie ggf. eine bestimmte Version dieser Bibliothek, um den Konflikt aufzulösen.", + "Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7013": "Eine Konstruktsignatur ohne Rückgabetypanmerkung weist implizit einen any-Rückgabetyp auf.", + "Constructor_implementation_is_missing_2390": "Die Konstruktorimplementierung fehlt.", + "Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration_2673": "Der Konstruktor der Klasse \"{0}\" ist privat. Auf ihn kann nur innerhalb der Klassendeklaration zugegriffen werden.", + "Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration_2674": "Der Konstruktor der Klasse \"{0}\" ist geschützt. Auf ihn kann nur innerhalb der Klassendeklaration zugegriffen werden.", + "Constructors_for_derived_classes_must_contain_a_super_call_2377": "Konstruktoren für abgeleitete Klassen müssen einen Aufruf \"super\" enthalten.", + "Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126": "Die enthaltene Datei wird nicht angegeben, und das Stammverzeichnis kann nicht ermittelt werden. Die Suche im Ordner \"node_modules\" wird übersprungen.", + "Convert_0_to_mapped_object_type_95055": "\"{0}\" in zugeordneten Objekttyp konvertieren", + "Convert_all_constructor_functions_to_classes_95045": "Alle Konstruktorfunktionen in Klassen konvertieren", + "Convert_all_require_to_import_95048": "Alle Aufrufe von \"require\" in \"import\" konvertieren", + "Convert_all_to_default_imports_95035": "Alle in Standardimporte konvertieren", + "Convert_function_0_to_class_95002": "Funktion \"{0}\" in Klasse konvertieren", + "Convert_function_to_an_ES2015_class_95001": "Funktion in eine ES2015-Klasse konvertieren", + "Convert_named_imports_to_namespace_import_95057": "Benannte Importe in Namespaceimport konvertieren", + "Convert_namespace_import_to_named_imports_95056": "Namespaceimport in benannte Importe konvertieren", + "Convert_require_to_import_95047": "\"require\" in \"import\" konvertieren", + "Convert_to_ES6_module_95017": "In ES6-Modul konvertieren", + "Convert_to_default_import_95013": "In Standardimport konvertieren", + "Corrupted_locale_file_0_6051": "Die Gebietsschemadatei \"{0}\" ist beschädigt.", + "Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type_7016": "Es wurde keine Deklarationsdatei für das Modul \"{0}\" gefunden. \"{1}\" weist implizit den Typ \"any\" auf.", + "Could_not_write_file_0_Colon_1_5033": "Die Datei \"{0}\" konnte nicht geschrieben werden. {1}.", + "DIRECTORY_6038": "VERZEICHNIS", + "Declaration_expected_1146": "Es wurde eine Deklaration erwartet.", + "Declaration_name_conflicts_with_built_in_global_identifier_0_2397": "Der Deklarationsname steht in Konflikt mit dem integrierten globalen Bezeichner \"{0}\".", + "Declaration_or_statement_expected_1128": "Es wurde eine Deklaration oder Anweisung erwartet.", + "Declare_method_0_90023": "Methode \"{0}\" deklarieren", + "Declare_property_0_90016": "Eigenschaft \"{0}\" deklarieren", + "Declare_static_method_0_90024": "Statische Methode \"{0}\" deklarieren", + "Declare_static_property_0_90027": "Statische Eigenschaft \"{0}\" deklarieren", + "Decorators_are_not_valid_here_1206": "Decorators sind hier ungültig.", + "Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name_1207": "Decorators dürfen nicht auf mehrere get-/set-Zugriffsmethoden mit dem gleichen Namen angewendet werden.", + "Default_export_of_the_module_has_or_is_using_private_name_0_4082": "Der Standardexport des Moduls besitzt oder verwendet den privaten Namen \"{0}\".", + "Delete_all_unused_declarations_95024": "Alle nicht verwendeten Deklarationen löschen", + "Delete_the_outputs_of_all_projects_6365": "Ausgaben aller Projekte löschen", + "Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react__6084": "[Veraltet] Verwenden Sie stattdessen \"--jsxFactory\". Geben Sie das Objekt an, das für \"createElement\" aufgerufen wurde, wenn das Ziel die JSX-Ausgabe \"react\" ist.", + "Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file_6170": "[Veraltet] Verwenden Sie stattdessen \"--outFile\". Verketten und Ausgeben in eine einzige Datei", + "Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files_6160": "[Veraltet] Verwenden Sie stattdessen \"--skipLibCheck\". Überspringen Sie die Typüberprüfung der Standardbibliothek-Deklarationsdateien.", + "Digit_expected_1124": "Eine Ziffer wurde erwartet.", + "Directory_0_does_not_exist_skipping_all_lookups_in_it_6148": "Das Verzeichnis \"{0}\" ist nicht vorhanden, Suchvorgänge darin werden übersprungen.", + "Disable_checking_for_this_file_90018": "Überprüfung für diese Datei deaktivieren", + "Disable_size_limitations_on_JavaScript_projects_6162": "Größenbeschränkungen für JavaScript-Projekte deaktivieren.", + "Disable_strict_checking_of_generic_signatures_in_function_types_6185": "Deaktivieren Sie die strenge Überprüfung generischer Signaturen in Funktionstypen.", + "Disallow_inconsistently_cased_references_to_the_same_file_6078": "Verweise mit uneinheitlicher Groß-/Kleinschreibung auf die gleiche Datei nicht zulassen.", + "Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files_6159": "Fügen Sie keine Verweise mit dreifachen Schrägstrichen oder importierte Module zur Liste kompilierter Dateien hinzu.", + "Do_not_emit_comments_to_output_6009": "Kommentare nicht an die Ausgabe ausgeben.", + "Do_not_emit_declarations_for_code_that_has_an_internal_annotation_6056": "Deklarationen für Code mit einer Anmerkung \"@internal\" nicht ausgeben.", + "Do_not_emit_outputs_6010": "Keine Ausgaben ausgeben.", + "Do_not_emit_outputs_if_any_errors_were_reported_6008": "Keine Ausgaben ausgeben, wenn Fehler gemeldet wurden.", + "Do_not_emit_use_strict_directives_in_module_output_6112": "Keine \"use strict\"-Direktiven in Modulausgabe ausgeben.", + "Do_not_erase_const_enum_declarations_in_generated_code_6007": "const-Enumerationsdeklarationen im generierten Code nicht löschen.", + "Do_not_generate_custom_helper_functions_like_extends_in_compiled_output_6157": "Erstellen Sie keine benutzerdefinierten Hilfsfunktionen wie \"__extends\" in der kompilierten Ausgabe.", + "Do_not_include_the_default_library_file_lib_d_ts_6158": "Beziehen Sie die Standardbibliotheksdatei (lib.d.ts) nicht ein.", + "Do_not_report_errors_on_unreachable_code_6077": "Fehler zu nicht erreichbarem Code nicht melden.", + "Do_not_report_errors_on_unused_labels_6074": "Fehler zu nicht verwendeten Bezeichnungen nicht melden.", + "Do_not_resolve_the_real_path_of_symlinks_6013": "Tatsächlichen Pfad von symbolischen Verknüpfungen nicht auflösen.", + "Do_not_truncate_error_messages_6165": "Kürzen Sie keine Fehlermeldungen.", + "Duplicate_declaration_0_2718": "Doppelte Deklaration \"{0}\".", + "Duplicate_function_implementation_2393": "Doppelte Funktionsimplementierung.", + "Duplicate_identifier_0_2300": "Doppelter Bezeichner \"{0}\".", + "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_2441": "Doppelter Bezeichner \"{0}\". Der Compiler reserviert den Namen \"{1}\" im Bereich der obersten Ebene eines Moduls.", + "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_func_2529": "Doppelter Bezeichner \"{0}\". Der Compiler reserviert den Namen \"{1}\" im Bereich der obersten Ebene eines Moduls, das asynchrone Funktionen enthält.", + "Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions_2520": "Doppelter Bezeichner \"{0}\". Der Compiler verwendet die Deklaration \"{1}\", um asynchrone Funktionen zu unterstützen.", + "Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters_2396": "Doppelter Bezeichner \"arguments\". Der Compiler verwendet \"arguments\" zum Initialisieren der rest-Parameter.", + "Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_me_2543": "Doppelter Bezeichner \"_newTarget\". Der Compiler verwendet die Variablendeklaration \"_newTarget\" zum Erfassen der Metaeigenschaftenreferenz \"new.target\".", + "Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference_2401": "Doppelter Bezeichner \"_super\". Der Compiler verwendet \"_super\" zum Erfassen des Basisklassenverweises.", + "Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference_2399": "Doppelter Bezeichner \"_this\". Der Compiler verwendet die Variablendeklaration \"_this\" zum Erfassen des this-Verweises.", + "Duplicate_label_0_1114": "Doppelte Bezeichnung \"{0}\".", + "Duplicate_number_index_signature_2375": "Doppelte Zahlenindexsignatur.", + "Duplicate_string_index_signature_2374": "Doppelte Zeichenfolgen-Indexsignatur.", + "Dynamic_import_cannot_have_type_arguments_1326": "Der dynamische Import kann nicht über Typargumente verfügen.", + "Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext_1323": "Der dynamische Import wird nur unterstützt, wenn das Flag \"--module\" auf \"commonjs\" oder \"esNext\" festgelegt ist.", + "Dynamic_import_must_have_one_specifier_as_an_argument_1324": "Der dynamische Import benötigt einen Spezifizierer als Argument.", + "Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036": "Der Spezifizierer des dynamischen Imports muss den Typ \"string\" aufweisen, hier ist er jedoch vom Typ \"{0}\".", + "Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015": "Das Element weist implizit einen Typ \"any\" auf, weil der Indexausdruck nicht vom Typ \"number\" ist.", + "Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature_7017": "Das Element weist implizit einen Typ \"any\" auf, weil der Typ \"{0}\" keine Indexsignatur umfasst.", + "Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files_6164": "Geben Sie zu Beginn der Ausgabedateien eine UTF-8-Bytereihenfolge-Marke (BOM) aus.", + "Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file_6151": "Geben Sie eine einzelne Datei mit Quellzuordnungen anstelle einer separaten Datei aus.", + "Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap__6152": "Geben Sie die Quelle zusammen mit den Quellzuordnungen innerhalb einer einzelnen Datei aus; hierfür muss \"--inlineSourceMap\" oder \"--sourceMap\" festgelegt sein.", + "Enable_all_strict_type_checking_options_6180": "Aktivieren Sie alle strengen Typüberprüfungsoptionen.", + "Enable_project_compilation_6302": "Projektkompilierung aktivieren", + "Enable_strict_checking_of_function_types_6186": "Aktivieren Sie die strenge Überprüfung für Funktionstypen.", + "Enable_strict_checking_of_property_initialization_in_classes_6187": "Aktivieren Sie die strenge Überprüfung der Eigenschafteninitialisierung in Klassen.", + "Enable_strict_null_checks_6113": "Strenge NULL-Überprüfungen aktivieren.", + "Enable_tracing_of_the_name_resolution_process_6085": "Ablaufverfolgung des Namensauflösungsvorgangs aktivieren.", + "Enable_verbose_logging_6366": "Ausführliche Protokollierung aktivieren", + "Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for__7037": "Ermöglicht Ausgabeinteroperabilität zwischen CommonJS- und ES-Modulen durch die Erstellung von Namespaceobjekten für alle Importe. Impliziert \"AllowSyntheticDefaultImports\".", + "Enables_experimental_support_for_ES7_async_functions_6068": "Ermöglicht experimentelle Unterstützung für asynchrone ES7-Funktionen.", + "Enables_experimental_support_for_ES7_decorators_6065": "Ermöglicht experimentelle Unterstützung für asynchrone ES7-Decorators.", + "Enables_experimental_support_for_emitting_type_metadata_for_decorators_6066": "Ermöglicht experimentelle Unterstützung zum Ausgeben von Typmetadaten für Decorators.", + "Enum_0_used_before_its_declaration_2450": "Enumeration \"{0}\", die vor der Deklaration wurde.", + "Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations_2567": "Enumerationsdeklarationen können nur mit Namespace- oder anderen Enumerationsdeklarationen zusammengeführt werden.", + "Enum_declarations_must_all_be_const_or_non_const_2473": "Enumerationsdeklarationen müssen alle konstant oder nicht konstant sein.", + "Enum_member_expected_1132": "Ein Enumerationsmember wurde erwartet.", + "Enum_member_must_have_initializer_1061": "Ein Enumerationsmember muss einen Initialisierer aufweisen.", + "Enum_name_cannot_be_0_2431": "Der Enumerationsname darf nicht \"{0}\" sein.", + "Enum_type_0_has_members_with_initializers_that_are_not_literals_2535": "Der Enumerationstyp \"{0}\" weist Member mit Initialisierern auf, die keine Literale sind.", + "Examples_Colon_0_6026": "Beispiele: {0}", + "Excessive_stack_depth_comparing_types_0_and_1_2321": "Übermäßige Stapeltiefe beim Vergleichen der Typen \"{0}\" und \"{1}\".", + "Expected_0_1_type_arguments_provide_these_with_an_extends_tag_8027": "{0}-{1} Typargumente erwartet; geben Sie diese mit einem @extends-Tag an.", + "Expected_0_arguments_but_got_1_2554": "{0} Argumente wurden erwartet, empfangen wurden aber {1}.", + "Expected_0_arguments_but_got_1_or_more_2556": "{0} Argumente wurden erwartet, empfangen wurden aber mindestens {1}.", + "Expected_0_type_arguments_but_got_1_2558": "{0} Typenargumente wurden erwartet, empfangen wurden aber {1}.", + "Expected_0_type_arguments_provide_these_with_an_extends_tag_8026": "{0} Typargumente erwartet; geben Sie diese mit einem @extends-Tag an.", + "Expected_at_least_0_arguments_but_got_1_2555": "Mindestens {0} Argumente wurden erwartet, empfangen wurden aber {1}.", + "Expected_at_least_0_arguments_but_got_1_or_more_2557": "Mindestens {0} Argumente wurden erwartet, empfangen wurden aber mindestens {1}.", + "Expected_corresponding_JSX_closing_tag_for_0_17002": "Das entsprechende schließende JSX-Tag wurde für \"{0}\" erwartet.", + "Expected_corresponding_closing_tag_for_JSX_fragment_17015": "Für das JSX-Fragment wurde das entsprechende schließende Tag erwartet.", + "Expected_type_of_0_field_in_package_json_to_be_string_got_1_6105": "Der erwartete Typ des Felds \"{0}\" in der Datei \"package.json\" ist \"string\". Abgerufener Typ: \"{1}\".", + "Experimental_Options_6177": "Experimentelle Optionen", + "Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_t_1219": "Experimentelle Unterstützung für Decorator-Elemente ist ein Feature, das in zukünftigen Versionen Änderungen unterliegt. Legen Sie die Option \"-experimentalDecorators\" fest, um diese Warnung zu entfernen.", + "Explicitly_specified_module_resolution_kind_Colon_0_6087": "Explizit angegebene Art der Modulauflösung: \"{0}\".", + "Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or__1203": "Die Exportzuweisung darf nicht verwendet werden, wenn das Ziel ECMAScript-Module sind. Verwenden Sie stattdessen ggf. \"export default\" oder ein anderes Modulformat.", + "Export_assignment_is_not_supported_when_module_flag_is_system_1218": "Die Exportzuweisung wird nicht unterstützt, wenn das Flag \"-module\" den Wert \"system\" aufweist.", + "Export_declaration_conflicts_with_exported_declaration_of_0_2484": "Die Exportdeklaration verursacht einen Konflikt mit der exportierten Deklaration von \"{0}\".", + "Export_declarations_are_not_permitted_in_a_namespace_1194": "Exportdeklarationen sind in einem Namespace unzulässig.", + "Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_2656": "Die exportierte externe Pakettypisierungsdatei \"{0}\" ist kein Modul. Bitte wenden Sie sich an den Paketautor, um die Paketdefinition zu aktualisieren.", + "Exported_external_package_typings_file_cannot_contain_tripleslash_references_Please_contact_the_pack_2654": "Exportierte externe Pakettypisierungen dürfen keine Verweise mit drei Schrägstrichen enthalten. Bitte wenden Sie sich an den Paketautor, um die Paketdefinition zu aktualisieren.", + "Exported_type_alias_0_has_or_is_using_private_name_1_4081": "Der exportierte Typalias \"{0}\" besitzt oder verwendet den privaten Namen \"{1}\".", + "Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4023": "Die exportierte Variable \"{0}\" besitzt oder verwendet den Namen \"{1}\" aus dem externen Modul \"{2}\", kann aber nicht benannt werden.", + "Exported_variable_0_has_or_is_using_name_1_from_private_module_2_4024": "Die exportierte Variable \"{0}\" besitzt oder verwendet den Namen \"{1}\" aus dem privaten Modul \"{2}\".", + "Exported_variable_0_has_or_is_using_private_name_1_4025": "Die exportierte Variable \"{0}\" besitzt oder verwendet den privaten Namen \"{1}\".", + "Exports_and_export_assignments_are_not_permitted_in_module_augmentations_2666": "Exporte und Exportzuweisungen sind in Modulerweiterungen unzulässig.", + "Expression_expected_1109": "Es wurde ein Ausdruck erwartet.", + "Expression_or_comma_expected_1137": "Es wurde ein Ausdruck oder Komma erwartet.", + "Expression_resolves_to_super_that_compiler_uses_to_capture_base_class_reference_2402": "Der Ausdruck wird in \"_super\" aufgelöst. Damit erfasst der Compiler den Basisklassenverweis.", + "Expression_resolves_to_variable_declaration_0_that_compiler_uses_to_support_async_functions_2521": "Der Ausdruck wird in die Variablendeklaration \"{0}\" aufgelöst, die der Compiler verwendet, um asynchrone Funktionen zu unterstützen.", + "Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta__2544": "Der Ausdruck wird in die Variablendeklaration \"_newTarget\" aufgelöst, die der Compiler zum Erfassen der Metaeigenschaftenreferenz \"new.target\" verwendet.", + "Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference_2400": "Der Ausdruck wird in die Variablendeklaration \"_this\" aufgelöst, die der Compiler verwendet, um den this-Verweis zu erfassen.", + "Extract_constant_95006": "Konstante extrahieren", + "Extract_function_95005": "Funktion extrahieren", + "Extract_to_0_in_1_95004": "Als {0} nach {1} extrahieren", + "Extract_to_0_in_1_scope_95008": "Als {0} in {1}-Bereich extrahieren", + "Extract_to_0_in_enclosing_scope_95007": "Als {0} in einschließenden Bereich extrahieren", + "FILE_6035": "DATEI", + "FILE_OR_DIRECTORY_6040": "DATEI ODER VERZEICHNIS", + "Failed_to_parse_file_0_Colon_1_5014": "Fehler beim Analysieren der Datei \"{0}\": {1}.", + "Fallthrough_case_in_switch_7029": "FallThrough-Fall in switch-Anweisung.", + "File_0_does_not_exist_6096": "Die Datei \"{0}\" ist nicht vorhanden.", + "File_0_exist_use_it_as_a_name_resolution_result_6097": "Die Datei \"{0}\" ist vorhanden – sie wird als Ergebnis der Namensauflösung verwendet.", + "File_0_has_an_unsupported_extension_so_skipping_it_6081": "Die Datei \"{0}\" hat eine nicht unterstützte Erweiterung und wird übersprungen.", + "File_0_has_unsupported_extension_The_only_supported_extensions_are_1_6054": "Die Datei \"{0}\" weist eine nicht unterstützte Erweiterung auf. Die einzigen unterstützten Erweiterungen sind \"{1}\".", + "File_0_is_not_a_module_2306": "Die Datei \"{0}\" ist kein Modul.", + "File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern_6307": "Die Datei \"{0}\" befindet sich nicht in der Liste der Projektdateien. Projekte müssen alle Dateien auflisten oder ein include-Muster verwenden.", + "File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files_6059": "Datei \"{0}\" befindet sich nicht unter \"rootDir\" \"{1}\". \"rootDir\" muss alle Quelldateien enthalten.", + "File_0_not_found_6053": "Die Datei \"{0}\" wurde nicht gefunden.", + "File_change_detected_Starting_incremental_compilation_6032": "Es wurde eine Dateiänderung erkannt. Die inkrementelle Kompilierung wird gestartet...", + "File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module_80001": "Die Datei ist ein CommonJS-Modul, sie kann in ein ES6-Modul konvertiert werden.", + "File_name_0_differs_from_already_included_file_name_1_only_in_casing_1149": "Der Dateiname \"{0}\" unterscheidet sich vom bereits enthaltenen Dateinamen \"{1}\" nur hinsichtlich der Groß-/Kleinschreibung.", + "File_name_0_has_a_1_extension_stripping_it_6132": "Der Dateiname \"{0}\" weist eine Erweiterung \"{1}\" auf. Diese wird entfernt.", + "File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildca_5065": "Die Dateispezifikation darf kein übergeordnetes Verzeichnis (\"..\") enthalten, das nach einem rekursiven Verzeichnisplatzhalter (\"**\") angegeben wird: \"{0}\".", + "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010": "Die Dateispezifikation darf nicht mit einem rekursiven Verzeichnisplatzhalter (\"**\") enden: \"{0}\".", + "Fix_all_detected_spelling_errors_95026": "Alle erkannten Rechtschreibfehler korrigieren", + "Found_0_errors_Watching_for_file_changes_6194": "{0} Fehler gefunden. Es wird auf Dateiänderungen überwacht.", + "Found_1_error_Watching_for_file_changes_6193": "1 Fehler gefunden. Es wird auf Dateiänderungen überwacht.", + "Found_package_json_at_0_6099": "\"package.json\" wurde unter \"{0}\" gefunden.", + "Found_package_json_at_0_Package_ID_is_1_6190": "\"Package.json\" unter \"{0}\" gefunden. Paket-ID: \"{1}\".", + "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_1250": "Funktionsdeklarationen sind in Blöcken im Strict-Modus unzulässig, wenn das Ziel \"ES3\" oder \"ES5\" ist.", + "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_d_1251": "Funktionsdeklarationen sind in Blöcken im Strict-Modus unzulässig, wenn das Ziel \"ES3\" oder \"ES5\" ist. Klassendefinitionen befinden sich automatisch im Strict-Modus.", + "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_1252": "Funktionsdeklarationen sind in Blöcken im Strict-Modus unzulässig, wenn das Ziel \"ES3\" oder \"ES5\" ist. Module befinden sich automatisch im Strict-Modus.", + "Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type_7011": "Ein Funktionsausdruck ohne Rückgabetypanmerkung weist implizit einen {0}-Rückgabetyp auf.", + "Function_implementation_is_missing_or_not_immediately_following_the_declaration_2391": "Die Funktionsimplementierung fehlt oder folgt nicht unmittelbar auf die Deklaration.", + "Function_implementation_name_must_be_0_2389": "Der Name der Funktionsimplementierung muss \"{0}\" lauten.", + "Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_ref_7024": "Die Funktion weist implizit den Typ \"any\" auf, weil keine Rückgabetypanmerkung vorhanden ist und darauf direkt oder indirekt in einem ihrer Rückgabeausdrücke verwiesen wird.", + "Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined_2366": "Der Funktion fehlt die abschließende return-Anweisung, und der Rückgabetyp enthält nicht \"undefined\".", + "Function_overload_must_be_static_2387": "Die Funktionsüberladung muss statisch sein.", + "Function_overload_must_not_be_static_2388": "Die Funktionsüberladung darf nicht statisch sein.", + "Generate_get_and_set_accessors_95046": "GET- und SET-Accessoren generieren", + "Generates_a_sourcemap_for_each_corresponding_d_ts_file_6000": "Generiert eine sourcemap für jede entsprechende .d.ts-Datei.", + "Generates_corresponding_d_ts_file_6002": "Generiert die entsprechende .d.ts-Datei.", + "Generates_corresponding_map_file_6043": "Generiert die entsprechende MAP-Datei.", + "Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_typ_7025": "Der Generator weist implizit den Typ \"{0}\" auf, weil er keine Werte ausgibt. Sie können ggf. einen Rückgabetyp angeben.", + "Generators_are_not_allowed_in_an_ambient_context_1221": "Generatoren sind in einem Umgebungskontext unzulässig.", + "Generators_are_only_available_when_targeting_ECMAScript_2015_or_higher_1220": "Generatoren sind nur verfügbar, wenn das Ziel ECMAScript 2015 oder höher ist.", + "Generic_type_0_requires_1_type_argument_s_2314": "Der generische Typ \"{0}\" erfordert {1} Typargument(e).", + "Generic_type_0_requires_between_1_and_2_type_arguments_2707": "Der generische Typ \"{0}\" benötigt zwischen {1} und {2} Typargumente.", + "Generic_type_instantiation_is_excessively_deep_and_possibly_infinite_2550": "Generische Typinstanziierung ist übermäßig tief und möglicherweise unendlich.", + "Getter_and_setter_accessors_do_not_agree_in_visibility_2379": "Die Sichtbarkeit der Getter- und Setter-Zugriffsmethoden stimmt nicht überein.", + "Global_module_exports_may_only_appear_at_top_level_1316": "Globale Modulexporte dürfen nur auf der obersten Ebene auftreten.", + "Global_module_exports_may_only_appear_in_declaration_files_1315": "Globale Modulexporte dürfen nur in Deklarationsdateien auftreten.", + "Global_module_exports_may_only_appear_in_module_files_1314": "Globale Modulexporte dürfen nur in Moduldateien auftreten.", + "Global_type_0_must_be_a_class_or_interface_type_2316": "Der globale Typ \"{0}\" muss eine Klassen- oder Schnittstellentyp sein.", + "Global_type_0_must_have_1_type_parameter_s_2317": "Der globale Typ \"{0}\" muss {1} Typparameter aufweisen.", + "Hexadecimal_digit_expected_1125": "Es wurde eine hexadezimale Zahl erwartet.", + "Identifier_expected_0_is_a_reserved_word_in_strict_mode_1212": "Ein Bezeichner wird erwartet. \"{0}\" ist ein reserviertes Wort im Strict-Modus.", + "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_stric_1213": "Es wurde ein Bezeichner erwartet. \"{0}\" ist ein reserviertes Wort im Strict-Modus. Klassendefinitionen befinden sich automatisch im Strict-Modus.", + "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode_1214": "Es wurde ein Bezeichner erwartet. \"{0}\" ist ein reserviertes Wort im Strict-Modus. Module befinden sich automatisch im Strict-Modus.", + "Identifier_expected_1003": "Es wurde ein Bezeichner erwartet.", + "Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules_1216": "Bezeichner erwartet. \"__esModule\" ist als exportierter Marker für die Umwandlung von ECMAScript-Modulen reserviert.", + "Ignore_this_error_message_90019": "Diese Fehlermeldung ignorieren", + "Implement_all_inherited_abstract_classes_95040": "Alle geerbten abstrakten Klassen implementieren", + "Implement_all_unimplemented_interfaces_95032": "Alle nicht implementierten Schnittstellen implementieren", + "Implement_inherited_abstract_class_90007": "Geerbte abstrakte Klasse implementieren", + "Implement_interface_0_90006": "Schnittstelle \"{0}\" implementieren", + "Implements_clause_of_exported_class_0_has_or_is_using_private_name_1_4019": "Die implements-Klausel der exportierten Klasse \"{0}\" besitzt oder verwendet den privaten Namen \"{1}\".", + "Import_0_from_module_1_90013": "\"{0}\" aus dem Modul \"{1}\" importieren", + "Import_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_import_Asterisk_as_1202": "Die Importzuweisung kann nicht verwendet werden, wenn das Ziel ECMAScript-Module sind. Verwenden Sie stattdessen ggf. \"import * as ns from 'mod'\", \"import {a} from 'mod'\", \"import d from 'mod'\" oder ein anderes Modulformat.", + "Import_declaration_0_is_using_private_name_1_4000": "Die Importdeklaration \"{0}\" verwendet den privaten Namen \"{1}\".", + "Import_declaration_conflicts_with_local_declaration_of_0_2440": "Die Importdeklaration verursacht einen Konflikt mit der lokalen Deklaration von \"{0}\".", + "Import_declarations_in_a_namespace_cannot_reference_a_module_1147": "Importdeklarationen in einem Namespace dürfen nicht auf ein Modul verweisen.", + "Import_emit_helpers_from_tslib_6139": "Ausgabehilfsprogramme aus \"tslib\" importieren.", + "Import_may_be_converted_to_a_default_import_80003": "Der Import kann in einen Standardimport konvertiert werden.", + "Import_name_cannot_be_0_2438": "Der Importname darf nicht \"{0}\" sein.", + "Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relati_2439": "Import- oder Exportdeklaration in einer Umgebungsmoduldeklaration dürfen nicht über den relativen Modulnamen auf ein Modul verweisen.", + "Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_mod_2667": "Importe sind in Modulerweiterungen unzulässig. Verschieben Sie diese ggf. in das einschließende externe Modul.", + "In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066": "In Umgebungsenumerationsdeklarationen muss der Memberinitialisierer ein konstanter Ausdruck sein.", + "In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enu_2432": "In einer Enumeration mit mehreren Deklarationen kann nur eine Deklaration einen Initialisierer für das erste Enumerationselement ausgeben.", + "In_const_enum_declarations_member_initializer_must_be_constant_expression_2474": "In const-Enumerationsdeklarationen muss der Memberinitialisierer ein konstanter Ausdruck sein.", + "Include_modules_imported_with_json_extension_6197": "Importierte Module mit der Erweiterung \"JSON\" einschließen", + "Index_signature_in_type_0_only_permits_reading_2542": "Die Indexsignatur in Typ \"{0}\" lässt nur Lesevorgänge zu.", + "Index_signature_is_missing_in_type_0_2329": "Die Indexsignatur fehlt im Typ \"{0}\".", + "Index_signatures_are_incompatible_2330": "Die Indexsignaturen sind nicht kompatibel.", + "Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local_2395": "Einzelne Deklarationen in der gemergten Deklaration \"{0}\" müssen alle exportiert oder alle lokal sein.", + "Infer_all_types_from_usage_95023": "Alle Typen aus der Syntax ableiten", + "Infer_parameter_types_from_usage_95012": "Parametertypen aus der Nutzung ableiten", + "Infer_type_of_0_from_usage_95011": "Typ von \"{0}\" aus der Nutzung ableiten", + "Initialize_property_0_in_the_constructor_90020": "Eigenschaft \"{0}\" im Konstruktor initialisieren", + "Initialize_static_property_0_90021": "Statische Eigenschaft \"{0}\" initialisieren", + "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301": "Der Initialisierer der Instanzmembervariablen \"{0}\" darf nicht auf den im Konstruktor deklarierten Bezeichner \"{1}\" verweisen.", + "Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it_2373": "Der Initialisierer des Parameters \"{0}\" darf nicht auf den anschließend deklarierten Bezeichner \"{1}\" verweisen.", + "Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value_2525": "Der Initialisierer stellt keinen Wert für dieses Bindungselement bereit, und das Bindungselement besitzt keinen Standardwert.", + "Initializers_are_not_allowed_in_ambient_contexts_1039": "Initialisierer sind in Umgebungskontexten unzulässig.", + "Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file_6070": "Initialisiert ein TypeScript-Projekt und erstellt eine Datei \"tsconfig.json\".", + "Insert_command_line_options_and_files_from_a_file_6030": "Fügt Befehlszeilenoptionen und Dateien aus einer Datei ein.", + "Install_0_95014": "\"{0}\" installieren", + "Install_all_missing_types_packages_95033": "Alle fehlenden Typenpakete installieren", + "Interface_0_cannot_simultaneously_extend_types_1_and_2_2320": "Die Schnittstelle \"{0}\" kann die Typen \"{1}\" und \"{2}\" nicht gleichzeitig erweitern.", + "Interface_0_incorrectly_extends_interface_1_2430": "Die Schnittstelle \"{0}\" erweitert fälschlicherweise die Schnittstelle \"{1}\".", + "Interface_declaration_cannot_have_implements_clause_1176": "Die Schnittstellendeklarationen darf keine implements-Klausel aufweisen.", + "Interface_name_cannot_be_0_2427": "Der Schnittstellenname darf nicht \"{0}\" sein.", + "Invalid_character_1127": "Ungültiges Zeichen.", + "Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augm_2665": "Ungültiger Modulname in Augmentation. Das Modul \"{0}\" wird in ein nicht typisiertes Modul in \"{1}\" aufgelöst, das nicht augmentiert werden kann.", + "Invalid_module_name_in_augmentation_module_0_cannot_be_found_2664": "Ungültiger Modulname in der Erweiterung. Das Modul \"{0}\" wurde nicht gefunden.", + "Invalid_reference_directive_syntax_1084": "Ungültige Syntax der reference-Direktive.", + "Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode_1210": "Ungültige Verwendung von \"{0}\". Klassendefinitionen befinden sich automatisch im Strict-Modus.", + "Invalid_use_of_0_Modules_are_automatically_in_strict_mode_1215": "Ungültige Verwendung von \"{0}\". Module befinden sich automatisch im Strict-Modus.", + "Invalid_use_of_0_in_strict_mode_1100": "Ungültige Verwendung von \"{0}\" im Strict-Modus.", + "Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name_5067": "Ungültiger Wert für \"jsxFactory\". \"{0}\" ist kein gültiger Bezeichner oder qualifizierter Name.", + "Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier_5059": "Ungültiger Wert für \"-reactNamespace\". \"{0}\" ist kein gültiger Bezeichner.", + "JSDoc_0_1_does_not_match_the_extends_2_clause_8023": "JSDoc \"@{0} {1}\" entspricht nicht der Klausel \"extends {2}\".", + "JSDoc_0_is_not_attached_to_a_class_8022": "JSDoc \"@{0}\" ist keiner Klassendeklaration zugeordnet.", + "JSDoc_may_only_appear_in_the_last_parameter_of_a_signature_8028": "Das JSDoc-Tag \"...\" wird möglicherweise nur im letzten Parameter einer Signatur angezeigt.", + "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_8024": "Das JSDoc-Tag \"@param\" weist den Namen \"{0}\" auf, es gibt jedoch keinen Parameter dieses Namens.", + "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_h_8029": "Das JSDoc-Tag \"@param\" weist den Namen \"{0}\" auf, es ist jedoch kein Parameter dieses Namens vorhanden. Es läge eine Übereinstimmung mit \"arguments\" vor, wenn ein Arraytyp vorläge.", + "JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags_8021": "Das JSDoc-Tag \"@typedef\" muss entweder eine Typanmerkung aufweisen, oder die Tags \"@property\" oder \"@member\" müssen darauf folgen.", + "JSDoc_types_can_only_be_used_inside_documentation_comments_8020": "JSDoc-Typen können nur innerhalb von Dokumentationskommentaren verwendet werden.", + "JSDoc_types_may_be_moved_to_TypeScript_types_80004": "JSDoc-Typen können in TypeScript-Typen verschoben werden.", + "JSX_attribute_expected_17003": "Ein JSX-Attribut wurde erwartet.", + "JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000": "JSX-Attributen darf nur ein nicht leeres expression-Objekt zugewiesen werden.", + "JSX_element_0_has_no_corresponding_closing_tag_17008": "Das JSX-Element \"{0}\" weist kein entsprechendes schließendes Tag auf.", + "JSX_element_attributes_type_0_may_not_be_a_union_type_2600": "Der JSX-Elementattributtyp \"{0}\" darf kein Union-Typ sein.", + "JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property_2607": "Die JSX-Elementklasse unterstützt keine Attribute, weil sie keine Eigenschaft \"{0}\" aufweist.", + "JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists_7026": "Das JSX-Element enthält implizit den Typ \"any\", weil keine Schnittstelle \"JSX.{0}\" vorhanden ist.", + "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602": "Das JSX-Element enthält implizit den Typ \"any\", weil der globale Typ \"JSX.Element\" nicht vorhanden ist.", + "JSX_element_type_0_does_not_have_any_construct_or_call_signatures_2604": "Der JSX-Elementtyp \"{0}\"weist keine Konstrukt- oder Aufrufsignaturen auf.", + "JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements_2605": "Der JSX-Elementtyp \"{0}\" ist keine Konstruktorfunktion für JSX-Elemente.", + "JSX_elements_cannot_have_multiple_attributes_with_the_same_name_17001": "JSX-Elemente dürfen nicht mehrere Attribute mit dem gleichen Namen aufweisen.", + "JSX_expressions_must_have_one_parent_element_2657": "JSX-Ausdrücke müssen ein übergeordnetes Element aufweisen.", + "JSX_fragment_has_no_corresponding_closing_tag_17014": "Das JSX-Fragment weist kein entsprechendes schließendes Tag auf.", + "JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma_17017": "Ein JSX-Fragment wird bei Verwendung eines Inline-JSX-Factory-Pragmas nicht unterstützt.", + "JSX_fragment_is_not_supported_when_using_jsxFactory_17016": "Das JSX-Fragment wird bei Verwendung von --jsxFactory nicht unterstützt.", + "JSX_spread_child_must_be_an_array_type_2609": "Die untergeordnete JSX-Verteilung muss ein Arraytyp sein.", + "Jump_target_cannot_cross_function_boundary_1107": "Das Sprungziel darf die Funktionsgrenze nicht überschreiten.", + "KIND_6034": "ART", + "LOCATION_6037": "SPEICHERORT", + "Language_service_is_disabled_9004": "Der Sprachdienst ist deaktiviert.", + "Left_side_of_comma_operator_is_unused_and_has_no_side_effects_2695": "Die linke Seite des Kommaoperators wird nicht verwendet besitzt keine Nebenwirkungen.", + "Line_break_not_permitted_here_1142": "Ein Zeilenumbruch ist hier unzulässig.", + "Line_terminator_not_permitted_before_arrow_1200": "Das Zeilenabschlusszeichen ist vor dem Pfeil unzulässig.", + "List_of_folders_to_include_type_definitions_from_6161": "Liste der Ordner, aus denen Typendefinitionen einbezogen werden sollen.", + "List_of_language_service_plugins_6181": "Liste der Sprachdienst-Plug-ins.", + "List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime_6168": "Liste der Stammordner, deren kombinierter Inhalt die Struktur des Projekts zur Laufzeit darstellt.", + "Loading_0_from_the_root_dir_1_candidate_location_2_6109": "\"{0}\" wird aus dem Stammverzeichnis \"{1}\" geladen. Speicherort des Kandidaten \"{2}\".", + "Loading_module_0_from_node_modules_folder_target_file_type_1_6098": "Modul \"{0}\" wird aus dem Ordner \"node_modules\" geladen, die Zieldatei ist vom Typ \"{1}\".", + "Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1_6095": "Modul wird als Datei/Ordner geladen, der Speicherort des Kandidatenmoduls ist \"{0}\", die Zieldatei ist vom Typ \"{1}\".", + "Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1_6048": "Für das Gebietsschema ist das Format oder - erforderlich, z. B. \"{0}\" oder \"{1}\".", + "Longest_matching_prefix_for_0_is_1_6108": "Das längste übereinstimmende Präfix für \"{0}\" ist \"{1}\".", + "Looking_up_in_node_modules_folder_initial_location_0_6125": "Die Suche erfolgt im Ordner \"node_modules\". Anfangsspeicherort \"{0}\".", + "Make_all_super_calls_the_first_statement_in_their_constructor_95036": "Alle \"super()\"-Aufrufe als erste Anweisung im entsprechenden Konstruktor festlegen", + "Make_super_call_the_first_statement_in_the_constructor_90002": "super()-Aufruf als erste Anweisung im Konstruktor festlegen", + "Mapped_object_type_implicitly_has_an_any_template_type_7039": "Der zugeordnete Objekttyp weist implizit einen any-Vorlagentyp auf.", + "Member_0_implicitly_has_an_1_type_7008": "Der Member \"{0}\" weist implizit den Typ \"{1}\" auf.", + "Merge_conflict_marker_encountered_1185": "Mergekonfliktmarkierung", + "Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_d_2652": "Die gemergte Deklaration \"{0}\" darf keine Exportstandarddeklaration enthalten. Fügen Sie ggf. eine separate Deklaration \"export default {0}\" hinzu.", + "Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constru_17013": "Die Metaeigenschaft \"{0}\" ist nur im Text einer Funktionsdeklaration, eines Funktionsausdrucks oder eines Konstruktors zulässig.", + "Method_0_cannot_have_an_implementation_because_it_is_marked_abstract_1245": "Die Methode \"{0}\" darf keine Implementierung besitzen, weil sie als abstrakt markiert ist.", + "Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4101": "Die Methode \"{0}\" der exportierten Schnittstelle besitzt oder verwendet den Namen \"{1}\" aus dem privaten Modul \"{2}\".", + "Method_0_of_exported_interface_has_or_is_using_private_name_1_4102": "Die Methode \"{0}\" der exportierten Schnittstelle besitzt oder verwendet den privaten Namen \"{1}\".", + "Modifiers_cannot_appear_here_1184": "Modifizierer dürfen hier nicht enthalten sein.", + "Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_1340": "Das Modul \"{0}\" verweist nicht auf einen Typ, wird hier aber als Typ verwendet.", + "Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here_1339": "Das Modul \"{0}\" verweist nicht auf einen Wert, wird hier aber als Wert verwendet.", + "Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambig_2308": "Das Modul \"{0}\" hat bereits einen Member mit dem Namen \"{1}\" exportiert. Erwägen Sie, ihn explizit erneut zu exportieren, um die Mehrdeutigkeit zu vermeiden.", + "Module_0_has_no_default_export_1192": "Das Modul \"{0}\" weist keinen Standardexport auf.", + "Module_0_has_no_exported_member_1_2305": "Das Modul \"{0}\" weist keinen exportierten Member \"{1}\" auf.", + "Module_0_has_no_exported_member_1_Did_you_mean_2_2724": "Das Modul \"{0}\" umfasst keinen exportierten Member \"{1}\". Meinten Sie \"{2}\"?", + "Module_0_is_hidden_by_a_local_declaration_with_the_same_name_2437": "Das Modul \"{0}\" wird durch eine lokale Deklaration mit dem gleichen Namen ausgeblendet.", + "Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct_2497": "Das Modul \"{0}\" wird in eine Nicht-Modulentität aufgelöst und darf nicht mithilfe dieses Konstrukts importiert werden.", + "Module_0_uses_export_and_cannot_be_used_with_export_Asterisk_2498": "Das Modul \"{0}\" verwendet \"export =\" und darf nicht mit \"export *\" verwendet werden.", + "Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified_6145": "Das Modul \"{0}\" wurde als in \"{1}\" deklariertes Umgebungsmodul aufgelöst, weil diese Datei nicht geändert wurde.", + "Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1_6144": "Das Modul \"{0}\" wurde als lokal deklariertes Umgebungsmodul in der Datei \"{1}\" aufgelöst.", + "Module_0_was_resolved_to_1_but_jsx_is_not_set_6142": "Das Modul \"{0}\" wurde zu \"{1}\" aufgelöst, aber \"--jsx\" wurde nicht festgelegt.", + "Module_Resolution_Options_6174": "Modulauflösungsoptionen", + "Module_name_0_matched_pattern_1_6092": "Modulname \"{0}\", übereinstimmendes Muster \"{1}\".", + "Module_name_0_was_not_resolved_6090": "======== Der Modulname \"{0}\" wurde nicht aufgelöst. ========", + "Module_name_0_was_successfully_resolved_to_1_6089": "======== Der Modulname \"{0}\" wurde erfolgreich in \"{1}\" aufgelöst. ========", + "Module_resolution_kind_is_not_specified_using_0_6088": "Die Art der Modulauflösung wird nicht angegeben. \"{0}\" wird verwendet.", + "Module_resolution_using_rootDirs_has_failed_6111": "Fehler bei der Modulauflösung mithilfe von \"rootDirs\".", + "Move_to_a_new_file_95049": "In neue Datei verschieben", + "Multiple_consecutive_numeric_separators_are_not_permitted_6189": "Mehrere aufeinander folgende numerische Trennzeichen sind nicht zulässig.", + "Multiple_constructor_implementations_are_not_allowed_2392": "Mehrere Konstruktorimplementierungen sind unzulässig.", + "NEWLINE_6061": "NEUE ZEILE", + "Named_property_0_of_types_1_and_2_are_not_identical_2319": "Die benannte Eigenschaft \"{0}\" der Typen \"{1}\" und \"{2}\" ist nicht identisch.", + "Namespace_0_has_no_exported_member_1_2694": "Der Namespace \"{0}\" besitzt keinen exportierten Member \"{1}\".", + "No_base_constructor_has_the_specified_number_of_type_arguments_2508": "Kein Basiskonstruktor weist die angegebene Anzahl von Typargumenten auf.", + "No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2_18003": "In der Konfigurationsdatei \"{0}\" wurden keine Eingaben gefunden. Als include-Pfade wurden \"{1}\", als exclude-Pfade wurden \"{2}\" angegeben.", + "Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2_2515": "Die nicht abstrakte Klasse \"{0}\" implementiert nicht den geerbten abstrakten Member \"{1}\" aus der Klasse \"{2}\".", + "Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1_2653": "Der nicht abstrakte Ausdruck implementiert nicht den geerbten abstrakten Member \"{0}\" aus der Klasse \"{1}\".", + "Not_all_code_paths_return_a_value_7030": "Nicht alle Codepfade geben einen Wert zurück.", + "Numeric_index_type_0_is_not_assignable_to_string_index_type_1_2413": "Der numerische Indextyp \"{0}\" kann dem Zeichenfolgen-Indextyp \"{1}\" nicht zugewiesen werden.", + "Numeric_separators_are_not_allowed_here_6188": "Numerische Trennzeichen sind hier nicht zulässig.", + "Object_is_of_type_unknown_2571": "Das Objekt ist vom Typ \"Unbekannt\".", + "Object_is_possibly_null_2531": "Das Objekt ist möglicherweise \"NULL\".", + "Object_is_possibly_null_or_undefined_2533": "Das Objekt ist möglicherweise \"NULL\" oder \"nicht definiert\".", + "Object_is_possibly_undefined_2532": "Das Objekt ist möglicherweise \"nicht definiert\".", + "Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1_2353": "Das Objektliteral kann nur bekannte Eigenschaften angeben, und \"{0}\" ist im Typ \"{1}\" nicht vorhanden.", + "Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_writ_2561": "Das Objektliteral gibt möglicherweise nur bekannte Eigenschaften an, \"{0}\" ist jedoch im Typ \"{1}\" nicht vorhanden. Wollten Sie \"{2}\" schreiben?", + "Object_literal_s_property_0_implicitly_has_an_1_type_7018": "Die Eigenschaft \"{0}\" des Objektliterals weist implizit den Typ \"{1}\" auf.", + "Octal_digit_expected_1178": "Es wurde eine Oktalzahl erwartet.", + "Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0_8017": "Oktalliteraltypen müssen die Syntax \"ES2015\" verwenden. Verwenden Sie die Syntax \"{0}\".", + "Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0_8018": "Oktalliterale sind in einem Mitgliederenumerationsinitialisierer nicht zulässig. Verwenden Sie die Syntax \"{0}\".", + "Octal_literals_are_not_allowed_in_strict_mode_1121": "Oktalliterale sind im Strict-Modus unzulässig.", + "Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0_1085": "Oktalliterale sind bei der Zielgruppenadressierung von ECMAScript 5 und höher nicht verfügbar. Verwenden Sie die Syntax \"{0}\".", + "Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement_1091": "In einer for...in-Anweisung ist nur eine einzige Variablendeklaration zulässig.", + "Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement_1188": "In einer for...of-Anweisung ist nur eine einzige Variablendeklaration zulässig.", + "Only_a_void_function_can_be_called_with_the_new_keyword_2350": "Nur eine void-Funktion kann mit dem Schlüsselwort \"new\" aufgerufen werden.", + "Only_ambient_modules_can_use_quoted_names_1035": "Nur Umgebungsmodule dürfen Namen in Anführungszeichen verwenden.", + "Only_amd_and_system_modules_are_supported_alongside_0_6082": "Nur die Module \"amd\" und \"system\" werden in Verbindung mit --{0} unterstützt.", + "Only_emit_d_ts_declaration_files_6014": "Geben Sie nur .d.ts-Deklarationsdateien aus.", + "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002": "Derzeit werden nur Bezeichner/qualifizierte Namen mit optionalen Typargumenten in den \"extends\"-Klauseln einer Klasse unterstützt.", + "Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword_2340": "Nur auf öffentliche und geschützte Methoden der Basisklasse kann über das Schlüsselwort \"super\" zugegriffen werden.", + "Operator_0_cannot_be_applied_to_types_1_and_2_2365": "Der Operator \"{0}\" darf nicht auf die Typen \"{1}\" und \"{2}\" angewendet werden.", + "Option_0_can_only_be_specified_in_tsconfig_json_file_6064": "Die Option \"{0}\" kann nur in der Datei \"tsconfig.json\" angegeben werden.", + "Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided_5051": "Die Option \"{0}\" kann nur verwendet werden, wenn die Option \"-inlineSourceMap\" oder \"-sourceMap\" angegeben wird.", + "Option_0_cannot_be_specified_with_option_1_5053": "Die Option \"{0}\" darf nicht zusammen mit der Option \"{1}\" angegeben werden.", + "Option_0_cannot_be_specified_without_specifying_option_1_5052": "Die Option \"{0}\" darf nicht ohne die Option \"{1}\" angegeben werden.", + "Option_0_cannot_be_specified_without_specifying_option_1_or_option_2_5069": "Die Option \"{0}\" kann nicht ohne die Option \"{1}\" oder \"{2}\" angegeben werden.", + "Option_0_should_have_array_of_strings_as_a_value_6103": "Die Option \"{0}\" muss ein Zeichenfolgenarray als Wert aufweisen.", + "Option_build_must_be_the_first_command_line_argument_6369": "Die Option \"--build\" muss das erste Befehlszeilenargument sein.", + "Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES_5047": "Die Option \"isolatedModules\" kann nur verwendet werden, wenn entweder die Option \"--module\" angegeben ist oder die Option \"target\" den Wert \"ES2015\" oder höher aufweist.", + "Option_paths_cannot_be_used_without_specifying_baseUrl_option_5060": "Die \"path\"-Option kann nicht ohne Angabe der \"-baseUrl\"-Option angegeben werden.", + "Option_project_cannot_be_mixed_with_source_files_on_a_command_line_5042": "Die Option \"project\" darf nicht mit Quelldateien in einer Befehlszeile kombiniert werden.", + "Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070": "Die Option \"--resolveJsonModule\" kann nicht ohne die Modulauflösungsstrategie \"node\" angegeben werden.", + "Options_0_and_1_cannot_be_combined_6370": "Die Optionen \"{0}\" und \"{1}\" können nicht kombiniert werden.", + "Options_Colon_6027": "Optionen:", + "Output_directory_for_generated_declaration_files_6166": "Ausgabeverzeichnis für erstellte Deklarationsdateien.", + "Output_file_0_from_project_1_does_not_exist_6309": "Die Ausgabedatei \"{0}\" aus dem Projekt \"{1}\" ist nicht vorhanden.", + "Output_file_0_has_not_been_built_from_source_file_1_6305": "Die Ausgabedatei \"{0}\" wurde nicht aus der Quelldatei \"{1}\" erstellt.", + "Overload_signature_is_not_compatible_with_function_implementation_2394": "Die Überladungssignatur ist nicht mit der Funktionsimplementierung kompatibel.", + "Overload_signatures_must_all_be_abstract_or_non_abstract_2512": "Überladungssignaturen müssen alle abstrakt oder nicht abstrakt sein.", + "Overload_signatures_must_all_be_ambient_or_non_ambient_2384": "Überladungssignaturen müssen alle umgebend oder nicht umgebend sein.", + "Overload_signatures_must_all_be_exported_or_non_exported_2383": "Überladungssignaturen müssen alle exportiert oder nicht exportiert sein.", + "Overload_signatures_must_all_be_optional_or_required_2386": "Überladungssignaturen müssen alle optional oder erforderlich sein.", + "Overload_signatures_must_all_be_public_private_or_protected_2385": "Überladungssignaturen müssen alle öffentlich, privat oder geschützt sein.", + "Parameter_0_cannot_be_referenced_in_its_initializer_2372": "Auf den Parameter \"{0}\" darf in diesem Initialisierer nicht verwiesen werden.", + "Parameter_0_implicitly_has_an_1_type_7006": "Der Parameter \"{0}\" weist implizit einen Typ \"{1}\" auf.", + "Parameter_0_is_not_in_the_same_position_as_parameter_1_1227": "Der Parameter \"{0}\" befindet sich nicht an der gleichen Position wie der Parameter \"{1}\".", + "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4066": "Der Parameter \"{0}\" der Aufrufsignatur aus der exportierten Schnittstelle besitzt oder verwendet den Namen \"{1}\" aus dem privaten Modul \"{2}\".", + "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4067": "Der Parameter \"{0}\" der Aufrufsignatur aus der exportierten Schnittstelle besitzt oder verwendet den privaten Namen \"{1}\".", + "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_can_4061": "Der Parameter \"{0}\" des Konstruktors aus der exportierten Klasse besitzt oder verwendet den Namen \"{1}\" aus dem externen Modul \"{2}\", kann aber nicht benannt werden.", + "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2_4062": "Der Parameter \"{0}\" des Konstruktors aus der exportierten Klasse besitzt oder verwendet den Namen \"{1}\" aus dem privaten Modul \"{2}\".", + "Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1_4063": "Der Parameter \"{0}\" des Konstruktors aus der exportierten Klasse besitzt oder verwendet den privaten Namen \"{1}\".", + "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_mod_4064": "Der Parameter \"{0}\" der Konstruktorsignatur aus der exportierten Schnittstelle besitzt oder verwendet den Namen \"{1}\" aus dem privaten Modul \"{2}\".", + "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4065": "Der Parameter \"{0}\" der Konstruktorsignatur aus der exportierten Schnittstelle besitzt oder verwendet den privaten Namen \"{1}\".", + "Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4076": "Der Parameter \"{0}\" der exportierten Funktion besitzt oder verwendet den Namen \"{1}\" aus dem externen Modul \"{2}\", kann aber nicht benannt werden.", + "Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2_4077": "Der Parameter \"{0}\" der exportierten Funktion besitzt oder verwendet den Namen \"{1}\" aus dem privaten Modul \"{2}\".", + "Parameter_0_of_exported_function_has_or_is_using_private_name_1_4078": "Der Parameter \"{0}\" der exportierten Funktion besitzt oder verwendet den privaten Namen \"{1}\".", + "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4091": "Der Parameter \"{0}\" der Indexsignatur aus der exportierten Schnittstelle weist den Namen \"{1}\" aus dem privaten Modul \"{2}\" auf oder verwendet diesen.", + "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1_4092": "Der Parameter \"{0}\" der Indexsignatur aus der exportierten Schnittstelle weist den privaten Namen \"{1}\" auf oder verwendet diesen.", + "Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4074": "Der Parameter \"{0}\" der Methode aus der exportierten Schnittstelle besitzt oder verwendet den Namen \"{1}\" aus dem privaten Modul \"{2}\".", + "Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4075": "Der Parameter \"{0}\" der Methode aus der exportierten Schnittstelle besitzt oder verwendet den privaten Namen \"{1}\".", + "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_c_4071": "Der Parameter \"{0}\" der öffentlichen Methode aus der exportierten Klasse besitzt oder verwendet den Namen \"{1}\" aus dem externen Modul \"{2}\", kann aber nicht benannt werden.", + "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4072": "Der Parameter \"{0}\" der öffentlichen Methode aus der exportierten Klasse besitzt oder verwendet den Namen \"{1}\" aus dem privaten Modul \"{2}\".", + "Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4073": "Der Parameter \"{0}\" der öffentlichen Methode aus der exportierten Klasse besitzt oder verwendet den privaten Namen \"{1}\".", + "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module__4068": "Der Parameter \"{0}\" der öffentlichen statischen Methode aus der exportierten Klasse besitzt oder verwendet den Namen \"{1}\" aus dem externen Modul \"{2}\", kann aber nicht benannt werden.", + "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4069": "Der Parameter \"{0}\" der öffentlichen statischen Methode aus der exportierten Klasse besitzt oder verwendet den Namen \"{1}\" aus dem privaten Modul \"{2}\".", + "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4070": "Der Parameter \"{0}\" der öffentlichen statischen Methode aus der exportierten Klasse besitzt oder verwendet den privaten Namen \"{1}\".", + "Parameter_cannot_have_question_mark_and_initializer_1015": "Der Parameter darf kein Fragezeichen und keinen Initialisierer aufweisen.", + "Parameter_declaration_expected_1138": "Eine Parameterdeklaration wurde erwartet.", + "Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2_4036": "Der Parametertyp des öffentlichen Setters \"{0}\" aus der exportierten Klasse besitzt oder verwendet den Namen \"{1}\" aus dem privaten Modul \"{2}\".", + "Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_private_name_1_4037": "Der Parametertyp des öffentlichen Setters \"{0}\" aus der exportierten Klasse besitzt oder verwendet den privaten Namen \"{1}\".", + "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_name_1_from_private_mod_4034": "Der Parametertyp des öffentlichen statischen Setters \"{0}\" aus der exportierten Klasse besitzt oder verwendet den Namen \"{1}\" aus dem privaten Modul \"{2}\".", + "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1_4035": "Der Parametertyp des öffentlichen statischen Setters \"{0}\" aus der exportierten Klasse besitzt oder verwendet den privaten Namen \"{1}\".", + "Parse_in_strict_mode_and_emit_use_strict_for_each_source_file_6141": "Im Strict-Modus analysieren und \"use strict\" für jede Quelldatei ausgeben.", + "Pattern_0_can_have_at_most_one_Asterisk_character_5061": "Das Muster \"{0}\" darf höchstens ein Zeichen \"*\" aufweisen.", + "Prefix_0_with_an_underscore_90025": "\"{0}\" einen Unterstrich voranstellen", + "Prefix_all_unused_declarations_with_where_possible_95025": "Alle nicht verwendeten Deklarationen nach Möglichkeit mit dem Präfix \"_\" versehen", + "Print_names_of_files_part_of_the_compilation_6155": "Drucknamen des Dateiteils der Kompilierung.", + "Print_names_of_generated_files_part_of_the_compilation_6154": "Drucknamen des generierten Dateiteils der Kompilierung.", + "Print_the_compiler_s_version_6019": "Die Version des Compilers ausgeben.", + "Print_this_message_6017": "Diese Nachricht ausgeben.", + "Project_0_can_t_be_built_because_its_dependency_1_has_errors_6363": "Projekt \"{0}\" kann nicht erstellt werden, weil die Abhängigkeit \"{1}\" Fehler enthält.", + "Project_0_is_out_of_date_because_its_dependency_1_is_out_of_date_6353": "Projekt \"{0}\" ist veraltet, weil die Abhängigkeit \"{1}\" veraltet ist.", + "Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2_6350": "Projekt \"{0}\" ist veraltet, weil die älteste Ausgabe \"{1}\" älter ist als die neueste Eingabe \"{2}\".", + "Project_0_is_out_of_date_because_output_file_1_does_not_exist_6352": "Projekt \"{0}\" ist veraltet, weil die Ausgabedatei \"{1}\" nicht vorhanden ist.", + "Project_0_is_up_to_date_6361": "Projekt \"{0}\" ist auf dem neuesten Stand.", + "Project_0_is_up_to_date_because_newest_input_1_is_older_than_oldest_output_2_6351": "Projekt \"{0}\" ist auf dem neuesten Stand, weil die neueste Eingabe \"{1}\" älter ist als die älteste Ausgabe \"{2}\".", + "Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies_6354": "Projekt \"{0}\" ist mit .d.ts-Dateien aus den zugehörigen Abhängigkeiten auf dem neuesten Stand.", + "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202": "Projektverweise dürfen keinen kreisförmigen Graphen bilden. Zyklus erkannt: {0}", + "Projects_in_this_build_Colon_0_6355": "Projekte in diesem Build: {0}", + "Projects_to_reference_6300": "Zu referenzierende Projekte", + "Property_0_does_not_exist_on_const_enum_1_2479": "Die Eigenschaft \"{0}\" ist für die const-Enumeration \"{1}\" nicht vorhanden.", + "Property_0_does_not_exist_on_type_1_2339": "Die Eigenschaft \"{0}\" ist für den Typ \"{1}\" nicht vorhanden.", + "Property_0_does_not_exist_on_type_1_Did_you_forget_to_use_await_2570": "Die Eigenschaft \"{0}\" ist im Typ \"{1}\" nicht vorhanden. Haben Sie \"await\" nicht verwendet?", + "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551": "Die Eigenschaft \"{0}\" existiert nicht für Typ \"{1}\". Meinten Sie \"{2}\"?", + "Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1_2546": "Eigenschaft \"{0}\" weist widersprüchliche Deklarationen auf und ein Zugriff in Typ \"{1}\" ist nicht möglich.", + "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor_2564": "Die Eigenschaft \"{0}\" weist keinen Initialisierer auf und ist im Konstruktor nicht definitiv zugewiesen.", + "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033": "Die Eigenschaft \"{0}\" weist implizit den Typ \"any\" auf, weil ihrem get-Accessor eine Parametertypanmerkung fehlt.", + "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032": "Die Eigenschaft \"{0}\" weist implizit den Typ \"any\" auf, weil ihrem set-Accessor eine Parametertypanmerkung fehlt.", + "Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2_2416": "Die Eigenschaft \"{0}\" im Typ \"{1}\" kann nicht der gleichen Eigenschaft in Basistyp \"{2}\" zugewiesen werden.", + "Property_0_in_type_1_is_not_assignable_to_type_2_2603": "Die Eigenschaft \"{0}\" im Typ \"{1}\" kann dem Typ \"{2}\" nicht zugewiesen werden.", + "Property_0_is_declared_but_its_value_is_never_read_6138": "Die Eigenschaft \"{0}\" ist deklariert, aber ihr Wert wird nie gelesen.", + "Property_0_is_incompatible_with_index_signature_2530": "Die Eigenschaft \"{0}\" ist nicht mit der Indexsignatur kompatibel.", + "Property_0_is_missing_in_type_1_2324": "Die Eigenschaft \"{0}\" fehlt im Typ \"{1}\".", + "Property_0_is_optional_in_type_1_but_required_in_type_2_2327": "Die Eigenschaft \"{0}\" ist im Typ \"{1}\" optional, im Typ \"{2}\" aber erforderlich.", + "Property_0_is_private_and_only_accessible_within_class_1_2341": "Die Eigenschaft \"{0}\" ist privat. Auf sie kann nur innerhalb der Klasse \"{1}\" zugegriffen werden.", + "Property_0_is_private_in_type_1_but_not_in_type_2_2325": "Die Eigenschaft \"{0}\" ist im Typ \"{1}\" privat, im Typ \"{2}\" hingegen nicht.", + "Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1_2446": "Die Eigenschaft \"{0}\" ist geschützt. Auf sie kann nur über eine Instanz der Klasse \"{1}\" zugegriffen werden.", + "Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses_2445": "Die Eigenschaft \"{0}\" ist geschützt. Auf sie kann nur innerhalb der Klasse \"{1}\" und ihrer Unterklassen zugegriffen werden.", + "Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2_2443": "Die Eigenschaft \"{0}\" ist geschützt, Typ \"{1}\" ist aber keine von \"{2}\" abgeleitete Klasse.", + "Property_0_is_protected_in_type_1_but_public_in_type_2_2444": "Die Eigenschaft \"{0}\" ist im Typ \"{1}\" geschützt, im Typ \"{2}\" aber öffentlich.", + "Property_0_is_used_before_being_assigned_2565": "Die Eigenschaft \"{0}\" wird vor ihrer Zuweisung verwendet.", + "Property_0_of_JSX_spread_attribute_is_not_assignable_to_target_property_2606": "Die Eigenschaft \"{0}\" des JSX-Verteilungsattributs kann nicht der Zieleigenschaft zugewiesen werden.", + "Property_0_of_exported_class_expression_may_not_be_private_or_protected_4094": "Die Eigenschaft \"{0}\" des exportierten Klassenausdrucks ist unter Umständen nicht privat oder geschützt.", + "Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4032": "Die Eigenschaft \"{0}\" der exportierten Schnittstelle besitzt oder verwendet den Namen \"{1}\" aus dem privaten Modul \"{2}\".", + "Property_0_of_exported_interface_has_or_is_using_private_name_1_4033": "Die Eigenschaft \"{0}\" der exportierten Schnittstelle besitzt oder verwendet den privaten Namen \"{1}\".", + "Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2_2412": "Die Eigenschaft \"{0}\" vom Typ \"{1}\" kann dem numerischen Indextyp \"{2}\" nicht zugewiesen werden.", + "Property_0_of_type_1_is_not_assignable_to_string_index_type_2_2411": "Die Eigenschaft \"{0}\" vom Typ \"{1}\" kann dem Zeichenfolgen-Indextyp \"{2}\" nicht zugewiesen werden.", + "Property_assignment_expected_1136": "Die Zuweisung einer Eigenschaft wurde erwartet.", + "Property_destructuring_pattern_expected_1180": "Ein Eigenschaftendestrukturierungsmuster wurde erwartet.", + "Property_or_signature_expected_1131": "Eine Eigenschaft oder Signatur wurde erwartet.", + "Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_li_1328": "Der Eigenschaftswert kann nur ein Zeichenfolgenliteral, ein numerisches Literal, \"true\", \"false\", \"NULL\", ein Objektliteral oder ein Arrayliteral sein.", + "Provide_full_support_for_iterables_in_for_of_spread_and_destructuring_when_targeting_ES5_or_ES3_6179": "Bieten Sie vollständige Unterstützung für Iterablen in \"for-of\", Verteilung und Destrukturierung mit dem Ziel \"ES5\" oder \"ES3\".", + "Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4098": "Die öffentliche Methode \"{0}\" der exportierten Klasse besitzt oder verwendet den Namen \"{1}\" aus dem externen Modul \"{2}\", kann aber nicht benannt werden.", + "Public_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4099": "Die öffentliche Methode \"{0}\" der exportierten Klasse besitzt oder verwendet den Namen \"{1}\" aus dem privaten Modul \"{2}\".", + "Public_method_0_of_exported_class_has_or_is_using_private_name_1_4100": "Die öffentliche Methode \"{0}\" der exportierten Klasse besitzt oder verwendet den privaten Namen \"{1}\".", + "Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_name_4029": "Die öffentliche Eigenschaft \"{0}\" der exportierten Klasse besitzt oder verwendet den Namen \"{1}\" aus dem externen Modul \"{2}\", kann aber nicht benannt werden.", + "Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4030": "Die öffentliche Eigenschaft \"{0}\" der exportierten Klasse besitzt oder verwendet den Namen \"{1}\" aus dem privaten Modul \"{2}\".", + "Public_property_0_of_exported_class_has_or_is_using_private_name_1_4031": "Die öffentliche Eigenschaft \"{0}\" der exportierten Klasse besitzt oder verwendet den privaten Namen \"{1}\".", + "Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_4095": "Die öffentliche statische Methode \"{0}\" der exportierten Klasse besitzt oder verwendet den Namen \"{1}\" aus dem externen Modul \"{2}\", kann aber nicht benannt werden.", + "Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4096": "Die öffentliche statische Methode \"{0}\" der exportierten Klasse besitzt oder verwendet den Namen \"{1}\" aus dem privaten Modul \"{2}\".", + "Public_static_method_0_of_exported_class_has_or_is_using_private_name_1_4097": "Die öffentliche statische Methode \"{0}\" der exportierten Klasse besitzt oder verwendet den privaten Namen \"{1}\".", + "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot__4026": "Die öffentliche statische Eigenschaft \"{0}\" der exportierten Klasse besitzt oder verwendet den Namen \"{1}\" aus dem externen Modul \"{2}\", kann aber nicht benannt werden.", + "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4027": "Die öffentliche statische Eigenschaft \"{0}\" der exportierten Klasse besitzt oder verwendet den Namen \"{1}\" aus dem privaten Modul \"{2}\".", + "Public_static_property_0_of_exported_class_has_or_is_using_private_name_1_4028": "Die öffentliche statische Eigenschaft \"{0}\" der exportierten Klasse besitzt oder verwendet den privaten Namen \"{1}\".", + "Raise_error_on_expressions_and_declarations_with_an_implied_any_type_6052": "Fehler für Ausdrücke und Deklarationen mit einem impliziten any-Typ auslösen.", + "Raise_error_on_this_expressions_with_an_implied_any_type_6115": "Fehler für \"this\"-Ausdrücke mit einem impliziten any-Typ auslösen.", + "Redirect_output_structure_to_the_directory_6006": "Die Ausgabestruktur in das Verzeichnis umleiten.", + "Referenced_project_0_must_have_setting_composite_Colon_true_6306": "Das referenzierte Projekt \"{0}\" muss für die Einstellung \"composite\" den Wert TRUE aufweisen.", + "Remove_all_unreachable_code_95051": "Gesamten nicht erreichbaren Code entfernen", + "Remove_all_unused_labels_95054": "Alle nicht verwendeten Bezeichnungen entfernen", + "Remove_braces_from_arrow_function_95060": "Geschweifte Klammern aus Pfeilfunktion entfernen", + "Remove_declaration_for_Colon_0_90004": "Deklaration entfernen für: {0}", + "Remove_destructuring_90009": "Destrukturierung entfernen", + "Remove_import_from_0_90005": "Import aus \"{0}\" entfernen", + "Remove_unreachable_code_95050": "Nicht erreichbaren Code entfernen", + "Remove_unused_label_95053": "Nicht verwendete Bezeichnung entfernen", + "Remove_variable_statement_90010": "Variablenanweisung entfernen", + "Replace_import_with_0_95015": "Ersetzen Sie den Import durch \"{0}\".", + "Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "Fehler melden, wenn nicht alle Codepfade in der Funktion einen Wert zurückgeben.", + "Report_errors_for_fallthrough_cases_in_switch_statement_6076": "Für FallTrough-Fälle in switch-Anweisung Fehler melden.", + "Report_errors_in_js_files_8019": "Fehler in .js-Dateien melden.", + "Report_errors_on_unused_locals_6134": "Fehler für nicht verwendete lokale Variablen melden.", + "Report_errors_on_unused_parameters_6135": "Fehler für nicht verwendete Parameter melden.", + "Required_type_parameters_may_not_follow_optional_type_parameters_2706": "Erforderliche Typparameter dürfen nicht auf optionale Typparameter folgen.", + "Resolution_for_module_0_was_found_in_cache_from_location_1_6147": "Die Auflösung für das Modul \"{0}\" wurde im Cache des Standorts \"{1}\" gefunden.", + "Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols_6195": "\"keyof\" darf nur in Eigenschaftennamen mit Zeichenfolgenwert aufgelöst werden (keine Ziffern oder Symbole).", + "Resolving_from_node_modules_folder_6118": "Auflösen aus dem Ordner \"node_modules\"...", + "Resolving_module_0_from_1_6086": "======== Das Modul \"{0}\" aus \"{1}\" wird aufgelöst. ========", + "Resolving_module_name_0_relative_to_base_url_1_2_6094": "Der Modulname \"{0}\" relativ zur Basis-URL \"{1}\"–\"{2}\" wird aufgelöst.", + "Resolving_real_path_for_0_result_1_6130": "Der tatsächliche Pfad für \"{0}\" wird aufgelöst, Ergebnis \"{1}\".", + "Resolving_type_reference_directive_0_containing_file_1_root_directory_2_6116": "======== Die Typverweisdirektive \"{0}\" wird aufgelöst, die die Datei \"{1}\" enthält. Das Stammverzeichnis ist \"{2}\". ========", + "Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set_6123": "======== Die Typverweisdirektive \"{0}\" wird aufgelöst, die die Datei \"{1}\" enthält. Das Stammverzeichnis ist nicht festgelegt. ========", + "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1_6127": "======== Die Typverweisdirektive \"{0}\" wird aufgelöst, die die nicht festgelegte Datei enthält. Das Stammverzeichnis ist \"{1}\". ========", + "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set_6128": "======== Die Typverweisdirektive \"{0}\" wird aufgelöst, die die nicht festgelegte Datei enthält. Das Stammverzeichnis ist nicht festgelegt. ========", + "Resolving_using_primary_search_paths_6117": "Auflösung mithilfe primärer Suchpfade...", + "Resolving_with_primary_search_path_0_6121": "Die Auflösung erfolgt mit dem primären Suchpfad \"{0}\".", + "Rest_parameter_0_implicitly_has_an_any_type_7019": "Der rest-parameter \"{0}\" weist implizit einen Typ \"any[]\" auf.", + "Rest_types_may_only_be_created_from_object_types_2700": "Rest-Typen dürfen nur aus object-Typen erstellt werden.", + "Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4046": "Der Rückgabetyp der Aufrufsignatur aus der exportierten Schnittstelle besitzt oder verwendet den Namen \"{0}\" aus dem privaten Modul \"{1}\".", + "Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0_4047": "Der Rückgabetyp der Aufrufsignatur aus der exportierten Schnittstelle besitzt oder verwendet den privaten Namen \"{0}\".", + "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_mod_4044": "Der Rückgabetyp der Konstruktorsignatur aus der exportierten Schnittstelle besitzt oder verwendet den Namen \"{0}\" aus dem privaten Modul \"{1}\".", + "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0_4045": "Der Rückgabetyp der Konstruktorsignatur aus der exportierten Schnittstelle besitzt oder verwendet den privaten Namen \"{0}\".", + "Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class_2409": "Der Rückgabetyp der Konstruktorsignatur muss dem Instanztyp der Klasse zugewiesen werden können.", + "Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named_4058": "Der Rückgabetyp der exportierten Funktion besitzt oder verwendet den Namen \"{0}\" aus dem externen Modul \"{1}\", kann aber nicht benannt werden.", + "Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1_4059": "Der Rückgabetyp der exportierten Funktion besitzt oder verwendet den Namen \"{0}\" aus dem privaten Modul \"{1}\".", + "Return_type_of_exported_function_has_or_is_using_private_name_0_4060": "Der Rückgabetyp der exportierten Funktion besitzt oder verwendet den privaten Namen \"{0}\".", + "Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4048": "Der Rückgabetyp der Indexsignatur aus der exportierten Schnittstelle besitzt oder verwendet den Namen \"{0}\" aus dem privaten Modul \"{1}\".", + "Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0_4049": "Der Rückgabetyp der Indexsignatur aus der exportierten Schnittstelle besitzt oder verwendet den privaten Namen \"{0}\".", + "Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4056": "Der Rückgabetyp der Methode aus der exportierten Schnittstelle besitzt oder verwendet den Namen \"{0}\" aus dem privaten Modul \"{1}\".", + "Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0_4057": "Der Rückgabetyp der Methode aus der exportierten Schnittstelle besitzt oder verwendet den privaten Namen \"{0}\".", + "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_4041": "Der Rückgabetyp des öffentlichen Getters \"{0}\" aus der exportierten Klasse besitzt oder verwendet den Namen \"{1}\" aus dem externen Modul \"{2}\", kann aber nicht benannt werden.", + "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2_4042": "Der Rückgabetyp des öffentlichen Getters \"{0}\" aus der exportierten Klasse besitzt oder verwendet den Namen \"{1}\" aus dem privaten Modul \"{2}\".", + "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_private_name_1_4043": "Der Rückgabetyp des öffentlichen Getters \"{0}\" aus der exportierten Klasse besitzt oder verwendet den privaten Namen \"{1}\".", + "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_c_4053": "Der Rückgabetyp der öffentlichen Methode aus der exportierten Klasse besitzt oder verwendet den Namen \"{0}\" aus dem externen Modul \"{1}\", kann aber nicht benannt werden.", + "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4054": "Der Rückgabetyp der öffentlichen Methode aus der exportierten Klasse besitzt oder verwendet den Namen \"{0}\" aus dem privaten Modul \"{1}\".", + "Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0_4055": "Der Rückgabetyp der öffentlichen Methode aus der exportierten Klasse besitzt oder verwendet den privaten Namen \"{0}\".", + "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_external_modul_4038": "Der Rückgabetyp des öffentlichen statischen Getters \"{0}\" aus der exportierten Klasse besitzt oder verwendet den Namen \"{1}\" aus dem externen Modul \"{2}\", kann aber nicht benannt werden.", + "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_4039": "Der Rückgabetyp des öffentlichen statischen Getters \"{0}\" aus der exportierten Klasse besitzt oder verwendet den Namen \"{1}\" aus dem privaten Modul \"{2}\".", + "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_private_name_1_4040": "Der Rückgabetyp des öffentlichen statischen Getters \"{0}\" aus der exportierten Klasse besitzt oder verwendet den privaten Namen \"{1}\".", + "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module__4050": "Der Rückgabetyp der öffentlichen statischen Methode aus der exportierten Klasse besitzt oder verwendet den Namen \"{0}\" aus dem externen Modul \"{1}\", kann aber nicht benannt werden.", + "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4051": "Der Rückgabetyp der öffentlichen statischen Methode aus der exportierten Klasse besitzt oder verwendet den Namen \"{0}\" aus dem privaten Modul \"{1}\".", + "Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0_4052": "Der Rückgabetyp der öffentlichen statischen Methode aus der exportierten Klasse besitzt oder verwendet den privaten Namen \"{0}\".", + "Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program_6184": "Modulauflösungen aus \"{0}\" werden wiederverwendet, da Auflösungen aus dem alten Programm nicht geändert wurden.", + "Reusing_resolution_of_module_0_to_file_1_from_old_program_6183": "Die Auflösung des Moduls \"{0}\" in die Datei \"{1}\" aus dem alten Programm wird wiederverwendet.", + "Rewrite_all_as_indexed_access_types_95034": "Alle als indizierte Zugriffstypen neu schreiben", + "Rewrite_as_the_indexed_access_type_0_90026": "Als indizierten Zugriffstyp \"{0}\" neu schreiben", + "Root_directory_cannot_be_determined_skipping_primary_search_paths_6122": "Das Stammverzeichnis kann nicht ermittelt werden. Die primären Suchpfade werden übersprungen.", + "STRATEGY_6039": "STRATEGIE", + "Scoped_package_detected_looking_in_0_6182": "Bereichsbezogenes Paket erkannt. In \"{0}\" wird gesucht", + "Setters_cannot_return_a_value_2408": "Setter können keinen Wert zurückgeben.", + "Show_all_compiler_options_6169": "Alle Compileroptionen anzeigen.", + "Show_diagnostic_information_6149": "Diagnoseinformationen anzeigen.", + "Show_verbose_diagnostic_information_6150": "Ausführliche Diagnoseinformationen anzeigen.", + "Show_what_would_be_built_or_deleted_if_specified_with_clean_6367": "Anzeigen, was erstellt würde (oder gelöscht würde, wenn mit \"--clean\" angegeben)", + "Signature_0_must_be_a_type_predicate_1224": "Die Signatur \"{0}\" muss ein Typprädikat sein.", + "Skip_type_checking_of_declaration_files_6012": "Überspringen Sie die Typüberprüfung von Deklarationsdateien.", + "Skipping_build_of_project_0_because_its_dependency_1_has_errors_6362": "Das Erstellen von Projekt \"{0}\" wird übersprungen, weil die Abhängigkeit \"{1}\" einen Fehler aufweist.", + "Skipping_clean_because_not_all_projects_could_be_located_6371": "Das Bereinigen wird übersprungen, weil nicht alle Projekte gefunden werden konnten.", + "Source_Map_Options_6175": "Quellzuordnungsoptionen", + "Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature_2382": "Eine spezialisierte Überladungssignatur kann keiner nicht spezialisierten Signatur zugewiesen werden.", + "Specifier_of_dynamic_import_cannot_be_spread_element_1325": "Der Spezifizierer des dynamischen Imports darf kein Spread-Element sein.", + "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_or_ESNEXT_6015": "ECMAScript-Zielversion angeben: ES3 (Standard), ES5, ES2015, ES2016, ES2017, ES2018 oder ESNEXT.", + "Specify_JSX_code_generation_Colon_preserve_react_native_or_react_6080": "JSX-Codegenerierung angeben: \"preserve\", \"react-native\" oder \"react\".", + "Specify_library_files_to_be_included_in_the_compilation_6079": "Geben Sie Bibliotheksdateien an, die in die Kompilierung eingeschlossen werden sollen.", + "Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext_6016": "Geben Sie die Codegenerierung für das Modul an: \"none\", \"commonjs\", \"amd\", \"system\", \"umd\", \"es2015\" oder \"ESNext\".", + "Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6_6069": "Geben Sie die Modulauflösungsstrategie an: \"node\" (Node.js) oder \"classic\" (TypeScript vor Version 1.6).", + "Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h_6146": "Geben Sie die JSX-Factoryfunktion an, die für eine react-JSX-Ausgabe verwendet werden soll, z. B. \"React.createElement\" oder \"h\".", + "Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix_6060": "Geben Sie die Zeilenendesequenz an, die beim Ausgeben von Dateien verwendet werden soll: \"CRLF\" (DOS) oder \"LF\" (Unix).", + "Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations_6004": "Geben Sie den Speicherort an, an dem der Debugger TypeScript-Dateien ermitteln soll, anstatt Quellspeicherorte zu verwenden.", + "Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations_6003": "Geben Sie den Speicherort an, an dem der Debugger Zuordnungsdateien ermitteln soll, anstatt generierte Speicherorte zu verwenden.", + "Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir_6058": "Geben Sie das Stammverzeichnis der Eingabedateien an. Verwenden Sie diese Angabe, um die Ausgabeverzeichnisstruktur mithilfe von \"-outDir\" zu steuern.", + "Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher_2472": "Der Verteilungsoperator in new-Ausdrücken ist nur verfügbar, wenn das Ziel ECMAScript 5 oder höher ist.", + "Spread_types_may_only_be_created_from_object_types_2698": "Spread-Typen dürfen nur aus object-Typen erstellt werden.", + "Starting_compilation_in_watch_mode_6031": "Kompilierung im Überwachungsmodus wird gestartet...", + "Statement_expected_1129": "Eine Anweisung wurde erwartet.", + "Statements_are_not_allowed_in_ambient_contexts_1036": "Anweisungen sind in Umgebungskontexten unzulässig.", + "Static_members_cannot_reference_class_type_parameters_2302": "Statische Member dürfen nicht auf Klassentypparameter verweisen.", + "Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1_2699": "Die statische Eigenschaft \"{0}\" steht in Konflikt mit der integrierten Eigenschaft \"Function.{0}\" der Konstruktorfunktion \"{1}\".", + "Strict_Type_Checking_Options_6173": "Strenge Typüberprüfungsoptionen", + "String_literal_expected_1141": "Ein Zeichenfolgenliteral wurde erwartet.", + "String_literal_with_double_quotes_expected_1327": "Ein Zeichenfolgenliteral mit doppelten Anführungszeichen wird erwartet.", + "Stylize_errors_and_messages_using_color_and_context_experimental_6073": "Fehler und Nachrichten farbig und mit Kontext formatieren (experimentell).", + "Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_t_2717": "Nachfolgende Eigenschaftendeklarationen müssen den gleichen Typ aufweisen. Die Eigenschaft \"{0}\" muss den Typ \"{1}\" aufweisen, ist hier aber vom Typ \"{2}\".", + "Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_t_2403": "Nachfolgende Variablendeklarationen müssen den gleichen Typ aufweisen. Die Variable \"{0}\" muss den Typ \"{1}\" aufweisen, ist hier aber vom Typ \"{2}\".", + "Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2_5064": "Die Ersetzung \"{0}\" für das Muster \"{1}\" weist einen falschen Typ auf. Erwartet wurde \"string\", abgerufen wurde \"{2}\".", + "Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character_5062": "Die Ersetzung \"{0}\" im Muster \"{1}\" darf höchstens ein Zeichen \"*\" aufweisen.", + "Substitutions_for_pattern_0_should_be_an_array_5063": "Die Ersetzung für das Muster \"{0}\" muss ein Array sein.", + "Substitutions_for_pattern_0_shouldn_t_be_an_empty_array_5066": "Ersetzungen für das Muster \"{0}\" dürfen kein leeres Array sein.", + "Successfully_created_a_tsconfig_json_file_6071": "Eine Datei \"tsconfig.json\" wurde erfolgreich erstellt.", + "Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors_2337": "Aufrufe von \"super\" sind außerhalb von Konstruktoren oder in geschachtelten Funktionen innerhalb von Konstruktoren unzulässig.", + "Suppress_excess_property_checks_for_object_literals_6072": "Übermäßige Eigenschaftenüberprüfungen für Objektliterale unterdrücken.", + "Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures_6055": "noImplicitAny-Fehler für die Indizierung von Objekten unterdrücken, denen Indexsignaturen fehlen.", + "Symbol_reference_does_not_refer_to_the_global_Symbol_constructor_object_2470": "Der Symbol-Verweis verweist nicht auf das globale Symbolkonstruktorobjekt.", + "Syntax_Colon_0_6023": "Syntax: {0}", + "The_0_operator_cannot_be_applied_to_type_symbol_2469": "Der Operator \"{0}\" darf nicht den Typ \"symbol\" angewendet werden.", + "The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead_2447": "Der Operator \"{0}\" ist für boolesche Typen unzulässig. Verwenden Sie stattdessen ggf. \"{1}\".", + "The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead_2696": "Der Typ \"Object\" kann nur wenigen anderen Typen zugewiesen werden. Wollten Sie stattdessen den Typ \"any\" verwenden?", + "The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_stand_2496": "Auf das Objekt \"arguments\" darf in einer Pfeilfunktion in ES3 und ES5 nicht verwiesen werden. Verwenden Sie ggf. einen Standardfunktionsausdruck.", + "The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_usi_2522": "Auf das Objekt \"arguments\" darf in einer asynchronen Funktion oder Methode in ES3 und ES5 nicht verwiesen werden. Verwenden Sie ggf. eine Standardfunktion oder -methode.", + "The_body_of_an_if_statement_cannot_be_the_empty_statement_1313": "Der Text einer \"if\"-Anweisung kann keine leere Anweisung sein.", + "The_character_set_of_the_input_files_6163": "Der Zeichensatz der Eingabedateien.", + "The_containing_function_or_module_body_is_too_large_for_control_flow_analysis_2563": "Der beinhaltende Funktions- oder Modulkörper ist zu groß für eine Ablaufsteuerungsanalyse.", + "The_current_host_does_not_support_the_0_option_5001": "Der aktuelle Host unterstützt die Option \"{0}\" nicht.", + "The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context_2714": "Der Ausdruck einer Exportzuweisung muss ein Bezeichner oder ein qualifizierter Name in einem Umgebungskontext sein.", + "The_files_list_in_config_file_0_is_empty_18002": "Die Liste \"files\" in der Konfigurationsdatei \"{0}\" ist leer.", + "The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback_1060": "Der erste Parameter der \"then\"-Methode einer Zusage muss ein Rückruf sein.", + "The_global_type_JSX_0_may_not_have_more_than_one_property_2608": "Der globale Typ \"JSX.{0}\" darf nur eine Eigenschaft aufweisen.", + "The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_option_1343": "Die Metaeigenschaft \"import.meta\" ist nur bei Verwendung von \"ESNext\" für die Compileroptionen \"target\" und \"module\" zulässig.", + "The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary_2527": "Der abgeleitete Typ von \"{0}\" verweist auf einen Typ \"{1}\", auf den nicht zugegriffen werden kann. Eine Typanmerkung ist erforderlich.", + "The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern_2491": "Die linke Seite einer for...in-Anweisung darf kein Destrukturierungsmuster sein.", + "The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation_2404": "Die linke Seite einer for...in-Anweisung darf keine Typanmerkung verwenden.", + "The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access_2406": "Die linke Seite einer for...in-Anweisung muss eine Variable oder ein Eigenschaftenzugriff sein.", + "The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any_2405": "Die linke Seite einer for...in-Anweisung muss vom Typ \"string\" oder \"any\" sein.", + "The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation_2483": "Die linke Seite einer for...of-Anweisung darf keine Typanmerkung verwenden.", + "The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access_2487": "Die linke Seite einer for...of-Anweisung muss eine Variable oder ein Eigenschaftenzugriff sein.", + "The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type_2362": "Die linke Seite einer arithmetischen Operation muss den Typ \"any\" oder \"number\" aufweisen oder ein Enumerationstyp sein.", + "The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access_2364": "Die linke Seite eines Zuweisungsausdrucks muss eine Variable oder ein Eigenschaftenzugriff sein.", + "The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol_2360": "Die linke Seite eines in-Ausdrucks muss vom Typ \"any\", \"string\", \"number\" oder \"symbol\" sein.", + "The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_paramete_2358": "Die linke Seite eines instanceof-Ausdrucks muss den Typ \"any\" aufweisen oder ein Objekttyp bzw. ein Typparameter sein.", + "The_locale_used_when_displaying_messages_to_the_user_e_g_en_us_6156": "Das beim Anzeigen von Meldungen für den Benutzer verwendete Gebietsschema (z. B. \"de-de\").", + "The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files_6136": "Die maximale Abhängigkeitstiefe, die unter \"node_modules\" durchsucht und für die JavaScript-Dateien geladen werden sollen.", + "The_operand_of_a_delete_operator_cannot_be_a_read_only_property_2704": "Der Operand eines delete-Operators darf keine schreibgeschützte Eigenschaft sein.", + "The_operand_of_a_delete_operator_must_be_a_property_reference_2703": "Der Operand eines delete-Operators muss eine Eigenschaftenreferenz sein.", + "The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access_2357": "Der Operand eines Inkrement- oder Dekrementoperators muss eine Variable oder ein Eigenschaftenzugriff sein.", + "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601": "Der Rückgabetyp eines JSX-Elementkonstruktors muss einen Objekttyp zurückgeben.", + "The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any_1237": "Der Rückgabetyp einer Parameter-Decorator-Funktion muss \"void\" oder \"any\" sein.", + "The_return_type_of_a_property_decorator_function_must_be_either_void_or_any_1236": "Der Rückgabetyp einer Eigenschaften-Decorator-Funktion muss \"void\" oder \"any\" sein.", + "The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_t_1058": "Der Rückgabetyp einer asynchronen Funktion muss entweder eine gültige Zusage sein oder darf keinen aufrufbaren \"then\"-Member enthalten.", + "The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_1064": "Der Rückgabetyp einer asynchronen Funktion oder Methode muss der globale Typ \"Promise\" sein.", + "The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_but_2407": "Die rechte Seite einer for...in-Anweisung muss den Typ \"any\" aufweisen oder ein Objekttyp bzw. ein Typparameter sein. Sie weist hier jedoch den Typ \"{0}\" auf.", + "The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type_2363": "Die rechte Seite einer arithmetischen Operation muss den Typ \"any\" oder \"number\" aufweisen oder ein Enumerationstyp sein.", + "The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter_2361": "Die rechte Seite eines in-Ausdrucks muss den Typ \"any\" aufweisen oder ein Objekttyp bzw. ein Typparameter sein.", + "The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_F_2359": "Die rechte Seite eines instanceof-Ausdrucks muss den Typ \"any\" oder einen Typ aufweisen, der dem Schnittstellentyp \"Function\" zugewiesen werden kann.", + "The_specified_path_does_not_exist_Colon_0_5058": "Der angegebene Pfad \"{0}\" ist nicht vorhanden.", + "The_target_of_an_assignment_must_be_a_variable_or_a_property_access_2541": "Das Ziel einer Zuweisung muss eine Variable oder ein Eigenschaftenzugriff sein.", + "The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access_2701": "Das Ziel einer REST-Zuweisung für ein Objekt muss eine Variable oder ein Eigenschaftenzugriff sein.", + "The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1_2684": "Der \"this\"-Kontext vom Typ \"{0}\" kann \"this\" vom Typ \"{1}\" der Methode nicht zugewiesen werden.", + "The_this_types_of_each_signature_are_incompatible_2685": "Die \"this\"-Typen jeder Signatur sind nicht kompatibel.", + "The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_typ_2453": "Das Typargument für den Typparameter \"{0}\" kann nicht aus der Syntax abgeleitet werden. Geben Sie die Typargumente ggf. explizit an.", + "The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value__2547": "Der von der \"next()\"-Methode eines Async-Iterators zurückgegebene Typ muss eine Zusage für einen Typ mit einer \"value\"-Eigenschaft sein.", + "The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property_2490": "Der von der Methode \"next()\" eines Iterators zurückgegebene Typ muss eine Eigenschaft \"value\" besitzen.", + "The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer_1189": "Die Variablendeklaration einer for...in-Anweisung darf keinen Initialisierer aufweisen.", + "The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer_1190": "Die Variablendeklaration einer for...of-Anweisung darf keinen Initialisierer aufweisen.", + "The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any_2410": "Die with-Anweisung wird nicht unterstützt. Alle Symbole in einem with-Block weisen den Typ \"any\" auf.", + "This_constructor_function_may_be_converted_to_a_class_declaration_80002": "Diese Konstruktorfunktion kann in eine Klassendeklaration konvertiert werden.", + "This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found_2354": "Diese Syntax erfordert ein importiertes Hilfsprogramm, aber das Modul \"{0}\" wurde nicht gefunden.", + "This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1_2343": "Diese Syntax erfordert ein importiertes Hilfsprogramm namens \"{1}\", aber das Modul \"{0}\" enthält keinen exportierten Member \"{1}\".", + "Trailing_comma_not_allowed_1009": "Ein nachgestelltes Komma ist unzulässig.", + "Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule_6153": "Jede Datei als separates Modul transpilieren (ähnlich wie bei \"ts.transpileModule\").", + "Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_mod_7035": "Versuchen Sie \"npm install @types/{0}\", sofern vorhanden, oder fügen Sie eine neue Deklarationsdatei (.d.ts) hinzu, die \"declare module '{0}';\" enthält.", + "Trying_other_entries_in_rootDirs_6110": "Andere Einträge in \"rootDirs\" werden versucht.", + "Trying_substitution_0_candidate_module_location_Colon_1_6093": "Die Ersetzung \"{0}\" wird versucht. Speicherort des Kandidatenmoduls: \"{1}\".", + "Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2_2493": "Der Tupeltyp \"{0}\" mit der Länge \"{1}\" kann dem Tupel mit der Länge \"{2}\" nicht zugewiesen werden.", + "Type_0_cannot_be_converted_to_type_1_2352": "Der Typ \"{0}\" kann nicht in den Typ \"{1}\" konvertiert werden.", + "Type_0_cannot_be_used_as_an_index_type_2538": "Der Typ \"{0}\" kann nicht als Indextyp verwendet werden.", + "Type_0_cannot_be_used_to_index_type_1_2536": "Der Typ \"{0}\" kann nicht zum Indizieren von Typ \"{1}\" verwendet werden.", + "Type_0_does_not_satisfy_the_constraint_1_2344": "Der Typ \"{0}\" erfüllt die Einschränkung \"{1}\" nicht.", + "Type_0_has_no_matching_index_signature_for_type_1_2537": "Der Typ \"{0}\" weist keine übereinstimmende Indexsignatur für den Typ \"{1}\" auf.", + "Type_0_has_no_properties_in_common_with_type_1_2559": "Der Typ \"{0}\" verfügt über keine gemeinsamen Eigenschaften mit Typ \"{1}\".", + "Type_0_has_no_property_1_2460": "Der Typ \"{0}\" besitzt keine Eigenschaft \"{1}\".", + "Type_0_has_no_property_1_and_no_string_index_signature_2459": "Der Typ \"{0}\" verfügt über keine Eigenschaft \"{1}\" und keine Zeichenfolgen-Indexsignatur.", + "Type_0_is_not_a_constructor_function_type_2507": "Der Typ \"{0}\" ist kein Konstruktorfunktionstyp.", + "Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Prom_1055": "Der Typ \"{0}\" ist in ES5/ES3 kein gültiger Rückgabetyp einer asynchronen Funktion, weil er nicht auf einen Promise-kompatiblen Konstruktorwert verweist.", + "Type_0_is_not_an_array_type_2461": "Der Typ \"{0}\" ist kein Arraytyp.", + "Type_0_is_not_an_array_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators_2568": "Der Typ \"{0}\" ist kein Arraytyp. Verwenden Sie die Compileroption \"--downlevelIteration\", um das Durchlaufen von Iteratoren zuzulassen.", + "Type_0_is_not_an_array_type_or_a_string_type_2495": "Der Typ \"{0}\" ist kein Array- oder Zeichenfolgentyp.", + "Type_0_is_not_an_array_type_or_a_string_type_Use_compiler_option_downlevelIteration_to_allow_iterati_2569": "Der Typ \"{0}\" ist kein Arraytyp oder Zeichenfolgentyp. Verwenden Sie die Compileroption \"--downlevelIteration\", um das Durchlaufen von Iteratoren zuzulassen.", + "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549": "Typ \"{0}\" ist kein Array-Typ oder Zeichenfolgentyp oder weist keine \"[Symbol.iterator]()\"-Methode auf, die einen Iterator zurückgibt.", + "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548": "Typ \"{0}\" ist kein Array-Typ oder weist keine \"[Symbol.iterator]()\"-Methode auf, die einen Iterator zurückgibt.", + "Type_0_is_not_assignable_to_type_1_2322": "Der Typ \"{0}\" kann dem Typ \"{1}\" nicht zugewiesen werden.", + "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_2719": "Der Typ \"{0}\" kann dem Typ \"{1}\" nicht zugewiesen werden. Es sind zwei verschiedene Typen mit diesem Namen vorhanden, diese sind jedoch nicht verwandt.", + "Type_0_is_not_comparable_to_type_1_2678": "Der Typ \"{0}\" kann nicht mit dem Typ \"{1}\" verglichen werden.", + "Type_0_is_not_generic_2315": "Der Typ \"{0}\" ist nicht generisch.", + "Type_0_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator_2504": "Der Typ \"{0}\" muss eine Methode \"[Symbol.asyncIterator]()\" aufweisen, die einen async-Iterator zurückgibt.", + "Type_0_must_have_a_Symbol_iterator_method_that_returns_an_iterator_2488": "Der Typ \"{0}\" muss eine Methode \"[Symbol.iterator]()\" aufweisen, die einen Iterator zurückgibt.", + "Type_0_provides_no_match_for_the_signature_1_2658": "Der Typ \"{0}\" enthält keine Entsprechung für die Signatur \"{1}\".", + "Type_0_recursively_references_itself_as_a_base_type_2310": "Der Typ \"{0}\" verweist rekursiv auf sich selbst als ein Basistyp.", + "Type_alias_0_circularly_references_itself_2456": "Der Typalias \"{0}\" verweist zirkulär auf sich selbst.", + "Type_alias_name_cannot_be_0_2457": "Der Typaliasname darf nicht \"{0}\" sein.", + "Type_annotation_cannot_appear_on_a_constructor_declaration_1093": "Die Typanmerkung darf nicht für eine Konstruktordeklaration verwendet werden.", + "Type_argument_candidate_1_is_not_a_valid_type_argument_because_it_is_not_a_supertype_of_candidate_0_2455": "Der Typargumentkandidat \"{1}\" ist kein gültiges Typargument, weil er kein Obertyp des Kandidaten \"{0}\" ist.", + "Type_argument_expected_1140": "Ein Typargument wurde erwartet.", + "Type_argument_list_cannot_be_empty_1099": "Die Typargumentliste darf nicht leer sein.", + "Type_arguments_cannot_be_used_here_1342": "Typargumente können an dieser Stelle nicht verwendet werden.", + "Type_declaration_files_to_be_included_in_compilation_6124": "Typdeklarationsdateien, die in die Kompilierung eingeschlossen werden sollen.", + "Type_expected_1110": "Es wurde ein Typ erwartet.", + "Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method_1062": "Auf den Typ wird direkt oder indirekt im Erfüllungsrückruf der eigenen \"then\"-Methode verwiesen.", + "Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member_1320": "Der Typ des \"await\"-Operanden muss entweder eine gültige Zusage sein oder darf keinen aufrufbaren \"then\"-Member enthalten.", + "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322": "Der Typ iterierter Elemente eines \"yield*\"-Operanden muss entweder eine gültige Zusage sein oder darf keinen aufrufbaren \"then\"-Member enthalten.", + "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321": "Der Typ eines \"yield\"-Operanden in einem asynchronen Generator muss entweder eine gültige Zusage sein oder darf keinen aufrufbaren \"then\"-Member enthalten.", + "Type_parameter_0_has_a_circular_constraint_2313": "Der Typparameter \"{0}\" weist eine zirkuläre Einschränkung auf.", + "Type_parameter_0_has_a_circular_default_2716": "Der Typparameter \"{0}\" besitzt einen zirkulären Standardwert.", + "Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4008": "Der Typparameter \"{0}\" der Aufrufsignatur aus der exportierten Schnittstelle besitzt oder verwendet den privaten Namen \"{1}\".", + "Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4006": "Der Typparameter \"{0}\" der Konstruktorsignatur aus der exportierten Schnittstelle besitzt oder verwendet den privaten Namen \"{1}\".", + "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002": "Der Typparameter \"{0}\" der exportierten Klasse besitzt oder verwendet den privaten Namen \"{1}\".", + "Type_parameter_0_of_exported_function_has_or_is_using_private_name_1_4016": "Der Typparameter \"{0}\" der exportierten Funktion besitzt oder verwendet den privaten Namen \"{1}\".", + "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004": "Der Typparameter \"{0}\" der exportierten Schnittstelle besitzt oder verwendet den privaten Namen \"{1}\".", + "Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1_4083": "Der Typparameter \"{0}\" des exportierten Typalias enthält oder verwendet den privaten Namen \"{1}\".", + "Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4014": "Der Typparameter \"{0}\" der Methode aus der exportierten Schnittstelle besitzt oder verwendet den privaten Namen \"{1}\".", + "Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4012": "Der Typparameter \"{0}\" der öffentlichen Methode aus der exportierten Klasse besitzt oder verwendet den privaten Namen \"{1}\".", + "Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4010": "Der Typparameter \"{0}\" der öffentlichen statischen Methode aus der exportierten Klasse besitzt oder verwendet den privaten Namen \"{1}\".", + "Type_parameter_declaration_expected_1139": "Eine Typparameterdeklaration wurde erwartet.", + "Type_parameter_list_cannot_be_empty_1098": "Die Typparameterliste darf nicht leer sein.", + "Type_parameter_name_cannot_be_0_2368": "Der Name des Typparameters darf nicht \"{0}\" sein.", + "Type_parameters_cannot_appear_on_a_constructor_declaration_1092": "Typparameter dürfen nicht für eine Konstruktordeklaration verwendet werden.", + "Type_predicate_0_is_not_assignable_to_1_1226": "Das Typprädikat \"{0}\" kann \"{1}\" nicht zugewiesen werden.", + "Type_reference_directive_0_was_not_resolved_6120": "======== Die Typverweisdirektive \"{0}\" wurde nicht aufgelöst. ========", + "Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2_6119": "======== Die Typverweisdirektive \"{0}\" wurde erfolgreich in \"{1}\" aufgelöst. Primär: {2}. ========", + "Types_have_separate_declarations_of_a_private_property_0_2442": "Typen weisen separate Deklarationen einer privaten Eigenschaft \"{0}\" auf.", + "Types_of_parameters_0_and_1_are_incompatible_2328": "Die Typen der Parameter \"{0}\" und \"{1}\" sind nicht kompatibel.", + "Types_of_property_0_are_incompatible_2326": "Die Typen der Eigenschaft \"{0}\" sind nicht kompatibel.", + "Unable_to_open_file_0_6050": "Die Datei \"{0}\" kann nicht geöffnet werden.", + "Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression_1238": "Die Signatur des Klassen-Decorator-Elements kann nicht aufgelöst werden, wenn der Aufruf als Ausdruck erfolgt.", + "Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression_1241": "Die Signatur des Methoden-Decorator-Elements kann nicht aufgelöst werden, wenn der Aufruf als Ausdruck erfolgt.", + "Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression_1239": "Die Signatur des Parameter-Decorator-Elements kann nicht aufgelöst werden, wenn der Aufruf als Ausdruck erfolgt.", + "Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression_1240": "Die Signatur des Eigenschaften-Decorator-Elements kann nicht aufgelöst werden, wenn der Aufruf als Ausdruck erfolgt.", + "Unexpected_end_of_text_1126": "Unerwartetes Textende.", + "Unexpected_token_1012": "Unerwartetes Token.", + "Unexpected_token_A_constructor_method_accessor_or_property_was_expected_1068": "Unerwartetes Token. Ein Konstruktor, eine Methode, eine Zugriffsmethode oder eine Eigenschaft wurde erwartet.", + "Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces_1069": "Unerwartetes Token. Es wurde ein Typparametername ohne geschweifte Klammern erwartet.", + "Unexpected_token_expected_1179": "Unerwartetes Token. \"{\" wurde erwartet.", + "Unknown_compiler_option_0_5023": "Unbekannte Compileroption \"{0}\".", + "Unknown_option_excludes_Did_you_mean_exclude_6114": "Unbekannte Option \"exclude\". Meinten Sie \"exclude\"?", + "Unknown_type_acquisition_option_0_17010": "Unbekannte Option zur Typerfassung: {0}.", + "Unreachable_code_detected_7027": "Es wurde unerreichbarer Code erkannt.", + "Unsupported_locale_0_6049": "Nicht unterstütztes Gebietsschema \"{0}\".", + "Unterminated_Unicode_escape_sequence_1199": "Nicht abgeschlossene Unicode-Escapesequenz.", + "Unterminated_quoted_string_in_response_file_0_6045": "Nicht abgeschlossene Zeichenfolge in Anführungszeichen in der Datei \"{0}\".", + "Unterminated_regular_expression_literal_1161": "Nicht abgeschlossenes reguläres Ausdrucksliteral.", + "Unterminated_string_literal_1002": "Nicht abgeschlossenes Zeichenfolgenliteral.", + "Unterminated_template_literal_1160": "Nicht abgeschlossenes Vorlagenliteral.", + "Untyped_function_calls_may_not_accept_type_arguments_2347": "Nicht typisierte Funktionsaufrufe dürfen keine Typargumente annehmen.", + "Unused_label_7028": "Nicht verwendete Bezeichnung.", + "Updating_output_timestamps_of_project_0_6359": "Ausgabezeitstempel von Projekt \"{0}\" werden aktualisiert...", + "Use_synthetic_default_member_95016": "Verwenden Sie den synthetischen Member \"default\".", + "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494": "Das Verwenden einer Zeichenfolge in einer for...of-Anweisung wird nur in ECMAScript 5 oder höher unterstützt.", + "VERSION_6036": "VERSION", + "Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it_2560": "Der Wert des Typs \"{0}\" verfügt über keine gemeinsamen Eigenschaften mit dem Typ \"{1}\". Wollten Sie ihn aufrufen?", + "Value_of_type_0_is_not_callable_Did_you_mean_to_include_new_2348": "Der Wert des Typs \"{0}\" kann nicht aufgerufen werden. Wollten Sie \"new\" einschließen?", + "Variable_0_implicitly_has_an_1_type_7005": "Die Variable \"{0}\" weist implizit einen Typ \"{1}\" auf.", + "Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined_7034": "Die Variable \"{0}\" weist an manchen Stellen implizit den Typ \"{1}\" auf, an denen der Typ nicht ermittelt werden kann.", + "Variable_0_is_used_before_being_assigned_2454": "Die Variable \"{0}\" wird vor ihrer Zuweisung verwendet.", + "Variable_declaration_expected_1134": "Eine Variablendeklaration wurde erwartet.", + "Variable_declaration_list_cannot_be_empty_1123": "Die Variablendeklarationsliste darf nicht leer sein.", + "Version_0_6029": "Version {0}", + "Watch_input_files_6005": "Eingabedateien überwachen.", + "Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen_6191": "Gibt an, ob eine veraltete Konsolenausgabe im Überwachungsmodus beibehalten wird, statt den Bildschirm zu löschen.", + "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001": "Sie können keine Elemente umbenennen, die in der TypeScript-Standardbibliothek definiert sind.", + "You_cannot_rename_this_element_8000": "Sie können dieses Element nicht umbenennen.", + "_0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write__1329": "\"{0}\" akzeptiert zu wenige Argumente, um hier als Decorator verwendet zu werden. Wollten Sie es zuerst aufrufen und \"@{0}()\" schreiben?", + "_0_are_specified_twice_The_attribute_named_0_will_be_overwritten_2710": "\"{0}\" ist zweimal angegeben. Das Attribut mit dem Namen \"{0}\" wird überschrieben.", + "_0_can_only_be_used_in_a_ts_file_8009": "\"{0}\" kann nur in einer TS-Datei verwendet werden.", + "_0_expected_1005": "\"{0}\" wurde erwartet.", + "_0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_reference_7023": "\"{0}\" weist implizit den Typ \"any\" auf, weil keine Rückgabetypanmerkung vorhanden ist und darauf direkt oder indirekt in einem der Rückgabeausdrücke des Objekts verwiesen wird.", + "_0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or__7022": "\"{0}\" weist implizit den Typ \"any\" auf, weil keine Typanmerkung vorhanden ist und darauf direkt oder indirekt im eigenen Initialisierer verwiesen wird.", + "_0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible_2692": "\"{0}\" ist ein primitiver Typ, aber \"{1}\" ist ein Wrapperobjekt. Verwenden Sie vorzugsweise \"{0}\", wenn möglich.", + "_0_is_declared_but_its_value_is_never_read_6133": "\"{0}\" ist deklariert, aber der zugehörige Wert wird nie gelesen.", + "_0_is_declared_but_never_used_6196": "\"{0}\" ist deklariert, wird aber nie verwendet.", + "_0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2_17012": "\"{0}\" ist keine gültige Metaeigenschaft für das Schlüsselwort \"{1}\". Meinten Sie \"{2}\"?", + "_0_is_referenced_directly_or_indirectly_in_its_own_base_expression_2506": "Auf \"{0}\" wird direkt oder indirekt im eigenen Basisausdruck verwiesen.", + "_0_is_referenced_directly_or_indirectly_in_its_own_type_annotation_2502": "Auf \"{0}\" wird direkt oder indirekt in der eigenen Typanmerkung verwiesen.", + "_0_list_cannot_be_empty_1097": "Die {0}-Liste darf nicht leer sein.", + "_0_modifier_already_seen_1030": "Der {0}-Modifizierer ist bereits vorhanden.", + "_0_modifier_cannot_appear_on_a_class_element_1031": "Der Modifizierer \"{0}\" darf nicht für ein Klassenelement verwendet werden.", + "_0_modifier_cannot_appear_on_a_constructor_declaration_1089": "Der Modifizierer \"{0}\" darf nicht für eine Konstruktordeklaration verwendet werden.", + "_0_modifier_cannot_appear_on_a_data_property_1043": "Der Modifizierer \"{0}\" darf nicht für eine Dateneigenschaft verwendet werden.", + "_0_modifier_cannot_appear_on_a_module_or_namespace_element_1044": "Der Modifizierer \"{0}\" darf nicht für ein Modul- oder Namespaceelement verwendet werden.", + "_0_modifier_cannot_appear_on_a_parameter_1090": "Der Modifizierer \"{0}\" darf nicht für einen Parameter verwendet werden.", + "_0_modifier_cannot_appear_on_a_type_member_1070": "Der Modifizierer \"{0}\" darf nicht für einen Typmember verwendet werden.", + "_0_modifier_cannot_appear_on_an_index_signature_1071": "Der Modifizierer \"{0}\" darf nicht für eine Indexsignatur verwendet werden.", + "_0_modifier_cannot_be_used_here_1042": "Der Modifizierer \"{0}\" kann hier nicht verwendet werden.", + "_0_modifier_cannot_be_used_in_an_ambient_context_1040": "Der Modifizierer \"{0}\" kann nicht in einem Umgebungskontext verwendet werden.", + "_0_modifier_cannot_be_used_with_1_modifier_1243": "Der Modifizierer \"{0}\" darf nicht mit dem Modifizierer \"{1}\" verwendet werden.", + "_0_modifier_cannot_be_used_with_a_class_declaration_1041": "Der Modifizierer \"{0}\" darf nicht mit einer Klassendeklaration verwendet werden.", + "_0_modifier_must_precede_1_modifier_1029": "Der Modifizierer \"{0}\" muss dem Modifizierer \"{1}\" vorangestellt sein.", + "_0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here_2702": "\"{0}\" bezieht sich nur auf einen Typ, wird hier jedoch als Namespace verwendet.", + "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_2693": "\"{0}\" bezieht sich nur auf einen Typ, wird aber hier als Wert verwendet.", + "_0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead_2686": "\"{0}\" bezieht sich auf eine globale UMD, die aktuelle Datei ist jedoch ein Modul. Ziehen Sie in Betracht, stattdessen einen Import hinzuzufügen.", + "_0_tag_already_specified_1223": "Das Tag \"{0}\" wurde bereits angegeben.", + "_0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag_1253": "Das Tag \"{0}\" kann nicht unabhängig als ein JSDoc-Tag der obersten Ebene verwendet werden.", + "_0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type_7010": "\"{0}\" ohne Rückgabetypanmerkung weist implizit einen Rückgabetyp \"{1}\" auf.", + "abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration_1242": "Der Modifizierer \"abstract\" darf nur für eine Klassen-, Methoden- oder Eigenschaftendeklaration verwendet werden.", + "await_expression_is_only_allowed_within_an_async_function_1308": "Der Ausdruck \"await\" ist nur in einer asynchronen Funktion zulässig.", + "await_expressions_cannot_be_used_in_a_parameter_initializer_2524": "await-Ausdrücke dürfen nicht in einem Parameterinitialisierer verwendet werden.", + "baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1_6106": "Die Option \"baseUrl\" ist auf \"{0}\" festgelegt. Dieser Wert wird verwendet, um den nicht relativen Modulnamen \"{1}\" aufzulösen.", + "can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment_1312": "\"=\" kann nur in einer Objektliteraleigenschaft innerhalb eines Destrukturierungsauftrags verwendet werden.", + "case_or_default_expected_1130": "\"case\" oder \"default\" wurde erwartet.", + "class_expressions_are_not_currently_supported_9003": "class-Ausdrücke werden zurzeit nicht unterstützt.", + "const_declarations_can_only_be_declared_inside_a_block_1156": "const-Deklarationen können nur innerhalb eines Blocks deklariert werden.", + "const_declarations_must_be_initialized_1155": "const-Deklarationen müssen initialisiert werden.", + "const_enum_member_initializer_was_evaluated_to_a_non_finite_value_2477": "Der const-Enumerationsmemberinitialisierer wurde in einen unendlichen Wert ausgewertet.", + "const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN_2478": "Der const-Enumerationsmemberinitialisierer wurde in den unzulässigen Wert \"NaN\" ausgewertet.", + "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475": "const-Enumerationen können nur in Eigenschaften- bzw. Indexzugriffsausdrücken oder auf der rechten Seite einer Importdeklaration oder Exportzuweisung verwendet werden.", + "delete_cannot_be_called_on_an_identifier_in_strict_mode_1102": "\"delete\" kann für einen Bezeichner im Strict-Modus nicht aufgerufen werden.", + "delete_this_Project_0_is_up_to_date_because_it_was_previously_built_6360": "Dies löschen – Projekt \"{0}\" ist auf dem neuesten Stand, da es bereits zuvor erstellt wurde", + "enum_declarations_can_only_be_used_in_a_ts_file_8015": "enum-Deklarationen können nur in einer TS-Datei verwendet werden.", + "export_can_only_be_used_in_a_ts_file_8003": "\"export=\" kann nur in einer TS-Datei verwendet werden.", + "export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always__2668": "Der Modifizierer \"export\" kann nicht auf Umgebungsmodule und Modulerweiterungen angewendet werden, da diese immer sichtbar sind.", + "extends_clause_already_seen_1172": "Die extends-Klausel ist bereits vorhanden.", + "extends_clause_must_precede_implements_clause_1173": "Die extends-Klausel muss der implements-Klausel vorangestellt sein.", + "extends_clause_of_exported_class_0_has_or_is_using_private_name_1_4020": "Die \"extends\"-Klausel der exportierten Klasse \"{0}\" besitzt oder verwendet den privaten Namen \"{1}\".", + "extends_clause_of_exported_interface_0_has_or_is_using_private_name_1_4022": "Die \"extends\"-Klausel der exportierten Schnittstelle \"{0}\" besitzt oder verwendet den privaten Namen \"{1}\".", + "file_6025": "Datei", + "get_and_set_accessor_must_have_the_same_this_type_2682": "Die get- und set-Accessoren müssen den gleichen this-Typ aufweisen.", + "get_and_set_accessor_must_have_the_same_type_2380": "Die get- und set-Zugriffsmethoden müssen den gleichen Typ aufweisen.", + "implements_clause_already_seen_1175": "Die implements-Klausel ist bereits vorhanden.", + "implements_clauses_can_only_be_used_in_a_ts_file_8005": "\"implements clauses\" kann nur in einer TS-Datei verwendet werden.", + "import_can_only_be_used_in_a_ts_file_8002": "\"import... =\" kann nur in einer TS-Datei verwendet werden.", + "infer_declarations_are_only_permitted_in_the_extends_clause_of_a_conditional_type_1338": "infer-Deklarationen sind nur in der extends-Klausel eines bedingten Typs zulässig.", + "interface_declarations_can_only_be_used_in_a_ts_file_8006": "\"interface declarations\" kann nur in einer TS-Datei verwendet werden.", + "let_declarations_can_only_be_declared_inside_a_block_1157": "let-Deklarationen können nur innerhalb eines Blocks deklariert werden.", + "let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations_2480": "\"let\" darf nicht als Name in let- oder const-Deklarationen verwendet werden.", + "module_declarations_can_only_be_used_in_a_ts_file_8007": "\"module declarations\" kann nur in einer TS-Datei verwendet werden.", + "new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead_1150": "\"new T[]\" kann nicht zum Erstellen eines Arrays verwendet werden. Verwenden Sie stattdessen \"new Array()\".", + "new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type_7009": "Der new-Ausdruck, in dessen Ziel eine Konstruktsignatur fehlt, weist implizit einen Typ \"any\" auf.", + "non_null_assertions_can_only_be_used_in_a_ts_file_8013": "Assertions, die nicht NULL sind, können nur in einer TS-Datei verwendet werden.", + "options_6024": "Optionen", + "or_expected_1144": "\"{\" oder \";\" wurde erwartet.", + "package_json_does_not_have_a_0_field_6100": "\"package.json\" besitzt kein \"{0}\"-Feld.", + "package_json_has_0_field_1_that_references_2_6101": "\"package.json\" weist das {0}-Feld \"{1}\" auf, das auf \"{2}\" verweist.", + "parameter_modifiers_can_only_be_used_in_a_ts_file_8012": "\"parameter modifiers\" kann nur in einer TS-Datei verwendet werden.", + "paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0_6091": "Die Option \"paths\" wurde angegeben. Es wird nach einem Muster gesucht, das mit dem Modulnamen \"{0}\" übereinstimmt.", + "readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024": "Der Modifizierer \"readonly\" darf nur für eine Eigenschaftendeklaration oder Indexsignatur verwendet werden.", + "require_call_may_be_converted_to_an_import_80005": "Der Aufruf von \"require\" kann in einen Aufruf von \"import\" konvertiert werden.", + "rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107": "Die Option \"rootDirs\" wurde festgelegt. Sie wird zum Auflösen des relativen Modulnamens \"{0}\" verwendet.", + "super_can_only_be_referenced_in_a_derived_class_2335": "Auf \"super\" kann nur in einer abgeleiteten Klasse verwiesen werden.", + "super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions_2660": "Auf \"super\" kann nur in Membern abgeleiteter Klassen oder Objektliteralausdrücken verwiesen werden.", + "super_cannot_be_referenced_in_a_computed_property_name_2466": "Auf \"super\" kann nicht in einem berechneten Eigenschaftennamen verwiesen werden.", + "super_cannot_be_referenced_in_constructor_arguments_2336": "Auf \"super\" kann nicht in Konstruktorargumenten verwiesen werden.", + "super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_highe_2659": "\"super\" ist nur in Membern von Objektliteralausdrücken zulässig, wenn die Option \"target\" den Wert \"ES2015\" oder höher aufweist.", + "super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class_17011": "Vor dem Zugriff auf eine Eigenschaft von \"super\" im Konstruktor einer abgeleiteten Klasse muss \"super\" aufgerufen werden.", + "super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class_17009": "\"super\" muss vor dem Zugreifen auf \"this\" im Konstruktor einer abgeleiteten Klasse aufgerufen werden.", + "super_must_be_followed_by_an_argument_list_or_member_access_1034": "Auf \"super\" muss eine Argumentliste oder Memberzugriff folgen.", + "super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_der_2338": "Der Zugriff auf die super-Eigenschaft ist nur in einem Konstruktor, einer Memberfunktion oder einer Memberzugriffsmethode einer abgeleiteten Klasse zulässig.", + "this_cannot_be_referenced_in_a_computed_property_name_2465": "Auf \"this\" kann nicht in einem berechneten Eigenschaftennamen verwiesen werden.", + "this_cannot_be_referenced_in_a_module_or_namespace_body_2331": "Auf \"this\" kann nicht in einem Modul- oder Namespacetext verwiesen werden.", + "this_cannot_be_referenced_in_a_static_property_initializer_2334": "Auf \"this\" kann nicht in einem statischen Eigenschafteninitialisierer verwiesen werden.", + "this_cannot_be_referenced_in_constructor_arguments_2333": "Auf \"this\" kann nicht in Konstruktorargumenten verwiesen werden.", + "this_cannot_be_referenced_in_current_location_2332": "Auf \"this\" kann am aktuellen Speicherort nicht verwiesen werden.", + "this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_2683": "\"this\" weist implizit den Typ \"any\" auf, weil keine Typanmerkung vorhanden ist.", + "type_aliases_can_only_be_used_in_a_ts_file_8008": "\"type aliases\" kann nur in einer TS-Datei verwendet werden.", + "type_arguments_can_only_be_used_in_a_ts_file_8011": "Typargumente können nur in einer TS-Datei verwendet werden.", + "type_assertion_expressions_can_only_be_used_in_a_ts_file_8016": "\"type assertion expressions\" kann nur in einer TS-Datei verwendet werden.", + "type_parameter_declarations_can_only_be_used_in_a_ts_file_8004": "\"type parameter declarations\" kann nur in einer TS-Datei verwendet werden.", + "types_can_only_be_used_in_a_ts_file_8010": "\"types\" kann nur in einer TS-Datei verwendet werden.", + "unique_symbol_types_are_not_allowed_here_1335": "\"unique symbol\"-Typen sind hier nicht zulässig.", + "unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement_1334": "\"unique symbol\"-Typen sind nur für Variablen in einer Variablenanweisung zulässig.", + "unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name_1333": "\"unique symbol\"-Typen dürfen für eine Variablendeklaration mit einem Bindungsnamen nicht verwendet werden.", + "with_statements_are_not_allowed_in_an_async_function_block_1300": "with-Anweisungen sind in einem asynchronen Funktionsblock unzulässig.", + "with_statements_are_not_allowed_in_strict_mode_1101": "this-Anweisungen sind im Strict-Modus unzulässig.", + "yield_expressions_cannot_be_used_in_a_parameter_initializer_2523": "yield-Ausdrücke dürfen nicht in einem Parameterinitialisierer verwendet werden." +} \ No newline at end of file diff --git a/node_modules/typescript/lib/diagnosticMessages.generated.json b/node_modules/typescript/lib/diagnosticMessages.generated.json new file mode 100644 index 0000000..7bb74d3 --- /dev/null +++ b/node_modules/typescript/lib/diagnosticMessages.generated.json @@ -0,0 +1,1047 @@ +{ + "Unterminated_string_literal_1002" : "Unterminated string literal.", + "Identifier_expected_1003" : "Identifier expected.", + "_0_expected_1005" : "'{0}' expected.", + "A_file_cannot_have_a_reference_to_itself_1006" : "A file cannot have a reference to itself.", + "Trailing_comma_not_allowed_1009" : "Trailing comma not allowed.", + "Asterisk_Slash_expected_1010" : "'*/' expected.", + "An_element_access_expression_should_take_an_argument_1011" : "An element access expression should take an argument.", + "Unexpected_token_1012" : "Unexpected token.", + "A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma_1013" : "A rest parameter or binding pattern may not have a trailing comma.", + "A_rest_parameter_must_be_last_in_a_parameter_list_1014" : "A rest parameter must be last in a parameter list.", + "Parameter_cannot_have_question_mark_and_initializer_1015" : "Parameter cannot have question mark and initializer.", + "A_required_parameter_cannot_follow_an_optional_parameter_1016" : "A required parameter cannot follow an optional parameter.", + "An_index_signature_cannot_have_a_rest_parameter_1017" : "An index signature cannot have a rest parameter.", + "An_index_signature_parameter_cannot_have_an_accessibility_modifier_1018" : "An index signature parameter cannot have an accessibility modifier.", + "An_index_signature_parameter_cannot_have_a_question_mark_1019" : "An index signature parameter cannot have a question mark.", + "An_index_signature_parameter_cannot_have_an_initializer_1020" : "An index signature parameter cannot have an initializer.", + "An_index_signature_must_have_a_type_annotation_1021" : "An index signature must have a type annotation.", + "An_index_signature_parameter_must_have_a_type_annotation_1022" : "An index signature parameter must have a type annotation.", + "An_index_signature_parameter_type_must_be_string_or_number_1023" : "An index signature parameter type must be 'string' or 'number'.", + "readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024" : "'readonly' modifier can only appear on a property declaration or index signature.", + "Accessibility_modifier_already_seen_1028" : "Accessibility modifier already seen.", + "_0_modifier_must_precede_1_modifier_1029" : "'{0}' modifier must precede '{1}' modifier.", + "_0_modifier_already_seen_1030" : "'{0}' modifier already seen.", + "_0_modifier_cannot_appear_on_a_class_element_1031" : "'{0}' modifier cannot appear on a class element.", + "super_must_be_followed_by_an_argument_list_or_member_access_1034" : "'super' must be followed by an argument list or member access.", + "Only_ambient_modules_can_use_quoted_names_1035" : "Only ambient modules can use quoted names.", + "Statements_are_not_allowed_in_ambient_contexts_1036" : "Statements are not allowed in ambient contexts.", + "A_declare_modifier_cannot_be_used_in_an_already_ambient_context_1038" : "A 'declare' modifier cannot be used in an already ambient context.", + "Initializers_are_not_allowed_in_ambient_contexts_1039" : "Initializers are not allowed in ambient contexts.", + "_0_modifier_cannot_be_used_in_an_ambient_context_1040" : "'{0}' modifier cannot be used in an ambient context.", + "_0_modifier_cannot_be_used_with_a_class_declaration_1041" : "'{0}' modifier cannot be used with a class declaration.", + "_0_modifier_cannot_be_used_here_1042" : "'{0}' modifier cannot be used here.", + "_0_modifier_cannot_appear_on_a_data_property_1043" : "'{0}' modifier cannot appear on a data property.", + "_0_modifier_cannot_appear_on_a_module_or_namespace_element_1044" : "'{0}' modifier cannot appear on a module or namespace element.", + "A_0_modifier_cannot_be_used_with_an_interface_declaration_1045" : "A '{0}' modifier cannot be used with an interface declaration.", + "A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file_1046" : "A 'declare' modifier is required for a top level declaration in a .d.ts file.", + "A_rest_parameter_cannot_be_optional_1047" : "A rest parameter cannot be optional.", + "A_rest_parameter_cannot_have_an_initializer_1048" : "A rest parameter cannot have an initializer.", + "A_set_accessor_must_have_exactly_one_parameter_1049" : "A 'set' accessor must have exactly one parameter.", + "A_set_accessor_cannot_have_an_optional_parameter_1051" : "A 'set' accessor cannot have an optional parameter.", + "A_set_accessor_parameter_cannot_have_an_initializer_1052" : "A 'set' accessor parameter cannot have an initializer.", + "A_set_accessor_cannot_have_rest_parameter_1053" : "A 'set' accessor cannot have rest parameter.", + "A_get_accessor_cannot_have_parameters_1054" : "A 'get' accessor cannot have parameters.", + "Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Prom_1055" : "Type '{0}' is not a valid async function return type in ES5/ES3 because it does not refer to a Promise-compatible constructor value.", + "Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher_1056" : "Accessors are only available when targeting ECMAScript 5 and higher.", + "An_async_function_or_method_must_have_a_valid_awaitable_return_type_1057" : "An async function or method must have a valid awaitable return type.", + "The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_t_1058" : "The return type of an async function must either be a valid promise or must not contain a callable 'then' member.", + "A_promise_must_have_a_then_method_1059" : "A promise must have a 'then' method.", + "The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback_1060" : "The first parameter of the 'then' method of a promise must be a callback.", + "Enum_member_must_have_initializer_1061" : "Enum member must have initializer.", + "Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method_1062" : "Type is referenced directly or indirectly in the fulfillment callback of its own 'then' method.", + "An_export_assignment_cannot_be_used_in_a_namespace_1063" : "An export assignment cannot be used in a namespace.", + "The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_1064" : "The return type of an async function or method must be the global Promise type.", + "In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066" : "In ambient enum declarations member initializer must be constant expression.", + "Unexpected_token_A_constructor_method_accessor_or_property_was_expected_1068" : "Unexpected token. A constructor, method, accessor, or property was expected.", + "_0_modifier_cannot_appear_on_a_type_member_1070" : "'{0}' modifier cannot appear on a type member.", + "_0_modifier_cannot_appear_on_an_index_signature_1071" : "'{0}' modifier cannot appear on an index signature.", + "A_0_modifier_cannot_be_used_with_an_import_declaration_1079" : "A '{0}' modifier cannot be used with an import declaration.", + "Invalid_reference_directive_syntax_1084" : "Invalid 'reference' directive syntax.", + "Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0_1085" : "Octal literals are not available when targeting ECMAScript 5 and higher. Use the syntax '{0}'.", + "An_accessor_cannot_be_declared_in_an_ambient_context_1086" : "An accessor cannot be declared in an ambient context.", + "_0_modifier_cannot_appear_on_a_constructor_declaration_1089" : "'{0}' modifier cannot appear on a constructor declaration.", + "_0_modifier_cannot_appear_on_a_parameter_1090" : "'{0}' modifier cannot appear on a parameter.", + "Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement_1091" : "Only a single variable declaration is allowed in a 'for...in' statement.", + "Type_parameters_cannot_appear_on_a_constructor_declaration_1092" : "Type parameters cannot appear on a constructor declaration.", + "Type_annotation_cannot_appear_on_a_constructor_declaration_1093" : "Type annotation cannot appear on a constructor declaration.", + "An_accessor_cannot_have_type_parameters_1094" : "An accessor cannot have type parameters.", + "A_set_accessor_cannot_have_a_return_type_annotation_1095" : "A 'set' accessor cannot have a return type annotation.", + "An_index_signature_must_have_exactly_one_parameter_1096" : "An index signature must have exactly one parameter.", + "_0_list_cannot_be_empty_1097" : "'{0}' list cannot be empty.", + "Type_parameter_list_cannot_be_empty_1098" : "Type parameter list cannot be empty.", + "Type_argument_list_cannot_be_empty_1099" : "Type argument list cannot be empty.", + "Invalid_use_of_0_in_strict_mode_1100" : "Invalid use of '{0}' in strict mode.", + "with_statements_are_not_allowed_in_strict_mode_1101" : "'with' statements are not allowed in strict mode.", + "delete_cannot_be_called_on_an_identifier_in_strict_mode_1102" : "'delete' cannot be called on an identifier in strict mode.", + "A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator_1103" : "A 'for-await-of' statement is only allowed within an async function or async generator.", + "A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement_1104" : "A 'continue' statement can only be used within an enclosing iteration statement.", + "A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement_1105" : "A 'break' statement can only be used within an enclosing iteration or switch statement.", + "Jump_target_cannot_cross_function_boundary_1107" : "Jump target cannot cross function boundary.", + "A_return_statement_can_only_be_used_within_a_function_body_1108" : "A 'return' statement can only be used within a function body.", + "Expression_expected_1109" : "Expression expected.", + "Type_expected_1110" : "Type expected.", + "A_default_clause_cannot_appear_more_than_once_in_a_switch_statement_1113" : "A 'default' clause cannot appear more than once in a 'switch' statement.", + "Duplicate_label_0_1114" : "Duplicate label '{0}'.", + "A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement_1115" : "A 'continue' statement can only jump to a label of an enclosing iteration statement.", + "A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement_1116" : "A 'break' statement can only jump to a label of an enclosing statement.", + "An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode_1117" : "An object literal cannot have multiple properties with the same name in strict mode.", + "An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name_1118" : "An object literal cannot have multiple get/set accessors with the same name.", + "An_object_literal_cannot_have_property_and_accessor_with_the_same_name_1119" : "An object literal cannot have property and accessor with the same name.", + "An_export_assignment_cannot_have_modifiers_1120" : "An export assignment cannot have modifiers.", + "Octal_literals_are_not_allowed_in_strict_mode_1121" : "Octal literals are not allowed in strict mode.", + "A_tuple_type_element_list_cannot_be_empty_1122" : "A tuple type element list cannot be empty.", + "Variable_declaration_list_cannot_be_empty_1123" : "Variable declaration list cannot be empty.", + "Digit_expected_1124" : "Digit expected.", + "Hexadecimal_digit_expected_1125" : "Hexadecimal digit expected.", + "Unexpected_end_of_text_1126" : "Unexpected end of text.", + "Invalid_character_1127" : "Invalid character.", + "Declaration_or_statement_expected_1128" : "Declaration or statement expected.", + "Statement_expected_1129" : "Statement expected.", + "case_or_default_expected_1130" : "'case' or 'default' expected.", + "Property_or_signature_expected_1131" : "Property or signature expected.", + "Enum_member_expected_1132" : "Enum member expected.", + "Variable_declaration_expected_1134" : "Variable declaration expected.", + "Argument_expression_expected_1135" : "Argument expression expected.", + "Property_assignment_expected_1136" : "Property assignment expected.", + "Expression_or_comma_expected_1137" : "Expression or comma expected.", + "Parameter_declaration_expected_1138" : "Parameter declaration expected.", + "Type_parameter_declaration_expected_1139" : "Type parameter declaration expected.", + "Type_argument_expected_1140" : "Type argument expected.", + "String_literal_expected_1141" : "String literal expected.", + "Line_break_not_permitted_here_1142" : "Line break not permitted here.", + "or_expected_1144" : "'{' or ';' expected.", + "Declaration_expected_1146" : "Declaration expected.", + "Import_declarations_in_a_namespace_cannot_reference_a_module_1147" : "Import declarations in a namespace cannot reference a module.", + "Cannot_use_imports_exports_or_module_augmentations_when_module_is_none_1148" : "Cannot use imports, exports, or module augmentations when '--module' is 'none'.", + "File_name_0_differs_from_already_included_file_name_1_only_in_casing_1149" : "File name '{0}' differs from already included file name '{1}' only in casing.", + "new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead_1150" : "'new T[]' cannot be used to create an array. Use 'new Array()' instead.", + "const_declarations_must_be_initialized_1155" : "'const' declarations must be initialized.", + "const_declarations_can_only_be_declared_inside_a_block_1156" : "'const' declarations can only be declared inside a block.", + "let_declarations_can_only_be_declared_inside_a_block_1157" : "'let' declarations can only be declared inside a block.", + "Unterminated_template_literal_1160" : "Unterminated template literal.", + "Unterminated_regular_expression_literal_1161" : "Unterminated regular expression literal.", + "An_object_member_cannot_be_declared_optional_1162" : "An object member cannot be declared optional.", + "A_yield_expression_is_only_allowed_in_a_generator_body_1163" : "A 'yield' expression is only allowed in a generator body.", + "Computed_property_names_are_not_allowed_in_enums_1164" : "Computed property names are not allowed in enums.", + "A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_t_1165" : "A computed property name in an ambient context must refer to an expression whose type is a literal type or a 'unique symbol' type.", + "A_computed_property_name_in_a_class_property_declaration_must_refer_to_an_expression_whose_type_is_a_1166" : "A computed property name in a class property declaration must refer to an expression whose type is a literal type or a 'unique symbol' type.", + "A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_ty_1168" : "A computed property name in a method overload must refer to an expression whose type is a literal type or a 'unique symbol' type.", + "A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_1169" : "A computed property name in an interface must refer to an expression whose type is a literal type or a 'unique symbol' type.", + "A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type__1170" : "A computed property name in a type literal must refer to an expression whose type is a literal type or a 'unique symbol' type.", + "A_comma_expression_is_not_allowed_in_a_computed_property_name_1171" : "A comma expression is not allowed in a computed property name.", + "extends_clause_already_seen_1172" : "'extends' clause already seen.", + "extends_clause_must_precede_implements_clause_1173" : "'extends' clause must precede 'implements' clause.", + "Classes_can_only_extend_a_single_class_1174" : "Classes can only extend a single class.", + "implements_clause_already_seen_1175" : "'implements' clause already seen.", + "Interface_declaration_cannot_have_implements_clause_1176" : "Interface declaration cannot have 'implements' clause.", + "Binary_digit_expected_1177" : "Binary digit expected.", + "Octal_digit_expected_1178" : "Octal digit expected.", + "Unexpected_token_expected_1179" : "Unexpected token. '{' expected.", + "Property_destructuring_pattern_expected_1180" : "Property destructuring pattern expected.", + "Array_element_destructuring_pattern_expected_1181" : "Array element destructuring pattern expected.", + "A_destructuring_declaration_must_have_an_initializer_1182" : "A destructuring declaration must have an initializer.", + "An_implementation_cannot_be_declared_in_ambient_contexts_1183" : "An implementation cannot be declared in ambient contexts.", + "Modifiers_cannot_appear_here_1184" : "Modifiers cannot appear here.", + "Merge_conflict_marker_encountered_1185" : "Merge conflict marker encountered.", + "A_rest_element_cannot_have_an_initializer_1186" : "A rest element cannot have an initializer.", + "A_parameter_property_may_not_be_declared_using_a_binding_pattern_1187" : "A parameter property may not be declared using a binding pattern.", + "Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement_1188" : "Only a single variable declaration is allowed in a 'for...of' statement.", + "The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer_1189" : "The variable declaration of a 'for...in' statement cannot have an initializer.", + "The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer_1190" : "The variable declaration of a 'for...of' statement cannot have an initializer.", + "An_import_declaration_cannot_have_modifiers_1191" : "An import declaration cannot have modifiers.", + "Module_0_has_no_default_export_1192" : "Module '{0}' has no default export.", + "An_export_declaration_cannot_have_modifiers_1193" : "An export declaration cannot have modifiers.", + "Export_declarations_are_not_permitted_in_a_namespace_1194" : "Export declarations are not permitted in a namespace.", + "Catch_clause_variable_cannot_have_a_type_annotation_1196" : "Catch clause variable cannot have a type annotation.", + "Catch_clause_variable_cannot_have_an_initializer_1197" : "Catch clause variable cannot have an initializer.", + "An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive_1198" : "An extended Unicode escape value must be between 0x0 and 0x10FFFF inclusive.", + "Unterminated_Unicode_escape_sequence_1199" : "Unterminated Unicode escape sequence.", + "Line_terminator_not_permitted_before_arrow_1200" : "Line terminator not permitted before arrow.", + "Import_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_import_Asterisk_as_1202" : "Import assignment cannot be used when targeting ECMAScript modules. Consider using 'import * as ns from \"mod\"', 'import {a} from \"mod\"', 'import d from \"mod\"', or another module format instead.", + "Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or__1203" : "Export assignment cannot be used when targeting ECMAScript modules. Consider using 'export default' or another module format instead.", + "Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205" : "Cannot re-export a type when the '--isolatedModules' flag is provided.", + "Decorators_are_not_valid_here_1206" : "Decorators are not valid here.", + "Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name_1207" : "Decorators cannot be applied to multiple get/set accessors of the same name.", + "Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided_1208" : "Cannot compile namespaces when the '--isolatedModules' flag is provided.", + "Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided_1209" : "Ambient const enums are not allowed when the '--isolatedModules' flag is provided.", + "Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode_1210" : "Invalid use of '{0}'. Class definitions are automatically in strict mode.", + "A_class_declaration_without_the_default_modifier_must_have_a_name_1211" : "A class declaration without the 'default' modifier must have a name.", + "Identifier_expected_0_is_a_reserved_word_in_strict_mode_1212" : "Identifier expected. '{0}' is a reserved word in strict mode.", + "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_stric_1213" : "Identifier expected. '{0}' is a reserved word in strict mode. Class definitions are automatically in strict mode.", + "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode_1214" : "Identifier expected. '{0}' is a reserved word in strict mode. Modules are automatically in strict mode.", + "Invalid_use_of_0_Modules_are_automatically_in_strict_mode_1215" : "Invalid use of '{0}'. Modules are automatically in strict mode.", + "Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules_1216" : "Identifier expected. '__esModule' is reserved as an exported marker when transforming ECMAScript modules.", + "Export_assignment_is_not_supported_when_module_flag_is_system_1218" : "Export assignment is not supported when '--module' flag is 'system'.", + "Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_t_1219" : "Experimental support for decorators is a feature that is subject to change in a future release. Set the 'experimentalDecorators' option to remove this warning.", + "Generators_are_only_available_when_targeting_ECMAScript_2015_or_higher_1220" : "Generators are only available when targeting ECMAScript 2015 or higher.", + "Generators_are_not_allowed_in_an_ambient_context_1221" : "Generators are not allowed in an ambient context.", + "An_overload_signature_cannot_be_declared_as_a_generator_1222" : "An overload signature cannot be declared as a generator.", + "_0_tag_already_specified_1223" : "'{0}' tag already specified.", + "Signature_0_must_be_a_type_predicate_1224" : "Signature '{0}' must be a type predicate.", + "Cannot_find_parameter_0_1225" : "Cannot find parameter '{0}'.", + "Type_predicate_0_is_not_assignable_to_1_1226" : "Type predicate '{0}' is not assignable to '{1}'.", + "Parameter_0_is_not_in_the_same_position_as_parameter_1_1227" : "Parameter '{0}' is not in the same position as parameter '{1}'.", + "A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods_1228" : "A type predicate is only allowed in return type position for functions and methods.", + "A_type_predicate_cannot_reference_a_rest_parameter_1229" : "A type predicate cannot reference a rest parameter.", + "A_type_predicate_cannot_reference_element_0_in_a_binding_pattern_1230" : "A type predicate cannot reference element '{0}' in a binding pattern.", + "An_export_assignment_can_only_be_used_in_a_module_1231" : "An export assignment can only be used in a module.", + "An_import_declaration_can_only_be_used_in_a_namespace_or_module_1232" : "An import declaration can only be used in a namespace or module.", + "An_export_declaration_can_only_be_used_in_a_module_1233" : "An export declaration can only be used in a module.", + "An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file_1234" : "An ambient module declaration is only allowed at the top level in a file.", + "A_namespace_declaration_is_only_allowed_in_a_namespace_or_module_1235" : "A namespace declaration is only allowed in a namespace or module.", + "The_return_type_of_a_property_decorator_function_must_be_either_void_or_any_1236" : "The return type of a property decorator function must be either 'void' or 'any'.", + "The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any_1237" : "The return type of a parameter decorator function must be either 'void' or 'any'.", + "Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression_1238" : "Unable to resolve signature of class decorator when called as an expression.", + "Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression_1239" : "Unable to resolve signature of parameter decorator when called as an expression.", + "Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression_1240" : "Unable to resolve signature of property decorator when called as an expression.", + "Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression_1241" : "Unable to resolve signature of method decorator when called as an expression.", + "abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration_1242" : "'abstract' modifier can only appear on a class, method, or property declaration.", + "_0_modifier_cannot_be_used_with_1_modifier_1243" : "'{0}' modifier cannot be used with '{1}' modifier.", + "Abstract_methods_can_only_appear_within_an_abstract_class_1244" : "Abstract methods can only appear within an abstract class.", + "Method_0_cannot_have_an_implementation_because_it_is_marked_abstract_1245" : "Method '{0}' cannot have an implementation because it is marked abstract.", + "An_interface_property_cannot_have_an_initializer_1246" : "An interface property cannot have an initializer.", + "A_type_literal_property_cannot_have_an_initializer_1247" : "A type literal property cannot have an initializer.", + "A_class_member_cannot_have_the_0_keyword_1248" : "A class member cannot have the '{0}' keyword.", + "A_decorator_can_only_decorate_a_method_implementation_not_an_overload_1249" : "A decorator can only decorate a method implementation, not an overload.", + "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_1250" : "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'.", + "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_d_1251" : "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Class definitions are automatically in strict mode.", + "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_1252" : "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Modules are automatically in strict mode.", + "_0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag_1253" : "'{0}' tag cannot be used independently as a top level JSDoc tag.", + "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_1254" : "A 'const' initializer in an ambient context must be a string or numeric literal.", + "A_definite_assignment_assertion_is_not_permitted_in_this_context_1255" : "A definite assignment assertion '!' is not permitted in this context.", + "with_statements_are_not_allowed_in_an_async_function_block_1300" : "'with' statements are not allowed in an async function block.", + "await_expression_is_only_allowed_within_an_async_function_1308" : "'await' expression is only allowed within an async function.", + "can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment_1312" : "'=' can only be used in an object literal property inside a destructuring assignment.", + "The_body_of_an_if_statement_cannot_be_the_empty_statement_1313" : "The body of an 'if' statement cannot be the empty statement.", + "Global_module_exports_may_only_appear_in_module_files_1314" : "Global module exports may only appear in module files.", + "Global_module_exports_may_only_appear_in_declaration_files_1315" : "Global module exports may only appear in declaration files.", + "Global_module_exports_may_only_appear_at_top_level_1316" : "Global module exports may only appear at top level.", + "A_parameter_property_cannot_be_declared_using_a_rest_parameter_1317" : "A parameter property cannot be declared using a rest parameter.", + "An_abstract_accessor_cannot_have_an_implementation_1318" : "An abstract accessor cannot have an implementation.", + "A_default_export_can_only_be_used_in_an_ECMAScript_style_module_1319" : "A default export can only be used in an ECMAScript-style module.", + "Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member_1320" : "Type of 'await' operand must either be a valid promise or must not contain a callable 'then' member.", + "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321" : "Type of 'yield' operand in an async generator must either be a valid promise or must not contain a callable 'then' member.", + "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322" : "Type of iterated elements of a 'yield*' operand must either be a valid promise or must not contain a callable 'then' member.", + "Dynamic_import_cannot_be_used_when_targeting_ECMAScript_2015_modules_1323" : "Dynamic import cannot be used when targeting ECMAScript 2015 modules.", + "Dynamic_import_must_have_one_specifier_as_an_argument_1324" : "Dynamic import must have one specifier as an argument.", + "Specifier_of_dynamic_import_cannot_be_spread_element_1325" : "Specifier of dynamic import cannot be spread element.", + "Dynamic_import_cannot_have_type_arguments_1326" : "Dynamic import cannot have type arguments", + "String_literal_with_double_quotes_expected_1327" : "String literal with double quotes expected.", + "Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_li_1328" : "Property value can only be string literal, numeric literal, 'true', 'false', 'null', object literal or array literal.", + "_0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write__1329" : "'{0}' accepts too few arguments to be used as a decorator here. Did you mean to call it first and write '@{0}()'?", + "A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly_1330" : "A property of an interface or type literal whose type is a 'unique symbol' type must be 'readonly'.", + "A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly_1331" : "A property of a class whose type is a 'unique symbol' type must be both 'static' and 'readonly'.", + "A_variable_whose_type_is_a_unique_symbol_type_must_be_const_1332" : "A variable whose type is a 'unique symbol' type must be 'const'.", + "unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name_1333" : "'unique symbol' types may not be used on a variable declaration with a binding name.", + "unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement_1334" : "'unique symbol' types are only allowed on variables in a variable statement.", + "unique_symbol_types_are_not_allowed_here_1335" : "'unique symbol' types are not allowed here.", + "An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead_1336" : "An index signature parameter type cannot be a type alias. Consider writing '[{0}: {1}]: {2}' instead.", + "An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead_1337" : "An index signature parameter type cannot be a union type. Consider using a mapped object type instead.", + "infer_declarations_are_only_permitted_in_the_extends_clause_of_a_conditional_type_1338" : "'infer' declarations are only permitted in the 'extends' clause of a conditional type.", + "Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here_1339" : "Module '{0}' does not refer to a value, but is used as a value here.", + "Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_1340" : "Module '{0}' does not refer to a type, but is used as a type here.", + "Type_arguments_cannot_be_used_here_1342" : "Type arguments cannot be used here.", + "The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_option_1343" : "The 'import.meta' meta-property is only allowed using 'ESNext' for the 'target' and 'module' compiler options.", + "Duplicate_identifier_0_2300" : "Duplicate identifier '{0}'.", + "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301" : "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor.", + "Static_members_cannot_reference_class_type_parameters_2302" : "Static members cannot reference class type parameters.", + "Circular_definition_of_import_alias_0_2303" : "Circular definition of import alias '{0}'.", + "Cannot_find_name_0_2304" : "Cannot find name '{0}'.", + "Module_0_has_no_exported_member_1_2305" : "Module '{0}' has no exported member '{1}'.", + "File_0_is_not_a_module_2306" : "File '{0}' is not a module.", + "Cannot_find_module_0_2307" : "Cannot find module '{0}'.", + "Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambig_2308" : "Module {0} has already exported a member named '{1}'. Consider explicitly re-exporting to resolve the ambiguity.", + "An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements_2309" : "An export assignment cannot be used in a module with other exported elements.", + "Type_0_recursively_references_itself_as_a_base_type_2310" : "Type '{0}' recursively references itself as a base type.", + "A_class_may_only_extend_another_class_2311" : "A class may only extend another class.", + "An_interface_may_only_extend_a_class_or_another_interface_2312" : "An interface may only extend a class or another interface.", + "Type_parameter_0_has_a_circular_constraint_2313" : "Type parameter '{0}' has a circular constraint.", + "Generic_type_0_requires_1_type_argument_s_2314" : "Generic type '{0}' requires {1} type argument(s).", + "Type_0_is_not_generic_2315" : "Type '{0}' is not generic.", + "Global_type_0_must_be_a_class_or_interface_type_2316" : "Global type '{0}' must be a class or interface type.", + "Global_type_0_must_have_1_type_parameter_s_2317" : "Global type '{0}' must have {1} type parameter(s).", + "Cannot_find_global_type_0_2318" : "Cannot find global type '{0}'.", + "Named_property_0_of_types_1_and_2_are_not_identical_2319" : "Named property '{0}' of types '{1}' and '{2}' are not identical.", + "Interface_0_cannot_simultaneously_extend_types_1_and_2_2320" : "Interface '{0}' cannot simultaneously extend types '{1}' and '{2}'.", + "Excessive_stack_depth_comparing_types_0_and_1_2321" : "Excessive stack depth comparing types '{0}' and '{1}'.", + "Type_0_is_not_assignable_to_type_1_2322" : "Type '{0}' is not assignable to type '{1}'.", + "Cannot_redeclare_exported_variable_0_2323" : "Cannot redeclare exported variable '{0}'.", + "Property_0_is_missing_in_type_1_2324" : "Property '{0}' is missing in type '{1}'.", + "Property_0_is_private_in_type_1_but_not_in_type_2_2325" : "Property '{0}' is private in type '{1}' but not in type '{2}'.", + "Types_of_property_0_are_incompatible_2326" : "Types of property '{0}' are incompatible.", + "Property_0_is_optional_in_type_1_but_required_in_type_2_2327" : "Property '{0}' is optional in type '{1}' but required in type '{2}'.", + "Types_of_parameters_0_and_1_are_incompatible_2328" : "Types of parameters '{0}' and '{1}' are incompatible.", + "Index_signature_is_missing_in_type_0_2329" : "Index signature is missing in type '{0}'.", + "Index_signatures_are_incompatible_2330" : "Index signatures are incompatible.", + "this_cannot_be_referenced_in_a_module_or_namespace_body_2331" : "'this' cannot be referenced in a module or namespace body.", + "this_cannot_be_referenced_in_current_location_2332" : "'this' cannot be referenced in current location.", + "this_cannot_be_referenced_in_constructor_arguments_2333" : "'this' cannot be referenced in constructor arguments.", + "this_cannot_be_referenced_in_a_static_property_initializer_2334" : "'this' cannot be referenced in a static property initializer.", + "super_can_only_be_referenced_in_a_derived_class_2335" : "'super' can only be referenced in a derived class.", + "super_cannot_be_referenced_in_constructor_arguments_2336" : "'super' cannot be referenced in constructor arguments.", + "Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors_2337" : "Super calls are not permitted outside constructors or in nested functions inside constructors.", + "super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_der_2338" : "'super' property access is permitted only in a constructor, member function, or member accessor of a derived class.", + "Property_0_does_not_exist_on_type_1_2339" : "Property '{0}' does not exist on type '{1}'.", + "Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword_2340" : "Only public and protected methods of the base class are accessible via the 'super' keyword.", + "Property_0_is_private_and_only_accessible_within_class_1_2341" : "Property '{0}' is private and only accessible within class '{1}'.", + "An_index_expression_argument_must_be_of_type_string_number_symbol_or_any_2342" : "An index expression argument must be of type 'string', 'number', 'symbol', or 'any'.", + "This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1_2343" : "This syntax requires an imported helper named '{1}', but module '{0}' has no exported member '{1}'.", + "Type_0_does_not_satisfy_the_constraint_1_2344" : "Type '{0}' does not satisfy the constraint '{1}'.", + "Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_2345" : "Argument of type '{0}' is not assignable to parameter of type '{1}'.", + "Call_target_does_not_contain_any_signatures_2346" : "Call target does not contain any signatures.", + "Untyped_function_calls_may_not_accept_type_arguments_2347" : "Untyped function calls may not accept type arguments.", + "Value_of_type_0_is_not_callable_Did_you_mean_to_include_new_2348" : "Value of type '{0}' is not callable. Did you mean to include 'new'?", + "Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatur_2349" : "Cannot invoke an expression whose type lacks a call signature. Type '{0}' has no compatible call signatures.", + "Only_a_void_function_can_be_called_with_the_new_keyword_2350" : "Only a void function can be called with the 'new' keyword.", + "Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature_2351" : "Cannot use 'new' with an expression whose type lacks a call or construct signature.", + "Type_0_cannot_be_converted_to_type_1_2352" : "Type '{0}' cannot be converted to type '{1}'.", + "Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1_2353" : "Object literal may only specify known properties, and '{0}' does not exist in type '{1}'.", + "This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found_2354" : "This syntax requires an imported helper but module '{0}' cannot be found.", + "A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value_2355" : "A function whose declared type is neither 'void' nor 'any' must return a value.", + "An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type_2356" : "An arithmetic operand must be of type 'any', 'number' or an enum type.", + "The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access_2357" : "The operand of an increment or decrement operator must be a variable or a property access.", + "The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_paramete_2358" : "The left-hand side of an 'instanceof' expression must be of type 'any', an object type or a type parameter.", + "The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_F_2359" : "The right-hand side of an 'instanceof' expression must be of type 'any' or of a type assignable to the 'Function' interface type.", + "The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol_2360" : "The left-hand side of an 'in' expression must be of type 'any', 'string', 'number', or 'symbol'.", + "The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter_2361" : "The right-hand side of an 'in' expression must be of type 'any', an object type or a type parameter.", + "The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type_2362" : "The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type.", + "The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type_2363" : "The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type.", + "The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access_2364" : "The left-hand side of an assignment expression must be a variable or a property access.", + "Operator_0_cannot_be_applied_to_types_1_and_2_2365" : "Operator '{0}' cannot be applied to types '{1}' and '{2}'.", + "Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined_2366" : "Function lacks ending return statement and return type does not include 'undefined'.", + "Type_parameter_name_cannot_be_0_2368" : "Type parameter name cannot be '{0}'.", + "A_parameter_property_is_only_allowed_in_a_constructor_implementation_2369" : "A parameter property is only allowed in a constructor implementation.", + "A_rest_parameter_must_be_of_an_array_type_2370" : "A rest parameter must be of an array type.", + "A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation_2371" : "A parameter initializer is only allowed in a function or constructor implementation.", + "Parameter_0_cannot_be_referenced_in_its_initializer_2372" : "Parameter '{0}' cannot be referenced in its initializer.", + "Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it_2373" : "Initializer of parameter '{0}' cannot reference identifier '{1}' declared after it.", + "Duplicate_string_index_signature_2374" : "Duplicate string index signature.", + "Duplicate_number_index_signature_2375" : "Duplicate number index signature.", + "A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_proper_2376" : "A 'super' call must be the first statement in the constructor when a class contains initialized properties or has parameter properties.", + "Constructors_for_derived_classes_must_contain_a_super_call_2377" : "Constructors for derived classes must contain a 'super' call.", + "A_get_accessor_must_return_a_value_2378" : "A 'get' accessor must return a value.", + "Getter_and_setter_accessors_do_not_agree_in_visibility_2379" : "Getter and setter accessors do not agree in visibility.", + "get_and_set_accessor_must_have_the_same_type_2380" : "'get' and 'set' accessor must have the same type.", + "A_signature_with_an_implementation_cannot_use_a_string_literal_type_2381" : "A signature with an implementation cannot use a string literal type.", + "Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature_2382" : "Specialized overload signature is not assignable to any non-specialized signature.", + "Overload_signatures_must_all_be_exported_or_non_exported_2383" : "Overload signatures must all be exported or non-exported.", + "Overload_signatures_must_all_be_ambient_or_non_ambient_2384" : "Overload signatures must all be ambient or non-ambient.", + "Overload_signatures_must_all_be_public_private_or_protected_2385" : "Overload signatures must all be public, private or protected.", + "Overload_signatures_must_all_be_optional_or_required_2386" : "Overload signatures must all be optional or required.", + "Function_overload_must_be_static_2387" : "Function overload must be static.", + "Function_overload_must_not_be_static_2388" : "Function overload must not be static.", + "Function_implementation_name_must_be_0_2389" : "Function implementation name must be '{0}'.", + "Constructor_implementation_is_missing_2390" : "Constructor implementation is missing.", + "Function_implementation_is_missing_or_not_immediately_following_the_declaration_2391" : "Function implementation is missing or not immediately following the declaration.", + "Multiple_constructor_implementations_are_not_allowed_2392" : "Multiple constructor implementations are not allowed.", + "Duplicate_function_implementation_2393" : "Duplicate function implementation.", + "Overload_signature_is_not_compatible_with_function_implementation_2394" : "Overload signature is not compatible with function implementation.", + "Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local_2395" : "Individual declarations in merged declaration '{0}' must be all exported or all local.", + "Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters_2396" : "Duplicate identifier 'arguments'. Compiler uses 'arguments' to initialize rest parameters.", + "Declaration_name_conflicts_with_built_in_global_identifier_0_2397" : "Declaration name conflicts with built-in global identifier '{0}'.", + "Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference_2399" : "Duplicate identifier '_this'. Compiler uses variable declaration '_this' to capture 'this' reference.", + "Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference_2400" : "Expression resolves to variable declaration '_this' that compiler uses to capture 'this' reference.", + "Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference_2401" : "Duplicate identifier '_super'. Compiler uses '_super' to capture base class reference.", + "Expression_resolves_to_super_that_compiler_uses_to_capture_base_class_reference_2402" : "Expression resolves to '_super' that compiler uses to capture base class reference.", + "Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_t_2403" : "Subsequent variable declarations must have the same type. Variable '{0}' must be of type '{1}', but here has type '{2}'.", + "The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation_2404" : "The left-hand side of a 'for...in' statement cannot use a type annotation.", + "The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any_2405" : "The left-hand side of a 'for...in' statement must be of type 'string' or 'any'.", + "The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access_2406" : "The left-hand side of a 'for...in' statement must be a variable or a property access.", + "The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_but_2407" : "The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter, but here has type '{0}'.", + "Setters_cannot_return_a_value_2408" : "Setters cannot return a value.", + "Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class_2409" : "Return type of constructor signature must be assignable to the instance type of the class.", + "The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any_2410" : "The 'with' statement is not supported. All symbols in a 'with' block will have type 'any'.", + "Property_0_of_type_1_is_not_assignable_to_string_index_type_2_2411" : "Property '{0}' of type '{1}' is not assignable to string index type '{2}'.", + "Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2_2412" : "Property '{0}' of type '{1}' is not assignable to numeric index type '{2}'.", + "Numeric_index_type_0_is_not_assignable_to_string_index_type_1_2413" : "Numeric index type '{0}' is not assignable to string index type '{1}'.", + "Class_name_cannot_be_0_2414" : "Class name cannot be '{0}'.", + "Class_0_incorrectly_extends_base_class_1_2415" : "Class '{0}' incorrectly extends base class '{1}'.", + "Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2_2416" : "Property '{0}' in type '{1}' is not assignable to the same property in base type '{2}'.", + "Class_static_side_0_incorrectly_extends_base_class_static_side_1_2417" : "Class static side '{0}' incorrectly extends base class static side '{1}'.", + "Class_0_incorrectly_implements_interface_1_2420" : "Class '{0}' incorrectly implements interface '{1}'.", + "A_class_may_only_implement_another_class_or_interface_2422" : "A class may only implement another class or interface.", + "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_access_2423" : "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member accessor.", + "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_proper_2424" : "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member property.", + "Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_functi_2425" : "Class '{0}' defines instance member property '{1}', but extended class '{2}' defines it as instance member function.", + "Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_functi_2426" : "Class '{0}' defines instance member accessor '{1}', but extended class '{2}' defines it as instance member function.", + "Interface_name_cannot_be_0_2427" : "Interface name cannot be '{0}'.", + "All_declarations_of_0_must_have_identical_type_parameters_2428" : "All declarations of '{0}' must have identical type parameters.", + "Interface_0_incorrectly_extends_interface_1_2430" : "Interface '{0}' incorrectly extends interface '{1}'.", + "Enum_name_cannot_be_0_2431" : "Enum name cannot be '{0}'.", + "In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enu_2432" : "In an enum with multiple declarations, only one declaration can omit an initializer for its first enum element.", + "A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merg_2433" : "A namespace declaration cannot be in a different file from a class or function with which it is merged.", + "A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged_2434" : "A namespace declaration cannot be located prior to a class or function with which it is merged.", + "Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces_2435" : "Ambient modules cannot be nested in other modules or namespaces.", + "Ambient_module_declaration_cannot_specify_relative_module_name_2436" : "Ambient module declaration cannot specify relative module name.", + "Module_0_is_hidden_by_a_local_declaration_with_the_same_name_2437" : "Module '{0}' is hidden by a local declaration with the same name.", + "Import_name_cannot_be_0_2438" : "Import name cannot be '{0}'.", + "Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relati_2439" : "Import or export declaration in an ambient module declaration cannot reference module through relative module name.", + "Import_declaration_conflicts_with_local_declaration_of_0_2440" : "Import declaration conflicts with local declaration of '{0}'.", + "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_2441" : "Duplicate identifier '{0}'. Compiler reserves name '{1}' in top level scope of a module.", + "Types_have_separate_declarations_of_a_private_property_0_2442" : "Types have separate declarations of a private property '{0}'.", + "Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2_2443" : "Property '{0}' is protected but type '{1}' is not a class derived from '{2}'.", + "Property_0_is_protected_in_type_1_but_public_in_type_2_2444" : "Property '{0}' is protected in type '{1}' but public in type '{2}'.", + "Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses_2445" : "Property '{0}' is protected and only accessible within class '{1}' and its subclasses.", + "Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1_2446" : "Property '{0}' is protected and only accessible through an instance of class '{1}'.", + "The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead_2447" : "The '{0}' operator is not allowed for boolean types. Consider using '{1}' instead.", + "Block_scoped_variable_0_used_before_its_declaration_2448" : "Block-scoped variable '{0}' used before its declaration.", + "Class_0_used_before_its_declaration_2449" : "Class '{0}' used before its declaration.", + "Enum_0_used_before_its_declaration_2450" : "Enum '{0}' used before its declaration.", + "Cannot_redeclare_block_scoped_variable_0_2451" : "Cannot redeclare block-scoped variable '{0}'.", + "An_enum_member_cannot_have_a_numeric_name_2452" : "An enum member cannot have a numeric name.", + "The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_typ_2453" : "The type argument for type parameter '{0}' cannot be inferred from the usage. Consider specifying the type arguments explicitly.", + "Variable_0_is_used_before_being_assigned_2454" : "Variable '{0}' is used before being assigned.", + "Type_argument_candidate_1_is_not_a_valid_type_argument_because_it_is_not_a_supertype_of_candidate_0_2455" : "Type argument candidate '{1}' is not a valid type argument because it is not a supertype of candidate '{0}'.", + "Type_alias_0_circularly_references_itself_2456" : "Type alias '{0}' circularly references itself.", + "Type_alias_name_cannot_be_0_2457" : "Type alias name cannot be '{0}'.", + "An_AMD_module_cannot_have_multiple_name_assignments_2458" : "An AMD module cannot have multiple name assignments.", + "Type_0_has_no_property_1_and_no_string_index_signature_2459" : "Type '{0}' has no property '{1}' and no string index signature.", + "Type_0_has_no_property_1_2460" : "Type '{0}' has no property '{1}'.", + "Type_0_is_not_an_array_type_2461" : "Type '{0}' is not an array type.", + "A_rest_element_must_be_last_in_a_destructuring_pattern_2462" : "A rest element must be last in a destructuring pattern.", + "A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature_2463" : "A binding pattern parameter cannot be optional in an implementation signature.", + "A_computed_property_name_must_be_of_type_string_number_symbol_or_any_2464" : "A computed property name must be of type 'string', 'number', 'symbol', or 'any'.", + "this_cannot_be_referenced_in_a_computed_property_name_2465" : "'this' cannot be referenced in a computed property name.", + "super_cannot_be_referenced_in_a_computed_property_name_2466" : "'super' cannot be referenced in a computed property name.", + "A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type_2467" : "A computed property name cannot reference a type parameter from its containing type.", + "Cannot_find_global_value_0_2468" : "Cannot find global value '{0}'.", + "The_0_operator_cannot_be_applied_to_type_symbol_2469" : "The '{0}' operator cannot be applied to type 'symbol'.", + "Symbol_reference_does_not_refer_to_the_global_Symbol_constructor_object_2470" : "'Symbol' reference does not refer to the global Symbol constructor object.", + "A_computed_property_name_of_the_form_0_must_be_of_type_symbol_2471" : "A computed property name of the form '{0}' must be of type 'symbol'.", + "Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher_2472" : "Spread operator in 'new' expressions is only available when targeting ECMAScript 5 and higher.", + "Enum_declarations_must_all_be_const_or_non_const_2473" : "Enum declarations must all be const or non-const.", + "In_const_enum_declarations_member_initializer_must_be_constant_expression_2474" : "In 'const' enum declarations member initializer must be constant expression.", + "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475" : "'const' enums can only be used in property or index access expressions or the right hand side of an import declaration or export assignment or type query.", + "A_const_enum_member_can_only_be_accessed_using_a_string_literal_2476" : "A const enum member can only be accessed using a string literal.", + "const_enum_member_initializer_was_evaluated_to_a_non_finite_value_2477" : "'const' enum member initializer was evaluated to a non-finite value.", + "const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN_2478" : "'const' enum member initializer was evaluated to disallowed value 'NaN'.", + "Property_0_does_not_exist_on_const_enum_1_2479" : "Property '{0}' does not exist on 'const' enum '{1}'.", + "let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations_2480" : "'let' is not allowed to be used as a name in 'let' or 'const' declarations.", + "Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1_2481" : "Cannot initialize outer scoped variable '{0}' in the same scope as block scoped declaration '{1}'.", + "The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation_2483" : "The left-hand side of a 'for...of' statement cannot use a type annotation.", + "Export_declaration_conflicts_with_exported_declaration_of_0_2484" : "Export declaration conflicts with exported declaration of '{0}'.", + "The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access_2487" : "The left-hand side of a 'for...of' statement must be a variable or a property access.", + "Type_0_must_have_a_Symbol_iterator_method_that_returns_an_iterator_2488" : "Type '{0}' must have a '[Symbol.iterator]()' method that returns an iterator.", + "An_iterator_must_have_a_next_method_2489" : "An iterator must have a 'next()' method.", + "The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property_2490" : "The type returned by the 'next()' method of an iterator must have a 'value' property.", + "The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern_2491" : "The left-hand side of a 'for...in' statement cannot be a destructuring pattern.", + "Cannot_redeclare_identifier_0_in_catch_clause_2492" : "Cannot redeclare identifier '{0}' in catch clause.", + "Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2_2493" : "Tuple type '{0}' with length '{1}' cannot be assigned to tuple with length '{2}'.", + "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494" : "Using a string in a 'for...of' statement is only supported in ECMAScript 5 and higher.", + "Type_0_is_not_an_array_type_or_a_string_type_2495" : "Type '{0}' is not an array type or a string type.", + "The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_stand_2496" : "The 'arguments' object cannot be referenced in an arrow function in ES3 and ES5. Consider using a standard function expression.", + "Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct_2497" : "Module '{0}' resolves to a non-module entity and cannot be imported using this construct.", + "Module_0_uses_export_and_cannot_be_used_with_export_Asterisk_2498" : "Module '{0}' uses 'export =' and cannot be used with 'export *'.", + "An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments_2499" : "An interface can only extend an identifier/qualified-name with optional type arguments.", + "A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments_2500" : "A class can only implement an identifier/qualified-name with optional type arguments.", + "A_rest_element_cannot_contain_a_binding_pattern_2501" : "A rest element cannot contain a binding pattern.", + "_0_is_referenced_directly_or_indirectly_in_its_own_type_annotation_2502" : "'{0}' is referenced directly or indirectly in its own type annotation.", + "Cannot_find_namespace_0_2503" : "Cannot find namespace '{0}'.", + "Type_0_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator_2504" : "Type '{0}' must have a '[Symbol.asyncIterator]()' method that returns an async iterator.", + "A_generator_cannot_have_a_void_type_annotation_2505" : "A generator cannot have a 'void' type annotation.", + "_0_is_referenced_directly_or_indirectly_in_its_own_base_expression_2506" : "'{0}' is referenced directly or indirectly in its own base expression.", + "Type_0_is_not_a_constructor_function_type_2507" : "Type '{0}' is not a constructor function type.", + "No_base_constructor_has_the_specified_number_of_type_arguments_2508" : "No base constructor has the specified number of type arguments.", + "Base_constructor_return_type_0_is_not_a_class_or_interface_type_2509" : "Base constructor return type '{0}' is not a class or interface type.", + "Base_constructors_must_all_have_the_same_return_type_2510" : "Base constructors must all have the same return type.", + "Cannot_create_an_instance_of_an_abstract_class_2511" : "Cannot create an instance of an abstract class.", + "Overload_signatures_must_all_be_abstract_or_non_abstract_2512" : "Overload signatures must all be abstract or non-abstract.", + "Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression_2513" : "Abstract method '{0}' in class '{1}' cannot be accessed via super expression.", + "Classes_containing_abstract_methods_must_be_marked_abstract_2514" : "Classes containing abstract methods must be marked abstract.", + "Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2_2515" : "Non-abstract class '{0}' does not implement inherited abstract member '{1}' from class '{2}'.", + "All_declarations_of_an_abstract_method_must_be_consecutive_2516" : "All declarations of an abstract method must be consecutive.", + "Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type_2517" : "Cannot assign an abstract constructor type to a non-abstract constructor type.", + "A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard_2518" : "A 'this'-based type guard is not compatible with a parameter-based type guard.", + "An_async_iterator_must_have_a_next_method_2519" : "An async iterator must have a 'next()' method.", + "Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions_2520" : "Duplicate identifier '{0}'. Compiler uses declaration '{1}' to support async functions.", + "Expression_resolves_to_variable_declaration_0_that_compiler_uses_to_support_async_functions_2521" : "Expression resolves to variable declaration '{0}' that compiler uses to support async functions.", + "The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_usi_2522" : "The 'arguments' object cannot be referenced in an async function or method in ES3 and ES5. Consider using a standard function or method.", + "yield_expressions_cannot_be_used_in_a_parameter_initializer_2523" : "'yield' expressions cannot be used in a parameter initializer.", + "await_expressions_cannot_be_used_in_a_parameter_initializer_2524" : "'await' expressions cannot be used in a parameter initializer.", + "Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value_2525" : "Initializer provides no value for this binding element and the binding element has no default value.", + "A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface_2526" : "A 'this' type is available only in a non-static member of a class or interface.", + "The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary_2527" : "The inferred type of '{0}' references an inaccessible '{1}' type. A type annotation is necessary.", + "A_module_cannot_have_multiple_default_exports_2528" : "A module cannot have multiple default exports.", + "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_func_2529" : "Duplicate identifier '{0}'. Compiler reserves name '{1}' in top level scope of a module containing async functions.", + "Property_0_is_incompatible_with_index_signature_2530" : "Property '{0}' is incompatible with index signature.", + "Object_is_possibly_null_2531" : "Object is possibly 'null'.", + "Object_is_possibly_undefined_2532" : "Object is possibly 'undefined'.", + "Object_is_possibly_null_or_undefined_2533" : "Object is possibly 'null' or 'undefined'.", + "A_function_returning_never_cannot_have_a_reachable_end_point_2534" : "A function returning 'never' cannot have a reachable end point.", + "Enum_type_0_has_members_with_initializers_that_are_not_literals_2535" : "Enum type '{0}' has members with initializers that are not literals.", + "Type_0_cannot_be_used_to_index_type_1_2536" : "Type '{0}' cannot be used to index type '{1}'.", + "Type_0_has_no_matching_index_signature_for_type_1_2537" : "Type '{0}' has no matching index signature for type '{1}'.", + "Type_0_cannot_be_used_as_an_index_type_2538" : "Type '{0}' cannot be used as an index type.", + "Cannot_assign_to_0_because_it_is_not_a_variable_2539" : "Cannot assign to '{0}' because it is not a variable.", + "Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property_2540" : "Cannot assign to '{0}' because it is a constant or a read-only property.", + "The_target_of_an_assignment_must_be_a_variable_or_a_property_access_2541" : "The target of an assignment must be a variable or a property access.", + "Index_signature_in_type_0_only_permits_reading_2542" : "Index signature in type '{0}' only permits reading.", + "Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_me_2543" : "Duplicate identifier '_newTarget'. Compiler uses variable declaration '_newTarget' to capture 'new.target' meta-property reference.", + "Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta__2544" : "Expression resolves to variable declaration '_newTarget' that compiler uses to capture 'new.target' meta-property reference.", + "A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any_2545" : "A mixin class must have a constructor with a single rest parameter of type 'any[]'.", + "Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1_2546" : "Property '{0}' has conflicting declarations and is inaccessible in type '{1}'.", + "The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value__2547" : "The type returned by the 'next()' method of an async iterator must be a promise for a type with a 'value' property.", + "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548" : "Type '{0}' is not an array type or does not have a '[Symbol.iterator]()' method that returns an iterator.", + "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549" : "Type '{0}' is not an array type or a string type or does not have a '[Symbol.iterator]()' method that returns an iterator.", + "Generic_type_instantiation_is_excessively_deep_and_possibly_infinite_2550" : "Generic type instantiation is excessively deep and possibly infinite.", + "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551" : "Property '{0}' does not exist on type '{1}'. Did you mean '{2}'?", + "Cannot_find_name_0_Did_you_mean_1_2552" : "Cannot find name '{0}'. Did you mean '{1}'?", + "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553" : "Computed values are not permitted in an enum with string valued members.", + "Expected_0_arguments_but_got_1_2554" : "Expected {0} arguments, but got {1}.", + "Expected_at_least_0_arguments_but_got_1_2555" : "Expected at least {0} arguments, but got {1}.", + "Expected_0_arguments_but_got_1_or_more_2556" : "Expected {0} arguments, but got {1} or more.", + "Expected_at_least_0_arguments_but_got_1_or_more_2557" : "Expected at least {0} arguments, but got {1} or more.", + "Expected_0_type_arguments_but_got_1_2558" : "Expected {0} type arguments, but got {1}.", + "Type_0_has_no_properties_in_common_with_type_1_2559" : "Type '{0}' has no properties in common with type '{1}'.", + "Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it_2560" : "Value of type '{0}' has no properties in common with type '{1}'. Did you mean to call it?", + "Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_writ_2561" : "Object literal may only specify known properties, but '{0}' does not exist in type '{1}'. Did you mean to write '{2}'?", + "Base_class_expressions_cannot_reference_class_type_parameters_2562" : "Base class expressions cannot reference class type parameters.", + "The_containing_function_or_module_body_is_too_large_for_control_flow_analysis_2563" : "The containing function or module body is too large for control flow analysis.", + "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor_2564" : "Property '{0}' has no initializer and is not definitely assigned in the constructor.", + "Property_0_is_used_before_being_assigned_2565" : "Property '{0}' is used before being assigned.", + "A_rest_element_cannot_have_a_property_name_2566" : "A rest element cannot have a property name.", + "Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations_2567" : "Enum declarations can only merge with namespace or other enum declarations.", + "Type_0_is_not_an_array_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators_2568" : "Type '{0}' is not an array type. Use compiler option '--downlevelIteration' to allow iterating of iterators.", + "Type_0_is_not_an_array_type_or_a_string_type_Use_compiler_option_downlevelIteration_to_allow_iterati_2569" : "Type '{0}' is not an array type or a string type. Use compiler option '--downlevelIteration' to allow iterating of iterators.", + "Property_0_does_not_exist_on_type_1_Did_you_forget_to_use_await_2570" : "Property '{0}' does not exist on type '{1}'. Did you forget to use 'await'?", + "JSX_element_attributes_type_0_may_not_be_a_union_type_2600" : "JSX element attributes type '{0}' may not be a union type.", + "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601" : "The return type of a JSX element constructor must return an object type.", + "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602" : "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist.", + "Property_0_in_type_1_is_not_assignable_to_type_2_2603" : "Property '{0}' in type '{1}' is not assignable to type '{2}'.", + "JSX_element_type_0_does_not_have_any_construct_or_call_signatures_2604" : "JSX element type '{0}' does not have any construct or call signatures.", + "JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements_2605" : "JSX element type '{0}' is not a constructor function for JSX elements.", + "Property_0_of_JSX_spread_attribute_is_not_assignable_to_target_property_2606" : "Property '{0}' of JSX spread attribute is not assignable to target property.", + "JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property_2607" : "JSX element class does not support attributes because it does not have a '{0}' property.", + "The_global_type_JSX_0_may_not_have_more_than_one_property_2608" : "The global type 'JSX.{0}' may not have more than one property.", + "JSX_spread_child_must_be_an_array_type_2609" : "JSX spread child must be an array type.", + "Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity_2649" : "Cannot augment module '{0}' with value exports because it resolves to a non-module entity.", + "A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_memb_2651" : "A member initializer in a enum declaration cannot reference members declared after it, including members defined in other enums.", + "Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_d_2652" : "Merged declaration '{0}' cannot include a default export declaration. Consider adding a separate 'export default {0}' declaration instead.", + "Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1_2653" : "Non-abstract class expression does not implement inherited abstract member '{0}' from class '{1}'.", + "Exported_external_package_typings_file_cannot_contain_tripleslash_references_Please_contact_the_pack_2654" : "Exported external package typings file cannot contain tripleslash references. Please contact the package author to update the package definition.", + "Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_2656" : "Exported external package typings file '{0}' is not a module. Please contact the package author to update the package definition.", + "JSX_expressions_must_have_one_parent_element_2657" : "JSX expressions must have one parent element.", + "Type_0_provides_no_match_for_the_signature_1_2658" : "Type '{0}' provides no match for the signature '{1}'.", + "super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_highe_2659" : "'super' is only allowed in members of object literal expressions when option 'target' is 'ES2015' or higher.", + "super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions_2660" : "'super' can only be referenced in members of derived classes or object literal expressions.", + "Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module_2661" : "Cannot export '{0}'. Only local declarations can be exported from a module.", + "Cannot_find_name_0_Did_you_mean_the_static_member_1_0_2662" : "Cannot find name '{0}'. Did you mean the static member '{1}.{0}'?", + "Cannot_find_name_0_Did_you_mean_the_instance_member_this_0_2663" : "Cannot find name '{0}'. Did you mean the instance member 'this.{0}'?", + "Invalid_module_name_in_augmentation_module_0_cannot_be_found_2664" : "Invalid module name in augmentation, module '{0}' cannot be found.", + "Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augm_2665" : "Invalid module name in augmentation. Module '{0}' resolves to an untyped module at '{1}', which cannot be augmented.", + "Exports_and_export_assignments_are_not_permitted_in_module_augmentations_2666" : "Exports and export assignments are not permitted in module augmentations.", + "Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_mod_2667" : "Imports are not permitted in module augmentations. Consider moving them to the enclosing external module.", + "export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always__2668" : "'export' modifier cannot be applied to ambient modules and module augmentations since they are always visible.", + "Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_2669" : "Augmentations for the global scope can only be directly nested in external modules or ambient module declarations.", + "Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambien_2670" : "Augmentations for the global scope should have 'declare' modifier unless they appear in already ambient context.", + "Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity_2671" : "Cannot augment module '{0}' because it resolves to a non-module entity.", + "Cannot_assign_a_0_constructor_type_to_a_1_constructor_type_2672" : "Cannot assign a '{0}' constructor type to a '{1}' constructor type.", + "Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration_2673" : "Constructor of class '{0}' is private and only accessible within the class declaration.", + "Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration_2674" : "Constructor of class '{0}' is protected and only accessible within the class declaration.", + "Cannot_extend_a_class_0_Class_constructor_is_marked_as_private_2675" : "Cannot extend a class '{0}'. Class constructor is marked as private.", + "Accessors_must_both_be_abstract_or_non_abstract_2676" : "Accessors must both be abstract or non-abstract.", + "A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type_2677" : "A type predicate's type must be assignable to its parameter's type.", + "Type_0_is_not_comparable_to_type_1_2678" : "Type '{0}' is not comparable to type '{1}'.", + "A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void_2679" : "A function that is called with the 'new' keyword cannot have a 'this' type that is 'void'.", + "A_0_parameter_must_be_the_first_parameter_2680" : "A '{0}' parameter must be the first parameter.", + "A_constructor_cannot_have_a_this_parameter_2681" : "A constructor cannot have a 'this' parameter.", + "get_and_set_accessor_must_have_the_same_this_type_2682" : "'get' and 'set' accessor must have the same 'this' type.", + "this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_2683" : "'this' implicitly has type 'any' because it does not have a type annotation.", + "The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1_2684" : "The 'this' context of type '{0}' is not assignable to method's 'this' of type '{1}'.", + "The_this_types_of_each_signature_are_incompatible_2685" : "The 'this' types of each signature are incompatible.", + "_0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead_2686" : "'{0}' refers to a UMD global, but the current file is a module. Consider adding an import instead.", + "All_declarations_of_0_must_have_identical_modifiers_2687" : "All declarations of '{0}' must have identical modifiers.", + "Cannot_find_type_definition_file_for_0_2688" : "Cannot find type definition file for '{0}'.", + "Cannot_extend_an_interface_0_Did_you_mean_implements_2689" : "Cannot extend an interface '{0}'. Did you mean 'implements'?", + "An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead_2691" : "An import path cannot end with a '{0}' extension. Consider importing '{1}' instead.", + "_0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible_2692" : "'{0}' is a primitive, but '{1}' is a wrapper object. Prefer using '{0}' when possible.", + "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_2693" : "'{0}' only refers to a type, but is being used as a value here.", + "Namespace_0_has_no_exported_member_1_2694" : "Namespace '{0}' has no exported member '{1}'.", + "Left_side_of_comma_operator_is_unused_and_has_no_side_effects_2695" : "Left side of comma operator is unused and has no side effects.", + "The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead_2696" : "The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead?", + "An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_in_2697" : "An async function or method must return a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your `--lib` option.", + "Spread_types_may_only_be_created_from_object_types_2698" : "Spread types may only be created from object types.", + "Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1_2699" : "Static property '{0}' conflicts with built-in property 'Function.{0}' of constructor function '{1}'.", + "Rest_types_may_only_be_created_from_object_types_2700" : "Rest types may only be created from object types.", + "The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access_2701" : "The target of an object rest assignment must be a variable or a property access.", + "_0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here_2702" : "'{0}' only refers to a type, but is being used as a namespace here.", + "The_operand_of_a_delete_operator_must_be_a_property_reference_2703" : "The operand of a delete operator must be a property reference.", + "The_operand_of_a_delete_operator_cannot_be_a_read_only_property_2704" : "The operand of a delete operator cannot be a read-only property.", + "An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_de_2705" : "An async function or method in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your `--lib` option.", + "Required_type_parameters_may_not_follow_optional_type_parameters_2706" : "Required type parameters may not follow optional type parameters.", + "Generic_type_0_requires_between_1_and_2_type_arguments_2707" : "Generic type '{0}' requires between {1} and {2} type arguments.", + "Cannot_use_namespace_0_as_a_value_2708" : "Cannot use namespace '{0}' as a value.", + "Cannot_use_namespace_0_as_a_type_2709" : "Cannot use namespace '{0}' as a type.", + "_0_are_specified_twice_The_attribute_named_0_will_be_overwritten_2710" : "'{0}' are specified twice. The attribute named '{0}' will be overwritten.", + "A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES20_2711" : "A dynamic import call returns a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your `--lib` option.", + "A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declarat_2712" : "A dynamic import call in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your `--lib` option.", + "Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_p_2713" : "Cannot access '{0}.{1}' because '{0}' is a type, but not a namespace. Did you mean to retrieve the type of the property '{1}' in '{0}' with '{0}[\"{1}\"]'?", + "The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context_2714" : "The expression of an export assignment must be an identifier or qualified name in an ambient context.", + "Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor_2715" : "Abstract property '{0}' in class '{1}' cannot be accessed in the constructor.", + "Type_parameter_0_has_a_circular_default_2716" : "Type parameter '{0}' has a circular default.", + "Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_t_2717" : "Subsequent property declarations must have the same type. Property '{0}' must be of type '{1}', but here has type '{2}'.", + "Duplicate_declaration_0_2718" : "Duplicate declaration '{0}'.", + "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_2719" : "Type '{0}' is not assignable to type '{1}'. Two different types with this name exist, but they are unrelated.", + "Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclas_2720" : "Class '{0}' incorrectly implements class '{1}'. Did you mean to extend '{1}' and inherit its members as a subclass?", + "Cannot_invoke_an_object_which_is_possibly_null_2721" : "Cannot invoke an object which is possibly 'null'.", + "Cannot_invoke_an_object_which_is_possibly_undefined_2722" : "Cannot invoke an object which is possibly 'undefined'.", + "Cannot_invoke_an_object_which_is_possibly_null_or_undefined_2723" : "Cannot invoke an object which is possibly 'null' or 'undefined'.", + "Module_0_has_no_exported_member_1_Did_you_mean_2_2724" : "Module '{0}' has no exported member '{1}'. Did you mean '{2}'?", + "Import_declaration_0_is_using_private_name_1_4000" : "Import declaration '{0}' is using private name '{1}'.", + "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002" : "Type parameter '{0}' of exported class has or is using private name '{1}'.", + "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004" : "Type parameter '{0}' of exported interface has or is using private name '{1}'.", + "Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4006" : "Type parameter '{0}' of constructor signature from exported interface has or is using private name '{1}'.", + "Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4008" : "Type parameter '{0}' of call signature from exported interface has or is using private name '{1}'.", + "Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4010" : "Type parameter '{0}' of public static method from exported class has or is using private name '{1}'.", + "Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4012" : "Type parameter '{0}' of public method from exported class has or is using private name '{1}'.", + "Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4014" : "Type parameter '{0}' of method from exported interface has or is using private name '{1}'.", + "Type_parameter_0_of_exported_function_has_or_is_using_private_name_1_4016" : "Type parameter '{0}' of exported function has or is using private name '{1}'.", + "Implements_clause_of_exported_class_0_has_or_is_using_private_name_1_4019" : "Implements clause of exported class '{0}' has or is using private name '{1}'.", + "extends_clause_of_exported_class_0_has_or_is_using_private_name_1_4020" : "'extends' clause of exported class '{0}' has or is using private name '{1}'.", + "extends_clause_of_exported_interface_0_has_or_is_using_private_name_1_4022" : "'extends' clause of exported interface '{0}' has or is using private name '{1}'.", + "Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4023" : "Exported variable '{0}' has or is using name '{1}' from external module {2} but cannot be named.", + "Exported_variable_0_has_or_is_using_name_1_from_private_module_2_4024" : "Exported variable '{0}' has or is using name '{1}' from private module '{2}'.", + "Exported_variable_0_has_or_is_using_private_name_1_4025" : "Exported variable '{0}' has or is using private name '{1}'.", + "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot__4026" : "Public static property '{0}' of exported class has or is using name '{1}' from external module {2} but cannot be named.", + "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4027" : "Public static property '{0}' of exported class has or is using name '{1}' from private module '{2}'.", + "Public_static_property_0_of_exported_class_has_or_is_using_private_name_1_4028" : "Public static property '{0}' of exported class has or is using private name '{1}'.", + "Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_name_4029" : "Public property '{0}' of exported class has or is using name '{1}' from external module {2} but cannot be named.", + "Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4030" : "Public property '{0}' of exported class has or is using name '{1}' from private module '{2}'.", + "Public_property_0_of_exported_class_has_or_is_using_private_name_1_4031" : "Public property '{0}' of exported class has or is using private name '{1}'.", + "Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4032" : "Property '{0}' of exported interface has or is using name '{1}' from private module '{2}'.", + "Property_0_of_exported_interface_has_or_is_using_private_name_1_4033" : "Property '{0}' of exported interface has or is using private name '{1}'.", + "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_name_1_from_private_mod_4034" : "Parameter type of public static setter '{0}' from exported class has or is using name '{1}' from private module '{2}'.", + "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1_4035" : "Parameter type of public static setter '{0}' from exported class has or is using private name '{1}'.", + "Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2_4036" : "Parameter type of public setter '{0}' from exported class has or is using name '{1}' from private module '{2}'.", + "Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_private_name_1_4037" : "Parameter type of public setter '{0}' from exported class has or is using private name '{1}'.", + "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_external_modul_4038" : "Return type of public static getter '{0}' from exported class has or is using name '{1}' from external module {2} but cannot be named.", + "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_4039" : "Return type of public static getter '{0}' from exported class has or is using name '{1}' from private module '{2}'.", + "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_private_name_1_4040" : "Return type of public static getter '{0}' from exported class has or is using private name '{1}'.", + "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_4041" : "Return type of public getter '{0}' from exported class has or is using name '{1}' from external module {2} but cannot be named.", + "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2_4042" : "Return type of public getter '{0}' from exported class has or is using name '{1}' from private module '{2}'.", + "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_private_name_1_4043" : "Return type of public getter '{0}' from exported class has or is using private name '{1}'.", + "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_mod_4044" : "Return type of constructor signature from exported interface has or is using name '{0}' from private module '{1}'.", + "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0_4045" : "Return type of constructor signature from exported interface has or is using private name '{0}'.", + "Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4046" : "Return type of call signature from exported interface has or is using name '{0}' from private module '{1}'.", + "Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0_4047" : "Return type of call signature from exported interface has or is using private name '{0}'.", + "Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4048" : "Return type of index signature from exported interface has or is using name '{0}' from private module '{1}'.", + "Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0_4049" : "Return type of index signature from exported interface has or is using private name '{0}'.", + "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module__4050" : "Return type of public static method from exported class has or is using name '{0}' from external module {1} but cannot be named.", + "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4051" : "Return type of public static method from exported class has or is using name '{0}' from private module '{1}'.", + "Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0_4052" : "Return type of public static method from exported class has or is using private name '{0}'.", + "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_c_4053" : "Return type of public method from exported class has or is using name '{0}' from external module {1} but cannot be named.", + "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4054" : "Return type of public method from exported class has or is using name '{0}' from private module '{1}'.", + "Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0_4055" : "Return type of public method from exported class has or is using private name '{0}'.", + "Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4056" : "Return type of method from exported interface has or is using name '{0}' from private module '{1}'.", + "Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0_4057" : "Return type of method from exported interface has or is using private name '{0}'.", + "Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named_4058" : "Return type of exported function has or is using name '{0}' from external module {1} but cannot be named.", + "Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1_4059" : "Return type of exported function has or is using name '{0}' from private module '{1}'.", + "Return_type_of_exported_function_has_or_is_using_private_name_0_4060" : "Return type of exported function has or is using private name '{0}'.", + "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_can_4061" : "Parameter '{0}' of constructor from exported class has or is using name '{1}' from external module {2} but cannot be named.", + "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2_4062" : "Parameter '{0}' of constructor from exported class has or is using name '{1}' from private module '{2}'.", + "Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1_4063" : "Parameter '{0}' of constructor from exported class has or is using private name '{1}'.", + "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_mod_4064" : "Parameter '{0}' of constructor signature from exported interface has or is using name '{1}' from private module '{2}'.", + "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4065" : "Parameter '{0}' of constructor signature from exported interface has or is using private name '{1}'.", + "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4066" : "Parameter '{0}' of call signature from exported interface has or is using name '{1}' from private module '{2}'.", + "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4067" : "Parameter '{0}' of call signature from exported interface has or is using private name '{1}'.", + "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module__4068" : "Parameter '{0}' of public static method from exported class has or is using name '{1}' from external module {2} but cannot be named.", + "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4069" : "Parameter '{0}' of public static method from exported class has or is using name '{1}' from private module '{2}'.", + "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4070" : "Parameter '{0}' of public static method from exported class has or is using private name '{1}'.", + "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_c_4071" : "Parameter '{0}' of public method from exported class has or is using name '{1}' from external module {2} but cannot be named.", + "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4072" : "Parameter '{0}' of public method from exported class has or is using name '{1}' from private module '{2}'.", + "Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4073" : "Parameter '{0}' of public method from exported class has or is using private name '{1}'.", + "Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4074" : "Parameter '{0}' of method from exported interface has or is using name '{1}' from private module '{2}'.", + "Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4075" : "Parameter '{0}' of method from exported interface has or is using private name '{1}'.", + "Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4076" : "Parameter '{0}' of exported function has or is using name '{1}' from external module {2} but cannot be named.", + "Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2_4077" : "Parameter '{0}' of exported function has or is using name '{1}' from private module '{2}'.", + "Parameter_0_of_exported_function_has_or_is_using_private_name_1_4078" : "Parameter '{0}' of exported function has or is using private name '{1}'.", + "Exported_type_alias_0_has_or_is_using_private_name_1_4081" : "Exported type alias '{0}' has or is using private name '{1}'.", + "Default_export_of_the_module_has_or_is_using_private_name_0_4082" : "Default export of the module has or is using private name '{0}'.", + "Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1_4083" : "Type parameter '{0}' of exported type alias has or is using private name '{1}'.", + "Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_librar_4090" : "Conflicting definitions for '{0}' found at '{1}' and '{2}'. Consider installing a specific version of this library to resolve the conflict.", + "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4091" : "Parameter '{0}' of index signature from exported interface has or is using name '{1}' from private module '{2}'.", + "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1_4092" : "Parameter '{0}' of index signature from exported interface has or is using private name '{1}'.", + "Property_0_of_exported_class_expression_may_not_be_private_or_protected_4094" : "Property '{0}' of exported class expression may not be private or protected.", + "Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_4095" : "Public static method '{0}' of exported class has or is using name '{1}' from external module {2} but cannot be named.", + "Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4096" : "Public static method '{0}' of exported class has or is using name '{1}' from private module '{2}'.", + "Public_static_method_0_of_exported_class_has_or_is_using_private_name_1_4097" : "Public static method '{0}' of exported class has or is using private name '{1}'.", + "Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4098" : "Public method '{0}' of exported class has or is using name '{1}' from external module {2} but cannot be named.", + "Public_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4099" : "Public method '{0}' of exported class has or is using name '{1}' from private module '{2}'.", + "Public_method_0_of_exported_class_has_or_is_using_private_name_1_4100" : "Public method '{0}' of exported class has or is using private name '{1}'.", + "Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4101" : "Method '{0}' of exported interface has or is using name '{1}' from private module '{2}'.", + "Method_0_of_exported_interface_has_or_is_using_private_name_1_4102" : "Method '{0}' of exported interface has or is using private name '{1}'.", + "The_current_host_does_not_support_the_0_option_5001" : "The current host does not support the '{0}' option.", + "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009" : "Cannot find the common subdirectory path for the input files.", + "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010" : "File specification cannot end in a recursive directory wildcard ('**'): '{0}'.", + "Cannot_read_file_0_Colon_1_5012" : "Cannot read file '{0}': {1}.", + "Failed_to_parse_file_0_Colon_1_5014" : "Failed to parse file '{0}': {1}.", + "Unknown_compiler_option_0_5023" : "Unknown compiler option '{0}'.", + "Compiler_option_0_requires_a_value_of_type_1_5024" : "Compiler option '{0}' requires a value of type {1}.", + "Could_not_write_file_0_Colon_1_5033" : "Could not write file '{0}': {1}.", + "Option_project_cannot_be_mixed_with_source_files_on_a_command_line_5042" : "Option 'project' cannot be mixed with source files on a command line.", + "Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES_5047" : "Option 'isolatedModules' can only be used when either option '--module' is provided or option 'target' is 'ES2015' or higher.", + "Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided_5051" : "Option '{0} can only be used when either option '--inlineSourceMap' or option '--sourceMap' is provided.", + "Option_0_cannot_be_specified_without_specifying_option_1_5052" : "Option '{0}' cannot be specified without specifying option '{1}'.", + "Option_0_cannot_be_specified_with_option_1_5053" : "Option '{0}' cannot be specified with option '{1}'.", + "A_tsconfig_json_file_is_already_defined_at_Colon_0_5054" : "A 'tsconfig.json' file is already defined at: '{0}'.", + "Cannot_write_file_0_because_it_would_overwrite_input_file_5055" : "Cannot write file '{0}' because it would overwrite input file.", + "Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files_5056" : "Cannot write file '{0}' because it would be overwritten by multiple input files.", + "Cannot_find_a_tsconfig_json_file_at_the_specified_directory_Colon_0_5057" : "Cannot find a tsconfig.json file at the specified directory: '{0}'.", + "The_specified_path_does_not_exist_Colon_0_5058" : "The specified path does not exist: '{0}'.", + "Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier_5059" : "Invalid value for '--reactNamespace'. '{0}' is not a valid identifier.", + "Option_paths_cannot_be_used_without_specifying_baseUrl_option_5060" : "Option 'paths' cannot be used without specifying '--baseUrl' option.", + "Pattern_0_can_have_at_most_one_Asterisk_character_5061" : "Pattern '{0}' can have at most one '*' character.", + "Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character_5062" : "Substitution '{0}' in pattern '{1}' in can have at most one '*' character.", + "Substitutions_for_pattern_0_should_be_an_array_5063" : "Substitutions for pattern '{0}' should be an array.", + "Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2_5064" : "Substitution '{0}' for pattern '{1}' has incorrect type, expected 'string', got '{2}'.", + "File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildca_5065" : "File specification cannot contain a parent directory ('..') that appears after a recursive directory wildcard ('**'): '{0}'.", + "Substitutions_for_pattern_0_shouldn_t_be_an_empty_array_5066" : "Substitutions for pattern '{0}' shouldn't be an empty array.", + "Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name_5067" : "Invalid value for 'jsxFactory'. '{0}' is not a valid identifier or qualified-name.", + "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068" : "Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig.", + "Option_0_cannot_be_specified_without_specifying_option_1_or_option_2_5069" : "Option '{0}' cannot be specified without specifying option '{1}' or option '{2}'.", + "Generates_a_sourcemap_for_each_corresponding_d_ts_file_6000" : "Generates a sourcemap for each corresponding '.d.ts' file.", + "Concatenate_and_emit_output_to_single_file_6001" : "Concatenate and emit output to single file.", + "Generates_corresponding_d_ts_file_6002" : "Generates corresponding '.d.ts' file.", + "Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations_6003" : "Specify the location where debugger should locate map files instead of generated locations.", + "Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations_6004" : "Specify the location where debugger should locate TypeScript files instead of source locations.", + "Watch_input_files_6005" : "Watch input files.", + "Redirect_output_structure_to_the_directory_6006" : "Redirect output structure to the directory.", + "Do_not_erase_const_enum_declarations_in_generated_code_6007" : "Do not erase const enum declarations in generated code.", + "Do_not_emit_outputs_if_any_errors_were_reported_6008" : "Do not emit outputs if any errors were reported.", + "Do_not_emit_comments_to_output_6009" : "Do not emit comments to output.", + "Do_not_emit_outputs_6010" : "Do not emit outputs.", + "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011" : "Allow default imports from modules with no default export. This does not affect code emit, just typechecking.", + "Skip_type_checking_of_declaration_files_6012" : "Skip type checking of declaration files.", + "Do_not_resolve_the_real_path_of_symlinks_6013" : "Do not resolve the real path of symlinks.", + "Only_emit_d_ts_declaration_files_6014" : "Only emit '.d.ts' declaration files.", + "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_or_ESNEXT_6015" : "Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'.", + "Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext_6016" : "Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'.", + "Print_this_message_6017" : "Print this message.", + "Print_the_compiler_s_version_6019" : "Print the compiler's version.", + "Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json_6020" : "Compile the project given the path to its configuration file, or to a folder with a 'tsconfig.json'.", + "Syntax_Colon_0_6023" : "Syntax: {0}", + "options_6024" : "options", + "file_6025" : "file", + "Examples_Colon_0_6026" : "Examples: {0}", + "Options_Colon_6027" : "Options:", + "Version_0_6029" : "Version {0}", + "Insert_command_line_options_and_files_from_a_file_6030" : "Insert command line options and files from a file.", + "Starting_compilation_in_watch_mode_6031" : "Starting compilation in watch mode...", + "File_change_detected_Starting_incremental_compilation_6032" : "File change detected. Starting incremental compilation...", + "KIND_6034" : "KIND", + "FILE_6035" : "FILE", + "VERSION_6036" : "VERSION", + "LOCATION_6037" : "LOCATION", + "DIRECTORY_6038" : "DIRECTORY", + "STRATEGY_6039" : "STRATEGY", + "FILE_OR_DIRECTORY_6040" : "FILE OR DIRECTORY", + "Generates_corresponding_map_file_6043" : "Generates corresponding '.map' file.", + "Compiler_option_0_expects_an_argument_6044" : "Compiler option '{0}' expects an argument.", + "Unterminated_quoted_string_in_response_file_0_6045" : "Unterminated quoted string in response file '{0}'.", + "Argument_for_0_option_must_be_Colon_1_6046" : "Argument for '{0}' option must be: {1}.", + "Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1_6048" : "Locale must be of the form or -. For example '{0}' or '{1}'.", + "Unsupported_locale_0_6049" : "Unsupported locale '{0}'.", + "Unable_to_open_file_0_6050" : "Unable to open file '{0}'.", + "Corrupted_locale_file_0_6051" : "Corrupted locale file {0}.", + "Raise_error_on_expressions_and_declarations_with_an_implied_any_type_6052" : "Raise error on expressions and declarations with an implied 'any' type.", + "File_0_not_found_6053" : "File '{0}' not found.", + "File_0_has_unsupported_extension_The_only_supported_extensions_are_1_6054" : "File '{0}' has unsupported extension. The only supported extensions are {1}.", + "Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures_6055" : "Suppress noImplicitAny errors for indexing objects lacking index signatures.", + "Do_not_emit_declarations_for_code_that_has_an_internal_annotation_6056" : "Do not emit declarations for code that has an '@internal' annotation.", + "Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir_6058" : "Specify the root directory of input files. Use to control the output directory structure with --outDir.", + "File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files_6059" : "File '{0}' is not under 'rootDir' '{1}'. 'rootDir' is expected to contain all source files.", + "Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix_6060" : "Specify the end of line sequence to be used when emitting files: 'CRLF' (dos) or 'LF' (unix).", + "NEWLINE_6061" : "NEWLINE", + "Option_0_can_only_be_specified_in_tsconfig_json_file_6064" : "Option '{0}' can only be specified in 'tsconfig.json' file.", + "Enables_experimental_support_for_ES7_decorators_6065" : "Enables experimental support for ES7 decorators.", + "Enables_experimental_support_for_emitting_type_metadata_for_decorators_6066" : "Enables experimental support for emitting type metadata for decorators.", + "Enables_experimental_support_for_ES7_async_functions_6068" : "Enables experimental support for ES7 async functions.", + "Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6_6069" : "Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6).", + "Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file_6070" : "Initializes a TypeScript project and creates a tsconfig.json file.", + "Successfully_created_a_tsconfig_json_file_6071" : "Successfully created a tsconfig.json file.", + "Suppress_excess_property_checks_for_object_literals_6072" : "Suppress excess property checks for object literals.", + "Stylize_errors_and_messages_using_color_and_context_experimental_6073" : "Stylize errors and messages using color and context (experimental).", + "Do_not_report_errors_on_unused_labels_6074" : "Do not report errors on unused labels.", + "Report_error_when_not_all_code_paths_in_function_return_a_value_6075" : "Report error when not all code paths in function return a value.", + "Report_errors_for_fallthrough_cases_in_switch_statement_6076" : "Report errors for fallthrough cases in switch statement.", + "Do_not_report_errors_on_unreachable_code_6077" : "Do not report errors on unreachable code.", + "Disallow_inconsistently_cased_references_to_the_same_file_6078" : "Disallow inconsistently-cased references to the same file.", + "Specify_library_files_to_be_included_in_the_compilation_6079" : "Specify library files to be included in the compilation.", + "Specify_JSX_code_generation_Colon_preserve_react_native_or_react_6080" : "Specify JSX code generation: 'preserve', 'react-native', or 'react'.", + "File_0_has_an_unsupported_extension_so_skipping_it_6081" : "File '{0}' has an unsupported extension, so skipping it.", + "Only_amd_and_system_modules_are_supported_alongside_0_6082" : "Only 'amd' and 'system' modules are supported alongside --{0}.", + "Base_directory_to_resolve_non_absolute_module_names_6083" : "Base directory to resolve non-absolute module names.", + "Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react__6084" : "[Deprecated] Use '--jsxFactory' instead. Specify the object invoked for createElement when targeting 'react' JSX emit", + "Enable_tracing_of_the_name_resolution_process_6085" : "Enable tracing of the name resolution process.", + "Resolving_module_0_from_1_6086" : "======== Resolving module '{0}' from '{1}'. ========", + "Explicitly_specified_module_resolution_kind_Colon_0_6087" : "Explicitly specified module resolution kind: '{0}'.", + "Module_resolution_kind_is_not_specified_using_0_6088" : "Module resolution kind is not specified, using '{0}'.", + "Module_name_0_was_successfully_resolved_to_1_6089" : "======== Module name '{0}' was successfully resolved to '{1}'. ========", + "Module_name_0_was_not_resolved_6090" : "======== Module name '{0}' was not resolved. ========", + "paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0_6091" : "'paths' option is specified, looking for a pattern to match module name '{0}'.", + "Module_name_0_matched_pattern_1_6092" : "Module name '{0}', matched pattern '{1}'.", + "Trying_substitution_0_candidate_module_location_Colon_1_6093" : "Trying substitution '{0}', candidate module location: '{1}'.", + "Resolving_module_name_0_relative_to_base_url_1_2_6094" : "Resolving module name '{0}' relative to base url '{1}' - '{2}'.", + "Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1_6095" : "Loading module as file / folder, candidate module location '{0}', target file type '{1}'.", + "File_0_does_not_exist_6096" : "File '{0}' does not exist.", + "File_0_exist_use_it_as_a_name_resolution_result_6097" : "File '{0}' exist - use it as a name resolution result.", + "Loading_module_0_from_node_modules_folder_target_file_type_1_6098" : "Loading module '{0}' from 'node_modules' folder, target file type '{1}'.", + "Found_package_json_at_0_6099" : "Found 'package.json' at '{0}'.", + "package_json_does_not_have_a_0_field_6100" : "'package.json' does not have a '{0}' field.", + "package_json_has_0_field_1_that_references_2_6101" : "'package.json' has '{0}' field '{1}' that references '{2}'.", + "Allow_javascript_files_to_be_compiled_6102" : "Allow javascript files to be compiled.", + "Option_0_should_have_array_of_strings_as_a_value_6103" : "Option '{0}' should have array of strings as a value.", + "Checking_if_0_is_the_longest_matching_prefix_for_1_2_6104" : "Checking if '{0}' is the longest matching prefix for '{1}' - '{2}'.", + "Expected_type_of_0_field_in_package_json_to_be_string_got_1_6105" : "Expected type of '{0}' field in 'package.json' to be 'string', got '{1}'.", + "baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1_6106" : "'baseUrl' option is set to '{0}', using this value to resolve non-relative module name '{1}'.", + "rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107" : "'rootDirs' option is set, using it to resolve relative module name '{0}'.", + "Longest_matching_prefix_for_0_is_1_6108" : "Longest matching prefix for '{0}' is '{1}'.", + "Loading_0_from_the_root_dir_1_candidate_location_2_6109" : "Loading '{0}' from the root dir '{1}', candidate location '{2}'.", + "Trying_other_entries_in_rootDirs_6110" : "Trying other entries in 'rootDirs'.", + "Module_resolution_using_rootDirs_has_failed_6111" : "Module resolution using 'rootDirs' has failed.", + "Do_not_emit_use_strict_directives_in_module_output_6112" : "Do not emit 'use strict' directives in module output.", + "Enable_strict_null_checks_6113" : "Enable strict null checks.", + "Unknown_option_excludes_Did_you_mean_exclude_6114" : "Unknown option 'excludes'. Did you mean 'exclude'?", + "Raise_error_on_this_expressions_with_an_implied_any_type_6115" : "Raise error on 'this' expressions with an implied 'any' type.", + "Resolving_type_reference_directive_0_containing_file_1_root_directory_2_6116" : "======== Resolving type reference directive '{0}', containing file '{1}', root directory '{2}'. ========", + "Resolving_using_primary_search_paths_6117" : "Resolving using primary search paths...", + "Resolving_from_node_modules_folder_6118" : "Resolving from node_modules folder...", + "Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2_6119" : "======== Type reference directive '{0}' was successfully resolved to '{1}', primary: {2}. ========", + "Type_reference_directive_0_was_not_resolved_6120" : "======== Type reference directive '{0}' was not resolved. ========", + "Resolving_with_primary_search_path_0_6121" : "Resolving with primary search path '{0}'.", + "Root_directory_cannot_be_determined_skipping_primary_search_paths_6122" : "Root directory cannot be determined, skipping primary search paths.", + "Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set_6123" : "======== Resolving type reference directive '{0}', containing file '{1}', root directory not set. ========", + "Type_declaration_files_to_be_included_in_compilation_6124" : "Type declaration files to be included in compilation.", + "Looking_up_in_node_modules_folder_initial_location_0_6125" : "Looking up in 'node_modules' folder, initial location '{0}'.", + "Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126" : "Containing file is not specified and root directory cannot be determined, skipping lookup in 'node_modules' folder.", + "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1_6127" : "======== Resolving type reference directive '{0}', containing file not set, root directory '{1}'. ========", + "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set_6128" : "======== Resolving type reference directive '{0}', containing file not set, root directory not set. ========", + "Resolving_real_path_for_0_result_1_6130" : "Resolving real path for '{0}', result '{1}'.", + "Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system_6131" : "Cannot compile modules using option '{0}' unless the '--module' flag is 'amd' or 'system'.", + "File_name_0_has_a_1_extension_stripping_it_6132" : "File name '{0}' has a '{1}' extension - stripping it.", + "_0_is_declared_but_its_value_is_never_read_6133" : "'{0}' is declared but its value is never read.", + "Report_errors_on_unused_locals_6134" : "Report errors on unused locals.", + "Report_errors_on_unused_parameters_6135" : "Report errors on unused parameters.", + "The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files_6136" : "The maximum dependency depth to search under node_modules and load JavaScript files.", + "Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1_6137" : "Cannot import type declaration files. Consider importing '{0}' instead of '{1}'.", + "Property_0_is_declared_but_its_value_is_never_read_6138" : "Property '{0}' is declared but its value is never read.", + "Import_emit_helpers_from_tslib_6139" : "Import emit helpers from 'tslib'.", + "Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using__6140" : "Auto discovery for typings is enabled in project '{0}'. Running extra resolution pass for module '{1}' using cache location '{2}'.", + "Parse_in_strict_mode_and_emit_use_strict_for_each_source_file_6141" : "Parse in strict mode and emit \"use strict\" for each source file.", + "Module_0_was_resolved_to_1_but_jsx_is_not_set_6142" : "Module '{0}' was resolved to '{1}', but '--jsx' is not set.", + "Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1_6144" : "Module '{0}' was resolved as locally declared ambient module in file '{1}'.", + "Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified_6145" : "Module '{0}' was resolved as ambient module declared in '{1}' since this file was not modified.", + "Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h_6146" : "Specify the JSX factory function to use when targeting 'react' JSX emit, e.g. 'React.createElement' or 'h'.", + "Resolution_for_module_0_was_found_in_cache_from_location_1_6147" : "Resolution for module '{0}' was found in cache from location '{1}'.", + "Directory_0_does_not_exist_skipping_all_lookups_in_it_6148" : "Directory '{0}' does not exist, skipping all lookups in it.", + "Show_diagnostic_information_6149" : "Show diagnostic information.", + "Show_verbose_diagnostic_information_6150" : "Show verbose diagnostic information.", + "Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file_6151" : "Emit a single file with source maps instead of having a separate file.", + "Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap__6152" : "Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set.", + "Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule_6153" : "Transpile each file as a separate module (similar to 'ts.transpileModule').", + "Print_names_of_generated_files_part_of_the_compilation_6154" : "Print names of generated files part of the compilation.", + "Print_names_of_files_part_of_the_compilation_6155" : "Print names of files part of the compilation.", + "The_locale_used_when_displaying_messages_to_the_user_e_g_en_us_6156" : "The locale used when displaying messages to the user (e.g. 'en-us')", + "Do_not_generate_custom_helper_functions_like_extends_in_compiled_output_6157" : "Do not generate custom helper functions like '__extends' in compiled output.", + "Do_not_include_the_default_library_file_lib_d_ts_6158" : "Do not include the default library file (lib.d.ts).", + "Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files_6159" : "Do not add triple-slash references or imported modules to the list of compiled files.", + "Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files_6160" : "[Deprecated] Use '--skipLibCheck' instead. Skip type checking of default library declaration files.", + "List_of_folders_to_include_type_definitions_from_6161" : "List of folders to include type definitions from.", + "Disable_size_limitations_on_JavaScript_projects_6162" : "Disable size limitations on JavaScript projects.", + "The_character_set_of_the_input_files_6163" : "The character set of the input files.", + "Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files_6164" : "Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files.", + "Do_not_truncate_error_messages_6165" : "Do not truncate error messages.", + "Output_directory_for_generated_declaration_files_6166" : "Output directory for generated declaration files.", + "A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl_6167" : "A series of entries which re-map imports to lookup locations relative to the 'baseUrl'.", + "List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime_6168" : "List of root folders whose combined content represents the structure of the project at runtime.", + "Show_all_compiler_options_6169" : "Show all compiler options.", + "Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file_6170" : "[Deprecated] Use '--outFile' instead. Concatenate and emit output to single file", + "Command_line_Options_6171" : "Command-line Options", + "Basic_Options_6172" : "Basic Options", + "Strict_Type_Checking_Options_6173" : "Strict Type-Checking Options", + "Module_Resolution_Options_6174" : "Module Resolution Options", + "Source_Map_Options_6175" : "Source Map Options", + "Additional_Checks_6176" : "Additional Checks", + "Experimental_Options_6177" : "Experimental Options", + "Advanced_Options_6178" : "Advanced Options", + "Provide_full_support_for_iterables_in_for_of_spread_and_destructuring_when_targeting_ES5_or_ES3_6179" : "Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'.", + "Enable_all_strict_type_checking_options_6180" : "Enable all strict type-checking options.", + "List_of_language_service_plugins_6181" : "List of language service plugins.", + "Scoped_package_detected_looking_in_0_6182" : "Scoped package detected, looking in '{0}'", + "Reusing_resolution_of_module_0_to_file_1_from_old_program_6183" : "Reusing resolution of module '{0}' to file '{1}' from old program.", + "Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program_6184" : "Reusing module resolutions originating in '{0}' since resolutions are unchanged from old program.", + "Disable_strict_checking_of_generic_signatures_in_function_types_6185" : "Disable strict checking of generic signatures in function types.", + "Enable_strict_checking_of_function_types_6186" : "Enable strict checking of function types.", + "Enable_strict_checking_of_property_initialization_in_classes_6187" : "Enable strict checking of property initialization in classes.", + "Numeric_separators_are_not_allowed_here_6188" : "Numeric separators are not allowed here.", + "Multiple_consecutive_numeric_separators_are_not_permitted_6189" : "Multiple consecutive numeric separators are not permitted.", + "Found_package_json_at_0_Package_ID_is_1_6190" : "Found 'package.json' at '{0}'. Package ID is '{1}'.", + "Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen_6191" : "Whether to keep outdated console output in watch mode instead of clearing the screen.", + "All_imports_in_import_declaration_are_unused_6192" : "All imports in import declaration are unused.", + "Found_1_error_Watching_for_file_changes_6193" : "Found 1 error. Watching for file changes.", + "Found_0_errors_Watching_for_file_changes_6194" : "Found {0} errors. Watching for file changes.", + "Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols_6195" : "Resolve 'keyof' to string valued property names only (no numbers or symbols).", + "_0_is_declared_but_never_used_6196" : "'{0}' is declared but never used.", + "Variable_0_implicitly_has_an_1_type_7005" : "Variable '{0}' implicitly has an '{1}' type.", + "Parameter_0_implicitly_has_an_1_type_7006" : "Parameter '{0}' implicitly has an '{1}' type.", + "Member_0_implicitly_has_an_1_type_7008" : "Member '{0}' implicitly has an '{1}' type.", + "new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type_7009" : "'new' expression, whose target lacks a construct signature, implicitly has an 'any' type.", + "_0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type_7010" : "'{0}', which lacks return-type annotation, implicitly has an '{1}' return type.", + "Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type_7011" : "Function expression, which lacks return-type annotation, implicitly has an '{0}' return type.", + "Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7013" : "Construct signature, which lacks return-type annotation, implicitly has an 'any' return type.", + "Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015" : "Element implicitly has an 'any' type because index expression is not of type 'number'.", + "Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type_7016" : "Could not find a declaration file for module '{0}'. '{1}' implicitly has an 'any' type.", + "Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature_7017" : "Element implicitly has an 'any' type because type '{0}' has no index signature.", + "Object_literal_s_property_0_implicitly_has_an_1_type_7018" : "Object literal's property '{0}' implicitly has an '{1}' type.", + "Rest_parameter_0_implicitly_has_an_any_type_7019" : "Rest parameter '{0}' implicitly has an 'any[]' type.", + "Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7020" : "Call signature, which lacks return-type annotation, implicitly has an 'any' return type.", + "_0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or__7022" : "'{0}' implicitly has type 'any' because it does not have a type annotation and is referenced directly or indirectly in its own initializer.", + "_0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_reference_7023" : "'{0}' implicitly has return type 'any' because it does not have a return type annotation and is referenced directly or indirectly in one of its return expressions.", + "Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_ref_7024" : "Function implicitly has return type 'any' because it does not have a return type annotation and is referenced directly or indirectly in one of its return expressions.", + "Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_typ_7025" : "Generator implicitly has type '{0}' because it does not yield any values. Consider supplying a return type.", + "JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists_7026" : "JSX element implicitly has type 'any' because no interface 'JSX.{0}' exists.", + "Unreachable_code_detected_7027" : "Unreachable code detected.", + "Unused_label_7028" : "Unused label.", + "Fallthrough_case_in_switch_7029" : "Fallthrough case in switch.", + "Not_all_code_paths_return_a_value_7030" : "Not all code paths return a value.", + "Binding_element_0_implicitly_has_an_1_type_7031" : "Binding element '{0}' implicitly has an '{1}' type.", + "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032" : "Property '{0}' implicitly has type 'any', because its set accessor lacks a parameter type annotation.", + "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033" : "Property '{0}' implicitly has type 'any', because its get accessor lacks a return type annotation.", + "Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined_7034" : "Variable '{0}' implicitly has type '{1}' in some locations where its type cannot be determined.", + "Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_mod_7035" : "Try `npm install @types/{0}` if it exists or add a new declaration (.d.ts) file containing `declare module '{0}';`", + "Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036" : "Dynamic import's specifier must be of type 'string', but here has type '{0}'.", + "Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for__7037" : "Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'.", + "A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_7038" : "A namespace-style import cannot be called or constructed, and will cause a failure at runtime.", + "Mapped_object_type_implicitly_has_an_any_template_type_7039" : "Mapped object type implicitly has an 'any' template type.", + "You_cannot_rename_this_element_8000" : "You cannot rename this element.", + "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001" : "You cannot rename elements that are defined in the standard TypeScript library.", + "import_can_only_be_used_in_a_ts_file_8002" : "'import ... =' can only be used in a .ts file.", + "export_can_only_be_used_in_a_ts_file_8003" : "'export=' can only be used in a .ts file.", + "type_parameter_declarations_can_only_be_used_in_a_ts_file_8004" : "'type parameter declarations' can only be used in a .ts file.", + "implements_clauses_can_only_be_used_in_a_ts_file_8005" : "'implements clauses' can only be used in a .ts file.", + "interface_declarations_can_only_be_used_in_a_ts_file_8006" : "'interface declarations' can only be used in a .ts file.", + "module_declarations_can_only_be_used_in_a_ts_file_8007" : "'module declarations' can only be used in a .ts file.", + "type_aliases_can_only_be_used_in_a_ts_file_8008" : "'type aliases' can only be used in a .ts file.", + "_0_can_only_be_used_in_a_ts_file_8009" : "'{0}' can only be used in a .ts file.", + "types_can_only_be_used_in_a_ts_file_8010" : "'types' can only be used in a .ts file.", + "type_arguments_can_only_be_used_in_a_ts_file_8011" : "'type arguments' can only be used in a .ts file.", + "parameter_modifiers_can_only_be_used_in_a_ts_file_8012" : "'parameter modifiers' can only be used in a .ts file.", + "non_null_assertions_can_only_be_used_in_a_ts_file_8013" : "'non-null assertions' can only be used in a .ts file.", + "enum_declarations_can_only_be_used_in_a_ts_file_8015" : "'enum declarations' can only be used in a .ts file.", + "type_assertion_expressions_can_only_be_used_in_a_ts_file_8016" : "'type assertion expressions' can only be used in a .ts file.", + "Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0_8017" : "Octal literal types must use ES2015 syntax. Use the syntax '{0}'.", + "Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0_8018" : "Octal literals are not allowed in enums members initializer. Use the syntax '{0}'.", + "Report_errors_in_js_files_8019" : "Report errors in .js files.", + "JSDoc_types_can_only_be_used_inside_documentation_comments_8020" : "JSDoc types can only be used inside documentation comments.", + "JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags_8021" : "JSDoc '@typedef' tag should either have a type annotation or be followed by '@property' or '@member' tags.", + "JSDoc_0_is_not_attached_to_a_class_8022" : "JSDoc '@{0}' is not attached to a class.", + "JSDoc_0_1_does_not_match_the_extends_2_clause_8023" : "JSDoc '@{0} {1}' does not match the 'extends {2}' clause.", + "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_8024" : "JSDoc '@param' tag has name '{0}', but there is no parameter with that name.", + "Class_declarations_cannot_have_more_than_one_augments_or_extends_tag_8025" : "Class declarations cannot have more than one `@augments` or `@extends` tag.", + "Expected_0_type_arguments_provide_these_with_an_extends_tag_8026" : "Expected {0} type arguments; provide these with an '@extends' tag.", + "Expected_0_1_type_arguments_provide_these_with_an_extends_tag_8027" : "Expected {0}-{1} type arguments; provide these with an '@extends' tag.", + "JSDoc_may_only_appear_in_the_last_parameter_of_a_signature_8028" : "JSDoc '...' may only appear in the last parameter of a signature.", + "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_h_8029" : "JSDoc '@param' tag has name '{0}', but there is no parameter with that name. It would match 'arguments' if it had an array type.", + "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002" : "Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clause.", + "class_expressions_are_not_currently_supported_9003" : "'class' expressions are not currently supported.", + "Language_service_is_disabled_9004" : "Language service is disabled.", + "JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000" : "JSX attributes must only be assigned a non-empty 'expression'.", + "JSX_elements_cannot_have_multiple_attributes_with_the_same_name_17001" : "JSX elements cannot have multiple attributes with the same name.", + "Expected_corresponding_JSX_closing_tag_for_0_17002" : "Expected corresponding JSX closing tag for '{0}'.", + "JSX_attribute_expected_17003" : "JSX attribute expected.", + "Cannot_use_JSX_unless_the_jsx_flag_is_provided_17004" : "Cannot use JSX unless the '--jsx' flag is provided.", + "A_constructor_cannot_contain_a_super_call_when_its_class_extends_null_17005" : "A constructor cannot contain a 'super' call when its class extends 'null'.", + "An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_ex_17006" : "An unary expression with the '{0}' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses.", + "A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Con_17007" : "A type assertion expression is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses.", + "JSX_element_0_has_no_corresponding_closing_tag_17008" : "JSX element '{0}' has no corresponding closing tag.", + "super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class_17009" : "'super' must be called before accessing 'this' in the constructor of a derived class.", + "Unknown_type_acquisition_option_0_17010" : "Unknown type acquisition option '{0}'.", + "super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class_17011" : "'super' must be called before accessing a property of 'super' in the constructor of a derived class.", + "_0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2_17012" : "'{0}' is not a valid meta-property for keyword '{1}'. Did you mean '{2}'?", + "Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constru_17013" : "Meta-property '{0}' is only allowed in the body of a function declaration, function expression, or constructor.", + "JSX_fragment_has_no_corresponding_closing_tag_17014" : "JSX fragment has no corresponding closing tag.", + "Expected_corresponding_closing_tag_for_JSX_fragment_17015" : "Expected corresponding closing tag for JSX fragment.", + "JSX_fragment_is_not_supported_when_using_jsxFactory_17016" : "JSX fragment is not supported when using --jsxFactory", + "JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma_17017" : "JSX fragment is not supported when using an inline JSX factory pragma", + "Circularity_detected_while_resolving_configuration_Colon_0_18000" : "Circularity detected while resolving configuration: {0}", + "A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not_18001" : "A path in an 'extends' option must be relative or rooted, but '{0}' is not.", + "The_files_list_in_config_file_0_is_empty_18002" : "The 'files' list in config file '{0}' is empty.", + "No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2_18003" : "No inputs were found in config file '{0}'. Specified 'include' paths were '{1}' and 'exclude' paths were '{2}'.", + "File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module_80001" : "File is a CommonJS module; it may be converted to an ES6 module.", + "This_constructor_function_may_be_converted_to_a_class_declaration_80002" : "This constructor function may be converted to a class declaration.", + "Import_may_be_converted_to_a_default_import_80003" : "Import may be converted to a default import.", + "JSDoc_types_may_be_moved_to_TypeScript_types_80004" : "JSDoc types may be moved to TypeScript types.", + "require_call_may_be_converted_to_an_import_80005" : "'require' call may be converted to an import.", + "Add_missing_super_call_90001" : "Add missing 'super()' call", + "Make_super_call_the_first_statement_in_the_constructor_90002" : "Make 'super()' call the first statement in the constructor", + "Change_extends_to_implements_90003" : "Change 'extends' to 'implements'", + "Remove_declaration_for_Colon_0_90004" : "Remove declaration for: '{0}'", + "Remove_import_from_0_90005" : "Remove import from '{0}'", + "Implement_interface_0_90006" : "Implement interface '{0}'", + "Implement_inherited_abstract_class_90007" : "Implement inherited abstract class", + "Add_0_to_unresolved_variable_90008" : "Add '{0}.' to unresolved variable", + "Import_0_from_module_1_90013" : "Import '{0}' from module \"{1}\"", + "Change_0_to_1_90014" : "Change '{0}' to '{1}'", + "Add_0_to_existing_import_declaration_from_1_90015" : "Add '{0}' to existing import declaration from \"{1}\"", + "Declare_property_0_90016" : "Declare property '{0}'", + "Add_index_signature_for_property_0_90017" : "Add index signature for property '{0}'", + "Disable_checking_for_this_file_90018" : "Disable checking for this file", + "Ignore_this_error_message_90019" : "Ignore this error message", + "Initialize_property_0_in_the_constructor_90020" : "Initialize property '{0}' in the constructor", + "Initialize_static_property_0_90021" : "Initialize static property '{0}'", + "Change_spelling_to_0_90022" : "Change spelling to '{0}'", + "Declare_method_0_90023" : "Declare method '{0}'", + "Declare_static_method_0_90024" : "Declare static method '{0}'", + "Prefix_0_with_an_underscore_90025" : "Prefix '{0}' with an underscore", + "Rewrite_as_the_indexed_access_type_0_90026" : "Rewrite as the indexed access type '{0}'", + "Declare_static_property_0_90027" : "Declare static property '{0}'", + "Call_decorator_expression_90028" : "Call decorator expression", + "Add_async_modifier_to_containing_function_90029" : "Add async modifier to containing function", + "Convert_function_to_an_ES2015_class_95001" : "Convert function to an ES2015 class", + "Convert_function_0_to_class_95002" : "Convert function '{0}' to class", + "Extract_to_0_in_1_95004" : "Extract to {0} in {1}", + "Extract_function_95005" : "Extract function", + "Extract_constant_95006" : "Extract constant", + "Extract_to_0_in_enclosing_scope_95007" : "Extract to {0} in enclosing scope", + "Extract_to_0_in_1_scope_95008" : "Extract to {0} in {1} scope", + "Annotate_with_type_from_JSDoc_95009" : "Annotate with type from JSDoc", + "Annotate_with_types_from_JSDoc_95010" : "Annotate with types from JSDoc", + "Infer_type_of_0_from_usage_95011" : "Infer type of '{0}' from usage", + "Infer_parameter_types_from_usage_95012" : "Infer parameter types from usage", + "Convert_to_default_import_95013" : "Convert to default import", + "Install_0_95014" : "Install '{0}'", + "Replace_import_with_0_95015" : "Replace import with '{0}'.", + "Use_synthetic_default_member_95016" : "Use synthetic 'default' member.", + "Convert_to_ES6_module_95017" : "Convert to ES6 module", + "Add_undefined_type_to_property_0_95018" : "Add 'undefined' type to property '{0}'", + "Add_initializer_to_property_0_95019" : "Add initializer to property '{0}'", + "Add_definite_assignment_assertion_to_property_0_95020" : "Add definite assignment assertion to property '{0}'", + "Add_all_missing_members_95022" : "Add all missing members", + "Infer_all_types_from_usage_95023" : "Infer all types from usage", + "Delete_all_unused_declarations_95024" : "Delete all unused declarations", + "Prefix_all_unused_declarations_with_where_possible_95025" : "Prefix all unused declarations with '_' where possible", + "Fix_all_detected_spelling_errors_95026" : "Fix all detected spelling errors", + "Add_initializers_to_all_uninitialized_properties_95027" : "Add initializers to all uninitialized properties", + "Add_definite_assignment_assertions_to_all_uninitialized_properties_95028" : "Add definite assignment assertions to all uninitialized properties", + "Add_undefined_type_to_all_uninitialized_properties_95029" : "Add undefined type to all uninitialized properties", + "Change_all_jsdoc_style_types_to_TypeScript_95030" : "Change all jsdoc-style types to TypeScript", + "Change_all_jsdoc_style_types_to_TypeScript_and_add_undefined_to_nullable_types_95031" : "Change all jsdoc-style types to TypeScript (and add '| undefined' to nullable types)", + "Implement_all_unimplemented_interfaces_95032" : "Implement all unimplemented interfaces", + "Install_all_missing_types_packages_95033" : "Install all missing types packages", + "Rewrite_all_as_indexed_access_types_95034" : "Rewrite all as indexed access types", + "Convert_all_to_default_imports_95035" : "Convert all to default imports", + "Make_all_super_calls_the_first_statement_in_their_constructor_95036" : "Make all 'super()' calls the first statement in their constructor", + "Add_qualifier_to_all_unresolved_variables_matching_a_member_name_95037" : "Add qualifier to all unresolved variables matching a member name", + "Change_all_extended_interfaces_to_implements_95038" : "Change all extended interfaces to 'implements'", + "Add_all_missing_super_calls_95039" : "Add all missing super calls", + "Implement_all_inherited_abstract_classes_95040" : "Implement all inherited abstract classes", + "Add_all_missing_async_modifiers_95041" : "Add all missing 'async' modifiers", + "Add_ts_ignore_to_all_error_messages_95042" : "Add '@ts-ignore' to all error messages", + "Annotate_everything_with_types_from_JSDoc_95043" : "Annotate everything with types from JSDoc", + "Add_to_all_uncalled_decorators_95044" : "Add '()' to all uncalled decorators", + "Convert_all_constructor_functions_to_classes_95045" : "Convert all constructor functions to classes", + "Generate_get_and_set_accessors_95046" : "Generate 'get' and 'set' accessors", + "Convert_require_to_import_95047" : "Convert 'require' to 'import'", + "Convert_all_require_to_import_95048" : "Convert all 'require' to 'import'" +} \ No newline at end of file diff --git a/node_modules/typescript/lib/es/diagnosticMessages.generated.json b/node_modules/typescript/lib/es/diagnosticMessages.generated.json new file mode 100644 index 0000000..52840b1 --- /dev/null +++ b/node_modules/typescript/lib/es/diagnosticMessages.generated.json @@ -0,0 +1,1101 @@ +{ + "A_0_modifier_cannot_be_used_with_an_import_declaration_1079": "Un modificador '{0}' no se puede usar con una declaración de importación.", + "A_0_modifier_cannot_be_used_with_an_interface_declaration_1045": "Un modificador '{0}' no se puede usar con una declaración de interfaz.", + "A_0_parameter_must_be_the_first_parameter_2680": "El parámetro \"{0}\" debe ser el primer parámetro.", + "A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature_2463": "Un parámetro de patrón de enlace no puede ser opcional en una signatura de implementación.", + "A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement_1105": "Una instrucción \"break\" solo se puede usar dentro de una iteración envolvente o en una instrucción switch.", + "A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement_1116": "Una instrucción \"break\" solo puede saltar a una etiqueta de una instrucción envolvente.", + "A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments_2500": "Una clase solo puede implementar un identificador o nombre completo con argumentos de tipo opcional.", + "A_class_declaration_without_the_default_modifier_must_have_a_name_1211": "Una declaración de clase sin el modificador \"default\" debe tener un nombre.", + "A_class_may_only_extend_another_class_2311": "Una clase solo puede extender otra clase.", + "A_class_may_only_implement_another_class_or_interface_2422": "Una clase solo puede implementar otra clase o interfaz.", + "A_class_member_cannot_have_the_0_keyword_1248": "Un miembro de clase no puede tener la palabra clave '{0}'.", + "A_comma_expression_is_not_allowed_in_a_computed_property_name_1171": "No se admite una expresión de coma en un nombre de propiedad calculada.", + "A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type_2467": "Un nombre de propiedad calculada no puede hacer referencia a un parámetro de tipo desde su tipo contenedor.", + "A_computed_property_name_in_a_class_property_declaration_must_refer_to_an_expression_whose_type_is_a_1166": "Un nombre de propiedad calculada en una declaración de propiedad de clase debe hacer referencia a una expresión que sea de tipo literal o \"unique symbol\".", + "A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_ty_1168": "Un nombre de propiedad calculada en una sobrecarga de método debe hacer referencia a una expresión que sea de tipo literal o \"unique symbol\".", + "A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type__1170": "Un nombre de propiedad calculada en un literal de tipo debe hacer referencia a una expresión que sea de tipo literal o \"unique symbol\".", + "A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_t_1165": "Un nombre de propiedad calculada en un contexto de ambiente debe hacer referencia a una expresión que sea de tipo literal o \"unique symbol\".", + "A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_1169": "Un nombre de propiedad calculada en una interfaz debe hacer referencia a una expresión que sea de tipo literal o \"unique symbol\".", + "A_computed_property_name_must_be_of_type_string_number_symbol_or_any_2464": "Un nombre de propiedad calculada debe ser de tipo \"string\", \"number\", \"symbol\" o \"any\".", + "A_computed_property_name_of_the_form_0_must_be_of_type_symbol_2471": "Un nombre de propiedad calculada con el formato '{0}' debe ser de tipo \"symbol\".", + "A_const_enum_member_can_only_be_accessed_using_a_string_literal_2476": "Solo se puede acceder a un miembro de enumeración const mediante un literal de cadena.", + "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_1254": "Un inicializador 'const' en un contexto de ambiente debe ser un literal de cadena o numérico.", + "A_constructor_cannot_contain_a_super_call_when_its_class_extends_null_17005": "Un constructor no puede contener una llamada a \"super\" si su clase extiende \"null\".", + "A_constructor_cannot_have_a_this_parameter_2681": "Un constructor no puede tener un parámetro 'this'.", + "A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement_1104": "Una instrucción \"continue\" solo se puede usar en una instrucción de iteración envolvente.", + "A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement_1115": "Una instrucción \"continue\" solo puede saltar a una etiqueta de una instrucción de iteración envolvente.", + "A_declare_modifier_cannot_be_used_in_an_already_ambient_context_1038": "Un modificador \"declare\" no se puede usar en un contexto de ambiente.", + "A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file_1046": "Se necesita un modificador \"declare\" para una declaración de nivel superior de un archivo .d.ts.", + "A_decorator_can_only_decorate_a_method_implementation_not_an_overload_1249": "Un decorador solo puede modificar la implementación de un método, no una sobrecarga.", + "A_default_clause_cannot_appear_more_than_once_in_a_switch_statement_1113": "Una cláusula \"default\" no puede aparecer más de una vez en una instrucción \"switch\".", + "A_default_export_can_only_be_used_in_an_ECMAScript_style_module_1319": "Solo se puede usar una exportación predeterminada en un módulo de estilo ECMAScript.", + "A_definite_assignment_assertion_is_not_permitted_in_this_context_1255": "En este contexto no se permite una aserción de asignación definitiva \"!\".", + "A_destructuring_declaration_must_have_an_initializer_1182": "Una declaración de desestructuración debe tener un inicializador.", + "A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declarat_2712": "Una llamada de importación dinámica en ES5/ES3 requiere el constructor \"Promise\". Asegúrese de que tiene una declaración para el constructor \"Promise\" o incluya \"ES2015\" en su opción \"--lib\".", + "A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES20_2711": "Una llamada de importación dinámica devuelven un valor \"Promise\". Asegúrese de que hay una declaración para \"Promise\" o incluya \"ES2015\" en la opción \"--lib\".", + "A_file_cannot_have_a_reference_to_itself_1006": "Un archivo no puede tener una referencia a sí mismo.", + "A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator_1103": "Solo se permite una instrucción \"for-await-of\" en una función o un generador de asincronía.", + "A_function_returning_never_cannot_have_a_reachable_end_point_2534": "Una función que devuelve 'never' no puede tener un punto de conexión alcanzable.", + "A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void_2679": "Una función a la que se llama con la palabra clave 'new' no puede tener un tipo 'this' que sea 'void'.", + "A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value_2355": "Una función cuyo tipo declarado no es \"void\" o \"any\" debe devolver un valor.", + "A_generator_cannot_have_a_void_type_annotation_2505": "Un generador no puede tener una anotación de tipo \"void\".", + "A_get_accessor_cannot_have_parameters_1054": "Un descriptor de acceso \"get\" no puede tener parámetros.", + "A_get_accessor_must_return_a_value_2378": "Un descriptor de acceso \"get\" debe devolver un valor.", + "A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_memb_2651": "Un inicializador de miembro de una declaración de enumeración no puede hacer referencia a los miembros que se declaran después de este, incluidos aquellos definidos en otras enumeraciones.", + "A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any_2545": "Una clase mixin debe tener un constructor con un solo parámetro rest de tipo \"any[]\"", + "A_module_cannot_have_multiple_default_exports_2528": "Un módulo no puede tener varias exportaciones predeterminadas.", + "A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merg_2433": "Una declaración de espacio de nombres no puede estar en un archivo distinto de una clase o función con la que se combina.", + "A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged_2434": "Una declaración de espacio de nombres no se puede situar antes que una clase o función con la que se combina.", + "A_namespace_declaration_is_only_allowed_in_a_namespace_or_module_1235": "Una declaración de espacio de nombres solo se permite en un espacio de nombres o en un módulo.", + "A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_7038": "No se puede llamar o construir una importación de estilo de espacio de nombres, y provocará un error en tiempo de ejecución.", + "A_non_dry_build_would_build_project_0_6357": "Una compilación no -dry compilaría el proyecto \"{0}\"", + "A_non_dry_build_would_delete_the_following_files_Colon_0_6356": "Una compilación no -dry eliminaría los archivos siguientes: {0}", + "A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation_2371": "Un inicializador de parámetros solo se permite en una implementación de función o de constructor.", + "A_parameter_property_cannot_be_declared_using_a_rest_parameter_1317": "Una propiedad de parámetro no se puede declarar mediante un parámetro rest.", + "A_parameter_property_is_only_allowed_in_a_constructor_implementation_2369": "Una propiedad de parámetro solo se permite en una implementación de constructor.", + "A_parameter_property_may_not_be_declared_using_a_binding_pattern_1187": "Una propiedad de parámetro podría no declararse mediante un patrón de enlace.", + "A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not_18001": "Una ruta de acceso en una opción \"extiende\" debe ser relativa o raíz, pero no \"{0}\".", + "A_promise_must_have_a_then_method_1059": "Una promesa debe tener un método \"then\".", + "A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly_1331": "Una propiedad de una clase cuyo tipo sea \"unique symbol\" debe ser \"static\" y \"readonly\".", + "A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly_1330": "Una propiedad de una interfaz o un literal de tipo cuyo tipo sea \"unique symbol\" debe ser \"readonly\".", + "A_required_parameter_cannot_follow_an_optional_parameter_1016": "Un parámetro obligatorio no puede seguir a un parámetro opcional.", + "A_rest_element_cannot_contain_a_binding_pattern_2501": "Un elemento rest no puede contener un patrón de enlace.", + "A_rest_element_cannot_have_a_property_name_2566": "Un elemento rest no puede tener un nombre de propiedad.", + "A_rest_element_cannot_have_an_initializer_1186": "Un elemento rest no puede tener un inicializador.", + "A_rest_element_must_be_last_in_a_destructuring_pattern_2462": "Un elemento rest debe ser el último en un patrón de desestructuración.", + "A_rest_parameter_cannot_be_optional_1047": "Un parámetro rest no puede ser opcional.", + "A_rest_parameter_cannot_have_an_initializer_1048": "Un parámetro rest no puede tener un inicializador.", + "A_rest_parameter_must_be_last_in_a_parameter_list_1014": "Un parámetro rest debe ser el último de una lista de parámetros.", + "A_rest_parameter_must_be_of_an_array_type_2370": "Un parámetro rest debe ser de un tipo de matriz.", + "A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma_1013": "Un parámetro rest o un patrón de enlace no pueden finalizar con una coma.", + "A_return_statement_can_only_be_used_within_a_function_body_1108": "Una instrucción \"return\" solo se puede usar en el cuerpo de una función.", + "A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl_6167": "Serie de entradas que reasigna las importaciones a ubicaciones de búsqueda relativas a \"baseUrl\".", + "A_set_accessor_cannot_have_a_return_type_annotation_1095": "Un descriptor de acceso \"set\" no puede tener una anotación de tipo de valor devuelto.", + "A_set_accessor_cannot_have_an_optional_parameter_1051": "Un descriptor de acceso \"set\" no puede tener un parámetro opcional.", + "A_set_accessor_cannot_have_rest_parameter_1053": "Un descriptor de acceso \"set\" no puede tener un parámetro rest.", + "A_set_accessor_must_have_exactly_one_parameter_1049": "Un descriptor de acceso \"set\" debe tener exactamente un parámetro.", + "A_set_accessor_parameter_cannot_have_an_initializer_1052": "Un parámetro de descriptor de acceso \"set\" no puede tener un inicializador.", + "A_signature_with_an_implementation_cannot_use_a_string_literal_type_2381": "Una signatura con una implementación no puede usar un tipo de literal de cadena.", + "A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_proper_2376": "Una llamada a \"super\" debe ser la primera instrucción del constructor cuando una clase contiene propiedades inicializadas o tiene propiedades de parámetro.", + "A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard_2518": "Una restricción de tipo basada en 'this' no es compatible con una restricción de tipo basada en un parámetro.", + "A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface_2526": "El tipo \"this\" solo está disponible en un miembro no estático de una clase o interfaz.", + "A_tsconfig_json_file_is_already_defined_at_Colon_0_5054": "Ya hay un archivo \"tsconfig.json\" definido en: '{0}'.", + "A_tuple_type_element_list_cannot_be_empty_1122": "Una lista de elementos de tipo de tupla no puede estar vacía.", + "A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Con_17007": "No se admite una expresión de aserción de tipo en el lado izquierdo de una expresión de exponenciación. Considere la posibilidad de incluir la expresión entre paréntesis.", + "A_type_literal_property_cannot_have_an_initializer_1247": "Una propiedad de literal de tipo no puede tener un inicializador.", + "A_type_predicate_cannot_reference_a_rest_parameter_1229": "Un predicado de tipo no puede hacer referencia a un parámetro rest.", + "A_type_predicate_cannot_reference_element_0_in_a_binding_pattern_1230": "Un predicado de tipo no puede hacer referencia al elemento '{0}' de un patrón de enlace.", + "A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods_1228": "En las funciones y los métodos, un predicado de tipo solo se permite en la posición de tipo de valor devuelto.", + "A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type_2677": "El tipo de un predicado de tipo debe poderse asignar al tipo de su parámetro.", + "A_variable_whose_type_is_a_unique_symbol_type_must_be_const_1332": "Una variable cuyo tipo sea \"unique symbol\" debe ser \"const\".", + "A_yield_expression_is_only_allowed_in_a_generator_body_1163": "Una expresión \"yield\" solo se permite en un cuerpo de generador.", + "Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression_2513": "No se puede acceder al método abstracto '{0}' de la clase '{1}' mediante una expresión super.", + "Abstract_methods_can_only_appear_within_an_abstract_class_1244": "Los métodos abstractos solo pueden aparecer en una clase abstracta.", + "Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor_2715": "No se puede acceder a la propiedad abstracta \"{0}\" de la clase \"{1}\" en el constructor.", + "Accessibility_modifier_already_seen_1028": "El modificador de accesibilidad ya se ha visto.", + "Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher_1056": "Los descriptores de acceso solo están disponibles cuando el destino es ECMAScript 5 y versiones posteriores.", + "Accessors_must_both_be_abstract_or_non_abstract_2676": "Los descriptores de acceso deben ser los dos abstractos o los dos no abstractos.", + "Add_0_to_existing_import_declaration_from_1_90015": "Agregar \"{0}\" a una declaración de importación existente desde \"{1}\"", + "Add_0_to_unresolved_variable_90008": "Agregar \"{0}.\" a una variable no resuelta", + "Add_all_missing_async_modifiers_95041": "Agregar todos los modificadores \"async\" que faltan", + "Add_all_missing_members_95022": "Agregar todos los miembros que faltan", + "Add_all_missing_super_calls_95039": "Agregar todas las llamadas a super que faltan", + "Add_async_modifier_to_containing_function_90029": "Agregar el modificador async a la función contenedora", + "Add_braces_to_arrow_function_95059": "Agregar llaves a la función de flecha", + "Add_definite_assignment_assertion_to_property_0_95020": "Agregar aserción de asignación definitiva a la propiedad \"{0}\"", + "Add_definite_assignment_assertions_to_all_uninitialized_properties_95028": "Agregar aserciones de asignación definitiva a todas las propiedades sin inicializar", + "Add_index_signature_for_property_0_90017": "Agregar una signatura de índice para la propiedad \"{0}\"", + "Add_initializer_to_property_0_95019": "Agregar inicializador a la propiedad \"{0}\"", + "Add_initializers_to_all_uninitialized_properties_95027": "Agregar inicializadores a todas las propiedades sin inicializar", + "Add_missing_super_call_90001": "Agregar la llamada a \"super()\" que falta", + "Add_missing_typeof_95052": "Agregar el elemento \"typeof\" que falta", + "Add_or_remove_braces_in_an_arrow_function_95058": "Agregar o quitar llaves en una función de flecha", + "Add_qualifier_to_all_unresolved_variables_matching_a_member_name_95037": "Agregar un calificador a todas las variables no resueltas que coincidan con un nombre de miembro", + "Add_to_all_uncalled_decorators_95044": "Agregar \"()\" a todos los elementos Decorator a los que no se llama", + "Add_ts_ignore_to_all_error_messages_95042": "Agregar \"@ts-ignore\" a todos los mensajes de error", + "Add_undefined_type_to_all_uninitialized_properties_95029": "Agregar un tipo no definido a todas las propiedades sin inicializar", + "Add_undefined_type_to_property_0_95018": "Agregar un tipo \"undefined\" a la propiedad \"{0}\"", + "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068": "Agregar un archivo tsconfig.json ayuda a organizar los proyectos que contienen archivos TypeScript y JavaScript. Más información en https://aka.ms/tsconfig.", + "Additional_Checks_6176": "Comprobaciones adicionales", + "Advanced_Options_6178": "Opciones avanzadas", + "All_declarations_of_0_must_have_identical_modifiers_2687": "Todas las declaraciones de '{0}' deben tener modificadores idénticos.", + "All_declarations_of_0_must_have_identical_type_parameters_2428": "Todas las declaraciones de '{0}' deben tener parámetros de tipo idénticos.", + "All_declarations_of_an_abstract_method_must_be_consecutive_2516": "Todas las declaraciones de un método abstracto deben ser consecutivas.", + "All_destructured_elements_are_unused_6198": "Todos los elementos desestructurados están sin utilizar.", + "All_imports_in_import_declaration_are_unused_6192": "Todas las importaciones de la declaración de importación están sin utilizar.", + "All_variables_are_unused_6199": "Todas las variables son no utilizadas.", + "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011": "Permitir las importaciones predeterminadas de los módulos sin exportación predeterminada. Esto no afecta a la emisión de código, solo a la comprobación de tipos.", + "Allow_javascript_files_to_be_compiled_6102": "Permitir que se compilen los archivos de JavaScript.", + "Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided_1209": "No se permiten enumeraciones const de ambiente cuando se proporciona la marca \"--isolatedModules\".", + "Ambient_module_declaration_cannot_specify_relative_module_name_2436": "La declaración de módulo de ambiente no puede especificar un nombre de módulo relativo.", + "Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces_2435": "Los módulos de ambiente no se pueden anidar en otros módulos o espacios de nombres.", + "An_AMD_module_cannot_have_multiple_name_assignments_2458": "Un módulo AMD no puede tener varias asignaciones de nombre.", + "An_abstract_accessor_cannot_have_an_implementation_1318": "Un descriptor de acceso abstracto no puede tener una implementación.", + "An_accessor_cannot_be_declared_in_an_ambient_context_1086": "Un descriptor de acceso no se puede declarar en un contexto de ambiente.", + "An_accessor_cannot_have_type_parameters_1094": "Un descriptor de acceso no puede tener parámetros de tipo.", + "An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file_1234": "Una declaración de módulo de ambiente solo se permite en el nivel superior de un archivo.", + "An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type_2356": "Un operando aritmético debe ser de tipo \"any\", \"number\" o un tipo de enumeración.", + "An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_de_2705": "Una función o un método de asincronía en ES5/ES3 requiere el constructor \"Promise\". Asegúrese de que tiene una declaración para el constructor \"Promise\" o incluya \"ES2015\" en su opción \"--lib\".", + "An_async_function_or_method_must_have_a_valid_awaitable_return_type_1057": "Una función o un método asincrónico deben tener un tipo de valor devuelto válido que admita await.", + "An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_in_2697": "Una función o un método asincrónicos deben devolver una \"promesa\". Asegúrese de que hay una declaración de \"promesa\" o incluya \"ES2015\" en la opción \"--lib\".", + "An_async_iterator_must_have_a_next_method_2519": "Un iterador de asincronía debe tener un método \"next()\".", + "An_element_access_expression_should_take_an_argument_1011": "Una expresión de acceso de elemento debe admitir un argumento.", + "An_enum_member_cannot_have_a_numeric_name_2452": "Un miembro de enumeración no puede tener un nombre numérico.", + "An_export_assignment_can_only_be_used_in_a_module_1231": "Una asignación de exportación solo se puede usar en un módulo.", + "An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements_2309": "Una asignación de exportación no se puede usar en un módulo con otros elementos exportados.", + "An_export_assignment_cannot_be_used_in_a_namespace_1063": "Una asignación de exportación no se puede usar en espacios de nombres.", + "An_export_assignment_cannot_have_modifiers_1120": "Una asignación de exportación no puede tener modificadores.", + "An_export_declaration_can_only_be_used_in_a_module_1233": "Una declaración de exportación solo se puede usar en un módulo.", + "An_export_declaration_cannot_have_modifiers_1193": "Una declaración de exportación no puede tener modificadores.", + "An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive_1198": "Un valor de escape Unicode extendido debe estar entre 0x0 y 0x10FFFF, incluidos.", + "An_implementation_cannot_be_declared_in_ambient_contexts_1183": "Una implementación no se puede declarar en contextos de ambiente.", + "An_import_declaration_can_only_be_used_in_a_namespace_or_module_1232": "Una declaración de importación solo se puede usar en un espacio de nombres o un módulo.", + "An_import_declaration_cannot_have_modifiers_1191": "Una declaración de importación no puede tener modificadores.", + "An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead_2691": "Una ruta de acceso de importación no puede terminar con una extensión '{0}'. Puede importar '{1}' en su lugar.", + "An_index_expression_argument_must_be_of_type_string_number_symbol_or_any_2342": "Un argumento de expresión de índice debe ser de tipo \"string\", \"number\", \"symbol\" o \"any\".", + "An_index_signature_cannot_have_a_rest_parameter_1017": "Una signatura de índice no puede tener un parámetro rest.", + "An_index_signature_must_have_a_type_annotation_1021": "Una signatura de índice debe tener una anotación de tipo.", + "An_index_signature_must_have_exactly_one_parameter_1096": "Una signatura de índice debe tener exactamente un parámetro.", + "An_index_signature_parameter_cannot_have_a_question_mark_1019": "Un parámetro de signatura de índice no puede tener un signo de interrogación.", + "An_index_signature_parameter_cannot_have_an_accessibility_modifier_1018": "Un parámetro de signatura de índice no puede tener un modificador de accesibilidad.", + "An_index_signature_parameter_cannot_have_an_initializer_1020": "Un parámetro de signatura de índice no puede tener un inicializador.", + "An_index_signature_parameter_must_have_a_type_annotation_1022": "Un parámetro de signatura de índice debe tener una anotación de tipo.", + "An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead_1336": "Un tipo de parámetro de firma de índice no puede ser un alias de tipo. Considere la posibilidad de escribir en su lugar \"[{0}: {1}]: {2}\".", + "An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead_1337": "Un tipo de parámetro de firma de índice no puede ser un tipo de unión. Considere la posibilidad de usar en su lugar un tipo de objeto asignado.", + "An_index_signature_parameter_type_must_be_string_or_number_1023": "El tipo de un parámetro de signatura de índice debe ser \"string\" o \"number\".", + "An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments_2499": "Una interfaz solo puede extender un identificador o nombre completo con argumentos de tipo opcional.", + "An_interface_may_only_extend_a_class_or_another_interface_2312": "Una interfaz solo puede extender una clase u otra interfaz.", + "An_interface_property_cannot_have_an_initializer_1246": "Una propiedad de interfaz no puede tener un inicializador.", + "An_iterator_must_have_a_next_method_2489": "Un iterador debe tener un método \"next()\".", + "An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name_1118": "Un literal de objeto no puede tener varios descriptores de acceso get o set con el mismo nombre.", + "An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode_1117": "Un literal de objeto no puede tener varias propiedades con el mismo nombre en modo strict.", + "An_object_literal_cannot_have_property_and_accessor_with_the_same_name_1119": "Un literal de objeto no puede tener una propiedad y un descriptor de acceso con el mismo nombre.", + "An_object_member_cannot_be_declared_optional_1162": "Un miembro de objeto no se puede declarar como opcional.", + "An_overload_signature_cannot_be_declared_as_a_generator_1222": "Una signatura de sobrecarga no se puede declarar como generador.", + "An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_ex_17006": "No se admite una expresión unaria con el operador '{0}' en el lado izquierdo de una expresión de exponenciación. Considere la posibilidad de incluir la expresión entre paréntesis.", + "Annotate_everything_with_types_from_JSDoc_95043": "Anotar todo con tipos de JSDoc", + "Annotate_with_type_from_JSDoc_95009": "Anotar con tipo de JSDoc", + "Annotate_with_types_from_JSDoc_95010": "Anotar con tipos de JSDoc", + "Argument_expression_expected_1135": "Se esperaba una expresión de argumento.", + "Argument_for_0_option_must_be_Colon_1_6046": "El argumento para la opción \"{0}\" debe ser {1}.", + "Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_2345": "No se puede asignar un argumento de tipo \"{0}\" al parámetro de tipo \"{1}\".", + "Array_element_destructuring_pattern_expected_1181": "Se esperaba un patrón de desestructuración de elementos de matriz.", + "Asterisk_Slash_expected_1010": "Se esperaba \"*/\".", + "Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_2669": "Los aumentos del ámbito global solo pueden anidarse directamente en módulos externos o en declaraciones de módulos de ambiente.", + "Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambien_2670": "Los aumentos del ámbito global deben tener el modificador 'declare', a menos que aparezcan en un contexto de ambiente.", + "Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using__6140": "La detección automática de escritura está habilitada en el proyecto '{0}'. Se va a ejecutar un paso de resolución extra para el módulo '{1}' usando la ubicación de caché '{2}'.", + "Base_class_expressions_cannot_reference_class_type_parameters_2562": "Las expresiones de clase base no pueden hacer referencia a parámetros de tipo de clase.", + "Base_constructor_return_type_0_is_not_a_class_or_interface_type_2509": "El tipo de valor devuelto del constructor base '{0}' no es un tipo de clase o interfaz.", + "Base_constructors_must_all_have_the_same_return_type_2510": "Todos los constructores base deben tener el mismo tipo de valor devuelto.", + "Base_directory_to_resolve_non_absolute_module_names_6083": "Directorio base para resolver nombres de módulos no absolutos.", + "Basic_Options_6172": "Opciones básicas", + "Binary_digit_expected_1177": "Se esperaba un dígito binario.", + "Binding_element_0_implicitly_has_an_1_type_7031": "El elemento de enlace '{0}' tiene un tipo '{1}' implícito.", + "Block_scoped_variable_0_used_before_its_declaration_2448": "Variable con ámbito de bloque '{0}' usada antes de su declaración.", + "Build_all_projects_including_those_that_appear_to_be_up_to_date_6368": "Compilar todos los proyectos, incluidos los que aparecen actualizados", + "Build_one_or_more_projects_and_their_dependencies_if_out_of_date_6364": "Generar uno o varios proyectos y sus dependencias, si no están actualizados", + "Building_project_0_6358": "Compilando el proyecto \"{0}\"...", + "Call_decorator_expression_90028": "Llamar a la expresión decorador", + "Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7020": "La signatura de llamada, que carece de una anotación de tipo de valor devuelto, tiene implícitamente un tipo de valor devuelto \"any\".", + "Call_target_does_not_contain_any_signatures_2346": "El destino de llamada no contiene signaturas.", + "Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_p_2713": "No se puede acceder a \"{0}.{1}\" porque \"{0}\" es un tipo, no un espacio de nombres. ¿Su intención era recuperar el tipo de la propiedad \"{1}\" en \"{0}\" con \"{0}[\"{1}\"]\"?", + "Cannot_assign_a_0_constructor_type_to_a_1_constructor_type_2672": "No se puede asignar un tipo de constructor '{0}' a un tipo de constructor '{1}'.", + "Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type_2517": "No se puede asignar un tipo de constructor abstracto a uno no abstracto.", + "Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property_2540": "No se puede asignar a '{0}' porque es una constante o una propiedad de solo lectura.", + "Cannot_assign_to_0_because_it_is_not_a_variable_2539": "No se puede asignar a '{0}' porque no es una variable.", + "Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity_2671": "No se puede aumentar el módulo '{0}' porque se resuelve como una entidad que no es un módulo.", + "Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity_2649": "No se puede aumentar el módulo \"{0}\" con exportaciones de valores porque se resuelve como una entidad que no es un módulo.", + "Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system_6131": "No se pueden compilar los módulos con la opción '{0}' a no ser que la marca \"--module\" sea \"amd\" o \"system\".", + "Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided_1208": "Los espacios de nombres no se pueden compilar si se proporciona la marca \"--isolatedModules\".", + "Cannot_create_an_instance_of_an_abstract_class_2511": "No se puede crear una instancia de una clase abstracta.", + "Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module_2661": "No se puede exportar '{0}'. Solo se pueden exportar declaraciones locales desde un módulo.", + "Cannot_extend_a_class_0_Class_constructor_is_marked_as_private_2675": "No se puede extender una clase '{0}'. El constructor de la clase está marcado como privado.", + "Cannot_extend_an_interface_0_Did_you_mean_implements_2689": "No se puede extender una interfaz '{0}'. ¿Quiso decir 'implements'?", + "Cannot_find_a_tsconfig_json_file_at_the_specified_directory_Colon_0_5057": "No se encuentra ningún archivo tsconfig.json en el directorio especificado: \"{0}\".", + "Cannot_find_global_type_0_2318": "No se encuentra el tipo '{0}' global.", + "Cannot_find_global_value_0_2468": "No se encuentra el valor '{0}' global.", + "Cannot_find_lib_definition_for_0_2726": "No se encuentra la definición lib para \"{0}\".", + "Cannot_find_lib_definition_for_0_Did_you_mean_1_2727": "No se encuentra la definición lib para \"{0}\". ¿Quiso decir \"{1}\"?", + "Cannot_find_module_0_2307": "No se encuentra el módulo '{0}'.", + "Cannot_find_name_0_2304": "No se encuentra el nombre '{0}'.", + "Cannot_find_name_0_Did_you_mean_1_2552": "No se encuentra el nombre \"{0}\". ¿Quería decir \"{1}\"?", + "Cannot_find_name_0_Did_you_mean_the_instance_member_this_0_2663": "No se encuentra el nombre '{0}'. ¿Quería decir el miembro de instancia 'this.{0}'?", + "Cannot_find_name_0_Did_you_mean_the_static_member_1_0_2662": "No se encuentra el nombre '{0}'. ¿Quería decir el miembro estático '{1}.{0}'?", + "Cannot_find_namespace_0_2503": "No se encuentra el espacio de nombres '{0}'.", + "Cannot_find_parameter_0_1225": "No se encuentra el parámetro '{0}'.", + "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009": "No se encuentra la ruta de acceso de subdirectorio común para los archivos de entrada.", + "Cannot_find_type_definition_file_for_0_2688": "No se puede encontrar el archivo de definición de tipo para '{0}'.", + "Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1_6137": "No se pueden importar archivos de declaración de tipos. Considere importar \"{0}\" en lugar de \"{1}\".", + "Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1_2481": "No se puede inicializar la variable '{0}' de ámbito externo en el mismo ámbito que la declaración '{1}' con ámbito de bloque.", + "Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatur_2349": "No se puede invocar una expresión con un tipo sin signatura de llamada. El tipo '{0}' no tiene ninguna signatura de llamada compatible.", + "Cannot_invoke_an_object_which_is_possibly_null_2721": "No se puede invocar un objeto que es posiblemente \"null\".", + "Cannot_invoke_an_object_which_is_possibly_null_or_undefined_2723": "No se puede invocar un objeto que es posiblemente \"null\" o \"no definido\".", + "Cannot_invoke_an_object_which_is_possibly_undefined_2722": "No se puede invocar un objeto que es posiblemente \"no definido\".", + "Cannot_prepend_project_0_because_it_does_not_have_outFile_set_6308": "No se puede anteponer el proyecto \"{0}\" porque no se ha establecido \"outFile\".", + "Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205": "No se puede volver a exportar un tipo si se proporciona la marca \"--isolatedModules\".", + "Cannot_read_file_0_Colon_1_5012": "No se puede leer el archivo \"{0}\": {1}.", + "Cannot_redeclare_block_scoped_variable_0_2451": "No se puede volver a declarar la variable con ámbito de bloque '{0}'.", + "Cannot_redeclare_exported_variable_0_2323": "No se puede volver a declarar la variable '{0}' exportada.", + "Cannot_redeclare_identifier_0_in_catch_clause_2492": "No se puede volver a declarar el identificador \"{0}\" en la cláusula catch.", + "Cannot_use_JSX_unless_the_jsx_flag_is_provided_17004": "JSX no se puede usar si no se proporciona la marca \"--jsx\".", + "Cannot_use_imports_exports_or_module_augmentations_when_module_is_none_1148": "No se pueden usar importaciones, exportaciones o aumentos de módulos si el valor de \"--module\" es \"none\".", + "Cannot_use_namespace_0_as_a_type_2709": "No se puede utilizar el espacio de nombres '{0}' como un tipo.", + "Cannot_use_namespace_0_as_a_value_2708": "No se puede utilizar el espacio de nombres '{0}' como un valor.", + "Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature_2351": "No se puede usar \"new\" con una expresión cuyo tipo carece de una signatura de construcción o de llamada.", + "Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files_5056": "No se puede escribir en el archivo '{0}' porque se sobrescribiría con varios archivos de entrada.", + "Cannot_write_file_0_because_it_would_overwrite_input_file_5055": "No se puede escribir en el archivo '{0}' porque sobrescribiría el archivo de entrada.", + "Catch_clause_variable_cannot_have_a_type_annotation_1196": "La variable de la cláusula catch no puede tener una anotación de tipo.", + "Catch_clause_variable_cannot_have_an_initializer_1197": "La variable de la cláusula catch no puede tener un inicializador.", + "Change_0_to_1_90014": "Cambiar \"{0}\" a \"{1}\"", + "Change_all_extended_interfaces_to_implements_95038": "Cambiar todas las interfaces mejoradas a \"implements\"", + "Change_all_jsdoc_style_types_to_TypeScript_95030": "Cambiar todos los tipos de jsdoc-style a TypeScript", + "Change_all_jsdoc_style_types_to_TypeScript_and_add_undefined_to_nullable_types_95031": "Cambiar todos los tipos de jsdoc-style a TypeScript (y agregar \"| undefined\" a los tipos que aceptan valores NULL)", + "Change_extends_to_implements_90003": "Cambiar \"extends\" a \"implements\"", + "Change_spelling_to_0_90022": "Cambiar la ortografía a \"{0}\"", + "Checking_if_0_is_the_longest_matching_prefix_for_1_2_6104": "Comprobando si '{0}' es el prefijo coincidente más largo para '{1}' - '{2}'.", + "Circular_definition_of_import_alias_0_2303": "Definición circular del alias de importación '{0}'.", + "Circularity_detected_while_resolving_configuration_Colon_0_18000": "Se detectó circularidad al resolver la configuración: {0}", + "Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_functi_2426": "La clase '{0}' define el descriptor de acceso del miembro de instancia como '{1}', pero la clase extendida '{2}' lo define como función miembro de instancia.", + "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_access_2423": "La clase '{0}' define la función miembro de instancia como '{1}', pero la clase extendida '{2}' la define como descriptor de acceso de miembro de instancia.", + "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_proper_2424": "La clase '{0}' define la función miembro de instancia como '{1}', pero la clase extendida '{2}' la define como propiedad de miembro de instancia.", + "Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_functi_2425": "La clase '{0}' define la propiedad de miembro de instancia como '{1}', pero la clase extendida '{2}' la define como función miembro de instancia.", + "Class_0_incorrectly_extends_base_class_1_2415": "La clase '{0}' extiende la clase base '{1}' de forma incorrecta.", + "Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclas_2720": "La clase \"{0}\" no implementa correctamente la clase \"{1}\". ¿Pretendía extender \"{1}\" y heredar sus miembros como una subclase?", + "Class_0_incorrectly_implements_interface_1_2420": "La clase '{0}' implementa la interfaz '{1}' de forma incorrecta.", + "Class_0_used_before_its_declaration_2449": "Se ha usado la clase \"{0}\" antes de declararla.", + "Class_declarations_cannot_have_more_than_one_augments_or_extends_tag_8025": "Las declaraciones de clase no pueden tener más de una etiqueta \"@augments\" o \"@extends\".", + "Class_name_cannot_be_0_2414": "El nombre de la clase no puede ser \"{0}\".", + "Class_name_cannot_be_Object_when_targeting_ES5_with_module_0_2725": "El nombre de clase no puede ser \"Object\" cuando el destino es ES5 con un módulo {0}.", + "Class_static_side_0_incorrectly_extends_base_class_static_side_1_2417": "El lado estático de la clase '{0}' extiende el lado estático de la clase base '{1}' de forma incorrecta.", + "Classes_can_only_extend_a_single_class_1174": "Las clases solo pueden extender una clase única.", + "Classes_containing_abstract_methods_must_be_marked_abstract_2514": "Las clases con métodos abstractos deben marcarse como abstractas.", + "Command_line_Options_6171": "Opciones de la línea de comandos", + "Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json_6020": "Compila el proyecto teniendo en cuenta la ruta de acceso a su archivo de configuración o a una carpeta con un archivo \"tsconfig.json\".", + "Compiler_option_0_expects_an_argument_6044": "La opción '{0}' del compilador espera un argumento.", + "Compiler_option_0_requires_a_value_of_type_1_5024": "La opción '{0}' del compilador requiere un valor de tipo {1}.", + "Composite_projects_may_not_disable_declaration_emit_6304": "Los proyectos compuestos no pueden deshabilitar la emisión de declaración.", + "Computed_property_names_are_not_allowed_in_enums_1164": "No se permiten nombres de propiedad calculada en las enumeraciones.", + "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553": "No se permiten valores calculados en una enumeración que tiene miembros con valores de cadena.", + "Concatenate_and_emit_output_to_single_file_6001": "Concatenar y emitir la salida en un único archivo.", + "Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_librar_4090": "Se encontraron definiciones de '{0}' en conflicto en '{1}' y '{2}'. Puede instalar una versión específica de esta biblioteca para resolver el conflicto.", + "Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7013": "La signatura de construcción, que carece de una anotación de tipo de valor devuelto, tiene implícitamente un tipo de valor devuelto \"any\".", + "Constructor_implementation_is_missing_2390": "Falta la implementación del constructor.", + "Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration_2673": "El constructor de la clase '{0}' es privado y solo es accesible desde la declaración de la clase.", + "Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration_2674": "El constructor de la clase '{0}' está protegido y solo es accesible desde la declaración de la clase.", + "Constructors_for_derived_classes_must_contain_a_super_call_2377": "Los constructores de las clases derivadas deben contener una llamada a \"super\".", + "Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126": "El archivo contenedor no se ha especificado y no se puede determinar el directorio raíz. Se omitirá la búsqueda en la carpeta 'node_modules'.", + "Convert_0_to_mapped_object_type_95055": "Convertir \"{0}\" en el tipo de objeto asignado", + "Convert_all_constructor_functions_to_classes_95045": "Convertir todas las funciones de constructor en clases", + "Convert_all_require_to_import_95048": "Convertir todas las repeticiones de \"require\" en \"import\"", + "Convert_all_to_default_imports_95035": "Convertir todo en importaciones predeterminadas", + "Convert_function_0_to_class_95002": "Convertir la función \"{0}\" en una clase", + "Convert_function_to_an_ES2015_class_95001": "Convertir la función en una clase ES2015", + "Convert_named_imports_to_namespace_import_95057": "Convertir importaciones con nombre en una importación de espacio de nombres", + "Convert_namespace_import_to_named_imports_95056": "Convertir una importación de espacio de nombres en importaciones con nombre", + "Convert_require_to_import_95047": "Convertir \"require\" en \"import\"", + "Convert_to_ES6_module_95017": "Convertir en módulo ES6", + "Convert_to_default_import_95013": "Convertir en importación predeterminada", + "Corrupted_locale_file_0_6051": "Archivo de configuración regional {0} dañado.", + "Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type_7016": "No se encontró ningún archivo de declaración para el módulo '{0}'. '{1}' tiene un tipo \"any\" de forma implícita.", + "Could_not_write_file_0_Colon_1_5033": "No se puede escribir en el archivo \"{0}\": \"{1}\".", + "DIRECTORY_6038": "DIRECTORIO", + "Declaration_expected_1146": "Se esperaba una declaración.", + "Declaration_name_conflicts_with_built_in_global_identifier_0_2397": "Conflictos entre nombres de declaración con el identificador global '{0}' integrado.", + "Declaration_or_statement_expected_1128": "Se esperaba una declaración o una instrucción.", + "Declare_method_0_90023": "Declarar el método \"{0}\"", + "Declare_property_0_90016": "Declarar la propiedad \"{0}\"", + "Declare_static_method_0_90024": "Declarar el método estático \"{0}\"", + "Declare_static_property_0_90027": "Declarar la propiedad estática \"{0}\"", + "Decorators_are_not_valid_here_1206": "Los elementos Decorator no son válidos aquí.", + "Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name_1207": "No se pueden aplicar elementos Decorator a varios descriptores de acceso get o set con el mismo nombre.", + "Default_export_of_the_module_has_or_is_using_private_name_0_4082": "La exportación predeterminada del módulo tiene o usa el nombre privado '{0}'.", + "Delete_all_unused_declarations_95024": "Eliminar todas las declaraciones sin usar", + "Delete_the_outputs_of_all_projects_6365": "Eliminar las salidas de todos los proyectos", + "Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react__6084": "[En desuso] Use \"--jsxFactory\" en su lugar. Especifique el objeto invocado para createElement cuando el destino sea la emisión de JSX \"react\"", + "Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file_6170": "[En desuso] Use \"--outFile\" en su lugar. Concatena y emite la salida en un solo archivo.", + "Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files_6160": "[En desuso] Use \"--skipLibCheck\" en su lugar. Omite la comprobación de tipos de los archivos de declaración de biblioteca predeterminados.", + "Digit_expected_1124": "Se esperaba un dígito.", + "Directory_0_does_not_exist_skipping_all_lookups_in_it_6148": "El directorio \"{0}\" no existe, se omitirán todas las búsquedas en él.", + "Disable_checking_for_this_file_90018": "Deshabilitar la comprobación para este archivo", + "Disable_size_limitations_on_JavaScript_projects_6162": "Deshabilitar los límites de tamaño de proyectos de JavaScript.", + "Disable_strict_checking_of_generic_signatures_in_function_types_6185": "Deshabilite la comprobación estricta de firmas genéricas en tipos de función.", + "Disallow_inconsistently_cased_references_to_the_same_file_6078": "No permitir referencias al mismo archivo con un uso incoherente de mayúsculas y minúsculas.", + "Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files_6159": "No agregar módulos importados ni referencias con triple barra diagonal a la lista de archivos compilados.", + "Do_not_emit_comments_to_output_6009": "No emitir comentarios en la salida.", + "Do_not_emit_declarations_for_code_that_has_an_internal_annotation_6056": "No emitir declaraciones para el código que tiene una anotación \"@internal\".", + "Do_not_emit_outputs_6010": "No emitir salidas.", + "Do_not_emit_outputs_if_any_errors_were_reported_6008": "No emitir salidas si se informa de algún error.", + "Do_not_emit_use_strict_directives_in_module_output_6112": "No emitir directivas 'use strict' en la salida del módulo.", + "Do_not_erase_const_enum_declarations_in_generated_code_6007": "No borrar las declaraciones de enumeración const en el código generado.", + "Do_not_generate_custom_helper_functions_like_extends_in_compiled_output_6157": "No generar funciones del asistente personalizadas como \"__extends\" en la salida compilada.", + "Do_not_include_the_default_library_file_lib_d_ts_6158": "No incluir el archivo de biblioteca predeterminado (lib.d.ts).", + "Do_not_report_errors_on_unreachable_code_6077": "No notificar los errores del código inaccesible.", + "Do_not_report_errors_on_unused_labels_6074": "No notificar los errores de las etiquetas no usadas.", + "Do_not_resolve_the_real_path_of_symlinks_6013": "No resolver la ruta de acceso real de los vínculos simbólicos.", + "Do_not_truncate_error_messages_6165": "No truncar los mensajes de error.", + "Duplicate_declaration_0_2718": "Declaración duplicada \"{0}\".", + "Duplicate_function_implementation_2393": "Implementación de función duplicada.", + "Duplicate_identifier_0_2300": "Identificador '{0}' duplicado.", + "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_2441": "Identificador '{0}' duplicado. El compilador se reserva el nombre '{1}' en el ámbito de nivel superior de un módulo.", + "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_func_2529": "Identificador '{0}' duplicado. El compilador reserva el nombre '{1}' en el ámbito de nivel superior de un módulo que contiene funciones asincrónicas.", + "Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions_2520": "Identificador '{0}' duplicado. El compilador usa la declaración '{1}' para admitir funciones asincrónicas.", + "Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters_2396": "Identificador \"arguments\" duplicado. El compilador usa \"arguments\" para inicializar parámetros rest.", + "Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_me_2543": "Identificador duplicado \"_newTarget\". El compilador usa la declaración de variable \"_newTarget\" para capturar la referencia de la propiedad Meta \"new.target\".", + "Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference_2401": "Identificador \"_super\" duplicado. El compilador usa \"_super\" para capturar una referencia de clase base.", + "Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference_2399": "Identificador \"_this\" duplicado. El compilador usa la declaración de variable \"_this\" para capturar una referencia \"this\".", + "Duplicate_label_0_1114": "Etiqueta \"{0}\" duplicada.", + "Duplicate_number_index_signature_2375": "Signatura de índice de número duplicada.", + "Duplicate_string_index_signature_2374": "Signatura de índice de cadena duplicada.", + "Dynamic_import_cannot_have_type_arguments_1326": "La importación dinámica no puede tener argumentos de tipo", + "Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext_1323": "La importación dinámica solo se admite cuando la marca \"--module\" es \"commonjs\" o \"esNext\".", + "Dynamic_import_must_have_one_specifier_as_an_argument_1324": "La importación dinámica debe tener un especificador como argumento.", + "Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036": "El especificador de la importación dinámica debe ser de tipo \"string\", pero aquí tiene el tipo \"{0}\".", + "Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015": "El elemento tiene un tipo 'any' implícito porque la expresión de índice no es de tipo 'number'.", + "Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature_7017": "El elemento tiene un tipo \"any\" implícito porque el tipo '{0}' no tiene signatura de índice.", + "Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files_6164": "Emitir una marca BOM UTF-8 al principio de los archivos de salida.", + "Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file_6151": "Emitir un solo archivo con mapas de origen en lugar de tener un archivo aparte.", + "Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap__6152": "Emitir el origen junto a los mapas de origen en un solo archivo; requiere que se establezca \"--inlineSourceMap\" o \"--sourceMap\".", + "Enable_all_strict_type_checking_options_6180": "Habilitar todas las opciones de comprobación de tipos estricta.", + "Enable_project_compilation_6302": "Habilitar la compilación de proyecto", + "Enable_strict_checking_of_function_types_6186": "Habilite la comprobación estricta de los tipos de función.", + "Enable_strict_checking_of_property_initialization_in_classes_6187": "Habilite la comprobación estricta de inicialización de propiedades en las clases.", + "Enable_strict_null_checks_6113": "Habilitar comprobaciones estrictas de elementos nulos.", + "Enable_tracing_of_the_name_resolution_process_6085": "Habilitar seguimiento del proceso de resolución de nombres.", + "Enable_verbose_logging_6366": "Habilitar el registro detallado", + "Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for__7037": "Permite emitir interoperabilidad entre módulos CommonJS y ES mediante la creación de objetos de espacio de nombres para todas las importaciones. Implica \"allowSyntheticDefaultImports\".", + "Enables_experimental_support_for_ES7_async_functions_6068": "Habilita la compatibilidad experimental con las funciones asincrónicas de ES7.", + "Enables_experimental_support_for_ES7_decorators_6065": "Habilita la compatibilidad experimental con los elementos Decorator de ES7.", + "Enables_experimental_support_for_emitting_type_metadata_for_decorators_6066": "Habilita la compatibilidad experimental para emitir metadatos de tipo para los elementos Decorator.", + "Enum_0_used_before_its_declaration_2450": "Se ha usado la enumeración \"{0}\" antes de declararla.", + "Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations_2567": "Las declaraciones de enumeración solo se pueden combinar con otras declaraciones de enumeración o de espacio de nombres.", + "Enum_declarations_must_all_be_const_or_non_const_2473": "Todas las declaraciones de enumeración deben ser de tipo const o no const.", + "Enum_member_expected_1132": "Se esperaba un miembro de enumeración.", + "Enum_member_must_have_initializer_1061": "El miembro de enumeración debe tener un inicializador.", + "Enum_name_cannot_be_0_2431": "El nombre de la enumeración no puede ser \"{0}\".", + "Enum_type_0_has_members_with_initializers_that_are_not_literals_2535": "El tipo de enumeración \"{0}\" tiene miembros con inicializadores que no son literales.", + "Examples_Colon_0_6026": "Ejemplos: {0}", + "Excessive_stack_depth_comparing_types_0_and_1_2321": "Profundidad excesiva de la pila al comparar los tipos '{0}' y '{1}'.", + "Expected_0_1_type_arguments_provide_these_with_an_extends_tag_8027": "Se esperaban argumentos de tipo {0}-{1}; proporciónelos con una etiqueta \"@extends\".", + "Expected_0_arguments_but_got_1_2554": "Se esperaban {0} argumentos, pero se obtuvieron {1}.", + "Expected_0_arguments_but_got_1_or_more_2556": "Se esperaban {0} argumentos, pero se obtuvieron {1} o más.", + "Expected_0_type_arguments_but_got_1_2558": "Se esperaban {0} argumentos de tipo, pero se obtuvieron {1}.", + "Expected_0_type_arguments_provide_these_with_an_extends_tag_8026": "Se esperaban argumentos de tipo {0}; proporciónelos con una etiqueta \"@extends\".", + "Expected_at_least_0_arguments_but_got_1_2555": "Se esperaban al menos {0} argumentos, pero se obtuvieron {1}.", + "Expected_at_least_0_arguments_but_got_1_or_more_2557": "Se esperaban al menos {0} argumentos, pero se obtuvieron {1} o más.", + "Expected_corresponding_JSX_closing_tag_for_0_17002": "Se esperaba la etiqueta de cierre JSX correspondiente de '{0}'.", + "Expected_corresponding_closing_tag_for_JSX_fragment_17015": "Se esperaba la etiqueta de cierre correspondiente para el fragmento de JSX.", + "Expected_type_of_0_field_in_package_json_to_be_string_got_1_6105": "Se esperaba que el tipo del campo '{0}' en 'package.json' fuese 'string', pero se obtuvo '{1}'.", + "Experimental_Options_6177": "Opciones experimentales", + "Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_t_1219": "La compatibilidad experimental con decoradores es una característica que está sujeta a cambios en una próxima versión. Establezca la opción 'experimentalDecorators' para quitar esta advertencia.", + "Explicitly_specified_module_resolution_kind_Colon_0_6087": "Tipo de resolución de módulo especificado de forma explícita: '{0}'.", + "Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or__1203": "No se puede usar una asignación de exportación cuando se eligen módulos de ECMAScript como destino. Considere la posibilidad de usar \"export default\" u otro formato de módulo en su lugar.", + "Export_assignment_is_not_supported_when_module_flag_is_system_1218": "La asignación de exportación no es compatible cuando la marca \"--module\" es \"system\".", + "Export_declaration_conflicts_with_exported_declaration_of_0_2484": "La declaración de exportación está en conflicto con la declaración exportada de \"{0}\".", + "Export_declarations_are_not_permitted_in_a_namespace_1194": "No se permiten declaraciones de exportación en un espacio de nombres.", + "Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_2656": "El archivo '{0}' de escritura del paquete externo exportado no es un módulo. Póngase en contacto con el autor del paquete para actualizar la definición de este.", + "Exported_external_package_typings_file_cannot_contain_tripleslash_references_Please_contact_the_pack_2654": "El archivo de escritura del paquete externo exportado no puede contener referencias con tres barras diagonales. Póngase en contacto con el autor del paquete para actualizar la definición de este.", + "Exported_type_alias_0_has_or_is_using_private_name_1_4081": "El alias de tipo exportado '{0}' tiene o usa el nombre privado '{1}'.", + "Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4023": "La variable exportada '{0}' tiene o usa el nombre '{1}' del módulo {2} externo, pero no se puede nombrar.", + "Exported_variable_0_has_or_is_using_name_1_from_private_module_2_4024": "La variable exportada '{0}' tiene o usa el nombre '{1}' del módulo '{2}' privado.", + "Exported_variable_0_has_or_is_using_private_name_1_4025": "La variable exportada '{0}' tiene o usa el nombre privado '{1}'.", + "Exports_and_export_assignments_are_not_permitted_in_module_augmentations_2666": "En aumentos de módulos, no se admiten exportaciones ni asignaciones de exportación.", + "Expression_expected_1109": "Se esperaba una expresión.", + "Expression_or_comma_expected_1137": "Se esperaba una expresión o una coma.", + "Expression_resolves_to_super_that_compiler_uses_to_capture_base_class_reference_2402": "La expresión se resuelve en el valor \"_super\" que el compilador usa para capturar una referencia a la clase base.", + "Expression_resolves_to_variable_declaration_0_that_compiler_uses_to_support_async_functions_2521": "La expresión se resuelve en la declaración de variable '{0}' que el compilador usa para admitir funciones asincrónicas.", + "Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta__2544": "La expresión se resuelve en una declaración de variable \"_newTarget\" que el compilador usa para capturar la referencia de la propiedad Meta \"new.target\".", + "Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference_2400": "La expresión se resuelve en la declaración de variable \"_this\" que el compilador usa para capturar una referencia \"this\".", + "Extract_constant_95006": "Extraer la constante", + "Extract_function_95005": "Extraer la función", + "Extract_to_0_in_1_95004": "Extraer a {0} en {1}", + "Extract_to_0_in_1_scope_95008": "Extraer a {0} en el ámbito {1}", + "Extract_to_0_in_enclosing_scope_95007": "Extraer a {0} en el ámbito de inclusión", + "FILE_6035": "ARCHIVO", + "FILE_OR_DIRECTORY_6040": "ARCHIVO O DIRECTORIO", + "Failed_to_parse_file_0_Colon_1_5014": "Error al analizar el archivo '{0}': {1}.", + "Fallthrough_case_in_switch_7029": "Caso de Fallthrough en instrucción switch.", + "File_0_does_not_exist_6096": "El archivo '{0}' no existe.", + "File_0_exist_use_it_as_a_name_resolution_result_6097": "El archivo '{0}' existe. Utilícelo como resultado de resolución de nombres.", + "File_0_has_an_unsupported_extension_so_skipping_it_6081": "El archivo \"{0}\" tiene una extensión no admitida, así que se omitirá.", + "File_0_has_unsupported_extension_The_only_supported_extensions_are_1_6054": "La extensión del archivo '{0}' no es compatible. Las únicas extensiones compatibles son {1}.", + "File_0_is_not_a_module_2306": "El archivo '{0}' no es un módulo.", + "File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern_6307": "El archivo \"{0}\" no está en la lista de archivos del proyecto. Los proyectos deben enumerar todos los archivos o usar un patrón \"include\".", + "File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files_6059": "El archivo '{0}' no está en \"rootDir\" '{1}'. Se espera que \"rootDir\" contenga todos los archivos de origen.", + "File_0_not_found_6053": "Archivo '{0}' no encontrado.", + "File_change_detected_Starting_incremental_compilation_6032": "Se detectó un cambio de archivo. Iniciando la compilación incremental...", + "File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module_80001": "El archivo es un módulo CommonJS; se puede convertir a un módulo ES6.", + "File_name_0_differs_from_already_included_file_name_1_only_in_casing_1149": "El nombre de archivo \"{0}\" es diferente del nombre de archivo \"{1}\" ya incluido solo en el uso de mayúsculas y minúsculas.", + "File_name_0_has_a_1_extension_stripping_it_6132": "El nombre de archivo \"{0}\" tiene una extensión \"{1}\" y se va a quitar.", + "File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildca_5065": "La especificación del archivo no puede contener un directorio primario ('..') que aparezca después de un comodín de directorios recursivo ('**'): '{0}'.", + "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010": "La especificación de archivo no puede finalizar en un comodín de directorio recursivo ('**'): '{0}'.", + "Fix_all_detected_spelling_errors_95026": "Corregir todos los errores ortográficos detectados", + "Found_0_errors_Watching_for_file_changes_6194": "Se encontraron {0} errores. Supervisando los cambios del archivo.", + "Found_1_error_Watching_for_file_changes_6193": "Se encontró un error. Supervisando los cambios del archivo.", + "Found_package_json_at_0_6099": "Se encontró 'package.json' en '{0}'.", + "Found_package_json_at_0_Package_ID_is_1_6190": "Se encontró \"package.json\" en \"{0}\". El identificador de paquete es \"{1}\".", + "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_1250": "No se permiten declaraciones de función en bloques en modo strict cuando el destino es 'ES3' o 'ES5'.", + "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_d_1251": "No se permiten declaraciones de función en bloques en modo strict cuando el destino es 'ES3' o 'ES5'. Las definiciones de clase están en modo strict de forma automática.", + "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_1252": "No se permiten declaraciones de función en bloques en modo strict cuando el destino es 'ES3' o 'ES5'. Los módulos están en modo strict de forma automática.", + "Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type_7011": "La expresión de función, que carece de una anotación de tipo de valor devuelto, tiene implícitamente un tipo de valor devuelto '{0}'.", + "Function_implementation_is_missing_or_not_immediately_following_the_declaration_2391": "Falta la implementación de función o no sigue inmediatamente a la declaración.", + "Function_implementation_name_must_be_0_2389": "El nombre de la implementación de función debe ser '{0}'.", + "Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_ref_7024": "La función tiene el tipo de valor devuelto \"any\" implícitamente porque no tiene una anotación de tipo de valor devuelto y se hace referencia a ella directa o indirectamente en una de sus expresiones return.", + "Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined_2366": "Falta la instrucción return final en la función y el tipo de valor devuelto no incluye 'undefined'.", + "Function_overload_must_be_static_2387": "La sobrecarga de función debe ser estática.", + "Function_overload_must_not_be_static_2388": "La sobrecarga de función no debe ser estática.", + "Generate_get_and_set_accessors_95046": "Generar los descriptores de acceso \"get\" y \"set\"", + "Generates_a_sourcemap_for_each_corresponding_d_ts_file_6000": "Genera un mapa de origen para cada archivo \".d.ts\" correspondiente.", + "Generates_corresponding_d_ts_file_6002": "Genera el archivo \".d.ts\" correspondiente.", + "Generates_corresponding_map_file_6043": "Genera el archivo \".map\" correspondiente.", + "Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_typ_7025": "El generador tiene el tipo '{0}' implícitamente porque no produce ningún valor. Considere la posibilidad de proporcionar un tipo de valor devuelto.", + "Generators_are_not_allowed_in_an_ambient_context_1221": "Los generadores no se permiten en un contexto de ambiente.", + "Generators_are_only_available_when_targeting_ECMAScript_2015_or_higher_1220": "Los generadores solo están disponibles cuando el destino es ECMAScript 2015 o una versión posterior.", + "Generic_type_0_requires_1_type_argument_s_2314": "El tipo genérico '{0}' requiere los siguientes argumentos de tipo: {1}.", + "Generic_type_0_requires_between_1_and_2_type_arguments_2707": "El tipo genérico \"{0}\" requiere entre {1} y {2} argumentos de tipo.", + "Generic_type_instantiation_is_excessively_deep_and_possibly_infinite_2550": "La creación de instancias de tipo genérico es excesivamente profunda y posiblemente infinita.", + "Getter_and_setter_accessors_do_not_agree_in_visibility_2379": "Los descriptores de acceso de captador y establecedor no se corresponden respecto a la visibilidad.", + "Global_module_exports_may_only_appear_at_top_level_1316": "Las exportaciones de módulos globales solo pueden aparecer en el nivel superior.", + "Global_module_exports_may_only_appear_in_declaration_files_1315": "Las exportaciones de módulos globales solo pueden aparecer en archivos de declaración.", + "Global_module_exports_may_only_appear_in_module_files_1314": "Las exportaciones de módulos globales solo pueden aparecer en archivos de módulo.", + "Global_type_0_must_be_a_class_or_interface_type_2316": "El tipo global '{0}' debe ser un tipo de clase o de interfaz.", + "Global_type_0_must_have_1_type_parameter_s_2317": "El tipo global '{0}' debe tener los siguientes parámetros de tipo: {1}.", + "Hexadecimal_digit_expected_1125": "Se esperaba un dígito hexadecimal.", + "Identifier_expected_0_is_a_reserved_word_in_strict_mode_1212": "Se esperaba un identificador. \"{0}\" es una palabra reservada en modo strict.", + "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_stric_1213": "Se esperaba un identificador. '{0}' es una palabra reservada en modo strict. Las definiciones de clase están en modo strict automáticamente.", + "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode_1214": "Se esperaba un identificador. '{0}' es una palabra reservada en modo strict. Los módulos están en modo strict automáticamente.", + "Identifier_expected_1003": "Se esperaba un identificador.", + "Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules_1216": "Identificador esperado. \"__esModule\" está reservado como marcador exportado al transformar módulos ECMAScript.", + "Ignore_this_error_message_90019": "Ignorar este mensaje de error", + "Implement_all_inherited_abstract_classes_95040": "Implementar todas las clases abstractas heredadas", + "Implement_all_unimplemented_interfaces_95032": "Implementar todas las interfaces no implementadas", + "Implement_inherited_abstract_class_90007": "Implementar clase abstracta heredada", + "Implement_interface_0_90006": "Implementar la interfaz \"{0}\"", + "Implements_clause_of_exported_class_0_has_or_is_using_private_name_1_4019": "La cláusula implements de la clase '{0}' exportada tiene o usa el nombre privado '{1}'.", + "Import_0_from_module_1_90013": "Importar \"{0}\" desde el módulo \"{1}\"", + "Import_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_import_Asterisk_as_1202": "No se puede usar una asignación de importación cuando se eligen módulos de ECMAScript como destino. Considere la posibilidad de usar \"import * as ns from 'mod'\", \"import {a} from 'mod'\", \"import d from 'mod'\" u otro formato de módulo en su lugar.", + "Import_declaration_0_is_using_private_name_1_4000": "La declaración de importación '{0}' usa el nombre privado '{1}'.", + "Import_declaration_conflicts_with_local_declaration_of_0_2440": "La declaración de importación está en conflicto con la declaración local de \"{0}\".", + "Import_declarations_in_a_namespace_cannot_reference_a_module_1147": "Las declaraciones de importación de un espacio de nombres no pueden hacer referencia a un módulo.", + "Import_emit_helpers_from_tslib_6139": "Importe asistentes de emisión de \"tslib\".", + "Import_may_be_converted_to_a_default_import_80003": "La importación puede convertirse a una importación predeterminada.", + "Import_name_cannot_be_0_2438": "El nombre de importación no puede ser \"{0}\".", + "Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relati_2439": "La declaración de importación o exportación de una declaración de módulo de ambiente no puede hacer referencia al módulo a través de su nombre relativo.", + "Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_mod_2667": "No se permiten importaciones en aumentos de módulos. Considere la posibilidad de moverlas al módulo externo envolvente.", + "In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066": "En las declaraciones de enumeración de ambiente, el inicializador de miembro debe ser una expresión constante.", + "In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enu_2432": "En una enumeración con varias declaraciones, solo una declaración puede omitir un inicializador para el primer elemento de la enumeración.", + "In_const_enum_declarations_member_initializer_must_be_constant_expression_2474": "El inicializador de miembro de las declaraciones de enumeración \"const\" debe ser una expresión constante.", + "Include_modules_imported_with_json_extension_6197": "Incluir módulos importados con la extensión \".json\"", + "Index_signature_in_type_0_only_permits_reading_2542": "La signatura de índice del tipo '{0}' solo permite lectura.", + "Index_signature_is_missing_in_type_0_2329": "Falta la signatura de índice en el tipo '{0}'.", + "Index_signatures_are_incompatible_2330": "Las signaturas de índice no son compatibles.", + "Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local_2395": "Las declaraciones individuales de la declaración '{0}' combinada deben ser todas exportadas o todas locales.", + "Infer_all_types_from_usage_95023": "Deducir todos los tipos del uso", + "Infer_parameter_types_from_usage_95012": "Deducir los tipos de parámetro del uso", + "Infer_type_of_0_from_usage_95011": "Deducir el tipo de \"{0}\" del uso", + "Initialize_property_0_in_the_constructor_90020": "Inicializar la propiedad \"{0}\" en el constructor", + "Initialize_static_property_0_90021": "Inicializar la propiedad estática \"{0}\"", + "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301": "El inicializador de la variable miembro de instancia '{0}' no puede hacer referencia al identificador '{1}' declarado en el constructor.", + "Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it_2373": "El inicializador del parámetro '{0}' no puede hacer referencia al identificador '{1}' declarado después.", + "Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value_2525": "El inicializador no proporciona ningún valor para este elemento de enlace que, a su vez, no tiene un valor predeterminado.", + "Initializers_are_not_allowed_in_ambient_contexts_1039": "No se permiten inicializadores en los contextos de ambiente.", + "Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file_6070": "Inicializa un proyecto de TypeScript y crea un archivo tsconfig.json.", + "Insert_command_line_options_and_files_from_a_file_6030": "Inserte opciones de la línea de comandos y archivos desde un archivo.", + "Install_0_95014": "Instalar \"{0}\"", + "Install_all_missing_types_packages_95033": "Instalar todos los paquetes de tipos que faltan", + "Interface_0_cannot_simultaneously_extend_types_1_and_2_2320": "La interfaz '{0}' no puede extender los tipos '{1}' y '{2}' simultáneamente.", + "Interface_0_incorrectly_extends_interface_1_2430": "La interfaz '{0}' extiende la interfaz '{1}' de forma incorrecta.", + "Interface_declaration_cannot_have_implements_clause_1176": "La declaración de interfaz no puede tener una cláusula \"implements\".", + "Interface_name_cannot_be_0_2427": "El nombre de la interfaz no puede ser \"{0}\".", + "Invalid_character_1127": "Carácter no válido.", + "Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augm_2665": "Nombre de módulo no válido en el aumento. El módulo '{0}' se resuelve como un módulo sin tipo en '{1}', que no se puede aumentar.", + "Invalid_module_name_in_augmentation_module_0_cannot_be_found_2664": "Nombre de módulo no válido en un aumento, no se encuentra el módulo '{0}'.", + "Invalid_reference_directive_syntax_1084": "Sintaxis de la directiva \"reference\" no válida.", + "Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode_1210": "Uso no válido de '{0}'. Las definiciones de clase están en modo strict automáticamente.", + "Invalid_use_of_0_Modules_are_automatically_in_strict_mode_1215": "Uso de '{0}' no válido. Los módulos están en modo strict automáticamente.", + "Invalid_use_of_0_in_strict_mode_1100": "Uso no válido de '{0}' en modo strict.", + "Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name_5067": "Valor no válido para \"jsxFactory\". \"{0}\" no es un nombre calificado o un identificador válido.", + "Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier_5059": "Valor no válido para '--reactNamespace'. '{0}' no es un identificador válido.", + "JSDoc_0_1_does_not_match_the_extends_2_clause_8023": "La etiqueta \"@{0} {1}\" de JSDoc no coincide con la cláusula \"extends {2}\".", + "JSDoc_0_is_not_attached_to_a_class_8022": "La etiqueta \"@{0}\" de JSDoc no está asociada a una clase.", + "JSDoc_may_only_appear_in_the_last_parameter_of_a_signature_8028": "\"...\" de JSDoc solo puede aparecer en el último parámetro de una signatura.", + "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_8024": "La etiqueta \"@param\" de JSDoc tiene el nombre \"{0}\", pero no hay ningún parámetro con ese nombre.", + "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_h_8029": "La etiqueta de JSDoc \"@param\" tiene el nombre \"{0}\", pero no hay ningún parámetro con ese nombre. Coincidiría con \"arguments\" si tuviera un tipo de matriz.", + "JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags_8021": "La etiqueta \"@typedef\" de JSDoc debe tener una anotación de tipo o ir seguida de las etiquetas \"@property\" o \"@member\".", + "JSDoc_types_can_only_be_used_inside_documentation_comments_8020": "Los tipos JSDoc solo se pueden usar en los comentarios de la documentación.", + "JSDoc_types_may_be_moved_to_TypeScript_types_80004": "Los tipos de JSDoc pueden moverse a tipos de TypeScript.", + "JSX_attribute_expected_17003": "Se esperaba un atributo JSX.", + "JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000": "A los atributos JSX se les debe asignar únicamente un elemento \"expression\" que no esté vacío.", + "JSX_element_0_has_no_corresponding_closing_tag_17008": "El elemento JSX '{0}' no tiene la etiqueta de cierre correspondiente.", + "JSX_element_attributes_type_0_may_not_be_a_union_type_2600": "El tipo '{0}' de los atributos del elemento JSX no puede ser un tipo de unión.", + "JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property_2607": "La clase de elemento JSX no admite atributos porque no tiene una propiedad \"{0}\".", + "JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists_7026": "El elemento JSX tiene el tipo \"any\" implícitamente porque no existe ninguna interfaz \"JSX.{0}\".", + "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602": "El elemento JSX tiene el tipo \"any\" implícitamente porque no existe el tipo global \"JSX.Element\".", + "JSX_element_type_0_does_not_have_any_construct_or_call_signatures_2604": "El tipo de elemento JSX '{0}' no tiene ninguna signatura de construcción ni de llamada.", + "JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements_2605": "El tipo de elemento JSX '{0}' no es una función de constructor de los elementos JSX.", + "JSX_elements_cannot_have_multiple_attributes_with_the_same_name_17001": "Los elementos JSX no pueden tener varios atributos con el mismo nombre.", + "JSX_expressions_must_have_one_parent_element_2657": "Las expresiones JSX deben tener un elemento primario.", + "JSX_fragment_has_no_corresponding_closing_tag_17014": "El fragmento de JSX no tiene la etiqueta de cierre correspondiente.", + "JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma_17017": "El fragmento JSX no se admite cuando se usa una pragma de fábrica JSX en línea", + "JSX_fragment_is_not_supported_when_using_jsxFactory_17016": "El fragmento de JSX no es compatible cuando se utiliza --jsxFactory", + "JSX_spread_child_must_be_an_array_type_2609": "El elemento secundario de propagación JSX debe ser de tipo matriz.", + "Jump_target_cannot_cross_function_boundary_1107": "Un destino de salto no puede atravesar el límite de función.", + "KIND_6034": "TIPO", + "LOCATION_6037": "UBICACIÓN", + "Language_service_is_disabled_9004": "El servicio de idioma está deshabilitado.", + "Left_side_of_comma_operator_is_unused_and_has_no_side_effects_2695": "La parte izquierda del operador de coma no se usa y no tiene efectos secundarios.", + "Line_break_not_permitted_here_1142": "No se permite el salto de línea aquí.", + "Line_terminator_not_permitted_before_arrow_1200": "No se permite usar un terminador de línea antes de una flecha.", + "List_of_folders_to_include_type_definitions_from_6161": "Lista de carpetas de donde se deben incluir las definiciones de tipos.", + "List_of_language_service_plugins_6181": "Lista de complementos de servicio de lenguaje.", + "List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime_6168": "Lista de carpetas raíz cuyo contenido combinado representa la estructura del proyecto en tiempo de ejecución.", + "Loading_0_from_the_root_dir_1_candidate_location_2_6109": "Cargando \"{0}\" del directorio raíz \"{1}\", ubicación candidata: \"{2}\"", + "Loading_module_0_from_node_modules_folder_target_file_type_1_6098": "Se cargará el módulo \"{0}\" de la carpeta \"node_modules\", tipo de archivo de destino \"{1}\".", + "Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1_6095": "Se cargará el módulo como archivo/carpeta, ubicación del módulo candidato \"{0}\", tipo de archivo de destino \"{1}\".", + "Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1_6048": "La configuración regional debe tener el formato o -. Por ejemplo, '{0}' o '{1}'.", + "Longest_matching_prefix_for_0_is_1_6108": "El prefijo coincidente más largo para \"{0}\" es \"{1}\".", + "Looking_up_in_node_modules_folder_initial_location_0_6125": "Buscando en la carpeta \"node_modules\", ubicación inicial: \"{0}\".", + "Make_all_super_calls_the_first_statement_in_their_constructor_95036": "Convertir todas las llamadas a \"super()\" en la primera instrucción de su constructor", + "Make_super_call_the_first_statement_in_the_constructor_90002": "Hacer que la llamada a \"super()\" sea la primera instrucción del constructor", + "Mapped_object_type_implicitly_has_an_any_template_type_7039": "El tipo de objeto asignado tiene implícitamente un tipo de plantilla \"any\".", + "Member_0_implicitly_has_an_1_type_7008": "El miembro '{0}' tiene un tipo '{1}' implícitamente.", + "Merge_conflict_marker_encountered_1185": "Se encontró un marcador de conflicto de combinación.", + "Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_d_2652": "La declaración combinada '{0}' no puede incluir una declaración de exportación predeterminada. Considere la posibilidad de agregar una declaración \"export default {0}\" independiente en su lugar.", + "Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constru_17013": "La propiedad Meta \"{0}\" solo se permite en el cuerpo de una declaración de función, una expresión de función o un constructor.", + "Method_0_cannot_have_an_implementation_because_it_is_marked_abstract_1245": "El método '{0}' no puede tener ninguna implementación porque está marcado como abstracto.", + "Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4101": "El método \"{0}\" de la interfaz exportada tiene o usa el nombre \"{1}\" del módulo privado \"{2}\".", + "Method_0_of_exported_interface_has_or_is_using_private_name_1_4102": "El método \"{0}\" de la interfaz exportada tiene o usa el nombre privado \"{1}\".", + "Modifiers_cannot_appear_here_1184": "Los modificadores no pueden aparecer aquí.", + "Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_1340": "El módulo \"{0}\" no hace referencia a un tipo, pero aquí se usa como tipo.", + "Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here_1339": "El módulo \"{0}\" no hace referencia a un valor, pero aquí se usa como valor.", + "Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambig_2308": "El módulo {0} ya ha exportado un miembro denominado '{1}'. Considere la posibilidad de volver a exportarlo de forma explícita para resolver la ambigüedad.", + "Module_0_has_no_default_export_1192": "El módulo '{0}' no tiene ninguna exportación predeterminada.", + "Module_0_has_no_exported_member_1_2305": "El módulo '{0}' no tiene ningún miembro '{1}' exportado.", + "Module_0_has_no_exported_member_1_Did_you_mean_2_2724": "El módulo \"{0}\" no tiene ningún miembro exportado \"{1}\". ¿Pretendía utilizar \"{2}\"?", + "Module_0_is_hidden_by_a_local_declaration_with_the_same_name_2437": "El módulo \"{0}\" está oculto por una declaración local con el mismo nombre.", + "Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct_2497": "El módulo '{0}' se resuelve en una entidad que no es un módulo y no se puede importar mediante esta construcción.", + "Module_0_uses_export_and_cannot_be_used_with_export_Asterisk_2498": "El módulo '{0}' usa \"export =\" y no se puede usar con \"export *\".", + "Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified_6145": "El módulo '{0}' se resolvió como un módulo de ambiente declarado en '{1}', porque este archivo no se había modificado.", + "Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1_6144": "El módulo '{0}' se resolvió como un módulo de ambiente declarado localmente en el archivo '{1}'.", + "Module_0_was_resolved_to_1_but_jsx_is_not_set_6142": "El módulo '{0}' se resolvió en '{1}', pero \"--jsx\" no está establecido.", + "Module_Resolution_Options_6174": "Opciones de resolución de módulo", + "Module_name_0_matched_pattern_1_6092": "Nombre del módulo: '{0}', patrón coincidente: '{1}'.", + "Module_name_0_was_not_resolved_6090": "======== No se resolvió el nombre de módulo '{0}'. ========", + "Module_name_0_was_successfully_resolved_to_1_6089": "======== El nombre del módulo '{0}' se resolvió correctamente como '{1}'. ========", + "Module_resolution_kind_is_not_specified_using_0_6088": "No se ha especificado el tipo de resolución del módulo, se usará '{0}'.", + "Module_resolution_using_rootDirs_has_failed_6111": "No se pudo resolver el módulo con \"rootDirs\".", + "Move_to_a_new_file_95049": "Mover a un nuevo archivo", + "Multiple_consecutive_numeric_separators_are_not_permitted_6189": "No se permiten varios separadores numéricos consecutivos.", + "Multiple_constructor_implementations_are_not_allowed_2392": "No se permiten varias implementaciones del constructor.", + "NEWLINE_6061": "NUEVA LÍNEA", + "Named_property_0_of_types_1_and_2_are_not_identical_2319": "La propiedad '{0}' con nombre de los tipos '{1}' y '{2}' no es idéntica en ambos.", + "Namespace_0_has_no_exported_member_1_2694": "El espacio de nombres '{0}' no tiene ningún miembro '{1}' exportado.", + "No_base_constructor_has_the_specified_number_of_type_arguments_2508": "No hay ningún constructor base con el número especificado de argumentos de tipo.", + "No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2_18003": "No se encontraron entradas en el archivo de configuración '{0}'. Las rutas 'include' especificadas fueron '{1}' y las rutas 'exclude' fueron '{2}'.", + "Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2_2515": "La clase '{0}' no abstracta no implementa el miembro abstracto heredado '{1}' de la clase '{2}'.", + "Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1_2653": "Una expresión de clase no abstracta no implementa el miembro abstracto heredado '{0}' de la clase '{1}'.", + "Not_all_code_paths_return_a_value_7030": "No todas las rutas de acceso de código devuelven un valor.", + "Numeric_index_type_0_is_not_assignable_to_string_index_type_1_2413": "El tipo de índice numérico '{0}' no se puede asignar a un tipo de índice de cadena '{1}'.", + "Numeric_separators_are_not_allowed_here_6188": "Aquí no se permiten separadores numéricos.", + "Object_is_of_type_unknown_2571": "El objeto es de tipo \"desconocido\".", + "Object_is_possibly_null_2531": "El objeto es posiblemente \"null\".", + "Object_is_possibly_null_or_undefined_2533": "El objeto es posiblemente \"null\" o \"undefined\".", + "Object_is_possibly_undefined_2532": "El objeto es posiblemente \"undefined\".", + "Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1_2353": "El literal de objeto solo puede especificar propiedades conocidas y '{0}' no existe en el tipo '{1}'.", + "Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_writ_2561": "El literal de objeto solo puede especificar propiedades conocidas, pero \"{0}\" no existe en el tipo \"{1}\". ¿Quería escribir \"{2}\"?", + "Object_literal_s_property_0_implicitly_has_an_1_type_7018": "La propiedad '{0}' del literal de objeto tiene un tipo '{1}' implícitamente.", + "Octal_digit_expected_1178": "Se esperaba un dígito octal.", + "Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0_8017": "Los tipos de literales octales deben usar la sintaxis ES2015. Use la sintaxis \"{0}\".", + "Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0_8018": "No se permiten literales octales en el inicializador de miembros de enumeraciones. Use la sintaxis \"{0}\".", + "Octal_literals_are_not_allowed_in_strict_mode_1121": "Los literales octales no se permiten en modo strict.", + "Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0_1085": "Los literales octales no están disponibles cuando el destino es ECMAScript 5 y superior. Use la sintaxis \"{0}\".", + "Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement_1091": "Solo se permite una declaración de variable en una instrucción \"for...in\".", + "Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement_1188": "Solo se permite una declaración de variable en una instrucción \"for...of\".", + "Only_a_void_function_can_be_called_with_the_new_keyword_2350": "Solo se puede llamar a una función void con la palabra clave \"new\".", + "Only_ambient_modules_can_use_quoted_names_1035": "Solo los módulos de ambiente pueden usar nombres entrecomillados.", + "Only_amd_and_system_modules_are_supported_alongside_0_6082": "Solo los módulos \"amd\" y \"system\" se admiten con --{0}.", + "Only_emit_d_ts_declaration_files_6014": "Solo deben emitirse archivos de declaración \".d.ts\".", + "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002": "Actualmente, solo se admiten identificadores o nombres completos con argumentos de tipo opcional en la cláusula \"extends\" de una clase.", + "Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword_2340": "Solo es posible tener acceso a los métodos públicos y protegidos de la clase base mediante la palabra clave \"super\".", + "Operator_0_cannot_be_applied_to_types_1_and_2_2365": "El operador '{0}' no se puede aplicar a los tipos '{1}' y '{2}'.", + "Option_0_can_only_be_specified_in_tsconfig_json_file_6064": "La opción '{0}' solo se puede especificar en el archivo 'tsconfig.json'.", + "Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided_5051": "La opción '{0}' solo se puede usar cuando se proporciona '--inlineSourceMap' o '--sourceMap'.", + "Option_0_cannot_be_specified_with_option_1_5053": "La opción '{0}' no se puede especificar con la opción '{1}'.", + "Option_0_cannot_be_specified_without_specifying_option_1_5052": "La opción '{0}' no se puede especificar sin la opción '{1}'.", + "Option_0_cannot_be_specified_without_specifying_option_1_or_option_2_5069": "La opción \"{0}\" no se puede especificar sin la opción \"{1}\" o la opción \"{2}\".", + "Option_0_should_have_array_of_strings_as_a_value_6103": "La opción '{0}' debe tener una matriz de cadenas como valor.", + "Option_build_must_be_the_first_command_line_argument_6369": "La opción \"--build\" debe ser el primer argumento de la línea de comandos.", + "Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES_5047": "La opción \"isolatedModules\" solo se puede usar cuando se proporciona la opción \"--module\" o si la opción \"target\" es \"ES2015\" o una versión posterior.", + "Option_paths_cannot_be_used_without_specifying_baseUrl_option_5060": "La opción 'paths' no se puede usar sin especificar la opción '--baseUrl'.", + "Option_project_cannot_be_mixed_with_source_files_on_a_command_line_5042": "La opción \"project\" no se puede combinar con archivos de origen en una línea de comandos.", + "Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070": "No se puede especificar la opción \"--resolveJsonModule\" sin la estrategia de resolución de módulos \"node\".", + "Options_0_and_1_cannot_be_combined_6370": "\"{0}\" y \"{1}\" no se pueden combinar.", + "Options_Colon_6027": "Opciones:", + "Output_directory_for_generated_declaration_files_6166": "Directorio de salida para los archivos de declaración generados.", + "Output_file_0_from_project_1_does_not_exist_6309": "El archivo de salida \"{0}\" del proyecto \"{1}\" no existe.", + "Output_file_0_has_not_been_built_from_source_file_1_6305": "El archivo de salida \"{0}\" no se compiló desde el archivo de origen \"{1}\".", + "Overload_signature_is_not_compatible_with_function_implementation_2394": "La signatura de sobrecarga no es compatible con la implementación de función.", + "Overload_signatures_must_all_be_abstract_or_non_abstract_2512": "Las signaturas de sobrecarga deben ser todas abstractas o no abstractas.", + "Overload_signatures_must_all_be_ambient_or_non_ambient_2384": "Las signaturas de sobrecarga deben ser todas de ambiente o de no ambiente.", + "Overload_signatures_must_all_be_exported_or_non_exported_2383": "Las signaturas de sobrecarga deben ser todas exportadas o no exportadas.", + "Overload_signatures_must_all_be_optional_or_required_2386": "Las signaturas de sobrecarga deben ser todas opcionales u obligatorias.", + "Overload_signatures_must_all_be_public_private_or_protected_2385": "Las signaturas de sobrecarga deben ser todas públicas, privadas o protegidas.", + "Parameter_0_cannot_be_referenced_in_its_initializer_2372": "No se puede hacer referencia al parámetro '{0}' en su inicializador.", + "Parameter_0_implicitly_has_an_1_type_7006": "El parámetro '{0}' tiene un tipo '{1}' implícitamente.", + "Parameter_0_is_not_in_the_same_position_as_parameter_1_1227": "El parámetro '{0}' no está en la misma posición que el parámetro '{1}'.", + "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4066": "El parámetro '{0}' de la signatura de llamada de una interfaz exportada tiene o usa el nombre '{1}' del módulo '{2}' privado.", + "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4067": "El parámetro '{0}' de la signatura de llamada de una interfaz exportada tiene o usa el nombre privado '{1}'.", + "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_can_4061": "El parámetro '{0}' del constructor de la clase exportada tiene o usa el nombre '{1}' del módulo {2} externo, pero no se puede nombrar.", + "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2_4062": "El parámetro '{0}' del constructor de la clase exportada tiene o usa el nombre '{1}' del módulo '{2}' privado.", + "Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1_4063": "El parámetro '{0}' del constructor de la clase exportada tiene o usa el nombre privado '{1}'.", + "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_mod_4064": "El parámetro '{0}' de la signatura de constructor de la interfaz exportada tiene o usa el nombre '{1}' del módulo '{2}' privado.", + "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4065": "El parámetro '{0}' de la signatura de constructor de la interfaz exportada tiene o usa el nombre privado '{1}'.", + "Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4076": "El parámetro '{0}' de la función exportada tiene o usa el nombre '{1}' del módulo {2} externo, pero no se puede nombrar.", + "Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2_4077": "El parámetro '{0}' de la función exportada tiene o usa el nombre '{1}' del módulo {2} privado.", + "Parameter_0_of_exported_function_has_or_is_using_private_name_1_4078": "El parámetro '{0}' de la función exportada tiene o usa el nombre privado '{1}'.", + "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4091": "El parámetro \"{0}\" de la signatura de índice de la interfaz exportada tiene o usa el nombre \"{1}\" del módulo privado \"{2}\".", + "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1_4092": "El parámetro \"{0}\" de la signatura de índice de la interfaz exportada tiene o usa el nombre privado \"{1}\".", + "Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4074": "El parámetro '{0}' del método de la interfaz exportada tiene o usa el nombre '{1}' del módulo '{2}' privado.", + "Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4075": "El parámetro '{0}' del método de la interfaz exportada tiene o usa el nombre privado '{1}'.", + "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_c_4071": "El parámetro '{0}' del método público de la clase exportada tiene o usa el nombre '{1}' del módulo {2} externo, pero no se puede nombrar.", + "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4072": "El parámetro '{0}' del método público de la clase exportada tiene o usa el nombre '{1}' del módulo {2} privado.", + "Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4073": "El parámetro '{0}' del método público de la clase exportada tiene o usa el nombre privado '{1}'.", + "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module__4068": "El parámetro '{0}' del método estático público de la clase exportada tiene o usa el nombre '{1}' del módulo {2} externo, pero no se puede nombrar.", + "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4069": "El parámetro '{0}' del método estático público de la clase exportada tiene o usa el nombre '{1}' del módulo {2} privado.", + "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4070": "El parámetro '{0}' del método estático público de la clase exportada tiene o usa el nombre privado '{1}'.", + "Parameter_cannot_have_question_mark_and_initializer_1015": "El parámetro no puede tener un signo de interrogación y un inicializador.", + "Parameter_declaration_expected_1138": "Se espera una declaración de parámetros.", + "Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2_4036": "El tipo de parámetro del establecedor público \"{0}\" de la clase exportada tiene o usa el nombre \"{1}\" del módulo \"{2}\" privado.", + "Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_private_name_1_4037": "El tipo de parámetro del establecedor público \"{0}\" de la clase exportada tiene o usa el nombre privado \"{1}\".", + "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_name_1_from_private_mod_4034": "El tipo de parámetro del establecedor estático público \"{0}\" de la clase exportada tiene o usa el nombre \"{1}\" del módulo \"{2}\" privado.", + "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1_4035": "El tipo de parámetro del establecedor estático público \"{0}\" de la clase exportada tiene o usa el nombre privado \"{1}\".", + "Parse_in_strict_mode_and_emit_use_strict_for_each_source_file_6141": "Analiza en modo strict y emite \"use strict\" para cada archivo de código fuente.", + "Pattern_0_can_have_at_most_one_Asterisk_character_5061": "El patrón \"{0}\" puede tener un carácter '*' como máximo.", + "Prefix_0_with_an_underscore_90025": "Prefijo \"{0}\" con guion bajo", + "Prefix_all_unused_declarations_with_where_possible_95025": "Agregar \"_\" como prefijo a todas las declaraciones sin usar, cuando sea posible", + "Print_names_of_files_part_of_the_compilation_6155": "Imprimir los nombres de los archivos que forman parte de la compilación.", + "Print_names_of_generated_files_part_of_the_compilation_6154": "Imprimir los nombres de los archivos generados que forman parte de la compilación.", + "Print_the_compiler_s_version_6019": "Imprima la versión del compilador.", + "Print_this_message_6017": "Imprima este mensaje.", + "Project_0_can_t_be_built_because_its_dependency_1_has_errors_6363": "El proyecto \"{0}\" no puede generarse porque su dependencia \"{1}\" tiene errores", + "Project_0_is_out_of_date_because_its_dependency_1_is_out_of_date_6353": "El proyecto \"{0}\" está obsoleto porque su dependencia \"{1}\" no está actualizada", + "Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2_6350": "El proyecto \"{0}\" está obsoleto porque la salida más antigua \"{1}\" es anterior a la entrada más reciente \"{2}\"", + "Project_0_is_out_of_date_because_output_file_1_does_not_exist_6352": "El proyecto \"{0}\" está obsoleto porque el archivo de salida \"{1}\" no existe", + "Project_0_is_up_to_date_6361": "El proyecto \"{0}\" está actualizado", + "Project_0_is_up_to_date_because_newest_input_1_is_older_than_oldest_output_2_6351": "El proyecto \"{0}\" está actualizado porque la entrada más reciente \"{1}\" es anterior a la salida más antigua \"{2}\"", + "Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies_6354": "El proyecto \"{0}\" está actualizado con archivos .d.ts de sus dependencias", + "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202": "Las referencias del proyecto no pueden formar un gráfico circular. Ciclo detectado: {0}", + "Projects_in_this_build_Colon_0_6355": "Proyectos de esta compilación: {0}", + "Projects_to_reference_6300": "Proyectos a los que se hará referencia", + "Property_0_does_not_exist_on_const_enum_1_2479": "La propiedad '{0}' no existe en la enumeración 'const' '{1}'.", + "Property_0_does_not_exist_on_type_1_2339": "La propiedad '{0}' no existe en el tipo '{1}'.", + "Property_0_does_not_exist_on_type_1_Did_you_forget_to_use_await_2570": "La propiedad \"{0}\" no existe en el tipo \"{1}\". ¿Olvidó usar \"await\"?", + "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551": "La propiedad \"{0}\" no existe en el tipo \"{1}\". ¿Quería decir \"{2}\"?", + "Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1_2546": "La propiedad \"{0}\" tiene declaraciones en conflicto y no está accesible en el tipo \"{1}\".", + "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor_2564": "La propiedad \"{0}\" no tiene inicializador y no está asignada de forma definitiva en el constructor.", + "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033": "La propiedad '{0}' tiene el tipo 'any' de forma implícita, porque a su descriptor de acceso get le falta una anotación de tipo de valor devuelto.", + "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032": "La propiedad '{0}' tiene el tipo 'any' de forma implícita, porque a su descriptor de acceso set le falta una anotación de tipo de parámetro.", + "Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2_2416": "La propiedad \"{0}\" del tipo \"{1}\" no se puede asignar a la misma propiedad del tipo base \"{2}\".", + "Property_0_in_type_1_is_not_assignable_to_type_2_2603": "La propiedad \"{0}\" del tipo \"{1}\" no se puede asignar al tipo \"{2}\".", + "Property_0_is_declared_but_its_value_is_never_read_6138": "La propiedad \"{0}\" se declara, pero su valor no se lee nunca.", + "Property_0_is_incompatible_with_index_signature_2530": "La propiedad '{0}' es incompatible con la signatura de índice.", + "Property_0_is_missing_in_type_1_2324": "Falta la propiedad '{0}' en el tipo '{1}'.", + "Property_0_is_optional_in_type_1_but_required_in_type_2_2327": "La propiedad '{0}' es opcional en el tipo '{1}', pero obligatoria en el tipo '{2}'.", + "Property_0_is_private_and_only_accessible_within_class_1_2341": "La propiedad '{0}' es privada y solo se puede acceder a ella en la clase '{1}'.", + "Property_0_is_private_in_type_1_but_not_in_type_2_2325": "La propiedad '{0}' es privada en el tipo '{1}', pero no en el tipo '{2}'.", + "Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1_2446": "La propiedad '{0}' está protegida y solo se puede acceder a ella a través de una instancia de la clase '{1}'.", + "Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses_2445": "La propiedad '{0}' está protegida y solo se puede acceder a ella en la clase '{1}' y las subclases de esta.", + "Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2_2443": "La propiedad '{0}' está protegida, pero el tipo '{1}' no es una clase derivada de '{2}'.", + "Property_0_is_protected_in_type_1_but_public_in_type_2_2444": "La propiedad '{0}' está protegida en el tipo '{1}', pero es pública en el tipo '{2}'.", + "Property_0_is_used_before_being_assigned_2565": "La propiedad \"{0}\" se usa antes de asignarla.", + "Property_0_of_JSX_spread_attribute_is_not_assignable_to_target_property_2606": "La propiedad '{0}' del atributo spread de JSX no se puede asignar a la propiedad de destino.", + "Property_0_of_exported_class_expression_may_not_be_private_or_protected_4094": "La propiedad \"{0}\" de la expresión de clase exportada no puede ser privada ni estar protegida.", + "Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4032": "La propiedad '{0}' de la interfaz exportada tiene o usa el nombre '{1}' del módulo '{2}' privado.", + "Property_0_of_exported_interface_has_or_is_using_private_name_1_4033": "La propiedad '{0}' de la interfaz exportada tiene o usa el nombre privado '{1}'.", + "Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2_2412": "La propiedad '{0}' de tipo '{1}' no se puede asignar al tipo de índice numérico '{2}'.", + "Property_0_of_type_1_is_not_assignable_to_string_index_type_2_2411": "La propiedad '{0}' de tipo '{1}' no se puede asignar al tipo de índice de cadena '{2}'.", + "Property_assignment_expected_1136": "Se esperaba una asignación de propiedad.", + "Property_destructuring_pattern_expected_1180": "Se esperaba un patrón de desestructuración de propiedad.", + "Property_or_signature_expected_1131": "Se esperaba una propiedad o una signatura.", + "Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_li_1328": "El valor de la propiedad puede ser solo un literal de cadena, literal numérico, 'true', 'false', 'null', literal de objeto o literal de matriz.", + "Provide_full_support_for_iterables_in_for_of_spread_and_destructuring_when_targeting_ES5_or_ES3_6179": "Proporcionar compatibilidad total con objetos iterables en \"for-of\", propagaciones y desestructuraciones cuando el destino es \"ES5\" o \"ES3\".", + "Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4098": "El método público \"{0}\" de la clase exportada tiene o usa el nombre \"{1}\" del módulo externo {2}, pero no puede tener nombre.", + "Public_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4099": "El método público \"{0}\" de la clase exportada tiene o usa el nombre \"{1}\" del módulo privado \"{2}\".", + "Public_method_0_of_exported_class_has_or_is_using_private_name_1_4100": "El método público \"{0}\" de la clase exportada tiene o usa el nombre privado \"{1}\".", + "Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_name_4029": "La propiedad pública '{0}' de la clase exportada tiene o usa el nombre '{1}' del módulo {2} externo, pero no se puede nombrar.", + "Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4030": "La propiedad pública '{0}' de la clase exportada tiene o usa el nombre '{1}' del módulo '{2}' privado.", + "Public_property_0_of_exported_class_has_or_is_using_private_name_1_4031": "La propiedad pública '{0}' de la clase exportada tiene o usa el nombre privado '{1}'.", + "Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_4095": "El método estático público \"{0}\" de la clase exportada tiene o usa el nombre \"{1}\" del módulo externo {2}, pero no puede tener nombre.", + "Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4096": "El método estático público \"{0}\" de la clase exportada tiene o usa el nombre \"{1}\" del módulo privado \"{2}\".", + "Public_static_method_0_of_exported_class_has_or_is_using_private_name_1_4097": "El método estático público \"{0}\" de la clase exportada tiene o usa el nombre privado \"{1}\".", + "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot__4026": "La propiedad estática pública '{0}' de la clase exportada tiene o usa el nombre '{1}' del módulo {2} externo, pero no se puede nombrar.", + "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4027": "La propiedad estática pública '{0}' de la clase exportada tiene o usa el nombre '{1}' del módulo {2} privado.", + "Public_static_property_0_of_exported_class_has_or_is_using_private_name_1_4028": "La propiedad estática pública '{0}' de la clase exportada tiene o usa el nombre privado '{1}'.", + "Raise_error_on_expressions_and_declarations_with_an_implied_any_type_6052": "Generar un error en las expresiones y las declaraciones con un tipo \"any\" implícito.", + "Raise_error_on_this_expressions_with_an_implied_any_type_6115": "Generar un error en expresiones 'this' con un tipo 'any' implícito.", + "Redirect_output_structure_to_the_directory_6006": "Redirija la estructura de salida al directorio.", + "Referenced_project_0_must_have_setting_composite_Colon_true_6306": "El proyecto \"{0}\" al que se hace referencia debe tener el valor \"composite\": true.", + "Remove_all_unreachable_code_95051": "Quitar todo el código inaccesible", + "Remove_all_unused_labels_95054": "Quitar todas las etiquetas no utilizadas", + "Remove_braces_from_arrow_function_95060": "Quitar las llaves de la función de flecha", + "Remove_declaration_for_Colon_0_90004": "Quitar declaración de: \"{0}\"", + "Remove_destructuring_90009": "Quitar la desestructuración", + "Remove_import_from_0_90005": "Quitar importación de \"{0}\"", + "Remove_unreachable_code_95050": "Quitar el código inaccesible", + "Remove_unused_label_95053": "Quitar etiqueta no utilizada", + "Remove_variable_statement_90010": "Quitar la declaración de variable", + "Replace_import_with_0_95015": "Reemplazar importación por \"{0}\".", + "Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "Notificar un error cuando no todas las rutas de acceso de código en funcionamiento devuelven un valor.", + "Report_errors_for_fallthrough_cases_in_switch_statement_6076": "Notificar errores de los casos de fallthrough en la instrucción switch.", + "Report_errors_in_js_files_8019": "Notifique los errores de los archivos .js.", + "Report_errors_on_unused_locals_6134": "Informe de errores sobre variables locales no usadas.", + "Report_errors_on_unused_parameters_6135": "Informe de errores sobre parámetros no usados.", + "Required_type_parameters_may_not_follow_optional_type_parameters_2706": "Los parámetros de tipo requeridos pueden no seguir parámetros de tipo opcionales.", + "Resolution_for_module_0_was_found_in_cache_from_location_1_6147": "La resolución del módulo \"{0}\" se encontró en la memoria caché de la ubicación \"{1}\".", + "Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols_6195": "Resolver \"keyof\" exclusivamente como nombres de propiedad con valores de cadena (sin números ni símbolos).", + "Resolving_from_node_modules_folder_6118": "Resolviendo desde la carpeta node_modules...", + "Resolving_module_0_from_1_6086": "======== Resolviendo el módulo '{0}' de '{1}'. ========", + "Resolving_module_name_0_relative_to_base_url_1_2_6094": "Resolviendo el nombre de módulo '{0}' relativo a la dirección URL base '{1}' - '{2}'.", + "Resolving_real_path_for_0_result_1_6130": "Resolviendo la ruta de acceso real de \"{0}\", resultado: \"{1}\".", + "Resolving_type_reference_directive_0_containing_file_1_root_directory_2_6116": "======== Resolviendo la directiva de referencia de tipo '{0}', archivo contenedor: '{1}', directorio raíz: '{2}'. ========", + "Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set_6123": "======== Resolviendo la directiva de referencia de tipo '{0}', archivo contenedor: '{1}', directorio raíz no establecido. ========", + "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1_6127": "======== Resolviendo la directiva de referencia de tipo '{0}', archivo contenedor no establecido, directorio raíz: '{1}'. ========", + "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set_6128": "======== Resolviendo la directiva de referencia de tipo '{0}', archivo contenedor no establecido, directorio raíz no establecido. ========", + "Resolving_using_primary_search_paths_6117": "Resolviendo con las rutas de búsqueda principales...", + "Resolving_with_primary_search_path_0_6121": "Resolviendo con la ruta de búsqueda principal \"{0}\".", + "Rest_parameter_0_implicitly_has_an_any_type_7019": "El parámetro rest '{0}' tiene un tipo \"any[]\" implícitamente.", + "Rest_types_may_only_be_created_from_object_types_2700": "Los tipos rest solo se pueden crear a partir de tipos de objeto.", + "Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4046": "El tipo de valor devuelto de la signatura de llamada de la interfaz exportada tiene o usa el nombre '{0}' del módulo '{1}' privado.", + "Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0_4047": "El tipo de valor devuelto de la signatura de llamada de la interfaz exportada tiene o usa el nombre privado '{0}'.", + "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_mod_4044": "El tipo de valor devuelto de la signatura de constructor de la interfaz exportada tiene o usa el nombre '{0}' del módulo '{1}' privado.", + "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0_4045": "El tipo de valor devuelto de la signatura de constructor de la interfaz exportada tiene o usa el nombre privado '{0}'.", + "Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class_2409": "El tipo de valor devuelto de la signatura de constructor se debe poder asignar al tipo de instancia de la clase.", + "Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named_4058": "El tipo de valor devuelto de la función exportada tiene o usa el nombre '{0}' del módulo {1} externo, pero no se puede nombrar.", + "Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1_4059": "El tipo de valor devuelto de la función exportada tiene o usa el nombre '{0}' del módulo {1} privado.", + "Return_type_of_exported_function_has_or_is_using_private_name_0_4060": "El tipo de valor devuelto de la función exportada tiene o usa el nombre privado '{0}'.", + "Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4048": "El tipo de valor devuelto de la signatura de índice de la interfaz exportada tiene o usa el nombre '{0}' del módulo '{1}' privado.", + "Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0_4049": "El tipo de valor devuelto de la signatura de índice de la interfaz exportada tiene o usa el nombre privado '{0}'.", + "Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4056": "El tipo de valor devuelto del método de la interfaz exportada tiene o usa el nombre '{0}' del módulo '{1}' privado.", + "Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0_4057": "El tipo de valor devuelto del método de la interfaz exportada tiene o usa el nombre privado '{0}'.", + "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_4041": "El tipo de valor devuelto del captador público \"{0}\" de la clase exportada tiene o usa el nombre \"{1}\" del módulo {2} externo, pero no se puede nombrar.", + "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2_4042": "El tipo de valor devuelto del captador público \"{0}\" de la clase exportada tiene o usa el nombre \"{1}\" del módulo \"{2}\" privado.", + "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_private_name_1_4043": "El tipo de valor devuelto del captador público \"{0}\" de la clase exportada tiene o usa el nombre privado \"{1}\".", + "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_c_4053": "El tipo de valor devuelto del método público de la clase exportada tiene o usa el nombre '{0}' del módulo {1} externo, pero no se puede nombrar.", + "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4054": "El tipo de valor devuelto del método público de la clase exportada tiene o usa el nombre '{0}' del módulo {1} privado.", + "Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0_4055": "El tipo de valor devuelto del método público de la clase exportada tiene o usa el nombre privado '{0}'.", + "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_external_modul_4038": "El tipo de valor devuelto del captador estático público \"{0}\" de la clase exportada tiene o usa el nombre \"{1}\" del módulo {2} externo, pero no se puede nombrar.", + "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_4039": "El tipo de valor devuelto del captador estático público \"{0}\" de la clase exportada tiene o usa el nombre \"{1}\" del módulo \"{2}\" privado.", + "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_private_name_1_4040": "El tipo de valor devuelto del captador estático público \"{0}\" de la clase exportada tiene o usa el nombre privado \"{1}\".", + "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module__4050": "El tipo de valor devuelto del método estático público de la clase exportada tiene o usa el nombre '{0}' del módulo {1} externo, pero no se puede nombrar.", + "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4051": "El tipo de valor devuelto del método estático público de la clase exportada tiene o usa el nombre '{0}' del módulo {1} privado.", + "Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0_4052": "El tipo de valor devuelto del método estático público de la clase exportada tiene o usa el nombre privado '{0}'.", + "Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program_6184": "Las resoluciones de módulo cuyo origen es \"{0}\" se reutilizan, ya que las resoluciones no varían respecto al programa anterior.", + "Reusing_resolution_of_module_0_to_file_1_from_old_program_6183": "Reutilizando la resolución del módulo \"{0}\" en el archivo \"{1}\" del programa anterior.", + "Rewrite_all_as_indexed_access_types_95034": "Reescribir todo como tipos de acceso indexados", + "Rewrite_as_the_indexed_access_type_0_90026": "Reescribir como tipo de acceso indexado \"{0}\"", + "Root_directory_cannot_be_determined_skipping_primary_search_paths_6122": "No se puede determinar el directorio raíz, se omitirán las rutas de búsqueda principales.", + "STRATEGY_6039": "ESTRATEGIA", + "Scoped_package_detected_looking_in_0_6182": "Se detectó un paquete con ámbito al buscar en \"{0}\"", + "Setters_cannot_return_a_value_2408": "Los establecedores no pueden devolver un valor.", + "Show_all_compiler_options_6169": "Mostrar todas las opciones de compilador.", + "Show_diagnostic_information_6149": "Mostrar información de diagnóstico.", + "Show_verbose_diagnostic_information_6150": "Mostrar información de diagnóstico detallada.", + "Show_what_would_be_built_or_deleted_if_specified_with_clean_6367": "Mostrar lo que podría compilarse (o eliminarse, si se especifica con \"--clean\")", + "Signature_0_must_be_a_type_predicate_1224": "La signatura '{0}' debe tener un predicado de tipo.", + "Skip_type_checking_of_declaration_files_6012": "Omita la comprobación de tipos de los archivos de declaración.", + "Skipping_build_of_project_0_because_its_dependency_1_has_errors_6362": "Omitiendo la compilación del proyecto \"{0}\" porque su dependencia \"{1}\" tiene errores", + "Skipping_clean_because_not_all_projects_could_be_located_6371": "Omitiendo la limpieza porque no se encontraron todos los proyectos", + "Source_Map_Options_6175": "Opciones de mapa de origen", + "Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature_2382": "La signatura de sobrecarga especializada no se puede asignar a ninguna signatura no especializada.", + "Specifier_of_dynamic_import_cannot_be_spread_element_1325": "El especificador de importación dinámica no puede ser un elemento de propagación.", + "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_or_ESNEXT_6015": "Especifique la versión de ECMAScript de destino: \"ES3\" (valor predeterminado), \"ES5\", \"ES2015\", \"ES2016\", \"ES2017\", \"ES2018\" o \"ESNEXT\".", + "Specify_JSX_code_generation_Colon_preserve_react_native_or_react_6080": "Especifique la generación de código JSX: \"preserve\", \"react-native\" o \"react\".", + "Specify_library_files_to_be_included_in_the_compilation_6079": "Especifique los archivos de biblioteca que se van a incluir en la compilación.", + "Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext_6016": "Especifique la generación de código del módulo: \"none\", \"commonjs\", \"amd\", \"system\", \"umd\", \"es2015\" o \"ESNext\".", + "Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6_6069": "Especifique la estrategia de resolución de módulos: 'node' (Node.js) o 'classic' (TypeScript pre-1.6).", + "Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h_6146": "Especifique la función de generador JSX que se usará cuando el destino sea la emisión de JSX \"react\"; por ejemplo, \"React.createElement\" o \"h\".", + "Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix_6060": "Especifique la secuencia de final de línea que debe usarse para emitir archivos: 'CRLF' (Dos) o 'LF' (Unix).", + "Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations_6004": "Especifique la ubicación donde el depurador debe colocar los archivos de TypeScript en lugar de sus ubicaciones de origen.", + "Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations_6003": "Especifique la ubicación donde el depurador debe colocar los archivos de asignaciones en lugar de las ubicaciones generadas.", + "Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir_6058": "Especifique el directorio raíz de los archivos de entrada. Úselo para controlar la estructura del directorio de salida con --outDir.", + "Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher_2472": "El operador spread de las expresiones \"new\" solo está disponible si el destino es ECMAScript 5 y versiones posteriores.", + "Spread_types_may_only_be_created_from_object_types_2698": "Los tipos spread solo se pueden crear a partir de tipos de objeto.", + "Starting_compilation_in_watch_mode_6031": "Iniciando la compilación en modo de inspección...", + "Statement_expected_1129": "Se esperaba una instrucción.", + "Statements_are_not_allowed_in_ambient_contexts_1036": "No se permiten instrucciones en los contextos de ambiente.", + "Static_members_cannot_reference_class_type_parameters_2302": "Los miembros estáticos no pueden hacer referencia a parámetros de tipo de clase.", + "Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1_2699": "La propiedad estática \"{0}\" está en conflicto con la propiedad integrada \"Function.{0}\" de la función de constructor \"{1}\".", + "Strict_Type_Checking_Options_6173": "Opciones de comprobación de tipos estricta", + "String_literal_expected_1141": "Se esperaba un literal de cadena.", + "String_literal_with_double_quotes_expected_1327": "Se esperaba un literal de cadena entre comillas dobles.", + "Stylize_errors_and_messages_using_color_and_context_experimental_6073": "Use color y contexto para estilizar los errores y los mensajes (experimental).", + "Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_t_2717": "Las declaraciones de propiedad subsiguientes deben tener el mismo tipo. La propiedad \"{0}\" debe ser de tipo \"{1}\", pero aquí tiene el tipo \"{2}\".", + "Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_t_2403": "Las declaraciones de variable subsiguientes deben tener el mismo tipo. La variable '{0}' debe ser de tipo '{1}', pero aquí tiene el tipo '{2}'.", + "Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2_5064": "La sustitución '{0}' para el patrón '{1}' tiene un tipo incorrecto. Se esperaba 'string', pero se obtuvo '{2}'.", + "Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character_5062": "La sustitución \"{0}\" del patrón \"{1}\" puede tener un carácter '*' como máximo.", + "Substitutions_for_pattern_0_should_be_an_array_5063": "Las sustituciones para el patrón '{0}' deben ser una matriz.", + "Substitutions_for_pattern_0_shouldn_t_be_an_empty_array_5066": "Las sustituciones para el patrón '{0}' no deben ser una matriz vacía.", + "Successfully_created_a_tsconfig_json_file_6071": "Archivo tsconfig.json creado correctamente.", + "Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors_2337": "No se permiten llamadas a \"super\" fuera de los constructores o en funciones anidadas dentro de estos.", + "Suppress_excess_property_checks_for_object_literals_6072": "Suprima las comprobaciones de propiedades en exceso de los literales de objeto.", + "Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures_6055": "Eliminar errores de noImplicitAny para los objetos de indexación a los que les falten firmas de índice.", + "Symbol_reference_does_not_refer_to_the_global_Symbol_constructor_object_2470": "La referencia \"Symbol\" no hace referencia al objeto de constructor Symbol global.", + "Syntax_Colon_0_6023": "Sintaxis: {0}", + "The_0_operator_cannot_be_applied_to_type_symbol_2469": "El operador '{0}' no se puede aplicar al tipo \"symbol\".", + "The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead_2447": "No se permite usar el operador '{0}' para los tipos booleanos. Como alternativa, puede usar '{1}'.", + "The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead_2696": "El tipo 'Object' se puede asignar a muy pocos tipos. ¿Se refería a usar el tipo 'any' en realidad?", + "The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_stand_2496": "No se puede hacer referencia al objeto \"arguments\" en una función de flecha en ES3 ni ES5. Considere la posibilidad de usar una expresión de función estándar.", + "The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_usi_2522": "No se puede hacer referencia al objeto \"arguments\" en una función o método asincrónico en ES3 ni ES5. Considere la posibilidad de usar un método o función estándar.", + "The_body_of_an_if_statement_cannot_be_the_empty_statement_1313": "El cuerpo de una instrucción \"if\" no puede ser la instrucción vacía.", + "The_character_set_of_the_input_files_6163": "Conjunto de caracteres de los archivos de entrada.", + "The_containing_function_or_module_body_is_too_large_for_control_flow_analysis_2563": "El cuerpo de la función o del módulo contenedor es demasiado grande para realizar un análisis de flujo de control.", + "The_current_host_does_not_support_the_0_option_5001": "El host actual no admite la opción '{0}'.", + "The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context_2714": "La expresión de una asignación de exportación debe ser un identificador o un nombre completo en un contexto de ambiente.", + "The_files_list_in_config_file_0_is_empty_18002": "La lista de archivos del archivo de configuración '{0}' está vacía.", + "The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback_1060": "El primer parámetro del método \"then\" de una promesa debe ser una devolución de llamada.", + "The_global_type_JSX_0_may_not_have_more_than_one_property_2608": "El tipo \"JSX.{0}\" global no puede tener más de una propiedad.", + "The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_option_1343": "La propiedad Meta \"import.meta\" solo se admite si se usa \"ESNext\" para las opciones del compilador \"target\" y \"module\".", + "The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary_2527": "El tipo inferido de \"{0}\" hace referencia a un tipo \"{1}\" no accesible. Se requiere una anotación de tipo.", + "The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern_2491": "La parte izquierda de una instrucción \"for...in\" no puede ser un patrón de desestructuración.", + "The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation_2404": "La parte izquierda de una instrucción \"for...in\" no puede usar una anotación de tipo.", + "The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access_2406": "La parte izquierda de una instrucción 'for...in' debe ser una variable o el acceso a una propiedad.", + "The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any_2405": "La parte izquierda de una instrucción \"for...in\" debe ser de tipo \"string\" o \"any\".", + "The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation_2483": "La parte izquierda de una instrucción \"for...of\" no puede usar una anotación de tipo.", + "The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access_2487": "La parte izquierda de una instrucción 'for...of' debe ser una variable o el acceso a una propiedad.", + "The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type_2362": "La parte izquierda de una operación aritmética debe ser de tipo \"any\", \"number\" o un tipo de enumeración.", + "The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access_2364": "La parte izquierda de una expresión de asignación debe ser una variable o el acceso a una propiedad.", + "The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol_2360": "La parte izquierda de una expresión \"in\" debe ser de tipo \"any\", \"string\", \"number\" o \"symbol\".", + "The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_paramete_2358": "La parte izquierda de una expresión \"instanceof\" debe ser de tipo \"any\", un tipo de objeto o un parámetro de tipo.", + "The_locale_used_when_displaying_messages_to_the_user_e_g_en_us_6156": "Configuración regional utilizada para mostrar los mensajes al usuario (por ejemplo, \"es-es\")", + "The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files_6136": "La profundidad máxima de dependencia para buscar en node_modules y cargar los archivos de JavaScript.", + "The_operand_of_a_delete_operator_cannot_be_a_read_only_property_2704": "El operando de un operador de eliminación no puede ser una propiedad de solo lectura.", + "The_operand_of_a_delete_operator_must_be_a_property_reference_2703": "El operando de un operador de eliminación debe ser una referencia de propiedad.", + "The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access_2357": "El operando de un operador de incremento o decremento debe ser una variable o el acceso a una propiedad.", + "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601": "El tipo de valor devuelto de un constructor de elemento JSX debe devolver un tipo de objeto.", + "The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any_1237": "El tipo de valor devuelto de una función Decorator de parámetro debe ser \"void\" o \"any\".", + "The_return_type_of_a_property_decorator_function_must_be_either_void_or_any_1236": "El tipo de valor devuelto de una función Decorator de propiedad debe ser \"void\" o \"any\".", + "The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_t_1058": "El tipo de valor devuelto de una función asincrónica debe ser una promesa válida o no debe contener un miembro \"then\" invocable.", + "The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_1064": "El tipo de valor devuelto de una función o un método asincrónicos debe ser el tipo Promise global.", + "The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_but_2407": "La parte derecha de una instrucción \"for...in\" debe ser de tipo \"any\", un tipo de objeto o un parámetro de tipo, pero aquí tiene el tipo \"{0}\".", + "The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type_2363": "La parte derecha de una operación aritmética debe ser de tipo \"any\", \"number\" o un tipo de enumeración.", + "The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter_2361": "La parte derecha de una expresión \"in\" debe ser de tipo \"any\", un tipo de objeto o un parámetro de tipo.", + "The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_F_2359": "La parte derecha de una expresión \"instanceof\" debe ser de tipo \"any\" o un tipo que pueda asignarse al tipo de interfaz \"Function\".", + "The_specified_path_does_not_exist_Colon_0_5058": "La ruta de acceso especificada no existe: \"{0}\".", + "The_target_of_an_assignment_must_be_a_variable_or_a_property_access_2541": "El destino de la asignación debe ser una variable o el acceso a una propiedad.", + "The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access_2701": "El destino de una asignación de reposo de objetos debe ser una variable o un acceso a propiedad.", + "The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1_2684": "El contexto 'this' de tipo '{0}' no se puede asignar al contexto 'this' de tipo '{1}' del método.", + "The_this_types_of_each_signature_are_incompatible_2685": "Los tipos 'this' de cada signatura son incompatibles.", + "The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_typ_2453": "El argumento de tipo del parámetro de tipo '{0}' no se puede inferir del uso. Puede especificar los argumentos de tipo explícitamente.", + "The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value__2547": "El tipo devuelto por el método \"next()\" de un iterador de asincronía debe ser una promesa para un tipo con una propiedad \"value\".", + "The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property_2490": "El tipo devuelto por el método \"next()\" de un iterador debe tener una propiedad \"value\".", + "The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer_1189": "La declaración de variable de una instrucción \"for...in\" no puede tener un inicializador.", + "The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer_1190": "La declaración de variable de una instrucción \"for...of\" no puede tener un inicializador.", + "The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any_2410": "No se admite la instrucción 'with'. Todos los símbolos de un bloque 'with' tendrán el tipo 'any'.", + "This_constructor_function_may_be_converted_to_a_class_declaration_80002": "Esta función de constructor puede convertirse en una declaración de clase.", + "This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found_2354": "Esta sintaxis requiere un asistente importado, pero no se puede encontrar el módulo \"{0}\".", + "This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1_2343": "Esta sintaxis requiere un asistente importado denominado \"{1}\", pero el módulo \"{0}\" no tiene el miembro exportado \"{1}\".", + "Trailing_comma_not_allowed_1009": "No se permite la coma final.", + "Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule_6153": "Transpilar cada archivo como un módulo aparte (parecido a \"ts.transpileModule\").", + "Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_mod_7035": "Pruebe \"npm install @types/{0}\" si existe o agregue un nuevo archivo de declaración (.d.ts) que incluya \"declare module '{0}';\"", + "Trying_other_entries_in_rootDirs_6110": "Se probarán otras entradas de \"rootDirs\".", + "Trying_substitution_0_candidate_module_location_Colon_1_6093": "Probando la sustitución '{0}', ubicación candidata para el módulo: '{1}'.", + "Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2_2493": "El tipo de tupla '{0}' con longitud '{1}' no se pude asignar a la tupla con longitud '{2}'.", + "Type_0_cannot_be_converted_to_type_1_2352": "El tipo '{0}' no se puede convertir en el tipo '{1}'.", + "Type_0_cannot_be_used_as_an_index_type_2538": "El tipo '{0}' no se puede usar como tipo de índice.", + "Type_0_cannot_be_used_to_index_type_1_2536": "El tipo '{0}' no se puede usar para indexar el tipo '{1}'.", + "Type_0_does_not_satisfy_the_constraint_1_2344": "El tipo '{0}' no cumple la restricción '{1}'.", + "Type_0_has_no_matching_index_signature_for_type_1_2537": "El tipo '{0}' no tiene una signatura de índice correspondiente al tipo '{1}'.", + "Type_0_has_no_properties_in_common_with_type_1_2559": "El tipo \"{0}\" no tiene propiedades en común con el tipo \"{1}\".", + "Type_0_has_no_property_1_2460": "El tipo '{0}' no tiene ninguna propiedad '{1}'.", + "Type_0_has_no_property_1_and_no_string_index_signature_2459": "El tipo '{0}' no tiene ninguna propiedad '{1}' ni ninguna signatura de índice de cadena.", + "Type_0_is_not_a_constructor_function_type_2507": "El tipo '{0}' no es un tipo de función de constructor.", + "Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Prom_1055": "El tipo '{0}' no es un tipo de valor devuelto válido para una función asincrónica en ES5/ES3, porque no hace referencia a un valor de constructor compatible con promesas.", + "Type_0_is_not_an_array_type_2461": "'{0}' no es un tipo de matriz.", + "Type_0_is_not_an_array_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators_2568": "\"{0}\" no es un tipo de matriz. Use la opción del compilador \"--downlevelIteration\" para permitir la iteración de los iteradores.", + "Type_0_is_not_an_array_type_or_a_string_type_2495": "'{0}' no es un tipo de matriz o un tipo de cadena.", + "Type_0_is_not_an_array_type_or_a_string_type_Use_compiler_option_downlevelIteration_to_allow_iterati_2569": "\"{0}\" no es un tipo de matriz o de cadena. Use la opción del compilador \"--downlevelIteration\" para permitir la iteración de los iteradores.", + "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549": "El tipo \"{0}\" no es un tipo de matriz o un tipo de cadena o no tiene un método \"[Symbol.iterator]()\" que devuelve un iterador.", + "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548": "El tipo \"{0}\" no es un tipo de matriz o no tiene un método \"[Symbol.iterator]()\" que devuelve un iterador.", + "Type_0_is_not_assignable_to_type_1_2322": "El tipo '{0}' no se puede asignar al tipo '{1}'.", + "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_2719": "El tipo \"{0}\" no se puede asignar al tipo \"{1}\". Existen dos tipos distintos con este nombre, pero no están relacionados.", + "Type_0_is_not_comparable_to_type_1_2678": "El tipo '{0}' no se puede comparar con el tipo '{1}'.", + "Type_0_is_not_generic_2315": "El tipo '{0}' no es genérico.", + "Type_0_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator_2504": "El tipo \"{0}\" debe tener un método \"[Symbol.asyncIterator]()\" que devuelve un iterador de asincronía.", + "Type_0_must_have_a_Symbol_iterator_method_that_returns_an_iterator_2488": "El tipo \"{0}\" debe tener un método \"[Symbol.iterator]()\" que devuelve un iterador.", + "Type_0_provides_no_match_for_the_signature_1_2658": "El tipo \"{0}\" no proporciona ninguna coincidencia para la signatura \"{1}\".", + "Type_0_recursively_references_itself_as_a_base_type_2310": "El tipo '{0}' se hace referencia a sí mismo de forma recursiva como tipo base.", + "Type_alias_0_circularly_references_itself_2456": "El alias de tipo '{0}' se hace referencia a sí mismo de forma circular.", + "Type_alias_name_cannot_be_0_2457": "El nombre del alias de tipo no puede ser \"{0}\".", + "Type_annotation_cannot_appear_on_a_constructor_declaration_1093": "Una anotación de tipo no puede aparecer en una declaración de constructor.", + "Type_argument_candidate_1_is_not_a_valid_type_argument_because_it_is_not_a_supertype_of_candidate_0_2455": "El candidato de argumento de tipo '{1}' no es un argumento de tipo válido porque no es un supertipo del candidato '{0}'.", + "Type_argument_expected_1140": "Se esperaba un argumento de tipo.", + "Type_argument_list_cannot_be_empty_1099": "La lista de argumentos de tipo no puede estar vacía.", + "Type_arguments_cannot_be_used_here_1342": "No se pueden usar argumentos de tipo aquí.", + "Type_declaration_files_to_be_included_in_compilation_6124": "Archivos de declaración de tipos que se incluirán en la compilación.", + "Type_expected_1110": "Se esperaba un tipo.", + "Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method_1062": "Se hace referencia al tipo directa o indirectamente en la devolución de llamada de entrega de su propio método \"then\".", + "Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member_1320": "El tipo de operando \"await\" debe ser una promesa válida o no debe contener un miembro \"then\" invocable.", + "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322": "El tipo de elementos iterados de un operando \"yield*\" debe ser una promesa válida o no debe contener un miembro \"then\" invocable.", + "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321": "El tipo de operando \"yield\" en un generador asincrónico debe ser una promesa válida o no debe contener un miembro \"then\" invocable.", + "Type_parameter_0_has_a_circular_constraint_2313": "El parámetro de tipo '{0}' tiene una restricción circular.", + "Type_parameter_0_has_a_circular_default_2716": "El parámetro de tipo \"{0}\" tiene un valor circular predeterminado.", + "Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4008": "El parámetro de tipo '{0}' de la signatura de llamada de la interfaz exportada tiene o usa el nombre privado '{1}'.", + "Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4006": "El parámetro de tipo '{0}' de la signatura de constructor de la interfaz exportada tiene o usa el nombre privado '{1}'.", + "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002": "El parámetro de tipo '{0}' de la clase exportada tiene o usa el nombre privado '{1}'.", + "Type_parameter_0_of_exported_function_has_or_is_using_private_name_1_4016": "El parámetro de tipo '{0}' de la función exportada tiene o usa el nombre privado '{1}'.", + "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004": "El parámetro de tipo '{0}' de la interfaz exportada tiene o usa el nombre privado '{1}'.", + "Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1_4083": "El parámetro de tipo '{0}' del alias del tipo exportado tiene o usa un nombre privado '{1}'.", + "Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4014": "El parámetro de tipo '{0}' del método de la interfaz exportada tiene o usa el nombre privado '{1}'.", + "Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4012": "El parámetro de tipo '{0}' del método público de la clase exportada tiene o usa el nombre privado '{1}'.", + "Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4010": "El parámetro de tipo '{0}' del método estático público de la clase exportada tiene o usa el nombre privado '{1}'.", + "Type_parameter_declaration_expected_1139": "Se esperaba una declaración de parámetros de tipo.", + "Type_parameter_list_cannot_be_empty_1098": "La lista de parámetros de tipo no puede estar vacía.", + "Type_parameter_name_cannot_be_0_2368": "El nombre del parámetro de tipo no puede ser \"{0}\".", + "Type_parameters_cannot_appear_on_a_constructor_declaration_1092": "Los parámetros de tipo no pueden aparecer en una declaración de constructor.", + "Type_predicate_0_is_not_assignable_to_1_1226": "El predicado de tipo '{0}' no se puede asignar a '{1}'.", + "Type_reference_directive_0_was_not_resolved_6120": "======== No se resolvió la directiva de referencia de tipo '{0}'. ========", + "Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2_6119": "======== La directiva de referencia de tipo '{0}' se resolvió correctamente como '{1}', principal: {2}. ========", + "Types_have_separate_declarations_of_a_private_property_0_2442": "Los tipos tienen declaraciones independientes de una propiedad '{0}' privada.", + "Types_of_parameters_0_and_1_are_incompatible_2328": "Los tipos de parámetros '{0}' y '{1}' no son compatibles.", + "Types_of_property_0_are_incompatible_2326": "Los tipos de propiedad '{0}' no son compatibles.", + "Unable_to_open_file_0_6050": "No se puede abrir el archivo '{0}'.", + "Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression_1238": "No se puede resolver la signatura de elemento Decorator de una clase cuando se llama como expresión.", + "Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression_1241": "No se puede resolver la signatura de elemento Decorator de un método cuando se llama como expresión.", + "Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression_1239": "No se puede resolver la signatura de elemento Decorator de un parámetro cuando se llama como expresión.", + "Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression_1240": "No se puede resolver la signatura de elemento Decorator de una propiedad cuando se llama como expresión.", + "Unexpected_end_of_text_1126": "Final de texto inesperado.", + "Unexpected_token_1012": "Token inesperado.", + "Unexpected_token_A_constructor_method_accessor_or_property_was_expected_1068": "Token inesperado. Se esperaba un constructor, un método, un descriptor de acceso o una propiedad.", + "Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces_1069": "Token inesperado. Se esperaba un nombre de parámetro de tipo sin llaves.", + "Unexpected_token_expected_1179": "Token inesperado. Se esperaba \"{\".", + "Unknown_compiler_option_0_5023": "Opción '{0}' del compilador desconocida.", + "Unknown_option_excludes_Did_you_mean_exclude_6114": "Opción 'excludes' desconocida. ¿Quería decir 'exclude'?", + "Unknown_type_acquisition_option_0_17010": "Opción '{0}' de adquisición de tipos desconocida.", + "Unreachable_code_detected_7027": "Se ha detectado código inaccesible.", + "Unsupported_locale_0_6049": "Configuración regional '{0}' no admitida.", + "Unterminated_Unicode_escape_sequence_1199": "Secuencia de escape Unicode sin terminar.", + "Unterminated_quoted_string_in_response_file_0_6045": "Cadena entrecomillada sin terminar en el archivo de respuesta '{0}'.", + "Unterminated_regular_expression_literal_1161": "Literal de expresión regular sin terminar.", + "Unterminated_string_literal_1002": "Literal de cadena sin terminar.", + "Unterminated_template_literal_1160": "Literal de plantilla sin terminar.", + "Untyped_function_calls_may_not_accept_type_arguments_2347": "Las llamadas a función sin tipo no pueden aceptar argumentos de tipo.", + "Unused_label_7028": "Etiqueta no usada.", + "Updating_output_timestamps_of_project_0_6359": "Actualizando las marcas de hora de salida del proyecto \"{0}\"...", + "Use_synthetic_default_member_95016": "Use el miembro sintético \"default\".", + "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494": "El uso de una cadena en una instrucción \"for...of\" solo se admite en ECMAScript 5 y versiones posteriores.", + "VERSION_6036": "VERSIÓN", + "Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it_2560": "El valor de tipo \"{0}\" no tiene propiedades en común con el tipo \"{1}\". ¿Realmente quiere llamarlo?", + "Value_of_type_0_is_not_callable_Did_you_mean_to_include_new_2348": "No se puede llamar a un valor de tipo '{0}'. ¿Pretendía incluir \"new\"?", + "Variable_0_implicitly_has_an_1_type_7005": "La variable '{0}' tiene un tipo '{1}' implícitamente.", + "Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined_7034": "La variable '{0}' tiene implícitamente el tipo '{1}' en algunos sitios donde no se puede determinar su tipo.", + "Variable_0_is_used_before_being_assigned_2454": "La variable '{0}' se usa antes de asignarla.", + "Variable_declaration_expected_1134": "Se esperaba una declaración de variable.", + "Variable_declaration_list_cannot_be_empty_1123": "La lista de declaraciones de variable no puede estar vacía.", + "Version_0_6029": "Versión {0}", + "Watch_input_files_6005": "Inspeccionar archivos de entrada.", + "Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen_6191": "Si se debe mantener la salida de la consola no actualizada en el modo de inspección en lugar de borrar la pantalla.", + "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001": "No se puede cambiar el nombre de elementos definidos en la biblioteca TypeScript estándar.", + "You_cannot_rename_this_element_8000": "No se puede cambiar el nombre a este elemento.", + "_0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write__1329": "\"{0}\" no acepta suficientes argumentos para utilizarse como decorador aquí. ¿Pretendía llamar primero y escribir \"@{0}()\"?", + "_0_are_specified_twice_The_attribute_named_0_will_be_overwritten_2710": "\"{0}\" se especifica dos veces. El atributo denominado \"{0}\" se sobrescribirá.", + "_0_can_only_be_used_in_a_ts_file_8009": "'{0}' solo se puede usar en un archivo .ts.", + "_0_expected_1005": "Se esperaba '{0}'.", + "_0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_reference_7023": "'{0}' tiene el tipo de valor devuelto \"any\" implícitamente porque no tiene una anotación de tipo de valor devuelto y se hace referencia a este directa o indirectamente en una de sus expresiones return.", + "_0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or__7022": "'{0}' tiene el tipo de valor devuelto \"any\" implícitamente porque no tiene una anotación de tipo y se hace referencia a este directa o indirectamente en su propio inicializador.", + "_0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible_2692": "'{0}' es un elemento primitivo, pero '{1}' es un objeto contenedor. Use '{0}' preferentemente cuando sea posible.", + "_0_is_declared_but_its_value_is_never_read_6133": "Se declara \"{0}\", pero su valor no se lee nunca.", + "_0_is_declared_but_never_used_6196": "\"{0}\" se declara pero nunca se utiliza.", + "_0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2_17012": "\"{0}\" no es una propiedad Meta válida para la palabra clave \"{1}\". ¿Pretendía usar \"{2}\"?", + "_0_is_referenced_directly_or_indirectly_in_its_own_base_expression_2506": "Se hace referencia a '{0}' directa o indirectamente en su propia expresión base.", + "_0_is_referenced_directly_or_indirectly_in_its_own_type_annotation_2502": "Se hace referencia a '{0}' directa o indirectamente en su propia anotación de tipo.", + "_0_list_cannot_be_empty_1097": "La lista '{0}' no puede estar vacía.", + "_0_modifier_already_seen_1030": "El modificador '{0}' ya se ha visto.", + "_0_modifier_cannot_appear_on_a_class_element_1031": "El modificador '{0}' no puede aparecer en un elemento de clase.", + "_0_modifier_cannot_appear_on_a_constructor_declaration_1089": "El modificador '{0}' no puede aparecer en una declaración de constructor.", + "_0_modifier_cannot_appear_on_a_data_property_1043": "El modificador '{0}' no puede aparecer en una propiedad data.", + "_0_modifier_cannot_appear_on_a_module_or_namespace_element_1044": "El modificador '{0}' no puede aparecer en un módulo o un elemento de espacio de nombres.", + "_0_modifier_cannot_appear_on_a_parameter_1090": "El modificador '{0}' no puede aparecer en un parámetro.", + "_0_modifier_cannot_appear_on_a_type_member_1070": "El modificador '{0}' no puede aparecer en un miembro de tipo.", + "_0_modifier_cannot_appear_on_an_index_signature_1071": "El modificador '{0}' no puede aparecer en una signatura de índice.", + "_0_modifier_cannot_be_used_here_1042": "El modificador '{0}' no se puede usar aquí.", + "_0_modifier_cannot_be_used_in_an_ambient_context_1040": "El modificador '{0}' no se puede usar en un contexto de ambiente.", + "_0_modifier_cannot_be_used_with_1_modifier_1243": "El modificador '{0}' no se puede usar con el modificador '{1}'.", + "_0_modifier_cannot_be_used_with_a_class_declaration_1041": "El modificador '{0}' no se puede usar con una declaración de clase.", + "_0_modifier_must_precede_1_modifier_1029": "El modificador \"{0}\" debe preceder al modificador \"{1}\".", + "_0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here_2702": "'{0}' solo hace referencia a un tipo, pero aquí se usa como espacio de nombres.", + "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_2693": "'{0}' solo hace referencia a un tipo, pero aquí se usa como valor.", + "_0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead_2686": "'{0}' hace referencia a un elemento UMD global, pero el archivo actual es un módulo. Puede agregar una importación en su lugar.", + "_0_tag_already_specified_1223": "La etiqueta '{0}' ya se ha especificado.", + "_0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag_1253": "La etiqueta '{0}' no se puede usar de forma independiente como etiqueta JSDoc de nivel superior.", + "_0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type_7010": "'{0}' carece de una anotación de tipo de valor devuelto, pero tiene un tipo de valor devuelto '{1}' implícitamente.", + "abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration_1242": "El modificador 'abstract' solo puede aparecer en una declaración de propiedad, clase o método.", + "await_expression_is_only_allowed_within_an_async_function_1308": "La expresión \"await\" solo se permite en una función asincrónica.", + "await_expressions_cannot_be_used_in_a_parameter_initializer_2524": "Las expresiones \"await\" no se pueden usar en un inicializador de parámetros.", + "baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1_6106": "La opción \"baseUrl\" está establecida en \"{0}\", se usará este valor para resolver el nombre de módulo no relativo \"{1}\".", + "can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment_1312": "\"=\" solo se puede usar en una propiedad de literal de objeto dentro de una asignación de desestructuración.", + "case_or_default_expected_1130": "Se esperaba \"case\" o \"default\".", + "class_expressions_are_not_currently_supported_9003": "Actualmente, no se admiten las expresiones \"class\".", + "const_declarations_can_only_be_declared_inside_a_block_1156": "Las declaraciones \"const\" solo se pueden declarar dentro de un bloque.", + "const_declarations_must_be_initialized_1155": "Las declaraciones \"const\" deben inicializarse.", + "const_enum_member_initializer_was_evaluated_to_a_non_finite_value_2477": "El inicializador de miembros de enumeración \"const\" se evaluó con un valor no finito.", + "const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN_2478": "El inicializador de miembros de enumeración \"const\" se evaluó con un valor \"NaN\" no permitido.", + "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475": "Las enumeraciones \"const\" solo se pueden usar en expresiones de acceso de propiedad o índice, o en la parte derecha de una declaración de importación, una asignación de exportación o una consulta de tipo.", + "delete_cannot_be_called_on_an_identifier_in_strict_mode_1102": "No se puede llamar a \"delete\" en un identificador en modo strict.", + "delete_this_Project_0_is_up_to_date_because_it_was_previously_built_6360": "eliminar esto - El proyecto \"{0}\" está actualizado porque se compiló previamente", + "enum_declarations_can_only_be_used_in_a_ts_file_8015": "Las declaraciones \"enum\" solo se pueden usar en un archivo .ts.", + "export_can_only_be_used_in_a_ts_file_8003": "\"export=\" solo se puede usar en un archivo .ts.", + "export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always__2668": "El modificador 'export' no se puede aplicar a módulos de ambiente ni aumentos de módulos, porque siempre están visibles.", + "extends_clause_already_seen_1172": "La cláusula \"extends\" ya se ha visto.", + "extends_clause_must_precede_implements_clause_1173": "La cláusula \"extends\" debe preceder a la cláusula \"implements\".", + "extends_clause_of_exported_class_0_has_or_is_using_private_name_1_4020": "La cláusula \"extends\" de la clase \"{0}\" exportada tiene o usa el nombre privado \"{1}\".", + "extends_clause_of_exported_interface_0_has_or_is_using_private_name_1_4022": "La cláusula \"extends\" de la interfaz \"{0}\" exportada tiene o usa el nombre privado \"{1}\".", + "file_6025": "archivo", + "get_and_set_accessor_must_have_the_same_this_type_2682": "Los descriptores de acceso 'get' y 'set' deben tener el mismo tipo 'this'.", + "get_and_set_accessor_must_have_the_same_type_2380": "Los descriptores de acceso \"get\" y \"set\" deben tener el mismo tipo.", + "implements_clause_already_seen_1175": "La cláusula \"implements\" ya se ha visto.", + "implements_clauses_can_only_be_used_in_a_ts_file_8005": "\"implements clauses\" solo se puede usar en un archivo .ts.", + "import_can_only_be_used_in_a_ts_file_8002": "\"import ... =\" solo se puede usar en un archivo .ts.", + "infer_declarations_are_only_permitted_in_the_extends_clause_of_a_conditional_type_1338": "Las declaraciones \"infer\" solo se permiten en la cláusula \"extends\" de un tipo condicional.", + "interface_declarations_can_only_be_used_in_a_ts_file_8006": "\"interface declarations\" solo se puede usar en un archivo .ts.", + "let_declarations_can_only_be_declared_inside_a_block_1157": "Las declaraciones \"let\" solo se pueden declarar dentro de un bloque.", + "let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations_2480": "No se permite usar \"let\" como nombre en las declaraciones \"let\" o \"const\".", + "module_declarations_can_only_be_used_in_a_ts_file_8007": "\"module declarations\" solo se puede usar en un archivo .ts.", + "new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead_1150": "\"new T[]\" no se puede usar para crear una matriz. Use \"new Array()\" en su lugar.", + "new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type_7009": "La expresión \"new\", a cuyo destino le falta una signatura de construcción, tiene implícitamente un tipo \"any\".", + "non_null_assertions_can_only_be_used_in_a_ts_file_8013": "Las \"aserciones no nulas\" solo se pueden usar en un archivo .ts.", + "options_6024": "Opciones", + "or_expected_1144": "Se esperaba \"{\" o \";\".", + "package_json_does_not_have_a_0_field_6100": "\"package.json\" no tiene un campo \"{0}\".", + "package_json_has_0_field_1_that_references_2_6101": "'package.json' tiene el campo '{1}' de '{0}' que hace referencia a '{2}'.", + "parameter_modifiers_can_only_be_used_in_a_ts_file_8012": "\"parameter modifiers\" solo se puede usar en un archivo .ts.", + "paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0_6091": "Se ha especificado la opción 'paths'. Se buscará un patrón que coincida con el nombre de módulo '{0}'.", + "readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024": "El modificador 'readonly' solo puede aparecer en una declaración de propiedad o una signatura de índice.", + "require_call_may_be_converted_to_an_import_80005": "La llamada a \"require\" puede convertirse en una importación.", + "rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107": "Se ha establecido la opción \"rootDirs\". Se usará para resolver el nombre de módulo relativo \"{0}\".", + "super_can_only_be_referenced_in_a_derived_class_2335": "Solo se puede hacer referencia a \"super\" en una clase derivada.", + "super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions_2660": "Solo se puede hacer referencia a 'super' en miembros de clases derivadas o expresiones de literal de objeto.", + "super_cannot_be_referenced_in_a_computed_property_name_2466": "No se puede hacer referencia a \"super\" en un nombre de propiedad calculada.", + "super_cannot_be_referenced_in_constructor_arguments_2336": "No se puede hacer referencia a \"super\" en argumentos de constructor.", + "super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_highe_2659": "'super' se permite únicamente en miembros de expresiones de literal de objeto cuando la opción 'target' es 'ES2015' o superior.", + "super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class_17011": "Debe llamarse a \"super\" antes de acceder a una propiedad de \"super\" en el constructor de una clase derivada.", + "super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class_17009": "Debe llamarse a 'super' antes de acceder a 'this' en el constructor de una clase derivada.", + "super_must_be_followed_by_an_argument_list_or_member_access_1034": "\"super\" debe estar seguido de una lista de argumentos o un acceso a miembros.", + "super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_der_2338": "El acceso a la propiedad \"super\" se permite únicamente en un constructor, una función miembro o un descriptor de acceso de miembro de una clase derivada.", + "this_cannot_be_referenced_in_a_computed_property_name_2465": "No se puede hacer referencia a \"this\" en un nombre de propiedad calculada.", + "this_cannot_be_referenced_in_a_module_or_namespace_body_2331": "No se puede hace referencia a \"this\" en el cuerpo de un módulo o de un espacio de nombres.", + "this_cannot_be_referenced_in_a_static_property_initializer_2334": "No se puede hacer referencia a \"this\" en un inicializador de propiedad estática.", + "this_cannot_be_referenced_in_constructor_arguments_2333": "No se puede hacer referencia a \"this\" en argumentos de constructor.", + "this_cannot_be_referenced_in_current_location_2332": "No se puede hacer referencia a \"this\" en la ubicación actual.", + "this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_2683": "'this' tiene el tipo implícito 'any' porque no tiene una anotación de tipo.", + "type_aliases_can_only_be_used_in_a_ts_file_8008": "\"type aliases\" solo se puede usar en un archivo .ts.", + "type_arguments_can_only_be_used_in_a_ts_file_8011": "\"type arguments\" solo se puede usar en un archivo .ts.", + "type_assertion_expressions_can_only_be_used_in_a_ts_file_8016": "\"type assertion expressions\" solo se puede usar en un archivo .ts.", + "type_parameter_declarations_can_only_be_used_in_a_ts_file_8004": "\"type parameter declarations\" solo se puede usar en un archivo .ts.", + "types_can_only_be_used_in_a_ts_file_8010": "\"types\" solo se puede usar en un archivo .ts.", + "unique_symbol_types_are_not_allowed_here_1335": "Aquí no se permiten tipos \"unique symbol\".", + "unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement_1334": "Los tipos \"unique symbol\" se permiten solo en variables en una instrucción de variable.", + "unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name_1333": "Los tipos \"unique symbol\" no se pueden utilizar en una declaración de variable con un nombre de enlace.", + "with_statements_are_not_allowed_in_an_async_function_block_1300": "No se permiten instrucciones \"with\" en un bloque de funciones asincrónicas.", + "with_statements_are_not_allowed_in_strict_mode_1101": "No se permiten instrucciones \"with\" en modo strict.", + "yield_expressions_cannot_be_used_in_a_parameter_initializer_2523": "Las expresiones \"yield\" no se pueden usar en un inicializador de parámetros." +} \ No newline at end of file diff --git a/node_modules/typescript/lib/fr/diagnosticMessages.generated.json b/node_modules/typescript/lib/fr/diagnosticMessages.generated.json new file mode 100644 index 0000000..1699b44 --- /dev/null +++ b/node_modules/typescript/lib/fr/diagnosticMessages.generated.json @@ -0,0 +1,1101 @@ +{ + "A_0_modifier_cannot_be_used_with_an_import_declaration_1079": "Impossible d'utiliser un modificateur '{0}' avec une déclaration d'importation.", + "A_0_modifier_cannot_be_used_with_an_interface_declaration_1045": "Impossible d'utiliser un modificateur '{0}' avec une déclaration d'interface.", + "A_0_parameter_must_be_the_first_parameter_2680": "Un paramètre '{0}' doit être le premier paramètre.", + "A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature_2463": "Un paramètre de modèle de liaison ne peut pas être facultatif dans une signature d'implémentation.", + "A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement_1105": "Une instruction 'break' peut être utilisée uniquement dans une itération englobante ou une instruction switch.", + "A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement_1116": "Une instruction 'break' peut accéder uniquement à une étiquette d'une instruction englobante.", + "A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments_2500": "Une classe peut uniquement implémenter un identificateur/nom qualifié avec des arguments de type facultatifs.", + "A_class_declaration_without_the_default_modifier_must_have_a_name_1211": "Une déclaration de classe sans modificateur 'default' doit porter un nom.", + "A_class_may_only_extend_another_class_2311": "Une classe peut uniquement étendre une autre classe.", + "A_class_may_only_implement_another_class_or_interface_2422": "Une classe peut uniquement implémenter une autre classe ou interface.", + "A_class_member_cannot_have_the_0_keyword_1248": "Un membre de classe ne peut pas avoir le mot clé '{0}'.", + "A_comma_expression_is_not_allowed_in_a_computed_property_name_1171": "Une expression avec virgule n'est pas autorisée dans un nom de propriété calculée.", + "A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type_2467": "Un nom de propriété calculée ne peut pas référencer un paramètre de type à partir de son type conteneur.", + "A_computed_property_name_in_a_class_property_declaration_must_refer_to_an_expression_whose_type_is_a_1166": "Un nom de propriété calculée dans une déclaration de propriété de classe doit faire référence à une expression dont le type est un type littéral ou un type 'unique symbol'.", + "A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_ty_1168": "Un nom de propriété calculée dans une surcharge de méthode doit faire référence à une expression dont le type est un type littéral ou un type 'unique symbol'.", + "A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type__1170": "Un nom de propriété calculée dans un littéral de type doit faire référence à une expression dont le type est un type littéral ou un type 'unique symbol'.", + "A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_t_1165": "Un nom de propriété calculée dans un contexte ambiant doit faire référence à une expression dont le type est un type littéral ou un type 'unique symbol'.", + "A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_1169": "Un nom de propriété calculée dans une interface doit faire référence à une expression dont le type est un type littéral ou un type 'unique symbol'.", + "A_computed_property_name_must_be_of_type_string_number_symbol_or_any_2464": "Un nom de propriété calculée doit être de type 'string', 'number', 'symbol' ou 'any'.", + "A_computed_property_name_of_the_form_0_must_be_of_type_symbol_2471": "Un nom de propriété calculée de la forme '{0}' doit être de type 'symbol'.", + "A_const_enum_member_can_only_be_accessed_using_a_string_literal_2476": "Un membre d'enum const n'est accessible qu'à l'aide d'un littéral de chaîne.", + "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_1254": "Un initialiseur 'const' dans un contexte ambiant doit être un littéral de chaîne ou un littéral numérique.", + "A_constructor_cannot_contain_a_super_call_when_its_class_extends_null_17005": "Un constructeur ne peut pas contenir d'appel de 'super' quand sa classe étend 'null'.", + "A_constructor_cannot_have_a_this_parameter_2681": "Un constructeur ne peut pas avoir un paramètre 'this'.", + "A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement_1104": "Une instruction 'continue' peut uniquement être utilisée dans une instruction d'itération englobante.", + "A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement_1115": "Une instruction 'continue' peut accéder uniquement à une étiquette d'une instruction d'itération englobante.", + "A_declare_modifier_cannot_be_used_in_an_already_ambient_context_1038": "Impossible d'utiliser un modificateur 'declare' dans un contexte ambiant déjà défini.", + "A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file_1046": "Un modificateur 'declare' est obligatoire pour une déclaration de niveau supérieur dans un fichier .d.ts.", + "A_decorator_can_only_decorate_a_method_implementation_not_an_overload_1249": "Un élément décoratif peut uniquement décorer une implémentation de méthode, pas une surcharge.", + "A_default_clause_cannot_appear_more_than_once_in_a_switch_statement_1113": "Une clause 'default' ne peut pas figurer plusieurs fois dans une instruction 'switch'.", + "A_default_export_can_only_be_used_in_an_ECMAScript_style_module_1319": "Une exportation par défaut ne peut être utilisée que dans un module ECMAScript.", + "A_definite_assignment_assertion_is_not_permitted_in_this_context_1255": "Une assertion d'affectation définie ' !' n'est pas autorisée dans ce contexte.", + "A_destructuring_declaration_must_have_an_initializer_1182": "Une déclaration de déstructuration doit avoir un initialiseur.", + "A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declarat_2712": "Un appel d'importation dynamique en ES5/ES3 nécessite le constructeur 'Promise'. Vérifiez que vous avez une déclaration pour le constructeur 'Promise', ou incluez 'ES2015' dans votre option '--lib'.", + "A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES20_2711": "Un appel d'importation dynamique retourne 'Promise'. Vérifiez que vous avez une déclaration pour 'Promise', ou incluez 'ES2015' dans votre option '--lib'.", + "A_file_cannot_have_a_reference_to_itself_1006": "Un fichier ne peut pas contenir une référence à lui-même.", + "A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator_1103": "Une instruction 'for-await-of' est uniquement autorisée dans une fonction asynchrone ou un générateur asynchrone.", + "A_function_returning_never_cannot_have_a_reachable_end_point_2534": "Une fonction qui retourne 'never' ne peut pas avoir de point de terminaison accessible.", + "A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void_2679": "Une fonction appelée avec le mot clé 'new' ne peut pas avoir un type 'this' dont la valeur est 'void'.", + "A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value_2355": "Une fonction dont le type déclaré n'est ni 'void', ni 'any', doit retourner une valeur.", + "A_generator_cannot_have_a_void_type_annotation_2505": "Un générateur ne peut pas avoir d'annotation de type 'void'.", + "A_get_accessor_cannot_have_parameters_1054": "Un accesseur 'get' ne peut pas avoir de paramètres.", + "A_get_accessor_must_return_a_value_2378": "Un accesseur 'get' doit retourner une valeur.", + "A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_memb_2651": "Un initialiseur de membre dans une déclaration d'enum ne peut pas référencer des membres déclarés après lui, notamment des membres définis dans d'autres enums.", + "A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any_2545": "Une classe mixin doit avoir un constructeur avec un paramètre rest unique de type 'any[]'.", + "A_module_cannot_have_multiple_default_exports_2528": "Un module ne peut pas avoir plusieurs exportations par défaut.", + "A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merg_2433": "Une déclaration d'espace de noms ne peut pas se trouver dans un autre fichier que celui d'une classe ou d'une fonction avec laquelle elle est fusionnée.", + "A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged_2434": "Une déclaration d'espace de noms ne peut pas se trouver avant une classe ou une fonction avec laquelle elle est fusionnée.", + "A_namespace_declaration_is_only_allowed_in_a_namespace_or_module_1235": "Une déclaration d'espace de noms est autorisée uniquement dans un espace de noms ou un module.", + "A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_7038": "Impossible d'appeler ou de construire une importation de style d'espace de noms, ce qui va entraîner un échec au moment de l'exécution.", + "A_non_dry_build_would_build_project_0_6357": "Une build non-dry va générer le projet '{0}'", + "A_non_dry_build_would_delete_the_following_files_Colon_0_6356": "Une build non-dry va supprimer les fichiers suivants : {0}", + "A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation_2371": "Un initialiseur de paramètre est uniquement autorisé dans une implémentation de fonction ou de constructeur.", + "A_parameter_property_cannot_be_declared_using_a_rest_parameter_1317": "Impossible de déclarer une propriété de paramètre à l'aide d'un paramètre rest.", + "A_parameter_property_is_only_allowed_in_a_constructor_implementation_2369": "Une propriété de paramètre est uniquement autorisée dans une implémentation de constructeur.", + "A_parameter_property_may_not_be_declared_using_a_binding_pattern_1187": "Impossible de déclarer une propriété de paramètre à l'aide d'un modèle de liaison.", + "A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not_18001": "Un chemin dans une option 'extends' doit être relatif ou rooté, mais '{0}' n'est ni l'un ni l'autre.", + "A_promise_must_have_a_then_method_1059": "Une promesse doit avoir une méthode 'then'.", + "A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly_1331": "Une propriété d'une classe dont le type est un type 'unique symbol' doit être à la fois 'static' et 'readonly'.", + "A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly_1330": "Une propriété d'une interface ou d'un littéral de type dont le type est un type 'unique symbol' doit être 'readonly'.", + "A_required_parameter_cannot_follow_an_optional_parameter_1016": "Un paramètre obligatoire ne peut pas suivre un paramètre optionnel.", + "A_rest_element_cannot_contain_a_binding_pattern_2501": "Un élément rest ne peut pas contenir de modèle de liaison.", + "A_rest_element_cannot_have_a_property_name_2566": "Un élément rest ne peut pas avoir de nom de propriété.", + "A_rest_element_cannot_have_an_initializer_1186": "Un élément rest ne peut pas avoir d'initialiseur.", + "A_rest_element_must_be_last_in_a_destructuring_pattern_2462": "Un élément rest doit être le dernier dans un modèle de déstructuration.", + "A_rest_parameter_cannot_be_optional_1047": "Un paramètre rest ne peut pas être facultatif.", + "A_rest_parameter_cannot_have_an_initializer_1048": "Un paramètre rest ne peut pas avoir d'initialiseur.", + "A_rest_parameter_must_be_last_in_a_parameter_list_1014": "Un paramètre rest doit être le dernier dans une liste de paramètres.", + "A_rest_parameter_must_be_of_an_array_type_2370": "Un paramètre rest doit être de type tableau.", + "A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma_1013": "Les modèles de liaison ou les paramètres rest ne doivent pas avoir de virgule de fin.", + "A_return_statement_can_only_be_used_within_a_function_body_1108": "Une instruction 'return' peut être utilisée uniquement dans un corps de fonction.", + "A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl_6167": "Série d'entrées qui remappent les importations aux emplacements de recherche en fonction de 'baseUrl'.", + "A_set_accessor_cannot_have_a_return_type_annotation_1095": "Un accesseur 'set' ne peut pas avoir d'annotation de type de retour.", + "A_set_accessor_cannot_have_an_optional_parameter_1051": "Un accesseur 'set' ne peut pas avoir de paramètre optionnel.", + "A_set_accessor_cannot_have_rest_parameter_1053": "Un accesseur 'set' ne peut pas avoir de paramètre rest.", + "A_set_accessor_must_have_exactly_one_parameter_1049": "Un accesseur 'set' doit avoir un seul paramètre.", + "A_set_accessor_parameter_cannot_have_an_initializer_1052": "Un paramètre d'accesseur 'set' ne peut pas avoir d'initialiseur.", + "A_signature_with_an_implementation_cannot_use_a_string_literal_type_2381": "Une signature avec une implémentation ne peut pas utiliser de type de littéral de chaîne.", + "A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_proper_2376": "Un appel de 'super' doit être la première instruction du constructeur quand une classe contient des propriétés initialisées ou possède des propriétés de paramètre.", + "A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard_2518": "Une protection de type basée sur 'this' n'est pas compatible avec une protection de type basée sur des paramètres.", + "A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface_2526": "Un type 'this' est disponible uniquement dans un membre non statique d'une classe ou d'une interface.", + "A_tsconfig_json_file_is_already_defined_at_Colon_0_5054": "Un fichier 'tsconfig.json' est déjà défini à l'emplacement '{0}'.", + "A_tuple_type_element_list_cannot_be_empty_1122": "Une liste d'éléments de type tuple ne peut pas être vide.", + "A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Con_17007": "Une expression d'assertion de type n'est pas autorisée dans la partie gauche d'une expression d'élévation à une puissance. Mettez l'expression entre parenthèses.", + "A_type_literal_property_cannot_have_an_initializer_1247": "Une propriété de littéral de type ne peut pas avoir d'initialiseur.", + "A_type_predicate_cannot_reference_a_rest_parameter_1229": "Un prédicat de type ne peut pas référencer un paramètre rest.", + "A_type_predicate_cannot_reference_element_0_in_a_binding_pattern_1230": "Un prédicat de type ne peut pas référencer un élément '{0}' dans un modèle de liaison.", + "A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods_1228": "Un prédicat de type est autorisé uniquement dans une position de type de retour pour les fonctions et les méthodes.", + "A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type_2677": "Le type d'un prédicat de type doit être assignable au type de son paramètre.", + "A_variable_whose_type_is_a_unique_symbol_type_must_be_const_1332": "Une variable dont le type est un type 'unique symbol' doit être 'const'.", + "A_yield_expression_is_only_allowed_in_a_generator_body_1163": "Une expression 'yield' est autorisée uniquement dans le corps d'un générateur.", + "Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression_2513": "La méthode abstraite '{0}' de la classe '{1}' n'est pas accessible au moyen de l'expression super.", + "Abstract_methods_can_only_appear_within_an_abstract_class_1244": "Les méthodes abstraites peuvent uniquement apparaître dans une classe abstraite.", + "Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor_2715": "La propriété abstraite '{0}' de la classe '{1}' n'est pas accessible dans le constructeur.", + "Accessibility_modifier_already_seen_1028": "Modificateur d'accessibilité déjà rencontré.", + "Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher_1056": "Les accesseurs sont uniquement disponibles quand EcmaScript 5 ou version supérieure est ciblé.", + "Accessors_must_both_be_abstract_or_non_abstract_2676": "Les accesseurs doivent être abstraits ou non abstraits.", + "Add_0_to_existing_import_declaration_from_1_90015": "Ajouter '{0}' à la déclaration d'importation existante de \"{1}\"", + "Add_0_to_unresolved_variable_90008": "Ajouter '{0}.' à la variable non résolue", + "Add_all_missing_async_modifiers_95041": "Ajouter tous les modificateurs 'async' manquants", + "Add_all_missing_members_95022": "Ajouter tous les membres manquants", + "Add_all_missing_super_calls_95039": "Ajouter tous les appels super manquants", + "Add_async_modifier_to_containing_function_90029": "Ajouter le modificateur async dans la fonction conteneur", + "Add_braces_to_arrow_function_95059": "Ajouter des accolades à la fonction arrow", + "Add_definite_assignment_assertion_to_property_0_95020": "Ajouter une assertion d'assignation définie à la propriété '{0}'", + "Add_definite_assignment_assertions_to_all_uninitialized_properties_95028": "Ajouter des assertions d'affectation définie à toutes les propriétés non initialisées", + "Add_index_signature_for_property_0_90017": "Ajouter une signature d'index pour la propriété '{0}'", + "Add_initializer_to_property_0_95019": "Ajouter un initialiseur à la propriété '{0}'", + "Add_initializers_to_all_uninitialized_properties_95027": "Ajouter des initialiseurs à toutes les propriétés non initialisées", + "Add_missing_super_call_90001": "Ajouter l'appel manquant à 'super()'", + "Add_missing_typeof_95052": "Ajouter un 'typeof' manquant", + "Add_or_remove_braces_in_an_arrow_function_95058": "Ajouter ou supprimer les accolades dans une fonction arrow", + "Add_qualifier_to_all_unresolved_variables_matching_a_member_name_95037": "Ajouter un qualificateur à toutes les variables non résolues correspondant à un nom de membre", + "Add_to_all_uncalled_decorators_95044": "Ajouter '()' à tous les décorateurs non appelés", + "Add_ts_ignore_to_all_error_messages_95042": "Ajouter '@ts-ignore' à tous les messages d'erreur", + "Add_undefined_type_to_all_uninitialized_properties_95029": "Ajouter un type non défini à toutes les propriétés non initialisées", + "Add_undefined_type_to_property_0_95018": "Ajouter un type 'undefined' à la propriété '{0}'", + "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068": "L'ajout d'un fichier tsconfig.json permet d'organiser les projets qui contiennent des fichiers TypeScript et JavaScript. En savoir plus sur https://aka.ms/tsconfig.", + "Additional_Checks_6176": "Vérifications supplémentaires", + "Advanced_Options_6178": "Options avancées", + "All_declarations_of_0_must_have_identical_modifiers_2687": "Toutes les déclarations de '{0}' doivent avoir des modificateurs identiques.", + "All_declarations_of_0_must_have_identical_type_parameters_2428": "Toutes les déclarations de '{0}' doivent avoir des paramètres de type identiques.", + "All_declarations_of_an_abstract_method_must_be_consecutive_2516": "Toutes les déclarations d'une méthode abstraite doivent être consécutives.", + "All_destructured_elements_are_unused_6198": "Tous les éléments déstructurés sont inutilisés.", + "All_imports_in_import_declaration_are_unused_6192": "Les importations de la déclaration d'importation ne sont pas toutes utilisées.", + "All_variables_are_unused_6199": "Toutes les variables sont inutilisées.", + "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011": "Autorisez les importations par défaut à partir des modules sans exportation par défaut. Cela n'affecte pas l'émission du code, juste le contrôle de type.", + "Allow_javascript_files_to_be_compiled_6102": "Autorisez la compilation des fichiers JavaScript.", + "Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided_1209": "Les enums const ambiants ne sont pas autorisés quand l'indicateur '--isolatedModules' est fourni.", + "Ambient_module_declaration_cannot_specify_relative_module_name_2436": "Une déclaration de module ambiant ne peut pas spécifier un nom de module relatif.", + "Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces_2435": "Impossible d'imbriquer des modules ambiants dans d'autres modules ou espaces de noms.", + "An_AMD_module_cannot_have_multiple_name_assignments_2458": "Un module AMD ne peut pas avoir plusieurs affectations de nom.", + "An_abstract_accessor_cannot_have_an_implementation_1318": "Un accesseur abstrait ne peut pas avoir d'implémentation.", + "An_accessor_cannot_be_declared_in_an_ambient_context_1086": "Impossible de déclarer un accesseur dans un contexte ambiant.", + "An_accessor_cannot_have_type_parameters_1094": "Un accesseur ne peut pas avoir de paramètres de type.", + "An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file_1234": "Une déclaration de module ambiant est uniquement autorisée au niveau supérieur dans un fichier.", + "An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type_2356": "Un opérande arithmétique doit être de type 'any', 'number' ou un type enum.", + "An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_de_2705": "Une fonction ou méthode asynchrone en ES5/ES3 nécessite le constructeur 'Promise'. Vérifiez que vous avez une déclaration pour le constructeur 'Promise', ou incluez 'ES2015' dans votre option '--lib'.", + "An_async_function_or_method_must_have_a_valid_awaitable_return_type_1057": "Une fonction ou une méthode async doit avoir un type de retour valide pouvant être attendu.", + "An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_in_2697": "Une fonction ou une méthode async doit retourner 'Promise'. Vérifiez que vous avez une déclaration pour 'Promise', ou incluez 'ES2015' dans votre option '--lib'.", + "An_async_iterator_must_have_a_next_method_2519": "Un itérateur asynchrone doit comporter une méthode 'next()'.", + "An_element_access_expression_should_take_an_argument_1011": "Une expression d'accès à un élément doit accepter un argument.", + "An_enum_member_cannot_have_a_numeric_name_2452": "Un membre enum ne peut pas avoir un nom numérique.", + "An_export_assignment_can_only_be_used_in_a_module_1231": "Une attribution d'exportation peut uniquement être utilisée dans un module.", + "An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements_2309": "Impossible d'utiliser une assignation d'exportation dans un module comportant d'autres éléments exportés.", + "An_export_assignment_cannot_be_used_in_a_namespace_1063": "Une affectation d'exportation ne peut pas être utilisée dans un espace de noms.", + "An_export_assignment_cannot_have_modifiers_1120": "Une assignation d'exportation ne peut pas avoir de modificateurs.", + "An_export_declaration_can_only_be_used_in_a_module_1233": "Une déclaration d'exportation peut uniquement être utilisée dans un module.", + "An_export_declaration_cannot_have_modifiers_1193": "Une déclaration d'exportation ne peut pas avoir de modificateurs.", + "An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive_1198": "Une valeur d'échappement Unicode étendue doit être comprise entre 0x0 et 0x10FFFF inclus.", + "An_implementation_cannot_be_declared_in_ambient_contexts_1183": "Impossible de déclarer une implémentation dans des contextes ambiants.", + "An_import_declaration_can_only_be_used_in_a_namespace_or_module_1232": "Une déclaration d'importation peut uniquement être utilisée dans un espace de noms ou un module.", + "An_import_declaration_cannot_have_modifiers_1191": "Une déclaration d'importation ne peut pas avoir de modificateurs.", + "An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead_2691": "Un chemin d'importation ne peut pas finir par une extension '{0}'. Importez '{1}' à la place.", + "An_index_expression_argument_must_be_of_type_string_number_symbol_or_any_2342": "Un argument d'expression d'index doit être de type 'string', 'number', 'symbol' ou 'any'.", + "An_index_signature_cannot_have_a_rest_parameter_1017": "Une signature d'index ne peut pas avoir de paramètre rest.", + "An_index_signature_must_have_a_type_annotation_1021": "Une signature d'index doit avoir une annotation de type.", + "An_index_signature_must_have_exactly_one_parameter_1096": "Une signature d'index doit avoir un seul paramètre.", + "An_index_signature_parameter_cannot_have_a_question_mark_1019": "Un paramètre de signature d'index ne peut pas contenir de point d'interrogation.", + "An_index_signature_parameter_cannot_have_an_accessibility_modifier_1018": "Un paramètre de signature d'index ne peut pas avoir de modificateur d'accessibilité.", + "An_index_signature_parameter_cannot_have_an_initializer_1020": "Un paramètre de signature d'index ne peut pas avoir d'initialiseur.", + "An_index_signature_parameter_must_have_a_type_annotation_1022": "Un paramètre de signature d'index doit avoir une annotation de type.", + "An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead_1336": "Un type de paramètre de signature d'index ne peut pas être un alias de type. Écrivez '[{0}: {1}]: {2}' à la place.", + "An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead_1337": "Un type de paramètre de signature d'index ne peut pas être un type union. Utilisez un type d'objet mappé à la place.", + "An_index_signature_parameter_type_must_be_string_or_number_1023": "Le type d'un paramètre de signature d'index doit être 'string' ou 'number'.", + "An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments_2499": "Une interface peut uniquement étendre un identificateur/nom qualifié avec des arguments de type facultatifs.", + "An_interface_may_only_extend_a_class_or_another_interface_2312": "Une interface peut uniquement étendre une classe ou une autre interface.", + "An_interface_property_cannot_have_an_initializer_1246": "Une propriété d'interface ne peut pas avoir d'initialiseur.", + "An_iterator_must_have_a_next_method_2489": "Un itérateur doit comporter une méthode 'next()'.", + "An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name_1118": "Un littéral d'objet ne peut pas avoir plusieurs accesseurs get/set portant le même nom.", + "An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode_1117": "Un littéral d'objet ne peut pas avoir plusieurs propriétés portant le même nom en mode strict.", + "An_object_literal_cannot_have_property_and_accessor_with_the_same_name_1119": "Un littéral d'objet ne peut pas avoir une propriété et un accesseur portant le même nom.", + "An_object_member_cannot_be_declared_optional_1162": "Impossible de déclarer un membre d'objet comme étant facultatif.", + "An_overload_signature_cannot_be_declared_as_a_generator_1222": "Une signature de surcharge ne peut pas être déclarée en tant que générateur.", + "An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_ex_17006": "Une expression unaire avec l'opérateur '{0}' n'est pas autorisée dans la partie gauche d'une expression d'élévation à une puissance. Mettez l'expression entre parenthèses.", + "Annotate_everything_with_types_from_JSDoc_95043": "Annoter tout avec des types de JSDoc", + "Annotate_with_type_from_JSDoc_95009": "Annoter avec le type de JSDoc", + "Annotate_with_types_from_JSDoc_95010": "Annoter avec les types de JSDoc", + "Argument_expression_expected_1135": "Expression d'argument attendue.", + "Argument_for_0_option_must_be_Colon_1_6046": "L'argument de l'option '{0}' doit être {1}.", + "Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_2345": "L'argument de type '{0}' n'est pas attribuable au paramètre de type '{1}'.", + "Array_element_destructuring_pattern_expected_1181": "Modèle de déstructuration d'élément de tableau attendu.", + "Asterisk_Slash_expected_1010": "'.' attendu.", + "Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_2669": "Les augmentations de la portée globale ne peuvent être directement imbriquées que dans les modules externes ou les déclarations de modules ambiants.", + "Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambien_2670": "Les augmentations de la portée globale doivent comporter un modificateur 'declare', sauf si elles apparaissent déjà dans un contexte ambiant.", + "Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using__6140": "La détection automatique des typages est activée dans le projet '{0}'. Exécution de la passe de résolution supplémentaire pour le module '{1}' à l'aide de l'emplacement du cache '{2}'.", + "Base_class_expressions_cannot_reference_class_type_parameters_2562": "Les expressions de classe de base ne peuvent pas référencer les paramètres de type de classe.", + "Base_constructor_return_type_0_is_not_a_class_or_interface_type_2509": "Le type de retour du constructeur de base '{0}' n'est pas un type de classe ou d'interface.", + "Base_constructors_must_all_have_the_same_return_type_2510": "Les constructeurs de base doivent tous avoir le même type de retour.", + "Base_directory_to_resolve_non_absolute_module_names_6083": "Répertoire de base pour la résolution des noms de modules non absolus.", + "Basic_Options_6172": "Options de base", + "Binary_digit_expected_1177": "Chiffre binaire attendu.", + "Binding_element_0_implicitly_has_an_1_type_7031": "L'élément de liaison '{0}' possède implicitement un type '{1}'.", + "Block_scoped_variable_0_used_before_its_declaration_2448": "Variable de portée de bloc '{0}' utilisée avant sa déclaration.", + "Build_all_projects_including_those_that_appear_to_be_up_to_date_6368": "Générer tous les projets, même ceux qui semblent être à jour", + "Build_one_or_more_projects_and_their_dependencies_if_out_of_date_6364": "Générer un ou plusieurs projets et leurs dépendances (s'ils sont obsolètes)", + "Building_project_0_6358": "Génération du projet '{0}'...", + "Call_decorator_expression_90028": "Appeler l'expression de l'élément décoratif", + "Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7020": "La signature d'appel, qui ne dispose pas d'annotation de type de retour, possède implicitement un type de retour 'any'.", + "Call_target_does_not_contain_any_signatures_2346": "La cible de l'appel ne contient aucune signature.", + "Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_p_2713": "Impossible d'accéder à '{0}.{1}', car '{0}' est un type, mais pas un espace de noms. Voulez-vous plutôt récupérer le type de la propriété '{1}' dans '{0}' avec '{0}[\"{1}\"]' ?", + "Cannot_assign_a_0_constructor_type_to_a_1_constructor_type_2672": "Impossible d'assigner un type de constructeur '{0}' à un type de constructeur '{1}'.", + "Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type_2517": "Impossible d'attribuer un type de constructeur abstrait à un type de constructeur non abstrait.", + "Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property_2540": "Impossible d'effectuer une assignation à '{0}', car il s'agit d'une constante ou d'une propriété en lecture seule.", + "Cannot_assign_to_0_because_it_is_not_a_variable_2539": "Impossible d'effectuer une assignation à '{0}', car il ne s'agit pas d'une variable.", + "Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity_2671": "Impossible d'augmenter le module '{0}', car il se résout en une entité non-module.", + "Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity_2649": "Impossible d'augmenter le module '{0}' avec des exportations de valeurs, car il se résout en une entité non-module.", + "Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system_6131": "Impossible de compiler des modules à l'aide de l'option '{0}' tant que l'indicateur '--module' n'a pas la valeur 'amd' ou 'system'.", + "Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided_1208": "Impossible de compiler des espaces de noms quand l'indicateur '--isolatedModules' est fourni.", + "Cannot_create_an_instance_of_an_abstract_class_2511": "Impossible de créer une instance d'une classe abstraite.", + "Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module_2661": "Impossible d'exporter '{0}'. Seules les déclarations locales peuvent être exportées à partir d'un module.", + "Cannot_extend_a_class_0_Class_constructor_is_marked_as_private_2675": "Impossible d'étendre une classe '{0}'. Le constructeur de classe est marqué comme étant privé.", + "Cannot_extend_an_interface_0_Did_you_mean_implements_2689": "Impossible d'étendre une interface '{0}'. Vouliez-vous dire 'implements' ?", + "Cannot_find_a_tsconfig_json_file_at_the_specified_directory_Colon_0_5057": "Le fichier tsconfig.json est introuvable dans le répertoire spécifié : '{0}'.", + "Cannot_find_global_type_0_2318": "Le type global '{0}' est introuvable.", + "Cannot_find_global_value_0_2468": "La valeur globale '{0}' est introuvable.", + "Cannot_find_lib_definition_for_0_2726": "Définition de lib introuvable pour '{0}'.", + "Cannot_find_lib_definition_for_0_Did_you_mean_1_2727": "Définition de lib introuvable pour '{0}'. Est-ce qu'il ne s'agit pas plutôt de '{1}' ?", + "Cannot_find_module_0_2307": "Le module '{0}' est introuvable.", + "Cannot_find_name_0_2304": "Le nom '{0}' est introuvable.", + "Cannot_find_name_0_Did_you_mean_1_2552": "Le nom '{0}' est introuvable. Est-ce qu'il ne s'agit pas plutôt de '{1}' ?", + "Cannot_find_name_0_Did_you_mean_the_instance_member_this_0_2663": "Le nom '{0}' est introuvable. Voulez-vous utiliser le membre d'instance 'this.{0}' ?", + "Cannot_find_name_0_Did_you_mean_the_static_member_1_0_2662": "Le nom '{0}' est introuvable. Voulez-vous utiliser le membre statique '{1}.{0}' ?", + "Cannot_find_namespace_0_2503": "L'espace de noms '{0}' est introuvable.", + "Cannot_find_parameter_0_1225": "Paramètre '{0}' introuvable.", + "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009": "Impossible de trouver le chemin d'accès au sous-répertoire commun pour les fichiers d'entrée.", + "Cannot_find_type_definition_file_for_0_2688": "Le fichier de définition de type est introuvable pour '{0}'.", + "Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1_6137": "Impossible d'importer les fichiers de déclaration de type. Importez '{0}' à la place de '{1}'.", + "Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1_2481": "Impossible d'initialiser la variable de portée externe '{0}' dans la même portée que celle de la déclaration de portée de bloc '{1}'.", + "Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatur_2349": "Impossible d'appeler une expression dont le type n'a pas de signature d'appel. Le type '{0}' n'a aucune signature d'appel compatible.", + "Cannot_invoke_an_object_which_is_possibly_null_2721": "Impossible d'appeler un objet qui a éventuellement une valeur 'null'.", + "Cannot_invoke_an_object_which_is_possibly_null_or_undefined_2723": "Impossible d'appeler un objet qui a éventuellement une valeur 'null' ou 'undefined'.", + "Cannot_invoke_an_object_which_is_possibly_undefined_2722": "Impossible d'appeler un objet qui a éventuellement une valeur 'undefined'.", + "Cannot_prepend_project_0_because_it_does_not_have_outFile_set_6308": "Impossible de préfixer le projet '{0}', car 'outFile' n'est pas défini", + "Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205": "Impossible de réexporter un type quand l'indicateur '--isolatedModules' est spécifié.", + "Cannot_read_file_0_Colon_1_5012": "Impossible de lire le fichier '{0}' : {1}.", + "Cannot_redeclare_block_scoped_variable_0_2451": "Impossible de redéclarer la variable de portée de bloc '{0}'.", + "Cannot_redeclare_exported_variable_0_2323": "Impossible de redéclarer la variable exportée '{0}'.", + "Cannot_redeclare_identifier_0_in_catch_clause_2492": "Impossible de redéclarer l'identificateur '{0}' dans la clause catch.", + "Cannot_use_JSX_unless_the_jsx_flag_is_provided_17004": "Impossible d'utiliser JSX, sauf si l'indicateur '--jsx' est fourni.", + "Cannot_use_imports_exports_or_module_augmentations_when_module_is_none_1148": "Impossible d'utiliser des importations, des exportations ou des augmentations de module quand '--module' a la valeur 'none'.", + "Cannot_use_namespace_0_as_a_type_2709": "Impossible d'utiliser l'espace de noms '{0}' en tant que type.", + "Cannot_use_namespace_0_as_a_value_2708": "Impossible d'utiliser l'espace de noms '{0}' en tant que valeur.", + "Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature_2351": "Impossible d'utiliser 'new' avec une expression dont le type ne possède pas de signature d'appel ou de construction.", + "Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files_5056": "Impossible d'écrire le fichier '{0}', car il serait remplacé par plusieurs fichiers d'entrée.", + "Cannot_write_file_0_because_it_would_overwrite_input_file_5055": "Impossible d'écrire le fichier '{0}', car cela entraînerait le remplacement du fichier d'entrée.", + "Catch_clause_variable_cannot_have_a_type_annotation_1196": "Une variable de clause catch ne peut pas avoir d'annotation de type.", + "Catch_clause_variable_cannot_have_an_initializer_1197": "Une variable de clause catch ne peut pas avoir d'initialiseur.", + "Change_0_to_1_90014": "Changer '{0}' en '{1}'", + "Change_all_extended_interfaces_to_implements_95038": "Remplacer toutes les interfaces étendues par 'implements'", + "Change_all_jsdoc_style_types_to_TypeScript_95030": "Remplacer tous les types jsdoc-style par TypeScript", + "Change_all_jsdoc_style_types_to_TypeScript_and_add_undefined_to_nullable_types_95031": "Remplacer tous les types jsdoc-type par TypeScript (et ajouter '| undefined' aux types nullable)", + "Change_extends_to_implements_90003": "Changer 'extends' en 'implements'", + "Change_spelling_to_0_90022": "Changer l'orthographe en '{0}'", + "Checking_if_0_is_the_longest_matching_prefix_for_1_2_6104": "Vérification en cours pour déterminer si '{0}' est le préfixe correspondant le plus long pour '{1}' - '{2}'.", + "Circular_definition_of_import_alias_0_2303": "Définition circulaire de l'alias d'importation '{0}'.", + "Circularity_detected_while_resolving_configuration_Colon_0_18000": "Circularité détectée durant la résolution de la configuration : {0}", + "Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_functi_2426": "La classe '{0}' définit l'accesseur de membre d'instance '{1}', mais la classe étendue '{2}' le définit comme fonction de membre d'instance.", + "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_access_2423": "La classe '{0}' définit la fonction de membre d'instance '{1}', mais la classe étendue '{2}' la définit comme accesseur de membre d'instance.", + "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_proper_2424": "La classe '{0}' définit la fonction de membre d'instance '{1}', mais la classe étendue '{2}' le définit comme propriété de membre d'instance.", + "Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_functi_2425": "La classe '{0}' définit la propriété de membre d'instance '{1}', mais la classe étendue '{2}' le définit comme fonction de membre d'instance.", + "Class_0_incorrectly_extends_base_class_1_2415": "La classe '{0}' étend de manière incorrecte la classe de base '{1}'.", + "Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclas_2720": "La classe '{0}' implémente de manière incorrecte la classe '{1}'. Voulez-vous vraiment étendre '{1}' et hériter de ses membres en tant que sous-classe ?", + "Class_0_incorrectly_implements_interface_1_2420": "La classe '{0}' implémente de manière incorrecte l'interface '{1}'.", + "Class_0_used_before_its_declaration_2449": "Classe '{0}' utilisée avant sa déclaration.", + "Class_declarations_cannot_have_more_than_one_augments_or_extends_tag_8025": "Les déclarations de classes ne peuvent pas avoir plusieurs balises '@augments' ou '@extends'.", + "Class_name_cannot_be_0_2414": "Le nom de la classe ne peut pas être '{0}'.", + "Class_name_cannot_be_Object_when_targeting_ES5_with_module_0_2725": "Le nom de la classe ne peut pas être 'Object' quand ES5 est ciblé avec le module {0}.", + "Class_static_side_0_incorrectly_extends_base_class_static_side_1_2417": "Le côté statique de la classe '{0}' étend de manière incorrecte le côté statique de la classe de base '{1}'.", + "Classes_can_only_extend_a_single_class_1174": "Les classes ne peuvent étendre qu'une seule classe.", + "Classes_containing_abstract_methods_must_be_marked_abstract_2514": "Les classes contenant des méthodes abstraites doivent être marquées comme étant abstraites.", + "Command_line_Options_6171": "Options de ligne de commande", + "Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json_6020": "Compilez le projet en fonction du chemin de son fichier config ou d'un dossier contenant 'tsconfig.json'.", + "Compiler_option_0_expects_an_argument_6044": "L'option de compilateur '{0}' attend an argument.", + "Compiler_option_0_requires_a_value_of_type_1_5024": "L'option de compilateur '{0}' exige une valeur de type {1}.", + "Composite_projects_may_not_disable_declaration_emit_6304": "Les projets composites ne doivent pas désactiver l'émission de déclaration.", + "Computed_property_names_are_not_allowed_in_enums_1164": "Les noms de propriétés calculées ne sont pas autorisés dans les enums.", + "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553": "Les valeurs calculées ne sont pas autorisées dans un enum avec des membres ayant une valeur de chaîne.", + "Concatenate_and_emit_output_to_single_file_6001": "Concaténer la sortie et l'émettre vers un seul fichier.", + "Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_librar_4090": "Définitions en conflit pour '{0}' sur '{1}' et '{2}'. Installez une version spécifique de cette bibliothèque pour résoudre le conflit.", + "Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7013": "La signature de construction, qui ne dispose pas d'annotation de type de retour, possède implicitement un type de retour 'any'.", + "Constructor_implementation_is_missing_2390": "L'implémentation de constructeur est manquante.", + "Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration_2673": "Le constructeur de la classe '{0}' est privé et uniquement accessible dans la déclaration de classe.", + "Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration_2674": "Le constructeur de la classe '{0}' est protégé et uniquement accessible dans la déclaration de classe.", + "Constructors_for_derived_classes_must_contain_a_super_call_2377": "Les constructeurs pour les classes dérivées doivent contenir un appel de 'super'.", + "Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126": "Fichier conteneur non spécifié et répertoire racine impossible à déterminer. Recherche ignorée dans le dossier 'node_modules'.", + "Convert_0_to_mapped_object_type_95055": "Convertir '{0}' en type d'objet mappé", + "Convert_all_constructor_functions_to_classes_95045": "Convertir toutes les fonctions de constructeur en classes", + "Convert_all_require_to_import_95048": "Convertir tous les 'require' en 'import'", + "Convert_all_to_default_imports_95035": "Convertir tout en importations par défaut", + "Convert_function_0_to_class_95002": "Convertir la fonction '{0}' en classe", + "Convert_function_to_an_ES2015_class_95001": "Convertir la fonction en classe ES2015", + "Convert_named_imports_to_namespace_import_95057": "Convertir les importations nommées en importation d'espace de noms", + "Convert_namespace_import_to_named_imports_95056": "Convertir l'importation d'espace de noms en importations nommées", + "Convert_require_to_import_95047": "Convertir 'require' en 'import'", + "Convert_to_ES6_module_95017": "Convertir en module ES6", + "Convert_to_default_import_95013": "Convertir en importation par défaut", + "Corrupted_locale_file_0_6051": "Fichier de paramètres régionaux endommagé : {0}.", + "Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type_7016": "Le fichier de déclaration du module '{0}' est introuvable. '{1}' a implicitement un type 'any'.", + "Could_not_write_file_0_Colon_1_5033": "Impossible d'écrire le fichier '{0}' : {1}.", + "DIRECTORY_6038": "RÉPERTOIRE", + "Declaration_expected_1146": "Déclaration attendue.", + "Declaration_name_conflicts_with_built_in_global_identifier_0_2397": "Le nom de la déclaration est en conflit avec l'identificateur global intégré '{0}'.", + "Declaration_or_statement_expected_1128": "Déclaration ou instruction attendue.", + "Declare_method_0_90023": "Déclarer la méthode '{0}'", + "Declare_property_0_90016": "Déclarer la propriété '{0}'", + "Declare_static_method_0_90024": "Déclarer la méthode statique '{0}'", + "Declare_static_property_0_90027": "Déclarer la propriété statique '{0}'", + "Decorators_are_not_valid_here_1206": "Les éléments décoratifs ne sont pas valides ici.", + "Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name_1207": "Impossible d'appliquer des éléments décoratifs à plusieurs accesseurs get/set du même nom.", + "Default_export_of_the_module_has_or_is_using_private_name_0_4082": "L'exportation par défaut du module a utilisé ou utilise le nom privé '{0}'.", + "Delete_all_unused_declarations_95024": "Supprimer toutes les déclarations inutilisées", + "Delete_the_outputs_of_all_projects_6365": "Supprimer les sorties de tous les projets", + "Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react__6084": "[Déconseillé] Utilisez '--jsxFactory' à la place. Permet de spécifier l'objet appelé pour createElement durant le ciblage de 'react' pour l'émission JSX", + "Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file_6170": "[Déconseillé] Utilisez '--outFile' à la place. Permet de concaténer et d'émettre la sortie vers un seul fichier", + "Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files_6160": "[Déconseillé] Utilisez '--skipLibCheck' à la place. Permet d'ignorer le contrôle de type des fichiers de déclaration de la bibliothèque par défaut.", + "Digit_expected_1124": "Chiffre attendu", + "Directory_0_does_not_exist_skipping_all_lookups_in_it_6148": "Le répertoire '{0}' n'existe pas. Toutes les recherches associées sont ignorées.", + "Disable_checking_for_this_file_90018": "Désactiver la vérification de ce fichier", + "Disable_size_limitations_on_JavaScript_projects_6162": "Désactivez les limitations de taille sur les projets JavaScript.", + "Disable_strict_checking_of_generic_signatures_in_function_types_6185": "Désactivez la vérification stricte des signatures génériques dans les types de fonction.", + "Disallow_inconsistently_cased_references_to_the_same_file_6078": "Interdisez les références dont la casse est incohérente dans le même fichier.", + "Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files_6159": "N'ajoutez pas de références avec trois barres obliques, ni de modules importés à la liste des fichiers compilés.", + "Do_not_emit_comments_to_output_6009": "Ne pas émettre de commentaires dans la sortie.", + "Do_not_emit_declarations_for_code_that_has_an_internal_annotation_6056": "N'émettez pas de déclarations pour du code ayant une annotation '@internal'.", + "Do_not_emit_outputs_6010": "N'émettez pas de sorties.", + "Do_not_emit_outputs_if_any_errors_were_reported_6008": "N'émettez pas de sortie si des erreurs sont signalées.", + "Do_not_emit_use_strict_directives_in_module_output_6112": "N'émettez pas de directives 'use strict' dans une sortie de module.", + "Do_not_erase_const_enum_declarations_in_generated_code_6007": "N'effacez pas les déclarations d'enum const dans le code généré.", + "Do_not_generate_custom_helper_functions_like_extends_in_compiled_output_6157": "Ne générez pas de fonctions d'assistance personnalisées comme '__extends' dans la sortie compilée.", + "Do_not_include_the_default_library_file_lib_d_ts_6158": "N'incluez pas le fichier bibliothèque par défaut (lib.d.ts).", + "Do_not_report_errors_on_unreachable_code_6077": "Ne signalez pas les erreurs pour le code inaccessible.", + "Do_not_report_errors_on_unused_labels_6074": "Ne signalez pas les erreurs pour les étiquettes inutilisées.", + "Do_not_resolve_the_real_path_of_symlinks_6013": "Ne pas résoudre le chemin réel des liens symboliques.", + "Do_not_truncate_error_messages_6165": "Ne tronquez pas les messages d'erreur.", + "Duplicate_declaration_0_2718": "Déclaration '{0}' dupliquée.", + "Duplicate_function_implementation_2393": "Implémentation de fonction en double.", + "Duplicate_identifier_0_2300": "Identificateur '{0}' en double.", + "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_2441": "Identificateur '{0}' en double. Le compilateur réserve le nom '{1}' dans l'étendue de plus haut niveau d'un module.", + "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_func_2529": "Identificateur '{0}' en double. Le compilateur réserve le nom '{1}' dans la portée de plus haut niveau d'un module contenant des fonctions async.", + "Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions_2520": "Identificateur '{0}' en double. Le compilateur utilise la déclaration '{1}' pour prendre en charge les fonctions async.", + "Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters_2396": "Identificateur dupliqué 'arguments'. Le compilateur utilise 'arguments' pour initialiser les paramètres rest.", + "Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_me_2543": "Dupliquez l'identificateur '_newTarget'. Le compilateur utilise la déclaration de variable '_newTarget' pour capturer la référence de méta-propriété 'new.target'.", + "Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference_2401": "Identificateur dupliqué '_super'. Le compilateur utilise '_super' pour capturer la référence de classe de base.", + "Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference_2399": "Identificateur dupliqué '_this'. Le compilateur utilise la déclaration de variable '_this' pour capturer la référence 'this'.", + "Duplicate_label_0_1114": "Étiquette '{0}' en double.", + "Duplicate_number_index_signature_2375": "Signature d'index de nombre dupliquée.", + "Duplicate_string_index_signature_2374": "Signature d'index de chaîne dupliquée.", + "Dynamic_import_cannot_have_type_arguments_1326": "L'importation dynamique ne peut pas avoir d'arguments de type", + "Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext_1323": "L'importation dynamique est prise en charge uniquement quand l'indicateur '--module' a la valeur 'commonjs' ou 'esNext'.", + "Dynamic_import_must_have_one_specifier_as_an_argument_1324": "L'importation dynamique doit avoir un seul spécificateur comme argument.", + "Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036": "Le spécificateur de l'importation dynamique doit être de type 'string', mais ici il est de type '{0}'.", + "Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015": "L'élément possède implicitement un type 'any', car l'expression d'index n'est pas de type 'number'.", + "Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature_7017": "L'élément a implicitement un type 'any', car le type '{0}' n'a aucune signature d'index.", + "Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files_6164": "Émettez une marque d'ordre d'octet (BOM) UTF-8 au début des fichiers de sortie.", + "Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file_6151": "Émettez un seul fichier avec des mappages de sources au lieu d'avoir un fichier distinct.", + "Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap__6152": "Émettez la source aux côtés des mappages de sources dans un fichier unique. Nécessite la définition de '--inlineSourceMap' ou '--sourceMap'.", + "Enable_all_strict_type_checking_options_6180": "Activez toutes les options de contrôle de type strict.", + "Enable_project_compilation_6302": "Activer la compilation du projet", + "Enable_strict_checking_of_function_types_6186": "Activez la vérification stricte des types de fonction.", + "Enable_strict_checking_of_property_initialization_in_classes_6187": "Activez la vérification stricte de l'initialisation des propriétés dans les classes.", + "Enable_strict_null_checks_6113": "Activez strict null checks.", + "Enable_tracing_of_the_name_resolution_process_6085": "Activez le traçage du processus de résolution de noms.", + "Enable_verbose_logging_6366": "Activer la journalisation détaillée", + "Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for__7037": "Active l'interopérabilité entre les modules CommonJS et ES via la création d'objets d'espace de noms pour toutes les importations. Implique 'allowSyntheticDefaultImports'.", + "Enables_experimental_support_for_ES7_async_functions_6068": "Active la prise en charge expérimentale des fonctions async ES7.", + "Enables_experimental_support_for_ES7_decorators_6065": "Active la prise en charge expérimentale des éléments décoratifs ES7.", + "Enables_experimental_support_for_emitting_type_metadata_for_decorators_6066": "Active la prise en charge expérimentale pour l'émission des métadonnées de type pour les éléments décoratifs.", + "Enum_0_used_before_its_declaration_2450": "Enum '{0}' utilisé avant sa déclaration.", + "Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations_2567": "Les déclarations enum ne peuvent fusionner qu'avec des espaces de noms ou d'autres déclarations enum.", + "Enum_declarations_must_all_be_const_or_non_const_2473": "Les déclarations d'enum doivent toutes être const ou non const.", + "Enum_member_expected_1132": "Membre enum attendu.", + "Enum_member_must_have_initializer_1061": "Un membre enum doit posséder un initialiseur.", + "Enum_name_cannot_be_0_2431": "Le nom d'enum ne peut pas être '{0}'.", + "Enum_type_0_has_members_with_initializers_that_are_not_literals_2535": "Le type enum '{0}' a des membres dont les initialiseurs ne sont pas des littéraux.", + "Examples_Colon_0_6026": "Exemples : {0}", + "Excessive_stack_depth_comparing_types_0_and_1_2321": "Profondeur excessive de la pile pour la comparaison des types '{0}' et '{1}'.", + "Expected_0_1_type_arguments_provide_these_with_an_extends_tag_8027": "Arguments de type {0}-{1} attendus ; indiquez-les avec la balise '@extends'.", + "Expected_0_arguments_but_got_1_2554": "{0} arguments attendus, mais {1} reçus.", + "Expected_0_arguments_but_got_1_or_more_2556": "{0} arguments attendus, mais {1} ou plus reçus.", + "Expected_0_type_arguments_but_got_1_2558": "{0} arguments de type attendus, mais {1} reçus.", + "Expected_0_type_arguments_provide_these_with_an_extends_tag_8026": "Arguments de type {0} attendus ; indiquez-les avec la balise '@extends'.", + "Expected_at_least_0_arguments_but_got_1_2555": "Au moins {0} arguments attendus, mais {1} reçus.", + "Expected_at_least_0_arguments_but_got_1_or_more_2557": "Au moins {0} arguments attendus, mais {1} ou plus reçus.", + "Expected_corresponding_JSX_closing_tag_for_0_17002": "Balise de fermeture JSX correspondante attendue pour '{0}'.", + "Expected_corresponding_closing_tag_for_JSX_fragment_17015": "Balise de fermeture correspondante attendue pour le fragment JSX.", + "Expected_type_of_0_field_in_package_json_to_be_string_got_1_6105": "Le type du champ '{0}' attendu dans 'package.json' est censé être 'string'. Obtention de '{1}'.", + "Experimental_Options_6177": "Options expérimentales", + "Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_t_1219": "La prise en charge expérimentale des éléments décoratifs est une fonctionnalité (feature) susceptible d'être changée dans une future mise en production. Définissez l'option '--experimentalDecorators' pour supprimer cet avertissement.", + "Explicitly_specified_module_resolution_kind_Colon_0_6087": "Spécification explicite du genre de résolution de module : '{0}'.", + "Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or__1203": "Vous ne pouvez pas utiliser l'assignation d'exportation pour cibler des modules ECMAScript. Utilisez 'export default' ou un autre format de module à la place.", + "Export_assignment_is_not_supported_when_module_flag_is_system_1218": "L'assignation d'exportation n'est pas prise en charge quand l'indicateur '--module' est 'system'.", + "Export_declaration_conflicts_with_exported_declaration_of_0_2484": "La déclaration d'exportation est en conflit avec la déclaration exportée de '{0}'.", + "Export_declarations_are_not_permitted_in_a_namespace_1194": "Les déclarations d'exportation ne sont pas autorisées dans un espace de noms.", + "Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_2656": "Le fichier de typages du package externe exporté '{0}' n'est pas un module. Contactez l'auteur du package pour mettre à jour la définition du package.", + "Exported_external_package_typings_file_cannot_contain_tripleslash_references_Please_contact_the_pack_2654": "Le fichier de typages du package externe exporté ne peut pas contenir de références avec trois barres obliques. Contactez l'auteur du package pour mettre à jour la définition du package.", + "Exported_type_alias_0_has_or_is_using_private_name_1_4081": "L'alias de type exporté '{0}' possède ou utilise le nom privé '{1}'.", + "Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4023": "La variable exportée '{0}' possède ou utilise le nom '{1}' du module externe {2}, mais elle ne peut pas être nommée.", + "Exported_variable_0_has_or_is_using_name_1_from_private_module_2_4024": "La variable exportée '{0}' possède ou utilise le nom '{1}' du module privé '{2}'.", + "Exported_variable_0_has_or_is_using_private_name_1_4025": "La variable exportée '{0}' possède ou utilise le nom privé '{1}'.", + "Exports_and_export_assignments_are_not_permitted_in_module_augmentations_2666": "Les exportations et les assignations d'exportation ne sont pas autorisées dans les augmentations de module.", + "Expression_expected_1109": "Expression attendue.", + "Expression_or_comma_expected_1137": "Expression ou virgule attendue.", + "Expression_resolves_to_super_that_compiler_uses_to_capture_base_class_reference_2402": "Expression résolue en '_super' et utilisée par le compilateur pour capturer la référence de classe de base.", + "Expression_resolves_to_variable_declaration_0_that_compiler_uses_to_support_async_functions_2521": "L'expression correspond à la déclaration de variable '{0}' que le compilateur utilise pour prendre en charge les fonctions async.", + "Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta__2544": "L'expression génère une déclaration de variable '_newTarget' que le compilateur utilise pour capturer la référence de méta-propriété 'new.target'.", + "Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference_2400": "Expression résolue en déclaration de variable '_this' et utilisée par le compilateur pour capturer la référence 'this'.", + "Extract_constant_95006": "Extraire la constante", + "Extract_function_95005": "Extraire la fonction", + "Extract_to_0_in_1_95004": "Extraire vers {0} dans {1}", + "Extract_to_0_in_1_scope_95008": "Extraire vers {0} dans la portée {1}", + "Extract_to_0_in_enclosing_scope_95007": "Extraire vers {0} dans la portée englobante", + "FILE_6035": "FICHIER", + "FILE_OR_DIRECTORY_6040": "FICHIER OU RÉPERTOIRE", + "Failed_to_parse_file_0_Colon_1_5014": "Échec de l'analyse du fichier '{0}' : {1}.", + "Fallthrough_case_in_switch_7029": "Case avec fallthrough dans une instruction switch.", + "File_0_does_not_exist_6096": "Le fichier '{0}' n'existe pas.", + "File_0_exist_use_it_as_a_name_resolution_result_6097": "Le fichier '{0}' existe. Utilisez-le comme résultat pour la résolution de noms.", + "File_0_has_an_unsupported_extension_so_skipping_it_6081": "Le fichier '{0}' a une extension non prise en charge. Il est ignoré.", + "File_0_has_unsupported_extension_The_only_supported_extensions_are_1_6054": "Le fichier '{0}' possède une extension non prise en charge. Les seules extensions prises en charge sont {1}.", + "File_0_is_not_a_module_2306": "Le fichier '{0}' n'est pas un module.", + "File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern_6307": "Le fichier '{0}' ne figure pas dans la liste de fichiers projet. Les projets doivent lister tous les fichiers ou utiliser un modèle 'include'.", + "File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files_6059": "Le fichier '{0}' ne se trouve pas sous 'rootDir' '{1}'. 'rootDir' est supposé contenir tous les fichiers sources.", + "File_0_not_found_6053": "Fichier '{0}' introuvable.", + "File_change_detected_Starting_incremental_compilation_6032": "Modification de fichier détectée. Démarrage de la compilation incrémentielle...", + "File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module_80001": "Le fichier est un module CommonJS ; il peut être converti en module ES6.", + "File_name_0_differs_from_already_included_file_name_1_only_in_casing_1149": "Le nom de fichier '{0}' diffère du nom de fichier '{1}' déjà inclus uniquement par la casse.", + "File_name_0_has_a_1_extension_stripping_it_6132": "Le nom de fichier '{0}' a une extension '{1}'. Suppression de l'extension.", + "File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildca_5065": "La spécification de fichier ne peut pas contenir un répertoire parent ('..') après un caractère générique de répertoire récursif ('**') : '{0}'.", + "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010": "Une spécification de fichier ne peut pas se terminer par un caractère générique de répertoire récursif ('**') : '{0}'.", + "Fix_all_detected_spelling_errors_95026": "Corriger toutes les fautes d'orthographe détectées", + "Found_0_errors_Watching_for_file_changes_6194": "{0} erreurs trouvées. Changements de fichier sous surveillance.", + "Found_1_error_Watching_for_file_changes_6193": "1 erreur trouvée. Changements de fichier sous surveillance.", + "Found_package_json_at_0_6099": "'package.json' trouvé sur '{0}'.", + "Found_package_json_at_0_Package_ID_is_1_6190": "'package.json' trouvé sur '{0}'. L'ID de package est '{1}'.", + "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_1250": "Les déclarations de fonction ne sont pas autorisées dans les blocs en mode strict durant le ciblage de la version 'ES3' ou 'ES5'.", + "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_d_1251": "Les déclarations de fonction ne sont pas autorisées dans les blocs en mode strict durant le ciblage de la version 'ES3' ou 'ES5'. Les définitions de classe sont automatiquement en mode strict.", + "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_1252": "Les déclarations de fonction ne sont pas autorisées dans les blocs en mode strict durant le ciblage de la version 'ES3' ou 'ES5'. Les modules sont automatiquement en mode strict.", + "Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type_7011": "L'expression de fonction, qui ne dispose pas d'annotation de type de retour, possède implicitement un type de retour '{0}'.", + "Function_implementation_is_missing_or_not_immediately_following_the_declaration_2391": "L'implémentation de fonction est manquante ou ne suit pas immédiatement la déclaration.", + "Function_implementation_name_must_be_0_2389": "Le nom de l'implémentation de fonction doit être '{0}'.", + "Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_ref_7024": "La fonction possède implicitement le type de retour 'any', car elle n'a pas d'annotation de type de retour, et est référencée directement ou indirectement dans l'une de ses expressions de retour.", + "Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined_2366": "La fonction n'a pas d'instruction return de fin, et le type de retour n'inclut pas 'undefined'.", + "Function_overload_must_be_static_2387": "La surcharge de fonction doit être statique.", + "Function_overload_must_not_be_static_2388": "La surcharge de fonction ne doit pas être statique.", + "Generate_get_and_set_accessors_95046": "Générer les accesseurs 'get' et 'set'", + "Generates_a_sourcemap_for_each_corresponding_d_ts_file_6000": "Génère un mappage de source pour chaque fichier '.d.ts' correspondant.", + "Generates_corresponding_d_ts_file_6002": "Génère le fichier '.d.ts' correspondant.", + "Generates_corresponding_map_file_6043": "Génère le fichier '.map' correspondant.", + "Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_typ_7025": "Le générateur a implicitement le type '{0}', car il ne produit aucune valeur. Fournissez plutôt un type de retour.", + "Generators_are_not_allowed_in_an_ambient_context_1221": "Les générateurs ne sont pas autorisés dans un contexte ambiant.", + "Generators_are_only_available_when_targeting_ECMAScript_2015_or_higher_1220": "Les générateurs sont disponibles uniquement quand ECMAScript 2015 ou version supérieure est ciblé.", + "Generic_type_0_requires_1_type_argument_s_2314": "Le type générique '{0}' exige {1} argument(s) de type.", + "Generic_type_0_requires_between_1_and_2_type_arguments_2707": "Le type générique '{0}' nécessite entre {1} et {2} arguments de type.", + "Generic_type_instantiation_is_excessively_deep_and_possibly_infinite_2550": "L'instanciation du type générique est trop profonde et éventuellement infinie.", + "Getter_and_setter_accessors_do_not_agree_in_visibility_2379": "Les accesseurs getter et setter ne sont pas en accord sur la visibilité.", + "Global_module_exports_may_only_appear_at_top_level_1316": "Les exportations de modules globaux ne peuvent apparaître qu'au niveau supérieur.", + "Global_module_exports_may_only_appear_in_declaration_files_1315": "Les exportations de modules globaux ne peuvent apparaître que dans les fichiers de déclaration.", + "Global_module_exports_may_only_appear_in_module_files_1314": "Les exportations de modules globaux ne peuvent apparaître que dans les fichiers de module.", + "Global_type_0_must_be_a_class_or_interface_type_2316": "Le type global '{0}' doit être un type de classe ou d'interface.", + "Global_type_0_must_have_1_type_parameter_s_2317": "Le type global '{0}' doit avoir {1} paramètre(s) de type.", + "Hexadecimal_digit_expected_1125": "Chiffre hexadécimal attendu.", + "Identifier_expected_0_is_a_reserved_word_in_strict_mode_1212": "Identificateur attendu. '{0}' est un mot réservé en mode strict.", + "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_stric_1213": "Identificateur attendu. '{0}' est un mot réservé en mode strict. Les définitions de classe sont automatiquement en mode strict.", + "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode_1214": "Identificateur attendu. '{0}' est un mot réservé en mode strict. Les modules sont automatiquement en mode strict.", + "Identifier_expected_1003": "Identificateur attendu.", + "Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules_1216": "Identificateur attendu. '__esModule' est réservé en tant que marqueur exporté durant la transformation des modules ECMAScript.", + "Ignore_this_error_message_90019": "Ignorer ce message d'erreur", + "Implement_all_inherited_abstract_classes_95040": "Implémenter toutes les classes abstraites héritées", + "Implement_all_unimplemented_interfaces_95032": "Implémenter toutes les interfaces non implémentées", + "Implement_inherited_abstract_class_90007": "Implémenter la classe abstraite héritée", + "Implement_interface_0_90006": "Implémenter l'interface '{0}'", + "Implements_clause_of_exported_class_0_has_or_is_using_private_name_1_4019": "La clause implements de la classe exportée '{0}' possède ou utilise le nom privé '{1}'.", + "Import_0_from_module_1_90013": "Importer '{0}' à partir du module \"{1}\"", + "Import_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_import_Asterisk_as_1202": "Vous ne pouvez pas utiliser l'assignation d'importation pour cibler des modules ECMAScript. Utilisez plutôt 'import * as ns from \"mod\"', 'import {a} from \"mod\"', 'import d from \"mod\"' ou un autre format de module.", + "Import_declaration_0_is_using_private_name_1_4000": "La déclaration d'importation '{0}' utilise le nom privé '{1}'.", + "Import_declaration_conflicts_with_local_declaration_of_0_2440": "La déclaration d'importation est en conflit avec la déclaration locale de '{0}'.", + "Import_declarations_in_a_namespace_cannot_reference_a_module_1147": "Les déclarations d'importation dans un espace de noms ne peuvent pas référencer un module.", + "Import_emit_helpers_from_tslib_6139": "Importer l'assistance à l'émission à partir de 'tslib'.", + "Import_may_be_converted_to_a_default_import_80003": "L'importation peut être convertie en importation par défaut.", + "Import_name_cannot_be_0_2438": "Le nom d'importation ne peut pas être '{0}'.", + "Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relati_2439": "Une déclaration d'importation ou d'exportation dans une déclaration de module ambiant ne peut référencer un module au moyen d'un nom de module relatif.", + "Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_mod_2667": "Les importations ne sont pas autorisées dans les augmentations de module. Déplacez-les vers le module externe englobant.", + "In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066": "Dans les déclarations d'enums ambiants, l'initialiseur de membre doit être une expression constante.", + "In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enu_2432": "Dans un enum avec plusieurs déclarations, seule une déclaration peut omettre un initialiseur pour son premier élément d'enum.", + "In_const_enum_declarations_member_initializer_must_be_constant_expression_2474": "Dans les déclarations d'enum 'const', l'initialiseur de membre doit être une expression constante.", + "Include_modules_imported_with_json_extension_6197": "Inclure les modules importés avec l'extension '.json'", + "Index_signature_in_type_0_only_permits_reading_2542": "La signature d'index du type '{0}' autorise uniquement la lecture.", + "Index_signature_is_missing_in_type_0_2329": "Signature d'index manquante dans le type '{0}'.", + "Index_signatures_are_incompatible_2330": "Les signatures d'index sont incompatibles.", + "Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local_2395": "Les déclarations individuelles de la déclaration fusionnée '{0}' doivent toutes être exportées ou locales.", + "Infer_all_types_from_usage_95023": "Déduire tous les types de l'utilisation", + "Infer_parameter_types_from_usage_95012": "Déduire les types des paramètres à partir de l'utilisation", + "Infer_type_of_0_from_usage_95011": "Déduire le type de '{0}' à partir de l'utilisation", + "Initialize_property_0_in_the_constructor_90020": "Initialiser la propriété '{0}' dans le constructeur", + "Initialize_static_property_0_90021": "Initialiser la propriété statique '{0}'", + "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301": "L'initialiseur de la variable membre d'instance '{0}' ne peut pas référencer l'identificateur '{1}' déclaré dans le constructeur.", + "Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it_2373": "L'initialiseur du paramètre '{0}' ne peut pas référencer l'identificateur '{1}' déclaré après lui.", + "Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value_2525": "L'initialiseur ne fournit aucune valeur pour cet élément de liaison, et ce dernier n'a pas de valeur par défaut.", + "Initializers_are_not_allowed_in_ambient_contexts_1039": "Les initialiseurs ne sont pas autorisés dans les contextes ambiants.", + "Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file_6070": "Initialise un projet TypeScript et crée un fichier tsconfig.json.", + "Insert_command_line_options_and_files_from_a_file_6030": "Insérer les options de ligne de commande et les fichiers à partir d'un fichier texte.", + "Install_0_95014": "Installer '{0}'", + "Install_all_missing_types_packages_95033": "Installer tous les packages de types manquants", + "Interface_0_cannot_simultaneously_extend_types_1_and_2_2320": "L'interface '{0}' ne peut pas étendre simultanément les types '{1}' et '{2}'.", + "Interface_0_incorrectly_extends_interface_1_2430": "L'interface '{0}' étend de manière incorrecte l'interface '{1}'.", + "Interface_declaration_cannot_have_implements_clause_1176": "Une déclaration d'interface ne peut pas avoir de clause 'implements'.", + "Interface_name_cannot_be_0_2427": "Le nom de l'interface ne peut pas être '{0}'.", + "Invalid_character_1127": "Caractère non valide.", + "Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augm_2665": "Nom de module non valide dans l'augmentation. Le module '{0}' est résolu en module non typé à l'emplacement '{1}', ce qui empêche toute augmentation.", + "Invalid_module_name_in_augmentation_module_0_cannot_be_found_2664": "Nom de module non valide dans l'augmentation. Le module '{0}' est introuvable.", + "Invalid_reference_directive_syntax_1084": "Syntaxe de directive 'reference' non valide.", + "Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode_1210": "Utilisation non valide de '{0}'. Les définitions de classe sont automatiquement en mode strict.", + "Invalid_use_of_0_Modules_are_automatically_in_strict_mode_1215": "Utilisation non valide de '{0}'. Les modules sont automatiquement en mode strict.", + "Invalid_use_of_0_in_strict_mode_1100": "Utilisation non valide de '{0}' en mode strict.", + "Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name_5067": "Valeur non valide pour 'jsxFactory'. '{0}' n'est pas un identificateur valide ou un nom qualifié.", + "Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier_5059": "Valeur non valide pour '--reactNamespace'. '{0}' n'est pas un identificateur valide.", + "JSDoc_0_1_does_not_match_the_extends_2_clause_8023": "La balise JSDoc '@{0} {1}' ne correspond pas à la clause 'extends {2}'.", + "JSDoc_0_is_not_attached_to_a_class_8022": "La balise JSDoc '@{0}' n'est pas attachée à une classe.", + "JSDoc_may_only_appear_in_the_last_parameter_of_a_signature_8028": "JSDoc '...' peut apparaître uniquement dans le dernier paramètre d'une signature.", + "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_8024": "La balise JSDoc '@param' se nomme '{0}', mais il n'existe aucun paramètre portant ce nom.", + "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_h_8029": "La balise JSDoc '@param' se nomme '{0}', mais il n'existe aucun paramètre portant ce nom. Elle doit correspondre à 'arguments', si elle est de type tableau.", + "JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags_8021": "La balise JSDoc '@typedef' doit avoir une annotation de type ou être suivie des balises '@property' ou '@member'.", + "JSDoc_types_can_only_be_used_inside_documentation_comments_8020": "Les types JSDoc peuvent uniquement être utilisés dans les commentaires de la documentation.", + "JSDoc_types_may_be_moved_to_TypeScript_types_80004": "Les types JSDoc peuvent être déplacés vers les types TypeScript.", + "JSX_attribute_expected_17003": "Attribut JSX attendu.", + "JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000": "Les attributs JSX doivent uniquement être attribués à une 'expression' non vide.", + "JSX_element_0_has_no_corresponding_closing_tag_17008": "L'élément JSX '{0}' n'a pas de balise de fermeture correspondante.", + "JSX_element_attributes_type_0_may_not_be_a_union_type_2600": "Le type '{0}' des attributs de l'élément JSX ne peut pas être un type union.", + "JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property_2607": "La classe de l'élément JSX ne prend pas en charge les attributs, car elle n'a pas de propriété '{0}'.", + "JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists_7026": "L'élément JSX a implicitement le type 'any', car il n'existe aucune interface 'JSX.{0}'.", + "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602": "L'élément JSX a implicitement le type 'any', car le type global 'JSX.Element' n'existe pas.", + "JSX_element_type_0_does_not_have_any_construct_or_call_signatures_2604": "Le type '{0}' de l'élément JSX n'a pas de signatures de construction ou d'appel.", + "JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements_2605": "Le type '{0}' de l'élément JSX n'est pas une fonction constructeur pour les éléments JSX.", + "JSX_elements_cannot_have_multiple_attributes_with_the_same_name_17001": "Les éléments JSX ne peuvent pas avoir plusieurs attributs du même nom.", + "JSX_expressions_must_have_one_parent_element_2657": "Les expressions JSX doivent avoir un élément parent.", + "JSX_fragment_has_no_corresponding_closing_tag_17014": "Le fragment JSX n'a pas de balise de fermeture correspondante.", + "JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma_17017": "Le fragment JSX n'est pas pris en charge quand vous utilisez un pragma de fabrique JSX inline", + "JSX_fragment_is_not_supported_when_using_jsxFactory_17016": "Le fragment JSX n'est pas pris en charge quand --jsxFactory est utilisé", + "JSX_spread_child_must_be_an_array_type_2609": "L'enfant spread JSX doit être un type de tableau.", + "Jump_target_cannot_cross_function_boundary_1107": "La cible du saut ne peut pas traverser une limite de fonction.", + "KIND_6034": "GENRE", + "LOCATION_6037": "EMPLACEMENT", + "Language_service_is_disabled_9004": "Le service de langage est désactivé.", + "Left_side_of_comma_operator_is_unused_and_has_no_side_effects_2695": "Le côté gauche de l'opérateur virgule n'est pas utilisé, et n'a aucun effet secondaire.", + "Line_break_not_permitted_here_1142": "Saut de ligne non autorisé ici.", + "Line_terminator_not_permitted_before_arrow_1200": "Marque de fin de ligne non autorisée devant une flèche.", + "List_of_folders_to_include_type_definitions_from_6161": "Liste des dossiers à partir desquels inclure les définitions de type.", + "List_of_language_service_plugins_6181": "Liste des plug-ins de service de langage.", + "List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime_6168": "Liste des dossiers racines dont le contenu combiné représente la structure du projet au moment de l'exécution.", + "Loading_0_from_the_root_dir_1_candidate_location_2_6109": "Chargement de '{0}' à partir du répertoire racine '{1}', emplacement candidat '{2}'.", + "Loading_module_0_from_node_modules_folder_target_file_type_1_6098": "Chargement du module '{0}' à partir du dossier 'node_modules'. Type du fichier cible '{1}'.", + "Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1_6095": "Chargement du module en tant que fichier/dossier. Emplacement du module candidat '{0}'. Type de fichier cible '{1}'.", + "Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1_6048": "Les paramètres régionaux doivent être sous la forme ou -. Par exemple, '{0}' ou '{1}'.", + "Longest_matching_prefix_for_0_is_1_6108": "Le préfixe correspondant le plus long pour '{0}' est '{1}'.", + "Looking_up_in_node_modules_folder_initial_location_0_6125": "Recherche dans le dossier 'node_modules', emplacement initial '{0}'.", + "Make_all_super_calls_the_first_statement_in_their_constructor_95036": "Faire de tous les appels 'super()' la première instruction dans leur constructeur", + "Make_super_call_the_first_statement_in_the_constructor_90002": "Faire de l'appel à 'super()' la première instruction du constructeur", + "Mapped_object_type_implicitly_has_an_any_template_type_7039": "Le type d'objet mappé a implicitement un type de modèle 'any'.", + "Member_0_implicitly_has_an_1_type_7008": "Le membre '{0}' possède implicitement un type '{1}'.", + "Merge_conflict_marker_encountered_1185": "Marqueur de conflit de fusion rencontré.", + "Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_d_2652": "La déclaration fusionnée '{0}' ne peut pas inclure de déclaration d'exportation par défaut. Ajoutez plutôt une déclaration 'export default {0}' distincte.", + "Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constru_17013": "La méta-propriété '{0}' n'est autorisée que dans le corps d'une déclaration de fonction, d'une expression de fonction ou d'un constructeur.", + "Method_0_cannot_have_an_implementation_because_it_is_marked_abstract_1245": "La méthode '{0}' ne peut pas avoir d'implémentation, car elle est marquée comme étant abstraite.", + "Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4101": "La méthode '{0}' de l'interface exportée comporte ou utilise le nom '{1}' du module privé '{2}'.", + "Method_0_of_exported_interface_has_or_is_using_private_name_1_4102": "La méthode '{0}' de l'interface exportée comporte ou utilise le nom privé '{1}'.", + "Modifiers_cannot_appear_here_1184": "Les modificateurs ne peuvent pas apparaître ici.", + "Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_1340": "Le module '{0}' ne fait pas référence à un type, mais est utilisé en tant que type ici.", + "Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here_1339": "Le module '{0}' ne fait pas référence à une valeur, mais est utilisé en tant que valeur ici.", + "Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambig_2308": "Le module {0} a déjà exporté un membre nommé '{1}'. Effectuez une réexportation explicite pour lever l'ambiguïté.", + "Module_0_has_no_default_export_1192": "Le module '{0}' n'a pas d'exportation par défaut.", + "Module_0_has_no_exported_member_1_2305": "Le module '{0}' n'a aucun membre exporté '{1}'.", + "Module_0_has_no_exported_member_1_Did_you_mean_2_2724": "Le module '{0}' n'a aucun membre exporté '{1}'. Pensiez-vous plutôt à '{2}' ?", + "Module_0_is_hidden_by_a_local_declaration_with_the_same_name_2437": "Le module '{0}' est masqué par une déclaration locale portant le même nom.", + "Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct_2497": "Le module '{0}' se résout en une entité non-module et ne peut pas être importé à l'aide de cette construction.", + "Module_0_uses_export_and_cannot_be_used_with_export_Asterisk_2498": "Le module '{0}' utilise 'export =' et ne peut pas être utilisé avec 'export *'.", + "Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified_6145": "Le module '{0}' a été résolu en tant que module ambiant déclaré dans '{1}', car ce fichier n'a pas été modifié.", + "Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1_6144": "Le module '{0}' a été résolu en tant que module ambiant déclaré localement dans le fichier '{1}'.", + "Module_0_was_resolved_to_1_but_jsx_is_not_set_6142": "Le module '{0}' a été résolu en '{1}' mais '--jsx' n'est pas défini.", + "Module_Resolution_Options_6174": "Options de résolution du module", + "Module_name_0_matched_pattern_1_6092": "Nom de module '{0}', modèle correspondant '{1}'.", + "Module_name_0_was_not_resolved_6090": "======== Le nom de module '{0}' n'a pas été résolu. ========", + "Module_name_0_was_successfully_resolved_to_1_6089": "======== Le nom de module '{0}' a été correctement résolu en '{1}'. ========", + "Module_resolution_kind_is_not_specified_using_0_6088": "Le genre de résolution de module n'est pas spécifié. Utilisation de '{0}'.", + "Module_resolution_using_rootDirs_has_failed_6111": "Échec de la résolution de module à l'aide de 'rootDirs'.", + "Move_to_a_new_file_95049": "Déplacer vers un nouveau fichier", + "Multiple_consecutive_numeric_separators_are_not_permitted_6189": "Les séparateurs numériques consécutifs multiples ne sont pas autorisés.", + "Multiple_constructor_implementations_are_not_allowed_2392": "Les implémentations de plusieurs constructeurs ne sont pas autorisées.", + "NEWLINE_6061": "NOUVELLE LIGNE", + "Named_property_0_of_types_1_and_2_are_not_identical_2319": "La propriété nommée '{0}' des types '{1}' et '{2}' n'est pas identique.", + "Namespace_0_has_no_exported_member_1_2694": "L'espace de noms '{0}' n'a aucun membre exporté '{1}'.", + "No_base_constructor_has_the_specified_number_of_type_arguments_2508": "Aucun constructeur de base n'a le nombre spécifié d'arguments de type.", + "No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2_18003": "Aucune entrée dans le fichier config '{0}'. Les chemins 'include' spécifiés étaient '{1}' et les chemins 'exclude' étaient '{2}'.", + "Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2_2515": "La classe non abstraite '{0}' n'implémente pas le membre abstrait '{1}' hérité de la classe '{2}'.", + "Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1_2653": "L'expression de classe non abstraite '{0}' n'implémente pas le membre abstrait hérité '{0}' de la classe '{1}'.", + "Not_all_code_paths_return_a_value_7030": "Les chemins de code ne retournent pas tous une valeur.", + "Numeric_index_type_0_is_not_assignable_to_string_index_type_1_2413": "Impossible d'assigner le type d'index numérique '{0}' au type d'index de chaîne '{1}'.", + "Numeric_separators_are_not_allowed_here_6188": "Les séparateurs numériques ne sont pas autorisés ici.", + "Object_is_of_type_unknown_2571": "L'objet est de type 'unknown'.", + "Object_is_possibly_null_2531": "L'objet a peut-être la valeur 'null'.", + "Object_is_possibly_null_or_undefined_2533": "L'objet a peut-être la valeur 'null' ou 'undefined'.", + "Object_is_possibly_undefined_2532": "L'objet a peut-être la valeur 'undefined'.", + "Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1_2353": "Un littéral d'objet peut uniquement spécifier des propriétés connues, et '{0}' n'existe pas dans le type '{1}'.", + "Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_writ_2561": "Un littéral d'objet peut uniquement spécifier des propriétés connues, mais '{0}' n'existe pas dans le type '{1}'. Est-ce que vous avez voulu écrire '{2}' ?", + "Object_literal_s_property_0_implicitly_has_an_1_type_7018": "La propriété '{0}' du littéral d'objet possède implicitement un type '{1}'.", + "Octal_digit_expected_1178": "Chiffre octal attendu.", + "Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0_8017": "Les types de littéral octal doivent utiliser la syntaxe ES2015. Utilisez la syntaxe '{0}'.", + "Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0_8018": "Les littéraux octaux ne sont pas autorisés dans l'initialiseur des membres d'enums. Utilisez la syntaxe '{0}'.", + "Octal_literals_are_not_allowed_in_strict_mode_1121": "Les littéraux octaux ne sont pas autorisés en mode strict.", + "Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0_1085": "Les littéraux octaux ne sont pas disponibles lorsque vous ciblez ECMAScript 5 et ultérieur. Utilisez la syntaxe '{0}'.", + "Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement_1091": "Une seule déclaration de variable est autorisée dans une instruction 'for...in'.", + "Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement_1188": "Seule une déclaration de variable unique est autorisée dans une instruction 'for...of'.", + "Only_a_void_function_can_be_called_with_the_new_keyword_2350": "Seule une fonction void peut être appelée avec le mot clé 'new'.", + "Only_ambient_modules_can_use_quoted_names_1035": "Seuls les modules ambiants peuvent utiliser des noms entre guillemets.", + "Only_amd_and_system_modules_are_supported_alongside_0_6082": "Seuls les modules 'amd' et 'system' sont pris en charge avec --{0}.", + "Only_emit_d_ts_declaration_files_6014": "Émettez uniquement les fichiers de déclaration '.d.ts'.", + "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002": "Seuls les identificateurs/noms qualifiés avec des arguments de type facultatifs sont pris en charge dans une clause 'extends' de classe.", + "Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword_2340": "Seules les méthodes publiques et protégées de la classe de base sont accessibles par le biais du mot clé 'super'.", + "Operator_0_cannot_be_applied_to_types_1_and_2_2365": "Impossible d'appliquer l'opérateur '{0}' aux types '{1}' et '{2}'.", + "Option_0_can_only_be_specified_in_tsconfig_json_file_6064": "L'option '{0}' ne peut être spécifiée que dans le fichier 'tsconfig.json'.", + "Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided_5051": "L'option '{0}' peut être utilisée uniquement quand l'option '--inlineSourceMap' ou l'option '--sourceMap' est spécifiée.", + "Option_0_cannot_be_specified_with_option_1_5053": "Impossible de spécifier l'option '{0}' avec l'option '{1}'.", + "Option_0_cannot_be_specified_without_specifying_option_1_5052": "Impossible de spécifier l'option '{0}' sans spécifier l'option '{1}'.", + "Option_0_cannot_be_specified_without_specifying_option_1_or_option_2_5069": "Impossible de spécifier l'option '{0}' sans spécifier l'option '{1}' ou l'option '{2}'.", + "Option_0_should_have_array_of_strings_as_a_value_6103": "L'option '{0}' doit avoir un tableau de chaînes en tant que valeur.", + "Option_build_must_be_the_first_command_line_argument_6369": "L'option '--build' doit être le premier argument de ligne de commande.", + "Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES_5047": "L'option 'isolatedModules' peut être utilisée seulement quand l'option '--module' est spécifiée, ou quand l'option 'target' a la valeur 'ES2015' ou une version supérieure.", + "Option_paths_cannot_be_used_without_specifying_baseUrl_option_5060": "Impossible d'utiliser l'option 'paths' sans spécifier l'option '--baseUrl'.", + "Option_project_cannot_be_mixed_with_source_files_on_a_command_line_5042": "Impossible d'associer l'option 'project' à des fichiers sources sur une ligne de commande.", + "Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070": "Impossible de spécifier l'option '--resolveJsonModule' sans la stratégie de résolution de module 'node'.", + "Options_0_and_1_cannot_be_combined_6370": "Impossible de combiner les options '{0}' et '{1}'.", + "Options_Colon_6027": "Options :", + "Output_directory_for_generated_declaration_files_6166": "Répertoire de sortie pour les fichiers de déclaration générés.", + "Output_file_0_from_project_1_does_not_exist_6309": "Le fichier de sortie '{0}' du projet '{1}' n'existe pas", + "Output_file_0_has_not_been_built_from_source_file_1_6305": "Le fichier de sortie '{0}' n'a pas été créé à partir du fichier source '{1}'.", + "Overload_signature_is_not_compatible_with_function_implementation_2394": "La signature de surcharge n'est pas compatible avec l'implémentation de fonction.", + "Overload_signatures_must_all_be_abstract_or_non_abstract_2512": "Les signatures de surcharge doivent toutes être abstraites ou non abstraites.", + "Overload_signatures_must_all_be_ambient_or_non_ambient_2384": "Les signatures de surcharge doivent toutes être ambiantes ou non ambiantes.", + "Overload_signatures_must_all_be_exported_or_non_exported_2383": "Les signatures de surcharge doivent toutes être exportées ou non exportées.", + "Overload_signatures_must_all_be_optional_or_required_2386": "Les signatures de surcharge doivent toutes être facultatives ou requises.", + "Overload_signatures_must_all_be_public_private_or_protected_2385": "Les signatures de surcharge doivent toutes être publiques, privées ou protégées.", + "Parameter_0_cannot_be_referenced_in_its_initializer_2372": "Le paramètre '{0}' ne peut pas être référencé dans son initialiseur.", + "Parameter_0_implicitly_has_an_1_type_7006": "Le paramètre '{0}' possède implicitement un type '{1}'.", + "Parameter_0_is_not_in_the_same_position_as_parameter_1_1227": "Le paramètre '{0}' n'est pas à la même position que le paramètre '{1}'.", + "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4066": "Le paramètre '{0}' de la signature d'appel de l'interface exportée possède ou utilise le nom '{1}' du module privé '{2}'.", + "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4067": "Le paramètre '{0}' de la signature d'appel de l'interface exportée possède ou utilise le nom privé '{1}'.", + "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_can_4061": "Le paramètre '{0}' du constructeur de la classe exportée possède ou utilise le nom '{1}' du module externe {2}, mais il ne peut pas être nommé.", + "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2_4062": "Le paramètre '{0}' du constructeur de la classe exportée possède ou utilise le nom '{1}' du module privé '{2}'.", + "Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1_4063": "Le paramètre '{0}' du constructeur de la classe exportée possède ou utilise le nom privé '{1}'.", + "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_mod_4064": "Le paramètre '{0}' de la signature de constructeur de l'interface exportée possède ou utilise le nom '{1}' du module privé '{2}'.", + "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4065": "Le paramètre '{0}' de la signature de constructeur de l'interface exportée possède ou utilise le nom privé '{1}'.", + "Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4076": "Le paramètre '{0}' de la fonction exportée possède ou utilise le nom '{1}' du module externe {2}, mais il ne peut pas être nommé.", + "Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2_4077": "Le paramètre '{0}' de la fonction exportée possède ou utilise le nom '{1}' du module privé '{2}'.", + "Parameter_0_of_exported_function_has_or_is_using_private_name_1_4078": "Le paramètre '{0}' de la fonction exportée possède ou utilise le nom privé '{1}'.", + "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4091": "Le paramètre '{0}' de la signature d'index de l'interface exportée a ou utilise le nom '{1}' du module privé '{2}'.", + "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1_4092": "Le paramètre '{0}' de la signature d'index de l'interface exportée a ou utilise le nom privé '{1}'.", + "Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4074": "Le paramètre '{0}' de la méthode de l'interface exportée possède ou utilise le nom '{1}' du module privé '{2}'.", + "Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4075": "Le paramètre '{0}' de la méthode de l'interface exportée possède ou utilise le nom privé '{1}'.", + "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_c_4071": "Le paramètre '{0}' de la méthode publique de la classe exportée possède ou utilise le nom '{1}' du module externe {2}, mais il ne peut pas être nommé.", + "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4072": "Le paramètre '{0}' de la méthode publique de la classe exportée possède ou utilise le nom '{1}' du module privé '{2}'.", + "Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4073": "Le paramètre '{0}' de la méthode publique de la classe exportée possède ou utilise le nom privé '{1}'.", + "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module__4068": "Le paramètre '{0}' de la méthode statique publique de la classe exportée possède ou utilise le nom '{1}' du module externe {2}, mais il ne peut pas être nommé.", + "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4069": "Le paramètre '{0}' de la méthode statique publique de la classe exportée possède ou utilise le nom '{1}' du module privé '{2}'.", + "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4070": "Le paramètre '{0}' de la méthode statique publique de la classe exportée possède ou utilise le nom privé '{1}'.", + "Parameter_cannot_have_question_mark_and_initializer_1015": "Un paramètre ne peut pas contenir de point d'interrogation et d'initialiseur.", + "Parameter_declaration_expected_1138": "Déclaration de paramètre attendue.", + "Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2_4036": "Le type de paramètre du setter public '{0}' de la classe exportée porte ou utilise le nom '{1}' du module privé '{2}'.", + "Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_private_name_1_4037": "Le type de paramètre du setter public '{0}' de la classe exportée porte ou utilise le nom privé '{1}'.", + "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_name_1_from_private_mod_4034": "Le type de paramètre du setter public '{0}' de la classe exportée porte ou utilise le nom '{1}' du module privé '{2}'.", + "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1_4035": "Le type de paramètre du setter public '{0}' de la classe exportée porte ou utilise le nom privé '{1}'.", + "Parse_in_strict_mode_and_emit_use_strict_for_each_source_file_6141": "Analyser en mode strict et émettre \"use strict\" pour chaque fichier source.", + "Pattern_0_can_have_at_most_one_Asterisk_character_5061": "Le modèle '{0}' ne peut avoir qu'un seul caractère '*' au maximum.", + "Prefix_0_with_an_underscore_90025": "Faire précéder '{0}' d'un trait de soulignement", + "Prefix_all_unused_declarations_with_where_possible_95025": "Préfixer toutes les déclarations inutilisées avec '_' si possible", + "Print_names_of_files_part_of_the_compilation_6155": "Imprimez les noms des fichiers faisant partie de la compilation.", + "Print_names_of_generated_files_part_of_the_compilation_6154": "Imprimez les noms des fichiers générés faisant partie de la compilation.", + "Print_the_compiler_s_version_6019": "Affichez la version du compilateur.", + "Print_this_message_6017": "Imprimez ce message.", + "Project_0_can_t_be_built_because_its_dependency_1_has_errors_6363": "Impossible de générer le projet '{0}' car sa dépendance '{1}' comporte des erreurs", + "Project_0_is_out_of_date_because_its_dependency_1_is_out_of_date_6353": "Le projet '{0}' est obsolète car sa dépendance '{1}' est obsolète", + "Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2_6350": "Le projet '{0}' est obsolète car la sortie la plus ancienne ('{1}') est antérieure à l'entrée la plus récente '{2}'", + "Project_0_is_out_of_date_because_output_file_1_does_not_exist_6352": "Le projet '{0}' est obsolète car le fichier de sortie '{1}' n'existe pas", + "Project_0_is_up_to_date_6361": "Le projet '{0}' est à jour", + "Project_0_is_up_to_date_because_newest_input_1_is_older_than_oldest_output_2_6351": "Le projet '{0}' est à jour car l'entrée la plus récente ('{1}') est antérieure à la sortie la plus ancienne ('{2}')", + "Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies_6354": "Le projet '{0}' est à jour avec les fichiers .d.ts de ses dépendances", + "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202": "Les références de projet ne peuvent pas former un graphe circulaire. Cycle détecté : {0}", + "Projects_in_this_build_Colon_0_6355": "Projets dans cette build : {0}", + "Projects_to_reference_6300": "Projets à référencer", + "Property_0_does_not_exist_on_const_enum_1_2479": "La propriété '{0}' n'existe pas sur l'enum 'const' '{1}'.", + "Property_0_does_not_exist_on_type_1_2339": "La propriété '{0}' n'existe pas sur le type '{1}'.", + "Property_0_does_not_exist_on_type_1_Did_you_forget_to_use_await_2570": "La propriété '{0}' n'existe pas sur le type '{1}'. Avez-vous oublié d'utiliser 'await' ?", + "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551": "La propriété '{0}' n'existe pas sur le type '{1}'. Est-ce qu'il ne s'agit pas plutôt de '{2}' ?", + "Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1_2546": "La propriété '{0}' a des déclarations en conflit et est inaccessible dans le type '{1}'.", + "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor_2564": "La propriété '{0}' n'a aucun initialiseur et n'est pas définitivement assignée dans le constructeur.", + "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033": "La propriété '{0}' a implicitement le type 'any', car son accesseur get ne dispose pas d'une annotation de type de retour.", + "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032": "La propriété '{0}' a implicitement le type 'any', car son accesseur set ne dispose pas d'une annotation de type de paramètre.", + "Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2_2416": "Impossible d'assigner la propriété '{0}' du type '{1}' à la même propriété du type de base '{2}'.", + "Property_0_in_type_1_is_not_assignable_to_type_2_2603": "La propriété '{0}' du type '{1}' ne peut pas être assignée au type '{2}'.", + "Property_0_is_declared_but_its_value_is_never_read_6138": "La propriété '{0}' est déclarée mais sa valeur n'est jamais lue.", + "Property_0_is_incompatible_with_index_signature_2530": "La propriété '{0}' est incompatible avec la signature d'index.", + "Property_0_is_missing_in_type_1_2324": "La propriété '{0}' est manquante dans le type '{1}'.", + "Property_0_is_optional_in_type_1_but_required_in_type_2_2327": "La propriété '{0}' est facultative dans le type '{1}', mais obligatoire dans le type '{2}'.", + "Property_0_is_private_and_only_accessible_within_class_1_2341": "La propriété '{0}' est privée et uniquement accessible dans la classe '{1}'.", + "Property_0_is_private_in_type_1_but_not_in_type_2_2325": "La propriété '{0}' est privée dans le type '{1}', mais pas dans le type '{2}'.", + "Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1_2446": "La propriété '{0}' est protégée et uniquement accessible par le biais d'une instance de la classe '{1}'.", + "Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses_2445": "La propriété '{0}' est protégée et uniquement accessible dans la classe '{1}' et ses sous-classes.", + "Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2_2443": "La propriété '{0}' est protégée, mais le type '{1}' n'est pas une classe dérivée de '{2}'.", + "Property_0_is_protected_in_type_1_but_public_in_type_2_2444": "La propriété '{0}' est protégée dans le type '{1}', mais publique dans le type '{2}'.", + "Property_0_is_used_before_being_assigned_2565": "La propriété '{0}' est utilisée avant d'être assignée.", + "Property_0_of_JSX_spread_attribute_is_not_assignable_to_target_property_2606": "Impossible d'assigner la propriété '{0}' de l'attribut spread JSX à la propriété cible.", + "Property_0_of_exported_class_expression_may_not_be_private_or_protected_4094": "La propriété '{0}' de l'expression de classe exportée ne peut pas être privée ou protégée.", + "Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4032": "La propriété '{0}' de l'interface exportée possède ou utilise le nom '{1}' du module privé '{2}'.", + "Property_0_of_exported_interface_has_or_is_using_private_name_1_4033": "La propriété '{0}' de l'interface exportée possède ou utilise le nom privé '{1}'.", + "Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2_2412": "Impossible d'assigner la propriété '{0}' de type '{1}' au type d'index numérique '{2}'.", + "Property_0_of_type_1_is_not_assignable_to_string_index_type_2_2411": "Impossible d'assigner la propriété '{0}' de type '{1}' au type d'index de chaîne '{2}'.", + "Property_assignment_expected_1136": "Assignation de propriété attendue.", + "Property_destructuring_pattern_expected_1180": "Modèle de déstructuration de propriété attendu.", + "Property_or_signature_expected_1131": "Propriété ou signature attendue.", + "Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_li_1328": "La valeur de la propriété peut être uniquement un littéral de chaîne, un littéral numérique, 'true', 'false', 'null', un littéral d'objet ou un littéral de tableau.", + "Provide_full_support_for_iterables_in_for_of_spread_and_destructuring_when_targeting_ES5_or_ES3_6179": "Fournissez une prise en charge complète des éléments pouvant faire l'objet d'une itération dans 'for-of', de l'opérateur spread et de la déstructuration durant le ciblage d''ES5' ou 'ES3'.", + "Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4098": "La méthode publique '{0}' de la classe exportée comporte ou utilise le nom '{1}' du module externe {2} mais ne peut pas être nommée.", + "Public_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4099": "La méthode publique '{0}' de la classe exportée comporte ou utilise le nom '{1}' du module privé '{2}'.", + "Public_method_0_of_exported_class_has_or_is_using_private_name_1_4100": "La méthode publique '{0}' de la classe exportée comporte ou utilise le nom privé '{1}'.", + "Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_name_4029": "La propriété publique '{0}' de la classe exportée possède ou utilise le nom '{1}' du module externe {2}, mais elle ne peut pas être nommée.", + "Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4030": "La propriété publique '{0}' de la classe exportée possède ou utilise le nom '{1}' du module privé '{2}'.", + "Public_property_0_of_exported_class_has_or_is_using_private_name_1_4031": "La propriété publique '{0}' de la classe exportée possède ou utilise le type privé '{1}'.", + "Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_4095": "La méthode statique publique '{0}' de la classe exportée comporte ou utilise le nom '{1}' du module externe {2} mais ne peut pas être nommée.", + "Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4096": "La méthode statique publique '{0}' de la classe exportée comporte ou utilise le nom '{1}' du module privé '{2}'.", + "Public_static_method_0_of_exported_class_has_or_is_using_private_name_1_4097": "La méthode statique publique '{0}' de la classe exportée comporte ou utilise le nom privé '{1}'.", + "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot__4026": "La propriété statique publique '{0}' de la classe exportée possède ou utilise le nom '{1}' du module externe {2}, mais elle ne peut pas être nommée.", + "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4027": "La propriété statique publique '{0}' de la classe exportée possède ou utilise le nom '{1}' du module privé '{2}'.", + "Public_static_property_0_of_exported_class_has_or_is_using_private_name_1_4028": "La propriété statique publique '{0}' de la classe exportée possède ou utilise le type privé '{1}'.", + "Raise_error_on_expressions_and_declarations_with_an_implied_any_type_6052": "Lever une erreur sur les expressions et les déclarations ayant un type 'any' implicite.", + "Raise_error_on_this_expressions_with_an_implied_any_type_6115": "Déclenche une erreur sur les expressions 'this' avec un type 'any' implicite.", + "Redirect_output_structure_to_the_directory_6006": "Rediriger la structure de sortie vers le répertoire.", + "Referenced_project_0_must_have_setting_composite_Colon_true_6306": "Le projet référencé '{0}' doit avoir le paramètre \"composite\" avec la valeur true.", + "Remove_all_unreachable_code_95051": "Supprimer tout le code inaccessible", + "Remove_all_unused_labels_95054": "Supprimer toutes les étiquettes inutilisées", + "Remove_braces_from_arrow_function_95060": "Supprimer les accolades de la fonction arrow", + "Remove_declaration_for_Colon_0_90004": "Supprimer la déclaration pour : '{0}'", + "Remove_destructuring_90009": "Supprimer la déstructuration", + "Remove_import_from_0_90005": "Supprimer l'importation de '{0}'", + "Remove_unreachable_code_95050": "Supprimer le code inaccessible", + "Remove_unused_label_95053": "Supprimer l'étiquette inutilisée", + "Remove_variable_statement_90010": "Supprimer l'instruction de variable", + "Replace_import_with_0_95015": "Remplacez l'importation par '{0}'.", + "Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "Signalez une erreur quand les chemins de code de la fonction ne retournent pas tous une valeur.", + "Report_errors_for_fallthrough_cases_in_switch_statement_6076": "Signalez les erreurs pour les case avec fallthrough dans une instruction switch.", + "Report_errors_in_js_files_8019": "Signalez les erreurs dans les fichiers .js.", + "Report_errors_on_unused_locals_6134": "Signaler les erreurs sur les variables locales inutilisées.", + "Report_errors_on_unused_parameters_6135": "Signaler les erreurs sur les paramètres inutilisés.", + "Required_type_parameters_may_not_follow_optional_type_parameters_2706": "Les paramètres de type obligatoires ne peuvent pas être placés à la suite des paramètres de type optionnels.", + "Resolution_for_module_0_was_found_in_cache_from_location_1_6147": "La résolution du module '{0}' a été trouvée dans le cache à l'emplacement '{1}'.", + "Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols_6195": "Résoudre 'keyof' en noms de propriétés de valeur chaîne uniquement (aucun nombre ou symbole).", + "Resolving_from_node_modules_folder_6118": "Résolution à partir du dossier node_modules...", + "Resolving_module_0_from_1_6086": "======== Résolution du module '{0}' à partir de '{1}'. ========", + "Resolving_module_name_0_relative_to_base_url_1_2_6094": "Résolution du nom de module '{0}' par rapport à l'URL de base '{1}' - '{2}'.", + "Resolving_real_path_for_0_result_1_6130": "Résolution du chemin réel pour '{0}', résultat '{1}'.", + "Resolving_type_reference_directive_0_containing_file_1_root_directory_2_6116": "======== Résolution de la directive de référence de type '{0}', fichier conteneur '{1}', répertoire racine '{2}'. ========", + "Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set_6123": "======== Résolution de la directive de référence de type '{0}', fichier conteneur '{1}', répertoire racine non défini. ========", + "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1_6127": "======== Résolution de la directive de référence de type '{0}', fichier conteneur non défini, répertoire racine '{1}'. ========", + "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set_6128": "======== Résolution de la directive de référence de type '{0}', fichier conteneur non défini, répertoire racine non défini. ========", + "Resolving_using_primary_search_paths_6117": "Résolution à l'aide des chemins de recherche primaires...", + "Resolving_with_primary_search_path_0_6121": "Résolution à l'aide du chemin de recherche primaire '{0}'.", + "Rest_parameter_0_implicitly_has_an_any_type_7019": "Le paramètre rest '{0}' possède implicitement un type 'any[]'.", + "Rest_types_may_only_be_created_from_object_types_2700": "Vous ne pouvez créer des types Rest qu'à partir de types d'objet.", + "Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4046": "Le type de retour de la signature d'appel de l'interface exportée possède ou utilise le nom '{0}' du module privé '{1}'.", + "Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0_4047": "Le type de retour de la signature d'appel de l'interface exportée possède ou utilise le nom privé '{0}'.", + "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_mod_4044": "Le type de retour de la signature de constructeur de l'interface exportée possède ou utilise le nom '{0}' du module privé '{1}'.", + "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0_4045": "Le type de retour de la signature de constructeur de l'interface exportée possède ou utilise le nom privé '{0}'.", + "Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class_2409": "Le type de retour de la signature de constructeur doit pouvoir être assigné au type d'instance de la classe.", + "Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named_4058": "Le type de retour de la fonction exportée possède ou utilise le nom '{0}' du module externe {1}, mais il ne peut pas être nommé.", + "Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1_4059": "Le type de retour de la fonction exportée possède ou utilise le nom '{0}' du module privé '{1}'.", + "Return_type_of_exported_function_has_or_is_using_private_name_0_4060": "Le type de retour de la fonction exportée possède ou utilise le nom privé '{0}'.", + "Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4048": "Le type de retour de la signature d'index de l'interface exportée possède ou utilise le nom '{0}' du module privé '{1}'.", + "Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0_4049": "Le type de retour de la signature d'index de l'interface exportée possède ou utilise le nom privé '{0}'.", + "Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4056": "Le type de retour de la méthode de l'interface exportée possède ou utilise le nom '{0}' du module privé '{1}'.", + "Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0_4057": "Le type de retour de la méthode de l'interface exportée possède ou utilise le nom privé '{0}'.", + "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_4041": "Le type de retour du getter public '{0}' de la classe exportée porte ou utilise le nom '{1}' du module externe {2}, mais il ne peut pas être nommé.", + "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2_4042": "Le type de retour du getter public '{0}' de la classe exportée porte ou utilise le nom '{1}' du module privé '{2}'.", + "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_private_name_1_4043": "Le type de retour du getter public '{0}' de la classe exportée porte ou utilise le nom privé '{1}'.", + "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_c_4053": "Le type de retour de la méthode publique de la classe exportée possède ou utilise le nom '{0}' du module externe {1}, mais il ne peut pas être nommé.", + "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4054": "Le type de retour de la méthode publique de la classe exportée possède ou utilise le nom '{0}' du module privé '{1}'.", + "Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0_4055": "Le type de retour de la méthode publique de la classe exportée possède ou utilise le nom privé '{0}'.", + "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_external_modul_4038": "Le type de retour du getter public '{0}' de la classe exportée porte ou utilise le nom '{1}' du module externe {2}, mais il ne peut pas être nommé.", + "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_4039": "Le type de retour du getter public '{0}' de la classe exportée porte ou utilise le nom '{1}' du module privé '{2}'.", + "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_private_name_1_4040": "Le type de retour du getter public '{0}' de la classe exportée porte ou utilise le nom privé '{1}'.", + "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module__4050": "Le type de retour de la méthode statique publique de la classe exportée possède ou utilise le nom '{0}' du module externe {1}, mais il ne peut pas être nommé.", + "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4051": "Le type de retour de la méthode statique publique de la classe exportée possède ou utilise le nom '{0}' du module privé '{1}'.", + "Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0_4052": "Le type de retour de la méthode statique publique de la classe exportée possède ou utilise le nom privé '{0}'.", + "Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program_6184": "Réutilisation des résolutions de module provenant de '{0}', car les résolutions sont inchangées par rapport à l'ancien programme.", + "Reusing_resolution_of_module_0_to_file_1_from_old_program_6183": "Réutilisation de la résolution du module '{0}' dans le fichier '{1}' à partir de l'ancien programme.", + "Rewrite_all_as_indexed_access_types_95034": "Réécrire tout comme types d'accès indexés", + "Rewrite_as_the_indexed_access_type_0_90026": "Réécrire en tant que type d'accès indexé '{0}'", + "Root_directory_cannot_be_determined_skipping_primary_search_paths_6122": "Impossible de déterminer le répertoire racine, chemins de recherche primaires ignorés.", + "STRATEGY_6039": "STRATÉGIE", + "Scoped_package_detected_looking_in_0_6182": "Package de portée détecté. Recherche dans '{0}'", + "Setters_cannot_return_a_value_2408": "Les méthodes setter ne peuvent pas retourner de valeur.", + "Show_all_compiler_options_6169": "Affichez toutes les options du compilateur.", + "Show_diagnostic_information_6149": "Affichez les informations de diagnostic.", + "Show_verbose_diagnostic_information_6150": "Affichez les informations de diagnostic détaillées.", + "Show_what_would_be_built_or_deleted_if_specified_with_clean_6367": "Montrer ce qui serait généré (ou supprimé si '--clean' est spécifié)", + "Signature_0_must_be_a_type_predicate_1224": "La signature '{0}' doit être un prédicat de type.", + "Skip_type_checking_of_declaration_files_6012": "Ignorer le contrôle de type des fichiers de déclaration.", + "Skipping_build_of_project_0_because_its_dependency_1_has_errors_6362": "Ignorer la génération du projet '{0}' car sa dépendance '{1}' comporte des erreurs", + "Skipping_clean_because_not_all_projects_could_be_located_6371": "Ignorer le nettoyage car tous les projets ne peuvent pas être localisés", + "Source_Map_Options_6175": "Options de mappage de source", + "Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature_2382": "La signature de surcharge spécialisée n'est assignable à aucune signature non spécialisée.", + "Specifier_of_dynamic_import_cannot_be_spread_element_1325": "Le spécificateur de l'importation dynamique ne peut pas être un élément spread.", + "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_or_ESNEXT_6015": "Spécifiez la version cible d'ECMAScript : 'ES3' (par défaut), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' ou 'ESNEXT'.", + "Specify_JSX_code_generation_Colon_preserve_react_native_or_react_6080": "Spécifiez la génération de code JSX : 'preserve', 'react-native' ou 'react'.", + "Specify_library_files_to_be_included_in_the_compilation_6079": "Spécifiez les fichiers bibliothèques à inclure dans la compilation.", + "Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext_6016": "Spécifiez la génération de code du module : 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015' ou 'ESNext'.", + "Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6_6069": "Spécifiez la stratégie de résolution de module : 'node' (Node.js) ou 'classic' (version de TypeScript antérieure à 1.6).", + "Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h_6146": "Spécifiez la fonction de fabrique JSX à utiliser pour le ciblage d'une émission JSX 'react', par exemple 'React.createElement' ou 'h'.", + "Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix_6060": "Spécifiez la séquence de fin de ligne à utiliser durant l'émission des fichiers : 'CRLF' (Dos) ou 'LF' (Unix).", + "Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations_6004": "Spécifiez l'emplacement dans lequel le débogueur doit localiser les fichiers TypeScript au lieu des emplacements sources.", + "Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations_6003": "Spécifiez l'emplacement dans lequel le débogueur doit localiser les fichiers de mappage au lieu des emplacements générés.", + "Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir_6058": "Spécifiez le répertoire racine des fichiers d'entrée. Contrôlez la structure des répertoires de sortie avec --outDir.", + "Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher_2472": "L'opérateur spread dans les expressions 'new' est disponible uniquement quand ECMAScript 5 ou version supérieure est ciblé.", + "Spread_types_may_only_be_created_from_object_types_2698": "Vous ne pouvez créer des types Spread qu'à partir de types d'objet.", + "Starting_compilation_in_watch_mode_6031": "Démarrage de la compilation en mode espion...", + "Statement_expected_1129": "Instruction attendue.", + "Statements_are_not_allowed_in_ambient_contexts_1036": "Les instructions ne sont pas autorisées dans les contextes ambiants.", + "Static_members_cannot_reference_class_type_parameters_2302": "Les membres statiques ne peuvent pas référencer des paramètres de type de classe.", + "Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1_2699": "La propriété statique '{0}' est en conflit avec la propriété intégrée 'Function.{0}' de la fonction constructeur '{1}'.", + "Strict_Type_Checking_Options_6173": "Options de contrôle de type strict", + "String_literal_expected_1141": "Littéral de chaîne attendu.", + "String_literal_with_double_quotes_expected_1327": "Littéral de chaîne avec guillemets doubles attendu.", + "Stylize_errors_and_messages_using_color_and_context_experimental_6073": "Stylisez les erreurs et les messages avec de la couleur et du contexte (expérimental).", + "Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_t_2717": "Les prochaines déclarations de propriétés doivent avoir le même type. La propriété '{0}' doit avoir le type '{1}', mais elle a ici le type '{2}'.", + "Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_t_2403": "Les déclarations de variable ultérieures doivent avoir le même type. La variable '{0}' doit être de type '{1}', mais elle a ici le type '{2}'.", + "Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2_5064": "Le type de la substitution '{0}' du modèle '{1}' est incorrect. Attente de 'string'. Obtention de '{2}'.", + "Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character_5062": "La substitution '{0}' dans le modèle '{1}' ne peut avoir qu'un seul caractère '*' au maximum.", + "Substitutions_for_pattern_0_should_be_an_array_5063": "Les substitutions du modèle '{0}' doivent correspondre à un tableau.", + "Substitutions_for_pattern_0_shouldn_t_be_an_empty_array_5066": "Les substitutions du modèle '{0}' ne doivent pas correspondre à un tableau vide.", + "Successfully_created_a_tsconfig_json_file_6071": "Un fichier tsconfig.json a été créé.", + "Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors_2337": "Les appels de 'super' ne sont pas autorisés hors des constructeurs ou dans des fonctions imbriquées dans des constructeurs.", + "Suppress_excess_property_checks_for_object_literals_6072": "Supprimez les vérifications des propriétés en trop pour les littéraux d'objet.", + "Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures_6055": "Supprimer les erreurs noImplicitAny pour les objets d'indexation auxquels il manque des signatures d'index.", + "Symbol_reference_does_not_refer_to_the_global_Symbol_constructor_object_2470": "La référence 'Symbol' ne fait pas référence à l'objet constructeur Symbol global.", + "Syntax_Colon_0_6023": "Syntaxe : {0}", + "The_0_operator_cannot_be_applied_to_type_symbol_2469": "Impossible d'appliquer l'opérateur '{0}' au type 'symbol'.", + "The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead_2447": "L'opérateur '{0}' n'est pas autorisé pour les types booléens. Utilisez '{1}' à la place.", + "The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead_2696": "Le type 'Object' peut être assigné à très peu d'autres types. Souhaitez-vous utiliser le type 'any' à la place ?", + "The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_stand_2496": "Impossible de référencer l'objet 'arguments' dans une fonction arrow dans ES3 et ES5. Utilisez plutôt une expression de fonction standard.", + "The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_usi_2522": "Les objets 'arguments' ne peuvent pas être référencés dans une fonction ou méthode async en ES3 et ES5. Utilisez une fonction ou méthode standard.", + "The_body_of_an_if_statement_cannot_be_the_empty_statement_1313": "Le corps d'une instruction 'if' ne peut pas être l'instruction vide.", + "The_character_set_of_the_input_files_6163": "Jeu de caractères des fichiers d'entrée.", + "The_containing_function_or_module_body_is_too_large_for_control_flow_analysis_2563": "Le corps de la fonction ou du module conteneur est trop grand pour l'analyse du flux de contrôle.", + "The_current_host_does_not_support_the_0_option_5001": "L'hôte actuel ne prend pas en charge l'option '{0}'.", + "The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context_2714": "L'expression d'une assignation d'exportation doit être un identificateur ou un nom qualifié dans un contexte ambiant.", + "The_files_list_in_config_file_0_is_empty_18002": "La liste 'files' du fichier config '{0}' est vide.", + "The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback_1060": "Le premier paramètre de la méthode 'then' d'une promesse doit être un rappel.", + "The_global_type_JSX_0_may_not_have_more_than_one_property_2608": "Le type global 'JSX.{0}' ne peut pas avoir plusieurs propriétés.", + "The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_option_1343": "La métapropriété 'import.meta' est uniquement autorisée avec 'ESNext' pour les options de compilateur 'target' et 'module'.", + "The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary_2527": "Le type déduit de '{0}' référence un type '{1}' inaccessible. Une annotation de type est nécessaire.", + "The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern_2491": "La partie gauche d'une instruction 'for...in' ne peut pas être un modèle de déstructuration.", + "The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation_2404": "La partie gauche d'une instruction 'for...in' ne peut pas utiliser d'annotation de type.", + "The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access_2406": "La partie gauche d'une instruction 'for...in' doit être un accès à une variable ou une propriété.", + "The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any_2405": "La partie gauche d'une instruction 'for...in' doit être de type 'string' ou 'any'.", + "The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation_2483": "La partie gauche d'une instruction 'for...of' ne peut pas utiliser d'annotation de type.", + "The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access_2487": "La partie gauche d'une instruction 'for...of' doit être un accès à une variable ou une propriété.", + "The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type_2362": "La partie gauche d'une opération arithmétique doit être de type 'any', 'number' ou un type enum.", + "The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access_2364": "La partie gauche d'une expression d'assignation doit être un accès à une variable ou une propriété.", + "The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol_2360": "La partie gauche d'une expression 'in' doit être de type 'any', 'string', 'number' ou 'symbol'.", + "The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_paramete_2358": "La partie gauche d'une expression 'instanceof' doit être de type 'any', un type d'objet ou un paramètre de type.", + "The_locale_used_when_displaying_messages_to_the_user_e_g_en_us_6156": "Paramètres régionaux utilisés pour afficher les messages à l'utilisateur (exemple : 'fr-fr')", + "The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files_6136": "Profondeur de dépendance maximale pour la recherche sous node_modules et le chargement de fichiers JavaScript.", + "The_operand_of_a_delete_operator_cannot_be_a_read_only_property_2704": "L'opérande d'un opérateur delete ne peut pas être une propriété en lecture seule.", + "The_operand_of_a_delete_operator_must_be_a_property_reference_2703": "L'opérande d'un opérateur delete doit être une référence de propriété.", + "The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access_2357": "L'opérande d'un opérateur d'incrémentation ou de décrémentation doit être un accès à une variable ou une propriété.", + "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601": "Le type de retour d'un constructeur d'éléments JSX doit retourner un type d'objet.", + "The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any_1237": "Le type de retour d'une fonction d'élément décoratif de paramètre doit être 'void' ou 'any'.", + "The_return_type_of_a_property_decorator_function_must_be_either_void_or_any_1236": "Le type de retour d'une fonction d'élément décoratif de propriété doit être 'void' ou 'any'.", + "The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_t_1058": "Le type de retour d'une fonction asynchrone doit être une promesse valide ou ne doit contenir aucun membre 'then' pouvant être appelé.", + "The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_1064": "Le type de retour d'une fonction ou d'une méthode async doit être le type Promise global.", + "The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_but_2407": "La partie droite d'une instruction 'for...in' doit être de type 'any', un type d'objet ou un paramètre de type, mais elle a le type '{0}' ici.", + "The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type_2363": "La partie droite d'une opération arithmétique doit être de type 'any', 'number' ou un type enum.", + "The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter_2361": "La partie droite d'une expression 'in' doit être de type 'any', un type d'objet ou un paramètre de type.", + "The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_F_2359": "La partie droite d'une expression 'instanceof' doit être de type 'any' ou d'un type pouvant être assigné au type d'interface 'Function'.", + "The_specified_path_does_not_exist_Colon_0_5058": "Le chemin spécifié n'existe pas : '{0}'.", + "The_target_of_an_assignment_must_be_a_variable_or_a_property_access_2541": "La cible d'une assignation doit être un accès à une variable ou une propriété.", + "The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access_2701": "La cible de l'assignation du reste d'un objet doit être un accès à une variable ou une propriété.", + "The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1_2684": "Le contexte 'this' de type '{0}' n'est pas assignable au contexte 'this' de type '{1}' de la méthode.", + "The_this_types_of_each_signature_are_incompatible_2685": "Les types 'this' de chaque signature sont incompatibles.", + "The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_typ_2453": "L'argument de type pour le paramètre de type '{0}' ne peut pas être déduit à partir de l'utilisation. Spécifiez plutôt les arguments de type de manière explicite.", + "The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value__2547": "Le type retourné par la méthode 'next()' d'un itérateur asynchrone doit être une promesse pour un type ayant une propriété 'value'.", + "The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property_2490": "Le type retourné par la méthode 'next()' d'un itérateur doit avoir une propriété 'value'.", + "The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer_1189": "La déclaration de variable d'une instruction 'for...in' ne peut pas avoir d'initialiseur.", + "The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer_1190": "La déclaration de variable d'une instruction 'for...of' ne peut pas avoir d'initialiseur.", + "The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any_2410": "L'instruction 'with' n'est pas prise en charge. Tous les symboles d'un bloc 'with' ont le type 'any'.", + "This_constructor_function_may_be_converted_to_a_class_declaration_80002": "Cette fonction constructeur peut être convertie en déclaration de classe.", + "This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found_2354": "Cette syntaxe nécessite une application d'assistance importée, mais le module '{0}' est introuvable.", + "This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1_2343": "Cette syntaxe nécessite une application d'assistance importée nommée '{1}', mais le module '{0}' ne compte aucun membre exporté '{1}'.", + "Trailing_comma_not_allowed_1009": "Virgule de fin non autorisée.", + "Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule_6153": "Transpilez chaque fichier sous forme de module distinct (semblable à 'ts.transpileModule').", + "Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_mod_7035": "Essayez 'npm install @types/{0}' s'il existe, ou ajoutez un nouveau fichier de déclaration (.d.ts) contenant 'declare module '{0}';'", + "Trying_other_entries_in_rootDirs_6110": "Essai avec d'autres entrées dans 'rootDirs'.", + "Trying_substitution_0_candidate_module_location_Colon_1_6093": "Essai avec la substitution '{0}', emplacement de module candidat : '{1}'.", + "Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2_2493": "Le type tuple '{0}' de longueur '{1}' ne peut pas être assigné à un tuple de longueur '{2}'.", + "Type_0_cannot_be_converted_to_type_1_2352": "Impossible de convertir le type '{0}' en type '{1}'.", + "Type_0_cannot_be_used_as_an_index_type_2538": "Impossible d'utiliser le type '{0}' comme type d'index.", + "Type_0_cannot_be_used_to_index_type_1_2536": "Le type '{0}' ne peut pas être utilisé pour indexer le type '{1}'.", + "Type_0_does_not_satisfy_the_constraint_1_2344": "Le type '{0}' ne satisfait pas la contrainte '{1}'.", + "Type_0_has_no_matching_index_signature_for_type_1_2537": "Le type '{0}' n'a aucune signature d'index correspondant au type '{1}'.", + "Type_0_has_no_properties_in_common_with_type_1_2559": "Le type '{0}' n'a aucune propriété en commun avec le type '{1}'.", + "Type_0_has_no_property_1_2460": "Le type '{0}' n'a pas de propriété '{1}'.", + "Type_0_has_no_property_1_and_no_string_index_signature_2459": "Le type '{0}' n'a pas de propriété '{1}' ni de signature d'index de chaîne.", + "Type_0_is_not_a_constructor_function_type_2507": "Le type '{0}' n'est pas un type de fonction constructeur.", + "Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Prom_1055": "Le type '{0}' n'est pas un type de retour de fonction async valide en ES5/ES3, car il ne référence pas une valeur de constructeur compatible avec une promesse.", + "Type_0_is_not_an_array_type_2461": "Le type '{0}' n'est pas un type de tableau.", + "Type_0_is_not_an_array_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators_2568": "Le type '{0}' n’est pas un type de tableau. Utilisez l'option du compilateur '--downlevelIteration' pour autoriser l'itération des itérateurs.", + "Type_0_is_not_an_array_type_or_a_string_type_2495": "Le type '{0}' n'est pas un type de tableau ou un type de chaîne.", + "Type_0_is_not_an_array_type_or_a_string_type_Use_compiler_option_downlevelIteration_to_allow_iterati_2569": "Le type '{0}' n’est pas un type de tableau ou un type string. Utilisez l'option du compilateur '--downlevelIteration' pour autoriser l'itération des itérateurs.", + "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549": "Le type '{0}' n'est pas un type tableau ou un type chaîne, ou n'a pas de méthode '[Symbol.iterator]()' qui retourne un itérateur.", + "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548": "Le type '{0}' n'est pas un type tableau ou n'a pas de méthode '[Symbol.iterator]()' qui retourne un itérateur.", + "Type_0_is_not_assignable_to_type_1_2322": "Impossible d'assigner le type '{0}' au type '{1}'.", + "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_2719": "Impossible d'assigner le type '{0}' au type '{1}'. Il existe deux types distincts portant ce nom, mais ils ne sont pas liés.", + "Type_0_is_not_comparable_to_type_1_2678": "Le type '{0}' n'est pas comparable au type '{1}'.", + "Type_0_is_not_generic_2315": "Le type '{0}' n'est pas générique.", + "Type_0_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator_2504": "Le type '{0}' doit avoir une méthode '[Symbol.asyncIterator]()' qui retourne un itérateur asynchrone.", + "Type_0_must_have_a_Symbol_iterator_method_that_returns_an_iterator_2488": "Le type '{0}' doit avoir une méthode '[Symbol.iterator]()' qui retourne un itérateur.", + "Type_0_provides_no_match_for_the_signature_1_2658": "Le type '{0}' ne fournit aucune correspondance pour la signature '{1}'.", + "Type_0_recursively_references_itself_as_a_base_type_2310": "Le type '{0}' fait référence à lui-même de manière récursive en tant que type de base.", + "Type_alias_0_circularly_references_itself_2456": "L'alias de type '{0}' fait référence à lui-même de manière circulaire.", + "Type_alias_name_cannot_be_0_2457": "Le nom de l'alias de type ne peut pas être '{0}'.", + "Type_annotation_cannot_appear_on_a_constructor_declaration_1093": "Une annotation de type ne peut pas apparaître sur une déclaration de constructeur.", + "Type_argument_candidate_1_is_not_a_valid_type_argument_because_it_is_not_a_supertype_of_candidate_0_2455": "Le candidat de l'argument de type '{1}' n'est pas un argument de type valide, car il ne s'agit pas d'un supertype du candidat '{0}'.", + "Type_argument_expected_1140": "Argument de type attendu.", + "Type_argument_list_cannot_be_empty_1099": "La liste des arguments de type ne peut pas être vide.", + "Type_arguments_cannot_be_used_here_1342": "Impossible d'utiliser des arguments de type ici.", + "Type_declaration_files_to_be_included_in_compilation_6124": "Fichiers de déclaration de type à inclure dans la compilation.", + "Type_expected_1110": "Type attendu.", + "Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method_1062": "Le type est directement ou indirectement référencé dans le rappel d'exécution de sa propre méthode 'then'.", + "Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member_1320": "Le type d'un opérande 'await' doit être une promesse valide ou ne doit contenir aucun membre 'then' pouvant être appelé.", + "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322": "Le type des éléments itérés d'un opérande 'yield*' doit être une promesse valide ou ne doit contenir aucun membre 'then' pouvant être appelé.", + "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321": "Le type d'un opérande 'yield' dans un générateur asynchrone doit être une promesse valide ou ne doit contenir aucun membre 'then' pouvant être appelé.", + "Type_parameter_0_has_a_circular_constraint_2313": "Le paramètre de type '{0}' possède une contrainte circulaire.", + "Type_parameter_0_has_a_circular_default_2716": "Le paramètre de type '{0}' a une valeur par défaut circulaire.", + "Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4008": "Le paramètre de type '{0}' de la signature d'appel de l'interface exportée possède ou utilise le nom privé '{1}'.", + "Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4006": "Le paramètre de type '{0}' de la signature de constructeur de l'interface exportée possède ou utilise le nom privé '{1}'.", + "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002": "Le paramètre de type '{0}' de la classe exportée possède ou utilise le nom privé '{1}'.", + "Type_parameter_0_of_exported_function_has_or_is_using_private_name_1_4016": "Le paramètre de type '{0}' de la fonction exportée possède ou utilise le nom privé '{1}'.", + "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004": "Le paramètre de type '{0}' de l'interface exportée possède ou utilise le nom privé '{1}'.", + "Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1_4083": "Le paramètre de type '{0}' de l'alias du type exporté contient ou utilise le nom privé '{1}'.", + "Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4014": "Le paramètre de type '{0}' de la méthode de l'interface exportée possède ou utilise le nom privé '{1}'.", + "Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4012": "Le paramètre de type '{0}' de la méthode publique de la classe exportée possède ou utilise le nom privé '{1}'.", + "Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4010": "Le paramètre de type '{0}' de la méthode statique publique de la classe exportée possède ou utilise le nom privé '{1}'.", + "Type_parameter_declaration_expected_1139": "Déclaration du paramètre de type attendue.", + "Type_parameter_list_cannot_be_empty_1098": "La liste des paramètres de type ne peut pas être vide.", + "Type_parameter_name_cannot_be_0_2368": "Le nom du paramètre de type ne peut pas être '{0}'.", + "Type_parameters_cannot_appear_on_a_constructor_declaration_1092": "Les paramètres de type ne peuvent pas apparaître sur une déclaration de constructeur.", + "Type_predicate_0_is_not_assignable_to_1_1226": "Impossible d'assigner le prédicat de type '{0}' à '{1}'.", + "Type_reference_directive_0_was_not_resolved_6120": "======== La directive de référence de type '{0}' n'a pas été résolue. ========", + "Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2_6119": "======== La directive de référence de type '{0}' a été correctement résolue en '{1}', primaire : {2}. ========", + "Types_have_separate_declarations_of_a_private_property_0_2442": "Les types ont des déclarations distinctes d'une propriété privée '{0}'.", + "Types_of_parameters_0_and_1_are_incompatible_2328": "Les types des paramètres '{0}' et '{1}' sont incompatibles.", + "Types_of_property_0_are_incompatible_2326": "Les types de la propriété '{0}' sont incompatibles.", + "Unable_to_open_file_0_6050": "Impossible d'ouvrir le fichier '{0}'.", + "Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression_1238": "Impossible de résoudre la signature d'un élément décoratif de classe quand il est appelé en tant qu'expression.", + "Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression_1241": "Impossible de résoudre la signature d'un élément décoratif de méthode quand il est appelé en tant qu'expression.", + "Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression_1239": "Impossible de résoudre la signature d'un élément décoratif de paramètre quand il est appelé en tant qu'expression.", + "Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression_1240": "Impossible de résoudre la signature d'un élément décoratif de propriété quand il est appelé en tant qu'expression.", + "Unexpected_end_of_text_1126": "Fin de texte inattendue.", + "Unexpected_token_1012": "Jeton inattendu.", + "Unexpected_token_A_constructor_method_accessor_or_property_was_expected_1068": "Jeton inattendu. Un constructeur, une méthode, un accesseur ou une propriété est attendu.", + "Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces_1069": "Jeton inattendu. Un nom de paramètre de type est attendu sans accolades.", + "Unexpected_token_expected_1179": "Jeton inattendu. '{' est attendu.", + "Unknown_compiler_option_0_5023": "Option de compilateur '{0}' inconnue.", + "Unknown_option_excludes_Did_you_mean_exclude_6114": "Option 'excludes' inconnue. Voulez-vous utiliser 'exclude' ?", + "Unknown_type_acquisition_option_0_17010": "Option d'acquisition de type inconnue '{0}'.", + "Unreachable_code_detected_7027": "Code inatteignable détecté.", + "Unsupported_locale_0_6049": "Paramètres régionaux non pris en charge : '{0}'.", + "Unterminated_Unicode_escape_sequence_1199": "Séquence d'échappement Unicode inachevée.", + "Unterminated_quoted_string_in_response_file_0_6045": "Chaîne entre guillemets inachevée dans le fichier réponse '{0}'.", + "Unterminated_regular_expression_literal_1161": "Littéral d'expression régulière inachevé.", + "Unterminated_string_literal_1002": "Littéral de chaîne inachevé.", + "Unterminated_template_literal_1160": "Littéral de modèle inachevé.", + "Untyped_function_calls_may_not_accept_type_arguments_2347": "Les appels de fonctions non typées ne peuvent pas accepter d'arguments de type.", + "Unused_label_7028": "Étiquette inutilisée.", + "Updating_output_timestamps_of_project_0_6359": "Mise à jour des horodatages de sortie du projet '{0}'...", + "Use_synthetic_default_member_95016": "Utilisez un membre 'default' synthétique.", + "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494": "L'utilisation d'une chaîne dans une instruction 'for...of' est prise en charge uniquement dans ECMAScript 5 et version supérieure.", + "VERSION_6036": "VERSION", + "Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it_2560": "La valeur de type '{0}' n'a aucune propriété en commun avec le type '{1}'. Voulez-vous vraiment l'appeler ?", + "Value_of_type_0_is_not_callable_Did_you_mean_to_include_new_2348": "La valeur de type '{0}' ne peut pas être appelée. Voulez-vous inclure 'new' ?", + "Variable_0_implicitly_has_an_1_type_7005": "La variable '{0}' possède implicitement un type '{1}'.", + "Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined_7034": "La variable '{0}' a implicitement le type '{1}' dans certains emplacements où son type ne peut pas être déterminé.", + "Variable_0_is_used_before_being_assigned_2454": "La variable '{0}' est utilisée avant d'être assignée.", + "Variable_declaration_expected_1134": "Déclaration de variable attendue.", + "Variable_declaration_list_cannot_be_empty_1123": "La liste des déclarations de variable ne peut pas être vide.", + "Version_0_6029": "Version {0}", + "Watch_input_files_6005": "Fichiers d'entrée d'espion.", + "Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen_6191": "Garder la sortie de console obsolète en mode espion au lieu d'effacer l'écran.", + "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001": "Vous ne pouvez pas renommer des éléments définis dans la bibliothèque TypeScript standard.", + "You_cannot_rename_this_element_8000": "Vous ne pouvez pas renommer cet élément.", + "_0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write__1329": "'{0}' accepte trop peu d'arguments pour pouvoir être utilisé ici en tant qu'élément décoratif. Voulez-vous vraiment l'appeler d'abord et écrire '@{0}()' ?", + "_0_are_specified_twice_The_attribute_named_0_will_be_overwritten_2710": "'{0}' spécifié deux fois. L'attribut nommé '{0}' va être remplacé.", + "_0_can_only_be_used_in_a_ts_file_8009": "'{0}' peut uniquement être utilisé dans un fichier .ts.", + "_0_expected_1005": "'{0}' attendu.", + "_0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_reference_7023": "'{0}' possède implicitement le type de retour 'any', car il n'a pas d'annotation de type de retour, et est référencé directement ou indirectement dans l'une de ses expressions de retour.", + "_0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or__7022": "'{0}' a implicitement le type 'any', car il n'a pas d'annotation de type et est référencé directement ou indirectement dans son propre initialiseur.", + "_0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible_2692": "'{0}' est une primitive, mais '{1}' est un objet wrapper. Si possible, utilisez '{0}' de préférence.", + "_0_is_declared_but_its_value_is_never_read_6133": "'{0}' est déclaré mais sa valeur n'est jamais lue.", + "_0_is_declared_but_never_used_6196": "'{0}' est déclaré mais n'est jamais utilisé.", + "_0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2_17012": "'{0}' n'est pas une métapropriété valide pour le mot clé '{1}'. Est-ce qu'il ne s'agit pas plutôt de '{2}' ?", + "_0_is_referenced_directly_or_indirectly_in_its_own_base_expression_2506": "'{0}' est référencé directement ou indirectement dans sa propre expression de base.", + "_0_is_referenced_directly_or_indirectly_in_its_own_type_annotation_2502": "'{0}' est référencé directement ou indirectement dans sa propre annotation de type.", + "_0_list_cannot_be_empty_1097": "La liste '{0}' ne peut pas être vide.", + "_0_modifier_already_seen_1030": "Modificateur '{0}' déjà rencontré.", + "_0_modifier_cannot_appear_on_a_class_element_1031": "Le modificateur '{0}' ne peut pas apparaître dans un élément de classe.", + "_0_modifier_cannot_appear_on_a_constructor_declaration_1089": "Le modificateur '{0}' ne peut pas apparaître sur une déclaration de constructeur.", + "_0_modifier_cannot_appear_on_a_data_property_1043": "Le modificateur '{0}' ne peut pas apparaître dans une propriété de données.", + "_0_modifier_cannot_appear_on_a_module_or_namespace_element_1044": "Le modificateur '{0}' ne peut pas apparaître dans un élément de module ou d'espace de noms.", + "_0_modifier_cannot_appear_on_a_parameter_1090": "Le modificateur '{0}' ne peut pas apparaître dans un paramètre.", + "_0_modifier_cannot_appear_on_a_type_member_1070": "Le modificateur '{0}' ne peut pas apparaître dans un membre de type.", + "_0_modifier_cannot_appear_on_an_index_signature_1071": "Le modificateur '{0}' ne peut pas apparaître dans une signature d'index.", + "_0_modifier_cannot_be_used_here_1042": "Impossible d'utiliser le modificateur '{0}' ici.", + "_0_modifier_cannot_be_used_in_an_ambient_context_1040": "Impossible d'utiliser le modificateur '{0}' dans un contexte ambiant.", + "_0_modifier_cannot_be_used_with_1_modifier_1243": "Impossible d'utiliser les modificateurs '{0}' et '{1}' ensemble.", + "_0_modifier_cannot_be_used_with_a_class_declaration_1041": "Impossible d'utiliser le modificateur '{0}' avec une déclaration de classe.", + "_0_modifier_must_precede_1_modifier_1029": "Le modificateur '{0}' doit précéder le modificateur '{1}'.", + "_0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here_2702": "'{0}' référence uniquement un type mais s'utilise en tant qu'espace de noms ici.", + "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_2693": "'{0}' fait uniquement référence à un type mais s'utilise en tant que valeur ici.", + "_0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead_2686": "'{0}' fait référence à une variable globale UMD, mais le fichier actuel est un module. Ajoutez une importation à la place.", + "_0_tag_already_specified_1223": "La balise '{0}' est déjà spécifiée.", + "_0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag_1253": "Impossible d'utiliser la balise '{0}' de manière indépendante en tant que balise JSDoc de niveau supérieur.", + "_0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type_7010": "'{0}', qui ne dispose pas d'annotation de type de retour, possède implicitement un type de retour '{1}'.", + "abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration_1242": "Le modificateur 'abstract' peut apparaître uniquement dans une déclaration de classe, de méthode ou de propriété.", + "await_expression_is_only_allowed_within_an_async_function_1308": "L'expression 'await' est autorisée uniquement dans une fonction async.", + "await_expressions_cannot_be_used_in_a_parameter_initializer_2524": "Impossible d'utiliser des expressions 'await' dans un initialiseur de paramètre.", + "baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1_6106": "L'option 'baseUrl' a la valeur '{0}'. Utilisation de cette valeur pour la résolution du nom de module non relatif '{1}'.", + "can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment_1312": "'=' ne peut être utilisé que dans une propriété de littéral d'objet au sein d'une affectation par déstructuration.", + "case_or_default_expected_1130": "'case' ou 'default' attendu.", + "class_expressions_are_not_currently_supported_9003": "Les expressions 'class' ne sont actuellement pas prises en charge.", + "const_declarations_can_only_be_declared_inside_a_block_1156": "Les déclarations 'const' ne peuvent être déclarées que dans un bloc.", + "const_declarations_must_be_initialized_1155": "Les déclarations 'const' doivent être initialisées.", + "const_enum_member_initializer_was_evaluated_to_a_non_finite_value_2477": "L'initialiseur de membre enum 'const' donne une valeur non finie.", + "const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN_2478": "L'initialiseur de membre enum 'const' donne une valeur non autorisée 'NaN'.", + "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475": "Les enums 'const' ne peuvent être utilisés que dans les expressions d'accès à une propriété ou un index, ou dans la partie droite d'une déclaration d'importation, d'une assignation d'exportation ou d'une requête de type.", + "delete_cannot_be_called_on_an_identifier_in_strict_mode_1102": "'delete' ne peut pas être appelé dans un identificateur en mode strict.", + "delete_this_Project_0_is_up_to_date_because_it_was_previously_built_6360": "supprimer ceci - Le projet '{0}' est à jour car il a déjà été généré", + "enum_declarations_can_only_be_used_in_a_ts_file_8015": "'Les déclarations enum' peuvent uniquement être utilisées dans un fichier .ts.", + "export_can_only_be_used_in_a_ts_file_8003": "'export=' peut uniquement être utilisé dans un fichier .ts.", + "export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always__2668": "Impossible d'appliquer le modificateur 'export' aux modules ambients et aux augmentations de module, car ils sont toujours visibles.", + "extends_clause_already_seen_1172": "Clause 'extends' déjà rencontrée.", + "extends_clause_must_precede_implements_clause_1173": "La clause 'extends' doit précéder la clause 'implements'.", + "extends_clause_of_exported_class_0_has_or_is_using_private_name_1_4020": "La clause 'extends' de la classe exportée '{0}' comporte ou utilise le nom privé '{1}'.", + "extends_clause_of_exported_interface_0_has_or_is_using_private_name_1_4022": "La clause 'extends' de l'interface exportée '{0}' comporte ou utilise le nom privé '{1}'.", + "file_6025": "fichier", + "get_and_set_accessor_must_have_the_same_this_type_2682": "Les accesseurs 'get' et 'set' doivent avoir le même type 'this'.", + "get_and_set_accessor_must_have_the_same_type_2380": "Les accesseurs 'get' et 'set' doivent avoir le même type.", + "implements_clause_already_seen_1175": "Clause 'implements' déjà rencontrée.", + "implements_clauses_can_only_be_used_in_a_ts_file_8005": "Les clauses 'implements' peuvent uniquement être utilisées dans un fichier .ts.", + "import_can_only_be_used_in_a_ts_file_8002": "'import ... =' peut uniquement être utilisé dans un fichier .ts.", + "infer_declarations_are_only_permitted_in_the_extends_clause_of_a_conditional_type_1338": "Les déclarations 'infer' sont uniquement autorisées dans la clause 'extends' d’un type conditionnel.", + "interface_declarations_can_only_be_used_in_a_ts_file_8006": "Les 'déclarations d'interface' peuvent uniquement être utilisées dans un fichier .ts.", + "let_declarations_can_only_be_declared_inside_a_block_1157": "Les déclarations 'let' ne peuvent être déclarées que dans un bloc.", + "let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations_2480": "'let' ne peut pas être utilisé comme nom dans les déclarations 'let' ou 'const'.", + "module_declarations_can_only_be_used_in_a_ts_file_8007": "Les 'déclarations de module' peuvent uniquement être utilisées dans un fichier .ts.", + "new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead_1150": "Impossible d'utiliser 'new T[]' pour créer un tableau. Utilisez 'new Array()' à la place.", + "new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type_7009": "L'expression 'new', dont la cible ne dispose pas d'une signature de construction, possède implicitement un type 'any'.", + "non_null_assertions_can_only_be_used_in_a_ts_file_8013": "Les 'assertions non null' peuvent uniquement être utilisées dans un fichier .ts.", + "options_6024": "options", + "or_expected_1144": "'{' ou ';' attendu.", + "package_json_does_not_have_a_0_field_6100": "'package.json' n'a aucun champ '{0}'.", + "package_json_has_0_field_1_that_references_2_6101": "'package.json' a un champ '{0}' '{1}' qui fait référence à '{2}'.", + "parameter_modifiers_can_only_be_used_in_a_ts_file_8012": "Les 'modificateurs de paramètre' peuvent uniquement être utilisés dans un fichier .ts.", + "paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0_6091": "L'option 'paths' est spécifiée. Recherche d'un modèle correspondant au nom de module '{0}'.", + "readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024": "Le modificateur 'readonly' peut apparaître uniquement dans une déclaration de propriété ou une signature d'index.", + "require_call_may_be_converted_to_an_import_80005": "L'appel de 'require' peut être converti en import.", + "rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107": "L'option 'rootDirs' est définie. Utilisation de celle-ci pour la résolution du nom de module relatif '{0}'.", + "super_can_only_be_referenced_in_a_derived_class_2335": "'super' ne peut être référencé que dans une classe dérivée.", + "super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions_2660": "'super' ne peut être référencé que dans les membres des classes dérivées ou les expressions littérales d'objet.", + "super_cannot_be_referenced_in_a_computed_property_name_2466": "Impossible de référencer 'super' dans un nom de propriété calculée.", + "super_cannot_be_referenced_in_constructor_arguments_2336": "Impossible de référencer 'super' dans des arguments de constructeur.", + "super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_highe_2659": "'super' est uniquement autorisé dans les membres des expressions littérales d'objet quand l'option 'target' a la valeur 'ES2015' ou une valeur supérieure.", + "super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class_17011": "'super' doit être appelé avant d'accéder à une propriété de 'super' dans le constructeur d'une classe dérivée.", + "super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class_17009": "'super' doit être appelé avant d'accéder à 'this' dans le constructeur d'une classe dérivée.", + "super_must_be_followed_by_an_argument_list_or_member_access_1034": "'super' doit être suivi d'une liste d'arguments ou d'un accès au membre.", + "super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_der_2338": "L'accès aux propriétés 'super' est autorisé uniquement dans un constructeur, une fonction membre ou un accesseur membre d'une classe dérivée.", + "this_cannot_be_referenced_in_a_computed_property_name_2465": "Impossible de référencer 'this' dans un nom de propriété calculée.", + "this_cannot_be_referenced_in_a_module_or_namespace_body_2331": "Impossible de référencer 'this' dans le corps d'un module ou d'un espace de noms.", + "this_cannot_be_referenced_in_a_static_property_initializer_2334": "Impossible de référencer 'this' dans un initialiseur de propriété statique.", + "this_cannot_be_referenced_in_constructor_arguments_2333": "Impossible de référencer 'this' dans des arguments de constructeur.", + "this_cannot_be_referenced_in_current_location_2332": "Impossible de référencer 'this' dans l'emplacement actuel.", + "this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_2683": "'this' possède implicitement le type 'any', car il n'a pas d'annotation de type.", + "type_aliases_can_only_be_used_in_a_ts_file_8008": "Les 'alias de type' peuvent uniquement être utilisés dans un fichier .ts.", + "type_arguments_can_only_be_used_in_a_ts_file_8011": "Les 'arguments de type' peuvent uniquement être utilisés dans un fichier .ts.", + "type_assertion_expressions_can_only_be_used_in_a_ts_file_8016": "Les 'expressions d'assertion de type' peuvent uniquement être utilisées dans un fichier .ts.", + "type_parameter_declarations_can_only_be_used_in_a_ts_file_8004": "Les 'déclarations de paramètre de type' peuvent uniquement être utilisées dans un fichier .ts.", + "types_can_only_be_used_in_a_ts_file_8010": "Les 'types' peuvent uniquement être utilisés dans un fichier .ts.", + "unique_symbol_types_are_not_allowed_here_1335": "Les types 'unique symbol' ne sont pas autorisés ici.", + "unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement_1334": "Les types 'unique symbol' sont uniquement autorisés sur les variables d'une déclaration de variable.", + "unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name_1333": "Les types 'unique symbol' ne peuvent pas être utilisés dans une déclaration de variable avec un nom de liaison.", + "with_statements_are_not_allowed_in_an_async_function_block_1300": "Les instructions 'with' ne sont pas autorisées dans un bloc de fonctions async.", + "with_statements_are_not_allowed_in_strict_mode_1101": "Les instructions 'with' ne sont pas autorisées en mode strict.", + "yield_expressions_cannot_be_used_in_a_parameter_initializer_2523": "Impossible d'utiliser des expressions 'yield' dans un initialiseur de paramètre." +} \ No newline at end of file diff --git a/node_modules/typescript/lib/it/diagnosticMessages.generated.json b/node_modules/typescript/lib/it/diagnosticMessages.generated.json new file mode 100644 index 0000000..9f8ef7d --- /dev/null +++ b/node_modules/typescript/lib/it/diagnosticMessages.generated.json @@ -0,0 +1,1101 @@ +{ + "A_0_modifier_cannot_be_used_with_an_import_declaration_1079": "Non è possibile usare un modificatore '{0}' con una dichiarazione di importazione.", + "A_0_modifier_cannot_be_used_with_an_interface_declaration_1045": "Non è possibile usare un modificatore '{0}' con una dichiarazione di interfaccia.", + "A_0_parameter_must_be_the_first_parameter_2680": "Il primo parametro deve essere '{0}'.", + "A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature_2463": "Un parametro del criterio di binding non può essere facoltativo in una firma di implementazione.", + "A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement_1105": "Un'istruzione 'break' può essere usata solo all'interno di un'iterazione di inclusione o di un'istruzione switch.", + "A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement_1116": "Un'istruzione 'break' può solo passare a un'etichetta di un'istruzione di inclusione.", + "A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments_2500": "Una classe può implementare solo un identificatore/nome qualificato con argomenti tipo facoltativi.", + "A_class_declaration_without_the_default_modifier_must_have_a_name_1211": "È necessario assegnare un nome a una dichiarazione di classe senza modificatore 'default'.", + "A_class_may_only_extend_another_class_2311": "Una classe può estendere solo un'altra classe.", + "A_class_may_only_implement_another_class_or_interface_2422": "Una classe può implementare solo un'altra classe o interfaccia.", + "A_class_member_cannot_have_the_0_keyword_1248": "Un membro di classe non può contenere la parola chiave '{0}'.", + "A_comma_expression_is_not_allowed_in_a_computed_property_name_1171": "Non sono consentite espressioni con virgole in un nome di proprietà calcolato.", + "A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type_2467": "Un nome di proprietà calcolato non può fare riferimento a un parametro di tipo dal tipo che lo contiene.", + "A_computed_property_name_in_a_class_property_declaration_must_refer_to_an_expression_whose_type_is_a_1166": "Un nome di proprietà calcolato in una dichiarazione di proprietà di classe deve fare riferimento a un'espressione il cui tipo è un tipo di valore letterale o un tipo 'unique symbol'.", + "A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_ty_1168": "Un nome di proprietà calcolato in un overload di metodo deve fare riferimento a un'espressione il cui tipo è un tipo di valore letterale o un tipo 'unique symbol'.", + "A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type__1170": "Un nome di proprietà calcolato in un valore letterale di tipo deve fare riferimento a un'espressione il cui tipo è un tipo di valore letterale o un tipo 'unique symbol'.", + "A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_t_1165": "Un nome di proprietà calcolato in un contesto di ambiente deve fare riferimento a un'espressione il cui tipo è un tipo di valore letterale o un tipo 'unique symbol'.", + "A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_1169": "Un nome di proprietà calcolato in un'interfaccia deve fare riferimento a un'espressione il cui tipo è un tipo di valore letterale o un tipo 'unique symbol'.", + "A_computed_property_name_must_be_of_type_string_number_symbol_or_any_2464": "Un nome di proprietà calcolato deve essere di tipo 'string', 'number', 'symbol' o 'any'.", + "A_computed_property_name_of_the_form_0_must_be_of_type_symbol_2471": "Un nome di proprietà calcolato in formato '{0}' deve essere di tipo 'symbol'.", + "A_const_enum_member_can_only_be_accessed_using_a_string_literal_2476": "È possibile accedere a un membro di enumerazione const solo tramite un valore letterale stringa.", + "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_1254": "Un inizializzatore 'const' in un contesto di ambiente deve essere un valore letterale numerico o stringa.", + "A_constructor_cannot_contain_a_super_call_when_its_class_extends_null_17005": "Un costruttore non può contenere una chiamata 'super' quando la relativa classe estende 'null'.", + "A_constructor_cannot_have_a_this_parameter_2681": "Un costruttore non può contenere un parametro 'this'.", + "A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement_1104": "Un'istruzione 'continue' può essere usata solo all'interno di un'istruzione di iterazione di inclusione.", + "A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement_1115": "Un'istruzione 'continue' può solo passare a un'etichetta di un'istruzione di iterazione di inclusione.", + "A_declare_modifier_cannot_be_used_in_an_already_ambient_context_1038": "Non è possibile usare un modificatore 'declare' in un contesto già di ambiente.", + "A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file_1046": "Un modificatore 'declare' è obbligatorio per una dichiarazione di primo livello in un file con estensione d.ts.", + "A_decorator_can_only_decorate_a_method_implementation_not_an_overload_1249": "Un elemento Decorator può solo decorare un'implementazione del metodo e non un overload.", + "A_default_clause_cannot_appear_more_than_once_in_a_switch_statement_1113": "Una clausola 'default' non può essere specificata più volte in un'istruzione 'switch'.", + "A_default_export_can_only_be_used_in_an_ECMAScript_style_module_1319": "È possibile usare un'esportazione predefinita solo in un modulo di tipo ECMAScript.", + "A_definite_assignment_assertion_is_not_permitted_in_this_context_1255": "In questo contesto non sono consentite asserzioni di assegnazione definite '!'.", + "A_destructuring_declaration_must_have_an_initializer_1182": "Una dichiarazione di destrutturazione deve includere un inizializzatore.", + "A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declarat_2712": "Con una chiamata di importazione dinamica in ES5/ES3 è necessario il costruttore 'Promise'. Assicurarsi che sia presente una dichiarazione per il costruttore 'Promise' oppure includere 'ES2015' nell'opzione `--lib`.", + "A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES20_2711": "Una chiamata di importazione dinamica restituisce un elemento 'Promise'. Assicurarsi che sia presente una dichiarazione per 'Promise' oppure includere 'ES2015' nell'opzione `--lib`.", + "A_file_cannot_have_a_reference_to_itself_1006": "Un file non può contenere un riferimento a se stesso.", + "A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator_1103": "Un'istruzione 'for-await-of' è consentita solo in una funzione asincrona o un generatore asincrono.", + "A_function_returning_never_cannot_have_a_reachable_end_point_2534": "Una funzione che restituisce 'never' non può includere un punto finale raggiungibile.", + "A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void_2679": "Una funzione chiamata con la parola chiave 'new' non può contenere un tipo 'this' con valore 'void'.", + "A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value_2355": "Una funzione il cui tipo dichiarato non è 'void' né 'any' deve restituire un valore.", + "A_generator_cannot_have_a_void_type_annotation_2505": "Un generatore non può contenere un'annotazione di tipo 'void'.", + "A_get_accessor_cannot_have_parameters_1054": "Una funzione di accesso 'get' non può contenere parametri.", + "A_get_accessor_must_return_a_value_2378": "Una funzione di accesso 'get' deve restituire un valore.", + "A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_memb_2651": "Un inizializzatore di membro in una dichiarazione di enumerazione non può fare riferimento a membri dichiarati successivamente, inclusi quelli definiti in altre enumerazioni.", + "A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any_2545": "Una classe mixin deve includere un costruttore con un unico parametro REST di tipo 'any[]'.", + "A_module_cannot_have_multiple_default_exports_2528": "Un modulo non può includere più esportazioni predefinite.", + "A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merg_2433": "Una dichiarazione di spazio dei nomi non può essere presente in un file diverso rispetto a una classe o funzione con cui è stato eseguito il merge.", + "A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged_2434": "Una dichiarazione di spazio dei nomi non può essere specificata prima di una classe o funzione con cui è stato eseguito il merge.", + "A_namespace_declaration_is_only_allowed_in_a_namespace_or_module_1235": "Una dichiarazione di spazio dei nomi è consentita solo in uno spazio dei nomi o in un modulo.", + "A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_7038": "Non è possibile chiamare o costruire un'importazione in stile spazio dei nomi. Questo comporterà un errore in fase di runtime.", + "A_non_dry_build_would_build_project_0_6357": "Se si esegue una compilazione senza flag -dry, verrà compilato il progetto '{0}'", + "A_non_dry_build_would_delete_the_following_files_Colon_0_6356": "Se si esegue una compilazione senza flag -dry, i file seguenti verranno eliminati: {0}", + "A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation_2371": "Un inizializzatore di parametro è consentito solo in un'implementazione di funzione o costruttore.", + "A_parameter_property_cannot_be_declared_using_a_rest_parameter_1317": "Non è possibile dichiarare una proprietà di parametro usando un parametro REST.", + "A_parameter_property_is_only_allowed_in_a_constructor_implementation_2369": "Una proprietà di parametro è consentita solo in un'implementazione di costruttore.", + "A_parameter_property_may_not_be_declared_using_a_binding_pattern_1187": "Non è possibile dichiarare una proprietà di parametro con un modello di associazione.", + "A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not_18001": "Un percorso in un'opzione 'extends' deve essere relativo o completo, ma '{0}' non lo è.", + "A_promise_must_have_a_then_method_1059": "Una promessa deve contenere un metodo 'then'.", + "A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly_1331": "Una proprietà di una classe il cui tipo è un tipo 'unique symbol' deve essere sia 'static' che 'readonly'.", + "A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly_1330": "Una proprietà di un'interfaccia o di un valore letterale di tipo il cui tipo è un tipo 'unique symbol' deve essere 'readonly'.", + "A_required_parameter_cannot_follow_an_optional_parameter_1016": "Un parametro obbligatorio non può seguire un parametro facoltativo.", + "A_rest_element_cannot_contain_a_binding_pattern_2501": "Un elemento rest non può contenere un criterio di binding.", + "A_rest_element_cannot_have_a_property_name_2566": "Un elemento rest non può contenere un nome proprietà.", + "A_rest_element_cannot_have_an_initializer_1186": "Un elemento rest non può includere un inizializzatore.", + "A_rest_element_must_be_last_in_a_destructuring_pattern_2462": "Un elemento rest deve essere l'ultimo di un criterio di destrutturazione.", + "A_rest_parameter_cannot_be_optional_1047": "Un parametro rest non può essere facoltativo.", + "A_rest_parameter_cannot_have_an_initializer_1048": "Un parametro rest non può contenere un inizializzatore.", + "A_rest_parameter_must_be_last_in_a_parameter_list_1014": "Un parametro rest deve essere l'ultimo di un elenco di parametri.", + "A_rest_parameter_must_be_of_an_array_type_2370": "Un parametro rest deve essere di un tipo di matrice.", + "A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma_1013": "Un modello di associazione o un parametro REST non può contenere una virgola finale.", + "A_return_statement_can_only_be_used_within_a_function_body_1108": "Un'istruzione 'return' può essere usata solo all'interno di un corpo di funzione.", + "A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl_6167": "Serie di voci che ripetono il mapping delle importazioni a percorsi di ricerca relativi al valore di 'baseUrl'.", + "A_set_accessor_cannot_have_a_return_type_annotation_1095": "Una funzione di accesso 'set' non può contenere un'annotazione di tipo restituito.", + "A_set_accessor_cannot_have_an_optional_parameter_1051": "Una funzione di accesso 'set' non può contenere un parametro facoltativo.", + "A_set_accessor_cannot_have_rest_parameter_1053": "Una funzione di accesso 'set' non può contenere il parametro rest.", + "A_set_accessor_must_have_exactly_one_parameter_1049": "Una funzione di accesso 'set' deve contenere un solo parametro.", + "A_set_accessor_parameter_cannot_have_an_initializer_1052": "Un parametro della funzione di accesso 'set' non può contenere un inizializzatore.", + "A_signature_with_an_implementation_cannot_use_a_string_literal_type_2381": "Una firma con un'implementazione non può usare un tipo di valore letterale stringa.", + "A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_proper_2376": "Una chiamata 'super' deve essere la prima istruzione del costruttore quando una classe contiene proprietà inizializzate o proprietà di parametri.", + "A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard_2518": "Un guard di tipo basato su 'this' non è compatibile con uno basato su parametri.", + "A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface_2526": "Un tipo 'this' è disponibile solo in un membro non statico di una classe o di interfaccia.", + "A_tsconfig_json_file_is_already_defined_at_Colon_0_5054": "Un file 'tsconfig.json' è già definito in: '{0}'.", + "A_tuple_type_element_list_cannot_be_empty_1122": "L'elenco degli elementi di tipo tupla non può essere vuoto.", + "A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Con_17007": "Nella parte sinistra di un'espressione di elevamento a potenza non è consentita un'espressione di asserzione tipi. Provare a racchiudere l'espressione tra parentesi.", + "A_type_literal_property_cannot_have_an_initializer_1247": "Una proprietà di valore letterale di tipo non può contenere un inizializzatore.", + "A_type_predicate_cannot_reference_a_rest_parameter_1229": "Un predicato di tipo non può fare riferimento a un parametro rest.", + "A_type_predicate_cannot_reference_element_0_in_a_binding_pattern_1230": "Un predicato di tipo non può fare riferimento all'elemento '{0}' in un criterio di binding.", + "A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods_1228": "Un predicato di tipo è consentito solo nella posizione del tipo restituito per le funzioni e i metodi.", + "A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type_2677": "Il tipo di un predicato di tipo deve essere assegnabile al tipo del relativo parametro.", + "A_variable_whose_type_is_a_unique_symbol_type_must_be_const_1332": "Una variabile il cui tipo è un tipo 'unique symbol' deve essere 'const'.", + "A_yield_expression_is_only_allowed_in_a_generator_body_1163": "Un'espressione 'yield' è consentita solo nel corpo di un generatore.", + "Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression_2513": "Non è possibile accedere al metodo astratto '{0}' nella classe '{1}' tramite l'espressione super.", + "Abstract_methods_can_only_appear_within_an_abstract_class_1244": "I metodi astratti possono essere inclusi solo in una classe astratta.", + "Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor_2715": "Non è possibile accedere alla proprietà astratta '{0}' nella classe '{1}' nel costruttore.", + "Accessibility_modifier_already_seen_1028": "Il modificatore di accessibilità è già presente.", + "Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher_1056": "Le funzioni di accesso sono disponibili solo se destinate a ECMAScript 5 e versioni successive.", + "Accessors_must_both_be_abstract_or_non_abstract_2676": "Le funzioni di accesso devono essere tutte astratte o tutte non astratte.", + "Add_0_to_existing_import_declaration_from_1_90015": "Aggiungere '{0}' alla dichiarazione di importazione esistente da \"{1}\"", + "Add_0_to_unresolved_variable_90008": "Aggiungere '{0}.' alla variabile non risolta", + "Add_all_missing_async_modifiers_95041": "Aggiungere tutti i modificatori 'async' mancanti", + "Add_all_missing_members_95022": "Aggiungere tutti i membri mancanti", + "Add_all_missing_super_calls_95039": "Aggiungere tutte le chiamate a super mancanti", + "Add_async_modifier_to_containing_function_90029": "Aggiungere il modificatore async alla funzione contenitore", + "Add_braces_to_arrow_function_95059": "Aggiungere le parentesi graffe alla funzione arrow", + "Add_definite_assignment_assertion_to_property_0_95020": "Aggiungere l'asserzione di assegnazione definita alla proprietà '{0}'", + "Add_definite_assignment_assertions_to_all_uninitialized_properties_95028": "Aggiungere le asserzioni di assegnazione definite a tutte le proprietà non inizializzate", + "Add_index_signature_for_property_0_90017": "Aggiungere la firma dell'indice per la proprietà '{0}'", + "Add_initializer_to_property_0_95019": "Aggiungere l'inizializzatore alla proprietà '{0}'", + "Add_initializers_to_all_uninitialized_properties_95027": "Aggiungere gli inizializzatori a tutte le proprietà non inizializzate", + "Add_missing_super_call_90001": "Aggiungere la chiamata mancante a 'super()'", + "Add_missing_typeof_95052": "Aggiungere l'elemento 'typeof' mancante", + "Add_or_remove_braces_in_an_arrow_function_95058": "Aggiungere o rimuovere le parentesi graffe in una funzione arrow", + "Add_qualifier_to_all_unresolved_variables_matching_a_member_name_95037": "Aggiungere il qualificatore a tutte le variabili non risolte corrispondenti a un nome di membro", + "Add_to_all_uncalled_decorators_95044": "Aggiungere '()' a tutti gli elementi Decorator non chiamati", + "Add_ts_ignore_to_all_error_messages_95042": "Aggiungere '@ts-ignore' a tutti i messaggi di errore", + "Add_undefined_type_to_all_uninitialized_properties_95029": "Aggiungere il tipo non definito a tutte le proprietà non inizializzate", + "Add_undefined_type_to_property_0_95018": "Aggiungere il tipo 'undefined' alla proprietà '{0}'", + "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068": "Aggiungere un file tsconfig.json per organizzare più facilmente progetti che contengono sia file TypeScript che JavaScript. Per altre informazioni, vedere https://aka.ms/tsconfig.", + "Additional_Checks_6176": "Controlli aggiuntivi", + "Advanced_Options_6178": "Opzioni avanzate", + "All_declarations_of_0_must_have_identical_modifiers_2687": "Tutte le dichiarazioni di '{0}' devono contenere modificatori identici.", + "All_declarations_of_0_must_have_identical_type_parameters_2428": "Tutte le dichiarazioni di '{0}' devono contenere parametri di tipo identici.", + "All_declarations_of_an_abstract_method_must_be_consecutive_2516": "Tutte le dichiarazioni di un metodo astratto devono essere consecutive.", + "All_destructured_elements_are_unused_6198": "Tutti gli elementi destrutturati sono inutilizzati.", + "All_imports_in_import_declaration_are_unused_6192": "Tutte le importazioni nella dichiarazione di importazione sono inutilizzate.", + "All_variables_are_unused_6199": "Tutte le variabili sono inutilizzate.", + "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011": "Consente di eseguire importazioni predefinite da moduli senza esportazione predefinita. Non influisce sulla creazione del codice ma solo sul controllo dei tipi.", + "Allow_javascript_files_to_be_compiled_6102": "Consente la compilazione di file JavaScript.", + "Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided_1209": "Le enumerazioni const di ambiente non sono consentite quando viene specificato il flag '--isolatedModules'.", + "Ambient_module_declaration_cannot_specify_relative_module_name_2436": "Non è possibile specificare il nome di modulo relativo nella dichiarazione di modulo di ambiente.", + "Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces_2435": "I moduli di ambiente non possono essere annidati in altri moduli o spazi dei nomi.", + "An_AMD_module_cannot_have_multiple_name_assignments_2458": "Un modulo AMD non può includere più assegnazioni di nome.", + "An_abstract_accessor_cannot_have_an_implementation_1318": "Una funzione di accesso astratta non può contenere un'implementazione.", + "An_accessor_cannot_be_declared_in_an_ambient_context_1086": "Non è possibile dichiarare una funzione di accesso in un contesto di ambiente.", + "An_accessor_cannot_have_type_parameters_1094": "Una funzione di accesso non può contenere parametri di tipo.", + "An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file_1234": "Una dichiarazione di modulo di ambiente è consentita solo al primo livello in un file.", + "An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type_2356": "Un operando aritmetico deve essere di tipo 'any', 'number' o un tipo di enumerazione.", + "An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_de_2705": "Con una funzione o un metodo asincrono in ES5/ES3 è necessario il costruttore 'Promise'. Assicurarsi che sia presente una dichiarazione per il costruttore 'Promise' oppure includere 'ES2015' nell'opzione `--lib`.", + "An_async_function_or_method_must_have_a_valid_awaitable_return_type_1057": "Una funzione o un metodo asincrono deve includere un tipo restituito awaitable valido.", + "An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_in_2697": "Un metodo o una funzione asincrona deve restituire un elemento 'Promise'. Assicurarsi che sia presente una dichiarazione per 'Promise' oppure includere 'ES2015' nell'opzione `--lib`.", + "An_async_iterator_must_have_a_next_method_2519": "Un iteratore asincrono deve contenere un metodo 'next()'.", + "An_element_access_expression_should_take_an_argument_1011": "Un'espressione di accesso a elementi deve accettare un argomento.", + "An_enum_member_cannot_have_a_numeric_name_2452": "Il nome di un membro di enumerazione non può essere numerico.", + "An_export_assignment_can_only_be_used_in_a_module_1231": "È possibile usare un'assegnazione di esportazione solo in un modulo.", + "An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements_2309": "Non è possibile usare un'assegnazione di esportazione in un modulo con altri elementi esportati.", + "An_export_assignment_cannot_be_used_in_a_namespace_1063": "Non è possibile usare un'assegnazione di esportazione in uno spazio dei nomi.", + "An_export_assignment_cannot_have_modifiers_1120": "Un'assegnazione di esportazione non può contenere modificatori.", + "An_export_declaration_can_only_be_used_in_a_module_1233": "È possibile usare una dichiarazione di esportazione solo in un modulo.", + "An_export_declaration_cannot_have_modifiers_1193": "Una dichiarazione di esportazione non può contenere modificatori.", + "An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive_1198": "Un valore di escape Unicode avanzato deve essere compreso tra 0x0 e 0x10FFFF inclusi.", + "An_implementation_cannot_be_declared_in_ambient_contexts_1183": "Non è possibile dichiarare un'implementazione in contesti di ambiente.", + "An_import_declaration_can_only_be_used_in_a_namespace_or_module_1232": "È possibile usare una dichiarazione di importazione solo in uno spazio dei nomi o in un modulo.", + "An_import_declaration_cannot_have_modifiers_1191": "Una dichiarazione di importazione non può contenere modificatori.", + "An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead_2691": "Un percorso di importazione non può terminare con l'estensione '{0}'. In alternativa, provare a importare '{1}'.", + "An_index_expression_argument_must_be_of_type_string_number_symbol_or_any_2342": "Un argomento di espressione di indice deve essere di tipo 'string', 'number', 'symbol' o 'any'.", + "An_index_signature_cannot_have_a_rest_parameter_1017": "Una firma dell'indice non può contenere un parametro rest.", + "An_index_signature_must_have_a_type_annotation_1021": "Una firma dell'indice deve contenere un'annotazione di tipo.", + "An_index_signature_must_have_exactly_one_parameter_1096": "Una firma dell'indice deve contenere un solo parametro.", + "An_index_signature_parameter_cannot_have_a_question_mark_1019": "Un parametro della firma dell'indice non può contenere un punto interrogativo.", + "An_index_signature_parameter_cannot_have_an_accessibility_modifier_1018": "Un parametro della firma dell'indice non può contenere un modificatore di accessibilità.", + "An_index_signature_parameter_cannot_have_an_initializer_1020": "Un parametro della firma dell'indice non può contenere un inizializzatore.", + "An_index_signature_parameter_must_have_a_type_annotation_1022": "Un parametro della firma dell'indice deve contenere un'annotazione di tipo.", + "An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead_1336": "Un tipo di parametro della firma dell'indice non può essere un alias di tipo. Provare a scrivere '[{0}: {1}]: {2}'.", + "An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead_1337": "Un tipo di parametro della firma dell'indice non può essere un tipo di unione. Provare a usare un tipo di oggetto con mapping.", + "An_index_signature_parameter_type_must_be_string_or_number_1023": "Il tipo di un parametro della firma dell'indice deve essere 'string' o 'number'.", + "An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments_2499": "Un'interfaccia può estendere solo un identificatore/nome qualificato con argomenti tipo facoltativi.", + "An_interface_may_only_extend_a_class_or_another_interface_2312": "Un'interfaccia può estendere solo una classe o un'altra interfaccia.", + "An_interface_property_cannot_have_an_initializer_1246": "Una proprietà di interfaccia non può contenere un inizializzatore.", + "An_iterator_must_have_a_next_method_2489": "Un iteratore deve contenere un metodo 'next()'.", + "An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name_1118": "Un valore letterale di oggetto non può contenere più funzioni di accesso get/set con lo stesso nome.", + "An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode_1117": "Un valore letterale di oggetto non può contenere più proprietà con lo stesso nome in modalità strict.", + "An_object_literal_cannot_have_property_and_accessor_with_the_same_name_1119": "Un valore letterale di oggetto non può contenere proprietà e funzioni di accesso con lo stesso nome.", + "An_object_member_cannot_be_declared_optional_1162": "Un membro di oggetto non può essere dichiarato come facoltativo.", + "An_overload_signature_cannot_be_declared_as_a_generator_1222": "Non è possibile dichiarare come generatore una firma di overload.", + "An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_ex_17006": "Nella parte sinistra di un'espressione di elevamento a potenza non è consentita un'espressione unaria con l'operatore '{0}'. Provare a racchiudere l'espressione tra parentesi.", + "Annotate_everything_with_types_from_JSDoc_95043": "Annotare tutto con tipi di JSDoc", + "Annotate_with_type_from_JSDoc_95009": "Annota con tipo di JSDoc", + "Annotate_with_types_from_JSDoc_95010": "Annota con tipi di JSDoc", + "Argument_expression_expected_1135": "È prevista l'espressione di argomento.", + "Argument_for_0_option_must_be_Colon_1_6046": "L'argomento per l'opzione '{0}' deve essere {1}.", + "Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_2345": "L'argomento di tipo '{0}' non è assegnabile al parametro di tipo '{1}'.", + "Array_element_destructuring_pattern_expected_1181": "È previsto il criterio di destrutturazione dell'elemento della matrice.", + "Asterisk_Slash_expected_1010": "È previsto '*/'.", + "Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_2669": "Gli aumenti per l'ambito globale possono solo essere direttamente annidati in dichiarazioni di modulo di ambiente o moduli esterni.", + "Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambien_2670": "Gli aumenti per l'ambito globale devono contenere il modificatore 'declare', a meno che non siano già presenti in un contesto di ambiente.", + "Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using__6140": "Il rilevamento automatico per le defizioni di tipi è abilitato nel progetto '{0}'. Verrà eseguito il passaggio di risoluzione aggiuntivo per il modulo '{1}' usando il percorso della cache '{2}'.", + "Base_class_expressions_cannot_reference_class_type_parameters_2562": "Le espressioni di classi di base non possono fare riferimento a parametri di tipo classe.", + "Base_constructor_return_type_0_is_not_a_class_or_interface_type_2509": "Il tipo restituito '{0}' del costruttore di base non è un tipo di classe o di interfaccia.", + "Base_constructors_must_all_have_the_same_return_type_2510": "Il tipo restituito deve essere identico per tutti i costruttori di base.", + "Base_directory_to_resolve_non_absolute_module_names_6083": "Directory di base per risolvere i nomi di modulo non assoluti.", + "Basic_Options_6172": "Opzioni di base", + "Binary_digit_expected_1177": "È prevista una cifra binaria.", + "Binding_element_0_implicitly_has_an_1_type_7031": "L'elemento di binding '{0}' contiene implicitamente un tipo '{1}'.", + "Block_scoped_variable_0_used_before_its_declaration_2448": "La variabile con ambito blocco '{0}' è stata usata prima di essere stata dichiarata.", + "Build_all_projects_including_those_that_appear_to_be_up_to_date_6368": "Compilare tutti i progetti, anche quelli che sembrano aggiornati", + "Build_one_or_more_projects_and_their_dependencies_if_out_of_date_6364": "Compilare uno o più progetti e le relative dipendenze, se non aggiornate", + "Building_project_0_6358": "Compilazione del progetto '{0}'...", + "Call_decorator_expression_90028": "Chiamare l'espressione Decorator", + "Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7020": "La firma di chiamata, in cui manca l'annotazione di tipo restituito, contiene implicitamente un tipo restituito 'any'.", + "Call_target_does_not_contain_any_signatures_2346": "La destinazione della chiamata non contiene alcuna firma.", + "Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_p_2713": "Non è possibile accedere a '{0}.{1}' perché '{0}' è un tipo ma non uno spazio dei nomi. Si intendeva recuperare il tipo della proprietà '{1}' in '{0}' con '{0}[\"{1}\"]'?", + "Cannot_assign_a_0_constructor_type_to_a_1_constructor_type_2672": "Non è possibile assegnare un tipo di costruttore '{0}' a un tipo di costruttore '{1}'.", + "Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type_2517": "Non è possibile assegnare un tipo di costruttore astratto a un tipo di costruttore non astratto.", + "Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property_2540": "Non è possibile assegnare a '{0}' perché è una costante o una proprietà di sola lettura.", + "Cannot_assign_to_0_because_it_is_not_a_variable_2539": "Non è possibile assegnare a '{0}' perché non è una variabile.", + "Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity_2671": "Non è possibile aumentare il modulo '{0}' perché viene risolto in un'entità non modulo.", + "Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity_2649": "Non è possibile aumentare il modulo '{0}' con le esportazioni dei valori perché viene risolto in un'entità non modulo.", + "Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system_6131": "Non è possibile compilare moduli con l'opzione '{0}' a meno che il flag '--module' non sia impostato su 'amd' o 'system'.", + "Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided_1208": "Non è possibile compilare spazi dei nomi se non viene specificato il flag '--isolatedModules'.", + "Cannot_create_an_instance_of_an_abstract_class_2511": "Non è possibile creare un'istanza di una classe astratta.", + "Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module_2661": "Non è possibile esportare '{0}'. Da un modulo è possibile esportare solo dichiarazioni locali.", + "Cannot_extend_a_class_0_Class_constructor_is_marked_as_private_2675": "Non è possibile estendere una classe '{0}'. Il costruttore di classe è contrassegnato come privato.", + "Cannot_extend_an_interface_0_Did_you_mean_implements_2689": "Non è possibile estendere un'interfaccia '{0}'. Si intendeva usare 'implements'?", + "Cannot_find_a_tsconfig_json_file_at_the_specified_directory_Colon_0_5057": "Non è stato trovato alcun file tsconfig.json nella directory specificata '{0}'.", + "Cannot_find_global_type_0_2318": "Il tipo globale '{0}' non è stato trovato.", + "Cannot_find_global_value_0_2468": "Il valore globale '{0}' non è stato trovato.", + "Cannot_find_lib_definition_for_0_2726": "La definizione della libreria per '{0}' non è stata trovata.", + "Cannot_find_lib_definition_for_0_Did_you_mean_1_2727": "La definizione della libreria per '{0}' non è stata trovata. Si intendeva '{1}'?", + "Cannot_find_module_0_2307": "Il modulo '{0}' non è stato trovato.", + "Cannot_find_name_0_2304": "Il nome '{0}' non è stato trovato.", + "Cannot_find_name_0_Did_you_mean_1_2552": "Il nome '{0}' non è stato trovato. Si intendeva '{1}'?", + "Cannot_find_name_0_Did_you_mean_the_instance_member_this_0_2663": "Il nome '{0}' non è stato trovato. Si intendeva il membro di istanza 'this.{0}'?", + "Cannot_find_name_0_Did_you_mean_the_static_member_1_0_2662": "Il nome '{0}' non è stato trovato. Si intendeva il membro statico '{1}.{0}'?", + "Cannot_find_namespace_0_2503": "Lo spazio dei nomi '{0}' non è stato trovato.", + "Cannot_find_parameter_0_1225": "Il parametro '{0}' non è stato trovato.", + "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009": "Il percorso della sottodirectory comune per i file di input non è stato trovato.", + "Cannot_find_type_definition_file_for_0_2688": "Il file di definizione del tipo per '{0}' non è stato trovato.", + "Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1_6137": "Non è possibile importare file di dichiarazione di tipo. Provare a importare '{0}' invece di '{1}'.", + "Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1_2481": "Non è possibile inizializzare la variabile con ambito esterna '{0}' nello stesso ambito della dichiarazione con ambito del blocco '{1}'.", + "Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatur_2349": "Non è possibile richiamare un'espressione al cui tipo manca una firma di chiamata. Per il tipo '{0}' non esistono firme di chiamata compatibili.", + "Cannot_invoke_an_object_which_is_possibly_null_2721": "Non è possibile richiamare un oggetto che è probabilmente 'null'.", + "Cannot_invoke_an_object_which_is_possibly_null_or_undefined_2723": "Non è possibile richiamare un oggetto che è probabilmente 'null' o 'undefined'.", + "Cannot_invoke_an_object_which_is_possibly_undefined_2722": "Non è possibile richiamare un oggetto che è probabilmente 'undefined'.", + "Cannot_prepend_project_0_because_it_does_not_have_outFile_set_6308": "Non è possibile anteporre il progetto '{0}' perché 'outFile' non è impostato", + "Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205": "Non è possibile riesportare un tipo quando è stato specificato il flag '--isolatedModules'.", + "Cannot_read_file_0_Colon_1_5012": "Non è possibile leggere il file '{0}': {1}.", + "Cannot_redeclare_block_scoped_variable_0_2451": "Non è possibile dichiarare di nuovo la variabile con ambito blocco '{0}'.", + "Cannot_redeclare_exported_variable_0_2323": "Non è possibile dichiarare di nuovo la variabile esportata '{0}'.", + "Cannot_redeclare_identifier_0_in_catch_clause_2492": "Non è possibile dichiarare di nuovo l'identificatore '{0}' nella clausola catch.", + "Cannot_use_JSX_unless_the_jsx_flag_is_provided_17004": "Non è possibile usare JSX a meno che non sia specificato il flag '--jsx'.", + "Cannot_use_imports_exports_or_module_augmentations_when_module_is_none_1148": "Non è possibile usare importazioni, esportazioni o aumenti del modulo quando il valore di '--module' è 'none'.", + "Cannot_use_namespace_0_as_a_type_2709": "Non è possibile usare lo spazio dei nomi '{0}' come tipo.", + "Cannot_use_namespace_0_as_a_value_2708": "Non è possibile usare lo spazio dei nomi '{0}' come valore.", + "Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature_2351": "Non è possibile usare 'new' con un'espressione al cui tipo manca una firma del costrutto o di chiamata.", + "Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files_5056": "Non è possibile scrivere il file '{0}' perché verrebbe sovrascritto da più file di input.", + "Cannot_write_file_0_because_it_would_overwrite_input_file_5055": "Non è possibile scrivere il file '{0}' perché sovrascriverebbe il file di input.", + "Catch_clause_variable_cannot_have_a_type_annotation_1196": "La variabile della clausola catch non può contenere un'annotazione di tipo.", + "Catch_clause_variable_cannot_have_an_initializer_1197": "La variabile della clausola catch non può contenere un inizializzatore.", + "Change_0_to_1_90014": "Modificare '{0}' in '{1}'", + "Change_all_extended_interfaces_to_implements_95038": "Cambiare tutte le interfacce estese in 'implements'", + "Change_all_jsdoc_style_types_to_TypeScript_95030": "Cambiare tutti i tipi in stile jsdoc in TypeScript", + "Change_all_jsdoc_style_types_to_TypeScript_and_add_undefined_to_nullable_types_95031": "Cambiare tutti i tipi in stile jsdoc in TypeScript (e aggiungere '| undefined' ai tipi nullable)", + "Change_extends_to_implements_90003": "Cambiare 'extends' in 'implements'", + "Change_spelling_to_0_90022": "Modificare l'ortografia in '{0}'", + "Checking_if_0_is_the_longest_matching_prefix_for_1_2_6104": "Verrà verificato se '{0}' è il prefisso di corrispondenza più lungo per '{1}' - '{2}'.", + "Circular_definition_of_import_alias_0_2303": "Definizione circolare dell'alias di importazione '{0}'.", + "Circularity_detected_while_resolving_configuration_Colon_0_18000": "È stata rilevata una circolarità durante la risoluzione della configurazione: {0}", + "Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_functi_2426": "La classe '{0}' definisce '{1}' come funzione di accesso di membro di istanza, mentre la classe estesa '{2}' la definisce come funzione di membro di istanza.", + "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_access_2423": "La classe '{0}' definisce '{1}' come funzione di membro di istanza, mentre la classe estesa '{2}' la definisce come funzione di accesso di membro di istanza.", + "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_proper_2424": "La classe '{0}' definisce '{1}' come funzione di membro di istanza, mentre la classe estesa '{2}' la definisce come proprietà di membro di istanza.", + "Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_functi_2425": "La classe '{0}' definisce '{1}' come proprietà di membro di istanza, mentre la classe estesa '{2}' la definisce come funzione di membro di istanza.", + "Class_0_incorrectly_extends_base_class_1_2415": "La classe '{0}' estende in modo errato la classe di base '{1}'.", + "Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclas_2720": "La classe '{0}' implementa in modo errato la classe '{1}'. Si intendeva estendere '{1}' ed ereditarne i membri come sottoclasse?", + "Class_0_incorrectly_implements_interface_1_2420": "La classe '{0}' implementa in modo errato l'interfaccia '{1}'.", + "Class_0_used_before_its_declaration_2449": "La classe '{0}' è stata usata prima di essere stata dichiarata.", + "Class_declarations_cannot_have_more_than_one_augments_or_extends_tag_8025": "Le dichiarazioni di classe non possono contenere più di un tag `@augments` o `@extends`.", + "Class_name_cannot_be_0_2414": "Il nome della classe non può essere '{0}'.", + "Class_name_cannot_be_Object_when_targeting_ES5_with_module_0_2725": "Il nome della classe non può essere 'Object' quando la destinazione è ES5 con il modulo {0}.", + "Class_static_side_0_incorrectly_extends_base_class_static_side_1_2417": "Il lato statico '{0}' della classe estende in modo errato il lato statico '{1}' della classe di base.", + "Classes_can_only_extend_a_single_class_1174": "Le classi possono estendere solo un'unica classe.", + "Classes_containing_abstract_methods_must_be_marked_abstract_2514": "Le classi che contengono metodi astratti devono essere contrassegnate come astratte.", + "Command_line_Options_6171": "Opzioni della riga di comando", + "Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json_6020": "Compila il progetto in base al percorso del file di configurazione o della cartella contenente un file 'tsconfig.json'.", + "Compiler_option_0_expects_an_argument_6044": "Con l'opzione '{0}' del compilatore è previsto un argomento.", + "Compiler_option_0_requires_a_value_of_type_1_5024": "Con l'opzione '{0}' del compilatore è richiesto un valore di tipo {1}.", + "Composite_projects_may_not_disable_declaration_emit_6304": "I progetti compositi non possono disabilitare la creazione di dichiarazioni.", + "Computed_property_names_are_not_allowed_in_enums_1164": "I nomi di proprietà calcolati non sono consentiti nelle enumerazioni.", + "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553": "In un'enumerazione con membri con valore stringa non sono consentiti valori calcolati.", + "Concatenate_and_emit_output_to_single_file_6001": "Concatena e crea l'output in un singolo file.", + "Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_librar_4090": "In '{1}' e '{2}' sono state trovate definizioni in conflitto per '{0}'. Per risolvere il conflitto, provare a installare una versione specifica di questa libreria.", + "Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7013": "La firma del costrutto, in cui manca l'annotazione di tipo restituito, contiene implicitamente un tipo restituito 'any'.", + "Constructor_implementation_is_missing_2390": "Manca l'implementazione di costruttore.", + "Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration_2673": "Il costruttore della classe '{0}' è privato e accessibile solo all'interno della dichiarazione di classe.", + "Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration_2674": "Il costruttore della classe '{0}' è protetto e accessibile solo all'interno della dichiarazione di classe.", + "Constructors_for_derived_classes_must_contain_a_super_call_2377": "I costruttori di classi derivate devono contenere una chiamata 'super'.", + "Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126": "Il file contenitore non è specificato e non è possibile determinare la directory radice. La ricerca nella cartella 'node_modules' verrà ignorata.", + "Convert_0_to_mapped_object_type_95055": "Convertire '{0}' nel tipo di oggetto con mapping", + "Convert_all_constructor_functions_to_classes_95045": "Convertire tutte le funzioni di costruttore in classi", + "Convert_all_require_to_import_95048": "Convertire tutte le occorrenze di 'require' in 'import'", + "Convert_all_to_default_imports_95035": "Convertire tutte le impostazioni predefinite", + "Convert_function_0_to_class_95002": "Converti la funzione '{0}' in classe", + "Convert_function_to_an_ES2015_class_95001": "Converti la funzione in una classe ES2015", + "Convert_named_imports_to_namespace_import_95057": "Convertire le importazioni denominate in importazione spazi dei nomi", + "Convert_namespace_import_to_named_imports_95056": "Convertire l'importazione spazi dei nomi in importazioni denominate", + "Convert_require_to_import_95047": "Convertire 'require' in 'import'", + "Convert_to_ES6_module_95017": "Converti in modulo ES6", + "Convert_to_default_import_95013": "Converti nell'importazione predefinita", + "Corrupted_locale_file_0_6051": "Il file delle impostazioni locali {0} è danneggiato.", + "Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type_7016": "Non è stato trovato alcun file di dichiarazione per il modulo '{0}'. A '{1}' è assegnato implicitamente un tipo 'any'.", + "Could_not_write_file_0_Colon_1_5033": "Non è stato possibile scrivere il file '{0}': {1}.", + "DIRECTORY_6038": "DIRECTORY", + "Declaration_expected_1146": "È prevista la dichiarazione.", + "Declaration_name_conflicts_with_built_in_global_identifier_0_2397": "Il nome della dichiarazione è in conflitto con l'identificatore globale predefinito '{0}'.", + "Declaration_or_statement_expected_1128": "È prevista la dichiarazione o l'istruzione.", + "Declare_method_0_90023": "Dichiarare il metodo '{0}'", + "Declare_property_0_90016": "Dichiarare la proprietà '{0}'", + "Declare_static_method_0_90024": "Dichiarare il metodo statico '{0}'", + "Declare_static_property_0_90027": "Dichiarare la proprietà statica '{0}'", + "Decorators_are_not_valid_here_1206": "In questo punto le espressioni Decorator non sono valide.", + "Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name_1207": "Non è possibile applicare le espressioni Decorator a più funzioni di accesso get/set con lo stesso nome.", + "Default_export_of_the_module_has_or_is_using_private_name_0_4082": "L'esportazione predefinita del modulo contiene o usa il nome privato '{0}'.", + "Delete_all_unused_declarations_95024": "Eliminare tutte le dichiarazioni non usate", + "Delete_the_outputs_of_all_projects_6365": "Eliminare gli output di tutti i progetti", + "Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react__6084": "[Deprecata] In alternativa, usare '--jsxFactory'. Specifica l'oggetto richiamato per createElement quando la destinazione è la creazione JSX 'react'", + "Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file_6170": "[Deprecata] In alternativa, usare '--outFile'. Concatena e crea l'output in un singolo file", + "Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files_6160": "[Deprecata] In alternativa, usare '--skipLibCheck'. Ignora il controllo del tipo dei file di dichiarazione delle librerie predefinite.", + "Digit_expected_1124": "È prevista la cifra.", + "Directory_0_does_not_exist_skipping_all_lookups_in_it_6148": "La directory '{0}' non esiste. Tutte le ricerche che la interessano verranno ignorate.", + "Disable_checking_for_this_file_90018": "Disabilitare la verifica per questo file", + "Disable_size_limitations_on_JavaScript_projects_6162": "Disabilita le dimensioni relative alle dimensioni per i progetti JavaScript.", + "Disable_strict_checking_of_generic_signatures_in_function_types_6185": "Disabilitare il controllo tassativo delle firme generiche nei tipi funzione.", + "Disallow_inconsistently_cased_references_to_the_same_file_6078": "Non consente riferimenti allo stesso file in cui le maiuscole/minuscole vengono usate in modo incoerente.", + "Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files_6159": "Non aggiunge riferimenti con tripla barra (////) o moduli importati all'elenco di file compilati.", + "Do_not_emit_comments_to_output_6009": "Non crea commenti nell'output.", + "Do_not_emit_declarations_for_code_that_has_an_internal_annotation_6056": "Non crea dichiarazioni per codice che contiene un'annotazione '@internal'.", + "Do_not_emit_outputs_6010": "Non crea output.", + "Do_not_emit_outputs_if_any_errors_were_reported_6008": "Non crea output se sono stati restituiti errori.", + "Do_not_emit_use_strict_directives_in_module_output_6112": "Non crea direttive 'use strict' nell'output del modulo.", + "Do_not_erase_const_enum_declarations_in_generated_code_6007": "Non cancella le dichiarazioni di enumerazione const nel codice generato.", + "Do_not_generate_custom_helper_functions_like_extends_in_compiled_output_6157": "Non genera funzioni di supporto personalizzate, come '__extends', nell'output compilato.", + "Do_not_include_the_default_library_file_lib_d_ts_6158": "Non include il file di libreria predefinito (lib.d.ts).", + "Do_not_report_errors_on_unreachable_code_6077": "Non segnala gli errori in caso di codice non raggiungibile.", + "Do_not_report_errors_on_unused_labels_6074": "Non segnala gli errori in caso di etichette non usate.", + "Do_not_resolve_the_real_path_of_symlinks_6013": "Non risolvere il percorso reale di collegamenti simbolici.", + "Do_not_truncate_error_messages_6165": "Non tronca i messaggi di errore.", + "Duplicate_declaration_0_2718": "La dichiarazione '{0}' è duplicata.", + "Duplicate_function_implementation_2393": "Implementazione di funzione duplicata.", + "Duplicate_identifier_0_2300": "Identificatore '{0}' duplicato.", + "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_2441": "Identificatore '{0}' duplicato. Il compilatore riserva il nome '{1}' nell'ambito di primo livello di un modulo.", + "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_func_2529": "L'identificatore '{0}' è duplicato. Il compilatore riserva il nome '{1}' nell'ambito di primo livello di un modulo che contiene funzioni asincrone.", + "Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions_2520": "Identificatore '{0}' duplicato. Il compilatore usa la dichiarazione '{1}' per supportare le funzioni asincrone.", + "Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters_2396": "Identificatore 'arguments' duplicato. Il compilatore usa 'arguments' per inizializzare i parametri rest.", + "Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_me_2543": "Identificatore '_newTarget' duplicato. Il compilatore usa la dichiarazione di variabile '_newTarget' per acquisire il riferimento alla metaproprietà 'new.target'.", + "Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference_2401": "Identificatore '_super' duplicato. Il compilatore usa '_super' per acquisire il riferimento della classe di base.", + "Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference_2399": "Identificatore '_this' duplicato. Il compilatore usa la dichiarazione di variabile '_this' per acquisire il riferimento 'this'.", + "Duplicate_label_0_1114": "Etichetta '{0}' duplicata.", + "Duplicate_number_index_signature_2375": "La firma dell'indice di tipo number è duplicata.", + "Duplicate_string_index_signature_2374": "La firma dell'indice di tipo string è duplicata.", + "Dynamic_import_cannot_have_type_arguments_1326": "Nell'importazione dinamica non possono essere presenti argomenti tipo", + "Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext_1323": "L'importazione dinamica è supportata solo quando il valore del flag '--module' è 'commonjs' o 'esNext'.", + "Dynamic_import_must_have_one_specifier_as_an_argument_1324": "Come argomento dell'importazione dinamica si può indicare un solo identificatore.", + "Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036": "L'identificatore dell'importazione dinamica deve essere di tipo 'string', ma il tipo specificato qui è '{0}'.", + "Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015": "L'elemento contiene implicitamente un tipo 'any' perché l'espressione di indice non è di tipo 'number'.", + "Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature_7017": "L'elemento contiene implicitamente un tipo 'any' perché al tipo '{0}' non è assegnata alcuna firma dell'indice.", + "Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files_6164": "Crea un BOM (Byte Order Mark) UTF-8 all'inizio dei file di output.", + "Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file_6151": "Crea un unico file con i mapping di origine invece di file separati.", + "Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap__6152": "Crea l'origine unitamente alle mappe di origine all'interno di un unico file. Richiede l'impostazione di '--inlineSourceMap' o '--sourceMap'.", + "Enable_all_strict_type_checking_options_6180": "Abilita tutte le opzioni per i controlli del tipo strict.", + "Enable_project_compilation_6302": "Abilitare la compilazione dei progetti", + "Enable_strict_checking_of_function_types_6186": "Abilita il controllo tassativo dei tipi funzione.", + "Enable_strict_checking_of_property_initialization_in_classes_6187": "Abilita il controllo tassativo dell'inizializzazione delle proprietà nelle classi.", + "Enable_strict_null_checks_6113": "Abilita i controlli strict Null.", + "Enable_tracing_of_the_name_resolution_process_6085": "Abilita la traccia del processo di risoluzione dei nomi.", + "Enable_verbose_logging_6366": "Abilitare la registrazione dettagliata", + "Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for__7037": "Abilita l'interoperabilità di creazione tra moduli ES e CommonJS tramite la creazione di oggetti spazio dei nomi per tutte le importazioni. Implica 'allowSyntheticDefaultImports'.", + "Enables_experimental_support_for_ES7_async_functions_6068": "Abilita il supporto sperimentale per le funzioni asincrone di ES7.", + "Enables_experimental_support_for_ES7_decorators_6065": "Abilita il supporto sperimentale per le espressioni Decorator di ES7.", + "Enables_experimental_support_for_emitting_type_metadata_for_decorators_6066": "Abilita il supporto sperimentale per la creazione dei metadati dei tipi per le espressioni Decorator.", + "Enum_0_used_before_its_declaration_2450": "L'enumerazione '{0}' è stata usata prima di essere stata dichiarata.", + "Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations_2567": "È possibile unire dichiarazioni di enumerazione solo con lo spazio dei nomi o altre dichiarazioni di enumerazione.", + "Enum_declarations_must_all_be_const_or_non_const_2473": "Le dichiarazioni di enumerazione devono essere tutte const o tutte non const.", + "Enum_member_expected_1132": "È previsto il membro di enumerazione.", + "Enum_member_must_have_initializer_1061": "Il membro di enumerazione deve contenere l'inizializzatore.", + "Enum_name_cannot_be_0_2431": "Il nome dell'enumerazione non può essere '{0}'.", + "Enum_type_0_has_members_with_initializers_that_are_not_literals_2535": "Il tipo di enumerazione '{0}' contiene membri i cui inizializzatori non sono valori letterali.", + "Examples_Colon_0_6026": "Esempi: {0}", + "Excessive_stack_depth_comparing_types_0_and_1_2321": "La profondità dello stack per il confronto dei tipi '{0}' e '{1}' è eccessiva.", + "Expected_0_1_type_arguments_provide_these_with_an_extends_tag_8027": "Sono previsti argomento tipo {0}-{1}. Per specificarli, usare un tag '@extends'.", + "Expected_0_arguments_but_got_1_2554": "Sono previsti {0} argomenti, ma ne sono stati ottenuti {1}.", + "Expected_0_arguments_but_got_1_or_more_2556": "Sono previsti {0} argomenti, ma ne sono stati ottenuti più di {1}.", + "Expected_0_type_arguments_but_got_1_2558": "Sono previsti {0} argomenti tipo, ma ne sono stati ottenuti {1}.", + "Expected_0_type_arguments_provide_these_with_an_extends_tag_8026": "Sono previsti {0} argomenti tipo. Per specificarli, usare un tag '@extends'.", + "Expected_at_least_0_arguments_but_got_1_2555": "Sono previsti almeno {0} argomenti, ma ne sono stati ottenuti {1}.", + "Expected_at_least_0_arguments_but_got_1_or_more_2557": "Sono previsti almeno {0} argomenti, ma ne sono stati ottenuti {1} o più.", + "Expected_corresponding_JSX_closing_tag_for_0_17002": "È previsto il tag di chiusura JSX corrispondente per '{0}'.", + "Expected_corresponding_closing_tag_for_JSX_fragment_17015": "È previsto il tag di chiusura corrispondente per il frammento JSX.", + "Expected_type_of_0_field_in_package_json_to_be_string_got_1_6105": "Il tipo previsto del campo '{0}' in 'package.json' è 'string', ma è stato ottenuto '{1}'.", + "Experimental_Options_6177": "Opzioni sperimentali", + "Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_t_1219": "Il supporto sperimentale per gli elementi Decorator è una funzionalità soggetta a modifica nelle prossime versioni. Per rimuovere questo avviso, impostare l'opzione 'experimentalDecorators'.", + "Explicitly_specified_module_resolution_kind_Colon_0_6087": "Il tipo di risoluzione del modulo '{0}' è stato specificato in modo esplicito.", + "Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or__1203": "Non è possibile usare l'assegnazione di esportazione se destinata a moduli ECMAScript. Provare a usare 'export default' o un altro formato di modulo.", + "Export_assignment_is_not_supported_when_module_flag_is_system_1218": "L'assegnazione dell'esportazione non è supportata quando il valore del flag '--module' è 'system'.", + "Export_declaration_conflicts_with_exported_declaration_of_0_2484": "La dichiarazione di esportazione è in conflitto con la dichiarazione esportata di '{0}'.", + "Export_declarations_are_not_permitted_in_a_namespace_1194": "Le dichiarazioni di esportazione non sono consentite in uno spazio dei nomi.", + "Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_2656": "Il file delle definizioni di tipi di pacchetto esterno esportate '{0}' non è un modulo. Contattare l'autore del pacchetto per aggiornare la definizione del pacchetto.", + "Exported_external_package_typings_file_cannot_contain_tripleslash_references_Please_contact_the_pack_2654": "Il file delle definizioni di tipi di pacchetto esterno esportate non può contenere riferimenti con ///. Contattare l'autore del pacchetto per aggiornare la definizione del pacchetto.", + "Exported_type_alias_0_has_or_is_using_private_name_1_4081": "L'alias di tipo esportato '{0}' contiene o usa il nome privato '{1}'.", + "Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4023": "La variabile esportata '{0}' contiene o usa il nome '{1}' del modulo esterno {2} ma non può essere rinominata.", + "Exported_variable_0_has_or_is_using_name_1_from_private_module_2_4024": "La variabile esportata '{0}' contiene o usa il nome '{1}' del modulo privato '{2}'.", + "Exported_variable_0_has_or_is_using_private_name_1_4025": "La variabile esportata '{0}' contiene o usa il nome privato '{1}'.", + "Exports_and_export_assignments_are_not_permitted_in_module_augmentations_2666": "Le esportazioni e le assegnazioni di esportazioni non sono consentite negli aumenti del modulo.", + "Expression_expected_1109": "È prevista l'espressione.", + "Expression_or_comma_expected_1137": "È prevista l'espressione o la virgola.", + "Expression_resolves_to_super_that_compiler_uses_to_capture_base_class_reference_2402": "L'espressione viene risolta in '_super', che è usato dal compilatore per acquisire il riferimento della classe di base.", + "Expression_resolves_to_variable_declaration_0_that_compiler_uses_to_support_async_functions_2521": "L'espressione viene risolta nella dichiarazione di variabile '{0}', che è usata dal compilatore per supportare le funzioni asincrone.", + "Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta__2544": "L'espressione viene risolta nella dichiarazione di variabile '_newTarget', che è usata dal compilatore per acquisire il riferimento alla metaproprietà 'new.target'.", + "Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference_2400": "L'espressione viene risolta nella dichiarazione di variabile '_this', che è usata dal compilatore per acquisire il riferimento 'this'.", + "Extract_constant_95006": "Estrarre la costante", + "Extract_function_95005": "Estrarre la funzione", + "Extract_to_0_in_1_95004": "Estrarre in {0} in {1}", + "Extract_to_0_in_1_scope_95008": "Estrarre in {0} nell'ambito {1}", + "Extract_to_0_in_enclosing_scope_95007": "Estrarre in {0} nell'ambito che lo contiene", + "FILE_6035": "FILE", + "FILE_OR_DIRECTORY_6040": "FILE O DIRECTORY", + "Failed_to_parse_file_0_Colon_1_5014": "Non è stato possibile analizzare il file '{0}': {1}.", + "Fallthrough_case_in_switch_7029": "Caso di fallthrough in switch.", + "File_0_does_not_exist_6096": "Il file '{0}' non esiste.", + "File_0_exist_use_it_as_a_name_resolution_result_6097": "Il file '{0}' esiste. Usarlo come risultato per la risoluzione dei nomi.", + "File_0_has_an_unsupported_extension_so_skipping_it_6081": "L'estensione del file '{0}' non è supportata. Il file verrà ignorato.", + "File_0_has_unsupported_extension_The_only_supported_extensions_are_1_6054": "L'estensione del file '{0}' non è supportata. Le uniche estensioni supportate sono {1}.", + "File_0_is_not_a_module_2306": "Il file '{0}' non è un modulo.", + "File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern_6307": "Il file '{0}' non è presente nell'elenco dei file di progetto. I progetti devono elencare tutti i file o usare un criterio 'include'.", + "File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files_6059": "Il file '{0}' non si trova in 'rootDir' '{1}'. 'rootDir' deve contenere tutti i file di origine.", + "File_0_not_found_6053": "Il file '{0}' non è stato trovato.", + "File_change_detected_Starting_incremental_compilation_6032": "È stata rilevata una modifica ai file. Verrà avviata la compilazione incrementale...", + "File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module_80001": "Il file è un modulo CommonJS; può essere convertito in un modulo ES6.", + "File_name_0_differs_from_already_included_file_name_1_only_in_casing_1149": "Il nome file '{0}' differisce da quello già incluso '{1}' solo per l'uso di maiuscole/minuscole.", + "File_name_0_has_a_1_extension_stripping_it_6132": "L'estensione del nome file '{0}' è '{1}' e verrà rimossa.", + "File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildca_5065": "La specifica del file non può contenere una directory padre ('..') inserita dopo un carattere jolly ('**') di directory ricorsiva: '{0}'.", + "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010": "La specifica del file non può terminare con caratteri jolly ('**') di directory ricorsiva: '{0}'.", + "Fix_all_detected_spelling_errors_95026": "Correggere tutti gli errori di ortografia rilevati", + "Found_0_errors_Watching_for_file_changes_6194": "Sono stati trovati {0} errori. Verranno individuate le modifiche ai file.", + "Found_1_error_Watching_for_file_changes_6193": "È stato trovato 1 errore. Verranno individuate le modifiche ai file.", + "Found_package_json_at_0_6099": "Il file 'package.json' è stato trovato in '{0}'.", + "Found_package_json_at_0_Package_ID_is_1_6190": "Il file 'package.json' è stato trovato in '{0}'. L'ID pacchetto è '{1}'.", + "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_1250": "Le dichiarazioni di funzione non sono consentite all'interno di blocchi in modalità strict quando la destinazione è 'ES3' o 'ES5'.", + "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_d_1251": "Le dichiarazioni di funzione non sono consentite all'interno di blocchi in modalità strict quando la destinazione è 'ES3' o 'ES5'. Le definizioni di classe sono impostate automaticamente nella modalità strict.", + "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_1252": "Le dichiarazioni di funzione non sono consentite all'interno di blocchi in modalità strict quando la destinazione è 'ES3' o 'ES5'. I moduli sono impostati automaticamente nella modalità strict.", + "Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type_7011": "L'espressione di funzione, in cui manca l'annotazione di tipo restituito, contiene implicitamente un tipo restituito '{0}'.", + "Function_implementation_is_missing_or_not_immediately_following_the_declaration_2391": "L'implementazione di funzione manca o non segue immediatamente la dichiarazione.", + "Function_implementation_name_must_be_0_2389": "Il nome dell'implementazione di funzione deve essere '{0}'.", + "Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_ref_7024": "La funzione contiene implicitamente il tipo restituito 'any', perché non contiene un'annotazione di tipo restituito e viene usata come riferimento diretto o indiretto in una delle relative espressioni restituite.", + "Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined_2366": "Nella funzione manca l'istruzione return finale e il tipo restituito non include 'undefined'.", + "Function_overload_must_be_static_2387": "L'overload della funzione deve essere statico.", + "Function_overload_must_not_be_static_2388": "L'overload della funzione non deve essere statico.", + "Generate_get_and_set_accessors_95046": "Generare le funzioni di accesso 'get' e 'set'", + "Generates_a_sourcemap_for_each_corresponding_d_ts_file_6000": "Genera un sourcemap per ogni file '.d.ts' corrispondente.", + "Generates_corresponding_d_ts_file_6002": "Genera il file '.d.ts' corrispondente.", + "Generates_corresponding_map_file_6043": "Genera il file '.map' corrispondente.", + "Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_typ_7025": "Il tipo del generatore è implicitamente '{0}' perché non contiene alcun valore. Provare a specificare un tipo restituito.", + "Generators_are_not_allowed_in_an_ambient_context_1221": "I generatori non sono consentiti in un contesto di ambiente.", + "Generators_are_only_available_when_targeting_ECMAScript_2015_or_higher_1220": "I generatori sono disponibili solo se destinati a ECMAScript 2015 o versioni successive.", + "Generic_type_0_requires_1_type_argument_s_2314": "Il tipo generico '{0}' richiede {1} argomento/i di tipo.", + "Generic_type_0_requires_between_1_and_2_type_arguments_2707": "Il tipo generico '{0}' richiede tra {1} e {2} argomenti tipo.", + "Generic_type_instantiation_is_excessively_deep_and_possibly_infinite_2550": "La creazione di un'istanza di tipo generico presenta troppi livelli ed è probabilmente infinita.", + "Getter_and_setter_accessors_do_not_agree_in_visibility_2379": "Le funzioni di accesso getter e setter non concordano nella visibilità.", + "Global_module_exports_may_only_appear_at_top_level_1316": "Le esportazioni di moduli globali possono essere usate solo al primo livello.", + "Global_module_exports_may_only_appear_in_declaration_files_1315": "Le esportazioni di moduli globali possono essere usate solo in file di dichiarazione.", + "Global_module_exports_may_only_appear_in_module_files_1314": "Le esportazioni di moduli globali possono essere usate solo in file di modulo.", + "Global_type_0_must_be_a_class_or_interface_type_2316": "Il tipo globale '{0}' deve un tipo di classe o di interfaccia.", + "Global_type_0_must_have_1_type_parameter_s_2317": "Il tipo globale '{0}' deve contenere {1} parametro/i di tipo.", + "Hexadecimal_digit_expected_1125": "È prevista la cifra esadecimale.", + "Identifier_expected_0_is_a_reserved_word_in_strict_mode_1212": "È previsto un identificatore. '{0}' è una parola riservata in modalità strict.", + "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_stric_1213": "È previsto un identificatore. '{0}' è una parola riservata in modalità strict. Le definizioni di classe sono automaticamente impostate sulla modalità strict.", + "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode_1214": "È previsto un identificatore. '{0}' è una parola riservata in modalità strict. I moduli vengono impostati automaticamente in modalità strict.", + "Identifier_expected_1003": "È previsto l'identificatore.", + "Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules_1216": "È previsto un identificatore. '__esModule' è riservato come marcatore esportato durante la trasformazione di moduli ECMAScript.", + "Ignore_this_error_message_90019": "Ignorare questo messaggio di errore", + "Implement_all_inherited_abstract_classes_95040": "Implementare tutte le classi astratte ereditate", + "Implement_all_unimplemented_interfaces_95032": "Implementare tutte le interfacce non implementate", + "Implement_inherited_abstract_class_90007": "Implementare la classe astratta ereditata", + "Implement_interface_0_90006": "Implementare l'interfaccia '{0}'", + "Implements_clause_of_exported_class_0_has_or_is_using_private_name_1_4019": "La clausola implements della classe esportata '{0}' contiene o usa il nome privato '{1}'.", + "Import_0_from_module_1_90013": "Importare '{0}' dal modulo \"{1}\"", + "Import_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_import_Asterisk_as_1202": "Non è possibile usare l'assegnazione di importazione se destinata a moduli ECMAScript. Provare a usare 'import * as ns from \"mod\"', 'import {a} from \"mod\"', 'import d from \"mod\"' o un altro formato di modulo.", + "Import_declaration_0_is_using_private_name_1_4000": "La dichiarazione di importazione '{0}' usa il nome privato '{1}'.", + "Import_declaration_conflicts_with_local_declaration_of_0_2440": "La dichiarazione di importazione è in conflitto con la dichiarazione locale di '{0}'.", + "Import_declarations_in_a_namespace_cannot_reference_a_module_1147": "Le dichiarazioni di importazione in uno spazio dei nomi non possono far riferimento a un modulo.", + "Import_emit_helpers_from_tslib_6139": "Importa gli helper di creazione da 'tslib'.", + "Import_may_be_converted_to_a_default_import_80003": "L'importazione può essere convertita in un'importazione predefinita.", + "Import_name_cannot_be_0_2438": "Il nome dell'importazione non può essere '{0}'.", + "Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relati_2439": "La dichiarazione di importazione o esportazione in una dichiarazione di modulo di ambiente non può fare riferimento al modulo tramite il nome di modulo relativo.", + "Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_mod_2667": "Le importazioni non sono consentite negli aumenti di modulo. Provare a spostarle nel modulo esterno di inclusione.", + "In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066": "Nelle dichiarazioni di enumerazione dell'ambiente l'inizializzatore di membro deve essere un'espressione costante.", + "In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enu_2432": "In un'enumerazione con più dichiarazioni solo una di queste può omettere un inizializzatore per il primo elemento dell'enumerazione.", + "In_const_enum_declarations_member_initializer_must_be_constant_expression_2474": "Nelle dichiarazioni di enumerazione 'const' l'inizializzatore di membro deve essere un'espressione costante.", + "Include_modules_imported_with_json_extension_6197": "Includere i moduli importati con estensione '.json'", + "Index_signature_in_type_0_only_permits_reading_2542": "La firma dell'indice nel tipo '{0}' consente solo la lettura.", + "Index_signature_is_missing_in_type_0_2329": "Nel tipo '{0}' manca la firma dell'indice.", + "Index_signatures_are_incompatible_2330": "Le firme dell'indice sono incompatibili.", + "Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local_2395": "Le singole dichiarazioni della dichiarazione sottoposta a merge '{0}' devono essere tutte esportate o tutte locali.", + "Infer_all_types_from_usage_95023": "Derivare tutti i tipi dall'utilizzo", + "Infer_parameter_types_from_usage_95012": "Derivare i tipi di parametro dall'utilizzo", + "Infer_type_of_0_from_usage_95011": "Derivare il tipo di '{0}' dall'utilizzo", + "Initialize_property_0_in_the_constructor_90020": "Inizializzare la proprietà '{0}' nel costruttore", + "Initialize_static_property_0_90021": "Inizializzare la proprietà statica '{0}'", + "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301": "L'inizializzatore della variabile del membro di istanza '{0}' non può fare riferimento all'identificatore '{1}' dichiarato nel costruttore.", + "Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it_2373": "L'inizializzatore del parametro '{0}' non può fare riferimento all'identificatore '{1}' dichiarato dopo di esso.", + "Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value_2525": "L'inizializzatore non fornisce alcun valore per questo elemento di binding e per quest'ultimo non è disponibile un valore predefinito.", + "Initializers_are_not_allowed_in_ambient_contexts_1039": "Gli inizializzatori non sono consentiti in contesti di ambiente.", + "Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file_6070": "Inizializza un progetto TypeScript e crea un file tsconfig.json.", + "Insert_command_line_options_and_files_from_a_file_6030": "Inserisce i file e le opzioni della riga di comando da un file.", + "Install_0_95014": "Installa '{0}'", + "Install_all_missing_types_packages_95033": "Installare tutti i pacchetti di tipi mancanti", + "Interface_0_cannot_simultaneously_extend_types_1_and_2_2320": "L'interfaccia '{0}' non può estendere simultaneamente i tipi '{1}' e '{2}'.", + "Interface_0_incorrectly_extends_interface_1_2430": "L'interfaccia '{0}' estende in modo errato l'interfaccia '{1}'.", + "Interface_declaration_cannot_have_implements_clause_1176": "La dichiarazione di interfaccia non può avere una clausola 'implements'.", + "Interface_name_cannot_be_0_2427": "Il nome dell'interfaccia non può essere '{0}'.", + "Invalid_character_1127": "Carattere non valido.", + "Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augm_2665": "Il nome di modulo nell'aumento non è valido. Il modulo '{0}' viene risolto in un modulo non tipizzato in '{1}', che non può essere aumentato.", + "Invalid_module_name_in_augmentation_module_0_cannot_be_found_2664": "Il nome di modulo nell'aumento non è valido. Il modulo '{0}' non è stato trovato.", + "Invalid_reference_directive_syntax_1084": "La sintassi della direttiva 'reference' non è valida.", + "Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode_1210": "Uso non valido di '{0}'. Le definizioni di classe sono automaticamente impostate sulla modalità strict.", + "Invalid_use_of_0_Modules_are_automatically_in_strict_mode_1215": "Uso non valido di '{0}'. I moduli vengono impostati automaticamente in modalità strict.", + "Invalid_use_of_0_in_strict_mode_1100": "Uso non valido di '{0}' in modalità strict.", + "Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name_5067": "Il valore non è valido per 'jsxFactory'. '{0}' non è un identificatore o un nome qualificato valido.", + "Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier_5059": "Il valore di '--reactNamespace' non è valido. '{0}' non è un identificatore valido", + "JSDoc_0_1_does_not_match_the_extends_2_clause_8023": "Il tag '@{0} {1}' di JSDoc non corrisponde alla clausola 'extends {2}'.", + "JSDoc_0_is_not_attached_to_a_class_8022": "Il tag '@{0}' di JSDoc non è collegato a una classe.", + "JSDoc_may_only_appear_in_the_last_parameter_of_a_signature_8028": "JSDoc '...' può essere presente solo nell'ultimo parametro di una firma.", + "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_8024": "Il nome del tag '@param' di JSDoc è '{0}', ma non esiste alcun parametro con questo nome.", + "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_h_8029": "Il nome del tag '@param' di JSDoc è '{0}', ma non esiste alcun parametro con questo nome. Se contenesse un tipo matrice, corrisponderebbe ad 'arguments'.", + "JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags_8021": "Il tag '@typedef' di JSDoc deve contenere un'annotazione di tipo o essere seguito dal tag '@property' o '@member'.", + "JSDoc_types_can_only_be_used_inside_documentation_comments_8020": "I tipi JSDoc possono essere usati solo nei commenti della documentazione.", + "JSDoc_types_may_be_moved_to_TypeScript_types_80004": "I tipi JSDoc possono essere convertiti in tipi TypeScript.", + "JSX_attribute_expected_17003": "È previsto l'attributo JSX.", + "JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000": "Agli attributi JSX deve essere assegnato solo un elemento 'expression' non vuoto.", + "JSX_element_0_has_no_corresponding_closing_tag_17008": "Per l'elemento JSX '{0}' non esiste alcun tag di chiusura corrispondente.", + "JSX_element_attributes_type_0_may_not_be_a_union_type_2600": "Il tipo '{0}' degli attributi dell'elemento JSX potrebbe non essere un tipo di unione.", + "JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property_2607": "La classe dell'elemento JSX non supporta gli attributi perché non contiene una proprietà '{0}'.", + "JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists_7026": "L'elemento JSX contiene implicitamente il tipo 'any' perché non esiste alcuna interfaccia 'JSX.{0}'.", + "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602": "L'elemento JSX contiene implicitamente il tipo 'any' perché il tipo globale 'JSX.Element' non esiste.", + "JSX_element_type_0_does_not_have_any_construct_or_call_signatures_2604": "Il tipo '{0}' dell'elemento JSX non contiene firme di costrutto o chiamata.", + "JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements_2605": "Il tipo '{0}' dell'elemento JSX non è una funzione del costruttore per elementi JSX.", + "JSX_elements_cannot_have_multiple_attributes_with_the_same_name_17001": "Gli elementi JSX non possono contenere più attributi con lo stesso nome.", + "JSX_expressions_must_have_one_parent_element_2657": "Le espressioni JSX devono contenere un solo elemento padre.", + "JSX_fragment_has_no_corresponding_closing_tag_17014": "Per il frammento JSX non esiste alcun tag di chiusura corrispondente.", + "JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma_17017": "Il frammento JSX non è supportato quando si usa una direttiva pragma factory JSX inline", + "JSX_fragment_is_not_supported_when_using_jsxFactory_17016": "Il frammento JSX non è supportato quando si usa --jsxFactory", + "JSX_spread_child_must_be_an_array_type_2609": "L'elemento figlio dell'attributo spread JSX deve essere un tipo di matrice.", + "Jump_target_cannot_cross_function_boundary_1107": "La destinazione di collegamento non può oltrepassare il limite della funzione.", + "KIND_6034": "TIPOLOGIA", + "LOCATION_6037": "PERCORSO", + "Language_service_is_disabled_9004": "Il servizio di linguaggio è disabilitato.", + "Left_side_of_comma_operator_is_unused_and_has_no_side_effects_2695": "Il lato sinistro dell'operatore virgola non è usato e non ha effetti collaterali.", + "Line_break_not_permitted_here_1142": "L'interruzione di riga non è consentita in questo punto.", + "Line_terminator_not_permitted_before_arrow_1200": "Il terminatore di riga non è consentito prima di arrow.", + "List_of_folders_to_include_type_definitions_from_6161": "Elenco di cartelle da cui includere le definizioni di tipo.", + "List_of_language_service_plugins_6181": "Elenco dei plug-in dei servizi di linguaggio.", + "List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime_6168": "Elenco delle cartelle radice il cui contenuto combinato rappresenta la struttura del progetto in fase di esecuzione.", + "Loading_0_from_the_root_dir_1_candidate_location_2_6109": "Verrà eseguito il caricamento di '{0}' dalla directory radice '{1}'. Percorso candidato: '{2}'.", + "Loading_module_0_from_node_modules_folder_target_file_type_1_6098": "Verrà eseguito il caricamento del modulo '{0}' dalla cartella 'node_modules'. Tipo di file di destinazione: '{1}'.", + "Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1_6095": "Verrà eseguito il caricamento del modulo come file/cartella. Percorso candidato del modulo: '{0}'. Tipo di file di destinazione: '{1}'.", + "Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1_6048": "Le impostazioni locali devono essere nel formato o -, ad esempio, '{0}' o '{1}'.", + "Longest_matching_prefix_for_0_is_1_6108": "Il prefisso di corrispondenza più lungo per '{0}' è '{1}'.", + "Looking_up_in_node_modules_folder_initial_location_0_6125": "Verrà eseguita la ricerca nella cartella 'node_modules'. Percorso iniziale: '{0}'.", + "Make_all_super_calls_the_first_statement_in_their_constructor_95036": "Impostare tutte le chiamate a 'super()' come prima istruzione nel costruttore", + "Make_super_call_the_first_statement_in_the_constructor_90002": "Impostare la chiamata a 'super()' come prima istruzione nel costruttore", + "Mapped_object_type_implicitly_has_an_any_template_type_7039": "Il tipo di oggetto con mapping contiene implicitamente un tipo di modello 'any'.", + "Member_0_implicitly_has_an_1_type_7008": "Il membro '{0}' contiene implicitamente un tipo '{1}'.", + "Merge_conflict_marker_encountered_1185": "È stato rilevato un indicatore di conflitti di merge.", + "Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_d_2652": "La dichiarazione '{0}' sottoposta a merge non può includere una dichiarazione di esportazione predefinita. Provare ad aggiungere una dichiarazione 'export default {0}' distinta.", + "Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constru_17013": "La metaproprietà '{0}' è consentita solo nel corpo di una dichiarazione di funzione, di un'espressione di funzione o di un costruttore.", + "Method_0_cannot_have_an_implementation_because_it_is_marked_abstract_1245": "Il metodo '{0}' non può includere un'implementazione perché è contrassegnato come astratto.", + "Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4101": "Il metodo '{0}' dell'interfaccia esportata ha o usa il nome '{1}' del modulo privato '{2}'.", + "Method_0_of_exported_interface_has_or_is_using_private_name_1_4102": "Il metodo '{0}' dell'interfaccia esportata ha o usa il nome privato '{1}'.", + "Modifiers_cannot_appear_here_1184": "In questo punto non è possibile usare modificatori.", + "Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_1340": "Il modulo '{0}' non fa riferimento a un tipo, ma qui viene usato come tipo.", + "Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here_1339": "Il modulo '{0}' non fa riferimento a un valore, ma qui viene usato come valore.", + "Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambig_2308": "Il modulo {0} ha già esportato un membro denominato '{1}'. Per risolvere l'ambiguità, provare a esportarlo di nuovo in modo esplicito.", + "Module_0_has_no_default_export_1192": "Per il modulo '{0}' non esistono esportazioni predefinite.", + "Module_0_has_no_exported_member_1_2305": "Il modulo '{0}' non contiene un membro esportato '{1}'.", + "Module_0_has_no_exported_member_1_Did_you_mean_2_2724": "Per il modulo '{0}' non esiste alcun membro esportato '{1}'. Si intendeva '{2}'?", + "Module_0_is_hidden_by_a_local_declaration_with_the_same_name_2437": "Il modulo '{0}' è nascosto da una dichiarazione locale con lo stesso nome.", + "Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct_2497": "Il modulo '{0}' viene risolto in un'entità non modulo e non può essere importato con questo costrutto.", + "Module_0_uses_export_and_cannot_be_used_with_export_Asterisk_2498": "Il modulo '{0}' usa 'export =' e non può essere usato con 'export *'.", + "Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified_6145": "Il modulo '{0}' è stato risolto come modulo di ambiente dichiarato in '{1}' dal momento che questo file non è stato modificato.", + "Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1_6144": "Il modulo '{0}' è stato risolto come modulo di ambiente dichiarato in locale nel file '{1}'.", + "Module_0_was_resolved_to_1_but_jsx_is_not_set_6142": "Il modulo '{0}' è stato risolto in '{1}', ma '--jsx' non è impostato.", + "Module_Resolution_Options_6174": "Opzioni di risoluzione moduli", + "Module_name_0_matched_pattern_1_6092": "Nome del modulo: '{0}'. Criterio corrispondente: '{1}'.", + "Module_name_0_was_not_resolved_6090": "======== Il nome del modulo '{0}' non è stato risolto. ========", + "Module_name_0_was_successfully_resolved_to_1_6089": "======== Il nome del modulo '{0}' è stato risolto in '{1}'. ========", + "Module_resolution_kind_is_not_specified_using_0_6088": "Il tipo di risoluzione del modulo non è specificato. Verrà usato '{0}'.", + "Module_resolution_using_rootDirs_has_failed_6111": "La risoluzione del modulo con 'rootDirs' non è riuscita.", + "Move_to_a_new_file_95049": "Passare a un nuovo file", + "Multiple_consecutive_numeric_separators_are_not_permitted_6189": "Non sono consentiti più separatori numerici consecutivi.", + "Multiple_constructor_implementations_are_not_allowed_2392": "Non è possibile usare più implementazioni di costruttore.", + "NEWLINE_6061": "NUOVA RIGA", + "Named_property_0_of_types_1_and_2_are_not_identical_2319": "Le proprietà denominate '{0}' dei tipi '{1}' e '{2}' non sono identiche.", + "Namespace_0_has_no_exported_member_1_2694": "Lo spazio dei nomi '{0}' non contiene un membro esportato '{1}'.", + "No_base_constructor_has_the_specified_number_of_type_arguments_2508": "Nessun costruttore di base contiene il numero specificato di argomenti tipo.", + "No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2_18003": "Non sono stati trovati input nel file config '{0}'. Percorsi 'include' specificati: '{1}'. Percorsi 'exclude' specificati: '{2}'.", + "Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2_2515": "La classe non astratta '{0}' non implementa il membro astratto ereditato '{1}' della classe '{2}'.", + "Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1_2653": "L'espressione di classe non astratta non implementa il membro astratto ereditato '{0}' dalla classe '{1}'.", + "Not_all_code_paths_return_a_value_7030": "Non tutti i percorsi del codice restituiscono un valore.", + "Numeric_index_type_0_is_not_assignable_to_string_index_type_1_2413": "Il tipo di indice numerico '{0}' non è assegnabile al tipo di indice stringa '{1}'.", + "Numeric_separators_are_not_allowed_here_6188": "I separatori numerici non sono consentiti in questa posizione.", + "Object_is_of_type_unknown_2571": "L'oggetto è di tipo 'unknown'.", + "Object_is_possibly_null_2531": "L'oggetto è probabilmente 'null'.", + "Object_is_possibly_null_or_undefined_2533": "L'oggetto è probabilmente 'null' o 'undefined'.", + "Object_is_possibly_undefined_2532": "L'oggetto è probabilmente 'undefined'.", + "Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1_2353": "Il valore letterale di oggetto può specificare solo proprietà note e '{0}' non esiste nel tipo '{1}'.", + "Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_writ_2561": "Il valore letterale dell'oggetto può specificare solo proprietà note, ma '{0}' non esiste nel tipo '{1}'. Si intendeva scrivere '{2}'?", + "Object_literal_s_property_0_implicitly_has_an_1_type_7018": "La proprietà '{0}' del valore letterale di oggetto contiene implicitamente un tipo '{1}'.", + "Octal_digit_expected_1178": "È prevista la cifra ottale.", + "Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0_8017": "I tipi di valori letterali ottali devono usare la sintassi ES2015. Usare la sintassi '{0}'.", + "Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0_8018": "I valori letterali ottali non sono consentiti nell'inizializzatore di membri di enumerazioni. Usare la sintassi '{0}'.", + "Octal_literals_are_not_allowed_in_strict_mode_1121": "I valori letterali ottali non sono consentiti in modalità strict.", + "Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0_1085": "I valori letterali ottali non sono disponibili quando la destinazione è ECMAScript 5 e versioni successive. Usare la sintassi '{0}'.", + "Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement_1091": "In un'istruzione 'for...in' è consentita solo una singola dichiarazione di variabile.", + "Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement_1188": "In un'istruzione 'for...of' è consentita solo una singola dichiarazione di variabile.", + "Only_a_void_function_can_be_called_with_the_new_keyword_2350": "Con la parola chiave 'new' può essere chiamata solo una funzione void.", + "Only_ambient_modules_can_use_quoted_names_1035": "I nomi delimitati si possono usare solo nei moduli di ambiente.", + "Only_amd_and_system_modules_are_supported_alongside_0_6082": "Unitamente a --{0} sono supportati solo i moduli 'amd' e 'system'.", + "Only_emit_d_ts_declaration_files_6014": "Crea solo i file di dichiarazione '.d.ts'.", + "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002": "Nella clausola 'extends' di una classe sono attualmente supportati solo identificatori/nomi qualificati con argomenti tipo facoltativi.", + "Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword_2340": "Con la parola chiave 'super' è possibile accedere solo ai metodi pubblico e protetto della classe di base.", + "Operator_0_cannot_be_applied_to_types_1_and_2_2365": "Non è possibile applicare l'operatore '{0}' ai tipi '{1}' e '{2}'.", + "Option_0_can_only_be_specified_in_tsconfig_json_file_6064": "L'opzione '{0}' può essere specificata solo nel file 'tsconfig.json'.", + "Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided_5051": "L'opzione '{0}' può essere usata solo quando si specifica l'opzione '--inlineSourceMap' o '--sourceMap'.", + "Option_0_cannot_be_specified_with_option_1_5053": "Non è possibile specificare l'opzione '{0}' insieme all'opzione '{1}'.", + "Option_0_cannot_be_specified_without_specifying_option_1_5052": "Non è possibile specificare l'opzione '{0}' senza l'opzione '{1}'.", + "Option_0_cannot_be_specified_without_specifying_option_1_or_option_2_5069": "Non è possibile specificare l'opzione '{0}' senza l'opzione'{1}' o '{2}'.", + "Option_0_should_have_array_of_strings_as_a_value_6103": "Il valore dell'opzione '{0}' deve essere una matrice di stringhe.", + "Option_build_must_be_the_first_command_line_argument_6369": "L'opzione '--build' deve essere il primo argomento della riga di comando.", + "Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES_5047": "L'opzione 'isolatedModules' può essere usata solo quando si specifica l'opzione '--module' oppure il valore dell'opzione 'target' è 'ES2015' o maggiore.", + "Option_paths_cannot_be_used_without_specifying_baseUrl_option_5060": "Non è possibile usare l'opzione 'paths' senza specificare l'opzione '--baseUrl'.", + "Option_project_cannot_be_mixed_with_source_files_on_a_command_line_5042": "Non è possibile combinare l'opzione 'project' con file di origine in una riga di comando.", + "Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070": "Non è possibile specificare l'opzione '--resolveJsonModule' senza la strategia di risoluzione del modulo 'node'.", + "Options_0_and_1_cannot_be_combined_6370": "Non è possibile combinare le opzioni '{0}' e '{1}'.", + "Options_Colon_6027": "Opzioni:", + "Output_directory_for_generated_declaration_files_6166": "Directory di output per i file di dichiarazione generati.", + "Output_file_0_from_project_1_does_not_exist_6309": "Il file di output '{0}' del progetto '{1}' non esiste", + "Output_file_0_has_not_been_built_from_source_file_1_6305": "Il file di output '{0}' non è stato compilato dal file di origine '{1}'.", + "Overload_signature_is_not_compatible_with_function_implementation_2394": "La firma di overload non è compatibile con l'implementazione di funzione.", + "Overload_signatures_must_all_be_abstract_or_non_abstract_2512": "Le firme di overload devono essere tutte astratte o tutte non astratte.", + "Overload_signatures_must_all_be_ambient_or_non_ambient_2384": "Le firme di overload devono essere tutte di ambiente o non di ambiente.", + "Overload_signatures_must_all_be_exported_or_non_exported_2383": "Le firme di overload devono essere tutte esportate o tutte non esportate.", + "Overload_signatures_must_all_be_optional_or_required_2386": "Le firme di overload devono essere tutte facoltative o obbligatorie.", + "Overload_signatures_must_all_be_public_private_or_protected_2385": "Le firme di overload devono essere tutte pubbliche, private o protette.", + "Parameter_0_cannot_be_referenced_in_its_initializer_2372": "Non è possibile fare riferimento al parametro '{0}' nel relativo inizializzatore.", + "Parameter_0_implicitly_has_an_1_type_7006": "Il parametro '{0}' contiene implicitamente un tipo '{1}'.", + "Parameter_0_is_not_in_the_same_position_as_parameter_1_1227": "Il parametro '{0}' non si trova nella stessa posizione del parametro '{1}'.", + "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4066": "Il parametro '{0}' della firma di chiamata dell'interfaccia esportata contiene o usa il nome '{1}' del modulo privato '{2}'.", + "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4067": "Il parametro '{0}' della firma di chiamata dell'interfaccia esportata contiene o usa il nome privato '{1}'.", + "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_can_4061": "Il parametro '{0}' del costruttore della classe esportata contiene o usa il nome '{1}' del modulo esterno {2} ma non può essere rinominato.", + "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2_4062": "Il parametro '{0}' del costruttore della classe esportata contiene o usa il nome '{1}' del modulo privato '{2}'.", + "Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1_4063": "Il parametro '{0}' del costruttore della classe esportata contiene o usa il nome privato '{1}'.", + "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_mod_4064": "Il parametro '{0}' della firma del costruttore dell'interfaccia esportata contiene o usa il nome '{1}' del modulo privato '{2}'.", + "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4065": "Il parametro '{0}' della firma del costruttore dell'interfaccia esportata contiene o usa il nome privato '{1}'.", + "Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4076": "Il parametro '{0}' della funzione esportata contiene o usa il nome '{1}' del modulo esterno {2} ma non può essere rinominato.", + "Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2_4077": "Il parametro '{0}' della funzione esportata contiene o usa il nome '{1}' del modulo privato '{2}'.", + "Parameter_0_of_exported_function_has_or_is_using_private_name_1_4078": "Il parametro '{0}' della funzione esportata contiene o usa il nome privato '{1}'.", + "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4091": "Il parametro '{0}' della firma dell'indice dell'interfaccia esportata contiene o usa il nome '{1}' del modulo privato '{2}'.", + "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1_4092": "Il parametro '{0}' della firma dell'indice dell'interfaccia esportata contiene o usa il nome privato '{1}'.", + "Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4074": "Il parametro '{0}' del metodo dell'interfaccia esportata contiene o usa il nome '{1}' del modulo privato '{2}'.", + "Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4075": "Il parametro '{0}' del metodo dell'interfaccia esportata contiene o usa il nome privato '{1}'.", + "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_c_4071": "Il parametro '{0}' del metodo pubblico della classe esportata contiene o usa il nome '{1}' del modulo esterno {2} ma non può essere rinominato.", + "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4072": "Il parametro '{0}' del metodo pubblico della classe esportata contiene o usa il nome '{1}' del modulo privato '{2}'.", + "Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4073": "Il parametro '{0}' del metodo pubblico della classe esportata contiene o usa il nome privato '{1}'.", + "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module__4068": "Il parametro '{0}' del metodo statico pubblico della classe esportata contiene o usa il nome '{1}' del modulo esterno {2} ma non può essere rinominato.", + "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4069": "Il parametro '{0}' del metodo statico pubblico della classe esportata contiene o usa il nome '{1}' del modulo privato '{2}'.", + "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4070": "Il parametro '{0}' del metodo statico pubblico della classe esportata contiene o usa il nome privato '{1}'.", + "Parameter_cannot_have_question_mark_and_initializer_1015": "Il parametro non può contenere il punto interrogativo e l'inizializzatore.", + "Parameter_declaration_expected_1138": "È prevista la dichiarazione di parametro.", + "Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2_4036": "Il tipo di parametro del setter pubblico '{0}' della classe esportata contiene o usa il nome '{1}' del modulo privato '{2}'.", + "Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_private_name_1_4037": "Il tipo di parametro del setter pubblico '{0}' della classe esportata contiene o usa il nome privato '{1}'.", + "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_name_1_from_private_mod_4034": "Il tipo di parametro del setter statico pubblico '{0}' della classe esportata contiene o usa il nome '{1}' del modulo privato '{2}'.", + "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1_4035": "Il tipo di parametro del setter statico pubblico '{0}' della classe esportata contiene o usa il nome privato '{1}'.", + "Parse_in_strict_mode_and_emit_use_strict_for_each_source_file_6141": "Esegue l'analisi in modalità strict e crea la direttiva \"use strict\" per ogni file di origine.", + "Pattern_0_can_have_at_most_one_Asterisk_character_5061": "Il criterio '{0}' deve contenere al massimo un carattere '*'.", + "Prefix_0_with_an_underscore_90025": "Anteporre un carattere di sottolineatura a '{0}'", + "Prefix_all_unused_declarations_with_where_possible_95025": "Aggiungere a tutte le dichiarazioni non usate il prefisso '_', laddove possibile", + "Print_names_of_files_part_of_the_compilation_6155": "Stampa i nomi dei file che fanno parte della compilazione.", + "Print_names_of_generated_files_part_of_the_compilation_6154": "Stampa i nomi dei file generati che fanno parte della compilazione.", + "Print_the_compiler_s_version_6019": "Stampa la versione del compilatore.", + "Print_this_message_6017": "Stampa questo messaggio.", + "Project_0_can_t_be_built_because_its_dependency_1_has_errors_6363": "Non è possibile compilare il progetto '{0}' perché la dipendenza '{1}' contiene errori", + "Project_0_is_out_of_date_because_its_dependency_1_is_out_of_date_6353": "Il progetto '{0}' non è aggiornato perché la dipendenza '{1}' non è aggiornata", + "Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2_6350": "Il progetto '{0}' non è aggiornato perché l'output meno recente '{1}' è meno recente dell'input più recente '{2}'", + "Project_0_is_out_of_date_because_output_file_1_does_not_exist_6352": "Il progetto '{0}' non è aggiornato perché il file di output '{1}' non esiste", + "Project_0_is_up_to_date_6361": "Il progetto '{0}' è aggiornato", + "Project_0_is_up_to_date_because_newest_input_1_is_older_than_oldest_output_2_6351": "Il progetto '{0}' è aggiornato perché l'input più recente '{1}' è meno recente dell'output meno recente '{2}'", + "Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies_6354": "Il progetto '{0}' è aggiornato con i file con estensione d.ts delle relative dipendenze", + "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202": "I riferimenti al progetto non possono formare un grafico circolare. Ciclo rilevato: {0}", + "Projects_in_this_build_Colon_0_6355": "Progetti in questa compilazione: {0}", + "Projects_to_reference_6300": "Progetti cui fare riferimento", + "Property_0_does_not_exist_on_const_enum_1_2479": "La proprietà '{0}' non esiste nell'enumerazione 'const' '{1}'.", + "Property_0_does_not_exist_on_type_1_2339": "La proprietà '{0}' non esiste nel tipo '{1}'.", + "Property_0_does_not_exist_on_type_1_Did_you_forget_to_use_await_2570": "La proprietà '{0}' non esiste nel tipo '{1}'. Si è dimenticato di usare 'await'?", + "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551": "La proprietà '{0}' non esiste nel tipo '{1}'. Si intendeva '{2}'?", + "Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1_2546": "La proprietà '{0}' include dichiarazioni in conflitto ed è inaccessibile nel tipo '{1}'.", + "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor_2564": "La proprietà '{0}' non include alcun inizializzatore e non viene assolutamente assegnata nel costruttore.", + "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033": "La proprietà '{0}' contiene implicitamente il tipo 'any', perché nella relativa funzione di accesso get manca un'annotazione di tipo restituito.", + "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032": "La proprietà '{0}' contiene implicitamente il tipo 'any', perché nella relativa funzione di accesso set manca un'annotazione di tipo di parametro.", + "Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2_2416": "La proprietà '{0}' nel tipo '{1}' non è assegnabile alla stessa proprietà nel tipo di base '{2}'.", + "Property_0_in_type_1_is_not_assignable_to_type_2_2603": "La proprietà '{0}' nel tipo '{1}' non è assegnabile al tipo '{2}'.", + "Property_0_is_declared_but_its_value_is_never_read_6138": "La proprietà '{0}' è dichiarata, ma il suo valore non viene mai letto.", + "Property_0_is_incompatible_with_index_signature_2530": "La proprietà '{0}' non è compatibile con la firma dell'indice.", + "Property_0_is_missing_in_type_1_2324": "Nel tipo '{1}' manca la proprietà '{0}'.", + "Property_0_is_optional_in_type_1_but_required_in_type_2_2327": "La proprietà '{0}' è facoltativa nel tipo '{1}', ma obbligatoria nel tipo '{2}'.", + "Property_0_is_private_and_only_accessible_within_class_1_2341": "La proprietà '{0}' è privata e accessibile solo all'interno della classe '{1}'.", + "Property_0_is_private_in_type_1_but_not_in_type_2_2325": "La proprietà '{0}' è privata nel tipo '{1}', ma non nel tipo '{2}'.", + "Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1_2446": "La proprietà '{0}' è protetta e accessibile solo tramite un'istanza della classe '{1}'.", + "Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses_2445": "La proprietà '{0}' è protetta e accessibile solo all'interno della classe '{1}' e delle relative sottoclassi.", + "Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2_2443": "La proprietà '{0}' è protetta, ma il tipo '{1}' non è una classe derivata da '{2}'.", + "Property_0_is_protected_in_type_1_but_public_in_type_2_2444": "La proprietà '{0}' è protetta nel tipo '{1}', ma è pubblica non nel tipo '{2}'.", + "Property_0_is_used_before_being_assigned_2565": "La proprietà '{0}' viene usata prima dell'assegnazione.", + "Property_0_of_JSX_spread_attribute_is_not_assignable_to_target_property_2606": "La proprietà '{0}' dell'attributo spread JSX non è assegnabile alla proprietà di destinazione.", + "Property_0_of_exported_class_expression_may_not_be_private_or_protected_4094": "La proprietà '{0}' dell'espressione di classe esportata potrebbe essere non privata o protetta.", + "Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4032": "La proprietà '{0}' dell'interfaccia esportata contiene o usa il nome '{1}' del modulo privato '{2}'.", + "Property_0_of_exported_interface_has_or_is_using_private_name_1_4033": "La proprietà '{0}' dell'interfaccia esportata contiene o usa il nome privato '{1}'.", + "Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2_2412": "La proprietà '{0}' del tipo '{1}' non è assegnabile a un tipo di indice numerico '{2}'.", + "Property_0_of_type_1_is_not_assignable_to_string_index_type_2_2411": "La proprietà '{0}' del tipo '{1}' non è assegnabile a un tipo di indice stringa '{2}'.", + "Property_assignment_expected_1136": "È prevista l'assegnazione di proprietà.", + "Property_destructuring_pattern_expected_1180": "È previsto il criterio di destrutturazione della proprietà.", + "Property_or_signature_expected_1131": "È prevista la proprietà o la firma.", + "Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_li_1328": "Il valore della proprietà può essere solo un valore letterale stringa, un valore letterale numerico, 'true', 'false', 'null', un valore letterale di oggetto o un valore letterale di matrice.", + "Provide_full_support_for_iterables_in_for_of_spread_and_destructuring_when_targeting_ES5_or_ES3_6179": "Fornisce supporto completo per elementi iterabili in 'for-of', spread e destrutturazione quando la destinazione è 'ES5' o 'ES3'.", + "Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4098": "Il metodo pubblico '{0}' della classe esportata ha o usa il nome '{1}' del modulo esterno {2} ma non può essere rinominato.", + "Public_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4099": "Il metodo pubblico '{0}' della classe esportata ha o usa il nome '{1}' del modulo privato '{2}'.", + "Public_method_0_of_exported_class_has_or_is_using_private_name_1_4100": "Il metodo pubblico '{0}' della classe esportata ha o usa il nome privato '{1}'.", + "Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_name_4029": "La proprietà pubblica '{0}' della classe esportata contiene o usa il nome '{1}' del modulo esterno {2} ma non può essere rinominata.", + "Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4030": "La proprietà pubblica '{0}' della classe esportata contiene o usa il nome '{1}' del modulo privato '{2}'.", + "Public_property_0_of_exported_class_has_or_is_using_private_name_1_4031": "La proprietà pubblica '{0}' della classe esportata contiene o usa il nome privato '{1}'.", + "Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_4095": "Il metodo statico pubblico '{0}' della classe esportata contiene o usa il nome '{1}' del modulo esterno {2} ma non può essere rinominato.", + "Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4096": "Il metodo statico pubblico '{0}' della classe esportata ha o usa il nome '{1}' del modulo privato '{2}'.", + "Public_static_method_0_of_exported_class_has_or_is_using_private_name_1_4097": "Il metodo statico pubblico '{0}' della classe esportata ha o usa il nome privato '{1}'.", + "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot__4026": "La proprietà statica pubblica '{0}' della classe esportata contiene o usa il nome '{1}' del modulo esterno {2} ma non può essere rinominata.", + "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4027": "La proprietà statica pubblica '{0}' della classe esportata contiene o usa il nome '{1}' del modulo privato '{2}'.", + "Public_static_property_0_of_exported_class_has_or_is_using_private_name_1_4028": "La proprietà statica pubblica '{0}' della classe esportata contiene o usa il nome privato '{1}'.", + "Raise_error_on_expressions_and_declarations_with_an_implied_any_type_6052": "Genera un errore in caso di espressioni o dichiarazioni con tipo 'any' implicito.", + "Raise_error_on_this_expressions_with_an_implied_any_type_6115": "Genera un errore in caso di espressioni 'this con un tipo 'any' implicito.", + "Redirect_output_structure_to_the_directory_6006": "Reindirizza la struttura di output alla directory.", + "Referenced_project_0_must_have_setting_composite_Colon_true_6306": "Il progetto di riferimento '{0}' deve includere l'impostazione \"composite\": true.", + "Remove_all_unreachable_code_95051": "Rimuovere tutto il codice non eseguibile", + "Remove_all_unused_labels_95054": "Rimuovere tutte le etichette inutilizzate", + "Remove_braces_from_arrow_function_95060": "Rimuovere le parentesi graffe dalla funzione arrow", + "Remove_declaration_for_Colon_0_90004": "Rimuovere la dichiarazione per '{0}'", + "Remove_destructuring_90009": "Rimuovere la destrutturazione", + "Remove_import_from_0_90005": "Rimuovere l'importazione da '{0}'", + "Remove_unreachable_code_95050": "Rimuovere il codice non eseguibile", + "Remove_unused_label_95053": "Rimuovere l'etichetta inutilizzata", + "Remove_variable_statement_90010": "Rimuovere l'istruzione di variabile", + "Replace_import_with_0_95015": "Sostituire l'importazione con '{0}'.", + "Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "Segnala l'errore quando non tutti i percorsi del codice nella funzione restituiscono un valore.", + "Report_errors_for_fallthrough_cases_in_switch_statement_6076": "Segnala errori per i casi di fallthrough nell'istruzione switch.", + "Report_errors_in_js_files_8019": "Segnala gli errori presenti nei file con estensione js.", + "Report_errors_on_unused_locals_6134": "Segnala errori relativi a variabili locali non usate.", + "Report_errors_on_unused_parameters_6135": "Segnala errori relativi a parametri non usati.", + "Required_type_parameters_may_not_follow_optional_type_parameters_2706": "I parametri di tipo obbligatori potrebbero non seguire i parametri di tipo facoltativi.", + "Resolution_for_module_0_was_found_in_cache_from_location_1_6147": "La risoluzione per il modulo '{0}' è stata trovata nella cache dal percorso '{1}'.", + "Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols_6195": "Risolvere 'keyof' solo in nomi di proprietà con valori stringa (senza numeri o simboli).", + "Resolving_from_node_modules_folder_6118": "Risoluzione dalla cartella node_modules...", + "Resolving_module_0_from_1_6086": "======== Risoluzione del modulo '{0}' da '{1}'. ========", + "Resolving_module_name_0_relative_to_base_url_1_2_6094": "Verrà eseguita la risoluzione del nome del modulo '{0}' relativo all'URL di base '{1}' - '{2}'.", + "Resolving_real_path_for_0_result_1_6130": "Risoluzione del percorso reale per '{0}'. Risultato: '{1}'.", + "Resolving_type_reference_directive_0_containing_file_1_root_directory_2_6116": "======== Risoluzione della direttiva '{0}' del riferimento al tipo contenente il file '{1}' con directory radice '{2}'. ========", + "Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set_6123": "======== Risoluzione della direttiva '{0}' del riferimento al tipo contenente il file '{1}' e directory radice non impostata. ========", + "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1_6127": "======== Risoluzione della direttiva '{0}' del riferimento al tipo contenente il file non impostato con directory radice '{1}'. ========", + "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set_6128": "======== Risoluzione della direttiva '{0}' del riferimento al tipo contenente il file non impostato con directory radice non impostata. ========", + "Resolving_using_primary_search_paths_6117": "Risoluzione con percorsi di ricerca primaria...", + "Resolving_with_primary_search_path_0_6121": "La risoluzione verrà eseguita con il percorso di ricerca primaria '{0}'.", + "Rest_parameter_0_implicitly_has_an_any_type_7019": "Il parametro rest '{0}' contiene implicitamente un tipo 'any[]'.", + "Rest_types_may_only_be_created_from_object_types_2700": "È possibile creare tipi rest solo da tipi di oggetto.", + "Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4046": "Il tipo restituito della firma di chiamata dell'interfaccia esportata contiene o usa il nome '{0}' del modulo privato '{1}'.", + "Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0_4047": "Il tipo restituito della firma di chiamata dell'interfaccia esportata contiene o usa il nome privato '{0}'.", + "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_mod_4044": "Il tipo restituito della firma del costruttore dell'interfaccia esportata contiene o usa il nome '{0}' del modulo privato '{1}'.", + "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0_4045": "Il tipo restituito della firma del costruttore dell'interfaccia esportata contiene o usa il nome privato '{0}'.", + "Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class_2409": "Il tipo restituito della firma del costruttore deve essere assegnabile al tipo di istanza della classe.", + "Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named_4058": "Il tipo restituito della funzione esportata contiene o usa il nome '{0}' del modulo esterno {1} ma non può essere rinominato.", + "Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1_4059": "Il tipo restituito della funzione esportata contiene o usa il nome '{0}' del modulo privato '{1}'.", + "Return_type_of_exported_function_has_or_is_using_private_name_0_4060": "Il tipo restituito della funzione esportata contiene o usa il nome privato '{0}'.", + "Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4048": "Il tipo restituito della firma dell'indice dell'interfaccia esportata contiene o usa il nome '{0}' del modulo privato '{1}'.", + "Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0_4049": "Il tipo restituito della firma dell'indice dell'interfaccia esportata contiene o usa il nome privato '{0}'.", + "Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4056": "Il tipo restituito del metodo dell'interfaccia esportata contiene o usa il nome '{0}' del modulo privato '{1}'.", + "Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0_4057": "Il tipo restituito del metodo dell'interfaccia esportata contiene o usa il nome privato '{0}'.", + "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_4041": "Il tipo restituito del getter pubblico '{0}' della classe esportata contiene o usa il nome '{1}' del modulo esterno {2}, ma non può essere rinominato.", + "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2_4042": "Il tipo restituito del getter pubblico '{0}' della classe esportata contiene o usa il nome '{1}' del modulo privato '{2}'.", + "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_private_name_1_4043": "Il tipo restituito del getter pubblico '{0}' della classe esportata contiene o usa il nome privato '{1}'.", + "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_c_4053": "Il tipo restituito del metodo pubblico della classe esportata contiene o usa il nome '{0}' del modulo esterno {1} ma non può essere rinominato.", + "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4054": "Il tipo restituito del metodo pubblico della classe esportata contiene o usa il nome '{0}' del modulo privato '{1}'.", + "Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0_4055": "Il tipo restituito del metodo pubblico della classe esportata contiene o usa il nome privato '{0}'.", + "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_external_modul_4038": "Il tipo restituito del getter di proprietà pubblico '{0}' della classe esportata contiene o usa il nome '{1}' del modulo esterno '{2}', ma non può essere rinominato.", + "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_4039": "Il tipo restituito del getter di proprietà pubblico '{0}' della classe esportata contiene o usa il nome '{1}' del modulo privato '{2}'.", + "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_private_name_1_4040": "Il tipo restituito del getter statico pubblico '{0}' della classe esportata contiene o usa il nome privato '{1}'.", + "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module__4050": "Il tipo restituito del metodo statico pubblico della classe esportata contiene o usa il nome '{0}' del modulo esterno {1} ma non può essere rinominato.", + "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4051": "Il tipo restituito del metodo statico pubblico della classe esportata contiene o usa il nome '{0}' del modulo privato '{1}'.", + "Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0_4052": "Il tipo restituito del metodo statico pubblico della classe esportata contiene o usa il nome privato '{0}'.", + "Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program_6184": "Le risoluzioni dei moduli con origine in '{0}' verranno riutilizzate perché sono invariate rispetto al vecchio programma.", + "Reusing_resolution_of_module_0_to_file_1_from_old_program_6183": "La risoluzione del modulo '{0}' del vecchio programma verrà riutilizzata nel file '{1}'.", + "Rewrite_all_as_indexed_access_types_95034": "Riscrivere tutti come tipi di accesso indicizzati", + "Rewrite_as_the_indexed_access_type_0_90026": "Riscrivere come tipo di accesso indicizzato '{0}'", + "Root_directory_cannot_be_determined_skipping_primary_search_paths_6122": "Non è possibile determinare la directory radice. I percorsi di ricerca primaria verranno ignorati.", + "STRATEGY_6039": "STRATEGIA", + "Scoped_package_detected_looking_in_0_6182": "Il pacchetto con ambito è stato rilevato. Verrà eseguita una ricerca in '{0}'", + "Setters_cannot_return_a_value_2408": "I setter non possono restituire un valore.", + "Show_all_compiler_options_6169": "Mostra tutte le opzioni del compilatore.", + "Show_diagnostic_information_6149": "Mostra le informazioni di diagnostica.", + "Show_verbose_diagnostic_information_6150": "Mostra le informazioni di diagnostica dettagliate.", + "Show_what_would_be_built_or_deleted_if_specified_with_clean_6367": "Mostra gli elementi che vengono compilati (o eliminati, se specificati con l'opzione '--clean')", + "Signature_0_must_be_a_type_predicate_1224": "La firma '{0}' deve essere un predicato di tipo.", + "Skip_type_checking_of_declaration_files_6012": "Ignora il controllo del tipo dei file di dichiarazione.", + "Skipping_build_of_project_0_because_its_dependency_1_has_errors_6362": "La compilazione del progetto '{0}' verrà ignorata perché la dipendenza '{1}' contiene errori", + "Skipping_clean_because_not_all_projects_could_be_located_6371": "La pulizia verrà ignorata perché non è stato possibile individuare tutti i progetti", + "Source_Map_Options_6175": "Opzioni per mapping di origine", + "Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature_2382": "La firma di overload specializzata non è assegnabile a una firma non specializzata.", + "Specifier_of_dynamic_import_cannot_be_spread_element_1325": "L'identificatore dell'importazione dinamica non può essere l'elemento spread.", + "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_or_ESNEXT_6015": "Specificare la versione di destinazione di ECMAScript: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018' o 'ESNEXT'.", + "Specify_JSX_code_generation_Colon_preserve_react_native_or_react_6080": "Specifica la generazione del codice JSX: 'preserve', 'react-native' o 'react'.", + "Specify_library_files_to_be_included_in_the_compilation_6079": "Specificare i file di libreria da includere nella compilazione.", + "Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext_6016": "Consente di specificare il tipo di generazione del codice del modulo, ovvero 'none', commonjs', 'amd', 'system', 'umd', 'es2015' o 'ESNext'.", + "Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6_6069": "Specifica la strategia di risoluzione del modulo: 'node' (Node.js) o 'classic' (TypeScript prima della versione 1.6).", + "Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h_6146": "Consente di specificare la funzione della factory JSX da usare quando la destinazione è la creazione JSX 'react', ad esempio 'React.createElement' o 'h'.", + "Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix_6060": "Specifica la sequenza di fine riga da usare per la creazione dei file, ovvero 'CRLF' (in DOS) o 'LF' (in UNIX).", + "Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations_6004": "Specifica il percorso in cui il debugger deve trovare i file TypeScript invece dei percorsi di origine.", + "Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations_6003": "Specifica il percorso in cui il debugger deve trovare i file map invece dei percorsi generati.", + "Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir_6058": "Specifica la directory radice dei file di input. Usare per controllare la struttura della directory di output con --outDir.", + "Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher_2472": "L'operatore Spread in espressioni 'new' è disponibile solo se destinato a ECMAScript 5 e versioni successive.", + "Spread_types_may_only_be_created_from_object_types_2698": "È possibile creare tipi spread solo da tipi di oggetto.", + "Starting_compilation_in_watch_mode_6031": "Avvio della compilazione in modalità espressione di controllo...", + "Statement_expected_1129": "È prevista l'istruzione.", + "Statements_are_not_allowed_in_ambient_contexts_1036": "Le istruzioni non sono consentite in contesti di ambiente.", + "Static_members_cannot_reference_class_type_parameters_2302": "I membri statici non possono fare riferimento a parametri di tipo classe.", + "Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1_2699": "La proprietà statica '{0}' è in conflitto con la proprietà predefinita 'Function.{0}' della funzione del costruttore '{1}'.", + "Strict_Type_Checking_Options_6173": "Opzioni per controlli del tipo strict", + "String_literal_expected_1141": "È previsto un valore letterale stringa.", + "String_literal_with_double_quotes_expected_1327": "È previsto un valore letterale stringa con virgolette doppie.", + "Stylize_errors_and_messages_using_color_and_context_experimental_6073": "Applica stili a errori e messaggi usando colore e contesto (sperimentale).", + "Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_t_2717": "Le dichiarazioni di proprietà successive devono essere dello stesso tipo. La proprietà '{0}' deve essere di tipo '{1}', ma qui è di tipo '{2}'.", + "Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_t_2403": "Le dichiarazioni di variabili successive devono essere dello stesso tipo. La variabile '{0}' deve essere di tipo '{1}', mentre è di tipo '{2}'.", + "Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2_5064": "Il tipo della sostituzione '{0}' per il criterio '{1}' non è corretto. È previsto 'string', ma è stato ottenuto '{2}'.", + "Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character_5062": "La sostituzione '{0}' nel criterio '{1}' può contenere al massimo un carattere '*'.", + "Substitutions_for_pattern_0_should_be_an_array_5063": "Le sostituzioni per il criterio '{0}' devono essere una matrice.", + "Substitutions_for_pattern_0_shouldn_t_be_an_empty_array_5066": "Le sostituzioni per il criterio '{0}' non devono essere una matrice vuota.", + "Successfully_created_a_tsconfig_json_file_6071": "La creazione di un file tsconfig.json è riuscita.", + "Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors_2337": "Le chiamate super non sono consentite all'esterno di costruttori o nelle funzioni annidate all'interno di costruttori.", + "Suppress_excess_property_checks_for_object_literals_6072": "Elimina i controlli delle proprietà in eccesso per i valori letterali di oggetto.", + "Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures_6055": "Non visualizza gli errori noImplicitAny per gli oggetti di indicizzazione in cui mancano le firme dell'indice.", + "Symbol_reference_does_not_refer_to_the_global_Symbol_constructor_object_2470": "Il riferimento 'Symbol' non fa riferimento all'oggetto costruttore Symbol globale.", + "Syntax_Colon_0_6023": "Sintassi: {0}", + "The_0_operator_cannot_be_applied_to_type_symbol_2469": "Non è possibile applicare l'operatore '{0}' al tipo 'symbol'.", + "The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead_2447": "L'operatore '{0}' non è consentito per i tipi booleani. Provare a usare '{1}'.", + "The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead_2696": "Il tipo 'Object' può essere assegnato a un numero molto limitato di altri tipi. Si intendeva usare il tipo 'any'?", + "The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_stand_2496": "Non è possibile fare riferimento all'oggetto 'arguments' in una funzione arrow in ES3 e ES5. Provare a usare un'espressione di funzione standard.", + "The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_usi_2522": "Non è possibile fare riferimento all'oggetto 'arguments' in un metodo o una funzione asincrona in ES3 e ES5. Provare a usare un metodo o una funzione standard.", + "The_body_of_an_if_statement_cannot_be_the_empty_statement_1313": "Il corpo di un'istruzione 'if' non può essere l'istruzione vuota.", + "The_character_set_of_the_input_files_6163": "Set di caratteri dei file di input.", + "The_containing_function_or_module_body_is_too_large_for_control_flow_analysis_2563": "Il corpo del modulo o la funzione che contiene è troppo grande per l'analisi del flusso di controllo.", + "The_current_host_does_not_support_the_0_option_5001": "L'host corrente non supporta l'opzione '{0}'.", + "The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context_2714": "L'espressione di un'assegnazione di esportazione deve essere un identificatore o un nome completo in un contesto di ambiente.", + "The_files_list_in_config_file_0_is_empty_18002": "L'elenco 'files' nel file config '{0}' è vuoto.", + "The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback_1060": "Il primo parametro del metodo 'then' di una promessa deve essere un callback.", + "The_global_type_JSX_0_may_not_have_more_than_one_property_2608": "Il tipo globale 'JSX.{0}' non può contenere più di una proprietà.", + "The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_option_1343": "La metaproprietà 'import.meta' è consentita solo se si usa 'ESNext' per le opzioni 'target' e 'module' del compilatore.", + "The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary_2527": "Il tipo dedotto di '{0}' fa riferimento a un tipo '{1}' non accessibile. È necessaria un'annotazione di tipo.", + "The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern_2491": "La parte sinistra di un'espressione 'for...in' non può essere un criterio di destrutturazione.", + "The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation_2404": "Nella parte sinistra di un'espressione 'for...in' non è possibile usare un'annotazione di tipo.", + "The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access_2406": "La parte sinistra di un'istruzione 'for...in' deve essere una variabile o un accesso a proprietà.", + "The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any_2405": "La parte sinistra di un'espressione 'for...in' deve essere di tipo 'string' o 'any'.", + "The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation_2483": "Nella parte sinistra di un'espressione 'for...of' non è possibile usare un'annotazione di tipo.", + "The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access_2487": "La parte sinistra di un'istruzione 'for...of' deve essere una variabile o un accesso a proprietà.", + "The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type_2362": "La parte sinistra di un'operazione aritmetica deve essere di tipo 'any', 'number' o un tipo di enumerazione.", + "The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access_2364": "La parte sinistra di un'espressione di assegnazione deve essere una variabile o un accesso a proprietà.", + "The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol_2360": "La parte sinistra di un'espressione 'in' deve essere di tipo 'any', 'string', 'number' o 'symbol'.", + "The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_paramete_2358": "La parte sinistra di un'espressione 'instanceof' deve essere di tipo 'any' oppure essere un tipo di oggetto o un parametro di tipo.", + "The_locale_used_when_displaying_messages_to_the_user_e_g_en_us_6156": "Impostazioni locali usate per la visualizzazione di messaggi all'utente, ad esempio 'it-it'", + "The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files_6136": "Profondità massima delle dipendenze per la ricerca in node_modules e il caricamento dei file JavaScript.", + "The_operand_of_a_delete_operator_cannot_be_a_read_only_property_2704": "L'operando di un operatore delete non può essere una proprietà di sola lettura.", + "The_operand_of_a_delete_operator_must_be_a_property_reference_2703": "L'operando di un operatore delete deve essere un riferimento a proprietà.", + "The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access_2357": "L'operando di un operatore di incremento o decremento deve essere una variabile o un accesso a proprietà.", + "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601": "Il tipo restituito di un costruttore di elementi JSX deve restituire un tipo di oggetto.", + "The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any_1237": "Il tipo restituito di una funzione di espressione Decorator del parametro deve essere 'void' o 'any'.", + "The_return_type_of_a_property_decorator_function_must_be_either_void_or_any_1236": "Il tipo restituito di una funzione di espressione Decorator della proprietà deve essere 'void' o 'any'.", + "The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_t_1058": "Il tipo restituito di una funzione asincrona deve essere una promessa valida oppure non deve contenere un membro 'then' chiamabile.", + "The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_1064": "Il tipo restituito di un metodo o una funzione asincrona deve essere il tipo globale Promise.", + "The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_but_2407": "La parte destra di un'istruzione 'for...in' deve essere di tipo 'any' oppure essere un tipo di oggetto o un parametro di tipo, ma in questo caso il tipo è '{0}'.", + "The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type_2363": "La parte destra di un'operazione aritmetica deve essere di tipo 'any', 'number' o un tipo di enumerazione.", + "The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter_2361": "La parte destra di un'espressione 'in' deve essere di tipo 'any' oppure deve essere un tipo di oggetto o un parametro di tipo.", + "The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_F_2359": "La parte destra di un'espressione 'instanceof' deve essere di tipo 'any' o di un tipo assegnabile al tipo di interfaccia 'Function'.", + "The_specified_path_does_not_exist_Colon_0_5058": "Il percorso specificato non esiste: '{0}'.", + "The_target_of_an_assignment_must_be_a_variable_or_a_property_access_2541": "La destinazione di un'assegnazione deve essere una variabile o un accesso a proprietà.", + "The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access_2701": "La destinazione di un'assegnazione REST di oggetto deve essere una variabile o un accesso a proprietà.", + "The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1_2684": "Il contesto 'this' del tipo '{0}' non è assegnabile a quello 'this' di tipo '{1}' del metodo.", + "The_this_types_of_each_signature_are_incompatible_2685": "I tipi 'this' delle singole firme non sono compatibili.", + "The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_typ_2453": "Non è possibile dedurre l'argomento tipo per il parametro di tipo '{0}' dall'utilizzo. Provare a specificare gli argomenti tipo in modo esplicito.", + "The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value__2547": "Il tipo restituito dal metodo 'next()' di un iteratore asincrono deve essere una promessa per un tipo con una proprietà 'value'.", + "The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property_2490": "Il tipo restituito dal metodo 'next()' di un iteratore deve contenere una proprietà 'value'.", + "The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer_1189": "La dichiarazione di variabile di un'istruzione 'for...in' non può contenere un inizializzatore.", + "The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer_1190": "La dichiarazione di variabile di un'istruzione 'for...of' non può contenere un inizializzatore.", + "The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any_2410": "L'istruzione 'with' non è supportata. Il tipo di tutti i simboli in un blocco 'with' è 'any'.", + "This_constructor_function_may_be_converted_to_a_class_declaration_80002": "Questa funzione del costruttore può essere convertita in una dichiarazione di classe.", + "This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found_2354": "Con questa sintassi è richiesto un helper importato, ma il modulo '{0}' non è stato trovato.", + "This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1_2343": "Con questa sintassi è richiesto un helper importato denominato '{1}', ma il modulo '{0}' non contiene alcun membro esportato '{1}'.", + "Trailing_comma_not_allowed_1009": "La virgola finale non è consentita.", + "Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule_6153": "Esegue il transpile di ogni file in un modulo separato (simile a 'ts.transpileModule').", + "Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_mod_7035": "Provare con `npm install @types/{0}` se esiste oppure aggiungere un nuovo file di dichiarazione con estensione d.ts contenente `declare module '{0}';`", + "Trying_other_entries_in_rootDirs_6110": "Verrà effettuato un tentativo con altre voci in 'rootDirs'.", + "Trying_substitution_0_candidate_module_location_Colon_1_6093": "Verrà effettuato un tentativo con la sostituzione '{0}'. Percorso candidato del modulo: '{1}'.", + "Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2_2493": "Non è possibile assegnare il tipo di tupla '{0}' la cui lunghezza è '{1}' alla tupla la cui lunghezza è '{2}'.", + "Type_0_cannot_be_converted_to_type_1_2352": "Non è possibile convertire il tipo '{0}' nel tipo '{1}'.", + "Type_0_cannot_be_used_as_an_index_type_2538": "Non è possibile usare il tipo '{0}' come tipo di indice.", + "Type_0_cannot_be_used_to_index_type_1_2536": "Non è possibile usare il tipo '{0}' per indicizzare il tipo '{1}'.", + "Type_0_does_not_satisfy_the_constraint_1_2344": "Il tipo '{0}' non soddisfa il vincolo '{1}'.", + "Type_0_has_no_matching_index_signature_for_type_1_2537": "Nel tipo '{0}' non esiste alcuna firma dell'indice corrispondente per il tipo '{1}'.", + "Type_0_has_no_properties_in_common_with_type_1_2559": "Il tipo '{0}' non ha proprietà in comune con il tipo '{1}'.", + "Type_0_has_no_property_1_2460": "Il tipo '{0}' non contiene la proprietà '{1}'.", + "Type_0_has_no_property_1_and_no_string_index_signature_2459": "Il tipo '{0}' non contiene la proprietà '{1}' né la firma dell'indice di tipo stringa.", + "Type_0_is_not_a_constructor_function_type_2507": "Il tipo '{0}' non è un tipo di funzione del costruttore.", + "Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Prom_1055": "Il tipo '{0}' non è un tipo restituito di funzione asincrona valido in ES5/ES3 perché non fa riferimento a un valore di costruttore compatibile con Promise.", + "Type_0_is_not_an_array_type_2461": "Il tipo '{0}' non è un tipo matrice.", + "Type_0_is_not_an_array_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators_2568": "Il tipo '{0}' non è un tipo matrice. Usare l'opzione del compilatore '--downlevelIteration' per consentire l'iterazione degli iteratori.", + "Type_0_is_not_an_array_type_or_a_string_type_2495": "Il tipo '{0}' non è un tipo matrice o stringa.", + "Type_0_is_not_an_array_type_or_a_string_type_Use_compiler_option_downlevelIteration_to_allow_iterati_2569": "Il tipo '{0}' non è un tipo matrice o stringa. Usare l'opzione del compilatore '--downlevelIteration' per consentire l'iterazione degli iteratori.", + "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549": "Il tipo '{0}' non è un tipo matrice o stringa oppure non contiene un metodo '[Symbol.iterator]()' che restituisce un iteratore.", + "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548": "Il tipo '{0}' non è un tipo matrice oppure non contiene un metodo '[Symbol.iterator]()' che restituisce un iteratore.", + "Type_0_is_not_assignable_to_type_1_2322": "Il tipo '{0}' non è assegnabile al tipo '{1}'.", + "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_2719": "Il tipo '{0}' non è assegnabile al tipo '{1}'. Sono presenti due tipi diversi con questo nome, che però non sono correlati.", + "Type_0_is_not_comparable_to_type_1_2678": "Il tipo '{0}' non è confrontabile con il tipo '{1}'.", + "Type_0_is_not_generic_2315": "Il tipo '{0}' non è generico.", + "Type_0_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator_2504": "Il tipo '{0}' deve contenere un metodo '[Symbol.asyncIterator]()' che restituisce un iteratore asincrono.", + "Type_0_must_have_a_Symbol_iterator_method_that_returns_an_iterator_2488": "Il tipo '{0}' deve contenere un metodo '[Symbol.iterator]()' che restituisce un iteratore.", + "Type_0_provides_no_match_for_the_signature_1_2658": "Il tipo '{0}' non fornisce corrispondenze per la firma '{1}'.", + "Type_0_recursively_references_itself_as_a_base_type_2310": "Il tipo '{0}' fa riferimento a se stesso in modo ricorsivo come tipo di base.", + "Type_alias_0_circularly_references_itself_2456": "L'alias di tipo '{0}' contiene un riferimento circolare a se stesso.", + "Type_alias_name_cannot_be_0_2457": "Il nome dell'alias di tipo non può essere '{0}'.", + "Type_annotation_cannot_appear_on_a_constructor_declaration_1093": "L'annotazione di tipo non può essere inclusa in una dichiarazione di costruttore.", + "Type_argument_candidate_1_is_not_a_valid_type_argument_because_it_is_not_a_supertype_of_candidate_0_2455": "Il candidato '{1}' non è un argomento tipo valido perché non è un supertipo del candidato '{0}'.", + "Type_argument_expected_1140": "È previsto l'argomento tipo.", + "Type_argument_list_cannot_be_empty_1099": "L'elenco degli argomenti tipo non può essere vuoto.", + "Type_arguments_cannot_be_used_here_1342": "Non è possibile usare argomenti tipo in questa posizione.", + "Type_declaration_files_to_be_included_in_compilation_6124": "File della dichiarazione di tipo da includere nella compilazione.", + "Type_expected_1110": "È previsto il tipo.", + "Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method_1062": "Il tipo viene usato come riferimento diretto o indiretto nel callback di fulfillment del relativo metodo 'then'.", + "Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member_1320": "Il tipo dell'operando 'await' deve essere una promessa valida oppure non deve contenere un membro 'then' chiamabile.", + "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322": "Il tipo di elementi iterati di un operando 'yield*' deve essere una promessa valida oppure non deve contenere un membro 'then' chiamabile.", + "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321": "Il tipo dell'operando 'yield' in un generatore asincrono deve essere una promessa valida oppure non deve contenere un membro 'then' chiamabile.", + "Type_parameter_0_has_a_circular_constraint_2313": "Il parametro di tipo '{0}' contiene un vincolo circolare.", + "Type_parameter_0_has_a_circular_default_2716": "Il parametro di tipo '{0}' contiene un'impostazione predefinita circolare.", + "Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4008": "Il parametro di tipo '{0}' della firma di chiamata dell'interfaccia esportata contiene o usa il nome privato '{1}'.", + "Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4006": "Il parametro di tipo '{0}' della firma del costruttore dell'interfaccia esportata contiene o usa il nome privato '{1}'.", + "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002": "Il parametro di tipo '{0}' della classe esportata contiene o usa il nome privato '{1}'.", + "Type_parameter_0_of_exported_function_has_or_is_using_private_name_1_4016": "Il parametro di tipo '{0}' della funzione esportata contiene o usa il nome privato '{1}'.", + "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004": "Il parametro di tipo '{0}' dell'interfaccia esportata contiene o usa il nome privato '{1}'.", + "Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1_4083": "Il parametro di tipo '{0}' dell'alias di tipo esportato contiene o usa il nome privato '{1}'.", + "Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4014": "Il parametro di tipo '{0}' del metodo dell'interfaccia esportata contiene o usa il nome privato '{1}'.", + "Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4012": "Il parametro di tipo '{0}' del metodo pubblico della classe esportata contiene o usa il nome privato '{1}'.", + "Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4010": "Il parametro di tipo '{0}' del metodo statico pubblico della classe esportata contiene o usa il nome privato '{1}'.", + "Type_parameter_declaration_expected_1139": "È prevista la dichiarazione di parametro di tipo.", + "Type_parameter_list_cannot_be_empty_1098": "L'elenco dei parametri di tipo non può essere vuoto.", + "Type_parameter_name_cannot_be_0_2368": "Il nome del parametro di tipo non può essere '{0}'.", + "Type_parameters_cannot_appear_on_a_constructor_declaration_1092": "I parametri di tipo non possono essere inclusi in una dichiarazione di costruttore.", + "Type_predicate_0_is_not_assignable_to_1_1226": "Il predicato di tipo '{0}' non è assegnabile a '{1}'.", + "Type_reference_directive_0_was_not_resolved_6120": "======== La direttiva '{0}' del riferimento al tipo non è stata risolta. ========", + "Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2_6119": "======== La direttiva '{0}' del riferimento al tipo è stata risolta in '{1}'. Primaria: {2}. ========", + "Types_have_separate_declarations_of_a_private_property_0_2442": "I tipi contengono dichiarazioni separate di una proprietà privata '{0}'.", + "Types_of_parameters_0_and_1_are_incompatible_2328": "I tipi dei parametri '{0}' e '{1}' sono incompatibili.", + "Types_of_property_0_are_incompatible_2326": "I tipi della proprietà '{0}' sono incompatibili.", + "Unable_to_open_file_0_6050": "Non è possibile aprire il file '{0}'.", + "Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression_1238": "Non è possibile risolvere la firma dell'espressione Decorator della classe quando è chiamata come espressione.", + "Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression_1241": "Non è possibile risolvere la firma dell'espressione Decorator del metodo quando è chiamata come espressione.", + "Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression_1239": "Non è possibile risolvere la firma dell'espressione Decorator del parametro quando è chiamata come espressione.", + "Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression_1240": "Non è possibile risolvere la firma dell'espressione Decorator della proprietà quando è chiamata come espressione.", + "Unexpected_end_of_text_1126": "Fine del testo imprevista.", + "Unexpected_token_1012": "Token imprevisto.", + "Unexpected_token_A_constructor_method_accessor_or_property_was_expected_1068": "Token imprevisto. È previsto un costruttore, un metodo, una funzione di accesso o una proprietà.", + "Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces_1069": "Token imprevisto. Sono previsti nomi di parametro senza parentesi graffe.", + "Unexpected_token_expected_1179": "Token imprevisto. È previsto '{'.", + "Unknown_compiler_option_0_5023": "Opzione del compilatore sconosciuta: '{0}'.", + "Unknown_option_excludes_Did_you_mean_exclude_6114": "L'opzione 'excludes' è sconosciuta. Si intendeva 'exclude'?", + "Unknown_type_acquisition_option_0_17010": "L'opzione '{0}' relativa all'acquisizione del tipo è sconosciuta.", + "Unreachable_code_detected_7027": "È stato rilevato codice non raggiungibile.", + "Unsupported_locale_0_6049": "Impostazioni locali non supportate: '{0}'.", + "Unterminated_Unicode_escape_sequence_1199": "Sequenza di escape Unicode senza terminazione.", + "Unterminated_quoted_string_in_response_file_0_6045": "Stringa tra virgolette senza terminazione nel file di risposta '{0}'.", + "Unterminated_regular_expression_literal_1161": "Valore letterale di espressione regolare senza terminazione.", + "Unterminated_string_literal_1002": "Valore letterale stringa senza terminazione.", + "Unterminated_template_literal_1160": "Valore letterale di modello senza terminazione.", + "Untyped_function_calls_may_not_accept_type_arguments_2347": "Le chiamate di funzione non tipizzate potrebbero non accettare argomenti tipo.", + "Unused_label_7028": "Etichetta non usata.", + "Updating_output_timestamps_of_project_0_6359": "Aggiornamento dei timestamp di output del progetto '{0}'...", + "Use_synthetic_default_member_95016": "Usare il membro 'default' sintetico.", + "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494": "L'uso di una stringa in un'istruzione 'for...of' è supportato solo in ECMAScript 5 e versioni successive.", + "VERSION_6036": "VERSIONE", + "Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it_2560": "Il valore di tipo '{0}' non ha proprietà in comune con il tipo '{1}'. Si intendeva chiamarlo?", + "Value_of_type_0_is_not_callable_Did_you_mean_to_include_new_2348": "Il valore di tipo '{0}' non è chiamabile. Si intendeva includere 'new'?", + "Variable_0_implicitly_has_an_1_type_7005": "La variabile '{0}' contiene implicitamente un tipo '{1}'.", + "Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined_7034": "La variabile '{0}' contiene implicitamente il tipo '{1}' in alcune posizioni in cui non è possibile determinarne il tipo.", + "Variable_0_is_used_before_being_assigned_2454": "La variabile '{0}' viene usata prima dell'assegnazione.", + "Variable_declaration_expected_1134": "È prevista la dichiarazione di variabile.", + "Variable_declaration_list_cannot_be_empty_1123": "L'elenco delle dichiarazioni di variabile non può essere vuoto.", + "Version_0_6029": "Versione {0}", + "Watch_input_files_6005": "Controlla i file di input.", + "Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen_6191": "Indica se mantenere l'output della console obsoleto in modalità espressione di controllo invece di pulire lo schermo.", + "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001": "Non è possibile rinominare elementi definiti nella libreria TypeScript standard.", + "You_cannot_rename_this_element_8000": "Non è possibile rinominare questo elemento.", + "_0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write__1329": "'{0}' accetta un numero troppo ridotto di argomenti da usare come espressione Decorator in questo punto. Si intendeva chiamarlo prima e scrivere '@{0}()'?", + "_0_are_specified_twice_The_attribute_named_0_will_be_overwritten_2710": "Gli attributi '{0}' sono stati specificati due volte. L'attributo denominato '{0}' verrà sovrascritto.", + "_0_can_only_be_used_in_a_ts_file_8009": "'{0}' può essere usato solo in un file con estensione ts.", + "_0_expected_1005": "È previsto '{0}'.", + "_0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_reference_7023": "'{0}' contiene implicitamente il tipo restituito 'any', perché non contiene un'annotazione di tipo restituito e viene usato come riferimento diretto o indiretto in una delle relative espressioni restituite.", + "_0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or__7022": "'{0}' contiene implicitamente il tipo 'any', perché non contiene un'annotazione di tipo e viene usato come riferimento diretto o indiretto nel relativo inizializzatore.", + "_0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible_2692": "'{0}' è una primitiva, ma '{1}' è un oggetto wrapper. Quando possibile, preferire '{0}'.", + "_0_is_declared_but_its_value_is_never_read_6133": "L'elemento '{0}' è dichiarato, ma il suo valore non viene mai letto.", + "_0_is_declared_but_never_used_6196": "La variabile '{0}' è dichiarata, ma non viene mai usata.", + "_0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2_17012": "'{0}' non è una metaproprietà valida per la parola chiave '{1}'. Si intendeva '{2}'?", + "_0_is_referenced_directly_or_indirectly_in_its_own_base_expression_2506": "'{0}' viene usato come riferimento diretto o indiretto nella relativa espressione di base.", + "_0_is_referenced_directly_or_indirectly_in_its_own_type_annotation_2502": "'{0}' viene usato come riferimento diretto o indiretto nella relativa annotazione di tipo.", + "_0_list_cannot_be_empty_1097": "L'elenco '{0}' non può essere vuoto.", + "_0_modifier_already_seen_1030": "Il modificatore '{0}' è già presente.", + "_0_modifier_cannot_appear_on_a_class_element_1031": "Il modificatore '{0}' non può essere incluso in un elemento classe.", + "_0_modifier_cannot_appear_on_a_constructor_declaration_1089": "Il modificatore '{0}' non può essere incluso in una dichiarazione di costruttore.", + "_0_modifier_cannot_appear_on_a_data_property_1043": "Il modificatore '{0}' non può essere incluso in una proprietà Data.", + "_0_modifier_cannot_appear_on_a_module_or_namespace_element_1044": "Il modificatore '{0}' non può essere incluso in un elemento modulo o spazio dei nomi.", + "_0_modifier_cannot_appear_on_a_parameter_1090": "Il modificatore '{0}' non può essere incluso in un parametro.", + "_0_modifier_cannot_appear_on_a_type_member_1070": "Il modificatore '{0}' non può essere incluso in un membro di tipo.", + "_0_modifier_cannot_appear_on_an_index_signature_1071": "Il modificatore '{0}' non può essere incluso in una firma dell'indice.", + "_0_modifier_cannot_be_used_here_1042": "Non è possibile usare il modificatore '{0}' in questo punto.", + "_0_modifier_cannot_be_used_in_an_ambient_context_1040": "Non è possibile usare il modificatore '{0}' in un contesto di ambiente.", + "_0_modifier_cannot_be_used_with_1_modifier_1243": "Non è possibile usare il modificatore '{0}' con il modificatore '{1}'.", + "_0_modifier_cannot_be_used_with_a_class_declaration_1041": "Non è possibile usare il modificatore '{0}' con una dichiarazione di classe.", + "_0_modifier_must_precede_1_modifier_1029": "Il modificatore '{0}' deve precedere il modificatore '{1}'.", + "_0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here_2702": "'{0}' fa riferimento solo a un tipo, ma qui viene usato come spazio dei nomi.", + "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_2693": "'{0}' fa riferimento solo a un tipo, ma qui viene usato come valore.", + "_0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead_2686": "'{0}' fa riferimento a un istruzione globale UMD, ma il file corrente è un modulo. Provare ad aggiungere un'importazione.", + "_0_tag_already_specified_1223": "Il tag '{0}' è già specificato.", + "_0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag_1253": "Non è possibile usare in modo indipendente il tag '{0}' come tag JSDoc di primo livello.", + "_0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type_7010": "'{0}', in cui manca l'annotazione di tipo restituito, contiene implicitamente un tipo restituito '{1}'.", + "abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration_1242": "Il modificatore 'abstract' può essere incluso solo in una dichiarazione di classe, metodo o proprietà.", + "await_expression_is_only_allowed_within_an_async_function_1308": "L'espressione 'await' è consentita solo in una funzione asincrona.", + "await_expressions_cannot_be_used_in_a_parameter_initializer_2524": "Non è possibile usare le espressioni 'await' in un inizializzatore di parametri.", + "baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1_6106": "L'opzione 'baseUrl' è impostata su '{0}'. Verrà usato questo valore per risolvere il nome del modulo non relativo '{1}'.", + "can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment_1312": "È possibile usare '=' solo in una proprietà di valore letterale di oggetto all'interno di un'assegnazione di destrutturazione.", + "case_or_default_expected_1130": "È previsto 'case' o 'default'.", + "class_expressions_are_not_currently_supported_9003": "Le espressioni 'class' non sono attualmente supportate.", + "const_declarations_can_only_be_declared_inside_a_block_1156": "Le dichiarazioni 'const' possono essere dichiarate solo all'interno di un blocco.", + "const_declarations_must_be_initialized_1155": "Le dichiarazioni 'const' devono essere inizializzate.", + "const_enum_member_initializer_was_evaluated_to_a_non_finite_value_2477": "L'inizializzatore del membro di enumerazione 'const' è stato valutato come valore non finito.", + "const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN_2478": "L'inizializzatore del membro di enumerazione 'const' è stato valutato come valore non consentito 'NaN'.", + "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475": "Le enumerazioni 'const' possono essere usate solo in espressioni di accesso a proprietà o indice oppure nella parte destra di un'assegnazione di esportazione, di una dichiarazione di importazione o di una query su tipo.", + "delete_cannot_be_called_on_an_identifier_in_strict_mode_1102": "Non è possibile chiamare 'delete' su un identificatore in modalità strict.", + "delete_this_Project_0_is_up_to_date_because_it_was_previously_built_6360": "eliminare - Il progetto '{0}' è aggiornato perché è stato compilato in precedenza", + "enum_declarations_can_only_be_used_in_a_ts_file_8015": "Le dichiarazioni 'enum' possono essere usate solo in un file con estensione ts.", + "export_can_only_be_used_in_a_ts_file_8003": "'export=' può essere usato solo in un file con estensione ts.", + "export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always__2668": "Non è possibile applicare il modificatore 'export' a moduli di ambiente e aumenti di modulo perché sono sempre visibili.", + "extends_clause_already_seen_1172": "La clausola 'extends' è già presente.", + "extends_clause_must_precede_implements_clause_1173": "La clausola 'extends' deve precedere la clausola 'implements'.", + "extends_clause_of_exported_class_0_has_or_is_using_private_name_1_4020": "La clausola 'extends' della classe esportata '{0}' contiene o usa il nome privato '{1}'.", + "extends_clause_of_exported_interface_0_has_or_is_using_private_name_1_4022": "La clausola 'extends' dell'interfaccia esportata '{0}' contiene o usa il nome privato '{1}'.", + "file_6025": "file", + "get_and_set_accessor_must_have_the_same_this_type_2682": "Le funzioni di accesso 'get e 'set' devono essere dello stesso tipo 'this'.", + "get_and_set_accessor_must_have_the_same_type_2380": "Le funzioni di accesso 'get e 'set' devono essere dello stesso tipo.", + "implements_clause_already_seen_1175": "La clausola 'implements' è già presente.", + "implements_clauses_can_only_be_used_in_a_ts_file_8005": "'implements clauses' può essere usato solo in un file con estensione ts.", + "import_can_only_be_used_in_a_ts_file_8002": "'import ... =' può essere usato solo in un file con estensione ts.", + "infer_declarations_are_only_permitted_in_the_extends_clause_of_a_conditional_type_1338": "Le dichiarazioni 'infer' sono consentite solo nella clausola 'extends' di un tipo condizionale.", + "interface_declarations_can_only_be_used_in_a_ts_file_8006": "'interface declarations' può essere usato solo in un file con estensione ts.", + "let_declarations_can_only_be_declared_inside_a_block_1157": "Le dichiarazioni 'let' possono essere dichiarate solo all'interno di un blocco.", + "let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations_2480": "Non è consentito usare 'let' come nome in dichiarazioni 'let' o 'const'.", + "module_declarations_can_only_be_used_in_a_ts_file_8007": "'module declarations' può essere usato solo in un file con estensione ts.", + "new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead_1150": "Non è possibile usare 'new T[]' per creare una matrice. Usare 'new Array()'.", + "new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type_7009": "L'espressione 'new', nella cui destinazione manca una firma del costrutto, contiene implicitamente un tipo 'any'.", + "non_null_assertions_can_only_be_used_in_a_ts_file_8013": "'non-null assertions' può essere usato solo in un file con estensione ts.", + "options_6024": "opzioni", + "or_expected_1144": "È previsto '{' o ';'.", + "package_json_does_not_have_a_0_field_6100": "Il file 'package.json' non contiene un campo '{0}'.", + "package_json_has_0_field_1_that_references_2_6101": "Il file 'package.json' contiene il campo '{1}' di '{0}' che fa riferimento a '{2}'.", + "parameter_modifiers_can_only_be_used_in_a_ts_file_8012": "'parameter modifiers' può essere usato solo in un file con estensione ts.", + "paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0_6091": "È specificata l'opzione 'paths'. Verrà cercato un criterio per la corrispondenza con il nome del modulo '{0}'.", + "readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024": "Il modificatore 'readonly' può essere incluso solo in una dichiarazione di proprietà o una firma dell'indice.", + "require_call_may_be_converted_to_an_import_80005": "La chiamata a 'require' può essere convertita in un'importazione.", + "rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107": "L'opzione 'rootDirs' è impostata e verrà usata per risolvere il nome del modulo relativo '{0}'.", + "super_can_only_be_referenced_in_a_derived_class_2335": "È possibile fare riferimento a 'super' solo in una classe derivata.", + "super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions_2660": "È possibile fare riferimento a 'super' solo in membri di classi derivate o espressioni letterali di oggetto.", + "super_cannot_be_referenced_in_a_computed_property_name_2466": "Non è possibile fare riferimento a 'super' in un nome di proprietà calcolato.", + "super_cannot_be_referenced_in_constructor_arguments_2336": "Non è possibile fare riferimento a 'super' in argomenti del costruttore.", + "super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_highe_2659": "'super' è consentito solo in membri di espressioni letterali di oggetto quando il valore dell'opzione 'target' è 'ES2015' o superiore.", + "super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class_17011": "È necessario chiamare 'super' prima di accedere a una proprietà di 'super' nel costruttore di una classe derivata.", + "super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class_17009": "È necessario chiamare 'super' prima di accedere a 'this' nel costruttore di una classe derivata.", + "super_must_be_followed_by_an_argument_list_or_member_access_1034": "'super' deve essere seguito da un elenco di argomento o da un accesso membro.", + "super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_der_2338": "L'accesso alla proprietà 'super' è consentito solo in un costruttore, in una funzione membro o in una funzione di accesso di membro di una classe derivata.", + "this_cannot_be_referenced_in_a_computed_property_name_2465": "Non è possibile fare riferimento a 'this' in un nome di proprietà calcolato.", + "this_cannot_be_referenced_in_a_module_or_namespace_body_2331": "Non è possibile fare riferimento a 'this' nel corpo di un modulo o di uno spazio dei nomi.", + "this_cannot_be_referenced_in_a_static_property_initializer_2334": "Non è possibile fare riferimento a 'this' in un inizializzatore di proprietà statica.", + "this_cannot_be_referenced_in_constructor_arguments_2333": "Non è possibile fare riferimento a 'this' in argomenti del costruttore.", + "this_cannot_be_referenced_in_current_location_2332": "Non è possibile fare riferimento a 'this' nella posizione corrente.", + "this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_2683": "'this' contiene implicitamente il tipo 'any' perché non include un'annotazione di tipo.", + "type_aliases_can_only_be_used_in_a_ts_file_8008": "'type aliases' può essere usato solo in un file con estensione ts.", + "type_arguments_can_only_be_used_in_a_ts_file_8011": "'type arguments' può essere usato solo in un file con estensione ts.", + "type_assertion_expressions_can_only_be_used_in_a_ts_file_8016": "'type assertion expressions' può essere usato solo in un file con estensione ts.", + "type_parameter_declarations_can_only_be_used_in_a_ts_file_8004": "'type parameter declarations' può essere usato solo in un file con estensione ts.", + "types_can_only_be_used_in_a_ts_file_8010": "'types' può essere usato solo in un file con estensione ts.", + "unique_symbol_types_are_not_allowed_here_1335": "I tipi 'unique symbol' non sono consentiti in questo punto.", + "unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement_1334": "I tipi 'unique symbol' sono consentiti solo nelle variabili in un'istruzione di variabile.", + "unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name_1333": "Non è possibile usare i tipi 'unique symbol' in una dichiarazione di variabile con nome di binding.", + "with_statements_are_not_allowed_in_an_async_function_block_1300": "Le istruzioni 'with' non sono consentite in un blocco di funzione asincrona.", + "with_statements_are_not_allowed_in_strict_mode_1101": "Le istruzioni 'with' non sono consentite in modalità strict.", + "yield_expressions_cannot_be_used_in_a_parameter_initializer_2523": "Non è possibile usare le espressioni 'yield' in un inizializzatore di parametri." +} \ No newline at end of file diff --git a/node_modules/typescript/lib/ja/diagnosticMessages.generated.json b/node_modules/typescript/lib/ja/diagnosticMessages.generated.json new file mode 100644 index 0000000..6877a89 --- /dev/null +++ b/node_modules/typescript/lib/ja/diagnosticMessages.generated.json @@ -0,0 +1,1101 @@ +{ + "A_0_modifier_cannot_be_used_with_an_import_declaration_1079": "'{0}' 修飾子とインポート宣言は同時に使用できません。", + "A_0_modifier_cannot_be_used_with_an_interface_declaration_1045": "'{0}' 修飾子とインターフェイス宣言は同時に使用できません。", + "A_0_parameter_must_be_the_first_parameter_2680": "'{0}' パラメーターは最初のパラメーターである必要があります。", + "A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature_2463": "実装シグネチャでバインド パターン パラメーターを省略可能にすることはできません。", + "A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement_1105": "'break' ステートメントは外側のイテレーションまたは switch ステートメント内でのみ使用できます。", + "A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement_1116": "'break' ステートメントは、外側のステートメントのラベルにのみ移動できます。", + "A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments_2500": "クラスで実装できるのは、オプションの型引数を指定した識別子/完全修飾名のみです。", + "A_class_declaration_without_the_default_modifier_must_have_a_name_1211": "'default' の修飾子がないクラス宣言には名前が必要です。", + "A_class_may_only_extend_another_class_2311": "クラスで拡張できるのは別のクラスだけです。", + "A_class_may_only_implement_another_class_or_interface_2422": "クラスで実装できるのは別のクラスまたはインターフェイスだけです。", + "A_class_member_cannot_have_the_0_keyword_1248": "クラス メンバーに '{0}' キーワードを指定することはできません。", + "A_comma_expression_is_not_allowed_in_a_computed_property_name_1171": "コンマ式は計算されたプロパティ名では使用できません。", + "A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type_2467": "計算されたプロパティ名は、型パラメーターをそれを含む型から参照することはできません。", + "A_computed_property_name_in_a_class_property_declaration_must_refer_to_an_expression_whose_type_is_a_1166": "クラス プロパティ宣言内の計算されたプロパティ名は、型がリテラル型または 'unique symbol' 型の式を参照する必要があります。", + "A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_ty_1168": "メソッド オーバーロード内の計算されたプロパティ名は、型がリテラル型または 'unique symbol' 型の式を参照する必要があります。", + "A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type__1170": "型リテラル内の計算されたプロパティ名は、型がリテラル型または 'unique symbol' 型の式を参照する必要があります。", + "A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_t_1165": "環境コンテキスト内の計算されたプロパティ名は、型がリテラル型または 'unique symbol' 型の式を参照する必要があります。", + "A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_1169": "インターフェイス内の計算されたプロパティ名は、型がリテラル型または 'unique symbol' 型の式を参照する必要があります。", + "A_computed_property_name_must_be_of_type_string_number_symbol_or_any_2464": "計算されたプロパティ名は 'string' 型、'number' 型、'symbol' 型、または 'any' 型のいずれかでなければなりません。", + "A_computed_property_name_of_the_form_0_must_be_of_type_symbol_2471": "形式 '{0}' の計算されたプロパティ名は 'symbol' 型でなければなりません。", + "A_const_enum_member_can_only_be_accessed_using_a_string_literal_2476": "const 列挙型メンバーは、文字列リテラルを使用してのみアクセスできます。", + "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_1254": "環境コンテキスト内の 'const' 初期化子は文字列リテラルか数値リテラルにする必要があります。", + "A_constructor_cannot_contain_a_super_call_when_its_class_extends_null_17005": "コンストラクターのクラスが 'null' を拡張する場合、そのコンストラクターに 'super' の呼び出しを含めることはできません。", + "A_constructor_cannot_have_a_this_parameter_2681": "コンストラクターに 'this' パラメーターを指定することはできません。", + "A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement_1104": "'continue' ステートメントは外側のイテレーション内でのみ使用できます。", + "A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement_1115": "'continue' ステートメントは、外側のイテレーション ステートメントのラベルにのみ移動できます。", + "A_declare_modifier_cannot_be_used_in_an_already_ambient_context_1038": "'declare' 修飾子は、環境コンテキストでは使用できません。", + "A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file_1046": ".d.ts ファイルの最上位宣言には、'declare' 修飾子が必要です。", + "A_decorator_can_only_decorate_a_method_implementation_not_an_overload_1249": "デコレーターが装飾できるのは、オーバーロードではなく、メソッドの実装のみです。", + "A_default_clause_cannot_appear_more_than_once_in_a_switch_statement_1113": "'default' 句を 'switch' ステートメントで複数回使用することはできません。", + "A_default_export_can_only_be_used_in_an_ECMAScript_style_module_1319": "既定のエクスポートは、ECMAScript スタイルのモジュールでのみ使用できます。", + "A_definite_assignment_assertion_is_not_permitted_in_this_context_1255": "限定代入アサーション '!' は、このコンテキストで許可されていません。", + "A_destructuring_declaration_must_have_an_initializer_1182": "非構造化宣言には初期化子が必要です。", + "A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declarat_2712": "ES5/ES3 の動的インポート呼び出しには、'Promise' コンストラクターが必要です。'Promise' コンストラクターの宣言があることを確認するか、`--lib` オプションに 'ES2015' を組み込んでください。", + "A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES20_2711": "動的インポート呼び出しは 'Promise' を返します。'Promise' の宣言があること、または `--lib` オプションに 'ES2015' を含めていることをご確認ください。", + "A_file_cannot_have_a_reference_to_itself_1006": "ファイルにそれ自体への参照を含めることはできません。", + "A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator_1103": "'for-await-of' ステートメントは、非同期関数または非同期ジェネレーターの中でのみ使用できます。", + "A_function_returning_never_cannot_have_a_reachable_end_point_2534": "'never' を返す関数には、到達可能なエンド ポイントがありません。", + "A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void_2679": "'new' キーワードで呼び出される関数に、'void' である 'this' 型を使用することはできません。", + "A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value_2355": "宣言された型が 'void' でも 'any' でもない関数は値を返す必要があります。", + "A_generator_cannot_have_a_void_type_annotation_2505": "ジェネレーターに 'void' 型の注釈を指定することはできません。", + "A_get_accessor_cannot_have_parameters_1054": "'get' アクセサーにパラメーターを指定することはできません。", + "A_get_accessor_must_return_a_value_2378": "'get' アクセサーは値を返す必要があります。", + "A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_memb_2651": "列挙型宣言のメンバー初期化子は、他の列挙型で定義されたメンバーを含め、その後で宣言されたメンバーを参照できません。", + "A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any_2545": "mixin クラスには、型 'any[]' の単一の rest パラメーターを持つコンストラクターが必要です。", + "A_module_cannot_have_multiple_default_exports_2528": "モジュールに複数の既定のエクスポートを含めることはできません。", + "A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merg_2433": "名前空間宣言は、それとマージするクラスや関数と異なるファイルに配置できません。", + "A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged_2434": "名前空間宣言は、それとマージするクラスや関数より前に配置できません。", + "A_namespace_declaration_is_only_allowed_in_a_namespace_or_module_1235": "名前空間宣言は、名前空間かモジュールでのみ使用できます。", + "A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_7038": "名前空間スタイルのインポートを呼び出したり、構築したりすることはできません。実行時にエラーが発生する原因となります。", + "A_non_dry_build_would_build_project_0_6357": "非 -dry ビルドを実行した場合、プロジェクト '{0}' がビルドされます", + "A_non_dry_build_would_delete_the_following_files_Colon_0_6356": "非 -dry ビルドを実行した場合、次のファイルが削除されます: {0}", + "A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation_2371": "パラメーター初期化子は、関数またはコンストラクターの実装でのみ指定できます。", + "A_parameter_property_cannot_be_declared_using_a_rest_parameter_1317": "パラメーター プロパティは、rest パラメーターを使用して宣言することはできません。", + "A_parameter_property_is_only_allowed_in_a_constructor_implementation_2369": "パラメーター プロパティは、コンストラクターの実装でのみ指定できます。", + "A_parameter_property_may_not_be_declared_using_a_binding_pattern_1187": "パラメーター プロパティは、バインド パターンを使用して宣言することはできません。", + "A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not_18001": "'拡張' オプション内のパスは相対パスまたはルート パスである必要がありますが、'{0}' の場合は、その必要はありません。", + "A_promise_must_have_a_then_method_1059": "Promise には 'then' メソッドが必要です。", + "A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly_1331": "型が 'unique symbol' 型のクラスのプロパティは、'static' と 'readonly' の両方である必要があります。", + "A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly_1330": "型が 'unique symbol' 型のインターフェイスまたは型リテラルのプロパティは、'readonly' である必要があります。", + "A_required_parameter_cannot_follow_an_optional_parameter_1016": "必須パラメーターを省略可能なパラメーターの後に指定することはできません。", + "A_rest_element_cannot_contain_a_binding_pattern_2501": "rest 要素にバインド パターンを含めることはできません。", + "A_rest_element_cannot_have_a_property_name_2566": "rest 要素にプロパティ名を指定することはできません。", + "A_rest_element_cannot_have_an_initializer_1186": "rest 要素に初期化子を指定することはできません。", + "A_rest_element_must_be_last_in_a_destructuring_pattern_2462": "rest 要素は非構造化パターンの最後に指定する必要があります。", + "A_rest_parameter_cannot_be_optional_1047": "rest パラメーターを省略可能にすることはできません。", + "A_rest_parameter_cannot_have_an_initializer_1048": "rest パラメーターに初期化子を指定することはできません。", + "A_rest_parameter_must_be_last_in_a_parameter_list_1014": "rest パラメーターはパラメーター リストの最後に指定する必要があります。", + "A_rest_parameter_must_be_of_an_array_type_2370": "rest パラメーターは配列型でなければなりません。", + "A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma_1013": "rest パラメーターまたはバインド パターンに末尾のコンマがない可能性があります。", + "A_return_statement_can_only_be_used_within_a_function_body_1108": "'return' ステートメントは、関数本体でのみ使用できます。", + "A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl_6167": "'baseUrl' の相対的な場所を検索するためにインポートを再マップする一連のエントリ。", + "A_set_accessor_cannot_have_a_return_type_annotation_1095": "'set' アクセサーに、戻り値の型の注釈を指定することはできません。", + "A_set_accessor_cannot_have_an_optional_parameter_1051": "'set' アクセサーに、省略可能パラメーターを指定することはできません。", + "A_set_accessor_cannot_have_rest_parameter_1053": "'set' アクセサーに rest パラメーターを指定することはできません。", + "A_set_accessor_must_have_exactly_one_parameter_1049": "'set' アクセサーにはパラメーターを 1 つだけ指定しなければなりません。", + "A_set_accessor_parameter_cannot_have_an_initializer_1052": "'set' アクセサーのパラメーターに初期化子を含めることはできません。", + "A_signature_with_an_implementation_cannot_use_a_string_literal_type_2381": "実装のシグネチャには文字列リテラル型は使用できません。", + "A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_proper_2376": "'super' の呼び出しは、初期化されたプロパティまたはパラメーターのプロパティがクラスに含まれている場合、コンストラクターの最初のステートメントでなければなりません。", + "A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard_2518": "'this' ベース型のガードはパラメーター ベース型のガードとは互換性がありません。", + "A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface_2526": "'this' 型はクラスまたはインターフェイスの静的でないメンバーでのみ使用できます。", + "A_tsconfig_json_file_is_already_defined_at_Colon_0_5054": "'tsconfig.json' ファイルは既に '{0}' で定義されています。", + "A_tuple_type_element_list_cannot_be_empty_1122": "タプル型の要素リストを空にすることはできません。", + "A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Con_17007": "累乗式の左辺で型アサーション式を使用することはできません。式を括弧で囲むことを検討してください。", + "A_type_literal_property_cannot_have_an_initializer_1247": "型リテラル プロパティに初期化子を使用することはできません。", + "A_type_predicate_cannot_reference_a_rest_parameter_1229": "型の述語は rest パラメーターを参照できません。", + "A_type_predicate_cannot_reference_element_0_in_a_binding_pattern_1230": "型の述語は、バインド パターン内の要素 '{0}' を参照できません。", + "A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods_1228": "型の述語は、関数およびメソッドの戻り値の型の位置でのみ使用できます。", + "A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type_2677": "type 述語の型はそのパラメーターの型に割り当て可能である必要があります。", + "A_variable_whose_type_is_a_unique_symbol_type_must_be_const_1332": "型が 'unique symbol' 型の変数は、'const' である必要があります。", + "A_yield_expression_is_only_allowed_in_a_generator_body_1163": "'yield' 式は、ジェネレーター本文でのみ使用できます。", + "Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression_2513": "クラス '{1}' の抽象メソッド '{0}' には super 式を介してアクセスできません。", + "Abstract_methods_can_only_appear_within_an_abstract_class_1244": "抽象メソッドは抽象クラス内でのみ使用できます。", + "Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor_2715": "コンストラクター内でクラス '{1}' の抽象プロパティ '{0}' にアクセスできません。", + "Accessibility_modifier_already_seen_1028": "アクセシビリティ修飾子は既に存在します。", + "Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher_1056": "アクセサーは ECMAScript 5 以上をターゲットにする場合にのみ使用できます。", + "Accessors_must_both_be_abstract_or_non_abstract_2676": "アクセサーはどちらも抽象または非抽象である必要があります。", + "Add_0_to_existing_import_declaration_from_1_90015": "\"{1}\" から既存のインポート宣言に '{0}' を追加する", + "Add_0_to_unresolved_variable_90008": "'{0}' を未解決の変数に追加します", + "Add_all_missing_async_modifiers_95041": "不足しているすべての 'async' 修飾子を追加します", + "Add_all_missing_members_95022": "不足しているすべてのメンバーを追加します", + "Add_all_missing_super_calls_95039": "不足しているすべての super の呼び出しを追加します", + "Add_async_modifier_to_containing_function_90029": "含まれている関数に async 修飾子を追加します", + "Add_braces_to_arrow_function_95059": "アロー関数に中かっこを追加します", + "Add_definite_assignment_assertion_to_property_0_95020": "プロパティ '{0}' に限定代入アサーションを追加します", + "Add_definite_assignment_assertions_to_all_uninitialized_properties_95028": "初期化されていないすべてのプロパティに限定代入アサーションを追加します", + "Add_index_signature_for_property_0_90017": "プロパティ '{0}' のインデックス シグネチャを追加する", + "Add_initializer_to_property_0_95019": "プロパティ '{0}' に初期化子を追加します", + "Add_initializers_to_all_uninitialized_properties_95027": "初期化されていないすべてのプロパティに初期化子を追加します", + "Add_missing_super_call_90001": "欠落している 'super()' 呼び出しを追加する", + "Add_missing_typeof_95052": "不足している 'typeof' を追加します", + "Add_or_remove_braces_in_an_arrow_function_95058": "アロー関数内の中かっこを追加または削除します", + "Add_qualifier_to_all_unresolved_variables_matching_a_member_name_95037": "メンバー名と一致するすべての未解決の変数に修飾子を追加します", + "Add_to_all_uncalled_decorators_95044": "呼び出されていないすべてのデコレーターに '()' を追加します", + "Add_ts_ignore_to_all_error_messages_95042": "すべてのエラー メッセージに '@ts-ignore' を追加します", + "Add_undefined_type_to_all_uninitialized_properties_95029": "初期化されていないすべてのプロパティに未定義の型を追加します", + "Add_undefined_type_to_property_0_95018": "プロパティ '{0}' に '未定義' の型を追加します", + "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068": "tsconfig.json ファイルを追加すると、TypeScript ファイルと JavaScript ファイルの両方を含むプロジェクトを整理できます。詳細については、https://aka.ms/tsconfig をご覧ください。", + "Additional_Checks_6176": "追加のチェック", + "Advanced_Options_6178": "詳細オプション", + "All_declarations_of_0_must_have_identical_modifiers_2687": "'{0}' のすべての宣言には、同一の修飾子が必要です。", + "All_declarations_of_0_must_have_identical_type_parameters_2428": "'{0}' のすべての宣言には、同一の型パラメーターがある必要があります。", + "All_declarations_of_an_abstract_method_must_be_consecutive_2516": "抽象メソッドの宣言はすべて連続している必要があります。", + "All_destructured_elements_are_unused_6198": "非構造化要素はいずれも使用されていません。", + "All_imports_in_import_declaration_are_unused_6192": "インポート宣言内のインポートはすべて未使用です。", + "All_variables_are_unused_6199": "すべての変数は未使用です。", + "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011": "既定のエクスポートがないモジュールからの既定のインポートを許可します。これは、型チェックのみのため、コード生成には影響を与えません。", + "Allow_javascript_files_to_be_compiled_6102": "javascript ファイルのコンパイルを許可します。", + "Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided_1209": "'--isolatedModules' フラグが指定されている場合、アンビエント const 列挙型は使用できません。", + "Ambient_module_declaration_cannot_specify_relative_module_name_2436": "アンビエント モジュール宣言では、相対モジュール名を指定できません。", + "Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces_2435": "アンビエント モジュールを、他のモジュールまたは名前空間内の入れ子にすることはできません。", + "An_AMD_module_cannot_have_multiple_name_assignments_2458": "AMD モジュールに複数の名前を割り当てることはできません。", + "An_abstract_accessor_cannot_have_an_implementation_1318": "抽象アクセサーに実装を含めることはできません。", + "An_accessor_cannot_be_declared_in_an_ambient_context_1086": "環境コンテキストではアクセサーは宣言できません。", + "An_accessor_cannot_have_type_parameters_1094": "アクセサーに型パラメーターを指定することはできません。", + "An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file_1234": "アンビエント モジュール宣言は、ファイルの最上位にのみ使用できます。", + "An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type_2356": "算術オペランドは 'any' 型、'number' 型、列挙型のいずれかでなければなりません。", + "An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_de_2705": "ES5/ES3 の非同期の関数またはメソッドには、'Promise' コンストラクターが必要です。'Promise' コンストラクターの宣言があることを確認するか、`--lib` オプションに 'ES2015' を組み込んでください。", + "An_async_function_or_method_must_have_a_valid_awaitable_return_type_1057": "非同期関数または非同期メソッドには、有効で待機可能な戻り値の型を指定する必要があります。", + "An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_in_2697": "非同期関数またはメソッドは 'Promise' を返す必要があります。'Promise' の宣言があること、または `--lib` オプションに 'ES2015' を含めていることを確認してください。", + "An_async_iterator_must_have_a_next_method_2519": "非同期反復子には 'next()' メソッドが必要です。", + "An_element_access_expression_should_take_an_argument_1011": "要素アクセス式では、引数を取る必要があります。", + "An_enum_member_cannot_have_a_numeric_name_2452": "列挙型メンバーに数値名を含めることはできません。", + "An_export_assignment_can_only_be_used_in_a_module_1231": "エクスポートの割り当てはモジュールでのみ使用可能です。", + "An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements_2309": "エクスポートの割り当ては、エクスポートされた他の要素を含むモジュールでは使用できません。", + "An_export_assignment_cannot_be_used_in_a_namespace_1063": "エクスポートの割り当ては、名前空間では使用できません。", + "An_export_assignment_cannot_have_modifiers_1120": "エクスポートの割り当てに修飾子を指定することはできません。", + "An_export_declaration_can_only_be_used_in_a_module_1233": "エクスポート宣言はモジュールでのみ使用可能です。", + "An_export_declaration_cannot_have_modifiers_1193": "エクスポート宣言に修飾子を指定することはできません。", + "An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive_1198": "拡張された Unicode エスケープ値は 0x0 と 0x10FFFF の間 (両端を含む) でなければなりません。", + "An_implementation_cannot_be_declared_in_ambient_contexts_1183": "実装は環境コンテキストでは宣言できません。", + "An_import_declaration_can_only_be_used_in_a_namespace_or_module_1232": "インポート宣言は名前空間またはモジュールでのみ使用可能です。", + "An_import_declaration_cannot_have_modifiers_1191": "インポート宣言に修飾子を指定することはできません。", + "An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead_2691": "インポート パスの末尾を拡張子 '{0}' にすることはできません。代わりに '{1}' のインポートをご検討ください。", + "An_index_expression_argument_must_be_of_type_string_number_symbol_or_any_2342": "インデックス式の引数の型は、'string'、'number'、'symbol' または 'any' である必要があります。", + "An_index_signature_cannot_have_a_rest_parameter_1017": "インデックス シグネチャに rest パラメーターを指定することはできません。", + "An_index_signature_must_have_a_type_annotation_1021": "インデックス シグネチャには型の注釈が必要です。", + "An_index_signature_must_have_exactly_one_parameter_1096": "インデックス シグネチャには、パラメーターを 1 つだけ指定しなければなりません。", + "An_index_signature_parameter_cannot_have_a_question_mark_1019": "インデックス シグネチャのパラメーターに疑問符を指定することはできません。", + "An_index_signature_parameter_cannot_have_an_accessibility_modifier_1018": "インデックス シグネチャのパラメーターにアクセシビリティ修飾子を指定することはできません。", + "An_index_signature_parameter_cannot_have_an_initializer_1020": "インデックス シグネチャのパラメーターに初期化子を指定することはできません。", + "An_index_signature_parameter_must_have_a_type_annotation_1022": "インデックス シグネチャのパラメーターには型の注釈が必要です。", + "An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead_1336": "インデックス シグネチャのパラメーターの型を型のエイリアスにすることはできません。代わりに、'[{0}: {1}]: {2}' と記述することをご検討ください。", + "An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead_1337": "インデックス シグネチャのパラメーターの型を共用体型にすることはできません。代わりに、マップされたオブジェクト型の使用をご検討ください。", + "An_index_signature_parameter_type_must_be_string_or_number_1023": "インデックス シグネチャのパラメーターの型は 'string' または 'number' でなければなりません。", + "An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments_2499": "インターフェイスが拡張するのは、オプションの型引数が指定された識別子/完全修飾名のみです。", + "An_interface_may_only_extend_a_class_or_another_interface_2312": "インターフェイスで拡張できるのは、クラスまたは他のインターフェイスのみです。", + "An_interface_property_cannot_have_an_initializer_1246": "インターフェイス プロパティに初期化子を使用することはできません。", + "An_iterator_must_have_a_next_method_2489": "反復子には 'next()' メソッドが必要です。", + "An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name_1118": "オブジェクト リテラルに同じ名前の複数の get/set アクセサーを指定することはできません。", + "An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode_1117": "厳格モードでは、オブジェクト リテラルに同じ名前の複数のプロパティを指定することはできません。", + "An_object_literal_cannot_have_property_and_accessor_with_the_same_name_1119": "オブジェクト リテラルには、同じ名前のプロパティおよびアクセサーを指定することはできません。", + "An_object_member_cannot_be_declared_optional_1162": "オブジェクト メンバーを省略可能として宣言することはできません。", + "An_overload_signature_cannot_be_declared_as_a_generator_1222": "オーバーロード シグネチャをジェネレーターとして宣言することはできません。", + "An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_ex_17006": "累乗式の左辺で '{0}' 演算子を含む単項式を使用することはできません。式を括弧で囲むことを検討してください。", + "Annotate_everything_with_types_from_JSDoc_95043": "すべてに JSDoc の型で注釈を付けます", + "Annotate_with_type_from_JSDoc_95009": "JSDoc の型で注釈を付けます", + "Annotate_with_types_from_JSDoc_95010": "JSDoc の型で注釈を付けます", + "Argument_expression_expected_1135": "引数式が必要です。", + "Argument_for_0_option_must_be_Colon_1_6046": "'{0}' オプションの引数は {1} である必要があります。", + "Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_2345": "型 '{0}' の引数を型 '{1}' のパラメーターに割り当てることはできません。", + "Array_element_destructuring_pattern_expected_1181": "配列要素の非構造化パターンが必要です。", + "Asterisk_Slash_expected_1010": "'*/' が必要です。", + "Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_2669": "グローバル スコープの拡張を直接入れ子にできるのは、外部モジュールまたは環境モジュールの宣言内のみです。", + "Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambien_2670": "グローバル スコープの拡張は、環境コンテキストに既にある場合を除いて、'declare' 修飾子を使用する必要があります。", + "Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using__6140": "プロジェクト '{0}' で型指定の自動検出が有効になっています。キャッシュの場所 '{2}' を使用して、モジュール '{1}' に対して追加の解決パスを実行しています。", + "Base_class_expressions_cannot_reference_class_type_parameters_2562": "基底クラスの式ではクラスの型パラメーターを参照することはできません。", + "Base_constructor_return_type_0_is_not_a_class_or_interface_type_2509": "既定コンストラクターの戻り値の型 '{0}' は、クラス型またはインターフェイス型ではありません。", + "Base_constructors_must_all_have_the_same_return_type_2510": "既定コンストラクターの戻り値の型は、すべて同じである必要があります。", + "Base_directory_to_resolve_non_absolute_module_names_6083": "相対モジュール名を解決するためのベース ディレクトリ。", + "Basic_Options_6172": "基本オプション", + "Binary_digit_expected_1177": "2 進の数字が必要です。", + "Binding_element_0_implicitly_has_an_1_type_7031": "バインド要素 '{0}' には暗黙的に '{1}' 型が含まれます。", + "Block_scoped_variable_0_used_before_its_declaration_2448": "ブロック スコープの変数 '{0}' が、宣言の前に使用されています。", + "Build_all_projects_including_those_that_appear_to_be_up_to_date_6368": "最新の状態であると思われるものを含むすべてのプロジェクトをビルドします", + "Build_one_or_more_projects_and_their_dependencies_if_out_of_date_6364": "最新でない場合は、1 つ以上のプロジェクトとその依存関係をビルドします", + "Building_project_0_6358": "プロジェクト \"{0}\" をビルドしています...", + "Call_decorator_expression_90028": "デコレーター式を呼び出す", + "Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7020": "戻り値の型の注釈がない呼び出しシグネチャの戻り値の型は、暗黙的に 'any' になります。", + "Call_target_does_not_contain_any_signatures_2346": "呼び出しターゲットにシグネチャが含まれていません。", + "Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_p_2713": "'{0}.{1}' にアクセスできません。'{0}' は型で、名前空間ではありません。'{0}[\"{1}\"]' で '{0}' のプロパティ '{1}' の型を取得するつもりでしたか?", + "Cannot_assign_a_0_constructor_type_to_a_1_constructor_type_2672": "'{0}' コンストラクター型を '{1}' コンストラクター型に割り当てることができません。", + "Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type_2517": "抽象コンストラクター型を非抽象コンストラクター型に割り当てることはできません。", + "Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property_2540": "定数または読み取り専用プロパティであるため、'{0}' に割り当てられません。", + "Cannot_assign_to_0_because_it_is_not_a_variable_2539": "変数ではないため、'{0}' に割り当てられません。", + "Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity_2671": "モジュール '{0}' は、モジュール以外のエンティティに解決するので拡張できません。", + "Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity_2649": "モジュール '{0}' は、モジュール以外のエンティティに解決するため、値のエクスポートで拡張できません。", + "Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system_6131": "'--module' フラグが 'amd' か 'system' でない限り、オプション '{0}' を使用してモジュールをコンパイルできません。", + "Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided_1208": "'--isolatedModules' フラグが指定されていると、名前空間をコンパイルできません。", + "Cannot_create_an_instance_of_an_abstract_class_2511": "抽象クラスのインスタンスは作成できません。", + "Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module_2661": "'{0}' をエクスポートできません。モジュールからエクスポートできるのはローカル宣言のみです。", + "Cannot_extend_a_class_0_Class_constructor_is_marked_as_private_2675": "クラス '{0}' を拡張できません。Class コンストラクターがプライベートに設定されています。", + "Cannot_extend_an_interface_0_Did_you_mean_implements_2689": "インターフェイス '{0}' を拡張できません。'implements' ですか?", + "Cannot_find_a_tsconfig_json_file_at_the_specified_directory_Colon_0_5057": "指定されたディレクトリに tsconfig.json ファイルが見つかりません: '{0}'。", + "Cannot_find_global_type_0_2318": "グローバル型 '{0}' が見つかりません。", + "Cannot_find_global_value_0_2468": "グローバル値 '{0}' が見つかりません。", + "Cannot_find_lib_definition_for_0_2726": "'{0}' のライブラリ定義が見つかりません。", + "Cannot_find_lib_definition_for_0_Did_you_mean_1_2727": "'{0}' のライブラリ定義が見つかりません。'{1}' ですか?", + "Cannot_find_module_0_2307": "モジュール '{0}' が見つかりません。", + "Cannot_find_name_0_2304": "名前 '{0}' が見つかりません。", + "Cannot_find_name_0_Did_you_mean_1_2552": "'{0}' という名前は見つかりません。'{1}' ですか?", + "Cannot_find_name_0_Did_you_mean_the_instance_member_this_0_2663": "名前 '{0}' が見つかりません。インスタンス メンバー 'this.{0}' ですか?", + "Cannot_find_name_0_Did_you_mean_the_static_member_1_0_2662": "名前 '{0}' が見つかりません。静的メンバー '{1}.{0}' ですか?", + "Cannot_find_namespace_0_2503": "名前空間 '{0}' が見つかりません。", + "Cannot_find_parameter_0_1225": "パラメーター '{0}' が見つかりません。", + "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009": "入力ファイルの共通サブディレクトリ パスが見つかりません。", + "Cannot_find_type_definition_file_for_0_2688": "'{0}' の型定義ファイルが見つかりません。", + "Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1_6137": "型宣言ファイルをインポートできません。'{1}' の代わりに '{0}' をインポートすることを検討してください。", + "Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1_2481": "ブロック スコープ宣言 '{1}' と同じスコープ内の外部スコープ変数 '{0}' を初期化できません。", + "Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatur_2349": "型に呼び出しシグネチャがない式を呼び出すことはできません。型 '{0}' には互換性のある呼び出しシグネチャがありません。", + "Cannot_invoke_an_object_which_is_possibly_null_2721": "'null' の可能性があるオブジェクトを呼び出すことはできません。", + "Cannot_invoke_an_object_which_is_possibly_null_or_undefined_2723": "'null' または 'undefined' の可能性があるオブジェクトを呼び出すことはできません。", + "Cannot_invoke_an_object_which_is_possibly_undefined_2722": "'undefined' の可能性があるオブジェクトを呼び出すことはできません。", + "Cannot_prepend_project_0_because_it_does_not_have_outFile_set_6308": "'outFile' が設定されていないため、プロジェクト '{0}' を先頭に追加することはできません", + "Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205": "0'--isolatedModules' フラグが指定されている場合、型を再エクスポートできません。", + "Cannot_read_file_0_Colon_1_5012": "ファイル '{0}' を読み取れません: {1}。", + "Cannot_redeclare_block_scoped_variable_0_2451": "ブロック スコープの変数 '{0}' を再宣言することはできません。", + "Cannot_redeclare_exported_variable_0_2323": "エクスポートされた変数 '{0}' を再び宣言できません。", + "Cannot_redeclare_identifier_0_in_catch_clause_2492": "catch 句で識別子 '{0}' を再宣言することはできません。", + "Cannot_use_JSX_unless_the_jsx_flag_is_provided_17004": "'--jsx' フラグが指定されていないと、JSX を使用できません。", + "Cannot_use_imports_exports_or_module_augmentations_when_module_is_none_1148": "'--module' が 'none' である場合、インポート、エクスポート、モジュール拡張は使用できません。", + "Cannot_use_namespace_0_as_a_type_2709": "名前空間 '{0}' を型として使用することはできません。", + "Cannot_use_namespace_0_as_a_value_2708": "名前空間 '{0}' を値として使用することはできません。", + "Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature_2351": "呼び出しシグネチャまたはコンストラクト シグネチャがない型が含まれる式では 'new' は使用できません。", + "Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files_5056": "複数の入力ファイルで上書きされることになるため、ファイル '{0}' を書き込めません。", + "Cannot_write_file_0_because_it_would_overwrite_input_file_5055": "入力ファイルを上書きすることになるため、ファイル '{0}' を書き込めません。", + "Catch_clause_variable_cannot_have_a_type_annotation_1196": "catch 句の変数に型の注釈を指定することはできません。", + "Catch_clause_variable_cannot_have_an_initializer_1197": "catch 句の変数に初期化子を指定することはできません。", + "Change_0_to_1_90014": "'{0}' を '{1}' に変更する", + "Change_all_extended_interfaces_to_implements_95038": "拡張されたすべてのインターフェイスを 'implements' に変更します", + "Change_all_jsdoc_style_types_to_TypeScript_95030": "jsdoc スタイルのすべての型を TypeScript に変更します", + "Change_all_jsdoc_style_types_to_TypeScript_and_add_undefined_to_nullable_types_95031": "jsdoc スタイルのすべての型を TypeScript に変更します (さらに、'| undefined' を null 許容型に追加します)", + "Change_extends_to_implements_90003": "'extends' を 'implements' に変更する", + "Change_spelling_to_0_90022": "スペルを '{0}' に変更する", + "Checking_if_0_is_the_longest_matching_prefix_for_1_2_6104": "'{0}' が '{1}' - '{2}' の最長一致のプレフィックスであるかを確認しています。", + "Circular_definition_of_import_alias_0_2303": "インポート エイリアス '{0}' の循環定義です。", + "Circularity_detected_while_resolving_configuration_Colon_0_18000": "構成: {0} の解決中に循環が検出されました", + "Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_functi_2426": "クラス '{0}' で定義されたインスタンス メンバー アクセサー '{1}' が、拡張されたクラス '{2}' ではインスタンス メンバー関数として定義されています。", + "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_access_2423": "クラス '{0}' で定義されたインスタンス メンバー関数 '{1}' が、拡張されたクラス '{2}' ではインスタンス メンバー アクセサーとして定義されています。", + "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_proper_2424": "クラス '{0}' で定義されたインスタンス メンバー関数 '{1}' が、拡張されたクラス '{2}' ではインスタンス メンバー プロパティとして定義されています。", + "Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_functi_2425": "クラス '{0}' で定義されたインスタンス メンバー プロパティ '{1}' が、拡張されたクラス '{2}' ではインスタンス メンバー関数として定義されています。", + "Class_0_incorrectly_extends_base_class_1_2415": "クラス '{0}' は基底クラス '{1}' を正しく拡張していません。", + "Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclas_2720": "クラス '{0}' はクラス '{1}' を正しく実装していません。'{1}' を拡張し、そのメンバーをサブクラスとして継承しますか?", + "Class_0_incorrectly_implements_interface_1_2420": "クラス '{0}' はインターフェイス '{1}' を正しく実装していません。", + "Class_0_used_before_its_declaration_2449": "クラス '{0}' は宣言の前に使用されました。", + "Class_declarations_cannot_have_more_than_one_augments_or_extends_tag_8025": "クラス宣言で複数の '@augments' または `@extends` タグを使用することはできません。", + "Class_name_cannot_be_0_2414": "クラス名を '{0}' にすることはできません。", + "Class_name_cannot_be_Object_when_targeting_ES5_with_module_0_2725": "モジュール {0} を使用して ES5 をターゲットとするときに、クラス名を 'オブジェクト' にすることはできません。", + "Class_static_side_0_incorrectly_extends_base_class_static_side_1_2417": "クラス側の静的な '{0}' が基底クラス側の静的な '{1}' を正しく拡張していません。", + "Classes_can_only_extend_a_single_class_1174": "クラスで拡張できるクラスは 1 つのみです。", + "Classes_containing_abstract_methods_must_be_marked_abstract_2514": "抽象メソッドを含むクラスは abstract に指定する必要があります。", + "Command_line_Options_6171": "コマンド ライン オプション", + "Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json_6020": "構成ファイルか、'tsconfig.json' を含むフォルダーにパスが指定されたプロジェクトをコンパイルします。", + "Compiler_option_0_expects_an_argument_6044": "コンパイラ オプション '{0}' には引数が必要です。", + "Compiler_option_0_requires_a_value_of_type_1_5024": "コンパイラ オプション '{0}' には {1} の型の値が必要です。", + "Composite_projects_may_not_disable_declaration_emit_6304": "複合プロジェクトで宣言の生成を無効にすることはできません。", + "Computed_property_names_are_not_allowed_in_enums_1164": "計算されたプロパティ名は列挙型では使用できません。", + "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553": "文字列値のメンバーを持つ列挙型では、計算値は許可されません。", + "Concatenate_and_emit_output_to_single_file_6001": "出力を連結して 1 つのファイルを生成します。", + "Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_librar_4090": "'{0}' の定義が '{1}' および '{2}' で競合しています。競合を解決するには、このライブラリの特定バージョンのインストールをご検討ください。", + "Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7013": "戻り値の型の注釈がないコンストラクト シグネチャの戻り値の型は、暗黙的に 'any' になります。", + "Constructor_implementation_is_missing_2390": "コンストラクターの実装がありません。", + "Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration_2673": "クラス '{0}' のコンストラクターはプライベートであり、クラス宣言内でのみアクセス可能です。", + "Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration_2674": "クラス '{0}' のコンストラクターは保護されており、クラス宣言内でのみアクセス可能です。", + "Constructors_for_derived_classes_must_contain_a_super_call_2377": "派生クラスのコンストラクターには 'super' の呼び出しを含める必要があります。", + "Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126": "包含するファイルが指定されていないため、ルート ディレクトリを決定できません。'node_modules' フォルダーのルックアップをスキップします。", + "Convert_0_to_mapped_object_type_95055": "'{0}' をマップされたオブジェクト型に変換する", + "Convert_all_constructor_functions_to_classes_95045": "すべてのコンストラクター関数をクラスに変換します", + "Convert_all_require_to_import_95048": "'require' をすべて 'import' に変換", + "Convert_all_to_default_imports_95035": "すべてを既定のインポートに変換します", + "Convert_function_0_to_class_95002": "関数 '{0}' をクラスに変換します", + "Convert_function_to_an_ES2015_class_95001": "関数を ES2015 クラスに変換します", + "Convert_named_imports_to_namespace_import_95057": "名前付きインポートを名前空間インポートに変換します", + "Convert_namespace_import_to_named_imports_95056": "名前空間インポートを名前付きインポートに変換します", + "Convert_require_to_import_95047": "'require' を 'import' に変換", + "Convert_to_ES6_module_95017": "ES6 モジュールに変換します", + "Convert_to_default_import_95013": "既定のインポートに変換する", + "Corrupted_locale_file_0_6051": "ロケール ファイル {0} は破損しています。", + "Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type_7016": "モジュール '{0}' の宣言ファイルが見つかりませんでした。'{1}' は暗黙的に 'any' 型になります。", + "Could_not_write_file_0_Colon_1_5033": "ファイル '{0}' を書き込めませんでした: '{1}'。", + "DIRECTORY_6038": "ディレクトリ", + "Declaration_expected_1146": "宣言が必要です。", + "Declaration_name_conflicts_with_built_in_global_identifier_0_2397": "宣言名が組み込みのグローバル識別子 '{0}' と競合しています。", + "Declaration_or_statement_expected_1128": "宣言またはステートメントが必要です。", + "Declare_method_0_90023": "メソッド '{0}' を宣言する", + "Declare_property_0_90016": "プロパティ '{0}' を宣言する", + "Declare_static_method_0_90024": "静的メソッド '{0}' を宣言する", + "Declare_static_property_0_90027": "静的プロパティ '{0}' を宣言する", + "Decorators_are_not_valid_here_1206": "デコレーターはここでは無効です。", + "Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name_1207": "デコレーターを同じ名前の複数の get/set アクセサーに適用することはできません。", + "Default_export_of_the_module_has_or_is_using_private_name_0_4082": "モジュールの既定エクスポートがプライベート名 '{0}' を持っているか、使用しています。", + "Delete_all_unused_declarations_95024": "未使用の宣言をすべて削除します", + "Delete_the_outputs_of_all_projects_6365": "すべてのプロジェクトの出力を削除します", + "Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react__6084": "[非推奨] 代わりに '--jsxFactory' を使います。'react' JSX 発行を対象とするときに、createElement に対して呼び出されたオブジェクトを指定します", + "Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file_6170": "[非推奨] 代わりに '--outFile' を使います。出力を連結して 1 つのファイルを生成します", + "Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files_6160": "[非推奨] 代わりに '--skipLibCheck' を使います。既定のライブラリ宣言ファイルの型チェックをスキップします。", + "Digit_expected_1124": "数値が必要です", + "Directory_0_does_not_exist_skipping_all_lookups_in_it_6148": "ディレクトリ '{0}' は存在していません。ディレクトリ内のすべての参照をスキップしています。", + "Disable_checking_for_this_file_90018": "このファイルのチェックを無効にする", + "Disable_size_limitations_on_JavaScript_projects_6162": "JavaScript プロジェクトのサイズ制限を無効にします。", + "Disable_strict_checking_of_generic_signatures_in_function_types_6185": "関数型の汎用シグネチャに対する厳密なチェックを無効にします。", + "Disallow_inconsistently_cased_references_to_the_same_file_6078": "同じファイルへの大文字小文字の異なる参照を許可しない。", + "Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files_6159": "トリプルスラッシュの参照やインポートしたモジュールをコンパイルされたファイルのリストに追加しないでください。", + "Do_not_emit_comments_to_output_6009": "コメントを出力しないでください。", + "Do_not_emit_declarations_for_code_that_has_an_internal_annotation_6056": "'@internal' の注釈を含むコードの宣言を生成しないでください。", + "Do_not_emit_outputs_6010": "出力しないでください。", + "Do_not_emit_outputs_if_any_errors_were_reported_6008": "エラーが報告される場合は、出力しないでください。", + "Do_not_emit_use_strict_directives_in_module_output_6112": "モジュール出力で 'use strict' ディレクティブを生成しません。", + "Do_not_erase_const_enum_declarations_in_generated_code_6007": "生成されたコード内で const 列挙型宣言を消去しないでください。", + "Do_not_generate_custom_helper_functions_like_extends_in_compiled_output_6157": "コンパイルされた出力で '__extends' などのカスタム ヘルパー関数を生成しないでください。", + "Do_not_include_the_default_library_file_lib_d_ts_6158": "既定のライブラリ ファイル (lib.d.ts) を含めないでください。", + "Do_not_report_errors_on_unreachable_code_6077": "到達できないコードに関するエラーを報告しない。", + "Do_not_report_errors_on_unused_labels_6074": "未使用のラベルに関するエラーを報告しない。", + "Do_not_resolve_the_real_path_of_symlinks_6013": "symlink の実際のパスを解決しません。", + "Do_not_truncate_error_messages_6165": "エラー メッセージを切り捨てないでください。", + "Duplicate_declaration_0_2718": "宣言 '{0}' が重複しています。", + "Duplicate_function_implementation_2393": "関数の実装が重複しています。", + "Duplicate_identifier_0_2300": "識別子 '{0}' が重複しています。", + "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_2441": "識別子 '{0}' が重複しています。コンパイラは、モジュールの最上位のスコープに名前 '{1}' を予約します。", + "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_func_2529": "識別子 '{0}' が重複しています。コンパイラは非同期関数を含むモジュールの最上位のスコープに名前 '{1}' を予約します。", + "Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions_2520": "識別子 '{0}' が重複しています。コンパイラは宣言 '{1}' を使用して非同期関数をサポートします。", + "Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters_2396": "識別子 'arguments' が重複しています。コンパイラは 'arguments' を使用して rest パラメーターを初期化します。", + "Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_me_2543": "識別子 '_newTarget' が重複しています。コンパイラは変数宣言 '_newTarget' を使用して、'new.target' メタプロパティの参照をキャプチャします。", + "Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference_2401": "識別子 '_super' が重複しています。コンパイラは '_super' を使用して基底クラスの参照をキャプチャします。", + "Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference_2399": "識別子 '_this' が重複しています。コンパイラは変数宣言 '_this' を使用して '_this' の参照をキャプチャします。", + "Duplicate_label_0_1114": "ラベル '{0}' が重複しています。", + "Duplicate_number_index_signature_2375": "number インデックス シグネチャが重複しています。", + "Duplicate_string_index_signature_2374": "string インデックス シグネチャが重複しています。", + "Dynamic_import_cannot_have_type_arguments_1326": "動的インポートには型引数を指定することはできません", + "Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext_1323": "動的インポートがサポートされるのは、'--module' フラグが 'commonjs' または 'esNext' の場合のみです。", + "Dynamic_import_must_have_one_specifier_as_an_argument_1324": "動的インポートには、引数として 1 つの指定子を指定する必要があります。", + "Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036": "動的インポートの指定子の型は 'string' である必要がありますが、ここでは型 '{0}' が指定されています。", + "Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015": "インデックス式が型 'number' ではないため、要素に 'any' 型が暗黙的に指定されます。", + "Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature_7017": "型 '{0}' にはインデックス シグネチャがないため、要素は暗黙的に 'any' 型になります。", + "Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files_6164": "出力ファイルの最初に UTF-8 バイト順マーク(BOM) を生成します。", + "Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file_6151": "個々のファイルを持つ代わりに、複数のソース マップを含む単一ファイルを生成します。", + "Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap__6152": "単一ファイル内で sourcemap と共にソースを生成します。'--inlineSourceMap' または '--sourceMap' を設定する必要があります。", + "Enable_all_strict_type_checking_options_6180": "厳密な型チェックのオプションをすべて有効にします。", + "Enable_project_compilation_6302": "プロジェクトのコンパイルを有効にします", + "Enable_strict_checking_of_function_types_6186": "関数の型の厳密なチェックを有効にします。", + "Enable_strict_checking_of_property_initialization_in_classes_6187": "クラス内のプロパティの初期化の厳密なチェックを有効にします。", + "Enable_strict_null_checks_6113": "厳格な null チェックを有効にします。", + "Enable_tracing_of_the_name_resolution_process_6085": "名前解決の処理のトレースを有効にします。", + "Enable_verbose_logging_6366": "詳細ログを有効にします", + "Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for__7037": "すべてのインポートの名前空間オブジェクトを作成して、CommonJS と ES モジュール間の生成の相互運用性を有効にします。'allowSyntheticDefaultImports' を暗黙のうちに表します。", + "Enables_experimental_support_for_ES7_async_functions_6068": "ES7 非同期関数用の実験的なサポートを有効にします。", + "Enables_experimental_support_for_ES7_decorators_6065": "ES7 デコレーター用の実験的なサポートを有効にします。", + "Enables_experimental_support_for_emitting_type_metadata_for_decorators_6066": "デコレーター用の型メタデータを発行するための実験的なサポートを有効にします。", + "Enum_0_used_before_its_declaration_2450": "列挙型 '{0}' は宣言の前に使用されました。", + "Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations_2567": "列挙型の宣言は、名前空間または他の列挙型の宣言とのみマージできます。", + "Enum_declarations_must_all_be_const_or_non_const_2473": "列挙型宣言は、すべてが定数、またはすべてが非定数でなければなりません。", + "Enum_member_expected_1132": "列挙型メンバーが必要です。", + "Enum_member_must_have_initializer_1061": "列挙型メンバーには初期化子が必要です。", + "Enum_name_cannot_be_0_2431": "列挙型の名前を '{0}' にすることはできません。", + "Enum_type_0_has_members_with_initializers_that_are_not_literals_2535": "列挙型 '{0}' に、リテラルではない初期化子を持つメンバーがあります。", + "Examples_Colon_0_6026": "例: {0}", + "Excessive_stack_depth_comparing_types_0_and_1_2321": "型 '{0}' と '{1}' を比較するスタックが深すぎます。", + "Expected_0_1_type_arguments_provide_these_with_an_extends_tag_8027": "{0}-{1} 型の引数が必要です。'@extends' タグで指定してください。", + "Expected_0_arguments_but_got_1_2554": "{0} 個の引数が必要ですが、{1} 個指定されました。", + "Expected_0_arguments_but_got_1_or_more_2556": "{0} 個の引数が必要ですが、{1} 個以上指定されました。", + "Expected_0_type_arguments_but_got_1_2558": "{0} 個の型引数が必要ですが、{1} 個が指定されました。", + "Expected_0_type_arguments_provide_these_with_an_extends_tag_8026": "{0} 型の引数が必要です。'@extends' タグで指定してください。", + "Expected_at_least_0_arguments_but_got_1_2555": "最低でも {0} 個の引数が必要ですが、{1} 個指定されました。", + "Expected_at_least_0_arguments_but_got_1_or_more_2557": "最低でも {0} 個の引数が必要ですが、{1} 個以上指定されました。", + "Expected_corresponding_JSX_closing_tag_for_0_17002": "'{0}' の対応する JSX 終了タグが必要です。", + "Expected_corresponding_closing_tag_for_JSX_fragment_17015": "JSX フラグメントの対応する終了タグが必要です。", + "Expected_type_of_0_field_in_package_json_to_be_string_got_1_6105": "'package.json' の '{0}' フィールドの型は 'string' であるべきですが、'{1}' を取得しました。", + "Experimental_Options_6177": "試験的なオプション", + "Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_t_1219": "デコレーターの実験的なサポートは将来のリリースで変更になる可能性がある機能です。'experimentalDecorators' オプションを設定してこの警告を削除します。", + "Explicitly_specified_module_resolution_kind_Colon_0_6087": "明示的に指定されたモジュール解決の種類 '{0}'。", + "Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or__1203": "ECMAScript モジュールを対象にする場合は、エクスポート割り当てを使用できません。代わりに 'export default' または別のモジュール書式の使用をご検討ください。", + "Export_assignment_is_not_supported_when_module_flag_is_system_1218": "割り当てのエクスポートは、'--module' フラグが 'system' の場合にはサポートされません。", + "Export_declaration_conflicts_with_exported_declaration_of_0_2484": "エクスポート宣言が、'{0}' のエクスポートされた宣言と競合しています。", + "Export_declarations_are_not_permitted_in_a_namespace_1194": "エクスポート宣言は名前空間でサポートされません。", + "Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_2656": "エクスポートされた外部パッケージの型指定のファイル '{0}' はモジュールではありません。パッケージ定義を更新する場合は、パッケージの作成者にお問い合わせください。", + "Exported_external_package_typings_file_cannot_contain_tripleslash_references_Please_contact_the_pack_2654": "エクスポートされた外部パッケージの型指定のファイルにトリプルスラッシュ参照を含めることはできません。パッケージ定義を更新する場合は、パッケージの作成者にお問い合わせください。", + "Exported_type_alias_0_has_or_is_using_private_name_1_4081": "エクスポートされた型のエイリアス '{0}' にプライベート名 '{1}' が付いているか、その名前を使用しています。", + "Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4023": "エクスポートされた変数 '{0}' が外部モジュール {2} の名前 '{1}' を持っているか使用していますが、名前を指定することはできません。", + "Exported_variable_0_has_or_is_using_name_1_from_private_module_2_4024": "エクスポートされた変数 '{0}' がプライベート モジュール '{2}' の名前 '{1}' を持っているか、使用しています。", + "Exported_variable_0_has_or_is_using_private_name_1_4025": "エクスポートされた変数 '{0}' がプライベート名 '{1}' を持っているか、使用しています。", + "Exports_and_export_assignments_are_not_permitted_in_module_augmentations_2666": "エクスポートとエクスポートの割り当てはモジュールの拡張では許可されていません。", + "Expression_expected_1109": "式が必要です。", + "Expression_or_comma_expected_1137": "式またはコンマが必要です。", + "Expression_resolves_to_super_that_compiler_uses_to_capture_base_class_reference_2402": "式は、コンパイラが基底クラスの参照をキャプチャするために使用する '_super' に解決されます。", + "Expression_resolves_to_variable_declaration_0_that_compiler_uses_to_support_async_functions_2521": "式は、コンパイラが非同期関数をサポートするために使用する変数宣言 '{0}' に解決されます。", + "Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta__2544": "式は、コンパイラが 'new.target' メタプロパティの参照をキャプチャするために使用する変数宣言 '_newTarget' に解決されます。", + "Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference_2400": "式は、コンパイラが 'this' の参照をキャプチャするために使用する変数宣言 '_this' に解決されます。", + "Extract_constant_95006": "定数の抽出", + "Extract_function_95005": "関数の抽出", + "Extract_to_0_in_1_95004": "{1} 内の {0} に抽出する", + "Extract_to_0_in_1_scope_95008": "{1} スコープ内の {0} に抽出する", + "Extract_to_0_in_enclosing_scope_95007": "外側のスコープ内の {0} に抽出する", + "FILE_6035": "ファイル", + "FILE_OR_DIRECTORY_6040": "ファイルまたはディレクトリ", + "Failed_to_parse_file_0_Colon_1_5014": "ファイル '{0}' を解析できませんでした。{1}。", + "Fallthrough_case_in_switch_7029": "switch に case のフォールスルーがあります。", + "File_0_does_not_exist_6096": "ファイル '{0}' が存在しません。", + "File_0_exist_use_it_as_a_name_resolution_result_6097": "ファイル '{0}' が存在します。名前解決の結果として使用します。", + "File_0_has_an_unsupported_extension_so_skipping_it_6081": "ファイル '{0}' にはサポートされていない拡張機能があるため、スキップしています。", + "File_0_has_unsupported_extension_The_only_supported_extensions_are_1_6054": "ファイル '{0}' はサポートされていない拡張子を含んでいます。サポートされている拡張子は {1} のみです。", + "File_0_is_not_a_module_2306": "ファイル '{0}' はモジュールではありません。", + "File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern_6307": "ファイル '{0}' がプロジェクト ファイル リストに含まれていません。プロジェクトではすべてのファイルをリストするか、'include' パターンを使用する必要があります。", + "File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files_6059": "ファイル '{0}' が 'rootDir' '{1}' の下にありません。'rootDir' にすべてにソース ファイルが含まれている必要があります。", + "File_0_not_found_6053": "ファイル '{0}' が見つかりません。", + "File_change_detected_Starting_incremental_compilation_6032": "ファイルの変更が検出されました。インクリメンタル コンパイルを開始しています...", + "File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module_80001": "ファイルは CommonJS モジュールです。ES6 モジュールに変換される可能性があります。", + "File_name_0_differs_from_already_included_file_name_1_only_in_casing_1149": "ファイル名 '{0}' は、既に含まれているファイル名 '{1}' と大文字と小文字の指定だけが異なります。", + "File_name_0_has_a_1_extension_stripping_it_6132": "ファイル名 '{0}' に '{1}' 拡張子が使われています - 削除しています。", + "File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildca_5065": "ファイルの指定で再帰ディレクトリのワイルドカード ('**') の後に親ディレクトリ ('..') を指定することはできません: '{0}'。", + "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010": "ファイルの指定の末尾を再帰的なディレクトリのワイルドカード ('**') にすることはできません: '{0}'。", + "Fix_all_detected_spelling_errors_95026": "検出されたすべてのスペル ミスを修正します", + "Found_0_errors_Watching_for_file_changes_6194": "{0} 件のエラーが見つかりました。ファイルの変更をモニタリングしています。", + "Found_1_error_Watching_for_file_changes_6193": "1 件のエラーが見つかりました。ファイルの変更をモニタリングしています。", + "Found_package_json_at_0_6099": "'{0}' で 'package.json' が見つかりました。", + "Found_package_json_at_0_Package_ID_is_1_6190": "'{0}' で 'package.json' が見つかりました。パッケージ ID は、'{1}' です。", + "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_1250": "'ES3' または 'ES5' を対象としている場合、関数宣言は厳格モードのブロック内では許可されていません。", + "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_d_1251": "'ES3' または 'ES5' を対象としている場合、関数宣言は厳格モードのブロック内では許可されていません。クラス定義は自動的に厳格モードになります。", + "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_1252": "'ES3' または 'ES5' を対象としている場合、関数宣言は厳格モードのブロック内では許可されていません。モジュールは自動的に厳格モードになります。", + "Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type_7011": "戻り値の型の注釈がない関数式の戻り値の型は、暗黙的に '{0}' になります。", + "Function_implementation_is_missing_or_not_immediately_following_the_declaration_2391": "関数の実装がないか、宣言の直後に指定されていません。", + "Function_implementation_name_must_be_0_2389": "関数の実装名は '{0}' でなければなりません。", + "Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_ref_7024": "関数は、戻り値の型の注釈がなく、いずれかの return 式で直接的にまたは間接的に参照されているため、戻り値の型は暗黙的に 'any' になります。", + "Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined_2366": "関数に終了の return ステートメントがないため、戻り値の型には 'undefined' が含まれません。", + "Function_overload_must_be_static_2387": "関数のオーバーロードは静的でなければなりません。", + "Function_overload_must_not_be_static_2388": "関数のオーバーロードは静的にはできせん。", + "Generate_get_and_set_accessors_95046": "'get' および 'set' アクセサーの生成", + "Generates_a_sourcemap_for_each_corresponding_d_ts_file_6000": "対応する各 '.d.ts' ファイルに sourcemap を生成します。", + "Generates_corresponding_d_ts_file_6002": "対応する '.d.ts' ファイルを生成します。", + "Generates_corresponding_map_file_6043": "対応する '.map' ファイルを生成します。", + "Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_typ_7025": "ジェネレーターは値を生成しないため、暗黙的に型 '{0}' になります。戻り値の型を指定することを検討してください。", + "Generators_are_not_allowed_in_an_ambient_context_1221": "ジェネレーターは環境コンテキストでは使用できません。", + "Generators_are_only_available_when_targeting_ECMAScript_2015_or_higher_1220": "ジェネレーターは、ECMAScript 2015 以上を対象にする場合のみ使用できます。", + "Generic_type_0_requires_1_type_argument_s_2314": "ジェネリック型 '{0}' には {1} 個の型引数が必要です。", + "Generic_type_0_requires_between_1_and_2_type_arguments_2707": "ジェネリック型 '{0}' には、{1} 個から {2} 個までの型引数が必要です。", + "Generic_type_instantiation_is_excessively_deep_and_possibly_infinite_2550": "ジェネリック型のインスタンス化は非常に深く、無限である可能性があります。", + "Getter_and_setter_accessors_do_not_agree_in_visibility_2379": "ゲッターおよびセッターで表示が許可されていません。", + "Global_module_exports_may_only_appear_at_top_level_1316": "グローバル モジュールのエクスポートは最上位レベルにのみ出現可能です。", + "Global_module_exports_may_only_appear_in_declaration_files_1315": "グローバル モジュールのエクスポートは宣言ファイルにのみ出現可能です。", + "Global_module_exports_may_only_appear_in_module_files_1314": "グローバル モジュールのエクスポートはモジュール ファイルにのみ出現可能です。", + "Global_type_0_must_be_a_class_or_interface_type_2316": "グローバル型 '{0}' はクラス型またはインターフェイス型でなければなりません。", + "Global_type_0_must_have_1_type_parameter_s_2317": "グローバル型 '{0}' には {1} 個の型パラメーターが必要です。", + "Hexadecimal_digit_expected_1125": "16 進の数字が必要です。", + "Identifier_expected_0_is_a_reserved_word_in_strict_mode_1212": "識別子が必要です。'{0}' は厳格モードの予約語です。", + "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_stric_1213": "識別子が必要です。'{0}' は厳格モードの予約語です。クラス定義は自動的に厳格モードになります。", + "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode_1214": "識別子が必要です。'{0}' は、厳格モードの予約語です。モジュールは自動的に厳格モードになります。", + "Identifier_expected_1003": "識別子が必要です。", + "Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules_1216": "識別子が必要です。'__esModule' は、ECMAScript モジュールを変換するときのエクスポート済みマーカーとして予約されています。", + "Ignore_this_error_message_90019": "このエラー メッセージを無視する", + "Implement_all_inherited_abstract_classes_95040": "継承されたすべての抽象クラスを実装します", + "Implement_all_unimplemented_interfaces_95032": "実装されていないすべてのインターフェイスを実装します", + "Implement_inherited_abstract_class_90007": "継承抽象クラスを実装する", + "Implement_interface_0_90006": "インターフェイス '{0}' を実装する", + "Implements_clause_of_exported_class_0_has_or_is_using_private_name_1_4019": "エクスポートされたクラス '{0}' の Implements 句がプライベート名 '{1}' を持っているか、使用しています。", + "Import_0_from_module_1_90013": "モジュール \"{1}\" から '{0}' をインポートする", + "Import_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_import_Asterisk_as_1202": "ECMAScript モジュールを対象にする場合は、インポート割り当てを使用できません。代わりに 'import * as ns from \"mod\"'、'import {a} from \"mod\"'、'import d from \"mod\"' などのモジュール書式の使用をご検討ください。", + "Import_declaration_0_is_using_private_name_1_4000": "インポート宣言 '{0}' がプライベート名 '{1}' を使用しています。", + "Import_declaration_conflicts_with_local_declaration_of_0_2440": "インポート宣言が、'{0}' のローカル宣言と競合しています。", + "Import_declarations_in_a_namespace_cannot_reference_a_module_1147": "名前空間内のインポート宣言は、モジュールを参照できません。", + "Import_emit_helpers_from_tslib_6139": "生成ヘルパーを 'tslib' からインポートします。", + "Import_may_be_converted_to_a_default_import_80003": "インポートは既定のインポートに変換される可能性があります。", + "Import_name_cannot_be_0_2438": "インポート名を '{0}' にすることはできません。", + "Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relati_2439": "アンビエント モジュール宣言内のインポート宣言またはエクスポート宣言は、相対モジュール名を通してモジュールを参照することはできません。", + "Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_mod_2667": "インポートはモジュールの拡張では許可されていません。外側の外部モジュールに移動することを検討してください。", + "In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066": "アンビエント列挙型の宣言では、メンバー初期化子は定数式である必要があります。", + "In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enu_2432": "複数の宣言がある列挙型で、最初の列挙要素の初期化子を省略できる宣言は 1 つのみです。", + "In_const_enum_declarations_member_initializer_must_be_constant_expression_2474": "'const' 列挙型の宣言で、メンバー初期化子は定数式でなければなりません。", + "Include_modules_imported_with_json_extension_6197": "'.json' 拡張子付きのインポートされたモジュールを含める", + "Index_signature_in_type_0_only_permits_reading_2542": "型 '{0}' のインデックス シグネチャは、読み取りのみを許可します。", + "Index_signature_is_missing_in_type_0_2329": "型 '{0}' のインデックス シグネチャがありません。", + "Index_signatures_are_incompatible_2330": "インデックスの署名に互換性がありません。", + "Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local_2395": "マージされた宣言 '{0}' の個々の宣言はすべてエクスポートされるか、すべてローカルであるかのどちらかである必要があります。", + "Infer_all_types_from_usage_95023": "使用法からすべての型を推論します", + "Infer_parameter_types_from_usage_95012": "使用状況からパラメーターの型を推論する", + "Infer_type_of_0_from_usage_95011": "使用状況から '{0}' の型を推論する", + "Initialize_property_0_in_the_constructor_90020": "コンストラクターのプロパティ '{0}' を初期化する", + "Initialize_static_property_0_90021": "静的プロパティ '{0}' を初期化する", + "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301": "インスタンス メンバー変数 '{0}' の初期化子はコンストラクターで宣言された識別子 '{1}' を参照できません。", + "Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it_2373": "パラメーター '{0}' の初期化子はその後で宣言された識別子 '{1}' を参照できません。", + "Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value_2525": "初期化子にこのバインド要素の値が提示されていません。またバインド要素に既定値がありません。", + "Initializers_are_not_allowed_in_ambient_contexts_1039": "初期化子は環境コンテキストでは使用できません。", + "Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file_6070": "TypeScript プロジェクトを初期化して、tsconfig.json ファイルを作成します。", + "Insert_command_line_options_and_files_from_a_file_6030": "コマンド ライン オプションとファイルをファイルから挿入します。", + "Install_0_95014": "'{0}' のインストール", + "Install_all_missing_types_packages_95033": "不足しているすべての型のパッケージをインストールします", + "Interface_0_cannot_simultaneously_extend_types_1_and_2_2320": "インターフェイス '{0}' で型 '{1}' と型 '{2}' を同時には拡張できません。", + "Interface_0_incorrectly_extends_interface_1_2430": "インターフェイス '{0}' はインターフェイス '{1}' を正しく拡張していません。", + "Interface_declaration_cannot_have_implements_clause_1176": "インターフェイス宣言に 'implements' 句を指定することはできません。", + "Interface_name_cannot_be_0_2427": "インターフェイス名を '{0}' にすることはできません。", + "Invalid_character_1127": "無効な文字です。", + "Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augm_2665": "拡張のモジュール名が無効です。モジュール '{0}' は '{1}' の型指定のないモジュールに解決されるため、拡張されません。", + "Invalid_module_name_in_augmentation_module_0_cannot_be_found_2664": "拡張のモジュール名が無効です。モジュール '{0}' が見つかりません。", + "Invalid_reference_directive_syntax_1084": "無効な 'reference' ディレクティブ構文です。", + "Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode_1210": "'{0}' の使用が無効です。クラス定義は自動的に厳格モードになります。", + "Invalid_use_of_0_Modules_are_automatically_in_strict_mode_1215": "'{0}' の使用方法が無効です。モジュールは自動的に厳格モードになります。", + "Invalid_use_of_0_in_strict_mode_1100": "厳格モードでは '{0}' の使用は無効です。", + "Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name_5067": "'jsxFactory' の値が無効です。'{0}' が有効な識別子または修飾名ではありません。", + "Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier_5059": "'--reactNamespace' の値が無効です。'{0}' は有効な識別子ではありません。", + "JSDoc_0_1_does_not_match_the_extends_2_clause_8023": "JSDoc '@{0} {1}' が 'extends {2}' 句と一致しません。", + "JSDoc_0_is_not_attached_to_a_class_8022": "JSDoc '@{0}' はクラスにアタッチされていません。", + "JSDoc_may_only_appear_in_the_last_parameter_of_a_signature_8028": "JSDoc '...' は、シグネチャの最後のパラメーターにのみ使用できます。", + "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_8024": "JSDoc '@param' タグの名前は '{0}' ですが、その名前のパラメーターはありません。", + "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_h_8029": "JSDoc '@param' タグに名前 '{0}' が指定されていますが、その名前のパラメーターはありません。配列型があった場合は、'arguments' と一致したはずです。", + "JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags_8021": "JSDoc '@typedef' タグには、型の注釈を指定するか、後に '@property' タグや '@member' タグを付ける必要があります。", + "JSDoc_types_can_only_be_used_inside_documentation_comments_8020": "JSDoc の種類は、ドキュメント コメント内でのみ使用できます。", + "JSDoc_types_may_be_moved_to_TypeScript_types_80004": "JSDoc の種類は TypeScript の種類に移行される可能性があります。", + "JSX_attribute_expected_17003": "JSX 属性が必要です。", + "JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000": "JSX 属性は、空ではない '式' にのみ割り当てる必要があります。", + "JSX_element_0_has_no_corresponding_closing_tag_17008": "JSX 要素 '{0}' には対応する終了タグがありません。", + "JSX_element_attributes_type_0_may_not_be_a_union_type_2600": "JSX 要素属性の型 '{0}' は共用体型ではありません。", + "JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property_2607": "JSX 要素クラスは '{0}' プロパティを含まないため、属性をサポートしません。", + "JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists_7026": "インターフェイス 'JSX.{0}' が存在しないため、暗黙的に JSX 要素の型は 'any' になります。", + "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602": "グローバル型 'JSX.Element' が存在しないため、JSX 要素は暗黙的に型 'any' になります。", + "JSX_element_type_0_does_not_have_any_construct_or_call_signatures_2604": "JSX 要素型 '{0}' にはコンストラクトも呼び出しシグネチャも含まれていません。", + "JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements_2605": "JSX 要素型 '{0}' は JSX 要素のコンストラクター関数ではありません。", + "JSX_elements_cannot_have_multiple_attributes_with_the_same_name_17001": "JSX 要素に同じ名前の複数の属性を指定することはできません。", + "JSX_expressions_must_have_one_parent_element_2657": "JSX 式には 1 つの親要素が必要です。", + "JSX_fragment_has_no_corresponding_closing_tag_17014": "JSX フラグメントには対応する終了タグがありません。", + "JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma_17017": "JSX フラグメントはインライン JSX ファクトリ プラグマの使用時にサポートされていません", + "JSX_fragment_is_not_supported_when_using_jsxFactory_17016": "--jsxFactory を使う場合、JSX フラグメントはサポートされません", + "JSX_spread_child_must_be_an_array_type_2609": "JSX スプレッドの子は、配列型でなければなりません。", + "Jump_target_cannot_cross_function_boundary_1107": "ジャンプ先は関数の境界を越えることはできません。", + "KIND_6034": "種類", + "LOCATION_6037": "場所", + "Language_service_is_disabled_9004": "言語サービスが無効になっています。", + "Left_side_of_comma_operator_is_unused_and_has_no_side_effects_2695": "コンマ演算子の左側が使用されていないため、副作用はありません。", + "Line_break_not_permitted_here_1142": "ここで改行することはできません。", + "Line_terminator_not_permitted_before_arrow_1200": "行の終端記号をアローの前で使用することはできません。", + "List_of_folders_to_include_type_definitions_from_6161": "含める型定義の元のフォルダーの一覧。", + "List_of_language_service_plugins_6181": "言語サービス プラグインの一覧。", + "List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime_6168": "結合されたコンテンツがランタイムでのプロジェクトの構成を表すルート フォルダーの一覧。", + "Loading_0_from_the_root_dir_1_candidate_location_2_6109": "ルート ディレクトリ '{1}' から '{0}' を読み込んでいます。候補の場所は '{2}' です。", + "Loading_module_0_from_node_modules_folder_target_file_type_1_6098": "'node_modules' フォルダーからモジュール '{0}' を読み込んでいます。対象のファイルの種類は '{1}' です。", + "Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1_6095": "ファイル / フォルダーとしてモジュールを読み込んでいます。候補のモジュールの場所は '{0}'、対象のファイルの種類は '{1}' です。", + "Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1_6048": "ロケールは または - の形式で指定する必要があります (例: '{0}'、'{1}')。", + "Longest_matching_prefix_for_0_is_1_6108": "'{0}' の一致する最長プレフィックスは '{1}' です。", + "Looking_up_in_node_modules_folder_initial_location_0_6125": "'node_modules' フォルダーを検索しています。最初の場所は '{0}' です。", + "Make_all_super_calls_the_first_statement_in_their_constructor_95036": "すべての 'super()' 呼び出しをそのコンストラクターの最初のステートメントにします", + "Make_super_call_the_first_statement_in_the_constructor_90002": "'super()' 呼び出しをコンストラクター内の最初のステートメントにする", + "Mapped_object_type_implicitly_has_an_any_template_type_7039": "マップされたオブジェクト型のテンプレートの型は暗黙的に 'any' になります。", + "Member_0_implicitly_has_an_1_type_7008": "メンバー '{0}' の型は暗黙的に '{1}' になります。", + "Merge_conflict_marker_encountered_1185": "マージ競合マーカーが検出されました。", + "Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_d_2652": "マージされた宣言 '{0}' に既定のエクスポート宣言を含めることはできません。代わりに、'export default {0}' 宣言を別個に追加することを検討してください。", + "Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constru_17013": "メタプロパティ '{0}' は、関数の宣言の本文、関数の式、またはコンストラクターでのみ許可されています。", + "Method_0_cannot_have_an_implementation_because_it_is_marked_abstract_1245": "メソッド '{0}' は abstract に指定されているため、実装を含めることができません。", + "Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4101": "エクスポートされたインターフェイスのメソッド '{0}' が、プライベート モジュール '{2}' の名前 '{1}' を持っているか、使用しています。", + "Method_0_of_exported_interface_has_or_is_using_private_name_1_4102": "エクスポートされたインターフェイスのメソッド '{0}' がプライベート名 '{1}' を持っているか、使用しています。", + "Modifiers_cannot_appear_here_1184": "ここで修飾子を使用することはできません。", + "Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_1340": "モジュール '{0}' は型を参照していませんが、ここでは型として使用されています。", + "Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here_1339": "モジュール '{0}' は値を参照していませんが、ここでは値として使用されています。", + "Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambig_2308": "モジュール {0} は既に '{1}' という名前のメンバーをエクスポートしています。あいまいさを解決するため、明示的にもう一度エクスポートすることを検討してください。", + "Module_0_has_no_default_export_1192": "モジュール '{0}' に既定エクスポートがありません。", + "Module_0_has_no_exported_member_1_2305": "モジュール '{0}' にエクスポートされたメンバー '{1}' がありません。", + "Module_0_has_no_exported_member_1_Did_you_mean_2_2724": "モジュール '{0}' にエクスポートされたメンバー '{1}' が含まれていません。候補: '{2}'", + "Module_0_is_hidden_by_a_local_declaration_with_the_same_name_2437": "モジュール '{0}' は同じ名前のローカル宣言によって非表示になっています。", + "Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct_2497": "モジュール '{0}' はモジュール以外のエンティティに解決されるため、このコンストラクトを使用してインポートできません。", + "Module_0_uses_export_and_cannot_be_used_with_export_Asterisk_2498": "モジュール '{0}' には 'export =' が使用されているため、'export *' は併用できません。", + "Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified_6145": "このファイルが変更されなかったため、モジュール '{0}' は '{1}' で宣言されたアンビエント モジュールとして解決されました。", + "Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1_6144": "モジュール '{0}' は、ファイル '{1}' のローカルで宣言されたアンビエント モジュールとして解決されました。", + "Module_0_was_resolved_to_1_but_jsx_is_not_set_6142": "モジュール '{0}' は '{1}' に解決されましたが、'--jsx' が設定されていません。", + "Module_Resolution_Options_6174": "モジュール解決のオプション", + "Module_name_0_matched_pattern_1_6092": "モジュール名 '{0}'、照合されたパターン '{1}'。", + "Module_name_0_was_not_resolved_6090": "======== モジュール名 '{0}' が解決されませんでした。========", + "Module_name_0_was_successfully_resolved_to_1_6089": "======== モジュール名 '{0}' が正常に '{1}' に解決されました。========", + "Module_resolution_kind_is_not_specified_using_0_6088": "モジュール解決の種類が '{0}' を使用して指定されていません。", + "Module_resolution_using_rootDirs_has_failed_6111": "'rootDirs' を使用したモジュール解決が失敗しました。", + "Move_to_a_new_file_95049": "新しいファイルへ移動します", + "Multiple_consecutive_numeric_separators_are_not_permitted_6189": "複数の連続した数値区切り記号を指定することはできません。", + "Multiple_constructor_implementations_are_not_allowed_2392": "コンストラクターを複数実装することはできません。", + "NEWLINE_6061": "改行", + "Named_property_0_of_types_1_and_2_are_not_identical_2319": "'{1}' 型および '{2}' 型の名前付きプロパティ '{0}' が一致しません。", + "Namespace_0_has_no_exported_member_1_2694": "名前空間 '{0}' にエクスポートされたメンバー '{1}' がありません。", + "No_base_constructor_has_the_specified_number_of_type_arguments_2508": "指定した数の型引数を持つ基底コンストラクターは存在しません。", + "No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2_18003": "構成ファイル '{0}' で入力が見つかりませんでした。指定された 'include' パスは '{1}' で、'exclude' パスは '{2}' でした。", + "Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2_2515": "非抽象クラス '{0}' はクラス '{2}' からの継承抽象メンバー '{1}' を実装しません。", + "Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1_2653": "非抽象クラスの式はクラス '{1}' からの継承抽象メンバー '{0}' を実装しません。", + "Not_all_code_paths_return_a_value_7030": "一部のコード パスは値を返しません。", + "Numeric_index_type_0_is_not_assignable_to_string_index_type_1_2413": "数値インデックス型 '{0}' を文字列インデックス型 '{1}' に割り当てることはできません。", + "Numeric_separators_are_not_allowed_here_6188": "数値の区切り記号は、ここでは使用できません。", + "Object_is_of_type_unknown_2571": "オブジェクト型は 'unknown' です。", + "Object_is_possibly_null_2531": "オブジェクトは 'null' である可能性があります。", + "Object_is_possibly_null_or_undefined_2533": "オブジェクトは 'null' か 'undefined' である可能性があります。", + "Object_is_possibly_undefined_2532": "オブジェクトは 'undefined' である可能性があります。", + "Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1_2353": "オブジェクト リテラルは既知のプロパティのみ指定できます。'{0}' は型 '{1}' に存在しません。", + "Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_writ_2561": "オブジェクト リテラルで指定できるのは既知のプロパティのみですが、'{0}' は型 '{1}' に存在しません。書こうとしたのは '{2}' ですか?", + "Object_literal_s_property_0_implicitly_has_an_1_type_7018": "オブジェクト リテラルのプロパティ '{0}' の型は暗黙的に '{1}' になります。", + "Octal_digit_expected_1178": "8 進の数字が必要です。", + "Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0_8017": "8 進数のリテラル型には、ES2015 構文を使用する必要があります。構文 '{0}' を使用してください。", + "Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0_8018": "8 進数のリテラルは、列挙型メンバーの初期化子では許可されていません。構文 '{0}' を使用してください。", + "Octal_literals_are_not_allowed_in_strict_mode_1121": "厳格モードでは Octal リテラルは使用できません。", + "Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0_1085": "ECMAScript 5 以降を対象にする場合、8 進数のリテラルは使用できません。構文 '{0}' を使用してください。", + "Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement_1091": "'for...in' ステートメントで使用できる変数宣言は 1 つのみです。", + "Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement_1188": "'for...of' ステートメントで使用できる変数宣言は 1 つのみです。", + "Only_a_void_function_can_be_called_with_the_new_keyword_2350": "'new' キーワードを指定して呼び出せるのは void 関数のみです。", + "Only_ambient_modules_can_use_quoted_names_1035": "引用符付きの名前を使用できるのはアンビエント モジュールのみです。", + "Only_amd_and_system_modules_are_supported_alongside_0_6082": "--{0} と共にサポートされるのは 'amd' モジュールと 'system' モジュールのみです。", + "Only_emit_d_ts_declaration_files_6014": "'.d.ts' 宣言ファイルのみを生成します。", + "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002": "クラス 'extends' 句で現在サポートされているのは、オプションの型引数が指定された ID/完全修飾名のみです。", + "Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword_2340": "'super' キーワードを使用してアクセスできるのは、基底クラスのパブリック メソッドと保護されたメソッドのみです。", + "Operator_0_cannot_be_applied_to_types_1_and_2_2365": "演算子 '{0}' を型 '{1}' および '{2}' に適用することはできません。", + "Option_0_can_only_be_specified_in_tsconfig_json_file_6064": "オプション '{0}' は 'tsconfig.json' ファイルにのみ指定できます。", + "Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided_5051": "オプション '{0} を使用できるのは、オプション '--inlineSourceMap' またはオプション '--sourceMap' のいずれかを指定した場合のみです。", + "Option_0_cannot_be_specified_with_option_1_5053": "オプション '{0}' をオプション '{1}' とともに指定することはできません。", + "Option_0_cannot_be_specified_without_specifying_option_1_5052": "オプション '{1}' を指定せずに、オプション '{0}' を指定することはできません。", + "Option_0_cannot_be_specified_without_specifying_option_1_or_option_2_5069": "オプション '{1}' またはオプション '{2}' を指定せずに、オプション '{0}' を指定することはできません。", + "Option_0_should_have_array_of_strings_as_a_value_6103": "オプション '{0}' には、値として文字列の配列を指定する必要があります。", + "Option_build_must_be_the_first_command_line_argument_6369": "オプション '--build' は最初のコマンド ライン引数である必要があります。", + "Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES_5047": "オプション 'isolatedModules' は、オプション '--module' が指定されているか、オプション 'target' が 'ES2015' 以上であるかのいずれかの場合でのみ使用できます。", + "Option_paths_cannot_be_used_without_specifying_baseUrl_option_5060": "オプション 'paths' は、'--baseUrl' オプションを指定せずに使用できません。", + "Option_project_cannot_be_mixed_with_source_files_on_a_command_line_5042": "オプション 'project' をコマンド ライン上でソース ファイルと一緒に指定することはできません。", + "Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070": "'node' モジュールの解決方法を使用せずにオプション '--resolveJsonModule' を指定することはできません。", + "Options_0_and_1_cannot_be_combined_6370": "オプション '{0}' と '{1}' を組み合わせることはできません。", + "Options_Colon_6027": "オプション:", + "Output_directory_for_generated_declaration_files_6166": "生成された宣言ファイルの出力ディレクトリ。", + "Output_file_0_from_project_1_does_not_exist_6309": "プロジェクト '{1}' からの出力ファイル '{0}' がありません", + "Output_file_0_has_not_been_built_from_source_file_1_6305": "出力ファイル '{0}' はソース ファイル '{1}' からビルドされていません。", + "Overload_signature_is_not_compatible_with_function_implementation_2394": "オーバーロード シグネチャは関数の実装に対応していません。", + "Overload_signatures_must_all_be_abstract_or_non_abstract_2512": "オーバーロードのシグネチャはすべてが抽象または非抽象である必要があります。", + "Overload_signatures_must_all_be_ambient_or_non_ambient_2384": "オーバーロードのシグネチャは、すべてアンビエントであるか、すべてアンビエントでないかのどちらかである必要があります。", + "Overload_signatures_must_all_be_exported_or_non_exported_2383": "オーバーロードのシグネチャはすべてがエクスポート済みであるか、またはエクスポート済みでない必要があります。", + "Overload_signatures_must_all_be_optional_or_required_2386": "オーバーロードのシグネチャは、すべて省略可能であるか、すべて必須であるかのどちらかである必要があります。", + "Overload_signatures_must_all_be_public_private_or_protected_2385": "オーバーロードのシグネチャはすべて、public、private、または protected でなければなりません。", + "Parameter_0_cannot_be_referenced_in_its_initializer_2372": "パラメーター '{0}' はその初期化子内では参照できません。", + "Parameter_0_implicitly_has_an_1_type_7006": "パラメーター '{0}' の型は暗黙的に '{1}' になります。", + "Parameter_0_is_not_in_the_same_position_as_parameter_1_1227": "パラメーター '{0}' がパラメーター '{1}' と同じ位置にありません。", + "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4066": "エクスポートされたインターフェイスの呼び出しシグネチャのパラメーター '{0}' が、プライベート モジュール '{2}' の名前 '{1}' を持っているか、使用しています。", + "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4067": "エクスポートされたインターフェイスの呼び出しシグネチャのパラメーター '{0}' が、プライベート名 '{1}' を持っているか、使用しています。", + "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_can_4061": "エクスポートされたクラスのコンストラクターのパラメーター '{0}' が外部モジュール {2} の名前 '{1}' を持っているか使用していますが、名前を指定することはできません。", + "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2_4062": "エクスポートされたクラスのコンストラクターのパラメーター '{0}' が、プライベート モジュール '{2}' の名前 '{1}' を持っているか、使用しています。", + "Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1_4063": "エクスポートされたクラスのコンストラクターのパラメーター '{0}' がプライベート名 '{1}' を持っているか、使用しています。", + "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_mod_4064": "エクスポートされたインターフェイスのコンストラクター シグネチャのパラメーター '{0}' が、プライベート モジュール '{2}' の名前 '{1}' を持っているか、使用しています。", + "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4065": "エクスポートされたインターフェイスのコンストラクター シグネチャのパラメーター '{0}' が、プライベート名 '{1}' を持っているか、使用しています。", + "Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4076": "エクスポートされた関数のパラメーター '{0}' が外部モジュール {2} の名前 '{1}' を持っているか使用していますが、名前を指定することはできません。", + "Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2_4077": "エクスポートされた関数のパラメーター '{0}' が、プライベート モジュール '{2}' の名前 '{1}' を持っているか、使用しています。", + "Parameter_0_of_exported_function_has_or_is_using_private_name_1_4078": "エクスポートされた関数のパラメーター '{0}' がプライベート名 '{1}' を持っているか、使用しています。", + "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4091": "エクスポートされたインターフェイスのインデックス シグネチャのパラメーター '{0}' で、プライベート モジュール '{2}' の名前 '{1}' が指定されているか使用されています。", + "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1_4092": "エクスポートされたインターフェイスのインデックス シグネチャのパラメーター '{0}' で、プライベート名 '{1}' が指定されているか使用されています。", + "Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4074": "エクスポートされたインターフェイスのメソッドのパラメーター '{0}' が、プライベート モジュール '{2}' の名前 '{1}' を持っているか、使用しています。", + "Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4075": "エクスポートされたインターフェイスのメソッドのパラメーター '{0}' がプライベート名 '{1}' を持っているか、使用しています。", + "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_c_4071": "エクスポートされたクラスのパブリック メソッドのパラメーター '{0}' が外部モジュール {2} の名前 '{1}' を持っているか使用していますが、名前を指定することはできません。", + "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4072": "エクスポートされたクラスのパブリック メソッドのパラメーター '{0}' が、プライベート モジュール '{2}' の名前 '{1}' を持っているか、使用しています。", + "Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4073": "エクスポートされたクラスのパブリック メソッドのパラメーター '{0}' がプライベート名 '{1}' を持っているか、使用しています。", + "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module__4068": "エクスポートされたクラスのパブリック静的メソッドのパラメーター '{0}' が外部モジュール {2} の名前 '{1}' を持っているか使用していますが、名前を指定することはできません。", + "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4069": "エクスポートされたクラスのパブリック静的メソッドのパラメーター '{0}' が、プライベート モジュール '{2}' の名前 '{1}' を持っているか、使用しています。", + "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4070": "エクスポートされたクラスのパブリック静的メソッドのパラメーター '{0}' が、プライベート名 '{1}' を持っているか、使用しています。", + "Parameter_cannot_have_question_mark_and_initializer_1015": "パラメーターに疑問符および初期化子を指定することはできません。", + "Parameter_declaration_expected_1138": "パラメーター宣言が必要です。", + "Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2_4036": "エクスポートされたクラスのパブリック セッター '{0}' のパラメーター型が、プライベート モジュール '{2}' の名前 '{1}' を持っているか、使用しています。", + "Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_private_name_1_4037": "エクスポートされたクラスのパブリック セッター '{0}' のパラメーター型が、プライベート名 '{1}' を持っているか、使用しています。", + "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_name_1_from_private_mod_4034": "エクスポートされたクラスのパブリック静的セッター '{0}' のパラメーター型が、プライベート モジュール '{2}' の名前 '{1}' を持っているか、使用しています。", + "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1_4035": "エクスポートされたクラスのパブリック静的セッター '{0}' のパラメーター型が、プライベート名 '{1}' を持っているか、使用しています。", + "Parse_in_strict_mode_and_emit_use_strict_for_each_source_file_6141": "厳格モードで解析してソース ファイルごとに \"use strict\" を生成します。", + "Pattern_0_can_have_at_most_one_Asterisk_character_5061": "パターン '{0}' に使用できる '*' 文字は最大で 1 つです。", + "Prefix_0_with_an_underscore_90025": "アンダースコアを含むプレフィックス '{0}'", + "Prefix_all_unused_declarations_with_where_possible_95025": "可能な場合は、使用されていないすべての宣言にプレフィックスとして '_' を付けます", + "Print_names_of_files_part_of_the_compilation_6155": "コンパイルの一環としてファイルの名前を書き出します。", + "Print_names_of_generated_files_part_of_the_compilation_6154": "コンパイルの一環として生成されたファイル名を書き出します。", + "Print_the_compiler_s_version_6019": "コンパイラのバージョンを表示します。", + "Print_this_message_6017": "このメッセージを表示します。", + "Project_0_can_t_be_built_because_its_dependency_1_has_errors_6363": "プロジェクト '{0}' はその依存関係 '{1}' にエラーがあるためビルドできません", + "Project_0_is_out_of_date_because_its_dependency_1_is_out_of_date_6353": "プロジェクト '{0}' はその依存関係 '{1}' が古いため最新の状態ではありません", + "Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2_6350": "プロジェクト '{0}' は最も古い出力 '{1}' が最新の入力 '{2}' より古いため最新の状態ではありません", + "Project_0_is_out_of_date_because_output_file_1_does_not_exist_6352": "プロジェクト '{0}' は出力ファイル '{1}' が存在しないため最新の状態ではありません", + "Project_0_is_up_to_date_6361": "プロジェクト '{0}' は最新の状態です", + "Project_0_is_up_to_date_because_newest_input_1_is_older_than_oldest_output_2_6351": "プロジェクト '{0}' は最新の入力 '{1}' が最も古い出力 '{2}' より古いため最新の状態です", + "Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies_6354": "プロジェクト '{0}' はその依存関係からの .d.ts ファイルで最新の状態です", + "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202": "プロジェクト参照が円グラフを形成できません。循環が検出されました: {0}", + "Projects_in_this_build_Colon_0_6355": "このビルドのプロジェクト: {0}", + "Projects_to_reference_6300": "参照するプロジェクト", + "Property_0_does_not_exist_on_const_enum_1_2479": "プロパティ '{0}' が 'const' 列挙型 '{1}' に存在しません。", + "Property_0_does_not_exist_on_type_1_2339": "プロパティ '{0}' は型 '{1}' に存在しません。", + "Property_0_does_not_exist_on_type_1_Did_you_forget_to_use_await_2570": "型 '{1}' にプロパティ '{0}' は存在しません。'await' を使用していない可能性があります。", + "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551": "プロパティ '{0}' は型 '{1}' に存在していません。'{2}' ですか?", + "Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1_2546": "プロパティ '{0}' には競合する宣言があり、型 '{1}' ではアクセスできません。", + "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor_2564": "プロパティ '{0}' に初期化子がなく、コンストラクターで明確に割り当てられていません。", + "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033": "プロパティ '{0}' には型 'any' が暗黙的に設定されています。get アクセサーには戻り値の型の注釈がないためです。", + "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032": "プロパティ '{0}' には型 'any' が暗黙的に設定されています。set アクセサーにはパラメーター型の注釈がないためです。", + "Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2_2416": "型 '{1}' のプロパティ '{0}' を基本データ型 '{2}' の同じプロパティに割り当てることはできません。", + "Property_0_in_type_1_is_not_assignable_to_type_2_2603": "型 '{1}' のプロパティ '{0}' を型 '{2}' に割り当てることはできません。", + "Property_0_is_declared_but_its_value_is_never_read_6138": "プロパティ '{0}' が宣言されていますが、その値が読み取られることはありません。", + "Property_0_is_incompatible_with_index_signature_2530": "プロパティ '{0}' はインデックス シグネチャと互換性がありません。", + "Property_0_is_missing_in_type_1_2324": "型 '{1}' にプロパティ '{0}' がありません。", + "Property_0_is_optional_in_type_1_but_required_in_type_2_2327": "プロパティ '{0}' は型 '{1}' では省略可能ですが、型 '{2}' では必須です。", + "Property_0_is_private_and_only_accessible_within_class_1_2341": "プロパティ '{0}' はプライベートで、クラス '{1}' 内でのみアクセスできます。", + "Property_0_is_private_in_type_1_but_not_in_type_2_2325": "プロパティ '{0}' は型 '{1}' ではプライベートですが、型 '{2}' ではプライベートではありません。", + "Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1_2446": "プロパティ '{0}' は保護されているため、クラス '{1}' のインスタンス経由でのみアクセスできます。", + "Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses_2445": "プロパティ '{0}' は保護されているため、クラス '{1}' とそのサブクラス内でのみアクセスできます。", + "Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2_2443": "プロパティ '{0}' は保護されていますが、型 '{1}' は '{2}' から派生したクラスではありません。", + "Property_0_is_protected_in_type_1_but_public_in_type_2_2444": "プロパティ '{0}' は型 '{1}' では保護されていますが、型 '{2}' ではパブリックです。", + "Property_0_is_used_before_being_assigned_2565": "プロパティ '{0}' は割り当てられる前に使用されています。", + "Property_0_of_JSX_spread_attribute_is_not_assignable_to_target_property_2606": "JSX のスプレッド属性のプロパティ '{0}' をターゲット プロパティに割り当てることはできません。", + "Property_0_of_exported_class_expression_may_not_be_private_or_protected_4094": "エクスポートされたクラスの式のプロパティ '{0}' が private または protected でない可能性があります。", + "Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4032": "エクスポートされたインターフェイスのプロパティ '{0}' が、プライベート モジュール '{2}' の名前 '{1}' を持っているか、使用しています。", + "Property_0_of_exported_interface_has_or_is_using_private_name_1_4033": "エクスポートされたインターフェイスのプロパティ '{0}' が、プライベート名 '{1}' を持っているか、使用しています。", + "Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2_2412": "型 '{1}' のプロパティ '{0}' を数値インデックス型 '{2}' に割り当てることはできません。", + "Property_0_of_type_1_is_not_assignable_to_string_index_type_2_2411": "型 '{1}' のプロパティ '{0}' を文字列インデックス型 '{2}' に割り当てることはできません。", + "Property_assignment_expected_1136": "プロパティの割り当てが必要です。", + "Property_destructuring_pattern_expected_1180": "プロパティの非構造化パターンが必要です。", + "Property_or_signature_expected_1131": "プロパティまたはシグネチャが必要です。", + "Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_li_1328": "プロパティ値には、文字列リテラル、数値リテラル、'true'、'false'、'null'、オブジェクト リテラルまたは配列リテラルのみ使用できます。", + "Provide_full_support_for_iterables_in_for_of_spread_and_destructuring_when_targeting_ES5_or_ES3_6179": "'for-of' の iterable、spread、'ES5' や 'ES3' をターゲットとする場合は destructuring に対してフル サポートを提供します。", + "Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4098": "エクスポートされたクラスのパブリック メソッド '{0}' が外部モジュール {2} の名前 '{1}' を持っているか使用していますが、名前を指定することはできません。", + "Public_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4099": "エクスポートされたクラスのパブリック メソッド '{0}' が、プライベート モジュール '{2}' の名前 '{1}' を持っているか、使用しています。", + "Public_method_0_of_exported_class_has_or_is_using_private_name_1_4100": "エクスポートされたクラスのパブリック メソッド '{0}' がプライベート名 '{1}' を持っているか、使用しています。", + "Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_name_4029": "エクスポートされたクラスのパブリック プロパティ '{0}' が外部モジュール {2} の名前 '{1}' を持っているか使用していますが、名前を指定することはできません。", + "Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4030": "エクスポートされたクラスのパブリック プロパティ '{0}' が、プライベート モジュール '{2}' の名前 '{1}' を持っているか、使用しています。", + "Public_property_0_of_exported_class_has_or_is_using_private_name_1_4031": "エクスポートされたクラスのパブリック プロパティ '{0}' が、プライベート名 '{1}' を持っているか、使用しています。", + "Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_4095": "エクスポートされたクラスのパブリック静的メソッド '{0}' が外部モジュール {2} の名前 '{1}' を持っているか使用していますが、名前を指定することはできません。", + "Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4096": "エクスポートされたクラスのパブリック静的メソッド '{0}' が、プライベート モジュール '{2}' の名前 '{1}' を持っているか、使用しています。", + "Public_static_method_0_of_exported_class_has_or_is_using_private_name_1_4097": "エクスポートされたクラスのパブリック静的メソッド '{0}' が、プライベート名 '{1}' を持っているか、使用しています。", + "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot__4026": "エクスポートされたクラスのパブリック静的プロパティ '{0}' が外部モジュール {2} の名前 '{1}' を持っているか使用していますが、名前を指定することはできません。", + "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4027": "エクスポートされたクラスのパブリック静的プロパティ '{0}' が、プライベート モジュール '{2}' の名前 '{1}' を持っているか、使用しています。", + "Public_static_property_0_of_exported_class_has_or_is_using_private_name_1_4028": "エクスポートされたクラスのパブリック静的プロパティ '{0}' が、プライベート名 '{1}' を持っているか、使用しています。", + "Raise_error_on_expressions_and_declarations_with_an_implied_any_type_6052": "暗黙的な 'any' 型を含む式と宣言に関するエラーを発生させます。", + "Raise_error_on_this_expressions_with_an_implied_any_type_6115": "暗黙的な 'any' 型を持つ 'this' 式でエラーが発生します。", + "Redirect_output_structure_to_the_directory_6006": "ディレクトリへ出力構造をリダイレクトします。", + "Referenced_project_0_must_have_setting_composite_Colon_true_6306": "参照されているプロジェクト '{0}' には、設定 \"composite\": true が必要です。", + "Remove_all_unreachable_code_95051": "到達できないコードをすべて削除します", + "Remove_all_unused_labels_95054": "すべての未使用のラベルを削除します", + "Remove_braces_from_arrow_function_95060": "アロー関数から中かっこを削除します", + "Remove_declaration_for_Colon_0_90004": "次に対する宣言を削除する: '{0}'", + "Remove_destructuring_90009": "非構造化を削除します", + "Remove_import_from_0_90005": "'{0}' からのインポートを削除", + "Remove_unreachable_code_95050": "到達できないコードを削除します", + "Remove_unused_label_95053": "未使用のラベルを削除します", + "Remove_variable_statement_90010": "変数のステートメントを削除します", + "Replace_import_with_0_95015": "インポートを '{0}' に置換します。", + "Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "関数の一部のコード パスが値を返さない場合にエラーを報告します。", + "Report_errors_for_fallthrough_cases_in_switch_statement_6076": "switch ステートメントに case のフォールスルーがある場合にエラーを報告します。", + "Report_errors_in_js_files_8019": ".js ファイルのエラーを報告します。", + "Report_errors_on_unused_locals_6134": "使用されていないローカルに関するエラーを報告します。", + "Report_errors_on_unused_parameters_6135": "使用されていないパラメーターに関するエラーを報告します。", + "Required_type_parameters_may_not_follow_optional_type_parameters_2706": "必須の型パラメーターの後に、オプションの型パラメーターを続けることはできません。", + "Resolution_for_module_0_was_found_in_cache_from_location_1_6147": "モジュール '{0}' の解決が場所 '{1}' のキャッシュに見つかりました。", + "Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols_6195": "'keyof' を文字列値のプロパティ名のみに解決します (数字または記号なし)。", + "Resolving_from_node_modules_folder_6118": "node_modules フォルダーから解決しています...", + "Resolving_module_0_from_1_6086": "======== '{1}' からモジュール '{0}' を解決しています。========", + "Resolving_module_name_0_relative_to_base_url_1_2_6094": "ベース URL '{1}' - '{2}' に相対するモジュール名 '{0}' を解決しています。", + "Resolving_real_path_for_0_result_1_6130": "'{0}' の実際のパスを解決しています。結果は '{1}' です。", + "Resolving_type_reference_directive_0_containing_file_1_root_directory_2_6116": "======== 型参照ディレクティブ '{0}' を解決しています。それを含むファイル '{1}'、ルート ディレクトリ '{2}'。========", + "Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set_6123": "======== 型参照ディレクティブ '{0}' を解決しています。それを含むファイル '{1}'、ルート ディレクトリは未設定。========", + "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1_6127": "======== 型参照ディレクティブ '{0}' を解決しています。それを含むファイルは未設定、ルート ディレクトリ '{1}'。========", + "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set_6128": "======== 型参照ディレクティブ '{0}' を解決しています。それを含むファイルは未設定、ルート ディレクトリは未設定。========", + "Resolving_using_primary_search_paths_6117": "プライマリ検索パスを使用して解決しています...", + "Resolving_with_primary_search_path_0_6121": "プライマリ検索パス '{0}' で解決しています。", + "Rest_parameter_0_implicitly_has_an_any_type_7019": "Rest パラメーター '{0}' の型は暗黙的に 'any[]' になります。", + "Rest_types_may_only_be_created_from_object_types_2700": "rest 型はオブジェクトの種類からのみ作成できます。", + "Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4046": "エクスポートされたインターフェイスの呼び出しシグネチャの戻り値の型が、プライベート モジュール '{1}' の名前 '{0}' を持っているか、使用しています。", + "Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0_4047": "エクスポートされたインターフェイスの呼び出しシグネチャの戻り値の型が、プライベート名 '{0}' を持っているか、使用しています。", + "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_mod_4044": "エクスポートされたインターフェイスのコンストラクター シグネチャの戻り値の型が、プライベート モジュール '{1}' の名前 '{0}' を持っているか、使用しています。", + "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0_4045": "エクスポートされたインターフェイスのコンストラクター シグネチャの戻り値の型が、プライベート名 '{0}' を持っているか、使用しています。", + "Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class_2409": "コンストラクター シグネチャの戻り値の型は、クラスのインスタンス型に割り当て可能でなければなりません。", + "Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named_4058": "エクスポートされた関数の戻り値の型が外部モジュール {1} の名前 '{0}' を持っているか使用していますが、名前を指定することはできません。", + "Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1_4059": "エクスポートされた関数の戻り値の型が、プライベート モジュール '{1}' の名前 '{0}' を持っているか、使用しています。", + "Return_type_of_exported_function_has_or_is_using_private_name_0_4060": "エクスポートされた関数の戻り値の型が、プライベート名 '{0}' を持っているか、使用しています。", + "Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4048": "エクスポートされたインターフェイスのインデックス シグネチャの戻り値の型が、プライベート モジュール '{1}' の名前 '{0}' を持っているか、使用しています。", + "Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0_4049": "エクスポートされたインターフェイスのインデックス シグネチャの戻り値の型が、プライベート名 '{0}' を持っているか、使用しています。", + "Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4056": "エクスポートされたインターフェイスのメソッドの戻り値の型が、プライベート モジュール '{1}' の名前 '{0}' を持っているか、使用しています。", + "Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0_4057": "エクスポートされたインターフェイスのメソッドの戻り値の型が、プライベート名 '{0}' を持っているか、使用しています。", + "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_4041": "エクスポートされたクラスのパブリック ゲッター '{0}' の戻り値の型が外部モジュール {2} の名前 '{1}' を持っているか使用していますが、名前を指定することはできません。", + "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2_4042": "エクスポートされたクラスのパブリック ゲッター '{0}' の戻り値の型が、プライベート モジュール '{2}' の名前 '{1}' を持っているか、使用しています。", + "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_private_name_1_4043": "エクスポートされたクラスのパブリック ゲッター '{0}' の戻り値の型が、プライベート名 '{1}' を持っているか、使用しています。", + "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_c_4053": "エクスポートされたクラスのパブリック メソッドの戻り値の型が外部モジュール {1} の名前 '{0}' を持っているか使用していますが、名前を指定することはできません。", + "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4054": "エクスポートされたクラスのパブリック メソッドの戻り値の型が、プライベート モジュール '{1}' の名前 '{0}' を持っているか、使用しています。", + "Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0_4055": "エクスポートされたクラスのパブリック メソッドの戻り値の型が、プライベート名 '{0}' を持っているか、使用しています。", + "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_external_modul_4038": "エクスポートされたクラスのパブリック静的ゲッター '{0}' の戻り値の型が外部モジュール {2} の名前 '{1}' を持っているか使用していますが、名前を指定することはできません。", + "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_4039": "エクスポートされたクラスのパブリック静的ゲッター '{0}' の戻り値の型が、プライベート モジュール '{2}' の名前 '{1}' を持っているか、使用しています。", + "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_private_name_1_4040": "エクスポートされたクラスのパブリック静的ゲッター '{0}' の戻り値の型が、プライベート名 '{1}' を持っているか、使用しています。", + "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module__4050": "エクスポートされたクラスのパブリック静的メソッドの戻り値の型が外部モジュール {1} の名前 '{0}' を持っているか使用していますが、名前を指定することはできません。", + "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4051": "エクスポートされたクラスのパブリック静的メソッドの戻り値の型が、プライベート モジュール '{1}' の名前 '{0}' を持っているか、使用しています。", + "Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0_4052": "エクスポートされたクラスのパブリック静的メソッドの戻り値の型が、プライベート名 '{0}' を持っているか、使用しています。", + "Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program_6184": "'{0}' で生成されたモジュール解決は、前のプログラムから変更されていないため、再利用しています。", + "Reusing_resolution_of_module_0_to_file_1_from_old_program_6183": "前のプログラムを再利用して、モジュール '{0}' をファイル '{1}' に解決しています。", + "Rewrite_all_as_indexed_access_types_95034": "すべてをインデックス付きアクセス型として書き換えます", + "Rewrite_as_the_indexed_access_type_0_90026": "インデックス付きのアクセスの種類 '{0}' として書き換える", + "Root_directory_cannot_be_determined_skipping_primary_search_paths_6122": "ルート ディレクトリを決定できません。プライマリ検索パスをスキップします。", + "STRATEGY_6039": "戦略", + "Scoped_package_detected_looking_in_0_6182": "'{0}' 内を検索して、スコープ パッケージが検出されました", + "Setters_cannot_return_a_value_2408": "セッターは値を返せません。", + "Show_all_compiler_options_6169": "コンパイラ オプションをすべて表示します。", + "Show_diagnostic_information_6149": "診断情報を表示します。", + "Show_verbose_diagnostic_information_6150": "詳細な診断情報を表示します。", + "Show_what_would_be_built_or_deleted_if_specified_with_clean_6367": "ビルドされる (または '--clean' で指定される場合は、削除される) 内容を表示する", + "Signature_0_must_be_a_type_predicate_1224": "シグネチャ '{0}' は型の述語である必要があります。", + "Skip_type_checking_of_declaration_files_6012": "宣言ファイルの型チェックをスキップします。", + "Skipping_build_of_project_0_because_its_dependency_1_has_errors_6362": "プロジェクト '{0}' のビルドは、その依存関係 '{1}' にエラーがあるため、スキップしています", + "Skipping_clean_because_not_all_projects_could_be_located_6371": "一部のプロジェクトが見つからなかったためクリーンをスキップしています", + "Source_Map_Options_6175": "ソース マップ オプション", + "Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature_2382": "特殊化されたオーバーロード シグネチャは、特殊化されていないシグネチャに割り当てることはできません。", + "Specifier_of_dynamic_import_cannot_be_spread_element_1325": "動的インポートの指定子にはスプレッド要素を指定できません。", + "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_or_ESNEXT_6015": "ECMAScript のターゲット バージョンを指定します: 'ES3' (既定)、'ES5'、'ES2015'、'ES2016'、'ES2017'、'ES2018'、'ESNEXT'。", + "Specify_JSX_code_generation_Colon_preserve_react_native_or_react_6080": "JSX コード生成を指定します: 'preserve'、'react-native'、'react'。", + "Specify_library_files_to_be_included_in_the_compilation_6079": "コンパイルに含めるライブラリ ファイルを指定します。", + "Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext_6016": "モジュール コード生成を指定します: 'none'、'commonjs'、'amd'、'system'、'umd'、'es2015'、'ESNext'。", + "Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6_6069": "モジュールの解決方法を指定します: 'node' (Node.js) または 'classic' (TypeScript pre-1.6)。", + "Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h_6146": "'react' JSX 発行 ('React.createElement' や 'h') などを対象とするときに使用する JSX ファクトリ関数を指定します。", + "Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix_6060": "ファイルの生成時に使用する行シーケンスの末尾を指定します: 'CRLF' (dos) または 'LF' (unix)。", + "Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations_6004": "デバッガーがソースの場所の代わりに TypeScript ファイルを検索する必要のある場所を指定します。", + "Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations_6003": "デバッガーが、生成された場所の代わりにマップ ファイルを検索する必要のある場所を指定します。", + "Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir_6058": "入力ファイルのルート ディレクトリを指定します。--outDir とともに、出力ディレクトリ構造の制御に使用します。", + "Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher_2472": "'new' 式のスプレッド演算子は ECMAScript 5 以上をターゲットにする場合にのみ使用できます。", + "Spread_types_may_only_be_created_from_object_types_2698": "spread 型はオブジェクトの種類からのみ作成できます。", + "Starting_compilation_in_watch_mode_6031": "ウォッチ モードでのコンパイルを開始しています...", + "Statement_expected_1129": "ステートメントが必要です。", + "Statements_are_not_allowed_in_ambient_contexts_1036": "ステートメントは環境コンテキストでは使用できません。", + "Static_members_cannot_reference_class_type_parameters_2302": "静的メンバーはクラスの型パラメーターを参照できません。", + "Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1_2699": "静的プロパティ '{0}' がコンストラクター関数 '{1}' のビルトイン プロパティ 'Function.{0}' と競合しています。", + "Strict_Type_Checking_Options_6173": "Strict 型チェック オプション", + "String_literal_expected_1141": "文字列リテラルが必要です。", + "String_literal_with_double_quotes_expected_1327": "二重引用符を含む文字列リテラルが必要です。", + "Stylize_errors_and_messages_using_color_and_context_experimental_6073": "色とコンテキストを使用してエラーとメッセージにスタイルを適用します (試験的)。", + "Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_t_2717": "後続のプロパティ宣言は同じ型でなければなりません。プロパティ '{0}' の型は '{1}' である必要がありますが、ここでは型が '{2}' になっています。", + "Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_t_2403": "後続の変数宣言は同じ型でなければなりません。変数 '{0}' の型は '{1}' である必要がありますが、'{2}' になっています。", + "Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2_5064": "パターン '{1}' の代入 '{0}' の型が正しくありません。必要な型は 'string' ですが、'{2}' を取得しました。", + "Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character_5062": "パターン '{1}' の代入 '{0}' に使用できる '*' 文字は最大 1 つです。", + "Substitutions_for_pattern_0_should_be_an_array_5063": "パターン '{0}' への代入は配列でなければなりません。", + "Substitutions_for_pattern_0_shouldn_t_be_an_empty_array_5066": "パターン '{0}' への代入を空の配列にすることはできません。", + "Successfully_created_a_tsconfig_json_file_6071": "tsconfig.json ファイルが正常に作成されました。", + "Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors_2337": "super の呼び出しは、コンストラクターの外部、またはコンストラクター内の入れ子になった関数では使用できません。", + "Suppress_excess_property_checks_for_object_literals_6072": "オブジェクト リテラルの過剰なプロパティ確認を抑制します。", + "Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures_6055": "インデックス シグニチャのないオブジェクトにインデックスを作成するため、noImplicitAny エラーを抑制します。", + "Symbol_reference_does_not_refer_to_the_global_Symbol_constructor_object_2470": "'Symbol' 参照は、グローバル シンボル コンストラクター オブジェクトを参照しません。", + "Syntax_Colon_0_6023": "構文: {0}", + "The_0_operator_cannot_be_applied_to_type_symbol_2469": "'{0}' 演算子を 'symbol' 型に適用することはできません。", + "The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead_2447": "'{0}' 演算子はブール型には使用できません。代わりに '{1}' を使用してください。", + "The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead_2696": "'Object' 型を割り当てることができるその他の型はごく少数です。代わりの候補には 'any' 型があります。", + "The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_stand_2496": "'arguments' オブジェクトは、ES3 および ES5 のアロー関数で参照することはできません。標準の関数式の使用を考慮してください。", + "The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_usi_2522": "'arguments' オブジェクトは、ES3 および ES5 の非同期関数またはメソッドで参照することはできません。標準の関数またはメソッドを使用することを検討してください。", + "The_body_of_an_if_statement_cannot_be_the_empty_statement_1313": "'if' ステートメントの本文を空のステートメントにすることはできません。", + "The_character_set_of_the_input_files_6163": "入力ファイルの文字セット。", + "The_containing_function_or_module_body_is_too_large_for_control_flow_analysis_2563": "含まれている関数またはモジュールの本体は、制御フロー解析には大きすぎます。", + "The_current_host_does_not_support_the_0_option_5001": "現在のホストは '{0}' オプションをサポートしていません。", + "The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context_2714": "エクスポートの割り当ての式は、環境コンテキストの識別子または修飾名にする必要があります。", + "The_files_list_in_config_file_0_is_empty_18002": "構成ファイル '{0}' の 'files' リストが空です。", + "The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback_1060": "Promise では、'then' メソッドの最初のパラメーターはコールバックでなければなりません。", + "The_global_type_JSX_0_may_not_have_more_than_one_property_2608": "グローバル型 'JSX.{0}' には複数のプロパティが含まれていない可能性があります。", + "The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_option_1343": "'Import.meta' メタ プロパティでは、'target' および 'module' コンパイラ オプションに対して 'ESNext' のみが許可されています。", + "The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary_2527": "'{0}' の推定型はアクセス不可能な '{1}' 型を参照します。型の注釈が必要です。", + "The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern_2491": "'for...in' ステートメントの左側を非構造化パターンにすることはできません。", + "The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation_2404": "'for...in' ステートメントの左側で型の注釈を使用することはできません。", + "The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access_2406": "'for...in' ステートメントの左側は、変数またはプロパティ アクセスである必要があります。", + "The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any_2405": "'for...in' ステートメントの左側の型は 'string' または 'any' でなければなりません。", + "The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation_2483": "'for...of' ステートメントの左側で型の注釈を使用することはできません。", + "The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access_2487": "'for...of' ステートメントの左側は、変数またはプロパティ アクセスである必要があります。", + "The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type_2362": "算術演算の左辺には、'any' 型、'number' 型、または列挙型を指定してください。", + "The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access_2364": "代入式の左側は、変数またはプロパティ アクセスである必要があります。", + "The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol_2360": "'in' 式の左辺の型は 'any'、'string'、'number'、または 'symbol' でなければなりません。", + "The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_paramete_2358": "'instanceof' 式の左辺には、'any' 型、オブジェクト型、または型パラメーターを指定してください。", + "The_locale_used_when_displaying_messages_to_the_user_e_g_en_us_6156": "ユーザーにメッセージを表示するときに使用するロケール (例: 'en-us')", + "The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files_6136": "node_modules の下を検索して JavaScript ファイルを読み込む依存関係の最大深度です。", + "The_operand_of_a_delete_operator_cannot_be_a_read_only_property_2704": "delete 演算子のオペランドを読み取り専用のプロパティにすることはできません。", + "The_operand_of_a_delete_operator_must_be_a_property_reference_2703": "delete 演算子のオペランドはプロパティ参照でなければなりません。", + "The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access_2357": "インクリメントまたはデクリメント演算子のオペランドは、変数またはプロパティ アクセスである必要があります。", + "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601": "JSX 要素コンストラクターの戻り値の型は、オブジェクト型を返す必要があります。", + "The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any_1237": "パラメーター デコレーター関数の戻り値の型は、'void' か 'any' である必要があります。", + "The_return_type_of_a_property_decorator_function_must_be_either_void_or_any_1236": "プロパティ デコレーター関数の戻り値の型は、'void' か 'any' である必要があります。", + "The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_t_1058": "非同期関数の戻り値の型は、有効な Promise であるか、呼び出し可能な 'then' メンバーを含んでいないかのどちらかであることが必要です。", + "The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_1064": "非同期関数または非同期メソッドの戻り値の型は、グローバル Promise 型である必要があります。", + "The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_but_2407": "'for...in' ステートメントの右側には、'any' 型、オブジェクト型、型パラメーターを指定する必要がありますが、ここでは型 '{0}' が指定されています。", + "The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type_2363": "算術演算の右辺には、'any' 型、'number' 型、または列挙型を指定してください。", + "The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter_2361": "'in' 式の右辺は、'any' 型、オブジェクト型、型パラメーターでなければなりません。", + "The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_F_2359": "instanceof' 式の右辺には、'any' 型、または 'Function' インターフェイス型に割り当てることができる型を指定してください。", + "The_specified_path_does_not_exist_Colon_0_5058": "指定されたパスがありません: '{0}'。", + "The_target_of_an_assignment_must_be_a_variable_or_a_property_access_2541": "代入式のターゲットは、変数またはプロパティ アクセスである必要があります。", + "The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access_2701": "オブジェクトの残り部分の割り当ての対象は、変数またはプロパティ アクセスである必要があります。", + "The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1_2684": "型 '{0}' の 'this' コンテキストを型 '{1}' のメソッドの 'this' に割り当てることはできません。", + "The_this_types_of_each_signature_are_incompatible_2685": "各シグネチャの 'this' 型に互換性がありません。", + "The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_typ_2453": "型パラメーター '{0}' の型引数を使用法から推論することはできません。型引数を明示的に指定してください。", + "The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value__2547": "非同期反復子の 'next()' メソッドから返される型は、'value' プロパティを持つ型の Promise でなければなりません。", + "The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property_2490": "反復子の 'next()' メソッドによって返される型には 'value' プロパティが必要です。", + "The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer_1189": "'for...in' ステートメントの変数宣言に初期化子を指定することはできません。", + "The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer_1190": "'for...of' ステートメントの変数宣言に初期化子を指定することはできません。", + "The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any_2410": "'with' ステートメントはサポートされていません。'with' ブロック内のすべてのシンボルの型は 'any' になります。", + "This_constructor_function_may_be_converted_to_a_class_declaration_80002": "このコンストラクター関数はクラス宣言に変換される可能性があります。", + "This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found_2354": "この構文にはインポートされたヘルパーが必要ですが、モジュール '{0}' が見つかりません。", + "This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1_2343": "この構文には '{1}' という名前のインポートされたヘルパーが必要ですが、モジュール '{0}' にエクスポートされたメンバー '{1}' がありません。", + "Trailing_comma_not_allowed_1009": "末尾にコンマは使用できません。", + "Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule_6153": "個々のモジュールとして各ファイルをトランスパイルします ('ts.transpileModule' に類似)。", + "Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_mod_7035": "`npm install @types/{0}` を試すか (存在する場合)、`declare module '{0}';` を含む新しい宣言 (.d.ts) ファイルを追加してください", + "Trying_other_entries_in_rootDirs_6110": "'rootDirs' の他のエントリを試しています。", + "Trying_substitution_0_candidate_module_location_Colon_1_6093": "代入 '{0}' を試しています。候補のモジュールの場所: '{1}'。", + "Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2_2493": "長さが '{1}' のタプル型 '{0}' を長さが '{2}' のタプルに割り当てることはできません。", + "Type_0_cannot_be_converted_to_type_1_2352": "型 '{0}' を型 '{1}' に変換できません。", + "Type_0_cannot_be_used_as_an_index_type_2538": "型 '{0}' はインデックスの型として使用できません。", + "Type_0_cannot_be_used_to_index_type_1_2536": "型 '{0}' はインデックスの種類 '{1}' に使用できません。", + "Type_0_does_not_satisfy_the_constraint_1_2344": "型 '{0}' は制約 '{1}' を満たしていません。", + "Type_0_has_no_matching_index_signature_for_type_1_2537": "型 '{0}' には型 '{1}' と一致するインデックス シグネチャがありません。", + "Type_0_has_no_properties_in_common_with_type_1_2559": "型 '{0}' には型 '{1}' と共通のプロパティがありません。", + "Type_0_has_no_property_1_2460": "型 '{0}' にプロパティ '{1}' がありません。", + "Type_0_has_no_property_1_and_no_string_index_signature_2459": "型 '{0}' にプロパティ '{1}' および string インデックス シグネチャがありません。", + "Type_0_is_not_a_constructor_function_type_2507": "型 '{0}' はコンストラクター関数型ではありません。", + "Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Prom_1055": "型 '{0}' は Promise と互換性のあるコンストラクター値を参照しないため、ES5/ES3 において有効な非同期関数の戻り値の型ではありません。", + "Type_0_is_not_an_array_type_2461": "型 '{0}' は配列型ではありません。", + "Type_0_is_not_an_array_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators_2568": "型 '{0}' は配列型ではありません。反復子の反復を許可するには、コンパイラ オプション '--downlevelIteration' を使用します。", + "Type_0_is_not_an_array_type_or_a_string_type_2495": "型 '{0}' は配列型でも文字列型でもありません。", + "Type_0_is_not_an_array_type_or_a_string_type_Use_compiler_option_downlevelIteration_to_allow_iterati_2569": "型 '{0}' は配列型でも文字列型でもありません。反復子の反復を許可するには、コンパイラ オプション '--downlevelIteration' を使用します。", + "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549": "型 '{0}' は、配列型でも文字列型でもないか、反復子を返す '[Symbol.iterator]()' メソッドを持っていません。", + "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548": "型 '{0}' は、配列型ではないか、反復子を返す '[Symbol.iterator]()' メソッドを持っていません。", + "Type_0_is_not_assignable_to_type_1_2322": "型 '{0}' を型 '{1}' に割り当てることはできません。", + "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_2719": "型 '{0}' は型 '{1}' に割り当てられません。同じ名前で 2 つの異なる型が存在しますが、これは関連していません。", + "Type_0_is_not_comparable_to_type_1_2678": "型 '{0}' は型 '{1}' と比較できません。", + "Type_0_is_not_generic_2315": "型 '{0}' はジェネリックではありません。", + "Type_0_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator_2504": "型 '{0}' には、非同期反復子を返す '[Symbol.asyncIterator]()' メソッドが必要です。", + "Type_0_must_have_a_Symbol_iterator_method_that_returns_an_iterator_2488": "型 '{0}' には、反復子を返す '[Symbol.iterator]()' メソッドが必要です。", + "Type_0_provides_no_match_for_the_signature_1_2658": "型 '{0}' にはシグネチャ '{1}' に一致するものがありません。", + "Type_0_recursively_references_itself_as_a_base_type_2310": "型 '{0}' が、基本型としてそれ自体を再帰的に参照しています。", + "Type_alias_0_circularly_references_itself_2456": "型のエイリアス '{0}' が自身を循環参照しています。", + "Type_alias_name_cannot_be_0_2457": "型のエイリアス名を '{0}' にすることはできません。", + "Type_annotation_cannot_appear_on_a_constructor_declaration_1093": "型の注釈はコンストラクター宣言では使用できません。", + "Type_argument_candidate_1_is_not_a_valid_type_argument_because_it_is_not_a_supertype_of_candidate_0_2455": "型引数の候補 '{1}' は、候補 '{0}' のスーパータイプではないため、有効な型引数ではありません。", + "Type_argument_expected_1140": "型引数が必要です。", + "Type_argument_list_cannot_be_empty_1099": "型引数リストを空にすることはできません。", + "Type_arguments_cannot_be_used_here_1342": "ここで型引数は使用できません。", + "Type_declaration_files_to_be_included_in_compilation_6124": "コンパイルに含む型宣言ファイル。", + "Type_expected_1110": "型が必要です。", + "Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method_1062": "型は、それ自身の 'then' メソッドのフルフィルメント コールバック内で直接または間接的に参照されます。", + "Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member_1320": "'await' オペランドの型は、有効な Promise であるか、呼び出し可能な 'then' メンバーを含んでいないかのどちらかであることが必要です。", + "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322": "'yield*' オペランドの反復要素の型は、有効な Promise であるか、呼び出し可能な 'then' メンバーを含んでいないかのどちらかであることが必要です。", + "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321": "非同期ジェネレーター内の 'yield' オペランドの型は、有効な Promise であるか、呼び出し可能な 'then' メンバーを含んでいないかのどちらかであることが必要です。", + "Type_parameter_0_has_a_circular_constraint_2313": "型パラメーター '{0}' に循環制約があります。", + "Type_parameter_0_has_a_circular_default_2716": "型パラメーター '{0}' に循環既定値があります。", + "Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4008": "エクスポートされたインターフェイスの呼び出しシグネチャの型パラメーター '{0}' が、プライベート名 '{1}' を持っているか、使用しています。", + "Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4006": "エクスポートされたインターフェイスのコンストラクター シグネチャの型パラメーター '{0}' が、プライベート名 '{1}' を持っているか、使用しています。", + "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002": "エクスポートされたクラスの型パラメーター '{0}' が、プライベート名 '{1}' を持っているか、使用しています。", + "Type_parameter_0_of_exported_function_has_or_is_using_private_name_1_4016": "エクスポートされた関数の型パラメーター '{0}' が、プライベート名 '{1}' を持っているか、使用しています。", + "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004": "エクスポートされたインターフェイスの型パラメーター '{0}' が、プライベート名 '{1}' を持っているか、使用しています。", + "Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1_4083": "エクスポートした型のエイリアスの型パラメーター '{0}' にプライベート名 '{1}' が指定されているか、これを使用しています。", + "Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4014": "エクスポートされたインターフェイスのメソッドの型パラメーター '{0}' が、プライベート名 '{1}' を持っているか、使用しています。", + "Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4012": "エクスポートされたクラスのパブリック メソッドの型パラメーター '{0}' が、プライベート名 '{1}' を持っているか、使用しています。", + "Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4010": "エクスポートされたクラスのパブリック静的メソッドの型パラメーター '{0}' が、プライベート名 '{1}' を持っているか、使用しています。", + "Type_parameter_declaration_expected_1139": "型パラメーターの宣言が必要です。", + "Type_parameter_list_cannot_be_empty_1098": "型パラメーター リストを空にすることはできません。", + "Type_parameter_name_cannot_be_0_2368": "型パラメーター名を '{0}' にすることはできません。", + "Type_parameters_cannot_appear_on_a_constructor_declaration_1092": "型パラメーターはコンストラクター宣言では使用できません。", + "Type_predicate_0_is_not_assignable_to_1_1226": "型の述語 '{0}' を '{1}' に割り当てることはできません。", + "Type_reference_directive_0_was_not_resolved_6120": "======== 型参照ディレクティブ '{0}' が解決されませんでした。========", + "Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2_6119": "======== 型参照ディレクティブ '{0}' が正常に '{1}' に解決されました。プライマリ: {2}。========", + "Types_have_separate_declarations_of_a_private_property_0_2442": "複数の型に、プライベート プロパティ '{0}' の異なる宣言が含まれています。", + "Types_of_parameters_0_and_1_are_incompatible_2328": "パラメーター '{0}' および '{1}' は型に互換性がありません。", + "Types_of_property_0_are_incompatible_2326": "プロパティ '{0}' の型に互換性がありません。", + "Unable_to_open_file_0_6050": "ファイル '{0}' を開くことができません。", + "Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression_1238": "式として呼び出される場合、クラス デコレーターのシグネチャを解決できません。", + "Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression_1241": "式として呼び出される場合、メソッド デコレーターのシグネチャを解決できません。", + "Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression_1239": "式として呼び出される場合、パラメーター デコレーターのシグネチャを解決できません。", + "Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression_1240": "式として呼び出される場合、プロパティ デコレーターのシグネチャを解決できません。", + "Unexpected_end_of_text_1126": "予期しないテキストの末尾です。", + "Unexpected_token_1012": "予期しないトークンです。", + "Unexpected_token_A_constructor_method_accessor_or_property_was_expected_1068": "予期しないトークンです。コンストラクター、メソッド、アクセサー、またはプロパティが必要です。", + "Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces_1069": "予期しないトークンです。型パラメーター名には、中かっこを含めることはできません。", + "Unexpected_token_expected_1179": "予期しないトークンです。'{' が必要です。", + "Unknown_compiler_option_0_5023": "コンパイラ オプション '{0}' が不明です。", + "Unknown_option_excludes_Did_you_mean_exclude_6114": "不明なオプション 'excludes' です。'exclude' ですか?", + "Unknown_type_acquisition_option_0_17010": "不明な型の取得オプション '{0}'。", + "Unreachable_code_detected_7027": "到達できないコードが検出されました。", + "Unsupported_locale_0_6049": "ロケール '{0}' はサポートされていません。", + "Unterminated_Unicode_escape_sequence_1199": "未終了の Unicode エスケープ シーケンスです。", + "Unterminated_quoted_string_in_response_file_0_6045": "応答ファイル '{0}' の文字列の終了引用符がありません。", + "Unterminated_regular_expression_literal_1161": "未終了の正規表現リテラルです。", + "Unterminated_string_literal_1002": "未終了の文字列リテラルです。", + "Unterminated_template_literal_1160": "未終了のテンプレート リテラルです。", + "Untyped_function_calls_may_not_accept_type_arguments_2347": "型指定のない関数の呼び出しで型引数を使用することはできません。", + "Unused_label_7028": "未使用のラベル。", + "Updating_output_timestamps_of_project_0_6359": "プロジェクト '{0}' の出力タイムスタンプを更新しています...", + "Use_synthetic_default_member_95016": "合成 'default' メンバーを使用します。", + "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494": "'for...of' ステートメントでの文字列の使用は ECMAScript 5 以上でのみサポートされています。", + "VERSION_6036": "バージョン", + "Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it_2560": "型 '{0}' の値には、型 '{1}' と共通のプロパティがありません。呼び出しますか?", + "Value_of_type_0_is_not_callable_Did_you_mean_to_include_new_2348": "型 '{0}' の値は呼び出せません。'new' を含めますか?", + "Variable_0_implicitly_has_an_1_type_7005": "変数 '{0}' の型は暗黙的に '{1}' になります。", + "Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined_7034": "変数 '{0}' は、型を決定できない一部の場所では、暗黙のうちに '{1}' 型になります。", + "Variable_0_is_used_before_being_assigned_2454": "変数 '{0}' は割り当てられる前に使用されています。", + "Variable_declaration_expected_1134": "変数の宣言が必要です。", + "Variable_declaration_list_cannot_be_empty_1123": "変数宣言リストを空にすることはできません。", + "Version_0_6029": "バージョン {0}", + "Watch_input_files_6005": "入力ファイルを監視します。", + "Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen_6191": "画面をクリアする代わりに、古くなったコンソール出力をウォッチ モードで保持するかどうか。", + "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001": "標準の TypeScript ライブラリで定義された要素の名前を変更することはできません。", + "You_cannot_rename_this_element_8000": "この要素の名前を変更することはできません。", + "_0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write__1329": "'{0}' は受け入れる引数が少なすぎるので、ここでデコレーターとして使用することができません。最初にこれを呼び出してから、'@{0}()' を書き込むつもりでしたか?", + "_0_are_specified_twice_The_attribute_named_0_will_be_overwritten_2710": "'{0}' は 2 回指定されています。'{0}' という名前の属性は上書きされます。", + "_0_can_only_be_used_in_a_ts_file_8009": "'{0}' を使用できるのは .ts ファイル内のみです。", + "_0_expected_1005": "'{0}' が必要です。", + "_0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_reference_7023": "'{0}' は、戻り値の型の注釈がなく、いずれかの return 式で直接的にまたは間接的に参照されているため、戻り値の型は暗黙的に 'any' になります。", + "_0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or__7022": "'{0}' には型の注釈がなく、直接または間接的に初期化子で参照されているため、暗黙的に 'any' 型が含まれています。", + "_0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible_2692": "'{0}' はプリミティブですが、'{1}' はラッパー オブジェクトです。できれば '{0}' をご使用ください。", + "_0_is_declared_but_its_value_is_never_read_6133": "'{0}' が宣言されていますが、その値が読み取られることはありません。", + "_0_is_declared_but_never_used_6196": "'{0}' は宣言されましたが使用されませんでした。", + "_0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2_17012": "'{0}' はキーワード '{1}' に関するメタプロパティとして無効です。候補: '{2}'。", + "_0_is_referenced_directly_or_indirectly_in_its_own_base_expression_2506": "'{0}' はそれ自身のベース式内で直接または間接的に参照されます。", + "_0_is_referenced_directly_or_indirectly_in_its_own_type_annotation_2502": "'{0}' はそれ自身の型の注釈内で直接または間接的に参照されます。", + "_0_list_cannot_be_empty_1097": "'{0}' のリストを空にすることはできません。", + "_0_modifier_already_seen_1030": "'{0}' 修飾子は既に存在します。", + "_0_modifier_cannot_appear_on_a_class_element_1031": "'{0}' 修飾子はクラス要素では使用できません。", + "_0_modifier_cannot_appear_on_a_constructor_declaration_1089": "'{0}' 修飾子はコンストラクター宣言では使用できません。", + "_0_modifier_cannot_appear_on_a_data_property_1043": "'{0}' 修飾子はデータ プロパティでは使用できません。", + "_0_modifier_cannot_appear_on_a_module_or_namespace_element_1044": "'{0}' 修飾子は、モジュールまたは名前空間の要素では使用できません。", + "_0_modifier_cannot_appear_on_a_parameter_1090": "'{0}' 修飾子はパラメーターでは使用できません。", + "_0_modifier_cannot_appear_on_a_type_member_1070": "'{0}' 修飾子は型メンバーでは使用できません。", + "_0_modifier_cannot_appear_on_an_index_signature_1071": "'{0}' 修飾子はインデックス シグネチャでは使用できません。", + "_0_modifier_cannot_be_used_here_1042": "'{0}' 修飾子はここでは使用できません。", + "_0_modifier_cannot_be_used_in_an_ambient_context_1040": "'{0}' 修飾子は環境コンテキストでは使用できません。", + "_0_modifier_cannot_be_used_with_1_modifier_1243": "'{0}' 修飾子と '{1}' 修飾子は同時に使用できません。", + "_0_modifier_cannot_be_used_with_a_class_declaration_1041": "'{0}' 修飾子とクラス宣言は同時に使用できません。", + "_0_modifier_must_precede_1_modifier_1029": "'{0}' 修飾子は '{1}' 修飾子の前に指定する必要があります。", + "_0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here_2702": "'{0}' は型のみを参照しますが、ここで名前空間として使用されています。", + "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_2693": "'{0}' は型のみを参照しますが、ここで値として使用されています。", + "_0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead_2686": "'{0}' は UMD グローバルを参照していますが、現在のファイルはモジュールです。代わりにインポートを追加することを考慮してください。", + "_0_tag_already_specified_1223": "'{0}' タグは既に指定されています。", + "_0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag_1253": "'{0}' タグはトップ レベルの JSDoc タグとして個別に使用することはできません。", + "_0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type_7010": "'{0}' には戻り値の型の注釈がないため、戻り値の型は暗黙的に '{1}' になります。", + "abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration_1242": "'abstract' 修飾子は、クラス宣言、メソッド宣言、またはプロパティ宣言のみに使用できます。", + "await_expression_is_only_allowed_within_an_async_function_1308": "'await' 式は、非同期関数内でのみ使用できます。", + "await_expressions_cannot_be_used_in_a_parameter_initializer_2524": "'await' 式は、パラメーター初期化子では使用できません。", + "baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1_6106": "'baseUrl' オプションは '{0}' に設定され、この値を使用して非相対モジュール名 '{1}' を解決します。", + "can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment_1312": "'=' は、非構造化割り当て内のオブジェクト リテラル プロパティでのみ使用できます。", + "case_or_default_expected_1130": "'case' または 'default' が必要です。", + "class_expressions_are_not_currently_supported_9003": "'class' 式は現在サポートされていません。", + "const_declarations_can_only_be_declared_inside_a_block_1156": "'const' 宣言は、ブロック内でのみ宣言できます。", + "const_declarations_must_be_initialized_1155": "'const' 宣言は初期化する必要があります。", + "const_enum_member_initializer_was_evaluated_to_a_non_finite_value_2477": "'const' 列挙型メンバーの初期化子が、無限値に評価されました。", + "const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN_2478": "'const' 列挙型メンバーの初期化子が、許可されない値 'NaN' に評価されました。", + "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475": "'const' 列挙型は、プロパティまたはインデックスのアクセス式、インポート宣言またはエクスポートの割り当ての右辺、型のクエリにのみ使用できます。", + "delete_cannot_be_called_on_an_identifier_in_strict_mode_1102": "厳格モードでは 'delete' を識別子で呼び出すことはできません。", + "delete_this_Project_0_is_up_to_date_because_it_was_previously_built_6360": "これを削除します - プロジェクト '{0}' は、以前にビルドされているため、最新の状態です", + "enum_declarations_can_only_be_used_in_a_ts_file_8015": "'列挙型宣言' を使用できるのは .ts ファイル内のみです。", + "export_can_only_be_used_in_a_ts_file_8003": "'export=' を使用できるのは .ts ファイル内のみです。", + "export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always__2668": "環境モジュールとモジュール拡張は常に表示されるので、これらに 'export' 修飾子を適用することはできません。", + "extends_clause_already_seen_1172": "'extends' 句は既に存在します。", + "extends_clause_must_precede_implements_clause_1173": "extends' 句は 'implements' 句の前に指定しなければなりません。", + "extends_clause_of_exported_class_0_has_or_is_using_private_name_1_4020": "エクスポートされたクラス '{0}' の 'extends' 句がプライベート名 '{1}' を持っているか、使用しています。", + "extends_clause_of_exported_interface_0_has_or_is_using_private_name_1_4022": "エクスポートされたインターフェイス '{0}' の 'extends' 句がプライベート名 '{1}' を持っているか、使用しています。", + "file_6025": "ファイル", + "get_and_set_accessor_must_have_the_same_this_type_2682": "'get' アクセサーおよび 'set' アクセサーには、同じ 'this' 型が必要です。", + "get_and_set_accessor_must_have_the_same_type_2380": "'get' アクセサーと 'set' アクセサーは同じ型でなければなりません。", + "implements_clause_already_seen_1175": "'implements' 句は既に存在します。", + "implements_clauses_can_only_be_used_in_a_ts_file_8005": "'implements 句' を使用できるのは .ts ファイル内のみです。", + "import_can_only_be_used_in_a_ts_file_8002": "'import ... =' を使用できるのは .ts ファイル内のみです。", + "infer_declarations_are_only_permitted_in_the_extends_clause_of_a_conditional_type_1338": "'infer' 宣言は、条件付き型の 'extends' 句でのみ許可されます。", + "interface_declarations_can_only_be_used_in_a_ts_file_8006": "'インターフェイス宣言' を使用できるのは .ts ファイル内のみです。", + "let_declarations_can_only_be_declared_inside_a_block_1157": "'let' 宣言は、ブロック内でのみ宣言できます。", + "let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations_2480": "'let' は、'let' 宣言または 'const' 宣言で名前として使用することはできません。", + "module_declarations_can_only_be_used_in_a_ts_file_8007": "'モジュール宣言' を使用できるのは .ts ファイル内のみです。", + "new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead_1150": "'new T[]' は配列の作成に使用できません。代わりに 'new Array()' を使用してください。", + "new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type_7009": "ターゲットにコンストラクト シグネチャがない 'new' 式の型は、暗黙的に 'any' になります。", + "non_null_assertions_can_only_be_used_in_a_ts_file_8013": "'null 以外のアサーション' を使用できるのは .ts ファイル内のみです。", + "options_6024": "オプション", + "or_expected_1144": "'{' または ';' が必要です。", + "package_json_does_not_have_a_0_field_6100": "'package.json' に '{0}' フィールドがありません。", + "package_json_has_0_field_1_that_references_2_6101": "'package.json' に '{2}' を参照する '{0}' フィールド '{1}' があります。", + "parameter_modifiers_can_only_be_used_in_a_ts_file_8012": "'パラメーター修飾子' を使用できるのは .ts ファイル内のみです。", + "paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0_6091": "'paths' オプションが指定され、モジュール名 '{0}' と一致するパターンを検索します。", + "readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024": "'readonly' 修飾子はプロパティ宣言またはインデックス シグネチャのみに使用できます。", + "require_call_may_be_converted_to_an_import_80005": "'require' の呼び出しはインポートに変換される可能性があります。", + "rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107": "'rootDirs' オプションが設定され、このオプションを使用して相対モジュール名 '{0}' を解決します。", + "super_can_only_be_referenced_in_a_derived_class_2335": "'super' は、派生クラスでのみ参照できます。", + "super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions_2660": "'super' は、派生クラスのメンバーまたはオブジェクトのリテラル式のメンバーでのみ参照されます。", + "super_cannot_be_referenced_in_a_computed_property_name_2466": "'super' は、計算されたプロパティ名では参照できません。", + "super_cannot_be_referenced_in_constructor_arguments_2336": "'super' はコンストラクター引数では参照できません。", + "super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_highe_2659": "オプション 'target' が 'ES2015' 以降の場合、'super' はオブジェクトのリテラル式のメンバーでのみ使用できます。", + "super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class_17011": "派生クラスのコンストラクター内の 'super' のプロパティにアクセスする前に、'super' を呼び出す必要があります。", + "super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class_17009": "派生クラスのコンストラクター内の 'this' にアクセスする前に、'super' を呼び出す必要があります。", + "super_must_be_followed_by_an_argument_list_or_member_access_1034": "'super' の後には、引数リストまたはメンバー アクセスが必要です。", + "super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_der_2338": "'super' プロパティ アクセスはコンストラクター、メンバー関数、または派生クラスのメンバー アクセサーでのみ許可されます。", + "this_cannot_be_referenced_in_a_computed_property_name_2465": "'this' は、計算されたプロパティ名では参照できません。", + "this_cannot_be_referenced_in_a_module_or_namespace_body_2331": "'this' はモジュール本体内または名前空間本体内では参照できません。", + "this_cannot_be_referenced_in_a_static_property_initializer_2334": "'this' は、静的プロパティ初期化子では参照できません。", + "this_cannot_be_referenced_in_constructor_arguments_2333": "'this' はコンストラクター引数では参照できません。", + "this_cannot_be_referenced_in_current_location_2332": "'this' は現在の場所では参照できません。", + "this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_2683": "'this' は型として注釈を持たないため、暗黙的に型 'any' になります。", + "type_aliases_can_only_be_used_in_a_ts_file_8008": "'型のエイリアス' を使用できるのは .ts ファイル内のみです。", + "type_arguments_can_only_be_used_in_a_ts_file_8011": "'型引数' を使用できるのは .ts ファイル内のみです。", + "type_assertion_expressions_can_only_be_used_in_a_ts_file_8016": "'型アサーション式' を使用できるのは、.ts ファイル内のみです。", + "type_parameter_declarations_can_only_be_used_in_a_ts_file_8004": "'型パラメーター宣言' を使用できるのは .ts ファイル内のみです。", + "types_can_only_be_used_in_a_ts_file_8010": "'型' を使用できるのは .ts ファイル内のみです。", + "unique_symbol_types_are_not_allowed_here_1335": "'unique symbol' 型はここでは許可されていません。", + "unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement_1334": "'unique symbol' 型は変数ステートメントの変数でのみ許可されています。", + "unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name_1333": "'unique symbol' 型は、バインディング名を持つ変数の宣言では使用できません。", + "with_statements_are_not_allowed_in_an_async_function_block_1300": "'with' 式は、非同期関数ブロックでは使用できません。", + "with_statements_are_not_allowed_in_strict_mode_1101": "厳格モードでは 'with' ステートメントは使用できません。", + "yield_expressions_cannot_be_used_in_a_parameter_initializer_2523": "'yield' 式は、パラメーター初期化子では使用できません。" +} \ No newline at end of file diff --git a/node_modules/typescript/lib/ko/diagnosticMessages.generated.json b/node_modules/typescript/lib/ko/diagnosticMessages.generated.json new file mode 100644 index 0000000..a1b1320 --- /dev/null +++ b/node_modules/typescript/lib/ko/diagnosticMessages.generated.json @@ -0,0 +1,1101 @@ +{ + "A_0_modifier_cannot_be_used_with_an_import_declaration_1079": "'{0}' 한정자는 가져오기 선언에서 사용할 수 없습니다.", + "A_0_modifier_cannot_be_used_with_an_interface_declaration_1045": "'{0}' 한정자는 인터페이스 선언에서 사용할 수 없습니다.", + "A_0_parameter_must_be_the_first_parameter_2680": "'{0}' 매개 변수는 첫 번째 매개 변수여야 합니다.", + "A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature_2463": "바인딩 패턴 매개 변수는 구현 서명에서 선택 사항이 될 수 없습니다.", + "A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement_1105": "'break' 문은 이 문을 둘러싼 반복문 또는 switch 문 내에서만 사용할 수 있습니다.", + "A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement_1116": "'break' 문은 이 문을 둘러싼 문의 레이블로만 이동할 수 있습니다.", + "A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments_2500": "클래스는 선택적 형식 인수가 포함된 식별자/정규화된 이름만 구현할 수 있습니다.", + "A_class_declaration_without_the_default_modifier_must_have_a_name_1211": "'default' 한정자를 사용하지 않는 클래스 선언에는 이름이 있어야 합니다.", + "A_class_may_only_extend_another_class_2311": "클래스는 다른 클래스만 확장할 수 있습니다.", + "A_class_may_only_implement_another_class_or_interface_2422": "클래스는 다른 클래스나 인터페이스만 구현할 수 있습니다.", + "A_class_member_cannot_have_the_0_keyword_1248": "클래스 멤버에는 '{0}' 키워드를 사용할 수 없습니다.", + "A_comma_expression_is_not_allowed_in_a_computed_property_name_1171": "쉼표 식은 컴퓨팅된 속성 이름에 사용할 수 없습니다.", + "A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type_2467": "계산된 속성 이름에서는 포함하는 형식의 형식 매개 변수를 참조할 수 없습니다.", + "A_computed_property_name_in_a_class_property_declaration_must_refer_to_an_expression_whose_type_is_a_1166": "클래스 속성 선언의 계산된 속성 이름은 형식이 리터럴 형식이거나 'unique symbol' 형식인 식을 참조해야 합니다.", + "A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_ty_1168": "메서드 오버로드의 계산된 속성 이름은 형식이 리터럴 형식이거나 'unique symbol' 형식인 식을 참조해야 합니다.", + "A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type__1170": "리터럴 형식의 계산된 속성 이름은 형식이 리터럴 형식이거나 'unique symbol' 형식인 식을 참조해야 합니다.", + "A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_t_1165": "앰비언트 컨텍스트의 계산된 속성 이름은 형식이 리터럴 형식이거나 'unique symbol' 형식인 식을 참조해야 합니다.", + "A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_1169": "인터페이스의 계산된 속성 이름은 형식이 리터럴 형식이거나 'unique symbol' 형식인 식을 참조해야 합니다.", + "A_computed_property_name_must_be_of_type_string_number_symbol_or_any_2464": "계산된 속성 이름은 'string', 'number', 'symbol' 또는 'any' 형식이어야 합니다.", + "A_computed_property_name_of_the_form_0_must_be_of_type_symbol_2471": "'{0}' 양식의 계산된 속성 이름은 'symbol' 형식이어야 합니다.", + "A_const_enum_member_can_only_be_accessed_using_a_string_literal_2476": "const 열거형 멤버는 문자열 리터럴을 통해서만 액세스할 수 있습니다.", + "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_1254": "앰비언트 컨텍스트의 'const' 이니셜라이저는 문자열 또는 숫자 리터럴이어야 합니다.", + "A_constructor_cannot_contain_a_super_call_when_its_class_extends_null_17005": "생성자는 해당 클래스가 'null'을 확장하는 경우 'super' 호출을 포함할 수 없습니다.", + "A_constructor_cannot_have_a_this_parameter_2681": "생성자에는 'this' 매개 변수를 사용할 수 없습니다.", + "A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement_1104": "'continue' 문은 이 문을 둘러싼 반복문 내에서만 사용할 수 있습니다.", + "A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement_1115": "'continue' 문은 이 문을 둘러싼 반복문의 레이블로만 이동할 수 있습니다.", + "A_declare_modifier_cannot_be_used_in_an_already_ambient_context_1038": "'declare' 한정자는 이미 존재하는 앰비언트 컨텍스트에서 사용할 수 없습니다.", + "A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file_1046": "'declare' 한정자는 .d.ts 파일의 최상위 선언에 필요합니다.", + "A_decorator_can_only_decorate_a_method_implementation_not_an_overload_1249": "데코레이터는 오버로드가 아니라 메서드 구현만 데코레이팅할 수 있습니다.", + "A_default_clause_cannot_appear_more_than_once_in_a_switch_statement_1113": "'default' 절은 'switch' 문에 두 번 이상 나올 수 없습니다.", + "A_default_export_can_only_be_used_in_an_ECMAScript_style_module_1319": "기본 내보내기는 ECMAScript 스타일 모듈에서만 사용할 수 있습니다.", + "A_definite_assignment_assertion_is_not_permitted_in_this_context_1255": "이 컨텍스트에서는 한정된 할당 어설션 '!'가 허용되지 않습니다.", + "A_destructuring_declaration_must_have_an_initializer_1182": "구조 파괴 선언에 이니셜라이저가 있어야 합니다.", + "A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declarat_2712": "ES5/ES3의 동적 가져오기 호출에 'Promise' 생성자가 필요합니다. 'Promise' 생성자에 대한 선언이 있거나 `--lib` 옵션에 'ES2015'가 포함되었는지 확인하세요.", + "A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES20_2711": "동적 가져오기 호출은 'Promise'를 반환합니다. 'Promise'에 대한 선언이 있거나 `--lib` 옵션에 'ES2015'가 포함되었는지 확인하세요.", + "A_file_cannot_have_a_reference_to_itself_1006": "파일은 자신에 대한 참조를 포함할 수 없습니다.", + "A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator_1103": "'for-await-of' 식은 비동기 함수 또는 비동기 생성기 내에서만 사용할 수 있습니다.", + "A_function_returning_never_cannot_have_a_reachable_end_point_2534": "'never'를 반환하는 함수에는 연결 가능한 끝점이 있을 수 없습니다.", + "A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void_2679": "'new' 키워드로 호출한 함수에는 'void'인 'this' 형식을 사용할 수 없습니다.", + "A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value_2355": "선언된 형식이 'void'도 'any'도 아닌 함수는 값을 반환해야 합니다.", + "A_generator_cannot_have_a_void_type_annotation_2505": "생성기에는 'void' 형식 주석을 사용할 수 없습니다.", + "A_get_accessor_cannot_have_parameters_1054": "'get' 접근자에는 매개 변수를 사용할 수 없습니다.", + "A_get_accessor_must_return_a_value_2378": "'get' 접근자는 값을 반환해야 합니다.", + "A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_memb_2651": "열거형 선언의 멤버 이니셜라이저는 그 뒤에 선언된 멤버와 다른 열거형에 정의된 멤버를 참조할 수 없습니다.", + "A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any_2545": "mixin 클래스에는 'any[]' 형식의 rest 매개 변수 하나를 사용하는 생성자가 있어야 합니다.", + "A_module_cannot_have_multiple_default_exports_2528": "모듈에는 기본 내보내기가 여러 개 있을 수 없습니다.", + "A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merg_2433": "네임스페이스 선언은 해당 선언이 병합된 클래스나 함수와 다른 파일에 있을 수 없습니다,", + "A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged_2434": "네임스페이스 선언은 해당 선언이 병합된 클래스나 함수 앞에 있을 수 없습니다.", + "A_namespace_declaration_is_only_allowed_in_a_namespace_or_module_1235": "네임스페이스 선언은 네임스페이스 또는 모듈에서만 사용할 수 있습니다.", + "A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_7038": "네임스페이스 스타일 가져오기를 호출하거나 생성할 수 없으며 런타임 시 오류가 발생합니다.", + "A_non_dry_build_would_build_project_0_6357": "-dry가 아닌 빌드는 프로젝트 '{0}'을(를) 빌드합니다.", + "A_non_dry_build_would_delete_the_following_files_Colon_0_6356": "-dry가 아닌 빌드는 다음 파일을 삭제합니다. {0}", + "A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation_2371": "매개 변수 이니셜라이저는 함수 또는 생성자 구현에서만 허용됩니다.", + "A_parameter_property_cannot_be_declared_using_a_rest_parameter_1317": "rest 매개 변수를 사용하여 매개 변수 속성을 선언할 수 없습니다.", + "A_parameter_property_is_only_allowed_in_a_constructor_implementation_2369": "매개 변수 속성은 생성자 구현에서만 허용됩니다.", + "A_parameter_property_may_not_be_declared_using_a_binding_pattern_1187": "바인딩 패턴을 사용하여 매개 변수 속성을 선언할 수 없습니다.", + "A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not_18001": "'extends' 옵션의 경로는 상대 경로이거나 루트 경로여야 하지만 '{0}'은(는) 아닙니다.", + "A_promise_must_have_a_then_method_1059": "프라미스에는 'then' 메서드가 있어야 합니다.", + "A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly_1331": "형식이 'unique symbol' 형식인 클래스의 속성은 'static'과 'readonly' 둘 다여야 합니다.", + "A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly_1330": "형식이 'unique symbol' 형식인 인터페이스 또는 형식 리터럴의 속성은 'readonly'여야 합니다.", + "A_required_parameter_cannot_follow_an_optional_parameter_1016": "필수 매개 변수는 선택적 매개 변수 뒤에 올 수 없습니다.", + "A_rest_element_cannot_contain_a_binding_pattern_2501": "rest 요소에는 바인딩 패턴이 포함될 수 없습니다.", + "A_rest_element_cannot_have_a_property_name_2566": "rest 요소에는 속성 이름을 사용할 수 없습니다.", + "A_rest_element_cannot_have_an_initializer_1186": "rest 요소에는 이니셜라이저를 사용할 수 없습니다.", + "A_rest_element_must_be_last_in_a_destructuring_pattern_2462": "rest 요소는 배열 구조 파괴 패턴의 마지막 요소여야 합니다.", + "A_rest_parameter_cannot_be_optional_1047": "rest 매개 변수는 선택 사항이 될 수 없습니다.", + "A_rest_parameter_cannot_have_an_initializer_1048": "rest 매개 변수에는 이니셜라이저를 사용할 수 없습니다.", + "A_rest_parameter_must_be_last_in_a_parameter_list_1014": "rest 매개 변수는 매개 변수 목록 마지막에 있어야 합니다.", + "A_rest_parameter_must_be_of_an_array_type_2370": "rest 매개 변수는 배열 형식이어야 합니다.", + "A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma_1013": "rest 매개 변수 또는 바인딩 패턴에 후행 쉼표가 없을 수 있습니다.", + "A_return_statement_can_only_be_used_within_a_function_body_1108": "'return' 문은 함수 본문 내에서만 사용할 수 있습니다.", + "A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl_6167": "가져오기를 'baseUrl'에 상대적인 조회 위치로 다시 매핑하는 일련의 항목입니다.", + "A_set_accessor_cannot_have_a_return_type_annotation_1095": "'set' 접근자에는 반환 형식 주석을 사용할 수 없습니다.", + "A_set_accessor_cannot_have_an_optional_parameter_1051": "'set' 접근자에는 선택적 매개 변수를 사용할 수 없습니다.", + "A_set_accessor_cannot_have_rest_parameter_1053": "'set' 접근자에는 rest 매개 변수를 사용할 수 없습니다.", + "A_set_accessor_must_have_exactly_one_parameter_1049": "'set' 접근자에는 매개 변수를 하나만 사용해야 합니다.", + "A_set_accessor_parameter_cannot_have_an_initializer_1052": "'set' 접근자 매개 변수에는 이니셜라이저를 사용할 수 없습니다.", + "A_signature_with_an_implementation_cannot_use_a_string_literal_type_2381": "구현이 있는 서명에는 문자열 리터럴 형식을 사용할 수 없습니다.", + "A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_proper_2376": "클래스에 초기화된 속성이 있거나 매개 변수 속성이 있으면 'super' 호출이 생성자에서 첫 번째 문이어야 합니다.", + "A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard_2518": "'this' 기반 형식 가드는 매개 변수 기반 형식 가드와 호환되지 않습니다.", + "A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface_2526": "'this' 형식은 클래스 또는 인터페이스의 비정적 멤버에서만 사용할 수 있습니다.", + "A_tsconfig_json_file_is_already_defined_at_Colon_0_5054": "'tsconfig.json' 파일이 이미 '{0}'에 정의되어 있습니다.", + "A_tuple_type_element_list_cannot_be_empty_1122": "튜플 형식 요소 목록은 비워 둘 수 없습니다.", + "A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Con_17007": "지수 식의 왼쪽에는 type assertion expression을 사용할 수 없습니다. 식을 괄호로 묶는 것이 좋습니다.", + "A_type_literal_property_cannot_have_an_initializer_1247": "형식 리터럴 속성에는 이니셜라이저를 사용할 수 없습니다.", + "A_type_predicate_cannot_reference_a_rest_parameter_1229": "형식 조건자는 rest 매개 변수를 참조할 수 없습니다.", + "A_type_predicate_cannot_reference_element_0_in_a_binding_pattern_1230": "형식 조건자는 바인딩 패턴에서 '{0}' 요소를 참조할 수 없습니다.", + "A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods_1228": "형식 조건자는 함수 및 메서드의 반환 형식 위치에서만 사용할 수 있습니다.", + "A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type_2677": "형식 조건자의 형식을 해당 매개 변수의 형식에 할당할 수 있어야 합니다.", + "A_variable_whose_type_is_a_unique_symbol_type_must_be_const_1332": "형식이 'unique symbol' 형식인 변수는 'const'여야 합니다.", + "A_yield_expression_is_only_allowed_in_a_generator_body_1163": "'yield' 식은 생성기 본문에서만 사용할 수 있습니다.", + "Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression_2513": "super 식을 통해 '{1}' 클래스의 추상 메서드 '{0}'에 액세스할 수 없습니다.", + "Abstract_methods_can_only_appear_within_an_abstract_class_1244": "추상 메서드는 추상 클래스 내에서만 사용할 수 있습니다.", + "Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor_2715": "생성자에서 '{1}' 클래스의 추상 속성 '{0}'에 액세스할 수 없습니다.", + "Accessibility_modifier_already_seen_1028": "액세스 가능성 한정자가 이미 있습니다.", + "Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher_1056": "접근자는 ECMAScript 5 이상을 대상으로 지정할 때만 사용할 수 있습니다.", + "Accessors_must_both_be_abstract_or_non_abstract_2676": "접근자는 모두 추상이거나 비추상이어야 합니다.", + "Add_0_to_existing_import_declaration_from_1_90015": "\"{1}\"에서 기존 가져오기 선언에 '{0}' 추가", + "Add_0_to_unresolved_variable_90008": "확인되지 않은 변수에 '{0}.' 추가", + "Add_all_missing_async_modifiers_95041": "누락된 모든 'async' 한정자 추가", + "Add_all_missing_members_95022": "누락된 모든 멤버 추가", + "Add_all_missing_super_calls_95039": "누락된 모든 super 호출 추가", + "Add_async_modifier_to_containing_function_90029": "포함된 함수에 async 한정자 추가", + "Add_braces_to_arrow_function_95059": "화살표 함수에 중괄호 추가", + "Add_definite_assignment_assertion_to_property_0_95020": "'{0}' 속성에 한정된 할당 어설션 추가", + "Add_definite_assignment_assertions_to_all_uninitialized_properties_95028": "초기화되지 않은 모든 속성에 한정된 할당 어설션 추가", + "Add_index_signature_for_property_0_90017": "'{0}' 속성에 대해 인덱스 시그니처 추가", + "Add_initializer_to_property_0_95019": "'{0}' 속성에 이니셜라이저 추가", + "Add_initializers_to_all_uninitialized_properties_95027": "초기화되지 않은 모든 속성에 이니셜라이저 추가", + "Add_missing_super_call_90001": "누락된 'super()' 호출 추가", + "Add_missing_typeof_95052": "누락된 'typeof' 추가", + "Add_or_remove_braces_in_an_arrow_function_95058": "화살표 함수에 중괄호 추가 또는 제거", + "Add_qualifier_to_all_unresolved_variables_matching_a_member_name_95037": "멤버 이름과 일치하는 모든 확인되지 않은 변수에 한정자 추가", + "Add_to_all_uncalled_decorators_95044": "호출되지 않는 모든 데코레이터에 '()' 추가", + "Add_ts_ignore_to_all_error_messages_95042": "모든 오류 메시지에 '@ts-ignore' 추가", + "Add_undefined_type_to_all_uninitialized_properties_95029": "초기화되지 않은 모든 속성에 정의되지 않은 형식 추가", + "Add_undefined_type_to_property_0_95018": "'{0}' 속성에 '정의되지 않은' 형식 추가", + "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068": "tsconfig.json 파일을 추가하면 TypeScript 파일과 JavaScript 파일이 둘 다 포함된 프로젝트를 정리하는 데 도움이 됩니다. 자세한 내용은 https://aka.ms/tsconfig를 참조하세요.", + "Additional_Checks_6176": "추가 검사", + "Advanced_Options_6178": "고급 옵션", + "All_declarations_of_0_must_have_identical_modifiers_2687": "'{0}'의 모든 선언에는 동일한 한정자가 있어야 합니다.", + "All_declarations_of_0_must_have_identical_type_parameters_2428": "'{0}'의 모든 선언에는 동일한 형식 매개 변수가 있어야 합니다.", + "All_declarations_of_an_abstract_method_must_be_consecutive_2516": "추상 메서드의 모든 선언은 연속적이어야 합니다.", + "All_destructured_elements_are_unused_6198": "구조 파괴된 요소가 모두 사용되지 않습니다.", + "All_imports_in_import_declaration_are_unused_6192": "가져오기 선언의 모든 가져오기가 사용되지 않습니다.", + "All_variables_are_unused_6199": "모든 변수가 사용되지 않습니다.", + "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011": "기본 내보내기가 없는 모듈에서 기본 가져오기를 허용합니다. 여기서는 코드 내보내기에는 영향을 주지 않고 형식 검사만 합니다.", + "Allow_javascript_files_to_be_compiled_6102": "Javascript 파일을 컴파일하도록 허용합니다.", + "Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided_1209": "'--isolatedModules' 플래그가 제공된 경우 앰비언트 const 열거형이 허용되지 않습니다.", + "Ambient_module_declaration_cannot_specify_relative_module_name_2436": "앰비언트 모듈 선언은 상대적 모듈 이름을 지정할 수 없습니다.", + "Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces_2435": "앰비언트 모듈은 다른 모듈 또는 네임스페이스에 중첩될 수 없습니다.", + "An_AMD_module_cannot_have_multiple_name_assignments_2458": "AMD 모듈에는 여러 이름이 할당될 수 없습니다.", + "An_abstract_accessor_cannot_have_an_implementation_1318": "추상 접근자는 구현이 있을 수 없습니다.", + "An_accessor_cannot_be_declared_in_an_ambient_context_1086": "접근자는 앰비언트 컨텍스트에서 선언될 수 없습니다.", + "An_accessor_cannot_have_type_parameters_1094": "접근자에는 형식 매개 변수를 사용할 수 없습니다.", + "An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file_1234": "앰비언트 모듈 선언은 파일의 최상위에서만 사용할 수 있습니다.", + "An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type_2356": "산술 피연산자는 'any', 'number' 또는 열거형 형식이어야 합니다.", + "An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_de_2705": "ES5/ES3의 비동기 함수 또는 메서드에 'Promise' 생성자가 필요합니다. 'Promise' 생성자에 대한 선언이 있거나 `--lib` 옵션에 'ES2015'가 포함되었는지 확인하세요.", + "An_async_function_or_method_must_have_a_valid_awaitable_return_type_1057": "비동기 함수 또는 메서드에는 유효한 대기 가능 반환 형식이 있어야 합니다.", + "An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_in_2697": "비동기 함수 또는 메서드는 'Promise'를 반환해야 합니다. 'Promise'에 대한 선언이 있거나 `--lib` 옵션에 'ES2015'가 포함되었는지 확인하세요.", + "An_async_iterator_must_have_a_next_method_2519": "비동기 반복기에는 'next()' 메서드가 있어야 합니다.", + "An_element_access_expression_should_take_an_argument_1011": "요소 액세스 식은 인수를 사용해야 합니다.", + "An_enum_member_cannot_have_a_numeric_name_2452": "열거형 멤버는 숫자 이름을 가질 수 없습니다.", + "An_export_assignment_can_only_be_used_in_a_module_1231": "내보내기 할당은 모듈에서만 사용할 수 있습니다.", + "An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements_2309": "내보내기 할당은 다른 내보낸 요소가 있는 모듈에서 사용될 수 없습니다.", + "An_export_assignment_cannot_be_used_in_a_namespace_1063": "내보내기 할당은 네임스페이스에서 사용될 수 없습니다.", + "An_export_assignment_cannot_have_modifiers_1120": "내보내기 할당에는 한정자를 사용할 수 없습니다.", + "An_export_declaration_can_only_be_used_in_a_module_1233": "내보내기 선언은 모듈에서만 사용할 수 있습니다.", + "An_export_declaration_cannot_have_modifiers_1193": "내보내기 선언에는 한정자를 사용할 수 없습니다.", + "An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive_1198": "확장된 유니코드 이스케이프 값은 0x0과 0x10FFFF(포함) 사이여야 합니다.", + "An_implementation_cannot_be_declared_in_ambient_contexts_1183": "앰비언트 컨텍스트에서는 구현을 선언할 수 없습니다.", + "An_import_declaration_can_only_be_used_in_a_namespace_or_module_1232": "내보내기 선언은 네임스페이스 또는 모듈에서만 사용할 수 있습니다.", + "An_import_declaration_cannot_have_modifiers_1191": "가져오기 선언에는 한정자를 사용할 수 없습니다.", + "An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead_2691": "가져오기 경로는 '{0}' 확장으로 끝날 수 없습니다. 대신 '{1}' 가져오기를 고려하세요.", + "An_index_expression_argument_must_be_of_type_string_number_symbol_or_any_2342": "인덱스 식 인수는 'string', 'number', 'symbol' 또는 'any' 형식이어야 합니다.", + "An_index_signature_cannot_have_a_rest_parameter_1017": "인덱스 시그니처에는 rest 매개 변수를 사용할 수 없습니다.", + "An_index_signature_must_have_a_type_annotation_1021": "인덱스 시그니처에는 형식 주석을 사용할 수 없습니다.", + "An_index_signature_must_have_exactly_one_parameter_1096": "인덱스 시그니처에는 한 개의 매개 변수만 사용할 수 있습니다.", + "An_index_signature_parameter_cannot_have_a_question_mark_1019": "인덱스 시그니처 매개 변수에는 물음표를 사용할 수 없습니다.", + "An_index_signature_parameter_cannot_have_an_accessibility_modifier_1018": "인덱스 시그니처 매개 변수에는 액세스 가능성 한정자를 사용할 수 없습니다.", + "An_index_signature_parameter_cannot_have_an_initializer_1020": "인덱스 시그니처 매개 변수에는 이니셜라이저를 사용할 수 없습니다.", + "An_index_signature_parameter_must_have_a_type_annotation_1022": "인덱스 시그니처 매개 변수에는 형식 주석을 사용할 수 없습니다.", + "An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead_1336": "인덱스 시그니처 매개 변수 형식은 형식 별칭일 수 없습니다. 대신 '[{0}: {1}]: {2}'을(를) 작성하세요.", + "An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead_1337": "인덱스 시그니처 매개 변수 형식은 공용 구조체 형식일 수 없습니다. 대신 매핑된 개체 형식을 사용하세요.", + "An_index_signature_parameter_type_must_be_string_or_number_1023": "인덱스 시그니처 매개 변수 형식은 'string' 또는 'number'여야 합니다.", + "An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments_2499": "인터페이스는 선택적 형식 인수가 포함된 식별자/정규화된 이름만 확장할 수 있습니다.", + "An_interface_may_only_extend_a_class_or_another_interface_2312": "인터페이스는 클래스 또는 다른 인터페이스만 확장할 수 있습니다.", + "An_interface_property_cannot_have_an_initializer_1246": "인터페이스 속성에는 이니셜라이저를 사용할 수 없습니다.", + "An_iterator_must_have_a_next_method_2489": "반복기에는 'next()' 메서드가 있어야 합니다.", + "An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name_1118": "개체 리터럴에 이름이 같은 여러 개의 get/set 접근자를 사용할 수 없습니다.", + "An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode_1117": "strict 모드에서는 개체 리터럴에 이름이 같은 여러 개의 속성을 사용할 수 없습니다.", + "An_object_literal_cannot_have_property_and_accessor_with_the_same_name_1119": "개체 리터럴에 이름이 같은 속성과 접근자를 사용할 수 없습니다.", + "An_object_member_cannot_be_declared_optional_1162": "개체 멤버는 선택적으로 선언될 수 없습니다.", + "An_overload_signature_cannot_be_declared_as_a_generator_1222": "오버로드 시그니처는 생성기로 선언할 수 없습니다.", + "An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_ex_17006": "지수 식의 왼쪽에는 '{0}' 연산자가 있는 단항 식을 사용할 수 없습니다. 식을 괄호로 묶는 것이 좋습니다.", + "Annotate_everything_with_types_from_JSDoc_95043": "JSDoc의 형식을 사용하여 모든 항목에 주석 달기", + "Annotate_with_type_from_JSDoc_95009": "JSDoc의 형식을 사용하여 주석 추가", + "Annotate_with_types_from_JSDoc_95010": "JSDoc의 형식을 사용하여 주석 추가", + "Argument_expression_expected_1135": "인수 식이 필요합니다.", + "Argument_for_0_option_must_be_Colon_1_6046": "'{0}' 옵션의 인수는 {1}이어야(여야) 합니다.", + "Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_2345": "'{0}' 형식의 인수는 '{1}' 형식의 매개 변수에 할당될 수 없습니다.", + "Array_element_destructuring_pattern_expected_1181": "배열 요소 구조 파괴 패턴이 필요합니다.", + "Asterisk_Slash_expected_1010": "'*/'가 필요합니다.", + "Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_2669": "전역 범위에 대한 확대는 외부 모듈 또는 앰비언트 모듈 선언에만 직접 중첩될 수 있습니다.", + "Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambien_2670": "전역 범위에 대한 확대는 이미 존재하는 앰비언트 컨텍스트에 표시되지 않는 한 'declare' 한정자를 포함해야 합니다.", + "Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using__6140": "프로젝트 '{0}'에서 입력에 대한 자동 검색을 사용하도록 설정되었습니다. '{2}' 캐시 위치를 사용하여 모듈 '{1}'에 대해 추가 해결 패스를 실행합니다.", + "Base_class_expressions_cannot_reference_class_type_parameters_2562": "기본 클래스 식에서 클래스 형식 매개 변수를 참조할 수 없습니다.", + "Base_constructor_return_type_0_is_not_a_class_or_interface_type_2509": "기본 생성자 반환 형식 '{0}'은(는) 클래스 또는 인터페이스 형식이 아닙니다.", + "Base_constructors_must_all_have_the_same_return_type_2510": "기본 생성자는 모두 반환 형식이 같아야 합니다.", + "Base_directory_to_resolve_non_absolute_module_names_6083": "비추상 모듈 이름을 확인할 기본 디렉터리입니다.", + "Basic_Options_6172": "기본 옵션", + "Binary_digit_expected_1177": "이진수가 있어야 합니다.", + "Binding_element_0_implicitly_has_an_1_type_7031": "바인딩 요소 '{0}'에 암시적으로 '{1}' 형식이 있습니다.", + "Block_scoped_variable_0_used_before_its_declaration_2448": "선언 전에 사용된 블록 범위 변수 '{0}'입니다.", + "Build_all_projects_including_those_that_appear_to_be_up_to_date_6368": "최신 상태로 표시될 프로젝트를 포함하여 모든 프로젝트 빌드", + "Build_one_or_more_projects_and_their_dependencies_if_out_of_date_6364": "최신 상태가 아닌 경우, 하나 이상의 프로젝트 및 해당 종속성 빌드", + "Building_project_0_6358": "'{0}' 프로젝트를 빌드하는 중...", + "Call_decorator_expression_90028": "데코레이터 식 호출", + "Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7020": "반환 형식 주석이 없는 호출 시그니처에는 암시적으로 'any' 반환 형식이 포함됩니다.", + "Call_target_does_not_contain_any_signatures_2346": "호출 대상에 시그니처가 포함되어 있지 않습니다.", + "Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_p_2713": "'{0}'이(가) 네임스페이스가 아니라 형식이므로 '{0}.{1}'에 액세스할 수 없습니다. '{0}'에서 '{0}[\"{1}\"]'과(와) 함께 '{1}' 속성의 형식을 검색하려고 했나요?", + "Cannot_assign_a_0_constructor_type_to_a_1_constructor_type_2672": "'{0}' 생성자 형식을 '{1}' 생성자 형식에 할당할 수 없습니다.", + "Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type_2517": "추상 생성자 형식을 비추상 생성자 형식에 할당할 수 없습니다.", + "Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property_2540": "상수 또는 읽기 전용 속성이므로 '{0}'에 할당할 수 없습니다.", + "Cannot_assign_to_0_because_it_is_not_a_variable_2539": "변수가 아니므로 '{0}'에 할당할 수 없습니다.", + "Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity_2671": "'{0}' 모듈은 모듈이 아닌 엔터티로 확인되므로 확대할 수 없습니다.", + "Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity_2649": "모듈이 아닌 엔터티로 확인되기 때문에 값 내보내기로 모듈 '{0}'을(를) 확대할 수 없습니다.", + "Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system_6131": "'--module' 플래그가 'amd' 또는 'system'이 아닌 경우 '{0}' 옵션을 사용하여 모듈을 컴파일할 수 없습니다.", + "Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided_1208": "'--isolatedModules' 플래그가 제공된 경우 네임스페이스를 컴파일할 수 없습니다.", + "Cannot_create_an_instance_of_an_abstract_class_2511": "추상 클래스의 인스턴스를 만들 수 없습니다.", + "Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module_2661": "'{0}'을(를) 내보낼 수 없습니다. 지역 선언만 모듈에서 내보낼 수 있습니다.", + "Cannot_extend_a_class_0_Class_constructor_is_marked_as_private_2675": "'{0}' 클래스를 확장할 수 없습니다. 클래스 생성자가 private로 표시되어 있습니다.", + "Cannot_extend_an_interface_0_Did_you_mean_implements_2689": "인터페이스 '{0}'을(를) 확장할 수 없습니다. 'implements'를 확장하시겠습니까?", + "Cannot_find_a_tsconfig_json_file_at_the_specified_directory_Colon_0_5057": "지정된 디렉터리에서 tsconfig.json 파일을 찾을 수 없습니다. '{0}'.", + "Cannot_find_global_type_0_2318": "전역 형식 '{0}'을(를) 찾을 수 없습니다.", + "Cannot_find_global_value_0_2468": "전역 값 '{0}'을(를) 찾을 수 없습니다.", + "Cannot_find_lib_definition_for_0_2726": "'{0}'에 대한 lib 정의를 찾을 수 없습니다.", + "Cannot_find_lib_definition_for_0_Did_you_mean_1_2727": "'{0}'에 대한 lib 정의를 찾을 수 없습니다. '{1}'이(가) 아닌지 확인하세요.", + "Cannot_find_module_0_2307": "'{0}' 모듈을 찾을 수 없습니다.", + "Cannot_find_name_0_2304": "'{0}' 이름을 찾을 수 없습니다.", + "Cannot_find_name_0_Did_you_mean_1_2552": "'{0}' 이름을 찾을 수 없습니다. '{1}'을(를) 사용하시겠습니까?", + "Cannot_find_name_0_Did_you_mean_the_instance_member_this_0_2663": "'{0}' 이름을 찾을 수 없습니다. 인스턴스 멤버 'this.{0}'을(를) 사용하시겠습니까?", + "Cannot_find_name_0_Did_you_mean_the_static_member_1_0_2662": "'{0}' 이름을 찾을 수 없습니다. 정적 멤버 '{1}.{0}'을(를) 사용하시겠습니까?", + "Cannot_find_namespace_0_2503": "'{0}' 네임스페이스를 찾을 수 없습니다.", + "Cannot_find_parameter_0_1225": "'{0}' 매개 변수를 찾을 수 없습니다.", + "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009": "입력 파일의 공용 하위 디렉터리 경로를 찾을 수 없습니다.", + "Cannot_find_type_definition_file_for_0_2688": "'{0}'에 대한 형식 정의 파일을 찾을 수 없습니다.", + "Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1_6137": "형식 선언 파일을 가져올 수 없습니다. '{1}' 대신 '{0}'을(를) 가져오세요.", + "Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1_2481": "블록 범위 선언 '{1}'과(와) 동일한 범위 내에서 외부 범위 변수 '{0}'을(를) 초기화할 수 없습니다.", + "Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatur_2349": "형식에 호출 시그니처가 없는 식을 호출할 수 없습니다. '{0}' 형식에 호환되는 호출 시그니처가 없습니다.", + "Cannot_invoke_an_object_which_is_possibly_null_2721": "'null'일 수 있는 개체를 호출할 수 없습니다.", + "Cannot_invoke_an_object_which_is_possibly_null_or_undefined_2723": "'null'이거나 '정의되지 않음'일 수 있는 개체를 호출할 수 없습니다.", + "Cannot_invoke_an_object_which_is_possibly_undefined_2722": "'정의되지 않음'일 수 있는 개체를 호출할 수 없습니다.", + "Cannot_prepend_project_0_because_it_does_not_have_outFile_set_6308": "'{0}' 프로젝트는 'outFile'이 설정되어 있지 않기 때문에 앞에 추가할 수 없습니다.", + "Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205": "'--isolatedModules' 플래그가 제공된 경우 형식을 다시 내보낼 수 없습니다.", + "Cannot_read_file_0_Colon_1_5012": "파일 '{0}'을(를) 읽을 수 없습니다. {1}.", + "Cannot_redeclare_block_scoped_variable_0_2451": "블록 범위 변수 '{0}'을(를) 다시 선언할 수 없습니다.", + "Cannot_redeclare_exported_variable_0_2323": "내보낸 변수 '{0}'을(를) 다시 선언할 수 없습니다.", + "Cannot_redeclare_identifier_0_in_catch_clause_2492": "catch 절에서 식별자 '{0}'을(를) 다시 선언할 수 없습니다.", + "Cannot_use_JSX_unless_the_jsx_flag_is_provided_17004": "'--jsx' 플래그를 제공하지 않으면 JSX를 사용할 수 없습니다.", + "Cannot_use_imports_exports_or_module_augmentations_when_module_is_none_1148": "'--module'이 'none'인 경우 가져오기, 내보내기 또는 모듈 확대를 사용할 수 없습니다.", + "Cannot_use_namespace_0_as_a_type_2709": "'{0}' 네임스페이스를 형식으로 사용할 수 없습니다.", + "Cannot_use_namespace_0_as_a_value_2708": "'{0}' 네임스페이스를 값으로 사용할 수 없습니다.", + "Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature_2351": "형식에 호출 또는 구문 시그니처가 없는 식에는 'new'를 사용할 수 없습니다.", + "Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files_5056": "'{0}' 파일은 여러 입력 파일로 덮어쓰이므로 쓸 수 없습니다.", + "Cannot_write_file_0_because_it_would_overwrite_input_file_5055": "'{0}' 파일은 입력 파일을 덮어쓰므로 쓸 수 없습니다.", + "Catch_clause_variable_cannot_have_a_type_annotation_1196": "Catch 절 변수에 형식 주석을 사용할 수 없습니다.", + "Catch_clause_variable_cannot_have_an_initializer_1197": "Catch 절 변수에 이니셜라이저를 사용할 수 없습니다.", + "Change_0_to_1_90014": "'{0}'을(를) '{1}'(으)로 변경", + "Change_all_extended_interfaces_to_implements_95038": "확장된 모든 인터페이스를 'implements'로 변경", + "Change_all_jsdoc_style_types_to_TypeScript_95030": "모든 jsdoc-style 형식을 TypeScript로 변경", + "Change_all_jsdoc_style_types_to_TypeScript_and_add_undefined_to_nullable_types_95031": "모든 jsdoc-style 형식을 TypeScript로 변경(그리고 nullable 형식에 '| undefined' 추가)", + "Change_extends_to_implements_90003": "'extends'를 'implements'로 변경", + "Change_spelling_to_0_90022": "맞춤법을 '{0}'(으)로 변경", + "Checking_if_0_is_the_longest_matching_prefix_for_1_2_6104": "'{0}'이(가) '{1}' - '{2}'에 대해 일치하는 가장 긴 접두사인지 확인하는 중입니다.", + "Circular_definition_of_import_alias_0_2303": "가져오기 별칭 '{0}'의 순환 정의입니다.", + "Circularity_detected_while_resolving_configuration_Colon_0_18000": "구성을 확인하는 동안 순환이 검색되었습니다. {0}", + "Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_functi_2426": "'{0}' 클래스는 인스턴스 멤버 접근자 '{1}'을(를) 정의하지만 확장 클래스 '{2}'은(는) 이 접근자를 인스턴스 멤버 함수로 정의합니다.", + "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_access_2423": "'{0}' 클래스가 인스턴스 멤버 함수 '{1}'을(를) 정의하지만 확장 클래스 '{2}'은(는) 이 함수를 인스턴스 멤버 접근자로 정의합니다.", + "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_proper_2424": "'{0}' 클래스가 인스턴스 멤버 함수 '{1}'을(를) 정의하지만 확장 클래스 '{2}'은(는) 이 함수를 인스턴스 멤버 속성으로 정의합니다.", + "Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_functi_2425": "'{0}' 클래스가 인스턴스 멤버 속성 '{1}'을(를) 정의하지만 확장 클래스 '{2}'은(는) 이 속성을 인스턴스 멤버 함수로 정의합니다.", + "Class_0_incorrectly_extends_base_class_1_2415": "'{0}' 클래스가 기본 클래스 '{1}'을(를) 잘못 확장합니다.", + "Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclas_2720": "'{0}' 클래스가 '{1}' 클래스를 잘못 구현합니다. '{1}'을(를) 확장하고 이 클래스의 멤버를 하위 클래스로 상속하시겠습니까?", + "Class_0_incorrectly_implements_interface_1_2420": "'{0}' 클래스가 '{1}' 인터페이스를 잘못 구현합니다.", + "Class_0_used_before_its_declaration_2449": "선언 전에 사용된 '{0}' 클래스입니다.", + "Class_declarations_cannot_have_more_than_one_augments_or_extends_tag_8025": "클래스 선언은 '@augments' 또는 `@extends` 태그를 둘 이상 가질 수 없습니다.", + "Class_name_cannot_be_0_2414": "클래스 이름은 '{0}'일 수 없습니다.", + "Class_name_cannot_be_Object_when_targeting_ES5_with_module_0_2725": "{0} 모듈을 사용하는 ES5를 대상으로 하는 경우 클래스 이름은 'Object'일 수 없습니다.", + "Class_static_side_0_incorrectly_extends_base_class_static_side_1_2417": "클래스 정적 측면 '{0}'이(가) 기본 클래스 정적 측면 '{1}'을(를) 잘못 확장합니다.", + "Classes_can_only_extend_a_single_class_1174": "클래스는 단일 클래스만 확장할 수 있습니다.", + "Classes_containing_abstract_methods_must_be_marked_abstract_2514": "추상 메서드를 포함하는 클래스는 abstract로 표시되어 있어야 합니다.", + "Command_line_Options_6171": "명령줄 옵션", + "Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json_6020": "구성 파일에 대한 경로 또는 'tsconfig.json'이 포함된 폴더에 대한 경로를 고려하여 프로젝트를 컴파일합니다.", + "Compiler_option_0_expects_an_argument_6044": "컴파일러 옵션 '{0}'에는 인수가 필요합니다.", + "Compiler_option_0_requires_a_value_of_type_1_5024": "컴파일러 옵션 '{0}'에 {1} 형식의 값이 필요합니다.", + "Composite_projects_may_not_disable_declaration_emit_6304": "복합 프로젝트는 선언 내보내기를 비활성화할 수 없습니다.", + "Computed_property_names_are_not_allowed_in_enums_1164": "컴퓨팅된 속성 이름은 열거형에 사용할 수 없습니다.", + "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553": "계산된 값은 문자열 값 멤버가 포함된 열거형에서 허용되지 않습니다.", + "Concatenate_and_emit_output_to_single_file_6001": "출력을 연결하고 단일 파일로 내보냅니다.", + "Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_librar_4090": "'{1}' 및 '{2}'에서 '{0}'에 대한 정의가 충돌하고 있습니다. 이 라이브러리의 특정 버전을 설치하여 충돌을 해결하세요.", + "Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7013": "반환 형식 주석이 없는 구문 시그니처에는 암시적으로 'any' 반환 형식이 포함됩니다.", + "Constructor_implementation_is_missing_2390": "생성자 구현이 없습니다.", + "Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration_2673": "'{0}' 클래스의 생성자는 private이며 클래스 선언 내에서만 액세스할 수 있습니다.", + "Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration_2674": "'{0}' 클래스의 생성자는 protected이며 클래스 선언 내에서만 액세스할 수 있습니다.", + "Constructors_for_derived_classes_must_contain_a_super_call_2377": "파생 클래스의 생성자는 'super' 호출을 포함해야 합니다.", + "Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126": "포함 파일이 지정되지 않았고 루트 디렉터리를 확인할 수 없어 'node_modules' 폴더 조회를 건너뜁니다.", + "Convert_0_to_mapped_object_type_95055": "'{0}'을(를) 매핑된 개체 형식으로 변환", + "Convert_all_constructor_functions_to_classes_95045": "모든 생성자 함수를 클래스로 변환", + "Convert_all_require_to_import_95048": "모든 'require'를 'import'로 변환", + "Convert_all_to_default_imports_95035": "모든 항목을 기본 가져오기로 변환", + "Convert_function_0_to_class_95002": "'{0}' 함수를 클래스로 변환", + "Convert_function_to_an_ES2015_class_95001": "함수를 ES2015 클래스로 변환", + "Convert_named_imports_to_namespace_import_95057": "명명된 가져오기를 네임스페이스 가져오기로 변환", + "Convert_namespace_import_to_named_imports_95056": "네임스페이스 가져오기를 명명된 가져오기로 변환", + "Convert_require_to_import_95047": "'require'를 'import'로 변환", + "Convert_to_ES6_module_95017": "ES6 모듈로 변환", + "Convert_to_default_import_95013": "기본 가져오기로 변환", + "Corrupted_locale_file_0_6051": "로캘 파일 {0}이(가) 손상되었습니다.", + "Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type_7016": "모듈 '{0}'에 대한 선언 파일을 찾을 수 없습니다. '{1}'에는 암시적으로 'any' 형식이 포함됩니다.", + "Could_not_write_file_0_Colon_1_5033": "'{0}' 파일을 쓸 수 없습니다. '{1}'.", + "DIRECTORY_6038": "디렉터리", + "Declaration_expected_1146": "선언이 필요합니다.", + "Declaration_name_conflicts_with_built_in_global_identifier_0_2397": "선언 이름이 기본 제공 전역 ID '{0}'과(와) 충돌합니다.", + "Declaration_or_statement_expected_1128": "선언 또는 문이 필요합니다.", + "Declare_method_0_90023": "'{0}' 메서드 선언", + "Declare_property_0_90016": "'{0}' 속성 선언", + "Declare_static_method_0_90024": "'{0}' 정적 메서드 선언", + "Declare_static_property_0_90027": "'{0}' 정적 속성 선언", + "Decorators_are_not_valid_here_1206": "데코레이터는 여기에 사용할 수 없습니다.", + "Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name_1207": "동일한 이름의 여러 get/set 접근자에 데코레이터를 적용할 수 없습니다.", + "Default_export_of_the_module_has_or_is_using_private_name_0_4082": "모듈의 기본 내보내기에서 전용 이름 '{0}'을(를) 가지고 있거나 사용 중입니다.", + "Delete_all_unused_declarations_95024": "사용하지 않는 선언 모두 삭제", + "Delete_the_outputs_of_all_projects_6365": "모든 프로젝트의 출력 삭제", + "Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react__6084": "[사용되지 않음] 대신 '--jsxFactory'를 사용합니다. 'react' JSX 내보내기를 대상으로 할 경우 createElement에 대해 호출되는 개체를 지정합니다.", + "Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file_6170": "[사용되지 않음] 대신 '--outFile'을 사용합니다. 출력을 연결하고 단일 파일로 내보냅니다.", + "Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files_6160": "[사용되지 않음] 대신 '--skipLibCheck'를 사용합니다. 기본 라이브러리 선언 파일의 형식 검사를 건너뜁니다.", + "Digit_expected_1124": "숫자가 필요합니다.", + "Directory_0_does_not_exist_skipping_all_lookups_in_it_6148": "'{0}' 디렉터리가 없으므로 이 디렉터리에서 모든 조회를 건너뜁니다.", + "Disable_checking_for_this_file_90018": "이 파일 확인을 사용하지 않도록 설정", + "Disable_size_limitations_on_JavaScript_projects_6162": "JavaScript 프로젝트에 대한 크기 제한을 사용하지 않도록 설정합니다.", + "Disable_strict_checking_of_generic_signatures_in_function_types_6185": "함수 형식의 제네릭 시그니처에 대한 엄격한 검사를 사용하지 않도록 설정합니다.", + "Disallow_inconsistently_cased_references_to_the_same_file_6078": "동일한 파일에 대해 대/소문자를 일관되지 않게 사용한 참조를 허용하지 않습니다.", + "Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files_6159": "컴파일된 파일 목록에 삼중 슬래시 참조 또는 가져온 모듈을 추가하지 않습니다.", + "Do_not_emit_comments_to_output_6009": "주석을 출력에 내보내지 마세요.", + "Do_not_emit_declarations_for_code_that_has_an_internal_annotation_6056": "'@internal' 주석이 있는 코드에 대한 선언을 내보내지 마세요.", + "Do_not_emit_outputs_6010": "출력을 내보내지 않습니다.", + "Do_not_emit_outputs_if_any_errors_were_reported_6008": "오류가 보고되면 출력을 내보내지 않습니다.", + "Do_not_emit_use_strict_directives_in_module_output_6112": "'use strict' 지시문을 모듈 출력에 내보내지 마세요.", + "Do_not_erase_const_enum_declarations_in_generated_code_6007": "생성된 코드에서 const 열거형 선언을 지우지 마세요.", + "Do_not_generate_custom_helper_functions_like_extends_in_compiled_output_6157": "컴파일된 출력에서 '__extends'와 같은 사용자 지정 도우미 함수를 생성하지 않습니다.", + "Do_not_include_the_default_library_file_lib_d_ts_6158": "기본 라이브러리 파일(lib.d.ts)을 포함하지 않습니다.", + "Do_not_report_errors_on_unreachable_code_6077": "접근할 수 없는 코드에 대한 오류를 보고하지 않습니다.", + "Do_not_report_errors_on_unused_labels_6074": "사용되지 않는 레이블에 대한 오류를 보고하지 않습니다.", + "Do_not_resolve_the_real_path_of_symlinks_6013": "symlink의 실제 경로를 확인하지 마세요.", + "Do_not_truncate_error_messages_6165": "오류 메시지를 자르지 않습니다.", + "Duplicate_declaration_0_2718": "'{0}' 선언이 중복되었습니다.", + "Duplicate_function_implementation_2393": "중복된 함수 구현입니다.", + "Duplicate_identifier_0_2300": "'{0}' 식별자가 중복되었습니다.", + "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_2441": "'{0}' 식별자가 중복되었습니다. 컴파일러는 모듈의 최상위 범위에 이름 '{1}'을(를) 예약합니다.", + "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_func_2529": "'{0}' 식별자가 중복되었습니다. 컴파일러는 비동기 함수를 포함하는 모듈의 최상위 범위에 '{1}' 이름을 예약합니다.", + "Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions_2520": "중복 식별자 '{0}'입니다. 컴파일러는 '{1}' 선언을 사용하여 비동기 함수를 지원합니다.", + "Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters_2396": "중복 식별자 'arguments'입니다. 컴파일러는 'arguments'를 사용해서 rest 매개 변수를 초기화합니다.", + "Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_me_2543": "'_newTarget' 식별자가 중복되었습니다. 컴파일러는 변수 선언 '_newTarget'을 사용하여 'new.target' 메타 속성 참조를 캡처합니다.", + "Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference_2401": "중복 식별자 '_super'입니다. 컴파일러는 '_super'를 사용해서 기본 클래스 참조를 캡처합니다.", + "Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference_2399": "중복 식별자 '_this'입니다. 컴파일러는 변수 선언 '_this'를 사용해서 'this' 참조를 캡처합니다.", + "Duplicate_label_0_1114": "중복된 레이블 '{0}'입니다.", + "Duplicate_number_index_signature_2375": "중복 숫자 인덱스 시그니처입니다.", + "Duplicate_string_index_signature_2374": "중복 문자열 인덱스 시그니처입니다.", + "Dynamic_import_cannot_have_type_arguments_1326": "동적 가져오기에는 형식 인수를 사용할 수 없습니다.", + "Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext_1323": "동적 가져오기는 '--module' 플래그가 'commonjs' 또는 'esNext'인 경우에만 지원됩니다.", + "Dynamic_import_must_have_one_specifier_as_an_argument_1324": "동적 가져오기에는 지정자 하나를 인수로 사용해야 합니다.", + "Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036": "동적 가져오기의 지정자는 'string' 형식이어야 하지만 여기에서 형식은 '{0}'입니다.", + "Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015": "인덱스 식이 'number' 형식이 아니므로 요소에 암시적으로 'any' 형식이 있습니다.", + "Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature_7017": "'{0}' 형식에 인덱스 시그니처가 없으므로 요소에 암시적으로 'any' 형식이 있습니다.", + "Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files_6164": "출력 파일의 시작에서 UTF-8 BOM(바이트 순서 표시)을 내보냅니다.", + "Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file_6151": "별도의 파일을 사용하는 대신 소스 맵과 함께 단일 파일을 내보냅니다.", + "Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap__6152": "단일 파일 내에서 소스 맵과 함께 소스를 내보냅니다. '--inlineSourceMap' 또는 '--sourceMap'을 설정해야 합니다.", + "Enable_all_strict_type_checking_options_6180": "엄격한 형식 검사 옵션을 모두 사용하도록 설정합니다.", + "Enable_project_compilation_6302": "프로젝트 컴파일을 사용하도록 설정", + "Enable_strict_checking_of_function_types_6186": "함수 형식에 대한 엄격한 검사를 사용하도록 설정합니다.", + "Enable_strict_checking_of_property_initialization_in_classes_6187": "클래스의 속성 초기화에 대해 엄격한 검사를 사용하도록 설정합니다.", + "Enable_strict_null_checks_6113": "엄격한 null 검사를 사용하도록 설정하세요.", + "Enable_tracing_of_the_name_resolution_process_6085": "이름 확인 프로세스 추적을 사용하도록 설정하세요.", + "Enable_verbose_logging_6366": "자세한 정보 로깅 사용", + "Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for__7037": "모든 가져오기에 대한 네임스페이스 개체를 만들어 CommonJS 및 ES 모듈 간의 내보내기 상호 운용성을 사용하도록 설정합니다. 'allowSyntheticDefaultImports'를 의미합니다.", + "Enables_experimental_support_for_ES7_async_functions_6068": "ES7 비동기 함수에 대해 실험적 지원을 사용합니다.", + "Enables_experimental_support_for_ES7_decorators_6065": "ES7 데코레이터에 대해 실험적 지원을 사용합니다.", + "Enables_experimental_support_for_emitting_type_metadata_for_decorators_6066": "데코레이터에 대한 형식 메타데이터를 내보내기 위해 실험적 지원을 사용합니다.", + "Enum_0_used_before_its_declaration_2450": "선언 전에 사용된 '{0}' 열거형입니다.", + "Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations_2567": "열거형 선언은 네임스페이스 또는 다른 열거형 선언과만 병합할 수 있습니다.", + "Enum_declarations_must_all_be_const_or_non_const_2473": "열거형 선언은 모두 const 또는 비const여야 합니다.", + "Enum_member_expected_1132": "열거형 멤버가 필요합니다.", + "Enum_member_must_have_initializer_1061": "열거형 멤버에는 이니셜라이저가 있어야 합니다.", + "Enum_name_cannot_be_0_2431": "열거형 이름은 '{0}'일 수 없습니다.", + "Enum_type_0_has_members_with_initializers_that_are_not_literals_2535": "열거형 형식 '{0}'에 리터럴이 아닌 이니셜라이저를 사용하는 멤버가 있습니다.", + "Examples_Colon_0_6026": "예: {0}", + "Excessive_stack_depth_comparing_types_0_and_1_2321": "'{0}' 및 '{1}' 형식을 비교하는 스택 깊이가 과도합니다.", + "Expected_0_1_type_arguments_provide_these_with_an_extends_tag_8027": "'@extends' 태그로 제공하는 예상되는 {0}-{1} 형식 인수입니다.", + "Expected_0_arguments_but_got_1_2554": "{0}개의 인수가 필요한데 {1}개를 가져왔습니다.", + "Expected_0_arguments_but_got_1_or_more_2556": "{0}개의 인수가 필요한데 {1}개 이상을 가져왔습니다.", + "Expected_0_type_arguments_but_got_1_2558": "{0}개의 형식 인수가 필요한데 {1}개를 가져왔습니다.", + "Expected_0_type_arguments_provide_these_with_an_extends_tag_8026": "'@extends' 태그로 제공하는 예상되는 {0} 형식 인수입니다.", + "Expected_at_least_0_arguments_but_got_1_2555": "최소 {0}개의 인수가 필요한데 {1}개를 가져왔습니다.", + "Expected_at_least_0_arguments_but_got_1_or_more_2557": "최소 {0}개의 인수가 필요한데 {1}개 이상을 가져왔습니다.", + "Expected_corresponding_JSX_closing_tag_for_0_17002": "'{0}'에 해당하는 JSX 닫는 태그가 필요합니다.", + "Expected_corresponding_closing_tag_for_JSX_fragment_17015": "JSX 조각에 닫는 태그가 필요합니다.", + "Expected_type_of_0_field_in_package_json_to_be_string_got_1_6105": "'package.json'의 '{0}' 필드에 'string' 형식이 필요한데 '{1}'을(를) 얻었습니다.", + "Experimental_Options_6177": "실험적 옵션", + "Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_t_1219": "데코레이터에 대한 실험적 지원 기능은 이후 릴리스에서 변경될 수 있습니다. 이 경고를 제거하려면 'experimentalDecorators' 옵션을 설정하세요.", + "Explicitly_specified_module_resolution_kind_Colon_0_6087": "명시적으로 지정된 모듈 확인 종류 '{0}'입니다.", + "Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or__1203": "ECMAScript 모듈을 대상으로 하는 경우 내보내기 할당을 사용할 수 없습니다. 대신 'export default'나 다른 모듈 형식의 사용을 고려하세요.", + "Export_assignment_is_not_supported_when_module_flag_is_system_1218": "'--module' 플래그가 'system'이면 내보내기 할당은 지원되지 않습니다.", + "Export_declaration_conflicts_with_exported_declaration_of_0_2484": "내보내기 선언이 '{0}'의 내보낸 선언과 충돌합니다.", + "Export_declarations_are_not_permitted_in_a_namespace_1194": "네임스페이스에서는 내보내기 선언이 허용되지 않습니다.", + "Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_2656": "내보낸 외부 패키지 입력 항목 파일 '{0}'은(는) 모듈이 아닙니다. 패키지 작성자에게 문의하여 패키지 정의를 업데이트하세요.", + "Exported_external_package_typings_file_cannot_contain_tripleslash_references_Please_contact_the_pack_2654": "내보낸 외부 패키지 입력 항목 파일에는 삼중 슬래시 참조가 포함될 수 없습니다. 패키지 작성자에게 문의하여 패키지 정의를 업데이트하세요.", + "Exported_type_alias_0_has_or_is_using_private_name_1_4081": "내보낸 형식 별칭 '{0}'은(는) '{1}' 전용 이름을 포함하거나 사용 중입니다.", + "Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4023": "내보낸 변수 '{0}'이(가) 외부 모듈 {2}의 '{1}' 이름을 가지고 있거나 사용 중이지만 명명할 수 없습니다.", + "Exported_variable_0_has_or_is_using_name_1_from_private_module_2_4024": "내보낸 변수 '{0}'이(가) 전용 모듈 '{2}'의 '{1}' 이름을 가지고 있거나 사용 중입니다.", + "Exported_variable_0_has_or_is_using_private_name_1_4025": "내보낸 변수 '{0}'이(가) 전용 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Exports_and_export_assignments_are_not_permitted_in_module_augmentations_2666": "내보내기 및 내보내기 할당는 모듈 확대에서 허용되지 않습니다.", + "Expression_expected_1109": "식이 필요합니다.", + "Expression_or_comma_expected_1137": "식 또는 쉼표가 필요합니다.", + "Expression_resolves_to_super_that_compiler_uses_to_capture_base_class_reference_2402": "컴파일러가 기본 클래스 참조를 캡처하기 위해 사용하는 '_super'로 식이 확인됩니다.", + "Expression_resolves_to_variable_declaration_0_that_compiler_uses_to_support_async_functions_2521": "컴파일러가 비동기 함수를 지원하기 위해 사용하는 변수 선언 '{0}'(으)로 식이 확인됩니다.", + "Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta__2544": "컴파일러가 'new.target' 메타 속성 참조를 캡처하기 위해 사용하는 변수 선언 '_newTarget'으로 식이 확인됩니다.", + "Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference_2400": "컴파일러가 'this' 참조를 캡처하기 위해 사용하는 변수 선언 '_this'로 식이 확인됩니다.", + "Extract_constant_95006": "상수 추출", + "Extract_function_95005": "함수 추출", + "Extract_to_0_in_1_95004": "{1}의 {0}(으)로 추출", + "Extract_to_0_in_1_scope_95008": "{1} 범위의 {0}(으)로 추출", + "Extract_to_0_in_enclosing_scope_95007": "바깥쪽 범위의 {0}(으)로 추출", + "FILE_6035": "파일", + "FILE_OR_DIRECTORY_6040": "파일 또는 디렉터리", + "Failed_to_parse_file_0_Colon_1_5014": "'{0}' 파일 구문 분석 실패: {1}.", + "Fallthrough_case_in_switch_7029": "switch에 Fallthrough case가 있습니다.", + "File_0_does_not_exist_6096": "'{0}' 파일이 없습니다.", + "File_0_exist_use_it_as_a_name_resolution_result_6097": "'{0}' 파일이 있습니다. 이 파일을 이름 확인 결과로 사용하세요.", + "File_0_has_an_unsupported_extension_so_skipping_it_6081": "'{0}' 파일은 확장명이 지원되지 않으므로 건너뜁니다.", + "File_0_has_unsupported_extension_The_only_supported_extensions_are_1_6054": "'{0}' 파일의 확장명이 지원되지 않습니다. 지원되는 확장명은 {1}뿐입니다.", + "File_0_is_not_a_module_2306": "'{0}' 파일은 모듈이 아닙니다.", + "File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern_6307": "'{0}' 파일이 프로젝트 파일 목록에 없습니다. 프로젝트는 모든 파일을 나열하거나 'include' 패턴을 사용해야 합니다.", + "File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files_6059": "'{0}' 파일이 'rootDir' '{1}' 아래에 있지 않습니다. 'rootDir'에는 모든 소스 파일이 포함되어 있어야 합니다.", + "File_0_not_found_6053": "파일 '{0}'을(를) 찾을 수 없습니다.", + "File_change_detected_Starting_incremental_compilation_6032": "파일 변경이 검색되었습니다. 증분 컴파일을 시작하는 중...", + "File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module_80001": "파일이 CommonJS 모듈입니다. ES6 모듈로 변환될 수 있습니다.", + "File_name_0_differs_from_already_included_file_name_1_only_in_casing_1149": "'{0}' 파일 이름은 이미 포함된 '{1}' 파일 이름과 대/소문자만 다릅니다.", + "File_name_0_has_a_1_extension_stripping_it_6132": "파일 이름 '{0}'에 '{1}' 확장명이 있어 제거하는 중입니다.", + "File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildca_5065": "파일 사양은 재귀 디렉터리 와일드카드('**') 뒤에 나타나는 부모 디렉터리('..')를 포함할 수 없습니다. '{0}'.", + "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010": "파일 사양은 재귀 디렉터리 와일드카드('**')로 끝날 수 없습니다. '{0}'.", + "Fix_all_detected_spelling_errors_95026": "검색된 맞춤법 오류 모두 수정", + "Found_0_errors_Watching_for_file_changes_6194": "{0}개 오류가 발견되었습니다. 파일이 변경되었는지 확인하는 중입니다.", + "Found_1_error_Watching_for_file_changes_6193": "1개 오류가 발견되었습니다. 파일이 변경되었는지 확인하는 중입니다.", + "Found_package_json_at_0_6099": "'{0}'에서 'package.json'을 찾았습니다.", + "Found_package_json_at_0_Package_ID_is_1_6190": "'{0}'에서 'package.json'을 찾았습니다. 패키지 ID는 '{1}'입니다.", + "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_1250": "'ES3' 또는 'ES5'를 대상으로 할 경우 strict 모드의 블록 내에서 함수 선언을 사용할 수 없습니다.", + "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_d_1251": "'ES3' 또는 'ES5'를 대상으로 할 경우 strict 모드의 블록 내에서 함수 선언을 사용할 수 없습니다. 클래스 정의는 자동으로 strict 모드가 됩니다.", + "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_1252": "'ES3' 또는 'ES5'를 대상으로 할 경우 strict 모드의 블록 내에서 함수 선언을 사용할 수 없습니다. 모듈은 자동으로 strict 모드가 됩니다.", + "Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type_7011": "반환 형식 주석이 없는 함수 식에는 암시적으로 '{0}' 반환 형식이 포함됩니다.", + "Function_implementation_is_missing_or_not_immediately_following_the_declaration_2391": "함수 구현이 없거나 선언 바로 다음에 나오지 않습니다.", + "Function_implementation_name_must_be_0_2389": "함수 구현 이름이 '{0}'이어야 합니다.", + "Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_ref_7024": "반환 형식 주석이 없고 반환 식 중 하나에서 직간접적으로 참조되므로 함수에는 암시적으로 반환 형식 'any'가 포함됩니다.", + "Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined_2366": "함수에 끝 return 문이 없으며 반환 형식에 'undefined'가 포함되지 않습니다.", + "Function_overload_must_be_static_2387": "함수 오버로드는 정적이어야 합니다.", + "Function_overload_must_not_be_static_2388": "함수 오버로드는 정적이 아니어야 합니다.", + "Generate_get_and_set_accessors_95046": "'get' 및 'set' 접근자 생성", + "Generates_a_sourcemap_for_each_corresponding_d_ts_file_6000": "해당하는 각 '.d.ts' 파일에 sourcemap을 생성합니다.", + "Generates_corresponding_d_ts_file_6002": "해당 '.d.ts' 파일을 생성합니다.", + "Generates_corresponding_map_file_6043": "해당 '.map' 파일을 생성합니다.", + "Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_typ_7025": "생성기는 값을 생성하지 않으므로 암시적으로 '{0}' 형식입니다. 반환 형식을 제공하세요.", + "Generators_are_not_allowed_in_an_ambient_context_1221": "생성기는 앰비언트 컨텍스트에서 사용할 수 없습니다.", + "Generators_are_only_available_when_targeting_ECMAScript_2015_or_higher_1220": "생성기는 ECMAScript 2015 이상을 대상으로 하는 경우에만 사용할 수 있습니다.", + "Generic_type_0_requires_1_type_argument_s_2314": "'{0}' 제네릭 형식에 {1} 형식 인수가 필요합니다.", + "Generic_type_0_requires_between_1_and_2_type_arguments_2707": "제네릭 형식 '{0}'에 {1} 및 {2} 사이의 형식 인수가 필요합니다.", + "Generic_type_instantiation_is_excessively_deep_and_possibly_infinite_2550": "제네릭 형식 인스턴스화는 깊이가 매우 깊으며 무한할 수도 있습니다.", + "Getter_and_setter_accessors_do_not_agree_in_visibility_2379": "Getter 및 Setter 접근자의 표시 유형이 다릅니다.", + "Global_module_exports_may_only_appear_at_top_level_1316": "전역 모듈 내보내기는 최상위 수준에만 나올 수 있습니다.", + "Global_module_exports_may_only_appear_in_declaration_files_1315": "전역 모듈 내보내기는 선언 파일에만 나올 수 있습니다.", + "Global_module_exports_may_only_appear_in_module_files_1314": "전역 모듈 내보내기는 모듈 파일에만 나올 수 있습니다.", + "Global_type_0_must_be_a_class_or_interface_type_2316": "전역 형식 '{0}'은 클래스 또는 인터페이스 형식이어야 합니다.", + "Global_type_0_must_have_1_type_parameter_s_2317": "전역 형식 '{0}'에는 {1} 형식 매개 변수를 사용해야 합니다.", + "Hexadecimal_digit_expected_1125": "16진수가 필요합니다.", + "Identifier_expected_0_is_a_reserved_word_in_strict_mode_1212": "식별자가 필요합니다. '{0}'은(는) strict 모드의 예약어입니다.", + "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_stric_1213": "식별자가 필요합니다. '{0}'은(는) strict 모드의 예약어입니다. 클래스 정의는 자동으로 strict 모드가 됩니다.", + "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode_1214": "식별자가 필요합니다. '{0}'은(는) strict 모드의 예약어입니다. 모듈은 자동으로 strict 모드가 됩니다.", + "Identifier_expected_1003": "식별자가 필요합니다.", + "Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules_1216": "식별자가 필요합니다. '__esModule'은 ECMAScript 모듈을 변환할 때 내보낸 표식으로 예약되어 있습니다.", + "Ignore_this_error_message_90019": "이 오류 메시지 무시", + "Implement_all_inherited_abstract_classes_95040": "상속된 추상 클래스 모두 구현", + "Implement_all_unimplemented_interfaces_95032": "구현되지 않은 인터페이스 모두 구현", + "Implement_inherited_abstract_class_90007": "상속된 추상 클래스 구현", + "Implement_interface_0_90006": "'{0}' 인터페이스 구현", + "Implements_clause_of_exported_class_0_has_or_is_using_private_name_1_4019": "내보낸 클래스 '{0}'의 Implements 절이 전용 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Import_0_from_module_1_90013": "\"{1}\" 모듈에서 '{0}' 가져오기", + "Import_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_import_Asterisk_as_1202": "ECMAScript 모듈을 대상으로 하는 경우 할당 가져오기를 사용할 수 없습니다. 대신 'import * as ns from \"mod\"', 'import {a} from \"mod\"', 'import d from \"mod\"' 또는 다른 모듈 형식 사용을 고려하세요.", + "Import_declaration_0_is_using_private_name_1_4000": "가져오기 선언 '{0}'이(가) 전용 이름 '{1}'을(를) 사용하고 있습니다.", + "Import_declaration_conflicts_with_local_declaration_of_0_2440": "가져오기 선언이 '{0}'의 로컬 선언과 충돌합니다.", + "Import_declarations_in_a_namespace_cannot_reference_a_module_1147": "네임스페이스의 가져오기 선언은 모듈을 참조할 수 없습니다.", + "Import_emit_helpers_from_tslib_6139": "'tslib'에서 내보내기 도우미를 가져오세요.", + "Import_may_be_converted_to_a_default_import_80003": "가져오기가 기본 가져오기로 변환될 수 있습니다.", + "Import_name_cannot_be_0_2438": "가져오기 이름은 '{0}'일 수 없습니다.", + "Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relati_2439": "앰비언트 모듈 선언의 가져오기 또는 내보내기 선언은 상대적 모듈 이름을 통해 모듈을 참조할 수 없습니다.", + "Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_mod_2667": "가져오기는 모듈 확대에서 허용되지 않습니다. 내보내기를 바깥쪽 외부 모듈로 이동하세요.", + "In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066": "앰비언트 열거형 선언에서 멤버 이니셜라이저는 상수 식이어야 합니다.", + "In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enu_2432": "다중 선언이 포함된 열거형에서는 하나의 선언만 첫 번째 열거형 요소에 대한 이니셜라이저를 생략할 수 있습니다.", + "In_const_enum_declarations_member_initializer_must_be_constant_expression_2474": "'const' 열거형 선언에서 멤버 이니셜라이저는 상수 식이어야 합니다.", + "Include_modules_imported_with_json_extension_6197": "'.json' 확장을 사용하여 가져온 모듈을 포함합니다.", + "Index_signature_in_type_0_only_permits_reading_2542": "'{0}' 형식의 인덱스 시그니처는 읽기만 허용됩니다.", + "Index_signature_is_missing_in_type_0_2329": "'{0}' 형식에 인덱스 시그니처가 없습니다.", + "Index_signatures_are_incompatible_2330": "인덱스 시그니처가 호환되지 않습니다.", + "Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local_2395": "병합된 선언 '{0}'의 개별 선언은 모두 내보내 졌거나 모두 로컬이어야 합니다.", + "Infer_all_types_from_usage_95023": "사용량에서 모든 형식 유추", + "Infer_parameter_types_from_usage_95012": "사용량에서 매개 변수 형식 유추", + "Infer_type_of_0_from_usage_95011": "사용량에서 '{0}'의 형식 유추", + "Initialize_property_0_in_the_constructor_90020": "생성자에서 속성 '{0}' 초기화", + "Initialize_static_property_0_90021": "정적 속성 '{0}' 초기화", + "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301": "인스턴스 멤버 변수 '{0}'의 이니셜라이저는 생성자에 선언된 식별자 '{1}'을(를) 참조할 수 없습니다.", + "Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it_2373": "매개 변수 '{0}'의 이니셜라이저는 그 다음에 선언된 식별자 '{1}'을(를) 참조할 수 없습니다.", + "Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value_2525": "이니셜라이저는 이 바인딩 요소에 대한 값을 제공하지 않으며 바인딩 요소에는 기본값이 없습니다.", + "Initializers_are_not_allowed_in_ambient_contexts_1039": "앰비언트 컨텍스트에서는 이니셜라이저가 허용되지 않습니다.", + "Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file_6070": "TypeScript 프로젝트를 초기화하고 tsconfig.json 파일을 만듭니다.", + "Insert_command_line_options_and_files_from_a_file_6030": "파일에서 명령줄 옵션 및 파일을 삽입합니다.", + "Install_0_95014": "'{0}' 설치", + "Install_all_missing_types_packages_95033": "누락된 형식 패키지 모두 설치", + "Interface_0_cannot_simultaneously_extend_types_1_and_2_2320": "'{0}' 인터페이스는 '{1}' 및 '{2}' 형식을 동시에 확장할 수 없습니다.", + "Interface_0_incorrectly_extends_interface_1_2430": "'{0}' 인터페이스가 '{1}' 인터페이스를 잘못 확장합니다.", + "Interface_declaration_cannot_have_implements_clause_1176": "인터페이스 선언에는 'implements' 절을 사용할 수 없습니다.", + "Interface_name_cannot_be_0_2427": "인터페이스 이름은 '{0}'일 수 없습니다.", + "Invalid_character_1127": "잘못된 문자입니다.", + "Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augm_2665": "확대의 모듈 이름이 잘못되었습니다. '{1}'에서 '{0}' 모듈이 형식화되지 않은 모듈로 확인되어 확대할 수 없습니다.", + "Invalid_module_name_in_augmentation_module_0_cannot_be_found_2664": "확대의 모듈 이름이 잘못되었습니다. '{0}' 모듈을 찾을 수 없습니다.", + "Invalid_reference_directive_syntax_1084": "'reference' 지시문 구문이 잘못되었습니다.", + "Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode_1210": "'{0}'을(를) 잘못 사용했습니다. 클래스 정의는 자동으로 strict 모드가 됩니다.", + "Invalid_use_of_0_Modules_are_automatically_in_strict_mode_1215": "'{0}'을(를) 잘못 사용했습니다. 모듈은 자동으로 strict 모드가 됩니다.", + "Invalid_use_of_0_in_strict_mode_1100": "strict 모드에서 '{0}'을(를) 잘못 사용했습니다.", + "Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name_5067": "'jsxFactory'에 대한 값이 잘못되었습니다. '{0}'이(가) 올바른 식별자 또는 정규화된 이름이 아닙니다.", + "Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier_5059": "'--reactNamespace'의 값이 잘못되었습니다. '{0}'은(는) 올바른 식별자가 아닙니다.", + "JSDoc_0_1_does_not_match_the_extends_2_clause_8023": "JSDoc '@{0} {1}'이(가) 'extends {2}' 절과 일치하지 않습니다.", + "JSDoc_0_is_not_attached_to_a_class_8022": "JSDoc '@{0}'이(가) 클래스에 연결되어 있지 않습니다.", + "JSDoc_may_only_appear_in_the_last_parameter_of_a_signature_8028": "JSDoc '...'은 시그니처의 마지막 매개 변수에만 나타날 수 있습니다.", + "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_8024": "JSDoc '@param' 태그의 이름이 '{0}'인데 해당 이름의 매개 변수가 없습니다.", + "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_h_8029": "JSDoc '@param' 태그에 '{0}' 이름이 있지만, 해당 이름의 매개 변수가 없습니다. 배열 형식이 있는 경우 '인수'를 일치시킵니다.", + "JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags_8021": "JSDoc '@typedef' 태그는 형식 주석을 포함하거나, '@property' 또는 '@member' 태그 앞에 와야 합니다.", + "JSDoc_types_can_only_be_used_inside_documentation_comments_8020": "JSDoc 유형은 문서 주석 내에서만 사용될 수 있습니다.", + "JSDoc_types_may_be_moved_to_TypeScript_types_80004": "JSDoc 형식이 TypeScript 형식으로 이동될 수 있습니다.", + "JSX_attribute_expected_17003": "JSX 특성이 필요합니다.", + "JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000": "JSX 특성에는 비어 있지 않은 '식'만 할당할 수 있습니다.", + "JSX_element_0_has_no_corresponding_closing_tag_17008": "JSX 요소 '{0}'에 닫는 태그가 없습니다.", + "JSX_element_attributes_type_0_may_not_be_a_union_type_2600": "JSX 요소 특성 형식 '{0}'은(는) 공용 구조체 형식일 수 없습니다.", + "JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property_2607": "JSX 요소 클래스는 '{0}' 속성이 없으므로 특성을 지원하지 않습니다.", + "JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists_7026": "'JSX.{0}' 인터페이스가 없으므로 JSX 요소는 암시적으로 'any' 형식입니다.", + "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602": "전역 형식 'JSX.Element'가 없으므로 JSX 요소는 암시적으로 'any' 형식입니다.", + "JSX_element_type_0_does_not_have_any_construct_or_call_signatures_2604": "JSX 요소 형식 '{0}'에 구문 또는 호출 시그니처가 없습니다.", + "JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements_2605": "JSX 요소 형식 '{0}'은(는) JSX 요소에 대한 생성자 함수가 아닙니다.", + "JSX_elements_cannot_have_multiple_attributes_with_the_same_name_17001": "JSX 요소에 이름이 같은 특성을 여러 개 사용할 수 없습니다.", + "JSX_expressions_must_have_one_parent_element_2657": "JSX 식에는 부모 요소가 하나 있어야 합니다.", + "JSX_fragment_has_no_corresponding_closing_tag_17014": "JSX 조각에 닫는 태그가 없습니다.", + "JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma_17017": "인라인 JSX 팩터리 pragma를 사용할 때에는 JSX 조각이 지원되지 않습니다.", + "JSX_fragment_is_not_supported_when_using_jsxFactory_17016": "JSX 조각은 --jsxFactory를 사용하는 경우 지원되지 않습니다.", + "JSX_spread_child_must_be_an_array_type_2609": "JSX 분배 자식은 배열 형식이어야 합니다.", + "Jump_target_cannot_cross_function_boundary_1107": "점프 대상은 함수 경계를 벗어날 수 없습니다.", + "KIND_6034": "KIND", + "LOCATION_6037": "위치", + "Language_service_is_disabled_9004": "언어 서비스를 사용할 수 없습니다.", + "Left_side_of_comma_operator_is_unused_and_has_no_side_effects_2695": "쉼표 연산자의 왼쪽은 사용되지 않으며 이로 인해 의도하지 않은 결과가 발생하지 않습니다.", + "Line_break_not_permitted_here_1142": "여기서는 줄 바꿈이 허용되지 않습니다.", + "Line_terminator_not_permitted_before_arrow_1200": "줄 마침 표시는 화살표 앞에 사용할 수 없습니다.", + "List_of_folders_to_include_type_definitions_from_6161": "포함할 형식 정의가 있는 폴더의 목록입니다.", + "List_of_language_service_plugins_6181": "언어 서비스 플러그 인의 목록입니다.", + "List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime_6168": "런타임에 프로젝트의 구조를 나타내는 결합된 콘텐츠가 있는 루트 폴더의 목록입니다.", + "Loading_0_from_the_root_dir_1_candidate_location_2_6109": "루트 디렉터리 '{1}'에서 '{0}'을(를) 로드하고 있습니다. 후보 위치: '{2}'.", + "Loading_module_0_from_node_modules_folder_target_file_type_1_6098": "'node_modules' 폴더에서 '{0}' 모듈을 로드하고 있습니다. 대상 파일 형식은 '{1}'입니다.", + "Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1_6095": "모듈을 파일/폴더로 로드하고 있습니다. 후보 모듈 위치는 '{0}', 대상 파일 형식은 '{1}'입니다.", + "Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1_6048": "로캘이 또는 - 형식이어야 합니다. 예를 들어 '{0}' 또는 '{1}'입니다.", + "Longest_matching_prefix_for_0_is_1_6108": "'{0}'에 대해 일치하는 가장 긴 접두사는 '{1}'입니다.", + "Looking_up_in_node_modules_folder_initial_location_0_6125": "'node_modules' 폴더에서 찾고 있습니다. 초기 위치: '{0}'.", + "Make_all_super_calls_the_first_statement_in_their_constructor_95036": "모든 'super()' 호출을 생성자의 첫 번째 문으로 만들기", + "Make_super_call_the_first_statement_in_the_constructor_90002": "생성자의 첫 번째 문을 'super()'로 호출", + "Mapped_object_type_implicitly_has_an_any_template_type_7039": "매핑된 개체 형식에는 'any' 템플릿 형식이 암시적으로 포함됩니다.", + "Member_0_implicitly_has_an_1_type_7008": "'{0}' 멤버에는 암시적으로 '{1}' 형식이 포함됩니다.", + "Merge_conflict_marker_encountered_1185": "병합 충돌 표식을 발견했습니다.", + "Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_d_2652": "병합된 선언 '{0}'에는 기본 내보내기 선언을 포함할 수 없습니다. 대신 별도의 'export default {0}' 선언을 추가하세요.", + "Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constru_17013": "메타 속성 '{0}'은(는) 함수 선언, 함수 식 또는 생성기의 본문에서만 사용할 수 있습니다.", + "Method_0_cannot_have_an_implementation_because_it_is_marked_abstract_1245": "'{0}' 메서드는 abstract로 표시되어 있으므로 구현이 있을 수 없습니다.", + "Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4101": "내보낸 인터페이스의 '{0}' 메서드가 전용 모듈 '{2}'의 '{1}' 이름을 가지고 있거나 사용 중입니다.", + "Method_0_of_exported_interface_has_or_is_using_private_name_1_4102": "내보낸 인터페이스의 '{0}' 메서드가 전용 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Modifiers_cannot_appear_here_1184": "한정자를 여기에 표시할 수 없습니다.", + "Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_1340": "모듈 '{0}'은(는) 형식을 참조하지 않지만, 여기에서 형식으로 사용됩니다.", + "Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here_1339": "모듈 '{0}'은(는) 값을 참조하지 않지만, 여기에서 값으로 사용됩니다.", + "Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambig_2308": "{0} 모듈에서 '{1}'(이)라는 멤버를 이미 내보냈습니다. 모호성을 해결하려면 명시적으로 다시 내보내는 것이 좋습니다.", + "Module_0_has_no_default_export_1192": "모듈 '{0}'에는 기본 내보내기가 없습니다.", + "Module_0_has_no_exported_member_1_2305": "'{0}' 모듈에 내보낸 멤버 '{1}'이(가) 없습니다.", + "Module_0_has_no_exported_member_1_Did_you_mean_2_2724": "모듈 '{0}'에 내보낸 멤버 '{1}'이(가) 없습니다. '{2}'이(가) 아닌지 확인하세요.", + "Module_0_is_hidden_by_a_local_declaration_with_the_same_name_2437": "'{0}' 모듈은 이름이 같은 로컬 선언으로 숨겨집니다.", + "Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct_2497": "모듈 '{0}'은(는) 모듈이 아닌 엔터티로 확인되므로 이 구문을 사용하여 가져올 수 없습니다.", + "Module_0_uses_export_and_cannot_be_used_with_export_Asterisk_2498": "모듈 '{0}'은(는) 'export ='을 사용하며 'export *'와 함께 사용할 수 없습니다.", + "Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified_6145": "이 파일은 수정되지 않았으므로 '{0}' 모듈은 '{1}'에서 선언된 앰비언트 모듈로 확인되었습니다.", + "Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1_6144": "'{0}' 모듈은 '{1}'에서 지역으로 선언된 앰비언트 모듈로 확인되었습니다.", + "Module_0_was_resolved_to_1_but_jsx_is_not_set_6142": "모듈 '{0}'이(가) '{1}'(으)로 확인되었지만 '--jsx'가 설정되지 않았습니다.", + "Module_Resolution_Options_6174": "모듈 확인 옵션", + "Module_name_0_matched_pattern_1_6092": "모듈 이름: '{0}', 일치하는 패턴: '{1}'", + "Module_name_0_was_not_resolved_6090": "======== 모듈 이름 '{0}'이(가) 확인되지 않았습니다. ========", + "Module_name_0_was_successfully_resolved_to_1_6089": "======== 모듈 이름 '{0}'이(가) '{1}'(으)로 확인되었습니다. ========", + "Module_resolution_kind_is_not_specified_using_0_6088": "모듈 확인 종류가 지정되지 않았습니다. '{0}'을(를) 사용합니다.", + "Module_resolution_using_rootDirs_has_failed_6111": "'rootDirs'를 사용한 모듈 확인에 실패했습니다.", + "Move_to_a_new_file_95049": "새 파일로 이동", + "Multiple_consecutive_numeric_separators_are_not_permitted_6189": "여러 개의 연속된 숫자 구분 기호는 허용되지 않습니다.", + "Multiple_constructor_implementations_are_not_allowed_2392": "여러 생성자 구현은 허용되지 않습니다.", + "NEWLINE_6061": "줄 바꿈", + "Named_property_0_of_types_1_and_2_are_not_identical_2319": "명명된 속성 '{0}'의 형식 '{1}' 및 '{2}'이(가) 동일하지 않습니다.", + "Namespace_0_has_no_exported_member_1_2694": "'{0}' 네임스페이스에 내보낸 멤버 '{1}'이(가) 없습니다.", + "No_base_constructor_has_the_specified_number_of_type_arguments_2508": "기본 생성자에 지정된 수의 형식 인수가 없습니다.", + "No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2_18003": "'{0}' 구성 파일에서 입력을 찾을 수 없습니다. 지정된 '포함' 경로는 '{1}'이고 '제외' 경로는 '{2}'이었습니다.", + "Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2_2515": "비추상 클래스 '{0}'은(는) '{2}' 클래스에서 상속된 추상 멤버 '{1}'을(를) 구현하지 않습니다.", + "Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1_2653": "비추상 클래스 식은 '{1}' 클래스에서 상속된 추상 멤버 '{0}'을(를) 구현하지 않습니다.", + "Not_all_code_paths_return_a_value_7030": "일부 코드 경로가 값을 반환하지 않습니다.", + "Numeric_index_type_0_is_not_assignable_to_string_index_type_1_2413": "숫자 인덱스 형식 '{0}'을(를) 문자열 인덱스 형식 '{1}'에 할당할 수 없습니다.", + "Numeric_separators_are_not_allowed_here_6188": "숫자 구분 기호는 여기에서 허용되지 않습니다.", + "Object_is_of_type_unknown_2571": "개체가 '알 수 없는' 형식입니다.", + "Object_is_possibly_null_2531": "개체가 'null'인 것 같습니다.", + "Object_is_possibly_null_or_undefined_2533": "개체가 'null' 또는 'undefined'인 것 같습니다.", + "Object_is_possibly_undefined_2532": "개체가 'undefined'인 것 같습니다.", + "Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1_2353": "개체 리터럴은 알려진 속성만 지정할 수 있으며 '{1}' 형식에 '{0}'이(가) 없습니다.", + "Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_writ_2561": "개체 리터럴은 알려진 속성만 지정할 수 있지만 '{1}' 형식에 '{0}'이(가) 없습니다. '{2}'을(를) 쓰려고 했습니까?", + "Object_literal_s_property_0_implicitly_has_an_1_type_7018": "개체 리터럴의 '{0}' 속성에는 암시적으로 '{1}' 형식이 포함됩니다.", + "Octal_digit_expected_1178": "8진수가 있어야 합니다.", + "Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0_8017": "8진수 리터럴 형식은 ES2015 구문을 사용해야 합니다. '{0}' 구문을 사용하세요.", + "Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0_8018": "8진수 리터럴은 열거형 멤버 이니셜라이저에서 사용할 수 없습니다. '{0}' 구문을 사용하세요.", + "Octal_literals_are_not_allowed_in_strict_mode_1121": "strict 모드에서는 8진수 리터럴이 허용되지 않습니다.", + "Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0_1085": "ECMAScript 5 이상을 대상으로 하는 경우 8진수 리터럴을 사용할 수 없습니다. '{0}' 구문을 사용하세요.", + "Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement_1091": "'for...in' 문에는 단일 변수 선언만 허용됩니다.", + "Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement_1188": "'for...of' 문에는 단일 변수 선언만 허용됩니다.", + "Only_a_void_function_can_be_called_with_the_new_keyword_2350": "void 함수만 'new' 키워드로 호출할 수 있습니다.", + "Only_ambient_modules_can_use_quoted_names_1035": "앰비언트 모듈만 따옴표가 붙은 이름을 사용할 수 있습니다.", + "Only_amd_and_system_modules_are_supported_alongside_0_6082": "'amd' 및 'system' 모듈만 --{0}과(와) 함께 사용할 수 있습니다.", + "Only_emit_d_ts_declaration_files_6014": "'.d.ts' 선언 파일만 내보냅니다.", + "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002": "선택적 형식 인수가 포함된 식별자/정규화된 이름만 현재 클래스 'extends' 절에서 지원됩니다.", + "Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword_2340": "기본 클래스의 공용 및 보호된 메서드만 'super' 키워드를 통해 액세스할 수 있습니다.", + "Operator_0_cannot_be_applied_to_types_1_and_2_2365": "'{0}' 연산자를 '{1}' 및 '{2}' 형식에 적용할 수 없습니다.", + "Option_0_can_only_be_specified_in_tsconfig_json_file_6064": "'{0}' 옵션은 'tsconfig.json' 파일에만 지정할 수 있습니다.", + "Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided_5051": "'{0}' 옵션은 '--inlineSourceMap' 옵션 또는 '--sourceMap' 옵션이 제공되는 경우에만 사용할 수 있습니다.", + "Option_0_cannot_be_specified_with_option_1_5053": "'{0}' 옵션은 '{1}' 옵션과 함께 지정할 수 없습니다.", + "Option_0_cannot_be_specified_without_specifying_option_1_5052": "'{1}' 옵션을 지정하지 않고 '{0}' 옵션을 지정할 수 없습니다.", + "Option_0_cannot_be_specified_without_specifying_option_1_or_option_2_5069": "'{1}' 또는 '{2}' 옵션을 지정하지 않고 '{0}' 옵션을 지정할 수 없습니다.", + "Option_0_should_have_array_of_strings_as_a_value_6103": "'{0}' 옵션은 문자열 배열 값을 사용해야 합니다.", + "Option_build_must_be_the_first_command_line_argument_6369": "'--build' 옵션은 첫 번째 명령줄 인수여야 합니다.", + "Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES_5047": "'isolatedModules' 옵션은 '--module' 옵션을 지정하거나 'target' 옵션이 'ES2015' 이상인 경우에만 사용할 수 있습니다.", + "Option_paths_cannot_be_used_without_specifying_baseUrl_option_5060": "'paths' 옵션은 '--baseUrl' 옵션을 지정하지 않고 사용할 수 없습니다.", + "Option_project_cannot_be_mixed_with_source_files_on_a_command_line_5042": "명령줄에서 'project' 옵션을 원본 파일과 혼합하여 사용할 수 없습니다.", + "Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070": "'node' 모듈 확인 전략 없이 '--resolveJsonModule' 옵션을 지정할 수 없습니다.", + "Options_0_and_1_cannot_be_combined_6370": "'{0}' 및 '{1}' 옵션은 조합할 수 없습니다.", + "Options_Colon_6027": "옵션:", + "Output_directory_for_generated_declaration_files_6166": "생성된 선언 파일의 출력 디렉터리입니다.", + "Output_file_0_from_project_1_does_not_exist_6309": "프로젝트 '{1}'의 출력 파일 '{0}'이(가) 존재하지 않습니다.", + "Output_file_0_has_not_been_built_from_source_file_1_6305": "출력 파일 '{0}'이(가) 소스 파일 '{1}'에서 빌드되지 않았습니다.", + "Overload_signature_is_not_compatible_with_function_implementation_2394": "오버로드 시그니처가 함수 구현과 호환되지 않습니다.", + "Overload_signatures_must_all_be_abstract_or_non_abstract_2512": "오버로드 시그니처는 모두 추상이거나 비추상이어야 합니다.", + "Overload_signatures_must_all_be_ambient_or_non_ambient_2384": "오버로드 시그니처는 모두 앰비언트이거나 앰비언트가 아니어야 합니다.", + "Overload_signatures_must_all_be_exported_or_non_exported_2383": "오버로드 시그니처는 모두 내보내거나 모두 내보내지 않아야 합니다.", + "Overload_signatures_must_all_be_optional_or_required_2386": "오버로드 시그니처는 모두 선택 사항이거나 필수 사항이어야 합니다.", + "Overload_signatures_must_all_be_public_private_or_protected_2385": "오버로드 시그니처는 모두 공용, 전용 또는 보호된 상태여야 합니다.", + "Parameter_0_cannot_be_referenced_in_its_initializer_2372": "매개 변수 '{0}'은(는) 해당 이니셜라이저에서 참조할 수 없습니다.", + "Parameter_0_implicitly_has_an_1_type_7006": "'{0}' 매개 변수에는 암시적으로 '{1}' 형식이 포함됩니다.", + "Parameter_0_is_not_in_the_same_position_as_parameter_1_1227": "'{0}' 매개 변수는 '{1}' 매개 변수와 같은 위치에 있지 않습니다.", + "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4066": "내보낸 인터페이스에 있는 호출 시그니처의 '{0}' 매개 변수가 전용 모듈 '{2}'의 '{1}' 이름을 가지고 있거나 사용 중입니다.", + "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4067": "내보낸 인터페이스에 있는 호출 시그니처의 '{0}' 매개 변수가 전용 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_can_4061": "내보낸 클래스에 있는 생성자의 '{0}' 매개 변수가 외부 모듈 {2}의 '{1}' 이름을 가지고 있거나 사용 중이지만 명명할 수 없습니다.", + "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2_4062": "내보낸 클래스에 있는 생성자의 '{0}' 매개 변수가 전용 모듈 '{2}'의 '{1}' 이름을 가지고 있거나 사용 중입니다.", + "Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1_4063": "내보낸 클래스에 있는 생성자의 '{0}' 매개 변수가 전용 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_mod_4064": "내보낸 인터페이스에 있는 생성자 시그니처의 '{0}' 매개 변수가 전용 모듈 '{2}'의 '{1}' 이름을 가지고 있거나 사용 중입니다.", + "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4065": "내보낸 인터페이스에 있는 생성자 시그니처의 '{0}' 매개 변수가 전용 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4076": "내보낸 함수의 '{0}' 매개 변수가 외부 모듈 {2}의 '{1}' 이름을 가지고 있거나 사용 중이지만 명명할 수 없습니다.", + "Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2_4077": "내보낸 함수의 '{0}' 매개 변수가 전용 모듈 '{2}'의 '{1}' 이름을 가지고 있거나 사용 중입니다.", + "Parameter_0_of_exported_function_has_or_is_using_private_name_1_4078": "내보낸 함수의 '{0}' 매개 변수가 전용 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4091": "내보낸 인터페이스에 있는 인덱스 시그니처의 '{0}' 매개 변수가 전용 모듈 '{2}'의 '{1}' 이름을 가지고 있거나 사용 중입니다.", + "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1_4092": "내보낸 인터페이스에 있는 인덱스 시그니처의 '{0}' 매개 변수가 전용 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4074": "내보낸 인터페이스에 있는 메서드의 '{0}' 매개 변수가 전용 모듈 '{2}'의 '{1}' 이름을 가지고 있거나 사용 중입니다.", + "Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4075": "내보낸 인터페이스에 있는 메서드의 '{0}' 매개 변수가 전용 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_c_4071": "내보낸 클래스에 있는 공용 메서드의 '{0}' 매개 변수가 외부 모듈 {2}의 '{1}' 이름을 가지고 있거나 사용 중이지만 명명할 수 없습니다.", + "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4072": "내보낸 클래스에 있는 공용 메서드의 '{0}' 매개 변수가 전용 모듈 '{2}'의 '{1}' 이름을 가지고 있거나 사용 중입니다.", + "Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4073": "내보낸 클래스에 있는 공용 메서드의 '{0}' 매개 변수가 전용 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module__4068": "내보낸 클래스에 있는 공용 정적 메서드의 '{0}' 매개 변수가 외부 모듈 {2}의 '{1}' 이름을 가지고 있거나 사용 중이지만 명명할 수 없습니다.", + "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4069": "내보낸 클래스에 있는 공용 정적 메서드의 '{0}' 매개 변수가 전용 모듈 '{2}'의 '{1}' 이름을 가지고 있거나 사용 중입니다.", + "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4070": "내보낸 클래스에 있는 공용 정적 메서드의 '{0}' 매개 변수가 전용 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Parameter_cannot_have_question_mark_and_initializer_1015": "매개 변수에 물음표와 이니셜라이저를 사용할 수 없습니다.", + "Parameter_declaration_expected_1138": "매개 변수 선언이 필요합니다.", + "Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2_4036": "내보낸 클래스에 있는 공용 setter '{0}'의 매개 변수 형식이 전용 모듈 '{2}'의 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_private_name_1_4037": "내보낸 클래스에 있는 공용 setter '{0}'의 매개 변수 형식이 전용 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_name_1_from_private_mod_4034": "내보낸 클래스에 있는 공용 정적 setter '{0}'의 매개 변수 형식이 전용 모듈 '{2}'의 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1_4035": "내보낸 클래스에 있는 공용 정적 setter '{0}'의 매개 변수 형식이 전용 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Parse_in_strict_mode_and_emit_use_strict_for_each_source_file_6141": "strict 모드에서 구문 분석하고 각 소스 파일에 대해 \"use strict\"를 내보냅니다.", + "Pattern_0_can_have_at_most_one_Asterisk_character_5061": "'{0}' 패턴에는 '*' 문자를 최대 하나만 사용할 수 있습니다.", + "Prefix_0_with_an_underscore_90025": "'{0}' 앞에 밑줄 추가", + "Prefix_all_unused_declarations_with_where_possible_95025": "가능한 경우 사용하지 않는 모든 선언에 '_'을 접두사로 추가", + "Print_names_of_files_part_of_the_compilation_6155": "컴파일의 일부인 파일의 이름을 인쇄합니다.", + "Print_names_of_generated_files_part_of_the_compilation_6154": "컴파일의 일부인 생성된 파일의 이름을 인쇄합니다.", + "Print_the_compiler_s_version_6019": "컴파일러 버전을 인쇄합니다.", + "Print_this_message_6017": "이 메시지를 출력합니다.", + "Project_0_can_t_be_built_because_its_dependency_1_has_errors_6363": "'{0}' 프로젝트는 '{1}' 종속성에 오류가 있기 때문에 빌드할 수 없습니다.", + "Project_0_is_out_of_date_because_its_dependency_1_is_out_of_date_6353": "'{1}' 종속성이 최신 상태가 아니기 때문에 '{0}' 프로젝트가 최신 상태가 아닙니다.", + "Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2_6350": "가장 오래된 출력 '{1}'이(가) 최신 입력 '{2}'보다 오래되었기 때문에 '{0}' 프로젝트가 최신 상태가 아닙니다.", + "Project_0_is_out_of_date_because_output_file_1_does_not_exist_6352": "'{1}' 출력 파일이 존재하지 않기 때문에 '{0}' 프로젝트가 최신 상태가 아닙니다.", + "Project_0_is_up_to_date_6361": "'{0}' 프로젝트가 최신 상태입니다.", + "Project_0_is_up_to_date_because_newest_input_1_is_older_than_oldest_output_2_6351": "최신 입력 '{1}'이(가) 가장 오래된 출력 '{2}'보다 오래되었기 때문에 '{0}' 프로젝트가 최신 상태입니다.", + "Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies_6354": "'{0}' 프로젝트는 종속성에 .d.ts 파일이 있는 최신 상태입니다.", + "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202": "프로젝트 참조는 순환 그래프를 형성할 수 없습니다. 순환이 발견되었습니다. {0}", + "Projects_in_this_build_Colon_0_6355": "이 빌드의 프로젝트: {0}", + "Projects_to_reference_6300": "참조할 프로젝트", + "Property_0_does_not_exist_on_const_enum_1_2479": "'const' 열거형 '{1}'에 '{0}' 속성이 없습니다.", + "Property_0_does_not_exist_on_type_1_2339": "'{1}' 형식에 '{0}' 속성이 없습니다.", + "Property_0_does_not_exist_on_type_1_Did_you_forget_to_use_await_2570": "속성 '{0}'이(가) '{1}' 형식에 없습니다. 'await' 사용을 잊으셨나요?", + "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551": "'{0}' 속성이 '{1}' 형식에 없습니다. '{2}'을(를) 사용하시겠습니까?", + "Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1_2546": "'{0}' 속성은 충돌하는 선언이 있고 '{1}' 형식에서 액세스할 수 없습니다.", + "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor_2564": "속성 '{0}'은(는) 이니셜라이저가 없고 생성자에 할당되어 있지 않습니다.", + "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033": "'{0}' 속성에는 해당 get 접근자에 반환 형식 주석이 없으므로 암시적으로 'any' 형식이 포함됩니다.", + "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032": "'{0}' 속성에는 해당 set 접근자에 매개 변수 형식 주석이 없으므로 암시적으로 'any' 형식이 포함됩니다.", + "Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2_2416": "'{1}' 형식의 '{0}' 속성을 기본 형식 '{2}'의 동일한 속성에 할당할 수 없습니다.", + "Property_0_in_type_1_is_not_assignable_to_type_2_2603": "'{1}' 형식의 '{0}' 속성을 '{2}' 형식에 할당할 수 없습니다.", + "Property_0_is_declared_but_its_value_is_never_read_6138": "속성 '{0}'이(가) 선언은 되었지만 해당 값이 읽히지는 않았습니다.", + "Property_0_is_incompatible_with_index_signature_2530": "'{0}' 속성이 인덱스 시그니처와 호환되지 않습니다.", + "Property_0_is_missing_in_type_1_2324": "'{0}' 속성이 '{1}' 형식에 없습니다.", + "Property_0_is_optional_in_type_1_but_required_in_type_2_2327": "'{0}' 속성은 '{1}' 형식에서 선택적이지만 '{2}' 형식에서는 필수입니다.", + "Property_0_is_private_and_only_accessible_within_class_1_2341": "'{0}' 속성은 private이며 '{1}' 클래스 내에서만 액세스할 수 있습니다.", + "Property_0_is_private_in_type_1_but_not_in_type_2_2325": "'{0}' 속성은 '{1}' 형식에서 private이지만 '{2}' 형식에서는 그렇지 않습니다.", + "Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1_2446": "'{0}' 속성은 보호된 속성이며 '{1}' 클래스의 인스턴스를 통해서만 액세스할 수 있습니다.", + "Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses_2445": "'{0}' 속성은 보호된 속성이며 '{1}' 클래스 및 해당 하위 클래스 내에서만 액세스할 수 있습니다.", + "Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2_2443": "'{0}' 속성은 보호된 속성이지만 '{1}' 형식은 '{2}'에서 파생된 클래스가 아닙니다.", + "Property_0_is_protected_in_type_1_but_public_in_type_2_2444": "'{0}' 속성은 '{1}' 형식에서는 보호된 속성이지만 '{2}' 형식에서는 공용입니다.", + "Property_0_is_used_before_being_assigned_2565": "'{0}' 속성이 할당되기 전에 사용되었습니다.", + "Property_0_of_JSX_spread_attribute_is_not_assignable_to_target_property_2606": "JSX 분배 특성의 '{0}' 속성을 대상 속성에 할당할 수 없습니다.", + "Property_0_of_exported_class_expression_may_not_be_private_or_protected_4094": "내보낸 클래스 식의 속성 '{0}'이(가) 비공개가 아니거나 보호되지 않을 수 있습니다.", + "Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4032": "내보낸 인터페이스의 '{0}' 속성이 전용 모듈 '{2}'의 '{1}' 이름을 가지고 있거나 사용 중입니다.", + "Property_0_of_exported_interface_has_or_is_using_private_name_1_4033": "내보낸 인터페이스의 '{0}' 속성이 전용 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2_2412": "'{1}' 형식의 '{0}' 속성을 숫자 인덱스 형식 '{2}'에 할당할 수 없습니다.", + "Property_0_of_type_1_is_not_assignable_to_string_index_type_2_2411": "'{1}' 형식의 '{0}' 속성을 문자열 인덱스 형식 '{2}'에 할당할 수 없습니다.", + "Property_assignment_expected_1136": "속성 할당이 필요합니다.", + "Property_destructuring_pattern_expected_1180": "속성 구조 파괴 패턴이 필요합니다.", + "Property_or_signature_expected_1131": "속성 또는 서명이 필요합니다.", + "Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_li_1328": "속성 값은 문자열 리터럴, 숫자 리터럴, 'true', 'false', 'null', 개체 리터럴 또는 배열 리터럴이어야 합니다.", + "Provide_full_support_for_iterables_in_for_of_spread_and_destructuring_when_targeting_ES5_or_ES3_6179": "'ES5' 또는 'ES3'을 대상으로 할 경우 'for-of', spread 및 소멸의 반복 가능한 개체를 완벽히 지원합니다.", + "Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4098": "내보낸 클래스의 공용 메서드 '{0}'이(가) 외부 모듈 {2}의 '{1}' 이름을 가지고 있거나 사용 중이지만 명명할 수 없습니다.", + "Public_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4099": "내보낸 클래스의 공용 메서드 '{0}'이(가) 전용 모듈 '{2}'의 '{1}' 이름을 가지고 있거나 사용 중입니다.", + "Public_method_0_of_exported_class_has_or_is_using_private_name_1_4100": "내보낸 클래스의 공용 메서드의 '{0}'이(가) 전용 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_name_4029": "내보낸 클래스의 공용 속성 '{0}'이(가) 외부 모듈 {2}의 '{1}' 이름을 가지고 있거나 사용 중이지만 명명할 수 없습니다.", + "Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4030": "내보낸 클래스의 공용 속성 '{0}'이(가) 전용 모듈 '{2}'의 '{1}' 이름을 가지고 있거나 사용 중입니다.", + "Public_property_0_of_exported_class_has_or_is_using_private_name_1_4031": "내보낸 클래스의 공용 속성 '{0}'이(가) 전용 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_4095": "내보낸 클래스의 공용 정적 메서드 '{0}'이(가) 외부 모듈 {2}의 '{1}' 이름을 가지고 있거나 사용 중이지만 명명할 수 없습니다.", + "Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4096": "내보낸 클래스에 있는 공용 정적 메서드 '{0}'이(가) 전용 모듈 '{2}'의 '{1}' 이름을 가지고 있거나 사용 중입니다.", + "Public_static_method_0_of_exported_class_has_or_is_using_private_name_1_4097": "내보낸 클래스의 공용 정적 메서드 '{0}'이(가) 전용 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot__4026": "내보낸 클래스에 있는 공용 정적 속성 '{0}'이(가) 외부 모듈 {2}의 '{1}' 이름을 가지고 있거나 사용 중이지만 명명할 수 없습니다.", + "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4027": "내보낸 클래스의 공용 정적 속성 '{0}'이(가) 전용 모듈 '{2}'의 '{1}' 이름을 가지고 있거나 사용 중입니다.", + "Public_static_property_0_of_exported_class_has_or_is_using_private_name_1_4028": "내보낸 클래스의 공용 정적 속성 '{0}'이(가) 전용 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Raise_error_on_expressions_and_declarations_with_an_implied_any_type_6052": "암시된 'any' 형식이 있는 식 및 선언에서 오류를 발생합니다.", + "Raise_error_on_this_expressions_with_an_implied_any_type_6115": "암시된 'any' 형식이 있는 'this' 식에서 오류를 발생합니다.", + "Redirect_output_structure_to_the_directory_6006": "출력 구조를 디렉터리로 리디렉션합니다.", + "Referenced_project_0_must_have_setting_composite_Colon_true_6306": "참조되는 프로젝트 '{0}'에는 \"composite\": true 설정이 있어야 합니다.", + "Remove_all_unreachable_code_95051": "접근할 수 없는 코드 모두 제거", + "Remove_all_unused_labels_95054": "사용되지 않는 레이블 모두 제거", + "Remove_braces_from_arrow_function_95060": "화살표 함수에서 중괄호 제거", + "Remove_declaration_for_Colon_0_90004": "'{0}'에 대한 선언 제거", + "Remove_destructuring_90009": "구조 파괴 제거", + "Remove_import_from_0_90005": "'{0}'에서 가져오기 제거", + "Remove_unreachable_code_95050": "접근할 수 없는 코드 제거", + "Remove_unused_label_95053": "사용되지 않는 레이블 제거", + "Remove_variable_statement_90010": "변수 문 제거", + "Replace_import_with_0_95015": "가져오기를 '{0}'(으)로 바꿉니다.", + "Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "함수의 일부 코드 경로가 값을 반환하지 않는 경우 오류를 보고합니다.", + "Report_errors_for_fallthrough_cases_in_switch_statement_6076": "switch 문의 fallthrough case에 대한 오류를 보고합니다.", + "Report_errors_in_js_files_8019": ".js 파일의 오류를 보고합니다.", + "Report_errors_on_unused_locals_6134": "사용되지 않은 로컬 항목에 대한 오류를 보고합니다.", + "Report_errors_on_unused_parameters_6135": "사용되지 않은 매개 변수에 대한 오류를 보고합니다.", + "Required_type_parameters_may_not_follow_optional_type_parameters_2706": "필수 형식 매개 변수는 선택적 형식 매개 변수 다음에 올 수 없습니다.", + "Resolution_for_module_0_was_found_in_cache_from_location_1_6147": "'{0}' 모듈에 대한 해결을 '{1}' 위치의 캐시에서 찾았습니다.", + "Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols_6195": "문자열 값 속성 이름에 대해서만 'keyof'를 확인합니다(숫자나 기호 아님).", + "Resolving_from_node_modules_folder_6118": "node_modules 폴더에서 확인하는 중...", + "Resolving_module_0_from_1_6086": "======== '{1}'에서 '{0}' 모듈을 확인하는 중입니다. ========", + "Resolving_module_name_0_relative_to_base_url_1_2_6094": "기본 URL '{1}' - '{2}'을(를) 기준으로 모듈 이름 '{0}'을(를) 확인하는 중입니다.", + "Resolving_real_path_for_0_result_1_6130": "'{0}'의 실제 경로를 확인하는 중입니다. 결과: '{1}'.", + "Resolving_type_reference_directive_0_containing_file_1_root_directory_2_6116": "======== 형식 참조 지시문 '{0}'을(를) 확인하는 중입니다. 포함 파일: '{1}', 루트 디렉터리: '{2}' ========", + "Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set_6123": "======== 형식 참조 지시문 '{0}'을(를) 확인하는 중입니다. 포함 파일: '{1}', 루트 디렉터리: 설정되지 않음 ========", + "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1_6127": "======== 형식 참조 지시문 '{0}'을(를) 확인하는 중입니다. 포함 파일: 설정되지 않음, 루트 디렉터리: '{1}' ========", + "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set_6128": "======== 형식 참조 지시문 '{0}'을(를) 확인하는 중입니다. 포함 파일: 설정되지 않음, 루트 디렉터리: 설정되지 않음 ========", + "Resolving_using_primary_search_paths_6117": "기본 검색 경로를 사용하여 확인하는 중...", + "Resolving_with_primary_search_path_0_6121": "기본 검색 경로 '{0}'을(를) 사용하여 확인하는 중입니다.", + "Rest_parameter_0_implicitly_has_an_any_type_7019": "Rest 매개 변수 '{0}'에는 암시적으로 'any[]' 형식이 포함됩니다.", + "Rest_types_may_only_be_created_from_object_types_2700": "rest 유형은 개체 형식에서만 만들 수 있습니다.", + "Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4046": "내보낸 인터페이스에 있는 호출 시그니처의 반환 형식이 전용 모듈 '{1}'의 '{0}' 이름을 가지고 있거나 사용 중입니다.", + "Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0_4047": "내보낸 인터페이스에 있는 호출 시그니처의 반환 형식이 전용 이름 '{0}'을(를) 가지고 있거나 사용 중입니다.", + "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_mod_4044": "내보낸 인터페이스에 있는 생성자 시그니처의 반환 형식이 전용 모듈 '{1}'의 '{0}' 이름을 가지고 있거나 사용 중입니다.", + "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0_4045": "내보낸 인터페이스에 있는 생성자 시그니처의 반환 형식이 전용 이름 '{0}'을(를) 가지고 있거나 사용 중입니다.", + "Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class_2409": "생성자 시그니처의 반환 형식을 클래스의 인스턴스 형식에 할당할 수 있어야 합니다.", + "Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named_4058": "내보낸 함수의 반환 형식이 외부 모듈 {1}의 '{0}' 이름을 가지고 있거나 사용 중이지만 명명할 수 없습니다.", + "Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1_4059": "내보낸 함수의 반환 형식이 전용 모듈 '{1}'의 '{0}' 이름을 가지고 있거나 사용 중입니다.", + "Return_type_of_exported_function_has_or_is_using_private_name_0_4060": "내보낸 함수의 반환 형식이 전용 이름 '{0}'을(를) 가지고 있거나 사용 중입니다.", + "Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4048": "내보낸 인터페이스에 있는 인덱스 시그니처의 반환 형식이 전용 모듈 '{1}'의 '{0}' 이름을 가지고 있거나 사용 중입니다.", + "Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0_4049": "내보낸 인터페이스에 있는 인덱스 시그니처의 반환 형식이 전용 이름 '{0}'을(를) 가지고 있거나 사용 중입니다.", + "Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4056": "내보낸 인터페이스에 있는 메서드의 반환 형식이 전용 모듈 '{1}'의 '{0}' 이름을 가지고 있거나 사용 중입니다.", + "Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0_4057": "내보낸 인터페이스에 있는 메서드의 반환 형식이 전용 이름 '{0}'을(를) 가지고 있거나 사용 중입니다.", + "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_4041": "내보낸 클래스에 있는 공용 getter '{0}'의 반환 형식이 외부 모듈 {2}의 이름 '{1}'을(를) 가지고 있거나 사용 중이지만 명명할 수 없습니다.", + "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2_4042": "내보낸 클래스에 있는 공용 getter '{0}'의 반환 형식이 전용 모듈 '{2}'의 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_private_name_1_4043": "내보낸 클래스에 있는 공용 getter '{0}'의 반환 형식이 전용 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_c_4053": "내보낸 클래스에 있는 공용 메서드의 반환 형식이 외부 모듈 {1}의 '{0}' 이름을 가지고 있거나 사용 중이지만 명명할 수 없습니다.", + "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4054": "내보낸 클래스에 있는 공용 메서드의 반환 형식이 전용 모듈 '{1}'의 '{0}' 이름을 가지고 있거나 사용 중입니다.", + "Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0_4055": "내보낸 클래스에 있는 공용 메서드의 반환 형식이 전용 이름 '{0}'을(를) 가지고 있거나 사용 중입니다.", + "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_external_modul_4038": "내보낸 클래스에 있는 공용 정적 getter '{0}'의 반환 형식이 외부 모듈 {2}의 이름 '{1}'을(를) 가지고 있거나 사용 중이지만 명명할 수 없습니다.", + "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_4039": "내보낸 클래스에 있는 공용 정적 getter '{0}'의 반환 형식이 전용 모듈 '{2}'의 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_private_name_1_4040": "내보낸 클래스에 있는 공용 정적 getter '{0}'의 반환 형식이 전용 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module__4050": "내보낸 클래스에 있는 공용 정적 메서드의 반환 형식이 외부 모듈 {1}의 '{0}' 이름을 가지고 있거나 사용 중이지만 명명할 수 없습니다.", + "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4051": "내보낸 클래스에 있는 공용 정적 메서드의 반환 형식이 전용 모듈 '{1}'의 '{0}' 이름을 가지고 있거나 사용 중입니다.", + "Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0_4052": "내보낸 클래스에 있는 공용 정적 메서드의 반환 형식이 전용 이름 '{0}'을(를) 가지고 있거나 사용 중입니다.", + "Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program_6184": "이전 프로그램에서 변경되지 않았으므로 '{0}'에서 발생하는 모듈 확인을 다시 사용합니다.", + "Reusing_resolution_of_module_0_to_file_1_from_old_program_6183": "'{0}' 모듈 확인을 이전 프로그램의 '{1}' 파일에 다시 사용합니다.", + "Rewrite_all_as_indexed_access_types_95034": "인덱싱된 액세스 형식으로 모두 다시 작성", + "Rewrite_as_the_indexed_access_type_0_90026": "인덱싱된 액세스 형식 '{0}'(으)로 다시 작성", + "Root_directory_cannot_be_determined_skipping_primary_search_paths_6122": "루트 디렉터리를 확인할 수 없어 기본 검색 경로를 건너뜁니다.", + "STRATEGY_6039": "전략", + "Scoped_package_detected_looking_in_0_6182": "범위가 지정된 패키지가 검색되었습니다. '{0}'에서 찾습니다.", + "Setters_cannot_return_a_value_2408": "Setter가 값을 반환할 수 없습니다.", + "Show_all_compiler_options_6169": "모든 컴파일러 옵션을 표시합니다.", + "Show_diagnostic_information_6149": "진단 정보를 표시합니다.", + "Show_verbose_diagnostic_information_6150": "자세한 진단 정보를 표시합니다.", + "Show_what_would_be_built_or_deleted_if_specified_with_clean_6367": "빌드될 항목 표시(또는 '--clean'으로 지정된 경우 삭제될 항목 표시)", + "Signature_0_must_be_a_type_predicate_1224": "'{0}' 시그니처는 형식 조건자여야 합니다.", + "Skip_type_checking_of_declaration_files_6012": "선언 파일 형식 검사를 건너뜁니다.", + "Skipping_build_of_project_0_because_its_dependency_1_has_errors_6362": "'{0}' 프로젝트의 빌드는 '{1}' 종속성에 오류가 있기 때문에 건너뜁니다.", + "Skipping_clean_because_not_all_projects_could_be_located_6371": "일부 프로젝트를 찾을 수 없으므로 정리를 건너뛰는 중입니다.", + "Source_Map_Options_6175": "소스 맵 옵션", + "Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature_2382": "특수화된 오버로드 시그니처는 특수화되지 않은 서명에 할당할 수 없습니다.", + "Specifier_of_dynamic_import_cannot_be_spread_element_1325": "동적 가져오기의 지정자는 스프레드 요소일 수 없습니다.", + "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_or_ESNEXT_6015": "ECMAScript 대상 버전을 'ES3'(기본값), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018' 또는 'ESNEXT'로 지정합니다.", + "Specify_JSX_code_generation_Colon_preserve_react_native_or_react_6080": "JSX 코드 생성 'preserve', 'react-native' 또는 'react'를 지정합니다.", + "Specify_library_files_to_be_included_in_the_compilation_6079": "컴파일에 포함할 라이브러리 파일을 지정합니다.", + "Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext_6016": "모듈 코드 생성을 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015' 또는 'ESNext'로 지정합니다.", + "Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6_6069": "모듈 확인 전략 지정: 'node'(Node.js) 또는 'classic'(TypeScript 1.6 이전).", + "Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h_6146": "'react' JSX 내보내기를 대상으로 하는 경우 사용할 JSX 팩터리 함수를 지정합니다(예: 'React.createElement' 또는 'h').", + "Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix_6060": "파일을 내보낼 때 사용할 줄 시퀀스의 끝 지정: 'CRLF'(dos) 또는 'LF'(unix).", + "Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations_6004": "소스 위치 대신 디버거가 TypeScript 파일을 찾아야 하는 위치를 지정하세요.", + "Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations_6003": "생성된 위치 대신 디버거가 맵 파일을 찾아야 하는 위치를 지정하세요.", + "Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir_6058": "입력 파일의 루트 디렉터리를 지정하세요. --outDir이 포함된 출력 디렉터리 구조를 제어하는 데 사용됩니다.", + "Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher_2472": "'new' 식에서 Spread 연산자는 ECMAScript 5 이상을 대상으로 하는 경우에만 사용할 수 있습니다.", + "Spread_types_may_only_be_created_from_object_types_2698": "spread 유형은 개체 형식에서만 만들 수 있습니다.", + "Starting_compilation_in_watch_mode_6031": "감시 모드에서 컴파일을 시작하는 중...", + "Statement_expected_1129": "문이 필요합니다.", + "Statements_are_not_allowed_in_ambient_contexts_1036": "앰비언트 컨텍스트에서는 문이 허용되지 않습니다.", + "Static_members_cannot_reference_class_type_parameters_2302": "정적 멤버는 클래스 형식 매개 변수를 참조할 수 없습니다.", + "Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1_2699": "정적 속성 '{0}'이(가) 생성자 함수 '{1}'의 기본 제공 속성 'Function.{0}'과(와) 충돌합니다.", + "Strict_Type_Checking_Options_6173": "엄격한 형식 검사 옵션", + "String_literal_expected_1141": "문자열 리터럴이 필요합니다.", + "String_literal_with_double_quotes_expected_1327": "큰따옴표로 묶은 문자열 리터럴이 필요합니다.", + "Stylize_errors_and_messages_using_color_and_context_experimental_6073": "색과 컨텍스트를 사용하여 오류 및 메시지를 스타일화합니다(실험적).", + "Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_t_2717": "후속 속성 선언에 같은 형식이 있어야 합니다. '{0}' 속성이 '{1}' 형식이어야 하는데 여기에는 '{2}' 형식이 있습니다.", + "Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_t_2403": "후속 변수 선언에 같은 형식이 있어야 합니다. '{0}' 변수가 '{1}' 형식이어야 하는데 여기에는 '{2}' 형식이 있습니다.", + "Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2_5064": "'{1}' 패턴에 대한 '{0}' 대체의 형식이 잘못되었습니다. 'string'이 필요한데 '{2}'을(를) 얻었습니다.", + "Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character_5062": "'{1}' 패턴의 '{0}' 대체에는 '*' 문자를 최대 하나만 사용할 수 있습니다.", + "Substitutions_for_pattern_0_should_be_an_array_5063": "'{0}' 패턴에 대한 대체는 배열이 되어야 합니다.", + "Substitutions_for_pattern_0_shouldn_t_be_an_empty_array_5066": "패턴 '{0}'에 대한 대체에는 배열이 비어 있지 않아야 합니다.", + "Successfully_created_a_tsconfig_json_file_6071": "tsconfig.json 파일을 만들었습니다.", + "Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors_2337": "생성자 밖이나 생성자 내부에 중첩된 함수에서는 Super 호출이 허용되지 않습니다.", + "Suppress_excess_property_checks_for_object_literals_6072": "개체 리터럴에 대한 초과 속성 검사를 생략합니다.", + "Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures_6055": "인덱스 시그니처가 없는 개체 인덱싱에 대한 noImplicitAny 오류를 표시하지 않습니다.", + "Symbol_reference_does_not_refer_to_the_global_Symbol_constructor_object_2470": "'기호' 참조에서 전역 기호 생성자 개체를 참조하지 않습니다.", + "Syntax_Colon_0_6023": "구문: {0}", + "The_0_operator_cannot_be_applied_to_type_symbol_2469": "'{0}' 연산자는 'symbol' 유형에 적용될 수 없습니다.", + "The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead_2447": "'{0}' 연산자는 부울 형식에 사용할 수 없습니다. 대신 '{1}'을(를) 사용하세요.", + "The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead_2696": "'Object' 형식은 할당할 수 있는 다른 형식이 거의 없습니다. 대신 'any' 형식을 사용할까요?", + "The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_stand_2496": "'arguments' 개체는 ES3 및 ES5의 화살표 함수에서 참조할 수 없습니다. 표준 함수 식을 사용해 보세요.", + "The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_usi_2522": "'arguments' 개체는 ES3 및 ES5의 비동기 함수 또는 메서드에서 참조할 수 없습니다. 표준 함수 또는 메서드를 사용해 보세요.", + "The_body_of_an_if_statement_cannot_be_the_empty_statement_1313": "'if' 문의 본문이 빈 문이면 안 됩니다.", + "The_character_set_of_the_input_files_6163": "입력 파일의 문자 집합입니다.", + "The_containing_function_or_module_body_is_too_large_for_control_flow_analysis_2563": "제어 흐름 분석에 대해 포함된 함수 또는 모듈 본문이 너무 큽니다.", + "The_current_host_does_not_support_the_0_option_5001": "현재 호스트가 '{0}' 옵션을 지원하지 않습니다.", + "The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context_2714": "내보내기 할당의 식은 앰비언트 컨텍스트의 식별자 또는 정규화된 이름이어야 합니다.", + "The_files_list_in_config_file_0_is_empty_18002": "'{0}' 구성 파일의 '파일' 목록이 비어 있습니다.", + "The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback_1060": "프라미스에서 'then' 메서드의 첫 번째 매개 변수는 콜백이어야 합니다.", + "The_global_type_JSX_0_may_not_have_more_than_one_property_2608": "전역 형식 'JSX.{0}'에 속성이 둘 이상 있을 수 없습니다.", + "The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_option_1343": "'import.meta' 메타 속성은 'target' 및 'module' 컴파일러 옵션에 'ESNext'를 사용해야만 허용됩니다.", + "The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary_2527": "'{0}'의 유추 형식이 액세스할 수 없는 '{1}' 형식을 참조합니다. 형식 주석이 필요합니다.", + "The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern_2491": "'for...in' 문의 왼쪽에는 구조 파괴 패턴을 사용할 수 없습니다.", + "The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation_2404": "'for...in' 문의 왼쪽에는 형식 주석을 사용할 수 없습니다.", + "The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access_2406": "'for...in' 문의 왼쪽은 변수 또는 속성 액세스여야 합니다.", + "The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any_2405": "'for...in' 문의 왼쪽은 'string' 또는 'any' 형식이어야 합니다.", + "The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation_2483": "'for...of' 문의 왼쪽에는 형식 주석을 사용할 수 없습니다.", + "The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access_2487": "'for...of' 문의 왼쪽은 변수 또는 속성 액세스여야 합니다.", + "The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type_2362": "산술 연산 왼쪽은 'any', 'number' 또는 열거형 형식이어야 합니다.", + "The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access_2364": "할당 식의 왼쪽은 변수 또는 속성 액세스여야 합니다.", + "The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol_2360": "'in' 식의 왼쪽은 'any', 'string', 'number' 또는 'symbol' 유형이어야 합니다.", + "The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_paramete_2358": "'instanceof' 식 왼쪽은 'any' 형식, 개체 형식 또는 형식 매개 변수여야 합니다.", + "The_locale_used_when_displaying_messages_to_the_user_e_g_en_us_6156": "사용자에게 메시지를 표시할 때 사용되는 로캘입니다(예: 'en-us').", + "The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files_6136": "node_modules에서 검색하고 JavaScript 파일을 로드할 최대 종속성 깊이입니다.", + "The_operand_of_a_delete_operator_cannot_be_a_read_only_property_2704": "delete 연산자의 피연산자는 읽기 전용 속성일 수 없습니다.", + "The_operand_of_a_delete_operator_must_be_a_property_reference_2703": "delete 연산자의 피연산자는 속성 참조여야 합니다.", + "The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access_2357": "증가 또는 감소 연산자의 피연산자는 변수 또는 속성 액세스여야 합니다.", + "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601": "JSX 요소 생성자의 반환 형식은 개체 형식을 반환해야 합니다.", + "The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any_1237": "매개 변수 데코레이터 함수의 반환 형식은 'void' 또는 'any'여야 합니다.", + "The_return_type_of_a_property_decorator_function_must_be_either_void_or_any_1236": "속성 데코레이터 함수의 반환 형식은 'void' 또는 'any'여야 합니다.", + "The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_t_1058": "비동기 함수의 반환 형식은 유효한 프라미스여야 하거나 호출 가능 'then' 멤버를 포함하지 않아야 합니다.", + "The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_1064": "비동기 함수 또는 메서드의 반환 형식은 전역 Promise 형식이어야 합니다.", + "The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_but_2407": "'for...in' 문 오른쪽은 'any' 형식, 개체 형식 또는 형식 매개 변수여야 하는데, 여기에 '{0}' 형식이 있습니다.", + "The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type_2363": "산술 연산 오른쪽은 'any', 'number' 또는 열거형 형식이어야 합니다.", + "The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter_2361": "'in' 식의 오른쪽은 'any' 형식, 개체 형식 또는 형식 매개 변수여야 합니다.", + "The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_F_2359": "'instanceof' 식 오른쪽은 'any' 형식이거나 'Function' 인터페이스 형식에 할당할 수 있는 형식이어야 합니다.", + "The_specified_path_does_not_exist_Colon_0_5058": "지정된 경로가 없습니다. '{0}'.", + "The_target_of_an_assignment_must_be_a_variable_or_a_property_access_2541": "할당의 대상은 변수 또는 속성 액세스여야 합니다.", + "The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access_2701": "개체 rest 할당의 대상은 변수 또는 속성 액세스여야 합니다.", + "The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1_2684": "'{0}' 형식의 'this' 컨텍스트를 메서드의 '{1}' 형식 'this'에 할당할 수 없습니다.", + "The_this_types_of_each_signature_are_incompatible_2685": "각 시그니처의 'this' 형식이 호환되지 않습니다.", + "The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_typ_2453": "형식 매개 변수 '{0}'의 형식 인수를 유추할 수 없습니다. 형식 인수를 명시적으로 지정하세요.", + "The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value__2547": "비동기 반복기의 'next()' 메서드에서 반환하는 형식은 'value' 속성이 있는 형식에 대한 프라미스여야 합니다.", + "The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property_2490": "반복기의 'next()' 메서드에 의해 반환되는 형식에는 'value' 속성이 있어야 합니다.", + "The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer_1189": "'for...in' 문의 변수 선언에 이니셜라이저가 포함될 수 없습니다.", + "The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer_1190": "'for...of' 문의 변수 선언에 이니셜라이저가 포함될 수 없습니다.", + "The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any_2410": "'with' 문은 지원되지 않습니다. 'with' 블록의 모든 기호가 'any' 형식이 됩니다.", + "This_constructor_function_may_be_converted_to_a_class_declaration_80002": "이 생성자 함수는 클래스 선언으로 변환될 수 있습니다.", + "This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found_2354": "이 구문에는 가져온 도우미가 필요하지만 '{0}' 모듈을 찾을 수 없습니다.", + "This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1_2343": "이 구문에는 가져온 도우미 '{1}'이(가) 필요하지만 '{0}' 모듈에 내보낸 멤버 '{1}'이(가) 없습니다.", + "Trailing_comma_not_allowed_1009": "후행 쉼표는 허용되지 않습니다.", + "Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule_6153": "각 파일을 별도 모듈로 변환 컴파일합니다('ts.transpileModule'과 유사).", + "Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_mod_7035": "`npm install @types/{0}`이(가) 있으면 이를 사용하거나 `declare module '{0}';`이 포함된 선언(.d.ts) 파일을 추가하세요.", + "Trying_other_entries_in_rootDirs_6110": "'rootDirs'의 다른 항목을 시도하는 중입니다.", + "Trying_substitution_0_candidate_module_location_Colon_1_6093": "'{0}' 대체를 시도하는 중입니다. 후보 모듈 위치: '{1}'.", + "Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2_2493": "길이가 '{1}'인 튜플 형식 '{0}'을(를) 길이가 '{2}'인 튜플에 할당할 수 없습니다.", + "Type_0_cannot_be_converted_to_type_1_2352": "'{0}' 형식을 '{1}' 형식으로 변환할 수 없습니다.", + "Type_0_cannot_be_used_as_an_index_type_2538": "'{0}' 형식을 인덱스 형식으로 사용할 수 없습니다.", + "Type_0_cannot_be_used_to_index_type_1_2536": "'{0}' 형식을 인덱스 형식 '{1}'에 사용할 수 없습니다.", + "Type_0_does_not_satisfy_the_constraint_1_2344": "'{0}' 형식이 '{1}' 제약 조건을 만족하지 않습니다.", + "Type_0_has_no_matching_index_signature_for_type_1_2537": "'{0}' 형식에 '{1}' 형식에 대한 일치하는 인덱스 시그니처가 없습니다.", + "Type_0_has_no_properties_in_common_with_type_1_2559": "'{0}' 유형에 '{1}' 유형과 공통적인 속성이 없습니다.", + "Type_0_has_no_property_1_2460": "'{0}' 형식에 '{1}' 속성이 없습니다.", + "Type_0_has_no_property_1_and_no_string_index_signature_2459": "'{0}' 형식에 '{1}' 속성과 문자열 인덱스 시그니처가 없습니다.", + "Type_0_is_not_a_constructor_function_type_2507": "'{0}' 형식은 생성자 함수 형식이 아닙니다.", + "Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Prom_1055": "'{0}' 형식은 Promise 호환 생성자 값을 참조하지 않으므로 ES5/ES3에서 유효한 비동기 함수 반환 형식이 아닙니다.", + "Type_0_is_not_an_array_type_2461": "'{0}' 형식은 배열 형식이 아닙니다.", + "Type_0_is_not_an_array_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators_2568": "'{0}' 형식이 배열 형식이 아닙니다. 컴파일러 옵션 '-downlevelIteration'을 사용하여 반복기의 반복을 허용하세요.", + "Type_0_is_not_an_array_type_or_a_string_type_2495": "'{0}' 형식은 배열 형식 또는 문자열 형식이 아닙니다.", + "Type_0_is_not_an_array_type_or_a_string_type_Use_compiler_option_downlevelIteration_to_allow_iterati_2569": "'{0}' 형식이 배열 형식 또는 문자열 형식이 아닙니다. 컴파일러 옵션 '-downlevelIteration'을 사용하여 반복기의 반복을 허용하세요.", + "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549": "'{0}' 형식은 배열 형식 또는 문자열 형식이 아니거나, 반복기를 반환하는 '[Symbol.iterator]()' 메서드가 없습니다.", + "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548": "'{0}' 형식은 배열 형식이 아니거나 반복기를 반환하는 '[Symbol.iterator]()' 메서드가 없습니다.", + "Type_0_is_not_assignable_to_type_1_2322": "'{0}' 형식은 '{1}' 형식에 할당할 수 없습니다.", + "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_2719": "'{0}' 형식을 '{1}' 형식에 할당할 수 없습니다. 이름이 같은 2개의 서로 다른 형식이 있지만 서로 관련은 없습니다.", + "Type_0_is_not_comparable_to_type_1_2678": "'{0}' 형식을 '{1}' 형식과 비교할 수 없습니다.", + "Type_0_is_not_generic_2315": "'{0}' 형식이 제네릭이 아닙니다.", + "Type_0_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator_2504": "'{0}' 형식에는 비동기 반복기를 반환하는 '[Symbol.asyncIterator]()' 메서드가 있어야 합니다.", + "Type_0_must_have_a_Symbol_iterator_method_that_returns_an_iterator_2488": "'{0}' 형식에는 반복기를 반환하는 '[Symbol.iterator]()' 메서드가 있어야 합니다.", + "Type_0_provides_no_match_for_the_signature_1_2658": "'{0}' 형식에서 '{1}' 시그니처에 대한 일치하는 항목을 제공하지 않습니다.", + "Type_0_recursively_references_itself_as_a_base_type_2310": "Type '{0}' 형식은 자기 자신을 기본 형식으로 재귀적으로 참조합니다.", + "Type_alias_0_circularly_references_itself_2456": "'{0}' 형식 별칭은 순환적으로 자신을 참조합니다.", + "Type_alias_name_cannot_be_0_2457": "형식 별칭 이름은 '{0}'일 수 없습니다.", + "Type_annotation_cannot_appear_on_a_constructor_declaration_1093": "형식 주석은 생성자 선언에 표시될 수 없습니다.", + "Type_argument_candidate_1_is_not_a_valid_type_argument_because_it_is_not_a_supertype_of_candidate_0_2455": "형식 인수 후보 '{1}'은(는) '{0}' 후보의 상위 형식이 아니므로 유효한 형식 인수가 아닙니다.", + "Type_argument_expected_1140": "형식 인수가 필요합니다.", + "Type_argument_list_cannot_be_empty_1099": "형식 인수 목록은 비워 둘 수 없습니다.", + "Type_arguments_cannot_be_used_here_1342": "형식 인수를 여기에 사용할 수 없습니다.", + "Type_declaration_files_to_be_included_in_compilation_6124": "컴파일에 포함할 선언 파일을 입력하세요.", + "Type_expected_1110": "형식이 필요합니다.", + "Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method_1062": "형식은 자체 'then' 메서드의 처리 콜백에서 직간접적으로 참조됩니다.", + "Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member_1320": "'await' 형식의 피연산자는 유효한 프라미스여야 하거나 호출 가능 'then' 멤버를 포함하지 않아야 합니다.", + "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322": "'yield*'의 반복되는 요소 형식의 피연산자는 유효한 프라미스여야 하거나 호출 가능 'then' 멤버를 포함하지 않아야 합니다.", + "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321": "비동기 생성기에 있는 'yield' 형식의 피연산자는 유효한 프라미스여야 하거나 호출 가능 'then' 멤버를 포함하지 않아야 합니다.", + "Type_parameter_0_has_a_circular_constraint_2313": "형식 매개 변수 '{0}'에 순환 제약 조건이 있습니다.", + "Type_parameter_0_has_a_circular_default_2716": "형식 매개 변수 '{0}'에 순환 기본값이 있습니다.", + "Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4008": "내보낸 인터페이스에 있는 호출 시그니처의 형식 매개 변수 '{0}'이(가) 전용 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4006": "내보낸 인터페이스에 있는 생성자 시그니처의 형식 매개 변수 '{0}'이(가) 전용 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002": "내보낸 클래스의 형식 매개 변수 '{0}'이(가) 전용 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Type_parameter_0_of_exported_function_has_or_is_using_private_name_1_4016": "내보낸 함수의 형식 매개 변수 '{0}'이(가) 전용 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004": "내보낸 인터페이스의 형식 매개 변수 '{0}'이(가) 전용 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1_4083": "내보낸 형식 별칭의 형식 매개 변수 '{0}'이(가) 전용 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4014": "내보낸 인터페이스에 있는 메서드의 형식 매개 변수 '{0}'이(가) 전용 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4012": "내보낸 클래스에 있는 공용 메서드의 형식 매개 변수 '{0}'이(가) 전용 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4010": "내보낸 클래스에 있는 공용 정적 메서드의 형식 매개 변수 '{0}'이(가) 전용 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Type_parameter_declaration_expected_1139": "형식 매개 변수 선언이 필요합니다.", + "Type_parameter_list_cannot_be_empty_1098": "형식 매개 변수 목록은 비워 둘 수 없습니다.", + "Type_parameter_name_cannot_be_0_2368": "형식 매개 변수 이름은 '{0}'일 수 없습니다.", + "Type_parameters_cannot_appear_on_a_constructor_declaration_1092": "형식 매개 변수는 생성자 선언에 표시될 수 없습니다.", + "Type_predicate_0_is_not_assignable_to_1_1226": "형식 조건자 '{0}'을(를) '{1}'에 할당할 수 없습니다.", + "Type_reference_directive_0_was_not_resolved_6120": "======== 형식 참조 지시문 '{0}'이(가) 확인되지 않았습니다. ========", + "Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2_6119": "======== 형식 참조 지시문 '{0}'이(가) '{1}'(으)로 확인되었습니다. 주: {2}. ========", + "Types_have_separate_declarations_of_a_private_property_0_2442": "형식에 별도의 전용 속성 '{0}' 선언이 있습니다.", + "Types_of_parameters_0_and_1_are_incompatible_2328": "'{0}' 및 '{1}' 매개 변수의 형식이 호환되지 않습니다.", + "Types_of_property_0_are_incompatible_2326": "'{0}' 속성의 형식이 호환되지 않습니다.", + "Unable_to_open_file_0_6050": "'{0}' 파일을 열 수 없습니다.", + "Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression_1238": "식으로 호출된 경우 클래스 데코레이터의 서명을 확인할 수 없습니다.", + "Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression_1241": "식으로 호출된 경우 메서드 데코레이터의 서명을 확인할 수 없습니다.", + "Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression_1239": "식으로 호출된 경우 매개 변수 데코레이터의 서명을 확인할 수 없습니다.", + "Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression_1240": "식으로 호출된 경우 속성 데코레이터의 서명을 확인할 수 없습니다.", + "Unexpected_end_of_text_1126": "예기치 않은 텍스트 끝입니다.", + "Unexpected_token_1012": "예기치 않은 토큰입니다.", + "Unexpected_token_A_constructor_method_accessor_or_property_was_expected_1068": "예기치 않은 토큰입니다. 생성자, 메서드, 접근자 또는 속성이 필요합니다.", + "Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces_1069": "예기치 않은 토큰입니다. 중괄호가 없는 형식 매개 변수 이름이 필요합니다.", + "Unexpected_token_expected_1179": "예기치 않은 토큰입니다. '{'가 있어야 합니다.", + "Unknown_compiler_option_0_5023": "알 수 없는 컴파일러 옵션 '{0}'입니다.", + "Unknown_option_excludes_Did_you_mean_exclude_6114": "알 수 없는 옵션 'excludes'입니다. 'exclude'를 사용하시겠습니까?", + "Unknown_type_acquisition_option_0_17010": "알 수 없는 형식 인식 옵션 '{0}'입니다.", + "Unreachable_code_detected_7027": "접근할 수 없는 코드가 있습니다.", + "Unsupported_locale_0_6049": "지원되지 않는 로캘 '{0}'입니다.", + "Unterminated_Unicode_escape_sequence_1199": "종결되지 않은 유니코드 이스케이프 시퀀스입니다.", + "Unterminated_quoted_string_in_response_file_0_6045": "응답 파일 '{0}'의 종결되지 않은 따옴표 붙은 문자열입니다.", + "Unterminated_regular_expression_literal_1161": "종결되지 않은 정규식 리터럴입니다.", + "Unterminated_string_literal_1002": "종결되지 않은 문자열 리터럴입니다.", + "Unterminated_template_literal_1160": "종결되지 않은 템플릿 리터럴입니다.", + "Untyped_function_calls_may_not_accept_type_arguments_2347": "형식화되지 않은 함수 호출에는 형식 인수를 사용할 수 없습니다.", + "Unused_label_7028": "사용되지 않는 레이블입니다.", + "Updating_output_timestamps_of_project_0_6359": "'{0}' 프로젝트의 출력 타임스탬프를 업데이트하는 중...", + "Use_synthetic_default_member_95016": "가상 '기본' 멤버를 사용합니다.", + "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494": "ECMAScript 5 이상에서만 'for...of' 문에서 문자열을 사용할 수 있습니다.", + "VERSION_6036": "버전", + "Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it_2560": "'{0}' 형식의 값에 '{1}' 형식과 공통된 속성이 없습니다. 속성을 호출하려고 했습니까?", + "Value_of_type_0_is_not_callable_Did_you_mean_to_include_new_2348": "'{0}' 형식의 값은 호출할 수 없습니다. 'new'를 포함하려고 했습니까?", + "Variable_0_implicitly_has_an_1_type_7005": "'{0}' 변수에는 암시적으로 '{1}' 형식이 포함됩니다.", + "Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined_7034": "'{0}' 변수는 형식을 확인할 수 없는 경우 일부 위치에서 암시적으로 '{1}' 형식입니다.", + "Variable_0_is_used_before_being_assigned_2454": "'{0}' 변수가 할당되기 전에 사용되었습니다.", + "Variable_declaration_expected_1134": "변수 선언이 필요합니다.", + "Variable_declaration_list_cannot_be_empty_1123": "변수 선언 목록은 비워 둘 수 없습니다.", + "Version_0_6029": "버전 {0}", + "Watch_input_files_6005": "조사식 입력 파일입니다.", + "Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen_6191": "화면을 지우지 않고, 감시 모드의 오래된 콘솔 출력을 유지할지 여부입니다.", + "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001": "표준 TypeScript 라이브러리에 정의된 요소의 이름을 바꿀 수 없습니다.", + "You_cannot_rename_this_element_8000": "이 요소의 이름을 바꿀 수 없습니다.", + "_0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write__1329": "'{0}'이(가) 여기에서 decorator로 사용할 인수를 너무 적게 허용합니다. 먼저 이를 호출하고 '@{0}()'을(를) 작성하시겠습니까?", + "_0_are_specified_twice_The_attribute_named_0_will_be_overwritten_2710": "'{0}'이(가) 두 번 지정되었습니다. 이름이 '{0}'인 특성을 덮어씁니다.", + "_0_can_only_be_used_in_a_ts_file_8009": "'{0}'은(는) .ts 파일에서만 사용할 수 있습니다.", + "_0_expected_1005": "'{0}'이(가) 필요합니다.", + "_0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_reference_7023": "반환 형식 주석이 없고 반환 식 중 하나에서 직간접적으로 참조되므로 '{0}'에는 암시적으로 'any' 반환 형식이 포함됩니다.", + "_0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or__7022": "'{0}'은(는) 형식 주석이 없고 자체 이니셜라이저에서 직간접적으로 참조되므로 암시적으로 'any' 형식입니다.", + "_0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible_2692": "{0}'은(는) 기본 개체이지만 '{1}'은(는) 래퍼 개체입니다. 가능한 경우 '{0}'을(를) 사용하세요.", + "_0_is_declared_but_its_value_is_never_read_6133": "'{0}'이(가) 선언은 되었지만 해당 값이 읽히지는 않았습니다.", + "_0_is_declared_but_never_used_6196": "'{0}'이(가) 선언되었지만 사용되지 않았습니다.", + "_0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2_17012": "'{0}'은(는) '{1}' 키워드에 대한 올바른 메타 속성이 아닙니다. '{2}'을(를) 사용하시겠습니까?", + "_0_is_referenced_directly_or_indirectly_in_its_own_base_expression_2506": "'{0}'은(는) 자체 기본 식에서 직간접적으로 참조됩니다.", + "_0_is_referenced_directly_or_indirectly_in_its_own_type_annotation_2502": "'{0}'은(는) 자체 형식 주석에서 직간접적으로 참조됩니다.", + "_0_list_cannot_be_empty_1097": "'{0}' 목록은 비워 둘 수 없습니다.", + "_0_modifier_already_seen_1030": "'{0}' 한정자가 이미 있습니다.", + "_0_modifier_cannot_appear_on_a_class_element_1031": "'{0}' 한정자는 클래스 요소에 나타날 수 없습니다.", + "_0_modifier_cannot_appear_on_a_constructor_declaration_1089": "'{0}' 한정자는 생성자 선언에 나타날 수 없습니다.", + "_0_modifier_cannot_appear_on_a_data_property_1043": "'{0}' 한정자는 데이터 속성에 나타날 수 없습니다.", + "_0_modifier_cannot_appear_on_a_module_or_namespace_element_1044": "'{0}' 한정자는 모듈 또는 네임스페이스 요소에 나타날 수 없습니다.", + "_0_modifier_cannot_appear_on_a_parameter_1090": "{0}' 한정자는 매개 변수에 표시될 수 없습니다.", + "_0_modifier_cannot_appear_on_a_type_member_1070": "'{0}' 한정자는 형식 멤버에 나타날 수 없습니다.", + "_0_modifier_cannot_appear_on_an_index_signature_1071": "'{0}' 한정자는 인덱스 시니그처에 나타날 수 없습니다.", + "_0_modifier_cannot_be_used_here_1042": "'{0}' 한정자는 여기에 사용할 수 없습니다.", + "_0_modifier_cannot_be_used_in_an_ambient_context_1040": "'{0}' 한정자는 앰비언트 컨텍스트에서 사용할 수 없습니다.", + "_0_modifier_cannot_be_used_with_1_modifier_1243": "'{0}' 한정자는 '{1}' 한정자와 함께 사용할 수 없습니다.", + "_0_modifier_cannot_be_used_with_a_class_declaration_1041": "'{0}' 한정자는 클래스 선언에서 사용할 수 없습니다.", + "_0_modifier_must_precede_1_modifier_1029": "'{0}' 한정자는 '{1}' 한정자 앞에 와야 합니다.", + "_0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here_2702": "'{0}'은(는) 형식만 참조하지만, 여기서는 네임스페이스로 사용되고 있습니다.", + "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_2693": "'{0}'은(는) 형식만 참조하지만, 여기서는 값으로 사용되고 있습니다.", + "_0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead_2686": "'{0}'은(는) UMD 전역을 참조하지만 현재 파일은 모듈입니다. 대신 가져오기를 추가해 보세요.", + "_0_tag_already_specified_1223": "'{0}' 태그가 이미 지정되었습니다.", + "_0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag_1253": "'{0}' 태그를 개별적으로 최상위 JSDoc 태그로 사용할 수 없습니다.", + "_0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type_7010": "반환 형식 주석이 없는 '{0}'에는 암시적으로 '{1}' 반환 형식이 포함됩니다.", + "abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration_1242": "'abstract' 한정자는 클래스, 메서드 또는 속성 선언에만 나타날 수 있습니다.", + "await_expression_is_only_allowed_within_an_async_function_1308": "'await' 식은 비동기 함수 내에서만 사용할 수 있습니다.", + "await_expressions_cannot_be_used_in_a_parameter_initializer_2524": "'await' 식은 매개 변수 이니셜라이저에서 사용할 수 없습니다.", + "baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1_6106": "'baseUrl' 옵션이 '{0}'(으)로 설정되어 있습니다. 상대적이지 않은 모듈 이름 '{1}'을(를) 확인하려면 이 값을 사용합니다.", + "can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment_1312": "'='는 구조 파괴 할당 내의 개체 리터럴 속성에서만 사용할 수 있습니다.", + "case_or_default_expected_1130": "'case' 또는 'default'가 필요합니다.", + "class_expressions_are_not_currently_supported_9003": "'class' 식은 현재 지원되지 않습니다.", + "const_declarations_can_only_be_declared_inside_a_block_1156": "'const' 선언은 블록 내부에서만 선언할 수 있습니다.", + "const_declarations_must_be_initialized_1155": "'const' 선언은 초기화해야 합니다.", + "const_enum_member_initializer_was_evaluated_to_a_non_finite_value_2477": "'const' 열거형 멤버 이니셜라이저가 무한 값에 대해 평가되었습니다.", + "const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN_2478": "'const' 열거형 멤버 이니셜라이저가 허용되지 않은 'NaN' 값에 대해 평가되었습니다.", + "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475": "'const' 열거형은 속성이나 인덱스 액세스 식, 또는 내보내기 할당이나 가져오기 선언의 오른쪽, 또는 형식 쿼리에서만 사용할 수 있습니다.", + "delete_cannot_be_called_on_an_identifier_in_strict_mode_1102": "strict 모드에서는 식별자에 대해 'delete'를 호출할 수 없습니다.", + "delete_this_Project_0_is_up_to_date_because_it_was_previously_built_6360": "이 항목 삭제 - '{0}' 프로젝트는 이전에 빌드되었기 때문에 최신 상태입니다.", + "enum_declarations_can_only_be_used_in_a_ts_file_8015": "'enum 선언'은 .ts 파일에서만 사용할 수 있습니다.", + "export_can_only_be_used_in_a_ts_file_8003": "'export='는 .ts 파일에서만 사용할 수 있습니다.", + "export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always__2668": "앰비언트 모듈 및 모듈 확대는 항상 표시되므로 'export' 한정자를 적용할 수 없습니다.", + "extends_clause_already_seen_1172": "'extends' 절이 이미 있습니다.", + "extends_clause_must_precede_implements_clause_1173": "'extends' 절은 'implements' 절 앞에 와야 합니다.", + "extends_clause_of_exported_class_0_has_or_is_using_private_name_1_4020": "내보낸 클래스 '{0}'의 Extends 절이 전용 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "extends_clause_of_exported_interface_0_has_or_is_using_private_name_1_4022": "내보낸 인터페이스 '{0}'의 Extends 절이 전용 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "file_6025": "파일", + "get_and_set_accessor_must_have_the_same_this_type_2682": "'get' 및 'set' 접근자는 동일한 'this' 형식이어야 합니다.", + "get_and_set_accessor_must_have_the_same_type_2380": "'get' 및 'set' 접근자의 형식이 같아야 합니다.", + "implements_clause_already_seen_1175": "'implements' 절이 이미 있습니다.", + "implements_clauses_can_only_be_used_in_a_ts_file_8005": "'implements clauses'는 .ts 파일에서만 사용할 수 있습니다.", + "import_can_only_be_used_in_a_ts_file_8002": "'import ... ='는 .ts 파일에서만 사용할 수 있습니다.", + "infer_declarations_are_only_permitted_in_the_extends_clause_of_a_conditional_type_1338": "'infer' 선언은 조건 형식의 'extends' 절에서만 사용할 수 있습니다.", + "interface_declarations_can_only_be_used_in_a_ts_file_8006": "'interface declarations'는 .ts 파일에서만 사용할 수 있습니다.", + "let_declarations_can_only_be_declared_inside_a_block_1157": "'let' 선언은 블록 내부에서만 선언될 수 있습니다.", + "let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations_2480": "'let'은 'let' 또는 'const' 선언에서 이름으로 사용할 수 없습니다.", + "module_declarations_can_only_be_used_in_a_ts_file_8007": "'module declarations'는 .ts 파일에서만 사용할 수 있습니다.", + "new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead_1150": "배열을 만드는 데 'new T[]'를 사용할 수 없습니다. 대신 'new Array()'를 사용하세요.", + "new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type_7009": "대상에 구문 시그니처가 없는 'new' 식에는 암시적으로 'any' 형식이 포함됩니다.", + "non_null_assertions_can_only_be_used_in_a_ts_file_8013": "'non-null assertions'는 .ts 파일에서만 사용할 수 있습니다.", + "options_6024": "옵션", + "or_expected_1144": "'{' 또는 ';'이(가) 필요합니다.", + "package_json_does_not_have_a_0_field_6100": "'package.json'에는 '{0}' 필드가 없습니다.", + "package_json_has_0_field_1_that_references_2_6101": "'package.json'에 '{2}'을(를) 참조하는 '{0}' 필드 '{1}'이(가) 있습니다.", + "parameter_modifiers_can_only_be_used_in_a_ts_file_8012": "'parameter modifiers'는 .ts 파일에서만 사용할 수 있습니다.", + "paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0_6091": "'paths' 옵션이 지정되었습니다. 모듈 이름 '{0}'과(와) 일치하는 패턴을 찾는 중입니다.", + "readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024": "'readonly' 한정자는 속성 선언 또는 인덱스 시그니처에만 나타날 수 있습니다.", + "require_call_may_be_converted_to_an_import_80005": "'require' 호출이 가져오기로 변환될 수 있습니다.", + "rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107": "'rootDirs' 옵션이 설정되어 있습니다. 상대 모듈 이름 '{0}'을(를) 확인하려면 이 옵션을 사용합니다.", + "super_can_only_be_referenced_in_a_derived_class_2335": "파생 클래스에서만 'super'를 참조할 수 있습니다.", + "super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions_2660": "파생 클래스 또는 개체 리터럴 식의 멤버에서만 'super'를 참조할 수 있습니다.", + "super_cannot_be_referenced_in_a_computed_property_name_2466": "'super'는 계산된 속성 이름에서 참조할 수 없습니다.", + "super_cannot_be_referenced_in_constructor_arguments_2336": "super'는 생성자 인수에서 참조할 수 없습니다.", + "super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_highe_2659": "옵션 'target'이 'ES2015' 이상인 경우 개체 리터럴 식의 멤버에서만 'super'를 사용할 수 있습니다.", + "super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class_17011": "파생 클래스의 생성자에서 'super'의 속성에 액세스하기 전에 'super'를 호출해야 합니다.", + "super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class_17009": "파생 클래스의 생성자에서 'this'에 액세스하기 전에 'super'를 호출해야 합니다.", + "super_must_be_followed_by_an_argument_list_or_member_access_1034": "'super' 다음에는 인수 목록 또는 멤버 액세스가 와야 합니다.", + "super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_der_2338": "'super' 속성 액세스는 생성자, 멤버 함수 또는 파생 클래스의 멤버 접근자에서만 허용됩니다.", + "this_cannot_be_referenced_in_a_computed_property_name_2465": "'this'는 계산된 속성 이름에서 참조할 수 없습니다.", + "this_cannot_be_referenced_in_a_module_or_namespace_body_2331": "'this'는 모듈 또는 네임스페이스 본문에서 참조될 수 없습니다.", + "this_cannot_be_referenced_in_a_static_property_initializer_2334": "정적 속성 이니셜라이저에서 'this'를 참조할 수 없습니다.", + "this_cannot_be_referenced_in_constructor_arguments_2333": "생성자 인수에서 'this'를 참조할 수 없습니다.", + "this_cannot_be_referenced_in_current_location_2332": "현재 위치에서 'this'를 참조할 수 없습니다.", + "this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_2683": "'this'에는 형식 주석이 없으므로 암시적으로 'any' 형식이 포함됩니다.", + "type_aliases_can_only_be_used_in_a_ts_file_8008": "'type aliases'는 .ts 파일에서만 사용할 수 있습니다.", + "type_arguments_can_only_be_used_in_a_ts_file_8011": "'type arguments'는 .ts 파일에서만 사용할 수 있습니다.", + "type_assertion_expressions_can_only_be_used_in_a_ts_file_8016": "'type assertion expressions'는 .ts 파일에서만 사용할 수 있습니다.", + "type_parameter_declarations_can_only_be_used_in_a_ts_file_8004": "'type parameter declarations'는 .ts 파일에서만 사용할 수 있습니다.", + "types_can_only_be_used_in_a_ts_file_8010": "'types'는 .ts 파일에서만 사용할 수 있습니다.", + "unique_symbol_types_are_not_allowed_here_1335": "여기에서 'unique symbol' 형식은 허용되지 않습니다.", + "unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement_1334": "'unique symbol' 형식은 변수 문의 변수에만 허용됩니다.", + "unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name_1333": "'unique symbol' 형식은 바인딩 이름과 함께 변수 선언에 사용할 수 없습니다.", + "with_statements_are_not_allowed_in_an_async_function_block_1300": "'with' 문은 비동기 함수 블록에서 사용할 수 없습니다.", + "with_statements_are_not_allowed_in_strict_mode_1101": "'with' 문은 strict 모드에서 사용할 수 없습니다.", + "yield_expressions_cannot_be_used_in_a_parameter_initializer_2523": "'yield' 식은 매개 변수 이니셜라이저에서 사용할 수 없습니다." +} \ No newline at end of file diff --git a/node_modules/typescript/lib/lib.d.ts b/node_modules/typescript/lib/lib.d.ts new file mode 100644 index 0000000..38a1cc0 --- /dev/null +++ b/node_modules/typescript/lib/lib.d.ts @@ -0,0 +1,24 @@ +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + + + +/// + + +/// +/// +/// +/// diff --git a/node_modules/typescript/lib/lib.dom.d.ts b/node_modules/typescript/lib/lib.dom.d.ts new file mode 100644 index 0000000..464dea8 --- /dev/null +++ b/node_modules/typescript/lib/lib.dom.d.ts @@ -0,0 +1,17992 @@ +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + + + +/// + + +///////////////////////////// +/// DOM APIs +///////////////////////////// + +interface Account { + displayName: string; + id: string; + imageURL?: string; + name?: string; + rpDisplayName: string; +} + +interface AddEventListenerOptions extends EventListenerOptions { + once?: boolean; + passive?: boolean; +} + +interface AesCbcParams extends Algorithm { + iv: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer; +} + +interface AesCtrParams extends Algorithm { + counter: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer; + length: number; +} + +interface AesDerivedKeyParams extends Algorithm { + length: number; +} + +interface AesGcmParams extends Algorithm { + additionalData?: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer; + iv: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer; + tagLength?: number; +} + +interface AesKeyAlgorithm extends KeyAlgorithm { + length: number; +} + +interface AesKeyGenParams extends Algorithm { + length: number; +} + +interface Algorithm { + name: string; +} + +interface AnalyserOptions extends AudioNodeOptions { + fftSize?: number; + maxDecibels?: number; + minDecibels?: number; + smoothingTimeConstant?: number; +} + +interface AnimationEventInit extends EventInit { + animationName?: string; + elapsedTime?: number; + pseudoElement?: string; +} + +interface AnimationPlaybackEventInit extends EventInit { + currentTime?: number | null; + timelineTime?: number | null; +} + +interface AssertionOptions { + allowList?: ScopedCredentialDescriptor[]; + extensions?: WebAuthnExtensions; + rpId?: string; + timeoutSeconds?: number; +} + +interface AssignedNodesOptions { + flatten?: boolean; +} + +interface AudioBufferOptions { + length: number; + numberOfChannels?: number; + sampleRate: number; +} + +interface AudioBufferSourceOptions { + buffer?: AudioBuffer | null; + detune?: number; + loop?: boolean; + loopEnd?: number; + loopStart?: number; + playbackRate?: number; +} + +interface AudioContextInfo { + currentTime?: number; + sampleRate?: number; +} + +interface AudioContextOptions { + latencyHint?: AudioContextLatencyCategory | number; + sampleRate?: number; +} + +interface AudioNodeOptions { + channelCount?: number; + channelCountMode?: ChannelCountMode; + channelInterpretation?: ChannelInterpretation; +} + +interface AudioParamDescriptor { + automationRate?: AutomationRate; + defaultValue?: number; + maxValue?: number; + minValue?: number; + name: string; +} + +interface AudioProcessingEventInit extends EventInit { + inputBuffer: AudioBuffer; + outputBuffer: AudioBuffer; + playbackTime: number; +} + +interface AudioTimestamp { + contextTime?: number; + performanceTime?: number; +} + +interface AudioWorkletNodeOptions extends AudioNodeOptions { + numberOfInputs?: number; + numberOfOutputs?: number; + outputChannelCount?: number[]; + parameterData?: Record; + processorOptions?: any; +} + +interface BiquadFilterOptions extends AudioNodeOptions { + Q?: number; + detune?: number; + frequency?: number; + gain?: number; + type?: BiquadFilterType; +} + +interface BlobPropertyBag { + endings?: EndingType; + type?: string; +} + +interface ByteLengthChunk { + byteLength?: number; +} + +interface CacheQueryOptions { + cacheName?: string; + ignoreMethod?: boolean; + ignoreSearch?: boolean; + ignoreVary?: boolean; +} + +interface CanvasRenderingContext2DSettings { + alpha?: boolean; +} + +interface ChannelMergerOptions extends AudioNodeOptions { + numberOfInputs?: number; +} + +interface ChannelSplitterOptions extends AudioNodeOptions { + numberOfOutputs?: number; +} + +interface ClientData { + challenge: string; + extensions?: WebAuthnExtensions; + hashAlg: string | Algorithm; + origin: string; + rpId: string; + tokenBinding?: string; +} + +interface ClientQueryOptions { + includeUncontrolled?: boolean; + type?: ClientTypes; +} + +interface CloseEventInit extends EventInit { + code?: number; + reason?: string; + wasClean?: boolean; +} + +interface CompositionEventInit extends UIEventInit { + data?: string; +} + +interface ComputedEffectTiming extends EffectTiming { + activeDuration?: number; + currentIteration?: number | null; + endTime?: number; + localTime?: number | null; + progress?: number | null; +} + +interface ComputedKeyframe { + composite: CompositeOperationOrAuto; + computedOffset: number; + easing: string; + offset: number | null; + [property: string]: string | number | null | undefined; +} + +interface ConfirmSiteSpecificExceptionsInformation extends ExceptionInformation { + arrayOfDomainStrings?: string[]; +} + +interface ConstantSourceOptions { + offset?: number; +} + +interface ConstrainBooleanParameters { + exact?: boolean; + ideal?: boolean; +} + +interface ConstrainDOMStringParameters { + exact?: string | string[]; + ideal?: string | string[]; +} + +interface ConstrainDoubleRange extends DoubleRange { + exact?: number; + ideal?: number; +} + +interface ConstrainLongRange extends LongRange { + exact?: number; + ideal?: number; +} + +interface ConstrainVideoFacingModeParameters { + exact?: VideoFacingModeEnum | VideoFacingModeEnum[]; + ideal?: VideoFacingModeEnum | VideoFacingModeEnum[]; +} + +interface ConvolverOptions extends AudioNodeOptions { + buffer?: AudioBuffer | null; + disableNormalization?: boolean; +} + +interface CustomEventInit extends EventInit { + detail?: T; +} + +interface DOMMatrix2DInit { + a?: number; + b?: number; + c?: number; + d?: number; + e?: number; + f?: number; + m11?: number; + m12?: number; + m21?: number; + m22?: number; + m41?: number; + m42?: number; +} + +interface DOMMatrixInit extends DOMMatrix2DInit { + is2D?: boolean; + m13?: number; + m14?: number; + m23?: number; + m24?: number; + m31?: number; + m32?: number; + m33?: number; + m34?: number; + m43?: number; + m44?: number; +} + +interface DOMPointInit { + w?: number; + x?: number; + y?: number; + z?: number; +} + +interface DOMQuadInit { + p1?: DOMPointInit; + p2?: DOMPointInit; + p3?: DOMPointInit; + p4?: DOMPointInit; +} + +interface DOMRectInit { + height?: number; + width?: number; + x?: number; + y?: number; +} + +interface DelayOptions extends AudioNodeOptions { + delayTime?: number; + maxDelayTime?: number; +} + +interface DeviceAccelerationDict { + x?: number | null; + y?: number | null; + z?: number | null; +} + +interface DeviceLightEventInit extends EventInit { + value?: number; +} + +interface DeviceMotionEventInit extends EventInit { + acceleration?: DeviceAccelerationDict | null; + accelerationIncludingGravity?: DeviceAccelerationDict | null; + interval?: number | null; + rotationRate?: DeviceRotationRateDict | null; +} + +interface DeviceOrientationEventInit extends EventInit { + absolute?: boolean; + alpha?: number | null; + beta?: number | null; + gamma?: number | null; +} + +interface DeviceRotationRateDict { + alpha?: number | null; + beta?: number | null; + gamma?: number | null; +} + +interface DocumentTimelineOptions { + originTime?: number; +} + +interface DoubleRange { + max?: number; + min?: number; +} + +interface DragEventInit extends MouseEventInit { + dataTransfer?: DataTransfer | null; +} + +interface DynamicsCompressorOptions extends AudioNodeOptions { + attack?: number; + knee?: number; + ratio?: number; + release?: number; + threshold?: number; +} + +interface EcKeyAlgorithm extends KeyAlgorithm { + namedCurve: NamedCurve; +} + +interface EcKeyGenParams extends Algorithm { + namedCurve: NamedCurve; +} + +interface EcKeyImportParams extends Algorithm { + namedCurve: NamedCurve; +} + +interface EcdhKeyDeriveParams extends Algorithm { + public: CryptoKey; +} + +interface EcdsaParams extends Algorithm { + hash: HashAlgorithmIdentifier; +} + +interface EffectTiming { + delay?: number; + direction?: PlaybackDirection; + duration?: number | string; + easing?: string; + endDelay?: number; + fill?: FillMode; + iterationStart?: number; + iterations?: number; +} + +interface ElementDefinitionOptions { + extends?: string; +} + +interface ErrorEventInit extends EventInit { + colno?: number; + error?: any; + filename?: string; + lineno?: number; + message?: string; +} + +interface EventInit { + bubbles?: boolean; + cancelable?: boolean; + composed?: boolean; +} + +interface EventListenerOptions { + capture?: boolean; +} + +interface EventModifierInit extends UIEventInit { + altKey?: boolean; + ctrlKey?: boolean; + metaKey?: boolean; + modifierAltGraph?: boolean; + modifierCapsLock?: boolean; + modifierFn?: boolean; + modifierFnLock?: boolean; + modifierHyper?: boolean; + modifierNumLock?: boolean; + modifierOS?: boolean; + modifierScrollLock?: boolean; + modifierSuper?: boolean; + modifierSymbol?: boolean; + modifierSymbolLock?: boolean; + shiftKey?: boolean; +} + +interface ExceptionInformation { + domain?: string | null; +} + +interface FilePropertyBag extends BlobPropertyBag { + lastModified?: number; +} + +interface FocusEventInit extends UIEventInit { + relatedTarget?: EventTarget | null; +} + +interface FocusNavigationEventInit extends EventInit { + navigationReason?: string | null; + originHeight?: number; + originLeft?: number; + originTop?: number; + originWidth?: number; +} + +interface FocusNavigationOrigin { + originHeight?: number; + originLeft?: number; + originTop?: number; + originWidth?: number; +} + +interface FocusOptions { + preventScroll?: boolean; +} + +interface GainOptions extends AudioNodeOptions { + gain?: number; +} + +interface GamepadEventInit extends EventInit { + gamepad?: Gamepad; +} + +interface GetNotificationOptions { + tag?: string; +} + +interface GetRootNodeOptions { + composed?: boolean; +} + +interface HashChangeEventInit extends EventInit { + newURL?: string; + oldURL?: string; +} + +interface HkdfParams extends Algorithm { + hash: HashAlgorithmIdentifier; + info: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer; + salt: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer; +} + +interface HmacImportParams extends Algorithm { + hash: HashAlgorithmIdentifier; + length?: number; +} + +interface HmacKeyAlgorithm extends KeyAlgorithm { + hash: KeyAlgorithm; + length: number; +} + +interface HmacKeyGenParams extends Algorithm { + hash: HashAlgorithmIdentifier; + length?: number; +} + +interface IDBIndexParameters { + multiEntry?: boolean; + unique?: boolean; +} + +interface IDBObjectStoreParameters { + autoIncrement?: boolean; + keyPath?: string | string[] | null; +} + +interface IDBVersionChangeEventInit extends EventInit { + newVersion?: number | null; + oldVersion?: number; +} + +interface IIRFilterOptions extends AudioNodeOptions { + feedback: number[]; + feedforward: number[]; +} + +interface IntersectionObserverEntryInit { + boundingClientRect: DOMRectInit; + intersectionRect: DOMRectInit; + isIntersecting: boolean; + rootBounds: DOMRectInit; + target: Element; + time: number; +} + +interface IntersectionObserverInit { + root?: Element | null; + rootMargin?: string; + threshold?: number | number[]; +} + +interface JsonWebKey { + alg?: string; + crv?: string; + d?: string; + dp?: string; + dq?: string; + e?: string; + ext?: boolean; + k?: string; + key_ops?: string[]; + kty?: string; + n?: string; + oth?: RsaOtherPrimesInfo[]; + p?: string; + q?: string; + qi?: string; + use?: string; + x?: string; + y?: string; +} + +interface KeyAlgorithm { + name: string; +} + +interface KeyboardEventInit extends EventModifierInit { + code?: string; + key?: string; + location?: number; + repeat?: boolean; +} + +interface Keyframe { + composite?: CompositeOperationOrAuto; + easing?: string; + offset?: number | null; + [property: string]: string | number | null | undefined; +} + +interface KeyframeAnimationOptions extends KeyframeEffectOptions { + id?: string; +} + +interface KeyframeEffectOptions extends EffectTiming { + composite?: CompositeOperation; + iterationComposite?: IterationCompositeOperation; +} + +interface LongRange { + max?: number; + min?: number; +} + +interface MediaElementAudioSourceOptions { + mediaElement: HTMLMediaElement; +} + +interface MediaEncryptedEventInit extends EventInit { + initData?: ArrayBuffer | null; + initDataType?: string; +} + +interface MediaKeyMessageEventInit extends EventInit { + message?: ArrayBuffer | null; + messageType?: MediaKeyMessageType; +} + +interface MediaKeySystemConfiguration { + audioCapabilities?: MediaKeySystemMediaCapability[]; + distinctiveIdentifier?: MediaKeysRequirement; + initDataTypes?: string[]; + persistentState?: MediaKeysRequirement; + videoCapabilities?: MediaKeySystemMediaCapability[]; +} + +interface MediaKeySystemMediaCapability { + contentType?: string; + robustness?: string; +} + +interface MediaQueryListEventInit extends EventInit { + matches?: boolean; + media?: string; +} + +interface MediaStreamAudioSourceOptions { + mediaStream: MediaStream; +} + +interface MediaStreamConstraints { + audio?: boolean | MediaTrackConstraints; + peerIdentity?: string; + video?: boolean | MediaTrackConstraints; +} + +interface MediaStreamErrorEventInit extends EventInit { + error?: MediaStreamError | null; +} + +interface MediaStreamEventInit extends EventInit { + stream?: MediaStream; +} + +interface MediaStreamTrackAudioSourceOptions { + mediaStreamTrack: MediaStreamTrack; +} + +interface MediaStreamTrackEventInit extends EventInit { + track?: MediaStreamTrack | null; +} + +interface MediaTrackCapabilities { + aspectRatio?: number | DoubleRange; + deviceId?: string; + echoCancellation?: boolean[]; + facingMode?: string; + frameRate?: number | DoubleRange; + groupId?: string; + height?: number | LongRange; + sampleRate?: number | LongRange; + sampleSize?: number | LongRange; + volume?: number | DoubleRange; + width?: number | LongRange; +} + +interface MediaTrackConstraintSet { + aspectRatio?: number | ConstrainDoubleRange; + channelCount?: number | ConstrainLongRange; + deviceId?: string | string[] | ConstrainDOMStringParameters; + displaySurface?: string | string[] | ConstrainDOMStringParameters; + echoCancellation?: boolean | ConstrainBooleanParameters; + facingMode?: string | string[] | ConstrainDOMStringParameters; + frameRate?: number | ConstrainDoubleRange; + groupId?: string | string[] | ConstrainDOMStringParameters; + height?: number | ConstrainLongRange; + latency?: number | ConstrainDoubleRange; + logicalSurface?: boolean | ConstrainBooleanParameters; + sampleRate?: number | ConstrainLongRange; + sampleSize?: number | ConstrainLongRange; + volume?: number | ConstrainDoubleRange; + width?: number | ConstrainLongRange; +} + +interface MediaTrackConstraints extends MediaTrackConstraintSet { + advanced?: MediaTrackConstraintSet[]; +} + +interface MediaTrackSettings { + aspectRatio?: number; + deviceId?: string; + echoCancellation?: boolean; + facingMode?: string; + frameRate?: number; + groupId?: string; + height?: number; + sampleRate?: number; + sampleSize?: number; + volume?: number; + width?: number; +} + +interface MediaTrackSupportedConstraints { + aspectRatio?: boolean; + deviceId?: boolean; + echoCancellation?: boolean; + facingMode?: boolean; + frameRate?: boolean; + groupId?: boolean; + height?: boolean; + sampleRate?: boolean; + sampleSize?: boolean; + volume?: boolean; + width?: boolean; +} + +interface MessageEventInit extends EventInit { + data?: any; + lastEventId?: string; + origin?: string; + ports?: MessagePort[]; + source?: MessageEventSource | null; +} + +interface MouseEventInit extends EventModifierInit { + button?: number; + buttons?: number; + clientX?: number; + clientY?: number; + relatedTarget?: EventTarget | null; + screenX?: number; + screenY?: number; +} + +interface MutationObserverInit { + attributeFilter?: string[]; + attributeOldValue?: boolean; + attributes?: boolean; + characterData?: boolean; + characterDataOldValue?: boolean; + childList?: boolean; + subtree?: boolean; +} + +interface NavigationPreloadState { + enabled?: boolean; + headerValue?: string; +} + +interface NotificationAction { + action: string; + icon?: string; + title: string; +} + +interface NotificationOptions { + actions?: NotificationAction[]; + badge?: string; + body?: string; + data?: any; + dir?: NotificationDirection; + icon?: string; + image?: string; + lang?: string; + renotify?: boolean; + requireInteraction?: boolean; + silent?: boolean; + tag?: string; + timestamp?: number; + vibrate?: VibratePattern; +} + +interface OfflineAudioCompletionEventInit extends EventInit { + renderedBuffer: AudioBuffer; +} + +interface OfflineAudioContextOptions { + length: number; + numberOfChannels?: number; + sampleRate: number; +} + +interface OptionalEffectTiming { + delay?: number; + direction?: PlaybackDirection; + duration?: number | string; + easing?: string; + endDelay?: number; + fill?: FillMode; + iterationStart?: number; + iterations?: number; +} + +interface OscillatorOptions extends AudioNodeOptions { + detune?: number; + frequency?: number; + periodicWave?: PeriodicWave; + type?: OscillatorType; +} + +interface PannerOptions extends AudioNodeOptions { + coneInnerAngle?: number; + coneOuterAngle?: number; + coneOuterGain?: number; + distanceModel?: DistanceModelType; + maxDistance?: number; + orientationX?: number; + orientationY?: number; + orientationZ?: number; + panningModel?: PanningModelType; + positionX?: number; + positionY?: number; + positionZ?: number; + refDistance?: number; + rolloffFactor?: number; +} + +interface PaymentCurrencyAmount { + currency: string; + currencySystem?: string; + value: string; +} + +interface PaymentDetailsBase { + displayItems?: PaymentItem[]; + modifiers?: PaymentDetailsModifier[]; + shippingOptions?: PaymentShippingOption[]; +} + +interface PaymentDetailsInit extends PaymentDetailsBase { + id?: string; + total: PaymentItem; +} + +interface PaymentDetailsModifier { + additionalDisplayItems?: PaymentItem[]; + data?: any; + supportedMethods: string | string[]; + total?: PaymentItem; +} + +interface PaymentDetailsUpdate extends PaymentDetailsBase { + error?: string; + total?: PaymentItem; +} + +interface PaymentItem { + amount: PaymentCurrencyAmount; + label: string; + pending?: boolean; +} + +interface PaymentMethodData { + data?: any; + supportedMethods: string | string[]; +} + +interface PaymentOptions { + requestPayerEmail?: boolean; + requestPayerName?: boolean; + requestPayerPhone?: boolean; + requestShipping?: boolean; + shippingType?: string; +} + +interface PaymentRequestUpdateEventInit extends EventInit { +} + +interface PaymentShippingOption { + amount: PaymentCurrencyAmount; + id: string; + label: string; + selected?: boolean; +} + +interface Pbkdf2Params extends Algorithm { + hash: HashAlgorithmIdentifier; + iterations: number; + salt: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer; +} + +interface PerformanceObserverInit { + buffered?: boolean; + entryTypes: string[]; +} + +interface PeriodicWaveConstraints { + disableNormalization?: boolean; +} + +interface PeriodicWaveOptions extends PeriodicWaveConstraints { + imag?: number[] | Float32Array; + real?: number[] | Float32Array; +} + +interface PipeOptions { + preventAbort?: boolean; + preventCancel?: boolean; + preventClose?: boolean; +} + +interface PointerEventInit extends MouseEventInit { + height?: number; + isPrimary?: boolean; + pointerId?: number; + pointerType?: string; + pressure?: number; + tangentialPressure?: number; + tiltX?: number; + tiltY?: number; + twist?: number; + width?: number; +} + +interface PopStateEventInit extends EventInit { + state?: any; +} + +interface PositionOptions { + enableHighAccuracy?: boolean; + maximumAge?: number; + timeout?: number; +} + +interface ProgressEventInit extends EventInit { + lengthComputable?: boolean; + loaded?: number; + total?: number; +} + +interface PromiseRejectionEventInit extends EventInit { + promise: Promise; + reason?: any; +} + +interface PropertyIndexedKeyframes { + composite?: CompositeOperationOrAuto | CompositeOperationOrAuto[]; + easing?: string | string[]; + offset?: number | (number | null)[]; + [property: string]: string | string[] | number | null | (number | null)[] | undefined; +} + +interface PushSubscriptionJSON { + endpoint?: string; + expirationTime?: number | null; + keys?: Record; +} + +interface PushSubscriptionOptionsInit { + applicationServerKey?: BufferSource | string | null; + userVisibleOnly?: boolean; +} + +interface QueuingStrategy { + highWaterMark?: number; + size?: QueuingStrategySizeCallback; +} + +interface RTCAnswerOptions extends RTCOfferAnswerOptions { +} + +interface RTCCertificateExpiration { + expires?: number; +} + +interface RTCConfiguration { + bundlePolicy?: RTCBundlePolicy; + certificates?: RTCCertificate[]; + iceCandidatePoolSize?: number; + iceServers?: RTCIceServer[]; + iceTransportPolicy?: RTCIceTransportPolicy; + peerIdentity?: string; + rtcpMuxPolicy?: RTCRtcpMuxPolicy; +} + +interface RTCDTMFToneChangeEventInit extends EventInit { + tone: string; +} + +interface RTCDataChannelEventInit extends EventInit { + channel: RTCDataChannel; +} + +interface RTCDataChannelInit { + id?: number; + maxPacketLifeTime?: number; + maxRetransmits?: number; + negotiated?: boolean; + ordered?: boolean; + priority?: RTCPriorityType; + protocol?: string; +} + +interface RTCDtlsFingerprint { + algorithm?: string; + value?: string; +} + +interface RTCDtlsParameters { + fingerprints?: RTCDtlsFingerprint[]; + role?: RTCDtlsRole; +} + +interface RTCErrorEventInit extends EventInit { + error?: RTCError | null; +} + +interface RTCIceCandidateAttributes extends RTCStats { + addressSourceUrl?: string; + candidateType?: RTCStatsIceCandidateType; + ipAddress?: string; + portNumber?: number; + priority?: number; + transport?: string; +} + +interface RTCIceCandidateComplete { +} + +interface RTCIceCandidateDictionary { + foundation?: string; + ip?: string; + msMTurnSessionId?: string; + port?: number; + priority?: number; + protocol?: RTCIceProtocol; + relatedAddress?: string; + relatedPort?: number; + tcpType?: RTCIceTcpCandidateType; + type?: RTCIceCandidateType; +} + +interface RTCIceCandidateInit { + candidate?: string; + sdpMLineIndex?: number | null; + sdpMid?: string | null; + usernameFragment?: string; +} + +interface RTCIceCandidatePair { + local?: RTCIceCandidate; + remote?: RTCIceCandidate; +} + +interface RTCIceCandidatePairStats extends RTCStats { + availableIncomingBitrate?: number; + availableOutgoingBitrate?: number; + bytesReceived?: number; + bytesSent?: number; + localCandidateId?: string; + nominated?: boolean; + priority?: number; + readable?: boolean; + remoteCandidateId?: string; + roundTripTime?: number; + state?: RTCStatsIceCandidatePairState; + transportId?: string; + writable?: boolean; +} + +interface RTCIceGatherOptions { + gatherPolicy?: RTCIceGatherPolicy; + iceservers?: RTCIceServer[]; +} + +interface RTCIceParameters { + password?: string; + usernameFragment?: string; +} + +interface RTCIceServer { + credential?: string | RTCOAuthCredential; + credentialType?: RTCIceCredentialType; + urls: string | string[]; + username?: string; +} + +interface RTCIdentityProviderOptions { + peerIdentity?: string; + protocol?: string; + usernameHint?: string; +} + +interface RTCInboundRTPStreamStats extends RTCRTPStreamStats { + bytesReceived?: number; + fractionLost?: number; + jitter?: number; + packetsLost?: number; + packetsReceived?: number; +} + +interface RTCMediaStreamTrackStats extends RTCStats { + audioLevel?: number; + echoReturnLoss?: number; + echoReturnLossEnhancement?: number; + frameHeight?: number; + frameWidth?: number; + framesCorrupted?: number; + framesDecoded?: number; + framesDropped?: number; + framesPerSecond?: number; + framesReceived?: number; + framesSent?: number; + remoteSource?: boolean; + ssrcIds?: string[]; + trackIdentifier?: string; +} + +interface RTCOAuthCredential { + accessToken: string; + macKey: string; +} + +interface RTCOfferAnswerOptions { + voiceActivityDetection?: boolean; +} + +interface RTCOfferOptions extends RTCOfferAnswerOptions { + iceRestart?: boolean; + offerToReceiveAudio?: boolean; + offerToReceiveVideo?: boolean; +} + +interface RTCOutboundRTPStreamStats extends RTCRTPStreamStats { + bytesSent?: number; + packetsSent?: number; + roundTripTime?: number; + targetBitrate?: number; +} + +interface RTCPeerConnectionIceErrorEventInit extends EventInit { + errorCode: number; + hostCandidate?: string; + statusText?: string; + url?: string; +} + +interface RTCPeerConnectionIceEventInit extends EventInit { + candidate?: RTCIceCandidate | null; + url?: string | null; +} + +interface RTCRTPStreamStats extends RTCStats { + associateStatsId?: string; + codecId?: string; + firCount?: number; + isRemote?: boolean; + mediaTrackId?: string; + mediaType?: string; + nackCount?: number; + pliCount?: number; + sliCount?: number; + ssrc?: string; + transportId?: string; +} + +interface RTCRtcpFeedback { + parameter?: string; + type?: string; +} + +interface RTCRtcpParameters { + cname?: string; + reducedSize?: boolean; +} + +interface RTCRtpCapabilities { + codecs: RTCRtpCodecCapability[]; + headerExtensions: RTCRtpHeaderExtensionCapability[]; +} + +interface RTCRtpCodecCapability { + channels?: number; + clockRate: number; + mimeType: string; + sdpFmtpLine?: string; +} + +interface RTCRtpCodecParameters { + channels?: number; + clockRate: number; + mimeType: string; + payloadType: number; + sdpFmtpLine?: string; +} + +interface RTCRtpCodingParameters { + rid?: string; +} + +interface RTCRtpContributingSource { + audioLevel?: number; + source: number; + timestamp: number; +} + +interface RTCRtpDecodingParameters extends RTCRtpCodingParameters { +} + +interface RTCRtpEncodingParameters extends RTCRtpCodingParameters { + active?: boolean; + codecPayloadType?: number; + dtx?: RTCDtxStatus; + maxBitrate?: number; + maxFramerate?: number; + priority?: RTCPriorityType; + ptime?: number; + scaleResolutionDownBy?: number; +} + +interface RTCRtpFecParameters { + mechanism?: string; + ssrc?: number; +} + +interface RTCRtpHeaderExtension { + kind?: string; + preferredEncrypt?: boolean; + preferredId?: number; + uri?: string; +} + +interface RTCRtpHeaderExtensionCapability { + uri?: string; +} + +interface RTCRtpHeaderExtensionParameters { + encrypted?: boolean; + id: number; + uri: string; +} + +interface RTCRtpParameters { + codecs: RTCRtpCodecParameters[]; + headerExtensions: RTCRtpHeaderExtensionParameters[]; + rtcp: RTCRtcpParameters; +} + +interface RTCRtpReceiveParameters extends RTCRtpParameters { + encodings: RTCRtpDecodingParameters[]; +} + +interface RTCRtpRtxParameters { + ssrc?: number; +} + +interface RTCRtpSendParameters extends RTCRtpParameters { + degradationPreference?: RTCDegradationPreference; + encodings: RTCRtpEncodingParameters[]; + transactionId: string; +} + +interface RTCRtpSynchronizationSource extends RTCRtpContributingSource { + voiceActivityFlag?: boolean; +} + +interface RTCRtpTransceiverInit { + direction?: RTCRtpTransceiverDirection; + sendEncodings?: RTCRtpEncodingParameters[]; + streams?: MediaStream[]; +} + +interface RTCRtpUnhandled { + muxId?: string; + payloadType?: number; + ssrc?: number; +} + +interface RTCSessionDescriptionInit { + sdp?: string; + type: RTCSdpType; +} + +interface RTCSrtpKeyParam { + keyMethod?: string; + keySalt?: string; + lifetime?: string; + mkiLength?: number; + mkiValue?: number; +} + +interface RTCSrtpSdesParameters { + cryptoSuite?: string; + keyParams?: RTCSrtpKeyParam[]; + sessionParams?: string[]; + tag?: number; +} + +interface RTCSsrcRange { + max?: number; + min?: number; +} + +interface RTCStats { + id: string; + timestamp: number; + type: RTCStatsType; +} + +interface RTCStatsEventInit extends EventInit { + report: RTCStatsReport; +} + +interface RTCStatsReport { +} + +interface RTCTrackEventInit extends EventInit { + receiver: RTCRtpReceiver; + streams?: MediaStream[]; + track: MediaStreamTrack; + transceiver: RTCRtpTransceiver; +} + +interface RTCTransportStats extends RTCStats { + activeConnection?: boolean; + bytesReceived?: number; + bytesSent?: number; + localCertificateId?: string; + remoteCertificateId?: string; + rtcpTransportStatsId?: string; + selectedCandidatePairId?: string; +} + +interface RegistrationOptions { + scope?: string; + type?: WorkerType; + updateViaCache?: ServiceWorkerUpdateViaCache; +} + +interface RequestInit { + body?: BodyInit | null; + cache?: RequestCache; + credentials?: RequestCredentials; + headers?: HeadersInit; + integrity?: string; + keepalive?: boolean; + method?: string; + mode?: RequestMode; + redirect?: RequestRedirect; + referrer?: string; + referrerPolicy?: ReferrerPolicy; + signal?: AbortSignal | null; + window?: any; +} + +interface ResponseInit { + headers?: HeadersInit; + status?: number; + statusText?: string; +} + +interface RsaHashedImportParams extends Algorithm { + hash: HashAlgorithmIdentifier; +} + +interface RsaHashedKeyAlgorithm extends RsaKeyAlgorithm { + hash: KeyAlgorithm; +} + +interface RsaHashedKeyGenParams extends RsaKeyGenParams { + hash: HashAlgorithmIdentifier; +} + +interface RsaKeyAlgorithm extends KeyAlgorithm { + modulusLength: number; + publicExponent: BigInteger; +} + +interface RsaKeyGenParams extends Algorithm { + modulusLength: number; + publicExponent: BigInteger; +} + +interface RsaOaepParams extends Algorithm { + label?: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer; +} + +interface RsaOtherPrimesInfo { + d?: string; + r?: string; + t?: string; +} + +interface RsaPssParams extends Algorithm { + saltLength: number; +} + +interface SVGBoundingBoxOptions { + clipped?: boolean; + fill?: boolean; + markers?: boolean; + stroke?: boolean; +} + +interface ScopedCredentialDescriptor { + id: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null; + transports?: Transport[]; + type: ScopedCredentialType; +} + +interface ScopedCredentialOptions { + excludeList?: ScopedCredentialDescriptor[]; + extensions?: WebAuthnExtensions; + rpId?: string; + timeoutSeconds?: number; +} + +interface ScopedCredentialParameters { + algorithm: string | Algorithm; + type: ScopedCredentialType; +} + +interface ScrollIntoViewOptions extends ScrollOptions { + block?: ScrollLogicalPosition; + inline?: ScrollLogicalPosition; +} + +interface ScrollOptions { + behavior?: ScrollBehavior; +} + +interface ScrollToOptions extends ScrollOptions { + left?: number; + top?: number; +} + +interface SecurityPolicyViolationEventInit extends EventInit { + blockedURI?: string; + columnNumber?: number; + documentURI?: string; + effectiveDirective?: string; + lineNumber?: number; + originalPolicy?: string; + referrer?: string; + sourceFile?: string; + statusCode?: number; + violatedDirective?: string; +} + +interface ServiceWorkerMessageEventInit extends EventInit { + data?: any; + lastEventId?: string; + origin?: string; + ports?: MessagePort[] | null; + source?: ServiceWorker | MessagePort | null; +} + +interface StereoPannerOptions extends AudioNodeOptions { + pan?: number; +} + +interface StorageEstimate { + quota?: number; + usage?: number; +} + +interface StorageEventInit extends EventInit { + key?: string | null; + newValue?: string | null; + oldValue?: string | null; + storageArea?: Storage | null; + url?: string; +} + +interface StoreExceptionsInformation extends ExceptionInformation { + detailURI?: string | null; + explanationString?: string | null; + siteName?: string | null; +} + +interface StoreSiteSpecificExceptionsInformation extends StoreExceptionsInformation { + arrayOfDomainStrings?: string[]; +} + +interface TextDecodeOptions { + stream?: boolean; +} + +interface TextDecoderOptions { + fatal?: boolean; + ignoreBOM?: boolean; +} + +interface TouchEventInit extends EventModifierInit { + changedTouches?: Touch[]; + targetTouches?: Touch[]; + touches?: Touch[]; +} + +interface TouchInit { + altitudeAngle?: number; + azimuthAngle?: number; + clientX?: number; + clientY?: number; + force?: number; + identifier: number; + pageX?: number; + pageY?: number; + radiusX?: number; + radiusY?: number; + rotationAngle?: number; + screenX?: number; + screenY?: number; + target: EventTarget; + touchType?: TouchType; +} + +interface TrackEventInit extends EventInit { + track?: VideoTrack | AudioTrack | TextTrack | null; +} + +interface Transformer { + flush?: TransformStreamDefaultControllerCallback; + readableType?: undefined; + start?: TransformStreamDefaultControllerCallback; + transform?: TransformStreamDefaultControllerTransformCallback; + writableType?: undefined; +} + +interface TransitionEventInit extends EventInit { + elapsedTime?: number; + propertyName?: string; + pseudoElement?: string; +} + +interface UIEventInit extends EventInit { + detail?: number; + view?: Window | null; +} + +interface UnderlyingByteSource { + autoAllocateChunkSize?: number; + cancel?: ReadableStreamErrorCallback; + pull?: ReadableByteStreamControllerCallback; + start?: ReadableByteStreamControllerCallback; + type: "bytes"; +} + +interface UnderlyingSink { + abort?: WritableStreamErrorCallback; + close?: WritableStreamDefaultControllerCloseCallback; + start?: WritableStreamDefaultControllerStartCallback; + type?: undefined; + write?: WritableStreamDefaultControllerWriteCallback; +} + +interface UnderlyingSource { + cancel?: ReadableStreamErrorCallback; + pull?: ReadableStreamDefaultControllerCallback; + start?: ReadableStreamDefaultControllerCallback; + type?: undefined; +} + +interface VRDisplayEventInit extends EventInit { + display: VRDisplay; + reason?: VRDisplayEventReason; +} + +interface VRLayer { + leftBounds?: number[] | Float32Array | null; + rightBounds?: number[] | Float32Array | null; + source?: HTMLCanvasElement | null; +} + +interface VRStageParameters { + sittingToStandingTransform?: Float32Array; + sizeX?: number; + sizeY?: number; +} + +interface WaveShaperOptions extends AudioNodeOptions { + curve?: number[] | Float32Array; + oversample?: OverSampleType; +} + +interface WebAuthnExtensions { +} + +interface WebGLContextAttributes { + alpha?: GLboolean; + antialias?: GLboolean; + depth?: GLboolean; + failIfMajorPerformanceCaveat?: boolean; + powerPreference?: WebGLPowerPreference; + premultipliedAlpha?: GLboolean; + preserveDrawingBuffer?: GLboolean; + stencil?: GLboolean; +} + +interface WebGLContextEventInit extends EventInit { + statusMessage?: string; +} + +interface WheelEventInit extends MouseEventInit { + deltaMode?: number; + deltaX?: number; + deltaY?: number; + deltaZ?: number; +} + +interface WorkerOptions { + credentials?: RequestCredentials; + name?: string; + type?: WorkerType; +} + +interface WorkletOptions { + credentials?: RequestCredentials; +} + +interface EventListener { + (evt: Event): void; +} + +interface ANGLE_instanced_arrays { + drawArraysInstancedANGLE(mode: GLenum, first: GLint, count: GLsizei, primcount: GLsizei): void; + drawElementsInstancedANGLE(mode: GLenum, count: GLsizei, type: GLenum, offset: GLintptr, primcount: GLsizei): void; + vertexAttribDivisorANGLE(index: GLuint, divisor: GLuint): void; + readonly VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE: GLenum; +} + +interface AbortController { + /** + * Returns the AbortSignal object associated with this object. + */ + readonly signal: AbortSignal; + /** + * Invoking this method will set this object's AbortSignal's aborted flag and + * signal to any observers that the associated activity is to be aborted. + */ + abort(): void; +} + +declare var AbortController: { + prototype: AbortController; + new(): AbortController; +}; + +interface AbortSignalEventMap { + "abort": ProgressEvent; +} + +interface AbortSignal extends EventTarget { + /** + * Returns true if this AbortSignal's AbortController has signaled to abort, and false + * otherwise. + */ + readonly aborted: boolean; + onabort: ((this: AbortSignal, ev: ProgressEvent) => any) | null; + addEventListener(type: K, listener: (this: AbortSignal, ev: AbortSignalEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: AbortSignal, ev: AbortSignalEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var AbortSignal: { + prototype: AbortSignal; + new(): AbortSignal; +}; + +interface AbstractRange { + readonly collapsed: boolean; + readonly endContainer: Node; + readonly endOffset: number; + readonly startContainer: Node; + readonly startOffset: number; +} + +declare var AbstractRange: { + prototype: AbstractRange; + new(): AbstractRange; +}; + +interface AbstractWorkerEventMap { + "error": ErrorEvent; +} + +interface AbstractWorker { + onerror: ((this: AbstractWorker, ev: ErrorEvent) => any) | null; + addEventListener(type: K, listener: (this: AbstractWorker, ev: AbstractWorkerEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: AbstractWorker, ev: AbstractWorkerEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +interface AesCfbParams extends Algorithm { + iv: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer; +} + +interface AesCmacParams extends Algorithm { + length: number; +} + +interface AnalyserNode extends AudioNode { + fftSize: number; + readonly frequencyBinCount: number; + maxDecibels: number; + minDecibels: number; + smoothingTimeConstant: number; + getByteFrequencyData(array: Uint8Array): void; + getByteTimeDomainData(array: Uint8Array): void; + getFloatFrequencyData(array: Float32Array): void; + getFloatTimeDomainData(array: Float32Array): void; +} + +declare var AnalyserNode: { + prototype: AnalyserNode; + new(context: BaseAudioContext, options?: AnalyserOptions): AnalyserNode; +}; + +interface Animatable { + animate(keyframes: Keyframe[] | PropertyIndexedKeyframes | null, options?: number | KeyframeAnimationOptions): Animation; + getAnimations(): Animation[]; +} + +interface AnimationEventMap { + "cancel": AnimationPlaybackEvent; + "finish": AnimationPlaybackEvent; +} + +interface Animation extends EventTarget { + currentTime: number | null; + effect: AnimationEffect | null; + readonly finished: Promise; + id: string; + oncancel: ((this: Animation, ev: AnimationPlaybackEvent) => any) | null; + onfinish: ((this: Animation, ev: AnimationPlaybackEvent) => any) | null; + readonly pending: boolean; + readonly playState: AnimationPlayState; + playbackRate: number; + readonly ready: Promise; + startTime: number | null; + timeline: AnimationTimeline | null; + cancel(): void; + finish(): void; + pause(): void; + play(): void; + reverse(): void; + updatePlaybackRate(playbackRate: number): void; + addEventListener(type: K, listener: (this: Animation, ev: AnimationEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: Animation, ev: AnimationEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var Animation: { + prototype: Animation; + new(effect?: AnimationEffect | null, timeline?: AnimationTimeline | null): Animation; +}; + +interface AnimationEffect { + getComputedTiming(): ComputedEffectTiming; + getTiming(): EffectTiming; + updateTiming(timing?: OptionalEffectTiming): void; +} + +declare var AnimationEffect: { + prototype: AnimationEffect; + new(): AnimationEffect; +}; + +interface AnimationEvent extends Event { + readonly animationName: string; + readonly elapsedTime: number; + readonly pseudoElement: string; +} + +declare var AnimationEvent: { + prototype: AnimationEvent; + new(type: string, animationEventInitDict?: AnimationEventInit): AnimationEvent; +}; + +interface AnimationPlaybackEvent extends Event { + readonly currentTime: number | null; + readonly timelineTime: number | null; +} + +declare var AnimationPlaybackEvent: { + prototype: AnimationPlaybackEvent; + new(type: string, eventInitDict?: AnimationPlaybackEventInit): AnimationPlaybackEvent; +}; + +interface AnimationTimeline { + readonly currentTime: number | null; +} + +declare var AnimationTimeline: { + prototype: AnimationTimeline; + new(): AnimationTimeline; +}; + +interface ApplicationCacheEventMap { + "cached": Event; + "checking": Event; + "downloading": Event; + "error": Event; + "noupdate": Event; + "obsolete": Event; + "progress": ProgressEvent; + "updateready": Event; +} + +interface ApplicationCache extends EventTarget { + /** @deprecated */ + oncached: ((this: ApplicationCache, ev: Event) => any) | null; + /** @deprecated */ + onchecking: ((this: ApplicationCache, ev: Event) => any) | null; + /** @deprecated */ + ondownloading: ((this: ApplicationCache, ev: Event) => any) | null; + /** @deprecated */ + onerror: ((this: ApplicationCache, ev: Event) => any) | null; + /** @deprecated */ + onnoupdate: ((this: ApplicationCache, ev: Event) => any) | null; + /** @deprecated */ + onobsolete: ((this: ApplicationCache, ev: Event) => any) | null; + /** @deprecated */ + onprogress: ((this: ApplicationCache, ev: ProgressEvent) => any) | null; + /** @deprecated */ + onupdateready: ((this: ApplicationCache, ev: Event) => any) | null; + /** @deprecated */ + readonly status: number; + /** @deprecated */ + abort(): void; + /** @deprecated */ + swapCache(): void; + /** @deprecated */ + update(): void; + readonly CHECKING: number; + readonly DOWNLOADING: number; + readonly IDLE: number; + readonly OBSOLETE: number; + readonly UNCACHED: number; + readonly UPDATEREADY: number; + addEventListener(type: K, listener: (this: ApplicationCache, ev: ApplicationCacheEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: ApplicationCache, ev: ApplicationCacheEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var ApplicationCache: { + prototype: ApplicationCache; + new(): ApplicationCache; + readonly CHECKING: number; + readonly DOWNLOADING: number; + readonly IDLE: number; + readonly OBSOLETE: number; + readonly UNCACHED: number; + readonly UPDATEREADY: number; +}; + +interface Attr extends Node { + readonly localName: string; + readonly name: string; + readonly namespaceURI: string | null; + readonly ownerElement: Element | null; + readonly prefix: string | null; + readonly specified: boolean; + value: string; +} + +declare var Attr: { + prototype: Attr; + new(): Attr; +}; + +interface AudioBuffer { + readonly duration: number; + readonly length: number; + readonly numberOfChannels: number; + readonly sampleRate: number; + copyFromChannel(destination: Float32Array, channelNumber: number, startInChannel?: number): void; + copyToChannel(source: Float32Array, channelNumber: number, startInChannel?: number): void; + getChannelData(channel: number): Float32Array; +} + +declare var AudioBuffer: { + prototype: AudioBuffer; + new(options: AudioBufferOptions): AudioBuffer; +}; + +interface AudioBufferSourceNode extends AudioScheduledSourceNode { + buffer: AudioBuffer | null; + readonly detune: AudioParam; + loop: boolean; + loopEnd: number; + loopStart: number; + readonly playbackRate: AudioParam; + start(when?: number, offset?: number, duration?: number): void; + addEventListener(type: K, listener: (this: AudioBufferSourceNode, ev: AudioScheduledSourceNodeEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: AudioBufferSourceNode, ev: AudioScheduledSourceNodeEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var AudioBufferSourceNode: { + prototype: AudioBufferSourceNode; + new(context: BaseAudioContext, options?: AudioBufferSourceOptions): AudioBufferSourceNode; +}; + +interface AudioContext extends BaseAudioContext { + readonly baseLatency: number; + readonly outputLatency: number; + close(): Promise; + createMediaElementSource(mediaElement: HTMLMediaElement): MediaElementAudioSourceNode; + createMediaStreamDestination(): MediaStreamAudioDestinationNode; + createMediaStreamSource(mediaStream: MediaStream): MediaStreamAudioSourceNode; + createMediaStreamTrackSource(mediaStreamTrack: MediaStreamTrack): MediaStreamTrackAudioSourceNode; + getOutputTimestamp(): AudioTimestamp; + suspend(): Promise; + addEventListener(type: K, listener: (this: AudioContext, ev: BaseAudioContextEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: AudioContext, ev: BaseAudioContextEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var AudioContext: { + prototype: AudioContext; + new(contextOptions?: AudioContextOptions): AudioContext; +}; + +interface AudioDestinationNode extends AudioNode { + readonly maxChannelCount: number; +} + +declare var AudioDestinationNode: { + prototype: AudioDestinationNode; + new(): AudioDestinationNode; +}; + +interface AudioListener { + readonly forwardX: AudioParam; + readonly forwardY: AudioParam; + readonly forwardZ: AudioParam; + readonly positionX: AudioParam; + readonly positionY: AudioParam; + readonly positionZ: AudioParam; + readonly upX: AudioParam; + readonly upY: AudioParam; + readonly upZ: AudioParam; + /** @deprecated */ + setOrientation(x: number, y: number, z: number, xUp: number, yUp: number, zUp: number): void; + /** @deprecated */ + setPosition(x: number, y: number, z: number): void; +} + +declare var AudioListener: { + prototype: AudioListener; + new(): AudioListener; +}; + +interface AudioNode extends EventTarget { + channelCount: number; + channelCountMode: ChannelCountMode; + channelInterpretation: ChannelInterpretation; + readonly context: BaseAudioContext; + readonly numberOfInputs: number; + readonly numberOfOutputs: number; + connect(destinationNode: AudioNode, output?: number, input?: number): AudioNode; + connect(destinationParam: AudioParam, output?: number): void; + disconnect(): void; + disconnect(output: number): void; + disconnect(destinationNode: AudioNode): void; + disconnect(destinationNode: AudioNode, output: number): void; + disconnect(destinationNode: AudioNode, output: number, input: number): void; + disconnect(destinationParam: AudioParam): void; + disconnect(destinationParam: AudioParam, output: number): void; +} + +declare var AudioNode: { + prototype: AudioNode; + new(): AudioNode; +}; + +interface AudioParam { + automationRate: AutomationRate; + readonly defaultValue: number; + readonly maxValue: number; + readonly minValue: number; + value: number; + cancelAndHoldAtTime(cancelTime: number): AudioParam; + cancelScheduledValues(cancelTime: number): AudioParam; + exponentialRampToValueAtTime(value: number, endTime: number): AudioParam; + linearRampToValueAtTime(value: number, endTime: number): AudioParam; + setTargetAtTime(target: number, startTime: number, timeConstant: number): AudioParam; + setValueAtTime(value: number, startTime: number): AudioParam; + setValueCurveAtTime(values: number[] | Float32Array, startTime: number, duration: number): AudioParam; +} + +declare var AudioParam: { + prototype: AudioParam; + new(): AudioParam; +}; + +interface AudioParamMap { + forEach(callbackfn: (value: AudioParam, key: string, parent: AudioParamMap) => void, thisArg?: any): void; +} + +declare var AudioParamMap: { + prototype: AudioParamMap; + new(): AudioParamMap; +}; + +interface AudioProcessingEvent extends Event { + readonly inputBuffer: AudioBuffer; + readonly outputBuffer: AudioBuffer; + readonly playbackTime: number; +} + +declare var AudioProcessingEvent: { + prototype: AudioProcessingEvent; + new(type: string, eventInitDict: AudioProcessingEventInit): AudioProcessingEvent; +}; + +interface AudioScheduledSourceNodeEventMap { + "ended": Event; +} + +interface AudioScheduledSourceNode extends AudioNode { + onended: ((this: AudioScheduledSourceNode, ev: Event) => any) | null; + start(when?: number): void; + stop(when?: number): void; + addEventListener(type: K, listener: (this: AudioScheduledSourceNode, ev: AudioScheduledSourceNodeEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: AudioScheduledSourceNode, ev: AudioScheduledSourceNodeEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var AudioScheduledSourceNode: { + prototype: AudioScheduledSourceNode; + new(): AudioScheduledSourceNode; +}; + +interface AudioTrack { + enabled: boolean; + readonly id: string; + kind: string; + readonly label: string; + language: string; + readonly sourceBuffer: SourceBuffer; +} + +declare var AudioTrack: { + prototype: AudioTrack; + new(): AudioTrack; +}; + +interface AudioTrackListEventMap { + "addtrack": TrackEvent; + "change": Event; + "removetrack": TrackEvent; +} + +interface AudioTrackList extends EventTarget { + readonly length: number; + onaddtrack: ((this: AudioTrackList, ev: TrackEvent) => any) | null; + onchange: ((this: AudioTrackList, ev: Event) => any) | null; + onremovetrack: ((this: AudioTrackList, ev: TrackEvent) => any) | null; + getTrackById(id: string): AudioTrack | null; + item(index: number): AudioTrack; + addEventListener(type: K, listener: (this: AudioTrackList, ev: AudioTrackListEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: AudioTrackList, ev: AudioTrackListEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; + [index: number]: AudioTrack; +} + +declare var AudioTrackList: { + prototype: AudioTrackList; + new(): AudioTrackList; +}; + +interface AudioWorklet extends Worklet { +} + +declare var AudioWorklet: { + prototype: AudioWorklet; + new(): AudioWorklet; +}; + +interface AudioWorkletNodeEventMap { + "processorerror": Event; +} + +interface AudioWorkletNode extends AudioNode { + onprocessorerror: ((this: AudioWorkletNode, ev: Event) => any) | null; + readonly parameters: AudioParamMap; + readonly port: MessagePort; + addEventListener(type: K, listener: (this: AudioWorkletNode, ev: AudioWorkletNodeEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: AudioWorkletNode, ev: AudioWorkletNodeEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var AudioWorkletNode: { + prototype: AudioWorkletNode; + new(context: BaseAudioContext, name: string, options?: AudioWorkletNodeOptions): AudioWorkletNode; +}; + +interface BarProp { + readonly visible: boolean; +} + +declare var BarProp: { + prototype: BarProp; + new(): BarProp; +}; + +interface BaseAudioContextEventMap { + "statechange": Event; +} + +interface BaseAudioContext extends EventTarget { + readonly audioWorklet: AudioWorklet; + readonly currentTime: number; + readonly destination: AudioDestinationNode; + readonly listener: AudioListener; + onstatechange: ((this: BaseAudioContext, ev: Event) => any) | null; + readonly sampleRate: number; + readonly state: AudioContextState; + createAnalyser(): AnalyserNode; + createBiquadFilter(): BiquadFilterNode; + createBuffer(numberOfChannels: number, length: number, sampleRate: number): AudioBuffer; + createBufferSource(): AudioBufferSourceNode; + createChannelMerger(numberOfInputs?: number): ChannelMergerNode; + createChannelSplitter(numberOfOutputs?: number): ChannelSplitterNode; + createConstantSource(): ConstantSourceNode; + createConvolver(): ConvolverNode; + createDelay(maxDelayTime?: number): DelayNode; + createDynamicsCompressor(): DynamicsCompressorNode; + createGain(): GainNode; + createIIRFilter(feedforward: number[], feedback: number[]): IIRFilterNode; + createOscillator(): OscillatorNode; + createPanner(): PannerNode; + createPeriodicWave(real: number[] | Float32Array, imag: number[] | Float32Array, constraints?: PeriodicWaveConstraints): PeriodicWave; + createScriptProcessor(bufferSize?: number, numberOfInputChannels?: number, numberOfOutputChannels?: number): ScriptProcessorNode; + createStereoPanner(): StereoPannerNode; + createWaveShaper(): WaveShaperNode; + decodeAudioData(audioData: ArrayBuffer, successCallback?: DecodeSuccessCallback | null, errorCallback?: DecodeErrorCallback | null): Promise; + resume(): Promise; + addEventListener(type: K, listener: (this: BaseAudioContext, ev: BaseAudioContextEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: BaseAudioContext, ev: BaseAudioContextEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var BaseAudioContext: { + prototype: BaseAudioContext; + new(): BaseAudioContext; +}; + +interface BeforeUnloadEvent extends Event { + returnValue: any; +} + +declare var BeforeUnloadEvent: { + prototype: BeforeUnloadEvent; + new(): BeforeUnloadEvent; +}; + +interface BhxBrowser { + readonly lastError: DOMException; + checkMatchesGlobExpression(pattern: string, value: string): boolean; + checkMatchesUriExpression(pattern: string, value: string): boolean; + clearLastError(): void; + currentWindowId(): number; + fireExtensionApiTelemetry(functionName: string, isSucceeded: boolean, isSupported: boolean, errorString: string): void; + genericFunction(functionId: number, destination: any, parameters?: string, callbackId?: number): void; + genericSynchronousFunction(functionId: number, parameters?: string): string; + getExtensionId(): string; + getThisAddress(): any; + registerGenericFunctionCallbackHandler(callbackHandler: Function): void; + registerGenericListenerHandler(eventHandler: Function): void; + setLastError(parameters: string): void; + webPlatformGenericFunction(destination: any, parameters?: string, callbackId?: number): void; +} + +declare var BhxBrowser: { + prototype: BhxBrowser; + new(): BhxBrowser; +}; + +interface BiquadFilterNode extends AudioNode { + readonly Q: AudioParam; + readonly detune: AudioParam; + readonly frequency: AudioParam; + readonly gain: AudioParam; + type: BiquadFilterType; + getFrequencyResponse(frequencyHz: Float32Array, magResponse: Float32Array, phaseResponse: Float32Array): void; +} + +declare var BiquadFilterNode: { + prototype: BiquadFilterNode; + new(context: BaseAudioContext, options?: BiquadFilterOptions): BiquadFilterNode; +}; + +interface Blob { + readonly size: number; + readonly type: string; + slice(start?: number, end?: number, contentType?: string): Blob; +} + +declare var Blob: { + prototype: Blob; + new(blobParts?: BlobPart[], options?: BlobPropertyBag): Blob; +}; + +interface Body { + readonly body: ReadableStream | null; + readonly bodyUsed: boolean; + arrayBuffer(): Promise; + blob(): Promise; + formData(): Promise; + json(): Promise; + text(): Promise; +} + +interface BroadcastChannelEventMap { + "message": MessageEvent; + "messageerror": MessageEvent; +} + +interface BroadcastChannel extends EventTarget { + /** + * Returns the channel name (as passed to the constructor). + */ + readonly name: string; + onmessage: ((this: BroadcastChannel, ev: MessageEvent) => any) | null; + onmessageerror: ((this: BroadcastChannel, ev: MessageEvent) => any) | null; + /** + * Closes the BroadcastChannel object, opening it up to garbage collection. + */ + close(): void; + /** + * Sends the given message to other BroadcastChannel objects set up for this channel. Messages can be structured objects, e.g. nested objects and arrays. + */ + postMessage(message: any): void; + addEventListener(type: K, listener: (this: BroadcastChannel, ev: BroadcastChannelEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: BroadcastChannel, ev: BroadcastChannelEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var BroadcastChannel: { + prototype: BroadcastChannel; + new(name: string): BroadcastChannel; +}; + +interface BroadcastChannelEventMap { + message: MessageEvent; + messageerror: MessageEvent; +} + +interface ByteLengthQueuingStrategy extends QueuingStrategy { + highWaterMark: number; + size(chunk: ArrayBufferView): number; +} + +declare var ByteLengthQueuingStrategy: { + prototype: ByteLengthQueuingStrategy; + new(options: { highWaterMark: number }): ByteLengthQueuingStrategy; +}; + +interface CDATASection extends Text { +} + +declare var CDATASection: { + prototype: CDATASection; + new(): CDATASection; +}; + +interface CSS { + escape(value: string): string; + supports(property: string, value?: string): boolean; +} +declare var CSS: CSS; + +interface CSSConditionRule extends CSSGroupingRule { + conditionText: string; +} + +declare var CSSConditionRule: { + prototype: CSSConditionRule; + new(): CSSConditionRule; +}; + +interface CSSFontFaceRule extends CSSRule { + readonly style: CSSStyleDeclaration; +} + +declare var CSSFontFaceRule: { + prototype: CSSFontFaceRule; + new(): CSSFontFaceRule; +}; + +interface CSSGroupingRule extends CSSRule { + readonly cssRules: CSSRuleList; + deleteRule(index: number): void; + insertRule(rule: string, index: number): number; +} + +declare var CSSGroupingRule: { + prototype: CSSGroupingRule; + new(): CSSGroupingRule; +}; + +interface CSSImportRule extends CSSRule { + readonly href: string; + readonly media: MediaList; + readonly styleSheet: CSSStyleSheet; +} + +declare var CSSImportRule: { + prototype: CSSImportRule; + new(): CSSImportRule; +}; + +interface CSSKeyframeRule extends CSSRule { + keyText: string; + readonly style: CSSStyleDeclaration; +} + +declare var CSSKeyframeRule: { + prototype: CSSKeyframeRule; + new(): CSSKeyframeRule; +}; + +interface CSSKeyframesRule extends CSSRule { + readonly cssRules: CSSRuleList; + name: string; + appendRule(rule: string): void; + deleteRule(select: string): void; + findRule(select: string): CSSKeyframeRule | null; +} + +declare var CSSKeyframesRule: { + prototype: CSSKeyframesRule; + new(): CSSKeyframesRule; +}; + +interface CSSMediaRule extends CSSConditionRule { + readonly media: MediaList; +} + +declare var CSSMediaRule: { + prototype: CSSMediaRule; + new(): CSSMediaRule; +}; + +interface CSSNamespaceRule extends CSSRule { + readonly namespaceURI: string; + readonly prefix: string; +} + +declare var CSSNamespaceRule: { + prototype: CSSNamespaceRule; + new(): CSSNamespaceRule; +}; + +interface CSSPageRule extends CSSRule { + readonly pseudoClass: string; + readonly selector: string; + selectorText: string; + readonly style: CSSStyleDeclaration; +} + +declare var CSSPageRule: { + prototype: CSSPageRule; + new(): CSSPageRule; +}; + +interface CSSRule { + cssText: string; + readonly parentRule: CSSRule | null; + readonly parentStyleSheet: CSSStyleSheet | null; + readonly type: number; + readonly CHARSET_RULE: number; + readonly FONT_FACE_RULE: number; + readonly IMPORT_RULE: number; + readonly KEYFRAMES_RULE: number; + readonly KEYFRAME_RULE: number; + readonly MEDIA_RULE: number; + readonly NAMESPACE_RULE: number; + readonly PAGE_RULE: number; + readonly STYLE_RULE: number; + readonly SUPPORTS_RULE: number; + readonly UNKNOWN_RULE: number; + readonly VIEWPORT_RULE: number; +} + +declare var CSSRule: { + prototype: CSSRule; + new(): CSSRule; + readonly CHARSET_RULE: number; + readonly FONT_FACE_RULE: number; + readonly IMPORT_RULE: number; + readonly KEYFRAMES_RULE: number; + readonly KEYFRAME_RULE: number; + readonly MEDIA_RULE: number; + readonly NAMESPACE_RULE: number; + readonly PAGE_RULE: number; + readonly STYLE_RULE: number; + readonly SUPPORTS_RULE: number; + readonly UNKNOWN_RULE: number; + readonly VIEWPORT_RULE: number; +}; + +interface CSSRuleList { + readonly length: number; + item(index: number): CSSRule | null; + [index: number]: CSSRule; +} + +declare var CSSRuleList: { + prototype: CSSRuleList; + new(): CSSRuleList; +}; + +interface CSSStyleDeclaration { + alignContent: string | null; + alignItems: string | null; + alignSelf: string | null; + alignmentBaseline: string | null; + animation: string; + animationDelay: string; + animationDirection: string; + animationDuration: string; + animationFillMode: string; + animationIterationCount: string; + animationName: string; + animationPlayState: string; + animationTimingFunction: string; + backfaceVisibility: string | null; + background: string | null; + backgroundAttachment: string | null; + backgroundClip: string | null; + backgroundColor: string | null; + backgroundImage: string | null; + backgroundOrigin: string | null; + backgroundPosition: string | null; + backgroundPositionX: string | null; + backgroundPositionY: string | null; + backgroundRepeat: string | null; + backgroundSize: string | null; + baselineShift: string | null; + border: string | null; + borderBottom: string | null; + borderBottomColor: string | null; + borderBottomLeftRadius: string | null; + borderBottomRightRadius: string | null; + borderBottomStyle: string | null; + borderBottomWidth: string | null; + borderCollapse: string | null; + borderColor: string | null; + borderImage: string | null; + borderImageOutset: string | null; + borderImageRepeat: string | null; + borderImageSlice: string | null; + borderImageSource: string | null; + borderImageWidth: string | null; + borderLeft: string | null; + borderLeftColor: string | null; + borderLeftStyle: string | null; + borderLeftWidth: string | null; + borderRadius: string | null; + borderRight: string | null; + borderRightColor: string | null; + borderRightStyle: string | null; + borderRightWidth: string | null; + borderSpacing: string | null; + borderStyle: string | null; + borderTop: string | null; + borderTopColor: string | null; + borderTopLeftRadius: string | null; + borderTopRightRadius: string | null; + borderTopStyle: string | null; + borderTopWidth: string | null; + borderWidth: string | null; + bottom: string | null; + boxShadow: string | null; + boxSizing: string | null; + breakAfter: string | null; + breakBefore: string | null; + breakInside: string | null; + captionSide: string | null; + clear: string | null; + clip: string | null; + clipPath: string | null; + clipRule: string | null; + color: string | null; + colorInterpolationFilters: string | null; + columnCount: any; + columnFill: string | null; + columnGap: any; + columnRule: string | null; + columnRuleColor: any; + columnRuleStyle: string | null; + columnRuleWidth: any; + columnSpan: string | null; + columnWidth: any; + columns: string | null; + content: string | null; + counterIncrement: string | null; + counterReset: string | null; + cssFloat: string | null; + cssText: string; + cursor: string | null; + direction: string | null; + display: string | null; + dominantBaseline: string | null; + emptyCells: string | null; + enableBackground: string | null; + fill: string | null; + fillOpacity: string | null; + fillRule: string | null; + filter: string | null; + flex: string | null; + flexBasis: string | null; + flexDirection: string | null; + flexFlow: string | null; + flexGrow: string | null; + flexShrink: string | null; + flexWrap: string | null; + floodColor: string | null; + floodOpacity: string | null; + font: string | null; + fontFamily: string | null; + fontFeatureSettings: string | null; + fontSize: string | null; + fontSizeAdjust: string | null; + fontStretch: string | null; + fontStyle: string | null; + fontVariant: string | null; + fontWeight: string | null; + gap: string | null; + glyphOrientationHorizontal: string | null; + glyphOrientationVertical: string | null; + grid: string | null; + gridArea: string | null; + gridAutoColumns: string | null; + gridAutoFlow: string | null; + gridAutoRows: string | null; + gridColumn: string | null; + gridColumnEnd: string | null; + gridColumnGap: string | null; + gridColumnStart: string | null; + gridGap: string | null; + gridRow: string | null; + gridRowEnd: string | null; + gridRowGap: string | null; + gridRowStart: string | null; + gridTemplate: string | null; + gridTemplateAreas: string | null; + gridTemplateColumns: string | null; + gridTemplateRows: string | null; + height: string | null; + imeMode: string | null; + justifyContent: string | null; + justifyItems: string | null; + justifySelf: string | null; + kerning: string | null; + layoutGrid: string | null; + layoutGridChar: string | null; + layoutGridLine: string | null; + layoutGridMode: string | null; + layoutGridType: string | null; + left: string | null; + readonly length: number; + letterSpacing: string | null; + lightingColor: string | null; + lineBreak: string | null; + lineHeight: string | null; + listStyle: string | null; + listStyleImage: string | null; + listStylePosition: string | null; + listStyleType: string | null; + margin: string | null; + marginBottom: string | null; + marginLeft: string | null; + marginRight: string | null; + marginTop: string | null; + marker: string | null; + markerEnd: string | null; + markerMid: string | null; + markerStart: string | null; + mask: string | null; + maskImage: string | null; + maxHeight: string | null; + maxWidth: string | null; + minHeight: string | null; + minWidth: string | null; + msContentZoomChaining: string | null; + msContentZoomLimit: string | null; + msContentZoomLimitMax: any; + msContentZoomLimitMin: any; + msContentZoomSnap: string | null; + msContentZoomSnapPoints: string | null; + msContentZoomSnapType: string | null; + msContentZooming: string | null; + msFlowFrom: string | null; + msFlowInto: string | null; + msFontFeatureSettings: string | null; + msGridColumn: any; + msGridColumnAlign: string | null; + msGridColumnSpan: any; + msGridColumns: string | null; + msGridRow: any; + msGridRowAlign: string | null; + msGridRowSpan: any; + msGridRows: string | null; + msHighContrastAdjust: string | null; + msHyphenateLimitChars: string | null; + msHyphenateLimitLines: any; + msHyphenateLimitZone: any; + msHyphens: string | null; + msImeAlign: string | null; + msOverflowStyle: string | null; + msScrollChaining: string | null; + msScrollLimit: string | null; + msScrollLimitXMax: any; + msScrollLimitXMin: any; + msScrollLimitYMax: any; + msScrollLimitYMin: any; + msScrollRails: string | null; + msScrollSnapPointsX: string | null; + msScrollSnapPointsY: string | null; + msScrollSnapType: string | null; + msScrollSnapX: string | null; + msScrollSnapY: string | null; + msScrollTranslation: string | null; + msTextCombineHorizontal: string | null; + msTextSizeAdjust: any; + msTouchAction: string | null; + msTouchSelect: string | null; + msUserSelect: string | null; + msWrapFlow: string; + msWrapMargin: any; + msWrapThrough: string; + objectFit: string | null; + objectPosition: string | null; + opacity: string | null; + order: string | null; + orphans: string | null; + outline: string | null; + outlineColor: string | null; + outlineOffset: string | null; + outlineStyle: string | null; + outlineWidth: string | null; + overflow: string | null; + overflowX: string | null; + overflowY: string | null; + padding: string | null; + paddingBottom: string | null; + paddingLeft: string | null; + paddingRight: string | null; + paddingTop: string | null; + pageBreakAfter: string | null; + pageBreakBefore: string | null; + pageBreakInside: string | null; + readonly parentRule: CSSRule; + penAction: string | null; + perspective: string | null; + perspectiveOrigin: string | null; + pointerEvents: string | null; + position: string | null; + quotes: string | null; + resize: string | null; + right: string | null; + rotate: string | null; + rowGap: string | null; + rubyAlign: string | null; + rubyOverhang: string | null; + rubyPosition: string | null; + scale: string | null; + scrollBehavior: string; + stopColor: string | null; + stopOpacity: string | null; + stroke: string | null; + strokeDasharray: string | null; + strokeDashoffset: string | null; + strokeLinecap: string | null; + strokeLinejoin: string | null; + strokeMiterlimit: string | null; + strokeOpacity: string | null; + strokeWidth: string | null; + tableLayout: string | null; + textAlign: string | null; + textAlignLast: string | null; + textAnchor: string | null; + textCombineUpright: string | null; + textDecoration: string | null; + textIndent: string | null; + textJustify: string | null; + textKashida: string | null; + textKashidaSpace: string | null; + textOverflow: string | null; + textShadow: string | null; + textTransform: string | null; + textUnderlinePosition: string | null; + top: string | null; + touchAction: string; + transform: string | null; + transformOrigin: string | null; + transformStyle: string | null; + transition: string; + transitionDelay: string; + transitionDuration: string; + transitionProperty: string; + transitionTimingFunction: string; + translate: string | null; + unicodeBidi: string | null; + userSelect: string | null; + verticalAlign: string | null; + visibility: string | null; + /** @deprecated */ + webkitAlignContent: string; + /** @deprecated */ + webkitAlignItems: string; + /** @deprecated */ + webkitAlignSelf: string; + /** @deprecated */ + webkitAnimation: string; + /** @deprecated */ + webkitAnimationDelay: string; + /** @deprecated */ + webkitAnimationDirection: string; + /** @deprecated */ + webkitAnimationDuration: string; + /** @deprecated */ + webkitAnimationFillMode: string; + /** @deprecated */ + webkitAnimationIterationCount: string; + /** @deprecated */ + webkitAnimationName: string; + /** @deprecated */ + webkitAnimationPlayState: string; + /** @deprecated */ + webkitAnimationTimingFunction: string; + /** @deprecated */ + webkitAppearance: string; + /** @deprecated */ + webkitBackfaceVisibility: string; + /** @deprecated */ + webkitBackgroundClip: string; + /** @deprecated */ + webkitBackgroundOrigin: string; + /** @deprecated */ + webkitBackgroundSize: string; + /** @deprecated */ + webkitBorderBottomLeftRadius: string; + /** @deprecated */ + webkitBorderBottomRightRadius: string; + webkitBorderImage: string | null; + /** @deprecated */ + webkitBorderRadius: string; + /** @deprecated */ + webkitBorderTopLeftRadius: string; + /** @deprecated */ + webkitBorderTopRightRadius: string; + /** @deprecated */ + webkitBoxAlign: string; + webkitBoxDirection: string | null; + /** @deprecated */ + webkitBoxFlex: string; + /** @deprecated */ + webkitBoxOrdinalGroup: string; + webkitBoxOrient: string | null; + /** @deprecated */ + webkitBoxPack: string; + /** @deprecated */ + webkitBoxShadow: string; + /** @deprecated */ + webkitBoxSizing: string; + webkitColumnBreakAfter: string | null; + webkitColumnBreakBefore: string | null; + webkitColumnBreakInside: string | null; + webkitColumnCount: any; + webkitColumnGap: any; + webkitColumnRule: string | null; + webkitColumnRuleColor: any; + webkitColumnRuleStyle: string | null; + webkitColumnRuleWidth: any; + webkitColumnSpan: string | null; + webkitColumnWidth: any; + webkitColumns: string | null; + /** @deprecated */ + webkitFilter: string; + /** @deprecated */ + webkitFlex: string; + /** @deprecated */ + webkitFlexBasis: string; + /** @deprecated */ + webkitFlexDirection: string; + /** @deprecated */ + webkitFlexFlow: string; + /** @deprecated */ + webkitFlexGrow: string; + /** @deprecated */ + webkitFlexShrink: string; + /** @deprecated */ + webkitFlexWrap: string; + /** @deprecated */ + webkitJustifyContent: string; + /** @deprecated */ + webkitMask: string; + /** @deprecated */ + webkitMaskBoxImage: string; + /** @deprecated */ + webkitMaskBoxImageOutset: string; + /** @deprecated */ + webkitMaskBoxImageRepeat: string; + /** @deprecated */ + webkitMaskBoxImageSlice: string; + /** @deprecated */ + webkitMaskBoxImageSource: string; + /** @deprecated */ + webkitMaskBoxImageWidth: string; + /** @deprecated */ + webkitMaskClip: string; + /** @deprecated */ + webkitMaskComposite: string; + /** @deprecated */ + webkitMaskImage: string; + /** @deprecated */ + webkitMaskOrigin: string; + /** @deprecated */ + webkitMaskPosition: string; + /** @deprecated */ + webkitMaskRepeat: string; + /** @deprecated */ + webkitMaskSize: string; + /** @deprecated */ + webkitOrder: string; + /** @deprecated */ + webkitPerspective: string; + /** @deprecated */ + webkitPerspectiveOrigin: string; + webkitTapHighlightColor: string | null; + /** @deprecated */ + webkitTextFillColor: string; + /** @deprecated */ + webkitTextSizeAdjust: string; + /** @deprecated */ + webkitTextStroke: string; + /** @deprecated */ + webkitTextStrokeColor: string; + /** @deprecated */ + webkitTextStrokeWidth: string; + /** @deprecated */ + webkitTransform: string; + /** @deprecated */ + webkitTransformOrigin: string; + /** @deprecated */ + webkitTransformStyle: string; + /** @deprecated */ + webkitTransition: string; + /** @deprecated */ + webkitTransitionDelay: string; + /** @deprecated */ + webkitTransitionDuration: string; + /** @deprecated */ + webkitTransitionProperty: string; + /** @deprecated */ + webkitTransitionTimingFunction: string; + webkitUserModify: string | null; + webkitUserSelect: string | null; + webkitWritingMode: string | null; + whiteSpace: string | null; + widows: string | null; + width: string | null; + wordBreak: string | null; + wordSpacing: string | null; + wordWrap: string | null; + writingMode: string | null; + zIndex: string | null; + zoom: string | null; + getPropertyPriority(propertyName: string): string; + getPropertyValue(propertyName: string): string; + item(index: number): string; + removeProperty(propertyName: string): string; + setProperty(propertyName: string, value: string | null, priority?: string | null): void; + [index: number]: string; +} + +declare var CSSStyleDeclaration: { + prototype: CSSStyleDeclaration; + new(): CSSStyleDeclaration; +}; + +interface CSSStyleRule extends CSSRule { + selectorText: string; + readonly style: CSSStyleDeclaration; +} + +declare var CSSStyleRule: { + prototype: CSSStyleRule; + new(): CSSStyleRule; +}; + +interface CSSStyleSheet extends StyleSheet { + readonly cssRules: CSSRuleList; + /** @deprecated */ + cssText: string; + /** @deprecated */ + readonly id: string; + /** @deprecated */ + readonly imports: StyleSheetList; + /** @deprecated */ + readonly isAlternate: boolean; + /** @deprecated */ + readonly isPrefAlternate: boolean; + readonly ownerRule: CSSRule | null; + /** @deprecated */ + readonly owningElement: Element; + /** @deprecated */ + readonly pages: any; + /** @deprecated */ + readonly readOnly: boolean; + readonly rules: CSSRuleList; + /** @deprecated */ + addImport(bstrURL: string, lIndex?: number): number; + /** @deprecated */ + addPageRule(bstrSelector: string, bstrStyle: string, lIndex?: number): number; + addRule(bstrSelector: string, bstrStyle?: string, lIndex?: number): number; + deleteRule(index?: number): void; + insertRule(rule: string, index?: number): number; + /** @deprecated */ + removeImport(lIndex: number): void; + removeRule(lIndex: number): void; +} + +declare var CSSStyleSheet: { + prototype: CSSStyleSheet; + new(): CSSStyleSheet; +}; + +interface CSSSupportsRule extends CSSConditionRule { +} + +declare var CSSSupportsRule: { + prototype: CSSSupportsRule; + new(): CSSSupportsRule; +}; + +interface Cache { + add(request: RequestInfo): Promise; + addAll(requests: RequestInfo[]): Promise; + delete(request: RequestInfo, options?: CacheQueryOptions): Promise; + keys(request?: RequestInfo, options?: CacheQueryOptions): Promise>; + match(request: RequestInfo, options?: CacheQueryOptions): Promise; + matchAll(request?: RequestInfo, options?: CacheQueryOptions): Promise>; + put(request: RequestInfo, response: Response): Promise; +} + +declare var Cache: { + prototype: Cache; + new(): Cache; +}; + +interface CacheStorage { + delete(cacheName: string): Promise; + has(cacheName: string): Promise; + keys(): Promise; + match(request: RequestInfo, options?: CacheQueryOptions): Promise; + open(cacheName: string): Promise; +} + +declare var CacheStorage: { + prototype: CacheStorage; + new(): CacheStorage; +}; + +interface CanvasCompositing { + globalAlpha: number; + globalCompositeOperation: string; +} + +interface CanvasDrawImage { + drawImage(image: CanvasImageSource, dx: number, dy: number): void; + drawImage(image: CanvasImageSource, dx: number, dy: number, dw: number, dh: number): void; + drawImage(image: CanvasImageSource, sx: number, sy: number, sw: number, sh: number, dx: number, dy: number, dw: number, dh: number): void; +} + +interface CanvasDrawPath { + beginPath(): void; + clip(fillRule?: CanvasFillRule): void; + clip(path: Path2D, fillRule?: CanvasFillRule): void; + fill(fillRule?: CanvasFillRule): void; + fill(path: Path2D, fillRule?: CanvasFillRule): void; + isPointInPath(x: number, y: number, fillRule?: CanvasFillRule): boolean; + isPointInPath(path: Path2D, x: number, y: number, fillRule?: CanvasFillRule): boolean; + isPointInStroke(x: number, y: number): boolean; + isPointInStroke(path: Path2D, x: number, y: number): boolean; + stroke(): void; + stroke(path: Path2D): void; +} + +interface CanvasFillStrokeStyles { + fillStyle: string | CanvasGradient | CanvasPattern; + strokeStyle: string | CanvasGradient | CanvasPattern; + createLinearGradient(x0: number, y0: number, x1: number, y1: number): CanvasGradient; + createPattern(image: CanvasImageSource, repetition: string): CanvasPattern | null; + createRadialGradient(x0: number, y0: number, r0: number, x1: number, y1: number, r1: number): CanvasGradient; +} + +interface CanvasFilters { + filter: string; +} + +interface CanvasGradient { + /** + * Adds a color stop with the given color to the gradient at the given offset. 0.0 is the offset + * at one end of the gradient, 1.0 is the offset at the other end. + * Throws an "IndexSizeError" DOMException if the offset + * is out of range. Throws a "SyntaxError" DOMException if + * the color cannot be parsed. + */ + addColorStop(offset: number, color: string): void; +} + +declare var CanvasGradient: { + prototype: CanvasGradient; + new(): CanvasGradient; +}; + +interface CanvasImageData { + createImageData(sw: number, sh: number): ImageData; + createImageData(imagedata: ImageData): ImageData; + getImageData(sx: number, sy: number, sw: number, sh: number): ImageData; + putImageData(imagedata: ImageData, dx: number, dy: number): void; + putImageData(imagedata: ImageData, dx: number, dy: number, dirtyX: number, dirtyY: number, dirtyWidth: number, dirtyHeight: number): void; +} + +interface CanvasImageSmoothing { + imageSmoothingEnabled: boolean; + imageSmoothingQuality: ImageSmoothingQuality; +} + +interface CanvasPath { + arc(x: number, y: number, radius: number, startAngle: number, endAngle: number, anticlockwise?: boolean): void; + arcTo(x1: number, y1: number, x2: number, y2: number, radius: number): void; + bezierCurveTo(cp1x: number, cp1y: number, cp2x: number, cp2y: number, x: number, y: number): void; + closePath(): void; + ellipse(x: number, y: number, radiusX: number, radiusY: number, rotation: number, startAngle: number, endAngle: number, anticlockwise?: boolean): void; + lineTo(x: number, y: number): void; + moveTo(x: number, y: number): void; + quadraticCurveTo(cpx: number, cpy: number, x: number, y: number): void; + rect(x: number, y: number, w: number, h: number): void; +} + +interface CanvasPathDrawingStyles { + lineCap: CanvasLineCap; + lineDashOffset: number; + lineJoin: CanvasLineJoin; + lineWidth: number; + miterLimit: number; + getLineDash(): number[]; + setLineDash(segments: number[]): void; +} + +interface CanvasPattern { + /** + * Sets the transformation matrix that will be used when rendering the pattern during a fill or + * stroke painting operation. + */ + setTransform(transform?: DOMMatrix2DInit): void; +} + +declare var CanvasPattern: { + prototype: CanvasPattern; + new(): CanvasPattern; +}; + +interface CanvasRect { + clearRect(x: number, y: number, w: number, h: number): void; + fillRect(x: number, y: number, w: number, h: number): void; + strokeRect(x: number, y: number, w: number, h: number): void; +} + +interface CanvasRenderingContext2D extends CanvasState, CanvasTransform, CanvasCompositing, CanvasImageSmoothing, CanvasFillStrokeStyles, CanvasShadowStyles, CanvasFilters, CanvasRect, CanvasDrawPath, CanvasUserInterface, CanvasText, CanvasDrawImage, CanvasImageData, CanvasPathDrawingStyles, CanvasTextDrawingStyles, CanvasPath { + readonly canvas: HTMLCanvasElement; +} + +declare var CanvasRenderingContext2D: { + prototype: CanvasRenderingContext2D; + new(): CanvasRenderingContext2D; +}; + +interface CanvasShadowStyles { + shadowBlur: number; + shadowColor: string; + shadowOffsetX: number; + shadowOffsetY: number; +} + +interface CanvasState { + restore(): void; + save(): void; +} + +interface CanvasText { + fillText(text: string, x: number, y: number, maxWidth?: number): void; + measureText(text: string): TextMetrics; + strokeText(text: string, x: number, y: number, maxWidth?: number): void; +} + +interface CanvasTextDrawingStyles { + direction: CanvasDirection; + font: string; + textAlign: CanvasTextAlign; + textBaseline: CanvasTextBaseline; +} + +interface CanvasTransform { + getTransform(): DOMMatrix; + resetTransform(): void; + rotate(angle: number): void; + scale(x: number, y: number): void; + setTransform(a: number, b: number, c: number, d: number, e: number, f: number): void; + setTransform(transform?: DOMMatrix2DInit): void; + transform(a: number, b: number, c: number, d: number, e: number, f: number): void; + translate(x: number, y: number): void; +} + +interface CanvasUserInterface { + drawFocusIfNeeded(element: Element): void; + drawFocusIfNeeded(path: Path2D, element: Element): void; + scrollPathIntoView(): void; + scrollPathIntoView(path: Path2D): void; +} + +interface CaretPosition { + readonly offset: number; + readonly offsetNode: Node; + getClientRect(): DOMRect | null; +} + +declare var CaretPosition: { + prototype: CaretPosition; + new(): CaretPosition; +}; + +interface ChannelMergerNode extends AudioNode { +} + +declare var ChannelMergerNode: { + prototype: ChannelMergerNode; + new(context: BaseAudioContext, options?: ChannelMergerOptions): ChannelMergerNode; +}; + +interface ChannelSplitterNode extends AudioNode { +} + +declare var ChannelSplitterNode: { + prototype: ChannelSplitterNode; + new(context: BaseAudioContext, options?: ChannelSplitterOptions): ChannelSplitterNode; +}; + +interface CharacterData extends Node, NonDocumentTypeChildNode, ChildNode { + data: string; + readonly length: number; + appendData(data: string): void; + deleteData(offset: number, count: number): void; + insertData(offset: number, data: string): void; + replaceData(offset: number, count: number, data: string): void; + substringData(offset: number, count: number): string; +} + +declare var CharacterData: { + prototype: CharacterData; + new(): CharacterData; +}; + +interface ChildNode extends Node { + /** + * Inserts nodes just after node, while replacing strings in nodes with equivalent Text nodes. + * Throws a "HierarchyRequestError" DOMException if the constraints of + * the node tree are violated. + */ + after(...nodes: (Node | string)[]): void; + /** + * Inserts nodes just before node, while replacing strings in nodes with equivalent Text nodes. + * Throws a "HierarchyRequestError" DOMException if the constraints of + * the node tree are violated. + */ + before(...nodes: (Node | string)[]): void; + /** + * Removes node. + */ + remove(): void; + /** + * Replaces node with nodes, while replacing strings in nodes with equivalent Text nodes. + * Throws a "HierarchyRequestError" DOMException if the constraints of + * the node tree are violated. + */ + replaceWith(...nodes: (Node | string)[]): void; +} + +interface ClientRect { + bottom: number; + readonly height: number; + left: number; + right: number; + top: number; + readonly width: number; +} + +declare var ClientRect: { + prototype: ClientRect; + new(): ClientRect; +}; + +interface ClientRectList { + readonly length: number; + item(index: number): ClientRect; + [index: number]: ClientRect; +} + +declare var ClientRectList: { + prototype: ClientRectList; + new(): ClientRectList; +}; + +interface ClipboardEvent extends Event { + readonly clipboardData: DataTransfer; +} + +declare var ClipboardEvent: { + prototype: ClipboardEvent; + new(type: string, eventInitDict?: ClipboardEventInit): ClipboardEvent; +}; + +interface ClipboardEventInit extends EventInit { + data?: string; + dataType?: string; +} + +interface CloseEvent extends Event { + readonly code: number; + readonly reason: string; + readonly wasClean: boolean; + /** @deprecated */ + initCloseEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, wasCleanArg: boolean, codeArg: number, reasonArg: string): void; +} + +declare var CloseEvent: { + prototype: CloseEvent; + new(type: string, eventInitDict?: CloseEventInit): CloseEvent; +}; + +interface Comment extends CharacterData { +} + +declare var Comment: { + prototype: Comment; + new(data?: string): Comment; +}; + +interface CompositionEvent extends UIEvent { + readonly data: string; + readonly locale: string; + initCompositionEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, dataArg: string, locale: string): void; +} + +declare var CompositionEvent: { + prototype: CompositionEvent; + new(typeArg: string, eventInitDict?: CompositionEventInit): CompositionEvent; +}; + +interface ConcatParams extends Algorithm { + algorithmId: Uint8Array; + hash?: string | Algorithm; + partyUInfo: Uint8Array; + partyVInfo: Uint8Array; + privateInfo?: Uint8Array; + publicInfo?: Uint8Array; +} + +interface Console { + memory: any; + assert(condition?: boolean, message?: string, ...data: any[]): void; + clear(): void; + count(label?: string): void; + debug(message?: any, ...optionalParams: any[]): void; + dir(value?: any, ...optionalParams: any[]): void; + dirxml(value: any): void; + error(message?: any, ...optionalParams: any[]): void; + exception(message?: string, ...optionalParams: any[]): void; + group(groupTitle?: string, ...optionalParams: any[]): void; + groupCollapsed(groupTitle?: string, ...optionalParams: any[]): void; + groupEnd(): void; + info(message?: any, ...optionalParams: any[]): void; + log(message?: any, ...optionalParams: any[]): void; + markTimeline(label?: string): void; + profile(reportName?: string): void; + profileEnd(reportName?: string): void; + table(...tabularData: any[]): void; + time(label?: string): void; + timeEnd(label?: string): void; + timeStamp(label?: string): void; + timeline(label?: string): void; + timelineEnd(label?: string): void; + trace(message?: any, ...optionalParams: any[]): void; + warn(message?: any, ...optionalParams: any[]): void; +} + +declare var Console: { + prototype: Console; + new(): Console; +}; + +interface ConstantSourceNode extends AudioScheduledSourceNode { + readonly offset: AudioParam; + addEventListener(type: K, listener: (this: ConstantSourceNode, ev: AudioScheduledSourceNodeEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: ConstantSourceNode, ev: AudioScheduledSourceNodeEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var ConstantSourceNode: { + prototype: ConstantSourceNode; + new(context: BaseAudioContext, options?: ConstantSourceOptions): ConstantSourceNode; +}; + +interface ConvolverNode extends AudioNode { + buffer: AudioBuffer | null; + normalize: boolean; +} + +declare var ConvolverNode: { + prototype: ConvolverNode; + new(context: BaseAudioContext, options?: ConvolverOptions): ConvolverNode; +}; + +interface Coordinates { + readonly accuracy: number; + readonly altitude: number | null; + readonly altitudeAccuracy: number | null; + readonly heading: number | null; + readonly latitude: number; + readonly longitude: number; + readonly speed: number | null; +} + +interface CountQueuingStrategy extends QueuingStrategy { + highWaterMark: number; + size(chunk: any): 1; +} + +declare var CountQueuingStrategy: { + prototype: CountQueuingStrategy; + new(options: { highWaterMark: number }): CountQueuingStrategy; +}; + +interface Crypto { + readonly subtle: SubtleCrypto; + getRandomValues(array: T): T; +} + +declare var Crypto: { + prototype: Crypto; + new(): Crypto; +}; + +interface CryptoKey { + readonly algorithm: KeyAlgorithm; + readonly extractable: boolean; + readonly type: KeyType; + readonly usages: KeyUsage[]; +} + +declare var CryptoKey: { + prototype: CryptoKey; + new(): CryptoKey; +}; + +interface CryptoKeyPair { + privateKey: CryptoKey; + publicKey: CryptoKey; +} + +declare var CryptoKeyPair: { + prototype: CryptoKeyPair; + new(): CryptoKeyPair; +}; + +interface CustomElementRegistry { + define(name: string, constructor: Function, options?: ElementDefinitionOptions): void; + get(name: string): any; + upgrade(root: Node): void; + whenDefined(name: string): Promise; +} + +declare var CustomElementRegistry: { + prototype: CustomElementRegistry; + new(): CustomElementRegistry; +}; + +interface CustomEvent extends Event { + /** + * Returns any custom data event was created with. + * Typically used for synthetic events. + */ + readonly detail: T; + initCustomEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, detailArg: T): void; +} + +declare var CustomEvent: { + prototype: CustomEvent; + new(typeArg: string, eventInitDict?: CustomEventInit): CustomEvent; +}; + +interface DOMError { + readonly name: string; + toString(): string; +} + +declare var DOMError: { + prototype: DOMError; + new(): DOMError; +}; + +interface DOMException { + readonly code: number; + readonly message: string; + readonly name: string; + readonly ABORT_ERR: number; + readonly DATA_CLONE_ERR: number; + readonly DOMSTRING_SIZE_ERR: number; + readonly HIERARCHY_REQUEST_ERR: number; + readonly INDEX_SIZE_ERR: number; + readonly INUSE_ATTRIBUTE_ERR: number; + readonly INVALID_ACCESS_ERR: number; + readonly INVALID_CHARACTER_ERR: number; + readonly INVALID_MODIFICATION_ERR: number; + readonly INVALID_NODE_TYPE_ERR: number; + readonly INVALID_STATE_ERR: number; + readonly NAMESPACE_ERR: number; + readonly NETWORK_ERR: number; + readonly NOT_FOUND_ERR: number; + readonly NOT_SUPPORTED_ERR: number; + readonly NO_DATA_ALLOWED_ERR: number; + readonly NO_MODIFICATION_ALLOWED_ERR: number; + readonly QUOTA_EXCEEDED_ERR: number; + readonly SECURITY_ERR: number; + readonly SYNTAX_ERR: number; + readonly TIMEOUT_ERR: number; + readonly TYPE_MISMATCH_ERR: number; + readonly URL_MISMATCH_ERR: number; + readonly VALIDATION_ERR: number; + readonly WRONG_DOCUMENT_ERR: number; +} + +declare var DOMException: { + prototype: DOMException; + new(message?: string, name?: string): DOMException; + readonly ABORT_ERR: number; + readonly DATA_CLONE_ERR: number; + readonly DOMSTRING_SIZE_ERR: number; + readonly HIERARCHY_REQUEST_ERR: number; + readonly INDEX_SIZE_ERR: number; + readonly INUSE_ATTRIBUTE_ERR: number; + readonly INVALID_ACCESS_ERR: number; + readonly INVALID_CHARACTER_ERR: number; + readonly INVALID_MODIFICATION_ERR: number; + readonly INVALID_NODE_TYPE_ERR: number; + readonly INVALID_STATE_ERR: number; + readonly NAMESPACE_ERR: number; + readonly NETWORK_ERR: number; + readonly NOT_FOUND_ERR: number; + readonly NOT_SUPPORTED_ERR: number; + readonly NO_DATA_ALLOWED_ERR: number; + readonly NO_MODIFICATION_ALLOWED_ERR: number; + readonly QUOTA_EXCEEDED_ERR: number; + readonly SECURITY_ERR: number; + readonly SYNTAX_ERR: number; + readonly TIMEOUT_ERR: number; + readonly TYPE_MISMATCH_ERR: number; + readonly URL_MISMATCH_ERR: number; + readonly VALIDATION_ERR: number; + readonly WRONG_DOCUMENT_ERR: number; +}; + +interface DOMImplementation { + createDocument(namespaceURI: string | null, qualifiedName: string | null, doctype: DocumentType | null): Document; + createDocumentType(qualifiedName: string, publicId: string, systemId: string): DocumentType; + createHTMLDocument(title?: string): Document; + /** @deprecated */ + hasFeature(...args: any[]): true; +} + +declare var DOMImplementation: { + prototype: DOMImplementation; + new(): DOMImplementation; +}; + +interface DOML2DeprecatedColorProperty { + color: string; +} + +interface DOMMatrix extends DOMMatrixReadOnly { + a: number; + b: number; + c: number; + d: number; + e: number; + f: number; + m11: number; + m12: number; + m13: number; + m14: number; + m21: number; + m22: number; + m23: number; + m24: number; + m31: number; + m32: number; + m33: number; + m34: number; + m41: number; + m42: number; + m43: number; + m44: number; + invertSelf(): DOMMatrix; + multiplySelf(other?: DOMMatrixInit): DOMMatrix; + preMultiplySelf(other?: DOMMatrixInit): DOMMatrix; + rotateAxisAngleSelf(x?: number, y?: number, z?: number, angle?: number): DOMMatrix; + rotateFromVectorSelf(x?: number, y?: number): DOMMatrix; + rotateSelf(rotX?: number, rotY?: number, rotZ?: number): DOMMatrix; + scale3dSelf(scale?: number, originX?: number, originY?: number, originZ?: number): DOMMatrix; + scaleSelf(scaleX?: number, scaleY?: number, scaleZ?: number, originX?: number, originY?: number, originZ?: number): DOMMatrix; + setMatrixValue(transformList: string): DOMMatrix; + skewXSelf(sx?: number): DOMMatrix; + skewYSelf(sy?: number): DOMMatrix; + translateSelf(tx?: number, ty?: number, tz?: number): DOMMatrix; +} + +declare var DOMMatrix: { + prototype: DOMMatrix; + new(init?: string | number[]): DOMMatrix; + fromFloat32Array(array32: Float32Array): DOMMatrix; + fromFloat64Array(array64: Float64Array): DOMMatrix; + fromMatrix(other?: DOMMatrixInit): DOMMatrix; +}; + +type SVGMatrix = DOMMatrix; +declare var SVGMatrix: typeof DOMMatrix; + +type WebKitCSSMatrix = DOMMatrix; +declare var WebKitCSSMatrix: typeof DOMMatrix; + +interface DOMMatrixReadOnly { + readonly a: number; + readonly b: number; + readonly c: number; + readonly d: number; + readonly e: number; + readonly f: number; + readonly is2D: boolean; + readonly isIdentity: boolean; + readonly m11: number; + readonly m12: number; + readonly m13: number; + readonly m14: number; + readonly m21: number; + readonly m22: number; + readonly m23: number; + readonly m24: number; + readonly m31: number; + readonly m32: number; + readonly m33: number; + readonly m34: number; + readonly m41: number; + readonly m42: number; + readonly m43: number; + readonly m44: number; + flipX(): DOMMatrix; + flipY(): DOMMatrix; + inverse(): DOMMatrix; + multiply(other?: DOMMatrixInit): DOMMatrix; + rotate(rotX?: number, rotY?: number, rotZ?: number): DOMMatrix; + rotateAxisAngle(x?: number, y?: number, z?: number, angle?: number): DOMMatrix; + rotateFromVector(x?: number, y?: number): DOMMatrix; + scale(scaleX?: number, scaleY?: number, scaleZ?: number, originX?: number, originY?: number, originZ?: number): DOMMatrix; + scale3d(scale?: number, originX?: number, originY?: number, originZ?: number): DOMMatrix; + skewX(sx?: number): DOMMatrix; + skewY(sy?: number): DOMMatrix; + toFloat32Array(): Float32Array; + toFloat64Array(): Float64Array; + toJSON(): any; + transformPoint(point?: DOMPointInit): DOMPoint; + translate(tx?: number, ty?: number, tz?: number): DOMMatrix; +} + +declare var DOMMatrixReadOnly: { + prototype: DOMMatrixReadOnly; + new(init?: string | number[]): DOMMatrixReadOnly; + fromFloat32Array(array32: Float32Array): DOMMatrixReadOnly; + fromFloat64Array(array64: Float64Array): DOMMatrixReadOnly; + fromMatrix(other?: DOMMatrixInit): DOMMatrixReadOnly; +}; + +interface DOMParser { + parseFromString(str: string, type: SupportedType): Document; +} + +declare var DOMParser: { + prototype: DOMParser; + new(): DOMParser; +}; + +interface DOMPoint extends DOMPointReadOnly { + w: number; + x: number; + y: number; + z: number; +} + +declare var DOMPoint: { + prototype: DOMPoint; + new(x?: number, y?: number, z?: number, w?: number): DOMPoint; + fromPoint(other?: DOMPointInit): DOMPoint; +}; + +type SVGPoint = DOMPoint; +declare var SVGPoint: typeof DOMPoint; + +interface DOMPointReadOnly { + readonly w: number; + readonly x: number; + readonly y: number; + readonly z: number; + matrixTransform(matrix?: DOMMatrixInit): DOMPoint; + toJSON(): any; +} + +declare var DOMPointReadOnly: { + prototype: DOMPointReadOnly; + new(x?: number, y?: number, z?: number, w?: number): DOMPointReadOnly; + fromPoint(other?: DOMPointInit): DOMPointReadOnly; +}; + +interface DOMQuad { + readonly p1: DOMPoint; + readonly p2: DOMPoint; + readonly p3: DOMPoint; + readonly p4: DOMPoint; + getBounds(): DOMRect; + toJSON(): any; +} + +declare var DOMQuad: { + prototype: DOMQuad; + new(p1?: DOMPointInit, p2?: DOMPointInit, p3?: DOMPointInit, p4?: DOMPointInit): DOMQuad; + fromQuad(other?: DOMQuadInit): DOMQuad; + fromRect(other?: DOMRectInit): DOMQuad; +}; + +interface DOMRect extends DOMRectReadOnly { + height: number; + width: number; + x: number; + y: number; +} + +declare var DOMRect: { + prototype: DOMRect; + new(x?: number, y?: number, width?: number, height?: number): DOMRect; + fromRect(other?: DOMRectInit): DOMRect; +}; + +type SVGRect = DOMRect; +declare var SVGRect: typeof DOMRect; + +interface DOMRectList { + readonly length: number; + item(index: number): DOMRect | null; + [index: number]: DOMRect; +} + +declare var DOMRectList: { + prototype: DOMRectList; + new(): DOMRectList; +}; + +interface DOMRectReadOnly { + readonly bottom: number; + readonly height: number; + readonly left: number; + readonly right: number; + readonly top: number; + readonly width: number; + readonly x: number; + readonly y: number; + toJSON(): any; +} + +declare var DOMRectReadOnly: { + prototype: DOMRectReadOnly; + new(x?: number, y?: number, width?: number, height?: number): DOMRectReadOnly; + fromRect(other?: DOMRectInit): DOMRectReadOnly; +}; + +interface DOMSettableTokenList extends DOMTokenList { + value: string; +} + +declare var DOMSettableTokenList: { + prototype: DOMSettableTokenList; + new(): DOMSettableTokenList; +}; + +interface DOMStringList { + /** + * Returns the number of strings in strings. + */ + readonly length: number; + /** + * Returns true if strings contains string, and false + * otherwise. + */ + contains(string: string): boolean; + /** + * Returns the string with index index from strings. + */ + item(index: number): string | null; + [index: number]: string; +} + +declare var DOMStringList: { + prototype: DOMStringList; + new(): DOMStringList; +}; + +interface DOMStringMap { + [name: string]: string | undefined; +} + +declare var DOMStringMap: { + prototype: DOMStringMap; + new(): DOMStringMap; +}; + +interface DOMTokenList { + /** + * Returns the number of tokens. + */ + readonly length: number; + /** + * Returns the associated set as string. + * Can be set, to change the associated attribute. + */ + value: string; + /** + * Adds all arguments passed, except those already present. + * Throws a "SyntaxError" DOMException if one of the arguments is the empty + * string. + * Throws an "InvalidCharacterError" DOMException if one of the arguments + * contains any ASCII whitespace. + */ + add(...tokens: string[]): void; + /** + * Returns true if token is present, and false otherwise. + */ + contains(token: string): boolean; + /** + * tokenlist[index] + */ + item(index: number): string | null; + /** + * Removes arguments passed, if they are present. + * Throws a "SyntaxError" DOMException if one of the arguments is the empty + * string. + * Throws an "InvalidCharacterError" DOMException if one of the arguments + * contains any ASCII whitespace. + */ + remove(...tokens: string[]): void; + /** + * Replaces token with newToken. + * Returns true if token was replaced with newToken, and false otherwise. + * Throws a "SyntaxError" DOMException if one of the arguments is the empty + * string. + * Throws an "InvalidCharacterError" DOMException if one of the arguments + * contains any ASCII whitespace. + */ + replace(oldToken: string, newToken: string): void; + /** + * Returns true if token is in the associated attribute's supported tokens. Returns + * false otherwise. + * Throws a TypeError if the associated attribute has no supported tokens defined. + */ + supports(token: string): boolean; + toggle(token: string, force?: boolean): boolean; + forEach(callbackfn: (value: string, key: number, parent: DOMTokenList) => void, thisArg?: any): void; + [index: number]: string; +} + +declare var DOMTokenList: { + prototype: DOMTokenList; + new(): DOMTokenList; +}; + +interface DataCue extends TextTrackCue { + data: ArrayBuffer; + addEventListener(type: K, listener: (this: DataCue, ev: TextTrackCueEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: DataCue, ev: TextTrackCueEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var DataCue: { + prototype: DataCue; + new(): DataCue; +}; + +interface DataTransfer { + dropEffect: string; + effectAllowed: string; + /** + * Returns a FileList of the files being dragged, if any. + */ + readonly files: FileList; + /** + * Returns a DataTransferItemList object, with the drag data. + */ + readonly items: DataTransferItemList; + /** + * Returns a frozen array listing the formats that were set in the dragstart event. In addition, if any files are being + * dragged, then one of the types will be the string "Files". + */ + readonly types: ReadonlyArray; + /** + * Removes the data of the specified formats. Removes all data if the argument is omitted. + */ + clearData(format?: string): void; + /** + * Returns the specified data. If there is no such data, returns the empty string. + */ + getData(format: string): string; + /** + * Adds the specified data. + */ + setData(format: string, data: string): void; + /** + * Uses the given element to update the drag feedback, replacing any previously specified + * feedback. + */ + setDragImage(image: Element, x: number, y: number): void; +} + +declare var DataTransfer: { + prototype: DataTransfer; + new(): DataTransfer; +}; + +interface DataTransferItem { + /** + * Returns the drag data item kind, one of: "string", + * "file". + */ + readonly kind: string; + /** + * Returns the drag data item type string. + */ + readonly type: string; + /** + * Returns a File object, if the drag data item kind is File. + */ + getAsFile(): File | null; + /** + * Invokes the callback with the string data as the argument, if the drag data item + * kind is Plain Unicode string. + */ + getAsString(callback: FunctionStringCallback | null): void; + webkitGetAsEntry(): any; +} + +declare var DataTransferItem: { + prototype: DataTransferItem; + new(): DataTransferItem; +}; + +interface DataTransferItemList { + /** + * Returns the number of items in the drag data store. + */ + readonly length: number; + /** + * Adds a new entry for the given data to the drag data store. If the data is plain + * text then a type string has to be provided + * also. + */ + add(data: string, type: string): DataTransferItem | null; + add(data: File): DataTransferItem | null; + /** + * Removes all the entries in the drag data store. + */ + clear(): void; + item(index: number): DataTransferItem; + /** + * Removes the indexth entry in the drag data store. + */ + remove(index: number): void; + [name: number]: DataTransferItem; +} + +declare var DataTransferItemList: { + prototype: DataTransferItemList; + new(): DataTransferItemList; +}; + +interface DeferredPermissionRequest { + readonly id: number; + readonly type: MSWebViewPermissionType; + readonly uri: string; + allow(): void; + deny(): void; +} + +declare var DeferredPermissionRequest: { + prototype: DeferredPermissionRequest; + new(): DeferredPermissionRequest; +}; + +interface DelayNode extends AudioNode { + readonly delayTime: AudioParam; +} + +declare var DelayNode: { + prototype: DelayNode; + new(context: BaseAudioContext, options?: DelayOptions): DelayNode; +}; + +interface DeviceAcceleration { + readonly x: number | null; + readonly y: number | null; + readonly z: number | null; +} + +declare var DeviceAcceleration: { + prototype: DeviceAcceleration; + new(): DeviceAcceleration; +}; + +interface DeviceLightEvent extends Event { + readonly value: number; +} + +declare var DeviceLightEvent: { + prototype: DeviceLightEvent; + new(typeArg: string, eventInitDict?: DeviceLightEventInit): DeviceLightEvent; +}; + +interface DeviceMotionEvent extends Event { + readonly acceleration: DeviceAcceleration | null; + readonly accelerationIncludingGravity: DeviceAcceleration | null; + readonly interval: number | null; + readonly rotationRate: DeviceRotationRate | null; + initDeviceMotionEvent(type: string, bubbles: boolean, cancelable: boolean, acceleration: DeviceAccelerationDict | null, accelerationIncludingGravity: DeviceAccelerationDict | null, rotationRate: DeviceRotationRateDict | null, interval: number | null): void; +} + +declare var DeviceMotionEvent: { + prototype: DeviceMotionEvent; + new(typeArg: string, eventInitDict?: DeviceMotionEventInit): DeviceMotionEvent; +}; + +interface DeviceOrientationEvent extends Event { + readonly absolute: boolean; + readonly alpha: number | null; + readonly beta: number | null; + readonly gamma: number | null; + initDeviceOrientationEvent(type: string, bubbles: boolean, cancelable: boolean, alpha: number | null, beta: number | null, gamma: number | null, absolute: boolean): void; +} + +declare var DeviceOrientationEvent: { + prototype: DeviceOrientationEvent; + new(typeArg: string, eventInitDict?: DeviceOrientationEventInit): DeviceOrientationEvent; +}; + +interface DeviceRotationRate { + readonly alpha: number | null; + readonly beta: number | null; + readonly gamma: number | null; +} + +declare var DeviceRotationRate: { + prototype: DeviceRotationRate; + new(): DeviceRotationRate; +}; + +interface DhImportKeyParams extends Algorithm { + generator: Uint8Array; + prime: Uint8Array; +} + +interface DhKeyAlgorithm extends KeyAlgorithm { + generator: Uint8Array; + prime: Uint8Array; +} + +interface DhKeyDeriveParams extends Algorithm { + public: CryptoKey; +} + +interface DhKeyGenParams extends Algorithm { + generator: Uint8Array; + prime: Uint8Array; +} + +interface DocumentEventMap extends GlobalEventHandlersEventMap, DocumentAndElementEventHandlersEventMap { + "fullscreenchange": Event; + "fullscreenerror": Event; + "readystatechange": ProgressEvent; + "visibilitychange": Event; +} + +interface Document extends Node, NonElementParentNode, DocumentOrShadowRoot, ParentNode, GlobalEventHandlers, DocumentAndElementEventHandlers { + /** + * Sets or gets the URL for the current document. + */ + readonly URL: string; + /** + * Gets the object that has the focus when the parent document has focus. + */ + readonly activeElement: Element | null; + /** + * Sets or gets the color of all active links in the document. + */ + /** @deprecated */ + alinkColor: string; + /** + * Returns a reference to the collection of elements contained by the object. + */ + /** @deprecated */ + readonly all: HTMLAllCollection; + /** + * Retrieves a collection of all a objects that have a name and/or id property. Objects in this collection are in HTML source order. + */ + /** @deprecated */ + readonly anchors: HTMLCollectionOf; + /** + * Retrieves a collection of all applet objects in the document. + */ + /** @deprecated */ + readonly applets: HTMLCollectionOf; + /** + * Deprecated. Sets or retrieves a value that indicates the background color behind the object. + */ + /** @deprecated */ + bgColor: string; + /** + * Specifies the beginning and end of the document body. + */ + body: HTMLElement; + /** + * Returns document's encoding. + */ + readonly characterSet: string; + /** + * Gets or sets the character set used to encode the object. + */ + readonly charset: string; + /** + * Gets a value that indicates whether standards-compliant mode is switched on for the object. + */ + readonly compatMode: string; + /** + * Returns document's content type. + */ + readonly contentType: string; + /** + * Returns the HTTP cookies that apply to the Document. If there are no cookies or + * cookies can't be applied to this resource, the empty string will be returned. + * Can be set, to add a new cookie to the element's set of HTTP cookies. + * If the contents are sandboxed into a + * unique origin (e.g. in an iframe with the sandbox attribute), a + * "SecurityError" DOMException will be thrown on getting + * and setting. + */ + cookie: string; + /** + * Returns the script element, or the SVG script element, + * that is currently executing, as long as the element represents a classic script. + * In the case of reentrant script execution, returns the one that most recently started executing + * amongst those that have not yet finished executing. + * Returns null if the Document is not currently executing a script + * or SVG script element (e.g., because the running script is an event + * handler, or a timeout), or if the currently executing script or SVG + * script element represents a module script. + */ + readonly currentScript: HTMLOrSVGScriptElement | null; + readonly defaultView: WindowProxy | null; + /** + * Sets or gets a value that indicates whether the document can be edited. + */ + designMode: string; + /** + * Sets or retrieves a value that indicates the reading order of the object. + */ + dir: string; + /** + * Gets an object representing the document type declaration associated with the current document. + */ + readonly doctype: DocumentType | null; + /** + * Gets a reference to the root node of the document. + */ + readonly documentElement: HTMLElement; + /** + * Returns document's URL. + */ + readonly documentURI: string; + /** + * Sets or gets the security domain of the document. + */ + domain: string; + /** + * Retrieves a collection of all embed objects in the document. + */ + readonly embeds: HTMLCollectionOf; + /** + * Sets or gets the foreground (text) color of the document. + */ + /** @deprecated */ + fgColor: string; + /** + * Retrieves a collection, in source order, of all form objects in the document. + */ + readonly forms: HTMLCollectionOf; + /** @deprecated */ + readonly fullscreen: boolean; + /** + * Returns true if document has the ability to display elements fullscreen + * and fullscreen is supported, or false otherwise. + */ + readonly fullscreenEnabled: boolean; + /** + * Returns the head element. + */ + readonly head: HTMLHeadElement; + readonly hidden: boolean; + /** + * Retrieves a collection, in source order, of img objects in the document. + */ + readonly images: HTMLCollectionOf; + /** + * Gets the implementation object of the current document. + */ + readonly implementation: DOMImplementation; + /** + * Returns the character encoding used to create the webpage that is loaded into the document object. + */ + readonly inputEncoding: string; + /** + * Gets the date that the page was last modified, if the page supplies one. + */ + readonly lastModified: string; + /** + * Sets or gets the color of the document links. + */ + /** @deprecated */ + linkColor: string; + /** + * Retrieves a collection of all a objects that specify the href property and all area objects in the document. + */ + readonly links: HTMLCollectionOf; + /** + * Contains information about the current URL. + */ + location: Location; + onfullscreenchange: ((this: Document, ev: Event) => any) | null; + onfullscreenerror: ((this: Document, ev: Event) => any) | null; + /** + * Fires when the state of the object has changed. + * @param ev The event + */ + onreadystatechange: ((this: Document, ev: ProgressEvent) => any) | null; + onvisibilitychange: ((this: Document, ev: Event) => any) | null; + /** + * Returns document's origin. + */ + readonly origin: string; + /** + * Return an HTMLCollection of the embed elements in the Document. + */ + readonly plugins: HTMLCollectionOf; + /** + * Retrieves a value that indicates the current state of the object. + */ + readonly readyState: DocumentReadyState; + /** + * Gets the URL of the location that referred the user to the current page. + */ + readonly referrer: string; + /** + * Retrieves a collection of all script objects in the document. + */ + readonly scripts: HTMLCollectionOf; + readonly scrollingElement: Element | null; + readonly timeline: DocumentTimeline; + /** + * Contains the title of the document. + */ + title: string; + readonly visibilityState: VisibilityState; + /** + * Sets or gets the color of the links that the user has visited. + */ + /** @deprecated */ + vlinkColor: string; + /** + * Moves node from another document and returns it. + * If node is a document, throws a "NotSupportedError" DOMException or, if node is a shadow root, throws a + * "HierarchyRequestError" DOMException. + */ + adoptNode(source: T): T; + /** @deprecated */ + captureEvents(): void; + caretPositionFromPoint(x: number, y: number): CaretPosition | null; + /** @deprecated */ + caretRangeFromPoint(x: number, y: number): Range; + /** @deprecated */ + clear(): void; + /** + * Closes an output stream and forces the sent data to display. + */ + close(): void; + /** + * Creates an attribute object with a specified name. + * @param name String that sets the attribute object's name. + */ + createAttribute(localName: string): Attr; + createAttributeNS(namespace: string | null, qualifiedName: string): Attr; + /** + * Returns a CDATASection node whose data is data. + */ + createCDATASection(data: string): CDATASection; + /** + * Creates a comment object with the specified data. + * @param data Sets the comment object's data. + */ + createComment(data: string): Comment; + /** + * Creates a new document. + */ + createDocumentFragment(): DocumentFragment; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: K, options?: ElementCreationOptions): HTMLElementTagNameMap[K]; + /** @deprecated */ + createElement(tagName: K, options?: ElementCreationOptions): HTMLElementDeprecatedTagNameMap[K]; + createElement(tagName: string, options?: ElementCreationOptions): HTMLElement; + /** + * Returns an element with namespace namespace. Its namespace prefix will be everything before ":" (U+003E) in qualifiedName or null. Its local name will be everything after + * ":" (U+003E) in qualifiedName or qualifiedName. + * If localName does not match the Name production an + * "InvalidCharacterError" DOMException will be thrown. + * If one of the following conditions is true a "NamespaceError" DOMException will be thrown: + * localName does not match the QName production. + * Namespace prefix is not null and namespace is the empty string. + * Namespace prefix is "xml" and namespace is not the XML namespace. + * qualifiedName or namespace prefix is "xmlns" and namespace is not the XMLNS namespace. + * namespace is the XMLNS namespace and + * neither qualifiedName nor namespace prefix is "xmlns". + * When supplied, options's is can be used to create a customized built-in element. + */ + createElementNS(namespaceURI: "http://www.w3.org/1999/xhtml", qualifiedName: string): HTMLElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "a"): SVGAElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "circle"): SVGCircleElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "clipPath"): SVGClipPathElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "componentTransferFunction"): SVGComponentTransferFunctionElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "cursor"): SVGCursorElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "defs"): SVGDefsElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "desc"): SVGDescElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "ellipse"): SVGEllipseElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feBlend"): SVGFEBlendElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feColorMatrix"): SVGFEColorMatrixElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feComponentTransfer"): SVGFEComponentTransferElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feComposite"): SVGFECompositeElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feConvolveMatrix"): SVGFEConvolveMatrixElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feDiffuseLighting"): SVGFEDiffuseLightingElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feDisplacementMap"): SVGFEDisplacementMapElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feDistantLight"): SVGFEDistantLightElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFlood"): SVGFEFloodElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFuncA"): SVGFEFuncAElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFuncB"): SVGFEFuncBElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFuncG"): SVGFEFuncGElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFuncR"): SVGFEFuncRElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feGaussianBlur"): SVGFEGaussianBlurElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feImage"): SVGFEImageElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feMerge"): SVGFEMergeElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feMergeNode"): SVGFEMergeNodeElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feMorphology"): SVGFEMorphologyElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feOffset"): SVGFEOffsetElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "fePointLight"): SVGFEPointLightElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feSpecularLighting"): SVGFESpecularLightingElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feSpotLight"): SVGFESpotLightElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feTile"): SVGFETileElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feTurbulence"): SVGFETurbulenceElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "filter"): SVGFilterElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "foreignObject"): SVGForeignObjectElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "g"): SVGGElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "image"): SVGImageElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "gradient"): SVGGradientElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "line"): SVGLineElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "linearGradient"): SVGLinearGradientElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "marker"): SVGMarkerElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "mask"): SVGMaskElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "path"): SVGPathElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "metadata"): SVGMetadataElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "pattern"): SVGPatternElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "polygon"): SVGPolygonElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "polyline"): SVGPolylineElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "radialGradient"): SVGRadialGradientElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "rect"): SVGRectElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "svg"): SVGSVGElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "script"): SVGScriptElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "stop"): SVGStopElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "style"): SVGStyleElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "switch"): SVGSwitchElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "symbol"): SVGSymbolElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "tspan"): SVGTSpanElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "textContent"): SVGTextContentElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "text"): SVGTextElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "textPath"): SVGTextPathElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "textPositioning"): SVGTextPositioningElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "title"): SVGTitleElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "use"): SVGUseElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "view"): SVGViewElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: string): SVGElement; + createElementNS(namespaceURI: string | null, qualifiedName: string, options?: ElementCreationOptions): Element; + createElementNS(namespace: string | null, qualifiedName: string, options?: string | ElementCreationOptions): Element; + createEvent(eventInterface: "AnimationEvent"): AnimationEvent; + createEvent(eventInterface: "AnimationPlaybackEvent"): AnimationPlaybackEvent; + createEvent(eventInterface: "AudioProcessingEvent"): AudioProcessingEvent; + createEvent(eventInterface: "BeforeUnloadEvent"): BeforeUnloadEvent; + createEvent(eventInterface: "ClipboardEvent"): ClipboardEvent; + createEvent(eventInterface: "CloseEvent"): CloseEvent; + createEvent(eventInterface: "CompositionEvent"): CompositionEvent; + createEvent(eventInterface: "CustomEvent"): CustomEvent; + createEvent(eventInterface: "DeviceLightEvent"): DeviceLightEvent; + createEvent(eventInterface: "DeviceMotionEvent"): DeviceMotionEvent; + createEvent(eventInterface: "DeviceOrientationEvent"): DeviceOrientationEvent; + createEvent(eventInterface: "DragEvent"): DragEvent; + createEvent(eventInterface: "ErrorEvent"): ErrorEvent; + createEvent(eventInterface: "Event"): Event; + createEvent(eventInterface: "Events"): Event; + createEvent(eventInterface: "FocusEvent"): FocusEvent; + createEvent(eventInterface: "FocusNavigationEvent"): FocusNavigationEvent; + createEvent(eventInterface: "GamepadEvent"): GamepadEvent; + createEvent(eventInterface: "HashChangeEvent"): HashChangeEvent; + createEvent(eventInterface: "IDBVersionChangeEvent"): IDBVersionChangeEvent; + createEvent(eventInterface: "KeyboardEvent"): KeyboardEvent; + createEvent(eventInterface: "ListeningStateChangedEvent"): ListeningStateChangedEvent; + createEvent(eventInterface: "MSGestureEvent"): MSGestureEvent; + createEvent(eventInterface: "MSMediaKeyMessageEvent"): MSMediaKeyMessageEvent; + createEvent(eventInterface: "MSMediaKeyNeededEvent"): MSMediaKeyNeededEvent; + createEvent(eventInterface: "MSPointerEvent"): MSPointerEvent; + createEvent(eventInterface: "MediaEncryptedEvent"): MediaEncryptedEvent; + createEvent(eventInterface: "MediaKeyMessageEvent"): MediaKeyMessageEvent; + createEvent(eventInterface: "MediaQueryListEvent"): MediaQueryListEvent; + createEvent(eventInterface: "MediaStreamErrorEvent"): MediaStreamErrorEvent; + createEvent(eventInterface: "MediaStreamEvent"): MediaStreamEvent; + createEvent(eventInterface: "MediaStreamTrackEvent"): MediaStreamTrackEvent; + createEvent(eventInterface: "MessageEvent"): MessageEvent; + createEvent(eventInterface: "MouseEvent"): MouseEvent; + createEvent(eventInterface: "MouseEvents"): MouseEvent; + createEvent(eventInterface: "MutationEvent"): MutationEvent; + createEvent(eventInterface: "MutationEvents"): MutationEvent; + createEvent(eventInterface: "OfflineAudioCompletionEvent"): OfflineAudioCompletionEvent; + createEvent(eventInterface: "OverflowEvent"): OverflowEvent; + createEvent(eventInterface: "PageTransitionEvent"): PageTransitionEvent; + createEvent(eventInterface: "PaymentRequestUpdateEvent"): PaymentRequestUpdateEvent; + createEvent(eventInterface: "PermissionRequestedEvent"): PermissionRequestedEvent; + createEvent(eventInterface: "PointerEvent"): PointerEvent; + createEvent(eventInterface: "PopStateEvent"): PopStateEvent; + createEvent(eventInterface: "ProgressEvent"): ProgressEvent; + createEvent(eventInterface: "PromiseRejectionEvent"): PromiseRejectionEvent; + createEvent(eventInterface: "RTCDTMFToneChangeEvent"): RTCDTMFToneChangeEvent; + createEvent(eventInterface: "RTCDataChannelEvent"): RTCDataChannelEvent; + createEvent(eventInterface: "RTCDtlsTransportStateChangedEvent"): RTCDtlsTransportStateChangedEvent; + createEvent(eventInterface: "RTCErrorEvent"): RTCErrorEvent; + createEvent(eventInterface: "RTCIceCandidatePairChangedEvent"): RTCIceCandidatePairChangedEvent; + createEvent(eventInterface: "RTCIceGathererEvent"): RTCIceGathererEvent; + createEvent(eventInterface: "RTCIceTransportStateChangedEvent"): RTCIceTransportStateChangedEvent; + createEvent(eventInterface: "RTCPeerConnectionIceErrorEvent"): RTCPeerConnectionIceErrorEvent; + createEvent(eventInterface: "RTCPeerConnectionIceEvent"): RTCPeerConnectionIceEvent; + createEvent(eventInterface: "RTCSsrcConflictEvent"): RTCSsrcConflictEvent; + createEvent(eventInterface: "RTCStatsEvent"): RTCStatsEvent; + createEvent(eventInterface: "RTCTrackEvent"): RTCTrackEvent; + createEvent(eventInterface: "SVGZoomEvent"): SVGZoomEvent; + createEvent(eventInterface: "SVGZoomEvents"): SVGZoomEvent; + createEvent(eventInterface: "SecurityPolicyViolationEvent"): SecurityPolicyViolationEvent; + createEvent(eventInterface: "ServiceWorkerMessageEvent"): ServiceWorkerMessageEvent; + createEvent(eventInterface: "SpeechRecognitionError"): SpeechRecognitionError; + createEvent(eventInterface: "SpeechRecognitionEvent"): SpeechRecognitionEvent; + createEvent(eventInterface: "SpeechSynthesisErrorEvent"): SpeechSynthesisErrorEvent; + createEvent(eventInterface: "SpeechSynthesisEvent"): SpeechSynthesisEvent; + createEvent(eventInterface: "StorageEvent"): StorageEvent; + createEvent(eventInterface: "TextEvent"): TextEvent; + createEvent(eventInterface: "TouchEvent"): TouchEvent; + createEvent(eventInterface: "TrackEvent"): TrackEvent; + createEvent(eventInterface: "TransitionEvent"): TransitionEvent; + createEvent(eventInterface: "UIEvent"): UIEvent; + createEvent(eventInterface: "UIEvents"): UIEvent; + createEvent(eventInterface: "VRDisplayEvent"): VRDisplayEvent; + createEvent(eventInterface: "VRDisplayEvent "): VRDisplayEvent ; + createEvent(eventInterface: "WebGLContextEvent"): WebGLContextEvent; + createEvent(eventInterface: "WheelEvent"): WheelEvent; + createEvent(eventInterface: string): Event; + /** + * Creates a NodeIterator object that you can use to traverse filtered lists of nodes or elements in a document. + * @param root The root element or node to start traversing on. + * @param whatToShow The type of nodes or elements to appear in the node list + * @param filter A custom NodeFilter function to use. For more information, see filter. Use null for no filter. + * @param entityReferenceExpansion A flag that specifies whether entity reference nodes are expanded. + */ + createNodeIterator(root: Node, whatToShow?: number, filter?: NodeFilter | null): NodeIterator; + /** + * Returns a ProcessingInstruction node whose target is target and data is data. + * If target does not match the Name production an + * "InvalidCharacterError" DOMException will be thrown. + * If data contains "?>" an + * "InvalidCharacterError" DOMException will be thrown. + */ + createProcessingInstruction(target: string, data: string): ProcessingInstruction; + /** + * Returns an empty range object that has both of its boundary points positioned at the beginning of the document. + */ + createRange(): Range; + /** + * Creates a text string from the specified value. + * @param data String that specifies the nodeValue property of the text node. + */ + createTextNode(data: string): Text; + createTouch(view: WindowProxy, target: EventTarget, identifier: number, pageX: number, pageY: number, screenX: number, screenY: number): Touch; + createTouchList(...touches: Touch[]): TouchList; + /** + * Creates a TreeWalker object that you can use to traverse filtered lists of nodes or elements in a document. + * @param root The root element or node to start traversing on. + * @param whatToShow The type of nodes or elements to appear in the node list. For more information, see whatToShow. + * @param filter A custom NodeFilter function to use. + * @param entityReferenceExpansion A flag that specifies whether entity reference nodes are expanded. + */ + createTreeWalker(root: Node, whatToShow?: number, filter?: NodeFilter | null): TreeWalker; + /** @deprecated */ + createTreeWalker(root: Node, whatToShow: number, filter: NodeFilter | null, entityReferenceExpansion?: boolean): TreeWalker; + /** + * Returns the element for the specified x coordinate and the specified y coordinate. + * @param x The x-offset + * @param y The y-offset + */ + elementFromPoint(x: number, y: number): Element | null; + elementsFromPoint(x: number, y: number): Element[]; + evaluate(expression: string, contextNode: Node, resolver: XPathNSResolver | ((prefix: string) => string | null) | null, type: number, result: XPathResult | null): XPathResult; + /** + * Executes a command on the current document, current selection, or the given range. + * @param commandId String that specifies the command to execute. This command can be any of the command identifiers that can be executed in script. + * @param showUI Display the user interface, defaults to false. + * @param value Value to assign. + */ + execCommand(commandId: string, showUI?: boolean, value?: string): boolean; + /** + * Stops document's fullscreen element from being displayed fullscreen and + * resolves promise when done. + */ + exitFullscreen(): Promise; + getAnimations(): Animation[]; + /** + * Returns a reference to the first object with the specified value of the ID or NAME attribute. + * @param elementId String that specifies the ID value. Case-insensitive. + */ + getElementById(elementId: string): HTMLElement | null; + /** + * collection = element . getElementsByClassName(classNames) + */ + getElementsByClassName(classNames: string): HTMLCollectionOf; + /** + * Gets a collection of objects based on the value of the NAME or ID attribute. + * @param elementName Gets a collection of objects based on the value of the NAME or ID attribute. + */ + getElementsByName(elementName: string): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(qualifiedName: K): HTMLCollectionOf; + getElementsByTagName(qualifiedName: K): HTMLCollectionOf; + getElementsByTagName(qualifiedName: string): HTMLCollectionOf; + /** + * If namespace and localName are + * "*" returns a HTMLCollection of all descendant elements. + * If only namespace is "*" returns a HTMLCollection of all descendant elements whose local name is localName. + * If only localName is "*" returns a HTMLCollection of all descendant elements whose namespace is namespace. + * Otherwise, returns a HTMLCollection of all descendant elements whose namespace is namespace and local name is localName. + */ + getElementsByTagNameNS(namespaceURI: "http://www.w3.org/1999/xhtml", localName: string): HTMLCollectionOf; + getElementsByTagNameNS(namespaceURI: "http://www.w3.org/2000/svg", localName: string): HTMLCollectionOf; + getElementsByTagNameNS(namespaceURI: string, localName: string): HTMLCollectionOf; + /** + * Gets a value indicating whether the object currently has focus. + */ + hasFocus(): boolean; + importNode(importedNode: T, deep: boolean): T; + /** + * Opens a new window and loads a document specified by a given URL. Also, opens a new window that uses the url parameter and the name parameter to collect the output of the write method and the writeln method. + * @param url Specifies a MIME type for the document. + * @param name Specifies the name of the window. This name is used as the value for the TARGET attribute on a form or an anchor element. + * @param features Contains a list of items separated by commas. Each item consists of an option and a value, separated by an equals sign (for example, "fullscreen=yes, toolbar=yes"). The following values are supported. + * @param replace Specifies whether the existing entry for the document is replaced in the history list. + */ + open(url?: string, name?: string, features?: string, replace?: boolean): Document; + /** + * Returns a Boolean value that indicates whether a specified command can be successfully executed using execCommand, given the current state of the document. + * @param commandId Specifies a command identifier. + */ + queryCommandEnabled(commandId: string): boolean; + /** + * Returns a Boolean value that indicates whether the specified command is in the indeterminate state. + * @param commandId String that specifies a command identifier. + */ + queryCommandIndeterm(commandId: string): boolean; + /** + * Returns a Boolean value that indicates the current state of the command. + * @param commandId String that specifies a command identifier. + */ + queryCommandState(commandId: string): boolean; + /** + * Returns a Boolean value that indicates whether the current command is supported on the current range. + * @param commandId Specifies a command identifier. + */ + queryCommandSupported(commandId: string): boolean; + /** + * Returns the current value of the document, range, or current selection for the given command. + * @param commandId String that specifies a command identifier. + */ + queryCommandValue(commandId: string): string; + /** @deprecated */ + releaseEvents(): void; + /** + * Writes one or more HTML expressions to a document in the specified window. + * @param content Specifies the text and HTML tags to write. + */ + write(...text: string[]): void; + /** + * Writes one or more HTML expressions, followed by a carriage return, to a document in the specified window. + * @param content The text and HTML tags to write. + */ + writeln(...text: string[]): void; + /** + * Returns an object representing the current selection of the document that is loaded into the object displaying a webpage. + */ + addEventListener(type: K, listener: (this: Document, ev: DocumentEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: Document, ev: DocumentEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var Document: { + prototype: Document; + new(): Document; +}; + +interface DocumentAndElementEventHandlersEventMap { + "copy": ClipboardEvent; + "cut": ClipboardEvent; + "paste": ClipboardEvent; +} + +interface DocumentAndElementEventHandlers { + oncopy: ((this: DocumentAndElementEventHandlers, ev: ClipboardEvent) => any) | null; + oncut: ((this: DocumentAndElementEventHandlers, ev: ClipboardEvent) => any) | null; + onpaste: ((this: DocumentAndElementEventHandlers, ev: ClipboardEvent) => any) | null; + addEventListener(type: K, listener: (this: DocumentAndElementEventHandlers, ev: DocumentAndElementEventHandlersEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: DocumentAndElementEventHandlers, ev: DocumentAndElementEventHandlersEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +interface DocumentEvent { + createEvent(eventInterface: "AnimationEvent"): AnimationEvent; + createEvent(eventInterface: "AnimationPlaybackEvent"): AnimationPlaybackEvent; + createEvent(eventInterface: "AudioProcessingEvent"): AudioProcessingEvent; + createEvent(eventInterface: "BeforeUnloadEvent"): BeforeUnloadEvent; + createEvent(eventInterface: "ClipboardEvent"): ClipboardEvent; + createEvent(eventInterface: "CloseEvent"): CloseEvent; + createEvent(eventInterface: "CompositionEvent"): CompositionEvent; + createEvent(eventInterface: "CustomEvent"): CustomEvent; + createEvent(eventInterface: "DeviceLightEvent"): DeviceLightEvent; + createEvent(eventInterface: "DeviceMotionEvent"): DeviceMotionEvent; + createEvent(eventInterface: "DeviceOrientationEvent"): DeviceOrientationEvent; + createEvent(eventInterface: "DragEvent"): DragEvent; + createEvent(eventInterface: "ErrorEvent"): ErrorEvent; + createEvent(eventInterface: "Event"): Event; + createEvent(eventInterface: "Events"): Event; + createEvent(eventInterface: "FocusEvent"): FocusEvent; + createEvent(eventInterface: "FocusNavigationEvent"): FocusNavigationEvent; + createEvent(eventInterface: "GamepadEvent"): GamepadEvent; + createEvent(eventInterface: "HashChangeEvent"): HashChangeEvent; + createEvent(eventInterface: "IDBVersionChangeEvent"): IDBVersionChangeEvent; + createEvent(eventInterface: "KeyboardEvent"): KeyboardEvent; + createEvent(eventInterface: "ListeningStateChangedEvent"): ListeningStateChangedEvent; + createEvent(eventInterface: "MSGestureEvent"): MSGestureEvent; + createEvent(eventInterface: "MSMediaKeyMessageEvent"): MSMediaKeyMessageEvent; + createEvent(eventInterface: "MSMediaKeyNeededEvent"): MSMediaKeyNeededEvent; + createEvent(eventInterface: "MSPointerEvent"): MSPointerEvent; + createEvent(eventInterface: "MediaEncryptedEvent"): MediaEncryptedEvent; + createEvent(eventInterface: "MediaKeyMessageEvent"): MediaKeyMessageEvent; + createEvent(eventInterface: "MediaQueryListEvent"): MediaQueryListEvent; + createEvent(eventInterface: "MediaStreamErrorEvent"): MediaStreamErrorEvent; + createEvent(eventInterface: "MediaStreamEvent"): MediaStreamEvent; + createEvent(eventInterface: "MediaStreamTrackEvent"): MediaStreamTrackEvent; + createEvent(eventInterface: "MessageEvent"): MessageEvent; + createEvent(eventInterface: "MouseEvent"): MouseEvent; + createEvent(eventInterface: "MouseEvents"): MouseEvent; + createEvent(eventInterface: "MutationEvent"): MutationEvent; + createEvent(eventInterface: "MutationEvents"): MutationEvent; + createEvent(eventInterface: "OfflineAudioCompletionEvent"): OfflineAudioCompletionEvent; + createEvent(eventInterface: "OverflowEvent"): OverflowEvent; + createEvent(eventInterface: "PageTransitionEvent"): PageTransitionEvent; + createEvent(eventInterface: "PaymentRequestUpdateEvent"): PaymentRequestUpdateEvent; + createEvent(eventInterface: "PermissionRequestedEvent"): PermissionRequestedEvent; + createEvent(eventInterface: "PointerEvent"): PointerEvent; + createEvent(eventInterface: "PopStateEvent"): PopStateEvent; + createEvent(eventInterface: "ProgressEvent"): ProgressEvent; + createEvent(eventInterface: "PromiseRejectionEvent"): PromiseRejectionEvent; + createEvent(eventInterface: "RTCDTMFToneChangeEvent"): RTCDTMFToneChangeEvent; + createEvent(eventInterface: "RTCDataChannelEvent"): RTCDataChannelEvent; + createEvent(eventInterface: "RTCDtlsTransportStateChangedEvent"): RTCDtlsTransportStateChangedEvent; + createEvent(eventInterface: "RTCErrorEvent"): RTCErrorEvent; + createEvent(eventInterface: "RTCIceCandidatePairChangedEvent"): RTCIceCandidatePairChangedEvent; + createEvent(eventInterface: "RTCIceGathererEvent"): RTCIceGathererEvent; + createEvent(eventInterface: "RTCIceTransportStateChangedEvent"): RTCIceTransportStateChangedEvent; + createEvent(eventInterface: "RTCPeerConnectionIceErrorEvent"): RTCPeerConnectionIceErrorEvent; + createEvent(eventInterface: "RTCPeerConnectionIceEvent"): RTCPeerConnectionIceEvent; + createEvent(eventInterface: "RTCSsrcConflictEvent"): RTCSsrcConflictEvent; + createEvent(eventInterface: "RTCStatsEvent"): RTCStatsEvent; + createEvent(eventInterface: "RTCTrackEvent"): RTCTrackEvent; + createEvent(eventInterface: "SVGZoomEvent"): SVGZoomEvent; + createEvent(eventInterface: "SVGZoomEvents"): SVGZoomEvent; + createEvent(eventInterface: "SecurityPolicyViolationEvent"): SecurityPolicyViolationEvent; + createEvent(eventInterface: "ServiceWorkerMessageEvent"): ServiceWorkerMessageEvent; + createEvent(eventInterface: "SpeechRecognitionError"): SpeechRecognitionError; + createEvent(eventInterface: "SpeechRecognitionEvent"): SpeechRecognitionEvent; + createEvent(eventInterface: "SpeechSynthesisErrorEvent"): SpeechSynthesisErrorEvent; + createEvent(eventInterface: "SpeechSynthesisEvent"): SpeechSynthesisEvent; + createEvent(eventInterface: "StorageEvent"): StorageEvent; + createEvent(eventInterface: "TextEvent"): TextEvent; + createEvent(eventInterface: "TouchEvent"): TouchEvent; + createEvent(eventInterface: "TrackEvent"): TrackEvent; + createEvent(eventInterface: "TransitionEvent"): TransitionEvent; + createEvent(eventInterface: "UIEvent"): UIEvent; + createEvent(eventInterface: "UIEvents"): UIEvent; + createEvent(eventInterface: "VRDisplayEvent"): VRDisplayEvent; + createEvent(eventInterface: "VRDisplayEvent "): VRDisplayEvent ; + createEvent(eventInterface: "WebGLContextEvent"): WebGLContextEvent; + createEvent(eventInterface: "WheelEvent"): WheelEvent; + createEvent(eventInterface: string): Event; +} + +interface DocumentFragment extends Node, NonElementParentNode, ParentNode { + getElementById(elementId: string): HTMLElement | null; +} + +declare var DocumentFragment: { + prototype: DocumentFragment; + new(): DocumentFragment; +}; + +interface DocumentOrShadowRoot { + readonly activeElement: Element | null; + /** + * Retrieves a collection of styleSheet objects representing the style sheets that correspond to each instance of a link or style object in the document. + */ + readonly styleSheets: StyleSheetList; + caretPositionFromPoint(x: number, y: number): CaretPosition | null; + /** @deprecated */ + caretRangeFromPoint(x: number, y: number): Range; + elementFromPoint(x: number, y: number): Element | null; + elementsFromPoint(x: number, y: number): Element[]; + getSelection(): Selection | null; +} + +interface DocumentTimeline extends AnimationTimeline { +} + +declare var DocumentTimeline: { + prototype: DocumentTimeline; + new(options?: DocumentTimelineOptions): DocumentTimeline; +}; + +interface DocumentType extends Node, ChildNode { + readonly name: string; + readonly publicId: string; + readonly systemId: string; +} + +declare var DocumentType: { + prototype: DocumentType; + new(): DocumentType; +}; + +interface DragEvent extends MouseEvent { + /** + * Returns the DataTransfer object for the event. + */ + readonly dataTransfer: DataTransfer | null; +} + +declare var DragEvent: { + prototype: DragEvent; + new(type: string, eventInitDict?: DragEventInit): DragEvent; +}; + +interface DynamicsCompressorNode extends AudioNode { + readonly attack: AudioParam; + readonly knee: AudioParam; + readonly ratio: AudioParam; + readonly reduction: number; + readonly release: AudioParam; + readonly threshold: AudioParam; +} + +declare var DynamicsCompressorNode: { + prototype: DynamicsCompressorNode; + new(context: BaseAudioContext, options?: DynamicsCompressorOptions): DynamicsCompressorNode; +}; + +interface EXT_blend_minmax { + readonly MAX_EXT: GLenum; + readonly MIN_EXT: GLenum; +} + +interface EXT_frag_depth { +} + +interface EXT_sRGB { + readonly FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING_EXT: GLenum; + readonly SRGB8_ALPHA8_EXT: GLenum; + readonly SRGB_ALPHA_EXT: GLenum; + readonly SRGB_EXT: GLenum; +} + +interface EXT_shader_texture_lod { +} + +interface EXT_texture_filter_anisotropic { + readonly MAX_TEXTURE_MAX_ANISOTROPY_EXT: GLenum; + readonly TEXTURE_MAX_ANISOTROPY_EXT: GLenum; +} + +interface ElementEventMap { + "fullscreenchange": Event; + "fullscreenerror": Event; +} + +interface Element extends Node, ParentNode, NonDocumentTypeChildNode, ChildNode, Slotable, Animatable { + readonly assignedSlot: HTMLSlotElement | null; + readonly attributes: NamedNodeMap; + /** + * Allows for manipulation of element's class content attribute as a + * set of whitespace-separated tokens through a DOMTokenList object. + */ + readonly classList: DOMTokenList; + /** + * Returns the value of element's class content attribute. Can be set + * to change it. + */ + className: string; + readonly clientHeight: number; + readonly clientLeft: number; + readonly clientTop: number; + readonly clientWidth: number; + /** + * Returns the value of element's id content attribute. Can be set to + * change it. + */ + id: string; + innerHTML: string; + /** + * Returns the local name. + */ + readonly localName: string; + /** + * Returns the namespace. + */ + readonly namespaceURI: string | null; + onfullscreenchange: ((this: Element, ev: Event) => any) | null; + onfullscreenerror: ((this: Element, ev: Event) => any) | null; + outerHTML: string; + /** + * Returns the namespace prefix. + */ + readonly prefix: string | null; + readonly scrollHeight: number; + scrollLeft: number; + scrollTop: number; + readonly scrollWidth: number; + /** + * Returns element's shadow root, if any, and if shadow root's mode is "open", and null otherwise. + */ + readonly shadowRoot: ShadowRoot | null; + /** + * Returns the value of element's slot content attribute. Can be set to + * change it. + */ + slot: string; + /** + * Returns the HTML-uppercased qualified name. + */ + readonly tagName: string; + /** + * Creates a shadow root for element and returns it. + */ + attachShadow(shadowRootInitDict: ShadowRootInit): ShadowRoot; + /** + * Returns the first (starting at element) inclusive ancestor that matches selectors, and null otherwise. + */ + closest(selector: K): HTMLElementTagNameMap[K] | null; + closest(selector: K): SVGElementTagNameMap[K] | null; + closest(selector: string): Element | null; + /** + * Returns element's first attribute whose qualified name is qualifiedName, and null if there is no such attribute otherwise. + */ + getAttribute(qualifiedName: string): string | null; + /** + * Returns element's attribute whose namespace is namespace and local name is localName, and null if there is + * no such attribute otherwise. + */ + getAttributeNS(namespace: string | null, localName: string): string | null; + /** + * Returns the qualified names of all element's attributes. + * Can contain duplicates. + */ + getAttributeNames(): string[]; + getAttributeNode(name: string): Attr | null; + getAttributeNodeNS(namespaceURI: string, localName: string): Attr | null; + getBoundingClientRect(): ClientRect | DOMRect; + getClientRects(): ClientRectList | DOMRectList; + getElementsByClassName(classNames: string): HTMLCollectionOf; + getElementsByTagName(qualifiedName: K): HTMLCollectionOf; + getElementsByTagName(qualifiedName: K): HTMLCollectionOf; + getElementsByTagName(qualifiedName: string): HTMLCollectionOf; + getElementsByTagNameNS(namespaceURI: "http://www.w3.org/1999/xhtml", localName: string): HTMLCollectionOf; + getElementsByTagNameNS(namespaceURI: "http://www.w3.org/2000/svg", localName: string): HTMLCollectionOf; + getElementsByTagNameNS(namespaceURI: string, localName: string): HTMLCollectionOf; + /** + * Returns true if element has an attribute whose qualified name is qualifiedName, and false otherwise. + */ + hasAttribute(qualifiedName: string): boolean; + /** + * Returns true if element has an attribute whose namespace is namespace and local name is localName. + */ + hasAttributeNS(namespace: string | null, localName: string): boolean; + /** + * Returns true if element has attributes, and false otherwise. + */ + hasAttributes(): boolean; + hasPointerCapture(pointerId: number): boolean; + insertAdjacentElement(position: InsertPosition, insertedElement: Element): Element | null; + insertAdjacentHTML(where: InsertPosition, html: string): void; + insertAdjacentText(where: InsertPosition, text: string): void; + /** + * Returns true if matching selectors against element's root yields element, and false otherwise. + */ + matches(selectors: string): boolean; + msGetRegionContent(): any; + releasePointerCapture(pointerId: number): void; + /** + * Removes element's first attribute whose qualified name is qualifiedName. + */ + removeAttribute(qualifiedName: string): void; + /** + * Removes element's attribute whose namespace is namespace and local name is localName. + */ + removeAttributeNS(namespace: string | null, localName: string): void; + removeAttributeNode(attr: Attr): Attr; + /** + * Displays element fullscreen and resolves promise when done. + */ + requestFullscreen(): Promise; + scroll(options?: ScrollToOptions): void; + scroll(x: number, y: number): void; + scrollBy(options?: ScrollToOptions): void; + scrollBy(x: number, y: number): void; + scrollIntoView(arg?: boolean | ScrollIntoViewOptions): void; + scrollTo(options?: ScrollToOptions): void; + scrollTo(x: number, y: number): void; + /** + * Sets the value of element's first attribute whose qualified name is qualifiedName to value. + */ + setAttribute(qualifiedName: string, value: string): void; + /** + * Sets the value of element's attribute whose namespace is namespace and local name is localName to value. + */ + setAttributeNS(namespace: string | null, qualifiedName: string, value: string): void; + setAttributeNode(attr: Attr): Attr | null; + setAttributeNodeNS(attr: Attr): Attr | null; + setPointerCapture(pointerId: number): void; + /** + * If force is not given, "toggles" qualifiedName, removing it if it is + * present and adding it if it is not present. If force is true, adds qualifiedName. If force is false, removes qualifiedName. + * Returns true if qualifiedName is now present, and false otherwise. + */ + toggleAttribute(qualifiedName: string, force?: boolean): boolean; + webkitMatchesSelector(selectors: string): boolean; + addEventListener(type: K, listener: (this: Element, ev: ElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: Element, ev: ElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var Element: { + prototype: Element; + new(): Element; +}; + +interface ElementCSSInlineStyle { + readonly style: CSSStyleDeclaration; +} + +interface ElementContentEditable { + contentEditable: string; + inputMode: string; + readonly isContentEditable: boolean; +} + +interface ElementCreationOptions { + is?: string; +} + +interface ErrorEvent extends Event { + readonly colno: number; + readonly error: any; + readonly filename: string; + readonly lineno: number; + readonly message: string; +} + +declare var ErrorEvent: { + prototype: ErrorEvent; + new(type: string, eventInitDict?: ErrorEventInit): ErrorEvent; +}; + +interface Event { + /** + * Returns true or false depending on how event was initialized. True if event goes through its target's ancestors in reverse tree order, and false otherwise. + */ + readonly bubbles: boolean; + cancelBubble: boolean; + readonly cancelable: boolean; + /** + * Returns true or false depending on how event was initialized. True if event invokes listeners past a ShadowRoot node that is the root of its target, and false otherwise. + */ + readonly composed: boolean; + /** + * Returns the object whose event listener's callback is currently being + * invoked. + */ + readonly currentTarget: EventTarget | null; + readonly defaultPrevented: boolean; + readonly eventPhase: number; + /** + * Returns true if event was dispatched by the user agent, and + * false otherwise. + */ + readonly isTrusted: boolean; + returnValue: boolean; + /** @deprecated */ + readonly srcElement: Element | null; + /** + * Returns the object to which event is dispatched (its target). + */ + readonly target: EventTarget | null; + /** + * Returns the event's timestamp as the number of milliseconds measured relative to + * the time origin. + */ + readonly timeStamp: number; + /** + * Returns the type of event, e.g. + * "click", "hashchange", or + * "submit". + */ + readonly type: string; + composedPath(): EventTarget[]; + initEvent(type: string, bubbles?: boolean, cancelable?: boolean): void; + preventDefault(): void; + /** + * Invoking this method prevents event from reaching + * any registered event listeners after the current one finishes running and, when dispatched in a tree, also prevents event from reaching any + * other objects. + */ + stopImmediatePropagation(): void; + /** + * When dispatched in a tree, invoking this method prevents event from reaching any objects other than the current object. + */ + stopPropagation(): void; + readonly AT_TARGET: number; + readonly BUBBLING_PHASE: number; + readonly CAPTURING_PHASE: number; + readonly NONE: number; +} + +declare var Event: { + prototype: Event; + new(type: string, eventInitDict?: EventInit): Event; + readonly AT_TARGET: number; + readonly BUBBLING_PHASE: number; + readonly CAPTURING_PHASE: number; + readonly NONE: number; +}; + +interface EventListenerObject { + handleEvent(evt: Event): void; +} + +interface EventSource extends EventTarget { + readonly CLOSED: number; + readonly CONNECTING: number; + readonly OPEN: number; + onerror: (evt: MessageEvent) => any; + onmessage: (evt: MessageEvent) => any; + onopen: (evt: MessageEvent) => any; + readonly readyState: number; + readonly url: string; + readonly withCredentials: boolean; + close(): void; +} + +declare var EventSource: { + prototype: EventSource; + new(url: string, eventSourceInitDict?: EventSourceInit): EventSource; +}; + +interface EventSourceInit { + readonly withCredentials: boolean; +} + +interface EventTarget { + /** + * Appends an event listener for events whose type attribute value is type. The callback argument sets the callback that will be invoked when the event is dispatched. + * The options argument sets listener-specific options. For compatibility this can be a + * boolean, in which case the method behaves exactly as if the value was specified as options's capture. + * When set to true, options's capture prevents callback from being invoked when the event's eventPhase attribute value is BUBBLING_PHASE. When false (or not present), callback will not be invoked when event's eventPhase attribute value is CAPTURING_PHASE. Either way, callback will be invoked if event's eventPhase attribute value is AT_TARGET. + * When set to true, options's passive indicates that the callback will not cancel the event by invoking preventDefault(). This is used to enable performance optimizations described in §2.8 Observing event listeners. + * When set to true, options's once indicates that the callback will only be invoked once after which the event listener will + * be removed. + * The event listener is appended to target's event listener list and is not appended if it has the same type, callback, and capture. + */ + addEventListener(type: string, listener: EventListenerOrEventListenerObject | null, options?: boolean | AddEventListenerOptions): void; + /** + * Dispatches a synthetic event event to target and returns true + * if either event's cancelable attribute value is false or its preventDefault() method was not invoked, and false otherwise. + */ + dispatchEvent(event: Event): boolean; + /** + * Removes the event listener in target's event listener list with the same type, callback, and options. + */ + removeEventListener(type: string, callback: EventListenerOrEventListenerObject | null, options?: EventListenerOptions | boolean): void; +} + +declare var EventTarget: { + prototype: EventTarget; + new(): EventTarget; +}; + +interface ExtensionScriptApis { + extensionIdToShortId(extensionId: string): number; + fireExtensionApiTelemetry(functionName: string, isSucceeded: boolean, isSupported: boolean, errorString: string): void; + genericFunction(routerAddress: any, parameters?: string, callbackId?: number): void; + genericSynchronousFunction(functionId: number, parameters?: string): string; + genericWebRuntimeCallout(to: any, from: any, payload: string): void; + getExtensionId(): string; + registerGenericFunctionCallbackHandler(callbackHandler: Function): void; + registerGenericPersistentCallbackHandler(callbackHandler: Function): void; + registerWebRuntimeCallbackHandler(handler: Function): any; +} + +declare var ExtensionScriptApis: { + prototype: ExtensionScriptApis; + new(): ExtensionScriptApis; +}; + +interface External { + /** @deprecated */ + AddSearchProvider(): void; + /** @deprecated */ + IsSearchProviderInstalled(): void; +} + +interface File extends Blob { + readonly lastModified: number; + readonly name: string; +} + +declare var File: { + prototype: File; + new(fileBits: BlobPart[], fileName: string, options?: FilePropertyBag): File; +}; + +interface FileList { + readonly length: number; + item(index: number): File | null; + [index: number]: File; +} + +declare var FileList: { + prototype: FileList; + new(): FileList; +}; + +interface FileReaderEventMap { + "abort": ProgressEvent; + "error": ProgressEvent; + "load": ProgressEvent; + "loadend": ProgressEvent; + "loadstart": ProgressEvent; + "progress": ProgressEvent; +} + +interface FileReader extends EventTarget { + readonly error: DOMException | null; + onabort: ((this: FileReader, ev: ProgressEvent) => any) | null; + onerror: ((this: FileReader, ev: ProgressEvent) => any) | null; + onload: ((this: FileReader, ev: ProgressEvent) => any) | null; + onloadend: ((this: FileReader, ev: ProgressEvent) => any) | null; + onloadstart: ((this: FileReader, ev: ProgressEvent) => any) | null; + onprogress: ((this: FileReader, ev: ProgressEvent) => any) | null; + readonly readyState: number; + readonly result: string | ArrayBuffer | null; + abort(): void; + readAsArrayBuffer(blob: Blob): void; + readAsBinaryString(blob: Blob): void; + readAsDataURL(blob: Blob): void; + readAsText(blob: Blob, encoding?: string): void; + readonly DONE: number; + readonly EMPTY: number; + readonly LOADING: number; + addEventListener(type: K, listener: (this: FileReader, ev: FileReaderEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: FileReader, ev: FileReaderEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var FileReader: { + prototype: FileReader; + new(): FileReader; + readonly DONE: number; + readonly EMPTY: number; + readonly LOADING: number; +}; + +interface FocusEvent extends UIEvent { + readonly relatedTarget: EventTarget; + initFocusEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, relatedTargetArg: EventTarget): void; +} + +declare var FocusEvent: { + prototype: FocusEvent; + new(typeArg: string, eventInitDict?: FocusEventInit): FocusEvent; +}; + +interface FocusNavigationEvent extends Event { + readonly navigationReason: NavigationReason; + readonly originHeight: number; + readonly originLeft: number; + readonly originTop: number; + readonly originWidth: number; + requestFocus(): void; +} + +declare var FocusNavigationEvent: { + prototype: FocusNavigationEvent; + new(type: string, eventInitDict?: FocusNavigationEventInit): FocusNavigationEvent; +}; + +interface FormData { + append(name: string, value: string | Blob, fileName?: string): void; + delete(name: string): void; + get(name: string): FormDataEntryValue | null; + getAll(name: string): FormDataEntryValue[]; + has(name: string): boolean; + set(name: string, value: string | Blob, fileName?: string): void; + forEach(callbackfn: (value: FormDataEntryValue, key: string, parent: FormData) => void, thisArg?: any): void; +} + +declare var FormData: { + prototype: FormData; + new(form?: HTMLFormElement): FormData; +}; + +interface GainNode extends AudioNode { + readonly gain: AudioParam; +} + +declare var GainNode: { + prototype: GainNode; + new(context: BaseAudioContext, options?: GainOptions): GainNode; +}; + +interface Gamepad { + readonly axes: number[]; + readonly buttons: GamepadButton[]; + readonly connected: boolean; + readonly displayId: number; + readonly hand: GamepadHand; + readonly hapticActuators: GamepadHapticActuator[]; + readonly id: string; + readonly index: number; + readonly mapping: GamepadMappingType; + readonly pose: GamepadPose | null; + readonly timestamp: number; +} + +declare var Gamepad: { + prototype: Gamepad; + new(): Gamepad; +}; + +interface GamepadButton { + readonly pressed: boolean; + readonly touched: boolean; + readonly value: number; +} + +declare var GamepadButton: { + prototype: GamepadButton; + new(): GamepadButton; +}; + +interface GamepadEvent extends Event { + readonly gamepad: Gamepad; +} + +declare var GamepadEvent: { + prototype: GamepadEvent; + new(typeArg: string, eventInitDict?: GamepadEventInit): GamepadEvent; +}; + +interface GamepadHapticActuator { + readonly type: GamepadHapticActuatorType; + pulse(value: number, duration: number): Promise; +} + +declare var GamepadHapticActuator: { + prototype: GamepadHapticActuator; + new(): GamepadHapticActuator; +}; + +interface GamepadPose { + readonly angularAcceleration: Float32Array | null; + readonly angularVelocity: Float32Array | null; + readonly hasOrientation: boolean; + readonly hasPosition: boolean; + readonly linearAcceleration: Float32Array | null; + readonly linearVelocity: Float32Array | null; + readonly orientation: Float32Array | null; + readonly position: Float32Array | null; +} + +declare var GamepadPose: { + prototype: GamepadPose; + new(): GamepadPose; +}; + +interface Geolocation { + clearWatch(watchId: number): void; + getCurrentPosition(successCallback: PositionCallback, errorCallback?: PositionErrorCallback, options?: PositionOptions): void; + watchPosition(successCallback: PositionCallback, errorCallback?: PositionErrorCallback, options?: PositionOptions): number; +} + +interface GetSVGDocument { + getSVGDocument(): Document; +} + +interface GlobalEventHandlersEventMap { + "abort": UIEvent; + "animationcancel": AnimationEvent; + "animationend": AnimationEvent; + "animationiteration": AnimationEvent; + "animationstart": AnimationEvent; + "auxclick": Event; + "blur": FocusEvent; + "cancel": Event; + "canplay": Event; + "canplaythrough": Event; + "change": Event; + "click": MouseEvent; + "close": Event; + "contextmenu": MouseEvent; + "cuechange": Event; + "dblclick": MouseEvent; + "drag": DragEvent; + "dragend": DragEvent; + "dragenter": DragEvent; + "dragexit": Event; + "dragleave": DragEvent; + "dragover": DragEvent; + "dragstart": DragEvent; + "drop": DragEvent; + "durationchange": Event; + "emptied": Event; + "ended": Event; + "error": ErrorEvent; + "focus": FocusEvent; + "gotpointercapture": PointerEvent; + "input": Event; + "invalid": Event; + "keydown": KeyboardEvent; + "keypress": KeyboardEvent; + "keyup": KeyboardEvent; + "load": Event; + "loadeddata": Event; + "loadedmetadata": Event; + "loadend": ProgressEvent; + "loadstart": Event; + "lostpointercapture": PointerEvent; + "mousedown": MouseEvent; + "mouseenter": MouseEvent; + "mouseleave": MouseEvent; + "mousemove": MouseEvent; + "mouseout": MouseEvent; + "mouseover": MouseEvent; + "mouseup": MouseEvent; + "pause": Event; + "play": Event; + "playing": Event; + "pointercancel": PointerEvent; + "pointerdown": PointerEvent; + "pointerenter": PointerEvent; + "pointerleave": PointerEvent; + "pointermove": PointerEvent; + "pointerout": PointerEvent; + "pointerover": PointerEvent; + "pointerup": PointerEvent; + "progress": ProgressEvent; + "ratechange": Event; + "reset": Event; + "resize": UIEvent; + "scroll": UIEvent; + "securitypolicyviolation": SecurityPolicyViolationEvent; + "seeked": Event; + "seeking": Event; + "select": UIEvent; + "stalled": Event; + "submit": Event; + "suspend": Event; + "timeupdate": Event; + "toggle": Event; + "touchcancel": TouchEvent; + "touchend": TouchEvent; + "touchmove": TouchEvent; + "touchstart": TouchEvent; + "transitioncancel": TransitionEvent; + "transitionend": TransitionEvent; + "transitionrun": TransitionEvent; + "transitionstart": TransitionEvent; + "volumechange": Event; + "waiting": Event; + "wheel": WheelEvent; +} + +interface GlobalEventHandlers { + /** + * Fires when the user aborts the download. + * @param ev The event. + */ + onabort: ((this: GlobalEventHandlers, ev: UIEvent) => any) | null; + onanimationcancel: ((this: GlobalEventHandlers, ev: AnimationEvent) => any) | null; + onanimationend: ((this: GlobalEventHandlers, ev: AnimationEvent) => any) | null; + onanimationiteration: ((this: GlobalEventHandlers, ev: AnimationEvent) => any) | null; + onanimationstart: ((this: GlobalEventHandlers, ev: AnimationEvent) => any) | null; + onauxclick: ((this: GlobalEventHandlers, ev: Event) => any) | null; + /** + * Fires when the object loses the input focus. + * @param ev The focus event. + */ + onblur: ((this: GlobalEventHandlers, ev: FocusEvent) => any) | null; + oncancel: ((this: GlobalEventHandlers, ev: Event) => any) | null; + /** + * Occurs when playback is possible, but would require further buffering. + * @param ev The event. + */ + oncanplay: ((this: GlobalEventHandlers, ev: Event) => any) | null; + oncanplaythrough: ((this: GlobalEventHandlers, ev: Event) => any) | null; + /** + * Fires when the contents of the object or selection have changed. + * @param ev The event. + */ + onchange: ((this: GlobalEventHandlers, ev: Event) => any) | null; + /** + * Fires when the user clicks the left mouse button on the object + * @param ev The mouse event. + */ + onclick: ((this: GlobalEventHandlers, ev: MouseEvent) => any) | null; + onclose: ((this: GlobalEventHandlers, ev: Event) => any) | null; + /** + * Fires when the user clicks the right mouse button in the client area, opening the context menu. + * @param ev The mouse event. + */ + oncontextmenu: ((this: GlobalEventHandlers, ev: MouseEvent) => any) | null; + oncuechange: ((this: GlobalEventHandlers, ev: Event) => any) | null; + /** + * Fires when the user double-clicks the object. + * @param ev The mouse event. + */ + ondblclick: ((this: GlobalEventHandlers, ev: MouseEvent) => any) | null; + /** + * Fires on the source object continuously during a drag operation. + * @param ev The event. + */ + ondrag: ((this: GlobalEventHandlers, ev: DragEvent) => any) | null; + /** + * Fires on the source object when the user releases the mouse at the close of a drag operation. + * @param ev The event. + */ + ondragend: ((this: GlobalEventHandlers, ev: DragEvent) => any) | null; + /** + * Fires on the target element when the user drags the object to a valid drop target. + * @param ev The drag event. + */ + ondragenter: ((this: GlobalEventHandlers, ev: DragEvent) => any) | null; + ondragexit: ((this: GlobalEventHandlers, ev: Event) => any) | null; + /** + * Fires on the target object when the user moves the mouse out of a valid drop target during a drag operation. + * @param ev The drag event. + */ + ondragleave: ((this: GlobalEventHandlers, ev: DragEvent) => any) | null; + /** + * Fires on the target element continuously while the user drags the object over a valid drop target. + * @param ev The event. + */ + ondragover: ((this: GlobalEventHandlers, ev: DragEvent) => any) | null; + /** + * Fires on the source object when the user starts to drag a text selection or selected object. + * @param ev The event. + */ + ondragstart: ((this: GlobalEventHandlers, ev: DragEvent) => any) | null; + ondrop: ((this: GlobalEventHandlers, ev: DragEvent) => any) | null; + /** + * Occurs when the duration attribute is updated. + * @param ev The event. + */ + ondurationchange: ((this: GlobalEventHandlers, ev: Event) => any) | null; + /** + * Occurs when the media element is reset to its initial state. + * @param ev The event. + */ + onemptied: ((this: GlobalEventHandlers, ev: Event) => any) | null; + /** + * Occurs when the end of playback is reached. + * @param ev The event + */ + onended: ((this: GlobalEventHandlers, ev: Event) => any) | null; + /** + * Fires when an error occurs during object loading. + * @param ev The event. + */ + onerror: ErrorEventHandler; + /** + * Fires when the object receives focus. + * @param ev The event. + */ + onfocus: ((this: GlobalEventHandlers, ev: FocusEvent) => any) | null; + ongotpointercapture: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null; + oninput: ((this: GlobalEventHandlers, ev: Event) => any) | null; + oninvalid: ((this: GlobalEventHandlers, ev: Event) => any) | null; + /** + * Fires when the user presses a key. + * @param ev The keyboard event + */ + onkeydown: ((this: GlobalEventHandlers, ev: KeyboardEvent) => any) | null; + /** + * Fires when the user presses an alphanumeric key. + * @param ev The event. + */ + onkeypress: ((this: GlobalEventHandlers, ev: KeyboardEvent) => any) | null; + /** + * Fires when the user releases a key. + * @param ev The keyboard event + */ + onkeyup: ((this: GlobalEventHandlers, ev: KeyboardEvent) => any) | null; + /** + * Fires immediately after the browser loads the object. + * @param ev The event. + */ + onload: ((this: GlobalEventHandlers, ev: Event) => any) | null; + /** + * Occurs when media data is loaded at the current playback position. + * @param ev The event. + */ + onloadeddata: ((this: GlobalEventHandlers, ev: Event) => any) | null; + /** + * Occurs when the duration and dimensions of the media have been determined. + * @param ev The event. + */ + onloadedmetadata: ((this: GlobalEventHandlers, ev: Event) => any) | null; + onloadend: ((this: GlobalEventHandlers, ev: ProgressEvent) => any) | null; + /** + * Occurs when Internet Explorer begins looking for media data. + * @param ev The event. + */ + onloadstart: ((this: GlobalEventHandlers, ev: Event) => any) | null; + onlostpointercapture: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null; + /** + * Fires when the user clicks the object with either mouse button. + * @param ev The mouse event. + */ + onmousedown: ((this: GlobalEventHandlers, ev: MouseEvent) => any) | null; + onmouseenter: ((this: GlobalEventHandlers, ev: MouseEvent) => any) | null; + onmouseleave: ((this: GlobalEventHandlers, ev: MouseEvent) => any) | null; + /** + * Fires when the user moves the mouse over the object. + * @param ev The mouse event. + */ + onmousemove: ((this: GlobalEventHandlers, ev: MouseEvent) => any) | null; + /** + * Fires when the user moves the mouse pointer outside the boundaries of the object. + * @param ev The mouse event. + */ + onmouseout: ((this: GlobalEventHandlers, ev: MouseEvent) => any) | null; + /** + * Fires when the user moves the mouse pointer into the object. + * @param ev The mouse event. + */ + onmouseover: ((this: GlobalEventHandlers, ev: MouseEvent) => any) | null; + /** + * Fires when the user releases a mouse button while the mouse is over the object. + * @param ev The mouse event. + */ + onmouseup: ((this: GlobalEventHandlers, ev: MouseEvent) => any) | null; + /** + * Occurs when playback is paused. + * @param ev The event. + */ + onpause: ((this: GlobalEventHandlers, ev: Event) => any) | null; + /** + * Occurs when the play method is requested. + * @param ev The event. + */ + onplay: ((this: GlobalEventHandlers, ev: Event) => any) | null; + /** + * Occurs when the audio or video has started playing. + * @param ev The event. + */ + onplaying: ((this: GlobalEventHandlers, ev: Event) => any) | null; + onpointercancel: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null; + onpointerdown: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null; + onpointerenter: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null; + onpointerleave: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null; + onpointermove: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null; + onpointerout: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null; + onpointerover: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null; + onpointerup: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null; + /** + * Occurs to indicate progress while downloading media data. + * @param ev The event. + */ + onprogress: ((this: GlobalEventHandlers, ev: ProgressEvent) => any) | null; + /** + * Occurs when the playback rate is increased or decreased. + * @param ev The event. + */ + onratechange: ((this: GlobalEventHandlers, ev: Event) => any) | null; + /** + * Fires when the user resets a form. + * @param ev The event. + */ + onreset: ((this: GlobalEventHandlers, ev: Event) => any) | null; + onresize: ((this: GlobalEventHandlers, ev: UIEvent) => any) | null; + /** + * Fires when the user repositions the scroll box in the scroll bar on the object. + * @param ev The event. + */ + onscroll: ((this: GlobalEventHandlers, ev: UIEvent) => any) | null; + onsecuritypolicyviolation: ((this: GlobalEventHandlers, ev: SecurityPolicyViolationEvent) => any) | null; + /** + * Occurs when the seek operation ends. + * @param ev The event. + */ + onseeked: ((this: GlobalEventHandlers, ev: Event) => any) | null; + /** + * Occurs when the current playback position is moved. + * @param ev The event. + */ + onseeking: ((this: GlobalEventHandlers, ev: Event) => any) | null; + /** + * Fires when the current selection changes. + * @param ev The event. + */ + onselect: ((this: GlobalEventHandlers, ev: UIEvent) => any) | null; + /** + * Occurs when the download has stopped. + * @param ev The event. + */ + onstalled: ((this: GlobalEventHandlers, ev: Event) => any) | null; + onsubmit: ((this: GlobalEventHandlers, ev: Event) => any) | null; + /** + * Occurs if the load operation has been intentionally halted. + * @param ev The event. + */ + onsuspend: ((this: GlobalEventHandlers, ev: Event) => any) | null; + /** + * Occurs to indicate the current playback position. + * @param ev The event. + */ + ontimeupdate: ((this: GlobalEventHandlers, ev: Event) => any) | null; + ontoggle: ((this: GlobalEventHandlers, ev: Event) => any) | null; + ontouchcancel: ((this: GlobalEventHandlers, ev: TouchEvent) => any) | null; + ontouchend: ((this: GlobalEventHandlers, ev: TouchEvent) => any) | null; + ontouchmove: ((this: GlobalEventHandlers, ev: TouchEvent) => any) | null; + ontouchstart: ((this: GlobalEventHandlers, ev: TouchEvent) => any) | null; + ontransitioncancel: ((this: GlobalEventHandlers, ev: TransitionEvent) => any) | null; + ontransitionend: ((this: GlobalEventHandlers, ev: TransitionEvent) => any) | null; + ontransitionrun: ((this: GlobalEventHandlers, ev: TransitionEvent) => any) | null; + ontransitionstart: ((this: GlobalEventHandlers, ev: TransitionEvent) => any) | null; + /** + * Occurs when the volume is changed, or playback is muted or unmuted. + * @param ev The event. + */ + onvolumechange: ((this: GlobalEventHandlers, ev: Event) => any) | null; + /** + * Occurs when playback stops because the next frame of a video resource is not available. + * @param ev The event. + */ + onwaiting: ((this: GlobalEventHandlers, ev: Event) => any) | null; + onwheel: ((this: GlobalEventHandlers, ev: WheelEvent) => any) | null; + addEventListener(type: K, listener: (this: GlobalEventHandlers, ev: GlobalEventHandlersEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: GlobalEventHandlers, ev: GlobalEventHandlersEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +interface GlobalFetch { + fetch(input: RequestInfo, init?: RequestInit): Promise; +} + +interface HTMLAllCollection { + /** + * Returns the number of elements in the collection. + */ + readonly length: number; + /** + * element = collection(index) + */ + item(nameOrIndex?: string): HTMLCollection | Element | null; + /** + * element = collection(name) + */ + namedItem(name: string): HTMLCollection | Element | null; + [index: number]: Element; +} + +declare var HTMLAllCollection: { + prototype: HTMLAllCollection; + new(): HTMLAllCollection; +}; + +interface HTMLAnchorElement extends HTMLElement, HTMLHyperlinkElementUtils { + /** + * Sets or retrieves the character set used to encode the object. + */ + /** @deprecated */ + charset: string; + /** + * Sets or retrieves the coordinates of the object. + */ + /** @deprecated */ + coords: string; + download: string; + /** + * Sets or retrieves the language code of the object. + */ + hreflang: string; + /** + * Sets or retrieves the shape of the object. + */ + /** @deprecated */ + name: string; + ping: string; + referrerPolicy: string; + /** + * Sets or retrieves the relationship between the object and the destination of the link. + */ + rel: string; + readonly relList: DOMTokenList; + /** + * Sets or retrieves the relationship between the object and the destination of the link. + */ + /** @deprecated */ + rev: string; + /** + * Sets or retrieves the shape of the object. + */ + /** @deprecated */ + shape: string; + /** + * Sets or retrieves the window or frame at which to target content. + */ + target: string; + /** + * Retrieves or sets the text of the object as a string. + */ + text: string; + type: string; + addEventListener(type: K, listener: (this: HTMLAnchorElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLAnchorElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLAnchorElement: { + prototype: HTMLAnchorElement; + new(): HTMLAnchorElement; +}; + +interface HTMLAppletElement extends HTMLElement { + /** @deprecated */ + align: string; + /** + * Sets or retrieves a text alternative to the graphic. + */ + /** @deprecated */ + alt: string; + /** + * Sets or retrieves a character string that can be used to implement your own archive functionality for the object. + */ + /** @deprecated */ + archive: string; + /** @deprecated */ + code: string; + /** + * Sets or retrieves the URL of the component. + */ + /** @deprecated */ + codeBase: string; + readonly form: HTMLFormElement | null; + /** + * Sets or retrieves the height of the object. + */ + /** @deprecated */ + height: string; + /** @deprecated */ + hspace: number; + /** + * Sets or retrieves the shape of the object. + */ + /** @deprecated */ + name: string; + /** @deprecated */ + object: string; + /** @deprecated */ + vspace: number; + /** @deprecated */ + width: string; + addEventListener(type: K, listener: (this: HTMLAppletElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLAppletElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLAppletElement: { + prototype: HTMLAppletElement; + new(): HTMLAppletElement; +}; + +interface HTMLAreaElement extends HTMLElement, HTMLHyperlinkElementUtils { + /** + * Sets or retrieves a text alternative to the graphic. + */ + alt: string; + /** + * Sets or retrieves the coordinates of the object. + */ + coords: string; + download: string; + /** + * Sets or gets whether clicks in this region cause action. + */ + /** @deprecated */ + noHref: boolean; + ping: string; + referrerPolicy: string; + rel: string; + readonly relList: DOMTokenList; + /** + * Sets or retrieves the shape of the object. + */ + shape: string; + /** + * Sets or retrieves the window or frame at which to target content. + */ + target: string; + addEventListener(type: K, listener: (this: HTMLAreaElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLAreaElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLAreaElement: { + prototype: HTMLAreaElement; + new(): HTMLAreaElement; +}; + +interface HTMLAudioElement extends HTMLMediaElement { + addEventListener(type: K, listener: (this: HTMLAudioElement, ev: HTMLMediaElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLAudioElement, ev: HTMLMediaElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLAudioElement: { + prototype: HTMLAudioElement; + new(): HTMLAudioElement; +}; + +interface HTMLBRElement extends HTMLElement { + /** + * Sets or retrieves the side on which floating objects are not to be positioned when any IHTMLBlockElement is inserted into the document. + */ + /** @deprecated */ + clear: string; + addEventListener(type: K, listener: (this: HTMLBRElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLBRElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLBRElement: { + prototype: HTMLBRElement; + new(): HTMLBRElement; +}; + +interface HTMLBaseElement extends HTMLElement { + /** + * Gets or sets the baseline URL on which relative links are based. + */ + href: string; + /** + * Sets or retrieves the window or frame at which to target content. + */ + target: string; + addEventListener(type: K, listener: (this: HTMLBaseElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLBaseElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLBaseElement: { + prototype: HTMLBaseElement; + new(): HTMLBaseElement; +}; + +interface HTMLBaseFontElement extends HTMLElement, DOML2DeprecatedColorProperty { + /** + * Sets or retrieves the current typeface family. + */ + /** @deprecated */ + face: string; + /** + * Sets or retrieves the font size of the object. + */ + /** @deprecated */ + size: number; + addEventListener(type: K, listener: (this: HTMLBaseFontElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLBaseFontElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLBaseFontElement: { + prototype: HTMLBaseFontElement; + new(): HTMLBaseFontElement; +}; + +interface HTMLBodyElementEventMap extends HTMLElementEventMap, WindowEventHandlersEventMap { + "orientationchange": Event; +} + +interface HTMLBodyElement extends HTMLElement, WindowEventHandlers { + /** @deprecated */ + aLink: string; + /** @deprecated */ + background: string; + /** @deprecated */ + bgColor: string; + bgProperties: string; + /** @deprecated */ + link: string; + /** @deprecated */ + noWrap: boolean; + /** @deprecated */ + onorientationchange: ((this: HTMLBodyElement, ev: Event) => any) | null; + /** @deprecated */ + text: string; + /** @deprecated */ + vLink: string; + addEventListener(type: K, listener: (this: HTMLBodyElement, ev: HTMLBodyElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLBodyElement, ev: HTMLBodyElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLBodyElement: { + prototype: HTMLBodyElement; + new(): HTMLBodyElement; +}; + +interface HTMLButtonElement extends HTMLElement { + /** + * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing. + */ + autofocus: boolean; + disabled: boolean; + /** + * Retrieves a reference to the form that the object is embedded in. + */ + readonly form: HTMLFormElement | null; + /** + * Overrides the action attribute (where the data on a form is sent) on the parent form element. + */ + formAction: string; + /** + * Used to override the encoding (formEnctype attribute) specified on the form element. + */ + formEnctype: string; + /** + * Overrides the submit method attribute previously specified on a form element. + */ + formMethod: string; + /** + * Overrides any validation or required attributes on a form or form elements to allow it to be submitted without validation. This can be used to create a "save draft"-type submit option. + */ + formNoValidate: boolean; + /** + * Overrides the target attribute on a form element. + */ + formTarget: string; + readonly labels: NodeListOf; + /** + * Sets or retrieves the name of the object. + */ + name: string; + /** + * Gets the classification and default behavior of the button. + */ + type: string; + /** + * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. + */ + readonly validationMessage: string; + /** + * Returns a ValidityState object that represents the validity states of an element. + */ + readonly validity: ValidityState; + /** + * Sets or retrieves the default or selected value of the control. + */ + value: string; + /** + * Returns whether an element will successfully validate based on forms validation rules and constraints. + */ + readonly willValidate: boolean; + /** + * Returns whether a form will validate when it is submitted, without having to submit it. + */ + checkValidity(): boolean; + reportValidity(): boolean; + /** + * Sets a custom error message that is displayed when a form is submitted. + * @param error Sets a custom error message that is displayed when a form is submitted. + */ + setCustomValidity(error: string): void; + addEventListener(type: K, listener: (this: HTMLButtonElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLButtonElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLButtonElement: { + prototype: HTMLButtonElement; + new(): HTMLButtonElement; +}; + +interface HTMLCanvasElement extends HTMLElement { + /** + * Gets or sets the height of a canvas element on a document. + */ + height: number; + /** + * Gets or sets the width of a canvas element on a document. + */ + width: number; + /** + * Returns an object that provides methods and properties for drawing and manipulating images and graphics on a canvas element in a document. A context object includes information about colors, line widths, fonts, and other graphic parameters that can be drawn on a canvas. + * @param contextId The identifier (ID) of the type of canvas to create. Internet Explorer 9 and Internet Explorer 10 support only a 2-D context using canvas.getContext("2d"); IE11 Preview also supports 3-D or WebGL context using canvas.getContext("experimental-webgl"); + */ + getContext(contextId: "2d", contextAttributes?: CanvasRenderingContext2DSettings): CanvasRenderingContext2D | null; + getContext(contextId: "webgl" | "experimental-webgl", contextAttributes?: WebGLContextAttributes): WebGLRenderingContext | null; + getContext(contextId: string, contextAttributes?: {}): CanvasRenderingContext2D | WebGLRenderingContext | null; + toBlob(callback: BlobCallback, type?: string, quality?: any): void; + /** + * Returns the content of the current canvas as an image that you can use as a source for another canvas or an HTML element. + * @param type The standard MIME type for the image format to return. If you do not specify this parameter, the default value is a PNG format image. + */ + toDataURL(type?: string, quality?: any): string; + addEventListener(type: K, listener: (this: HTMLCanvasElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLCanvasElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLCanvasElement: { + prototype: HTMLCanvasElement; + new(): HTMLCanvasElement; +}; + +interface HTMLCollectionBase { + /** + * Sets or retrieves the number of objects in a collection. + */ + readonly length: number; + /** + * Retrieves an object from various collections. + */ + item(index: number): Element | null; + [index: number]: Element; +} + +interface HTMLCollection extends HTMLCollectionBase { + /** + * Retrieves a select object or an object from an options collection. + */ + namedItem(name: string): Element | null; +} + +declare var HTMLCollection: { + prototype: HTMLCollection; + new(): HTMLCollection; +}; + +interface HTMLCollectionOf extends HTMLCollectionBase { + item(index: number): T | null; + namedItem(name: string): T | null; + [index: number]: T; +} + +interface HTMLDListElement extends HTMLElement { + /** @deprecated */ + compact: boolean; + addEventListener(type: K, listener: (this: HTMLDListElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLDListElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLDListElement: { + prototype: HTMLDListElement; + new(): HTMLDListElement; +}; + +interface HTMLDataElement extends HTMLElement { + value: string; + addEventListener(type: K, listener: (this: HTMLDataElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLDataElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLDataElement: { + prototype: HTMLDataElement; + new(): HTMLDataElement; +}; + +interface HTMLDataListElement extends HTMLElement { + readonly options: HTMLCollectionOf; + addEventListener(type: K, listener: (this: HTMLDataListElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLDataListElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLDataListElement: { + prototype: HTMLDataListElement; + new(): HTMLDataListElement; +}; + +interface HTMLDetailsElement extends HTMLElement { + open: boolean; + addEventListener(type: K, listener: (this: HTMLDetailsElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLDetailsElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLDetailsElement: { + prototype: HTMLDetailsElement; + new(): HTMLDetailsElement; +}; + +interface HTMLDialogElement extends HTMLElement { + open: boolean; + returnValue: string; + close(returnValue?: string): void; + show(): void; + showModal(): void; + addEventListener(type: K, listener: (this: HTMLDialogElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLDialogElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLDialogElement: { + prototype: HTMLDialogElement; + new(): HTMLDialogElement; +}; + +interface HTMLDirectoryElement extends HTMLElement { + /** @deprecated */ + compact: boolean; + addEventListener(type: K, listener: (this: HTMLDirectoryElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLDirectoryElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLDirectoryElement: { + prototype: HTMLDirectoryElement; + new(): HTMLDirectoryElement; +}; + +interface HTMLDivElement extends HTMLElement { + /** + * Sets or retrieves how the object is aligned with adjacent text. + */ + /** @deprecated */ + align: string; + addEventListener(type: K, listener: (this: HTMLDivElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLDivElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLDivElement: { + prototype: HTMLDivElement; + new(): HTMLDivElement; +}; + +interface HTMLDocument extends Document { + addEventListener(type: K, listener: (this: HTMLDocument, ev: DocumentEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLDocument, ev: DocumentEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLDocument: { + prototype: HTMLDocument; + new(): HTMLDocument; +}; + +interface HTMLElementEventMap extends ElementEventMap, GlobalEventHandlersEventMap, DocumentAndElementEventHandlersEventMap { +} + +interface HTMLElement extends Element, GlobalEventHandlers, DocumentAndElementEventHandlers, ElementContentEditable, HTMLOrSVGElement, ElementCSSInlineStyle { + accessKey: string; + readonly accessKeyLabel: string; + autocapitalize: string; + dir: string; + draggable: boolean; + hidden: boolean; + innerText: string; + lang: string; + readonly offsetHeight: number; + readonly offsetLeft: number; + readonly offsetParent: Element | null; + readonly offsetTop: number; + readonly offsetWidth: number; + spellcheck: boolean; + title: string; + translate: boolean; + click(): void; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLElement: { + prototype: HTMLElement; + new(): HTMLElement; +}; + +interface HTMLEmbedElement extends HTMLElement, GetSVGDocument { + /** @deprecated */ + align: string; + /** + * Sets or retrieves the height of the object. + */ + height: string; + hidden: any; + /** + * Gets or sets whether the DLNA PlayTo device is available. + */ + msPlayToDisabled: boolean; + /** + * Gets or sets the path to the preferred media source. This enables the Play To target device to stream the media content, which can be DRM protected, from a different location, such as a cloud media server. + */ + msPlayToPreferredSourceUri: string; + /** + * Gets or sets the primary DLNA PlayTo device. + */ + msPlayToPrimary: boolean; + /** + * Gets the source associated with the media element for use by the PlayToManager. + */ + readonly msPlayToSource: any; + /** + * Sets or retrieves the name of the object. + */ + /** @deprecated */ + name: string; + /** + * Retrieves the palette used for the embedded document. + */ + readonly palette: string; + /** + * Retrieves the URL of the plug-in used to view an embedded document. + */ + readonly pluginspage: string; + readonly readyState: string; + /** + * Sets or retrieves a URL to be loaded by the object. + */ + src: string; + /** + * Sets or retrieves the height and width units of the embed object. + */ + units: string; + /** + * Sets or retrieves the width of the object. + */ + width: string; + addEventListener(type: K, listener: (this: HTMLEmbedElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLEmbedElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLEmbedElement: { + prototype: HTMLEmbedElement; + new(): HTMLEmbedElement; +}; + +interface HTMLFieldSetElement extends HTMLElement { + disabled: boolean; + readonly elements: HTMLCollection; + /** + * Retrieves a reference to the form that the object is embedded in. + */ + readonly form: HTMLFormElement | null; + name: string; + readonly type: string; + /** + * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. + */ + readonly validationMessage: string; + /** + * Returns a ValidityState object that represents the validity states of an element. + */ + readonly validity: ValidityState; + /** + * Returns whether an element will successfully validate based on forms validation rules and constraints. + */ + readonly willValidate: boolean; + /** + * Returns whether a form will validate when it is submitted, without having to submit it. + */ + checkValidity(): boolean; + reportValidity(): boolean; + /** + * Sets a custom error message that is displayed when a form is submitted. + * @param error Sets a custom error message that is displayed when a form is submitted. + */ + setCustomValidity(error: string): void; + addEventListener(type: K, listener: (this: HTMLFieldSetElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLFieldSetElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLFieldSetElement: { + prototype: HTMLFieldSetElement; + new(): HTMLFieldSetElement; +}; + +interface HTMLFontElement extends HTMLElement { + /** @deprecated */ + color: string; + /** + * Sets or retrieves the current typeface family. + */ + /** @deprecated */ + face: string; + /** @deprecated */ + size: string; + addEventListener(type: K, listener: (this: HTMLFontElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLFontElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLFontElement: { + prototype: HTMLFontElement; + new(): HTMLFontElement; +}; + +interface HTMLFormControlsCollection extends HTMLCollectionBase { + /** + * element = collection[name] + */ + namedItem(name: string): RadioNodeList | Element | null; +} + +declare var HTMLFormControlsCollection: { + prototype: HTMLFormControlsCollection; + new(): HTMLFormControlsCollection; +}; + +interface HTMLFormElement extends HTMLElement { + /** + * Sets or retrieves a list of character encodings for input data that must be accepted by the server processing the form. + */ + acceptCharset: string; + /** + * Sets or retrieves the URL to which the form content is sent for processing. + */ + action: string; + /** + * Specifies whether autocomplete is applied to an editable text field. + */ + autocomplete: string; + /** + * Retrieves a collection, in source order, of all controls in a given form. + */ + readonly elements: HTMLFormControlsCollection; + /** + * Sets or retrieves the MIME encoding for the form. + */ + encoding: string; + /** + * Sets or retrieves the encoding type for the form. + */ + enctype: string; + /** + * Sets or retrieves the number of objects in a collection. + */ + readonly length: number; + /** + * Sets or retrieves how to send the form data to the server. + */ + method: string; + /** + * Sets or retrieves the name of the object. + */ + name: string; + /** + * Designates a form that is not validated when submitted. + */ + noValidate: boolean; + /** + * Sets or retrieves the window or frame at which to target content. + */ + target: string; + /** + * Returns whether a form will validate when it is submitted, without having to submit it. + */ + checkValidity(): boolean; + reportValidity(): boolean; + /** + * Fires when the user resets a form. + */ + reset(): void; + /** + * Fires when a FORM is about to be submitted. + */ + submit(): void; + addEventListener(type: K, listener: (this: HTMLFormElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLFormElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; + [index: number]: Element; + [name: string]: any; +} + +declare var HTMLFormElement: { + prototype: HTMLFormElement; + new(): HTMLFormElement; +}; + +interface HTMLFrameElement extends HTMLElement { + /** + * Retrieves the document object of the page or frame. + */ + /** @deprecated */ + readonly contentDocument: Document | null; + /** + * Retrieves the object of the specified. + */ + /** @deprecated */ + readonly contentWindow: WindowProxy | null; + /** + * Sets or retrieves whether to display a border for the frame. + */ + /** @deprecated */ + frameBorder: string; + /** + * Sets or retrieves a URI to a long description of the object. + */ + /** @deprecated */ + longDesc: string; + /** + * Sets or retrieves the top and bottom margin heights before displaying the text in a frame. + */ + /** @deprecated */ + marginHeight: string; + /** + * Sets or retrieves the left and right margin widths before displaying the text in a frame. + */ + /** @deprecated */ + marginWidth: string; + /** + * Sets or retrieves the frame name. + */ + /** @deprecated */ + name: string; + /** + * Sets or retrieves whether the user can resize the frame. + */ + /** @deprecated */ + noResize: boolean; + /** + * Sets or retrieves whether the frame can be scrolled. + */ + /** @deprecated */ + scrolling: string; + /** + * Sets or retrieves a URL to be loaded by the object. + */ + /** @deprecated */ + src: string; + addEventListener(type: K, listener: (this: HTMLFrameElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLFrameElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLFrameElement: { + prototype: HTMLFrameElement; + new(): HTMLFrameElement; +}; + +interface HTMLFrameSetElementEventMap extends HTMLElementEventMap, WindowEventHandlersEventMap { +} + +interface HTMLFrameSetElement extends HTMLElement, WindowEventHandlers { + /** + * Sets or retrieves the frame widths of the object. + */ + /** @deprecated */ + cols: string; + /** + * Sets or retrieves the frame heights of the object. + */ + /** @deprecated */ + rows: string; + addEventListener(type: K, listener: (this: HTMLFrameSetElement, ev: HTMLFrameSetElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLFrameSetElement, ev: HTMLFrameSetElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLFrameSetElement: { + prototype: HTMLFrameSetElement; + new(): HTMLFrameSetElement; +}; + +interface HTMLHRElement extends HTMLElement { + /** + * Sets or retrieves how the object is aligned with adjacent text. + */ + /** @deprecated */ + align: string; + /** @deprecated */ + color: string; + /** + * Sets or retrieves whether the horizontal rule is drawn with 3-D shading. + */ + /** @deprecated */ + noShade: boolean; + /** @deprecated */ + size: string; + /** + * Sets or retrieves the width of the object. + */ + /** @deprecated */ + width: string; + addEventListener(type: K, listener: (this: HTMLHRElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLHRElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLHRElement: { + prototype: HTMLHRElement; + new(): HTMLHRElement; +}; + +interface HTMLHeadElement extends HTMLElement { + addEventListener(type: K, listener: (this: HTMLHeadElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLHeadElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLHeadElement: { + prototype: HTMLHeadElement; + new(): HTMLHeadElement; +}; + +interface HTMLHeadingElement extends HTMLElement { + /** + * Sets or retrieves a value that indicates the table alignment. + */ + /** @deprecated */ + align: string; + addEventListener(type: K, listener: (this: HTMLHeadingElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLHeadingElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLHeadingElement: { + prototype: HTMLHeadingElement; + new(): HTMLHeadingElement; +}; + +interface HTMLHtmlElement extends HTMLElement { + /** + * Sets or retrieves the DTD version that governs the current document. + */ + /** @deprecated */ + version: string; + addEventListener(type: K, listener: (this: HTMLHtmlElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLHtmlElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLHtmlElement: { + prototype: HTMLHtmlElement; + new(): HTMLHtmlElement; +}; + +interface HTMLHyperlinkElementUtils { + hash: string; + host: string; + hostname: string; + href: string; + readonly origin: string; + password: string; + pathname: string; + port: string; + protocol: string; + search: string; + username: string; +} + +interface HTMLIFrameElement extends HTMLElement, GetSVGDocument { + /** + * Sets or retrieves how the object is aligned with adjacent text. + */ + /** @deprecated */ + align: string; + allowFullscreen: boolean; + allowPaymentRequest: boolean; + /** + * Retrieves the document object of the page or frame. + */ + readonly contentDocument: Document | null; + /** + * Retrieves the object of the specified. + */ + readonly contentWindow: Window | null; + /** + * Sets or retrieves whether to display a border for the frame. + */ + /** @deprecated */ + frameBorder: string; + /** + * Sets or retrieves the height of the object. + */ + height: string; + /** + * Sets or retrieves a URI to a long description of the object. + */ + /** @deprecated */ + longDesc: string; + /** + * Sets or retrieves the top and bottom margin heights before displaying the text in a frame. + */ + /** @deprecated */ + marginHeight: string; + /** + * Sets or retrieves the left and right margin widths before displaying the text in a frame. + */ + /** @deprecated */ + marginWidth: string; + /** + * Sets or retrieves the frame name. + */ + name: string; + readonly referrerPolicy: ReferrerPolicy; + readonly sandbox: DOMTokenList; + /** + * Sets or retrieves whether the frame can be scrolled. + */ + /** @deprecated */ + scrolling: string; + /** + * Sets or retrieves a URL to be loaded by the object. + */ + src: string; + /** + * Sets or retrives the content of the page that is to contain. + */ + srcdoc: string; + /** + * Sets or retrieves the width of the object. + */ + width: string; + addEventListener(type: K, listener: (this: HTMLIFrameElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLIFrameElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLIFrameElement: { + prototype: HTMLIFrameElement; + new(): HTMLIFrameElement; +}; + +interface HTMLImageElement extends HTMLElement { + /** + * Sets or retrieves how the object is aligned with adjacent text. + */ + /** @deprecated */ + align: string; + /** + * Sets or retrieves a text alternative to the graphic. + */ + alt: string; + /** + * Specifies the properties of a border drawn around an object. + */ + /** @deprecated */ + border: string; + /** + * Retrieves whether the object is fully loaded. + */ + readonly complete: boolean; + crossOrigin: string | null; + readonly currentSrc: string; + decoding: "async" | "sync" | "auto"; + /** + * Sets or retrieves the height of the object. + */ + height: number; + /** + * Sets or retrieves the width of the border to draw around the object. + */ + /** @deprecated */ + hspace: number; + /** + * Sets or retrieves whether the image is a server-side image map. + */ + isMap: boolean; + /** + * Sets or retrieves a Uniform Resource Identifier (URI) to a long description of the object. + */ + /** @deprecated */ + longDesc: string; + /** @deprecated */ + lowsrc: string; + /** + * Sets or retrieves the name of the object. + */ + /** @deprecated */ + name: string; + /** + * The original height of the image resource before sizing. + */ + readonly naturalHeight: number; + /** + * The original width of the image resource before sizing. + */ + readonly naturalWidth: number; + referrerPolicy: string; + sizes: string; + /** + * The address or URL of the a media resource that is to be considered. + */ + src: string; + srcset: string; + /** + * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. + */ + useMap: string; + /** + * Sets or retrieves the vertical margin for the object. + */ + /** @deprecated */ + vspace: number; + /** + * Sets or retrieves the width of the object. + */ + width: number; + readonly x: number; + readonly y: number; + decode(): Promise; + addEventListener(type: K, listener: (this: HTMLImageElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLImageElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLImageElement: { + prototype: HTMLImageElement; + new(): HTMLImageElement; +}; + +interface HTMLInputElement extends HTMLElement { + /** + * Sets or retrieves a comma-separated list of content types. + */ + accept: string; + /** + * Sets or retrieves how the object is aligned with adjacent text. + */ + /** @deprecated */ + align: string; + /** + * Sets or retrieves a text alternative to the graphic. + */ + alt: string; + /** + * Specifies whether autocomplete is applied to an editable text field. + */ + autocomplete: string; + /** + * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing. + */ + autofocus: boolean; + /** + * Sets or retrieves the state of the check box or radio button. + */ + checked: boolean; + /** + * Sets or retrieves the state of the check box or radio button. + */ + defaultChecked: boolean; + /** + * Sets or retrieves the initial contents of the object. + */ + defaultValue: string; + dirName: string; + disabled: boolean; + /** + * Returns a FileList object on a file type input object. + */ + files: FileList | null; + /** + * Retrieves a reference to the form that the object is embedded in. + */ + readonly form: HTMLFormElement | null; + /** + * Overrides the action attribute (where the data on a form is sent) on the parent form element. + */ + formAction: string; + /** + * Used to override the encoding (formEnctype attribute) specified on the form element. + */ + formEnctype: string; + /** + * Overrides the submit method attribute previously specified on a form element. + */ + formMethod: string; + /** + * Overrides any validation or required attributes on a form or form elements to allow it to be submitted without validation. This can be used to create a "save draft"-type submit option. + */ + formNoValidate: boolean; + /** + * Overrides the target attribute on a form element. + */ + formTarget: string; + /** + * Sets or retrieves the height of the object. + */ + height: number; + indeterminate: boolean; + readonly labels: NodeListOf | null; + /** + * Specifies the ID of a pre-defined datalist of options for an input element. + */ + readonly list: HTMLElement | null; + /** + * Defines the maximum acceptable value for an input element with type="number".When used with the min and step attributes, lets you control the range and increment (such as only even numbers) that the user can enter into an input field. + */ + max: string; + /** + * Sets or retrieves the maximum number of characters that the user can enter in a text control. + */ + maxLength: number; + /** + * Defines the minimum acceptable value for an input element with type="number". When used with the max and step attributes, lets you control the range and increment (such as even numbers only) that the user can enter into an input field. + */ + min: string; + minLength: number; + /** + * Sets or retrieves the Boolean value indicating whether multiple items can be selected from a list. + */ + multiple: boolean; + /** + * Sets or retrieves the name of the object. + */ + name: string; + /** + * Gets or sets a string containing a regular expression that the user's input must match. + */ + pattern: string; + /** + * Gets or sets a text string that is displayed in an input field as a hint or prompt to users as the format or type of information they need to enter.The text appears in an input field until the user puts focus on the field. + */ + placeholder: string; + readOnly: boolean; + /** + * When present, marks an element that can't be submitted without a value. + */ + required: boolean; + selectionDirection: string | null; + /** + * Gets or sets the end position or offset of a text selection. + */ + selectionEnd: number | null; + /** + * Gets or sets the starting position or offset of a text selection. + */ + selectionStart: number | null; + size: number; + /** + * The address or URL of the a media resource that is to be considered. + */ + src: string; + /** + * Defines an increment or jump between values that you want to allow the user to enter. When used with the max and min attributes, lets you control the range and increment (for example, allow only even numbers) that the user can enter into an input field. + */ + step: string; + /** + * Returns the content type of the object. + */ + type: string; + /** + * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. + */ + /** @deprecated */ + useMap: string; + /** + * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. + */ + readonly validationMessage: string; + /** + * Returns a ValidityState object that represents the validity states of an element. + */ + readonly validity: ValidityState; + /** + * Returns the value of the data at the cursor's current position. + */ + value: string; + valueAsDate: any; + /** + * Returns the input field value as a number. + */ + valueAsNumber: number; + /** + * Sets or retrieves the width of the object. + */ + width: number; + /** + * Returns whether an element will successfully validate based on forms validation rules and constraints. + */ + readonly willValidate: boolean; + /** + * Returns whether a form will validate when it is submitted, without having to submit it. + */ + checkValidity(): boolean; + reportValidity(): boolean; + /** + * Makes the selection equal to the current object. + */ + select(): void; + /** + * Sets a custom error message that is displayed when a form is submitted. + * @param error Sets a custom error message that is displayed when a form is submitted. + */ + setCustomValidity(error: string): void; + setRangeText(replacement: string): void; + setRangeText(replacement: string, start: number, end: number, selectionMode?: SelectionMode): void; + /** + * Sets the start and end positions of a selection in a text field. + * @param start The offset into the text field for the start of the selection. + * @param end The offset into the text field for the end of the selection. + * @param direction The direction in which the selection is performed. + */ + setSelectionRange(start: number, end: number, direction?: "forward" | "backward" | "none"): void; + /** + * Decrements a range input control's value by the value given by the Step attribute. If the optional parameter is used, it will decrement the input control's step value multiplied by the parameter's value. + * @param n Value to decrement the value by. + */ + stepDown(n?: number): void; + /** + * Increments a range input control's value by the value given by the Step attribute. If the optional parameter is used, will increment the input control's value by that value. + * @param n Value to increment the value by. + */ + stepUp(n?: number): void; + addEventListener(type: K, listener: (this: HTMLInputElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLInputElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLInputElement: { + prototype: HTMLInputElement; + new(): HTMLInputElement; +}; + +interface HTMLLIElement extends HTMLElement { + /** @deprecated */ + type: string; + /** + * Sets or retrieves the value of a list item. + */ + value: number; + addEventListener(type: K, listener: (this: HTMLLIElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLLIElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLLIElement: { + prototype: HTMLLIElement; + new(): HTMLLIElement; +}; + +interface HTMLLabelElement extends HTMLElement { + readonly control: HTMLElement | null; + /** + * Retrieves a reference to the form that the object is embedded in. + */ + readonly form: HTMLFormElement | null; + /** + * Sets or retrieves the object to which the given label object is assigned. + */ + htmlFor: string; + addEventListener(type: K, listener: (this: HTMLLabelElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLLabelElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLLabelElement: { + prototype: HTMLLabelElement; + new(): HTMLLabelElement; +}; + +interface HTMLLegendElement extends HTMLElement { + /** @deprecated */ + align: string; + /** + * Retrieves a reference to the form that the object is embedded in. + */ + readonly form: HTMLFormElement | null; + addEventListener(type: K, listener: (this: HTMLLegendElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLLegendElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLLegendElement: { + prototype: HTMLLegendElement; + new(): HTMLLegendElement; +}; + +interface HTMLLinkElement extends HTMLElement, LinkStyle { + as: string; + /** + * Sets or retrieves the character set used to encode the object. + */ + /** @deprecated */ + charset: string; + crossOrigin: string | null; + disabled: boolean; + /** + * Sets or retrieves a destination URL or an anchor point. + */ + href: string; + /** + * Sets or retrieves the language code of the object. + */ + hreflang: string; + integrity: string; + /** + * Sets or retrieves the media type. + */ + media: string; + referrerPolicy: string; + /** + * Sets or retrieves the relationship between the object and the destination of the link. + */ + rel: string; + readonly relList: DOMTokenList; + /** + * Sets or retrieves the relationship between the object and the destination of the link. + */ + /** @deprecated */ + rev: string; + readonly sizes: DOMTokenList; + /** + * Sets or retrieves the window or frame at which to target content. + */ + /** @deprecated */ + target: string; + /** + * Sets or retrieves the MIME type of the object. + */ + type: string; + addEventListener(type: K, listener: (this: HTMLLinkElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLLinkElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLLinkElement: { + prototype: HTMLLinkElement; + new(): HTMLLinkElement; +}; + +interface HTMLMainElement extends HTMLElement { + addEventListener(type: K, listener: (this: HTMLMainElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLMainElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLMainElement: { + prototype: HTMLMainElement; + new(): HTMLMainElement; +}; + +interface HTMLMapElement extends HTMLElement { + /** + * Retrieves a collection of the area objects defined for the given map object. + */ + readonly areas: HTMLCollection; + /** + * Sets or retrieves the name of the object. + */ + name: string; + addEventListener(type: K, listener: (this: HTMLMapElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLMapElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLMapElement: { + prototype: HTMLMapElement; + new(): HTMLMapElement; +}; + +interface HTMLMarqueeElementEventMap extends HTMLElementEventMap { + "bounce": Event; + "finish": Event; + "start": Event; +} + +interface HTMLMarqueeElement extends HTMLElement { + /** @deprecated */ + behavior: string; + /** @deprecated */ + bgColor: string; + /** @deprecated */ + direction: string; + /** @deprecated */ + height: string; + /** @deprecated */ + hspace: number; + /** @deprecated */ + loop: number; + /** @deprecated */ + onbounce: ((this: HTMLMarqueeElement, ev: Event) => any) | null; + /** @deprecated */ + onfinish: ((this: HTMLMarqueeElement, ev: Event) => any) | null; + /** @deprecated */ + onstart: ((this: HTMLMarqueeElement, ev: Event) => any) | null; + /** @deprecated */ + scrollAmount: number; + /** @deprecated */ + scrollDelay: number; + /** @deprecated */ + trueSpeed: boolean; + /** @deprecated */ + vspace: number; + /** @deprecated */ + width: string; + /** @deprecated */ + start(): void; + /** @deprecated */ + stop(): void; + addEventListener(type: K, listener: (this: HTMLMarqueeElement, ev: HTMLMarqueeElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLMarqueeElement, ev: HTMLMarqueeElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLMarqueeElement: { + prototype: HTMLMarqueeElement; + new(): HTMLMarqueeElement; +}; + +interface HTMLMediaElementEventMap extends HTMLElementEventMap { + "encrypted": MediaEncryptedEvent; + "msneedkey": Event; +} + +interface HTMLMediaElement extends HTMLElement { + /** + * Returns an AudioTrackList object with the audio tracks for a given video element. + */ + readonly audioTracks: AudioTrackList; + /** + * Gets or sets a value that indicates whether to start playing the media automatically. + */ + autoplay: boolean; + /** + * Gets a collection of buffered time ranges. + */ + readonly buffered: TimeRanges; + /** + * Gets or sets a flag that indicates whether the client provides a set of controls for the media (in case the developer does not include controls for the player). + */ + controls: boolean; + crossOrigin: string | null; + /** + * Gets the address or URL of the current media resource that is selected by IHTMLMediaElement. + */ + readonly currentSrc: string; + /** + * Gets or sets the current playback position, in seconds. + */ + currentTime: number; + defaultMuted: boolean; + /** + * Gets or sets the default playback rate when the user is not using fast forward or reverse for a video or audio resource. + */ + defaultPlaybackRate: number; + /** + * Returns the duration in seconds of the current media resource. A NaN value is returned if duration is not available, or Infinity if the media resource is streaming. + */ + readonly duration: number; + /** + * Gets information about whether the playback has ended or not. + */ + readonly ended: boolean; + /** + * Returns an object representing the current error state of the audio or video element. + */ + readonly error: MediaError | null; + /** + * Gets or sets a flag to specify whether playback should restart after it completes. + */ + loop: boolean; + readonly mediaKeys: MediaKeys | null; + /** + * Specifies the purpose of the audio or video media, such as background audio or alerts. + */ + msAudioCategory: string; + /** + * Specifies the output device id that the audio will be sent to. + */ + msAudioDeviceType: string; + readonly msGraphicsTrustStatus: MSGraphicsTrust; + /** + * Gets the MSMediaKeys object, which is used for decrypting media data, that is associated with this media element. + */ + /** @deprecated */ + readonly msKeys: MSMediaKeys; + /** + * Gets or sets whether the DLNA PlayTo device is available. + */ + msPlayToDisabled: boolean; + /** + * Gets or sets the path to the preferred media source. This enables the Play To target device to stream the media content, which can be DRM protected, from a different location, such as a cloud media server. + */ + msPlayToPreferredSourceUri: string; + /** + * Gets or sets the primary DLNA PlayTo device. + */ + msPlayToPrimary: boolean; + /** + * Gets the source associated with the media element for use by the PlayToManager. + */ + readonly msPlayToSource: any; + /** + * Specifies whether or not to enable low-latency playback on the media element. + */ + msRealTime: boolean; + /** + * Gets or sets a flag that indicates whether the audio (either audio or the audio track on video media) is muted. + */ + muted: boolean; + /** + * Gets the current network activity for the element. + */ + readonly networkState: number; + onencrypted: ((this: HTMLMediaElement, ev: MediaEncryptedEvent) => any) | null; + /** @deprecated */ + onmsneedkey: ((this: HTMLMediaElement, ev: Event) => any) | null; + /** + * Gets a flag that specifies whether playback is paused. + */ + readonly paused: boolean; + /** + * Gets or sets the current rate of speed for the media resource to play. This speed is expressed as a multiple of the normal speed of the media resource. + */ + playbackRate: number; + /** + * Gets TimeRanges for the current media resource that has been played. + */ + readonly played: TimeRanges; + /** + * Gets or sets the current playback position, in seconds. + */ + preload: string; + readonly readyState: number; + /** + * Returns a TimeRanges object that represents the ranges of the current media resource that can be seeked. + */ + readonly seekable: TimeRanges; + /** + * Gets a flag that indicates whether the client is currently moving to a new playback position in the media resource. + */ + readonly seeking: boolean; + /** + * The address or URL of the a media resource that is to be considered. + */ + src: string; + srcObject: MediaStream | MediaSource | Blob | null; + readonly textTracks: TextTrackList; + readonly videoTracks: VideoTrackList; + /** + * Gets or sets the volume level for audio portions of the media element. + */ + volume: number; + addTextTrack(kind: TextTrackKind, label?: string, language?: string): TextTrack; + /** + * Returns a string that specifies whether the client can play a given media resource type. + */ + canPlayType(type: string): CanPlayTypeResult; + /** + * Resets the audio or video object and loads a new media resource. + */ + load(): void; + /** + * Clears all effects from the media pipeline. + */ + msClearEffects(): void; + msGetAsCastingSource(): any; + /** + * Inserts the specified audio effect into media pipeline. + */ + msInsertAudioEffect(activatableClassId: string, effectRequired: boolean, config?: any): void; + /** @deprecated */ + msSetMediaKeys(mediaKeys: MSMediaKeys): void; + /** + * Specifies the media protection manager for a given media pipeline. + */ + msSetMediaProtectionManager(mediaProtectionManager?: any): void; + /** + * Pauses the current playback and sets paused to TRUE. This can be used to test whether the media is playing or paused. You can also use the pause or play events to tell whether the media is playing or not. + */ + pause(): void; + /** + * Loads and starts playback of a media resource. + */ + play(): Promise; + setMediaKeys(mediaKeys: MediaKeys | null): Promise; + readonly HAVE_CURRENT_DATA: number; + readonly HAVE_ENOUGH_DATA: number; + readonly HAVE_FUTURE_DATA: number; + readonly HAVE_METADATA: number; + readonly HAVE_NOTHING: number; + readonly NETWORK_EMPTY: number; + readonly NETWORK_IDLE: number; + readonly NETWORK_LOADING: number; + readonly NETWORK_NO_SOURCE: number; + addEventListener(type: K, listener: (this: HTMLMediaElement, ev: HTMLMediaElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLMediaElement, ev: HTMLMediaElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLMediaElement: { + prototype: HTMLMediaElement; + new(): HTMLMediaElement; + readonly HAVE_CURRENT_DATA: number; + readonly HAVE_ENOUGH_DATA: number; + readonly HAVE_FUTURE_DATA: number; + readonly HAVE_METADATA: number; + readonly HAVE_NOTHING: number; + readonly NETWORK_EMPTY: number; + readonly NETWORK_IDLE: number; + readonly NETWORK_LOADING: number; + readonly NETWORK_NO_SOURCE: number; +}; + +interface HTMLMenuElement extends HTMLElement { + /** @deprecated */ + compact: boolean; + addEventListener(type: K, listener: (this: HTMLMenuElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLMenuElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLMenuElement: { + prototype: HTMLMenuElement; + new(): HTMLMenuElement; +}; + +interface HTMLMetaElement extends HTMLElement { + /** + * Gets or sets meta-information to associate with httpEquiv or name. + */ + content: string; + /** + * Gets or sets information used to bind the value of a content attribute of a meta element to an HTTP response header. + */ + httpEquiv: string; + /** + * Sets or retrieves the value specified in the content attribute of the meta object. + */ + name: string; + /** + * Sets or retrieves a scheme to be used in interpreting the value of a property specified for the object. + */ + /** @deprecated */ + scheme: string; + addEventListener(type: K, listener: (this: HTMLMetaElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLMetaElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLMetaElement: { + prototype: HTMLMetaElement; + new(): HTMLMetaElement; +}; + +interface HTMLMeterElement extends HTMLElement { + high: number; + readonly labels: NodeListOf; + low: number; + max: number; + min: number; + optimum: number; + value: number; + addEventListener(type: K, listener: (this: HTMLMeterElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLMeterElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLMeterElement: { + prototype: HTMLMeterElement; + new(): HTMLMeterElement; +}; + +interface HTMLModElement extends HTMLElement { + /** + * Sets or retrieves reference information about the object. + */ + cite: string; + /** + * Sets or retrieves the date and time of a modification to the object. + */ + dateTime: string; + addEventListener(type: K, listener: (this: HTMLModElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLModElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLModElement: { + prototype: HTMLModElement; + new(): HTMLModElement; +}; + +interface HTMLOListElement extends HTMLElement { + /** @deprecated */ + compact: boolean; + reversed: boolean; + /** + * The starting number. + */ + start: number; + type: string; + addEventListener(type: K, listener: (this: HTMLOListElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLOListElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLOListElement: { + prototype: HTMLOListElement; + new(): HTMLOListElement; +}; + +interface HTMLObjectElement extends HTMLElement, GetSVGDocument { + /** + * Retrieves a string of the URL where the object tag can be found. This is often the href of the document that the object is in, or the value set by a base element. + */ + readonly BaseHref: string; + /** @deprecated */ + align: string; + /** + * Sets or retrieves a character string that can be used to implement your own archive functionality for the object. + */ + /** @deprecated */ + archive: string; + /** @deprecated */ + border: string; + /** + * Sets or retrieves the URL of the file containing the compiled Java class. + */ + /** @deprecated */ + code: string; + /** + * Sets or retrieves the URL of the component. + */ + /** @deprecated */ + codeBase: string; + /** + * Sets or retrieves the Internet media type for the code associated with the object. + */ + /** @deprecated */ + codeType: string; + /** + * Retrieves the document object of the page or frame. + */ + readonly contentDocument: Document | null; + /** + * Sets or retrieves the URL that references the data of the object. + */ + data: string; + /** @deprecated */ + declare: boolean; + /** + * Retrieves a reference to the form that the object is embedded in. + */ + readonly form: HTMLFormElement | null; + /** + * Sets or retrieves the height of the object. + */ + height: string; + /** @deprecated */ + hspace: number; + /** + * Gets or sets whether the DLNA PlayTo device is available. + */ + msPlayToDisabled: boolean; + /** + * Gets or sets the path to the preferred media source. This enables the Play To target device to stream the media content, which can be DRM protected, from a different location, such as a cloud media server. + */ + msPlayToPreferredSourceUri: string; + /** + * Gets or sets the primary DLNA PlayTo device. + */ + msPlayToPrimary: boolean; + /** + * Gets the source associated with the media element for use by the PlayToManager. + */ + readonly msPlayToSource: any; + /** + * Sets or retrieves the name of the object. + */ + name: string; + readonly readyState: number; + /** + * Sets or retrieves a message to be displayed while an object is loading. + */ + /** @deprecated */ + standby: string; + /** + * Sets or retrieves the MIME type of the object. + */ + type: string; + typemustmatch: boolean; + /** + * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. + */ + useMap: string; + /** + * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. + */ + readonly validationMessage: string; + /** + * Returns a ValidityState object that represents the validity states of an element. + */ + readonly validity: ValidityState; + /** @deprecated */ + vspace: number; + /** + * Sets or retrieves the width of the object. + */ + width: string; + /** + * Returns whether an element will successfully validate based on forms validation rules and constraints. + */ + readonly willValidate: boolean; + /** + * Returns whether a form will validate when it is submitted, without having to submit it. + */ + checkValidity(): boolean; + reportValidity(): boolean; + /** + * Sets a custom error message that is displayed when a form is submitted. + * @param error Sets a custom error message that is displayed when a form is submitted. + */ + setCustomValidity(error: string): void; + addEventListener(type: K, listener: (this: HTMLObjectElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLObjectElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLObjectElement: { + prototype: HTMLObjectElement; + new(): HTMLObjectElement; +}; + +interface HTMLOptGroupElement extends HTMLElement { + disabled: boolean; + /** + * Retrieves a reference to the form that the object is embedded in. + */ + readonly form: HTMLFormElement | null; + /** + * Sets or retrieves a value that you can use to implement your own label functionality for the object. + */ + label: string; + addEventListener(type: K, listener: (this: HTMLOptGroupElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLOptGroupElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLOptGroupElement: { + prototype: HTMLOptGroupElement; + new(): HTMLOptGroupElement; +}; + +interface HTMLOptionElement extends HTMLElement { + /** + * Sets or retrieves the status of an option. + */ + defaultSelected: boolean; + disabled: boolean; + /** + * Retrieves a reference to the form that the object is embedded in. + */ + readonly form: HTMLFormElement | null; + /** + * Sets or retrieves the ordinal position of an option in a list box. + */ + readonly index: number; + /** + * Sets or retrieves a value that you can use to implement your own label functionality for the object. + */ + label: string; + /** + * Sets or retrieves whether the option in the list box is the default item. + */ + selected: boolean; + /** + * Sets or retrieves the text string specified by the option tag. + */ + text: string; + /** + * Sets or retrieves the value which is returned to the server when the form control is submitted. + */ + value: string; + addEventListener(type: K, listener: (this: HTMLOptionElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLOptionElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLOptionElement: { + prototype: HTMLOptionElement; + new(): HTMLOptionElement; +}; + +interface HTMLOptionsCollection extends HTMLCollectionOf { + /** + * Returns the number of elements in the collection. + * When set to a smaller number, truncates the number of option elements in the corresponding container. + * When set to a greater number, adds new blank option elements to that container. + */ + length: number; + /** + * Returns the index of the first selected item, if any, or −1 if there is no selected + * item. + * Can be set, to change the selection. + */ + selectedIndex: number; + /** + * Inserts element before the node given by before. + * The before argument can be a number, in which case element is inserted before the item with that number, or an element from the + * collection, in which case element is inserted before that element. + * If before is omitted, null, or a number out of range, then element will be added at the end of the list. + * This method will throw a "HierarchyRequestError" DOMException if + * element is an ancestor of the element into which it is to be inserted. + */ + add(element: HTMLOptionElement | HTMLOptGroupElement, before?: HTMLElement | number | null): void; + /** + * Removes the item with index index from the collection. + */ + remove(index: number): void; +} + +declare var HTMLOptionsCollection: { + prototype: HTMLOptionsCollection; + new(): HTMLOptionsCollection; +}; + +interface HTMLOrSVGElement { + readonly dataset: DOMStringMap; + nonce: string; + tabIndex: number; + blur(): void; + focus(options?: FocusOptions): void; +} + +interface HTMLOutputElement extends HTMLElement { + defaultValue: string; + readonly form: HTMLFormElement | null; + readonly htmlFor: DOMTokenList; + readonly labels: NodeListOf; + name: string; + readonly type: string; + readonly validationMessage: string; + readonly validity: ValidityState; + value: string; + readonly willValidate: boolean; + checkValidity(): boolean; + reportValidity(): boolean; + setCustomValidity(error: string): void; + addEventListener(type: K, listener: (this: HTMLOutputElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLOutputElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLOutputElement: { + prototype: HTMLOutputElement; + new(): HTMLOutputElement; +}; + +interface HTMLParagraphElement extends HTMLElement { + /** + * Sets or retrieves how the object is aligned with adjacent text. + */ + /** @deprecated */ + align: string; + addEventListener(type: K, listener: (this: HTMLParagraphElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLParagraphElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLParagraphElement: { + prototype: HTMLParagraphElement; + new(): HTMLParagraphElement; +}; + +interface HTMLParamElement extends HTMLElement { + /** + * Sets or retrieves the name of an input parameter for an element. + */ + name: string; + /** + * Sets or retrieves the content type of the resource designated by the value attribute. + */ + /** @deprecated */ + type: string; + /** + * Sets or retrieves the value of an input parameter for an element. + */ + value: string; + /** + * Sets or retrieves the data type of the value attribute. + */ + /** @deprecated */ + valueType: string; + addEventListener(type: K, listener: (this: HTMLParamElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLParamElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLParamElement: { + prototype: HTMLParamElement; + new(): HTMLParamElement; +}; + +interface HTMLPictureElement extends HTMLElement { + addEventListener(type: K, listener: (this: HTMLPictureElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLPictureElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLPictureElement: { + prototype: HTMLPictureElement; + new(): HTMLPictureElement; +}; + +interface HTMLPreElement extends HTMLElement { + /** + * Sets or gets a value that you can use to implement your own width functionality for the object. + */ + /** @deprecated */ + width: number; + addEventListener(type: K, listener: (this: HTMLPreElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLPreElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLPreElement: { + prototype: HTMLPreElement; + new(): HTMLPreElement; +}; + +interface HTMLProgressElement extends HTMLElement { + readonly labels: NodeListOf; + /** + * Defines the maximum, or "done" value for a progress element. + */ + max: number; + /** + * Returns the quotient of value/max when the value attribute is set (determinate progress bar), or -1 when the value attribute is missing (indeterminate progress bar). + */ + readonly position: number; + /** + * Sets or gets the current value of a progress element. The value must be a non-negative number between 0 and the max value. + */ + value: number; + addEventListener(type: K, listener: (this: HTMLProgressElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLProgressElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLProgressElement: { + prototype: HTMLProgressElement; + new(): HTMLProgressElement; +}; + +interface HTMLQuoteElement extends HTMLElement { + /** + * Sets or retrieves reference information about the object. + */ + cite: string; + addEventListener(type: K, listener: (this: HTMLQuoteElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLQuoteElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLQuoteElement: { + prototype: HTMLQuoteElement; + new(): HTMLQuoteElement; +}; + +interface HTMLScriptElement extends HTMLElement { + async: boolean; + /** + * Sets or retrieves the character set used to encode the object. + */ + /** @deprecated */ + charset: string; + crossOrigin: string | null; + /** + * Sets or retrieves the status of the script. + */ + defer: boolean; + /** + * Sets or retrieves the event for which the script is written. + */ + /** @deprecated */ + event: string; + /** + * Sets or retrieves the object that is bound to the event script. + */ + /** @deprecated */ + htmlFor: string; + integrity: string; + noModule: boolean; + referrerPolicy: string; + /** + * Retrieves the URL to an external file that contains the source code or data. + */ + src: string; + /** + * Retrieves or sets the text of the object as a string. + */ + text: string; + /** + * Sets or retrieves the MIME type for the associated scripting engine. + */ + type: string; + addEventListener(type: K, listener: (this: HTMLScriptElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLScriptElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLScriptElement: { + prototype: HTMLScriptElement; + new(): HTMLScriptElement; +}; + +interface HTMLSelectElement extends HTMLElement { + autocomplete: string; + /** + * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing. + */ + autofocus: boolean; + disabled: boolean; + /** + * Retrieves a reference to the form that the object is embedded in. + */ + readonly form: HTMLFormElement | null; + readonly labels: NodeListOf; + /** + * Sets or retrieves the number of objects in a collection. + */ + length: number; + /** + * Sets or retrieves the Boolean value indicating whether multiple items can be selected from a list. + */ + multiple: boolean; + /** + * Sets or retrieves the name of the object. + */ + name: string; + readonly options: HTMLOptionsCollection; + /** + * When present, marks an element that can't be submitted without a value. + */ + required: boolean; + /** + * Sets or retrieves the index of the selected option in a select object. + */ + selectedIndex: number; + readonly selectedOptions: HTMLCollectionOf; + /** + * Sets or retrieves the number of rows in the list box. + */ + size: number; + /** + * Retrieves the type of select control based on the value of the MULTIPLE attribute. + */ + readonly type: string; + /** + * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. + */ + readonly validationMessage: string; + /** + * Returns a ValidityState object that represents the validity states of an element. + */ + readonly validity: ValidityState; + /** + * Sets or retrieves the value which is returned to the server when the form control is submitted. + */ + value: string; + /** + * Returns whether an element will successfully validate based on forms validation rules and constraints. + */ + readonly willValidate: boolean; + /** + * Adds an element to the areas, controlRange, or options collection. + * @param element Variant of type Number that specifies the index position in the collection where the element is placed. If no value is given, the method places the element at the end of the collection. + * @param before Variant of type Object that specifies an element to insert before, or null to append the object to the collection. + */ + add(element: HTMLOptionElement | HTMLOptGroupElement, before?: HTMLElement | number | null): void; + /** + * Returns whether a form will validate when it is submitted, without having to submit it. + */ + checkValidity(): boolean; + /** + * Retrieves a select object or an object from an options collection. + * @param name Variant of type Number or String that specifies the object or collection to retrieve. If this parameter is an integer, it is the zero-based index of the object. If this parameter is a string, all objects with matching name or id properties are retrieved, and a collection is returned if more than one match is made. + * @param index Variant of type Number that specifies the zero-based index of the object to retrieve when a collection is returned. + */ + item(index: number): Element | null; + /** + * Retrieves a select object or an object from an options collection. + * @param namedItem A String that specifies the name or id property of the object to retrieve. A collection is returned if more than one match is made. + */ + namedItem(name: string): HTMLOptionElement | null; + /** + * Removes an element from the collection. + * @param index Number that specifies the zero-based index of the element to remove from the collection. + */ + remove(): void; + remove(index: number): void; + reportValidity(): boolean; + /** + * Sets a custom error message that is displayed when a form is submitted. + * @param error Sets a custom error message that is displayed when a form is submitted. + */ + setCustomValidity(error: string): void; + addEventListener(type: K, listener: (this: HTMLSelectElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLSelectElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; + [name: number]: HTMLOptionElement | HTMLOptGroupElement; +} + +declare var HTMLSelectElement: { + prototype: HTMLSelectElement; + new(): HTMLSelectElement; +}; + +interface HTMLSlotElement extends HTMLElement { + name: string; + assignedElements(options?: AssignedNodesOptions): Element[]; + assignedNodes(options?: AssignedNodesOptions): Node[]; + addEventListener(type: K, listener: (this: HTMLSlotElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLSlotElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLSlotElement: { + prototype: HTMLSlotElement; + new(): HTMLSlotElement; +}; + +interface HTMLSourceElement extends HTMLElement { + /** + * Gets or sets the intended media type of the media source. + */ + media: string; + sizes: string; + /** + * The address or URL of the a media resource that is to be considered. + */ + src: string; + srcset: string; + /** + * Gets or sets the MIME type of a media resource. + */ + type: string; + addEventListener(type: K, listener: (this: HTMLSourceElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLSourceElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLSourceElement: { + prototype: HTMLSourceElement; + new(): HTMLSourceElement; +}; + +interface HTMLSpanElement extends HTMLElement { + addEventListener(type: K, listener: (this: HTMLSpanElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLSpanElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLSpanElement: { + prototype: HTMLSpanElement; + new(): HTMLSpanElement; +}; + +interface HTMLStyleElement extends HTMLElement, LinkStyle { + /** + * Sets or retrieves the media type. + */ + media: string; + /** + * Retrieves the CSS language in which the style sheet is written. + */ + /** @deprecated */ + type: string; + addEventListener(type: K, listener: (this: HTMLStyleElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLStyleElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLStyleElement: { + prototype: HTMLStyleElement; + new(): HTMLStyleElement; +}; + +interface HTMLTableCaptionElement extends HTMLElement { + /** + * Sets or retrieves the alignment of the caption or legend. + */ + /** @deprecated */ + align: string; + addEventListener(type: K, listener: (this: HTMLTableCaptionElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLTableCaptionElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLTableCaptionElement: { + prototype: HTMLTableCaptionElement; + new(): HTMLTableCaptionElement; +}; + +interface HTMLTableCellElement extends HTMLElement { + /** + * Sets or retrieves abbreviated text for the object. + */ + abbr: string; + /** + * Sets or retrieves how the object is aligned with adjacent text. + */ + /** @deprecated */ + align: string; + /** + * Sets or retrieves a comma-delimited list of conceptual categories associated with the object. + */ + /** @deprecated */ + axis: string; + /** @deprecated */ + bgColor: string; + /** + * Retrieves the position of the object in the cells collection of a row. + */ + readonly cellIndex: number; + /** @deprecated */ + ch: string; + /** @deprecated */ + chOff: string; + /** + * Sets or retrieves the number columns in the table that the object should span. + */ + colSpan: number; + /** + * Sets or retrieves a list of header cells that provide information for the object. + */ + headers: string; + /** + * Sets or retrieves the height of the object. + */ + /** @deprecated */ + height: string; + /** + * Sets or retrieves whether the browser automatically performs wordwrap. + */ + /** @deprecated */ + noWrap: boolean; + /** + * Sets or retrieves how many rows in a table the cell should span. + */ + rowSpan: number; + /** + * Sets or retrieves the group of cells in a table to which the object's information applies. + */ + scope: string; + /** @deprecated */ + vAlign: string; + /** + * Sets or retrieves the width of the object. + */ + /** @deprecated */ + width: string; + addEventListener(type: K, listener: (this: HTMLTableCellElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLTableCellElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLTableCellElement: { + prototype: HTMLTableCellElement; + new(): HTMLTableCellElement; +}; + +interface HTMLTableColElement extends HTMLElement { + /** + * Sets or retrieves the alignment of the object relative to the display or table. + */ + /** @deprecated */ + align: string; + /** @deprecated */ + ch: string; + /** @deprecated */ + chOff: string; + /** + * Sets or retrieves the number of columns in the group. + */ + span: number; + /** @deprecated */ + vAlign: string; + /** + * Sets or retrieves the width of the object. + */ + /** @deprecated */ + width: string; + addEventListener(type: K, listener: (this: HTMLTableColElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLTableColElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLTableColElement: { + prototype: HTMLTableColElement; + new(): HTMLTableColElement; +}; + +interface HTMLTableDataCellElement extends HTMLTableCellElement { + addEventListener(type: K, listener: (this: HTMLTableDataCellElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLTableDataCellElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLTableDataCellElement: { + prototype: HTMLTableDataCellElement; + new(): HTMLTableDataCellElement; +}; + +interface HTMLTableElement extends HTMLElement { + /** + * Sets or retrieves a value that indicates the table alignment. + */ + /** @deprecated */ + align: string; + /** @deprecated */ + bgColor: string; + /** + * Sets or retrieves the width of the border to draw around the object. + */ + /** @deprecated */ + border: string; + /** + * Retrieves the caption object of a table. + */ + caption: HTMLTableCaptionElement | null; + /** + * Sets or retrieves the amount of space between the border of the cell and the content of the cell. + */ + /** @deprecated */ + cellPadding: string; + /** + * Sets or retrieves the amount of space between cells in a table. + */ + /** @deprecated */ + cellSpacing: string; + /** + * Sets or retrieves the way the border frame around the table is displayed. + */ + /** @deprecated */ + frame: string; + /** + * Sets or retrieves the number of horizontal rows contained in the object. + */ + readonly rows: HTMLCollectionOf; + /** + * Sets or retrieves which dividing lines (inner borders) are displayed. + */ + /** @deprecated */ + rules: string; + /** + * Sets or retrieves a description and/or structure of the object. + */ + /** @deprecated */ + summary: string; + /** + * Retrieves a collection of all tBody objects in the table. Objects in this collection are in source order. + */ + readonly tBodies: HTMLCollectionOf; + /** + * Retrieves the tFoot object of the table. + */ + tFoot: HTMLTableSectionElement | null; + /** + * Retrieves the tHead object of the table. + */ + tHead: HTMLTableSectionElement | null; + /** + * Sets or retrieves the width of the object. + */ + /** @deprecated */ + width: string; + /** + * Creates an empty caption element in the table. + */ + createCaption(): HTMLTableCaptionElement; + /** + * Creates an empty tBody element in the table. + */ + createTBody(): HTMLTableSectionElement; + /** + * Creates an empty tFoot element in the table. + */ + createTFoot(): HTMLTableSectionElement; + /** + * Returns the tHead element object if successful, or null otherwise. + */ + createTHead(): HTMLTableSectionElement; + /** + * Deletes the caption element and its contents from the table. + */ + deleteCaption(): void; + /** + * Removes the specified row (tr) from the element and from the rows collection. + * @param index Number that specifies the zero-based position in the rows collection of the row to remove. + */ + deleteRow(index: number): void; + /** + * Deletes the tFoot element and its contents from the table. + */ + deleteTFoot(): void; + /** + * Deletes the tHead element and its contents from the table. + */ + deleteTHead(): void; + /** + * Creates a new row (tr) in the table, and adds the row to the rows collection. + * @param index Number that specifies where to insert the row in the rows collection. The default value is -1, which appends the new row to the end of the rows collection. + */ + insertRow(index?: number): HTMLTableRowElement; + addEventListener(type: K, listener: (this: HTMLTableElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLTableElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLTableElement: { + prototype: HTMLTableElement; + new(): HTMLTableElement; +}; + +interface HTMLTableHeaderCellElement extends HTMLTableCellElement { + scope: string; + addEventListener(type: K, listener: (this: HTMLTableHeaderCellElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLTableHeaderCellElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLTableHeaderCellElement: { + prototype: HTMLTableHeaderCellElement; + new(): HTMLTableHeaderCellElement; +}; + +interface HTMLTableRowElement extends HTMLElement { + /** + * Sets or retrieves how the object is aligned with adjacent text. + */ + /** @deprecated */ + align: string; + /** @deprecated */ + bgColor: string; + /** + * Retrieves a collection of all cells in the table row. + */ + readonly cells: HTMLCollectionOf; + /** @deprecated */ + ch: string; + /** @deprecated */ + chOff: string; + /** + * Retrieves the position of the object in the rows collection for the table. + */ + readonly rowIndex: number; + /** + * Retrieves the position of the object in the collection. + */ + readonly sectionRowIndex: number; + /** @deprecated */ + vAlign: string; + /** + * Removes the specified cell from the table row, as well as from the cells collection. + * @param index Number that specifies the zero-based position of the cell to remove from the table row. If no value is provided, the last cell in the cells collection is deleted. + */ + deleteCell(index: number): void; + /** + * Creates a new cell in the table row, and adds the cell to the cells collection. + * @param index Number that specifies where to insert the cell in the tr. The default value is -1, which appends the new cell to the end of the cells collection. + */ + insertCell(index?: number): HTMLTableDataCellElement; + addEventListener(type: K, listener: (this: HTMLTableRowElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLTableRowElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLTableRowElement: { + prototype: HTMLTableRowElement; + new(): HTMLTableRowElement; +}; + +interface HTMLTableSectionElement extends HTMLElement { + /** + * Sets or retrieves a value that indicates the table alignment. + */ + /** @deprecated */ + align: string; + /** @deprecated */ + ch: string; + /** @deprecated */ + chOff: string; + /** + * Sets or retrieves the number of horizontal rows contained in the object. + */ + readonly rows: HTMLCollectionOf; + /** @deprecated */ + vAlign: string; + /** + * Removes the specified row (tr) from the element and from the rows collection. + * @param index Number that specifies the zero-based position in the rows collection of the row to remove. + */ + deleteRow(index: number): void; + /** + * Creates a new row (tr) in the table, and adds the row to the rows collection. + * @param index Number that specifies where to insert the row in the rows collection. The default value is -1, which appends the new row to the end of the rows collection. + */ + insertRow(index?: number): HTMLTableRowElement; + addEventListener(type: K, listener: (this: HTMLTableSectionElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLTableSectionElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLTableSectionElement: { + prototype: HTMLTableSectionElement; + new(): HTMLTableSectionElement; +}; + +interface HTMLTemplateElement extends HTMLElement { + readonly content: DocumentFragment; + addEventListener(type: K, listener: (this: HTMLTemplateElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLTemplateElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLTemplateElement: { + prototype: HTMLTemplateElement; + new(): HTMLTemplateElement; +}; + +interface HTMLTextAreaElement extends HTMLElement { + autocomplete: string; + /** + * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing. + */ + autofocus: boolean; + /** + * Sets or retrieves the width of the object. + */ + cols: number; + /** + * Sets or retrieves the initial contents of the object. + */ + defaultValue: string; + dirName: string; + disabled: boolean; + /** + * Retrieves a reference to the form that the object is embedded in. + */ + readonly form: HTMLFormElement | null; + readonly labels: NodeListOf; + /** + * Sets or retrieves the maximum number of characters that the user can enter in a text control. + */ + maxLength: number; + minLength: number; + /** + * Sets or retrieves the name of the object. + */ + name: string; + /** + * Gets or sets a text string that is displayed in an input field as a hint or prompt to users as the format or type of information they need to enter.The text appears in an input field until the user puts focus on the field. + */ + placeholder: string; + /** + * Sets or retrieves the value indicated whether the content of the object is read-only. + */ + readOnly: boolean; + /** + * When present, marks an element that can't be submitted without a value. + */ + required: boolean; + /** + * Sets or retrieves the number of horizontal rows contained in the object. + */ + rows: number; + selectionDirection: string; + /** + * Gets or sets the end position or offset of a text selection. + */ + selectionEnd: number; + /** + * Gets or sets the starting position or offset of a text selection. + */ + selectionStart: number; + readonly textLength: number; + /** + * Retrieves the type of control. + */ + readonly type: string; + /** + * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. + */ + readonly validationMessage: string; + /** + * Returns a ValidityState object that represents the validity states of an element. + */ + readonly validity: ValidityState; + /** + * Retrieves or sets the text in the entry field of the textArea element. + */ + value: string; + /** + * Returns whether an element will successfully validate based on forms validation rules and constraints. + */ + readonly willValidate: boolean; + /** + * Sets or retrieves how to handle wordwrapping in the object. + */ + wrap: string; + /** + * Returns whether a form will validate when it is submitted, without having to submit it. + */ + checkValidity(): boolean; + reportValidity(): boolean; + /** + * Highlights the input area of a form element. + */ + select(): void; + /** + * Sets a custom error message that is displayed when a form is submitted. + * @param error Sets a custom error message that is displayed when a form is submitted. + */ + setCustomValidity(error: string): void; + setRangeText(replacement: string): void; + setRangeText(replacement: string, start: number, end: number, selectionMode?: SelectionMode): void; + /** + * Sets the start and end positions of a selection in a text field. + * @param start The offset into the text field for the start of the selection. + * @param end The offset into the text field for the end of the selection. + * @param direction The direction in which the selection is performed. + */ + setSelectionRange(start: number, end: number, direction?: "forward" | "backward" | "none"): void; + addEventListener(type: K, listener: (this: HTMLTextAreaElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLTextAreaElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLTextAreaElement: { + prototype: HTMLTextAreaElement; + new(): HTMLTextAreaElement; +}; + +interface HTMLTimeElement extends HTMLElement { + dateTime: string; + addEventListener(type: K, listener: (this: HTMLTimeElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLTimeElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLTimeElement: { + prototype: HTMLTimeElement; + new(): HTMLTimeElement; +}; + +interface HTMLTitleElement extends HTMLElement { + /** + * Retrieves or sets the text of the object as a string. + */ + text: string; + addEventListener(type: K, listener: (this: HTMLTitleElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLTitleElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLTitleElement: { + prototype: HTMLTitleElement; + new(): HTMLTitleElement; +}; + +interface HTMLTrackElement extends HTMLElement { + default: boolean; + kind: string; + label: string; + readonly readyState: number; + src: string; + srclang: string; + readonly track: TextTrack; + readonly ERROR: number; + readonly LOADED: number; + readonly LOADING: number; + readonly NONE: number; + addEventListener(type: K, listener: (this: HTMLTrackElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLTrackElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLTrackElement: { + prototype: HTMLTrackElement; + new(): HTMLTrackElement; + readonly ERROR: number; + readonly LOADED: number; + readonly LOADING: number; + readonly NONE: number; +}; + +interface HTMLUListElement extends HTMLElement { + /** @deprecated */ + compact: boolean; + /** @deprecated */ + type: string; + addEventListener(type: K, listener: (this: HTMLUListElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLUListElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLUListElement: { + prototype: HTMLUListElement; + new(): HTMLUListElement; +}; + +interface HTMLUnknownElement extends HTMLElement { + addEventListener(type: K, listener: (this: HTMLUnknownElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLUnknownElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLUnknownElement: { + prototype: HTMLUnknownElement; + new(): HTMLUnknownElement; +}; + +interface HTMLVideoElementEventMap extends HTMLMediaElementEventMap { + "MSVideoFormatChanged": Event; + "MSVideoFrameStepCompleted": Event; + "MSVideoOptimalLayoutChanged": Event; +} + +interface HTMLVideoElement extends HTMLMediaElement { + /** + * Gets or sets the height of the video element. + */ + height: number; + msHorizontalMirror: boolean; + readonly msIsLayoutOptimalForPlayback: boolean; + readonly msIsStereo3D: boolean; + msStereo3DPackingMode: string; + msStereo3DRenderMode: string; + msZoom: boolean; + onMSVideoFormatChanged: ((this: HTMLVideoElement, ev: Event) => any) | null; + onMSVideoFrameStepCompleted: ((this: HTMLVideoElement, ev: Event) => any) | null; + onMSVideoOptimalLayoutChanged: ((this: HTMLVideoElement, ev: Event) => any) | null; + /** + * Gets or sets a URL of an image to display, for example, like a movie poster. This can be a still frame from the video, or another image if no video data is available. + */ + poster: string; + /** + * Gets the intrinsic height of a video in CSS pixels, or zero if the dimensions are not known. + */ + readonly videoHeight: number; + /** + * Gets the intrinsic width of a video in CSS pixels, or zero if the dimensions are not known. + */ + readonly videoWidth: number; + readonly webkitDisplayingFullscreen: boolean; + readonly webkitSupportsFullscreen: boolean; + /** + * Gets or sets the width of the video element. + */ + width: number; + getVideoPlaybackQuality(): VideoPlaybackQuality; + msFrameStep(forward: boolean): void; + msInsertVideoEffect(activatableClassId: string, effectRequired: boolean, config?: any): void; + msSetVideoRectangle(left: number, top: number, right: number, bottom: number): void; + webkitEnterFullScreen(): void; + webkitEnterFullscreen(): void; + webkitExitFullScreen(): void; + webkitExitFullscreen(): void; + addEventListener(type: K, listener: (this: HTMLVideoElement, ev: HTMLVideoElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLVideoElement, ev: HTMLVideoElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLVideoElement: { + prototype: HTMLVideoElement; + new(): HTMLVideoElement; +}; + +interface HashChangeEvent extends Event { + readonly newURL: string; + readonly oldURL: string; +} + +declare var HashChangeEvent: { + prototype: HashChangeEvent; + new(type: string, eventInitDict?: HashChangeEventInit): HashChangeEvent; +}; + +interface Headers { + append(name: string, value: string): void; + delete(name: string): void; + get(name: string): string | null; + has(name: string): boolean; + set(name: string, value: string): void; + forEach(callbackfn: (value: string, key: string, parent: Headers) => void, thisArg?: any): void; +} + +declare var Headers: { + prototype: Headers; + new(init?: HeadersInit): Headers; +}; + +interface History { + readonly length: number; + scrollRestoration: ScrollRestoration; + readonly state: any; + back(): void; + forward(): void; + go(delta?: number): void; + pushState(data: any, title: string, url?: string | null): void; + replaceState(data: any, title: string, url?: string | null): void; +} + +declare var History: { + prototype: History; + new(): History; +}; + +interface HkdfCtrParams extends Algorithm { + context: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer; + hash: string | Algorithm; + label: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer; +} + +interface IDBArrayKey extends Array { +} + +interface IDBCursor { + /** + * Returns the direction ("next", "nextunique", "prev" or "prevunique") + * of the cursor. + */ + readonly direction: IDBCursorDirection; + /** + * Returns the key of the cursor. + * Throws a "InvalidStateError" DOMException if the cursor is advancing or is finished. + */ + readonly key: IDBValidKey | IDBKeyRange; + /** + * Returns the effective key of the cursor. + * Throws a "InvalidStateError" DOMException if the cursor is advancing or is finished. + */ + readonly primaryKey: IDBValidKey | IDBKeyRange; + /** + * Returns the IDBObjectStore or IDBIndex the cursor was opened from. + */ + readonly source: IDBObjectStore | IDBIndex; + /** + * Advances the cursor through the next count records in + * range. + */ + advance(count: number): void; + /** + * Advances the cursor to the next record in range matching or + * after key. + */ + continue(key?: IDBValidKey | IDBKeyRange): void; + /** + * Advances the cursor to the next record in range matching + * or after key and primaryKey. Throws an "InvalidAccessError" DOMException if the source is not an index. + */ + continuePrimaryKey(key: IDBValidKey | IDBKeyRange, primaryKey: IDBValidKey | IDBKeyRange): void; + /** + * Delete the record pointed at by the cursor with a new value. + * If successful, request's result will be undefined. + */ + delete(): IDBRequest; + /** + * Updated the record pointed at by the cursor with a new value. + * Throws a "DataError" DOMException if the effective object store uses in-line keys and the key would have changed. + * If successful, request's result will be the record's key. + */ + update(value: any): IDBRequest; +} + +declare var IDBCursor: { + prototype: IDBCursor; + new(): IDBCursor; +}; + +interface IDBCursorWithValue extends IDBCursor { + /** + * Returns the cursor's current value. + */ + readonly value: any; +} + +declare var IDBCursorWithValue: { + prototype: IDBCursorWithValue; + new(): IDBCursorWithValue; +}; + +interface IDBDatabaseEventMap { + "abort": Event; + "close": Event; + "error": Event; + "versionchange": IDBVersionChangeEvent; +} + +interface IDBDatabase extends EventTarget { + /** + * Returns the name of the database. + */ + readonly name: string; + /** + * Returns a list of the names of object stores in the database. + */ + readonly objectStoreNames: DOMStringList; + onabort: ((this: IDBDatabase, ev: Event) => any) | null; + onclose: ((this: IDBDatabase, ev: Event) => any) | null; + onerror: ((this: IDBDatabase, ev: Event) => any) | null; + onversionchange: ((this: IDBDatabase, ev: IDBVersionChangeEvent) => any) | null; + /** + * Returns the version of the database. + */ + readonly version: number; + /** + * Closes the connection once all running transactions have finished. + */ + close(): void; + /** + * Creates a new object store with the given name and options and returns a new IDBObjectStore. + * Throws a "InvalidStateError" DOMException if not called within an upgrade transaction. + */ + createObjectStore(name: string, optionalParameters?: IDBObjectStoreParameters): IDBObjectStore; + /** + * Deletes the object store with the given name. + * Throws a "InvalidStateError" DOMException if not called within an upgrade transaction. + */ + deleteObjectStore(name: string): void; + /** + * Returns a new transaction with the given mode ("readonly" or "readwrite") + * and scope which can be a single object store name or an array of names. + */ + transaction(storeNames: string | string[], mode?: IDBTransactionMode): IDBTransaction; + addEventListener(type: K, listener: (this: IDBDatabase, ev: IDBDatabaseEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: IDBDatabase, ev: IDBDatabaseEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var IDBDatabase: { + prototype: IDBDatabase; + new(): IDBDatabase; +}; + +interface IDBEnvironment { + readonly indexedDB: IDBFactory; +} + +interface IDBFactory { + /** + * Compares two values as keys. Returns -1 if key1 precedes key2, 1 if key2 precedes key1, and 0 if + * the keys are equal. + * Throws a "DataError" DOMException if either input is not a valid key. + */ + cmp(first: any, second: any): number; + /** + * Attempts to delete the named database. If the + * database already exists and there are open connections that don't close in response to a versionchange event, the request will be blocked until all they close. If the request + * is successful request's result will be null. + */ + deleteDatabase(name: string): IDBOpenDBRequest; + /** + * Attempts to open a connection to the named database with the specified version. If the database already exists + * with a lower version and there are open connections that don't close in response to a versionchange event, the request will be blocked until all they close, then an upgrade + * will occur. If the database already exists with a higher + * version the request will fail. If the request is + * successful request's result will + * be the connection. + */ + open(name: string, version?: number): IDBOpenDBRequest; +} + +declare var IDBFactory: { + prototype: IDBFactory; + new(): IDBFactory; +}; + +interface IDBIndex { + readonly keyPath: string | string[]; + readonly multiEntry: boolean; + /** + * Updates the name of the store to newName. + * Throws an "InvalidStateError" DOMException if not called within an upgrade + * transaction. + */ + name: string; + /** + * Returns the IDBObjectStore the index belongs to. + */ + readonly objectStore: IDBObjectStore; + readonly unique: boolean; + /** + * Retrieves the number of records matching the given key or key range in query. + * If successful, request's result will be the + * count. + */ + count(key?: IDBValidKey | IDBKeyRange): IDBRequest; + /** + * Retrieves the value of the first record matching the + * given key or key range in query. + * If successful, request's result will be the value, or undefined if there was no matching record. + */ + get(key: IDBValidKey | IDBKeyRange): IDBRequest; + /** + * Retrieves the values of the records matching the given key or key range in query (up to count if given). + * If successful, request's result will be an Array of the values. + */ + getAll(query?: IDBValidKey | IDBKeyRange, count?: number): IDBRequest; + /** + * Retrieves the keys of records matching the given key or key range in query (up to count if given). + * If successful, request's result will be an Array of the keys. + */ + getAllKeys(query?: IDBValidKey | IDBKeyRange, count?: number): IDBRequest; + /** + * Retrieves the key of the first record matching the + * given key or key range in query. + * If successful, request's result will be the key, or undefined if there was no matching record. + */ + getKey(key: IDBValidKey | IDBKeyRange): IDBRequest; + /** + * Opens a cursor over the records matching query, + * ordered by direction. If query is null, all records in index are matched. + * If successful, request's result will be an IDBCursorWithValue, or null if there were no matching records. + */ + openCursor(range?: IDBValidKey | IDBKeyRange, direction?: IDBCursorDirection): IDBRequest; + /** + * Opens a cursor with key only flag set over the records matching query, ordered by direction. If query is null, all records in index are matched. + * If successful, request's result will be an IDBCursor, or null if there were no matching records. + */ + openKeyCursor(range?: IDBValidKey | IDBKeyRange, direction?: IDBCursorDirection): IDBRequest; +} + +declare var IDBIndex: { + prototype: IDBIndex; + new(): IDBIndex; +}; + +interface IDBKeyRange { + /** + * Returns lower bound, or undefined if none. + */ + readonly lower: any; + /** + * Returns true if the lower open flag is set, and false otherwise. + */ + readonly lowerOpen: boolean; + /** + * Returns upper bound, or undefined if none. + */ + readonly upper: any; + /** + * Returns true if the upper open flag is set, and false otherwise. + */ + readonly upperOpen: boolean; + /** + * Returns true if key is included in the range, and false otherwise. + */ + includes(key: any): boolean; +} + +declare var IDBKeyRange: { + prototype: IDBKeyRange; + new(): IDBKeyRange; + /** + * Returns a new IDBKeyRange spanning from lower to upper. + * If lowerOpen is true, lower is not included in the range. + * If upperOpen is true, upper is not included in the range. + */ + bound(lower: any, upper: any, lowerOpen?: boolean, upperOpen?: boolean): IDBKeyRange; + /** + * Returns a new IDBKeyRange starting at key with no + * upper bound. If open is true, key is not included in the + * range. + */ + lowerBound(lower: any, open?: boolean): IDBKeyRange; + /** + * Returns a new IDBKeyRange spanning only key. + */ + only(value: any): IDBKeyRange; + /** + * Returns a new IDBKeyRange with no lower bound and ending at key. If open is true, key is not included in the range. + */ + upperBound(upper: any, open?: boolean): IDBKeyRange; +}; + +interface IDBObjectStore { + /** + * Returns true if the store has a key generator, and false otherwise. + */ + readonly autoIncrement: boolean; + /** + * Returns a list of the names of indexes in the store. + */ + readonly indexNames: DOMStringList; + /** + * Returns the key path of the store, or null if none. + */ + readonly keyPath: string | string[]; + /** + * Updates the name of the store to newName. + * Throws "InvalidStateError" DOMException if not called within an upgrade + * transaction. + */ + name: string; + /** + * Returns the associated transaction. + */ + readonly transaction: IDBTransaction; + add(value: any, key?: IDBValidKey | IDBKeyRange): IDBRequest; + /** + * Deletes all records in store. + * If successful, request's result will + * be undefined. + */ + clear(): IDBRequest; + /** + * Retrieves the number of records matching the + * given key or key range in query. + * If successful, request's result will be the count. + */ + count(key?: IDBValidKey | IDBKeyRange): IDBRequest; + /** + * Creates a new index in store with the given name, keyPath and options and returns a new IDBIndex. If the keyPath and options define constraints that cannot be + * satisfied with the data already in store the upgrade + * transaction will abort with + * a "ConstraintError" DOMException. + * Throws an "InvalidStateError" DOMException if not called within an upgrade + * transaction. + */ + createIndex(name: string, keyPath: string | string[], options?: IDBIndexParameters): IDBIndex; + /** + * Deletes records in store with the given key or in the given key range in query. + * If successful, request's result will + * be undefined. + */ + delete(key: IDBValidKey | IDBKeyRange): IDBRequest; + /** + * Deletes the index in store with the given name. + * Throws an "InvalidStateError" DOMException if not called within an upgrade + * transaction. + */ + deleteIndex(name: string): void; + /** + * Retrieves the value of the first record matching the + * given key or key range in query. + * If successful, request's result will be the value, or undefined if there was no matching record. + */ + get(query: IDBValidKey | IDBKeyRange): IDBRequest; + /** + * Retrieves the values of the records matching the + * given key or key range in query (up to count if given). + * If successful, request's result will + * be an Array of the values. + */ + getAll(query?: IDBValidKey | IDBKeyRange, count?: number): IDBRequest; + /** + * Retrieves the keys of records matching the + * given key or key range in query (up to count if given). + * If successful, request's result will + * be an Array of the keys. + */ + getAllKeys(query?: IDBValidKey | IDBKeyRange, count?: number): IDBRequest; + /** + * Retrieves the key of the first record matching the + * given key or key range in query. + * If successful, request's result will be the key, or undefined if there was no matching record. + */ + getKey(query: IDBValidKey | IDBKeyRange): IDBRequest; + index(name: string): IDBIndex; + /** + * Opens a cursor over the records matching query, + * ordered by direction. If query is null, all records in store are matched. + * If successful, request's result will be an IDBCursorWithValue pointing at the first matching record, or null if there were no matching records. + */ + openCursor(range?: IDBValidKey | IDBKeyRange, direction?: IDBCursorDirection): IDBRequest; + /** + * Opens a cursor with key only flag set over the records matching query, ordered by direction. If query is null, all records in store are matched. + * If successful, request's result will be an IDBCursor pointing at the first matching record, or + * null if there were no matching records. + */ + openKeyCursor(query?: IDBValidKey | IDBKeyRange, direction?: IDBCursorDirection): IDBRequest; + put(value: any, key?: IDBValidKey | IDBKeyRange): IDBRequest; +} + +declare var IDBObjectStore: { + prototype: IDBObjectStore; + new(): IDBObjectStore; +}; + +interface IDBOpenDBRequestEventMap extends IDBRequestEventMap { + "blocked": Event; + "upgradeneeded": IDBVersionChangeEvent; +} + +interface IDBOpenDBRequest extends IDBRequest { + onblocked: ((this: IDBOpenDBRequest, ev: Event) => any) | null; + onupgradeneeded: ((this: IDBOpenDBRequest, ev: IDBVersionChangeEvent) => any) | null; + addEventListener(type: K, listener: (this: IDBOpenDBRequest, ev: IDBOpenDBRequestEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: IDBOpenDBRequest, ev: IDBOpenDBRequestEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var IDBOpenDBRequest: { + prototype: IDBOpenDBRequest; + new(): IDBOpenDBRequest; +}; + +interface IDBRequestEventMap { + "error": Event; + "success": Event; +} + +interface IDBRequest extends EventTarget { + /** + * When a request is completed, returns the error (a DOMException), or null if the request succeeded. Throws + * a "InvalidStateError" DOMException if the request is still pending. + */ + readonly error: DOMException | null; + onerror: ((this: IDBRequest, ev: Event) => any) | null; + onsuccess: ((this: IDBRequest, ev: Event) => any) | null; + /** + * Returns "pending" until a request is complete, + * then returns "done". + */ + readonly readyState: IDBRequestReadyState; + /** + * When a request is completed, returns the result, + * or undefined if the request failed. Throws a + * "InvalidStateError" DOMException if the request is still pending. + */ + readonly result: T; + /** + * Returns the IDBObjectStore, IDBIndex, or IDBCursor the request was made against, or null if is was an open + * request. + */ + readonly source: IDBObjectStore | IDBIndex | IDBCursor; + /** + * Returns the IDBTransaction the request was made within. + * If this as an open request, then it returns an upgrade transaction while it is running, or null otherwise. + */ + readonly transaction: IDBTransaction | null; + addEventListener(type: K, listener: (this: IDBRequest, ev: IDBRequestEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: IDBRequest, ev: IDBRequestEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var IDBRequest: { + prototype: IDBRequest; + new(): IDBRequest; +}; + +interface IDBTransactionEventMap { + "abort": Event; + "complete": Event; + "error": Event; +} + +interface IDBTransaction extends EventTarget { + /** + * Returns the transaction's connection. + */ + readonly db: IDBDatabase; + /** + * If the transaction was aborted, returns the + * error (a DOMException) providing the reason. + */ + readonly error: DOMException; + /** + * Returns the mode the transaction was created with + * ("readonly" or "readwrite"), or "versionchange" for + * an upgrade transaction. + */ + readonly mode: IDBTransactionMode; + /** + * Returns a list of the names of object stores in the + * transaction's scope. For an upgrade transaction this is all object stores in the database. + */ + readonly objectStoreNames: DOMStringList; + onabort: ((this: IDBTransaction, ev: Event) => any) | null; + oncomplete: ((this: IDBTransaction, ev: Event) => any) | null; + onerror: ((this: IDBTransaction, ev: Event) => any) | null; + /** + * Aborts the transaction. All pending requests will fail with + * a "AbortError" DOMException and all changes made to the database will be + * reverted. + */ + abort(): void; + /** + * Returns an IDBObjectStore in the transaction's scope. + */ + objectStore(name: string): IDBObjectStore; + addEventListener(type: K, listener: (this: IDBTransaction, ev: IDBTransactionEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: IDBTransaction, ev: IDBTransactionEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var IDBTransaction: { + prototype: IDBTransaction; + new(): IDBTransaction; +}; + +interface IDBVersionChangeEvent extends Event { + readonly newVersion: number | null; + readonly oldVersion: number; +} + +declare var IDBVersionChangeEvent: { + prototype: IDBVersionChangeEvent; + new(type: string, eventInitDict?: IDBVersionChangeEventInit): IDBVersionChangeEvent; +}; + +interface IIRFilterNode extends AudioNode { + getFrequencyResponse(frequencyHz: Float32Array, magResponse: Float32Array, phaseResponse: Float32Array): void; +} + +declare var IIRFilterNode: { + prototype: IIRFilterNode; + new(context: BaseAudioContext, options: IIRFilterOptions): IIRFilterNode; +}; + +interface ImageBitmap { + /** + * Returns the intrinsic height of the image, in CSS + * pixels. + */ + readonly height: number; + /** + * Returns the intrinsic width of the image, in CSS + * pixels. + */ + readonly width: number; + /** + * Releases imageBitmap's underlying bitmap data. + */ + close(): void; +} + +declare var ImageBitmap: { + prototype: ImageBitmap; + new(): ImageBitmap; +}; + +interface ImageBitmapOptions { + colorSpaceConversion?: "none" | "default"; + imageOrientation?: "none" | "flipY"; + premultiplyAlpha?: "none" | "premultiply" | "default"; + resizeHeight?: number; + resizeQuality?: "pixelated" | "low" | "medium" | "high"; + resizeWidth?: number; +} + +interface ImageBitmapRenderingContext { + /** + * Returns the canvas element that the context is bound to. + */ + readonly canvas: HTMLCanvasElement; + /** + * Replaces contents of the canvas element to which context + * is bound with a transparent black bitmap whose size corresponds to the width and height + * content attributes of the canvas element. + */ + transferFromImageBitmap(bitmap: ImageBitmap | null): void; +} + +declare var ImageBitmapRenderingContext: { + prototype: ImageBitmapRenderingContext; + new(): ImageBitmapRenderingContext; +}; + +interface ImageData { + /** + * Returns the one-dimensional array containing the data in RGBA order, as integers in the + * range 0 to 255. + */ + readonly data: Uint8ClampedArray; + /** + * Returns the actual dimensions of the data in the ImageData object, in + * pixels. + */ + readonly height: number; + readonly width: number; +} + +declare var ImageData: { + prototype: ImageData; + new(width: number, height: number): ImageData; + new(array: Uint8ClampedArray, width: number, height: number): ImageData; +}; + +interface IntersectionObserver { + readonly root: Element | null; + readonly rootMargin: string; + readonly thresholds: number[]; + disconnect(): void; + observe(target: Element): void; + takeRecords(): IntersectionObserverEntry[]; + unobserve(target: Element): void; +} + +declare var IntersectionObserver: { + prototype: IntersectionObserver; + new(callback: IntersectionObserverCallback, options?: IntersectionObserverInit): IntersectionObserver; +}; + +interface IntersectionObserverEntry { + readonly boundingClientRect: ClientRect | DOMRect; + readonly intersectionRatio: number; + readonly intersectionRect: ClientRect | DOMRect; + readonly isIntersecting: boolean; + readonly rootBounds: ClientRect | DOMRect; + readonly target: Element; + readonly time: number; +} + +declare var IntersectionObserverEntry: { + prototype: IntersectionObserverEntry; + new(intersectionObserverEntryInit: IntersectionObserverEntryInit): IntersectionObserverEntry; +}; + +interface KeyboardEvent extends UIEvent { + readonly altKey: boolean; + /** @deprecated */ + char: string; + /** @deprecated */ + readonly charCode: number; + readonly code: string; + readonly ctrlKey: boolean; + readonly key: string; + /** @deprecated */ + readonly keyCode: number; + readonly location: number; + readonly metaKey: boolean; + readonly repeat: boolean; + readonly shiftKey: boolean; + /** @deprecated */ + readonly which: number; + getModifierState(keyArg: string): boolean; + /** @deprecated */ + initKeyboardEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, keyArg: string, locationArg: number, modifiersListArg: string, repeat: boolean, locale: string): void; + readonly DOM_KEY_LOCATION_JOYSTICK: number; + readonly DOM_KEY_LOCATION_LEFT: number; + readonly DOM_KEY_LOCATION_MOBILE: number; + readonly DOM_KEY_LOCATION_NUMPAD: number; + readonly DOM_KEY_LOCATION_RIGHT: number; + readonly DOM_KEY_LOCATION_STANDARD: number; +} + +declare var KeyboardEvent: { + prototype: KeyboardEvent; + new(typeArg: string, eventInitDict?: KeyboardEventInit): KeyboardEvent; + readonly DOM_KEY_LOCATION_JOYSTICK: number; + readonly DOM_KEY_LOCATION_LEFT: number; + readonly DOM_KEY_LOCATION_MOBILE: number; + readonly DOM_KEY_LOCATION_NUMPAD: number; + readonly DOM_KEY_LOCATION_RIGHT: number; + readonly DOM_KEY_LOCATION_STANDARD: number; +}; + +interface KeyframeEffect extends AnimationEffect { + composite: CompositeOperation; + iterationComposite: IterationCompositeOperation; + target: Element | null; + getKeyframes(): ComputedKeyframe[]; + setKeyframes(keyframes: Keyframe[] | PropertyIndexedKeyframes | null): void; +} + +declare var KeyframeEffect: { + prototype: KeyframeEffect; + new(target: Element | null, keyframes: Keyframe[] | PropertyIndexedKeyframes | null, options?: number | KeyframeEffectOptions): KeyframeEffect; + new(source: KeyframeEffect): KeyframeEffect; +}; + +interface LinkStyle { + readonly sheet: StyleSheet | null; +} + +interface ListeningStateChangedEvent extends Event { + readonly label: string; + readonly state: ListeningState; +} + +declare var ListeningStateChangedEvent: { + prototype: ListeningStateChangedEvent; + new(): ListeningStateChangedEvent; +}; + +interface Location { + /** + * Returns a DOMStringList object listing the origins of the ancestor browsing contexts, from the parent browsing + * context to the top-level browsing context. + */ + readonly ancestorOrigins: DOMStringList; + /** + * Returns the Location object's URL's fragment (includes leading "#" if non-empty). + * Can be set, to navigate to the same URL with a changed fragment (ignores leading "#"). + */ + hash: string; + /** + * Returns the Location object's URL's host and port (if different from the default + * port for the scheme). + * Can be set, to navigate to the same URL with a changed host and port. + */ + host: string; + /** + * Returns the Location object's URL's host. + * Can be set, to navigate to the same URL with a changed host. + */ + hostname: string; + /** + * Returns the Location object's URL. + * Can be set, to navigate to the given URL. + */ + href: string; + /** + * Returns the Location object's URL's origin. + */ + readonly origin: string; + /** + * Returns the Location object's URL's path. + * Can be set, to navigate to the same URL with a changed path. + */ + pathname: string; + /** + * Returns the Location object's URL's port. + * Can be set, to navigate to the same URL with a changed port. + */ + port: string; + /** + * Returns the Location object's URL's scheme. + * Can be set, to navigate to the same URL with a changed scheme. + */ + protocol: string; + /** + * Returns the Location object's URL's query (includes leading "?" if non-empty). + * Can be set, to navigate to the same URL with a changed query (ignores leading "?"). + */ + search: string; + /** + * Navigates to the given URL. + */ + assign(url: string): void; + /** + * Reloads the current page. + */ + reload(): void; + /** @deprecated */ + reload(forcedReload: boolean): void; + /** + * Removes the current page from the session history and navigates to the given URL. + */ + replace(url: string): void; +} + +declare var Location: { + prototype: Location; + new(): Location; +}; + +interface MSAssertion { + readonly id: string; + readonly type: MSCredentialType; +} + +declare var MSAssertion: { + prototype: MSAssertion; + new(): MSAssertion; +}; + +interface MSBlobBuilder { + append(data: any, endings?: string): void; + getBlob(contentType?: string): Blob; +} + +declare var MSBlobBuilder: { + prototype: MSBlobBuilder; + new(): MSBlobBuilder; +}; + +interface MSFIDOCredentialAssertion extends MSAssertion { + readonly algorithm: string | Algorithm; + readonly attestation: any; + readonly publicKey: string; + readonly transportHints: MSTransportType[]; +} + +declare var MSFIDOCredentialAssertion: { + prototype: MSFIDOCredentialAssertion; + new(): MSFIDOCredentialAssertion; +}; + +interface MSFIDOSignature { + readonly authnrData: string; + readonly clientData: string; + readonly signature: string; +} + +declare var MSFIDOSignature: { + prototype: MSFIDOSignature; + new(): MSFIDOSignature; +}; + +interface MSFIDOSignatureAssertion extends MSAssertion { + readonly signature: MSFIDOSignature; +} + +declare var MSFIDOSignatureAssertion: { + prototype: MSFIDOSignatureAssertion; + new(): MSFIDOSignatureAssertion; +}; + +interface MSFileSaver { + msSaveBlob(blob: any, defaultName?: string): boolean; + msSaveOrOpenBlob(blob: any, defaultName?: string): boolean; +} + +interface MSGesture { + target: Element; + addPointer(pointerId: number): void; + stop(): void; +} + +declare var MSGesture: { + prototype: MSGesture; + new(): MSGesture; +}; + +interface MSGestureEvent extends UIEvent { + readonly clientX: number; + readonly clientY: number; + readonly expansion: number; + readonly gestureObject: any; + readonly hwTimestamp: number; + readonly offsetX: number; + readonly offsetY: number; + readonly rotation: number; + readonly scale: number; + readonly screenX: number; + readonly screenY: number; + readonly translationX: number; + readonly translationY: number; + readonly velocityAngular: number; + readonly velocityExpansion: number; + readonly velocityX: number; + readonly velocityY: number; + initGestureEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, offsetXArg: number, offsetYArg: number, translationXArg: number, translationYArg: number, scaleArg: number, expansionArg: number, rotationArg: number, velocityXArg: number, velocityYArg: number, velocityExpansionArg: number, velocityAngularArg: number, hwTimestampArg: number): void; + readonly MSGESTURE_FLAG_BEGIN: number; + readonly MSGESTURE_FLAG_CANCEL: number; + readonly MSGESTURE_FLAG_END: number; + readonly MSGESTURE_FLAG_INERTIA: number; + readonly MSGESTURE_FLAG_NONE: number; +} + +declare var MSGestureEvent: { + prototype: MSGestureEvent; + new(): MSGestureEvent; + readonly MSGESTURE_FLAG_BEGIN: number; + readonly MSGESTURE_FLAG_CANCEL: number; + readonly MSGESTURE_FLAG_END: number; + readonly MSGESTURE_FLAG_INERTIA: number; + readonly MSGESTURE_FLAG_NONE: number; +}; + +interface MSGraphicsTrust { + readonly constrictionActive: boolean; + readonly status: string; +} + +declare var MSGraphicsTrust: { + prototype: MSGraphicsTrust; + new(): MSGraphicsTrust; +}; + +interface MSInputMethodContextEventMap { + "MSCandidateWindowHide": Event; + "MSCandidateWindowShow": Event; + "MSCandidateWindowUpdate": Event; +} + +interface MSInputMethodContext extends EventTarget { + readonly compositionEndOffset: number; + readonly compositionStartOffset: number; + oncandidatewindowhide: ((this: MSInputMethodContext, ev: Event) => any) | null; + oncandidatewindowshow: ((this: MSInputMethodContext, ev: Event) => any) | null; + oncandidatewindowupdate: ((this: MSInputMethodContext, ev: Event) => any) | null; + readonly target: HTMLElement; + getCandidateWindowClientRect(): ClientRect; + getCompositionAlternatives(): string[]; + hasComposition(): boolean; + isCandidateWindowVisible(): boolean; + addEventListener(type: K, listener: (this: MSInputMethodContext, ev: MSInputMethodContextEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: MSInputMethodContext, ev: MSInputMethodContextEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var MSInputMethodContext: { + prototype: MSInputMethodContext; + new(): MSInputMethodContext; +}; + +interface MSMediaKeyError { + readonly code: number; + readonly systemCode: number; + readonly MS_MEDIA_KEYERR_CLIENT: number; + readonly MS_MEDIA_KEYERR_DOMAIN: number; + readonly MS_MEDIA_KEYERR_HARDWARECHANGE: number; + readonly MS_MEDIA_KEYERR_OUTPUT: number; + readonly MS_MEDIA_KEYERR_SERVICE: number; + readonly MS_MEDIA_KEYERR_UNKNOWN: number; +} + +declare var MSMediaKeyError: { + prototype: MSMediaKeyError; + new(): MSMediaKeyError; + readonly MS_MEDIA_KEYERR_CLIENT: number; + readonly MS_MEDIA_KEYERR_DOMAIN: number; + readonly MS_MEDIA_KEYERR_HARDWARECHANGE: number; + readonly MS_MEDIA_KEYERR_OUTPUT: number; + readonly MS_MEDIA_KEYERR_SERVICE: number; + readonly MS_MEDIA_KEYERR_UNKNOWN: number; +}; + +interface MSMediaKeyMessageEvent extends Event { + readonly destinationURL: string | null; + readonly message: Uint8Array; +} + +declare var MSMediaKeyMessageEvent: { + prototype: MSMediaKeyMessageEvent; + new(): MSMediaKeyMessageEvent; +}; + +interface MSMediaKeyNeededEvent extends Event { + readonly initData: Uint8Array | null; +} + +declare var MSMediaKeyNeededEvent: { + prototype: MSMediaKeyNeededEvent; + new(): MSMediaKeyNeededEvent; +}; + +interface MSMediaKeySession extends EventTarget { + readonly error: MSMediaKeyError | null; + readonly keySystem: string; + readonly sessionId: string; + close(): void; + update(key: Uint8Array): void; +} + +declare var MSMediaKeySession: { + prototype: MSMediaKeySession; + new(): MSMediaKeySession; +}; + +interface MSMediaKeys { + readonly keySystem: string; + createSession(type: string, initData: Uint8Array, cdmData?: Uint8Array | null): MSMediaKeySession; +} + +declare var MSMediaKeys: { + prototype: MSMediaKeys; + new(keySystem: string): MSMediaKeys; + isTypeSupported(keySystem: string, type?: string | null): boolean; + isTypeSupportedWithFeatures(keySystem: string, type?: string | null): string; +}; + +interface MSNavigatorDoNotTrack { + confirmSiteSpecificTrackingException(args: ConfirmSiteSpecificExceptionsInformation): boolean; + confirmWebWideTrackingException(args: ExceptionInformation): boolean; + removeSiteSpecificTrackingException(args: ExceptionInformation): void; + removeWebWideTrackingException(args: ExceptionInformation): void; + storeSiteSpecificTrackingException(args: StoreSiteSpecificExceptionsInformation): void; + storeWebWideTrackingException(args: StoreExceptionsInformation): void; +} + +interface MSPointerEvent extends MouseEvent { + readonly currentPoint: any; + readonly height: number; + readonly hwTimestamp: number; + readonly intermediatePoints: any; + readonly isPrimary: boolean; + readonly pointerId: number; + readonly pointerType: any; + readonly pressure: number; + readonly rotation: number; + readonly tiltX: number; + readonly tiltY: number; + readonly width: number; + getCurrentPoint(element: Element): void; + getIntermediatePoints(element: Element): void; + initPointerEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, ctrlKeyArg: boolean, altKeyArg: boolean, shiftKeyArg: boolean, metaKeyArg: boolean, buttonArg: number, relatedTargetArg: EventTarget, offsetXArg: number, offsetYArg: number, widthArg: number, heightArg: number, pressure: number, rotation: number, tiltX: number, tiltY: number, pointerIdArg: number, pointerType: any, hwTimestampArg: number, isPrimary: boolean): void; +} + +declare var MSPointerEvent: { + prototype: MSPointerEvent; + new(typeArg: string, eventInitDict?: PointerEventInit): MSPointerEvent; +}; + +interface MSStream { + readonly type: string; + msClose(): void; + msDetachStream(): any; +} + +declare var MSStream: { + prototype: MSStream; + new(): MSStream; +}; + +interface MediaDeviceInfo { + readonly deviceId: string; + readonly groupId: string; + readonly kind: MediaDeviceKind; + readonly label: string; +} + +declare var MediaDeviceInfo: { + prototype: MediaDeviceInfo; + new(): MediaDeviceInfo; +}; + +interface MediaDevicesEventMap { + "devicechange": Event; +} + +interface MediaDevices extends EventTarget { + ondevicechange: ((this: MediaDevices, ev: Event) => any) | null; + enumerateDevices(): Promise; + getSupportedConstraints(): MediaTrackSupportedConstraints; + getUserMedia(constraints: MediaStreamConstraints): Promise; + addEventListener(type: K, listener: (this: MediaDevices, ev: MediaDevicesEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: MediaDevices, ev: MediaDevicesEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var MediaDevices: { + prototype: MediaDevices; + new(): MediaDevices; +}; + +interface MediaElementAudioSourceNode extends AudioNode { + readonly mediaElement: HTMLMediaElement; +} + +declare var MediaElementAudioSourceNode: { + prototype: MediaElementAudioSourceNode; + new(context: AudioContext, options: MediaElementAudioSourceOptions): MediaElementAudioSourceNode; +}; + +interface MediaEncryptedEvent extends Event { + readonly initData: ArrayBuffer | null; + readonly initDataType: string; +} + +declare var MediaEncryptedEvent: { + prototype: MediaEncryptedEvent; + new(type: string, eventInitDict?: MediaEncryptedEventInit): MediaEncryptedEvent; +}; + +interface MediaError { + readonly code: number; + readonly message: string; + readonly msExtendedCode: number; + readonly MEDIA_ERR_ABORTED: number; + readonly MEDIA_ERR_DECODE: number; + readonly MEDIA_ERR_NETWORK: number; + readonly MEDIA_ERR_SRC_NOT_SUPPORTED: number; + readonly MS_MEDIA_ERR_ENCRYPTED: number; +} + +declare var MediaError: { + prototype: MediaError; + new(): MediaError; + readonly MEDIA_ERR_ABORTED: number; + readonly MEDIA_ERR_DECODE: number; + readonly MEDIA_ERR_NETWORK: number; + readonly MEDIA_ERR_SRC_NOT_SUPPORTED: number; + readonly MS_MEDIA_ERR_ENCRYPTED: number; +}; + +interface MediaKeyMessageEvent extends Event { + readonly message: ArrayBuffer; + readonly messageType: MediaKeyMessageType; +} + +declare var MediaKeyMessageEvent: { + prototype: MediaKeyMessageEvent; + new(type: string, eventInitDict?: MediaKeyMessageEventInit): MediaKeyMessageEvent; +}; + +interface MediaKeySession extends EventTarget { + readonly closed: Promise; + readonly expiration: number; + readonly keyStatuses: MediaKeyStatusMap; + readonly sessionId: string; + close(): Promise; + generateRequest(initDataType: string, initData: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null): Promise; + load(sessionId: string): Promise; + remove(): Promise; + update(response: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null): Promise; +} + +declare var MediaKeySession: { + prototype: MediaKeySession; + new(): MediaKeySession; +}; + +interface MediaKeyStatusMap { + readonly size: number; + forEach(callback: Function, thisArg?: any): void; + get(keyId: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null): MediaKeyStatus; + has(keyId: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null): boolean; +} + +declare var MediaKeyStatusMap: { + prototype: MediaKeyStatusMap; + new(): MediaKeyStatusMap; +}; + +interface MediaKeySystemAccess { + readonly keySystem: string; + createMediaKeys(): Promise; + getConfiguration(): MediaKeySystemConfiguration; +} + +declare var MediaKeySystemAccess: { + prototype: MediaKeySystemAccess; + new(): MediaKeySystemAccess; +}; + +interface MediaKeys { + createSession(sessionType?: MediaKeySessionType): MediaKeySession; + setServerCertificate(serverCertificate: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null): Promise; +} + +declare var MediaKeys: { + prototype: MediaKeys; + new(): MediaKeys; +}; + +interface MediaList { + readonly length: number; + mediaText: string; + appendMedium(medium: string): void; + deleteMedium(medium: string): void; + item(index: number): string | null; + toString(): number; + [index: number]: string; +} + +declare var MediaList: { + prototype: MediaList; + new(): MediaList; +}; + +interface MediaQueryListEventMap { + "change": MediaQueryListEvent; +} + +interface MediaQueryList extends EventTarget { + readonly matches: boolean; + readonly media: string; + onchange: ((this: MediaQueryList, ev: MediaQueryListEvent) => any) | null; + /** @deprecated */ + addListener(listener: ((this: MediaQueryList, ev: MediaQueryListEvent) => any) | null): void; + /** @deprecated */ + removeListener(listener: ((this: MediaQueryList, ev: MediaQueryListEvent) => any) | null): void; + addEventListener(type: K, listener: (this: MediaQueryList, ev: MediaQueryListEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: MediaQueryList, ev: MediaQueryListEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var MediaQueryList: { + prototype: MediaQueryList; + new(): MediaQueryList; +}; + +interface MediaQueryListEvent extends Event { + readonly matches: boolean; + readonly media: string; +} + +declare var MediaQueryListEvent: { + prototype: MediaQueryListEvent; + new(type: string, eventInitDict?: MediaQueryListEventInit): MediaQueryListEvent; +}; + +interface MediaSource extends EventTarget { + readonly activeSourceBuffers: SourceBufferList; + duration: number; + readonly readyState: ReadyState; + readonly sourceBuffers: SourceBufferList; + addSourceBuffer(type: string): SourceBuffer; + endOfStream(error?: EndOfStreamError): void; + removeSourceBuffer(sourceBuffer: SourceBuffer): void; +} + +declare var MediaSource: { + prototype: MediaSource; + new(): MediaSource; + isTypeSupported(type: string): boolean; +}; + +interface MediaStreamEventMap { + "active": Event; + "addtrack": MediaStreamTrackEvent; + "inactive": Event; + "removetrack": MediaStreamTrackEvent; +} + +interface MediaStream extends EventTarget { + readonly active: boolean; + readonly id: string; + onactive: ((this: MediaStream, ev: Event) => any) | null; + onaddtrack: ((this: MediaStream, ev: MediaStreamTrackEvent) => any) | null; + oninactive: ((this: MediaStream, ev: Event) => any) | null; + onremovetrack: ((this: MediaStream, ev: MediaStreamTrackEvent) => any) | null; + addTrack(track: MediaStreamTrack): void; + clone(): MediaStream; + getAudioTracks(): MediaStreamTrack[]; + getTrackById(trackId: string): MediaStreamTrack | null; + getTracks(): MediaStreamTrack[]; + getVideoTracks(): MediaStreamTrack[]; + removeTrack(track: MediaStreamTrack): void; + stop(): void; + addEventListener(type: K, listener: (this: MediaStream, ev: MediaStreamEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: MediaStream, ev: MediaStreamEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var MediaStream: { + prototype: MediaStream; + new(): MediaStream; + new(stream: MediaStream): MediaStream; + new(tracks: MediaStreamTrack[]): MediaStream; +}; + +interface MediaStreamAudioDestinationNode extends AudioNode { + readonly stream: MediaStream; +} + +declare var MediaStreamAudioDestinationNode: { + prototype: MediaStreamAudioDestinationNode; + new(context: AudioContext, options?: AudioNodeOptions): MediaStreamAudioDestinationNode; +}; + +interface MediaStreamAudioSourceNode extends AudioNode { + readonly mediaStream: MediaStream; +} + +declare var MediaStreamAudioSourceNode: { + prototype: MediaStreamAudioSourceNode; + new(context: AudioContext, options: MediaStreamAudioSourceOptions): MediaStreamAudioSourceNode; +}; + +interface MediaStreamError { + readonly constraintName: string | null; + readonly message: string | null; + readonly name: string; +} + +declare var MediaStreamError: { + prototype: MediaStreamError; + new(): MediaStreamError; +}; + +interface MediaStreamErrorEvent extends Event { + readonly error: MediaStreamError | null; +} + +declare var MediaStreamErrorEvent: { + prototype: MediaStreamErrorEvent; + new(typeArg: string, eventInitDict?: MediaStreamErrorEventInit): MediaStreamErrorEvent; +}; + +interface MediaStreamEvent extends Event { + readonly stream: MediaStream | null; +} + +declare var MediaStreamEvent: { + prototype: MediaStreamEvent; + new(type: string, eventInitDict: MediaStreamEventInit): MediaStreamEvent; +}; + +interface MediaStreamTrackEventMap { + "ended": MediaStreamErrorEvent; + "isolationchange": Event; + "mute": Event; + "overconstrained": MediaStreamErrorEvent; + "unmute": Event; +} + +interface MediaStreamTrack extends EventTarget { + enabled: boolean; + readonly id: string; + readonly isolated: boolean; + readonly kind: string; + readonly label: string; + readonly muted: boolean; + onended: ((this: MediaStreamTrack, ev: MediaStreamErrorEvent) => any) | null; + onisolationchange: ((this: MediaStreamTrack, ev: Event) => any) | null; + onmute: ((this: MediaStreamTrack, ev: Event) => any) | null; + onoverconstrained: ((this: MediaStreamTrack, ev: MediaStreamErrorEvent) => any) | null; + onunmute: ((this: MediaStreamTrack, ev: Event) => any) | null; + readonly readonly: boolean; + readonly readyState: MediaStreamTrackState; + readonly remote: boolean; + applyConstraints(constraints: MediaTrackConstraints): Promise; + clone(): MediaStreamTrack; + getCapabilities(): MediaTrackCapabilities; + getConstraints(): MediaTrackConstraints; + getSettings(): MediaTrackSettings; + stop(): void; + addEventListener(type: K, listener: (this: MediaStreamTrack, ev: MediaStreamTrackEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: MediaStreamTrack, ev: MediaStreamTrackEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var MediaStreamTrack: { + prototype: MediaStreamTrack; + new(): MediaStreamTrack; +}; + +interface MediaStreamTrackAudioSourceNode extends AudioNode { +} + +declare var MediaStreamTrackAudioSourceNode: { + prototype: MediaStreamTrackAudioSourceNode; + new(context: AudioContext, options: MediaStreamTrackAudioSourceOptions): MediaStreamTrackAudioSourceNode; +}; + +interface MediaStreamTrackEvent extends Event { + readonly track: MediaStreamTrack; +} + +declare var MediaStreamTrackEvent: { + prototype: MediaStreamTrackEvent; + new(typeArg: string, eventInitDict?: MediaStreamTrackEventInit): MediaStreamTrackEvent; +}; + +interface MessageChannel { + readonly port1: MessagePort; + readonly port2: MessagePort; +} + +declare var MessageChannel: { + prototype: MessageChannel; + new(): MessageChannel; +}; + +interface MessageEvent extends Event { + /** + * Returns the data of the message. + */ + readonly data: any; + /** + * Returns the last event ID string, for + * server-sent events. + */ + readonly lastEventId: string; + /** + * Returns the origin of the message, for server-sent events and + * cross-document messaging. + */ + readonly origin: string; + /** + * Returns the MessagePort array sent with the message, for cross-document + * messaging and channel messaging. + */ + readonly ports: ReadonlyArray; + /** + * Returns the WindowProxy of the source window, for cross-document + * messaging, and the MessagePort being attached, in the connect event fired at + * SharedWorkerGlobalScope objects. + */ + readonly source: MessageEventSource | null; +} + +declare var MessageEvent: { + prototype: MessageEvent; + new(type: string, eventInitDict?: MessageEventInit): MessageEvent; +}; + +interface MessagePortEventMap { + "message": MessageEvent; + "messageerror": MessageEvent; +} + +interface MessagePort extends EventTarget { + onmessage: ((this: MessagePort, ev: MessageEvent) => any) | null; + onmessageerror: ((this: MessagePort, ev: MessageEvent) => any) | null; + /** + * Disconnects the port, so that it is no longer active. + */ + close(): void; + /** + * Posts a message through the channel. Objects listed in transfer are + * transferred, not just cloned, meaning that they are no longer usable on the sending side. + * Throws a "DataCloneError" DOMException if + * transfer contains duplicate objects or port, or if message + * could not be cloned. + */ + postMessage(message: any, transfer?: Transferable[]): void; + /** + * Begins dispatching messages received on the port. + */ + start(): void; + addEventListener(type: K, listener: (this: MessagePort, ev: MessagePortEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: MessagePort, ev: MessagePortEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var MessagePort: { + prototype: MessagePort; + new(): MessagePort; +}; + +interface MimeType { + readonly description: string; + readonly enabledPlugin: Plugin; + readonly suffixes: string; + readonly type: string; +} + +declare var MimeType: { + prototype: MimeType; + new(): MimeType; +}; + +interface MimeTypeArray { + readonly length: number; + item(index: number): Plugin; + namedItem(type: string): Plugin; + [index: number]: Plugin; +} + +declare var MimeTypeArray: { + prototype: MimeTypeArray; + new(): MimeTypeArray; +}; + +interface MouseEvent extends UIEvent { + readonly altKey: boolean; + readonly button: number; + readonly buttons: number; + readonly clientX: number; + readonly clientY: number; + readonly ctrlKey: boolean; + /** @deprecated */ + readonly fromElement: Element; + readonly layerX: number; + readonly layerY: number; + readonly metaKey: boolean; + readonly movementX: number; + readonly movementY: number; + readonly offsetX: number; + readonly offsetY: number; + readonly pageX: number; + readonly pageY: number; + readonly relatedTarget: EventTarget; + readonly screenX: number; + readonly screenY: number; + readonly shiftKey: boolean; + /** @deprecated */ + readonly toElement: Element; + /** @deprecated */ + readonly which: number; + readonly x: number; + readonly y: number; + getModifierState(keyArg: string): boolean; + initMouseEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, ctrlKeyArg: boolean, altKeyArg: boolean, shiftKeyArg: boolean, metaKeyArg: boolean, buttonArg: number, relatedTargetArg: EventTarget | null): void; +} + +declare var MouseEvent: { + prototype: MouseEvent; + new(typeArg: string, eventInitDict?: MouseEventInit): MouseEvent; +}; + +interface MutationEvent extends Event { + readonly attrChange: number; + readonly attrName: string; + readonly newValue: string; + readonly prevValue: string; + readonly relatedNode: Node; + initMutationEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, relatedNodeArg: Node, prevValueArg: string, newValueArg: string, attrNameArg: string, attrChangeArg: number): void; + readonly ADDITION: number; + readonly MODIFICATION: number; + readonly REMOVAL: number; +} + +declare var MutationEvent: { + prototype: MutationEvent; + new(): MutationEvent; + readonly ADDITION: number; + readonly MODIFICATION: number; + readonly REMOVAL: number; +}; + +interface MutationObserver { + disconnect(): void; + /** + * Instructs the user agent to observe a given target (a node) and report any mutations based on + * the criteria given by options (an object). + * The options argument allows for setting mutation + * observation options via object members. These are the object members that + * can be used: + * childList + * Set to true if mutations to target's children are to be observed. + * attributes + * Set to true if mutations to target's attributes are to be observed. Can be omitted if attributeOldValue or attributeFilter is + * specified. + * characterData + * Set to true if mutations to target's data are to be observed. Can be omitted if characterDataOldValue is specified. + * subtree + * Set to true if mutations to not just target, but + * also target's descendants are to be + * observed. + * attributeOldValue + * Set to true if attributes is true or omitted + * and target's attribute value before the mutation + * needs to be recorded. + * characterDataOldValue + * Set to true if characterData is set to true or omitted and target's data before the mutation + * needs to be recorded. + * attributeFilter + * Set to a list of attribute local names (without namespace) if not all attribute mutations need to be + * observed and attributes is true + * or omitted. + */ + observe(target: Node, options?: MutationObserverInit): void; + /** + * Empties the record queue and + * returns what was in there. + */ + takeRecords(): MutationRecord[]; +} + +declare var MutationObserver: { + prototype: MutationObserver; + new(callback: MutationCallback): MutationObserver; +}; + +interface MutationRecord { + readonly addedNodes: NodeList; + /** + * Returns the local name of the + * changed attribute, and null otherwise. + */ + readonly attributeName: string | null; + /** + * Returns the namespace of the + * changed attribute, and null otherwise. + */ + readonly attributeNamespace: string | null; + /** + * Return the previous and next sibling respectively + * of the added or removed nodes, and null otherwise. + */ + readonly nextSibling: Node | null; + /** + * The return value depends on type. For + * "attributes", it is the value of the + * changed attribute before the change. + * For "characterData", it is the data of the changed node before the change. For + * "childList", it is null. + */ + readonly oldValue: string | null; + readonly previousSibling: Node | null; + /** + * Return the nodes added and removed + * respectively. + */ + readonly removedNodes: NodeList; + readonly target: Node; + /** + * Returns "attributes" if it was an attribute mutation. + * "characterData" if it was a mutation to a CharacterData node. And + * "childList" if it was a mutation to the tree of nodes. + */ + readonly type: MutationRecordType; +} + +declare var MutationRecord: { + prototype: MutationRecord; + new(): MutationRecord; +}; + +interface NamedNodeMap { + readonly length: number; + getNamedItem(qualifiedName: string): Attr | null; + getNamedItemNS(namespace: string | null, localName: string): Attr | null; + item(index: number): Attr | null; + removeNamedItem(qualifiedName: string): Attr; + removeNamedItemNS(namespace: string | null, localName: string): Attr; + setNamedItem(attr: Attr): Attr | null; + setNamedItemNS(attr: Attr): Attr | null; + [index: number]: Attr; +} + +declare var NamedNodeMap: { + prototype: NamedNodeMap; + new(): NamedNodeMap; +}; + +interface NavigationPreloadManager { + disable(): Promise; + enable(): Promise; + getState(): Promise; + setHeaderValue(value: string): Promise; +} + +declare var NavigationPreloadManager: { + prototype: NavigationPreloadManager; + new(): NavigationPreloadManager; +}; + +interface Navigator extends NavigatorID, NavigatorOnLine, NavigatorContentUtils, NavigatorStorageUtils, MSNavigatorDoNotTrack, MSFileSaver, NavigatorBeacon, NavigatorConcurrentHardware, NavigatorUserMedia, NavigatorLanguage, NavigatorStorage, NavigatorAutomationInformation { + readonly activeVRDisplays: ReadonlyArray; + readonly authentication: WebAuthentication; + readonly cookieEnabled: boolean; + readonly doNotTrack: string | null; + gamepadInputEmulation: GamepadInputEmulationType; + readonly geolocation: Geolocation; + readonly maxTouchPoints: number; + readonly mimeTypes: MimeTypeArray; + readonly msManipulationViewsEnabled: boolean; + readonly msMaxTouchPoints: number; + readonly msPointerEnabled: boolean; + readonly plugins: PluginArray; + readonly pointerEnabled: boolean; + readonly serviceWorker: ServiceWorkerContainer; + readonly webdriver: boolean; + getGamepads(): (Gamepad | null)[]; + getVRDisplays(): Promise; + javaEnabled(): boolean; + msLaunchUri(uri: string, successCallback?: MSLaunchUriCallback, noHandlerCallback?: MSLaunchUriCallback): void; + requestMediaKeySystemAccess(keySystem: string, supportedConfigurations: MediaKeySystemConfiguration[]): Promise; + vibrate(pattern: number | number[]): boolean; +} + +declare var Navigator: { + prototype: Navigator; + new(): Navigator; +}; + +interface NavigatorAutomationInformation { + readonly webdriver: boolean; +} + +interface NavigatorBeacon { + sendBeacon(url: string, data?: Blob | Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | FormData | string | null): boolean; +} + +interface NavigatorConcurrentHardware { + readonly hardwareConcurrency: number; +} + +interface NavigatorContentUtils { +} + +interface NavigatorID { + readonly appCodeName: string; + readonly appName: string; + readonly appVersion: string; + readonly platform: string; + readonly product: string; + readonly productSub: string; + readonly userAgent: string; + readonly vendor: string; + readonly vendorSub: string; +} + +interface NavigatorLanguage { + readonly language: string; + readonly languages: ReadonlyArray; +} + +interface NavigatorOnLine { + readonly onLine: boolean; +} + +interface NavigatorStorage { + readonly storage: StorageManager; +} + +interface NavigatorStorageUtils { +} + +interface NavigatorUserMedia { + readonly mediaDevices: MediaDevices; + getDisplayMedia(constraints: MediaStreamConstraints): Promise; + getUserMedia(constraints: MediaStreamConstraints, successCallback: NavigatorUserMediaSuccessCallback, errorCallback: NavigatorUserMediaErrorCallback): void; +} + +interface Node extends EventTarget { + /** + * Returns node's node document's document base URL. + */ + readonly baseURI: string; + /** + * Returns the children. + */ + readonly childNodes: NodeListOf; + /** + * Returns the first child. + */ + readonly firstChild: ChildNode | null; + /** + * Returns true if node is connected and false otherwise. + */ + readonly isConnected: boolean; + /** + * Returns the last child. + */ + readonly lastChild: ChildNode | null; + /** @deprecated */ + readonly namespaceURI: string | null; + /** + * Returns the next sibling. + */ + readonly nextSibling: Node | null; + /** + * Returns a string appropriate for the type of node, as + * follows: + * Element + * Its HTML-uppercased qualified name. + * Attr + * Its qualified name. + * Text + * "#text". + * CDATASection + * "#cdata-section". + * ProcessingInstruction + * Its target. + * Comment + * "#comment". + * Document + * "#document". + * DocumentType + * Its name. + * DocumentFragment + * "#document-fragment". + */ + readonly nodeName: string; + readonly nodeType: number; + nodeValue: string | null; + /** + * Returns the node document. + * Returns null for documents. + */ + readonly ownerDocument: Document | null; + /** + * Returns the parent element. + */ + readonly parentElement: HTMLElement | null; + /** + * Returns the parent. + */ + readonly parentNode: Node & ParentNode | null; + /** + * Returns the previous sibling. + */ + readonly previousSibling: Node | null; + textContent: string | null; + appendChild(newChild: T): T; + /** + * Returns a copy of node. If deep is true, the copy also includes the node's descendants. + */ + cloneNode(deep?: boolean): Node; + compareDocumentPosition(other: Node): number; + /** + * Returns true if other is an inclusive descendant of node, and false otherwise. + */ + contains(other: Node | null): boolean; + /** + * Returns node's shadow-including root. + */ + getRootNode(options?: GetRootNodeOptions): Node; + /** + * Returns whether node has children. + */ + hasChildNodes(): boolean; + insertBefore(newChild: T, refChild: Node | null): T; + isDefaultNamespace(namespace: string | null): boolean; + /** + * Returns whether node and otherNode have the same properties. + */ + isEqualNode(otherNode: Node | null): boolean; + isSameNode(otherNode: Node | null): boolean; + lookupNamespaceURI(prefix: string | null): string | null; + lookupPrefix(namespace: string | null): string | null; + /** + * Removes empty exclusive Text nodes and concatenates the data of remaining contiguous exclusive Text nodes into the first of their nodes. + */ + normalize(): void; + removeChild(oldChild: T): T; + replaceChild(newChild: Node, oldChild: T): T; + readonly ATTRIBUTE_NODE: number; + readonly CDATA_SECTION_NODE: number; + readonly COMMENT_NODE: number; + readonly DOCUMENT_FRAGMENT_NODE: number; + readonly DOCUMENT_NODE: number; + readonly DOCUMENT_POSITION_CONTAINED_BY: number; + readonly DOCUMENT_POSITION_CONTAINS: number; + readonly DOCUMENT_POSITION_DISCONNECTED: number; + readonly DOCUMENT_POSITION_FOLLOWING: number; + readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: number; + readonly DOCUMENT_POSITION_PRECEDING: number; + readonly DOCUMENT_TYPE_NODE: number; + readonly ELEMENT_NODE: number; + readonly ENTITY_NODE: number; + readonly ENTITY_REFERENCE_NODE: number; + readonly NOTATION_NODE: number; + readonly PROCESSING_INSTRUCTION_NODE: number; + readonly TEXT_NODE: number; +} + +declare var Node: { + prototype: Node; + new(): Node; + readonly ATTRIBUTE_NODE: number; + readonly CDATA_SECTION_NODE: number; + readonly COMMENT_NODE: number; + readonly DOCUMENT_FRAGMENT_NODE: number; + readonly DOCUMENT_NODE: number; + readonly DOCUMENT_POSITION_CONTAINED_BY: number; + readonly DOCUMENT_POSITION_CONTAINS: number; + readonly DOCUMENT_POSITION_DISCONNECTED: number; + readonly DOCUMENT_POSITION_FOLLOWING: number; + readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: number; + readonly DOCUMENT_POSITION_PRECEDING: number; + readonly DOCUMENT_TYPE_NODE: number; + readonly ELEMENT_NODE: number; + readonly ENTITY_NODE: number; + readonly ENTITY_REFERENCE_NODE: number; + readonly NOTATION_NODE: number; + readonly PROCESSING_INSTRUCTION_NODE: number; + readonly TEXT_NODE: number; +}; + +interface NodeFilter { + acceptNode(node: Node): number; +} + +declare var NodeFilter: { + readonly FILTER_ACCEPT: number; + readonly FILTER_REJECT: number; + readonly FILTER_SKIP: number; + readonly SHOW_ALL: number; + readonly SHOW_ATTRIBUTE: number; + readonly SHOW_CDATA_SECTION: number; + readonly SHOW_COMMENT: number; + readonly SHOW_DOCUMENT: number; + readonly SHOW_DOCUMENT_FRAGMENT: number; + readonly SHOW_DOCUMENT_TYPE: number; + readonly SHOW_ELEMENT: number; + readonly SHOW_ENTITY: number; + readonly SHOW_ENTITY_REFERENCE: number; + readonly SHOW_NOTATION: number; + readonly SHOW_PROCESSING_INSTRUCTION: number; + readonly SHOW_TEXT: number; +}; + +interface NodeIterator { + readonly filter: NodeFilter | null; + readonly pointerBeforeReferenceNode: boolean; + readonly referenceNode: Node; + readonly root: Node; + readonly whatToShow: number; + detach(): void; + nextNode(): Node | null; + previousNode(): Node | null; +} + +declare var NodeIterator: { + prototype: NodeIterator; + new(): NodeIterator; +}; + +interface NodeList { + /** + * Returns the number of nodes in the collection. + */ + readonly length: number; + /** + * element = collection[index] + */ + item(index: number): Node | null; + /** + * Performs the specified action for each node in an list. + * @param callbackfn A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the list. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + forEach(callbackfn: (value: Node, key: number, parent: NodeList) => void, thisArg?: any): void; + [index: number]: Node; +} + +declare var NodeList: { + prototype: NodeList; + new(): NodeList; +}; + +interface NodeListOf extends NodeList { + length: number; + item(index: number): TNode; + /** + * Performs the specified action for each node in an list. + * @param callbackfn A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the list. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + forEach(callbackfn: (value: TNode, key: number, parent: NodeListOf) => void, thisArg?: any): void; + [index: number]: TNode; +} + +interface NodeSelector { + querySelector(selectors: K): HTMLElementTagNameMap[K] | null; + querySelector(selectors: K): SVGElementTagNameMap[K] | null; + querySelector(selectors: string): E | null; + querySelectorAll(selectors: K): NodeListOf; + querySelectorAll(selectors: K): NodeListOf; + querySelectorAll(selectors: string): NodeListOf; +} + +interface NonDocumentTypeChildNode { + /** + * Returns the first following sibling that + * is an element, and null otherwise. + */ + readonly nextElementSibling: Element | null; + /** + * Returns the first preceding sibling that + * is an element, and null otherwise. + */ + readonly previousElementSibling: Element | null; +} + +interface NonElementParentNode { + /** + * Returns the first element within node's descendants whose ID is elementId. + */ + getElementById(elementId: string): Element | null; +} + +interface NotificationEventMap { + "click": Event; + "close": Event; + "error": Event; + "show": Event; +} + +interface Notification extends EventTarget { + readonly actions: ReadonlyArray; + readonly badge: string; + readonly body: string; + readonly data: any; + readonly dir: NotificationDirection; + readonly icon: string; + readonly image: string; + readonly lang: string; + onclick: ((this: Notification, ev: Event) => any) | null; + onclose: ((this: Notification, ev: Event) => any) | null; + onerror: ((this: Notification, ev: Event) => any) | null; + onshow: ((this: Notification, ev: Event) => any) | null; + readonly renotify: boolean; + readonly requireInteraction: boolean; + readonly silent: boolean; + readonly tag: string; + readonly timestamp: number; + readonly title: string; + readonly vibrate: ReadonlyArray; + close(): void; + addEventListener(type: K, listener: (this: Notification, ev: NotificationEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: Notification, ev: NotificationEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var Notification: { + prototype: Notification; + new(title: string, options?: NotificationOptions): Notification; + readonly maxActions: number; + readonly permission: NotificationPermission; + requestPermission(deprecatedCallback?: NotificationPermissionCallback): Promise; +}; + +interface OES_element_index_uint { +} + +interface OES_standard_derivatives { + readonly FRAGMENT_SHADER_DERIVATIVE_HINT_OES: GLenum; +} + +interface OES_texture_float { +} + +interface OES_texture_float_linear { +} + +interface OES_texture_half_float { + readonly HALF_FLOAT_OES: GLenum; +} + +interface OES_texture_half_float_linear { +} + +interface OES_vertex_array_object { + bindVertexArrayOES(arrayObject: WebGLVertexArrayObjectOES | null): void; + createVertexArrayOES(): WebGLVertexArrayObjectOES | null; + deleteVertexArrayOES(arrayObject: WebGLVertexArrayObjectOES | null): void; + isVertexArrayOES(arrayObject: WebGLVertexArrayObjectOES | null): GLboolean; + readonly VERTEX_ARRAY_BINDING_OES: GLenum; +} + +interface OfflineAudioCompletionEvent extends Event { + readonly renderedBuffer: AudioBuffer; +} + +declare var OfflineAudioCompletionEvent: { + prototype: OfflineAudioCompletionEvent; + new(type: string, eventInitDict: OfflineAudioCompletionEventInit): OfflineAudioCompletionEvent; +}; + +interface OfflineAudioContextEventMap extends BaseAudioContextEventMap { + "complete": OfflineAudioCompletionEvent; +} + +interface OfflineAudioContext extends BaseAudioContext { + readonly length: number; + oncomplete: ((this: OfflineAudioContext, ev: OfflineAudioCompletionEvent) => any) | null; + startRendering(): Promise; + suspend(suspendTime: number): Promise; + addEventListener(type: K, listener: (this: OfflineAudioContext, ev: OfflineAudioContextEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: OfflineAudioContext, ev: OfflineAudioContextEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var OfflineAudioContext: { + prototype: OfflineAudioContext; + new(contextOptions: OfflineAudioContextOptions): OfflineAudioContext; + new(numberOfChannels: number, length: number, sampleRate: number): OfflineAudioContext; +}; + +interface OscillatorNode extends AudioScheduledSourceNode { + readonly detune: AudioParam; + readonly frequency: AudioParam; + type: OscillatorType; + setPeriodicWave(periodicWave: PeriodicWave): void; + addEventListener(type: K, listener: (this: OscillatorNode, ev: AudioScheduledSourceNodeEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: OscillatorNode, ev: AudioScheduledSourceNodeEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var OscillatorNode: { + prototype: OscillatorNode; + new(context: BaseAudioContext, options?: OscillatorOptions): OscillatorNode; +}; + +interface OverflowEvent extends UIEvent { + readonly horizontalOverflow: boolean; + readonly orient: number; + readonly verticalOverflow: boolean; + readonly BOTH: number; + readonly HORIZONTAL: number; + readonly VERTICAL: number; +} + +declare var OverflowEvent: { + prototype: OverflowEvent; + new(): OverflowEvent; + readonly BOTH: number; + readonly HORIZONTAL: number; + readonly VERTICAL: number; +}; + +interface PageTransitionEvent extends Event { + readonly persisted: boolean; +} + +declare var PageTransitionEvent: { + prototype: PageTransitionEvent; + new(): PageTransitionEvent; +}; + +interface PannerNode extends AudioNode { + coneInnerAngle: number; + coneOuterAngle: number; + coneOuterGain: number; + distanceModel: DistanceModelType; + maxDistance: number; + readonly orientationX: AudioParam; + readonly orientationY: AudioParam; + readonly orientationZ: AudioParam; + panningModel: PanningModelType; + readonly positionX: AudioParam; + readonly positionY: AudioParam; + readonly positionZ: AudioParam; + refDistance: number; + rolloffFactor: number; + /** @deprecated */ + setOrientation(x: number, y: number, z: number): void; + /** @deprecated */ + setPosition(x: number, y: number, z: number): void; +} + +declare var PannerNode: { + prototype: PannerNode; + new(context: BaseAudioContext, options?: PannerOptions): PannerNode; +}; + +interface ParentNode { + readonly childElementCount: number; + /** + * Returns the child elements. + */ + readonly children: HTMLCollection; + /** + * Returns the first child that is an element, and null otherwise. + */ + readonly firstElementChild: Element | null; + /** + * Returns the last child that is an element, and null otherwise. + */ + readonly lastElementChild: Element | null; + /** + * Inserts nodes after the last child of node, while replacing + * strings in nodes with equivalent Text nodes. + * Throws a "HierarchyRequestError" DOMException if the constraints of + * the node tree are violated. + */ + append(...nodes: (Node | string)[]): void; + /** + * Inserts nodes before the first child of node, while + * replacing strings in nodes with equivalent Text nodes. + * Throws a "HierarchyRequestError" DOMException if the constraints of + * the node tree are violated. + */ + prepend(...nodes: (Node | string)[]): void; + /** + * Returns the first element that is a descendant of node that + * matches selectors. + */ + querySelector(selectors: K): HTMLElementTagNameMap[K] | null; + querySelector(selectors: K): SVGElementTagNameMap[K] | null; + querySelector(selectors: string): E | null; + /** + * Returns all element descendants of node that + * match selectors. + */ + querySelectorAll(selectors: K): NodeListOf; + querySelectorAll(selectors: K): NodeListOf; + querySelectorAll(selectors: string): NodeListOf; +} + +interface Path2D extends CanvasPath { + addPath(path: Path2D, transform?: DOMMatrix2DInit): void; +} + +declare var Path2D: { + prototype: Path2D; + new(path?: Path2D | string): Path2D; +}; + +interface PaymentAddress { + readonly addressLine: string[]; + readonly city: string; + readonly country: string; + readonly dependentLocality: string; + readonly languageCode: string; + readonly organization: string; + readonly phone: string; + readonly postalCode: string; + readonly recipient: string; + readonly region: string; + readonly sortingCode: string; + toJSON(): any; +} + +declare var PaymentAddress: { + prototype: PaymentAddress; + new(): PaymentAddress; +}; + +interface PaymentRequestEventMap { + "shippingaddresschange": Event; + "shippingoptionchange": Event; +} + +interface PaymentRequest extends EventTarget { + readonly id: string; + onshippingaddresschange: ((this: PaymentRequest, ev: Event) => any) | null; + onshippingoptionchange: ((this: PaymentRequest, ev: Event) => any) | null; + readonly shippingAddress: PaymentAddress | null; + readonly shippingOption: string | null; + readonly shippingType: PaymentShippingType | null; + abort(): Promise; + canMakePayment(): Promise; + show(): Promise; + addEventListener(type: K, listener: (this: PaymentRequest, ev: PaymentRequestEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: PaymentRequest, ev: PaymentRequestEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var PaymentRequest: { + prototype: PaymentRequest; + new(methodData: PaymentMethodData[], details: PaymentDetailsInit, options?: PaymentOptions): PaymentRequest; +}; + +interface PaymentRequestUpdateEvent extends Event { + updateWith(detailsPromise: Promise): void; +} + +declare var PaymentRequestUpdateEvent: { + prototype: PaymentRequestUpdateEvent; + new(type: string, eventInitDict?: PaymentRequestUpdateEventInit): PaymentRequestUpdateEvent; +}; + +interface PaymentResponse { + readonly details: any; + readonly methodName: string; + readonly payerEmail: string | null; + readonly payerName: string | null; + readonly payerPhone: string | null; + readonly requestId: string; + readonly shippingAddress: PaymentAddress | null; + readonly shippingOption: string | null; + complete(result?: PaymentComplete): Promise; + toJSON(): any; +} + +declare var PaymentResponse: { + prototype: PaymentResponse; + new(): PaymentResponse; +}; + +interface PerfWidgetExternal { + readonly activeNetworkRequestCount: number; + readonly averageFrameTime: number; + readonly averagePaintTime: number; + readonly extraInformationEnabled: boolean; + readonly independentRenderingEnabled: boolean; + readonly irDisablingContentString: string; + readonly irStatusAvailable: boolean; + readonly maxCpuSpeed: number; + readonly paintRequestsPerSecond: number; + readonly performanceCounter: number; + readonly performanceCounterFrequency: number; + addEventListener(eventType: string, callback: Function): void; + getMemoryUsage(): number; + getProcessCpuUsage(): number; + getRecentCpuUsage(last: number | null): any; + getRecentFrames(last: number | null): any; + getRecentMemoryUsage(last: number | null): any; + getRecentPaintRequests(last: number | null): any; + removeEventListener(eventType: string, callback: Function): void; + repositionWindow(x: number, y: number): void; + resizeWindow(width: number, height: number): void; +} + +declare var PerfWidgetExternal: { + prototype: PerfWidgetExternal; + new(): PerfWidgetExternal; +}; + +interface PerformanceEventMap { + "resourcetimingbufferfull": Event; +} + +interface Performance extends EventTarget { + /** @deprecated */ + readonly navigation: PerformanceNavigation; + onresourcetimingbufferfull: ((this: Performance, ev: Event) => any) | null; + readonly timeOrigin: number; + /** @deprecated */ + readonly timing: PerformanceTiming; + clearMarks(markName?: string): void; + clearMeasures(measureName?: string): void; + clearResourceTimings(): void; + getEntries(): PerformanceEntryList; + getEntriesByName(name: string, type?: string): PerformanceEntryList; + getEntriesByType(type: string): PerformanceEntryList; + mark(markName: string): void; + measure(measureName: string, startMark?: string, endMark?: string): void; + now(): number; + setResourceTimingBufferSize(maxSize: number): void; + toJSON(): any; + addEventListener(type: K, listener: (this: Performance, ev: PerformanceEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: Performance, ev: PerformanceEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var Performance: { + prototype: Performance; + new(): Performance; +}; + +interface PerformanceEntry { + readonly duration: number; + readonly entryType: string; + readonly name: string; + readonly startTime: number; + toJSON(): any; +} + +declare var PerformanceEntry: { + prototype: PerformanceEntry; + new(): PerformanceEntry; +}; + +interface PerformanceMark extends PerformanceEntry { +} + +declare var PerformanceMark: { + prototype: PerformanceMark; + new(): PerformanceMark; +}; + +interface PerformanceMeasure extends PerformanceEntry { +} + +declare var PerformanceMeasure: { + prototype: PerformanceMeasure; + new(): PerformanceMeasure; +}; + +interface PerformanceNavigation { + readonly redirectCount: number; + readonly type: number; + toJSON(): any; + readonly TYPE_BACK_FORWARD: number; + readonly TYPE_NAVIGATE: number; + readonly TYPE_RELOAD: number; + readonly TYPE_RESERVED: number; +} + +declare var PerformanceNavigation: { + prototype: PerformanceNavigation; + new(): PerformanceNavigation; + readonly TYPE_BACK_FORWARD: number; + readonly TYPE_NAVIGATE: number; + readonly TYPE_RELOAD: number; + readonly TYPE_RESERVED: number; +}; + +interface PerformanceNavigationTiming extends PerformanceResourceTiming { + readonly domComplete: number; + readonly domContentLoadedEventEnd: number; + readonly domContentLoadedEventStart: number; + readonly domInteractive: number; + readonly loadEventEnd: number; + readonly loadEventStart: number; + readonly redirectCount: number; + readonly type: NavigationType; + readonly unloadEventEnd: number; + readonly unloadEventStart: number; + toJSON(): any; +} + +declare var PerformanceNavigationTiming: { + prototype: PerformanceNavigationTiming; + new(): PerformanceNavigationTiming; +}; + +interface PerformanceObserver { + disconnect(): void; + observe(options: PerformanceObserverInit): void; + takeRecords(): PerformanceEntryList; +} + +declare var PerformanceObserver: { + prototype: PerformanceObserver; + new(callback: PerformanceObserverCallback): PerformanceObserver; +}; + +interface PerformanceObserverEntryList { + getEntries(): PerformanceEntryList; + getEntriesByName(name: string, type?: string): PerformanceEntryList; + getEntriesByType(type: string): PerformanceEntryList; +} + +declare var PerformanceObserverEntryList: { + prototype: PerformanceObserverEntryList; + new(): PerformanceObserverEntryList; +}; + +interface PerformanceResourceTiming extends PerformanceEntry { + readonly connectEnd: number; + readonly connectStart: number; + readonly decodedBodySize: number; + readonly domainLookupEnd: number; + readonly domainLookupStart: number; + readonly encodedBodySize: number; + readonly fetchStart: number; + readonly initiatorType: string; + readonly nextHopProtocol: string; + readonly redirectEnd: number; + readonly redirectStart: number; + readonly requestStart: number; + readonly responseEnd: number; + readonly responseStart: number; + readonly secureConnectionStart: number; + readonly transferSize: number; + readonly workerStart: number; + toJSON(): any; +} + +declare var PerformanceResourceTiming: { + prototype: PerformanceResourceTiming; + new(): PerformanceResourceTiming; +}; + +interface PerformanceTiming { + readonly connectEnd: number; + readonly connectStart: number; + readonly domComplete: number; + readonly domContentLoadedEventEnd: number; + readonly domContentLoadedEventStart: number; + readonly domInteractive: number; + readonly domLoading: number; + readonly domainLookupEnd: number; + readonly domainLookupStart: number; + readonly fetchStart: number; + readonly loadEventEnd: number; + readonly loadEventStart: number; + readonly navigationStart: number; + readonly redirectEnd: number; + readonly redirectStart: number; + readonly requestStart: number; + readonly responseEnd: number; + readonly responseStart: number; + readonly secureConnectionStart: number; + readonly unloadEventEnd: number; + readonly unloadEventStart: number; + toJSON(): any; +} + +declare var PerformanceTiming: { + prototype: PerformanceTiming; + new(): PerformanceTiming; +}; + +interface PeriodicWave { +} + +declare var PeriodicWave: { + prototype: PeriodicWave; + new(context: BaseAudioContext, options?: PeriodicWaveOptions): PeriodicWave; +}; + +interface PermissionRequest extends DeferredPermissionRequest { + readonly state: MSWebViewPermissionState; + defer(): void; +} + +declare var PermissionRequest: { + prototype: PermissionRequest; + new(): PermissionRequest; +}; + +interface PermissionRequestedEvent extends Event { + readonly permissionRequest: PermissionRequest; +} + +declare var PermissionRequestedEvent: { + prototype: PermissionRequestedEvent; + new(): PermissionRequestedEvent; +}; + +interface Plugin { + readonly description: string; + readonly filename: string; + readonly length: number; + readonly name: string; + readonly version: string; + item(index: number): MimeType; + namedItem(type: string): MimeType; + [index: number]: MimeType; +} + +declare var Plugin: { + prototype: Plugin; + new(): Plugin; +}; + +interface PluginArray { + readonly length: number; + item(index: number): Plugin; + namedItem(name: string): Plugin; + refresh(reload?: boolean): void; + [index: number]: Plugin; +} + +declare var PluginArray: { + prototype: PluginArray; + new(): PluginArray; +}; + +interface PointerEvent extends MouseEvent { + readonly height: number; + readonly isPrimary: boolean; + readonly pointerId: number; + readonly pointerType: string; + readonly pressure: number; + readonly tangentialPressure: number; + readonly tiltX: number; + readonly tiltY: number; + readonly twist: number; + readonly width: number; +} + +declare var PointerEvent: { + prototype: PointerEvent; + new(type: string, eventInitDict?: PointerEventInit): PointerEvent; +}; + +interface PopStateEvent extends Event { + readonly state: any; +} + +declare var PopStateEvent: { + prototype: PopStateEvent; + new(type: string, eventInitDict?: PopStateEventInit): PopStateEvent; +}; + +interface Position { + readonly coords: Coordinates; + readonly timestamp: number; +} + +interface PositionError { + readonly code: number; + readonly message: string; + readonly PERMISSION_DENIED: number; + readonly POSITION_UNAVAILABLE: number; + readonly TIMEOUT: number; +} + +interface ProcessingInstruction extends CharacterData { + readonly target: string; +} + +declare var ProcessingInstruction: { + prototype: ProcessingInstruction; + new(): ProcessingInstruction; +}; + +interface ProgressEvent extends Event { + readonly lengthComputable: boolean; + readonly loaded: number; + readonly total: number; +} + +declare var ProgressEvent: { + prototype: ProgressEvent; + new(type: string, eventInitDict?: ProgressEventInit): ProgressEvent; +}; + +interface PromiseRejectionEvent extends Event { + readonly promise: Promise; + readonly reason: any; +} + +declare var PromiseRejectionEvent: { + prototype: PromiseRejectionEvent; + new(type: string, eventInitDict: PromiseRejectionEventInit): PromiseRejectionEvent; +}; + +interface PushManager { + getSubscription(): Promise; + permissionState(options?: PushSubscriptionOptionsInit): Promise; + subscribe(options?: PushSubscriptionOptionsInit): Promise; +} + +declare var PushManager: { + prototype: PushManager; + new(): PushManager; + readonly supportedContentEncodings: ReadonlyArray; +}; + +interface PushSubscription { + readonly endpoint: string; + readonly expirationTime: number | null; + readonly options: PushSubscriptionOptions; + getKey(name: PushEncryptionKeyName): ArrayBuffer | null; + toJSON(): PushSubscriptionJSON; + unsubscribe(): Promise; +} + +declare var PushSubscription: { + prototype: PushSubscription; + new(): PushSubscription; +}; + +interface PushSubscriptionOptions { + readonly applicationServerKey: ArrayBuffer | null; + readonly userVisibleOnly: boolean; +} + +declare var PushSubscriptionOptions: { + prototype: PushSubscriptionOptions; + new(): PushSubscriptionOptions; +}; + +interface RTCCertificate { + readonly expires: number; + getFingerprints(): RTCDtlsFingerprint[]; +} + +declare var RTCCertificate: { + prototype: RTCCertificate; + new(): RTCCertificate; + getSupportedAlgorithms(): AlgorithmIdentifier[]; +}; + +interface RTCDTMFSenderEventMap { + "tonechange": RTCDTMFToneChangeEvent; +} + +interface RTCDTMFSender extends EventTarget { + readonly canInsertDTMF: boolean; + ontonechange: ((this: RTCDTMFSender, ev: RTCDTMFToneChangeEvent) => any) | null; + readonly toneBuffer: string; + insertDTMF(tones: string, duration?: number, interToneGap?: number): void; + addEventListener(type: K, listener: (this: RTCDTMFSender, ev: RTCDTMFSenderEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: RTCDTMFSender, ev: RTCDTMFSenderEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var RTCDTMFSender: { + prototype: RTCDTMFSender; + new(): RTCDTMFSender; +}; + +interface RTCDTMFToneChangeEvent extends Event { + readonly tone: string; +} + +declare var RTCDTMFToneChangeEvent: { + prototype: RTCDTMFToneChangeEvent; + new(type: string, eventInitDict: RTCDTMFToneChangeEventInit): RTCDTMFToneChangeEvent; +}; + +interface RTCDataChannelEventMap { + "bufferedamountlow": Event; + "close": Event; + "error": RTCErrorEvent; + "message": MessageEvent; + "open": Event; +} + +interface RTCDataChannel extends EventTarget { + binaryType: string; + readonly bufferedAmount: number; + bufferedAmountLowThreshold: number; + readonly id: number | null; + readonly label: string; + readonly maxPacketLifeTime: number | null; + readonly maxRetransmits: number | null; + readonly negotiated: boolean; + onbufferedamountlow: ((this: RTCDataChannel, ev: Event) => any) | null; + onclose: ((this: RTCDataChannel, ev: Event) => any) | null; + onerror: ((this: RTCDataChannel, ev: RTCErrorEvent) => any) | null; + onmessage: ((this: RTCDataChannel, ev: MessageEvent) => any) | null; + onopen: ((this: RTCDataChannel, ev: Event) => any) | null; + readonly ordered: boolean; + readonly priority: RTCPriorityType; + readonly protocol: string; + readonly readyState: RTCDataChannelState; + close(): void; + send(data: string): void; + send(data: Blob): void; + send(data: ArrayBuffer): void; + send(data: ArrayBufferView): void; + addEventListener(type: K, listener: (this: RTCDataChannel, ev: RTCDataChannelEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: RTCDataChannel, ev: RTCDataChannelEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var RTCDataChannel: { + prototype: RTCDataChannel; + new(): RTCDataChannel; +}; + +interface RTCDataChannelEvent extends Event { + readonly channel: RTCDataChannel; +} + +declare var RTCDataChannelEvent: { + prototype: RTCDataChannelEvent; + new(type: string, eventInitDict: RTCDataChannelEventInit): RTCDataChannelEvent; +}; + +interface RTCDtlsTransportEventMap { + "error": RTCErrorEvent; + "statechange": Event; +} + +interface RTCDtlsTransport extends EventTarget { + onerror: ((this: RTCDtlsTransport, ev: RTCErrorEvent) => any) | null; + onstatechange: ((this: RTCDtlsTransport, ev: Event) => any) | null; + readonly state: RTCDtlsTransportState; + readonly transport: RTCIceTransport; + getRemoteCertificates(): ArrayBuffer[]; + addEventListener(type: K, listener: (this: RTCDtlsTransport, ev: RTCDtlsTransportEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: RTCDtlsTransport, ev: RTCDtlsTransportEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var RTCDtlsTransport: { + prototype: RTCDtlsTransport; + new(): RTCDtlsTransport; +}; + +interface RTCDtlsTransportStateChangedEvent extends Event { + readonly state: RTCDtlsTransportState; +} + +declare var RTCDtlsTransportStateChangedEvent: { + prototype: RTCDtlsTransportStateChangedEvent; + new(): RTCDtlsTransportStateChangedEvent; +}; + +interface RTCDtmfSenderEventMap { + "tonechange": RTCDTMFToneChangeEvent; +} + +interface RTCDtmfSender extends EventTarget { + readonly canInsertDTMF: boolean; + readonly duration: number; + readonly interToneGap: number; + ontonechange: ((this: RTCDtmfSender, ev: RTCDTMFToneChangeEvent) => any) | null; + readonly sender: RTCRtpSender; + readonly toneBuffer: string; + insertDTMF(tones: string, duration?: number, interToneGap?: number): void; + addEventListener(type: K, listener: (this: RTCDtmfSender, ev: RTCDtmfSenderEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: RTCDtmfSender, ev: RTCDtmfSenderEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var RTCDtmfSender: { + prototype: RTCDtmfSender; + new(sender: RTCRtpSender): RTCDtmfSender; +}; + +interface RTCError extends Error { + errorDetail: string; + httpRequestStatusCode: number; + message: string; + name: string; + receivedAlert: number | null; + sctpCauseCode: number; + sdpLineNumber: number; + sentAlert: number | null; +} + +declare var RTCError: { + prototype: RTCError; + new(errorDetail?: string, message?: string): RTCError; +}; + +interface RTCErrorEvent extends Event { + readonly error: RTCError | null; +} + +declare var RTCErrorEvent: { + prototype: RTCErrorEvent; + new(type: string, eventInitDict: RTCErrorEventInit): RTCErrorEvent; +}; + +interface RTCIceCandidate { + readonly candidate: string; + readonly component: RTCIceComponent | null; + readonly foundation: string | null; + readonly ip: string | null; + readonly port: number | null; + readonly priority: number | null; + readonly protocol: RTCIceProtocol | null; + readonly relatedAddress: string | null; + readonly relatedPort: number | null; + readonly sdpMLineIndex: number | null; + readonly sdpMid: string | null; + readonly tcpType: RTCIceTcpCandidateType | null; + readonly type: RTCIceCandidateType | null; + readonly usernameFragment: string | null; + toJSON(): RTCIceCandidateInit; +} + +declare var RTCIceCandidate: { + prototype: RTCIceCandidate; + new(candidateInitDict?: RTCIceCandidateInit): RTCIceCandidate; +}; + +interface RTCIceCandidatePairChangedEvent extends Event { + readonly pair: RTCIceCandidatePair; +} + +declare var RTCIceCandidatePairChangedEvent: { + prototype: RTCIceCandidatePairChangedEvent; + new(): RTCIceCandidatePairChangedEvent; +}; + +interface RTCIceGathererEventMap { + "error": Event; + "localcandidate": RTCIceGathererEvent; +} + +interface RTCIceGatherer extends RTCStatsProvider { + readonly component: RTCIceComponent; + onerror: ((this: RTCIceGatherer, ev: Event) => any) | null; + onlocalcandidate: ((this: RTCIceGatherer, ev: RTCIceGathererEvent) => any) | null; + createAssociatedGatherer(): RTCIceGatherer; + getLocalCandidates(): RTCIceCandidateDictionary[]; + getLocalParameters(): RTCIceParameters; + addEventListener(type: K, listener: (this: RTCIceGatherer, ev: RTCIceGathererEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: RTCIceGatherer, ev: RTCIceGathererEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var RTCIceGatherer: { + prototype: RTCIceGatherer; + new(options: RTCIceGatherOptions): RTCIceGatherer; +}; + +interface RTCIceGathererEvent extends Event { + readonly candidate: RTCIceCandidateDictionary | RTCIceCandidateComplete; +} + +declare var RTCIceGathererEvent: { + prototype: RTCIceGathererEvent; + new(): RTCIceGathererEvent; +}; + +interface RTCIceTransportEventMap { + "gatheringstatechange": Event; + "selectedcandidatepairchange": Event; + "statechange": Event; +} + +interface RTCIceTransport extends EventTarget { + readonly component: RTCIceComponent; + readonly gatheringState: RTCIceGathererState; + ongatheringstatechange: ((this: RTCIceTransport, ev: Event) => any) | null; + onselectedcandidatepairchange: ((this: RTCIceTransport, ev: Event) => any) | null; + onstatechange: ((this: RTCIceTransport, ev: Event) => any) | null; + readonly role: RTCIceRole; + readonly state: RTCIceTransportState; + getLocalCandidates(): RTCIceCandidate[]; + getLocalParameters(): RTCIceParameters | null; + getRemoteCandidates(): RTCIceCandidate[]; + getRemoteParameters(): RTCIceParameters | null; + getSelectedCandidatePair(): RTCIceCandidatePair | null; + addEventListener(type: K, listener: (this: RTCIceTransport, ev: RTCIceTransportEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: RTCIceTransport, ev: RTCIceTransportEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var RTCIceTransport: { + prototype: RTCIceTransport; + new(): RTCIceTransport; +}; + +interface RTCIceTransportStateChangedEvent extends Event { + readonly state: RTCIceTransportState; +} + +declare var RTCIceTransportStateChangedEvent: { + prototype: RTCIceTransportStateChangedEvent; + new(): RTCIceTransportStateChangedEvent; +}; + +interface RTCIdentityAssertion { + idp: string; + name: string; +} + +declare var RTCIdentityAssertion: { + prototype: RTCIdentityAssertion; + new(idp: string, name: string): RTCIdentityAssertion; +}; + +interface RTCPeerConnectionEventMap { + "connectionstatechange": Event; + "datachannel": RTCDataChannelEvent; + "icecandidate": RTCPeerConnectionIceEvent; + "icecandidateerror": RTCPeerConnectionIceErrorEvent; + "iceconnectionstatechange": Event; + "icegatheringstatechange": Event; + "negotiationneeded": Event; + "signalingstatechange": Event; + "statsended": RTCStatsEvent; + "track": RTCTrackEvent; +} + +interface RTCPeerConnection extends EventTarget { + readonly canTrickleIceCandidates: boolean | null; + readonly connectionState: RTCPeerConnectionState; + readonly currentLocalDescription: RTCSessionDescription | null; + readonly currentRemoteDescription: RTCSessionDescription | null; + readonly iceConnectionState: RTCIceConnectionState; + readonly iceGatheringState: RTCIceGatheringState; + readonly idpErrorInfo: string | null; + readonly idpLoginUrl: string | null; + readonly localDescription: RTCSessionDescription | null; + onconnectionstatechange: ((this: RTCPeerConnection, ev: Event) => any) | null; + ondatachannel: ((this: RTCPeerConnection, ev: RTCDataChannelEvent) => any) | null; + onicecandidate: ((this: RTCPeerConnection, ev: RTCPeerConnectionIceEvent) => any) | null; + onicecandidateerror: ((this: RTCPeerConnection, ev: RTCPeerConnectionIceErrorEvent) => any) | null; + oniceconnectionstatechange: ((this: RTCPeerConnection, ev: Event) => any) | null; + onicegatheringstatechange: ((this: RTCPeerConnection, ev: Event) => any) | null; + onnegotiationneeded: ((this: RTCPeerConnection, ev: Event) => any) | null; + onsignalingstatechange: ((this: RTCPeerConnection, ev: Event) => any) | null; + onstatsended: ((this: RTCPeerConnection, ev: RTCStatsEvent) => any) | null; + ontrack: ((this: RTCPeerConnection, ev: RTCTrackEvent) => any) | null; + readonly peerIdentity: Promise; + readonly pendingLocalDescription: RTCSessionDescription | null; + readonly pendingRemoteDescription: RTCSessionDescription | null; + readonly remoteDescription: RTCSessionDescription | null; + readonly sctp: RTCSctpTransport | null; + readonly signalingState: RTCSignalingState; + addIceCandidate(candidate: RTCIceCandidateInit | RTCIceCandidate): Promise; + addTrack(track: MediaStreamTrack, ...streams: MediaStream[]): RTCRtpSender; + addTransceiver(trackOrKind: MediaStreamTrack | string, init?: RTCRtpTransceiverInit): RTCRtpTransceiver; + close(): void; + createAnswer(options?: RTCOfferOptions): Promise; + createDataChannel(label: string, dataChannelDict?: RTCDataChannelInit): RTCDataChannel; + createOffer(options?: RTCOfferOptions): Promise; + getConfiguration(): RTCConfiguration; + getIdentityAssertion(): Promise; + getReceivers(): RTCRtpReceiver[]; + getSenders(): RTCRtpSender[]; + getStats(selector?: MediaStreamTrack | null): Promise; + getTransceivers(): RTCRtpTransceiver[]; + removeTrack(sender: RTCRtpSender): void; + setConfiguration(configuration: RTCConfiguration): void; + setIdentityProvider(provider: string, options?: RTCIdentityProviderOptions): void; + setLocalDescription(description: RTCSessionDescriptionInit): Promise; + setRemoteDescription(description: RTCSessionDescriptionInit): Promise; + addEventListener(type: K, listener: (this: RTCPeerConnection, ev: RTCPeerConnectionEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: RTCPeerConnection, ev: RTCPeerConnectionEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var RTCPeerConnection: { + prototype: RTCPeerConnection; + new(configuration?: RTCConfiguration): RTCPeerConnection; + generateCertificate(keygenAlgorithm: AlgorithmIdentifier): Promise; + getDefaultIceServers(): RTCIceServer[]; +}; + +interface RTCPeerConnectionIceErrorEvent extends Event { + readonly errorCode: number; + readonly errorText: string; + readonly hostCandidate: string; + readonly url: string; +} + +declare var RTCPeerConnectionIceErrorEvent: { + prototype: RTCPeerConnectionIceErrorEvent; + new(type: string, eventInitDict: RTCPeerConnectionIceErrorEventInit): RTCPeerConnectionIceErrorEvent; +}; + +interface RTCPeerConnectionIceEvent extends Event { + readonly candidate: RTCIceCandidate | null; + readonly url: string | null; +} + +declare var RTCPeerConnectionIceEvent: { + prototype: RTCPeerConnectionIceEvent; + new(type: string, eventInitDict?: RTCPeerConnectionIceEventInit): RTCPeerConnectionIceEvent; +}; + +interface RTCRtpReceiver { + readonly rtcpTransport: RTCDtlsTransport | null; + readonly track: MediaStreamTrack; + readonly transport: RTCDtlsTransport | null; + getContributingSources(): RTCRtpContributingSource[]; + getParameters(): RTCRtpReceiveParameters; + getStats(): Promise; + getSynchronizationSources(): RTCRtpSynchronizationSource[]; +} + +declare var RTCRtpReceiver: { + prototype: RTCRtpReceiver; + new(): RTCRtpReceiver; + getCapabilities(kind: string): RTCRtpCapabilities | null; +}; + +interface RTCRtpSender { + readonly dtmf: RTCDTMFSender | null; + readonly rtcpTransport: RTCDtlsTransport | null; + readonly track: MediaStreamTrack | null; + readonly transport: RTCDtlsTransport | null; + getParameters(): RTCRtpSendParameters; + getStats(): Promise; + replaceTrack(withTrack: MediaStreamTrack | null): Promise; + setParameters(parameters: RTCRtpSendParameters): Promise; + setStreams(...streams: MediaStream[]): void; +} + +declare var RTCRtpSender: { + prototype: RTCRtpSender; + new(): RTCRtpSender; + getCapabilities(kind: string): RTCRtpCapabilities | null; +}; + +interface RTCRtpTransceiver { + readonly currentDirection: RTCRtpTransceiverDirection | null; + direction: RTCRtpTransceiverDirection; + readonly mid: string | null; + readonly receiver: RTCRtpReceiver; + readonly sender: RTCRtpSender; + readonly stopped: boolean; + setCodecPreferences(codecs: RTCRtpCodecCapability[]): void; + stop(): void; +} + +declare var RTCRtpTransceiver: { + prototype: RTCRtpTransceiver; + new(): RTCRtpTransceiver; +}; + +interface RTCSctpTransportEventMap { + "statechange": Event; +} + +interface RTCSctpTransport { + readonly maxChannels: number | null; + readonly maxMessageSize: number; + onstatechange: ((this: RTCSctpTransport, ev: Event) => any) | null; + readonly state: RTCSctpTransportState; + readonly transport: RTCDtlsTransport; + addEventListener(type: K, listener: (this: RTCSctpTransport, ev: RTCSctpTransportEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: RTCSctpTransport, ev: RTCSctpTransportEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var RTCSctpTransport: { + prototype: RTCSctpTransport; + new(): RTCSctpTransport; +}; + +interface RTCSessionDescription { + readonly sdp: string; + readonly type: RTCSdpType; + toJSON(): any; +} + +declare var RTCSessionDescription: { + prototype: RTCSessionDescription; + new(descriptionInitDict: RTCSessionDescriptionInit): RTCSessionDescription; +}; + +interface RTCSrtpSdesTransportEventMap { + "error": Event; +} + +interface RTCSrtpSdesTransport extends EventTarget { + onerror: ((this: RTCSrtpSdesTransport, ev: Event) => any) | null; + readonly transport: RTCIceTransport; + addEventListener(type: K, listener: (this: RTCSrtpSdesTransport, ev: RTCSrtpSdesTransportEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: RTCSrtpSdesTransport, ev: RTCSrtpSdesTransportEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var RTCSrtpSdesTransport: { + prototype: RTCSrtpSdesTransport; + new(transport: RTCIceTransport, encryptParameters: RTCSrtpSdesParameters, decryptParameters: RTCSrtpSdesParameters): RTCSrtpSdesTransport; + getLocalParameters(): RTCSrtpSdesParameters[]; +}; + +interface RTCSsrcConflictEvent extends Event { + readonly ssrc: number; +} + +declare var RTCSsrcConflictEvent: { + prototype: RTCSsrcConflictEvent; + new(): RTCSsrcConflictEvent; +}; + +interface RTCStatsEvent extends Event { + readonly report: RTCStatsReport; +} + +declare var RTCStatsEvent: { + prototype: RTCStatsEvent; + new(type: string, eventInitDict: RTCStatsEventInit): RTCStatsEvent; +}; + +interface RTCStatsProvider extends EventTarget { + getStats(): Promise; + msGetStats(): Promise; +} + +declare var RTCStatsProvider: { + prototype: RTCStatsProvider; + new(): RTCStatsProvider; +}; + +interface RTCStatsReport { + forEach(callbackfn: (value: any, key: string, parent: RTCStatsReport) => void, thisArg?: any): void; +} + +declare var RTCStatsReport: { + prototype: RTCStatsReport; + new(): RTCStatsReport; +}; + +interface RTCTrackEvent extends Event { + readonly receiver: RTCRtpReceiver; + readonly streams: ReadonlyArray; + readonly track: MediaStreamTrack; + readonly transceiver: RTCRtpTransceiver; +} + +declare var RTCTrackEvent: { + prototype: RTCTrackEvent; + new(type: string, eventInitDict: RTCTrackEventInit): RTCTrackEvent; +}; + +interface RadioNodeList extends NodeList { + value: string; +} + +declare var RadioNodeList: { + prototype: RadioNodeList; + new(): RadioNodeList; +}; + +interface RandomSource { + getRandomValues(array: T): T; +} + +declare var RandomSource: { + prototype: RandomSource; + new(): RandomSource; +}; + +interface Range extends AbstractRange { + /** + * Returns the node, furthest away from + * the document, that is an ancestor of both range's start node and end node. + */ + readonly commonAncestorContainer: Node; + cloneContents(): DocumentFragment; + cloneRange(): Range; + collapse(toStart?: boolean): void; + compareBoundaryPoints(how: number, sourceRange: Range): number; + /** + * Returns −1 if the point is before the range, 0 if the point is + * in the range, and 1 if the point is after the range. + */ + comparePoint(node: Node, offset: number): number; + createContextualFragment(fragment: string): DocumentFragment; + deleteContents(): void; + detach(): void; + extractContents(): DocumentFragment; + getBoundingClientRect(): ClientRect | DOMRect; + getClientRects(): ClientRectList | DOMRectList; + insertNode(node: Node): void; + /** + * Returns whether range intersects node. + */ + intersectsNode(node: Node): boolean; + isPointInRange(node: Node, offset: number): boolean; + selectNode(node: Node): void; + selectNodeContents(node: Node): void; + setEnd(node: Node, offset: number): void; + setEndAfter(node: Node): void; + setEndBefore(node: Node): void; + setStart(node: Node, offset: number): void; + setStartAfter(node: Node): void; + setStartBefore(node: Node): void; + surroundContents(newParent: Node): void; + readonly END_TO_END: number; + readonly END_TO_START: number; + readonly START_TO_END: number; + readonly START_TO_START: number; +} + +declare var Range: { + prototype: Range; + new(): Range; + readonly END_TO_END: number; + readonly END_TO_START: number; + readonly START_TO_END: number; + readonly START_TO_START: number; +}; + +interface ReadableByteStreamController { + readonly byobRequest: ReadableStreamBYOBRequest | undefined; + readonly desiredSize: number | null; + close(): void; + enqueue(chunk: ArrayBufferView): void; + error(error?: any): void; +} + +interface ReadableStream { + readonly locked: boolean; + cancel(reason?: any): Promise; + getReader(options: { mode: "byob" }): ReadableStreamBYOBReader; + getReader(): ReadableStreamDefaultReader; + pipeThrough({ writable, readable }: { writable: WritableStream, readable: ReadableStream }, options?: PipeOptions): ReadableStream; + pipeTo(dest: WritableStream, options?: PipeOptions): Promise; + tee(): [ReadableStream, ReadableStream]; +} + +declare var ReadableStream: { + prototype: ReadableStream; + new(underlyingSource: UnderlyingByteSource, strategy?: { highWaterMark?: number, size?: undefined }): ReadableStream; + new(underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy): ReadableStream; +}; + +interface ReadableStreamBYOBReader { + readonly closed: Promise; + cancel(reason?: any): Promise; + read(view: T): Promise>; + releaseLock(): void; +} + +declare var ReadableStreamBYOBReader: { + prototype: ReadableStreamBYOBReader; + new(stream: ReadableStream): ReadableStreamBYOBReader; +}; + +interface ReadableStreamBYOBRequest { + readonly view: ArrayBufferView; + respond(bytesWritten: number): void; + respondWithNewView(view: ArrayBufferView): void; +} + +interface ReadableStreamDefaultController { + readonly desiredSize: number | null; + close(): void; + enqueue(chunk: R): void; + error(error?: any): void; +} + +interface ReadableStreamDefaultReader { + readonly closed: Promise; + cancel(reason?: any): Promise; + read(): Promise>; + releaseLock(): void; +} + +interface ReadableStreamReadResult { + done: boolean; + value: T; +} + +interface ReadableStreamReader { + cancel(): Promise; + read(): Promise>; + releaseLock(): void; +} + +declare var ReadableStreamReader: { + prototype: ReadableStreamReader; + new(): ReadableStreamReader; +}; + +interface Request extends Body { + /** + * Returns the cache mode associated with request, which is a string indicating + * how the request will interact with the browser's cache when fetching. + */ + readonly cache: RequestCache; + /** + * Returns the credentials mode associated with request, which is a string + * indicating whether credentials will be sent with the request always, never, or only when sent to a + * same-origin URL. + */ + readonly credentials: RequestCredentials; + /** + * Returns the kind of resource requested by request, e.g., "document" or + * "script". + */ + readonly destination: RequestDestination; + /** + * Returns a Headers object consisting of the headers associated with request. + * Note that headers added in the network layer by the user agent will not be accounted for in this + * object, e.g., the "Host" header. + */ + readonly headers: Headers; + /** + * Returns request's subresource integrity metadata, which is a cryptographic hash of + * the resource being fetched. Its value consists of multiple hashes separated by whitespace. [SRI] + */ + readonly integrity: string; + /** + * Returns a boolean indicating whether or not request is for a history + * navigation (a.k.a. back-foward navigation). + */ + readonly isHistoryNavigation: boolean; + /** + * Returns a boolean indicating whether or not request is for a reload navigation. + */ + readonly isReloadNavigation: boolean; + /** + * Returns a boolean indicating whether or not request can outlive the global in which + * it was created. + */ + readonly keepalive: boolean; + /** + * Returns request's HTTP method, which is "GET" by default. + */ + readonly method: string; + /** + * Returns the mode associated with request, which is a string indicating + * whether the request will use CORS, or will be restricted to same-origin URLs. + */ + readonly mode: RequestMode; + /** + * Returns the redirect mode associated with request, which is a string + * indicating how redirects for the request will be handled during fetching. A request will follow redirects by default. + */ + readonly redirect: RequestRedirect; + /** + * Returns the referrer of request. Its value can be a same-origin URL if + * explicitly set in init, the empty string to indicate no referrer, and + * "about:client" when defaulting to the global's default. This is used during + * fetching to determine the value of the `Referer` header of the request being made. + */ + readonly referrer: string; + /** + * Returns the referrer policy associated with request. This is used during + * fetching to compute the value of the request's referrer. + */ + readonly referrerPolicy: ReferrerPolicy; + /** + * Returns the signal associated with request, which is an AbortSignal object indicating whether or not request has been aborted, and its abort + * event handler. + */ + readonly signal: AbortSignal; + /** + * Returns the URL of request as a string. + */ + readonly url: string; + clone(): Request; +} + +declare var Request: { + prototype: Request; + new(input: RequestInfo, init?: RequestInit): Request; +}; + +interface Response extends Body { + readonly headers: Headers; + readonly ok: boolean; + readonly redirected: boolean; + readonly status: number; + readonly statusText: string; + readonly trailer: Promise; + readonly type: ResponseType; + readonly url: string; + clone(): Response; +} + +declare var Response: { + prototype: Response; + new(body?: BodyInit | null, init?: ResponseInit): Response; + error(): Response; + redirect(url: string, status?: number): Response; +}; + +interface SVGAElement extends SVGGraphicsElement, SVGURIReference { + readonly target: SVGAnimatedString; + addEventListener(type: K, listener: (this: SVGAElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGAElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGAElement: { + prototype: SVGAElement; + new(): SVGAElement; +}; + +interface SVGAngle { + readonly unitType: number; + value: number; + valueAsString: string; + valueInSpecifiedUnits: number; + convertToSpecifiedUnits(unitType: number): void; + newValueSpecifiedUnits(unitType: number, valueInSpecifiedUnits: number): void; + readonly SVG_ANGLETYPE_DEG: number; + readonly SVG_ANGLETYPE_GRAD: number; + readonly SVG_ANGLETYPE_RAD: number; + readonly SVG_ANGLETYPE_UNKNOWN: number; + readonly SVG_ANGLETYPE_UNSPECIFIED: number; +} + +declare var SVGAngle: { + prototype: SVGAngle; + new(): SVGAngle; + readonly SVG_ANGLETYPE_DEG: number; + readonly SVG_ANGLETYPE_GRAD: number; + readonly SVG_ANGLETYPE_RAD: number; + readonly SVG_ANGLETYPE_UNKNOWN: number; + readonly SVG_ANGLETYPE_UNSPECIFIED: number; +}; + +interface SVGAnimateElement extends SVGAnimationElement { + addEventListener(type: K, listener: (this: SVGAnimateElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGAnimateElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGAnimateElement: { + prototype: SVGAnimateElement; + new(): SVGAnimateElement; +}; + +interface SVGAnimateMotionElement extends SVGAnimationElement { + addEventListener(type: K, listener: (this: SVGAnimateMotionElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGAnimateMotionElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGAnimateMotionElement: { + prototype: SVGAnimateMotionElement; + new(): SVGAnimateMotionElement; +}; + +interface SVGAnimateTransformElement extends SVGAnimationElement { + addEventListener(type: K, listener: (this: SVGAnimateTransformElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGAnimateTransformElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGAnimateTransformElement: { + prototype: SVGAnimateTransformElement; + new(): SVGAnimateTransformElement; +}; + +interface SVGAnimatedAngle { + readonly animVal: SVGAngle; + readonly baseVal: SVGAngle; +} + +declare var SVGAnimatedAngle: { + prototype: SVGAnimatedAngle; + new(): SVGAnimatedAngle; +}; + +interface SVGAnimatedBoolean { + readonly animVal: boolean; + baseVal: boolean; +} + +declare var SVGAnimatedBoolean: { + prototype: SVGAnimatedBoolean; + new(): SVGAnimatedBoolean; +}; + +interface SVGAnimatedEnumeration { + readonly animVal: number; + baseVal: number; +} + +declare var SVGAnimatedEnumeration: { + prototype: SVGAnimatedEnumeration; + new(): SVGAnimatedEnumeration; +}; + +interface SVGAnimatedInteger { + readonly animVal: number; + baseVal: number; +} + +declare var SVGAnimatedInteger: { + prototype: SVGAnimatedInteger; + new(): SVGAnimatedInteger; +}; + +interface SVGAnimatedLength { + readonly animVal: SVGLength; + readonly baseVal: SVGLength; +} + +declare var SVGAnimatedLength: { + prototype: SVGAnimatedLength; + new(): SVGAnimatedLength; +}; + +interface SVGAnimatedLengthList { + readonly animVal: SVGLengthList; + readonly baseVal: SVGLengthList; +} + +declare var SVGAnimatedLengthList: { + prototype: SVGAnimatedLengthList; + new(): SVGAnimatedLengthList; +}; + +interface SVGAnimatedNumber { + readonly animVal: number; + baseVal: number; +} + +declare var SVGAnimatedNumber: { + prototype: SVGAnimatedNumber; + new(): SVGAnimatedNumber; +}; + +interface SVGAnimatedNumberList { + readonly animVal: SVGNumberList; + readonly baseVal: SVGNumberList; +} + +declare var SVGAnimatedNumberList: { + prototype: SVGAnimatedNumberList; + new(): SVGAnimatedNumberList; +}; + +interface SVGAnimatedPoints { + readonly animatedPoints: SVGPointList; + readonly points: SVGPointList; +} + +interface SVGAnimatedPreserveAspectRatio { + readonly animVal: SVGPreserveAspectRatio; + readonly baseVal: SVGPreserveAspectRatio; +} + +declare var SVGAnimatedPreserveAspectRatio: { + prototype: SVGAnimatedPreserveAspectRatio; + new(): SVGAnimatedPreserveAspectRatio; +}; + +interface SVGAnimatedRect { + readonly animVal: DOMRectReadOnly; + readonly baseVal: DOMRect; +} + +declare var SVGAnimatedRect: { + prototype: SVGAnimatedRect; + new(): SVGAnimatedRect; +}; + +interface SVGAnimatedString { + readonly animVal: string; + baseVal: string; +} + +declare var SVGAnimatedString: { + prototype: SVGAnimatedString; + new(): SVGAnimatedString; +}; + +interface SVGAnimatedTransformList { + readonly animVal: SVGTransformList; + readonly baseVal: SVGTransformList; +} + +declare var SVGAnimatedTransformList: { + prototype: SVGAnimatedTransformList; + new(): SVGAnimatedTransformList; +}; + +interface SVGAnimationElement extends SVGElement { + readonly targetElement: SVGElement; + getCurrentTime(): number; + getSimpleDuration(): number; + getStartTime(): number; + addEventListener(type: K, listener: (this: SVGAnimationElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGAnimationElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGAnimationElement: { + prototype: SVGAnimationElement; + new(): SVGAnimationElement; +}; + +interface SVGCircleElement extends SVGGraphicsElement { + readonly cx: SVGAnimatedLength; + readonly cy: SVGAnimatedLength; + readonly r: SVGAnimatedLength; + addEventListener(type: K, listener: (this: SVGCircleElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGCircleElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGCircleElement: { + prototype: SVGCircleElement; + new(): SVGCircleElement; +}; + +interface SVGClipPathElement extends SVGGraphicsElement { + readonly clipPathUnits: SVGAnimatedEnumeration; + addEventListener(type: K, listener: (this: SVGClipPathElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGClipPathElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGClipPathElement: { + prototype: SVGClipPathElement; + new(): SVGClipPathElement; +}; + +interface SVGComponentTransferFunctionElement extends SVGElement { + readonly amplitude: SVGAnimatedNumber; + readonly exponent: SVGAnimatedNumber; + readonly intercept: SVGAnimatedNumber; + readonly offset: SVGAnimatedNumber; + readonly slope: SVGAnimatedNumber; + readonly tableValues: SVGAnimatedNumberList; + readonly type: SVGAnimatedEnumeration; + readonly SVG_FECOMPONENTTRANSFER_TYPE_DISCRETE: number; + readonly SVG_FECOMPONENTTRANSFER_TYPE_GAMMA: number; + readonly SVG_FECOMPONENTTRANSFER_TYPE_IDENTITY: number; + readonly SVG_FECOMPONENTTRANSFER_TYPE_LINEAR: number; + readonly SVG_FECOMPONENTTRANSFER_TYPE_TABLE: number; + readonly SVG_FECOMPONENTTRANSFER_TYPE_UNKNOWN: number; + addEventListener(type: K, listener: (this: SVGComponentTransferFunctionElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGComponentTransferFunctionElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGComponentTransferFunctionElement: { + prototype: SVGComponentTransferFunctionElement; + new(): SVGComponentTransferFunctionElement; + readonly SVG_FECOMPONENTTRANSFER_TYPE_DISCRETE: number; + readonly SVG_FECOMPONENTTRANSFER_TYPE_GAMMA: number; + readonly SVG_FECOMPONENTTRANSFER_TYPE_IDENTITY: number; + readonly SVG_FECOMPONENTTRANSFER_TYPE_LINEAR: number; + readonly SVG_FECOMPONENTTRANSFER_TYPE_TABLE: number; + readonly SVG_FECOMPONENTTRANSFER_TYPE_UNKNOWN: number; +}; + +interface SVGCursorElement extends SVGElement { + readonly x: SVGAnimatedLength; + readonly y: SVGAnimatedLength; + addEventListener(type: K, listener: (this: SVGCursorElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGCursorElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGCursorElement: { + prototype: SVGCursorElement; + new(): SVGCursorElement; +}; + +interface SVGDefsElement extends SVGGraphicsElement { + addEventListener(type: K, listener: (this: SVGDefsElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGDefsElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGDefsElement: { + prototype: SVGDefsElement; + new(): SVGDefsElement; +}; + +interface SVGDescElement extends SVGElement { + addEventListener(type: K, listener: (this: SVGDescElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGDescElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGDescElement: { + prototype: SVGDescElement; + new(): SVGDescElement; +}; + +interface SVGElementEventMap extends ElementEventMap, GlobalEventHandlersEventMap, DocumentAndElementEventHandlersEventMap { +} + +interface SVGElement extends Element, GlobalEventHandlers, DocumentAndElementEventHandlers, SVGElementInstance, HTMLOrSVGElement, ElementCSSInlineStyle { + /** @deprecated */ + readonly className: any; + readonly ownerSVGElement: SVGSVGElement | null; + readonly viewportElement: SVGElement | null; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGElement: { + prototype: SVGElement; + new(): SVGElement; +}; + +interface SVGElementInstance extends EventTarget { + readonly correspondingElement: SVGElement; + readonly correspondingUseElement: SVGUseElement; +} + +declare var SVGElementInstance: { + prototype: SVGElementInstance; + new(): SVGElementInstance; +}; + +interface SVGElementInstanceList { + /** @deprecated */ + readonly length: number; + /** @deprecated */ + item(index: number): SVGElementInstance; +} + +declare var SVGElementInstanceList: { + prototype: SVGElementInstanceList; + new(): SVGElementInstanceList; +}; + +interface SVGEllipseElement extends SVGGraphicsElement { + readonly cx: SVGAnimatedLength; + readonly cy: SVGAnimatedLength; + readonly rx: SVGAnimatedLength; + readonly ry: SVGAnimatedLength; + addEventListener(type: K, listener: (this: SVGEllipseElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGEllipseElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGEllipseElement: { + prototype: SVGEllipseElement; + new(): SVGEllipseElement; +}; + +interface SVGFEBlendElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + readonly in1: SVGAnimatedString; + readonly in2: SVGAnimatedString; + readonly mode: SVGAnimatedEnumeration; + readonly SVG_FEBLEND_MODE_COLOR: number; + readonly SVG_FEBLEND_MODE_COLOR_BURN: number; + readonly SVG_FEBLEND_MODE_COLOR_DODGE: number; + readonly SVG_FEBLEND_MODE_DARKEN: number; + readonly SVG_FEBLEND_MODE_DIFFERENCE: number; + readonly SVG_FEBLEND_MODE_EXCLUSION: number; + readonly SVG_FEBLEND_MODE_HARD_LIGHT: number; + readonly SVG_FEBLEND_MODE_HUE: number; + readonly SVG_FEBLEND_MODE_LIGHTEN: number; + readonly SVG_FEBLEND_MODE_LUMINOSITY: number; + readonly SVG_FEBLEND_MODE_MULTIPLY: number; + readonly SVG_FEBLEND_MODE_NORMAL: number; + readonly SVG_FEBLEND_MODE_OVERLAY: number; + readonly SVG_FEBLEND_MODE_SATURATION: number; + readonly SVG_FEBLEND_MODE_SCREEN: number; + readonly SVG_FEBLEND_MODE_SOFT_LIGHT: number; + readonly SVG_FEBLEND_MODE_UNKNOWN: number; + addEventListener(type: K, listener: (this: SVGFEBlendElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEBlendElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGFEBlendElement: { + prototype: SVGFEBlendElement; + new(): SVGFEBlendElement; + readonly SVG_FEBLEND_MODE_COLOR: number; + readonly SVG_FEBLEND_MODE_COLOR_BURN: number; + readonly SVG_FEBLEND_MODE_COLOR_DODGE: number; + readonly SVG_FEBLEND_MODE_DARKEN: number; + readonly SVG_FEBLEND_MODE_DIFFERENCE: number; + readonly SVG_FEBLEND_MODE_EXCLUSION: number; + readonly SVG_FEBLEND_MODE_HARD_LIGHT: number; + readonly SVG_FEBLEND_MODE_HUE: number; + readonly SVG_FEBLEND_MODE_LIGHTEN: number; + readonly SVG_FEBLEND_MODE_LUMINOSITY: number; + readonly SVG_FEBLEND_MODE_MULTIPLY: number; + readonly SVG_FEBLEND_MODE_NORMAL: number; + readonly SVG_FEBLEND_MODE_OVERLAY: number; + readonly SVG_FEBLEND_MODE_SATURATION: number; + readonly SVG_FEBLEND_MODE_SCREEN: number; + readonly SVG_FEBLEND_MODE_SOFT_LIGHT: number; + readonly SVG_FEBLEND_MODE_UNKNOWN: number; +}; + +interface SVGFEColorMatrixElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + readonly in1: SVGAnimatedString; + readonly type: SVGAnimatedEnumeration; + readonly values: SVGAnimatedNumberList; + readonly SVG_FECOLORMATRIX_TYPE_HUEROTATE: number; + readonly SVG_FECOLORMATRIX_TYPE_LUMINANCETOALPHA: number; + readonly SVG_FECOLORMATRIX_TYPE_MATRIX: number; + readonly SVG_FECOLORMATRIX_TYPE_SATURATE: number; + readonly SVG_FECOLORMATRIX_TYPE_UNKNOWN: number; + addEventListener(type: K, listener: (this: SVGFEColorMatrixElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEColorMatrixElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGFEColorMatrixElement: { + prototype: SVGFEColorMatrixElement; + new(): SVGFEColorMatrixElement; + readonly SVG_FECOLORMATRIX_TYPE_HUEROTATE: number; + readonly SVG_FECOLORMATRIX_TYPE_LUMINANCETOALPHA: number; + readonly SVG_FECOLORMATRIX_TYPE_MATRIX: number; + readonly SVG_FECOLORMATRIX_TYPE_SATURATE: number; + readonly SVG_FECOLORMATRIX_TYPE_UNKNOWN: number; +}; + +interface SVGFEComponentTransferElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + readonly in1: SVGAnimatedString; + addEventListener(type: K, listener: (this: SVGFEComponentTransferElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEComponentTransferElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGFEComponentTransferElement: { + prototype: SVGFEComponentTransferElement; + new(): SVGFEComponentTransferElement; +}; + +interface SVGFECompositeElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + readonly in1: SVGAnimatedString; + readonly in2: SVGAnimatedString; + readonly k1: SVGAnimatedNumber; + readonly k2: SVGAnimatedNumber; + readonly k3: SVGAnimatedNumber; + readonly k4: SVGAnimatedNumber; + readonly operator: SVGAnimatedEnumeration; + readonly SVG_FECOMPOSITE_OPERATOR_ARITHMETIC: number; + readonly SVG_FECOMPOSITE_OPERATOR_ATOP: number; + readonly SVG_FECOMPOSITE_OPERATOR_IN: number; + readonly SVG_FECOMPOSITE_OPERATOR_OUT: number; + readonly SVG_FECOMPOSITE_OPERATOR_OVER: number; + readonly SVG_FECOMPOSITE_OPERATOR_UNKNOWN: number; + readonly SVG_FECOMPOSITE_OPERATOR_XOR: number; + addEventListener(type: K, listener: (this: SVGFECompositeElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFECompositeElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGFECompositeElement: { + prototype: SVGFECompositeElement; + new(): SVGFECompositeElement; + readonly SVG_FECOMPOSITE_OPERATOR_ARITHMETIC: number; + readonly SVG_FECOMPOSITE_OPERATOR_ATOP: number; + readonly SVG_FECOMPOSITE_OPERATOR_IN: number; + readonly SVG_FECOMPOSITE_OPERATOR_OUT: number; + readonly SVG_FECOMPOSITE_OPERATOR_OVER: number; + readonly SVG_FECOMPOSITE_OPERATOR_UNKNOWN: number; + readonly SVG_FECOMPOSITE_OPERATOR_XOR: number; +}; + +interface SVGFEConvolveMatrixElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + readonly bias: SVGAnimatedNumber; + readonly divisor: SVGAnimatedNumber; + readonly edgeMode: SVGAnimatedEnumeration; + readonly in1: SVGAnimatedString; + readonly kernelMatrix: SVGAnimatedNumberList; + readonly kernelUnitLengthX: SVGAnimatedNumber; + readonly kernelUnitLengthY: SVGAnimatedNumber; + readonly orderX: SVGAnimatedInteger; + readonly orderY: SVGAnimatedInteger; + readonly preserveAlpha: SVGAnimatedBoolean; + readonly targetX: SVGAnimatedInteger; + readonly targetY: SVGAnimatedInteger; + readonly SVG_EDGEMODE_DUPLICATE: number; + readonly SVG_EDGEMODE_NONE: number; + readonly SVG_EDGEMODE_UNKNOWN: number; + readonly SVG_EDGEMODE_WRAP: number; + addEventListener(type: K, listener: (this: SVGFEConvolveMatrixElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEConvolveMatrixElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGFEConvolveMatrixElement: { + prototype: SVGFEConvolveMatrixElement; + new(): SVGFEConvolveMatrixElement; + readonly SVG_EDGEMODE_DUPLICATE: number; + readonly SVG_EDGEMODE_NONE: number; + readonly SVG_EDGEMODE_UNKNOWN: number; + readonly SVG_EDGEMODE_WRAP: number; +}; + +interface SVGFEDiffuseLightingElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + readonly diffuseConstant: SVGAnimatedNumber; + readonly in1: SVGAnimatedString; + readonly kernelUnitLengthX: SVGAnimatedNumber; + readonly kernelUnitLengthY: SVGAnimatedNumber; + readonly surfaceScale: SVGAnimatedNumber; + addEventListener(type: K, listener: (this: SVGFEDiffuseLightingElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEDiffuseLightingElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGFEDiffuseLightingElement: { + prototype: SVGFEDiffuseLightingElement; + new(): SVGFEDiffuseLightingElement; +}; + +interface SVGFEDisplacementMapElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + readonly in1: SVGAnimatedString; + readonly in2: SVGAnimatedString; + readonly scale: SVGAnimatedNumber; + readonly xChannelSelector: SVGAnimatedEnumeration; + readonly yChannelSelector: SVGAnimatedEnumeration; + readonly SVG_CHANNEL_A: number; + readonly SVG_CHANNEL_B: number; + readonly SVG_CHANNEL_G: number; + readonly SVG_CHANNEL_R: number; + readonly SVG_CHANNEL_UNKNOWN: number; + addEventListener(type: K, listener: (this: SVGFEDisplacementMapElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEDisplacementMapElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGFEDisplacementMapElement: { + prototype: SVGFEDisplacementMapElement; + new(): SVGFEDisplacementMapElement; + readonly SVG_CHANNEL_A: number; + readonly SVG_CHANNEL_B: number; + readonly SVG_CHANNEL_G: number; + readonly SVG_CHANNEL_R: number; + readonly SVG_CHANNEL_UNKNOWN: number; +}; + +interface SVGFEDistantLightElement extends SVGElement { + readonly azimuth: SVGAnimatedNumber; + readonly elevation: SVGAnimatedNumber; + addEventListener(type: K, listener: (this: SVGFEDistantLightElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEDistantLightElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGFEDistantLightElement: { + prototype: SVGFEDistantLightElement; + new(): SVGFEDistantLightElement; +}; + +interface SVGFEFloodElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + addEventListener(type: K, listener: (this: SVGFEFloodElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEFloodElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGFEFloodElement: { + prototype: SVGFEFloodElement; + new(): SVGFEFloodElement; +}; + +interface SVGFEFuncAElement extends SVGComponentTransferFunctionElement { + addEventListener(type: K, listener: (this: SVGFEFuncAElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEFuncAElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGFEFuncAElement: { + prototype: SVGFEFuncAElement; + new(): SVGFEFuncAElement; +}; + +interface SVGFEFuncBElement extends SVGComponentTransferFunctionElement { + addEventListener(type: K, listener: (this: SVGFEFuncBElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEFuncBElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGFEFuncBElement: { + prototype: SVGFEFuncBElement; + new(): SVGFEFuncBElement; +}; + +interface SVGFEFuncGElement extends SVGComponentTransferFunctionElement { + addEventListener(type: K, listener: (this: SVGFEFuncGElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEFuncGElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGFEFuncGElement: { + prototype: SVGFEFuncGElement; + new(): SVGFEFuncGElement; +}; + +interface SVGFEFuncRElement extends SVGComponentTransferFunctionElement { + addEventListener(type: K, listener: (this: SVGFEFuncRElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEFuncRElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGFEFuncRElement: { + prototype: SVGFEFuncRElement; + new(): SVGFEFuncRElement; +}; + +interface SVGFEGaussianBlurElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + readonly in1: SVGAnimatedString; + readonly stdDeviationX: SVGAnimatedNumber; + readonly stdDeviationY: SVGAnimatedNumber; + setStdDeviation(stdDeviationX: number, stdDeviationY: number): void; + addEventListener(type: K, listener: (this: SVGFEGaussianBlurElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEGaussianBlurElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGFEGaussianBlurElement: { + prototype: SVGFEGaussianBlurElement; + new(): SVGFEGaussianBlurElement; +}; + +interface SVGFEImageElement extends SVGElement, SVGFilterPrimitiveStandardAttributes, SVGURIReference { + readonly preserveAspectRatio: SVGAnimatedPreserveAspectRatio; + addEventListener(type: K, listener: (this: SVGFEImageElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEImageElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGFEImageElement: { + prototype: SVGFEImageElement; + new(): SVGFEImageElement; +}; + +interface SVGFEMergeElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + addEventListener(type: K, listener: (this: SVGFEMergeElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEMergeElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGFEMergeElement: { + prototype: SVGFEMergeElement; + new(): SVGFEMergeElement; +}; + +interface SVGFEMergeNodeElement extends SVGElement { + readonly in1: SVGAnimatedString; + addEventListener(type: K, listener: (this: SVGFEMergeNodeElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEMergeNodeElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGFEMergeNodeElement: { + prototype: SVGFEMergeNodeElement; + new(): SVGFEMergeNodeElement; +}; + +interface SVGFEMorphologyElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + readonly in1: SVGAnimatedString; + readonly operator: SVGAnimatedEnumeration; + readonly radiusX: SVGAnimatedNumber; + readonly radiusY: SVGAnimatedNumber; + readonly SVG_MORPHOLOGY_OPERATOR_DILATE: number; + readonly SVG_MORPHOLOGY_OPERATOR_ERODE: number; + readonly SVG_MORPHOLOGY_OPERATOR_UNKNOWN: number; + addEventListener(type: K, listener: (this: SVGFEMorphologyElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEMorphologyElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGFEMorphologyElement: { + prototype: SVGFEMorphologyElement; + new(): SVGFEMorphologyElement; + readonly SVG_MORPHOLOGY_OPERATOR_DILATE: number; + readonly SVG_MORPHOLOGY_OPERATOR_ERODE: number; + readonly SVG_MORPHOLOGY_OPERATOR_UNKNOWN: number; +}; + +interface SVGFEOffsetElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + readonly dx: SVGAnimatedNumber; + readonly dy: SVGAnimatedNumber; + readonly in1: SVGAnimatedString; + addEventListener(type: K, listener: (this: SVGFEOffsetElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEOffsetElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGFEOffsetElement: { + prototype: SVGFEOffsetElement; + new(): SVGFEOffsetElement; +}; + +interface SVGFEPointLightElement extends SVGElement { + readonly x: SVGAnimatedNumber; + readonly y: SVGAnimatedNumber; + readonly z: SVGAnimatedNumber; + addEventListener(type: K, listener: (this: SVGFEPointLightElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEPointLightElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGFEPointLightElement: { + prototype: SVGFEPointLightElement; + new(): SVGFEPointLightElement; +}; + +interface SVGFESpecularLightingElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + readonly in1: SVGAnimatedString; + readonly kernelUnitLengthX: SVGAnimatedNumber; + readonly kernelUnitLengthY: SVGAnimatedNumber; + readonly specularConstant: SVGAnimatedNumber; + readonly specularExponent: SVGAnimatedNumber; + readonly surfaceScale: SVGAnimatedNumber; + addEventListener(type: K, listener: (this: SVGFESpecularLightingElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFESpecularLightingElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGFESpecularLightingElement: { + prototype: SVGFESpecularLightingElement; + new(): SVGFESpecularLightingElement; +}; + +interface SVGFESpotLightElement extends SVGElement { + readonly limitingConeAngle: SVGAnimatedNumber; + readonly pointsAtX: SVGAnimatedNumber; + readonly pointsAtY: SVGAnimatedNumber; + readonly pointsAtZ: SVGAnimatedNumber; + readonly specularExponent: SVGAnimatedNumber; + readonly x: SVGAnimatedNumber; + readonly y: SVGAnimatedNumber; + readonly z: SVGAnimatedNumber; + addEventListener(type: K, listener: (this: SVGFESpotLightElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFESpotLightElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGFESpotLightElement: { + prototype: SVGFESpotLightElement; + new(): SVGFESpotLightElement; +}; + +interface SVGFETileElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + readonly in1: SVGAnimatedString; + addEventListener(type: K, listener: (this: SVGFETileElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFETileElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGFETileElement: { + prototype: SVGFETileElement; + new(): SVGFETileElement; +}; + +interface SVGFETurbulenceElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + readonly baseFrequencyX: SVGAnimatedNumber; + readonly baseFrequencyY: SVGAnimatedNumber; + readonly numOctaves: SVGAnimatedInteger; + readonly seed: SVGAnimatedNumber; + readonly stitchTiles: SVGAnimatedEnumeration; + readonly type: SVGAnimatedEnumeration; + readonly SVG_STITCHTYPE_NOSTITCH: number; + readonly SVG_STITCHTYPE_STITCH: number; + readonly SVG_STITCHTYPE_UNKNOWN: number; + readonly SVG_TURBULENCE_TYPE_FRACTALNOISE: number; + readonly SVG_TURBULENCE_TYPE_TURBULENCE: number; + readonly SVG_TURBULENCE_TYPE_UNKNOWN: number; + addEventListener(type: K, listener: (this: SVGFETurbulenceElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFETurbulenceElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGFETurbulenceElement: { + prototype: SVGFETurbulenceElement; + new(): SVGFETurbulenceElement; + readonly SVG_STITCHTYPE_NOSTITCH: number; + readonly SVG_STITCHTYPE_STITCH: number; + readonly SVG_STITCHTYPE_UNKNOWN: number; + readonly SVG_TURBULENCE_TYPE_FRACTALNOISE: number; + readonly SVG_TURBULENCE_TYPE_TURBULENCE: number; + readonly SVG_TURBULENCE_TYPE_UNKNOWN: number; +}; + +interface SVGFilterElement extends SVGElement, SVGURIReference { + /** @deprecated */ + readonly filterResX: SVGAnimatedInteger; + /** @deprecated */ + readonly filterResY: SVGAnimatedInteger; + readonly filterUnits: SVGAnimatedEnumeration; + readonly height: SVGAnimatedLength; + readonly primitiveUnits: SVGAnimatedEnumeration; + readonly width: SVGAnimatedLength; + readonly x: SVGAnimatedLength; + readonly y: SVGAnimatedLength; + /** @deprecated */ + setFilterRes(filterResX: number, filterResY: number): void; + addEventListener(type: K, listener: (this: SVGFilterElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFilterElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGFilterElement: { + prototype: SVGFilterElement; + new(): SVGFilterElement; +}; + +interface SVGFilterPrimitiveStandardAttributes { + readonly height: SVGAnimatedLength; + readonly result: SVGAnimatedString; + readonly width: SVGAnimatedLength; + readonly x: SVGAnimatedLength; + readonly y: SVGAnimatedLength; +} + +interface SVGFitToViewBox { + readonly preserveAspectRatio: SVGAnimatedPreserveAspectRatio; + readonly viewBox: SVGAnimatedRect; +} + +interface SVGForeignObjectElement extends SVGGraphicsElement { + readonly height: SVGAnimatedLength; + readonly width: SVGAnimatedLength; + readonly x: SVGAnimatedLength; + readonly y: SVGAnimatedLength; + addEventListener(type: K, listener: (this: SVGForeignObjectElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGForeignObjectElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGForeignObjectElement: { + prototype: SVGForeignObjectElement; + new(): SVGForeignObjectElement; +}; + +interface SVGGElement extends SVGGraphicsElement { + addEventListener(type: K, listener: (this: SVGGElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGGElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGGElement: { + prototype: SVGGElement; + new(): SVGGElement; +}; + +interface SVGGeometryElement extends SVGGraphicsElement { + readonly pathLength: SVGAnimatedNumber; + getPointAtLength(distance: number): DOMPoint; + getTotalLength(): number; + isPointInFill(point?: DOMPointInit): boolean; + isPointInStroke(point?: DOMPointInit): boolean; + addEventListener(type: K, listener: (this: SVGGeometryElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGGeometryElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGGeometryElement: { + prototype: SVGGeometryElement; + new(): SVGGeometryElement; +}; + +interface SVGGradientElement extends SVGElement, SVGURIReference { + readonly gradientTransform: SVGAnimatedTransformList; + readonly gradientUnits: SVGAnimatedEnumeration; + readonly spreadMethod: SVGAnimatedEnumeration; + readonly SVG_SPREADMETHOD_PAD: number; + readonly SVG_SPREADMETHOD_REFLECT: number; + readonly SVG_SPREADMETHOD_REPEAT: number; + readonly SVG_SPREADMETHOD_UNKNOWN: number; + addEventListener(type: K, listener: (this: SVGGradientElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGGradientElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGGradientElement: { + prototype: SVGGradientElement; + new(): SVGGradientElement; + readonly SVG_SPREADMETHOD_PAD: number; + readonly SVG_SPREADMETHOD_REFLECT: number; + readonly SVG_SPREADMETHOD_REPEAT: number; + readonly SVG_SPREADMETHOD_UNKNOWN: number; +}; + +interface SVGGraphicsElement extends SVGElement, SVGTests { + readonly transform: SVGAnimatedTransformList; + getBBox(options?: SVGBoundingBoxOptions): DOMRect; + getCTM(): DOMMatrix | null; + getScreenCTM(): DOMMatrix | null; + addEventListener(type: K, listener: (this: SVGGraphicsElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGGraphicsElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGGraphicsElement: { + prototype: SVGGraphicsElement; + new(): SVGGraphicsElement; +}; + +interface SVGImageElement extends SVGGraphicsElement, SVGURIReference { + readonly height: SVGAnimatedLength; + readonly preserveAspectRatio: SVGAnimatedPreserveAspectRatio; + readonly width: SVGAnimatedLength; + readonly x: SVGAnimatedLength; + readonly y: SVGAnimatedLength; + addEventListener(type: K, listener: (this: SVGImageElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGImageElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGImageElement: { + prototype: SVGImageElement; + new(): SVGImageElement; +}; + +interface SVGLength { + readonly unitType: number; + value: number; + valueAsString: string; + valueInSpecifiedUnits: number; + convertToSpecifiedUnits(unitType: number): void; + newValueSpecifiedUnits(unitType: number, valueInSpecifiedUnits: number): void; + readonly SVG_LENGTHTYPE_CM: number; + readonly SVG_LENGTHTYPE_EMS: number; + readonly SVG_LENGTHTYPE_EXS: number; + readonly SVG_LENGTHTYPE_IN: number; + readonly SVG_LENGTHTYPE_MM: number; + readonly SVG_LENGTHTYPE_NUMBER: number; + readonly SVG_LENGTHTYPE_PC: number; + readonly SVG_LENGTHTYPE_PERCENTAGE: number; + readonly SVG_LENGTHTYPE_PT: number; + readonly SVG_LENGTHTYPE_PX: number; + readonly SVG_LENGTHTYPE_UNKNOWN: number; +} + +declare var SVGLength: { + prototype: SVGLength; + new(): SVGLength; + readonly SVG_LENGTHTYPE_CM: number; + readonly SVG_LENGTHTYPE_EMS: number; + readonly SVG_LENGTHTYPE_EXS: number; + readonly SVG_LENGTHTYPE_IN: number; + readonly SVG_LENGTHTYPE_MM: number; + readonly SVG_LENGTHTYPE_NUMBER: number; + readonly SVG_LENGTHTYPE_PC: number; + readonly SVG_LENGTHTYPE_PERCENTAGE: number; + readonly SVG_LENGTHTYPE_PT: number; + readonly SVG_LENGTHTYPE_PX: number; + readonly SVG_LENGTHTYPE_UNKNOWN: number; +}; + +interface SVGLengthList { + readonly length: number; + readonly numberOfItems: number; + appendItem(newItem: SVGLength): SVGLength; + clear(): void; + getItem(index: number): SVGLength; + initialize(newItem: SVGLength): SVGLength; + insertItemBefore(newItem: SVGLength, index: number): SVGLength; + removeItem(index: number): SVGLength; + replaceItem(newItem: SVGLength, index: number): SVGLength; + [index: number]: SVGLength; +} + +declare var SVGLengthList: { + prototype: SVGLengthList; + new(): SVGLengthList; +}; + +interface SVGLineElement extends SVGGraphicsElement { + readonly x1: SVGAnimatedLength; + readonly x2: SVGAnimatedLength; + readonly y1: SVGAnimatedLength; + readonly y2: SVGAnimatedLength; + addEventListener(type: K, listener: (this: SVGLineElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGLineElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGLineElement: { + prototype: SVGLineElement; + new(): SVGLineElement; +}; + +interface SVGLinearGradientElement extends SVGGradientElement { + readonly x1: SVGAnimatedLength; + readonly x2: SVGAnimatedLength; + readonly y1: SVGAnimatedLength; + readonly y2: SVGAnimatedLength; + addEventListener(type: K, listener: (this: SVGLinearGradientElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGLinearGradientElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGLinearGradientElement: { + prototype: SVGLinearGradientElement; + new(): SVGLinearGradientElement; +}; + +interface SVGMarkerElement extends SVGElement, SVGFitToViewBox { + readonly markerHeight: SVGAnimatedLength; + readonly markerUnits: SVGAnimatedEnumeration; + readonly markerWidth: SVGAnimatedLength; + readonly orientAngle: SVGAnimatedAngle; + readonly orientType: SVGAnimatedEnumeration; + readonly refX: SVGAnimatedLength; + readonly refY: SVGAnimatedLength; + setOrientToAngle(angle: SVGAngle): void; + setOrientToAuto(): void; + readonly SVG_MARKERUNITS_STROKEWIDTH: number; + readonly SVG_MARKERUNITS_UNKNOWN: number; + readonly SVG_MARKERUNITS_USERSPACEONUSE: number; + readonly SVG_MARKER_ORIENT_ANGLE: number; + readonly SVG_MARKER_ORIENT_AUTO: number; + readonly SVG_MARKER_ORIENT_UNKNOWN: number; + addEventListener(type: K, listener: (this: SVGMarkerElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGMarkerElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGMarkerElement: { + prototype: SVGMarkerElement; + new(): SVGMarkerElement; + readonly SVG_MARKERUNITS_STROKEWIDTH: number; + readonly SVG_MARKERUNITS_UNKNOWN: number; + readonly SVG_MARKERUNITS_USERSPACEONUSE: number; + readonly SVG_MARKER_ORIENT_ANGLE: number; + readonly SVG_MARKER_ORIENT_AUTO: number; + readonly SVG_MARKER_ORIENT_UNKNOWN: number; +}; + +interface SVGMaskElement extends SVGElement, SVGTests { + readonly height: SVGAnimatedLength; + readonly maskContentUnits: SVGAnimatedEnumeration; + readonly maskUnits: SVGAnimatedEnumeration; + readonly width: SVGAnimatedLength; + readonly x: SVGAnimatedLength; + readonly y: SVGAnimatedLength; + addEventListener(type: K, listener: (this: SVGMaskElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGMaskElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGMaskElement: { + prototype: SVGMaskElement; + new(): SVGMaskElement; +}; + +interface SVGMetadataElement extends SVGElement { + addEventListener(type: K, listener: (this: SVGMetadataElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGMetadataElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGMetadataElement: { + prototype: SVGMetadataElement; + new(): SVGMetadataElement; +}; + +interface SVGNumber { + value: number; +} + +declare var SVGNumber: { + prototype: SVGNumber; + new(): SVGNumber; +}; + +interface SVGNumberList { + readonly length: number; + readonly numberOfItems: number; + appendItem(newItem: SVGNumber): SVGNumber; + clear(): void; + getItem(index: number): SVGNumber; + initialize(newItem: SVGNumber): SVGNumber; + insertItemBefore(newItem: SVGNumber, index: number): SVGNumber; + removeItem(index: number): SVGNumber; + replaceItem(newItem: SVGNumber, index: number): SVGNumber; + [index: number]: SVGNumber; +} + +declare var SVGNumberList: { + prototype: SVGNumberList; + new(): SVGNumberList; +}; + +interface SVGPathElement extends SVGGraphicsElement { + /** @deprecated */ + readonly pathSegList: SVGPathSegList; + /** @deprecated */ + createSVGPathSegArcAbs(x: number, y: number, r1: number, r2: number, angle: number, largeArcFlag: boolean, sweepFlag: boolean): SVGPathSegArcAbs; + /** @deprecated */ + createSVGPathSegArcRel(x: number, y: number, r1: number, r2: number, angle: number, largeArcFlag: boolean, sweepFlag: boolean): SVGPathSegArcRel; + /** @deprecated */ + createSVGPathSegClosePath(): SVGPathSegClosePath; + /** @deprecated */ + createSVGPathSegCurvetoCubicAbs(x: number, y: number, x1: number, y1: number, x2: number, y2: number): SVGPathSegCurvetoCubicAbs; + /** @deprecated */ + createSVGPathSegCurvetoCubicRel(x: number, y: number, x1: number, y1: number, x2: number, y2: number): SVGPathSegCurvetoCubicRel; + /** @deprecated */ + createSVGPathSegCurvetoCubicSmoothAbs(x: number, y: number, x2: number, y2: number): SVGPathSegCurvetoCubicSmoothAbs; + /** @deprecated */ + createSVGPathSegCurvetoCubicSmoothRel(x: number, y: number, x2: number, y2: number): SVGPathSegCurvetoCubicSmoothRel; + /** @deprecated */ + createSVGPathSegCurvetoQuadraticAbs(x: number, y: number, x1: number, y1: number): SVGPathSegCurvetoQuadraticAbs; + /** @deprecated */ + createSVGPathSegCurvetoQuadraticRel(x: number, y: number, x1: number, y1: number): SVGPathSegCurvetoQuadraticRel; + /** @deprecated */ + createSVGPathSegCurvetoQuadraticSmoothAbs(x: number, y: number): SVGPathSegCurvetoQuadraticSmoothAbs; + /** @deprecated */ + createSVGPathSegCurvetoQuadraticSmoothRel(x: number, y: number): SVGPathSegCurvetoQuadraticSmoothRel; + /** @deprecated */ + createSVGPathSegLinetoAbs(x: number, y: number): SVGPathSegLinetoAbs; + /** @deprecated */ + createSVGPathSegLinetoHorizontalAbs(x: number): SVGPathSegLinetoHorizontalAbs; + /** @deprecated */ + createSVGPathSegLinetoHorizontalRel(x: number): SVGPathSegLinetoHorizontalRel; + /** @deprecated */ + createSVGPathSegLinetoRel(x: number, y: number): SVGPathSegLinetoRel; + /** @deprecated */ + createSVGPathSegLinetoVerticalAbs(y: number): SVGPathSegLinetoVerticalAbs; + /** @deprecated */ + createSVGPathSegLinetoVerticalRel(y: number): SVGPathSegLinetoVerticalRel; + /** @deprecated */ + createSVGPathSegMovetoAbs(x: number, y: number): SVGPathSegMovetoAbs; + /** @deprecated */ + createSVGPathSegMovetoRel(x: number, y: number): SVGPathSegMovetoRel; + /** @deprecated */ + getPathSegAtLength(distance: number): number; + getPointAtLength(distance: number): SVGPoint; + getTotalLength(): number; + addEventListener(type: K, listener: (this: SVGPathElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGPathElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGPathElement: { + prototype: SVGPathElement; + new(): SVGPathElement; +}; + +interface SVGPathSeg { + readonly pathSegType: number; + readonly pathSegTypeAsLetter: string; + readonly PATHSEG_ARC_ABS: number; + readonly PATHSEG_ARC_REL: number; + readonly PATHSEG_CLOSEPATH: number; + readonly PATHSEG_CURVETO_CUBIC_ABS: number; + readonly PATHSEG_CURVETO_CUBIC_REL: number; + readonly PATHSEG_CURVETO_CUBIC_SMOOTH_ABS: number; + readonly PATHSEG_CURVETO_CUBIC_SMOOTH_REL: number; + readonly PATHSEG_CURVETO_QUADRATIC_ABS: number; + readonly PATHSEG_CURVETO_QUADRATIC_REL: number; + readonly PATHSEG_CURVETO_QUADRATIC_SMOOTH_ABS: number; + readonly PATHSEG_CURVETO_QUADRATIC_SMOOTH_REL: number; + readonly PATHSEG_LINETO_ABS: number; + readonly PATHSEG_LINETO_HORIZONTAL_ABS: number; + readonly PATHSEG_LINETO_HORIZONTAL_REL: number; + readonly PATHSEG_LINETO_REL: number; + readonly PATHSEG_LINETO_VERTICAL_ABS: number; + readonly PATHSEG_LINETO_VERTICAL_REL: number; + readonly PATHSEG_MOVETO_ABS: number; + readonly PATHSEG_MOVETO_REL: number; + readonly PATHSEG_UNKNOWN: number; +} + +declare var SVGPathSeg: { + prototype: SVGPathSeg; + new(): SVGPathSeg; + readonly PATHSEG_ARC_ABS: number; + readonly PATHSEG_ARC_REL: number; + readonly PATHSEG_CLOSEPATH: number; + readonly PATHSEG_CURVETO_CUBIC_ABS: number; + readonly PATHSEG_CURVETO_CUBIC_REL: number; + readonly PATHSEG_CURVETO_CUBIC_SMOOTH_ABS: number; + readonly PATHSEG_CURVETO_CUBIC_SMOOTH_REL: number; + readonly PATHSEG_CURVETO_QUADRATIC_ABS: number; + readonly PATHSEG_CURVETO_QUADRATIC_REL: number; + readonly PATHSEG_CURVETO_QUADRATIC_SMOOTH_ABS: number; + readonly PATHSEG_CURVETO_QUADRATIC_SMOOTH_REL: number; + readonly PATHSEG_LINETO_ABS: number; + readonly PATHSEG_LINETO_HORIZONTAL_ABS: number; + readonly PATHSEG_LINETO_HORIZONTAL_REL: number; + readonly PATHSEG_LINETO_REL: number; + readonly PATHSEG_LINETO_VERTICAL_ABS: number; + readonly PATHSEG_LINETO_VERTICAL_REL: number; + readonly PATHSEG_MOVETO_ABS: number; + readonly PATHSEG_MOVETO_REL: number; + readonly PATHSEG_UNKNOWN: number; +}; + +interface SVGPathSegArcAbs extends SVGPathSeg { + angle: number; + largeArcFlag: boolean; + r1: number; + r2: number; + sweepFlag: boolean; + x: number; + y: number; +} + +declare var SVGPathSegArcAbs: { + prototype: SVGPathSegArcAbs; + new(): SVGPathSegArcAbs; +}; + +interface SVGPathSegArcRel extends SVGPathSeg { + angle: number; + largeArcFlag: boolean; + r1: number; + r2: number; + sweepFlag: boolean; + x: number; + y: number; +} + +declare var SVGPathSegArcRel: { + prototype: SVGPathSegArcRel; + new(): SVGPathSegArcRel; +}; + +interface SVGPathSegClosePath extends SVGPathSeg { +} + +declare var SVGPathSegClosePath: { + prototype: SVGPathSegClosePath; + new(): SVGPathSegClosePath; +}; + +interface SVGPathSegCurvetoCubicAbs extends SVGPathSeg { + x: number; + x1: number; + x2: number; + y: number; + y1: number; + y2: number; +} + +declare var SVGPathSegCurvetoCubicAbs: { + prototype: SVGPathSegCurvetoCubicAbs; + new(): SVGPathSegCurvetoCubicAbs; +}; + +interface SVGPathSegCurvetoCubicRel extends SVGPathSeg { + x: number; + x1: number; + x2: number; + y: number; + y1: number; + y2: number; +} + +declare var SVGPathSegCurvetoCubicRel: { + prototype: SVGPathSegCurvetoCubicRel; + new(): SVGPathSegCurvetoCubicRel; +}; + +interface SVGPathSegCurvetoCubicSmoothAbs extends SVGPathSeg { + x: number; + x2: number; + y: number; + y2: number; +} + +declare var SVGPathSegCurvetoCubicSmoothAbs: { + prototype: SVGPathSegCurvetoCubicSmoothAbs; + new(): SVGPathSegCurvetoCubicSmoothAbs; +}; + +interface SVGPathSegCurvetoCubicSmoothRel extends SVGPathSeg { + x: number; + x2: number; + y: number; + y2: number; +} + +declare var SVGPathSegCurvetoCubicSmoothRel: { + prototype: SVGPathSegCurvetoCubicSmoothRel; + new(): SVGPathSegCurvetoCubicSmoothRel; +}; + +interface SVGPathSegCurvetoQuadraticAbs extends SVGPathSeg { + x: number; + x1: number; + y: number; + y1: number; +} + +declare var SVGPathSegCurvetoQuadraticAbs: { + prototype: SVGPathSegCurvetoQuadraticAbs; + new(): SVGPathSegCurvetoQuadraticAbs; +}; + +interface SVGPathSegCurvetoQuadraticRel extends SVGPathSeg { + x: number; + x1: number; + y: number; + y1: number; +} + +declare var SVGPathSegCurvetoQuadraticRel: { + prototype: SVGPathSegCurvetoQuadraticRel; + new(): SVGPathSegCurvetoQuadraticRel; +}; + +interface SVGPathSegCurvetoQuadraticSmoothAbs extends SVGPathSeg { + x: number; + y: number; +} + +declare var SVGPathSegCurvetoQuadraticSmoothAbs: { + prototype: SVGPathSegCurvetoQuadraticSmoothAbs; + new(): SVGPathSegCurvetoQuadraticSmoothAbs; +}; + +interface SVGPathSegCurvetoQuadraticSmoothRel extends SVGPathSeg { + x: number; + y: number; +} + +declare var SVGPathSegCurvetoQuadraticSmoothRel: { + prototype: SVGPathSegCurvetoQuadraticSmoothRel; + new(): SVGPathSegCurvetoQuadraticSmoothRel; +}; + +interface SVGPathSegLinetoAbs extends SVGPathSeg { + x: number; + y: number; +} + +declare var SVGPathSegLinetoAbs: { + prototype: SVGPathSegLinetoAbs; + new(): SVGPathSegLinetoAbs; +}; + +interface SVGPathSegLinetoHorizontalAbs extends SVGPathSeg { + x: number; +} + +declare var SVGPathSegLinetoHorizontalAbs: { + prototype: SVGPathSegLinetoHorizontalAbs; + new(): SVGPathSegLinetoHorizontalAbs; +}; + +interface SVGPathSegLinetoHorizontalRel extends SVGPathSeg { + x: number; +} + +declare var SVGPathSegLinetoHorizontalRel: { + prototype: SVGPathSegLinetoHorizontalRel; + new(): SVGPathSegLinetoHorizontalRel; +}; + +interface SVGPathSegLinetoRel extends SVGPathSeg { + x: number; + y: number; +} + +declare var SVGPathSegLinetoRel: { + prototype: SVGPathSegLinetoRel; + new(): SVGPathSegLinetoRel; +}; + +interface SVGPathSegLinetoVerticalAbs extends SVGPathSeg { + y: number; +} + +declare var SVGPathSegLinetoVerticalAbs: { + prototype: SVGPathSegLinetoVerticalAbs; + new(): SVGPathSegLinetoVerticalAbs; +}; + +interface SVGPathSegLinetoVerticalRel extends SVGPathSeg { + y: number; +} + +declare var SVGPathSegLinetoVerticalRel: { + prototype: SVGPathSegLinetoVerticalRel; + new(): SVGPathSegLinetoVerticalRel; +}; + +interface SVGPathSegList { + readonly numberOfItems: number; + appendItem(newItem: SVGPathSeg): SVGPathSeg; + clear(): void; + getItem(index: number): SVGPathSeg; + initialize(newItem: SVGPathSeg): SVGPathSeg; + insertItemBefore(newItem: SVGPathSeg, index: number): SVGPathSeg; + removeItem(index: number): SVGPathSeg; + replaceItem(newItem: SVGPathSeg, index: number): SVGPathSeg; +} + +declare var SVGPathSegList: { + prototype: SVGPathSegList; + new(): SVGPathSegList; +}; + +interface SVGPathSegMovetoAbs extends SVGPathSeg { + x: number; + y: number; +} + +declare var SVGPathSegMovetoAbs: { + prototype: SVGPathSegMovetoAbs; + new(): SVGPathSegMovetoAbs; +}; + +interface SVGPathSegMovetoRel extends SVGPathSeg { + x: number; + y: number; +} + +declare var SVGPathSegMovetoRel: { + prototype: SVGPathSegMovetoRel; + new(): SVGPathSegMovetoRel; +}; + +interface SVGPatternElement extends SVGElement, SVGTests, SVGFitToViewBox, SVGURIReference { + readonly height: SVGAnimatedLength; + readonly patternContentUnits: SVGAnimatedEnumeration; + readonly patternTransform: SVGAnimatedTransformList; + readonly patternUnits: SVGAnimatedEnumeration; + readonly width: SVGAnimatedLength; + readonly x: SVGAnimatedLength; + readonly y: SVGAnimatedLength; + addEventListener(type: K, listener: (this: SVGPatternElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGPatternElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGPatternElement: { + prototype: SVGPatternElement; + new(): SVGPatternElement; +}; + +interface SVGPointList { + readonly numberOfItems: number; + appendItem(newItem: SVGPoint): SVGPoint; + clear(): void; + getItem(index: number): SVGPoint; + initialize(newItem: SVGPoint): SVGPoint; + insertItemBefore(newItem: SVGPoint, index: number): SVGPoint; + removeItem(index: number): SVGPoint; + replaceItem(newItem: SVGPoint, index: number): SVGPoint; +} + +declare var SVGPointList: { + prototype: SVGPointList; + new(): SVGPointList; +}; + +interface SVGPolygonElement extends SVGGraphicsElement, SVGAnimatedPoints { + addEventListener(type: K, listener: (this: SVGPolygonElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGPolygonElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGPolygonElement: { + prototype: SVGPolygonElement; + new(): SVGPolygonElement; +}; + +interface SVGPolylineElement extends SVGGraphicsElement, SVGAnimatedPoints { + addEventListener(type: K, listener: (this: SVGPolylineElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGPolylineElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGPolylineElement: { + prototype: SVGPolylineElement; + new(): SVGPolylineElement; +}; + +interface SVGPreserveAspectRatio { + align: number; + meetOrSlice: number; + readonly SVG_MEETORSLICE_MEET: number; + readonly SVG_MEETORSLICE_SLICE: number; + readonly SVG_MEETORSLICE_UNKNOWN: number; + readonly SVG_PRESERVEASPECTRATIO_NONE: number; + readonly SVG_PRESERVEASPECTRATIO_UNKNOWN: number; + readonly SVG_PRESERVEASPECTRATIO_XMAXYMAX: number; + readonly SVG_PRESERVEASPECTRATIO_XMAXYMID: number; + readonly SVG_PRESERVEASPECTRATIO_XMAXYMIN: number; + readonly SVG_PRESERVEASPECTRATIO_XMIDYMAX: number; + readonly SVG_PRESERVEASPECTRATIO_XMIDYMID: number; + readonly SVG_PRESERVEASPECTRATIO_XMIDYMIN: number; + readonly SVG_PRESERVEASPECTRATIO_XMINYMAX: number; + readonly SVG_PRESERVEASPECTRATIO_XMINYMID: number; + readonly SVG_PRESERVEASPECTRATIO_XMINYMIN: number; +} + +declare var SVGPreserveAspectRatio: { + prototype: SVGPreserveAspectRatio; + new(): SVGPreserveAspectRatio; + readonly SVG_MEETORSLICE_MEET: number; + readonly SVG_MEETORSLICE_SLICE: number; + readonly SVG_MEETORSLICE_UNKNOWN: number; + readonly SVG_PRESERVEASPECTRATIO_NONE: number; + readonly SVG_PRESERVEASPECTRATIO_UNKNOWN: number; + readonly SVG_PRESERVEASPECTRATIO_XMAXYMAX: number; + readonly SVG_PRESERVEASPECTRATIO_XMAXYMID: number; + readonly SVG_PRESERVEASPECTRATIO_XMAXYMIN: number; + readonly SVG_PRESERVEASPECTRATIO_XMIDYMAX: number; + readonly SVG_PRESERVEASPECTRATIO_XMIDYMID: number; + readonly SVG_PRESERVEASPECTRATIO_XMIDYMIN: number; + readonly SVG_PRESERVEASPECTRATIO_XMINYMAX: number; + readonly SVG_PRESERVEASPECTRATIO_XMINYMID: number; + readonly SVG_PRESERVEASPECTRATIO_XMINYMIN: number; +}; + +interface SVGRadialGradientElement extends SVGGradientElement { + readonly cx: SVGAnimatedLength; + readonly cy: SVGAnimatedLength; + readonly fx: SVGAnimatedLength; + readonly fy: SVGAnimatedLength; + readonly r: SVGAnimatedLength; + addEventListener(type: K, listener: (this: SVGRadialGradientElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGRadialGradientElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGRadialGradientElement: { + prototype: SVGRadialGradientElement; + new(): SVGRadialGradientElement; +}; + +interface SVGRectElement extends SVGGraphicsElement { + readonly height: SVGAnimatedLength; + readonly rx: SVGAnimatedLength; + readonly ry: SVGAnimatedLength; + readonly width: SVGAnimatedLength; + readonly x: SVGAnimatedLength; + readonly y: SVGAnimatedLength; + addEventListener(type: K, listener: (this: SVGRectElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGRectElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGRectElement: { + prototype: SVGRectElement; + new(): SVGRectElement; +}; + +interface SVGSVGElementEventMap extends SVGElementEventMap { + "SVGUnload": Event; + "SVGZoom": SVGZoomEvent; +} + +interface SVGSVGElement extends SVGGraphicsElement, DocumentEvent, SVGFitToViewBox, SVGZoomAndPan { + /** @deprecated */ + contentScriptType: string; + /** @deprecated */ + contentStyleType: string; + currentScale: number; + readonly currentTranslate: SVGPoint; + readonly height: SVGAnimatedLength; + onunload: ((this: SVGSVGElement, ev: Event) => any) | null; + onzoom: ((this: SVGSVGElement, ev: SVGZoomEvent) => any) | null; + /** @deprecated */ + readonly pixelUnitToMillimeterX: number; + /** @deprecated */ + readonly pixelUnitToMillimeterY: number; + /** @deprecated */ + readonly screenPixelToMillimeterX: number; + /** @deprecated */ + readonly screenPixelToMillimeterY: number; + /** @deprecated */ + readonly viewport: SVGRect; + readonly width: SVGAnimatedLength; + readonly x: SVGAnimatedLength; + readonly y: SVGAnimatedLength; + checkEnclosure(element: SVGElement, rect: SVGRect): boolean; + checkIntersection(element: SVGElement, rect: SVGRect): boolean; + createSVGAngle(): SVGAngle; + createSVGLength(): SVGLength; + createSVGMatrix(): SVGMatrix; + createSVGNumber(): SVGNumber; + createSVGPoint(): SVGPoint; + createSVGRect(): SVGRect; + createSVGTransform(): SVGTransform; + createSVGTransformFromMatrix(matrix: SVGMatrix): SVGTransform; + deselectAll(): void; + /** @deprecated */ + forceRedraw(): void; + getComputedStyle(elt: Element, pseudoElt?: string | null): CSSStyleDeclaration; + /** @deprecated */ + getCurrentTime(): number; + getElementById(elementId: string): Element; + getEnclosureList(rect: SVGRect, referenceElement: SVGElement): NodeListOf; + getIntersectionList(rect: SVGRect, referenceElement: SVGElement): NodeListOf; + /** @deprecated */ + pauseAnimations(): void; + /** @deprecated */ + setCurrentTime(seconds: number): void; + /** @deprecated */ + suspendRedraw(maxWaitMilliseconds: number): number; + /** @deprecated */ + unpauseAnimations(): void; + /** @deprecated */ + unsuspendRedraw(suspendHandleID: number): void; + /** @deprecated */ + unsuspendRedrawAll(): void; + addEventListener(type: K, listener: (this: SVGSVGElement, ev: SVGSVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGSVGElement, ev: SVGSVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGSVGElement: { + prototype: SVGSVGElement; + new(): SVGSVGElement; + readonly SVG_ZOOMANDPAN_DISABLE: number; + readonly SVG_ZOOMANDPAN_MAGNIFY: number; + readonly SVG_ZOOMANDPAN_UNKNOWN: number; +}; + +interface SVGScriptElement extends SVGElement, SVGURIReference { + type: string; + addEventListener(type: K, listener: (this: SVGScriptElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGScriptElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGScriptElement: { + prototype: SVGScriptElement; + new(): SVGScriptElement; +}; + +interface SVGStopElement extends SVGElement { + readonly offset: SVGAnimatedNumber; + addEventListener(type: K, listener: (this: SVGStopElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGStopElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGStopElement: { + prototype: SVGStopElement; + new(): SVGStopElement; +}; + +interface SVGStringList { + readonly length: number; + readonly numberOfItems: number; + appendItem(newItem: string): string; + clear(): void; + getItem(index: number): string; + initialize(newItem: string): string; + insertItemBefore(newItem: string, index: number): string; + removeItem(index: number): string; + replaceItem(newItem: string, index: number): string; + [index: number]: string; +} + +declare var SVGStringList: { + prototype: SVGStringList; + new(): SVGStringList; +}; + +interface SVGStyleElement extends SVGElement { + disabled: boolean; + media: string; + title: string; + type: string; + addEventListener(type: K, listener: (this: SVGStyleElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGStyleElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGStyleElement: { + prototype: SVGStyleElement; + new(): SVGStyleElement; +}; + +interface SVGSwitchElement extends SVGGraphicsElement { + addEventListener(type: K, listener: (this: SVGSwitchElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGSwitchElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGSwitchElement: { + prototype: SVGSwitchElement; + new(): SVGSwitchElement; +}; + +interface SVGSymbolElement extends SVGElement, SVGFitToViewBox { + addEventListener(type: K, listener: (this: SVGSymbolElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGSymbolElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGSymbolElement: { + prototype: SVGSymbolElement; + new(): SVGSymbolElement; +}; + +interface SVGTSpanElement extends SVGTextPositioningElement { + addEventListener(type: K, listener: (this: SVGTSpanElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGTSpanElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGTSpanElement: { + prototype: SVGTSpanElement; + new(): SVGTSpanElement; +}; + +interface SVGTests { + readonly requiredExtensions: SVGStringList; + readonly systemLanguage: SVGStringList; +} + +interface SVGTextContentElement extends SVGGraphicsElement { + readonly lengthAdjust: SVGAnimatedEnumeration; + readonly textLength: SVGAnimatedLength; + getCharNumAtPosition(point: SVGPoint): number; + getComputedTextLength(): number; + getEndPositionOfChar(charnum: number): SVGPoint; + getExtentOfChar(charnum: number): SVGRect; + getNumberOfChars(): number; + getRotationOfChar(charnum: number): number; + getStartPositionOfChar(charnum: number): SVGPoint; + getSubStringLength(charnum: number, nchars: number): number; + selectSubString(charnum: number, nchars: number): void; + readonly LENGTHADJUST_SPACING: number; + readonly LENGTHADJUST_SPACINGANDGLYPHS: number; + readonly LENGTHADJUST_UNKNOWN: number; + addEventListener(type: K, listener: (this: SVGTextContentElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGTextContentElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGTextContentElement: { + prototype: SVGTextContentElement; + new(): SVGTextContentElement; + readonly LENGTHADJUST_SPACING: number; + readonly LENGTHADJUST_SPACINGANDGLYPHS: number; + readonly LENGTHADJUST_UNKNOWN: number; +}; + +interface SVGTextElement extends SVGTextPositioningElement { + addEventListener(type: K, listener: (this: SVGTextElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGTextElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGTextElement: { + prototype: SVGTextElement; + new(): SVGTextElement; +}; + +interface SVGTextPathElement extends SVGTextContentElement, SVGURIReference { + readonly method: SVGAnimatedEnumeration; + readonly spacing: SVGAnimatedEnumeration; + readonly startOffset: SVGAnimatedLength; + readonly TEXTPATH_METHODTYPE_ALIGN: number; + readonly TEXTPATH_METHODTYPE_STRETCH: number; + readonly TEXTPATH_METHODTYPE_UNKNOWN: number; + readonly TEXTPATH_SPACINGTYPE_AUTO: number; + readonly TEXTPATH_SPACINGTYPE_EXACT: number; + readonly TEXTPATH_SPACINGTYPE_UNKNOWN: number; + addEventListener(type: K, listener: (this: SVGTextPathElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGTextPathElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGTextPathElement: { + prototype: SVGTextPathElement; + new(): SVGTextPathElement; + readonly TEXTPATH_METHODTYPE_ALIGN: number; + readonly TEXTPATH_METHODTYPE_STRETCH: number; + readonly TEXTPATH_METHODTYPE_UNKNOWN: number; + readonly TEXTPATH_SPACINGTYPE_AUTO: number; + readonly TEXTPATH_SPACINGTYPE_EXACT: number; + readonly TEXTPATH_SPACINGTYPE_UNKNOWN: number; +}; + +interface SVGTextPositioningElement extends SVGTextContentElement { + readonly dx: SVGAnimatedLengthList; + readonly dy: SVGAnimatedLengthList; + readonly rotate: SVGAnimatedNumberList; + readonly x: SVGAnimatedLengthList; + readonly y: SVGAnimatedLengthList; + addEventListener(type: K, listener: (this: SVGTextPositioningElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGTextPositioningElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGTextPositioningElement: { + prototype: SVGTextPositioningElement; + new(): SVGTextPositioningElement; +}; + +interface SVGTitleElement extends SVGElement { + addEventListener(type: K, listener: (this: SVGTitleElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGTitleElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGTitleElement: { + prototype: SVGTitleElement; + new(): SVGTitleElement; +}; + +interface SVGTransform { + readonly angle: number; + readonly matrix: SVGMatrix; + readonly type: number; + setMatrix(matrix: SVGMatrix): void; + setRotate(angle: number, cx: number, cy: number): void; + setScale(sx: number, sy: number): void; + setSkewX(angle: number): void; + setSkewY(angle: number): void; + setTranslate(tx: number, ty: number): void; + readonly SVG_TRANSFORM_MATRIX: number; + readonly SVG_TRANSFORM_ROTATE: number; + readonly SVG_TRANSFORM_SCALE: number; + readonly SVG_TRANSFORM_SKEWX: number; + readonly SVG_TRANSFORM_SKEWY: number; + readonly SVG_TRANSFORM_TRANSLATE: number; + readonly SVG_TRANSFORM_UNKNOWN: number; +} + +declare var SVGTransform: { + prototype: SVGTransform; + new(): SVGTransform; + readonly SVG_TRANSFORM_MATRIX: number; + readonly SVG_TRANSFORM_ROTATE: number; + readonly SVG_TRANSFORM_SCALE: number; + readonly SVG_TRANSFORM_SKEWX: number; + readonly SVG_TRANSFORM_SKEWY: number; + readonly SVG_TRANSFORM_TRANSLATE: number; + readonly SVG_TRANSFORM_UNKNOWN: number; +}; + +interface SVGTransformList { + readonly numberOfItems: number; + appendItem(newItem: SVGTransform): SVGTransform; + clear(): void; + consolidate(): SVGTransform; + createSVGTransformFromMatrix(matrix: SVGMatrix): SVGTransform; + getItem(index: number): SVGTransform; + initialize(newItem: SVGTransform): SVGTransform; + insertItemBefore(newItem: SVGTransform, index: number): SVGTransform; + removeItem(index: number): SVGTransform; + replaceItem(newItem: SVGTransform, index: number): SVGTransform; +} + +declare var SVGTransformList: { + prototype: SVGTransformList; + new(): SVGTransformList; +}; + +interface SVGURIReference { + readonly href: SVGAnimatedString; +} + +interface SVGUnitTypes { + readonly SVG_UNIT_TYPE_OBJECTBOUNDINGBOX: number; + readonly SVG_UNIT_TYPE_UNKNOWN: number; + readonly SVG_UNIT_TYPE_USERSPACEONUSE: number; +} + +declare var SVGUnitTypes: { + prototype: SVGUnitTypes; + new(): SVGUnitTypes; + readonly SVG_UNIT_TYPE_OBJECTBOUNDINGBOX: number; + readonly SVG_UNIT_TYPE_UNKNOWN: number; + readonly SVG_UNIT_TYPE_USERSPACEONUSE: number; +}; + +interface SVGUseElement extends SVGGraphicsElement, SVGURIReference { + readonly animatedInstanceRoot: SVGElementInstance | null; + readonly height: SVGAnimatedLength; + readonly instanceRoot: SVGElementInstance | null; + readonly width: SVGAnimatedLength; + readonly x: SVGAnimatedLength; + readonly y: SVGAnimatedLength; + addEventListener(type: K, listener: (this: SVGUseElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGUseElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGUseElement: { + prototype: SVGUseElement; + new(): SVGUseElement; +}; + +interface SVGViewElement extends SVGElement, SVGFitToViewBox, SVGZoomAndPan { + /** @deprecated */ + readonly viewTarget: SVGStringList; + addEventListener(type: K, listener: (this: SVGViewElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGViewElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGViewElement: { + prototype: SVGViewElement; + new(): SVGViewElement; + readonly SVG_ZOOMANDPAN_DISABLE: number; + readonly SVG_ZOOMANDPAN_MAGNIFY: number; + readonly SVG_ZOOMANDPAN_UNKNOWN: number; +}; + +interface SVGZoomAndPan { + readonly zoomAndPan: number; +} + +declare var SVGZoomAndPan: { + readonly SVG_ZOOMANDPAN_DISABLE: number; + readonly SVG_ZOOMANDPAN_MAGNIFY: number; + readonly SVG_ZOOMANDPAN_UNKNOWN: number; +}; + +interface SVGZoomEvent extends UIEvent { + readonly newScale: number; + readonly newTranslate: SVGPoint; + readonly previousScale: number; + readonly previousTranslate: SVGPoint; + readonly zoomRectScreen: SVGRect; +} + +declare var SVGZoomEvent: { + prototype: SVGZoomEvent; + new(): SVGZoomEvent; +}; + +interface ScopedCredential { + readonly id: ArrayBuffer; + readonly type: ScopedCredentialType; +} + +declare var ScopedCredential: { + prototype: ScopedCredential; + new(): ScopedCredential; +}; + +interface ScopedCredentialInfo { + readonly credential: ScopedCredential; + readonly publicKey: CryptoKey; +} + +declare var ScopedCredentialInfo: { + prototype: ScopedCredentialInfo; + new(): ScopedCredentialInfo; +}; + +interface Screen { + readonly availHeight: number; + readonly availWidth: number; + readonly colorDepth: number; + readonly height: number; + readonly orientation: ScreenOrientation; + readonly pixelDepth: number; + readonly width: number; +} + +declare var Screen: { + prototype: Screen; + new(): Screen; +}; + +interface ScreenOrientationEventMap { + "change": Event; +} + +interface ScreenOrientation extends EventTarget { + readonly angle: number; + onchange: ((this: ScreenOrientation, ev: Event) => any) | null; + readonly type: OrientationType; + lock(orientation: OrientationLockType): Promise; + unlock(): void; + addEventListener(type: K, listener: (this: ScreenOrientation, ev: ScreenOrientationEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: ScreenOrientation, ev: ScreenOrientationEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var ScreenOrientation: { + prototype: ScreenOrientation; + new(): ScreenOrientation; +}; + +interface ScriptProcessorNodeEventMap { + "audioprocess": AudioProcessingEvent; +} + +interface ScriptProcessorNode extends AudioNode { + /** @deprecated */ + readonly bufferSize: number; + /** @deprecated */ + onaudioprocess: ((this: ScriptProcessorNode, ev: AudioProcessingEvent) => any) | null; + addEventListener(type: K, listener: (this: ScriptProcessorNode, ev: ScriptProcessorNodeEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: ScriptProcessorNode, ev: ScriptProcessorNodeEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var ScriptProcessorNode: { + prototype: ScriptProcessorNode; + new(): ScriptProcessorNode; +}; + +interface SecurityPolicyViolationEvent extends Event { + readonly blockedURI: string; + readonly columnNumber: number; + readonly documentURI: string; + readonly effectiveDirective: string; + readonly lineNumber: number; + readonly originalPolicy: string; + readonly referrer: string; + readonly sourceFile: string; + readonly statusCode: number; + readonly violatedDirective: string; +} + +declare var SecurityPolicyViolationEvent: { + prototype: SecurityPolicyViolationEvent; + new(type: string, eventInitDict?: SecurityPolicyViolationEventInit): SecurityPolicyViolationEvent; +}; + +interface Selection { + readonly anchorNode: Node; + readonly anchorOffset: number; + readonly baseNode: Node; + readonly baseOffset: number; + readonly extentNode: Node; + readonly extentOffset: number; + readonly focusNode: Node; + readonly focusOffset: number; + readonly isCollapsed: boolean; + readonly rangeCount: number; + readonly type: string; + addRange(range: Range): void; + collapse(parentNode: Node, offset: number): void; + collapseToEnd(): void; + collapseToStart(): void; + containsNode(node: Node, partlyContained: boolean): boolean; + deleteFromDocument(): void; + empty(): void; + extend(newNode: Node, offset: number): void; + getRangeAt(index: number): Range; + removeAllRanges(): void; + removeRange(range: Range): void; + selectAllChildren(parentNode: Node): void; + setBaseAndExtent(baseNode: Node, baseOffset: number, extentNode: Node, extentOffset: number): void; + setPosition(parentNode: Node, offset: number): void; + toString(): string; +} + +declare var Selection: { + prototype: Selection; + new(): Selection; +}; + +interface ServiceUIFrameContext { + getCachedFrameMessage(key: string): string; + postFrameMessage(key: string, data: string): void; +} +declare var ServiceUIFrameContext: ServiceUIFrameContext; + +interface ServiceWorkerEventMap extends AbstractWorkerEventMap { + "statechange": Event; +} + +interface ServiceWorker extends EventTarget, AbstractWorker { + onstatechange: ((this: ServiceWorker, ev: Event) => any) | null; + readonly scriptURL: string; + readonly state: ServiceWorkerState; + postMessage(message: any, transfer?: Transferable[]): void; + addEventListener(type: K, listener: (this: ServiceWorker, ev: ServiceWorkerEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: ServiceWorker, ev: ServiceWorkerEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var ServiceWorker: { + prototype: ServiceWorker; + new(): ServiceWorker; +}; + +interface ServiceWorkerContainerEventMap { + "controllerchange": Event; + "message": MessageEvent; + "messageerror": MessageEvent; +} + +interface ServiceWorkerContainer extends EventTarget { + readonly controller: ServiceWorker | null; + oncontrollerchange: ((this: ServiceWorkerContainer, ev: Event) => any) | null; + onmessage: ((this: ServiceWorkerContainer, ev: MessageEvent) => any) | null; + onmessageerror: ((this: ServiceWorkerContainer, ev: MessageEvent) => any) | null; + readonly ready: Promise; + getRegistration(clientURL?: string): Promise; + getRegistrations(): Promise>; + register(scriptURL: string, options?: RegistrationOptions): Promise; + startMessages(): void; + addEventListener(type: K, listener: (this: ServiceWorkerContainer, ev: ServiceWorkerContainerEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: ServiceWorkerContainer, ev: ServiceWorkerContainerEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var ServiceWorkerContainer: { + prototype: ServiceWorkerContainer; + new(): ServiceWorkerContainer; +}; + +interface ServiceWorkerMessageEvent extends Event { + readonly data: any; + readonly lastEventId: string; + readonly origin: string; + readonly ports: ReadonlyArray | null; + readonly source: ServiceWorker | MessagePort | null; +} + +declare var ServiceWorkerMessageEvent: { + prototype: ServiceWorkerMessageEvent; + new(type: string, eventInitDict?: ServiceWorkerMessageEventInit): ServiceWorkerMessageEvent; +}; + +interface ServiceWorkerRegistrationEventMap { + "updatefound": Event; +} + +interface ServiceWorkerRegistration extends EventTarget { + readonly active: ServiceWorker | null; + readonly installing: ServiceWorker | null; + readonly navigationPreload: NavigationPreloadManager; + onupdatefound: ((this: ServiceWorkerRegistration, ev: Event) => any) | null; + readonly pushManager: PushManager; + readonly scope: string; + readonly sync: SyncManager; + readonly updateViaCache: ServiceWorkerUpdateViaCache; + readonly waiting: ServiceWorker | null; + getNotifications(filter?: GetNotificationOptions): Promise; + showNotification(title: string, options?: NotificationOptions): Promise; + unregister(): Promise; + update(): Promise; + addEventListener(type: K, listener: (this: ServiceWorkerRegistration, ev: ServiceWorkerRegistrationEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: ServiceWorkerRegistration, ev: ServiceWorkerRegistrationEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var ServiceWorkerRegistration: { + prototype: ServiceWorkerRegistration; + new(): ServiceWorkerRegistration; +}; + +interface ShadowRoot extends DocumentOrShadowRoot, DocumentFragment, DocumentOrShadowRoot { + readonly host: Element; + innerHTML: string; + readonly mode: ShadowRootMode; +} + +interface ShadowRootInit { + delegatesFocus?: boolean; + mode: "open" | "closed"; +} + +interface Slotable { + readonly assignedSlot: HTMLSlotElement | null; +} + +interface SourceBuffer extends EventTarget { + appendWindowEnd: number; + appendWindowStart: number; + readonly audioTracks: AudioTrackList; + readonly buffered: TimeRanges; + mode: AppendMode; + readonly textTracks: TextTrackList; + timestampOffset: number; + readonly updating: boolean; + readonly videoTracks: VideoTrackList; + abort(): void; + appendBuffer(data: ArrayBuffer | Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | null): void; + appendStream(stream: MSStream, maxSize?: number): void; + remove(start: number, end: number): void; +} + +declare var SourceBuffer: { + prototype: SourceBuffer; + new(): SourceBuffer; +}; + +interface SourceBufferList extends EventTarget { + readonly length: number; + item(index: number): SourceBuffer; + [index: number]: SourceBuffer; +} + +declare var SourceBufferList: { + prototype: SourceBufferList; + new(): SourceBufferList; +}; + +interface SpeechGrammar { + src: string; + weight: number; +} + +declare var SpeechGrammar: { + prototype: SpeechGrammar; + new(): SpeechGrammar; +}; + +interface SpeechGrammarList { + readonly length: number; + addFromString(string: string, weight?: number): void; + addFromURI(src: string, weight?: number): void; + item(index: number): SpeechGrammar; + [index: number]: SpeechGrammar; +} + +declare var SpeechGrammarList: { + prototype: SpeechGrammarList; + new(): SpeechGrammarList; +}; + +interface SpeechRecognitionEventMap { + "audioend": Event; + "audiostart": Event; + "end": Event; + "error": SpeechRecognitionError; + "nomatch": SpeechRecognitionEvent; + "result": SpeechRecognitionEvent; + "soundend": Event; + "soundstart": Event; + "speechend": Event; + "speechstart": Event; + "start": Event; +} + +interface SpeechRecognition extends EventTarget { + continuous: boolean; + grammars: SpeechGrammarList; + interimResults: boolean; + lang: string; + maxAlternatives: number; + onaudioend: ((this: SpeechRecognition, ev: Event) => any) | null; + onaudiostart: ((this: SpeechRecognition, ev: Event) => any) | null; + onend: ((this: SpeechRecognition, ev: Event) => any) | null; + onerror: ((this: SpeechRecognition, ev: SpeechRecognitionError) => any) | null; + onnomatch: ((this: SpeechRecognition, ev: SpeechRecognitionEvent) => any) | null; + onresult: ((this: SpeechRecognition, ev: SpeechRecognitionEvent) => any) | null; + onsoundend: ((this: SpeechRecognition, ev: Event) => any) | null; + onsoundstart: ((this: SpeechRecognition, ev: Event) => any) | null; + onspeechend: ((this: SpeechRecognition, ev: Event) => any) | null; + onspeechstart: ((this: SpeechRecognition, ev: Event) => any) | null; + onstart: ((this: SpeechRecognition, ev: Event) => any) | null; + serviceURI: string; + abort(): void; + start(): void; + stop(): void; + addEventListener(type: K, listener: (this: SpeechRecognition, ev: SpeechRecognitionEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SpeechRecognition, ev: SpeechRecognitionEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SpeechRecognition: { + prototype: SpeechRecognition; + new(): SpeechRecognition; +}; + +interface SpeechRecognitionAlternative { + readonly confidence: number; + readonly transcript: string; +} + +declare var SpeechRecognitionAlternative: { + prototype: SpeechRecognitionAlternative; + new(): SpeechRecognitionAlternative; +}; + +interface SpeechRecognitionError extends Event { + readonly error: SpeechRecognitionErrorCode; + readonly message: string; +} + +declare var SpeechRecognitionError: { + prototype: SpeechRecognitionError; + new(): SpeechRecognitionError; +}; + +interface SpeechRecognitionEvent extends Event { + readonly emma: Document | null; + readonly interpretation: any; + readonly resultIndex: number; + readonly results: SpeechRecognitionResultList; +} + +declare var SpeechRecognitionEvent: { + prototype: SpeechRecognitionEvent; + new(): SpeechRecognitionEvent; +}; + +interface SpeechRecognitionResult { + readonly isFinal: boolean; + readonly length: number; + item(index: number): SpeechRecognitionAlternative; + [index: number]: SpeechRecognitionAlternative; +} + +declare var SpeechRecognitionResult: { + prototype: SpeechRecognitionResult; + new(): SpeechRecognitionResult; +}; + +interface SpeechRecognitionResultList { + readonly length: number; + item(index: number): SpeechRecognitionResult; + [index: number]: SpeechRecognitionResult; +} + +declare var SpeechRecognitionResultList: { + prototype: SpeechRecognitionResultList; + new(): SpeechRecognitionResultList; +}; + +interface SpeechSynthesisEventMap { + "voiceschanged": Event; +} + +interface SpeechSynthesis extends EventTarget { + onvoiceschanged: ((this: SpeechSynthesis, ev: Event) => any) | null; + readonly paused: boolean; + readonly pending: boolean; + readonly speaking: boolean; + cancel(): void; + getVoices(): SpeechSynthesisVoice[]; + pause(): void; + resume(): void; + speak(utterance: SpeechSynthesisUtterance): void; + addEventListener(type: K, listener: (this: SpeechSynthesis, ev: SpeechSynthesisEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SpeechSynthesis, ev: SpeechSynthesisEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SpeechSynthesis: { + prototype: SpeechSynthesis; + new(): SpeechSynthesis; +}; + +interface SpeechSynthesisErrorEvent extends SpeechSynthesisEvent { + readonly error: SpeechSynthesisErrorCode; +} + +declare var SpeechSynthesisErrorEvent: { + prototype: SpeechSynthesisErrorEvent; + new(): SpeechSynthesisErrorEvent; +}; + +interface SpeechSynthesisEvent extends Event { + readonly charIndex: number; + readonly elapsedTime: number; + readonly name: string; + readonly utterance: SpeechSynthesisUtterance; +} + +declare var SpeechSynthesisEvent: { + prototype: SpeechSynthesisEvent; + new(): SpeechSynthesisEvent; +}; + +interface SpeechSynthesisUtteranceEventMap { + "boundary": SpeechSynthesisEvent; + "end": SpeechSynthesisEvent; + "error": SpeechSynthesisErrorEvent; + "mark": SpeechSynthesisEvent; + "pause": SpeechSynthesisEvent; + "resume": SpeechSynthesisEvent; + "start": SpeechSynthesisEvent; +} + +interface SpeechSynthesisUtterance extends EventTarget { + lang: string; + onboundary: ((this: SpeechSynthesisUtterance, ev: SpeechSynthesisEvent) => any) | null; + onend: ((this: SpeechSynthesisUtterance, ev: SpeechSynthesisEvent) => any) | null; + onerror: ((this: SpeechSynthesisUtterance, ev: SpeechSynthesisErrorEvent) => any) | null; + onmark: ((this: SpeechSynthesisUtterance, ev: SpeechSynthesisEvent) => any) | null; + onpause: ((this: SpeechSynthesisUtterance, ev: SpeechSynthesisEvent) => any) | null; + onresume: ((this: SpeechSynthesisUtterance, ev: SpeechSynthesisEvent) => any) | null; + onstart: ((this: SpeechSynthesisUtterance, ev: SpeechSynthesisEvent) => any) | null; + pitch: number; + rate: number; + text: string; + voice: SpeechSynthesisVoice; + volume: number; + addEventListener(type: K, listener: (this: SpeechSynthesisUtterance, ev: SpeechSynthesisUtteranceEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SpeechSynthesisUtterance, ev: SpeechSynthesisUtteranceEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SpeechSynthesisUtterance: { + prototype: SpeechSynthesisUtterance; + new(): SpeechSynthesisUtterance; + new(text: string): SpeechSynthesisUtterance; +}; + +interface SpeechSynthesisVoice { + readonly default: boolean; + readonly lang: string; + readonly localService: boolean; + readonly name: string; + readonly voiceURI: string; +} + +declare var SpeechSynthesisVoice: { + prototype: SpeechSynthesisVoice; + new(): SpeechSynthesisVoice; +}; + +interface StaticRange extends AbstractRange { +} + +declare var StaticRange: { + prototype: StaticRange; + new(): StaticRange; +}; + +interface StereoPannerNode extends AudioNode { + readonly pan: AudioParam; +} + +declare var StereoPannerNode: { + prototype: StereoPannerNode; + new(context: BaseAudioContext, options?: StereoPannerOptions): StereoPannerNode; +}; + +interface Storage { + /** + * Returns the number of key/value pairs currently present in the list associated with the + * object. + */ + readonly length: number; + /** + * Empties the list associated with the object of all key/value pairs, if there are any. + */ + clear(): void; + /** + * value = storage[key] + */ + getItem(key: string): string | null; + /** + * Returns the name of the nth key in the list, or null if n is greater + * than or equal to the number of key/value pairs in the object. + */ + key(index: number): string | null; + /** + * delete storage[key] + */ + removeItem(key: string): void; + /** + * storage[key] = value + */ + setItem(key: string, value: string): void; + [name: string]: any; +} + +declare var Storage: { + prototype: Storage; + new(): Storage; +}; + +interface StorageEvent extends Event { + /** + * Returns the key of the storage item being changed. + */ + readonly key: string | null; + /** + * Returns the new value of the key of the storage item whose value is being changed. + */ + readonly newValue: string | null; + /** + * Returns the old value of the key of the storage item whose value is being changed. + */ + readonly oldValue: string | null; + /** + * Returns the Storage object that was affected. + */ + readonly storageArea: Storage | null; + /** + * Returns the URL of the document whose storage item changed. + */ + readonly url: string; +} + +declare var StorageEvent: { + prototype: StorageEvent; + new(type: string, eventInitDict?: StorageEventInit): StorageEvent; +}; + +interface StorageManager { + estimate(): Promise; + persist(): Promise; + persisted(): Promise; +} + +declare var StorageManager: { + prototype: StorageManager; + new(): StorageManager; +}; + +interface StyleMedia { + readonly type: string; + matchMedium(mediaquery: string): boolean; +} + +declare var StyleMedia: { + prototype: StyleMedia; + new(): StyleMedia; +}; + +interface StyleSheet { + disabled: boolean; + readonly href: string | null; + readonly media: MediaList; + readonly ownerNode: Node; + readonly parentStyleSheet: StyleSheet | null; + readonly title: string | null; + readonly type: string; +} + +declare var StyleSheet: { + prototype: StyleSheet; + new(): StyleSheet; +}; + +interface StyleSheetList { + readonly length: number; + item(index: number): StyleSheet | null; + [index: number]: StyleSheet; +} + +declare var StyleSheetList: { + prototype: StyleSheetList; + new(): StyleSheetList; +}; + +interface SubtleCrypto { + decrypt(algorithm: string | RsaOaepParams | AesCtrParams | AesCbcParams | AesCmacParams | AesGcmParams | AesCfbParams, key: CryptoKey, data: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer): PromiseLike; + deriveBits(algorithm: string | EcdhKeyDeriveParams | DhKeyDeriveParams | ConcatParams | HkdfCtrParams | Pbkdf2Params, baseKey: CryptoKey, length: number): PromiseLike; + deriveKey(algorithm: string | EcdhKeyDeriveParams | DhKeyDeriveParams | ConcatParams | HkdfCtrParams | Pbkdf2Params, baseKey: CryptoKey, derivedKeyType: string | AesDerivedKeyParams | HmacImportParams | ConcatParams | HkdfCtrParams | Pbkdf2Params, extractable: boolean, keyUsages: string[]): PromiseLike; + digest(algorithm: string | Algorithm, data: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer): PromiseLike; + encrypt(algorithm: string | RsaOaepParams | AesCtrParams | AesCbcParams | AesCmacParams | AesGcmParams | AesCfbParams, key: CryptoKey, data: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer): PromiseLike; + exportKey(format: "jwk", key: CryptoKey): PromiseLike; + exportKey(format: "raw" | "pkcs8" | "spki", key: CryptoKey): PromiseLike; + exportKey(format: string, key: CryptoKey): PromiseLike; + generateKey(algorithm: string, extractable: boolean, keyUsages: string[]): PromiseLike; + generateKey(algorithm: RsaHashedKeyGenParams | EcKeyGenParams | DhKeyGenParams, extractable: boolean, keyUsages: string[]): PromiseLike; + generateKey(algorithm: AesKeyGenParams | HmacKeyGenParams | Pbkdf2Params, extractable: boolean, keyUsages: string[]): PromiseLike; + importKey(format: "jwk", keyData: JsonWebKey, algorithm: string | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | DhImportKeyParams | AesKeyAlgorithm, extractable: boolean, keyUsages: string[]): PromiseLike; + importKey(format: "raw" | "pkcs8" | "spki", keyData: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer, algorithm: string | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | DhImportKeyParams | AesKeyAlgorithm, extractable: boolean, keyUsages: string[]): PromiseLike; + importKey(format: string, keyData: JsonWebKey | Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer, algorithm: string | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | DhImportKeyParams | AesKeyAlgorithm, extractable: boolean, keyUsages: string[]): PromiseLike; + sign(algorithm: string | RsaPssParams | EcdsaParams | AesCmacParams, key: CryptoKey, data: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer): PromiseLike; + unwrapKey(format: string, wrappedKey: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer, unwrappingKey: CryptoKey, unwrapAlgorithm: string | Algorithm, unwrappedKeyAlgorithm: string | Algorithm, extractable: boolean, keyUsages: string[]): PromiseLike; + verify(algorithm: string | RsaPssParams | EcdsaParams | AesCmacParams, key: CryptoKey, signature: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer, data: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer): PromiseLike; + wrapKey(format: string, key: CryptoKey, wrappingKey: CryptoKey, wrapAlgorithm: string | Algorithm): PromiseLike; +} + +declare var SubtleCrypto: { + prototype: SubtleCrypto; + new(): SubtleCrypto; +}; + +interface SyncManager { + getTags(): Promise; + register(tag: string): Promise; +} + +declare var SyncManager: { + prototype: SyncManager; + new(): SyncManager; +}; + +interface Text extends CharacterData, Slotable { + readonly assignedSlot: HTMLSlotElement | null; + /** + * Returns the combined data of all direct Text node siblings. + */ + readonly wholeText: string; + /** + * Splits data at the given offset and returns the remainder as Text node. + */ + splitText(offset: number): Text; +} + +declare var Text: { + prototype: Text; + new(data?: string): Text; +}; + +interface TextDecoder { + /** + * Returns encoding's name, lowercased. + */ + readonly encoding: string; + /** + * Returns true if error mode is "fatal", and false + * otherwise. + */ + readonly fatal: boolean; + /** + * Returns true if ignore BOM flag is set, and false otherwise. + */ + readonly ignoreBOM: boolean; + /** + * Returns the result of running encoding's decoder. The + * method can be invoked zero or more times with options's stream set to + * true, and then once without options's stream (or set to false), to process + * a fragmented stream. If the invocation without options's stream (or set to + * false) has no input, it's clearest to omit both arguments. + * var string = "", decoder = new TextDecoder(encoding), buffer; + * while(buffer = next_chunk()) { + * string += decoder.decode(buffer, {stream:true}); + * } + * string += decoder.decode(); // end-of-stream + * If the error mode is "fatal" and encoding's decoder returns error, throws a TypeError. + */ + decode(input?: BufferSource, options?: TextDecodeOptions): string; +} + +declare var TextDecoder: { + prototype: TextDecoder; + new(label?: string, options?: TextDecoderOptions): TextDecoder; +}; + +interface TextEncoder { + /** + * Returns "utf-8". + */ + readonly encoding: string; + /** + * Returns the result of running UTF-8's encoder. + */ + encode(input?: string): Uint8Array; +} + +declare var TextEncoder: { + prototype: TextEncoder; + new(): TextEncoder; +}; + +interface TextEvent extends UIEvent { + readonly data: string; + initTextEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, dataArg: string, inputMethod: number, locale: string): void; + readonly DOM_INPUT_METHOD_DROP: number; + readonly DOM_INPUT_METHOD_HANDWRITING: number; + readonly DOM_INPUT_METHOD_IME: number; + readonly DOM_INPUT_METHOD_KEYBOARD: number; + readonly DOM_INPUT_METHOD_MULTIMODAL: number; + readonly DOM_INPUT_METHOD_OPTION: number; + readonly DOM_INPUT_METHOD_PASTE: number; + readonly DOM_INPUT_METHOD_SCRIPT: number; + readonly DOM_INPUT_METHOD_UNKNOWN: number; + readonly DOM_INPUT_METHOD_VOICE: number; +} + +declare var TextEvent: { + prototype: TextEvent; + new(): TextEvent; + readonly DOM_INPUT_METHOD_DROP: number; + readonly DOM_INPUT_METHOD_HANDWRITING: number; + readonly DOM_INPUT_METHOD_IME: number; + readonly DOM_INPUT_METHOD_KEYBOARD: number; + readonly DOM_INPUT_METHOD_MULTIMODAL: number; + readonly DOM_INPUT_METHOD_OPTION: number; + readonly DOM_INPUT_METHOD_PASTE: number; + readonly DOM_INPUT_METHOD_SCRIPT: number; + readonly DOM_INPUT_METHOD_UNKNOWN: number; + readonly DOM_INPUT_METHOD_VOICE: number; +}; + +interface TextMetrics { + readonly actualBoundingBoxAscent: number; + readonly actualBoundingBoxDescent: number; + readonly actualBoundingBoxLeft: number; + readonly actualBoundingBoxRight: number; + readonly alphabeticBaseline: number; + readonly emHeightAscent: number; + readonly emHeightDescent: number; + readonly fontBoundingBoxAscent: number; + readonly fontBoundingBoxDescent: number; + readonly hangingBaseline: number; + /** + * Returns the measurement described below. + */ + readonly ideographicBaseline: number; + readonly width: number; +} + +declare var TextMetrics: { + prototype: TextMetrics; + new(): TextMetrics; +}; + +interface TextTrackEventMap { + "cuechange": Event; + "error": Event; + "load": Event; +} + +interface TextTrack extends EventTarget { + readonly activeCues: TextTrackCueList; + readonly cues: TextTrackCueList; + readonly inBandMetadataTrackDispatchType: string; + readonly kind: string; + readonly label: string; + readonly language: string; + mode: TextTrackMode | number; + oncuechange: ((this: TextTrack, ev: Event) => any) | null; + onerror: ((this: TextTrack, ev: Event) => any) | null; + onload: ((this: TextTrack, ev: Event) => any) | null; + readonly readyState: number; + addCue(cue: TextTrackCue): void; + removeCue(cue: TextTrackCue): void; + readonly DISABLED: number; + readonly ERROR: number; + readonly HIDDEN: number; + readonly LOADED: number; + readonly LOADING: number; + readonly NONE: number; + readonly SHOWING: number; + addEventListener(type: K, listener: (this: TextTrack, ev: TextTrackEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: TextTrack, ev: TextTrackEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var TextTrack: { + prototype: TextTrack; + new(): TextTrack; + readonly DISABLED: number; + readonly ERROR: number; + readonly HIDDEN: number; + readonly LOADED: number; + readonly LOADING: number; + readonly NONE: number; + readonly SHOWING: number; +}; + +interface TextTrackCueEventMap { + "enter": Event; + "exit": Event; +} + +interface TextTrackCue extends EventTarget { + endTime: number; + id: string; + onenter: ((this: TextTrackCue, ev: Event) => any) | null; + onexit: ((this: TextTrackCue, ev: Event) => any) | null; + pauseOnExit: boolean; + startTime: number; + text: string; + readonly track: TextTrack; + getCueAsHTML(): DocumentFragment; + addEventListener(type: K, listener: (this: TextTrackCue, ev: TextTrackCueEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: TextTrackCue, ev: TextTrackCueEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var TextTrackCue: { + prototype: TextTrackCue; + new(startTime: number, endTime: number, text: string): TextTrackCue; +}; + +interface TextTrackCueList { + readonly length: number; + getCueById(id: string): TextTrackCue; + item(index: number): TextTrackCue; + [index: number]: TextTrackCue; +} + +declare var TextTrackCueList: { + prototype: TextTrackCueList; + new(): TextTrackCueList; +}; + +interface TextTrackListEventMap { + "addtrack": TrackEvent; +} + +interface TextTrackList extends EventTarget { + readonly length: number; + onaddtrack: ((this: TextTrackList, ev: TrackEvent) => any) | null; + item(index: number): TextTrack; + addEventListener(type: K, listener: (this: TextTrackList, ev: TextTrackListEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: TextTrackList, ev: TextTrackListEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; + [index: number]: TextTrack; +} + +declare var TextTrackList: { + prototype: TextTrackList; + new(): TextTrackList; +}; + +interface TimeRanges { + readonly length: number; + end(index: number): number; + start(index: number): number; +} + +declare var TimeRanges: { + prototype: TimeRanges; + new(): TimeRanges; +}; + +interface Touch { + readonly altitudeAngle: number; + readonly azimuthAngle: number; + readonly clientX: number; + readonly clientY: number; + readonly force: number; + readonly identifier: number; + readonly pageX: number; + readonly pageY: number; + readonly radiusX: number; + readonly radiusY: number; + readonly rotationAngle: number; + readonly screenX: number; + readonly screenY: number; + readonly target: EventTarget; + readonly touchType: TouchType; +} + +declare var Touch: { + prototype: Touch; + new(touchInitDict: TouchInit): Touch; +}; + +interface TouchEvent extends UIEvent { + readonly altKey: boolean; + readonly changedTouches: TouchList; + readonly ctrlKey: boolean; + readonly metaKey: boolean; + readonly shiftKey: boolean; + readonly targetTouches: TouchList; + readonly touches: TouchList; +} + +declare var TouchEvent: { + prototype: TouchEvent; + new(type: string, eventInitDict?: TouchEventInit): TouchEvent; +}; + +interface TouchList { + readonly length: number; + item(index: number): Touch | null; + [index: number]: Touch; +} + +declare var TouchList: { + prototype: TouchList; + new(): TouchList; +}; + +interface TrackEvent extends Event { + readonly track: VideoTrack | AudioTrack | TextTrack | null; +} + +declare var TrackEvent: { + prototype: TrackEvent; + new(typeArg: string, eventInitDict?: TrackEventInit): TrackEvent; +}; + +interface TransformStream { + readonly readable: ReadableStream; + readonly writable: WritableStream; +} + +declare var TransformStream: { + prototype: TransformStream; + new(transformer?: Transformer, writableStrategy?: QueuingStrategy, readableStrategy?: QueuingStrategy): TransformStream; +}; + +interface TransformStreamDefaultController { + readonly desiredSize: number | null; + enqueue(chunk: O): void; + error(reason?: any): void; + terminate(): void; +} + +interface TransitionEvent extends Event { + readonly elapsedTime: number; + readonly propertyName: string; + readonly pseudoElement: string; +} + +declare var TransitionEvent: { + prototype: TransitionEvent; + new(type: string, transitionEventInitDict?: TransitionEventInit): TransitionEvent; +}; + +interface TreeWalker { + currentNode: Node; + readonly filter: NodeFilter | null; + readonly root: Node; + readonly whatToShow: number; + firstChild(): Node | null; + lastChild(): Node | null; + nextNode(): Node | null; + nextSibling(): Node | null; + parentNode(): Node | null; + previousNode(): Node | null; + previousSibling(): Node | null; +} + +declare var TreeWalker: { + prototype: TreeWalker; + new(): TreeWalker; +}; + +interface UIEvent extends Event { + readonly detail: number; + readonly view: Window; + initUIEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number): void; +} + +declare var UIEvent: { + prototype: UIEvent; + new(typeArg: string, eventInitDict?: UIEventInit): UIEvent; +}; + +interface URL { + hash: string; + host: string; + hostname: string; + href: string; + readonly origin: string; + password: string; + pathname: string; + port: string; + protocol: string; + search: string; + readonly searchParams: URLSearchParams; + username: string; + toJSON(): string; +} + +declare var URL: { + prototype: URL; + new(url: string, base?: string | URL): URL; + createObjectURL(object: any): string; + revokeObjectURL(url: string): void; +}; + +type webkitURL = URL; +declare var webkitURL: typeof URL; + +interface URLSearchParams { + /** + * Appends a specified key/value pair as a new search parameter. + */ + append(name: string, value: string): void; + /** + * Deletes the given search parameter, and its associated value, from the list of all search parameters. + */ + delete(name: string): void; + /** + * Returns the first value associated to the given search parameter. + */ + get(name: string): string | null; + /** + * Returns all the values association with a given search parameter. + */ + getAll(name: string): string[]; + /** + * Returns a Boolean indicating if such a search parameter exists. + */ + has(name: string): boolean; + /** + * Sets the value associated to a given search parameter to the given value. If there were several values, delete the others. + */ + set(name: string, value: string): void; + sort(): void; + forEach(callbackfn: (value: string, key: string, parent: URLSearchParams) => void, thisArg?: any): void; +} + +declare var URLSearchParams: { + prototype: URLSearchParams; + new(init?: string[][] | Record | string | URLSearchParams): URLSearchParams; +}; + +interface VRDisplay extends EventTarget { + readonly capabilities: VRDisplayCapabilities; + depthFar: number; + depthNear: number; + readonly displayId: number; + readonly displayName: string; + readonly isConnected: boolean; + readonly isPresenting: boolean; + readonly stageParameters: VRStageParameters | null; + cancelAnimationFrame(handle: number): void; + exitPresent(): Promise; + getEyeParameters(whichEye: string): VREyeParameters; + getFrameData(frameData: VRFrameData): boolean; + getLayers(): VRLayer[]; + /** @deprecated */ + getPose(): VRPose; + requestAnimationFrame(callback: FrameRequestCallback): number; + requestPresent(layers: VRLayer[]): Promise; + resetPose(): void; + submitFrame(pose?: VRPose): void; +} + +declare var VRDisplay: { + prototype: VRDisplay; + new(): VRDisplay; +}; + +interface VRDisplayCapabilities { + readonly canPresent: boolean; + readonly hasExternalDisplay: boolean; + readonly hasOrientation: boolean; + readonly hasPosition: boolean; + readonly maxLayers: number; +} + +declare var VRDisplayCapabilities: { + prototype: VRDisplayCapabilities; + new(): VRDisplayCapabilities; +}; + +interface VRDisplayEvent extends Event { + readonly display: VRDisplay; + readonly reason: VRDisplayEventReason | null; +} + +declare var VRDisplayEvent: { + prototype: VRDisplayEvent; + new(type: string, eventInitDict: VRDisplayEventInit): VRDisplayEvent; +}; + +interface VREyeParameters { + /** @deprecated */ + readonly fieldOfView: VRFieldOfView; + readonly offset: Float32Array; + readonly renderHeight: number; + readonly renderWidth: number; +} + +declare var VREyeParameters: { + prototype: VREyeParameters; + new(): VREyeParameters; +}; + +interface VRFieldOfView { + readonly downDegrees: number; + readonly leftDegrees: number; + readonly rightDegrees: number; + readonly upDegrees: number; +} + +declare var VRFieldOfView: { + prototype: VRFieldOfView; + new(): VRFieldOfView; +}; + +interface VRFrameData { + readonly leftProjectionMatrix: Float32Array; + readonly leftViewMatrix: Float32Array; + readonly pose: VRPose; + readonly rightProjectionMatrix: Float32Array; + readonly rightViewMatrix: Float32Array; + readonly timestamp: number; +} + +declare var VRFrameData: { + prototype: VRFrameData; + new(): VRFrameData; +}; + +interface VRPose { + readonly angularAcceleration: Float32Array | null; + readonly angularVelocity: Float32Array | null; + readonly linearAcceleration: Float32Array | null; + readonly linearVelocity: Float32Array | null; + readonly orientation: Float32Array | null; + readonly position: Float32Array | null; + readonly timestamp: number; +} + +declare var VRPose: { + prototype: VRPose; + new(): VRPose; +}; + +interface VTTCue extends TextTrackCue { + align: AlignSetting; + line: LineAndPositionSetting; + lineAlign: LineAlignSetting; + position: LineAndPositionSetting; + positionAlign: PositionAlignSetting; + region: VTTRegion | null; + size: number; + snapToLines: boolean; + text: string; + vertical: DirectionSetting; + getCueAsHTML(): DocumentFragment; + addEventListener(type: K, listener: (this: VTTCue, ev: TextTrackCueEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: VTTCue, ev: TextTrackCueEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var VTTCue: { + prototype: VTTCue; + new(startTime: number, endTime: number, text: string): VTTCue; +}; + +interface VTTRegion { + id: string; + lines: number; + regionAnchorX: number; + regionAnchorY: number; + scroll: ScrollSetting; + viewportAnchorX: number; + viewportAnchorY: number; + width: number; +} + +declare var VTTRegion: { + prototype: VTTRegion; + new(): VTTRegion; +}; + +interface ValidityState { + readonly badInput: boolean; + readonly customError: boolean; + readonly patternMismatch: boolean; + readonly rangeOverflow: boolean; + readonly rangeUnderflow: boolean; + readonly stepMismatch: boolean; + readonly tooLong: boolean; + readonly tooShort: boolean; + readonly typeMismatch: boolean; + readonly valid: boolean; + readonly valueMissing: boolean; +} + +declare var ValidityState: { + prototype: ValidityState; + new(): ValidityState; +}; + +interface VideoPlaybackQuality { + readonly corruptedVideoFrames: number; + readonly creationTime: number; + readonly droppedVideoFrames: number; + readonly totalFrameDelay: number; + readonly totalVideoFrames: number; +} + +declare var VideoPlaybackQuality: { + prototype: VideoPlaybackQuality; + new(): VideoPlaybackQuality; +}; + +interface VideoTrack { + readonly id: string; + kind: string; + readonly label: string; + language: string; + selected: boolean; + readonly sourceBuffer: SourceBuffer; +} + +declare var VideoTrack: { + prototype: VideoTrack; + new(): VideoTrack; +}; + +interface VideoTrackListEventMap { + "addtrack": TrackEvent; + "change": Event; + "removetrack": TrackEvent; +} + +interface VideoTrackList extends EventTarget { + readonly length: number; + onaddtrack: ((this: VideoTrackList, ev: TrackEvent) => any) | null; + onchange: ((this: VideoTrackList, ev: Event) => any) | null; + onremovetrack: ((this: VideoTrackList, ev: TrackEvent) => any) | null; + readonly selectedIndex: number; + getTrackById(id: string): VideoTrack | null; + item(index: number): VideoTrack; + addEventListener(type: K, listener: (this: VideoTrackList, ev: VideoTrackListEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: VideoTrackList, ev: VideoTrackListEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; + [index: number]: VideoTrack; +} + +declare var VideoTrackList: { + prototype: VideoTrackList; + new(): VideoTrackList; +}; + +interface WEBGL_color_buffer_float { + readonly FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE_EXT: GLenum; + readonly RGBA32F_EXT: GLenum; + readonly UNSIGNED_NORMALIZED_EXT: GLenum; +} + +interface WEBGL_compressed_texture_astc { + getSupportedProfiles(): string[]; + readonly COMPRESSED_RGBA_ASTC_10x10_KHR: GLenum; + readonly COMPRESSED_RGBA_ASTC_10x5_KHR: GLenum; + readonly COMPRESSED_RGBA_ASTC_10x6_KHR: GLenum; + readonly COMPRESSED_RGBA_ASTC_10x8_KHR: GLenum; + readonly COMPRESSED_RGBA_ASTC_12x10_KHR: GLenum; + readonly COMPRESSED_RGBA_ASTC_12x12_KHR: GLenum; + readonly COMPRESSED_RGBA_ASTC_4x4_KHR: GLenum; + readonly COMPRESSED_RGBA_ASTC_5x4_KHR: GLenum; + readonly COMPRESSED_RGBA_ASTC_5x5_KHR: GLenum; + readonly COMPRESSED_RGBA_ASTC_6x5_KHR: GLenum; + readonly COMPRESSED_RGBA_ASTC_6x6_KHR: GLenum; + readonly COMPRESSED_RGBA_ASTC_8x5_KHR: GLenum; + readonly COMPRESSED_RGBA_ASTC_8x6_KHR: GLenum; + readonly COMPRESSED_RGBA_ASTC_8x8_KHR: GLenum; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR: GLenum; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR: GLenum; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR: GLenum; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR: GLenum; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR: GLenum; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR: GLenum; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR: GLenum; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR: GLenum; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR: GLenum; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR: GLenum; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR: GLenum; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR: GLenum; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR: GLenum; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR: GLenum; +} + +interface WEBGL_compressed_texture_s3tc { + readonly COMPRESSED_RGBA_S3TC_DXT1_EXT: GLenum; + readonly COMPRESSED_RGBA_S3TC_DXT3_EXT: GLenum; + readonly COMPRESSED_RGBA_S3TC_DXT5_EXT: GLenum; + readonly COMPRESSED_RGB_S3TC_DXT1_EXT: GLenum; +} + +interface WEBGL_compressed_texture_s3tc_srgb { + readonly COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT: GLenum; + readonly COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT: GLenum; + readonly COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT: GLenum; + readonly COMPRESSED_SRGB_S3TC_DXT1_EXT: GLenum; +} + +interface WEBGL_debug_renderer_info { + readonly UNMASKED_RENDERER_WEBGL: GLenum; + readonly UNMASKED_VENDOR_WEBGL: GLenum; +} + +interface WEBGL_debug_shaders { + getTranslatedShaderSource(shader: WebGLShader): string; +} + +interface WEBGL_depth_texture { + readonly UNSIGNED_INT_24_8_WEBGL: GLenum; +} + +interface WEBGL_draw_buffers { + drawBuffersWEBGL(buffers: GLenum[]): void; + readonly COLOR_ATTACHMENT0_WEBGL: GLenum; + readonly COLOR_ATTACHMENT10_WEBGL: GLenum; + readonly COLOR_ATTACHMENT11_WEBGL: GLenum; + readonly COLOR_ATTACHMENT12_WEBGL: GLenum; + readonly COLOR_ATTACHMENT13_WEBGL: GLenum; + readonly COLOR_ATTACHMENT14_WEBGL: GLenum; + readonly COLOR_ATTACHMENT15_WEBGL: GLenum; + readonly COLOR_ATTACHMENT1_WEBGL: GLenum; + readonly COLOR_ATTACHMENT2_WEBGL: GLenum; + readonly COLOR_ATTACHMENT3_WEBGL: GLenum; + readonly COLOR_ATTACHMENT4_WEBGL: GLenum; + readonly COLOR_ATTACHMENT5_WEBGL: GLenum; + readonly COLOR_ATTACHMENT6_WEBGL: GLenum; + readonly COLOR_ATTACHMENT7_WEBGL: GLenum; + readonly COLOR_ATTACHMENT8_WEBGL: GLenum; + readonly COLOR_ATTACHMENT9_WEBGL: GLenum; + readonly DRAW_BUFFER0_WEBGL: GLenum; + readonly DRAW_BUFFER10_WEBGL: GLenum; + readonly DRAW_BUFFER11_WEBGL: GLenum; + readonly DRAW_BUFFER12_WEBGL: GLenum; + readonly DRAW_BUFFER13_WEBGL: GLenum; + readonly DRAW_BUFFER14_WEBGL: GLenum; + readonly DRAW_BUFFER15_WEBGL: GLenum; + readonly DRAW_BUFFER1_WEBGL: GLenum; + readonly DRAW_BUFFER2_WEBGL: GLenum; + readonly DRAW_BUFFER3_WEBGL: GLenum; + readonly DRAW_BUFFER4_WEBGL: GLenum; + readonly DRAW_BUFFER5_WEBGL: GLenum; + readonly DRAW_BUFFER6_WEBGL: GLenum; + readonly DRAW_BUFFER7_WEBGL: GLenum; + readonly DRAW_BUFFER8_WEBGL: GLenum; + readonly DRAW_BUFFER9_WEBGL: GLenum; + readonly MAX_COLOR_ATTACHMENTS_WEBGL: GLenum; + readonly MAX_DRAW_BUFFERS_WEBGL: GLenum; +} + +interface WEBGL_lose_context { + loseContext(): void; + restoreContext(): void; +} + +interface WaveShaperNode extends AudioNode { + curve: Float32Array | null; + oversample: OverSampleType; +} + +declare var WaveShaperNode: { + prototype: WaveShaperNode; + new(context: BaseAudioContext, options?: WaveShaperOptions): WaveShaperNode; +}; + +interface WebAuthentication { + getAssertion(assertionChallenge: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null, options?: AssertionOptions): Promise; + makeCredential(accountInformation: Account, cryptoParameters: ScopedCredentialParameters[], attestationChallenge: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null, options?: ScopedCredentialOptions): Promise; +} + +declare var WebAuthentication: { + prototype: WebAuthentication; + new(): WebAuthentication; +}; + +interface WebAuthnAssertion { + readonly authenticatorData: ArrayBuffer; + readonly clientData: ArrayBuffer; + readonly credential: ScopedCredential; + readonly signature: ArrayBuffer; +} + +declare var WebAuthnAssertion: { + prototype: WebAuthnAssertion; + new(): WebAuthnAssertion; +}; + +interface WebGLActiveInfo { + readonly name: string; + readonly size: GLint; + readonly type: GLenum; +} + +declare var WebGLActiveInfo: { + prototype: WebGLActiveInfo; + new(): WebGLActiveInfo; +}; + +interface WebGLBuffer extends WebGLObject { +} + +declare var WebGLBuffer: { + prototype: WebGLBuffer; + new(): WebGLBuffer; +}; + +interface WebGLContextEvent extends Event { + readonly statusMessage: string; +} + +declare var WebGLContextEvent: { + prototype: WebGLContextEvent; + new(type: string, eventInit?: WebGLContextEventInit): WebGLContextEvent; +}; + +interface WebGLFramebuffer extends WebGLObject { +} + +declare var WebGLFramebuffer: { + prototype: WebGLFramebuffer; + new(): WebGLFramebuffer; +}; + +interface WebGLObject { +} + +declare var WebGLObject: { + prototype: WebGLObject; + new(): WebGLObject; +}; + +interface WebGLProgram extends WebGLObject { +} + +declare var WebGLProgram: { + prototype: WebGLProgram; + new(): WebGLProgram; +}; + +interface WebGLRenderbuffer extends WebGLObject { +} + +declare var WebGLRenderbuffer: { + prototype: WebGLRenderbuffer; + new(): WebGLRenderbuffer; +}; + +interface WebGLRenderingContext extends WebGLRenderingContextBase { +} + +declare var WebGLRenderingContext: { + prototype: WebGLRenderingContext; + new(): WebGLRenderingContext; + readonly ACTIVE_ATTRIBUTES: GLenum; + readonly ACTIVE_TEXTURE: GLenum; + readonly ACTIVE_UNIFORMS: GLenum; + readonly ALIASED_LINE_WIDTH_RANGE: GLenum; + readonly ALIASED_POINT_SIZE_RANGE: GLenum; + readonly ALPHA: GLenum; + readonly ALPHA_BITS: GLenum; + readonly ALWAYS: GLenum; + readonly ARRAY_BUFFER: GLenum; + readonly ARRAY_BUFFER_BINDING: GLenum; + readonly ATTACHED_SHADERS: GLenum; + readonly BACK: GLenum; + readonly BLEND: GLenum; + readonly BLEND_COLOR: GLenum; + readonly BLEND_DST_ALPHA: GLenum; + readonly BLEND_DST_RGB: GLenum; + readonly BLEND_EQUATION: GLenum; + readonly BLEND_EQUATION_ALPHA: GLenum; + readonly BLEND_EQUATION_RGB: GLenum; + readonly BLEND_SRC_ALPHA: GLenum; + readonly BLEND_SRC_RGB: GLenum; + readonly BLUE_BITS: GLenum; + readonly BOOL: GLenum; + readonly BOOL_VEC2: GLenum; + readonly BOOL_VEC3: GLenum; + readonly BOOL_VEC4: GLenum; + readonly BROWSER_DEFAULT_WEBGL: GLenum; + readonly BUFFER_SIZE: GLenum; + readonly BUFFER_USAGE: GLenum; + readonly BYTE: GLenum; + readonly CCW: GLenum; + readonly CLAMP_TO_EDGE: GLenum; + readonly COLOR_ATTACHMENT0: GLenum; + readonly COLOR_BUFFER_BIT: GLenum; + readonly COLOR_CLEAR_VALUE: GLenum; + readonly COLOR_WRITEMASK: GLenum; + readonly COMPILE_STATUS: GLenum; + readonly COMPRESSED_TEXTURE_FORMATS: GLenum; + readonly CONSTANT_ALPHA: GLenum; + readonly CONSTANT_COLOR: GLenum; + readonly CONTEXT_LOST_WEBGL: GLenum; + readonly CULL_FACE: GLenum; + readonly CULL_FACE_MODE: GLenum; + readonly CURRENT_PROGRAM: GLenum; + readonly CURRENT_VERTEX_ATTRIB: GLenum; + readonly CW: GLenum; + readonly DECR: GLenum; + readonly DECR_WRAP: GLenum; + readonly DELETE_STATUS: GLenum; + readonly DEPTH_ATTACHMENT: GLenum; + readonly DEPTH_BITS: GLenum; + readonly DEPTH_BUFFER_BIT: GLenum; + readonly DEPTH_CLEAR_VALUE: GLenum; + readonly DEPTH_COMPONENT: GLenum; + readonly DEPTH_COMPONENT16: GLenum; + readonly DEPTH_FUNC: GLenum; + readonly DEPTH_RANGE: GLenum; + readonly DEPTH_STENCIL: GLenum; + readonly DEPTH_STENCIL_ATTACHMENT: GLenum; + readonly DEPTH_TEST: GLenum; + readonly DEPTH_WRITEMASK: GLenum; + readonly DITHER: GLenum; + readonly DONT_CARE: GLenum; + readonly DST_ALPHA: GLenum; + readonly DST_COLOR: GLenum; + readonly DYNAMIC_DRAW: GLenum; + readonly ELEMENT_ARRAY_BUFFER: GLenum; + readonly ELEMENT_ARRAY_BUFFER_BINDING: GLenum; + readonly EQUAL: GLenum; + readonly FASTEST: GLenum; + readonly FLOAT: GLenum; + readonly FLOAT_MAT2: GLenum; + readonly FLOAT_MAT3: GLenum; + readonly FLOAT_MAT4: GLenum; + readonly FLOAT_VEC2: GLenum; + readonly FLOAT_VEC3: GLenum; + readonly FLOAT_VEC4: GLenum; + readonly FRAGMENT_SHADER: GLenum; + readonly FRAMEBUFFER: GLenum; + readonly FRAMEBUFFER_ATTACHMENT_OBJECT_NAME: GLenum; + readonly FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE: GLenum; + readonly FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE: GLenum; + readonly FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL: GLenum; + readonly FRAMEBUFFER_BINDING: GLenum; + readonly FRAMEBUFFER_COMPLETE: GLenum; + readonly FRAMEBUFFER_INCOMPLETE_ATTACHMENT: GLenum; + readonly FRAMEBUFFER_INCOMPLETE_DIMENSIONS: GLenum; + readonly FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: GLenum; + readonly FRAMEBUFFER_UNSUPPORTED: GLenum; + readonly FRONT: GLenum; + readonly FRONT_AND_BACK: GLenum; + readonly FRONT_FACE: GLenum; + readonly FUNC_ADD: GLenum; + readonly FUNC_REVERSE_SUBTRACT: GLenum; + readonly FUNC_SUBTRACT: GLenum; + readonly GENERATE_MIPMAP_HINT: GLenum; + readonly GEQUAL: GLenum; + readonly GREATER: GLenum; + readonly GREEN_BITS: GLenum; + readonly HIGH_FLOAT: GLenum; + readonly HIGH_INT: GLenum; + readonly IMPLEMENTATION_COLOR_READ_FORMAT: GLenum; + readonly IMPLEMENTATION_COLOR_READ_TYPE: GLenum; + readonly INCR: GLenum; + readonly INCR_WRAP: GLenum; + readonly INT: GLenum; + readonly INT_VEC2: GLenum; + readonly INT_VEC3: GLenum; + readonly INT_VEC4: GLenum; + readonly INVALID_ENUM: GLenum; + readonly INVALID_FRAMEBUFFER_OPERATION: GLenum; + readonly INVALID_OPERATION: GLenum; + readonly INVALID_VALUE: GLenum; + readonly INVERT: GLenum; + readonly KEEP: GLenum; + readonly LEQUAL: GLenum; + readonly LESS: GLenum; + readonly LINEAR: GLenum; + readonly LINEAR_MIPMAP_LINEAR: GLenum; + readonly LINEAR_MIPMAP_NEAREST: GLenum; + readonly LINES: GLenum; + readonly LINE_LOOP: GLenum; + readonly LINE_STRIP: GLenum; + readonly LINE_WIDTH: GLenum; + readonly LINK_STATUS: GLenum; + readonly LOW_FLOAT: GLenum; + readonly LOW_INT: GLenum; + readonly LUMINANCE: GLenum; + readonly LUMINANCE_ALPHA: GLenum; + readonly MAX_COMBINED_TEXTURE_IMAGE_UNITS: GLenum; + readonly MAX_CUBE_MAP_TEXTURE_SIZE: GLenum; + readonly MAX_FRAGMENT_UNIFORM_VECTORS: GLenum; + readonly MAX_RENDERBUFFER_SIZE: GLenum; + readonly MAX_TEXTURE_IMAGE_UNITS: GLenum; + readonly MAX_TEXTURE_SIZE: GLenum; + readonly MAX_VARYING_VECTORS: GLenum; + readonly MAX_VERTEX_ATTRIBS: GLenum; + readonly MAX_VERTEX_TEXTURE_IMAGE_UNITS: GLenum; + readonly MAX_VERTEX_UNIFORM_VECTORS: GLenum; + readonly MAX_VIEWPORT_DIMS: GLenum; + readonly MEDIUM_FLOAT: GLenum; + readonly MEDIUM_INT: GLenum; + readonly MIRRORED_REPEAT: GLenum; + readonly NEAREST: GLenum; + readonly NEAREST_MIPMAP_LINEAR: GLenum; + readonly NEAREST_MIPMAP_NEAREST: GLenum; + readonly NEVER: GLenum; + readonly NICEST: GLenum; + readonly NONE: GLenum; + readonly NOTEQUAL: GLenum; + readonly NO_ERROR: GLenum; + readonly ONE: GLenum; + readonly ONE_MINUS_CONSTANT_ALPHA: GLenum; + readonly ONE_MINUS_CONSTANT_COLOR: GLenum; + readonly ONE_MINUS_DST_ALPHA: GLenum; + readonly ONE_MINUS_DST_COLOR: GLenum; + readonly ONE_MINUS_SRC_ALPHA: GLenum; + readonly ONE_MINUS_SRC_COLOR: GLenum; + readonly OUT_OF_MEMORY: GLenum; + readonly PACK_ALIGNMENT: GLenum; + readonly POINTS: GLenum; + readonly POLYGON_OFFSET_FACTOR: GLenum; + readonly POLYGON_OFFSET_FILL: GLenum; + readonly POLYGON_OFFSET_UNITS: GLenum; + readonly RED_BITS: GLenum; + readonly RENDERBUFFER: GLenum; + readonly RENDERBUFFER_ALPHA_SIZE: GLenum; + readonly RENDERBUFFER_BINDING: GLenum; + readonly RENDERBUFFER_BLUE_SIZE: GLenum; + readonly RENDERBUFFER_DEPTH_SIZE: GLenum; + readonly RENDERBUFFER_GREEN_SIZE: GLenum; + readonly RENDERBUFFER_HEIGHT: GLenum; + readonly RENDERBUFFER_INTERNAL_FORMAT: GLenum; + readonly RENDERBUFFER_RED_SIZE: GLenum; + readonly RENDERBUFFER_STENCIL_SIZE: GLenum; + readonly RENDERBUFFER_WIDTH: GLenum; + readonly RENDERER: GLenum; + readonly REPEAT: GLenum; + readonly REPLACE: GLenum; + readonly RGB: GLenum; + readonly RGB565: GLenum; + readonly RGB5_A1: GLenum; + readonly RGBA: GLenum; + readonly RGBA4: GLenum; + readonly SAMPLER_2D: GLenum; + readonly SAMPLER_CUBE: GLenum; + readonly SAMPLES: GLenum; + readonly SAMPLE_ALPHA_TO_COVERAGE: GLenum; + readonly SAMPLE_BUFFERS: GLenum; + readonly SAMPLE_COVERAGE: GLenum; + readonly SAMPLE_COVERAGE_INVERT: GLenum; + readonly SAMPLE_COVERAGE_VALUE: GLenum; + readonly SCISSOR_BOX: GLenum; + readonly SCISSOR_TEST: GLenum; + readonly SHADER_TYPE: GLenum; + readonly SHADING_LANGUAGE_VERSION: GLenum; + readonly SHORT: GLenum; + readonly SRC_ALPHA: GLenum; + readonly SRC_ALPHA_SATURATE: GLenum; + readonly SRC_COLOR: GLenum; + readonly STATIC_DRAW: GLenum; + readonly STENCIL_ATTACHMENT: GLenum; + readonly STENCIL_BACK_FAIL: GLenum; + readonly STENCIL_BACK_FUNC: GLenum; + readonly STENCIL_BACK_PASS_DEPTH_FAIL: GLenum; + readonly STENCIL_BACK_PASS_DEPTH_PASS: GLenum; + readonly STENCIL_BACK_REF: GLenum; + readonly STENCIL_BACK_VALUE_MASK: GLenum; + readonly STENCIL_BACK_WRITEMASK: GLenum; + readonly STENCIL_BITS: GLenum; + readonly STENCIL_BUFFER_BIT: GLenum; + readonly STENCIL_CLEAR_VALUE: GLenum; + readonly STENCIL_FAIL: GLenum; + readonly STENCIL_FUNC: GLenum; + readonly STENCIL_INDEX8: GLenum; + readonly STENCIL_PASS_DEPTH_FAIL: GLenum; + readonly STENCIL_PASS_DEPTH_PASS: GLenum; + readonly STENCIL_REF: GLenum; + readonly STENCIL_TEST: GLenum; + readonly STENCIL_VALUE_MASK: GLenum; + readonly STENCIL_WRITEMASK: GLenum; + readonly STREAM_DRAW: GLenum; + readonly SUBPIXEL_BITS: GLenum; + readonly TEXTURE: GLenum; + readonly TEXTURE0: GLenum; + readonly TEXTURE1: GLenum; + readonly TEXTURE10: GLenum; + readonly TEXTURE11: GLenum; + readonly TEXTURE12: GLenum; + readonly TEXTURE13: GLenum; + readonly TEXTURE14: GLenum; + readonly TEXTURE15: GLenum; + readonly TEXTURE16: GLenum; + readonly TEXTURE17: GLenum; + readonly TEXTURE18: GLenum; + readonly TEXTURE19: GLenum; + readonly TEXTURE2: GLenum; + readonly TEXTURE20: GLenum; + readonly TEXTURE21: GLenum; + readonly TEXTURE22: GLenum; + readonly TEXTURE23: GLenum; + readonly TEXTURE24: GLenum; + readonly TEXTURE25: GLenum; + readonly TEXTURE26: GLenum; + readonly TEXTURE27: GLenum; + readonly TEXTURE28: GLenum; + readonly TEXTURE29: GLenum; + readonly TEXTURE3: GLenum; + readonly TEXTURE30: GLenum; + readonly TEXTURE31: GLenum; + readonly TEXTURE4: GLenum; + readonly TEXTURE5: GLenum; + readonly TEXTURE6: GLenum; + readonly TEXTURE7: GLenum; + readonly TEXTURE8: GLenum; + readonly TEXTURE9: GLenum; + readonly TEXTURE_2D: GLenum; + readonly TEXTURE_BINDING_2D: GLenum; + readonly TEXTURE_BINDING_CUBE_MAP: GLenum; + readonly TEXTURE_CUBE_MAP: GLenum; + readonly TEXTURE_CUBE_MAP_NEGATIVE_X: GLenum; + readonly TEXTURE_CUBE_MAP_NEGATIVE_Y: GLenum; + readonly TEXTURE_CUBE_MAP_NEGATIVE_Z: GLenum; + readonly TEXTURE_CUBE_MAP_POSITIVE_X: GLenum; + readonly TEXTURE_CUBE_MAP_POSITIVE_Y: GLenum; + readonly TEXTURE_CUBE_MAP_POSITIVE_Z: GLenum; + readonly TEXTURE_MAG_FILTER: GLenum; + readonly TEXTURE_MIN_FILTER: GLenum; + readonly TEXTURE_WRAP_S: GLenum; + readonly TEXTURE_WRAP_T: GLenum; + readonly TRIANGLES: GLenum; + readonly TRIANGLE_FAN: GLenum; + readonly TRIANGLE_STRIP: GLenum; + readonly UNPACK_ALIGNMENT: GLenum; + readonly UNPACK_COLORSPACE_CONVERSION_WEBGL: GLenum; + readonly UNPACK_FLIP_Y_WEBGL: GLenum; + readonly UNPACK_PREMULTIPLY_ALPHA_WEBGL: GLenum; + readonly UNSIGNED_BYTE: GLenum; + readonly UNSIGNED_INT: GLenum; + readonly UNSIGNED_SHORT: GLenum; + readonly UNSIGNED_SHORT_4_4_4_4: GLenum; + readonly UNSIGNED_SHORT_5_5_5_1: GLenum; + readonly UNSIGNED_SHORT_5_6_5: GLenum; + readonly VALIDATE_STATUS: GLenum; + readonly VENDOR: GLenum; + readonly VERSION: GLenum; + readonly VERTEX_ATTRIB_ARRAY_BUFFER_BINDING: GLenum; + readonly VERTEX_ATTRIB_ARRAY_ENABLED: GLenum; + readonly VERTEX_ATTRIB_ARRAY_NORMALIZED: GLenum; + readonly VERTEX_ATTRIB_ARRAY_POINTER: GLenum; + readonly VERTEX_ATTRIB_ARRAY_SIZE: GLenum; + readonly VERTEX_ATTRIB_ARRAY_STRIDE: GLenum; + readonly VERTEX_ATTRIB_ARRAY_TYPE: GLenum; + readonly VERTEX_SHADER: GLenum; + readonly VIEWPORT: GLenum; + readonly ZERO: GLenum; +}; + +interface WebGLRenderingContextBase { + readonly canvas: HTMLCanvasElement; + readonly drawingBufferHeight: GLsizei; + readonly drawingBufferWidth: GLsizei; + activeTexture(texture: GLenum): void; + attachShader(program: WebGLProgram, shader: WebGLShader): void; + bindAttribLocation(program: WebGLProgram, index: GLuint, name: string): void; + bindBuffer(target: GLenum, buffer: WebGLBuffer | null): void; + bindFramebuffer(target: GLenum, framebuffer: WebGLFramebuffer | null): void; + bindRenderbuffer(target: GLenum, renderbuffer: WebGLRenderbuffer | null): void; + bindTexture(target: GLenum, texture: WebGLTexture | null): void; + blendColor(red: GLclampf, green: GLclampf, blue: GLclampf, alpha: GLclampf): void; + blendEquation(mode: GLenum): void; + blendEquationSeparate(modeRGB: GLenum, modeAlpha: GLenum): void; + blendFunc(sfactor: GLenum, dfactor: GLenum): void; + blendFuncSeparate(srcRGB: GLenum, dstRGB: GLenum, srcAlpha: GLenum, dstAlpha: GLenum): void; + bufferData(target: GLenum, size: GLsizeiptr, usage: GLenum): void; + bufferData(target: GLenum, data: BufferSource | null, usage: GLenum): void; + bufferSubData(target: GLenum, offset: GLintptr, data: BufferSource): void; + checkFramebufferStatus(target: GLenum): GLenum; + clear(mask: GLbitfield): void; + clearColor(red: GLclampf, green: GLclampf, blue: GLclampf, alpha: GLclampf): void; + clearDepth(depth: GLclampf): void; + clearStencil(s: GLint): void; + colorMask(red: GLboolean, green: GLboolean, blue: GLboolean, alpha: GLboolean): void; + compileShader(shader: WebGLShader): void; + compressedTexImage2D(target: GLenum, level: GLint, internalformat: GLenum, width: GLsizei, height: GLsizei, border: GLint, data: ArrayBufferView): void; + compressedTexSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, width: GLsizei, height: GLsizei, format: GLenum, data: ArrayBufferView): void; + copyTexImage2D(target: GLenum, level: GLint, internalformat: GLenum, x: GLint, y: GLint, width: GLsizei, height: GLsizei, border: GLint): void; + copyTexSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, x: GLint, y: GLint, width: GLsizei, height: GLsizei): void; + createBuffer(): WebGLBuffer | null; + createFramebuffer(): WebGLFramebuffer | null; + createProgram(): WebGLProgram | null; + createRenderbuffer(): WebGLRenderbuffer | null; + createShader(type: GLenum): WebGLShader | null; + createTexture(): WebGLTexture | null; + cullFace(mode: GLenum): void; + deleteBuffer(buffer: WebGLBuffer | null): void; + deleteFramebuffer(framebuffer: WebGLFramebuffer | null): void; + deleteProgram(program: WebGLProgram | null): void; + deleteRenderbuffer(renderbuffer: WebGLRenderbuffer | null): void; + deleteShader(shader: WebGLShader | null): void; + deleteTexture(texture: WebGLTexture | null): void; + depthFunc(func: GLenum): void; + depthMask(flag: GLboolean): void; + depthRange(zNear: GLclampf, zFar: GLclampf): void; + detachShader(program: WebGLProgram, shader: WebGLShader): void; + disable(cap: GLenum): void; + disableVertexAttribArray(index: GLuint): void; + drawArrays(mode: GLenum, first: GLint, count: GLsizei): void; + drawElements(mode: GLenum, count: GLsizei, type: GLenum, offset: GLintptr): void; + enable(cap: GLenum): void; + enableVertexAttribArray(index: GLuint): void; + finish(): void; + flush(): void; + framebufferRenderbuffer(target: GLenum, attachment: GLenum, renderbuffertarget: GLenum, renderbuffer: WebGLRenderbuffer | null): void; + framebufferTexture2D(target: GLenum, attachment: GLenum, textarget: GLenum, texture: WebGLTexture | null, level: GLint): void; + frontFace(mode: GLenum): void; + generateMipmap(target: GLenum): void; + getActiveAttrib(program: WebGLProgram, index: GLuint): WebGLActiveInfo | null; + getActiveUniform(program: WebGLProgram, index: GLuint): WebGLActiveInfo | null; + getAttachedShaders(program: WebGLProgram): WebGLShader[] | null; + getAttribLocation(program: WebGLProgram, name: string): GLint; + getBufferParameter(target: GLenum, pname: GLenum): any; + getContextAttributes(): WebGLContextAttributes | null; + getError(): GLenum; + getExtension(extensionName: "EXT_blend_minmax"): EXT_blend_minmax | null; + getExtension(extensionName: "EXT_texture_filter_anisotropic"): EXT_texture_filter_anisotropic | null; + getExtension(extensionName: "EXT_frag_depth"): EXT_frag_depth | null; + getExtension(extensionName: "EXT_shader_texture_lod"): EXT_shader_texture_lod | null; + getExtension(extensionName: "EXT_sRGB"): EXT_sRGB | null; + getExtension(extensionName: "OES_vertex_array_object"): OES_vertex_array_object | null; + getExtension(extensionName: "WEBGL_color_buffer_float"): WEBGL_color_buffer_float | null; + getExtension(extensionName: "WEBGL_compressed_texture_astc"): WEBGL_compressed_texture_astc | null; + getExtension(extensionName: "WEBGL_compressed_texture_s3tc_srgb"): WEBGL_compressed_texture_s3tc_srgb | null; + getExtension(extensionName: "WEBGL_debug_shaders"): WEBGL_debug_shaders | null; + getExtension(extensionName: "WEBGL_draw_buffers"): WEBGL_draw_buffers | null; + getExtension(extensionName: "WEBGL_lose_context"): WEBGL_lose_context | null; + getExtension(extensionName: "WEBGL_depth_texture"): WEBGL_depth_texture | null; + getExtension(extensionName: "WEBGL_debug_renderer_info"): WEBGL_debug_renderer_info | null; + getExtension(extensionName: "WEBGL_compressed_texture_s3tc"): WEBGL_compressed_texture_s3tc | null; + getExtension(extensionName: "OES_texture_half_float_linear"): OES_texture_half_float_linear | null; + getExtension(extensionName: "OES_texture_half_float"): OES_texture_half_float | null; + getExtension(extensionName: "OES_texture_float_linear"): OES_texture_float_linear | null; + getExtension(extensionName: "OES_texture_float"): OES_texture_float | null; + getExtension(extensionName: "OES_standard_derivatives"): OES_standard_derivatives | null; + getExtension(extensionName: "OES_element_index_uint"): OES_element_index_uint | null; + getExtension(extensionName: "ANGLE_instanced_arrays"): ANGLE_instanced_arrays | null; + getExtension(extensionName: string): any; + getFramebufferAttachmentParameter(target: GLenum, attachment: GLenum, pname: GLenum): any; + getParameter(pname: GLenum): any; + getProgramInfoLog(program: WebGLProgram): string | null; + getProgramParameter(program: WebGLProgram, pname: GLenum): any; + getRenderbufferParameter(target: GLenum, pname: GLenum): any; + getShaderInfoLog(shader: WebGLShader): string | null; + getShaderParameter(shader: WebGLShader, pname: GLenum): any; + getShaderPrecisionFormat(shadertype: GLenum, precisiontype: GLenum): WebGLShaderPrecisionFormat | null; + getShaderSource(shader: WebGLShader): string | null; + getSupportedExtensions(): string[] | null; + getTexParameter(target: GLenum, pname: GLenum): any; + getUniform(program: WebGLProgram, location: WebGLUniformLocation): any; + getUniformLocation(program: WebGLProgram, name: string): WebGLUniformLocation | null; + getVertexAttrib(index: GLuint, pname: GLenum): any; + getVertexAttribOffset(index: GLuint, pname: GLenum): GLintptr; + hint(target: GLenum, mode: GLenum): void; + isBuffer(buffer: WebGLBuffer | null): GLboolean; + isContextLost(): boolean; + isEnabled(cap: GLenum): GLboolean; + isFramebuffer(framebuffer: WebGLFramebuffer | null): GLboolean; + isProgram(program: WebGLProgram | null): GLboolean; + isRenderbuffer(renderbuffer: WebGLRenderbuffer | null): GLboolean; + isShader(shader: WebGLShader | null): GLboolean; + isTexture(texture: WebGLTexture | null): GLboolean; + lineWidth(width: GLfloat): void; + linkProgram(program: WebGLProgram): void; + pixelStorei(pname: GLenum, param: GLint): void; + polygonOffset(factor: GLfloat, units: GLfloat): void; + readPixels(x: GLint, y: GLint, width: GLsizei, height: GLsizei, format: GLenum, type: GLenum, pixels: ArrayBufferView | null): void; + renderbufferStorage(target: GLenum, internalformat: GLenum, width: GLsizei, height: GLsizei): void; + sampleCoverage(value: GLclampf, invert: GLboolean): void; + scissor(x: GLint, y: GLint, width: GLsizei, height: GLsizei): void; + shaderSource(shader: WebGLShader, source: string): void; + stencilFunc(func: GLenum, ref: GLint, mask: GLuint): void; + stencilFuncSeparate(face: GLenum, func: GLenum, ref: GLint, mask: GLuint): void; + stencilMask(mask: GLuint): void; + stencilMaskSeparate(face: GLenum, mask: GLuint): void; + stencilOp(fail: GLenum, zfail: GLenum, zpass: GLenum): void; + stencilOpSeparate(face: GLenum, fail: GLenum, zfail: GLenum, zpass: GLenum): void; + texImage2D(target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, height: GLsizei, border: GLint, format: GLenum, type: GLenum, pixels: ArrayBufferView | null): void; + texImage2D(target: GLenum, level: GLint, internalformat: GLint, format: GLenum, type: GLenum, source: TexImageSource): void; + texParameterf(target: GLenum, pname: GLenum, param: GLfloat): void; + texParameteri(target: GLenum, pname: GLenum, param: GLint): void; + texSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, width: GLsizei, height: GLsizei, format: GLenum, type: GLenum, pixels: ArrayBufferView | null): void; + texSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, format: GLenum, type: GLenum, source: TexImageSource): void; + uniform1f(location: WebGLUniformLocation | null, x: GLfloat): void; + uniform1fv(location: WebGLUniformLocation | null, v: Float32List): void; + uniform1i(location: WebGLUniformLocation | null, x: GLint): void; + uniform1iv(location: WebGLUniformLocation | null, v: Int32List): void; + uniform2f(location: WebGLUniformLocation | null, x: GLfloat, y: GLfloat): void; + uniform2fv(location: WebGLUniformLocation | null, v: Float32List): void; + uniform2i(location: WebGLUniformLocation | null, x: GLint, y: GLint): void; + uniform2iv(location: WebGLUniformLocation | null, v: Int32List): void; + uniform3f(location: WebGLUniformLocation | null, x: GLfloat, y: GLfloat, z: GLfloat): void; + uniform3fv(location: WebGLUniformLocation | null, v: Float32List): void; + uniform3i(location: WebGLUniformLocation | null, x: GLint, y: GLint, z: GLint): void; + uniform3iv(location: WebGLUniformLocation | null, v: Int32List): void; + uniform4f(location: WebGLUniformLocation | null, x: GLfloat, y: GLfloat, z: GLfloat, w: GLfloat): void; + uniform4fv(location: WebGLUniformLocation | null, v: Float32List): void; + uniform4i(location: WebGLUniformLocation | null, x: GLint, y: GLint, z: GLint, w: GLint): void; + uniform4iv(location: WebGLUniformLocation | null, v: Int32List): void; + uniformMatrix2fv(location: WebGLUniformLocation | null, transpose: GLboolean, value: Float32List): void; + uniformMatrix3fv(location: WebGLUniformLocation | null, transpose: GLboolean, value: Float32List): void; + uniformMatrix4fv(location: WebGLUniformLocation | null, transpose: GLboolean, value: Float32List): void; + useProgram(program: WebGLProgram | null): void; + validateProgram(program: WebGLProgram): void; + vertexAttrib1f(index: GLuint, x: GLfloat): void; + vertexAttrib1fv(index: GLuint, values: Float32List): void; + vertexAttrib2f(index: GLuint, x: GLfloat, y: GLfloat): void; + vertexAttrib2fv(index: GLuint, values: Float32List): void; + vertexAttrib3f(index: GLuint, x: GLfloat, y: GLfloat, z: GLfloat): void; + vertexAttrib3fv(index: GLuint, values: Float32List): void; + vertexAttrib4f(index: GLuint, x: GLfloat, y: GLfloat, z: GLfloat, w: GLfloat): void; + vertexAttrib4fv(index: GLuint, values: Float32List): void; + vertexAttribPointer(index: GLuint, size: GLint, type: GLenum, normalized: GLboolean, stride: GLsizei, offset: GLintptr): void; + viewport(x: GLint, y: GLint, width: GLsizei, height: GLsizei): void; + readonly ACTIVE_ATTRIBUTES: GLenum; + readonly ACTIVE_TEXTURE: GLenum; + readonly ACTIVE_UNIFORMS: GLenum; + readonly ALIASED_LINE_WIDTH_RANGE: GLenum; + readonly ALIASED_POINT_SIZE_RANGE: GLenum; + readonly ALPHA: GLenum; + readonly ALPHA_BITS: GLenum; + readonly ALWAYS: GLenum; + readonly ARRAY_BUFFER: GLenum; + readonly ARRAY_BUFFER_BINDING: GLenum; + readonly ATTACHED_SHADERS: GLenum; + readonly BACK: GLenum; + readonly BLEND: GLenum; + readonly BLEND_COLOR: GLenum; + readonly BLEND_DST_ALPHA: GLenum; + readonly BLEND_DST_RGB: GLenum; + readonly BLEND_EQUATION: GLenum; + readonly BLEND_EQUATION_ALPHA: GLenum; + readonly BLEND_EQUATION_RGB: GLenum; + readonly BLEND_SRC_ALPHA: GLenum; + readonly BLEND_SRC_RGB: GLenum; + readonly BLUE_BITS: GLenum; + readonly BOOL: GLenum; + readonly BOOL_VEC2: GLenum; + readonly BOOL_VEC3: GLenum; + readonly BOOL_VEC4: GLenum; + readonly BROWSER_DEFAULT_WEBGL: GLenum; + readonly BUFFER_SIZE: GLenum; + readonly BUFFER_USAGE: GLenum; + readonly BYTE: GLenum; + readonly CCW: GLenum; + readonly CLAMP_TO_EDGE: GLenum; + readonly COLOR_ATTACHMENT0: GLenum; + readonly COLOR_BUFFER_BIT: GLenum; + readonly COLOR_CLEAR_VALUE: GLenum; + readonly COLOR_WRITEMASK: GLenum; + readonly COMPILE_STATUS: GLenum; + readonly COMPRESSED_TEXTURE_FORMATS: GLenum; + readonly CONSTANT_ALPHA: GLenum; + readonly CONSTANT_COLOR: GLenum; + readonly CONTEXT_LOST_WEBGL: GLenum; + readonly CULL_FACE: GLenum; + readonly CULL_FACE_MODE: GLenum; + readonly CURRENT_PROGRAM: GLenum; + readonly CURRENT_VERTEX_ATTRIB: GLenum; + readonly CW: GLenum; + readonly DECR: GLenum; + readonly DECR_WRAP: GLenum; + readonly DELETE_STATUS: GLenum; + readonly DEPTH_ATTACHMENT: GLenum; + readonly DEPTH_BITS: GLenum; + readonly DEPTH_BUFFER_BIT: GLenum; + readonly DEPTH_CLEAR_VALUE: GLenum; + readonly DEPTH_COMPONENT: GLenum; + readonly DEPTH_COMPONENT16: GLenum; + readonly DEPTH_FUNC: GLenum; + readonly DEPTH_RANGE: GLenum; + readonly DEPTH_STENCIL: GLenum; + readonly DEPTH_STENCIL_ATTACHMENT: GLenum; + readonly DEPTH_TEST: GLenum; + readonly DEPTH_WRITEMASK: GLenum; + readonly DITHER: GLenum; + readonly DONT_CARE: GLenum; + readonly DST_ALPHA: GLenum; + readonly DST_COLOR: GLenum; + readonly DYNAMIC_DRAW: GLenum; + readonly ELEMENT_ARRAY_BUFFER: GLenum; + readonly ELEMENT_ARRAY_BUFFER_BINDING: GLenum; + readonly EQUAL: GLenum; + readonly FASTEST: GLenum; + readonly FLOAT: GLenum; + readonly FLOAT_MAT2: GLenum; + readonly FLOAT_MAT3: GLenum; + readonly FLOAT_MAT4: GLenum; + readonly FLOAT_VEC2: GLenum; + readonly FLOAT_VEC3: GLenum; + readonly FLOAT_VEC4: GLenum; + readonly FRAGMENT_SHADER: GLenum; + readonly FRAMEBUFFER: GLenum; + readonly FRAMEBUFFER_ATTACHMENT_OBJECT_NAME: GLenum; + readonly FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE: GLenum; + readonly FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE: GLenum; + readonly FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL: GLenum; + readonly FRAMEBUFFER_BINDING: GLenum; + readonly FRAMEBUFFER_COMPLETE: GLenum; + readonly FRAMEBUFFER_INCOMPLETE_ATTACHMENT: GLenum; + readonly FRAMEBUFFER_INCOMPLETE_DIMENSIONS: GLenum; + readonly FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: GLenum; + readonly FRAMEBUFFER_UNSUPPORTED: GLenum; + readonly FRONT: GLenum; + readonly FRONT_AND_BACK: GLenum; + readonly FRONT_FACE: GLenum; + readonly FUNC_ADD: GLenum; + readonly FUNC_REVERSE_SUBTRACT: GLenum; + readonly FUNC_SUBTRACT: GLenum; + readonly GENERATE_MIPMAP_HINT: GLenum; + readonly GEQUAL: GLenum; + readonly GREATER: GLenum; + readonly GREEN_BITS: GLenum; + readonly HIGH_FLOAT: GLenum; + readonly HIGH_INT: GLenum; + readonly IMPLEMENTATION_COLOR_READ_FORMAT: GLenum; + readonly IMPLEMENTATION_COLOR_READ_TYPE: GLenum; + readonly INCR: GLenum; + readonly INCR_WRAP: GLenum; + readonly INT: GLenum; + readonly INT_VEC2: GLenum; + readonly INT_VEC3: GLenum; + readonly INT_VEC4: GLenum; + readonly INVALID_ENUM: GLenum; + readonly INVALID_FRAMEBUFFER_OPERATION: GLenum; + readonly INVALID_OPERATION: GLenum; + readonly INVALID_VALUE: GLenum; + readonly INVERT: GLenum; + readonly KEEP: GLenum; + readonly LEQUAL: GLenum; + readonly LESS: GLenum; + readonly LINEAR: GLenum; + readonly LINEAR_MIPMAP_LINEAR: GLenum; + readonly LINEAR_MIPMAP_NEAREST: GLenum; + readonly LINES: GLenum; + readonly LINE_LOOP: GLenum; + readonly LINE_STRIP: GLenum; + readonly LINE_WIDTH: GLenum; + readonly LINK_STATUS: GLenum; + readonly LOW_FLOAT: GLenum; + readonly LOW_INT: GLenum; + readonly LUMINANCE: GLenum; + readonly LUMINANCE_ALPHA: GLenum; + readonly MAX_COMBINED_TEXTURE_IMAGE_UNITS: GLenum; + readonly MAX_CUBE_MAP_TEXTURE_SIZE: GLenum; + readonly MAX_FRAGMENT_UNIFORM_VECTORS: GLenum; + readonly MAX_RENDERBUFFER_SIZE: GLenum; + readonly MAX_TEXTURE_IMAGE_UNITS: GLenum; + readonly MAX_TEXTURE_SIZE: GLenum; + readonly MAX_VARYING_VECTORS: GLenum; + readonly MAX_VERTEX_ATTRIBS: GLenum; + readonly MAX_VERTEX_TEXTURE_IMAGE_UNITS: GLenum; + readonly MAX_VERTEX_UNIFORM_VECTORS: GLenum; + readonly MAX_VIEWPORT_DIMS: GLenum; + readonly MEDIUM_FLOAT: GLenum; + readonly MEDIUM_INT: GLenum; + readonly MIRRORED_REPEAT: GLenum; + readonly NEAREST: GLenum; + readonly NEAREST_MIPMAP_LINEAR: GLenum; + readonly NEAREST_MIPMAP_NEAREST: GLenum; + readonly NEVER: GLenum; + readonly NICEST: GLenum; + readonly NONE: GLenum; + readonly NOTEQUAL: GLenum; + readonly NO_ERROR: GLenum; + readonly ONE: GLenum; + readonly ONE_MINUS_CONSTANT_ALPHA: GLenum; + readonly ONE_MINUS_CONSTANT_COLOR: GLenum; + readonly ONE_MINUS_DST_ALPHA: GLenum; + readonly ONE_MINUS_DST_COLOR: GLenum; + readonly ONE_MINUS_SRC_ALPHA: GLenum; + readonly ONE_MINUS_SRC_COLOR: GLenum; + readonly OUT_OF_MEMORY: GLenum; + readonly PACK_ALIGNMENT: GLenum; + readonly POINTS: GLenum; + readonly POLYGON_OFFSET_FACTOR: GLenum; + readonly POLYGON_OFFSET_FILL: GLenum; + readonly POLYGON_OFFSET_UNITS: GLenum; + readonly RED_BITS: GLenum; + readonly RENDERBUFFER: GLenum; + readonly RENDERBUFFER_ALPHA_SIZE: GLenum; + readonly RENDERBUFFER_BINDING: GLenum; + readonly RENDERBUFFER_BLUE_SIZE: GLenum; + readonly RENDERBUFFER_DEPTH_SIZE: GLenum; + readonly RENDERBUFFER_GREEN_SIZE: GLenum; + readonly RENDERBUFFER_HEIGHT: GLenum; + readonly RENDERBUFFER_INTERNAL_FORMAT: GLenum; + readonly RENDERBUFFER_RED_SIZE: GLenum; + readonly RENDERBUFFER_STENCIL_SIZE: GLenum; + readonly RENDERBUFFER_WIDTH: GLenum; + readonly RENDERER: GLenum; + readonly REPEAT: GLenum; + readonly REPLACE: GLenum; + readonly RGB: GLenum; + readonly RGB565: GLenum; + readonly RGB5_A1: GLenum; + readonly RGBA: GLenum; + readonly RGBA4: GLenum; + readonly SAMPLER_2D: GLenum; + readonly SAMPLER_CUBE: GLenum; + readonly SAMPLES: GLenum; + readonly SAMPLE_ALPHA_TO_COVERAGE: GLenum; + readonly SAMPLE_BUFFERS: GLenum; + readonly SAMPLE_COVERAGE: GLenum; + readonly SAMPLE_COVERAGE_INVERT: GLenum; + readonly SAMPLE_COVERAGE_VALUE: GLenum; + readonly SCISSOR_BOX: GLenum; + readonly SCISSOR_TEST: GLenum; + readonly SHADER_TYPE: GLenum; + readonly SHADING_LANGUAGE_VERSION: GLenum; + readonly SHORT: GLenum; + readonly SRC_ALPHA: GLenum; + readonly SRC_ALPHA_SATURATE: GLenum; + readonly SRC_COLOR: GLenum; + readonly STATIC_DRAW: GLenum; + readonly STENCIL_ATTACHMENT: GLenum; + readonly STENCIL_BACK_FAIL: GLenum; + readonly STENCIL_BACK_FUNC: GLenum; + readonly STENCIL_BACK_PASS_DEPTH_FAIL: GLenum; + readonly STENCIL_BACK_PASS_DEPTH_PASS: GLenum; + readonly STENCIL_BACK_REF: GLenum; + readonly STENCIL_BACK_VALUE_MASK: GLenum; + readonly STENCIL_BACK_WRITEMASK: GLenum; + readonly STENCIL_BITS: GLenum; + readonly STENCIL_BUFFER_BIT: GLenum; + readonly STENCIL_CLEAR_VALUE: GLenum; + readonly STENCIL_FAIL: GLenum; + readonly STENCIL_FUNC: GLenum; + readonly STENCIL_INDEX8: GLenum; + readonly STENCIL_PASS_DEPTH_FAIL: GLenum; + readonly STENCIL_PASS_DEPTH_PASS: GLenum; + readonly STENCIL_REF: GLenum; + readonly STENCIL_TEST: GLenum; + readonly STENCIL_VALUE_MASK: GLenum; + readonly STENCIL_WRITEMASK: GLenum; + readonly STREAM_DRAW: GLenum; + readonly SUBPIXEL_BITS: GLenum; + readonly TEXTURE: GLenum; + readonly TEXTURE0: GLenum; + readonly TEXTURE1: GLenum; + readonly TEXTURE10: GLenum; + readonly TEXTURE11: GLenum; + readonly TEXTURE12: GLenum; + readonly TEXTURE13: GLenum; + readonly TEXTURE14: GLenum; + readonly TEXTURE15: GLenum; + readonly TEXTURE16: GLenum; + readonly TEXTURE17: GLenum; + readonly TEXTURE18: GLenum; + readonly TEXTURE19: GLenum; + readonly TEXTURE2: GLenum; + readonly TEXTURE20: GLenum; + readonly TEXTURE21: GLenum; + readonly TEXTURE22: GLenum; + readonly TEXTURE23: GLenum; + readonly TEXTURE24: GLenum; + readonly TEXTURE25: GLenum; + readonly TEXTURE26: GLenum; + readonly TEXTURE27: GLenum; + readonly TEXTURE28: GLenum; + readonly TEXTURE29: GLenum; + readonly TEXTURE3: GLenum; + readonly TEXTURE30: GLenum; + readonly TEXTURE31: GLenum; + readonly TEXTURE4: GLenum; + readonly TEXTURE5: GLenum; + readonly TEXTURE6: GLenum; + readonly TEXTURE7: GLenum; + readonly TEXTURE8: GLenum; + readonly TEXTURE9: GLenum; + readonly TEXTURE_2D: GLenum; + readonly TEXTURE_BINDING_2D: GLenum; + readonly TEXTURE_BINDING_CUBE_MAP: GLenum; + readonly TEXTURE_CUBE_MAP: GLenum; + readonly TEXTURE_CUBE_MAP_NEGATIVE_X: GLenum; + readonly TEXTURE_CUBE_MAP_NEGATIVE_Y: GLenum; + readonly TEXTURE_CUBE_MAP_NEGATIVE_Z: GLenum; + readonly TEXTURE_CUBE_MAP_POSITIVE_X: GLenum; + readonly TEXTURE_CUBE_MAP_POSITIVE_Y: GLenum; + readonly TEXTURE_CUBE_MAP_POSITIVE_Z: GLenum; + readonly TEXTURE_MAG_FILTER: GLenum; + readonly TEXTURE_MIN_FILTER: GLenum; + readonly TEXTURE_WRAP_S: GLenum; + readonly TEXTURE_WRAP_T: GLenum; + readonly TRIANGLES: GLenum; + readonly TRIANGLE_FAN: GLenum; + readonly TRIANGLE_STRIP: GLenum; + readonly UNPACK_ALIGNMENT: GLenum; + readonly UNPACK_COLORSPACE_CONVERSION_WEBGL: GLenum; + readonly UNPACK_FLIP_Y_WEBGL: GLenum; + readonly UNPACK_PREMULTIPLY_ALPHA_WEBGL: GLenum; + readonly UNSIGNED_BYTE: GLenum; + readonly UNSIGNED_INT: GLenum; + readonly UNSIGNED_SHORT: GLenum; + readonly UNSIGNED_SHORT_4_4_4_4: GLenum; + readonly UNSIGNED_SHORT_5_5_5_1: GLenum; + readonly UNSIGNED_SHORT_5_6_5: GLenum; + readonly VALIDATE_STATUS: GLenum; + readonly VENDOR: GLenum; + readonly VERSION: GLenum; + readonly VERTEX_ATTRIB_ARRAY_BUFFER_BINDING: GLenum; + readonly VERTEX_ATTRIB_ARRAY_ENABLED: GLenum; + readonly VERTEX_ATTRIB_ARRAY_NORMALIZED: GLenum; + readonly VERTEX_ATTRIB_ARRAY_POINTER: GLenum; + readonly VERTEX_ATTRIB_ARRAY_SIZE: GLenum; + readonly VERTEX_ATTRIB_ARRAY_STRIDE: GLenum; + readonly VERTEX_ATTRIB_ARRAY_TYPE: GLenum; + readonly VERTEX_SHADER: GLenum; + readonly VIEWPORT: GLenum; + readonly ZERO: GLenum; +} + +interface WebGLShader extends WebGLObject { +} + +declare var WebGLShader: { + prototype: WebGLShader; + new(): WebGLShader; +}; + +interface WebGLShaderPrecisionFormat { + readonly precision: GLint; + readonly rangeMax: GLint; + readonly rangeMin: GLint; +} + +declare var WebGLShaderPrecisionFormat: { + prototype: WebGLShaderPrecisionFormat; + new(): WebGLShaderPrecisionFormat; +}; + +interface WebGLTexture extends WebGLObject { +} + +declare var WebGLTexture: { + prototype: WebGLTexture; + new(): WebGLTexture; +}; + +interface WebGLUniformLocation { +} + +declare var WebGLUniformLocation: { + prototype: WebGLUniformLocation; + new(): WebGLUniformLocation; +}; + +interface WebGLVertexArrayObjectOES extends WebGLObject { +} + +interface WebKitPoint { + x: number; + y: number; +} + +declare var WebKitPoint: { + prototype: WebKitPoint; + new(x?: number, y?: number): WebKitPoint; +}; + +interface WebSocketEventMap { + "close": CloseEvent; + "error": Event; + "message": MessageEvent; + "open": Event; +} + +interface WebSocket extends EventTarget { + binaryType: BinaryType; + readonly bufferedAmount: number; + readonly extensions: string; + onclose: ((this: WebSocket, ev: CloseEvent) => any) | null; + onerror: ((this: WebSocket, ev: Event) => any) | null; + onmessage: ((this: WebSocket, ev: MessageEvent) => any) | null; + onopen: ((this: WebSocket, ev: Event) => any) | null; + readonly protocol: string; + readonly readyState: number; + readonly url: string; + close(code?: number, reason?: string): void; + send(data: string | ArrayBufferLike | Blob | ArrayBufferView): void; + readonly CLOSED: number; + readonly CLOSING: number; + readonly CONNECTING: number; + readonly OPEN: number; + addEventListener(type: K, listener: (this: WebSocket, ev: WebSocketEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: WebSocket, ev: WebSocketEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var WebSocket: { + prototype: WebSocket; + new(url: string, protocols?: string | string[]): WebSocket; + readonly CLOSED: number; + readonly CLOSING: number; + readonly CONNECTING: number; + readonly OPEN: number; +}; + +interface WheelEvent extends MouseEvent { + readonly deltaMode: number; + readonly deltaX: number; + readonly deltaY: number; + readonly deltaZ: number; + getCurrentPoint(element: Element): void; + initWheelEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, buttonArg: number, relatedTargetArg: EventTarget, modifiersListArg: string, deltaXArg: number, deltaYArg: number, deltaZArg: number, deltaMode: number): void; + readonly DOM_DELTA_LINE: number; + readonly DOM_DELTA_PAGE: number; + readonly DOM_DELTA_PIXEL: number; +} + +declare var WheelEvent: { + prototype: WheelEvent; + new(typeArg: string, eventInitDict?: WheelEventInit): WheelEvent; + readonly DOM_DELTA_LINE: number; + readonly DOM_DELTA_PAGE: number; + readonly DOM_DELTA_PIXEL: number; +}; + +interface WindowEventMap extends GlobalEventHandlersEventMap, WindowEventHandlersEventMap { + "abort": UIEvent; + "afterprint": Event; + "beforeprint": Event; + "beforeunload": BeforeUnloadEvent; + "blur": FocusEvent; + "canplay": Event; + "canplaythrough": Event; + "change": Event; + "click": MouseEvent; + "compassneedscalibration": Event; + "contextmenu": MouseEvent; + "dblclick": MouseEvent; + "devicelight": DeviceLightEvent; + "devicemotion": DeviceMotionEvent; + "deviceorientation": DeviceOrientationEvent; + "drag": DragEvent; + "dragend": DragEvent; + "dragenter": DragEvent; + "dragleave": DragEvent; + "dragover": DragEvent; + "dragstart": DragEvent; + "drop": DragEvent; + "durationchange": Event; + "emptied": Event; + "ended": Event; + "error": ErrorEvent; + "focus": FocusEvent; + "hashchange": HashChangeEvent; + "input": Event; + "invalid": Event; + "keydown": KeyboardEvent; + "keypress": KeyboardEvent; + "keyup": KeyboardEvent; + "load": Event; + "loadeddata": Event; + "loadedmetadata": Event; + "loadstart": Event; + "message": MessageEvent; + "mousedown": MouseEvent; + "mouseenter": MouseEvent; + "mouseleave": MouseEvent; + "mousemove": MouseEvent; + "mouseout": MouseEvent; + "mouseover": MouseEvent; + "mouseup": MouseEvent; + "mousewheel": Event; + "MSGestureChange": Event; + "MSGestureDoubleTap": Event; + "MSGestureEnd": Event; + "MSGestureHold": Event; + "MSGestureStart": Event; + "MSGestureTap": Event; + "MSInertiaStart": Event; + "MSPointerCancel": Event; + "MSPointerDown": Event; + "MSPointerEnter": Event; + "MSPointerLeave": Event; + "MSPointerMove": Event; + "MSPointerOut": Event; + "MSPointerOver": Event; + "MSPointerUp": Event; + "offline": Event; + "online": Event; + "orientationchange": Event; + "pagehide": PageTransitionEvent; + "pageshow": PageTransitionEvent; + "pause": Event; + "play": Event; + "playing": Event; + "popstate": PopStateEvent; + "progress": ProgressEvent; + "ratechange": Event; + "readystatechange": ProgressEvent; + "reset": Event; + "resize": UIEvent; + "scroll": UIEvent; + "seeked": Event; + "seeking": Event; + "select": UIEvent; + "stalled": Event; + "storage": StorageEvent; + "submit": Event; + "suspend": Event; + "timeupdate": Event; + "unload": Event; + "volumechange": Event; + "vrdisplayactivate": Event; + "vrdisplayblur": Event; + "vrdisplayconnect": Event; + "vrdisplaydeactivate": Event; + "vrdisplaydisconnect": Event; + "vrdisplayfocus": Event; + "vrdisplaypointerrestricted": Event; + "vrdisplaypointerunrestricted": Event; + "vrdisplaypresentchange": Event; + "waiting": Event; +} + +interface Window extends EventTarget, WindowTimers, WindowSessionStorage, WindowLocalStorage, WindowConsole, GlobalEventHandlers, IDBEnvironment, WindowBase64, GlobalFetch, WindowOrWorkerGlobalScope, WindowEventHandlers { + Blob: typeof Blob; + URL: typeof URL; + URLSearchParams: typeof URLSearchParams; + readonly applicationCache: ApplicationCache; + readonly caches: CacheStorage; + readonly clientInformation: Navigator; + readonly closed: boolean; + readonly crypto: Crypto; + customElements: CustomElementRegistry; + defaultStatus: string; + readonly devicePixelRatio: number; + readonly doNotTrack: string; + readonly document: Document; + readonly event: Event | undefined; + /** @deprecated */ + readonly external: External; + readonly frameElement: Element; + readonly frames: Window; + readonly history: History; + readonly innerHeight: number; + readonly innerWidth: number; + readonly isSecureContext: boolean; + readonly length: number; + location: Location; + readonly locationbar: BarProp; + readonly menubar: BarProp; + readonly msContentScript: ExtensionScriptApis; + name: string; + readonly navigator: Navigator; + offscreenBuffering: string | boolean; + oncompassneedscalibration: ((this: Window, ev: Event) => any) | null; + ondevicelight: ((this: Window, ev: DeviceLightEvent) => any) | null; + ondevicemotion: ((this: Window, ev: DeviceMotionEvent) => any) | null; + ondeviceorientation: ((this: Window, ev: DeviceOrientationEvent) => any) | null; + onmousewheel: ((this: Window, ev: Event) => any) | null; + onmsgesturechange: ((this: Window, ev: Event) => any) | null; + onmsgesturedoubletap: ((this: Window, ev: Event) => any) | null; + onmsgestureend: ((this: Window, ev: Event) => any) | null; + onmsgesturehold: ((this: Window, ev: Event) => any) | null; + onmsgesturestart: ((this: Window, ev: Event) => any) | null; + onmsgesturetap: ((this: Window, ev: Event) => any) | null; + onmsinertiastart: ((this: Window, ev: Event) => any) | null; + onmspointercancel: ((this: Window, ev: Event) => any) | null; + onmspointerdown: ((this: Window, ev: Event) => any) | null; + onmspointerenter: ((this: Window, ev: Event) => any) | null; + onmspointerleave: ((this: Window, ev: Event) => any) | null; + onmspointermove: ((this: Window, ev: Event) => any) | null; + onmspointerout: ((this: Window, ev: Event) => any) | null; + onmspointerover: ((this: Window, ev: Event) => any) | null; + onmspointerup: ((this: Window, ev: Event) => any) | null; + /** @deprecated */ + onorientationchange: ((this: Window, ev: Event) => any) | null; + onreadystatechange: ((this: Window, ev: ProgressEvent) => any) | null; + onvrdisplayactivate: ((this: Window, ev: Event) => any) | null; + onvrdisplayblur: ((this: Window, ev: Event) => any) | null; + onvrdisplayconnect: ((this: Window, ev: Event) => any) | null; + onvrdisplaydeactivate: ((this: Window, ev: Event) => any) | null; + onvrdisplaydisconnect: ((this: Window, ev: Event) => any) | null; + onvrdisplayfocus: ((this: Window, ev: Event) => any) | null; + onvrdisplaypointerrestricted: ((this: Window, ev: Event) => any) | null; + onvrdisplaypointerunrestricted: ((this: Window, ev: Event) => any) | null; + onvrdisplaypresentchange: ((this: Window, ev: Event) => any) | null; + opener: any; + /** @deprecated */ + readonly orientation: string | number; + readonly outerHeight: number; + readonly outerWidth: number; + readonly pageXOffset: number; + readonly pageYOffset: number; + readonly parent: Window; + readonly performance: Performance; + readonly personalbar: BarProp; + readonly screen: Screen; + readonly screenLeft: number; + readonly screenTop: number; + readonly screenX: number; + readonly screenY: number; + readonly scrollX: number; + readonly scrollY: number; + readonly scrollbars: BarProp; + readonly self: Window; + readonly speechSynthesis: SpeechSynthesis; + status: string; + readonly statusbar: BarProp; + readonly styleMedia: StyleMedia; + readonly toolbar: BarProp; + readonly top: Window; + readonly window: Window; + alert(message?: any): void; + blur(): void; + cancelAnimationFrame(handle: number): void; + /** @deprecated */ + captureEvents(): void; + close(): void; + confirm(message?: string): boolean; + departFocus(navigationReason: NavigationReason, origin: FocusNavigationOrigin): void; + focus(): void; + getComputedStyle(elt: Element, pseudoElt?: string | null): CSSStyleDeclaration; + getMatchedCSSRules(elt: Element, pseudoElt?: string | null): CSSRuleList; + getSelection(): Selection; + matchMedia(query: string): MediaQueryList; + moveBy(x: number, y: number): void; + moveTo(x: number, y: number): void; + msWriteProfilerMark(profilerMarkName: string): void; + open(url?: string, target?: string, features?: string, replace?: boolean): Window | null; + postMessage(message: any, targetOrigin: string, transfer?: Transferable[]): void; + print(): void; + prompt(message?: string, _default?: string): string | null; + /** @deprecated */ + releaseEvents(): void; + requestAnimationFrame(callback: FrameRequestCallback): number; + resizeBy(x: number, y: number): void; + resizeTo(x: number, y: number): void; + scroll(options?: ScrollToOptions): void; + scroll(x: number, y: number): void; + scrollBy(options?: ScrollToOptions): void; + scrollBy(x: number, y: number): void; + scrollTo(options?: ScrollToOptions): void; + scrollTo(x: number, y: number): void; + stop(): void; + webkitCancelAnimationFrame(handle: number): void; + webkitConvertPointFromNodeToPage(node: Node, pt: WebKitPoint): WebKitPoint; + webkitConvertPointFromPageToNode(node: Node, pt: WebKitPoint): WebKitPoint; + webkitRequestAnimationFrame(callback: FrameRequestCallback): number; + addEventListener(type: K, listener: (this: Window, ev: WindowEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: Window, ev: WindowEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var Window: { + prototype: Window; + new(): Window; +}; + +interface WindowBase64 { + atob(encodedString: string): string; + btoa(rawString: string): string; +} + +interface WindowConsole { + readonly console: Console; +} + +interface WindowEventHandlersEventMap { + "afterprint": Event; + "beforeprint": Event; + "beforeunload": BeforeUnloadEvent; + "hashchange": HashChangeEvent; + "languagechange": Event; + "message": MessageEvent; + "messageerror": MessageEvent; + "offline": Event; + "online": Event; + "pagehide": PageTransitionEvent; + "pageshow": PageTransitionEvent; + "popstate": PopStateEvent; + "rejectionhandled": Event; + "storage": StorageEvent; + "unhandledrejection": PromiseRejectionEvent; + "unload": Event; +} + +interface WindowEventHandlers { + onafterprint: ((this: WindowEventHandlers, ev: Event) => any) | null; + onbeforeprint: ((this: WindowEventHandlers, ev: Event) => any) | null; + onbeforeunload: ((this: WindowEventHandlers, ev: BeforeUnloadEvent) => any) | null; + onhashchange: ((this: WindowEventHandlers, ev: HashChangeEvent) => any) | null; + onlanguagechange: ((this: WindowEventHandlers, ev: Event) => any) | null; + onmessage: ((this: WindowEventHandlers, ev: MessageEvent) => any) | null; + onmessageerror: ((this: WindowEventHandlers, ev: MessageEvent) => any) | null; + onoffline: ((this: WindowEventHandlers, ev: Event) => any) | null; + ononline: ((this: WindowEventHandlers, ev: Event) => any) | null; + onpagehide: ((this: WindowEventHandlers, ev: PageTransitionEvent) => any) | null; + onpageshow: ((this: WindowEventHandlers, ev: PageTransitionEvent) => any) | null; + onpopstate: ((this: WindowEventHandlers, ev: PopStateEvent) => any) | null; + onrejectionhandled: ((this: WindowEventHandlers, ev: Event) => any) | null; + onstorage: ((this: WindowEventHandlers, ev: StorageEvent) => any) | null; + onunhandledrejection: ((this: WindowEventHandlers, ev: PromiseRejectionEvent) => any) | null; + onunload: ((this: WindowEventHandlers, ev: Event) => any) | null; + addEventListener(type: K, listener: (this: WindowEventHandlers, ev: WindowEventHandlersEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: WindowEventHandlers, ev: WindowEventHandlersEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +interface WindowLocalStorage { + readonly localStorage: Storage; +} + +interface WindowOrWorkerGlobalScope { + readonly caches: CacheStorage; + readonly crypto: Crypto; + readonly indexedDB: IDBFactory; + readonly origin: string; + readonly performance: Performance; + atob(data: string): string; + btoa(data: string): string; + clearInterval(handle?: number): void; + clearTimeout(handle?: number): void; + createImageBitmap(image: ImageBitmapSource): Promise; + createImageBitmap(image: ImageBitmapSource, sx: number, sy: number, sw: number, sh: number): Promise; + fetch(input: RequestInfo, init?: RequestInit): Promise; + queueMicrotask(callback: Function): void; + setInterval(handler: TimerHandler, timeout?: number, ...arguments: any[]): number; + setTimeout(handler: TimerHandler, timeout?: number, ...arguments: any[]): number; +} + +interface WindowSessionStorage { + readonly sessionStorage: Storage; +} + +interface WindowTimers { +} + +interface WorkerEventMap extends AbstractWorkerEventMap { + "message": MessageEvent; +} + +interface Worker extends EventTarget, AbstractWorker { + onmessage: ((this: Worker, ev: MessageEvent) => any) | null; + postMessage(message: any, transfer?: Transferable[]): void; + terminate(): void; + addEventListener(type: K, listener: (this: Worker, ev: WorkerEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: Worker, ev: WorkerEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var Worker: { + prototype: Worker; + new(stringUrl: string, options?: WorkerOptions): Worker; +}; + +interface Worklet { + addModule(moduleURL: string, options?: WorkletOptions): Promise; +} + +declare var Worklet: { + prototype: Worklet; + new(): Worklet; +}; + +interface WritableStream { + readonly locked: boolean; + abort(reason?: any): Promise; + getWriter(): WritableStreamDefaultWriter; +} + +declare var WritableStream: { + prototype: WritableStream; + new(underlyingSink?: UnderlyingSink, strategy?: QueuingStrategy): WritableStream; +}; + +interface WritableStreamDefaultController { + error(error?: any): void; +} + +interface WritableStreamDefaultWriter { + readonly closed: Promise; + readonly desiredSize: number | null; + readonly ready: Promise; + abort(reason?: any): Promise; + close(): Promise; + releaseLock(): void; + write(chunk: W): Promise; +} + +interface XMLDocument extends Document { + addEventListener(type: K, listener: (this: XMLDocument, ev: DocumentEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: XMLDocument, ev: DocumentEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var XMLDocument: { + prototype: XMLDocument; + new(): XMLDocument; +}; + +interface XMLHttpRequestEventMap extends XMLHttpRequestEventTargetEventMap { + "readystatechange": Event; +} + +interface XMLHttpRequest extends XMLHttpRequestEventTarget { + onreadystatechange: ((this: XMLHttpRequest, ev: Event) => any) | null; + /** + * Returns client's state. + */ + readonly readyState: number; + /** + * Returns the response's body. + */ + readonly response: any; + /** + * Returns the text response. + * Throws an "InvalidStateError" DOMException if responseType is not the empty string or "text". + */ + readonly responseText: string; + /** + * Returns the response type. + * Can be set to change the response type. Values are: + * the empty string (default), + * "arraybuffer", + * "blob", + * "document", + * "json", and + * "text". + * When set: setting to "document" is ignored if current global object is not a Window object. + * When set: throws an "InvalidStateError" DOMException if state is loading or done. + * When set: throws an "InvalidAccessError" DOMException if the synchronous flag is set and current global object is a Window object. + */ + responseType: XMLHttpRequestResponseType; + readonly responseURL: string; + /** + * Returns the document response. + * Throws an "InvalidStateError" DOMException if responseType is not the empty string or "document". + */ + readonly responseXML: Document | null; + readonly status: number; + readonly statusText: string; + /** + * Can be set to a time in milliseconds. When set to a non-zero value will cause fetching to terminate after the given time has passed. When the time has passed, the + * request has not yet completed, and the synchronous flag is unset, a timeout event will then be dispatched, or a + * "TimeoutError" DOMException will be thrown otherwise (for the send() method). + * When set: throws an "InvalidAccessError" DOMException if the synchronous flag is set and current global object is a Window object. + */ + timeout: number; + /** + * Returns the associated XMLHttpRequestUpload object. It can be used to gather transmission information when data is + * transferred to a server. + */ + readonly upload: XMLHttpRequestUpload; + /** + * True when credentials are to be included in a cross-origin request. False when they are + * to be excluded in a cross-origin request and when cookies are to be ignored in its response. + * Initially false. + * When set: throws an "InvalidStateError" DOMException if state is not unsent or opened, or if the send() flag is set. + */ + withCredentials: boolean; + /** + * Cancels any network activity. + */ + abort(): void; + getAllResponseHeaders(): string; + getResponseHeader(name: string): string | null; + /** + * Sets the request method, request URL, and synchronous flag. + * Throws a "SyntaxError" DOMException if either method is not a + * valid HTTP method or url cannot be parsed. + * Throws a "SecurityError" DOMException if method is a + * case-insensitive match for `CONNECT`, `TRACE`, or `TRACK`. + * Throws an "InvalidAccessError" DOMException if async is false, current global object is a Window object, and the timeout attribute is not zero or the responseType attribute is not the empty string. + */ + open(method: string, url: string): void; + open(method: string, url: string, async: boolean, username?: string | null, password?: string | null): void; + /** + * Acts as if the `Content-Type` header value for response is mime. + * (It does not actually change the header though.) + * Throws an "InvalidStateError" DOMException if state is loading or done. + */ + overrideMimeType(mime: string): void; + /** + * Initiates the request. The optional argument provides the request body. The argument is ignored if request method is GET or HEAD. + * Throws an "InvalidStateError" DOMException if either state is not opened or the send() flag is set. + */ + send(body?: Document | BodyInit | null): void; + /** + * Combines a header in author request headers. + * Throws an "InvalidStateError" DOMException if either state is not opened or the send() flag is set. + * Throws a "SyntaxError" DOMException if name is not a header name + * or if value is not a header value. + */ + setRequestHeader(name: string, value: string): void; + readonly DONE: number; + readonly HEADERS_RECEIVED: number; + readonly LOADING: number; + readonly OPENED: number; + readonly UNSENT: number; + addEventListener(type: K, listener: (this: XMLHttpRequest, ev: XMLHttpRequestEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: XMLHttpRequest, ev: XMLHttpRequestEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var XMLHttpRequest: { + prototype: XMLHttpRequest; + new(): XMLHttpRequest; + readonly DONE: number; + readonly HEADERS_RECEIVED: number; + readonly LOADING: number; + readonly OPENED: number; + readonly UNSENT: number; +}; + +interface XMLHttpRequestEventTargetEventMap { + "abort": ProgressEvent; + "error": ProgressEvent; + "load": ProgressEvent; + "loadend": ProgressEvent; + "loadstart": ProgressEvent; + "progress": ProgressEvent; + "timeout": ProgressEvent; +} + +interface XMLHttpRequestEventTarget extends EventTarget { + onabort: ((this: XMLHttpRequest, ev: ProgressEvent) => any) | null; + onerror: ((this: XMLHttpRequest, ev: ProgressEvent) => any) | null; + onload: ((this: XMLHttpRequest, ev: ProgressEvent) => any) | null; + onloadend: ((this: XMLHttpRequest, ev: ProgressEvent) => any) | null; + onloadstart: ((this: XMLHttpRequest, ev: ProgressEvent) => any) | null; + onprogress: ((this: XMLHttpRequest, ev: ProgressEvent) => any) | null; + ontimeout: ((this: XMLHttpRequest, ev: ProgressEvent) => any) | null; + addEventListener(type: K, listener: (this: XMLHttpRequestEventTarget, ev: XMLHttpRequestEventTargetEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: XMLHttpRequestEventTarget, ev: XMLHttpRequestEventTargetEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var XMLHttpRequestEventTarget: { + prototype: XMLHttpRequestEventTarget; + new(): XMLHttpRequestEventTarget; +}; + +interface XMLHttpRequestUpload extends XMLHttpRequestEventTarget { + addEventListener(type: K, listener: (this: XMLHttpRequestUpload, ev: XMLHttpRequestEventTargetEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: XMLHttpRequestUpload, ev: XMLHttpRequestEventTargetEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var XMLHttpRequestUpload: { + prototype: XMLHttpRequestUpload; + new(): XMLHttpRequestUpload; +}; + +interface XMLSerializer { + serializeToString(root: Node): string; +} + +declare var XMLSerializer: { + prototype: XMLSerializer; + new(): XMLSerializer; +}; + +interface XPathEvaluator { + createExpression(expression: string, resolver: XPathNSResolver): XPathExpression; + createNSResolver(nodeResolver?: Node): XPathNSResolver; + evaluate(expression: string, contextNode: Node, resolver: XPathNSResolver | ((prefix: string) => string | null) | null, type: number, result: XPathResult | null): XPathResult; +} + +declare var XPathEvaluator: { + prototype: XPathEvaluator; + new(): XPathEvaluator; +}; + +interface XPathExpression { + evaluate(contextNode: Node, type: number, result: XPathResult | null): XPathResult; +} + +declare var XPathExpression: { + prototype: XPathExpression; + new(): XPathExpression; +}; + +interface XPathNSResolver { + lookupNamespaceURI(prefix: string): string | null; +} + +declare var XPathNSResolver: { + prototype: XPathNSResolver; + new(): XPathNSResolver; +}; + +interface XPathResult { + readonly booleanValue: boolean; + readonly invalidIteratorState: boolean; + readonly numberValue: number; + readonly resultType: number; + readonly singleNodeValue: Node; + readonly snapshotLength: number; + readonly stringValue: string; + iterateNext(): Node; + snapshotItem(index: number): Node; + readonly ANY_TYPE: number; + readonly ANY_UNORDERED_NODE_TYPE: number; + readonly BOOLEAN_TYPE: number; + readonly FIRST_ORDERED_NODE_TYPE: number; + readonly NUMBER_TYPE: number; + readonly ORDERED_NODE_ITERATOR_TYPE: number; + readonly ORDERED_NODE_SNAPSHOT_TYPE: number; + readonly STRING_TYPE: number; + readonly UNORDERED_NODE_ITERATOR_TYPE: number; + readonly UNORDERED_NODE_SNAPSHOT_TYPE: number; +} + +declare var XPathResult: { + prototype: XPathResult; + new(): XPathResult; + readonly ANY_TYPE: number; + readonly ANY_UNORDERED_NODE_TYPE: number; + readonly BOOLEAN_TYPE: number; + readonly FIRST_ORDERED_NODE_TYPE: number; + readonly NUMBER_TYPE: number; + readonly ORDERED_NODE_ITERATOR_TYPE: number; + readonly ORDERED_NODE_SNAPSHOT_TYPE: number; + readonly STRING_TYPE: number; + readonly UNORDERED_NODE_ITERATOR_TYPE: number; + readonly UNORDERED_NODE_SNAPSHOT_TYPE: number; +}; + +interface XSLTProcessor { + clearParameters(): void; + getParameter(namespaceURI: string, localName: string): any; + importStylesheet(style: Node): void; + removeParameter(namespaceURI: string, localName: string): void; + reset(): void; + setParameter(namespaceURI: string, localName: string, value: any): void; + transformToDocument(source: Node): Document; + transformToFragment(source: Node, document: Document): DocumentFragment; +} + +declare var XSLTProcessor: { + prototype: XSLTProcessor; + new(): XSLTProcessor; +}; + +interface webkitRTCPeerConnection extends RTCPeerConnection { + addEventListener(type: K, listener: (this: webkitRTCPeerConnection, ev: RTCPeerConnectionEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: webkitRTCPeerConnection, ev: RTCPeerConnectionEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var webkitRTCPeerConnection: { + prototype: webkitRTCPeerConnection; + new(configuration: RTCConfiguration): webkitRTCPeerConnection; +}; + +declare type EventListenerOrEventListenerObject = EventListener | EventListenerObject; + +interface BlobCallback { + (blob: Blob | null): void; +} + +interface DecodeErrorCallback { + (error: DOMException): void; +} + +interface DecodeSuccessCallback { + (decodedData: AudioBuffer): void; +} + +interface ErrorEventHandler { + (event: Event | string, source?: string, fileno?: number, columnNumber?: number, error?: Error): void; +} + +interface EventHandlerNonNull { + (event: Event): any; +} + +interface ForEachCallback { + (keyId: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null, status: MediaKeyStatus): void; +} + +interface FrameRequestCallback { + (time: number): void; +} + +interface FunctionStringCallback { + (data: string): void; +} + +interface IntersectionObserverCallback { + (entries: IntersectionObserverEntry[], observer: IntersectionObserver): void; +} + +interface MSLaunchUriCallback { + (): void; +} + +interface MutationCallback { + (mutations: MutationRecord[], observer: MutationObserver): void; +} + +interface NavigatorUserMediaErrorCallback { + (error: MediaStreamError): void; +} + +interface NavigatorUserMediaSuccessCallback { + (stream: MediaStream): void; +} + +interface NotificationPermissionCallback { + (permission: NotificationPermission): void; +} + +interface OnBeforeUnloadEventHandlerNonNull { + (event: Event): string | null; +} + +interface OnErrorEventHandlerNonNull { + (event: Event | string, source?: string, lineno?: number, colno?: number, error?: any): any; +} + +interface PerformanceObserverCallback { + (entries: PerformanceObserverEntryList, observer: PerformanceObserver): void; +} + +interface PositionCallback { + (position: Position): void; +} + +interface PositionErrorCallback { + (positionError: PositionError): void; +} + +interface QueuingStrategySizeCallback { + (chunk: T): number; +} + +interface RTCPeerConnectionErrorCallback { + (error: DOMException): void; +} + +interface RTCSessionDescriptionCallback { + (description: RTCSessionDescriptionInit): void; +} + +interface RTCStatsCallback { + (report: RTCStatsReport): void; +} + +interface ReadableByteStreamControllerCallback { + (controller: ReadableByteStreamController): void | PromiseLike; +} + +interface ReadableStreamDefaultControllerCallback { + (controller: ReadableStreamDefaultController): void | PromiseLike; +} + +interface ReadableStreamErrorCallback { + (reason: any): void | PromiseLike; +} + +interface TransformStreamDefaultControllerCallback { + (controller: TransformStreamDefaultController): void | PromiseLike; +} + +interface TransformStreamDefaultControllerTransformCallback { + (chunk: I, controller: TransformStreamDefaultController): void | PromiseLike; +} + +interface VoidFunction { + (): void; +} + +interface WritableStreamDefaultControllerCloseCallback { + (): void | PromiseLike; +} + +interface WritableStreamDefaultControllerStartCallback { + (controller: WritableStreamDefaultController): void | PromiseLike; +} + +interface WritableStreamDefaultControllerWriteCallback { + (chunk: W, controller: WritableStreamDefaultController): void | PromiseLike; +} + +interface WritableStreamErrorCallback { + (reason: any): void | PromiseLike; +} + +interface HTMLElementTagNameMap { + "a": HTMLAnchorElement; + "abbr": HTMLElement; + "address": HTMLElement; + "applet": HTMLAppletElement; + "area": HTMLAreaElement; + "article": HTMLElement; + "aside": HTMLElement; + "audio": HTMLAudioElement; + "b": HTMLElement; + "base": HTMLBaseElement; + "basefont": HTMLBaseFontElement; + "bdo": HTMLElement; + "blockquote": HTMLQuoteElement; + "body": HTMLBodyElement; + "br": HTMLBRElement; + "button": HTMLButtonElement; + "canvas": HTMLCanvasElement; + "caption": HTMLTableCaptionElement; + "cite": HTMLElement; + "code": HTMLElement; + "col": HTMLTableColElement; + "colgroup": HTMLTableColElement; + "data": HTMLDataElement; + "datalist": HTMLDataListElement; + "dd": HTMLElement; + "del": HTMLModElement; + "details": HTMLDetailsElement; + "dfn": HTMLElement; + "dialog": HTMLDialogElement; + "dir": HTMLDirectoryElement; + "div": HTMLDivElement; + "dl": HTMLDListElement; + "dt": HTMLElement; + "em": HTMLElement; + "embed": HTMLEmbedElement; + "fieldset": HTMLFieldSetElement; + "figcaption": HTMLElement; + "figure": HTMLElement; + "font": HTMLFontElement; + "footer": HTMLElement; + "form": HTMLFormElement; + "frame": HTMLFrameElement; + "frameset": HTMLFrameSetElement; + "h1": HTMLHeadingElement; + "h2": HTMLHeadingElement; + "h3": HTMLHeadingElement; + "h4": HTMLHeadingElement; + "h5": HTMLHeadingElement; + "h6": HTMLHeadingElement; + "head": HTMLHeadElement; + "header": HTMLElement; + "hgroup": HTMLElement; + "hr": HTMLHRElement; + "html": HTMLHtmlElement; + "i": HTMLElement; + "iframe": HTMLIFrameElement; + "img": HTMLImageElement; + "input": HTMLInputElement; + "ins": HTMLModElement; + "kbd": HTMLElement; + "label": HTMLLabelElement; + "legend": HTMLLegendElement; + "li": HTMLLIElement; + "link": HTMLLinkElement; + "map": HTMLMapElement; + "mark": HTMLElement; + "marquee": HTMLMarqueeElement; + "menu": HTMLMenuElement; + "meta": HTMLMetaElement; + "meter": HTMLMeterElement; + "nav": HTMLElement; + "noscript": HTMLElement; + "object": HTMLObjectElement; + "ol": HTMLOListElement; + "optgroup": HTMLOptGroupElement; + "option": HTMLOptionElement; + "output": HTMLOutputElement; + "p": HTMLParagraphElement; + "param": HTMLParamElement; + "picture": HTMLPictureElement; + "pre": HTMLPreElement; + "progress": HTMLProgressElement; + "q": HTMLQuoteElement; + "rt": HTMLElement; + "ruby": HTMLElement; + "s": HTMLElement; + "samp": HTMLElement; + "script": HTMLScriptElement; + "section": HTMLElement; + "select": HTMLSelectElement; + "slot": HTMLSlotElement; + "small": HTMLElement; + "source": HTMLSourceElement; + "span": HTMLSpanElement; + "strong": HTMLElement; + "style": HTMLStyleElement; + "sub": HTMLElement; + "sup": HTMLElement; + "table": HTMLTableElement; + "tbody": HTMLTableSectionElement; + "td": HTMLTableDataCellElement; + "template": HTMLTemplateElement; + "textarea": HTMLTextAreaElement; + "tfoot": HTMLTableSectionElement; + "th": HTMLTableHeaderCellElement; + "thead": HTMLTableSectionElement; + "time": HTMLTimeElement; + "title": HTMLTitleElement; + "tr": HTMLTableRowElement; + "track": HTMLTrackElement; + "u": HTMLElement; + "ul": HTMLUListElement; + "var": HTMLElement; + "video": HTMLVideoElement; + "wbr": HTMLElement; +} + +interface HTMLElementDeprecatedTagNameMap { + "listing": HTMLPreElement; + "xmp": HTMLPreElement; +} + +interface SVGElementTagNameMap { + "circle": SVGCircleElement; + "clipPath": SVGClipPathElement; + "defs": SVGDefsElement; + "desc": SVGDescElement; + "ellipse": SVGEllipseElement; + "feBlend": SVGFEBlendElement; + "feColorMatrix": SVGFEColorMatrixElement; + "feComponentTransfer": SVGFEComponentTransferElement; + "feComposite": SVGFECompositeElement; + "feConvolveMatrix": SVGFEConvolveMatrixElement; + "feDiffuseLighting": SVGFEDiffuseLightingElement; + "feDisplacementMap": SVGFEDisplacementMapElement; + "feDistantLight": SVGFEDistantLightElement; + "feFlood": SVGFEFloodElement; + "feFuncA": SVGFEFuncAElement; + "feFuncB": SVGFEFuncBElement; + "feFuncG": SVGFEFuncGElement; + "feFuncR": SVGFEFuncRElement; + "feGaussianBlur": SVGFEGaussianBlurElement; + "feImage": SVGFEImageElement; + "feMerge": SVGFEMergeElement; + "feMergeNode": SVGFEMergeNodeElement; + "feMorphology": SVGFEMorphologyElement; + "feOffset": SVGFEOffsetElement; + "fePointLight": SVGFEPointLightElement; + "feSpecularLighting": SVGFESpecularLightingElement; + "feSpotLight": SVGFESpotLightElement; + "feTile": SVGFETileElement; + "feTurbulence": SVGFETurbulenceElement; + "filter": SVGFilterElement; + "foreignObject": SVGForeignObjectElement; + "g": SVGGElement; + "image": SVGImageElement; + "line": SVGLineElement; + "linearGradient": SVGLinearGradientElement; + "marker": SVGMarkerElement; + "mask": SVGMaskElement; + "metadata": SVGMetadataElement; + "path": SVGPathElement; + "pattern": SVGPatternElement; + "polygon": SVGPolygonElement; + "polyline": SVGPolylineElement; + "radialGradient": SVGRadialGradientElement; + "rect": SVGRectElement; + "stop": SVGStopElement; + "svg": SVGSVGElement; + "switch": SVGSwitchElement; + "symbol": SVGSymbolElement; + "text": SVGTextElement; + "textPath": SVGTextPathElement; + "tspan": SVGTSpanElement; + "use": SVGUseElement; + "view": SVGViewElement; +} + +/** @deprecated Directly use HTMLElementTagNameMap or SVGElementTagNameMap as appropriate, instead. */ +interface ElementTagNameMap extends HTMLElementTagNameMap, SVGElementTagNameMap { } + +declare var Audio: { + new(src?: string): HTMLAudioElement; +}; +declare var Image: { + new(width?: number, height?: number): HTMLImageElement; +}; +declare var Option: { + new(text?: string, value?: string, defaultSelected?: boolean, selected?: boolean): HTMLOptionElement; +}; +declare var Blob: typeof Blob; +declare var URL: typeof URL; +declare var URLSearchParams: typeof URLSearchParams; +declare var applicationCache: ApplicationCache; +declare var caches: CacheStorage; +declare var clientInformation: Navigator; +declare var closed: boolean; +declare var crypto: Crypto; +declare var customElements: CustomElementRegistry; +declare var defaultStatus: string; +declare var devicePixelRatio: number; +declare var doNotTrack: string; +declare var document: Document; +declare var event: Event | undefined; +/** @deprecated */ +declare var external: External; +declare var frameElement: Element; +declare var frames: Window; +declare var history: History; +declare var innerHeight: number; +declare var innerWidth: number; +declare var isSecureContext: boolean; +declare var length: number; +declare var location: Location; +declare var locationbar: BarProp; +declare var menubar: BarProp; +declare var msContentScript: ExtensionScriptApis; +declare const name: never; +declare var navigator: Navigator; +declare var offscreenBuffering: string | boolean; +declare var oncompassneedscalibration: ((this: Window, ev: Event) => any) | null; +declare var ondevicelight: ((this: Window, ev: DeviceLightEvent) => any) | null; +declare var ondevicemotion: ((this: Window, ev: DeviceMotionEvent) => any) | null; +declare var ondeviceorientation: ((this: Window, ev: DeviceOrientationEvent) => any) | null; +declare var onmousewheel: ((this: Window, ev: Event) => any) | null; +declare var onmsgesturechange: ((this: Window, ev: Event) => any) | null; +declare var onmsgesturedoubletap: ((this: Window, ev: Event) => any) | null; +declare var onmsgestureend: ((this: Window, ev: Event) => any) | null; +declare var onmsgesturehold: ((this: Window, ev: Event) => any) | null; +declare var onmsgesturestart: ((this: Window, ev: Event) => any) | null; +declare var onmsgesturetap: ((this: Window, ev: Event) => any) | null; +declare var onmsinertiastart: ((this: Window, ev: Event) => any) | null; +declare var onmspointercancel: ((this: Window, ev: Event) => any) | null; +declare var onmspointerdown: ((this: Window, ev: Event) => any) | null; +declare var onmspointerenter: ((this: Window, ev: Event) => any) | null; +declare var onmspointerleave: ((this: Window, ev: Event) => any) | null; +declare var onmspointermove: ((this: Window, ev: Event) => any) | null; +declare var onmspointerout: ((this: Window, ev: Event) => any) | null; +declare var onmspointerover: ((this: Window, ev: Event) => any) | null; +declare var onmspointerup: ((this: Window, ev: Event) => any) | null; +/** @deprecated */ +declare var onorientationchange: ((this: Window, ev: Event) => any) | null; +declare var onreadystatechange: ((this: Window, ev: ProgressEvent) => any) | null; +declare var onvrdisplayactivate: ((this: Window, ev: Event) => any) | null; +declare var onvrdisplayblur: ((this: Window, ev: Event) => any) | null; +declare var onvrdisplayconnect: ((this: Window, ev: Event) => any) | null; +declare var onvrdisplaydeactivate: ((this: Window, ev: Event) => any) | null; +declare var onvrdisplaydisconnect: ((this: Window, ev: Event) => any) | null; +declare var onvrdisplayfocus: ((this: Window, ev: Event) => any) | null; +declare var onvrdisplaypointerrestricted: ((this: Window, ev: Event) => any) | null; +declare var onvrdisplaypointerunrestricted: ((this: Window, ev: Event) => any) | null; +declare var onvrdisplaypresentchange: ((this: Window, ev: Event) => any) | null; +declare var opener: any; +/** @deprecated */ +declare var orientation: string | number; +declare var outerHeight: number; +declare var outerWidth: number; +declare var pageXOffset: number; +declare var pageYOffset: number; +declare var parent: Window; +declare var performance: Performance; +declare var personalbar: BarProp; +declare var screen: Screen; +declare var screenLeft: number; +declare var screenTop: number; +declare var screenX: number; +declare var screenY: number; +declare var scrollX: number; +declare var scrollY: number; +declare var scrollbars: BarProp; +declare var self: Window; +declare var speechSynthesis: SpeechSynthesis; +declare var status: string; +declare var statusbar: BarProp; +declare var styleMedia: StyleMedia; +declare var toolbar: BarProp; +declare var top: Window; +declare var window: Window; +declare function alert(message?: any): void; +declare function blur(): void; +declare function cancelAnimationFrame(handle: number): void; +/** @deprecated */ +declare function captureEvents(): void; +declare function close(): void; +declare function confirm(message?: string): boolean; +declare function departFocus(navigationReason: NavigationReason, origin: FocusNavigationOrigin): void; +declare function focus(): void; +declare function getComputedStyle(elt: Element, pseudoElt?: string | null): CSSStyleDeclaration; +declare function getMatchedCSSRules(elt: Element, pseudoElt?: string | null): CSSRuleList; +declare function getSelection(): Selection; +declare function matchMedia(query: string): MediaQueryList; +declare function moveBy(x: number, y: number): void; +declare function moveTo(x: number, y: number): void; +declare function msWriteProfilerMark(profilerMarkName: string): void; +declare function open(url?: string, target?: string, features?: string, replace?: boolean): Window | null; +declare function postMessage(message: any, targetOrigin: string, transfer?: Transferable[]): void; +declare function print(): void; +declare function prompt(message?: string, _default?: string): string | null; +/** @deprecated */ +declare function releaseEvents(): void; +declare function requestAnimationFrame(callback: FrameRequestCallback): number; +declare function resizeBy(x: number, y: number): void; +declare function resizeTo(x: number, y: number): void; +declare function scroll(options?: ScrollToOptions): void; +declare function scroll(x: number, y: number): void; +declare function scrollBy(options?: ScrollToOptions): void; +declare function scrollBy(x: number, y: number): void; +declare function scrollTo(options?: ScrollToOptions): void; +declare function scrollTo(x: number, y: number): void; +declare function stop(): void; +declare function webkitCancelAnimationFrame(handle: number): void; +declare function webkitConvertPointFromNodeToPage(node: Node, pt: WebKitPoint): WebKitPoint; +declare function webkitConvertPointFromPageToNode(node: Node, pt: WebKitPoint): WebKitPoint; +declare function webkitRequestAnimationFrame(callback: FrameRequestCallback): number; +declare function toString(): string; +/** + * Dispatches a synthetic event event to target and returns true + * if either event's cancelable attribute value is false or its preventDefault() method was not invoked, and false otherwise. + */ +declare function dispatchEvent(event: Event): boolean; +declare var sessionStorage: Storage; +declare var localStorage: Storage; +declare var console: Console; +/** + * Fires when the user aborts the download. + * @param ev The event. + */ +declare var onabort: ((this: Window, ev: UIEvent) => any) | null; +declare var onanimationcancel: ((this: Window, ev: AnimationEvent) => any) | null; +declare var onanimationend: ((this: Window, ev: AnimationEvent) => any) | null; +declare var onanimationiteration: ((this: Window, ev: AnimationEvent) => any) | null; +declare var onanimationstart: ((this: Window, ev: AnimationEvent) => any) | null; +declare var onauxclick: ((this: Window, ev: Event) => any) | null; +/** + * Fires when the object loses the input focus. + * @param ev The focus event. + */ +declare var onblur: ((this: Window, ev: FocusEvent) => any) | null; +declare var oncancel: ((this: Window, ev: Event) => any) | null; +/** + * Occurs when playback is possible, but would require further buffering. + * @param ev The event. + */ +declare var oncanplay: ((this: Window, ev: Event) => any) | null; +declare var oncanplaythrough: ((this: Window, ev: Event) => any) | null; +/** + * Fires when the contents of the object or selection have changed. + * @param ev The event. + */ +declare var onchange: ((this: Window, ev: Event) => any) | null; +/** + * Fires when the user clicks the left mouse button on the object + * @param ev The mouse event. + */ +declare var onclick: ((this: Window, ev: MouseEvent) => any) | null; +declare var onclose: ((this: Window, ev: Event) => any) | null; +/** + * Fires when the user clicks the right mouse button in the client area, opening the context menu. + * @param ev The mouse event. + */ +declare var oncontextmenu: ((this: Window, ev: MouseEvent) => any) | null; +declare var oncuechange: ((this: Window, ev: Event) => any) | null; +/** + * Fires when the user double-clicks the object. + * @param ev The mouse event. + */ +declare var ondblclick: ((this: Window, ev: MouseEvent) => any) | null; +/** + * Fires on the source object continuously during a drag operation. + * @param ev The event. + */ +declare var ondrag: ((this: Window, ev: DragEvent) => any) | null; +/** + * Fires on the source object when the user releases the mouse at the close of a drag operation. + * @param ev The event. + */ +declare var ondragend: ((this: Window, ev: DragEvent) => any) | null; +/** + * Fires on the target element when the user drags the object to a valid drop target. + * @param ev The drag event. + */ +declare var ondragenter: ((this: Window, ev: DragEvent) => any) | null; +declare var ondragexit: ((this: Window, ev: Event) => any) | null; +/** + * Fires on the target object when the user moves the mouse out of a valid drop target during a drag operation. + * @param ev The drag event. + */ +declare var ondragleave: ((this: Window, ev: DragEvent) => any) | null; +/** + * Fires on the target element continuously while the user drags the object over a valid drop target. + * @param ev The event. + */ +declare var ondragover: ((this: Window, ev: DragEvent) => any) | null; +/** + * Fires on the source object when the user starts to drag a text selection or selected object. + * @param ev The event. + */ +declare var ondragstart: ((this: Window, ev: DragEvent) => any) | null; +declare var ondrop: ((this: Window, ev: DragEvent) => any) | null; +/** + * Occurs when the duration attribute is updated. + * @param ev The event. + */ +declare var ondurationchange: ((this: Window, ev: Event) => any) | null; +/** + * Occurs when the media element is reset to its initial state. + * @param ev The event. + */ +declare var onemptied: ((this: Window, ev: Event) => any) | null; +/** + * Occurs when the end of playback is reached. + * @param ev The event + */ +declare var onended: ((this: Window, ev: Event) => any) | null; +/** + * Fires when an error occurs during object loading. + * @param ev The event. + */ +declare var onerror: ErrorEventHandler; +/** + * Fires when the object receives focus. + * @param ev The event. + */ +declare var onfocus: ((this: Window, ev: FocusEvent) => any) | null; +declare var ongotpointercapture: ((this: Window, ev: PointerEvent) => any) | null; +declare var oninput: ((this: Window, ev: Event) => any) | null; +declare var oninvalid: ((this: Window, ev: Event) => any) | null; +/** + * Fires when the user presses a key. + * @param ev The keyboard event + */ +declare var onkeydown: ((this: Window, ev: KeyboardEvent) => any) | null; +/** + * Fires when the user presses an alphanumeric key. + * @param ev The event. + */ +declare var onkeypress: ((this: Window, ev: KeyboardEvent) => any) | null; +/** + * Fires when the user releases a key. + * @param ev The keyboard event + */ +declare var onkeyup: ((this: Window, ev: KeyboardEvent) => any) | null; +/** + * Fires immediately after the browser loads the object. + * @param ev The event. + */ +declare var onload: ((this: Window, ev: Event) => any) | null; +/** + * Occurs when media data is loaded at the current playback position. + * @param ev The event. + */ +declare var onloadeddata: ((this: Window, ev: Event) => any) | null; +/** + * Occurs when the duration and dimensions of the media have been determined. + * @param ev The event. + */ +declare var onloadedmetadata: ((this: Window, ev: Event) => any) | null; +declare var onloadend: ((this: Window, ev: ProgressEvent) => any) | null; +/** + * Occurs when Internet Explorer begins looking for media data. + * @param ev The event. + */ +declare var onloadstart: ((this: Window, ev: Event) => any) | null; +declare var onlostpointercapture: ((this: Window, ev: PointerEvent) => any) | null; +/** + * Fires when the user clicks the object with either mouse button. + * @param ev The mouse event. + */ +declare var onmousedown: ((this: Window, ev: MouseEvent) => any) | null; +declare var onmouseenter: ((this: Window, ev: MouseEvent) => any) | null; +declare var onmouseleave: ((this: Window, ev: MouseEvent) => any) | null; +/** + * Fires when the user moves the mouse over the object. + * @param ev The mouse event. + */ +declare var onmousemove: ((this: Window, ev: MouseEvent) => any) | null; +/** + * Fires when the user moves the mouse pointer outside the boundaries of the object. + * @param ev The mouse event. + */ +declare var onmouseout: ((this: Window, ev: MouseEvent) => any) | null; +/** + * Fires when the user moves the mouse pointer into the object. + * @param ev The mouse event. + */ +declare var onmouseover: ((this: Window, ev: MouseEvent) => any) | null; +/** + * Fires when the user releases a mouse button while the mouse is over the object. + * @param ev The mouse event. + */ +declare var onmouseup: ((this: Window, ev: MouseEvent) => any) | null; +/** + * Occurs when playback is paused. + * @param ev The event. + */ +declare var onpause: ((this: Window, ev: Event) => any) | null; +/** + * Occurs when the play method is requested. + * @param ev The event. + */ +declare var onplay: ((this: Window, ev: Event) => any) | null; +/** + * Occurs when the audio or video has started playing. + * @param ev The event. + */ +declare var onplaying: ((this: Window, ev: Event) => any) | null; +declare var onpointercancel: ((this: Window, ev: PointerEvent) => any) | null; +declare var onpointerdown: ((this: Window, ev: PointerEvent) => any) | null; +declare var onpointerenter: ((this: Window, ev: PointerEvent) => any) | null; +declare var onpointerleave: ((this: Window, ev: PointerEvent) => any) | null; +declare var onpointermove: ((this: Window, ev: PointerEvent) => any) | null; +declare var onpointerout: ((this: Window, ev: PointerEvent) => any) | null; +declare var onpointerover: ((this: Window, ev: PointerEvent) => any) | null; +declare var onpointerup: ((this: Window, ev: PointerEvent) => any) | null; +/** + * Occurs to indicate progress while downloading media data. + * @param ev The event. + */ +declare var onprogress: ((this: Window, ev: ProgressEvent) => any) | null; +/** + * Occurs when the playback rate is increased or decreased. + * @param ev The event. + */ +declare var onratechange: ((this: Window, ev: Event) => any) | null; +/** + * Fires when the user resets a form. + * @param ev The event. + */ +declare var onreset: ((this: Window, ev: Event) => any) | null; +declare var onresize: ((this: Window, ev: UIEvent) => any) | null; +/** + * Fires when the user repositions the scroll box in the scroll bar on the object. + * @param ev The event. + */ +declare var onscroll: ((this: Window, ev: UIEvent) => any) | null; +declare var onsecuritypolicyviolation: ((this: Window, ev: SecurityPolicyViolationEvent) => any) | null; +/** + * Occurs when the seek operation ends. + * @param ev The event. + */ +declare var onseeked: ((this: Window, ev: Event) => any) | null; +/** + * Occurs when the current playback position is moved. + * @param ev The event. + */ +declare var onseeking: ((this: Window, ev: Event) => any) | null; +/** + * Fires when the current selection changes. + * @param ev The event. + */ +declare var onselect: ((this: Window, ev: UIEvent) => any) | null; +/** + * Occurs when the download has stopped. + * @param ev The event. + */ +declare var onstalled: ((this: Window, ev: Event) => any) | null; +declare var onsubmit: ((this: Window, ev: Event) => any) | null; +/** + * Occurs if the load operation has been intentionally halted. + * @param ev The event. + */ +declare var onsuspend: ((this: Window, ev: Event) => any) | null; +/** + * Occurs to indicate the current playback position. + * @param ev The event. + */ +declare var ontimeupdate: ((this: Window, ev: Event) => any) | null; +declare var ontoggle: ((this: Window, ev: Event) => any) | null; +declare var ontouchcancel: ((this: Window, ev: TouchEvent) => any) | null; +declare var ontouchend: ((this: Window, ev: TouchEvent) => any) | null; +declare var ontouchmove: ((this: Window, ev: TouchEvent) => any) | null; +declare var ontouchstart: ((this: Window, ev: TouchEvent) => any) | null; +declare var ontransitioncancel: ((this: Window, ev: TransitionEvent) => any) | null; +declare var ontransitionend: ((this: Window, ev: TransitionEvent) => any) | null; +declare var ontransitionrun: ((this: Window, ev: TransitionEvent) => any) | null; +declare var ontransitionstart: ((this: Window, ev: TransitionEvent) => any) | null; +/** + * Occurs when the volume is changed, or playback is muted or unmuted. + * @param ev The event. + */ +declare var onvolumechange: ((this: Window, ev: Event) => any) | null; +/** + * Occurs when playback stops because the next frame of a video resource is not available. + * @param ev The event. + */ +declare var onwaiting: ((this: Window, ev: Event) => any) | null; +declare var onwheel: ((this: Window, ev: WheelEvent) => any) | null; +declare var indexedDB: IDBFactory; +declare function atob(encodedString: string): string; +declare function btoa(rawString: string): string; +declare function fetch(input: RequestInfo, init?: RequestInit): Promise; +declare var caches: CacheStorage; +declare var crypto: Crypto; +declare var indexedDB: IDBFactory; +declare var origin: string; +declare var performance: Performance; +declare function atob(data: string): string; +declare function btoa(data: string): string; +declare function clearInterval(handle?: number): void; +declare function clearTimeout(handle?: number): void; +declare function createImageBitmap(image: ImageBitmapSource): Promise; +declare function createImageBitmap(image: ImageBitmapSource, sx: number, sy: number, sw: number, sh: number): Promise; +declare function fetch(input: RequestInfo, init?: RequestInit): Promise; +declare function queueMicrotask(callback: Function): void; +declare function setInterval(handler: TimerHandler, timeout?: number, ...arguments: any[]): number; +declare function setTimeout(handler: TimerHandler, timeout?: number, ...arguments: any[]): number; +declare var sessionStorage: Storage; +declare var localStorage: Storage; +declare var onafterprint: ((this: Window, ev: Event) => any) | null; +declare var onbeforeprint: ((this: Window, ev: Event) => any) | null; +declare var onbeforeunload: ((this: Window, ev: BeforeUnloadEvent) => any) | null; +declare var onhashchange: ((this: Window, ev: HashChangeEvent) => any) | null; +declare var onlanguagechange: ((this: Window, ev: Event) => any) | null; +declare var onmessage: ((this: Window, ev: MessageEvent) => any) | null; +declare var onmessageerror: ((this: Window, ev: MessageEvent) => any) | null; +declare var onoffline: ((this: Window, ev: Event) => any) | null; +declare var ononline: ((this: Window, ev: Event) => any) | null; +declare var onpagehide: ((this: Window, ev: PageTransitionEvent) => any) | null; +declare var onpageshow: ((this: Window, ev: PageTransitionEvent) => any) | null; +declare var onpopstate: ((this: Window, ev: PopStateEvent) => any) | null; +declare var onrejectionhandled: ((this: Window, ev: Event) => any) | null; +declare var onstorage: ((this: Window, ev: StorageEvent) => any) | null; +declare var onunhandledrejection: ((this: Window, ev: PromiseRejectionEvent) => any) | null; +declare var onunload: ((this: Window, ev: Event) => any) | null; +declare function addEventListener(type: K, listener: (this: Window, ev: WindowEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; +declare function addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; +declare function removeEventListener(type: K, listener: (this: Window, ev: WindowEventMap[K]) => any, options?: boolean | EventListenerOptions): void; +declare function removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +type BlobPart = BufferSource | Blob | string; +type HeadersInit = Headers | string[][] | Record; +type BodyInit = Blob | BufferSource | FormData | URLSearchParams | ReadableStream | string; +type RequestInfo = Request | string; +type DOMHighResTimeStamp = number; +type RenderingContext = CanvasRenderingContext2D | ImageBitmapRenderingContext | WebGLRenderingContext; +type HTMLOrSVGImageElement = HTMLImageElement | SVGImageElement; +type CanvasImageSource = HTMLOrSVGImageElement | HTMLVideoElement | HTMLCanvasElement | ImageBitmap; +type MessageEventSource = WindowProxy | MessagePort | ServiceWorker; +type HTMLOrSVGScriptElement = HTMLScriptElement | SVGScriptElement; +type ImageBitmapSource = CanvasImageSource | Blob | ImageData; +type OnErrorEventHandler = OnErrorEventHandlerNonNull | null; +type OnBeforeUnloadEventHandler = OnBeforeUnloadEventHandlerNonNull | null; +type TimerHandler = string | Function; +type PerformanceEntryList = PerformanceEntry[]; +type VibratePattern = number | number[]; +type AlgorithmIdentifier = string | Algorithm; +type HashAlgorithmIdentifier = AlgorithmIdentifier; +type BigInteger = Uint8Array; +type NamedCurve = string; +type GLenum = number; +type GLboolean = boolean; +type GLbitfield = number; +type GLint = number; +type GLsizei = number; +type GLintptr = number; +type GLsizeiptr = number; +type GLuint = number; +type GLfloat = number; +type GLclampf = number; +type TexImageSource = ImageBitmap | ImageData | HTMLImageElement | HTMLCanvasElement | HTMLVideoElement; +type Float32List = Float32Array | GLfloat[]; +type Int32List = Int32Array | GLint[]; +type BufferSource = ArrayBufferView | ArrayBuffer; +type DOMTimeStamp = number; +type LineAndPositionSetting = number | AutoKeyword; +type FormDataEntryValue = File | string; +type InsertPosition = "beforebegin" | "afterbegin" | "beforeend" | "afterend"; +type IDBValidKey = number | string | Date | BufferSource | IDBArrayKey; +type MutationRecordType = "attributes" | "characterData" | "childList"; +type ConstrainBoolean = boolean | ConstrainBooleanParameters; +type ConstrainDOMString = string | string[] | ConstrainDOMStringParameters; +type ConstrainDouble = number | ConstrainDoubleRange; +type ConstrainLong = number | ConstrainLongRange; +type IDBKeyPath = string; +type Transferable = ArrayBuffer | MessagePort | ImageBitmap; +type RTCIceGatherCandidate = RTCIceCandidateDictionary | RTCIceCandidateComplete; +type RTCTransport = RTCDtlsTransport | RTCSrtpSdesTransport; +/** @deprecated */ +type MouseWheelEvent = WheelEvent; +type WindowProxy = Window; +type AlignSetting = "start" | "center" | "end" | "left" | "right"; +type AnimationPlayState = "idle" | "running" | "paused" | "finished"; +type AppendMode = "segments" | "sequence"; +type AudioContextLatencyCategory = "balanced" | "interactive" | "playback"; +type AudioContextState = "suspended" | "running" | "closed"; +type AutoKeyword = "auto"; +type AutomationRate = "a-rate" | "k-rate"; +type BinaryType = "blob" | "arraybuffer"; +type BiquadFilterType = "lowpass" | "highpass" | "bandpass" | "lowshelf" | "highshelf" | "peaking" | "notch" | "allpass"; +type CanPlayTypeResult = "" | "maybe" | "probably"; +type CanvasDirection = "ltr" | "rtl" | "inherit"; +type CanvasFillRule = "nonzero" | "evenodd"; +type CanvasLineCap = "butt" | "round" | "square"; +type CanvasLineJoin = "round" | "bevel" | "miter"; +type CanvasTextAlign = "start" | "end" | "left" | "right" | "center"; +type CanvasTextBaseline = "top" | "hanging" | "middle" | "alphabetic" | "ideographic" | "bottom"; +type ChannelCountMode = "max" | "clamped-max" | "explicit"; +type ChannelInterpretation = "speakers" | "discrete"; +type ClientTypes = "window" | "worker" | "sharedworker" | "all"; +type CompositeOperation = "replace" | "add" | "accumulate"; +type CompositeOperationOrAuto = "replace" | "add" | "accumulate" | "auto"; +type DirectionSetting = "" | "rl" | "lr"; +type DisplayCaptureSurfaceType = "monitor" | "window" | "application" | "browser"; +type DistanceModelType = "linear" | "inverse" | "exponential"; +type DocumentReadyState = "loading" | "interactive" | "complete"; +type EndOfStreamError = "network" | "decode"; +type EndingType = "transparent" | "native"; +type FillMode = "none" | "forwards" | "backwards" | "both" | "auto"; +type GamepadHand = "" | "left" | "right"; +type GamepadHapticActuatorType = "vibration"; +type GamepadInputEmulationType = "mouse" | "keyboard" | "gamepad"; +type GamepadMappingType = "" | "standard"; +type IDBCursorDirection = "next" | "nextunique" | "prev" | "prevunique"; +type IDBRequestReadyState = "pending" | "done"; +type IDBTransactionMode = "readonly" | "readwrite" | "versionchange"; +type ImageSmoothingQuality = "low" | "medium" | "high"; +type IterationCompositeOperation = "replace" | "accumulate"; +type KeyFormat = "raw" | "spki" | "pkcs8" | "jwk"; +type KeyType = "public" | "private" | "secret"; +type KeyUsage = "encrypt" | "decrypt" | "sign" | "verify" | "deriveKey" | "deriveBits" | "wrapKey" | "unwrapKey"; +type LineAlignSetting = "start" | "center" | "end"; +type ListeningState = "inactive" | "active" | "disambiguation"; +type MSCredentialType = "FIDO_2_0"; +type MSTransportType = "Embedded" | "USB" | "NFC" | "BT"; +type MSWebViewPermissionState = "unknown" | "defer" | "allow" | "deny"; +type MSWebViewPermissionType = "geolocation" | "unlimitedIndexedDBQuota" | "media" | "pointerlock" | "webnotifications"; +type MediaDeviceKind = "audioinput" | "audiooutput" | "videoinput"; +type MediaKeyMessageType = "license-request" | "license-renewal" | "license-release" | "individualization-request"; +type MediaKeySessionType = "temporary" | "persistent-license" | "persistent-release-message"; +type MediaKeyStatus = "usable" | "expired" | "output-downscaled" | "output-not-allowed" | "status-pending" | "internal-error"; +type MediaKeysRequirement = "required" | "optional" | "not-allowed"; +type MediaStreamTrackState = "live" | "ended"; +type NavigationReason = "up" | "down" | "left" | "right"; +type NavigationType = "navigate" | "reload" | "back_forward" | "prerender"; +type NotificationDirection = "auto" | "ltr" | "rtl"; +type NotificationPermission = "default" | "denied" | "granted"; +type OrientationLockType = "any" | "natural" | "landscape" | "portrait" | "portrait-primary" | "portrait-secondary" | "landscape-primary" | "landscape-secondary"; +type OrientationType = "portrait-primary" | "portrait-secondary" | "landscape-primary" | "landscape-secondary"; +type OscillatorType = "sine" | "square" | "sawtooth" | "triangle" | "custom"; +type OverSampleType = "none" | "2x" | "4x"; +type PanningModelType = "equalpower" | "HRTF"; +type PaymentComplete = "success" | "fail" | "unknown"; +type PaymentShippingType = "shipping" | "delivery" | "pickup"; +type PlaybackDirection = "normal" | "reverse" | "alternate" | "alternate-reverse"; +type PositionAlignSetting = "line-left" | "center" | "line-right" | "auto"; +type PushEncryptionKeyName = "p256dh" | "auth"; +type PushPermissionState = "denied" | "granted" | "prompt"; +type RTCBundlePolicy = "balanced" | "max-compat" | "max-bundle"; +type RTCDataChannelState = "connecting" | "open" | "closing" | "closed"; +type RTCDegradationPreference = "maintain-framerate" | "maintain-resolution" | "balanced"; +type RTCDtlsRole = "auto" | "client" | "server"; +type RTCDtlsTransportState = "new" | "connecting" | "connected" | "closed" | "failed"; +type RTCDtxStatus = "disabled" | "enabled"; +type RTCErrorDetailType = "data-channel-failure" | "dtls-failure" | "fingerprint-failure" | "idp-bad-script-failure" | "idp-execution-failure" | "idp-load-failure" | "idp-need-login" | "idp-timeout" | "idp-tls-failure" | "idp-token-expired" | "idp-token-invalid" | "sctp-failure" | "sdp-syntax-error" | "hardware-encoder-not-available" | "hardware-encoder-error"; +type RTCIceCandidateType = "host" | "srflx" | "prflx" | "relay"; +type RTCIceComponent = "rtp" | "rtcp"; +type RTCIceConnectionState = "new" | "checking" | "connected" | "completed" | "disconnected" | "failed" | "closed"; +type RTCIceCredentialType = "password" | "oauth"; +type RTCIceGatherPolicy = "all" | "nohost" | "relay"; +type RTCIceGathererState = "new" | "gathering" | "complete"; +type RTCIceGatheringState = "new" | "gathering" | "complete"; +type RTCIceProtocol = "udp" | "tcp"; +type RTCIceRole = "controlling" | "controlled"; +type RTCIceTcpCandidateType = "active" | "passive" | "so"; +type RTCIceTransportPolicy = "relay" | "all"; +type RTCIceTransportState = "new" | "checking" | "connected" | "completed" | "disconnected" | "failed" | "closed"; +type RTCPeerConnectionState = "new" | "connecting" | "connected" | "disconnected" | "failed" | "closed"; +type RTCPriorityType = "very-low" | "low" | "medium" | "high"; +type RTCRtcpMuxPolicy = "negotiate" | "require"; +type RTCRtpTransceiverDirection = "sendrecv" | "sendonly" | "recvonly" | "inactive"; +type RTCSctpTransportState = "connecting" | "connected" | "closed"; +type RTCSdpType = "offer" | "pranswer" | "answer" | "rollback"; +type RTCSignalingState = "stable" | "have-local-offer" | "have-remote-offer" | "have-local-pranswer" | "have-remote-pranswer" | "closed"; +type RTCStatsIceCandidatePairState = "frozen" | "waiting" | "inprogress" | "failed" | "succeeded" | "cancelled"; +type RTCStatsIceCandidateType = "host" | "serverreflexive" | "peerreflexive" | "relayed"; +type RTCStatsType = "inboundrtp" | "outboundrtp" | "session" | "datachannel" | "track" | "transport" | "candidatepair" | "localcandidate" | "remotecandidate"; +type ReadyState = "closed" | "open" | "ended"; +type ReferrerPolicy = "" | "no-referrer" | "no-referrer-when-downgrade" | "origin-only" | "origin-when-cross-origin" | "unsafe-url"; +type RequestCache = "default" | "no-store" | "reload" | "no-cache" | "force-cache" | "only-if-cached"; +type RequestCredentials = "omit" | "same-origin" | "include"; +type RequestDestination = "" | "audio" | "audioworklet" | "document" | "embed" | "font" | "image" | "manifest" | "object" | "paintworklet" | "report" | "script" | "sharedworker" | "style" | "track" | "video" | "worker" | "xslt"; +type RequestMode = "navigate" | "same-origin" | "no-cors" | "cors"; +type RequestRedirect = "follow" | "error" | "manual"; +type ResponseType = "basic" | "cors" | "default" | "error" | "opaque" | "opaqueredirect"; +type ScopedCredentialType = "ScopedCred"; +type ScrollBehavior = "auto" | "smooth"; +type ScrollLogicalPosition = "start" | "center" | "end" | "nearest"; +type ScrollRestoration = "auto" | "manual"; +type ScrollSetting = "" | "up"; +type SelectionMode = "select" | "start" | "end" | "preserve"; +type ServiceWorkerState = "installing" | "installed" | "activating" | "activated" | "redundant"; +type ServiceWorkerUpdateViaCache = "imports" | "all" | "none"; +type ShadowRootMode = "open" | "closed"; +type SpeechRecognitionErrorCode = "no-speech" | "aborted" | "audio-capture" | "network" | "not-allowed" | "service-not-allowed" | "bad-grammar" | "language-not-supported"; +type SpeechSynthesisErrorCode = "canceled" | "interrupted" | "audio-busy" | "audio-hardware" | "network" | "synthesis-unavailable" | "synthesis-failed" | "language-unavailable" | "voice-unavailable" | "text-too-long" | "invalid-argument"; +type SupportedType = "text/html" | "text/xml" | "application/xml" | "application/xhtml+xml" | "image/svg+xml"; +type TextTrackKind = "subtitles" | "captions" | "descriptions" | "chapters" | "metadata"; +type TextTrackMode = "disabled" | "hidden" | "showing"; +type TouchType = "direct" | "stylus"; +type Transport = "usb" | "nfc" | "ble"; +type VRDisplayEventReason = "mounted" | "navigation" | "requested" | "unmounted"; +type VideoFacingModeEnum = "user" | "environment" | "left" | "right"; +type VisibilityState = "hidden" | "visible" | "prerender"; +type WebGLPowerPreference = "default" | "low-power" | "high-performance"; +type WorkerType = "classic" | "module"; +type XMLHttpRequestResponseType = "" | "arraybuffer" | "blob" | "document" | "json" | "text"; diff --git a/node_modules/typescript/lib/lib.dom.iterable.d.ts b/node_modules/typescript/lib/lib.dom.iterable.d.ts new file mode 100644 index 0000000..0948f70 --- /dev/null +++ b/node_modules/typescript/lib/lib.dom.iterable.d.ts @@ -0,0 +1,236 @@ +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + + + +/// + + +///////////////////////////// +/// DOM Iterable APIs +///////////////////////////// + +interface AudioParamMap extends ReadonlyMap { +} + +interface AudioTrackList { + [Symbol.iterator](): IterableIterator; +} + +interface CSSRuleList { + [Symbol.iterator](): IterableIterator; +} + +interface CSSStyleDeclaration { + [Symbol.iterator](): IterableIterator; +} + +interface ClientRectList { + [Symbol.iterator](): IterableIterator; +} + +interface DOMRectList { + [Symbol.iterator](): IterableIterator; +} + +interface DOMStringList { + [Symbol.iterator](): IterableIterator; +} + +interface DOMTokenList { + [Symbol.iterator](): IterableIterator; + entries(): IterableIterator<[number, string]>; + keys(): IterableIterator; + values(): IterableIterator; +} + +interface DataTransferItemList { + [Symbol.iterator](): IterableIterator; +} + +interface FileList { + [Symbol.iterator](): IterableIterator; +} + +interface FormData { + [Symbol.iterator](): IterableIterator<[string, FormDataEntryValue]>; + /** + * Returns an array of key, value pairs for every entry in the list. + */ + entries(): IterableIterator<[string, FormDataEntryValue]>; + /** + * Returns a list of keys in the list. + */ + keys(): IterableIterator; + /** + * Returns a list of values in the list. + */ + values(): IterableIterator; +} + +interface HTMLAllCollection { + [Symbol.iterator](): IterableIterator; +} + +interface HTMLCollectionBase { + [Symbol.iterator](): IterableIterator; +} + +interface HTMLCollectionOf { + [Symbol.iterator](): IterableIterator; +} + +interface HTMLFormElement { + [Symbol.iterator](): IterableIterator; +} + +interface HTMLSelectElement { + [Symbol.iterator](): IterableIterator; +} + +interface Headers { + [Symbol.iterator](): IterableIterator<[string, string]>; + /** + * Returns an iterator allowing to go through all key/value pairs contained in this object. + */ + entries(): IterableIterator<[string, string]>; + /** + * Returns an iterator allowing to go through all keys of the key/value pairs contained in this object. + */ + keys(): IterableIterator; + /** + * Returns an iterator allowing to go through all values of the key/value pairs contained in this object. + */ + values(): IterableIterator; +} + +interface MediaList { + [Symbol.iterator](): IterableIterator; +} + +interface MimeTypeArray { + [Symbol.iterator](): IterableIterator; +} + +interface NamedNodeMap { + [Symbol.iterator](): IterableIterator; +} + +interface NodeList { + [Symbol.iterator](): IterableIterator; + /** + * Returns an array of key, value pairs for every entry in the list. + */ + entries(): IterableIterator<[number, Node]>; + /** + * Returns an list of keys in the list. + */ + keys(): IterableIterator; + /** + * Returns an list of values in the list. + */ + values(): IterableIterator; +} + +interface NodeListOf { + [Symbol.iterator](): IterableIterator; + /** + * Returns an array of key, value pairs for every entry in the list. + */ + entries(): IterableIterator<[number, TNode]>; + /** + * Returns an list of keys in the list. + */ + keys(): IterableIterator; + /** + * Returns an list of values in the list. + */ + values(): IterableIterator; +} + +interface Plugin { + [Symbol.iterator](): IterableIterator; +} + +interface PluginArray { + [Symbol.iterator](): IterableIterator; +} + +interface RTCStatsReport extends ReadonlyMap { +} + +interface SVGLengthList { + [Symbol.iterator](): IterableIterator; +} + +interface SVGNumberList { + [Symbol.iterator](): IterableIterator; +} + +interface SVGStringList { + [Symbol.iterator](): IterableIterator; +} + +interface SourceBufferList { + [Symbol.iterator](): IterableIterator; +} + +interface SpeechGrammarList { + [Symbol.iterator](): IterableIterator; +} + +interface SpeechRecognitionResult { + [Symbol.iterator](): IterableIterator; +} + +interface SpeechRecognitionResultList { + [Symbol.iterator](): IterableIterator; +} + +interface StyleSheetList { + [Symbol.iterator](): IterableIterator; +} + +interface TextTrackCueList { + [Symbol.iterator](): IterableIterator; +} + +interface TextTrackList { + [Symbol.iterator](): IterableIterator; +} + +interface TouchList { + [Symbol.iterator](): IterableIterator; +} + +interface URLSearchParams { + [Symbol.iterator](): IterableIterator<[string, string]>; + /** + * Returns an array of key, value pairs for every entry in the search params. + */ + entries(): IterableIterator<[string, string]>; + /** + * Returns a list of keys in the search params. + */ + keys(): IterableIterator; + /** + * Returns a list of values in the search params. + */ + values(): IterableIterator; +} + +interface VideoTrackList { + [Symbol.iterator](): IterableIterator; +} diff --git a/node_modules/typescript/lib/lib.es2015.collection.d.ts b/node_modules/typescript/lib/lib.es2015.collection.d.ts new file mode 100644 index 0000000..2c19919 --- /dev/null +++ b/node_modules/typescript/lib/lib.es2015.collection.d.ts @@ -0,0 +1,89 @@ +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + + + +/// + + +interface Map { + clear(): void; + delete(key: K): boolean; + forEach(callbackfn: (value: V, key: K, map: Map) => void, thisArg?: any): void; + get(key: K): V | undefined; + has(key: K): boolean; + set(key: K, value: V): this; + readonly size: number; +} + +interface MapConstructor { + new(): Map; + new(entries?: ReadonlyArray<[K, V]> | null): Map; + readonly prototype: Map; +} +declare var Map: MapConstructor; + +interface ReadonlyMap { + forEach(callbackfn: (value: V, key: K, map: ReadonlyMap) => void, thisArg?: any): void; + get(key: K): V | undefined; + has(key: K): boolean; + readonly size: number; +} + +interface WeakMap { + delete(key: K): boolean; + get(key: K): V | undefined; + has(key: K): boolean; + set(key: K, value: V): this; +} + +interface WeakMapConstructor { + new (entries?: ReadonlyArray<[K, V]> | null): WeakMap; + readonly prototype: WeakMap; +} +declare var WeakMap: WeakMapConstructor; + +interface Set { + add(value: T): this; + clear(): void; + delete(value: T): boolean; + forEach(callbackfn: (value: T, value2: T, set: Set) => void, thisArg?: any): void; + has(value: T): boolean; + readonly size: number; +} + +interface SetConstructor { + new (values?: ReadonlyArray | null): Set; + readonly prototype: Set; +} +declare var Set: SetConstructor; + +interface ReadonlySet { + forEach(callbackfn: (value: T, value2: T, set: ReadonlySet) => void, thisArg?: any): void; + has(value: T): boolean; + readonly size: number; +} + +interface WeakSet { + add(value: T): this; + delete(value: T): boolean; + has(value: T): boolean; +} + +interface WeakSetConstructor { + new (values?: ReadonlyArray | null): WeakSet; + readonly prototype: WeakSet; +} +declare var WeakSet: WeakSetConstructor; diff --git a/node_modules/typescript/lib/lib.es2015.core.d.ts b/node_modules/typescript/lib/lib.es2015.core.d.ts new file mode 100644 index 0000000..7c43b36 --- /dev/null +++ b/node_modules/typescript/lib/lib.es2015.core.d.ts @@ -0,0 +1,511 @@ +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + + + +/// + + +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: (this: void, value: T, index: number, obj: T[]) => value is S, thisArg?: any): S | undefined; + find(predicate: (value: T, index: number, obj: T[]) => 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, + * findIndex immediately returns that element index. Otherwise, findIndex returns -1. + * @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, index: number, obj: 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): this; + + /** + * 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): this; +} + +interface ArrayConstructor { + /** + * Creates an array from an array-like object. + * @param arrayLike An array-like object to convert to an array. + */ + from(arrayLike: ArrayLike): T[]; + + /** + * Creates an array from an iterable 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): U[]; + + /** + * 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[]): T[]; +} + +interface DateConstructor { + new (value: number | string | Date): Date; +} + +interface Function { + /** + * Returns the name of the function. Function names are read-only and can not be changed. + */ + readonly name: 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), which is an implementation-dependent approximation to + * subtracting 1 from the exponential function 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 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. + */ + readonly EPSILON: number; + + /** + * Returns true if passed value is finite. + * Unlike the global isFinite, 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.MAX_SAFE_INTEGER is 9007199254740991 2^53 − 1. + */ + readonly 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)). + */ + readonly 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 source The source object from which to copy properties. + */ + assign(target: T, source: U): T & U; + + /** + * 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 source1 The first source object from which to copy properties. + * @param source2 The second source object from which to copy properties. + */ + assign(target: T, source1: U, source2: V): T & U & V; + + /** + * 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 source1 The first source object from which to copy properties. + * @param source2 The second source object from which to copy properties. + * @param source3 The third source object from which to copy properties. + */ + assign(target: T, source1: U, source2: V, source3: W): T & U & V & W; + + /** + * 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 from which to copy properties + */ + assign(target: object, ...sources: any[]): any; + + /** + * Returns an array of all symbol properties found directly on object o. + * @param o Object to retrieve the symbols from. + */ + getOwnPropertySymbols(o: any): symbol[]; + + /** + * 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. + */ + setPrototypeOf(o: any, proto: object | null): any; +} + +interface ReadonlyArray { + /** + * 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: (this: void, value: T, index: number, obj: ReadonlyArray) => value is S, thisArg?: any): S | undefined; + find(predicate: (value: T, index: number, obj: ReadonlyArray) => 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, + * findIndex immediately returns that element index. Otherwise, findIndex returns -1. + * @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, index: number, obj: ReadonlyArray) => boolean, thisArg?: any): number; +} + +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. + */ + readonly flags: string; + + /** + * Returns a Boolean value indicating the state of the sticky flag (y) used with a regular + * expression. Default is false. Read-only. + */ + readonly sticky: boolean; + + /** + * Returns a Boolean value indicating the state of the Unicode flag (u) used with a regular + * expression. Default is false. Read-only. + */ + readonly unicode: boolean; +} + +interface RegExpConstructor { + new (pattern: RegExp, flags?: string): RegExp; + (pattern: RegExp, flags?: string): RegExp; +} + +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 | undefined; + + /** + * 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 the String value result of normalizing the string into the normalization form + * named by form as specified in Unicode Standard Annex #15, Unicode Normalization Forms. + * @param form Applicable values: "NFC", "NFD", "NFKC", or "NFKD", If not specified default + * is "NFC" + */ + normalize(form: "NFC" | "NFD" | "NFKC" | "NFKD"): string; + + /** + * Returns the String value result of normalizing the string into the normalization form + * named by form as specified in Unicode Standard Annex #15, Unicode Normalization Forms. + * @param form Applicable values: "NFC", "NFD", "NFKC", or "NFKD", If not specified default + * is "NFC" + */ + normalize(form?: string): string; + + /** + * Returns a String value that is made from count copies appended together. If count is 0, + * 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; +} + +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; +} diff --git a/node_modules/typescript/lib/lib.es2015.d.ts b/node_modules/typescript/lib/lib.es2015.d.ts new file mode 100644 index 0000000..80aaba0 --- /dev/null +++ b/node_modules/typescript/lib/lib.es2015.d.ts @@ -0,0 +1,30 @@ +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + + + +/// + + +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// diff --git a/node_modules/typescript/lib/lib.es2015.generator.d.ts b/node_modules/typescript/lib/lib.es2015.generator.d.ts new file mode 100644 index 0000000..df6a987 --- /dev/null +++ b/node_modules/typescript/lib/lib.es2015.generator.d.ts @@ -0,0 +1,71 @@ +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + + + +/// + + +interface Generator extends Iterator { } + +interface GeneratorFunction { + /** + * Creates a new Generator object. + * @param args A list of arguments the function accepts. + */ + new (...args: any[]): Generator; + /** + * Creates a new Generator object. + * @param args A list of arguments the function accepts. + */ + (...args: any[]): Generator; + /** + * The length of the arguments. + */ + readonly length: number; + /** + * Returns the name of the function. + */ + readonly name: string; + /** + * A reference to the prototype. + */ + readonly prototype: Generator; +} + +interface GeneratorFunctionConstructor { + /** + * Creates a new Generator function. + * @param args A list of arguments the function accepts. + */ + new (...args: string[]): GeneratorFunction; + /** + * Creates a new Generator function. + * @param args A list of arguments the function accepts. + */ + (...args: string[]): GeneratorFunction; + /** + * The length of the arguments. + */ + readonly length: number; + /** + * Returns the name of the function. + */ + readonly name: string; + /** + * A reference to the prototype. + */ + readonly prototype: GeneratorFunction; +} diff --git a/node_modules/typescript/lib/lib.es2015.iterable.d.ts b/node_modules/typescript/lib/lib.es2015.iterable.d.ts new file mode 100644 index 0000000..43b021a --- /dev/null +++ b/node_modules/typescript/lib/lib.es2015.iterable.d.ts @@ -0,0 +1,493 @@ +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + + + +/// + + +/// + +interface SymbolConstructor { + /** + * A method that returns the default iterator for an object. Called by the semantics of the + * for-of statement. + */ + readonly iterator: symbol; +} + +interface IteratorResult { + done: boolean; + value: T; +} + +interface Iterator { + next(value?: any): IteratorResult; + return?(value?: any): IteratorResult; + throw?(e?: any): IteratorResult; +} + +interface Iterable { + [Symbol.iterator](): Iterator; +} + +interface IterableIterator extends Iterator { + [Symbol.iterator](): IterableIterator; +} + +interface Array { + /** Iterator */ + [Symbol.iterator](): IterableIterator; + + /** + * Returns an iterable of key, value pairs for every entry in the array + */ + entries(): IterableIterator<[number, T]>; + + /** + * Returns an iterable of keys in the array + */ + keys(): IterableIterator; + + /** + * Returns an iterable of values in the array + */ + values(): IterableIterator; +} + +interface ArrayConstructor { + /** + * Creates an array from an iterable object. + * @param iterable An iterable object to convert to an array. + */ + from(iterable: Iterable | ArrayLike): T[]; + + /** + * 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: Iterable | ArrayLike, mapfn: (v: T, k: number) => U, thisArg?: any): U[]; +} + +interface ReadonlyArray { + /** Iterator of values in the array. */ + [Symbol.iterator](): IterableIterator; + + /** + * Returns an iterable of key, value pairs for every entry in the array + */ + entries(): IterableIterator<[number, T]>; + + /** + * Returns an iterable of keys in the array + */ + keys(): IterableIterator; + + /** + * Returns an iterable of values in the array + */ + values(): IterableIterator; +} + +interface IArguments { + /** Iterator */ + [Symbol.iterator](): IterableIterator; +} + +interface Map { + /** Returns an iterable of entries in the map. */ + [Symbol.iterator](): IterableIterator<[K, V]>; + + /** + * Returns an iterable of key, value pairs for every entry in the map. + */ + entries(): IterableIterator<[K, V]>; + + /** + * Returns an iterable of keys in the map + */ + keys(): IterableIterator; + + /** + * Returns an iterable of values in the map + */ + values(): IterableIterator; +} + +interface ReadonlyMap { + /** Returns an iterable of entries in the map. */ + [Symbol.iterator](): IterableIterator<[K, V]>; + + /** + * Returns an iterable of key, value pairs for every entry in the map. + */ + entries(): IterableIterator<[K, V]>; + + /** + * Returns an iterable of keys in the map + */ + keys(): IterableIterator; + + /** + * Returns an iterable of values in the map + */ + values(): IterableIterator; +} + +interface MapConstructor { + new (iterable: Iterable<[K, V]>): Map; +} + +interface WeakMap { } + +interface WeakMapConstructor { + new (iterable: Iterable<[K, V]>): WeakMap; +} + +interface Set { + /** Iterates over values in the set. */ + [Symbol.iterator](): IterableIterator; + /** + * Returns an iterable of [v,v] pairs for every value `v` in the set. + */ + entries(): IterableIterator<[T, T]>; + /** + * Despite its name, returns an iterable of the values in the set, + */ + keys(): IterableIterator; + + /** + * Returns an iterable of values in the set. + */ + values(): IterableIterator; +} + +interface ReadonlySet { + /** Iterates over values in the set. */ + [Symbol.iterator](): IterableIterator; + + /** + * Returns an iterable of [v,v] pairs for every value `v` in the set. + */ + entries(): IterableIterator<[T, T]>; + + /** + * Despite its name, returns an iterable of the values in the set, + */ + keys(): IterableIterator; + + /** + * Returns an iterable of values in the set. + */ + values(): IterableIterator; +} + +interface SetConstructor { + new (iterable: Iterable): Set; +} + +interface WeakSet { } + +interface WeakSetConstructor { + new (iterable: Iterable): WeakSet; +} + +interface Promise { } + +interface PromiseConstructor { + /** + * 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: Iterable>): 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: Iterable>): Promise; +} + +declare namespace Reflect { + function enumerate(target: object): IterableIterator; +} + +interface String { + /** Iterator */ + [Symbol.iterator](): IterableIterator; +} + +interface Int8Array { + [Symbol.iterator](): IterableIterator; + /** + * Returns an array of key, value pairs for every entry in the array + */ + entries(): IterableIterator<[number, number]>; + /** + * Returns an list of keys in the array + */ + keys(): IterableIterator; + /** + * Returns an list of values in the array + */ + values(): IterableIterator; +} + +interface Int8ArrayConstructor { + new (elements: Iterable): Int8Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or 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(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Int8Array; +} + +interface Uint8Array { + [Symbol.iterator](): IterableIterator; + /** + * Returns an array of key, value pairs for every entry in the array + */ + entries(): IterableIterator<[number, number]>; + /** + * Returns an list of keys in the array + */ + keys(): IterableIterator; + /** + * Returns an list of values in the array + */ + values(): IterableIterator; +} + +interface Uint8ArrayConstructor { + new (elements: Iterable): Uint8Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or 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(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint8Array; +} + +interface Uint8ClampedArray { + [Symbol.iterator](): IterableIterator; + /** + * Returns an array of key, value pairs for every entry in the array + */ + entries(): IterableIterator<[number, number]>; + + /** + * Returns an list of keys in the array + */ + keys(): IterableIterator; + + /** + * Returns an list of values in the array + */ + values(): IterableIterator; +} + +interface Uint8ClampedArrayConstructor { + new (elements: Iterable): Uint8ClampedArray; + + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or 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(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint8ClampedArray; +} + +interface Int16Array { + [Symbol.iterator](): IterableIterator; + /** + * Returns an array of key, value pairs for every entry in the array + */ + entries(): IterableIterator<[number, number]>; + + /** + * Returns an list of keys in the array + */ + keys(): IterableIterator; + + /** + * Returns an list of values in the array + */ + values(): IterableIterator; +} + +interface Int16ArrayConstructor { + new (elements: Iterable): Int16Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or 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(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Int16Array; +} + +interface Uint16Array { + [Symbol.iterator](): IterableIterator; + /** + * Returns an array of key, value pairs for every entry in the array + */ + entries(): IterableIterator<[number, number]>; + /** + * Returns an list of keys in the array + */ + keys(): IterableIterator; + /** + * Returns an list of values in the array + */ + values(): IterableIterator; +} + +interface Uint16ArrayConstructor { + new (elements: Iterable): Uint16Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or 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(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint16Array; +} + +interface Int32Array { + [Symbol.iterator](): IterableIterator; + /** + * Returns an array of key, value pairs for every entry in the array + */ + entries(): IterableIterator<[number, number]>; + /** + * Returns an list of keys in the array + */ + keys(): IterableIterator; + /** + * Returns an list of values in the array + */ + values(): IterableIterator; +} + +interface Int32ArrayConstructor { + new (elements: Iterable): Int32Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or 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(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Int32Array; +} + +interface Uint32Array { + [Symbol.iterator](): IterableIterator; + /** + * Returns an array of key, value pairs for every entry in the array + */ + entries(): IterableIterator<[number, number]>; + /** + * Returns an list of keys in the array + */ + keys(): IterableIterator; + /** + * Returns an list of values in the array + */ + values(): IterableIterator; +} + +interface Uint32ArrayConstructor { + new (elements: Iterable): Uint32Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or 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(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint32Array; +} + +interface Float32Array { + [Symbol.iterator](): IterableIterator; + /** + * Returns an array of key, value pairs for every entry in the array + */ + entries(): IterableIterator<[number, number]>; + /** + * Returns an list of keys in the array + */ + keys(): IterableIterator; + /** + * Returns an list of values in the array + */ + values(): IterableIterator; +} + +interface Float32ArrayConstructor { + new (elements: Iterable): Float32Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or 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(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Float32Array; +} + +interface Float64Array { + [Symbol.iterator](): IterableIterator; + /** + * Returns an array of key, value pairs for every entry in the array + */ + entries(): IterableIterator<[number, number]>; + /** + * Returns an list of keys in the array + */ + keys(): IterableIterator; + /** + * Returns an list of values in the array + */ + values(): IterableIterator; +} + +interface Float64ArrayConstructor { + new (elements: Iterable): Float64Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or 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(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Float64Array; +} diff --git a/node_modules/typescript/lib/lib.es2015.promise.d.ts b/node_modules/typescript/lib/lib.es2015.promise.d.ts new file mode 100644 index 0000000..002d691 --- /dev/null +++ b/node_modules/typescript/lib/lib.es2015.promise.d.ts @@ -0,0 +1,216 @@ +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + + + +/// + + +interface PromiseConstructor { + /** + * A reference to the prototype. + */ + readonly 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: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike, T9 | PromiseLike, T10 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10]>; + + /** + * 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: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike, T9 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8, T9]>; + + /** + * 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: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8]>; + + /** + * 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: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6, T7]>; + + /** + * 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: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6]>; + + /** + * 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: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike]): Promise<[T1, T2, T3, T4, T5]>; + + /** + * 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: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike ]): Promise<[T1, T2, T3, T4]>; + + /** + * 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: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike]): Promise<[T1, T2, T3]>; + + /** + * 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: [T1 | PromiseLike, T2 | PromiseLike]): Promise<[T1, T2]>; + + /** + * 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: (T | PromiseLike)[]): 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: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike, T9 | PromiseLike, T10 | PromiseLike]): 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: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike, T9 | PromiseLike]): 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: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike]): 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: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike]): 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: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike, T6 | PromiseLike]): 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: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike]): 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: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike]): 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: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike]): 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: [T1 | PromiseLike, T2 | PromiseLike]): 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: (T | PromiseLike)[]): 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; diff --git a/node_modules/typescript/lib/lib.es2015.proxy.d.ts b/node_modules/typescript/lib/lib.es2015.proxy.d.ts new file mode 100644 index 0000000..4408970 --- /dev/null +++ b/node_modules/typescript/lib/lib.es2015.proxy.d.ts @@ -0,0 +1,42 @@ +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + + + +/// + + +interface ProxyHandler { + getPrototypeOf? (target: T): object | null; + setPrototypeOf? (target: T, v: any): boolean; + isExtensible? (target: T): boolean; + preventExtensions? (target: T): boolean; + getOwnPropertyDescriptor? (target: T, p: PropertyKey): PropertyDescriptor | undefined; + has? (target: T, p: PropertyKey): boolean; + get? (target: T, p: PropertyKey, receiver: any): any; + set? (target: T, p: PropertyKey, value: any, receiver: any): boolean; + deleteProperty? (target: T, p: PropertyKey): boolean; + defineProperty? (target: T, p: PropertyKey, attributes: PropertyDescriptor): boolean; + enumerate? (target: T): PropertyKey[]; + ownKeys? (target: T): PropertyKey[]; + apply? (target: T, thisArg: any, argArray?: any): any; + construct? (target: T, argArray: any, newTarget?: any): object; +} + +interface ProxyConstructor { + revocable(target: T, handler: ProxyHandler): { proxy: T; revoke: () => void; }; + new (target: T, handler: ProxyHandler): T; +} +declare var Proxy: ProxyConstructor; diff --git a/node_modules/typescript/lib/lib.es2015.reflect.d.ts b/node_modules/typescript/lib/lib.es2015.reflect.d.ts new file mode 100644 index 0000000..1139f1c --- /dev/null +++ b/node_modules/typescript/lib/lib.es2015.reflect.d.ts @@ -0,0 +1,35 @@ +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + + + +/// + + +declare namespace Reflect { + function apply(target: Function, thisArgument: any, argumentsList: ArrayLike): any; + function construct(target: Function, argumentsList: ArrayLike, newTarget?: any): any; + function defineProperty(target: object, propertyKey: PropertyKey, attributes: PropertyDescriptor): boolean; + function deleteProperty(target: object, propertyKey: PropertyKey): boolean; + function get(target: object, propertyKey: PropertyKey, receiver?: any): any; + function getOwnPropertyDescriptor(target: object, propertyKey: PropertyKey): PropertyDescriptor | undefined; + function getPrototypeOf(target: object): object; + function has(target: object, propertyKey: PropertyKey): boolean; + function isExtensible(target: object): boolean; + function ownKeys(target: object): PropertyKey[]; + function preventExtensions(target: object): boolean; + function set(target: object, propertyKey: PropertyKey, value: any, receiver?: any): boolean; + function setPrototypeOf(target: object, proto: any): boolean; +} diff --git a/node_modules/typescript/lib/lib.es2015.symbol.d.ts b/node_modules/typescript/lib/lib.es2015.symbol.d.ts new file mode 100644 index 0000000..bf09484 --- /dev/null +++ b/node_modules/typescript/lib/lib.es2015.symbol.d.ts @@ -0,0 +1,48 @@ +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + + + +/// + + +interface SymbolConstructor { + /** + * A reference to the prototype. + */ + readonly prototype: Symbol; + + /** + * Returns a new unique Symbol value. + * @param description Description of the new Symbol object. + */ + (description?: string | number): symbol; + + /** + * Returns a Symbol object from the global symbol registry matching the given key if found. + * Otherwise, returns a new symbol with this key. + * @param key key to search for. + */ + for(key: string): symbol; + + /** + * Returns a key from the global symbol registry matching the given Symbol if found. + * Otherwise, returns a undefined. + * @param sym Symbol to find the key for. + */ + keyFor(sym: symbol): string | undefined; +} + +declare var Symbol: SymbolConstructor; \ No newline at end of file diff --git a/node_modules/typescript/lib/lib.es2015.symbol.wellknown.d.ts b/node_modules/typescript/lib/lib.es2015.symbol.wellknown.d.ts new file mode 100644 index 0000000..400f70a --- /dev/null +++ b/node_modules/typescript/lib/lib.es2015.symbol.wellknown.d.ts @@ -0,0 +1,318 @@ +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + + + +/// + + +/// + +interface SymbolConstructor { + /** + * A method that determines if a constructor object recognizes an object as one of the + * constructor’s instances. Called by the semantics of the instanceof operator. + */ + readonly hasInstance: symbol; + + /** + * A Boolean value that if true indicates that an object should flatten to its array elements + * by Array.prototype.concat. + */ + readonly isConcatSpreadable: symbol; + + /** + * A regular expression method that matches the regular expression against a string. Called + * by the String.prototype.match method. + */ + readonly match: symbol; + + /** + * A regular expression method that replaces matched substrings of a string. Called by the + * String.prototype.replace method. + */ + readonly replace: symbol; + + /** + * A regular expression method that returns the index within a string that matches the + * regular expression. Called by the String.prototype.search method. + */ + readonly search: symbol; + + /** + * A function valued property that is the constructor function that is used to create + * derived objects. + */ + readonly species: symbol; + + /** + * A regular expression method that splits a string at the indices that match the regular + * expression. Called by the String.prototype.split method. + */ + readonly split: symbol; + + /** + * A method that converts an object to a corresponding primitive value. + * Called by the ToPrimitive abstract operation. + */ + readonly toPrimitive: symbol; + + /** + * A String value that is used in the creation of the default string description of an object. + * Called by the built-in method Object.prototype.toString. + */ + readonly toStringTag: symbol; + + /** + * An Object whose own property names are property names that are excluded from the 'with' + * environment bindings of the associated objects. + */ + readonly unscopables: symbol; +} + +interface Symbol { + readonly [Symbol.toStringTag]: string; +} + +interface Array { + /** + * Returns an object whose properties have the value 'true' + * when they will be absent when used in a 'with' statement. + */ + [Symbol.unscopables](): { + copyWithin: boolean; + entries: boolean; + fill: boolean; + find: boolean; + findIndex: boolean; + keys: boolean; + values: boolean; + }; +} + +interface Date { + /** + * Converts a Date object to a string. + */ + [Symbol.toPrimitive](hint: "default"): string; + /** + * Converts a Date object to a string. + */ + [Symbol.toPrimitive](hint: "string"): string; + /** + * Converts a Date object to a number. + */ + [Symbol.toPrimitive](hint: "number"): number; + /** + * Converts a Date object to a string or number. + * + * @param hint The strings "number", "string", or "default" to specify what primitive to return. + * + * @throws {TypeError} If 'hint' was given something other than "number", "string", or "default". + * @returns A number if 'hint' was "number", a string if 'hint' was "string" or "default". + */ + [Symbol.toPrimitive](hint: string): string | number; +} + +interface Map { + readonly [Symbol.toStringTag]: string; +} + +interface WeakMap { + readonly [Symbol.toStringTag]: string; +} + +interface Set { + readonly [Symbol.toStringTag]: string; +} + +interface WeakSet { + readonly [Symbol.toStringTag]: string; +} + +interface JSON { + readonly [Symbol.toStringTag]: string; +} + +interface Function { + /** + * Determines whether the given value inherits from this function if this function was used + * as a constructor function. + * + * A constructor function can control which objects are recognized as its instances by + * 'instanceof' by overriding this method. + */ + [Symbol.hasInstance](value: any): boolean; +} + +interface GeneratorFunction { + readonly [Symbol.toStringTag]: string; +} + +interface Math { + readonly [Symbol.toStringTag]: string; +} + +interface Promise { + readonly [Symbol.toStringTag]: string; +} + +interface PromiseConstructor { + readonly [Symbol.species]: PromiseConstructor; +} + +interface RegExp { + /** + * Matches a string with this regular expression, and returns an array containing the results of + * that search. + * @param string A string to search within. + */ + [Symbol.match](string: string): RegExpMatchArray | null; + + /** + * Replaces text in a string, using this regular expression. + * @param string A String object or string literal whose contents matching against + * this regular expression will be replaced + * @param replaceValue A String object or string literal containing the text to replace for every + * successful match of this regular expression. + */ + [Symbol.replace](string: string, replaceValue: string): string; + + /** + * Replaces text in a string, using this regular expression. + * @param string A String object or string literal whose contents matching against + * this regular expression will be replaced + * @param replacer A function that returns the replacement text. + */ + [Symbol.replace](string: string, replacer: (substring: string, ...args: any[]) => string): string; + + /** + * Finds the position beginning first substring match in a regular expression search + * using this regular expression. + * + * @param string The string to search within. + */ + [Symbol.search](string: string): number; + + /** + * Returns an array of substrings that were delimited by strings in the original input that + * match against this regular expression. + * + * If the regular expression contains capturing parentheses, then each time this + * regular expression matches, the results (including any undefined results) of the + * capturing parentheses are spliced. + * + * @param string string value to split + * @param limit if not undefined, the output array is truncated so that it contains no more + * than 'limit' elements. + */ + [Symbol.split](string: string, limit?: number): string[]; +} + +interface RegExpConstructor { + readonly [Symbol.species]: RegExpConstructor; +} + +interface String { + /** + * Matches a string an object that supports being matched against, and returns an array containing the results of that search. + * @param matcher An object that supports being matched against. + */ + match(matcher: { [Symbol.match](string: string): RegExpMatchArray | null; }): RegExpMatchArray | null; + + /** + * Replaces text in a string, using an object that supports replacement within a string. + * @param searchValue A object can search for and replace matches within a string. + * @param replaceValue A string containing the text to replace for every successful match of searchValue in this string. + */ + replace(searchValue: { [Symbol.replace](string: string, replaceValue: string): string; }, replaceValue: string): string; + + /** + * Replaces text in a string, using an object that supports replacement within a string. + * @param searchValue A object can search for and replace matches within a string. + * @param replacer A function that returns the replacement text. + */ + replace(searchValue: { [Symbol.replace](string: string, replacer: (substring: string, ...args: any[]) => string): string; }, replacer: (substring: string, ...args: any[]) => string): string; + + /** + * Finds the first substring match in a regular expression search. + * @param searcher An object which supports searching within a string. + */ + search(searcher: { [Symbol.search](string: string): number; }): number; + + /** + * Split a string into substrings using the specified separator and return them as an array. + * @param splitter An object that can split a string. + * @param limit A value used to limit the number of elements returned in the array. + */ + split(splitter: { [Symbol.split](string: string, limit?: number): string[]; }, limit?: number): string[]; +} + +interface ArrayBuffer { + readonly [Symbol.toStringTag]: string; +} + +interface DataView { + readonly [Symbol.toStringTag]: string; +} + +interface Int8Array { + readonly [Symbol.toStringTag]: "Int8Array"; +} + +interface Uint8Array { + readonly [Symbol.toStringTag]: "UInt8Array"; +} + +interface Uint8ClampedArray { + readonly [Symbol.toStringTag]: "Uint8ClampedArray"; +} + +interface Int16Array { + readonly [Symbol.toStringTag]: "Int16Array"; +} + +interface Uint16Array { + readonly [Symbol.toStringTag]: "Uint16Array"; +} + +interface Int32Array { + readonly [Symbol.toStringTag]: "Int32Array"; +} + +interface Uint32Array { + readonly [Symbol.toStringTag]: "Uint32Array"; +} + +interface Float32Array { + readonly [Symbol.toStringTag]: "Float32Array"; +} + +interface Float64Array { + readonly [Symbol.toStringTag]: "Float64Array"; +} + +interface ArrayConstructor { + readonly [Symbol.species]: ArrayConstructor; +} +interface MapConstructor { + readonly [Symbol.species]: MapConstructor; +} +interface SetConstructor { + readonly [Symbol.species]: SetConstructor; +} +interface ArrayBufferConstructor { + readonly [Symbol.species]: ArrayBufferConstructor; +} \ No newline at end of file diff --git a/node_modules/typescript/lib/lib.es2016.array.include.d.ts b/node_modules/typescript/lib/lib.es2016.array.include.d.ts new file mode 100644 index 0000000..734fa45 --- /dev/null +++ b/node_modules/typescript/lib/lib.es2016.array.include.d.ts @@ -0,0 +1,118 @@ +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + + + +/// + + +interface Array { + /** + * Determines whether an array includes a certain element, returning true or false as appropriate. + * @param searchElement The element to search for. + * @param fromIndex The position in this array at which to begin searching for searchElement. + */ + includes(searchElement: T, fromIndex?: number): boolean; +} + +interface ReadonlyArray { + /** + * Determines whether an array includes a certain element, returning true or false as appropriate. + * @param searchElement The element to search for. + * @param fromIndex The position in this array at which to begin searching for searchElement. + */ + includes(searchElement: T, fromIndex?: number): boolean; +} + +interface Int8Array { + /** + * Determines whether an array includes a certain element, returning true or false as appropriate. + * @param searchElement The element to search for. + * @param fromIndex The position in this array at which to begin searching for searchElement. + */ + includes(searchElement: number, fromIndex?: number): boolean; +} + +interface Uint8Array { + /** + * Determines whether an array includes a certain element, returning true or false as appropriate. + * @param searchElement The element to search for. + * @param fromIndex The position in this array at which to begin searching for searchElement. + */ + includes(searchElement: number, fromIndex?: number): boolean; +} + +interface Uint8ClampedArray { + /** + * Determines whether an array includes a certain element, returning true or false as appropriate. + * @param searchElement The element to search for. + * @param fromIndex The position in this array at which to begin searching for searchElement. + */ + includes(searchElement: number, fromIndex?: number): boolean; +} + +interface Int16Array { + /** + * Determines whether an array includes a certain element, returning true or false as appropriate. + * @param searchElement The element to search for. + * @param fromIndex The position in this array at which to begin searching for searchElement. + */ + includes(searchElement: number, fromIndex?: number): boolean; +} + +interface Uint16Array { + /** + * Determines whether an array includes a certain element, returning true or false as appropriate. + * @param searchElement The element to search for. + * @param fromIndex The position in this array at which to begin searching for searchElement. + */ + includes(searchElement: number, fromIndex?: number): boolean; +} + +interface Int32Array { + /** + * Determines whether an array includes a certain element, returning true or false as appropriate. + * @param searchElement The element to search for. + * @param fromIndex The position in this array at which to begin searching for searchElement. + */ + includes(searchElement: number, fromIndex?: number): boolean; +} + +interface Uint32Array { + /** + * Determines whether an array includes a certain element, returning true or false as appropriate. + * @param searchElement The element to search for. + * @param fromIndex The position in this array at which to begin searching for searchElement. + */ + includes(searchElement: number, fromIndex?: number): boolean; +} + +interface Float32Array { + /** + * Determines whether an array includes a certain element, returning true or false as appropriate. + * @param searchElement The element to search for. + * @param fromIndex The position in this array at which to begin searching for searchElement. + */ + includes(searchElement: number, fromIndex?: number): boolean; +} + +interface Float64Array { + /** + * Determines whether an array includes a certain element, returning true or false as appropriate. + * @param searchElement The element to search for. + * @param fromIndex The position in this array at which to begin searching for searchElement. + */ + includes(searchElement: number, fromIndex?: number): boolean; +} \ No newline at end of file diff --git a/node_modules/typescript/lib/lib.es2016.d.ts b/node_modules/typescript/lib/lib.es2016.d.ts new file mode 100644 index 0000000..b2d59b8 --- /dev/null +++ b/node_modules/typescript/lib/lib.es2016.d.ts @@ -0,0 +1,22 @@ +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + + + +/// + + +/// +/// \ No newline at end of file diff --git a/node_modules/typescript/lib/lib.es2016.full.d.ts b/node_modules/typescript/lib/lib.es2016.full.d.ts new file mode 100644 index 0000000..6ecfe0a --- /dev/null +++ b/node_modules/typescript/lib/lib.es2016.full.d.ts @@ -0,0 +1,25 @@ +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + + + +/// + + +/// +/// +/// +/// +/// \ No newline at end of file diff --git a/node_modules/typescript/lib/lib.es2017.d.ts b/node_modules/typescript/lib/lib.es2017.d.ts new file mode 100644 index 0000000..850e81d --- /dev/null +++ b/node_modules/typescript/lib/lib.es2017.d.ts @@ -0,0 +1,26 @@ +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + + + +/// + + +/// +/// +/// +/// +/// +/// diff --git a/node_modules/typescript/lib/lib.es2017.full.d.ts b/node_modules/typescript/lib/lib.es2017.full.d.ts new file mode 100644 index 0000000..46d2ee8 --- /dev/null +++ b/node_modules/typescript/lib/lib.es2017.full.d.ts @@ -0,0 +1,25 @@ +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + + + +/// + + +/// +/// +/// +/// +/// \ No newline at end of file diff --git a/node_modules/typescript/lib/lib.es2017.intl.d.ts b/node_modules/typescript/lib/lib.es2017.intl.d.ts new file mode 100644 index 0000000..25b1fa5 --- /dev/null +++ b/node_modules/typescript/lib/lib.es2017.intl.d.ts @@ -0,0 +1,32 @@ +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + + + +/// + + +declare namespace Intl { + type DateTimeFormatPartTypes = "day" | "dayPeriod" | "era" | "hour" | "literal" | "minute" | "month" | "second" | "timeZoneName" | "weekday" | "year"; + + interface DateTimeFormatPart { + type: DateTimeFormatPartTypes; + value: string; + } + + interface DateTimeFormat { + formatToParts(date?: Date | number): DateTimeFormatPart[]; + } +} diff --git a/node_modules/typescript/lib/lib.es2017.object.d.ts b/node_modules/typescript/lib/lib.es2017.object.d.ts new file mode 100644 index 0000000..65aa1f9 --- /dev/null +++ b/node_modules/typescript/lib/lib.es2017.object.d.ts @@ -0,0 +1,51 @@ +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + + + +/// + + +interface ObjectConstructor { + /** + * Returns an array of values of the enumerable properties of an object + * @param o Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object. + */ + values(o: { [s: string]: T } | ArrayLike): T[]; + + /** + * Returns an array of values of the enumerable properties of an object + * @param o Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object. + */ + values(o: {}): any[]; + + /** + * Returns an array of key/values of the enumerable properties of an object + * @param o Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object. + */ + entries(o: { [s: string]: T } | ArrayLike): [string, T][]; + + /** + * Returns an array of key/values of the enumerable properties of an object + * @param o Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object. + */ + entries(o: {}): [string, any][]; + + /** + * Returns an object containing all own property descriptors of an object + * @param o Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object. + */ + getOwnPropertyDescriptors(o: T): {[P in keyof T]: TypedPropertyDescriptor} & { [x: string]: PropertyDescriptor }; +} diff --git a/node_modules/typescript/lib/lib.es2017.sharedmemory.d.ts b/node_modules/typescript/lib/lib.es2017.sharedmemory.d.ts new file mode 100644 index 0000000..ef304d3 --- /dev/null +++ b/node_modules/typescript/lib/lib.es2017.sharedmemory.d.ts @@ -0,0 +1,138 @@ +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + + + +/// + + +/// +/// + +interface SharedArrayBuffer { + /** + * Read-only. The length of the ArrayBuffer (in bytes). + */ + readonly byteLength: number; + + /* + * The SharedArrayBuffer constructor's length property whose value is 1. + */ + length: number; + /** + * Returns a section of an SharedArrayBuffer. + */ + slice(begin: number, end?: number): SharedArrayBuffer; + readonly [Symbol.species]: SharedArrayBuffer; + readonly [Symbol.toStringTag]: "SharedArrayBuffer"; +} + +interface SharedArrayBufferConstructor { + readonly prototype: SharedArrayBuffer; + new (byteLength: number): SharedArrayBuffer; +} +declare var SharedArrayBuffer: SharedArrayBufferConstructor; + +interface ArrayBufferTypes { + SharedArrayBuffer: SharedArrayBuffer; +} + +interface Atomics { + /** + * Adds a value to the value at the given position in the array, returning the original value. + * Until this atomic operation completes, any other read or write operation against the array + * will block. + */ + add(typedArray: Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array, index: number, value: number): number; + + /** + * Stores the bitwise AND of a value with the value at the given position in the array, + * returning the original value. Until this atomic operation completes, any other read or + * write operation against the array will block. + */ + and(typedArray: Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array, index: number, value: number): number; + + /** + * Replaces the value at the given position in the array if the original value equals the given + * expected value, returning the original value. Until this atomic operation completes, any + * other read or write operation against the array will block. + */ + compareExchange(typedArray: Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array, index: number, expectedValue: number, replacementValue: number): number; + + /** + * Replaces the value at the given position in the array, returning the original value. Until + * this atomic operation completes, any other read or write operation against the array will + * block. + */ + exchange(typedArray: Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array, index: number, value: number): number; + + /** + * Returns a value indicating whether high-performance algorithms can use atomic operations + * (`true`) or must use locks (`false`) for the given number of bytes-per-element of a typed + * array. + */ + isLockFree(size: number): boolean; + + /** + * Returns the value at the given position in the array. Until this atomic operation completes, + * any other read or write operation against the array will block. + */ + load(typedArray: Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array, index: number): number; + + /** + * Stores the bitwise OR of a value with the value at the given position in the array, + * returning the original value. Until this atomic operation completes, any other read or write + * operation against the array will block. + */ + or(typedArray: Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array, index: number, value: number): number; + + /** + * Stores a value at the given position in the array, returning the new value. Until this + * atomic operation completes, any other read or write operation against the array will block. + */ + store(typedArray: Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array, index: number, value: number): number; + + /** + * Subtracts a value from the value at the given position in the array, returning the original + * value. Until this atomic operation completes, any other read or write operation against the + * array will block. + */ + sub(typedArray: Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array, index: number, value: number): number; + + /** + * If the value at the given position in the array is equal to the provided value, the current + * agent is put to sleep causing execution to suspend until the timeout expires (returning + * `"timed-out"`) or until the agent is awoken (returning `"ok"`); otherwise, returns + * `"not-equal"`. + */ + wait(typedArray: Int32Array, index: number, value: number, timeout?: number): "ok" | "not-equal" | "timed-out"; + + /** + * Wakes up sleeping agents that are waiting on the given index of the array, returning the + * number of agents that were awoken. + */ + wake(typedArray: Int32Array, index: number, count: number): number; + + /** + * Stores the bitwise XOR of a value with the value at the given position in the array, + * returning the original value. Until this atomic operation completes, any other read or write + * operation against the array will block. + */ + xor(typedArray: Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array, index: number, value: number): number; + + readonly [Symbol.toStringTag]: "Atomics"; +} + +declare var Atomics: Atomics; \ No newline at end of file diff --git a/node_modules/typescript/lib/lib.es2017.string.d.ts b/node_modules/typescript/lib/lib.es2017.string.d.ts new file mode 100644 index 0000000..dad64f0 --- /dev/null +++ b/node_modules/typescript/lib/lib.es2017.string.d.ts @@ -0,0 +1,47 @@ +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + + + +/// + + +interface String { + /** + * Pads the current string with a given string (possibly repeated) so that the resulting string reaches a given length. + * The padding is applied from the start (left) of the current string. + * + * @param maxLength The length of the resulting string once the current string has been padded. + * If this parameter is smaller than the current string's length, the current string will be returned as it is. + * + * @param fillString The string to pad the current string with. + * If this string is too long, it will be truncated and the left-most part will be applied. + * The default value for this parameter is " " (U+0020). + */ + padStart(maxLength: number, fillString?: string): string; + + /** + * Pads the current string with a given string (possibly repeated) so that the resulting string reaches a given length. + * The padding is applied from the end (right) of the current string. + * + * @param maxLength The length of the resulting string once the current string has been padded. + * If this parameter is smaller than the current string's length, the current string will be returned as it is. + * + * @param fillString The string to pad the current string with. + * If this string is too long, it will be truncated and the left-most part will be applied. + * The default value for this parameter is " " (U+0020). + */ + padEnd(maxLength: number, fillString?: string): string; +} diff --git a/node_modules/typescript/lib/lib.es2017.typedarrays.d.ts b/node_modules/typescript/lib/lib.es2017.typedarrays.d.ts new file mode 100644 index 0000000..4f6f6e7 --- /dev/null +++ b/node_modules/typescript/lib/lib.es2017.typedarrays.d.ts @@ -0,0 +1,55 @@ +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + + + +/// + + +interface Int8ArrayConstructor { + new (): Int8Array; +} + +interface Uint8ArrayConstructor { + new (): Uint8Array; +} + +interface Uint8ClampedArrayConstructor { + new (): Uint8ClampedArray; +} + +interface Int16ArrayConstructor { + new (): Int16Array; +} + +interface Uint16ArrayConstructor { + new (): Uint16Array; +} + +interface Int32ArrayConstructor { + new (): Int32Array; +} + +interface Uint32ArrayConstructor { + new (): Uint32Array; +} + +interface Float32ArrayConstructor { + new (): Float32Array; +} + +interface Float64ArrayConstructor { + new (): Float64Array; +} diff --git a/node_modules/typescript/lib/lib.es2018.d.ts b/node_modules/typescript/lib/lib.es2018.d.ts new file mode 100644 index 0000000..2a694e3 --- /dev/null +++ b/node_modules/typescript/lib/lib.es2018.d.ts @@ -0,0 +1,24 @@ +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + + + +/// + + +/// +/// +/// +/// diff --git a/node_modules/typescript/lib/lib.es2018.full.d.ts b/node_modules/typescript/lib/lib.es2018.full.d.ts new file mode 100644 index 0000000..277d541 --- /dev/null +++ b/node_modules/typescript/lib/lib.es2018.full.d.ts @@ -0,0 +1,25 @@ +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + + + +/// + + +/// +/// +/// +/// +/// \ No newline at end of file diff --git a/node_modules/typescript/lib/lib.es2018.intl.d.ts b/node_modules/typescript/lib/lib.es2018.intl.d.ts new file mode 100644 index 0000000..84e95f4 --- /dev/null +++ b/node_modules/typescript/lib/lib.es2018.intl.d.ts @@ -0,0 +1,51 @@ +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + + + +/// + + +declare namespace Intl { + interface PluralRulesOptions { + localeMatcher?: 'lookup' | 'best fit'; + type?: 'cardinal' | 'ordinal'; + } + + interface ResolvedPluralRulesOptions { + locale: string; + pluralCategories: string[]; + type: 'cardinal' | 'ordinal'; + minimumIntegerDigits: number; + minimumFractionDigits: number; + maximumFractionDigits: number; + minimumSignificantDigits: number; + maximumSignificantDigits: number; + } + + interface PluralRules { + resolvedOptions(): ResolvedPluralRulesOptions; + select(n: number): string; + } + + const PluralRules: { + new (locales?: string | string[], options?: PluralRulesOptions): PluralRules; + (locales?: string | string[], options?: PluralRulesOptions): PluralRules; + supportedLocalesOf( + locales: string | string[], + options?: PluralRulesOptions, + ): string[]; + }; +} diff --git a/node_modules/typescript/lib/lib.es2018.promise.d.ts b/node_modules/typescript/lib/lib.es2018.promise.d.ts new file mode 100644 index 0000000..d73b4d4 --- /dev/null +++ b/node_modules/typescript/lib/lib.es2018.promise.d.ts @@ -0,0 +1,32 @@ +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + + + +/// + + +/** + * Represents the completion of an asynchronous operation + */ +interface Promise { + /** + * Attaches a callback that is invoked when the Promise is settled (fulfilled or rejected). The + * resolved value cannot be modified from the callback. + * @param onfinally The callback to execute when the Promise is settled (fulfilled or rejected). + * @returns A Promise for the completion of the callback. + */ + finally(onfinally?: (() => void) | undefined | null): Promise +} diff --git a/node_modules/typescript/lib/lib.es2018.regexp.d.ts b/node_modules/typescript/lib/lib.es2018.regexp.d.ts new file mode 100644 index 0000000..4ba698f --- /dev/null +++ b/node_modules/typescript/lib/lib.es2018.regexp.d.ts @@ -0,0 +1,39 @@ +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + + + +/// + + +interface RegExpMatchArray { + groups?: { + [key: string]: string + } +} + +interface RegExpExecArray { + groups?: { + [key: string]: string + } +} + +interface RegExp { + /** + * Returns a Boolean value indicating the state of the dotAll flag (s) used with a regular expression. + * Default is false. Read-only. + */ + readonly dotAll: boolean; +} \ No newline at end of file diff --git a/node_modules/typescript/lib/lib.es5.d.ts b/node_modules/typescript/lib/lib.es5.d.ts new file mode 100644 index 0000000..d1a9d6f --- /dev/null +++ b/node_modules/typescript/lib/lib.es5.d.ts @@ -0,0 +1,4243 @@ +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + + + +/// + + +///////////////////////////// +/// ECMAScript APIs +///////////////////////////// + +declare const NaN: number; +declare const Infinity: number; + +/** + * Evaluates JavaScript code and executes it. + * @param x A String value that contains valid JavaScript code. + */ +declare function eval(x: string): any; + +/** + * 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. + */ +declare function parseInt(s: string, radix?: number): number; + +/** + * Converts a string to a floating-point number. + * @param string A string that contains a floating-point number. + */ +declare function parseFloat(string: string): number; + +/** + * Returns a Boolean value that indicates whether a value is the reserved value NaN (not a number). + * @param number A numeric value. + */ +declare function isNaN(number: number): boolean; + +/** + * Determines whether a supplied number is finite. + * @param number Any numeric value. + */ +declare function isFinite(number: number): boolean; + +/** + * Gets the unencoded version of an encoded Uniform Resource Identifier (URI). + * @param encodedURI A value representing an encoded URI. + */ +declare function decodeURI(encodedURI: string): string; + +/** + * Gets the unencoded version of an encoded component of a Uniform Resource Identifier (URI). + * @param encodedURIComponent A value representing an encoded URI component. + */ +declare function decodeURIComponent(encodedURIComponent: string): string; + +/** + * Encodes a text string as a valid Uniform Resource Identifier (URI) + * @param uri A value representing an encoded URI. + */ +declare function encodeURI(uri: string): string; + +/** + * Encodes a text string as a valid component of a Uniform Resource Identifier (URI). + * @param uriComponent A value representing an encoded URI component. + */ +declare function encodeURIComponent(uriComponent: string): string; + +/** + * Computes a new string in which certain characters have been replaced by a hexadecimal escape sequence. + * @param string A string value + */ +declare function escape(string: string): string; + +/** + * Computes a new string in which hexadecimal escape sequences are replaced with the character that it represents. + * @param string A string value + */ +declare function unescape(string: string): string; + +interface Symbol { + /** Returns a string representation of an object. */ + toString(): string; + + /** Returns the primitive value of the specified object. */ + valueOf(): symbol; +} + +declare type PropertyKey = string | number | symbol; + +interface PropertyDescriptor { + configurable?: boolean; + enumerable?: boolean; + value?: any; + writable?: boolean; + get?(): any; + set?(v: any): void; +} + +interface PropertyDescriptorMap { + [s: string]: PropertyDescriptor; +} + +interface Object { + /** The initial value of Object.prototype.constructor is the standard built-in Object constructor. */ + constructor: Function; + + /** Returns a string representation of an object. */ + toString(): string; + + /** Returns a date converted to a string using the current locale. */ + toLocaleString(): string; + + /** Returns the primitive value of the specified object. */ + valueOf(): Object; + + /** + * Determines whether an object has a property with the specified name. + * @param v A property name. + */ + hasOwnProperty(v: PropertyKey): boolean; + + /** + * Determines whether an object exists in another object's prototype chain. + * @param v Another object whose prototype chain is to be checked. + */ + isPrototypeOf(v: Object): boolean; + + /** + * Determines whether a specified property is enumerable. + * @param v A property name. + */ + propertyIsEnumerable(v: PropertyKey): boolean; +} + +interface ObjectConstructor { + new(value?: any): Object; + (): any; + (value: any): any; + + /** A reference to the prototype for a class of objects. */ + readonly prototype: Object; + + /** + * Returns the prototype of an object. + * @param o The object that references the prototype. + */ + getPrototypeOf(o: any): any; + + /** + * Gets the own property descriptor of the specified object. + * An own property descriptor is one that is defined directly on the object and is not inherited from the object's prototype. + * @param o Object that contains the property. + * @param p Name of the property. + */ + getOwnPropertyDescriptor(o: any, p: PropertyKey): PropertyDescriptor | undefined; + + /** + * Returns the names of the own properties of an object. The own properties of an object are those that are defined directly + * on that object, and are not inherited from the object's prototype. The properties of an object include both fields (objects) and functions. + * @param o Object that contains the own properties. + */ + getOwnPropertyNames(o: any): string[]; + + /** + * Creates an object that has the specified prototype or that has null prototype. + * @param o Object to use as a prototype. May be null. + */ + create(o: object | null): any; + + /** + * Creates an object that has the specified prototype, and that optionally contains specified properties. + * @param o Object to use as a prototype. May be null + * @param properties JavaScript object that contains one or more property descriptors. + */ + create(o: object | null, properties: PropertyDescriptorMap & ThisType): any; + + /** + * Adds a property to an object, or modifies attributes of an existing property. + * @param o Object on which to add or modify the property. This can be a native JavaScript object (that is, a user-defined object or a built in object) or a DOM object. + * @param p The property name. + * @param attributes Descriptor for the property. It can be for a data property or an accessor property. + */ + defineProperty(o: any, p: PropertyKey, attributes: PropertyDescriptor & ThisType): any; + + /** + * Adds one or more properties to an object, and/or modifies attributes of existing properties. + * @param o Object on which to add or modify the properties. This can be a native JavaScript object or a DOM object. + * @param properties JavaScript object that contains one or more descriptor objects. Each descriptor object describes a data property or an accessor property. + */ + defineProperties(o: any, properties: PropertyDescriptorMap & ThisType): any; + + /** + * Prevents the modification of attributes of existing properties, and prevents the addition of new properties. + * @param o Object on which to lock the attributes. + */ + seal(o: T): T; + + /** + * Prevents the modification of existing property attributes and values, and prevents the addition of new properties. + * @param o Object on which to lock the attributes. + */ + freeze(a: T[]): ReadonlyArray; + + /** + * Prevents the modification of existing property attributes and values, and prevents the addition of new properties. + * @param o Object on which to lock the attributes. + */ + freeze(f: T): T; + + /** + * Prevents the modification of existing property attributes and values, and prevents the addition of new properties. + * @param o Object on which to lock the attributes. + */ + freeze(o: T): Readonly; + + /** + * Prevents the addition of new properties to an object. + * @param o Object to make non-extensible. + */ + preventExtensions(o: T): T; + + /** + * Returns true if existing property attributes cannot be modified in an object and new properties cannot be added to the object. + * @param o Object to test. + */ + isSealed(o: any): boolean; + + /** + * Returns true if existing property attributes and values cannot be modified in an object, and new properties cannot be added to the object. + * @param o Object to test. + */ + isFrozen(o: any): boolean; + + /** + * Returns a value that indicates whether new properties can be added to an object. + * @param o Object to test. + */ + isExtensible(o: any): boolean; + + /** + * Returns the names of the enumerable properties and methods of an object. + * @param o Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object. + */ + keys(o: {}): string[]; +} + +/** + * Provides functionality common to all JavaScript objects. + */ +declare const Object: ObjectConstructor; + +/** + * Creates a new function. + */ +interface Function { + /** + * Calls the function, substituting the specified object for the this value of the function, and the specified array for the arguments of the function. + * @param thisArg The object to be used as the this object. + * @param argArray A set of arguments to be passed to the function. + */ + apply(this: Function, thisArg: any, argArray?: any): any; + + /** + * Calls a method of an object, substituting another object for the current object. + * @param thisArg The object to be used as the current object. + * @param argArray A list of arguments to be passed to the method. + */ + call(this: Function, thisArg: any, ...argArray: any[]): any; + + /** + * For a given function, creates a bound function that has the same body as the original function. + * The this object of the bound function is associated with the specified object, and has the specified initial parameters. + * @param thisArg An object to which the this keyword can refer inside the new function. + * @param argArray A list of arguments to be passed to the new function. + */ + bind(this: Function, thisArg: any, ...argArray: any[]): any; + + /** Returns a string representation of a function. */ + toString(): string; + + prototype: any; + readonly length: number; + + // Non-standard extensions + arguments: any; + caller: Function; +} + +interface FunctionConstructor { + /** + * Creates a new function. + * @param args A list of arguments the function accepts. + */ + new(...args: string[]): Function; + (...args: string[]): Function; + readonly prototype: Function; +} + +declare const Function: FunctionConstructor; + +interface CallableFunction extends Function { + /** + * Calls the function with the specified object as the this value and the elements of specified array as the arguments. + * @param thisArg The object to be used as the this object. + * @param args An array of argument values to be passed to the function. + */ + apply(this: (this: T) => R, thisArg: T): R; + apply(this: (this: T, ...args: A) => R, thisArg: T, args: A): R; + + /** + * Calls the function with the specified object as the this value and the specified rest arguments as the arguments. + * @param thisArg The object to be used as the this object. + * @param args Argument values to be passed to the function. + */ + call(this: (this: T, ...args: A) => R, thisArg: T, ...args: A): R; + + /** + * For a given function, creates a bound function that has the same body as the original function. + * The this object of the bound function is associated with the specified object, and has the specified initial parameters. + * @param thisArg The object to be used as the this object. + * @param args Arguments to bind to the parameters of the function. + */ + bind(this: (this: T, ...args: A) => R, thisArg: T): (...args: A) => R; + bind(this: (this: T, arg0: A0, ...args: A) => R, thisArg: T, arg0: A0): (...args: A) => R; + bind(this: (this: T, arg0: A0, arg1: A1, ...args: A) => R, thisArg: T, arg0: A0, arg1: A1): (...args: A) => R; + bind(this: (this: T, arg0: A0, arg1: A1, arg2: A2, ...args: A) => R, thisArg: T, arg0: A0, arg1: A1, arg2: A2): (...args: A) => R; + bind(this: (this: T, arg0: A0, arg1: A1, arg2: A2, arg3: A3, ...args: A) => R, thisArg: T, arg0: A0, arg1: A1, arg2: A2, arg3: A3): (...args: A) => R; + bind(this: (this: T, ...args: AX[]) => R, thisArg: T, ...args: AX[]): (...args: AX[]) => R; +} + +interface NewableFunction extends Function { + /** + * Calls the function with the specified object as the this value and the elements of specified array as the arguments. + * @param thisArg The object to be used as the this object. + * @param args An array of argument values to be passed to the function. + */ + apply(this: new () => T, thisArg: T): void; + apply(this: new (...args: A) => T, thisArg: T, args: A): void; + + /** + * Calls the function with the specified object as the this value and the specified rest arguments as the arguments. + * @param thisArg The object to be used as the this object. + * @param args Argument values to be passed to the function. + */ + call(this: new (...args: A) => T, thisArg: T, ...args: A): void; + + /** + * For a given function, creates a bound function that has the same body as the original function. + * The this object of the bound function is associated with the specified object, and has the specified initial parameters. + * @param thisArg The object to be used as the this object. + * @param args Arguments to bind to the parameters of the function. + */ + bind(this: new (...args: A) => R, thisArg: any): new (...args: A) => R; + bind(this: new (arg0: A0, ...args: A) => R, thisArg: any, arg0: A0): new (...args: A) => R; + bind(this: new (arg0: A0, arg1: A1, ...args: A) => R, thisArg: any, arg0: A0, arg1: A1): new (...args: A) => R; + bind(this: new (arg0: A0, arg1: A1, arg2: A2, ...args: A) => R, thisArg: any, arg0: A0, arg1: A1, arg2: A2): new (...args: A) => R; + bind(this: new (arg0: A0, arg1: A1, arg2: A2, arg3: A3, ...args: A) => R, thisArg: any, arg0: A0, arg1: A1, arg2: A2, arg3: A3): new (...args: A) => R; + bind(this: new (...args: AX[]) => R, thisArg: any, ...args: AX[]): new (...args: AX[]) => R; +} + +interface IArguments { + [index: number]: any; + length: number; + callee: Function; +} + +interface String { + /** Returns a string representation of a string. */ + toString(): string; + + /** + * Returns the character at the specified index. + * @param pos The zero-based index of the desired character. + */ + charAt(pos: number): string; + + /** + * Returns the Unicode value of the character at the specified location. + * @param index The zero-based index of the desired character. If there is no character at the specified index, NaN is returned. + */ + charCodeAt(index: number): number; + + /** + * Returns a string that contains the concatenation of two or more strings. + * @param strings The strings to append to the end of the string. + */ + concat(...strings: string[]): string; + + /** + * Returns the position of the first occurrence of a substring. + * @param searchString The substring to search for in the string + * @param position The index at which to begin searching the String object. If omitted, search starts at the beginning of the string. + */ + indexOf(searchString: string, position?: number): number; + + /** + * Returns the last occurrence of a substring in the string. + * @param searchString The substring to search for. + * @param position The index at which to begin searching. If omitted, the search begins at the end of the string. + */ + lastIndexOf(searchString: string, position?: number): number; + + /** + * Determines whether two strings are equivalent in the current locale. + * @param that String to compare to target string + */ + localeCompare(that: string): number; + + /** + * Matches a string with a regular expression, and returns an array containing the results of that search. + * @param regexp A variable name or string literal containing the regular expression pattern and flags. + */ + match(regexp: string | RegExp): RegExpMatchArray | null; + + /** + * Replaces text in a string, using a regular expression or search string. + * @param searchValue A string to search for. + * @param replaceValue A string containing the text to replace for every successful match of searchValue in this string. + */ + replace(searchValue: string | RegExp, replaceValue: string): string; + + /** + * Replaces text in a string, using a regular expression or search string. + * @param searchValue A string to search for. + * @param replacer A function that returns the replacement text. + */ + replace(searchValue: string | RegExp, replacer: (substring: string, ...args: any[]) => string): string; + + /** + * Finds the first substring match in a regular expression search. + * @param regexp The regular expression pattern and applicable flags. + */ + search(regexp: string | RegExp): number; + + /** + * Returns a section of a string. + * @param start The index to the beginning of the specified portion of stringObj. + * @param end The index to the end of the specified portion of stringObj. The substring includes the characters up to, but not including, the character indicated by end. + * If this value is not specified, the substring continues to the end of stringObj. + */ + slice(start?: number, end?: number): string; + + /** + * Split a string into substrings using the specified separator and return them as an array. + * @param separator A string that identifies character or characters to use in separating the string. If omitted, a single-element array containing the entire string is returned. + * @param limit A value used to limit the number of elements returned in the array. + */ + split(separator: string | RegExp, limit?: number): string[]; + + /** + * Returns the substring at the specified location within a String object. + * @param start The zero-based index number indicating the beginning of the substring. + * @param end Zero-based index number indicating the end of the substring. The substring includes the characters up to, but not including, the character indicated by end. + * If end is omitted, the characters from start through the end of the original string are returned. + */ + substring(start: number, end?: number): string; + + /** Converts all the alphabetic characters in a string to lowercase. */ + toLowerCase(): string; + + /** Converts all alphabetic characters to lowercase, taking into account the host environment's current locale. */ + toLocaleLowerCase(): string; + + /** Converts all the alphabetic characters in a string to uppercase. */ + toUpperCase(): string; + + /** Returns a string where all alphabetic characters have been converted to uppercase, taking into account the host environment's current locale. */ + toLocaleUpperCase(): string; + + /** Removes the leading and trailing white space and line terminator characters from a string. */ + trim(): string; + + /** Returns the length of a String object. */ + readonly length: number; + + // IE extensions + /** + * Gets a substring beginning at the specified location and having the specified length. + * @param from The starting position of the desired substring. The index of the first character in the string is zero. + * @param length The number of characters to include in the returned substring. + */ + substr(from: number, length?: number): string; + + /** Returns the primitive value of the specified object. */ + valueOf(): string; + + readonly [index: number]: string; +} + +interface StringConstructor { + new(value?: any): String; + (value?: any): string; + readonly prototype: String; + fromCharCode(...codes: number[]): string; +} + +/** + * Allows manipulation and formatting of text strings and determination and location of substrings within strings. + */ +declare const String: StringConstructor; + +interface Boolean { + /** Returns the primitive value of the specified object. */ + valueOf(): boolean; +} + +interface BooleanConstructor { + new(value?: any): Boolean; + (value?: any): boolean; + readonly prototype: Boolean; +} + +declare const Boolean: BooleanConstructor; + +interface Number { + /** + * Returns a string representation of an object. + * @param radix Specifies a radix for converting numeric values to strings. This value is only used for numbers. + */ + toString(radix?: number): string; + + /** + * Returns a string representing a number in fixed-point notation. + * @param fractionDigits Number of digits after the decimal point. Must be in the range 0 - 20, inclusive. + */ + toFixed(fractionDigits?: number): string; + + /** + * Returns a string containing a number represented in exponential notation. + * @param fractionDigits Number of digits after the decimal point. Must be in the range 0 - 20, inclusive. + */ + toExponential(fractionDigits?: number): string; + + /** + * Returns a string containing a number represented either in exponential or fixed-point notation with a specified number of digits. + * @param precision Number of significant digits. Must be in the range 1 - 21, inclusive. + */ + toPrecision(precision?: number): string; + + /** Returns the primitive value of the specified object. */ + valueOf(): number; +} + +interface NumberConstructor { + new(value?: any): Number; + (value?: any): number; + readonly prototype: Number; + + /** The largest number that can be represented in JavaScript. Equal to approximately 1.79E+308. */ + readonly MAX_VALUE: number; + + /** The closest number to zero that can be represented in JavaScript. Equal to approximately 5.00E-324. */ + readonly MIN_VALUE: number; + + /** + * A value that is not a number. + * In equality comparisons, NaN does not equal any value, including itself. To test whether a value is equivalent to NaN, use the isNaN function. + */ + readonly NaN: number; + + /** + * A value that is less than the largest negative number that can be represented in JavaScript. + * JavaScript displays NEGATIVE_INFINITY values as -infinity. + */ + readonly NEGATIVE_INFINITY: number; + + /** + * A value greater than the largest number that can be represented in JavaScript. + * JavaScript displays POSITIVE_INFINITY values as infinity. + */ + readonly POSITIVE_INFINITY: number; +} + +/** An object that represents a number of any kind. All JavaScript numbers are 64-bit floating-point numbers. */ +declare const Number: NumberConstructor; + +interface TemplateStringsArray extends ReadonlyArray { + readonly raw: ReadonlyArray; +} + +/** + * The type of `import.meta`. + * + * If you need to declare that a given property exists on `import.meta`, + * this type may be augmented via interface merging. + */ +interface ImportMeta { +} + +interface Math { + /** The mathematical constant e. This is Euler's number, the base of natural logarithms. */ + readonly E: number; + /** The natural logarithm of 10. */ + readonly LN10: number; + /** The natural logarithm of 2. */ + readonly LN2: number; + /** The base-2 logarithm of e. */ + readonly LOG2E: number; + /** The base-10 logarithm of e. */ + readonly LOG10E: number; + /** Pi. This is the ratio of the circumference of a circle to its diameter. */ + readonly PI: number; + /** The square root of 0.5, or, equivalently, one divided by the square root of 2. */ + readonly SQRT1_2: number; + /** The square root of 2. */ + readonly SQRT2: number; + /** + * Returns the absolute value of a number (the value without regard to whether it is positive or negative). + * For example, the absolute value of -5 is the same as the absolute value of 5. + * @param x A numeric expression for which the absolute value is needed. + */ + abs(x: number): number; + /** + * Returns the arc cosine (or inverse cosine) of a number. + * @param x A numeric expression. + */ + acos(x: number): number; + /** + * Returns the arcsine of a number. + * @param x A numeric expression. + */ + asin(x: number): number; + /** + * Returns the arctangent of a number. + * @param x A numeric expression for which the arctangent is needed. + */ + atan(x: number): number; + /** + * Returns the angle (in radians) from the X axis to a point. + * @param y A numeric expression representing the cartesian y-coordinate. + * @param x A numeric expression representing the cartesian x-coordinate. + */ + atan2(y: number, x: number): number; + /** + * Returns the smallest integer greater than or equal to its numeric argument. + * @param x A numeric expression. + */ + ceil(x: number): number; + /** + * Returns the cosine of a number. + * @param x A numeric expression that contains an angle measured in radians. + */ + cos(x: number): number; + /** + * Returns e (the base of natural logarithms) raised to a power. + * @param x A numeric expression representing the power of e. + */ + exp(x: number): number; + /** + * Returns the greatest integer less than or equal to its numeric argument. + * @param x A numeric expression. + */ + floor(x: number): number; + /** + * Returns the natural logarithm (base e) of a number. + * @param x A numeric expression. + */ + log(x: number): number; + /** + * Returns the larger of a set of supplied numeric expressions. + * @param values Numeric expressions to be evaluated. + */ + max(...values: number[]): number; + /** + * Returns the smaller of a set of supplied numeric expressions. + * @param values Numeric expressions to be evaluated. + */ + min(...values: number[]): number; + /** + * Returns the value of a base expression taken to a specified power. + * @param x The base value of the expression. + * @param y The exponent value of the expression. + */ + pow(x: number, y: number): number; + /** Returns a pseudorandom number between 0 and 1. */ + random(): number; + /** + * Returns a supplied numeric expression rounded to the nearest number. + * @param x The value to be rounded to the nearest number. + */ + round(x: number): number; + /** + * Returns the sine of a number. + * @param x A numeric expression that contains an angle measured in radians. + */ + sin(x: number): number; + /** + * Returns the square root of a number. + * @param x A numeric expression. + */ + sqrt(x: number): number; + /** + * Returns the tangent of a number. + * @param x A numeric expression that contains an angle measured in radians. + */ + tan(x: number): number; +} +/** An intrinsic object that provides basic mathematics functionality and constants. */ +declare const Math: Math; + +/** Enables basic storage and retrieval of dates and times. */ +interface Date { + /** Returns a string representation of a date. The format of the string depends on the locale. */ + toString(): string; + /** Returns a date as a string value. */ + toDateString(): string; + /** Returns a time as a string value. */ + toTimeString(): string; + /** Returns a value as a string value appropriate to the host environment's current locale. */ + toLocaleString(): string; + /** Returns a date as a string value appropriate to the host environment's current locale. */ + toLocaleDateString(): string; + /** Returns a time as a string value appropriate to the host environment's current locale. */ + toLocaleTimeString(): string; + /** Returns the stored time value in milliseconds since midnight, January 1, 1970 UTC. */ + valueOf(): number; + /** Gets the time value in milliseconds. */ + getTime(): number; + /** Gets the year, using local time. */ + getFullYear(): number; + /** Gets the year using Universal Coordinated Time (UTC). */ + getUTCFullYear(): number; + /** Gets the month, using local time. */ + getMonth(): number; + /** Gets the month of a Date object using Universal Coordinated Time (UTC). */ + getUTCMonth(): number; + /** Gets the day-of-the-month, using local time. */ + getDate(): number; + /** Gets the day-of-the-month, using Universal Coordinated Time (UTC). */ + getUTCDate(): number; + /** Gets the day of the week, using local time. */ + getDay(): number; + /** Gets the day of the week using Universal Coordinated Time (UTC). */ + getUTCDay(): number; + /** Gets the hours in a date, using local time. */ + getHours(): number; + /** Gets the hours value in a Date object using Universal Coordinated Time (UTC). */ + getUTCHours(): number; + /** Gets the minutes of a Date object, using local time. */ + getMinutes(): number; + /** Gets the minutes of a Date object using Universal Coordinated Time (UTC). */ + getUTCMinutes(): number; + /** Gets the seconds of a Date object, using local time. */ + getSeconds(): number; + /** Gets the seconds of a Date object using Universal Coordinated Time (UTC). */ + getUTCSeconds(): number; + /** Gets the milliseconds of a Date, using local time. */ + getMilliseconds(): number; + /** Gets the milliseconds of a Date object using Universal Coordinated Time (UTC). */ + getUTCMilliseconds(): number; + /** Gets the difference in minutes between the time on the local computer and Universal Coordinated Time (UTC). */ + getTimezoneOffset(): number; + /** + * Sets the date and time value in the Date object. + * @param time A numeric value representing the number of elapsed milliseconds since midnight, January 1, 1970 GMT. + */ + setTime(time: number): number; + /** + * Sets the milliseconds value in the Date object using local time. + * @param ms A numeric value equal to the millisecond value. + */ + setMilliseconds(ms: number): number; + /** + * Sets the milliseconds value in the Date object using Universal Coordinated Time (UTC). + * @param ms A numeric value equal to the millisecond value. + */ + setUTCMilliseconds(ms: number): number; + + /** + * Sets the seconds value in the Date object using local time. + * @param sec A numeric value equal to the seconds value. + * @param ms A numeric value equal to the milliseconds value. + */ + setSeconds(sec: number, ms?: number): number; + /** + * Sets the seconds value in the Date object using Universal Coordinated Time (UTC). + * @param sec A numeric value equal to the seconds value. + * @param ms A numeric value equal to the milliseconds value. + */ + setUTCSeconds(sec: number, ms?: number): number; + /** + * Sets the minutes value in the Date object using local time. + * @param min A numeric value equal to the minutes value. + * @param sec A numeric value equal to the seconds value. + * @param ms A numeric value equal to the milliseconds value. + */ + setMinutes(min: number, sec?: number, ms?: number): number; + /** + * Sets the minutes value in the Date object using Universal Coordinated Time (UTC). + * @param min A numeric value equal to the minutes value. + * @param sec A numeric value equal to the seconds value. + * @param ms A numeric value equal to the milliseconds value. + */ + setUTCMinutes(min: number, sec?: number, ms?: number): number; + /** + * Sets the hour value in the Date object using local time. + * @param hours A numeric value equal to the hours value. + * @param min A numeric value equal to the minutes value. + * @param sec A numeric value equal to the seconds value. + * @param ms A numeric value equal to the milliseconds value. + */ + setHours(hours: number, min?: number, sec?: number, ms?: number): number; + /** + * Sets the hours value in the Date object using Universal Coordinated Time (UTC). + * @param hours A numeric value equal to the hours value. + * @param min A numeric value equal to the minutes value. + * @param sec A numeric value equal to the seconds value. + * @param ms A numeric value equal to the milliseconds value. + */ + setUTCHours(hours: number, min?: number, sec?: number, ms?: number): number; + /** + * Sets the numeric day-of-the-month value of the Date object using local time. + * @param date A numeric value equal to the day of the month. + */ + setDate(date: number): number; + /** + * Sets the numeric day of the month in the Date object using Universal Coordinated Time (UTC). + * @param date A numeric value equal to the day of the month. + */ + setUTCDate(date: number): number; + /** + * Sets the month value in the Date object using local time. + * @param month A numeric value equal to the month. The value for January is 0, and other month values follow consecutively. + * @param date A numeric value representing the day of the month. If this value is not supplied, the value from a call to the getDate method is used. + */ + setMonth(month: number, date?: number): number; + /** + * Sets the month value in the Date object using Universal Coordinated Time (UTC). + * @param month A numeric value equal to the month. The value for January is 0, and other month values follow consecutively. + * @param date A numeric value representing the day of the month. If it is not supplied, the value from a call to the getUTCDate method is used. + */ + setUTCMonth(month: number, date?: number): number; + /** + * Sets the year of the Date object using local time. + * @param year A numeric value for the year. + * @param month A zero-based numeric value for the month (0 for January, 11 for December). Must be specified if numDate is specified. + * @param date A numeric value equal for the day of the month. + */ + setFullYear(year: number, month?: number, date?: number): number; + /** + * Sets the year value in the Date object using Universal Coordinated Time (UTC). + * @param year A numeric value equal to the year. + * @param month A numeric value equal to the month. The value for January is 0, and other month values follow consecutively. Must be supplied if numDate is supplied. + * @param date A numeric value equal to the day of the month. + */ + setUTCFullYear(year: number, month?: number, date?: number): number; + /** Returns a date converted to a string using Universal Coordinated Time (UTC). */ + toUTCString(): string; + /** Returns a date as a string value in ISO format. */ + toISOString(): string; + /** Used by the JSON.stringify method to enable the transformation of an object's data for JavaScript Object Notation (JSON) serialization. */ + toJSON(key?: any): string; +} + +interface DateConstructor { + new(): Date; + new(value: number | string): Date; + new(year: number, month: number, date?: number, hours?: number, minutes?: number, seconds?: number, ms?: number): Date; + (): string; + readonly prototype: Date; + /** + * Parses a string containing a date, and returns the number of milliseconds between that date and midnight, January 1, 1970. + * @param s A date string + */ + parse(s: string): number; + /** + * Returns the number of milliseconds between midnight, January 1, 1970 Universal Coordinated Time (UTC) (or GMT) and the specified date. + * @param year The full year designation is required for cross-century date accuracy. If year is between 0 and 99 is used, then year is assumed to be 1900 + year. + * @param month The month as an number between 0 and 11 (January to December). + * @param date The date as an number between 1 and 31. + * @param hours Must be supplied if minutes is supplied. An number from 0 to 23 (midnight to 11pm) that specifies the hour. + * @param minutes Must be supplied if seconds is supplied. An number from 0 to 59 that specifies the minutes. + * @param seconds Must be supplied if milliseconds is supplied. An number from 0 to 59 that specifies the seconds. + * @param ms An number from 0 to 999 that specifies the milliseconds. + */ + UTC(year: number, month: number, date?: number, hours?: number, minutes?: number, seconds?: number, ms?: number): number; + now(): number; +} + +declare const Date: DateConstructor; + +interface RegExpMatchArray extends Array { + index?: number; + input?: string; +} + +interface RegExpExecArray extends Array { + index: number; + input: string; +} + +interface RegExp { + /** + * Executes a search on a string using a regular expression pattern, and returns an array containing the results of that search. + * @param string The String object or string literal on which to perform the search. + */ + exec(string: string): RegExpExecArray | null; + + /** + * Returns a Boolean value that indicates whether or not a pattern exists in a searched string. + * @param string String on which to perform the search. + */ + test(string: string): boolean; + + /** Returns a copy of the text of the regular expression pattern. Read-only. The regExp argument is a Regular expression object. It can be a variable name or a literal. */ + readonly source: string; + + /** Returns a Boolean value indicating the state of the global flag (g) used with a regular expression. Default is false. Read-only. */ + readonly global: boolean; + + /** Returns a Boolean value indicating the state of the ignoreCase flag (i) used with a regular expression. Default is false. Read-only. */ + readonly ignoreCase: boolean; + + /** Returns a Boolean value indicating the state of the multiline flag (m) used with a regular expression. Default is false. Read-only. */ + readonly multiline: boolean; + + lastIndex: number; + + // Non-standard extensions + compile(): this; +} + +interface RegExpConstructor { + new(pattern: RegExp | string): RegExp; + new(pattern: string, flags?: string): RegExp; + (pattern: RegExp | string): RegExp; + (pattern: string, flags?: string): RegExp; + readonly prototype: RegExp; + + // Non-standard extensions + $1: string; + $2: string; + $3: string; + $4: string; + $5: string; + $6: string; + $7: string; + $8: string; + $9: string; + lastMatch: string; +} + +declare const RegExp: RegExpConstructor; + +interface Error { + name: string; + message: string; + stack?: string; +} + +interface ErrorConstructor { + new(message?: string): Error; + (message?: string): Error; + readonly prototype: Error; +} + +declare const Error: ErrorConstructor; + +interface EvalError extends Error { +} + +interface EvalErrorConstructor { + new(message?: string): EvalError; + (message?: string): EvalError; + readonly prototype: EvalError; +} + +declare const EvalError: EvalErrorConstructor; + +interface RangeError extends Error { +} + +interface RangeErrorConstructor { + new(message?: string): RangeError; + (message?: string): RangeError; + readonly prototype: RangeError; +} + +declare const RangeError: RangeErrorConstructor; + +interface ReferenceError extends Error { +} + +interface ReferenceErrorConstructor { + new(message?: string): ReferenceError; + (message?: string): ReferenceError; + readonly prototype: ReferenceError; +} + +declare const ReferenceError: ReferenceErrorConstructor; + +interface SyntaxError extends Error { +} + +interface SyntaxErrorConstructor { + new(message?: string): SyntaxError; + (message?: string): SyntaxError; + readonly prototype: SyntaxError; +} + +declare const SyntaxError: SyntaxErrorConstructor; + +interface TypeError extends Error { +} + +interface TypeErrorConstructor { + new(message?: string): TypeError; + (message?: string): TypeError; + readonly prototype: TypeError; +} + +declare const TypeError: TypeErrorConstructor; + +interface URIError extends Error { +} + +interface URIErrorConstructor { + new(message?: string): URIError; + (message?: string): URIError; + readonly prototype: URIError; +} + +declare const URIError: URIErrorConstructor; + +interface JSON { + /** + * Converts a JavaScript Object Notation (JSON) string into an object. + * @param text A valid JSON string. + * @param reviver A function that transforms the results. This function is called for each member of the object. + * If a member contains nested objects, the nested objects are transformed before the parent object is. + */ + parse(text: string, reviver?: (key: any, value: any) => any): any; + /** + * Converts a JavaScript value to a JavaScript Object Notation (JSON) string. + * @param value A JavaScript value, usually an object or array, to be converted. + * @param replacer A function that transforms the results. + * @param space Adds indentation, white space, and line break characters to the return-value JSON text to make it easier to read. + */ + stringify(value: any, replacer?: (key: string, value: any) => any, space?: string | number): string; + /** + * Converts a JavaScript value to a JavaScript Object Notation (JSON) string. + * @param value A JavaScript value, usually an object or array, to be converted. + * @param replacer An array of strings and numbers that acts as a approved list for selecting the object properties that will be stringified. + * @param space Adds indentation, white space, and line break characters to the return-value JSON text to make it easier to read. + */ + stringify(value: any, replacer?: (number | string)[] | null, space?: string | number): string; +} + +/** + * An intrinsic object that provides functions to convert JavaScript values to and from the JavaScript Object Notation (JSON) format. + */ +declare const JSON: JSON; + + +///////////////////////////// +/// ECMAScript Array API (specially handled by compiler) +///////////////////////////// + +interface ReadonlyArray { + /** + * Gets the length of the array. This is a number one higher than the highest element defined in an array. + */ + readonly length: number; + /** + * Returns a string representation of an array. + */ + toString(): string; + /** + * Returns a string representation of an array. The elements are converted to string using their toLocalString methods. + */ + toLocaleString(): string; + /** + * Combines two or more arrays. + * @param items Additional items to add to the end of array1. + */ + concat(...items: ConcatArray[]): T[]; + /** + * Combines two or more arrays. + * @param items Additional items to add to the end of array1. + */ + concat(...items: (T | ConcatArray)[]): T[]; + /** + * Adds all the elements of an array separated by the specified separator string. + * @param separator A string used to separate one element of an array from the next in the resulting String. If omitted, the array elements are separated with a comma. + */ + join(separator?: string): string; + /** + * Returns a section of an array. + * @param start The beginning of the specified portion of the array. + * @param end The end of the specified portion of the array. + */ + slice(start?: number, end?: number): T[]; + /** + * Returns the index of the first occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at index 0. + */ + indexOf(searchElement: T, fromIndex?: number): number; + /** + * Returns the index of the last occurrence of a specified value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at the last index in the array. + */ + lastIndexOf(searchElement: T, fromIndex?: number): number; + /** + * Determines whether all the members of an array satisfy the specified test. + * @param callbackfn A function that accepts up to three arguments. The every method calls the callbackfn function for each element in array1 until the callbackfn returns false, or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + every(callbackfn: (value: T, index: number, array: ReadonlyArray) => boolean, thisArg?: any): boolean; + /** + * Determines whether the specified callback function returns true for any element of an array. + * @param callbackfn A function that accepts up to three arguments. The some method calls the callbackfn function for each element in array1 until the callbackfn returns true, or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + some(callbackfn: (value: T, index: number, array: ReadonlyArray) => boolean, thisArg?: any): boolean; + /** + * Performs the specified action for each element in an array. + * @param callbackfn A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + forEach(callbackfn: (value: T, index: number, array: ReadonlyArray) => void, thisArg?: any): void; + /** + * Calls a defined callback function on each element of an array, and returns an array that contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + map(callbackfn: (value: T, index: number, array: ReadonlyArray) => U, thisArg?: any): U[]; + /** + * Returns the elements of an array that meet the condition specified in a callback function. + * @param callbackfn A function that accepts up to three arguments. The filter method calls the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + filter(callbackfn: (value: T, index: number, array: ReadonlyArray) => value is S, thisArg?: any): S[]; + /** + * Returns the elements of an array that meet the condition specified in a callback function. + * @param callbackfn A function that accepts up to three arguments. The filter method calls the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + filter(callbackfn: (value: T, index: number, array: ReadonlyArray) => any, thisArg?: any): T[]; + /** + * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. + */ + reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: ReadonlyArray) => T): T; + reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: ReadonlyArray) => T, initialValue: T): T; + /** + * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. + */ + reduce(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: ReadonlyArray) => U, initialValue: U): U; + /** + * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. + */ + reduceRight(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: ReadonlyArray) => T): T; + reduceRight(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: ReadonlyArray) => T, initialValue: T): T; + /** + * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. + */ + reduceRight(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: ReadonlyArray) => U, initialValue: U): U; + + readonly [n: number]: T; +} + +interface ConcatArray { + readonly length: number; + readonly [n: number]: T; + join(separator?: string): string; + slice(start?: number, end?: number): T[]; +} + +interface Array { + /** + * Gets or sets the length of the array. This is a number one higher than the highest element defined in an array. + */ + length: number; + /** + * Returns a string representation of an array. + */ + toString(): string; + /** + * Returns a string representation of an array. The elements are converted to string using their toLocalString methods. + */ + toLocaleString(): string; + /** + * Removes the last element from an array and returns it. + */ + pop(): T | undefined; + /** + * Appends new elements to an array, and returns the new length of the array. + * @param items New elements of the Array. + */ + push(...items: T[]): number; + /** + * Combines two or more arrays. + * @param items Additional items to add to the end of array1. + */ + concat(...items: ConcatArray[]): T[]; + /** + * Combines two or more arrays. + * @param items Additional items to add to the end of array1. + */ + concat(...items: (T | ConcatArray)[]): T[]; + /** + * Adds all the elements of an array separated by the specified separator string. + * @param separator A string used to separate one element of an array from the next in the resulting String. If omitted, the array elements are separated with a comma. + */ + join(separator?: string): string; + /** + * Reverses the elements in an Array. + */ + reverse(): T[]; + /** + * Removes the first element from an array and returns it. + */ + shift(): T | undefined; + /** + * Returns a section of an array. + * @param start The beginning of the specified portion of the array. + * @param end The end of the specified portion of the array. + */ + slice(start?: number, end?: number): T[]; + /** + * Sorts an array. + * @param compareFn The name of the function used to determine the order of the elements. If omitted, the elements are sorted in ascending, ASCII character order. + */ + sort(compareFn?: (a: T, b: T) => number): this; + /** + * Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements. + * @param start The zero-based location in the array from which to start removing elements. + * @param deleteCount The number of elements to remove. + */ + splice(start: number, deleteCount?: number): T[]; + /** + * Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements. + * @param start The zero-based location in the array from which to start removing elements. + * @param deleteCount The number of elements to remove. + * @param items Elements to insert into the array in place of the deleted elements. + */ + splice(start: number, deleteCount: number, ...items: T[]): T[]; + /** + * Inserts new elements at the start of an array. + * @param items Elements to insert at the start of the Array. + */ + unshift(...items: T[]): number; + /** + * Returns the index of the first occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at index 0. + */ + indexOf(searchElement: T, fromIndex?: number): number; + /** + * Returns the index of the last occurrence of a specified value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at the last index in the array. + */ + lastIndexOf(searchElement: T, fromIndex?: number): number; + /** + * Determines whether all the members of an array satisfy the specified test. + * @param callbackfn A function that accepts up to three arguments. The every method calls the callbackfn function for each element in array1 until the callbackfn returns false, or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + every(callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg?: any): boolean; + /** + * Determines whether the specified callback function returns true for any element of an array. + * @param callbackfn A function that accepts up to three arguments. The some method calls the callbackfn function for each element in array1 until the callbackfn returns true, or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + some(callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg?: any): boolean; + /** + * Performs the specified action for each element in an array. + * @param callbackfn A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + forEach(callbackfn: (value: T, index: number, array: T[]) => void, thisArg?: any): void; + /** + * Calls a defined callback function on each element of an array, and returns an array that contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + map(callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): U[]; + /** + * Returns the elements of an array that meet the condition specified in a callback function. + * @param callbackfn A function that accepts up to three arguments. The filter method calls the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + filter(callbackfn: (value: T, index: number, array: T[]) => value is S, thisArg?: any): S[]; + /** + * Returns the elements of an array that meet the condition specified in a callback function. + * @param callbackfn A function that accepts up to three arguments. The filter method calls the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + filter(callbackfn: (value: T, index: number, array: T[]) => any, thisArg?: any): T[]; + /** + * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. + */ + reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T): T; + reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T, initialValue: T): T; + /** + * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. + */ + reduce(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: T[]) => U, initialValue: U): U; + /** + * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. + */ + reduceRight(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T): T; + reduceRight(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T, initialValue: T): T; + /** + * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. + */ + reduceRight(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: T[]) => U, initialValue: U): U; + + [n: number]: T; +} + +interface ArrayConstructor { + new(arrayLength?: number): any[]; + new (arrayLength: number): T[]; + new (...items: T[]): T[]; + (arrayLength?: number): any[]; + (arrayLength: number): T[]; + (...items: T[]): T[]; + isArray(arg: any): arg is Array; + readonly prototype: Array; +} + +declare const Array: ArrayConstructor; + +interface TypedPropertyDescriptor { + enumerable?: boolean; + configurable?: boolean; + writable?: boolean; + value?: T; + get?: () => T; + set?: (value: T) => void; +} + +declare type ClassDecorator = (target: TFunction) => TFunction | void; +declare type PropertyDecorator = (target: Object, propertyKey: string | symbol) => void; +declare type MethodDecorator = (target: Object, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor) => TypedPropertyDescriptor | void; +declare type ParameterDecorator = (target: Object, propertyKey: string | symbol, parameterIndex: number) => void; + +declare type PromiseConstructorLike = new (executor: (resolve: (value?: T | PromiseLike) => void, reject: (reason?: any) => void) => void) => PromiseLike; + +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) => TResult1 | PromiseLike) | undefined | null, onrejected?: ((reason: any) => TResult2 | PromiseLike) | undefined | null): 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) => TResult1 | PromiseLike) | undefined | null, onrejected?: ((reason: any) => TResult2 | PromiseLike) | undefined | null): 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) => TResult | PromiseLike) | undefined | null): Promise; +} + +interface ArrayLike { + readonly length: number; + readonly [n: number]: T; +} + +/** + * Make all properties in T optional + */ +type Partial = { + [P in keyof T]?: T[P]; +}; + +/** + * Make all properties in T required + */ +type Required = { + [P in keyof T]-?: T[P]; +}; + +/** + * Make all properties in T readonly + */ +type Readonly = { + readonly [P in keyof T]: T[P]; +}; + +/** + * From T, pick a set of properties whose keys are in the union K + */ +type Pick = { + [P in K]: T[P]; +}; + +/** + * Construct a type with a set of properties K of type T + */ +type Record = { + [P in K]: T; +}; + +/** + * Exclude from T those types that are assignable to U + */ +type Exclude = T extends U ? never : T; + +/** + * Extract from T those types that are assignable to U + */ +type Extract = T extends U ? T : never; + +/** + * Exclude null and undefined from T + */ +type NonNullable = T extends null | undefined ? never : T; + +/** + * Obtain the parameters of a function type in a tuple + */ +type Parameters any> = T extends (...args: infer P) => any ? P : never; + +/** + * Obtain the parameters of a constructor function type in a tuple + */ +type ConstructorParameters any> = T extends new (...args: infer P) => any ? P : never; + +/** + * Obtain the return type of a function type + */ +type ReturnType any> = T extends (...args: any[]) => infer R ? R : any; + +/** + * Obtain the return type of a constructor function type + */ +type InstanceType any> = T extends new (...args: any[]) => infer R ? R : any; + +/** + * Marker for contextual 'this' type + */ +interface ThisType { } + +/** + * Represents a raw buffer of binary data, which is used to store data for the + * different typed arrays. ArrayBuffers cannot be read from or written to directly, + * but can be passed to a typed array or DataView Object to interpret the raw + * buffer as needed. + */ +interface ArrayBuffer { + /** + * Read-only. The length of the ArrayBuffer (in bytes). + */ + readonly byteLength: number; + + /** + * Returns a section of an ArrayBuffer. + */ + slice(begin: number, end?: number): ArrayBuffer; +} + +/** + * Allowed ArrayBuffer types for the buffer of an ArrayBufferView and related Typed Arrays. + */ +interface ArrayBufferTypes { + ArrayBuffer: ArrayBuffer; +} +type ArrayBufferLike = ArrayBufferTypes[keyof ArrayBufferTypes]; + +interface ArrayBufferConstructor { + readonly prototype: ArrayBuffer; + new(byteLength: number): ArrayBuffer; + isView(arg: any): arg is ArrayBufferView; +} +declare const ArrayBuffer: ArrayBufferConstructor; + +interface ArrayBufferView { + /** + * The ArrayBuffer instance referenced by the array. + */ + buffer: ArrayBufferLike; + + /** + * The length in bytes of the array. + */ + byteLength: number; + + /** + * The offset in bytes of the array. + */ + byteOffset: number; +} + +interface DataView { + readonly buffer: ArrayBuffer; + readonly byteLength: number; + readonly byteOffset: number; + /** + * Gets the Float32 value at the specified byte offset from the start of the view. There is + * no alignment constraint; multi-byte values may be fetched from any offset. + * @param byteOffset The place in the buffer at which the value should be retrieved. + */ + getFloat32(byteOffset: number, littleEndian?: boolean): number; + + /** + * Gets the Float64 value at the specified byte offset from the start of the view. There is + * no alignment constraint; multi-byte values may be fetched from any offset. + * @param byteOffset The place in the buffer at which the value should be retrieved. + */ + getFloat64(byteOffset: number, littleEndian?: boolean): number; + + /** + * Gets the Int8 value at the specified byte offset from the start of the view. There is + * no alignment constraint; multi-byte values may be fetched from any offset. + * @param byteOffset The place in the buffer at which the value should be retrieved. + */ + getInt8(byteOffset: number): number; + + /** + * Gets the Int16 value at the specified byte offset from the start of the view. There is + * no alignment constraint; multi-byte values may be fetched from any offset. + * @param byteOffset The place in the buffer at which the value should be retrieved. + */ + getInt16(byteOffset: number, littleEndian?: boolean): number; + /** + * Gets the Int32 value at the specified byte offset from the start of the view. There is + * no alignment constraint; multi-byte values may be fetched from any offset. + * @param byteOffset The place in the buffer at which the value should be retrieved. + */ + getInt32(byteOffset: number, littleEndian?: boolean): number; + + /** + * Gets the Uint8 value at the specified byte offset from the start of the view. There is + * no alignment constraint; multi-byte values may be fetched from any offset. + * @param byteOffset The place in the buffer at which the value should be retrieved. + */ + getUint8(byteOffset: number): number; + + /** + * Gets the Uint16 value at the specified byte offset from the start of the view. There is + * no alignment constraint; multi-byte values may be fetched from any offset. + * @param byteOffset The place in the buffer at which the value should be retrieved. + */ + getUint16(byteOffset: number, littleEndian?: boolean): number; + + /** + * Gets the Uint32 value at the specified byte offset from the start of the view. There is + * no alignment constraint; multi-byte values may be fetched from any offset. + * @param byteOffset The place in the buffer at which the value should be retrieved. + */ + getUint32(byteOffset: number, littleEndian?: boolean): number; + + /** + * Stores an Float32 value at the specified byte offset from the start of the view. + * @param byteOffset The place in the buffer at which the value should be set. + * @param value The value to set. + * @param littleEndian If false or undefined, a big-endian value should be written, + * otherwise a little-endian value should be written. + */ + setFloat32(byteOffset: number, value: number, littleEndian?: boolean): void; + + /** + * Stores an Float64 value at the specified byte offset from the start of the view. + * @param byteOffset The place in the buffer at which the value should be set. + * @param value The value to set. + * @param littleEndian If false or undefined, a big-endian value should be written, + * otherwise a little-endian value should be written. + */ + setFloat64(byteOffset: number, value: number, littleEndian?: boolean): void; + + /** + * Stores an Int8 value at the specified byte offset from the start of the view. + * @param byteOffset The place in the buffer at which the value should be set. + * @param value The value to set. + */ + setInt8(byteOffset: number, value: number): void; + + /** + * Stores an Int16 value at the specified byte offset from the start of the view. + * @param byteOffset The place in the buffer at which the value should be set. + * @param value The value to set. + * @param littleEndian If false or undefined, a big-endian value should be written, + * otherwise a little-endian value should be written. + */ + setInt16(byteOffset: number, value: number, littleEndian?: boolean): void; + + /** + * Stores an Int32 value at the specified byte offset from the start of the view. + * @param byteOffset The place in the buffer at which the value should be set. + * @param value The value to set. + * @param littleEndian If false or undefined, a big-endian value should be written, + * otherwise a little-endian value should be written. + */ + setInt32(byteOffset: number, value: number, littleEndian?: boolean): void; + + /** + * Stores an Uint8 value at the specified byte offset from the start of the view. + * @param byteOffset The place in the buffer at which the value should be set. + * @param value The value to set. + */ + setUint8(byteOffset: number, value: number): void; + + /** + * Stores an Uint16 value at the specified byte offset from the start of the view. + * @param byteOffset The place in the buffer at which the value should be set. + * @param value The value to set. + * @param littleEndian If false or undefined, a big-endian value should be written, + * otherwise a little-endian value should be written. + */ + setUint16(byteOffset: number, value: number, littleEndian?: boolean): void; + + /** + * Stores an Uint32 value at the specified byte offset from the start of the view. + * @param byteOffset The place in the buffer at which the value should be set. + * @param value The value to set. + * @param littleEndian If false or undefined, a big-endian value should be written, + * otherwise a little-endian value should be written. + */ + setUint32(byteOffset: number, value: number, littleEndian?: boolean): void; +} + +interface DataViewConstructor { + new(buffer: ArrayBufferLike, byteOffset?: number, byteLength?: number): DataView; +} +declare const DataView: DataViewConstructor; + +/** + * A typed array of 8-bit integer values. The contents are initialized to 0. If the requested + * number of bytes could not be allocated an exception is raised. + */ +interface Int8Array { + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * The ArrayBuffer instance referenced by the array. + */ + readonly buffer: ArrayBufferLike; + + /** + * The length in bytes of the array. + */ + readonly byteLength: number; + + /** + * The offset in bytes of the array. + */ + readonly byteOffset: number; + + /** + * 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): this; + + /** + * Determines whether all the members of an array satisfy the specified test. + * @param callbackfn A function that accepts up to three arguments. The every method calls + * the callbackfn function for each element in array1 until the callbackfn returns false, + * or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + every(callbackfn: (value: number, index: number, array: Int8Array) => boolean, thisArg?: any): boolean; + + /** + * 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: number, start?: number, end?: number): this; + + /** + * Returns the elements of an array that meet the condition specified in a callback function. + * @param callbackfn A function that accepts up to three arguments. The filter method calls + * the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + filter(callbackfn: (value: number, index: number, array: Int8Array) => any, thisArg?: any): Int8Array; + + /** + * 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: number, index: number, obj: Int8Array) => boolean, thisArg?: any): number | 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, + * findIndex immediately returns that element index. Otherwise, findIndex returns -1. + * @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: number, index: number, obj: Int8Array) => boolean, thisArg?: any): number; + + /** + * Performs the specified action for each element in an array. + * @param callbackfn A function that accepts up to three arguments. forEach calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + forEach(callbackfn: (value: number, index: number, array: Int8Array) => void, thisArg?: any): void; + + /** + * Returns the index of the first occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + indexOf(searchElement: number, fromIndex?: number): number; + + /** + * Adds all the elements of an array separated by the specified separator string. + * @param separator A string used to separate one element of an array from the next in the + * resulting String. If omitted, the array elements are separated with a comma. + */ + join(separator?: string): string; + + /** + * Returns the index of the last occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + lastIndexOf(searchElement: number, fromIndex?: number): number; + + /** + * The length of the array. + */ + readonly length: number; + + /** + * Calls a defined callback function on each element of an array, and returns an array that + * contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + map(callbackfn: (value: number, index: number, array: Int8Array) => number, thisArg?: any): Int8Array; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int8Array) => number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int8Array) => number, initialValue: number): number; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Int8Array) => U, initialValue: U): U; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an + * argument instead of an array value. + */ + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int8Array) => number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int8Array) => number, initialValue: number): number; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Int8Array) => U, initialValue: U): U; + + /** + * Reverses the elements in an Array. + */ + reverse(): Int8Array; + + /** + * Sets a value or an array of values. + * @param array A typed or untyped array of values to set. + * @param offset The index in the current array at which the values are to be written. + */ + set(array: ArrayLike, offset?: number): void; + + /** + * Returns a section of an array. + * @param start The beginning of the specified portion of the array. + * @param end The end of the specified portion of the array. + */ + slice(start?: number, end?: number): Int8Array; + + /** + * Determines whether the specified callback function returns true for any element of an array. + * @param callbackfn A function that accepts up to three arguments. The some method calls the + * callbackfn function for each element in array1 until the callbackfn returns true, or until + * the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + some(callbackfn: (value: number, index: number, array: Int8Array) => boolean, thisArg?: any): boolean; + + /** + * Sorts an array. + * @param compareFn The name of the function used to determine the order of the elements. If + * omitted, the elements are sorted in ascending, ASCII character order. + */ + sort(compareFn?: (a: number, b: number) => number): this; + + /** + * Gets a new Int8Array view of the ArrayBuffer store for this array, referencing the elements + * at begin, inclusive, up to end, exclusive. + * @param begin The index of the beginning of the array. + * @param end The index of the end of the array. + */ + subarray(begin: number, end?: number): Int8Array; + + /** + * Converts a number to a string by using the current locale. + */ + toLocaleString(): string; + + /** + * Returns a string representation of an array. + */ + toString(): string; + + [index: number]: number; +} +interface Int8ArrayConstructor { + readonly prototype: Int8Array; + new(length: number): Int8Array; + new(arrayOrArrayBuffer: ArrayLike | ArrayBufferLike): Int8Array; + new(buffer: ArrayBufferLike, byteOffset: number, length?: number): Int8Array; + + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * Returns a new array from a set of elements. + * @param items A set of elements to include in the new array object. + */ + of(...items: number[]): Int8Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or 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(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Int8Array; + + +} +declare const Int8Array: Int8ArrayConstructor; + +/** + * A typed array of 8-bit unsigned integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Uint8Array { + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * The ArrayBuffer instance referenced by the array. + */ + readonly buffer: ArrayBufferLike; + + /** + * The length in bytes of the array. + */ + readonly byteLength: number; + + /** + * The offset in bytes of the array. + */ + readonly byteOffset: number; + + /** + * 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): this; + + /** + * Determines whether all the members of an array satisfy the specified test. + * @param callbackfn A function that accepts up to three arguments. The every method calls + * the callbackfn function for each element in array1 until the callbackfn returns false, + * or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + every(callbackfn: (value: number, index: number, array: Uint8Array) => boolean, thisArg?: any): boolean; + + /** + * 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: number, start?: number, end?: number): this; + + /** + * Returns the elements of an array that meet the condition specified in a callback function. + * @param callbackfn A function that accepts up to three arguments. The filter method calls + * the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + filter(callbackfn: (value: number, index: number, array: Uint8Array) => any, thisArg?: any): Uint8Array; + + /** + * 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: number, index: number, obj: Uint8Array) => boolean, thisArg?: any): number | 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, + * findIndex immediately returns that element index. Otherwise, findIndex returns -1. + * @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: number, index: number, obj: Uint8Array) => boolean, thisArg?: any): number; + + /** + * Performs the specified action for each element in an array. + * @param callbackfn A function that accepts up to three arguments. forEach calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + forEach(callbackfn: (value: number, index: number, array: Uint8Array) => void, thisArg?: any): void; + + /** + * Returns the index of the first occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + indexOf(searchElement: number, fromIndex?: number): number; + + /** + * Adds all the elements of an array separated by the specified separator string. + * @param separator A string used to separate one element of an array from the next in the + * resulting String. If omitted, the array elements are separated with a comma. + */ + join(separator?: string): string; + + /** + * Returns the index of the last occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + lastIndexOf(searchElement: number, fromIndex?: number): number; + + /** + * The length of the array. + */ + readonly length: number; + + /** + * Calls a defined callback function on each element of an array, and returns an array that + * contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + map(callbackfn: (value: number, index: number, array: Uint8Array) => number, thisArg?: any): Uint8Array; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8Array) => number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8Array) => number, initialValue: number): number; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint8Array) => U, initialValue: U): U; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an + * argument instead of an array value. + */ + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8Array) => number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8Array) => number, initialValue: number): number; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint8Array) => U, initialValue: U): U; + + /** + * Reverses the elements in an Array. + */ + reverse(): Uint8Array; + + /** + * Sets a value or an array of values. + * @param array A typed or untyped array of values to set. + * @param offset The index in the current array at which the values are to be written. + */ + set(array: ArrayLike, offset?: number): void; + + /** + * Returns a section of an array. + * @param start The beginning of the specified portion of the array. + * @param end The end of the specified portion of the array. + */ + slice(start?: number, end?: number): Uint8Array; + + /** + * Determines whether the specified callback function returns true for any element of an array. + * @param callbackfn A function that accepts up to three arguments. The some method calls the + * callbackfn function for each element in array1 until the callbackfn returns true, or until + * the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + some(callbackfn: (value: number, index: number, array: Uint8Array) => boolean, thisArg?: any): boolean; + + /** + * Sorts an array. + * @param compareFn The name of the function used to determine the order of the elements. If + * omitted, the elements are sorted in ascending, ASCII character order. + */ + sort(compareFn?: (a: number, b: number) => number): this; + + /** + * Gets a new Uint8Array view of the ArrayBuffer store for this array, referencing the elements + * at begin, inclusive, up to end, exclusive. + * @param begin The index of the beginning of the array. + * @param end The index of the end of the array. + */ + subarray(begin: number, end?: number): Uint8Array; + + /** + * Converts a number to a string by using the current locale. + */ + toLocaleString(): string; + + /** + * Returns a string representation of an array. + */ + toString(): string; + + [index: number]: number; +} + +interface Uint8ArrayConstructor { + readonly prototype: Uint8Array; + new(length: number): Uint8Array; + new(arrayOrArrayBuffer: ArrayLike | ArrayBufferLike): Uint8Array; + new(buffer: ArrayBufferLike, byteOffset: number, length?: number): Uint8Array; + + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * Returns a new array from a set of elements. + * @param items A set of elements to include in the new array object. + */ + of(...items: number[]): Uint8Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or 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(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint8Array; + +} +declare const Uint8Array: Uint8ArrayConstructor; + +/** + * A typed array of 8-bit unsigned integer (clamped) values. The contents are initialized to 0. + * If the requested number of bytes could not be allocated an exception is raised. + */ +interface Uint8ClampedArray { + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * The ArrayBuffer instance referenced by the array. + */ + readonly buffer: ArrayBufferLike; + + /** + * The length in bytes of the array. + */ + readonly byteLength: number; + + /** + * The offset in bytes of the array. + */ + readonly byteOffset: number; + + /** + * 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): this; + + /** + * Determines whether all the members of an array satisfy the specified test. + * @param callbackfn A function that accepts up to three arguments. The every method calls + * the callbackfn function for each element in array1 until the callbackfn returns false, + * or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + every(callbackfn: (value: number, index: number, array: Uint8ClampedArray) => boolean, thisArg?: any): boolean; + + /** + * 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: number, start?: number, end?: number): this; + + /** + * Returns the elements of an array that meet the condition specified in a callback function. + * @param callbackfn A function that accepts up to three arguments. The filter method calls + * the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + filter(callbackfn: (value: number, index: number, array: Uint8ClampedArray) => any, thisArg?: any): Uint8ClampedArray; + + /** + * 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: number, index: number, obj: Uint8ClampedArray) => boolean, thisArg?: any): number | 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, + * findIndex immediately returns that element index. Otherwise, findIndex returns -1. + * @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: number, index: number, obj: Uint8ClampedArray) => boolean, thisArg?: any): number; + + /** + * Performs the specified action for each element in an array. + * @param callbackfn A function that accepts up to three arguments. forEach calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + forEach(callbackfn: (value: number, index: number, array: Uint8ClampedArray) => void, thisArg?: any): void; + + /** + * Returns the index of the first occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + indexOf(searchElement: number, fromIndex?: number): number; + + /** + * Adds all the elements of an array separated by the specified separator string. + * @param separator A string used to separate one element of an array from the next in the + * resulting String. If omitted, the array elements are separated with a comma. + */ + join(separator?: string): string; + + /** + * Returns the index of the last occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + lastIndexOf(searchElement: number, fromIndex?: number): number; + + /** + * The length of the array. + */ + readonly length: number; + + /** + * Calls a defined callback function on each element of an array, and returns an array that + * contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + map(callbackfn: (value: number, index: number, array: Uint8ClampedArray) => number, thisArg?: any): Uint8ClampedArray; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => number, initialValue: number): number; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => U, initialValue: U): U; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an + * argument instead of an array value. + */ + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => number, initialValue: number): number; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => U, initialValue: U): U; + + /** + * Reverses the elements in an Array. + */ + reverse(): Uint8ClampedArray; + + /** + * Sets a value or an array of values. + * @param array A typed or untyped array of values to set. + * @param offset The index in the current array at which the values are to be written. + */ + set(array: ArrayLike, offset?: number): void; + + /** + * Returns a section of an array. + * @param start The beginning of the specified portion of the array. + * @param end The end of the specified portion of the array. + */ + slice(start?: number, end?: number): Uint8ClampedArray; + + /** + * Determines whether the specified callback function returns true for any element of an array. + * @param callbackfn A function that accepts up to three arguments. The some method calls the + * callbackfn function for each element in array1 until the callbackfn returns true, or until + * the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + some(callbackfn: (value: number, index: number, array: Uint8ClampedArray) => boolean, thisArg?: any): boolean; + + /** + * Sorts an array. + * @param compareFn The name of the function used to determine the order of the elements. If + * omitted, the elements are sorted in ascending, ASCII character order. + */ + sort(compareFn?: (a: number, b: number) => number): this; + + /** + * Gets a new Uint8ClampedArray view of the ArrayBuffer store for this array, referencing the elements + * at begin, inclusive, up to end, exclusive. + * @param begin The index of the beginning of the array. + * @param end The index of the end of the array. + */ + subarray(begin: number, end?: number): Uint8ClampedArray; + + /** + * Converts a number to a string by using the current locale. + */ + toLocaleString(): string; + + /** + * Returns a string representation of an array. + */ + toString(): string; + + [index: number]: number; +} + +interface Uint8ClampedArrayConstructor { + readonly prototype: Uint8ClampedArray; + new(length: number): Uint8ClampedArray; + new(arrayOrArrayBuffer: ArrayLike | ArrayBufferLike): Uint8ClampedArray; + new(buffer: ArrayBufferLike, byteOffset: number, length?: number): Uint8ClampedArray; + + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * Returns a new array from a set of elements. + * @param items A set of elements to include in the new array object. + */ + of(...items: number[]): Uint8ClampedArray; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or 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(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint8ClampedArray; +} +declare const Uint8ClampedArray: Uint8ClampedArrayConstructor; + +/** + * A typed array of 16-bit signed integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Int16Array { + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * The ArrayBuffer instance referenced by the array. + */ + readonly buffer: ArrayBufferLike; + + /** + * The length in bytes of the array. + */ + readonly byteLength: number; + + /** + * The offset in bytes of the array. + */ + readonly byteOffset: number; + + /** + * 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): this; + + /** + * Determines whether all the members of an array satisfy the specified test. + * @param callbackfn A function that accepts up to three arguments. The every method calls + * the callbackfn function for each element in array1 until the callbackfn returns false, + * or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + every(callbackfn: (value: number, index: number, array: Int16Array) => boolean, thisArg?: any): boolean; + + /** + * 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: number, start?: number, end?: number): this; + + /** + * Returns the elements of an array that meet the condition specified in a callback function. + * @param callbackfn A function that accepts up to three arguments. The filter method calls + * the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + filter(callbackfn: (value: number, index: number, array: Int16Array) => any, thisArg?: any): Int16Array; + + /** + * 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: number, index: number, obj: Int16Array) => boolean, thisArg?: any): number | 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, + * findIndex immediately returns that element index. Otherwise, findIndex returns -1. + * @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: number, index: number, obj: Int16Array) => boolean, thisArg?: any): number; + + /** + * Performs the specified action for each element in an array. + * @param callbackfn A function that accepts up to three arguments. forEach calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + forEach(callbackfn: (value: number, index: number, array: Int16Array) => void, thisArg?: any): void; + /** + * Returns the index of the first occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + indexOf(searchElement: number, fromIndex?: number): number; + + /** + * Adds all the elements of an array separated by the specified separator string. + * @param separator A string used to separate one element of an array from the next in the + * resulting String. If omitted, the array elements are separated with a comma. + */ + join(separator?: string): string; + + /** + * Returns the index of the last occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + lastIndexOf(searchElement: number, fromIndex?: number): number; + + /** + * The length of the array. + */ + readonly length: number; + + /** + * Calls a defined callback function on each element of an array, and returns an array that + * contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + map(callbackfn: (value: number, index: number, array: Int16Array) => number, thisArg?: any): Int16Array; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int16Array) => number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int16Array) => number, initialValue: number): number; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Int16Array) => U, initialValue: U): U; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an + * argument instead of an array value. + */ + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int16Array) => number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int16Array) => number, initialValue: number): number; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Int16Array) => U, initialValue: U): U; + + /** + * Reverses the elements in an Array. + */ + reverse(): Int16Array; + + /** + * Sets a value or an array of values. + * @param array A typed or untyped array of values to set. + * @param offset The index in the current array at which the values are to be written. + */ + set(array: ArrayLike, offset?: number): void; + + /** + * Returns a section of an array. + * @param start The beginning of the specified portion of the array. + * @param end The end of the specified portion of the array. + */ + slice(start?: number, end?: number): Int16Array; + + /** + * Determines whether the specified callback function returns true for any element of an array. + * @param callbackfn A function that accepts up to three arguments. The some method calls the + * callbackfn function for each element in array1 until the callbackfn returns true, or until + * the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + some(callbackfn: (value: number, index: number, array: Int16Array) => boolean, thisArg?: any): boolean; + + /** + * Sorts an array. + * @param compareFn The name of the function used to determine the order of the elements. If + * omitted, the elements are sorted in ascending, ASCII character order. + */ + sort(compareFn?: (a: number, b: number) => number): this; + + /** + * Gets a new Int16Array view of the ArrayBuffer store for this array, referencing the elements + * at begin, inclusive, up to end, exclusive. + * @param begin The index of the beginning of the array. + * @param end The index of the end of the array. + */ + subarray(begin: number, end?: number): Int16Array; + + /** + * Converts a number to a string by using the current locale. + */ + toLocaleString(): string; + + /** + * Returns a string representation of an array. + */ + toString(): string; + + [index: number]: number; +} + +interface Int16ArrayConstructor { + readonly prototype: Int16Array; + new(length: number): Int16Array; + new(arrayOrArrayBuffer: ArrayLike | ArrayBufferLike): Int16Array; + new(buffer: ArrayBufferLike, byteOffset: number, length?: number): Int16Array; + + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * Returns a new array from a set of elements. + * @param items A set of elements to include in the new array object. + */ + of(...items: number[]): Int16Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or 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(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Int16Array; + + +} +declare const Int16Array: Int16ArrayConstructor; + +/** + * A typed array of 16-bit unsigned integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Uint16Array { + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * The ArrayBuffer instance referenced by the array. + */ + readonly buffer: ArrayBufferLike; + + /** + * The length in bytes of the array. + */ + readonly byteLength: number; + + /** + * The offset in bytes of the array. + */ + readonly byteOffset: number; + + /** + * 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): this; + + /** + * Determines whether all the members of an array satisfy the specified test. + * @param callbackfn A function that accepts up to three arguments. The every method calls + * the callbackfn function for each element in array1 until the callbackfn returns false, + * or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + every(callbackfn: (value: number, index: number, array: Uint16Array) => boolean, thisArg?: any): boolean; + + /** + * 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: number, start?: number, end?: number): this; + + /** + * Returns the elements of an array that meet the condition specified in a callback function. + * @param callbackfn A function that accepts up to three arguments. The filter method calls + * the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + filter(callbackfn: (value: number, index: number, array: Uint16Array) => any, thisArg?: any): Uint16Array; + + /** + * 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: number, index: number, obj: Uint16Array) => boolean, thisArg?: any): number | 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, + * findIndex immediately returns that element index. Otherwise, findIndex returns -1. + * @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: number, index: number, obj: Uint16Array) => boolean, thisArg?: any): number; + + /** + * Performs the specified action for each element in an array. + * @param callbackfn A function that accepts up to three arguments. forEach calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + forEach(callbackfn: (value: number, index: number, array: Uint16Array) => void, thisArg?: any): void; + + /** + * Returns the index of the first occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + indexOf(searchElement: number, fromIndex?: number): number; + + /** + * Adds all the elements of an array separated by the specified separator string. + * @param separator A string used to separate one element of an array from the next in the + * resulting String. If omitted, the array elements are separated with a comma. + */ + join(separator?: string): string; + + /** + * Returns the index of the last occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + lastIndexOf(searchElement: number, fromIndex?: number): number; + + /** + * The length of the array. + */ + readonly length: number; + + /** + * Calls a defined callback function on each element of an array, and returns an array that + * contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + map(callbackfn: (value: number, index: number, array: Uint16Array) => number, thisArg?: any): Uint16Array; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint16Array) => number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint16Array) => number, initialValue: number): number; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint16Array) => U, initialValue: U): U; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an + * argument instead of an array value. + */ + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint16Array) => number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint16Array) => number, initialValue: number): number; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint16Array) => U, initialValue: U): U; + + /** + * Reverses the elements in an Array. + */ + reverse(): Uint16Array; + + /** + * Sets a value or an array of values. + * @param array A typed or untyped array of values to set. + * @param offset The index in the current array at which the values are to be written. + */ + set(array: ArrayLike, offset?: number): void; + + /** + * Returns a section of an array. + * @param start The beginning of the specified portion of the array. + * @param end The end of the specified portion of the array. + */ + slice(start?: number, end?: number): Uint16Array; + + /** + * Determines whether the specified callback function returns true for any element of an array. + * @param callbackfn A function that accepts up to three arguments. The some method calls the + * callbackfn function for each element in array1 until the callbackfn returns true, or until + * the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + some(callbackfn: (value: number, index: number, array: Uint16Array) => boolean, thisArg?: any): boolean; + + /** + * Sorts an array. + * @param compareFn The name of the function used to determine the order of the elements. If + * omitted, the elements are sorted in ascending, ASCII character order. + */ + sort(compareFn?: (a: number, b: number) => number): this; + + /** + * Gets a new Uint16Array view of the ArrayBuffer store for this array, referencing the elements + * at begin, inclusive, up to end, exclusive. + * @param begin The index of the beginning of the array. + * @param end The index of the end of the array. + */ + subarray(begin: number, end?: number): Uint16Array; + + /** + * Converts a number to a string by using the current locale. + */ + toLocaleString(): string; + + /** + * Returns a string representation of an array. + */ + toString(): string; + + [index: number]: number; +} + +interface Uint16ArrayConstructor { + readonly prototype: Uint16Array; + new(length: number): Uint16Array; + new(arrayOrArrayBuffer: ArrayLike | ArrayBufferLike): Uint16Array; + new(buffer: ArrayBufferLike, byteOffset: number, length?: number): Uint16Array; + + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * Returns a new array from a set of elements. + * @param items A set of elements to include in the new array object. + */ + of(...items: number[]): Uint16Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or 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(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint16Array; + + +} +declare const Uint16Array: Uint16ArrayConstructor; +/** + * A typed array of 32-bit signed integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Int32Array { + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * The ArrayBuffer instance referenced by the array. + */ + readonly buffer: ArrayBufferLike; + + /** + * The length in bytes of the array. + */ + readonly byteLength: number; + + /** + * The offset in bytes of the array. + */ + readonly byteOffset: number; + + /** + * 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): this; + + /** + * Determines whether all the members of an array satisfy the specified test. + * @param callbackfn A function that accepts up to three arguments. The every method calls + * the callbackfn function for each element in array1 until the callbackfn returns false, + * or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + every(callbackfn: (value: number, index: number, array: Int32Array) => boolean, thisArg?: any): boolean; + + /** + * 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: number, start?: number, end?: number): this; + + /** + * Returns the elements of an array that meet the condition specified in a callback function. + * @param callbackfn A function that accepts up to three arguments. The filter method calls + * the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + filter(callbackfn: (value: number, index: number, array: Int32Array) => any, thisArg?: any): Int32Array; + + /** + * 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: number, index: number, obj: Int32Array) => boolean, thisArg?: any): number | 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, + * findIndex immediately returns that element index. Otherwise, findIndex returns -1. + * @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: number, index: number, obj: Int32Array) => boolean, thisArg?: any): number; + + /** + * Performs the specified action for each element in an array. + * @param callbackfn A function that accepts up to three arguments. forEach calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + forEach(callbackfn: (value: number, index: number, array: Int32Array) => void, thisArg?: any): void; + + /** + * Returns the index of the first occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + indexOf(searchElement: number, fromIndex?: number): number; + + /** + * Adds all the elements of an array separated by the specified separator string. + * @param separator A string used to separate one element of an array from the next in the + * resulting String. If omitted, the array elements are separated with a comma. + */ + join(separator?: string): string; + + /** + * Returns the index of the last occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + lastIndexOf(searchElement: number, fromIndex?: number): number; + + /** + * The length of the array. + */ + readonly length: number; + + /** + * Calls a defined callback function on each element of an array, and returns an array that + * contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + map(callbackfn: (value: number, index: number, array: Int32Array) => number, thisArg?: any): Int32Array; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int32Array) => number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int32Array) => number, initialValue: number): number; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Int32Array) => U, initialValue: U): U; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an + * argument instead of an array value. + */ + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int32Array) => number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int32Array) => number, initialValue: number): number; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Int32Array) => U, initialValue: U): U; + + /** + * Reverses the elements in an Array. + */ + reverse(): Int32Array; + + /** + * Sets a value or an array of values. + * @param array A typed or untyped array of values to set. + * @param offset The index in the current array at which the values are to be written. + */ + set(array: ArrayLike, offset?: number): void; + + /** + * Returns a section of an array. + * @param start The beginning of the specified portion of the array. + * @param end The end of the specified portion of the array. + */ + slice(start?: number, end?: number): Int32Array; + + /** + * Determines whether the specified callback function returns true for any element of an array. + * @param callbackfn A function that accepts up to three arguments. The some method calls the + * callbackfn function for each element in array1 until the callbackfn returns true, or until + * the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + some(callbackfn: (value: number, index: number, array: Int32Array) => boolean, thisArg?: any): boolean; + + /** + * Sorts an array. + * @param compareFn The name of the function used to determine the order of the elements. If + * omitted, the elements are sorted in ascending, ASCII character order. + */ + sort(compareFn?: (a: number, b: number) => number): this; + + /** + * Gets a new Int32Array view of the ArrayBuffer store for this array, referencing the elements + * at begin, inclusive, up to end, exclusive. + * @param begin The index of the beginning of the array. + * @param end The index of the end of the array. + */ + subarray(begin: number, end?: number): Int32Array; + + /** + * Converts a number to a string by using the current locale. + */ + toLocaleString(): string; + + /** + * Returns a string representation of an array. + */ + toString(): string; + + [index: number]: number; +} + +interface Int32ArrayConstructor { + readonly prototype: Int32Array; + new(length: number): Int32Array; + new(arrayOrArrayBuffer: ArrayLike | ArrayBufferLike): Int32Array; + new(buffer: ArrayBufferLike, byteOffset: number, length?: number): Int32Array; + + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * Returns a new array from a set of elements. + * @param items A set of elements to include in the new array object. + */ + of(...items: number[]): Int32Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or 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(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Int32Array; + +} +declare const Int32Array: Int32ArrayConstructor; + +/** + * A typed array of 32-bit unsigned integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Uint32Array { + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * The ArrayBuffer instance referenced by the array. + */ + readonly buffer: ArrayBufferLike; + + /** + * The length in bytes of the array. + */ + readonly byteLength: number; + + /** + * The offset in bytes of the array. + */ + readonly byteOffset: number; + + /** + * 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): this; + + /** + * Determines whether all the members of an array satisfy the specified test. + * @param callbackfn A function that accepts up to three arguments. The every method calls + * the callbackfn function for each element in array1 until the callbackfn returns false, + * or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + every(callbackfn: (value: number, index: number, array: Uint32Array) => boolean, thisArg?: any): boolean; + + /** + * 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: number, start?: number, end?: number): this; + + /** + * Returns the elements of an array that meet the condition specified in a callback function. + * @param callbackfn A function that accepts up to three arguments. The filter method calls + * the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + filter(callbackfn: (value: number, index: number, array: Uint32Array) => any, thisArg?: any): Uint32Array; + + /** + * 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: number, index: number, obj: Uint32Array) => boolean, thisArg?: any): number | 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, + * findIndex immediately returns that element index. Otherwise, findIndex returns -1. + * @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: number, index: number, obj: Uint32Array) => boolean, thisArg?: any): number; + + /** + * Performs the specified action for each element in an array. + * @param callbackfn A function that accepts up to three arguments. forEach calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + forEach(callbackfn: (value: number, index: number, array: Uint32Array) => void, thisArg?: any): void; + /** + * Returns the index of the first occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + indexOf(searchElement: number, fromIndex?: number): number; + + /** + * Adds all the elements of an array separated by the specified separator string. + * @param separator A string used to separate one element of an array from the next in the + * resulting String. If omitted, the array elements are separated with a comma. + */ + join(separator?: string): string; + + /** + * Returns the index of the last occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + lastIndexOf(searchElement: number, fromIndex?: number): number; + + /** + * The length of the array. + */ + readonly length: number; + + /** + * Calls a defined callback function on each element of an array, and returns an array that + * contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + map(callbackfn: (value: number, index: number, array: Uint32Array) => number, thisArg?: any): Uint32Array; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint32Array) => number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint32Array) => number, initialValue: number): number; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint32Array) => U, initialValue: U): U; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an + * argument instead of an array value. + */ + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint32Array) => number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint32Array) => number, initialValue: number): number; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint32Array) => U, initialValue: U): U; + + /** + * Reverses the elements in an Array. + */ + reverse(): Uint32Array; + + /** + * Sets a value or an array of values. + * @param array A typed or untyped array of values to set. + * @param offset The index in the current array at which the values are to be written. + */ + set(array: ArrayLike, offset?: number): void; + + /** + * Returns a section of an array. + * @param start The beginning of the specified portion of the array. + * @param end The end of the specified portion of the array. + */ + slice(start?: number, end?: number): Uint32Array; + + /** + * Determines whether the specified callback function returns true for any element of an array. + * @param callbackfn A function that accepts up to three arguments. The some method calls the + * callbackfn function for each element in array1 until the callbackfn returns true, or until + * the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + some(callbackfn: (value: number, index: number, array: Uint32Array) => boolean, thisArg?: any): boolean; + + /** + * Sorts an array. + * @param compareFn The name of the function used to determine the order of the elements. If + * omitted, the elements are sorted in ascending, ASCII character order. + */ + sort(compareFn?: (a: number, b: number) => number): this; + + /** + * Gets a new Uint32Array view of the ArrayBuffer store for this array, referencing the elements + * at begin, inclusive, up to end, exclusive. + * @param begin The index of the beginning of the array. + * @param end The index of the end of the array. + */ + subarray(begin: number, end?: number): Uint32Array; + + /** + * Converts a number to a string by using the current locale. + */ + toLocaleString(): string; + + /** + * Returns a string representation of an array. + */ + toString(): string; + + [index: number]: number; +} + +interface Uint32ArrayConstructor { + readonly prototype: Uint32Array; + new(length: number): Uint32Array; + new(arrayOrArrayBuffer: ArrayLike | ArrayBufferLike): Uint32Array; + new(buffer: ArrayBufferLike, byteOffset: number, length?: number): Uint32Array; + + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * Returns a new array from a set of elements. + * @param items A set of elements to include in the new array object. + */ + of(...items: number[]): Uint32Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or 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(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint32Array; + +} +declare const Uint32Array: Uint32ArrayConstructor; + +/** + * A typed array of 32-bit float values. The contents are initialized to 0. If the requested number + * of bytes could not be allocated an exception is raised. + */ +interface Float32Array { + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * The ArrayBuffer instance referenced by the array. + */ + readonly buffer: ArrayBufferLike; + + /** + * The length in bytes of the array. + */ + readonly byteLength: number; + + /** + * The offset in bytes of the array. + */ + readonly byteOffset: number; + + /** + * 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): this; + + /** + * Determines whether all the members of an array satisfy the specified test. + * @param callbackfn A function that accepts up to three arguments. The every method calls + * the callbackfn function for each element in array1 until the callbackfn returns false, + * or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + every(callbackfn: (value: number, index: number, array: Float32Array) => boolean, thisArg?: any): boolean; + + /** + * 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: number, start?: number, end?: number): this; + + /** + * Returns the elements of an array that meet the condition specified in a callback function. + * @param callbackfn A function that accepts up to three arguments. The filter method calls + * the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + filter(callbackfn: (value: number, index: number, array: Float32Array) => any, thisArg?: any): Float32Array; + + /** + * 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: number, index: number, obj: Float32Array) => boolean, thisArg?: any): number | 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, + * findIndex immediately returns that element index. Otherwise, findIndex returns -1. + * @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: number, index: number, obj: Float32Array) => boolean, thisArg?: any): number; + + /** + * Performs the specified action for each element in an array. + * @param callbackfn A function that accepts up to three arguments. forEach calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + forEach(callbackfn: (value: number, index: number, array: Float32Array) => void, thisArg?: any): void; + + /** + * Returns the index of the first occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + indexOf(searchElement: number, fromIndex?: number): number; + + /** + * Adds all the elements of an array separated by the specified separator string. + * @param separator A string used to separate one element of an array from the next in the + * resulting String. If omitted, the array elements are separated with a comma. + */ + join(separator?: string): string; + + /** + * Returns the index of the last occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + lastIndexOf(searchElement: number, fromIndex?: number): number; + + /** + * The length of the array. + */ + readonly length: number; + + /** + * Calls a defined callback function on each element of an array, and returns an array that + * contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + map(callbackfn: (value: number, index: number, array: Float32Array) => number, thisArg?: any): Float32Array; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float32Array) => number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float32Array) => number, initialValue: number): number; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Float32Array) => U, initialValue: U): U; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an + * argument instead of an array value. + */ + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float32Array) => number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float32Array) => number, initialValue: number): number; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Float32Array) => U, initialValue: U): U; + + /** + * Reverses the elements in an Array. + */ + reverse(): Float32Array; + + /** + * Sets a value or an array of values. + * @param array A typed or untyped array of values to set. + * @param offset The index in the current array at which the values are to be written. + */ + set(array: ArrayLike, offset?: number): void; + + /** + * Returns a section of an array. + * @param start The beginning of the specified portion of the array. + * @param end The end of the specified portion of the array. + */ + slice(start?: number, end?: number): Float32Array; + + /** + * Determines whether the specified callback function returns true for any element of an array. + * @param callbackfn A function that accepts up to three arguments. The some method calls the + * callbackfn function for each element in array1 until the callbackfn returns true, or until + * the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + some(callbackfn: (value: number, index: number, array: Float32Array) => boolean, thisArg?: any): boolean; + + /** + * Sorts an array. + * @param compareFn The name of the function used to determine the order of the elements. If + * omitted, the elements are sorted in ascending, ASCII character order. + */ + sort(compareFn?: (a: number, b: number) => number): this; + + /** + * Gets a new Float32Array view of the ArrayBuffer store for this array, referencing the elements + * at begin, inclusive, up to end, exclusive. + * @param begin The index of the beginning of the array. + * @param end The index of the end of the array. + */ + subarray(begin: number, end?: number): Float32Array; + + /** + * Converts a number to a string by using the current locale. + */ + toLocaleString(): string; + + /** + * Returns a string representation of an array. + */ + toString(): string; + + [index: number]: number; +} + +interface Float32ArrayConstructor { + readonly prototype: Float32Array; + new(length: number): Float32Array; + new(arrayOrArrayBuffer: ArrayLike | ArrayBufferLike): Float32Array; + new(buffer: ArrayBufferLike, byteOffset: number, length?: number): Float32Array; + + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * Returns a new array from a set of elements. + * @param items A set of elements to include in the new array object. + */ + of(...items: number[]): Float32Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or 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(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Float32Array; + + +} +declare const Float32Array: Float32ArrayConstructor; + +/** + * A typed array of 64-bit float values. The contents are initialized to 0. If the requested + * number of bytes could not be allocated an exception is raised. + */ +interface Float64Array { + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * The ArrayBuffer instance referenced by the array. + */ + readonly buffer: ArrayBufferLike; + + /** + * The length in bytes of the array. + */ + readonly byteLength: number; + + /** + * The offset in bytes of the array. + */ + readonly byteOffset: number; + + /** + * 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): this; + + /** + * Determines whether all the members of an array satisfy the specified test. + * @param callbackfn A function that accepts up to three arguments. The every method calls + * the callbackfn function for each element in array1 until the callbackfn returns false, + * or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + every(callbackfn: (value: number, index: number, array: Float64Array) => boolean, thisArg?: any): boolean; + + /** + * 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: number, start?: number, end?: number): this; + + /** + * Returns the elements of an array that meet the condition specified in a callback function. + * @param callbackfn A function that accepts up to three arguments. The filter method calls + * the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + filter(callbackfn: (value: number, index: number, array: Float64Array) => any, thisArg?: any): Float64Array; + + /** + * 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: number, index: number, obj: Float64Array) => boolean, thisArg?: any): number | 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, + * findIndex immediately returns that element index. Otherwise, findIndex returns -1. + * @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: number, index: number, obj: Float64Array) => boolean, thisArg?: any): number; + + /** + * Performs the specified action for each element in an array. + * @param callbackfn A function that accepts up to three arguments. forEach calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + forEach(callbackfn: (value: number, index: number, array: Float64Array) => void, thisArg?: any): void; + + /** + * Returns the index of the first occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + indexOf(searchElement: number, fromIndex?: number): number; + + /** + * Adds all the elements of an array separated by the specified separator string. + * @param separator A string used to separate one element of an array from the next in the + * resulting String. If omitted, the array elements are separated with a comma. + */ + join(separator?: string): string; + + /** + * Returns the index of the last occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + lastIndexOf(searchElement: number, fromIndex?: number): number; + + /** + * The length of the array. + */ + readonly length: number; + + /** + * Calls a defined callback function on each element of an array, and returns an array that + * contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + map(callbackfn: (value: number, index: number, array: Float64Array) => number, thisArg?: any): Float64Array; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float64Array) => number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float64Array) => number, initialValue: number): number; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Float64Array) => U, initialValue: U): U; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an + * argument instead of an array value. + */ + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float64Array) => number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float64Array) => number, initialValue: number): number; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Float64Array) => U, initialValue: U): U; + + /** + * Reverses the elements in an Array. + */ + reverse(): Float64Array; + + /** + * Sets a value or an array of values. + * @param array A typed or untyped array of values to set. + * @param offset The index in the current array at which the values are to be written. + */ + set(array: ArrayLike, offset?: number): void; + + /** + * Returns a section of an array. + * @param start The beginning of the specified portion of the array. + * @param end The end of the specified portion of the array. + */ + slice(start?: number, end?: number): Float64Array; + + /** + * Determines whether the specified callback function returns true for any element of an array. + * @param callbackfn A function that accepts up to three arguments. The some method calls the + * callbackfn function for each element in array1 until the callbackfn returns true, or until + * the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + some(callbackfn: (value: number, index: number, array: Float64Array) => boolean, thisArg?: any): boolean; + + /** + * Sorts an array. + * @param compareFn The name of the function used to determine the order of the elements. If + * omitted, the elements are sorted in ascending, ASCII character order. + */ + sort(compareFn?: (a: number, b: number) => number): this; + + /** + * Gets a new Float64Array view of the ArrayBuffer store for this array, referencing the elements + * at begin, inclusive, up to end, exclusive. + * @param begin The index of the beginning of the array. + * @param end The index of the end of the array. + */ + subarray(begin: number, end?: number): Float64Array; + + /** + * Converts a number to a string by using the current locale. + */ + toLocaleString(): string; + + /** + * Returns a string representation of an array. + */ + toString(): string; + + [index: number]: number; +} + +interface Float64ArrayConstructor { + readonly prototype: Float64Array; + new(length: number): Float64Array; + new(arrayOrArrayBuffer: ArrayLike | ArrayBufferLike): Float64Array; + new(buffer: ArrayBufferLike, byteOffset: number, length?: number): Float64Array; + + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * Returns a new array from a set of elements. + * @param items A set of elements to include in the new array object. + */ + of(...items: number[]): Float64Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or 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(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Float64Array; + +} +declare const Float64Array: Float64ArrayConstructor; + +///////////////////////////// +/// ECMAScript Internationalization API +///////////////////////////// + +declare namespace Intl { + interface CollatorOptions { + usage?: string; + localeMatcher?: string; + numeric?: boolean; + caseFirst?: string; + sensitivity?: string; + ignorePunctuation?: boolean; + } + + interface ResolvedCollatorOptions { + locale: string; + usage: string; + sensitivity: string; + ignorePunctuation: boolean; + collation: string; + caseFirst: string; + numeric: boolean; + } + + interface Collator { + compare(x: string, y: string): number; + resolvedOptions(): ResolvedCollatorOptions; + } + var Collator: { + new(locales?: string | string[], options?: CollatorOptions): Collator; + (locales?: string | string[], options?: CollatorOptions): Collator; + supportedLocalesOf(locales: string | string[], options?: CollatorOptions): string[]; + }; + + interface NumberFormatOptions { + localeMatcher?: string; + style?: string; + currency?: string; + currencyDisplay?: string; + useGrouping?: boolean; + minimumIntegerDigits?: number; + minimumFractionDigits?: number; + maximumFractionDigits?: number; + minimumSignificantDigits?: number; + maximumSignificantDigits?: number; + } + + interface ResolvedNumberFormatOptions { + locale: string; + numberingSystem: string; + style: string; + currency?: string; + currencyDisplay?: string; + minimumIntegerDigits: number; + minimumFractionDigits: number; + maximumFractionDigits: number; + minimumSignificantDigits?: number; + maximumSignificantDigits?: number; + useGrouping: boolean; + } + + interface NumberFormat { + format(value: number): string; + resolvedOptions(): ResolvedNumberFormatOptions; + } + var NumberFormat: { + new(locales?: string | string[], options?: NumberFormatOptions): NumberFormat; + (locales?: string | string[], options?: NumberFormatOptions): NumberFormat; + supportedLocalesOf(locales: string | string[], options?: NumberFormatOptions): string[]; + }; + + interface DateTimeFormatOptions { + localeMatcher?: string; + weekday?: string; + era?: string; + year?: string; + month?: string; + day?: string; + hour?: string; + minute?: string; + second?: string; + timeZoneName?: string; + formatMatcher?: string; + hour12?: boolean; + timeZone?: string; + } + + interface ResolvedDateTimeFormatOptions { + locale: string; + calendar: string; + numberingSystem: string; + timeZone: string; + hour12?: boolean; + weekday?: string; + era?: string; + year?: string; + month?: string; + day?: string; + hour?: string; + minute?: string; + second?: string; + timeZoneName?: string; + } + + interface DateTimeFormat { + format(date?: Date | number): string; + resolvedOptions(): ResolvedDateTimeFormatOptions; + } + var DateTimeFormat: { + new(locales?: string | string[], options?: DateTimeFormatOptions): DateTimeFormat; + (locales?: string | string[], options?: DateTimeFormatOptions): DateTimeFormat; + supportedLocalesOf(locales: string | string[], options?: DateTimeFormatOptions): string[]; + }; +} + +interface String { + /** + * Determines whether two strings are equivalent in the current or specified locale. + * @param that String to compare to target string + * @param locales A locale string or array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used. This parameter must conform to BCP 47 standards; see the Intl.Collator object for details. + * @param options An object that contains one or more properties that specify comparison options. see the Intl.Collator object for details. + */ + localeCompare(that: string, locales?: string | string[], options?: Intl.CollatorOptions): number; +} + +interface Number { + /** + * Converts a number to a string by using the current or specified locale. + * @param locales A locale string or array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used. + * @param options An object that contains one or more properties that specify comparison options. + */ + toLocaleString(locales?: string | string[], options?: Intl.NumberFormatOptions): string; +} + +interface Date { + /** + * Converts a date and time to a string by using the current or specified locale. + * @param locales A locale string or array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used. + * @param options An object that contains one or more properties that specify comparison options. + */ + toLocaleString(locales?: string | string[], options?: Intl.DateTimeFormatOptions): string; + /** + * Converts a date to a string by using the current or specified locale. + * @param locales A locale string or array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used. + * @param options An object that contains one or more properties that specify comparison options. + */ + toLocaleDateString(locales?: string | string[], options?: Intl.DateTimeFormatOptions): string; + + /** + * Converts a time to a string by using the current or specified locale. + * @param locales A locale string or array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used. + * @param options An object that contains one or more properties that specify comparison options. + */ + toLocaleTimeString(locales?: string | string[], options?: Intl.DateTimeFormatOptions): string; +} diff --git a/node_modules/typescript/lib/lib.es6.d.ts b/node_modules/typescript/lib/lib.es6.d.ts new file mode 100644 index 0000000..6149c4a --- /dev/null +++ b/node_modules/typescript/lib/lib.es6.d.ts @@ -0,0 +1,25 @@ +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + + + +/// + + +/// +/// +/// +/// +/// diff --git a/node_modules/typescript/lib/lib.esnext.array.d.ts b/node_modules/typescript/lib/lib.esnext.array.d.ts new file mode 100644 index 0000000..6c75122 --- /dev/null +++ b/node_modules/typescript/lib/lib.esnext.array.d.ts @@ -0,0 +1,223 @@ +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + + + +/// + + +interface ReadonlyArray { + + /** + * Calls a defined callback function on each element of an array. Then, flattens the result into + * a new array. + * This is identical to a map followed by flat with depth 1. + * + * @param callback A function that accepts up to three arguments. The flatMap method calls the + * callback function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callback function. If + * thisArg is omitted, undefined is used as the this value. + */ + flatMap ( + callback: (this: This, value: T, index: number, array: T[]) => U|ReadonlyArray, + thisArg?: This + ): U[] + + + /** + * Returns a new array with all sub-array elements concatenated into it recursively up to the + * specified depth. + * + * @param depth The maximum recursion depth + */ + flat(this: + ReadonlyArray | + + ReadonlyArray> | + ReadonlyArray[]> | + ReadonlyArray[][]> | + ReadonlyArray[][][]> | + + ReadonlyArray>> | + ReadonlyArray[][]>> | + ReadonlyArray>[][]> | + ReadonlyArray[]>[]> | + ReadonlyArray>[]> | + ReadonlyArray[]>> | + + ReadonlyArray>>> | + ReadonlyArray[]>>> | + ReadonlyArray>[]>> | + ReadonlyArray>>[]> | + + ReadonlyArray>>>>, + depth: 4): U[]; + + /** + * Returns a new array with all sub-array elements concatenated into it recursively up to the + * specified depth. + * + * @param depth The maximum recursion depth + */ + flat(this: + ReadonlyArray | + + ReadonlyArray[][]> | + ReadonlyArray[]> | + ReadonlyArray> | + + ReadonlyArray>> | + ReadonlyArray[]>> | + ReadonlyArray>[]> | + + ReadonlyArray>>>, + depth: 3): U[]; + + /** + * Returns a new array with all sub-array elements concatenated into it recursively up to the + * specified depth. + * + * @param depth The maximum recursion depth + */ + flat(this: + ReadonlyArray | + + ReadonlyArray> | + ReadonlyArray[]> | + + ReadonlyArray>>, + depth: 2): U[]; + + /** + * Returns a new array with all sub-array elements concatenated into it recursively up to the + * specified depth. + * + * @param depth The maximum recursion depth + */ + flat(this: + ReadonlyArray | + ReadonlyArray>, + depth?: 1 + ): U[]; + + /** + * Returns a new array with all sub-array elements concatenated into it recursively up to the + * specified depth. + * + * @param depth The maximum recursion depth + */ + flat(this: + ReadonlyArray, + depth: 0 + ): U[]; + + /** + * Returns a new array with all sub-array elements concatenated into it recursively up to the + * specified depth. If no depth is provided, flat method defaults to the depth of 1. + * + * @param depth The maximum recursion depth + */ + flat(depth?: number): any[]; + } + +interface Array { + + /** + * Calls a defined callback function on each element of an array. Then, flattens the result into + * a new array. + * This is identical to a map followed by flat with depth 1. + * + * @param callback A function that accepts up to three arguments. The flatMap method calls the + * callback function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callback function. If + * thisArg is omitted, undefined is used as the this value. + */ + flatMap ( + callback: (this: This, value: T, index: number, array: T[]) => U|ReadonlyArray, + thisArg?: This + ): U[] + + /** + * Returns a new array with all sub-array elements concatenated into it recursively up to the + * specified depth. + * + * @param depth The maximum recursion depth + */ + flat(this: U[][][][][][][][], depth: 7): U[]; + + /** + * Returns a new array with all sub-array elements concatenated into it recursively up to the + * specified depth. + * + * @param depth The maximum recursion depth + */ + flat(this: U[][][][][][][], depth: 6): U[]; + + /** + * Returns a new array with all sub-array elements concatenated into it recursively up to the + * specified depth. + * + * @param depth The maximum recursion depth + */ + flat(this: U[][][][][][], depth: 5): U[]; + + /** + * Returns a new array with all sub-array elements concatenated into it recursively up to the + * specified depth. + * + * @param depth The maximum recursion depth + */ + flat(this: U[][][][][], depth: 4): U[]; + + /** + * Returns a new array with all sub-array elements concatenated into it recursively up to the + * specified depth. + * + * @param depth The maximum recursion depth + */ + flat(this: U[][][][], depth: 3): U[]; + + /** + * Returns a new array with all sub-array elements concatenated into it recursively up to the + * specified depth. + * + * @param depth The maximum recursion depth + */ + flat(this: U[][][], depth: 2): U[]; + + /** + * Returns a new array with all sub-array elements concatenated into it recursively up to the + * specified depth. + * + * @param depth The maximum recursion depth + */ + flat(this: U[][], depth?: 1): U[]; + + /** + * Returns a new array with all sub-array elements concatenated into it recursively up to the + * specified depth. + * + * @param depth The maximum recursion depth + */ + flat(this: U[], depth: 0): U[]; + + /** + * Returns a new array with all sub-array elements concatenated into it recursively up to the + * specified depth. If no depth is provided, flat method defaults to the depth of 1. + * + * @param depth The maximum recursion depth + */ + flat(depth?: number): any[]; +} diff --git a/node_modules/typescript/lib/lib.esnext.asynciterable.d.ts b/node_modules/typescript/lib/lib.esnext.asynciterable.d.ts new file mode 100644 index 0000000..38e12a7 --- /dev/null +++ b/node_modules/typescript/lib/lib.esnext.asynciterable.d.ts @@ -0,0 +1,44 @@ +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + + + +/// + + +/// +/// + +interface SymbolConstructor { + /** + * A method that returns the default async iterator for an object. Called by the semantics of + * the for-await-of statement. + */ + readonly asyncIterator: symbol; +} + +interface AsyncIterator { + next(value?: any): Promise>; + return?(value?: any): Promise>; + throw?(e?: any): Promise>; +} + +interface AsyncIterable { + [Symbol.asyncIterator](): AsyncIterator; +} + +interface AsyncIterableIterator extends AsyncIterator { + [Symbol.asyncIterator](): AsyncIterableIterator; +} \ No newline at end of file diff --git a/node_modules/typescript/lib/lib.esnext.bigint.d.ts b/node_modules/typescript/lib/lib.esnext.bigint.d.ts new file mode 100644 index 0000000..ccb73be --- /dev/null +++ b/node_modules/typescript/lib/lib.esnext.bigint.d.ts @@ -0,0 +1,629 @@ +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + + + +/// + + +interface BigInt { + /** + * Returns a string representation of an object. + * @param radix Specifies a radix for converting numeric values to strings. + */ + toString(radix?: number): string; + + /** Returns a string representation appropriate to the host environment's current locale. */ + toLocaleString(): string; + + /** Returns the primitive value of the specified object. */ + valueOf(): bigint; + + readonly [Symbol.toStringTag]: "BigInt"; +} + +interface BigIntConstructor { + (value?: any): bigint; + readonly prototype: BigInt; + + /** + * Interprets the low bits of a BigInt as a 2's-complement signed integer. + * All higher bits are discarded. + * @param bits The number of low bits to use + * @param int The BigInt whose bits to extract + */ + asIntN(bits: number, int: bigint): bigint; + /** + * Interprets the low bits of a BigInt as an unsigned integer. + * All higher bits are discarded. + * @param bits The number of low bits to use + * @param int The BigInt whose bits to extract + */ + asUintN(bits: number, int: bigint): bigint; +} + +declare const BigInt: BigIntConstructor; + +/** + * A typed array of 64-bit signed integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated, an exception is raised. + */ +interface BigInt64Array { + /** The size in bytes of each element in the array. */ + readonly BYTES_PER_ELEMENT: number; + + /** The ArrayBuffer instance referenced by the array. */ + readonly buffer: ArrayBufferLike; + + /** The length in bytes of the array. */ + readonly byteLength: number; + + /** The offset in bytes of the array. */ + readonly byteOffset: number; + + /** + * 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): this; + + /** Yields index, value pairs for every entry in the array. */ + entries(): IterableIterator<[number, bigint]>; + + /** + * Determines whether all the members of an array satisfy the specified test. + * @param callbackfn A function that accepts up to three arguments. The every method calls + * the callbackfn function for each element in the array until the callbackfn returns false, + * or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + every(callbackfn: (value: bigint, index: number, array: BigInt64Array) => boolean, thisArg?: any): boolean; + + /** + * 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: bigint, start?: number, end?: number): this; + + /** + * Returns the elements of an array that meet the condition specified in a callback function. + * @param callbackfn A function that accepts up to three arguments. The filter method calls + * the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + filter(callbackfn: (value: bigint, index: number, array: BigInt64Array) => any, thisArg?: any): BigInt64Array; + + /** + * 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: bigint, index: number, array: BigInt64Array) => boolean, thisArg?: any): bigint | 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, + * findIndex immediately returns that element index. Otherwise, findIndex returns -1. + * @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: bigint, index: number, array: BigInt64Array) => boolean, thisArg?: any): number; + + /** + * Performs the specified action for each element in an array. + * @param callbackfn A function that accepts up to three arguments. forEach calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + forEach(callbackfn: (value: bigint, index: number, array: BigInt64Array) => void, thisArg?: any): void; + + /** + * Determines whether an array includes a certain element, returning true or false as appropriate. + * @param searchElement The element to search for. + * @param fromIndex The position in this array at which to begin searching for searchElement. + */ + includes(searchElement: bigint, fromIndex?: number): boolean; + + /** + * Returns the index of the first occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + indexOf(searchElement: bigint, fromIndex?: number): number; + + /** + * Adds all the elements of an array separated by the specified separator string. + * @param separator A string used to separate one element of an array from the next in the + * resulting String. If omitted, the array elements are separated with a comma. + */ + join(separator?: string): string; + + /** Yields each index in the array. */ + keys(): IterableIterator; + + /** + * Returns the index of the last occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + lastIndexOf(searchElement: bigint, fromIndex?: number): number; + + /** The length of the array. */ + readonly length: number; + + /** + * Calls a defined callback function on each element of an array, and returns an array that + * contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + map(callbackfn: (value: bigint, index: number, array: BigInt64Array) => bigint, thisArg?: any): BigInt64Array; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: bigint, currentValue: bigint, currentIndex: number, array: BigInt64Array) => bigint): bigint; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: U, currentValue: bigint, currentIndex: number, array: BigInt64Array) => U, initialValue: U): U; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an + * argument instead of an array value. + */ + reduceRight(callbackfn: (previousValue: bigint, currentValue: bigint, currentIndex: number, array: BigInt64Array) => bigint): bigint; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduceRight(callbackfn: (previousValue: U, currentValue: bigint, currentIndex: number, array: BigInt64Array) => U, initialValue: U): U; + + /** Reverses the elements in the array. */ + reverse(): this; + + /** + * Sets a value or an array of values. + * @param array A typed or untyped array of values to set. + * @param offset The index in the current array at which the values are to be written. + */ + set(array: ArrayLike, offset?: number): void; + + /** + * Returns a section of an array. + * @param start The beginning of the specified portion of the array. + * @param end The end of the specified portion of the array. + */ + slice(start?: number, end?: number): BigInt64Array; + + /** + * Determines whether the specified callback function returns true for any element of an array. + * @param callbackfn A function that accepts up to three arguments. The some method calls the + * callbackfn function for each element in the array until the callbackfn returns true, or until + * the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + some(callbackfn: (value: bigint, index: number, array: BigInt64Array) => boolean, thisArg?: any): boolean; + + /** + * Sorts the array. + * @param compareFn The function used to determine the order of the elements. If omitted, the elements are sorted in ascending order. + */ + sort(compareFn?: (a: bigint, b: bigint) => number | bigint): this; + + /** + * Gets a new BigInt64Array view of the ArrayBuffer store for this array, referencing the elements + * at begin, inclusive, up to end, exclusive. + * @param begin The index of the beginning of the array. + * @param end The index of the end of the array. + */ + subarray(begin: number, end?: number): BigInt64Array; + + /** Converts the array to a string by using the current locale. */ + toLocaleString(): string; + + /** Returns a string representation of the array. */ + toString(): string; + + /** Yields each value in the array. */ + values(): IterableIterator; + + [Symbol.iterator](): IterableIterator; + + readonly [Symbol.toStringTag]: "BigInt64Array"; + + [index: number]: bigint; +} + +interface BigInt64ArrayConstructor { + readonly prototype: BigInt64Array; + new(length?: number): BigInt64Array; + new(array: Iterable): BigInt64Array; + new(buffer: ArrayBufferLike, byteOffset?: number, length?: number): BigInt64Array; + + /** The size in bytes of each element in the array. */ + readonly BYTES_PER_ELEMENT: number; + + /** + * Returns a new array from a set of elements. + * @param items A set of elements to include in the new array object. + */ + of(...items: bigint[]): BigInt64Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or 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(arrayLike: ArrayLike): BigInt64Array; + from(arrayLike: ArrayLike, mapfn: (v: U, k: number) => bigint, thisArg?: any): BigInt64Array; +} + +declare const BigInt64Array: BigInt64ArrayConstructor; + +/** + * A typed array of 64-bit unsigned integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated, an exception is raised. + */ +interface BigUint64Array { + /** The size in bytes of each element in the array. */ + readonly BYTES_PER_ELEMENT: number; + + /** The ArrayBuffer instance referenced by the array. */ + readonly buffer: ArrayBufferLike; + + /** The length in bytes of the array. */ + readonly byteLength: number; + + /** The offset in bytes of the array. */ + readonly byteOffset: number; + + /** + * 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): this; + + /** Yields index, value pairs for every entry in the array. */ + entries(): IterableIterator<[number, bigint]>; + + /** + * Determines whether all the members of an array satisfy the specified test. + * @param callbackfn A function that accepts up to three arguments. The every method calls + * the callbackfn function for each element in the array until the callbackfn returns false, + * or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + every(callbackfn: (value: bigint, index: number, array: BigUint64Array) => boolean, thisArg?: any): boolean; + + /** + * 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: bigint, start?: number, end?: number): this; + + /** + * Returns the elements of an array that meet the condition specified in a callback function. + * @param callbackfn A function that accepts up to three arguments. The filter method calls + * the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + filter(callbackfn: (value: bigint, index: number, array: BigUint64Array) => any, thisArg?: any): BigUint64Array; + + /** + * 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: bigint, index: number, array: BigUint64Array) => boolean, thisArg?: any): bigint | 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, + * findIndex immediately returns that element index. Otherwise, findIndex returns -1. + * @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: bigint, index: number, array: BigUint64Array) => boolean, thisArg?: any): number; + + /** + * Performs the specified action for each element in an array. + * @param callbackfn A function that accepts up to three arguments. forEach calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + forEach(callbackfn: (value: bigint, index: number, array: BigUint64Array) => void, thisArg?: any): void; + + /** + * Determines whether an array includes a certain element, returning true or false as appropriate. + * @param searchElement The element to search for. + * @param fromIndex The position in this array at which to begin searching for searchElement. + */ + includes(searchElement: bigint, fromIndex?: number): boolean; + + /** + * Returns the index of the first occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + indexOf(searchElement: bigint, fromIndex?: number): number; + + /** + * Adds all the elements of an array separated by the specified separator string. + * @param separator A string used to separate one element of an array from the next in the + * resulting String. If omitted, the array elements are separated with a comma. + */ + join(separator?: string): string; + + /** Yields each index in the array. */ + keys(): IterableIterator; + + /** + * Returns the index of the last occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + lastIndexOf(searchElement: bigint, fromIndex?: number): number; + + /** The length of the array. */ + readonly length: number; + + /** + * Calls a defined callback function on each element of an array, and returns an array that + * contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + map(callbackfn: (value: bigint, index: number, array: BigUint64Array) => bigint, thisArg?: any): BigUint64Array; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: bigint, currentValue: bigint, currentIndex: number, array: BigUint64Array) => bigint): bigint; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: U, currentValue: bigint, currentIndex: number, array: BigUint64Array) => U, initialValue: U): U; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an + * argument instead of an array value. + */ + reduceRight(callbackfn: (previousValue: bigint, currentValue: bigint, currentIndex: number, array: BigUint64Array) => bigint): bigint; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduceRight(callbackfn: (previousValue: U, currentValue: bigint, currentIndex: number, array: BigUint64Array) => U, initialValue: U): U; + + /** Reverses the elements in the array. */ + reverse(): this; + + /** + * Sets a value or an array of values. + * @param array A typed or untyped array of values to set. + * @param offset The index in the current array at which the values are to be written. + */ + set(array: ArrayLike, offset?: number): void; + + /** + * Returns a section of an array. + * @param start The beginning of the specified portion of the array. + * @param end The end of the specified portion of the array. + */ + slice(start?: number, end?: number): BigUint64Array; + + /** + * Determines whether the specified callback function returns true for any element of an array. + * @param callbackfn A function that accepts up to three arguments. The some method calls the + * callbackfn function for each element in the array until the callbackfn returns true, or until + * the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + some(callbackfn: (value: bigint, index: number, array: BigUint64Array) => boolean, thisArg?: any): boolean; + + /** + * Sorts the array. + * @param compareFn The function used to determine the order of the elements. If omitted, the elements are sorted in ascending order. + */ + sort(compareFn?: (a: bigint, b: bigint) => number | bigint): this; + + /** + * Gets a new BigUint64Array view of the ArrayBuffer store for this array, referencing the elements + * at begin, inclusive, up to end, exclusive. + * @param begin The index of the beginning of the array. + * @param end The index of the end of the array. + */ + subarray(begin: number, end?: number): BigUint64Array; + + /** Converts the array to a string by using the current locale. */ + toLocaleString(): string; + + /** Returns a string representation of the array. */ + toString(): string; + + /** Yields each value in the array. */ + values(): IterableIterator; + + [Symbol.iterator](): IterableIterator; + + readonly [Symbol.toStringTag]: "BigUint64Array"; + + [index: number]: bigint; +} + +interface BigUint64ArrayConstructor { + readonly prototype: BigUint64Array; + new(length?: number): BigUint64Array; + new(array: Iterable): BigUint64Array; + new(buffer: ArrayBufferLike, byteOffset?: number, length?: number): BigUint64Array; + + /** The size in bytes of each element in the array. */ + readonly BYTES_PER_ELEMENT: number; + + /** + * Returns a new array from a set of elements. + * @param items A set of elements to include in the new array object. + */ + of(...items: bigint[]): BigUint64Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or 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(arrayLike: ArrayLike): BigUint64Array; + from(arrayLike: ArrayLike, mapfn: (v: U, k: number) => bigint, thisArg?: any): BigUint64Array; +} + +declare const BigUint64Array: BigUint64ArrayConstructor; + +interface DataView { + /** + * Gets the BigInt64 value at the specified byte offset from the start of the view. There is + * no alignment constraint; multi-byte values may be fetched from any offset. + * @param byteOffset The place in the buffer at which the value should be retrieved. + */ + getBigInt64(byteOffset: number, littleEndian?: boolean): bigint; + + /** + * Gets the BigUint64 value at the specified byte offset from the start of the view. There is + * no alignment constraint; multi-byte values may be fetched from any offset. + * @param byteOffset The place in the buffer at which the value should be retrieved. + */ + getBigUint64(byteOffset: number, littleEndian?: boolean): bigint; + + /** + * Stores a BigInt64 value at the specified byte offset from the start of the view. + * @param byteOffset The place in the buffer at which the value should be set. + * @param value The value to set. + * @param littleEndian If false or undefined, a big-endian value should be written, + * otherwise a little-endian value should be written. + */ + setBigInt64(byteOffset: number, value: bigint, littleEndian?: boolean): void; + + /** + * Stores a BigUint64 value at the specified byte offset from the start of the view. + * @param byteOffset The place in the buffer at which the value should be set. + * @param value The value to set. + * @param littleEndian If false or undefined, a big-endian value should be written, + * otherwise a little-endian value should be written. + */ + setBigUint64(byteOffset: number, value: bigint, littleEndian?: boolean): void; +} \ No newline at end of file diff --git a/node_modules/typescript/lib/lib.esnext.d.ts b/node_modules/typescript/lib/lib.esnext.d.ts new file mode 100644 index 0000000..f213999 --- /dev/null +++ b/node_modules/typescript/lib/lib.esnext.d.ts @@ -0,0 +1,26 @@ +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + + + +/// + + +/// +/// +/// +/// +/// +/// diff --git a/node_modules/typescript/lib/lib.esnext.full.d.ts b/node_modules/typescript/lib/lib.esnext.full.d.ts new file mode 100644 index 0000000..e3c4fa5 --- /dev/null +++ b/node_modules/typescript/lib/lib.esnext.full.d.ts @@ -0,0 +1,25 @@ +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + + + +/// + + +/// +/// +/// +/// +/// \ No newline at end of file diff --git a/node_modules/typescript/lib/lib.esnext.intl.d.ts b/node_modules/typescript/lib/lib.esnext.intl.d.ts new file mode 100644 index 0000000..73a45ee --- /dev/null +++ b/node_modules/typescript/lib/lib.esnext.intl.d.ts @@ -0,0 +1,32 @@ +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + + + +/// + + +declare namespace Intl { + type NumberFormatPartTypes = "currency" | "decimal" | "fraction" | "group" | "infinity" | "integer" | "literal" | "minusSign" | "nan" | "plusSign" | "percentSign"; + + interface NumberFormatPart { + type: NumberFormatPartTypes; + value: string; + } + + interface NumberFormat { + formatToParts(number?: number): NumberFormatPart[]; + } + } diff --git a/node_modules/typescript/lib/lib.esnext.symbol.d.ts b/node_modules/typescript/lib/lib.esnext.symbol.d.ts new file mode 100644 index 0000000..98293ea --- /dev/null +++ b/node_modules/typescript/lib/lib.esnext.symbol.d.ts @@ -0,0 +1,26 @@ +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + + + +/// + + +interface Symbol { + /** + * expose the [[Description]] internal slot of a symbol directly + */ + readonly description: string; +} diff --git a/node_modules/typescript/lib/lib.scripthost.d.ts b/node_modules/typescript/lib/lib.scripthost.d.ts new file mode 100644 index 0000000..5aab121 --- /dev/null +++ b/node_modules/typescript/lib/lib.scripthost.d.ts @@ -0,0 +1,327 @@ +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + + + +/// + + + + +///////////////////////////// +/// Windows Script Host APIS +///////////////////////////// + + +interface ActiveXObject { + new (s: string): any; +} +declare var ActiveXObject: ActiveXObject; + +interface ITextWriter { + Write(s: string): void; + WriteLine(s: string): void; + Close(): void; +} + +interface TextStreamBase { + /** + * The column number of the current character position in an input stream. + */ + Column: number; + + /** + * The current line number in an input stream. + */ + Line: number; + + /** + * Closes a text stream. + * It is not necessary to close standard streams; they close automatically when the process ends. If + * you close a standard stream, be aware that any other pointers to that standard stream become invalid. + */ + Close(): void; +} + +interface TextStreamWriter extends TextStreamBase { + /** + * Sends a string to an output stream. + */ + Write(s: string): void; + + /** + * Sends a specified number of blank lines (newline characters) to an output stream. + */ + WriteBlankLines(intLines: number): void; + + /** + * Sends a string followed by a newline character to an output stream. + */ + WriteLine(s: string): void; +} + +interface TextStreamReader extends TextStreamBase { + /** + * Returns a specified number of characters from an input stream, starting at the current pointer position. + * Does not return until the ENTER key is pressed. + * Can only be used on a stream in reading mode; causes an error in writing or appending mode. + */ + Read(characters: number): string; + + /** + * Returns all characters from an input stream. + * Can only be used on a stream in reading mode; causes an error in writing or appending mode. + */ + ReadAll(): string; + + /** + * Returns an entire line from an input stream. + * Although this method extracts the newline character, it does not add it to the returned string. + * Can only be used on a stream in reading mode; causes an error in writing or appending mode. + */ + ReadLine(): string; + + /** + * Skips a specified number of characters when reading from an input text stream. + * Can only be used on a stream in reading mode; causes an error in writing or appending mode. + * @param characters Positive number of characters to skip forward. (Backward skipping is not supported.) + */ + Skip(characters: number): void; + + /** + * Skips the next line when reading from an input text stream. + * Can only be used on a stream in reading mode, not writing or appending mode. + */ + SkipLine(): void; + + /** + * Indicates whether the stream pointer position is at the end of a line. + */ + AtEndOfLine: boolean; + + /** + * Indicates whether the stream pointer position is at the end of a stream. + */ + AtEndOfStream: boolean; +} + +declare var WScript: { + /** + * Outputs text to either a message box (under WScript.exe) or the command console window followed by + * a newline (under CScript.exe). + */ + Echo(s: any): void; + + /** + * Exposes the write-only error output stream for the current script. + * Can be accessed only while using CScript.exe. + */ + StdErr: TextStreamWriter; + + /** + * Exposes the write-only output stream for the current script. + * Can be accessed only while using CScript.exe. + */ + StdOut: TextStreamWriter; + Arguments: { length: number; Item(n: number): string; }; + + /** + * The full path of the currently running script. + */ + ScriptFullName: string; + + /** + * Forces the script to stop immediately, with an optional exit code. + */ + Quit(exitCode?: number): number; + + /** + * The Windows Script Host build version number. + */ + BuildVersion: number; + + /** + * Fully qualified path of the host executable. + */ + FullName: string; + + /** + * Gets/sets the script mode - interactive(true) or batch(false). + */ + Interactive: boolean; + + /** + * The name of the host executable (WScript.exe or CScript.exe). + */ + Name: string; + + /** + * Path of the directory containing the host executable. + */ + Path: string; + + /** + * The filename of the currently running script. + */ + ScriptName: string; + + /** + * Exposes the read-only input stream for the current script. + * Can be accessed only while using CScript.exe. + */ + StdIn: TextStreamReader; + + /** + * Windows Script Host version + */ + Version: string; + + /** + * Connects a COM object's event sources to functions named with a given prefix, in the form prefix_event. + */ + ConnectObject(objEventSource: any, strPrefix: string): void; + + /** + * Creates a COM object. + * @param strProgiID + * @param strPrefix Function names in the form prefix_event will be bound to this object's COM events. + */ + CreateObject(strProgID: string, strPrefix?: string): any; + + /** + * Disconnects a COM object from its event sources. + */ + DisconnectObject(obj: any): void; + + /** + * Retrieves an existing object with the specified ProgID from memory, or creates a new one from a file. + * @param strPathname Fully qualified path to the file containing the object persisted to disk. + * For objects in memory, pass a zero-length string. + * @param strProgID + * @param strPrefix Function names in the form prefix_event will be bound to this object's COM events. + */ + GetObject(strPathname: string, strProgID?: string, strPrefix?: string): any; + + /** + * Suspends script execution for a specified length of time, then continues execution. + * @param intTime Interval (in milliseconds) to suspend script execution. + */ + Sleep(intTime: number): void; +}; + +/** + * WSH is an alias for WScript under Windows Script Host + */ +declare var WSH: typeof WScript; + +/** + * Represents an Automation SAFEARRAY + */ +declare class SafeArray { + private constructor(); + private SafeArray_typekey: SafeArray; +} + +/** + * Allows enumerating over a COM collection, which may not have indexed item access. + */ +interface Enumerator { + /** + * Returns true if the current item is the last one in the collection, or the collection is empty, + * or the current item is undefined. + */ + atEnd(): boolean; + + /** + * Returns the current item in the collection + */ + item(): T; + + /** + * Resets the current item in the collection to the first item. If there are no items in the collection, + * the current item is set to undefined. + */ + moveFirst(): void; + + /** + * Moves the current item to the next item in the collection. If the enumerator is at the end of + * the collection or the collection is empty, the current item is set to undefined. + */ + moveNext(): void; +} + +interface EnumeratorConstructor { + new (safearray: SafeArray): Enumerator; + new (collection: { Item(index: any): T }): Enumerator; + new (collection: any): Enumerator; +} + +declare var Enumerator: EnumeratorConstructor; + +/** + * Enables reading from a COM safe array, which might have an alternate lower bound, or multiple dimensions. + */ +interface VBArray { + /** + * Returns the number of dimensions (1-based). + */ + dimensions(): number; + + /** + * Takes an index for each dimension in the array, and returns the item at the corresponding location. + */ + getItem(dimension1Index: number, ...dimensionNIndexes: number[]): T; + + /** + * Returns the smallest available index for a given dimension. + * @param dimension 1-based dimension (defaults to 1) + */ + lbound(dimension?: number): number; + + /** + * Returns the largest available index for a given dimension. + * @param dimension 1-based dimension (defaults to 1) + */ + ubound(dimension?: number): number; + + /** + * Returns a Javascript array with all the elements in the VBArray. If there are multiple dimensions, + * each successive dimension is appended to the end of the array. + * Example: [[1,2,3],[4,5,6]] becomes [1,2,3,4,5,6] + */ + toArray(): T[]; +} + +interface VBArrayConstructor { + new (safeArray: SafeArray): VBArray; +} + +declare var VBArray: VBArrayConstructor; + +/** + * Automation date (VT_DATE) + */ +declare class VarDate { + private constructor(); + private VarDate_typekey: VarDate; +} + +interface DateConstructor { + new (vd: VarDate): Date; +} + +interface Date { + getVarDate: () => VarDate; +} diff --git a/node_modules/typescript/lib/lib.webworker.d.ts b/node_modules/typescript/lib/lib.webworker.d.ts new file mode 100644 index 0000000..2387027 --- /dev/null +++ b/node_modules/typescript/lib/lib.webworker.d.ts @@ -0,0 +1,4294 @@ +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + + + +/// + + +///////////////////////////// +/// Worker APIs +///////////////////////////// + +interface AddEventListenerOptions extends EventListenerOptions { + once?: boolean; + passive?: boolean; +} + +interface AesCbcParams extends Algorithm { + iv: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer; +} + +interface AesCtrParams extends Algorithm { + counter: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer; + length: number; +} + +interface AesDerivedKeyParams extends Algorithm { + length: number; +} + +interface AesGcmParams extends Algorithm { + additionalData?: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer; + iv: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer; + tagLength?: number; +} + +interface AesKeyAlgorithm extends KeyAlgorithm { + length: number; +} + +interface AesKeyGenParams extends Algorithm { + length: number; +} + +interface Algorithm { + name: string; +} + +interface BlobPropertyBag { + endings?: EndingType; + type?: string; +} + +interface CacheQueryOptions { + cacheName?: string; + ignoreMethod?: boolean; + ignoreSearch?: boolean; + ignoreVary?: boolean; +} + +interface ClientQueryOptions { + includeUncontrolled?: boolean; + type?: ClientTypes; +} + +interface CloseEventInit extends EventInit { + code?: number; + reason?: string; + wasClean?: boolean; +} + +interface CryptoKeyPair { + privateKey?: CryptoKey; + publicKey?: CryptoKey; +} + +interface CustomEventInit extends EventInit { + detail?: T; +} + +interface DOMMatrix2DInit { + a?: number; + b?: number; + c?: number; + d?: number; + e?: number; + f?: number; + m11?: number; + m12?: number; + m21?: number; + m22?: number; + m41?: number; + m42?: number; +} + +interface DOMMatrixInit extends DOMMatrix2DInit { + is2D?: boolean; + m13?: number; + m14?: number; + m23?: number; + m24?: number; + m31?: number; + m32?: number; + m33?: number; + m34?: number; + m43?: number; + m44?: number; +} + +interface DOMPointInit { + w?: number; + x?: number; + y?: number; + z?: number; +} + +interface DOMQuadInit { + p1?: DOMPointInit; + p2?: DOMPointInit; + p3?: DOMPointInit; + p4?: DOMPointInit; +} + +interface DOMRectInit { + height?: number; + width?: number; + x?: number; + y?: number; +} + +interface EcKeyGenParams extends Algorithm { + namedCurve: NamedCurve; +} + +interface EcKeyImportParams extends Algorithm { + namedCurve: NamedCurve; +} + +interface EcdhKeyDeriveParams extends Algorithm { + public: CryptoKey; +} + +interface EcdsaParams extends Algorithm { + hash: HashAlgorithmIdentifier; +} + +interface ErrorEventInit extends EventInit { + colno?: number; + error?: any; + filename?: string; + lineno?: number; + message?: string; +} + +interface EventInit { + bubbles?: boolean; + cancelable?: boolean; + composed?: boolean; +} + +interface EventListenerOptions { + capture?: boolean; +} + +interface ExtendableEventInit extends EventInit { +} + +interface ExtendableMessageEventInit extends ExtendableEventInit { + data?: any; + lastEventId?: string; + origin?: string; + ports?: MessagePort[]; + source?: Client | ServiceWorker | MessagePort | null; +} + +interface FetchEventInit extends ExtendableEventInit { + clientId?: string; + preloadResponse?: Promise; + request: Request; + resultingClientId?: string; + targetClientId?: string; +} + +interface FilePropertyBag extends BlobPropertyBag { + lastModified?: number; +} + +interface GetNotificationOptions { + tag?: string; +} + +interface HmacImportParams extends Algorithm { + hash: HashAlgorithmIdentifier; + length?: number; +} + +interface HmacKeyGenParams extends Algorithm { + hash: HashAlgorithmIdentifier; + length?: number; +} + +interface IDBIndexParameters { + multiEntry?: boolean; + unique?: boolean; +} + +interface IDBObjectStoreParameters { + autoIncrement?: boolean; + keyPath?: string | string[] | null; +} + +interface IDBVersionChangeEventInit extends EventInit { + newVersion?: number | null; + oldVersion?: number; +} + +interface JsonWebKey { + alg?: string; + crv?: string; + d?: string; + dp?: string; + dq?: string; + e?: string; + ext?: boolean; + k?: string; + key_ops?: string[]; + kty?: string; + n?: string; + oth?: RsaOtherPrimesInfo[]; + p?: string; + q?: string; + qi?: string; + use?: string; + x?: string; + y?: string; +} + +interface KeyAlgorithm { + name: string; +} + +interface MessageEventInit extends EventInit { + data?: any; + lastEventId?: string; + origin?: string; + ports?: MessagePort[]; + source?: MessageEventSource | null; +} + +interface NavigationPreloadState { + enabled?: boolean; + headerValue?: string; +} + +interface NotificationAction { + action: string; + icon?: string; + title: string; +} + +interface NotificationEventInit extends ExtendableEventInit { + action?: string; + notification: Notification; +} + +interface NotificationOptions { + actions?: NotificationAction[]; + badge?: string; + body?: string; + data?: any; + dir?: NotificationDirection; + icon?: string; + image?: string; + lang?: string; + renotify?: boolean; + requireInteraction?: boolean; + silent?: boolean; + tag?: string; + timestamp?: number; + vibrate?: VibratePattern; +} + +interface Pbkdf2Params extends Algorithm { + hash: HashAlgorithmIdentifier; + iterations: number; + salt: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer; +} + +interface PerformanceObserverInit { + buffered?: boolean; + entryTypes: string[]; +} + +interface PipeOptions { + preventAbort?: boolean; + preventCancel?: boolean; + preventClose?: boolean; +} + +interface ProgressEventInit extends EventInit { + lengthComputable?: boolean; + loaded?: number; + total?: number; +} + +interface PromiseRejectionEventInit extends EventInit { + promise: Promise; + reason?: any; +} + +interface PushEventInit extends ExtendableEventInit { + data?: PushMessageDataInit; +} + +interface PushSubscriptionChangeInit extends ExtendableEventInit { + newSubscription?: PushSubscription; + oldSubscription?: PushSubscription; +} + +interface PushSubscriptionJSON { + endpoint?: string; + expirationTime?: number | null; + keys?: Record; +} + +interface PushSubscriptionOptionsInit { + applicationServerKey?: BufferSource | string | null; + userVisibleOnly?: boolean; +} + +interface QueuingStrategy { + highWaterMark?: number; + size?: QueuingStrategySizeCallback; +} + +interface RegistrationOptions { + scope?: string; + type?: WorkerType; + updateViaCache?: ServiceWorkerUpdateViaCache; +} + +interface RequestInit { + body?: BodyInit | null; + cache?: RequestCache; + credentials?: RequestCredentials; + headers?: HeadersInit; + integrity?: string; + keepalive?: boolean; + method?: string; + mode?: RequestMode; + redirect?: RequestRedirect; + referrer?: string; + referrerPolicy?: ReferrerPolicy; + signal?: AbortSignal | null; + window?: any; +} + +interface ResponseInit { + headers?: HeadersInit; + status?: number; + statusText?: string; +} + +interface RsaHashedImportParams extends Algorithm { + hash: HashAlgorithmIdentifier; +} + +interface RsaHashedKeyGenParams extends RsaKeyGenParams { + hash: HashAlgorithmIdentifier; +} + +interface RsaKeyGenParams extends Algorithm { + modulusLength: number; + publicExponent: BigInteger; +} + +interface RsaOaepParams extends Algorithm { + label?: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer; +} + +interface RsaOtherPrimesInfo { + d?: string; + r?: string; + t?: string; +} + +interface RsaPssParams extends Algorithm { + saltLength: number; +} + +interface StorageEstimate { + quota?: number; + usage?: number; +} + +interface SyncEventInit extends ExtendableEventInit { + lastChance?: boolean; + tag: string; +} + +interface TextDecodeOptions { + stream?: boolean; +} + +interface TextDecoderOptions { + fatal?: boolean; + ignoreBOM?: boolean; +} + +interface Transformer { + flush?: TransformStreamDefaultControllerCallback; + readableType?: undefined; + start?: TransformStreamDefaultControllerCallback; + transform?: TransformStreamDefaultControllerTransformCallback; + writableType?: undefined; +} + +interface UnderlyingByteSource { + autoAllocateChunkSize?: number; + cancel?: ReadableStreamErrorCallback; + pull?: ReadableByteStreamControllerCallback; + start?: ReadableByteStreamControllerCallback; + type: "bytes"; +} + +interface UnderlyingSink { + abort?: WritableStreamErrorCallback; + close?: WritableStreamDefaultControllerCloseCallback; + start?: WritableStreamDefaultControllerStartCallback; + type?: undefined; + write?: WritableStreamDefaultControllerWriteCallback; +} + +interface UnderlyingSource { + cancel?: ReadableStreamErrorCallback; + pull?: ReadableStreamDefaultControllerCallback; + start?: ReadableStreamDefaultControllerCallback; + type?: undefined; +} + +interface WebGLContextAttributes { + alpha?: GLboolean; + antialias?: GLboolean; + depth?: GLboolean; + failIfMajorPerformanceCaveat?: boolean; + powerPreference?: WebGLPowerPreference; + premultipliedAlpha?: GLboolean; + preserveDrawingBuffer?: GLboolean; + stencil?: GLboolean; +} + +interface WebGLContextEventInit extends EventInit { + statusMessage?: string; +} + +interface WorkerOptions { + credentials?: RequestCredentials; + name?: string; + type?: WorkerType; +} + +interface EventListener { + (evt: Event): void; +} + +interface ANGLE_instanced_arrays { + drawArraysInstancedANGLE(mode: GLenum, first: GLint, count: GLsizei, primcount: GLsizei): void; + drawElementsInstancedANGLE(mode: GLenum, count: GLsizei, type: GLenum, offset: GLintptr, primcount: GLsizei): void; + vertexAttribDivisorANGLE(index: GLuint, divisor: GLuint): void; + readonly VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE: GLenum; +} + +interface AbortController { + /** + * Returns the AbortSignal object associated with this object. + */ + readonly signal: AbortSignal; + /** + * Invoking this method will set this object's AbortSignal's aborted flag and + * signal to any observers that the associated activity is to be aborted. + */ + abort(): void; +} + +declare var AbortController: { + prototype: AbortController; + new(): AbortController; +}; + +interface AbortSignalEventMap { + "abort": ProgressEvent; +} + +interface AbortSignal extends EventTarget { + /** + * Returns true if this AbortSignal's AbortController has signaled to abort, and false + * otherwise. + */ + readonly aborted: boolean; + onabort: ((this: AbortSignal, ev: ProgressEvent) => any) | null; + addEventListener(type: K, listener: (this: AbortSignal, ev: AbortSignalEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: AbortSignal, ev: AbortSignalEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var AbortSignal: { + prototype: AbortSignal; + new(): AbortSignal; +}; + +interface AbstractWorkerEventMap { + "error": ErrorEvent; +} + +interface AbstractWorker { + onerror: ((this: AbstractWorker, ev: ErrorEvent) => any) | null; + addEventListener(type: K, listener: (this: AbstractWorker, ev: AbstractWorkerEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: AbstractWorker, ev: AbstractWorkerEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +interface AesCfbParams extends Algorithm { + iv: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer; +} + +interface AesCmacParams extends Algorithm { + length: number; +} + +interface Blob { + readonly size: number; + readonly type: string; + slice(start?: number, end?: number, contentType?: string): Blob; +} + +declare var Blob: { + prototype: Blob; + new(blobParts?: BlobPart[], options?: BlobPropertyBag): Blob; +}; + +interface Body { + readonly body: ReadableStream | null; + readonly bodyUsed: boolean; + arrayBuffer(): Promise; + blob(): Promise; + formData(): Promise; + json(): Promise; + text(): Promise; +} + +interface BroadcastChannelEventMap { + "message": MessageEvent; + "messageerror": MessageEvent; +} + +interface BroadcastChannel extends EventTarget { + /** + * Returns the channel name (as passed to the constructor). + */ + readonly name: string; + onmessage: ((this: BroadcastChannel, ev: MessageEvent) => any) | null; + onmessageerror: ((this: BroadcastChannel, ev: MessageEvent) => any) | null; + /** + * Closes the BroadcastChannel object, opening it up to garbage collection. + */ + close(): void; + /** + * Sends the given message to other BroadcastChannel objects set up for this channel. Messages can be structured objects, e.g. nested objects and arrays. + */ + postMessage(message: any): void; + addEventListener(type: K, listener: (this: BroadcastChannel, ev: BroadcastChannelEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: BroadcastChannel, ev: BroadcastChannelEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var BroadcastChannel: { + prototype: BroadcastChannel; + new(name: string): BroadcastChannel; +}; + +interface BroadcastChannelEventMap { + message: MessageEvent; + messageerror: MessageEvent; +} + +interface ByteLengthQueuingStrategy extends QueuingStrategy { + highWaterMark: number; + size(chunk: ArrayBufferView): number; +} + +declare var ByteLengthQueuingStrategy: { + prototype: ByteLengthQueuingStrategy; + new(options: { highWaterMark: number }): ByteLengthQueuingStrategy; +}; + +interface Cache { + add(request: RequestInfo): Promise; + addAll(requests: RequestInfo[]): Promise; + delete(request: RequestInfo, options?: CacheQueryOptions): Promise; + keys(request?: RequestInfo, options?: CacheQueryOptions): Promise>; + match(request: RequestInfo, options?: CacheQueryOptions): Promise; + matchAll(request?: RequestInfo, options?: CacheQueryOptions): Promise>; + put(request: RequestInfo, response: Response): Promise; +} + +declare var Cache: { + prototype: Cache; + new(): Cache; +}; + +interface CacheStorage { + delete(cacheName: string): Promise; + has(cacheName: string): Promise; + keys(): Promise; + match(request: RequestInfo, options?: CacheQueryOptions): Promise; + open(cacheName: string): Promise; +} + +declare var CacheStorage: { + prototype: CacheStorage; + new(): CacheStorage; +}; + +interface CanvasGradient { + /** + * Adds a color stop with the given color to the gradient at the given offset. 0.0 is the offset + * at one end of the gradient, 1.0 is the offset at the other end. + * Throws an "IndexSizeError" DOMException if the offset + * is out of range. Throws a "SyntaxError" DOMException if + * the color cannot be parsed. + */ + addColorStop(offset: number, color: string): void; +} + +declare var CanvasGradient: { + prototype: CanvasGradient; + new(): CanvasGradient; +}; + +interface CanvasPath { + arc(x: number, y: number, radius: number, startAngle: number, endAngle: number, anticlockwise?: boolean): void; + arcTo(x1: number, y1: number, x2: number, y2: number, radius: number): void; + bezierCurveTo(cp1x: number, cp1y: number, cp2x: number, cp2y: number, x: number, y: number): void; + closePath(): void; + ellipse(x: number, y: number, radiusX: number, radiusY: number, rotation: number, startAngle: number, endAngle: number, anticlockwise?: boolean): void; + lineTo(x: number, y: number): void; + moveTo(x: number, y: number): void; + quadraticCurveTo(cpx: number, cpy: number, x: number, y: number): void; + rect(x: number, y: number, w: number, h: number): void; +} + +interface CanvasPattern { + /** + * Sets the transformation matrix that will be used when rendering the pattern during a fill or + * stroke painting operation. + */ + setTransform(transform?: DOMMatrix2DInit): void; +} + +declare var CanvasPattern: { + prototype: CanvasPattern; + new(): CanvasPattern; +}; + +interface Client { + readonly id: string; + readonly type: ClientTypes; + readonly url: string; + postMessage(message: any, transfer?: Transferable[]): void; +} + +declare var Client: { + prototype: Client; + new(): Client; +}; + +interface Clients { + claim(): Promise; + get(id: string): Promise; + matchAll(options?: ClientQueryOptions): Promise>; + openWindow(url: string): Promise; +} + +declare var Clients: { + prototype: Clients; + new(): Clients; +}; + +interface CloseEvent extends Event { + readonly code: number; + readonly reason: string; + readonly wasClean: boolean; + /** @deprecated */ + initCloseEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, wasCleanArg: boolean, codeArg: number, reasonArg: string): void; +} + +declare var CloseEvent: { + prototype: CloseEvent; + new(type: string, eventInitDict?: CloseEventInit): CloseEvent; +}; + +interface ConcatParams extends Algorithm { + algorithmId: Uint8Array; + hash?: string | Algorithm; + partyUInfo: Uint8Array; + partyVInfo: Uint8Array; + privateInfo?: Uint8Array; + publicInfo?: Uint8Array; +} + +interface Console { + memory: any; + assert(condition?: boolean, message?: string, ...data: any[]): void; + clear(): void; + count(label?: string): void; + debug(message?: any, ...optionalParams: any[]): void; + dir(value?: any, ...optionalParams: any[]): void; + dirxml(value: any): void; + error(message?: any, ...optionalParams: any[]): void; + exception(message?: string, ...optionalParams: any[]): void; + group(groupTitle?: string, ...optionalParams: any[]): void; + groupCollapsed(groupTitle?: string, ...optionalParams: any[]): void; + groupEnd(): void; + info(message?: any, ...optionalParams: any[]): void; + log(message?: any, ...optionalParams: any[]): void; + markTimeline(label?: string): void; + profile(reportName?: string): void; + profileEnd(reportName?: string): void; + table(...tabularData: any[]): void; + time(label?: string): void; + timeEnd(label?: string): void; + timeStamp(label?: string): void; + timeline(label?: string): void; + timelineEnd(label?: string): void; + trace(message?: any, ...optionalParams: any[]): void; + warn(message?: any, ...optionalParams: any[]): void; +} + +declare var Console: { + prototype: Console; + new(): Console; +}; + +interface CountQueuingStrategy extends QueuingStrategy { + highWaterMark: number; + size(chunk: any): 1; +} + +declare var CountQueuingStrategy: { + prototype: CountQueuingStrategy; + new(options: { highWaterMark: number }): CountQueuingStrategy; +}; + +interface Crypto { + readonly subtle: SubtleCrypto; + getRandomValues(array: T): T; +} + +declare var Crypto: { + prototype: Crypto; + new(): Crypto; +}; + +interface CryptoKey { + readonly algorithm: KeyAlgorithm; + readonly extractable: boolean; + readonly type: KeyType; + readonly usages: KeyUsage[]; +} + +declare var CryptoKey: { + prototype: CryptoKey; + new(): CryptoKey; +}; + +interface CustomEvent extends Event { + /** + * Returns any custom data event was created with. + * Typically used for synthetic events. + */ + readonly detail: T; + initCustomEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, detailArg: T): void; +} + +declare var CustomEvent: { + prototype: CustomEvent; + new(typeArg: string, eventInitDict?: CustomEventInit): CustomEvent; +}; + +interface DOMException { + readonly code: number; + readonly message: string; + readonly name: string; + readonly ABORT_ERR: number; + readonly DATA_CLONE_ERR: number; + readonly DOMSTRING_SIZE_ERR: number; + readonly HIERARCHY_REQUEST_ERR: number; + readonly INDEX_SIZE_ERR: number; + readonly INUSE_ATTRIBUTE_ERR: number; + readonly INVALID_ACCESS_ERR: number; + readonly INVALID_CHARACTER_ERR: number; + readonly INVALID_MODIFICATION_ERR: number; + readonly INVALID_NODE_TYPE_ERR: number; + readonly INVALID_STATE_ERR: number; + readonly NAMESPACE_ERR: number; + readonly NETWORK_ERR: number; + readonly NOT_FOUND_ERR: number; + readonly NOT_SUPPORTED_ERR: number; + readonly NO_DATA_ALLOWED_ERR: number; + readonly NO_MODIFICATION_ALLOWED_ERR: number; + readonly QUOTA_EXCEEDED_ERR: number; + readonly SECURITY_ERR: number; + readonly SYNTAX_ERR: number; + readonly TIMEOUT_ERR: number; + readonly TYPE_MISMATCH_ERR: number; + readonly URL_MISMATCH_ERR: number; + readonly VALIDATION_ERR: number; + readonly WRONG_DOCUMENT_ERR: number; +} + +declare var DOMException: { + prototype: DOMException; + new(message?: string, name?: string): DOMException; + readonly ABORT_ERR: number; + readonly DATA_CLONE_ERR: number; + readonly DOMSTRING_SIZE_ERR: number; + readonly HIERARCHY_REQUEST_ERR: number; + readonly INDEX_SIZE_ERR: number; + readonly INUSE_ATTRIBUTE_ERR: number; + readonly INVALID_ACCESS_ERR: number; + readonly INVALID_CHARACTER_ERR: number; + readonly INVALID_MODIFICATION_ERR: number; + readonly INVALID_NODE_TYPE_ERR: number; + readonly INVALID_STATE_ERR: number; + readonly NAMESPACE_ERR: number; + readonly NETWORK_ERR: number; + readonly NOT_FOUND_ERR: number; + readonly NOT_SUPPORTED_ERR: number; + readonly NO_DATA_ALLOWED_ERR: number; + readonly NO_MODIFICATION_ALLOWED_ERR: number; + readonly QUOTA_EXCEEDED_ERR: number; + readonly SECURITY_ERR: number; + readonly SYNTAX_ERR: number; + readonly TIMEOUT_ERR: number; + readonly TYPE_MISMATCH_ERR: number; + readonly URL_MISMATCH_ERR: number; + readonly VALIDATION_ERR: number; + readonly WRONG_DOCUMENT_ERR: number; +}; + +interface DOMMatrix extends DOMMatrixReadOnly { + a: number; + b: number; + c: number; + d: number; + e: number; + f: number; + m11: number; + m12: number; + m13: number; + m14: number; + m21: number; + m22: number; + m23: number; + m24: number; + m31: number; + m32: number; + m33: number; + m34: number; + m41: number; + m42: number; + m43: number; + m44: number; + invertSelf(): DOMMatrix; + multiplySelf(other?: DOMMatrixInit): DOMMatrix; + preMultiplySelf(other?: DOMMatrixInit): DOMMatrix; + rotateAxisAngleSelf(x?: number, y?: number, z?: number, angle?: number): DOMMatrix; + rotateFromVectorSelf(x?: number, y?: number): DOMMatrix; + rotateSelf(rotX?: number, rotY?: number, rotZ?: number): DOMMatrix; + scale3dSelf(scale?: number, originX?: number, originY?: number, originZ?: number): DOMMatrix; + scaleSelf(scaleX?: number, scaleY?: number, scaleZ?: number, originX?: number, originY?: number, originZ?: number): DOMMatrix; + skewXSelf(sx?: number): DOMMatrix; + skewYSelf(sy?: number): DOMMatrix; + translateSelf(tx?: number, ty?: number, tz?: number): DOMMatrix; +} + +declare var DOMMatrix: { + prototype: DOMMatrix; + new(init?: string | number[]): DOMMatrix; + fromFloat32Array(array32: Float32Array): DOMMatrix; + fromFloat64Array(array64: Float64Array): DOMMatrix; + fromMatrix(other?: DOMMatrixInit): DOMMatrix; +}; + +interface DOMMatrixReadOnly { + readonly a: number; + readonly b: number; + readonly c: number; + readonly d: number; + readonly e: number; + readonly f: number; + readonly is2D: boolean; + readonly isIdentity: boolean; + readonly m11: number; + readonly m12: number; + readonly m13: number; + readonly m14: number; + readonly m21: number; + readonly m22: number; + readonly m23: number; + readonly m24: number; + readonly m31: number; + readonly m32: number; + readonly m33: number; + readonly m34: number; + readonly m41: number; + readonly m42: number; + readonly m43: number; + readonly m44: number; + flipX(): DOMMatrix; + flipY(): DOMMatrix; + inverse(): DOMMatrix; + multiply(other?: DOMMatrixInit): DOMMatrix; + rotate(rotX?: number, rotY?: number, rotZ?: number): DOMMatrix; + rotateAxisAngle(x?: number, y?: number, z?: number, angle?: number): DOMMatrix; + rotateFromVector(x?: number, y?: number): DOMMatrix; + scale(scaleX?: number, scaleY?: number, scaleZ?: number, originX?: number, originY?: number, originZ?: number): DOMMatrix; + scale3d(scale?: number, originX?: number, originY?: number, originZ?: number): DOMMatrix; + skewX(sx?: number): DOMMatrix; + skewY(sy?: number): DOMMatrix; + toFloat32Array(): Float32Array; + toFloat64Array(): Float64Array; + toJSON(): any; + transformPoint(point?: DOMPointInit): DOMPoint; + translate(tx?: number, ty?: number, tz?: number): DOMMatrix; +} + +declare var DOMMatrixReadOnly: { + prototype: DOMMatrixReadOnly; + new(init?: string | number[]): DOMMatrixReadOnly; + fromFloat32Array(array32: Float32Array): DOMMatrixReadOnly; + fromFloat64Array(array64: Float64Array): DOMMatrixReadOnly; + fromMatrix(other?: DOMMatrixInit): DOMMatrixReadOnly; +}; + +interface DOMPoint extends DOMPointReadOnly { + w: number; + x: number; + y: number; + z: number; +} + +declare var DOMPoint: { + prototype: DOMPoint; + new(x?: number, y?: number, z?: number, w?: number): DOMPoint; + fromPoint(other?: DOMPointInit): DOMPoint; +}; + +interface DOMPointReadOnly { + readonly w: number; + readonly x: number; + readonly y: number; + readonly z: number; + matrixTransform(matrix?: DOMMatrixInit): DOMPoint; + toJSON(): any; +} + +declare var DOMPointReadOnly: { + prototype: DOMPointReadOnly; + new(x?: number, y?: number, z?: number, w?: number): DOMPointReadOnly; + fromPoint(other?: DOMPointInit): DOMPointReadOnly; +}; + +interface DOMQuad { + readonly p1: DOMPoint; + readonly p2: DOMPoint; + readonly p3: DOMPoint; + readonly p4: DOMPoint; + getBounds(): DOMRect; + toJSON(): any; +} + +declare var DOMQuad: { + prototype: DOMQuad; + new(p1?: DOMPointInit, p2?: DOMPointInit, p3?: DOMPointInit, p4?: DOMPointInit): DOMQuad; + fromQuad(other?: DOMQuadInit): DOMQuad; + fromRect(other?: DOMRectInit): DOMQuad; +}; + +interface DOMRect extends DOMRectReadOnly { + height: number; + width: number; + x: number; + y: number; +} + +declare var DOMRect: { + prototype: DOMRect; + new(x?: number, y?: number, width?: number, height?: number): DOMRect; + fromRect(other?: DOMRectInit): DOMRect; +}; + +interface DOMRectReadOnly { + readonly bottom: number; + readonly height: number; + readonly left: number; + readonly right: number; + readonly top: number; + readonly width: number; + readonly x: number; + readonly y: number; + toJSON(): any; +} + +declare var DOMRectReadOnly: { + prototype: DOMRectReadOnly; + new(x?: number, y?: number, width?: number, height?: number): DOMRectReadOnly; + fromRect(other?: DOMRectInit): DOMRectReadOnly; +}; + +interface DOMStringList { + /** + * Returns the number of strings in strings. + */ + readonly length: number; + /** + * Returns true if strings contains string, and false + * otherwise. + */ + contains(string: string): boolean; + /** + * Returns the string with index index from strings. + */ + item(index: number): string | null; + [index: number]: string; +} + +declare var DOMStringList: { + prototype: DOMStringList; + new(): DOMStringList; +}; + +interface DedicatedWorkerGlobalScopeEventMap extends WorkerGlobalScopeEventMap { + "message": MessageEvent; +} + +interface DedicatedWorkerGlobalScope extends WorkerGlobalScope { + onmessage: ((this: DedicatedWorkerGlobalScope, ev: MessageEvent) => any) | null; + close(): void; + postMessage(message: any, transfer?: Transferable[]): void; + addEventListener(type: K, listener: (this: DedicatedWorkerGlobalScope, ev: DedicatedWorkerGlobalScopeEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: DedicatedWorkerGlobalScope, ev: DedicatedWorkerGlobalScopeEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var DedicatedWorkerGlobalScope: { + prototype: DedicatedWorkerGlobalScope; + new(): DedicatedWorkerGlobalScope; +}; + +interface DhImportKeyParams extends Algorithm { + generator: Uint8Array; + prime: Uint8Array; +} + +interface DhKeyAlgorithm extends KeyAlgorithm { + generator: Uint8Array; + prime: Uint8Array; +} + +interface DhKeyDeriveParams extends Algorithm { + public: CryptoKey; +} + +interface DhKeyGenParams extends Algorithm { + generator: Uint8Array; + prime: Uint8Array; +} + +interface EXT_blend_minmax { + readonly MAX_EXT: GLenum; + readonly MIN_EXT: GLenum; +} + +interface EXT_frag_depth { +} + +interface EXT_sRGB { + readonly FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING_EXT: GLenum; + readonly SRGB8_ALPHA8_EXT: GLenum; + readonly SRGB_ALPHA_EXT: GLenum; + readonly SRGB_EXT: GLenum; +} + +interface EXT_shader_texture_lod { +} + +interface EXT_texture_filter_anisotropic { + readonly MAX_TEXTURE_MAX_ANISOTROPY_EXT: GLenum; + readonly TEXTURE_MAX_ANISOTROPY_EXT: GLenum; +} + +interface ErrorEvent extends Event { + readonly colno: number; + readonly error: any; + readonly filename: string; + readonly lineno: number; + readonly message: string; +} + +declare var ErrorEvent: { + prototype: ErrorEvent; + new(type: string, eventInitDict?: ErrorEventInit): ErrorEvent; +}; + +interface Event { + /** + * Returns true or false depending on how event was initialized. True if event goes through its target's ancestors in reverse tree order, and false otherwise. + */ + readonly bubbles: boolean; + cancelBubble: boolean; + readonly cancelable: boolean; + /** + * Returns true or false depending on how event was initialized. True if event invokes listeners past a ShadowRoot node that is the root of its target, and false otherwise. + */ + readonly composed: boolean; + /** + * Returns the object whose event listener's callback is currently being + * invoked. + */ + readonly currentTarget: EventTarget | null; + readonly defaultPrevented: boolean; + readonly eventPhase: number; + /** + * Returns true if event was dispatched by the user agent, and + * false otherwise. + */ + readonly isTrusted: boolean; + returnValue: boolean; + /** + * Returns the object to which event is dispatched (its target). + */ + readonly target: EventTarget | null; + /** + * Returns the event's timestamp as the number of milliseconds measured relative to + * the time origin. + */ + readonly timeStamp: number; + /** + * Returns the type of event, e.g. + * "click", "hashchange", or + * "submit". + */ + readonly type: string; + composedPath(): EventTarget[]; + initEvent(type: string, bubbles?: boolean, cancelable?: boolean): void; + preventDefault(): void; + /** + * Invoking this method prevents event from reaching + * any registered event listeners after the current one finishes running and, when dispatched in a tree, also prevents event from reaching any + * other objects. + */ + stopImmediatePropagation(): void; + /** + * When dispatched in a tree, invoking this method prevents event from reaching any objects other than the current object. + */ + stopPropagation(): void; + readonly AT_TARGET: number; + readonly BUBBLING_PHASE: number; + readonly CAPTURING_PHASE: number; + readonly NONE: number; +} + +declare var Event: { + prototype: Event; + new(type: string, eventInitDict?: EventInit): Event; + readonly AT_TARGET: number; + readonly BUBBLING_PHASE: number; + readonly CAPTURING_PHASE: number; + readonly NONE: number; +}; + +interface EventListenerObject { + handleEvent(evt: Event): void; +} + +interface EventSource extends EventTarget { + readonly CLOSED: number; + readonly CONNECTING: number; + readonly OPEN: number; + onerror: (evt: MessageEvent) => any; + onmessage: (evt: MessageEvent) => any; + onopen: (evt: MessageEvent) => any; + readonly readyState: number; + readonly url: string; + readonly withCredentials: boolean; + close(): void; +} + +declare var EventSource: { + prototype: EventSource; + new(url: string, eventSourceInitDict?: EventSourceInit): EventSource; +}; + +interface EventSourceInit { + readonly withCredentials: boolean; +} + +interface EventTarget { + /** + * Appends an event listener for events whose type attribute value is type. The callback argument sets the callback that will be invoked when the event is dispatched. + * The options argument sets listener-specific options. For compatibility this can be a + * boolean, in which case the method behaves exactly as if the value was specified as options's capture. + * When set to true, options's capture prevents callback from being invoked when the event's eventPhase attribute value is BUBBLING_PHASE. When false (or not present), callback will not be invoked when event's eventPhase attribute value is CAPTURING_PHASE. Either way, callback will be invoked if event's eventPhase attribute value is AT_TARGET. + * When set to true, options's passive indicates that the callback will not cancel the event by invoking preventDefault(). This is used to enable performance optimizations described in §2.8 Observing event listeners. + * When set to true, options's once indicates that the callback will only be invoked once after which the event listener will + * be removed. + * The event listener is appended to target's event listener list and is not appended if it has the same type, callback, and capture. + */ + addEventListener(type: string, listener: EventListenerOrEventListenerObject | null, options?: boolean | AddEventListenerOptions): void; + /** + * Dispatches a synthetic event event to target and returns true + * if either event's cancelable attribute value is false or its preventDefault() method was not invoked, and false otherwise. + */ + dispatchEvent(event: Event): boolean; + /** + * Removes the event listener in target's event listener list with the same type, callback, and options. + */ + removeEventListener(type: string, callback: EventListenerOrEventListenerObject | null, options?: EventListenerOptions | boolean): void; +} + +declare var EventTarget: { + prototype: EventTarget; + new(): EventTarget; +}; + +interface ExtendableEvent extends Event { + waitUntil(f: Promise): void; +} + +declare var ExtendableEvent: { + prototype: ExtendableEvent; + new(type: string, eventInitDict?: ExtendableEventInit): ExtendableEvent; +}; + +interface ExtendableMessageEvent extends ExtendableEvent { + readonly data: any; + readonly lastEventId: string; + readonly origin: string; + readonly ports: ReadonlyArray; + readonly source: Client | ServiceWorker | MessagePort | null; +} + +declare var ExtendableMessageEvent: { + prototype: ExtendableMessageEvent; + new(type: string, eventInitDict?: ExtendableMessageEventInit): ExtendableMessageEvent; +}; + +interface FetchEvent extends ExtendableEvent { + readonly clientId: string; + readonly preloadResponse: Promise; + readonly request: Request; + readonly resultingClientId: string; + readonly targetClientId: string; + respondWith(r: Promise): void; +} + +declare var FetchEvent: { + prototype: FetchEvent; + new(type: string, eventInitDict: FetchEventInit): FetchEvent; +}; + +interface File extends Blob { + readonly lastModified: number; + readonly name: string; +} + +declare var File: { + prototype: File; + new(fileBits: BlobPart[], fileName: string, options?: FilePropertyBag): File; +}; + +interface FileList { + readonly length: number; + item(index: number): File | null; + [index: number]: File; +} + +declare var FileList: { + prototype: FileList; + new(): FileList; +}; + +interface FileReaderEventMap { + "abort": ProgressEvent; + "error": ProgressEvent; + "load": ProgressEvent; + "loadend": ProgressEvent; + "loadstart": ProgressEvent; + "progress": ProgressEvent; +} + +interface FileReader extends EventTarget { + readonly error: DOMException | null; + onabort: ((this: FileReader, ev: ProgressEvent) => any) | null; + onerror: ((this: FileReader, ev: ProgressEvent) => any) | null; + onload: ((this: FileReader, ev: ProgressEvent) => any) | null; + onloadend: ((this: FileReader, ev: ProgressEvent) => any) | null; + onloadstart: ((this: FileReader, ev: ProgressEvent) => any) | null; + onprogress: ((this: FileReader, ev: ProgressEvent) => any) | null; + readonly readyState: number; + readonly result: string | ArrayBuffer | null; + abort(): void; + readAsArrayBuffer(blob: Blob): void; + readAsBinaryString(blob: Blob): void; + readAsDataURL(blob: Blob): void; + readAsText(blob: Blob, encoding?: string): void; + readonly DONE: number; + readonly EMPTY: number; + readonly LOADING: number; + addEventListener(type: K, listener: (this: FileReader, ev: FileReaderEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: FileReader, ev: FileReaderEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var FileReader: { + prototype: FileReader; + new(): FileReader; + readonly DONE: number; + readonly EMPTY: number; + readonly LOADING: number; +}; + +interface FileReaderSync { + readAsArrayBuffer(blob: Blob): ArrayBuffer; + readAsBinaryString(blob: Blob): string; + readAsDataURL(blob: Blob): string; + readAsText(blob: Blob, encoding?: string): string; +} + +declare var FileReaderSync: { + prototype: FileReaderSync; + new(): FileReaderSync; +}; + +interface FormData { + append(name: string, value: string | Blob, fileName?: string): void; + delete(name: string): void; + get(name: string): FormDataEntryValue | null; + getAll(name: string): FormDataEntryValue[]; + has(name: string): boolean; + set(name: string, value: string | Blob, fileName?: string): void; + forEach(callbackfn: (value: FormDataEntryValue, key: string, parent: FormData) => void, thisArg?: any): void; +} + +declare var FormData: { + prototype: FormData; + new(): FormData; +}; + +interface GlobalFetch { + fetch(input: RequestInfo, init?: RequestInit): Promise; +} + +interface Headers { + append(name: string, value: string): void; + delete(name: string): void; + get(name: string): string | null; + has(name: string): boolean; + set(name: string, value: string): void; + forEach(callbackfn: (value: string, key: string, parent: Headers) => void, thisArg?: any): void; +} + +declare var Headers: { + prototype: Headers; + new(init?: HeadersInit): Headers; +}; + +interface HkdfCtrParams extends Algorithm { + context: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer; + hash: string | Algorithm; + label: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer; +} + +interface IDBArrayKey extends Array { +} + +interface IDBCursor { + /** + * Returns the direction ("next", "nextunique", "prev" or "prevunique") + * of the cursor. + */ + readonly direction: IDBCursorDirection; + /** + * Returns the key of the cursor. + * Throws a "InvalidStateError" DOMException if the cursor is advancing or is finished. + */ + readonly key: IDBValidKey | IDBKeyRange; + /** + * Returns the effective key of the cursor. + * Throws a "InvalidStateError" DOMException if the cursor is advancing or is finished. + */ + readonly primaryKey: IDBValidKey | IDBKeyRange; + /** + * Returns the IDBObjectStore or IDBIndex the cursor was opened from. + */ + readonly source: IDBObjectStore | IDBIndex; + /** + * Advances the cursor through the next count records in + * range. + */ + advance(count: number): void; + /** + * Advances the cursor to the next record in range matching or + * after key. + */ + continue(key?: IDBValidKey | IDBKeyRange): void; + /** + * Advances the cursor to the next record in range matching + * or after key and primaryKey. Throws an "InvalidAccessError" DOMException if the source is not an index. + */ + continuePrimaryKey(key: IDBValidKey | IDBKeyRange, primaryKey: IDBValidKey | IDBKeyRange): void; + /** + * Delete the record pointed at by the cursor with a new value. + * If successful, request's result will be undefined. + */ + delete(): IDBRequest; + /** + * Updated the record pointed at by the cursor with a new value. + * Throws a "DataError" DOMException if the effective object store uses in-line keys and the key would have changed. + * If successful, request's result will be the record's key. + */ + update(value: any): IDBRequest; +} + +declare var IDBCursor: { + prototype: IDBCursor; + new(): IDBCursor; +}; + +interface IDBCursorWithValue extends IDBCursor { + /** + * Returns the cursor's current value. + */ + readonly value: any; +} + +declare var IDBCursorWithValue: { + prototype: IDBCursorWithValue; + new(): IDBCursorWithValue; +}; + +interface IDBDatabaseEventMap { + "abort": Event; + "close": Event; + "error": Event; + "versionchange": IDBVersionChangeEvent; +} + +interface IDBDatabase extends EventTarget { + /** + * Returns the name of the database. + */ + readonly name: string; + /** + * Returns a list of the names of object stores in the database. + */ + readonly objectStoreNames: DOMStringList; + onabort: ((this: IDBDatabase, ev: Event) => any) | null; + onclose: ((this: IDBDatabase, ev: Event) => any) | null; + onerror: ((this: IDBDatabase, ev: Event) => any) | null; + onversionchange: ((this: IDBDatabase, ev: IDBVersionChangeEvent) => any) | null; + /** + * Returns the version of the database. + */ + readonly version: number; + /** + * Closes the connection once all running transactions have finished. + */ + close(): void; + /** + * Creates a new object store with the given name and options and returns a new IDBObjectStore. + * Throws a "InvalidStateError" DOMException if not called within an upgrade transaction. + */ + createObjectStore(name: string, optionalParameters?: IDBObjectStoreParameters): IDBObjectStore; + /** + * Deletes the object store with the given name. + * Throws a "InvalidStateError" DOMException if not called within an upgrade transaction. + */ + deleteObjectStore(name: string): void; + /** + * Returns a new transaction with the given mode ("readonly" or "readwrite") + * and scope which can be a single object store name or an array of names. + */ + transaction(storeNames: string | string[], mode?: IDBTransactionMode): IDBTransaction; + addEventListener(type: K, listener: (this: IDBDatabase, ev: IDBDatabaseEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: IDBDatabase, ev: IDBDatabaseEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var IDBDatabase: { + prototype: IDBDatabase; + new(): IDBDatabase; +}; + +interface IDBFactory { + /** + * Compares two values as keys. Returns -1 if key1 precedes key2, 1 if key2 precedes key1, and 0 if + * the keys are equal. + * Throws a "DataError" DOMException if either input is not a valid key. + */ + cmp(first: any, second: any): number; + /** + * Attempts to delete the named database. If the + * database already exists and there are open connections that don't close in response to a versionchange event, the request will be blocked until all they close. If the request + * is successful request's result will be null. + */ + deleteDatabase(name: string): IDBOpenDBRequest; + /** + * Attempts to open a connection to the named database with the specified version. If the database already exists + * with a lower version and there are open connections that don't close in response to a versionchange event, the request will be blocked until all they close, then an upgrade + * will occur. If the database already exists with a higher + * version the request will fail. If the request is + * successful request's result will + * be the connection. + */ + open(name: string, version?: number): IDBOpenDBRequest; +} + +declare var IDBFactory: { + prototype: IDBFactory; + new(): IDBFactory; +}; + +interface IDBIndex { + readonly keyPath: string | string[]; + readonly multiEntry: boolean; + /** + * Updates the name of the store to newName. + * Throws an "InvalidStateError" DOMException if not called within an upgrade + * transaction. + */ + name: string; + /** + * Returns the IDBObjectStore the index belongs to. + */ + readonly objectStore: IDBObjectStore; + readonly unique: boolean; + /** + * Retrieves the number of records matching the given key or key range in query. + * If successful, request's result will be the + * count. + */ + count(key?: IDBValidKey | IDBKeyRange): IDBRequest; + /** + * Retrieves the value of the first record matching the + * given key or key range in query. + * If successful, request's result will be the value, or undefined if there was no matching record. + */ + get(key: IDBValidKey | IDBKeyRange): IDBRequest; + /** + * Retrieves the values of the records matching the given key or key range in query (up to count if given). + * If successful, request's result will be an Array of the values. + */ + getAll(query?: IDBValidKey | IDBKeyRange, count?: number): IDBRequest; + /** + * Retrieves the keys of records matching the given key or key range in query (up to count if given). + * If successful, request's result will be an Array of the keys. + */ + getAllKeys(query?: IDBValidKey | IDBKeyRange, count?: number): IDBRequest; + /** + * Retrieves the key of the first record matching the + * given key or key range in query. + * If successful, request's result will be the key, or undefined if there was no matching record. + */ + getKey(key: IDBValidKey | IDBKeyRange): IDBRequest; + /** + * Opens a cursor over the records matching query, + * ordered by direction. If query is null, all records in index are matched. + * If successful, request's result will be an IDBCursorWithValue, or null if there were no matching records. + */ + openCursor(range?: IDBValidKey | IDBKeyRange, direction?: IDBCursorDirection): IDBRequest; + /** + * Opens a cursor with key only flag set over the records matching query, ordered by direction. If query is null, all records in index are matched. + * If successful, request's result will be an IDBCursor, or null if there were no matching records. + */ + openKeyCursor(range?: IDBValidKey | IDBKeyRange, direction?: IDBCursorDirection): IDBRequest; +} + +declare var IDBIndex: { + prototype: IDBIndex; + new(): IDBIndex; +}; + +interface IDBKeyRange { + /** + * Returns lower bound, or undefined if none. + */ + readonly lower: any; + /** + * Returns true if the lower open flag is set, and false otherwise. + */ + readonly lowerOpen: boolean; + /** + * Returns upper bound, or undefined if none. + */ + readonly upper: any; + /** + * Returns true if the upper open flag is set, and false otherwise. + */ + readonly upperOpen: boolean; + /** + * Returns true if key is included in the range, and false otherwise. + */ + includes(key: any): boolean; +} + +declare var IDBKeyRange: { + prototype: IDBKeyRange; + new(): IDBKeyRange; + /** + * Returns a new IDBKeyRange spanning from lower to upper. + * If lowerOpen is true, lower is not included in the range. + * If upperOpen is true, upper is not included in the range. + */ + bound(lower: any, upper: any, lowerOpen?: boolean, upperOpen?: boolean): IDBKeyRange; + /** + * Returns a new IDBKeyRange starting at key with no + * upper bound. If open is true, key is not included in the + * range. + */ + lowerBound(lower: any, open?: boolean): IDBKeyRange; + /** + * Returns a new IDBKeyRange spanning only key. + */ + only(value: any): IDBKeyRange; + /** + * Returns a new IDBKeyRange with no lower bound and ending at key. If open is true, key is not included in the range. + */ + upperBound(upper: any, open?: boolean): IDBKeyRange; +}; + +interface IDBObjectStore { + /** + * Returns true if the store has a key generator, and false otherwise. + */ + readonly autoIncrement: boolean; + /** + * Returns a list of the names of indexes in the store. + */ + readonly indexNames: DOMStringList; + /** + * Returns the key path of the store, or null if none. + */ + readonly keyPath: string | string[]; + /** + * Updates the name of the store to newName. + * Throws "InvalidStateError" DOMException if not called within an upgrade + * transaction. + */ + name: string; + /** + * Returns the associated transaction. + */ + readonly transaction: IDBTransaction; + add(value: any, key?: IDBValidKey | IDBKeyRange): IDBRequest; + /** + * Deletes all records in store. + * If successful, request's result will + * be undefined. + */ + clear(): IDBRequest; + /** + * Retrieves the number of records matching the + * given key or key range in query. + * If successful, request's result will be the count. + */ + count(key?: IDBValidKey | IDBKeyRange): IDBRequest; + /** + * Creates a new index in store with the given name, keyPath and options and returns a new IDBIndex. If the keyPath and options define constraints that cannot be + * satisfied with the data already in store the upgrade + * transaction will abort with + * a "ConstraintError" DOMException. + * Throws an "InvalidStateError" DOMException if not called within an upgrade + * transaction. + */ + createIndex(name: string, keyPath: string | string[], options?: IDBIndexParameters): IDBIndex; + /** + * Deletes records in store with the given key or in the given key range in query. + * If successful, request's result will + * be undefined. + */ + delete(key: IDBValidKey | IDBKeyRange): IDBRequest; + /** + * Deletes the index in store with the given name. + * Throws an "InvalidStateError" DOMException if not called within an upgrade + * transaction. + */ + deleteIndex(name: string): void; + /** + * Retrieves the value of the first record matching the + * given key or key range in query. + * If successful, request's result will be the value, or undefined if there was no matching record. + */ + get(query: IDBValidKey | IDBKeyRange): IDBRequest; + /** + * Retrieves the values of the records matching the + * given key or key range in query (up to count if given). + * If successful, request's result will + * be an Array of the values. + */ + getAll(query?: IDBValidKey | IDBKeyRange, count?: number): IDBRequest; + /** + * Retrieves the keys of records matching the + * given key or key range in query (up to count if given). + * If successful, request's result will + * be an Array of the keys. + */ + getAllKeys(query?: IDBValidKey | IDBKeyRange, count?: number): IDBRequest; + /** + * Retrieves the key of the first record matching the + * given key or key range in query. + * If successful, request's result will be the key, or undefined if there was no matching record. + */ + getKey(query: IDBValidKey | IDBKeyRange): IDBRequest; + index(name: string): IDBIndex; + /** + * Opens a cursor over the records matching query, + * ordered by direction. If query is null, all records in store are matched. + * If successful, request's result will be an IDBCursorWithValue pointing at the first matching record, or null if there were no matching records. + */ + openCursor(range?: IDBValidKey | IDBKeyRange, direction?: IDBCursorDirection): IDBRequest; + /** + * Opens a cursor with key only flag set over the records matching query, ordered by direction. If query is null, all records in store are matched. + * If successful, request's result will be an IDBCursor pointing at the first matching record, or + * null if there were no matching records. + */ + openKeyCursor(query?: IDBValidKey | IDBKeyRange, direction?: IDBCursorDirection): IDBRequest; + put(value: any, key?: IDBValidKey | IDBKeyRange): IDBRequest; +} + +declare var IDBObjectStore: { + prototype: IDBObjectStore; + new(): IDBObjectStore; +}; + +interface IDBOpenDBRequestEventMap extends IDBRequestEventMap { + "blocked": Event; + "upgradeneeded": IDBVersionChangeEvent; +} + +interface IDBOpenDBRequest extends IDBRequest { + onblocked: ((this: IDBOpenDBRequest, ev: Event) => any) | null; + onupgradeneeded: ((this: IDBOpenDBRequest, ev: IDBVersionChangeEvent) => any) | null; + addEventListener(type: K, listener: (this: IDBOpenDBRequest, ev: IDBOpenDBRequestEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: IDBOpenDBRequest, ev: IDBOpenDBRequestEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var IDBOpenDBRequest: { + prototype: IDBOpenDBRequest; + new(): IDBOpenDBRequest; +}; + +interface IDBRequestEventMap { + "error": Event; + "success": Event; +} + +interface IDBRequest extends EventTarget { + /** + * When a request is completed, returns the error (a DOMException), or null if the request succeeded. Throws + * a "InvalidStateError" DOMException if the request is still pending. + */ + readonly error: DOMException | null; + onerror: ((this: IDBRequest, ev: Event) => any) | null; + onsuccess: ((this: IDBRequest, ev: Event) => any) | null; + /** + * Returns "pending" until a request is complete, + * then returns "done". + */ + readonly readyState: IDBRequestReadyState; + /** + * When a request is completed, returns the result, + * or undefined if the request failed. Throws a + * "InvalidStateError" DOMException if the request is still pending. + */ + readonly result: T; + /** + * Returns the IDBObjectStore, IDBIndex, or IDBCursor the request was made against, or null if is was an open + * request. + */ + readonly source: IDBObjectStore | IDBIndex | IDBCursor; + /** + * Returns the IDBTransaction the request was made within. + * If this as an open request, then it returns an upgrade transaction while it is running, or null otherwise. + */ + readonly transaction: IDBTransaction | null; + addEventListener(type: K, listener: (this: IDBRequest, ev: IDBRequestEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: IDBRequest, ev: IDBRequestEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var IDBRequest: { + prototype: IDBRequest; + new(): IDBRequest; +}; + +interface IDBTransactionEventMap { + "abort": Event; + "complete": Event; + "error": Event; +} + +interface IDBTransaction extends EventTarget { + /** + * Returns the transaction's connection. + */ + readonly db: IDBDatabase; + /** + * If the transaction was aborted, returns the + * error (a DOMException) providing the reason. + */ + readonly error: DOMException; + /** + * Returns the mode the transaction was created with + * ("readonly" or "readwrite"), or "versionchange" for + * an upgrade transaction. + */ + readonly mode: IDBTransactionMode; + /** + * Returns a list of the names of object stores in the + * transaction's scope. For an upgrade transaction this is all object stores in the database. + */ + readonly objectStoreNames: DOMStringList; + onabort: ((this: IDBTransaction, ev: Event) => any) | null; + oncomplete: ((this: IDBTransaction, ev: Event) => any) | null; + onerror: ((this: IDBTransaction, ev: Event) => any) | null; + /** + * Aborts the transaction. All pending requests will fail with + * a "AbortError" DOMException and all changes made to the database will be + * reverted. + */ + abort(): void; + /** + * Returns an IDBObjectStore in the transaction's scope. + */ + objectStore(name: string): IDBObjectStore; + addEventListener(type: K, listener: (this: IDBTransaction, ev: IDBTransactionEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: IDBTransaction, ev: IDBTransactionEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var IDBTransaction: { + prototype: IDBTransaction; + new(): IDBTransaction; +}; + +interface IDBVersionChangeEvent extends Event { + readonly newVersion: number | null; + readonly oldVersion: number; +} + +declare var IDBVersionChangeEvent: { + prototype: IDBVersionChangeEvent; + new(type: string, eventInitDict?: IDBVersionChangeEventInit): IDBVersionChangeEvent; +}; + +interface ImageBitmap { + /** + * Returns the intrinsic height of the image, in CSS + * pixels. + */ + readonly height: number; + /** + * Returns the intrinsic width of the image, in CSS + * pixels. + */ + readonly width: number; + /** + * Releases imageBitmap's underlying bitmap data. + */ + close(): void; +} + +declare var ImageBitmap: { + prototype: ImageBitmap; + new(): ImageBitmap; +}; + +interface ImageBitmapOptions { + colorSpaceConversion?: "none" | "default"; + imageOrientation?: "none" | "flipY"; + premultiplyAlpha?: "none" | "premultiply" | "default"; + resizeHeight?: number; + resizeQuality?: "pixelated" | "low" | "medium" | "high"; + resizeWidth?: number; +} + +interface ImageData { + /** + * Returns the one-dimensional array containing the data in RGBA order, as integers in the + * range 0 to 255. + */ + readonly data: Uint8ClampedArray; + /** + * Returns the actual dimensions of the data in the ImageData object, in + * pixels. + */ + readonly height: number; + readonly width: number; +} + +declare var ImageData: { + prototype: ImageData; + new(width: number, height: number): ImageData; + new(array: Uint8ClampedArray, width: number, height: number): ImageData; +}; + +interface MessageChannel { + readonly port1: MessagePort; + readonly port2: MessagePort; +} + +declare var MessageChannel: { + prototype: MessageChannel; + new(): MessageChannel; +}; + +interface MessageEvent extends Event { + /** + * Returns the data of the message. + */ + readonly data: any; + /** + * Returns the last event ID string, for + * server-sent events. + */ + readonly lastEventId: string; + /** + * Returns the origin of the message, for server-sent events and + * cross-document messaging. + */ + readonly origin: string; + /** + * Returns the MessagePort array sent with the message, for cross-document + * messaging and channel messaging. + */ + readonly ports: ReadonlyArray; + /** + * Returns the WindowProxy of the source window, for cross-document + * messaging, and the MessagePort being attached, in the connect event fired at + * SharedWorkerGlobalScope objects. + */ + readonly source: MessageEventSource | null; +} + +declare var MessageEvent: { + prototype: MessageEvent; + new(type: string, eventInitDict?: MessageEventInit): MessageEvent; +}; + +interface MessagePortEventMap { + "message": MessageEvent; + "messageerror": MessageEvent; +} + +interface MessagePort extends EventTarget { + onmessage: ((this: MessagePort, ev: MessageEvent) => any) | null; + onmessageerror: ((this: MessagePort, ev: MessageEvent) => any) | null; + /** + * Disconnects the port, so that it is no longer active. + */ + close(): void; + /** + * Posts a message through the channel. Objects listed in transfer are + * transferred, not just cloned, meaning that they are no longer usable on the sending side. + * Throws a "DataCloneError" DOMException if + * transfer contains duplicate objects or port, or if message + * could not be cloned. + */ + postMessage(message: any, transfer?: Transferable[]): void; + /** + * Begins dispatching messages received on the port. + */ + start(): void; + addEventListener(type: K, listener: (this: MessagePort, ev: MessagePortEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: MessagePort, ev: MessagePortEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var MessagePort: { + prototype: MessagePort; + new(): MessagePort; +}; + +interface NavigationPreloadManager { + disable(): Promise; + enable(): Promise; + getState(): Promise; + setHeaderValue(value: string): Promise; +} + +declare var NavigationPreloadManager: { + prototype: NavigationPreloadManager; + new(): NavigationPreloadManager; +}; + +interface NavigatorBeacon { + sendBeacon(url: string, data?: Blob | Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | FormData | string | null): boolean; +} + +interface NavigatorConcurrentHardware { + readonly hardwareConcurrency: number; +} + +interface NavigatorID { + readonly appCodeName: string; + readonly appName: string; + readonly appVersion: string; + readonly platform: string; + readonly product: string; + readonly productSub: string; + readonly userAgent: string; + readonly vendor: string; + readonly vendorSub: string; +} + +interface NavigatorOnLine { + readonly onLine: boolean; +} + +interface NavigatorStorage { + readonly storage: StorageManager; +} + +interface NotificationEventMap { + "click": Event; + "close": Event; + "error": Event; + "show": Event; +} + +interface Notification extends EventTarget { + readonly actions: ReadonlyArray; + readonly badge: string; + readonly body: string; + readonly data: any; + readonly dir: NotificationDirection; + readonly icon: string; + readonly image: string; + readonly lang: string; + onclick: ((this: Notification, ev: Event) => any) | null; + onclose: ((this: Notification, ev: Event) => any) | null; + onerror: ((this: Notification, ev: Event) => any) | null; + onshow: ((this: Notification, ev: Event) => any) | null; + readonly renotify: boolean; + readonly requireInteraction: boolean; + readonly silent: boolean; + readonly tag: string; + readonly timestamp: number; + readonly title: string; + readonly vibrate: ReadonlyArray; + close(): void; + addEventListener(type: K, listener: (this: Notification, ev: NotificationEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: Notification, ev: NotificationEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var Notification: { + prototype: Notification; + new(title: string, options?: NotificationOptions): Notification; + readonly maxActions: number; + readonly permission: NotificationPermission; +}; + +interface NotificationEvent extends ExtendableEvent { + readonly action: string; + readonly notification: Notification; +} + +declare var NotificationEvent: { + prototype: NotificationEvent; + new(type: string, eventInitDict: NotificationEventInit): NotificationEvent; +}; + +interface OES_element_index_uint { +} + +interface OES_standard_derivatives { + readonly FRAGMENT_SHADER_DERIVATIVE_HINT_OES: GLenum; +} + +interface OES_texture_float { +} + +interface OES_texture_float_linear { +} + +interface OES_texture_half_float { + readonly HALF_FLOAT_OES: GLenum; +} + +interface OES_texture_half_float_linear { +} + +interface OES_vertex_array_object { + bindVertexArrayOES(arrayObject: WebGLVertexArrayObjectOES | null): void; + createVertexArrayOES(): WebGLVertexArrayObjectOES | null; + deleteVertexArrayOES(arrayObject: WebGLVertexArrayObjectOES | null): void; + isVertexArrayOES(arrayObject: WebGLVertexArrayObjectOES | null): GLboolean; + readonly VERTEX_ARRAY_BINDING_OES: GLenum; +} + +interface Path2D extends CanvasPath { + addPath(path: Path2D, transform?: DOMMatrix2DInit): void; +} + +declare var Path2D: { + prototype: Path2D; + new(path?: Path2D | string): Path2D; +}; + +interface PerformanceEventMap { + "resourcetimingbufferfull": Event; +} + +interface Performance extends EventTarget { + onresourcetimingbufferfull: ((this: Performance, ev: Event) => any) | null; + readonly timeOrigin: number; + clearMarks(markName?: string): void; + clearMeasures(measureName?: string): void; + clearResourceTimings(): void; + getEntries(): PerformanceEntryList; + getEntriesByName(name: string, type?: string): PerformanceEntryList; + getEntriesByType(type: string): PerformanceEntryList; + mark(markName: string): void; + measure(measureName: string, startMark?: string, endMark?: string): void; + now(): number; + setResourceTimingBufferSize(maxSize: number): void; + toJSON(): any; + addEventListener(type: K, listener: (this: Performance, ev: PerformanceEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: Performance, ev: PerformanceEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var Performance: { + prototype: Performance; + new(): Performance; +}; + +interface PerformanceEntry { + readonly duration: number; + readonly entryType: string; + readonly name: string; + readonly startTime: number; + toJSON(): any; +} + +declare var PerformanceEntry: { + prototype: PerformanceEntry; + new(): PerformanceEntry; +}; + +interface PerformanceMark extends PerformanceEntry { +} + +declare var PerformanceMark: { + prototype: PerformanceMark; + new(): PerformanceMark; +}; + +interface PerformanceMeasure extends PerformanceEntry { +} + +declare var PerformanceMeasure: { + prototype: PerformanceMeasure; + new(): PerformanceMeasure; +}; + +interface PerformanceObserver { + disconnect(): void; + observe(options: PerformanceObserverInit): void; + takeRecords(): PerformanceEntryList; +} + +declare var PerformanceObserver: { + prototype: PerformanceObserver; + new(callback: PerformanceObserverCallback): PerformanceObserver; +}; + +interface PerformanceObserverEntryList { + getEntries(): PerformanceEntryList; + getEntriesByName(name: string, type?: string): PerformanceEntryList; + getEntriesByType(type: string): PerformanceEntryList; +} + +declare var PerformanceObserverEntryList: { + prototype: PerformanceObserverEntryList; + new(): PerformanceObserverEntryList; +}; + +interface PerformanceResourceTiming extends PerformanceEntry { + readonly connectEnd: number; + readonly connectStart: number; + readonly decodedBodySize: number; + readonly domainLookupEnd: number; + readonly domainLookupStart: number; + readonly encodedBodySize: number; + readonly fetchStart: number; + readonly initiatorType: string; + readonly nextHopProtocol: string; + readonly redirectEnd: number; + readonly redirectStart: number; + readonly requestStart: number; + readonly responseEnd: number; + readonly responseStart: number; + readonly secureConnectionStart: number; + readonly transferSize: number; + readonly workerStart: number; + toJSON(): any; +} + +declare var PerformanceResourceTiming: { + prototype: PerformanceResourceTiming; + new(): PerformanceResourceTiming; +}; + +interface ProgressEvent extends Event { + readonly lengthComputable: boolean; + readonly loaded: number; + readonly total: number; +} + +declare var ProgressEvent: { + prototype: ProgressEvent; + new(type: string, eventInitDict?: ProgressEventInit): ProgressEvent; +}; + +interface PromiseRejectionEvent extends Event { + readonly promise: Promise; + readonly reason: any; +} + +declare var PromiseRejectionEvent: { + prototype: PromiseRejectionEvent; + new(type: string, eventInitDict: PromiseRejectionEventInit): PromiseRejectionEvent; +}; + +interface PushEvent extends ExtendableEvent { + readonly data: PushMessageData | null; +} + +declare var PushEvent: { + prototype: PushEvent; + new(type: string, eventInitDict?: PushEventInit): PushEvent; +}; + +interface PushManager { + getSubscription(): Promise; + permissionState(options?: PushSubscriptionOptionsInit): Promise; + subscribe(options?: PushSubscriptionOptionsInit): Promise; +} + +declare var PushManager: { + prototype: PushManager; + new(): PushManager; + readonly supportedContentEncodings: ReadonlyArray; +}; + +interface PushMessageData { + arrayBuffer(): ArrayBuffer; + blob(): Blob; + json(): any; + text(): string; +} + +declare var PushMessageData: { + prototype: PushMessageData; + new(): PushMessageData; +}; + +interface PushSubscription { + readonly endpoint: string; + readonly expirationTime: number | null; + readonly options: PushSubscriptionOptions; + getKey(name: PushEncryptionKeyName): ArrayBuffer | null; + toJSON(): PushSubscriptionJSON; + unsubscribe(): Promise; +} + +declare var PushSubscription: { + prototype: PushSubscription; + new(): PushSubscription; +}; + +interface PushSubscriptionChangeEvent extends ExtendableEvent { + readonly newSubscription: PushSubscription | null; + readonly oldSubscription: PushSubscription | null; +} + +declare var PushSubscriptionChangeEvent: { + prototype: PushSubscriptionChangeEvent; + new(type: string, eventInitDict?: PushSubscriptionChangeInit): PushSubscriptionChangeEvent; +}; + +interface PushSubscriptionOptions { + readonly applicationServerKey: ArrayBuffer | null; + readonly userVisibleOnly: boolean; +} + +declare var PushSubscriptionOptions: { + prototype: PushSubscriptionOptions; + new(): PushSubscriptionOptions; +}; + +interface ReadableByteStreamController { + readonly byobRequest: ReadableStreamBYOBRequest | undefined; + readonly desiredSize: number | null; + close(): void; + enqueue(chunk: ArrayBufferView): void; + error(error?: any): void; +} + +interface ReadableStream { + readonly locked: boolean; + cancel(reason?: any): Promise; + getReader(options: { mode: "byob" }): ReadableStreamBYOBReader; + getReader(): ReadableStreamDefaultReader; + pipeThrough({ writable, readable }: { writable: WritableStream, readable: ReadableStream }, options?: PipeOptions): ReadableStream; + pipeTo(dest: WritableStream, options?: PipeOptions): Promise; + tee(): [ReadableStream, ReadableStream]; +} + +declare var ReadableStream: { + prototype: ReadableStream; + new(underlyingSource: UnderlyingByteSource, strategy?: { highWaterMark?: number, size?: undefined }): ReadableStream; + new(underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy): ReadableStream; +}; + +interface ReadableStreamBYOBReader { + readonly closed: Promise; + cancel(reason?: any): Promise; + read(view: T): Promise>; + releaseLock(): void; +} + +declare var ReadableStreamBYOBReader: { + prototype: ReadableStreamBYOBReader; + new(stream: ReadableStream): ReadableStreamBYOBReader; +}; + +interface ReadableStreamBYOBRequest { + readonly view: ArrayBufferView; + respond(bytesWritten: number): void; + respondWithNewView(view: ArrayBufferView): void; +} + +interface ReadableStreamDefaultController { + readonly desiredSize: number | null; + close(): void; + enqueue(chunk: R): void; + error(error?: any): void; +} + +interface ReadableStreamDefaultReader { + readonly closed: Promise; + cancel(reason?: any): Promise; + read(): Promise>; + releaseLock(): void; +} + +interface ReadableStreamReadResult { + done: boolean; + value: T; +} + +interface ReadableStreamReader { + cancel(): Promise; + read(): Promise>; + releaseLock(): void; +} + +declare var ReadableStreamReader: { + prototype: ReadableStreamReader; + new(): ReadableStreamReader; +}; + +interface Request extends Body { + /** + * Returns the cache mode associated with request, which is a string indicating + * how the request will interact with the browser's cache when fetching. + */ + readonly cache: RequestCache; + /** + * Returns the credentials mode associated with request, which is a string + * indicating whether credentials will be sent with the request always, never, or only when sent to a + * same-origin URL. + */ + readonly credentials: RequestCredentials; + /** + * Returns the kind of resource requested by request, e.g., "document" or + * "script". + */ + readonly destination: RequestDestination; + /** + * Returns a Headers object consisting of the headers associated with request. + * Note that headers added in the network layer by the user agent will not be accounted for in this + * object, e.g., the "Host" header. + */ + readonly headers: Headers; + /** + * Returns request's subresource integrity metadata, which is a cryptographic hash of + * the resource being fetched. Its value consists of multiple hashes separated by whitespace. [SRI] + */ + readonly integrity: string; + /** + * Returns a boolean indicating whether or not request is for a history + * navigation (a.k.a. back-foward navigation). + */ + readonly isHistoryNavigation: boolean; + /** + * Returns a boolean indicating whether or not request is for a reload navigation. + */ + readonly isReloadNavigation: boolean; + /** + * Returns a boolean indicating whether or not request can outlive the global in which + * it was created. + */ + readonly keepalive: boolean; + /** + * Returns request's HTTP method, which is "GET" by default. + */ + readonly method: string; + /** + * Returns the mode associated with request, which is a string indicating + * whether the request will use CORS, or will be restricted to same-origin URLs. + */ + readonly mode: RequestMode; + /** + * Returns the redirect mode associated with request, which is a string + * indicating how redirects for the request will be handled during fetching. A request will follow redirects by default. + */ + readonly redirect: RequestRedirect; + /** + * Returns the referrer of request. Its value can be a same-origin URL if + * explicitly set in init, the empty string to indicate no referrer, and + * "about:client" when defaulting to the global's default. This is used during + * fetching to determine the value of the `Referer` header of the request being made. + */ + readonly referrer: string; + /** + * Returns the referrer policy associated with request. This is used during + * fetching to compute the value of the request's referrer. + */ + readonly referrerPolicy: ReferrerPolicy; + /** + * Returns the signal associated with request, which is an AbortSignal object indicating whether or not request has been aborted, and its abort + * event handler. + */ + readonly signal: AbortSignal; + /** + * Returns the URL of request as a string. + */ + readonly url: string; + clone(): Request; +} + +declare var Request: { + prototype: Request; + new(input: RequestInfo, init?: RequestInit): Request; +}; + +interface Response extends Body { + readonly headers: Headers; + readonly ok: boolean; + readonly redirected: boolean; + readonly status: number; + readonly statusText: string; + readonly trailer: Promise; + readonly type: ResponseType; + readonly url: string; + clone(): Response; +} + +declare var Response: { + prototype: Response; + new(body?: BodyInit | null, init?: ResponseInit): Response; + error(): Response; + redirect(url: string, status?: number): Response; +}; + +interface ServiceWorkerEventMap extends AbstractWorkerEventMap { + "statechange": Event; +} + +interface ServiceWorker extends EventTarget, AbstractWorker { + onstatechange: ((this: ServiceWorker, ev: Event) => any) | null; + readonly scriptURL: string; + readonly state: ServiceWorkerState; + postMessage(message: any, transfer?: Transferable[]): void; + addEventListener(type: K, listener: (this: ServiceWorker, ev: ServiceWorkerEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: ServiceWorker, ev: ServiceWorkerEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var ServiceWorker: { + prototype: ServiceWorker; + new(): ServiceWorker; +}; + +interface ServiceWorkerContainerEventMap { + "controllerchange": Event; + "message": MessageEvent; + "messageerror": MessageEvent; +} + +interface ServiceWorkerContainer extends EventTarget { + readonly controller: ServiceWorker | null; + oncontrollerchange: ((this: ServiceWorkerContainer, ev: Event) => any) | null; + onmessage: ((this: ServiceWorkerContainer, ev: MessageEvent) => any) | null; + onmessageerror: ((this: ServiceWorkerContainer, ev: MessageEvent) => any) | null; + readonly ready: Promise; + getRegistration(clientURL?: string): Promise; + getRegistrations(): Promise>; + register(scriptURL: string, options?: RegistrationOptions): Promise; + startMessages(): void; + addEventListener(type: K, listener: (this: ServiceWorkerContainer, ev: ServiceWorkerContainerEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: ServiceWorkerContainer, ev: ServiceWorkerContainerEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var ServiceWorkerContainer: { + prototype: ServiceWorkerContainer; + new(): ServiceWorkerContainer; +}; + +interface ServiceWorkerGlobalScopeEventMap extends WorkerGlobalScopeEventMap { + "activate": ExtendableEvent; + "fetch": FetchEvent; + "install": ExtendableEvent; + "message": ExtendableMessageEvent; + "messageerror": MessageEvent; + "notificationclick": NotificationEvent; + "notificationclose": NotificationEvent; + "push": PushEvent; + "pushsubscriptionchange": PushSubscriptionChangeEvent; + "sync": SyncEvent; +} + +interface ServiceWorkerGlobalScope extends WorkerGlobalScope { + readonly clients: Clients; + onactivate: ((this: ServiceWorkerGlobalScope, ev: ExtendableEvent) => any) | null; + onfetch: ((this: ServiceWorkerGlobalScope, ev: FetchEvent) => any) | null; + oninstall: ((this: ServiceWorkerGlobalScope, ev: ExtendableEvent) => any) | null; + onmessage: ((this: ServiceWorkerGlobalScope, ev: ExtendableMessageEvent) => any) | null; + onmessageerror: ((this: ServiceWorkerGlobalScope, ev: MessageEvent) => any) | null; + onnotificationclick: ((this: ServiceWorkerGlobalScope, ev: NotificationEvent) => any) | null; + onnotificationclose: ((this: ServiceWorkerGlobalScope, ev: NotificationEvent) => any) | null; + onpush: ((this: ServiceWorkerGlobalScope, ev: PushEvent) => any) | null; + onpushsubscriptionchange: ((this: ServiceWorkerGlobalScope, ev: PushSubscriptionChangeEvent) => any) | null; + onsync: ((this: ServiceWorkerGlobalScope, ev: SyncEvent) => any) | null; + readonly registration: ServiceWorkerRegistration; + skipWaiting(): Promise; + addEventListener(type: K, listener: (this: ServiceWorkerGlobalScope, ev: ServiceWorkerGlobalScopeEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: ServiceWorkerGlobalScope, ev: ServiceWorkerGlobalScopeEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var ServiceWorkerGlobalScope: { + prototype: ServiceWorkerGlobalScope; + new(): ServiceWorkerGlobalScope; +}; + +interface ServiceWorkerRegistrationEventMap { + "updatefound": Event; +} + +interface ServiceWorkerRegistration extends EventTarget { + readonly active: ServiceWorker | null; + readonly installing: ServiceWorker | null; + readonly navigationPreload: NavigationPreloadManager; + onupdatefound: ((this: ServiceWorkerRegistration, ev: Event) => any) | null; + readonly pushManager: PushManager; + readonly scope: string; + readonly sync: SyncManager; + readonly updateViaCache: ServiceWorkerUpdateViaCache; + readonly waiting: ServiceWorker | null; + getNotifications(filter?: GetNotificationOptions): Promise; + showNotification(title: string, options?: NotificationOptions): Promise; + unregister(): Promise; + update(): Promise; + addEventListener(type: K, listener: (this: ServiceWorkerRegistration, ev: ServiceWorkerRegistrationEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: ServiceWorkerRegistration, ev: ServiceWorkerRegistrationEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var ServiceWorkerRegistration: { + prototype: ServiceWorkerRegistration; + new(): ServiceWorkerRegistration; +}; + +interface StorageManager { + estimate(): Promise; + persisted(): Promise; +} + +declare var StorageManager: { + prototype: StorageManager; + new(): StorageManager; +}; + +interface SubtleCrypto { + decrypt(algorithm: string | RsaOaepParams | AesCtrParams | AesCbcParams | AesCmacParams | AesGcmParams | AesCfbParams, key: CryptoKey, data: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer): PromiseLike; + deriveBits(algorithm: string | EcdhKeyDeriveParams | DhKeyDeriveParams | ConcatParams | HkdfCtrParams | Pbkdf2Params, baseKey: CryptoKey, length: number): PromiseLike; + deriveKey(algorithm: string | EcdhKeyDeriveParams | DhKeyDeriveParams | ConcatParams | HkdfCtrParams | Pbkdf2Params, baseKey: CryptoKey, derivedKeyType: string | AesDerivedKeyParams | HmacImportParams | ConcatParams | HkdfCtrParams | Pbkdf2Params, extractable: boolean, keyUsages: string[]): PromiseLike; + digest(algorithm: string | Algorithm, data: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer): PromiseLike; + encrypt(algorithm: string | RsaOaepParams | AesCtrParams | AesCbcParams | AesCmacParams | AesGcmParams | AesCfbParams, key: CryptoKey, data: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer): PromiseLike; + exportKey(format: "jwk", key: CryptoKey): PromiseLike; + exportKey(format: "raw" | "pkcs8" | "spki", key: CryptoKey): PromiseLike; + exportKey(format: string, key: CryptoKey): PromiseLike; + generateKey(algorithm: string, extractable: boolean, keyUsages: string[]): PromiseLike; + generateKey(algorithm: RsaHashedKeyGenParams | EcKeyGenParams | DhKeyGenParams, extractable: boolean, keyUsages: string[]): PromiseLike; + generateKey(algorithm: AesKeyGenParams | HmacKeyGenParams | Pbkdf2Params, extractable: boolean, keyUsages: string[]): PromiseLike; + importKey(format: "jwk", keyData: JsonWebKey, algorithm: string | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | DhImportKeyParams | AesKeyAlgorithm, extractable: boolean, keyUsages: string[]): PromiseLike; + importKey(format: "raw" | "pkcs8" | "spki", keyData: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer, algorithm: string | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | DhImportKeyParams | AesKeyAlgorithm, extractable: boolean, keyUsages: string[]): PromiseLike; + importKey(format: string, keyData: JsonWebKey | Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer, algorithm: string | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | DhImportKeyParams | AesKeyAlgorithm, extractable: boolean, keyUsages: string[]): PromiseLike; + sign(algorithm: string | RsaPssParams | EcdsaParams | AesCmacParams, key: CryptoKey, data: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer): PromiseLike; + unwrapKey(format: string, wrappedKey: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer, unwrappingKey: CryptoKey, unwrapAlgorithm: string | Algorithm, unwrappedKeyAlgorithm: string | Algorithm, extractable: boolean, keyUsages: string[]): PromiseLike; + verify(algorithm: string | RsaPssParams | EcdsaParams | AesCmacParams, key: CryptoKey, signature: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer, data: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer): PromiseLike; + wrapKey(format: string, key: CryptoKey, wrappingKey: CryptoKey, wrapAlgorithm: string | Algorithm): PromiseLike; +} + +declare var SubtleCrypto: { + prototype: SubtleCrypto; + new(): SubtleCrypto; +}; + +interface SyncEvent extends ExtendableEvent { + readonly lastChance: boolean; + readonly tag: string; +} + +declare var SyncEvent: { + prototype: SyncEvent; + new(type: string, init: SyncEventInit): SyncEvent; +}; + +interface SyncManager { + getTags(): Promise; + register(tag: string): Promise; +} + +declare var SyncManager: { + prototype: SyncManager; + new(): SyncManager; +}; + +interface TextDecoder { + /** + * Returns encoding's name, lowercased. + */ + readonly encoding: string; + /** + * Returns true if error mode is "fatal", and false + * otherwise. + */ + readonly fatal: boolean; + /** + * Returns true if ignore BOM flag is set, and false otherwise. + */ + readonly ignoreBOM: boolean; + /** + * Returns the result of running encoding's decoder. The + * method can be invoked zero or more times with options's stream set to + * true, and then once without options's stream (or set to false), to process + * a fragmented stream. If the invocation without options's stream (or set to + * false) has no input, it's clearest to omit both arguments. + * var string = "", decoder = new TextDecoder(encoding), buffer; + * while(buffer = next_chunk()) { + * string += decoder.decode(buffer, {stream:true}); + * } + * string += decoder.decode(); // end-of-stream + * If the error mode is "fatal" and encoding's decoder returns error, throws a TypeError. + */ + decode(input?: BufferSource, options?: TextDecodeOptions): string; +} + +declare var TextDecoder: { + prototype: TextDecoder; + new(label?: string, options?: TextDecoderOptions): TextDecoder; +}; + +interface TextEncoder { + /** + * Returns "utf-8". + */ + readonly encoding: string; + /** + * Returns the result of running UTF-8's encoder. + */ + encode(input?: string): Uint8Array; +} + +declare var TextEncoder: { + prototype: TextEncoder; + new(): TextEncoder; +}; + +interface TextMetrics { + readonly actualBoundingBoxAscent: number; + readonly actualBoundingBoxDescent: number; + readonly actualBoundingBoxLeft: number; + readonly actualBoundingBoxRight: number; + readonly alphabeticBaseline: number; + readonly emHeightAscent: number; + readonly emHeightDescent: number; + readonly fontBoundingBoxAscent: number; + readonly fontBoundingBoxDescent: number; + readonly hangingBaseline: number; + /** + * Returns the measurement described below. + */ + readonly ideographicBaseline: number; + readonly width: number; +} + +declare var TextMetrics: { + prototype: TextMetrics; + new(): TextMetrics; +}; + +interface TransformStream { + readonly readable: ReadableStream; + readonly writable: WritableStream; +} + +declare var TransformStream: { + prototype: TransformStream; + new(transformer?: Transformer, writableStrategy?: QueuingStrategy, readableStrategy?: QueuingStrategy): TransformStream; +}; + +interface TransformStreamDefaultController { + readonly desiredSize: number | null; + enqueue(chunk: O): void; + error(reason?: any): void; + terminate(): void; +} + +interface URL { + hash: string; + host: string; + hostname: string; + href: string; + readonly origin: string; + password: string; + pathname: string; + port: string; + protocol: string; + search: string; + readonly searchParams: URLSearchParams; + username: string; + toJSON(): string; +} + +declare var URL: { + prototype: URL; + new(url: string, base?: string | URL): URL; + createObjectURL(object: any): string; + revokeObjectURL(url: string): void; +}; + +interface URLSearchParams { + /** + * Appends a specified key/value pair as a new search parameter. + */ + append(name: string, value: string): void; + /** + * Deletes the given search parameter, and its associated value, from the list of all search parameters. + */ + delete(name: string): void; + /** + * Returns the first value associated to the given search parameter. + */ + get(name: string): string | null; + /** + * Returns all the values association with a given search parameter. + */ + getAll(name: string): string[]; + /** + * Returns a Boolean indicating if such a search parameter exists. + */ + has(name: string): boolean; + /** + * Sets the value associated to a given search parameter to the given value. If there were several values, delete the others. + */ + set(name: string, value: string): void; + sort(): void; + forEach(callbackfn: (value: string, key: string, parent: URLSearchParams) => void, thisArg?: any): void; +} + +declare var URLSearchParams: { + prototype: URLSearchParams; + new(init?: string[][] | Record | string | URLSearchParams): URLSearchParams; +}; + +interface WEBGL_color_buffer_float { + readonly FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE_EXT: GLenum; + readonly RGBA32F_EXT: GLenum; + readonly UNSIGNED_NORMALIZED_EXT: GLenum; +} + +interface WEBGL_compressed_texture_astc { + getSupportedProfiles(): string[]; + readonly COMPRESSED_RGBA_ASTC_10x10_KHR: GLenum; + readonly COMPRESSED_RGBA_ASTC_10x5_KHR: GLenum; + readonly COMPRESSED_RGBA_ASTC_10x6_KHR: GLenum; + readonly COMPRESSED_RGBA_ASTC_10x8_KHR: GLenum; + readonly COMPRESSED_RGBA_ASTC_12x10_KHR: GLenum; + readonly COMPRESSED_RGBA_ASTC_12x12_KHR: GLenum; + readonly COMPRESSED_RGBA_ASTC_4x4_KHR: GLenum; + readonly COMPRESSED_RGBA_ASTC_5x4_KHR: GLenum; + readonly COMPRESSED_RGBA_ASTC_5x5_KHR: GLenum; + readonly COMPRESSED_RGBA_ASTC_6x5_KHR: GLenum; + readonly COMPRESSED_RGBA_ASTC_6x6_KHR: GLenum; + readonly COMPRESSED_RGBA_ASTC_8x5_KHR: GLenum; + readonly COMPRESSED_RGBA_ASTC_8x6_KHR: GLenum; + readonly COMPRESSED_RGBA_ASTC_8x8_KHR: GLenum; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR: GLenum; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR: GLenum; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR: GLenum; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR: GLenum; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR: GLenum; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR: GLenum; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR: GLenum; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR: GLenum; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR: GLenum; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR: GLenum; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR: GLenum; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR: GLenum; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR: GLenum; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR: GLenum; +} + +interface WEBGL_compressed_texture_s3tc { + readonly COMPRESSED_RGBA_S3TC_DXT1_EXT: GLenum; + readonly COMPRESSED_RGBA_S3TC_DXT3_EXT: GLenum; + readonly COMPRESSED_RGBA_S3TC_DXT5_EXT: GLenum; + readonly COMPRESSED_RGB_S3TC_DXT1_EXT: GLenum; +} + +interface WEBGL_compressed_texture_s3tc_srgb { + readonly COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT: GLenum; + readonly COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT: GLenum; + readonly COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT: GLenum; + readonly COMPRESSED_SRGB_S3TC_DXT1_EXT: GLenum; +} + +interface WEBGL_debug_renderer_info { + readonly UNMASKED_RENDERER_WEBGL: GLenum; + readonly UNMASKED_VENDOR_WEBGL: GLenum; +} + +interface WEBGL_debug_shaders { + getTranslatedShaderSource(shader: WebGLShader): string; +} + +interface WEBGL_depth_texture { + readonly UNSIGNED_INT_24_8_WEBGL: GLenum; +} + +interface WEBGL_draw_buffers { + drawBuffersWEBGL(buffers: GLenum[]): void; + readonly COLOR_ATTACHMENT0_WEBGL: GLenum; + readonly COLOR_ATTACHMENT10_WEBGL: GLenum; + readonly COLOR_ATTACHMENT11_WEBGL: GLenum; + readonly COLOR_ATTACHMENT12_WEBGL: GLenum; + readonly COLOR_ATTACHMENT13_WEBGL: GLenum; + readonly COLOR_ATTACHMENT14_WEBGL: GLenum; + readonly COLOR_ATTACHMENT15_WEBGL: GLenum; + readonly COLOR_ATTACHMENT1_WEBGL: GLenum; + readonly COLOR_ATTACHMENT2_WEBGL: GLenum; + readonly COLOR_ATTACHMENT3_WEBGL: GLenum; + readonly COLOR_ATTACHMENT4_WEBGL: GLenum; + readonly COLOR_ATTACHMENT5_WEBGL: GLenum; + readonly COLOR_ATTACHMENT6_WEBGL: GLenum; + readonly COLOR_ATTACHMENT7_WEBGL: GLenum; + readonly COLOR_ATTACHMENT8_WEBGL: GLenum; + readonly COLOR_ATTACHMENT9_WEBGL: GLenum; + readonly DRAW_BUFFER0_WEBGL: GLenum; + readonly DRAW_BUFFER10_WEBGL: GLenum; + readonly DRAW_BUFFER11_WEBGL: GLenum; + readonly DRAW_BUFFER12_WEBGL: GLenum; + readonly DRAW_BUFFER13_WEBGL: GLenum; + readonly DRAW_BUFFER14_WEBGL: GLenum; + readonly DRAW_BUFFER15_WEBGL: GLenum; + readonly DRAW_BUFFER1_WEBGL: GLenum; + readonly DRAW_BUFFER2_WEBGL: GLenum; + readonly DRAW_BUFFER3_WEBGL: GLenum; + readonly DRAW_BUFFER4_WEBGL: GLenum; + readonly DRAW_BUFFER5_WEBGL: GLenum; + readonly DRAW_BUFFER6_WEBGL: GLenum; + readonly DRAW_BUFFER7_WEBGL: GLenum; + readonly DRAW_BUFFER8_WEBGL: GLenum; + readonly DRAW_BUFFER9_WEBGL: GLenum; + readonly MAX_COLOR_ATTACHMENTS_WEBGL: GLenum; + readonly MAX_DRAW_BUFFERS_WEBGL: GLenum; +} + +interface WEBGL_lose_context { + loseContext(): void; + restoreContext(): void; +} + +interface WebGLActiveInfo { + readonly name: string; + readonly size: GLint; + readonly type: GLenum; +} + +declare var WebGLActiveInfo: { + prototype: WebGLActiveInfo; + new(): WebGLActiveInfo; +}; + +interface WebGLBuffer extends WebGLObject { +} + +declare var WebGLBuffer: { + prototype: WebGLBuffer; + new(): WebGLBuffer; +}; + +interface WebGLContextEvent extends Event { + readonly statusMessage: string; +} + +declare var WebGLContextEvent: { + prototype: WebGLContextEvent; + new(type: string, eventInit?: WebGLContextEventInit): WebGLContextEvent; +}; + +interface WebGLFramebuffer extends WebGLObject { +} + +declare var WebGLFramebuffer: { + prototype: WebGLFramebuffer; + new(): WebGLFramebuffer; +}; + +interface WebGLObject { +} + +declare var WebGLObject: { + prototype: WebGLObject; + new(): WebGLObject; +}; + +interface WebGLProgram extends WebGLObject { +} + +declare var WebGLProgram: { + prototype: WebGLProgram; + new(): WebGLProgram; +}; + +interface WebGLRenderbuffer extends WebGLObject { +} + +declare var WebGLRenderbuffer: { + prototype: WebGLRenderbuffer; + new(): WebGLRenderbuffer; +}; + +interface WebGLRenderingContext extends WebGLRenderingContextBase { +} + +declare var WebGLRenderingContext: { + prototype: WebGLRenderingContext; + new(): WebGLRenderingContext; + readonly ACTIVE_ATTRIBUTES: GLenum; + readonly ACTIVE_TEXTURE: GLenum; + readonly ACTIVE_UNIFORMS: GLenum; + readonly ALIASED_LINE_WIDTH_RANGE: GLenum; + readonly ALIASED_POINT_SIZE_RANGE: GLenum; + readonly ALPHA: GLenum; + readonly ALPHA_BITS: GLenum; + readonly ALWAYS: GLenum; + readonly ARRAY_BUFFER: GLenum; + readonly ARRAY_BUFFER_BINDING: GLenum; + readonly ATTACHED_SHADERS: GLenum; + readonly BACK: GLenum; + readonly BLEND: GLenum; + readonly BLEND_COLOR: GLenum; + readonly BLEND_DST_ALPHA: GLenum; + readonly BLEND_DST_RGB: GLenum; + readonly BLEND_EQUATION: GLenum; + readonly BLEND_EQUATION_ALPHA: GLenum; + readonly BLEND_EQUATION_RGB: GLenum; + readonly BLEND_SRC_ALPHA: GLenum; + readonly BLEND_SRC_RGB: GLenum; + readonly BLUE_BITS: GLenum; + readonly BOOL: GLenum; + readonly BOOL_VEC2: GLenum; + readonly BOOL_VEC3: GLenum; + readonly BOOL_VEC4: GLenum; + readonly BROWSER_DEFAULT_WEBGL: GLenum; + readonly BUFFER_SIZE: GLenum; + readonly BUFFER_USAGE: GLenum; + readonly BYTE: GLenum; + readonly CCW: GLenum; + readonly CLAMP_TO_EDGE: GLenum; + readonly COLOR_ATTACHMENT0: GLenum; + readonly COLOR_BUFFER_BIT: GLenum; + readonly COLOR_CLEAR_VALUE: GLenum; + readonly COLOR_WRITEMASK: GLenum; + readonly COMPILE_STATUS: GLenum; + readonly COMPRESSED_TEXTURE_FORMATS: GLenum; + readonly CONSTANT_ALPHA: GLenum; + readonly CONSTANT_COLOR: GLenum; + readonly CONTEXT_LOST_WEBGL: GLenum; + readonly CULL_FACE: GLenum; + readonly CULL_FACE_MODE: GLenum; + readonly CURRENT_PROGRAM: GLenum; + readonly CURRENT_VERTEX_ATTRIB: GLenum; + readonly CW: GLenum; + readonly DECR: GLenum; + readonly DECR_WRAP: GLenum; + readonly DELETE_STATUS: GLenum; + readonly DEPTH_ATTACHMENT: GLenum; + readonly DEPTH_BITS: GLenum; + readonly DEPTH_BUFFER_BIT: GLenum; + readonly DEPTH_CLEAR_VALUE: GLenum; + readonly DEPTH_COMPONENT: GLenum; + readonly DEPTH_COMPONENT16: GLenum; + readonly DEPTH_FUNC: GLenum; + readonly DEPTH_RANGE: GLenum; + readonly DEPTH_STENCIL: GLenum; + readonly DEPTH_STENCIL_ATTACHMENT: GLenum; + readonly DEPTH_TEST: GLenum; + readonly DEPTH_WRITEMASK: GLenum; + readonly DITHER: GLenum; + readonly DONT_CARE: GLenum; + readonly DST_ALPHA: GLenum; + readonly DST_COLOR: GLenum; + readonly DYNAMIC_DRAW: GLenum; + readonly ELEMENT_ARRAY_BUFFER: GLenum; + readonly ELEMENT_ARRAY_BUFFER_BINDING: GLenum; + readonly EQUAL: GLenum; + readonly FASTEST: GLenum; + readonly FLOAT: GLenum; + readonly FLOAT_MAT2: GLenum; + readonly FLOAT_MAT3: GLenum; + readonly FLOAT_MAT4: GLenum; + readonly FLOAT_VEC2: GLenum; + readonly FLOAT_VEC3: GLenum; + readonly FLOAT_VEC4: GLenum; + readonly FRAGMENT_SHADER: GLenum; + readonly FRAMEBUFFER: GLenum; + readonly FRAMEBUFFER_ATTACHMENT_OBJECT_NAME: GLenum; + readonly FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE: GLenum; + readonly FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE: GLenum; + readonly FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL: GLenum; + readonly FRAMEBUFFER_BINDING: GLenum; + readonly FRAMEBUFFER_COMPLETE: GLenum; + readonly FRAMEBUFFER_INCOMPLETE_ATTACHMENT: GLenum; + readonly FRAMEBUFFER_INCOMPLETE_DIMENSIONS: GLenum; + readonly FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: GLenum; + readonly FRAMEBUFFER_UNSUPPORTED: GLenum; + readonly FRONT: GLenum; + readonly FRONT_AND_BACK: GLenum; + readonly FRONT_FACE: GLenum; + readonly FUNC_ADD: GLenum; + readonly FUNC_REVERSE_SUBTRACT: GLenum; + readonly FUNC_SUBTRACT: GLenum; + readonly GENERATE_MIPMAP_HINT: GLenum; + readonly GEQUAL: GLenum; + readonly GREATER: GLenum; + readonly GREEN_BITS: GLenum; + readonly HIGH_FLOAT: GLenum; + readonly HIGH_INT: GLenum; + readonly IMPLEMENTATION_COLOR_READ_FORMAT: GLenum; + readonly IMPLEMENTATION_COLOR_READ_TYPE: GLenum; + readonly INCR: GLenum; + readonly INCR_WRAP: GLenum; + readonly INT: GLenum; + readonly INT_VEC2: GLenum; + readonly INT_VEC3: GLenum; + readonly INT_VEC4: GLenum; + readonly INVALID_ENUM: GLenum; + readonly INVALID_FRAMEBUFFER_OPERATION: GLenum; + readonly INVALID_OPERATION: GLenum; + readonly INVALID_VALUE: GLenum; + readonly INVERT: GLenum; + readonly KEEP: GLenum; + readonly LEQUAL: GLenum; + readonly LESS: GLenum; + readonly LINEAR: GLenum; + readonly LINEAR_MIPMAP_LINEAR: GLenum; + readonly LINEAR_MIPMAP_NEAREST: GLenum; + readonly LINES: GLenum; + readonly LINE_LOOP: GLenum; + readonly LINE_STRIP: GLenum; + readonly LINE_WIDTH: GLenum; + readonly LINK_STATUS: GLenum; + readonly LOW_FLOAT: GLenum; + readonly LOW_INT: GLenum; + readonly LUMINANCE: GLenum; + readonly LUMINANCE_ALPHA: GLenum; + readonly MAX_COMBINED_TEXTURE_IMAGE_UNITS: GLenum; + readonly MAX_CUBE_MAP_TEXTURE_SIZE: GLenum; + readonly MAX_FRAGMENT_UNIFORM_VECTORS: GLenum; + readonly MAX_RENDERBUFFER_SIZE: GLenum; + readonly MAX_TEXTURE_IMAGE_UNITS: GLenum; + readonly MAX_TEXTURE_SIZE: GLenum; + readonly MAX_VARYING_VECTORS: GLenum; + readonly MAX_VERTEX_ATTRIBS: GLenum; + readonly MAX_VERTEX_TEXTURE_IMAGE_UNITS: GLenum; + readonly MAX_VERTEX_UNIFORM_VECTORS: GLenum; + readonly MAX_VIEWPORT_DIMS: GLenum; + readonly MEDIUM_FLOAT: GLenum; + readonly MEDIUM_INT: GLenum; + readonly MIRRORED_REPEAT: GLenum; + readonly NEAREST: GLenum; + readonly NEAREST_MIPMAP_LINEAR: GLenum; + readonly NEAREST_MIPMAP_NEAREST: GLenum; + readonly NEVER: GLenum; + readonly NICEST: GLenum; + readonly NONE: GLenum; + readonly NOTEQUAL: GLenum; + readonly NO_ERROR: GLenum; + readonly ONE: GLenum; + readonly ONE_MINUS_CONSTANT_ALPHA: GLenum; + readonly ONE_MINUS_CONSTANT_COLOR: GLenum; + readonly ONE_MINUS_DST_ALPHA: GLenum; + readonly ONE_MINUS_DST_COLOR: GLenum; + readonly ONE_MINUS_SRC_ALPHA: GLenum; + readonly ONE_MINUS_SRC_COLOR: GLenum; + readonly OUT_OF_MEMORY: GLenum; + readonly PACK_ALIGNMENT: GLenum; + readonly POINTS: GLenum; + readonly POLYGON_OFFSET_FACTOR: GLenum; + readonly POLYGON_OFFSET_FILL: GLenum; + readonly POLYGON_OFFSET_UNITS: GLenum; + readonly RED_BITS: GLenum; + readonly RENDERBUFFER: GLenum; + readonly RENDERBUFFER_ALPHA_SIZE: GLenum; + readonly RENDERBUFFER_BINDING: GLenum; + readonly RENDERBUFFER_BLUE_SIZE: GLenum; + readonly RENDERBUFFER_DEPTH_SIZE: GLenum; + readonly RENDERBUFFER_GREEN_SIZE: GLenum; + readonly RENDERBUFFER_HEIGHT: GLenum; + readonly RENDERBUFFER_INTERNAL_FORMAT: GLenum; + readonly RENDERBUFFER_RED_SIZE: GLenum; + readonly RENDERBUFFER_STENCIL_SIZE: GLenum; + readonly RENDERBUFFER_WIDTH: GLenum; + readonly RENDERER: GLenum; + readonly REPEAT: GLenum; + readonly REPLACE: GLenum; + readonly RGB: GLenum; + readonly RGB565: GLenum; + readonly RGB5_A1: GLenum; + readonly RGBA: GLenum; + readonly RGBA4: GLenum; + readonly SAMPLER_2D: GLenum; + readonly SAMPLER_CUBE: GLenum; + readonly SAMPLES: GLenum; + readonly SAMPLE_ALPHA_TO_COVERAGE: GLenum; + readonly SAMPLE_BUFFERS: GLenum; + readonly SAMPLE_COVERAGE: GLenum; + readonly SAMPLE_COVERAGE_INVERT: GLenum; + readonly SAMPLE_COVERAGE_VALUE: GLenum; + readonly SCISSOR_BOX: GLenum; + readonly SCISSOR_TEST: GLenum; + readonly SHADER_TYPE: GLenum; + readonly SHADING_LANGUAGE_VERSION: GLenum; + readonly SHORT: GLenum; + readonly SRC_ALPHA: GLenum; + readonly SRC_ALPHA_SATURATE: GLenum; + readonly SRC_COLOR: GLenum; + readonly STATIC_DRAW: GLenum; + readonly STENCIL_ATTACHMENT: GLenum; + readonly STENCIL_BACK_FAIL: GLenum; + readonly STENCIL_BACK_FUNC: GLenum; + readonly STENCIL_BACK_PASS_DEPTH_FAIL: GLenum; + readonly STENCIL_BACK_PASS_DEPTH_PASS: GLenum; + readonly STENCIL_BACK_REF: GLenum; + readonly STENCIL_BACK_VALUE_MASK: GLenum; + readonly STENCIL_BACK_WRITEMASK: GLenum; + readonly STENCIL_BITS: GLenum; + readonly STENCIL_BUFFER_BIT: GLenum; + readonly STENCIL_CLEAR_VALUE: GLenum; + readonly STENCIL_FAIL: GLenum; + readonly STENCIL_FUNC: GLenum; + readonly STENCIL_INDEX8: GLenum; + readonly STENCIL_PASS_DEPTH_FAIL: GLenum; + readonly STENCIL_PASS_DEPTH_PASS: GLenum; + readonly STENCIL_REF: GLenum; + readonly STENCIL_TEST: GLenum; + readonly STENCIL_VALUE_MASK: GLenum; + readonly STENCIL_WRITEMASK: GLenum; + readonly STREAM_DRAW: GLenum; + readonly SUBPIXEL_BITS: GLenum; + readonly TEXTURE: GLenum; + readonly TEXTURE0: GLenum; + readonly TEXTURE1: GLenum; + readonly TEXTURE10: GLenum; + readonly TEXTURE11: GLenum; + readonly TEXTURE12: GLenum; + readonly TEXTURE13: GLenum; + readonly TEXTURE14: GLenum; + readonly TEXTURE15: GLenum; + readonly TEXTURE16: GLenum; + readonly TEXTURE17: GLenum; + readonly TEXTURE18: GLenum; + readonly TEXTURE19: GLenum; + readonly TEXTURE2: GLenum; + readonly TEXTURE20: GLenum; + readonly TEXTURE21: GLenum; + readonly TEXTURE22: GLenum; + readonly TEXTURE23: GLenum; + readonly TEXTURE24: GLenum; + readonly TEXTURE25: GLenum; + readonly TEXTURE26: GLenum; + readonly TEXTURE27: GLenum; + readonly TEXTURE28: GLenum; + readonly TEXTURE29: GLenum; + readonly TEXTURE3: GLenum; + readonly TEXTURE30: GLenum; + readonly TEXTURE31: GLenum; + readonly TEXTURE4: GLenum; + readonly TEXTURE5: GLenum; + readonly TEXTURE6: GLenum; + readonly TEXTURE7: GLenum; + readonly TEXTURE8: GLenum; + readonly TEXTURE9: GLenum; + readonly TEXTURE_2D: GLenum; + readonly TEXTURE_BINDING_2D: GLenum; + readonly TEXTURE_BINDING_CUBE_MAP: GLenum; + readonly TEXTURE_CUBE_MAP: GLenum; + readonly TEXTURE_CUBE_MAP_NEGATIVE_X: GLenum; + readonly TEXTURE_CUBE_MAP_NEGATIVE_Y: GLenum; + readonly TEXTURE_CUBE_MAP_NEGATIVE_Z: GLenum; + readonly TEXTURE_CUBE_MAP_POSITIVE_X: GLenum; + readonly TEXTURE_CUBE_MAP_POSITIVE_Y: GLenum; + readonly TEXTURE_CUBE_MAP_POSITIVE_Z: GLenum; + readonly TEXTURE_MAG_FILTER: GLenum; + readonly TEXTURE_MIN_FILTER: GLenum; + readonly TEXTURE_WRAP_S: GLenum; + readonly TEXTURE_WRAP_T: GLenum; + readonly TRIANGLES: GLenum; + readonly TRIANGLE_FAN: GLenum; + readonly TRIANGLE_STRIP: GLenum; + readonly UNPACK_ALIGNMENT: GLenum; + readonly UNPACK_COLORSPACE_CONVERSION_WEBGL: GLenum; + readonly UNPACK_FLIP_Y_WEBGL: GLenum; + readonly UNPACK_PREMULTIPLY_ALPHA_WEBGL: GLenum; + readonly UNSIGNED_BYTE: GLenum; + readonly UNSIGNED_INT: GLenum; + readonly UNSIGNED_SHORT: GLenum; + readonly UNSIGNED_SHORT_4_4_4_4: GLenum; + readonly UNSIGNED_SHORT_5_5_5_1: GLenum; + readonly UNSIGNED_SHORT_5_6_5: GLenum; + readonly VALIDATE_STATUS: GLenum; + readonly VENDOR: GLenum; + readonly VERSION: GLenum; + readonly VERTEX_ATTRIB_ARRAY_BUFFER_BINDING: GLenum; + readonly VERTEX_ATTRIB_ARRAY_ENABLED: GLenum; + readonly VERTEX_ATTRIB_ARRAY_NORMALIZED: GLenum; + readonly VERTEX_ATTRIB_ARRAY_POINTER: GLenum; + readonly VERTEX_ATTRIB_ARRAY_SIZE: GLenum; + readonly VERTEX_ATTRIB_ARRAY_STRIDE: GLenum; + readonly VERTEX_ATTRIB_ARRAY_TYPE: GLenum; + readonly VERTEX_SHADER: GLenum; + readonly VIEWPORT: GLenum; + readonly ZERO: GLenum; +}; + +interface WebGLRenderingContextBase { + readonly drawingBufferHeight: GLsizei; + readonly drawingBufferWidth: GLsizei; + activeTexture(texture: GLenum): void; + attachShader(program: WebGLProgram, shader: WebGLShader): void; + bindAttribLocation(program: WebGLProgram, index: GLuint, name: string): void; + bindBuffer(target: GLenum, buffer: WebGLBuffer | null): void; + bindFramebuffer(target: GLenum, framebuffer: WebGLFramebuffer | null): void; + bindRenderbuffer(target: GLenum, renderbuffer: WebGLRenderbuffer | null): void; + bindTexture(target: GLenum, texture: WebGLTexture | null): void; + blendColor(red: GLclampf, green: GLclampf, blue: GLclampf, alpha: GLclampf): void; + blendEquation(mode: GLenum): void; + blendEquationSeparate(modeRGB: GLenum, modeAlpha: GLenum): void; + blendFunc(sfactor: GLenum, dfactor: GLenum): void; + blendFuncSeparate(srcRGB: GLenum, dstRGB: GLenum, srcAlpha: GLenum, dstAlpha: GLenum): void; + bufferData(target: GLenum, size: GLsizeiptr, usage: GLenum): void; + bufferData(target: GLenum, data: BufferSource | null, usage: GLenum): void; + bufferSubData(target: GLenum, offset: GLintptr, data: BufferSource): void; + checkFramebufferStatus(target: GLenum): GLenum; + clear(mask: GLbitfield): void; + clearColor(red: GLclampf, green: GLclampf, blue: GLclampf, alpha: GLclampf): void; + clearDepth(depth: GLclampf): void; + clearStencil(s: GLint): void; + colorMask(red: GLboolean, green: GLboolean, blue: GLboolean, alpha: GLboolean): void; + compileShader(shader: WebGLShader): void; + compressedTexImage2D(target: GLenum, level: GLint, internalformat: GLenum, width: GLsizei, height: GLsizei, border: GLint, data: ArrayBufferView): void; + compressedTexSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, width: GLsizei, height: GLsizei, format: GLenum, data: ArrayBufferView): void; + copyTexImage2D(target: GLenum, level: GLint, internalformat: GLenum, x: GLint, y: GLint, width: GLsizei, height: GLsizei, border: GLint): void; + copyTexSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, x: GLint, y: GLint, width: GLsizei, height: GLsizei): void; + createBuffer(): WebGLBuffer | null; + createFramebuffer(): WebGLFramebuffer | null; + createProgram(): WebGLProgram | null; + createRenderbuffer(): WebGLRenderbuffer | null; + createShader(type: GLenum): WebGLShader | null; + createTexture(): WebGLTexture | null; + cullFace(mode: GLenum): void; + deleteBuffer(buffer: WebGLBuffer | null): void; + deleteFramebuffer(framebuffer: WebGLFramebuffer | null): void; + deleteProgram(program: WebGLProgram | null): void; + deleteRenderbuffer(renderbuffer: WebGLRenderbuffer | null): void; + deleteShader(shader: WebGLShader | null): void; + deleteTexture(texture: WebGLTexture | null): void; + depthFunc(func: GLenum): void; + depthMask(flag: GLboolean): void; + depthRange(zNear: GLclampf, zFar: GLclampf): void; + detachShader(program: WebGLProgram, shader: WebGLShader): void; + disable(cap: GLenum): void; + disableVertexAttribArray(index: GLuint): void; + drawArrays(mode: GLenum, first: GLint, count: GLsizei): void; + drawElements(mode: GLenum, count: GLsizei, type: GLenum, offset: GLintptr): void; + enable(cap: GLenum): void; + enableVertexAttribArray(index: GLuint): void; + finish(): void; + flush(): void; + framebufferRenderbuffer(target: GLenum, attachment: GLenum, renderbuffertarget: GLenum, renderbuffer: WebGLRenderbuffer | null): void; + framebufferTexture2D(target: GLenum, attachment: GLenum, textarget: GLenum, texture: WebGLTexture | null, level: GLint): void; + frontFace(mode: GLenum): void; + generateMipmap(target: GLenum): void; + getActiveAttrib(program: WebGLProgram, index: GLuint): WebGLActiveInfo | null; + getActiveUniform(program: WebGLProgram, index: GLuint): WebGLActiveInfo | null; + getAttachedShaders(program: WebGLProgram): WebGLShader[] | null; + getAttribLocation(program: WebGLProgram, name: string): GLint; + getBufferParameter(target: GLenum, pname: GLenum): any; + getContextAttributes(): WebGLContextAttributes | null; + getError(): GLenum; + getExtension(extensionName: "EXT_blend_minmax"): EXT_blend_minmax | null; + getExtension(extensionName: "EXT_texture_filter_anisotropic"): EXT_texture_filter_anisotropic | null; + getExtension(extensionName: "EXT_frag_depth"): EXT_frag_depth | null; + getExtension(extensionName: "EXT_shader_texture_lod"): EXT_shader_texture_lod | null; + getExtension(extensionName: "EXT_sRGB"): EXT_sRGB | null; + getExtension(extensionName: "OES_vertex_array_object"): OES_vertex_array_object | null; + getExtension(extensionName: "WEBGL_color_buffer_float"): WEBGL_color_buffer_float | null; + getExtension(extensionName: "WEBGL_compressed_texture_astc"): WEBGL_compressed_texture_astc | null; + getExtension(extensionName: "WEBGL_compressed_texture_s3tc_srgb"): WEBGL_compressed_texture_s3tc_srgb | null; + getExtension(extensionName: "WEBGL_debug_shaders"): WEBGL_debug_shaders | null; + getExtension(extensionName: "WEBGL_draw_buffers"): WEBGL_draw_buffers | null; + getExtension(extensionName: "WEBGL_lose_context"): WEBGL_lose_context | null; + getExtension(extensionName: "WEBGL_depth_texture"): WEBGL_depth_texture | null; + getExtension(extensionName: "WEBGL_debug_renderer_info"): WEBGL_debug_renderer_info | null; + getExtension(extensionName: "WEBGL_compressed_texture_s3tc"): WEBGL_compressed_texture_s3tc | null; + getExtension(extensionName: "OES_texture_half_float_linear"): OES_texture_half_float_linear | null; + getExtension(extensionName: "OES_texture_half_float"): OES_texture_half_float | null; + getExtension(extensionName: "OES_texture_float_linear"): OES_texture_float_linear | null; + getExtension(extensionName: "OES_texture_float"): OES_texture_float | null; + getExtension(extensionName: "OES_standard_derivatives"): OES_standard_derivatives | null; + getExtension(extensionName: "OES_element_index_uint"): OES_element_index_uint | null; + getExtension(extensionName: "ANGLE_instanced_arrays"): ANGLE_instanced_arrays | null; + getExtension(extensionName: string): any; + getFramebufferAttachmentParameter(target: GLenum, attachment: GLenum, pname: GLenum): any; + getParameter(pname: GLenum): any; + getProgramInfoLog(program: WebGLProgram): string | null; + getProgramParameter(program: WebGLProgram, pname: GLenum): any; + getRenderbufferParameter(target: GLenum, pname: GLenum): any; + getShaderInfoLog(shader: WebGLShader): string | null; + getShaderParameter(shader: WebGLShader, pname: GLenum): any; + getShaderPrecisionFormat(shadertype: GLenum, precisiontype: GLenum): WebGLShaderPrecisionFormat | null; + getShaderSource(shader: WebGLShader): string | null; + getSupportedExtensions(): string[] | null; + getTexParameter(target: GLenum, pname: GLenum): any; + getUniform(program: WebGLProgram, location: WebGLUniformLocation): any; + getUniformLocation(program: WebGLProgram, name: string): WebGLUniformLocation | null; + getVertexAttrib(index: GLuint, pname: GLenum): any; + getVertexAttribOffset(index: GLuint, pname: GLenum): GLintptr; + hint(target: GLenum, mode: GLenum): void; + isBuffer(buffer: WebGLBuffer | null): GLboolean; + isContextLost(): boolean; + isEnabled(cap: GLenum): GLboolean; + isFramebuffer(framebuffer: WebGLFramebuffer | null): GLboolean; + isProgram(program: WebGLProgram | null): GLboolean; + isRenderbuffer(renderbuffer: WebGLRenderbuffer | null): GLboolean; + isShader(shader: WebGLShader | null): GLboolean; + isTexture(texture: WebGLTexture | null): GLboolean; + lineWidth(width: GLfloat): void; + linkProgram(program: WebGLProgram): void; + pixelStorei(pname: GLenum, param: GLint): void; + polygonOffset(factor: GLfloat, units: GLfloat): void; + readPixels(x: GLint, y: GLint, width: GLsizei, height: GLsizei, format: GLenum, type: GLenum, pixels: ArrayBufferView | null): void; + renderbufferStorage(target: GLenum, internalformat: GLenum, width: GLsizei, height: GLsizei): void; + sampleCoverage(value: GLclampf, invert: GLboolean): void; + scissor(x: GLint, y: GLint, width: GLsizei, height: GLsizei): void; + shaderSource(shader: WebGLShader, source: string): void; + stencilFunc(func: GLenum, ref: GLint, mask: GLuint): void; + stencilFuncSeparate(face: GLenum, func: GLenum, ref: GLint, mask: GLuint): void; + stencilMask(mask: GLuint): void; + stencilMaskSeparate(face: GLenum, mask: GLuint): void; + stencilOp(fail: GLenum, zfail: GLenum, zpass: GLenum): void; + stencilOpSeparate(face: GLenum, fail: GLenum, zfail: GLenum, zpass: GLenum): void; + texImage2D(target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, height: GLsizei, border: GLint, format: GLenum, type: GLenum, pixels: ArrayBufferView | null): void; + texImage2D(target: GLenum, level: GLint, internalformat: GLint, format: GLenum, type: GLenum, source: TexImageSource): void; + texParameterf(target: GLenum, pname: GLenum, param: GLfloat): void; + texParameteri(target: GLenum, pname: GLenum, param: GLint): void; + texSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, width: GLsizei, height: GLsizei, format: GLenum, type: GLenum, pixels: ArrayBufferView | null): void; + texSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, format: GLenum, type: GLenum, source: TexImageSource): void; + uniform1f(location: WebGLUniformLocation | null, x: GLfloat): void; + uniform1fv(location: WebGLUniformLocation | null, v: Float32List): void; + uniform1i(location: WebGLUniformLocation | null, x: GLint): void; + uniform1iv(location: WebGLUniformLocation | null, v: Int32List): void; + uniform2f(location: WebGLUniformLocation | null, x: GLfloat, y: GLfloat): void; + uniform2fv(location: WebGLUniformLocation | null, v: Float32List): void; + uniform2i(location: WebGLUniformLocation | null, x: GLint, y: GLint): void; + uniform2iv(location: WebGLUniformLocation | null, v: Int32List): void; + uniform3f(location: WebGLUniformLocation | null, x: GLfloat, y: GLfloat, z: GLfloat): void; + uniform3fv(location: WebGLUniformLocation | null, v: Float32List): void; + uniform3i(location: WebGLUniformLocation | null, x: GLint, y: GLint, z: GLint): void; + uniform3iv(location: WebGLUniformLocation | null, v: Int32List): void; + uniform4f(location: WebGLUniformLocation | null, x: GLfloat, y: GLfloat, z: GLfloat, w: GLfloat): void; + uniform4fv(location: WebGLUniformLocation | null, v: Float32List): void; + uniform4i(location: WebGLUniformLocation | null, x: GLint, y: GLint, z: GLint, w: GLint): void; + uniform4iv(location: WebGLUniformLocation | null, v: Int32List): void; + uniformMatrix2fv(location: WebGLUniformLocation | null, transpose: GLboolean, value: Float32List): void; + uniformMatrix3fv(location: WebGLUniformLocation | null, transpose: GLboolean, value: Float32List): void; + uniformMatrix4fv(location: WebGLUniformLocation | null, transpose: GLboolean, value: Float32List): void; + useProgram(program: WebGLProgram | null): void; + validateProgram(program: WebGLProgram): void; + vertexAttrib1f(index: GLuint, x: GLfloat): void; + vertexAttrib1fv(index: GLuint, values: Float32List): void; + vertexAttrib2f(index: GLuint, x: GLfloat, y: GLfloat): void; + vertexAttrib2fv(index: GLuint, values: Float32List): void; + vertexAttrib3f(index: GLuint, x: GLfloat, y: GLfloat, z: GLfloat): void; + vertexAttrib3fv(index: GLuint, values: Float32List): void; + vertexAttrib4f(index: GLuint, x: GLfloat, y: GLfloat, z: GLfloat, w: GLfloat): void; + vertexAttrib4fv(index: GLuint, values: Float32List): void; + vertexAttribPointer(index: GLuint, size: GLint, type: GLenum, normalized: GLboolean, stride: GLsizei, offset: GLintptr): void; + viewport(x: GLint, y: GLint, width: GLsizei, height: GLsizei): void; + readonly ACTIVE_ATTRIBUTES: GLenum; + readonly ACTIVE_TEXTURE: GLenum; + readonly ACTIVE_UNIFORMS: GLenum; + readonly ALIASED_LINE_WIDTH_RANGE: GLenum; + readonly ALIASED_POINT_SIZE_RANGE: GLenum; + readonly ALPHA: GLenum; + readonly ALPHA_BITS: GLenum; + readonly ALWAYS: GLenum; + readonly ARRAY_BUFFER: GLenum; + readonly ARRAY_BUFFER_BINDING: GLenum; + readonly ATTACHED_SHADERS: GLenum; + readonly BACK: GLenum; + readonly BLEND: GLenum; + readonly BLEND_COLOR: GLenum; + readonly BLEND_DST_ALPHA: GLenum; + readonly BLEND_DST_RGB: GLenum; + readonly BLEND_EQUATION: GLenum; + readonly BLEND_EQUATION_ALPHA: GLenum; + readonly BLEND_EQUATION_RGB: GLenum; + readonly BLEND_SRC_ALPHA: GLenum; + readonly BLEND_SRC_RGB: GLenum; + readonly BLUE_BITS: GLenum; + readonly BOOL: GLenum; + readonly BOOL_VEC2: GLenum; + readonly BOOL_VEC3: GLenum; + readonly BOOL_VEC4: GLenum; + readonly BROWSER_DEFAULT_WEBGL: GLenum; + readonly BUFFER_SIZE: GLenum; + readonly BUFFER_USAGE: GLenum; + readonly BYTE: GLenum; + readonly CCW: GLenum; + readonly CLAMP_TO_EDGE: GLenum; + readonly COLOR_ATTACHMENT0: GLenum; + readonly COLOR_BUFFER_BIT: GLenum; + readonly COLOR_CLEAR_VALUE: GLenum; + readonly COLOR_WRITEMASK: GLenum; + readonly COMPILE_STATUS: GLenum; + readonly COMPRESSED_TEXTURE_FORMATS: GLenum; + readonly CONSTANT_ALPHA: GLenum; + readonly CONSTANT_COLOR: GLenum; + readonly CONTEXT_LOST_WEBGL: GLenum; + readonly CULL_FACE: GLenum; + readonly CULL_FACE_MODE: GLenum; + readonly CURRENT_PROGRAM: GLenum; + readonly CURRENT_VERTEX_ATTRIB: GLenum; + readonly CW: GLenum; + readonly DECR: GLenum; + readonly DECR_WRAP: GLenum; + readonly DELETE_STATUS: GLenum; + readonly DEPTH_ATTACHMENT: GLenum; + readonly DEPTH_BITS: GLenum; + readonly DEPTH_BUFFER_BIT: GLenum; + readonly DEPTH_CLEAR_VALUE: GLenum; + readonly DEPTH_COMPONENT: GLenum; + readonly DEPTH_COMPONENT16: GLenum; + readonly DEPTH_FUNC: GLenum; + readonly DEPTH_RANGE: GLenum; + readonly DEPTH_STENCIL: GLenum; + readonly DEPTH_STENCIL_ATTACHMENT: GLenum; + readonly DEPTH_TEST: GLenum; + readonly DEPTH_WRITEMASK: GLenum; + readonly DITHER: GLenum; + readonly DONT_CARE: GLenum; + readonly DST_ALPHA: GLenum; + readonly DST_COLOR: GLenum; + readonly DYNAMIC_DRAW: GLenum; + readonly ELEMENT_ARRAY_BUFFER: GLenum; + readonly ELEMENT_ARRAY_BUFFER_BINDING: GLenum; + readonly EQUAL: GLenum; + readonly FASTEST: GLenum; + readonly FLOAT: GLenum; + readonly FLOAT_MAT2: GLenum; + readonly FLOAT_MAT3: GLenum; + readonly FLOAT_MAT4: GLenum; + readonly FLOAT_VEC2: GLenum; + readonly FLOAT_VEC3: GLenum; + readonly FLOAT_VEC4: GLenum; + readonly FRAGMENT_SHADER: GLenum; + readonly FRAMEBUFFER: GLenum; + readonly FRAMEBUFFER_ATTACHMENT_OBJECT_NAME: GLenum; + readonly FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE: GLenum; + readonly FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE: GLenum; + readonly FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL: GLenum; + readonly FRAMEBUFFER_BINDING: GLenum; + readonly FRAMEBUFFER_COMPLETE: GLenum; + readonly FRAMEBUFFER_INCOMPLETE_ATTACHMENT: GLenum; + readonly FRAMEBUFFER_INCOMPLETE_DIMENSIONS: GLenum; + readonly FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: GLenum; + readonly FRAMEBUFFER_UNSUPPORTED: GLenum; + readonly FRONT: GLenum; + readonly FRONT_AND_BACK: GLenum; + readonly FRONT_FACE: GLenum; + readonly FUNC_ADD: GLenum; + readonly FUNC_REVERSE_SUBTRACT: GLenum; + readonly FUNC_SUBTRACT: GLenum; + readonly GENERATE_MIPMAP_HINT: GLenum; + readonly GEQUAL: GLenum; + readonly GREATER: GLenum; + readonly GREEN_BITS: GLenum; + readonly HIGH_FLOAT: GLenum; + readonly HIGH_INT: GLenum; + readonly IMPLEMENTATION_COLOR_READ_FORMAT: GLenum; + readonly IMPLEMENTATION_COLOR_READ_TYPE: GLenum; + readonly INCR: GLenum; + readonly INCR_WRAP: GLenum; + readonly INT: GLenum; + readonly INT_VEC2: GLenum; + readonly INT_VEC3: GLenum; + readonly INT_VEC4: GLenum; + readonly INVALID_ENUM: GLenum; + readonly INVALID_FRAMEBUFFER_OPERATION: GLenum; + readonly INVALID_OPERATION: GLenum; + readonly INVALID_VALUE: GLenum; + readonly INVERT: GLenum; + readonly KEEP: GLenum; + readonly LEQUAL: GLenum; + readonly LESS: GLenum; + readonly LINEAR: GLenum; + readonly LINEAR_MIPMAP_LINEAR: GLenum; + readonly LINEAR_MIPMAP_NEAREST: GLenum; + readonly LINES: GLenum; + readonly LINE_LOOP: GLenum; + readonly LINE_STRIP: GLenum; + readonly LINE_WIDTH: GLenum; + readonly LINK_STATUS: GLenum; + readonly LOW_FLOAT: GLenum; + readonly LOW_INT: GLenum; + readonly LUMINANCE: GLenum; + readonly LUMINANCE_ALPHA: GLenum; + readonly MAX_COMBINED_TEXTURE_IMAGE_UNITS: GLenum; + readonly MAX_CUBE_MAP_TEXTURE_SIZE: GLenum; + readonly MAX_FRAGMENT_UNIFORM_VECTORS: GLenum; + readonly MAX_RENDERBUFFER_SIZE: GLenum; + readonly MAX_TEXTURE_IMAGE_UNITS: GLenum; + readonly MAX_TEXTURE_SIZE: GLenum; + readonly MAX_VARYING_VECTORS: GLenum; + readonly MAX_VERTEX_ATTRIBS: GLenum; + readonly MAX_VERTEX_TEXTURE_IMAGE_UNITS: GLenum; + readonly MAX_VERTEX_UNIFORM_VECTORS: GLenum; + readonly MAX_VIEWPORT_DIMS: GLenum; + readonly MEDIUM_FLOAT: GLenum; + readonly MEDIUM_INT: GLenum; + readonly MIRRORED_REPEAT: GLenum; + readonly NEAREST: GLenum; + readonly NEAREST_MIPMAP_LINEAR: GLenum; + readonly NEAREST_MIPMAP_NEAREST: GLenum; + readonly NEVER: GLenum; + readonly NICEST: GLenum; + readonly NONE: GLenum; + readonly NOTEQUAL: GLenum; + readonly NO_ERROR: GLenum; + readonly ONE: GLenum; + readonly ONE_MINUS_CONSTANT_ALPHA: GLenum; + readonly ONE_MINUS_CONSTANT_COLOR: GLenum; + readonly ONE_MINUS_DST_ALPHA: GLenum; + readonly ONE_MINUS_DST_COLOR: GLenum; + readonly ONE_MINUS_SRC_ALPHA: GLenum; + readonly ONE_MINUS_SRC_COLOR: GLenum; + readonly OUT_OF_MEMORY: GLenum; + readonly PACK_ALIGNMENT: GLenum; + readonly POINTS: GLenum; + readonly POLYGON_OFFSET_FACTOR: GLenum; + readonly POLYGON_OFFSET_FILL: GLenum; + readonly POLYGON_OFFSET_UNITS: GLenum; + readonly RED_BITS: GLenum; + readonly RENDERBUFFER: GLenum; + readonly RENDERBUFFER_ALPHA_SIZE: GLenum; + readonly RENDERBUFFER_BINDING: GLenum; + readonly RENDERBUFFER_BLUE_SIZE: GLenum; + readonly RENDERBUFFER_DEPTH_SIZE: GLenum; + readonly RENDERBUFFER_GREEN_SIZE: GLenum; + readonly RENDERBUFFER_HEIGHT: GLenum; + readonly RENDERBUFFER_INTERNAL_FORMAT: GLenum; + readonly RENDERBUFFER_RED_SIZE: GLenum; + readonly RENDERBUFFER_STENCIL_SIZE: GLenum; + readonly RENDERBUFFER_WIDTH: GLenum; + readonly RENDERER: GLenum; + readonly REPEAT: GLenum; + readonly REPLACE: GLenum; + readonly RGB: GLenum; + readonly RGB565: GLenum; + readonly RGB5_A1: GLenum; + readonly RGBA: GLenum; + readonly RGBA4: GLenum; + readonly SAMPLER_2D: GLenum; + readonly SAMPLER_CUBE: GLenum; + readonly SAMPLES: GLenum; + readonly SAMPLE_ALPHA_TO_COVERAGE: GLenum; + readonly SAMPLE_BUFFERS: GLenum; + readonly SAMPLE_COVERAGE: GLenum; + readonly SAMPLE_COVERAGE_INVERT: GLenum; + readonly SAMPLE_COVERAGE_VALUE: GLenum; + readonly SCISSOR_BOX: GLenum; + readonly SCISSOR_TEST: GLenum; + readonly SHADER_TYPE: GLenum; + readonly SHADING_LANGUAGE_VERSION: GLenum; + readonly SHORT: GLenum; + readonly SRC_ALPHA: GLenum; + readonly SRC_ALPHA_SATURATE: GLenum; + readonly SRC_COLOR: GLenum; + readonly STATIC_DRAW: GLenum; + readonly STENCIL_ATTACHMENT: GLenum; + readonly STENCIL_BACK_FAIL: GLenum; + readonly STENCIL_BACK_FUNC: GLenum; + readonly STENCIL_BACK_PASS_DEPTH_FAIL: GLenum; + readonly STENCIL_BACK_PASS_DEPTH_PASS: GLenum; + readonly STENCIL_BACK_REF: GLenum; + readonly STENCIL_BACK_VALUE_MASK: GLenum; + readonly STENCIL_BACK_WRITEMASK: GLenum; + readonly STENCIL_BITS: GLenum; + readonly STENCIL_BUFFER_BIT: GLenum; + readonly STENCIL_CLEAR_VALUE: GLenum; + readonly STENCIL_FAIL: GLenum; + readonly STENCIL_FUNC: GLenum; + readonly STENCIL_INDEX8: GLenum; + readonly STENCIL_PASS_DEPTH_FAIL: GLenum; + readonly STENCIL_PASS_DEPTH_PASS: GLenum; + readonly STENCIL_REF: GLenum; + readonly STENCIL_TEST: GLenum; + readonly STENCIL_VALUE_MASK: GLenum; + readonly STENCIL_WRITEMASK: GLenum; + readonly STREAM_DRAW: GLenum; + readonly SUBPIXEL_BITS: GLenum; + readonly TEXTURE: GLenum; + readonly TEXTURE0: GLenum; + readonly TEXTURE1: GLenum; + readonly TEXTURE10: GLenum; + readonly TEXTURE11: GLenum; + readonly TEXTURE12: GLenum; + readonly TEXTURE13: GLenum; + readonly TEXTURE14: GLenum; + readonly TEXTURE15: GLenum; + readonly TEXTURE16: GLenum; + readonly TEXTURE17: GLenum; + readonly TEXTURE18: GLenum; + readonly TEXTURE19: GLenum; + readonly TEXTURE2: GLenum; + readonly TEXTURE20: GLenum; + readonly TEXTURE21: GLenum; + readonly TEXTURE22: GLenum; + readonly TEXTURE23: GLenum; + readonly TEXTURE24: GLenum; + readonly TEXTURE25: GLenum; + readonly TEXTURE26: GLenum; + readonly TEXTURE27: GLenum; + readonly TEXTURE28: GLenum; + readonly TEXTURE29: GLenum; + readonly TEXTURE3: GLenum; + readonly TEXTURE30: GLenum; + readonly TEXTURE31: GLenum; + readonly TEXTURE4: GLenum; + readonly TEXTURE5: GLenum; + readonly TEXTURE6: GLenum; + readonly TEXTURE7: GLenum; + readonly TEXTURE8: GLenum; + readonly TEXTURE9: GLenum; + readonly TEXTURE_2D: GLenum; + readonly TEXTURE_BINDING_2D: GLenum; + readonly TEXTURE_BINDING_CUBE_MAP: GLenum; + readonly TEXTURE_CUBE_MAP: GLenum; + readonly TEXTURE_CUBE_MAP_NEGATIVE_X: GLenum; + readonly TEXTURE_CUBE_MAP_NEGATIVE_Y: GLenum; + readonly TEXTURE_CUBE_MAP_NEGATIVE_Z: GLenum; + readonly TEXTURE_CUBE_MAP_POSITIVE_X: GLenum; + readonly TEXTURE_CUBE_MAP_POSITIVE_Y: GLenum; + readonly TEXTURE_CUBE_MAP_POSITIVE_Z: GLenum; + readonly TEXTURE_MAG_FILTER: GLenum; + readonly TEXTURE_MIN_FILTER: GLenum; + readonly TEXTURE_WRAP_S: GLenum; + readonly TEXTURE_WRAP_T: GLenum; + readonly TRIANGLES: GLenum; + readonly TRIANGLE_FAN: GLenum; + readonly TRIANGLE_STRIP: GLenum; + readonly UNPACK_ALIGNMENT: GLenum; + readonly UNPACK_COLORSPACE_CONVERSION_WEBGL: GLenum; + readonly UNPACK_FLIP_Y_WEBGL: GLenum; + readonly UNPACK_PREMULTIPLY_ALPHA_WEBGL: GLenum; + readonly UNSIGNED_BYTE: GLenum; + readonly UNSIGNED_INT: GLenum; + readonly UNSIGNED_SHORT: GLenum; + readonly UNSIGNED_SHORT_4_4_4_4: GLenum; + readonly UNSIGNED_SHORT_5_5_5_1: GLenum; + readonly UNSIGNED_SHORT_5_6_5: GLenum; + readonly VALIDATE_STATUS: GLenum; + readonly VENDOR: GLenum; + readonly VERSION: GLenum; + readonly VERTEX_ATTRIB_ARRAY_BUFFER_BINDING: GLenum; + readonly VERTEX_ATTRIB_ARRAY_ENABLED: GLenum; + readonly VERTEX_ATTRIB_ARRAY_NORMALIZED: GLenum; + readonly VERTEX_ATTRIB_ARRAY_POINTER: GLenum; + readonly VERTEX_ATTRIB_ARRAY_SIZE: GLenum; + readonly VERTEX_ATTRIB_ARRAY_STRIDE: GLenum; + readonly VERTEX_ATTRIB_ARRAY_TYPE: GLenum; + readonly VERTEX_SHADER: GLenum; + readonly VIEWPORT: GLenum; + readonly ZERO: GLenum; +} + +interface WebGLShader extends WebGLObject { +} + +declare var WebGLShader: { + prototype: WebGLShader; + new(): WebGLShader; +}; + +interface WebGLShaderPrecisionFormat { + readonly precision: GLint; + readonly rangeMax: GLint; + readonly rangeMin: GLint; +} + +declare var WebGLShaderPrecisionFormat: { + prototype: WebGLShaderPrecisionFormat; + new(): WebGLShaderPrecisionFormat; +}; + +interface WebGLTexture extends WebGLObject { +} + +declare var WebGLTexture: { + prototype: WebGLTexture; + new(): WebGLTexture; +}; + +interface WebGLUniformLocation { +} + +declare var WebGLUniformLocation: { + prototype: WebGLUniformLocation; + new(): WebGLUniformLocation; +}; + +interface WebGLVertexArrayObjectOES extends WebGLObject { +} + +interface WebSocketEventMap { + "close": CloseEvent; + "error": Event; + "message": MessageEvent; + "open": Event; +} + +interface WebSocket extends EventTarget { + binaryType: BinaryType; + readonly bufferedAmount: number; + readonly extensions: string; + onclose: ((this: WebSocket, ev: CloseEvent) => any) | null; + onerror: ((this: WebSocket, ev: Event) => any) | null; + onmessage: ((this: WebSocket, ev: MessageEvent) => any) | null; + onopen: ((this: WebSocket, ev: Event) => any) | null; + readonly protocol: string; + readonly readyState: number; + readonly url: string; + close(code?: number, reason?: string): void; + send(data: string | ArrayBufferLike | Blob | ArrayBufferView): void; + readonly CLOSED: number; + readonly CLOSING: number; + readonly CONNECTING: number; + readonly OPEN: number; + addEventListener(type: K, listener: (this: WebSocket, ev: WebSocketEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: WebSocket, ev: WebSocketEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var WebSocket: { + prototype: WebSocket; + new(url: string, protocols?: string | string[]): WebSocket; + readonly CLOSED: number; + readonly CLOSING: number; + readonly CONNECTING: number; + readonly OPEN: number; +}; + +interface WindowBase64 { + atob(encodedString: string): string; + btoa(rawString: string): string; +} + +interface WindowClient extends Client { + readonly ancestorOrigins: ReadonlyArray; + readonly focused: boolean; + readonly visibilityState: VisibilityState; + focus(): Promise; + navigate(url: string): Promise; +} + +declare var WindowClient: { + prototype: WindowClient; + new(): WindowClient; +}; + +interface WindowConsole { + readonly console: Console; +} + +interface WindowOrWorkerGlobalScope { + readonly caches: CacheStorage; + readonly crypto: Crypto; + readonly indexedDB: IDBFactory; + readonly origin: string; + readonly performance: Performance; + atob(data: string): string; + btoa(data: string): string; + clearInterval(handle?: number): void; + clearTimeout(handle?: number): void; + createImageBitmap(image: ImageBitmapSource): Promise; + createImageBitmap(image: ImageBitmapSource, sx: number, sy: number, sw: number, sh: number): Promise; + fetch(input: RequestInfo, init?: RequestInit): Promise; + queueMicrotask(callback: Function): void; + setInterval(handler: TimerHandler, timeout?: number, ...arguments: any[]): number; + setTimeout(handler: TimerHandler, timeout?: number, ...arguments: any[]): number; +} + +interface WorkerEventMap extends AbstractWorkerEventMap { + "message": MessageEvent; +} + +interface Worker extends EventTarget, AbstractWorker { + onmessage: ((this: Worker, ev: MessageEvent) => any) | null; + postMessage(message: any, transfer?: Transferable[]): void; + terminate(): void; + addEventListener(type: K, listener: (this: Worker, ev: WorkerEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: Worker, ev: WorkerEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var Worker: { + prototype: Worker; + new(stringUrl: string, options?: WorkerOptions): Worker; +}; + +interface WorkerGlobalScopeEventMap { + "error": ErrorEvent; +} + +interface WorkerGlobalScope extends EventTarget, WorkerUtils, WindowConsole, GlobalFetch, WindowOrWorkerGlobalScope { + readonly caches: CacheStorage; + readonly isSecureContext: boolean; + readonly location: WorkerLocation; + onerror: ((this: WorkerGlobalScope, ev: ErrorEvent) => any) | null; + readonly performance: Performance; + readonly self: WorkerGlobalScope; + msWriteProfilerMark(profilerMarkName: string): void; + addEventListener(type: K, listener: (this: WorkerGlobalScope, ev: WorkerGlobalScopeEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: WorkerGlobalScope, ev: WorkerGlobalScopeEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var WorkerGlobalScope: { + prototype: WorkerGlobalScope; + new(): WorkerGlobalScope; +}; + +interface WorkerLocation { + readonly hash: string; + readonly host: string; + readonly hostname: string; + readonly href: string; + readonly origin: string; + readonly pathname: string; + readonly port: string; + readonly protocol: string; + readonly search: string; + toString(): string; +} + +declare var WorkerLocation: { + prototype: WorkerLocation; + new(): WorkerLocation; +}; + +interface WorkerNavigator extends NavigatorID, NavigatorOnLine, NavigatorBeacon, NavigatorConcurrentHardware, NavigatorStorage { + readonly serviceWorker: ServiceWorkerContainer; +} + +declare var WorkerNavigator: { + prototype: WorkerNavigator; + new(): WorkerNavigator; +}; + +interface WorkerUtils extends WindowBase64 { + readonly indexedDB: IDBFactory; + readonly msIndexedDB: IDBFactory; + readonly navigator: WorkerNavigator; + importScripts(...urls: string[]): void; +} + +interface WritableStream { + readonly locked: boolean; + abort(reason?: any): Promise; + getWriter(): WritableStreamDefaultWriter; +} + +declare var WritableStream: { + prototype: WritableStream; + new(underlyingSink?: UnderlyingSink, strategy?: QueuingStrategy): WritableStream; +}; + +interface WritableStreamDefaultController { + error(error?: any): void; +} + +interface WritableStreamDefaultWriter { + readonly closed: Promise; + readonly desiredSize: number | null; + readonly ready: Promise; + abort(reason?: any): Promise; + close(): Promise; + releaseLock(): void; + write(chunk: W): Promise; +} + +interface XMLHttpRequestEventMap extends XMLHttpRequestEventTargetEventMap { + "readystatechange": Event; +} + +interface XMLHttpRequest extends XMLHttpRequestEventTarget { + onreadystatechange: ((this: XMLHttpRequest, ev: Event) => any) | null; + /** + * Returns client's state. + */ + readonly readyState: number; + /** + * Returns the response's body. + */ + readonly response: any; + /** + * Returns the text response. + * Throws an "InvalidStateError" DOMException if responseType is not the empty string or "text". + */ + readonly responseText: string; + /** + * Returns the response type. + * Can be set to change the response type. Values are: + * the empty string (default), + * "arraybuffer", + * "blob", + * "document", + * "json", and + * "text". + * When set: setting to "document" is ignored if current global object is not a Window object. + * When set: throws an "InvalidStateError" DOMException if state is loading or done. + * When set: throws an "InvalidAccessError" DOMException if the synchronous flag is set and current global object is a Window object. + */ + responseType: XMLHttpRequestResponseType; + readonly responseURL: string; + readonly status: number; + readonly statusText: string; + /** + * Can be set to a time in milliseconds. When set to a non-zero value will cause fetching to terminate after the given time has passed. When the time has passed, the + * request has not yet completed, and the synchronous flag is unset, a timeout event will then be dispatched, or a + * "TimeoutError" DOMException will be thrown otherwise (for the send() method). + * When set: throws an "InvalidAccessError" DOMException if the synchronous flag is set and current global object is a Window object. + */ + timeout: number; + /** + * Returns the associated XMLHttpRequestUpload object. It can be used to gather transmission information when data is + * transferred to a server. + */ + readonly upload: XMLHttpRequestUpload; + /** + * True when credentials are to be included in a cross-origin request. False when they are + * to be excluded in a cross-origin request and when cookies are to be ignored in its response. + * Initially false. + * When set: throws an "InvalidStateError" DOMException if state is not unsent or opened, or if the send() flag is set. + */ + withCredentials: boolean; + /** + * Cancels any network activity. + */ + abort(): void; + getAllResponseHeaders(): string; + getResponseHeader(name: string): string | null; + /** + * Sets the request method, request URL, and synchronous flag. + * Throws a "SyntaxError" DOMException if either method is not a + * valid HTTP method or url cannot be parsed. + * Throws a "SecurityError" DOMException if method is a + * case-insensitive match for `CONNECT`, `TRACE`, or `TRACK`. + * Throws an "InvalidAccessError" DOMException if async is false, current global object is a Window object, and the timeout attribute is not zero or the responseType attribute is not the empty string. + */ + open(method: string, url: string): void; + open(method: string, url: string, async: boolean, username?: string | null, password?: string | null): void; + /** + * Acts as if the `Content-Type` header value for response is mime. + * (It does not actually change the header though.) + * Throws an "InvalidStateError" DOMException if state is loading or done. + */ + overrideMimeType(mime: string): void; + /** + * Initiates the request. The optional argument provides the request body. The argument is ignored if request method is GET or HEAD. + * Throws an "InvalidStateError" DOMException if either state is not opened or the send() flag is set. + */ + send(body?: BodyInit | null): void; + /** + * Combines a header in author request headers. + * Throws an "InvalidStateError" DOMException if either state is not opened or the send() flag is set. + * Throws a "SyntaxError" DOMException if name is not a header name + * or if value is not a header value. + */ + setRequestHeader(name: string, value: string): void; + readonly DONE: number; + readonly HEADERS_RECEIVED: number; + readonly LOADING: number; + readonly OPENED: number; + readonly UNSENT: number; + addEventListener(type: K, listener: (this: XMLHttpRequest, ev: XMLHttpRequestEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: XMLHttpRequest, ev: XMLHttpRequestEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var XMLHttpRequest: { + prototype: XMLHttpRequest; + new(): XMLHttpRequest; + readonly DONE: number; + readonly HEADERS_RECEIVED: number; + readonly LOADING: number; + readonly OPENED: number; + readonly UNSENT: number; +}; + +interface XMLHttpRequestEventTargetEventMap { + "abort": ProgressEvent; + "error": ProgressEvent; + "load": ProgressEvent; + "loadend": ProgressEvent; + "loadstart": ProgressEvent; + "progress": ProgressEvent; + "timeout": ProgressEvent; +} + +interface XMLHttpRequestEventTarget extends EventTarget { + onabort: ((this: XMLHttpRequest, ev: ProgressEvent) => any) | null; + onerror: ((this: XMLHttpRequest, ev: ProgressEvent) => any) | null; + onload: ((this: XMLHttpRequest, ev: ProgressEvent) => any) | null; + onloadend: ((this: XMLHttpRequest, ev: ProgressEvent) => any) | null; + onloadstart: ((this: XMLHttpRequest, ev: ProgressEvent) => any) | null; + onprogress: ((this: XMLHttpRequest, ev: ProgressEvent) => any) | null; + ontimeout: ((this: XMLHttpRequest, ev: ProgressEvent) => any) | null; + addEventListener(type: K, listener: (this: XMLHttpRequestEventTarget, ev: XMLHttpRequestEventTargetEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: XMLHttpRequestEventTarget, ev: XMLHttpRequestEventTargetEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var XMLHttpRequestEventTarget: { + prototype: XMLHttpRequestEventTarget; + new(): XMLHttpRequestEventTarget; +}; + +interface XMLHttpRequestUpload extends XMLHttpRequestEventTarget { + addEventListener(type: K, listener: (this: XMLHttpRequestUpload, ev: XMLHttpRequestEventTargetEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: XMLHttpRequestUpload, ev: XMLHttpRequestEventTargetEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var XMLHttpRequestUpload: { + prototype: XMLHttpRequestUpload; + new(): XMLHttpRequestUpload; +}; + +declare type EventListenerOrEventListenerObject = EventListener | EventListenerObject; + +interface EventHandlerNonNull { + (event: Event): any; +} + +interface PerformanceObserverCallback { + (entries: PerformanceObserverEntryList, observer: PerformanceObserver): void; +} + +interface QueuingStrategySizeCallback { + (chunk: T): number; +} + +interface ReadableByteStreamControllerCallback { + (controller: ReadableByteStreamController): void | PromiseLike; +} + +interface ReadableStreamDefaultControllerCallback { + (controller: ReadableStreamDefaultController): void | PromiseLike; +} + +interface ReadableStreamErrorCallback { + (reason: any): void | PromiseLike; +} + +interface TransformStreamDefaultControllerCallback { + (controller: TransformStreamDefaultController): void | PromiseLike; +} + +interface TransformStreamDefaultControllerTransformCallback { + (chunk: I, controller: TransformStreamDefaultController): void | PromiseLike; +} + +interface WritableStreamDefaultControllerCloseCallback { + (): void | PromiseLike; +} + +interface WritableStreamDefaultControllerStartCallback { + (controller: WritableStreamDefaultController): void | PromiseLike; +} + +interface WritableStreamDefaultControllerWriteCallback { + (chunk: W, controller: WritableStreamDefaultController): void | PromiseLike; +} + +interface WritableStreamErrorCallback { + (reason: any): void | PromiseLike; +} + +declare var onmessage: ((this: DedicatedWorkerGlobalScope, ev: MessageEvent) => any) | null; +declare function close(): void; +declare function postMessage(message: any, transfer?: Transferable[]): void; +/** + * Dispatches a synthetic event event to target and returns true + * if either event's cancelable attribute value is false or its preventDefault() method was not invoked, and false otherwise. + */ +declare function dispatchEvent(event: Event): boolean; +declare var caches: CacheStorage; +declare var isSecureContext: boolean; +declare var location: WorkerLocation; +declare var onerror: ((this: DedicatedWorkerGlobalScope, ev: ErrorEvent) => any) | null; +declare var performance: Performance; +declare var self: WorkerGlobalScope; +declare function msWriteProfilerMark(profilerMarkName: string): void; +/** + * Dispatches a synthetic event event to target and returns true + * if either event's cancelable attribute value is false or its preventDefault() method was not invoked, and false otherwise. + */ +declare function dispatchEvent(event: Event): boolean; +declare var indexedDB: IDBFactory; +declare var msIndexedDB: IDBFactory; +declare var navigator: WorkerNavigator; +declare function importScripts(...urls: string[]): void; +declare function atob(encodedString: string): string; +declare function btoa(rawString: string): string; +declare var console: Console; +declare function fetch(input: RequestInfo, init?: RequestInit): Promise; +declare var caches: CacheStorage; +declare var crypto: Crypto; +declare var indexedDB: IDBFactory; +declare var origin: string; +declare var performance: Performance; +declare function atob(data: string): string; +declare function btoa(data: string): string; +declare function clearInterval(handle?: number): void; +declare function clearTimeout(handle?: number): void; +declare function createImageBitmap(image: ImageBitmapSource): Promise; +declare function createImageBitmap(image: ImageBitmapSource, sx: number, sy: number, sw: number, sh: number): Promise; +declare function fetch(input: RequestInfo, init?: RequestInit): Promise; +declare function queueMicrotask(callback: Function): void; +declare function setInterval(handler: TimerHandler, timeout?: number, ...arguments: any[]): number; +declare function setTimeout(handler: TimerHandler, timeout?: number, ...arguments: any[]): number; +declare function addEventListener(type: K, listener: (this: DedicatedWorkerGlobalScope, ev: DedicatedWorkerGlobalScopeEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; +declare function addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; +declare function removeEventListener(type: K, listener: (this: DedicatedWorkerGlobalScope, ev: DedicatedWorkerGlobalScopeEventMap[K]) => any, options?: boolean | EventListenerOptions): void; +declare function removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +type BlobPart = BufferSource | Blob | string; +type HeadersInit = Headers | string[][] | Record; +type BodyInit = Blob | BufferSource | FormData | URLSearchParams | ReadableStream | string; +type RequestInfo = Request | string; +type DOMHighResTimeStamp = number; +type CanvasImageSource = ImageBitmap; +type MessageEventSource = MessagePort | ServiceWorker; +type ImageBitmapSource = CanvasImageSource | Blob | ImageData; +type TimerHandler = string | Function; +type PerformanceEntryList = PerformanceEntry[]; +type PushMessageDataInit = BufferSource | string; +type VibratePattern = number | number[]; +type AlgorithmIdentifier = string | Algorithm; +type HashAlgorithmIdentifier = AlgorithmIdentifier; +type BigInteger = Uint8Array; +type NamedCurve = string; +type GLenum = number; +type GLboolean = boolean; +type GLbitfield = number; +type GLint = number; +type GLsizei = number; +type GLintptr = number; +type GLsizeiptr = number; +type GLuint = number; +type GLfloat = number; +type GLclampf = number; +type TexImageSource = ImageBitmap | ImageData; +type Float32List = Float32Array | GLfloat[]; +type Int32List = Int32Array | GLint[]; +type BufferSource = ArrayBufferView | ArrayBuffer; +type DOMTimeStamp = number; +type FormDataEntryValue = File | string; +type IDBValidKey = number | string | Date | BufferSource | IDBArrayKey; +type Transferable = ArrayBuffer | MessagePort | ImageBitmap; +type BinaryType = "blob" | "arraybuffer"; +type ClientTypes = "window" | "worker" | "sharedworker" | "all"; +type EndingType = "transparent" | "native"; +type IDBCursorDirection = "next" | "nextunique" | "prev" | "prevunique"; +type IDBRequestReadyState = "pending" | "done"; +type IDBTransactionMode = "readonly" | "readwrite" | "versionchange"; +type KeyFormat = "raw" | "spki" | "pkcs8" | "jwk"; +type KeyType = "public" | "private" | "secret"; +type KeyUsage = "encrypt" | "decrypt" | "sign" | "verify" | "deriveKey" | "deriveBits" | "wrapKey" | "unwrapKey"; +type NotificationDirection = "auto" | "ltr" | "rtl"; +type NotificationPermission = "default" | "denied" | "granted"; +type PushEncryptionKeyName = "p256dh" | "auth"; +type PushPermissionState = "denied" | "granted" | "prompt"; +type ReferrerPolicy = "" | "no-referrer" | "no-referrer-when-downgrade" | "origin-only" | "origin-when-cross-origin" | "unsafe-url"; +type RequestCache = "default" | "no-store" | "reload" | "no-cache" | "force-cache" | "only-if-cached"; +type RequestCredentials = "omit" | "same-origin" | "include"; +type RequestDestination = "" | "audio" | "audioworklet" | "document" | "embed" | "font" | "image" | "manifest" | "object" | "paintworklet" | "report" | "script" | "sharedworker" | "style" | "track" | "video" | "worker" | "xslt"; +type RequestMode = "navigate" | "same-origin" | "no-cors" | "cors"; +type RequestRedirect = "follow" | "error" | "manual"; +type ResponseType = "basic" | "cors" | "default" | "error" | "opaque" | "opaqueredirect"; +type ServiceWorkerState = "installing" | "installed" | "activating" | "activated" | "redundant"; +type ServiceWorkerUpdateViaCache = "imports" | "all" | "none"; +type VisibilityState = "hidden" | "visible" | "prerender"; +type WebGLPowerPreference = "default" | "low-power" | "high-performance"; +type WorkerType = "classic" | "module"; +type XMLHttpRequestResponseType = "" | "arraybuffer" | "blob" | "document" | "json" | "text"; diff --git a/node_modules/typescript/lib/lib.webworker.importscripts.d.ts b/node_modules/typescript/lib/lib.webworker.importscripts.d.ts new file mode 100644 index 0000000..c373ba8 --- /dev/null +++ b/node_modules/typescript/lib/lib.webworker.importscripts.d.ts @@ -0,0 +1,26 @@ +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + + + +/// + + + +///////////////////////////// +/// WorkerGlobalScope APIs +///////////////////////////// +// These are only available in a Web Worker +declare function importScripts(...urls: string[]): void; diff --git a/node_modules/typescript/lib/pl/diagnosticMessages.generated.json b/node_modules/typescript/lib/pl/diagnosticMessages.generated.json new file mode 100644 index 0000000..bfab76b --- /dev/null +++ b/node_modules/typescript/lib/pl/diagnosticMessages.generated.json @@ -0,0 +1,1101 @@ +{ + "A_0_modifier_cannot_be_used_with_an_import_declaration_1079": "Modyfikatora „{0}” nie można używać z deklaracją importu.", + "A_0_modifier_cannot_be_used_with_an_interface_declaration_1045": "Modyfikatora „{0}” nie można używać z deklaracją interfejsu.", + "A_0_parameter_must_be_the_first_parameter_2680": "Parametr „{0}” musi być pierwszym parametrem.", + "A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature_2463": "Parametr wzorca wiązania nie może być opcjonalny w sygnaturze implementacji.", + "A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement_1105": "Instrukcji „break” można użyć tylko w ramach otaczającej instrukcji iteracji lub switch.", + "A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement_1116": "Instrukcja „break” może wykonać skok tylko do etykiety otaczającej instrukcji.", + "A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments_2500": "Klasa może zawierać implementację tylko identyfikatora/nazwy kwalifikowanej z opcjonalnymi argumentami typu.", + "A_class_declaration_without_the_default_modifier_must_have_a_name_1211": "Deklaracja klasy bez modyfikatora „default” musi mieć nazwę.", + "A_class_may_only_extend_another_class_2311": "Klasa może rozszerzać tylko inną klasę.", + "A_class_may_only_implement_another_class_or_interface_2422": "Klasa może zawierać implementację tylko innej klasy lub innego interfejsu.", + "A_class_member_cannot_have_the_0_keyword_1248": "Składowa klasy nie może zawierać słowa kluczowego „{0}”.", + "A_comma_expression_is_not_allowed_in_a_computed_property_name_1171": "Wyrażenie przecinkowe nie jest dozwolone w obliczonej nazwie właściwości.", + "A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type_2467": "Obliczona nazwa właściwości nie może odwoływać się do parametru typu z zawierającego go typu.", + "A_computed_property_name_in_a_class_property_declaration_must_refer_to_an_expression_whose_type_is_a_1166": "Nazwa właściwości obliczanej w deklaracji właściwości klasy musi odwoływać się do wyrażenia, którego typem jest literał lub „unique symbol”.", + "A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_ty_1168": "Nazwa właściwości obliczanej w przeciążeniu metody musi odwoływać się do wyrażenia, którego typem jest literał lub „unique symbol”.", + "A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type__1170": "Nazwa właściwości obliczanej w typie literału musi odwoływać się do wyrażenia, którego typem jest literał lub „unique symbol”.", + "A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_t_1165": "Nazwa właściwości obliczanej w otaczającym kontekście musi odwoływać się do wyrażenia, którego typem jest literał lub „unique symbol”.", + "A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_1169": "Nazwa właściwości obliczanej w interfejsie musi odwoływać się do wyrażenia, którego typem jest literał lub „unique symbol”.", + "A_computed_property_name_must_be_of_type_string_number_symbol_or_any_2464": "Obliczona nazwa właściwości musi być typu „string”, „number”, „symbol” lub „any”.", + "A_computed_property_name_of_the_form_0_must_be_of_type_symbol_2471": "Obliczona nazwa właściwości w postaci „{0}” musi być typu „symbol”.", + "A_const_enum_member_can_only_be_accessed_using_a_string_literal_2476": "Dostęp do składowej wyliczenia ze specyfikatorem const można uzyskać tylko za pomocą literału ciągu.", + "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_1254": "Inicjator „const” w otaczającym kontekście musi być ciągiem lub literałem numerycznym.", + "A_constructor_cannot_contain_a_super_call_when_its_class_extends_null_17005": "Konstruktor nie może zawierać wywołania „super”, gdy jego klasa rozszerza wartość „null”.", + "A_constructor_cannot_have_a_this_parameter_2681": "Konstruktor nie może zawierać parametru „this”.", + "A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement_1104": "Instrukcji „continue” można użyć tylko w otaczającej instrukcji iteracji.", + "A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement_1115": "Instrukcja „continue” może wykonać skok tylko do etykiety otaczającej instrukcji iteracji.", + "A_declare_modifier_cannot_be_used_in_an_already_ambient_context_1038": "Nie można użyć modyfikatora „declare” w otaczającym kontekście.", + "A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file_1046": "Wymagany jest modyfikator „declare” dla deklaracji najwyższego poziomu w pliku d.ts.", + "A_decorator_can_only_decorate_a_method_implementation_not_an_overload_1249": "Dekorator może dekorować jedynie implementację metody, a nie przeciążenie.", + "A_default_clause_cannot_appear_more_than_once_in_a_switch_statement_1113": "Klauzula „default” nie może występować więcej niż raz w instrukcji „switch”.", + "A_default_export_can_only_be_used_in_an_ECMAScript_style_module_1319": "Eksport domyślny może być używany tylko w module w stylu języka ECMAScript.", + "A_definite_assignment_assertion_is_not_permitted_in_this_context_1255": "Asercja określonego przydziału „!” nie jest dozwolona w tym kontekście.", + "A_destructuring_declaration_must_have_an_initializer_1182": "Deklaracja usuwająca strukturę musi mieć inicjator.", + "A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declarat_2712": "Wywołanie dynamicznego importowania w wersji ES5/ES3 wymaga konstruktora „Promise”. Upewnij się, że masz deklarację dla konstruktora „Promise”, lub uwzględnij wartość „ES2015” w opcji „--lib”.", + "A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES20_2711": "Wywołanie dynamicznego importowania zwraca element „Promise”. Upewnij się, że masz deklarację elementu „Promise” lub uwzględnij wartość „ES2015” w opcji „--lib”.", + "A_file_cannot_have_a_reference_to_itself_1006": "Plik nie może przywoływać samego siebie.", + "A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator_1103": "Instrukcja „for-await-of” jest dozwolona jedynie w funkcji asynchronicznej lub generatorze asynchronicznym.", + "A_function_returning_never_cannot_have_a_reachable_end_point_2534": "Funkcja zwracająca wartość „never” nie może mieć osiągalnego punktu końcowego.", + "A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void_2679": "Funkcja wywoływana ze słowem kluczowym „new” nie może mieć typu „this” o wartości „void”.", + "A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value_2355": "Funkcja, której deklarowany typ jest inny niż „void” lub „any”, musi zwracać wartość.", + "A_generator_cannot_have_a_void_type_annotation_2505": "Generator nie może mieć adnotacji typu „void”.", + "A_get_accessor_cannot_have_parameters_1054": "Metoda dostępu „get” nie może mieć parametrów.", + "A_get_accessor_must_return_a_value_2378": "Metoda dostępu „get” musi zwracać wartość.", + "A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_memb_2651": "Inicjator składowej w deklaracji wyliczenia nie może przywoływać składowych zadeklarowanych po nim, w tym składowych zdefiniowanych w innych wyliczeniach.", + "A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any_2545": "Klasa mixin musi mieć konstruktor z pojedynczym parametrem rest o typie „any[]”.", + "A_module_cannot_have_multiple_default_exports_2528": "Moduł nie może mieć wielu eksportów domyślnych.", + "A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merg_2433": "Deklaracja przestrzeni nazw nie może znajdować się w innym pliku niż klasa lub funkcja, z którą ją scalono.", + "A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged_2434": "Deklaracja przestrzeni nazw nie może występować przed klasą lub funkcją, z którą ją scalono.", + "A_namespace_declaration_is_only_allowed_in_a_namespace_or_module_1235": "Deklaracja przestrzeni nazw jest dozwolona tylko w przestrzeni nazw lub module.", + "A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_7038": "Nie można wywołać lub skonstruować importu stylu przestrzeni nazw. Spowoduje to błąd w czasie wykonania.", + "A_non_dry_build_would_build_project_0_6357": "Kompilacja inna niż -dry spowodowałaby skompilowanie projektu „{0}”", + "A_non_dry_build_would_delete_the_following_files_Colon_0_6356": "Kompilacja inna niż -dry spowodowałaby usunięcie następujących plików: {0}", + "A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation_2371": "Inicjator parametru jest dozwolony tylko w implementacji funkcji lub konstruktora.", + "A_parameter_property_cannot_be_declared_using_a_rest_parameter_1317": "Właściwości parametru nie można zadeklarować za pomocą parametru rest.", + "A_parameter_property_is_only_allowed_in_a_constructor_implementation_2369": "Właściwość parametru jest dozwolona tylko w implementacji konstruktora.", + "A_parameter_property_may_not_be_declared_using_a_binding_pattern_1187": "Właściwości parametru nie można zadeklarować za pomocą wzorca wiązania.", + "A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not_18001": "Ścieżka w opcji „extends” musi być względna lub bezwzględna, lecz element „{0}” nie spełnia tego wymagania.", + "A_promise_must_have_a_then_method_1059": "Obietnica musi mieć metodę „then”.", + "A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly_1331": "Właściwość klasy, której typem jest „unique symbol”, musi być określona zarówno jako „static”, jak i „readonly”.", + "A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly_1330": "Właściwość klasy, której typem jest literał lub „unique symbol”, musi być określona zarówno jako „static”, jak i „readonly”.", + "A_required_parameter_cannot_follow_an_optional_parameter_1016": "Wymagany parametr nie może występować po opcjonalnym parametrze.", + "A_rest_element_cannot_contain_a_binding_pattern_2501": "Element rest nie może zawierać wzorca wiązania.", + "A_rest_element_cannot_have_a_property_name_2566": "Element rest nie może mieć nazwy właściwości.", + "A_rest_element_cannot_have_an_initializer_1186": "Element rest nie może mieć inicjatora.", + "A_rest_element_must_be_last_in_a_destructuring_pattern_2462": "Element rest musi być ostatni we wzorcu usuwającym strukturę.", + "A_rest_parameter_cannot_be_optional_1047": "Parametr rest nie może być opcjonalny.", + "A_rest_parameter_cannot_have_an_initializer_1048": "Parametr rest nie może mieć inicjatora.", + "A_rest_parameter_must_be_last_in_a_parameter_list_1014": "Parametr rest musi występować na końcu listy parametrów.", + "A_rest_parameter_must_be_of_an_array_type_2370": "Parametr rest musi być typu tablicowego.", + "A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma_1013": "Parametr rest ani wzorzec wiązania nie może mieć końcowego przecinka.", + "A_return_statement_can_only_be_used_within_a_function_body_1108": "Instrukcji „return” można użyć tylko w treści funkcji.", + "A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl_6167": "Seria wpisów, które ponownie mapują importowane dane na lokalizacje wyszukiwania względne wobec adresu „baseUrl”.", + "A_set_accessor_cannot_have_a_return_type_annotation_1095": "Metoda dostępu „set” nie może mieć adnotacji zwracanego typu.", + "A_set_accessor_cannot_have_an_optional_parameter_1051": "Metoda dostępu „set” nie może mieć parametru opcjonalnego.", + "A_set_accessor_cannot_have_rest_parameter_1053": "Metoda dostępu „set” nie może mieć parametru rest.", + "A_set_accessor_must_have_exactly_one_parameter_1049": "Metoda dostępu „set” musi mieć dokładnie jeden parametr.", + "A_set_accessor_parameter_cannot_have_an_initializer_1052": "Parametr metody dostępu „set” nie może mieć inicjatora.", + "A_signature_with_an_implementation_cannot_use_a_string_literal_type_2381": "Sygnatura z implementacją nie może używać typu literału ciągu.", + "A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_proper_2376": "Wywołanie „super” musi być pierwszą instrukcją konstruktora, jeśli klasa zawiera zainicjowane właściwości lub ma właściwości parametrów.", + "A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard_2518": "Ochrona typu oparta na elemencie „this” nie jest zgodna z ochroną typu opartą na parametrze.", + "A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface_2526": "Typ „this” jest dostępny tylko w niestatycznej składowej klasy lub interfejsu.", + "A_tsconfig_json_file_is_already_defined_at_Colon_0_5054": "Plik „tsconfig.json” jest już zdefiniowany w: „{0}”.", + "A_tuple_type_element_list_cannot_be_empty_1122": "Lista elementów typu krotki nie może być pusta.", + "A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Con_17007": "Wyrażenie asercji typu jest niedozwolone po lewej stronie wyrażenia potęgowania. Zastanów się nad zamknięciem wyrażenia w nawiasach.", + "A_type_literal_property_cannot_have_an_initializer_1247": "Właściwość literału typu nie może mieć inicjatora.", + "A_type_predicate_cannot_reference_a_rest_parameter_1229": "Predykat typów nie może zawierać odwołania do parametru rest.", + "A_type_predicate_cannot_reference_element_0_in_a_binding_pattern_1230": "Predykat typów nie może zawierać odwołania do elementu „{0}” we wzorcu wiązania.", + "A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods_1228": "Predykat typów jest dozwolony tylko w położeniu zwracanego typu dla funkcji i metod.", + "A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type_2677": "Musi być możliwe przypisanie typu predykatu typów do typu jego parametru.", + "A_variable_whose_type_is_a_unique_symbol_type_must_be_const_1332": "Zmienna, której typem „unique symbol”, musi być określona jako „const”.", + "A_yield_expression_is_only_allowed_in_a_generator_body_1163": "Wyrażenie „yield” jest dozwolone tylko w treści generatora.", + "Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression_2513": "Nie można uzyskać dostępu do metody abstrakcyjnej „{0}” w klasie „{1}” za pomocą wyrażenia super.", + "Abstract_methods_can_only_appear_within_an_abstract_class_1244": "Metody abstrakcyjne mogą występować tylko w klasie abstrakcyjnej.", + "Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor_2715": "Właściwość abstrakcyjna „{0}” w klasie „{1}” jest niedostępna w konstruktorze.", + "Accessibility_modifier_already_seen_1028": "Napotkano już modyfikator dostępności.", + "Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher_1056": "Metody dostępu są dostępne tylko wtedy, gdy jest używany język ECMAScript 5 lub nowszy.", + "Accessors_must_both_be_abstract_or_non_abstract_2676": "Obie metody dostępu muszą być abstrakcyjne lub nieabstrakcyjne.", + "Add_0_to_existing_import_declaration_from_1_90015": "Dodaj element „{0}” do istniejącej deklaracji importu z elementu „{1}”", + "Add_0_to_unresolved_variable_90008": "Dodaj „{0}.” do nierozpoznanej zmiennej", + "Add_all_missing_async_modifiers_95041": "Dodaj wszystkie brakujące modyfikatory „async”", + "Add_all_missing_members_95022": "Dodaj wszystkie brakujące elementy członkowskie", + "Add_all_missing_super_calls_95039": "Dodaj wszystkie brakujące wywołania typu super", + "Add_async_modifier_to_containing_function_90029": "Dodaj modyfikator asynchroniczny do funkcji zawierającej", + "Add_braces_to_arrow_function_95059": "Dodaj nawiasy klamrowe do funkcji strzałki", + "Add_definite_assignment_assertion_to_property_0_95020": "Dodaj asercję określonego przypisania do właściwości „{0}”", + "Add_definite_assignment_assertions_to_all_uninitialized_properties_95028": "Dodaj asercję określonego przypisania do wszystkich niezainicjowanych właściwości", + "Add_index_signature_for_property_0_90017": "Dodaj sygnaturę indeksu dla właściwości „{0}”", + "Add_initializer_to_property_0_95019": "Dodaj inicjator do właściwości „{0}”", + "Add_initializers_to_all_uninitialized_properties_95027": "Dodaj inicjatory do wszystkich niezainicjowanych właściwości", + "Add_missing_super_call_90001": "Dodaj brakujące wywołanie „super()”", + "Add_missing_typeof_95052": "Dodaj brakujący element „typeof”", + "Add_or_remove_braces_in_an_arrow_function_95058": "Dodaj lub usuń nawiasy klamrowe w funkcji strzałki", + "Add_qualifier_to_all_unresolved_variables_matching_a_member_name_95037": "Dodaj kwalifikator do wszystkich nierozpoznanych zmiennych pasujących do nazwy składowej", + "Add_to_all_uncalled_decorators_95044": "Dodaj element „()” do wszystkich niewywoływanych dekoratorów", + "Add_ts_ignore_to_all_error_messages_95042": "Dodaj element „@ts-ignore” do wszystkich komunikatów o błędach", + "Add_undefined_type_to_all_uninitialized_properties_95029": "Dodaj typ nieokreślony do wszystkich niezainicjowanych właściwości", + "Add_undefined_type_to_property_0_95018": "Dodaj typ „undefined” do właściwości „{0}”", + "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068": "Dodanie pliku tsconfig.json pomoże w organizowaniu projektów, które zawierają pliki TypeScript i JavaScript. Dowiedz się więcej: https://aka.ms/tsconfig.", + "Additional_Checks_6176": "Dodatkowe kontrole", + "Advanced_Options_6178": "Opcje zaawansowane", + "All_declarations_of_0_must_have_identical_modifiers_2687": "Wszystkie deklaracje elementu „{0}” muszą mieć identyczne modyfikatory.", + "All_declarations_of_0_must_have_identical_type_parameters_2428": "Wszystkie deklaracje „{0}” muszą mieć identyczne parametry typu.", + "All_declarations_of_an_abstract_method_must_be_consecutive_2516": "Wszystkie deklaracje metody abstrakcyjnej muszą występować obok siebie.", + "All_destructured_elements_are_unused_6198": "Wszystkie elementy, których strukturę usunięto, są nieużywane.", + "All_imports_in_import_declaration_are_unused_6192": "Wszystkie importy w deklaracji importu są nieużywane.", + "All_variables_are_unused_6199": "Wszystkie zmienne są nieużywane.", + "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011": "Zezwalaj na domyślne importy z modułów bez domyślnego eksportu. To nie wpływa na emitowanie kodu, a tylko na sprawdzanie typów.", + "Allow_javascript_files_to_be_compiled_6102": "Zezwalaj na kompilowanie plików JavaScript.", + "Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided_1209": "Otaczające wyliczenia ze specyfikacją const nie są dozwolone w przypadku podania flagi „--isolatedModules”.", + "Ambient_module_declaration_cannot_specify_relative_module_name_2436": "Deklaracja otaczającego modułu nie może określać względnej nazwy modułu.", + "Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces_2435": "Moduły otoczenia nie mogą być zagnieżdżone w innych modułach ani przestrzeniach nazw.", + "An_AMD_module_cannot_have_multiple_name_assignments_2458": "Moduł AMD nie może mieć wielu przypisań nazw.", + "An_abstract_accessor_cannot_have_an_implementation_1318": "Abstrakcyjna metoda dostępu nie może mieć implementacji.", + "An_accessor_cannot_be_declared_in_an_ambient_context_1086": "Metoda dostępu nie może być zadeklarowana w otaczającym kontekście.", + "An_accessor_cannot_have_type_parameters_1094": "Metoda dostępu nie może mieć parametrów typu.", + "An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file_1234": "Deklaracja otaczającego modułu jest dozwolona tylko na najwyższym poziomie pliku.", + "An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type_2356": "Arytmetyczny operand musi być typu „any”, „number” lub typu wyliczeniowego.", + "An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_de_2705": "Asynchroniczna funkcja lub metoda w wersji ES5/ES3 wymaga konstruktora „Promise”. Upewnij się, że masz deklarację dla konstruktora „Promise”, lub uwzględnij wartość „ES2015” w opcji „--lib”.", + "An_async_function_or_method_must_have_a_valid_awaitable_return_type_1057": "Funkcja lub metoda asynchroniczna musi mieć prawidłowy oczekujący zwracany typ.", + "An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_in_2697": "Metoda lub funkcja asynchroniczna musi zwrócić element „Promise”. Upewnij się, że masz deklarację elementu „Promise” lub uwzględnij wartość „ES2015” w opcji „--lib”.", + "An_async_iterator_must_have_a_next_method_2519": "Iterator asynchroniczny musi mieć metodę „next()”.", + "An_element_access_expression_should_take_an_argument_1011": "Wyrażenie dostępu do elementu powinno przyjmować argument.", + "An_enum_member_cannot_have_a_numeric_name_2452": "Składowa wyliczenia nie może mieć nazwy liczbowej.", + "An_export_assignment_can_only_be_used_in_a_module_1231": "Przypisanie eksportu może być używane tylko w module.", + "An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements_2309": "Nie można użyć przypisania eksportu w module z innymi eksportowanymi elementami.", + "An_export_assignment_cannot_be_used_in_a_namespace_1063": "Nie można użyć przypisania eksportu w przestrzeni nazw.", + "An_export_assignment_cannot_have_modifiers_1120": "Przypisanie eksportu nie może mieć modyfikatorów.", + "An_export_declaration_can_only_be_used_in_a_module_1233": "Deklaracja eksportu może być używana tylko w module.", + "An_export_declaration_cannot_have_modifiers_1193": "Deklaracja eksportu nie może mieć modyfikatorów.", + "An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive_1198": "Rozszerzona wartość znaku ucieczki Unicode musi należeć do zakresu od 0x0 do 0x10FFFF (włącznie).", + "An_implementation_cannot_be_declared_in_ambient_contexts_1183": "Implementacja nie może być zadeklarowana w otaczających kontekstach.", + "An_import_declaration_can_only_be_used_in_a_namespace_or_module_1232": "Deklaracja importu może być używana tylko w przestrzeni nazw lub module.", + "An_import_declaration_cannot_have_modifiers_1191": "Deklaracja importu nie może mieć modyfikatorów.", + "An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead_2691": "Ścieżka importu nie może kończyć się rozszerzeniem „{0}”. Rozważ zaimportowanie „{1}”.", + "An_index_expression_argument_must_be_of_type_string_number_symbol_or_any_2342": "Argument wyrażenia indeksu musi być typu „string”, „number”, „symbol” lub „any”.", + "An_index_signature_cannot_have_a_rest_parameter_1017": "Sygnatura indeksu nie może mieć parametru rest.", + "An_index_signature_must_have_a_type_annotation_1021": "Sygnatura indeksu musi mieć adnotację typu.", + "An_index_signature_must_have_exactly_one_parameter_1096": "Sygnatura indeksu musi mieć dokładnie jeden parametr.", + "An_index_signature_parameter_cannot_have_a_question_mark_1019": "Parametr sygnatury indeksu nie może zawierać znaku zapytania.", + "An_index_signature_parameter_cannot_have_an_accessibility_modifier_1018": "Parametr sygnatury indeksu nie może mieć modyfikatora dostępności.", + "An_index_signature_parameter_cannot_have_an_initializer_1020": "Parametr sygnatury indeksu nie może mieć inicjatora.", + "An_index_signature_parameter_must_have_a_type_annotation_1022": "Parametr sygnatury indeksu musi mieć adnotację typu.", + "An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead_1336": "Typ parametru sygnatury indeksu nie może być aliasem typu. Rozważ zastosowanie następującego zapisu: „[{0}: {1}]: {2}”.", + "An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead_1337": "Typ parametru sygnatury indeksu nie może być typem unii. Rozważ użycie zamiast niego mapowanego typu obiektu.", + "An_index_signature_parameter_type_must_be_string_or_number_1023": "Parametr sygnatury indeksu musi być typu „string” lub „number”.", + "An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments_2499": "Interfejs może rozszerzać tylko identyfikator/nazwę kwalifikowaną z opcjonalnymi argumentami typu.", + "An_interface_may_only_extend_a_class_or_another_interface_2312": "Interfejs może rozszerzać tylko klasę lub inny interfejs.", + "An_interface_property_cannot_have_an_initializer_1246": "Właściwość interfejsu nie może mieć inicjatora.", + "An_iterator_must_have_a_next_method_2489": "Iterator musi zawierać metodę „next()”.", + "An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name_1118": "Literał obiektu nie może mieć wielu metod dostępu pobierania/ustawiania o takiej samej nazwie.", + "An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode_1117": "Literał obiektu nie może mieć wielu właściwości o takiej samej nazwie w trybie z ograniczeniami.", + "An_object_literal_cannot_have_property_and_accessor_with_the_same_name_1119": "Literał obiektu nie może mieć właściwości i metody dostępu o takiej samej nazwie.", + "An_object_member_cannot_be_declared_optional_1162": "Składowa obiektu nie może być zadeklarowana jako opcjonalna.", + "An_overload_signature_cannot_be_declared_as_a_generator_1222": "Sygnatura przeciążenia nie może być zadeklarowana jako generator.", + "An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_ex_17006": "Wyrażenie jednoargumentowe z operatorem „{0}” jest niedozwolone po lewej stronie wyrażenia potęgowania. Zastanów się nad zamknięciem wyrażenia w nawiasach.", + "Annotate_everything_with_types_from_JSDoc_95043": "Adnotuj wszystko przy użyciu typów JSDoc", + "Annotate_with_type_from_JSDoc_95009": "Dodaj adnotację z typem z danych JSDoc", + "Annotate_with_types_from_JSDoc_95010": "Dodaj adnotację z typami z danych JSDoc", + "Argument_expression_expected_1135": "Oczekiwano wyrażenia argumentu.", + "Argument_for_0_option_must_be_Colon_1_6046": "Argumentem opcji „{0}” musi być: {1}.", + "Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_2345": "Nie można przypisać argumentu typu „{0}” do parametru typu „{1}”.", + "Array_element_destructuring_pattern_expected_1181": "Oczekiwano wzorca usuwającego strukturę elementu tablicy.", + "Asterisk_Slash_expected_1010": "Oczekiwano znaków „*/”.", + "Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_2669": "Rozszerzenia zakresu globalnego mogą być zagnieżdżane bezpośrednio jedynie w modułach zewnętrznych lub deklaracjach modułów otoczenia.", + "Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambien_2670": "Rozszerzenia zakresu globalnego muszą mieć modyfikator „declare”, chyba że znajdują się w już otaczającym kontekście.", + "Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using__6140": "Automatyczne odnajdowanie operacji wpisywania zostało włączone w projekcie „{0}”. Trwa uruchamianie dodatkowego przejścia rozwiązania dla modułu „{1}” przy użyciu lokalizacji pamięci podręcznej „{2}”.", + "Base_class_expressions_cannot_reference_class_type_parameters_2562": "Wyrażenia klasy bazowej nie mogą odwoływać się do parametrów typu klasy.", + "Base_constructor_return_type_0_is_not_a_class_or_interface_type_2509": "Zwracany typ konstruktora bazowego „{0}” nie jest typem klasy ani interfejsu.", + "Base_constructors_must_all_have_the_same_return_type_2510": "Wszystkie konstruktory podstawowe muszą mieć ten sam zwracany typ.", + "Base_directory_to_resolve_non_absolute_module_names_6083": "Katalog podstawowy do rozpoznawania innych niż bezwzględne nazw modułów.", + "Basic_Options_6172": "Opcje podstawowe", + "Binary_digit_expected_1177": "Oczekiwano bitu.", + "Binding_element_0_implicitly_has_an_1_type_7031": "Dla elementu powiązania „{0}” niejawnie określono typ „{1}”.", + "Block_scoped_variable_0_used_before_its_declaration_2448": "Zmienna „{0}” o zakresie bloku została użyta przed jej deklaracją.", + "Build_all_projects_including_those_that_appear_to_be_up_to_date_6368": "Kompiluj wszystkie projekty, łącznie z tymi, które wydają się być aktualne", + "Build_one_or_more_projects_and_their_dependencies_if_out_of_date_6364": "Kompiluj co najmniej jeden projekt i jego zależności, jeśli są nieaktualne", + "Building_project_0_6358": "Trwa kompilowanie projektu „{0}”...", + "Call_decorator_expression_90028": "Wywołaj wyrażenie dekoratora", + "Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7020": "Dla sygnatury wywołania bez adnotacji zwracanego typu niejawnie określono zwracany typ „any”.", + "Call_target_does_not_contain_any_signatures_2346": "Cel wywołania nie zawiera żadnych podpisów.", + "Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_p_2713": "Nie można uzyskać dostępu do elementu „{0}.{1}”, ponieważ element „{0}” jest typem, ale nie przestrzenią nazw. Czy chcesz pobrać typ właściwości „{1}” w lokalizacji „{0}” za pomocą elementu „{0}[„{1}”]”?", + "Cannot_assign_a_0_constructor_type_to_a_1_constructor_type_2672": "Nie można przypisać typu konstruktora „{0}” do typu konstruktora „{1}”.", + "Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type_2517": "Nie można przypisać abstrakcyjnego typu konstruktora do nieabstrakcyjnego typu konstruktora.", + "Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property_2540": "Nie można przydzielić do elementu „{0}”, ponieważ jest to stała lub właściwość tylko do odczytu.", + "Cannot_assign_to_0_because_it_is_not_a_variable_2539": "Nie można przydzielić do elementu „{0}”, ponieważ nie jest to zmienna.", + "Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity_2671": "Nie można rozszerzyć modułu „{0}”, ponieważ rozpoznawany jest obiekt inny niż moduł.", + "Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity_2649": "Nie można rozszerzyć modułu „{0}” za pośrednictwem operacji eksportu wartości, ponieważ jest on rozpoznawany jako jednostka inna niż moduł.", + "Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system_6131": "Nie można skompilować modułów za pomocą opcji „{0}”, chyba że flaga „--module” ma wartość „amd” lub „system”.", + "Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided_1208": "Nie można skompilować przestrzeni nazw, jeśli podano flagę „--isolatedModules”.", + "Cannot_create_an_instance_of_an_abstract_class_2511": "Nie można utworzyć wystąpienia klasy abstrakcyjnej.", + "Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module_2661": "Nie można wyeksportować elementu „{0}”. Z modułu można eksportować jedynie lokalne deklaracje.", + "Cannot_extend_a_class_0_Class_constructor_is_marked_as_private_2675": "Nie można rozszerzyć klasy „{0}”. Konstruktor klasy jest oznaczony jako prywatny.", + "Cannot_extend_an_interface_0_Did_you_mean_implements_2689": "Nie można rozszerzyć interfejsu „{0}”. Czy chodziło Ci o „implements”?", + "Cannot_find_a_tsconfig_json_file_at_the_specified_directory_Colon_0_5057": "Nie można znaleźć pliku tsconfig.json w określonym katalogu: „{0}”.", + "Cannot_find_global_type_0_2318": "Nie można odnaleźć typu globalnego „{0}”.", + "Cannot_find_global_value_0_2468": "Nie można odnaleźć wartości globalnej „{0}”.", + "Cannot_find_lib_definition_for_0_2726": "Nie można znaleźć definicji biblioteki dla elementu „{0}”.", + "Cannot_find_lib_definition_for_0_Did_you_mean_1_2727": "Nie można znaleźć definicji biblioteki dla elementu „{0}”. Czy chodziło Ci o element „{1}”?", + "Cannot_find_module_0_2307": "Nie można odnaleźć modułu „{0}”.", + "Cannot_find_name_0_2304": "Nie można odnaleźć nazwy „{0}”.", + "Cannot_find_name_0_Did_you_mean_1_2552": "Nie można znaleźć nazwy „{0}”. Czy chodziło Ci o „{1}”?", + "Cannot_find_name_0_Did_you_mean_the_instance_member_this_0_2663": "Nie można znaleźć nazwy „{0}”. Czy chodziło o składową wystąpienia „this.{0}”?", + "Cannot_find_name_0_Did_you_mean_the_static_member_1_0_2662": "Nie można znaleźć nazwy „{0}”. Czy chodziło o statyczną składową „{1}.{0}”?", + "Cannot_find_namespace_0_2503": "Nie można odnaleźć przestrzeni nazw „{0}”.", + "Cannot_find_parameter_0_1225": "Nie można odnaleźć parametru „{0}”.", + "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009": "Nie można odnaleźć wspólnej ścieżki podkatalogu dla plików wejściowych.", + "Cannot_find_type_definition_file_for_0_2688": "Nie można znaleźć pliku definicji typu dla elementu „{0}”.", + "Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1_6137": "Nie można zaimportować plików deklaracji typu. Rozważ zaimportowanie „{0}” zamiast „{1}”.", + "Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1_2481": "Nie można zainicjować zmiennej „{0}” z zakresu zewnętrznego w tym samym zakresie co deklaracja „{1}” należąca do zakresu bloku.", + "Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatur_2349": "Nie można wywołać wyrażenia, w którego typie nie ma sygnatury wywołania. Typ „{0}” nie ma zgodnych sygnatur wywołań.", + "Cannot_invoke_an_object_which_is_possibly_null_2721": "Nie można wywołać obiektu, który ma prawdopodobnie wartość „null”.", + "Cannot_invoke_an_object_which_is_possibly_null_or_undefined_2723": "Nie można wywołać obiektu, który ma prawdopodobnie wartość „null” lub „undefined”.", + "Cannot_invoke_an_object_which_is_possibly_undefined_2722": "Nie można wywołać obiektu, który ma prawdopodobnie wartość „undefined”.", + "Cannot_prepend_project_0_because_it_does_not_have_outFile_set_6308": "Nie można poprzedzić projektu „{0}”, ponieważ nie ma on ustawionej właściwości „outFile”", + "Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205": "Nie można ponownie wyeksportować typu, jeśli podano flagę „--isolatedModules”", + "Cannot_read_file_0_Colon_1_5012": "Nie można odczytać pliku „{0}”: {1}.", + "Cannot_redeclare_block_scoped_variable_0_2451": "Nie można ponownie zadeklarować zmiennej „{0}” o zakresie bloku.", + "Cannot_redeclare_exported_variable_0_2323": "Nie można zadeklarować ponownie wyeksportowanej zmiennej „{0}”.", + "Cannot_redeclare_identifier_0_in_catch_clause_2492": "Nie można ponownie zadeklarować identyfikatora „{0}” w klauzuli catch.", + "Cannot_use_JSX_unless_the_jsx_flag_is_provided_17004": "Nie można użyć kodu JSX, jeśli nie podano flagi „--jsx”.", + "Cannot_use_imports_exports_or_module_augmentations_when_module_is_none_1148": "Nie można używać importów, eksportów lub rozszerzeń modułów, jeśli flaga „--module” ma wartość „none”.", + "Cannot_use_namespace_0_as_a_type_2709": "Nie można używać przestrzeni nazw „{0}” jako typu.", + "Cannot_use_namespace_0_as_a_value_2708": "Nie można używać przestrzeni nazw „{0}” jako wartości.", + "Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature_2351": "Nie można użyć elementu „new” z wyrażeniem, którego typ nie ma sygnatury wywołania lub konstrukcji.", + "Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files_5056": "Nie można zapisać pliku „{0}”, ponieważ zostałby nadpisany przez wiele plików wejściowych.", + "Cannot_write_file_0_because_it_would_overwrite_input_file_5055": "Nie można zapisać pliku „{0}”, ponieważ nadpisałby plik wejściowy.", + "Catch_clause_variable_cannot_have_a_type_annotation_1196": "Zmienna klauzuli catch nie może mieć adnotacji typu.", + "Catch_clause_variable_cannot_have_an_initializer_1197": "Zmienna klauzuli catch nie może mieć inicjatora.", + "Change_0_to_1_90014": "Zmień element „{0}” na „{1}”", + "Change_all_extended_interfaces_to_implements_95038": "Zmień wszystkie rozszerzone interfejsy na elementy „implements”", + "Change_all_jsdoc_style_types_to_TypeScript_95030": "Zmień wszystkie typy w stylu JSDoc na TypeScript", + "Change_all_jsdoc_style_types_to_TypeScript_and_add_undefined_to_nullable_types_95031": "Zmień wszystkie typy w stylu JSDoc na TypeScript (i dodaj element „| undefined” do typów dopuszczających wartość null)", + "Change_extends_to_implements_90003": "Zmień atrybut „extends” na „implements”", + "Change_spelling_to_0_90022": "Zmień pisownię na „{0}”", + "Checking_if_0_is_the_longest_matching_prefix_for_1_2_6104": "Sprawdzanie, czy „{0}” to najdłuższy zgodny prefiks dla „{1}” — „{2}”.", + "Circular_definition_of_import_alias_0_2303": "Definicja cykliczna aliasu importu „{0}”.", + "Circularity_detected_while_resolving_configuration_Colon_0_18000": "Wykryto cykliczność podczas rozpoznawania konfiguracji: {0}", + "Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_functi_2426": "Klasa „{0}” definiuje metodę dostępu do składowej wystąpienia „{1}”, ale rozszerzona klasa „{2}” definiuje ją jako funkcję składową wystąpienia.", + "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_access_2423": "Klasa „{0}” definiuje funkcję składową wystąpienia „{1}”, ale rozszerzona klasa „{2}” definiuje ją jako metodę dostępu do składowej wystąpienia.", + "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_proper_2424": "Klasa „{0}” definiuje funkcję składową wystąpienia „{1}”, ale rozszerzona klasa „{2}” definiuje ją jako właściwość składowej wystąpienia.", + "Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_functi_2425": "Klasa „{0}” definiuje właściwość składowej wystąpienia „{1}”, ale rozszerzona klasa „{2}” definiuje ją jako funkcję składową wystąpienia.", + "Class_0_incorrectly_extends_base_class_1_2415": "Klasa „{0}” niepoprawnie rozszerza klasę bazową „{1}”.", + "Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclas_2720": "Klasa „{0}” niepoprawnie implementuje klasę „{1}”. Czy chodziło o rozszerzenie „{1}” i odziedziczenie jego elementów członkowskich jako podklasy?", + "Class_0_incorrectly_implements_interface_1_2420": "Klasa „{0}” zawiera niepoprawną implementację interfejsu „{1}”.", + "Class_0_used_before_its_declaration_2449": "Klasa „{0}” została użyta przed zadeklarowaniem.", + "Class_declarations_cannot_have_more_than_one_augments_or_extends_tag_8025": "Deklaracje klas nie mogą mieć więcej niż jeden tag „@augments” lub „@extends”.", + "Class_name_cannot_be_0_2414": "Klasa nie może mieć nazwy „{0}”.", + "Class_name_cannot_be_Object_when_targeting_ES5_with_module_0_2725": "Nazwą klasy nie może być słowo „Object”, gdy docelowym językiem jest ES5 z modułem {0}.", + "Class_static_side_0_incorrectly_extends_base_class_static_side_1_2417": "Strona statyczna klasy „{0}” niepoprawnie rozszerza stronę statyczną klasy bazowej „{1}”.", + "Classes_can_only_extend_a_single_class_1174": "Klasy mogą rozszerzać tylko pojedynczą klasę.", + "Classes_containing_abstract_methods_must_be_marked_abstract_2514": "Klasy zawierające metody abstrakcyjne muszą być oznaczone jako abstrakcyjne.", + "Command_line_Options_6171": "Opcje wiersza polecenia", + "Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json_6020": "Skompiluj projekt z uwzględnieniem ścieżki jego pliku konfiguracji lub folderu z plikiem „tsconfig.json”.", + "Compiler_option_0_expects_an_argument_6044": "Opcja kompilatora „{0}” oczekuje argumentu.", + "Compiler_option_0_requires_a_value_of_type_1_5024": "Opcja kompilatora „{0}” wymaga wartości typu {1}.", + "Composite_projects_may_not_disable_declaration_emit_6304": "Projekty kompozytowe nie mogą wyłączyć emitowania deklaracji.", + "Computed_property_names_are_not_allowed_in_enums_1164": "Obliczone nazwy właściwości nie są dozwolone w wyliczeniach.", + "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553": "Obliczone wartości nie są dozwolone w wyliczeniu ze składowymi o wartości ciągu.", + "Concatenate_and_emit_output_to_single_file_6001": "Połącz i wyemituj dane wyjściowe do pojedynczego pliku.", + "Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_librar_4090": "Znaleziono sprzeczne definicje dla „{0}” w „{1}” i „{2}”. Rozważ zainstalowanie konkretnej wersji tej biblioteki, aby rozwiązać problem.", + "Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7013": "Dla sygnatury konstrukcji bez adnotacji zwracanego typu niejawnie określono zwracany typ „any”.", + "Constructor_implementation_is_missing_2390": "Brak implementacji konstruktora.", + "Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration_2673": "Konstruktor klasy „{0}” jest prywatny i dostępny tylko w ramach deklaracji klasy.", + "Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration_2674": "Konstruktor klasy „{0}” jest chroniony i dostępny tylko w ramach deklaracji klasy.", + "Constructors_for_derived_classes_must_contain_a_super_call_2377": "Konstruktory klas pochodnych muszą zawierać wywołanie „super”.", + "Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126": "Nie podano pliku zawierającego i nie można określić katalogu głównego. Pomijanie wyszukiwania w folderze „node_modules”.", + "Convert_0_to_mapped_object_type_95055": "Konwertuj element „{0}” na zamapowany typ obiektu", + "Convert_all_constructor_functions_to_classes_95045": "Przekonwertuj wszystkie funkcje konstruktora na klasy", + "Convert_all_require_to_import_95048": "Konwertuj wszystkie wywołania „require” na wywołania „import”", + "Convert_all_to_default_imports_95035": "Przekonwertuj wszystko na domyślne importowanie", + "Convert_function_0_to_class_95002": "Konwertuj funkcję „{0}” na klasę", + "Convert_function_to_an_ES2015_class_95001": "Konwertuj funkcję na klasę ES2015", + "Convert_named_imports_to_namespace_import_95057": "Konwertuj importy nazwane na import przestrzeni nazw", + "Convert_namespace_import_to_named_imports_95056": "Konwertuj import przestrzeni nazw na importy nazwane", + "Convert_require_to_import_95047": "Konwertuj wywołanie „require” na wywołanie „import”", + "Convert_to_ES6_module_95017": "Konwertuj na moduł ES6", + "Convert_to_default_import_95013": "Konwertuj na import domyślny", + "Corrupted_locale_file_0_6051": "Uszkodzony plik ustawień regionalnych {0}.", + "Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type_7016": "Nie można znaleźć pliku deklaracji dla modułu „{0}”. Element „{1}” ma niejawnie typ „any”.", + "Could_not_write_file_0_Colon_1_5033": "Nie można zapisać pliku „{0}”: {1}.", + "DIRECTORY_6038": "KATALOG", + "Declaration_expected_1146": "Oczekiwano deklaracji.", + "Declaration_name_conflicts_with_built_in_global_identifier_0_2397": "Nazwa deklaracji powoduje konflikt z wbudowanym identyfikatorem globalnym „{0}”.", + "Declaration_or_statement_expected_1128": "Oczekiwano deklaracji lub instrukcji.", + "Declare_method_0_90023": "Zadeklaruj metodę „{0}”", + "Declare_property_0_90016": "Zadeklaruj właściwość „{0}”", + "Declare_static_method_0_90024": "Zadeklaruj metodę statyczną „{0}”", + "Declare_static_property_0_90027": "Zadeklaruj właściwość statyczną „{0}”", + "Decorators_are_not_valid_here_1206": "Elementy Decorator nie są tutaj prawidłowe.", + "Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name_1207": "Nie można stosować elementów Decorator do wielu metod dostępu pobierania/ustawiania o takiej samej nazwie.", + "Default_export_of_the_module_has_or_is_using_private_name_0_4082": "Domyślny eksport modułu ma nazwę prywatną „{0}” lub używa tej nazwy.", + "Delete_all_unused_declarations_95024": "Usuń wszystkie nieużywane deklaracje", + "Delete_the_outputs_of_all_projects_6365": "Usuń dane wyjściowe wszystkich projektów", + "Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react__6084": "[Przestarzałe] Użyj w zastępstwie opcji „--jsxFactory”. Określ obiekt wywoływany dla elementu createElement przy określaniu jako celu emisji JSX „react”", + "Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file_6170": "[Przestarzałe] Użyj w zastępstwie opcji „--outFile”. Połącz dane wyjściowe i wyemituj jako jeden plik", + "Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files_6160": "[Przestarzałe] Użyj w zastępstwie opcji „--skipLibCheck”. Pomiń sprawdzanie typów domyślnych plików deklaracji biblioteki.", + "Digit_expected_1124": "Oczekiwano cyfry.", + "Directory_0_does_not_exist_skipping_all_lookups_in_it_6148": "Katalog „{0}” nie istnieje. Operacje wyszukiwania w nim zostaną pominięte.", + "Disable_checking_for_this_file_90018": "Wyłącz sprawdzanie dla tego pliku", + "Disable_size_limitations_on_JavaScript_projects_6162": "Wyłącz ograniczenia rozmiarów dla projektów JavaScript.", + "Disable_strict_checking_of_generic_signatures_in_function_types_6185": "Wyłącz dokładne sprawdzanie sygnatur ogólnych w typach funkcji.", + "Disallow_inconsistently_cased_references_to_the_same_file_6078": "Nie zezwalaj na przywoływanie tego samego pliku za pomocą nazw różniących się wielkością liter.", + "Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files_6159": "Nie dodawaj odwołań z trzema ukośnikami ani zaimportowanych modułów do listy skompilowanych plików.", + "Do_not_emit_comments_to_output_6009": "Nie emituj komentarzy do danych wyjściowych.", + "Do_not_emit_declarations_for_code_that_has_an_internal_annotation_6056": "Nie emituj deklaracji dla kodu z adnotacją „@internal”.", + "Do_not_emit_outputs_6010": "Nie emituj danych wyjściowych.", + "Do_not_emit_outputs_if_any_errors_were_reported_6008": "Nie emituj danych wyjściowych w przypadku zgłoszenia błędów.", + "Do_not_emit_use_strict_directives_in_module_output_6112": "Nie emituj dyrektyw „use strict” w danych wyjściowych modułu.", + "Do_not_erase_const_enum_declarations_in_generated_code_6007": "Nie wymazuj deklaracji wyliczeń ze specyfikacją const w wygenerowanym kodzie.", + "Do_not_generate_custom_helper_functions_like_extends_in_compiled_output_6157": "Nie generuj w skompilowanych danych wyjściowych niestandardowych funkcji pomocy, takich jak „__extends”.", + "Do_not_include_the_default_library_file_lib_d_ts_6158": "Nie uwzględniaj domyślnego pliku biblioteki (lib.d.ts).", + "Do_not_report_errors_on_unreachable_code_6077": "Nie zgłaszaj błędów dla nieosiągalnego kodu.", + "Do_not_report_errors_on_unused_labels_6074": "Nie zgłaszaj błędów dla nieużywanych etykiet.", + "Do_not_resolve_the_real_path_of_symlinks_6013": "Nie rozpoznawaj rzeczywistej ścieżki linków symbolicznych.", + "Do_not_truncate_error_messages_6165": "Nie obcinaj komunikatów o błędach.", + "Duplicate_declaration_0_2718": "Zduplikowana deklaracja „{0}”.", + "Duplicate_function_implementation_2393": "Zduplikowana implementacja funkcji.", + "Duplicate_identifier_0_2300": "Zduplikowany identyfikator „{0}”.", + "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_2441": "Zduplikowany identyfikator „{0}”. Kompilator rezerwuje nazwę „{1}” w zakresie najwyższego poziomu modułu.", + "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_func_2529": "Zduplikowany identyfikator „{0}”. Kompilator rezerwuje nazwę „{1}” w zakresie najwyższego poziomu modułu zawierającego funkcje asynchroniczne.", + "Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions_2520": "Zduplikowany identyfikator „{0}”. Kompilator używa deklaracji „{1}” do obsługi funkcji asynchronicznych.", + "Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters_2396": "Zduplikowany identyfikator „arguments”. Kompilator używa ciągu „arguments” do zainicjowania parametrów rest.", + "Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_me_2543": "Powielony identyfikator „_newTarget”. Kompilator używa deklaracji zmiennej „_newTarget” do przechwytywania odwołania do metawłaściwości „new.target”.", + "Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference_2401": "Zduplikowany identyfikator „_super”. Kompilator używa ciągu „_super” do przechwycenia odwołania do klasy bazowej.", + "Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference_2399": "Zduplikowany identyfikator „_this”. Kompilator używa deklaracji zmiennej „_this” do przechwycenia odwołania do elementu „this”.", + "Duplicate_label_0_1114": "Zduplikowana etykieta „{0}”.", + "Duplicate_number_index_signature_2375": "Zduplikowana sygnatura indeksu liczbowego.", + "Duplicate_string_index_signature_2374": "Zduplikowana sygnatura indeksu ciągu.", + "Dynamic_import_cannot_have_type_arguments_1326": "Dynamiczne importowanie nie może mieć argumentów typu", + "Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext_1323": "Import dynamiczny jest obsługiwany tylko wtedy, gdy flaga „--module” to „commonjs” lub „esNext”.", + "Dynamic_import_must_have_one_specifier_as_an_argument_1324": "Dynamiczne importowanie musi mieć jeden specyfikator jako argument.", + "Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036": "Specyfikator dynamicznego importowania musi być typu „string”, ale określono typ „{0}”.", + "Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015": "Element niejawnie przyjmuje typ „any”, ponieważ wyrażenie indeksu ma typ inny niż „number”.", + "Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature_7017": "Element ma niejawnie typ „any”, ponieważ typ „{0}” nie ma sygnatury indeksu.", + "Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files_6164": "Emituj znacznik kolejności bajtów UTF-8 na początku plików wyjściowych.", + "Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file_6151": "Emituj pojedynczy plik z mapami źródeł zamiast oddzielnego pliku.", + "Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap__6152": "Emituj źródło razem z mapami źródłowymi w pojedynczym pliku; wymaga ustawienia opcji „--inlineSourceMap” lub „--sourceMap”.", + "Enable_all_strict_type_checking_options_6180": "Włącz wszystkie opcje ścisłego sprawdzania typów.", + "Enable_project_compilation_6302": "Włącz kompilację projektu", + "Enable_strict_checking_of_function_types_6186": "Włącz dokładne sprawdzanie typów funkcji.", + "Enable_strict_checking_of_property_initialization_in_classes_6187": "Włącz dokładne sprawdzanie inicjowania właściwości w klasach.", + "Enable_strict_null_checks_6113": "Włącz dokładne sprawdzanie wartości null.", + "Enable_tracing_of_the_name_resolution_process_6085": "Włącz śledzenie procesu rozpoznawania nazw.", + "Enable_verbose_logging_6366": "Włącz pełne rejestrowanie", + "Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for__7037": "Umożliwia współdziałanie emitowania między modułami CommonJS i ES przez tworzenie obiektów przestrzeni nazw dla wszystkich importów. Implikuje użycie ustawienia „allowSyntheticDefaultImports”.", + "Enables_experimental_support_for_ES7_async_functions_6068": "Umożliwia obsługę eksperymentalną funkcji asynchronicznych języka ES7.", + "Enables_experimental_support_for_ES7_decorators_6065": "Umożliwia obsługę eksperymentalną elementów Decorator języka ES7.", + "Enables_experimental_support_for_emitting_type_metadata_for_decorators_6066": "Umożliwia obsługę eksperymentalną emitowania metadanych typów elementów Decorator.", + "Enum_0_used_before_its_declaration_2450": "Wyliczenie „{0}” zostało użyte przed zadeklarowaniem.", + "Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations_2567": "Deklaracje wyliczeń można scalać tylko z przestrzeniami nazw lub innymi deklaracjami wyliczeń.", + "Enum_declarations_must_all_be_const_or_non_const_2473": "Wszystkie deklaracje wyliczeń muszą być elementami const lub żadna nie może być elementem const.", + "Enum_member_expected_1132": "Oczekiwano składowych wyliczenia.", + "Enum_member_must_have_initializer_1061": "Składowa wyliczenia musi mieć inicjator.", + "Enum_name_cannot_be_0_2431": "Wyliczenie nie może mieć nazwy „{0}”.", + "Enum_type_0_has_members_with_initializers_that_are_not_literals_2535": "Typ wyliczenia „{0}” ma składowe z inicjatorami niebędącymi literałami.", + "Examples_Colon_0_6026": "Przykłady: {0}", + "Excessive_stack_depth_comparing_types_0_and_1_2321": "Nadmierna głębokość stosu podczas porównywania typów „{0}” i „{1}”.", + "Expected_0_1_type_arguments_provide_these_with_an_extends_tag_8027": "Oczekiwano argumentów typu {0}-{1}; podaj je z tagiem „@extends”.", + "Expected_0_arguments_but_got_1_2554": "Oczekiwane argumenty: {0}, uzyskano: {1}.", + "Expected_0_arguments_but_got_1_or_more_2556": "Oczekiwano {0} argumentów, ale otrzymano {1} lub więcej.", + "Expected_0_type_arguments_but_got_1_2558": "Oczekiwane argumenty typu: {0}, uzyskano: {1}.", + "Expected_0_type_arguments_provide_these_with_an_extends_tag_8026": "Oczekiwano argumentów typu {0}; podaj je z tagiem „@extends”.", + "Expected_at_least_0_arguments_but_got_1_2555": "Oczekiwane argumenty: co najmniej {0}, uzyskano: {1}.", + "Expected_at_least_0_arguments_but_got_1_or_more_2557": "Oczekiwano co najmniej {0} argumentów, ale otrzymano {1} lub więcej.", + "Expected_corresponding_JSX_closing_tag_for_0_17002": "Oczekiwano odpowiadającego tagu zamykającego kodu JSX dla elementu „{0}”.", + "Expected_corresponding_closing_tag_for_JSX_fragment_17015": "Oczekiwano odpowiedniego tagu zamykającego dla fragmentu kodu JSX.", + "Expected_type_of_0_field_in_package_json_to_be_string_got_1_6105": "Oczekiwany typ pola „{0}” w pliku „package.json” to „string”, a uzyskano typ „{1}”.", + "Experimental_Options_6177": "Opcje eksperymentalne", + "Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_t_1219": "Obsługa eksperymentalna dekoratorów to funkcja, która może ulec zmianie w nowszych wersjach. Ustaw opcję „experimentalDecorators”, aby usunąć to ostrzeżenie.", + "Explicitly_specified_module_resolution_kind_Colon_0_6087": "Jawnie określony rodzaj rozpoznawania modułów: „{0}”.", + "Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or__1203": "Nie można użyć przypisania eksportu, gdy są używane moduły języka ECMAScript. Zamiast tego rozważ użycie elementu „export default” lub innego formatu modułu.", + "Export_assignment_is_not_supported_when_module_flag_is_system_1218": "Przypisanie eksportu nie jest obsługiwane, gdy flaga „--module” ma postać „system”.", + "Export_declaration_conflicts_with_exported_declaration_of_0_2484": "Deklaracja eksportu powoduje konflikt z wyeksportowaną deklaracją „{0}”.", + "Export_declarations_are_not_permitted_in_a_namespace_1194": "Deklaracje eksportu są niedozwolone w przestrzeni nazw.", + "Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_2656": "Plik typów wyeksportowanych pakietów zewnętrznych „{0}” nie jest modułem. Skontaktuj się z autorem pakietu, aby zaktualizować definicję pakietu.", + "Exported_external_package_typings_file_cannot_contain_tripleslash_references_Please_contact_the_pack_2654": "Plik typów wyeksportowanych pakietów zewnętrznych nie może zawierać odwołań z potrójnym ukośnikiem. Skontaktuj się z autorem pakietu, aby zaktualizować definicję pakietu.", + "Exported_type_alias_0_has_or_is_using_private_name_1_4081": "Alias „{0}” wyeksportowanego typu ma nazwę prywatną „{1}” lub używa tej nazwy.", + "Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4023": "Wyeksportowana zmienna „{0}” ma nazwę „{1}” z modułu zewnętrznego {2} lub używa tej nazwy, ale nie można jej nazwać.", + "Exported_variable_0_has_or_is_using_name_1_from_private_module_2_4024": "Wyeksportowana zmienna „{0}” ma nazwę „{1}” z modułu prywatnego „{2}” lub używa tej nazwy.", + "Exported_variable_0_has_or_is_using_private_name_1_4025": "Wyeksportowana zmienna „{0}” ma nazwę prywatną „{1}” lub używa tej nazwy.", + "Exports_and_export_assignments_are_not_permitted_in_module_augmentations_2666": "Eksporty i przypisania eksportów nie są dozwolone w rozszerzeniach modułów.", + "Expression_expected_1109": "Oczekiwano wyrażenia.", + "Expression_or_comma_expected_1137": "Oczekiwano wyrażenia lub przecinka.", + "Expression_resolves_to_super_that_compiler_uses_to_capture_base_class_reference_2402": "Wynikiem rozpoznania wyrażenia jest element „_super” używany przez kompilator do przechwycenia odwołania do klasy bazowej.", + "Expression_resolves_to_variable_declaration_0_that_compiler_uses_to_support_async_functions_2521": "Wynikiem rozpoznania wyrażenia jest deklaracja zmiennej „{0}” używana przez kompilator do obsługi funkcji asynchronicznych.", + "Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta__2544": "Wynikiem rozpoznania wyrażenia jest deklaracja zmiennej „_newTarget” używana przez kompilator do przechwytywania odwołania do metawłaściwości „new.target”.", + "Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference_2400": "Wynikiem rozpoznania wyrażenia jest deklaracja zmiennej „_this” używana przez kompilator do przechwycenia odwołania do elementu „this”.", + "Extract_constant_95006": "Wyodrębnij stałą", + "Extract_function_95005": "Wyodrębnij funkcję", + "Extract_to_0_in_1_95004": "Wyodrębnij do {0} w {1}", + "Extract_to_0_in_1_scope_95008": "Wyodrębnij do {0} w zakresie {1}", + "Extract_to_0_in_enclosing_scope_95007": "Wyodrębnij do {0} w zakresie otaczającym", + "FILE_6035": "PLIK", + "FILE_OR_DIRECTORY_6040": "PLIK LUB KATALOG", + "Failed_to_parse_file_0_Colon_1_5014": "Nie można przeanalizować pliku „{0}”: {1}.", + "Fallthrough_case_in_switch_7029": "Przepuszczająca klauzula case w instrukcji switch.", + "File_0_does_not_exist_6096": "Plik „{0}” nie istnieje.", + "File_0_exist_use_it_as_a_name_resolution_result_6097": "Plik „{0}” istnieje — użyj go jako wyniku rozpoznawania nazw.", + "File_0_has_an_unsupported_extension_so_skipping_it_6081": "Plik „{0}” ma nieobsługiwane rozszerzenie, dlatego zostanie pominięty.", + "File_0_has_unsupported_extension_The_only_supported_extensions_are_1_6054": "Plik „{0}” ma nieobsługiwane rozszerzenie. Obsługiwane są tylko rozszerzenia {1}.", + "File_0_is_not_a_module_2306": "Plik „{0}” nie jest modułem.", + "File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern_6307": "Plik „{0}” nie znajduje się na liście plików projektu. Projekty muszą zawierać listę wszystkich plików lub używać wzorca „include”.", + "File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files_6059": "Plik „{0}” nie znajduje się w katalogu „rootDir” „{1}”. Katalog „rootDir” powinien zawierać wszystkie pliki źródłowe.", + "File_0_not_found_6053": "Nie można odnaleźć pliku '{0}'.", + "File_change_detected_Starting_incremental_compilation_6032": "Wykryto zmianę pliku. Trwa rozpoczynanie kompilacji przyrostowej...", + "File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module_80001": "Plik jest modułem CommonJS. Może zostać przekonwertowany na moduł ES6.", + "File_name_0_differs_from_already_included_file_name_1_only_in_casing_1149": "Nazwa pliku „{0}” różni się od już dołączonej nazwy pliku „{1}” tylko wielkością liter.", + "File_name_0_has_a_1_extension_stripping_it_6132": "Nazwa pliku „{0}” ma rozszerzenie „{1}” — zostanie ono usunięte.", + "File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildca_5065": "Specyfikacja pliku nie może zawierać katalogu nadrzędnego („..”) wyświetlanego po symbolu wieloznacznym katalogu rekursywnego („**”): „{0}”.", + "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010": "Specyfikacja pliku nie może kończyć się cyklicznym symbolem wieloznacznym katalogu („**”): „{0}”.", + "Fix_all_detected_spelling_errors_95026": "Napraw wszystkie wykryte błędy pisowni", + "Found_0_errors_Watching_for_file_changes_6194": "Znalezione błędy: {0}. Obserwowanie zmian plików.", + "Found_1_error_Watching_for_file_changes_6193": "Znaleziono 1 błąd. Obserwowanie zmian plików.", + "Found_package_json_at_0_6099": "Znaleziono plik „package.json” w lokalizacji „{0}”.", + "Found_package_json_at_0_Package_ID_is_1_6190": "Znaleziono plik „package.json” w lokalizacji „{0}”. Identyfikator pakietu to „{1}”.", + "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_1250": "Deklaracje funkcji nie są dozwolone wewnątrz bloków w trybie z ograniczeniami, jeśli elementem docelowym jest „ES3” lub „ES5”.", + "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_d_1251": "Deklaracje funkcji nie są dozwolone wewnątrz bloków w trybie z ograniczeniami, jeśli elementem docelowym jest „ES3” lub „ES5”. Definicje klas automatycznie używają trybu z ograniczeniami.", + "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_1252": "Deklaracje funkcji nie są dozwolone wewnątrz bloków w trybie z ograniczeniami, jeśli elementem docelowym jest „ES3” lub „ES5”. Moduły automatycznie używają trybu z ograniczeniami.", + "Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type_7011": "Dla wyrażenia funkcji bez adnotacji zwracanego typu jest niejawnie określony zwracany typ „{0}”.", + "Function_implementation_is_missing_or_not_immediately_following_the_declaration_2391": "Brak implementacji funkcji lub nie występuje ona bezpośrednio po deklaracji.", + "Function_implementation_name_must_be_0_2389": "Implementacja funkcji musi mieć nazwę „{0}”.", + "Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_ref_7024": "Dla funkcji niejawnie określono zwracany typ „any”, ponieważ nie zawiera ona adnotacji zwracanego typu i jest przywoływana bezpośrednio lub pośrednio w jednym z jej zwracanych wyrażeń.", + "Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined_2366": "Funkcja nie zawiera końcowej instrukcji „return”, a zwracany typ nie obejmuje wartości „undefined”.", + "Function_overload_must_be_static_2387": "Przeciążenie funkcji musi być statyczne.", + "Function_overload_must_not_be_static_2388": "Przeciążenie funkcji nie może być statyczne.", + "Generate_get_and_set_accessors_95046": "Generuj metody dostępu „get” i „set”.", + "Generates_a_sourcemap_for_each_corresponding_d_ts_file_6000": "Generuje mapę źródła dla każdego odpowiadającego pliku „.d.ts”.", + "Generates_corresponding_d_ts_file_6002": "Generuje odpowiadający plik „d.ts”.", + "Generates_corresponding_map_file_6043": "Generuje odpowiadający plik „map”.", + "Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_typ_7025": "Dla generatora niejawnie określono typ „{0}”, ponieważ nie przekazuje on żadnych wartości. Rozważ podanie zwracanego typu.", + "Generators_are_not_allowed_in_an_ambient_context_1221": "Generatory nie są dozwolone w otaczającym kontekście.", + "Generators_are_only_available_when_targeting_ECMAScript_2015_or_higher_1220": "Generatory są dostępne tylko wtedy, gdy jest używany język ECMAScript 2015 lub nowszy.", + "Generic_type_0_requires_1_type_argument_s_2314": "Typ ogólny „{0}” wymaga następującej liczby argumentów typu: {1}.", + "Generic_type_0_requires_between_1_and_2_type_arguments_2707": "Typ ogólny „{0}” wymaga od {1} do {2} argumentów typu.", + "Generic_type_instantiation_is_excessively_deep_and_possibly_infinite_2550": "Tworzenie wystąpienia typu ogólnego jest nadmiernie szczegółowe i prawdopodobnie nieskończone.", + "Getter_and_setter_accessors_do_not_agree_in_visibility_2379": "Widoczności metod dostępu pobierającej i ustawiającej są niezgodne.", + "Global_module_exports_may_only_appear_at_top_level_1316": "Globalne eksporty modułu mogą występować tylko na najwyższym poziomie.", + "Global_module_exports_may_only_appear_in_declaration_files_1315": "Globalne eksporty modułu mogą występować tylko w plikach deklaracji.", + "Global_module_exports_may_only_appear_in_module_files_1314": "Globalne eksporty modułu mogą występować tylko w plikach modułów.", + "Global_type_0_must_be_a_class_or_interface_type_2316": "Typ globalny „{0}” musi być typem klasy lub interfejsu.", + "Global_type_0_must_have_1_type_parameter_s_2317": "Typ globalny „{0}” musi mieć następującą liczbę parametrów typu: {1}.", + "Hexadecimal_digit_expected_1125": "Oczekiwano cyfry szesnastkowej.", + "Identifier_expected_0_is_a_reserved_word_in_strict_mode_1212": "Oczekiwano identyfikatora. „{0}” jest wyrazem zastrzeżonym w trybie z ograniczeniami.", + "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_stric_1213": "Oczekiwano identyfikatora. „{0}” jest wyrazem zastrzeżonym w trybie z ograniczeniami. Definicje klas są określane automatycznie w trybie z ograniczeniami.", + "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode_1214": "Oczekiwano identyfikatora. Element „{0}” jest wyrazem zastrzeżonym w trybie z ograniczeniami. Moduły są określane automatycznie w trybie z ograniczeniami.", + "Identifier_expected_1003": "Oczekiwano identyfikatora.", + "Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules_1216": "Oczekiwano identyfikatora. Ciąg „__esModule” jest zastrzeżony jako eksportowany znacznik podczas transformowania modułów ECMAScript.", + "Ignore_this_error_message_90019": "Ignoruj ten komunikat o błędzie", + "Implement_all_inherited_abstract_classes_95040": "Zaimplementuj wszystkie dziedziczone klasy abstrakcyjne", + "Implement_all_unimplemented_interfaces_95032": "Zaimplementuj wszystkie niezaimplementowane interfejsy", + "Implement_inherited_abstract_class_90007": "Wdróż odziedziczoną klasę abstrakcyjną", + "Implement_interface_0_90006": "Implementuj interfejs „{0}”", + "Implements_clause_of_exported_class_0_has_or_is_using_private_name_1_4019": "Klauzula implements wyeksportowanej klasy „{0}” ma nazwę prywatną „{1}” lub używa tej nazwy.", + "Import_0_from_module_1_90013": "Importuj element „{0}” z modułu „{1}”", + "Import_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_import_Asterisk_as_1202": "Nie można użyć przypisania importu, gdy są używane moduły języka ECMAScript. Zamiast tego rozważ użycie elementu „import * as ns from \"mod\"”, „import {a} from \"mod\"” lub „import d from \"mod\"” albo innego formatu modułu.", + "Import_declaration_0_is_using_private_name_1_4000": "Deklaracja importu „{0}” używa nazwy prywatnej „{1}”.", + "Import_declaration_conflicts_with_local_declaration_of_0_2440": "Deklaracja importu powoduje konflikt z deklaracją lokalną „{0}”.", + "Import_declarations_in_a_namespace_cannot_reference_a_module_1147": "Deklaracje importu w przestrzeni nazw nie mogą odwoływać się do modułu.", + "Import_emit_helpers_from_tslib_6139": "Importuj pomocników emitowania z elementu „tslib”.", + "Import_may_be_converted_to_a_default_import_80003": "Import może zostać przekonwertowany na import domyślny.", + "Import_name_cannot_be_0_2438": "Import nie może mieć nazwy „{0}”.", + "Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relati_2439": "Deklaracja importu lub eksportu w deklaracji otaczającego modułu nie może przywoływać modułu za pomocą jego nazwy względnej.", + "Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_mod_2667": "Importy nie są dozwolone w rozszerzeniach modułów. Rozważ przeniesienie ich do obejmującego modułu zewnętrznego.", + "In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066": "W deklaracjach wyliczenia otoczenia inicjator składowej musi być wyrażeniem stałym.", + "In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enu_2432": "W przypadku wyliczenia z wieloma deklaracjami tylko jedna deklaracja może pominąć inicjator dla pierwszego elementu wyliczenia.", + "In_const_enum_declarations_member_initializer_must_be_constant_expression_2474": "W deklaracjach wyliczeń ze specyfikatorem „const” inicjator składowej musi być wyrażeniem stałym.", + "Include_modules_imported_with_json_extension_6197": "Uwzględnij moduły zaimportowane z rozszerzeniem „json”", + "Index_signature_in_type_0_only_permits_reading_2542": "Sygnatura indeksu w typie „{0}” zezwala tylko na odczytywanie.", + "Index_signature_is_missing_in_type_0_2329": "Brak sygnatury indeksu w typie „{0}”.", + "Index_signatures_are_incompatible_2330": "Sygnatury indeksów są niezgodne.", + "Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local_2395": "Wszystkie poszczególne deklaracje w scalonej deklaracji „{0}” muszą być wyeksportowane lub lokalne.", + "Infer_all_types_from_usage_95023": "Wywnioskuj wszystkie typy na podstawie użycia", + "Infer_parameter_types_from_usage_95012": "Wnioskuj typy parametrów na podstawie użycia", + "Infer_type_of_0_from_usage_95011": "Wnioskuj typ elementu „{0}” na podstawie użycia", + "Initialize_property_0_in_the_constructor_90020": "Zainicjuj właściwość „{0}” w konstruktorze", + "Initialize_static_property_0_90021": "Zainicjuj właściwość statyczną „{0}”", + "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301": "Inicjator zmiennej składowej wystąpienia „{0}” nie może przywoływać identyfikatora „{1}” zadeklarowanego w konstruktorze.", + "Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it_2373": "Inicjator parametru „{0}” nie może przywoływać identyfikatora „{1}” zadeklarowanego po nim.", + "Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value_2525": "Inicjator nie określa żadnej wartości dla tego elementu powiązania, a element powiązania nie ma wartości domyślnej.", + "Initializers_are_not_allowed_in_ambient_contexts_1039": "Inicjatory są niedozwolone w otaczających kontekstach.", + "Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file_6070": "Inicjuje projekt TypeScript i tworzy plik tsconfig.json.", + "Insert_command_line_options_and_files_from_a_file_6030": "Wstaw opcje wiersza polecenia i pliki z pliku.", + "Install_0_95014": "Zainstaluj składnik „{0}”", + "Install_all_missing_types_packages_95033": "Zainstaluj wszystkie brakujące pakiety typów", + "Interface_0_cannot_simultaneously_extend_types_1_and_2_2320": "Interfejs „{0}” nie może jednocześnie rozszerzać typów „{1}” i „{2}”.", + "Interface_0_incorrectly_extends_interface_1_2430": "Interfejs „{0}” niepoprawnie rozszerza interfejs „{1}”.", + "Interface_declaration_cannot_have_implements_clause_1176": "Deklaracja interfejsu nie może mieć klauzuli „implements”.", + "Interface_name_cannot_be_0_2427": "Interfejs nie może mieć nazwy „{0}”.", + "Invalid_character_1127": "Nieprawidłowy znak.", + "Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augm_2665": "Nieprawidłowa nazwa modułu w rozszerzeniu. Moduł „{0}” jest rozpoznawany jako moduł bez typu na poziomie „{1}”, którego nie można rozszerzyć.", + "Invalid_module_name_in_augmentation_module_0_cannot_be_found_2664": "Nieprawidłowa nazwa modułu w rozszerzeniu. Nie można znaleźć modułu „{0}”.", + "Invalid_reference_directive_syntax_1084": "Nieprawidłowa składnia dyrektywy „reference”.", + "Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode_1210": "Nieprawidłowe użycie elementu „{0}”. Definicje klas są określane automatycznie w trybie z ograniczeniami.", + "Invalid_use_of_0_Modules_are_automatically_in_strict_mode_1215": "Nieprawidłowe użycie elementu „{0}”. Moduły są określane automatycznie w trybie z ograniczeniami.", + "Invalid_use_of_0_in_strict_mode_1100": "Nieprawidłowe użycie elementu „{0}” w trybie z ograniczeniami.", + "Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name_5067": "Nieprawidłowa wartość elementu „jsxFactory”. „{0}” to nie jest prawidłowy identyfikator ani kwalifikowana nazwa.", + "Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier_5059": "Nieprawidłowa wartość opcji „--reactNamespace”. Element „{0}” nie jest prawidłowym identyfikatorem.", + "JSDoc_0_1_does_not_match_the_extends_2_clause_8023": "Element JSDoc „@{0} {1}” nie pasuje do klauzuli „extends {2}”.", + "JSDoc_0_is_not_attached_to_a_class_8022": "Element JSDoc „@{0}” nie został dołączony do klasy.", + "JSDoc_may_only_appear_in_the_last_parameter_of_a_signature_8028": "Element „...” JSDoc może występować tylko w ostatnim parametrze sygnatury.", + "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_8024": "Tag JSDoc „@param” tag ma nazwę „{0}”, ale nie ma parametru o tej nazwie.", + "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_h_8029": "Tag JSDoc „@param” ma nazwę „{0}”, ale nie istnieje parametr o tej nazwie. Byłby on zgodny z elementem „arguments”, gdyby miał typ tablicy.", + "JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags_8021": "Tag „@typedef” JSDoc powinien mieć adnotację typu lub powinien po nim następować tag „@property” lub „@member”.", + "JSDoc_types_can_only_be_used_inside_documentation_comments_8020": "Typy JSDoc mogą być używane wyłącznie w komentarzach dokumentacji.", + "JSDoc_types_may_be_moved_to_TypeScript_types_80004": "Typy JSDoc mogą być przenoszone do typów TypeScript.", + "JSX_attribute_expected_17003": "Oczekiwano atrybutu JSX.", + "JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000": "Atrybuty JSX muszą mieć przypisane wyrażenie, które nie jest puste.", + "JSX_element_0_has_no_corresponding_closing_tag_17008": "Element JSX „{0}” nie ma odpowiedniego tagu zamykającego.", + "JSX_element_attributes_type_0_may_not_be_a_union_type_2600": "Typ atrybutów elementu JSX „{0}” nie może być typem unii.", + "JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property_2607": "Klasa elementów JSX nie obsługuje atrybutów, ponieważ nie ma właściwości „{0}”.", + "JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists_7026": "Dla elementu JSX niejawnie określono typ „any”, ponieważ interfejs „JSX.{0}” nie istnieje.", + "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602": "Dla elementu JSX niejawnie określono typ „any”, ponieważ typ globalny „JSX.Element” nie istnieje.", + "JSX_element_type_0_does_not_have_any_construct_or_call_signatures_2604": "Typ elementu JSX „{0}” nie ma sygnatury konstrukcji ani wywołania.", + "JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements_2605": "Typ elementu JSX „{0}” nie jest funkcją konstruktora dla elementów JSX.", + "JSX_elements_cannot_have_multiple_attributes_with_the_same_name_17001": "Elementy JSX nie mogą mieć wielu atrybutów o tej samej nazwie.", + "JSX_expressions_must_have_one_parent_element_2657": "Wyrażenia JSX muszą mieć jeden element nadrzędny.", + "JSX_fragment_has_no_corresponding_closing_tag_17014": "Fragment kodu JSX nie ma odpowiedniego tagu zamykającego.", + "JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma_17017": "Fragment JSX nie jest obsługiwany podczas używania śródwierszowej dyrektywy pragma fabryki JSX", + "JSX_fragment_is_not_supported_when_using_jsxFactory_17016": "W przypadku korzystania z opcji --jsxFactory fragment kodu JSX nie jest obsługiwany", + "JSX_spread_child_must_be_an_array_type_2609": "Element podrzędny rozkładu JSX musi być typem tablicy.", + "Jump_target_cannot_cross_function_boundary_1107": "Cel skoku nie może przekraczać granicy funkcji.", + "KIND_6034": "RODZAJ", + "LOCATION_6037": "LOKALIZACJA", + "Language_service_is_disabled_9004": "Usługa języka jest wyłączona.", + "Left_side_of_comma_operator_is_unused_and_has_no_side_effects_2695": "Lewa strona operatora „przecinek” jest nieużywana i nie ma żadnych efektów ubocznych.", + "Line_break_not_permitted_here_1142": "Podział wiersza nie jest tutaj dozwolony.", + "Line_terminator_not_permitted_before_arrow_1200": "Terminator wiersza nie jest dozwolony przed strzałką.", + "List_of_folders_to_include_type_definitions_from_6161": "Lista folderów, z których mają być uwzględnione definicje typów.", + "List_of_language_service_plugins_6181": "Lista wtyczek usługi języka.", + "List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime_6168": "Lista folderów głównych, których połączona zawartość reprezentuje strukturę projektu w czasie wykonywania.", + "Loading_0_from_the_root_dir_1_candidate_location_2_6109": "Ładowanie elementu „{0}” z katalogu głównego „{1}”, lokalizacja kandydata: „{2}”.", + "Loading_module_0_from_node_modules_folder_target_file_type_1_6098": "Ładowanie modułu „{0}” z folderu „node_modules”, docelowy typ pliku: „{1}”.", + "Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1_6095": "Ładowanie modułu jako pliku/folderu, lokalizacja modułu kandydata: „{0}”, docelowy typ pliku: „{1}”.", + "Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1_6048": "Ustawienia regionalne muszą mieć postać lub -. Na przykład „{0}” lub „{1}”.", + "Longest_matching_prefix_for_0_is_1_6108": "Najdłuższy zgodny prefiks dla „{0}” to „{1}”.", + "Looking_up_in_node_modules_folder_initial_location_0_6125": "Wyszukiwanie w folderze „node_modules”, początkowa lokalizacja: „{0}”.", + "Make_all_super_calls_the_first_statement_in_their_constructor_95036": "Wszystkie wywołania „super()” powinny być pierwszą instrukcją w konstruktorze", + "Make_super_call_the_first_statement_in_the_constructor_90002": "Ustaw wywołanie „super()” jako pierwszą instrukcję w konstruktorze", + "Mapped_object_type_implicitly_has_an_any_template_type_7039": "Zmapowany typ obiektu niejawnie ma typ szablonu „any”.", + "Member_0_implicitly_has_an_1_type_7008": "Dla składowej „{0}” niejawnie określono typ „{1}”.", + "Merge_conflict_marker_encountered_1185": "Napotkano znacznik konfliktu scalania.", + "Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_d_2652": "Scalona deklaracja „{0}” nie może zawierać domyślnej deklaracji eksportu. Rozważ dodanie oddzielnej deklaracji „export default {0}” zamiast niej.", + "Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constru_17013": "Metawłaściwość „{0}” jest dozwolona tylko w treści deklaracji funkcji, wyrażeniu funkcji lub konstruktorze.", + "Method_0_cannot_have_an_implementation_because_it_is_marked_abstract_1245": "Metoda „{0}” nie może mieć implementacji, ponieważ jest oznaczona jako abstrakcyjna.", + "Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4101": "Metoda „{0}” wyeksportowanego interfejsu ma nazwę „{1}” z modułu prywatnego „{2}” lub używa tej nazwy.", + "Method_0_of_exported_interface_has_or_is_using_private_name_1_4102": "Metoda „{0}” wyeksportowanego interfejsu ma nazwę prywatną „{1}” lub używa tej nazwy.", + "Modifiers_cannot_appear_here_1184": "Modyfikatory nie mogą występować w tym miejscu.", + "Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_1340": "Moduł „{0}” nie odwołuje się do typu, ale jest tutaj używany jako typ.", + "Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here_1339": "Moduł „{0}” nie odwołuje się do wartości, ale jest tutaj używany jako wartość.", + "Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambig_2308": "Moduł {0} już wyeksportował składową o nazwie „{1}”. Zastanów się nad jawnym ponownym eksportem, aby rozstrzygnąć niejednoznaczność.", + "Module_0_has_no_default_export_1192": "Moduł „{0}” nie ma eksportu domyślnego.", + "Module_0_has_no_exported_member_1_2305": "Moduł „{0}” nie ma wyeksportowanej składowej „{1}”.", + "Module_0_has_no_exported_member_1_Did_you_mean_2_2724": "Moduł „{0}” nie ma wyeksportowanego elementu członkowskiego „{1}”. Czy chodziło o „{2}”?", + "Module_0_is_hidden_by_a_local_declaration_with_the_same_name_2437": "Moduł „{0}” został ukryty przez deklarację lokalną o takiej samej nazwie.", + "Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct_2497": "Wynikiem rozpoznania modułu „{0}” jest jednostka niebędąca modułem i nie można zaimportować tego modułu przy użyciu tej konstrukcji.", + "Module_0_uses_export_and_cannot_be_used_with_export_Asterisk_2498": "Moduł „{0}” używa elementu „export =” i nie może być używany z elementem „export *”.", + "Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified_6145": "Moduł „{0}” został rozpoznany jako otaczający moduł zadeklarowany w elemencie „{1}”, ponieważ nie zmodyfikowano tego pliku.", + "Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1_6144": "Moduł „{0}” został rozpoznany jako otaczający moduł zadeklarowany lokalnie w pliku „{1}”.", + "Module_0_was_resolved_to_1_but_jsx_is_not_set_6142": "Moduł „{0}” został rozpoznany jako „{1}”, ale nie jest ustawiona opcja „--jsx”.", + "Module_Resolution_Options_6174": "Opcje rozpoznawania modułu", + "Module_name_0_matched_pattern_1_6092": "Nazwa modułu: „{0}”, dopasowany wzorzec: „{1}”.", + "Module_name_0_was_not_resolved_6090": "======== Nazwa modułu „{0}” nie została rozpoznana. ========", + "Module_name_0_was_successfully_resolved_to_1_6089": "======== Nazwa modułu „{0}” została pomyślnie rozpoznana jako „{1}”. ========", + "Module_resolution_kind_is_not_specified_using_0_6088": "Rodzaj rozpoznawania modułów nie został podany. Zostanie użyty rodzaj „{0}”.", + "Module_resolution_using_rootDirs_has_failed_6111": "Nie można rozpoznać modułów przy użyciu opcji „rootDirs”.", + "Move_to_a_new_file_95049": "Przenieś do nowego pliku", + "Multiple_consecutive_numeric_separators_are_not_permitted_6189": "Kolejne następujące po sobie separatory liczbowe nie są dozwolone.", + "Multiple_constructor_implementations_are_not_allowed_2392": "Konstruktor nie może mieć wielu implementacji.", + "NEWLINE_6061": "NOWY WIERSZ", + "Named_property_0_of_types_1_and_2_are_not_identical_2319": "Nazwane właściwości „{0}” typów „{1}” i „{2}” nie są identyczne.", + "Namespace_0_has_no_exported_member_1_2694": "Przestrzeń nazw „{0}” nie ma wyeksportowanej składowej „{1}”.", + "No_base_constructor_has_the_specified_number_of_type_arguments_2508": "Żaden z konstruktorów podstawowych nie ma określonej liczby argumentów typu.", + "No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2_18003": "Nie można znaleźć danych wejściowych w pliku konfiguracji „{0}”. Określone ścieżki „include” to „{1}”, a „exclude” to „{2}”.", + "Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2_2515": "Klasa nieabstrakcyjna „{0}” nie implementuje odziedziczonej abstrakcyjnej składowej „{1}” z klasy „{2}”.", + "Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1_2653": "Wyrażenie klasy nieabstrakcyjnej nie implementuje odziedziczonej abstrakcyjnej składowej „{0}” z klasy „{1}”.", + "Not_all_code_paths_return_a_value_7030": "Nie wszystkie ścieżki kodu zwracają wartość.", + "Numeric_index_type_0_is_not_assignable_to_string_index_type_1_2413": "Nie można przypisać typu indeksu numerycznego „{0}” do typu indeksu ciągu „{1}”.", + "Numeric_separators_are_not_allowed_here_6188": "Separatory liczbowe nie są dozwolone w tym miejscu.", + "Object_is_of_type_unknown_2571": "Obiekt jest typu „nieznany”.", + "Object_is_possibly_null_2531": "Obiekt ma prawdopodobnie wartość „null”.", + "Object_is_possibly_null_or_undefined_2533": "Obiekt ma prawdopodobnie wartość „null” lub „undefined”.", + "Object_is_possibly_undefined_2532": "Obiekt ma prawdopodobnie wartość „undefined”.", + "Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1_2353": "Dla literału obiektu można określić tylko znane właściwości, a właściwość „{0}” nie istnieje w typie „{1}”.", + "Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_writ_2561": "Literał obiektu może określać wyłącznie znane właściwości, ale element „{0}” nie istnieje w typie „{1}”. Czy chodziło Ci o „{2}”?", + "Object_literal_s_property_0_implicitly_has_an_1_type_7018": "Dla właściwości „{0}” literału obiektu niejawnie określono typ „{1}”.", + "Octal_digit_expected_1178": "Oczekiwano cyfry ósemkowej.", + "Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0_8017": "Typy literałów ósemkowych muszą korzystać ze składni ES2015. Użyj składni „{0}”.", + "Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0_8018": "Literały ósemkowe są niedozwolone w inicjatorze składowych wyliczeń. Użyj składni „{0}”.", + "Octal_literals_are_not_allowed_in_strict_mode_1121": "Literały ósemkowe są niedozwolone w trybie z ograniczeniami.", + "Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0_1085": "Literały ósemkowe są niedostępne, jeśli językiem docelowym jest ECMAScript 5 lub nowszy. Użyj składni „{0}”.", + "Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement_1091": "W instrukcji „for...in” jest dozwolona tylko pojedyncza deklaracja zmiennej.", + "Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement_1188": "W instrukcji „for...of” jest dozwolona tylko pojedyncza deklaracja zmiennej.", + "Only_a_void_function_can_be_called_with_the_new_keyword_2350": "Tylko funkcja typu void może być wywoływana za pomocą słowa kluczowego „new”.", + "Only_ambient_modules_can_use_quoted_names_1035": "Tylko otaczające moduły mogą używać nazw w cudzysłowie.", + "Only_amd_and_system_modules_are_supported_alongside_0_6082": "Tylko moduły „amd” i „system” są obsługiwane razem z parametrem --{0}.", + "Only_emit_d_ts_declaration_files_6014": "Emituj tylko pliki deklaracji „d.ts”.", + "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002": "Klauzula „extends” klasy obsługuje obecnie tylko identyfikatory/nazwy kwalifikowane z opcjonalnymi argumentami typu.", + "Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword_2340": "Tylko publiczne i chronione metody klasy bazowej są dostępne przy użyciu słowa kluczowego „super”.", + "Operator_0_cannot_be_applied_to_types_1_and_2_2365": "Nie można zastosować operatora „{0}” do typów „{1}” i „{2}”.", + "Option_0_can_only_be_specified_in_tsconfig_json_file_6064": "Opcję „{0}” można określić jedynie w pliku „tsconfig.json”.", + "Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided_5051": "Opcja „{0}” może być używana tylko w przypadku podania opcji „--inlineSourceMap” lub „--sourceMap”.", + "Option_0_cannot_be_specified_with_option_1_5053": "Opcji „{0}” nie można określić razem z opcją „{1}”.", + "Option_0_cannot_be_specified_without_specifying_option_1_5052": "Opcji „{0}” nie można określić bez opcji „{1}”.", + "Option_0_cannot_be_specified_without_specifying_option_1_or_option_2_5069": "Opcji „{0}” nie można określić bez opcji „{1}” lub opcji „{2}”.", + "Option_0_should_have_array_of_strings_as_a_value_6103": "Wartość opcji „{0}” powinna być tablicą łańcuchów.", + "Option_build_must_be_the_first_command_line_argument_6369": "Opcja „--build” musi być pierwszym argumentem wiersza polecenia.", + "Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES_5047": "Opcji „isolatedModules” można użyć tylko wtedy, gdy podano opcję „--module” lub opcja „target” określa cel „ES2015” lub wyższy.", + "Option_paths_cannot_be_used_without_specifying_baseUrl_option_5060": "Opcji „paths” nie można użyć bez podawania opcji „--baseUrl”.", + "Option_project_cannot_be_mixed_with_source_files_on_a_command_line_5042": "Nie można mieszać opcji „project” z plikami źródłowymi w wierszu polecenia.", + "Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070": "Nie można określić opcji „--resolveJsonModule” bez strategii rozpoznawania modułów „node”.", + "Options_0_and_1_cannot_be_combined_6370": "Nie można połączyć opcji „{0}” i „{1}”.", + "Options_Colon_6027": "Opcje:", + "Output_directory_for_generated_declaration_files_6166": "Katalog wyjściowy dla wygenerowanych plików deklaracji.", + "Output_file_0_from_project_1_does_not_exist_6309": "Plik wyjściowy „{0}” z projektu „{1}” nie istnieje", + "Output_file_0_has_not_been_built_from_source_file_1_6305": "Plik wyjściowy „{0}” nie został utworzony na podstawie pliku źródłowego „{1}”.", + "Overload_signature_is_not_compatible_with_function_implementation_2394": "Sygnatura przeciążenia nie jest zgodna z implementacją funkcji.", + "Overload_signatures_must_all_be_abstract_or_non_abstract_2512": "Wszystkie sygnatury przeciążeń muszą być abstrakcyjne lub nieabstrakcyjne.", + "Overload_signatures_must_all_be_ambient_or_non_ambient_2384": "Wszystkie sygnatury przeciążeń muszą być otaczającymi sygnaturami lub żadna nie może być otaczającą sygnaturą.", + "Overload_signatures_must_all_be_exported_or_non_exported_2383": "Wszystkie sygnatury przeciążeń muszą być wyeksportowane lub żadna nie może być wyeksportowana.", + "Overload_signatures_must_all_be_optional_or_required_2386": "Wszystkie sygnatury przeciążeń muszą być opcjonalne lub wymagane.", + "Overload_signatures_must_all_be_public_private_or_protected_2385": "Wszystkie sygnatury przeciążeń muszą być publiczne, prywatne lub chronione.", + "Parameter_0_cannot_be_referenced_in_its_initializer_2372": "Parametr „{0}” nie może być przywoływany w swoim inicjatorze.", + "Parameter_0_implicitly_has_an_1_type_7006": "Dla parametru „{0}” niejawnie określono typ „{1}”.", + "Parameter_0_is_not_in_the_same_position_as_parameter_1_1227": "Parametr „{0}” nie znajduje się w tym samym położeniu co parametr „{1}”.", + "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4066": "Parametr „{0}” sygnatury wywołania z wyeksportowanego interfejsu ma nazwę „{1}” z modułu prywatnego „{2}” lub używa tej nazwy.", + "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4067": "Parametr „{0}” sygnatury wywołania z wyeksportowanego interfejsu ma nazwę prywatną „{1}” lub używa tej nazwy.", + "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_can_4061": "Parametr „{0}” konstruktora z wyeksportowanej klasy ma nazwę „{1}” z modułu zewnętrznego {2} lub używa tej nazwy, ale nie można go nazwać.", + "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2_4062": "Parametr „{0}” konstruktora z wyeksportowanej klasy ma nazwę „{1}” z modułu prywatnego „{2}” lub używa tej nazwy.", + "Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1_4063": "Parametr „{0}” konstruktora z wyeksportowanej klasy ma nazwę prywatną „{1}” lub używa tej nazwy.", + "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_mod_4064": "Parametr „{0}” sygnatury konstruktora z wyeksportowanego interfejsu ma nazwę „{1}” z modułu prywatnego „{2}” lub używa tej nazwy.", + "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4065": "Parametr „{0}” sygnatury konstruktora z wyeksportowanego interfejsu ma nazwę prywatną „{1}” lub używa tej nazwy.", + "Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4076": "Parametr „{0}” wyeksportowanej funkcji ma nazwę „{1}” z modułu zewnętrznego {2} lub używa tej nazwy, ale nie można go nazwać.", + "Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2_4077": "Parametr „{0}” wyeksportowanej funkcji ma nazwę „{1}” z modułu prywatnego „{2}” lub używa tej nazwy.", + "Parameter_0_of_exported_function_has_or_is_using_private_name_1_4078": "Parametr „{0}” wyeksportowanej funkcji ma nazwę prywatną „{1}” lub używa tej nazwy.", + "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4091": "Parametr „{0}” sygnatury indeksu z wyeksportowanego interfejsu ma nazwę „{1}” z modułu prywatnego „{2}” lub używa tej nazwy.", + "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1_4092": "Parametr „{0}” sygnatury indeksu z wyeksportowanego interfejsu ma nazwę prywatną „{1}” lub używa tej nazwy.", + "Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4074": "Parametr „{0}” metody z wyeksportowanego interfejsu ma nazwę „{1}” z modułu prywatnego „{2}” lub używa tej nazwy.", + "Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4075": "Parametr „{0}” metody z wyeksportowanego interfejsu ma nazwę prywatną „{1}” lub używa tej nazwy.", + "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_c_4071": "Parametr „{0}” metody publicznej z wyeksportowanej klasy ma nazwę „{1}” z modułu zewnętrznego {2} lub używa tej nazwy, ale nie można go nazwać.", + "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4072": "Parametr „{0}” metody publicznej z wyeksportowanej klasy ma nazwę „{1}” z modułu prywatnego „{2}” lub używa tej nazwy.", + "Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4073": "Parametr „{0}” metody publicznej z wyeksportowanej klasy ma nazwę prywatną „{1}” lub używa tej nazwy.", + "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module__4068": "Parametr „{0}” publicznej metody statycznej z wyeksportowanej klasy ma nazwę „{1}” z modułu zewnętrznego {2} lub używa tej nazwy, ale nie można go nazwać.", + "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4069": "Parametr „{0}” publicznej metody statycznej z wyeksportowanej klasy ma nazwę „{1}” z modułu prywatnego „{2}” lub używa tej nazwy.", + "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4070": "Parametr „{0}” publicznej metody statycznej z wyeksportowanej klasy ma nazwę prywatną „{1}” lub używa tej nazwy.", + "Parameter_cannot_have_question_mark_and_initializer_1015": "Parametr nie może mieć znaku zapytania i inicjatora.", + "Parameter_declaration_expected_1138": "Oczekiwano deklaracji parametru.", + "Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2_4036": "Typ parametru publicznej metody ustawiającej „{0}” z wyeksportowanej klasy ma nazwę „{1}” z modułu prywatnego „{2}” lub używa tej nazwy.", + "Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_private_name_1_4037": "Typ parametru publicznej metody ustawiającej „{0}” z wyeksportowanej klasy ma nazwę prywatną „{1}” lub używa tej nazwy.", + "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_name_1_from_private_mod_4034": "Typ parametru publicznej statycznej metody ustawiającej „{0}” z wyeksportowanej klasy ma nazwę „{1}” z modułu prywatnego „{2}” lub używa tej nazwy.", + "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1_4035": "Typ parametru publicznej statycznej metody ustawiającej „{0}” z wyeksportowanej klasy ma nazwę prywatną „{1}” lub używa tej nazwy.", + "Parse_in_strict_mode_and_emit_use_strict_for_each_source_file_6141": "Analizuj w trybie z ograniczeniami i emituj ciąg „use strict” dla każdego pliku źródłowego.", + "Pattern_0_can_have_at_most_one_Asterisk_character_5061": "Wzorzec „{0}” może zawierać maksymalnie jeden znak „*”.", + "Prefix_0_with_an_underscore_90025": "Poprzedzaj elementy „{0}” znakiem podkreślenia", + "Prefix_all_unused_declarations_with_where_possible_95025": "Jeśli to możliwe, poprzedź wszystkie nieużywane deklaracje znakiem „_”", + "Print_names_of_files_part_of_the_compilation_6155": "Drukuj nazwy plików będących częścią kompilacji.", + "Print_names_of_generated_files_part_of_the_compilation_6154": "Drukuj nazwy wygenerowanych plików będących częścią kompilacji.", + "Print_the_compiler_s_version_6019": "Wypisz wersję kompilatora.", + "Print_this_message_6017": "Wypisz ten komunikat.", + "Project_0_can_t_be_built_because_its_dependency_1_has_errors_6363": "Nie można skompilować projektu „{0}”, ponieważ jego zależność „{1}” zawiera błędy", + "Project_0_is_out_of_date_because_its_dependency_1_is_out_of_date_6353": "Projekt „{0}” jest nieaktualny, ponieważ jego zależność „{1}” jest nieaktualna", + "Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2_6350": "Projekt „{0}” jest nieaktualny, ponieważ najstarsze dane wyjściowe „{1}” są starsze niż najnowsze dane wejściowe „{2}”", + "Project_0_is_out_of_date_because_output_file_1_does_not_exist_6352": "Projekt „{0}” jest nieaktualny, ponieważ plik wyjściowy „{1}” nie istnieje", + "Project_0_is_up_to_date_6361": "Projekt „{0}” jest aktualny", + "Project_0_is_up_to_date_because_newest_input_1_is_older_than_oldest_output_2_6351": "Projekt „{0}” jest aktualny, ponieważ najnowsze dane wejściowe „{1}” są starsze niż najstarsze dane wyjściowe „{2}”", + "Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies_6354": "Projekt „{0}” jest aktualny z plikami .d.ts z jego zależności", + "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202": "Odwołania do projektu nie mogą tworzyć grafu kołowego. Wykryto cykl: {0}", + "Projects_in_this_build_Colon_0_6355": "Projekty w tej kompilacji: {0}", + "Projects_to_reference_6300": "Projekty do przywołania", + "Property_0_does_not_exist_on_const_enum_1_2479": "Właściwość „{0}” nie istnieje w wyliczeniu ze specyfikatorem „const” „{1}”.", + "Property_0_does_not_exist_on_type_1_2339": "Właściwość „{0}” nie istnieje w typie „{1}”.", + "Property_0_does_not_exist_on_type_1_Did_you_forget_to_use_await_2570": "Właściwość „{0}” nie istnieje w typie „{1}”. Czy zapomniano użyć elementu „await”?", + "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551": "Właściwość „{0}” nie istnieje w typie „{1}”. Czy chodziło Ci o „{2}”?", + "Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1_2546": "Właściwość „{0}” ma deklaracje będące w konflikcie i jest niedostępna w typie „{1}”.", + "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor_2564": "Właściwość „{0}” nie ma inicjatora i nie jest na pewno przypisana w konstruktorze.", + "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033": "Dla właściwości „{0}” niejawnie określono typ „any”, ponieważ jego metoda dostępu „get” nie ma adnotacji zwracanego typu.", + "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032": "Dla właściwości „{0}” niejawnie określono typ „any”, ponieważ jego metoda dostępu „set” nie ma adnotacji typu parametru.", + "Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2_2416": "Właściwości „{0}” w typie „{1}” nie można przypisać do tej samej właściwości w typie podstawowym „{2}”.", + "Property_0_in_type_1_is_not_assignable_to_type_2_2603": "Właściwości „{0}” w typie „{1}” nie można przypisać do typu „{2}”.", + "Property_0_is_declared_but_its_value_is_never_read_6138": "Właściwość „{0}” jest zadeklarowana, ale jej wartość nie jest nigdy odczytywana.", + "Property_0_is_incompatible_with_index_signature_2530": "Właściwość „{0}” jest niezgodna z sygnaturą indeksu.", + "Property_0_is_missing_in_type_1_2324": "W typie „{1}” brakuje właściwości „{0}”.", + "Property_0_is_optional_in_type_1_but_required_in_type_2_2327": "Właściwość „{0}” jest opcjonalna w typie „{1}”, ale jest wymagana w typie „{2}”.", + "Property_0_is_private_and_only_accessible_within_class_1_2341": "Właściwość „{0}” jest prywatna i dostępna tylko w klasie „{1}”.", + "Property_0_is_private_in_type_1_but_not_in_type_2_2325": "Właściwość „{0}” jest prywatna w typie „{1}”, ale nie w typie „{2}”.", + "Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1_2446": "Właściwość „{0}” jest chroniona i dostępna tylko za pośrednictwem wystąpienia klasy „{1}”.", + "Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses_2445": "Właściwość „{0}” jest chroniona i dostępna tylko w klasie „{1}” oraz w jej podklasach.", + "Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2_2443": "Właściwość „{0}” jest chroniona, ale typ „{1}” nie jest klasą pochodną elementu „{2}”.", + "Property_0_is_protected_in_type_1_but_public_in_type_2_2444": "Właściwość „{0}” jest chroniona w typie „{1}”, ale jest publiczna w typie „{2}”.", + "Property_0_is_used_before_being_assigned_2565": "Właściwość „{0}” jest używana przed przypisaniem.", + "Property_0_of_JSX_spread_attribute_is_not_assignable_to_target_property_2606": "Właściwości „{0}” atrybutu rozkładu JSX nie można przypisać do właściwości docelowej.", + "Property_0_of_exported_class_expression_may_not_be_private_or_protected_4094": "Właściwość „{0}” wyeksportowanego wyrażenia klasy nie może być prywatna ani chroniona.", + "Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4032": "Właściwość „{0}” wyeksportowanego interfejsu ma nazwę „{1}” z modułu prywatnego „{2}” lub używa tej nazwy.", + "Property_0_of_exported_interface_has_or_is_using_private_name_1_4033": "Właściwość „{0}” wyeksportowanego interfejsu ma nazwę prywatną „{1}” lub używa tej nazwy.", + "Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2_2412": "Nie można przypisać właściwości „{0}” typu „{1}” do typu indeksu numerycznego „{2}”.", + "Property_0_of_type_1_is_not_assignable_to_string_index_type_2_2411": "Nie można przypisać właściwości „{0}” typu „{1}” do typu indeksu ciągu „{2}”.", + "Property_assignment_expected_1136": "Oczekiwano przypisania właściwości.", + "Property_destructuring_pattern_expected_1180": "Oczekiwano wzorca usuwającego strukturę właściwości.", + "Property_or_signature_expected_1131": "Oczekiwano właściwości lub sygnatury.", + "Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_li_1328": "Wartością właściwości może być jedynie literał ciągu, literał numeryczny, wartości „true”, „false” i „null”, literał obiektu i literał tablicy.", + "Provide_full_support_for_iterables_in_for_of_spread_and_destructuring_when_targeting_ES5_or_ES3_6179": "Udostępnij pełne wsparcie dla elementów iterowanych w elementach „for-of”, rozpiętości i usuwania, gdy elementem docelowym jest „ES5” lub „ES3”.", + "Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4098": "Metoda publiczna „{0}” wyeksportowanej klasy ma nazwę „{1}” z modułu zewnętrznego {2} lub używa tej nazwy, ale nie można jej nazwać.", + "Public_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4099": "Metoda publiczna „{0}” wyeksportowanej klasy ma nazwę „{1}” z modułu prywatnego „{2}” lub używa tej nazwy.", + "Public_method_0_of_exported_class_has_or_is_using_private_name_1_4100": "Metoda publiczna „{0}” wyeksportowanej klasy ma nazwę prywatną „{1}” lub używa tej nazwy.", + "Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_name_4029": "Właściwość publiczna „{0}” wyeksportowanej klasy ma nazwę „{1}” z modułu zewnętrznego {2} lub używa tej nazwy, ale nie można jej nazwać.", + "Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4030": "Właściwość publiczna „{0}” wyeksportowanej klasy ma nazwę „{1}” z modułu prywatnego „{2}” lub używa tej nazwy.", + "Public_property_0_of_exported_class_has_or_is_using_private_name_1_4031": "Właściwość publiczna „{0}” wyeksportowanej klasy ma nazwę prywatną „{1}” lub używa tej nazwy.", + "Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_4095": "Publiczna metoda statyczna „{0}” wyeksportowanej klasy ma nazwę „{1}” z modułu zewnętrznego {2} lub używa tej nazwy, ale nie można jej nazwać.", + "Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4096": "Publiczna metoda statyczna „{0}” wyeksportowanej klasy ma nazwę „{1}” z modułu prywatnego „{2}” lub używa tej nazwy.", + "Public_static_method_0_of_exported_class_has_or_is_using_private_name_1_4097": "Publiczna metoda statyczna „{0}” wyeksportowanej klasy ma nazwę prywatną „{1}” lub używa tej nazwy.", + "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot__4026": "Publiczna właściwość statyczna „{0}” wyeksportowanej klasy ma nazwę „{1}” z modułu zewnętrznego {2} lub używa tej nazwy, ale nie można jej nazwać.", + "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4027": "Publiczna właściwość statyczna „{0}” wyeksportowanej klasy ma nazwę „{1}” z modułu prywatnego „{2}” lub używa tej nazwy.", + "Public_static_property_0_of_exported_class_has_or_is_using_private_name_1_4028": "Publiczna właściwość statyczna „{0}” wyeksportowanej klasy ma nazwę prywatną „{1}” lub używa tej nazwy.", + "Raise_error_on_expressions_and_declarations_with_an_implied_any_type_6052": "Zgłaszaj błąd w przypadku wyrażeń i deklaracji z implikowanym typem „any”.", + "Raise_error_on_this_expressions_with_an_implied_any_type_6115": "Zgłaszaj błąd w przypadku wyrażeń „this” z niejawnym typem „any”.", + "Redirect_output_structure_to_the_directory_6006": "Przekieruj strukturę wyjściową do katalogu.", + "Referenced_project_0_must_have_setting_composite_Colon_true_6306": "Przywoływany projekt „{0}” musi mieć ustawienie „composite” o wartości true.", + "Remove_all_unreachable_code_95051": "Usuń cały nieosiągalny kod", + "Remove_all_unused_labels_95054": "Usuń wszystkie nieużywane etykiety", + "Remove_braces_from_arrow_function_95060": "Usuń nawiasy klamrowe z funkcji strzałki", + "Remove_declaration_for_Colon_0_90004": "Usuń deklarację dla: „{0}”", + "Remove_destructuring_90009": "Usuń usuwanie struktury", + "Remove_import_from_0_90005": "Usuń import z „{0}”", + "Remove_unreachable_code_95050": "Usuń nieosiągalny kod", + "Remove_unused_label_95053": "Usuń nieużywaną etykietę", + "Remove_variable_statement_90010": "Usuń instrukcję zmiennej", + "Replace_import_with_0_95015": "Zamień import na element „{0}”.", + "Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "Zgłoś błąd, gdy nie wszystkie ścieżki kodu zwracają wartość.", + "Report_errors_for_fallthrough_cases_in_switch_statement_6076": "Zgłoś błędy dla przepuszczających klauzul case w instrukcji switch.", + "Report_errors_in_js_files_8019": "Zgłaszaj błędy w plikach js.", + "Report_errors_on_unused_locals_6134": "Raportuj błędy dla nieużywanych elementów lokalnych.", + "Report_errors_on_unused_parameters_6135": "Raportuj błędy dla nieużywanych parametrów.", + "Required_type_parameters_may_not_follow_optional_type_parameters_2706": "Wymagane parametry typu mogą nie być zgodne z opcjonalnymi parametrami typu.", + "Resolution_for_module_0_was_found_in_cache_from_location_1_6147": "Znaleziono rozwiązanie dla modułu „{0}” w pamięci podręcznej z lokalizacji „{1}”.", + "Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols_6195": "Rozwiązuj elementy „keyof” tylko do nazw właściwości mających jako wartość ciągi (nie liczby czy symbole).", + "Resolving_from_node_modules_folder_6118": "Trwa rozpoznawanie na podstawie folderu node_modules...", + "Resolving_module_0_from_1_6086": "======== Rozpoznawanie modułu „{0}” na podstawie „{1}”. ========", + "Resolving_module_name_0_relative_to_base_url_1_2_6094": "Rozpoznawanie nazwy modułu „{0}” względem podstawowego adresu URL „{1}” — „{2}”.", + "Resolving_real_path_for_0_result_1_6130": "Rozpoznawanie rzeczywistej ścieżki elementu ƒ„{0}”, wynik: „{1}”.", + "Resolving_type_reference_directive_0_containing_file_1_root_directory_2_6116": "======== Rozpoznawanie dyrektywy odwołania do typu „{0}”, plik zawierający: „{1}”, katalog główny: „{2}”. ========", + "Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set_6123": "======== Rozpoznawanie dyrektywy odwołania do typu „{0}”, plik zawierający: „{1}”, katalog główny nie został ustawiony. ========", + "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1_6127": "======== Rozpoznawanie dyrektywy odwołania do typu „{0}”, plik zawierający nie został ustawiony, katalog główny: „{1}”. ========", + "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set_6128": "======== Rozpoznawanie dyrektywy odwołania do typu „{0}”, plik zawierający nie został ustawiony, katalog główny nie został ustawiony. ========", + "Resolving_using_primary_search_paths_6117": "Trwa rozpoznawanie przy użyciu ścieżek wyszukiwania podstawowego...", + "Resolving_with_primary_search_path_0_6121": "Rozpoznawanie przy użyciu ścieżki wyszukiwania podstawowego „{0}”.", + "Rest_parameter_0_implicitly_has_an_any_type_7019": "Dla parametru rest „{0}” niejawnie określono typ „any[]”.", + "Rest_types_may_only_be_created_from_object_types_2700": "Typy rest można tworzyć tylko na podstawie typów obiektu.", + "Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4046": "Zwracany typ sygnatury wywołania z wyeksportowanego interfejsu ma nazwę „{0}” z modułu prywatnego „{1}” lub używa tej nazwy.", + "Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0_4047": "Zwracany typ sygnatury wywołania z wyeksportowanego interfejsu ma nazwę prywatną „{0}” lub używa tej nazwy.", + "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_mod_4044": "Zwracany typ sygnatury konstruktora z wyeksportowanego interfejsu ma nazwę „{0}” z modułu prywatnego „{1}” lub używa tej nazwy.", + "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0_4045": "Zwracany typ sygnatury konstruktora z wyeksportowanego interfejsu ma nazwę prywatną „{0}” lub używa tej nazwy.", + "Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class_2409": "Musi istnieć możliwość przypisania zwracanego typu sygnatury konstruktora do typu wystąpienia klasy.", + "Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named_4058": "Zwracany typ wyeksportowanej funkcji ma nazwę „{0}” z modułu zewnętrznego {1} lub używa tej nazwy, ale nie można go nazwać.", + "Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1_4059": "Zwracany typ wyeksportowanej funkcji ma nazwę „{0}” z modułu prywatnego „{1}” lub używa tej nazwy.", + "Return_type_of_exported_function_has_or_is_using_private_name_0_4060": "Zwracany typ wyeksportowanej funkcji ma nazwę prywatną „{0}” lub używa tej nazwy.", + "Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4048": "Zwracany typ sygnatury indeksu z wyeksportowanego interfejsu ma nazwę „{0}” z modułu prywatnego „{1}” lub używa tej nazwy.", + "Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0_4049": "Zwracany typ sygnatury indeksu z wyeksportowanego interfejsu ma nazwę prywatną „{0}” lub używa tej nazwy.", + "Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4056": "Zwracany typ metody z wyeksportowanego interfejsu ma nazwę „{0}” z modułu prywatnego „{1}” lub używa tej nazwy.", + "Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0_4057": "Zwracany typ metody z wyeksportowanego interfejsu ma nazwę prywatną „{0}” lub używa tej nazwy.", + "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_4041": "Zwracany typ publicznej metody pobierającej „{0}” z wyeksportowanej klasy ma nazwę „{1}” z modułu zewnętrznego {2} lub używa tej nazwy, ale nie można go nazwać.", + "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2_4042": "Zwracany typ publicznej metody pobierającej „{0}” z wyeksportowanej klasy ma nazwę „{1}” z modułu prywatnego „{2}” lub używa tej nazwy.", + "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_private_name_1_4043": "Zwracany typ publicznej metody pobierającej „{0}” z wyeksportowanej klasy ma nazwę prywatną „{1}” lub używa tej nazwy.", + "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_c_4053": "Zwracany typ metody publicznej z wyeksportowanej klasy ma nazwę „{0}” z modułu zewnętrznego {1} lub używa tej nazwy, ale nie można go nazwać.", + "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4054": "Zwracany typ metody publicznej z wyeksportowanej klasy ma nazwę „{0}” z modułu prywatnego „{1}” lub używa tej nazwy.", + "Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0_4055": "Zwracany typ metody publicznej z wyeksportowanej klasy ma nazwę prywatną „{0}” lub używa tej nazwy.", + "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_external_modul_4038": "Zwracany typ publicznej statycznej metody pobierającej „{0}” z wyeksportowanej klasy ma nazwę „{1}” z modułu zewnętrznego {2} lub używa tej nazwy, ale nie można go nazwać.", + "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_4039": "Zwracany typ publicznej statycznej metody pobierającej „{0}” z wyeksportowanej klasy ma nazwę „{1}” z modułu prywatnego „{2}” lub używa tej nazwy.", + "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_private_name_1_4040": "Zwracany typ publicznej statycznej metody pobierającej „{0}” z wyeksportowanej klasy ma nazwę prywatną „{1}” lub używa tej nazwy.", + "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module__4050": "Zwracany typ publicznej metody statycznej z wyeksportowanej klasy ma nazwę „{0}” z modułu zewnętrznego {1} lub używa tej nazwy, ale nie można go nazwać.", + "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4051": "Zwracany typ publicznej metody statycznej z wyeksportowanej klasy ma nazwę „{0}” z modułu prywatnego „{1}” lub używa tej nazwy.", + "Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0_4052": "Zwracany typ publicznej metody statycznej z wyeksportowanej klasy ma nazwę prywatną „{0}” lub używa tej nazwy.", + "Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program_6184": "Ponownie używane są rozwiązania modułu pochodzące z programu „{0}”, ponieważ rozwiązania nie zmieniły się w stosunku do starej wersji programu.", + "Reusing_resolution_of_module_0_to_file_1_from_old_program_6183": "Ponownie używane jest rozwiązanie modułu „{0}” do pliku „{1}” ze starej wersji programu.", + "Rewrite_all_as_indexed_access_types_95034": "Zmień wszystko na indeksowane typy dostępu", + "Rewrite_as_the_indexed_access_type_0_90026": "Napisz ponownie jako indeksowany typ dostępu „{0}”", + "Root_directory_cannot_be_determined_skipping_primary_search_paths_6122": "Nie można określić katalogu głównego. Pomijanie ścieżek wyszukiwania podstawowego.", + "STRATEGY_6039": "STRATEGIA", + "Scoped_package_detected_looking_in_0_6182": "Wykryto pakiet w zakresie, wyszukiwanie w „{0}”", + "Setters_cannot_return_a_value_2408": "Metody ustawiające nie mogą zwracać wartości.", + "Show_all_compiler_options_6169": "Pokaż wszystkie opcje kompilatora.", + "Show_diagnostic_information_6149": "Pokaż informacje diagnostyczne.", + "Show_verbose_diagnostic_information_6150": "Pokaż pełne informacje diagnostyczne.", + "Show_what_would_be_built_or_deleted_if_specified_with_clean_6367": "Pokaż, co zostanie skompilowane (lub usunięte, jeśli określono opcję „--clean”)", + "Signature_0_must_be_a_type_predicate_1224": "Sygnatura „{0}” musi być predykatem typów.", + "Skip_type_checking_of_declaration_files_6012": "Pomiń sprawdzanie typu plików deklaracji.", + "Skipping_build_of_project_0_because_its_dependency_1_has_errors_6362": "Pomijanie kompilacji projektu „{0}”, ponieważ jego zależność „{1}” zawiera błędy", + "Skipping_clean_because_not_all_projects_could_be_located_6371": "Pomijanie czyszczenia, ponieważ nie można zlokalizować wszystkich projektów", + "Source_Map_Options_6175": "Opcje mapy źródła", + "Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature_2382": "Nie można przypisać specjalizowanej sygnatury przeciążenia do żadnej sygnatury niespecjalizowanej.", + "Specifier_of_dynamic_import_cannot_be_spread_element_1325": "Specyfikator dynamicznego importowania nie może być elementem spread.", + "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_or_ESNEXT_6015": "Podaj wersję docelową języka ECMAScript: „ES3” (domyślna), „ES5”, „ES2015”, „ES2016”, „ES2017”, „ES2018” lub „ESNEXT”.", + "Specify_JSX_code_generation_Colon_preserve_react_native_or_react_6080": "Wybierz sposób generowania kodu JSX: „preserve”, „react-native” lub „react”.", + "Specify_library_files_to_be_included_in_the_compilation_6079": "Określ pliki biblioteki do uwzględnienia w kompilacji.", + "Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext_6016": "Określ sposób generowania kodu modułu: „none”, „commonjs”, „amd”, „system”, „umd”, „es2015” lub „ESNext”.", + "Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6_6069": "Określ strategię rozpoznawania modułów: „node” (Node.js) lub „classic” (TypeScript w wersji wcześniejszej niż 1.6).", + "Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h_6146": "Określ funkcję fabryki JSX do użycia, gdy elementem docelowym jest emisja elementu JSX „react”, np. „React.createElement” lub „h”.", + "Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix_6060": "Określ sekwencję końca wiersza, która ma być używana podczas emitowania plików: „CRLF” (dos) lub „LF” (unix).", + "Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations_6004": "Określ lokalizację, w której debuger ma szukać plików TypeScript zamiast szukania w lokalizacjach źródłowych.", + "Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations_6003": "Określ lokalizację, w której debuger ma szukać plików map zamiast szukania w wygenerowanych lokalizacjach.", + "Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir_6058": "Określ katalog główny plików wejściowych. Strukturą katalogów wyjściowych można sterować przy użyciu opcji --outDir.", + "Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher_2472": "Operator rozpiętości w wyrażeniach „new” jest dostępny tylko wtedy, gdy jest używany język ECMAScript 5 lub nowszy.", + "Spread_types_may_only_be_created_from_object_types_2698": "Typy spread można tworzyć tylko z typów obiektu.", + "Starting_compilation_in_watch_mode_6031": "Trwa uruchamianie kompilacji w trybie śledzenia...", + "Statement_expected_1129": "Oczekiwano instrukcji.", + "Statements_are_not_allowed_in_ambient_contexts_1036": "Instrukcje są niedozwolone w otaczających kontekstach.", + "Static_members_cannot_reference_class_type_parameters_2302": "Statyczne składowe nie mogą przywoływać parametrów typu klasy.", + "Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1_2699": "Właściwość statyczna „{0}” jest w konflikcie z właściwością wbudowaną „Function.{0}” funkcji konstruktora „{1}”.", + "Strict_Type_Checking_Options_6173": "Opcje ścisłego sprawdzania typów", + "String_literal_expected_1141": "Oczekiwano literału ciągu.", + "String_literal_with_double_quotes_expected_1327": "Oczekiwano literału ciągu z podwójnymi cudzysłowami.", + "Stylize_errors_and_messages_using_color_and_context_experimental_6073": "Stosuj styl dla błędów i komunikatów za pomocą koloru i kontekstu. (eksperymentalne).", + "Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_t_2717": "Kolejne deklaracje właściwości muszą być tego samego typu. Właściwość „{0}” musi być typu „{1}”, ale w tym miejscu jest typu „{2}”.", + "Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_t_2403": "Kolejne deklaracje zmiennej muszą być tego samego typu. Zmienna „{0}” musi być typu „{1}”, ale w tym miejscu jest typu „{2}”.", + "Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2_5064": "Podstawienie „{0}” dla wzorca „{1}” ma nieprawidłowy typ. Oczekiwano typu „string”, a uzyskano typ „{2}”.", + "Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character_5062": "Podstawienie „{0}” we wzorcu „{1}” może zawierać maksymalnie jeden znak „*”.", + "Substitutions_for_pattern_0_should_be_an_array_5063": "Podstawieniami wzorca „{0}” powinna być tablica.", + "Substitutions_for_pattern_0_shouldn_t_be_an_empty_array_5066": "Podstawienia dla wzorca „{0}” nie powinny być pustą tablicą.", + "Successfully_created_a_tsconfig_json_file_6071": "Pomyślnie utworzono plik tsconfig.json.", + "Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors_2337": "Wywołania super są niedozwolone poza konstruktorami i zagnieżdżonymi funkcjami wewnątrz konstruktorów.", + "Suppress_excess_property_checks_for_object_literals_6072": "Pomiń nadmiarowe sprawdzenia właściwości dla literałów obiektu.", + "Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures_6055": "Pomiń błędy noImplicitAny dotyczące obiektów indeksowania bez sygnatur indeksów.", + "Symbol_reference_does_not_refer_to_the_global_Symbol_constructor_object_2470": "Odwołanie do elementu „Symbol” nie zawiera odwołania do globalnego obiektu konstruktora symboli.", + "Syntax_Colon_0_6023": "Składnia: {0}", + "The_0_operator_cannot_be_applied_to_type_symbol_2469": "Nie można zastosować operatora „{0}” do typu „symbol”.", + "The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead_2447": "Operator „{0}” nie jest dozwolony w przypadku typów logicznych. Zamiast tego rozważ użycie operatora „{1}”.", + "The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead_2696": "Typ „Object” można przypisać do niewielu innych typów. Czy zamiast tego typu miał zostać użyty typ „any”?", + "The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_stand_2496": "Obiekt „arguments” nie może być przywoływany w funkcji strzałkowej w językach ES3 i ES5. Rozważ użycie standardowego wyrażenia funkcji.", + "The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_usi_2522": "Obiekt „arguments” nie może być przywoływany w asynchronicznej funkcji lub metodzie w języku ES3 i ES5. Rozważ użycie standardowej funkcji lub metody.", + "The_body_of_an_if_statement_cannot_be_the_empty_statement_1313": "Treść instrukcji „if” nie może być pustą instrukcją.", + "The_character_set_of_the_input_files_6163": "Zestaw znaków plików wejściowych.", + "The_containing_function_or_module_body_is_too_large_for_control_flow_analysis_2563": "Treść zawierającej funkcji lub modułu jest za duża do analizy przepływu sterowania.", + "The_current_host_does_not_support_the_0_option_5001": "Bieżący host nie obsługuje opcji „{0}”.", + "The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context_2714": "Wyrażenie przypisania eksportu musi być identyfikatorem lub kwalifikowaną nazwą w otaczającym kontekście.", + "The_files_list_in_config_file_0_is_empty_18002": "Lista „files” w pliku konfiguracji „{0}” jest pusta.", + "The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback_1060": "Pierwszym parametrem metody „then” obietnicy musi być wywołanie zwrotne.", + "The_global_type_JSX_0_may_not_have_more_than_one_property_2608": "Dla typu globalnego „JSX.{0}” nie można określić więcej niż jednej właściwości.", + "The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_option_1343": "Metawłaściwość „import.meta” jest dozwolona tylko w przypadku podania wartości „ESNext” dla opcji kompilatora „target” i „module”.", + "The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary_2527": "Wnioskowany typ „{0}” przywołuje niedostępny typ „{1}”. Adnotacja typu jest konieczna.", + "The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern_2491": "Lewa strona instrukcji „for...in” nie może być wzorcem usuwającym strukturę.", + "The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation_2404": "Lewa strona instrukcji „for...in” nie może używać adnotacji typu.", + "The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access_2406": "Lewa strona instrukcji „for...in” musi być zmienną lub dostępem do właściwości.", + "The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any_2405": "Lewa strona instrukcji „for...in” musi być typu „string” lub „any”.", + "The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation_2483": "Lewa strona instrukcji „for...of” nie może używać adnotacji typu.", + "The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access_2487": "Lewa strona instrukcji „for...of” musi być zmienną lub dostępem do właściwości.", + "The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type_2362": "Lewa strona operacji arytmetycznej musi być typu „any”, „number” lub typu wyliczeniowego.", + "The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access_2364": "Lewa strona wyrażenia przypisania musi być zmienną lub dostępem do właściwości.", + "The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol_2360": "Lewa strona wyrażenia „in” musi być typu „any”, „string”, „number” lub „symbol”.", + "The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_paramete_2358": "Lewa strona wyrażenia „instanceof” musi być typu „any”, typu obiektu lub parametrem typu.", + "The_locale_used_when_displaying_messages_to_the_user_e_g_en_us_6156": "Ustawienia regionalne używane przy wyświetlaniu komunikatów użytkownikowi (np. „pl-pl”)", + "The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files_6136": "Maksymalna głębokość zależności na potrzeby wyszukiwania w elemencie node_modules i ładownia plików JavaScript.", + "The_operand_of_a_delete_operator_cannot_be_a_read_only_property_2704": "Argument operacji dla operatora delete nie może być właściwością tylko do odczytu.", + "The_operand_of_a_delete_operator_must_be_a_property_reference_2703": "Argument operacji dla operatora delete musi być odwołaniem do właściwości.", + "The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access_2357": "Operand operatora inkrementacji lub dekrementacji musi być zmienną lub dostępem do właściwości.", + "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601": "Zwracany typ konstruktora elementu JSX musi zwracać typ obiektu.", + "The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any_1237": "Zwracany typ funkcji dekoratora parametrów musi mieć postać „void” lub „any”.", + "The_return_type_of_a_property_decorator_function_must_be_either_void_or_any_1236": "Zwracany typ funkcji dekoratora właściwości musi mieć postać „void” lub „any”.", + "The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_t_1058": "Zwracany typ funkcji asynchronicznej musi być prawidłową obietnicą lub nie może zawierać wywoływalnej składowej „then”.", + "The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_1064": "Zwracany typ metody lub funkcji asynchronicznej musi być globalnym typem Promise.", + "The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_but_2407": "Prawa strona instrukcji „for...in” musi zawierać typ „any”, typ obiektu lub parametr typu, a tutaj ma typ „{0}”.", + "The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type_2363": "Prawa strona operacji arytmetycznej musi być typu „any”, „number” lub typu wyliczeniowego.", + "The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter_2361": "Prawa strona wyrażenia „in” musi być typu „any”, typu obiektu lub parametrem typu.", + "The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_F_2359": "Prawa strona wyrażenia „instanceof” musi być typu „any” lub typu, który można przypisać do typu interfejsu „Function”.", + "The_specified_path_does_not_exist_Colon_0_5058": "Wybrana ścieżka nie istnieje: „{0}”.", + "The_target_of_an_assignment_must_be_a_variable_or_a_property_access_2541": "Cel przypisania musi być zmienną lub dostępem do właściwości.", + "The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access_2701": "Cel przypisania rest obiektu musi stanowić dostęp do zmiennej lub właściwości.", + "The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1_2684": "Kontekstu „this” typu „{0}” nie można przypisać do elementu „this” metody typu „{1}”.", + "The_this_types_of_each_signature_are_incompatible_2685": "Typy „this” sygnatur nie są zgodne.", + "The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_typ_2453": "Nie można wywnioskować argumentu typu dla parametru typu „{0}” na podstawie użycia. Rozważ jawne określenie argumentów typu.", + "The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value__2547": "Typ zwracany przez metodę „next()” iteratora asynchronicznego musi być obietnicą dla typu z właściwością „value”.", + "The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property_2490": "Typ zwracany przez metodę „next()” iteratora musi mieć właściwość „value”.", + "The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer_1189": "Deklaracja zmiennej instrukcji „for...in” nie może mieć inicjatora.", + "The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer_1190": "Deklaracja zmiennej instrukcji „for...of” nie może mieć inicjatora.", + "The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any_2410": "Instrukcja „with” nie jest obsługiwana. Wszystkie symbole w bloku „with” będą mieć typ „any”.", + "This_constructor_function_may_be_converted_to_a_class_declaration_80002": "Ta funkcja konstruktora może zostać przekonwertowana na deklarację klasy.", + "This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found_2354": "Ta składnia wymaga zaimportowanego pomocnika, ale nie można znaleźć modułu „{0}”.", + "This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1_2343": "Ta składnia wymaga zaimportowanego pomocnika o nazwie „{1}”, ale moduł „{0}” nie ma wyeksportowanej składowej „{1}”.", + "Trailing_comma_not_allowed_1009": "Końcowy przecinek jest niedozwolony.", + "Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule_6153": "Transpiluj każdy plik jako oddzielny moduł (podobne do „ts.transpileModule”).", + "Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_mod_7035": "Spróbuj użyć polecenia „npm install @types/{0}”, jeśli istnieje, lub dodać nowy plik deklaracji (.d.ts) zawierający ciąg „declare module '{0}';”", + "Trying_other_entries_in_rootDirs_6110": "Wykonywanie prób przy użyciu innych pozycji opcji „rootDirs”.", + "Trying_substitution_0_candidate_module_location_Colon_1_6093": "Wykonywanie próby przeprowadzenia podstawienia „{0}”, lokalizacja modułu kandydata: „{1}”.", + "Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2_2493": "Nie można przypisać typu krotki „{0}” o długości „{1}” do krotki o długości „{2}”.", + "Type_0_cannot_be_converted_to_type_1_2352": "Typu „{0}” nie można przekonwertować na typ „{1}”.", + "Type_0_cannot_be_used_as_an_index_type_2538": "Typu „{0}” nie można używać jako typu indeksu.", + "Type_0_cannot_be_used_to_index_type_1_2536": "Typu „{0}” nie można użyć do indeksowania typu „{1}”.", + "Type_0_does_not_satisfy_the_constraint_1_2344": "Typ „{0}” nie spełnia warunków ograniczenia „{1}”.", + "Type_0_has_no_matching_index_signature_for_type_1_2537": "Typ „{0}” nie ma pasującej sygnatury indeksu dla typu „{1}”.", + "Type_0_has_no_properties_in_common_with_type_1_2559": "Typy „{0}” i „{1}” nie mają żadnych wspólnych właściwości.", + "Type_0_has_no_property_1_2460": "Typ „{0}” nie ma właściwości „{1}”.", + "Type_0_has_no_property_1_and_no_string_index_signature_2459": "Typ „{0}” nie ma właściwości „{1}” i sygnatury indeksu ciągu.", + "Type_0_is_not_a_constructor_function_type_2507": "Typ „{0}” nie jest typem funkcji konstruktora.", + "Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Prom_1055": "Typ „{0}” nie jest prawidłowym zwracanym typem funkcji asynchronicznej w wersji ES5/ES3, ponieważ nie odwołuje się do wartości konstruktora zgodnej z elementem Promise.", + "Type_0_is_not_an_array_type_2461": "Typ „{0}” nie jest typem tablicowym.", + "Type_0_is_not_an_array_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators_2568": "Typ „{0}” nie jest typem tablicy. Użyj opcji kompilatora „--downlevelIteration”, aby zezwolić na iterowanie iteratorów.", + "Type_0_is_not_an_array_type_or_a_string_type_2495": "Typ „{0}” nie jest typem tablicowym ani typem ciągu.", + "Type_0_is_not_an_array_type_or_a_string_type_Use_compiler_option_downlevelIteration_to_allow_iterati_2569": "Typ „{0}” nie jest typem tablicy ani typem ciągu. Użyj opcji kompilatora „--downlevelIteration”, aby zezwolić na iterowanie iteratorów.", + "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549": "Typ „{0}” nie jest typem tablicy ani ciągu lub nie ma metody „[Symbol.iterator]()” zwracającej iterator.", + "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548": "Typ „{0}” nie jest typem tablicy lub nie ma metody „[Symbol.iterator]()” zwracającej iterator.", + "Type_0_is_not_assignable_to_type_1_2322": "Typu „{0}” nie można przypisać do typu „{1}”.", + "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_2719": "Typu „{0}” nie można przypisać do typu „{1}”. Istnieją dwa różne typy o tej nazwie, lecz są ze sobą niezwiązane.", + "Type_0_is_not_comparable_to_type_1_2678": "Typu „{0}” nie można porównać z typem „{1}”.", + "Type_0_is_not_generic_2315": "Typ „{0}” nie jest ogólny.", + "Type_0_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator_2504": "Typ „{0}” musi zawierać metodę „[Symbol.asyncIterator]()” zwracającą iterator asynchroniczny.", + "Type_0_must_have_a_Symbol_iterator_method_that_returns_an_iterator_2488": "Typ „{0}” musi zawierać metodę „[Symbol.iterator]()” zwracającą iterator.", + "Type_0_provides_no_match_for_the_signature_1_2658": "Typ „{0}” nie udostępnia dopasowania dla sygnatury „{1}”.", + "Type_0_recursively_references_itself_as_a_base_type_2310": "Typ „{0}” rekursywnie przywołuje sam siebie jako typ podstawowy.", + "Type_alias_0_circularly_references_itself_2456": "Alias typu „{0}” cyklicznie przywołuje sam siebie.", + "Type_alias_name_cannot_be_0_2457": "Alias typu nie może mieć nazwy „{0}”.", + "Type_annotation_cannot_appear_on_a_constructor_declaration_1093": "Adnotacja typu nie może występować w deklaracji konstruktora.", + "Type_argument_candidate_1_is_not_a_valid_type_argument_because_it_is_not_a_supertype_of_candidate_0_2455": "Kandydujący argument typu „{1}” nie jest prawidłowym argumentem typu, ponieważ nie jest nadtypem kandydata „{0}”.", + "Type_argument_expected_1140": "Oczekiwano argumentu typu.", + "Type_argument_list_cannot_be_empty_1099": "Lista argumentów typu nie może być pusta.", + "Type_arguments_cannot_be_used_here_1342": "Nie można tutaj używać argumentów typu.", + "Type_declaration_files_to_be_included_in_compilation_6124": "Pliki deklaracji typu do uwzględnienia w kompilacji.", + "Type_expected_1110": "Oczekiwano typu.", + "Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method_1062": "Typ jest przywoływany bezpośrednio lub pośrednio w wywołaniu zwrotnym realizacji jego własnej metody „then”.", + "Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member_1320": "Typ operandu „await” musi być prawidłową obietnicą lub nie może zawierać wywoływalnej składowej „then”.", + "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322": "Typ iterowanych elementów operandu „yield*” musi być prawidłową obietnicą lub nie może zawierać wywoływalnej składowej „then”.", + "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321": "Typ operandu „yield” w generatorze asynchronicznym musi być prawidłową obietnicą lub nie może zawierać wywoływalnej składowej „then”.", + "Type_parameter_0_has_a_circular_constraint_2313": "Parametr typu „{0}” zawiera ograniczenie cykliczne.", + "Type_parameter_0_has_a_circular_default_2716": "Parametr typu „{0}” ma cykliczną wartość domyślną.", + "Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4008": "Parametr typu „{0}” sygnatury wywołania z wyeksportowanego interfejsu ma nazwę prywatną „{1}” lub używa tej nazwy.", + "Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4006": "Parametr typu „{0}” sygnatury konstruktora z wyeksportowanego interfejsu ma nazwę prywatną „{1}” lub używa tej nazwy.", + "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002": "Parametr typu „{0}” wyeksportowanej klasy ma nazwę prywatną „{1}” lub używa tej nazwy.", + "Type_parameter_0_of_exported_function_has_or_is_using_private_name_1_4016": "Parametr typu „{0}” wyeksportowanej funkcji ma nazwę prywatną „{1}” lub używa tej nazwy.", + "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004": "Parametr typu „{0}” wyeksportowanego interfejsu ma nazwę prywatną „{1}” lub używa tej nazwy.", + "Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1_4083": "Parametr typu „{0}” wyeksportowanego aliasu typu ma nazwę prywatną „{1}” lub jej używa.", + "Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4014": "Parametr typu „{0}” metody z wyeksportowanego interfejsu ma nazwę prywatną „{1}” lub używa tej nazwy.", + "Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4012": "Parametr typu „{0}” metody publicznej z wyeksportowanej klasy ma nazwę prywatną „{1}” lub używa tej nazwy.", + "Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4010": "Parametr typu „{0}” publicznej metody statycznej z wyeksportowanej klasy ma nazwę prywatną „{1}” lub używa tej nazwy.", + "Type_parameter_declaration_expected_1139": "Oczekiwano deklaracji parametru typu.", + "Type_parameter_list_cannot_be_empty_1098": "Lista parametrów typu nie może być pusta.", + "Type_parameter_name_cannot_be_0_2368": "Parametr typu nie może mieć nazwy „{0}”.", + "Type_parameters_cannot_appear_on_a_constructor_declaration_1092": "Parametry typu nie mogą występować w deklaracji konstruktora.", + "Type_predicate_0_is_not_assignable_to_1_1226": "Predykatu typów „{0}” nie można przypisać do elementu „{1}”.", + "Type_reference_directive_0_was_not_resolved_6120": "======== Dyrektywa odwołania do typu „{0}” nie została rozpoznana. ========", + "Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2_6119": "======== Dyrektywa odwołania do typu „{0}” została pomyślnie rozpoznana jako „{1}”, podstawowe: {2}. ========", + "Types_have_separate_declarations_of_a_private_property_0_2442": "Typy mają osobne deklaracje właściwości prywatnej „{0}”.", + "Types_of_parameters_0_and_1_are_incompatible_2328": "Typy parametrów „{0}” i „{1}” są niezgodne.", + "Types_of_property_0_are_incompatible_2326": "Typy właściwości „{0}” są niezgodne.", + "Unable_to_open_file_0_6050": "Nie można otworzyć pliku „{0}”.", + "Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression_1238": "Nie można rozpoznać sygnatury dekoratora klasy wywołanego jako wyrażenie.", + "Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression_1241": "Nie można rozpoznać sygnatury dekoratora metody wywołanego jako wyrażenie.", + "Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression_1239": "Nie można rozpoznać sygnatury dekoratora parametru wywołanego jako wyrażenie.", + "Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression_1240": "Nie można rozpoznać sygnatury dekoratora właściwości wywołanego jako wyrażenie.", + "Unexpected_end_of_text_1126": "Nieoczekiwany koniec tekstu.", + "Unexpected_token_1012": "Nieoczekiwany token.", + "Unexpected_token_A_constructor_method_accessor_or_property_was_expected_1068": "Nieoczekiwany token. Oczekiwano konstruktora, metody, metody dostępu lub właściwości.", + "Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces_1069": "Nieoczekiwany token. Oczekiwano nazwy parametru typu bez nawiasów klamrowych.", + "Unexpected_token_expected_1179": "Nieoczekiwany token. Oczekiwano znaku „{”.", + "Unknown_compiler_option_0_5023": "Nieznana opcja kompilatora „{0}”.", + "Unknown_option_excludes_Did_you_mean_exclude_6114": "Nieznana opcja „excludes”. Czy chodziło o „exclude”?", + "Unknown_type_acquisition_option_0_17010": "Opcja pozyskania nieznanego typu „{0}”.", + "Unreachable_code_detected_7027": "Wykryto nieosiągalny kod.", + "Unsupported_locale_0_6049": "Nieobsługiwane ustawienia regionalne „{0}”.", + "Unterminated_Unicode_escape_sequence_1199": "Niezakończona sekwencja ucieczki kodu Unicode.", + "Unterminated_quoted_string_in_response_file_0_6045": "Niezakończony ciąg ujęty w cudzysłów w pliku odpowiedzi „{0}”.", + "Unterminated_regular_expression_literal_1161": "Niezakończony literał wyrażenia regularnego.", + "Unterminated_string_literal_1002": "Niezakończony literał ciągu znaków.", + "Unterminated_template_literal_1160": "Niezakończony literał szablonu.", + "Untyped_function_calls_may_not_accept_type_arguments_2347": "Wywołania funkcji bez typu nie mogą przyjmować argumentów typu.", + "Unused_label_7028": "Nieużywana etykieta.", + "Updating_output_timestamps_of_project_0_6359": "Trwa aktualizowanie sygnatury czasowej danych wyjściowych projektu „{0}”...", + "Use_synthetic_default_member_95016": "Użyj syntetycznej składowej „default”.", + "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494": "Używanie ciągu w instrukcji „for...of” jest obsługiwane tylko w języku ECMAScript 5 lub nowszym.", + "VERSION_6036": "WERSJA", + "Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it_2560": "Wartość typu „{0}” nie ma żadnych wspólnych właściwości z typem „{1}”. Czy jej wywołanie było zamierzone?", + "Value_of_type_0_is_not_callable_Did_you_mean_to_include_new_2348": "Nie można wywołać wartości typu „{0}”. Czy miał zostać użyty operator „new”?", + "Variable_0_implicitly_has_an_1_type_7005": "Dla zmiennej „{0}” niejawnie określono typ „{1}”.", + "Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined_7034": "Zmienna „{0}” ma niejawnie typ „{1}” w niektórych lokalizacjach, w których nie można określić jej typu.", + "Variable_0_is_used_before_being_assigned_2454": "Zmienna „{0}” jest używana przed przypisaniem.", + "Variable_declaration_expected_1134": "Oczekiwano deklaracji zmiennej.", + "Variable_declaration_list_cannot_be_empty_1123": "Lista deklaracji zmiennych nie może być pusta.", + "Version_0_6029": "Wersja {0}", + "Watch_input_files_6005": "Obserwuj pliki wejściowe.", + "Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen_6191": "Określa, czy zachować nieaktualne dane wyjściowe konsoli w trybie śledzenia zamiast wyczyścić ekran.", + "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001": "Nie można zmienić nazw elementów zdefiniowanych w standardowej bibliotece TypeScript.", + "You_cannot_rename_this_element_8000": "Nie można zmienić nazwy tego elementu.", + "_0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write__1329": "Element „{0}” akceptuje za mało argumentów, aby można go było użyć w tym miejscu jako dekorator. Czy chcesz najpierw go wywołać i zapisać tag „@{0}()”?", + "_0_are_specified_twice_The_attribute_named_0_will_be_overwritten_2710": "Element „{0}” został określony dwa razy. Atrybut o nazwie „{0}” zostanie przesłonięty.", + "_0_can_only_be_used_in_a_ts_file_8009": "Elementu „{0}” można użyć tylko w pliku .ts.", + "_0_expected_1005": "Oczekiwano elementu „{0}”.", + "_0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_reference_7023": "Dla elementu „{0}” niejawnie określono zwracany typ „any”, ponieważ nie zawiera on adnotacji zwracanego typu i jest przywoływany bezpośrednio lub pośrednio w jednym z jego zwracanych wyrażeń.", + "_0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or__7022": "Dla elementu „{0}” niejawnie określono typ „any”, ponieważ nie zawiera on adnotacji typu i jest przywoływany bezpośrednio lub pośrednio w jego własnym inicjatorze.", + "_0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible_2692": "Element „{0}” jest elementem podstawowym, ale element „{1}” jest obiektem otoki. Preferuje się użycie elementu „{0}”, jeśli jest to możliwe.", + "_0_is_declared_but_its_value_is_never_read_6133": "Element „{0}” jest zadeklarowany, ale jego wartość nie jest nigdy odczytywana.", + "_0_is_declared_but_never_used_6196": "Element „{0}” jest zadeklarowany, ale nie jest nigdy używany.", + "_0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2_17012": "„{0}” nie jest prawidłową metawłaściwością słowa kluczowego „{1}”. Czy miał to być element „{2}”?", + "_0_is_referenced_directly_or_indirectly_in_its_own_base_expression_2506": "Element „{0}” jest przywoływany bezpośrednio lub pośrednio w jego własnym wyrażeniu podstawowym.", + "_0_is_referenced_directly_or_indirectly_in_its_own_type_annotation_2502": "Element „{0}” jest przywoływany bezpośrednio lub pośrednio w jego własnej adnotacji typu.", + "_0_list_cannot_be_empty_1097": "Lista „{0}” nie może być pusta.", + "_0_modifier_already_seen_1030": "Napotkano już modyfikator „{0}”.", + "_0_modifier_cannot_appear_on_a_class_element_1031": "Modyfikator „{0}” nie może występować w elemencie klasy.", + "_0_modifier_cannot_appear_on_a_constructor_declaration_1089": "Modyfikator „{0}” nie może występować w deklaracji konstruktora.", + "_0_modifier_cannot_appear_on_a_data_property_1043": "Modyfikator „{0}” nie może występować we właściwości danych.", + "_0_modifier_cannot_appear_on_a_module_or_namespace_element_1044": "Modyfikator „{0}” nie może być stosowany w przypadku elementu przestrzeni nazw lub modułu.", + "_0_modifier_cannot_appear_on_a_parameter_1090": "Modyfikator „{0}” nie może występować w parametrze.", + "_0_modifier_cannot_appear_on_a_type_member_1070": "Modyfikator „{0}” nie może być stosowany w przypadku składowej typu.", + "_0_modifier_cannot_appear_on_an_index_signature_1071": "Modyfikator „{0}” nie może być stosowany w przypadku sygnatury indeksu.", + "_0_modifier_cannot_be_used_here_1042": "Modyfikatora „{0}” nie można użyć w tym miejscu.", + "_0_modifier_cannot_be_used_in_an_ambient_context_1040": "Modyfikatora „{0}” nie można użyć w otaczającym kontekście.", + "_0_modifier_cannot_be_used_with_1_modifier_1243": "Modyfikatora „{0}” nie można używać z modyfikatorem „{1}”.", + "_0_modifier_cannot_be_used_with_a_class_declaration_1041": "Modyfikatora „{0}” nie można używać z deklaracją klasy.", + "_0_modifier_must_precede_1_modifier_1029": "Modyfikator „{0}” musi występować przed modyfikatorem „{1}”.", + "_0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here_2702": "Element „{0}” odwołuje się tylko do typu, ale jest używany tutaj jako przestrzeń nazw.", + "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_2693": "Element „{0}” odwołuje się jedynie do typu, ale jest używany w tym miejscu jako wartość.", + "_0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead_2686": "„{0}” odnosi się do globalnego formatu UMD, ale bieżący plik jest modułem. Rozważ zamiast tego dodanie importu.", + "_0_tag_already_specified_1223": "Tag „{0}” jest już określony.", + "_0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag_1253": "Tag „{0}” nie może być użyty niezależnie jako tag JSDoc najwyższego poziomu.", + "_0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type_7010": "Dla elementu „{0}” bez adnotacji zwracanego typu niejawnie określono zwracany typ „{1}”.", + "abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration_1242": "Modyfikator „abstract” może być stosowany jedynie w przypadku deklaracji klasy, metody lub właściwości.", + "await_expression_is_only_allowed_within_an_async_function_1308": "Wyrażenie „await” jest dozwolone tylko w funkcji asynchronicznej.", + "await_expressions_cannot_be_used_in_a_parameter_initializer_2524": "Wyrażeń „await” nie można używać w inicjatorze parametru.", + "baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1_6106": "Opcja „baseUrl” ma ustawioną wartość „{0}”. Ta wartość zostanie użyta do rozpoznania innej niż względna nazwy modułu „{1}”.", + "can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment_1312": "Znaku „=” można użyć tylko we właściwości literału obiektu wewnątrz przypisania usuwającego strukturę.", + "case_or_default_expected_1130": "Oczekiwano elementu „case” lub „default”.", + "class_expressions_are_not_currently_supported_9003": "Wyrażenia „class” nie są obecnie obsługiwane.", + "const_declarations_can_only_be_declared_inside_a_block_1156": "Deklaracje „const” mogą być deklarowane tylko w bloku.", + "const_declarations_must_be_initialized_1155": "Konieczne jest zainicjowanie deklaracji „const”.", + "const_enum_member_initializer_was_evaluated_to_a_non_finite_value_2477": "Wynikiem obliczenia inicjatora składowej wyliczenia ze specyfikatorem „const” jest wartość nieskończona.", + "const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN_2478": "Wynikiem obliczenia inicjatora składowej wyliczenia ze specyfikatorem „const” jest niedozwolona wartość „NaN”.", + "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475": "Wyliczenia ze specyfikatorem „const” mogą być używane tylko w wyrażeniach dostępu do indeksu lub właściwości albo po prawej stronie deklaracji importu, przypisania eksportu lub typu zapytania.", + "delete_cannot_be_called_on_an_identifier_in_strict_mode_1102": "Nie można wywołać elementu „delete” dla identyfikatora w trybie z ograniczeniami.", + "delete_this_Project_0_is_up_to_date_because_it_was_previously_built_6360": "usuń to — projekt „{0}” jest aktualny, ponieważ został wcześniej skompilowany", + "enum_declarations_can_only_be_used_in_a_ts_file_8015": "Deklaracji enum można używać tylko w pliku ts.", + "export_can_only_be_used_in_a_ts_file_8003": "Ciągu „export=” można użyć tylko w pliku ts.", + "export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always__2668": "Modyfikator „export” nie może być stosowany do modułów otoczenia ani rozszerzeń modułów, ponieważ są one zawsze widoczne.", + "extends_clause_already_seen_1172": "Napotkano już klauzulę „extends”.", + "extends_clause_must_precede_implements_clause_1173": "Klauzula „extends” musi poprzedzać klauzulę „implements”.", + "extends_clause_of_exported_class_0_has_or_is_using_private_name_1_4020": "Klauzula „extends” wyeksportowanej klasy „{0}” ma nazwę prywatną „{1}” lub używa tej nazwy.", + "extends_clause_of_exported_interface_0_has_or_is_using_private_name_1_4022": "Klauzula „extends” wyeksportowanego interfejsu „{0}” ma nazwę prywatną „{1}” lub używa tej nazwy.", + "file_6025": "plik", + "get_and_set_accessor_must_have_the_same_this_type_2682": "Metody dostępu „get” i „set” muszą mieć ten sam typ „this”.", + "get_and_set_accessor_must_have_the_same_type_2380": "Metody dostępu „get” i „set” muszą być tego samego typu.", + "implements_clause_already_seen_1175": "Napotkano już klauzulę „implements”.", + "implements_clauses_can_only_be_used_in_a_ts_file_8005": "Klauzul implements można używać tylko w pliku ts.", + "import_can_only_be_used_in_a_ts_file_8002": "Ciągu „export ... =” można użyć tylko w pliku ts.", + "infer_declarations_are_only_permitted_in_the_extends_clause_of_a_conditional_type_1338": "Deklaracje „infer” są dozwolone tylko w klauzuli „extends” typu warunkowego.", + "interface_declarations_can_only_be_used_in_a_ts_file_8006": "Deklaracji interfejsów można używać tylko w pliku ts.", + "let_declarations_can_only_be_declared_inside_a_block_1157": "Deklaracje „let” mogą być deklarowane tylko w bloku.", + "let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations_2480": "Element „let” nie może być używany jako nazwa w deklaracjach „let” ani „const”.", + "module_declarations_can_only_be_used_in_a_ts_file_8007": "Deklaracji modułów można używać tylko w pliku ts.", + "new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead_1150": "Nie można użyć instrukcji „new T[]” do utworzenia tablicy. Zamiast tego użyj instrukcji „new Array()”.", + "new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type_7009": "Wyrażenie „new”, którego element docelowy nie ma sygnatury konstrukcji, jest niejawnie typu „any”.", + "non_null_assertions_can_only_be_used_in_a_ts_file_8013": "Asercje o wartości innej niż null mogą być używane tylko w pliku ts.", + "options_6024": "opcje", + "or_expected_1144": "Oczekiwano znaku „{” lub „;”.", + "package_json_does_not_have_a_0_field_6100": "Plik „package.json” nie zawiera pola „{0}”.", + "package_json_has_0_field_1_that_references_2_6101": "Plik „package.json” zawiera pole „{0}” „{1}” odwołujące się do elementu „{2}”.", + "parameter_modifiers_can_only_be_used_in_a_ts_file_8012": "Modyfikatorów parametrów można używać tylko w pliku ts.", + "paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0_6091": "Opcja „paths” została określona. Wyszukiwanie wzorca zgodnego z nazwą modułu „{0}”.", + "readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024": "Modyfikator „readonly” może występować jedynie w deklaracji właściwości lub sygnaturze indeksu.", + "require_call_may_be_converted_to_an_import_80005": "Wywołanie „require” może zostać przekonwertowane na wywołanie import.", + "rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107": "Opcja „rootDirs” została ustawiona. Zostanie ona użyta do rozpoznania względnej nazwy modułu „{0}”.", + "super_can_only_be_referenced_in_a_derived_class_2335": "Element „super” może być przywoływany tylko w klasie pochodnej.", + "super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions_2660": "Element „super” może być przywoływany jedynie w składowych klas pochodnych lub wyrażeń literałów obiektów.", + "super_cannot_be_referenced_in_a_computed_property_name_2466": "Nie można przywołać elementu „super” w obliczonej nazwie właściwości.", + "super_cannot_be_referenced_in_constructor_arguments_2336": "Nie można przywoływać elementu „super” w argumentach konstruktora.", + "super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_highe_2659": "Element „super” jest dozwolony w składowych wyrażeń literałów obiektów tylko wtedy, gdy opcja „target” ma wartość „ES2015” lub wyższą.", + "super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class_17011": "Element „super” należy wywołać przed uzyskaniem dostępu do właściwości elementu „super” w konstruktorze klasy pochodnej.", + "super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class_17009": "Element „super” musi być wywoływany przed uzyskaniem dostępu do elementu „this” w konstruktorze klasy pochodnej.", + "super_must_be_followed_by_an_argument_list_or_member_access_1034": "Po elemencie „super” musi występować lista argumentów lub metoda dostępu do składowej.", + "super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_der_2338": "Dostęp do właściwości „super” jest dozwolony tylko w konstruktorze, funkcji składowej lub metodzie dostępu składowej klasy pochodnej.", + "this_cannot_be_referenced_in_a_computed_property_name_2465": "Nie można przywołać elementu „this” w obliczonej nazwie właściwości.", + "this_cannot_be_referenced_in_a_module_or_namespace_body_2331": "Nie można przywołać elementu „this” w treści modułu ani przestrzeni nazw.", + "this_cannot_be_referenced_in_a_static_property_initializer_2334": "Nie można przywołać elementu „this” w inicjatorze właściwości statycznej.", + "this_cannot_be_referenced_in_constructor_arguments_2333": "Nie można przywołać elementu „this” w argumentach konstruktora.", + "this_cannot_be_referenced_in_current_location_2332": "Nie można przywołać elementu „this” w bieżącej lokalizacji.", + "this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_2683": "Element „this” niejawnie przyjmuje typ „any”, ponieważ nie ma adnotacji typu.", + "type_aliases_can_only_be_used_in_a_ts_file_8008": "Aliasów typów można używać tylko w pliku ts.", + "type_arguments_can_only_be_used_in_a_ts_file_8011": "Argumentów typu można używać tylko w pliku ts.", + "type_assertion_expressions_can_only_be_used_in_a_ts_file_8016": "Wyrażeń asercji typów można używać tylko w pliku ts.", + "type_parameter_declarations_can_only_be_used_in_a_ts_file_8004": "Deklaracji parametru typu można używać tylko w pliku ts.", + "types_can_only_be_used_in_a_ts_file_8010": "Typów można używać tylko w pliku ts.", + "unique_symbol_types_are_not_allowed_here_1335": "Typy „unique symbol” nie są dozwolone w tym miejscu.", + "unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement_1334": "Typy „unique symbol” są dozwolone tylko w zmiennych w instrukcji zmiennej.", + "unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name_1333": "Typów „unique symbol” nie można używać w deklaracji zmiennej z nazwą powiązania.", + "with_statements_are_not_allowed_in_an_async_function_block_1300": "Instrukcje „with” są niedozwolone w bloku funkcji asynchronicznej.", + "with_statements_are_not_allowed_in_strict_mode_1101": "Instrukcje „with” są niedozwolone w trybie z ograniczeniami.", + "yield_expressions_cannot_be_used_in_a_parameter_initializer_2523": "Wyrażeń „yield” nie można używać w inicjatorze parametru." +} \ No newline at end of file diff --git a/node_modules/typescript/lib/protocol.d.ts b/node_modules/typescript/lib/protocol.d.ts new file mode 100644 index 0000000..74855bf --- /dev/null +++ b/node_modules/typescript/lib/protocol.d.ts @@ -0,0 +1,2552 @@ +/** + * Declaration module describing the TypeScript Server protocol + */ +declare namespace ts.server.protocol { + const enum CommandTypes { + JsxClosingTag = "jsxClosingTag", + Brace = "brace", + BraceCompletion = "braceCompletion", + GetSpanOfEnclosingComment = "getSpanOfEnclosingComment", + Change = "change", + Close = "close", + /** @deprecated Prefer CompletionInfo -- see comment on CompletionsResponse */ + Completions = "completions", + CompletionInfo = "completionInfo", + CompletionDetails = "completionEntryDetails", + CompileOnSaveAffectedFileList = "compileOnSaveAffectedFileList", + CompileOnSaveEmitFile = "compileOnSaveEmitFile", + Configure = "configure", + Definition = "definition", + DefinitionAndBoundSpan = "definitionAndBoundSpan", + Implementation = "implementation", + Exit = "exit", + Format = "format", + Formatonkey = "formatonkey", + Geterr = "geterr", + GeterrForProject = "geterrForProject", + SemanticDiagnosticsSync = "semanticDiagnosticsSync", + SyntacticDiagnosticsSync = "syntacticDiagnosticsSync", + SuggestionDiagnosticsSync = "suggestionDiagnosticsSync", + NavBar = "navbar", + Navto = "navto", + NavTree = "navtree", + NavTreeFull = "navtree-full", + /** @deprecated */ + Occurrences = "occurrences", + DocumentHighlights = "documentHighlights", + Open = "open", + Quickinfo = "quickinfo", + References = "references", + Reload = "reload", + Rename = "rename", + Saveto = "saveto", + SignatureHelp = "signatureHelp", + Status = "status", + TypeDefinition = "typeDefinition", + ProjectInfo = "projectInfo", + ReloadProjects = "reloadProjects", + Unknown = "unknown", + OpenExternalProject = "openExternalProject", + OpenExternalProjects = "openExternalProjects", + CloseExternalProject = "closeExternalProject", + GetOutliningSpans = "getOutliningSpans", + TodoComments = "todoComments", + Indentation = "indentation", + DocCommentTemplate = "docCommentTemplate", + CompilerOptionsForInferredProjects = "compilerOptionsForInferredProjects", + GetCodeFixes = "getCodeFixes", + GetCombinedCodeFix = "getCombinedCodeFix", + ApplyCodeActionCommand = "applyCodeActionCommand", + GetSupportedCodeFixes = "getSupportedCodeFixes", + GetApplicableRefactors = "getApplicableRefactors", + GetEditsForRefactor = "getEditsForRefactor", + OrganizeImports = "organizeImports", + GetEditsForFileRename = "getEditsForFileRename", + ConfigurePlugin = "configurePlugin" + } + /** + * A TypeScript Server message + */ + interface Message { + /** + * Sequence number of the message + */ + seq: number; + /** + * One of "request", "response", or "event" + */ + type: "request" | "response" | "event"; + } + /** + * Client-initiated request message + */ + interface Request extends Message { + type: "request"; + /** + * The command to execute + */ + command: string; + /** + * Object containing arguments for the command + */ + arguments?: any; + } + /** + * Request to reload the project structure for all the opened files + */ + interface ReloadProjectsRequest extends Message { + command: CommandTypes.ReloadProjects; + } + /** + * Server-initiated event message + */ + interface Event extends Message { + type: "event"; + /** + * Name of event + */ + event: string; + /** + * Event-specific information + */ + body?: any; + } + /** + * Response by server to client request message. + */ + interface Response extends Message { + type: "response"; + /** + * Sequence number of the request message. + */ + request_seq: number; + /** + * Outcome of the request. + */ + success: boolean; + /** + * The command requested. + */ + command: string; + /** + * If success === false, this should always be provided. + * Otherwise, may (or may not) contain a success message. + */ + message?: string; + /** + * Contains message body if success === true. + */ + body?: any; + /** + * Contains extra information that plugin can include to be passed on + */ + metadata?: unknown; + } + /** + * Arguments for FileRequest messages. + */ + interface FileRequestArgs { + /** + * The file for the request (absolute pathname required). + */ + file: string; + projectFileName?: string; + } + interface StatusRequest extends Request { + command: CommandTypes.Status; + } + interface StatusResponseBody { + /** + * The TypeScript version (`ts.version`). + */ + version: string; + } + /** + * Response to StatusRequest + */ + interface StatusResponse extends Response { + body: StatusResponseBody; + } + /** + * Requests a JS Doc comment template for a given position + */ + interface DocCommentTemplateRequest extends FileLocationRequest { + command: CommandTypes.DocCommentTemplate; + } + /** + * Response to DocCommentTemplateRequest + */ + interface DocCommandTemplateResponse extends Response { + body?: TextInsertion; + } + /** + * A request to get TODO comments from the file + */ + interface TodoCommentRequest extends FileRequest { + command: CommandTypes.TodoComments; + arguments: TodoCommentRequestArgs; + } + /** + * Arguments for TodoCommentRequest request. + */ + interface TodoCommentRequestArgs extends FileRequestArgs { + /** + * Array of target TodoCommentDescriptors that describes TODO comments to be found + */ + descriptors: TodoCommentDescriptor[]; + } + /** + * Response for TodoCommentRequest request. + */ + interface TodoCommentsResponse extends Response { + body?: TodoComment[]; + } + /** + * A request to determine if the caret is inside a comment. + */ + interface SpanOfEnclosingCommentRequest extends FileLocationRequest { + command: CommandTypes.GetSpanOfEnclosingComment; + arguments: SpanOfEnclosingCommentRequestArgs; + } + interface SpanOfEnclosingCommentRequestArgs extends FileLocationRequestArgs { + /** + * Requires that the enclosing span be a multi-line comment, or else the request returns undefined. + */ + onlyMultiLine: boolean; + } + /** + * Request to obtain outlining spans in file. + */ + interface OutliningSpansRequest extends FileRequest { + command: CommandTypes.GetOutliningSpans; + } + interface OutliningSpan { + /** The span of the document to actually collapse. */ + textSpan: TextSpan; + /** The span of the document to display when the user hovers over the collapsed span. */ + hintSpan: TextSpan; + /** The text to display in the editor for the collapsed region. */ + bannerText: string; + /** + * Whether or not this region should be automatically collapsed when + * the 'Collapse to Definitions' command is invoked. + */ + autoCollapse: boolean; + /** + * Classification of the contents of the span + */ + kind: OutliningSpanKind; + } + /** + * Response to OutliningSpansRequest request. + */ + interface OutliningSpansResponse extends Response { + body?: OutliningSpan[]; + } + /** + * A request to get indentation for a location in file + */ + interface IndentationRequest extends FileLocationRequest { + command: CommandTypes.Indentation; + arguments: IndentationRequestArgs; + } + /** + * Response for IndentationRequest request. + */ + interface IndentationResponse extends Response { + body?: IndentationResult; + } + /** + * Indentation result representing where indentation should be placed + */ + interface IndentationResult { + /** + * The base position in the document that the indent should be relative to + */ + position: number; + /** + * The number of columns the indent should be at relative to the position's column. + */ + indentation: number; + } + /** + * Arguments for IndentationRequest request. + */ + interface IndentationRequestArgs extends FileLocationRequestArgs { + /** + * An optional set of settings to be used when computing indentation. + * If argument is omitted - then it will use settings for file that were previously set via 'configure' request or global settings. + */ + options?: EditorSettings; + } + /** + * Arguments for ProjectInfoRequest request. + */ + interface ProjectInfoRequestArgs extends FileRequestArgs { + /** + * Indicate if the file name list of the project is needed + */ + needFileNameList: boolean; + } + /** + * A request to get the project information of the current file. + */ + interface ProjectInfoRequest extends Request { + command: CommandTypes.ProjectInfo; + arguments: ProjectInfoRequestArgs; + } + /** + * A request to retrieve compiler options diagnostics for a project + */ + interface CompilerOptionsDiagnosticsRequest extends Request { + arguments: CompilerOptionsDiagnosticsRequestArgs; + } + /** + * Arguments for CompilerOptionsDiagnosticsRequest request. + */ + interface CompilerOptionsDiagnosticsRequestArgs { + /** + * Name of the project to retrieve compiler options diagnostics. + */ + projectFileName: string; + } + /** + * Response message body for "projectInfo" request + */ + interface ProjectInfo { + /** + * For configured project, this is the normalized path of the 'tsconfig.json' file + * For inferred project, this is undefined + */ + configFileName: string; + /** + * The list of normalized file name in the project, including 'lib.d.ts' + */ + fileNames?: string[]; + /** + * Indicates if the project has a active language service instance + */ + languageServiceDisabled?: boolean; + } + /** + * Represents diagnostic info that includes location of diagnostic in two forms + * - start position and length of the error span + * - startLocation and endLocation - a pair of Location objects that store start/end line and offset of the error span. + */ + interface DiagnosticWithLinePosition { + message: string; + start: number; + length: number; + startLocation: Location; + endLocation: Location; + category: string; + code: number; + /** May store more in future. For now, this will simply be `true` to indicate when a diagnostic is an unused-identifier diagnostic. */ + reportsUnnecessary?: {}; + relatedInformation?: DiagnosticRelatedInformation[]; + } + /** + * Response message for "projectInfo" request + */ + interface ProjectInfoResponse extends Response { + body?: ProjectInfo; + } + /** + * Request whose sole parameter is a file name. + */ + interface FileRequest extends Request { + arguments: FileRequestArgs; + } + /** + * Instances of this interface specify a location in a source file: + * (file, line, character offset), where line and character offset are 1-based. + */ + interface FileLocationRequestArgs extends FileRequestArgs { + /** + * The line number for the request (1-based). + */ + line: number; + /** + * The character offset (on the line) for the request (1-based). + */ + offset: number; + } + type FileLocationOrRangeRequestArgs = FileLocationRequestArgs | FileRangeRequestArgs; + /** + * Request refactorings at a given position or selection area. + */ + interface GetApplicableRefactorsRequest extends Request { + command: CommandTypes.GetApplicableRefactors; + arguments: GetApplicableRefactorsRequestArgs; + } + type GetApplicableRefactorsRequestArgs = FileLocationOrRangeRequestArgs; + /** + * Response is a list of available refactorings. + * Each refactoring exposes one or more "Actions"; a user selects one action to invoke a refactoring + */ + interface GetApplicableRefactorsResponse extends Response { + body?: ApplicableRefactorInfo[]; + } + /** + * A set of one or more available refactoring actions, grouped under a parent refactoring. + */ + interface ApplicableRefactorInfo { + /** + * The programmatic name of the refactoring + */ + name: string; + /** + * A description of this refactoring category to show to the user. + * If the refactoring gets inlined (see below), this text will not be visible. + */ + description: string; + /** + * Inlineable refactorings can have their actions hoisted out to the top level + * of a context menu. Non-inlineanable refactorings should always be shown inside + * their parent grouping. + * + * If not specified, this value is assumed to be 'true' + */ + inlineable?: boolean; + actions: RefactorActionInfo[]; + } + /** + * Represents a single refactoring action - for example, the "Extract Method..." refactor might + * offer several actions, each corresponding to a surround class or closure to extract into. + */ + interface RefactorActionInfo { + /** + * The programmatic name of the refactoring action + */ + name: string; + /** + * A description of this refactoring action to show to the user. + * If the parent refactoring is inlined away, this will be the only text shown, + * so this description should make sense by itself if the parent is inlineable=true + */ + description: string; + } + interface GetEditsForRefactorRequest extends Request { + command: CommandTypes.GetEditsForRefactor; + arguments: GetEditsForRefactorRequestArgs; + } + /** + * Request the edits that a particular refactoring action produces. + * Callers must specify the name of the refactor and the name of the action. + */ + type GetEditsForRefactorRequestArgs = FileLocationOrRangeRequestArgs & { + refactor: string; + action: string; + }; + interface GetEditsForRefactorResponse extends Response { + body?: RefactorEditInfo; + } + interface RefactorEditInfo { + edits: FileCodeEdits[]; + /** + * An optional location where the editor should start a rename operation once + * the refactoring edits have been applied + */ + renameLocation?: Location; + renameFilename?: string; + } + /** + * Organize imports by: + * 1) Removing unused imports + * 2) Coalescing imports from the same module + * 3) Sorting imports + */ + interface OrganizeImportsRequest extends Request { + command: CommandTypes.OrganizeImports; + arguments: OrganizeImportsRequestArgs; + } + type OrganizeImportsScope = GetCombinedCodeFixScope; + interface OrganizeImportsRequestArgs { + scope: OrganizeImportsScope; + } + interface OrganizeImportsResponse extends Response { + body: ReadonlyArray; + } + interface GetEditsForFileRenameRequest extends Request { + command: CommandTypes.GetEditsForFileRename; + arguments: GetEditsForFileRenameRequestArgs; + } + /** Note: Paths may also be directories. */ + interface GetEditsForFileRenameRequestArgs { + readonly oldFilePath: string; + readonly newFilePath: string; + } + interface GetEditsForFileRenameResponse extends Response { + body: ReadonlyArray; + } + /** + * Request for the available codefixes at a specific position. + */ + interface CodeFixRequest extends Request { + command: CommandTypes.GetCodeFixes; + arguments: CodeFixRequestArgs; + } + interface GetCombinedCodeFixRequest extends Request { + command: CommandTypes.GetCombinedCodeFix; + arguments: GetCombinedCodeFixRequestArgs; + } + interface GetCombinedCodeFixResponse extends Response { + body: CombinedCodeActions; + } + interface ApplyCodeActionCommandRequest extends Request { + command: CommandTypes.ApplyCodeActionCommand; + arguments: ApplyCodeActionCommandRequestArgs; + } + interface ApplyCodeActionCommandResponse extends Response { + } + interface FileRangeRequestArgs extends FileRequestArgs { + /** + * The line number for the request (1-based). + */ + startLine: number; + /** + * The character offset (on the line) for the request (1-based). + */ + startOffset: number; + /** + * The line number for the request (1-based). + */ + endLine: number; + /** + * The character offset (on the line) for the request (1-based). + */ + endOffset: number; + } + /** + * Instances of this interface specify errorcodes on a specific location in a sourcefile. + */ + interface CodeFixRequestArgs extends FileRangeRequestArgs { + /** + * Errorcodes we want to get the fixes for. + */ + errorCodes: ReadonlyArray; + } + interface GetCombinedCodeFixRequestArgs { + scope: GetCombinedCodeFixScope; + fixId: {}; + } + interface GetCombinedCodeFixScope { + type: "file"; + args: FileRequestArgs; + } + interface ApplyCodeActionCommandRequestArgs { + /** May also be an array of commands. */ + command: {}; + } + /** + * Response for GetCodeFixes request. + */ + interface GetCodeFixesResponse extends Response { + body?: CodeAction[]; + } + /** + * A request whose arguments specify a file location (file, line, col). + */ + interface FileLocationRequest extends FileRequest { + arguments: FileLocationRequestArgs; + } + /** + * A request to get codes of supported code fixes. + */ + interface GetSupportedCodeFixesRequest extends Request { + command: CommandTypes.GetSupportedCodeFixes; + } + /** + * A response for GetSupportedCodeFixesRequest request. + */ + interface GetSupportedCodeFixesResponse extends Response { + /** + * List of error codes supported by the server. + */ + body?: string[]; + } + /** + * Arguments for EncodedSemanticClassificationsRequest request. + */ + interface EncodedSemanticClassificationsRequestArgs extends FileRequestArgs { + /** + * Start position of the span. + */ + start: number; + /** + * Length of the span. + */ + length: number; + } + /** + * Arguments in document highlight request; include: filesToSearch, file, + * line, offset. + */ + interface DocumentHighlightsRequestArgs extends FileLocationRequestArgs { + /** + * List of files to search for document highlights. + */ + filesToSearch: string[]; + } + /** + * Go to definition request; value of command field is + * "definition". Return response giving the file locations that + * define the symbol found in file at location line, col. + */ + interface DefinitionRequest extends FileLocationRequest { + command: CommandTypes.Definition; + } + interface DefinitionAndBoundSpanRequest extends FileLocationRequest { + readonly command: CommandTypes.DefinitionAndBoundSpan; + } + interface DefinitionAndBoundSpanResponse extends Response { + readonly body: DefinitionInfoAndBoundSpan; + } + /** + * Go to type request; value of command field is + * "typeDefinition". Return response giving the file locations that + * define the type for the symbol found in file at location line, col. + */ + interface TypeDefinitionRequest extends FileLocationRequest { + command: CommandTypes.TypeDefinition; + } + /** + * Go to implementation request; value of command field is + * "implementation". Return response giving the file locations that + * implement the symbol found in file at location line, col. + */ + interface ImplementationRequest extends FileLocationRequest { + command: CommandTypes.Implementation; + } + /** + * Location in source code expressed as (one-based) line and (one-based) column offset. + */ + interface Location { + line: number; + offset: number; + } + /** + * Object found in response messages defining a span of text in source code. + */ + interface TextSpan { + /** + * First character of the definition. + */ + start: Location; + /** + * One character past last character of the definition. + */ + end: Location; + } + /** + * Object found in response messages defining a span of text in a specific source file. + */ + interface FileSpan extends TextSpan { + /** + * File containing text span. + */ + file: string; + } + interface DefinitionInfoAndBoundSpan { + definitions: ReadonlyArray; + textSpan: TextSpan; + } + /** + * Definition response message. Gives text range for definition. + */ + interface DefinitionResponse extends Response { + body?: FileSpan[]; + } + interface DefinitionInfoAndBoundSpanReponse extends Response { + body?: DefinitionInfoAndBoundSpan; + } + /** + * Definition response message. Gives text range for definition. + */ + interface TypeDefinitionResponse extends Response { + body?: FileSpan[]; + } + /** + * Implementation response message. Gives text range for implementations. + */ + interface ImplementationResponse extends Response { + body?: FileSpan[]; + } + /** + * Request to get brace completion for a location in the file. + */ + interface BraceCompletionRequest extends FileLocationRequest { + command: CommandTypes.BraceCompletion; + arguments: BraceCompletionRequestArgs; + } + /** + * Argument for BraceCompletionRequest request. + */ + interface BraceCompletionRequestArgs extends FileLocationRequestArgs { + /** + * Kind of opening brace + */ + openingBrace: string; + } + interface JsxClosingTagRequest extends FileLocationRequest { + readonly command: CommandTypes.JsxClosingTag; + readonly arguments: JsxClosingTagRequestArgs; + } + interface JsxClosingTagRequestArgs extends FileLocationRequestArgs { + } + interface JsxClosingTagResponse extends Response { + readonly body: TextInsertion; + } + /** + * @deprecated + * Get occurrences request; value of command field is + * "occurrences". Return response giving spans that are relevant + * in the file at a given line and column. + */ + interface OccurrencesRequest extends FileLocationRequest { + command: CommandTypes.Occurrences; + } + /** @deprecated */ + interface OccurrencesResponseItem extends FileSpan { + /** + * True if the occurrence is a write location, false otherwise. + */ + isWriteAccess: boolean; + /** + * True if the occurrence is in a string, undefined otherwise; + */ + isInString?: true; + } + /** @deprecated */ + interface OccurrencesResponse extends Response { + body?: OccurrencesResponseItem[]; + } + /** + * Get document highlights request; value of command field is + * "documentHighlights". Return response giving spans that are relevant + * in the file at a given line and column. + */ + interface DocumentHighlightsRequest extends FileLocationRequest { + command: CommandTypes.DocumentHighlights; + arguments: DocumentHighlightsRequestArgs; + } + /** + * Span augmented with extra information that denotes the kind of the highlighting to be used for span. + */ + interface HighlightSpan extends TextSpan { + kind: HighlightSpanKind; + } + /** + * Represents a set of highligh spans for a give name + */ + interface DocumentHighlightsItem { + /** + * File containing highlight spans. + */ + file: string; + /** + * Spans to highlight in file. + */ + highlightSpans: HighlightSpan[]; + } + /** + * Response for a DocumentHighlightsRequest request. + */ + interface DocumentHighlightsResponse extends Response { + body?: DocumentHighlightsItem[]; + } + /** + * Find references request; value of command field is + * "references". Return response giving the file locations that + * reference the symbol found in file at location line, col. + */ + interface ReferencesRequest extends FileLocationRequest { + command: CommandTypes.References; + } + interface ReferencesResponseItem extends FileSpan { + /** Text of line containing the reference. Including this + * with the response avoids latency of editor loading files + * to show text of reference line (the server already has + * loaded the referencing files). + */ + lineText: string; + /** + * True if reference is a write location, false otherwise. + */ + isWriteAccess: boolean; + /** + * True if reference is a definition, false otherwise. + */ + isDefinition: boolean; + } + /** + * The body of a "references" response message. + */ + interface ReferencesResponseBody { + /** + * The file locations referencing the symbol. + */ + refs: ReadonlyArray; + /** + * The name of the symbol. + */ + symbolName: string; + /** + * The start character offset of the symbol (on the line provided by the references request). + */ + symbolStartOffset: number; + /** + * The full display name of the symbol. + */ + symbolDisplayString: string; + } + /** + * Response to "references" request. + */ + interface ReferencesResponse extends Response { + body?: ReferencesResponseBody; + } + /** + * Argument for RenameRequest request. + */ + interface RenameRequestArgs extends FileLocationRequestArgs { + /** + * Should text at specified location be found/changed in comments? + */ + findInComments?: boolean; + /** + * Should text at specified location be found/changed in strings? + */ + findInStrings?: boolean; + } + /** + * Rename request; value of command field is "rename". Return + * response giving the file locations that reference the symbol + * found in file at location line, col. Also return full display + * name of the symbol so that client can print it unambiguously. + */ + interface RenameRequest extends FileLocationRequest { + command: CommandTypes.Rename; + arguments: RenameRequestArgs; + } + /** + * Information about the item to be renamed. + */ + type RenameInfo = RenameInfoSuccess | RenameInfoFailure; + interface RenameInfoSuccess { + /** + * True if item can be renamed. + */ + canRename: true; + /** + * File or directory to rename. + * If set, `getEditsForFileRename` should be called instead of `findRenameLocations`. + */ + fileToRename?: string; + /** + * Display name of the item to be renamed. + */ + displayName: string; + /** + * Full display name of item to be renamed. + */ + fullDisplayName: string; + /** + * The items's kind (such as 'className' or 'parameterName' or plain 'text'). + */ + kind: ScriptElementKind; + /** + * Optional modifiers for the kind (such as 'public'). + */ + kindModifiers: string; + /** Span of text to rename. */ + triggerSpan: TextSpan; + } + interface RenameInfoFailure { + canRename: false; + /** + * Error message if item can not be renamed. + */ + localizedErrorMessage: string; + } + /** + * A group of text spans, all in 'file'. + */ + interface SpanGroup { + /** The file to which the spans apply */ + file: string; + /** The text spans in this group */ + locs: RenameTextSpan[]; + } + interface RenameTextSpan extends TextSpan { + readonly prefixText?: string; + readonly suffixText?: string; + } + interface RenameResponseBody { + /** + * Information about the item to be renamed. + */ + info: RenameInfo; + /** + * An array of span groups (one per file) that refer to the item to be renamed. + */ + locs: ReadonlyArray; + } + /** + * Rename response message. + */ + interface RenameResponse extends Response { + body?: RenameResponseBody; + } + /** + * Represents a file in external project. + * External project is project whose set of files, compilation options and open\close state + * is maintained by the client (i.e. if all this data come from .csproj file in Visual Studio). + * External project will exist even if all files in it are closed and should be closed explicitly. + * If external project includes one or more tsconfig.json/jsconfig.json files then tsserver will + * create configured project for every config file but will maintain a link that these projects were created + * as a result of opening external project so they should be removed once external project is closed. + */ + interface ExternalFile { + /** + * Name of file file + */ + fileName: string; + /** + * Script kind of the file + */ + scriptKind?: ScriptKindName | ts.ScriptKind; + /** + * Whether file has mixed content (i.e. .cshtml file that combines html markup with C#/JavaScript) + */ + hasMixedContent?: boolean; + /** + * Content of the file + */ + content?: string; + } + /** + * Represent an external project + */ + interface ExternalProject { + /** + * Project name + */ + projectFileName: string; + /** + * List of root files in project + */ + rootFiles: ExternalFile[]; + /** + * Compiler options for the project + */ + options: ExternalProjectCompilerOptions; + /** + * @deprecated typingOptions. Use typeAcquisition instead + */ + typingOptions?: TypeAcquisition; + /** + * Explicitly specified type acquisition for the project + */ + typeAcquisition?: TypeAcquisition; + } + interface CompileOnSaveMixin { + /** + * If compile on save is enabled for the project + */ + compileOnSave?: boolean; + } + /** + * For external projects, some of the project settings are sent together with + * compiler settings. + */ + type ExternalProjectCompilerOptions = CompilerOptions & CompileOnSaveMixin; + /** + * Represents a set of changes that happen in project + */ + interface ProjectChanges { + /** + * List of added files + */ + added: string[]; + /** + * List of removed files + */ + removed: string[]; + /** + * List of updated files + */ + updated: string[]; + } + /** + * Information found in a configure request. + */ + interface ConfigureRequestArguments { + /** + * Information about the host, for example 'Emacs 24.4' or + * 'Sublime Text version 3075' + */ + hostInfo?: string; + /** + * If present, tab settings apply only to this file. + */ + file?: string; + /** + * The format options to use during formatting and other code editing features. + */ + formatOptions?: FormatCodeSettings; + preferences?: UserPreferences; + /** + * The host's additional supported .js file extensions + */ + extraFileExtensions?: FileExtensionInfo[]; + } + /** + * Configure request; value of command field is "configure". Specifies + * host information, such as host type, tab size, and indent size. + */ + interface ConfigureRequest extends Request { + command: CommandTypes.Configure; + arguments: ConfigureRequestArguments; + } + /** + * Response to "configure" request. This is just an acknowledgement, so + * no body field is required. + */ + interface ConfigureResponse extends Response { + } + interface ConfigurePluginRequestArguments { + pluginName: string; + configuration: any; + } + interface ConfigurePluginRequest extends Request { + command: CommandTypes.ConfigurePlugin; + arguments: ConfigurePluginRequestArguments; + } + /** + * Information found in an "open" request. + */ + interface OpenRequestArgs extends FileRequestArgs { + /** + * Used when a version of the file content is known to be more up to date than the one on disk. + * Then the known content will be used upon opening instead of the disk copy + */ + fileContent?: string; + /** + * Used to specify the script kind of the file explicitly. It could be one of the following: + * "TS", "JS", "TSX", "JSX" + */ + scriptKindName?: ScriptKindName; + /** + * Used to limit the searching for project config file. If given the searching will stop at this + * root path; otherwise it will go all the way up to the dist root path. + */ + projectRootPath?: string; + } + type ScriptKindName = "TS" | "JS" | "TSX" | "JSX"; + /** + * Open request; value of command field is "open". Notify the + * server that the client has file open. The server will not + * monitor the filesystem for changes in this file and will assume + * that the client is updating the server (using the change and/or + * reload messages) when the file changes. Server does not currently + * send a response to an open request. + */ + interface OpenRequest extends Request { + command: CommandTypes.Open; + arguments: OpenRequestArgs; + } + /** + * Request to open or update external project + */ + interface OpenExternalProjectRequest extends Request { + command: CommandTypes.OpenExternalProject; + arguments: OpenExternalProjectArgs; + } + /** + * Arguments to OpenExternalProjectRequest request + */ + type OpenExternalProjectArgs = ExternalProject; + /** + * Request to open multiple external projects + */ + interface OpenExternalProjectsRequest extends Request { + command: CommandTypes.OpenExternalProjects; + arguments: OpenExternalProjectsArgs; + } + /** + * Arguments to OpenExternalProjectsRequest + */ + interface OpenExternalProjectsArgs { + /** + * List of external projects to open or update + */ + projects: ExternalProject[]; + } + /** + * Response to OpenExternalProjectRequest request. This is just an acknowledgement, so + * no body field is required. + */ + interface OpenExternalProjectResponse extends Response { + } + /** + * Response to OpenExternalProjectsRequest request. This is just an acknowledgement, so + * no body field is required. + */ + interface OpenExternalProjectsResponse extends Response { + } + /** + * Request to close external project. + */ + interface CloseExternalProjectRequest extends Request { + command: CommandTypes.CloseExternalProject; + arguments: CloseExternalProjectRequestArgs; + } + /** + * Arguments to CloseExternalProjectRequest request + */ + interface CloseExternalProjectRequestArgs { + /** + * Name of the project to close + */ + projectFileName: string; + } + /** + * Response to CloseExternalProjectRequest request. This is just an acknowledgement, so + * no body field is required. + */ + interface CloseExternalProjectResponse extends Response { + } + /** + * Request to set compiler options for inferred projects. + * External projects are opened / closed explicitly. + * Configured projects are opened when user opens loose file that has 'tsconfig.json' or 'jsconfig.json' anywhere in one of containing folders. + * This configuration file will be used to obtain a list of files and configuration settings for the project. + * Inferred projects are created when user opens a loose file that is not the part of external project + * or configured project and will contain only open file and transitive closure of referenced files if 'useOneInferredProject' is false, + * or all open loose files and its transitive closure of referenced files if 'useOneInferredProject' is true. + */ + interface SetCompilerOptionsForInferredProjectsRequest extends Request { + command: CommandTypes.CompilerOptionsForInferredProjects; + arguments: SetCompilerOptionsForInferredProjectsArgs; + } + /** + * Argument for SetCompilerOptionsForInferredProjectsRequest request. + */ + interface SetCompilerOptionsForInferredProjectsArgs { + /** + * Compiler options to be used with inferred projects. + */ + options: ExternalProjectCompilerOptions; + /** + * Specifies the project root path used to scope compiler options. + * It is an error to provide this property if the server has not been started with + * `useInferredProjectPerProjectRoot` enabled. + */ + projectRootPath?: string; + } + /** + * Response to SetCompilerOptionsForInferredProjectsResponse request. This is just an acknowledgement, so + * no body field is required. + */ + interface SetCompilerOptionsForInferredProjectsResponse extends Response { + } + /** + * Exit request; value of command field is "exit". Ask the server process + * to exit. + */ + interface ExitRequest extends Request { + command: CommandTypes.Exit; + } + /** + * Close request; value of command field is "close". Notify the + * server that the client has closed a previously open file. If + * file is still referenced by open files, the server will resume + * monitoring the filesystem for changes to file. Server does not + * currently send a response to a close request. + */ + interface CloseRequest extends FileRequest { + command: CommandTypes.Close; + } + /** + * Request to obtain the list of files that should be regenerated if target file is recompiled. + * NOTE: this us query-only operation and does not generate any output on disk. + */ + interface CompileOnSaveAffectedFileListRequest extends FileRequest { + command: CommandTypes.CompileOnSaveAffectedFileList; + } + /** + * Contains a list of files that should be regenerated in a project + */ + interface CompileOnSaveAffectedFileListSingleProject { + /** + * Project name + */ + projectFileName: string; + /** + * List of files names that should be recompiled + */ + fileNames: string[]; + /** + * true if project uses outFile or out compiler option + */ + projectUsesOutFile: boolean; + } + /** + * Response for CompileOnSaveAffectedFileListRequest request; + */ + interface CompileOnSaveAffectedFileListResponse extends Response { + body: CompileOnSaveAffectedFileListSingleProject[]; + } + /** + * Request to recompile the file. All generated outputs (.js, .d.ts or .js.map files) is written on disk. + */ + interface CompileOnSaveEmitFileRequest extends FileRequest { + command: CommandTypes.CompileOnSaveEmitFile; + arguments: CompileOnSaveEmitFileRequestArgs; + } + /** + * Arguments for CompileOnSaveEmitFileRequest + */ + interface CompileOnSaveEmitFileRequestArgs extends FileRequestArgs { + /** + * if true - then file should be recompiled even if it does not have any changes. + */ + forced?: boolean; + } + /** + * Quickinfo request; value of command field is + * "quickinfo". Return response giving a quick type and + * documentation string for the symbol found in file at location + * line, col. + */ + interface QuickInfoRequest extends FileLocationRequest { + command: CommandTypes.Quickinfo; + } + /** + * Body of QuickInfoResponse. + */ + interface QuickInfoResponseBody { + /** + * The symbol's kind (such as 'className' or 'parameterName' or plain 'text'). + */ + kind: ScriptElementKind; + /** + * Optional modifiers for the kind (such as 'public'). + */ + kindModifiers: string; + /** + * Starting file location of symbol. + */ + start: Location; + /** + * One past last character of symbol. + */ + end: Location; + /** + * Type and kind of symbol. + */ + displayString: string; + /** + * Documentation associated with symbol. + */ + documentation: string; + /** + * JSDoc tags associated with symbol. + */ + tags: JSDocTagInfo[]; + } + /** + * Quickinfo response message. + */ + interface QuickInfoResponse extends Response { + body?: QuickInfoResponseBody; + } + /** + * Arguments for format messages. + */ + interface FormatRequestArgs extends FileLocationRequestArgs { + /** + * Last line of range for which to format text in file. + */ + endLine: number; + /** + * Character offset on last line of range for which to format text in file. + */ + endOffset: number; + /** + * Format options to be used. + */ + options?: FormatCodeSettings; + } + /** + * Format request; value of command field is "format". Return + * response giving zero or more edit instructions. The edit + * instructions will be sorted in file order. Applying the edit + * instructions in reverse to file will result in correctly + * reformatted text. + */ + interface FormatRequest extends FileLocationRequest { + command: CommandTypes.Format; + arguments: FormatRequestArgs; + } + /** + * Object found in response messages defining an editing + * instruction for a span of text in source code. The effect of + * this instruction is to replace the text starting at start and + * ending one character before end with newText. For an insertion, + * the text span is empty. For a deletion, newText is empty. + */ + interface CodeEdit { + /** + * First character of the text span to edit. + */ + start: Location; + /** + * One character past last character of the text span to edit. + */ + end: Location; + /** + * Replace the span defined above with this string (may be + * the empty string). + */ + newText: string; + } + interface FileCodeEdits { + fileName: string; + textChanges: CodeEdit[]; + } + interface CodeFixResponse extends Response { + /** The code actions that are available */ + body?: CodeFixAction[]; + } + interface CodeAction { + /** Description of the code action to display in the UI of the editor */ + description: string; + /** Text changes to apply to each file as part of the code action */ + changes: FileCodeEdits[]; + /** A command is an opaque object that should be passed to `ApplyCodeActionCommandRequestArgs` without modification. */ + commands?: {}[]; + } + interface CombinedCodeActions { + changes: ReadonlyArray; + commands?: ReadonlyArray<{}>; + } + interface CodeFixAction extends CodeAction { + /** Short name to identify the fix, for use by telemetry. */ + fixName: string; + /** + * If present, one may call 'getCombinedCodeFix' with this fixId. + * This may be omitted to indicate that the code fix can't be applied in a group. + */ + fixId?: {}; + /** Should be present if and only if 'fixId' is. */ + fixAllDescription?: string; + } + /** + * Format and format on key response message. + */ + interface FormatResponse extends Response { + body?: CodeEdit[]; + } + /** + * Arguments for format on key messages. + */ + interface FormatOnKeyRequestArgs extends FileLocationRequestArgs { + /** + * Key pressed (';', '\n', or '}'). + */ + key: string; + options?: FormatCodeSettings; + } + /** + * Format on key request; value of command field is + * "formatonkey". Given file location and key typed (as string), + * return response giving zero or more edit instructions. The + * edit instructions will be sorted in file order. Applying the + * edit instructions in reverse to file will result in correctly + * reformatted text. + */ + interface FormatOnKeyRequest extends FileLocationRequest { + command: CommandTypes.Formatonkey; + arguments: FormatOnKeyRequestArgs; + } + type CompletionsTriggerCharacter = "." | '"' | "'" | "`" | "/" | "@" | "<"; + /** + * Arguments for completions messages. + */ + interface CompletionsRequestArgs extends FileLocationRequestArgs { + /** + * Optional prefix to apply to possible completions. + */ + prefix?: string; + /** + * Character that was responsible for triggering completion. + * Should be `undefined` if a user manually requested completion. + */ + triggerCharacter?: CompletionsTriggerCharacter; + /** + * @deprecated Use UserPreferences.includeCompletionsForModuleExports + */ + includeExternalModuleExports?: boolean; + /** + * @deprecated Use UserPreferences.includeCompletionsWithInsertText + */ + includeInsertTextCompletions?: boolean; + } + /** + * Completions request; value of command field is "completions". + * Given a file location (file, line, col) and a prefix (which may + * be the empty string), return the possible completions that + * begin with prefix. + */ + interface CompletionsRequest extends FileLocationRequest { + command: CommandTypes.Completions | CommandTypes.CompletionInfo; + arguments: CompletionsRequestArgs; + } + /** + * Arguments for completion details request. + */ + interface CompletionDetailsRequestArgs extends FileLocationRequestArgs { + /** + * Names of one or more entries for which to obtain details. + */ + entryNames: (string | CompletionEntryIdentifier)[]; + } + interface CompletionEntryIdentifier { + name: string; + source?: string; + } + /** + * Completion entry details request; value of command field is + * "completionEntryDetails". Given a file location (file, line, + * col) and an array of completion entry names return more + * detailed information for each completion entry. + */ + interface CompletionDetailsRequest extends FileLocationRequest { + command: CommandTypes.CompletionDetails; + arguments: CompletionDetailsRequestArgs; + } + /** + * Part of a symbol description. + */ + interface SymbolDisplayPart { + /** + * Text of an item describing the symbol. + */ + text: string; + /** + * The symbol's kind (such as 'className' or 'parameterName' or plain 'text'). + */ + kind: string; + } + /** + * An item found in a completion response. + */ + interface CompletionEntry { + /** + * The symbol's name. + */ + name: string; + /** + * The symbol's kind (such as 'className' or 'parameterName'). + */ + kind: ScriptElementKind; + /** + * Optional modifiers for the kind (such as 'public'). + */ + kindModifiers?: string; + /** + * A string that is used for comparing completion items so that they can be ordered. This + * is often the same as the name but may be different in certain circumstances. + */ + sortText: string; + /** + * Text to insert instead of `name`. + * This is used to support bracketed completions; If `name` might be "a-b" but `insertText` would be `["a-b"]`, + * coupled with `replacementSpan` to replace a dotted access with a bracket access. + */ + insertText?: string; + /** + * An optional span that indicates the text to be replaced by this completion item. + * If present, this span should be used instead of the default one. + * It will be set if the required span differs from the one generated by the default replacement behavior. + */ + replacementSpan?: TextSpan; + /** + * Indicates whether commiting this completion entry will require additional code actions to be + * made to avoid errors. The CompletionEntryDetails will have these actions. + */ + hasAction?: true; + /** + * Identifier (not necessarily human-readable) identifying where this completion came from. + */ + source?: string; + /** + * If true, this completion should be highlighted as recommended. There will only be one of these. + * This will be set when we know the user should write an expression with a certain type and that type is an enum or constructable class. + * Then either that enum/class or a namespace containing it will be the recommended symbol. + */ + isRecommended?: true; + } + /** + * Additional completion entry details, available on demand + */ + interface CompletionEntryDetails { + /** + * The symbol's name. + */ + name: string; + /** + * The symbol's kind (such as 'className' or 'parameterName'). + */ + kind: ScriptElementKind; + /** + * Optional modifiers for the kind (such as 'public'). + */ + kindModifiers: string; + /** + * Display parts of the symbol (similar to quick info). + */ + displayParts: SymbolDisplayPart[]; + /** + * Documentation strings for the symbol. + */ + documentation?: SymbolDisplayPart[]; + /** + * JSDoc tags for the symbol. + */ + tags?: JSDocTagInfo[]; + /** + * The associated code actions for this entry + */ + codeActions?: CodeAction[]; + /** + * Human-readable description of the `source` from the CompletionEntry. + */ + source?: SymbolDisplayPart[]; + } + /** @deprecated Prefer CompletionInfoResponse, which supports several top-level fields in addition to the array of entries. */ + interface CompletionsResponse extends Response { + body?: CompletionEntry[]; + } + interface CompletionInfoResponse extends Response { + body?: CompletionInfo; + } + interface CompletionInfo { + readonly isGlobalCompletion: boolean; + readonly isMemberCompletion: boolean; + readonly isNewIdentifierLocation: boolean; + readonly entries: ReadonlyArray; + } + interface CompletionDetailsResponse extends Response { + body?: CompletionEntryDetails[]; + } + /** + * Signature help information for a single parameter + */ + interface SignatureHelpParameter { + /** + * The parameter's name + */ + name: string; + /** + * Documentation of the parameter. + */ + documentation: SymbolDisplayPart[]; + /** + * Display parts of the parameter. + */ + displayParts: SymbolDisplayPart[]; + /** + * Whether the parameter is optional or not. + */ + isOptional: boolean; + } + /** + * Represents a single signature to show in signature help. + */ + interface SignatureHelpItem { + /** + * Whether the signature accepts a variable number of arguments. + */ + isVariadic: boolean; + /** + * The prefix display parts. + */ + prefixDisplayParts: SymbolDisplayPart[]; + /** + * The suffix display parts. + */ + suffixDisplayParts: SymbolDisplayPart[]; + /** + * The separator display parts. + */ + separatorDisplayParts: SymbolDisplayPart[]; + /** + * The signature helps items for the parameters. + */ + parameters: SignatureHelpParameter[]; + /** + * The signature's documentation + */ + documentation: SymbolDisplayPart[]; + /** + * The signature's JSDoc tags + */ + tags: JSDocTagInfo[]; + } + /** + * Signature help items found in the response of a signature help request. + */ + interface SignatureHelpItems { + /** + * The signature help items. + */ + items: SignatureHelpItem[]; + /** + * The span for which signature help should appear on a signature + */ + applicableSpan: TextSpan; + /** + * The item selected in the set of available help items. + */ + selectedItemIndex: number; + /** + * The argument selected in the set of parameters. + */ + argumentIndex: number; + /** + * The argument count + */ + argumentCount: number; + } + type SignatureHelpTriggerCharacter = "," | "(" | "<"; + type SignatureHelpRetriggerCharacter = SignatureHelpTriggerCharacter | ")"; + /** + * Arguments of a signature help request. + */ + interface SignatureHelpRequestArgs extends FileLocationRequestArgs { + /** + * Reason why signature help was invoked. + * See each individual possible + */ + triggerReason?: SignatureHelpTriggerReason; + } + type SignatureHelpTriggerReason = SignatureHelpInvokedReason | SignatureHelpCharacterTypedReason | SignatureHelpRetriggeredReason; + /** + * Signals that the user manually requested signature help. + * The language service will unconditionally attempt to provide a result. + */ + interface SignatureHelpInvokedReason { + kind: "invoked"; + triggerCharacter?: undefined; + } + /** + * Signals that the signature help request came from a user typing a character. + * Depending on the character and the syntactic context, the request may or may not be served a result. + */ + interface SignatureHelpCharacterTypedReason { + kind: "characterTyped"; + /** + * Character that was responsible for triggering signature help. + */ + triggerCharacter: SignatureHelpTriggerCharacter; + } + /** + * Signals that this signature help request came from typing a character or moving the cursor. + * This should only occur if a signature help session was already active and the editor needs to see if it should adjust. + * The language service will unconditionally attempt to provide a result. + * `triggerCharacter` can be `undefined` for a retrigger caused by a cursor move. + */ + interface SignatureHelpRetriggeredReason { + kind: "retrigger"; + /** + * Character that was responsible for triggering signature help. + */ + triggerCharacter?: SignatureHelpRetriggerCharacter; + } + /** + * Signature help request; value of command field is "signatureHelp". + * Given a file location (file, line, col), return the signature + * help. + */ + interface SignatureHelpRequest extends FileLocationRequest { + command: CommandTypes.SignatureHelp; + arguments: SignatureHelpRequestArgs; + } + /** + * Response object for a SignatureHelpRequest. + */ + interface SignatureHelpResponse extends Response { + body?: SignatureHelpItems; + } + /** + * Synchronous request for semantic diagnostics of one file. + */ + interface SemanticDiagnosticsSyncRequest extends FileRequest { + command: CommandTypes.SemanticDiagnosticsSync; + arguments: SemanticDiagnosticsSyncRequestArgs; + } + interface SemanticDiagnosticsSyncRequestArgs extends FileRequestArgs { + includeLinePosition?: boolean; + } + /** + * Response object for synchronous sematic diagnostics request. + */ + interface SemanticDiagnosticsSyncResponse extends Response { + body?: Diagnostic[] | DiagnosticWithLinePosition[]; + } + interface SuggestionDiagnosticsSyncRequest extends FileRequest { + command: CommandTypes.SuggestionDiagnosticsSync; + arguments: SuggestionDiagnosticsSyncRequestArgs; + } + type SuggestionDiagnosticsSyncRequestArgs = SemanticDiagnosticsSyncRequestArgs; + type SuggestionDiagnosticsSyncResponse = SemanticDiagnosticsSyncResponse; + /** + * Synchronous request for syntactic diagnostics of one file. + */ + interface SyntacticDiagnosticsSyncRequest extends FileRequest { + command: CommandTypes.SyntacticDiagnosticsSync; + arguments: SyntacticDiagnosticsSyncRequestArgs; + } + interface SyntacticDiagnosticsSyncRequestArgs extends FileRequestArgs { + includeLinePosition?: boolean; + } + /** + * Response object for synchronous syntactic diagnostics request. + */ + interface SyntacticDiagnosticsSyncResponse extends Response { + body?: Diagnostic[] | DiagnosticWithLinePosition[]; + } + /** + * Arguments for GeterrForProject request. + */ + interface GeterrForProjectRequestArgs { + /** + * the file requesting project error list + */ + file: string; + /** + * Delay in milliseconds to wait before starting to compute + * errors for the files in the file list + */ + delay: number; + } + /** + * GeterrForProjectRequest request; value of command field is + * "geterrForProject". It works similarly with 'Geterr', only + * it request for every file in this project. + */ + interface GeterrForProjectRequest extends Request { + command: CommandTypes.GeterrForProject; + arguments: GeterrForProjectRequestArgs; + } + /** + * Arguments for geterr messages. + */ + interface GeterrRequestArgs { + /** + * List of file names for which to compute compiler errors. + * The files will be checked in list order. + */ + files: string[]; + /** + * Delay in milliseconds to wait before starting to compute + * errors for the files in the file list + */ + delay: number; + } + /** + * Geterr request; value of command field is "geterr". Wait for + * delay milliseconds and then, if during the wait no change or + * reload messages have arrived for the first file in the files + * list, get the syntactic errors for the file, field requests, + * and then get the semantic errors for the file. Repeat with a + * smaller delay for each subsequent file on the files list. Best + * practice for an editor is to send a file list containing each + * file that is currently visible, in most-recently-used order. + */ + interface GeterrRequest extends Request { + command: CommandTypes.Geterr; + arguments: GeterrRequestArgs; + } + type RequestCompletedEventName = "requestCompleted"; + /** + * Event that is sent when server have finished processing request with specified id. + */ + interface RequestCompletedEvent extends Event { + event: RequestCompletedEventName; + body: RequestCompletedEventBody; + } + interface RequestCompletedEventBody { + request_seq: number; + } + /** + * Item of diagnostic information found in a DiagnosticEvent message. + */ + interface Diagnostic { + /** + * Starting file location at which text applies. + */ + start: Location; + /** + * The last file location at which the text applies. + */ + end: Location; + /** + * Text of diagnostic message. + */ + text: string; + /** + * The category of the diagnostic message, e.g. "error", "warning", or "suggestion". + */ + category: string; + reportsUnnecessary?: {}; + /** + * Any related spans the diagnostic may have, such as other locations relevant to an error, such as declarartion sites + */ + relatedInformation?: DiagnosticRelatedInformation[]; + /** + * The error code of the diagnostic message. + */ + code?: number; + /** + * The name of the plugin reporting the message. + */ + source?: string; + } + interface DiagnosticWithFileName extends Diagnostic { + /** + * Name of the file the diagnostic is in + */ + fileName: string; + } + /** + * Represents additional spans returned with a diagnostic which are relevant to it + */ + interface DiagnosticRelatedInformation { + /** + * The category of the related information message, e.g. "error", "warning", or "suggestion". + */ + category: string; + /** + * The code used ot identify the related information + */ + code: number; + /** + * Text of related or additional information. + */ + message: string; + /** + * Associated location + */ + span?: FileSpan; + } + interface DiagnosticEventBody { + /** + * The file for which diagnostic information is reported. + */ + file: string; + /** + * An array of diagnostic information items. + */ + diagnostics: Diagnostic[]; + } + type DiagnosticEventKind = "semanticDiag" | "syntaxDiag" | "suggestionDiag"; + /** + * Event message for DiagnosticEventKind event types. + * These events provide syntactic and semantic errors for a file. + */ + interface DiagnosticEvent extends Event { + body?: DiagnosticEventBody; + event: DiagnosticEventKind; + } + interface ConfigFileDiagnosticEventBody { + /** + * The file which trigged the searching and error-checking of the config file + */ + triggerFile: string; + /** + * The name of the found config file. + */ + configFile: string; + /** + * An arry of diagnostic information items for the found config file. + */ + diagnostics: DiagnosticWithFileName[]; + } + /** + * Event message for "configFileDiag" event type. + * This event provides errors for a found config file. + */ + interface ConfigFileDiagnosticEvent extends Event { + body?: ConfigFileDiagnosticEventBody; + event: "configFileDiag"; + } + type ProjectLanguageServiceStateEventName = "projectLanguageServiceState"; + interface ProjectLanguageServiceStateEvent extends Event { + event: ProjectLanguageServiceStateEventName; + body?: ProjectLanguageServiceStateEventBody; + } + interface ProjectLanguageServiceStateEventBody { + /** + * Project name that has changes in the state of language service. + * For configured projects this will be the config file path. + * For external projects this will be the name of the projects specified when project was open. + * For inferred projects this event is not raised. + */ + projectName: string; + /** + * True if language service state switched from disabled to enabled + * and false otherwise. + */ + languageServiceEnabled: boolean; + } + type ProjectsUpdatedInBackgroundEventName = "projectsUpdatedInBackground"; + interface ProjectsUpdatedInBackgroundEvent extends Event { + event: ProjectsUpdatedInBackgroundEventName; + body: ProjectsUpdatedInBackgroundEventBody; + } + interface ProjectsUpdatedInBackgroundEventBody { + /** + * Current set of open files + */ + openFiles: string[]; + } + type ProjectLoadingStartEventName = "projectLoadingStart"; + interface ProjectLoadingStartEvent extends Event { + event: ProjectLoadingStartEventName; + body: ProjectLoadingStartEventBody; + } + interface ProjectLoadingStartEventBody { + /** name of the project */ + projectName: string; + /** reason for loading */ + reason: string; + } + type ProjectLoadingFinishEventName = "projectLoadingFinish"; + interface ProjectLoadingFinishEvent extends Event { + event: ProjectLoadingFinishEventName; + body: ProjectLoadingFinishEventBody; + } + interface ProjectLoadingFinishEventBody { + /** name of the project */ + projectName: string; + } + type SurveyReadyEventName = "surveyReady"; + interface SurveyReadyEvent extends Event { + event: SurveyReadyEventName; + body: SurveyReadyEventBody; + } + interface SurveyReadyEventBody { + /** Name of the survey. This is an internal machine- and programmer-friendly name */ + surveyId: string; + } + type LargeFileReferencedEventName = "largeFileReferenced"; + interface LargeFileReferencedEvent extends Event { + event: LargeFileReferencedEventName; + body: LargeFileReferencedEventBody; + } + interface LargeFileReferencedEventBody { + /** + * name of the large file being loaded + */ + file: string; + /** + * size of the file + */ + fileSize: number; + /** + * max file size allowed on the server + */ + maxFileSize: number; + } + /** + * Arguments for reload request. + */ + interface ReloadRequestArgs extends FileRequestArgs { + /** + * Name of temporary file from which to reload file + * contents. May be same as file. + */ + tmpfile: string; + } + /** + * Reload request message; value of command field is "reload". + * Reload contents of file with name given by the 'file' argument + * from temporary file with name given by the 'tmpfile' argument. + * The two names can be identical. + */ + interface ReloadRequest extends FileRequest { + command: CommandTypes.Reload; + arguments: ReloadRequestArgs; + } + /** + * Response to "reload" request. This is just an acknowledgement, so + * no body field is required. + */ + interface ReloadResponse extends Response { + } + /** + * Arguments for saveto request. + */ + interface SavetoRequestArgs extends FileRequestArgs { + /** + * Name of temporary file into which to save server's view of + * file contents. + */ + tmpfile: string; + } + /** + * Saveto request message; value of command field is "saveto". + * For debugging purposes, save to a temporaryfile (named by + * argument 'tmpfile') the contents of file named by argument + * 'file'. The server does not currently send a response to a + * "saveto" request. + */ + interface SavetoRequest extends FileRequest { + command: CommandTypes.Saveto; + arguments: SavetoRequestArgs; + } + /** + * Arguments for navto request message. + */ + interface NavtoRequestArgs extends FileRequestArgs { + /** + * Search term to navigate to from current location; term can + * be '.*' or an identifier prefix. + */ + searchValue: string; + /** + * Optional limit on the number of items to return. + */ + maxResultCount?: number; + /** + * Optional flag to indicate we want results for just the current file + * or the entire project. + */ + currentFileOnly?: boolean; + projectFileName?: string; + } + /** + * Navto request message; value of command field is "navto". + * Return list of objects giving file locations and symbols that + * match the search term given in argument 'searchTerm'. The + * context for the search is given by the named file. + */ + interface NavtoRequest extends FileRequest { + command: CommandTypes.Navto; + arguments: NavtoRequestArgs; + } + /** + * An item found in a navto response. + */ + interface NavtoItem extends FileSpan { + /** + * The symbol's name. + */ + name: string; + /** + * The symbol's kind (such as 'className' or 'parameterName'). + */ + kind: ScriptElementKind; + /** + * exact, substring, or prefix. + */ + matchKind: string; + /** + * If this was a case sensitive or insensitive match. + */ + isCaseSensitive: boolean; + /** + * Optional modifiers for the kind (such as 'public'). + */ + kindModifiers?: string; + /** + * Name of symbol's container symbol (if any); for example, + * the class name if symbol is a class member. + */ + containerName?: string; + /** + * Kind of symbol's container symbol (if any). + */ + containerKind?: ScriptElementKind; + } + /** + * Navto response message. Body is an array of navto items. Each + * item gives a symbol that matched the search term. + */ + interface NavtoResponse extends Response { + body?: NavtoItem[]; + } + /** + * Arguments for change request message. + */ + interface ChangeRequestArgs extends FormatRequestArgs { + /** + * Optional string to insert at location (file, line, offset). + */ + insertString?: string; + } + /** + * Change request message; value of command field is "change". + * Update the server's view of the file named by argument 'file'. + * Server does not currently send a response to a change request. + */ + interface ChangeRequest extends FileLocationRequest { + command: CommandTypes.Change; + arguments: ChangeRequestArgs; + } + /** + * Response to "brace" request. + */ + interface BraceResponse extends Response { + body?: TextSpan[]; + } + /** + * Brace matching request; value of command field is "brace". + * Return response giving the file locations of matching braces + * found in file at location line, offset. + */ + interface BraceRequest extends FileLocationRequest { + command: CommandTypes.Brace; + } + /** + * NavBar items request; value of command field is "navbar". + * Return response giving the list of navigation bar entries + * extracted from the requested file. + */ + interface NavBarRequest extends FileRequest { + command: CommandTypes.NavBar; + } + /** + * NavTree request; value of command field is "navtree". + * Return response giving the navigation tree of the requested file. + */ + interface NavTreeRequest extends FileRequest { + command: CommandTypes.NavTree; + } + interface NavigationBarItem { + /** + * The item's display text. + */ + text: string; + /** + * The symbol's kind (such as 'className' or 'parameterName'). + */ + kind: ScriptElementKind; + /** + * Optional modifiers for the kind (such as 'public'). + */ + kindModifiers?: string; + /** + * The definition locations of the item. + */ + spans: TextSpan[]; + /** + * Optional children. + */ + childItems?: NavigationBarItem[]; + /** + * Number of levels deep this item should appear. + */ + indent: number; + } + /** protocol.NavigationTree is identical to ts.NavigationTree, except using protocol.TextSpan instead of ts.TextSpan */ + interface NavigationTree { + text: string; + kind: ScriptElementKind; + kindModifiers: string; + spans: TextSpan[]; + nameSpan: TextSpan | undefined; + childItems?: NavigationTree[]; + } + type TelemetryEventName = "telemetry"; + interface TelemetryEvent extends Event { + event: TelemetryEventName; + body: TelemetryEventBody; + } + interface TelemetryEventBody { + telemetryEventName: string; + payload: any; + } + type TypesInstallerInitializationFailedEventName = "typesInstallerInitializationFailed"; + interface TypesInstallerInitializationFailedEvent extends Event { + event: TypesInstallerInitializationFailedEventName; + body: TypesInstallerInitializationFailedEventBody; + } + interface TypesInstallerInitializationFailedEventBody { + message: string; + } + type TypingsInstalledTelemetryEventName = "typingsInstalled"; + interface TypingsInstalledTelemetryEventBody extends TelemetryEventBody { + telemetryEventName: TypingsInstalledTelemetryEventName; + payload: TypingsInstalledTelemetryEventPayload; + } + interface TypingsInstalledTelemetryEventPayload { + /** + * Comma separated list of installed typing packages + */ + installedPackages: string; + /** + * true if install request succeeded, otherwise - false + */ + installSuccess: boolean; + /** + * version of typings installer + */ + typingsInstallerVersion: string; + } + type BeginInstallTypesEventName = "beginInstallTypes"; + type EndInstallTypesEventName = "endInstallTypes"; + interface BeginInstallTypesEvent extends Event { + event: BeginInstallTypesEventName; + body: BeginInstallTypesEventBody; + } + interface EndInstallTypesEvent extends Event { + event: EndInstallTypesEventName; + body: EndInstallTypesEventBody; + } + interface InstallTypesEventBody { + /** + * correlation id to match begin and end events + */ + eventId: number; + /** + * list of packages to install + */ + packages: ReadonlyArray; + } + interface BeginInstallTypesEventBody extends InstallTypesEventBody { + } + interface EndInstallTypesEventBody extends InstallTypesEventBody { + /** + * true if installation succeeded, otherwise false + */ + success: boolean; + } + interface NavBarResponse extends Response { + body?: NavigationBarItem[]; + } + interface NavTreeResponse extends Response { + body?: NavigationTree; + } + const enum IndentStyle { + None = "None", + Block = "Block", + Smart = "Smart" + } + interface EditorSettings { + baseIndentSize?: number; + indentSize?: number; + tabSize?: number; + newLineCharacter?: string; + convertTabsToSpaces?: boolean; + indentStyle?: IndentStyle | ts.IndentStyle; + } + interface FormatCodeSettings extends EditorSettings { + insertSpaceAfterCommaDelimiter?: boolean; + insertSpaceAfterSemicolonInForStatements?: boolean; + insertSpaceBeforeAndAfterBinaryOperators?: boolean; + insertSpaceAfterConstructor?: boolean; + insertSpaceAfterKeywordsInControlFlowStatements?: boolean; + insertSpaceAfterFunctionKeywordForAnonymousFunctions?: boolean; + insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis?: boolean; + insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets?: boolean; + insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces?: boolean; + insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces?: boolean; + insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces?: boolean; + insertSpaceAfterTypeAssertion?: boolean; + insertSpaceBeforeFunctionParenthesis?: boolean; + placeOpenBraceOnNewLineForFunctions?: boolean; + placeOpenBraceOnNewLineForControlBlocks?: boolean; + insertSpaceBeforeTypeAnnotation?: boolean; + } + interface UserPreferences { + readonly disableSuggestions?: boolean; + readonly quotePreference?: "double" | "single"; + /** + * If enabled, TypeScript will search through all external modules' exports and add them to the completions list. + * This affects lone identifier completions but not completions on the right hand side of `obj.`. + */ + readonly includeCompletionsForModuleExports?: boolean; + /** + * If enabled, the completion list will include completions with invalid identifier names. + * For those entries, The `insertText` and `replacementSpan` properties will be set to change from `.x` property access to `["x"]`. + */ + readonly includeCompletionsWithInsertText?: boolean; + readonly importModuleSpecifierPreference?: "relative" | "non-relative"; + readonly allowTextChangesInNewFiles?: boolean; + readonly lazyConfiguredProjectsFromExternalProject?: boolean; + } + interface CompilerOptions { + allowJs?: boolean; + allowSyntheticDefaultImports?: boolean; + allowUnreachableCode?: boolean; + allowUnusedLabels?: boolean; + alwaysStrict?: boolean; + baseUrl?: string; + charset?: string; + checkJs?: boolean; + declaration?: boolean; + declarationDir?: string; + disableSizeLimit?: boolean; + downlevelIteration?: boolean; + emitBOM?: boolean; + emitDecoratorMetadata?: boolean; + experimentalDecorators?: boolean; + forceConsistentCasingInFileNames?: boolean; + importHelpers?: boolean; + inlineSourceMap?: boolean; + inlineSources?: boolean; + isolatedModules?: boolean; + jsx?: JsxEmit | ts.JsxEmit; + lib?: string[]; + locale?: string; + mapRoot?: string; + maxNodeModuleJsDepth?: number; + module?: ModuleKind | ts.ModuleKind; + moduleResolution?: ModuleResolutionKind | ts.ModuleResolutionKind; + newLine?: NewLineKind | ts.NewLineKind; + noEmit?: boolean; + noEmitHelpers?: boolean; + noEmitOnError?: boolean; + noErrorTruncation?: boolean; + noFallthroughCasesInSwitch?: boolean; + noImplicitAny?: boolean; + noImplicitReturns?: boolean; + noImplicitThis?: boolean; + noUnusedLocals?: boolean; + noUnusedParameters?: boolean; + noImplicitUseStrict?: boolean; + noLib?: boolean; + noResolve?: boolean; + out?: string; + outDir?: string; + outFile?: string; + paths?: MapLike; + plugins?: PluginImport[]; + preserveConstEnums?: boolean; + preserveSymlinks?: boolean; + project?: string; + reactNamespace?: string; + removeComments?: boolean; + references?: ProjectReference[]; + rootDir?: string; + rootDirs?: string[]; + skipLibCheck?: boolean; + skipDefaultLibCheck?: boolean; + sourceMap?: boolean; + sourceRoot?: string; + strict?: boolean; + strictNullChecks?: boolean; + suppressExcessPropertyErrors?: boolean; + suppressImplicitAnyIndexErrors?: boolean; + target?: ScriptTarget | ts.ScriptTarget; + traceResolution?: boolean; + resolveJsonModule?: boolean; + types?: string[]; + /** Paths used to used to compute primary types search locations */ + typeRoots?: string[]; + [option: string]: CompilerOptionsValue | undefined; + } + const enum JsxEmit { + None = "None", + Preserve = "Preserve", + ReactNative = "ReactNative", + React = "React" + } + const enum ModuleKind { + None = "None", + CommonJS = "CommonJS", + AMD = "AMD", + UMD = "UMD", + System = "System", + ES6 = "ES6", + ES2015 = "ES2015", + ESNext = "ESNext" + } + const enum ModuleResolutionKind { + Classic = "Classic", + Node = "Node" + } + const enum NewLineKind { + Crlf = "Crlf", + Lf = "Lf" + } + const enum ScriptTarget { + ES3 = "ES3", + ES5 = "ES5", + ES6 = "ES6", + ES2015 = "ES2015", + ES2016 = "ES2016", + ES2017 = "ES2017", + ESNext = "ESNext" + } +} +declare namespace ts.server.protocol { + + interface TextInsertion { + newText: string; + /** The position in newText the caret should point to after the insertion. */ + caretOffset: number; + } + + interface TodoCommentDescriptor { + text: string; + priority: number; + } + + interface TodoComment { + descriptor: TodoCommentDescriptor; + message: string; + position: number; + } + + enum OutliningSpanKind { + /** Single or multi-line comments */ + Comment = "comment", + /** Sections marked by '// #region' and '// #endregion' comments */ + Region = "region", + /** Declarations and expressions */ + Code = "code", + /** Contiguous blocks of import declarations */ + Imports = "imports" + } + + enum HighlightSpanKind { + none = "none", + definition = "definition", + reference = "reference", + writtenReference = "writtenReference" + } + + enum ScriptElementKind { + unknown = "", + warning = "warning", + /** predefined type (void) or keyword (class) */ + keyword = "keyword", + /** top level script node */ + scriptElement = "script", + /** module foo {} */ + moduleElement = "module", + /** class X {} */ + classElement = "class", + /** var x = class X {} */ + localClassElement = "local class", + /** interface Y {} */ + interfaceElement = "interface", + /** type T = ... */ + typeElement = "type", + /** enum E */ + enumElement = "enum", + enumMemberElement = "enum member", + /** + * Inside module and script only + * const v = .. + */ + variableElement = "var", + /** Inside function */ + localVariableElement = "local var", + /** + * Inside module and script only + * function f() { } + */ + functionElement = "function", + /** Inside function */ + localFunctionElement = "local function", + /** class X { [public|private]* foo() {} } */ + memberFunctionElement = "method", + /** class X { [public|private]* [get|set] foo:number; } */ + memberGetAccessorElement = "getter", + memberSetAccessorElement = "setter", + /** + * class X { [public|private]* foo:number; } + * interface Y { foo:number; } + */ + memberVariableElement = "property", + /** class X { constructor() { } } */ + constructorImplementationElement = "constructor", + /** interface Y { ():number; } */ + callSignatureElement = "call", + /** interface Y { []:number; } */ + indexSignatureElement = "index", + /** interface Y { new():Y; } */ + constructSignatureElement = "construct", + /** function foo(*Y*: string) */ + parameterElement = "parameter", + typeParameterElement = "type parameter", + primitiveType = "primitive type", + label = "label", + alias = "alias", + constElement = "const", + letElement = "let", + directory = "directory", + externalModuleName = "external module name", + /** + * + */ + jsxAttribute = "JSX attribute", + /** String literal */ + string = "string" + } + + interface TypeAcquisition { + enableAutoDiscovery?: boolean; + enable?: boolean; + include?: string[]; + exclude?: string[]; + [option: string]: string[] | boolean | undefined; + } + + interface FileExtensionInfo { + extension: string; + isMixedContent: boolean; + scriptKind?: ScriptKind; + } + + interface JSDocTagInfo { + name: string; + text?: string; + } + + /** + * Type of objects whose values are all of the same type. + * The `in` and `for-in` operators can *not* be safely used, + * since `Object.prototype` may be modified by outside code. + */ + interface MapLike { + [index: string]: T; + } + + interface PluginImport { + name: string; + } + + interface ProjectReference { + /** A normalized path on disk */ + path: string; + /** The path as the user originally wrote it */ + originalPath?: string; + /** True if the output of this reference should be prepended to the output of this project. Only valid for --outFile compilations */ + prepend?: boolean; + /** True if it is intended that this reference form a circularity */ + circular?: boolean; + } + + type CompilerOptionsValue = string | number | boolean | (string | number)[] | string[] | MapLike | PluginImport[] | ProjectReference[] | null | undefined; +} +declare namespace ts { + // these types are empty stubs for types from services and should not be used directly + export type ScriptKind = never; + export type IndentStyle = never; + export type JsxEmit = never; + export type ModuleKind = never; + export type ModuleResolutionKind = never; + export type NewLineKind = never; + export type ScriptTarget = never; +} +import protocol = ts.server.protocol; +export = protocol; +export as namespace protocol; \ No newline at end of file diff --git a/node_modules/typescript/lib/pt-br/diagnosticMessages.generated.json b/node_modules/typescript/lib/pt-br/diagnosticMessages.generated.json new file mode 100644 index 0000000..de74fa7 --- /dev/null +++ b/node_modules/typescript/lib/pt-br/diagnosticMessages.generated.json @@ -0,0 +1,1101 @@ +{ + "A_0_modifier_cannot_be_used_with_an_import_declaration_1079": "Um modificador '{0}' não pode ser usado com uma declaração de importação.", + "A_0_modifier_cannot_be_used_with_an_interface_declaration_1045": "Um modificador '{0}' não pode ser usado com uma declaração de interface.", + "A_0_parameter_must_be_the_first_parameter_2680": "Um parâmetro '{0}' deve ser o primeiro parâmetro.", + "A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature_2463": "Um parâmetro de padrão de associação não pode ser opcional em uma assinatura de implementação.", + "A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement_1105": "Uma instrução 'break' só pode ser usada em uma iteração de circunscrição ou instrução switch.", + "A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement_1116": "Uma instrução 'break' só pode saltar para um rótulo de uma instrução de circunscrição.", + "A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments_2500": "Uma classe pode implementar apenas um identificador/nome qualificado com argumentos de tipo opcionais.", + "A_class_declaration_without_the_default_modifier_must_have_a_name_1211": "Uma declaração de classe sem o modificador 'default' deve ter um nome.", + "A_class_may_only_extend_another_class_2311": "Uma classe somente pode estender-se para outra classe.", + "A_class_may_only_implement_another_class_or_interface_2422": "Uma classe somente pode implementar outra classe ou interface.", + "A_class_member_cannot_have_the_0_keyword_1248": "Um membro de classe não pode ter a palavra-chave '{0}'.", + "A_comma_expression_is_not_allowed_in_a_computed_property_name_1171": "Uma expressão de vírgula não é permitida em um nome de propriedade calculado.", + "A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type_2467": "Um nome de propriedade calculado não pode fazer referência a um parâmetro de tipo no seu tipo recipiente.", + "A_computed_property_name_in_a_class_property_declaration_must_refer_to_an_expression_whose_type_is_a_1166": "Um nome de propriedade computado em uma declaração de propriedade de classe deve se referir a uma expressão cujo tipo é um tipo literal ou um 'unique symbol'.", + "A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_ty_1168": "Um nome de propriedade computado em uma sobrecarga do método deve se referir a uma expressão cujo tipo é um tipo literal ou um 'unique symbol'.", + "A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type__1170": "Um nome de propriedade computado em um tipo literal deve se referir a uma expressão cujo tipo é um tipo literal ou um 'unique symbol'.", + "A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_t_1165": "Um nome de propriedade computado em um contexto de ambiente deve se referir a uma expressão cujo tipo é um tipo literal ou um 'unique symbol'.", + "A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_1169": "Um nome de propriedade computado em uma interface deve se referir a uma expressão cujo tipo é um tipo literal ou um 'unique symbol'.", + "A_computed_property_name_must_be_of_type_string_number_symbol_or_any_2464": "Um nome de propriedade calculado deve ser do tipo 'string', 'number', 'symbol' ou 'any'.", + "A_computed_property_name_of_the_form_0_must_be_of_type_symbol_2471": "Um nome de propriedade calculado do formulário '{0}' deve ser do tipo 'symbol'.", + "A_const_enum_member_can_only_be_accessed_using_a_string_literal_2476": "Um membro const enum só pode ser acessado usando um literal de cadeia de caracteres.", + "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_1254": "Um inicializador 'const' em um contexto de ambiente deve ser uma cadeia ou um literal numérico.", + "A_constructor_cannot_contain_a_super_call_when_its_class_extends_null_17005": "Um construtor não pode conter uma chamada 'super' quando sua classe estende 'null'.", + "A_constructor_cannot_have_a_this_parameter_2681": "Um construtor não pode ter um parâmetro 'this'.", + "A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement_1104": "Uma instrução 'continue' só pode ser usada em uma instrução de iteração de circunscrição.", + "A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement_1115": "Uma instrução 'continue' só pode saltar para um rótulo de uma instrução de iteração de circunscrição.", + "A_declare_modifier_cannot_be_used_in_an_already_ambient_context_1038": "Um modificador 'declare' não pode ser usado em um contexto de ambiente.", + "A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file_1046": "Um modificador 'declare' é necessário para uma declaração de nível superior em um arquivo .d.ts.", + "A_decorator_can_only_decorate_a_method_implementation_not_an_overload_1249": "Um decorador pode decorar somente uma implementação de método, não uma sobrecarga.", + "A_default_clause_cannot_appear_more_than_once_in_a_switch_statement_1113": "Uma cláusula 'default' não pode aparecer mais de uma vez em uma instrução 'switch'.", + "A_default_export_can_only_be_used_in_an_ECMAScript_style_module_1319": "Uma exportação padrão só pode ser usada em um módulo do estilo ECMAScript.", + "A_definite_assignment_assertion_is_not_permitted_in_this_context_1255": "Uma declaração de atribuição definitiva '!' não é permitida neste contexto.", + "A_destructuring_declaration_must_have_an_initializer_1182": "Uma declaração de desestruturação deve ter um inicializador.", + "A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declarat_2712": "Uma chamada de importação dinâmica em ES5/ES3 exige o construtor 'Promise'. Verifique se você tem uma declaração para o construtor 'Promise' ou inclua 'ES2015' em sua opção `--lib`.", + "A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES20_2711": "Uma chamada de importação dinâmica retorna um 'Promise'. Verifique se você tem uma declaração para 'Promise' ou inclua 'ES2015' em sua opção `--lib`.", + "A_file_cannot_have_a_reference_to_itself_1006": "Um arquivo não pode fazer referência a si mesmo.", + "A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator_1103": "Uma instrução 'for-await-of' é permitida somente na função assíncrona ou no gerador assíncrono.", + "A_function_returning_never_cannot_have_a_reachable_end_point_2534": "Uma função que retorna 'never' não pode ter um ponto de extremidade acessível.", + "A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void_2679": "Uma função chamada com a palavra-chave 'new' não pode ter um tipo 'this' que seja 'void'.", + "A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value_2355": "A função cujo tipo declarado não é 'void' nem 'any' deve retornar um valor.", + "A_generator_cannot_have_a_void_type_annotation_2505": "O gerador não pode ter uma anotação de tipo 'void'.", + "A_get_accessor_cannot_have_parameters_1054": "Um acessador 'get' não pode ter parâmetros.", + "A_get_accessor_must_return_a_value_2378": "Um acessador 'get' deve retornar um valor.", + "A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_memb_2651": "O inicializador de um membro em uma declaração de enumeração não pode referenciar membros declarados depois dele, inclusive membros definidos em outras enumerações.", + "A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any_2545": "Uma classe mixin deve ter um construtor um único parâmetro rest do tipo 'any[]'.", + "A_module_cannot_have_multiple_default_exports_2528": "Um módulo não pode ter várias exportações padrão.", + "A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merg_2433": "Uma declaração de namespace não pode estar em um arquivo diferente de uma classe ou função com a qual ela é mesclada.", + "A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged_2434": "Uma declaração de namespace não pode estar localizada antes de uma classe ou função com a qual ela é mesclada.", + "A_namespace_declaration_is_only_allowed_in_a_namespace_or_module_1235": "Uma declaração de namespace só é permitida e um namespace ou módulo.", + "A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_7038": "Uma importação de estilo do namespace não pode ser chamada nem construída e causará uma falha no tempo de execução.", + "A_non_dry_build_would_build_project_0_6357": "Um build não -dry criaria o projeto '{0}'", + "A_non_dry_build_would_delete_the_following_files_Colon_0_6356": "Um build não -dry excluiria os seguintes arquivos: {0}", + "A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation_2371": "Um inicializador de parâmetro só é permitido em uma implementação de função ou de construtor.", + "A_parameter_property_cannot_be_declared_using_a_rest_parameter_1317": "Uma propriedade de parâmetro não pode ser declarada usando um parâmetro rest.", + "A_parameter_property_is_only_allowed_in_a_constructor_implementation_2369": "Uma propriedade de parâmetro somente é permitida em uma implementação de construtor.", + "A_parameter_property_may_not_be_declared_using_a_binding_pattern_1187": "Uma propriedade de parâmetro pode não ser declarada usando um padrão de associação.", + "A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not_18001": "Um caminho em uma opção 'extends' deve ser relativo ou ter raiz, mas o '{0}' não é.", + "A_promise_must_have_a_then_method_1059": "Uma promessa deve ter um método 'then'.", + "A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly_1331": "Uma propriedade de uma classe cujo tipo é um tipo de 'unique symbol' deve ser 'static' e 'readonly'.", + "A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly_1330": "Uma propriedade de uma interface ou tipo literal cujo tipo é um tipo de 'unique symbol' deve ser 'readonly'.", + "A_required_parameter_cannot_follow_an_optional_parameter_1016": "Um parâmetro obrigatório não pode seguir um parâmetro opcional.", + "A_rest_element_cannot_contain_a_binding_pattern_2501": "Um elemento rest não pode conter um padrão de associação.", + "A_rest_element_cannot_have_a_property_name_2566": "Um elemento rest não pode ter um nome de propriedade.", + "A_rest_element_cannot_have_an_initializer_1186": "Um elemento rest não pode ter um inicializador.", + "A_rest_element_must_be_last_in_a_destructuring_pattern_2462": "Um elemento rest deve ser o último em um padrão de desestruturação.", + "A_rest_parameter_cannot_be_optional_1047": "Um parâmetro rest não pode ser opcional.", + "A_rest_parameter_cannot_have_an_initializer_1048": "Um parâmetro rest não pode ter um inicializador.", + "A_rest_parameter_must_be_last_in_a_parameter_list_1014": "Um parâmetro rest deve ser o último em uma lista de parâmetros.", + "A_rest_parameter_must_be_of_an_array_type_2370": "Um parâmetro rest deve ser de um tipo de matriz.", + "A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma_1013": "Um padrão de associação ou o parâmetro rest não pode ter uma vírgula à direita.", + "A_return_statement_can_only_be_used_within_a_function_body_1108": "Uma instrução 'return' só pode ser usada dentro de um corpo de função.", + "A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl_6167": "Uma série de entradas que o remapeamento importa para pesquisar locais relativos a 'baseUrl'.", + "A_set_accessor_cannot_have_a_return_type_annotation_1095": "Um acessador 'set' não pode ter uma anotação de tipo de retorno.", + "A_set_accessor_cannot_have_an_optional_parameter_1051": "Um acessador 'set' não pode ter um parâmetro opcional.", + "A_set_accessor_cannot_have_rest_parameter_1053": "Um acessador 'set' não pode ter um parâmetro rest.", + "A_set_accessor_must_have_exactly_one_parameter_1049": "Um acessador 'set' deve ter exatamente um parâmetro.", + "A_set_accessor_parameter_cannot_have_an_initializer_1052": "Um parâmetro de acessador 'set' não pode ter um inicializador.", + "A_signature_with_an_implementation_cannot_use_a_string_literal_type_2381": "Uma assinatura com uma implementação não pode usar um tipo de cadeia de caracteres literal.", + "A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_proper_2376": "Uma chamada 'super' deve ser a primeira instrução no construtor quando uma classe contiver propriedades inicializadas ou propriedades de parâmetro.", + "A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard_2518": "Uma proteção de tipo baseado em 'this não é compatível com uma proteção de tipo baseado em parâmetro.", + "A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface_2526": "Um tipo 'this' está disponível somente em um membro não estático de uma classe ou interface.", + "A_tsconfig_json_file_is_already_defined_at_Colon_0_5054": "Um arquivo 'tsconfig.json' já está definido em: '{0}'.", + "A_tuple_type_element_list_cannot_be_empty_1122": "Uma lista de elementos do tipo tupla não pode estar vazia.", + "A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Con_17007": "Uma expressão de asserção de tipo não é permitida no lado esquerdo de uma expressão de exponenciação. Considere delimitar a expressão em parênteses.", + "A_type_literal_property_cannot_have_an_initializer_1247": "Uma propriedade literal de tipo não pode ter um inicializador.", + "A_type_predicate_cannot_reference_a_rest_parameter_1229": "O predicado de tipo não pode fazer referência a um parâmetro rest.", + "A_type_predicate_cannot_reference_element_0_in_a_binding_pattern_1230": "O predicado de tipo não pode fazer referência ao elemento '{0}' em um padrão de associação.", + "A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods_1228": "O predicado de tipo só é permitido na posição de tipo de retorno para funções e métodos.", + "A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type_2677": "O tipo de um predicado de tipo deve ser atribuível para o tipo de seu parâmetro.", + "A_variable_whose_type_is_a_unique_symbol_type_must_be_const_1332": "Uma variável cujo tipo é um tipo de 'unique symbol' deve ser 'const'.", + "A_yield_expression_is_only_allowed_in_a_generator_body_1163": "A expressão 'yield' só é permitida em um corpo gerador.", + "Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression_2513": "O método abstrato '{0}' na classe '{1}' não pode ser acessado por meio da expressão super.", + "Abstract_methods_can_only_appear_within_an_abstract_class_1244": "Os métodos abstratos só podem aparecer dentro de uma classe abstrata.", + "Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor_2715": "A propriedade abstrata '{0}' na classe '{1}' não pode ser acessada no construtor.", + "Accessibility_modifier_already_seen_1028": "O modificador de acessibilidade já foi visto.", + "Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher_1056": "Os acessadores somente estão disponíveis no direcionamento para ECMAScript 5 e superior.", + "Accessors_must_both_be_abstract_or_non_abstract_2676": "Acessadores devem ser abstratos ou não abstratos.", + "Add_0_to_existing_import_declaration_from_1_90015": "Adicionar '{0}' à declaração de importação existente de \"{1}\"", + "Add_0_to_unresolved_variable_90008": "Adicionar '{0}.' à variável não resolvida", + "Add_all_missing_async_modifiers_95041": "Adicionar todos os modificadores 'async' ausentes", + "Add_all_missing_members_95022": "Adicionar todos os membros ausentes", + "Add_all_missing_super_calls_95039": "Adicionar todas as chamadas super ausentes", + "Add_async_modifier_to_containing_function_90029": "Adicione o modificador assíncrono que contém a função", + "Add_braces_to_arrow_function_95059": "Adicionar chaves para a função de seta", + "Add_definite_assignment_assertion_to_property_0_95020": "Adicionar a asserção de atribuição definitiva à propriedade '{0}'", + "Add_definite_assignment_assertions_to_all_uninitialized_properties_95028": "Adicionar declarações de atribuição definidas a todas as propriedades não inicializadas", + "Add_index_signature_for_property_0_90017": "Adicionar assinatura de índice para a propriedade '{0}'", + "Add_initializer_to_property_0_95019": "Adicionar inicializador à propriedade '{0}'", + "Add_initializers_to_all_uninitialized_properties_95027": "Adicionar inicializadores a todas as propriedades não inicializadas", + "Add_missing_super_call_90001": "Adicionar chamada 'super()' ausente", + "Add_missing_typeof_95052": "Adicionar 'typeof' ausente", + "Add_or_remove_braces_in_an_arrow_function_95058": "Adicionar ou remover chaves em uma função de seta", + "Add_qualifier_to_all_unresolved_variables_matching_a_member_name_95037": "Adicionar um qualificador a todas as variáveis não resolvidas correspondentes a um nome de membro", + "Add_to_all_uncalled_decorators_95044": "Adicionar '()' a todos os decoradores não chamados", + "Add_ts_ignore_to_all_error_messages_95042": "Adicionar '@ts-ignore' a todas as mensagens de erro", + "Add_undefined_type_to_all_uninitialized_properties_95029": "Adicionar tipo indefinido a todas as propriedades não inicializadas", + "Add_undefined_type_to_property_0_95018": "Adicionar tipo 'indefinido' à propriedade '{0}'", + "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068": "Adicionar um arquivo tsconfig.json ajudará a organizar projetos que contêm arquivos TypeScript e JavaScript. Saiba mais em https://aka.ms/tsconfig.", + "Additional_Checks_6176": "Verificações Adicionais", + "Advanced_Options_6178": "Opções Avançadas", + "All_declarations_of_0_must_have_identical_modifiers_2687": "Todas as declarações de '{0}' devem ter modificadores idênticos.", + "All_declarations_of_0_must_have_identical_type_parameters_2428": "Todas as declarações de '{0}' devem ter parâmetros de tipo idênticos.", + "All_declarations_of_an_abstract_method_must_be_consecutive_2516": "Todas as declarações de um método abstrato devem ser consecutivas.", + "All_destructured_elements_are_unused_6198": "Todos os elementos desestruturados são inutilizados.", + "All_imports_in_import_declaration_are_unused_6192": "Nenhuma das importações na declaração de importação está sendo utilizada.", + "All_variables_are_unused_6199": "Nenhuma das variáveis está sendo utilizada.", + "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011": "Permita importações padrão de módulos sem exportação padrão. Isso não afeta a emissão do código, apenas a verificação de digitação.", + "Allow_javascript_files_to_be_compiled_6102": "Permita que arquivos javascript sejam compilados.", + "Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided_1209": "As enumerações de constante de ambiente não são permitidas quando o sinalizador '--isolatedModules' é fornecido.", + "Ambient_module_declaration_cannot_specify_relative_module_name_2436": "A declaração de módulo de ambiente não pode especificar o nome do módulo relativo.", + "Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces_2435": "Módulos de ambiente não podem ser aninhados em outros módulos ou namespaces.", + "An_AMD_module_cannot_have_multiple_name_assignments_2458": "Um módulo AMD não pode ter várias atribuições de nome.", + "An_abstract_accessor_cannot_have_an_implementation_1318": "Um acessador abstrato não pode ter uma implementação.", + "An_accessor_cannot_be_declared_in_an_ambient_context_1086": "Um acessador não pode ser declarado em um contexto de ambiente.", + "An_accessor_cannot_have_type_parameters_1094": "Um acessador não pode ter parâmetros de tipo.", + "An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file_1234": "Uma declaração de módulo de ambiente só é permitida no nível superior em um arquivo.", + "An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type_2356": "Um operando aritmético deve ser do tipo 'any', 'number' ou um tipo de enumeração.", + "An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_de_2705": "Uma função ou método assíncrono em ES5/ES3 requer o construtor 'Promise'. Verifique se você tem a declaração para o construtor 'Promise' ou inclua 'ES2015' em sua opção `--lib`.", + "An_async_function_or_method_must_have_a_valid_awaitable_return_type_1057": "Um método ou função assíncrona deve ter um tipo de retorno válido que é possível aguardar.", + "An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_in_2697": "Um método ou função assíncrona deve retornar uma 'Promessa'. Certifique-se de ter uma declaração para 'Promessa' ou inclua 'ES2015' na sua opção `--lib`.", + "An_async_iterator_must_have_a_next_method_2519": "O iterador assíncrono deve ter um método 'next()'.", + "An_element_access_expression_should_take_an_argument_1011": "Uma expressão de acesso do elemento deveria receber um argumento.", + "An_enum_member_cannot_have_a_numeric_name_2452": "Um membro de enumeração não pode ter um nome numérico.", + "An_export_assignment_can_only_be_used_in_a_module_1231": "Uma atribuição de exportação só pode ser usada em um módulo.", + "An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements_2309": "Uma atribuição de exportação não pode ser usada em um módulo com outros elementos exportados.", + "An_export_assignment_cannot_be_used_in_a_namespace_1063": "Uma atribuição de exportação não pode ser usada em um namespace.", + "An_export_assignment_cannot_have_modifiers_1120": "Uma atribuição de exportação não pode ter modificadores.", + "An_export_declaration_can_only_be_used_in_a_module_1233": "Uma declaração de exportação só pode ser usada em um módulo.", + "An_export_declaration_cannot_have_modifiers_1193": "Uma declaração de exportação não pode ter modificadores.", + "An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive_1198": "Um valor de escape Unicode estendido deve estar entre 0x0 e 0x10FFFF, inclusive.", + "An_implementation_cannot_be_declared_in_ambient_contexts_1183": "Uma implementação não pode ser declarada em contextos de ambiente.", + "An_import_declaration_can_only_be_used_in_a_namespace_or_module_1232": "Uma declaração de importação só pode ser usada em um namespace ou módulo.", + "An_import_declaration_cannot_have_modifiers_1191": "Uma declaração de importação não pode ter modificadores.", + "An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead_2691": "Um caminho de importação não pode terminar com uma extensão '{0}'. Considere importar '{1}'.", + "An_index_expression_argument_must_be_of_type_string_number_symbol_or_any_2342": "Um argumento de expressão de índice deve ser do tipo 'string', 'number', 'symbol' ou 'any'.", + "An_index_signature_cannot_have_a_rest_parameter_1017": "Uma assinatura de índice não pode ter um parâmetro rest.", + "An_index_signature_must_have_a_type_annotation_1021": "Uma assinatura de índice deve ter uma anotação de tipo.", + "An_index_signature_must_have_exactly_one_parameter_1096": "Uma assinatura de índice deve ter exatamente um parâmetro.", + "An_index_signature_parameter_cannot_have_a_question_mark_1019": "Um parâmetro de assinatura de índice não pode ter um ponto de interrogação.", + "An_index_signature_parameter_cannot_have_an_accessibility_modifier_1018": "Um parâmetro de assinatura de índice não pode ter um modificador de acessibilidade.", + "An_index_signature_parameter_cannot_have_an_initializer_1020": "Um parâmetro de assinatura de índice não pode ter um inicializador.", + "An_index_signature_parameter_must_have_a_type_annotation_1022": "Um parâmetro de assinatura de índice deve ter uma anotação de tipo.", + "An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead_1336": "Um tipo de parâmetro de assinatura de índice não pode ser um alias de tipo. Considere gravar ' [{0}: {1}]: {2}' em vez disso.", + "An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead_1337": "Um tipo de parâmetro de assinatura de índice não pode ser um tipo de união. Considere usar um tipo de objeto mapeado em vez disso.", + "An_index_signature_parameter_type_must_be_string_or_number_1023": "Um tipo de parâmetro de assinatura de índice deve ser 'string' ou 'number'.", + "An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments_2499": "Uma interface só pode estender um identificador/nome qualificado com argumentos de tipo opcionais.", + "An_interface_may_only_extend_a_class_or_another_interface_2312": "Uma interface só pode estender uma classe ou outra interface.", + "An_interface_property_cannot_have_an_initializer_1246": "Uma propriedade de interface não pode ter um inicializador.", + "An_iterator_must_have_a_next_method_2489": "Um iterador deve ter um método 'next()'.", + "An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name_1118": "Um literal de objeto não pode ter vários acessadores get/set com o mesmo nome.", + "An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode_1117": "Um literal de objeto não pode ter várias propriedades com o mesmo nome no modo estrito.", + "An_object_literal_cannot_have_property_and_accessor_with_the_same_name_1119": "Um literal de objeto não pode ter propriedade e acessador com o mesmo nome.", + "An_object_member_cannot_be_declared_optional_1162": "Um membro de objeto não pode ser declarado como opcional.", + "An_overload_signature_cannot_be_declared_as_a_generator_1222": "A assinatura de sobrecarga não pode ser declarada como geradora.", + "An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_ex_17006": "Uma expressão unária com o operador '{0}' não é permitida no lado esquerdo de uma expressão de exponenciação. Considere delimitar a expressão em parênteses.", + "Annotate_everything_with_types_from_JSDoc_95043": "Anotar tudo com tipos do JSDoc", + "Annotate_with_type_from_JSDoc_95009": "Anotar com o tipo do JSDoc", + "Annotate_with_types_from_JSDoc_95010": "Anotar com os tipos do JSDoc", + "Argument_expression_expected_1135": "Expressão de argumento esperada.", + "Argument_for_0_option_must_be_Colon_1_6046": "O argumento para a opção '{0}' deve ser: {1}.", + "Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_2345": "O argumento do tipo '{0}' não é atribuível ao parâmetro do tipo '{1}'.", + "Array_element_destructuring_pattern_expected_1181": "Padrão de desestruturação de elemento da matriz esperado.", + "Asterisk_Slash_expected_1010": "'*/' esperado.", + "Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_2669": "Acréscimos de escopo global somente podem ser diretamente aninhados em módulos externos ou declarações de módulo de ambiente.", + "Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambien_2670": "Acréscimos de escopo global devem ter o modificador 'declare' a menos que apareçam em contexto já ambiente.", + "Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using__6140": "A descoberta automática para digitações está habilitada no projeto '{0}'. Executando o passe de resolução extra para o módulo '{1}' usando o local do cache '{2}'.", + "Base_class_expressions_cannot_reference_class_type_parameters_2562": "As expressões de classe base não podem referenciar parâmetros de tipo de classe.", + "Base_constructor_return_type_0_is_not_a_class_or_interface_type_2509": "O tipo de retorno do construtor base '{0}' não é um tipo de interface ou classe.", + "Base_constructors_must_all_have_the_same_return_type_2510": "Todos os construtores base devem ter o mesmo tipo de retorno.", + "Base_directory_to_resolve_non_absolute_module_names_6083": "Diretório base para resolver nomes de módulo não absolutos.", + "Basic_Options_6172": "Opções Básicas", + "Binary_digit_expected_1177": "Dígito binário esperado.", + "Binding_element_0_implicitly_has_an_1_type_7031": "O elemento de associação '{0}' tem implicitamente um tipo '{1}'.", + "Block_scoped_variable_0_used_before_its_declaration_2448": "Variável de escopo de bloco '{0}' usada antes da sua declaração.", + "Build_all_projects_including_those_that_appear_to_be_up_to_date_6368": "Compilar todos os projetos, incluindo aqueles que parecem estar atualizados", + "Build_one_or_more_projects_and_their_dependencies_if_out_of_date_6364": "Compilar um ou mais projetos e suas dependências, se estiverem desatualizados", + "Building_project_0_6358": "Compilando o projeto '{0}'...", + "Call_decorator_expression_90028": "Chamar expressão do decorador", + "Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7020": "Assinatura de chamada, que não tem a anotação de tipo de retorno, implicitamente tem um tipo de retorno 'any'.", + "Call_target_does_not_contain_any_signatures_2346": "O destino da chamada não contém nenhuma assinatura.", + "Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_p_2713": "Não foi possível acessar '{0}.{1}' porque '{0}' é um tipo, mas não um namespace. Você quis dizer recuperar o tipo da propriedade '{1}' em '{0}' com '{0}[\"{1}\"]'?", + "Cannot_assign_a_0_constructor_type_to_a_1_constructor_type_2672": "Não é possível atribuir um tipo de construtor '{0}' para um tipo de construtor '{1}'.", + "Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type_2517": "Não é possível atribuir um tipo de construtor abstrato a um tipo de construtor não abstrato.", + "Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property_2540": "Não é possível atribuir a '{0}' porque é uma constante ou uma propriedade de somente leitura.", + "Cannot_assign_to_0_because_it_is_not_a_variable_2539": "Não é possível atribuir a '{0}' porque não é uma variável.", + "Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity_2671": "Não é possível aumentar o módulo '{0}' porque ele resolve para uma entidade não módulo.", + "Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity_2649": "Não é possível aumentar o módulo '{0}' com as exportações do valor, porque ele resolve para uma entidade sem módulo.", + "Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system_6131": "Não é possível compilar módulos usando a opção '{0}', a menos que o sinalizador '--module' seja 'amd' ou 'system'.", + "Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided_1208": "Não é possível compilar namespaces quando o sinalizador '--isolatedModules' é fornecido.", + "Cannot_create_an_instance_of_an_abstract_class_2511": "Não é possível criar uma instância de uma classe abstrata.", + "Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module_2661": "Não é possível exportar '{0}'. Somente declarações locais podem ser exportadas de um módulo.", + "Cannot_extend_a_class_0_Class_constructor_is_marked_as_private_2675": "Não é possível estender uma classe '{0}'. O construtor de classe está marcado como privado.", + "Cannot_extend_an_interface_0_Did_you_mean_implements_2689": "Não é possível estender uma interface '{0}'. Você quis dizer 'implements'?", + "Cannot_find_a_tsconfig_json_file_at_the_specified_directory_Colon_0_5057": "Não é possível encontrar um arquivo tsconfig.json no diretório especificado: '{0}'.", + "Cannot_find_global_type_0_2318": "Não é possível encontrar o tipo global '{0}'.", + "Cannot_find_global_value_0_2468": "Não é possível encontrar o valor global '{0}'.", + "Cannot_find_lib_definition_for_0_2726": "Não é possível encontrar a definição de lib para '{0}'.", + "Cannot_find_lib_definition_for_0_Did_you_mean_1_2727": "Não é possível encontrar a definição de lib para '{0}'. Você quis dizer '{1}'?", + "Cannot_find_module_0_2307": "Não é possível encontrar o módulo '{0}'.", + "Cannot_find_name_0_2304": "Não é possível encontrar o nome '{0}'.", + "Cannot_find_name_0_Did_you_mean_1_2552": "Não é possível localizar o nome '{0}'. Você quis dizer '{1}'?", + "Cannot_find_name_0_Did_you_mean_the_instance_member_this_0_2663": "Não foi possível localizar o nome '{0}'. Você quis dizer o membro de instância 'this.{0}'?", + "Cannot_find_name_0_Did_you_mean_the_static_member_1_0_2662": "Não foi possível encontrar o nome '{0}'. Você quis dizer o membro estático '{1}.{0}'?", + "Cannot_find_namespace_0_2503": "Não é possível encontrar o namespace '{0}'.", + "Cannot_find_parameter_0_1225": "Não é possível encontrar o parâmetro '{0}'.", + "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009": "Não é possível encontrar o caminho do subdiretório comum para os arquivos de entrada.", + "Cannot_find_type_definition_file_for_0_2688": "Não é possível encontrar o arquivo de definição de tipo para '{0}'.", + "Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1_6137": "Não é possível importar arquivos de declaração de tipo. Considere a possibilidade de importar '{0}' em vez de '{1}'.", + "Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1_2481": "Não é possível inicializar a variável com escopo externo '{0}' no mesmo escopo que a declaração de escopo de bloco '{1}'.", + "Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatur_2349": "Não é possível invocar uma expressão cujo tipo não tem uma assinatura de chamada. O tipo '{0}' não tem assinaturas de chamada compatíveis.", + "Cannot_invoke_an_object_which_is_possibly_null_2721": "Não é possível invocar um objeto que é possivelmente 'nulo'.", + "Cannot_invoke_an_object_which_is_possibly_null_or_undefined_2723": "Não é possível invocar um objeto que é possivelmente 'nulo' ou 'indefinido'.", + "Cannot_invoke_an_object_which_is_possibly_undefined_2722": "Não é possível invocar um objeto que é possivelmente 'indefinido'.", + "Cannot_prepend_project_0_because_it_does_not_have_outFile_set_6308": "Não é possível preceder o projeto '{0}' porque ele não tem o conjunto 'outFile'", + "Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205": "Não será possível reexportar um tipo quando o sinalizador '--isolatedModules' for fornecido.", + "Cannot_read_file_0_Colon_1_5012": "Não é possível ler o arquivo '{0}': {1}.", + "Cannot_redeclare_block_scoped_variable_0_2451": "Não é possível declarar novamente a variável de escopo de bloco '{0}'.", + "Cannot_redeclare_exported_variable_0_2323": "Não é possível redeclarar a variável exportada '{0}'.", + "Cannot_redeclare_identifier_0_in_catch_clause_2492": "Não é possível declarar novamente o identificador '{0}' na cláusula catch.", + "Cannot_use_JSX_unless_the_jsx_flag_is_provided_17004": "Não é possível usar JSX, a menos que o sinalizador '--jsx' seja fornecido.", + "Cannot_use_imports_exports_or_module_augmentations_when_module_is_none_1148": "Não será possível usar importações, exportações ou acréscimos de módulo quando '--module' for 'none'.", + "Cannot_use_namespace_0_as_a_type_2709": "Não é possível usar o namespace '{0}' como um tipo.", + "Cannot_use_namespace_0_as_a_value_2708": "Não é possível usar o namespace '{0}' como um valor.", + "Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature_2351": "Não é possível usar 'new' com uma expressão cujo tipo não tem uma chamada ou assinatura de constructo.", + "Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files_5056": "Não é possível gravar o arquivo '{0}' porque ele seria substituído por diversos arquivos de entrada.", + "Cannot_write_file_0_because_it_would_overwrite_input_file_5055": "Não é possível gravar o arquivo '{0}' porque ele substituiria o arquivo de entrada.", + "Catch_clause_variable_cannot_have_a_type_annotation_1196": "A variável de cláusula catch não pode ter uma anotação de tipo.", + "Catch_clause_variable_cannot_have_an_initializer_1197": "A variável de cláusula catch não pode ter um inicializador.", + "Change_0_to_1_90014": "Alterar '{0}' para '{1}'", + "Change_all_extended_interfaces_to_implements_95038": "Alterar todas as interfaces estendidas para 'implements'", + "Change_all_jsdoc_style_types_to_TypeScript_95030": "Alterar todos os tipos de estilo jsdoc para TypeScript", + "Change_all_jsdoc_style_types_to_TypeScript_and_add_undefined_to_nullable_types_95031": "Alterar todos os tipos de estilo jsdoc para TypeScript (e adicionar '| undefined' a tipos que permitem valor nulo)", + "Change_extends_to_implements_90003": "Alterar 'extends' para 'implements'", + "Change_spelling_to_0_90022": "Alterar ortografia para '{0}'", + "Checking_if_0_is_the_longest_matching_prefix_for_1_2_6104": "Verificando se '{0}' é o maior prefixo correspondente para '{1}' - '{2}'.", + "Circular_definition_of_import_alias_0_2303": "Definição circular do alias de importação '{0}'.", + "Circularity_detected_while_resolving_configuration_Colon_0_18000": "Circularidade detectada ao resolver a configuração: {0}", + "Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_functi_2426": "A classe '{0}' define o acessador de membro de instância '{1}', mas a classe estendida '{2}' o define como uma função de membro de instância.", + "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_access_2423": "A classe '{0}' define a função de membro de instância '{1}', mas a classe estendida '{2}' a define como um acessador de membro de instância.", + "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_proper_2424": "A classe '{0}' define a função de membro de instância '{1}', mas a classe estendida '{2}' a define como uma propriedade de membro de instância.", + "Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_functi_2425": "A classe '{0}' define a propriedade de membro de instância '{1}', mas a classe estendida '{2}' a define como uma função de membro de instância.", + "Class_0_incorrectly_extends_base_class_1_2415": "A classe '{0}' estende incorretamente a classe base '{1}'.", + "Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclas_2720": "A classe '{0}' implementa incorretamente a classe '{1}'. Você pretendia estender '{1}' e herdar seus membros como uma subclasse?", + "Class_0_incorrectly_implements_interface_1_2420": "A classe '{0}' implementa incorretamente a interface '{1}'.", + "Class_0_used_before_its_declaration_2449": "Classe '{0}' usada antes de sua declaração.", + "Class_declarations_cannot_have_more_than_one_augments_or_extends_tag_8025": "Declarações de classe não podem ter mais de uma marca `@augments` ou `@extends`.", + "Class_name_cannot_be_0_2414": "O nome de classe não pode ser '{0}'.", + "Class_name_cannot_be_Object_when_targeting_ES5_with_module_0_2725": "O nome da classe não pode ser 'Object' ao direcionar ES5 com módulo {0}.", + "Class_static_side_0_incorrectly_extends_base_class_static_side_1_2417": "O lado estático da classe '{0}' incorretamente estende o lado estático da classe base '{1}'.", + "Classes_can_only_extend_a_single_class_1174": "Classes só podem estender uma única classe.", + "Classes_containing_abstract_methods_must_be_marked_abstract_2514": "As classes que contêm métodos abstratos devem ser marcadas como abstratas.", + "Command_line_Options_6171": "Opções da Linha de Comando", + "Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json_6020": "Compile o projeto dando o caminho para seu arquivo de configuração ou para uma pasta com um 'tsconfig.json'.", + "Compiler_option_0_expects_an_argument_6044": "A opção do compilador '{0}' espera um argumento.", + "Compiler_option_0_requires_a_value_of_type_1_5024": "A opção do compilador '{0}' requer um valor do tipo {1}.", + "Composite_projects_may_not_disable_declaration_emit_6304": "Projetos compostos não podem desabilitar a emissão de declaração.", + "Computed_property_names_are_not_allowed_in_enums_1164": "Nomes de propriedade calculados não são permitidos em enums.", + "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553": "Os valores computados não são permitidos em uma enumeração com membros de valor de cadeia de caracteres.", + "Concatenate_and_emit_output_to_single_file_6001": "Concatenar e emitir saída para um arquivo único.", + "Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_librar_4090": "Foram encontradas definições em conflito para '{0}' em '{1}' e em '{2}'. Considere instalar uma versão específica desta biblioteca para solucionar o conflito.", + "Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7013": "Assinatura de constructo, que não tem a anotação de tipo de retorno, implicitamente tem um tipo de retorno 'any'.", + "Constructor_implementation_is_missing_2390": "Implementação do construtor ausente.", + "Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration_2673": "O construtor de classe '{0}' é privado e somente acessível na declaração de classe.", + "Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration_2674": "O construtor de classe '{0}' é protegido e somente acessível na declaração de classe.", + "Constructors_for_derived_classes_must_contain_a_super_call_2377": "Construtores para classes derivadas devem conter uma chamada 'super'.", + "Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126": "O arquivo contido não foi especificado e o diretório raiz não pode ser determinado, ignorando a pesquisa na pasta 'node_modules'.", + "Convert_0_to_mapped_object_type_95055": "Converter '{0}' para o tipo de objeto mapeado", + "Convert_all_constructor_functions_to_classes_95045": "Converter todas as funções de construtor em classes", + "Convert_all_require_to_import_95048": "Converter todos os 'require' em 'import'", + "Convert_all_to_default_imports_95035": "Converter tudo para importações padrão", + "Convert_function_0_to_class_95002": "Converter função '{0}' em classe", + "Convert_function_to_an_ES2015_class_95001": "Converter função em uma classe ES2015", + "Convert_named_imports_to_namespace_import_95057": "Converter importações nomeadas em importação de namespace", + "Convert_namespace_import_to_named_imports_95056": "Converter importação de namespace em importações nomeadas", + "Convert_require_to_import_95047": "Converter 'require' em 'import'", + "Convert_to_ES6_module_95017": "Converter em módulo ES6", + "Convert_to_default_import_95013": "Converter para importação padrão", + "Corrupted_locale_file_0_6051": "Arquivo de localidade {0} corrompido.", + "Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type_7016": "Não foi possível localizar o arquivo de declaração para o módulo '{0}'. '{1}' tem implicitamente um tipo 'any'.", + "Could_not_write_file_0_Colon_1_5033": "Não foi possível gravar o arquivo '{0}': {1}.", + "DIRECTORY_6038": "DIRETÓRIO", + "Declaration_expected_1146": "Declaração esperada.", + "Declaration_name_conflicts_with_built_in_global_identifier_0_2397": "O nome de declaração entra em conflito com o identificador global integrado '{0}'.", + "Declaration_or_statement_expected_1128": "Declaração ou instrução esperada.", + "Declare_method_0_90023": "Declarar método '{0}'", + "Declare_property_0_90016": "Declarar propriedade '{0}'", + "Declare_static_method_0_90024": "Declarar método estático '{0}'", + "Declare_static_property_0_90027": "Declarar propriedade estática '{0}'", + "Decorators_are_not_valid_here_1206": "Os decoradores não são válidos aqui.", + "Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name_1207": "Os decoradores não podem ser aplicados a vários acessadores get/set de mesmo nome.", + "Default_export_of_the_module_has_or_is_using_private_name_0_4082": "A exportação padrão do módulo tem ou está usando o nome particular '{0}'.", + "Delete_all_unused_declarations_95024": "Excluir todas as declarações não usadas", + "Delete_the_outputs_of_all_projects_6365": "Excluir as saídas de todos os projetos", + "Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react__6084": "[Preterido] Use '--jsxFactory' no lugar. Especifique o objeto invocado para createElement ao direcionar uma emissão de JSX 'react'", + "Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file_6170": "[Preterido] Use '--outFile' no lugar. Concatene e emita uma saída para um arquivo único", + "Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files_6160": "[Preterido] Use '--skipLibCheck' no lugar. Ignore a verificação de tipo dos arquivos de declaração de biblioteca padrão.", + "Digit_expected_1124": "Dígito esperado.", + "Directory_0_does_not_exist_skipping_all_lookups_in_it_6148": "O diretório '{0}' não existe; ignorando todas as pesquisas nele.", + "Disable_checking_for_this_file_90018": "Desabilitar a verificação para esse arquivo", + "Disable_size_limitations_on_JavaScript_projects_6162": "Desabilitar as limitações de tamanho nos projetos JavaScript.", + "Disable_strict_checking_of_generic_signatures_in_function_types_6185": "Desabilitar verificação estrita de assinaturas genéricas em tipos de função.", + "Disallow_inconsistently_cased_references_to_the_same_file_6078": "Não permitir referências com maiúsculas de minúsculas inconsistentes no mesmo arquivo.", + "Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files_6159": "Não adicionar as referências de barra tripla nem os módulos importados à lista de arquivos compilados.", + "Do_not_emit_comments_to_output_6009": "Não emita comentários para a saída.", + "Do_not_emit_declarations_for_code_that_has_an_internal_annotation_6056": "Não emita declarações de código que contenham uma anotação '@internal'.", + "Do_not_emit_outputs_6010": "Não emita saídas.", + "Do_not_emit_outputs_if_any_errors_were_reported_6008": "Não emita saídas se erros forem reportados.", + "Do_not_emit_use_strict_directives_in_module_output_6112": "Não emita diretivas 'use strict' na saída de módulo.", + "Do_not_erase_const_enum_declarations_in_generated_code_6007": "Não apague declarações const enum no código gerado.", + "Do_not_generate_custom_helper_functions_like_extends_in_compiled_output_6157": "Não gerar funções auxiliares personalizadas como '__extends' nas saídas compiladas.", + "Do_not_include_the_default_library_file_lib_d_ts_6158": "Não incluir o arquivo de biblioteca padrão (lib.d.ts).", + "Do_not_report_errors_on_unreachable_code_6077": "Não relate erros sobre código inacessível.", + "Do_not_report_errors_on_unused_labels_6074": "Não relate erros sobre rótulos não utilizados.", + "Do_not_resolve_the_real_path_of_symlinks_6013": "Não resolver o real caminho de symlinks.", + "Do_not_truncate_error_messages_6165": "Não truncar as mensagens de erro.", + "Duplicate_declaration_0_2718": "Declaração duplicada '{0}'.", + "Duplicate_function_implementation_2393": "Implementação de função duplicada.", + "Duplicate_identifier_0_2300": "Identificador '{0}' duplicado.", + "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_2441": "Identificador duplicado '{0}'. O compilador reserva o nome '{1}' no escopo de nível superior de um módulo.", + "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_func_2529": "Duplicar o identificador '{0}'. O compilador reserva o nome '{1}' em escopo de alto nível de um módulo que contém funções assíncronas.", + "Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions_2520": "Identificador '{0}' duplicado. O compilador usa a declaração '{1}' para dar suporte a funções assíncronas.", + "Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters_2396": "Identificador 'arguments' duplicado. O compilador usa 'arguments' para inicializar os parâmetros rest.", + "Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_me_2543": "Identificador duplicado '_newTarget'. O compilador usa a declaração de variável '_newTarget' para capturar a referência de metapropriedade 'new.target'.", + "Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference_2401": "Identificador '_super' duplicado. O compilador usa '_super' para capturar a referência da classe base.", + "Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference_2399": "Identificador '_this' duplicado. O compilador usa a declaração de variável '_this' para capturar a referência 'this'.", + "Duplicate_label_0_1114": "Rótulo '{0}' duplicado.", + "Duplicate_number_index_signature_2375": "Assinatura de índice de número duplicado.", + "Duplicate_string_index_signature_2374": "Assinatura de índice de cadeia de caracteres duplicada.", + "Dynamic_import_cannot_have_type_arguments_1326": "A importação dinâmica não pode ter argumentos de tipo", + "Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext_1323": "Só há suporte para importação dinâmica quando o sinalizador '--module' é 'commonjs' ou 'esNext'.", + "Dynamic_import_must_have_one_specifier_as_an_argument_1324": "A importação dinâmica deve ter um especificador como um argumento.", + "Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036": "O especificador da importação dinâmica deve ser do tipo 'string', mas aqui tem o tipo '{0}'.", + "Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015": "O elemento implicitamente tem um tipo 'any' porque a expressão de índice não é do tipo 'number'.", + "Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature_7017": "O elemento tem, implicitamente, 'qualquer' tipo, pois o tipo '{0}' não tem assinatura de índice.", + "Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files_6164": "Emitir uma Marca de Ordem de Byte (BOM) UTF-8 no início dos arquivos de saída.", + "Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file_6151": "Emitir um arquivo único com os mapas de origem em vez de arquivos separados.", + "Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap__6152": "Emitir a origem ao lado dos sourcemaps em um arquivo único; a definição requer '--inlineSourceMap' ou '--sourceMap'.", + "Enable_all_strict_type_checking_options_6180": "Habilitar todas as opções estritas de verificação de tipo.", + "Enable_project_compilation_6302": "Habilitar a compilação do projeto", + "Enable_strict_checking_of_function_types_6186": "Habilitar verificação estrita de tipos de função.", + "Enable_strict_checking_of_property_initialization_in_classes_6187": "Habilite a verificação estrita de inicialização de propriedade nas classes.", + "Enable_strict_null_checks_6113": "Habilite verificações nulas estritas.", + "Enable_tracing_of_the_name_resolution_process_6085": "Habilite o rastreio do processo de resolução de nome.", + "Enable_verbose_logging_6366": "Habilitar registro em log detalhado", + "Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for__7037": "Permite emissão de interoperabilidade entre CommonJS e Módulos ES através da criação de objetos de namespace para todas as importações. Implica em 'allowSyntheticDefaultImports'.", + "Enables_experimental_support_for_ES7_async_functions_6068": "Habilita o suporte experimental para funções assíncronas de ES7.", + "Enables_experimental_support_for_ES7_decorators_6065": "Habilita o suporte experimental para decoradores ES7.", + "Enables_experimental_support_for_emitting_type_metadata_for_decorators_6066": "Habilita o suporte experimental para a emissão de tipo de metadados para decoradores.", + "Enum_0_used_before_its_declaration_2450": "A enumeração '{0}' usada antes de sua declaração.", + "Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations_2567": "As declarações enum só podem ser mescladas com namespaces ou com outras declarações enum.", + "Enum_declarations_must_all_be_const_or_non_const_2473": "Declarações de enumeração devem ser const ou não const.", + "Enum_member_expected_1132": "Membro de enumeração esperado.", + "Enum_member_must_have_initializer_1061": "O membro de enumeração deve ter um inicializador.", + "Enum_name_cannot_be_0_2431": "O nome de enumeração não pode ser '{0}'.", + "Enum_type_0_has_members_with_initializers_that_are_not_literals_2535": "O tipo de Enumeração '{0}' tem membros com inicializadores que não são literais.", + "Examples_Colon_0_6026": "Exemplos: {0}", + "Excessive_stack_depth_comparing_types_0_and_1_2321": "Profundidade da pilha excessiva ao comparar tipos '{0}' e '{1}'.", + "Expected_0_1_type_arguments_provide_these_with_an_extends_tag_8027": "Espera-se {0}-{1} argumentos de tipo; forneça esses recursos com uma marca \"@extends\".", + "Expected_0_arguments_but_got_1_2554": "{0} argumentos eram esperados, mas {1} foram obtidos.", + "Expected_0_arguments_but_got_1_or_more_2556": "Eram {0} argumentos esperados, mas {1} ou mais foram obtidos.", + "Expected_0_type_arguments_but_got_1_2558": "{0} argumentos de tipo eram esperados, mas {1} foram obtidos.", + "Expected_0_type_arguments_provide_these_with_an_extends_tag_8026": "Espera-se {0} argumentos de tipo; forneça esses recursos com uma marca \"@extends\".", + "Expected_at_least_0_arguments_but_got_1_2555": "Pelo menos {0} argumentos eram esperados, mas {1} foram obtidos.", + "Expected_at_least_0_arguments_but_got_1_or_more_2557": "Pelo menos {0} argumentos eram esperados, mas {1} ou mais foram obtidos.", + "Expected_corresponding_JSX_closing_tag_for_0_17002": "Marca de fechamento de JSX correspondente esperada para '{0}'.", + "Expected_corresponding_closing_tag_for_JSX_fragment_17015": "Marca de fechamento correspondente esperada para fragmento JSX.", + "Expected_type_of_0_field_in_package_json_to_be_string_got_1_6105": "O tipo esperado do campo '{0}' em 'package.json' como 'string', obteve '{1}'.", + "Experimental_Options_6177": "Opções Experimentais", + "Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_t_1219": "O suporte experimental de decorador é um recurso que está sujeito a alterações em uma liberação futura. Configure a opção 'experimentalDecorators' para remover este aviso.", + "Explicitly_specified_module_resolution_kind_Colon_0_6087": "Tipo de resolução de módulo especificado explicitamente: '{0}'.", + "Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or__1203": "Não é possível usar a atribuição de exportação durante o direcionamento para módulos de ECMAScript. Use a 'exportação padrão' ou outro formato de módulo em vez disso.", + "Export_assignment_is_not_supported_when_module_flag_is_system_1218": "A atribuição de exportação não tem suporte quando o sinalizador '--module' é 'system'.", + "Export_declaration_conflicts_with_exported_declaration_of_0_2484": "Exportar conflitos de declaração com declaração exportada de '{0}'.", + "Export_declarations_are_not_permitted_in_a_namespace_1194": "As declarações de exportação não são permitidas em um namespace.", + "Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_2656": "O arquivo de digitação '{0}' do pacote externo exportado não é um módulo. Entre em contato com o autor do pacote para atualizar a definição de pacote.", + "Exported_external_package_typings_file_cannot_contain_tripleslash_references_Please_contact_the_pack_2654": "O arquivo de digitação do pacote externo exportado não pode conter referências de barra tripla. Entre em contato com o autor do pacote para atualizar a definição de pacote.", + "Exported_type_alias_0_has_or_is_using_private_name_1_4081": "O alias de tipo exportado '{0}' tem ou está usando o nome particular '{1}'.", + "Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4023": "A variável exportada '{0}' tem ou está usando o nome '{1}' do módulo externo {2}, mas não pode ser nomeada.", + "Exported_variable_0_has_or_is_using_name_1_from_private_module_2_4024": "A variável exportada '{0}' tem ou está usando o nome '{1}' do módulo particular '{2}'.", + "Exported_variable_0_has_or_is_using_private_name_1_4025": "A variável exportada '{0}' tem ou está usando o nome particular '{1}'.", + "Exports_and_export_assignments_are_not_permitted_in_module_augmentations_2666": "Exportações e designações de exportações não são permitidas em acréscimos de módulo.", + "Expression_expected_1109": "Expressão esperada.", + "Expression_or_comma_expected_1137": "Expressão ou vírgula esperada.", + "Expression_resolves_to_super_that_compiler_uses_to_capture_base_class_reference_2402": "A expressão é resolvida como '_super', que o compilador utiliza para capturar a referência da classe base.", + "Expression_resolves_to_variable_declaration_0_that_compiler_uses_to_support_async_functions_2521": "A expressão é resolvida como uma declaração de variável '{0}' que o compilador usa para dar suporte a funções assíncronas.", + "Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta__2544": "A expressão é resolvida para a declaração de variável '_newTarget' que o compilador usa para capturar a referência de metapropriedade 'new.target'.", + "Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference_2400": "A expressão é resolvida como a declaração de variável '_this' que o compilador utiliza para capturar a referência 'this'.", + "Extract_constant_95006": "Extrair constante", + "Extract_function_95005": "Extrair função", + "Extract_to_0_in_1_95004": "Extrair para {0} em {1}", + "Extract_to_0_in_1_scope_95008": "Extrair para {0} no escopo {1}", + "Extract_to_0_in_enclosing_scope_95007": "Extrair para {0} no escopo de delimitação", + "FILE_6035": "ARQUIVO", + "FILE_OR_DIRECTORY_6040": "ARQUIVO OU DIRETÓRIO", + "Failed_to_parse_file_0_Colon_1_5014": "Falha ao analisar arquivo '{0}': {1}.", + "Fallthrough_case_in_switch_7029": "Caso de fallthrough no comutador.", + "File_0_does_not_exist_6096": "O arquivo '{0}' não existe.", + "File_0_exist_use_it_as_a_name_resolution_result_6097": "O arquivo '{0}' existe; use-o como um resultado de resolução de nome.", + "File_0_has_an_unsupported_extension_so_skipping_it_6081": "O arquivo '{0}' tem uma extensão sem suporte, portanto ele será ignorado.", + "File_0_has_unsupported_extension_The_only_supported_extensions_are_1_6054": "O arquivo '{0}' tem extensão sem suporte. As únicas extensões com suporte são {1}.", + "File_0_is_not_a_module_2306": "O arquivo '{0}' não é um módulo.", + "File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern_6307": "O arquivo '{0}' não está na lista de arquivos de projeto. Os projetos devem listar todos os arquivos ou usar um padrão 'include'.", + "File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files_6059": "O arquivo '{0}' não está em 'rootDir' '{1}'. Espera-se que 'rootDir' contenha todos os arquivos de origem.", + "File_0_not_found_6053": "Arquivo '{0}' não encontrado.", + "File_change_detected_Starting_incremental_compilation_6032": "Alteração do arquivo detectada. Iniciando compilação incremental...", + "File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module_80001": "O arquivo é um módulo CommonJS; ele pode ser convertido em um módulo ES6.", + "File_name_0_differs_from_already_included_file_name_1_only_in_casing_1149": "O nome do arquivo '{0}' difere do nome de arquivo '{1}' já incluído somente em maiúsculas e minúsculas.", + "File_name_0_has_a_1_extension_stripping_it_6132": "O nome do arquivo '{0}' tem uma extensão '{1}' – remoção.", + "File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildca_5065": "A especificação de arquivo não pode conter um diretório pai ('..') que aparece após um curinga de diretório recursivo ('**'): '{0}'.", + "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010": "A especificação de arquivo não pode terminar em um curinga do diretório recursivo ('**'): '{0}'.", + "Fix_all_detected_spelling_errors_95026": "Corrigir todos os erros de ortografia detectados", + "Found_0_errors_Watching_for_file_changes_6194": "{0} erros encontrados. Monitorando alterações de arquivo.", + "Found_1_error_Watching_for_file_changes_6193": "Um erro encontrado. Monitorando alterações de arquivo.", + "Found_package_json_at_0_6099": "'package.json' encontrado em '{0}'.", + "Found_package_json_at_0_Package_ID_is_1_6190": "'package.json' encontrado em '{0}'. A ID do pacote é '{1}'.", + "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_1250": "Decorações de função não são permitidas dentro de blocos em modo estrito quando o objetivo é 'ES3' ou 'ES5'.", + "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_d_1251": "Declarações de função não são permitidas dentro de blocos em modo estrito quando o objetivo é 'ES3' ou 'ES5'. Definições de classe estão automaticamente em modo estrito.", + "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_1252": "Declarações de função não são permitidas dentro de blocos em modo estrito quando o objetivo é 'ES3' ou 'ES5'. Módulos estão automaticamente em modo estrito.", + "Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type_7011": "A expressão de função, que não tem a anotação de tipo de retorno, implicitamente tem um tipo de retorno '{0}'.", + "Function_implementation_is_missing_or_not_immediately_following_the_declaration_2391": "A implementação da função está ausente ou não está imediatamente depois da declaração.", + "Function_implementation_name_must_be_0_2389": "O nome da implementação de função deve ser '{0}'.", + "Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_ref_7024": "A função tem o tipo de retorno 'any', de forma implícita, porque ela não tem uma anotação de tipo de retorno e é referenciada direta ou indiretamente em uma das suas expressões de retorno.", + "Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined_2366": "A função não tem a instrução de retorno final e o tipo de retorno não inclui 'undefined'.", + "Function_overload_must_be_static_2387": "A sobrecarga de função deve ser estática.", + "Function_overload_must_not_be_static_2388": "A sobrecarga de função não deve ser estática.", + "Generate_get_and_set_accessors_95046": "Gerar acessadores 'get' e 'set'", + "Generates_a_sourcemap_for_each_corresponding_d_ts_file_6000": "Gera um sourcemap para cada arquivo '.d.ts' correspondente.", + "Generates_corresponding_d_ts_file_6002": "Gera o arquivo '.d.ts' correspondente.", + "Generates_corresponding_map_file_6043": "Gera o arquivo '.map' correspondente.", + "Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_typ_7025": "Implicitamente, o gerador tem o tipo '{0}' porque não produz nenhum valor. Considere fornecer um tipo de retorno.", + "Generators_are_not_allowed_in_an_ambient_context_1221": "Os geradores não são permitidos em um contexto de ambiente.", + "Generators_are_only_available_when_targeting_ECMAScript_2015_or_higher_1220": "Geradores só estão disponíveis ao direcionar para o ECMAScript 2015 ou superior.", + "Generic_type_0_requires_1_type_argument_s_2314": "O tipo genérico '{0}' exige {1} argumento(s) de tipo.", + "Generic_type_0_requires_between_1_and_2_type_arguments_2707": "O tipo genérico '{0}' exige argumentos de tipo entre {1} e {2}.", + "Generic_type_instantiation_is_excessively_deep_and_possibly_infinite_2550": "A instanciação de tipo genérico é muito profunda e possivelmente infinita.", + "Getter_and_setter_accessors_do_not_agree_in_visibility_2379": "Acessadores getter e setter não concordam quanto à visibilidade.", + "Global_module_exports_may_only_appear_at_top_level_1316": "As exportações de módulo global podem somente aparecer no nível superior.", + "Global_module_exports_may_only_appear_in_declaration_files_1315": "As exportações de módulo global podem somente aparecer em arquivos de declaração.", + "Global_module_exports_may_only_appear_in_module_files_1314": "As exportações de módulo global podem somente aparecer em arquivos de módulo.", + "Global_type_0_must_be_a_class_or_interface_type_2316": "O tipo global '{0}' deve ser um tipo de classe ou interface.", + "Global_type_0_must_have_1_type_parameter_s_2317": "O tipo global '{0}' deve ter {1} parâmetro(s) de tipo.", + "Hexadecimal_digit_expected_1125": "Dígito hexadecimal esperado.", + "Identifier_expected_0_is_a_reserved_word_in_strict_mode_1212": "Identificador esperado. '{0}' é uma palavra reservada no modo estrito.", + "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_stric_1213": "Identificador esperado. '{0}' é uma palavra reservada no modo estrito. Definições de classe estão automaticamente no modo estrito.", + "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode_1214": "Identificador esperado. '{0}' é uma palavra reservada em modo estrito. Os módulos ficam automaticamente em modo estrito.", + "Identifier_expected_1003": "Identificador esperado.", + "Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules_1216": "Identificador esperado. '__esModule' é reservado como um marcador exportado ao transformar os módulos ECMAScript.", + "Ignore_this_error_message_90019": "Ignorar essa mensagem de erro", + "Implement_all_inherited_abstract_classes_95040": "Implementar todas as classes abstratas herdadas", + "Implement_all_unimplemented_interfaces_95032": "Implementar todas as interfaces não implementadas", + "Implement_inherited_abstract_class_90007": "Implementar classe abstrata herdada", + "Implement_interface_0_90006": "Implementar a interface '{0}'", + "Implements_clause_of_exported_class_0_has_or_is_using_private_name_1_4019": "A cláusula implements da classe exportada '{0}' tem ou está usando o nome particular '{1}'.", + "Import_0_from_module_1_90013": "Importar '{0}' do módulo \"{1}\"", + "Import_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_import_Asterisk_as_1202": "Não é possível usar a atribuição de importação durante o direcionamento para módulos de ECMAScript. Use 'importar * como ns de \"mod\"', 'importar {a} de \"mod\"', 'importar d de \"mod\"' ou outro formato de módulo em vez disso.", + "Import_declaration_0_is_using_private_name_1_4000": "A declaração da importação '{0}' está usando o nome particular '{1}'.", + "Import_declaration_conflicts_with_local_declaration_of_0_2440": "A declaração da importação está em conflito com a declaração local '{0}'.", + "Import_declarations_in_a_namespace_cannot_reference_a_module_1147": "As declarações de importação em um namespace não podem fazer referência a um módulo.", + "Import_emit_helpers_from_tslib_6139": "Importar auxiliares de emissão de 'tslib'.", + "Import_may_be_converted_to_a_default_import_80003": "A importação pode ser convertida em uma importação padrão.", + "Import_name_cannot_be_0_2438": "O nome da importação não pode ser '{0}'.", + "Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relati_2439": "A declaração de importação e exportação em uma declaração de módulo de ambiente não pode fazer referência ao módulo por meio do nome do módulo relativo.", + "Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_mod_2667": "Importações não são permitidas em acréscimos de módulo. Considere movê-las para o módulo externo delimitador.", + "In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066": "Em declarações de enumeração de ambiente, o inicializador de membro deve ser uma expressão de constante.", + "In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enu_2432": "Em uma enumeração com várias declarações, somente uma declaração pode omitir um inicializador para o primeiro elemento de enumeração.", + "In_const_enum_declarations_member_initializer_must_be_constant_expression_2474": "Em declarações de enumeração 'const', o inicializador de membro deve ser uma expressão de constante.", + "Include_modules_imported_with_json_extension_6197": "Incluir módulos importados com a extensão '.json'", + "Index_signature_in_type_0_only_permits_reading_2542": "Assinatura de índice no tipo '{0}' permite somente leitura.", + "Index_signature_is_missing_in_type_0_2329": "Assinatura de índice ausente no tipo '{0}'.", + "Index_signatures_are_incompatible_2330": "As assinaturas de índice são incompatíveis.", + "Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local_2395": "Todas as declarações individuais na declaração mesclada '{0}' devem ser exportadas ou ficar no local.", + "Infer_all_types_from_usage_95023": "Inferir todos os tipos de uso", + "Infer_parameter_types_from_usage_95012": "Inferir tipos de parâmetro pelo uso", + "Infer_type_of_0_from_usage_95011": "Inferir tipo de '{0}' pelo uso", + "Initialize_property_0_in_the_constructor_90020": "Inicializar a propriedade '{0}' no construtor", + "Initialize_static_property_0_90021": "Inicializar a propriedade estática '{0}'", + "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301": "O inicializador da variável de membro de instância '{0}' não pode referenciar o identificador '{1}' declarado no construtor.", + "Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it_2373": "O inicializador do parâmetro '{0}' não pode referenciar o identificador '{1}' declarado depois dele.", + "Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value_2525": "O inicializador não fornece um valor para esse elemento de associação e o elemento de associação não tem valor padrão.", + "Initializers_are_not_allowed_in_ambient_contexts_1039": "Inicializadores não são permitidos em contextos de ambiente.", + "Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file_6070": "Inicializa um projeto TypeScript e cria um arquivo tsconfig.json.", + "Insert_command_line_options_and_files_from_a_file_6030": "Inserir opções e arquivos de linha de comando de um arquivo.", + "Install_0_95014": "Instalar '{0}'", + "Install_all_missing_types_packages_95033": "Instalar todos os pacotes de tipos ausentes", + "Interface_0_cannot_simultaneously_extend_types_1_and_2_2320": "A interface '{0}' não pode estender os tipos '{1}' e '{2}' simultaneamente.", + "Interface_0_incorrectly_extends_interface_1_2430": "A interface '{0}' estende incorretamente a interface '{1}'.", + "Interface_declaration_cannot_have_implements_clause_1176": "A declaração de interface não pode ter a cláusula 'implements'.", + "Interface_name_cannot_be_0_2427": "O nome da interface não pode ser '{0}'.", + "Invalid_character_1127": "Caractere inválido.", + "Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augm_2665": "Nome de módulo inválido no aumento. O módulo '{0}' resolve para um módulo não tipado em '{1}', que não pode ser aumentado.", + "Invalid_module_name_in_augmentation_module_0_cannot_be_found_2664": "Nome de módulo inválido em acréscimo, o módulo '{0}' não pôde ser encontrado.", + "Invalid_reference_directive_syntax_1084": "Sintaxe de diretiva 'reference' inválida.", + "Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode_1210": "Uso inválido de '{0}'. Definições de classe estão automaticamente no modo estrito.", + "Invalid_use_of_0_Modules_are_automatically_in_strict_mode_1215": "Uso inválido de '{0}'. Os módulos ficam automaticamente em modo estrito.", + "Invalid_use_of_0_in_strict_mode_1100": "Uso inválido de '{0}' no modo estrito.", + "Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name_5067": "Valor inválido para 'jsxFactory'. '{0}' não é um identificador válido ou nome qualificado.", + "Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier_5059": "Valor inválido para '--reactNamespace'. '{0}' não é um identificador válido.", + "JSDoc_0_1_does_not_match_the_extends_2_clause_8023": "O '@{0} {1}' do JSDoc não corresponde à cláusula 'extends {2}'.", + "JSDoc_0_is_not_attached_to_a_class_8022": "O '@{0}' do JSDoc não está anexado a uma classe.", + "JSDoc_may_only_appear_in_the_last_parameter_of_a_signature_8028": "JSDoc '...' só pode aparecer no último parâmetro de uma assinatura.", + "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_8024": "A marcação do JSDoc \"@param\" tem o nome \"{0}\", mas não há nenhum parâmetro com esse nome.", + "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_h_8029": "A marca '@param' do JSDoc tem o nome '{0}', mas não há nenhum parâmetro com esse nome. Ela corresponderia a 'argumentos' se tivesse um tipo de matriz.", + "JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags_8021": "A marca JSDoc \"@typedef\" deve ter uma anotação de tipo ou ser seguida pelas marcas \"@property\" or \"@member\".", + "JSDoc_types_can_only_be_used_inside_documentation_comments_8020": "Os tipos de JSDoc podem ser usados somente dentro dos comentários de documentação.", + "JSDoc_types_may_be_moved_to_TypeScript_types_80004": "Tipos JSDoc podem ser movidos para tipos TypeScript.", + "JSX_attribute_expected_17003": "Atributo JSX esperado.", + "JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000": "Os atributos JSX só devem ser atribuídos a 'expressões' que não estejam vazias.", + "JSX_element_0_has_no_corresponding_closing_tag_17008": "O elemento JSX '{0}' não tem uma marcação de fechamento correspondente.", + "JSX_element_attributes_type_0_may_not_be_a_union_type_2600": "O tipo de atributos de elemento JSX '{0}' não pode ser um tipo de união.", + "JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property_2607": "A classe do elemento JSX não dá suporte a atributos porque não tem uma propriedade '{0}'.", + "JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists_7026": "O elemento JSX implicitamente tem o tipo 'any' porque não há uma interface de 'JSX.{0}'.", + "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602": "O elemento JSX implicitamente tem tipo 'any' porque o tipo global \"JSX.Element\" não existe.", + "JSX_element_type_0_does_not_have_any_construct_or_call_signatures_2604": "O tipo de elemento JSX '{0}' não tem nenhum constructo nem assinaturas de chamadas.", + "JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements_2605": "O tipo de elemento JSX '{0}' não é uma função de construtor para elementos JSX.", + "JSX_elements_cannot_have_multiple_attributes_with_the_same_name_17001": "Elementos JSX não podem ter vários atributos com o mesmo nome.", + "JSX_expressions_must_have_one_parent_element_2657": "As expressões JSX devem ter um elemento pai.", + "JSX_fragment_has_no_corresponding_closing_tag_17014": "O fragmento JSX não tem uma marcação de fechamento correspondente.", + "JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma_17017": "O fragmento de JSX não é compatível ao se utilizar um pragma de fábrica JSX embutido", + "JSX_fragment_is_not_supported_when_using_jsxFactory_17016": "O fragmento JSX não é compatível com o uso de --jsxFactory", + "JSX_spread_child_must_be_an_array_type_2609": "O filho do espalhamento JSX deve ser um tipo de matriz.", + "Jump_target_cannot_cross_function_boundary_1107": "O destino do salto não pode ultrapassar o limite de função.", + "KIND_6034": "TIPO", + "LOCATION_6037": "LOCAL", + "Language_service_is_disabled_9004": "O serviço de linguagem está desabilitado.", + "Left_side_of_comma_operator_is_unused_and_has_no_side_effects_2695": "O operador antes da vírgula não é usado e não tem efeitos colaterais.", + "Line_break_not_permitted_here_1142": "Quebra de linha não permitida aqui.", + "Line_terminator_not_permitted_before_arrow_1200": "Terminador de linha não permitido antes de seta.", + "List_of_folders_to_include_type_definitions_from_6161": "Lista de pastas das quais são incluídas as definições de tipo.", + "List_of_language_service_plugins_6181": "Lista de plug-ins de serviço de linguagem.", + "List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime_6168": "Listas das pastas raiz cujo conteúdo combinado representa a estrutura do projeto no tempo de execução.", + "Loading_0_from_the_root_dir_1_candidate_location_2_6109": "Carregando '{0}' do diretório raiz '{1}', local candidato '{2}'.", + "Loading_module_0_from_node_modules_folder_target_file_type_1_6098": "Carregando o módulo '{0}' da pasta 'node_modules', tipo de arquivo de destino '{1}'.", + "Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1_6095": "Carregando módulo como arquivo/pasta, local do módulo candidato '{0}', tipo de arquivo de destino '{1}'.", + "Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1_6048": "A localidade deve estar no formato ou -. Por exemplo '{0}' ou '{1}'.", + "Longest_matching_prefix_for_0_is_1_6108": "O maior prefixo correspondente para '{0}' é '{1}'.", + "Looking_up_in_node_modules_folder_initial_location_0_6125": "Pesquisando na pasta 'node_modules', local inicial '{0}'.", + "Make_all_super_calls_the_first_statement_in_their_constructor_95036": "Tornar todas as chamadas 'super()' a primeira instrução nos respectivos construtores", + "Make_super_call_the_first_statement_in_the_constructor_90002": "Tornar a chamada 'super()' a primeira instrução no construtor", + "Mapped_object_type_implicitly_has_an_any_template_type_7039": "O tipo de objeto mapeado implicitamente tem um tipo de modelo 'any'.", + "Member_0_implicitly_has_an_1_type_7008": "O membro '{0}' implicitamente tem um tipo '{1}'.", + "Merge_conflict_marker_encountered_1185": "Marcador de conflito de mesclagem encontrado.", + "Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_d_2652": "A declaração mesclada '{0}' não pode conter uma declaração de exportação padrão. Considere adicionar uma declaração 'export default {0}' independente.", + "Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constru_17013": "A metapropriedade '{0}' só é permitida no corpo de uma declaração de função, expressão de função ou construtor.", + "Method_0_cannot_have_an_implementation_because_it_is_marked_abstract_1245": "O método '{0}' não pode ter uma implementação, pois está marcado como abstrato.", + "Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4101": "O método '{0}' da interface exportada tem ou está usando o nome '{1}' do módulo privado '{2}'.", + "Method_0_of_exported_interface_has_or_is_using_private_name_1_4102": "O método '{0}' da interface exportada tem ou está usando o nome privado '{1}'.", + "Modifiers_cannot_appear_here_1184": "Modificadores não podem aparecer aqui.", + "Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_1340": "O módulo '{0}' não faz referência a um tipo, mas é usado como um tipo aqui.", + "Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here_1339": "O módulo '{0}' não faz referência a um valor, mas é usado como um valor aqui.", + "Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambig_2308": "O módulo {0} já exportou um membro denominado '{1}'. Considere reexportar explicitamente para resolver a ambiguidade.", + "Module_0_has_no_default_export_1192": "O módulo '{0}' não tem padrão de exportação.", + "Module_0_has_no_exported_member_1_2305": "O módulo '{0}' não tem nenhum membro exportado '{1}'.", + "Module_0_has_no_exported_member_1_Did_you_mean_2_2724": "O módulo '{0}' não tem nenhum membro '{1}' exportado. Você quis dizer '{2}'?", + "Module_0_is_hidden_by_a_local_declaration_with_the_same_name_2437": "O módulo '{0}' está oculto por uma declaração de local com o mesmo nome.", + "Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct_2497": "O módulo '{0}' resolve para uma entidade sem módulo e não pode ser importado usando este constructo.", + "Module_0_uses_export_and_cannot_be_used_with_export_Asterisk_2498": "O módulo '{0}' usa 'export =' e não pode ser usado com 'export *'.", + "Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified_6145": "O módulo '{0}' foi resolvido como um módulo de ambiente declarado em '{1}', já que este arquivo não foi modificado.", + "Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1_6144": "O módulo '{0}' foi resolvido como módulo de ambiente declarado localmente no arquivo '{1}'.", + "Module_0_was_resolved_to_1_but_jsx_is_not_set_6142": "O módulo '{0}' foi resolvido para '{1}', mas '--jsx' não está configurado.", + "Module_Resolution_Options_6174": "Opções da Resolução de Módulo", + "Module_name_0_matched_pattern_1_6092": "Nome do módulo '{0}', padrão correspondido '{1}'.", + "Module_name_0_was_not_resolved_6090": "======== Nome do módulo '{0}' não foi resolvido. ========", + "Module_name_0_was_successfully_resolved_to_1_6089": "======== Nome do módulo '{0}' foi resolvido com sucesso '{1}'. ========", + "Module_resolution_kind_is_not_specified_using_0_6088": "Resolução de tipo não foi especificado, usando '{0}'.", + "Module_resolution_using_rootDirs_has_failed_6111": "Falha na resolução de módulo usando 'rootDirs'.", + "Move_to_a_new_file_95049": "Mover para um novo arquivo", + "Multiple_consecutive_numeric_separators_are_not_permitted_6189": "Não são permitidos vários separadores numéricos consecutivos.", + "Multiple_constructor_implementations_are_not_allowed_2392": "Não são permitidas várias implementações de construtor.", + "NEWLINE_6061": "NEWLINE", + "Named_property_0_of_types_1_and_2_are_not_identical_2319": "As propriedades com nome '{0}' dos tipos '{1}' e '{2}' não são idênticas.", + "Namespace_0_has_no_exported_member_1_2694": "O namespace '{0}' não tem o membro exportado '{1}'.", + "No_base_constructor_has_the_specified_number_of_type_arguments_2508": "Nenhum construtor base tem o número especificado de argumentos de tipo.", + "No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2_18003": "Nenhuma entrada foi localizada no arquivo de configuração '{0}'. Os caminhos especificados foram 'incluir' '{1}' e 'excluir' '{2}'.", + "Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2_2515": "A classe não abstrata '{0}' não implementa o membro abstrato herdado '{1}' da classe '{2}'.", + "Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1_2653": "A expressão da classe não abstrata não implementa o membro abstrato herdado '{0}' da classe '{1}'.", + "Not_all_code_paths_return_a_value_7030": "Nem todos os caminhos de código retornam um valor.", + "Numeric_index_type_0_is_not_assignable_to_string_index_type_1_2413": "O tipo de índice numérico '{0}' não é atribuível ao tipo de índice de cadeia de caracteres '{1}'.", + "Numeric_separators_are_not_allowed_here_6188": "Separadores numéricos não são permitidos aqui.", + "Object_is_of_type_unknown_2571": "O objeto é do tipo 'desconhecido'.", + "Object_is_possibly_null_2531": "Possivelmente, o objeto é 'nulo'.", + "Object_is_possibly_null_or_undefined_2533": "Possivelmente, o objeto é 'nulo' ou 'indefinido'.", + "Object_is_possibly_undefined_2532": "Possivelmente, o objeto é 'nulo'.", + "Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1_2353": "O literal de objeto pode especificar apenas propriedades conhecidas e '{0}' não existe no tipo '{1}'.", + "Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_writ_2561": "O literal de objeto pode especificar somente propriedades conhecidas, mas o '{0}' não existe no tipo '{1}'. Você queria ter escrito '{2}'?", + "Object_literal_s_property_0_implicitly_has_an_1_type_7018": "A propriedade '{0}' do literal de objeto implicitamente tem um tipo '{1}'.", + "Octal_digit_expected_1178": "Dígito octal esperado.", + "Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0_8017": "Tipos de literais octais devem usar a sintaxe ES2015. Use a sintaxe '{0}'.", + "Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0_8018": "Literais octais não são permitidos em inicializador de membros de enumerações. Use a sintaxe '{0}'.", + "Octal_literals_are_not_allowed_in_strict_mode_1121": "Literais octais não são permitidos no modo estrito.", + "Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0_1085": "Literais octais não estão disponíveis quando se tem como destino ECMAScript 5 e superiores. Use a sintaxe '{0}'.", + "Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement_1091": "É permitida apenas uma única declaração de variável em uma instrução 'for...in'.", + "Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement_1188": "É permitida apenas uma única declaração de variável em uma instrução 'for...of'.", + "Only_a_void_function_can_be_called_with_the_new_keyword_2350": "Apenas uma função void pode ser chamada com a palavra-chave 'new'.", + "Only_ambient_modules_can_use_quoted_names_1035": "Somente os módulos de ambiente podem usar nomes entre aspas.", + "Only_amd_and_system_modules_are_supported_alongside_0_6082": "Há suporte somente aos módulos 'amd' e 'system' ao lado de --{0}.", + "Only_emit_d_ts_declaration_files_6014": "Emita somente arquivos de declaração '.d.ts'.", + "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002": "Somente os identificadores/nomes qualificados com argumentos de tipo opcionais tem suporte atualmente nas cláusulas de classe 'extends'.", + "Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword_2340": "Somente métodos protegidos e públicos da classe base são acessíveis pela palavra-chave 'super'.", + "Operator_0_cannot_be_applied_to_types_1_and_2_2365": "O operador '{0}' não pode ser aplicado aos tipos '{1}' e '{2}'.", + "Option_0_can_only_be_specified_in_tsconfig_json_file_6064": "A opção '{0}' só pode ser especificada no arquivo 'tsconfig.json'.", + "Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided_5051": "A opção '{0} só pode ser usada quando qualquer uma das opções '--inlineSourceMap' ou '--sourceMap' é fornecida.", + "Option_0_cannot_be_specified_with_option_1_5053": "A opção '{0}' não pode ser especificada com a opção '{1}'.", + "Option_0_cannot_be_specified_without_specifying_option_1_5052": "A opção '{0}' não pode ser especificada sem especificar a opção '{1}'.", + "Option_0_cannot_be_specified_without_specifying_option_1_or_option_2_5069": "A opção '{0}' não pode ser especificada sem a especificação da opção '{1}' ou '{2}'.", + "Option_0_should_have_array_of_strings_as_a_value_6103": "A opção '{0}' deve ter matriz de cadeias de um valor.", + "Option_build_must_be_the_first_command_line_argument_6369": "A opção '--build' precisa ser o primeiro argumento da linha de comando.", + "Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES_5047": "A opção 'isolatedModules' só pode ser usada quando nenhuma opção de '--module' for fornecida ou a opção 'target' for 'ES2015' ou superior.", + "Option_paths_cannot_be_used_without_specifying_baseUrl_option_5060": "A opção 'paths' não pode ser usada sem se especificar a opção '--baseUrl'.", + "Option_project_cannot_be_mixed_with_source_files_on_a_command_line_5042": "A opção 'project' não pode ser mesclada com arquivos de origem em uma linha de comando.", + "Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070": "A opção '--resolveJsonModule' não pode ser especificada sem a estratégia de resolução de módulo de 'nó'.", + "Options_0_and_1_cannot_be_combined_6370": "As opções '{0}' e '{1}' não podem ser combinadas.", + "Options_Colon_6027": "Opções:", + "Output_directory_for_generated_declaration_files_6166": "Diretório de saída para os arquivos de declaração gerados.", + "Output_file_0_from_project_1_does_not_exist_6309": "O arquivo de saída '{0}' do projeto '{1}' não existe", + "Output_file_0_has_not_been_built_from_source_file_1_6305": "O arquivo de saída '{0}' não foi compilado do arquivo de origem '{1}'.", + "Overload_signature_is_not_compatible_with_function_implementation_2394": "A assinatura de sobrecarga não é compatível com a implementação da função.", + "Overload_signatures_must_all_be_abstract_or_non_abstract_2512": "Assinaturas de sobrecarga devem todas ser abstratas ou não abstratas.", + "Overload_signatures_must_all_be_ambient_or_non_ambient_2384": "Todas as assinaturas de sobrecarga devem ser ambiente ou não ambiente.", + "Overload_signatures_must_all_be_exported_or_non_exported_2383": "Assinaturas de sobrecarga devem todas ser exportadas ou não exportadas.", + "Overload_signatures_must_all_be_optional_or_required_2386": "Todas as assinaturas de sobrecarga devem ser opcionais ou obrigatórias.", + "Overload_signatures_must_all_be_public_private_or_protected_2385": "Todas as assinaturas de sobrecarga devem ser protegidas, privadas ou públicas.", + "Parameter_0_cannot_be_referenced_in_its_initializer_2372": "O parâmetro '{0}' não pode ser referenciado em seu inicializador.", + "Parameter_0_implicitly_has_an_1_type_7006": "O parâmetro '{0}' implicitamente tem um tipo '{1}'.", + "Parameter_0_is_not_in_the_same_position_as_parameter_1_1227": "O parâmetro '{0}' não está na mesma posição que o parâmetro '{1}'.", + "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4066": "O parâmetro '{0}' da assinatura de chamada da interface exportada tem ou está usando o nome '{1}' do módulo particular '{2}'.", + "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4067": "O parâmetro '{0}' da assinatura de chamada da interface exportada tem ou está usando o nome particular '{1}'.", + "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_can_4061": "O parâmetro '{0}' do construtor da classe exportada tem ou está usando o nome '{1}' do módulo externo {2}, mas não pode ser nomeado.", + "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2_4062": "O parâmetro '{0}' do construtor da classe exportada tem ou está usando o nome '{1}' do módulo particular '{2}'.", + "Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1_4063": "O parâmetro '{0}' do construtor da classe exportada tem ou está usando o nome particular '{1}'.", + "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_mod_4064": "O parâmetro '{0}' da assinatura de construtor da interface exportada tem ou está usando o nome '{1}' do módulo particular '{2}'.", + "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4065": "O parâmetro '{0}' da assinatura de construtor da interface exportada tem ou está usando o nome particular '{1}'.", + "Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4076": "O parâmetro '{0}' da função exportada tem ou está usando o nome '{1}' do módulo externo {2}, mas não pode ser nomeado.", + "Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2_4077": "O parâmetro '{0}' da função exportada tem ou está usando o nome '{1}' do módulo particular '{2}'.", + "Parameter_0_of_exported_function_has_or_is_using_private_name_1_4078": "O parâmetro '{0}' da função exportada tem ou está usando o nome particular '{1}'.", + "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4091": "O parâmetro '{0}' da assinatura de índice da interface exportada tem ou está usando o nome '{1}' do módulo privado '{2}'.", + "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1_4092": "O parâmetro '{0}' da assinatura de índice da interface exportadas tem ou está usando o nome privado '{1}'.", + "Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4074": "O parâmetro '{0}' do método da interface exportada tem ou está usando o nome '{1}' do módulo particular '{2}'.", + "Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4075": "O parâmetro '{0}' do método da interface exportada tem ou está usando o nome particular '{1}'.", + "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_c_4071": "O parâmetro '{0}' do método público da classe exportada tem ou está usando o nome '{1}' do módulo externo {2}, mas não pode ser nomeado.", + "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4072": "O parâmetro '{0}' do método público da classe exportada tem ou está usando o nome '{1}' do módulo particular '{2}'.", + "Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4073": "O parâmetro '{0}' do método público da classe exportada tem ou está usando o nome particular '{1}'.", + "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module__4068": "O parâmetro '{0}' do método estático público da classe exportada tem ou está usando o nome '{1}' do módulo externo {2}, mas não pode ser nomeado.", + "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4069": "O parâmetro '{0}' do método estático público da classe exportada tem ou está usando o nome '{1}' do módulo particular '{2}'.", + "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4070": "O parâmetro '{0}' do método estático público da classe exportada tem ou está usando o nome particular '{1}'.", + "Parameter_cannot_have_question_mark_and_initializer_1015": "O parâmetro não pode ter inicializador e ponto de interrogação.", + "Parameter_declaration_expected_1138": "Declaração de parâmetro esperada.", + "Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2_4036": "O tipo de parâmetro do setter público '{0}' da classe exportada tem ou está usando o nome '{1}' do módulo privado '{2}'.", + "Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_private_name_1_4037": "O tipo de parâmetro do setter público '{0}' da classe exportada tem ou está usando o nome privado '{1}'.", + "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_name_1_from_private_mod_4034": "O tipo de parâmetro do setter estático público '{0}' da classe exportada tem ou está usando o nome '{1}' do módulo privado '{2}'.", + "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1_4035": "O tipo de parâmetro do setter estático público '{0}' da classe exportada tem ou está usando o nome privado '{1}'.", + "Parse_in_strict_mode_and_emit_use_strict_for_each_source_file_6141": "Analisar em modo estrito e emitir \"usar estrito\" para cada arquivo de origem.", + "Pattern_0_can_have_at_most_one_Asterisk_character_5061": "O padrão '{0}' pode ter no máximo um caractere '*'.", + "Prefix_0_with_an_underscore_90025": "Prefixo '{0}' com um sublinhado", + "Prefix_all_unused_declarations_with_where_possible_95025": "Prefixar com '_' todas as declarações não usadas quando possível", + "Print_names_of_files_part_of_the_compilation_6155": "Nomes de impressão das partes dos arquivos da compilação.", + "Print_names_of_generated_files_part_of_the_compilation_6154": "Nomes de impressão das partes dos arquivos gerados da compilação.", + "Print_the_compiler_s_version_6019": "Imprima a versão do compilador.", + "Print_this_message_6017": "Imprima esta mensagem.", + "Project_0_can_t_be_built_because_its_dependency_1_has_errors_6363": "O projeto '{0}' não pode ser compilado porque sua dependência '{1}' tem erros", + "Project_0_is_out_of_date_because_its_dependency_1_is_out_of_date_6353": "O projeto '{0}' está desatualizado porque sua dependência '{1}' está desatualizada", + "Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2_6350": "O projeto '{0}' está desatualizado porque a saída mais antiga '{1}' é mais antiga que a entrada mais recente '{2}'", + "Project_0_is_out_of_date_because_output_file_1_does_not_exist_6352": "O projeto '{0}' está desatualizado porque o arquivo de saída '{1}' não existe", + "Project_0_is_up_to_date_6361": "O projeto '{0}' está atualizado", + "Project_0_is_up_to_date_because_newest_input_1_is_older_than_oldest_output_2_6351": "O projeto '{0}' está atualizado porque a entrada mais recente '{1}' é mais antiga que a saída mais antiga '{2}'", + "Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies_6354": "O projeto '{0}' está atualizado com os arquivos .d.ts de suas dependências", + "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202": "Referências de projeto não podem formar um gráfico circular. Ciclo detectado: {0}", + "Projects_in_this_build_Colon_0_6355": "Projetos neste build: {0}", + "Projects_to_reference_6300": "Projetos a serem referenciados", + "Property_0_does_not_exist_on_const_enum_1_2479": "A propriedade '{0}' não existe na enumeração 'const' '{1}'.", + "Property_0_does_not_exist_on_type_1_2339": "A propriedade '{0}' não existe no tipo '{1}'.", + "Property_0_does_not_exist_on_type_1_Did_you_forget_to_use_await_2570": "A propriedade '{0}' não existe no tipo '{1}'. Você esqueceu de usar 'await'?", + "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551": "A propriedade '{0}' não existe no tipo '{1}'. Você quis dizer '{2}'?", + "Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1_2546": "A propriedade '{0}' tem declarações conflitantes e é inacessível no tipo '{1}'.", + "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor_2564": "A propriedade '{0}' não tem nenhum inicializador e não está definitivamente atribuída no construtor.", + "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033": "A propriedade '{0}' tem implicitamente o tipo 'any' porque o acessador get não tem uma anotação de tipo de retorno.", + "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032": "A propriedade '{0}' tem implicitamente o tipo 'any' porque o acessador set não tem uma anotação de tipo de parâmetro.", + "Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2_2416": "A propriedade '{0}' no tipo '{1}' não pode ser atribuída à mesma propriedade no tipo base '{2}'.", + "Property_0_in_type_1_is_not_assignable_to_type_2_2603": "A propriedade '{0}' no tipo '{1}' não pode ser atribuída ao tipo '{2}'.", + "Property_0_is_declared_but_its_value_is_never_read_6138": "A propriedade '{0}' é declarada, mas seu valor nunca é lido.", + "Property_0_is_incompatible_with_index_signature_2530": "A propriedade '{0}' é incompatível com a assinatura de índice.", + "Property_0_is_missing_in_type_1_2324": "A propriedade '{0}' está ausente no tipo '{1}'.", + "Property_0_is_optional_in_type_1_but_required_in_type_2_2327": "A propriedade '{0}' é opcional no tipo '{1}', mas obrigatória no tipo '{2}'.", + "Property_0_is_private_and_only_accessible_within_class_1_2341": "A propriedade '{0}' é particular e somente é acessível na classe '{1}'.", + "Property_0_is_private_in_type_1_but_not_in_type_2_2325": "A propriedade '{0}' é particular no tipo '{1}', mas não no tipo '{2}'.", + "Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1_2446": "A propriedade '{0}' é protegida e somente é acessível por meio de uma instância da classe '{1}'.", + "Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses_2445": "A propriedade '{0}' é protegida e somente é acessível na classe '{1}' e em suas subclasses.", + "Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2_2443": "A propriedade '{0}' é protegida, mas o tipo '{1}' não é uma classe derivada de '{2}'.", + "Property_0_is_protected_in_type_1_but_public_in_type_2_2444": "A propriedade '{0}' é protegida no tipo '{1}', mas pública no tipo '{2}'.", + "Property_0_is_used_before_being_assigned_2565": "A propriedade '{0}' é usada antes de ser atribuída.", + "Property_0_of_JSX_spread_attribute_is_not_assignable_to_target_property_2606": "A propriedade \"{0}\" do atributo de espalhamento JSX não pode ser atribuída à propriedade de destino.", + "Property_0_of_exported_class_expression_may_not_be_private_or_protected_4094": "A propriedade '{0}' da expressão de classe exportada não pode ser privada nem protegida.", + "Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4032": "A propriedade '{0}' da interface exportada tem ou está usando o nome '{1}' do módulo particular '{2}'.", + "Property_0_of_exported_interface_has_or_is_using_private_name_1_4033": "A propriedade '{0}' da interface exportada tem ou está usando o nome particular '{1}'.", + "Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2_2412": "A propriedade '{0}' do tipo '{1}' não é atribuível ao tipo de índice numérico '{2}'.", + "Property_0_of_type_1_is_not_assignable_to_string_index_type_2_2411": "A propriedade '{0}' do tipo '{1}' não é atribuível ao tipo de índice de cadeia de caracteres '{2}'.", + "Property_assignment_expected_1136": "Atribuição de propriedade esperada.", + "Property_destructuring_pattern_expected_1180": "Padrão de desestruturação de propriedade esperado.", + "Property_or_signature_expected_1131": "Propriedade ou assinatura esperada.", + "Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_li_1328": "O valor da propriedade pode ser somente um literal de cadeia, um literal numérico, 'true', 'false', 'null', literal de objeto ou literal de matriz.", + "Provide_full_support_for_iterables_in_for_of_spread_and_destructuring_when_targeting_ES5_or_ES3_6179": "Fornecer suporte completo para os iteráveis em 'for-of', espalhamento e desestruturação ao direcionar 'ES5' ou 'ES3'.", + "Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4098": "O método público '{0}' da classe exportada tem ou está usando o nome '{1}' do módulo externo {2}, mas não pode ser nomeado.", + "Public_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4099": "O método público '{0}' da classe exportada tem ou está usando o nome '{1}' do módulo privado '{2}'.", + "Public_method_0_of_exported_class_has_or_is_using_private_name_1_4100": "O método público '{0}' da classe exportada tem ou está usando o nome privado '{1}'.", + "Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_name_4029": "A propriedade pública '{0}' da classe exportada tem ou está usando o nome '{1}' do módulo externo {2}, mas não pode ser nomeada.", + "Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4030": "A propriedade pública '{0}' da classe exportada tem ou está usando o nome '{1}' do módulo particular '{2}'.", + "Public_property_0_of_exported_class_has_or_is_using_private_name_1_4031": "A propriedade pública '{0}' da classe exportada tem ou está usando o nome particular '{1}'.", + "Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_4095": "O método estático público '{0}' da classe exportada tem ou está usando o nome '{1}' do módulo externo {2}, mas não pode ser nomeado.", + "Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4096": "O método estático público '{0}' da classe exportada tem ou está usando o nome '{1}' do módulo privado '{2}'.", + "Public_static_method_0_of_exported_class_has_or_is_using_private_name_1_4097": "O método estático público '{0}' da classe exportada tem ou está usando o nome privado '{1}'.", + "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot__4026": "A propriedade estática pública '{0}' da classe exportada tem ou está usando o nome '{1}' do módulo externo {2}, mas não pode ser nomeada.", + "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4027": "A propriedade estática pública '{0}' da classe exportada tem ou está usando o nome '{1}' do módulo particular '{2}'.", + "Public_static_property_0_of_exported_class_has_or_is_using_private_name_1_4028": "A propriedade estática pública '{0}' da classe exportada tem ou está usando o nome particular '{1}'.", + "Raise_error_on_expressions_and_declarations_with_an_implied_any_type_6052": "Gerar erro em expressões e declarações com um tipo 'any' implícito.", + "Raise_error_on_this_expressions_with_an_implied_any_type_6115": "Gerar erro em expressões 'this' com um tipo 'any' implícito.", + "Redirect_output_structure_to_the_directory_6006": "Redirecione a estrutura de saída para o diretório.", + "Referenced_project_0_must_have_setting_composite_Colon_true_6306": "O projeto referenciado '{0}' deve ter a configuração de \"composite\": true.", + "Remove_all_unreachable_code_95051": "Remover todo o código inacessível", + "Remove_all_unused_labels_95054": "Remover todos os rótulos não utilizados", + "Remove_braces_from_arrow_function_95060": "Remover chaves da função de seta", + "Remove_declaration_for_Colon_0_90004": "Remover declaração para: '{0}'", + "Remove_destructuring_90009": "Remover desestruturação", + "Remove_import_from_0_90005": "Remover importação de '{0}'", + "Remove_unreachable_code_95050": "Remover código inacessível", + "Remove_unused_label_95053": "Remover rótulo não utilizado", + "Remove_variable_statement_90010": "Remover instrução de variável", + "Replace_import_with_0_95015": "Substitua a importação com '{0}'.", + "Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "Relate erro quando nem todos os caminhos de código na função retornarem um valor.", + "Report_errors_for_fallthrough_cases_in_switch_statement_6076": "Relate erros para casos de fallthrough na instrução switch.", + "Report_errors_in_js_files_8019": "Relatar erros em arquivos .js.", + "Report_errors_on_unused_locals_6134": "Relatar erros nos locais não utilizados.", + "Report_errors_on_unused_parameters_6135": "Relatar erros nos parâmetros não utilizados.", + "Required_type_parameters_may_not_follow_optional_type_parameters_2706": "Os parâmetros de tipo necessários podem não seguir os parâmetros de tipo opcionais.", + "Resolution_for_module_0_was_found_in_cache_from_location_1_6147": "A resolução para o módulo '{0}' foi encontrada no cache do local '{1}'.", + "Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols_6195": "Resolva 'keyof' somente para nomes de propriedades com valores de cadeia de caracteres (sem números nem símbolos).", + "Resolving_from_node_modules_folder_6118": "Resolvendo na pasta node_modules...", + "Resolving_module_0_from_1_6086": "======== Resolvendo módulo '{0}' de '{1}'. ========", + "Resolving_module_name_0_relative_to_base_url_1_2_6094": "Resolvendo nome de módulo '{0}' relativo à URL base '{1}' - '{2}'.", + "Resolving_real_path_for_0_result_1_6130": "Resolvendo o caminho real de '{0}', resultado '{1}'.", + "Resolving_type_reference_directive_0_containing_file_1_root_directory_2_6116": "======== Resolvendo diretiva de referência de tipo '{0}', arquivo contido '{1}', diretório raiz '{2}'. ========", + "Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set_6123": "======== Resolvendo diretiva de referência de tipo '{0}', arquivo contido '{1}', diretório raiz não configurado. ========", + "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1_6127": "======== Resolvendo diretiva de referência de tipo '{0}', arquivo contido não configurado, diretório raiz '{1}'. ========", + "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set_6128": "======== Resolvendo diretiva de referência de tipo '{0}', arquivo contido não configurado, diretório raiz não configurado. ========", + "Resolving_using_primary_search_paths_6117": "Resolvendo usando caminhos de pesquisa primários...", + "Resolving_with_primary_search_path_0_6121": "Resolvendo com caminho de pesquisa primário '{0}'.", + "Rest_parameter_0_implicitly_has_an_any_type_7019": "O parâmetro rest '{0}' implicitamente tem um tipo 'any[]'.", + "Rest_types_may_only_be_created_from_object_types_2700": "Os tipos de rest podem ser criado somente de tipos de objeto.", + "Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4046": "O tipo de retorno da assinatura de chamada da interface exportada tem ou está usando o nome '{0}' do módulo particular '{1}'.", + "Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0_4047": "O tipo de retorno da assinatura de chamada da interface exportada tem ou está usando o nome particular '{0}'.", + "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_mod_4044": "O tipo de retorno da assinatura de construtor da interface exportada tem ou está usando o nome '{0}' do módulo particular '{1}'.", + "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0_4045": "O tipo de retorno da assinatura de construtor da interface exportada tem ou está usando o nome particular '{0}'.", + "Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class_2409": "O tipo de retorno da assinatura de construtor deve ser atribuível ao tipo de instância da classe.", + "Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named_4058": "O tipo de retorno da função exportada tem ou está usando o nome '{0}' do módulo externo {1}, mas não pode ser nomeado.", + "Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1_4059": "O tipo de retorno da função exportada tem ou está usando o nome '{0}' do módulo particular '{1}'.", + "Return_type_of_exported_function_has_or_is_using_private_name_0_4060": "O tipo de retorno da função exportada tem ou está usando o nome particular '{0}'.", + "Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4048": "O tipo de retorno da assinatura de índice da interface exportada tem ou está usando o nome '{0}' do módulo particular '{1}'.", + "Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0_4049": "O tipo de retorno da assinatura de índice da interface exportada tem ou está usando o nome particular '{0}'.", + "Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4056": "O tipo de retorno do método da interface exportada tem ou está usando o nome '{0}' do módulo particular '{1}'.", + "Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0_4057": "O tipo de retorno do método da interface exportada tem ou está usando o nome particular '{0}'.", + "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_4041": "O tipo de retorno do getter público '{0}' da classe exportada tem ou está usando o nome '{1}' do módulo externo {2}, mas não pode ser nomeado.", + "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2_4042": "O tipo de retorno do getter público '{0}' da classe exportada tem ou está usando o nome '{1}' do módulo privado '{2}'.", + "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_private_name_1_4043": "O tipo de retorno do getter público '{0}' da classe exportada tem ou está usando o nome privado '{1}'.", + "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_c_4053": "O tipo de retorno do método público da classe exportada tem ou está usando o nome '{0}' do módulo externo {1}, mas não pode ser nomeado.", + "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4054": "O tipo de retorno do método público da classe exportada tem ou está usando o nome '{0}' do módulo particular '{1}'.", + "Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0_4055": "O tipo de retorno do método público da classe exportada tem ou está usando o nome particular '{0}'.", + "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_external_modul_4038": "O tipo de retorno do getter estático público '{0}' da classe exportada tem ou está usando o nome '{1}' do módulo externo '{2}', mas não pode ser nomeado.", + "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_4039": "O tipo de retorno do getter estático público '{0}' da classe exportada tem ou está usando o nome '{1}' do módulo privado '{2}'.", + "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_private_name_1_4040": "O tipo de retorno do getter estático público '{0}' da classe exportada tem ou está usando o nome privado '{1}'.", + "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module__4050": "O tipo de retorno do método estático público da classe exportada tem ou está usando o nome '{0}' do módulo externo {1}, mas não pode ser nomeado.", + "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4051": "O tipo de retorno do método estático público da classe exportada tem ou está usando o nome '{0}' do módulo particular '{1}'.", + "Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0_4052": "O tipo de retorno do método estático público da classe exportada tem ou está usando o nome particular '{0}'.", + "Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program_6184": "Reutilizando resoluções de módulo originados em '{0}', já que as resoluções do programa antigo estão inalteradas.", + "Reusing_resolution_of_module_0_to_file_1_from_old_program_6183": "Reutilizando a resolução do módulo '{0}' para o arquivo '{1}' do programa antigo.", + "Rewrite_all_as_indexed_access_types_95034": "Reescrever tudo como tipos de acesso indexados", + "Rewrite_as_the_indexed_access_type_0_90026": "Reescrever como o tipo de acesso indexado '{0}'", + "Root_directory_cannot_be_determined_skipping_primary_search_paths_6122": "Diretório raiz não pode ser determinado, ignorando caminhos de pesquisa primários.", + "STRATEGY_6039": "ESTRATÉGIA", + "Scoped_package_detected_looking_in_0_6182": "Pacote com escopo detectado, procurando no '{0}'", + "Setters_cannot_return_a_value_2408": "Setters não podem retornar um valor.", + "Show_all_compiler_options_6169": "Mostrar todas as opções do compilador.", + "Show_diagnostic_information_6149": "Mostras as informações de diagnóstico.", + "Show_verbose_diagnostic_information_6150": "Mostras as informações detalhadas de diagnóstico.", + "Show_what_would_be_built_or_deleted_if_specified_with_clean_6367": "Mostrar o que seria compilado (ou excluído, se especificado com '--clean')", + "Signature_0_must_be_a_type_predicate_1224": "A assinatura '{0}' deve ser um predicado de tipo.", + "Skip_type_checking_of_declaration_files_6012": "Ignorar a verificação de tipo dos arquivos de declaração.", + "Skipping_build_of_project_0_because_its_dependency_1_has_errors_6362": "Ignorando o build do projeto '{0}' porque a dependência '{1}' tem erros", + "Skipping_clean_because_not_all_projects_could_be_located_6371": "Ignorando a limpeza porque não foram localizados todos os projetos", + "Source_Map_Options_6175": "Opções do Sourcemap", + "Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature_2382": "A assinatura de sobrecarga especializada não pode ser atribuída a qualquer assinatura não especializada.", + "Specifier_of_dynamic_import_cannot_be_spread_element_1325": "O especificador de importação dinâmica não pode ser o elemento de difusão.", + "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_or_ESNEXT_6015": "Especifique a versão de destino do ECMAScript: 'ES3' (padrão), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018' ou 'ESNEXT'.", + "Specify_JSX_code_generation_Colon_preserve_react_native_or_react_6080": "Especifique a geração de código JSX: 'preserve', 'react-native' ou 'react'.", + "Specify_library_files_to_be_included_in_the_compilation_6079": "Especifique os arquivos de biblioteca a serem incluídos na compilação.", + "Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext_6016": "Especifique a geração de código de módulo: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015' ou 'ESNext'.", + "Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6_6069": "Especifique a estratégia de resolução de módulo: 'node' (Node.js) ou 'classic' (TypeScript pré-1.6).", + "Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h_6146": "Especifique a função de fábrica JSX a ser usada ao direcionar a emissão 'react' do JSX, por ex., 'React.createElement' ou 'h'.", + "Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix_6060": "Especifique o fim da sequência de linha a ser usado ao emitir arquivos: 'CRLF' (dos) ou 'LF' (unix).", + "Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations_6004": "Especifique o local onde o depurador deve localizar arquivos TypeScript em vez de locais de origem.", + "Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations_6003": "Especifique o local onde o depurador deve localizar arquivos de mapa em vez de locais gerados.", + "Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir_6058": "Especifique o diretório raiz de arquivos de entrada. Use para controlar a estrutura do diretório de saída com --outDir.", + "Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher_2472": "O operador de espalhamento só está disponível em expressões 'new' no direcionamento a ECMAScript 5 e superior.", + "Spread_types_may_only_be_created_from_object_types_2698": "Os tipos de espalhamento podem ser criados apenas de tipos de objeto.", + "Starting_compilation_in_watch_mode_6031": "Iniciando compilação no modo de inspeção...", + "Statement_expected_1129": "Instrução esperada.", + "Statements_are_not_allowed_in_ambient_contexts_1036": "Instruções não são permitidas em contextos de ambiente.", + "Static_members_cannot_reference_class_type_parameters_2302": "Membros estáticos não podem fazer referência a parâmetros de tipo de classe.", + "Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1_2699": "Conflitos de propriedade estática '{0}' com propriedade interna 'Function.{0}' da função de construtor '{1}'.", + "Strict_Type_Checking_Options_6173": "Opções Estritas da Verificação de Tipo", + "String_literal_expected_1141": "Literal de cadeia de caracteres esperado.", + "String_literal_with_double_quotes_expected_1327": "Literal de cadeia com aspas duplas é esperado.", + "Stylize_errors_and_messages_using_color_and_context_experimental_6073": "Estilizar erros e mensagens usando cor e contexto (experimental).", + "Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_t_2717": "Declarações de propriedade subsequentes devem ter o mesmo tipo. A propriedade '{0}' deve ser do tipo '{1}', mas aqui tem o tipo '{2}'.", + "Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_t_2403": "Declarações de variável subsequentes devem ter o mesmo tipo. A variável '{0}' deve ser do tipo '{1}', mas aqui tem o tipo '{2}'.", + "Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2_5064": "A substituição '{0}' para o padrão '{1}' tem um tipo incorreto, 'string' esperada, obteve '{2}'.", + "Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character_5062": "A substituição '{0}' no padrão '{1}' pode ter no máximo um caractere '*'.", + "Substitutions_for_pattern_0_should_be_an_array_5063": "As substituições para o padrão '{0}' devem ser uma matriz.", + "Substitutions_for_pattern_0_shouldn_t_be_an_empty_array_5066": "Substituições para o padrão '{0}' não devem ser uma matriz vazia.", + "Successfully_created_a_tsconfig_json_file_6071": "Arquivo tsconfig.json criado com êxito.", + "Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors_2337": "As chamadas super não são permitidas fora dos construtores ou em funções aninhadas dentro dos construtores.", + "Suppress_excess_property_checks_for_object_literals_6072": "Verificações de propriedade de excesso de compactação para literais de objeto.", + "Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures_6055": "Suprimir erros de noImplicitAny para objetos de indexação sem assinaturas de índice.", + "Symbol_reference_does_not_refer_to_the_global_Symbol_constructor_object_2470": "A referência 'symbol' não se refere ao objeto global do construtor Symbol.", + "Syntax_Colon_0_6023": "Sintaxe: {0}", + "The_0_operator_cannot_be_applied_to_type_symbol_2469": "O operador '{0}' não pode ser aplicado ao tipo 'symbol'.", + "The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead_2447": "O operador '{0}' não é permitido para tipos boolianos. Considere usar '{1}'.", + "The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead_2696": "O tipo 'Objeto' pode ser atribuído para muito poucos outros tipos. Você desejava usar o tipo 'qualquer' ao invés disso?", + "The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_stand_2496": "O objeto 'arguments' não pode ser referenciado em uma função de seta em ES3 e ES5. Considere usar uma expressão de função padrão.", + "The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_usi_2522": "O objeto 'arguments' não pode ser referenciado em uma função assíncrona ou o método no ES3 e ES5. Considere usar uma função ou um método padrão.", + "The_body_of_an_if_statement_cannot_be_the_empty_statement_1313": "O corpo de uma instrução 'if' não pode ser uma instrução vazia.", + "The_character_set_of_the_input_files_6163": "O conjunto de caracteres dos arquivos de entrada.", + "The_containing_function_or_module_body_is_too_large_for_control_flow_analysis_2563": "O corpo da função ou do módulo contido é muito grande para a análise de fluxo de controle.", + "The_current_host_does_not_support_the_0_option_5001": "O host atual não dá suporte à opção '{0}'.", + "The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context_2714": "A expressão de uma atribuição de exportação deve ser um identificador ou nome qualificado em um contexto de ambiente.", + "The_files_list_in_config_file_0_is_empty_18002": "A lista de 'arquivos' no arquivo de configuração '{0}' está vazia.", + "The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback_1060": "O primeiro parâmetro do método 'then' de uma promessa deve ser um retorno de chamada.", + "The_global_type_JSX_0_may_not_have_more_than_one_property_2608": "O tipo global 'JSX.{0}' não pode ter mais de uma propriedade.", + "The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_option_1343": "A metapropriedade 'import.meta' é permitida apenas usando 'ESNext' para as opções de compilador 'target' e 'module'.", + "The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary_2527": "O tipo inferido de '{0}' faz referência a um tipo '{1}' inacessível. Uma anotação de tipo é necessária.", + "The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern_2491": "O lado esquerdo de uma instrução 'for...in' não pode ser um padrão de desestruturação.", + "The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation_2404": "O lado esquerdo de uma instrução 'for...in' não pode usar uma anotação de tipo.", + "The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access_2406": "O lado esquerdo de uma instrução 'for...in' deve ser uma variável ou um acesso à propriedade.", + "The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any_2405": "O lado esquerdo de uma instrução de 'for...in' deve ser do tipo 'string' ou 'any'.", + "The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation_2483": "O lado esquerdo de uma instrução 'for...of' não pode usar uma anotação de tipo.", + "The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access_2487": "O lado esquerdo de uma instrução 'for...of' deve ser uma variável ou um acesso à propriedade.", + "The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type_2362": "O lado esquerdo de uma operação aritmética deve ser do tipo 'any', 'number' ou de enumeração.", + "The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access_2364": "O lado esquerdo de uma expressão de atribuição deve ser uma variável ou um acesso à propriedade.", + "The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol_2360": "O lado esquerdo de uma expressão 'in' deve ser do tipo 'any', 'string', 'number' ou 'symbol'.", + "The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_paramete_2358": "O lado esquerdo de uma expressão 'instanceof' deve ser do tipo 'any', um tipo de objeto ou um parâmetro de tipo.", + "The_locale_used_when_displaying_messages_to_the_user_e_g_en_us_6156": "O local usado ao exibir mensagens ao usuário (por exemplo, 'en-us')", + "The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files_6136": "A profundidade máxima de dependência a ser pesquisada em arquivos node_modules e de carregamento de JavaScript.", + "The_operand_of_a_delete_operator_cannot_be_a_read_only_property_2704": "O operando de um operador delete não pode ser uma propriedade somente leitura.", + "The_operand_of_a_delete_operator_must_be_a_property_reference_2703": "O operando de um operador delete deve ser uma referência de propriedade.", + "The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access_2357": "O operando de um operador de incremento ou decremento deve ser uma variável ou um acesso à propriedade.", + "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601": "O tipo de retorno de um construtor de elemento JSX deve retornar um tipo de objeto.", + "The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any_1237": "O tipo de retorno de uma função de decorador de parâmetro deve ser 'void' ou 'any'.", + "The_return_type_of_a_property_decorator_function_must_be_either_void_or_any_1236": "O tipo de retorno de uma função de decorador de propriedade deve ser 'void' ou 'any'.", + "The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_t_1058": "O tipo de retorno de uma função assíncrona deve ser uma promessa válida ou não deve conter um membro \"then\" que pode ser chamado.", + "The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_1064": "O tipo de retorno de uma função assíncrona ou método deve ser o tipo Promessa global.", + "The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_but_2407": "O lado direito de uma instrução 'for...in' deve ser do tipo 'any', um tipo de objeto ou um parâmetro de tipo, mas aqui ele tem o tipo '{0}'.", + "The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type_2363": "O lado direito de uma operação aritmética deve ser do tipo 'any', 'number' ou de enumeração.", + "The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter_2361": "O lado direito de uma expressão 'in' deve ser do tipo 'any', um tipo de objeto ou um parâmetro de tipo.", + "The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_F_2359": "O lado direito de uma expressão 'instanceof' deve ser do tipo 'any' ou de um tipo que pode ser atribuído ao tipo de interface 'Function'.", + "The_specified_path_does_not_exist_Colon_0_5058": "O caminho especificado não existe: '{0}'.", + "The_target_of_an_assignment_must_be_a_variable_or_a_property_access_2541": "O destino de uma atribuição deve ser uma variável ou um acesso à propriedade.", + "The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access_2701": "O destino de uma atribuição rest de objeto deve ser uma variável ou um acesso de propriedade.", + "The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1_2684": "O contexto 'this' de tipo '{0}' não é atribuível para o 'this' do método de tipo '{1}'.", + "The_this_types_of_each_signature_are_incompatible_2685": "Os tipos 'this' de cada assinatura são incompatíveis.", + "The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_typ_2453": "O argumento de tipo para o parâmetro de tipo '{0}' não pode ser inferido com base no uso. Considere especificar os argumentos de tipo explicitamente.", + "The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value__2547": "O tipo retornado pelo método 'next()' de um iterador assíncrono deve ser uma promessa para um tipo com a propriedade 'value'.", + "The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property_2490": "O tipo retornado pelo método 'next()' de um iterador deve ter uma propriedade 'value'.", + "The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer_1189": "A declaração de variável de uma instrução 'for...in' não pode ter um inicializador.", + "The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer_1190": "A declaração de variável de uma instrução 'for...of' não pode ter um inicializador.", + "The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any_2410": "A instrução \"with\" não tem suporte. Todos os símbolos em um bloco \"with\" terão o tipo \"any\".", + "This_constructor_function_may_be_converted_to_a_class_declaration_80002": "Esta função de construtor pode ser convertida em uma declaração de classe.", + "This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found_2354": "Essa sintaxe requer um auxiliar importado, mas o módulo '{0}' não pode ser encontrado.", + "This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1_2343": "Essa sintaxe requer um auxiliar importado chamado '{1}', mas o módulo '{0}' não tem nenhum membro exportado '{1}'.", + "Trailing_comma_not_allowed_1009": "Vírgula à direita não permitida.", + "Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule_6153": "Transcompilar cada arquivo como um módulo separado (do mesmo modo que 'ts.transpileModule').", + "Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_mod_7035": "Tente `npm install @types/{0}`, se existir, ou adicione um novo arquivo de declaração (.d.ts) que contenha `declare module '{0}';`", + "Trying_other_entries_in_rootDirs_6110": "Tentando outras entradas em 'rootDirs'.", + "Trying_substitution_0_candidate_module_location_Colon_1_6093": "Tentando substituição '{0}', local de módulo candidato: '{1}'.", + "Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2_2493": "O tipo de tupla '{0}' com comprimento '{1}' não pode ser atribuído à tupla com comprimento '{2}'.", + "Type_0_cannot_be_converted_to_type_1_2352": "O tipo '{0}' não pode ser convertido para o tipo '{1}'.", + "Type_0_cannot_be_used_as_an_index_type_2538": "O tipo '{0}' não pode ser usado como um tipo de índice.", + "Type_0_cannot_be_used_to_index_type_1_2536": "O tipo '{0}' não pode ser usado para indexar o tipo '{1}'.", + "Type_0_does_not_satisfy_the_constraint_1_2344": "O tipo '{0}' não satisfaz a restrição '{1}'.", + "Type_0_has_no_matching_index_signature_for_type_1_2537": "O tipo '{0}' não tem assinatura de índice correspondente para o tipo '{1}'.", + "Type_0_has_no_properties_in_common_with_type_1_2559": "O tipo '{0}' não tem propriedades em comum com o tipo '{1}'.", + "Type_0_has_no_property_1_2460": "O tipo '{0}' não tem nenhuma propriedade '{1}'.", + "Type_0_has_no_property_1_and_no_string_index_signature_2459": "O tipo '{0}' não tem nenhuma propriedade '{1}' e nenhuma assinatura de índice da cadeia de caracteres.", + "Type_0_is_not_a_constructor_function_type_2507": "O tipo '{0}' não é um tipo de função de construtor.", + "Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Prom_1055": "O tipo '{0}' não é um tipo de retorno de função assíncrona válido no ES5/ES3, pois não se refere ao valor construtor compatível com a Promessa.", + "Type_0_is_not_an_array_type_2461": "O tipo '{0}' não é um tipo de matriz.", + "Type_0_is_not_an_array_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators_2568": "O tipo '{0}' não é um tipo de matriz. Use a opção do compilador '--downlevelIteration' para permitir a iteração dos iteradores.", + "Type_0_is_not_an_array_type_or_a_string_type_2495": "O tipo '{0}' não é um tipo de matriz ou de cadeia de caracteres.", + "Type_0_is_not_an_array_type_or_a_string_type_Use_compiler_option_downlevelIteration_to_allow_iterati_2569": "O tipo '{0}' não é um tipo de matriz nem um tipo de cadeia de caracteres. Use a opção do compilador '--downlevelIteration' para permitir a iteração dos iteradores.", + "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549": "O tipo '{0}' não é um tipo de matriz de um tipo de cadeia ou não tem um método '[Symbol.iterator]()' que retorna um iterador.", + "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548": "O tipo '{0}' não é um tipo de matriz ou não tem um método '[Symbol.iterator]()' que retorna um iterador.", + "Type_0_is_not_assignable_to_type_1_2322": "O tipo '{0}' não pode ser atribuído ao tipo '{1}'.", + "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_2719": "O tipo '{0}' não é atribuível ao tipo '{1}'. Dois tipos diferentes com esse nome existem, mas eles não estão relacionados.", + "Type_0_is_not_comparable_to_type_1_2678": "O tipo '{0}' não pode ser comparável ao tipo '{1}'.", + "Type_0_is_not_generic_2315": "O tipo '{0}' não é genérico.", + "Type_0_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator_2504": "O tipo '{0}' deve ter um método '[Symbol.asyncIterator]()' que retorna um iterador assíncrono.", + "Type_0_must_have_a_Symbol_iterator_method_that_returns_an_iterator_2488": "O tipo '{0}' deve ter um método '[Symbol.iterator]()' que retorna um iterador.", + "Type_0_provides_no_match_for_the_signature_1_2658": "O tipo '{0}' fornece nenhuma correspondência para a assinatura '{1}'.", + "Type_0_recursively_references_itself_as_a_base_type_2310": "O tipo '{0}' referencia recursivamente a si próprio como um tipo base.", + "Type_alias_0_circularly_references_itself_2456": "O alias de tipo '{0}' referencia circulamente a si próprio.", + "Type_alias_name_cannot_be_0_2457": "O nome do alias de tipo não pode ser '{0}'.", + "Type_annotation_cannot_appear_on_a_constructor_declaration_1093": "Uma anotação de tipo não pode aparecer em uma declaração de construtor.", + "Type_argument_candidate_1_is_not_a_valid_type_argument_because_it_is_not_a_supertype_of_candidate_0_2455": "O candidato de argumento de tipo '{1}' não é um argumento de tipo válido porque ele não é um supertipo do candidato '{0}'.", + "Type_argument_expected_1140": "Argumento de tipo esperado.", + "Type_argument_list_cannot_be_empty_1099": "A lista de argumentos de tipo não pode estar vazia.", + "Type_arguments_cannot_be_used_here_1342": "Argumentos de tipo não podem ser usados aqui.", + "Type_declaration_files_to_be_included_in_compilation_6124": "Arquivos de declaração de tipo a serem incluídos em compilação.", + "Type_expected_1110": "Tipo esperado.", + "Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method_1062": "O tipo é referenciado diretamente ou indiretamente em um retorno de chamada de preenchimento do seu próprio método 'then'.", + "Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member_1320": "O tipo de operando \"await\" deve ser uma promessa válida ou não deve conter um membro \"then\" que pode ser chamado.", + "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322": "O tipo de elementos iterados de um operando \"yield*\" deve ser uma promessa válida ou não deve conter um membro \"then\" que pode ser chamado.", + "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321": "O tipo do operando \"yield\" em um gerador assíncrono deve ser uma promessa válida ou não deve conter um membro \"then\" que pode ser chamado.", + "Type_parameter_0_has_a_circular_constraint_2313": "O parâmetro de tipo '{0}' tem uma restrição circular.", + "Type_parameter_0_has_a_circular_default_2716": "O parâmetro de tipo '{0}' tem um padrão circular.", + "Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4008": "O parâmetro de tipo '{0}' da assinatura de chamada da interface exportada tem ou está usando o nome particular '{1}'.", + "Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4006": "O parâmetro de tipo '{0}' da assinatura de construtor da interface exportada tem ou está usando o nome particular '{1}'.", + "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002": "O parâmetro de tipo '{0}' da classe exportada tem ou está usando o nome particular '{1}'.", + "Type_parameter_0_of_exported_function_has_or_is_using_private_name_1_4016": "O parâmetro de tipo '{0}' da função exportada tem ou está usando o nome particular '{1}'.", + "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004": "O parâmetro de tipo '{0}' da interface exportada tem ou está usando o nome particular '{1}'.", + "Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1_4083": "O parâmetro de tipo '{0}' do alias de tipo exportado tem ou está usando o nome privado '{1}'.", + "Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4014": "O parâmetro de tipo '{0}' do método da interface exportada tem ou está usando o nome particular '{1}'.", + "Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4012": "O parâmetro de tipo '{0}' do método público da classe exportada tem ou está usando o nome particular '{1}'.", + "Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4010": "O parâmetro de tipo '{0}' do método estático público da classe exportada tem ou está usando o nome particular '{1}'.", + "Type_parameter_declaration_expected_1139": "Declaração de parâmetro de tipo esperada.", + "Type_parameter_list_cannot_be_empty_1098": "A lista de parâmetros de tipo não pode estar vazia.", + "Type_parameter_name_cannot_be_0_2368": "O nome do parâmetro de tipo não pode ser '{0}'.", + "Type_parameters_cannot_appear_on_a_constructor_declaration_1092": "Os parâmetros de tipo não podem aparecer em uma declaração de construtor.", + "Type_predicate_0_is_not_assignable_to_1_1226": "O predicado de tipo '{0}' não pode ser atribuído a '{1}'.", + "Type_reference_directive_0_was_not_resolved_6120": "======== A diretiva de referência de tipo '{0}' não foi resolvida. ========", + "Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2_6119": "======== A diretiva de referência de tipo '{0}' foi resolvida com sucesso para '{1}', primário: {2}. ========", + "Types_have_separate_declarations_of_a_private_property_0_2442": "Tipos têm declarações separadas de uma propriedade privada '{0}'.", + "Types_of_parameters_0_and_1_are_incompatible_2328": "Os tipos de parâmetros '{0}' e '{1}' são incompatíveis.", + "Types_of_property_0_are_incompatible_2326": "Tipos de propriedade '{0}' são incompatíveis.", + "Unable_to_open_file_0_6050": "Não é possível abrir o arquivo '{0}'.", + "Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression_1238": "Não é possível resolver a assinatura do decorador de classe quando ele é chamado como uma expressão.", + "Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression_1241": "Não é possível resolver a assinatura do decorador de método quando ele é chamado como uma expressão.", + "Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression_1239": "Não é possível resolver a assinatura do decorador de parâmetro quando ele é chamado como uma expressão.", + "Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression_1240": "Não é possível resolver a assinatura do decorador de propriedade quando ele é chamado como uma expressão.", + "Unexpected_end_of_text_1126": "Fim inesperado do texto.", + "Unexpected_token_1012": "Token inesperado.", + "Unexpected_token_A_constructor_method_accessor_or_property_was_expected_1068": "Token inesperado. Um construtor, método, acessador ou propriedade era esperado.", + "Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces_1069": "Token inesperado. Era esperado um nome de parâmetro de tipo sem chaves.", + "Unexpected_token_expected_1179": "Token inesperado. '{' esperado.", + "Unknown_compiler_option_0_5023": "Opção do compilador '{0}' desconhecida.", + "Unknown_option_excludes_Did_you_mean_exclude_6114": "Opção desconhecida 'excludes'. Você quis dizer 'exclude'?", + "Unknown_type_acquisition_option_0_17010": "Opção de aquisição de tipo desconhecido '{0}'.", + "Unreachable_code_detected_7027": "Código inacessível detectado.", + "Unsupported_locale_0_6049": "Localidade '{0}' sem suporte.", + "Unterminated_Unicode_escape_sequence_1199": "Sequência de escape Unicode não finalizada.", + "Unterminated_quoted_string_in_response_file_0_6045": "Cadeia de caracteres entre aspas não finalizada no arquivo de resposta '{0}'.", + "Unterminated_regular_expression_literal_1161": "Literal de expressão regular não finalizado.", + "Unterminated_string_literal_1002": "Literal de cadeia de caracteres não finalizado.", + "Unterminated_template_literal_1160": "Literal de modelo não finalizado.", + "Untyped_function_calls_may_not_accept_type_arguments_2347": "Chamadas de função não tipadas não podem aceitar argumentos de tipo.", + "Unused_label_7028": "Rótulo não utilizado.", + "Updating_output_timestamps_of_project_0_6359": "Atualizando os carimbos de data/hora de saída do projeto '{0}'...", + "Use_synthetic_default_member_95016": "Use o membro sintético 'padrão'.", + "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494": "Há suporte para o uso de uma cadeia de caracteres em uma instrução 'for...of' somente no ECMAScript 5 e superior.", + "VERSION_6036": "VERSÃO", + "Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it_2560": "O valor do tipo '{0}' não tem propriedades em comum com o tipo '{1}'. Você queria chamá-lo?", + "Value_of_type_0_is_not_callable_Did_you_mean_to_include_new_2348": "O valor do tipo '{0}' não pode ser chamado. Você pretendia incluir 'new'?", + "Variable_0_implicitly_has_an_1_type_7005": "A variável '{0}' implicitamente tem um tipo '{1}'.", + "Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined_7034": "A variável '{0}' tem implicitamente o tipo '{1}' em alguns locais onde o tipo não pode ser determinado.", + "Variable_0_is_used_before_being_assigned_2454": "A variável '{0}' é usada antes de ser atribuída.", + "Variable_declaration_expected_1134": "Declaração de variável esperada.", + "Variable_declaration_list_cannot_be_empty_1123": "A lista de declaração de variável não pode estar vazia.", + "Version_0_6029": "Versão {0}", + "Watch_input_files_6005": "Observe os arquivos de entrada.", + "Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen_6191": "Se é necessário manter a saída de console desatualizada no modo de inspeção, em vez de limpar a tela.", + "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001": "Não é possível renomear elementos que são definidos na biblioteca TypeScript padrão.", + "You_cannot_rename_this_element_8000": "Você não pode renomear este elemento.", + "_0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write__1329": "'{0}' aceita muito poucos argumentos para serem usados como um decorador aqui. Você quis dizer para chamá-lo primeiro e gravar '@{0}()'?", + "_0_are_specified_twice_The_attribute_named_0_will_be_overwritten_2710": "'{0}' são especificados duas vezes. O atributo chamado '{0}' será substituído.", + "_0_can_only_be_used_in_a_ts_file_8009": "'{0}' só pode ser usado em um arquivo .ts.", + "_0_expected_1005": "'{0}' esperado.", + "_0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_reference_7023": "Implicitamente, '{0}' tem um retorno tipo 'any' porque ele não tem uma anotação de tipo de retorno e é referenciado direta ou indiretamente em uma das suas expressões de retorno.", + "_0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or__7022": "Implicitamente, '{0}' tem o tipo 'any' porque não tem uma anotação de tipo e é referenciado direta ou indiretamente em seu próprio inicializador.", + "_0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible_2692": "'{0}' é um primitivo, mas '{1}' é um objeto de wrapper. Prefira usar '{0}' quando possível.", + "_0_is_declared_but_its_value_is_never_read_6133": "'{0}' é declarado, mas seu valor nunca é lido.", + "_0_is_declared_but_never_used_6196": "'{0}' está declarado, mas nunca foi usado.", + "_0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2_17012": "'{0}' não é uma metapropriedade para a palavra-chave '{1}'. Você quis dizer '{2}'?", + "_0_is_referenced_directly_or_indirectly_in_its_own_base_expression_2506": "'{0}' é referenciado direta ou indiretamente em sua própria expressão base.", + "_0_is_referenced_directly_or_indirectly_in_its_own_type_annotation_2502": "'{0}' é referenciado direta ou indiretamente em sua própria anotação de tipo.", + "_0_list_cannot_be_empty_1097": "A lista '{0}' não pode estar vazia.", + "_0_modifier_already_seen_1030": "O modificador '{0}' já foi visto.", + "_0_modifier_cannot_appear_on_a_class_element_1031": "O modificador '{0}' não pode aparecer em um elemento de classe.", + "_0_modifier_cannot_appear_on_a_constructor_declaration_1089": "O modificador '{0}' não pode aparecer em uma declaração de construtor.", + "_0_modifier_cannot_appear_on_a_data_property_1043": "O modificador '{0}' não pode aparecer nas propriedades dos dados.", + "_0_modifier_cannot_appear_on_a_module_or_namespace_element_1044": "O modificador '{0}' não pode aparecer em um módulo ou elemento de namespace.", + "_0_modifier_cannot_appear_on_a_parameter_1090": "O modificador '{0}' não pode aparecer em um parâmetro.", + "_0_modifier_cannot_appear_on_a_type_member_1070": "O modificador '{0}' não pode aparecer em um membro de tipo.", + "_0_modifier_cannot_appear_on_an_index_signature_1071": "O modificador '{0}' não pode aparecer em uma assinatura de índice.", + "_0_modifier_cannot_be_used_here_1042": "O modificador '{0}' não pode ser usado aqui.", + "_0_modifier_cannot_be_used_in_an_ambient_context_1040": "O modificador '{0}' não pode ser usado em um contexto de ambiente.", + "_0_modifier_cannot_be_used_with_1_modifier_1243": "O modificador '{0}' não pode ser usado com um modificador '{1}'.", + "_0_modifier_cannot_be_used_with_a_class_declaration_1041": "O modificador '{0}' não pode ser usado com declarações de classes.", + "_0_modifier_must_precede_1_modifier_1029": "O modificador '{0}' deve preceder o modificador '{1}'.", + "_0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here_2702": "'{0}' refere-se apenas a um tipo, mas está sendo usado como um namespace aqui.", + "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_2693": "'{0}' só faz referência a um tipo, mas está sendo usado como valor no momento.", + "_0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead_2686": "'{0}' refere-se a uma UMD global, mas o arquivo atual é um módulo. Considere adicionar uma importação.", + "_0_tag_already_specified_1223": "A marca '{0}' já foi especificada.", + "_0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag_1253": "A marcação '{0}' não pode ser usada independentemente como uma marcação de JSDoc de nível superior.", + "_0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type_7010": "'{0}', que não tem a anotação de tipo de retorno, implicitamente tem um tipo de retorno '{1}'.", + "abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration_1242": "O modificador 'abstract' pode aparecer somente em uma declaração de classe, método ou propriedade.", + "await_expression_is_only_allowed_within_an_async_function_1308": "A expressão 'await' só é permitida em funções assíncronas.", + "await_expressions_cannot_be_used_in_a_parameter_initializer_2524": "As expressões 'await' não podem ser usadas em inicializadores de parâmetros.", + "baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1_6106": "A opção 'baseUrl' é configurada para '{0}', usando este valor para resolver o nome de módulo não relativo '{1}'.", + "can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment_1312": "'=' só pode ser usado em uma propriedade literal de objeto dentro de uma atribuição de desestruturação.", + "case_or_default_expected_1130": "'case' ou 'default' esperado.", + "class_expressions_are_not_currently_supported_9003": "No momento, não há suporte para expressões 'class'.", + "const_declarations_can_only_be_declared_inside_a_block_1156": "Declarações 'const' só podem ser declaradas dentro de um bloco.", + "const_declarations_must_be_initialized_1155": "Declarações 'const' devem ser inicializadas.", + "const_enum_member_initializer_was_evaluated_to_a_non_finite_value_2477": "O inicializador de membro de enumeração 'const' foi avaliado como um valor não finito.", + "const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN_2478": "O inicializador de membro de enumeração 'const' foi avaliado como o valor não permitido 'NaN'.", + "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475": "Enumerações 'const' só podem ser usadas em expressões de acesso de índice ou propriedade, ou então do lado direito de uma consulta de tipo, declaração de importação ou atribuição de exportação.", + "delete_cannot_be_called_on_an_identifier_in_strict_mode_1102": "'delete' não pode ser chamado em um identificador no modo estrito.", + "delete_this_Project_0_is_up_to_date_because_it_was_previously_built_6360": "excluir isto – o Projeto '{0}' está atualizado porque ele já foi compilado", + "enum_declarations_can_only_be_used_in_a_ts_file_8015": "'enum declarations' só podem ser usadas em um arquivo .ts.", + "export_can_only_be_used_in_a_ts_file_8003": "'export=' só pode ser usado em um arquivo .ts.", + "export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always__2668": "O modificador 'export' não pode ser aplicado a módulos de ambiente e acréscimos de módulo, pois eles estão sempre visíveis.", + "extends_clause_already_seen_1172": "A cláusula 'extends' já foi vista.", + "extends_clause_must_precede_implements_clause_1173": "A cláusula 'extends' deve preceder a cláusula 'implements'.", + "extends_clause_of_exported_class_0_has_or_is_using_private_name_1_4020": "A cláusula 'extends' da classe exportada '{0}' tem ou está usando o nome particular '{1}'.", + "extends_clause_of_exported_interface_0_has_or_is_using_private_name_1_4022": "A cláusula 'extends' da interface exportada '{0}' tem ou está usando o nome particular '{1}'.", + "file_6025": "arquivo", + "get_and_set_accessor_must_have_the_same_this_type_2682": "os assessores 'set' e 'get' devem ter o mesmo tipo 'this'.", + "get_and_set_accessor_must_have_the_same_type_2380": "Os acessadores 'get' e 'set' devem ser do mesmo tipo.", + "implements_clause_already_seen_1175": "A cláusula 'implements' já foi vista.", + "implements_clauses_can_only_be_used_in_a_ts_file_8005": "'implements clauses' só podem ser usadas em um arquivo .ts.", + "import_can_only_be_used_in_a_ts_file_8002": "'import ... =' só pode ser usado em um arquivo .ts.", + "infer_declarations_are_only_permitted_in_the_extends_clause_of_a_conditional_type_1338": "As declarações 'infer' só são permitidas na cláusula 'extends' de um tipo condicional.", + "interface_declarations_can_only_be_used_in_a_ts_file_8006": "'interface declarations' só podem ser usadas em um arquivo .ts.", + "let_declarations_can_only_be_declared_inside_a_block_1157": "Declarações 'let' só podem ser declaradas dentro de um bloco.", + "let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations_2480": "O uso de 'let' não é permitido como um nome em declarações 'let' ou 'const'.", + "module_declarations_can_only_be_used_in_a_ts_file_8007": "'module declarations' só podem ser usadas em um arquivo .ts.", + "new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead_1150": "'new T[]' não pode ser usado para criar uma matriz. Use 'new Array()' em vez disso.", + "new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type_7009": "A expressão 'new', cujo destino não tem uma assinatura de constructo, implicitamente tem um tipo 'any'.", + "non_null_assertions_can_only_be_used_in_a_ts_file_8013": "'non-null assertions' só podem ser usados em um arquivo .ts.", + "options_6024": "opções", + "or_expected_1144": "'{' ou ';' esperado.", + "package_json_does_not_have_a_0_field_6100": "'package.json' não tem um campo '{0}'.", + "package_json_has_0_field_1_that_references_2_6101": "'package.json' tem '{0}' campo '{1}' que faz referência a '{2}'.", + "parameter_modifiers_can_only_be_used_in_a_ts_file_8012": "'parameter modifiers' só podem ser usados em um arquivo .ts.", + "paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0_6091": "A opção 'paths' é especificada, procurando por um padrão para corresponder ao nome do módulo '{0}'.", + "readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024": "O modificador 'readonly' pode aparecer somente em uma declaração de propriedade ou assinatura de índice.", + "require_call_may_be_converted_to_an_import_80005": "A chamada 'require' pode ser convertida em uma importação.", + "rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107": "A opção 'rootDirs' está configurada, usando-a para resolver o nome de módulo relativo '{0}'.", + "super_can_only_be_referenced_in_a_derived_class_2335": "'super' só pode ser referenciado em uma classe derivada.", + "super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions_2660": "'super' pode ser referido somente em membros de classes derivadas ou expressões literais de objeto.", + "super_cannot_be_referenced_in_a_computed_property_name_2466": "'super' não pode ser referenciado em um nome de propriedade calculado.", + "super_cannot_be_referenced_in_constructor_arguments_2336": "'super' não pode ser referenciado nos argumentos do construtor.", + "super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_highe_2659": "'super' é permitido somente em membros de expressões literais de objeto quando a opção 'target' é 'ES2015' ou maior.", + "super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class_17011": "'super' deve ser chamado antes de acessar uma propriedade de 'super' no construtor de uma classe derivada.", + "super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class_17009": "'super' deve ser chamado antes de acessar 'this' no construtor de uma classe derivada.", + "super_must_be_followed_by_an_argument_list_or_member_access_1034": "'super' deve ser seguido por um acesso de membro ou lista de argumentos.", + "super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_der_2338": "O acesso à propriedade 'super' só é permitido em um construtor, em funções de membros ou acessadores de membros de uma classe derivada.", + "this_cannot_be_referenced_in_a_computed_property_name_2465": "'this' não pode ser referenciado em um nome de propriedade calculado.", + "this_cannot_be_referenced_in_a_module_or_namespace_body_2331": "'this' não pode ser referenciado em um corpo de módulo ou de namespace.", + "this_cannot_be_referenced_in_a_static_property_initializer_2334": "'this' não pode ser referenciado em um inicializador de propriedade estática.", + "this_cannot_be_referenced_in_constructor_arguments_2333": "'this' não pode ser referenciado em argumentos de construtor.", + "this_cannot_be_referenced_in_current_location_2332": "'this' não pode ser referenciado no local atual.", + "this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_2683": "'this' implicitamente tem o tipo 'any' porque não tem uma anotação de tipo.", + "type_aliases_can_only_be_used_in_a_ts_file_8008": "'type aliases' só podem ser usados em um arquivo .ts.", + "type_arguments_can_only_be_used_in_a_ts_file_8011": "'type arguments' só podem ser usados em um arquivo .ts.", + "type_assertion_expressions_can_only_be_used_in_a_ts_file_8016": "'type assertion expressions' só podem ser usadas em um arquivo .ts.", + "type_parameter_declarations_can_only_be_used_in_a_ts_file_8004": "'type parameter declarations' só podem ser usadas em um arquivo .ts.", + "types_can_only_be_used_in_a_ts_file_8010": "'types' só podem ser usados em um arquivo .ts.", + "unique_symbol_types_are_not_allowed_here_1335": "Tipos de 'unique symbol' não são permitidos aqui.", + "unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement_1334": "Tipos de 'unique symbol' são permitidos apenas em variáveis em uma declaração de variável.", + "unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name_1333": "Tipos de 'unique symbol' não podem ser usados em uma declaração de variável com um nome associado.", + "with_statements_are_not_allowed_in_an_async_function_block_1300": "As declarações 'with' não são permitidas em blocos de funções assíncronas.", + "with_statements_are_not_allowed_in_strict_mode_1101": "Instruções 'with' não são permitidas no modo estrito.", + "yield_expressions_cannot_be_used_in_a_parameter_initializer_2523": "As expressões 'yield' não podem ser usadas em inicializadores de parâmetros." +} \ No newline at end of file diff --git a/node_modules/typescript/lib/ru/diagnosticMessages.generated.json b/node_modules/typescript/lib/ru/diagnosticMessages.generated.json new file mode 100644 index 0000000..90d11ce --- /dev/null +++ b/node_modules/typescript/lib/ru/diagnosticMessages.generated.json @@ -0,0 +1,1101 @@ +{ + "A_0_modifier_cannot_be_used_with_an_import_declaration_1079": "Модификатор \"{0}\" не может быть использован с объявлением импорта.", + "A_0_modifier_cannot_be_used_with_an_interface_declaration_1045": "Модификатор \"{0}\" не может быть использован с объявлением интерфейса.", + "A_0_parameter_must_be_the_first_parameter_2680": "В качестве первого параметра необходимо указать \"{0}\".", + "A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature_2463": "Параметр шаблона привязки не может быть необязательным в сигнатуре реализации.", + "A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement_1105": "Оператор break можно использовать только во включающей итерации или операторе switch.", + "A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement_1116": "Оператор break может переходить только к метке внешнего оператора.", + "A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments_2500": "Класс может реализовать только идентификатор или полное имя с дополнительными аргументами типа.", + "A_class_declaration_without_the_default_modifier_must_have_a_name_1211": "Объявление класса без модификатора \"default\" должно иметь имя.", + "A_class_may_only_extend_another_class_2311": "Класс может расширять только другой класс.", + "A_class_may_only_implement_another_class_or_interface_2422": "Класс может реализовывать только другой класс или интерфейс.", + "A_class_member_cannot_have_the_0_keyword_1248": "Элемент класса не может иметь ключевое слово \"{0}\".", + "A_comma_expression_is_not_allowed_in_a_computed_property_name_1171": "Выражение с запятой запрещено в имени вычисляемого свойства.", + "A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type_2467": "Имя вычисляемого свойства не может ссылаться на параметр типа из содержащего его типа.", + "A_computed_property_name_in_a_class_property_declaration_must_refer_to_an_expression_whose_type_is_a_1166": "Имя вычисляемого свойства в объявлении свойств класса должно ссылаться на выражение, тип которого — литерал или \"unique symbol\".", + "A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_ty_1168": "Имя вычисляемого свойства в перегрузке метода должно ссылаться на выражение, тип которого — литерал или \"unique symbol\".", + "A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type__1170": "Имя вычисляемого свойства в литерале должно ссылаться на выражение, тип которого — литерал или \"unique symbol\".", + "A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_t_1165": "Имя вычисляемого свойства в окружающем контексте должно ссылаться на выражение, тип которого — литерал или \"unique symbol\".", + "A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_1169": "Имя вычисляемого свойства в интерфейсе должно ссылаться на выражение, тип которого — литерал или \"unique symbol\".", + "A_computed_property_name_must_be_of_type_string_number_symbol_or_any_2464": "Имя вычисляемого свойства должно иметь тип string, number, symbol или any.", + "A_computed_property_name_of_the_form_0_must_be_of_type_symbol_2471": "Имя вычисляемого свойства в форме \"{0}\" должно иметь тип symbol.", + "A_const_enum_member_can_only_be_accessed_using_a_string_literal_2476": "Доступ к элементу перечисления констант может осуществляться только с использованием строкового литерала.", + "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_1254": "Инициализатор const в окружающем контексте должен быть строковым или цифровым литералом.", + "A_constructor_cannot_contain_a_super_call_when_its_class_extends_null_17005": "Конструктор не может содержать вызов \"super\", если его класс расширяет \"null\".", + "A_constructor_cannot_have_a_this_parameter_2681": "Конструктор не может иметь параметр this.", + "A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement_1104": "Оператор continue можно использовать только в операторе включающей итерации.", + "A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement_1115": "Оператор continue может переходить только к метке оператора включающей итерации.", + "A_declare_modifier_cannot_be_used_in_an_already_ambient_context_1038": "Модификатор declare нельзя использовать в уже окружающем контексте.", + "A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file_1046": "Модификатор declare необходим для объявления верхнего уровня в D.TS-файле.", + "A_decorator_can_only_decorate_a_method_implementation_not_an_overload_1249": "Декоратор может только декорировать реализацию метода, а не перегрузку.", + "A_default_clause_cannot_appear_more_than_once_in_a_switch_statement_1113": "Предложение default не может повторяться в операторе switch.", + "A_default_export_can_only_be_used_in_an_ECMAScript_style_module_1319": "Экспорт по умолчанию можно использовать только в модуле в стиле ECMAScript.", + "A_definite_assignment_assertion_is_not_permitted_in_this_context_1255": "Утверждение определенного присваивания \"!\" запрещено в этом контексте.", + "A_destructuring_declaration_must_have_an_initializer_1182": "Объявление деструктурирования должно включать инициализатор.", + "A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declarat_2712": "Для вызова динамического импорта в ES5/ES3 требуется конструктор \"Promise\". Объявите конструктор \"Promise\" или включите \"ES2015\" в параметр \"--lib\".", + "A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES20_2711": "Вызов динамического импорта возвращает конструктор \"Promise\". Объявите конструктор \"Promise\" или включите \"ES2015\" в параметр \"--lib\".", + "A_file_cannot_have_a_reference_to_itself_1006": "Файл не может содержать ссылку на самого себя.", + "A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator_1103": "Оператор for-await-of разрешено использовать только в асинхронной функции или в асинхронном генераторе.", + "A_function_returning_never_cannot_have_a_reachable_end_point_2534": "Функция, возвращающая \"never\", не может иметь доступную конечную точку.", + "A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void_2679": "Функция, которая вызывается с ключевым словом new, не может иметь тип this со значением void.", + "A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value_2355": "Функция, объявленный тип которой не является void или any, должна возвращать значение.", + "A_generator_cannot_have_a_void_type_annotation_2505": "Генератор не может иметь аннотацию типа void.", + "A_get_accessor_cannot_have_parameters_1054": "Метод доступа get не может иметь параметров.", + "A_get_accessor_must_return_a_value_2378": "Метод доступа get должен возвращать значение.", + "A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_memb_2651": "Инициализатор элемента в объявлении перечисления не может ссылаться на элементы, объявленные после него, включая элементы, определенные в других перечислениях.", + "A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any_2545": "Класс примеси должен иметь конструктор с одиночным параметром REST типа any[].", + "A_module_cannot_have_multiple_default_exports_2528": "Модуль не может иметь несколько импортов по умолчанию.", + "A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merg_2433": "Объявление пространства имен и класс или функция, с которыми оно объединено, не могут находится в разных файлах.", + "A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged_2434": "Объявление пространства имен не может располагаться раньше класса или функции, с которыми оно объединено.", + "A_namespace_declaration_is_only_allowed_in_a_namespace_or_module_1235": "Объявление пространства имен разрешено использовать только в пространстве имен или модуле.", + "A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_7038": "Импорт стиля пространства имен не может быть вызван или создан и приведет к сбою во время выполнения.", + "A_non_dry_build_would_build_project_0_6357": "При сборке без флага -dry будет собран проект \"{0}\"", + "A_non_dry_build_would_delete_the_following_files_Colon_0_6356": "При сборке без флага -dry будут удалены следующие файлы: {0}", + "A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation_2371": "Инициализатор параметра разрешено использовать только в реализации функции или конструктора.", + "A_parameter_property_cannot_be_declared_using_a_rest_parameter_1317": "Свойство параметра невозможно объявить с помощью параметра REST.", + "A_parameter_property_is_only_allowed_in_a_constructor_implementation_2369": "Свойство параметра допускается только в реализации конструктора.", + "A_parameter_property_may_not_be_declared_using_a_binding_pattern_1187": "Свойство параметра невозможно объявить с помощью шаблона привязки.", + "A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not_18001": "Путь в параметре extends должен быть относительным или указанным от корня, но \"{0}\" не является ни тем ни другим.", + "A_promise_must_have_a_then_method_1059": "Класс promise должен содержать метод then.", + "A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly_1331": "Свойство класса, тип которого — \"unique symbol\", должно быть задано как \"static\" и \"readonly\".", + "A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly_1330": "Свойство интерфейса или литерала, тип которого — \"unique symbol\", должно быть задано как \"readonly\".", + "A_required_parameter_cannot_follow_an_optional_parameter_1016": "Обязательный параметр не должен следовать за необязательным.", + "A_rest_element_cannot_contain_a_binding_pattern_2501": "Элемент rest не может содержать шаблон привязки.", + "A_rest_element_cannot_have_a_property_name_2566": "Элемент rest не может иметь имя свойства.", + "A_rest_element_cannot_have_an_initializer_1186": "Элемент rest не может содержать инициализатор.", + "A_rest_element_must_be_last_in_a_destructuring_pattern_2462": "Элемент REST должен быть последним в шаблоне деструктуризации.", + "A_rest_parameter_cannot_be_optional_1047": "Параметр rest не может быть необязательным.", + "A_rest_parameter_cannot_have_an_initializer_1048": "Параметр rest не может иметь инициализатор.", + "A_rest_parameter_must_be_last_in_a_parameter_list_1014": "Параметр rest должен стоять на последнем месте в списке параметров.", + "A_rest_parameter_must_be_of_an_array_type_2370": "Параметр rest должен иметь тип массива.", + "A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma_1013": "После параметра rest или шаблона привязки не может стоять запятая.", + "A_return_statement_can_only_be_used_within_a_function_body_1108": "Оператор return можно использовать только в теле функции.", + "A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl_6167": "Серия записей, которая повторно сопоставляет импорты с расположениями поиска, заданными относительно baseUrl.", + "A_set_accessor_cannot_have_a_return_type_annotation_1095": "Метод доступа set не может иметь заметку с типом возвращаемого значения.", + "A_set_accessor_cannot_have_an_optional_parameter_1051": "Метод доступа set не может иметь необязательный параметр.", + "A_set_accessor_cannot_have_rest_parameter_1053": "Метод доступа set не может иметь параметр rest.", + "A_set_accessor_must_have_exactly_one_parameter_1049": "У метода доступа set должен быть ровно один параметр.", + "A_set_accessor_parameter_cannot_have_an_initializer_1052": "Параметр метода доступа set не может иметь инициализатор.", + "A_signature_with_an_implementation_cannot_use_a_string_literal_type_2381": "Сигнатура с реализацией не может использовать тип строкового литерала.", + "A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_proper_2376": "Вызов super должен быть первой инструкцией в конструкторе, если класс содержит инициализированные свойства или свойства параметров.", + "A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard_2518": "Условие типа this несовместимо с условием типа на основе параметров.", + "A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface_2526": "Тип this доступен только в нестатическом элементе класса или интерфейса.", + "A_tsconfig_json_file_is_already_defined_at_Colon_0_5054": "Файл tsconfig.json уже определен в \"{0}\".", + "A_tuple_type_element_list_cannot_be_empty_1122": "Список элементов типа кортежа не может быть пустым.", + "A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Con_17007": "Выражение утверждения типа не допускается в левой части выражения, возводимого в степень. Попробуйте заключить выражение в скобки.", + "A_type_literal_property_cannot_have_an_initializer_1247": "Свойство литерала типа не может иметь инициализатор.", + "A_type_predicate_cannot_reference_a_rest_parameter_1229": "Предикат типов не может ссылаться на параметр rest.", + "A_type_predicate_cannot_reference_element_0_in_a_binding_pattern_1230": "Предикат типов не может ссылаться на элемент \"{0}\" в шаблоне привязки.", + "A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods_1228": "Предикат типов разрешено использовать только в позиции типа возвращаемого значения для функций и методов.", + "A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type_2677": "Тип предиката типа должен быть доступным для назначения этому типу параметра.", + "A_variable_whose_type_is_a_unique_symbol_type_must_be_const_1332": "Переменная, тип которой — \"unique symbol\", должна быть задана как \"const\".", + "A_yield_expression_is_only_allowed_in_a_generator_body_1163": "Выражение yield разрешено использовать только в теле генератора.", + "Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression_2513": "Невозможно получить доступ к абстрактному методу \"{0}\" класса \"{1}\" с помощью выражения super.", + "Abstract_methods_can_only_appear_within_an_abstract_class_1244": "Абстрактные методы могут использоваться только в абстрактных классах.", + "Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor_2715": "Абстрактное свойство \"{0}\" в классе \"{1}\" недоступно в конструкторе.", + "Accessibility_modifier_already_seen_1028": "Модификатор специальных возможностей уже встречался.", + "Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher_1056": "Методы доступа доступны только при разработке для ECMAScript 5 и более поздних версий.", + "Accessors_must_both_be_abstract_or_non_abstract_2676": "Методы доступа должны быть абстрактными или неабстрактными.", + "Add_0_to_existing_import_declaration_from_1_90015": "Добавьте \"{0}\" в существующее объявление импорта из \"{1}\"", + "Add_0_to_unresolved_variable_90008": "Добавить \"{0}.\" к неразрешенной переменной", + "Add_all_missing_async_modifiers_95041": "Добавить все отсутствующие модификаторы \"async\"", + "Add_all_missing_members_95022": "Добавить все отсутствующие элементы", + "Add_all_missing_super_calls_95039": "Добавить все отсутствующие вызовы super", + "Add_async_modifier_to_containing_function_90029": "Добавьте модификатор async в содержащую функцию", + "Add_braces_to_arrow_function_95059": "Добавить скобки в стрелочную функцию", + "Add_definite_assignment_assertion_to_property_0_95020": "Добавить утверждение определенного присваивания к свойству \"{0}\"", + "Add_definite_assignment_assertions_to_all_uninitialized_properties_95028": "Добавить утверждения определенного присваивания ко всем неинициализированным свойствам", + "Add_index_signature_for_property_0_90017": "Добавьте сигнатуру индекса для свойства \"{0}\"", + "Add_initializer_to_property_0_95019": "Добавить инициализатор к свойству \"{0}\"", + "Add_initializers_to_all_uninitialized_properties_95027": "Добавить инициализаторы ко всем неинициализированным свойствам", + "Add_missing_super_call_90001": "Добавьте отсутствующий вызов \"super()\"", + "Add_missing_typeof_95052": "Добавить отсутствующий \"typeof\"", + "Add_or_remove_braces_in_an_arrow_function_95058": "Добавить скобки в стрелочную функцию или удалить скобки из нее", + "Add_qualifier_to_all_unresolved_variables_matching_a_member_name_95037": "Добавить квалификатор ко всем неразрешенным переменным, соответствующим имени члена", + "Add_to_all_uncalled_decorators_95044": "Добавить \"()\" ко всем невызванным декораторам", + "Add_ts_ignore_to_all_error_messages_95042": "Добавить \"@ts-ignore\" ко всем сообщениям об ошибках", + "Add_undefined_type_to_all_uninitialized_properties_95029": "Добавить неопределенный тип ко всем неинициализированным свойствам", + "Add_undefined_type_to_property_0_95018": "Добавить тип \"undefined\" к свойству \"{0}\"", + "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068": "Добавление файла tsconfig.json поможет организовать проекты, содержащие файлы TypeScript и JavaScript. Дополнительные сведения: https://aka.ms/tsconfig.", + "Additional_Checks_6176": "Дополнительные проверки", + "Advanced_Options_6178": "Дополнительные параметры", + "All_declarations_of_0_must_have_identical_modifiers_2687": "Все объявления \"{0}\" должны иметь одинаковые модификаторы.", + "All_declarations_of_0_must_have_identical_type_parameters_2428": "Все объявления \"{0}\" должны иметь одинаковые параметры типа.", + "All_declarations_of_an_abstract_method_must_be_consecutive_2516": "Все объявления абстрактных методов должны быть последовательными.", + "All_destructured_elements_are_unused_6198": "Все деструктурированные элементы не используются.", + "All_imports_in_import_declaration_are_unused_6192": "Ни один из импортов в объявлении импорта не используется.", + "All_variables_are_unused_6199": "Ни одна переменная не используется.", + "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011": "Разрешить импорт по умолчанию из модулей без экспорта по умолчанию. Это не повлияет на выведение кода — только на проверку типов.", + "Allow_javascript_files_to_be_compiled_6102": "Разрешить компиляцию файлов javascript.", + "Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided_1209": "Перечисление внешних констант не разрешено, если задан флаг \"--isolatedModules\".", + "Ambient_module_declaration_cannot_specify_relative_module_name_2436": "Объявление окружающего модуля не может содержать относительное имя модуля.", + "Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces_2435": "Внешний модуль не может быть вложен в другие модули или пространства имен.", + "An_AMD_module_cannot_have_multiple_name_assignments_2458": "Модуль AMD не может иметь несколько присваиваний имен.", + "An_abstract_accessor_cannot_have_an_implementation_1318": "У абстрактного метода доступа не может быть реализации.", + "An_accessor_cannot_be_declared_in_an_ambient_context_1086": "Метод доступа нельзя объявить в окружающем контексте.", + "An_accessor_cannot_have_type_parameters_1094": "Метод доступа не может иметь параметры типа.", + "An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file_1234": "Объявление окружающего модуля разрешено использовать только в рамках верхнего уровня файла.", + "An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type_2356": "Арифметический операнд должен иметь тип any, number или тип перечисления.", + "An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_de_2705": "Асинхронной функции или методу ES5/ES3 требуется конструктор Promise. Убедитесь, что имеется объявление для конструктора Promise или включите ES2015 в параметр \"--lib\".", + "An_async_function_or_method_must_have_a_valid_awaitable_return_type_1057": "Асинхронная функция или метод должны иметь допустимый тип возвращаемого значения, поддерживающий ожидание.", + "An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_in_2697": "Асинхронная функция или метод должны вернуть Promise. Убедитесь, что у вас есть объявление для Promise или включите ES2015 в параметр --lib.", + "An_async_iterator_must_have_a_next_method_2519": "В асинхронном итераторе должен быть метод next().", + "An_element_access_expression_should_take_an_argument_1011": "Выражение доступа к элементу должно принимать аргумент.", + "An_enum_member_cannot_have_a_numeric_name_2452": "Имя элемента перечисления не может быть числовым.", + "An_export_assignment_can_only_be_used_in_a_module_1231": "Присваивание экспорта может быть использовано только в модуле.", + "An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements_2309": "Присваивание экспорта нельзя использовать в модуле с другими экспортированными элементами.", + "An_export_assignment_cannot_be_used_in_a_namespace_1063": "Присваивание экспорта нельзя использовать в пространстве имен.", + "An_export_assignment_cannot_have_modifiers_1120": "Присваивание экспорта не может иметь модификаторы.", + "An_export_declaration_can_only_be_used_in_a_module_1233": "Объявление экспорта может быть использовано только в модуле.", + "An_export_declaration_cannot_have_modifiers_1193": "Объявление экспорта не может иметь модификаторы.", + "An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive_1198": "Расширенное escape-значение в Юникоде должно быть в пределах от 0x0 до 0x10FFFF включительно.", + "An_implementation_cannot_be_declared_in_ambient_contexts_1183": "Реализацию невозможно объявить в окружающих контекстах.", + "An_import_declaration_can_only_be_used_in_a_namespace_or_module_1232": "Объявление импорта может быть использовано только в пространстве имен или модуле.", + "An_import_declaration_cannot_have_modifiers_1191": "Объявление импорта не может иметь модификаторы.", + "An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead_2691": "Путь импорта не может заканчиваться расширением \"{0}\". Попробуйте импортировать \"{1}\".", + "An_index_expression_argument_must_be_of_type_string_number_symbol_or_any_2342": "Аргумент выражения индекса должен иметь тип string, number, symbol или any.", + "An_index_signature_cannot_have_a_rest_parameter_1017": "Сигнатура индекса не может иметь параметр rest.", + "An_index_signature_must_have_a_type_annotation_1021": "У сигнатуры индекса должна быть аннотация типа.", + "An_index_signature_must_have_exactly_one_parameter_1096": "У сигнатуры индекса должен быть ровно один параметр.", + "An_index_signature_parameter_cannot_have_a_question_mark_1019": "Параметр сигнатуры индекса не может содержать вопросительный знак.", + "An_index_signature_parameter_cannot_have_an_accessibility_modifier_1018": "Параметра сигнатуры индекса не может содержать модификатор специальных возможностей.", + "An_index_signature_parameter_cannot_have_an_initializer_1020": "Параметр сигнатуры индекса не может содержать инициализатор.", + "An_index_signature_parameter_must_have_a_type_annotation_1022": "У параметра сигнатуры индекса должна быть аннотация типа.", + "An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead_1336": "Тип параметра сигнатуры индекса не может быть псевдонимом типа. Вместо этого рекомендуется написать \"[{0}: {1}]: {2}\".", + "An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead_1337": "Тип параметра сигнатуры индекса не может быть типом объединения. Рекомендуется использовать тип сопоставляемого объекта.", + "An_index_signature_parameter_type_must_be_string_or_number_1023": "Параметр сигнатуры индекса должен иметь тип string или number.", + "An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments_2499": "Интерфейс может расширить только идентификатор или полное имя с дополнительными аргументами типа.", + "An_interface_may_only_extend_a_class_or_another_interface_2312": "Интерфейс может расширять только класс или другой интерфейс.", + "An_interface_property_cannot_have_an_initializer_1246": "Свойство интерфейса не может иметь инициализатор.", + "An_iterator_must_have_a_next_method_2489": "Итератор должен иметь метод \"next()\".", + "An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name_1118": "Объектный литерал не может иметь несколько методов доступа get/set с одинаковым именем.", + "An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode_1117": "Объектный литерал не может иметь несколько свойств с одинаковым именем в строгом режиме.", + "An_object_literal_cannot_have_property_and_accessor_with_the_same_name_1119": "Объектный литерал не может иметь свойство и метод доступа с одинаковым именем.", + "An_object_member_cannot_be_declared_optional_1162": "Элемент объекта не может быть объявлен необязательным.", + "An_overload_signature_cannot_be_declared_as_a_generator_1222": "Сигнатура перегрузки не может быть объявлена в качестве генератора.", + "An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_ex_17006": "Унарное выражение с оператором \"{0}\" не допускается в левой части выражения, возводимого в степень. Попробуйте заключить выражение в скобки.", + "Annotate_everything_with_types_from_JSDoc_95043": "Добавить заметки ко всем элементам с типами JSDoc", + "Annotate_with_type_from_JSDoc_95009": "Заметка с типом из JSDoc", + "Annotate_with_types_from_JSDoc_95010": "Заметки с типами из JSDoc", + "Argument_expression_expected_1135": "Ожидалось выражение аргумента.", + "Argument_for_0_option_must_be_Colon_1_6046": "Аргумент для параметра \"{0}\" должен быть {1}.", + "Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_2345": "Аргумент типа \"{0}\" нельзя назначить параметру типа \"{1}\".", + "Array_element_destructuring_pattern_expected_1181": "Ожидался шаблон деструктурирования элемента массива.", + "Asterisk_Slash_expected_1010": "Ожидалось \"*/\".", + "Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_2669": "Улучшения для глобальной области могут быть вложены во внешние модули или неоднозначные объявления модулей только напрямую.", + "Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambien_2670": "Улучшения для глобальной области не должны иметь модификатор declare, если они отображаются в окружающем контексте.", + "Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using__6140": "Автообнаружение для вводимых данных включено в проекте \"{0}\". Идет запуск дополнительного этапа разрешения для модуля \"{1}\" с использованием расположения кэша \"{2}\".", + "Base_class_expressions_cannot_reference_class_type_parameters_2562": "Выражения базового класса не могут ссылаться на параметры типа класса.", + "Base_constructor_return_type_0_is_not_a_class_or_interface_type_2509": "Тип возвращаемого значения конструктора базового класса \"{0}\" не является классом или типом интерфейса.", + "Base_constructors_must_all_have_the_same_return_type_2510": "Конструкторы базового класса должны иметь одинаковые типы возвращаемых значений.", + "Base_directory_to_resolve_non_absolute_module_names_6083": "Базовый каталог для разрешения неабсолютных имен модуля.", + "Basic_Options_6172": "Базовые параметры", + "Binary_digit_expected_1177": "Ожидался бит.", + "Binding_element_0_implicitly_has_an_1_type_7031": "Элемент привязки \"{0}\" имеет неявный тип \"{1}\".", + "Block_scoped_variable_0_used_before_its_declaration_2448": "Переменная \"{0}\" с областью видимости, ограниченной блоком, использована перед своим объявлением.", + "Build_all_projects_including_those_that_appear_to_be_up_to_date_6368": "Собрать все проекты, включая не требующие обновления", + "Build_one_or_more_projects_and_their_dependencies_if_out_of_date_6364": "Собрать один проект или несколько и их зависимости, если они не обновлены", + "Building_project_0_6358": "Сборка проекта \"{0}\"...", + "Call_decorator_expression_90028": "Вызовите выражение декоратора", + "Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7020": "Сигнатура вызова, у которой нет аннотации типа возвращаемого значения, неявно имеет тип возвращаемого значения any.", + "Call_target_does_not_contain_any_signatures_2346": "Объект вызова не содержит сигнатуры.", + "Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_p_2713": "Не удается получить доступ к {0}.{1}, так как {0} является типом, но не является пространством имен. Вы хотели получить тип свойства {1} в {0} с использованием {0}[\"{1}\"]?", + "Cannot_assign_a_0_constructor_type_to_a_1_constructor_type_2672": "Не удается назначить тип конструктора \"{0}\" для типа конструктора \"{1}\".", + "Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type_2517": "Не удается назначить тип конструктора абстрактного класса для типа конструктора класса, не являющегося абстрактным.", + "Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property_2540": "Не удается задать значение для \"{0}\", так как это константа или свойство, доступное только для чтения.", + "Cannot_assign_to_0_because_it_is_not_a_variable_2539": "Не удается задать значение для \"{0}\", так как это не переменная.", + "Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity_2671": "Не удается улучшить модуль \"{0}\", так как он разрешается в немодульную сущность.", + "Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity_2649": "Невозможно добавить экспорт значений в модуль \"{0}\", так как он разрешается в немодульную сущность.", + "Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system_6131": "Невозможно скомпилировать модули с использованием параметра \"{0}\", если флаг \"--module\" не имеет значения \"amd\" или \"system\".", + "Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided_1208": "Невозможно скомпилировать пространства имен, если задан флаг \"--isolatedModules\".", + "Cannot_create_an_instance_of_an_abstract_class_2511": "Невозможно создать экземпляр абстрактного класса.", + "Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module_2661": "Не удается экспортировать \"{0}\". Только локальные объявления можно экспортировать из модуля.", + "Cannot_extend_a_class_0_Class_constructor_is_marked_as_private_2675": "Не удается расширить класс \"{0}\". Конструктор класса помечен как частный.", + "Cannot_extend_an_interface_0_Did_you_mean_implements_2689": "Не удается расширить интерфейс \"{0}\". Вы имели в виду \"реализует\"?", + "Cannot_find_a_tsconfig_json_file_at_the_specified_directory_Colon_0_5057": "Не удается найти файл tsconfig.json в указанном каталоге: \"{0}\".", + "Cannot_find_global_type_0_2318": "Не удается найти глобальный тип \"{0}\".", + "Cannot_find_global_value_0_2468": "Не удается найти глобальное значение \"{0}\".", + "Cannot_find_lib_definition_for_0_2726": "Не удается найти определение lib для \"{0}\".", + "Cannot_find_lib_definition_for_0_Did_you_mean_1_2727": "Не удается найти определение lib для \"{0}\". Вы имели в виду \"{1}\"?", + "Cannot_find_module_0_2307": "Не удается найти модуль \"{0}\".", + "Cannot_find_name_0_2304": "Не удается найти имя \"{0}\".", + "Cannot_find_name_0_Did_you_mean_1_2552": "Не удается найти имя \"{0}\". Вы имели в виду \"{1}\"?", + "Cannot_find_name_0_Did_you_mean_the_instance_member_this_0_2663": "Не удается найти имя \"{0}\". Возможно, вы имели в виду элемент экземпляра \"this.{0}\"?", + "Cannot_find_name_0_Did_you_mean_the_static_member_1_0_2662": "Не удается найти имя \"{0}\". Возможно, вы имели в виду статический элемент \"{1}.{0}\"?", + "Cannot_find_namespace_0_2503": "Не удается найти пространство имен \"{0}\".", + "Cannot_find_parameter_0_1225": "Не удается найти параметр \"{0}\".", + "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009": "Не удается найти общий путь к подкаталогу для входных файлов.", + "Cannot_find_type_definition_file_for_0_2688": "Не удается найти файл определения типа для \"{0}\".", + "Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1_6137": "Невозможно импортировать файлы объявления типа. Рекомендуется импортировать \"{0}\" вместо \"{1}\".", + "Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1_2481": "Невозможно инициализировать переменную \"{0}\" с внешней областью видимости в той же области видимости, что и объявление \"{1}\" с областью видимости \"Блок\".", + "Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatur_2349": "Не удается вызвать выражение, в типе которого отсутствует сигнатура вызова. Тип \"{0}\" не содержит совместимые сигнатуры вызова.", + "Cannot_invoke_an_object_which_is_possibly_null_2721": "Не удается вызвать объект, который может иметь значение \"NULL\".", + "Cannot_invoke_an_object_which_is_possibly_null_or_undefined_2723": "Не удается вызвать объект, который может иметь значение \"NULL\" или \"undefined\".", + "Cannot_invoke_an_object_which_is_possibly_undefined_2722": "Не удается вызвать объект, который может иметь значение \"undefined\".", + "Cannot_prepend_project_0_because_it_does_not_have_outFile_set_6308": "Невозможно добавить проект \"{0}\" в начало, так как для него не задан outFile", + "Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205": "Невозможно повторно экспортировать тип, если установлен флажок \"--isolatedModules\".", + "Cannot_read_file_0_Colon_1_5012": "Не удается считать файл \"{0}\": {1}.", + "Cannot_redeclare_block_scoped_variable_0_2451": "Невозможно повторно объявить переменную \"{0}\" с областью видимости \"Блок\".", + "Cannot_redeclare_exported_variable_0_2323": "Не удается повторно объявить экспортированную переменную \"{0}\".", + "Cannot_redeclare_identifier_0_in_catch_clause_2492": "Невозможно повторно объявить идентификатор \"{0}\" в операторе catch.", + "Cannot_use_JSX_unless_the_jsx_flag_is_provided_17004": "Невозможно использовать JSX, если не задан флаг \"--jsx\".", + "Cannot_use_imports_exports_or_module_augmentations_when_module_is_none_1148": "Невозможно использовать директивы import, export или приращения модуля, если флаг \"--module\" имеет значение \"none\".", + "Cannot_use_namespace_0_as_a_type_2709": "Невозможно использовать пространство имен \"{0}\" как тип.", + "Cannot_use_namespace_0_as_a_value_2708": "Невозможно использовать пространство имен \"{0}\" как значение.", + "Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature_2351": "Невозможно использовать new с выражением, у типа которого нет сигнатуры вызова или конструктора.", + "Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files_5056": "Не удается записать файл \"{0}\", так как он будет перезаписан несколькими входными файлами.", + "Cannot_write_file_0_because_it_would_overwrite_input_file_5055": "Не удается записать файл \"{0}\", так как это привело бы к перезаписи входного файла.", + "Catch_clause_variable_cannot_have_a_type_annotation_1196": "Переменная оператора catch не может иметь аннотацию типа.", + "Catch_clause_variable_cannot_have_an_initializer_1197": "Переменная оператора catch не может иметь инициализатор.", + "Change_0_to_1_90014": "Измените \"{0}\" на \"{1}\"", + "Change_all_extended_interfaces_to_implements_95038": "Изменить все расширенные интерфейсы на \"implements\"", + "Change_all_jsdoc_style_types_to_TypeScript_95030": "Изменить все типы JSDoc на TypeScript", + "Change_all_jsdoc_style_types_to_TypeScript_and_add_undefined_to_nullable_types_95031": "Изменить все типы JSDoc на TypeScript (и добавить \"| undefined\" к типам, допускающим значение NULL)", + "Change_extends_to_implements_90003": "Измените \"extends\" на \"implements\"", + "Change_spelling_to_0_90022": "Измените написание на \"{0}\"", + "Checking_if_0_is_the_longest_matching_prefix_for_1_2_6104": "Идет проверка того, является ли \"{0}\" самым длинным соответствующим префиксом для \"{1}\" — \"{2}\".", + "Circular_definition_of_import_alias_0_2303": "Циклическое определение псевдонима импорта \"{0}\".", + "Circularity_detected_while_resolving_configuration_Colon_0_18000": "Обнаружена цикличность при разрешении конфигурации: {0}", + "Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_functi_2426": "Класс \"{0}\" определяет метод доступа — элемент экземпляра \"{1}\", а расширенный класс \"{2}\" определяет его как функцию — элемент экземпляра.", + "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_access_2423": "Класс \"{0}\" определяет функцию — элемент экземпляра \"{1}\", а расширенный класс \"{2}\" определяет ее как метод доступа — элемент экземпляра.", + "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_proper_2424": "Класс \"{0}\" определяет функцию-элемент экземпляра \"{1}\", а расширенный класс \"{2}\" определяет ее как свойство-элемент экземпляра.", + "Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_functi_2425": "Класс \"{0}\" определяет свойство-элемент экземпляра \"{1}\", а расширенный класс \"{2}\" определяет его как функцию-элемент экземпляра.", + "Class_0_incorrectly_extends_base_class_1_2415": "Класс \"{0}\" неправильно расширяет базовый класс \"{1}\".", + "Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclas_2720": "Класс \"{0}\" неправильно реализует класс \"{1}\". Вы хотели расширить \"{1}\" и унаследовать его члены в виде подкласса?", + "Class_0_incorrectly_implements_interface_1_2420": "Класс \"{0}\" неправильно реализует интерфейс \"{1}\".", + "Class_0_used_before_its_declaration_2449": "Класс \"{0}\" использован прежде, чем объявлен.", + "Class_declarations_cannot_have_more_than_one_augments_or_extends_tag_8025": "В объявлении класса не может использоваться более одного тега \"@augments\" или \"@extends\".", + "Class_name_cannot_be_0_2414": "Имя класса не может иметь значение \"{0}\".", + "Class_name_cannot_be_Object_when_targeting_ES5_with_module_0_2725": "Класс не может иметь имя \"Object\" при выборе ES5 с модулем {0} в качестве целевого.", + "Class_static_side_0_incorrectly_extends_base_class_static_side_1_2417": "Статическая сторона класса \"{0}\" неправильно расширяет статическую сторону базового класса \"{1}\".", + "Classes_can_only_extend_a_single_class_1174": "Классы могут расширить только один класс.", + "Classes_containing_abstract_methods_must_be_marked_abstract_2514": "Классы, содержащие абстрактные методы, должны быть отмечены как абстрактные.", + "Command_line_Options_6171": "Параметры командной строки", + "Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json_6020": "Компиляция проекта по заданному пути к файлу конфигурации или папке с файлом tsconfig.json.", + "Compiler_option_0_expects_an_argument_6044": "Параметр компилятора \"{0}\" ожидает аргумент.", + "Compiler_option_0_requires_a_value_of_type_1_5024": "Параметр \"{0}\" компилятора требует значение типа {1}.", + "Composite_projects_may_not_disable_declaration_emit_6304": "Составные проекты не могут отключать выпуск объявления.", + "Computed_property_names_are_not_allowed_in_enums_1164": "Имена вычисляемых свойств запрещены в перечислениях.", + "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553": "Вычисленные значения запрещены в перечислении с членами, имеющими строковые значения.", + "Concatenate_and_emit_output_to_single_file_6001": "Связать и вывести результаты в один файл.", + "Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_librar_4090": "Конфликтующие определения для \"{0}\" найдены в \"{1}\" и \"{2}\". Попробуйте установить конкретную версию этой библиотеки, чтобы устранить конфликт.", + "Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7013": "Сигнатура конструктора, у которой нет аннотации типа возвращаемого значения, неявно имеет тип возвращаемого значения any.", + "Constructor_implementation_is_missing_2390": "Отсутствует реализация конструктора.", + "Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration_2673": "Конструктор класса \"{0}\" является частным и доступным только в объявлении класса.", + "Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration_2674": "Конструктор класса \"{0}\" защищен и доступен только в объявлении класса.", + "Constructors_for_derived_classes_must_contain_a_super_call_2377": "Конструкторы производных классов должны содержать вызов super.", + "Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126": "Содержащий файл не указан, корневой каталог невозможно определить. Выполняется пропуск поиска в папке node_modules.", + "Convert_0_to_mapped_object_type_95055": "Преобразовать \"{0}\" в тип сопоставленного объекта", + "Convert_all_constructor_functions_to_classes_95045": "Преобразовать все функции конструктора в классы", + "Convert_all_require_to_import_95048": "Преобразовать все \"require\" в \"import\"", + "Convert_all_to_default_imports_95035": "Преобразовать все в импорт по умолчанию", + "Convert_function_0_to_class_95002": "Преобразование функции \"{0}\" в класс", + "Convert_function_to_an_ES2015_class_95001": "Преобразование функции в класс ES2015", + "Convert_named_imports_to_namespace_import_95057": "Преобразовать операции импорта имен в импорт пространства имен", + "Convert_namespace_import_to_named_imports_95056": "Преобразовать импорт пространства имен в операции импорта имен", + "Convert_require_to_import_95047": "Преобразовать \"require\" в \"import\"", + "Convert_to_ES6_module_95017": "Преобразовать в модуль ES6", + "Convert_to_default_import_95013": "Преобразовать в импорт по умолчанию", + "Corrupted_locale_file_0_6051": "Поврежденный файл языкового стандарта \"{0}\".", + "Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type_7016": "Не удалось найти файл объявления модуля \"{0}\". \"{1}\" имеет неявный тип \"any\".", + "Could_not_write_file_0_Colon_1_5033": "Не удалось записать файл \"{0}\": \"{1}\".", + "DIRECTORY_6038": "КАТАЛОГ", + "Declaration_expected_1146": "Ожидалось объявление.", + "Declaration_name_conflicts_with_built_in_global_identifier_0_2397": "Имя объявления конфликтует со встроенным глобальным идентификатором \"{0}\".", + "Declaration_or_statement_expected_1128": "Ожидалось объявление или оператор.", + "Declare_method_0_90023": "Объявите метод \"{0}\"", + "Declare_property_0_90016": "Объявите свойство \"{0}\"", + "Declare_static_method_0_90024": "Объявите статический метод \"{0}\"", + "Declare_static_property_0_90027": "Объявите статическое свойство \"{0}\"", + "Decorators_are_not_valid_here_1206": "Декораторы здесь недопустимы.", + "Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name_1207": "Декораторы нельзя применять к множественным методам доступа get или set с совпадающим именем.", + "Default_export_of_the_module_has_or_is_using_private_name_0_4082": "Экспорт модуля по умолчанию использует или имеет закрытое имя \"{0}\".", + "Delete_all_unused_declarations_95024": "Удалить все неиспользуемые объявления", + "Delete_the_outputs_of_all_projects_6365": "Удалить выходные данные всех проектов", + "Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react__6084": "[Устарело.] Используйте --jsxFactory. Укажите объект, вызываемый для createElement при целевом порождении JSX react", + "Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file_6170": "[Устарело.] Используйте --outFile. Сцепление и порождение выходных данных в одном файле", + "Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files_6160": "[Устарело.] Используйте --skipLibCheck. Пропуск проверки типов для файлов объявления библиотеки по умолчанию.", + "Digit_expected_1124": "Ожидалась цифра.", + "Directory_0_does_not_exist_skipping_all_lookups_in_it_6148": "Каталога \"{0}\" не существует. Поиск в нем будет пропускаться.", + "Disable_checking_for_this_file_90018": "Отключите проверку для этого файла", + "Disable_size_limitations_on_JavaScript_projects_6162": "Отключение ограничений на размеры в проектах JavaScript.", + "Disable_strict_checking_of_generic_signatures_in_function_types_6185": "Отключить строгую проверку универсальных сигнатур в типах функций.", + "Disallow_inconsistently_cased_references_to_the_same_file_6078": "Запретить ссылки с разным регистром, указывающие на один файл.", + "Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files_6159": "Не добавлять ссылки с тройной косой чертой или импортированные модули в список скомпилированных файлов.", + "Do_not_emit_comments_to_output_6009": "Не создавать комментарии в выходных данных.", + "Do_not_emit_declarations_for_code_that_has_an_internal_annotation_6056": "Не создавать объявления для кода, имеющего аннотацию \"@internal\".", + "Do_not_emit_outputs_6010": "Не создавать выходные данные.", + "Do_not_emit_outputs_if_any_errors_were_reported_6008": "Не выводить выходные элементы, если есть ошибки.", + "Do_not_emit_use_strict_directives_in_module_output_6112": "Не порождать директивы use strict в выходных данных модуля.", + "Do_not_erase_const_enum_declarations_in_generated_code_6007": "Не удалять объявления перечислений констант из сгенерированного кода.", + "Do_not_generate_custom_helper_functions_like_extends_in_compiled_output_6157": "Не создавать вспомогательные пользовательские функции, такие как __extends, в скомпилированных выходных данных.", + "Do_not_include_the_default_library_file_lib_d_ts_6158": "Не включать файл библиотеки по умолчанию (lib.d.ts).", + "Do_not_report_errors_on_unreachable_code_6077": "Не сообщать об ошибках в недостижимом коде.", + "Do_not_report_errors_on_unused_labels_6074": "Не сообщать об ошибках в неиспользуемых метках.", + "Do_not_resolve_the_real_path_of_symlinks_6013": "Не разрешать реальный путь symlink.", + "Do_not_truncate_error_messages_6165": "Не усекать сообщения об ошибках.", + "Duplicate_declaration_0_2718": "Дублирующееся объявление \"{0}\".", + "Duplicate_function_implementation_2393": "Повторяющаяся реализация функции.", + "Duplicate_identifier_0_2300": "Повторяющийся идентификатор \"{0}\".", + "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_2441": "Повторяющийся идентификатор \"{0}\". Компилятор резервирует имя \"{1}\" в области верхнего уровня модуля.", + "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_func_2529": "Повторяющийся идентификатор \"{0}\". Компилятор резервирует имя \"{1}\" в области верхнего уровня для асинхронных функций в модуле.", + "Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions_2520": "Повторяющийся идентификатор \"{0}\". Компилятор использует объявление \"{1}\" для поддержки асинхронных функций.", + "Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters_2396": "Повторяющийся идентификатор arguments. Компилятор использует arguments для инициализации параметров \"rest\".", + "Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_me_2543": "Дублирующийся идентификатор \"_newTarget\". Компилятор использует объявление переменной \"_newTarget\" для получения ссылки на метасвойство \"new.target\".", + "Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference_2401": "Повторяющийся идентификатор \"_super\". Компилятор использует \"_super\" для получения ссылки на базовый класс.", + "Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference_2399": "Повторяющийся идентификатор \"_this\". Компилятор использует объявление переменной \"_this\" для получения ссылки this.", + "Duplicate_label_0_1114": "Повторяющаяся метка \"{0}\".", + "Duplicate_number_index_signature_2375": "Повторяющаяся сигнатура числового индекса.", + "Duplicate_string_index_signature_2374": "Повторяющаяся сигнатура строкового индекса.", + "Dynamic_import_cannot_have_type_arguments_1326": "При динамическом импорте не могут использоваться аргументы типов", + "Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext_1323": "Динамический импорт поддерживается, только если флаг \"--module\" имеет значение \"commonjs\" или \"esNext\".", + "Dynamic_import_must_have_one_specifier_as_an_argument_1324": "При динамическом импорте необходимо указать один описатель в качестве аргумента.", + "Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036": "Описатель динамического импорта должен иметь тип \"string\", но имеет тип \"{0}\".", + "Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015": "Элемент неявно содержит тип any, так как выражение индекса не имеет тип number.", + "Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature_7017": "Элемент неявно имеет тип any, так как тип \"{0}\" не содержит сигнатуру индекса.", + "Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files_6164": "Порождать метку порядка байтов UTF-8 в начале выходных файлов.", + "Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file_6151": "Порождать один файл с сопоставлениями источников, а не создавать отдельный файл.", + "Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap__6152": "Порождать источник вместе с sourcemap в одном файле (нужно задать параметр --inlineSourceMap или --sourceMap).", + "Enable_all_strict_type_checking_options_6180": "Включить все параметры строгой проверки типов.", + "Enable_project_compilation_6302": "Включить компиляцию проекта", + "Enable_strict_checking_of_function_types_6186": "Включение строгой проверки типов функций.", + "Enable_strict_checking_of_property_initialization_in_classes_6187": "Включение строгой проверки инициализации свойств в классах.", + "Enable_strict_null_checks_6113": "Включить строгие проверки NULL.", + "Enable_tracing_of_the_name_resolution_process_6085": "Включить трассировку процесса разрешения имен.", + "Enable_verbose_logging_6366": "Включить подробное ведение журнала", + "Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for__7037": "Позволяет обеспечивать взаимодействие между модулями CommonJS и ES посредством создания объектов пространства имен для всех импортов. Подразумевает \"allowSyntheticDefaultImports\".", + "Enables_experimental_support_for_ES7_async_functions_6068": "Включает экспериментальную поддержку для асинхронных функций ES7.", + "Enables_experimental_support_for_ES7_decorators_6065": "Включает экспериментальную поддержку для декораторов ES7.", + "Enables_experimental_support_for_emitting_type_metadata_for_decorators_6066": "Включает экспериментальную поддержку для создания метаданных типа для декораторов.", + "Enum_0_used_before_its_declaration_2450": "Перечисление \"{0}\" использовано прежде, чем объявлено.", + "Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations_2567": "Объявления перечислений можно объединять только с пространствами имен или другими объявлениями перечислений.", + "Enum_declarations_must_all_be_const_or_non_const_2473": "Все объявления перечислений должны иметь значение const или отличное от const.", + "Enum_member_expected_1132": "Ожидался элемент перечисления.", + "Enum_member_must_have_initializer_1061": "У элемента перечисления должен быть инициализатор.", + "Enum_name_cannot_be_0_2431": "Имя перечисления не может иметь значение \"{0}\".", + "Enum_type_0_has_members_with_initializers_that_are_not_literals_2535": "Тип перечисления \"{0}\" имеет элементы с инициализаторами, которые не являются литералами.", + "Examples_Colon_0_6026": "Примеры: {0}", + "Excessive_stack_depth_comparing_types_0_and_1_2321": "Чрезмерная глубина стека при сравнении типов \"{0}\" и \"{1}\".", + "Expected_0_1_type_arguments_provide_these_with_an_extends_tag_8027": "Ожидается аргументов типа: {0}–{1}. Укажите их с тегом \"@extends\".", + "Expected_0_arguments_but_got_1_2554": "Ожидалось аргументов: {0}, получено: {1}.", + "Expected_0_arguments_but_got_1_or_more_2556": "Ожидалось аргументов: {0}, получено: {1} или больше.", + "Expected_0_type_arguments_but_got_1_2558": "Ожидались аргументы типа {0}, получены: {1}.", + "Expected_0_type_arguments_provide_these_with_an_extends_tag_8026": "Ожидается аргументов типа: {0}. Укажите их с тегом \"@extends\".", + "Expected_at_least_0_arguments_but_got_1_2555": "Ожидалось аргументов не меньше: {0}, получено: {1}.", + "Expected_at_least_0_arguments_but_got_1_or_more_2557": "Ожидалось аргументов не меньше: {0}, получено: {1} или больше.", + "Expected_corresponding_JSX_closing_tag_for_0_17002": "Ожидался соответствующий закрывающий тег JSX для \"{0}\".", + "Expected_corresponding_closing_tag_for_JSX_fragment_17015": "Ожидался соответствующий закрывающий тег фрагмента JSX.", + "Expected_type_of_0_field_in_package_json_to_be_string_got_1_6105": "Ожидаемый тип поля \"{0}\" в package.json должен быть string, получен \"{1}\".", + "Experimental_Options_6177": "Экспериментальные параметры", + "Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_t_1219": "Экспериментальная поддержка для декораторов — это функция, которая будет изменена в будущем выпуске. Задайте параметр experimentalDecorators, чтобы удалить это предупреждение.", + "Explicitly_specified_module_resolution_kind_Colon_0_6087": "Явно указанный тип разрешения модуля: \"{0}\".", + "Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or__1203": "Назначение экспорта невозможно использовать при разработке для модулей ECMAScript. Попробуйте использовать \"export default\" или другой формат модуля.", + "Export_assignment_is_not_supported_when_module_flag_is_system_1218": "Присваивание экспорта не поддерживается, если флаг \"--module\" имеет значение \"system\".", + "Export_declaration_conflicts_with_exported_declaration_of_0_2484": "Объявление экспорта конфликтует с экспортированным объявлением \"{0}\".", + "Export_declarations_are_not_permitted_in_a_namespace_1194": "Объявления экспорта не разрешены в пространстве имен.", + "Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_2656": "Файл экспортированных внешних типизаций пакета \"{0}\" не является модулем. Обратитесь к автору пакета для обновления определения пакета.", + "Exported_external_package_typings_file_cannot_contain_tripleslash_references_Please_contact_the_pack_2654": "Файл экспортированных внешних типизаций пакета не может содержать ссылки с тройной косой чертой. Обратитесь к автору пакета для обновления определения пакета.", + "Exported_type_alias_0_has_or_is_using_private_name_1_4081": "Экспортированный псевдоним типа \"{0}\" имеет или использует закрытое имя \"{1}\".", + "Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4023": "Экспортированная переменная \"{0}\" имеет или использует имя \"{1}\" из внешнего модуля {2}, но не может быть именована.", + "Exported_variable_0_has_or_is_using_name_1_from_private_module_2_4024": "Экспортированная переменная \"{0}\" имеет или использует имя \"{1}\" из закрытого модуля \"{2}\".", + "Exported_variable_0_has_or_is_using_private_name_1_4025": "Экспортированная переменная \"{0}\" имеет или использует закрытое имя \"{1}\".", + "Exports_and_export_assignments_are_not_permitted_in_module_augmentations_2666": "Экспорт и назначения экспорта не разрешены в улучшениях модуля.", + "Expression_expected_1109": "Ожидалось выражение.", + "Expression_or_comma_expected_1137": "Ожидалось выражение или запятая.", + "Expression_resolves_to_super_that_compiler_uses_to_capture_base_class_reference_2402": "Разрешение выражения дает идентификатор \"_super\", который используется компилятором для получения ссылки на базовый класс.", + "Expression_resolves_to_variable_declaration_0_that_compiler_uses_to_support_async_functions_2521": "Разрешение выражения дает объявление переменной \"{0}\", которое используется компилятором для поддержки асинхронных функций.", + "Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta__2544": "Выражение разрешается в объявление переменной \"_newTarget\", которое компилятор использует для получения ссылки на метасвойство \"new.target\".", + "Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference_2400": "Разрешение выражения дает объявление переменной \"_this\", которое используется компилятором для получения ссылки this.", + "Extract_constant_95006": "Извлечь константу", + "Extract_function_95005": "Извлечь функцию", + "Extract_to_0_in_1_95004": "Извлечь в {0} в {1}", + "Extract_to_0_in_1_scope_95008": "Извлечь в {0} в области {1}", + "Extract_to_0_in_enclosing_scope_95007": "Извлечь в {0} во включающей области", + "FILE_6035": "ФАЙЛ", + "FILE_OR_DIRECTORY_6040": "Файл или каталог", + "Failed_to_parse_file_0_Colon_1_5014": "Не удалось проанализировать файл \"{0}\": {1}.", + "Fallthrough_case_in_switch_7029": "Случай передачи управления в операторе switch.", + "File_0_does_not_exist_6096": "Файл \"{0}\" не существует.", + "File_0_exist_use_it_as_a_name_resolution_result_6097": "Файл \"{0}\" существует — используйте его как результат разрешения имени.", + "File_0_has_an_unsupported_extension_so_skipping_it_6081": "Файл \"{0}\" имеет неподдерживаемое разрешение, поэтому будет пропущен.", + "File_0_has_unsupported_extension_The_only_supported_extensions_are_1_6054": "Файл \"{0}\" имеет неподдерживаемое расширение. Поддерживаются только следующие расширения: {1}.", + "File_0_is_not_a_module_2306": "Файл \"{0}\" не является модулем.", + "File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern_6307": "Файл \"{0}\" отсутствует в списке файлов проекта. Проекты должны перечислять все файлы или использовать шаблон включения.", + "File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files_6059": "Файл \"{0}\" отсутствует в \"rootDir\" \"{1}\". Все исходные файлы должны находиться в каталоге \"rootDir\".", + "File_0_not_found_6053": "Файл \"{0}\" не найден.", + "File_change_detected_Starting_incremental_compilation_6032": "Обнаружено изменение в файле. Запускается инкрементная компиляция...", + "File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module_80001": "Файл является модулем CommonJS; его можно преобразовать в модуль ES6.", + "File_name_0_differs_from_already_included_file_name_1_only_in_casing_1149": "Файл с именем \"{0}\" отличается от уже включенного файла с именем \"{1}\" только регистром.", + "File_name_0_has_a_1_extension_stripping_it_6132": "У имени файла \"{0}\" есть расширение \"{1}\"; расширение удаляется.", + "File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildca_5065": "Спецификация файла не может содержать родительский каталог (\"..\"), который указывается после рекурсивного подстановочного знака каталога (\"**\"): \"{0}\".", + "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010": "Спецификация файла не может заканчиваться рекурсивным подстановочным знаком каталога (\"**\"): \"{0}\".", + "Fix_all_detected_spelling_errors_95026": "Исправить все обнаруженные синтаксические ошибки", + "Found_0_errors_Watching_for_file_changes_6194": "Найдено ошибок: {0}. Отслеживаются изменения в файлах.", + "Found_1_error_Watching_for_file_changes_6193": "Найдена одна ошибка. Отслеживаются изменения в файлах.", + "Found_package_json_at_0_6099": "Обнаружен package.json в \"{0}\".", + "Found_package_json_at_0_Package_ID_is_1_6190": "Найден \"package.json\" в \"{0}\". Идентификатор пакета: \"{1}\".", + "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_1250": "Объявления функций не разрешены в блоках в строгом режиме при нацеливании ES3 или ES5.", + "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_d_1251": "Объявления функций не разрешены в блоках в строгом режиме при нацеливании ES3 или ES5. Определения класса автоматически появляются в строгом режиме.", + "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_1252": "Объявления функций не разрешены в блоках в строгом режиме при нацеливании ES3 или ES5. Модули автоматически появляются в строгом режиме.", + "Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type_7011": "Выражение функции, у которого нет аннотации типа возвращаемого значения, неявно имеет тип возвращаемого значения \"{0}\".", + "Function_implementation_is_missing_or_not_immediately_following_the_declaration_2391": "Реализация функции отсутствует либо не идет сразу после объявления.", + "Function_implementation_name_must_be_0_2389": "Имя реализации функции должно иметь значение \"{0}\".", + "Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_ref_7024": "Функция неявно имеет тип возвращаемого значения any, так как у нее нет заметки с типом возвращаемого значения, а также на нее прямо или косвенно указывает ссылка в одном из ее выражений \"return\".", + "Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined_2366": "В функции отсутствует завершающий оператор возвращаемого значения, а тип возвращаемого значения не включает undefined.", + "Function_overload_must_be_static_2387": "Перегрузка функции должна быть статической.", + "Function_overload_must_not_be_static_2388": "Перегрузка функции не должна быть статической.", + "Generate_get_and_set_accessors_95046": "Создать методы доступа get и set", + "Generates_a_sourcemap_for_each_corresponding_d_ts_file_6000": "Создает sourcemap для каждого соответствующего файла \".d.ts\".", + "Generates_corresponding_d_ts_file_6002": "Создает соответствующий D.TS-файл.", + "Generates_corresponding_map_file_6043": "Создает соответствующий файл с расширением \".map\".", + "Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_typ_7025": "Генератор неявно имеет тип \"{0}\", поскольку он не предоставляет никаких значений. Рекомендуется указать тип возвращаемого значения.", + "Generators_are_not_allowed_in_an_ambient_context_1221": "Генераторы не разрешается использовать в окружающем контексте.", + "Generators_are_only_available_when_targeting_ECMAScript_2015_or_higher_1220": "Генераторы доступны только при разработке для ECMAScript 2015 или более поздних версий.", + "Generic_type_0_requires_1_type_argument_s_2314": "Универсальный тип \"{0}\" требует следующее число аргументов типа: {1}.", + "Generic_type_0_requires_between_1_and_2_type_arguments_2707": "Универсальный тип \"{0}\" требует аргументы типа от {1} до {2}.", + "Generic_type_instantiation_is_excessively_deep_and_possibly_infinite_2550": "Создание экземпляров универсального типа слишком глубокое и, возможно, бесконечное.", + "Getter_and_setter_accessors_do_not_agree_in_visibility_2379": "Методы доступа get и set не согласуются с точки зрения видимости.", + "Global_module_exports_may_only_appear_at_top_level_1316": "Глобальные операции экспорта модуля могут появиться только на верхнем уровне.", + "Global_module_exports_may_only_appear_in_declaration_files_1315": "Глобальные операции экспорта модуля могут появиться только в файлах объявления.", + "Global_module_exports_may_only_appear_in_module_files_1314": "Глобальные операции экспорта модуля могут появиться только в файлах модуля.", + "Global_type_0_must_be_a_class_or_interface_type_2316": "Глобальный тип \"{0}\" должен быть классом или интерфейсом.", + "Global_type_0_must_have_1_type_parameter_s_2317": "Глобальный тип \"{0}\" должен иметь следующее число параметров типа: {1}.", + "Hexadecimal_digit_expected_1125": "Ожидалась шестнадцатеричная цифра.", + "Identifier_expected_0_is_a_reserved_word_in_strict_mode_1212": "Ожидался идентификатор. \"{0}\" является зарезервированным словом в строгом режиме.", + "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_stric_1213": "Ожидался идентификатор. \"{0}\" является зарезервированным словом в строгом режиме. Определения классов автоматически находятся в строгом режиме.", + "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode_1214": "Ожидался идентификатор. \"{0}\" является зарезервированным словом в строгом режиме. Модули автоматически находятся в строгом режиме.", + "Identifier_expected_1003": "Ожидался идентификатор.", + "Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules_1216": "Ожидался идентификатор. Значение \"__esModule\" зарезервировано как экспортируемый маркер при преобразовании модулей ECMAScript.", + "Ignore_this_error_message_90019": "Пропустите это сообщение об ошибке", + "Implement_all_inherited_abstract_classes_95040": "Реализовать все унаследованные абстрактные классы", + "Implement_all_unimplemented_interfaces_95032": "Реализовать все нереализованные интерфейсы", + "Implement_inherited_abstract_class_90007": "Реализуйте наследуемый абстрактный класс", + "Implement_interface_0_90006": "Реализуйте интерфейс \"{0}\"", + "Implements_clause_of_exported_class_0_has_or_is_using_private_name_1_4019": "Предложение Implements экспортированного класса \"{0}\" имеет или использует закрытое имя \"{1}\".", + "Import_0_from_module_1_90013": "Импортируйте \"{0}\" из модуля \"{1}\"", + "Import_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_import_Asterisk_as_1202": "Назначение импорта невозможно использовать при разработке для модулей ECMAScript. Попробуйте использовать \"import * as ns from \"mod\", \"import {a} from \"mod\", \"import d from \"mod\" или другой формат модуля.", + "Import_declaration_0_is_using_private_name_1_4000": "Объявление импорта \"{0}\" использует закрытое имя \"{1}\".", + "Import_declaration_conflicts_with_local_declaration_of_0_2440": "Объявление импорта конфликтует с локальным объявлением \"{0}\".", + "Import_declarations_in_a_namespace_cannot_reference_a_module_1147": "Объявления импорта в пространстве имен не могут иметь ссылки на модуль.", + "Import_emit_helpers_from_tslib_6139": "Импорт вспомогательных объектов, участвующих в порождении, из \"tslib\".", + "Import_may_be_converted_to_a_default_import_80003": "Импорт можно преобразовать в импорт по умолчанию.", + "Import_name_cannot_be_0_2438": "Имя импорта не может иметь значение \"{0}\".", + "Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relati_2439": "Объявление импорта или экспорта во объявлении окружающего модуля не может иметь ссылки на модуль через относительное имя модуля.", + "Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_mod_2667": "Операции импорта запрещены в улучшениях модуля. Попробуйте переместить их в содержащий внешний модуль.", + "In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066": "Во внешних объявлениях перечислений инициализатор элемента должен быть константным выражением.", + "In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enu_2432": "В перечислении с несколькими объявлениями только одно объявление может опустить инициализатор для своего первого элемента перечисления.", + "In_const_enum_declarations_member_initializer_must_be_constant_expression_2474": "В инициализаторе элементов объявлений перечисления const должно быть константным выражением.", + "Include_modules_imported_with_json_extension_6197": "Включать модули, импортированные с расширением .json", + "Index_signature_in_type_0_only_permits_reading_2542": "Сигнатура индекса в типе \"{0}\" разрешает только чтение.", + "Index_signature_is_missing_in_type_0_2329": "В типе \"{0}\" отсутствует сигнатура индекса.", + "Index_signatures_are_incompatible_2330": "Сигнатуры индекса несовместимы.", + "Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local_2395": "Все отдельные объявления в объединенном объявлении \"{0}\" должны быть экспортированными или локальными.", + "Infer_all_types_from_usage_95023": "Вывести все типы исходя из использования", + "Infer_parameter_types_from_usage_95012": "Выведите типы параметров на основании их использования", + "Infer_type_of_0_from_usage_95011": "Выведите тип \"{0}\" на основании его использования", + "Initialize_property_0_in_the_constructor_90020": "Инициализируйте свойство \"{0}\" в конструкторе", + "Initialize_static_property_0_90021": "Инициализируйте статическое свойство \"{0}\"", + "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301": "Инициализатор переменной-элемента экземпляра \"{0}\" не может ссылаться на идентификатор \"{1}\", объявленный в конструкторе.", + "Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it_2373": "Инициализатор параметра \"{0}\" не может ссылаться на идентификатор \"{1}\", объявленный после него.", + "Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value_2525": "Инициализатор не предоставляет значения для элемента привязки, который не имеет значения по умолчанию.", + "Initializers_are_not_allowed_in_ambient_contexts_1039": "Инициализаторы не разрешены в окружающих контекстах.", + "Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file_6070": "Инициализирует проект TypeScript и создает файл \"tsconfig.json\".", + "Insert_command_line_options_and_files_from_a_file_6030": "Вставка параметров командной строки и файлов из файла.", + "Install_0_95014": "Установить \"{0}\"", + "Install_all_missing_types_packages_95033": "Установить все отсутствующие пакеты типов", + "Interface_0_cannot_simultaneously_extend_types_1_and_2_2320": "Интерфейс \"{0}\" не может одновременно расширить типы \"{1}\" и \"{2}\".", + "Interface_0_incorrectly_extends_interface_1_2430": "Интерфейс \"{0}\" неправильно расширяет интерфейс \"{1}\".", + "Interface_declaration_cannot_have_implements_clause_1176": "Объявление интерфейса не может иметь предложение implements.", + "Interface_name_cannot_be_0_2427": "Имя интерфейса не может иметь значение \"{0}\".", + "Invalid_character_1127": "Недопустимый символ.", + "Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augm_2665": "Недопустимое имя модуля в приращении. Модуль \"{0}\" разрешается в модуль без типа в \"{1}\", который невозможно дополнить.", + "Invalid_module_name_in_augmentation_module_0_cannot_be_found_2664": "Недопустимое имя модуля в улучшении, не удается найти модуль \"{0}\".", + "Invalid_reference_directive_syntax_1084": "Недопустимый синтаксис директивы reference.", + "Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode_1210": "Недопустимое использование \"{0}\". Определения классов автоматически находятся в строгом режиме.", + "Invalid_use_of_0_Modules_are_automatically_in_strict_mode_1215": "Недопустимое использование \"{0}\". Модули автоматически находятся в строгом режиме.", + "Invalid_use_of_0_in_strict_mode_1100": "Недопустимое использование \"{0}\" в строгом режиме.", + "Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name_5067": "Недопустимое значение для jsxFactory. \"{0}\" не является допустимым идентификатором или полным именем.", + "Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier_5059": "Недопустимое значение для \"--reactNamespace\". \"{0}\" не является допустимым идентификатором.", + "JSDoc_0_1_does_not_match_the_extends_2_clause_8023": "Параметр \"@{0} {1}\" JSDoc не соответствует предложению \"extends {2}\".", + "JSDoc_0_is_not_attached_to_a_class_8022": "Параметр \"@{0}\" JSDoc не связан с классом.", + "JSDoc_may_only_appear_in_the_last_parameter_of_a_signature_8028": "JSDoc \"...\" может использоваться только в последнем параметре сигнатуры.", + "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_8024": "У тега \"@param\" JSDoc есть имя \"{0}\", но параметр с таким именем отсутствует.", + "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_h_8029": "Тег \"@param\" JSDoc имеет имя \"{0}\", но параметра с таким именем не существует. Он совпадал бы с \"arguments\", если бы у него был указан тип массива.", + "JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags_8021": "У тега \"@typedef\" JSDoc должна быть аннотация типа, или после него должны стоять теги \"@property\" или \"@member\".", + "JSDoc_types_can_only_be_used_inside_documentation_comments_8020": "Типы JSDoc можно использовать только в комментариях в документации.", + "JSDoc_types_may_be_moved_to_TypeScript_types_80004": "Типы JSDoc могут быть преобразованы в типы TypeScript.", + "JSX_attribute_expected_17003": "Ожидался атрибут JSX.", + "JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000": "Атрибутам JSX должно назначаться только непустое \"expression\".", + "JSX_element_0_has_no_corresponding_closing_tag_17008": "Элемент JSX \"{0}\" не содержит соответствующий закрывающий тег.", + "JSX_element_attributes_type_0_may_not_be_a_union_type_2600": "Тип атрибутов элемента JSX \"{0}\" не может быть типом объединения.", + "JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property_2607": "Класс элементов JSX не поддерживает атрибуты, так как не имеет свойства \"{0}\".", + "JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists_7026": "Элемент JSX неявно имеет тип \"any\", так как интерфейс \"JSX.{0}\" не существует.", + "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602": "Элемент JSX неявно имеет тип any, так как глобальный тип \"JSX.Element\" не существует.", + "JSX_element_type_0_does_not_have_any_construct_or_call_signatures_2604": "Тип элемента JSX \"{0}\" не имеет конструкций или сигнатур вызова.", + "JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements_2605": "Тип элемента JSX \"{0}\" не является функцией конструктора для элементов JSX.", + "JSX_elements_cannot_have_multiple_attributes_with_the_same_name_17001": "Элементы JSX не могут иметь несколько атрибутов с одним именем.", + "JSX_expressions_must_have_one_parent_element_2657": "Выражения JSX должны иметь один родительский элемент.", + "JSX_fragment_has_no_corresponding_closing_tag_17014": "Фрагмент JSX не имеет соответствующего закрывающего тега.", + "JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma_17017": "Фрагмент JSX не поддерживается при использовании встроенной директивы pragma фабрики JSX.", + "JSX_fragment_is_not_supported_when_using_jsxFactory_17016": "Фрагмент JSX не поддерживается при использовании --jsxFactory", + "JSX_spread_child_must_be_an_array_type_2609": "Дочерний объект расширения JSX должен иметь тип массива.", + "Jump_target_cannot_cross_function_boundary_1107": "Целевой объект перехода не может находиться за границей функции.", + "KIND_6034": "ВИД", + "LOCATION_6037": "РАСПОЛОЖЕНИЕ", + "Language_service_is_disabled_9004": "Языковая служба отключена.", + "Left_side_of_comma_operator_is_unused_and_has_no_side_effects_2695": "Сторона оператора слева от запятой не используется и не имеет побочных эффектов.", + "Line_break_not_permitted_here_1142": "Здесь запрещено использовать разрыв строки.", + "Line_terminator_not_permitted_before_arrow_1200": "Перед стрелкой запрещен символ завершения строки.", + "List_of_folders_to_include_type_definitions_from_6161": "Список папок, определения типов из которых будут включены.", + "List_of_language_service_plugins_6181": "Список подключаемых модулей языковой службы.", + "List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime_6168": "Список корневых папок, объединенное содержимое которых представляет структуру проекта во время выполнения.", + "Loading_0_from_the_root_dir_1_candidate_location_2_6109": "Загружается \"{0}\" из корневого каталога \"{1}\"; расположение кандидата: \"{2}\".", + "Loading_module_0_from_node_modules_folder_target_file_type_1_6098": "Загружается модуль \"{0}\" из папки \"node_modules\", тип целевого файла: \"{1}\".", + "Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1_6095": "Загружается модуль в виде файла или папки, расположение модуля-кандидата: \"{0}\", тип целевого файла: \"{1}\".", + "Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1_6048": "Языковой стандарт должен иметь форму <язык> или <язык>–<территория>. Например, \"{0}\" или \"{1}\".", + "Longest_matching_prefix_for_0_is_1_6108": "Самый длинный соответствующий префикс для \"{0}\": \"{1}\".", + "Looking_up_in_node_modules_folder_initial_location_0_6125": "Поиск в папке node_modules; первоначальное расположение: \"{0}\".", + "Make_all_super_calls_the_first_statement_in_their_constructor_95036": "Сделать все вызовы \"super()\" первой инструкцией в конструкторе", + "Make_super_call_the_first_statement_in_the_constructor_90002": "Сделайте вызов \"super()\" первой инструкцией в конструкторе", + "Mapped_object_type_implicitly_has_an_any_template_type_7039": "Сопоставленный объект неявно имеет тип шаблона \"любой\".", + "Member_0_implicitly_has_an_1_type_7008": "Элемент \"{0}\" неявно имеет тип \"{1}\".", + "Merge_conflict_marker_encountered_1185": "Встретилась отметка о конфликте слияния.", + "Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_d_2652": "Объединенное объявление \"{0}\" не может включать объявление экспорта по умолчанию. Рекомендуется добавить вместо него отдельное объявление \"export default {0}\".", + "Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constru_17013": "Метасвойство \"{0}\" разрешено только в тексте объявления функции, выражения функции или конструктора.", + "Method_0_cannot_have_an_implementation_because_it_is_marked_abstract_1245": "Метод \"{0}\" не может иметь реализацию, так как он отмечен в качестве абстрактного.", + "Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4101": "Метод \"{0}\" экспортированного интерфейса имеет или использует имя \"{1}\" из закрытого модуля \"{2}\".", + "Method_0_of_exported_interface_has_or_is_using_private_name_1_4102": "Метод \"{0}\" экспортированного интерфейса имеет или использует закрытое имя \"{1}\".", + "Modifiers_cannot_appear_here_1184": "Здесь невозможно использовать модификаторы.", + "Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_1340": "Модуль \"{0}\" не ссылается на тип, но используется здесь как тип.", + "Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here_1339": "Модуль \"{0}\" не ссылается на значение, но используется здесь как значение.", + "Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambig_2308": "Модуль {0} уже экспортировал элемент с именем \"{1}\". Попробуйте явно повторно экспортировать его, чтобы устранить неоднозначность.", + "Module_0_has_no_default_export_1192": "У модуля \"{0}\" нет экспорта по умолчанию.", + "Module_0_has_no_exported_member_1_2305": "Модуль \"{0}\" не имеет экспортированного элемента \"{1}\".", + "Module_0_has_no_exported_member_1_Did_you_mean_2_2724": "В модуле \"{0}\" нет экспортированного элемента \"{1}\". Вы имели в виду \"{2}\"?", + "Module_0_is_hidden_by_a_local_declaration_with_the_same_name_2437": "Модуль \"{0}\" скрыт локальным объявлением с таким же именем.", + "Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct_2497": "Модуль \"{0}\" разрешается в немодульную сущность и не может быть импортирован с помощью этой конструкции.", + "Module_0_uses_export_and_cannot_be_used_with_export_Asterisk_2498": "Модуль \"{0}\" использует параметр \"export =\" и не может использоваться с параметром \"export *\".", + "Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified_6145": "Модуль \"{0}\" был разрешен в окружающий модуль, объявленный в \"{1}\", так как этот файл не был изменен.", + "Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1_6144": "Модуль \"{0}\" был разрешен как локально объявленный окружающий модуль в файле \"{1}\".", + "Module_0_was_resolved_to_1_but_jsx_is_not_set_6142": "Модуль \"{0}\" был разрешен как \"{1}\", но параметр \"--jsx\" не задан.", + "Module_Resolution_Options_6174": "Параметры разрешения модулей", + "Module_name_0_matched_pattern_1_6092": "Имя модуля \"{0}\", соответствующий шаблон \"{1}\".", + "Module_name_0_was_not_resolved_6090": "======== Имя модуля \"{0}\" не было разрешено. ========", + "Module_name_0_was_successfully_resolved_to_1_6089": "======== Имя модуля \"{0}\" было успешно разрешено в \"{1}\". ========", + "Module_resolution_kind_is_not_specified_using_0_6088": "Тип разрешения модуля не указан, используется \"{0}\".", + "Module_resolution_using_rootDirs_has_failed_6111": "Произошел сбой при разрешении модуля с помощью \"rootDirs\".", + "Move_to_a_new_file_95049": "Переместить в новый файл", + "Multiple_consecutive_numeric_separators_are_not_permitted_6189": "Использовать несколько последовательных числовых разделителей запрещено.", + "Multiple_constructor_implementations_are_not_allowed_2392": "Не разрешается использование нескольких реализаций конструкторов.", + "NEWLINE_6061": "НОВАЯ СТРОКА", + "Named_property_0_of_types_1_and_2_are_not_identical_2319": "Именованное свойство \"{0}\" содержит типы \"{1}\" и \"{2}\", которые не являются идентичными.", + "Namespace_0_has_no_exported_member_1_2694": "Пространство имен \"{0}\" не содержит экспортированный элемент \"{1}\".", + "No_base_constructor_has_the_specified_number_of_type_arguments_2508": "Ни один конструктор базового класса не имеет указанного числа аргументов типа.", + "No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2_18003": "Не удалось найти входные данные в файле конфигурации \"{0}\". Указанные пути \"include\": \"{1}\", пути \"exclude\": \"{2}\".", + "Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2_2515": "Класс \"{0}\", не являющийся абстрактным, не реализует наследуемый абстрактный элемент \"{1}\" класса \"{2}\".", + "Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1_2653": "Выражение неабстрактного класса не реализует унаследованный абстрактный элемент \"{0}\" класса \"{1}\".", + "Not_all_code_paths_return_a_value_7030": "Не все пути кода возвращают значение.", + "Numeric_index_type_0_is_not_assignable_to_string_index_type_1_2413": "Тип числового индекса \"{0}\" нельзя назначить типу строкового индекса \"{1}\".", + "Numeric_separators_are_not_allowed_here_6188": "Числовые разделители здесь запрещены.", + "Object_is_of_type_unknown_2571": "Объект имеет тип \"Неизвестный\".", + "Object_is_possibly_null_2531": "Возможно, объект равен null.", + "Object_is_possibly_null_or_undefined_2533": "Возможно, объект равен null или undefined.", + "Object_is_possibly_undefined_2532": "Возможно, объект равен undefined.", + "Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1_2353": "Объектный литерал может использовать только известные свойства. \"{0}\" не существует в типе \"{1}\".", + "Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_writ_2561": "Объектный литерал может указывать только известные свойства, но \"{0}\" не существует в типе \"{1}\". Вы хотели записать \"{2}\"?", + "Object_literal_s_property_0_implicitly_has_an_1_type_7018": "Свойство объектного литерала \"{0}\" неявно имеет тип \"{1}\".", + "Octal_digit_expected_1178": "Ожидалась восьмеричная цифра.", + "Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0_8017": "Литералы восьмеричного типа должны использовать синтаксис ES2015. Используйте синтаксис \"{0}\".", + "Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0_8018": "Восьмеричные литералы запрещены в инициализаторах членов перечисления. Используйте синтаксис \"{0}\".", + "Octal_literals_are_not_allowed_in_strict_mode_1121": "Восьмеричные литералы запрещено использовать в строгом режиме.", + "Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0_1085": "Восьмеричные литералы недоступны при выборе целевой платформы ECMAScript 5 и более поздних. Используйте синтаксис \"{0}\".", + "Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement_1091": "В операторе for...in разрешено только одно объявление переменной.", + "Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement_1188": "В операторе for...of разрешено только одно объявление переменной.", + "Only_a_void_function_can_be_called_with_the_new_keyword_2350": "С помощью ключевого слова new можно вызвать только функцию void.", + "Only_ambient_modules_can_use_quoted_names_1035": "Имена в кавычках могут использоваться только во внешних модулях.", + "Only_amd_and_system_modules_are_supported_alongside_0_6082": "Только модули amd и system поддерживаются вместе с --{0}.", + "Only_emit_d_ts_declaration_files_6014": "Порождаются только файлы объявлений \".d.ts\".", + "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002": "В предложениях extends класса сейчас поддерживаются только идентификаторы или полные имена с необязательными аргументами типа.", + "Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword_2340": "Через ключевое слово super доступны только общие и защищенные методы базового класса.", + "Operator_0_cannot_be_applied_to_types_1_and_2_2365": "Оператор \"{0}\" невозможно применить к типам \"{1}\" и \"{2}\".", + "Option_0_can_only_be_specified_in_tsconfig_json_file_6064": "Параметр \"{0}\" можно указать только в файле tsconfig.json.", + "Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided_5051": "Параметр \"{0}\" можно использовать только при указании \"--inlineSourceMap\" или \"--sourceMap\".", + "Option_0_cannot_be_specified_with_option_1_5053": "Параметр \"{0}\" невозможно указать с помощью параметра \"{1}\".", + "Option_0_cannot_be_specified_without_specifying_option_1_5052": "Параметр \"{0}\" невозможно указать без указания параметра \"{1}\".", + "Option_0_cannot_be_specified_without_specifying_option_1_or_option_2_5069": "Параметр \"{0}\" нельзя указывать без указания параметра \"{1}\" или \"{2}\".", + "Option_0_should_have_array_of_strings_as_a_value_6103": "Параметр \"{0}\" должен иметь массив строк в качестве значения.", + "Option_build_must_be_the_first_command_line_argument_6369": "Параметр \"--build\" должен быть первым аргументом командной строки.", + "Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES_5047": "Параметр isolatedModules можно использовать, только если указан параметр --module или если параметр target — ES2015 или выше.", + "Option_paths_cannot_be_used_without_specifying_baseUrl_option_5060": "Параметр paths невозможно использовать без указания параметра \"--baseUrl\".", + "Option_project_cannot_be_mixed_with_source_files_on_a_command_line_5042": "Параметр project не может быть указан вместе с исходными файлами в командной строке.", + "Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070": "Параметр \"--resolveJsonModule\" нельзя указать без стратегии разрешения модуля node.", + "Options_0_and_1_cannot_be_combined_6370": "Параметры \"{0}\" и \"{1}\" не могут использоваться одновременно.", + "Options_Colon_6027": "Параметры:", + "Output_directory_for_generated_declaration_files_6166": "Выходной каталог для создаваемых файлов объявления.", + "Output_file_0_from_project_1_does_not_exist_6309": "Выходной файл \"{0}\" из проекта \"{1}\" не существует", + "Output_file_0_has_not_been_built_from_source_file_1_6305": "Выходной файл \"{0}\" не создан из исходного файла \"{1}\".", + "Overload_signature_is_not_compatible_with_function_implementation_2394": "Сигнатура перегрузки несовместима с реализацией функции.", + "Overload_signatures_must_all_be_abstract_or_non_abstract_2512": "Сигнатуры перегрузки должны быть абстрактными или неабстрактными.", + "Overload_signatures_must_all_be_ambient_or_non_ambient_2384": "Все сигнатуры перегрузки должны быть либо внешними, либо не внешними.", + "Overload_signatures_must_all_be_exported_or_non_exported_2383": "Сигнатуры перегрузки должны быть экспортированы и не экспортированы.", + "Overload_signatures_must_all_be_optional_or_required_2386": "Все сигнатуры перегрузки должны быть либо необязательными, либо обязательными.", + "Overload_signatures_must_all_be_public_private_or_protected_2385": "Все сигнатуры перегрузки должны быть либо общими, либо закрытыми, либо защищенными.", + "Parameter_0_cannot_be_referenced_in_its_initializer_2372": "На параметр \"{0}\" невозможно ссылаться в его инициализаторе.", + "Parameter_0_implicitly_has_an_1_type_7006": "Параметр \"{0}\" неявно имеет тип \"{1}\".", + "Parameter_0_is_not_in_the_same_position_as_parameter_1_1227": "Параметр \"{0}\" находится в позиции, отличной от позиции параметра \"{1}\".", + "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4066": "Параметр \"{0}\" сигнатуры вызова из экспортированного интерфейса имеет или использует имя \"{1}\" из закрытого модуля \"{2}\".", + "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4067": "Параметр \"{0}\" сигнатуры вызова из экспортированного интерфейса имеет или использует закрытое имя \"{1}\".", + "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_can_4061": "Параметр \"{0}\" конструктора из экспортированного класса имеет или использует имя \"{1}\" из внешнего модуля {2}, но не может быть именован.", + "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2_4062": "Параметр \"{0}\" конструктора из экспортированного класса имеет или использует имя \"{1}\" из закрытого модуля \"{2}\".", + "Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1_4063": "Параметр \"{0}\" конструктора из экспортированного класса имеет или использует закрытое имя \"{1}\".", + "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_mod_4064": "Параметр \"{0}\" сигнатуры конструктора из экспортированного интерфейса имеет или использует имя \"{1}\" из закрытого модуля \"{2}\".", + "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4065": "Параметр \"{0}\" сигнатуры конструктора из экспортированного интерфейса имеет или использует закрытое имя \"{1}\".", + "Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4076": "Параметр \"{0}\" экспортированной функции имеет или использует имя \"{1}\" из внешнего модуля {2}, но не может быть именован.", + "Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2_4077": "Параметр \"{0}\" экспортированной функции имеет или использует имя \"{1}\" из закрытого модуля \"{2}\".", + "Parameter_0_of_exported_function_has_or_is_using_private_name_1_4078": "Параметр \"{0}\" экспортированной функции имеет или использует закрытое имя \"{1}\".", + "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4091": "Параметр \"{0}\" сигнатуры индекса из экспортированного интерфейса имеет или использует имя \"{1}\" из закрытого модуля \"{2}\".", + "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1_4092": "Параметр \"{0}\" сигнатуры индекса из экспортированного интерфейса имеет или использует закрытое имя \"{1}\".", + "Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4074": "Параметр \"{0}\" метода из экспортированного интерфейса имеет или использует имя \"{1}\" из закрытого модуля \"{2}\".", + "Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4075": "Параметр \"{0}\" метода из экспортированного интерфейса имеет или использует закрытое имя \"{1}\".", + "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_c_4071": "Параметр \"{0}\" общего метода из экспортированного класса имеет или использует имя \"{1}\" из внешнего модуля {2}, но не может быть именован.", + "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4072": "Параметр \"{0}\" общего метода из экспортированного класса имеет или использует имя \"{1}\" из закрытого модуля \"{2}\".", + "Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4073": "Параметр \"{0}\" общего метода из экспортированного класса имеет или использует закрытое имя \"{1}\".", + "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module__4068": "Параметр \"{0}\" общего статического метода из экспортированного класса имеет или использует имя \"{1}\" из внешнего модуля {2}, но не может быть именован.", + "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4069": "Параметр \"{0}\" общего статического метода из экспортированного класса имеет или использует имя \"{1}\" из закрытого модуля \"{2}\".", + "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4070": "Параметр \"{0}\" общего статического метода из экспортированного класса имеет или использует закрытое имя \"{1}\".", + "Parameter_cannot_have_question_mark_and_initializer_1015": "Параметр не может содержать вопросительный знак и инициализатор.", + "Parameter_declaration_expected_1138": "Ожидалось объявление параметра.", + "Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2_4036": "Тип параметра открытого метода задания \"{0}\" из экспортированного класса имеет или использует имя \"{1}\" из закрытого модуля \"{2}\".", + "Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_private_name_1_4037": "Тип параметра открытого метода задания \"{0}\" из экспортированного класса имеет или использует закрытое имя \"{1}\".", + "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_name_1_from_private_mod_4034": "Тип параметра открытого статического метода задания \"{0}\" из экспортированного класса имеет или использует имя \"{1}\" из закрытого модуля \"{2}\".", + "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1_4035": "Тип параметра открытого статического метода задания \"{0}\" из экспортированного класса имеет или использует закрытое имя \"{1}\".", + "Parse_in_strict_mode_and_emit_use_strict_for_each_source_file_6141": "Анализ в строгом режиме и создание директивы \"use strict\" для каждого исходного файла.", + "Pattern_0_can_have_at_most_one_Asterisk_character_5061": "Шаблон \"{0}\" может содержать не больше одного символа \"*\".", + "Prefix_0_with_an_underscore_90025": "Добавьте к \"{0}\" префикс — символ подчеркивания", + "Prefix_all_unused_declarations_with_where_possible_95025": "Добавить префикс \"_\" ко всем неиспользуемым объявлениям, где это возможно", + "Print_names_of_files_part_of_the_compilation_6155": "Печатать имена файлов, входящих в компиляцию.", + "Print_names_of_generated_files_part_of_the_compilation_6154": "Печатать имена создаваемых файлов, входящих в компиляцию.", + "Print_the_compiler_s_version_6019": "Печать версии компилятора.", + "Print_this_message_6017": "Напечатайте это сообщение.", + "Project_0_can_t_be_built_because_its_dependency_1_has_errors_6363": "Не удается собрать проект \"{0}\", так как его зависимость \"{1}\" содержит ошибки", + "Project_0_is_out_of_date_because_its_dependency_1_is_out_of_date_6353": "Проект \"{0}\" требует обновления, так как не обновлена его зависимость \"{1}\"", + "Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2_6350": "Проект \"{0}\" требует обновления, так как самые старые выходные данные \"{1}\" старше самых новых входных данных \"{2}\"", + "Project_0_is_out_of_date_because_output_file_1_does_not_exist_6352": "Проект \"{0}\" требует обновления, так как выходного файла \"{1}\" не существует", + "Project_0_is_up_to_date_6361": "Проект \"{0}\" не требует обновления", + "Project_0_is_up_to_date_because_newest_input_1_is_older_than_oldest_output_2_6351": "Проект \"{0}\" не требует обновления, так как самые новые входные данные \"{1}\" старее самых старых выходных данных \"{2}\"", + "Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies_6354": "Проект \"{0}\" не требует обновления с файлами .d.ts, взятыми из зависимостей проекта", + "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202": "Ссылки на проект не могут формировать циклический граф. Обнаружен цикл: {0}", + "Projects_in_this_build_Colon_0_6355": "Проекты в этой сборке: {0}", + "Projects_to_reference_6300": "Проекты для ссылки", + "Property_0_does_not_exist_on_const_enum_1_2479": "Свойство \"{0}\" не существует в перечислении const \"{1}\".", + "Property_0_does_not_exist_on_type_1_2339": "Свойство \"{0}\" не существует в типе \"{1}\".", + "Property_0_does_not_exist_on_type_1_Did_you_forget_to_use_await_2570": "Свойство \"{0}\" не существует в типе \"{1}\". Возможно, пропущено \"await\"?", + "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551": "Свойство \"{0}\" не существует в типе \"{1}\". Вы имели в виду \"{2}\"?", + "Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1_2546": "Свойство \"{0}\" содержит конфликтующие объявления и недоступно в типе \"{1}\".", + "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor_2564": "Свойство \"{0}\" не имеет инициализатора, и ему не гарантировано присваивание в конструкторе.", + "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033": "Свойство \"{0}\" неявно имеет тип \"все\", так как для его метода доступа get не задана заметка с типом возвращаемого значения.", + "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032": "Свойство \"{0}\" неявно имеет тип \"все\", так как для его метода доступа set не задана заметка с типом параметра.", + "Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2_2416": "Свойство \"{0}\" в типе \"{1}\" невозможно присвоить тому же свойству в базовом типе \"{2}\".", + "Property_0_in_type_1_is_not_assignable_to_type_2_2603": "Свойство \"{0}\" в типе \"{1}\" не может быть присвоено типу \"{2}\".", + "Property_0_is_declared_but_its_value_is_never_read_6138": "Свойство \"{0}\" объявлено, но его значение не было прочитано.", + "Property_0_is_incompatible_with_index_signature_2530": "Свойство \"{0}\" несовместимо с сигнатурой индекса.", + "Property_0_is_missing_in_type_1_2324": "Свойство \"{0}\" отсутствует в типе \"{1}\".", + "Property_0_is_optional_in_type_1_but_required_in_type_2_2327": "Свойство \"{0}\" является необязательным в типе \"{1}\" и обязательным в типе \"{2}\".", + "Property_0_is_private_and_only_accessible_within_class_1_2341": "Свойство \"{0}\" является закрытым и доступно только в классе \"{1}\".", + "Property_0_is_private_in_type_1_but_not_in_type_2_2325": "Свойство \"{0}\" является закрытым в типе \"{1}\" и не является таковым в типе \"{2}\".", + "Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1_2446": "Свойство \"{0}\" является защищенным и доступно только через экземпляр класса \"{1}\".", + "Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses_2445": "Свойство \"{0}\" является защищенным и доступно только в классе \"{1}\" и его подклассах.", + "Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2_2443": "Свойство \"{0}\" является защищенным, однако тип \"{1}\" не является классом, производным от \"{2}\".", + "Property_0_is_protected_in_type_1_but_public_in_type_2_2444": "Свойство \"{0}\" является защищенным в типе \"{1}\" и общим в типе \"{2}\".", + "Property_0_is_used_before_being_assigned_2565": "Свойство \"{0}\" используется перед присваиванием значения.", + "Property_0_of_JSX_spread_attribute_is_not_assignable_to_target_property_2606": "Свойство \"{0}\" атрибута расширения JSX не может быть назначено для целевого свойства.", + "Property_0_of_exported_class_expression_may_not_be_private_or_protected_4094": "Свойство \"{0}\" выражения экспортированного класса не может быть частным или защищенным.", + "Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4032": "Свойство \"{0}\" экспортированного интерфейса имеет или использует имя \"{1}\" из закрытого модуля \"{2}\".", + "Property_0_of_exported_interface_has_or_is_using_private_name_1_4033": "Свойство \"{0}\" экспортированного интерфейса имеет или использует закрытое имя \"{1}\".", + "Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2_2412": "Свойство \"{0}\" типа \"{1}\" нельзя назначить типу числового индекса \"{2}\".", + "Property_0_of_type_1_is_not_assignable_to_string_index_type_2_2411": "Свойство \"{0}\" типа \"{1}\" нельзя назначить типу строкового индекса \"{2}\".", + "Property_assignment_expected_1136": "Ожидалось присваивание свойства.", + "Property_destructuring_pattern_expected_1180": "Ожидался шаблон деструктурирования свойства.", + "Property_or_signature_expected_1131": "Ожидалось свойство или сигнатура.", + "Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_li_1328": "Значение свойства может быть только строковым или числовым литералом, True, False, Null, объектным литералом либо литералом массива.", + "Provide_full_support_for_iterables_in_for_of_spread_and_destructuring_when_targeting_ES5_or_ES3_6179": "Предоставление полной поддержки для итерируемых элементов в for-of, расширение и деструктуризация при выборе целевой платформы ES5 или ES3.", + "Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4098": "Открытый метод \"{0}\" экспортированного класса имеет или использует имя \"{1}\" из внешнего модуля {2}, но не может быть именован.", + "Public_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4099": "Открытый метод \"{0}\" экспортированного класса имеет или использует имя \"{1}\" из закрытого модуля \"{2}\".", + "Public_method_0_of_exported_class_has_or_is_using_private_name_1_4100": "Открытый метод \"{0}\" экспортированного класса имеет или использует закрытое имя \"{1}\".", + "Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_name_4029": "Общее свойство \"{0}\" экспортированного класса имеет или использует имя \"{1}\" из внешнего модуля {2}, но не может быть именовано.", + "Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4030": "Общее свойство \"{0}\" экспортированного класса имеет или использует имя \"{1}\" из закрытого модуля \"{2}\".", + "Public_property_0_of_exported_class_has_or_is_using_private_name_1_4031": "Общее свойство \"{0}\" экспортированного класса имеет или использует закрытое имя \"{1}\".", + "Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_4095": "Открытый статический метод \"{0}\" экспортированного класса имеет или использует имя \"{1}\" из внешнего модуля {2}, но не может быть именован.", + "Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4096": "Открытый статический метод \"{0}\" экспортированного класса имеет или использует имя \"{1}\" из закрытого модуля \"{2}\".", + "Public_static_method_0_of_exported_class_has_or_is_using_private_name_1_4097": "Открытый статический метод \"{0}\" экспортированного класса имеет или использует закрытое имя \"{1}\".", + "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot__4026": "Общее статическое свойство \"{0}\" экспортированного класса имеет или использует имя \"{1}\" из внешнего модуля {2}, но не может быть именовано.", + "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4027": "Общее статическое свойство \"{0}\" экспортированного класса имеет или использует имя \"{1}\" из закрытого модуля \"{2}\".", + "Public_static_property_0_of_exported_class_has_or_is_using_private_name_1_4028": "Общее статическое свойство \"{0}\" экспортированного класса имеет или использует закрытое имя \"{1}\".", + "Raise_error_on_expressions_and_declarations_with_an_implied_any_type_6052": "Вызывать ошибку в выражениях и объявлениях с подразумеваемым типом any.", + "Raise_error_on_this_expressions_with_an_implied_any_type_6115": "Вызвать ошибку в выражениях this с неявным типом any.", + "Redirect_output_structure_to_the_directory_6006": "Перенаправить структуру вывода в каталог.", + "Referenced_project_0_must_have_setting_composite_Colon_true_6306": "Указанный в ссылке проект \"{0}\" должен иметь следующее значение параметра composite: true.", + "Remove_all_unreachable_code_95051": "Удалить весь недостижимый код", + "Remove_all_unused_labels_95054": "Удалить все неиспользуемые метки", + "Remove_braces_from_arrow_function_95060": "Удалить скобки из стрелочной функции", + "Remove_declaration_for_Colon_0_90004": "Удалите объявление: \"{0}\"", + "Remove_destructuring_90009": "Удалить деструктурирование", + "Remove_import_from_0_90005": "Удалить импорт из \"{0}\"", + "Remove_unreachable_code_95050": "Удалить недостижимый код", + "Remove_unused_label_95053": "Удалить неиспользуемую метку", + "Remove_variable_statement_90010": "Удалить оператор с переменной", + "Replace_import_with_0_95015": "Замена импорта на \"{0}\".", + "Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "Сообщать об ошибке, если не все пути кода в функции возвращают значение.", + "Report_errors_for_fallthrough_cases_in_switch_statement_6076": "Сообщать об ошибках для случаев передачи управления в операторе switch.", + "Report_errors_in_js_files_8019": "Сообщать об ошибках в JS-файлах.", + "Report_errors_on_unused_locals_6134": "Сообщать об ошибках в неиспользованных локальных переменных.", + "Report_errors_on_unused_parameters_6135": "Сообщать об ошибках в неиспользованных параметрах.", + "Required_type_parameters_may_not_follow_optional_type_parameters_2706": "Обязательные параметры типа не могут следовать за необязательными параметрами типа.", + "Resolution_for_module_0_was_found_in_cache_from_location_1_6147": "Разрешение для модуля \"{0}\" найдено в кэше из расположения \"{1}\".", + "Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols_6195": "Разрешать \"keyof\" только в имена свойств со строковым значением (не числа и не символы).", + "Resolving_from_node_modules_folder_6118": "Идет разрешение из папки node_modules...", + "Resolving_module_0_from_1_6086": "======== Идет разрешение модуля \"{0}\" из \"{1}\". ========", + "Resolving_module_name_0_relative_to_base_url_1_2_6094": "Идет разрешение имени модуля \"{0}\" относительного к базовому URL-адресу \"{1}\" — \"{2}\".", + "Resolving_real_path_for_0_result_1_6130": "Разрешается реальный путь для \"{0}\"; результат: \"{1}\".", + "Resolving_type_reference_directive_0_containing_file_1_root_directory_2_6116": "======== Идет разрешение директивы ссылки на тип \"{0}\", содержащий файл \"{1}\", корневой каталог \"{2}\". ========", + "Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set_6123": "======== Идет разрешение директивы ссылки на тип \"{0}\", содержащий файл \"{1}\", корневой каталог не задан. ========", + "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1_6127": "======== Идет разрешение директивы ссылки на тип \"{0}\", содержащий файл не задан, корневой каталог \"{1}\". ========", + "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set_6128": "======== Идет разрешение директивы ссылки на тип \"{0}\", содержащий файл не задан, корневой каталог не задан. ========", + "Resolving_using_primary_search_paths_6117": "Идет разрешение с помощью первичных путей поиска...", + "Resolving_with_primary_search_path_0_6121": "Разрешается с помощью первичного пути поиска \"{0}\".", + "Rest_parameter_0_implicitly_has_an_any_type_7019": "Параметр rest \"{0}\" неявно имеет тип any[].", + "Rest_types_may_only_be_created_from_object_types_2700": "Типы REST можно создавать только из типов объектов.", + "Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4046": "Тип возвращаемого значения сигнатуры вызова из экспортированного интерфейса имеет или использует имя \"{0}\" из закрытого модуля \"{1}\".", + "Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0_4047": "Тип возвращаемого значения сигнатуры вызова из экспортированного интерфейса имеет или использует закрытое имя \"{0}\".", + "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_mod_4044": "Тип возвращаемого значения сигнатуры конструктора из экспортированного интерфейса имеет или использует имя \"{0}\" из закрытого модуля \"{1}\".", + "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0_4045": "Тип возвращаемого значения сигнатуры конструктора из экспортированного интерфейса имеет или использует закрытое имя \"{0}\".", + "Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class_2409": "Тип возвращаемого значения сигнатуры конструктора должен поддерживать присваивание типу экземпляра класса.", + "Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named_4058": "Тип возвращаемого значения экспортированной функции имеет или использует имя \"{0}\" из внешнего модуля {1}, но не может быть именован.", + "Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1_4059": "Тип возвращаемого значения экспортированной функции имеет или использует имя \"{0}\" из закрытого модуля \"{1}\".", + "Return_type_of_exported_function_has_or_is_using_private_name_0_4060": "Тип возвращаемого значения экспортированной функции имеет или использует закрытое имя \"{0}\".", + "Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4048": "Тип возвращаемого значения сигнатуры индекса из экспортированного интерфейса имеет или использует имя \"{0}\" из закрытого модуля \"{1}\".", + "Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0_4049": "Тип возвращаемого значения сигнатуры индекса из экспортированного интерфейса имеет или использует закрытое имя \"{0}\".", + "Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4056": "Тип возвращаемого значения метода из экспортированного интерфейса имеет или использует имя \"{0}\" из закрытого модуля \"{1}\".", + "Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0_4057": "Тип возвращаемого значения метода из экспортированного интерфейса имеет или использует закрытое имя \"{0}\".", + "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_4041": "Тип возвращаемого значения открытого метода получения \"{0}\" из экспортированного класса имеет или использует имя \"{1}\" из внешнего модуля {2}, но не может быть именован.", + "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2_4042": "Тип возвращаемого значения открытого метода получения \"{0}\" из экспортированного класса имеет или использует имя \"{1}\" из закрытого модуля \"{2}\".", + "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_private_name_1_4043": "Тип возвращаемого значения открытого метода получения \"{0}\" из экспортированного класса имеет или использует закрытое имя \"{1}\".", + "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_c_4053": "Тип возвращаемого значения общего метода из экспортированного класса имеет или использует имя \"{0}\" из внешнего модуля {1}, но не может быть именован.", + "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4054": "Тип возвращаемого значения общего метода из экспортированного класса имеет или использует имя \"{0}\" из закрытого модуля \"{1}\".", + "Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0_4055": "Тип возвращаемого значения общего метода из экспортированного класса имеет или использует закрытое имя \"{0}\".", + "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_external_modul_4038": "Тип возвращаемого значения открытого статического метода получения \"{0}\" из экспортированного класса имеет или использует имя \"{1}\" из внешнего модуля {2}, но не может быть именован.", + "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_4039": "Тип возвращаемого значения открытого статического метода получения \"{0}\" из экспортированного класса имеет или использует имя \"{1}\" из закрытого модуля \"{2}\".", + "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_private_name_1_4040": "Тип возвращаемого значения открытого статического метода получения \"{0}\" из экспортированного класса имеет или использует закрытое имя \"{1}\".", + "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module__4050": "Тип возвращаемого значения общего статического метода из экспортированного класса имеет или использует имя \"{0}\" из внешнего модуля {1}, но не может быть именован.", + "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4051": "Тип возвращаемого значения общего статического метода из экспортированного класса имеет или использует имя \"{0}\" из закрытого модуля \"{1}\".", + "Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0_4052": "Тип возвращаемого значения общего статического метода из экспортированного класса имеет или использует закрытое имя \"{0}\".", + "Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program_6184": "Повторно используются разрешения модулей, унаследованные из \"{0}\", так как они не изменились со старой программы.", + "Reusing_resolution_of_module_0_to_file_1_from_old_program_6183": "Повторно используется разрешение модуля \"{0}\" в файле \"{1}\" из старой программы.", + "Rewrite_all_as_indexed_access_types_95034": "Перезаписать все как типы с индексным доступом", + "Rewrite_as_the_indexed_access_type_0_90026": "Перезапишите как тип с индексным доступом \"{0}\"", + "Root_directory_cannot_be_determined_skipping_primary_search_paths_6122": "Корневой каталог невозможно определить, идет пропуск первичных путей поиска.", + "STRATEGY_6039": "СТРАТЕГИЯ", + "Scoped_package_detected_looking_in_0_6182": "Обнаружен пакет, относящийся к области; поиск в \"{0}\"", + "Setters_cannot_return_a_value_2408": "Методы доступа set не могут возвращать значения.", + "Show_all_compiler_options_6169": "Отображение всех параметров компилятора.", + "Show_diagnostic_information_6149": "Отображение сведений диагностики.", + "Show_verbose_diagnostic_information_6150": "Отображение подробных сведений диагностики.", + "Show_what_would_be_built_or_deleted_if_specified_with_clean_6367": "Показать компоненты, которые будут собраны (или удалены, если дополнительно указан параметр \"--clean\")", + "Signature_0_must_be_a_type_predicate_1224": "Сигнатура \"{0}\" должна быть предикатом типа.", + "Skip_type_checking_of_declaration_files_6012": "Пропустить проверку типа файлов объявления.", + "Skipping_build_of_project_0_because_its_dependency_1_has_errors_6362": "Сборка проекта \"{0}\" будет пропущена, так как его зависимость \"{1}\" содержит ошибки", + "Skipping_clean_because_not_all_projects_could_be_located_6371": "Очистка будет пропущена, так как не удалось найти некоторые проекты", + "Source_Map_Options_6175": "Параметры сопоставления источников", + "Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature_2382": "Специализированная сигнатура перегрузки не поддерживает назначение неспециализированной сигнатуре.", + "Specifier_of_dynamic_import_cannot_be_spread_element_1325": "Описатель динамического импорта не может быть элементом расширения.", + "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_or_ESNEXT_6015": "Укажите целевую версию ECMAScript: \"ES3\" (по умолчанию), \"ES5\", \"ES2015\", \"ES2016\", \"ES2017\", \"ES2018\" или \"ESNEXT\".", + "Specify_JSX_code_generation_Colon_preserve_react_native_or_react_6080": "Укажите вариант создания кода JSX: \"preserve\", \"react-native\" или \"react\".", + "Specify_library_files_to_be_included_in_the_compilation_6079": "Укажите файлы библиотек для включения в компиляцию.", + "Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext_6016": "Укажите вариант создания кода модуля: \"none\", \"commonjs\", \"amd\", \"system\", \"umd\", \"es2015\", или \"ESNext\".", + "Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6_6069": "Укажите стратегию разрешения модуля: node (Node.js) или classic (TypeScript pre-1.6).", + "Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h_6146": "Укажите функцию фабрики JSX, используемую при нацеливании на вывод JSX \"react\", например \"React.createElement\" или \"h\".", + "Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix_6060": "Укажите окончание последовательности строки для использования при порождении файлов: CRLF (DOS) или LF (UNIX).", + "Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations_6004": "Укажите расположение, в котором отладчик должен найти файлы TypeScript вместо исходных расположений.", + "Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations_6003": "Укажите расположение, в котором отладчик должен найти файлы карты, вместо созданных расположений.", + "Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir_6058": "Укажите корневой каталог входных файлов. Используйте его для управления структурой выходных каталогов с --outDir.", + "Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher_2472": "Оператор расширения в выражениях new доступен только при разработке для ECMAScript 5 и более поздних версий.", + "Spread_types_may_only_be_created_from_object_types_2698": "Типы расширения можно создавать только из типов объектов.", + "Starting_compilation_in_watch_mode_6031": "Запуск компиляции в режиме наблюдения...", + "Statement_expected_1129": "Ожидался оператор.", + "Statements_are_not_allowed_in_ambient_contexts_1036": "Операторы не разрешены в окружающих контекстах.", + "Static_members_cannot_reference_class_type_parameters_2302": "Статические элементы не могут ссылаться на параметры типов класса.", + "Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1_2699": "Статическое свойство \"{0}\" конфликтует со встроенным свойством \"Function.{0}\" функции-конструктора \"{1}\".", + "Strict_Type_Checking_Options_6173": "Параметры строгой проверки типов", + "String_literal_expected_1141": "Ожидался строковый литерал.", + "String_literal_with_double_quotes_expected_1327": "Ожидается строковый литерал с двойными кавычками.", + "Stylize_errors_and_messages_using_color_and_context_experimental_6073": "Стилизовать ошибки и сообщения с помощью цвета и контекста (экспериментальная функция).", + "Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_t_2717": "Последовательные объявления свойств должны иметь один и тот же тип. Свойство \"{0}\" должно иметь тип \"{1}\", но имеет здесь тип \"{2}\".", + "Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_t_2403": "Последующие объявления переменных должны иметь тот же тип. Переменная \"{0}\" должна иметь тип \"{1}\", однако имеет тип \"{2}\".", + "Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2_5064": "Подстановка \"{0}\" для шаблона \"{1}\" содержит неправильный тип, ожидается string, получен \"{2}\".", + "Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character_5062": "Подстановка \"{0}\" в шаблоне \"{1}\" может содержать не больше одного символа \"*\".", + "Substitutions_for_pattern_0_should_be_an_array_5063": "Подстановки для шаблона \"{0}\" должны быть массивом.", + "Substitutions_for_pattern_0_shouldn_t_be_an_empty_array_5066": "Замены для шаблона \"{0}\" не должны быть пустым массивом.", + "Successfully_created_a_tsconfig_json_file_6071": "Файл tsconfig.json успешно создан.", + "Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors_2337": "Вызовы super не разрешены вне конструкторов или во вложенных функциях внутри конструкторов.", + "Suppress_excess_property_checks_for_object_literals_6072": "Подавлять избыточные проверки свойств для объектных литералов.", + "Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures_6055": "Подавлять ошибки noImplicitAny для объектов индексирования, у которых отсутствуют сигнатуры индекса.", + "Symbol_reference_does_not_refer_to_the_global_Symbol_constructor_object_2470": "Ссылка Symbol не ссылается на глобальный объект конструктора Symbol.", + "Syntax_Colon_0_6023": "Синтаксис: {0}", + "The_0_operator_cannot_be_applied_to_type_symbol_2469": "Оператор \"{0}\" невозможно применить к типу Symbol.", + "The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead_2447": "Оператор \"{0}\" не разрешен для логических типов. Попробуйте использовать \"{1}\" вместо него.", + "The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead_2696": "Тип Object можно назначить малому количеству других типов. Возможно, вы хотели использовать тип any?", + "The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_stand_2496": "Нельзя ссылаться на объект типа arguments в стрелочной функции ES3 и ES5. Используйте стандартное выражение функции.", + "The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_usi_2522": "На объект arguments невозможно указать ссылку в асинхронной функции или методе в ES3 и ES5. Попробуйте использовать стандартную функцию или метод.", + "The_body_of_an_if_statement_cannot_be_the_empty_statement_1313": "Текст оператора if не может быть пустым.", + "The_character_set_of_the_input_files_6163": "Кодировка входных файлов.", + "The_containing_function_or_module_body_is_too_large_for_control_flow_analysis_2563": "Содержащая функция или текст модуля слишком велики для анализа потока управления.", + "The_current_host_does_not_support_the_0_option_5001": "Текущий узел не поддерживает параметр \"{0}\".", + "The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context_2714": "Выражение присваивания экспорта должно представлять собой идентификатор или полное имя в окружающем контексте.", + "The_files_list_in_config_file_0_is_empty_18002": "Список \"files\" в файле конфигурации \"{0}\" пуст.", + "The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback_1060": "Первым параметром метода then класса promise должен быть обратный вызов.", + "The_global_type_JSX_0_may_not_have_more_than_one_property_2608": "Глобальный тип \"JSX.{0}\" не может иметь больше одного свойства.", + "The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_option_1343": "Метасвойство \"import.meta\" разрешено только при использовании \"ESNext\" для параметров компилятора \"target\" и \"module\".", + "The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary_2527": "Выведенный тип \"{0}\" ссылается на недоступный тип \"{1}\". Требуется аннотация типа.", + "The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern_2491": "Левый операнд оператора for...in не может быть шаблоном деструктурирования.", + "The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation_2404": "Левый операнд оператора for...in не может использовать аннотацию типа.", + "The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access_2406": "В левой части оператора \"for...in\" должна быть переменная или доступ к свойству.", + "The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any_2405": "Левый операнд оператора for...in должен иметь тип string или any.", + "The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation_2483": "Левый операнд оператора for...of не может использовать аннотацию типа.", + "The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access_2487": "В левой части оператора \"for...of\" должна быть переменная или доступ к свойству.", + "The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type_2362": "Левый операнд арифметической операции должен иметь тип any, number или тип перечисления.", + "The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access_2364": "В левой части выражения назначения должна быть переменная или доступ к свойству.", + "The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol_2360": "Левый операнд выражения in должен иметь тип any, string, number или Symbol.", + "The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_paramete_2358": "Левый операнд выражения instanceof должен иметь тип any, тип объекта или параметр типа.", + "The_locale_used_when_displaying_messages_to_the_user_e_g_en_us_6156": "Языковой стандарт, который используется при отображении сообщений пользователю (например, en-us)", + "The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files_6136": "Максимальная глубина зависимостей для поиска в папке node_modules и загрузки файлов JavaScript.", + "The_operand_of_a_delete_operator_cannot_be_a_read_only_property_2704": "Операнд оператора delete не может быть свойством только для чтения.", + "The_operand_of_a_delete_operator_must_be_a_property_reference_2703": "Операнд оператора delete должен быть ссылкой на свойство.", + "The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access_2357": "Операнд оператора инкремента или декремента должен быть переменной или доступом к свойству.", + "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601": "Тип возвращаемого значения конструктора элемента JSX должен возвращать тип объекта.", + "The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any_1237": "Тип возвращаемого значения функции декоратора параметра должен быть либо void, либо any.", + "The_return_type_of_a_property_decorator_function_must_be_either_void_or_any_1236": "Тип возвращаемого значения функции декоратора свойства должен быть либо void, либо any.", + "The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_t_1058": "Тип возвращаемого значения асинхронной функции должен быть допустимым обещанием либо не должен содержать вызываемый элемент \"then\".", + "The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_1064": "Тип возвращаемого значения асинхронной функции или метода должен быть глобальным типом Promise.", + "The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_but_2407": "Правая часть оператора \"for…in\" должна иметь тип \"any\", тип объекта или быть параметром типа, однако указан тип \"{0}\".", + "The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type_2363": "Правый операнд арифметической операции должен иметь тип any, number или тип перечисления.", + "The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter_2361": "Правый операнд выражения \"in\" должен иметь тип \"any\", быть типом объекта или параметром типа.", + "The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_F_2359": "Правый операнд выражения instanceof должен иметь тип any или тип, который можно назначить типу интерфейса Function.", + "The_specified_path_does_not_exist_Colon_0_5058": "Указанный путь не существует: \"{0}\".", + "The_target_of_an_assignment_must_be_a_variable_or_a_property_access_2541": "Целевой объект назначения должен быть переменной или доступом к свойству.", + "The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access_2701": "Цель остального назначения объектов должна быть обращением к переменной или свойству.", + "The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1_2684": "Контекст this типа \"{0}\" не может быть назначен методу this типа \"{1}\".", + "The_this_types_of_each_signature_are_incompatible_2685": "Типы this каждой подписи несовместимы.", + "The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_typ_2453": "Аргумент типа для параметра типа \"{0}\" невозможно вывести из использования. Рассмотрите возможность явного указания аргументов типа.", + "The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value__2547": "Возвращаемый тип метода next() асинхронного итератора должен быть классом promise (для типа со свойством value).", + "The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property_2490": "Тип, возвращаемый методом \"next()\" итератора, должен содержать свойство value.", + "The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer_1189": "Объявление переменной оператора for...in не может содержать инициализатор.", + "The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer_1190": "Объявление переменной оператора for...of не может содержать инициализатор.", + "The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any_2410": "Оператор with не поддерживается. Все символы в блоке with получат тип any.", + "This_constructor_function_may_be_converted_to_a_class_declaration_80002": "Эту функцию конструктора можно преобразовать в объявление класса.", + "This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found_2354": "Для этого синтаксиса требуется импортированный вспомогательный объект, но найти модуль \"{0}\" не удается.", + "This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1_2343": "Для этого синтаксиса требуется импортированный вспомогательный объект \"{1}\", но у модуля \"{0}\" нет экспортированного элемента \"{1}\".", + "Trailing_comma_not_allowed_1009": "Завершающая запятая запрещена.", + "Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule_6153": "Транскомпиляция каждого файла как отдельного модуля (аналогично ts.transpileModule).", + "Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_mod_7035": "Попробуйте команду \"npm install @types/{0}\", если это возможно, или добавьте новый файл объявления (.d.ts), содержащий \"declare module '{0}';\"", + "Trying_other_entries_in_rootDirs_6110": "Попытка использовать другие записи в \"rootDirs\".", + "Trying_substitution_0_candidate_module_location_Colon_1_6093": "Выполняется попытка замены \"{0}\", расположение модуля кандидата: \"{1}\".", + "Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2_2493": "Кортеж типа \"{0}\" с длиной \"{1}\" невозможно назначить кортежу с длиной \"{2}\".", + "Type_0_cannot_be_converted_to_type_1_2352": "Тип \"{0}\" невозможно преобразовать в тип \"{1}\".", + "Type_0_cannot_be_used_as_an_index_type_2538": "Тип \"{0}\" невозможно использовать как тип индекса.", + "Type_0_cannot_be_used_to_index_type_1_2536": "Тип \"{0}\" не может использоваться для индексации типа \"{1}\".", + "Type_0_does_not_satisfy_the_constraint_1_2344": "Тип \"{0}\" не удовлетворяет ограничению \"{1}\".", + "Type_0_has_no_matching_index_signature_for_type_1_2537": "Тип \"{0}\" не содержит соответствующую сигнатуру индекса для типа \"{1}\".", + "Type_0_has_no_properties_in_common_with_type_1_2559": "У типа \"{0}\" нет общих свойств с типом \"{1}\".", + "Type_0_has_no_property_1_2460": "Тип \"{0}\" не содержит свойство \"{1}\".", + "Type_0_has_no_property_1_and_no_string_index_signature_2459": "Тип \"{0}\" не содержит свойство \"{1}\" и сигнатуру строкового индекса.", + "Type_0_is_not_a_constructor_function_type_2507": "Тип \"{0}\" не является типом функции конструктора.", + "Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Prom_1055": "Тип \"{0}\" не является допустимым типом возвращаемого значения асинхронной функции в ES5/ES3, так как он не ссылается на значение конструктора, совместимое с Promise.", + "Type_0_is_not_an_array_type_2461": "Тип \"{0}\" не является типом массива.", + "Type_0_is_not_an_array_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators_2568": "Тип \"{0}\" не является типом массива. Используйте параметр компилятора \"--downlevelIteration\", чтобы разрешить итерацию итераторов.", + "Type_0_is_not_an_array_type_or_a_string_type_2495": "Тип \"{0}\" не является типом массива или типом строки.", + "Type_0_is_not_an_array_type_or_a_string_type_Use_compiler_option_downlevelIteration_to_allow_iterati_2569": "Тип \"{0}\" не является типом строки или массива. Используйте параметр компилятора \"--downlevelIteration\", чтобы разрешить итерацию итераторов.", + "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549": "{0} не является типом массива или строки или в нем нет метода [Symbol.iterator](), который возвращает итератор.", + "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548": "{0} не является типом массива или в нем нет метода [Symbol.iterator](), который возвращает итератор.", + "Type_0_is_not_assignable_to_type_1_2322": "Тип \"{0}\" не может быть назначен для типа \"{1}\".", + "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_2719": "Тип \"{0}\" невозможно присвоить типу \"{1}\". Существует два разных типа с таким именем, но они не связаны.", + "Type_0_is_not_comparable_to_type_1_2678": "Тип \"{0}\" невозможно сравнить с типом \"{1}\".", + "Type_0_is_not_generic_2315": "Тип \"{0}\" не является универсальным.", + "Type_0_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator_2504": "Тип \"{0}\" должен иметь метод \"[Symbol.asyncIterator]()\", который возвращает асинхронный итератор.", + "Type_0_must_have_a_Symbol_iterator_method_that_returns_an_iterator_2488": "Тип \"{0}\" должен иметь метод \"[Symbol.iterator]()\", который возвращает итератор.", + "Type_0_provides_no_match_for_the_signature_1_2658": "Тип \"{0}\" не предоставляет соответствия для сигнатуры \"{1}\".", + "Type_0_recursively_references_itself_as_a_base_type_2310": "Тип \"{0}\" рекурсивно ссылается сам на себя как на базовый тип.", + "Type_alias_0_circularly_references_itself_2456": "Псевдоним типа \"{0}\" циклически ссылается на себя.", + "Type_alias_name_cannot_be_0_2457": "Псевдоним типа не может иметь имя \"{0}\".", + "Type_annotation_cannot_appear_on_a_constructor_declaration_1093": "Аннотация типа не может содержаться в объявлении конструктора.", + "Type_argument_candidate_1_is_not_a_valid_type_argument_because_it_is_not_a_supertype_of_candidate_0_2455": "Кандидат аргумента типа \"{1}\" является недопустимым аргументом, так как это не супертип кандидата \"{0}\".", + "Type_argument_expected_1140": "Ожидался аргумент типа.", + "Type_argument_list_cannot_be_empty_1099": "Список аргументов типа не может быть пустым.", + "Type_arguments_cannot_be_used_here_1342": "Использовать аргументы типа здесь недопустимо.", + "Type_declaration_files_to_be_included_in_compilation_6124": "Файлы объявления типа, включаемые в компиляцию.", + "Type_expected_1110": "Ожидался тип.", + "Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method_1062": "На тип есть прямые или непрямые ссылки в обратном вызове выполнения собственного метода then.", + "Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member_1320": "Тип операнда \"await\" должен быть допустимым обещанием либо не должен содержать вызываемый элемент \"then\".", + "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322": "Тип элементов итерации для операнда \"yield*\" должен быть допустимым обещанием либо не должен содержать вызываемый элемент \"then\".", + "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321": "Тип операнда \"yield\" в асинхронном генераторе должен быть допустимым обещанием либо не должен содержать вызываемый элемент \"then\".", + "Type_parameter_0_has_a_circular_constraint_2313": "Параметр типа \"{0}\" содержит циклическое ограничение.", + "Type_parameter_0_has_a_circular_default_2716": "Параметр типа \"{0}\" по умолчанию является циклическим.", + "Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4008": "Параметр типа \"{0}\" сигнатуры вызова из экспортированного интерфейса имеет или использует закрытое имя \"{1}\".", + "Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4006": "Параметр типа \"{0}\" сигнатуры конструктора из экспортированного интерфейса имеет или использует закрытое имя \"{1}\".", + "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002": "Параметр типа \"{0}\" экспортированного класса имеет или использует закрытое имя \"{1}\".", + "Type_parameter_0_of_exported_function_has_or_is_using_private_name_1_4016": "Параметр типа \"{0}\" экспортированной функции имеет или использует закрытое имя \"{1}\".", + "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004": "Параметр типа \"{0}\" экспортированного интерфейса имеет или использует закрытое имя \"{1}\".", + "Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1_4083": "Параметр типа \"{0}\" экспортированного псевдонима типа имеет или использует закрытое имя \"{1}\".", + "Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4014": "Параметр типа \"{0}\" метода из экспортированного интерфейса имеет или использует закрытое имя \"{1}\".", + "Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4012": "Параметр типа \"{0}\" общего метода из экспортированного класса имеет или использует закрытое имя \"{1}\".", + "Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4010": "Параметр типа \"{0}\" общего статического метода из экспортированного класса имеет или использует закрытое имя \"{1}\".", + "Type_parameter_declaration_expected_1139": "Ожидалось объявление параметра типа.", + "Type_parameter_list_cannot_be_empty_1098": "Список параметров типа не может быть пустым.", + "Type_parameter_name_cannot_be_0_2368": "Параметр типа не может иметь имя \"{0}\".", + "Type_parameters_cannot_appear_on_a_constructor_declaration_1092": "Параметры типов не могут содержаться в объявлении конструктора.", + "Type_predicate_0_is_not_assignable_to_1_1226": "Предикат типов \"{0}\" не может быть назначен для \"{1}\".", + "Type_reference_directive_0_was_not_resolved_6120": "======== Директива ссылки на тип \"{0}\" не разрешена. ========", + "Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2_6119": "======== Директива ссылки на тип \"{0}\" успешно разрешена в \"{1}\", первичный объект: {2}. ========", + "Types_have_separate_declarations_of_a_private_property_0_2442": "Типы имеют раздельные объявления закрытого свойства \"{0}\".", + "Types_of_parameters_0_and_1_are_incompatible_2328": "Типы параметров \"{0}\" и \"{1}\" несовместимы.", + "Types_of_property_0_are_incompatible_2326": "Типы свойства \"{0}\" несовместимы.", + "Unable_to_open_file_0_6050": "Не удается открыть файл \"{0}\".", + "Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression_1238": "Не удается разрешить сигнатуру декоратора класса при вызове в качестве выражения.", + "Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression_1241": "Не удается разрешить сигнатуру декоратора метода при вызове в качестве выражения.", + "Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression_1239": "Не удается разрешить сигнатуру декоратора параметра при вызове в качестве выражения.", + "Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression_1240": "Не удается разрешить сигнатуру декоратора свойства при вызове в качестве выражения.", + "Unexpected_end_of_text_1126": "Неожиданный конец текста.", + "Unexpected_token_1012": "Неожиданный токен.", + "Unexpected_token_A_constructor_method_accessor_or_property_was_expected_1068": "Неожиданный токен. Ожидался конструктор, метод, метод доступа или свойство.", + "Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces_1069": "Непредвиденная лексема. Ожидалось имя параметра типа без фигурных скобок.", + "Unexpected_token_expected_1179": "Неожиданный токен. Ожидался символ \"{\".", + "Unknown_compiler_option_0_5023": "Неизвестный параметр компилятора \"{0}\".", + "Unknown_option_excludes_Did_you_mean_exclude_6114": "Неизвестный параметр excludes. Возможно, вы имели в виду exclude?", + "Unknown_type_acquisition_option_0_17010": "Неизвестный параметр получения типа, \"{0}\".", + "Unreachable_code_detected_7027": "Обнаружен недостижимый код.", + "Unsupported_locale_0_6049": "Неподдерживаемый языковой стандарт \"{0}\".", + "Unterminated_Unicode_escape_sequence_1199": "Незавершенная escape-последовательность Юникода.", + "Unterminated_quoted_string_in_response_file_0_6045": "Незавершенная строка в кавычках в файле ответов \"{0}\".", + "Unterminated_regular_expression_literal_1161": "Незавершенный литерал регулярного выражения.", + "Unterminated_string_literal_1002": "Строковый литерал без признака конца.", + "Unterminated_template_literal_1160": "Незавершенный литерал шаблона.", + "Untyped_function_calls_may_not_accept_type_arguments_2347": "Вызовы функций без типов не могут принимать аргументы типов.", + "Unused_label_7028": "Неиспользуемая метка.", + "Updating_output_timestamps_of_project_0_6359": "Обновление меток времени в выходных данных проекта \"{0}\"...", + "Use_synthetic_default_member_95016": "Используйте искусственный элемент \"default\".", + "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494": "Использование строки для оператора for...of поддерживается только в ECMAScript 5 и более поздних версиях.", + "VERSION_6036": "ВЕРСИЯ", + "Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it_2560": "Значение типа \"{0}\" не имеет общих свойств со значением типа \"{1}\". Вы хотели вызвать его?", + "Value_of_type_0_is_not_callable_Did_you_mean_to_include_new_2348": "Значение типа \"{0}\" не может вызываться. Вы хотели использовать new?", + "Variable_0_implicitly_has_an_1_type_7005": "Переменная \"{0}\" неявно имеет тип \"{1}\".", + "Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined_7034": "Переменная \"{0}\" неявным образом получает тип \"{1}\" в некоторых местах, где ее тип невозможно определить.", + "Variable_0_is_used_before_being_assigned_2454": "Переменная \"{0}\" используется перед назначением.", + "Variable_declaration_expected_1134": "Ожидалось объявление переменной.", + "Variable_declaration_list_cannot_be_empty_1123": "Список объявлений переменной не может быть пустым.", + "Version_0_6029": "Версия {0}", + "Watch_input_files_6005": "Просмотр входных файлов.", + "Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen_6191": "Сохранять ли устаревшие выходные данные консоли в режиме просмотра вместо очистки экрана.", + "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001": "Невозможно переименовать элементы, определенные в стандартной библиотеке TypeScript.", + "You_cannot_rename_this_element_8000": "Этот элемент переименовать нельзя.", + "_0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write__1329": "\"{0}\" принимает слишком мало аргументов для использования в качестве декоратора. Вы хотели сначала вызвать его и записать \"@{0}()\"?", + "_0_are_specified_twice_The_attribute_named_0_will_be_overwritten_2710": "\"{0}\" указаны дважды. Атрибут \"{0}\" будет перезаписан.", + "_0_can_only_be_used_in_a_ts_file_8009": "\"{0}\" может использоваться только в TS-файле.", + "_0_expected_1005": "Ожидалось \"{0}\".", + "_0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_reference_7023": "\"{0}\" неявно имеет тип возвращаемого значения any, так как у него нет заметки с типом возвращаемого значения, а также на него прямо или косвенно указана ссылка в одном из его выражений return.", + "_0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or__7022": "\"{0}\" неявно имеет тип any, так как отсутствует аннотация типа и на \"{0}\" есть прямые или непрямые ссылки в его собственном инициализаторе.", + "_0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible_2692": "\"{0}\" является примитивом, но \"{1}\" — объект оболочки. Предпочтительно использовать \"{0}\" по мере возможности.", + "_0_is_declared_but_its_value_is_never_read_6133": "Свойство \"{0}\" объявлено, но его значение не было прочитано.", + "_0_is_declared_but_never_used_6196": "\"{0}\" объявлен, но никогда не использовался.", + "_0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2_17012": "\"{0}\" не является допустимым метасвойством для ключевого слова \"{1}\". Вы имели в виду \"{2}\"?", + "_0_is_referenced_directly_or_indirectly_in_its_own_base_expression_2506": "На \"{0}\" есть прямые или непрямые ссылки в его собственном базовом выражении.", + "_0_is_referenced_directly_or_indirectly_in_its_own_type_annotation_2502": "На \"{0}\" есть прямые или непрямые ссылки в его собственной аннотации типа.", + "_0_list_cannot_be_empty_1097": "Список \"{0}\" не может быть пустым.", + "_0_modifier_already_seen_1030": "Модификатор \"{0}\" уже встречался.", + "_0_modifier_cannot_appear_on_a_class_element_1031": "Модификатор \"{0}\" не может использоваться в элементе класса.", + "_0_modifier_cannot_appear_on_a_constructor_declaration_1089": "Модификатор \"{0}\" не может содержаться в объявлении конструктора.", + "_0_modifier_cannot_appear_on_a_data_property_1043": "Модификатор \"{0}\" не может содержаться в свойстве данных.", + "_0_modifier_cannot_appear_on_a_module_or_namespace_element_1044": "Модификатор \"{0}\" не может отображаться в модуле или элементе пространства имен.", + "_0_modifier_cannot_appear_on_a_parameter_1090": "Модификатор \"{0}\" не может содержаться в параметре.", + "_0_modifier_cannot_appear_on_a_type_member_1070": "Модификатор \"{0}\" не может отображаться в элементе типа.", + "_0_modifier_cannot_appear_on_an_index_signature_1071": "Модификатор \"{0}\" не может отображаться в сигнатуре индекса.", + "_0_modifier_cannot_be_used_here_1042": "Модификатор \"{0}\" не может использоваться здесь.", + "_0_modifier_cannot_be_used_in_an_ambient_context_1040": "Модификатор \"{0}\" не может использоваться в окружающем контексте.", + "_0_modifier_cannot_be_used_with_1_modifier_1243": "Модификатор \"{0}\" не может использоваться с модификатором \"{1}\".", + "_0_modifier_cannot_be_used_with_a_class_declaration_1041": "Модификатор \"{0}\" не может использоваться с объявлением класса.", + "_0_modifier_must_precede_1_modifier_1029": "Модификатор \"{0}\" должен предшествовать модификатору \"{1}\".", + "_0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here_2702": "\"{0}\" относится только к типу, а здесь используется как пространство имен.", + "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_2693": "\"{0}\" относится только к типу, но используется здесь как значение.", + "_0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead_2686": "\"{0}\" ссылается на глобальную переменную UMD, но текущий файл является модулем. Рекомендуется добавить импорт.", + "_0_tag_already_specified_1223": "Тег \"{0}\" уже указан.", + "_0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag_1253": "Невозможно использовать тег \"{0}\" независимо в качестве тега верхнего уровня JSDoc.", + "_0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type_7010": "\"{0}\", у которого нет аннотации типа возвращаемого значения, неявно имеет тип возвращаемого значения \"{1}\".", + "abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration_1242": "Модификатор abstract может отображаться только в объявлении класса, метода или свойства.", + "await_expression_is_only_allowed_within_an_async_function_1308": "Выражение await разрешено использовать только в асинхронной функции.", + "await_expressions_cannot_be_used_in_a_parameter_initializer_2524": "Выражения await не могут быть использованы в инициализаторе параметра.", + "baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1_6106": "Параметр \"baseUrl\" имеет значение \"{0}\", это значение используется для разрешения безотносительного имени модуля \"{1}\".", + "can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment_1312": "\"=\" можно использовать только в свойстве объектного литерала в назначении деструктурирования.", + "case_or_default_expected_1130": "Ожидалось case или default.", + "class_expressions_are_not_currently_supported_9003": "Выражения class в настоящий момент не поддерживаются.", + "const_declarations_can_only_be_declared_inside_a_block_1156": "Объявления const можно задать только в блоке.", + "const_declarations_must_be_initialized_1155": "Объявления \"const\" должны быть инициализированы.", + "const_enum_member_initializer_was_evaluated_to_a_non_finite_value_2477": "Инициализатор элементов перечисления const был вычислен в неконечное значение.", + "const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN_2478": "Инициализатор элементов перечисления const был вычислен в запрещенное значение NaN.", + "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475": "Перечисления const можно использовать только в выражениях доступа к свойству или индексу, а также в правой части объявления импорта, присваивания экспорта или запроса типа.", + "delete_cannot_be_called_on_an_identifier_in_strict_mode_1102": "Невозможно вызвать оператор delete с идентификатором в строгом режиме.", + "delete_this_Project_0_is_up_to_date_because_it_was_previously_built_6360": "удалить это — проект \"{0}\" не требует обновления, так как был собран ранее", + "enum_declarations_can_only_be_used_in_a_ts_file_8015": "Объявления перечислений можно использовать только в TS-файле.", + "export_can_only_be_used_in_a_ts_file_8003": "Элемент \"export=\" может использоваться только в TS-файле.", + "export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always__2668": "Модификатор export невозможно применить к неоднозначным модулям и улучшениям модулей, так как они всегда видимые.", + "extends_clause_already_seen_1172": "Предложение extends уже существует.", + "extends_clause_must_precede_implements_clause_1173": "Предложение extends должно предшествовать предложению implements.", + "extends_clause_of_exported_class_0_has_or_is_using_private_name_1_4020": "Предложение extends экспортированного класса \"{0}\" имеет или использует закрытое имя \"{1}\".", + "extends_clause_of_exported_interface_0_has_or_is_using_private_name_1_4022": "Предложение extends экспортированного интерфейса \"{0}\" имеет или использует закрытое имя \"{1}\".", + "file_6025": "файл", + "get_and_set_accessor_must_have_the_same_this_type_2682": "Методы доступа \"get\" и \"set\" должны иметь одинаковый тип \"this\".", + "get_and_set_accessor_must_have_the_same_type_2380": "Методы доступа get и set должны иметь одинаковый тип.", + "implements_clause_already_seen_1175": "Предложение implements уже существует.", + "implements_clauses_can_only_be_used_in_a_ts_file_8005": "Предложения implements могут использоваться только в TS-файле.", + "import_can_only_be_used_in_a_ts_file_8002": "Элемент \"import ... =\" может использоваться только в TS-файле.", + "infer_declarations_are_only_permitted_in_the_extends_clause_of_a_conditional_type_1338": "Объявления \"infer\" допустимы только в предложении \"extends\" условного типа.", + "interface_declarations_can_only_be_used_in_a_ts_file_8006": "Объявления интерфейсов могут использоваться только в TS-файле.", + "let_declarations_can_only_be_declared_inside_a_block_1157": "Объявления let можно задать только в блоке.", + "let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations_2480": "Не допускается использование let в качестве имени в объявлениях let или const.", + "module_declarations_can_only_be_used_in_a_ts_file_8007": "Объявления модулей могут использоваться только в TS-файле.", + "new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead_1150": "Оператор new T[] не может использоваться для создания массива. Используйте вместо него \"new Array()\".", + "new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type_7009": "Выражение new, у цели которого нет сигнатуры конструктора, неявно имеет тип any.", + "non_null_assertions_can_only_be_used_in_a_ts_file_8013": "Утверждения для проверки на null могут использоваться только в TS-файле.", + "options_6024": "параметры", + "or_expected_1144": "Ожидалось \"{\" или \";\".", + "package_json_does_not_have_a_0_field_6100": "В package.json нет поля \"{0}\".", + "package_json_has_0_field_1_that_references_2_6101": "package.json содержит поле \"{0}\" \"{1}\", которое ссылается на \"{2}\".", + "parameter_modifiers_can_only_be_used_in_a_ts_file_8012": "Модификаторы параметров могут использоваться только в TS-файле.", + "paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0_6091": "Параметр paths указан, идет поиск шаблона, соответствующего имени модуля \"{0}\".", + "readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024": "Модификатор readonly может отображаться только в объявлении свойства или сигнатуре индекса.", + "require_call_may_be_converted_to_an_import_80005": "Вызов \"require\" можно преобразовать в \"import\".", + "rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107": "Параметр \"rootDirs\" задан; он используется для разрешения относительного имени модуля \"{0}\".", + "super_can_only_be_referenced_in_a_derived_class_2335": "Ссылка на super может указываться только в производном классе.", + "super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions_2660": "На super можно ссылаться только в элементах производных классов или литеральных выражениях объекта.", + "super_cannot_be_referenced_in_a_computed_property_name_2466": "Не допускается ссылка на super в имени вычисляемого свойства.", + "super_cannot_be_referenced_in_constructor_arguments_2336": "На super невозможно ссылаться в аргументах конструктора.", + "super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_highe_2659": "super допускается только в элементах литеральных выражений объекта, если параметр target — ES2015 или выше.", + "super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class_17011": "Перед тем, как получить доступ к свойству \"super\" в конструкторе производного класса, необходимо вызвать \"super\".", + "super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class_17009": "super следует вызывать перед получением доступа к this в конструкторе производного класса.", + "super_must_be_followed_by_an_argument_list_or_member_access_1034": "После super должен идти список аргументов или доступ к элементу.", + "super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_der_2338": "Доступ к свойству super разрешен только в конструкторе, функции-элементе или методе доступа к элементам производного класса.", + "this_cannot_be_referenced_in_a_computed_property_name_2465": "На this не может указывать ссылка в имени вычисляемого свойства.", + "this_cannot_be_referenced_in_a_module_or_namespace_body_2331": "На this не могут указывать ссылки в теле модуля или пространства имен.", + "this_cannot_be_referenced_in_a_static_property_initializer_2334": "На this не могут указывать ссылки в инициализаторе статического свойства.", + "this_cannot_be_referenced_in_constructor_arguments_2333": "На this не могут указывать ссылки в аргументах конструктора.", + "this_cannot_be_referenced_in_current_location_2332": "На this не могут указывать ссылки в текущем расположении.", + "this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_2683": "this неявно содержит тип any, так как он не имеет аннотации типа.", + "type_aliases_can_only_be_used_in_a_ts_file_8008": "Псевдонимы типов могут использоваться только в TS-файле.", + "type_arguments_can_only_be_used_in_a_ts_file_8011": "Аргументы типов могут использоваться только в TS-файле.", + "type_assertion_expressions_can_only_be_used_in_a_ts_file_8016": "Выражения утверждения типа могут использоваться только в TS-файле.", + "type_parameter_declarations_can_only_be_used_in_a_ts_file_8004": "Объявления параметров типа могут использоваться только в TS-файле.", + "types_can_only_be_used_in_a_ts_file_8010": "Типы могут использоваться только в TS-файле.", + "unique_symbol_types_are_not_allowed_here_1335": "Типы \"unique symbol\" здесь запрещены.", + "unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement_1334": "Типы \"unique symbol\" разрешены только у переменных в операторах с переменными.", + "unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name_1333": "Типы \"unique symbol\" невозможно использовать в объявлении переменной с именем привязки.", + "with_statements_are_not_allowed_in_an_async_function_block_1300": "Операторы with не разрешено использовать в блоке асинхронной функции.", + "with_statements_are_not_allowed_in_strict_mode_1101": "Операторы with не разрешено использовать в строгом режиме.", + "yield_expressions_cannot_be_used_in_a_parameter_initializer_2523": "Выражения yield не могут быть использованы в инициализаторе параметра." +} \ No newline at end of file diff --git a/node_modules/typescript/lib/tr/diagnosticMessages.generated.json b/node_modules/typescript/lib/tr/diagnosticMessages.generated.json new file mode 100644 index 0000000..284c223 --- /dev/null +++ b/node_modules/typescript/lib/tr/diagnosticMessages.generated.json @@ -0,0 +1,1101 @@ +{ + "A_0_modifier_cannot_be_used_with_an_import_declaration_1079": "Bir '{0}' değiştiricisi, içeri aktarma bildirimiyle birlikte kullanılamaz.", + "A_0_modifier_cannot_be_used_with_an_interface_declaration_1045": "Bir '{0}' değiştiricisi, arabirim bildirimiyle birlikte kullanılamaz.", + "A_0_parameter_must_be_the_first_parameter_2680": "Bir '{0}' parametresi ilk parametre olmalıdır.", + "A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature_2463": "Uygulama imzasındaki bir bağlama deseni parametresi isteğe bağlı olamaz.", + "A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement_1105": "'break' deyimi yalnızca bir kapsayan yineleme veya switch deyimi içinde kullanılabilir.", + "A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement_1116": "'break' deyimi, yalnızca kapsayan deyimin etiketine atlayabilir.", + "A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments_2500": "Bir sınıf, isteğe bağlı tür bağımsız değişkenleri ile yalnızca bir tanımlayıcıyı/tam adı uygulayabilir.", + "A_class_declaration_without_the_default_modifier_must_have_a_name_1211": "'default' değiştiricisi olmayan bir sınıf bildiriminin adı olmalıdır.", + "A_class_may_only_extend_another_class_2311": "Bir sınıf yalnızca başka bir sınıfı genişletebilir.", + "A_class_may_only_implement_another_class_or_interface_2422": "Bir sınıf yalnızca başka bir sınıfı veya arabirimi uygulayabilir.", + "A_class_member_cannot_have_the_0_keyword_1248": "Bir sınıf üyesi '{0}' anahtar kelimesini içeremez.", + "A_comma_expression_is_not_allowed_in_a_computed_property_name_1171": "Hesaplanan özellik adında virgül ifadesine izin verilmez.", + "A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type_2467": "Hesaplanan özellik adı, kapsayan türündeki bir tür parametresine başvuramaz.", + "A_computed_property_name_in_a_class_property_declaration_must_refer_to_an_expression_whose_type_is_a_1166": "Bir sınıf özelliği bildirimindeki hesaplanan özellik adı, sabit değer türündeki veya 'unique symbol' türündeki bir ifadeye başvurmalıdır.", + "A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_ty_1168": "Bir metot aşırı yüklemesindeki hesaplanan özellik adı, sabit değer türündeki veya 'unique symbol' türündeki bir ifadeye başvurmalıdır.", + "A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type__1170": "Bir tür sabit değerindeki hesaplanan özellik adı, sabit değer türündeki veya 'unique symbol' türündeki bir ifadeye başvurmalıdır.", + "A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_t_1165": "Bir çevresel bağlamdaki hesaplanan özellik adı, sabit değer türündeki veya 'unique symbol' türündeki bir ifadeye başvurmalıdır.", + "A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_1169": "Bir arabirimdeki hesaplanan özellik adı, sabit değer türündeki veya 'unique symbol' türündeki bir ifadeye başvurmalıdır.", + "A_computed_property_name_must_be_of_type_string_number_symbol_or_any_2464": "Hesaplanan özellik adı 'string', 'number', 'symbol' veya 'any' türünde olmalıdır.", + "A_computed_property_name_of_the_form_0_must_be_of_type_symbol_2471": "'{0}' biçimindeki hesaplanan özellik adı 'symbol' türünde olmalıdır.", + "A_const_enum_member_can_only_be_accessed_using_a_string_literal_2476": "const numaralandırma üyesine yalnızca dize sabit değeri kullanılarak erişilebilir.", + "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_1254": "Çevresel bağlamdaki 'const' başlatıcısı bir dize veya sayısal sabit değer olmalıdır.", + "A_constructor_cannot_contain_a_super_call_when_its_class_extends_null_17005": "Sınıfı 'null' değerini aşan bir oluşturucu 'super' çağrısını içeremez.", + "A_constructor_cannot_have_a_this_parameter_2681": "Bir oluşturucu 'this' parametresini içeremez.", + "A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement_1104": "'continue' deyimi yalnızca bir kapsayan yineleme deyimi içinde kullanılabilir.", + "A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement_1115": "'continue' deyimi, yalnızca kapsayan yineleme deyiminin etiketine atlayabilir.", + "A_declare_modifier_cannot_be_used_in_an_already_ambient_context_1038": "Çevresel bağlamda 'declare' değiştiricisi kullanılamaz.", + "A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file_1046": "Bir .d.ts dosyasındaki en üst düzey bildirim için 'declare' değiştiricisi gerekir.", + "A_decorator_can_only_decorate_a_method_implementation_not_an_overload_1249": "Dekoratörler yalnızca metot uygulaması dekore edebilir; aşırı yüklemeleri dekore edemez.", + "A_default_clause_cannot_appear_more_than_once_in_a_switch_statement_1113": "'default' yan tümcesi, 'switch' deyiminde birden fazla kez bulunamaz.", + "A_default_export_can_only_be_used_in_an_ECMAScript_style_module_1319": "Varsayılan dışarı aktarma, yalnızca ECMAScript stili bir modülde kullanılabilir.", + "A_definite_assignment_assertion_is_not_permitted_in_this_context_1255": "Bu bağlamda '!' belirli atama onayına izin verilmez.", + "A_destructuring_declaration_must_have_an_initializer_1182": "Yok etme bildiriminin bir başlatıcısı olmalıdır.", + "A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declarat_2712": "ES5/ES3 içindeki dinamik içeri aktarma çağrısı, 'Promise' oluşturucusu gerektirir. 'Promise' oluşturucusu için bir bildiriminizin olduğundan veya `--lib` seçeneğinize 'ES2015' eklediğinizden emin olun.", + "A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES20_2711": "Dinamik içeri aktarma çağrısı, 'Promise' döndürür. Bir 'Promise' bildiriminiz olduğundan emin olun veya `--lib` seçeneğinize 'ES2015' ekleyin.", + "A_file_cannot_have_a_reference_to_itself_1006": "Bir dosya kendine başvuramaz.", + "A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator_1103": "Bir 'for-await-of' deyimine yalnızca zaman uyumsuz işlev veya zaman uyumsuz oluşturucu içinde izin verilir.", + "A_function_returning_never_cannot_have_a_reachable_end_point_2534": "'never' döndüren bir işlev, erişilebilir bir uç noktaya sahip olamaz.", + "A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void_2679": "'New' anahtar kelimesiyle çağrılan bir işlev, 'void' olan bir 'this' türüne sahip olamaz.", + "A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value_2355": "Bildirilen türü 'void' veya 'any' olmayan işlevin bir değer döndürmesi gerekir.", + "A_generator_cannot_have_a_void_type_annotation_2505": "Bir oluşturucu 'void' türündeki bir ek açıklamaya sahip olamaz.", + "A_get_accessor_cannot_have_parameters_1054": "Bir 'get' erişimcisi parametrelere sahip olamaz.", + "A_get_accessor_must_return_a_value_2378": "'get' erişimcisinin bir değer döndürmesi gerekir.", + "A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_memb_2651": "Sabit listesi bildirimindeki bir üye başlatıcısı, diğer sabit listelerinde tanımlanan üyeler dahil olmak üzere kendinden sonra bildirilen üyelere başvuramaz.", + "A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any_2545": "Mixin sınıfının 'any[]' türünde tek bir rest parametresi içeren bir oluşturucusu olmalıdır.", + "A_module_cannot_have_multiple_default_exports_2528": "Modül, birden fazla varsayılan dışarı aktarmaya sahip olamaz.", + "A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merg_2433": "Bir ad alanı bildirimi, birleştirildiği sınıf veya işlevden farklı bir dosyada olamaz.", + "A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged_2434": "Bir ad alanı bildirimi, birleştirildiği sınıf veya işlevden önce gelemez.", + "A_namespace_declaration_is_only_allowed_in_a_namespace_or_module_1235": "Ad alanı bildirimine yalnızca bir ad alanında veya modülde izin verilir.", + "A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_7038": "Bir ad alanı stili içeri aktarma işlemi çağrılamadığından veya oluşturulamadığından çalışma zamanında hataya yol açacak.", + "A_non_dry_build_would_build_project_0_6357": "-dry bayrağı kullanılmayan bir derleme '{0}' projesini derler", + "A_non_dry_build_would_delete_the_following_files_Colon_0_6356": "-dry bayrağı kullanılmayan bir derleme şu dosyaları siler: {0}", + "A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation_2371": "Parametre başlatıcısına yalnızca bir işlevde veya oluşturucu uygulamasında izin verilir.", + "A_parameter_property_cannot_be_declared_using_a_rest_parameter_1317": "Parametre özelliği, rest parametresi kullanılarak bildirilemez.", + "A_parameter_property_is_only_allowed_in_a_constructor_implementation_2369": "Parametre özelliğine yalnızca bir oluşturucu uygulamasında izin verilir.", + "A_parameter_property_may_not_be_declared_using_a_binding_pattern_1187": "Parametre özelliği, bağlama deseni kullanılarak bildirilemez.", + "A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not_18001": "'extends' seçeneğindeki yolun göreli veya kök olması gerekir, ancak '{0}' bu koşullara uymuyor.", + "A_promise_must_have_a_then_method_1059": "Promise'in bir 'then' metodu olmalıdır.", + "A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly_1331": "Bir 'unique symbol' türündeki sınıfın özelliği hem 'static' hem de 'readonly' olmalıdır.", + "A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly_1330": "Bir 'unique symbol' türündeki arabirimin veya tür sabit değerinin özelliği 'readonly' olmalıdır.", + "A_required_parameter_cannot_follow_an_optional_parameter_1016": "Gerekli parametre, isteğe bağlı parametreden sonra gelemez.", + "A_rest_element_cannot_contain_a_binding_pattern_2501": "rest öğesi bir bağlama deseni içeremez.", + "A_rest_element_cannot_have_a_property_name_2566": "Rest öğesinin özellik adı olamaz.", + "A_rest_element_cannot_have_an_initializer_1186": "rest öğesi bir başlatıcıya sahip olamaz.", + "A_rest_element_must_be_last_in_a_destructuring_pattern_2462": "Rest öğesi, yok etme desenindeki son öğe olmalıdır.", + "A_rest_parameter_cannot_be_optional_1047": "rest parametresi isteğe bağlı olamaz.", + "A_rest_parameter_cannot_have_an_initializer_1048": "rest parametresi bir başlatıcıya sahip olamaz.", + "A_rest_parameter_must_be_last_in_a_parameter_list_1014": "rest parametresi, parametre listesinin sonunda bulunmalıdır.", + "A_rest_parameter_must_be_of_an_array_type_2370": "rest parametresi dizi türünde olmalıdır.", + "A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma_1013": "Bir rest parametresi veya bağlama deseninin sonunda virgül olamaz.", + "A_return_statement_can_only_be_used_within_a_function_body_1108": "'return' deyimi, yalnızca bir işlev gövdesinde kullanılabilir.", + "A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl_6167": "İçeri aktarmaları, 'baseUrl' ile ilgili arama konumlarına yeniden eşleyen bir girdi dizisi.", + "A_set_accessor_cannot_have_a_return_type_annotation_1095": "'set' erişimcisi, dönüş türü ek açıklamasına sahip olamaz.", + "A_set_accessor_cannot_have_an_optional_parameter_1051": "'set' erişimcisi isteğe bağlı bir parametreye sahip olamaz.", + "A_set_accessor_cannot_have_rest_parameter_1053": "'set' erişimcisi rest parametresine sahip olamaz.", + "A_set_accessor_must_have_exactly_one_parameter_1049": "'set' erişimcisi tam olarak bir parametreye sahip olmalıdır.", + "A_set_accessor_parameter_cannot_have_an_initializer_1052": "'set' erişimci parametresinin bir başlatıcısı olamaz.", + "A_signature_with_an_implementation_cannot_use_a_string_literal_type_2381": "Uygulamaya sahip bir imza, dize sabit değeri türünü kullanamaz.", + "A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_proper_2376": "Bir sınıf başlatılmış özellik içerdiğinde veya parametre özelliklerine sahip olduğunda 'super' çağrısı, oluşturucudaki ilk deyim olmalıdır.", + "A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard_2518": "'This' tabanlı tür koruması, parametre tabanlı tür koruması ile uyumlu değildir.", + "A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface_2526": "'this' türü, yalnızca bir sınıfın veya arabirimin statik olmayan bir üyesinde kullanılabilir.", + "A_tsconfig_json_file_is_already_defined_at_Colon_0_5054": "'tsconfig.json' dosyası şu konumda zaten tanımlanmış: '{0}'.", + "A_tuple_type_element_list_cannot_be_empty_1122": "Demet türü öğe listesi boş olamaz.", + "A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Con_17007": "Üs ifadesinin sol tarafında tür onaylama ifadesine izin verilmez. İfadeyi parantez içine yazmayı düşünün.", + "A_type_literal_property_cannot_have_an_initializer_1247": "Tür sabit değeri özelliği bir başlatıcıya sahip olamaz.", + "A_type_predicate_cannot_reference_a_rest_parameter_1229": "Bir tür koşulu, rest parametresine başvuru yapamaz.", + "A_type_predicate_cannot_reference_element_0_in_a_binding_pattern_1230": "Bir tür koşulu, bağlama desenindeki '{0}' öğesine başvuru yapamaz.", + "A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods_1228": "Bir tür koşuluna yalnızca işlevlere ve metotlara ait dönüş türü konumunda izin verilir.", + "A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type_2677": "Bir tür koşulunun türü, parametresinin türüne atanabilir olmalıdır.", + "A_variable_whose_type_is_a_unique_symbol_type_must_be_const_1332": "Bir 'unique symbol' türündeki değişken 'const' olmalıdır.", + "A_yield_expression_is_only_allowed_in_a_generator_body_1163": "Bir 'yield' ifadesine yalnızca oluşturucu gövdesinde izin verilir.", + "Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression_2513": "'{1}' sınıfındaki '{0}' soyut metoduna super ifadesi ile erişilemez.", + "Abstract_methods_can_only_appear_within_an_abstract_class_1244": "Soyut metotlar yalnızca bir soyut sınıfta görüntülenebilir.", + "Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor_2715": "'{1}' sınıfındaki '{0}' soyut özelliğine oluşturucuda erişilemiyor.", + "Accessibility_modifier_already_seen_1028": "Erişilebilirlik değiştiricisi zaten görüldü.", + "Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher_1056": "Erişimciler yalnızca ECMAScript 5 ve üzeri hedeflenirken kullanılabilir.", + "Accessors_must_both_be_abstract_or_non_abstract_2676": "İki erişimci de soyut veya soyut olmayan olmalıdır.", + "Add_0_to_existing_import_declaration_from_1_90015": "'{0}' öğesini \"{1}\" konumundaki mevcut içeri aktarma bildirimine ekle", + "Add_0_to_unresolved_variable_90008": "Çözümlenmemiş değişkene '{0}.' ekle", + "Add_all_missing_async_modifiers_95041": "Tüm eksik 'async' değiştiricileri ekle", + "Add_all_missing_members_95022": "Tüm eksik üyeleri ekle", + "Add_all_missing_super_calls_95039": "Tüm eksik süper çağrıları ekle", + "Add_async_modifier_to_containing_function_90029": "İçeren işleve zaman uyumsuz değiştirici ekle", + "Add_braces_to_arrow_function_95059": "Ok işlevine küme ayracı ekleyin", + "Add_definite_assignment_assertion_to_property_0_95020": "'{0}' özelliğine belirli atama onayı ekle", + "Add_definite_assignment_assertions_to_all_uninitialized_properties_95028": "Tüm başlatılmamış özelliklere kesin atama onayları ekle", + "Add_index_signature_for_property_0_90017": "'{0}' özelliği için dizin imzası ekle", + "Add_initializer_to_property_0_95019": "'{0}' özelliğine başlatıcı ekle", + "Add_initializers_to_all_uninitialized_properties_95027": "Tüm başlatılmamış özelliklere başlatıcılar ekle", + "Add_missing_super_call_90001": "Eksik 'super()' çağrısını ekle", + "Add_missing_typeof_95052": "Eksik 'typeof' öğesini ekle", + "Add_or_remove_braces_in_an_arrow_function_95058": "Ok işlevine küme ayracı ekle veya kaldır", + "Add_qualifier_to_all_unresolved_variables_matching_a_member_name_95037": "Bir üye adıyla eşleşen tüm çözülmemiş değişkenlere niteleyici ekle", + "Add_to_all_uncalled_decorators_95044": "Çağrılmayan tüm dekoratörlere '()' ekle", + "Add_ts_ignore_to_all_error_messages_95042": "Tüm hata iletilerine '@ts-ignore' ekle", + "Add_undefined_type_to_all_uninitialized_properties_95029": "Tüm başlatılmamış özelliklere tanımsız tür ekle", + "Add_undefined_type_to_property_0_95018": "'{0}' özelliğine 'undefined' türünü ekle", + "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068": "Bir tsconfig.json dosyası eklemek, hem TypeScript hem de JavaScript dosyaları içeren projeleri düzenlemenize yardımcı olur. Daha fazla bilgi edinmek için bkz. https://aka.ms/tsconfig.", + "Additional_Checks_6176": "Ek Denetimler", + "Advanced_Options_6178": "Gelişmiş Seçenekler", + "All_declarations_of_0_must_have_identical_modifiers_2687": "Tüm '{0}' bildirimleri aynı değiştiricilere sahip olmalıdır.", + "All_declarations_of_0_must_have_identical_type_parameters_2428": "Tüm '{0}' bildirimleri özdeş tür parametrelerine sahip olmalıdır.", + "All_declarations_of_an_abstract_method_must_be_consecutive_2516": "Soyut metoda ait tüm bildirimler ardışık olmalıdır.", + "All_destructured_elements_are_unused_6198": "Yapısı bozulan öğelerin hiçbiri kullanılmıyor.", + "All_imports_in_import_declaration_are_unused_6192": "İçeri aktarma bildirimindeki hiçbir içeri aktarma kullanılmadı.", + "All_variables_are_unused_6199": "Hiçbir değişken kullanılmıyor.", + "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011": "Varsayılan dışarı aktarmaya sahip olmayan modüllerde varsayılan içeri aktarmalara izin verin. Bu işlem kod üretimini etkilemez, yalnızca tür denetimini etkiler.", + "Allow_javascript_files_to_be_compiled_6102": "Javascript dosyalarının derlenmesine izin ver.", + "Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided_1209": "'--isolatedModules' bayrağı sağlandığında çevresel const sabit listesi değerlerine izin verilmez.", + "Ambient_module_declaration_cannot_specify_relative_module_name_2436": "Çevresel modül bildirimi göreli modül adını belirtemez.", + "Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces_2435": "Çevresel modüller, diğer modüllerde veya ad alanlarında iç içe bulunamaz.", + "An_AMD_module_cannot_have_multiple_name_assignments_2458": "AMD modülü birden fazla ad atamasında sahip olamaz.", + "An_abstract_accessor_cannot_have_an_implementation_1318": "Soyut erişimcinin uygulaması olamaz.", + "An_accessor_cannot_be_declared_in_an_ambient_context_1086": "Erişimci, çevresel bağlamda bildirilemez.", + "An_accessor_cannot_have_type_parameters_1094": "Erişimci, tür parametrelerine sahip olamaz.", + "An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file_1234": "Çevresel modül bildirimine yalnızca bir dosyadaki en üst düzeyde izin verilir.", + "An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type_2356": "Aritmetik işlenen, 'any', 'number' veya sabit listesi türünde olmalıdır.", + "An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_de_2705": "ES5/ES3 içindeki zaman uyumsuz bir fonksiyon veya metot, 'Promise' oluşturucusu gerektiriyor. 'Promise' oluşturucusu için bir bildiriminizin olduğundan veya `--lib` seçeneğinize 'ES2015' eklediğinizden emin olun.", + "An_async_function_or_method_must_have_a_valid_awaitable_return_type_1057": "Zaman uyumsuz bir işlev veya metot, geçerli bir beklenebilir dönüş türüne sahip olmalıdır.", + "An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_in_2697": "Zaman uyumsuz bir işlevin veya metodun 'Promise' döndürmesi gerekir. Bir 'Promise' bildiriminiz olduğundan emin olun veya `--lib` seçeneğinize 'ES2015' ifadesini ekleyin.", + "An_async_iterator_must_have_a_next_method_2519": "Zaman uyumsuz yineleyicinin bir 'next()' metodu olmalıdır.", + "An_element_access_expression_should_take_an_argument_1011": "Bir öğe erişimi ifadesi bir bağımsız değişken almalıdır.", + "An_enum_member_cannot_have_a_numeric_name_2452": "Sabit listesi üyesi, sayısal bir ada sahip olamaz.", + "An_export_assignment_can_only_be_used_in_a_module_1231": "Dışarı aktarma ataması yalnızca bir modülde kullanılabilir.", + "An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements_2309": "Dışarı aktarma ataması, dışarı aktarılmış diğer öğelere sahip bir modülde kullanılamaz.", + "An_export_assignment_cannot_be_used_in_a_namespace_1063": "Ad alanında dışarı aktarma ataması kullanılamaz.", + "An_export_assignment_cannot_have_modifiers_1120": "Dışarı aktarma ataması, değiştiricilere sahip olamaz.", + "An_export_declaration_can_only_be_used_in_a_module_1233": "Dışarı aktarma bildirimi yalnızca bir modülde kullanılabilir.", + "An_export_declaration_cannot_have_modifiers_1193": "Dışarı aktarma bildirimi, değiştiricilere sahip olamaz.", + "An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive_1198": "Genişletilmiş Unicode kaçış değeri, 0x0 ve 0x10FFFF dahil olmak üzere bu değerler arasında olmalıdır.", + "An_implementation_cannot_be_declared_in_ambient_contexts_1183": "Uygulama, çevresel bağlamda bildirilemez.", + "An_import_declaration_can_only_be_used_in_a_namespace_or_module_1232": "İçeri aktarma bildirimi yalnızca bir ad alanında veya modülde kullanılabilir.", + "An_import_declaration_cannot_have_modifiers_1191": "İçeri aktarma bildirimi, değiştiricilere sahip olamaz.", + "An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead_2691": "İçeri aktarma yolu '{0}' uzantısıyla bitemez. Bunun yerine '{1}' öğesini içeri aktarmayı deneyin.", + "An_index_expression_argument_must_be_of_type_string_number_symbol_or_any_2342": "Dizin ifadesi bağımsız değişkeni 'string', 'number', 'symbol' veya 'any' değerlerine sahip olmalıdır.", + "An_index_signature_cannot_have_a_rest_parameter_1017": "Dizin imzası bir rest parametresine sahip olamaz.", + "An_index_signature_must_have_a_type_annotation_1021": "Dizin imzası bir tür açıklamasına sahip olmalıdır.", + "An_index_signature_must_have_exactly_one_parameter_1096": "Dizin imzası tam olarak bir parametreye sahip olmalıdır.", + "An_index_signature_parameter_cannot_have_a_question_mark_1019": "Dizin imzası parametresi, bir soru işareti içeremez.", + "An_index_signature_parameter_cannot_have_an_accessibility_modifier_1018": "Dizin imzası parametresi, bir erişilebilirlik değiştiricisine sahip olamaz.", + "An_index_signature_parameter_cannot_have_an_initializer_1020": "Dizin imzası parametresi, bir başlatıcıya sahip olamaz.", + "An_index_signature_parameter_must_have_a_type_annotation_1022": "Dizin imzası parametresi, bir tür ek açıklamasına sahip olmalıdır.", + "An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead_1336": "Dizin imzası parametre türü bir tür diğer adı olamaz. Bunun yerine '[{0}: {1}]: {2}' yazabilirsiniz.", + "An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead_1337": "Dizin imzası parametre türü bir birleşim türü olamaz. Bunun yerine eşlenen nesne türü kullanabilirsiniz.", + "An_index_signature_parameter_type_must_be_string_or_number_1023": "Dizin imzası parametresi, 'string' veya 'number' türünde olmalıdır.", + "An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments_2499": "Bir arabirim, isteğe bağlı tür bağımsız değişkenleri ile yalnızca bir tanımlayıcıyı/tam adı genişletebilir.", + "An_interface_may_only_extend_a_class_or_another_interface_2312": "Arabirim, yalnızca bir sınıfı veya başka bir arabirimi genişletebilir.", + "An_interface_property_cannot_have_an_initializer_1246": "Arabirim özelliği bir başlatıcıya sahip olamaz.", + "An_iterator_must_have_a_next_method_2489": "Bir yineleyici 'next()' metoduna sahip olmalıdır.", + "An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name_1118": "Nesne sabit değeri aynı ada sahip birden fazla get/set erişimcisine sahip olamaz.", + "An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode_1117": "Nesne sabit değeri, katı modda aynı ada sahip birden fazla özelliğe sahip olamaz.", + "An_object_literal_cannot_have_property_and_accessor_with_the_same_name_1119": "Nesne sabit değeri, aynı ada sahip bir özellik ve erişimciye sahip olamaz.", + "An_object_member_cannot_be_declared_optional_1162": "Nesne üyesi, isteğe bağlı olarak bildirilemez.", + "An_overload_signature_cannot_be_declared_as_a_generator_1222": "Aşırı yükleme imzası, bir oluşturucu olarak bildirilemez.", + "An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_ex_17006": "Üs ifadesinin sol tarafında '{0}' işlecine sahip bir tek terimli ifadeye izin verilmez. İfadeyi parantez içine yazmayı düşünün.", + "Annotate_everything_with_types_from_JSDoc_95043": "Her şeye JSDoc'tan türler ile not ekle", + "Annotate_with_type_from_JSDoc_95009": "JSDoc türü ile not ekle", + "Annotate_with_types_from_JSDoc_95010": "JSDoc türleri ile not ekle", + "Argument_expression_expected_1135": "Bağımsız değişken ifadesi bekleniyor.", + "Argument_for_0_option_must_be_Colon_1_6046": "'{0}' seçeneğinin bağımsız değişkeni {1} olmalıdır.", + "Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_2345": "'{0}' türündeki bağımsız değişken '{1}' türündeki parametreye atanamaz.", + "Array_element_destructuring_pattern_expected_1181": "Dizi öğesi yok etme deseni bekleniyor.", + "Asterisk_Slash_expected_1010": "'*/' bekleniyor.", + "Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_2669": "Genel kapsam genişletmeleri yalnızca dış modüllerde ya da çevresel modül bildirimlerinde doğrudan yuvalanabilir.", + "Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambien_2670": "Genel kapsam genişletmeleri, zaten çevresel olan bir bağlamda göründükleri durumlar dışında 'declare' değiştiricisine sahip olmalıdır.", + "Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using__6140": "'{0}' projesinde otomatik tür bulma etkinleştirildi. '{2}' önbellek konumu kullanılarak '{1}' modülü için ek çözümleme geçişi çalıştırılıyor.", + "Base_class_expressions_cannot_reference_class_type_parameters_2562": "Temel sınıf ifadelerinde sınıf türü parametrelerine başvuruda bulunulamaz.", + "Base_constructor_return_type_0_is_not_a_class_or_interface_type_2509": "Temel oluşturucu dönüş türü '{0}', bir sınıf veya arabirim türü değil.", + "Base_constructors_must_all_have_the_same_return_type_2510": "Tüm temel oluşturucuların aynı dönüş türüne sahip olması gerekir.", + "Base_directory_to_resolve_non_absolute_module_names_6083": "Mutlak olmayan modül adlarını çözümlemek için kullanılan temel dizin.", + "Basic_Options_6172": "Temel Seçenekler", + "Binary_digit_expected_1177": "İkili sayı bekleniyor.", + "Binding_element_0_implicitly_has_an_1_type_7031": "'{0}' bağlama öğesi, örtük olarak '{1}' türü içeriyor.", + "Block_scoped_variable_0_used_before_its_declaration_2448": "Blok kapsamlı değişken '{0}', bildirilmeden önce kullanıldı.", + "Build_all_projects_including_those_that_appear_to_be_up_to_date_6368": "Güncel görünenler de dahil olmak üzere tüm projeleri derleyin", + "Build_one_or_more_projects_and_their_dependencies_if_out_of_date_6364": "Eskiyse, bir veya daha fazla projeyi ve bağımlılıklarını derleyin", + "Building_project_0_6358": "'{0}' projesi derleniyor...", + "Call_decorator_expression_90028": "Dekoratör ifadesini çağır", + "Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7020": "Dönüş türü ek açıklaması bulunmayan çağrı imzası, örtük olarak 'any' dönüş türüne sahip.", + "Call_target_does_not_contain_any_signatures_2346": "Çağrı hedefi imza içermiyor.", + "Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_p_2713": "'{0}' bir ad alanı değil tür olduğundan '{0}.{1}' erişimi sağlanamıyor. '{0}[\"{1}\"]' değerini belirterek '{0}' içindeki '{1}' özelliğinin türünü almak mı istediniz?", + "Cannot_assign_a_0_constructor_type_to_a_1_constructor_type_2672": "'{0}' oluşturucu türüne '{1}' oluşturucu türü atanamaz.", + "Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type_2517": "Bir soyut oluşturucu türü, soyut olmayan bir oluşturucu türüne atanamaz.", + "Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property_2540": "Sabit veya salt okunur bir özellik olduğundan '{0}' özelliğine atama yapılamıyor.", + "Cannot_assign_to_0_because_it_is_not_a_variable_2539": "Değişken olmadığından '{0}' öğesine atama yapılamıyor.", + "Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity_2671": "'{0}' modülü, modül olmayan bir varlığa çözümlendiğinden genişletilemiyor.", + "Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity_2649": "Modül olmayan bir varlığa çözümlendiğinden '{0}' modülü, değer dışarı aktarmalarıyla genişletilemiyor.", + "Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system_6131": "'--module' bayrağı 'amd' veya 'system' olmadığı sürece '{0}' seçeneği kullanılarak modül derlenemez.", + "Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided_1208": "'--isolatedModules' bayrağı sağlandığında ad alanları derlenemez.", + "Cannot_create_an_instance_of_an_abstract_class_2511": "Bir soyut sınıfın örneği oluşturulamaz.", + "Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module_2661": "'{0}' dışarı aktarılamıyor. Bir modülden yalnızca yerel bildirimler dışarı aktarılabilir.", + "Cannot_extend_a_class_0_Class_constructor_is_marked_as_private_2675": "'{0}' sınıfı genişletilemez. Sınıf oluşturucusu, özel olarak işaretlenmiş.", + "Cannot_extend_an_interface_0_Did_you_mean_implements_2689": "'{0}' arabirimi genişletilemiyor. Bunun yerine 'implements' kullanmayı deneyin.", + "Cannot_find_a_tsconfig_json_file_at_the_specified_directory_Colon_0_5057": "Belirtilen dizinde tsconfig.json dosyası bulunamıyor: '{0}'.", + "Cannot_find_global_type_0_2318": "'{0}' genel türü bulunamıyor.", + "Cannot_find_global_value_0_2468": "'{0}' genel değeri bulunamıyor.", + "Cannot_find_lib_definition_for_0_2726": "'{0}' için kitaplık tanımı bulunamıyor.", + "Cannot_find_lib_definition_for_0_Did_you_mean_1_2727": "'{0}' için kitaplık tanımı bulunamıyor. Şunu mu demek istediniz: '{1}'?", + "Cannot_find_module_0_2307": "'{0}' modülü bulunamıyor.", + "Cannot_find_name_0_2304": "'{0}' adı bulunamıyor.", + "Cannot_find_name_0_Did_you_mean_1_2552": "'{0}' adı bulunamıyor. Bunu mu demek istediniz: '{1}'?", + "Cannot_find_name_0_Did_you_mean_the_instance_member_this_0_2663": "'{0}' adı bulunamıyor. 'this.{0}' örnek üyesini mi aradınız?", + "Cannot_find_name_0_Did_you_mean_the_static_member_1_0_2662": "'{0}' adı bulunamıyor. '{1}.{0}' statik üyesini mi aradınız?", + "Cannot_find_namespace_0_2503": "'{0}' ad alanı bulunamıyor.", + "Cannot_find_parameter_0_1225": "'{0}' parametresi bulunamıyor.", + "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009": "Giriş dosyalarına ait ortak alt dizin yolu bulunamıyor.", + "Cannot_find_type_definition_file_for_0_2688": "'{0}' için tür tanımı dosyası bulunamıyor.", + "Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1_6137": "Tür bildirim dosyaları içeri aktarılamıyor. '{1}' yerine '{0}' dosyasını içeri aktarmanız önerilir.", + "Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1_2481": "Dış kapsamdaki '{0}' değişkeni, blok kapsamındaki '{1}' bildirimiyle aynı kapsamda başlatılamaz.", + "Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatur_2349": "Türü bir çağrı imzasına sahip olmayan bir ifade çağrılamaz. '{0}' türünün uyumlu çağrı imzası yok.", + "Cannot_invoke_an_object_which_is_possibly_null_2721": "Muhtemelen 'null' olan bir nesne çağrılamıyor.", + "Cannot_invoke_an_object_which_is_possibly_null_or_undefined_2723": "Muhtemelen 'null' veya 'undefined' olan bir nesne çağrılamıyor.", + "Cannot_invoke_an_object_which_is_possibly_undefined_2722": "Muhtemelen 'undefined' olan bir nesne çağrılamıyor.", + "Cannot_prepend_project_0_because_it_does_not_have_outFile_set_6308": "{0}' projesi için 'outFile' ayarlanmadığından başa eklenemiyor", + "Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205": "'--isolatedModules' bayrağı sağlandığında bir tür yeniden dışarı aktarılamaz.", + "Cannot_read_file_0_Colon_1_5012": "'{0}' dosyası okunamıyor: {1}.", + "Cannot_redeclare_block_scoped_variable_0_2451": "Blok kapsamlı değişken '{0}', yeniden bildirilemiyor.", + "Cannot_redeclare_exported_variable_0_2323": "Dışarı aktarılan '{0}' değişkeni yeniden bildirilemiyor.", + "Cannot_redeclare_identifier_0_in_catch_clause_2492": "Catch yan tümcesindeki '{0}' tanımlayıcısı yeniden bildirilemiyor.", + "Cannot_use_JSX_unless_the_jsx_flag_is_provided_17004": "'--jsx' bayrağı sağlanmazsa JSX kullanılamaz.", + "Cannot_use_imports_exports_or_module_augmentations_when_module_is_none_1148": "'--module' değeri 'none' olduğunda içeri aktarma, dışarı aktarma veya modül genişletme kullanılamaz.", + "Cannot_use_namespace_0_as_a_type_2709": "'{0}' ad alanı, tür olarak kullanılamaz.", + "Cannot_use_namespace_0_as_a_value_2708": "'{0}' ad alanı, değer olarak kullanılamaz.", + "Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature_2351": "Türünde çağrı veya yapı imzası olmayan ifadeyle 'new' kullanılamaz.", + "Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files_5056": "Birden fazla giriş dosyası tarafından üzerine yazılacağı için '{0}' dosyası yazılamıyor.", + "Cannot_write_file_0_because_it_would_overwrite_input_file_5055": "Giriş dosyasının üzerine yazacağı için '{0}' dosyası yazılamıyor.", + "Catch_clause_variable_cannot_have_a_type_annotation_1196": "Catch yan tümcesi değişkeni bir tür ek açıklamasına sahip olamaz.", + "Catch_clause_variable_cannot_have_an_initializer_1197": "Catch yan tümcesi değişkeni bir başlatıcıya sahip olamaz.", + "Change_0_to_1_90014": "'{0}' değerini '{1}' olarak değiştir", + "Change_all_extended_interfaces_to_implements_95038": "Tüm genişletilmiş arabirimleri 'implements' olarak değiştir", + "Change_all_jsdoc_style_types_to_TypeScript_95030": "Tüm jsdoc-style türlerini TypeScript olarak değiştir", + "Change_all_jsdoc_style_types_to_TypeScript_and_add_undefined_to_nullable_types_95031": "Tüm jsdoc-style türlerini TypeScript olarak değiştir (ve null yapılabilir türlere '| undefined' ekle)", + "Change_extends_to_implements_90003": "'extends' ifadesini 'implements' olarak değiştirin", + "Change_spelling_to_0_90022": "Yazımı '{0}' olarak değiştir", + "Checking_if_0_is_the_longest_matching_prefix_for_1_2_6104": "'{0}' ön ekinin '{1}' - '{2}' için eşleşen en uzun ön ek olup olmadığı denetleniyor.", + "Circular_definition_of_import_alias_0_2303": "'{0}' içeri aktarma diğer adının döngüsel tanımı.", + "Circularity_detected_while_resolving_configuration_Colon_0_18000": "Yapılandırma çözümlenirken döngüsellik algılandı: {0}", + "Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_functi_2426": "'{0}' sınıfı, '{1}' örnek üyesi erişimcisini tanımlar; ancak genişletilmiş '{2}' sınıfı, bunu bir örnek üyesi işlevi olarak tanımlar.", + "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_access_2423": "'{0}' sınıfı, '{1}' örnek üyesi işlevini tanımlar; ancak genişletilmiş '{2}' sınıfı, bunu bir örnek üyesi erişimcisi olarak tanımlar.", + "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_proper_2424": "'{0}' sınıfı, '{1}' örnek üyesi işlevini tanımlar; ancak genişletilmiş '{2}' sınıfı, bunu bir örnek üyesi özelliği olarak tanımlar.", + "Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_functi_2425": "'{0}' sınıfı, '{1}' örnek üyesi özelliğini tanımlar; ancak genişletilmiş '{2}' sınıfı, bunu bir örnek üyesi işlevi olarak tanımlar.", + "Class_0_incorrectly_extends_base_class_1_2415": "'{0}' sınıfı, '{1}' temel sınıfını yanlış genişletiyor.", + "Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclas_2720": "'{0}' sınıfı hatalı olarak '{1}' sınıfını uyguluyor. '{1}' sınıfını genişletip üyelerini bir alt sınıf olarak devralmak mı istiyordunuz?", + "Class_0_incorrectly_implements_interface_1_2420": "'{0}' sınıfı, '{1}' arabirimini yanlış uyguluyor.", + "Class_0_used_before_its_declaration_2449": "'{0}' sınıfı, bildiriminden önce kullanıldı.", + "Class_declarations_cannot_have_more_than_one_augments_or_extends_tag_8025": "Sınıf bildirimlerinde birden fazla `@augments` veya `@extends` etiketi olamaz.", + "Class_name_cannot_be_0_2414": "Sınıf adı '{0}' olamaz.", + "Class_name_cannot_be_Object_when_targeting_ES5_with_module_0_2725": "Modül {0} ile ES5 hedeflendiğinde sınıf adı 'Object' olamaz.", + "Class_static_side_0_incorrectly_extends_base_class_static_side_1_2417": "'{0}' statik sınıf tarafı, '{1}' statik temel sınıf tarafını yanlış genişletiyor.", + "Classes_can_only_extend_a_single_class_1174": "Sınıflar yalnızca bir sınıfı genişletebilir.", + "Classes_containing_abstract_methods_must_be_marked_abstract_2514": "Soyut metotlar içeren sınıflar abstract olarak işaretlenmelidir.", + "Command_line_Options_6171": "Komut Satırı Seçenekleri", + "Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json_6020": "Yapılandırma dosyasının yolu veya 'tsconfig.json' dosyasını içeren klasörün yolu belirtilen projeyi derleyin.", + "Compiler_option_0_expects_an_argument_6044": "'{0}' derleyici seçeneği, bağımsız değişken bekliyor.", + "Compiler_option_0_requires_a_value_of_type_1_5024": "'{0}' derleyici seçeneği, {1} türünde bir değer gerektiriyor.", + "Composite_projects_may_not_disable_declaration_emit_6304": "Bileşik projeler, bildirim gösterimini devre dışı bırakamaz.", + "Computed_property_names_are_not_allowed_in_enums_1164": "Sabit listelerinde hesaplanan özellik adına izin verilmiyor.", + "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553": "Dize değeri içeren üyelerin bulunduğu bir sabit listesinde hesaplanan değerlere izin verilmez.", + "Concatenate_and_emit_output_to_single_file_6001": "Çıktıyı tek dosyaya birleştirin ve yayın.", + "Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_librar_4090": "'{1}' ve '{2}' içinde '{0}' için çakışan tanımlar bulundu. Çakışmayı çözmek için bu kitaplığın belirli bir versiyonunu yüklemeniz önerilir.", + "Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7013": "Dönüş türü ek açıklaması bulunmayan yapı imzası, örtük olarak 'any' dönüş türüne sahip.", + "Constructor_implementation_is_missing_2390": "Oluşturucu uygulaması yok.", + "Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration_2673": "'{0}' sınıfının oluşturucusu özel olduğundan, oluşturucuya yalnızca sınıf bildiriminden erişilebilir.", + "Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration_2674": "'{0}' sınıfının oluşturucusu korumalı olduğundan, oluşturucuya yalnızca sınıf bildiriminden erişilebilir.", + "Constructors_for_derived_classes_must_contain_a_super_call_2377": "Türetilmiş sınıflara ilişkin oluşturucular bir 'super' çağrısı içermelidir.", + "Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126": "Kapsayıcı dosya belirtilmedi ve kök dizini belirlenemiyor; 'node_modules' klasöründe arama atlanıyor.", + "Convert_0_to_mapped_object_type_95055": "'{0}' öğesini eşlenen nesne türüne dönüştür", + "Convert_all_constructor_functions_to_classes_95045": "Tüm oluşturucu işlevleri sınıflara dönüştür", + "Convert_all_require_to_import_95048": "Tüm 'require' öğelerini 'import' olarak dönüştür", + "Convert_all_to_default_imports_95035": "Tümünü varsayılan içeri aktarmalara dönüştür", + "Convert_function_0_to_class_95002": "'{0}' işlevini sınıfa dönüştür", + "Convert_function_to_an_ES2015_class_95001": "İşlevi bir ES2015 sınıfına dönüştür", + "Convert_named_imports_to_namespace_import_95057": "Adlandırılmış içeri aktarmaları ad alanı içeri aktarmasına dönüştür", + "Convert_namespace_import_to_named_imports_95056": "Ad alanı içeri aktarmasını adlandırılmış içeri aktarmalara dönüştür", + "Convert_require_to_import_95047": "'require' öğesini 'import' olarak dönüştür", + "Convert_to_ES6_module_95017": "ES6 modülüne dönüştür", + "Convert_to_default_import_95013": "Varsayılan içeri aktarmaya dönüştür", + "Corrupted_locale_file_0_6051": "{0} yerel ayar dosyası bozuk.", + "Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type_7016": "'{0}' modülü için bildirim dosyası bulunamadı. '{1}' örtülü olarak 'any' türüne sahip.", + "Could_not_write_file_0_Colon_1_5033": "'{0}' dosyası yazılamadı: {1}.", + "DIRECTORY_6038": "DİZİN", + "Declaration_expected_1146": "Bildirim bekleniyor.", + "Declaration_name_conflicts_with_built_in_global_identifier_0_2397": "Bildirim adı, yerleşik genel tanımlayıcı '{0}' ile çakışıyor.", + "Declaration_or_statement_expected_1128": "Bildirim veya deyim bekleniyor.", + "Declare_method_0_90023": "'{0}' metodunu bildir", + "Declare_property_0_90016": "'{0}' özelliğini bildir", + "Declare_static_method_0_90024": "'{0}' statik metodunu bildir", + "Declare_static_property_0_90027": "'{0}' statik özelliğini bildir", + "Decorators_are_not_valid_here_1206": "Buradaki dekoratörler geçerli değil.", + "Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name_1207": "Dekoratörler aynı ada sahip birden fazla get/set erişimcisine uygulanamaz.", + "Default_export_of_the_module_has_or_is_using_private_name_0_4082": "Modülün varsayılan dışarı aktarımı '{0}' özel adına sahip veya bu adı kullanıyor.", + "Delete_all_unused_declarations_95024": "Kullanılmayan tüm bildirimleri sil", + "Delete_the_outputs_of_all_projects_6365": "Tüm projelerin çıkışlarını sil", + "Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react__6084": "[Kullanım Dışı] Bunun yerine '--jsxFactory' kullanın. 'react' JSX gösterimi hedefleniyorsa, createElement için çağrılan nesneyi belirtin", + "Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file_6170": "[Kullanım Dışı] Bunun yerine '--outFile' kullanın. Çıkışı tek bir dosya olarak birleştirin ve gösterin", + "Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files_6160": "[Kullanım Dışı] Bunun yerine '--skipLibCheck' kullanın. Varsayılan kitaplık bildirim dosyalarının tür denetimini atlayın.", + "Digit_expected_1124": "Rakam bekleniyor.", + "Directory_0_does_not_exist_skipping_all_lookups_in_it_6148": "'{0}' dizini yok, içindeki tüm aramalar atlanıyor.", + "Disable_checking_for_this_file_90018": "Bu dosya için denetimi devre dışı bırak", + "Disable_size_limitations_on_JavaScript_projects_6162": "JavaScript projelerinde boyut sınırlamalarını devre dışı bırakın.", + "Disable_strict_checking_of_generic_signatures_in_function_types_6185": "İşlev türlerinde genel imzalar için katı denetimi devre dışı bırakın.", + "Disallow_inconsistently_cased_references_to_the_same_file_6078": "Aynı dosyaya yönelik tutarsız büyük/küçük harflere sahip başvurulara izin verme.", + "Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files_6159": "Derlenen dosya listesine üç eğik çizgi başvuruları veya içeri aktarılan modüller eklemeyin.", + "Do_not_emit_comments_to_output_6009": "Çıktıya ait açıklamaları gösterme.", + "Do_not_emit_declarations_for_code_that_has_an_internal_annotation_6056": "'@internal' ek açıklamasına sahip kod için bildirimleri gösterme.", + "Do_not_emit_outputs_6010": "Çıktıları gösterme.", + "Do_not_emit_outputs_if_any_errors_were_reported_6008": "Herhangi bir hata bildirildiyse çıkışları gösterme.", + "Do_not_emit_use_strict_directives_in_module_output_6112": "Modül çıkışında 'use strict' yönergeleri gösterme.", + "Do_not_erase_const_enum_declarations_in_generated_code_6007": "Oluşturulan kodda const sabit listesi bildirimlerini silme.", + "Do_not_generate_custom_helper_functions_like_extends_in_compiled_output_6157": "Derlenen çıkışta '__extends' gibi özel yardımcı işlevler oluşturmayın.", + "Do_not_include_the_default_library_file_lib_d_ts_6158": "Varsayılan kitaplık dosyasını (lib.d.ts) eklemeyin.", + "Do_not_report_errors_on_unreachable_code_6077": "Erişilemeyen kod ile ilgili hataları bildirme.", + "Do_not_report_errors_on_unused_labels_6074": "Kullanılmayan etiketler ile ilgili hataları bildirme.", + "Do_not_resolve_the_real_path_of_symlinks_6013": "Simgesel bağlantıların gerçek yolunu çözümlemeyin.", + "Do_not_truncate_error_messages_6165": "Hata iletilerini kesmeyin.", + "Duplicate_declaration_0_2718": "Yinelenen '{0}' bildirimi.", + "Duplicate_function_implementation_2393": "Yinelenen işlev uygulaması.", + "Duplicate_identifier_0_2300": "Yinelenen tanımlayıcı: '{0}'.", + "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_2441": "Yinelenen tanımlayıcı: '{0}'. Derleyici, bir modülün üst düzey kapsamındaki '{1}' adını ayırır.", + "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_func_2529": "'{0}' tanımlayıcısı yineleniyor. Derleyici, zaman uyumsuz işlevler içeren bir modülün en üst düzey kapsamında '{1}' adını ayırıyor.", + "Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions_2520": "Yinelenen tanımlayıcı: '{0}'. Derleyici, zaman uyumsuz işlevleri desteklemek için '{1}' bildirimini kullanır.", + "Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters_2396": "Yinelenen tanımlayıcı: 'arguments'. Derleyici, rest parametrelerini başlatmak için 'arguments' tanımlayıcısını kullanır.", + "Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_me_2543": "Yinelenen '_newTarget' tanımlayıcısı. Derleyicide, '_newTarget' değişken bildirimi 'new.target' meta-özellik başvurusu yakalamak için kullanılıyor.", + "Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference_2401": "Yinelenen tanımlayıcı: '_super'. Derleyici, temel sınıf başvurusunu yakalamak için '_super' tanımlayıcısını kullanır.", + "Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference_2399": "Yinelenen tanımlayıcı: '_this'. Derleyici, 'this' başvurusunu yakalamak için '_this' değişken bildirimini kullanır.", + "Duplicate_label_0_1114": "'{0}' etiketi yineleniyor.", + "Duplicate_number_index_signature_2375": "Dizin imzasında yinelenen numara.", + "Duplicate_string_index_signature_2374": "Dizin imzasında yinelenen dize.", + "Dynamic_import_cannot_have_type_arguments_1326": "Dinamik içeri aktarma, tür bağımsız değişkenleri içeremez", + "Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext_1323": "Dinamik içeri aktarma yalnızca '--module' bayrağı 'commonjs' veya 'esNext' olduğunda desteklenir.", + "Dynamic_import_must_have_one_specifier_as_an_argument_1324": "Dinamik içeri aktarma, bağımsız değişken olarak bir tanımlayıcı içermelidir.", + "Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036": "Dinamik içeri aktarmanın tanımlayıcısı 'string' türünde olmalıdır, ancak buradaki tür: '{0}'.", + "Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015": "Dizin ifadesi 'number' türünde olmadığından, öğe örtük olarak 'any' türü içeriyor.", + "Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature_7017": "'{0}' türünün dizin imzası olmadığından öğe dolaylı olarak 'any' türüne sahip.", + "Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files_6164": "Çıkış dosyalarının başında bir UTF-8 Bayt Sırası İşareti (BOM) gösterin.", + "Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file_6151": "Ayrı bir dosya oluşturmak yerine, kaynak eşlemeleri içeren tek bir dosya gösterin.", + "Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap__6152": "Kaynağı, kaynak eşlemeleri ile birlikte tek bir dosya içinde gösterin; '--inlineSourceMap' veya '--sourceMap' öğesinin ayarlanmasını gerektirir.", + "Enable_all_strict_type_checking_options_6180": "Tüm katı tür denetleme seçeneklerini etkinleştirin.", + "Enable_project_compilation_6302": "Proje derlemeyi etkinleştir", + "Enable_strict_checking_of_function_types_6186": "İşlev türleri üzerinde katı denetimi etkinleştirin.", + "Enable_strict_checking_of_property_initialization_in_classes_6187": "Sınıflarda sıkı özellik başlatma denetimini etkinleştirin.", + "Enable_strict_null_checks_6113": "Katı null denetimlerini etkinleştir.", + "Enable_tracing_of_the_name_resolution_process_6085": "Ad çözümleme işlemini izlemeyi etkinleştir.", + "Enable_verbose_logging_6366": "Ayrıntılı günlüğe yazmayı etkinleştir", + "Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for__7037": "Tüm içeri aktarma işlemleri için ad alanı nesnelerinin oluşturulması aracılığıyla CommonJS ile ES Modülleri arasında yayımlama birlikte çalışabilirliğine imkan tanır. Şu anlama gelir: 'allowSyntheticDefaultImports'.", + "Enables_experimental_support_for_ES7_async_functions_6068": "Zaman uyumsuz ES7 işlevleri için deneysel desteği etkinleştirir.", + "Enables_experimental_support_for_ES7_decorators_6065": "ES7 dekoratörleri için deneysel desteği etkinleştirir.", + "Enables_experimental_support_for_emitting_type_metadata_for_decorators_6066": "Dekoratörlere tür meta verisi gönderme için deneysel desteği etkinleştirir.", + "Enum_0_used_before_its_declaration_2450": "'{0}' sabit listesi, bildiriminden önce kullanıldı.", + "Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations_2567": "Sabit listesi bildirimleri yalnızca ad alanı veya diğer sabit listesi bildirimleri ile birleştirilebilir.", + "Enum_declarations_must_all_be_const_or_non_const_2473": "Sabit listesi bildirimlerinin tümü const veya const olmayan değerler olmalıdır.", + "Enum_member_expected_1132": "Sabit listesi üyesi bekleniyor.", + "Enum_member_must_have_initializer_1061": "Sabit listesi üyesi bir başlatıcıya sahip olmalıdır.", + "Enum_name_cannot_be_0_2431": "Sabit listesi adı '{0}' olamaz.", + "Enum_type_0_has_members_with_initializers_that_are_not_literals_2535": "Sabit listesi türü '{0}', sabit değer olmayan başlatıcılara sahip üyeler içeriyor.", + "Examples_Colon_0_6026": "Örnekler: {0}", + "Excessive_stack_depth_comparing_types_0_and_1_2321": "Aşırı yığın derinliği, '{0}' ve '{1}' türlerini karşılaştırıyor.", + "Expected_0_1_type_arguments_provide_these_with_an_extends_tag_8027": "{0}-{1} tür bağımsız değişkeni bekleniyordu; bunları bir '@extends' etiketiyle sağlayın.", + "Expected_0_arguments_but_got_1_2554": "{0} bağımsız değişken bekleniyordu ancak {1} alındı.", + "Expected_0_arguments_but_got_1_or_more_2556": "{0} bağımsız değişken bekleniyordu ancak {1} veya daha fazla bağımsız değişken alındı.", + "Expected_0_type_arguments_but_got_1_2558": "{0} tür bağımsız değişkeni bekleniyordu ancak {1} alındı.", + "Expected_0_type_arguments_provide_these_with_an_extends_tag_8026": "{0} tür bağımsız değişkeni bekleniyordu; bunları bir '@extends' etiketiyle sağlayın.", + "Expected_at_least_0_arguments_but_got_1_2555": "En az {0} bağımsız değişken bekleniyordu ancak {1} alındı.", + "Expected_at_least_0_arguments_but_got_1_or_more_2557": "En az {0} bağımsız değişken bekleniyordu ancak {1} veya daha fazla bağımsız değişken alındı.", + "Expected_corresponding_JSX_closing_tag_for_0_17002": "'{0}' için ilgili JSX kapanış etiketi bekleniyor.", + "Expected_corresponding_closing_tag_for_JSX_fragment_17015": "JSX parçasına karşılık gelen kapanış etiketi bekleniyordu.", + "Expected_type_of_0_field_in_package_json_to_be_string_got_1_6105": "'Package.json' öğesindeki '{0}' alanının türünün 'string' olması bekleniyordu, ancak '{1}' alındı.", + "Experimental_Options_6177": "Deneysel Seçenekler", + "Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_t_1219": "Dekoratörler için sunulan deneysel destek özelliği, sonraki sürümlerde değiştirilebilir. Bu uyarıyı kaldırmak için 'experimentalDecorators' seçeneğini ayarlayın.", + "Explicitly_specified_module_resolution_kind_Colon_0_6087": "Açık olarak belirtilen modül çözümleme türü: '{0}'.", + "Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or__1203": "ECMAScript modülleri hedeflenirken dışarı aktarma ataması kullanılamaz. Bunun yerine 'export default' veya başka bir modül biçimi kullanmayı deneyin.", + "Export_assignment_is_not_supported_when_module_flag_is_system_1218": "'--module' bayrağı 'system' ise dışarı aktarma ataması desteklenmez.", + "Export_declaration_conflicts_with_exported_declaration_of_0_2484": "Dışarı aktarma bildirimi, dışarı aktarılan '{0}' bildirimiyle çakışıyor.", + "Export_declarations_are_not_permitted_in_a_namespace_1194": "Ad alanında dışarı aktarma bildirimlerine izin verilmez.", + "Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_2656": "Dışarı aktarılan dış paket yazı dosyası '{0}', bir modül değil. Paket tanımını güncelleştirmek için lütfen paket yazarı ile iletişime geçin.", + "Exported_external_package_typings_file_cannot_contain_tripleslash_references_Please_contact_the_pack_2654": "Dışarı aktarılan dış paket yazıları, üç eğik çizgili başvurular içeremez. Paket tanımını güncelleştirmek için lütfen paket yazarı ile iletişime geçin.", + "Exported_type_alias_0_has_or_is_using_private_name_1_4081": "Dışarı aktarılan '{0}' tür diğer adı, '{1}' özel adına sahip veya bu adı kullanıyor.", + "Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4023": "Dışarı aktarılan '{0}' değişkeni, {2} dış modülündeki '{1}' adına sahip veya bu adı kullanıyor, ancak adlandırılamıyor.", + "Exported_variable_0_has_or_is_using_name_1_from_private_module_2_4024": "Dışarı aktarılan '{0}' değişkeni, '{2}' özel modüldeki '{1}' adına sahip veya bu adı kullanıyor.", + "Exported_variable_0_has_or_is_using_private_name_1_4025": "Dışarı aktarılan '{0}' değişkeni, '{1}' özel adına sahip veya bu adı kullanıyor.", + "Exports_and_export_assignments_are_not_permitted_in_module_augmentations_2666": "Modül genişletmelerinde dışarı aktarmalara ve dışarı aktarma atamalarına izin verilmez.", + "Expression_expected_1109": "İfade bekleniyor.", + "Expression_or_comma_expected_1137": "İfade veya virgül bekleniyor.", + "Expression_resolves_to_super_that_compiler_uses_to_capture_base_class_reference_2402": "İfade, derleyicinin temel sınıf başvurusunu yakalamak için kullandığı '_super' öğesi olarak çözümleniyor.", + "Expression_resolves_to_variable_declaration_0_that_compiler_uses_to_support_async_functions_2521": "İfade, derleyicinin zaman uyumsuz işlevleri desteklemek için kullandığı '{0}' değişken bildirimi olarak çözümleniyor.", + "Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta__2544": "İfade, derleyicinin 'new.target' meta-özellik başvurusu yakalamak için kullandığı '_newTarget' değişken bildirimi olarak çözümleniyor.", + "Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference_2400": "İfade, derleyicinin 'this' başvurusunu yakalamak için kullandığı '_this' değişken bildirimi olarak çözümleniyor.", + "Extract_constant_95006": "Sabiti ayıkla", + "Extract_function_95005": "İşlevi ayıkla", + "Extract_to_0_in_1_95004": "{1} içindeki {0} konumuna ayıkla", + "Extract_to_0_in_1_scope_95008": "{1} kapsamındaki {0} konumuna ayıkla", + "Extract_to_0_in_enclosing_scope_95007": "Çevreleyen kapsamdaki {0} konumuna ayıkla", + "FILE_6035": "DOSYA", + "FILE_OR_DIRECTORY_6040": "DOSYA VEYA DİZİN", + "Failed_to_parse_file_0_Colon_1_5014": "'{0}' dosyası ayrıştırılamadı: {1}.", + "Fallthrough_case_in_switch_7029": "switch deyiminde sonraki ifadeye geçiş.", + "File_0_does_not_exist_6096": "'{0}' adlı dosya yok.", + "File_0_exist_use_it_as_a_name_resolution_result_6097": "'{0}' adlı dosya yok; bunu bir çözümleme sonucu olarak kullanın.", + "File_0_has_an_unsupported_extension_so_skipping_it_6081": "'{0}' dosyasının desteklenmeyen bir uzantısı olduğundan dosya atlanıyor.", + "File_0_has_unsupported_extension_The_only_supported_extensions_are_1_6054": "'{0}' dosyası desteklenmeyen uzantıya sahip. Yalnızca {1} uzantıları desteklenir.", + "File_0_is_not_a_module_2306": "'{0}' dosyası bir modül değil.", + "File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern_6307": "'{0}' dosyası, proje dosyası listesinde değil. Projelerin tüm dosyaları listelemesi veya bir 'include' düzeni kullanması gerekir.", + "File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files_6059": "'{0}' dosyası, 'rootDir' '{1}' dizininde değil. 'rootDir' dizininin tüm kaynak dosyalarını içermesi bekleniyor.", + "File_0_not_found_6053": "'{0}' dosyası bulunamadı.", + "File_change_detected_Starting_incremental_compilation_6032": "Dosya değişikliği algılandı. Artımlı derleme başlatılıyor...", + "File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module_80001": "Bir CommonJS modülü olan dosya, ES6 modülüne dönüştürülebilir.", + "File_name_0_differs_from_already_included_file_name_1_only_in_casing_1149": "'{0}' dosya adının, zaten eklenmiş olan '{1}' dosya adından tek farkı, büyük/küçük harf kullanımı.", + "File_name_0_has_a_1_extension_stripping_it_6132": "'{0}' dosya adında '{1}' uzantısı var; uzantı ayrılıyor.", + "File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildca_5065": "Dosya belirtimi, özyinelemeli dizin joker karakterinden ('**') sonra görünen bir üst dizin ('..') içeremez: '{0}'.", + "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010": "Dosya belirtimi, özyinelemeli dizin joker karakter ('**') ile bitemez: '{0}'.", + "Fix_all_detected_spelling_errors_95026": "Algılanan tüm yazım hatalarını düzelt", + "Found_0_errors_Watching_for_file_changes_6194": "{0} hata bulundu. Dosya değişiklikleri izleniyor.", + "Found_1_error_Watching_for_file_changes_6193": "1 hata bulundu. Dosya değişiklikleri izleniyor.", + "Found_package_json_at_0_6099": "'{0}' içinde 'package.json' bulundu.", + "Found_package_json_at_0_Package_ID_is_1_6190": "'{0}' konumunda 'package.json' bulundu. Paket kimliği '{1}'.", + "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_1250": "Katı modda 'ES3' veya 'ES5' hedeflenirken blokların içinde işlev bildirimlerine izin verilmez.", + "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_d_1251": "Katı modda 'ES3' veya 'ES5' hedeflenirken blokların içinde işlev bildirimlerine izin verilmez. Sınıf tanımları otomatik olarak katı moddadır.", + "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_1252": "Katı modda 'ES3' veya 'ES5' hedeflenirken blokların içinde işlev bildirimlerine izin verilmez. Modüller otomatik olarak katı moddadır.", + "Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type_7011": "Dönüş türü ek açıklaması bulunmayan işlev ifadesi, örtük olarak '{0}' dönüş türüne sahip.", + "Function_implementation_is_missing_or_not_immediately_following_the_declaration_2391": "İşlev uygulaması yok veya bildirimden hemen sonra gelmiyor.", + "Function_implementation_name_must_be_0_2389": "İşlev uygulamasının adı '{0}' olmalıdır.", + "Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_ref_7024": "Dönüş türü ek açıklamasına sahip olmadığından ve doğrudan veya dolaylı olarak dönüş ifadelerinden birinde kendine başvurulduğundan işlev, örtük olarak 'any' türüne sahiptir.", + "Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined_2366": "İşlevin sonunda return deyimi eksik ve dönüş türü 'undefined' içermiyor.", + "Function_overload_must_be_static_2387": "İşlev aşırı yüklemesi statik olmalıdır.", + "Function_overload_must_not_be_static_2388": "İşlev aşırı yüklemesi statik olmamalıdır.", + "Generate_get_and_set_accessors_95046": "'get' ve 'set' erişimcilerini oluşturun", + "Generates_a_sourcemap_for_each_corresponding_d_ts_file_6000": "Karşılık gelen her '.d.ts' dosyası için bir kaynak eşlemesi oluşturur.", + "Generates_corresponding_d_ts_file_6002": "İlgili '.d.ts' dosyasını oluşturur.", + "Generates_corresponding_map_file_6043": "İlgili '.map' dosyasını oluşturur.", + "Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_typ_7025": "Oluşturucu herhangi bir değer içermediğinden örtük olarak '{0}' türüne sahip. Bir dönüş türü sağlamayı göz önünde bulundurun.", + "Generators_are_not_allowed_in_an_ambient_context_1221": "Çevresel bağlamda oluşturuculara izin verilmez.", + "Generators_are_only_available_when_targeting_ECMAScript_2015_or_higher_1220": "Oluşturucular yalnızca ECMEAScript 2015 veya üstü hedeflenirken kullanılabilir.", + "Generic_type_0_requires_1_type_argument_s_2314": "'{0}' genel türü, {1} tür bağımsız değişkenini gerektiriyor.", + "Generic_type_0_requires_between_1_and_2_type_arguments_2707": "'{0}' genel türü {1} ile {2} arasında bağımsız değişken gerektirir.", + "Generic_type_instantiation_is_excessively_deep_and_possibly_infinite_2550": "Genel tür oluşturma işlemi, fazla ayrıntılı ve büyük olasılıkla sınırsız.", + "Getter_and_setter_accessors_do_not_agree_in_visibility_2379": "Alıcı ve ayarlayıcı erişimcileri görünürlükte anlaşamıyor.", + "Global_module_exports_may_only_appear_at_top_level_1316": "Genel modül dışarı aktarmaları yalnızca en üst düzeyde görünebilir.", + "Global_module_exports_may_only_appear_in_declaration_files_1315": "Genel modül dışarı aktarmaları yalnızca bildirim dosyalarında görünebilir.", + "Global_module_exports_may_only_appear_in_module_files_1314": "Genel modül dışarı aktarmaları yalnızca modül dosyalarında görünebilir.", + "Global_type_0_must_be_a_class_or_interface_type_2316": "'{0}' genel türü, bir sınıf veya arabirim türü olmalıdır.", + "Global_type_0_must_have_1_type_parameter_s_2317": "'{0}' genel türü, {1} türünde parametre içermelidir.", + "Hexadecimal_digit_expected_1125": "Onaltılık basamak bekleniyor.", + "Identifier_expected_0_is_a_reserved_word_in_strict_mode_1212": "Tanımlayıcı bekleniyor. '{0}', katı modda ayrılmış bir sözcüktür.", + "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_stric_1213": "Tanımlayıcı bekleniyor. '{0}', katı modda ayrılmış bir sözcüktür. Sınıf tanımları otomatik olarak katı moddadır.", + "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode_1214": "Tanımlayıcı bekleniyor. '{0}', katı modda ayrılmış bir sözcüktür. Modüller otomatik olarak katı moddadır.", + "Identifier_expected_1003": "Tanımlayıcı bekleniyor.", + "Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules_1216": "Tanımlayıcı bekleniyor. '__esModule', ECMAScript modülleri dönüştürülürken, dışarı aktarılan bir işaretçi olarak ayrılmış.", + "Ignore_this_error_message_90019": "Bu hata iletisini yoksay", + "Implement_all_inherited_abstract_classes_95040": "Devralınan tüm soyut sınıfları uygula", + "Implement_all_unimplemented_interfaces_95032": "Uygulanmayan tüm arabirimleri uygula", + "Implement_inherited_abstract_class_90007": "Devralınan soyut sınıfı uygula", + "Implement_interface_0_90006": "'{0}' arabirimini uygula", + "Implements_clause_of_exported_class_0_has_or_is_using_private_name_1_4019": "'{1}' özel adına sahip veya bu adı kullanan '{0}' dışarı aktarılan sınıfının yan tümcesini uygular.", + "Import_0_from_module_1_90013": "\"{1}\" modülünden '{0}' öğesini içeri aktar", + "Import_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_import_Asterisk_as_1202": "ECMAScript modülleri hedeflenirken içeri aktarma ataması kullanılamaz. Bunun yerine 'import * as ns from \"mod\"', 'import {a} from \"mod\"', 'import d from \"mod\"' veya başka bir modül biçimi kullanmayı deneyin.", + "Import_declaration_0_is_using_private_name_1_4000": "'{0}' içeri aktarma bildirimi, '{1}' özel adına sahip veya bu adı kullanıyor.", + "Import_declaration_conflicts_with_local_declaration_of_0_2440": "İçeri aktarma bildirimi, yerel '{0}' bildirimiyle çakışıyor.", + "Import_declarations_in_a_namespace_cannot_reference_a_module_1147": "Ad alanındaki içeri aktarma bildirimleri bir modüle başvuramaz.", + "Import_emit_helpers_from_tslib_6139": "'Tslib'den yayma yardımcılarını içeri aktar.", + "Import_may_be_converted_to_a_default_import_80003": "İçeri aktarma varsayılan bir içeri aktarmaya dönüştürülebilir.", + "Import_name_cannot_be_0_2438": "İçeri aktarma adı '{0}' olamaz.", + "Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relati_2439": "Çevresel modül bildirimindeki içeri veya dışarı aktarma bildirimi, göreli modül adı aracılığıyla modüle başvuramaz.", + "Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_mod_2667": "Modül genişletmelerinde içeri aktarmalara izin verilmez. Bunları, kapsayan dış modüle taşımanız önerilir.", + "In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066": "Çevresel sabit listesi bildirimlerinde, üye başlatıcısı sabit ifade olmalıdır.", + "In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enu_2432": "Birden fazla bildirime sahip sabit listesinde yalnızca bir bildirim ilk sabit listesi öğesine ait başlatıcıyı atlayabilir.", + "In_const_enum_declarations_member_initializer_must_be_constant_expression_2474": "'const' sabit listesi bildirimlerinde, üye başlatıcısı sabit ifade olmalıdır.", + "Include_modules_imported_with_json_extension_6197": "'.json' uzantısıyla içeri aktarılan modülleri dahil et", + "Index_signature_in_type_0_only_permits_reading_2542": "'{0}' türündeki dizin imzası yalnızca okumaya izin veriyor.", + "Index_signature_is_missing_in_type_0_2329": "'{0}' türündeki dizin imzası yok.", + "Index_signatures_are_incompatible_2330": "Dizin imzaları uyumsuz.", + "Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local_2395": "'{0}' birleştirilmiş bildirimindeki bildirimlerin tümü dışarı aktarılmış veya yerel olmalıdır.", + "Infer_all_types_from_usage_95023": "Tüm türleri kullanımdan çıkar", + "Infer_parameter_types_from_usage_95012": "Parametre türleri için kullanımdan çıkarım yap", + "Infer_type_of_0_from_usage_95011": "'{0}' türü için kullanımdan çıkarım yap", + "Initialize_property_0_in_the_constructor_90020": "Oluşturucu içinde '{0}' özelliğini başlat", + "Initialize_static_property_0_90021": "'{0}' statik özelliğini başlat", + "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301": "'{0}' örnek üyesi değişkeninin başlatıcısı, oluşturucuda bildirilen '{1}' tanımlayıcısına başvuramaz.", + "Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it_2373": "'{0}' parametresinin başlatıcısı, kendinden sonra bildirilen '{1}' tanımlayıcısına başvuramaz.", + "Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value_2525": "Başlatıcı bu bağlama öğesi için bir değer sağlamıyor ve bağlama öğesi varsayılan değere sahip değil.", + "Initializers_are_not_allowed_in_ambient_contexts_1039": "Çevresel bağlamlarda başlatıcılara izin verilmez.", + "Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file_6070": "Bir TypeScript projesi başlatır ve bir tsconfig.json dosyası oluşturur.", + "Insert_command_line_options_and_files_from_a_file_6030": "Dosyadaki komut satırı seçeneklerini ve dosyaları ekleyin.", + "Install_0_95014": "'{0}' yükle", + "Install_all_missing_types_packages_95033": "Tüm eksik tür paketlerini yükle", + "Interface_0_cannot_simultaneously_extend_types_1_and_2_2320": "'{0}' arabirimi, aynı anda '{1}' ve '{2}' türlerini genişletemez.", + "Interface_0_incorrectly_extends_interface_1_2430": "'{0}' arabirimi, '{1}' arabirimini yanlış genişletiyor.", + "Interface_declaration_cannot_have_implements_clause_1176": "Arabirim bildirimi, 'implements' yan tümcesine sahip olamaz.", + "Interface_name_cannot_be_0_2427": "Arabirim adı '{0}' olamaz.", + "Invalid_character_1127": "Geçersiz karakter.", + "Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augm_2665": "Genişletmedeki modül adı geçersiz. '{0}' modülü, '{1}' konumundaki türü belirsiz ve genişletilemeyen bir modüle çözümleniyor.", + "Invalid_module_name_in_augmentation_module_0_cannot_be_found_2664": "Genişletmedeki modül adı geçersiz; '{0}' adlı modül bulunamıyor.", + "Invalid_reference_directive_syntax_1084": "Geçersiz 'reference' yönergesi söz dizimi.", + "Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode_1210": "Geçersiz '{0}' kullanımı. Sınıf tanımları otomatik olarak katı moddadır.", + "Invalid_use_of_0_Modules_are_automatically_in_strict_mode_1215": "Geçersiz '{0}' kullanımı. Modüller otomatik olarak katı moddadır.", + "Invalid_use_of_0_in_strict_mode_1100": "Katı modda geçersiz '{0}' kullanımı.", + "Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name_5067": "'jsxFactory' değeri geçersiz. '{0}' geçerli bir tanımlayıcı veya tam ad değil.", + "Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier_5059": "'--reactNamespace' için geçersiz değer. '{0}' geçerli bir tanımlayıcı değil.", + "JSDoc_0_1_does_not_match_the_extends_2_clause_8023": "JSDoc '@{0} {1}', 'extends {2}' yan tümcesiyle eşleşmiyor.", + "JSDoc_0_is_not_attached_to_a_class_8022": "JSDoc '@{0}' bir sınıfa eklenmemiş.", + "JSDoc_may_only_appear_in_the_last_parameter_of_a_signature_8028": "JSDoc '...' yalnızca bir imzanın son parametresi içinde görünebilir.", + "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_8024": "JSDoc '@param' etiketinin adı '{0}' ancak bu ada sahip bir parametre yok.", + "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_h_8029": "JSDoc '@param' etiketi '{0}' adına sahip ancak bu ada sahip bir parametre yok. Bir dizi türü olsaydı 'arguments' ile eşleşirdi.", + "JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags_8021": "JSDoc '@typedef' etiketi bir tür ek açıklamasına sahip olmalıdır veya sonrasında '@property' ya da '@member' etiketlerinden biri gelmelidir.", + "JSDoc_types_can_only_be_used_inside_documentation_comments_8020": "JSDoc türleri yalnızca belge açıklamalarının içinde kullanılabilir.", + "JSDoc_types_may_be_moved_to_TypeScript_types_80004": "JSDoc türleri TypeScript türlerine taşınabilir.", + "JSX_attribute_expected_17003": "JSX özniteliği bekleniyor.", + "JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000": "JSX özniteliklerine yalnızca boş olmayan 'expression' ifadesi atanabilir.", + "JSX_element_0_has_no_corresponding_closing_tag_17008": "'{0}' adlı JSX öğesine karşılık gelen bir kapatma etiketi yok.", + "JSX_element_attributes_type_0_may_not_be_a_union_type_2600": "JSX öğesinin öznitelik türü '{0}', birleşim türü olamaz.", + "JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property_2607": "JSX öğe sınıfı, '{0}' özelliğine sahip olmadığı için öznitelikleri desteklemiyor.", + "JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists_7026": "Herhangi bir arabirim 'JSX.{0}' öğesi olmadığı için JSX öğesi örtük olarak 'any' türüne sahip.", + "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602": "Genel türdeki 'JSX.Element' öğesi olmadığı için JSX öğesi örtük olarak 'any' türüne sahip.", + "JSX_element_type_0_does_not_have_any_construct_or_call_signatures_2604": "JSX öğesi türü '{0}', oluşturma veya çağrı imzasına sahip değil.", + "JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements_2605": "JSX öğesi türü '{0}', JSX öğelerine ait bir oluşturucu işlevi değil.", + "JSX_elements_cannot_have_multiple_attributes_with_the_same_name_17001": "JSX öğeleri aynı ada sahip birden fazla özniteliğe sahip olamaz.", + "JSX_expressions_must_have_one_parent_element_2657": "JSX ifadelerinin bir üst öğesi olmalıdır.", + "JSX_fragment_has_no_corresponding_closing_tag_17014": "JSX parçasına karşılık gelen bir kapatma etiketi yok.", + "JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma_17017": "Satır içi JSX fabrika pragma'sı kullanılırken JSX parçası desteklenmez", + "JSX_fragment_is_not_supported_when_using_jsxFactory_17016": "JSX parçası --jsxFactory kullanılırken desteklenmiyor", + "JSX_spread_child_must_be_an_array_type_2609": "JSX yayılma alt öğesi, bir dizi türü olmalıdır.", + "Jump_target_cannot_cross_function_boundary_1107": "Atlama hedefi işlev sınırını geçemez.", + "KIND_6034": "TÜR", + "LOCATION_6037": "KONUM", + "Language_service_is_disabled_9004": "Dil hizmeti devre dışı.", + "Left_side_of_comma_operator_is_unused_and_has_no_side_effects_2695": "Virgül işlecinin sol tarafı kullanılmıyor ve herhangi bir yan etkisi yok.", + "Line_break_not_permitted_here_1142": "Burada satır sonuna izin verilmez.", + "Line_terminator_not_permitted_before_arrow_1200": "Oktan önce satır sonlandırıcısına izin verilmez.", + "List_of_folders_to_include_type_definitions_from_6161": "Eklenecek tür tanımlarının alınacağı klasörlerin listesi.", + "List_of_language_service_plugins_6181": "Dil hizmeti eklentilerinin listesi.", + "List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime_6168": "Birleştirilmiş içerikleri, çalışma zamanında proje yapısını temsil eden kök klasörlerin listesi.", + "Loading_0_from_the_root_dir_1_candidate_location_2_6109": "'{1}' kök dizininden '{0}' yükleniyor; aday konumu: '{2}'.", + "Loading_module_0_from_node_modules_folder_target_file_type_1_6098": "'node_modules' klasöründen '{0}' modülü yükleniyor, hedef dosya türü '{1}'.", + "Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1_6095": "Modül, dosya/klasör olarak yükleniyor; aday modül konumu '{0}'; hedef dosya türü '{1}'.", + "Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1_6048": "Yerel ayar, veya - biçiminde olmalıdır. Örneğin, '{0}' veya '{1}'.", + "Longest_matching_prefix_for_0_is_1_6108": "'{0}' için eşleşen en uzun ön ek: '{1}'.", + "Looking_up_in_node_modules_folder_initial_location_0_6125": "'node_modules' klasöründe aranıyor; ilk konum: '{0}'.", + "Make_all_super_calls_the_first_statement_in_their_constructor_95036": "Tüm 'super()' çağrılarını kendi oluşturucularının ilk deyimi yap", + "Make_super_call_the_first_statement_in_the_constructor_90002": "Oluşturucudaki ilk deyime 'super()' tarafından çağrı yapılmasını sağla", + "Mapped_object_type_implicitly_has_an_any_template_type_7039": "Eşleştirilmiş nesne türü örtük olarak 'any' şablon türüne sahip.", + "Member_0_implicitly_has_an_1_type_7008": "'{0}' üyesi örtük olarak '{1}' türüne sahip.", + "Merge_conflict_marker_encountered_1185": "Birleştirme çakışması işaretçisiyle karşılaşıldı.", + "Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_d_2652": "'{0}' birleştirilen bildirimi, varsayılan bir dışarı aktarma bildirimini içeremez. Bunun yerine ayrı bir 'export default {0}' bildirimi eklemeyi göz önünde bulundurun.", + "Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constru_17013": "'{0}' meta-özelliğine yalnızca bir işlev bildiriminin, işlev ifadesinin veya oluşturucunun gövdesinde izin verilir.", + "Method_0_cannot_have_an_implementation_because_it_is_marked_abstract_1245": "'{0}' metodu abstract olarak işaretlendiğinden bir uygulamaya sahip olamaz.", + "Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4101": "Dışarı aktarılan arabirimin '{0}' metodu, '{2}' özel modülündeki '{1}' adına sahip veya bu adı kullanıyor.", + "Method_0_of_exported_interface_has_or_is_using_private_name_1_4102": "Dışarı aktarılan arabirimin '{0}' metodu, '{1}' özel adına sahip veya bu adı kullanıyor.", + "Modifiers_cannot_appear_here_1184": "Değiştiriciler burada görüntülenemez.", + "Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_1340": "'{0}' modülü bir türe başvurmuyor ancak burada bir tür olarak kullanılmış.", + "Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here_1339": "'{0}' modülü bir değere başvurmuyor ancak burada bir değer olarak kullanılmış.", + "Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambig_2308": "{0} modülü, '{1}' adlı bir üyeyi zaten dışarı aktardı. Belirsizliği çözmek için açık olarak yeniden dışarı aktarmayı göz önünde bulundurun.", + "Module_0_has_no_default_export_1192": "'{0}' modülü için varsayılan dışarı aktarma yok.", + "Module_0_has_no_exported_member_1_2305": "'{0}' modülü, dışarı aktarılan '{1}' üyesine sahip değil.", + "Module_0_has_no_exported_member_1_Did_you_mean_2_2724": "{0}' modülünün dışarı aktarılan '{1}' adlı bir üyesi yok. Şunu mu demek istediniz: '{2}'?", + "Module_0_is_hidden_by_a_local_declaration_with_the_same_name_2437": "'{0}' modülü, aynı ada sahip bir yerel bildirim tarafından gizleniyor.", + "Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct_2497": "'{0}' modülü, modül olmayan bir varlığa çözümleniyor ve bu oluşturma ile içeri aktarılamaz.", + "Module_0_uses_export_and_cannot_be_used_with_export_Asterisk_2498": "'{0}' modülü 'export =' kullanıyor ve 'export *' ile birlikte kullanılamaz.", + "Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified_6145": "'{1}' dosyası değiştirilmediğinden '{0}' modülü, bu dosyada bildirilen çevresel modül olarak çözümlendi.", + "Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1_6144": "'{0}' modülü, '{1}' dosyasında yerel olarak bildirilmiş çevresel modül olarak çözümlendi.", + "Module_0_was_resolved_to_1_but_jsx_is_not_set_6142": "'{0}' modülü '{1}' olarak çözüldü ancak '--jsx' ayarlanmadı.", + "Module_Resolution_Options_6174": "Modül Çözümleme Seçenekleri", + "Module_name_0_matched_pattern_1_6092": "Modül adı: '{0}', eşleşen desen: '{1}'.", + "Module_name_0_was_not_resolved_6090": "======== '{0}' modül adı çözümlenemedi. ========", + "Module_name_0_was_successfully_resolved_to_1_6089": "======== '{0}' modül adı '{1}' öğesine başarıyla çözümlendi. ========", + "Module_resolution_kind_is_not_specified_using_0_6088": "Modül çözümleme türü belirtilmedi, '{0}' kullanılıyor.", + "Module_resolution_using_rootDirs_has_failed_6111": "'rootDirs' kullanarak modül çözümleme başarısız oldu.", + "Move_to_a_new_file_95049": "Yeni bir dosyaya taşı", + "Multiple_consecutive_numeric_separators_are_not_permitted_6189": "Birbirini izleyen birden çok sayısal ayırıcıya izin verilmez.", + "Multiple_constructor_implementations_are_not_allowed_2392": "Birden çok oluşturucu uygulamasına izin verilmez.", + "NEWLINE_6061": "YENİ SATIR", + "Named_property_0_of_types_1_and_2_are_not_identical_2319": "'{1}' ve '{2}' türündeki '{0}' adlı özellikler aynı değil.", + "Namespace_0_has_no_exported_member_1_2694": "'{0}' ad alanında dışarı aktarılan '{1}' üyesi yok.", + "No_base_constructor_has_the_specified_number_of_type_arguments_2508": "Hiçbir temel oluşturucu, belirtilen tür bağımsız değişkeni sayısına sahip değil.", + "No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2_18003": "'{0}' yapılandırma dosyasında giriş bulunamadı. Belirtilen 'include' yolları: '{1}', 'exclude' yolları: '{2}'.", + "Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2_2515": "Soyut olmayan '{0}' sınıfı, '{2}' sınıfından devralınan '{1}' soyut üyesini uygulamıyor.", + "Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1_2653": "Soyut olmayan sınıf ifadesi, '{1}' sınıfından devralınan '{0}' soyut üyesini uygulamıyor.", + "Not_all_code_paths_return_a_value_7030": "Tüm kod yolları bir değer döndürmez.", + "Numeric_index_type_0_is_not_assignable_to_string_index_type_1_2413": "'{0}' sayısal dizin türü, '{1}' dize dizini türüne atanamaz.", + "Numeric_separators_are_not_allowed_here_6188": "Burada sayısal ayırıcılara izin verilmez.", + "Object_is_of_type_unknown_2571": "Nesne 'unknown' türünde.", + "Object_is_possibly_null_2531": "Nesne büyük olasılıkla 'null'.", + "Object_is_possibly_null_or_undefined_2533": "Nesne büyük olasılıkla 'null' veya 'undefined'.", + "Object_is_possibly_undefined_2532": "Nesne büyük olasılıkla 'undefined'.", + "Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1_2353": "Nesne sabit değeri yalnızca bilinen özellikleri belirtebilir ve '{0}', '{1}' türünde değil.", + "Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_writ_2561": "Nesne sabit değerinde yalnızca bilinen özellikler belirtilebilir, ancak '{0}', '{1}' türünde yok. '{2}' yazmak mı istediniz?", + "Object_literal_s_property_0_implicitly_has_an_1_type_7018": "'{0}' nesne sabit değeri özelliği, örtük olarak '{1}' türüne sahip.", + "Octal_digit_expected_1178": "Sekizli basamak bekleniyor.", + "Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0_8017": "Sekizlik sabit değerli türlerde ES2015 söz dizimi kullanılmalıdır. '{0}' söz dizimini kullanın.", + "Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0_8018": "Sabit listesi üyelerinin başlatıcısında sekizlik sabit değerlere izin verilmez. '{0}' söz dizimini kullanın.", + "Octal_literals_are_not_allowed_in_strict_mode_1121": "Katı modda sekizlik sabit değerlere izin verilmez.", + "Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0_1085": "ECMAScript 5 ve üzeri hedeflenirken sekizlik sabit değerler kullanılamaz. '{0}' söz dizimini kullanın.", + "Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement_1091": "'for...in' deyiminde yalnızca tek bir değişken bildirimine izin verilir.", + "Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement_1188": "'for...of' deyiminde yalnızca tek bir değişken bildirimine izin verilir.", + "Only_a_void_function_can_be_called_with_the_new_keyword_2350": "'new' anahtar sözcüğüyle yalnızca void işlevi çağrılabilir.", + "Only_ambient_modules_can_use_quoted_names_1035": "Yalnızca çevresel modüller tırnak içinde ad kullanabilir.", + "Only_amd_and_system_modules_are_supported_alongside_0_6082": "--{0} ile birlikte yalnızca 'amd' ve 'system' modülleri desteklenir.", + "Only_emit_d_ts_declaration_files_6014": "Yalnızca '.d.ts' bildirim dosyalarını yayımla.", + "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002": "Sınıf 'extends' yan tümceleri içinde, şu an için yalnızca isteğe bağlı tür bağımsız değişkenlerine sahip tanımlayıcılar/tam adlar destekleniyor.", + "Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword_2340": "'super' anahtar sözcüğüyle yalnızca temel sınıfa ait ortak ve korunan metotlara erişilebilir.", + "Operator_0_cannot_be_applied_to_types_1_and_2_2365": "'{0}' işleci, '{1}' ve '{2}' türüne uygulanamaz.", + "Option_0_can_only_be_specified_in_tsconfig_json_file_6064": "'{0}' seçeneği yalnızca 'tsconfig.json' dosyasında belirtilebilir.", + "Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided_5051": "'{0} seçeneği yalnızca '--inlineSourceMap' veya '--sourceMap' seçeneği sağlandığında kullanılabilir.", + "Option_0_cannot_be_specified_with_option_1_5053": "'{0}' seçeneği, '{1}' seçeneği ile belirtilemez.", + "Option_0_cannot_be_specified_without_specifying_option_1_5052": "'{0}' seçeneği, '{1}' seçeneği belirtilmeden belirtilemez.", + "Option_0_cannot_be_specified_without_specifying_option_1_or_option_2_5069": "'{1}' seçeneği veya '{2}' seçeneği belirtilmeden '{0}' seçeneği belirtilemez.", + "Option_0_should_have_array_of_strings_as_a_value_6103": "'{0}' seçeneği değer olarak, dizelerden oluşan bir dizi içermelidir.", + "Option_build_must_be_the_first_command_line_argument_6369": "'--build' seçeneği ilk komut satırı bağımsız değişkeni olmalıdır.", + "Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES_5047": "'isolatedModules' seçeneği, yalnızca '--module' sağlandığında veya 'target' seçeneği 'ES2015' veya daha yüksek bir sürüm değerine sahip olduğunda kullanılabilir.", + "Option_paths_cannot_be_used_without_specifying_baseUrl_option_5060": "'Paths' seçeneği, '--baseUrl' seçeneği belirtilmeden kullanılamaz.", + "Option_project_cannot_be_mixed_with_source_files_on_a_command_line_5042": "'project' seçeneği, komut satırındaki kaynak dosyalarıyla karıştırılamaz.", + "Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070": "'node' modül çözümleme stratejisi olmadan '--resolveJsonModule' seçeneği belirtilemez.", + "Options_0_and_1_cannot_be_combined_6370": "'{0}' ve '{1}' seçenekleri birleştirilemez.", + "Options_Colon_6027": "Seçenekler:", + "Output_directory_for_generated_declaration_files_6166": "Oluşturulan bildirim dosyaları için çıkış dizini.", + "Output_file_0_from_project_1_does_not_exist_6309": "'{1}' projesinden '{0}' çıkış dosyası yok", + "Output_file_0_has_not_been_built_from_source_file_1_6305": "Çıkış dosyası '{0}' '{1}' kaynak dosyasından oluşturulmamış.", + "Overload_signature_is_not_compatible_with_function_implementation_2394": "Aşırı yükleme imzası işlev uygulamasıyla uyumlu değil.", + "Overload_signatures_must_all_be_abstract_or_non_abstract_2512": "Aşırı yükleme imzalarının hepsi soyut veya soyut olmayan olmalıdır.", + "Overload_signatures_must_all_be_ambient_or_non_ambient_2384": "Aşırı yükleme imzalarının tümü çevresel veya çevresel olmayan türde olmalıdır.", + "Overload_signatures_must_all_be_exported_or_non_exported_2383": "Aşırı yükleme imzalarının hepsi dışarı aktarılmış veya dışarı aktarılmamış olmalıdır.", + "Overload_signatures_must_all_be_optional_or_required_2386": "Aşırı yükleme imzalarının tümü isteğe bağlı veya gerekli olmalıdır.", + "Overload_signatures_must_all_be_public_private_or_protected_2385": "Aşırı yükleme imzalarının tümü ortak, özel veya korumalı olmalıdır.", + "Parameter_0_cannot_be_referenced_in_its_initializer_2372": "'{0}' parametresine başlatıcısında başvurulamaz.", + "Parameter_0_implicitly_has_an_1_type_7006": "'{0}' parametresi örtük olarak '{1}' türüne sahip.", + "Parameter_0_is_not_in_the_same_position_as_parameter_1_1227": "'{0}' parametresi, '{1}' parametresi ile aynı konumda değil.", + "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4066": "Dışarı aktarılan arabirimdeki çağrı imzasının '{0}' parametresi, '{2}' özel modülündeki '{1}' adına sahip veya bu adı kullanıyor.", + "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4067": "Dışarı aktarılan arabirimdeki çağrı imzasının '{0}' parametresi, '{1}' özel adına sahip veya bu adı kullanıyor.", + "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_can_4061": "Dışarı aktarılan sınıftaki oluşturucunun '{0}' parametresi, {2} dış modülündeki '{1}' adına sahip veya bu adı kullanıyor, ancak adlandırılamıyor.", + "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2_4062": "Dışarı aktarılan sınıftaki oluşturucunun '{0}' parametresi, '{2}' özel modülündeki '{1}' adına sahip veya bu adı kullanıyor.", + "Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1_4063": "Dışarı aktarılan sınıftaki oluşturucunun '{0}' parametresi, '{1}' özel adına sahip veya bu adı kullanıyor.", + "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_mod_4064": "Dışarı aktarılan arabirimdeki oluşturucu imzasının '{0}' parametresi, '{2}' özel modülündeki '{1}' adına sahip veya bu adı kullanıyor.", + "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4065": "Dışarı aktarılan arabirimdeki oluşturucu imzasının '{0}' parametresi, '{1}' özel adına sahip veya bu adı kullanıyor.", + "Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4076": "Dışarı aktarılan işlevin '{0}' parametresi, {2} dış modülündeki '{1}' adına sahip veya bu adı kullanıyor, ancak adlandırılamıyor.", + "Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2_4077": "Dışarı aktarılan işlevin '{0}' parametresi, '{2}' özel modülündeki '{1}' adına sahip veya bu adı kullanıyor.", + "Parameter_0_of_exported_function_has_or_is_using_private_name_1_4078": "Dışarı aktarılan işlevin '{0}' parametresi, '{1}' özel adına sahip veya bu adı kullanıyor.", + "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4091": "Dışarı aktarılan arabirimin dizin imzasındaki '{0}' parametresi, '{2}' adlı özel modüldeki '{1}' adına sahip ya da bu adı kullanıyor.", + "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1_4092": "Dışarı aktarılan arabirimin dizin imzasındaki '{0}' parametresi, '{1}' adına sahip ya da bu adı kullanıyor.", + "Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4074": "Dışarı aktarılan arabirimdeki metodun '{0}' parametresi, '{2}' özel modülündeki '{1}' adına sahip veya bu adı kullanıyor.", + "Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4075": "Dışarı aktarılan arabirimdeki metodun '{0}' parametresi, '{1}' özel adına sahip veya bu adı kullanıyor.", + "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_c_4071": "Dışarı aktarılan sınıftaki ortak metodun '{0}' parametresi, {2} dış modülündeki '{1}' adına sahip veya bu adı kullanıyor, ancak adlandırılamıyor.", + "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4072": "Dışarı aktarılan sınıftaki ortak metodun '{0}' parametresi, '{2}' özel modülündeki '{1}' adına sahip veya bu adı kullanıyor.", + "Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4073": "Dışarı aktarılan sınıftaki ortak metodun '{0}' parametresi, '{1}' özel adına sahip veya bu adı kullanıyor.", + "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module__4068": "Dışarı aktarılan sınıftaki ortak metodun '{0}' parametresi, {2} dış modülündeki '{1}' adına sahip veya bu adı kullanıyor, ancak adlandırılamıyor.", + "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4069": "Dışarı aktarılan sınıftaki statik metodun '{0}' parametresi, '{2}' özel modülündeki '{1}' adına sahip veya bu adı kullanıyor.", + "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4070": "Dışarı aktarılan sınıftaki statik metodun '{0}' parametresi, '{1}' özel adına sahip veya bu adı kullanıyor.", + "Parameter_cannot_have_question_mark_and_initializer_1015": "Parametre soru işareti ve başlatıcı içeremez.", + "Parameter_declaration_expected_1138": "Parametre bildirimi bekleniyor.", + "Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2_4036": "Dışarı aktarılan sınıftaki genel ayarlayıcı '{0}' için parametre türü, '{2}' özel modülündeki '{1}' adına sahip veya bu adı kullanıyor.", + "Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_private_name_1_4037": "Dışarı aktarılan sınıftaki genel ayarlayıcı '{0}' için parametre türü, '{1}' özel adına sahip veya bu adı kullanıyor.", + "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_name_1_from_private_mod_4034": "Dışarı aktarılan sınıftaki genel statik ayarlayıcı '{0}' için parametre türü, '{2}' özel modülündeki '{1}' adına sahip veya bu adı kullanıyor.", + "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1_4035": "Dışarı aktarılan sınıftaki genel statik ayarlayıcı '{0}' için parametre türü, '{1}' özel adına sahip veya bu adı kullanıyor.", + "Parse_in_strict_mode_and_emit_use_strict_for_each_source_file_6141": "Katı modda ayrıştırın ve her kaynak dosya için \"use strict\" kullanın.", + "Pattern_0_can_have_at_most_one_Asterisk_character_5061": "'{0}' deseni en fazla bir adet '*' karakteri içerebilir.", + "Prefix_0_with_an_underscore_90025": "'{0}' için ön ek olarak alt çizgi kullan", + "Prefix_all_unused_declarations_with_where_possible_95025": "Mümkün olduğunda tüm kullanılmayan bildirimlerin başına '_' ekle", + "Print_names_of_files_part_of_the_compilation_6155": "Derlemenin parçası olan dosyaların adlarını yazdırın.", + "Print_names_of_generated_files_part_of_the_compilation_6154": "Oluşturulan dosyalardan, derlemenin parçası olanların adlarını yazdırın.", + "Print_the_compiler_s_version_6019": "Derleyici sürümünü yazdır.", + "Print_this_message_6017": "Bu iletiyi yazdır.", + "Project_0_can_t_be_built_because_its_dependency_1_has_errors_6363": "'{0}' projesinin '{1}' bağımlılığında hatalar olduğundan proje derlenemiyor", + "Project_0_is_out_of_date_because_its_dependency_1_is_out_of_date_6353": "'{0}' projesinin '{1}' bağımlılığı güncel olmadığından proje güncel değil", + "Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2_6350": "En eski '{1}' çıkışı en yeni '{2}' girişinden daha eski olduğundan '{0}' projesi güncel değil", + "Project_0_is_out_of_date_because_output_file_1_does_not_exist_6352": "Çıkış dosyası '{1}' mevcut olmadığından '{0}' projesi güncel değil", + "Project_0_is_up_to_date_6361": "'{0}' projesi güncel", + "Project_0_is_up_to_date_because_newest_input_1_is_older_than_oldest_output_2_6351": "En yeni '{1}' girişi en eski '{2}' çıkışından daha eski olduğundan '{0}' projesi güncel", + "Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies_6354": "'{0}' projesi bağımlılıklarından d.ts dosyaları ile güncel", + "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202": "Proje başvuruları döngüsel bir grafik formu oluşturamaz. Döngü tespit edildi: {0}", + "Projects_in_this_build_Colon_0_6355": "Bu derlemedeki projeler: {0}", + "Projects_to_reference_6300": "Başvurulacak projeler", + "Property_0_does_not_exist_on_const_enum_1_2479": "'{0}' özelliği, '{1}' 'const' sabit listesi üzerinde değil.", + "Property_0_does_not_exist_on_type_1_2339": "'{0}' özelliği, '{1}' türünde değil.", + "Property_0_does_not_exist_on_type_1_Did_you_forget_to_use_await_2570": "'{0}' özelliği '{1}' türü üzerinde yok. 'await' kullanmayı mı unuttunuz?", + "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551": "'{0}' özelliği '{1}' türünde yok. Bunu mu demek istediniz: '{2}'?", + "Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1_2546": "'{0}' özelliği, çakışan bildirimler içeriyor ve '{1}' türü içinde erişilebilir değil.", + "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor_2564": "'{0}' özelliği başlatıcı içermiyor ve oluşturucuda kesin olarak atanmamış.", + "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033": "'{0}' özelliği, get erişimcisinin dönüş türü ek açıklaması olmadığı için örtük olarak 'any' türü içeriyor.", + "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032": "'{0}' özelliği, set erişimcisinin parametre türü ek açıklaması olmadığı için örtük olarak 'any' türü içeriyor.", + "Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2_2416": "'{1}' türündeki '{0}' özelliği, '{2}' temel türündeki aynı özelliğe atanamaz.", + "Property_0_in_type_1_is_not_assignable_to_type_2_2603": "'{1}' türündeki '{0}' özelliği, '{2}' türüne atanamaz.", + "Property_0_is_declared_but_its_value_is_never_read_6138": "'{0}' özelliği bildirildi ancak değeri hiç okunmadı.", + "Property_0_is_incompatible_with_index_signature_2530": "'{0}' özelliği, dizin imzasıyla uyumsuz.", + "Property_0_is_missing_in_type_1_2324": "'{0}' özelliği '{1}' türünde değil.", + "Property_0_is_optional_in_type_1_but_required_in_type_2_2327": "'{0}' özelliği, '{1}' türünde isteğe bağlıdır, ancak '{2}' türünde gereklidir.", + "Property_0_is_private_and_only_accessible_within_class_1_2341": "'{0}' özelliği özeldir ve yalnızca '{1}' sınıfı içinden erişilebilir.", + "Property_0_is_private_in_type_1_but_not_in_type_2_2325": "'{0}' özelliği, '{1}' türünde özel, '{2}' türünde özel değildir.", + "Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1_2446": "'{0}' özelliği korumalıdır ve yalnızca '{1}' sınıfının örneği aracılığıyla erişilebilir.", + "Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses_2445": "'{0}' özelliği korumalıdır ve yalnızca '{1}' sınıfı içinden ve alt sınıflarından erişilebilir.", + "Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2_2443": "'{0}' özelliği korumalıdır; ancak '{1}' türü, '{2}' öğesinden türetilmiş bir sınıf değildir.", + "Property_0_is_protected_in_type_1_but_public_in_type_2_2444": "'{0}' özelliği '{1}' türünde korumalı, '{2}' türünde ise ortaktır.", + "Property_0_is_used_before_being_assigned_2565": "'{0}' özelliği atanmadan önce kullanıldı.", + "Property_0_of_JSX_spread_attribute_is_not_assignable_to_target_property_2606": "JSX yayılma özniteliğine ait '{0}' özelliği, hedef özelliğe atanamaz.", + "Property_0_of_exported_class_expression_may_not_be_private_or_protected_4094": "Dışarı aktarılan sınıf ifadesinin '{0}' özelliği, özel veya korumalı olmayabilir.", + "Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4032": "Dışarı aktarılan arabirimin '{0}' özelliği, '{2}' özel modülündeki '{1}' adına sahip veya bu adı kullanıyor.", + "Property_0_of_exported_interface_has_or_is_using_private_name_1_4033": "Dışarı aktarılan arabirimin '{0}' özelliği, '{1}' özel adına sahip veya bu adı kullanıyor.", + "Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2_2412": "'{1}' türünün '{0}' özelliği, '{2}' sayısal dizin türüne atanamaz.", + "Property_0_of_type_1_is_not_assignable_to_string_index_type_2_2411": "'{1}' türünün '{0}' özelliği, '{2}' dize dizini türüne atanamaz.", + "Property_assignment_expected_1136": "Özellik ataması bekleniyor.", + "Property_destructuring_pattern_expected_1180": "Özellik yok etme deseni bekleniyor.", + "Property_or_signature_expected_1131": "Özellik veya imza bekleniyor.", + "Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_li_1328": "Özellik değeri yalnızca, dize sabit değeri, sayısal sabit değer, 'true', 'false', 'null', nesne sabit değeri veya dizi sabit değeri olabilir.", + "Provide_full_support_for_iterables_in_for_of_spread_and_destructuring_when_targeting_ES5_or_ES3_6179": "'ES5' veya 'ES3' hedefleniyorsa, 'for-of' içindeki yinelenebilir öğeler için yayılma ve yok etmeye yönelik tam destek sağlayın.", + "Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4098": "Dışarı aktarılan sınıfın '{0}' genel metodu, {2} dış modülündeki '{1}' adına sahip veya bu adı kullanıyor, ancak adlandırılamıyor.", + "Public_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4099": "Dışarı aktarılan sınıfın '{0}' genel metodu, '{2}' özel modülündeki '{1}' adına sahip veya bu adı kullanıyor.", + "Public_method_0_of_exported_class_has_or_is_using_private_name_1_4100": "Dışarı aktarılan sınıfın '{0}' genel metodu, '{1}' özel adına sahip veya bu adı kullanıyor.", + "Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_name_4029": "Dışarı aktarılan sınıfın '{0}' ortak özelliği, {2} dış modülündeki '{1}' adına sahip veya bu adı kullanıyor, ancak adlandırılamıyor.", + "Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4030": "Dışarı aktarılan sınıfın '{0}' ortak özelliği, '{2}' özel modülündeki '{1}' adına sahip veya bu adı kullanıyor.", + "Public_property_0_of_exported_class_has_or_is_using_private_name_1_4031": "Dışarı aktarılan sınıfın '{0}' ortak özelliği, '{1}' özel adına sahip veya bu adı kullanıyor.", + "Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_4095": "Dışarı aktarılan sınıfın '{0}' genel statik metodu, {2} dış modülündeki '{1}' adına sahip veya bu adı kullanıyor, ancak adlandırılamıyor.", + "Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4096": "Dışarı aktarılan sınıfın '{0}' genel statik metodu, '{2}' özel modülündeki '{1}' adına sahip veya bu adı kullanıyor.", + "Public_static_method_0_of_exported_class_has_or_is_using_private_name_1_4097": "Dışarı aktarılan sınıfın '{0}' genel statik metodu, '{1}' özel adına sahip veya bu adı kullanıyor.", + "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot__4026": "Dışarı aktarılan sınıfın '{0}' ortak statik özelliği, {2} dış modülündeki '{1}' adına sahip veya bu adı kullanıyor, ancak adlandırılamıyor.", + "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4027": "Dışarı aktarılan sınıfın '{0}' ortak statik özelliği, '{2}' özel modülündeki '{1}' adına sahip veya bu adı kullanıyor.", + "Public_static_property_0_of_exported_class_has_or_is_using_private_name_1_4028": "Dışarı aktarılan sınıfın '{0}' ortak statik özelliği, '{1}' özel adına sahip veya bu adı kullanıyor.", + "Raise_error_on_expressions_and_declarations_with_an_implied_any_type_6052": "Belirtilen 'any' türüne sahip ifade ve bildirimlerde hata oluştur.", + "Raise_error_on_this_expressions_with_an_implied_any_type_6115": "Örtük olarak 'any' türü içeren 'this' ifadelerinde hata tetikle.", + "Redirect_output_structure_to_the_directory_6006": "Çıktı yapısını dizine yeniden yönlendir.", + "Referenced_project_0_must_have_setting_composite_Colon_true_6306": "Başvurulan proje '{0}' \"composite\": true ayarına sahip olmalıdır.", + "Remove_all_unreachable_code_95051": "Tüm erişilemeyen kodları kaldır", + "Remove_all_unused_labels_95054": "Kullanılmayan tüm etiketleri kaldır", + "Remove_braces_from_arrow_function_95060": "Ok işlevinden küme ayraçlarını kaldır", + "Remove_declaration_for_Colon_0_90004": "'{0}' bildirimini kaldır", + "Remove_destructuring_90009": "Yıkmayı kaldır", + "Remove_import_from_0_90005": "'{0}' öğesinden içeri aktarmayı kaldır", + "Remove_unreachable_code_95050": "Erişilemeyen kodları kaldır", + "Remove_unused_label_95053": "Kullanılmayan etiketi kaldır", + "Remove_variable_statement_90010": "Değişken deyimini kaldır", + "Replace_import_with_0_95015": "İçeri aktarma işlemini '{0}' ile değiştirin.", + "Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "İşlevdeki tüm kod yolları bir değer döndürmediğinde hata bildir.", + "Report_errors_for_fallthrough_cases_in_switch_statement_6076": "switch deyiminde sonraki ifadelere geçiş ile ilgili hataları bildir.", + "Report_errors_in_js_files_8019": ".js dosyalarındaki hataları bildirin.", + "Report_errors_on_unused_locals_6134": "Kullanılmayan yerel öğelerdeki hataları bildirin.", + "Report_errors_on_unused_parameters_6135": "Kullanılmayan parametrelerdeki hataları bildirin.", + "Required_type_parameters_may_not_follow_optional_type_parameters_2706": "Gerekli tür parametreleri, isteğe bağlı tür parametrelerini takip edemez.", + "Resolution_for_module_0_was_found_in_cache_from_location_1_6147": "'{0}' modülünün çözümü '{1}' konumundaki önbellekte bulundu.", + "Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols_6195": "'Keyof' değerini yalnızca dize değerli özellik adlarına (sayılar veya simgeler olmadan) çözümleyin.", + "Resolving_from_node_modules_folder_6118": "Node_modules klasöründen çözümleniyor...", + "Resolving_module_0_from_1_6086": "======== '{0}' modülü '{1}' öğesinden çözümleniyor. ========", + "Resolving_module_name_0_relative_to_base_url_1_2_6094": "'{0}' modül adı, '{1}' - '{2}' temel url'sine göre çözümleniyor.", + "Resolving_real_path_for_0_result_1_6130": "'{0}' için gerçek yol çözümleniyor, sonuç: '{1}'.", + "Resolving_type_reference_directive_0_containing_file_1_root_directory_2_6116": "======== '{0}' tür başvurusu yönergesi çözümleniyor, kapsayan dosya: '{1}', kök dizini: '{2}'. ========", + "Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set_6123": "======== '{0}' tür başvuru yönergesi çözümleniyor, içeren dosya '{1}', kök dizin ayarlanmadı. ========", + "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1_6127": "======== '{0}' tür başvurusu yönergesi çözümleniyor, kapsayan dosya ayarlanmadı, kök dizin: '{1}'. ========", + "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set_6128": "======== '{0}' tür başvurusu yönergesi çözümleniyor, kapsayan dosya ayarlanmadı, kök dizin ayarlanmadı. ========", + "Resolving_using_primary_search_paths_6117": "Birincil arama yolları kullanılarak çözümleniyor...", + "Resolving_with_primary_search_path_0_6121": "Birincil arama yolu '{0}' kullanılarak çözümleniyor.", + "Rest_parameter_0_implicitly_has_an_any_type_7019": "'{0}' rest parametresi, örtük olarak 'any[]' türüne sahip.", + "Rest_types_may_only_be_created_from_object_types_2700": "Rest türleri yalnızca nesne türlerinden oluşturulabilir.", + "Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4046": "Dışarı aktarılan arabirimdeki çağrı imzasının dönüş türü, '{1}' özel modülündeki '{0}' adına sahip veya bu adı kullanıyor.", + "Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0_4047": "Dışarı aktarılan arabirimdeki çağrı imzasının dönüş türü, '{0}' özel adına sahip veya bu adı kullanıyor.", + "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_mod_4044": "Dışarı aktarılan arabirimdeki oluşturucu imzasının dönüş türü, '{1}' özel modülündeki '{0}' adına sahip veya bu adı kullanıyor.", + "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0_4045": "Dışarı aktarılan arabirimdeki oluşturucu imzasının dönüş türü, '{0}' özel adına sahip veya bu adı kullanıyor.", + "Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class_2409": "Oluşturucu imzasının dönüş türü, sınıfın örnek türüne atanabilir olmalıdır.", + "Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named_4058": "Dışarı aktarılan işlevin dönüş türü, '{1}' dış modülündeki '{0}' adına sahip veya bu adı kullanıyor, ancak adlandırılamıyor.", + "Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1_4059": "Dışarı aktarılan işlevin dönüş türü, '{1}' özel modülündeki '{0}' adına sahip veya bu adı kullanıyor.", + "Return_type_of_exported_function_has_or_is_using_private_name_0_4060": "Dışarı aktarılan işlevin dönüş türü, '{0}' özel adına sahip veya bu adı kullanıyor.", + "Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4048": "Dışarı aktarılan arabirimdeki dizin imzasının dönüş türü, '{1}' özel modülündeki '{0}' adına sahip veya bu adı kullanıyor.", + "Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0_4049": "Dışarı aktarılan arabirimdeki dizin imzasının dönüş türü, '{0}' özel adına sahip veya bu adı kullanıyor.", + "Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4056": "Dışarı aktarılan arabirimdeki metodun dönüş türü, '{1}' özel modülündeki '{0}' adına sahip veya bu adı kullanıyor.", + "Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0_4057": "Dışarı aktarılan arabirimdeki metodun dönüş türü, '{0}' özel adına sahip veya bu adı kullanıyor.", + "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_4041": "Dışarı aktarılan sınıftaki genel alıcı '{0}' için dönüş türü, '{2}' dış modülündeki '{1}' adına sahip veya bu adı kullanıyor ancak adlandırılamıyor.", + "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2_4042": "Dışarı aktarılan sınıftaki genel alıcı '{0}' için dönüş türü, '{2}' özel modülündeki '{1}' adına sahip veya bu adı kullanıyor.", + "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_private_name_1_4043": "Dışarı aktarılan sınıftaki genel alıcı '{0}' için dönüş türü, '{1}' özel adına sahip veya bu adı kullanıyor.", + "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_c_4053": "Dışarı aktarılan sınıftaki ortak metodun dönüş türü, '{1}' dış modülündeki '{0}' adına sahip veya bu adı kullanıyor, ancak adlandırılamıyor.", + "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4054": "Dışarı aktarılan sınıftaki ortak metodun dönüş türü, '{1}' özel modülündeki '{0}' adına sahip veya bu adı kullanıyor.", + "Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0_4055": "Dışarı aktarılan sınıftaki ortak metodun dönüş türü, '{0}' özel adına sahip veya bu adı kullanıyor.", + "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_external_modul_4038": "Dışarı aktarılan sınıftaki genel statik alıcı '{0}' için dönüş türü, '{2}' dış modülündeki '{1}' adına sahip veya bu adı kullanıyor ancak adlandırılamıyor.", + "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_4039": "Dışarı aktarılan sınıftaki genel statik alıcı '{0}' için dönüş türü, '{2}' özel modülündeki '{1}' adına sahip veya bu adı kullanıyor.", + "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_private_name_1_4040": "Dışarı aktarılan sınıftaki genel statik alıcı '{0}' için dönüş türü, '{1}' özel adına sahip veya bu adı kullanıyor.", + "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module__4050": "Dışarı aktarılan sınıftaki ortak statik metodun dönüş türü, '{1}' dış modülündeki '{0}' adına sahip veya bu adı kullanıyor, ancak adlandırılamıyor.", + "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4051": "Dışarı aktarılan sınıftaki ortak statik metodun dönüş türü, '{1}' özel modülündeki '{0}' adına sahip veya bu adı kullanıyor.", + "Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0_4052": "Dışarı aktarılan sınıftaki ortak statik metodun dönüş türü, '{0}' özel adına sahip veya bu adı kullanıyor.", + "Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program_6184": "Eski programdaki çözümlemeler değişmediğinden '{0}' kaynaklı modül çözümlemeleri yeniden kullanılıyor.", + "Reusing_resolution_of_module_0_to_file_1_from_old_program_6183": "Eski programın '{1}' dosyasında '{0}' modülü çözmesi yeniden kullanılıyor.", + "Rewrite_all_as_indexed_access_types_95034": "Tümünü dizinlenmiş erişim türleri olarak yeniden yaz", + "Rewrite_as_the_indexed_access_type_0_90026": "Dizine eklenmiş erişim türü '{0}' olarak yeniden yaz", + "Root_directory_cannot_be_determined_skipping_primary_search_paths_6122": "Kök dizin belirlenemiyor, birincil arama yolları atlanıyor.", + "STRATEGY_6039": "STRATEJİ", + "Scoped_package_detected_looking_in_0_6182": "Kapsamlı paket algılandı, '{0}' içinde aranıyor", + "Setters_cannot_return_a_value_2408": "Ayarlayıcılar bir değer döndüremez.", + "Show_all_compiler_options_6169": "Tüm derleyici seçeneklerini gösterin.", + "Show_diagnostic_information_6149": "Tanılama bilgilerini gösterin.", + "Show_verbose_diagnostic_information_6150": "Ayrıntılı tanılama bilgilerini gösterin.", + "Show_what_would_be_built_or_deleted_if_specified_with_clean_6367": "Nelerin derleneceğini (veya '--clean' ile belirtilmişse silineceğini) göster", + "Signature_0_must_be_a_type_predicate_1224": "'{0}' imzası bir tür koşulu olmalıdır.", + "Skip_type_checking_of_declaration_files_6012": "Bildirim dosyalarının tür denetimini atla.", + "Skipping_build_of_project_0_because_its_dependency_1_has_errors_6362": "'{0}' projesinin '{1}' bağımlılığında hatalar olduğundan projenin derlenmesi atlanıyor", + "Skipping_clean_because_not_all_projects_could_be_located_6371": "Tüm projeler bulunamadığından temizleme atlanıyor", + "Source_Map_Options_6175": "Kaynak Eşleme Seçenekleri", + "Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature_2382": "Özelleşmiş aşırı yükleme imzası özelleşmemiş imzalara atanamaz.", + "Specifier_of_dynamic_import_cannot_be_spread_element_1325": "Dinamik içeri aktarmanın tanımlayıcısı, yayılma öğesi olamaz.", + "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_or_ESNEXT_6015": "ECMAScript hedef sürümünü belirleyin: 'ES3' (varsayılan), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018' ya da 'ESNEXT'.", + "Specify_JSX_code_generation_Colon_preserve_react_native_or_react_6080": "JSX kod oluşturma seçeneğini belirtin: 'preserve', 'react-native' veya 'react'.", + "Specify_library_files_to_be_included_in_the_compilation_6079": "Derlemeye dahil edilecek kitaplık dosyalarını belirtin.", + "Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext_6016": "Modül kodu oluşturmayı belirtin: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015' veya 'ESNext'.", + "Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6_6069": "Modül çözümleme stratejisini belirtin: 'Node' (Node.js) veya 'classic' (TypeScript pre-1.6).", + "Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h_6146": "'React.createElement' veya 'h' gibi 'react' JSX emit hedeflerken kullanılacak JSX fabrika işlevini belirtin.", + "Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix_6060": "Dosyalar gösterilirken kullanılacak satır sonu dizisini belirtin: 'CRLF' (dos) veya 'LF' (unix).", + "Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations_6004": "Hata ayıklayıcının TypeScript dosyalarını kaynak konumlar yerine nerede bulması gerektiğini belirtin.", + "Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations_6003": "Hata ayıklayıcının, eşlem dosyalarını üretilen konumlar yerine nerede bulması gerektiğini belirtin.", + "Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir_6058": "Giriş dosyalarının kök dizinini belirtin. Çıkış dizininin yapısını --outDir ile denetlemek için kullanın.", + "Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher_2472": "'new' ifadelerindeki yayılma işleci yalnızca ECMAScript 5 ve üzeri hedeflenirken kullanılabilir.", + "Spread_types_may_only_be_created_from_object_types_2698": "Yayılma türleri yalnızca nesne türlerinden oluşturulabilir.", + "Starting_compilation_in_watch_mode_6031": "Derleme, izleme modunda başlatılıyor...", + "Statement_expected_1129": "Deyim bekleniyor.", + "Statements_are_not_allowed_in_ambient_contexts_1036": "Çevresel bağlamlarda deyimlere izin verilmez.", + "Static_members_cannot_reference_class_type_parameters_2302": "Statik üyeler sınıf türündeki parametrelere başvuramaz.", + "Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1_2699": "'{0}' statik özelliği, '{1}' oluşturucu işlevinin yerleşik özelliği olan 'Function.{0}' ile çakışıyor.", + "Strict_Type_Checking_Options_6173": "Katı Tür Denetimi Seçenekleri", + "String_literal_expected_1141": "Dize sabit değeri bekleniyor.", + "String_literal_with_double_quotes_expected_1327": "Çift tırnak içine alınmış bir dize sabit değeri bekleniyor.", + "Stylize_errors_and_messages_using_color_and_context_experimental_6073": "Renk ve bağlam kullanarak hataların ve iletilerin stilini belirleyin (deneysel).", + "Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_t_2717": "Ardışık özellik bildirimleri aynı türe sahip olmalıdır. '{0}' özelliği '{1}' türünde olmalıdır, ancak burada '{2}' türüne sahip.", + "Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_t_2403": "Ardışık değişken bildirimleri aynı türe sahip olmalıdır. '{0}' değişkeni '{1}' türünde olmalıdır, ancak burada '{2}' türüne sahip.", + "Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2_5064": "'{1}' deseni için '{0}' alternatifinin türü hatalı; beklenen: 'string' alınan: '{2}'.", + "Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character_5062": "'{1}' desenindeki '{0}' değişimi, en fazla bir adet '*' karakteri içerebilir.", + "Substitutions_for_pattern_0_should_be_an_array_5063": "'{0}' deseni için değişimler bir dizi olmalıdır.", + "Substitutions_for_pattern_0_shouldn_t_be_an_empty_array_5066": "'{0}' deseni için değiştirme değeri boş bir dizi olamaz.", + "Successfully_created_a_tsconfig_json_file_6071": "tsconfig.json dosyası başarıyla oluşturuldu.", + "Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors_2337": "Super çağrılarına oluşturucu dışında veya oluşturucu içindeki iç içe işlevlerde izin verilmez.", + "Suppress_excess_property_checks_for_object_literals_6072": "Nesne sabit değerlerine ait fazla özellik denetimlerini gösterme.", + "Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures_6055": "Dizin imzaları olmayan nesneler için dizin oluştururken noImplicitAny hatalarını gösterme.", + "Symbol_reference_does_not_refer_to_the_global_Symbol_constructor_object_2470": "'Symbol' başvurusu, genel Simge oluşturucu nesnesine başvurmaz.", + "Syntax_Colon_0_6023": "Söz dizimi: {0}", + "The_0_operator_cannot_be_applied_to_type_symbol_2469": "'{0}' işleci, 'symbol' türüne uygulanamaz.", + "The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead_2447": "'{0}' işlecine boole türü için izin verilmez. Bunun yerine '{1}' kullanmayı göz önünde bulundurun.", + "The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead_2696": "'Object' türü başka çok az sayıda türe atanabilir. Bunun yerine 'any' türünü mü kullanmak istemiştiniz?", + "The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_stand_2496": "ES3 ve ES5'te bulunan bir ok işlevinde 'arguments' nesnesine başvuru yapılamaz. Standart bir işlev ifadesi kullanmayı göz önünde bulundurun.", + "The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_usi_2522": "ES3 ve ES5'te 'arguments' nesnesine zaman uyumsuz bir işlev veya metot içinde başvurulamaz. Standart bir işlev veya metot kullanmayı düşünün.", + "The_body_of_an_if_statement_cannot_be_the_empty_statement_1313": "'if' deyiminin gövdesi boş deyim olamaz.", + "The_character_set_of_the_input_files_6163": "Girdi dosyalarının karakter kümesi.", + "The_containing_function_or_module_body_is_too_large_for_control_flow_analysis_2563": "İçeren işlev veya modül gövdesi, denetim akışı analizi için çok büyük.", + "The_current_host_does_not_support_the_0_option_5001": "Mevcut ana bilgisayar '{0}' seçeneğini desteklemiyor.", + "The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context_2714": "Bir dışarı aktarma ataması ifadesi, çevresel bağlamda bir tanımlayıcı veya tam ad olmalıdır.", + "The_files_list_in_config_file_0_is_empty_18002": "'{0}' yapılandırma dosyasındaki 'dosyalar' listesi boş.", + "The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback_1060": "Promise'in 'then' metodunun ilk parametresi, bir geri arama parametresi olmalıdır.", + "The_global_type_JSX_0_may_not_have_more_than_one_property_2608": "'JSX.{0}' genel türü birden fazla özelliğe sahip olamaz.", + "The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_option_1343": "'import.meta' meta özelliğine yalnızca 'target' ve 'module' derleyici seçenekleri için 'ESNext' kullanıldığında izin verilir.", + "The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary_2527": "Çıkarsanan '{0}' türü, erişilemeyen bir '{1}' türüne başvuruyor. Tür ek açıklaması gereklidir.", + "The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern_2491": "'for...in' deyiminin sol tarafı yok etme deseni olamaz.", + "The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation_2404": "'for...in' deyiminin sol tarafında tür ek açıklaması kullanılamaz.", + "The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access_2406": "'for...in' deyiminin sol tarafında bir değişken veya özellik erişimi bulunmalıdır.", + "The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any_2405": "'for...in' deyiminin sol tarafı 'string' veya 'any' türünde olmalıdır.", + "The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation_2483": "'for...of' deyiminin sol tarafında tür ek açıklaması kullanılamaz.", + "The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access_2487": "'for...of' deyiminin sol tarafında bir değişken veya özellik erişimi bulunmalıdır.", + "The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type_2362": "Aritmetik işlemin sol tarafı, 'any', 'number' veya bir sabit listesi türünde olmalıdır.", + "The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access_2364": "Atama ifadesinin sol tarafında bir değişken veya özellik erişimi bulunmalıdır.", + "The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol_2360": "'in' ifadesinin sol tarafı, 'any', 'string', 'number' veya 'symbol' türünde olmalıdır.", + "The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_paramete_2358": "'instanceof' ifadesinin sol tarafı 'any' türünde, bir nesne türü veya tür parametresi olmalıdır.", + "The_locale_used_when_displaying_messages_to_the_user_e_g_en_us_6156": "Kullanıcıya ileti görüntülenirken kullanılacak yerel ayar (örn. 'tr-tr')", + "The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files_6136": "node_modules altında arama yapmak ve JavaScript dosyalarını yüklemek için en yüksek bağımlılık derinliği.", + "The_operand_of_a_delete_operator_cannot_be_a_read_only_property_2704": "Delete işlecinin işleneni, salt okunur bir özellik olamaz.", + "The_operand_of_a_delete_operator_must_be_a_property_reference_2703": "Delete işlecinin işleneni, bir özellik başvurusu olmalıdır.", + "The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access_2357": "Artırma veya eksiltme operatörünün işleneni, bir değişken veya özellik erişimi olmalıdır.", + "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601": "JSX öğe oluşturucusuna ait dönüş türü bir nesne türünü döndürmelidir.", + "The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any_1237": "Parametre dekoratör işlevine ait dönüş türü 'void' veya 'any' olmalıdır.", + "The_return_type_of_a_property_decorator_function_must_be_either_void_or_any_1236": "Özellik dekoratör işlevine ait dönüş türü 'void' veya 'any' olmalıdır.", + "The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_t_1058": "Zaman uyumsuz bir işlevin dönüş türü, geçerli bir promise olmalı veya çağrılabilir 'then' üyesi içermemelidir.", + "The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_1064": "Zaman uyumsuz bir işlevin ya da metodun döndürme türü, genel Promise türü olmalıdır.", + "The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_but_2407": "'for...in' deyiminin sağ tarafı 'any' türünde, bir nesne türü veya tür parametresi olmalıdır ancak burada '{0}' türüne sahip.", + "The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type_2363": "Aritmetik işlemin sağ tarafı, 'any', 'number' veya bir sabit listesi türünde olmalıdır.", + "The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter_2361": "'in' ifadesinin sağ tarafı 'any' türünde, bir nesne türü veya tür parametresi olmalıdır.", + "The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_F_2359": "'instanceof' ifadesinin sağ tarafı 'any' türünde veya 'Function' arabirim türüne atanabilir bir türde olmalıdır.", + "The_specified_path_does_not_exist_Colon_0_5058": "Belirtilen yol yok: '{0}'.", + "The_target_of_an_assignment_must_be_a_variable_or_a_property_access_2541": "Atama hedefi, bir değişken veya özellik erişimi olmalıdır.", + "The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access_2701": "Nesne geri kalan özellik atamasının hedefi, bir değişken veya özellik erişimi olmalıdır.", + "The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1_2684": "'{0}' türünün 'this' bağlamı, metodun '{1}' türündeki 'this' değerine atanamaz.", + "The_this_types_of_each_signature_are_incompatible_2685": "İmzaların 'this' türleri uyumsuz.", + "The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_typ_2453": "'{0}' tür parametresinin tür bağımsız değişkeni kullanımdan belirlenemez. Tür bağımsız değişkenlerini açık olarak belirtmeyi göz önünde bulundurun.", + "The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value__2547": "Zaman uyumsuz yineleyicinin 'next()' metodu tarafından döndürülen tür, 'value' özelliğine sahip bir tür için promise olmalıdır.", + "The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property_2490": "Bir yineleyicinin 'next()' metodu tarafından döndürülen tür, 'value' özelliğine sahip olmalıdır.", + "The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer_1189": "'for...in' deyiminin değişken bildirimi bir başlatıcıya sahip olamaz.", + "The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer_1190": "'for...of' deyiminin değişken bildirimi bir başlatıcıya sahip olamaz.", + "The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any_2410": "'with' ifadesi desteklenmiyor. 'with' bloklarındaki tüm simgeler 'any' türüne sahip olacaktır.", + "This_constructor_function_may_be_converted_to_a_class_declaration_80002": "Bu oluşturucu işlevi bir sınıf bildirimine dönüştürülebilir.", + "This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found_2354": "Bu söz dizimi, içeri aktarılan bir yardımcı gerektiriyor ancak '{0}' modülü bulunamıyor.", + "This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1_2343": "Bu söz dizimi, '{1}' adlı içeri aktarılan yardımcıyı gerektiriyor ancak '{0}' modülünde dışarı aktarılan '{1}' üyesi yok.", + "Trailing_comma_not_allowed_1009": "Sona eklenen virgüle izin verilmez.", + "Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule_6153": "Her dosyayı ayrı bir modül olarak derleyin ('ts.transpileModule' gibi).", + "Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_mod_7035": "Varsa `npm install @types/{0}` deneyin veya `declare module '{0}';` öğesini içeren yeni bir bildirim (.d.ts) dosyası ekleyin", + "Trying_other_entries_in_rootDirs_6110": "'rootDirs' içindeki diğer girişler deneniyor.", + "Trying_substitution_0_candidate_module_location_Colon_1_6093": "'{0}' alternatifi deneniyor, aday modül konumu: '{1}'.", + "Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2_2493": "'{1}' uzunluğuna sahip '{0}' demeti, '{2}' uzunluğuna sahip demete atanamaz.", + "Type_0_cannot_be_converted_to_type_1_2352": "'{0}' türü '{1}' türüne dönüştürülemez.", + "Type_0_cannot_be_used_as_an_index_type_2538": "'{0}' türü, dizin türü olarak kullanılamaz.", + "Type_0_cannot_be_used_to_index_type_1_2536": "'{0}' türü, '{1}' türünü dizinlemek için kullanılamaz.", + "Type_0_does_not_satisfy_the_constraint_1_2344": "'{0}' türü, '{1}' kısıtlamasını karşılamıyor.", + "Type_0_has_no_matching_index_signature_for_type_1_2537": "'{0}' türü, '{1}' türüyle eşleşen dizin imzasına sahip değil.", + "Type_0_has_no_properties_in_common_with_type_1_2559": "'{0}' türünün '{1}' türüyle ortak özelliği yok.", + "Type_0_has_no_property_1_2460": "'{0}' türü, '{1}' özelliğine sahip değil.", + "Type_0_has_no_property_1_and_no_string_index_signature_2459": "'{0}' türü, '{1}' özelliğine ve dize dizin imzasına sahip değil.", + "Type_0_is_not_a_constructor_function_type_2507": "'{0}' türü bir oluşturucu işlevi türü değil.", + "Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Prom_1055": "ES5/ES3 içindeki '{0}' türü, Promise ile uyumlu bir oluşturucu değerine başvurmadığından geçerli bir zaman uyumsuz işlev dönüş türü değil.", + "Type_0_is_not_an_array_type_2461": "'{0}' türü bir dizi türü değil.", + "Type_0_is_not_an_array_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators_2568": "'{0}' türü bir dizi türü değil. Yineleyicilerin yinelenmesine izin vermek için '--downlevelIteration' derleyici seçeneğini kullanın.", + "Type_0_is_not_an_array_type_or_a_string_type_2495": "'{0}' türü, bir dizi türü veya dize türü değil.", + "Type_0_is_not_an_array_type_or_a_string_type_Use_compiler_option_downlevelIteration_to_allow_iterati_2569": "'{0}' türü bir dizi türü veya bir dize türü değil. Yineleyicilerin yinelenmesine izin vermek için '--downlevelIteration' derleyici seçeneğini kullanın.", + "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549": "'{0}' türü, bir dizi türü veya dize türü değil ya da bir yineleyici döndüren '[Symbol.iterator]()' metoduna sahip değil.", + "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548": "'{0}' türü, bir dizi türü değil ya da bir yineleyici döndüren '[Symbol.iterator]()' metoduna sahip değil.", + "Type_0_is_not_assignable_to_type_1_2322": "'{0}' türü, '{1}' türüne atanamaz.", + "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_2719": "'{0}' türü '{1}' türüne atanamaz. Bu ada sahip iki farklı tür mevcut, ancak bu türler birbiriyle ilişkisiz.", + "Type_0_is_not_comparable_to_type_1_2678": "'{0}' türü '{1}' türüyle karşılaştırılamaz.", + "Type_0_is_not_generic_2315": "'{0}' türü genel değil.", + "Type_0_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator_2504": "'{0}' türünün, zaman uyumsuz bir yineleyici döndüren bir '[Symbol.asyncIterator]()' metoduna sahip olması gerekir.", + "Type_0_must_have_a_Symbol_iterator_method_that_returns_an_iterator_2488": "'{0}' türünün, bir yineleyici döndüren '[Symbol.iterator]()' metoduna sahip olması gerekir.", + "Type_0_provides_no_match_for_the_signature_1_2658": "'{0}' türü, '{1}' imzası için eşleşme sağlamıyor.", + "Type_0_recursively_references_itself_as_a_base_type_2310": "'{0}' türü, öz yinelemeli şekilde kendine temel tür olarak başvuruyor.", + "Type_alias_0_circularly_references_itself_2456": "'{0}' tür diğer adı, döngüsel olarak kendine başvuruyor.", + "Type_alias_name_cannot_be_0_2457": "Tür diğer adı '{0}' olamaz.", + "Type_annotation_cannot_appear_on_a_constructor_declaration_1093": "Tür ek açıklaması, oluşturucu bildiriminde görüntülenemez.", + "Type_argument_candidate_1_is_not_a_valid_type_argument_because_it_is_not_a_supertype_of_candidate_0_2455": "'{1}' tür bağımsız değişken adayı, '{0}' adayının üst türü olmadığından geçerli bir tür bağımsız değişkeni değil.", + "Type_argument_expected_1140": "Tür bağımsız değişkeni bekleniyor.", + "Type_argument_list_cannot_be_empty_1099": "Tür bağımsız değişkeni listesi boş olamaz.", + "Type_arguments_cannot_be_used_here_1342": "Tür bağımsız değişkenleri burada kullanılamaz.", + "Type_declaration_files_to_be_included_in_compilation_6124": "Derlemeye eklenecek tür bildirim dosyaları.", + "Type_expected_1110": "Tür bekleniyor.", + "Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method_1062": "Türe, kendi 'then' metodunun tamamlama geri aramasında doğrudan veya dolaylı olarak başvuruluyor.", + "Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member_1320": "'await' işleneninin türü, geçerli bir promise olmalı veya çağrılabilir 'then' üyesi içermemelidir.", + "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322": "Bir 'yield*' işleneninin yinelenen öğelerinin türü, geçerli bir promise olmalı veya çağrılabilir 'then' üyesi içermemelidir.", + "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321": "Zaman uyumsuz bir oluşturucudaki 'yield' işleneninin türü, geçerli bir promise olmalı veya çağrılabilir 'then' üyesi içermemelidir.", + "Type_parameter_0_has_a_circular_constraint_2313": "'{0}' tür parametresi döngüsel bir kısıtlamaya sahip.", + "Type_parameter_0_has_a_circular_default_2716": "'{0}' tür parametresi döngüsel bir varsayılana sahip.", + "Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4008": "Dışarı aktarılan arabirimdeki çağrı imzasının '{0}' tür parametresi, '{1}' özel adına sahip veya bu adı kullanıyor.", + "Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4006": "Dışarı aktarılan arabirimdeki oluşturucu imzasının '{0}' tür parametresi, '{1}' özel adına sahip veya bu adı kullanıyor.", + "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002": "Dışarı aktarılan sınıfın '{0}' tür parametresi, '{1}' özel adına sahip veya bu adı kullanıyor.", + "Type_parameter_0_of_exported_function_has_or_is_using_private_name_1_4016": "Dışarı aktarılan işlevin '{0}' tür parametresi, '{1}' özel adına sahip veya bu adı kullanıyor.", + "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004": "Dışarı aktarılan arabirimin '{0}' tür parametresi, '{1}' özel adına sahip veya bu adı kullanıyor.", + "Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1_4083": "Dışarı aktarılan tür diğer adına ait '{0}' tür parametresi, '{1}' özel adına sahip veya bu adı kullanıyor.", + "Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4014": "Dışarı aktarılan arabirimdeki metodun '{0}' tür parametresi, '{1}' özel adına sahip veya bu adı kullanıyor.", + "Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4012": "Dışarı aktarılan sınıftaki ortak metodun '{0}' tür parametresi, '{1}' özel adına sahip veya bu adı kullanıyor.", + "Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4010": "Dışarı aktarılan sınıftaki ortak statik metodun '{0}' tür parametresi, '{1}' özel adına sahip veya bu adı kullanıyor.", + "Type_parameter_declaration_expected_1139": "Tür parametresi bildirimi bekleniyor.", + "Type_parameter_list_cannot_be_empty_1098": "Tür parametresi listesi boş olamaz.", + "Type_parameter_name_cannot_be_0_2368": "Tür parametresi adı '{0}' olamaz.", + "Type_parameters_cannot_appear_on_a_constructor_declaration_1092": "Tür parametreleri, oluşturucu bildiriminde görüntülenemez.", + "Type_predicate_0_is_not_assignable_to_1_1226": "'{0}' tür koşulu, '{1}' öğesine atanamaz.", + "Type_reference_directive_0_was_not_resolved_6120": "======== '{0}' tür başvuru yönergesi çözümlenmedi. ========", + "Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2_6119": "======== '{0}' tür başvuru yönergesi '{1}' olarak başarıyla çözümlendi, birincil: {2}. ========", + "Types_have_separate_declarations_of_a_private_property_0_2442": "Türler, '{0}' özel özelliğinin ayrı bildirimlerine sahip.", + "Types_of_parameters_0_and_1_are_incompatible_2328": "'{0}' ve '{1}' parametre türleri uyumsuz.", + "Types_of_property_0_are_incompatible_2326": "'{0}' özellik türleri uyumsuz.", + "Unable_to_open_file_0_6050": "'{0}' dosyası açılamıyor.", + "Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression_1238": "Bir ifade olarak çağrıldığında sınıf dekoratörünün imzası çözümlenemez.", + "Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression_1241": "Bir ifade olarak çağrıldığında metot dekoratörünün imzası çözümlenemez.", + "Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression_1239": "Bir ifade olarak çağrıldığında parametre dekoratörünün imzası çözümlenemez.", + "Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression_1240": "Bir ifade olarak çağrıldığında özellik dekoratörünün imzası çözümlenemez.", + "Unexpected_end_of_text_1126": "Beklenmeyen metin sonu.", + "Unexpected_token_1012": "Beklenmeyen belirteç.", + "Unexpected_token_A_constructor_method_accessor_or_property_was_expected_1068": "Beklenmeyen belirteç. Bir oluşturucu, metot, erişimci veya özellik bekleniyordu.", + "Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces_1069": "Beklenmeyen belirteç. Küme ayracı olmadan bir tür parametresi adı bekleniyordu.", + "Unexpected_token_expected_1179": "Beklenmeyen belirteç. '{' bekleniyordu.", + "Unknown_compiler_option_0_5023": "Bilinmeyen '{0}' derleyici seçeneği.", + "Unknown_option_excludes_Did_you_mean_exclude_6114": "'Excludes' seçeneği bilinmiyor. 'Exclude' seçeneğini mi belirtmek istediniz?", + "Unknown_type_acquisition_option_0_17010": "Bilinmeyen '{0}' tür alımı seçeneği.", + "Unreachable_code_detected_7027": "Erişilemeyen kod algılandı.", + "Unsupported_locale_0_6049": "Desteklenmeyen '{0}' yerel ayarı.", + "Unterminated_Unicode_escape_sequence_1199": "Sonlandırılmamış Unicode kaçış dizisi.", + "Unterminated_quoted_string_in_response_file_0_6045": "'{0}' yanıt dosyasında sonlandırılmamış alıntılanmış dize.", + "Unterminated_regular_expression_literal_1161": "Sonlandırılmamış normal ifade sabit değeri.", + "Unterminated_string_literal_1002": "Sonlandırılmamış dize sabit değeri.", + "Unterminated_template_literal_1160": "Sonlandırılmamış şablon sabit değeri.", + "Untyped_function_calls_may_not_accept_type_arguments_2347": "Türü belirtilmemiş işlev çağrıları tür bağımsız değişkenlerini kabul etmeyebilir.", + "Unused_label_7028": "Kullanılmayan etiket.", + "Updating_output_timestamps_of_project_0_6359": "'{0}' projesinin çıkış zaman damgaları güncelleştiriliyor...", + "Use_synthetic_default_member_95016": "Yapay 'default' üyesini kullanın.", + "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494": "'for...of' deyiminde dize kullanma yalnızca ECMAScript 5 veya üzerinde desteklenir.", + "VERSION_6036": "SÜRÜM", + "Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it_2560": "'{0}' türünün değeri ile '{1}' türü arasında hiç ortak özellik yok. Bunun yerine çağrı yapmak mı istediniz?", + "Value_of_type_0_is_not_callable_Did_you_mean_to_include_new_2348": "'{0}' türündeki değeri çağrılabilir değil. 'new' öğesini mi eklemek istemiştiniz?", + "Variable_0_implicitly_has_an_1_type_7005": "'{0}' değişkeni örtük olarak '{1}' türüne sahip.", + "Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined_7034": "'{0}' değişkeni, türünün belirlenemeyeceği bazı konumlarda örtülü olarak '{1}' türünü içeriyor.", + "Variable_0_is_used_before_being_assigned_2454": "'{0}' değişkeni atanmadan önce kullanılır.", + "Variable_declaration_expected_1134": "Değişken bildirimi bekleniyor.", + "Variable_declaration_list_cannot_be_empty_1123": "Değişken bildirim listesi boş olamaz.", + "Version_0_6029": "Sürüm {0}", + "Watch_input_files_6005": "Giriş dosyalarını izleyin.", + "Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen_6191": "Eski konsol çıktısının ekrandan kaldırılmak yerine izleme modunda tutulup tutulmayacağı.", + "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001": "Standart TypeScript kitaplığında tanımlanmış öğeleri yeniden adlandıramazsınız.", + "You_cannot_rename_this_element_8000": "Bu öğeyi yeniden adlandıramazsınız.", + "_0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write__1329": "'{0}' burada dekoratör olarak kullanılmak için çok az bağımsız değişken kabul ediyor. Önce çağırıp '@{0}()' yazmak mı istediniz?", + "_0_are_specified_twice_The_attribute_named_0_will_be_overwritten_2710": "'{0}' iki kez belirtildi. '{0}' özniteliğinin üzerine yazılacak.", + "_0_can_only_be_used_in_a_ts_file_8009": "'{0}' yalnızca bir .ts dosyasında kullanılabilir.", + "_0_expected_1005": "'{0}' bekleniyor.", + "_0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_reference_7023": "Dönüş türü ek açıklamasına sahip olmadığından ve doğrudan veya dolaylı olarak dönüş ifadelerinden birinde kendine başvurulduğundan, '{0}' öğesi örtük olarak 'any' türüne sahip.", + "_0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or__7022": "Bir tür ek açıklamasına sahip olmadığından ve kendi başlatıcısında doğrudan veya dolaylı olarak başvurulduğundan, '{0}' öğesi örtük olarak 'any' türüne sahip.", + "_0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible_2692": "'{0}' temel elemandır ancak '{1}' sarmalayıcı nesnedir. Mümkün olduğunda '{0}' kullanmayı tercih edin.", + "_0_is_declared_but_its_value_is_never_read_6133": "'{0}' bildirildi ancak değeri hiç okunmadı.", + "_0_is_declared_but_never_used_6196": "'{0}' bildirildi ancak hiç kullanılmadı.", + "_0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2_17012": "'{0}', '{1}' anahtar sözcüğü için geçerli bir meta özellik değil. Bunu mu demek istediniz: '{2}'?", + "_0_is_referenced_directly_or_indirectly_in_its_own_base_expression_2506": "'{0}' öğesine kendi temel ifadesinde doğrudan veya dolaylı olarak başvuruluyor.", + "_0_is_referenced_directly_or_indirectly_in_its_own_type_annotation_2502": "'{0}' öğesine kendi tür ek açıklamasında doğrudan veya dolaylı olarak başvuruluyor.", + "_0_list_cannot_be_empty_1097": "'{0}' listesi boş olamaz.", + "_0_modifier_already_seen_1030": "'{0}' değiştiricisi zaten görüldü.", + "_0_modifier_cannot_appear_on_a_class_element_1031": "'{0}' değiştiricisi bir sınıf öğesinde görüntülenemez.", + "_0_modifier_cannot_appear_on_a_constructor_declaration_1089": "'{0}' değiştiricisi bir oluşturucu bildiriminde görüntülenemez.", + "_0_modifier_cannot_appear_on_a_data_property_1043": "'{0}' değiştiricisi bir veri özelliğinde görüntülenemez.", + "_0_modifier_cannot_appear_on_a_module_or_namespace_element_1044": "'{0}' değiştiricisi, bir modülde veya ad alanı öğesinde görünemez.", + "_0_modifier_cannot_appear_on_a_parameter_1090": "'{0}' değiştiricisi bir parametrede görüntülenemez.", + "_0_modifier_cannot_appear_on_a_type_member_1070": "'{0}' değiştiricisi, bir tür üyesinde görünemez.", + "_0_modifier_cannot_appear_on_an_index_signature_1071": "'{0}' değiştiricisi, bir dizin imzasında görünemez.", + "_0_modifier_cannot_be_used_here_1042": "'{0}' değiştiricisi burada kullanılamaz.", + "_0_modifier_cannot_be_used_in_an_ambient_context_1040": "'{0}' değiştiricisi bir çevresel bağlamda kullanılamaz.", + "_0_modifier_cannot_be_used_with_1_modifier_1243": "'{0}' değiştiricisi, '{1}' değiştiricisi ile birlikte kullanılamaz.", + "_0_modifier_cannot_be_used_with_a_class_declaration_1041": "'{0}' değiştiricisi bir sınıf bildirimiyle birlikte kullanılamaz.", + "_0_modifier_must_precede_1_modifier_1029": "'{0}' değiştiricisi, '{1}' değiştiricisinden önce gelmelidir.", + "_0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here_2702": "'{0}' yalnızca bir türe başvuruyor, ancak burada bir ad alanı olarak kullanılıyor.", + "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_2693": "'{0}' yalnızca bir türe başvuruyor, ancak burada bir değer olarak kullanılıyor.", + "_0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead_2686": "'{0}' bir UMD genel öğesine başvuruyor, ancak geçerli dosya bir modül. Bunun yerine bir içeri aktarma eklemeyi deneyin.", + "_0_tag_already_specified_1223": "'{0}' etiketi zaten belirtildi.", + "_0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag_1253": "'{0}' etiketi tek başına üst düzey bir JSDoc etiketi olarak kullanılamaz.", + "_0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type_7010": "Dönüş türü ek açıklaması olmayan '{0}', örtük olarak '{1}' dönüş türüne sahip.", + "abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration_1242": "'abstract' değiştiricisi yalnızca sınıf, metot veya özellik bildiriminde görünebilir.", + "await_expression_is_only_allowed_within_an_async_function_1308": "'await' ifadesine yalnızca bir zaman uyumsuz işlevde izin verilir.", + "await_expressions_cannot_be_used_in_a_parameter_initializer_2524": "'await' ifadeleri bir parametre başlatıcısında kullanılamaz.", + "baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1_6106": "'baseUrl' seçeneği '{0}' olarak ayarlandı; göreli olmayan '{1}' modül adını çözümlemek için bu değer kullanılıyor.", + "can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment_1312": "'=', yalnızca yok etme ataması içindeki bir nesne sabit değeri özelliğinde kullanılabilir.", + "case_or_default_expected_1130": "'case' veya 'default' ifadeleri bekleniyor.", + "class_expressions_are_not_currently_supported_9003": "'class' ifadeleri şu anda desteklenmiyor.", + "const_declarations_can_only_be_declared_inside_a_block_1156": "'const' bildirimleri yalnızca bir bloğun içinde bildirilebilir.", + "const_declarations_must_be_initialized_1155": "'const' bildirimlerinin başlatılması gerekiyor.", + "const_enum_member_initializer_was_evaluated_to_a_non_finite_value_2477": "'const' sabit listesi üyesi başlatıcısı, sonlu olmayan bir değer olarak hesaplandı.", + "const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN_2478": "'const' sabit listesi üyesi başlatıcısı, izin verilmeyen 'NaN' değeri olarak hesaplandı.", + "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475": "'const' sabit listeleri yalnızca bir özellikte, dizin erişim ifadelerinde, içeri aktarma bildiriminin veya dışarı aktarma atamasının sağ tarafında ya da tür sorgusunda kullanılabilir.", + "delete_cannot_be_called_on_an_identifier_in_strict_mode_1102": "'delete', katı moddaki bir tanımlayıcıda çağrılamaz.", + "delete_this_Project_0_is_up_to_date_because_it_was_previously_built_6360": "bunu silin - '{0}' projesi önceden derlenmiş olduğundan güncel", + "enum_declarations_can_only_be_used_in_a_ts_file_8015": "'enum declarations' yalnızca bir .ts dosyasında kullanılabilir.", + "export_can_only_be_used_in_a_ts_file_8003": "'export=' yalnızca bir .ts dosyasında kullanılabilir.", + "export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always__2668": "'export' değiştiricisi, her zaman görünür olduğu için çevresel modüllere ve modül genişletmelerine uygulanamaz.", + "extends_clause_already_seen_1172": "'extends' yan tümcesi zaten görüldü.", + "extends_clause_must_precede_implements_clause_1173": "'extends' yan tümcesi, 'implements' yan tümcesinden önce gelmelidir.", + "extends_clause_of_exported_class_0_has_or_is_using_private_name_1_4020": "Dışarı aktarılan '{0}' sınıfının 'extends' yan tümcesi, '{1}' özel adına sahip veya bu adı kullanıyor.", + "extends_clause_of_exported_interface_0_has_or_is_using_private_name_1_4022": "Dışarı aktarılan '{0}' arabiriminin 'extends' yan tümcesi, '{1}' özel adına sahip veya bu adı kullanıyor.", + "file_6025": "dosya", + "get_and_set_accessor_must_have_the_same_this_type_2682": "'get' ve 'set' erişimcisi aynı 'this' türüne sahip olmalıdır.", + "get_and_set_accessor_must_have_the_same_type_2380": "'get' ve 'set' erişimcisi aynı türde olmalıdır.", + "implements_clause_already_seen_1175": "'implements' yan tümcesi zaten görüldü.", + "implements_clauses_can_only_be_used_in_a_ts_file_8005": "'implements clauses' yalnızca bir .ts dosyasında kullanılabilir.", + "import_can_only_be_used_in_a_ts_file_8002": "'import ... =' yalnızca bir .ts dosyasında kullanılabilir.", + "infer_declarations_are_only_permitted_in_the_extends_clause_of_a_conditional_type_1338": "'infer' bildirimlerine yalnızca bir koşullu türün 'extends' yan tümcesinde izin verilir.", + "interface_declarations_can_only_be_used_in_a_ts_file_8006": "'interface declarations' yalnızca bir .ts dosyasında kullanılabilir.", + "let_declarations_can_only_be_declared_inside_a_block_1157": "'let' bildirimleri yalnızca bu bloğun içinde bildirilebilir.", + "let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations_2480": "'let' ifadesi, 'let' veya 'const' bildirimlerinde ad olarak kullanılamaz.", + "module_declarations_can_only_be_used_in_a_ts_file_8007": "'module declarations' yalnızca bir .ts dosyasında kullanılabilir.", + "new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead_1150": "'new T[]', dizi oluşturmak için kullanılamaz. Bunun yerine 'new Array()' kullanın.", + "new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type_7009": "Yapı imzası bulunmayan 'new' ifadesi örtük olarak 'any' türüne sahip.", + "non_null_assertions_can_only_be_used_in_a_ts_file_8013": "'non-null assertions' yalnızca .ts dosyasında kullanılabilir.", + "options_6024": "seçenekler", + "or_expected_1144": "'{' veya ';' bekleniyor.", + "package_json_does_not_have_a_0_field_6100": "'package.json' geçerli bir '{0}' alanına sahip değil.", + "package_json_has_0_field_1_that_references_2_6101": "'package.json', '{2}' öğesine başvuruda bulunan '{1}' adlı '{0}' alanını içeriyor.", + "parameter_modifiers_can_only_be_used_in_a_ts_file_8012": "'parameter modifiers' yalnızca bir .ts dosyasında kullanılabilir.", + "paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0_6091": "'paths' seçeneği belirtildi, '{0}' modül adıyla eşleşen bir desen aranıyor.", + "readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024": "'readonly' değiştiricisi yalnızca özellik bildiriminde ya da dizin imzasında görünebilir.", + "require_call_may_be_converted_to_an_import_80005": "'require' çağrısı bir import olarak dönüştürülebilir.", + "rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107": "'rootDirs' seçeneği ayarlandı, '{0}' göreli modül adını çözümlemek için bu değer kullanılıyor.", + "super_can_only_be_referenced_in_a_derived_class_2335": "'super' öğesine yalnızca bir türetilmiş sınıfta başvurulabilir.", + "super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions_2660": "'super' değerine yalnızca türetilen sınıfların üyelerinde ya da nesne değişmez ifadelerinde başvurulabilir.", + "super_cannot_be_referenced_in_a_computed_property_name_2466": "'super' öğesine hesaplanan bir özellik adında başvurulamaz.", + "super_cannot_be_referenced_in_constructor_arguments_2336": "'super' öğesine oluşturucu bağımsız değişkenlerinde başvurulamaz.", + "super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_highe_2659": "Nesne değişmez ifadelerinde 'super' değerine yalnızca 'target' seçeneği 'ES2015' veya üzeri olarak ayarlandığında izin verilir.", + "super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class_17011": "Türetilmiş bir sınıfın oluşturucusunda 'super' özelliğine erişmeden önce 'super' çağrılmalıdır.", + "super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class_17009": "Türetilen bir sınıfın oluşturucusundaki 'this' değerine erişilmeden önce 'super' çağrılmalıdır.", + "super_must_be_followed_by_an_argument_list_or_member_access_1034": "'super' öğesinden sonra bir bağımsız değişken listesi veya üye erişimi gelmelidir.", + "super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_der_2338": "'super' özellik erişimine yalnızca bir oluşturucuda, üye işlevinde veya bir türetilmiş sınıfa ait üye erişimcisinde izin verilir.", + "this_cannot_be_referenced_in_a_computed_property_name_2465": "'this' öğesine hesaplanan bir özellik adında başvurulamaz.", + "this_cannot_be_referenced_in_a_module_or_namespace_body_2331": "'this' öğesine bir modülde veya ad alanı gövdesinde başvurulamaz.", + "this_cannot_be_referenced_in_a_static_property_initializer_2334": "'this' öğesine statik özellik başlatıcısında başvurulamaz.", + "this_cannot_be_referenced_in_constructor_arguments_2333": "'super' öğesine oluşturucu bağımsız değişkenlerinde başvurulamaz.", + "this_cannot_be_referenced_in_current_location_2332": "'this' öğesine geçerli konumda başvurulamaz.", + "this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_2683": "'this', tür ek açıklamasına sahip olmadığından örtük olarak 'any' türü içeriyor", + "type_aliases_can_only_be_used_in_a_ts_file_8008": "'type aliases' yalnızca bir .ts dosyasında kullanılabilir.", + "type_arguments_can_only_be_used_in_a_ts_file_8011": "'type arguments' yalnızca bir .ts dosyasında kullanılabilir.", + "type_assertion_expressions_can_only_be_used_in_a_ts_file_8016": "'type assertion expressions' yalnızca bir .ts dosyasında kullanılabilir.", + "type_parameter_declarations_can_only_be_used_in_a_ts_file_8004": "'type parameter declarations' yalnızca bir .ts dosyasında kullanılabilir.", + "types_can_only_be_used_in_a_ts_file_8010": "'types' yalnızca bir .ts dosyasında kullanılabilir.", + "unique_symbol_types_are_not_allowed_here_1335": "Burada 'unique symbol' türlerine izin verilmez.", + "unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement_1334": "'unique symbol' türlerine yalnızca bir değişken deyimindeki değişkenlerde izin verilir.", + "unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name_1333": "'unique symbol' türleri, bağlama adına sahip bir değişken bildiriminde kullanılamaz.", + "with_statements_are_not_allowed_in_an_async_function_block_1300": "'with' deyimlerine zaman uyumsuz bir işlev bloğunda izin verilmez.", + "with_statements_are_not_allowed_in_strict_mode_1101": "'with' deyimlerine katı modda izin verilmez.", + "yield_expressions_cannot_be_used_in_a_parameter_initializer_2523": "'yield' ifadeleri bir parametre başlatıcısında kullanılamaz." +} \ No newline at end of file diff --git a/node_modules/typescript/lib/tsc.js b/node_modules/typescript/lib/tsc.js new file mode 100644 index 0000000..bad684c --- /dev/null +++ b/node_modules/typescript/lib/tsc.js @@ -0,0 +1,75882 @@ +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + + +"use strict"; +"use strict"; +var __assign = (this && this.__assign) || function () { + __assign = Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; + }; + return __assign.apply(this, arguments); +}; +var __generator = (this && this.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } +}; +var __makeTemplateObject = (this && this.__makeTemplateObject) || function (cooked, raw) { + if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } + return cooked; +}; +var ts; +(function (ts) { + ts.versionMajorMinor = "3.2"; + ts.version = ts.versionMajorMinor + ".2"; +})(ts || (ts = {})); +(function (ts) { + ts.emptyArray = []; + function createDictionaryObject() { + var map = Object.create(null); + map.__ = undefined; + delete map.__; + return map; + } + function createMap() { + return new ts.MapCtr(); + } + ts.createMap = createMap; + function createMapFromEntries(entries) { + var map = createMap(); + for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) { + var _a = entries_1[_i], key = _a[0], value = _a[1]; + map.set(key, value); + } + return map; + } + ts.createMapFromEntries = createMapFromEntries; + function createMapFromTemplate(template) { + var map = new ts.MapCtr(); + for (var key in template) { + if (hasOwnProperty.call(template, key)) { + map.set(key, template[key]); + } + } + return map; + } + ts.createMapFromTemplate = createMapFromTemplate; + ts.MapCtr = typeof Map !== "undefined" && "entries" in Map.prototype ? Map : shimMap(); + function shimMap() { + var MapIterator = (function () { + function MapIterator(data, selector) { + this.index = 0; + this.data = data; + this.selector = selector; + this.keys = Object.keys(data); + } + MapIterator.prototype.next = function () { + var index = this.index; + if (index < this.keys.length) { + this.index++; + return { value: this.selector(this.data, this.keys[index]), done: false }; + } + return { value: undefined, done: true }; + }; + return MapIterator; + }()); + return (function () { + function class_1() { + this.data = createDictionaryObject(); + this.size = 0; + } + class_1.prototype.get = function (key) { + return this.data[key]; + }; + class_1.prototype.set = function (key, value) { + if (!this.has(key)) { + this.size++; + } + this.data[key] = value; + return this; + }; + class_1.prototype.has = function (key) { + return key in this.data; + }; + class_1.prototype.delete = function (key) { + if (this.has(key)) { + this.size--; + delete this.data[key]; + return true; + } + return false; + }; + class_1.prototype.clear = function () { + this.data = createDictionaryObject(); + this.size = 0; + }; + class_1.prototype.keys = function () { + return new MapIterator(this.data, function (_data, key) { return key; }); + }; + class_1.prototype.values = function () { + return new MapIterator(this.data, function (data, key) { return data[key]; }); + }; + class_1.prototype.entries = function () { + return new MapIterator(this.data, function (data, key) { return [key, data[key]]; }); + }; + class_1.prototype.forEach = function (action) { + for (var key in this.data) { + action(this.data[key], key); + } + }; + return class_1; + }()); + } + function length(array) { + return array ? array.length : 0; + } + ts.length = length; + function forEach(array, callback) { + if (array) { + for (var i = 0; i < array.length; i++) { + var result = callback(array[i], i); + if (result) { + return result; + } + } + } + return undefined; + } + ts.forEach = forEach; + function firstDefined(array, callback) { + if (array === undefined) { + return undefined; + } + for (var i = 0; i < array.length; i++) { + var result = callback(array[i], i); + if (result !== undefined) { + return result; + } + } + return undefined; + } + ts.firstDefined = firstDefined; + function firstDefinedIterator(iter, callback) { + while (true) { + var _a = iter.next(), value = _a.value, done = _a.done; + if (done) { + return undefined; + } + var result = callback(value); + if (result !== undefined) { + return result; + } + } + } + ts.firstDefinedIterator = firstDefinedIterator; + function zipWith(arrayA, arrayB, callback) { + var result = []; + Debug.assertEqual(arrayA.length, arrayB.length); + for (var i = 0; i < arrayA.length; i++) { + result.push(callback(arrayA[i], arrayB[i], i)); + } + return result; + } + ts.zipWith = zipWith; + function zipToIterator(arrayA, arrayB) { + Debug.assertEqual(arrayA.length, arrayB.length); + var i = 0; + return { + next: function () { + if (i === arrayA.length) { + return { value: undefined, done: true }; + } + i++; + return { value: [arrayA[i - 1], arrayB[i - 1]], done: false }; + } + }; + } + ts.zipToIterator = zipToIterator; + function zipToMap(keys, values) { + Debug.assert(keys.length === values.length); + var map = createMap(); + for (var i = 0; i < keys.length; ++i) { + map.set(keys[i], values[i]); + } + return map; + } + ts.zipToMap = zipToMap; + function every(array, callback) { + if (array) { + for (var i = 0; i < array.length; i++) { + if (!callback(array[i], i)) { + return false; + } + } + } + return true; + } + ts.every = every; + function find(array, predicate) { + for (var i = 0; i < array.length; i++) { + var value = array[i]; + if (predicate(value, i)) { + return value; + } + } + return undefined; + } + ts.find = find; + function findLast(array, predicate) { + for (var i = array.length - 1; i >= 0; i--) { + var value = array[i]; + if (predicate(value, i)) { + return value; + } + } + return undefined; + } + ts.findLast = findLast; + function findIndex(array, predicate, startIndex) { + for (var i = startIndex || 0; i < array.length; i++) { + if (predicate(array[i], i)) { + return i; + } + } + return -1; + } + ts.findIndex = findIndex; + function findLastIndex(array, predicate, startIndex) { + for (var i = startIndex === undefined ? array.length - 1 : startIndex; i >= 0; i--) { + if (predicate(array[i], i)) { + return i; + } + } + return -1; + } + ts.findLastIndex = findLastIndex; + function findMap(array, callback) { + for (var i = 0; i < array.length; i++) { + var result = callback(array[i], i); + if (result) { + return result; + } + } + return Debug.fail(); + } + ts.findMap = findMap; + function contains(array, value, equalityComparer) { + if (equalityComparer === void 0) { equalityComparer = equateValues; } + if (array) { + for (var _i = 0, array_1 = array; _i < array_1.length; _i++) { + var v = array_1[_i]; + if (equalityComparer(v, value)) { + return true; + } + } + } + return false; + } + ts.contains = contains; + function arraysEqual(a, b, equalityComparer) { + if (equalityComparer === void 0) { equalityComparer = equateValues; } + return a.length === b.length && a.every(function (x, i) { return equalityComparer(x, b[i]); }); + } + ts.arraysEqual = arraysEqual; + function indexOfAnyCharCode(text, charCodes, start) { + for (var i = start || 0; i < text.length; i++) { + if (contains(charCodes, text.charCodeAt(i))) { + return i; + } + } + return -1; + } + ts.indexOfAnyCharCode = indexOfAnyCharCode; + function countWhere(array, predicate) { + var count = 0; + if (array) { + for (var i = 0; i < array.length; i++) { + var v = array[i]; + if (predicate(v, i)) { + count++; + } + } + } + return count; + } + ts.countWhere = countWhere; + function filter(array, f) { + if (array) { + var len = array.length; + var i = 0; + while (i < len && f(array[i])) + i++; + if (i < len) { + var result = array.slice(0, i); + i++; + while (i < len) { + var item = array[i]; + if (f(item)) { + result.push(item); + } + i++; + } + return result; + } + } + return array; + } + ts.filter = filter; + function filterMutate(array, f) { + var outIndex = 0; + for (var i = 0; i < array.length; i++) { + if (f(array[i], i, array)) { + array[outIndex] = array[i]; + outIndex++; + } + } + array.length = outIndex; + } + ts.filterMutate = filterMutate; + function clear(array) { + array.length = 0; + } + ts.clear = clear; + function map(array, f) { + var result; + if (array) { + result = []; + for (var i = 0; i < array.length; i++) { + result.push(f(array[i], i)); + } + } + return result; + } + ts.map = map; + function mapIterator(iter, mapFn) { + return { + next: function () { + var iterRes = iter.next(); + return iterRes.done ? iterRes : { value: mapFn(iterRes.value), done: false }; + } + }; + } + ts.mapIterator = mapIterator; + function sameMap(array, f) { + if (array) { + for (var i = 0; i < array.length; i++) { + var item = array[i]; + var mapped = f(item, i); + if (item !== mapped) { + var result = array.slice(0, i); + result.push(mapped); + for (i++; i < array.length; i++) { + result.push(f(array[i], i)); + } + return result; + } + } + } + return array; + } + ts.sameMap = sameMap; + function flatten(array) { + var result; + if (array) { + result = []; + for (var _i = 0, array_2 = array; _i < array_2.length; _i++) { + var v = array_2[_i]; + if (v) { + if (isArray(v)) { + addRange(result, v); + } + else { + result.push(v); + } + } + } + } + return result; + } + ts.flatten = flatten; + function flatMap(array, mapfn) { + var result; + if (array) { + for (var i = 0; i < array.length; i++) { + var v = mapfn(array[i], i); + if (v) { + if (isArray(v)) { + result = addRange(result, v); + } + else { + result = append(result, v); + } + } + } + } + return result || ts.emptyArray; + } + ts.flatMap = flatMap; + function flatMapToMutable(array, mapfn) { + var result = []; + if (array) { + for (var i = 0; i < array.length; i++) { + var v = mapfn(array[i], i); + if (v) { + if (isArray(v)) { + addRange(result, v); + } + else { + result.push(v); + } + } + } + } + return result; + } + ts.flatMapToMutable = flatMapToMutable; + function flatMapIterator(iter, mapfn) { + var first = iter.next(); + if (first.done) { + return ts.emptyIterator; + } + var currentIter = getIterator(first.value); + return { + next: function () { + while (true) { + var currentRes = currentIter.next(); + if (!currentRes.done) { + return currentRes; + } + var iterRes = iter.next(); + if (iterRes.done) { + return iterRes; + } + currentIter = getIterator(iterRes.value); + } + }, + }; + function getIterator(x) { + var res = mapfn(x); + return res === undefined ? ts.emptyIterator : isArray(res) ? arrayIterator(res) : res; + } + } + ts.flatMapIterator = flatMapIterator; + function sameFlatMap(array, mapfn) { + var result; + if (array) { + for (var i = 0; i < array.length; i++) { + var item = array[i]; + var mapped = mapfn(item, i); + if (result || item !== mapped || isArray(mapped)) { + if (!result) { + result = array.slice(0, i); + } + if (isArray(mapped)) { + addRange(result, mapped); + } + else { + result.push(mapped); + } + } + } + } + return result || array; + } + ts.sameFlatMap = sameFlatMap; + function mapAllOrFail(array, mapFn) { + var result = []; + for (var i = 0; i < array.length; i++) { + var mapped = mapFn(array[i], i); + if (mapped === undefined) { + return undefined; + } + result.push(mapped); + } + return result; + } + ts.mapAllOrFail = mapAllOrFail; + function mapDefined(array, mapFn) { + var result = []; + if (array) { + for (var i = 0; i < array.length; i++) { + var mapped = mapFn(array[i], i); + if (mapped !== undefined) { + result.push(mapped); + } + } + } + return result; + } + ts.mapDefined = mapDefined; + function mapDefinedIterator(iter, mapFn) { + return { + next: function () { + while (true) { + var res = iter.next(); + if (res.done) { + return res; + } + var value = mapFn(res.value); + if (value !== undefined) { + return { value: value, done: false }; + } + } + } + }; + } + ts.mapDefinedIterator = mapDefinedIterator; + ts.emptyIterator = { next: function () { return ({ value: undefined, done: true }); } }; + function singleIterator(value) { + var done = false; + return { + next: function () { + var wasDone = done; + done = true; + return wasDone ? { value: undefined, done: true } : { value: value, done: false }; + } + }; + } + ts.singleIterator = singleIterator; + function spanMap(array, keyfn, mapfn) { + var result; + if (array) { + result = []; + var len = array.length; + var previousKey = void 0; + var key = void 0; + var start = 0; + var pos = 0; + while (start < len) { + while (pos < len) { + var value = array[pos]; + key = keyfn(value, pos); + if (pos === 0) { + previousKey = key; + } + else if (key !== previousKey) { + break; + } + pos++; + } + if (start < pos) { + var v = mapfn(array.slice(start, pos), previousKey, start, pos); + if (v) { + result.push(v); + } + start = pos; + } + previousKey = key; + pos++; + } + } + return result; + } + ts.spanMap = spanMap; + function mapEntries(map, f) { + if (!map) { + return undefined; + } + var result = createMap(); + map.forEach(function (value, key) { + var _a = f(key, value), newKey = _a[0], newValue = _a[1]; + result.set(newKey, newValue); + }); + return result; + } + ts.mapEntries = mapEntries; + function some(array, predicate) { + if (array) { + if (predicate) { + for (var _i = 0, array_3 = array; _i < array_3.length; _i++) { + var v = array_3[_i]; + if (predicate(v)) { + return true; + } + } + } + else { + return array.length > 0; + } + } + return false; + } + ts.some = some; + function getRangesWhere(arr, pred, cb) { + var start; + for (var i = 0; i < arr.length; i++) { + if (pred(arr[i])) { + start = start === undefined ? i : start; + } + else { + if (start !== undefined) { + cb(start, i); + start = undefined; + } + } + } + if (start !== undefined) + cb(start, arr.length); + } + ts.getRangesWhere = getRangesWhere; + function concatenate(array1, array2) { + if (!some(array2)) + return array1; + if (!some(array1)) + return array2; + return array1.concat(array2); + } + ts.concatenate = concatenate; + function deduplicateRelational(array, equalityComparer, comparer) { + var indices = array.map(function (_, i) { return i; }); + stableSortIndices(array, indices, comparer); + var last = array[indices[0]]; + var deduplicated = [indices[0]]; + for (var i = 1; i < indices.length; i++) { + var index = indices[i]; + var item = array[index]; + if (!equalityComparer(last, item)) { + deduplicated.push(index); + last = item; + } + } + deduplicated.sort(); + return deduplicated.map(function (i) { return array[i]; }); + } + function deduplicateEquality(array, equalityComparer) { + var result = []; + for (var _i = 0, array_4 = array; _i < array_4.length; _i++) { + var item = array_4[_i]; + pushIfUnique(result, item, equalityComparer); + } + return result; + } + function deduplicate(array, equalityComparer, comparer) { + return array.length === 0 ? [] : + array.length === 1 ? array.slice() : + comparer ? deduplicateRelational(array, equalityComparer, comparer) : + deduplicateEquality(array, equalityComparer); + } + ts.deduplicate = deduplicate; + function deduplicateSorted(array, comparer) { + if (array.length === 0) + return ts.emptyArray; + var last = array[0]; + var deduplicated = [last]; + for (var i = 1; i < array.length; i++) { + var next = array[i]; + switch (comparer(next, last)) { + case true: + case 0: + continue; + case -1: + return Debug.fail("Array is unsorted."); + } + deduplicated.push(last = next); + } + return deduplicated; + } + function insertSorted(array, insert, compare) { + if (array.length === 0) { + array.push(insert); + return; + } + var insertIndex = binarySearch(array, insert, identity, compare); + if (insertIndex < 0) { + array.splice(~insertIndex, 0, insert); + } + } + ts.insertSorted = insertSorted; + function sortAndDeduplicate(array, comparer, equalityComparer) { + return deduplicateSorted(sort(array, comparer), equalityComparer || comparer || compareStringsCaseSensitive); + } + ts.sortAndDeduplicate = sortAndDeduplicate; + function arrayIsEqualTo(array1, array2, equalityComparer) { + if (equalityComparer === void 0) { equalityComparer = equateValues; } + if (!array1 || !array2) { + return array1 === array2; + } + if (array1.length !== array2.length) { + return false; + } + for (var i = 0; i < array1.length; i++) { + if (!equalityComparer(array1[i], array2[i], i)) { + return false; + } + } + return true; + } + ts.arrayIsEqualTo = arrayIsEqualTo; + function compact(array) { + var result; + if (array) { + for (var i = 0; i < array.length; i++) { + var v = array[i]; + if (result || !v) { + if (!result) { + result = array.slice(0, i); + } + if (v) { + result.push(v); + } + } + } + } + return result || array; + } + ts.compact = compact; + function relativeComplement(arrayA, arrayB, comparer) { + if (!arrayB || !arrayA || arrayB.length === 0 || arrayA.length === 0) + return arrayB; + var result = []; + loopB: for (var offsetA = 0, offsetB = 0; offsetB < arrayB.length; offsetB++) { + if (offsetB > 0) { + Debug.assertGreaterThanOrEqual(comparer(arrayB[offsetB], arrayB[offsetB - 1]), 0); + } + loopA: for (var startA = offsetA; offsetA < arrayA.length; offsetA++) { + if (offsetA > startA) { + Debug.assertGreaterThanOrEqual(comparer(arrayA[offsetA], arrayA[offsetA - 1]), 0); + } + switch (comparer(arrayB[offsetB], arrayA[offsetA])) { + case -1: + result.push(arrayB[offsetB]); + continue loopB; + case 0: + continue loopB; + case 1: + continue loopA; + } + } + } + return result; + } + ts.relativeComplement = relativeComplement; + function sum(array, prop) { + var result = 0; + for (var _i = 0, array_5 = array; _i < array_5.length; _i++) { + var v = array_5[_i]; + result += v[prop]; + } + return result; + } + ts.sum = sum; + function append(to, value) { + if (value === undefined) + return to; + if (to === undefined) + return [value]; + to.push(value); + return to; + } + ts.append = append; + function toOffset(array, offset) { + return offset < 0 ? array.length + offset : offset; + } + function addRange(to, from, start, end) { + if (from === undefined || from.length === 0) + return to; + if (to === undefined) + return from.slice(start, end); + start = start === undefined ? 0 : toOffset(from, start); + end = end === undefined ? from.length : toOffset(from, end); + for (var i = start; i < end && i < from.length; i++) { + if (from[i] !== undefined) { + to.push(from[i]); + } + } + return to; + } + ts.addRange = addRange; + function pushIfUnique(array, toAdd, equalityComparer) { + if (contains(array, toAdd, equalityComparer)) { + return false; + } + else { + array.push(toAdd); + return true; + } + } + ts.pushIfUnique = pushIfUnique; + function appendIfUnique(array, toAdd, equalityComparer) { + if (array) { + pushIfUnique(array, toAdd, equalityComparer); + return array; + } + else { + return [toAdd]; + } + } + ts.appendIfUnique = appendIfUnique; + function stableSortIndices(array, indices, comparer) { + indices.sort(function (x, y) { return comparer(array[x], array[y]) || compareValues(x, y); }); + } + function sort(array, comparer) { + return (array.length === 0 ? array : array.slice().sort(comparer)); + } + ts.sort = sort; + function arrayIterator(array) { + var i = 0; + return { next: function () { + if (i === array.length) { + return { value: undefined, done: true }; + } + else { + i++; + return { value: array[i - 1], done: false }; + } + } }; + } + ts.arrayIterator = arrayIterator; + function stableSort(array, comparer) { + var indices = array.map(function (_, i) { return i; }); + stableSortIndices(array, indices, comparer); + return indices.map(function (i) { return array[i]; }); + } + ts.stableSort = stableSort; + function rangeEquals(array1, array2, pos, end) { + while (pos < end) { + if (array1[pos] !== array2[pos]) { + return false; + } + pos++; + } + return true; + } + ts.rangeEquals = rangeEquals; + function elementAt(array, offset) { + if (array) { + offset = toOffset(array, offset); + if (offset < array.length) { + return array[offset]; + } + } + return undefined; + } + ts.elementAt = elementAt; + function firstOrUndefined(array) { + return array.length === 0 ? undefined : array[0]; + } + ts.firstOrUndefined = firstOrUndefined; + function first(array) { + Debug.assert(array.length !== 0); + return array[0]; + } + ts.first = first; + function lastOrUndefined(array) { + return array.length === 0 ? undefined : array[array.length - 1]; + } + ts.lastOrUndefined = lastOrUndefined; + function last(array) { + Debug.assert(array.length !== 0); + return array[array.length - 1]; + } + ts.last = last; + function singleOrUndefined(array) { + return array && array.length === 1 + ? array[0] + : undefined; + } + ts.singleOrUndefined = singleOrUndefined; + function singleOrMany(array) { + return array && array.length === 1 + ? array[0] + : array; + } + ts.singleOrMany = singleOrMany; + function replaceElement(array, index, value) { + var result = array.slice(0); + result[index] = value; + return result; + } + ts.replaceElement = replaceElement; + function binarySearch(array, value, keySelector, keyComparer, offset) { + return binarySearchKey(array, keySelector(value), keySelector, keyComparer, offset); + } + ts.binarySearch = binarySearch; + function binarySearchKey(array, key, keySelector, keyComparer, offset) { + if (!some(array)) { + return -1; + } + var low = offset || 0; + var high = array.length - 1; + while (low <= high) { + var middle = low + ((high - low) >> 1); + var midKey = keySelector(array[middle]); + switch (keyComparer(midKey, key)) { + case -1: + low = middle + 1; + break; + case 0: + return middle; + case 1: + high = middle - 1; + break; + } + } + return ~low; + } + ts.binarySearchKey = binarySearchKey; + function reduceLeft(array, f, initial, start, count) { + if (array && array.length > 0) { + var size = array.length; + if (size > 0) { + var pos = start === undefined || start < 0 ? 0 : start; + var end = count === undefined || pos + count > size - 1 ? size - 1 : pos + count; + var result = void 0; + if (arguments.length <= 2) { + result = array[pos]; + pos++; + } + else { + result = initial; + } + while (pos <= end) { + result = f(result, array[pos], pos); + pos++; + } + return result; + } + } + return initial; + } + ts.reduceLeft = reduceLeft; + var hasOwnProperty = Object.prototype.hasOwnProperty; + function hasProperty(map, key) { + return hasOwnProperty.call(map, key); + } + ts.hasProperty = hasProperty; + function getProperty(map, key) { + return hasOwnProperty.call(map, key) ? map[key] : undefined; + } + ts.getProperty = getProperty; + function getOwnKeys(map) { + var keys = []; + for (var key in map) { + if (hasOwnProperty.call(map, key)) { + keys.push(key); + } + } + return keys; + } + ts.getOwnKeys = getOwnKeys; + function getOwnValues(sparseArray) { + var values = []; + for (var key in sparseArray) { + if (hasOwnProperty.call(sparseArray, key)) { + values.push(sparseArray[key]); + } + } + return values; + } + ts.getOwnValues = getOwnValues; + function arrayFrom(iterator, map) { + var _a; + var result = []; + for (var _b = iterator.next(), value = _b.value, done = _b.done; !done; _a = iterator.next(), value = _a.value, done = _a.done, _a) { + result.push(map ? map(value) : value); + } + return result; + } + ts.arrayFrom = arrayFrom; + function assign(t) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + for (var _a = 0, args_1 = args; _a < args_1.length; _a++) { + var arg = args_1[_a]; + for (var p in arg) { + if (hasProperty(arg, p)) { + t[p] = arg[p]; + } + } + } + return t; + } + ts.assign = assign; + function equalOwnProperties(left, right, equalityComparer) { + if (equalityComparer === void 0) { equalityComparer = equateValues; } + if (left === right) + return true; + if (!left || !right) + return false; + for (var key in left) { + if (hasOwnProperty.call(left, key)) { + if (!hasOwnProperty.call(right, key)) + return false; + if (!equalityComparer(left[key], right[key])) + return false; + } + } + for (var key in right) { + if (hasOwnProperty.call(right, key)) { + if (!hasOwnProperty.call(left, key)) + return false; + } + } + return true; + } + ts.equalOwnProperties = equalOwnProperties; + function arrayToMap(array, makeKey, makeValue) { + if (makeValue === void 0) { makeValue = identity; } + var result = createMap(); + for (var _i = 0, array_6 = array; _i < array_6.length; _i++) { + var value = array_6[_i]; + var key = makeKey(value); + if (key !== undefined) + result.set(key, makeValue(value)); + } + return result; + } + ts.arrayToMap = arrayToMap; + function arrayToNumericMap(array, makeKey, makeValue) { + if (makeValue === void 0) { makeValue = identity; } + var result = []; + for (var _i = 0, array_7 = array; _i < array_7.length; _i++) { + var value = array_7[_i]; + result[makeKey(value)] = makeValue(value); + } + return result; + } + ts.arrayToNumericMap = arrayToNumericMap; + function arrayToMultiMap(values, makeKey, makeValue) { + if (makeValue === void 0) { makeValue = identity; } + var result = createMultiMap(); + for (var _i = 0, values_1 = values; _i < values_1.length; _i++) { + var value = values_1[_i]; + result.add(makeKey(value), makeValue(value)); + } + return result; + } + ts.arrayToMultiMap = arrayToMultiMap; + function group(values, getGroupId) { + return arrayFrom(arrayToMultiMap(values, getGroupId).values()); + } + ts.group = group; + function clone(object) { + var result = {}; + for (var id in object) { + if (hasOwnProperty.call(object, id)) { + result[id] = object[id]; + } + } + return result; + } + ts.clone = clone; + function extend(first, second) { + var result = {}; + for (var id in second) { + if (hasOwnProperty.call(second, id)) { + result[id] = second[id]; + } + } + for (var id in first) { + if (hasOwnProperty.call(first, id)) { + result[id] = first[id]; + } + } + return result; + } + ts.extend = extend; + function createMultiMap() { + var map = createMap(); + map.add = multiMapAdd; + map.remove = multiMapRemove; + return map; + } + ts.createMultiMap = createMultiMap; + function multiMapAdd(key, value) { + var values = this.get(key); + if (values) { + values.push(value); + } + else { + this.set(key, values = [value]); + } + return values; + } + function multiMapRemove(key, value) { + var values = this.get(key); + if (values) { + unorderedRemoveItem(values, value); + if (!values.length) { + this.delete(key); + } + } + } + function isArray(value) { + return Array.isArray ? Array.isArray(value) : value instanceof Array; + } + ts.isArray = isArray; + function toArray(value) { + return isArray(value) ? value : [value]; + } + ts.toArray = toArray; + function isString(text) { + return typeof text === "string"; + } + ts.isString = isString; + function isNumber(x) { + return typeof x === "number"; + } + ts.isNumber = isNumber; + function tryCast(value, test) { + return value !== undefined && test(value) ? value : undefined; + } + ts.tryCast = tryCast; + function cast(value, test) { + if (value !== undefined && test(value)) + return value; + return Debug.fail("Invalid cast. The supplied value " + value + " did not pass the test '" + Debug.getFunctionName(test) + "'."); + } + ts.cast = cast; + function noop(_) { } + ts.noop = noop; + function returnFalse() { return false; } + ts.returnFalse = returnFalse; + function returnTrue() { return true; } + ts.returnTrue = returnTrue; + function identity(x) { return x; } + ts.identity = identity; + function toLowerCase(x) { return x.toLowerCase(); } + ts.toLowerCase = toLowerCase; + function notImplemented() { + throw new Error("Not implemented"); + } + ts.notImplemented = notImplemented; + function memoize(callback) { + var value; + return function () { + if (callback) { + value = callback(); + callback = undefined; + } + return value; + }; + } + ts.memoize = memoize; + function chain(a, b, c, d, e) { + if (e) { + var args_2 = []; + for (var i = 0; i < arguments.length; i++) { + args_2[i] = arguments[i]; + } + return function (t) { return compose.apply(void 0, map(args_2, function (f) { return f(t); })); }; + } + else if (d) { + return function (t) { return compose(a(t), b(t), c(t), d(t)); }; + } + else if (c) { + return function (t) { return compose(a(t), b(t), c(t)); }; + } + else if (b) { + return function (t) { return compose(a(t), b(t)); }; + } + else if (a) { + return function (t) { return compose(a(t)); }; + } + else { + return function (_) { return function (u) { return u; }; }; + } + } + ts.chain = chain; + function compose(a, b, c, d, e) { + if (e) { + var args_3 = []; + for (var i = 0; i < arguments.length; i++) { + args_3[i] = arguments[i]; + } + return function (t) { return reduceLeft(args_3, function (u, f) { return f(u); }, t); }; + } + else if (d) { + return function (t) { return d(c(b(a(t)))); }; + } + else if (c) { + return function (t) { return c(b(a(t))); }; + } + else if (b) { + return function (t) { return b(a(t)); }; + } + else if (a) { + return function (t) { return a(t); }; + } + else { + return function (t) { return t; }; + } + } + ts.compose = compose; + var Debug; + (function (Debug) { + Debug.currentAssertionLevel = 0; + Debug.isDebugging = false; + function shouldAssert(level) { + return Debug.currentAssertionLevel >= level; + } + Debug.shouldAssert = shouldAssert; + function assert(expression, message, verboseDebugInfo, stackCrawlMark) { + if (!expression) { + if (verboseDebugInfo) { + message += "\r\nVerbose Debug Information: " + (typeof verboseDebugInfo === "string" ? verboseDebugInfo : verboseDebugInfo()); + } + fail(message ? "False expression: " + message : "False expression.", stackCrawlMark || assert); + } + } + Debug.assert = assert; + function assertEqual(a, b, msg, msg2) { + if (a !== b) { + var message = msg ? msg2 ? msg + " " + msg2 : msg : ""; + fail("Expected " + a + " === " + b + ". " + message); + } + } + Debug.assertEqual = assertEqual; + function assertLessThan(a, b, msg) { + if (a >= b) { + fail("Expected " + a + " < " + b + ". " + (msg || "")); + } + } + Debug.assertLessThan = assertLessThan; + function assertLessThanOrEqual(a, b) { + if (a > b) { + fail("Expected " + a + " <= " + b); + } + } + Debug.assertLessThanOrEqual = assertLessThanOrEqual; + function assertGreaterThanOrEqual(a, b) { + if (a < b) { + fail("Expected " + a + " >= " + b); + } + } + Debug.assertGreaterThanOrEqual = assertGreaterThanOrEqual; + function fail(message, stackCrawlMark) { + debugger; + var e = new Error(message ? "Debug Failure. " + message : "Debug Failure."); + if (Error.captureStackTrace) { + Error.captureStackTrace(e, stackCrawlMark || fail); + } + throw e; + } + Debug.fail = fail; + function assertDefined(value, message) { + if (value === undefined || value === null) + return fail(message); + return value; + } + Debug.assertDefined = assertDefined; + function assertEachDefined(value, message) { + for (var _i = 0, value_1 = value; _i < value_1.length; _i++) { + var v = value_1[_i]; + assertDefined(v, message); + } + return value; + } + Debug.assertEachDefined = assertEachDefined; + function assertNever(member, message, stackCrawlMark) { + if (message === void 0) { message = "Illegal value:"; } + var detail = "kind" in member && "pos" in member ? "SyntaxKind: " + Debug.showSyntaxKind(member) : JSON.stringify(member); + return fail(message + " " + detail, stackCrawlMark || assertNever); + } + Debug.assertNever = assertNever; + function getFunctionName(func) { + if (typeof func !== "function") { + return ""; + } + else if (func.hasOwnProperty("name")) { + return func.name; + } + else { + var text = Function.prototype.toString.call(func); + var match = /^function\s+([\w\$]+)\s*\(/.exec(text); + return match ? match[1] : ""; + } + } + Debug.getFunctionName = getFunctionName; + })(Debug = ts.Debug || (ts.Debug = {})); + function equateValues(a, b) { + return a === b; + } + ts.equateValues = equateValues; + function equateStringsCaseInsensitive(a, b) { + return a === b + || a !== undefined + && b !== undefined + && a.toUpperCase() === b.toUpperCase(); + } + ts.equateStringsCaseInsensitive = equateStringsCaseInsensitive; + function equateStringsCaseSensitive(a, b) { + return equateValues(a, b); + } + ts.equateStringsCaseSensitive = equateStringsCaseSensitive; + function compareComparableValues(a, b) { + return a === b ? 0 : + a === undefined ? -1 : + b === undefined ? 1 : + a < b ? -1 : + 1; + } + function compareValues(a, b) { + return compareComparableValues(a, b); + } + ts.compareValues = compareValues; + function min(a, b, compare) { + return compare(a, b) === -1 ? a : b; + } + ts.min = min; + function compareStringsCaseInsensitive(a, b) { + if (a === b) + return 0; + if (a === undefined) + return -1; + if (b === undefined) + return 1; + a = a.toUpperCase(); + b = b.toUpperCase(); + return a < b ? -1 : a > b ? 1 : 0; + } + ts.compareStringsCaseInsensitive = compareStringsCaseInsensitive; + function compareStringsCaseSensitive(a, b) { + return compareComparableValues(a, b); + } + ts.compareStringsCaseSensitive = compareStringsCaseSensitive; + function getStringComparer(ignoreCase) { + return ignoreCase ? compareStringsCaseInsensitive : compareStringsCaseSensitive; + } + ts.getStringComparer = getStringComparer; + var createUIStringComparer = (function () { + var defaultComparer; + var enUSComparer; + var stringComparerFactory = getStringComparerFactory(); + return createStringComparer; + function compareWithCallback(a, b, comparer) { + if (a === b) + return 0; + if (a === undefined) + return -1; + if (b === undefined) + return 1; + var value = comparer(a, b); + return value < 0 ? -1 : value > 0 ? 1 : 0; + } + function createIntlCollatorStringComparer(locale) { + var comparer = new Intl.Collator(locale, { usage: "sort", sensitivity: "variant" }).compare; + return function (a, b) { return compareWithCallback(a, b, comparer); }; + } + function createLocaleCompareStringComparer(locale) { + if (locale !== undefined) + return createFallbackStringComparer(); + return function (a, b) { return compareWithCallback(a, b, compareStrings); }; + function compareStrings(a, b) { + return a.localeCompare(b); + } + } + function createFallbackStringComparer() { + return function (a, b) { return compareWithCallback(a, b, compareDictionaryOrder); }; + function compareDictionaryOrder(a, b) { + return compareStrings(a.toUpperCase(), b.toUpperCase()) || compareStrings(a, b); + } + function compareStrings(a, b) { + return a < b ? -1 : a > b ? 1 : 0; + } + } + function getStringComparerFactory() { + if (typeof Intl === "object" && typeof Intl.Collator === "function") { + return createIntlCollatorStringComparer; + } + if (typeof String.prototype.localeCompare === "function" && + typeof String.prototype.toLocaleUpperCase === "function" && + "a".localeCompare("B") < 0) { + return createLocaleCompareStringComparer; + } + return createFallbackStringComparer; + } + function createStringComparer(locale) { + if (locale === undefined) { + return defaultComparer || (defaultComparer = stringComparerFactory(locale)); + } + else if (locale === "en-US") { + return enUSComparer || (enUSComparer = stringComparerFactory(locale)); + } + else { + return stringComparerFactory(locale); + } + } + })(); + var uiComparerCaseSensitive; + var uiLocale; + function getUILocale() { + return uiLocale; + } + ts.getUILocale = getUILocale; + function setUILocale(value) { + if (uiLocale !== value) { + uiLocale = value; + uiComparerCaseSensitive = undefined; + } + } + ts.setUILocale = setUILocale; + function compareStringsCaseSensitiveUI(a, b) { + var comparer = uiComparerCaseSensitive || (uiComparerCaseSensitive = createUIStringComparer(uiLocale)); + return comparer(a, b); + } + ts.compareStringsCaseSensitiveUI = compareStringsCaseSensitiveUI; + function compareProperties(a, b, key, comparer) { + return a === b ? 0 : + a === undefined ? -1 : + b === undefined ? 1 : + comparer(a[key], b[key]); + } + ts.compareProperties = compareProperties; + function compareBooleans(a, b) { + return compareValues(a ? 1 : 0, b ? 1 : 0); + } + ts.compareBooleans = compareBooleans; + function getSpellingSuggestion(name, candidates, getName) { + var maximumLengthDifference = Math.min(2, Math.floor(name.length * 0.34)); + var bestDistance = Math.floor(name.length * 0.4) + 1; + var bestCandidate; + var justCheckExactMatches = false; + var nameLowerCase = name.toLowerCase(); + for (var _i = 0, candidates_1 = candidates; _i < candidates_1.length; _i++) { + var candidate = candidates_1[_i]; + var candidateName = getName(candidate); + if (candidateName !== undefined && Math.abs(candidateName.length - nameLowerCase.length) <= maximumLengthDifference) { + var candidateNameLowerCase = candidateName.toLowerCase(); + if (candidateNameLowerCase === nameLowerCase) { + if (candidateName === name) { + continue; + } + return candidate; + } + if (justCheckExactMatches) { + continue; + } + if (candidateName.length < 3) { + continue; + } + var distance = levenshteinWithMax(nameLowerCase, candidateNameLowerCase, bestDistance - 1); + if (distance === undefined) { + continue; + } + if (distance < 3) { + justCheckExactMatches = true; + bestCandidate = candidate; + } + else { + Debug.assert(distance < bestDistance); + bestDistance = distance; + bestCandidate = candidate; + } + } + } + return bestCandidate; + } + ts.getSpellingSuggestion = getSpellingSuggestion; + function levenshteinWithMax(s1, s2, max) { + var previous = new Array(s2.length + 1); + var current = new Array(s2.length + 1); + var big = max + 1; + for (var i = 0; i <= s2.length; i++) { + previous[i] = i; + } + for (var i = 1; i <= s1.length; i++) { + var c1 = s1.charCodeAt(i - 1); + var minJ = i > max ? i - max : 1; + var maxJ = s2.length > max + i ? max + i : s2.length; + current[0] = i; + var colMin = i; + for (var j = 1; j < minJ; j++) { + current[j] = big; + } + for (var j = minJ; j <= maxJ; j++) { + var dist = c1 === s2.charCodeAt(j - 1) + ? previous[j - 1] + : Math.min(previous[j] + 1, current[j - 1] + 1, previous[j - 1] + 2); + current[j] = dist; + colMin = Math.min(colMin, dist); + } + for (var j = maxJ + 1; j <= s2.length; j++) { + current[j] = big; + } + if (colMin > max) { + return undefined; + } + var temp = previous; + previous = current; + current = temp; + } + var res = previous[s2.length]; + return res > max ? undefined : res; + } + function endsWith(str, suffix) { + var expectedPos = str.length - suffix.length; + return expectedPos >= 0 && str.indexOf(suffix, expectedPos) === expectedPos; + } + ts.endsWith = endsWith; + function removeSuffix(str, suffix) { + return endsWith(str, suffix) ? str.slice(0, str.length - suffix.length) : str; + } + ts.removeSuffix = removeSuffix; + function tryRemoveSuffix(str, suffix) { + return endsWith(str, suffix) ? str.slice(0, str.length - suffix.length) : undefined; + } + ts.tryRemoveSuffix = tryRemoveSuffix; + function stringContains(str, substring) { + return str.indexOf(substring) !== -1; + } + ts.stringContains = stringContains; + function fileExtensionIs(path, extension) { + return path.length > extension.length && endsWith(path, extension); + } + ts.fileExtensionIs = fileExtensionIs; + function fileExtensionIsOneOf(path, extensions) { + for (var _i = 0, extensions_1 = extensions; _i < extensions_1.length; _i++) { + var extension = extensions_1[_i]; + if (fileExtensionIs(path, extension)) { + return true; + } + } + return false; + } + ts.fileExtensionIsOneOf = fileExtensionIsOneOf; + function removeMinAndVersionNumbers(fileName) { + var trailingMinOrVersion = /[.-]((min)|(\d+(\.\d+)*))$/; + return fileName.replace(trailingMinOrVersion, "").replace(trailingMinOrVersion, ""); + } + ts.removeMinAndVersionNumbers = removeMinAndVersionNumbers; + function orderedRemoveItem(array, item) { + for (var i = 0; i < array.length; i++) { + if (array[i] === item) { + orderedRemoveItemAt(array, i); + return true; + } + } + return false; + } + ts.orderedRemoveItem = orderedRemoveItem; + function orderedRemoveItemAt(array, index) { + for (var i = index; i < array.length - 1; i++) { + array[i] = array[i + 1]; + } + array.pop(); + } + ts.orderedRemoveItemAt = orderedRemoveItemAt; + function unorderedRemoveItemAt(array, index) { + array[index] = array[array.length - 1]; + array.pop(); + } + ts.unorderedRemoveItemAt = unorderedRemoveItemAt; + function unorderedRemoveItem(array, item) { + return unorderedRemoveFirstItemWhere(array, function (element) { return element === item; }); + } + ts.unorderedRemoveItem = unorderedRemoveItem; + function unorderedRemoveFirstItemWhere(array, predicate) { + for (var i = 0; i < array.length; i++) { + if (predicate(array[i])) { + unorderedRemoveItemAt(array, i); + return true; + } + } + return false; + } + function createGetCanonicalFileName(useCaseSensitiveFileNames) { + return useCaseSensitiveFileNames ? identity : toLowerCase; + } + ts.createGetCanonicalFileName = createGetCanonicalFileName; + function patternText(_a) { + var prefix = _a.prefix, suffix = _a.suffix; + return prefix + "*" + suffix; + } + ts.patternText = patternText; + function matchedText(pattern, candidate) { + Debug.assert(isPatternMatch(pattern, candidate)); + return candidate.substring(pattern.prefix.length, candidate.length - pattern.suffix.length); + } + ts.matchedText = matchedText; + function findBestPatternMatch(values, getPattern, candidate) { + var matchedValue; + var longestMatchPrefixLength = -1; + for (var _i = 0, values_2 = values; _i < values_2.length; _i++) { + var v = values_2[_i]; + var pattern = getPattern(v); + if (isPatternMatch(pattern, candidate) && pattern.prefix.length > longestMatchPrefixLength) { + longestMatchPrefixLength = pattern.prefix.length; + matchedValue = v; + } + } + return matchedValue; + } + ts.findBestPatternMatch = findBestPatternMatch; + function startsWith(str, prefix) { + return str.lastIndexOf(prefix, 0) === 0; + } + ts.startsWith = startsWith; + function removePrefix(str, prefix) { + return startsWith(str, prefix) ? str.substr(prefix.length) : str; + } + ts.removePrefix = removePrefix; + function tryRemovePrefix(str, prefix, getCanonicalFileName) { + if (getCanonicalFileName === void 0) { getCanonicalFileName = identity; } + return startsWith(getCanonicalFileName(str), getCanonicalFileName(prefix)) ? str.substring(prefix.length) : undefined; + } + ts.tryRemovePrefix = tryRemovePrefix; + function isPatternMatch(_a, candidate) { + var prefix = _a.prefix, suffix = _a.suffix; + return candidate.length >= prefix.length + suffix.length && + startsWith(candidate, prefix) && + endsWith(candidate, suffix); + } + function and(f, g) { + return function (arg) { return f(arg) && g(arg); }; + } + ts.and = and; + function or(f, g) { + return function (arg) { return f(arg) || g(arg); }; + } + ts.or = or; + function assertType(_) { } + ts.assertType = assertType; + function singleElementArray(t) { + return t === undefined ? undefined : [t]; + } + ts.singleElementArray = singleElementArray; + function enumerateInsertsAndDeletes(newItems, oldItems, comparer, inserted, deleted, unchanged) { + unchanged = unchanged || noop; + var newIndex = 0; + var oldIndex = 0; + var newLen = newItems.length; + var oldLen = oldItems.length; + while (newIndex < newLen && oldIndex < oldLen) { + var newItem = newItems[newIndex]; + var oldItem = oldItems[oldIndex]; + var compareResult = comparer(newItem, oldItem); + if (compareResult === -1) { + inserted(newItem); + newIndex++; + } + else if (compareResult === 1) { + deleted(oldItem); + oldIndex++; + } + else { + unchanged(oldItem, newItem); + newIndex++; + oldIndex++; + } + } + while (newIndex < newLen) { + inserted(newItems[newIndex++]); + } + while (oldIndex < oldLen) { + deleted(oldItems[oldIndex++]); + } + } + ts.enumerateInsertsAndDeletes = enumerateInsertsAndDeletes; + function fill(length, cb) { + return new Array(length).fill(0).map(function (_, i) { return cb(i); }); + } + ts.fill = fill; +})(ts || (ts = {})); +var ts; +(function (ts) { + ts.timestamp = typeof performance !== "undefined" && performance.now ? function () { return performance.now(); } : Date.now ? Date.now : function () { return +(new Date()); }; +})(ts || (ts = {})); +(function (ts) { + var performance; + (function (performance) { + var profilerEvent = typeof onProfilerEvent === "function" && onProfilerEvent.profiler === true ? onProfilerEvent : function () { }; + var enabled = false; + var profilerStart = 0; + var counts; + var marks; + var measures; + function createTimerIf(condition, measureName, startMarkName, endMarkName) { + return condition ? createTimer(measureName, startMarkName, endMarkName) : performance.nullTimer; + } + performance.createTimerIf = createTimerIf; + function createTimer(measureName, startMarkName, endMarkName) { + var enterCount = 0; + return { + enter: enter, + exit: exit + }; + function enter() { + if (++enterCount === 1) { + mark(startMarkName); + } + } + function exit() { + if (--enterCount === 0) { + mark(endMarkName); + measure(measureName, startMarkName, endMarkName); + } + else if (enterCount < 0) { + ts.Debug.fail("enter/exit count does not match."); + } + } + } + performance.createTimer = createTimer; + performance.nullTimer = { enter: ts.noop, exit: ts.noop }; + function mark(markName) { + if (enabled) { + marks.set(markName, ts.timestamp()); + counts.set(markName, (counts.get(markName) || 0) + 1); + profilerEvent(markName); + } + } + performance.mark = mark; + function measure(measureName, startMarkName, endMarkName) { + if (enabled) { + var end = endMarkName && marks.get(endMarkName) || ts.timestamp(); + var start = startMarkName && marks.get(startMarkName) || profilerStart; + measures.set(measureName, (measures.get(measureName) || 0) + (end - start)); + } + } + performance.measure = measure; + function getCount(markName) { + return counts && counts.get(markName) || 0; + } + performance.getCount = getCount; + function getDuration(measureName) { + return measures && measures.get(measureName) || 0; + } + performance.getDuration = getDuration; + function forEachMeasure(cb) { + measures.forEach(function (measure, key) { + cb(key, measure); + }); + } + performance.forEachMeasure = forEachMeasure; + function enable() { + counts = ts.createMap(); + marks = ts.createMap(); + measures = ts.createMap(); + enabled = true; + profilerStart = ts.timestamp(); + } + performance.enable = enable; + function disable() { + enabled = false; + } + performance.disable = disable; + })(performance = ts.performance || (ts.performance = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + var versionRegExp = /^(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\-([a-z0-9-.]+))?(?:\+([a-z0-9-.]+))?)?)?$/i; + var prereleaseRegExp = /^(?:0|[1-9]\d*|[a-z-][a-z0-9-]*)(?:\.(?:0|[1-9]\d*|[a-z-][a-z0-9-]*))*$/i; + var buildRegExp = /^[a-z0-9-]+(?:\.[a-z0-9-]+)*$/i; + var numericIdentifierRegExp = /^(0|[1-9]\d*)$/; + var Version = (function () { + function Version(major, minor, patch, prerelease, build) { + if (minor === void 0) { minor = 0; } + if (patch === void 0) { patch = 0; } + if (prerelease === void 0) { prerelease = ""; } + if (build === void 0) { build = ""; } + if (typeof major === "string") { + var result = ts.Debug.assertDefined(tryParseComponents(major), "Invalid version"); + (major = result.major, minor = result.minor, patch = result.patch, prerelease = result.prerelease, build = result.build); + } + ts.Debug.assert(major >= 0, "Invalid argument: major"); + ts.Debug.assert(minor >= 0, "Invalid argument: minor"); + ts.Debug.assert(patch >= 0, "Invalid argument: patch"); + ts.Debug.assert(!prerelease || prereleaseRegExp.test(prerelease), "Invalid argument: prerelease"); + ts.Debug.assert(!build || buildRegExp.test(build), "Invalid argument: build"); + this.major = major; + this.minor = minor; + this.patch = patch; + this.prerelease = prerelease ? prerelease.split(".") : ts.emptyArray; + this.build = build ? build.split(".") : ts.emptyArray; + } + Version.tryParse = function (text) { + var result = tryParseComponents(text); + if (!result) + return undefined; + var major = result.major, minor = result.minor, patch = result.patch, prerelease = result.prerelease, build = result.build; + return new Version(major, minor, patch, prerelease, build); + }; + Version.prototype.compareTo = function (other) { + if (this === other) + return 0; + if (other === undefined) + return 1; + return ts.compareValues(this.major, other.major) + || ts.compareValues(this.minor, other.minor) + || ts.compareValues(this.patch, other.patch) + || comparePrerelaseIdentifiers(this.prerelease, other.prerelease); + }; + Version.prototype.increment = function (field) { + switch (field) { + case "major": return new Version(this.major + 1, 0, 0); + case "minor": return new Version(this.major, this.minor + 1, 0); + case "patch": return new Version(this.major, this.minor, this.patch + 1); + default: return ts.Debug.assertNever(field); + } + }; + Version.prototype.toString = function () { + var result = this.major + "." + this.minor + "." + this.patch; + if (ts.some(this.prerelease)) + result += "-" + this.prerelease.join("."); + if (ts.some(this.build)) + result += "+" + this.build.join("."); + return result; + }; + Version.zero = new Version(0, 0, 0); + return Version; + }()); + ts.Version = Version; + function tryParseComponents(text) { + var match = versionRegExp.exec(text); + if (!match) + return undefined; + var major = match[1], _a = match[2], minor = _a === void 0 ? "0" : _a, _b = match[3], patch = _b === void 0 ? "0" : _b, _c = match[4], prerelease = _c === void 0 ? "" : _c, _d = match[5], build = _d === void 0 ? "" : _d; + if (prerelease && !prereleaseRegExp.test(prerelease)) + return undefined; + if (build && !buildRegExp.test(build)) + return undefined; + return { + major: parseInt(major, 10), + minor: parseInt(minor, 10), + patch: parseInt(patch, 10), + prerelease: prerelease, + build: build + }; + } + function comparePrerelaseIdentifiers(left, right) { + if (left === right) + return 0; + if (left.length === 0) + return right.length === 0 ? 0 : 1; + if (right.length === 0) + return -1; + var length = Math.min(left.length, right.length); + for (var i = 0; i < length; i++) { + var leftIdentifier = left[i]; + var rightIdentifier = right[i]; + if (leftIdentifier === rightIdentifier) + continue; + var leftIsNumeric = numericIdentifierRegExp.test(leftIdentifier); + var rightIsNumeric = numericIdentifierRegExp.test(rightIdentifier); + if (leftIsNumeric || rightIsNumeric) { + if (leftIsNumeric !== rightIsNumeric) + return leftIsNumeric ? -1 : 1; + var result = ts.compareValues(+leftIdentifier, +rightIdentifier); + if (result) + return result; + } + else { + var result = ts.compareStringsCaseSensitive(leftIdentifier, rightIdentifier); + if (result) + return result; + } + } + return ts.compareValues(left.length, right.length); + } + var VersionRange = (function () { + function VersionRange(spec) { + this._alternatives = spec ? ts.Debug.assertDefined(parseRange(spec), "Invalid range spec.") : ts.emptyArray; + } + VersionRange.tryParse = function (text) { + var sets = parseRange(text); + if (sets) { + var range = new VersionRange(""); + range._alternatives = sets; + return range; + } + return undefined; + }; + VersionRange.prototype.test = function (version) { + if (typeof version === "string") + version = new Version(version); + return testDisjunction(version, this._alternatives); + }; + VersionRange.prototype.toString = function () { + return formatDisjunction(this._alternatives); + }; + return VersionRange; + }()); + ts.VersionRange = VersionRange; + var logicalOrRegExp = /\s*\|\|\s*/g; + var whitespaceRegExp = /\s+/g; + var partialRegExp = /^([xX*0]|[1-9]\d*)(?:\.([xX*0]|[1-9]\d*)(?:\.([xX*0]|[1-9]\d*)(?:-([a-z0-9-.]+))?(?:\+([a-z0-9-.]+))?)?)?$/i; + var hyphenRegExp = /^\s*([a-z0-9-+.*]+)\s+-\s+([a-z0-9-+.*]+)\s*$/i; + var rangeRegExp = /^\s*(~|\^|<|<=|>|>=|=)?\s*([a-z0-9-+.*]+)$/i; + function parseRange(text) { + var alternatives = []; + for (var _i = 0, _a = text.trim().split(logicalOrRegExp); _i < _a.length; _i++) { + var range = _a[_i]; + if (!range) + continue; + var comparators = []; + var match = hyphenRegExp.exec(range); + if (match) { + if (!parseHyphen(match[1], match[2], comparators)) + return undefined; + } + else { + for (var _b = 0, _c = range.split(whitespaceRegExp); _b < _c.length; _b++) { + var simple = _c[_b]; + var match_1 = rangeRegExp.exec(simple); + if (!match_1 || !parseComparator(match_1[1], match_1[2], comparators)) + return undefined; + } + } + alternatives.push(comparators); + } + return alternatives; + } + function parsePartial(text) { + var match = partialRegExp.exec(text); + if (!match) + return undefined; + var major = match[1], _a = match[2], minor = _a === void 0 ? "*" : _a, _b = match[3], patch = _b === void 0 ? "*" : _b, prerelease = match[4], build = match[5]; + var version = new Version(isWildcard(major) ? 0 : parseInt(major, 10), isWildcard(major) || isWildcard(minor) ? 0 : parseInt(minor, 10), isWildcard(major) || isWildcard(minor) || isWildcard(patch) ? 0 : parseInt(patch, 10), prerelease, build); + return { version: version, major: major, minor: minor, patch: patch }; + } + function parseHyphen(left, right, comparators) { + var leftResult = parsePartial(left); + if (!leftResult) + return false; + var rightResult = parsePartial(right); + if (!rightResult) + return false; + if (!isWildcard(leftResult.major)) { + comparators.push(createComparator(">=", leftResult.version)); + } + if (!isWildcard(rightResult.major)) { + comparators.push(isWildcard(rightResult.minor) ? createComparator("<", rightResult.version.increment("major")) : + isWildcard(rightResult.patch) ? createComparator("<", rightResult.version.increment("minor")) : + createComparator("<=", rightResult.version)); + } + return true; + } + function parseComparator(operator, text, comparators) { + var result = parsePartial(text); + if (!result) + return false; + var version = result.version, major = result.major, minor = result.minor, patch = result.patch; + if (!isWildcard(major)) { + switch (operator) { + case "~": + comparators.push(createComparator(">=", version)); + comparators.push(createComparator("<", version.increment(isWildcard(minor) ? "major" : + "minor"))); + break; + case "^": + comparators.push(createComparator(">=", version)); + comparators.push(createComparator("<", version.increment(version.major > 0 || isWildcard(minor) ? "major" : + version.minor > 0 || isWildcard(patch) ? "minor" : + "patch"))); + break; + case "<": + case ">=": + comparators.push(createComparator(operator, version)); + break; + case "<=": + case ">": + comparators.push(isWildcard(minor) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("major")) : + isWildcard(patch) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("minor")) : + createComparator(operator, version)); + break; + case "=": + case undefined: + if (isWildcard(minor) || isWildcard(patch)) { + comparators.push(createComparator(">=", version)); + comparators.push(createComparator("<", version.increment(isWildcard(minor) ? "major" : "minor"))); + } + else { + comparators.push(createComparator("=", version)); + } + break; + default: + return false; + } + } + else if (operator === "<" || operator === ">") { + comparators.push(createComparator("<", Version.zero)); + } + return true; + } + function isWildcard(part) { + return part === "*" || part === "x" || part === "X"; + } + function createComparator(operator, operand) { + return { operator: operator, operand: operand }; + } + function testDisjunction(version, alternatives) { + if (alternatives.length === 0) + return true; + for (var _i = 0, alternatives_1 = alternatives; _i < alternatives_1.length; _i++) { + var alternative = alternatives_1[_i]; + if (testAlternative(version, alternative)) + return true; + } + return false; + } + function testAlternative(version, comparators) { + for (var _i = 0, comparators_1 = comparators; _i < comparators_1.length; _i++) { + var comparator = comparators_1[_i]; + if (!testComparator(version, comparator.operator, comparator.operand)) + return false; + } + return true; + } + function testComparator(version, operator, operand) { + var cmp = version.compareTo(operand); + switch (operator) { + case "<": return cmp < 0; + case "<=": return cmp <= 0; + case ">": return cmp > 0; + case ">=": return cmp >= 0; + case "=": return cmp === 0; + default: return ts.Debug.assertNever(operator); + } + } + function formatDisjunction(alternatives) { + return ts.map(alternatives, formatAlternative).join(" || ") || "*"; + } + function formatAlternative(comparators) { + return ts.map(comparators, formatComparator).join(" "); + } + function formatComparator(comparator) { + return "" + comparator.operator + comparator.operand; + } +})(ts || (ts = {})); +var ts; +(function (ts) { + var OperationCanceledException = (function () { + function OperationCanceledException() { + } + return OperationCanceledException; + }()); + ts.OperationCanceledException = OperationCanceledException; + var ExitStatus; + (function (ExitStatus) { + ExitStatus[ExitStatus["Success"] = 0] = "Success"; + ExitStatus[ExitStatus["DiagnosticsPresent_OutputsSkipped"] = 1] = "DiagnosticsPresent_OutputsSkipped"; + ExitStatus[ExitStatus["DiagnosticsPresent_OutputsGenerated"] = 2] = "DiagnosticsPresent_OutputsGenerated"; + })(ExitStatus = ts.ExitStatus || (ts.ExitStatus = {})); + var TypeReferenceSerializationKind; + (function (TypeReferenceSerializationKind) { + TypeReferenceSerializationKind[TypeReferenceSerializationKind["Unknown"] = 0] = "Unknown"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["TypeWithConstructSignatureAndValue"] = 1] = "TypeWithConstructSignatureAndValue"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["VoidNullableOrNeverType"] = 2] = "VoidNullableOrNeverType"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["NumberLikeType"] = 3] = "NumberLikeType"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["BigIntLikeType"] = 4] = "BigIntLikeType"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["StringLikeType"] = 5] = "StringLikeType"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["BooleanType"] = 6] = "BooleanType"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["ArrayLikeType"] = 7] = "ArrayLikeType"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["ESSymbolType"] = 8] = "ESSymbolType"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["Promise"] = 9] = "Promise"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["TypeWithCallSignature"] = 10] = "TypeWithCallSignature"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["ObjectType"] = 11] = "ObjectType"; + })(TypeReferenceSerializationKind = ts.TypeReferenceSerializationKind || (ts.TypeReferenceSerializationKind = {})); + var DiagnosticCategory; + (function (DiagnosticCategory) { + DiagnosticCategory[DiagnosticCategory["Warning"] = 0] = "Warning"; + DiagnosticCategory[DiagnosticCategory["Error"] = 1] = "Error"; + DiagnosticCategory[DiagnosticCategory["Suggestion"] = 2] = "Suggestion"; + DiagnosticCategory[DiagnosticCategory["Message"] = 3] = "Message"; + })(DiagnosticCategory = ts.DiagnosticCategory || (ts.DiagnosticCategory = {})); + function diagnosticCategoryName(d, lowerCase) { + if (lowerCase === void 0) { lowerCase = true; } + var name = DiagnosticCategory[d.category]; + return lowerCase ? name.toLowerCase() : name; + } + ts.diagnosticCategoryName = diagnosticCategoryName; + var ModuleResolutionKind; + (function (ModuleResolutionKind) { + ModuleResolutionKind[ModuleResolutionKind["Classic"] = 1] = "Classic"; + ModuleResolutionKind[ModuleResolutionKind["NodeJs"] = 2] = "NodeJs"; + })(ModuleResolutionKind = ts.ModuleResolutionKind || (ts.ModuleResolutionKind = {})); + var ModuleKind; + (function (ModuleKind) { + ModuleKind[ModuleKind["None"] = 0] = "None"; + ModuleKind[ModuleKind["CommonJS"] = 1] = "CommonJS"; + ModuleKind[ModuleKind["AMD"] = 2] = "AMD"; + ModuleKind[ModuleKind["UMD"] = 3] = "UMD"; + ModuleKind[ModuleKind["System"] = 4] = "System"; + ModuleKind[ModuleKind["ES2015"] = 5] = "ES2015"; + ModuleKind[ModuleKind["ESNext"] = 6] = "ESNext"; + })(ModuleKind = ts.ModuleKind || (ts.ModuleKind = {})); + function _contextuallyTypePragmas(args) { + return args; + } + ts.commentPragmas = _contextuallyTypePragmas({ + "reference": { + args: [ + { name: "types", optional: true, captureSpan: true }, + { name: "lib", optional: true, captureSpan: true }, + { name: "path", optional: true, captureSpan: true }, + { name: "no-default-lib", optional: true } + ], + kind: 1 + }, + "amd-dependency": { + args: [{ name: "path" }, { name: "name", optional: true }], + kind: 1 + }, + "amd-module": { + args: [{ name: "name" }], + kind: 1 + }, + "ts-check": { + kind: 2 + }, + "ts-nocheck": { + kind: 2 + }, + "jsx": { + args: [{ name: "factory" }], + kind: 4 + }, + }); +})(ts || (ts = {})); +var ts; +(function (ts) { + function setStackTraceLimit() { + if (Error.stackTraceLimit < 100) { + Error.stackTraceLimit = 100; + } + } + ts.setStackTraceLimit = setStackTraceLimit; + var FileWatcherEventKind; + (function (FileWatcherEventKind) { + FileWatcherEventKind[FileWatcherEventKind["Created"] = 0] = "Created"; + FileWatcherEventKind[FileWatcherEventKind["Changed"] = 1] = "Changed"; + FileWatcherEventKind[FileWatcherEventKind["Deleted"] = 2] = "Deleted"; + })(FileWatcherEventKind = ts.FileWatcherEventKind || (ts.FileWatcherEventKind = {})); + var PollingInterval; + (function (PollingInterval) { + PollingInterval[PollingInterval["High"] = 2000] = "High"; + PollingInterval[PollingInterval["Medium"] = 500] = "Medium"; + PollingInterval[PollingInterval["Low"] = 250] = "Low"; + })(PollingInterval = ts.PollingInterval || (ts.PollingInterval = {})); + ts.missingFileModifiedTime = new Date(0); + function createPollingIntervalBasedLevels(levels) { + var _a; + return _a = {}, + _a[PollingInterval.Low] = levels.Low, + _a[PollingInterval.Medium] = levels.Medium, + _a[PollingInterval.High] = levels.High, + _a; + } + var defaultChunkLevels = { Low: 32, Medium: 64, High: 256 }; + var pollingChunkSize = createPollingIntervalBasedLevels(defaultChunkLevels); + ts.unchangedPollThresholds = createPollingIntervalBasedLevels(defaultChunkLevels); + function setCustomPollingValues(system) { + if (!system.getEnvironmentVariable) { + return; + } + var pollingIntervalChanged = setCustomLevels("TSC_WATCH_POLLINGINTERVAL", PollingInterval); + pollingChunkSize = getCustomPollingBasedLevels("TSC_WATCH_POLLINGCHUNKSIZE", defaultChunkLevels) || pollingChunkSize; + ts.unchangedPollThresholds = getCustomPollingBasedLevels("TSC_WATCH_UNCHANGEDPOLLTHRESHOLDS", defaultChunkLevels) || ts.unchangedPollThresholds; + function getLevel(envVar, level) { + return system.getEnvironmentVariable(envVar + "_" + level.toUpperCase()); + } + function getCustomLevels(baseVariable) { + var customLevels; + setCustomLevel("Low"); + setCustomLevel("Medium"); + setCustomLevel("High"); + return customLevels; + function setCustomLevel(level) { + var customLevel = getLevel(baseVariable, level); + if (customLevel) { + (customLevels || (customLevels = {}))[level] = Number(customLevel); + } + } + } + function setCustomLevels(baseVariable, levels) { + var customLevels = getCustomLevels(baseVariable); + if (customLevels) { + setLevel("Low"); + setLevel("Medium"); + setLevel("High"); + return true; + } + return false; + function setLevel(level) { + levels[level] = customLevels[level] || levels[level]; + } + } + function getCustomPollingBasedLevels(baseVariable, defaultLevels) { + var customLevels = getCustomLevels(baseVariable); + return (pollingIntervalChanged || customLevels) && + createPollingIntervalBasedLevels(customLevels ? __assign({}, defaultLevels, customLevels) : defaultLevels); + } + } + ts.setCustomPollingValues = setCustomPollingValues; + function createDynamicPriorityPollingWatchFile(host) { + var watchedFiles = []; + var changedFilesInLastPoll = []; + var lowPollingIntervalQueue = createPollingIntervalQueue(PollingInterval.Low); + var mediumPollingIntervalQueue = createPollingIntervalQueue(PollingInterval.Medium); + var highPollingIntervalQueue = createPollingIntervalQueue(PollingInterval.High); + return watchFile; + function watchFile(fileName, callback, defaultPollingInterval) { + var file = { + fileName: fileName, + callback: callback, + unchangedPolls: 0, + mtime: getModifiedTime(fileName) + }; + watchedFiles.push(file); + addToPollingIntervalQueue(file, defaultPollingInterval); + return { + close: function () { + file.isClosed = true; + ts.unorderedRemoveItem(watchedFiles, file); + } + }; + } + function createPollingIntervalQueue(pollingInterval) { + var queue = []; + queue.pollingInterval = pollingInterval; + queue.pollIndex = 0; + queue.pollScheduled = false; + return queue; + } + function pollPollingIntervalQueue(queue) { + queue.pollIndex = pollQueue(queue, queue.pollingInterval, queue.pollIndex, pollingChunkSize[queue.pollingInterval]); + if (queue.length) { + scheduleNextPoll(queue.pollingInterval); + } + else { + ts.Debug.assert(queue.pollIndex === 0); + queue.pollScheduled = false; + } + } + function pollLowPollingIntervalQueue(queue) { + pollQueue(changedFilesInLastPoll, PollingInterval.Low, 0, changedFilesInLastPoll.length); + pollPollingIntervalQueue(queue); + if (!queue.pollScheduled && changedFilesInLastPoll.length) { + scheduleNextPoll(PollingInterval.Low); + } + } + function pollQueue(queue, pollingInterval, pollIndex, chunkSize) { + var needsVisit = queue.length; + var definedValueCopyToIndex = pollIndex; + for (var polled = 0; polled < chunkSize && needsVisit > 0; nextPollIndex(), needsVisit--) { + var watchedFile = queue[pollIndex]; + if (!watchedFile) { + continue; + } + else if (watchedFile.isClosed) { + queue[pollIndex] = undefined; + continue; + } + polled++; + var fileChanged = onWatchedFileStat(watchedFile, getModifiedTime(watchedFile.fileName)); + if (watchedFile.isClosed) { + queue[pollIndex] = undefined; + } + else if (fileChanged) { + watchedFile.unchangedPolls = 0; + if (queue !== changedFilesInLastPoll) { + queue[pollIndex] = undefined; + addChangedFileToLowPollingIntervalQueue(watchedFile); + } + } + else if (watchedFile.unchangedPolls !== ts.unchangedPollThresholds[pollingInterval]) { + watchedFile.unchangedPolls++; + } + else if (queue === changedFilesInLastPoll) { + watchedFile.unchangedPolls = 1; + queue[pollIndex] = undefined; + addToPollingIntervalQueue(watchedFile, PollingInterval.Low); + } + else if (pollingInterval !== PollingInterval.High) { + watchedFile.unchangedPolls++; + queue[pollIndex] = undefined; + addToPollingIntervalQueue(watchedFile, pollingInterval === PollingInterval.Low ? PollingInterval.Medium : PollingInterval.High); + } + if (queue[pollIndex]) { + if (definedValueCopyToIndex < pollIndex) { + queue[definedValueCopyToIndex] = watchedFile; + queue[pollIndex] = undefined; + } + definedValueCopyToIndex++; + } + } + return pollIndex; + function nextPollIndex() { + pollIndex++; + if (pollIndex === queue.length) { + if (definedValueCopyToIndex < pollIndex) { + queue.length = definedValueCopyToIndex; + } + pollIndex = 0; + definedValueCopyToIndex = 0; + } + } + } + function pollingIntervalQueue(pollingInterval) { + switch (pollingInterval) { + case PollingInterval.Low: + return lowPollingIntervalQueue; + case PollingInterval.Medium: + return mediumPollingIntervalQueue; + case PollingInterval.High: + return highPollingIntervalQueue; + } + } + function addToPollingIntervalQueue(file, pollingInterval) { + pollingIntervalQueue(pollingInterval).push(file); + scheduleNextPollIfNotAlreadyScheduled(pollingInterval); + } + function addChangedFileToLowPollingIntervalQueue(file) { + changedFilesInLastPoll.push(file); + scheduleNextPollIfNotAlreadyScheduled(PollingInterval.Low); + } + function scheduleNextPollIfNotAlreadyScheduled(pollingInterval) { + if (!pollingIntervalQueue(pollingInterval).pollScheduled) { + scheduleNextPoll(pollingInterval); + } + } + function scheduleNextPoll(pollingInterval) { + pollingIntervalQueue(pollingInterval).pollScheduled = host.setTimeout(pollingInterval === PollingInterval.Low ? pollLowPollingIntervalQueue : pollPollingIntervalQueue, pollingInterval, pollingIntervalQueue(pollingInterval)); + } + function getModifiedTime(fileName) { + return host.getModifiedTime(fileName) || ts.missingFileModifiedTime; + } + } + ts.createDynamicPriorityPollingWatchFile = createDynamicPriorityPollingWatchFile; + function onWatchedFileStat(watchedFile, modifiedTime) { + var oldTime = watchedFile.mtime.getTime(); + var newTime = modifiedTime.getTime(); + if (oldTime !== newTime) { + watchedFile.mtime = modifiedTime; + watchedFile.callback(watchedFile.fileName, getFileWatcherEventKind(oldTime, newTime)); + return true; + } + return false; + } + ts.onWatchedFileStat = onWatchedFileStat; + function getFileWatcherEventKind(oldTime, newTime) { + return oldTime === 0 + ? FileWatcherEventKind.Created + : newTime === 0 + ? FileWatcherEventKind.Deleted + : FileWatcherEventKind.Changed; + } + ts.getFileWatcherEventKind = getFileWatcherEventKind; + function createRecursiveDirectoryWatcher(host) { + var cache = ts.createMap(); + var callbackCache = ts.createMultiMap(); + var filePathComparer = ts.getStringComparer(!host.useCaseSensitiveFileNames); + var toCanonicalFilePath = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); + return createDirectoryWatcher; + function createDirectoryWatcher(dirName, callback) { + var dirPath = toCanonicalFilePath(dirName); + var directoryWatcher = cache.get(dirPath); + if (directoryWatcher) { + directoryWatcher.refCount++; + } + else { + directoryWatcher = { + watcher: host.watchDirectory(dirName, function (fileName) { + callbackCache.forEach(function (callbacks, rootDirName) { + if (rootDirName === dirPath || (ts.startsWith(dirPath, rootDirName) && dirPath[rootDirName.length] === ts.directorySeparator)) { + callbacks.forEach(function (callback) { return callback(fileName); }); + } + }); + updateChildWatches(dirName, dirPath); + }), + refCount: 1, + childWatches: ts.emptyArray + }; + cache.set(dirPath, directoryWatcher); + updateChildWatches(dirName, dirPath); + } + if (callback) { + callbackCache.add(dirPath, callback); + } + return { + dirName: dirName, + close: function () { + var directoryWatcher = ts.Debug.assertDefined(cache.get(dirPath)); + if (callback) + callbackCache.remove(dirPath, callback); + directoryWatcher.refCount--; + if (directoryWatcher.refCount) + return; + cache.delete(dirPath); + ts.closeFileWatcherOf(directoryWatcher); + directoryWatcher.childWatches.forEach(ts.closeFileWatcher); + } + }; + } + function updateChildWatches(dirName, dirPath) { + var parentWatcher = cache.get(dirPath); + if (parentWatcher) { + parentWatcher.childWatches = watchChildDirectories(dirName, parentWatcher.childWatches); + } + } + function watchChildDirectories(parentDir, existingChildWatches) { + var newChildWatches; + ts.enumerateInsertsAndDeletes(host.directoryExists(parentDir) ? ts.mapDefined(host.getAccessibleSortedChildDirectories(parentDir), function (child) { + var childFullName = ts.getNormalizedAbsolutePath(child, parentDir); + return filePathComparer(childFullName, ts.normalizePath(host.realpath(childFullName))) === 0 ? childFullName : undefined; + }) : ts.emptyArray, existingChildWatches, function (child, childWatcher) { return filePathComparer(child, childWatcher.dirName); }, createAndAddChildDirectoryWatcher, ts.closeFileWatcher, addChildDirectoryWatcher); + return newChildWatches || ts.emptyArray; + function createAndAddChildDirectoryWatcher(childName) { + var result = createDirectoryWatcher(childName); + addChildDirectoryWatcher(result); + } + function addChildDirectoryWatcher(childWatcher) { + (newChildWatches || (newChildWatches = [])).push(childWatcher); + } + } + } + ts.createRecursiveDirectoryWatcher = createRecursiveDirectoryWatcher; + function getNodeMajorVersion() { + if (typeof process === "undefined") { + return undefined; + } + var version = process.version; + if (!version) { + return undefined; + } + var dot = version.indexOf("."); + if (dot === -1) { + return undefined; + } + return parseInt(version.substring(1, dot)); + } + ts.getNodeMajorVersion = getNodeMajorVersion; + ts.sys = (function () { + var byteOrderMarkIndicator = "\uFEFF"; + function getNodeSystem() { + var _fs = require("fs"); + var _path = require("path"); + var _os = require("os"); + var _crypto; + try { + _crypto = require("crypto"); + } + catch (_a) { + _crypto = undefined; + } + var Buffer = require("buffer").Buffer; + var nodeVersion = getNodeMajorVersion(); + var isNode4OrLater = nodeVersion >= 4; + var platform = _os.platform(); + var useCaseSensitiveFileNames = isFileSystemCaseSensitive(); + var useNonPollingWatchers = process.env.TSC_NONPOLLING_WATCHER; + var tscWatchFile = process.env.TSC_WATCHFILE; + var tscWatchDirectory = process.env.TSC_WATCHDIRECTORY; + var dynamicPollingWatchFile; + var nodeSystem = { + args: process.argv.slice(2), + newLine: _os.EOL, + useCaseSensitiveFileNames: useCaseSensitiveFileNames, + write: function (s) { + process.stdout.write(s); + }, + writeOutputIsTTY: function () { + return process.stdout.isTTY; + }, + readFile: readFile, + writeFile: writeFile, + watchFile: getWatchFile(), + watchDirectory: getWatchDirectory(), + resolvePath: function (path) { return _path.resolve(path); }, + fileExists: fileExists, + directoryExists: directoryExists, + createDirectory: function (directoryName) { + if (!nodeSystem.directoryExists(directoryName)) { + _fs.mkdirSync(directoryName); + } + }, + getExecutingFilePath: function () { + return __filename; + }, + getCurrentDirectory: function () { + return process.cwd(); + }, + getDirectories: getDirectories, + getEnvironmentVariable: function (name) { + return process.env[name] || ""; + }, + readDirectory: readDirectory, + getModifiedTime: getModifiedTime, + setModifiedTime: setModifiedTime, + deleteFile: deleteFile, + createHash: _crypto ? createMD5HashUsingNativeCrypto : generateDjb2Hash, + createSHA256Hash: _crypto ? createSHA256Hash : undefined, + getMemoryUsage: function () { + if (global.gc) { + global.gc(); + } + return process.memoryUsage().heapUsed; + }, + getFileSize: function (path) { + try { + var stat = _fs.statSync(path); + if (stat.isFile()) { + return stat.size; + } + } + catch (_a) { } + return 0; + }, + exit: function (exitCode) { + process.exit(exitCode); + }, + realpath: realpath, + debugMode: ts.some(process.execArgv, function (arg) { return /^--(inspect|debug)(-brk)?(=\d+)?$/i.test(arg); }), + tryEnableSourceMapsForHost: function () { + try { + require("source-map-support").install(); + } + catch (_a) { + } + }, + setTimeout: setTimeout, + clearTimeout: clearTimeout, + clearScreen: function () { + process.stdout.write("\x1Bc"); + }, + setBlocking: function () { + if (process.stdout && process.stdout._handle && process.stdout._handle.setBlocking) { + process.stdout._handle.setBlocking(true); + } + }, + bufferFrom: bufferFrom, + base64decode: function (input) { return bufferFrom(input, "base64").toString("utf8"); }, + base64encode: function (input) { return bufferFrom(input).toString("base64"); }, + }; + return nodeSystem; + function bufferFrom(input, encoding) { + return Buffer.from && Buffer.from !== Int8Array.from + ? Buffer.from(input, encoding) + : new Buffer(input, encoding); + } + function isFileSystemCaseSensitive() { + if (platform === "win32" || platform === "win64") { + return false; + } + return !fileExists(swapCase(__filename)); + } + function swapCase(s) { + return s.replace(/\w/g, function (ch) { + var up = ch.toUpperCase(); + return ch === up ? ch.toLowerCase() : up; + }); + } + function getWatchFile() { + switch (tscWatchFile) { + case "PriorityPollingInterval": + return fsWatchFile; + case "DynamicPriorityPolling": + return createDynamicPriorityPollingWatchFile({ getModifiedTime: getModifiedTime, setTimeout: setTimeout }); + case "UseFsEvents": + return watchFileUsingFsWatch; + case "UseFsEventsWithFallbackDynamicPolling": + dynamicPollingWatchFile = createDynamicPriorityPollingWatchFile({ getModifiedTime: getModifiedTime, setTimeout: setTimeout }); + return createWatchFileUsingDynamicWatchFile(dynamicPollingWatchFile); + case "UseFsEventsOnParentDirectory": + return createNonPollingWatchFile(); + } + return useNonPollingWatchers ? + createNonPollingWatchFile() : + function (fileName, callback) { return fsWatchFile(fileName, callback); }; + } + function getWatchDirectory() { + var fsSupportsRecursive = isNode4OrLater && (process.platform === "win32" || process.platform === "darwin"); + if (fsSupportsRecursive) { + return watchDirectoryUsingFsWatch; + } + var watchDirectory = tscWatchDirectory === "RecursiveDirectoryUsingFsWatchFile" ? + createWatchDirectoryUsing(fsWatchFile) : + tscWatchDirectory === "RecursiveDirectoryUsingDynamicPriorityPolling" ? + createWatchDirectoryUsing(dynamicPollingWatchFile || createDynamicPriorityPollingWatchFile({ getModifiedTime: getModifiedTime, setTimeout: setTimeout })) : + watchDirectoryUsingFsWatch; + var watchDirectoryRecursively = createRecursiveDirectoryWatcher({ + useCaseSensitiveFileNames: useCaseSensitiveFileNames, + directoryExists: directoryExists, + getAccessibleSortedChildDirectories: function (path) { return getAccessibleFileSystemEntries(path).directories; }, + watchDirectory: watchDirectory, + realpath: realpath + }); + return function (directoryName, callback, recursive) { + if (recursive) { + return watchDirectoryRecursively(directoryName, callback); + } + return watchDirectory(directoryName, callback); + }; + } + function createNonPollingWatchFile() { + var fileWatcherCallbacks = ts.createMultiMap(); + var dirWatchers = ts.createMap(); + var toCanonicalName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); + return nonPollingWatchFile; + function nonPollingWatchFile(fileName, callback) { + var filePath = toCanonicalName(fileName); + fileWatcherCallbacks.add(filePath, callback); + var dirPath = ts.getDirectoryPath(filePath) || "."; + var watcher = dirWatchers.get(dirPath) || createDirectoryWatcher(ts.getDirectoryPath(fileName) || ".", dirPath); + watcher.referenceCount++; + return { + close: function () { + if (watcher.referenceCount === 1) { + watcher.close(); + dirWatchers.delete(dirPath); + } + else { + watcher.referenceCount--; + } + fileWatcherCallbacks.remove(filePath, callback); + } + }; + } + function createDirectoryWatcher(dirName, dirPath) { + var watcher = fsWatchDirectory(dirName, function (_eventName, relativeFileName) { + if (!ts.isString(relativeFileName)) { + return; + } + var fileName = ts.getNormalizedAbsolutePath(relativeFileName, dirName); + var callbacks = fileName && fileWatcherCallbacks.get(toCanonicalName(fileName)); + if (callbacks) { + for (var _i = 0, callbacks_1 = callbacks; _i < callbacks_1.length; _i++) { + var fileCallback = callbacks_1[_i]; + fileCallback(fileName, FileWatcherEventKind.Changed); + } + } + }); + watcher.referenceCount = 0; + dirWatchers.set(dirPath, watcher); + return watcher; + } + } + function fsWatchFile(fileName, callback, pollingInterval) { + _fs.watchFile(fileName, { persistent: true, interval: pollingInterval || 250 }, fileChanged); + var eventKind; + return { + close: function () { return _fs.unwatchFile(fileName, fileChanged); } + }; + function fileChanged(curr, prev) { + var isPreviouslyDeleted = +prev.mtime === 0 || eventKind === FileWatcherEventKind.Deleted; + if (+curr.mtime === 0) { + if (isPreviouslyDeleted) { + return; + } + eventKind = FileWatcherEventKind.Deleted; + } + else if (isPreviouslyDeleted) { + eventKind = FileWatcherEventKind.Created; + } + else if (+curr.mtime === +prev.mtime) { + return; + } + else { + eventKind = FileWatcherEventKind.Changed; + } + callback(fileName, eventKind); + } + } + function createFileWatcherCallback(callback) { + return function (_fileName, eventKind) { return callback(eventKind === FileWatcherEventKind.Changed ? "change" : "rename", ""); }; + } + function createFsWatchCallbackForFileWatcherCallback(fileName, callback) { + return function (eventName) { + if (eventName === "rename") { + callback(fileName, fileExists(fileName) ? FileWatcherEventKind.Created : FileWatcherEventKind.Deleted); + } + else { + callback(fileName, FileWatcherEventKind.Changed); + } + }; + } + function createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback) { + return function (eventName, relativeFileName) { + if (eventName === "rename") { + callback(!relativeFileName ? directoryName : ts.normalizePath(ts.combinePaths(directoryName, relativeFileName))); + } + }; + } + function fsWatch(fileOrDirectory, entryKind, callback, recursive, fallbackPollingWatchFile, pollingInterval) { + var options; + var watcher = !fileSystemEntryExists(fileOrDirectory, entryKind) ? + watchMissingFileSystemEntry() : + watchPresentFileSystemEntry(); + return { + close: function () { + watcher.close(); + watcher = undefined; + } + }; + function invokeCallbackAndUpdateWatcher(createWatcher) { + callback("rename", ""); + if (watcher) { + watcher.close(); + watcher = createWatcher(); + } + } + function watchPresentFileSystemEntry() { + if (options === undefined) { + if (isNode4OrLater && (process.platform === "win32" || process.platform === "darwin")) { + options = { persistent: true, recursive: !!recursive }; + } + else { + options = { persistent: true }; + } + } + try { + var presentWatcher = _fs.watch(fileOrDirectory, options, callback); + presentWatcher.on("error", function () { return invokeCallbackAndUpdateWatcher(watchMissingFileSystemEntry); }); + return presentWatcher; + } + catch (e) { + return watchPresentFileSystemEntryWithFsWatchFile(); + } + } + function watchPresentFileSystemEntryWithFsWatchFile() { + return fallbackPollingWatchFile(fileOrDirectory, createFileWatcherCallback(callback), pollingInterval); + } + function watchMissingFileSystemEntry() { + return fallbackPollingWatchFile(fileOrDirectory, function (_fileName, eventKind) { + if (eventKind === FileWatcherEventKind.Created && fileSystemEntryExists(fileOrDirectory, entryKind)) { + invokeCallbackAndUpdateWatcher(watchPresentFileSystemEntry); + } + }, pollingInterval); + } + } + function watchFileUsingFsWatch(fileName, callback, pollingInterval) { + return fsWatch(fileName, 0, createFsWatchCallbackForFileWatcherCallback(fileName, callback), false, fsWatchFile, pollingInterval); + } + function createWatchFileUsingDynamicWatchFile(watchFile) { + return function (fileName, callback, pollingInterval) { return fsWatch(fileName, 0, createFsWatchCallbackForFileWatcherCallback(fileName, callback), false, watchFile, pollingInterval); }; + } + function fsWatchDirectory(directoryName, callback, recursive) { + return fsWatch(directoryName, 1, callback, !!recursive, fsWatchFile); + } + function watchDirectoryUsingFsWatch(directoryName, callback, recursive) { + return fsWatchDirectory(directoryName, createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback), recursive); + } + function createWatchDirectoryUsing(fsWatchFile) { + return function (directoryName, callback) { return fsWatchFile(directoryName, function () { return callback(directoryName); }, PollingInterval.Medium); }; + } + function readFile(fileName, _encoding) { + if (!fileExists(fileName)) { + return undefined; + } + var buffer = _fs.readFileSync(fileName); + var len = buffer.length; + if (len >= 2 && buffer[0] === 0xFE && buffer[1] === 0xFF) { + len &= ~1; + for (var i = 0; i < len; i += 2) { + var temp = buffer[i]; + buffer[i] = buffer[i + 1]; + buffer[i + 1] = temp; + } + return buffer.toString("utf16le", 2); + } + if (len >= 2 && buffer[0] === 0xFF && buffer[1] === 0xFE) { + return buffer.toString("utf16le", 2); + } + if (len >= 3 && buffer[0] === 0xEF && buffer[1] === 0xBB && buffer[2] === 0xBF) { + return buffer.toString("utf8", 3); + } + return buffer.toString("utf8"); + } + function writeFile(fileName, data, writeByteOrderMark) { + if (writeByteOrderMark) { + data = byteOrderMarkIndicator + data; + } + var fd; + try { + fd = _fs.openSync(fileName, "w"); + _fs.writeSync(fd, data, undefined, "utf8"); + } + finally { + if (fd !== undefined) { + _fs.closeSync(fd); + } + } + } + function getAccessibleFileSystemEntries(path) { + try { + var entries = _fs.readdirSync(path || ".").sort(); + var files = []; + var directories = []; + for (var _i = 0, entries_2 = entries; _i < entries_2.length; _i++) { + var entry = entries_2[_i]; + if (entry === "." || entry === "..") { + continue; + } + var name = ts.combinePaths(path, entry); + var stat = void 0; + try { + stat = _fs.statSync(name); + } + catch (e) { + continue; + } + if (stat.isFile()) { + files.push(entry); + } + else if (stat.isDirectory()) { + directories.push(entry); + } + } + return { files: files, directories: directories }; + } + catch (e) { + return ts.emptyFileSystemEntries; + } + } + function readDirectory(path, extensions, excludes, includes, depth) { + return ts.matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, process.cwd(), depth, getAccessibleFileSystemEntries); + } + function fileSystemEntryExists(path, entryKind) { + try { + var stat = _fs.statSync(path); + switch (entryKind) { + case 0: return stat.isFile(); + case 1: return stat.isDirectory(); + default: return false; + } + } + catch (e) { + return false; + } + } + function fileExists(path) { + return fileSystemEntryExists(path, 0); + } + function directoryExists(path) { + return fileSystemEntryExists(path, 1); + } + function getDirectories(path) { + return ts.filter(_fs.readdirSync(path), function (dir) { return fileSystemEntryExists(ts.combinePaths(path, dir), 1); }); + } + function realpath(path) { + try { + return _fs.realpathSync(path); + } + catch (_a) { + return path; + } + } + function getModifiedTime(path) { + try { + return _fs.statSync(path).mtime; + } + catch (e) { + return undefined; + } + } + function setModifiedTime(path, time) { + try { + _fs.utimesSync(path, time, time); + } + catch (e) { + return; + } + } + function deleteFile(path) { + try { + return _fs.unlinkSync(path); + } + catch (e) { + return; + } + } + function generateDjb2Hash(data) { + var chars = data.split("").map(function (str) { return str.charCodeAt(0); }); + return "" + chars.reduce(function (prev, curr) { return ((prev << 5) + prev) + curr; }, 5381); + } + function createMD5HashUsingNativeCrypto(data) { + var hash = _crypto.createHash("md5"); + hash.update(data); + return hash.digest("hex"); + } + function createSHA256Hash(data) { + var hash = _crypto.createHash("sha256"); + hash.update(data); + return hash.digest("hex"); + } + } + function getChakraSystem() { + var realpath = ChakraHost.realpath && (function (path) { return ChakraHost.realpath(path); }); + return { + newLine: ChakraHost.newLine || "\r\n", + args: ChakraHost.args, + useCaseSensitiveFileNames: !!ChakraHost.useCaseSensitiveFileNames, + write: ChakraHost.echo, + readFile: function (path, _encoding) { + return ChakraHost.readFile(path); + }, + writeFile: function (path, data, writeByteOrderMark) { + if (writeByteOrderMark) { + data = byteOrderMarkIndicator + data; + } + ChakraHost.writeFile(path, data); + }, + resolvePath: ChakraHost.resolvePath, + fileExists: ChakraHost.fileExists, + deleteFile: ChakraHost.deleteFile, + getModifiedTime: ChakraHost.getModifiedTime, + setModifiedTime: ChakraHost.setModifiedTime, + directoryExists: ChakraHost.directoryExists, + createDirectory: ChakraHost.createDirectory, + getExecutingFilePath: function () { return ChakraHost.executingFile; }, + getCurrentDirectory: function () { return ChakraHost.currentDirectory; }, + getDirectories: ChakraHost.getDirectories, + getEnvironmentVariable: ChakraHost.getEnvironmentVariable || (function () { return ""; }), + readDirectory: function (path, extensions, excludes, includes, _depth) { + var pattern = ts.getFileMatcherPatterns(path, excludes, includes, !!ChakraHost.useCaseSensitiveFileNames, ChakraHost.currentDirectory); + return ChakraHost.readDirectory(path, extensions, pattern.basePaths, pattern.excludePattern, pattern.includeFilePattern, pattern.includeDirectoryPattern); + }, + exit: ChakraHost.quit, + realpath: realpath + }; + } + function recursiveCreateDirectory(directoryPath, sys) { + var basePath = ts.getDirectoryPath(directoryPath); + var shouldCreateParent = basePath !== "" && directoryPath !== basePath && !sys.directoryExists(basePath); + if (shouldCreateParent) { + recursiveCreateDirectory(basePath, sys); + } + if (shouldCreateParent || !sys.directoryExists(directoryPath)) { + sys.createDirectory(directoryPath); + } + } + var sys; + if (typeof ChakraHost !== "undefined") { + sys = getChakraSystem(); + } + else if (typeof process !== "undefined" && process.nextTick && !process.browser && typeof require !== "undefined") { + sys = getNodeSystem(); + } + if (sys) { + var originalWriteFile_1 = sys.writeFile; + sys.writeFile = function (path, data, writeBom) { + var directoryPath = ts.getDirectoryPath(ts.normalizeSlashes(path)); + if (directoryPath && !sys.directoryExists(directoryPath)) { + recursiveCreateDirectory(directoryPath, sys); + } + originalWriteFile_1.call(sys, path, data, writeBom); + }; + } + return sys; + })(); + if (ts.sys && ts.sys.getEnvironmentVariable) { + setCustomPollingValues(ts.sys); + ts.Debug.currentAssertionLevel = /^development$/i.test(ts.sys.getEnvironmentVariable("NODE_ENV")) + ? 1 + : 0; + } + if (ts.sys && ts.sys.debugMode) { + ts.Debug.isDebugging = true; + } +})(ts || (ts = {})); +var ts; +(function (ts) { + function diag(code, category, key, message, reportsUnnecessary) { + return { code: code, category: category, key: key, message: message, reportsUnnecessary: reportsUnnecessary }; + } + ts.Diagnostics = { + Unterminated_string_literal: diag(1002, ts.DiagnosticCategory.Error, "Unterminated_string_literal_1002", "Unterminated string literal."), + Identifier_expected: diag(1003, ts.DiagnosticCategory.Error, "Identifier_expected_1003", "Identifier expected."), + _0_expected: diag(1005, ts.DiagnosticCategory.Error, "_0_expected_1005", "'{0}' expected."), + A_file_cannot_have_a_reference_to_itself: diag(1006, ts.DiagnosticCategory.Error, "A_file_cannot_have_a_reference_to_itself_1006", "A file cannot have a reference to itself."), + Trailing_comma_not_allowed: diag(1009, ts.DiagnosticCategory.Error, "Trailing_comma_not_allowed_1009", "Trailing comma not allowed."), + Asterisk_Slash_expected: diag(1010, ts.DiagnosticCategory.Error, "Asterisk_Slash_expected_1010", "'*/' expected."), + An_element_access_expression_should_take_an_argument: diag(1011, ts.DiagnosticCategory.Error, "An_element_access_expression_should_take_an_argument_1011", "An element access expression should take an argument."), + Unexpected_token: diag(1012, ts.DiagnosticCategory.Error, "Unexpected_token_1012", "Unexpected token."), + A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma: diag(1013, ts.DiagnosticCategory.Error, "A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma_1013", "A rest parameter or binding pattern may not have a trailing comma."), + A_rest_parameter_must_be_last_in_a_parameter_list: diag(1014, ts.DiagnosticCategory.Error, "A_rest_parameter_must_be_last_in_a_parameter_list_1014", "A rest parameter must be last in a parameter list."), + Parameter_cannot_have_question_mark_and_initializer: diag(1015, ts.DiagnosticCategory.Error, "Parameter_cannot_have_question_mark_and_initializer_1015", "Parameter cannot have question mark and initializer."), + A_required_parameter_cannot_follow_an_optional_parameter: diag(1016, ts.DiagnosticCategory.Error, "A_required_parameter_cannot_follow_an_optional_parameter_1016", "A required parameter cannot follow an optional parameter."), + An_index_signature_cannot_have_a_rest_parameter: diag(1017, ts.DiagnosticCategory.Error, "An_index_signature_cannot_have_a_rest_parameter_1017", "An index signature cannot have a rest parameter."), + An_index_signature_parameter_cannot_have_an_accessibility_modifier: diag(1018, ts.DiagnosticCategory.Error, "An_index_signature_parameter_cannot_have_an_accessibility_modifier_1018", "An index signature parameter cannot have an accessibility modifier."), + An_index_signature_parameter_cannot_have_a_question_mark: diag(1019, ts.DiagnosticCategory.Error, "An_index_signature_parameter_cannot_have_a_question_mark_1019", "An index signature parameter cannot have a question mark."), + An_index_signature_parameter_cannot_have_an_initializer: diag(1020, ts.DiagnosticCategory.Error, "An_index_signature_parameter_cannot_have_an_initializer_1020", "An index signature parameter cannot have an initializer."), + An_index_signature_must_have_a_type_annotation: diag(1021, ts.DiagnosticCategory.Error, "An_index_signature_must_have_a_type_annotation_1021", "An index signature must have a type annotation."), + An_index_signature_parameter_must_have_a_type_annotation: diag(1022, ts.DiagnosticCategory.Error, "An_index_signature_parameter_must_have_a_type_annotation_1022", "An index signature parameter must have a type annotation."), + An_index_signature_parameter_type_must_be_string_or_number: diag(1023, ts.DiagnosticCategory.Error, "An_index_signature_parameter_type_must_be_string_or_number_1023", "An index signature parameter type must be 'string' or 'number'."), + readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature: diag(1024, ts.DiagnosticCategory.Error, "readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024", "'readonly' modifier can only appear on a property declaration or index signature."), + Accessibility_modifier_already_seen: diag(1028, ts.DiagnosticCategory.Error, "Accessibility_modifier_already_seen_1028", "Accessibility modifier already seen."), + _0_modifier_must_precede_1_modifier: diag(1029, ts.DiagnosticCategory.Error, "_0_modifier_must_precede_1_modifier_1029", "'{0}' modifier must precede '{1}' modifier."), + _0_modifier_already_seen: diag(1030, ts.DiagnosticCategory.Error, "_0_modifier_already_seen_1030", "'{0}' modifier already seen."), + _0_modifier_cannot_appear_on_a_class_element: diag(1031, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_a_class_element_1031", "'{0}' modifier cannot appear on a class element."), + super_must_be_followed_by_an_argument_list_or_member_access: diag(1034, ts.DiagnosticCategory.Error, "super_must_be_followed_by_an_argument_list_or_member_access_1034", "'super' must be followed by an argument list or member access."), + Only_ambient_modules_can_use_quoted_names: diag(1035, ts.DiagnosticCategory.Error, "Only_ambient_modules_can_use_quoted_names_1035", "Only ambient modules can use quoted names."), + Statements_are_not_allowed_in_ambient_contexts: diag(1036, ts.DiagnosticCategory.Error, "Statements_are_not_allowed_in_ambient_contexts_1036", "Statements are not allowed in ambient contexts."), + A_declare_modifier_cannot_be_used_in_an_already_ambient_context: diag(1038, ts.DiagnosticCategory.Error, "A_declare_modifier_cannot_be_used_in_an_already_ambient_context_1038", "A 'declare' modifier cannot be used in an already ambient context."), + Initializers_are_not_allowed_in_ambient_contexts: diag(1039, ts.DiagnosticCategory.Error, "Initializers_are_not_allowed_in_ambient_contexts_1039", "Initializers are not allowed in ambient contexts."), + _0_modifier_cannot_be_used_in_an_ambient_context: diag(1040, ts.DiagnosticCategory.Error, "_0_modifier_cannot_be_used_in_an_ambient_context_1040", "'{0}' modifier cannot be used in an ambient context."), + _0_modifier_cannot_be_used_with_a_class_declaration: diag(1041, ts.DiagnosticCategory.Error, "_0_modifier_cannot_be_used_with_a_class_declaration_1041", "'{0}' modifier cannot be used with a class declaration."), + _0_modifier_cannot_be_used_here: diag(1042, ts.DiagnosticCategory.Error, "_0_modifier_cannot_be_used_here_1042", "'{0}' modifier cannot be used here."), + _0_modifier_cannot_appear_on_a_data_property: diag(1043, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_a_data_property_1043", "'{0}' modifier cannot appear on a data property."), + _0_modifier_cannot_appear_on_a_module_or_namespace_element: diag(1044, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_a_module_or_namespace_element_1044", "'{0}' modifier cannot appear on a module or namespace element."), + A_0_modifier_cannot_be_used_with_an_interface_declaration: diag(1045, ts.DiagnosticCategory.Error, "A_0_modifier_cannot_be_used_with_an_interface_declaration_1045", "A '{0}' modifier cannot be used with an interface declaration."), + A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file: diag(1046, ts.DiagnosticCategory.Error, "A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file_1046", "A 'declare' modifier is required for a top level declaration in a .d.ts file."), + A_rest_parameter_cannot_be_optional: diag(1047, ts.DiagnosticCategory.Error, "A_rest_parameter_cannot_be_optional_1047", "A rest parameter cannot be optional."), + A_rest_parameter_cannot_have_an_initializer: diag(1048, ts.DiagnosticCategory.Error, "A_rest_parameter_cannot_have_an_initializer_1048", "A rest parameter cannot have an initializer."), + A_set_accessor_must_have_exactly_one_parameter: diag(1049, ts.DiagnosticCategory.Error, "A_set_accessor_must_have_exactly_one_parameter_1049", "A 'set' accessor must have exactly one parameter."), + A_set_accessor_cannot_have_an_optional_parameter: diag(1051, ts.DiagnosticCategory.Error, "A_set_accessor_cannot_have_an_optional_parameter_1051", "A 'set' accessor cannot have an optional parameter."), + A_set_accessor_parameter_cannot_have_an_initializer: diag(1052, ts.DiagnosticCategory.Error, "A_set_accessor_parameter_cannot_have_an_initializer_1052", "A 'set' accessor parameter cannot have an initializer."), + A_set_accessor_cannot_have_rest_parameter: diag(1053, ts.DiagnosticCategory.Error, "A_set_accessor_cannot_have_rest_parameter_1053", "A 'set' accessor cannot have rest parameter."), + A_get_accessor_cannot_have_parameters: diag(1054, ts.DiagnosticCategory.Error, "A_get_accessor_cannot_have_parameters_1054", "A 'get' accessor cannot have parameters."), + Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value: diag(1055, ts.DiagnosticCategory.Error, "Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Prom_1055", "Type '{0}' is not a valid async function return type in ES5/ES3 because it does not refer to a Promise-compatible constructor value."), + Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher: diag(1056, ts.DiagnosticCategory.Error, "Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher_1056", "Accessors are only available when targeting ECMAScript 5 and higher."), + An_async_function_or_method_must_have_a_valid_awaitable_return_type: diag(1057, ts.DiagnosticCategory.Error, "An_async_function_or_method_must_have_a_valid_awaitable_return_type_1057", "An async function or method must have a valid awaitable return type."), + The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1058, ts.DiagnosticCategory.Error, "The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_t_1058", "The return type of an async function must either be a valid promise or must not contain a callable 'then' member."), + A_promise_must_have_a_then_method: diag(1059, ts.DiagnosticCategory.Error, "A_promise_must_have_a_then_method_1059", "A promise must have a 'then' method."), + The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback: diag(1060, ts.DiagnosticCategory.Error, "The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback_1060", "The first parameter of the 'then' method of a promise must be a callback."), + Enum_member_must_have_initializer: diag(1061, ts.DiagnosticCategory.Error, "Enum_member_must_have_initializer_1061", "Enum member must have initializer."), + Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method: diag(1062, ts.DiagnosticCategory.Error, "Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method_1062", "Type is referenced directly or indirectly in the fulfillment callback of its own 'then' method."), + An_export_assignment_cannot_be_used_in_a_namespace: diag(1063, ts.DiagnosticCategory.Error, "An_export_assignment_cannot_be_used_in_a_namespace_1063", "An export assignment cannot be used in a namespace."), + The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type: diag(1064, ts.DiagnosticCategory.Error, "The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_1064", "The return type of an async function or method must be the global Promise type."), + In_ambient_enum_declarations_member_initializer_must_be_constant_expression: diag(1066, ts.DiagnosticCategory.Error, "In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066", "In ambient enum declarations member initializer must be constant expression."), + Unexpected_token_A_constructor_method_accessor_or_property_was_expected: diag(1068, ts.DiagnosticCategory.Error, "Unexpected_token_A_constructor_method_accessor_or_property_was_expected_1068", "Unexpected token. A constructor, method, accessor, or property was expected."), + Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces: diag(1069, ts.DiagnosticCategory.Error, "Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces_1069", "Unexpected token. A type parameter name was expected without curly braces."), + _0_modifier_cannot_appear_on_a_type_member: diag(1070, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_a_type_member_1070", "'{0}' modifier cannot appear on a type member."), + _0_modifier_cannot_appear_on_an_index_signature: diag(1071, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_an_index_signature_1071", "'{0}' modifier cannot appear on an index signature."), + A_0_modifier_cannot_be_used_with_an_import_declaration: diag(1079, ts.DiagnosticCategory.Error, "A_0_modifier_cannot_be_used_with_an_import_declaration_1079", "A '{0}' modifier cannot be used with an import declaration."), + Invalid_reference_directive_syntax: diag(1084, ts.DiagnosticCategory.Error, "Invalid_reference_directive_syntax_1084", "Invalid 'reference' directive syntax."), + Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0: diag(1085, ts.DiagnosticCategory.Error, "Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0_1085", "Octal literals are not available when targeting ECMAScript 5 and higher. Use the syntax '{0}'."), + An_accessor_cannot_be_declared_in_an_ambient_context: diag(1086, ts.DiagnosticCategory.Error, "An_accessor_cannot_be_declared_in_an_ambient_context_1086", "An accessor cannot be declared in an ambient context."), + _0_modifier_cannot_appear_on_a_constructor_declaration: diag(1089, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_a_constructor_declaration_1089", "'{0}' modifier cannot appear on a constructor declaration."), + _0_modifier_cannot_appear_on_a_parameter: diag(1090, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_a_parameter_1090", "'{0}' modifier cannot appear on a parameter."), + Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement: diag(1091, ts.DiagnosticCategory.Error, "Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement_1091", "Only a single variable declaration is allowed in a 'for...in' statement."), + Type_parameters_cannot_appear_on_a_constructor_declaration: diag(1092, ts.DiagnosticCategory.Error, "Type_parameters_cannot_appear_on_a_constructor_declaration_1092", "Type parameters cannot appear on a constructor declaration."), + Type_annotation_cannot_appear_on_a_constructor_declaration: diag(1093, ts.DiagnosticCategory.Error, "Type_annotation_cannot_appear_on_a_constructor_declaration_1093", "Type annotation cannot appear on a constructor declaration."), + An_accessor_cannot_have_type_parameters: diag(1094, ts.DiagnosticCategory.Error, "An_accessor_cannot_have_type_parameters_1094", "An accessor cannot have type parameters."), + A_set_accessor_cannot_have_a_return_type_annotation: diag(1095, ts.DiagnosticCategory.Error, "A_set_accessor_cannot_have_a_return_type_annotation_1095", "A 'set' accessor cannot have a return type annotation."), + An_index_signature_must_have_exactly_one_parameter: diag(1096, ts.DiagnosticCategory.Error, "An_index_signature_must_have_exactly_one_parameter_1096", "An index signature must have exactly one parameter."), + _0_list_cannot_be_empty: diag(1097, ts.DiagnosticCategory.Error, "_0_list_cannot_be_empty_1097", "'{0}' list cannot be empty."), + Type_parameter_list_cannot_be_empty: diag(1098, ts.DiagnosticCategory.Error, "Type_parameter_list_cannot_be_empty_1098", "Type parameter list cannot be empty."), + Type_argument_list_cannot_be_empty: diag(1099, ts.DiagnosticCategory.Error, "Type_argument_list_cannot_be_empty_1099", "Type argument list cannot be empty."), + Invalid_use_of_0_in_strict_mode: diag(1100, ts.DiagnosticCategory.Error, "Invalid_use_of_0_in_strict_mode_1100", "Invalid use of '{0}' in strict mode."), + with_statements_are_not_allowed_in_strict_mode: diag(1101, ts.DiagnosticCategory.Error, "with_statements_are_not_allowed_in_strict_mode_1101", "'with' statements are not allowed in strict mode."), + delete_cannot_be_called_on_an_identifier_in_strict_mode: diag(1102, ts.DiagnosticCategory.Error, "delete_cannot_be_called_on_an_identifier_in_strict_mode_1102", "'delete' cannot be called on an identifier in strict mode."), + A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator: diag(1103, ts.DiagnosticCategory.Error, "A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator_1103", "A 'for-await-of' statement is only allowed within an async function or async generator."), + A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement: diag(1104, ts.DiagnosticCategory.Error, "A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement_1104", "A 'continue' statement can only be used within an enclosing iteration statement."), + A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement: diag(1105, ts.DiagnosticCategory.Error, "A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement_1105", "A 'break' statement can only be used within an enclosing iteration or switch statement."), + Jump_target_cannot_cross_function_boundary: diag(1107, ts.DiagnosticCategory.Error, "Jump_target_cannot_cross_function_boundary_1107", "Jump target cannot cross function boundary."), + A_return_statement_can_only_be_used_within_a_function_body: diag(1108, ts.DiagnosticCategory.Error, "A_return_statement_can_only_be_used_within_a_function_body_1108", "A 'return' statement can only be used within a function body."), + Expression_expected: diag(1109, ts.DiagnosticCategory.Error, "Expression_expected_1109", "Expression expected."), + Type_expected: diag(1110, ts.DiagnosticCategory.Error, "Type_expected_1110", "Type expected."), + A_default_clause_cannot_appear_more_than_once_in_a_switch_statement: diag(1113, ts.DiagnosticCategory.Error, "A_default_clause_cannot_appear_more_than_once_in_a_switch_statement_1113", "A 'default' clause cannot appear more than once in a 'switch' statement."), + Duplicate_label_0: diag(1114, ts.DiagnosticCategory.Error, "Duplicate_label_0_1114", "Duplicate label '{0}'."), + A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement: diag(1115, ts.DiagnosticCategory.Error, "A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement_1115", "A 'continue' statement can only jump to a label of an enclosing iteration statement."), + A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement: diag(1116, ts.DiagnosticCategory.Error, "A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement_1116", "A 'break' statement can only jump to a label of an enclosing statement."), + An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode: diag(1117, ts.DiagnosticCategory.Error, "An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode_1117", "An object literal cannot have multiple properties with the same name in strict mode."), + An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name: diag(1118, ts.DiagnosticCategory.Error, "An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name_1118", "An object literal cannot have multiple get/set accessors with the same name."), + An_object_literal_cannot_have_property_and_accessor_with_the_same_name: diag(1119, ts.DiagnosticCategory.Error, "An_object_literal_cannot_have_property_and_accessor_with_the_same_name_1119", "An object literal cannot have property and accessor with the same name."), + An_export_assignment_cannot_have_modifiers: diag(1120, ts.DiagnosticCategory.Error, "An_export_assignment_cannot_have_modifiers_1120", "An export assignment cannot have modifiers."), + Octal_literals_are_not_allowed_in_strict_mode: diag(1121, ts.DiagnosticCategory.Error, "Octal_literals_are_not_allowed_in_strict_mode_1121", "Octal literals are not allowed in strict mode."), + Variable_declaration_list_cannot_be_empty: diag(1123, ts.DiagnosticCategory.Error, "Variable_declaration_list_cannot_be_empty_1123", "Variable declaration list cannot be empty."), + Digit_expected: diag(1124, ts.DiagnosticCategory.Error, "Digit_expected_1124", "Digit expected."), + Hexadecimal_digit_expected: diag(1125, ts.DiagnosticCategory.Error, "Hexadecimal_digit_expected_1125", "Hexadecimal digit expected."), + Unexpected_end_of_text: diag(1126, ts.DiagnosticCategory.Error, "Unexpected_end_of_text_1126", "Unexpected end of text."), + Invalid_character: diag(1127, ts.DiagnosticCategory.Error, "Invalid_character_1127", "Invalid character."), + Declaration_or_statement_expected: diag(1128, ts.DiagnosticCategory.Error, "Declaration_or_statement_expected_1128", "Declaration or statement expected."), + Statement_expected: diag(1129, ts.DiagnosticCategory.Error, "Statement_expected_1129", "Statement expected."), + case_or_default_expected: diag(1130, ts.DiagnosticCategory.Error, "case_or_default_expected_1130", "'case' or 'default' expected."), + Property_or_signature_expected: diag(1131, ts.DiagnosticCategory.Error, "Property_or_signature_expected_1131", "Property or signature expected."), + Enum_member_expected: diag(1132, ts.DiagnosticCategory.Error, "Enum_member_expected_1132", "Enum member expected."), + Variable_declaration_expected: diag(1134, ts.DiagnosticCategory.Error, "Variable_declaration_expected_1134", "Variable declaration expected."), + Argument_expression_expected: diag(1135, ts.DiagnosticCategory.Error, "Argument_expression_expected_1135", "Argument expression expected."), + Property_assignment_expected: diag(1136, ts.DiagnosticCategory.Error, "Property_assignment_expected_1136", "Property assignment expected."), + Expression_or_comma_expected: diag(1137, ts.DiagnosticCategory.Error, "Expression_or_comma_expected_1137", "Expression or comma expected."), + Parameter_declaration_expected: diag(1138, ts.DiagnosticCategory.Error, "Parameter_declaration_expected_1138", "Parameter declaration expected."), + Type_parameter_declaration_expected: diag(1139, ts.DiagnosticCategory.Error, "Type_parameter_declaration_expected_1139", "Type parameter declaration expected."), + Type_argument_expected: diag(1140, ts.DiagnosticCategory.Error, "Type_argument_expected_1140", "Type argument expected."), + String_literal_expected: diag(1141, ts.DiagnosticCategory.Error, "String_literal_expected_1141", "String literal expected."), + Line_break_not_permitted_here: diag(1142, ts.DiagnosticCategory.Error, "Line_break_not_permitted_here_1142", "Line break not permitted here."), + or_expected: diag(1144, ts.DiagnosticCategory.Error, "or_expected_1144", "'{' or ';' expected."), + Declaration_expected: diag(1146, ts.DiagnosticCategory.Error, "Declaration_expected_1146", "Declaration expected."), + Import_declarations_in_a_namespace_cannot_reference_a_module: diag(1147, ts.DiagnosticCategory.Error, "Import_declarations_in_a_namespace_cannot_reference_a_module_1147", "Import declarations in a namespace cannot reference a module."), + Cannot_use_imports_exports_or_module_augmentations_when_module_is_none: diag(1148, ts.DiagnosticCategory.Error, "Cannot_use_imports_exports_or_module_augmentations_when_module_is_none_1148", "Cannot use imports, exports, or module augmentations when '--module' is 'none'."), + File_name_0_differs_from_already_included_file_name_1_only_in_casing: diag(1149, ts.DiagnosticCategory.Error, "File_name_0_differs_from_already_included_file_name_1_only_in_casing_1149", "File name '{0}' differs from already included file name '{1}' only in casing."), + new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead: diag(1150, ts.DiagnosticCategory.Error, "new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead_1150", "'new T[]' cannot be used to create an array. Use 'new Array()' instead."), + const_declarations_must_be_initialized: diag(1155, ts.DiagnosticCategory.Error, "const_declarations_must_be_initialized_1155", "'const' declarations must be initialized."), + const_declarations_can_only_be_declared_inside_a_block: diag(1156, ts.DiagnosticCategory.Error, "const_declarations_can_only_be_declared_inside_a_block_1156", "'const' declarations can only be declared inside a block."), + let_declarations_can_only_be_declared_inside_a_block: diag(1157, ts.DiagnosticCategory.Error, "let_declarations_can_only_be_declared_inside_a_block_1157", "'let' declarations can only be declared inside a block."), + Unterminated_template_literal: diag(1160, ts.DiagnosticCategory.Error, "Unterminated_template_literal_1160", "Unterminated template literal."), + Unterminated_regular_expression_literal: diag(1161, ts.DiagnosticCategory.Error, "Unterminated_regular_expression_literal_1161", "Unterminated regular expression literal."), + An_object_member_cannot_be_declared_optional: diag(1162, ts.DiagnosticCategory.Error, "An_object_member_cannot_be_declared_optional_1162", "An object member cannot be declared optional."), + A_yield_expression_is_only_allowed_in_a_generator_body: diag(1163, ts.DiagnosticCategory.Error, "A_yield_expression_is_only_allowed_in_a_generator_body_1163", "A 'yield' expression is only allowed in a generator body."), + Computed_property_names_are_not_allowed_in_enums: diag(1164, ts.DiagnosticCategory.Error, "Computed_property_names_are_not_allowed_in_enums_1164", "Computed property names are not allowed in enums."), + A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: diag(1165, ts.DiagnosticCategory.Error, "A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_t_1165", "A computed property name in an ambient context must refer to an expression whose type is a literal type or a 'unique symbol' type."), + A_computed_property_name_in_a_class_property_declaration_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: diag(1166, ts.DiagnosticCategory.Error, "A_computed_property_name_in_a_class_property_declaration_must_refer_to_an_expression_whose_type_is_a_1166", "A computed property name in a class property declaration must refer to an expression whose type is a literal type or a 'unique symbol' type."), + A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: diag(1168, ts.DiagnosticCategory.Error, "A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_ty_1168", "A computed property name in a method overload must refer to an expression whose type is a literal type or a 'unique symbol' type."), + A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: diag(1169, ts.DiagnosticCategory.Error, "A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_1169", "A computed property name in an interface must refer to an expression whose type is a literal type or a 'unique symbol' type."), + A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: diag(1170, ts.DiagnosticCategory.Error, "A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type__1170", "A computed property name in a type literal must refer to an expression whose type is a literal type or a 'unique symbol' type."), + A_comma_expression_is_not_allowed_in_a_computed_property_name: diag(1171, ts.DiagnosticCategory.Error, "A_comma_expression_is_not_allowed_in_a_computed_property_name_1171", "A comma expression is not allowed in a computed property name."), + extends_clause_already_seen: diag(1172, ts.DiagnosticCategory.Error, "extends_clause_already_seen_1172", "'extends' clause already seen."), + extends_clause_must_precede_implements_clause: diag(1173, ts.DiagnosticCategory.Error, "extends_clause_must_precede_implements_clause_1173", "'extends' clause must precede 'implements' clause."), + Classes_can_only_extend_a_single_class: diag(1174, ts.DiagnosticCategory.Error, "Classes_can_only_extend_a_single_class_1174", "Classes can only extend a single class."), + implements_clause_already_seen: diag(1175, ts.DiagnosticCategory.Error, "implements_clause_already_seen_1175", "'implements' clause already seen."), + Interface_declaration_cannot_have_implements_clause: diag(1176, ts.DiagnosticCategory.Error, "Interface_declaration_cannot_have_implements_clause_1176", "Interface declaration cannot have 'implements' clause."), + Binary_digit_expected: diag(1177, ts.DiagnosticCategory.Error, "Binary_digit_expected_1177", "Binary digit expected."), + Octal_digit_expected: diag(1178, ts.DiagnosticCategory.Error, "Octal_digit_expected_1178", "Octal digit expected."), + Unexpected_token_expected: diag(1179, ts.DiagnosticCategory.Error, "Unexpected_token_expected_1179", "Unexpected token. '{' expected."), + Property_destructuring_pattern_expected: diag(1180, ts.DiagnosticCategory.Error, "Property_destructuring_pattern_expected_1180", "Property destructuring pattern expected."), + Array_element_destructuring_pattern_expected: diag(1181, ts.DiagnosticCategory.Error, "Array_element_destructuring_pattern_expected_1181", "Array element destructuring pattern expected."), + A_destructuring_declaration_must_have_an_initializer: diag(1182, ts.DiagnosticCategory.Error, "A_destructuring_declaration_must_have_an_initializer_1182", "A destructuring declaration must have an initializer."), + An_implementation_cannot_be_declared_in_ambient_contexts: diag(1183, ts.DiagnosticCategory.Error, "An_implementation_cannot_be_declared_in_ambient_contexts_1183", "An implementation cannot be declared in ambient contexts."), + Modifiers_cannot_appear_here: diag(1184, ts.DiagnosticCategory.Error, "Modifiers_cannot_appear_here_1184", "Modifiers cannot appear here."), + Merge_conflict_marker_encountered: diag(1185, ts.DiagnosticCategory.Error, "Merge_conflict_marker_encountered_1185", "Merge conflict marker encountered."), + A_rest_element_cannot_have_an_initializer: diag(1186, ts.DiagnosticCategory.Error, "A_rest_element_cannot_have_an_initializer_1186", "A rest element cannot have an initializer."), + A_parameter_property_may_not_be_declared_using_a_binding_pattern: diag(1187, ts.DiagnosticCategory.Error, "A_parameter_property_may_not_be_declared_using_a_binding_pattern_1187", "A parameter property may not be declared using a binding pattern."), + Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement: diag(1188, ts.DiagnosticCategory.Error, "Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement_1188", "Only a single variable declaration is allowed in a 'for...of' statement."), + The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer: diag(1189, ts.DiagnosticCategory.Error, "The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer_1189", "The variable declaration of a 'for...in' statement cannot have an initializer."), + The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer: diag(1190, ts.DiagnosticCategory.Error, "The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer_1190", "The variable declaration of a 'for...of' statement cannot have an initializer."), + An_import_declaration_cannot_have_modifiers: diag(1191, ts.DiagnosticCategory.Error, "An_import_declaration_cannot_have_modifiers_1191", "An import declaration cannot have modifiers."), + Module_0_has_no_default_export: diag(1192, ts.DiagnosticCategory.Error, "Module_0_has_no_default_export_1192", "Module '{0}' has no default export."), + An_export_declaration_cannot_have_modifiers: diag(1193, ts.DiagnosticCategory.Error, "An_export_declaration_cannot_have_modifiers_1193", "An export declaration cannot have modifiers."), + Export_declarations_are_not_permitted_in_a_namespace: diag(1194, ts.DiagnosticCategory.Error, "Export_declarations_are_not_permitted_in_a_namespace_1194", "Export declarations are not permitted in a namespace."), + Catch_clause_variable_cannot_have_a_type_annotation: diag(1196, ts.DiagnosticCategory.Error, "Catch_clause_variable_cannot_have_a_type_annotation_1196", "Catch clause variable cannot have a type annotation."), + Catch_clause_variable_cannot_have_an_initializer: diag(1197, ts.DiagnosticCategory.Error, "Catch_clause_variable_cannot_have_an_initializer_1197", "Catch clause variable cannot have an initializer."), + An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive: diag(1198, ts.DiagnosticCategory.Error, "An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive_1198", "An extended Unicode escape value must be between 0x0 and 0x10FFFF inclusive."), + Unterminated_Unicode_escape_sequence: diag(1199, ts.DiagnosticCategory.Error, "Unterminated_Unicode_escape_sequence_1199", "Unterminated Unicode escape sequence."), + Line_terminator_not_permitted_before_arrow: diag(1200, ts.DiagnosticCategory.Error, "Line_terminator_not_permitted_before_arrow_1200", "Line terminator not permitted before arrow."), + Import_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_import_Asterisk_as_ns_from_mod_import_a_from_mod_import_d_from_mod_or_another_module_format_instead: diag(1202, ts.DiagnosticCategory.Error, "Import_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_import_Asterisk_as_1202", "Import assignment cannot be used when targeting ECMAScript modules. Consider using 'import * as ns from \"mod\"', 'import {a} from \"mod\"', 'import d from \"mod\"', or another module format instead."), + Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or_another_module_format_instead: diag(1203, ts.DiagnosticCategory.Error, "Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or__1203", "Export assignment cannot be used when targeting ECMAScript modules. Consider using 'export default' or another module format instead."), + Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided: diag(1205, ts.DiagnosticCategory.Error, "Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205", "Cannot re-export a type when the '--isolatedModules' flag is provided."), + Decorators_are_not_valid_here: diag(1206, ts.DiagnosticCategory.Error, "Decorators_are_not_valid_here_1206", "Decorators are not valid here."), + Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name: diag(1207, ts.DiagnosticCategory.Error, "Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name_1207", "Decorators cannot be applied to multiple get/set accessors of the same name."), + Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided: diag(1208, ts.DiagnosticCategory.Error, "Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided_1208", "Cannot compile namespaces when the '--isolatedModules' flag is provided."), + Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided: diag(1209, ts.DiagnosticCategory.Error, "Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided_1209", "Ambient const enums are not allowed when the '--isolatedModules' flag is provided."), + Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode: diag(1210, ts.DiagnosticCategory.Error, "Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode_1210", "Invalid use of '{0}'. Class definitions are automatically in strict mode."), + A_class_declaration_without_the_default_modifier_must_have_a_name: diag(1211, ts.DiagnosticCategory.Error, "A_class_declaration_without_the_default_modifier_must_have_a_name_1211", "A class declaration without the 'default' modifier must have a name."), + Identifier_expected_0_is_a_reserved_word_in_strict_mode: diag(1212, ts.DiagnosticCategory.Error, "Identifier_expected_0_is_a_reserved_word_in_strict_mode_1212", "Identifier expected. '{0}' is a reserved word in strict mode."), + Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode: diag(1213, ts.DiagnosticCategory.Error, "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_stric_1213", "Identifier expected. '{0}' is a reserved word in strict mode. Class definitions are automatically in strict mode."), + Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode: diag(1214, ts.DiagnosticCategory.Error, "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode_1214", "Identifier expected. '{0}' is a reserved word in strict mode. Modules are automatically in strict mode."), + Invalid_use_of_0_Modules_are_automatically_in_strict_mode: diag(1215, ts.DiagnosticCategory.Error, "Invalid_use_of_0_Modules_are_automatically_in_strict_mode_1215", "Invalid use of '{0}'. Modules are automatically in strict mode."), + Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules: diag(1216, ts.DiagnosticCategory.Error, "Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules_1216", "Identifier expected. '__esModule' is reserved as an exported marker when transforming ECMAScript modules."), + Export_assignment_is_not_supported_when_module_flag_is_system: diag(1218, ts.DiagnosticCategory.Error, "Export_assignment_is_not_supported_when_module_flag_is_system_1218", "Export assignment is not supported when '--module' flag is 'system'."), + Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_to_remove_this_warning: diag(1219, ts.DiagnosticCategory.Error, "Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_t_1219", "Experimental support for decorators is a feature that is subject to change in a future release. Set the 'experimentalDecorators' option to remove this warning."), + Generators_are_only_available_when_targeting_ECMAScript_2015_or_higher: diag(1220, ts.DiagnosticCategory.Error, "Generators_are_only_available_when_targeting_ECMAScript_2015_or_higher_1220", "Generators are only available when targeting ECMAScript 2015 or higher."), + Generators_are_not_allowed_in_an_ambient_context: diag(1221, ts.DiagnosticCategory.Error, "Generators_are_not_allowed_in_an_ambient_context_1221", "Generators are not allowed in an ambient context."), + An_overload_signature_cannot_be_declared_as_a_generator: diag(1222, ts.DiagnosticCategory.Error, "An_overload_signature_cannot_be_declared_as_a_generator_1222", "An overload signature cannot be declared as a generator."), + _0_tag_already_specified: diag(1223, ts.DiagnosticCategory.Error, "_0_tag_already_specified_1223", "'{0}' tag already specified."), + Signature_0_must_be_a_type_predicate: diag(1224, ts.DiagnosticCategory.Error, "Signature_0_must_be_a_type_predicate_1224", "Signature '{0}' must be a type predicate."), + Cannot_find_parameter_0: diag(1225, ts.DiagnosticCategory.Error, "Cannot_find_parameter_0_1225", "Cannot find parameter '{0}'."), + Type_predicate_0_is_not_assignable_to_1: diag(1226, ts.DiagnosticCategory.Error, "Type_predicate_0_is_not_assignable_to_1_1226", "Type predicate '{0}' is not assignable to '{1}'."), + Parameter_0_is_not_in_the_same_position_as_parameter_1: diag(1227, ts.DiagnosticCategory.Error, "Parameter_0_is_not_in_the_same_position_as_parameter_1_1227", "Parameter '{0}' is not in the same position as parameter '{1}'."), + A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods: diag(1228, ts.DiagnosticCategory.Error, "A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods_1228", "A type predicate is only allowed in return type position for functions and methods."), + A_type_predicate_cannot_reference_a_rest_parameter: diag(1229, ts.DiagnosticCategory.Error, "A_type_predicate_cannot_reference_a_rest_parameter_1229", "A type predicate cannot reference a rest parameter."), + A_type_predicate_cannot_reference_element_0_in_a_binding_pattern: diag(1230, ts.DiagnosticCategory.Error, "A_type_predicate_cannot_reference_element_0_in_a_binding_pattern_1230", "A type predicate cannot reference element '{0}' in a binding pattern."), + An_export_assignment_can_only_be_used_in_a_module: diag(1231, ts.DiagnosticCategory.Error, "An_export_assignment_can_only_be_used_in_a_module_1231", "An export assignment can only be used in a module."), + An_import_declaration_can_only_be_used_in_a_namespace_or_module: diag(1232, ts.DiagnosticCategory.Error, "An_import_declaration_can_only_be_used_in_a_namespace_or_module_1232", "An import declaration can only be used in a namespace or module."), + An_export_declaration_can_only_be_used_in_a_module: diag(1233, ts.DiagnosticCategory.Error, "An_export_declaration_can_only_be_used_in_a_module_1233", "An export declaration can only be used in a module."), + An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file: diag(1234, ts.DiagnosticCategory.Error, "An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file_1234", "An ambient module declaration is only allowed at the top level in a file."), + A_namespace_declaration_is_only_allowed_in_a_namespace_or_module: diag(1235, ts.DiagnosticCategory.Error, "A_namespace_declaration_is_only_allowed_in_a_namespace_or_module_1235", "A namespace declaration is only allowed in a namespace or module."), + The_return_type_of_a_property_decorator_function_must_be_either_void_or_any: diag(1236, ts.DiagnosticCategory.Error, "The_return_type_of_a_property_decorator_function_must_be_either_void_or_any_1236", "The return type of a property decorator function must be either 'void' or 'any'."), + The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any: diag(1237, ts.DiagnosticCategory.Error, "The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any_1237", "The return type of a parameter decorator function must be either 'void' or 'any'."), + Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression: diag(1238, ts.DiagnosticCategory.Error, "Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression_1238", "Unable to resolve signature of class decorator when called as an expression."), + Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression: diag(1239, ts.DiagnosticCategory.Error, "Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression_1239", "Unable to resolve signature of parameter decorator when called as an expression."), + Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression: diag(1240, ts.DiagnosticCategory.Error, "Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression_1240", "Unable to resolve signature of property decorator when called as an expression."), + Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression: diag(1241, ts.DiagnosticCategory.Error, "Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression_1241", "Unable to resolve signature of method decorator when called as an expression."), + abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration: diag(1242, ts.DiagnosticCategory.Error, "abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration_1242", "'abstract' modifier can only appear on a class, method, or property declaration."), + _0_modifier_cannot_be_used_with_1_modifier: diag(1243, ts.DiagnosticCategory.Error, "_0_modifier_cannot_be_used_with_1_modifier_1243", "'{0}' modifier cannot be used with '{1}' modifier."), + Abstract_methods_can_only_appear_within_an_abstract_class: diag(1244, ts.DiagnosticCategory.Error, "Abstract_methods_can_only_appear_within_an_abstract_class_1244", "Abstract methods can only appear within an abstract class."), + Method_0_cannot_have_an_implementation_because_it_is_marked_abstract: diag(1245, ts.DiagnosticCategory.Error, "Method_0_cannot_have_an_implementation_because_it_is_marked_abstract_1245", "Method '{0}' cannot have an implementation because it is marked abstract."), + An_interface_property_cannot_have_an_initializer: diag(1246, ts.DiagnosticCategory.Error, "An_interface_property_cannot_have_an_initializer_1246", "An interface property cannot have an initializer."), + A_type_literal_property_cannot_have_an_initializer: diag(1247, ts.DiagnosticCategory.Error, "A_type_literal_property_cannot_have_an_initializer_1247", "A type literal property cannot have an initializer."), + A_class_member_cannot_have_the_0_keyword: diag(1248, ts.DiagnosticCategory.Error, "A_class_member_cannot_have_the_0_keyword_1248", "A class member cannot have the '{0}' keyword."), + A_decorator_can_only_decorate_a_method_implementation_not_an_overload: diag(1249, ts.DiagnosticCategory.Error, "A_decorator_can_only_decorate_a_method_implementation_not_an_overload_1249", "A decorator can only decorate a method implementation, not an overload."), + Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5: diag(1250, ts.DiagnosticCategory.Error, "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_1250", "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'."), + Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_definitions_are_automatically_in_strict_mode: diag(1251, ts.DiagnosticCategory.Error, "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_d_1251", "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Class definitions are automatically in strict mode."), + Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_are_automatically_in_strict_mode: diag(1252, ts.DiagnosticCategory.Error, "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_1252", "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Modules are automatically in strict mode."), + _0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag: diag(1253, ts.DiagnosticCategory.Error, "_0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag_1253", "'{0}' tag cannot be used independently as a top level JSDoc tag."), + A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_reference: diag(1254, ts.DiagnosticCategory.Error, "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_refere_1254", "A 'const' initializer in an ambient context must be a string or numeric literal or literal enum reference."), + A_definite_assignment_assertion_is_not_permitted_in_this_context: diag(1255, ts.DiagnosticCategory.Error, "A_definite_assignment_assertion_is_not_permitted_in_this_context_1255", "A definite assignment assertion '!' is not permitted in this context."), + A_rest_element_must_be_last_in_a_tuple_type: diag(1256, ts.DiagnosticCategory.Error, "A_rest_element_must_be_last_in_a_tuple_type_1256", "A rest element must be last in a tuple type."), + A_required_element_cannot_follow_an_optional_element: diag(1257, ts.DiagnosticCategory.Error, "A_required_element_cannot_follow_an_optional_element_1257", "A required element cannot follow an optional element."), + with_statements_are_not_allowed_in_an_async_function_block: diag(1300, ts.DiagnosticCategory.Error, "with_statements_are_not_allowed_in_an_async_function_block_1300", "'with' statements are not allowed in an async function block."), + await_expression_is_only_allowed_within_an_async_function: diag(1308, ts.DiagnosticCategory.Error, "await_expression_is_only_allowed_within_an_async_function_1308", "'await' expression is only allowed within an async function."), + can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment: diag(1312, ts.DiagnosticCategory.Error, "can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment_1312", "'=' can only be used in an object literal property inside a destructuring assignment."), + The_body_of_an_if_statement_cannot_be_the_empty_statement: diag(1313, ts.DiagnosticCategory.Error, "The_body_of_an_if_statement_cannot_be_the_empty_statement_1313", "The body of an 'if' statement cannot be the empty statement."), + Global_module_exports_may_only_appear_in_module_files: diag(1314, ts.DiagnosticCategory.Error, "Global_module_exports_may_only_appear_in_module_files_1314", "Global module exports may only appear in module files."), + Global_module_exports_may_only_appear_in_declaration_files: diag(1315, ts.DiagnosticCategory.Error, "Global_module_exports_may_only_appear_in_declaration_files_1315", "Global module exports may only appear in declaration files."), + Global_module_exports_may_only_appear_at_top_level: diag(1316, ts.DiagnosticCategory.Error, "Global_module_exports_may_only_appear_at_top_level_1316", "Global module exports may only appear at top level."), + A_parameter_property_cannot_be_declared_using_a_rest_parameter: diag(1317, ts.DiagnosticCategory.Error, "A_parameter_property_cannot_be_declared_using_a_rest_parameter_1317", "A parameter property cannot be declared using a rest parameter."), + An_abstract_accessor_cannot_have_an_implementation: diag(1318, ts.DiagnosticCategory.Error, "An_abstract_accessor_cannot_have_an_implementation_1318", "An abstract accessor cannot have an implementation."), + A_default_export_can_only_be_used_in_an_ECMAScript_style_module: diag(1319, ts.DiagnosticCategory.Error, "A_default_export_can_only_be_used_in_an_ECMAScript_style_module_1319", "A default export can only be used in an ECMAScript-style module."), + Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1320, ts.DiagnosticCategory.Error, "Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member_1320", "Type of 'await' operand must either be a valid promise or must not contain a callable 'then' member."), + Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1321, ts.DiagnosticCategory.Error, "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321", "Type of 'yield' operand in an async generator must either be a valid promise or must not contain a callable 'then' member."), + Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1322, ts.DiagnosticCategory.Error, "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322", "Type of iterated elements of a 'yield*' operand must either be a valid promise or must not contain a callable 'then' member."), + Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext: diag(1323, ts.DiagnosticCategory.Error, "Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext_1323", "Dynamic import is only supported when '--module' flag is 'commonjs' or 'esNext'."), + Dynamic_import_must_have_one_specifier_as_an_argument: diag(1324, ts.DiagnosticCategory.Error, "Dynamic_import_must_have_one_specifier_as_an_argument_1324", "Dynamic import must have one specifier as an argument."), + Specifier_of_dynamic_import_cannot_be_spread_element: diag(1325, ts.DiagnosticCategory.Error, "Specifier_of_dynamic_import_cannot_be_spread_element_1325", "Specifier of dynamic import cannot be spread element."), + Dynamic_import_cannot_have_type_arguments: diag(1326, ts.DiagnosticCategory.Error, "Dynamic_import_cannot_have_type_arguments_1326", "Dynamic import cannot have type arguments"), + String_literal_with_double_quotes_expected: diag(1327, ts.DiagnosticCategory.Error, "String_literal_with_double_quotes_expected_1327", "String literal with double quotes expected."), + Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_literal: diag(1328, ts.DiagnosticCategory.Error, "Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_li_1328", "Property value can only be string literal, numeric literal, 'true', 'false', 'null', object literal or array literal."), + _0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write_0: diag(1329, ts.DiagnosticCategory.Error, "_0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write__1329", "'{0}' accepts too few arguments to be used as a decorator here. Did you mean to call it first and write '@{0}()'?"), + A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly: diag(1330, ts.DiagnosticCategory.Error, "A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly_1330", "A property of an interface or type literal whose type is a 'unique symbol' type must be 'readonly'."), + A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly: diag(1331, ts.DiagnosticCategory.Error, "A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly_1331", "A property of a class whose type is a 'unique symbol' type must be both 'static' and 'readonly'."), + A_variable_whose_type_is_a_unique_symbol_type_must_be_const: diag(1332, ts.DiagnosticCategory.Error, "A_variable_whose_type_is_a_unique_symbol_type_must_be_const_1332", "A variable whose type is a 'unique symbol' type must be 'const'."), + unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name: diag(1333, ts.DiagnosticCategory.Error, "unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name_1333", "'unique symbol' types may not be used on a variable declaration with a binding name."), + unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement: diag(1334, ts.DiagnosticCategory.Error, "unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement_1334", "'unique symbol' types are only allowed on variables in a variable statement."), + unique_symbol_types_are_not_allowed_here: diag(1335, ts.DiagnosticCategory.Error, "unique_symbol_types_are_not_allowed_here_1335", "'unique symbol' types are not allowed here."), + An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead: diag(1336, ts.DiagnosticCategory.Error, "An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead_1336", "An index signature parameter type cannot be a type alias. Consider writing '[{0}: {1}]: {2}' instead."), + An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead: diag(1337, ts.DiagnosticCategory.Error, "An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead_1337", "An index signature parameter type cannot be a union type. Consider using a mapped object type instead."), + infer_declarations_are_only_permitted_in_the_extends_clause_of_a_conditional_type: diag(1338, ts.DiagnosticCategory.Error, "infer_declarations_are_only_permitted_in_the_extends_clause_of_a_conditional_type_1338", "'infer' declarations are only permitted in the 'extends' clause of a conditional type."), + Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here: diag(1339, ts.DiagnosticCategory.Error, "Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here_1339", "Module '{0}' does not refer to a value, but is used as a value here."), + Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0: diag(1340, ts.DiagnosticCategory.Error, "Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0_1340", "Module '{0}' does not refer to a type, but is used as a type here. Did you mean 'typeof import('{0}')'?"), + Type_arguments_cannot_be_used_here: diag(1342, ts.DiagnosticCategory.Error, "Type_arguments_cannot_be_used_here_1342", "Type arguments cannot be used here."), + The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_options: diag(1343, ts.DiagnosticCategory.Error, "The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_option_1343", "The 'import.meta' meta-property is only allowed using 'ESNext' for the 'target' and 'module' compiler options."), + A_label_is_not_allowed_here: diag(1344, ts.DiagnosticCategory.Error, "A_label_is_not_allowed_here_1344", "'A label is not allowed here."), + An_expression_of_type_void_cannot_be_tested_for_truthiness: diag(1345, ts.DiagnosticCategory.Error, "An_expression_of_type_void_cannot_be_tested_for_truthiness_1345", "An expression of type 'void' cannot be tested for truthiness"), + This_parameter_is_not_allowed_with_use_strict_directive: diag(1346, ts.DiagnosticCategory.Error, "This_parameter_is_not_allowed_with_use_strict_directive_1346", "This parameter is not allowed with 'use strict' directive."), + use_strict_directive_cannot_be_used_with_non_simple_parameter_list: diag(1347, ts.DiagnosticCategory.Error, "use_strict_directive_cannot_be_used_with_non_simple_parameter_list_1347", "'use strict' directive cannot be used with non-simple parameter list."), + Non_simple_parameter_declared_here: diag(1348, ts.DiagnosticCategory.Error, "Non_simple_parameter_declared_here_1348", "Non-simple parameter declared here."), + use_strict_directive_used_here: diag(1349, ts.DiagnosticCategory.Error, "use_strict_directive_used_here_1349", "'use strict' directive used here."), + Print_the_final_configuration_instead_of_building: diag(1350, ts.DiagnosticCategory.Message, "Print_the_final_configuration_instead_of_building_1350", "Print the final configuration instead of building."), + Duplicate_identifier_0: diag(2300, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_2300", "Duplicate identifier '{0}'."), + Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: diag(2301, ts.DiagnosticCategory.Error, "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301", "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor."), + Static_members_cannot_reference_class_type_parameters: diag(2302, ts.DiagnosticCategory.Error, "Static_members_cannot_reference_class_type_parameters_2302", "Static members cannot reference class type parameters."), + Circular_definition_of_import_alias_0: diag(2303, ts.DiagnosticCategory.Error, "Circular_definition_of_import_alias_0_2303", "Circular definition of import alias '{0}'."), + Cannot_find_name_0: diag(2304, ts.DiagnosticCategory.Error, "Cannot_find_name_0_2304", "Cannot find name '{0}'."), + Module_0_has_no_exported_member_1: diag(2305, ts.DiagnosticCategory.Error, "Module_0_has_no_exported_member_1_2305", "Module '{0}' has no exported member '{1}'."), + File_0_is_not_a_module: diag(2306, ts.DiagnosticCategory.Error, "File_0_is_not_a_module_2306", "File '{0}' is not a module."), + Cannot_find_module_0: diag(2307, ts.DiagnosticCategory.Error, "Cannot_find_module_0_2307", "Cannot find module '{0}'."), + Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambiguity: diag(2308, ts.DiagnosticCategory.Error, "Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambig_2308", "Module {0} has already exported a member named '{1}'. Consider explicitly re-exporting to resolve the ambiguity."), + An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements: diag(2309, ts.DiagnosticCategory.Error, "An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements_2309", "An export assignment cannot be used in a module with other exported elements."), + Type_0_recursively_references_itself_as_a_base_type: diag(2310, ts.DiagnosticCategory.Error, "Type_0_recursively_references_itself_as_a_base_type_2310", "Type '{0}' recursively references itself as a base type."), + A_class_may_only_extend_another_class: diag(2311, ts.DiagnosticCategory.Error, "A_class_may_only_extend_another_class_2311", "A class may only extend another class."), + An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_members: diag(2312, ts.DiagnosticCategory.Error, "An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_me_2312", "An interface can only extend an object type or intersection of object types with statically known members."), + Type_parameter_0_has_a_circular_constraint: diag(2313, ts.DiagnosticCategory.Error, "Type_parameter_0_has_a_circular_constraint_2313", "Type parameter '{0}' has a circular constraint."), + Generic_type_0_requires_1_type_argument_s: diag(2314, ts.DiagnosticCategory.Error, "Generic_type_0_requires_1_type_argument_s_2314", "Generic type '{0}' requires {1} type argument(s)."), + Type_0_is_not_generic: diag(2315, ts.DiagnosticCategory.Error, "Type_0_is_not_generic_2315", "Type '{0}' is not generic."), + Global_type_0_must_be_a_class_or_interface_type: diag(2316, ts.DiagnosticCategory.Error, "Global_type_0_must_be_a_class_or_interface_type_2316", "Global type '{0}' must be a class or interface type."), + Global_type_0_must_have_1_type_parameter_s: diag(2317, ts.DiagnosticCategory.Error, "Global_type_0_must_have_1_type_parameter_s_2317", "Global type '{0}' must have {1} type parameter(s)."), + Cannot_find_global_type_0: diag(2318, ts.DiagnosticCategory.Error, "Cannot_find_global_type_0_2318", "Cannot find global type '{0}'."), + Named_property_0_of_types_1_and_2_are_not_identical: diag(2319, ts.DiagnosticCategory.Error, "Named_property_0_of_types_1_and_2_are_not_identical_2319", "Named property '{0}' of types '{1}' and '{2}' are not identical."), + Interface_0_cannot_simultaneously_extend_types_1_and_2: diag(2320, ts.DiagnosticCategory.Error, "Interface_0_cannot_simultaneously_extend_types_1_and_2_2320", "Interface '{0}' cannot simultaneously extend types '{1}' and '{2}'."), + Excessive_stack_depth_comparing_types_0_and_1: diag(2321, ts.DiagnosticCategory.Error, "Excessive_stack_depth_comparing_types_0_and_1_2321", "Excessive stack depth comparing types '{0}' and '{1}'."), + Type_0_is_not_assignable_to_type_1: diag(2322, ts.DiagnosticCategory.Error, "Type_0_is_not_assignable_to_type_1_2322", "Type '{0}' is not assignable to type '{1}'."), + Cannot_redeclare_exported_variable_0: diag(2323, ts.DiagnosticCategory.Error, "Cannot_redeclare_exported_variable_0_2323", "Cannot redeclare exported variable '{0}'."), + Property_0_is_missing_in_type_1: diag(2324, ts.DiagnosticCategory.Error, "Property_0_is_missing_in_type_1_2324", "Property '{0}' is missing in type '{1}'."), + Property_0_is_private_in_type_1_but_not_in_type_2: diag(2325, ts.DiagnosticCategory.Error, "Property_0_is_private_in_type_1_but_not_in_type_2_2325", "Property '{0}' is private in type '{1}' but not in type '{2}'."), + Types_of_property_0_are_incompatible: diag(2326, ts.DiagnosticCategory.Error, "Types_of_property_0_are_incompatible_2326", "Types of property '{0}' are incompatible."), + Property_0_is_optional_in_type_1_but_required_in_type_2: diag(2327, ts.DiagnosticCategory.Error, "Property_0_is_optional_in_type_1_but_required_in_type_2_2327", "Property '{0}' is optional in type '{1}' but required in type '{2}'."), + Types_of_parameters_0_and_1_are_incompatible: diag(2328, ts.DiagnosticCategory.Error, "Types_of_parameters_0_and_1_are_incompatible_2328", "Types of parameters '{0}' and '{1}' are incompatible."), + Index_signature_is_missing_in_type_0: diag(2329, ts.DiagnosticCategory.Error, "Index_signature_is_missing_in_type_0_2329", "Index signature is missing in type '{0}'."), + Index_signatures_are_incompatible: diag(2330, ts.DiagnosticCategory.Error, "Index_signatures_are_incompatible_2330", "Index signatures are incompatible."), + this_cannot_be_referenced_in_a_module_or_namespace_body: diag(2331, ts.DiagnosticCategory.Error, "this_cannot_be_referenced_in_a_module_or_namespace_body_2331", "'this' cannot be referenced in a module or namespace body."), + this_cannot_be_referenced_in_current_location: diag(2332, ts.DiagnosticCategory.Error, "this_cannot_be_referenced_in_current_location_2332", "'this' cannot be referenced in current location."), + this_cannot_be_referenced_in_constructor_arguments: diag(2333, ts.DiagnosticCategory.Error, "this_cannot_be_referenced_in_constructor_arguments_2333", "'this' cannot be referenced in constructor arguments."), + this_cannot_be_referenced_in_a_static_property_initializer: diag(2334, ts.DiagnosticCategory.Error, "this_cannot_be_referenced_in_a_static_property_initializer_2334", "'this' cannot be referenced in a static property initializer."), + super_can_only_be_referenced_in_a_derived_class: diag(2335, ts.DiagnosticCategory.Error, "super_can_only_be_referenced_in_a_derived_class_2335", "'super' can only be referenced in a derived class."), + super_cannot_be_referenced_in_constructor_arguments: diag(2336, ts.DiagnosticCategory.Error, "super_cannot_be_referenced_in_constructor_arguments_2336", "'super' cannot be referenced in constructor arguments."), + Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors: diag(2337, ts.DiagnosticCategory.Error, "Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors_2337", "Super calls are not permitted outside constructors or in nested functions inside constructors."), + super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_derived_class: diag(2338, ts.DiagnosticCategory.Error, "super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_der_2338", "'super' property access is permitted only in a constructor, member function, or member accessor of a derived class."), + Property_0_does_not_exist_on_type_1: diag(2339, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_2339", "Property '{0}' does not exist on type '{1}'."), + Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword: diag(2340, ts.DiagnosticCategory.Error, "Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword_2340", "Only public and protected methods of the base class are accessible via the 'super' keyword."), + Property_0_is_private_and_only_accessible_within_class_1: diag(2341, ts.DiagnosticCategory.Error, "Property_0_is_private_and_only_accessible_within_class_1_2341", "Property '{0}' is private and only accessible within class '{1}'."), + An_index_expression_argument_must_be_of_type_string_number_symbol_or_any: diag(2342, ts.DiagnosticCategory.Error, "An_index_expression_argument_must_be_of_type_string_number_symbol_or_any_2342", "An index expression argument must be of type 'string', 'number', 'symbol', or 'any'."), + This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1: diag(2343, ts.DiagnosticCategory.Error, "This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1_2343", "This syntax requires an imported helper named '{1}', but module '{0}' has no exported member '{1}'."), + Type_0_does_not_satisfy_the_constraint_1: diag(2344, ts.DiagnosticCategory.Error, "Type_0_does_not_satisfy_the_constraint_1_2344", "Type '{0}' does not satisfy the constraint '{1}'."), + Argument_of_type_0_is_not_assignable_to_parameter_of_type_1: diag(2345, ts.DiagnosticCategory.Error, "Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_2345", "Argument of type '{0}' is not assignable to parameter of type '{1}'."), + Call_target_does_not_contain_any_signatures: diag(2346, ts.DiagnosticCategory.Error, "Call_target_does_not_contain_any_signatures_2346", "Call target does not contain any signatures."), + Untyped_function_calls_may_not_accept_type_arguments: diag(2347, ts.DiagnosticCategory.Error, "Untyped_function_calls_may_not_accept_type_arguments_2347", "Untyped function calls may not accept type arguments."), + Value_of_type_0_is_not_callable_Did_you_mean_to_include_new: diag(2348, ts.DiagnosticCategory.Error, "Value_of_type_0_is_not_callable_Did_you_mean_to_include_new_2348", "Value of type '{0}' is not callable. Did you mean to include 'new'?"), + Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures: diag(2349, ts.DiagnosticCategory.Error, "Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatur_2349", "Cannot invoke an expression whose type lacks a call signature. Type '{0}' has no compatible call signatures."), + Only_a_void_function_can_be_called_with_the_new_keyword: diag(2350, ts.DiagnosticCategory.Error, "Only_a_void_function_can_be_called_with_the_new_keyword_2350", "Only a void function can be called with the 'new' keyword."), + Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature: diag(2351, ts.DiagnosticCategory.Error, "Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature_2351", "Cannot use 'new' with an expression whose type lacks a call or construct signature."), + Conversion_of_type_0_to_type_1_may_be_a_mistake_because_neither_type_sufficiently_overlaps_with_the_other_If_this_was_intentional_convert_the_expression_to_unknown_first: diag(2352, ts.DiagnosticCategory.Error, "Conversion_of_type_0_to_type_1_may_be_a_mistake_because_neither_type_sufficiently_overlaps_with_the__2352", "Conversion of type '{0}' to type '{1}' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first."), + Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1: diag(2353, ts.DiagnosticCategory.Error, "Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1_2353", "Object literal may only specify known properties, and '{0}' does not exist in type '{1}'."), + This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found: diag(2354, ts.DiagnosticCategory.Error, "This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found_2354", "This syntax requires an imported helper but module '{0}' cannot be found."), + A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value: diag(2355, ts.DiagnosticCategory.Error, "A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value_2355", "A function whose declared type is neither 'void' nor 'any' must return a value."), + An_arithmetic_operand_must_be_of_type_any_number_bigint_or_an_enum_type: diag(2356, ts.DiagnosticCategory.Error, "An_arithmetic_operand_must_be_of_type_any_number_bigint_or_an_enum_type_2356", "An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type."), + The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access: diag(2357, ts.DiagnosticCategory.Error, "The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access_2357", "The operand of an increment or decrement operator must be a variable or a property access."), + The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter: diag(2358, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_paramete_2358", "The left-hand side of an 'instanceof' expression must be of type 'any', an object type or a type parameter."), + The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_Function_interface_type: diag(2359, ts.DiagnosticCategory.Error, "The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_F_2359", "The right-hand side of an 'instanceof' expression must be of type 'any' or of a type assignable to the 'Function' interface type."), + The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol: diag(2360, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol_2360", "The left-hand side of an 'in' expression must be of type 'any', 'string', 'number', or 'symbol'."), + The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter: diag(2361, ts.DiagnosticCategory.Error, "The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter_2361", "The right-hand side of an 'in' expression must be of type 'any', an object type or a type parameter."), + The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type: diag(2362, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type_2362", "The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type."), + The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type: diag(2363, ts.DiagnosticCategory.Error, "The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type_2363", "The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type."), + The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access: diag(2364, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access_2364", "The left-hand side of an assignment expression must be a variable or a property access."), + Operator_0_cannot_be_applied_to_types_1_and_2: diag(2365, ts.DiagnosticCategory.Error, "Operator_0_cannot_be_applied_to_types_1_and_2_2365", "Operator '{0}' cannot be applied to types '{1}' and '{2}'."), + Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined: diag(2366, ts.DiagnosticCategory.Error, "Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined_2366", "Function lacks ending return statement and return type does not include 'undefined'."), + This_condition_will_always_return_0_since_the_types_1_and_2_have_no_overlap: diag(2367, ts.DiagnosticCategory.Error, "This_condition_will_always_return_0_since_the_types_1_and_2_have_no_overlap_2367", "This condition will always return '{0}' since the types '{1}' and '{2}' have no overlap."), + Type_parameter_name_cannot_be_0: diag(2368, ts.DiagnosticCategory.Error, "Type_parameter_name_cannot_be_0_2368", "Type parameter name cannot be '{0}'."), + A_parameter_property_is_only_allowed_in_a_constructor_implementation: diag(2369, ts.DiagnosticCategory.Error, "A_parameter_property_is_only_allowed_in_a_constructor_implementation_2369", "A parameter property is only allowed in a constructor implementation."), + A_rest_parameter_must_be_of_an_array_type: diag(2370, ts.DiagnosticCategory.Error, "A_rest_parameter_must_be_of_an_array_type_2370", "A rest parameter must be of an array type."), + A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation: diag(2371, ts.DiagnosticCategory.Error, "A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation_2371", "A parameter initializer is only allowed in a function or constructor implementation."), + Parameter_0_cannot_be_referenced_in_its_initializer: diag(2372, ts.DiagnosticCategory.Error, "Parameter_0_cannot_be_referenced_in_its_initializer_2372", "Parameter '{0}' cannot be referenced in its initializer."), + Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it: diag(2373, ts.DiagnosticCategory.Error, "Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it_2373", "Initializer of parameter '{0}' cannot reference identifier '{1}' declared after it."), + Duplicate_string_index_signature: diag(2374, ts.DiagnosticCategory.Error, "Duplicate_string_index_signature_2374", "Duplicate string index signature."), + Duplicate_number_index_signature: diag(2375, ts.DiagnosticCategory.Error, "Duplicate_number_index_signature_2375", "Duplicate number index signature."), + A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_properties_or_has_parameter_properties: diag(2376, ts.DiagnosticCategory.Error, "A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_proper_2376", "A 'super' call must be the first statement in the constructor when a class contains initialized properties or has parameter properties."), + Constructors_for_derived_classes_must_contain_a_super_call: diag(2377, ts.DiagnosticCategory.Error, "Constructors_for_derived_classes_must_contain_a_super_call_2377", "Constructors for derived classes must contain a 'super' call."), + A_get_accessor_must_return_a_value: diag(2378, ts.DiagnosticCategory.Error, "A_get_accessor_must_return_a_value_2378", "A 'get' accessor must return a value."), + Getter_and_setter_accessors_do_not_agree_in_visibility: diag(2379, ts.DiagnosticCategory.Error, "Getter_and_setter_accessors_do_not_agree_in_visibility_2379", "Getter and setter accessors do not agree in visibility."), + get_and_set_accessor_must_have_the_same_type: diag(2380, ts.DiagnosticCategory.Error, "get_and_set_accessor_must_have_the_same_type_2380", "'get' and 'set' accessor must have the same type."), + A_signature_with_an_implementation_cannot_use_a_string_literal_type: diag(2381, ts.DiagnosticCategory.Error, "A_signature_with_an_implementation_cannot_use_a_string_literal_type_2381", "A signature with an implementation cannot use a string literal type."), + Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature: diag(2382, ts.DiagnosticCategory.Error, "Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature_2382", "Specialized overload signature is not assignable to any non-specialized signature."), + Overload_signatures_must_all_be_exported_or_non_exported: diag(2383, ts.DiagnosticCategory.Error, "Overload_signatures_must_all_be_exported_or_non_exported_2383", "Overload signatures must all be exported or non-exported."), + Overload_signatures_must_all_be_ambient_or_non_ambient: diag(2384, ts.DiagnosticCategory.Error, "Overload_signatures_must_all_be_ambient_or_non_ambient_2384", "Overload signatures must all be ambient or non-ambient."), + Overload_signatures_must_all_be_public_private_or_protected: diag(2385, ts.DiagnosticCategory.Error, "Overload_signatures_must_all_be_public_private_or_protected_2385", "Overload signatures must all be public, private or protected."), + Overload_signatures_must_all_be_optional_or_required: diag(2386, ts.DiagnosticCategory.Error, "Overload_signatures_must_all_be_optional_or_required_2386", "Overload signatures must all be optional or required."), + Function_overload_must_be_static: diag(2387, ts.DiagnosticCategory.Error, "Function_overload_must_be_static_2387", "Function overload must be static."), + Function_overload_must_not_be_static: diag(2388, ts.DiagnosticCategory.Error, "Function_overload_must_not_be_static_2388", "Function overload must not be static."), + Function_implementation_name_must_be_0: diag(2389, ts.DiagnosticCategory.Error, "Function_implementation_name_must_be_0_2389", "Function implementation name must be '{0}'."), + Constructor_implementation_is_missing: diag(2390, ts.DiagnosticCategory.Error, "Constructor_implementation_is_missing_2390", "Constructor implementation is missing."), + Function_implementation_is_missing_or_not_immediately_following_the_declaration: diag(2391, ts.DiagnosticCategory.Error, "Function_implementation_is_missing_or_not_immediately_following_the_declaration_2391", "Function implementation is missing or not immediately following the declaration."), + Multiple_constructor_implementations_are_not_allowed: diag(2392, ts.DiagnosticCategory.Error, "Multiple_constructor_implementations_are_not_allowed_2392", "Multiple constructor implementations are not allowed."), + Duplicate_function_implementation: diag(2393, ts.DiagnosticCategory.Error, "Duplicate_function_implementation_2393", "Duplicate function implementation."), + Overload_signature_is_not_compatible_with_function_implementation: diag(2394, ts.DiagnosticCategory.Error, "Overload_signature_is_not_compatible_with_function_implementation_2394", "Overload signature is not compatible with function implementation."), + Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local: diag(2395, ts.DiagnosticCategory.Error, "Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local_2395", "Individual declarations in merged declaration '{0}' must be all exported or all local."), + Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters: diag(2396, ts.DiagnosticCategory.Error, "Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters_2396", "Duplicate identifier 'arguments'. Compiler uses 'arguments' to initialize rest parameters."), + Declaration_name_conflicts_with_built_in_global_identifier_0: diag(2397, ts.DiagnosticCategory.Error, "Declaration_name_conflicts_with_built_in_global_identifier_0_2397", "Declaration name conflicts with built-in global identifier '{0}'."), + Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference: diag(2399, ts.DiagnosticCategory.Error, "Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference_2399", "Duplicate identifier '_this'. Compiler uses variable declaration '_this' to capture 'this' reference."), + Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference: diag(2400, ts.DiagnosticCategory.Error, "Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference_2400", "Expression resolves to variable declaration '_this' that compiler uses to capture 'this' reference."), + Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference: diag(2401, ts.DiagnosticCategory.Error, "Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference_2401", "Duplicate identifier '_super'. Compiler uses '_super' to capture base class reference."), + Expression_resolves_to_super_that_compiler_uses_to_capture_base_class_reference: diag(2402, ts.DiagnosticCategory.Error, "Expression_resolves_to_super_that_compiler_uses_to_capture_base_class_reference_2402", "Expression resolves to '_super' that compiler uses to capture base class reference."), + Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2: diag(2403, ts.DiagnosticCategory.Error, "Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_t_2403", "Subsequent variable declarations must have the same type. Variable '{0}' must be of type '{1}', but here has type '{2}'."), + The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation: diag(2404, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation_2404", "The left-hand side of a 'for...in' statement cannot use a type annotation."), + The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any: diag(2405, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any_2405", "The left-hand side of a 'for...in' statement must be of type 'string' or 'any'."), + The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access: diag(2406, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access_2406", "The left-hand side of a 'for...in' statement must be a variable or a property access."), + The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_but_here_has_type_0: diag(2407, ts.DiagnosticCategory.Error, "The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_but_2407", "The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter, but here has type '{0}'."), + Setters_cannot_return_a_value: diag(2408, ts.DiagnosticCategory.Error, "Setters_cannot_return_a_value_2408", "Setters cannot return a value."), + Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class: diag(2409, ts.DiagnosticCategory.Error, "Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class_2409", "Return type of constructor signature must be assignable to the instance type of the class."), + The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any: diag(2410, ts.DiagnosticCategory.Error, "The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any_2410", "The 'with' statement is not supported. All symbols in a 'with' block will have type 'any'."), + Property_0_of_type_1_is_not_assignable_to_string_index_type_2: diag(2411, ts.DiagnosticCategory.Error, "Property_0_of_type_1_is_not_assignable_to_string_index_type_2_2411", "Property '{0}' of type '{1}' is not assignable to string index type '{2}'."), + Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2: diag(2412, ts.DiagnosticCategory.Error, "Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2_2412", "Property '{0}' of type '{1}' is not assignable to numeric index type '{2}'."), + Numeric_index_type_0_is_not_assignable_to_string_index_type_1: diag(2413, ts.DiagnosticCategory.Error, "Numeric_index_type_0_is_not_assignable_to_string_index_type_1_2413", "Numeric index type '{0}' is not assignable to string index type '{1}'."), + Class_name_cannot_be_0: diag(2414, ts.DiagnosticCategory.Error, "Class_name_cannot_be_0_2414", "Class name cannot be '{0}'."), + Class_0_incorrectly_extends_base_class_1: diag(2415, ts.DiagnosticCategory.Error, "Class_0_incorrectly_extends_base_class_1_2415", "Class '{0}' incorrectly extends base class '{1}'."), + Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2: diag(2416, ts.DiagnosticCategory.Error, "Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2_2416", "Property '{0}' in type '{1}' is not assignable to the same property in base type '{2}'."), + Class_static_side_0_incorrectly_extends_base_class_static_side_1: diag(2417, ts.DiagnosticCategory.Error, "Class_static_side_0_incorrectly_extends_base_class_static_side_1_2417", "Class static side '{0}' incorrectly extends base class static side '{1}'."), + Type_of_computed_property_s_value_is_0_which_is_not_assignable_to_type_1: diag(2418, ts.DiagnosticCategory.Error, "Type_of_computed_property_s_value_is_0_which_is_not_assignable_to_type_1_2418", "Type of computed property's value is '{0}', which is not assignable to type '{1}'."), + Class_0_incorrectly_implements_interface_1: diag(2420, ts.DiagnosticCategory.Error, "Class_0_incorrectly_implements_interface_1_2420", "Class '{0}' incorrectly implements interface '{1}'."), + A_class_can_only_implement_an_object_type_or_intersection_of_object_types_with_statically_known_members: diag(2422, ts.DiagnosticCategory.Error, "A_class_can_only_implement_an_object_type_or_intersection_of_object_types_with_statically_known_memb_2422", "A class can only implement an object type or intersection of object types with statically known members."), + Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor: diag(2423, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_access_2423", "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member accessor."), + Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_property: diag(2424, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_proper_2424", "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member property."), + Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_function: diag(2425, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_functi_2425", "Class '{0}' defines instance member property '{1}', but extended class '{2}' defines it as instance member function."), + Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function: diag(2426, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_functi_2426", "Class '{0}' defines instance member accessor '{1}', but extended class '{2}' defines it as instance member function."), + Interface_name_cannot_be_0: diag(2427, ts.DiagnosticCategory.Error, "Interface_name_cannot_be_0_2427", "Interface name cannot be '{0}'."), + All_declarations_of_0_must_have_identical_type_parameters: diag(2428, ts.DiagnosticCategory.Error, "All_declarations_of_0_must_have_identical_type_parameters_2428", "All declarations of '{0}' must have identical type parameters."), + Interface_0_incorrectly_extends_interface_1: diag(2430, ts.DiagnosticCategory.Error, "Interface_0_incorrectly_extends_interface_1_2430", "Interface '{0}' incorrectly extends interface '{1}'."), + Enum_name_cannot_be_0: diag(2431, ts.DiagnosticCategory.Error, "Enum_name_cannot_be_0_2431", "Enum name cannot be '{0}'."), + In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enum_element: diag(2432, ts.DiagnosticCategory.Error, "In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enu_2432", "In an enum with multiple declarations, only one declaration can omit an initializer for its first enum element."), + A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merged: diag(2433, ts.DiagnosticCategory.Error, "A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merg_2433", "A namespace declaration cannot be in a different file from a class or function with which it is merged."), + A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged: diag(2434, ts.DiagnosticCategory.Error, "A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged_2434", "A namespace declaration cannot be located prior to a class or function with which it is merged."), + Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces: diag(2435, ts.DiagnosticCategory.Error, "Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces_2435", "Ambient modules cannot be nested in other modules or namespaces."), + Ambient_module_declaration_cannot_specify_relative_module_name: diag(2436, ts.DiagnosticCategory.Error, "Ambient_module_declaration_cannot_specify_relative_module_name_2436", "Ambient module declaration cannot specify relative module name."), + Module_0_is_hidden_by_a_local_declaration_with_the_same_name: diag(2437, ts.DiagnosticCategory.Error, "Module_0_is_hidden_by_a_local_declaration_with_the_same_name_2437", "Module '{0}' is hidden by a local declaration with the same name."), + Import_name_cannot_be_0: diag(2438, ts.DiagnosticCategory.Error, "Import_name_cannot_be_0_2438", "Import name cannot be '{0}'."), + Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relative_module_name: diag(2439, ts.DiagnosticCategory.Error, "Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relati_2439", "Import or export declaration in an ambient module declaration cannot reference module through relative module name."), + Import_declaration_conflicts_with_local_declaration_of_0: diag(2440, ts.DiagnosticCategory.Error, "Import_declaration_conflicts_with_local_declaration_of_0_2440", "Import declaration conflicts with local declaration of '{0}'."), + Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module: diag(2441, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_2441", "Duplicate identifier '{0}'. Compiler reserves name '{1}' in top level scope of a module."), + Types_have_separate_declarations_of_a_private_property_0: diag(2442, ts.DiagnosticCategory.Error, "Types_have_separate_declarations_of_a_private_property_0_2442", "Types have separate declarations of a private property '{0}'."), + Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2: diag(2443, ts.DiagnosticCategory.Error, "Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2_2443", "Property '{0}' is protected but type '{1}' is not a class derived from '{2}'."), + Property_0_is_protected_in_type_1_but_public_in_type_2: diag(2444, ts.DiagnosticCategory.Error, "Property_0_is_protected_in_type_1_but_public_in_type_2_2444", "Property '{0}' is protected in type '{1}' but public in type '{2}'."), + Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses: diag(2445, ts.DiagnosticCategory.Error, "Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses_2445", "Property '{0}' is protected and only accessible within class '{1}' and its subclasses."), + Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1: diag(2446, ts.DiagnosticCategory.Error, "Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1_2446", "Property '{0}' is protected and only accessible through an instance of class '{1}'."), + The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead: diag(2447, ts.DiagnosticCategory.Error, "The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead_2447", "The '{0}' operator is not allowed for boolean types. Consider using '{1}' instead."), + Block_scoped_variable_0_used_before_its_declaration: diag(2448, ts.DiagnosticCategory.Error, "Block_scoped_variable_0_used_before_its_declaration_2448", "Block-scoped variable '{0}' used before its declaration."), + Class_0_used_before_its_declaration: diag(2449, ts.DiagnosticCategory.Error, "Class_0_used_before_its_declaration_2449", "Class '{0}' used before its declaration."), + Enum_0_used_before_its_declaration: diag(2450, ts.DiagnosticCategory.Error, "Enum_0_used_before_its_declaration_2450", "Enum '{0}' used before its declaration."), + Cannot_redeclare_block_scoped_variable_0: diag(2451, ts.DiagnosticCategory.Error, "Cannot_redeclare_block_scoped_variable_0_2451", "Cannot redeclare block-scoped variable '{0}'."), + An_enum_member_cannot_have_a_numeric_name: diag(2452, ts.DiagnosticCategory.Error, "An_enum_member_cannot_have_a_numeric_name_2452", "An enum member cannot have a numeric name."), + The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_type_arguments_explicitly: diag(2453, ts.DiagnosticCategory.Error, "The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_typ_2453", "The type argument for type parameter '{0}' cannot be inferred from the usage. Consider specifying the type arguments explicitly."), + Variable_0_is_used_before_being_assigned: diag(2454, ts.DiagnosticCategory.Error, "Variable_0_is_used_before_being_assigned_2454", "Variable '{0}' is used before being assigned."), + Type_argument_candidate_1_is_not_a_valid_type_argument_because_it_is_not_a_supertype_of_candidate_0: diag(2455, ts.DiagnosticCategory.Error, "Type_argument_candidate_1_is_not_a_valid_type_argument_because_it_is_not_a_supertype_of_candidate_0_2455", "Type argument candidate '{1}' is not a valid type argument because it is not a supertype of candidate '{0}'."), + Type_alias_0_circularly_references_itself: diag(2456, ts.DiagnosticCategory.Error, "Type_alias_0_circularly_references_itself_2456", "Type alias '{0}' circularly references itself."), + Type_alias_name_cannot_be_0: diag(2457, ts.DiagnosticCategory.Error, "Type_alias_name_cannot_be_0_2457", "Type alias name cannot be '{0}'."), + An_AMD_module_cannot_have_multiple_name_assignments: diag(2458, ts.DiagnosticCategory.Error, "An_AMD_module_cannot_have_multiple_name_assignments_2458", "An AMD module cannot have multiple name assignments."), + Type_0_has_no_property_1_and_no_string_index_signature: diag(2459, ts.DiagnosticCategory.Error, "Type_0_has_no_property_1_and_no_string_index_signature_2459", "Type '{0}' has no property '{1}' and no string index signature."), + Type_0_has_no_property_1: diag(2460, ts.DiagnosticCategory.Error, "Type_0_has_no_property_1_2460", "Type '{0}' has no property '{1}'."), + Type_0_is_not_an_array_type: diag(2461, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_2461", "Type '{0}' is not an array type."), + A_rest_element_must_be_last_in_a_destructuring_pattern: diag(2462, ts.DiagnosticCategory.Error, "A_rest_element_must_be_last_in_a_destructuring_pattern_2462", "A rest element must be last in a destructuring pattern."), + A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature: diag(2463, ts.DiagnosticCategory.Error, "A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature_2463", "A binding pattern parameter cannot be optional in an implementation signature."), + A_computed_property_name_must_be_of_type_string_number_symbol_or_any: diag(2464, ts.DiagnosticCategory.Error, "A_computed_property_name_must_be_of_type_string_number_symbol_or_any_2464", "A computed property name must be of type 'string', 'number', 'symbol', or 'any'."), + this_cannot_be_referenced_in_a_computed_property_name: diag(2465, ts.DiagnosticCategory.Error, "this_cannot_be_referenced_in_a_computed_property_name_2465", "'this' cannot be referenced in a computed property name."), + super_cannot_be_referenced_in_a_computed_property_name: diag(2466, ts.DiagnosticCategory.Error, "super_cannot_be_referenced_in_a_computed_property_name_2466", "'super' cannot be referenced in a computed property name."), + A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type: diag(2467, ts.DiagnosticCategory.Error, "A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type_2467", "A computed property name cannot reference a type parameter from its containing type."), + Cannot_find_global_value_0: diag(2468, ts.DiagnosticCategory.Error, "Cannot_find_global_value_0_2468", "Cannot find global value '{0}'."), + The_0_operator_cannot_be_applied_to_type_symbol: diag(2469, ts.DiagnosticCategory.Error, "The_0_operator_cannot_be_applied_to_type_symbol_2469", "The '{0}' operator cannot be applied to type 'symbol'."), + Symbol_reference_does_not_refer_to_the_global_Symbol_constructor_object: diag(2470, ts.DiagnosticCategory.Error, "Symbol_reference_does_not_refer_to_the_global_Symbol_constructor_object_2470", "'Symbol' reference does not refer to the global Symbol constructor object."), + A_computed_property_name_of_the_form_0_must_be_of_type_symbol: diag(2471, ts.DiagnosticCategory.Error, "A_computed_property_name_of_the_form_0_must_be_of_type_symbol_2471", "A computed property name of the form '{0}' must be of type 'symbol'."), + Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher: diag(2472, ts.DiagnosticCategory.Error, "Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher_2472", "Spread operator in 'new' expressions is only available when targeting ECMAScript 5 and higher."), + Enum_declarations_must_all_be_const_or_non_const: diag(2473, ts.DiagnosticCategory.Error, "Enum_declarations_must_all_be_const_or_non_const_2473", "Enum declarations must all be const or non-const."), + In_const_enum_declarations_member_initializer_must_be_constant_expression: diag(2474, ts.DiagnosticCategory.Error, "In_const_enum_declarations_member_initializer_must_be_constant_expression_2474", "In 'const' enum declarations member initializer must be constant expression."), + const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment_or_type_query: diag(2475, ts.DiagnosticCategory.Error, "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475", "'const' enums can only be used in property or index access expressions or the right hand side of an import declaration or export assignment or type query."), + A_const_enum_member_can_only_be_accessed_using_a_string_literal: diag(2476, ts.DiagnosticCategory.Error, "A_const_enum_member_can_only_be_accessed_using_a_string_literal_2476", "A const enum member can only be accessed using a string literal."), + const_enum_member_initializer_was_evaluated_to_a_non_finite_value: diag(2477, ts.DiagnosticCategory.Error, "const_enum_member_initializer_was_evaluated_to_a_non_finite_value_2477", "'const' enum member initializer was evaluated to a non-finite value."), + const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN: diag(2478, ts.DiagnosticCategory.Error, "const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN_2478", "'const' enum member initializer was evaluated to disallowed value 'NaN'."), + Property_0_does_not_exist_on_const_enum_1: diag(2479, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_const_enum_1_2479", "Property '{0}' does not exist on 'const' enum '{1}'."), + let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations: diag(2480, ts.DiagnosticCategory.Error, "let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations_2480", "'let' is not allowed to be used as a name in 'let' or 'const' declarations."), + Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1: diag(2481, ts.DiagnosticCategory.Error, "Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1_2481", "Cannot initialize outer scoped variable '{0}' in the same scope as block scoped declaration '{1}'."), + The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation: diag(2483, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation_2483", "The left-hand side of a 'for...of' statement cannot use a type annotation."), + Export_declaration_conflicts_with_exported_declaration_of_0: diag(2484, ts.DiagnosticCategory.Error, "Export_declaration_conflicts_with_exported_declaration_of_0_2484", "Export declaration conflicts with exported declaration of '{0}'."), + The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access: diag(2487, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access_2487", "The left-hand side of a 'for...of' statement must be a variable or a property access."), + Type_0_must_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2488, ts.DiagnosticCategory.Error, "Type_0_must_have_a_Symbol_iterator_method_that_returns_an_iterator_2488", "Type '{0}' must have a '[Symbol.iterator]()' method that returns an iterator."), + An_iterator_must_have_a_next_method: diag(2489, ts.DiagnosticCategory.Error, "An_iterator_must_have_a_next_method_2489", "An iterator must have a 'next()' method."), + The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property: diag(2490, ts.DiagnosticCategory.Error, "The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property_2490", "The type returned by the 'next()' method of an iterator must have a 'value' property."), + The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern: diag(2491, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern_2491", "The left-hand side of a 'for...in' statement cannot be a destructuring pattern."), + Cannot_redeclare_identifier_0_in_catch_clause: diag(2492, ts.DiagnosticCategory.Error, "Cannot_redeclare_identifier_0_in_catch_clause_2492", "Cannot redeclare identifier '{0}' in catch clause."), + Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2: diag(2493, ts.DiagnosticCategory.Error, "Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2_2493", "Tuple type '{0}' with length '{1}' cannot be assigned to tuple with length '{2}'."), + Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher: diag(2494, ts.DiagnosticCategory.Error, "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494", "Using a string in a 'for...of' statement is only supported in ECMAScript 5 and higher."), + Type_0_is_not_an_array_type_or_a_string_type: diag(2495, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_a_string_type_2495", "Type '{0}' is not an array type or a string type."), + The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_standard_function_expression: diag(2496, ts.DiagnosticCategory.Error, "The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_stand_2496", "The 'arguments' object cannot be referenced in an arrow function in ES3 and ES5. Consider using a standard function expression."), + Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct: diag(2497, ts.DiagnosticCategory.Error, "Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct_2497", "Module '{0}' resolves to a non-module entity and cannot be imported using this construct."), + Module_0_uses_export_and_cannot_be_used_with_export_Asterisk: diag(2498, ts.DiagnosticCategory.Error, "Module_0_uses_export_and_cannot_be_used_with_export_Asterisk_2498", "Module '{0}' uses 'export =' and cannot be used with 'export *'."), + An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments: diag(2499, ts.DiagnosticCategory.Error, "An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments_2499", "An interface can only extend an identifier/qualified-name with optional type arguments."), + A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments: diag(2500, ts.DiagnosticCategory.Error, "A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments_2500", "A class can only implement an identifier/qualified-name with optional type arguments."), + A_rest_element_cannot_contain_a_binding_pattern: diag(2501, ts.DiagnosticCategory.Error, "A_rest_element_cannot_contain_a_binding_pattern_2501", "A rest element cannot contain a binding pattern."), + _0_is_referenced_directly_or_indirectly_in_its_own_type_annotation: diag(2502, ts.DiagnosticCategory.Error, "_0_is_referenced_directly_or_indirectly_in_its_own_type_annotation_2502", "'{0}' is referenced directly or indirectly in its own type annotation."), + Cannot_find_namespace_0: diag(2503, ts.DiagnosticCategory.Error, "Cannot_find_namespace_0_2503", "Cannot find namespace '{0}'."), + Type_0_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator: diag(2504, ts.DiagnosticCategory.Error, "Type_0_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator_2504", "Type '{0}' must have a '[Symbol.asyncIterator]()' method that returns an async iterator."), + A_generator_cannot_have_a_void_type_annotation: diag(2505, ts.DiagnosticCategory.Error, "A_generator_cannot_have_a_void_type_annotation_2505", "A generator cannot have a 'void' type annotation."), + _0_is_referenced_directly_or_indirectly_in_its_own_base_expression: diag(2506, ts.DiagnosticCategory.Error, "_0_is_referenced_directly_or_indirectly_in_its_own_base_expression_2506", "'{0}' is referenced directly or indirectly in its own base expression."), + Type_0_is_not_a_constructor_function_type: diag(2507, ts.DiagnosticCategory.Error, "Type_0_is_not_a_constructor_function_type_2507", "Type '{0}' is not a constructor function type."), + No_base_constructor_has_the_specified_number_of_type_arguments: diag(2508, ts.DiagnosticCategory.Error, "No_base_constructor_has_the_specified_number_of_type_arguments_2508", "No base constructor has the specified number of type arguments."), + Base_constructor_return_type_0_is_not_an_object_type_or_intersection_of_object_types_with_statically_known_members: diag(2509, ts.DiagnosticCategory.Error, "Base_constructor_return_type_0_is_not_an_object_type_or_intersection_of_object_types_with_statically_2509", "Base constructor return type '{0}' is not an object type or intersection of object types with statically known members."), + Base_constructors_must_all_have_the_same_return_type: diag(2510, ts.DiagnosticCategory.Error, "Base_constructors_must_all_have_the_same_return_type_2510", "Base constructors must all have the same return type."), + Cannot_create_an_instance_of_an_abstract_class: diag(2511, ts.DiagnosticCategory.Error, "Cannot_create_an_instance_of_an_abstract_class_2511", "Cannot create an instance of an abstract class."), + Overload_signatures_must_all_be_abstract_or_non_abstract: diag(2512, ts.DiagnosticCategory.Error, "Overload_signatures_must_all_be_abstract_or_non_abstract_2512", "Overload signatures must all be abstract or non-abstract."), + Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression: diag(2513, ts.DiagnosticCategory.Error, "Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression_2513", "Abstract method '{0}' in class '{1}' cannot be accessed via super expression."), + Classes_containing_abstract_methods_must_be_marked_abstract: diag(2514, ts.DiagnosticCategory.Error, "Classes_containing_abstract_methods_must_be_marked_abstract_2514", "Classes containing abstract methods must be marked abstract."), + Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2: diag(2515, ts.DiagnosticCategory.Error, "Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2_2515", "Non-abstract class '{0}' does not implement inherited abstract member '{1}' from class '{2}'."), + All_declarations_of_an_abstract_method_must_be_consecutive: diag(2516, ts.DiagnosticCategory.Error, "All_declarations_of_an_abstract_method_must_be_consecutive_2516", "All declarations of an abstract method must be consecutive."), + Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type: diag(2517, ts.DiagnosticCategory.Error, "Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type_2517", "Cannot assign an abstract constructor type to a non-abstract constructor type."), + A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard: diag(2518, ts.DiagnosticCategory.Error, "A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard_2518", "A 'this'-based type guard is not compatible with a parameter-based type guard."), + An_async_iterator_must_have_a_next_method: diag(2519, ts.DiagnosticCategory.Error, "An_async_iterator_must_have_a_next_method_2519", "An async iterator must have a 'next()' method."), + Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions: diag(2520, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions_2520", "Duplicate identifier '{0}'. Compiler uses declaration '{1}' to support async functions."), + Expression_resolves_to_variable_declaration_0_that_compiler_uses_to_support_async_functions: diag(2521, ts.DiagnosticCategory.Error, "Expression_resolves_to_variable_declaration_0_that_compiler_uses_to_support_async_functions_2521", "Expression resolves to variable declaration '{0}' that compiler uses to support async functions."), + The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_using_a_standard_function_or_method: diag(2522, ts.DiagnosticCategory.Error, "The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_usi_2522", "The 'arguments' object cannot be referenced in an async function or method in ES3 and ES5. Consider using a standard function or method."), + yield_expressions_cannot_be_used_in_a_parameter_initializer: diag(2523, ts.DiagnosticCategory.Error, "yield_expressions_cannot_be_used_in_a_parameter_initializer_2523", "'yield' expressions cannot be used in a parameter initializer."), + await_expressions_cannot_be_used_in_a_parameter_initializer: diag(2524, ts.DiagnosticCategory.Error, "await_expressions_cannot_be_used_in_a_parameter_initializer_2524", "'await' expressions cannot be used in a parameter initializer."), + Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value: diag(2525, ts.DiagnosticCategory.Error, "Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value_2525", "Initializer provides no value for this binding element and the binding element has no default value."), + A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface: diag(2526, ts.DiagnosticCategory.Error, "A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface_2526", "A 'this' type is available only in a non-static member of a class or interface."), + The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary: diag(2527, ts.DiagnosticCategory.Error, "The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary_2527", "The inferred type of '{0}' references an inaccessible '{1}' type. A type annotation is necessary."), + A_module_cannot_have_multiple_default_exports: diag(2528, ts.DiagnosticCategory.Error, "A_module_cannot_have_multiple_default_exports_2528", "A module cannot have multiple default exports."), + Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_functions: diag(2529, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_func_2529", "Duplicate identifier '{0}'. Compiler reserves name '{1}' in top level scope of a module containing async functions."), + Property_0_is_incompatible_with_index_signature: diag(2530, ts.DiagnosticCategory.Error, "Property_0_is_incompatible_with_index_signature_2530", "Property '{0}' is incompatible with index signature."), + Object_is_possibly_null: diag(2531, ts.DiagnosticCategory.Error, "Object_is_possibly_null_2531", "Object is possibly 'null'."), + Object_is_possibly_undefined: diag(2532, ts.DiagnosticCategory.Error, "Object_is_possibly_undefined_2532", "Object is possibly 'undefined'."), + Object_is_possibly_null_or_undefined: diag(2533, ts.DiagnosticCategory.Error, "Object_is_possibly_null_or_undefined_2533", "Object is possibly 'null' or 'undefined'."), + A_function_returning_never_cannot_have_a_reachable_end_point: diag(2534, ts.DiagnosticCategory.Error, "A_function_returning_never_cannot_have_a_reachable_end_point_2534", "A function returning 'never' cannot have a reachable end point."), + Enum_type_0_has_members_with_initializers_that_are_not_literals: diag(2535, ts.DiagnosticCategory.Error, "Enum_type_0_has_members_with_initializers_that_are_not_literals_2535", "Enum type '{0}' has members with initializers that are not literals."), + Type_0_cannot_be_used_to_index_type_1: diag(2536, ts.DiagnosticCategory.Error, "Type_0_cannot_be_used_to_index_type_1_2536", "Type '{0}' cannot be used to index type '{1}'."), + Type_0_has_no_matching_index_signature_for_type_1: diag(2537, ts.DiagnosticCategory.Error, "Type_0_has_no_matching_index_signature_for_type_1_2537", "Type '{0}' has no matching index signature for type '{1}'."), + Type_0_cannot_be_used_as_an_index_type: diag(2538, ts.DiagnosticCategory.Error, "Type_0_cannot_be_used_as_an_index_type_2538", "Type '{0}' cannot be used as an index type."), + Cannot_assign_to_0_because_it_is_not_a_variable: diag(2539, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_not_a_variable_2539", "Cannot assign to '{0}' because it is not a variable."), + Cannot_assign_to_0_because_it_is_a_read_only_property: diag(2540, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_a_read_only_property_2540", "Cannot assign to '{0}' because it is a read-only property."), + The_target_of_an_assignment_must_be_a_variable_or_a_property_access: diag(2541, ts.DiagnosticCategory.Error, "The_target_of_an_assignment_must_be_a_variable_or_a_property_access_2541", "The target of an assignment must be a variable or a property access."), + Index_signature_in_type_0_only_permits_reading: diag(2542, ts.DiagnosticCategory.Error, "Index_signature_in_type_0_only_permits_reading_2542", "Index signature in type '{0}' only permits reading."), + Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference: diag(2543, ts.DiagnosticCategory.Error, "Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_me_2543", "Duplicate identifier '_newTarget'. Compiler uses variable declaration '_newTarget' to capture 'new.target' meta-property reference."), + Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta_property_reference: diag(2544, ts.DiagnosticCategory.Error, "Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta__2544", "Expression resolves to variable declaration '_newTarget' that compiler uses to capture 'new.target' meta-property reference."), + A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any: diag(2545, ts.DiagnosticCategory.Error, "A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any_2545", "A mixin class must have a constructor with a single rest parameter of type 'any[]'."), + Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1: diag(2546, ts.DiagnosticCategory.Error, "Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1_2546", "Property '{0}' has conflicting declarations and is inaccessible in type '{1}'."), + The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property: diag(2547, ts.DiagnosticCategory.Error, "The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value__2547", "The type returned by the 'next()' method of an async iterator must be a promise for a type with a 'value' property."), + Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2548, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548", "Type '{0}' is not an array type or does not have a '[Symbol.iterator]()' method that returns an iterator."), + Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2549, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549", "Type '{0}' is not an array type or a string type or does not have a '[Symbol.iterator]()' method that returns an iterator."), + Property_0_does_not_exist_on_type_1_Did_you_mean_2: diag(2551, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551", "Property '{0}' does not exist on type '{1}'. Did you mean '{2}'?"), + Cannot_find_name_0_Did_you_mean_1: diag(2552, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Did_you_mean_1_2552", "Cannot find name '{0}'. Did you mean '{1}'?"), + Computed_values_are_not_permitted_in_an_enum_with_string_valued_members: diag(2553, ts.DiagnosticCategory.Error, "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553", "Computed values are not permitted in an enum with string valued members."), + Expected_0_arguments_but_got_1: diag(2554, ts.DiagnosticCategory.Error, "Expected_0_arguments_but_got_1_2554", "Expected {0} arguments, but got {1}."), + Expected_at_least_0_arguments_but_got_1: diag(2555, ts.DiagnosticCategory.Error, "Expected_at_least_0_arguments_but_got_1_2555", "Expected at least {0} arguments, but got {1}."), + Expected_0_arguments_but_got_1_or_more: diag(2556, ts.DiagnosticCategory.Error, "Expected_0_arguments_but_got_1_or_more_2556", "Expected {0} arguments, but got {1} or more."), + Expected_at_least_0_arguments_but_got_1_or_more: diag(2557, ts.DiagnosticCategory.Error, "Expected_at_least_0_arguments_but_got_1_or_more_2557", "Expected at least {0} arguments, but got {1} or more."), + Expected_0_type_arguments_but_got_1: diag(2558, ts.DiagnosticCategory.Error, "Expected_0_type_arguments_but_got_1_2558", "Expected {0} type arguments, but got {1}."), + Type_0_has_no_properties_in_common_with_type_1: diag(2559, ts.DiagnosticCategory.Error, "Type_0_has_no_properties_in_common_with_type_1_2559", "Type '{0}' has no properties in common with type '{1}'."), + Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it: diag(2560, ts.DiagnosticCategory.Error, "Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it_2560", "Value of type '{0}' has no properties in common with type '{1}'. Did you mean to call it?"), + Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_write_2: diag(2561, ts.DiagnosticCategory.Error, "Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_writ_2561", "Object literal may only specify known properties, but '{0}' does not exist in type '{1}'. Did you mean to write '{2}'?"), + Base_class_expressions_cannot_reference_class_type_parameters: diag(2562, ts.DiagnosticCategory.Error, "Base_class_expressions_cannot_reference_class_type_parameters_2562", "Base class expressions cannot reference class type parameters."), + The_containing_function_or_module_body_is_too_large_for_control_flow_analysis: diag(2563, ts.DiagnosticCategory.Error, "The_containing_function_or_module_body_is_too_large_for_control_flow_analysis_2563", "The containing function or module body is too large for control flow analysis."), + Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor: diag(2564, ts.DiagnosticCategory.Error, "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor_2564", "Property '{0}' has no initializer and is not definitely assigned in the constructor."), + Property_0_is_used_before_being_assigned: diag(2565, ts.DiagnosticCategory.Error, "Property_0_is_used_before_being_assigned_2565", "Property '{0}' is used before being assigned."), + A_rest_element_cannot_have_a_property_name: diag(2566, ts.DiagnosticCategory.Error, "A_rest_element_cannot_have_a_property_name_2566", "A rest element cannot have a property name."), + Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations: diag(2567, ts.DiagnosticCategory.Error, "Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations_2567", "Enum declarations can only merge with namespace or other enum declarations."), + Type_0_is_not_an_array_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators: diag(2568, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators_2568", "Type '{0}' is not an array type. Use compiler option '--downlevelIteration' to allow iterating of iterators."), + Type_0_is_not_an_array_type_or_a_string_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators: diag(2569, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_a_string_type_Use_compiler_option_downlevelIteration_to_allow_iterati_2569", "Type '{0}' is not an array type or a string type. Use compiler option '--downlevelIteration' to allow iterating of iterators."), + Property_0_does_not_exist_on_type_1_Did_you_forget_to_use_await: diag(2570, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_Did_you_forget_to_use_await_2570", "Property '{0}' does not exist on type '{1}'. Did you forget to use 'await'?"), + Object_is_of_type_unknown: diag(2571, ts.DiagnosticCategory.Error, "Object_is_of_type_unknown_2571", "Object is of type 'unknown'."), + Rest_signatures_are_incompatible: diag(2572, ts.DiagnosticCategory.Error, "Rest_signatures_are_incompatible_2572", "Rest signatures are incompatible."), + Property_0_is_incompatible_with_rest_element_type: diag(2573, ts.DiagnosticCategory.Error, "Property_0_is_incompatible_with_rest_element_type_2573", "Property '{0}' is incompatible with rest element type."), + A_rest_element_type_must_be_an_array_type: diag(2574, ts.DiagnosticCategory.Error, "A_rest_element_type_must_be_an_array_type_2574", "A rest element type must be an array type."), + No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments: diag(2575, ts.DiagnosticCategory.Error, "No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments_2575", "No overload expects {0} arguments, but overloads do exist that expect either {1} or {2} arguments."), + Property_0_is_a_static_member_of_type_1: diag(2576, ts.DiagnosticCategory.Error, "Property_0_is_a_static_member_of_type_1_2576", "Property '{0}' is a static member of type '{1}'"), + Return_type_annotation_circularly_references_itself: diag(2577, ts.DiagnosticCategory.Error, "Return_type_annotation_circularly_references_itself_2577", "Return type annotation circularly references itself."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_and_then_add_node_to_the_types_field_in_your_tsconfig: diag(2580, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_and_th_2580", "Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i @types/node` and then add `node` to the types field in your tsconfig."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_and_then_add_jquery_to_the_types_field_in_your_tsconfig: diag(2581, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_an_2581", "Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i @types/jquery` and then add `jquery` to the types field in your tsconfig."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha_and_then_add_jest_or_mocha_to_the_types_field_in_your_tsconfig: diag(2582, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashje_2582", "Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha` and then add `jest` or `mocha` to the types field in your tsconfig."), + Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later: diag(2583, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2583", "Cannot find name '{0}'. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later."), + Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom: diag(2584, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2584", "Cannot find name '{0}'. Do you need to change your target library? Try changing the `lib` compiler option to include 'dom'."), + _0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later: diag(2585, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_2585", "'{0}' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later."), + Enum_type_0_circularly_references_itself: diag(2586, ts.DiagnosticCategory.Error, "Enum_type_0_circularly_references_itself_2586", "Enum type '{0}' circularly references itself."), + JSDoc_type_0_circularly_references_itself: diag(2587, ts.DiagnosticCategory.Error, "JSDoc_type_0_circularly_references_itself_2587", "JSDoc type '{0}' circularly references itself."), + Cannot_assign_to_0_because_it_is_a_constant: diag(2588, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_a_constant_2588", "Cannot assign to '{0}' because it is a constant."), + JSX_element_attributes_type_0_may_not_be_a_union_type: diag(2600, ts.DiagnosticCategory.Error, "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", "JSX element attributes type '{0}' may not be a union type."), + The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: diag(2601, ts.DiagnosticCategory.Error, "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", "The return type of a JSX element constructor must return an object type."), + JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: diag(2602, ts.DiagnosticCategory.Error, "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist."), + Property_0_in_type_1_is_not_assignable_to_type_2: diag(2603, ts.DiagnosticCategory.Error, "Property_0_in_type_1_is_not_assignable_to_type_2_2603", "Property '{0}' in type '{1}' is not assignable to type '{2}'."), + JSX_element_type_0_does_not_have_any_construct_or_call_signatures: diag(2604, ts.DiagnosticCategory.Error, "JSX_element_type_0_does_not_have_any_construct_or_call_signatures_2604", "JSX element type '{0}' does not have any construct or call signatures."), + JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements: diag(2605, ts.DiagnosticCategory.Error, "JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements_2605", "JSX element type '{0}' is not a constructor function for JSX elements."), + Property_0_of_JSX_spread_attribute_is_not_assignable_to_target_property: diag(2606, ts.DiagnosticCategory.Error, "Property_0_of_JSX_spread_attribute_is_not_assignable_to_target_property_2606", "Property '{0}' of JSX spread attribute is not assignable to target property."), + JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property: diag(2607, ts.DiagnosticCategory.Error, "JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property_2607", "JSX element class does not support attributes because it does not have a '{0}' property."), + The_global_type_JSX_0_may_not_have_more_than_one_property: diag(2608, ts.DiagnosticCategory.Error, "The_global_type_JSX_0_may_not_have_more_than_one_property_2608", "The global type 'JSX.{0}' may not have more than one property."), + JSX_spread_child_must_be_an_array_type: diag(2609, ts.DiagnosticCategory.Error, "JSX_spread_child_must_be_an_array_type_2609", "JSX spread child must be an array type."), + Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity: diag(2649, ts.DiagnosticCategory.Error, "Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity_2649", "Cannot augment module '{0}' with value exports because it resolves to a non-module entity."), + A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums: diag(2651, ts.DiagnosticCategory.Error, "A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_memb_2651", "A member initializer in a enum declaration cannot reference members declared after it, including members defined in other enums."), + Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead: diag(2652, ts.DiagnosticCategory.Error, "Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_d_2652", "Merged declaration '{0}' cannot include a default export declaration. Consider adding a separate 'export default {0}' declaration instead."), + Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1: diag(2653, ts.DiagnosticCategory.Error, "Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1_2653", "Non-abstract class expression does not implement inherited abstract member '{0}' from class '{1}'."), + Exported_external_package_typings_file_cannot_contain_tripleslash_references_Please_contact_the_package_author_to_update_the_package_definition: diag(2654, ts.DiagnosticCategory.Error, "Exported_external_package_typings_file_cannot_contain_tripleslash_references_Please_contact_the_pack_2654", "Exported external package typings file cannot contain tripleslash references. Please contact the package author to update the package definition."), + Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_the_package_definition: diag(2656, ts.DiagnosticCategory.Error, "Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_2656", "Exported external package typings file '{0}' is not a module. Please contact the package author to update the package definition."), + JSX_expressions_must_have_one_parent_element: diag(2657, ts.DiagnosticCategory.Error, "JSX_expressions_must_have_one_parent_element_2657", "JSX expressions must have one parent element."), + Type_0_provides_no_match_for_the_signature_1: diag(2658, ts.DiagnosticCategory.Error, "Type_0_provides_no_match_for_the_signature_1_2658", "Type '{0}' provides no match for the signature '{1}'."), + super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_higher: diag(2659, ts.DiagnosticCategory.Error, "super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_highe_2659", "'super' is only allowed in members of object literal expressions when option 'target' is 'ES2015' or higher."), + super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions: diag(2660, ts.DiagnosticCategory.Error, "super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions_2660", "'super' can only be referenced in members of derived classes or object literal expressions."), + Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module: diag(2661, ts.DiagnosticCategory.Error, "Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module_2661", "Cannot export '{0}'. Only local declarations can be exported from a module."), + Cannot_find_name_0_Did_you_mean_the_static_member_1_0: diag(2662, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Did_you_mean_the_static_member_1_0_2662", "Cannot find name '{0}'. Did you mean the static member '{1}.{0}'?"), + Cannot_find_name_0_Did_you_mean_the_instance_member_this_0: diag(2663, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Did_you_mean_the_instance_member_this_0_2663", "Cannot find name '{0}'. Did you mean the instance member 'this.{0}'?"), + Invalid_module_name_in_augmentation_module_0_cannot_be_found: diag(2664, ts.DiagnosticCategory.Error, "Invalid_module_name_in_augmentation_module_0_cannot_be_found_2664", "Invalid module name in augmentation, module '{0}' cannot be found."), + Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented: diag(2665, ts.DiagnosticCategory.Error, "Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augm_2665", "Invalid module name in augmentation. Module '{0}' resolves to an untyped module at '{1}', which cannot be augmented."), + Exports_and_export_assignments_are_not_permitted_in_module_augmentations: diag(2666, ts.DiagnosticCategory.Error, "Exports_and_export_assignments_are_not_permitted_in_module_augmentations_2666", "Exports and export assignments are not permitted in module augmentations."), + Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_module: diag(2667, ts.DiagnosticCategory.Error, "Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_mod_2667", "Imports are not permitted in module augmentations. Consider moving them to the enclosing external module."), + export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always_visible: diag(2668, ts.DiagnosticCategory.Error, "export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always__2668", "'export' modifier cannot be applied to ambient modules and module augmentations since they are always visible."), + Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_declarations: diag(2669, ts.DiagnosticCategory.Error, "Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_2669", "Augmentations for the global scope can only be directly nested in external modules or ambient module declarations."), + Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambient_context: diag(2670, ts.DiagnosticCategory.Error, "Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambien_2670", "Augmentations for the global scope should have 'declare' modifier unless they appear in already ambient context."), + Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity: diag(2671, ts.DiagnosticCategory.Error, "Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity_2671", "Cannot augment module '{0}' because it resolves to a non-module entity."), + Cannot_assign_a_0_constructor_type_to_a_1_constructor_type: diag(2672, ts.DiagnosticCategory.Error, "Cannot_assign_a_0_constructor_type_to_a_1_constructor_type_2672", "Cannot assign a '{0}' constructor type to a '{1}' constructor type."), + Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration: diag(2673, ts.DiagnosticCategory.Error, "Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration_2673", "Constructor of class '{0}' is private and only accessible within the class declaration."), + Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration: diag(2674, ts.DiagnosticCategory.Error, "Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration_2674", "Constructor of class '{0}' is protected and only accessible within the class declaration."), + Cannot_extend_a_class_0_Class_constructor_is_marked_as_private: diag(2675, ts.DiagnosticCategory.Error, "Cannot_extend_a_class_0_Class_constructor_is_marked_as_private_2675", "Cannot extend a class '{0}'. Class constructor is marked as private."), + Accessors_must_both_be_abstract_or_non_abstract: diag(2676, ts.DiagnosticCategory.Error, "Accessors_must_both_be_abstract_or_non_abstract_2676", "Accessors must both be abstract or non-abstract."), + A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type: diag(2677, ts.DiagnosticCategory.Error, "A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type_2677", "A type predicate's type must be assignable to its parameter's type."), + Type_0_is_not_comparable_to_type_1: diag(2678, ts.DiagnosticCategory.Error, "Type_0_is_not_comparable_to_type_1_2678", "Type '{0}' is not comparable to type '{1}'."), + A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void: diag(2679, ts.DiagnosticCategory.Error, "A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void_2679", "A function that is called with the 'new' keyword cannot have a 'this' type that is 'void'."), + A_0_parameter_must_be_the_first_parameter: diag(2680, ts.DiagnosticCategory.Error, "A_0_parameter_must_be_the_first_parameter_2680", "A '{0}' parameter must be the first parameter."), + A_constructor_cannot_have_a_this_parameter: diag(2681, ts.DiagnosticCategory.Error, "A_constructor_cannot_have_a_this_parameter_2681", "A constructor cannot have a 'this' parameter."), + get_and_set_accessor_must_have_the_same_this_type: diag(2682, ts.DiagnosticCategory.Error, "get_and_set_accessor_must_have_the_same_this_type_2682", "'get' and 'set' accessor must have the same 'this' type."), + this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation: diag(2683, ts.DiagnosticCategory.Error, "this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_2683", "'this' implicitly has type 'any' because it does not have a type annotation."), + The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1: diag(2684, ts.DiagnosticCategory.Error, "The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1_2684", "The 'this' context of type '{0}' is not assignable to method's 'this' of type '{1}'."), + The_this_types_of_each_signature_are_incompatible: diag(2685, ts.DiagnosticCategory.Error, "The_this_types_of_each_signature_are_incompatible_2685", "The 'this' types of each signature are incompatible."), + _0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead: diag(2686, ts.DiagnosticCategory.Error, "_0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead_2686", "'{0}' refers to a UMD global, but the current file is a module. Consider adding an import instead."), + All_declarations_of_0_must_have_identical_modifiers: diag(2687, ts.DiagnosticCategory.Error, "All_declarations_of_0_must_have_identical_modifiers_2687", "All declarations of '{0}' must have identical modifiers."), + Cannot_find_type_definition_file_for_0: diag(2688, ts.DiagnosticCategory.Error, "Cannot_find_type_definition_file_for_0_2688", "Cannot find type definition file for '{0}'."), + Cannot_extend_an_interface_0_Did_you_mean_implements: diag(2689, ts.DiagnosticCategory.Error, "Cannot_extend_an_interface_0_Did_you_mean_implements_2689", "Cannot extend an interface '{0}'. Did you mean 'implements'?"), + An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead: diag(2691, ts.DiagnosticCategory.Error, "An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead_2691", "An import path cannot end with a '{0}' extension. Consider importing '{1}' instead."), + _0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible: diag(2692, ts.DiagnosticCategory.Error, "_0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible_2692", "'{0}' is a primitive, but '{1}' is a wrapper object. Prefer using '{0}' when possible."), + _0_only_refers_to_a_type_but_is_being_used_as_a_value_here: diag(2693, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_2693", "'{0}' only refers to a type, but is being used as a value here."), + Namespace_0_has_no_exported_member_1: diag(2694, ts.DiagnosticCategory.Error, "Namespace_0_has_no_exported_member_1_2694", "Namespace '{0}' has no exported member '{1}'."), + Left_side_of_comma_operator_is_unused_and_has_no_side_effects: diag(2695, ts.DiagnosticCategory.Error, "Left_side_of_comma_operator_is_unused_and_has_no_side_effects_2695", "Left side of comma operator is unused and has no side effects.", true), + The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead: diag(2696, ts.DiagnosticCategory.Error, "The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead_2696", "The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead?"), + An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option: diag(2697, ts.DiagnosticCategory.Error, "An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_in_2697", "An async function or method must return a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your `--lib` option."), + Spread_types_may_only_be_created_from_object_types: diag(2698, ts.DiagnosticCategory.Error, "Spread_types_may_only_be_created_from_object_types_2698", "Spread types may only be created from object types."), + Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1: diag(2699, ts.DiagnosticCategory.Error, "Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1_2699", "Static property '{0}' conflicts with built-in property 'Function.{0}' of constructor function '{1}'."), + Rest_types_may_only_be_created_from_object_types: diag(2700, ts.DiagnosticCategory.Error, "Rest_types_may_only_be_created_from_object_types_2700", "Rest types may only be created from object types."), + The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access: diag(2701, ts.DiagnosticCategory.Error, "The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access_2701", "The target of an object rest assignment must be a variable or a property access."), + _0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here: diag(2702, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here_2702", "'{0}' only refers to a type, but is being used as a namespace here."), + The_operand_of_a_delete_operator_must_be_a_property_reference: diag(2703, ts.DiagnosticCategory.Error, "The_operand_of_a_delete_operator_must_be_a_property_reference_2703", "The operand of a delete operator must be a property reference."), + The_operand_of_a_delete_operator_cannot_be_a_read_only_property: diag(2704, ts.DiagnosticCategory.Error, "The_operand_of_a_delete_operator_cannot_be_a_read_only_property_2704", "The operand of a delete operator cannot be a read-only property."), + An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option: diag(2705, ts.DiagnosticCategory.Error, "An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_de_2705", "An async function or method in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your `--lib` option."), + Required_type_parameters_may_not_follow_optional_type_parameters: diag(2706, ts.DiagnosticCategory.Error, "Required_type_parameters_may_not_follow_optional_type_parameters_2706", "Required type parameters may not follow optional type parameters."), + Generic_type_0_requires_between_1_and_2_type_arguments: diag(2707, ts.DiagnosticCategory.Error, "Generic_type_0_requires_between_1_and_2_type_arguments_2707", "Generic type '{0}' requires between {1} and {2} type arguments."), + Cannot_use_namespace_0_as_a_value: diag(2708, ts.DiagnosticCategory.Error, "Cannot_use_namespace_0_as_a_value_2708", "Cannot use namespace '{0}' as a value."), + Cannot_use_namespace_0_as_a_type: diag(2709, ts.DiagnosticCategory.Error, "Cannot_use_namespace_0_as_a_type_2709", "Cannot use namespace '{0}' as a type."), + _0_are_specified_twice_The_attribute_named_0_will_be_overwritten: diag(2710, ts.DiagnosticCategory.Error, "_0_are_specified_twice_The_attribute_named_0_will_be_overwritten_2710", "'{0}' are specified twice. The attribute named '{0}' will be overwritten."), + A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option: diag(2711, ts.DiagnosticCategory.Error, "A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES20_2711", "A dynamic import call returns a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your `--lib` option."), + A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option: diag(2712, ts.DiagnosticCategory.Error, "A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declarat_2712", "A dynamic import call in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your `--lib` option."), + Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_property_1_in_0_with_0_1: diag(2713, ts.DiagnosticCategory.Error, "Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_p_2713", "Cannot access '{0}.{1}' because '{0}' is a type, but not a namespace. Did you mean to retrieve the type of the property '{1}' in '{0}' with '{0}[\"{1}\"]'?"), + The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context: diag(2714, ts.DiagnosticCategory.Error, "The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context_2714", "The expression of an export assignment must be an identifier or qualified name in an ambient context."), + Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor: diag(2715, ts.DiagnosticCategory.Error, "Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor_2715", "Abstract property '{0}' in class '{1}' cannot be accessed in the constructor."), + Type_parameter_0_has_a_circular_default: diag(2716, ts.DiagnosticCategory.Error, "Type_parameter_0_has_a_circular_default_2716", "Type parameter '{0}' has a circular default."), + Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_type_2: diag(2717, ts.DiagnosticCategory.Error, "Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_t_2717", "Subsequent property declarations must have the same type. Property '{0}' must be of type '{1}', but here has type '{2}'."), + Duplicate_declaration_0: diag(2718, ts.DiagnosticCategory.Error, "Duplicate_declaration_0_2718", "Duplicate declaration '{0}'."), + Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated: diag(2719, ts.DiagnosticCategory.Error, "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_2719", "Type '{0}' is not assignable to type '{1}'. Two different types with this name exist, but they are unrelated."), + Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass: diag(2720, ts.DiagnosticCategory.Error, "Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclas_2720", "Class '{0}' incorrectly implements class '{1}'. Did you mean to extend '{1}' and inherit its members as a subclass?"), + Cannot_invoke_an_object_which_is_possibly_null: diag(2721, ts.DiagnosticCategory.Error, "Cannot_invoke_an_object_which_is_possibly_null_2721", "Cannot invoke an object which is possibly 'null'."), + Cannot_invoke_an_object_which_is_possibly_undefined: diag(2722, ts.DiagnosticCategory.Error, "Cannot_invoke_an_object_which_is_possibly_undefined_2722", "Cannot invoke an object which is possibly 'undefined'."), + Cannot_invoke_an_object_which_is_possibly_null_or_undefined: diag(2723, ts.DiagnosticCategory.Error, "Cannot_invoke_an_object_which_is_possibly_null_or_undefined_2723", "Cannot invoke an object which is possibly 'null' or 'undefined'."), + Module_0_has_no_exported_member_1_Did_you_mean_2: diag(2724, ts.DiagnosticCategory.Error, "Module_0_has_no_exported_member_1_Did_you_mean_2_2724", "Module '{0}' has no exported member '{1}'. Did you mean '{2}'?"), + Class_name_cannot_be_Object_when_targeting_ES5_with_module_0: diag(2725, ts.DiagnosticCategory.Error, "Class_name_cannot_be_Object_when_targeting_ES5_with_module_0_2725", "Class name cannot be 'Object' when targeting ES5 with module {0}."), + Cannot_find_lib_definition_for_0: diag(2726, ts.DiagnosticCategory.Error, "Cannot_find_lib_definition_for_0_2726", "Cannot find lib definition for '{0}'."), + Cannot_find_lib_definition_for_0_Did_you_mean_1: diag(2727, ts.DiagnosticCategory.Error, "Cannot_find_lib_definition_for_0_Did_you_mean_1_2727", "Cannot find lib definition for '{0}'. Did you mean '{1}'?"), + _0_is_declared_here: diag(2728, ts.DiagnosticCategory.Message, "_0_is_declared_here_2728", "'{0}' is declared here."), + Property_0_is_used_before_its_initialization: diag(2729, ts.DiagnosticCategory.Error, "Property_0_is_used_before_its_initialization_2729", "Property '{0}' is used before its initialization."), + An_arrow_function_cannot_have_a_this_parameter: diag(2730, ts.DiagnosticCategory.Error, "An_arrow_function_cannot_have_a_this_parameter_2730", "An arrow function cannot have a 'this' parameter."), + Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_in_String: diag(2731, ts.DiagnosticCategory.Error, "Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_i_2731", "Implicit conversion of a 'symbol' to a 'string' will fail at runtime. Consider wrapping this expression in 'String(...)'."), + Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension: diag(2732, ts.DiagnosticCategory.Error, "Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension_2732", "Cannot find module '{0}'. Consider using '--resolveJsonModule' to import module with '.json' extension"), + It_is_highly_likely_that_you_are_missing_a_semicolon: diag(2734, ts.DiagnosticCategory.Error, "It_is_highly_likely_that_you_are_missing_a_semicolon_2734", "It is highly likely that you are missing a semicolon."), + Did_you_mean_for_0_to_be_constrained_to_type_new_args_Colon_any_1: diag(2735, ts.DiagnosticCategory.Error, "Did_you_mean_for_0_to_be_constrained_to_type_new_args_Colon_any_1_2735", "Did you mean for '{0}' to be constrained to type 'new (...args: any[]) => {1}'?"), + Operator_0_cannot_be_applied_to_type_1: diag(2736, ts.DiagnosticCategory.Error, "Operator_0_cannot_be_applied_to_type_1_2736", "Operator '{0}' cannot be applied to type '{1}'."), + BigInt_literals_are_not_available_when_targeting_lower_than_ESNext: diag(2737, ts.DiagnosticCategory.Error, "BigInt_literals_are_not_available_when_targeting_lower_than_ESNext_2737", "BigInt literals are not available when targeting lower than ESNext."), + An_outer_value_of_this_is_shadowed_by_this_container: diag(2738, ts.DiagnosticCategory.Message, "An_outer_value_of_this_is_shadowed_by_this_container_2738", "An outer value of 'this' is shadowed by this container."), + Type_0_is_missing_the_following_properties_from_type_1_Colon_2: diag(2739, ts.DiagnosticCategory.Error, "Type_0_is_missing_the_following_properties_from_type_1_Colon_2_2739", "Type '{0}' is missing the following properties from type '{1}': {2}"), + Type_0_is_missing_the_following_properties_from_type_1_Colon_2_and_3_more: diag(2740, ts.DiagnosticCategory.Error, "Type_0_is_missing_the_following_properties_from_type_1_Colon_2_and_3_more_2740", "Type '{0}' is missing the following properties from type '{1}': {2}, and {3} more."), + Property_0_is_missing_in_type_1_but_required_in_type_2: diag(2741, ts.DiagnosticCategory.Error, "Property_0_is_missing_in_type_1_but_required_in_type_2_2741", "Property '{0}' is missing in type '{1}' but required in type '{2}'."), + The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_annotation_is_necessary: diag(2742, ts.DiagnosticCategory.Error, "The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_a_2742", "The inferred type of '{0}' cannot be named without a reference to '{1}'. This is likely not portable. A type annotation is necessary."), + Import_declaration_0_is_using_private_name_1: diag(4000, ts.DiagnosticCategory.Error, "Import_declaration_0_is_using_private_name_1_4000", "Import declaration '{0}' is using private name '{1}'."), + Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: diag(4002, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", "Type parameter '{0}' of exported class has or is using private name '{1}'."), + Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: diag(4004, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", "Type parameter '{0}' of exported interface has or is using private name '{1}'."), + Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1: diag(4006, ts.DiagnosticCategory.Error, "Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4006", "Type parameter '{0}' of constructor signature from exported interface has or is using private name '{1}'."), + Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1: diag(4008, ts.DiagnosticCategory.Error, "Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4008", "Type parameter '{0}' of call signature from exported interface has or is using private name '{1}'."), + Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1: diag(4010, ts.DiagnosticCategory.Error, "Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4010", "Type parameter '{0}' of public static method from exported class has or is using private name '{1}'."), + Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1: diag(4012, ts.DiagnosticCategory.Error, "Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4012", "Type parameter '{0}' of public method from exported class has or is using private name '{1}'."), + Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1: diag(4014, ts.DiagnosticCategory.Error, "Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4014", "Type parameter '{0}' of method from exported interface has or is using private name '{1}'."), + Type_parameter_0_of_exported_function_has_or_is_using_private_name_1: diag(4016, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_function_has_or_is_using_private_name_1_4016", "Type parameter '{0}' of exported function has or is using private name '{1}'."), + Implements_clause_of_exported_class_0_has_or_is_using_private_name_1: diag(4019, ts.DiagnosticCategory.Error, "Implements_clause_of_exported_class_0_has_or_is_using_private_name_1_4019", "Implements clause of exported class '{0}' has or is using private name '{1}'."), + extends_clause_of_exported_class_0_has_or_is_using_private_name_1: diag(4020, ts.DiagnosticCategory.Error, "extends_clause_of_exported_class_0_has_or_is_using_private_name_1_4020", "'extends' clause of exported class '{0}' has or is using private name '{1}'."), + extends_clause_of_exported_interface_0_has_or_is_using_private_name_1: diag(4022, ts.DiagnosticCategory.Error, "extends_clause_of_exported_interface_0_has_or_is_using_private_name_1_4022", "'extends' clause of exported interface '{0}' has or is using private name '{1}'."), + Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4023, ts.DiagnosticCategory.Error, "Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4023", "Exported variable '{0}' has or is using name '{1}' from external module {2} but cannot be named."), + Exported_variable_0_has_or_is_using_name_1_from_private_module_2: diag(4024, ts.DiagnosticCategory.Error, "Exported_variable_0_has_or_is_using_name_1_from_private_module_2_4024", "Exported variable '{0}' has or is using name '{1}' from private module '{2}'."), + Exported_variable_0_has_or_is_using_private_name_1: diag(4025, ts.DiagnosticCategory.Error, "Exported_variable_0_has_or_is_using_private_name_1_4025", "Exported variable '{0}' has or is using private name '{1}'."), + Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4026, ts.DiagnosticCategory.Error, "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot__4026", "Public static property '{0}' of exported class has or is using name '{1}' from external module {2} but cannot be named."), + Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4027, ts.DiagnosticCategory.Error, "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4027", "Public static property '{0}' of exported class has or is using name '{1}' from private module '{2}'."), + Public_static_property_0_of_exported_class_has_or_is_using_private_name_1: diag(4028, ts.DiagnosticCategory.Error, "Public_static_property_0_of_exported_class_has_or_is_using_private_name_1_4028", "Public static property '{0}' of exported class has or is using private name '{1}'."), + Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4029, ts.DiagnosticCategory.Error, "Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_name_4029", "Public property '{0}' of exported class has or is using name '{1}' from external module {2} but cannot be named."), + Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4030, ts.DiagnosticCategory.Error, "Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4030", "Public property '{0}' of exported class has or is using name '{1}' from private module '{2}'."), + Public_property_0_of_exported_class_has_or_is_using_private_name_1: diag(4031, ts.DiagnosticCategory.Error, "Public_property_0_of_exported_class_has_or_is_using_private_name_1_4031", "Public property '{0}' of exported class has or is using private name '{1}'."), + Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4032, ts.DiagnosticCategory.Error, "Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4032", "Property '{0}' of exported interface has or is using name '{1}' from private module '{2}'."), + Property_0_of_exported_interface_has_or_is_using_private_name_1: diag(4033, ts.DiagnosticCategory.Error, "Property_0_of_exported_interface_has_or_is_using_private_name_1_4033", "Property '{0}' of exported interface has or is using private name '{1}'."), + Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4034, ts.DiagnosticCategory.Error, "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_name_1_from_private_mod_4034", "Parameter type of public static setter '{0}' from exported class has or is using name '{1}' from private module '{2}'."), + Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1: diag(4035, ts.DiagnosticCategory.Error, "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1_4035", "Parameter type of public static setter '{0}' from exported class has or is using private name '{1}'."), + Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4036, ts.DiagnosticCategory.Error, "Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2_4036", "Parameter type of public setter '{0}' from exported class has or is using name '{1}' from private module '{2}'."), + Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_private_name_1: diag(4037, ts.DiagnosticCategory.Error, "Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_private_name_1_4037", "Parameter type of public setter '{0}' from exported class has or is using private name '{1}'."), + Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4038, ts.DiagnosticCategory.Error, "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_external_modul_4038", "Return type of public static getter '{0}' from exported class has or is using name '{1}' from external module {2} but cannot be named."), + Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4039, ts.DiagnosticCategory.Error, "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_4039", "Return type of public static getter '{0}' from exported class has or is using name '{1}' from private module '{2}'."), + Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_private_name_1: diag(4040, ts.DiagnosticCategory.Error, "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_private_name_1_4040", "Return type of public static getter '{0}' from exported class has or is using private name '{1}'."), + Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4041, ts.DiagnosticCategory.Error, "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_4041", "Return type of public getter '{0}' from exported class has or is using name '{1}' from external module {2} but cannot be named."), + Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4042, ts.DiagnosticCategory.Error, "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2_4042", "Return type of public getter '{0}' from exported class has or is using name '{1}' from private module '{2}'."), + Return_type_of_public_getter_0_from_exported_class_has_or_is_using_private_name_1: diag(4043, ts.DiagnosticCategory.Error, "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_private_name_1_4043", "Return type of public getter '{0}' from exported class has or is using private name '{1}'."), + Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1: diag(4044, ts.DiagnosticCategory.Error, "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_mod_4044", "Return type of constructor signature from exported interface has or is using name '{0}' from private module '{1}'."), + Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0: diag(4045, ts.DiagnosticCategory.Error, "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0_4045", "Return type of constructor signature from exported interface has or is using private name '{0}'."), + Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1: diag(4046, ts.DiagnosticCategory.Error, "Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4046", "Return type of call signature from exported interface has or is using name '{0}' from private module '{1}'."), + Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0: diag(4047, ts.DiagnosticCategory.Error, "Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0_4047", "Return type of call signature from exported interface has or is using private name '{0}'."), + Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1: diag(4048, ts.DiagnosticCategory.Error, "Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4048", "Return type of index signature from exported interface has or is using name '{0}' from private module '{1}'."), + Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0: diag(4049, ts.DiagnosticCategory.Error, "Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0_4049", "Return type of index signature from exported interface has or is using private name '{0}'."), + Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: diag(4050, ts.DiagnosticCategory.Error, "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module__4050", "Return type of public static method from exported class has or is using name '{0}' from external module {1} but cannot be named."), + Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1: diag(4051, ts.DiagnosticCategory.Error, "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4051", "Return type of public static method from exported class has or is using name '{0}' from private module '{1}'."), + Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0: diag(4052, ts.DiagnosticCategory.Error, "Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0_4052", "Return type of public static method from exported class has or is using private name '{0}'."), + Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: diag(4053, ts.DiagnosticCategory.Error, "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_c_4053", "Return type of public method from exported class has or is using name '{0}' from external module {1} but cannot be named."), + Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1: diag(4054, ts.DiagnosticCategory.Error, "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4054", "Return type of public method from exported class has or is using name '{0}' from private module '{1}'."), + Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0: diag(4055, ts.DiagnosticCategory.Error, "Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0_4055", "Return type of public method from exported class has or is using private name '{0}'."), + Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1: diag(4056, ts.DiagnosticCategory.Error, "Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4056", "Return type of method from exported interface has or is using name '{0}' from private module '{1}'."), + Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0: diag(4057, ts.DiagnosticCategory.Error, "Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0_4057", "Return type of method from exported interface has or is using private name '{0}'."), + Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: diag(4058, ts.DiagnosticCategory.Error, "Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named_4058", "Return type of exported function has or is using name '{0}' from external module {1} but cannot be named."), + Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1: diag(4059, ts.DiagnosticCategory.Error, "Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1_4059", "Return type of exported function has or is using name '{0}' from private module '{1}'."), + Return_type_of_exported_function_has_or_is_using_private_name_0: diag(4060, ts.DiagnosticCategory.Error, "Return_type_of_exported_function_has_or_is_using_private_name_0_4060", "Return type of exported function has or is using private name '{0}'."), + Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4061, ts.DiagnosticCategory.Error, "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_can_4061", "Parameter '{0}' of constructor from exported class has or is using name '{1}' from external module {2} but cannot be named."), + Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4062, ts.DiagnosticCategory.Error, "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2_4062", "Parameter '{0}' of constructor from exported class has or is using name '{1}' from private module '{2}'."), + Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1: diag(4063, ts.DiagnosticCategory.Error, "Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1_4063", "Parameter '{0}' of constructor from exported class has or is using private name '{1}'."), + Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4064, ts.DiagnosticCategory.Error, "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_mod_4064", "Parameter '{0}' of constructor signature from exported interface has or is using name '{1}' from private module '{2}'."), + Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1: diag(4065, ts.DiagnosticCategory.Error, "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4065", "Parameter '{0}' of constructor signature from exported interface has or is using private name '{1}'."), + Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4066, ts.DiagnosticCategory.Error, "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4066", "Parameter '{0}' of call signature from exported interface has or is using name '{1}' from private module '{2}'."), + Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1: diag(4067, ts.DiagnosticCategory.Error, "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4067", "Parameter '{0}' of call signature from exported interface has or is using private name '{1}'."), + Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4068, ts.DiagnosticCategory.Error, "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module__4068", "Parameter '{0}' of public static method from exported class has or is using name '{1}' from external module {2} but cannot be named."), + Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4069, ts.DiagnosticCategory.Error, "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4069", "Parameter '{0}' of public static method from exported class has or is using name '{1}' from private module '{2}'."), + Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1: diag(4070, ts.DiagnosticCategory.Error, "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4070", "Parameter '{0}' of public static method from exported class has or is using private name '{1}'."), + Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4071, ts.DiagnosticCategory.Error, "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_c_4071", "Parameter '{0}' of public method from exported class has or is using name '{1}' from external module {2} but cannot be named."), + Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4072, ts.DiagnosticCategory.Error, "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4072", "Parameter '{0}' of public method from exported class has or is using name '{1}' from private module '{2}'."), + Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1: diag(4073, ts.DiagnosticCategory.Error, "Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4073", "Parameter '{0}' of public method from exported class has or is using private name '{1}'."), + Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4074, ts.DiagnosticCategory.Error, "Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4074", "Parameter '{0}' of method from exported interface has or is using name '{1}' from private module '{2}'."), + Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1: diag(4075, ts.DiagnosticCategory.Error, "Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4075", "Parameter '{0}' of method from exported interface has or is using private name '{1}'."), + Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4076, ts.DiagnosticCategory.Error, "Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4076", "Parameter '{0}' of exported function has or is using name '{1}' from external module {2} but cannot be named."), + Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2: diag(4077, ts.DiagnosticCategory.Error, "Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2_4077", "Parameter '{0}' of exported function has or is using name '{1}' from private module '{2}'."), + Parameter_0_of_exported_function_has_or_is_using_private_name_1: diag(4078, ts.DiagnosticCategory.Error, "Parameter_0_of_exported_function_has_or_is_using_private_name_1_4078", "Parameter '{0}' of exported function has or is using private name '{1}'."), + Exported_type_alias_0_has_or_is_using_private_name_1: diag(4081, ts.DiagnosticCategory.Error, "Exported_type_alias_0_has_or_is_using_private_name_1_4081", "Exported type alias '{0}' has or is using private name '{1}'."), + Default_export_of_the_module_has_or_is_using_private_name_0: diag(4082, ts.DiagnosticCategory.Error, "Default_export_of_the_module_has_or_is_using_private_name_0_4082", "Default export of the module has or is using private name '{0}'."), + Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1: diag(4083, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1_4083", "Type parameter '{0}' of exported type alias has or is using private name '{1}'."), + Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict: diag(4090, ts.DiagnosticCategory.Error, "Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_librar_4090", "Conflicting definitions for '{0}' found at '{1}' and '{2}'. Consider installing a specific version of this library to resolve the conflict."), + Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4091, ts.DiagnosticCategory.Error, "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4091", "Parameter '{0}' of index signature from exported interface has or is using name '{1}' from private module '{2}'."), + Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1: diag(4092, ts.DiagnosticCategory.Error, "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1_4092", "Parameter '{0}' of index signature from exported interface has or is using private name '{1}'."), + Property_0_of_exported_class_expression_may_not_be_private_or_protected: diag(4094, ts.DiagnosticCategory.Error, "Property_0_of_exported_class_expression_may_not_be_private_or_protected_4094", "Property '{0}' of exported class expression may not be private or protected."), + Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4095, ts.DiagnosticCategory.Error, "Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_4095", "Public static method '{0}' of exported class has or is using name '{1}' from external module {2} but cannot be named."), + Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4096, ts.DiagnosticCategory.Error, "Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4096", "Public static method '{0}' of exported class has or is using name '{1}' from private module '{2}'."), + Public_static_method_0_of_exported_class_has_or_is_using_private_name_1: diag(4097, ts.DiagnosticCategory.Error, "Public_static_method_0_of_exported_class_has_or_is_using_private_name_1_4097", "Public static method '{0}' of exported class has or is using private name '{1}'."), + Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4098, ts.DiagnosticCategory.Error, "Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4098", "Public method '{0}' of exported class has or is using name '{1}' from external module {2} but cannot be named."), + Public_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4099, ts.DiagnosticCategory.Error, "Public_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4099", "Public method '{0}' of exported class has or is using name '{1}' from private module '{2}'."), + Public_method_0_of_exported_class_has_or_is_using_private_name_1: diag(4100, ts.DiagnosticCategory.Error, "Public_method_0_of_exported_class_has_or_is_using_private_name_1_4100", "Public method '{0}' of exported class has or is using private name '{1}'."), + Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4101, ts.DiagnosticCategory.Error, "Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4101", "Method '{0}' of exported interface has or is using name '{1}' from private module '{2}'."), + Method_0_of_exported_interface_has_or_is_using_private_name_1: diag(4102, ts.DiagnosticCategory.Error, "Method_0_of_exported_interface_has_or_is_using_private_name_1_4102", "Method '{0}' of exported interface has or is using private name '{1}'."), + The_current_host_does_not_support_the_0_option: diag(5001, ts.DiagnosticCategory.Error, "The_current_host_does_not_support_the_0_option_5001", "The current host does not support the '{0}' option."), + Cannot_find_the_common_subdirectory_path_for_the_input_files: diag(5009, ts.DiagnosticCategory.Error, "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009", "Cannot find the common subdirectory path for the input files."), + File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: diag(5010, ts.DiagnosticCategory.Error, "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010", "File specification cannot end in a recursive directory wildcard ('**'): '{0}'."), + Cannot_read_file_0_Colon_1: diag(5012, ts.DiagnosticCategory.Error, "Cannot_read_file_0_Colon_1_5012", "Cannot read file '{0}': {1}."), + Failed_to_parse_file_0_Colon_1: diag(5014, ts.DiagnosticCategory.Error, "Failed_to_parse_file_0_Colon_1_5014", "Failed to parse file '{0}': {1}."), + Unknown_compiler_option_0: diag(5023, ts.DiagnosticCategory.Error, "Unknown_compiler_option_0_5023", "Unknown compiler option '{0}'."), + Compiler_option_0_requires_a_value_of_type_1: diag(5024, ts.DiagnosticCategory.Error, "Compiler_option_0_requires_a_value_of_type_1_5024", "Compiler option '{0}' requires a value of type {1}."), + Could_not_write_file_0_Colon_1: diag(5033, ts.DiagnosticCategory.Error, "Could_not_write_file_0_Colon_1_5033", "Could not write file '{0}': {1}."), + Option_project_cannot_be_mixed_with_source_files_on_a_command_line: diag(5042, ts.DiagnosticCategory.Error, "Option_project_cannot_be_mixed_with_source_files_on_a_command_line_5042", "Option 'project' cannot be mixed with source files on a command line."), + Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher: diag(5047, ts.DiagnosticCategory.Error, "Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES_5047", "Option 'isolatedModules' can only be used when either option '--module' is provided or option 'target' is 'ES2015' or higher."), + Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided: diag(5051, ts.DiagnosticCategory.Error, "Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided_5051", "Option '{0} can only be used when either option '--inlineSourceMap' or option '--sourceMap' is provided."), + Option_0_cannot_be_specified_without_specifying_option_1: diag(5052, ts.DiagnosticCategory.Error, "Option_0_cannot_be_specified_without_specifying_option_1_5052", "Option '{0}' cannot be specified without specifying option '{1}'."), + Option_0_cannot_be_specified_with_option_1: diag(5053, ts.DiagnosticCategory.Error, "Option_0_cannot_be_specified_with_option_1_5053", "Option '{0}' cannot be specified with option '{1}'."), + A_tsconfig_json_file_is_already_defined_at_Colon_0: diag(5054, ts.DiagnosticCategory.Error, "A_tsconfig_json_file_is_already_defined_at_Colon_0_5054", "A 'tsconfig.json' file is already defined at: '{0}'."), + Cannot_write_file_0_because_it_would_overwrite_input_file: diag(5055, ts.DiagnosticCategory.Error, "Cannot_write_file_0_because_it_would_overwrite_input_file_5055", "Cannot write file '{0}' because it would overwrite input file."), + Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files: diag(5056, ts.DiagnosticCategory.Error, "Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files_5056", "Cannot write file '{0}' because it would be overwritten by multiple input files."), + Cannot_find_a_tsconfig_json_file_at_the_specified_directory_Colon_0: diag(5057, ts.DiagnosticCategory.Error, "Cannot_find_a_tsconfig_json_file_at_the_specified_directory_Colon_0_5057", "Cannot find a tsconfig.json file at the specified directory: '{0}'."), + The_specified_path_does_not_exist_Colon_0: diag(5058, ts.DiagnosticCategory.Error, "The_specified_path_does_not_exist_Colon_0_5058", "The specified path does not exist: '{0}'."), + Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier: diag(5059, ts.DiagnosticCategory.Error, "Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier_5059", "Invalid value for '--reactNamespace'. '{0}' is not a valid identifier."), + Option_paths_cannot_be_used_without_specifying_baseUrl_option: diag(5060, ts.DiagnosticCategory.Error, "Option_paths_cannot_be_used_without_specifying_baseUrl_option_5060", "Option 'paths' cannot be used without specifying '--baseUrl' option."), + Pattern_0_can_have_at_most_one_Asterisk_character: diag(5061, ts.DiagnosticCategory.Error, "Pattern_0_can_have_at_most_one_Asterisk_character_5061", "Pattern '{0}' can have at most one '*' character."), + Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character: diag(5062, ts.DiagnosticCategory.Error, "Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character_5062", "Substitution '{0}' in pattern '{1}' in can have at most one '*' character."), + Substitutions_for_pattern_0_should_be_an_array: diag(5063, ts.DiagnosticCategory.Error, "Substitutions_for_pattern_0_should_be_an_array_5063", "Substitutions for pattern '{0}' should be an array."), + Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2: diag(5064, ts.DiagnosticCategory.Error, "Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2_5064", "Substitution '{0}' for pattern '{1}' has incorrect type, expected 'string', got '{2}'."), + File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: diag(5065, ts.DiagnosticCategory.Error, "File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildca_5065", "File specification cannot contain a parent directory ('..') that appears after a recursive directory wildcard ('**'): '{0}'."), + Substitutions_for_pattern_0_shouldn_t_be_an_empty_array: diag(5066, ts.DiagnosticCategory.Error, "Substitutions_for_pattern_0_shouldn_t_be_an_empty_array_5066", "Substitutions for pattern '{0}' shouldn't be an empty array."), + Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name: diag(5067, ts.DiagnosticCategory.Error, "Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name_5067", "Invalid value for 'jsxFactory'. '{0}' is not a valid identifier or qualified-name."), + Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig: diag(5068, ts.DiagnosticCategory.Error, "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068", "Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig."), + Option_0_cannot_be_specified_without_specifying_option_1_or_option_2: diag(5069, ts.DiagnosticCategory.Error, "Option_0_cannot_be_specified_without_specifying_option_1_or_option_2_5069", "Option '{0}' cannot be specified without specifying option '{1}' or option '{2}'."), + Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy: diag(5070, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070", "Option '--resolveJsonModule' cannot be specified without 'node' module resolution strategy."), + Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_esNext: diag(5071, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_5071", "Option '--resolveJsonModule' can only be specified when module code generation is 'commonjs', 'amd', 'es2015' or 'esNext'."), + Unknown_build_option_0: diag(5072, ts.DiagnosticCategory.Error, "Unknown_build_option_0_5072", "Unknown build option '{0}'."), + Build_option_0_requires_a_value_of_type_1: diag(5073, ts.DiagnosticCategory.Error, "Build_option_0_requires_a_value_of_type_1_5073", "Build option '{0}' requires a value of type {1}."), + Generates_a_sourcemap_for_each_corresponding_d_ts_file: diag(6000, ts.DiagnosticCategory.Message, "Generates_a_sourcemap_for_each_corresponding_d_ts_file_6000", "Generates a sourcemap for each corresponding '.d.ts' file."), + Concatenate_and_emit_output_to_single_file: diag(6001, ts.DiagnosticCategory.Message, "Concatenate_and_emit_output_to_single_file_6001", "Concatenate and emit output to single file."), + Generates_corresponding_d_ts_file: diag(6002, ts.DiagnosticCategory.Message, "Generates_corresponding_d_ts_file_6002", "Generates corresponding '.d.ts' file."), + Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations: diag(6003, ts.DiagnosticCategory.Message, "Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations_6003", "Specify the location where debugger should locate map files instead of generated locations."), + Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations: diag(6004, ts.DiagnosticCategory.Message, "Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations_6004", "Specify the location where debugger should locate TypeScript files instead of source locations."), + Watch_input_files: diag(6005, ts.DiagnosticCategory.Message, "Watch_input_files_6005", "Watch input files."), + Redirect_output_structure_to_the_directory: diag(6006, ts.DiagnosticCategory.Message, "Redirect_output_structure_to_the_directory_6006", "Redirect output structure to the directory."), + Do_not_erase_const_enum_declarations_in_generated_code: diag(6007, ts.DiagnosticCategory.Message, "Do_not_erase_const_enum_declarations_in_generated_code_6007", "Do not erase const enum declarations in generated code."), + Do_not_emit_outputs_if_any_errors_were_reported: diag(6008, ts.DiagnosticCategory.Message, "Do_not_emit_outputs_if_any_errors_were_reported_6008", "Do not emit outputs if any errors were reported."), + Do_not_emit_comments_to_output: diag(6009, ts.DiagnosticCategory.Message, "Do_not_emit_comments_to_output_6009", "Do not emit comments to output."), + Do_not_emit_outputs: diag(6010, ts.DiagnosticCategory.Message, "Do_not_emit_outputs_6010", "Do not emit outputs."), + Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking: diag(6011, ts.DiagnosticCategory.Message, "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011", "Allow default imports from modules with no default export. This does not affect code emit, just typechecking."), + Skip_type_checking_of_declaration_files: diag(6012, ts.DiagnosticCategory.Message, "Skip_type_checking_of_declaration_files_6012", "Skip type checking of declaration files."), + Do_not_resolve_the_real_path_of_symlinks: diag(6013, ts.DiagnosticCategory.Message, "Do_not_resolve_the_real_path_of_symlinks_6013", "Do not resolve the real path of symlinks."), + Only_emit_d_ts_declaration_files: diag(6014, ts.DiagnosticCategory.Message, "Only_emit_d_ts_declaration_files_6014", "Only emit '.d.ts' declaration files."), + Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_or_ESNEXT: diag(6015, ts.DiagnosticCategory.Message, "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_or_ESNEXT_6015", "Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'."), + Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext: diag(6016, ts.DiagnosticCategory.Message, "Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext_6016", "Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'."), + Print_this_message: diag(6017, ts.DiagnosticCategory.Message, "Print_this_message_6017", "Print this message."), + Print_the_compiler_s_version: diag(6019, ts.DiagnosticCategory.Message, "Print_the_compiler_s_version_6019", "Print the compiler's version."), + Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json: diag(6020, ts.DiagnosticCategory.Message, "Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json_6020", "Compile the project given the path to its configuration file, or to a folder with a 'tsconfig.json'."), + Syntax_Colon_0: diag(6023, ts.DiagnosticCategory.Message, "Syntax_Colon_0_6023", "Syntax: {0}"), + options: diag(6024, ts.DiagnosticCategory.Message, "options_6024", "options"), + file: diag(6025, ts.DiagnosticCategory.Message, "file_6025", "file"), + Examples_Colon_0: diag(6026, ts.DiagnosticCategory.Message, "Examples_Colon_0_6026", "Examples: {0}"), + Options_Colon: diag(6027, ts.DiagnosticCategory.Message, "Options_Colon_6027", "Options:"), + Version_0: diag(6029, ts.DiagnosticCategory.Message, "Version_0_6029", "Version {0}"), + Insert_command_line_options_and_files_from_a_file: diag(6030, ts.DiagnosticCategory.Message, "Insert_command_line_options_and_files_from_a_file_6030", "Insert command line options and files from a file."), + Starting_compilation_in_watch_mode: diag(6031, ts.DiagnosticCategory.Message, "Starting_compilation_in_watch_mode_6031", "Starting compilation in watch mode..."), + File_change_detected_Starting_incremental_compilation: diag(6032, ts.DiagnosticCategory.Message, "File_change_detected_Starting_incremental_compilation_6032", "File change detected. Starting incremental compilation..."), + KIND: diag(6034, ts.DiagnosticCategory.Message, "KIND_6034", "KIND"), + FILE: diag(6035, ts.DiagnosticCategory.Message, "FILE_6035", "FILE"), + VERSION: diag(6036, ts.DiagnosticCategory.Message, "VERSION_6036", "VERSION"), + LOCATION: diag(6037, ts.DiagnosticCategory.Message, "LOCATION_6037", "LOCATION"), + DIRECTORY: diag(6038, ts.DiagnosticCategory.Message, "DIRECTORY_6038", "DIRECTORY"), + STRATEGY: diag(6039, ts.DiagnosticCategory.Message, "STRATEGY_6039", "STRATEGY"), + FILE_OR_DIRECTORY: diag(6040, ts.DiagnosticCategory.Message, "FILE_OR_DIRECTORY_6040", "FILE OR DIRECTORY"), + Generates_corresponding_map_file: diag(6043, ts.DiagnosticCategory.Message, "Generates_corresponding_map_file_6043", "Generates corresponding '.map' file."), + Compiler_option_0_expects_an_argument: diag(6044, ts.DiagnosticCategory.Error, "Compiler_option_0_expects_an_argument_6044", "Compiler option '{0}' expects an argument."), + Unterminated_quoted_string_in_response_file_0: diag(6045, ts.DiagnosticCategory.Error, "Unterminated_quoted_string_in_response_file_0_6045", "Unterminated quoted string in response file '{0}'."), + Argument_for_0_option_must_be_Colon_1: diag(6046, ts.DiagnosticCategory.Error, "Argument_for_0_option_must_be_Colon_1_6046", "Argument for '{0}' option must be: {1}."), + Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1: diag(6048, ts.DiagnosticCategory.Error, "Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1_6048", "Locale must be of the form or -. For example '{0}' or '{1}'."), + Unsupported_locale_0: diag(6049, ts.DiagnosticCategory.Error, "Unsupported_locale_0_6049", "Unsupported locale '{0}'."), + Unable_to_open_file_0: diag(6050, ts.DiagnosticCategory.Error, "Unable_to_open_file_0_6050", "Unable to open file '{0}'."), + Corrupted_locale_file_0: diag(6051, ts.DiagnosticCategory.Error, "Corrupted_locale_file_0_6051", "Corrupted locale file {0}."), + Raise_error_on_expressions_and_declarations_with_an_implied_any_type: diag(6052, ts.DiagnosticCategory.Message, "Raise_error_on_expressions_and_declarations_with_an_implied_any_type_6052", "Raise error on expressions and declarations with an implied 'any' type."), + File_0_not_found: diag(6053, ts.DiagnosticCategory.Error, "File_0_not_found_6053", "File '{0}' not found."), + File_0_has_unsupported_extension_The_only_supported_extensions_are_1: diag(6054, ts.DiagnosticCategory.Error, "File_0_has_unsupported_extension_The_only_supported_extensions_are_1_6054", "File '{0}' has unsupported extension. The only supported extensions are {1}."), + Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures: diag(6055, ts.DiagnosticCategory.Message, "Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures_6055", "Suppress noImplicitAny errors for indexing objects lacking index signatures."), + Do_not_emit_declarations_for_code_that_has_an_internal_annotation: diag(6056, ts.DiagnosticCategory.Message, "Do_not_emit_declarations_for_code_that_has_an_internal_annotation_6056", "Do not emit declarations for code that has an '@internal' annotation."), + Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir: diag(6058, ts.DiagnosticCategory.Message, "Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir_6058", "Specify the root directory of input files. Use to control the output directory structure with --outDir."), + File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files: diag(6059, ts.DiagnosticCategory.Error, "File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files_6059", "File '{0}' is not under 'rootDir' '{1}'. 'rootDir' is expected to contain all source files."), + Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix: diag(6060, ts.DiagnosticCategory.Message, "Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix_6060", "Specify the end of line sequence to be used when emitting files: 'CRLF' (dos) or 'LF' (unix)."), + NEWLINE: diag(6061, ts.DiagnosticCategory.Message, "NEWLINE_6061", "NEWLINE"), + Option_0_can_only_be_specified_in_tsconfig_json_file: diag(6064, ts.DiagnosticCategory.Error, "Option_0_can_only_be_specified_in_tsconfig_json_file_6064", "Option '{0}' can only be specified in 'tsconfig.json' file."), + Enables_experimental_support_for_ES7_decorators: diag(6065, ts.DiagnosticCategory.Message, "Enables_experimental_support_for_ES7_decorators_6065", "Enables experimental support for ES7 decorators."), + Enables_experimental_support_for_emitting_type_metadata_for_decorators: diag(6066, ts.DiagnosticCategory.Message, "Enables_experimental_support_for_emitting_type_metadata_for_decorators_6066", "Enables experimental support for emitting type metadata for decorators."), + Enables_experimental_support_for_ES7_async_functions: diag(6068, ts.DiagnosticCategory.Message, "Enables_experimental_support_for_ES7_async_functions_6068", "Enables experimental support for ES7 async functions."), + Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6: diag(6069, ts.DiagnosticCategory.Message, "Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6_6069", "Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6)."), + Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file: diag(6070, ts.DiagnosticCategory.Message, "Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file_6070", "Initializes a TypeScript project and creates a tsconfig.json file."), + Successfully_created_a_tsconfig_json_file: diag(6071, ts.DiagnosticCategory.Message, "Successfully_created_a_tsconfig_json_file_6071", "Successfully created a tsconfig.json file."), + Suppress_excess_property_checks_for_object_literals: diag(6072, ts.DiagnosticCategory.Message, "Suppress_excess_property_checks_for_object_literals_6072", "Suppress excess property checks for object literals."), + Stylize_errors_and_messages_using_color_and_context_experimental: diag(6073, ts.DiagnosticCategory.Message, "Stylize_errors_and_messages_using_color_and_context_experimental_6073", "Stylize errors and messages using color and context (experimental)."), + Do_not_report_errors_on_unused_labels: diag(6074, ts.DiagnosticCategory.Message, "Do_not_report_errors_on_unused_labels_6074", "Do not report errors on unused labels."), + Report_error_when_not_all_code_paths_in_function_return_a_value: diag(6075, ts.DiagnosticCategory.Message, "Report_error_when_not_all_code_paths_in_function_return_a_value_6075", "Report error when not all code paths in function return a value."), + Report_errors_for_fallthrough_cases_in_switch_statement: diag(6076, ts.DiagnosticCategory.Message, "Report_errors_for_fallthrough_cases_in_switch_statement_6076", "Report errors for fallthrough cases in switch statement."), + Do_not_report_errors_on_unreachable_code: diag(6077, ts.DiagnosticCategory.Message, "Do_not_report_errors_on_unreachable_code_6077", "Do not report errors on unreachable code."), + Disallow_inconsistently_cased_references_to_the_same_file: diag(6078, ts.DiagnosticCategory.Message, "Disallow_inconsistently_cased_references_to_the_same_file_6078", "Disallow inconsistently-cased references to the same file."), + Specify_library_files_to_be_included_in_the_compilation: diag(6079, ts.DiagnosticCategory.Message, "Specify_library_files_to_be_included_in_the_compilation_6079", "Specify library files to be included in the compilation."), + Specify_JSX_code_generation_Colon_preserve_react_native_or_react: diag(6080, ts.DiagnosticCategory.Message, "Specify_JSX_code_generation_Colon_preserve_react_native_or_react_6080", "Specify JSX code generation: 'preserve', 'react-native', or 'react'."), + File_0_has_an_unsupported_extension_so_skipping_it: diag(6081, ts.DiagnosticCategory.Message, "File_0_has_an_unsupported_extension_so_skipping_it_6081", "File '{0}' has an unsupported extension, so skipping it."), + Only_amd_and_system_modules_are_supported_alongside_0: diag(6082, ts.DiagnosticCategory.Error, "Only_amd_and_system_modules_are_supported_alongside_0_6082", "Only 'amd' and 'system' modules are supported alongside --{0}."), + Base_directory_to_resolve_non_absolute_module_names: diag(6083, ts.DiagnosticCategory.Message, "Base_directory_to_resolve_non_absolute_module_names_6083", "Base directory to resolve non-absolute module names."), + Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react_JSX_emit: diag(6084, ts.DiagnosticCategory.Message, "Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react__6084", "[Deprecated] Use '--jsxFactory' instead. Specify the object invoked for createElement when targeting 'react' JSX emit"), + Enable_tracing_of_the_name_resolution_process: diag(6085, ts.DiagnosticCategory.Message, "Enable_tracing_of_the_name_resolution_process_6085", "Enable tracing of the name resolution process."), + Resolving_module_0_from_1: diag(6086, ts.DiagnosticCategory.Message, "Resolving_module_0_from_1_6086", "======== Resolving module '{0}' from '{1}'. ========"), + Explicitly_specified_module_resolution_kind_Colon_0: diag(6087, ts.DiagnosticCategory.Message, "Explicitly_specified_module_resolution_kind_Colon_0_6087", "Explicitly specified module resolution kind: '{0}'."), + Module_resolution_kind_is_not_specified_using_0: diag(6088, ts.DiagnosticCategory.Message, "Module_resolution_kind_is_not_specified_using_0_6088", "Module resolution kind is not specified, using '{0}'."), + Module_name_0_was_successfully_resolved_to_1: diag(6089, ts.DiagnosticCategory.Message, "Module_name_0_was_successfully_resolved_to_1_6089", "======== Module name '{0}' was successfully resolved to '{1}'. ========"), + Module_name_0_was_not_resolved: diag(6090, ts.DiagnosticCategory.Message, "Module_name_0_was_not_resolved_6090", "======== Module name '{0}' was not resolved. ========"), + paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0: diag(6091, ts.DiagnosticCategory.Message, "paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0_6091", "'paths' option is specified, looking for a pattern to match module name '{0}'."), + Module_name_0_matched_pattern_1: diag(6092, ts.DiagnosticCategory.Message, "Module_name_0_matched_pattern_1_6092", "Module name '{0}', matched pattern '{1}'."), + Trying_substitution_0_candidate_module_location_Colon_1: diag(6093, ts.DiagnosticCategory.Message, "Trying_substitution_0_candidate_module_location_Colon_1_6093", "Trying substitution '{0}', candidate module location: '{1}'."), + Resolving_module_name_0_relative_to_base_url_1_2: diag(6094, ts.DiagnosticCategory.Message, "Resolving_module_name_0_relative_to_base_url_1_2_6094", "Resolving module name '{0}' relative to base url '{1}' - '{2}'."), + Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1: diag(6095, ts.DiagnosticCategory.Message, "Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1_6095", "Loading module as file / folder, candidate module location '{0}', target file type '{1}'."), + File_0_does_not_exist: diag(6096, ts.DiagnosticCategory.Message, "File_0_does_not_exist_6096", "File '{0}' does not exist."), + File_0_exist_use_it_as_a_name_resolution_result: diag(6097, ts.DiagnosticCategory.Message, "File_0_exist_use_it_as_a_name_resolution_result_6097", "File '{0}' exist - use it as a name resolution result."), + Loading_module_0_from_node_modules_folder_target_file_type_1: diag(6098, ts.DiagnosticCategory.Message, "Loading_module_0_from_node_modules_folder_target_file_type_1_6098", "Loading module '{0}' from 'node_modules' folder, target file type '{1}'."), + Found_package_json_at_0: diag(6099, ts.DiagnosticCategory.Message, "Found_package_json_at_0_6099", "Found 'package.json' at '{0}'."), + package_json_does_not_have_a_0_field: diag(6100, ts.DiagnosticCategory.Message, "package_json_does_not_have_a_0_field_6100", "'package.json' does not have a '{0}' field."), + package_json_has_0_field_1_that_references_2: diag(6101, ts.DiagnosticCategory.Message, "package_json_has_0_field_1_that_references_2_6101", "'package.json' has '{0}' field '{1}' that references '{2}'."), + Allow_javascript_files_to_be_compiled: diag(6102, ts.DiagnosticCategory.Message, "Allow_javascript_files_to_be_compiled_6102", "Allow javascript files to be compiled."), + Option_0_should_have_array_of_strings_as_a_value: diag(6103, ts.DiagnosticCategory.Error, "Option_0_should_have_array_of_strings_as_a_value_6103", "Option '{0}' should have array of strings as a value."), + Checking_if_0_is_the_longest_matching_prefix_for_1_2: diag(6104, ts.DiagnosticCategory.Message, "Checking_if_0_is_the_longest_matching_prefix_for_1_2_6104", "Checking if '{0}' is the longest matching prefix for '{1}' - '{2}'."), + Expected_type_of_0_field_in_package_json_to_be_1_got_2: diag(6105, ts.DiagnosticCategory.Message, "Expected_type_of_0_field_in_package_json_to_be_1_got_2_6105", "Expected type of '{0}' field in 'package.json' to be '{1}', got '{2}'."), + baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1: diag(6106, ts.DiagnosticCategory.Message, "baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1_6106", "'baseUrl' option is set to '{0}', using this value to resolve non-relative module name '{1}'."), + rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0: diag(6107, ts.DiagnosticCategory.Message, "rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107", "'rootDirs' option is set, using it to resolve relative module name '{0}'."), + Longest_matching_prefix_for_0_is_1: diag(6108, ts.DiagnosticCategory.Message, "Longest_matching_prefix_for_0_is_1_6108", "Longest matching prefix for '{0}' is '{1}'."), + Loading_0_from_the_root_dir_1_candidate_location_2: diag(6109, ts.DiagnosticCategory.Message, "Loading_0_from_the_root_dir_1_candidate_location_2_6109", "Loading '{0}' from the root dir '{1}', candidate location '{2}'."), + Trying_other_entries_in_rootDirs: diag(6110, ts.DiagnosticCategory.Message, "Trying_other_entries_in_rootDirs_6110", "Trying other entries in 'rootDirs'."), + Module_resolution_using_rootDirs_has_failed: diag(6111, ts.DiagnosticCategory.Message, "Module_resolution_using_rootDirs_has_failed_6111", "Module resolution using 'rootDirs' has failed."), + Do_not_emit_use_strict_directives_in_module_output: diag(6112, ts.DiagnosticCategory.Message, "Do_not_emit_use_strict_directives_in_module_output_6112", "Do not emit 'use strict' directives in module output."), + Enable_strict_null_checks: diag(6113, ts.DiagnosticCategory.Message, "Enable_strict_null_checks_6113", "Enable strict null checks."), + Unknown_option_excludes_Did_you_mean_exclude: diag(6114, ts.DiagnosticCategory.Error, "Unknown_option_excludes_Did_you_mean_exclude_6114", "Unknown option 'excludes'. Did you mean 'exclude'?"), + Raise_error_on_this_expressions_with_an_implied_any_type: diag(6115, ts.DiagnosticCategory.Message, "Raise_error_on_this_expressions_with_an_implied_any_type_6115", "Raise error on 'this' expressions with an implied 'any' type."), + Resolving_type_reference_directive_0_containing_file_1_root_directory_2: diag(6116, ts.DiagnosticCategory.Message, "Resolving_type_reference_directive_0_containing_file_1_root_directory_2_6116", "======== Resolving type reference directive '{0}', containing file '{1}', root directory '{2}'. ========"), + Resolving_using_primary_search_paths: diag(6117, ts.DiagnosticCategory.Message, "Resolving_using_primary_search_paths_6117", "Resolving using primary search paths..."), + Resolving_from_node_modules_folder: diag(6118, ts.DiagnosticCategory.Message, "Resolving_from_node_modules_folder_6118", "Resolving from node_modules folder..."), + Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2: diag(6119, ts.DiagnosticCategory.Message, "Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2_6119", "======== Type reference directive '{0}' was successfully resolved to '{1}', primary: {2}. ========"), + Type_reference_directive_0_was_not_resolved: diag(6120, ts.DiagnosticCategory.Message, "Type_reference_directive_0_was_not_resolved_6120", "======== Type reference directive '{0}' was not resolved. ========"), + Resolving_with_primary_search_path_0: diag(6121, ts.DiagnosticCategory.Message, "Resolving_with_primary_search_path_0_6121", "Resolving with primary search path '{0}'."), + Root_directory_cannot_be_determined_skipping_primary_search_paths: diag(6122, ts.DiagnosticCategory.Message, "Root_directory_cannot_be_determined_skipping_primary_search_paths_6122", "Root directory cannot be determined, skipping primary search paths."), + Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set: diag(6123, ts.DiagnosticCategory.Message, "Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set_6123", "======== Resolving type reference directive '{0}', containing file '{1}', root directory not set. ========"), + Type_declaration_files_to_be_included_in_compilation: diag(6124, ts.DiagnosticCategory.Message, "Type_declaration_files_to_be_included_in_compilation_6124", "Type declaration files to be included in compilation."), + Looking_up_in_node_modules_folder_initial_location_0: diag(6125, ts.DiagnosticCategory.Message, "Looking_up_in_node_modules_folder_initial_location_0_6125", "Looking up in 'node_modules' folder, initial location '{0}'."), + Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder: diag(6126, ts.DiagnosticCategory.Message, "Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126", "Containing file is not specified and root directory cannot be determined, skipping lookup in 'node_modules' folder."), + Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1: diag(6127, ts.DiagnosticCategory.Message, "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1_6127", "======== Resolving type reference directive '{0}', containing file not set, root directory '{1}'. ========"), + Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set: diag(6128, ts.DiagnosticCategory.Message, "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set_6128", "======== Resolving type reference directive '{0}', containing file not set, root directory not set. ========"), + Resolving_real_path_for_0_result_1: diag(6130, ts.DiagnosticCategory.Message, "Resolving_real_path_for_0_result_1_6130", "Resolving real path for '{0}', result '{1}'."), + Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system: diag(6131, ts.DiagnosticCategory.Error, "Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system_6131", "Cannot compile modules using option '{0}' unless the '--module' flag is 'amd' or 'system'."), + File_name_0_has_a_1_extension_stripping_it: diag(6132, ts.DiagnosticCategory.Message, "File_name_0_has_a_1_extension_stripping_it_6132", "File name '{0}' has a '{1}' extension - stripping it."), + _0_is_declared_but_its_value_is_never_read: diag(6133, ts.DiagnosticCategory.Error, "_0_is_declared_but_its_value_is_never_read_6133", "'{0}' is declared but its value is never read.", true), + Report_errors_on_unused_locals: diag(6134, ts.DiagnosticCategory.Message, "Report_errors_on_unused_locals_6134", "Report errors on unused locals."), + Report_errors_on_unused_parameters: diag(6135, ts.DiagnosticCategory.Message, "Report_errors_on_unused_parameters_6135", "Report errors on unused parameters."), + The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files: diag(6136, ts.DiagnosticCategory.Message, "The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files_6136", "The maximum dependency depth to search under node_modules and load JavaScript files."), + Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1: diag(6137, ts.DiagnosticCategory.Error, "Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1_6137", "Cannot import type declaration files. Consider importing '{0}' instead of '{1}'."), + Property_0_is_declared_but_its_value_is_never_read: diag(6138, ts.DiagnosticCategory.Error, "Property_0_is_declared_but_its_value_is_never_read_6138", "Property '{0}' is declared but its value is never read.", true), + Import_emit_helpers_from_tslib: diag(6139, ts.DiagnosticCategory.Message, "Import_emit_helpers_from_tslib_6139", "Import emit helpers from 'tslib'."), + Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2: diag(6140, ts.DiagnosticCategory.Error, "Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using__6140", "Auto discovery for typings is enabled in project '{0}'. Running extra resolution pass for module '{1}' using cache location '{2}'."), + Parse_in_strict_mode_and_emit_use_strict_for_each_source_file: diag(6141, ts.DiagnosticCategory.Message, "Parse_in_strict_mode_and_emit_use_strict_for_each_source_file_6141", "Parse in strict mode and emit \"use strict\" for each source file."), + Module_0_was_resolved_to_1_but_jsx_is_not_set: diag(6142, ts.DiagnosticCategory.Error, "Module_0_was_resolved_to_1_but_jsx_is_not_set_6142", "Module '{0}' was resolved to '{1}', but '--jsx' is not set."), + Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1: diag(6144, ts.DiagnosticCategory.Message, "Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1_6144", "Module '{0}' was resolved as locally declared ambient module in file '{1}'."), + Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified: diag(6145, ts.DiagnosticCategory.Message, "Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified_6145", "Module '{0}' was resolved as ambient module declared in '{1}' since this file was not modified."), + Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h: diag(6146, ts.DiagnosticCategory.Message, "Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h_6146", "Specify the JSX factory function to use when targeting 'react' JSX emit, e.g. 'React.createElement' or 'h'."), + Resolution_for_module_0_was_found_in_cache_from_location_1: diag(6147, ts.DiagnosticCategory.Message, "Resolution_for_module_0_was_found_in_cache_from_location_1_6147", "Resolution for module '{0}' was found in cache from location '{1}'."), + Directory_0_does_not_exist_skipping_all_lookups_in_it: diag(6148, ts.DiagnosticCategory.Message, "Directory_0_does_not_exist_skipping_all_lookups_in_it_6148", "Directory '{0}' does not exist, skipping all lookups in it."), + Show_diagnostic_information: diag(6149, ts.DiagnosticCategory.Message, "Show_diagnostic_information_6149", "Show diagnostic information."), + Show_verbose_diagnostic_information: diag(6150, ts.DiagnosticCategory.Message, "Show_verbose_diagnostic_information_6150", "Show verbose diagnostic information."), + Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file: diag(6151, ts.DiagnosticCategory.Message, "Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file_6151", "Emit a single file with source maps instead of having a separate file."), + Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap_to_be_set: diag(6152, ts.DiagnosticCategory.Message, "Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap__6152", "Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set."), + Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule: diag(6153, ts.DiagnosticCategory.Message, "Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule_6153", "Transpile each file as a separate module (similar to 'ts.transpileModule')."), + Print_names_of_generated_files_part_of_the_compilation: diag(6154, ts.DiagnosticCategory.Message, "Print_names_of_generated_files_part_of_the_compilation_6154", "Print names of generated files part of the compilation."), + Print_names_of_files_part_of_the_compilation: diag(6155, ts.DiagnosticCategory.Message, "Print_names_of_files_part_of_the_compilation_6155", "Print names of files part of the compilation."), + The_locale_used_when_displaying_messages_to_the_user_e_g_en_us: diag(6156, ts.DiagnosticCategory.Message, "The_locale_used_when_displaying_messages_to_the_user_e_g_en_us_6156", "The locale used when displaying messages to the user (e.g. 'en-us')"), + Do_not_generate_custom_helper_functions_like_extends_in_compiled_output: diag(6157, ts.DiagnosticCategory.Message, "Do_not_generate_custom_helper_functions_like_extends_in_compiled_output_6157", "Do not generate custom helper functions like '__extends' in compiled output."), + Do_not_include_the_default_library_file_lib_d_ts: diag(6158, ts.DiagnosticCategory.Message, "Do_not_include_the_default_library_file_lib_d_ts_6158", "Do not include the default library file (lib.d.ts)."), + Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files: diag(6159, ts.DiagnosticCategory.Message, "Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files_6159", "Do not add triple-slash references or imported modules to the list of compiled files."), + Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files: diag(6160, ts.DiagnosticCategory.Message, "Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files_6160", "[Deprecated] Use '--skipLibCheck' instead. Skip type checking of default library declaration files."), + List_of_folders_to_include_type_definitions_from: diag(6161, ts.DiagnosticCategory.Message, "List_of_folders_to_include_type_definitions_from_6161", "List of folders to include type definitions from."), + Disable_size_limitations_on_JavaScript_projects: diag(6162, ts.DiagnosticCategory.Message, "Disable_size_limitations_on_JavaScript_projects_6162", "Disable size limitations on JavaScript projects."), + The_character_set_of_the_input_files: diag(6163, ts.DiagnosticCategory.Message, "The_character_set_of_the_input_files_6163", "The character set of the input files."), + Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files: diag(6164, ts.DiagnosticCategory.Message, "Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files_6164", "Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files."), + Do_not_truncate_error_messages: diag(6165, ts.DiagnosticCategory.Message, "Do_not_truncate_error_messages_6165", "Do not truncate error messages."), + Output_directory_for_generated_declaration_files: diag(6166, ts.DiagnosticCategory.Message, "Output_directory_for_generated_declaration_files_6166", "Output directory for generated declaration files."), + A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl: diag(6167, ts.DiagnosticCategory.Message, "A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl_6167", "A series of entries which re-map imports to lookup locations relative to the 'baseUrl'."), + List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime: diag(6168, ts.DiagnosticCategory.Message, "List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime_6168", "List of root folders whose combined content represents the structure of the project at runtime."), + Show_all_compiler_options: diag(6169, ts.DiagnosticCategory.Message, "Show_all_compiler_options_6169", "Show all compiler options."), + Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file: diag(6170, ts.DiagnosticCategory.Message, "Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file_6170", "[Deprecated] Use '--outFile' instead. Concatenate and emit output to single file"), + Command_line_Options: diag(6171, ts.DiagnosticCategory.Message, "Command_line_Options_6171", "Command-line Options"), + Basic_Options: diag(6172, ts.DiagnosticCategory.Message, "Basic_Options_6172", "Basic Options"), + Strict_Type_Checking_Options: diag(6173, ts.DiagnosticCategory.Message, "Strict_Type_Checking_Options_6173", "Strict Type-Checking Options"), + Module_Resolution_Options: diag(6174, ts.DiagnosticCategory.Message, "Module_Resolution_Options_6174", "Module Resolution Options"), + Source_Map_Options: diag(6175, ts.DiagnosticCategory.Message, "Source_Map_Options_6175", "Source Map Options"), + Additional_Checks: diag(6176, ts.DiagnosticCategory.Message, "Additional_Checks_6176", "Additional Checks"), + Experimental_Options: diag(6177, ts.DiagnosticCategory.Message, "Experimental_Options_6177", "Experimental Options"), + Advanced_Options: diag(6178, ts.DiagnosticCategory.Message, "Advanced_Options_6178", "Advanced Options"), + Provide_full_support_for_iterables_in_for_of_spread_and_destructuring_when_targeting_ES5_or_ES3: diag(6179, ts.DiagnosticCategory.Message, "Provide_full_support_for_iterables_in_for_of_spread_and_destructuring_when_targeting_ES5_or_ES3_6179", "Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'."), + Enable_all_strict_type_checking_options: diag(6180, ts.DiagnosticCategory.Message, "Enable_all_strict_type_checking_options_6180", "Enable all strict type-checking options."), + List_of_language_service_plugins: diag(6181, ts.DiagnosticCategory.Message, "List_of_language_service_plugins_6181", "List of language service plugins."), + Scoped_package_detected_looking_in_0: diag(6182, ts.DiagnosticCategory.Message, "Scoped_package_detected_looking_in_0_6182", "Scoped package detected, looking in '{0}'"), + Reusing_resolution_of_module_0_to_file_1_from_old_program: diag(6183, ts.DiagnosticCategory.Message, "Reusing_resolution_of_module_0_to_file_1_from_old_program_6183", "Reusing resolution of module '{0}' to file '{1}' from old program."), + Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program: diag(6184, ts.DiagnosticCategory.Message, "Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program_6184", "Reusing module resolutions originating in '{0}' since resolutions are unchanged from old program."), + Disable_strict_checking_of_generic_signatures_in_function_types: diag(6185, ts.DiagnosticCategory.Message, "Disable_strict_checking_of_generic_signatures_in_function_types_6185", "Disable strict checking of generic signatures in function types."), + Enable_strict_checking_of_function_types: diag(6186, ts.DiagnosticCategory.Message, "Enable_strict_checking_of_function_types_6186", "Enable strict checking of function types."), + Enable_strict_checking_of_property_initialization_in_classes: diag(6187, ts.DiagnosticCategory.Message, "Enable_strict_checking_of_property_initialization_in_classes_6187", "Enable strict checking of property initialization in classes."), + Numeric_separators_are_not_allowed_here: diag(6188, ts.DiagnosticCategory.Error, "Numeric_separators_are_not_allowed_here_6188", "Numeric separators are not allowed here."), + Multiple_consecutive_numeric_separators_are_not_permitted: diag(6189, ts.DiagnosticCategory.Error, "Multiple_consecutive_numeric_separators_are_not_permitted_6189", "Multiple consecutive numeric separators are not permitted."), + Found_package_json_at_0_Package_ID_is_1: diag(6190, ts.DiagnosticCategory.Message, "Found_package_json_at_0_Package_ID_is_1_6190", "Found 'package.json' at '{0}'. Package ID is '{1}'."), + Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen: diag(6191, ts.DiagnosticCategory.Message, "Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen_6191", "Whether to keep outdated console output in watch mode instead of clearing the screen."), + All_imports_in_import_declaration_are_unused: diag(6192, ts.DiagnosticCategory.Error, "All_imports_in_import_declaration_are_unused_6192", "All imports in import declaration are unused.", true), + Found_1_error_Watching_for_file_changes: diag(6193, ts.DiagnosticCategory.Message, "Found_1_error_Watching_for_file_changes_6193", "Found 1 error. Watching for file changes."), + Found_0_errors_Watching_for_file_changes: diag(6194, ts.DiagnosticCategory.Message, "Found_0_errors_Watching_for_file_changes_6194", "Found {0} errors. Watching for file changes."), + Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols: diag(6195, ts.DiagnosticCategory.Message, "Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols_6195", "Resolve 'keyof' to string valued property names only (no numbers or symbols)."), + _0_is_declared_but_never_used: diag(6196, ts.DiagnosticCategory.Error, "_0_is_declared_but_never_used_6196", "'{0}' is declared but never used.", true), + Include_modules_imported_with_json_extension: diag(6197, ts.DiagnosticCategory.Message, "Include_modules_imported_with_json_extension_6197", "Include modules imported with '.json' extension"), + All_destructured_elements_are_unused: diag(6198, ts.DiagnosticCategory.Error, "All_destructured_elements_are_unused_6198", "All destructured elements are unused.", true), + All_variables_are_unused: diag(6199, ts.DiagnosticCategory.Error, "All_variables_are_unused_6199", "All variables are unused.", true), + Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0: diag(6200, ts.DiagnosticCategory.Error, "Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0_6200", "Definitions of the following identifiers conflict with those in another file: {0}"), + Conflicts_are_in_this_file: diag(6201, ts.DiagnosticCategory.Message, "Conflicts_are_in_this_file_6201", "Conflicts are in this file."), + _0_was_also_declared_here: diag(6203, ts.DiagnosticCategory.Message, "_0_was_also_declared_here_6203", "'{0}' was also declared here."), + and_here: diag(6204, ts.DiagnosticCategory.Message, "and_here_6204", "and here."), + All_type_parameters_are_unused: diag(6205, ts.DiagnosticCategory.Error, "All_type_parameters_are_unused_6205", "All type parameters are unused"), + package_json_has_a_typesVersions_field_with_version_specific_path_mappings: diag(6206, ts.DiagnosticCategory.Message, "package_json_has_a_typesVersions_field_with_version_specific_path_mappings_6206", "'package.json' has a 'typesVersions' field with version-specific path mappings."), + package_json_does_not_have_a_typesVersions_entry_that_matches_version_0: diag(6207, ts.DiagnosticCategory.Message, "package_json_does_not_have_a_typesVersions_entry_that_matches_version_0_6207", "'package.json' does not have a 'typesVersions' entry that matches version '{0}'."), + package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2: diag(6208, ts.DiagnosticCategory.Message, "package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_ma_6208", "'package.json' has a 'typesVersions' entry '{0}' that matches compiler version '{1}', looking for a pattern to match module name '{2}'."), + package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range: diag(6209, ts.DiagnosticCategory.Message, "package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range_6209", "'package.json' has a 'typesVersions' entry '{0}' that is not a valid semver range."), + An_argument_for_0_was_not_provided: diag(6210, ts.DiagnosticCategory.Message, "An_argument_for_0_was_not_provided_6210", "An argument for '{0}' was not provided."), + An_argument_matching_this_binding_pattern_was_not_provided: diag(6211, ts.DiagnosticCategory.Message, "An_argument_matching_this_binding_pattern_was_not_provided_6211", "An argument matching this binding pattern was not provided."), + Did_you_mean_to_call_this_expression: diag(6212, ts.DiagnosticCategory.Message, "Did_you_mean_to_call_this_expression_6212", "Did you mean to call this expression?"), + Did_you_mean_to_use_new_with_this_expression: diag(6213, ts.DiagnosticCategory.Message, "Did_you_mean_to_use_new_with_this_expression_6213", "Did you mean to use 'new' with this expression?"), + Enable_strict_bind_call_and_apply_methods_on_functions: diag(6214, ts.DiagnosticCategory.Message, "Enable_strict_bind_call_and_apply_methods_on_functions_6214", "Enable strict 'bind', 'call', and 'apply' methods on functions."), + Using_compiler_options_of_project_reference_redirect_0: diag(6215, ts.DiagnosticCategory.Message, "Using_compiler_options_of_project_reference_redirect_0_6215", "Using compiler options of project reference redirect '{0}'."), + Found_1_error: diag(6216, ts.DiagnosticCategory.Message, "Found_1_error_6216", "Found 1 error."), + Found_0_errors: diag(6217, ts.DiagnosticCategory.Message, "Found_0_errors_6217", "Found {0} errors."), + Projects_to_reference: diag(6300, ts.DiagnosticCategory.Message, "Projects_to_reference_6300", "Projects to reference"), + Enable_project_compilation: diag(6302, ts.DiagnosticCategory.Message, "Enable_project_compilation_6302", "Enable project compilation"), + Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0: diag(6202, ts.DiagnosticCategory.Error, "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202", "Project references may not form a circular graph. Cycle detected: {0}"), + Composite_projects_may_not_disable_declaration_emit: diag(6304, ts.DiagnosticCategory.Error, "Composite_projects_may_not_disable_declaration_emit_6304", "Composite projects may not disable declaration emit."), + Output_file_0_has_not_been_built_from_source_file_1: diag(6305, ts.DiagnosticCategory.Error, "Output_file_0_has_not_been_built_from_source_file_1_6305", "Output file '{0}' has not been built from source file '{1}'."), + Referenced_project_0_must_have_setting_composite_Colon_true: diag(6306, ts.DiagnosticCategory.Error, "Referenced_project_0_must_have_setting_composite_Colon_true_6306", "Referenced project '{0}' must have setting \"composite\": true."), + File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern: diag(6307, ts.DiagnosticCategory.Error, "File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern_6307", "File '{0}' is not in project file list. Projects must list all files or use an 'include' pattern."), + Cannot_prepend_project_0_because_it_does_not_have_outFile_set: diag(6308, ts.DiagnosticCategory.Error, "Cannot_prepend_project_0_because_it_does_not_have_outFile_set_6308", "Cannot prepend project '{0}' because it does not have 'outFile' set"), + Output_file_0_from_project_1_does_not_exist: diag(6309, ts.DiagnosticCategory.Error, "Output_file_0_from_project_1_does_not_exist_6309", "Output file '{0}' from project '{1}' does not exist"), + Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2: diag(6350, ts.DiagnosticCategory.Message, "Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2_6350", "Project '{0}' is out of date because oldest output '{1}' is older than newest input '{2}'"), + Project_0_is_up_to_date_because_newest_input_1_is_older_than_oldest_output_2: diag(6351, ts.DiagnosticCategory.Message, "Project_0_is_up_to_date_because_newest_input_1_is_older_than_oldest_output_2_6351", "Project '{0}' is up to date because newest input '{1}' is older than oldest output '{2}'"), + Project_0_is_out_of_date_because_output_file_1_does_not_exist: diag(6352, ts.DiagnosticCategory.Message, "Project_0_is_out_of_date_because_output_file_1_does_not_exist_6352", "Project '{0}' is out of date because output file '{1}' does not exist"), + Project_0_is_out_of_date_because_its_dependency_1_is_out_of_date: diag(6353, ts.DiagnosticCategory.Message, "Project_0_is_out_of_date_because_its_dependency_1_is_out_of_date_6353", "Project '{0}' is out of date because its dependency '{1}' is out of date"), + Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies: diag(6354, ts.DiagnosticCategory.Message, "Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies_6354", "Project '{0}' is up to date with .d.ts files from its dependencies"), + Projects_in_this_build_Colon_0: diag(6355, ts.DiagnosticCategory.Message, "Projects_in_this_build_Colon_0_6355", "Projects in this build: {0}"), + A_non_dry_build_would_delete_the_following_files_Colon_0: diag(6356, ts.DiagnosticCategory.Message, "A_non_dry_build_would_delete_the_following_files_Colon_0_6356", "A non-dry build would delete the following files: {0}"), + A_non_dry_build_would_build_project_0: diag(6357, ts.DiagnosticCategory.Message, "A_non_dry_build_would_build_project_0_6357", "A non-dry build would build project '{0}'"), + Building_project_0: diag(6358, ts.DiagnosticCategory.Message, "Building_project_0_6358", "Building project '{0}'..."), + Updating_output_timestamps_of_project_0: diag(6359, ts.DiagnosticCategory.Message, "Updating_output_timestamps_of_project_0_6359", "Updating output timestamps of project '{0}'..."), + delete_this_Project_0_is_up_to_date_because_it_was_previously_built: diag(6360, ts.DiagnosticCategory.Message, "delete_this_Project_0_is_up_to_date_because_it_was_previously_built_6360", "delete this - Project '{0}' is up to date because it was previously built"), + Project_0_is_up_to_date: diag(6361, ts.DiagnosticCategory.Message, "Project_0_is_up_to_date_6361", "Project '{0}' is up to date"), + Skipping_build_of_project_0_because_its_dependency_1_has_errors: diag(6362, ts.DiagnosticCategory.Message, "Skipping_build_of_project_0_because_its_dependency_1_has_errors_6362", "Skipping build of project '{0}' because its dependency '{1}' has errors"), + Project_0_can_t_be_built_because_its_dependency_1_has_errors: diag(6363, ts.DiagnosticCategory.Message, "Project_0_can_t_be_built_because_its_dependency_1_has_errors_6363", "Project '{0}' can't be built because its dependency '{1}' has errors"), + Build_one_or_more_projects_and_their_dependencies_if_out_of_date: diag(6364, ts.DiagnosticCategory.Message, "Build_one_or_more_projects_and_their_dependencies_if_out_of_date_6364", "Build one or more projects and their dependencies, if out of date"), + Delete_the_outputs_of_all_projects: diag(6365, ts.DiagnosticCategory.Message, "Delete_the_outputs_of_all_projects_6365", "Delete the outputs of all projects"), + Enable_verbose_logging: diag(6366, ts.DiagnosticCategory.Message, "Enable_verbose_logging_6366", "Enable verbose logging"), + Show_what_would_be_built_or_deleted_if_specified_with_clean: diag(6367, ts.DiagnosticCategory.Message, "Show_what_would_be_built_or_deleted_if_specified_with_clean_6367", "Show what would be built (or deleted, if specified with '--clean')"), + Build_all_projects_including_those_that_appear_to_be_up_to_date: diag(6368, ts.DiagnosticCategory.Message, "Build_all_projects_including_those_that_appear_to_be_up_to_date_6368", "Build all projects, including those that appear to be up to date"), + Option_build_must_be_the_first_command_line_argument: diag(6369, ts.DiagnosticCategory.Error, "Option_build_must_be_the_first_command_line_argument_6369", "Option '--build' must be the first command line argument."), + Options_0_and_1_cannot_be_combined: diag(6370, ts.DiagnosticCategory.Error, "Options_0_and_1_cannot_be_combined_6370", "Options '{0}' and '{1}' cannot be combined."), + The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1: diag(6500, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1_6500", "The expected type comes from property '{0}' which is declared here on type '{1}'"), + The_expected_type_comes_from_this_index_signature: diag(6501, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_this_index_signature_6501", "The expected type comes from this index signature."), + The_expected_type_comes_from_the_return_type_of_this_signature: diag(6502, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_the_return_type_of_this_signature_6502", "The expected type comes from the return type of this signature."), + Variable_0_implicitly_has_an_1_type: diag(7005, ts.DiagnosticCategory.Error, "Variable_0_implicitly_has_an_1_type_7005", "Variable '{0}' implicitly has an '{1}' type."), + Parameter_0_implicitly_has_an_1_type: diag(7006, ts.DiagnosticCategory.Error, "Parameter_0_implicitly_has_an_1_type_7006", "Parameter '{0}' implicitly has an '{1}' type."), + Member_0_implicitly_has_an_1_type: diag(7008, ts.DiagnosticCategory.Error, "Member_0_implicitly_has_an_1_type_7008", "Member '{0}' implicitly has an '{1}' type."), + new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type: diag(7009, ts.DiagnosticCategory.Error, "new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type_7009", "'new' expression, whose target lacks a construct signature, implicitly has an 'any' type."), + _0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type: diag(7010, ts.DiagnosticCategory.Error, "_0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type_7010", "'{0}', which lacks return-type annotation, implicitly has an '{1}' return type."), + Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type: diag(7011, ts.DiagnosticCategory.Error, "Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type_7011", "Function expression, which lacks return-type annotation, implicitly has an '{0}' return type."), + Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: diag(7013, ts.DiagnosticCategory.Error, "Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7013", "Construct signature, which lacks return-type annotation, implicitly has an 'any' return type."), + Function_type_which_lacks_return_type_annotation_implicitly_has_an_0_return_type: diag(7014, ts.DiagnosticCategory.Error, "Function_type_which_lacks_return_type_annotation_implicitly_has_an_0_return_type_7014", "Function type, which lacks return-type annotation, implicitly has an '{0}' return type."), + Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number: diag(7015, ts.DiagnosticCategory.Error, "Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015", "Element implicitly has an 'any' type because index expression is not of type 'number'."), + Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type: diag(7016, ts.DiagnosticCategory.Error, "Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type_7016", "Could not find a declaration file for module '{0}'. '{1}' implicitly has an 'any' type."), + Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature: diag(7017, ts.DiagnosticCategory.Error, "Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature_7017", "Element implicitly has an 'any' type because type '{0}' has no index signature."), + Object_literal_s_property_0_implicitly_has_an_1_type: diag(7018, ts.DiagnosticCategory.Error, "Object_literal_s_property_0_implicitly_has_an_1_type_7018", "Object literal's property '{0}' implicitly has an '{1}' type."), + Rest_parameter_0_implicitly_has_an_any_type: diag(7019, ts.DiagnosticCategory.Error, "Rest_parameter_0_implicitly_has_an_any_type_7019", "Rest parameter '{0}' implicitly has an 'any[]' type."), + Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: diag(7020, ts.DiagnosticCategory.Error, "Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7020", "Call signature, which lacks return-type annotation, implicitly has an 'any' return type."), + _0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer: diag(7022, ts.DiagnosticCategory.Error, "_0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or__7022", "'{0}' implicitly has type 'any' because it does not have a type annotation and is referenced directly or indirectly in its own initializer."), + _0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions: diag(7023, ts.DiagnosticCategory.Error, "_0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_reference_7023", "'{0}' implicitly has return type 'any' because it does not have a return type annotation and is referenced directly or indirectly in one of its return expressions."), + Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions: diag(7024, ts.DiagnosticCategory.Error, "Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_ref_7024", "Function implicitly has return type 'any' because it does not have a return type annotation and is referenced directly or indirectly in one of its return expressions."), + Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_type: diag(7025, ts.DiagnosticCategory.Error, "Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_typ_7025", "Generator implicitly has type '{0}' because it does not yield any values. Consider supplying a return type."), + JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists: diag(7026, ts.DiagnosticCategory.Error, "JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists_7026", "JSX element implicitly has type 'any' because no interface 'JSX.{0}' exists."), + Unreachable_code_detected: diag(7027, ts.DiagnosticCategory.Error, "Unreachable_code_detected_7027", "Unreachable code detected.", true), + Unused_label: diag(7028, ts.DiagnosticCategory.Error, "Unused_label_7028", "Unused label.", true), + Fallthrough_case_in_switch: diag(7029, ts.DiagnosticCategory.Error, "Fallthrough_case_in_switch_7029", "Fallthrough case in switch."), + Not_all_code_paths_return_a_value: diag(7030, ts.DiagnosticCategory.Error, "Not_all_code_paths_return_a_value_7030", "Not all code paths return a value."), + Binding_element_0_implicitly_has_an_1_type: diag(7031, ts.DiagnosticCategory.Error, "Binding_element_0_implicitly_has_an_1_type_7031", "Binding element '{0}' implicitly has an '{1}' type."), + Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation: diag(7032, ts.DiagnosticCategory.Error, "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032", "Property '{0}' implicitly has type 'any', because its set accessor lacks a parameter type annotation."), + Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation: diag(7033, ts.DiagnosticCategory.Error, "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033", "Property '{0}' implicitly has type 'any', because its get accessor lacks a return type annotation."), + Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined: diag(7034, ts.DiagnosticCategory.Error, "Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined_7034", "Variable '{0}' implicitly has type '{1}' in some locations where its type cannot be determined."), + Try_npm_install_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0: diag(7035, ts.DiagnosticCategory.Error, "Try_npm_install_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_mod_7035", "Try `npm install @types/{1}` if it exists or add a new declaration (.d.ts) file containing `declare module '{0}';`"), + Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0: diag(7036, ts.DiagnosticCategory.Error, "Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036", "Dynamic import's specifier must be of type 'string', but here has type '{0}'."), + Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for_all_imports_Implies_allowSyntheticDefaultImports: diag(7037, ts.DiagnosticCategory.Message, "Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for__7037", "Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'."), + Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_Consider_using_a_default_import_or_import_require_here_instead: diag(7038, ts.DiagnosticCategory.Message, "Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cau_7038", "Type originates at this import. A namespace-style import cannot be called or constructed, and will cause a failure at runtime. Consider using a default import or import require here instead."), + Mapped_object_type_implicitly_has_an_any_template_type: diag(7039, ts.DiagnosticCategory.Error, "Mapped_object_type_implicitly_has_an_any_template_type_7039", "Mapped object type implicitly has an 'any' template type."), + If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1: diag(7040, ts.DiagnosticCategory.Error, "If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_S_7040", "If the '{0}' package actually exposes this module, consider sending a pull request to amend 'https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/{1}`"), + The_containing_arrow_function_captures_the_global_value_of_this_which_implicitly_has_type_any: diag(7041, ts.DiagnosticCategory.Error, "The_containing_arrow_function_captures_the_global_value_of_this_which_implicitly_has_type_any_7041", "The containing arrow function captures the global value of 'this' which implicitly has type 'any'."), + Module_0_was_resolved_to_1_but_resolveJsonModule_is_not_used: diag(7042, ts.DiagnosticCategory.Error, "Module_0_was_resolved_to_1_but_resolveJsonModule_is_not_used_7042", "Module '{0}' was resolved to '{1}', but '--resolveJsonModule' is not used."), + Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage: diag(7043, ts.DiagnosticCategory.Suggestion, "Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7043", "Variable '{0}' implicitly has an '{1}' type, but a better type may be inferred from usage."), + Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage: diag(7044, ts.DiagnosticCategory.Suggestion, "Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7044", "Parameter '{0}' implicitly has an '{1}' type, but a better type may be inferred from usage."), + Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage: diag(7045, ts.DiagnosticCategory.Suggestion, "Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7045", "Member '{0}' implicitly has an '{1}' type, but a better type may be inferred from usage."), + Variable_0_implicitly_has_type_1_in_some_locations_but_a_better_type_may_be_inferred_from_usage: diag(7046, ts.DiagnosticCategory.Suggestion, "Variable_0_implicitly_has_type_1_in_some_locations_but_a_better_type_may_be_inferred_from_usage_7046", "Variable '{0}' implicitly has type '{1}' in some locations, but a better type may be inferred from usage."), + Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage: diag(7047, ts.DiagnosticCategory.Suggestion, "Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage_7047", "Rest parameter '{0}' implicitly has an 'any[]' type, but a better type may be inferred from usage."), + Property_0_implicitly_has_type_any_but_a_better_type_for_its_get_accessor_may_be_inferred_from_usage: diag(7048, ts.DiagnosticCategory.Suggestion, "Property_0_implicitly_has_type_any_but_a_better_type_for_its_get_accessor_may_be_inferred_from_usage_7048", "Property '{0}' implicitly has type 'any', but a better type for its get accessor may be inferred from usage."), + Property_0_implicitly_has_type_any_but_a_better_type_for_its_set_accessor_may_be_inferred_from_usage: diag(7049, ts.DiagnosticCategory.Suggestion, "Property_0_implicitly_has_type_any_but_a_better_type_for_its_set_accessor_may_be_inferred_from_usage_7049", "Property '{0}' implicitly has type 'any', but a better type for its set accessor may be inferred from usage."), + _0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage: diag(7050, ts.DiagnosticCategory.Suggestion, "_0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage_7050", "'{0}' implicitly has an '{1}' return type, but a better type may be inferred from usage."), + Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1: diag(7051, ts.DiagnosticCategory.Error, "Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1_7051", "Parameter has a name but no type. Did you mean '{0}: {1}'?"), + You_cannot_rename_this_element: diag(8000, ts.DiagnosticCategory.Error, "You_cannot_rename_this_element_8000", "You cannot rename this element."), + You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library: diag(8001, ts.DiagnosticCategory.Error, "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001", "You cannot rename elements that are defined in the standard TypeScript library."), + import_can_only_be_used_in_a_ts_file: diag(8002, ts.DiagnosticCategory.Error, "import_can_only_be_used_in_a_ts_file_8002", "'import ... =' can only be used in a .ts file."), + export_can_only_be_used_in_a_ts_file: diag(8003, ts.DiagnosticCategory.Error, "export_can_only_be_used_in_a_ts_file_8003", "'export=' can only be used in a .ts file."), + type_parameter_declarations_can_only_be_used_in_a_ts_file: diag(8004, ts.DiagnosticCategory.Error, "type_parameter_declarations_can_only_be_used_in_a_ts_file_8004", "'type parameter declarations' can only be used in a .ts file."), + implements_clauses_can_only_be_used_in_a_ts_file: diag(8005, ts.DiagnosticCategory.Error, "implements_clauses_can_only_be_used_in_a_ts_file_8005", "'implements clauses' can only be used in a .ts file."), + interface_declarations_can_only_be_used_in_a_ts_file: diag(8006, ts.DiagnosticCategory.Error, "interface_declarations_can_only_be_used_in_a_ts_file_8006", "'interface declarations' can only be used in a .ts file."), + module_declarations_can_only_be_used_in_a_ts_file: diag(8007, ts.DiagnosticCategory.Error, "module_declarations_can_only_be_used_in_a_ts_file_8007", "'module declarations' can only be used in a .ts file."), + type_aliases_can_only_be_used_in_a_ts_file: diag(8008, ts.DiagnosticCategory.Error, "type_aliases_can_only_be_used_in_a_ts_file_8008", "'type aliases' can only be used in a .ts file."), + _0_can_only_be_used_in_a_ts_file: diag(8009, ts.DiagnosticCategory.Error, "_0_can_only_be_used_in_a_ts_file_8009", "'{0}' can only be used in a .ts file."), + types_can_only_be_used_in_a_ts_file: diag(8010, ts.DiagnosticCategory.Error, "types_can_only_be_used_in_a_ts_file_8010", "'types' can only be used in a .ts file."), + type_arguments_can_only_be_used_in_a_ts_file: diag(8011, ts.DiagnosticCategory.Error, "type_arguments_can_only_be_used_in_a_ts_file_8011", "'type arguments' can only be used in a .ts file."), + parameter_modifiers_can_only_be_used_in_a_ts_file: diag(8012, ts.DiagnosticCategory.Error, "parameter_modifiers_can_only_be_used_in_a_ts_file_8012", "'parameter modifiers' can only be used in a .ts file."), + non_null_assertions_can_only_be_used_in_a_ts_file: diag(8013, ts.DiagnosticCategory.Error, "non_null_assertions_can_only_be_used_in_a_ts_file_8013", "'non-null assertions' can only be used in a .ts file."), + enum_declarations_can_only_be_used_in_a_ts_file: diag(8015, ts.DiagnosticCategory.Error, "enum_declarations_can_only_be_used_in_a_ts_file_8015", "'enum declarations' can only be used in a .ts file."), + type_assertion_expressions_can_only_be_used_in_a_ts_file: diag(8016, ts.DiagnosticCategory.Error, "type_assertion_expressions_can_only_be_used_in_a_ts_file_8016", "'type assertion expressions' can only be used in a .ts file."), + Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0: diag(8017, ts.DiagnosticCategory.Error, "Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0_8017", "Octal literal types must use ES2015 syntax. Use the syntax '{0}'."), + Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0: diag(8018, ts.DiagnosticCategory.Error, "Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0_8018", "Octal literals are not allowed in enums members initializer. Use the syntax '{0}'."), + Report_errors_in_js_files: diag(8019, ts.DiagnosticCategory.Message, "Report_errors_in_js_files_8019", "Report errors in .js files."), + JSDoc_types_can_only_be_used_inside_documentation_comments: diag(8020, ts.DiagnosticCategory.Error, "JSDoc_types_can_only_be_used_inside_documentation_comments_8020", "JSDoc types can only be used inside documentation comments."), + JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags: diag(8021, ts.DiagnosticCategory.Error, "JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags_8021", "JSDoc '@typedef' tag should either have a type annotation or be followed by '@property' or '@member' tags."), + JSDoc_0_is_not_attached_to_a_class: diag(8022, ts.DiagnosticCategory.Error, "JSDoc_0_is_not_attached_to_a_class_8022", "JSDoc '@{0}' is not attached to a class."), + JSDoc_0_1_does_not_match_the_extends_2_clause: diag(8023, ts.DiagnosticCategory.Error, "JSDoc_0_1_does_not_match_the_extends_2_clause_8023", "JSDoc '@{0} {1}' does not match the 'extends {2}' clause."), + JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name: diag(8024, ts.DiagnosticCategory.Error, "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_8024", "JSDoc '@param' tag has name '{0}', but there is no parameter with that name."), + Class_declarations_cannot_have_more_than_one_augments_or_extends_tag: diag(8025, ts.DiagnosticCategory.Error, "Class_declarations_cannot_have_more_than_one_augments_or_extends_tag_8025", "Class declarations cannot have more than one `@augments` or `@extends` tag."), + Expected_0_type_arguments_provide_these_with_an_extends_tag: diag(8026, ts.DiagnosticCategory.Error, "Expected_0_type_arguments_provide_these_with_an_extends_tag_8026", "Expected {0} type arguments; provide these with an '@extends' tag."), + Expected_0_1_type_arguments_provide_these_with_an_extends_tag: diag(8027, ts.DiagnosticCategory.Error, "Expected_0_1_type_arguments_provide_these_with_an_extends_tag_8027", "Expected {0}-{1} type arguments; provide these with an '@extends' tag."), + JSDoc_may_only_appear_in_the_last_parameter_of_a_signature: diag(8028, ts.DiagnosticCategory.Error, "JSDoc_may_only_appear_in_the_last_parameter_of_a_signature_8028", "JSDoc '...' may only appear in the last parameter of a signature."), + JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_had_an_array_type: diag(8029, ts.DiagnosticCategory.Error, "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_h_8029", "JSDoc '@param' tag has name '{0}', but there is no parameter with that name. It would match 'arguments' if it had an array type."), + The_type_of_a_function_declaration_must_match_the_function_s_signature: diag(8030, ts.DiagnosticCategory.Error, "The_type_of_a_function_declaration_must_match_the_function_s_signature_8030", "The type of a function declaration must match the function's signature."), + You_cannot_rename_a_module_via_a_global_import: diag(8031, ts.DiagnosticCategory.Error, "You_cannot_rename_a_module_via_a_global_import_8031", "You cannot rename a module via a global import."), + Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_class_extends_clause: diag(9002, ts.DiagnosticCategory.Error, "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002", "Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clause."), + class_expressions_are_not_currently_supported: diag(9003, ts.DiagnosticCategory.Error, "class_expressions_are_not_currently_supported_9003", "'class' expressions are not currently supported."), + Language_service_is_disabled: diag(9004, ts.DiagnosticCategory.Error, "Language_service_is_disabled_9004", "Language service is disabled."), + JSX_attributes_must_only_be_assigned_a_non_empty_expression: diag(17000, ts.DiagnosticCategory.Error, "JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000", "JSX attributes must only be assigned a non-empty 'expression'."), + JSX_elements_cannot_have_multiple_attributes_with_the_same_name: diag(17001, ts.DiagnosticCategory.Error, "JSX_elements_cannot_have_multiple_attributes_with_the_same_name_17001", "JSX elements cannot have multiple attributes with the same name."), + Expected_corresponding_JSX_closing_tag_for_0: diag(17002, ts.DiagnosticCategory.Error, "Expected_corresponding_JSX_closing_tag_for_0_17002", "Expected corresponding JSX closing tag for '{0}'."), + JSX_attribute_expected: diag(17003, ts.DiagnosticCategory.Error, "JSX_attribute_expected_17003", "JSX attribute expected."), + Cannot_use_JSX_unless_the_jsx_flag_is_provided: diag(17004, ts.DiagnosticCategory.Error, "Cannot_use_JSX_unless_the_jsx_flag_is_provided_17004", "Cannot use JSX unless the '--jsx' flag is provided."), + A_constructor_cannot_contain_a_super_call_when_its_class_extends_null: diag(17005, ts.DiagnosticCategory.Error, "A_constructor_cannot_contain_a_super_call_when_its_class_extends_null_17005", "A constructor cannot contain a 'super' call when its class extends 'null'."), + An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses: diag(17006, ts.DiagnosticCategory.Error, "An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_ex_17006", "An unary expression with the '{0}' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses."), + A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses: diag(17007, ts.DiagnosticCategory.Error, "A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Con_17007", "A type assertion expression is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses."), + JSX_element_0_has_no_corresponding_closing_tag: diag(17008, ts.DiagnosticCategory.Error, "JSX_element_0_has_no_corresponding_closing_tag_17008", "JSX element '{0}' has no corresponding closing tag."), + super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class: diag(17009, ts.DiagnosticCategory.Error, "super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class_17009", "'super' must be called before accessing 'this' in the constructor of a derived class."), + Unknown_type_acquisition_option_0: diag(17010, ts.DiagnosticCategory.Error, "Unknown_type_acquisition_option_0_17010", "Unknown type acquisition option '{0}'."), + super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class: diag(17011, ts.DiagnosticCategory.Error, "super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class_17011", "'super' must be called before accessing a property of 'super' in the constructor of a derived class."), + _0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2: diag(17012, ts.DiagnosticCategory.Error, "_0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2_17012", "'{0}' is not a valid meta-property for keyword '{1}'. Did you mean '{2}'?"), + Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constructor: diag(17013, ts.DiagnosticCategory.Error, "Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constru_17013", "Meta-property '{0}' is only allowed in the body of a function declaration, function expression, or constructor."), + JSX_fragment_has_no_corresponding_closing_tag: diag(17014, ts.DiagnosticCategory.Error, "JSX_fragment_has_no_corresponding_closing_tag_17014", "JSX fragment has no corresponding closing tag."), + Expected_corresponding_closing_tag_for_JSX_fragment: diag(17015, ts.DiagnosticCategory.Error, "Expected_corresponding_closing_tag_for_JSX_fragment_17015", "Expected corresponding closing tag for JSX fragment."), + JSX_fragment_is_not_supported_when_using_jsxFactory: diag(17016, ts.DiagnosticCategory.Error, "JSX_fragment_is_not_supported_when_using_jsxFactory_17016", "JSX fragment is not supported when using --jsxFactory"), + JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma: diag(17017, ts.DiagnosticCategory.Error, "JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma_17017", "JSX fragment is not supported when using an inline JSX factory pragma"), + Circularity_detected_while_resolving_configuration_Colon_0: diag(18000, ts.DiagnosticCategory.Error, "Circularity_detected_while_resolving_configuration_Colon_0_18000", "Circularity detected while resolving configuration: {0}"), + A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not: diag(18001, ts.DiagnosticCategory.Error, "A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not_18001", "A path in an 'extends' option must be relative or rooted, but '{0}' is not."), + The_files_list_in_config_file_0_is_empty: diag(18002, ts.DiagnosticCategory.Error, "The_files_list_in_config_file_0_is_empty_18002", "The 'files' list in config file '{0}' is empty."), + No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2: diag(18003, ts.DiagnosticCategory.Error, "No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2_18003", "No inputs were found in config file '{0}'. Specified 'include' paths were '{1}' and 'exclude' paths were '{2}'."), + File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module: diag(80001, ts.DiagnosticCategory.Suggestion, "File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module_80001", "File is a CommonJS module; it may be converted to an ES6 module."), + This_constructor_function_may_be_converted_to_a_class_declaration: diag(80002, ts.DiagnosticCategory.Suggestion, "This_constructor_function_may_be_converted_to_a_class_declaration_80002", "This constructor function may be converted to a class declaration."), + Import_may_be_converted_to_a_default_import: diag(80003, ts.DiagnosticCategory.Suggestion, "Import_may_be_converted_to_a_default_import_80003", "Import may be converted to a default import."), + JSDoc_types_may_be_moved_to_TypeScript_types: diag(80004, ts.DiagnosticCategory.Suggestion, "JSDoc_types_may_be_moved_to_TypeScript_types_80004", "JSDoc types may be moved to TypeScript types."), + require_call_may_be_converted_to_an_import: diag(80005, ts.DiagnosticCategory.Suggestion, "require_call_may_be_converted_to_an_import_80005", "'require' call may be converted to an import."), + This_may_be_converted_to_an_async_function: diag(80006, ts.DiagnosticCategory.Suggestion, "This_may_be_converted_to_an_async_function_80006", "This may be converted to an async function."), + Add_missing_super_call: diag(90001, ts.DiagnosticCategory.Message, "Add_missing_super_call_90001", "Add missing 'super()' call"), + Make_super_call_the_first_statement_in_the_constructor: diag(90002, ts.DiagnosticCategory.Message, "Make_super_call_the_first_statement_in_the_constructor_90002", "Make 'super()' call the first statement in the constructor"), + Change_extends_to_implements: diag(90003, ts.DiagnosticCategory.Message, "Change_extends_to_implements_90003", "Change 'extends' to 'implements'"), + Remove_declaration_for_Colon_0: diag(90004, ts.DiagnosticCategory.Message, "Remove_declaration_for_Colon_0_90004", "Remove declaration for: '{0}'"), + Remove_import_from_0: diag(90005, ts.DiagnosticCategory.Message, "Remove_import_from_0_90005", "Remove import from '{0}'"), + Implement_interface_0: diag(90006, ts.DiagnosticCategory.Message, "Implement_interface_0_90006", "Implement interface '{0}'"), + Implement_inherited_abstract_class: diag(90007, ts.DiagnosticCategory.Message, "Implement_inherited_abstract_class_90007", "Implement inherited abstract class"), + Add_0_to_unresolved_variable: diag(90008, ts.DiagnosticCategory.Message, "Add_0_to_unresolved_variable_90008", "Add '{0}.' to unresolved variable"), + Remove_destructuring: diag(90009, ts.DiagnosticCategory.Message, "Remove_destructuring_90009", "Remove destructuring"), + Remove_variable_statement: diag(90010, ts.DiagnosticCategory.Message, "Remove_variable_statement_90010", "Remove variable statement"), + Remove_template_tag: diag(90011, ts.DiagnosticCategory.Message, "Remove_template_tag_90011", "Remove template tag"), + Remove_type_parameters: diag(90012, ts.DiagnosticCategory.Message, "Remove_type_parameters_90012", "Remove type parameters"), + Import_0_from_module_1: diag(90013, ts.DiagnosticCategory.Message, "Import_0_from_module_1_90013", "Import '{0}' from module \"{1}\""), + Change_0_to_1: diag(90014, ts.DiagnosticCategory.Message, "Change_0_to_1_90014", "Change '{0}' to '{1}'"), + Add_0_to_existing_import_declaration_from_1: diag(90015, ts.DiagnosticCategory.Message, "Add_0_to_existing_import_declaration_from_1_90015", "Add '{0}' to existing import declaration from \"{1}\""), + Declare_property_0: diag(90016, ts.DiagnosticCategory.Message, "Declare_property_0_90016", "Declare property '{0}'"), + Add_index_signature_for_property_0: diag(90017, ts.DiagnosticCategory.Message, "Add_index_signature_for_property_0_90017", "Add index signature for property '{0}'"), + Disable_checking_for_this_file: diag(90018, ts.DiagnosticCategory.Message, "Disable_checking_for_this_file_90018", "Disable checking for this file"), + Ignore_this_error_message: diag(90019, ts.DiagnosticCategory.Message, "Ignore_this_error_message_90019", "Ignore this error message"), + Initialize_property_0_in_the_constructor: diag(90020, ts.DiagnosticCategory.Message, "Initialize_property_0_in_the_constructor_90020", "Initialize property '{0}' in the constructor"), + Initialize_static_property_0: diag(90021, ts.DiagnosticCategory.Message, "Initialize_static_property_0_90021", "Initialize static property '{0}'"), + Change_spelling_to_0: diag(90022, ts.DiagnosticCategory.Message, "Change_spelling_to_0_90022", "Change spelling to '{0}'"), + Declare_method_0: diag(90023, ts.DiagnosticCategory.Message, "Declare_method_0_90023", "Declare method '{0}'"), + Declare_static_method_0: diag(90024, ts.DiagnosticCategory.Message, "Declare_static_method_0_90024", "Declare static method '{0}'"), + Prefix_0_with_an_underscore: diag(90025, ts.DiagnosticCategory.Message, "Prefix_0_with_an_underscore_90025", "Prefix '{0}' with an underscore"), + Rewrite_as_the_indexed_access_type_0: diag(90026, ts.DiagnosticCategory.Message, "Rewrite_as_the_indexed_access_type_0_90026", "Rewrite as the indexed access type '{0}'"), + Declare_static_property_0: diag(90027, ts.DiagnosticCategory.Message, "Declare_static_property_0_90027", "Declare static property '{0}'"), + Call_decorator_expression: diag(90028, ts.DiagnosticCategory.Message, "Call_decorator_expression_90028", "Call decorator expression"), + Add_async_modifier_to_containing_function: diag(90029, ts.DiagnosticCategory.Message, "Add_async_modifier_to_containing_function_90029", "Add async modifier to containing function"), + Replace_infer_0_with_unknown: diag(90030, ts.DiagnosticCategory.Message, "Replace_infer_0_with_unknown_90030", "Replace 'infer {0}' with 'unknown'"), + Replace_all_unused_infer_with_unknown: diag(90031, ts.DiagnosticCategory.Message, "Replace_all_unused_infer_with_unknown_90031", "Replace all unused 'infer' with 'unknown'"), + Import_default_0_from_module_1: diag(90032, ts.DiagnosticCategory.Message, "Import_default_0_from_module_1_90032", "Import default '{0}' from module \"{1}\""), + Add_default_import_0_to_existing_import_declaration_from_1: diag(90033, ts.DiagnosticCategory.Message, "Add_default_import_0_to_existing_import_declaration_from_1_90033", "Add default import '{0}' to existing import declaration from \"{1}\""), + Add_parameter_name: diag(90034, ts.DiagnosticCategory.Message, "Add_parameter_name_90034", "Add parameter name"), + Convert_function_to_an_ES2015_class: diag(95001, ts.DiagnosticCategory.Message, "Convert_function_to_an_ES2015_class_95001", "Convert function to an ES2015 class"), + Convert_function_0_to_class: diag(95002, ts.DiagnosticCategory.Message, "Convert_function_0_to_class_95002", "Convert function '{0}' to class"), + Extract_to_0_in_1: diag(95004, ts.DiagnosticCategory.Message, "Extract_to_0_in_1_95004", "Extract to {0} in {1}"), + Extract_function: diag(95005, ts.DiagnosticCategory.Message, "Extract_function_95005", "Extract function"), + Extract_constant: diag(95006, ts.DiagnosticCategory.Message, "Extract_constant_95006", "Extract constant"), + Extract_to_0_in_enclosing_scope: diag(95007, ts.DiagnosticCategory.Message, "Extract_to_0_in_enclosing_scope_95007", "Extract to {0} in enclosing scope"), + Extract_to_0_in_1_scope: diag(95008, ts.DiagnosticCategory.Message, "Extract_to_0_in_1_scope_95008", "Extract to {0} in {1} scope"), + Annotate_with_type_from_JSDoc: diag(95009, ts.DiagnosticCategory.Message, "Annotate_with_type_from_JSDoc_95009", "Annotate with type from JSDoc"), + Annotate_with_types_from_JSDoc: diag(95010, ts.DiagnosticCategory.Message, "Annotate_with_types_from_JSDoc_95010", "Annotate with types from JSDoc"), + Infer_type_of_0_from_usage: diag(95011, ts.DiagnosticCategory.Message, "Infer_type_of_0_from_usage_95011", "Infer type of '{0}' from usage"), + Infer_parameter_types_from_usage: diag(95012, ts.DiagnosticCategory.Message, "Infer_parameter_types_from_usage_95012", "Infer parameter types from usage"), + Convert_to_default_import: diag(95013, ts.DiagnosticCategory.Message, "Convert_to_default_import_95013", "Convert to default import"), + Install_0: diag(95014, ts.DiagnosticCategory.Message, "Install_0_95014", "Install '{0}'"), + Replace_import_with_0: diag(95015, ts.DiagnosticCategory.Message, "Replace_import_with_0_95015", "Replace import with '{0}'."), + Use_synthetic_default_member: diag(95016, ts.DiagnosticCategory.Message, "Use_synthetic_default_member_95016", "Use synthetic 'default' member."), + Convert_to_ES6_module: diag(95017, ts.DiagnosticCategory.Message, "Convert_to_ES6_module_95017", "Convert to ES6 module"), + Add_undefined_type_to_property_0: diag(95018, ts.DiagnosticCategory.Message, "Add_undefined_type_to_property_0_95018", "Add 'undefined' type to property '{0}'"), + Add_initializer_to_property_0: diag(95019, ts.DiagnosticCategory.Message, "Add_initializer_to_property_0_95019", "Add initializer to property '{0}'"), + Add_definite_assignment_assertion_to_property_0: diag(95020, ts.DiagnosticCategory.Message, "Add_definite_assignment_assertion_to_property_0_95020", "Add definite assignment assertion to property '{0}'"), + Add_all_missing_members: diag(95022, ts.DiagnosticCategory.Message, "Add_all_missing_members_95022", "Add all missing members"), + Infer_all_types_from_usage: diag(95023, ts.DiagnosticCategory.Message, "Infer_all_types_from_usage_95023", "Infer all types from usage"), + Delete_all_unused_declarations: diag(95024, ts.DiagnosticCategory.Message, "Delete_all_unused_declarations_95024", "Delete all unused declarations"), + Prefix_all_unused_declarations_with_where_possible: diag(95025, ts.DiagnosticCategory.Message, "Prefix_all_unused_declarations_with_where_possible_95025", "Prefix all unused declarations with '_' where possible"), + Fix_all_detected_spelling_errors: diag(95026, ts.DiagnosticCategory.Message, "Fix_all_detected_spelling_errors_95026", "Fix all detected spelling errors"), + Add_initializers_to_all_uninitialized_properties: diag(95027, ts.DiagnosticCategory.Message, "Add_initializers_to_all_uninitialized_properties_95027", "Add initializers to all uninitialized properties"), + Add_definite_assignment_assertions_to_all_uninitialized_properties: diag(95028, ts.DiagnosticCategory.Message, "Add_definite_assignment_assertions_to_all_uninitialized_properties_95028", "Add definite assignment assertions to all uninitialized properties"), + Add_undefined_type_to_all_uninitialized_properties: diag(95029, ts.DiagnosticCategory.Message, "Add_undefined_type_to_all_uninitialized_properties_95029", "Add undefined type to all uninitialized properties"), + Change_all_jsdoc_style_types_to_TypeScript: diag(95030, ts.DiagnosticCategory.Message, "Change_all_jsdoc_style_types_to_TypeScript_95030", "Change all jsdoc-style types to TypeScript"), + Change_all_jsdoc_style_types_to_TypeScript_and_add_undefined_to_nullable_types: diag(95031, ts.DiagnosticCategory.Message, "Change_all_jsdoc_style_types_to_TypeScript_and_add_undefined_to_nullable_types_95031", "Change all jsdoc-style types to TypeScript (and add '| undefined' to nullable types)"), + Implement_all_unimplemented_interfaces: diag(95032, ts.DiagnosticCategory.Message, "Implement_all_unimplemented_interfaces_95032", "Implement all unimplemented interfaces"), + Install_all_missing_types_packages: diag(95033, ts.DiagnosticCategory.Message, "Install_all_missing_types_packages_95033", "Install all missing types packages"), + Rewrite_all_as_indexed_access_types: diag(95034, ts.DiagnosticCategory.Message, "Rewrite_all_as_indexed_access_types_95034", "Rewrite all as indexed access types"), + Convert_all_to_default_imports: diag(95035, ts.DiagnosticCategory.Message, "Convert_all_to_default_imports_95035", "Convert all to default imports"), + Make_all_super_calls_the_first_statement_in_their_constructor: diag(95036, ts.DiagnosticCategory.Message, "Make_all_super_calls_the_first_statement_in_their_constructor_95036", "Make all 'super()' calls the first statement in their constructor"), + Add_qualifier_to_all_unresolved_variables_matching_a_member_name: diag(95037, ts.DiagnosticCategory.Message, "Add_qualifier_to_all_unresolved_variables_matching_a_member_name_95037", "Add qualifier to all unresolved variables matching a member name"), + Change_all_extended_interfaces_to_implements: diag(95038, ts.DiagnosticCategory.Message, "Change_all_extended_interfaces_to_implements_95038", "Change all extended interfaces to 'implements'"), + Add_all_missing_super_calls: diag(95039, ts.DiagnosticCategory.Message, "Add_all_missing_super_calls_95039", "Add all missing super calls"), + Implement_all_inherited_abstract_classes: diag(95040, ts.DiagnosticCategory.Message, "Implement_all_inherited_abstract_classes_95040", "Implement all inherited abstract classes"), + Add_all_missing_async_modifiers: diag(95041, ts.DiagnosticCategory.Message, "Add_all_missing_async_modifiers_95041", "Add all missing 'async' modifiers"), + Add_ts_ignore_to_all_error_messages: diag(95042, ts.DiagnosticCategory.Message, "Add_ts_ignore_to_all_error_messages_95042", "Add '@ts-ignore' to all error messages"), + Annotate_everything_with_types_from_JSDoc: diag(95043, ts.DiagnosticCategory.Message, "Annotate_everything_with_types_from_JSDoc_95043", "Annotate everything with types from JSDoc"), + Add_to_all_uncalled_decorators: diag(95044, ts.DiagnosticCategory.Message, "Add_to_all_uncalled_decorators_95044", "Add '()' to all uncalled decorators"), + Convert_all_constructor_functions_to_classes: diag(95045, ts.DiagnosticCategory.Message, "Convert_all_constructor_functions_to_classes_95045", "Convert all constructor functions to classes"), + Generate_get_and_set_accessors: diag(95046, ts.DiagnosticCategory.Message, "Generate_get_and_set_accessors_95046", "Generate 'get' and 'set' accessors"), + Convert_require_to_import: diag(95047, ts.DiagnosticCategory.Message, "Convert_require_to_import_95047", "Convert 'require' to 'import'"), + Convert_all_require_to_import: diag(95048, ts.DiagnosticCategory.Message, "Convert_all_require_to_import_95048", "Convert all 'require' to 'import'"), + Move_to_a_new_file: diag(95049, ts.DiagnosticCategory.Message, "Move_to_a_new_file_95049", "Move to a new file"), + Remove_unreachable_code: diag(95050, ts.DiagnosticCategory.Message, "Remove_unreachable_code_95050", "Remove unreachable code"), + Remove_all_unreachable_code: diag(95051, ts.DiagnosticCategory.Message, "Remove_all_unreachable_code_95051", "Remove all unreachable code"), + Add_missing_typeof: diag(95052, ts.DiagnosticCategory.Message, "Add_missing_typeof_95052", "Add missing 'typeof'"), + Remove_unused_label: diag(95053, ts.DiagnosticCategory.Message, "Remove_unused_label_95053", "Remove unused label"), + Remove_all_unused_labels: diag(95054, ts.DiagnosticCategory.Message, "Remove_all_unused_labels_95054", "Remove all unused labels"), + Convert_0_to_mapped_object_type: diag(95055, ts.DiagnosticCategory.Message, "Convert_0_to_mapped_object_type_95055", "Convert '{0}' to mapped object type"), + Convert_namespace_import_to_named_imports: diag(95056, ts.DiagnosticCategory.Message, "Convert_namespace_import_to_named_imports_95056", "Convert namespace import to named imports"), + Convert_named_imports_to_namespace_import: diag(95057, ts.DiagnosticCategory.Message, "Convert_named_imports_to_namespace_import_95057", "Convert named imports to namespace import"), + Add_or_remove_braces_in_an_arrow_function: diag(95058, ts.DiagnosticCategory.Message, "Add_or_remove_braces_in_an_arrow_function_95058", "Add or remove braces in an arrow function"), + Add_braces_to_arrow_function: diag(95059, ts.DiagnosticCategory.Message, "Add_braces_to_arrow_function_95059", "Add braces to arrow function"), + Remove_braces_from_arrow_function: diag(95060, ts.DiagnosticCategory.Message, "Remove_braces_from_arrow_function_95060", "Remove braces from arrow function"), + Convert_default_export_to_named_export: diag(95061, ts.DiagnosticCategory.Message, "Convert_default_export_to_named_export_95061", "Convert default export to named export"), + Convert_named_export_to_default_export: diag(95062, ts.DiagnosticCategory.Message, "Convert_named_export_to_default_export_95062", "Convert named export to default export"), + Add_missing_enum_member_0: diag(95063, ts.DiagnosticCategory.Message, "Add_missing_enum_member_0_95063", "Add missing enum member '{0}'"), + Add_all_missing_imports: diag(95064, ts.DiagnosticCategory.Message, "Add_all_missing_imports_95064", "Add all missing imports"), + Convert_to_async_function: diag(95065, ts.DiagnosticCategory.Message, "Convert_to_async_function_95065", "Convert to async function"), + Convert_all_to_async_functions: diag(95066, ts.DiagnosticCategory.Message, "Convert_all_to_async_functions_95066", "Convert all to async functions"), + Generate_types_for_0: diag(95067, ts.DiagnosticCategory.Message, "Generate_types_for_0_95067", "Generate types for '{0}'"), + Generate_types_for_all_packages_without_types: diag(95068, ts.DiagnosticCategory.Message, "Generate_types_for_all_packages_without_types_95068", "Generate types for all packages without types"), + Add_unknown_conversion_for_non_overlapping_types: diag(95069, ts.DiagnosticCategory.Message, "Add_unknown_conversion_for_non_overlapping_types_95069", "Add 'unknown' conversion for non-overlapping types"), + Add_unknown_to_all_conversions_of_non_overlapping_types: diag(95070, ts.DiagnosticCategory.Message, "Add_unknown_to_all_conversions_of_non_overlapping_types_95070", "Add 'unknown' to all conversions of non-overlapping types"), + Add_missing_new_operator_to_call: diag(95071, ts.DiagnosticCategory.Message, "Add_missing_new_operator_to_call_95071", "Add missing 'new' operator to call"), + Add_missing_new_operator_to_all_calls: diag(95072, ts.DiagnosticCategory.Message, "Add_missing_new_operator_to_all_calls_95072", "Add missing 'new' operator to all calls"), + Add_names_to_all_parameters_without_names: diag(95073, ts.DiagnosticCategory.Message, "Add_names_to_all_parameters_without_names_95073", "Add names to all parameters without names"), + }; +})(ts || (ts = {})); +var ts; +(function (ts) { + var _a; + function tokenIsIdentifierOrKeyword(token) { + return token >= 72; + } + ts.tokenIsIdentifierOrKeyword = tokenIsIdentifierOrKeyword; + function tokenIsIdentifierOrKeywordOrGreaterThan(token) { + return token === 30 || tokenIsIdentifierOrKeyword(token); + } + ts.tokenIsIdentifierOrKeywordOrGreaterThan = tokenIsIdentifierOrKeywordOrGreaterThan; + var textToKeywordObj = (_a = { + abstract: 118, + any: 120, + as: 119, + bigint: 146, + boolean: 123, + break: 73, + case: 74, + catch: 75, + class: 76, + continue: 78, + const: 77 + }, + _a["" + "constructor"] = 124, + _a.debugger = 79, + _a.declare = 125, + _a.default = 80, + _a.delete = 81, + _a.do = 82, + _a.else = 83, + _a.enum = 84, + _a.export = 85, + _a.extends = 86, + _a.false = 87, + _a.finally = 88, + _a.for = 89, + _a.from = 144, + _a.function = 90, + _a.get = 126, + _a.if = 91, + _a.implements = 109, + _a.import = 92, + _a.in = 93, + _a.infer = 127, + _a.instanceof = 94, + _a.interface = 110, + _a.is = 128, + _a.keyof = 129, + _a.let = 111, + _a.module = 130, + _a.namespace = 131, + _a.never = 132, + _a.new = 95, + _a.null = 96, + _a.number = 135, + _a.object = 136, + _a.package = 112, + _a.private = 113, + _a.protected = 114, + _a.public = 115, + _a.readonly = 133, + _a.require = 134, + _a.global = 145, + _a.return = 97, + _a.set = 137, + _a.static = 116, + _a.string = 138, + _a.super = 98, + _a.switch = 99, + _a.symbol = 139, + _a.this = 100, + _a.throw = 101, + _a.true = 102, + _a.try = 103, + _a.type = 140, + _a.typeof = 104, + _a.undefined = 141, + _a.unique = 142, + _a.unknown = 143, + _a.var = 105, + _a.void = 106, + _a.while = 107, + _a.with = 108, + _a.yield = 117, + _a.async = 121, + _a.await = 122, + _a.of = 147, + _a); + var textToKeyword = ts.createMapFromTemplate(textToKeywordObj); + var textToToken = ts.createMapFromTemplate(__assign({}, textToKeywordObj, { "{": 18, "}": 19, "(": 20, ")": 21, "[": 22, "]": 23, ".": 24, "...": 25, ";": 26, ",": 27, "<": 28, ">": 30, "<=": 31, ">=": 32, "==": 33, "!=": 34, "===": 35, "!==": 36, "=>": 37, "+": 38, "-": 39, "**": 41, "*": 40, "/": 42, "%": 43, "++": 44, "--": 45, "<<": 46, ">": 47, ">>>": 48, "&": 49, "|": 50, "^": 51, "!": 52, "~": 53, "&&": 54, "||": 55, "?": 56, ":": 57, "=": 59, "+=": 60, "-=": 61, "*=": 62, "**=": 63, "/=": 64, "%=": 65, "<<=": 66, ">>=": 67, ">>>=": 68, "&=": 69, "|=": 70, "^=": 71, "@": 58 })); + var unicodeES3IdentifierStart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 543, 546, 563, 592, 685, 688, 696, 699, 705, 720, 721, 736, 740, 750, 750, 890, 890, 902, 902, 904, 906, 908, 908, 910, 929, 931, 974, 976, 983, 986, 1011, 1024, 1153, 1164, 1220, 1223, 1224, 1227, 1228, 1232, 1269, 1272, 1273, 1329, 1366, 1369, 1369, 1377, 1415, 1488, 1514, 1520, 1522, 1569, 1594, 1600, 1610, 1649, 1747, 1749, 1749, 1765, 1766, 1786, 1788, 1808, 1808, 1810, 1836, 1920, 1957, 2309, 2361, 2365, 2365, 2384, 2384, 2392, 2401, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2524, 2525, 2527, 2529, 2544, 2545, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2649, 2652, 2654, 2654, 2674, 2676, 2693, 2699, 2701, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2749, 2749, 2768, 2768, 2784, 2784, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2870, 2873, 2877, 2877, 2908, 2909, 2911, 2913, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 2997, 2999, 3001, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3168, 3169, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3294, 3294, 3296, 3297, 3333, 3340, 3342, 3344, 3346, 3368, 3370, 3385, 3424, 3425, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3585, 3632, 3634, 3635, 3648, 3654, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3760, 3762, 3763, 3773, 3773, 3776, 3780, 3782, 3782, 3804, 3805, 3840, 3840, 3904, 3911, 3913, 3946, 3976, 3979, 4096, 4129, 4131, 4135, 4137, 4138, 4176, 4181, 4256, 4293, 4304, 4342, 4352, 4441, 4447, 4514, 4520, 4601, 4608, 4614, 4616, 4678, 4680, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4742, 4744, 4744, 4746, 4749, 4752, 4782, 4784, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4814, 4816, 4822, 4824, 4846, 4848, 4878, 4880, 4880, 4882, 4885, 4888, 4894, 4896, 4934, 4936, 4954, 5024, 5108, 5121, 5740, 5743, 5750, 5761, 5786, 5792, 5866, 6016, 6067, 6176, 6263, 6272, 6312, 7680, 7835, 7840, 7929, 7936, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8319, 8319, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8497, 8499, 8505, 8544, 8579, 12293, 12295, 12321, 12329, 12337, 12341, 12344, 12346, 12353, 12436, 12445, 12446, 12449, 12538, 12540, 12542, 12549, 12588, 12593, 12686, 12704, 12727, 13312, 19893, 19968, 40869, 40960, 42124, 44032, 55203, 63744, 64045, 64256, 64262, 64275, 64279, 64285, 64285, 64287, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65136, 65138, 65140, 65140, 65142, 65276, 65313, 65338, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500,]; + var unicodeES3IdentifierPart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 543, 546, 563, 592, 685, 688, 696, 699, 705, 720, 721, 736, 740, 750, 750, 768, 846, 864, 866, 890, 890, 902, 902, 904, 906, 908, 908, 910, 929, 931, 974, 976, 983, 986, 1011, 1024, 1153, 1155, 1158, 1164, 1220, 1223, 1224, 1227, 1228, 1232, 1269, 1272, 1273, 1329, 1366, 1369, 1369, 1377, 1415, 1425, 1441, 1443, 1465, 1467, 1469, 1471, 1471, 1473, 1474, 1476, 1476, 1488, 1514, 1520, 1522, 1569, 1594, 1600, 1621, 1632, 1641, 1648, 1747, 1749, 1756, 1759, 1768, 1770, 1773, 1776, 1788, 1808, 1836, 1840, 1866, 1920, 1968, 2305, 2307, 2309, 2361, 2364, 2381, 2384, 2388, 2392, 2403, 2406, 2415, 2433, 2435, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2492, 2492, 2494, 2500, 2503, 2504, 2507, 2509, 2519, 2519, 2524, 2525, 2527, 2531, 2534, 2545, 2562, 2562, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2620, 2620, 2622, 2626, 2631, 2632, 2635, 2637, 2649, 2652, 2654, 2654, 2662, 2676, 2689, 2691, 2693, 2699, 2701, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2748, 2757, 2759, 2761, 2763, 2765, 2768, 2768, 2784, 2784, 2790, 2799, 2817, 2819, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2870, 2873, 2876, 2883, 2887, 2888, 2891, 2893, 2902, 2903, 2908, 2909, 2911, 2913, 2918, 2927, 2946, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 2997, 2999, 3001, 3006, 3010, 3014, 3016, 3018, 3021, 3031, 3031, 3047, 3055, 3073, 3075, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3134, 3140, 3142, 3144, 3146, 3149, 3157, 3158, 3168, 3169, 3174, 3183, 3202, 3203, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3262, 3268, 3270, 3272, 3274, 3277, 3285, 3286, 3294, 3294, 3296, 3297, 3302, 3311, 3330, 3331, 3333, 3340, 3342, 3344, 3346, 3368, 3370, 3385, 3390, 3395, 3398, 3400, 3402, 3405, 3415, 3415, 3424, 3425, 3430, 3439, 3458, 3459, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3530, 3530, 3535, 3540, 3542, 3542, 3544, 3551, 3570, 3571, 3585, 3642, 3648, 3662, 3664, 3673, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3769, 3771, 3773, 3776, 3780, 3782, 3782, 3784, 3789, 3792, 3801, 3804, 3805, 3840, 3840, 3864, 3865, 3872, 3881, 3893, 3893, 3895, 3895, 3897, 3897, 3902, 3911, 3913, 3946, 3953, 3972, 3974, 3979, 3984, 3991, 3993, 4028, 4038, 4038, 4096, 4129, 4131, 4135, 4137, 4138, 4140, 4146, 4150, 4153, 4160, 4169, 4176, 4185, 4256, 4293, 4304, 4342, 4352, 4441, 4447, 4514, 4520, 4601, 4608, 4614, 4616, 4678, 4680, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4742, 4744, 4744, 4746, 4749, 4752, 4782, 4784, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4814, 4816, 4822, 4824, 4846, 4848, 4878, 4880, 4880, 4882, 4885, 4888, 4894, 4896, 4934, 4936, 4954, 4969, 4977, 5024, 5108, 5121, 5740, 5743, 5750, 5761, 5786, 5792, 5866, 6016, 6099, 6112, 6121, 6160, 6169, 6176, 6263, 6272, 6313, 7680, 7835, 7840, 7929, 7936, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8255, 8256, 8319, 8319, 8400, 8412, 8417, 8417, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8497, 8499, 8505, 8544, 8579, 12293, 12295, 12321, 12335, 12337, 12341, 12344, 12346, 12353, 12436, 12441, 12442, 12445, 12446, 12449, 12542, 12549, 12588, 12593, 12686, 12704, 12727, 13312, 19893, 19968, 40869, 40960, 42124, 44032, 55203, 63744, 64045, 64256, 64262, 64275, 64279, 64285, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65056, 65059, 65075, 65076, 65101, 65103, 65136, 65138, 65140, 65140, 65142, 65276, 65296, 65305, 65313, 65338, 65343, 65343, 65345, 65370, 65381, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500,]; + var unicodeES5IdentifierStart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 705, 710, 721, 736, 740, 748, 748, 750, 750, 880, 884, 886, 887, 890, 893, 902, 902, 904, 906, 908, 908, 910, 929, 931, 1013, 1015, 1153, 1162, 1319, 1329, 1366, 1369, 1369, 1377, 1415, 1488, 1514, 1520, 1522, 1568, 1610, 1646, 1647, 1649, 1747, 1749, 1749, 1765, 1766, 1774, 1775, 1786, 1788, 1791, 1791, 1808, 1808, 1810, 1839, 1869, 1957, 1969, 1969, 1994, 2026, 2036, 2037, 2042, 2042, 2048, 2069, 2074, 2074, 2084, 2084, 2088, 2088, 2112, 2136, 2208, 2208, 2210, 2220, 2308, 2361, 2365, 2365, 2384, 2384, 2392, 2401, 2417, 2423, 2425, 2431, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2493, 2493, 2510, 2510, 2524, 2525, 2527, 2529, 2544, 2545, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2649, 2652, 2654, 2654, 2674, 2676, 2693, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2749, 2749, 2768, 2768, 2784, 2785, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2869, 2873, 2877, 2877, 2908, 2909, 2911, 2913, 2929, 2929, 2947, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 3001, 3024, 3024, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3133, 3133, 3160, 3161, 3168, 3169, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3261, 3261, 3294, 3294, 3296, 3297, 3313, 3314, 3333, 3340, 3342, 3344, 3346, 3386, 3389, 3389, 3406, 3406, 3424, 3425, 3450, 3455, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3585, 3632, 3634, 3635, 3648, 3654, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3760, 3762, 3763, 3773, 3773, 3776, 3780, 3782, 3782, 3804, 3807, 3840, 3840, 3904, 3911, 3913, 3948, 3976, 3980, 4096, 4138, 4159, 4159, 4176, 4181, 4186, 4189, 4193, 4193, 4197, 4198, 4206, 4208, 4213, 4225, 4238, 4238, 4256, 4293, 4295, 4295, 4301, 4301, 4304, 4346, 4348, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4744, 4746, 4749, 4752, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4822, 4824, 4880, 4882, 4885, 4888, 4954, 4992, 5007, 5024, 5108, 5121, 5740, 5743, 5759, 5761, 5786, 5792, 5866, 5870, 5872, 5888, 5900, 5902, 5905, 5920, 5937, 5952, 5969, 5984, 5996, 5998, 6000, 6016, 6067, 6103, 6103, 6108, 6108, 6176, 6263, 6272, 6312, 6314, 6314, 6320, 6389, 6400, 6428, 6480, 6509, 6512, 6516, 6528, 6571, 6593, 6599, 6656, 6678, 6688, 6740, 6823, 6823, 6917, 6963, 6981, 6987, 7043, 7072, 7086, 7087, 7098, 7141, 7168, 7203, 7245, 7247, 7258, 7293, 7401, 7404, 7406, 7409, 7413, 7414, 7424, 7615, 7680, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8305, 8305, 8319, 8319, 8336, 8348, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8505, 8508, 8511, 8517, 8521, 8526, 8526, 8544, 8584, 11264, 11310, 11312, 11358, 11360, 11492, 11499, 11502, 11506, 11507, 11520, 11557, 11559, 11559, 11565, 11565, 11568, 11623, 11631, 11631, 11648, 11670, 11680, 11686, 11688, 11694, 11696, 11702, 11704, 11710, 11712, 11718, 11720, 11726, 11728, 11734, 11736, 11742, 11823, 11823, 12293, 12295, 12321, 12329, 12337, 12341, 12344, 12348, 12353, 12438, 12445, 12447, 12449, 12538, 12540, 12543, 12549, 12589, 12593, 12686, 12704, 12730, 12784, 12799, 13312, 19893, 19968, 40908, 40960, 42124, 42192, 42237, 42240, 42508, 42512, 42527, 42538, 42539, 42560, 42606, 42623, 42647, 42656, 42735, 42775, 42783, 42786, 42888, 42891, 42894, 42896, 42899, 42912, 42922, 43000, 43009, 43011, 43013, 43015, 43018, 43020, 43042, 43072, 43123, 43138, 43187, 43250, 43255, 43259, 43259, 43274, 43301, 43312, 43334, 43360, 43388, 43396, 43442, 43471, 43471, 43520, 43560, 43584, 43586, 43588, 43595, 43616, 43638, 43642, 43642, 43648, 43695, 43697, 43697, 43701, 43702, 43705, 43709, 43712, 43712, 43714, 43714, 43739, 43741, 43744, 43754, 43762, 43764, 43777, 43782, 43785, 43790, 43793, 43798, 43808, 43814, 43816, 43822, 43968, 44002, 44032, 55203, 55216, 55238, 55243, 55291, 63744, 64109, 64112, 64217, 64256, 64262, 64275, 64279, 64285, 64285, 64287, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65136, 65140, 65142, 65276, 65313, 65338, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500,]; + var unicodeES5IdentifierPart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 705, 710, 721, 736, 740, 748, 748, 750, 750, 768, 884, 886, 887, 890, 893, 902, 902, 904, 906, 908, 908, 910, 929, 931, 1013, 1015, 1153, 1155, 1159, 1162, 1319, 1329, 1366, 1369, 1369, 1377, 1415, 1425, 1469, 1471, 1471, 1473, 1474, 1476, 1477, 1479, 1479, 1488, 1514, 1520, 1522, 1552, 1562, 1568, 1641, 1646, 1747, 1749, 1756, 1759, 1768, 1770, 1788, 1791, 1791, 1808, 1866, 1869, 1969, 1984, 2037, 2042, 2042, 2048, 2093, 2112, 2139, 2208, 2208, 2210, 2220, 2276, 2302, 2304, 2403, 2406, 2415, 2417, 2423, 2425, 2431, 2433, 2435, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2492, 2500, 2503, 2504, 2507, 2510, 2519, 2519, 2524, 2525, 2527, 2531, 2534, 2545, 2561, 2563, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2620, 2620, 2622, 2626, 2631, 2632, 2635, 2637, 2641, 2641, 2649, 2652, 2654, 2654, 2662, 2677, 2689, 2691, 2693, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2748, 2757, 2759, 2761, 2763, 2765, 2768, 2768, 2784, 2787, 2790, 2799, 2817, 2819, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2869, 2873, 2876, 2884, 2887, 2888, 2891, 2893, 2902, 2903, 2908, 2909, 2911, 2915, 2918, 2927, 2929, 2929, 2946, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 3001, 3006, 3010, 3014, 3016, 3018, 3021, 3024, 3024, 3031, 3031, 3046, 3055, 3073, 3075, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3133, 3140, 3142, 3144, 3146, 3149, 3157, 3158, 3160, 3161, 3168, 3171, 3174, 3183, 3202, 3203, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3260, 3268, 3270, 3272, 3274, 3277, 3285, 3286, 3294, 3294, 3296, 3299, 3302, 3311, 3313, 3314, 3330, 3331, 3333, 3340, 3342, 3344, 3346, 3386, 3389, 3396, 3398, 3400, 3402, 3406, 3415, 3415, 3424, 3427, 3430, 3439, 3450, 3455, 3458, 3459, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3530, 3530, 3535, 3540, 3542, 3542, 3544, 3551, 3570, 3571, 3585, 3642, 3648, 3662, 3664, 3673, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3769, 3771, 3773, 3776, 3780, 3782, 3782, 3784, 3789, 3792, 3801, 3804, 3807, 3840, 3840, 3864, 3865, 3872, 3881, 3893, 3893, 3895, 3895, 3897, 3897, 3902, 3911, 3913, 3948, 3953, 3972, 3974, 3991, 3993, 4028, 4038, 4038, 4096, 4169, 4176, 4253, 4256, 4293, 4295, 4295, 4301, 4301, 4304, 4346, 4348, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4744, 4746, 4749, 4752, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4822, 4824, 4880, 4882, 4885, 4888, 4954, 4957, 4959, 4992, 5007, 5024, 5108, 5121, 5740, 5743, 5759, 5761, 5786, 5792, 5866, 5870, 5872, 5888, 5900, 5902, 5908, 5920, 5940, 5952, 5971, 5984, 5996, 5998, 6000, 6002, 6003, 6016, 6099, 6103, 6103, 6108, 6109, 6112, 6121, 6155, 6157, 6160, 6169, 6176, 6263, 6272, 6314, 6320, 6389, 6400, 6428, 6432, 6443, 6448, 6459, 6470, 6509, 6512, 6516, 6528, 6571, 6576, 6601, 6608, 6617, 6656, 6683, 6688, 6750, 6752, 6780, 6783, 6793, 6800, 6809, 6823, 6823, 6912, 6987, 6992, 7001, 7019, 7027, 7040, 7155, 7168, 7223, 7232, 7241, 7245, 7293, 7376, 7378, 7380, 7414, 7424, 7654, 7676, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8204, 8205, 8255, 8256, 8276, 8276, 8305, 8305, 8319, 8319, 8336, 8348, 8400, 8412, 8417, 8417, 8421, 8432, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8505, 8508, 8511, 8517, 8521, 8526, 8526, 8544, 8584, 11264, 11310, 11312, 11358, 11360, 11492, 11499, 11507, 11520, 11557, 11559, 11559, 11565, 11565, 11568, 11623, 11631, 11631, 11647, 11670, 11680, 11686, 11688, 11694, 11696, 11702, 11704, 11710, 11712, 11718, 11720, 11726, 11728, 11734, 11736, 11742, 11744, 11775, 11823, 11823, 12293, 12295, 12321, 12335, 12337, 12341, 12344, 12348, 12353, 12438, 12441, 12442, 12445, 12447, 12449, 12538, 12540, 12543, 12549, 12589, 12593, 12686, 12704, 12730, 12784, 12799, 13312, 19893, 19968, 40908, 40960, 42124, 42192, 42237, 42240, 42508, 42512, 42539, 42560, 42607, 42612, 42621, 42623, 42647, 42655, 42737, 42775, 42783, 42786, 42888, 42891, 42894, 42896, 42899, 42912, 42922, 43000, 43047, 43072, 43123, 43136, 43204, 43216, 43225, 43232, 43255, 43259, 43259, 43264, 43309, 43312, 43347, 43360, 43388, 43392, 43456, 43471, 43481, 43520, 43574, 43584, 43597, 43600, 43609, 43616, 43638, 43642, 43643, 43648, 43714, 43739, 43741, 43744, 43759, 43762, 43766, 43777, 43782, 43785, 43790, 43793, 43798, 43808, 43814, 43816, 43822, 43968, 44010, 44012, 44013, 44016, 44025, 44032, 55203, 55216, 55238, 55243, 55291, 63744, 64109, 64112, 64217, 64256, 64262, 64275, 64279, 64285, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65024, 65039, 65056, 65062, 65075, 65076, 65101, 65103, 65136, 65140, 65142, 65276, 65296, 65305, 65313, 65338, 65343, 65343, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500,]; + function lookupInUnicodeMap(code, map) { + if (code < map[0]) { + return false; + } + var lo = 0; + var hi = map.length; + var mid; + while (lo + 1 < hi) { + mid = lo + (hi - lo) / 2; + mid -= mid % 2; + if (map[mid] <= code && code <= map[mid + 1]) { + return true; + } + if (code < map[mid]) { + hi = mid; + } + else { + lo = mid + 2; + } + } + return false; + } + function isUnicodeIdentifierStart(code, languageVersion) { + return languageVersion >= 1 ? + lookupInUnicodeMap(code, unicodeES5IdentifierStart) : + lookupInUnicodeMap(code, unicodeES3IdentifierStart); + } + ts.isUnicodeIdentifierStart = isUnicodeIdentifierStart; + function isUnicodeIdentifierPart(code, languageVersion) { + return languageVersion >= 1 ? + lookupInUnicodeMap(code, unicodeES5IdentifierPart) : + lookupInUnicodeMap(code, unicodeES3IdentifierPart); + } + function makeReverseMap(source) { + var result = []; + source.forEach(function (value, name) { + result[value] = name; + }); + return result; + } + var tokenStrings = makeReverseMap(textToToken); + function tokenToString(t) { + return tokenStrings[t]; + } + ts.tokenToString = tokenToString; + function stringToToken(s) { + return textToToken.get(s); + } + ts.stringToToken = stringToToken; + function computeLineStarts(text) { + var result = new Array(); + var pos = 0; + var lineStart = 0; + while (pos < text.length) { + var ch = text.charCodeAt(pos); + pos++; + switch (ch) { + case 13: + if (text.charCodeAt(pos) === 10) { + pos++; + } + case 10: + result.push(lineStart); + lineStart = pos; + break; + default: + if (ch > 127 && isLineBreak(ch)) { + result.push(lineStart); + lineStart = pos; + } + break; + } + } + result.push(lineStart); + return result; + } + ts.computeLineStarts = computeLineStarts; + function getPositionOfLineAndCharacter(sourceFile, line, character) { + return computePositionOfLineAndCharacter(getLineStarts(sourceFile), line, character, sourceFile.text); + } + ts.getPositionOfLineAndCharacter = getPositionOfLineAndCharacter; + function getPositionOfLineAndCharacterWithEdits(sourceFile, line, character) { + return computePositionOfLineAndCharacter(getLineStarts(sourceFile), line, character, sourceFile.text, true); + } + ts.getPositionOfLineAndCharacterWithEdits = getPositionOfLineAndCharacterWithEdits; + function computePositionOfLineAndCharacter(lineStarts, line, character, debugText, allowEdits) { + if (line < 0 || line >= lineStarts.length) { + if (allowEdits) { + line = line < 0 ? 0 : line >= lineStarts.length ? lineStarts.length - 1 : line; + } + else { + ts.Debug.fail("Bad line number. Line: " + line + ", lineStarts.length: " + lineStarts.length + " , line map is correct? " + (debugText !== undefined ? ts.arraysEqual(lineStarts, computeLineStarts(debugText)) : "unknown")); + } + } + var res = lineStarts[line] + character; + if (allowEdits) { + return res > lineStarts[line + 1] ? lineStarts[line + 1] : typeof debugText === "string" && res > debugText.length ? debugText.length : res; + } + if (line < lineStarts.length - 1) { + ts.Debug.assert(res < lineStarts[line + 1]); + } + else if (debugText !== undefined) { + ts.Debug.assert(res <= debugText.length); + } + return res; + } + ts.computePositionOfLineAndCharacter = computePositionOfLineAndCharacter; + function getLineStarts(sourceFile) { + return sourceFile.lineMap || (sourceFile.lineMap = computeLineStarts(sourceFile.text)); + } + ts.getLineStarts = getLineStarts; + function computeLineAndCharacterOfPosition(lineStarts, position) { + var lineNumber = ts.binarySearch(lineStarts, position, ts.identity, ts.compareValues); + if (lineNumber < 0) { + lineNumber = ~lineNumber - 1; + ts.Debug.assert(lineNumber !== -1, "position cannot precede the beginning of the file"); + } + return { + line: lineNumber, + character: position - lineStarts[lineNumber] + }; + } + ts.computeLineAndCharacterOfPosition = computeLineAndCharacterOfPosition; + function getLineAndCharacterOfPosition(sourceFile, position) { + return computeLineAndCharacterOfPosition(getLineStarts(sourceFile), position); + } + ts.getLineAndCharacterOfPosition = getLineAndCharacterOfPosition; + function isWhiteSpaceLike(ch) { + return isWhiteSpaceSingleLine(ch) || isLineBreak(ch); + } + ts.isWhiteSpaceLike = isWhiteSpaceLike; + function isWhiteSpaceSingleLine(ch) { + return ch === 32 || + ch === 9 || + ch === 11 || + ch === 12 || + ch === 160 || + ch === 133 || + ch === 5760 || + ch >= 8192 && ch <= 8203 || + ch === 8239 || + ch === 8287 || + ch === 12288 || + ch === 65279; + } + ts.isWhiteSpaceSingleLine = isWhiteSpaceSingleLine; + function isLineBreak(ch) { + return ch === 10 || + ch === 13 || + ch === 8232 || + ch === 8233; + } + ts.isLineBreak = isLineBreak; + function isDigit(ch) { + return ch >= 48 && ch <= 57; + } + function isOctalDigit(ch) { + return ch >= 48 && ch <= 55; + } + ts.isOctalDigit = isOctalDigit; + function couldStartTrivia(text, pos) { + var ch = text.charCodeAt(pos); + switch (ch) { + case 13: + case 10: + case 9: + case 11: + case 12: + case 32: + case 47: + case 60: + case 124: + case 61: + case 62: + return true; + case 35: + return pos === 0; + default: + return ch > 127; + } + } + ts.couldStartTrivia = couldStartTrivia; + function skipTrivia(text, pos, stopAfterLineBreak, stopAtComments) { + if (stopAtComments === void 0) { stopAtComments = false; } + if (ts.positionIsSynthesized(pos)) { + return pos; + } + while (true) { + var ch = text.charCodeAt(pos); + switch (ch) { + case 13: + if (text.charCodeAt(pos + 1) === 10) { + pos++; + } + case 10: + pos++; + if (stopAfterLineBreak) { + return pos; + } + continue; + case 9: + case 11: + case 12: + case 32: + pos++; + continue; + case 47: + if (stopAtComments) { + break; + } + if (text.charCodeAt(pos + 1) === 47) { + pos += 2; + while (pos < text.length) { + if (isLineBreak(text.charCodeAt(pos))) { + break; + } + pos++; + } + continue; + } + if (text.charCodeAt(pos + 1) === 42) { + pos += 2; + while (pos < text.length) { + if (text.charCodeAt(pos) === 42 && text.charCodeAt(pos + 1) === 47) { + pos += 2; + break; + } + pos++; + } + continue; + } + break; + case 60: + case 124: + case 61: + case 62: + if (isConflictMarkerTrivia(text, pos)) { + pos = scanConflictMarkerTrivia(text, pos); + continue; + } + break; + case 35: + if (pos === 0 && isShebangTrivia(text, pos)) { + pos = scanShebangTrivia(text, pos); + continue; + } + break; + default: + if (ch > 127 && (isWhiteSpaceLike(ch))) { + pos++; + continue; + } + break; + } + return pos; + } + } + ts.skipTrivia = skipTrivia; + var mergeConflictMarkerLength = "<<<<<<<".length; + function isConflictMarkerTrivia(text, pos) { + ts.Debug.assert(pos >= 0); + if (pos === 0 || isLineBreak(text.charCodeAt(pos - 1))) { + var ch = text.charCodeAt(pos); + if ((pos + mergeConflictMarkerLength) < text.length) { + for (var i = 0; i < mergeConflictMarkerLength; i++) { + if (text.charCodeAt(pos + i) !== ch) { + return false; + } + } + return ch === 61 || + text.charCodeAt(pos + mergeConflictMarkerLength) === 32; + } + } + return false; + } + function scanConflictMarkerTrivia(text, pos, error) { + if (error) { + error(ts.Diagnostics.Merge_conflict_marker_encountered, pos, mergeConflictMarkerLength); + } + var ch = text.charCodeAt(pos); + var len = text.length; + if (ch === 60 || ch === 62) { + while (pos < len && !isLineBreak(text.charCodeAt(pos))) { + pos++; + } + } + else { + ts.Debug.assert(ch === 124 || ch === 61); + while (pos < len) { + var currentChar = text.charCodeAt(pos); + if ((currentChar === 61 || currentChar === 62) && currentChar !== ch && isConflictMarkerTrivia(text, pos)) { + break; + } + pos++; + } + } + return pos; + } + var shebangTriviaRegex = /^#!.*/; + function isShebangTrivia(text, pos) { + ts.Debug.assert(pos === 0); + return shebangTriviaRegex.test(text); + } + function scanShebangTrivia(text, pos) { + var shebang = shebangTriviaRegex.exec(text)[0]; + pos = pos + shebang.length; + return pos; + } + function iterateCommentRanges(reduce, text, pos, trailing, cb, state, initial) { + var pendingPos; + var pendingEnd; + var pendingKind; + var pendingHasTrailingNewLine; + var hasPendingCommentRange = false; + var collecting = trailing || pos === 0; + var accumulator = initial; + scan: while (pos >= 0 && pos < text.length) { + var ch = text.charCodeAt(pos); + switch (ch) { + case 13: + if (text.charCodeAt(pos + 1) === 10) { + pos++; + } + case 10: + pos++; + if (trailing) { + break scan; + } + collecting = true; + if (hasPendingCommentRange) { + pendingHasTrailingNewLine = true; + } + continue; + case 9: + case 11: + case 12: + case 32: + pos++; + continue; + case 47: + var nextChar = text.charCodeAt(pos + 1); + var hasTrailingNewLine = false; + if (nextChar === 47 || nextChar === 42) { + var kind = nextChar === 47 ? 2 : 3; + var startPos = pos; + pos += 2; + if (nextChar === 47) { + while (pos < text.length) { + if (isLineBreak(text.charCodeAt(pos))) { + hasTrailingNewLine = true; + break; + } + pos++; + } + } + else { + while (pos < text.length) { + if (text.charCodeAt(pos) === 42 && text.charCodeAt(pos + 1) === 47) { + pos += 2; + break; + } + pos++; + } + } + if (collecting) { + if (hasPendingCommentRange) { + accumulator = cb(pendingPos, pendingEnd, pendingKind, pendingHasTrailingNewLine, state, accumulator); + if (!reduce && accumulator) { + return accumulator; + } + } + pendingPos = startPos; + pendingEnd = pos; + pendingKind = kind; + pendingHasTrailingNewLine = hasTrailingNewLine; + hasPendingCommentRange = true; + } + continue; + } + break scan; + default: + if (ch > 127 && (isWhiteSpaceLike(ch))) { + if (hasPendingCommentRange && isLineBreak(ch)) { + pendingHasTrailingNewLine = true; + } + pos++; + continue; + } + break scan; + } + } + if (hasPendingCommentRange) { + accumulator = cb(pendingPos, pendingEnd, pendingKind, pendingHasTrailingNewLine, state, accumulator); + } + return accumulator; + } + function forEachLeadingCommentRange(text, pos, cb, state) { + return iterateCommentRanges(false, text, pos, false, cb, state); + } + ts.forEachLeadingCommentRange = forEachLeadingCommentRange; + function forEachTrailingCommentRange(text, pos, cb, state) { + return iterateCommentRanges(false, text, pos, true, cb, state); + } + ts.forEachTrailingCommentRange = forEachTrailingCommentRange; + function reduceEachLeadingCommentRange(text, pos, cb, state, initial) { + return iterateCommentRanges(true, text, pos, false, cb, state, initial); + } + ts.reduceEachLeadingCommentRange = reduceEachLeadingCommentRange; + function reduceEachTrailingCommentRange(text, pos, cb, state, initial) { + return iterateCommentRanges(true, text, pos, true, cb, state, initial); + } + ts.reduceEachTrailingCommentRange = reduceEachTrailingCommentRange; + function appendCommentRange(pos, end, kind, hasTrailingNewLine, _state, comments) { + if (!comments) { + comments = []; + } + comments.push({ kind: kind, pos: pos, end: end, hasTrailingNewLine: hasTrailingNewLine }); + return comments; + } + function getLeadingCommentRanges(text, pos) { + return reduceEachLeadingCommentRange(text, pos, appendCommentRange, undefined, undefined); + } + ts.getLeadingCommentRanges = getLeadingCommentRanges; + function getTrailingCommentRanges(text, pos) { + return reduceEachTrailingCommentRange(text, pos, appendCommentRange, undefined, undefined); + } + ts.getTrailingCommentRanges = getTrailingCommentRanges; + function getShebang(text) { + var match = shebangTriviaRegex.exec(text); + if (match) { + return match[0]; + } + } + ts.getShebang = getShebang; + function isIdentifierStart(ch, languageVersion) { + return ch >= 65 && ch <= 90 || ch >= 97 && ch <= 122 || + ch === 36 || ch === 95 || + ch > 127 && isUnicodeIdentifierStart(ch, languageVersion); + } + ts.isIdentifierStart = isIdentifierStart; + function isIdentifierPart(ch, languageVersion) { + return ch >= 65 && ch <= 90 || ch >= 97 && ch <= 122 || + ch >= 48 && ch <= 57 || ch === 36 || ch === 95 || + ch > 127 && isUnicodeIdentifierPart(ch, languageVersion); + } + ts.isIdentifierPart = isIdentifierPart; + function isIdentifierText(name, languageVersion) { + if (!isIdentifierStart(name.charCodeAt(0), languageVersion)) { + return false; + } + for (var i = 1; i < name.length; i++) { + if (!isIdentifierPart(name.charCodeAt(i), languageVersion)) { + return false; + } + } + return true; + } + ts.isIdentifierText = isIdentifierText; + function createScanner(languageVersion, skipTrivia, languageVariant, textInitial, onError, start, length) { + if (languageVariant === void 0) { languageVariant = 0; } + var text = textInitial; + var pos; + var end; + var startPos; + var tokenPos; + var token; + var tokenValue; + var tokenFlags; + var inJSDocType = 0; + setText(text, start, length); + return { + getStartPos: function () { return startPos; }, + getTextPos: function () { return pos; }, + getToken: function () { return token; }, + getTokenPos: function () { return tokenPos; }, + getTokenText: function () { return text.substring(tokenPos, pos); }, + getTokenValue: function () { return tokenValue; }, + hasExtendedUnicodeEscape: function () { return (tokenFlags & 8) !== 0; }, + hasPrecedingLineBreak: function () { return (tokenFlags & 1) !== 0; }, + isIdentifier: function () { return token === 72 || token > 108; }, + isReservedWord: function () { return token >= 73 && token <= 108; }, + isUnterminated: function () { return (tokenFlags & 4) !== 0; }, + getTokenFlags: function () { return tokenFlags; }, + reScanGreaterToken: reScanGreaterToken, + reScanSlashToken: reScanSlashToken, + reScanTemplateToken: reScanTemplateToken, + scanJsxIdentifier: scanJsxIdentifier, + scanJsxAttributeValue: scanJsxAttributeValue, + reScanJsxToken: reScanJsxToken, + scanJsxToken: scanJsxToken, + scanJSDocToken: scanJSDocToken, + scan: scan, + getText: getText, + setText: setText, + setScriptTarget: setScriptTarget, + setLanguageVariant: setLanguageVariant, + setOnError: setOnError, + setTextPos: setTextPos, + setInJSDocType: setInJSDocType, + tryScan: tryScan, + lookAhead: lookAhead, + scanRange: scanRange, + }; + function error(message, errPos, length) { + if (errPos === void 0) { errPos = pos; } + if (onError) { + var oldPos = pos; + pos = errPos; + onError(message, length || 0); + pos = oldPos; + } + } + function scanNumberFragment() { + var start = pos; + var allowSeparator = false; + var isPreviousTokenSeparator = false; + var result = ""; + while (true) { + var ch = text.charCodeAt(pos); + if (ch === 95) { + tokenFlags |= 512; + if (allowSeparator) { + allowSeparator = false; + isPreviousTokenSeparator = true; + result += text.substring(start, pos); + } + else if (isPreviousTokenSeparator) { + error(ts.Diagnostics.Multiple_consecutive_numeric_separators_are_not_permitted, pos, 1); + } + else { + error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos, 1); + } + pos++; + start = pos; + continue; + } + if (isDigit(ch)) { + allowSeparator = true; + isPreviousTokenSeparator = false; + pos++; + continue; + } + break; + } + if (text.charCodeAt(pos - 1) === 95) { + error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos - 1, 1); + } + return result + text.substring(start, pos); + } + function scanNumber() { + var start = pos; + var mainFragment = scanNumberFragment(); + var decimalFragment; + var scientificFragment; + if (text.charCodeAt(pos) === 46) { + pos++; + decimalFragment = scanNumberFragment(); + } + var end = pos; + if (text.charCodeAt(pos) === 69 || text.charCodeAt(pos) === 101) { + pos++; + tokenFlags |= 16; + if (text.charCodeAt(pos) === 43 || text.charCodeAt(pos) === 45) + pos++; + var preNumericPart = pos; + var finalFragment = scanNumberFragment(); + if (!finalFragment) { + error(ts.Diagnostics.Digit_expected); + } + else { + scientificFragment = text.substring(end, preNumericPart) + finalFragment; + end = pos; + } + } + var result; + if (tokenFlags & 512) { + result = mainFragment; + if (decimalFragment) { + result += "." + decimalFragment; + } + if (scientificFragment) { + result += scientificFragment; + } + } + else { + result = text.substring(start, end); + } + if (decimalFragment !== undefined || tokenFlags & 16) { + return { + type: 8, + value: "" + +result + }; + } + else { + tokenValue = result; + var type = checkBigIntSuffix(); + return { type: type, value: tokenValue }; + } + } + function scanOctalDigits() { + var start = pos; + while (isOctalDigit(text.charCodeAt(pos))) { + pos++; + } + return +(text.substring(start, pos)); + } + function scanExactNumberOfHexDigits(count, canHaveSeparators) { + var valueString = scanHexDigits(count, false, canHaveSeparators); + return valueString ? parseInt(valueString, 16) : -1; + } + function scanMinimumNumberOfHexDigits(count, canHaveSeparators) { + return scanHexDigits(count, true, canHaveSeparators); + } + function scanHexDigits(minCount, scanAsManyAsPossible, canHaveSeparators) { + var valueChars = []; + var allowSeparator = false; + var isPreviousTokenSeparator = false; + while (valueChars.length < minCount || scanAsManyAsPossible) { + var ch = text.charCodeAt(pos); + if (canHaveSeparators && ch === 95) { + tokenFlags |= 512; + if (allowSeparator) { + allowSeparator = false; + isPreviousTokenSeparator = true; + } + else if (isPreviousTokenSeparator) { + error(ts.Diagnostics.Multiple_consecutive_numeric_separators_are_not_permitted, pos, 1); + } + else { + error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos, 1); + } + pos++; + continue; + } + allowSeparator = canHaveSeparators; + if (ch >= 65 && ch <= 70) { + ch += 97 - 65; + } + else if (!((ch >= 48 && ch <= 57) || + (ch >= 97 && ch <= 102))) { + break; + } + valueChars.push(ch); + pos++; + isPreviousTokenSeparator = false; + } + if (valueChars.length < minCount) { + valueChars = []; + } + if (text.charCodeAt(pos - 1) === 95) { + error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos - 1, 1); + } + return String.fromCharCode.apply(String, valueChars); + } + function scanString(jsxAttributeString) { + if (jsxAttributeString === void 0) { jsxAttributeString = false; } + var quote = text.charCodeAt(pos); + pos++; + var result = ""; + var start = pos; + while (true) { + if (pos >= end) { + result += text.substring(start, pos); + tokenFlags |= 4; + error(ts.Diagnostics.Unterminated_string_literal); + break; + } + var ch = text.charCodeAt(pos); + if (ch === quote) { + result += text.substring(start, pos); + pos++; + break; + } + if (ch === 92 && !jsxAttributeString) { + result += text.substring(start, pos); + result += scanEscapeSequence(); + start = pos; + continue; + } + if (isLineBreak(ch) && !jsxAttributeString) { + result += text.substring(start, pos); + tokenFlags |= 4; + error(ts.Diagnostics.Unterminated_string_literal); + break; + } + pos++; + } + return result; + } + function scanTemplateAndSetTokenValue() { + var startedWithBacktick = text.charCodeAt(pos) === 96; + pos++; + var start = pos; + var contents = ""; + var resultingToken; + while (true) { + if (pos >= end) { + contents += text.substring(start, pos); + tokenFlags |= 4; + error(ts.Diagnostics.Unterminated_template_literal); + resultingToken = startedWithBacktick ? 14 : 17; + break; + } + var currChar = text.charCodeAt(pos); + if (currChar === 96) { + contents += text.substring(start, pos); + pos++; + resultingToken = startedWithBacktick ? 14 : 17; + break; + } + if (currChar === 36 && pos + 1 < end && text.charCodeAt(pos + 1) === 123) { + contents += text.substring(start, pos); + pos += 2; + resultingToken = startedWithBacktick ? 15 : 16; + break; + } + if (currChar === 92) { + contents += text.substring(start, pos); + contents += scanEscapeSequence(); + start = pos; + continue; + } + if (currChar === 13) { + contents += text.substring(start, pos); + pos++; + if (pos < end && text.charCodeAt(pos) === 10) { + pos++; + } + contents += "\n"; + start = pos; + continue; + } + pos++; + } + ts.Debug.assert(resultingToken !== undefined); + tokenValue = contents; + return resultingToken; + } + function scanEscapeSequence() { + pos++; + if (pos >= end) { + error(ts.Diagnostics.Unexpected_end_of_text); + return ""; + } + var ch = text.charCodeAt(pos); + pos++; + switch (ch) { + case 48: + return "\0"; + case 98: + return "\b"; + case 116: + return "\t"; + case 110: + return "\n"; + case 118: + return "\v"; + case 102: + return "\f"; + case 114: + return "\r"; + case 39: + return "\'"; + case 34: + return "\""; + case 117: + if (pos < end && text.charCodeAt(pos) === 123) { + tokenFlags |= 8; + pos++; + return scanExtendedUnicodeEscape(); + } + return scanHexadecimalEscape(4); + case 120: + return scanHexadecimalEscape(2); + case 13: + if (pos < end && text.charCodeAt(pos) === 10) { + pos++; + } + case 10: + case 8232: + case 8233: + return ""; + default: + return String.fromCharCode(ch); + } + } + function scanHexadecimalEscape(numDigits) { + var escapedValue = scanExactNumberOfHexDigits(numDigits, false); + if (escapedValue >= 0) { + return String.fromCharCode(escapedValue); + } + else { + error(ts.Diagnostics.Hexadecimal_digit_expected); + return ""; + } + } + function scanExtendedUnicodeEscape() { + var escapedValueString = scanMinimumNumberOfHexDigits(1, false); + var escapedValue = escapedValueString ? parseInt(escapedValueString, 16) : -1; + var isInvalidExtendedEscape = false; + if (escapedValue < 0) { + error(ts.Diagnostics.Hexadecimal_digit_expected); + isInvalidExtendedEscape = true; + } + else if (escapedValue > 0x10FFFF) { + error(ts.Diagnostics.An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive); + isInvalidExtendedEscape = true; + } + if (pos >= end) { + error(ts.Diagnostics.Unexpected_end_of_text); + isInvalidExtendedEscape = true; + } + else if (text.charCodeAt(pos) === 125) { + pos++; + } + else { + error(ts.Diagnostics.Unterminated_Unicode_escape_sequence); + isInvalidExtendedEscape = true; + } + if (isInvalidExtendedEscape) { + return ""; + } + return utf16EncodeAsString(escapedValue); + } + function utf16EncodeAsString(codePoint) { + ts.Debug.assert(0x0 <= codePoint && codePoint <= 0x10FFFF); + if (codePoint <= 65535) { + return String.fromCharCode(codePoint); + } + var codeUnit1 = Math.floor((codePoint - 65536) / 1024) + 0xD800; + var codeUnit2 = ((codePoint - 65536) % 1024) + 0xDC00; + return String.fromCharCode(codeUnit1, codeUnit2); + } + function peekUnicodeEscape() { + if (pos + 5 < end && text.charCodeAt(pos + 1) === 117) { + var start_1 = pos; + pos += 2; + var value = scanExactNumberOfHexDigits(4, false); + pos = start_1; + return value; + } + return -1; + } + function scanIdentifierParts() { + var result = ""; + var start = pos; + while (pos < end) { + var ch = text.charCodeAt(pos); + if (isIdentifierPart(ch, languageVersion)) { + pos++; + } + else if (ch === 92) { + ch = peekUnicodeEscape(); + if (!(ch >= 0 && isIdentifierPart(ch, languageVersion))) { + break; + } + result += text.substring(start, pos); + result += String.fromCharCode(ch); + pos += 6; + start = pos; + } + else { + break; + } + } + result += text.substring(start, pos); + return result; + } + function getIdentifierToken() { + var len = tokenValue.length; + if (len >= 2 && len <= 11) { + var ch = tokenValue.charCodeAt(0); + if (ch >= 97 && ch <= 122) { + var keyword = textToKeyword.get(tokenValue); + if (keyword !== undefined) { + return token = keyword; + } + } + } + return token = 72; + } + function scanBinaryOrOctalDigits(base) { + var value = ""; + var separatorAllowed = false; + var isPreviousTokenSeparator = false; + while (true) { + var ch = text.charCodeAt(pos); + if (ch === 95) { + tokenFlags |= 512; + if (separatorAllowed) { + separatorAllowed = false; + isPreviousTokenSeparator = true; + } + else if (isPreviousTokenSeparator) { + error(ts.Diagnostics.Multiple_consecutive_numeric_separators_are_not_permitted, pos, 1); + } + else { + error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos, 1); + } + pos++; + continue; + } + separatorAllowed = true; + if (!isDigit(ch) || ch - 48 >= base) { + break; + } + value += text[pos]; + pos++; + isPreviousTokenSeparator = false; + } + if (text.charCodeAt(pos - 1) === 95) { + error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos - 1, 1); + } + return value; + } + function checkBigIntSuffix() { + if (text.charCodeAt(pos) === 110) { + tokenValue += "n"; + if (tokenFlags & 384) { + tokenValue = ts.parsePseudoBigInt(tokenValue) + "n"; + } + pos++; + return 9; + } + else { + var numericValue = tokenFlags & 128 + ? parseInt(tokenValue.slice(2), 2) + : tokenFlags & 256 + ? parseInt(tokenValue.slice(2), 8) + : +tokenValue; + tokenValue = "" + numericValue; + return 8; + } + } + function scan() { + var _a; + startPos = pos; + tokenFlags = 0; + var asteriskSeen = false; + while (true) { + tokenPos = pos; + if (pos >= end) { + return token = 1; + } + var ch = text.charCodeAt(pos); + if (ch === 35 && pos === 0 && isShebangTrivia(text, pos)) { + pos = scanShebangTrivia(text, pos); + if (skipTrivia) { + continue; + } + else { + return token = 6; + } + } + switch (ch) { + case 10: + case 13: + tokenFlags |= 1; + if (skipTrivia) { + pos++; + continue; + } + else { + if (ch === 13 && pos + 1 < end && text.charCodeAt(pos + 1) === 10) { + pos += 2; + } + else { + pos++; + } + return token = 4; + } + case 9: + case 11: + case 12: + case 32: + case 160: + case 5760: + case 8192: + case 8193: + case 8194: + case 8195: + case 8196: + case 8197: + case 8198: + case 8199: + case 8200: + case 8201: + case 8202: + case 8203: + case 8239: + case 8287: + case 12288: + case 65279: + if (skipTrivia) { + pos++; + continue; + } + else { + while (pos < end && isWhiteSpaceSingleLine(text.charCodeAt(pos))) { + pos++; + } + return token = 5; + } + case 33: + if (text.charCodeAt(pos + 1) === 61) { + if (text.charCodeAt(pos + 2) === 61) { + return pos += 3, token = 36; + } + return pos += 2, token = 34; + } + pos++; + return token = 52; + case 34: + case 39: + tokenValue = scanString(); + return token = 10; + case 96: + return token = scanTemplateAndSetTokenValue(); + case 37: + if (text.charCodeAt(pos + 1) === 61) { + return pos += 2, token = 65; + } + pos++; + return token = 43; + case 38: + if (text.charCodeAt(pos + 1) === 38) { + return pos += 2, token = 54; + } + if (text.charCodeAt(pos + 1) === 61) { + return pos += 2, token = 69; + } + pos++; + return token = 49; + case 40: + pos++; + return token = 20; + case 41: + pos++; + return token = 21; + case 42: + if (text.charCodeAt(pos + 1) === 61) { + return pos += 2, token = 62; + } + if (text.charCodeAt(pos + 1) === 42) { + if (text.charCodeAt(pos + 2) === 61) { + return pos += 3, token = 63; + } + return pos += 2, token = 41; + } + pos++; + if (inJSDocType && !asteriskSeen && (tokenFlags & 1)) { + asteriskSeen = true; + continue; + } + return token = 40; + case 43: + if (text.charCodeAt(pos + 1) === 43) { + return pos += 2, token = 44; + } + if (text.charCodeAt(pos + 1) === 61) { + return pos += 2, token = 60; + } + pos++; + return token = 38; + case 44: + pos++; + return token = 27; + case 45: + if (text.charCodeAt(pos + 1) === 45) { + return pos += 2, token = 45; + } + if (text.charCodeAt(pos + 1) === 61) { + return pos += 2, token = 61; + } + pos++; + return token = 39; + case 46: + if (isDigit(text.charCodeAt(pos + 1))) { + tokenValue = scanNumber().value; + return token = 8; + } + if (text.charCodeAt(pos + 1) === 46 && text.charCodeAt(pos + 2) === 46) { + return pos += 3, token = 25; + } + pos++; + return token = 24; + case 47: + if (text.charCodeAt(pos + 1) === 47) { + pos += 2; + while (pos < end) { + if (isLineBreak(text.charCodeAt(pos))) { + break; + } + pos++; + } + if (skipTrivia) { + continue; + } + else { + return token = 2; + } + } + if (text.charCodeAt(pos + 1) === 42) { + pos += 2; + if (text.charCodeAt(pos) === 42 && text.charCodeAt(pos + 1) !== 47) { + tokenFlags |= 2; + } + var commentClosed = false; + while (pos < end) { + var ch_1 = text.charCodeAt(pos); + if (ch_1 === 42 && text.charCodeAt(pos + 1) === 47) { + pos += 2; + commentClosed = true; + break; + } + if (isLineBreak(ch_1)) { + tokenFlags |= 1; + } + pos++; + } + if (!commentClosed) { + error(ts.Diagnostics.Asterisk_Slash_expected); + } + if (skipTrivia) { + continue; + } + else { + if (!commentClosed) { + tokenFlags |= 4; + } + return token = 3; + } + } + if (text.charCodeAt(pos + 1) === 61) { + return pos += 2, token = 64; + } + pos++; + return token = 42; + case 48: + if (pos + 2 < end && (text.charCodeAt(pos + 1) === 88 || text.charCodeAt(pos + 1) === 120)) { + pos += 2; + tokenValue = scanMinimumNumberOfHexDigits(1, true); + if (!tokenValue) { + error(ts.Diagnostics.Hexadecimal_digit_expected); + tokenValue = "0"; + } + tokenValue = "0x" + tokenValue; + tokenFlags |= 64; + return token = checkBigIntSuffix(); + } + else if (pos + 2 < end && (text.charCodeAt(pos + 1) === 66 || text.charCodeAt(pos + 1) === 98)) { + pos += 2; + tokenValue = scanBinaryOrOctalDigits(2); + if (!tokenValue) { + error(ts.Diagnostics.Binary_digit_expected); + tokenValue = "0"; + } + tokenValue = "0b" + tokenValue; + tokenFlags |= 128; + return token = checkBigIntSuffix(); + } + else if (pos + 2 < end && (text.charCodeAt(pos + 1) === 79 || text.charCodeAt(pos + 1) === 111)) { + pos += 2; + tokenValue = scanBinaryOrOctalDigits(8); + if (!tokenValue) { + error(ts.Diagnostics.Octal_digit_expected); + tokenValue = "0"; + } + tokenValue = "0o" + tokenValue; + tokenFlags |= 256; + return token = checkBigIntSuffix(); + } + if (pos + 1 < end && isOctalDigit(text.charCodeAt(pos + 1))) { + tokenValue = "" + scanOctalDigits(); + tokenFlags |= 32; + return token = 8; + } + case 49: + case 50: + case 51: + case 52: + case 53: + case 54: + case 55: + case 56: + case 57: + (_a = scanNumber(), token = _a.type, tokenValue = _a.value); + return token; + case 58: + pos++; + return token = 57; + case 59: + pos++; + return token = 26; + case 60: + if (isConflictMarkerTrivia(text, pos)) { + pos = scanConflictMarkerTrivia(text, pos, error); + if (skipTrivia) { + continue; + } + else { + return token = 7; + } + } + if (text.charCodeAt(pos + 1) === 60) { + if (text.charCodeAt(pos + 2) === 61) { + return pos += 3, token = 66; + } + return pos += 2, token = 46; + } + if (text.charCodeAt(pos + 1) === 61) { + return pos += 2, token = 31; + } + if (languageVariant === 1 && + text.charCodeAt(pos + 1) === 47 && + text.charCodeAt(pos + 2) !== 42) { + return pos += 2, token = 29; + } + pos++; + return token = 28; + case 61: + if (isConflictMarkerTrivia(text, pos)) { + pos = scanConflictMarkerTrivia(text, pos, error); + if (skipTrivia) { + continue; + } + else { + return token = 7; + } + } + if (text.charCodeAt(pos + 1) === 61) { + if (text.charCodeAt(pos + 2) === 61) { + return pos += 3, token = 35; + } + return pos += 2, token = 33; + } + if (text.charCodeAt(pos + 1) === 62) { + return pos += 2, token = 37; + } + pos++; + return token = 59; + case 62: + if (isConflictMarkerTrivia(text, pos)) { + pos = scanConflictMarkerTrivia(text, pos, error); + if (skipTrivia) { + continue; + } + else { + return token = 7; + } + } + pos++; + return token = 30; + case 63: + pos++; + return token = 56; + case 91: + pos++; + return token = 22; + case 93: + pos++; + return token = 23; + case 94: + if (text.charCodeAt(pos + 1) === 61) { + return pos += 2, token = 71; + } + pos++; + return token = 51; + case 123: + pos++; + return token = 18; + case 124: + if (isConflictMarkerTrivia(text, pos)) { + pos = scanConflictMarkerTrivia(text, pos, error); + if (skipTrivia) { + continue; + } + else { + return token = 7; + } + } + if (text.charCodeAt(pos + 1) === 124) { + return pos += 2, token = 55; + } + if (text.charCodeAt(pos + 1) === 61) { + return pos += 2, token = 70; + } + pos++; + return token = 50; + case 125: + pos++; + return token = 19; + case 126: + pos++; + return token = 53; + case 64: + pos++; + return token = 58; + case 92: + var cookedChar = peekUnicodeEscape(); + if (cookedChar >= 0 && isIdentifierStart(cookedChar, languageVersion)) { + pos += 6; + tokenValue = String.fromCharCode(cookedChar) + scanIdentifierParts(); + return token = getIdentifierToken(); + } + error(ts.Diagnostics.Invalid_character); + pos++; + return token = 0; + default: + if (isIdentifierStart(ch, languageVersion)) { + pos++; + while (pos < end && isIdentifierPart(ch = text.charCodeAt(pos), languageVersion)) + pos++; + tokenValue = text.substring(tokenPos, pos); + if (ch === 92) { + tokenValue += scanIdentifierParts(); + } + return token = getIdentifierToken(); + } + else if (isWhiteSpaceSingleLine(ch)) { + pos++; + continue; + } + else if (isLineBreak(ch)) { + tokenFlags |= 1; + pos++; + continue; + } + error(ts.Diagnostics.Invalid_character); + pos++; + return token = 0; + } + } + } + function reScanGreaterToken() { + if (token === 30) { + if (text.charCodeAt(pos) === 62) { + if (text.charCodeAt(pos + 1) === 62) { + if (text.charCodeAt(pos + 2) === 61) { + return pos += 3, token = 68; + } + return pos += 2, token = 48; + } + if (text.charCodeAt(pos + 1) === 61) { + return pos += 2, token = 67; + } + pos++; + return token = 47; + } + if (text.charCodeAt(pos) === 61) { + pos++; + return token = 32; + } + } + return token; + } + function reScanSlashToken() { + if (token === 42 || token === 64) { + var p = tokenPos + 1; + var inEscape = false; + var inCharacterClass = false; + while (true) { + if (p >= end) { + tokenFlags |= 4; + error(ts.Diagnostics.Unterminated_regular_expression_literal); + break; + } + var ch = text.charCodeAt(p); + if (isLineBreak(ch)) { + tokenFlags |= 4; + error(ts.Diagnostics.Unterminated_regular_expression_literal); + break; + } + if (inEscape) { + inEscape = false; + } + else if (ch === 47 && !inCharacterClass) { + p++; + break; + } + else if (ch === 91) { + inCharacterClass = true; + } + else if (ch === 92) { + inEscape = true; + } + else if (ch === 93) { + inCharacterClass = false; + } + p++; + } + while (p < end && isIdentifierPart(text.charCodeAt(p), languageVersion)) { + p++; + } + pos = p; + tokenValue = text.substring(tokenPos, pos); + token = 13; + } + return token; + } + function reScanTemplateToken() { + ts.Debug.assert(token === 19, "'reScanTemplateToken' should only be called on a '}'"); + pos = tokenPos; + return token = scanTemplateAndSetTokenValue(); + } + function reScanJsxToken() { + pos = tokenPos = startPos; + return token = scanJsxToken(); + } + function scanJsxToken() { + startPos = tokenPos = pos; + if (pos >= end) { + return token = 1; + } + var char = text.charCodeAt(pos); + if (char === 60) { + if (text.charCodeAt(pos + 1) === 47) { + pos += 2; + return token = 29; + } + pos++; + return token = 28; + } + if (char === 123) { + pos++; + return token = 18; + } + var firstNonWhitespace = 0; + while (pos < end) { + char = text.charCodeAt(pos); + if (char === 123) { + break; + } + if (char === 60) { + if (isConflictMarkerTrivia(text, pos)) { + pos = scanConflictMarkerTrivia(text, pos, error); + return token = 7; + } + break; + } + if (isLineBreak(char) && firstNonWhitespace === 0) { + firstNonWhitespace = -1; + } + else if (!isWhiteSpaceLike(char)) { + firstNonWhitespace = pos; + } + pos++; + } + return firstNonWhitespace === -1 ? 12 : 11; + } + function scanJsxIdentifier() { + if (tokenIsIdentifierOrKeyword(token)) { + var firstCharPosition = pos; + while (pos < end) { + var ch = text.charCodeAt(pos); + if (ch === 45 || ((firstCharPosition === pos) ? isIdentifierStart(ch, languageVersion) : isIdentifierPart(ch, languageVersion))) { + pos++; + } + else { + break; + } + } + tokenValue += text.substring(firstCharPosition, pos); + } + return token; + } + function scanJsxAttributeValue() { + startPos = pos; + switch (text.charCodeAt(pos)) { + case 34: + case 39: + tokenValue = scanString(true); + return token = 10; + default: + return scan(); + } + } + function scanJSDocToken() { + startPos = tokenPos = pos; + tokenFlags = 0; + if (pos >= end) { + return token = 1; + } + var ch = text.charCodeAt(pos); + pos++; + switch (ch) { + case 9: + case 11: + case 12: + case 32: + while (pos < end && isWhiteSpaceSingleLine(text.charCodeAt(pos))) { + pos++; + } + return token = 5; + case 64: + return token = 58; + case 10: + case 13: + tokenFlags |= 1; + return token = 4; + case 42: + return token = 40; + case 123: + return token = 18; + case 125: + return token = 19; + case 91: + return token = 22; + case 93: + return token = 23; + case 60: + return token = 28; + case 61: + return token = 59; + case 44: + return token = 27; + case 46: + return token = 24; + case 96: + while (pos < end && text.charCodeAt(pos) !== 96) { + pos++; + } + tokenValue = text.substring(tokenPos + 1, pos); + pos++; + return token = 14; + } + if (isIdentifierStart(ch, 6)) { + while (isIdentifierPart(text.charCodeAt(pos), 6) && pos < end) { + pos++; + } + tokenValue = text.substring(tokenPos, pos); + return token = getIdentifierToken(); + } + else { + return token = 0; + } + } + function speculationHelper(callback, isLookahead) { + var savePos = pos; + var saveStartPos = startPos; + var saveTokenPos = tokenPos; + var saveToken = token; + var saveTokenValue = tokenValue; + var saveTokenFlags = tokenFlags; + var result = callback(); + if (!result || isLookahead) { + pos = savePos; + startPos = saveStartPos; + tokenPos = saveTokenPos; + token = saveToken; + tokenValue = saveTokenValue; + tokenFlags = saveTokenFlags; + } + return result; + } + function scanRange(start, length, callback) { + var saveEnd = end; + var savePos = pos; + var saveStartPos = startPos; + var saveTokenPos = tokenPos; + var saveToken = token; + var saveTokenValue = tokenValue; + var saveTokenFlags = tokenFlags; + setText(text, start, length); + var result = callback(); + end = saveEnd; + pos = savePos; + startPos = saveStartPos; + tokenPos = saveTokenPos; + token = saveToken; + tokenValue = saveTokenValue; + tokenFlags = saveTokenFlags; + return result; + } + function lookAhead(callback) { + return speculationHelper(callback, true); + } + function tryScan(callback) { + return speculationHelper(callback, false); + } + function getText() { + return text; + } + function setText(newText, start, length) { + text = newText || ""; + end = length === undefined ? text.length : start + length; + setTextPos(start || 0); + } + function setOnError(errorCallback) { + onError = errorCallback; + } + function setScriptTarget(scriptTarget) { + languageVersion = scriptTarget; + } + function setLanguageVariant(variant) { + languageVariant = variant; + } + function setTextPos(textPos) { + ts.Debug.assert(textPos >= 0); + pos = textPos; + startPos = textPos; + tokenPos = textPos; + token = 0; + tokenValue = undefined; + tokenFlags = 0; + } + function setInJSDocType(inType) { + inJSDocType += inType ? 1 : -1; + } + } + ts.createScanner = createScanner; +})(ts || (ts = {})); +var ts; +(function (ts) { + function isExternalModuleNameRelative(moduleName) { + return ts.pathIsRelative(moduleName) || ts.isRootedDiskPath(moduleName); + } + ts.isExternalModuleNameRelative = isExternalModuleNameRelative; + function sortAndDeduplicateDiagnostics(diagnostics) { + return ts.sortAndDeduplicate(diagnostics, ts.compareDiagnostics); + } + ts.sortAndDeduplicateDiagnostics = sortAndDeduplicateDiagnostics; +})(ts || (ts = {})); +(function (ts) { + ts.resolvingEmptyArray = []; + ts.emptyMap = ts.createMap(); + ts.emptyUnderscoreEscapedMap = ts.emptyMap; + ts.externalHelpersModuleNameText = "tslib"; + ts.defaultMaximumTruncationLength = 160; + function getDeclarationOfKind(symbol, kind) { + var declarations = symbol.declarations; + if (declarations) { + for (var _i = 0, declarations_1 = declarations; _i < declarations_1.length; _i++) { + var declaration = declarations_1[_i]; + if (declaration.kind === kind) { + return declaration; + } + } + } + return undefined; + } + ts.getDeclarationOfKind = getDeclarationOfKind; + function createUnderscoreEscapedMap() { + return new ts.MapCtr(); + } + ts.createUnderscoreEscapedMap = createUnderscoreEscapedMap; + function hasEntries(map) { + return !!map && !!map.size; + } + ts.hasEntries = hasEntries; + function createSymbolTable(symbols) { + var result = ts.createMap(); + if (symbols) { + for (var _i = 0, symbols_1 = symbols; _i < symbols_1.length; _i++) { + var symbol = symbols_1[_i]; + result.set(symbol.escapedName, symbol); + } + } + return result; + } + ts.createSymbolTable = createSymbolTable; + var stringWriter = createSingleLineStringWriter(); + function createSingleLineStringWriter() { + var str = ""; + var writeText = function (text) { return str += text; }; + return { + getText: function () { return str; }, + write: writeText, + rawWrite: writeText, + writeKeyword: writeText, + writeOperator: writeText, + writePunctuation: writeText, + writeSpace: writeText, + writeStringLiteral: writeText, + writeLiteral: writeText, + writeParameter: writeText, + writeProperty: writeText, + writeSymbol: function (s, _) { return writeText(s); }, + writeTrailingSemicolon: writeText, + writeComment: writeText, + getTextPos: function () { return str.length; }, + getLine: function () { return 0; }, + getColumn: function () { return 0; }, + getIndent: function () { return 0; }, + isAtStartOfLine: function () { return false; }, + writeLine: function () { return str += " "; }, + increaseIndent: ts.noop, + decreaseIndent: ts.noop, + clear: function () { return str = ""; }, + trackSymbol: ts.noop, + reportInaccessibleThisError: ts.noop, + reportInaccessibleUniqueSymbolError: ts.noop, + reportPrivateInBaseOfClassExpression: ts.noop, + }; + } + function toPath(fileName, basePath, getCanonicalFileName) { + var nonCanonicalizedPath = ts.isRootedDiskPath(fileName) + ? ts.normalizePath(fileName) + : ts.getNormalizedAbsolutePath(fileName, basePath); + return getCanonicalFileName(nonCanonicalizedPath); + } + ts.toPath = toPath; + function changesAffectModuleResolution(oldOptions, newOptions) { + return oldOptions.configFilePath !== newOptions.configFilePath || ts.moduleResolutionOptionDeclarations.some(function (o) { + return !ts.isJsonEqual(ts.getCompilerOptionValue(oldOptions, o), ts.getCompilerOptionValue(newOptions, o)); + }); + } + ts.changesAffectModuleResolution = changesAffectModuleResolution; + function findAncestor(node, callback) { + while (node) { + var result = callback(node); + if (result === "quit") { + return undefined; + } + else if (result) { + return node; + } + node = node.parent; + } + return undefined; + } + ts.findAncestor = findAncestor; + function forEachAncestor(node, callback) { + while (true) { + var res = callback(node); + if (res === "quit") + return undefined; + if (res !== undefined) + return res; + if (ts.isSourceFile(node)) + return undefined; + node = node.parent; + } + } + ts.forEachAncestor = forEachAncestor; + function forEachEntry(map, callback) { + var _a; + var iterator = map.entries(); + for (var _b = iterator.next(), pair = _b.value, done = _b.done; !done; _a = iterator.next(), pair = _a.value, done = _a.done, _a) { + var key = pair[0], value = pair[1]; + var result = callback(value, key); + if (result) { + return result; + } + } + return undefined; + } + ts.forEachEntry = forEachEntry; + function forEachKey(map, callback) { + var _a; + var iterator = map.keys(); + for (var _b = iterator.next(), key = _b.value, done = _b.done; !done; _a = iterator.next(), key = _a.value, done = _a.done, _a) { + var result = callback(key); + if (result) { + return result; + } + } + return undefined; + } + ts.forEachKey = forEachKey; + function copyEntries(source, target) { + source.forEach(function (value, key) { + target.set(key, value); + }); + } + ts.copyEntries = copyEntries; + function arrayToSet(array, makeKey) { + return ts.arrayToMap(array, makeKey || (function (s) { return s; }), function () { return true; }); + } + ts.arrayToSet = arrayToSet; + function cloneMap(map) { + var clone = ts.createMap(); + copyEntries(map, clone); + return clone; + } + ts.cloneMap = cloneMap; + function usingSingleLineStringWriter(action) { + var oldString = stringWriter.getText(); + try { + action(stringWriter); + return stringWriter.getText(); + } + finally { + stringWriter.clear(); + stringWriter.writeKeyword(oldString); + } + } + ts.usingSingleLineStringWriter = usingSingleLineStringWriter; + function getFullWidth(node) { + return node.end - node.pos; + } + ts.getFullWidth = getFullWidth; + function getResolvedModule(sourceFile, moduleNameText) { + return sourceFile && sourceFile.resolvedModules && sourceFile.resolvedModules.get(moduleNameText); + } + ts.getResolvedModule = getResolvedModule; + function setResolvedModule(sourceFile, moduleNameText, resolvedModule) { + if (!sourceFile.resolvedModules) { + sourceFile.resolvedModules = ts.createMap(); + } + sourceFile.resolvedModules.set(moduleNameText, resolvedModule); + } + ts.setResolvedModule = setResolvedModule; + function setResolvedTypeReferenceDirective(sourceFile, typeReferenceDirectiveName, resolvedTypeReferenceDirective) { + if (!sourceFile.resolvedTypeReferenceDirectiveNames) { + sourceFile.resolvedTypeReferenceDirectiveNames = ts.createMap(); + } + sourceFile.resolvedTypeReferenceDirectiveNames.set(typeReferenceDirectiveName, resolvedTypeReferenceDirective); + } + ts.setResolvedTypeReferenceDirective = setResolvedTypeReferenceDirective; + function projectReferenceIsEqualTo(oldRef, newRef) { + return oldRef.path === newRef.path && + !oldRef.prepend === !newRef.prepend && + !oldRef.circular === !newRef.circular; + } + ts.projectReferenceIsEqualTo = projectReferenceIsEqualTo; + function moduleResolutionIsEqualTo(oldResolution, newResolution) { + return oldResolution.isExternalLibraryImport === newResolution.isExternalLibraryImport && + oldResolution.extension === newResolution.extension && + oldResolution.resolvedFileName === newResolution.resolvedFileName && + oldResolution.originalPath === newResolution.originalPath && + packageIdIsEqual(oldResolution.packageId, newResolution.packageId); + } + ts.moduleResolutionIsEqualTo = moduleResolutionIsEqualTo; + function packageIdIsEqual(a, b) { + return a === b || !!a && !!b && a.name === b.name && a.subModuleName === b.subModuleName && a.version === b.version; + } + function packageIdToString(_a) { + var name = _a.name, subModuleName = _a.subModuleName, version = _a.version; + var fullName = subModuleName ? name + "/" + subModuleName : name; + return fullName + "@" + version; + } + ts.packageIdToString = packageIdToString; + function typeDirectiveIsEqualTo(oldResolution, newResolution) { + return oldResolution.resolvedFileName === newResolution.resolvedFileName && oldResolution.primary === newResolution.primary; + } + ts.typeDirectiveIsEqualTo = typeDirectiveIsEqualTo; + function hasChangesInResolutions(names, newResolutions, oldResolutions, comparer) { + ts.Debug.assert(names.length === newResolutions.length); + for (var i = 0; i < names.length; i++) { + var newResolution = newResolutions[i]; + var oldResolution = oldResolutions && oldResolutions.get(names[i]); + var changed = oldResolution + ? !newResolution || !comparer(oldResolution, newResolution) + : newResolution; + if (changed) { + return true; + } + } + return false; + } + ts.hasChangesInResolutions = hasChangesInResolutions; + function containsParseError(node) { + aggregateChildData(node); + return (node.flags & 131072) !== 0; + } + ts.containsParseError = containsParseError; + function aggregateChildData(node) { + if (!(node.flags & 262144)) { + var thisNodeOrAnySubNodesHasError = ((node.flags & 32768) !== 0) || + ts.forEachChild(node, containsParseError); + if (thisNodeOrAnySubNodesHasError) { + node.flags |= 131072; + } + node.flags |= 262144; + } + } + function getSourceFileOfNode(node) { + while (node && node.kind !== 279) { + node = node.parent; + } + return node; + } + ts.getSourceFileOfNode = getSourceFileOfNode; + function isStatementWithLocals(node) { + switch (node.kind) { + case 218: + case 246: + case 225: + case 226: + case 227: + return true; + } + return false; + } + ts.isStatementWithLocals = isStatementWithLocals; + function getStartPositionOfLine(line, sourceFile) { + ts.Debug.assert(line >= 0); + return ts.getLineStarts(sourceFile)[line]; + } + ts.getStartPositionOfLine = getStartPositionOfLine; + function nodePosToString(node) { + var file = getSourceFileOfNode(node); + var loc = ts.getLineAndCharacterOfPosition(file, node.pos); + return file.fileName + "(" + (loc.line + 1) + "," + (loc.character + 1) + ")"; + } + ts.nodePosToString = nodePosToString; + function getEndLinePosition(line, sourceFile) { + ts.Debug.assert(line >= 0); + var lineStarts = ts.getLineStarts(sourceFile); + var lineIndex = line; + var sourceText = sourceFile.text; + if (lineIndex + 1 === lineStarts.length) { + return sourceText.length - 1; + } + else { + var start = lineStarts[lineIndex]; + var pos = lineStarts[lineIndex + 1] - 1; + ts.Debug.assert(ts.isLineBreak(sourceText.charCodeAt(pos))); + while (start <= pos && ts.isLineBreak(sourceText.charCodeAt(pos))) { + pos--; + } + return pos; + } + } + ts.getEndLinePosition = getEndLinePosition; + function isFileLevelUniqueName(sourceFile, name, hasGlobalName) { + return !(hasGlobalName && hasGlobalName(name)) && !sourceFile.identifiers.has(name); + } + ts.isFileLevelUniqueName = isFileLevelUniqueName; + function nodeIsMissing(node) { + if (node === undefined) { + return true; + } + return node.pos === node.end && node.pos >= 0 && node.kind !== 1; + } + ts.nodeIsMissing = nodeIsMissing; + function nodeIsPresent(node) { + return !nodeIsMissing(node); + } + ts.nodeIsPresent = nodeIsPresent; + function addStatementsAfterPrologue(to, from) { + if (from === undefined || from.length === 0) + return to; + var statementIndex = 0; + for (; statementIndex < to.length; ++statementIndex) { + if (!isPrologueDirective(to[statementIndex])) { + break; + } + } + to.splice.apply(to, [statementIndex, 0].concat(from)); + return to; + } + ts.addStatementsAfterPrologue = addStatementsAfterPrologue; + function isRecognizedTripleSlashComment(text, commentPos, commentEnd) { + if (text.charCodeAt(commentPos + 1) === 47 && + commentPos + 2 < commentEnd && + text.charCodeAt(commentPos + 2) === 47) { + var textSubStr = text.substring(commentPos, commentEnd); + return textSubStr.match(ts.fullTripleSlashReferencePathRegEx) || + textSubStr.match(ts.fullTripleSlashAMDReferencePathRegEx) || + textSubStr.match(fullTripleSlashReferenceTypeReferenceDirectiveRegEx) || + textSubStr.match(defaultLibReferenceRegEx) ? + true : false; + } + return false; + } + ts.isRecognizedTripleSlashComment = isRecognizedTripleSlashComment; + function isPinnedComment(text, start) { + return text.charCodeAt(start + 1) === 42 && + text.charCodeAt(start + 2) === 33; + } + ts.isPinnedComment = isPinnedComment; + function getTokenPosOfNode(node, sourceFile, includeJsDoc) { + if (nodeIsMissing(node)) { + return node.pos; + } + if (ts.isJSDocNode(node)) { + return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos, false, true); + } + if (includeJsDoc && ts.hasJSDocNodes(node)) { + return getTokenPosOfNode(node.jsDoc[0]); + } + if (node.kind === 306 && node._children.length > 0) { + return getTokenPosOfNode(node._children[0], sourceFile, includeJsDoc); + } + return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos); + } + ts.getTokenPosOfNode = getTokenPosOfNode; + function getNonDecoratorTokenPosOfNode(node, sourceFile) { + if (nodeIsMissing(node) || !node.decorators) { + return getTokenPosOfNode(node, sourceFile); + } + return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.decorators.end); + } + ts.getNonDecoratorTokenPosOfNode = getNonDecoratorTokenPosOfNode; + function getSourceTextOfNodeFromSourceFile(sourceFile, node, includeTrivia) { + if (includeTrivia === void 0) { includeTrivia = false; } + return getTextOfNodeFromSourceText(sourceFile.text, node, includeTrivia); + } + ts.getSourceTextOfNodeFromSourceFile = getSourceTextOfNodeFromSourceFile; + function isJSDocTypeExpressionOrChild(node) { + return node.kind === 283 || (node.parent && isJSDocTypeExpressionOrChild(node.parent)); + } + function getTextOfNodeFromSourceText(sourceText, node, includeTrivia) { + if (includeTrivia === void 0) { includeTrivia = false; } + if (nodeIsMissing(node)) { + return ""; + } + var text = sourceText.substring(includeTrivia ? node.pos : ts.skipTrivia(sourceText, node.pos), node.end); + if (isJSDocTypeExpressionOrChild(node)) { + text = text.replace(/(^|\r?\n|\r)\s*\*\s*/g, "$1"); + } + return text; + } + ts.getTextOfNodeFromSourceText = getTextOfNodeFromSourceText; + function getTextOfNode(node, includeTrivia) { + if (includeTrivia === void 0) { includeTrivia = false; } + return getSourceTextOfNodeFromSourceFile(getSourceFileOfNode(node), node, includeTrivia); + } + ts.getTextOfNode = getTextOfNode; + function getPos(range) { + return range.pos; + } + function indexOfNode(nodeArray, node) { + return ts.binarySearch(nodeArray, node, getPos, ts.compareValues); + } + ts.indexOfNode = indexOfNode; + function getEmitFlags(node) { + var emitNode = node.emitNode; + return emitNode && emitNode.flags || 0; + } + ts.getEmitFlags = getEmitFlags; + function getLiteralText(node, sourceFile, neverAsciiEscape) { + if (!nodeIsSynthesized(node) && node.parent && !((ts.isNumericLiteral(node) && node.numericLiteralFlags & 512) || + ts.isBigIntLiteral(node))) { + return getSourceTextOfNodeFromSourceFile(sourceFile, node); + } + var escapeText = neverAsciiEscape || (getEmitFlags(node) & 16777216) ? escapeString : escapeNonAsciiString; + switch (node.kind) { + case 10: + if (node.singleQuote) { + return "'" + escapeText(node.text, 39) + "'"; + } + else { + return '"' + escapeText(node.text, 34) + '"'; + } + case 14: + return "`" + escapeText(node.text, 96) + "`"; + case 15: + return "`" + escapeText(node.text, 96) + "${"; + case 16: + return "}" + escapeText(node.text, 96) + "${"; + case 17: + return "}" + escapeText(node.text, 96) + "`"; + case 8: + case 9: + case 13: + return node.text; + } + return ts.Debug.fail("Literal kind '" + node.kind + "' not accounted for."); + } + ts.getLiteralText = getLiteralText; + function getTextOfConstantValue(value) { + return ts.isString(value) ? '"' + escapeNonAsciiString(value) + '"' : "" + value; + } + ts.getTextOfConstantValue = getTextOfConstantValue; + function makeIdentifierFromModuleName(moduleName) { + return ts.getBaseFileName(moduleName).replace(/^(\d)/, "_$1").replace(/\W/g, "_"); + } + ts.makeIdentifierFromModuleName = makeIdentifierFromModuleName; + function isBlockOrCatchScoped(declaration) { + return (ts.getCombinedNodeFlags(declaration) & 3) !== 0 || + isCatchClauseVariableDeclarationOrBindingElement(declaration); + } + ts.isBlockOrCatchScoped = isBlockOrCatchScoped; + function isCatchClauseVariableDeclarationOrBindingElement(declaration) { + var node = getRootDeclaration(declaration); + return node.kind === 237 && node.parent.kind === 274; + } + ts.isCatchClauseVariableDeclarationOrBindingElement = isCatchClauseVariableDeclarationOrBindingElement; + function isAmbientModule(node) { + return ts.isModuleDeclaration(node) && (node.name.kind === 10 || isGlobalScopeAugmentation(node)); + } + ts.isAmbientModule = isAmbientModule; + function isModuleWithStringLiteralName(node) { + return ts.isModuleDeclaration(node) && node.name.kind === 10; + } + ts.isModuleWithStringLiteralName = isModuleWithStringLiteralName; + function isNonGlobalAmbientModule(node) { + return ts.isModuleDeclaration(node) && ts.isStringLiteral(node.name); + } + ts.isNonGlobalAmbientModule = isNonGlobalAmbientModule; + function isEffectiveModuleDeclaration(node) { + return ts.isModuleDeclaration(node) || ts.isIdentifier(node); + } + ts.isEffectiveModuleDeclaration = isEffectiveModuleDeclaration; + function isShorthandAmbientModuleSymbol(moduleSymbol) { + return isShorthandAmbientModule(moduleSymbol.valueDeclaration); + } + ts.isShorthandAmbientModuleSymbol = isShorthandAmbientModuleSymbol; + function isShorthandAmbientModule(node) { + return node && node.kind === 244 && (!node.body); + } + function isBlockScopedContainerTopLevel(node) { + return node.kind === 279 || + node.kind === 244 || + ts.isFunctionLike(node); + } + ts.isBlockScopedContainerTopLevel = isBlockScopedContainerTopLevel; + function isGlobalScopeAugmentation(module) { + return !!(module.flags & 512); + } + ts.isGlobalScopeAugmentation = isGlobalScopeAugmentation; + function isExternalModuleAugmentation(node) { + return isAmbientModule(node) && isModuleAugmentationExternal(node); + } + ts.isExternalModuleAugmentation = isExternalModuleAugmentation; + function isModuleAugmentationExternal(node) { + switch (node.parent.kind) { + case 279: + return ts.isExternalModule(node.parent); + case 245: + return isAmbientModule(node.parent.parent) && ts.isSourceFile(node.parent.parent.parent) && !ts.isExternalModule(node.parent.parent.parent); + } + return false; + } + ts.isModuleAugmentationExternal = isModuleAugmentationExternal; + function getNonAugmentationDeclaration(symbol) { + return ts.find(symbol.declarations, function (d) { return !isExternalModuleAugmentation(d) && !(ts.isModuleDeclaration(d) && isGlobalScopeAugmentation(d)); }); + } + ts.getNonAugmentationDeclaration = getNonAugmentationDeclaration; + function isEffectiveExternalModule(node, compilerOptions) { + return ts.isExternalModule(node) || compilerOptions.isolatedModules || ((ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS) && !!node.commonJsModuleIndicator); + } + ts.isEffectiveExternalModule = isEffectiveExternalModule; + function isBlockScope(node, parentNode) { + switch (node.kind) { + case 279: + case 246: + case 274: + case 244: + case 225: + case 226: + case 227: + case 157: + case 156: + case 158: + case 159: + case 239: + case 196: + case 197: + return true; + case 218: + return !ts.isFunctionLike(parentNode); + } + return false; + } + ts.isBlockScope = isBlockScope; + function isDeclarationWithTypeParameters(node) { + switch (node.kind) { + case 297: + case 304: + case 293: + return true; + default: + ts.assertType(node); + return isDeclarationWithTypeParameterChildren(node); + } + } + ts.isDeclarationWithTypeParameters = isDeclarationWithTypeParameters; + function isDeclarationWithTypeParameterChildren(node) { + switch (node.kind) { + case 160: + case 161: + case 155: + case 162: + case 165: + case 166: + case 289: + case 240: + case 209: + case 241: + case 242: + case 303: + case 239: + case 156: + case 157: + case 158: + case 159: + case 196: + case 197: + return true; + default: + ts.assertType(node); + return false; + } + } + ts.isDeclarationWithTypeParameterChildren = isDeclarationWithTypeParameterChildren; + function isAnyImportSyntax(node) { + switch (node.kind) { + case 249: + case 248: + return true; + default: + return false; + } + } + ts.isAnyImportSyntax = isAnyImportSyntax; + function isLateVisibilityPaintedStatement(node) { + switch (node.kind) { + case 249: + case 248: + case 219: + case 240: + case 239: + case 244: + case 242: + case 241: + case 243: + return true; + default: + return false; + } + } + ts.isLateVisibilityPaintedStatement = isLateVisibilityPaintedStatement; + function isAnyImportOrReExport(node) { + return isAnyImportSyntax(node) || ts.isExportDeclaration(node); + } + ts.isAnyImportOrReExport = isAnyImportOrReExport; + function getEnclosingBlockScopeContainer(node) { + return findAncestor(node.parent, function (current) { return isBlockScope(current, current.parent); }); + } + ts.getEnclosingBlockScopeContainer = getEnclosingBlockScopeContainer; + function declarationNameToString(name) { + return !name || getFullWidth(name) === 0 ? "(Missing)" : getTextOfNode(name); + } + ts.declarationNameToString = declarationNameToString; + function getNameFromIndexInfo(info) { + return info.declaration ? declarationNameToString(info.declaration.parameters[0].name) : undefined; + } + ts.getNameFromIndexInfo = getNameFromIndexInfo; + function getTextOfPropertyName(name) { + switch (name.kind) { + case 72: + return name.escapedText; + case 10: + case 8: + case 14: + return ts.escapeLeadingUnderscores(name.text); + case 149: + return isStringOrNumericLiteralLike(name.expression) ? ts.escapeLeadingUnderscores(name.expression.text) : undefined; + default: + return ts.Debug.assertNever(name); + } + } + ts.getTextOfPropertyName = getTextOfPropertyName; + function entityNameToString(name) { + switch (name.kind) { + case 72: + return getFullWidth(name) === 0 ? ts.idText(name) : getTextOfNode(name); + case 148: + return entityNameToString(name.left) + "." + entityNameToString(name.right); + case 189: + return entityNameToString(name.expression) + "." + entityNameToString(name.name); + default: + throw ts.Debug.assertNever(name); + } + } + ts.entityNameToString = entityNameToString; + function createDiagnosticForNode(node, message, arg0, arg1, arg2, arg3) { + var sourceFile = getSourceFileOfNode(node); + return createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2, arg3); + } + ts.createDiagnosticForNode = createDiagnosticForNode; + function createDiagnosticForNodeArray(sourceFile, nodes, message, arg0, arg1, arg2, arg3) { + var start = ts.skipTrivia(sourceFile.text, nodes.pos); + return ts.createFileDiagnostic(sourceFile, start, nodes.end - start, message, arg0, arg1, arg2, arg3); + } + ts.createDiagnosticForNodeArray = createDiagnosticForNodeArray; + function createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2, arg3) { + var span = getErrorSpanForNode(sourceFile, node); + return ts.createFileDiagnostic(sourceFile, span.start, span.length, message, arg0, arg1, arg2, arg3); + } + ts.createDiagnosticForNodeInSourceFile = createDiagnosticForNodeInSourceFile; + function createDiagnosticForNodeFromMessageChain(node, messageChain, relatedInformation) { + var sourceFile = getSourceFileOfNode(node); + var span = getErrorSpanForNode(sourceFile, node); + return { + file: sourceFile, + start: span.start, + length: span.length, + code: messageChain.code, + category: messageChain.category, + messageText: messageChain.next ? messageChain : messageChain.messageText, + relatedInformation: relatedInformation + }; + } + ts.createDiagnosticForNodeFromMessageChain = createDiagnosticForNodeFromMessageChain; + function getSpanOfTokenAtPosition(sourceFile, pos) { + var scanner = ts.createScanner(sourceFile.languageVersion, true, sourceFile.languageVariant, sourceFile.text, undefined, pos); + scanner.scan(); + var start = scanner.getTokenPos(); + return ts.createTextSpanFromBounds(start, scanner.getTextPos()); + } + ts.getSpanOfTokenAtPosition = getSpanOfTokenAtPosition; + function getErrorSpanForArrowFunction(sourceFile, node) { + var pos = ts.skipTrivia(sourceFile.text, node.pos); + if (node.body && node.body.kind === 218) { + var startLine = ts.getLineAndCharacterOfPosition(sourceFile, node.body.pos).line; + var endLine = ts.getLineAndCharacterOfPosition(sourceFile, node.body.end).line; + if (startLine < endLine) { + return ts.createTextSpan(pos, getEndLinePosition(startLine, sourceFile) - pos + 1); + } + } + return ts.createTextSpanFromBounds(pos, node.end); + } + function getErrorSpanForNode(sourceFile, node) { + var errorNode = node; + switch (node.kind) { + case 279: + var pos_1 = ts.skipTrivia(sourceFile.text, 0, false); + if (pos_1 === sourceFile.text.length) { + return ts.createTextSpan(0, 0); + } + return getSpanOfTokenAtPosition(sourceFile, pos_1); + case 237: + case 186: + case 240: + case 209: + case 241: + case 244: + case 243: + case 278: + case 239: + case 196: + case 156: + case 158: + case 159: + case 242: + case 154: + case 153: + errorNode = node.name; + break; + case 197: + return getErrorSpanForArrowFunction(sourceFile, node); + } + if (errorNode === undefined) { + return getSpanOfTokenAtPosition(sourceFile, node.pos); + } + var isMissing = nodeIsMissing(errorNode); + var pos = isMissing + ? errorNode.pos + : ts.skipTrivia(sourceFile.text, errorNode.pos); + if (isMissing) { + ts.Debug.assert(pos === errorNode.pos, "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809"); + ts.Debug.assert(pos === errorNode.end, "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809"); + } + else { + ts.Debug.assert(pos >= errorNode.pos, "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809"); + ts.Debug.assert(pos <= errorNode.end, "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809"); + } + return ts.createTextSpanFromBounds(pos, errorNode.end); + } + ts.getErrorSpanForNode = getErrorSpanForNode; + function isExternalOrCommonJsModule(file) { + return (file.externalModuleIndicator || file.commonJsModuleIndicator) !== undefined; + } + ts.isExternalOrCommonJsModule = isExternalOrCommonJsModule; + function isJsonSourceFile(file) { + return file.scriptKind === 6; + } + ts.isJsonSourceFile = isJsonSourceFile; + function isEnumConst(node) { + return !!(ts.getCombinedModifierFlags(node) & 2048); + } + ts.isEnumConst = isEnumConst; + function isDeclarationReadonly(declaration) { + return !!(ts.getCombinedModifierFlags(declaration) & 64 && !ts.isParameterPropertyDeclaration(declaration)); + } + ts.isDeclarationReadonly = isDeclarationReadonly; + function isVarConst(node) { + return !!(ts.getCombinedNodeFlags(node) & 2); + } + ts.isVarConst = isVarConst; + function isLet(node) { + return !!(ts.getCombinedNodeFlags(node) & 1); + } + ts.isLet = isLet; + function isSuperCall(n) { + return n.kind === 191 && n.expression.kind === 98; + } + ts.isSuperCall = isSuperCall; + function isImportCall(n) { + return n.kind === 191 && n.expression.kind === 92; + } + ts.isImportCall = isImportCall; + function isLiteralImportTypeNode(n) { + return ts.isImportTypeNode(n) && ts.isLiteralTypeNode(n.argument) && ts.isStringLiteral(n.argument.literal); + } + ts.isLiteralImportTypeNode = isLiteralImportTypeNode; + function isPrologueDirective(node) { + return node.kind === 221 + && node.expression.kind === 10; + } + ts.isPrologueDirective = isPrologueDirective; + function getLeadingCommentRangesOfNode(node, sourceFileOfNode) { + return node.kind !== 11 ? ts.getLeadingCommentRanges(sourceFileOfNode.text, node.pos) : undefined; + } + ts.getLeadingCommentRangesOfNode = getLeadingCommentRangesOfNode; + function getJSDocCommentRanges(node, text) { + var commentRanges = (node.kind === 151 || + node.kind === 150 || + node.kind === 196 || + node.kind === 197 || + node.kind === 195) ? + ts.concatenate(ts.getTrailingCommentRanges(text, node.pos), ts.getLeadingCommentRanges(text, node.pos)) : + ts.getLeadingCommentRanges(text, node.pos); + return ts.filter(commentRanges, function (comment) { + return text.charCodeAt(comment.pos + 1) === 42 && + text.charCodeAt(comment.pos + 2) === 42 && + text.charCodeAt(comment.pos + 3) !== 47; + }); + } + ts.getJSDocCommentRanges = getJSDocCommentRanges; + ts.fullTripleSlashReferencePathRegEx = /^(\/\/\/\s*/; + var fullTripleSlashReferenceTypeReferenceDirectiveRegEx = /^(\/\/\/\s*/; + ts.fullTripleSlashAMDReferencePathRegEx = /^(\/\/\/\s*/; + var defaultLibReferenceRegEx = /^(\/\/\/\s*/; + function isPartOfTypeNode(node) { + if (163 <= node.kind && node.kind <= 183) { + return true; + } + switch (node.kind) { + case 120: + case 143: + case 135: + case 146: + case 138: + case 123: + case 139: + case 136: + case 141: + case 132: + return true; + case 106: + return node.parent.kind !== 200; + case 211: + return !isExpressionWithTypeArgumentsInClassExtendsClause(node); + case 150: + return node.parent.kind === 181 || node.parent.kind === 176; + case 72: + if (node.parent.kind === 148 && node.parent.right === node) { + node = node.parent; + } + else if (node.parent.kind === 189 && node.parent.name === node) { + node = node.parent; + } + ts.Debug.assert(node.kind === 72 || node.kind === 148 || node.kind === 189, "'node' was expected to be a qualified name, identifier or property access in 'isPartOfTypeNode'."); + case 148: + case 189: + case 100: { + var parent = node.parent; + if (parent.kind === 167) { + return false; + } + if (parent.kind === 183) { + return !parent.isTypeOf; + } + if (163 <= parent.kind && parent.kind <= 183) { + return true; + } + switch (parent.kind) { + case 211: + return !isExpressionWithTypeArgumentsInClassExtendsClause(parent); + case 150: + return node === parent.constraint; + case 303: + return node === parent.constraint; + case 154: + case 153: + case 151: + case 237: + return node === parent.type; + case 239: + case 196: + case 197: + case 157: + case 156: + case 155: + case 158: + case 159: + return node === parent.type; + case 160: + case 161: + case 162: + return node === parent.type; + case 194: + return node === parent.type; + case 191: + case 192: + return ts.contains(parent.typeArguments, node); + case 193: + return false; + } + } + } + return false; + } + ts.isPartOfTypeNode = isPartOfTypeNode; + function isChildOfNodeWithKind(node, kind) { + while (node) { + if (node.kind === kind) { + return true; + } + node = node.parent; + } + return false; + } + ts.isChildOfNodeWithKind = isChildOfNodeWithKind; + function forEachReturnStatement(body, visitor) { + return traverse(body); + function traverse(node) { + switch (node.kind) { + case 230: + return visitor(node); + case 246: + case 218: + case 222: + case 223: + case 224: + case 225: + case 226: + case 227: + case 231: + case 232: + case 271: + case 272: + case 233: + case 235: + case 274: + return ts.forEachChild(node, traverse); + } + } + } + ts.forEachReturnStatement = forEachReturnStatement; + function forEachYieldExpression(body, visitor) { + return traverse(body); + function traverse(node) { + switch (node.kind) { + case 207: + visitor(node); + var operand = node.expression; + if (operand) { + traverse(operand); + } + return; + case 243: + case 241: + case 244: + case 242: + case 240: + case 209: + return; + default: + if (ts.isFunctionLike(node)) { + if (node.name && node.name.kind === 149) { + traverse(node.name.expression); + return; + } + } + else if (!isPartOfTypeNode(node)) { + ts.forEachChild(node, traverse); + } + } + } + } + ts.forEachYieldExpression = forEachYieldExpression; + function getRestParameterElementType(node) { + if (node && node.kind === 169) { + return node.elementType; + } + else if (node && node.kind === 164) { + return ts.singleOrUndefined(node.typeArguments); + } + else { + return undefined; + } + } + ts.getRestParameterElementType = getRestParameterElementType; + function getMembersOfDeclaration(node) { + switch (node.kind) { + case 241: + case 240: + case 209: + case 168: + return node.members; + case 188: + return node.properties; + } + } + ts.getMembersOfDeclaration = getMembersOfDeclaration; + function isVariableLike(node) { + if (node) { + switch (node.kind) { + case 186: + case 278: + case 151: + case 275: + case 154: + case 153: + case 276: + case 237: + return true; + } + } + return false; + } + ts.isVariableLike = isVariableLike; + function isVariableLikeOrAccessor(node) { + return isVariableLike(node) || ts.isAccessor(node); + } + ts.isVariableLikeOrAccessor = isVariableLikeOrAccessor; + function isVariableDeclarationInVariableStatement(node) { + return node.parent.kind === 238 + && node.parent.parent.kind === 219; + } + ts.isVariableDeclarationInVariableStatement = isVariableDeclarationInVariableStatement; + function isValidESSymbolDeclaration(node) { + return ts.isVariableDeclaration(node) ? isVarConst(node) && ts.isIdentifier(node.name) && isVariableDeclarationInVariableStatement(node) : + ts.isPropertyDeclaration(node) ? hasReadonlyModifier(node) && hasStaticModifier(node) : + ts.isPropertySignature(node) && hasReadonlyModifier(node); + } + ts.isValidESSymbolDeclaration = isValidESSymbolDeclaration; + function introducesArgumentsExoticObject(node) { + switch (node.kind) { + case 156: + case 155: + case 157: + case 158: + case 159: + case 239: + case 196: + return true; + } + return false; + } + ts.introducesArgumentsExoticObject = introducesArgumentsExoticObject; + function unwrapInnermostStatementOfLabel(node, beforeUnwrapLabelCallback) { + while (true) { + if (beforeUnwrapLabelCallback) { + beforeUnwrapLabelCallback(node); + } + if (node.statement.kind !== 233) { + return node.statement; + } + node = node.statement; + } + } + ts.unwrapInnermostStatementOfLabel = unwrapInnermostStatementOfLabel; + function isFunctionBlock(node) { + return node && node.kind === 218 && ts.isFunctionLike(node.parent); + } + ts.isFunctionBlock = isFunctionBlock; + function isObjectLiteralMethod(node) { + return node && node.kind === 156 && node.parent.kind === 188; + } + ts.isObjectLiteralMethod = isObjectLiteralMethod; + function isObjectLiteralOrClassExpressionMethod(node) { + return node.kind === 156 && + (node.parent.kind === 188 || + node.parent.kind === 209); + } + ts.isObjectLiteralOrClassExpressionMethod = isObjectLiteralOrClassExpressionMethod; + function isIdentifierTypePredicate(predicate) { + return predicate && predicate.kind === 1; + } + ts.isIdentifierTypePredicate = isIdentifierTypePredicate; + function isThisTypePredicate(predicate) { + return predicate && predicate.kind === 0; + } + ts.isThisTypePredicate = isThisTypePredicate; + function getPropertyAssignment(objectLiteral, key, key2) { + return objectLiteral.properties.filter(function (property) { + if (property.kind === 275) { + var propName = getTextOfPropertyName(property.name); + return key === propName || (!!key2 && key2 === propName); + } + return false; + }); + } + ts.getPropertyAssignment = getPropertyAssignment; + function getTsConfigObjectLiteralExpression(tsConfigSourceFile) { + if (tsConfigSourceFile && tsConfigSourceFile.statements.length) { + var expression = tsConfigSourceFile.statements[0].expression; + return ts.tryCast(expression, ts.isObjectLiteralExpression); + } + } + ts.getTsConfigObjectLiteralExpression = getTsConfigObjectLiteralExpression; + function getTsConfigPropArrayElementValue(tsConfigSourceFile, propKey, elementValue) { + return ts.firstDefined(getTsConfigPropArray(tsConfigSourceFile, propKey), function (property) { + return ts.isArrayLiteralExpression(property.initializer) ? + ts.find(property.initializer.elements, function (element) { return ts.isStringLiteral(element) && element.text === elementValue; }) : + undefined; + }); + } + ts.getTsConfigPropArrayElementValue = getTsConfigPropArrayElementValue; + function getTsConfigPropArray(tsConfigSourceFile, propKey) { + var jsonObjectLiteral = getTsConfigObjectLiteralExpression(tsConfigSourceFile); + return jsonObjectLiteral ? getPropertyAssignment(jsonObjectLiteral, propKey) : ts.emptyArray; + } + ts.getTsConfigPropArray = getTsConfigPropArray; + function getContainingFunction(node) { + return findAncestor(node.parent, ts.isFunctionLike); + } + ts.getContainingFunction = getContainingFunction; + function getContainingClass(node) { + return findAncestor(node.parent, ts.isClassLike); + } + ts.getContainingClass = getContainingClass; + function getThisContainer(node, includeArrowFunctions) { + ts.Debug.assert(node.kind !== 279); + while (true) { + node = node.parent; + if (!node) { + return ts.Debug.fail(); + } + switch (node.kind) { + case 149: + if (ts.isClassLike(node.parent.parent)) { + return node; + } + node = node.parent; + break; + case 152: + if (node.parent.kind === 151 && ts.isClassElement(node.parent.parent)) { + node = node.parent.parent; + } + else if (ts.isClassElement(node.parent)) { + node = node.parent; + } + break; + case 197: + if (!includeArrowFunctions) { + continue; + } + case 239: + case 196: + case 244: + case 154: + case 153: + case 156: + case 155: + case 157: + case 158: + case 159: + case 160: + case 161: + case 162: + case 243: + case 279: + return node; + } + } + } + ts.getThisContainer = getThisContainer; + function getNewTargetContainer(node) { + var container = getThisContainer(node, false); + if (container) { + switch (container.kind) { + case 157: + case 239: + case 196: + return container; + } + } + return undefined; + } + ts.getNewTargetContainer = getNewTargetContainer; + function getSuperContainer(node, stopOnFunctions) { + while (true) { + node = node.parent; + if (!node) { + return node; + } + switch (node.kind) { + case 149: + node = node.parent; + break; + case 239: + case 196: + case 197: + if (!stopOnFunctions) { + continue; + } + case 154: + case 153: + case 156: + case 155: + case 157: + case 158: + case 159: + return node; + case 152: + if (node.parent.kind === 151 && ts.isClassElement(node.parent.parent)) { + node = node.parent.parent; + } + else if (ts.isClassElement(node.parent)) { + node = node.parent; + } + break; + } + } + } + ts.getSuperContainer = getSuperContainer; + function getImmediatelyInvokedFunctionExpression(func) { + if (func.kind === 196 || func.kind === 197) { + var prev = func; + var parent = func.parent; + while (parent.kind === 195) { + prev = parent; + parent = parent.parent; + } + if (parent.kind === 191 && parent.expression === prev) { + return parent; + } + } + } + ts.getImmediatelyInvokedFunctionExpression = getImmediatelyInvokedFunctionExpression; + function isSuperProperty(node) { + var kind = node.kind; + return (kind === 189 || kind === 190) + && node.expression.kind === 98; + } + ts.isSuperProperty = isSuperProperty; + function isThisProperty(node) { + var kind = node.kind; + return (kind === 189 || kind === 190) + && node.expression.kind === 100; + } + ts.isThisProperty = isThisProperty; + function getEntityNameFromTypeNode(node) { + switch (node.kind) { + case 164: + return node.typeName; + case 211: + return isEntityNameExpression(node.expression) + ? node.expression + : undefined; + case 72: + case 148: + return node; + } + return undefined; + } + ts.getEntityNameFromTypeNode = getEntityNameFromTypeNode; + function getInvokedExpression(node) { + switch (node.kind) { + case 193: + return node.tag; + case 262: + case 261: + return node.tagName; + default: + return node.expression; + } + } + ts.getInvokedExpression = getInvokedExpression; + function nodeCanBeDecorated(node, parent, grandparent) { + switch (node.kind) { + case 240: + return true; + case 154: + return parent.kind === 240; + case 158: + case 159: + case 156: + return node.body !== undefined + && parent.kind === 240; + case 151: + return parent.body !== undefined + && (parent.kind === 157 + || parent.kind === 156 + || parent.kind === 159) + && grandparent.kind === 240; + } + return false; + } + ts.nodeCanBeDecorated = nodeCanBeDecorated; + function nodeIsDecorated(node, parent, grandparent) { + return node.decorators !== undefined + && nodeCanBeDecorated(node, parent, grandparent); + } + ts.nodeIsDecorated = nodeIsDecorated; + function nodeOrChildIsDecorated(node, parent, grandparent) { + return nodeIsDecorated(node, parent, grandparent) || childIsDecorated(node, parent); + } + ts.nodeOrChildIsDecorated = nodeOrChildIsDecorated; + function childIsDecorated(node, parent) { + switch (node.kind) { + case 240: + return ts.some(node.members, function (m) { return nodeOrChildIsDecorated(m, node, parent); }); + case 156: + case 159: + return ts.some(node.parameters, function (p) { return nodeIsDecorated(p, node, parent); }); + default: + return false; + } + } + ts.childIsDecorated = childIsDecorated; + function isJSXTagName(node) { + var parent = node.parent; + if (parent.kind === 262 || + parent.kind === 261 || + parent.kind === 263) { + return parent.tagName === node; + } + return false; + } + ts.isJSXTagName = isJSXTagName; + function isExpressionNode(node) { + switch (node.kind) { + case 98: + case 96: + case 102: + case 87: + case 13: + case 187: + case 188: + case 189: + case 190: + case 191: + case 192: + case 193: + case 212: + case 194: + case 213: + case 195: + case 196: + case 209: + case 197: + case 200: + case 198: + case 199: + case 202: + case 203: + case 204: + case 205: + case 208: + case 206: + case 14: + case 210: + case 260: + case 261: + case 264: + case 207: + case 201: + case 214: + return true; + case 148: + while (node.parent.kind === 148) { + node = node.parent; + } + return node.parent.kind === 167 || isJSXTagName(node); + case 72: + if (node.parent.kind === 167 || isJSXTagName(node)) { + return true; + } + case 8: + case 9: + case 10: + case 100: + return isInExpressionContext(node); + default: + return false; + } + } + ts.isExpressionNode = isExpressionNode; + function isInExpressionContext(node) { + var parent = node.parent; + switch (parent.kind) { + case 237: + case 151: + case 154: + case 153: + case 278: + case 275: + case 186: + return parent.initializer === node; + case 221: + case 222: + case 223: + case 224: + case 230: + case 231: + case 232: + case 271: + case 234: + return parent.expression === node; + case 225: + var forStatement = parent; + return (forStatement.initializer === node && forStatement.initializer.kind !== 238) || + forStatement.condition === node || + forStatement.incrementor === node; + case 226: + case 227: + var forInStatement = parent; + return (forInStatement.initializer === node && forInStatement.initializer.kind !== 238) || + forInStatement.expression === node; + case 194: + case 212: + return node === parent.expression; + case 216: + return node === parent.expression; + case 149: + return node === parent.expression; + case 152: + case 270: + case 269: + case 277: + return true; + case 211: + return parent.expression === node && isExpressionWithTypeArgumentsInClassExtendsClause(parent); + case 276: + return parent.objectAssignmentInitializer === node; + default: + return isExpressionNode(parent); + } + } + ts.isInExpressionContext = isInExpressionContext; + function isExternalModuleImportEqualsDeclaration(node) { + return node.kind === 248 && node.moduleReference.kind === 259; + } + ts.isExternalModuleImportEqualsDeclaration = isExternalModuleImportEqualsDeclaration; + function getExternalModuleImportEqualsDeclarationExpression(node) { + ts.Debug.assert(isExternalModuleImportEqualsDeclaration(node)); + return node.moduleReference.expression; + } + ts.getExternalModuleImportEqualsDeclarationExpression = getExternalModuleImportEqualsDeclarationExpression; + function isInternalModuleImportEqualsDeclaration(node) { + return node.kind === 248 && node.moduleReference.kind !== 259; + } + ts.isInternalModuleImportEqualsDeclaration = isInternalModuleImportEqualsDeclaration; + function isSourceFileJS(file) { + return isInJSFile(file); + } + ts.isSourceFileJS = isSourceFileJS; + function isSourceFileNotJS(file) { + return !isInJSFile(file); + } + ts.isSourceFileNotJS = isSourceFileNotJS; + function isInJSFile(node) { + return !!node && !!(node.flags & 65536); + } + ts.isInJSFile = isInJSFile; + function isInJsonFile(node) { + return !!node && !!(node.flags & 16777216); + } + ts.isInJsonFile = isInJsonFile; + function isInJSDoc(node) { + return !!node && !!(node.flags & 2097152); + } + ts.isInJSDoc = isInJSDoc; + function isJSDocIndexSignature(node) { + return ts.isTypeReferenceNode(node) && + ts.isIdentifier(node.typeName) && + node.typeName.escapedText === "Object" && + node.typeArguments && node.typeArguments.length === 2 && + (node.typeArguments[0].kind === 138 || node.typeArguments[0].kind === 135); + } + ts.isJSDocIndexSignature = isJSDocIndexSignature; + function isRequireCall(callExpression, checkArgumentIsStringLiteralLike) { + if (callExpression.kind !== 191) { + return false; + } + var _a = callExpression, expression = _a.expression, args = _a.arguments; + if (expression.kind !== 72 || expression.escapedText !== "require") { + return false; + } + if (args.length !== 1) { + return false; + } + var arg = args[0]; + return !checkArgumentIsStringLiteralLike || ts.isStringLiteralLike(arg); + } + ts.isRequireCall = isRequireCall; + function isSingleOrDoubleQuote(charCode) { + return charCode === 39 || charCode === 34; + } + ts.isSingleOrDoubleQuote = isSingleOrDoubleQuote; + function isStringDoubleQuoted(str, sourceFile) { + return getSourceTextOfNodeFromSourceFile(sourceFile, str).charCodeAt(0) === 34; + } + ts.isStringDoubleQuoted = isStringDoubleQuoted; + function getDeclarationOfExpando(node) { + if (!node.parent) { + return undefined; + } + var name; + var decl; + if (ts.isVariableDeclaration(node.parent) && node.parent.initializer === node) { + if (!isInJSFile(node) && !isVarConst(node.parent)) { + return undefined; + } + name = node.parent.name; + decl = node.parent; + } + else if (ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 59 && node.parent.right === node) { + name = node.parent.left; + decl = name; + } + else if (ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 55) { + if (ts.isVariableDeclaration(node.parent.parent) && node.parent.parent.initializer === node.parent) { + name = node.parent.parent.name; + decl = node.parent.parent; + } + else if (ts.isBinaryExpression(node.parent.parent) && node.parent.parent.operatorToken.kind === 59 && node.parent.parent.right === node.parent) { + name = node.parent.parent.left; + decl = name; + } + if (!name || !isEntityNameExpression(name) || !isSameEntityName(name, node.parent.left)) { + return undefined; + } + } + if (!name || !getExpandoInitializer(node, isPrototypeAccess(name))) { + return undefined; + } + return decl; + } + ts.getDeclarationOfExpando = getDeclarationOfExpando; + function isAssignmentDeclaration(decl) { + return ts.isBinaryExpression(decl) || ts.isPropertyAccessExpression(decl) || ts.isIdentifier(decl) || ts.isCallExpression(decl); + } + ts.isAssignmentDeclaration = isAssignmentDeclaration; + function getEffectiveInitializer(node) { + if (isInJSFile(node) && node.initializer && + ts.isBinaryExpression(node.initializer) && node.initializer.operatorToken.kind === 55 && + node.name && isEntityNameExpression(node.name) && isSameEntityName(node.name, node.initializer.left)) { + return node.initializer.right; + } + return node.initializer; + } + ts.getEffectiveInitializer = getEffectiveInitializer; + function getDeclaredExpandoInitializer(node) { + var init = getEffectiveInitializer(node); + return init && getExpandoInitializer(init, isPrototypeAccess(node.name)); + } + ts.getDeclaredExpandoInitializer = getDeclaredExpandoInitializer; + function hasExpandoValueProperty(node, isPrototypeAssignment) { + return ts.forEach(node.properties, function (p) { return ts.isPropertyAssignment(p) && ts.isIdentifier(p.name) && p.name.escapedText === "value" && p.initializer && getExpandoInitializer(p.initializer, isPrototypeAssignment); }); + } + function getAssignedExpandoInitializer(node) { + if (node && node.parent && ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 59) { + var isPrototypeAssignment = isPrototypeAccess(node.parent.left); + return getExpandoInitializer(node.parent.right, isPrototypeAssignment) || + getDefaultedExpandoInitializer(node.parent.left, node.parent.right, isPrototypeAssignment); + } + if (node && ts.isCallExpression(node) && isBindableObjectDefinePropertyCall(node)) { + var result = hasExpandoValueProperty(node.arguments[2], node.arguments[1].text === "prototype"); + if (result) { + return result; + } + } + } + ts.getAssignedExpandoInitializer = getAssignedExpandoInitializer; + function getExpandoInitializer(initializer, isPrototypeAssignment) { + if (ts.isCallExpression(initializer)) { + var e = skipParentheses(initializer.expression); + return e.kind === 196 || e.kind === 197 ? initializer : undefined; + } + if (initializer.kind === 196 || + initializer.kind === 209 || + initializer.kind === 197) { + return initializer; + } + if (ts.isObjectLiteralExpression(initializer) && (initializer.properties.length === 0 || isPrototypeAssignment)) { + return initializer; + } + } + ts.getExpandoInitializer = getExpandoInitializer; + function getDefaultedExpandoInitializer(name, initializer, isPrototypeAssignment) { + var e = ts.isBinaryExpression(initializer) && initializer.operatorToken.kind === 55 && getExpandoInitializer(initializer.right, isPrototypeAssignment); + if (e && isSameEntityName(name, initializer.left)) { + return e; + } + } + function isDefaultedExpandoInitializer(node) { + var name = ts.isVariableDeclaration(node.parent) ? node.parent.name : + ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 59 ? node.parent.left : + undefined; + return name && getExpandoInitializer(node.right, isPrototypeAccess(name)) && isEntityNameExpression(name) && isSameEntityName(name, node.left); + } + ts.isDefaultedExpandoInitializer = isDefaultedExpandoInitializer; + function getNameOfExpando(node) { + if (ts.isBinaryExpression(node.parent)) { + var parent = (node.parent.operatorToken.kind === 55 && ts.isBinaryExpression(node.parent.parent)) ? node.parent.parent : node.parent; + if (parent.operatorToken.kind === 59 && ts.isIdentifier(parent.left)) { + return parent.left; + } + } + else if (ts.isVariableDeclaration(node.parent)) { + return node.parent.name; + } + } + ts.getNameOfExpando = getNameOfExpando; + function isSameEntityName(name, initializer) { + if (ts.isIdentifier(name) && ts.isIdentifier(initializer)) { + return name.escapedText === initializer.escapedText; + } + if (ts.isIdentifier(name) && ts.isPropertyAccessExpression(initializer)) { + return (initializer.expression.kind === 100 || + ts.isIdentifier(initializer.expression) && + (initializer.expression.escapedText === "window" || + initializer.expression.escapedText === "self" || + initializer.expression.escapedText === "global")) && + isSameEntityName(name, initializer.name); + } + if (ts.isPropertyAccessExpression(name) && ts.isPropertyAccessExpression(initializer)) { + return name.name.escapedText === initializer.name.escapedText && isSameEntityName(name.expression, initializer.expression); + } + return false; + } + function getRightMostAssignedExpression(node) { + while (isAssignmentExpression(node, true)) { + node = node.right; + } + return node; + } + ts.getRightMostAssignedExpression = getRightMostAssignedExpression; + function isExportsIdentifier(node) { + return ts.isIdentifier(node) && node.escapedText === "exports"; + } + ts.isExportsIdentifier = isExportsIdentifier; + function isModuleExportsPropertyAccessExpression(node) { + return ts.isPropertyAccessExpression(node) && ts.isIdentifier(node.expression) && node.expression.escapedText === "module" && node.name.escapedText === "exports"; + } + ts.isModuleExportsPropertyAccessExpression = isModuleExportsPropertyAccessExpression; + function getAssignmentDeclarationKind(expr) { + var special = getAssignmentDeclarationKindWorker(expr); + return special === 5 || isInJSFile(expr) ? special : 0; + } + ts.getAssignmentDeclarationKind = getAssignmentDeclarationKind; + function isBindableObjectDefinePropertyCall(expr) { + return ts.length(expr.arguments) === 3 && + ts.isPropertyAccessExpression(expr.expression) && + ts.isIdentifier(expr.expression.expression) && + ts.idText(expr.expression.expression) === "Object" && + ts.idText(expr.expression.name) === "defineProperty" && + isStringOrNumericLiteralLike(expr.arguments[1]) && + isEntityNameExpression(expr.arguments[0]); + } + ts.isBindableObjectDefinePropertyCall = isBindableObjectDefinePropertyCall; + function getAssignmentDeclarationKindWorker(expr) { + if (ts.isCallExpression(expr)) { + if (!isBindableObjectDefinePropertyCall(expr)) { + return 0; + } + var entityName = expr.arguments[0]; + if (isExportsIdentifier(entityName) || isModuleExportsPropertyAccessExpression(entityName)) { + return 8; + } + if (ts.isPropertyAccessExpression(entityName) && entityName.name.escapedText === "prototype" && isEntityNameExpression(entityName.expression)) { + return 9; + } + return 7; + } + if (expr.operatorToken.kind !== 59 || + !ts.isPropertyAccessExpression(expr.left)) { + return 0; + } + var lhs = expr.left; + if (isEntityNameExpression(lhs.expression) && lhs.name.escapedText === "prototype" && ts.isObjectLiteralExpression(getInitializerOfBinaryExpression(expr))) { + return 6; + } + return getAssignmentDeclarationPropertyAccessKind(lhs); + } + function getAssignmentDeclarationPropertyAccessKind(lhs) { + if (lhs.expression.kind === 100) { + return 4; + } + else if (isModuleExportsPropertyAccessExpression(lhs)) { + return 2; + } + else if (isEntityNameExpression(lhs.expression)) { + if (isPrototypeAccess(lhs.expression)) { + return 3; + } + var nextToLast = lhs; + while (ts.isPropertyAccessExpression(nextToLast.expression)) { + nextToLast = nextToLast.expression; + } + ts.Debug.assert(ts.isIdentifier(nextToLast.expression)); + var id = nextToLast.expression; + if (id.escapedText === "exports" || + id.escapedText === "module" && nextToLast.name.escapedText === "exports") { + return 1; + } + return 5; + } + return 0; + } + ts.getAssignmentDeclarationPropertyAccessKind = getAssignmentDeclarationPropertyAccessKind; + function getInitializerOfBinaryExpression(expr) { + while (ts.isBinaryExpression(expr.right)) { + expr = expr.right; + } + return expr.right; + } + ts.getInitializerOfBinaryExpression = getInitializerOfBinaryExpression; + function isPrototypePropertyAssignment(node) { + return ts.isBinaryExpression(node) && getAssignmentDeclarationKind(node) === 3; + } + ts.isPrototypePropertyAssignment = isPrototypePropertyAssignment; + function isSpecialPropertyDeclaration(expr) { + return isInJSFile(expr) && + expr.parent && expr.parent.kind === 221 && + !!ts.getJSDocTypeTag(expr.parent); + } + ts.isSpecialPropertyDeclaration = isSpecialPropertyDeclaration; + function isFunctionSymbol(symbol) { + if (!symbol || !symbol.valueDeclaration) { + return false; + } + var decl = symbol.valueDeclaration; + return decl.kind === 239 || ts.isVariableDeclaration(decl) && decl.initializer && ts.isFunctionLike(decl.initializer); + } + ts.isFunctionSymbol = isFunctionSymbol; + function importFromModuleSpecifier(node) { + return tryGetImportFromModuleSpecifier(node) || ts.Debug.fail(ts.Debug.showSyntaxKind(node.parent)); + } + ts.importFromModuleSpecifier = importFromModuleSpecifier; + function tryGetImportFromModuleSpecifier(node) { + switch (node.parent.kind) { + case 249: + case 255: + return node.parent; + case 259: + return node.parent.parent; + case 191: + return isImportCall(node.parent) || isRequireCall(node.parent, false) ? node.parent : undefined; + case 182: + ts.Debug.assert(ts.isStringLiteral(node)); + return ts.tryCast(node.parent.parent, ts.isImportTypeNode); + default: + return undefined; + } + } + ts.tryGetImportFromModuleSpecifier = tryGetImportFromModuleSpecifier; + function getExternalModuleName(node) { + switch (node.kind) { + case 249: + case 255: + return node.moduleSpecifier; + case 248: + return node.moduleReference.kind === 259 ? node.moduleReference.expression : undefined; + case 183: + return isLiteralImportTypeNode(node) ? node.argument.literal : undefined; + default: + return ts.Debug.assertNever(node); + } + } + ts.getExternalModuleName = getExternalModuleName; + function getNamespaceDeclarationNode(node) { + switch (node.kind) { + case 249: + return node.importClause && ts.tryCast(node.importClause.namedBindings, ts.isNamespaceImport); + case 248: + return node; + case 255: + return undefined; + default: + return ts.Debug.assertNever(node); + } + } + ts.getNamespaceDeclarationNode = getNamespaceDeclarationNode; + function isDefaultImport(node) { + return node.kind === 249 && !!node.importClause && !!node.importClause.name; + } + ts.isDefaultImport = isDefaultImport; + function hasQuestionToken(node) { + if (node) { + switch (node.kind) { + case 151: + case 156: + case 155: + case 276: + case 275: + case 154: + case 153: + return node.questionToken !== undefined; + } + } + return false; + } + ts.hasQuestionToken = hasQuestionToken; + function isJSDocConstructSignature(node) { + var param = ts.isJSDocFunctionType(node) ? ts.firstOrUndefined(node.parameters) : undefined; + var name = ts.tryCast(param && param.name, ts.isIdentifier); + return !!name && name.escapedText === "new"; + } + ts.isJSDocConstructSignature = isJSDocConstructSignature; + function isJSDocTypeAlias(node) { + return node.kind === 304 || node.kind === 297; + } + ts.isJSDocTypeAlias = isJSDocTypeAlias; + function isTypeAlias(node) { + return isJSDocTypeAlias(node) || ts.isTypeAliasDeclaration(node); + } + ts.isTypeAlias = isTypeAlias; + function getSourceOfAssignment(node) { + return ts.isExpressionStatement(node) && + node.expression && ts.isBinaryExpression(node.expression) && + node.expression.operatorToken.kind === 59 + ? node.expression.right + : undefined; + } + function getSourceOfDefaultedAssignment(node) { + return ts.isExpressionStatement(node) && + ts.isBinaryExpression(node.expression) && + getAssignmentDeclarationKind(node.expression) !== 0 && + ts.isBinaryExpression(node.expression.right) && + node.expression.right.operatorToken.kind === 55 + ? node.expression.right.right + : undefined; + } + function getSingleInitializerOfVariableStatementOrPropertyDeclaration(node) { + switch (node.kind) { + case 219: + var v = getSingleVariableOfVariableStatement(node); + return v && v.initializer; + case 154: + return node.initializer; + case 275: + return node.initializer; + } + } + function getSingleVariableOfVariableStatement(node) { + return ts.isVariableStatement(node) ? ts.firstOrUndefined(node.declarationList.declarations) : undefined; + } + function getNestedModuleDeclaration(node) { + return ts.isModuleDeclaration(node) && + node.body && + node.body.kind === 244 + ? node.body + : undefined; + } + function getJSDocCommentsAndTags(hostNode) { + var result; + if (isVariableLike(hostNode) && ts.hasInitializer(hostNode) && ts.hasJSDocNodes(hostNode.initializer)) { + result = ts.addRange(result, hostNode.initializer.jsDoc); + } + var node = hostNode; + while (node && node.parent) { + if (ts.hasJSDocNodes(node)) { + result = ts.addRange(result, node.jsDoc); + } + if (node.kind === 151) { + result = ts.addRange(result, ts.getJSDocParameterTags(node)); + break; + } + if (node.kind === 150) { + result = ts.addRange(result, ts.getJSDocTypeParameterTags(node)); + break; + } + node = getNextJSDocCommentLocation(node); + } + return result || ts.emptyArray; + } + ts.getJSDocCommentsAndTags = getJSDocCommentsAndTags; + function getNextJSDocCommentLocation(node) { + var parent = node.parent; + if (parent.kind === 275 || + parent.kind === 154 || + parent.kind === 221 && node.kind === 189 || + getNestedModuleDeclaration(parent) || + ts.isBinaryExpression(node) && node.operatorToken.kind === 59) { + return parent; + } + else if (parent.parent && + (getSingleVariableOfVariableStatement(parent.parent) === node || + ts.isBinaryExpression(parent) && parent.operatorToken.kind === 59)) { + return parent.parent; + } + else if (parent.parent && parent.parent.parent && + (getSingleVariableOfVariableStatement(parent.parent.parent) || + getSingleInitializerOfVariableStatementOrPropertyDeclaration(parent.parent.parent) === node || + getSourceOfDefaultedAssignment(parent.parent.parent))) { + return parent.parent.parent; + } + } + function getParameterSymbolFromJSDoc(node) { + if (node.symbol) { + return node.symbol; + } + if (!ts.isIdentifier(node.name)) { + return undefined; + } + var name = node.name.escapedText; + var decl = getHostSignatureFromJSDoc(node); + if (!decl) { + return undefined; + } + var parameter = ts.find(decl.parameters, function (p) { return p.name.kind === 72 && p.name.escapedText === name; }); + return parameter && parameter.symbol; + } + ts.getParameterSymbolFromJSDoc = getParameterSymbolFromJSDoc; + function getHostSignatureFromJSDoc(node) { + return getHostSignatureFromJSDocHost(getJSDocHost(node)); + } + ts.getHostSignatureFromJSDoc = getHostSignatureFromJSDoc; + function getHostSignatureFromJSDocHost(host) { + var decl = getSourceOfDefaultedAssignment(host) || + getSourceOfAssignment(host) || + getSingleInitializerOfVariableStatementOrPropertyDeclaration(host) || + getSingleVariableOfVariableStatement(host) || + getNestedModuleDeclaration(host) || + host; + return decl && ts.isFunctionLike(decl) ? decl : undefined; + } + ts.getHostSignatureFromJSDocHost = getHostSignatureFromJSDocHost; + function getJSDocHost(node) { + return ts.Debug.assertDefined(findAncestor(node.parent, ts.isJSDoc)).parent; + } + ts.getJSDocHost = getJSDocHost; + function getTypeParameterFromJsDoc(node) { + var name = node.name.escapedText; + var typeParameters = node.parent.parent.parent.typeParameters; + return ts.find(typeParameters, function (p) { return p.name.escapedText === name; }); + } + ts.getTypeParameterFromJsDoc = getTypeParameterFromJsDoc; + function hasRestParameter(s) { + var last = ts.lastOrUndefined(s.parameters); + return !!last && isRestParameter(last); + } + ts.hasRestParameter = hasRestParameter; + function isRestParameter(node) { + var type = ts.isJSDocParameterTag(node) ? (node.typeExpression && node.typeExpression.type) : node.type; + return node.dotDotDotToken !== undefined || !!type && type.kind === 290; + } + ts.isRestParameter = isRestParameter; + function getAssignmentTargetKind(node) { + var parent = node.parent; + while (true) { + switch (parent.kind) { + case 204: + var binaryOperator = parent.operatorToken.kind; + return isAssignmentOperator(binaryOperator) && parent.left === node ? + binaryOperator === 59 ? 1 : 2 : + 0; + case 202: + case 203: + var unaryOperator = parent.operator; + return unaryOperator === 44 || unaryOperator === 45 ? 2 : 0; + case 226: + case 227: + return parent.initializer === node ? 1 : 0; + case 195: + case 187: + case 208: + case 213: + node = parent; + break; + case 276: + if (parent.name !== node) { + return 0; + } + node = parent.parent; + break; + case 275: + if (parent.name === node) { + return 0; + } + node = parent.parent; + break; + default: + return 0; + } + parent = node.parent; + } + } + ts.getAssignmentTargetKind = getAssignmentTargetKind; + function isAssignmentTarget(node) { + return getAssignmentTargetKind(node) !== 0; + } + ts.isAssignmentTarget = isAssignmentTarget; + function isNodeWithPossibleHoistedDeclaration(node) { + switch (node.kind) { + case 218: + case 219: + case 231: + case 222: + case 232: + case 246: + case 271: + case 272: + case 233: + case 225: + case 226: + case 227: + case 223: + case 224: + case 235: + case 274: + return true; + } + return false; + } + ts.isNodeWithPossibleHoistedDeclaration = isNodeWithPossibleHoistedDeclaration; + function isValueSignatureDeclaration(node) { + return ts.isFunctionExpression(node) || ts.isArrowFunction(node) || ts.isMethodOrAccessor(node) || ts.isFunctionDeclaration(node) || ts.isConstructorDeclaration(node); + } + ts.isValueSignatureDeclaration = isValueSignatureDeclaration; + function walkUp(node, kind) { + while (node && node.kind === kind) { + node = node.parent; + } + return node; + } + function walkUpParenthesizedTypes(node) { + return walkUp(node, 177); + } + ts.walkUpParenthesizedTypes = walkUpParenthesizedTypes; + function walkUpParenthesizedExpressions(node) { + return walkUp(node, 195); + } + ts.walkUpParenthesizedExpressions = walkUpParenthesizedExpressions; + function skipParentheses(node) { + while (node.kind === 195) { + node = node.expression; + } + return node; + } + ts.skipParentheses = skipParentheses; + function skipParenthesesUp(node) { + while (node.kind === 195) { + node = node.parent; + } + return node; + } + function isDeleteTarget(node) { + if (node.kind !== 189 && node.kind !== 190) { + return false; + } + node = walkUpParenthesizedExpressions(node.parent); + return node && node.kind === 198; + } + ts.isDeleteTarget = isDeleteTarget; + function isNodeDescendantOf(node, ancestor) { + while (node) { + if (node === ancestor) + return true; + node = node.parent; + } + return false; + } + ts.isNodeDescendantOf = isNodeDescendantOf; + function isDeclarationName(name) { + return !ts.isSourceFile(name) && !ts.isBindingPattern(name) && ts.isDeclaration(name.parent) && name.parent.name === name; + } + ts.isDeclarationName = isDeclarationName; + function getDeclarationFromName(name) { + var parent = name.parent; + switch (name.kind) { + case 10: + case 8: + if (ts.isComputedPropertyName(parent)) + return parent.parent; + case 72: + if (ts.isDeclaration(parent)) { + return parent.name === name ? parent : undefined; + } + else if (ts.isQualifiedName(parent)) { + var tag = parent.parent; + return ts.isJSDocParameterTag(tag) && tag.name === parent ? tag : undefined; + } + else { + var binExp = parent.parent; + return ts.isBinaryExpression(binExp) && + getAssignmentDeclarationKind(binExp) !== 0 && + (binExp.left.symbol || binExp.symbol) && + ts.getNameOfDeclaration(binExp) === name + ? binExp + : undefined; + } + default: + return undefined; + } + } + ts.getDeclarationFromName = getDeclarationFromName; + function isLiteralComputedPropertyDeclarationName(node) { + return (node.kind === 10 || node.kind === 8) && + node.parent.kind === 149 && + ts.isDeclaration(node.parent.parent); + } + ts.isLiteralComputedPropertyDeclarationName = isLiteralComputedPropertyDeclarationName; + function isIdentifierName(node) { + var parent = node.parent; + switch (parent.kind) { + case 154: + case 153: + case 156: + case 155: + case 158: + case 159: + case 278: + case 275: + case 189: + return parent.name === node; + case 148: + if (parent.right === node) { + while (parent.kind === 148) { + parent = parent.parent; + } + return parent.kind === 167 || parent.kind === 164; + } + return false; + case 186: + case 253: + return parent.propertyName === node; + case 257: + case 267: + return true; + } + return false; + } + ts.isIdentifierName = isIdentifierName; + function isAliasSymbolDeclaration(node) { + return node.kind === 248 || + node.kind === 247 || + node.kind === 250 && !!node.name || + node.kind === 251 || + node.kind === 253 || + node.kind === 257 || + node.kind === 254 && exportAssignmentIsAlias(node) || + ts.isBinaryExpression(node) && getAssignmentDeclarationKind(node) === 2 && exportAssignmentIsAlias(node); + } + ts.isAliasSymbolDeclaration = isAliasSymbolDeclaration; + function exportAssignmentIsAlias(node) { + var e = ts.isExportAssignment(node) ? node.expression : node.right; + return isEntityNameExpression(e) || ts.isClassExpression(e); + } + ts.exportAssignmentIsAlias = exportAssignmentIsAlias; + function getEffectiveBaseTypeNode(node) { + if (isInJSFile(node)) { + var tag = ts.getJSDocAugmentsTag(node); + if (tag) { + return tag.class; + } + } + return getClassExtendsHeritageElement(node); + } + ts.getEffectiveBaseTypeNode = getEffectiveBaseTypeNode; + function getClassExtendsHeritageElement(node) { + var heritageClause = getHeritageClause(node.heritageClauses, 86); + return heritageClause && heritageClause.types.length > 0 ? heritageClause.types[0] : undefined; + } + ts.getClassExtendsHeritageElement = getClassExtendsHeritageElement; + function getClassImplementsHeritageClauseElements(node) { + var heritageClause = getHeritageClause(node.heritageClauses, 109); + return heritageClause ? heritageClause.types : undefined; + } + ts.getClassImplementsHeritageClauseElements = getClassImplementsHeritageClauseElements; + function getAllSuperTypeNodes(node) { + return ts.isInterfaceDeclaration(node) ? getInterfaceBaseTypeNodes(node) || ts.emptyArray + : ts.isClassLike(node) ? ts.concatenate(ts.singleElementArray(getEffectiveBaseTypeNode(node)), getClassImplementsHeritageClauseElements(node)) || ts.emptyArray + : ts.emptyArray; + } + ts.getAllSuperTypeNodes = getAllSuperTypeNodes; + function getInterfaceBaseTypeNodes(node) { + var heritageClause = getHeritageClause(node.heritageClauses, 86); + return heritageClause ? heritageClause.types : undefined; + } + ts.getInterfaceBaseTypeNodes = getInterfaceBaseTypeNodes; + function getHeritageClause(clauses, kind) { + if (clauses) { + for (var _i = 0, clauses_1 = clauses; _i < clauses_1.length; _i++) { + var clause = clauses_1[_i]; + if (clause.token === kind) { + return clause; + } + } + } + return undefined; + } + ts.getHeritageClause = getHeritageClause; + function tryResolveScriptReference(host, sourceFile, reference) { + if (!host.getCompilerOptions().noResolve) { + var referenceFileName = ts.isRootedDiskPath(reference.fileName) ? reference.fileName : ts.combinePaths(ts.getDirectoryPath(sourceFile.fileName), reference.fileName); + return host.getSourceFile(referenceFileName); + } + } + ts.tryResolveScriptReference = tryResolveScriptReference; + function getAncestor(node, kind) { + while (node) { + if (node.kind === kind) { + return node; + } + node = node.parent; + } + return undefined; + } + ts.getAncestor = getAncestor; + function isKeyword(token) { + return 73 <= token && token <= 147; + } + ts.isKeyword = isKeyword; + function isContextualKeyword(token) { + return 118 <= token && token <= 147; + } + ts.isContextualKeyword = isContextualKeyword; + function isNonContextualKeyword(token) { + return isKeyword(token) && !isContextualKeyword(token); + } + ts.isNonContextualKeyword = isNonContextualKeyword; + function isStringANonContextualKeyword(name) { + var token = ts.stringToToken(name); + return token !== undefined && isNonContextualKeyword(token); + } + ts.isStringANonContextualKeyword = isStringANonContextualKeyword; + function isIdentifierANonContextualKeyword(_a) { + var originalKeywordKind = _a.originalKeywordKind; + return !!originalKeywordKind && !isContextualKeyword(originalKeywordKind); + } + ts.isIdentifierANonContextualKeyword = isIdentifierANonContextualKeyword; + function isTrivia(token) { + return 2 <= token && token <= 7; + } + ts.isTrivia = isTrivia; + function getFunctionFlags(node) { + if (!node) { + return 4; + } + var flags = 0; + switch (node.kind) { + case 239: + case 196: + case 156: + if (node.asteriskToken) { + flags |= 1; + } + case 197: + if (hasModifier(node, 256)) { + flags |= 2; + } + break; + } + if (!node.body) { + flags |= 4; + } + return flags; + } + ts.getFunctionFlags = getFunctionFlags; + function isAsyncFunction(node) { + switch (node.kind) { + case 239: + case 196: + case 197: + case 156: + return node.body !== undefined + && node.asteriskToken === undefined + && hasModifier(node, 256); + } + return false; + } + ts.isAsyncFunction = isAsyncFunction; + function isStringOrNumericLiteralLike(node) { + return ts.isStringLiteralLike(node) || ts.isNumericLiteral(node); + } + ts.isStringOrNumericLiteralLike = isStringOrNumericLiteralLike; + function hasDynamicName(declaration) { + var name = ts.getNameOfDeclaration(declaration); + return !!name && isDynamicName(name); + } + ts.hasDynamicName = hasDynamicName; + function isDynamicName(name) { + return name.kind === 149 && + !isStringOrNumericLiteralLike(name.expression) && + !isWellKnownSymbolSyntactically(name.expression); + } + ts.isDynamicName = isDynamicName; + function isWellKnownSymbolSyntactically(node) { + return ts.isPropertyAccessExpression(node) && isESSymbolIdentifier(node.expression); + } + ts.isWellKnownSymbolSyntactically = isWellKnownSymbolSyntactically; + function getPropertyNameForPropertyNameNode(name) { + switch (name.kind) { + case 72: + return name.escapedText; + case 10: + case 8: + return ts.escapeLeadingUnderscores(name.text); + case 149: + var nameExpression = name.expression; + if (isWellKnownSymbolSyntactically(nameExpression)) { + return getPropertyNameForKnownSymbolName(ts.idText(nameExpression.name)); + } + else if (isStringOrNumericLiteralLike(nameExpression)) { + return ts.escapeLeadingUnderscores(nameExpression.text); + } + return undefined; + default: + return ts.Debug.assertNever(name); + } + } + ts.getPropertyNameForPropertyNameNode = getPropertyNameForPropertyNameNode; + function isPropertyNameLiteral(node) { + switch (node.kind) { + case 72: + case 10: + case 14: + case 8: + return true; + default: + return false; + } + } + ts.isPropertyNameLiteral = isPropertyNameLiteral; + function getTextOfIdentifierOrLiteral(node) { + return node.kind === 72 ? ts.idText(node) : node.text; + } + ts.getTextOfIdentifierOrLiteral = getTextOfIdentifierOrLiteral; + function getEscapedTextOfIdentifierOrLiteral(node) { + return node.kind === 72 ? node.escapedText : ts.escapeLeadingUnderscores(node.text); + } + ts.getEscapedTextOfIdentifierOrLiteral = getEscapedTextOfIdentifierOrLiteral; + function getPropertyNameForKnownSymbolName(symbolName) { + return "__@" + symbolName; + } + ts.getPropertyNameForKnownSymbolName = getPropertyNameForKnownSymbolName; + function isKnownSymbol(symbol) { + return ts.startsWith(symbol.escapedName, "__@"); + } + ts.isKnownSymbol = isKnownSymbol; + function isESSymbolIdentifier(node) { + return node.kind === 72 && node.escapedText === "Symbol"; + } + ts.isESSymbolIdentifier = isESSymbolIdentifier; + function isPushOrUnshiftIdentifier(node) { + return node.escapedText === "push" || node.escapedText === "unshift"; + } + ts.isPushOrUnshiftIdentifier = isPushOrUnshiftIdentifier; + function isParameterDeclaration(node) { + var root = getRootDeclaration(node); + return root.kind === 151; + } + ts.isParameterDeclaration = isParameterDeclaration; + function getRootDeclaration(node) { + while (node.kind === 186) { + node = node.parent.parent; + } + return node; + } + ts.getRootDeclaration = getRootDeclaration; + function nodeStartsNewLexicalEnvironment(node) { + var kind = node.kind; + return kind === 157 + || kind === 196 + || kind === 239 + || kind === 197 + || kind === 156 + || kind === 158 + || kind === 159 + || kind === 244 + || kind === 279; + } + ts.nodeStartsNewLexicalEnvironment = nodeStartsNewLexicalEnvironment; + function nodeIsSynthesized(range) { + return ts.positionIsSynthesized(range.pos) + || ts.positionIsSynthesized(range.end); + } + ts.nodeIsSynthesized = nodeIsSynthesized; + function getOriginalSourceFile(sourceFile) { + return ts.getParseTreeNode(sourceFile, ts.isSourceFile) || sourceFile; + } + ts.getOriginalSourceFile = getOriginalSourceFile; + function getExpressionAssociativity(expression) { + var operator = getOperator(expression); + var hasArguments = expression.kind === 192 && expression.arguments !== undefined; + return getOperatorAssociativity(expression.kind, operator, hasArguments); + } + ts.getExpressionAssociativity = getExpressionAssociativity; + function getOperatorAssociativity(kind, operator, hasArguments) { + switch (kind) { + case 192: + return hasArguments ? 0 : 1; + case 202: + case 199: + case 200: + case 198: + case 201: + case 205: + case 207: + return 1; + case 204: + switch (operator) { + case 41: + case 59: + case 60: + case 61: + case 63: + case 62: + case 64: + case 65: + case 66: + case 67: + case 68: + case 69: + case 71: + case 70: + return 1; + } + } + return 0; + } + ts.getOperatorAssociativity = getOperatorAssociativity; + function getExpressionPrecedence(expression) { + var operator = getOperator(expression); + var hasArguments = expression.kind === 192 && expression.arguments !== undefined; + return getOperatorPrecedence(expression.kind, operator, hasArguments); + } + ts.getExpressionPrecedence = getExpressionPrecedence; + function getOperator(expression) { + if (expression.kind === 204) { + return expression.operatorToken.kind; + } + else if (expression.kind === 202 || expression.kind === 203) { + return expression.operator; + } + else { + return expression.kind; + } + } + ts.getOperator = getOperator; + function getOperatorPrecedence(nodeKind, operatorKind, hasArguments) { + switch (nodeKind) { + case 309: + return 0; + case 208: + return 1; + case 207: + return 2; + case 205: + return 4; + case 204: + switch (operatorKind) { + case 27: + return 0; + case 59: + case 60: + case 61: + case 63: + case 62: + case 64: + case 65: + case 66: + case 67: + case 68: + case 69: + case 71: + case 70: + return 3; + default: + return getBinaryOperatorPrecedence(operatorKind); + } + case 202: + case 199: + case 200: + case 198: + case 201: + return 16; + case 203: + return 17; + case 191: + return 18; + case 192: + return hasArguments ? 19 : 18; + case 193: + case 189: + case 190: + return 19; + case 100: + case 98: + case 72: + case 96: + case 102: + case 87: + case 8: + case 9: + case 10: + case 187: + case 188: + case 196: + case 197: + case 209: + case 260: + case 261: + case 264: + case 13: + case 14: + case 206: + case 195: + case 210: + return 20; + default: + return -1; + } + } + ts.getOperatorPrecedence = getOperatorPrecedence; + function getBinaryOperatorPrecedence(kind) { + switch (kind) { + case 55: + return 5; + case 54: + return 6; + case 50: + return 7; + case 51: + return 8; + case 49: + return 9; + case 33: + case 34: + case 35: + case 36: + return 10; + case 28: + case 30: + case 31: + case 32: + case 94: + case 93: + case 119: + return 11; + case 46: + case 47: + case 48: + return 12; + case 38: + case 39: + return 13; + case 40: + case 42: + case 43: + return 14; + case 41: + return 15; + } + return -1; + } + ts.getBinaryOperatorPrecedence = getBinaryOperatorPrecedence; + function createDiagnosticCollection() { + var nonFileDiagnostics = []; + var filesWithDiagnostics = []; + var fileDiagnostics = ts.createMap(); + var hasReadNonFileDiagnostics = false; + return { + add: add, + lookup: lookup, + getGlobalDiagnostics: getGlobalDiagnostics, + getDiagnostics: getDiagnostics, + reattachFileDiagnostics: reattachFileDiagnostics + }; + function reattachFileDiagnostics(newFile) { + ts.forEach(fileDiagnostics.get(newFile.fileName), function (diagnostic) { return diagnostic.file = newFile; }); + } + function lookup(diagnostic) { + var diagnostics; + if (diagnostic.file) { + diagnostics = fileDiagnostics.get(diagnostic.file.fileName); + } + else { + diagnostics = nonFileDiagnostics; + } + if (!diagnostics) { + return undefined; + } + var result = ts.binarySearch(diagnostics, diagnostic, ts.identity, ts.compareDiagnosticsSkipRelatedInformation); + if (result >= 0) { + return diagnostics[result]; + } + return undefined; + } + function add(diagnostic) { + var diagnostics; + if (diagnostic.file) { + diagnostics = fileDiagnostics.get(diagnostic.file.fileName); + if (!diagnostics) { + diagnostics = []; + fileDiagnostics.set(diagnostic.file.fileName, diagnostics); + ts.insertSorted(filesWithDiagnostics, diagnostic.file.fileName, ts.compareStringsCaseSensitive); + } + } + else { + if (hasReadNonFileDiagnostics) { + hasReadNonFileDiagnostics = false; + nonFileDiagnostics = nonFileDiagnostics.slice(); + } + diagnostics = nonFileDiagnostics; + } + ts.insertSorted(diagnostics, diagnostic, ts.compareDiagnostics); + } + function getGlobalDiagnostics() { + hasReadNonFileDiagnostics = true; + return nonFileDiagnostics; + } + function getDiagnostics(fileName) { + if (fileName) { + return fileDiagnostics.get(fileName) || []; + } + var fileDiags = ts.flatMapToMutable(filesWithDiagnostics, function (f) { return fileDiagnostics.get(f); }); + if (!nonFileDiagnostics.length) { + return fileDiags; + } + fileDiags.unshift.apply(fileDiags, nonFileDiagnostics); + return fileDiags; + } + } + ts.createDiagnosticCollection = createDiagnosticCollection; + var doubleQuoteEscapedCharsRegExp = /[\\\"\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g; + var singleQuoteEscapedCharsRegExp = /[\\\'\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g; + var backtickQuoteEscapedCharsRegExp = /[\\\`\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g; + var escapedCharsMap = ts.createMapFromTemplate({ + "\t": "\\t", + "\v": "\\v", + "\f": "\\f", + "\b": "\\b", + "\r": "\\r", + "\n": "\\n", + "\\": "\\\\", + "\"": "\\\"", + "\'": "\\\'", + "\`": "\\\`", + "\u2028": "\\u2028", + "\u2029": "\\u2029", + "\u0085": "\\u0085" + }); + function escapeString(s, quoteChar) { + var escapedCharsRegExp = quoteChar === 96 ? backtickQuoteEscapedCharsRegExp : + quoteChar === 39 ? singleQuoteEscapedCharsRegExp : + doubleQuoteEscapedCharsRegExp; + return s.replace(escapedCharsRegExp, getReplacement); + } + ts.escapeString = escapeString; + function getReplacement(c, offset, input) { + if (c.charCodeAt(0) === 0) { + var lookAhead = input.charCodeAt(offset + c.length); + if (lookAhead >= 48 && lookAhead <= 57) { + return "\\x00"; + } + return "\\0"; + } + return escapedCharsMap.get(c) || get16BitUnicodeEscapeSequence(c.charCodeAt(0)); + } + function isIntrinsicJsxName(name) { + var ch = name.charCodeAt(0); + return (ch >= 97 && ch <= 122) || ts.stringContains(name, "-"); + } + ts.isIntrinsicJsxName = isIntrinsicJsxName; + function get16BitUnicodeEscapeSequence(charCode) { + var hexCharCode = charCode.toString(16).toUpperCase(); + var paddedHexCode = ("0000" + hexCharCode).slice(-4); + return "\\u" + paddedHexCode; + } + var nonAsciiCharacters = /[^\u0000-\u007F]/g; + function escapeNonAsciiString(s, quoteChar) { + s = escapeString(s, quoteChar); + return nonAsciiCharacters.test(s) ? + s.replace(nonAsciiCharacters, function (c) { return get16BitUnicodeEscapeSequence(c.charCodeAt(0)); }) : + s; + } + ts.escapeNonAsciiString = escapeNonAsciiString; + var indentStrings = ["", " "]; + function getIndentString(level) { + if (indentStrings[level] === undefined) { + indentStrings[level] = getIndentString(level - 1) + indentStrings[1]; + } + return indentStrings[level]; + } + ts.getIndentString = getIndentString; + function getIndentSize() { + return indentStrings[1].length; + } + ts.getIndentSize = getIndentSize; + function createTextWriter(newLine) { + var output; + var indent; + var lineStart; + var lineCount; + var linePos; + function updateLineCountAndPosFor(s) { + var lineStartsOfS = ts.computeLineStarts(s); + if (lineStartsOfS.length > 1) { + lineCount = lineCount + lineStartsOfS.length - 1; + linePos = output.length - s.length + ts.last(lineStartsOfS); + lineStart = (linePos - output.length) === 0; + } + else { + lineStart = false; + } + } + function write(s) { + if (s && s.length) { + if (lineStart) { + s = getIndentString(indent) + s; + lineStart = false; + } + output += s; + updateLineCountAndPosFor(s); + } + } + function reset() { + output = ""; + indent = 0; + lineStart = true; + lineCount = 0; + linePos = 0; + } + function rawWrite(s) { + if (s !== undefined) { + output += s; + updateLineCountAndPosFor(s); + } + } + function writeLiteral(s) { + if (s && s.length) { + write(s); + } + } + function writeLine() { + if (!lineStart) { + output += newLine; + lineCount++; + linePos = output.length; + lineStart = true; + } + } + reset(); + return { + write: write, + rawWrite: rawWrite, + writeLiteral: writeLiteral, + writeLine: writeLine, + increaseIndent: function () { indent++; }, + decreaseIndent: function () { indent--; }, + getIndent: function () { return indent; }, + getTextPos: function () { return output.length; }, + getLine: function () { return lineCount; }, + getColumn: function () { return lineStart ? indent * getIndentSize() : output.length - linePos; }, + getText: function () { return output; }, + isAtStartOfLine: function () { return lineStart; }, + clear: reset, + reportInaccessibleThisError: ts.noop, + reportPrivateInBaseOfClassExpression: ts.noop, + reportInaccessibleUniqueSymbolError: ts.noop, + trackSymbol: ts.noop, + writeKeyword: write, + writeOperator: write, + writeParameter: write, + writeProperty: write, + writePunctuation: write, + writeSpace: write, + writeStringLiteral: write, + writeSymbol: function (s, _) { return write(s); }, + writeTrailingSemicolon: write, + writeComment: write + }; + } + ts.createTextWriter = createTextWriter; + function getTrailingSemicolonOmittingWriter(writer) { + var pendingTrailingSemicolon = false; + function commitPendingTrailingSemicolon() { + if (pendingTrailingSemicolon) { + writer.writeTrailingSemicolon(";"); + pendingTrailingSemicolon = false; + } + } + return __assign({}, writer, { writeTrailingSemicolon: function () { + pendingTrailingSemicolon = true; + }, + writeLiteral: function (s) { + commitPendingTrailingSemicolon(); + writer.writeLiteral(s); + }, + writeStringLiteral: function (s) { + commitPendingTrailingSemicolon(); + writer.writeStringLiteral(s); + }, + writeSymbol: function (s, sym) { + commitPendingTrailingSemicolon(); + writer.writeSymbol(s, sym); + }, + writePunctuation: function (s) { + commitPendingTrailingSemicolon(); + writer.writePunctuation(s); + }, + writeKeyword: function (s) { + commitPendingTrailingSemicolon(); + writer.writeKeyword(s); + }, + writeOperator: function (s) { + commitPendingTrailingSemicolon(); + writer.writeOperator(s); + }, + writeParameter: function (s) { + commitPendingTrailingSemicolon(); + writer.writeParameter(s); + }, + writeSpace: function (s) { + commitPendingTrailingSemicolon(); + writer.writeSpace(s); + }, + writeProperty: function (s) { + commitPendingTrailingSemicolon(); + writer.writeProperty(s); + }, + writeComment: function (s) { + commitPendingTrailingSemicolon(); + writer.writeComment(s); + }, + writeLine: function () { + commitPendingTrailingSemicolon(); + writer.writeLine(); + }, + increaseIndent: function () { + commitPendingTrailingSemicolon(); + writer.increaseIndent(); + }, + decreaseIndent: function () { + commitPendingTrailingSemicolon(); + writer.decreaseIndent(); + } }); + } + ts.getTrailingSemicolonOmittingWriter = getTrailingSemicolonOmittingWriter; + function getResolvedExternalModuleName(host, file, referenceFile) { + return file.moduleName || getExternalModuleNameFromPath(host, file.fileName, referenceFile && referenceFile.fileName); + } + ts.getResolvedExternalModuleName = getResolvedExternalModuleName; + function getExternalModuleNameFromDeclaration(host, resolver, declaration) { + var file = resolver.getExternalModuleFileFromDeclaration(declaration); + if (!file || file.isDeclarationFile) { + return undefined; + } + return getResolvedExternalModuleName(host, file); + } + ts.getExternalModuleNameFromDeclaration = getExternalModuleNameFromDeclaration; + function getExternalModuleNameFromPath(host, fileName, referencePath) { + var getCanonicalFileName = function (f) { return host.getCanonicalFileName(f); }; + var dir = toPath(referencePath ? ts.getDirectoryPath(referencePath) : host.getCommonSourceDirectory(), host.getCurrentDirectory(), getCanonicalFileName); + var filePath = ts.getNormalizedAbsolutePath(fileName, host.getCurrentDirectory()); + var relativePath = ts.getRelativePathToDirectoryOrUrl(dir, filePath, dir, getCanonicalFileName, false); + var extensionless = ts.removeFileExtension(relativePath); + return referencePath ? ts.ensurePathIsNonModuleName(extensionless) : extensionless; + } + ts.getExternalModuleNameFromPath = getExternalModuleNameFromPath; + function getOwnEmitOutputFilePath(fileName, host, extension) { + var compilerOptions = host.getCompilerOptions(); + var emitOutputFilePathWithoutExtension; + if (compilerOptions.outDir) { + emitOutputFilePathWithoutExtension = ts.removeFileExtension(getSourceFilePathInNewDir(fileName, host, compilerOptions.outDir)); + } + else { + emitOutputFilePathWithoutExtension = ts.removeFileExtension(fileName); + } + return emitOutputFilePathWithoutExtension + extension; + } + ts.getOwnEmitOutputFilePath = getOwnEmitOutputFilePath; + function getDeclarationEmitOutputFilePath(fileName, host) { + return getDeclarationEmitOutputFilePathWorker(fileName, host.getCompilerOptions(), host.getCurrentDirectory(), host.getCommonSourceDirectory(), function (f) { return host.getCanonicalFileName(f); }); + } + ts.getDeclarationEmitOutputFilePath = getDeclarationEmitOutputFilePath; + function getDeclarationEmitOutputFilePathWorker(fileName, options, currentDirectory, commonSourceDirectory, getCanonicalFileName) { + var outputDir = options.declarationDir || options.outDir; + var path = outputDir + ? getSourceFilePathInNewDirWorker(fileName, outputDir, currentDirectory, commonSourceDirectory, getCanonicalFileName) + : fileName; + return ts.removeFileExtension(path) + ".d.ts"; + } + ts.getDeclarationEmitOutputFilePathWorker = getDeclarationEmitOutputFilePathWorker; + function getSourceFilesToEmit(host, targetSourceFile) { + var options = host.getCompilerOptions(); + var isSourceFileFromExternalLibrary = function (file) { return host.isSourceFileFromExternalLibrary(file); }; + if (options.outFile || options.out) { + var moduleKind = ts.getEmitModuleKind(options); + var moduleEmitEnabled_1 = options.emitDeclarationOnly || moduleKind === ts.ModuleKind.AMD || moduleKind === ts.ModuleKind.System; + return ts.filter(host.getSourceFiles(), function (sourceFile) { + return (moduleEmitEnabled_1 || !ts.isExternalModule(sourceFile)) && sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary); + }); + } + else { + var sourceFiles = targetSourceFile === undefined ? host.getSourceFiles() : [targetSourceFile]; + return ts.filter(sourceFiles, function (sourceFile) { return sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary); }); + } + } + ts.getSourceFilesToEmit = getSourceFilesToEmit; + function sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary) { + return !(options.noEmitForJsFiles && isSourceFileJS(sourceFile)) && !sourceFile.isDeclarationFile && !isSourceFileFromExternalLibrary(sourceFile); + } + ts.sourceFileMayBeEmitted = sourceFileMayBeEmitted; + function getSourceFilePathInNewDir(fileName, host, newDirPath) { + return getSourceFilePathInNewDirWorker(fileName, newDirPath, host.getCurrentDirectory(), host.getCommonSourceDirectory(), function (f) { return host.getCanonicalFileName(f); }); + } + ts.getSourceFilePathInNewDir = getSourceFilePathInNewDir; + function getSourceFilePathInNewDirWorker(fileName, newDirPath, currentDirectory, commonSourceDirectory, getCanonicalFileName) { + var sourceFilePath = ts.getNormalizedAbsolutePath(fileName, currentDirectory); + var isSourceFileInCommonSourceDirectory = getCanonicalFileName(sourceFilePath).indexOf(getCanonicalFileName(commonSourceDirectory)) === 0; + sourceFilePath = isSourceFileInCommonSourceDirectory ? sourceFilePath.substring(commonSourceDirectory.length) : sourceFilePath; + return ts.combinePaths(newDirPath, sourceFilePath); + } + ts.getSourceFilePathInNewDirWorker = getSourceFilePathInNewDirWorker; + function writeFile(host, diagnostics, fileName, data, writeByteOrderMark, sourceFiles) { + host.writeFile(fileName, data, writeByteOrderMark, function (hostErrorMessage) { + diagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Could_not_write_file_0_Colon_1, fileName, hostErrorMessage)); + }, sourceFiles); + } + ts.writeFile = writeFile; + function getLineOfLocalPosition(currentSourceFile, pos) { + return ts.getLineAndCharacterOfPosition(currentSourceFile, pos).line; + } + ts.getLineOfLocalPosition = getLineOfLocalPosition; + function getLineOfLocalPositionFromLineMap(lineMap, pos) { + return ts.computeLineAndCharacterOfPosition(lineMap, pos).line; + } + ts.getLineOfLocalPositionFromLineMap = getLineOfLocalPositionFromLineMap; + function getFirstConstructorWithBody(node) { + return ts.find(node.members, function (member) { return ts.isConstructorDeclaration(member) && nodeIsPresent(member.body); }); + } + ts.getFirstConstructorWithBody = getFirstConstructorWithBody; + function getSetAccessorValueParameter(accessor) { + if (accessor && accessor.parameters.length > 0) { + var hasThis = accessor.parameters.length === 2 && parameterIsThisKeyword(accessor.parameters[0]); + return accessor.parameters[hasThis ? 1 : 0]; + } + } + function getSetAccessorTypeAnnotationNode(accessor) { + var parameter = getSetAccessorValueParameter(accessor); + return parameter && parameter.type; + } + ts.getSetAccessorTypeAnnotationNode = getSetAccessorTypeAnnotationNode; + function getThisParameter(signature) { + if (signature.parameters.length && !ts.isJSDocSignature(signature)) { + var thisParameter = signature.parameters[0]; + if (parameterIsThisKeyword(thisParameter)) { + return thisParameter; + } + } + } + ts.getThisParameter = getThisParameter; + function parameterIsThisKeyword(parameter) { + return isThisIdentifier(parameter.name); + } + ts.parameterIsThisKeyword = parameterIsThisKeyword; + function isThisIdentifier(node) { + return !!node && node.kind === 72 && identifierIsThisKeyword(node); + } + ts.isThisIdentifier = isThisIdentifier; + function identifierIsThisKeyword(id) { + return id.originalKeywordKind === 100; + } + ts.identifierIsThisKeyword = identifierIsThisKeyword; + function getAllAccessorDeclarations(declarations, accessor) { + var firstAccessor; + var secondAccessor; + var getAccessor; + var setAccessor; + if (hasDynamicName(accessor)) { + firstAccessor = accessor; + if (accessor.kind === 158) { + getAccessor = accessor; + } + else if (accessor.kind === 159) { + setAccessor = accessor; + } + else { + ts.Debug.fail("Accessor has wrong kind"); + } + } + else { + ts.forEach(declarations, function (member) { + if (ts.isAccessor(member) + && hasModifier(member, 32) === hasModifier(accessor, 32)) { + var memberName = getPropertyNameForPropertyNameNode(member.name); + var accessorName = getPropertyNameForPropertyNameNode(accessor.name); + if (memberName === accessorName) { + if (!firstAccessor) { + firstAccessor = member; + } + else if (!secondAccessor) { + secondAccessor = member; + } + if (member.kind === 158 && !getAccessor) { + getAccessor = member; + } + if (member.kind === 159 && !setAccessor) { + setAccessor = member; + } + } + } + }); + } + return { + firstAccessor: firstAccessor, + secondAccessor: secondAccessor, + getAccessor: getAccessor, + setAccessor: setAccessor + }; + } + ts.getAllAccessorDeclarations = getAllAccessorDeclarations; + function getEffectiveTypeAnnotationNode(node) { + var type = node.type; + if (type || !isInJSFile(node)) + return type; + return ts.isJSDocPropertyLikeTag(node) ? node.typeExpression && node.typeExpression.type : ts.getJSDocType(node); + } + ts.getEffectiveTypeAnnotationNode = getEffectiveTypeAnnotationNode; + function getTypeAnnotationNode(node) { + return node.type; + } + ts.getTypeAnnotationNode = getTypeAnnotationNode; + function getEffectiveReturnTypeNode(node) { + return ts.isJSDocSignature(node) ? + node.type && node.type.typeExpression && node.type.typeExpression.type : + node.type || (isInJSFile(node) ? ts.getJSDocReturnType(node) : undefined); + } + ts.getEffectiveReturnTypeNode = getEffectiveReturnTypeNode; + function getJSDocTypeParameterDeclarations(node) { + return ts.flatMap(ts.getJSDocTags(node), function (tag) { return isNonTypeAliasTemplate(tag) ? tag.typeParameters : undefined; }); + } + ts.getJSDocTypeParameterDeclarations = getJSDocTypeParameterDeclarations; + function isNonTypeAliasTemplate(tag) { + return ts.isJSDocTemplateTag(tag) && !(tag.parent.kind === 291 && tag.parent.tags.some(isJSDocTypeAlias)); + } + function getEffectiveSetAccessorTypeAnnotationNode(node) { + var parameter = getSetAccessorValueParameter(node); + return parameter && getEffectiveTypeAnnotationNode(parameter); + } + ts.getEffectiveSetAccessorTypeAnnotationNode = getEffectiveSetAccessorTypeAnnotationNode; + function emitNewLineBeforeLeadingComments(lineMap, writer, node, leadingComments) { + emitNewLineBeforeLeadingCommentsOfPosition(lineMap, writer, node.pos, leadingComments); + } + ts.emitNewLineBeforeLeadingComments = emitNewLineBeforeLeadingComments; + function emitNewLineBeforeLeadingCommentsOfPosition(lineMap, writer, pos, leadingComments) { + if (leadingComments && leadingComments.length && pos !== leadingComments[0].pos && + getLineOfLocalPositionFromLineMap(lineMap, pos) !== getLineOfLocalPositionFromLineMap(lineMap, leadingComments[0].pos)) { + writer.writeLine(); + } + } + ts.emitNewLineBeforeLeadingCommentsOfPosition = emitNewLineBeforeLeadingCommentsOfPosition; + function emitNewLineBeforeLeadingCommentOfPosition(lineMap, writer, pos, commentPos) { + if (pos !== commentPos && + getLineOfLocalPositionFromLineMap(lineMap, pos) !== getLineOfLocalPositionFromLineMap(lineMap, commentPos)) { + writer.writeLine(); + } + } + ts.emitNewLineBeforeLeadingCommentOfPosition = emitNewLineBeforeLeadingCommentOfPosition; + function emitComments(text, lineMap, writer, comments, leadingSeparator, trailingSeparator, newLine, writeComment) { + if (comments && comments.length > 0) { + if (leadingSeparator) { + writer.writeSpace(" "); + } + var emitInterveningSeparator = false; + for (var _i = 0, comments_1 = comments; _i < comments_1.length; _i++) { + var comment = comments_1[_i]; + if (emitInterveningSeparator) { + writer.writeSpace(" "); + emitInterveningSeparator = false; + } + writeComment(text, lineMap, writer, comment.pos, comment.end, newLine); + if (comment.hasTrailingNewLine) { + writer.writeLine(); + } + else { + emitInterveningSeparator = true; + } + } + if (emitInterveningSeparator && trailingSeparator) { + writer.writeSpace(" "); + } + } + } + ts.emitComments = emitComments; + function emitDetachedComments(text, lineMap, writer, writeComment, node, newLine, removeComments) { + var leadingComments; + var currentDetachedCommentInfo; + if (removeComments) { + if (node.pos === 0) { + leadingComments = ts.filter(ts.getLeadingCommentRanges(text, node.pos), isPinnedCommentLocal); + } + } + else { + leadingComments = ts.getLeadingCommentRanges(text, node.pos); + } + if (leadingComments) { + var detachedComments = []; + var lastComment = void 0; + for (var _i = 0, leadingComments_1 = leadingComments; _i < leadingComments_1.length; _i++) { + var comment = leadingComments_1[_i]; + if (lastComment) { + var lastCommentLine = getLineOfLocalPositionFromLineMap(lineMap, lastComment.end); + var commentLine = getLineOfLocalPositionFromLineMap(lineMap, comment.pos); + if (commentLine >= lastCommentLine + 2) { + break; + } + } + detachedComments.push(comment); + lastComment = comment; + } + if (detachedComments.length) { + var lastCommentLine = getLineOfLocalPositionFromLineMap(lineMap, ts.last(detachedComments).end); + var nodeLine = getLineOfLocalPositionFromLineMap(lineMap, ts.skipTrivia(text, node.pos)); + if (nodeLine >= lastCommentLine + 2) { + emitNewLineBeforeLeadingComments(lineMap, writer, node, leadingComments); + emitComments(text, lineMap, writer, detachedComments, false, true, newLine, writeComment); + currentDetachedCommentInfo = { nodePos: node.pos, detachedCommentEndPos: ts.last(detachedComments).end }; + } + } + } + return currentDetachedCommentInfo; + function isPinnedCommentLocal(comment) { + return isPinnedComment(text, comment.pos); + } + } + ts.emitDetachedComments = emitDetachedComments; + function writeCommentRange(text, lineMap, writer, commentPos, commentEnd, newLine) { + if (text.charCodeAt(commentPos + 1) === 42) { + var firstCommentLineAndCharacter = ts.computeLineAndCharacterOfPosition(lineMap, commentPos); + var lineCount = lineMap.length; + var firstCommentLineIndent = void 0; + for (var pos = commentPos, currentLine = firstCommentLineAndCharacter.line; pos < commentEnd; currentLine++) { + var nextLineStart = (currentLine + 1) === lineCount + ? text.length + 1 + : lineMap[currentLine + 1]; + if (pos !== commentPos) { + if (firstCommentLineIndent === undefined) { + firstCommentLineIndent = calculateIndent(text, lineMap[firstCommentLineAndCharacter.line], commentPos); + } + var currentWriterIndentSpacing = writer.getIndent() * getIndentSize(); + var spacesToEmit = currentWriterIndentSpacing - firstCommentLineIndent + calculateIndent(text, pos, nextLineStart); + if (spacesToEmit > 0) { + var numberOfSingleSpacesToEmit = spacesToEmit % getIndentSize(); + var indentSizeSpaceString = getIndentString((spacesToEmit - numberOfSingleSpacesToEmit) / getIndentSize()); + writer.rawWrite(indentSizeSpaceString); + while (numberOfSingleSpacesToEmit) { + writer.rawWrite(" "); + numberOfSingleSpacesToEmit--; + } + } + else { + writer.rawWrite(""); + } + } + writeTrimmedCurrentLine(text, commentEnd, writer, newLine, pos, nextLineStart); + pos = nextLineStart; + } + } + else { + writer.writeComment(text.substring(commentPos, commentEnd)); + } + } + ts.writeCommentRange = writeCommentRange; + function writeTrimmedCurrentLine(text, commentEnd, writer, newLine, pos, nextLineStart) { + var end = Math.min(commentEnd, nextLineStart - 1); + var currentLineText = text.substring(pos, end).replace(/^\s+|\s+$/g, ""); + if (currentLineText) { + writer.writeComment(currentLineText); + if (end !== commentEnd) { + writer.writeLine(); + } + } + else { + writer.rawWrite(newLine); + } + } + function calculateIndent(text, pos, end) { + var currentLineIndent = 0; + for (; pos < end && ts.isWhiteSpaceSingleLine(text.charCodeAt(pos)); pos++) { + if (text.charCodeAt(pos) === 9) { + currentLineIndent += getIndentSize() - (currentLineIndent % getIndentSize()); + } + else { + currentLineIndent++; + } + } + return currentLineIndent; + } + function hasModifiers(node) { + return getModifierFlags(node) !== 0; + } + ts.hasModifiers = hasModifiers; + function hasModifier(node, flags) { + return !!getSelectedModifierFlags(node, flags); + } + ts.hasModifier = hasModifier; + function hasStaticModifier(node) { + return hasModifier(node, 32); + } + ts.hasStaticModifier = hasStaticModifier; + function hasReadonlyModifier(node) { + return hasModifier(node, 64); + } + ts.hasReadonlyModifier = hasReadonlyModifier; + function getSelectedModifierFlags(node, flags) { + return getModifierFlags(node) & flags; + } + ts.getSelectedModifierFlags = getSelectedModifierFlags; + function getModifierFlags(node) { + if (node.modifierFlagsCache & 536870912) { + return node.modifierFlagsCache & ~536870912; + } + var flags = getModifierFlagsNoCache(node); + node.modifierFlagsCache = flags | 536870912; + return flags; + } + ts.getModifierFlags = getModifierFlags; + function getModifierFlagsNoCache(node) { + var flags = 0; + if (node.modifiers) { + for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) { + var modifier = _a[_i]; + flags |= modifierToFlag(modifier.kind); + } + } + if (node.flags & 4 || (node.kind === 72 && node.isInJSDocNamespace)) { + flags |= 1; + } + return flags; + } + ts.getModifierFlagsNoCache = getModifierFlagsNoCache; + function modifierToFlag(token) { + switch (token) { + case 116: return 32; + case 115: return 4; + case 114: return 16; + case 113: return 8; + case 118: return 128; + case 85: return 1; + case 125: return 2; + case 77: return 2048; + case 80: return 512; + case 121: return 256; + case 133: return 64; + } + return 0; + } + ts.modifierToFlag = modifierToFlag; + function isLogicalOperator(token) { + return token === 55 + || token === 54 + || token === 52; + } + ts.isLogicalOperator = isLogicalOperator; + function isAssignmentOperator(token) { + return token >= 59 && token <= 71; + } + ts.isAssignmentOperator = isAssignmentOperator; + function tryGetClassExtendingExpressionWithTypeArguments(node) { + var cls = tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node); + return cls && !cls.isImplements ? cls.class : undefined; + } + ts.tryGetClassExtendingExpressionWithTypeArguments = tryGetClassExtendingExpressionWithTypeArguments; + function tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node) { + return ts.isExpressionWithTypeArguments(node) + && ts.isHeritageClause(node.parent) + && ts.isClassLike(node.parent.parent) + ? { class: node.parent.parent, isImplements: node.parent.token === 109 } + : undefined; + } + ts.tryGetClassImplementingOrExtendingExpressionWithTypeArguments = tryGetClassImplementingOrExtendingExpressionWithTypeArguments; + function isAssignmentExpression(node, excludeCompoundAssignment) { + return ts.isBinaryExpression(node) + && (excludeCompoundAssignment + ? node.operatorToken.kind === 59 + : isAssignmentOperator(node.operatorToken.kind)) + && ts.isLeftHandSideExpression(node.left); + } + ts.isAssignmentExpression = isAssignmentExpression; + function isDestructuringAssignment(node) { + if (isAssignmentExpression(node, true)) { + var kind = node.left.kind; + return kind === 188 + || kind === 187; + } + return false; + } + ts.isDestructuringAssignment = isDestructuringAssignment; + function isExpressionWithTypeArgumentsInClassExtendsClause(node) { + return tryGetClassExtendingExpressionWithTypeArguments(node) !== undefined; + } + ts.isExpressionWithTypeArgumentsInClassExtendsClause = isExpressionWithTypeArgumentsInClassExtendsClause; + function isEntityNameExpression(node) { + return node.kind === 72 || isPropertyAccessEntityNameExpression(node); + } + ts.isEntityNameExpression = isEntityNameExpression; + function isPropertyAccessEntityNameExpression(node) { + return ts.isPropertyAccessExpression(node) && isEntityNameExpression(node.expression); + } + ts.isPropertyAccessEntityNameExpression = isPropertyAccessEntityNameExpression; + function isPrototypeAccess(node) { + return ts.isPropertyAccessExpression(node) && node.name.escapedText === "prototype"; + } + ts.isPrototypeAccess = isPrototypeAccess; + function isRightSideOfQualifiedNameOrPropertyAccess(node) { + return (node.parent.kind === 148 && node.parent.right === node) || + (node.parent.kind === 189 && node.parent.name === node); + } + ts.isRightSideOfQualifiedNameOrPropertyAccess = isRightSideOfQualifiedNameOrPropertyAccess; + function isEmptyObjectLiteral(expression) { + return expression.kind === 188 && + expression.properties.length === 0; + } + ts.isEmptyObjectLiteral = isEmptyObjectLiteral; + function isEmptyArrayLiteral(expression) { + return expression.kind === 187 && + expression.elements.length === 0; + } + ts.isEmptyArrayLiteral = isEmptyArrayLiteral; + function getLocalSymbolForExportDefault(symbol) { + return isExportDefaultSymbol(symbol) ? symbol.declarations[0].localSymbol : undefined; + } + ts.getLocalSymbolForExportDefault = getLocalSymbolForExportDefault; + function isExportDefaultSymbol(symbol) { + return symbol && ts.length(symbol.declarations) > 0 && hasModifier(symbol.declarations[0], 512); + } + function tryExtractTSExtension(fileName) { + return ts.find(ts.supportedTSExtensionsForExtractExtension, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + } + ts.tryExtractTSExtension = tryExtractTSExtension; + function getExpandedCharCodes(input) { + var output = []; + var length = input.length; + for (var i = 0; i < length; i++) { + var charCode = input.charCodeAt(i); + if (charCode < 0x80) { + output.push(charCode); + } + else if (charCode < 0x800) { + output.push((charCode >> 6) | 192); + output.push((charCode & 63) | 128); + } + else if (charCode < 0x10000) { + output.push((charCode >> 12) | 224); + output.push(((charCode >> 6) & 63) | 128); + output.push((charCode & 63) | 128); + } + else if (charCode < 0x20000) { + output.push((charCode >> 18) | 240); + output.push(((charCode >> 12) & 63) | 128); + output.push(((charCode >> 6) & 63) | 128); + output.push((charCode & 63) | 128); + } + else { + ts.Debug.assert(false, "Unexpected code point"); + } + } + return output; + } + var base64Digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; + function convertToBase64(input) { + var result = ""; + var charCodes = getExpandedCharCodes(input); + var i = 0; + var length = charCodes.length; + var byte1, byte2, byte3, byte4; + while (i < length) { + byte1 = charCodes[i] >> 2; + byte2 = (charCodes[i] & 3) << 4 | charCodes[i + 1] >> 4; + byte3 = (charCodes[i + 1] & 15) << 2 | charCodes[i + 2] >> 6; + byte4 = charCodes[i + 2] & 63; + if (i + 1 >= length) { + byte3 = byte4 = 64; + } + else if (i + 2 >= length) { + byte4 = 64; + } + result += base64Digits.charAt(byte1) + base64Digits.charAt(byte2) + base64Digits.charAt(byte3) + base64Digits.charAt(byte4); + i += 3; + } + return result; + } + ts.convertToBase64 = convertToBase64; + function getStringFromExpandedCharCodes(codes) { + var output = ""; + var i = 0; + var length = codes.length; + while (i < length) { + var charCode = codes[i]; + if (charCode < 0x80) { + output += String.fromCharCode(charCode); + i++; + } + else if ((charCode & 192) === 192) { + var value = charCode & 63; + i++; + var nextCode = codes[i]; + while ((nextCode & 192) === 128) { + value = (value << 6) | (nextCode & 63); + i++; + nextCode = codes[i]; + } + output += String.fromCharCode(value); + } + else { + output += String.fromCharCode(charCode); + i++; + } + } + return output; + } + function base64encode(host, input) { + if (host && host.base64encode) { + return host.base64encode(input); + } + return convertToBase64(input); + } + ts.base64encode = base64encode; + function base64decode(host, input) { + if (host && host.base64decode) { + return host.base64decode(input); + } + var length = input.length; + var expandedCharCodes = []; + var i = 0; + while (i < length) { + if (input.charCodeAt(i) === base64Digits.charCodeAt(64)) { + break; + } + var ch1 = base64Digits.indexOf(input[i]); + var ch2 = base64Digits.indexOf(input[i + 1]); + var ch3 = base64Digits.indexOf(input[i + 2]); + var ch4 = base64Digits.indexOf(input[i + 3]); + var code1 = ((ch1 & 63) << 2) | ((ch2 >> 4) & 3); + var code2 = ((ch2 & 15) << 4) | ((ch3 >> 2) & 15); + var code3 = ((ch3 & 3) << 6) | (ch4 & 63); + if (code2 === 0 && ch3 !== 0) { + expandedCharCodes.push(code1); + } + else if (code3 === 0 && ch4 !== 0) { + expandedCharCodes.push(code1, code2); + } + else { + expandedCharCodes.push(code1, code2, code3); + } + i += 4; + } + return getStringFromExpandedCharCodes(expandedCharCodes); + } + ts.base64decode = base64decode; + function readJson(path, host) { + try { + var jsonText = host.readFile(path); + if (!jsonText) + return {}; + var result = ts.parseConfigFileTextToJson(path, jsonText); + if (result.error) { + return {}; + } + return result.config; + } + catch (e) { + return {}; + } + } + ts.readJson = readJson; + function directoryProbablyExists(directoryName, host) { + return !host.directoryExists || host.directoryExists(directoryName); + } + ts.directoryProbablyExists = directoryProbablyExists; + var carriageReturnLineFeed = "\r\n"; + var lineFeed = "\n"; + function getNewLineCharacter(options, getNewLine) { + switch (options.newLine) { + case 0: + return carriageReturnLineFeed; + case 1: + return lineFeed; + } + return getNewLine ? getNewLine() : ts.sys ? ts.sys.newLine : carriageReturnLineFeed; + } + ts.getNewLineCharacter = getNewLineCharacter; + function formatEnum(value, enumObject, isFlags) { + if (value === void 0) { value = 0; } + var members = getEnumMembers(enumObject); + if (value === 0) { + return members.length > 0 && members[0][0] === 0 ? members[0][1] : "0"; + } + if (isFlags) { + var result = ""; + var remainingFlags = value; + for (var i = members.length - 1; i >= 0 && remainingFlags !== 0; i--) { + var _a = members[i], enumValue = _a[0], enumName = _a[1]; + if (enumValue !== 0 && (remainingFlags & enumValue) === enumValue) { + remainingFlags &= ~enumValue; + result = "" + enumName + (result ? ", " : "") + result; + } + } + if (remainingFlags === 0) { + return result; + } + } + else { + for (var _i = 0, members_1 = members; _i < members_1.length; _i++) { + var _b = members_1[_i], enumValue = _b[0], enumName = _b[1]; + if (enumValue === value) { + return enumName; + } + } + } + return value.toString(); + } + function getEnumMembers(enumObject) { + var result = []; + for (var name in enumObject) { + var value = enumObject[name]; + if (typeof value === "number") { + result.push([value, name]); + } + } + return ts.stableSort(result, function (x, y) { return ts.compareValues(x[0], y[0]); }); + } + function formatSyntaxKind(kind) { + return formatEnum(kind, ts.SyntaxKind, false); + } + ts.formatSyntaxKind = formatSyntaxKind; + function formatModifierFlags(flags) { + return formatEnum(flags, ts.ModifierFlags, true); + } + ts.formatModifierFlags = formatModifierFlags; + function formatTransformFlags(flags) { + return formatEnum(flags, ts.TransformFlags, true); + } + ts.formatTransformFlags = formatTransformFlags; + function formatEmitFlags(flags) { + return formatEnum(flags, ts.EmitFlags, true); + } + ts.formatEmitFlags = formatEmitFlags; + function formatSymbolFlags(flags) { + return formatEnum(flags, ts.SymbolFlags, true); + } + ts.formatSymbolFlags = formatSymbolFlags; + function formatTypeFlags(flags) { + return formatEnum(flags, ts.TypeFlags, true); + } + ts.formatTypeFlags = formatTypeFlags; + function formatObjectFlags(flags) { + return formatEnum(flags, ts.ObjectFlags, true); + } + ts.formatObjectFlags = formatObjectFlags; + function createRange(pos, end) { + if (end === void 0) { end = pos; } + ts.Debug.assert(end >= pos || end === -1); + return { pos: pos, end: end }; + } + ts.createRange = createRange; + function moveRangeEnd(range, end) { + return createRange(range.pos, end); + } + ts.moveRangeEnd = moveRangeEnd; + function moveRangePos(range, pos) { + return createRange(pos, range.end); + } + ts.moveRangePos = moveRangePos; + function moveRangePastDecorators(node) { + return node.decorators && node.decorators.length > 0 + ? moveRangePos(node, node.decorators.end) + : node; + } + ts.moveRangePastDecorators = moveRangePastDecorators; + function moveRangePastModifiers(node) { + return node.modifiers && node.modifiers.length > 0 + ? moveRangePos(node, node.modifiers.end) + : moveRangePastDecorators(node); + } + ts.moveRangePastModifiers = moveRangePastModifiers; + function isCollapsedRange(range) { + return range.pos === range.end; + } + ts.isCollapsedRange = isCollapsedRange; + function createTokenRange(pos, token) { + return createRange(pos, pos + ts.tokenToString(token).length); + } + ts.createTokenRange = createTokenRange; + function rangeIsOnSingleLine(range, sourceFile) { + return rangeStartIsOnSameLineAsRangeEnd(range, range, sourceFile); + } + ts.rangeIsOnSingleLine = rangeIsOnSingleLine; + function rangeStartPositionsAreOnSameLine(range1, range2, sourceFile) { + return positionsAreOnSameLine(getStartPositionOfRange(range1, sourceFile), getStartPositionOfRange(range2, sourceFile), sourceFile); + } + ts.rangeStartPositionsAreOnSameLine = rangeStartPositionsAreOnSameLine; + function rangeEndPositionsAreOnSameLine(range1, range2, sourceFile) { + return positionsAreOnSameLine(range1.end, range2.end, sourceFile); + } + ts.rangeEndPositionsAreOnSameLine = rangeEndPositionsAreOnSameLine; + function rangeStartIsOnSameLineAsRangeEnd(range1, range2, sourceFile) { + return positionsAreOnSameLine(getStartPositionOfRange(range1, sourceFile), range2.end, sourceFile); + } + ts.rangeStartIsOnSameLineAsRangeEnd = rangeStartIsOnSameLineAsRangeEnd; + function rangeEndIsOnSameLineAsRangeStart(range1, range2, sourceFile) { + return positionsAreOnSameLine(range1.end, getStartPositionOfRange(range2, sourceFile), sourceFile); + } + ts.rangeEndIsOnSameLineAsRangeStart = rangeEndIsOnSameLineAsRangeStart; + function positionsAreOnSameLine(pos1, pos2, sourceFile) { + return pos1 === pos2 || + getLineOfLocalPosition(sourceFile, pos1) === getLineOfLocalPosition(sourceFile, pos2); + } + ts.positionsAreOnSameLine = positionsAreOnSameLine; + function getStartPositionOfRange(range, sourceFile) { + return ts.positionIsSynthesized(range.pos) ? -1 : ts.skipTrivia(sourceFile.text, range.pos); + } + ts.getStartPositionOfRange = getStartPositionOfRange; + function isDeclarationNameOfEnumOrNamespace(node) { + var parseNode = ts.getParseTreeNode(node); + if (parseNode) { + switch (parseNode.parent.kind) { + case 243: + case 244: + return parseNode === parseNode.parent.name; + } + } + return false; + } + ts.isDeclarationNameOfEnumOrNamespace = isDeclarationNameOfEnumOrNamespace; + function getInitializedVariables(node) { + return ts.filter(node.declarations, isInitializedVariable); + } + ts.getInitializedVariables = getInitializedVariables; + function isInitializedVariable(node) { + return node.initializer !== undefined; + } + function isWatchSet(options) { + return options.watch && options.hasOwnProperty("watch"); + } + ts.isWatchSet = isWatchSet; + function closeFileWatcher(watcher) { + watcher.close(); + } + ts.closeFileWatcher = closeFileWatcher; + function getCheckFlags(symbol) { + return symbol.flags & 33554432 ? symbol.checkFlags : 0; + } + ts.getCheckFlags = getCheckFlags; + function getDeclarationModifierFlagsFromSymbol(s) { + if (s.valueDeclaration) { + var flags = ts.getCombinedModifierFlags(s.valueDeclaration); + return s.parent && s.parent.flags & 32 ? flags : flags & ~28; + } + if (getCheckFlags(s) & 6) { + var checkFlags = s.checkFlags; + var accessModifier = checkFlags & 256 ? 8 : + checkFlags & 64 ? 4 : + 16; + var staticModifier = checkFlags & 512 ? 32 : 0; + return accessModifier | staticModifier; + } + if (s.flags & 4194304) { + return 4 | 32; + } + return 0; + } + ts.getDeclarationModifierFlagsFromSymbol = getDeclarationModifierFlagsFromSymbol; + function skipAlias(symbol, checker) { + return symbol.flags & 2097152 ? checker.getAliasedSymbol(symbol) : symbol; + } + ts.skipAlias = skipAlias; + function getCombinedLocalAndExportSymbolFlags(symbol) { + return symbol.exportSymbol ? symbol.exportSymbol.flags | symbol.flags : symbol.flags; + } + ts.getCombinedLocalAndExportSymbolFlags = getCombinedLocalAndExportSymbolFlags; + function isWriteOnlyAccess(node) { + return accessKind(node) === 1; + } + ts.isWriteOnlyAccess = isWriteOnlyAccess; + function isWriteAccess(node) { + return accessKind(node) !== 0; + } + ts.isWriteAccess = isWriteAccess; + function accessKind(node) { + var parent = node.parent; + if (!parent) + return 0; + switch (parent.kind) { + case 195: + return accessKind(parent); + case 203: + case 202: + var operator = parent.operator; + return operator === 44 || operator === 45 ? writeOrReadWrite() : 0; + case 204: + var _a = parent, left = _a.left, operatorToken = _a.operatorToken; + return left === node && isAssignmentOperator(operatorToken.kind) ? + operatorToken.kind === 59 ? 1 : writeOrReadWrite() + : 0; + case 189: + return parent.name !== node ? 0 : accessKind(parent); + case 275: { + var parentAccess = accessKind(parent.parent); + return node === parent.name ? reverseAccessKind(parentAccess) : parentAccess; + } + case 276: + return node === parent.objectAssignmentInitializer ? 0 : accessKind(parent.parent); + case 187: + return accessKind(parent); + default: + return 0; + } + function writeOrReadWrite() { + return parent.parent && skipParenthesesUp(parent.parent).kind === 221 ? 1 : 2; + } + } + function reverseAccessKind(a) { + switch (a) { + case 0: + return 1; + case 1: + return 0; + case 2: + return 2; + default: + return ts.Debug.assertNever(a); + } + } + function compareDataObjects(dst, src) { + if (!dst || !src || Object.keys(dst).length !== Object.keys(src).length) { + return false; + } + for (var e in dst) { + if (typeof dst[e] === "object") { + if (!compareDataObjects(dst[e], src[e])) { + return false; + } + } + else if (typeof dst[e] !== "function") { + if (dst[e] !== src[e]) { + return false; + } + } + } + return true; + } + ts.compareDataObjects = compareDataObjects; + function clearMap(map, onDeleteValue) { + map.forEach(onDeleteValue); + map.clear(); + } + ts.clearMap = clearMap; + function mutateMap(map, newMap, options) { + var createNewValue = options.createNewValue, onDeleteValue = options.onDeleteValue, onExistingValue = options.onExistingValue; + map.forEach(function (existingValue, key) { + var valueInNewMap = newMap.get(key); + if (valueInNewMap === undefined) { + map.delete(key); + onDeleteValue(existingValue, key); + } + else if (onExistingValue) { + onExistingValue(existingValue, valueInNewMap, key); + } + }); + newMap.forEach(function (valueInNewMap, key) { + if (!map.has(key)) { + map.set(key, createNewValue(key, valueInNewMap)); + } + }); + } + ts.mutateMap = mutateMap; + function forEachAncestorDirectory(directory, callback) { + while (true) { + var result = callback(directory); + if (result !== undefined) { + return result; + } + var parentPath = ts.getDirectoryPath(directory); + if (parentPath === directory) { + return undefined; + } + directory = parentPath; + } + } + ts.forEachAncestorDirectory = forEachAncestorDirectory; + function isAbstractConstructorType(type) { + return !!(getObjectFlags(type) & 16) && !!type.symbol && isAbstractConstructorSymbol(type.symbol); + } + ts.isAbstractConstructorType = isAbstractConstructorType; + function isAbstractConstructorSymbol(symbol) { + if (symbol.flags & 32) { + var declaration = getClassLikeDeclarationOfSymbol(symbol); + return !!declaration && hasModifier(declaration, 128); + } + return false; + } + ts.isAbstractConstructorSymbol = isAbstractConstructorSymbol; + function getClassLikeDeclarationOfSymbol(symbol) { + return ts.find(symbol.declarations, ts.isClassLike); + } + ts.getClassLikeDeclarationOfSymbol = getClassLikeDeclarationOfSymbol; + function getObjectFlags(type) { + return type.flags & 524288 ? type.objectFlags : 0; + } + ts.getObjectFlags = getObjectFlags; + function typeHasCallOrConstructSignatures(type, checker) { + return checker.getSignaturesOfType(type, 0).length !== 0 || checker.getSignaturesOfType(type, 1).length !== 0; + } + ts.typeHasCallOrConstructSignatures = typeHasCallOrConstructSignatures; + function forSomeAncestorDirectory(directory, callback) { + return !!forEachAncestorDirectory(directory, function (d) { return callback(d) ? true : undefined; }); + } + ts.forSomeAncestorDirectory = forSomeAncestorDirectory; + function isUMDExportSymbol(symbol) { + return !!symbol && !!symbol.declarations && !!symbol.declarations[0] && ts.isNamespaceExportDeclaration(symbol.declarations[0]); + } + ts.isUMDExportSymbol = isUMDExportSymbol; + function showModuleSpecifier(_a) { + var moduleSpecifier = _a.moduleSpecifier; + return ts.isStringLiteral(moduleSpecifier) ? moduleSpecifier.text : getTextOfNode(moduleSpecifier); + } + ts.showModuleSpecifier = showModuleSpecifier; + function getLastChild(node) { + var lastChild; + ts.forEachChild(node, function (child) { + if (nodeIsPresent(child)) + lastChild = child; + }, function (children) { + for (var i = children.length - 1; i >= 0; i--) { + if (nodeIsPresent(children[i])) { + lastChild = children[i]; + break; + } + } + }); + return lastChild; + } + ts.getLastChild = getLastChild; + function addToSeen(seen, key, value) { + if (value === void 0) { value = true; } + key = String(key); + if (seen.has(key)) { + return false; + } + seen.set(key, value); + return true; + } + ts.addToSeen = addToSeen; + function isObjectTypeDeclaration(node) { + return ts.isClassLike(node) || ts.isInterfaceDeclaration(node) || ts.isTypeLiteralNode(node); + } + ts.isObjectTypeDeclaration = isObjectTypeDeclaration; + function isTypeNodeKind(kind) { + return (kind >= 163 && kind <= 183) + || kind === 120 + || kind === 143 + || kind === 135 + || kind === 146 + || kind === 136 + || kind === 123 + || kind === 138 + || kind === 139 + || kind === 100 + || kind === 106 + || kind === 141 + || kind === 96 + || kind === 132 + || kind === 211 + || kind === 284 + || kind === 285 + || kind === 286 + || kind === 287 + || kind === 288 + || kind === 289 + || kind === 290; + } + ts.isTypeNodeKind = isTypeNodeKind; +})(ts || (ts = {})); +(function (ts) { + function getDefaultLibFileName(options) { + switch (options.target) { + case 6: + return "lib.esnext.full.d.ts"; + case 5: + return "lib.es2018.full.d.ts"; + case 4: + return "lib.es2017.full.d.ts"; + case 3: + return "lib.es2016.full.d.ts"; + case 2: + return "lib.es6.d.ts"; + default: + return "lib.d.ts"; + } + } + ts.getDefaultLibFileName = getDefaultLibFileName; + function textSpanEnd(span) { + return span.start + span.length; + } + ts.textSpanEnd = textSpanEnd; + function textSpanIsEmpty(span) { + return span.length === 0; + } + ts.textSpanIsEmpty = textSpanIsEmpty; + function textSpanContainsPosition(span, position) { + return position >= span.start && position < textSpanEnd(span); + } + ts.textSpanContainsPosition = textSpanContainsPosition; + function textRangeContainsPositionInclusive(span, position) { + return position >= span.pos && position <= span.end; + } + ts.textRangeContainsPositionInclusive = textRangeContainsPositionInclusive; + function textSpanContainsTextSpan(span, other) { + return other.start >= span.start && textSpanEnd(other) <= textSpanEnd(span); + } + ts.textSpanContainsTextSpan = textSpanContainsTextSpan; + function textSpanOverlapsWith(span, other) { + return textSpanOverlap(span, other) !== undefined; + } + ts.textSpanOverlapsWith = textSpanOverlapsWith; + function textSpanOverlap(span1, span2) { + var overlap = textSpanIntersection(span1, span2); + return overlap && overlap.length === 0 ? undefined : overlap; + } + ts.textSpanOverlap = textSpanOverlap; + function textSpanIntersectsWithTextSpan(span, other) { + return decodedTextSpanIntersectsWith(span.start, span.length, other.start, other.length); + } + ts.textSpanIntersectsWithTextSpan = textSpanIntersectsWithTextSpan; + function textSpanIntersectsWith(span, start, length) { + return decodedTextSpanIntersectsWith(span.start, span.length, start, length); + } + ts.textSpanIntersectsWith = textSpanIntersectsWith; + function decodedTextSpanIntersectsWith(start1, length1, start2, length2) { + var end1 = start1 + length1; + var end2 = start2 + length2; + return start2 <= end1 && end2 >= start1; + } + ts.decodedTextSpanIntersectsWith = decodedTextSpanIntersectsWith; + function textSpanIntersectsWithPosition(span, position) { + return position <= textSpanEnd(span) && position >= span.start; + } + ts.textSpanIntersectsWithPosition = textSpanIntersectsWithPosition; + function textSpanIntersection(span1, span2) { + var start = Math.max(span1.start, span2.start); + var end = Math.min(textSpanEnd(span1), textSpanEnd(span2)); + return start <= end ? createTextSpanFromBounds(start, end) : undefined; + } + ts.textSpanIntersection = textSpanIntersection; + function createTextSpan(start, length) { + if (start < 0) { + throw new Error("start < 0"); + } + if (length < 0) { + throw new Error("length < 0"); + } + return { start: start, length: length }; + } + ts.createTextSpan = createTextSpan; + function createTextSpanFromBounds(start, end) { + return createTextSpan(start, end - start); + } + ts.createTextSpanFromBounds = createTextSpanFromBounds; + function textChangeRangeNewSpan(range) { + return createTextSpan(range.span.start, range.newLength); + } + ts.textChangeRangeNewSpan = textChangeRangeNewSpan; + function textChangeRangeIsUnchanged(range) { + return textSpanIsEmpty(range.span) && range.newLength === 0; + } + ts.textChangeRangeIsUnchanged = textChangeRangeIsUnchanged; + function createTextChangeRange(span, newLength) { + if (newLength < 0) { + throw new Error("newLength < 0"); + } + return { span: span, newLength: newLength }; + } + ts.createTextChangeRange = createTextChangeRange; + ts.unchangedTextChangeRange = createTextChangeRange(createTextSpan(0, 0), 0); + function collapseTextChangeRangesAcrossMultipleVersions(changes) { + if (changes.length === 0) { + return ts.unchangedTextChangeRange; + } + if (changes.length === 1) { + return changes[0]; + } + var change0 = changes[0]; + var oldStartN = change0.span.start; + var oldEndN = textSpanEnd(change0.span); + var newEndN = oldStartN + change0.newLength; + for (var i = 1; i < changes.length; i++) { + var nextChange = changes[i]; + var oldStart1 = oldStartN; + var oldEnd1 = oldEndN; + var newEnd1 = newEndN; + var oldStart2 = nextChange.span.start; + var oldEnd2 = textSpanEnd(nextChange.span); + var newEnd2 = oldStart2 + nextChange.newLength; + oldStartN = Math.min(oldStart1, oldStart2); + oldEndN = Math.max(oldEnd1, oldEnd1 + (oldEnd2 - newEnd1)); + newEndN = Math.max(newEnd2, newEnd2 + (newEnd1 - oldEnd2)); + } + return createTextChangeRange(createTextSpanFromBounds(oldStartN, oldEndN), newEndN - oldStartN); + } + ts.collapseTextChangeRangesAcrossMultipleVersions = collapseTextChangeRangesAcrossMultipleVersions; + function getTypeParameterOwner(d) { + if (d && d.kind === 150) { + for (var current = d; current; current = current.parent) { + if (ts.isFunctionLike(current) || ts.isClassLike(current) || current.kind === 241) { + return current; + } + } + } + } + ts.getTypeParameterOwner = getTypeParameterOwner; + function isParameterPropertyDeclaration(node) { + return ts.hasModifier(node, 92) && node.parent.kind === 157; + } + ts.isParameterPropertyDeclaration = isParameterPropertyDeclaration; + function isEmptyBindingPattern(node) { + if (ts.isBindingPattern(node)) { + return ts.every(node.elements, isEmptyBindingElement); + } + return false; + } + ts.isEmptyBindingPattern = isEmptyBindingPattern; + function isEmptyBindingElement(node) { + if (ts.isOmittedExpression(node)) { + return true; + } + return isEmptyBindingPattern(node.name); + } + ts.isEmptyBindingElement = isEmptyBindingElement; + function walkUpBindingElementsAndPatterns(binding) { + var node = binding.parent; + while (ts.isBindingElement(node.parent)) { + node = node.parent.parent; + } + return node.parent; + } + ts.walkUpBindingElementsAndPatterns = walkUpBindingElementsAndPatterns; + function getCombinedFlags(node, getFlags) { + if (ts.isBindingElement(node)) { + node = walkUpBindingElementsAndPatterns(node); + } + var flags = getFlags(node); + if (node.kind === 237) { + node = node.parent; + } + if (node && node.kind === 238) { + flags |= getFlags(node); + node = node.parent; + } + if (node && node.kind === 219) { + flags |= getFlags(node); + } + return flags; + } + function getCombinedModifierFlags(node) { + return getCombinedFlags(node, ts.getModifierFlags); + } + ts.getCombinedModifierFlags = getCombinedModifierFlags; + function getCombinedNodeFlags(node) { + return getCombinedFlags(node, function (n) { return n.flags; }); + } + ts.getCombinedNodeFlags = getCombinedNodeFlags; + function validateLocaleAndSetLanguage(locale, sys, errors) { + var matchResult = /^([a-z]+)([_\-]([a-z]+))?$/.exec(locale.toLowerCase()); + if (!matchResult) { + if (errors) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1, "en", "ja-jp")); + } + return; + } + var language = matchResult[1]; + var territory = matchResult[3]; + if (!trySetLanguageAndTerritory(language, territory, errors)) { + trySetLanguageAndTerritory(language, undefined, errors); + } + ts.setUILocale(locale); + function trySetLanguageAndTerritory(language, territory, errors) { + var compilerFilePath = ts.normalizePath(sys.getExecutingFilePath()); + var containingDirectoryPath = ts.getDirectoryPath(compilerFilePath); + var filePath = ts.combinePaths(containingDirectoryPath, language); + if (territory) { + filePath = filePath + "-" + territory; + } + filePath = sys.resolvePath(ts.combinePaths(filePath, "diagnosticMessages.generated.json")); + if (!sys.fileExists(filePath)) { + return false; + } + var fileContents = ""; + try { + fileContents = sys.readFile(filePath); + } + catch (e) { + if (errors) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unable_to_open_file_0, filePath)); + } + return false; + } + try { + ts.localizedDiagnosticMessages = JSON.parse(fileContents); + } + catch (_a) { + if (errors) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Corrupted_locale_file_0, filePath)); + } + return false; + } + return true; + } + } + ts.validateLocaleAndSetLanguage = validateLocaleAndSetLanguage; + function getOriginalNode(node, nodeTest) { + if (node) { + while (node.original !== undefined) { + node = node.original; + } + } + return !nodeTest || nodeTest(node) ? node : undefined; + } + ts.getOriginalNode = getOriginalNode; + function isParseTreeNode(node) { + return (node.flags & 8) === 0; + } + ts.isParseTreeNode = isParseTreeNode; + function getParseTreeNode(node, nodeTest) { + if (node === undefined || isParseTreeNode(node)) { + return node; + } + node = getOriginalNode(node); + if (isParseTreeNode(node) && (!nodeTest || nodeTest(node))) { + return node; + } + return undefined; + } + ts.getParseTreeNode = getParseTreeNode; + function escapeLeadingUnderscores(identifier) { + return (identifier.length >= 2 && identifier.charCodeAt(0) === 95 && identifier.charCodeAt(1) === 95 ? "_" + identifier : identifier); + } + ts.escapeLeadingUnderscores = escapeLeadingUnderscores; + function unescapeLeadingUnderscores(identifier) { + var id = identifier; + return id.length >= 3 && id.charCodeAt(0) === 95 && id.charCodeAt(1) === 95 && id.charCodeAt(2) === 95 ? id.substr(1) : id; + } + ts.unescapeLeadingUnderscores = unescapeLeadingUnderscores; + function idText(identifier) { + return unescapeLeadingUnderscores(identifier.escapedText); + } + ts.idText = idText; + function symbolName(symbol) { + return unescapeLeadingUnderscores(symbol.escapedName); + } + ts.symbolName = symbolName; + function nameForNamelessJSDocTypedef(declaration) { + var hostNode = declaration.parent.parent; + if (!hostNode) { + return undefined; + } + if (ts.isDeclaration(hostNode)) { + return getDeclarationIdentifier(hostNode); + } + switch (hostNode.kind) { + case 219: + if (hostNode.declarationList && hostNode.declarationList.declarations[0]) { + return getDeclarationIdentifier(hostNode.declarationList.declarations[0]); + } + break; + case 221: + var expr = hostNode.expression; + switch (expr.kind) { + case 189: + return expr.name; + case 190: + var arg = expr.argumentExpression; + if (ts.isIdentifier(arg)) { + return arg; + } + } + break; + case 195: { + return getDeclarationIdentifier(hostNode.expression); + } + case 233: { + if (ts.isDeclaration(hostNode.statement) || ts.isExpression(hostNode.statement)) { + return getDeclarationIdentifier(hostNode.statement); + } + break; + } + } + } + function getDeclarationIdentifier(node) { + var name = getNameOfDeclaration(node); + return name && ts.isIdentifier(name) ? name : undefined; + } + function getNameOfJSDocTypedef(declaration) { + return declaration.name || nameForNamelessJSDocTypedef(declaration); + } + ts.getNameOfJSDocTypedef = getNameOfJSDocTypedef; + function isNamedDeclaration(node) { + return !!node.name; + } + ts.isNamedDeclaration = isNamedDeclaration; + function getNonAssignedNameOfDeclaration(declaration) { + switch (declaration.kind) { + case 72: + return declaration; + case 305: + case 299: { + var name = declaration.name; + if (name.kind === 148) { + return name.right; + } + break; + } + case 191: + case 204: { + var expr = declaration; + switch (ts.getAssignmentDeclarationKind(expr)) { + case 1: + case 4: + case 5: + case 3: + return expr.left.name; + case 7: + case 8: + case 9: + return expr.arguments[1]; + default: + return undefined; + } + } + case 304: + return getNameOfJSDocTypedef(declaration); + case 254: { + var expression = declaration.expression; + return ts.isIdentifier(expression) ? expression : undefined; + } + } + return declaration.name; + } + ts.getNonAssignedNameOfDeclaration = getNonAssignedNameOfDeclaration; + function getNameOfDeclaration(declaration) { + if (declaration === undefined) + return undefined; + return getNonAssignedNameOfDeclaration(declaration) || + (ts.isFunctionExpression(declaration) || ts.isClassExpression(declaration) ? getAssignedName(declaration) : undefined); + } + ts.getNameOfDeclaration = getNameOfDeclaration; + function getAssignedName(node) { + if (!node.parent) { + return undefined; + } + else if (ts.isPropertyAssignment(node.parent) || ts.isBindingElement(node.parent)) { + return node.parent.name; + } + else if (ts.isBinaryExpression(node.parent) && node === node.parent.right) { + if (ts.isIdentifier(node.parent.left)) { + return node.parent.left; + } + else if (ts.isPropertyAccessExpression(node.parent.left)) { + return node.parent.left.name; + } + } + } + function getJSDocParameterTags(param) { + if (param.name) { + if (ts.isIdentifier(param.name)) { + var name_1 = param.name.escapedText; + return getJSDocTags(param.parent).filter(function (tag) { return ts.isJSDocParameterTag(tag) && ts.isIdentifier(tag.name) && tag.name.escapedText === name_1; }); + } + else { + var i = param.parent.parameters.indexOf(param); + ts.Debug.assert(i > -1, "Parameters should always be in their parents' parameter list"); + var paramTags = getJSDocTags(param.parent).filter(ts.isJSDocParameterTag); + if (i < paramTags.length) { + return [paramTags[i]]; + } + } + } + return ts.emptyArray; + } + ts.getJSDocParameterTags = getJSDocParameterTags; + function getJSDocTypeParameterTags(param) { + var name = param.name.escapedText; + return getJSDocTags(param.parent).filter(function (tag) { + return ts.isJSDocTemplateTag(tag) && tag.typeParameters.some(function (tp) { return tp.name.escapedText === name; }); + }); + } + ts.getJSDocTypeParameterTags = getJSDocTypeParameterTags; + function hasJSDocParameterTags(node) { + return !!getFirstJSDocTag(node, ts.isJSDocParameterTag); + } + ts.hasJSDocParameterTags = hasJSDocParameterTags; + function getJSDocAugmentsTag(node) { + return getFirstJSDocTag(node, ts.isJSDocAugmentsTag); + } + ts.getJSDocAugmentsTag = getJSDocAugmentsTag; + function getJSDocClassTag(node) { + return getFirstJSDocTag(node, ts.isJSDocClassTag); + } + ts.getJSDocClassTag = getJSDocClassTag; + function getJSDocEnumTag(node) { + return getFirstJSDocTag(node, ts.isJSDocEnumTag); + } + ts.getJSDocEnumTag = getJSDocEnumTag; + function getJSDocThisTag(node) { + return getFirstJSDocTag(node, ts.isJSDocThisTag); + } + ts.getJSDocThisTag = getJSDocThisTag; + function getJSDocReturnTag(node) { + return getFirstJSDocTag(node, ts.isJSDocReturnTag); + } + ts.getJSDocReturnTag = getJSDocReturnTag; + function getJSDocTemplateTag(node) { + return getFirstJSDocTag(node, ts.isJSDocTemplateTag); + } + ts.getJSDocTemplateTag = getJSDocTemplateTag; + function getJSDocTypeTag(node) { + var tag = getFirstJSDocTag(node, ts.isJSDocTypeTag); + if (tag && tag.typeExpression && tag.typeExpression.type) { + return tag; + } + return undefined; + } + ts.getJSDocTypeTag = getJSDocTypeTag; + function getJSDocType(node) { + var tag = getFirstJSDocTag(node, ts.isJSDocTypeTag); + if (!tag && ts.isParameter(node)) { + tag = ts.find(getJSDocParameterTags(node), function (tag) { return !!tag.typeExpression; }); + } + return tag && tag.typeExpression && tag.typeExpression.type; + } + ts.getJSDocType = getJSDocType; + function getJSDocReturnType(node) { + var returnTag = getJSDocReturnTag(node); + if (returnTag && returnTag.typeExpression) { + return returnTag.typeExpression.type; + } + var typeTag = getJSDocTypeTag(node); + if (typeTag && typeTag.typeExpression) { + var type = typeTag.typeExpression.type; + if (ts.isTypeLiteralNode(type)) { + var sig = ts.find(type.members, ts.isCallSignatureDeclaration); + return sig && sig.type; + } + if (ts.isFunctionTypeNode(type)) { + return type.type; + } + } + } + ts.getJSDocReturnType = getJSDocReturnType; + function getJSDocTags(node) { + var tags = node.jsDocCache; + if (tags === undefined) { + var comments = ts.getJSDocCommentsAndTags(node); + ts.Debug.assert(comments.length < 2 || comments[0] !== comments[1]); + node.jsDocCache = tags = ts.flatMap(comments, function (j) { return ts.isJSDoc(j) ? j.tags : j; }); + } + return tags; + } + ts.getJSDocTags = getJSDocTags; + function getFirstJSDocTag(node, predicate) { + return ts.find(getJSDocTags(node), predicate); + } + function getAllJSDocTagsOfKind(node, kind) { + return getJSDocTags(node).filter(function (doc) { return doc.kind === kind; }); + } + ts.getAllJSDocTagsOfKind = getAllJSDocTagsOfKind; + function getEffectiveTypeParameterDeclarations(node) { + if (ts.isJSDocSignature(node)) { + return ts.emptyArray; + } + if (ts.isJSDocTypeAlias(node)) { + ts.Debug.assert(node.parent.kind === 291); + return ts.flatMap(node.parent.tags, function (tag) { return ts.isJSDocTemplateTag(tag) ? tag.typeParameters : undefined; }); + } + if (node.typeParameters) { + return node.typeParameters; + } + if (ts.isInJSFile(node)) { + var decls = ts.getJSDocTypeParameterDeclarations(node); + if (decls.length) { + return decls; + } + var typeTag = getJSDocType(node); + if (typeTag && ts.isFunctionTypeNode(typeTag) && typeTag.typeParameters) { + return typeTag.typeParameters; + } + } + return ts.emptyArray; + } + ts.getEffectiveTypeParameterDeclarations = getEffectiveTypeParameterDeclarations; + function getEffectiveConstraintOfTypeParameter(node) { + return node.constraint ? node.constraint + : ts.isJSDocTemplateTag(node.parent) && node === node.parent.typeParameters[0] + ? node.parent.constraint + : undefined; + } + ts.getEffectiveConstraintOfTypeParameter = getEffectiveConstraintOfTypeParameter; +})(ts || (ts = {})); +(function (ts) { + function isNumericLiteral(node) { + return node.kind === 8; + } + ts.isNumericLiteral = isNumericLiteral; + function isBigIntLiteral(node) { + return node.kind === 9; + } + ts.isBigIntLiteral = isBigIntLiteral; + function isStringLiteral(node) { + return node.kind === 10; + } + ts.isStringLiteral = isStringLiteral; + function isJsxText(node) { + return node.kind === 11; + } + ts.isJsxText = isJsxText; + function isRegularExpressionLiteral(node) { + return node.kind === 13; + } + ts.isRegularExpressionLiteral = isRegularExpressionLiteral; + function isNoSubstitutionTemplateLiteral(node) { + return node.kind === 14; + } + ts.isNoSubstitutionTemplateLiteral = isNoSubstitutionTemplateLiteral; + function isTemplateHead(node) { + return node.kind === 15; + } + ts.isTemplateHead = isTemplateHead; + function isTemplateMiddle(node) { + return node.kind === 16; + } + ts.isTemplateMiddle = isTemplateMiddle; + function isTemplateTail(node) { + return node.kind === 17; + } + ts.isTemplateTail = isTemplateTail; + function isIdentifier(node) { + return node.kind === 72; + } + ts.isIdentifier = isIdentifier; + function isQualifiedName(node) { + return node.kind === 148; + } + ts.isQualifiedName = isQualifiedName; + function isComputedPropertyName(node) { + return node.kind === 149; + } + ts.isComputedPropertyName = isComputedPropertyName; + function isTypeParameterDeclaration(node) { + return node.kind === 150; + } + ts.isTypeParameterDeclaration = isTypeParameterDeclaration; + function isParameter(node) { + return node.kind === 151; + } + ts.isParameter = isParameter; + function isDecorator(node) { + return node.kind === 152; + } + ts.isDecorator = isDecorator; + function isPropertySignature(node) { + return node.kind === 153; + } + ts.isPropertySignature = isPropertySignature; + function isPropertyDeclaration(node) { + return node.kind === 154; + } + ts.isPropertyDeclaration = isPropertyDeclaration; + function isMethodSignature(node) { + return node.kind === 155; + } + ts.isMethodSignature = isMethodSignature; + function isMethodDeclaration(node) { + return node.kind === 156; + } + ts.isMethodDeclaration = isMethodDeclaration; + function isConstructorDeclaration(node) { + return node.kind === 157; + } + ts.isConstructorDeclaration = isConstructorDeclaration; + function isGetAccessorDeclaration(node) { + return node.kind === 158; + } + ts.isGetAccessorDeclaration = isGetAccessorDeclaration; + function isSetAccessorDeclaration(node) { + return node.kind === 159; + } + ts.isSetAccessorDeclaration = isSetAccessorDeclaration; + function isCallSignatureDeclaration(node) { + return node.kind === 160; + } + ts.isCallSignatureDeclaration = isCallSignatureDeclaration; + function isConstructSignatureDeclaration(node) { + return node.kind === 161; + } + ts.isConstructSignatureDeclaration = isConstructSignatureDeclaration; + function isIndexSignatureDeclaration(node) { + return node.kind === 162; + } + ts.isIndexSignatureDeclaration = isIndexSignatureDeclaration; + function isGetOrSetAccessorDeclaration(node) { + return node.kind === 159 || node.kind === 158; + } + ts.isGetOrSetAccessorDeclaration = isGetOrSetAccessorDeclaration; + function isTypePredicateNode(node) { + return node.kind === 163; + } + ts.isTypePredicateNode = isTypePredicateNode; + function isTypeReferenceNode(node) { + return node.kind === 164; + } + ts.isTypeReferenceNode = isTypeReferenceNode; + function isFunctionTypeNode(node) { + return node.kind === 165; + } + ts.isFunctionTypeNode = isFunctionTypeNode; + function isConstructorTypeNode(node) { + return node.kind === 166; + } + ts.isConstructorTypeNode = isConstructorTypeNode; + function isTypeQueryNode(node) { + return node.kind === 167; + } + ts.isTypeQueryNode = isTypeQueryNode; + function isTypeLiteralNode(node) { + return node.kind === 168; + } + ts.isTypeLiteralNode = isTypeLiteralNode; + function isArrayTypeNode(node) { + return node.kind === 169; + } + ts.isArrayTypeNode = isArrayTypeNode; + function isTupleTypeNode(node) { + return node.kind === 170; + } + ts.isTupleTypeNode = isTupleTypeNode; + function isUnionTypeNode(node) { + return node.kind === 173; + } + ts.isUnionTypeNode = isUnionTypeNode; + function isIntersectionTypeNode(node) { + return node.kind === 174; + } + ts.isIntersectionTypeNode = isIntersectionTypeNode; + function isConditionalTypeNode(node) { + return node.kind === 175; + } + ts.isConditionalTypeNode = isConditionalTypeNode; + function isInferTypeNode(node) { + return node.kind === 176; + } + ts.isInferTypeNode = isInferTypeNode; + function isParenthesizedTypeNode(node) { + return node.kind === 177; + } + ts.isParenthesizedTypeNode = isParenthesizedTypeNode; + function isThisTypeNode(node) { + return node.kind === 178; + } + ts.isThisTypeNode = isThisTypeNode; + function isTypeOperatorNode(node) { + return node.kind === 179; + } + ts.isTypeOperatorNode = isTypeOperatorNode; + function isIndexedAccessTypeNode(node) { + return node.kind === 180; + } + ts.isIndexedAccessTypeNode = isIndexedAccessTypeNode; + function isMappedTypeNode(node) { + return node.kind === 181; + } + ts.isMappedTypeNode = isMappedTypeNode; + function isLiteralTypeNode(node) { + return node.kind === 182; + } + ts.isLiteralTypeNode = isLiteralTypeNode; + function isImportTypeNode(node) { + return node.kind === 183; + } + ts.isImportTypeNode = isImportTypeNode; + function isObjectBindingPattern(node) { + return node.kind === 184; + } + ts.isObjectBindingPattern = isObjectBindingPattern; + function isArrayBindingPattern(node) { + return node.kind === 185; + } + ts.isArrayBindingPattern = isArrayBindingPattern; + function isBindingElement(node) { + return node.kind === 186; + } + ts.isBindingElement = isBindingElement; + function isArrayLiteralExpression(node) { + return node.kind === 187; + } + ts.isArrayLiteralExpression = isArrayLiteralExpression; + function isObjectLiteralExpression(node) { + return node.kind === 188; + } + ts.isObjectLiteralExpression = isObjectLiteralExpression; + function isPropertyAccessExpression(node) { + return node.kind === 189; + } + ts.isPropertyAccessExpression = isPropertyAccessExpression; + function isElementAccessExpression(node) { + return node.kind === 190; + } + ts.isElementAccessExpression = isElementAccessExpression; + function isCallExpression(node) { + return node.kind === 191; + } + ts.isCallExpression = isCallExpression; + function isNewExpression(node) { + return node.kind === 192; + } + ts.isNewExpression = isNewExpression; + function isTaggedTemplateExpression(node) { + return node.kind === 193; + } + ts.isTaggedTemplateExpression = isTaggedTemplateExpression; + function isTypeAssertion(node) { + return node.kind === 194; + } + ts.isTypeAssertion = isTypeAssertion; + function isParenthesizedExpression(node) { + return node.kind === 195; + } + ts.isParenthesizedExpression = isParenthesizedExpression; + function skipPartiallyEmittedExpressions(node) { + while (node.kind === 308) { + node = node.expression; + } + return node; + } + ts.skipPartiallyEmittedExpressions = skipPartiallyEmittedExpressions; + function isFunctionExpression(node) { + return node.kind === 196; + } + ts.isFunctionExpression = isFunctionExpression; + function isArrowFunction(node) { + return node.kind === 197; + } + ts.isArrowFunction = isArrowFunction; + function isDeleteExpression(node) { + return node.kind === 198; + } + ts.isDeleteExpression = isDeleteExpression; + function isTypeOfExpression(node) { + return node.kind === 199; + } + ts.isTypeOfExpression = isTypeOfExpression; + function isVoidExpression(node) { + return node.kind === 200; + } + ts.isVoidExpression = isVoidExpression; + function isAwaitExpression(node) { + return node.kind === 201; + } + ts.isAwaitExpression = isAwaitExpression; + function isPrefixUnaryExpression(node) { + return node.kind === 202; + } + ts.isPrefixUnaryExpression = isPrefixUnaryExpression; + function isPostfixUnaryExpression(node) { + return node.kind === 203; + } + ts.isPostfixUnaryExpression = isPostfixUnaryExpression; + function isBinaryExpression(node) { + return node.kind === 204; + } + ts.isBinaryExpression = isBinaryExpression; + function isConditionalExpression(node) { + return node.kind === 205; + } + ts.isConditionalExpression = isConditionalExpression; + function isTemplateExpression(node) { + return node.kind === 206; + } + ts.isTemplateExpression = isTemplateExpression; + function isYieldExpression(node) { + return node.kind === 207; + } + ts.isYieldExpression = isYieldExpression; + function isSpreadElement(node) { + return node.kind === 208; + } + ts.isSpreadElement = isSpreadElement; + function isClassExpression(node) { + return node.kind === 209; + } + ts.isClassExpression = isClassExpression; + function isOmittedExpression(node) { + return node.kind === 210; + } + ts.isOmittedExpression = isOmittedExpression; + function isExpressionWithTypeArguments(node) { + return node.kind === 211; + } + ts.isExpressionWithTypeArguments = isExpressionWithTypeArguments; + function isAsExpression(node) { + return node.kind === 212; + } + ts.isAsExpression = isAsExpression; + function isNonNullExpression(node) { + return node.kind === 213; + } + ts.isNonNullExpression = isNonNullExpression; + function isMetaProperty(node) { + return node.kind === 214; + } + ts.isMetaProperty = isMetaProperty; + function isTemplateSpan(node) { + return node.kind === 216; + } + ts.isTemplateSpan = isTemplateSpan; + function isSemicolonClassElement(node) { + return node.kind === 217; + } + ts.isSemicolonClassElement = isSemicolonClassElement; + function isBlock(node) { + return node.kind === 218; + } + ts.isBlock = isBlock; + function isVariableStatement(node) { + return node.kind === 219; + } + ts.isVariableStatement = isVariableStatement; + function isEmptyStatement(node) { + return node.kind === 220; + } + ts.isEmptyStatement = isEmptyStatement; + function isExpressionStatement(node) { + return node.kind === 221; + } + ts.isExpressionStatement = isExpressionStatement; + function isIfStatement(node) { + return node.kind === 222; + } + ts.isIfStatement = isIfStatement; + function isDoStatement(node) { + return node.kind === 223; + } + ts.isDoStatement = isDoStatement; + function isWhileStatement(node) { + return node.kind === 224; + } + ts.isWhileStatement = isWhileStatement; + function isForStatement(node) { + return node.kind === 225; + } + ts.isForStatement = isForStatement; + function isForInStatement(node) { + return node.kind === 226; + } + ts.isForInStatement = isForInStatement; + function isForOfStatement(node) { + return node.kind === 227; + } + ts.isForOfStatement = isForOfStatement; + function isContinueStatement(node) { + return node.kind === 228; + } + ts.isContinueStatement = isContinueStatement; + function isBreakStatement(node) { + return node.kind === 229; + } + ts.isBreakStatement = isBreakStatement; + function isBreakOrContinueStatement(node) { + return node.kind === 229 || node.kind === 228; + } + ts.isBreakOrContinueStatement = isBreakOrContinueStatement; + function isReturnStatement(node) { + return node.kind === 230; + } + ts.isReturnStatement = isReturnStatement; + function isWithStatement(node) { + return node.kind === 231; + } + ts.isWithStatement = isWithStatement; + function isSwitchStatement(node) { + return node.kind === 232; + } + ts.isSwitchStatement = isSwitchStatement; + function isLabeledStatement(node) { + return node.kind === 233; + } + ts.isLabeledStatement = isLabeledStatement; + function isThrowStatement(node) { + return node.kind === 234; + } + ts.isThrowStatement = isThrowStatement; + function isTryStatement(node) { + return node.kind === 235; + } + ts.isTryStatement = isTryStatement; + function isDebuggerStatement(node) { + return node.kind === 236; + } + ts.isDebuggerStatement = isDebuggerStatement; + function isVariableDeclaration(node) { + return node.kind === 237; + } + ts.isVariableDeclaration = isVariableDeclaration; + function isVariableDeclarationList(node) { + return node.kind === 238; + } + ts.isVariableDeclarationList = isVariableDeclarationList; + function isFunctionDeclaration(node) { + return node.kind === 239; + } + ts.isFunctionDeclaration = isFunctionDeclaration; + function isClassDeclaration(node) { + return node.kind === 240; + } + ts.isClassDeclaration = isClassDeclaration; + function isInterfaceDeclaration(node) { + return node.kind === 241; + } + ts.isInterfaceDeclaration = isInterfaceDeclaration; + function isTypeAliasDeclaration(node) { + return node.kind === 242; + } + ts.isTypeAliasDeclaration = isTypeAliasDeclaration; + function isEnumDeclaration(node) { + return node.kind === 243; + } + ts.isEnumDeclaration = isEnumDeclaration; + function isModuleDeclaration(node) { + return node.kind === 244; + } + ts.isModuleDeclaration = isModuleDeclaration; + function isModuleBlock(node) { + return node.kind === 245; + } + ts.isModuleBlock = isModuleBlock; + function isCaseBlock(node) { + return node.kind === 246; + } + ts.isCaseBlock = isCaseBlock; + function isNamespaceExportDeclaration(node) { + return node.kind === 247; + } + ts.isNamespaceExportDeclaration = isNamespaceExportDeclaration; + function isImportEqualsDeclaration(node) { + return node.kind === 248; + } + ts.isImportEqualsDeclaration = isImportEqualsDeclaration; + function isImportDeclaration(node) { + return node.kind === 249; + } + ts.isImportDeclaration = isImportDeclaration; + function isImportClause(node) { + return node.kind === 250; + } + ts.isImportClause = isImportClause; + function isNamespaceImport(node) { + return node.kind === 251; + } + ts.isNamespaceImport = isNamespaceImport; + function isNamedImports(node) { + return node.kind === 252; + } + ts.isNamedImports = isNamedImports; + function isImportSpecifier(node) { + return node.kind === 253; + } + ts.isImportSpecifier = isImportSpecifier; + function isExportAssignment(node) { + return node.kind === 254; + } + ts.isExportAssignment = isExportAssignment; + function isExportDeclaration(node) { + return node.kind === 255; + } + ts.isExportDeclaration = isExportDeclaration; + function isNamedExports(node) { + return node.kind === 256; + } + ts.isNamedExports = isNamedExports; + function isExportSpecifier(node) { + return node.kind === 257; + } + ts.isExportSpecifier = isExportSpecifier; + function isMissingDeclaration(node) { + return node.kind === 258; + } + ts.isMissingDeclaration = isMissingDeclaration; + function isExternalModuleReference(node) { + return node.kind === 259; + } + ts.isExternalModuleReference = isExternalModuleReference; + function isJsxElement(node) { + return node.kind === 260; + } + ts.isJsxElement = isJsxElement; + function isJsxSelfClosingElement(node) { + return node.kind === 261; + } + ts.isJsxSelfClosingElement = isJsxSelfClosingElement; + function isJsxOpeningElement(node) { + return node.kind === 262; + } + ts.isJsxOpeningElement = isJsxOpeningElement; + function isJsxClosingElement(node) { + return node.kind === 263; + } + ts.isJsxClosingElement = isJsxClosingElement; + function isJsxFragment(node) { + return node.kind === 264; + } + ts.isJsxFragment = isJsxFragment; + function isJsxOpeningFragment(node) { + return node.kind === 265; + } + ts.isJsxOpeningFragment = isJsxOpeningFragment; + function isJsxClosingFragment(node) { + return node.kind === 266; + } + ts.isJsxClosingFragment = isJsxClosingFragment; + function isJsxAttribute(node) { + return node.kind === 267; + } + ts.isJsxAttribute = isJsxAttribute; + function isJsxAttributes(node) { + return node.kind === 268; + } + ts.isJsxAttributes = isJsxAttributes; + function isJsxSpreadAttribute(node) { + return node.kind === 269; + } + ts.isJsxSpreadAttribute = isJsxSpreadAttribute; + function isJsxExpression(node) { + return node.kind === 270; + } + ts.isJsxExpression = isJsxExpression; + function isCaseClause(node) { + return node.kind === 271; + } + ts.isCaseClause = isCaseClause; + function isDefaultClause(node) { + return node.kind === 272; + } + ts.isDefaultClause = isDefaultClause; + function isHeritageClause(node) { + return node.kind === 273; + } + ts.isHeritageClause = isHeritageClause; + function isCatchClause(node) { + return node.kind === 274; + } + ts.isCatchClause = isCatchClause; + function isPropertyAssignment(node) { + return node.kind === 275; + } + ts.isPropertyAssignment = isPropertyAssignment; + function isShorthandPropertyAssignment(node) { + return node.kind === 276; + } + ts.isShorthandPropertyAssignment = isShorthandPropertyAssignment; + function isSpreadAssignment(node) { + return node.kind === 277; + } + ts.isSpreadAssignment = isSpreadAssignment; + function isEnumMember(node) { + return node.kind === 278; + } + ts.isEnumMember = isEnumMember; + function isSourceFile(node) { + return node.kind === 279; + } + ts.isSourceFile = isSourceFile; + function isBundle(node) { + return node.kind === 280; + } + ts.isBundle = isBundle; + function isUnparsedSource(node) { + return node.kind === 281; + } + ts.isUnparsedSource = isUnparsedSource; + function isJSDocTypeExpression(node) { + return node.kind === 283; + } + ts.isJSDocTypeExpression = isJSDocTypeExpression; + function isJSDocAllType(node) { + return node.kind === 284; + } + ts.isJSDocAllType = isJSDocAllType; + function isJSDocUnknownType(node) { + return node.kind === 285; + } + ts.isJSDocUnknownType = isJSDocUnknownType; + function isJSDocNullableType(node) { + return node.kind === 286; + } + ts.isJSDocNullableType = isJSDocNullableType; + function isJSDocNonNullableType(node) { + return node.kind === 287; + } + ts.isJSDocNonNullableType = isJSDocNonNullableType; + function isJSDocOptionalType(node) { + return node.kind === 288; + } + ts.isJSDocOptionalType = isJSDocOptionalType; + function isJSDocFunctionType(node) { + return node.kind === 289; + } + ts.isJSDocFunctionType = isJSDocFunctionType; + function isJSDocVariadicType(node) { + return node.kind === 290; + } + ts.isJSDocVariadicType = isJSDocVariadicType; + function isJSDoc(node) { + return node.kind === 291; + } + ts.isJSDoc = isJSDoc; + function isJSDocAugmentsTag(node) { + return node.kind === 295; + } + ts.isJSDocAugmentsTag = isJSDocAugmentsTag; + function isJSDocClassTag(node) { + return node.kind === 296; + } + ts.isJSDocClassTag = isJSDocClassTag; + function isJSDocEnumTag(node) { + return node.kind === 298; + } + ts.isJSDocEnumTag = isJSDocEnumTag; + function isJSDocThisTag(node) { + return node.kind === 301; + } + ts.isJSDocThisTag = isJSDocThisTag; + function isJSDocParameterTag(node) { + return node.kind === 299; + } + ts.isJSDocParameterTag = isJSDocParameterTag; + function isJSDocReturnTag(node) { + return node.kind === 300; + } + ts.isJSDocReturnTag = isJSDocReturnTag; + function isJSDocTypeTag(node) { + return node.kind === 302; + } + ts.isJSDocTypeTag = isJSDocTypeTag; + function isJSDocTemplateTag(node) { + return node.kind === 303; + } + ts.isJSDocTemplateTag = isJSDocTemplateTag; + function isJSDocTypedefTag(node) { + return node.kind === 304; + } + ts.isJSDocTypedefTag = isJSDocTypedefTag; + function isJSDocPropertyTag(node) { + return node.kind === 305; + } + ts.isJSDocPropertyTag = isJSDocPropertyTag; + function isJSDocPropertyLikeTag(node) { + return node.kind === 305 || node.kind === 299; + } + ts.isJSDocPropertyLikeTag = isJSDocPropertyLikeTag; + function isJSDocTypeLiteral(node) { + return node.kind === 292; + } + ts.isJSDocTypeLiteral = isJSDocTypeLiteral; + function isJSDocCallbackTag(node) { + return node.kind === 297; + } + ts.isJSDocCallbackTag = isJSDocCallbackTag; + function isJSDocSignature(node) { + return node.kind === 293; + } + ts.isJSDocSignature = isJSDocSignature; +})(ts || (ts = {})); +(function (ts) { + function isSyntaxList(n) { + return n.kind === 306; + } + ts.isSyntaxList = isSyntaxList; + function isNode(node) { + return isNodeKind(node.kind); + } + ts.isNode = isNode; + function isNodeKind(kind) { + return kind >= 148; + } + ts.isNodeKind = isNodeKind; + function isToken(n) { + return n.kind >= 0 && n.kind <= 147; + } + ts.isToken = isToken; + function isNodeArray(array) { + return array.hasOwnProperty("pos") && array.hasOwnProperty("end"); + } + ts.isNodeArray = isNodeArray; + function isLiteralKind(kind) { + return 8 <= kind && kind <= 14; + } + ts.isLiteralKind = isLiteralKind; + function isLiteralExpression(node) { + return isLiteralKind(node.kind); + } + ts.isLiteralExpression = isLiteralExpression; + function isTemplateLiteralKind(kind) { + return 14 <= kind && kind <= 17; + } + ts.isTemplateLiteralKind = isTemplateLiteralKind; + function isTemplateLiteralToken(node) { + return isTemplateLiteralKind(node.kind); + } + ts.isTemplateLiteralToken = isTemplateLiteralToken; + function isTemplateMiddleOrTemplateTail(node) { + var kind = node.kind; + return kind === 16 + || kind === 17; + } + ts.isTemplateMiddleOrTemplateTail = isTemplateMiddleOrTemplateTail; + function isImportOrExportSpecifier(node) { + return ts.isImportSpecifier(node) || ts.isExportSpecifier(node); + } + ts.isImportOrExportSpecifier = isImportOrExportSpecifier; + function isStringTextContainingNode(node) { + return node.kind === 10 || isTemplateLiteralKind(node.kind); + } + ts.isStringTextContainingNode = isStringTextContainingNode; + function isGeneratedIdentifier(node) { + return ts.isIdentifier(node) && (node.autoGenerateFlags & 7) > 0; + } + ts.isGeneratedIdentifier = isGeneratedIdentifier; + function isModifierKind(token) { + switch (token) { + case 118: + case 121: + case 77: + case 125: + case 80: + case 85: + case 115: + case 113: + case 114: + case 133: + case 116: + return true; + } + return false; + } + ts.isModifierKind = isModifierKind; + function isParameterPropertyModifier(kind) { + return !!(ts.modifierToFlag(kind) & 92); + } + ts.isParameterPropertyModifier = isParameterPropertyModifier; + function isClassMemberModifier(idToken) { + return isParameterPropertyModifier(idToken) || idToken === 116; + } + ts.isClassMemberModifier = isClassMemberModifier; + function isModifier(node) { + return isModifierKind(node.kind); + } + ts.isModifier = isModifier; + function isEntityName(node) { + var kind = node.kind; + return kind === 148 + || kind === 72; + } + ts.isEntityName = isEntityName; + function isPropertyName(node) { + var kind = node.kind; + return kind === 72 + || kind === 10 + || kind === 8 + || kind === 149; + } + ts.isPropertyName = isPropertyName; + function isBindingName(node) { + var kind = node.kind; + return kind === 72 + || kind === 184 + || kind === 185; + } + ts.isBindingName = isBindingName; + function isFunctionLike(node) { + return node && isFunctionLikeKind(node.kind); + } + ts.isFunctionLike = isFunctionLike; + function isFunctionLikeDeclaration(node) { + return node && isFunctionLikeDeclarationKind(node.kind); + } + ts.isFunctionLikeDeclaration = isFunctionLikeDeclaration; + function isFunctionLikeDeclarationKind(kind) { + switch (kind) { + case 239: + case 156: + case 157: + case 158: + case 159: + case 196: + case 197: + return true; + default: + return false; + } + } + function isFunctionLikeKind(kind) { + switch (kind) { + case 155: + case 160: + case 293: + case 161: + case 162: + case 165: + case 289: + case 166: + return true; + default: + return isFunctionLikeDeclarationKind(kind); + } + } + ts.isFunctionLikeKind = isFunctionLikeKind; + function isFunctionOrModuleBlock(node) { + return ts.isSourceFile(node) || ts.isModuleBlock(node) || ts.isBlock(node) && isFunctionLike(node.parent); + } + ts.isFunctionOrModuleBlock = isFunctionOrModuleBlock; + function isClassElement(node) { + var kind = node.kind; + return kind === 157 + || kind === 154 + || kind === 156 + || kind === 158 + || kind === 159 + || kind === 162 + || kind === 217; + } + ts.isClassElement = isClassElement; + function isClassLike(node) { + return node && (node.kind === 240 || node.kind === 209); + } + ts.isClassLike = isClassLike; + function isAccessor(node) { + return node && (node.kind === 158 || node.kind === 159); + } + ts.isAccessor = isAccessor; + function isMethodOrAccessor(node) { + switch (node.kind) { + case 156: + case 158: + case 159: + return true; + default: + return false; + } + } + ts.isMethodOrAccessor = isMethodOrAccessor; + function isTypeElement(node) { + var kind = node.kind; + return kind === 161 + || kind === 160 + || kind === 153 + || kind === 155 + || kind === 162; + } + ts.isTypeElement = isTypeElement; + function isClassOrTypeElement(node) { + return isTypeElement(node) || isClassElement(node); + } + ts.isClassOrTypeElement = isClassOrTypeElement; + function isObjectLiteralElementLike(node) { + var kind = node.kind; + return kind === 275 + || kind === 276 + || kind === 277 + || kind === 156 + || kind === 158 + || kind === 159; + } + ts.isObjectLiteralElementLike = isObjectLiteralElementLike; + function isTypeNode(node) { + return ts.isTypeNodeKind(node.kind); + } + ts.isTypeNode = isTypeNode; + function isFunctionOrConstructorTypeNode(node) { + switch (node.kind) { + case 165: + case 166: + return true; + } + return false; + } + ts.isFunctionOrConstructorTypeNode = isFunctionOrConstructorTypeNode; + function isBindingPattern(node) { + if (node) { + var kind = node.kind; + return kind === 185 + || kind === 184; + } + return false; + } + ts.isBindingPattern = isBindingPattern; + function isAssignmentPattern(node) { + var kind = node.kind; + return kind === 187 + || kind === 188; + } + ts.isAssignmentPattern = isAssignmentPattern; + function isArrayBindingElement(node) { + var kind = node.kind; + return kind === 186 + || kind === 210; + } + ts.isArrayBindingElement = isArrayBindingElement; + function isDeclarationBindingElement(bindingElement) { + switch (bindingElement.kind) { + case 237: + case 151: + case 186: + return true; + } + return false; + } + ts.isDeclarationBindingElement = isDeclarationBindingElement; + function isBindingOrAssignmentPattern(node) { + return isObjectBindingOrAssignmentPattern(node) + || isArrayBindingOrAssignmentPattern(node); + } + ts.isBindingOrAssignmentPattern = isBindingOrAssignmentPattern; + function isObjectBindingOrAssignmentPattern(node) { + switch (node.kind) { + case 184: + case 188: + return true; + } + return false; + } + ts.isObjectBindingOrAssignmentPattern = isObjectBindingOrAssignmentPattern; + function isArrayBindingOrAssignmentPattern(node) { + switch (node.kind) { + case 185: + case 187: + return true; + } + return false; + } + ts.isArrayBindingOrAssignmentPattern = isArrayBindingOrAssignmentPattern; + function isPropertyAccessOrQualifiedNameOrImportTypeNode(node) { + var kind = node.kind; + return kind === 189 + || kind === 148 + || kind === 183; + } + ts.isPropertyAccessOrQualifiedNameOrImportTypeNode = isPropertyAccessOrQualifiedNameOrImportTypeNode; + function isPropertyAccessOrQualifiedName(node) { + var kind = node.kind; + return kind === 189 + || kind === 148; + } + ts.isPropertyAccessOrQualifiedName = isPropertyAccessOrQualifiedName; + function isCallLikeExpression(node) { + switch (node.kind) { + case 262: + case 261: + case 191: + case 192: + case 193: + case 152: + return true; + default: + return false; + } + } + ts.isCallLikeExpression = isCallLikeExpression; + function isCallOrNewExpression(node) { + return node.kind === 191 || node.kind === 192; + } + ts.isCallOrNewExpression = isCallOrNewExpression; + function isTemplateLiteral(node) { + var kind = node.kind; + return kind === 206 + || kind === 14; + } + ts.isTemplateLiteral = isTemplateLiteral; + function isLeftHandSideExpression(node) { + return isLeftHandSideExpressionKind(ts.skipPartiallyEmittedExpressions(node).kind); + } + ts.isLeftHandSideExpression = isLeftHandSideExpression; + function isLeftHandSideExpressionKind(kind) { + switch (kind) { + case 189: + case 190: + case 192: + case 191: + case 260: + case 261: + case 264: + case 193: + case 187: + case 195: + case 188: + case 209: + case 196: + case 72: + case 13: + case 8: + case 9: + case 10: + case 14: + case 206: + case 87: + case 96: + case 100: + case 102: + case 98: + case 213: + case 214: + case 92: + return true; + default: + return false; + } + } + function isUnaryExpression(node) { + return isUnaryExpressionKind(ts.skipPartiallyEmittedExpressions(node).kind); + } + ts.isUnaryExpression = isUnaryExpression; + function isUnaryExpressionKind(kind) { + switch (kind) { + case 202: + case 203: + case 198: + case 199: + case 200: + case 201: + case 194: + return true; + default: + return isLeftHandSideExpressionKind(kind); + } + } + function isUnaryExpressionWithWrite(expr) { + switch (expr.kind) { + case 203: + return true; + case 202: + return expr.operator === 44 || + expr.operator === 45; + default: + return false; + } + } + ts.isUnaryExpressionWithWrite = isUnaryExpressionWithWrite; + function isExpression(node) { + return isExpressionKind(ts.skipPartiallyEmittedExpressions(node).kind); + } + ts.isExpression = isExpression; + function isExpressionKind(kind) { + switch (kind) { + case 205: + case 207: + case 197: + case 204: + case 208: + case 212: + case 210: + case 309: + case 308: + return true; + default: + return isUnaryExpressionKind(kind); + } + } + function isAssertionExpression(node) { + var kind = node.kind; + return kind === 194 + || kind === 212; + } + ts.isAssertionExpression = isAssertionExpression; + function isPartiallyEmittedExpression(node) { + return node.kind === 308; + } + ts.isPartiallyEmittedExpression = isPartiallyEmittedExpression; + function isNotEmittedStatement(node) { + return node.kind === 307; + } + ts.isNotEmittedStatement = isNotEmittedStatement; + function isNotEmittedOrPartiallyEmittedNode(node) { + return isNotEmittedStatement(node) + || isPartiallyEmittedExpression(node); + } + ts.isNotEmittedOrPartiallyEmittedNode = isNotEmittedOrPartiallyEmittedNode; + function isIterationStatement(node, lookInLabeledStatements) { + switch (node.kind) { + case 225: + case 226: + case 227: + case 223: + case 224: + return true; + case 233: + return lookInLabeledStatements && isIterationStatement(node.statement, lookInLabeledStatements); + } + return false; + } + ts.isIterationStatement = isIterationStatement; + function isForInOrOfStatement(node) { + return node.kind === 226 || node.kind === 227; + } + ts.isForInOrOfStatement = isForInOrOfStatement; + function isConciseBody(node) { + return ts.isBlock(node) + || isExpression(node); + } + ts.isConciseBody = isConciseBody; + function isFunctionBody(node) { + return ts.isBlock(node); + } + ts.isFunctionBody = isFunctionBody; + function isForInitializer(node) { + return ts.isVariableDeclarationList(node) + || isExpression(node); + } + ts.isForInitializer = isForInitializer; + function isModuleBody(node) { + var kind = node.kind; + return kind === 245 + || kind === 244 + || kind === 72; + } + ts.isModuleBody = isModuleBody; + function isNamespaceBody(node) { + var kind = node.kind; + return kind === 245 + || kind === 244; + } + ts.isNamespaceBody = isNamespaceBody; + function isJSDocNamespaceBody(node) { + var kind = node.kind; + return kind === 72 + || kind === 244; + } + ts.isJSDocNamespaceBody = isJSDocNamespaceBody; + function isNamedImportBindings(node) { + var kind = node.kind; + return kind === 252 + || kind === 251; + } + ts.isNamedImportBindings = isNamedImportBindings; + function isModuleOrEnumDeclaration(node) { + return node.kind === 244 || node.kind === 243; + } + ts.isModuleOrEnumDeclaration = isModuleOrEnumDeclaration; + function isDeclarationKind(kind) { + return kind === 197 + || kind === 186 + || kind === 240 + || kind === 209 + || kind === 157 + || kind === 243 + || kind === 278 + || kind === 257 + || kind === 239 + || kind === 196 + || kind === 158 + || kind === 250 + || kind === 248 + || kind === 253 + || kind === 241 + || kind === 267 + || kind === 156 + || kind === 155 + || kind === 244 + || kind === 247 + || kind === 251 + || kind === 151 + || kind === 275 + || kind === 154 + || kind === 153 + || kind === 159 + || kind === 276 + || kind === 242 + || kind === 150 + || kind === 237 + || kind === 304 + || kind === 297 + || kind === 305; + } + function isDeclarationStatementKind(kind) { + return kind === 239 + || kind === 258 + || kind === 240 + || kind === 241 + || kind === 242 + || kind === 243 + || kind === 244 + || kind === 249 + || kind === 248 + || kind === 255 + || kind === 254 + || kind === 247; + } + function isStatementKindButNotDeclarationKind(kind) { + return kind === 229 + || kind === 228 + || kind === 236 + || kind === 223 + || kind === 221 + || kind === 220 + || kind === 226 + || kind === 227 + || kind === 225 + || kind === 222 + || kind === 233 + || kind === 230 + || kind === 232 + || kind === 234 + || kind === 235 + || kind === 219 + || kind === 224 + || kind === 231 + || kind === 307 + || kind === 311 + || kind === 310; + } + function isDeclaration(node) { + if (node.kind === 150) { + return node.parent.kind !== 303 || ts.isInJSFile(node); + } + return isDeclarationKind(node.kind); + } + ts.isDeclaration = isDeclaration; + function isDeclarationStatement(node) { + return isDeclarationStatementKind(node.kind); + } + ts.isDeclarationStatement = isDeclarationStatement; + function isStatementButNotDeclaration(node) { + return isStatementKindButNotDeclarationKind(node.kind); + } + ts.isStatementButNotDeclaration = isStatementButNotDeclaration; + function isStatement(node) { + var kind = node.kind; + return isStatementKindButNotDeclarationKind(kind) + || isDeclarationStatementKind(kind) + || isBlockStatement(node); + } + ts.isStatement = isStatement; + function isBlockStatement(node) { + if (node.kind !== 218) + return false; + if (node.parent !== undefined) { + if (node.parent.kind === 235 || node.parent.kind === 274) { + return false; + } + } + return !ts.isFunctionBlock(node); + } + function isModuleReference(node) { + var kind = node.kind; + return kind === 259 + || kind === 148 + || kind === 72; + } + ts.isModuleReference = isModuleReference; + function isJsxTagNameExpression(node) { + var kind = node.kind; + return kind === 100 + || kind === 72 + || kind === 189; + } + ts.isJsxTagNameExpression = isJsxTagNameExpression; + function isJsxChild(node) { + var kind = node.kind; + return kind === 260 + || kind === 270 + || kind === 261 + || kind === 11 + || kind === 264; + } + ts.isJsxChild = isJsxChild; + function isJsxAttributeLike(node) { + var kind = node.kind; + return kind === 267 + || kind === 269; + } + ts.isJsxAttributeLike = isJsxAttributeLike; + function isStringLiteralOrJsxExpression(node) { + var kind = node.kind; + return kind === 10 + || kind === 270; + } + ts.isStringLiteralOrJsxExpression = isStringLiteralOrJsxExpression; + function isJsxOpeningLikeElement(node) { + var kind = node.kind; + return kind === 262 + || kind === 261; + } + ts.isJsxOpeningLikeElement = isJsxOpeningLikeElement; + function isCaseOrDefaultClause(node) { + var kind = node.kind; + return kind === 271 + || kind === 272; + } + ts.isCaseOrDefaultClause = isCaseOrDefaultClause; + function isJSDocNode(node) { + return node.kind >= 283 && node.kind <= 305; + } + ts.isJSDocNode = isJSDocNode; + function isJSDocCommentContainingNode(node) { + return node.kind === 291 || isJSDocTag(node) || ts.isJSDocTypeLiteral(node) || ts.isJSDocSignature(node); + } + ts.isJSDocCommentContainingNode = isJSDocCommentContainingNode; + function isJSDocTag(node) { + return node.kind >= 294 && node.kind <= 305; + } + ts.isJSDocTag = isJSDocTag; + function isSetAccessor(node) { + return node.kind === 159; + } + ts.isSetAccessor = isSetAccessor; + function isGetAccessor(node) { + return node.kind === 158; + } + ts.isGetAccessor = isGetAccessor; + function hasJSDocNodes(node) { + var jsDoc = node.jsDoc; + return !!jsDoc && jsDoc.length > 0; + } + ts.hasJSDocNodes = hasJSDocNodes; + function hasType(node) { + return !!node.type; + } + ts.hasType = hasType; + function hasInitializer(node) { + return !!node.initializer; + } + ts.hasInitializer = hasInitializer; + function hasOnlyExpressionInitializer(node) { + return hasInitializer(node) && !ts.isForStatement(node) && !ts.isForInStatement(node) && !ts.isForOfStatement(node) && !ts.isJsxAttribute(node); + } + ts.hasOnlyExpressionInitializer = hasOnlyExpressionInitializer; + function isObjectLiteralElement(node) { + return node.kind === 267 || node.kind === 269 || isObjectLiteralElementLike(node); + } + ts.isObjectLiteralElement = isObjectLiteralElement; + function isTypeReferenceType(node) { + return node.kind === 164 || node.kind === 211; + } + ts.isTypeReferenceType = isTypeReferenceType; + var MAX_SMI_X86 = 1073741823; + function guessIndentation(lines) { + var indentation = MAX_SMI_X86; + for (var _i = 0, lines_1 = lines; _i < lines_1.length; _i++) { + var line = lines_1[_i]; + if (!line.length) { + continue; + } + var i = 0; + for (; i < line.length && i < indentation; i++) { + if (!ts.isWhiteSpaceLike(line.charCodeAt(i))) { + break; + } + } + if (i < indentation) { + indentation = i; + } + if (indentation === 0) { + return 0; + } + } + return indentation === MAX_SMI_X86 ? undefined : indentation; + } + ts.guessIndentation = guessIndentation; + function isStringLiteralLike(node) { + return node.kind === 10 || node.kind === 14; + } + ts.isStringLiteralLike = isStringLiteralLike; +})(ts || (ts = {})); +(function (ts) { + function isNamedImportsOrExports(node) { + return node.kind === 252 || node.kind === 256; + } + ts.isNamedImportsOrExports = isNamedImportsOrExports; + function Symbol(flags, name) { + this.flags = flags; + this.escapedName = name; + this.declarations = undefined; + this.valueDeclaration = undefined; + this.id = undefined; + this.mergeId = undefined; + this.parent = undefined; + } + function Type(checker, flags) { + this.flags = flags; + if (ts.Debug.isDebugging) { + this.checker = checker; + } + } + function Signature() { } + function Node(kind, pos, end) { + this.pos = pos; + this.end = end; + this.kind = kind; + this.id = 0; + this.flags = 0; + this.modifierFlagsCache = 0; + this.transformFlags = 0; + this.parent = undefined; + this.original = undefined; + } + function SourceMapSource(fileName, text, skipTrivia) { + this.fileName = fileName; + this.text = text; + this.skipTrivia = skipTrivia || (function (pos) { return pos; }); + } + ts.objectAllocator = { + getNodeConstructor: function () { return Node; }, + getTokenConstructor: function () { return Node; }, + getIdentifierConstructor: function () { return Node; }, + getSourceFileConstructor: function () { return Node; }, + getSymbolConstructor: function () { return Symbol; }, + getTypeConstructor: function () { return Type; }, + getSignatureConstructor: function () { return Signature; }, + getSourceMapSourceConstructor: function () { return SourceMapSource; }, + }; + function formatStringFromArgs(text, args, baseIndex) { + if (baseIndex === void 0) { baseIndex = 0; } + return text.replace(/{(\d+)}/g, function (_match, index) { return "" + ts.Debug.assertDefined(args[+index + baseIndex]); }); + } + ts.formatStringFromArgs = formatStringFromArgs; + function getLocaleSpecificMessage(message) { + return ts.localizedDiagnosticMessages && ts.localizedDiagnosticMessages[message.key] || message.message; + } + ts.getLocaleSpecificMessage = getLocaleSpecificMessage; + function createFileDiagnostic(file, start, length, message) { + ts.Debug.assertGreaterThanOrEqual(start, 0); + ts.Debug.assertGreaterThanOrEqual(length, 0); + if (file) { + ts.Debug.assertLessThanOrEqual(start, file.text.length); + ts.Debug.assertLessThanOrEqual(start + length, file.text.length); + } + var text = getLocaleSpecificMessage(message); + if (arguments.length > 4) { + text = formatStringFromArgs(text, arguments, 4); + } + return { + file: file, + start: start, + length: length, + messageText: text, + category: message.category, + code: message.code, + reportsUnnecessary: message.reportsUnnecessary, + }; + } + ts.createFileDiagnostic = createFileDiagnostic; + function formatMessage(_dummy, message) { + var text = getLocaleSpecificMessage(message); + if (arguments.length > 2) { + text = formatStringFromArgs(text, arguments, 2); + } + return text; + } + ts.formatMessage = formatMessage; + function createCompilerDiagnostic(message) { + var text = getLocaleSpecificMessage(message); + if (arguments.length > 1) { + text = formatStringFromArgs(text, arguments, 1); + } + return { + file: undefined, + start: undefined, + length: undefined, + messageText: text, + category: message.category, + code: message.code, + reportsUnnecessary: message.reportsUnnecessary, + }; + } + ts.createCompilerDiagnostic = createCompilerDiagnostic; + function createCompilerDiagnosticFromMessageChain(chain) { + return { + file: undefined, + start: undefined, + length: undefined, + code: chain.code, + category: chain.category, + messageText: chain.next ? chain : chain.messageText, + }; + } + ts.createCompilerDiagnosticFromMessageChain = createCompilerDiagnosticFromMessageChain; + function chainDiagnosticMessages(details, message) { + var text = getLocaleSpecificMessage(message); + if (arguments.length > 2) { + text = formatStringFromArgs(text, arguments, 2); + } + return { + messageText: text, + category: message.category, + code: message.code, + next: details + }; + } + ts.chainDiagnosticMessages = chainDiagnosticMessages; + function concatenateDiagnosticMessageChains(headChain, tailChain) { + var lastChain = headChain; + while (lastChain.next) { + lastChain = lastChain.next; + } + lastChain.next = tailChain; + return headChain; + } + ts.concatenateDiagnosticMessageChains = concatenateDiagnosticMessageChains; + function getDiagnosticFilePath(diagnostic) { + return diagnostic.file ? diagnostic.file.path : undefined; + } + function compareDiagnostics(d1, d2) { + return compareDiagnosticsSkipRelatedInformation(d1, d2) || + compareRelatedInformation(d1, d2) || + 0; + } + ts.compareDiagnostics = compareDiagnostics; + function compareDiagnosticsSkipRelatedInformation(d1, d2) { + return ts.compareStringsCaseSensitive(getDiagnosticFilePath(d1), getDiagnosticFilePath(d2)) || + ts.compareValues(d1.start, d2.start) || + ts.compareValues(d1.length, d2.length) || + ts.compareValues(d1.code, d2.code) || + compareMessageText(d1.messageText, d2.messageText) || + 0; + } + ts.compareDiagnosticsSkipRelatedInformation = compareDiagnosticsSkipRelatedInformation; + function compareRelatedInformation(d1, d2) { + if (!d1.relatedInformation && !d2.relatedInformation) { + return 0; + } + if (d1.relatedInformation && d2.relatedInformation) { + return ts.compareValues(d1.relatedInformation.length, d2.relatedInformation.length) || ts.forEach(d1.relatedInformation, function (d1i, index) { + var d2i = d2.relatedInformation[index]; + return compareDiagnostics(d1i, d2i); + }) || 0; + } + return d1.relatedInformation ? -1 : 1; + } + function compareMessageText(t1, t2) { + var text1 = t1; + var text2 = t2; + while (text1 && text2) { + var string1 = ts.isString(text1) ? text1 : text1.messageText; + var string2 = ts.isString(text2) ? text2 : text2.messageText; + var res = ts.compareStringsCaseSensitive(string1, string2); + if (res) { + return res; + } + text1 = ts.isString(text1) ? undefined : text1.next; + text2 = ts.isString(text2) ? undefined : text2.next; + } + if (!text1 && !text2) { + return 0; + } + return text1 ? 1 : -1; + } + function getEmitScriptTarget(compilerOptions) { + return compilerOptions.target || 0; + } + ts.getEmitScriptTarget = getEmitScriptTarget; + function getEmitModuleKind(compilerOptions) { + return typeof compilerOptions.module === "number" ? + compilerOptions.module : + getEmitScriptTarget(compilerOptions) >= 2 ? ts.ModuleKind.ES2015 : ts.ModuleKind.CommonJS; + } + ts.getEmitModuleKind = getEmitModuleKind; + function getEmitModuleResolutionKind(compilerOptions) { + var moduleResolution = compilerOptions.moduleResolution; + if (moduleResolution === undefined) { + moduleResolution = getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS ? ts.ModuleResolutionKind.NodeJs : ts.ModuleResolutionKind.Classic; + } + return moduleResolution; + } + ts.getEmitModuleResolutionKind = getEmitModuleResolutionKind; + function hasJsonModuleEmitEnabled(options) { + switch (getEmitModuleKind(options)) { + case ts.ModuleKind.CommonJS: + case ts.ModuleKind.AMD: + case ts.ModuleKind.ES2015: + case ts.ModuleKind.ESNext: + return true; + default: + return false; + } + } + ts.hasJsonModuleEmitEnabled = hasJsonModuleEmitEnabled; + function unreachableCodeIsError(options) { + return options.allowUnreachableCode === false; + } + ts.unreachableCodeIsError = unreachableCodeIsError; + function unusedLabelIsError(options) { + return options.allowUnusedLabels === false; + } + ts.unusedLabelIsError = unusedLabelIsError; + function getAreDeclarationMapsEnabled(options) { + return !!(getEmitDeclarations(options) && options.declarationMap); + } + ts.getAreDeclarationMapsEnabled = getAreDeclarationMapsEnabled; + function getAllowSyntheticDefaultImports(compilerOptions) { + var moduleKind = getEmitModuleKind(compilerOptions); + return compilerOptions.allowSyntheticDefaultImports !== undefined + ? compilerOptions.allowSyntheticDefaultImports + : compilerOptions.esModuleInterop || + moduleKind === ts.ModuleKind.System; + } + ts.getAllowSyntheticDefaultImports = getAllowSyntheticDefaultImports; + function getEmitDeclarations(compilerOptions) { + return !!(compilerOptions.declaration || compilerOptions.composite); + } + ts.getEmitDeclarations = getEmitDeclarations; + function getStrictOptionValue(compilerOptions, flag) { + return compilerOptions[flag] === undefined ? !!compilerOptions.strict : !!compilerOptions[flag]; + } + ts.getStrictOptionValue = getStrictOptionValue; + function compilerOptionsAffectSemanticDiagnostics(newOptions, oldOptions) { + return oldOptions !== newOptions && + ts.semanticDiagnosticsOptionDeclarations.some(function (option) { return !ts.isJsonEqual(getCompilerOptionValue(oldOptions, option), getCompilerOptionValue(newOptions, option)); }); + } + ts.compilerOptionsAffectSemanticDiagnostics = compilerOptionsAffectSemanticDiagnostics; + function getCompilerOptionValue(options, option) { + return option.strictFlag ? getStrictOptionValue(options, option.name) : options[option.name]; + } + ts.getCompilerOptionValue = getCompilerOptionValue; + function hasZeroOrOneAsteriskCharacter(str) { + var seenAsterisk = false; + for (var i = 0; i < str.length; i++) { + if (str.charCodeAt(i) === 42) { + if (!seenAsterisk) { + seenAsterisk = true; + } + else { + return false; + } + } + } + return true; + } + ts.hasZeroOrOneAsteriskCharacter = hasZeroOrOneAsteriskCharacter; + ts.directorySeparator = "/"; + var altDirectorySeparator = "\\"; + var urlSchemeSeparator = "://"; + var backslashRegExp = /\\/g; + function normalizeSlashes(path) { + return path.replace(backslashRegExp, ts.directorySeparator); + } + ts.normalizeSlashes = normalizeSlashes; + function isVolumeCharacter(charCode) { + return (charCode >= 97 && charCode <= 122) || + (charCode >= 65 && charCode <= 90); + } + function getFileUrlVolumeSeparatorEnd(url, start) { + var ch0 = url.charCodeAt(start); + if (ch0 === 58) + return start + 1; + if (ch0 === 37 && url.charCodeAt(start + 1) === 51) { + var ch2 = url.charCodeAt(start + 2); + if (ch2 === 97 || ch2 === 65) + return start + 3; + } + return -1; + } + function getEncodedRootLength(path) { + if (!path) + return 0; + var ch0 = path.charCodeAt(0); + if (ch0 === 47 || ch0 === 92) { + if (path.charCodeAt(1) !== ch0) + return 1; + var p1 = path.indexOf(ch0 === 47 ? ts.directorySeparator : altDirectorySeparator, 2); + if (p1 < 0) + return path.length; + return p1 + 1; + } + if (isVolumeCharacter(ch0) && path.charCodeAt(1) === 58) { + var ch2 = path.charCodeAt(2); + if (ch2 === 47 || ch2 === 92) + return 3; + if (path.length === 2) + return 2; + } + var schemeEnd = path.indexOf(urlSchemeSeparator); + if (schemeEnd !== -1) { + var authorityStart = schemeEnd + urlSchemeSeparator.length; + var authorityEnd = path.indexOf(ts.directorySeparator, authorityStart); + if (authorityEnd !== -1) { + var scheme = path.slice(0, schemeEnd); + var authority = path.slice(authorityStart, authorityEnd); + if (scheme === "file" && (authority === "" || authority === "localhost") && + isVolumeCharacter(path.charCodeAt(authorityEnd + 1))) { + var volumeSeparatorEnd = getFileUrlVolumeSeparatorEnd(path, authorityEnd + 2); + if (volumeSeparatorEnd !== -1) { + if (path.charCodeAt(volumeSeparatorEnd) === 47) { + return ~(volumeSeparatorEnd + 1); + } + if (volumeSeparatorEnd === path.length) { + return ~volumeSeparatorEnd; + } + } + } + return ~(authorityEnd + 1); + } + return ~path.length; + } + return 0; + } + function getRootLength(path) { + var rootLength = getEncodedRootLength(path); + return rootLength < 0 ? ~rootLength : rootLength; + } + ts.getRootLength = getRootLength; + function normalizePath(path) { + return ts.resolvePath(path); + } + ts.normalizePath = normalizePath; + function normalizePathAndParts(path) { + path = normalizeSlashes(path); + var _a = reducePathComponents(getPathComponents(path)), root = _a[0], parts = _a.slice(1); + if (parts.length) { + var joinedParts = root + parts.join(ts.directorySeparator); + return { path: ts.hasTrailingDirectorySeparator(path) ? ts.ensureTrailingDirectorySeparator(joinedParts) : joinedParts, parts: parts }; + } + else { + return { path: root, parts: parts }; + } + } + ts.normalizePathAndParts = normalizePathAndParts; + function getDirectoryPath(path) { + path = normalizeSlashes(path); + var rootLength = getRootLength(path); + if (rootLength === path.length) + return path; + path = ts.removeTrailingDirectorySeparator(path); + return path.slice(0, Math.max(rootLength, path.lastIndexOf(ts.directorySeparator))); + } + ts.getDirectoryPath = getDirectoryPath; + function startsWithDirectory(fileName, directoryName, getCanonicalFileName) { + var canonicalFileName = getCanonicalFileName(fileName); + var canonicalDirectoryName = getCanonicalFileName(directoryName); + return ts.startsWith(canonicalFileName, canonicalDirectoryName + "/") || ts.startsWith(canonicalFileName, canonicalDirectoryName + "\\"); + } + ts.startsWithDirectory = startsWithDirectory; + function isUrl(path) { + return getEncodedRootLength(path) < 0; + } + ts.isUrl = isUrl; + function pathIsRelative(path) { + return /^\.\.?($|[\\/])/.test(path); + } + ts.pathIsRelative = pathIsRelative; + function isRootedDiskPath(path) { + return getEncodedRootLength(path) > 0; + } + ts.isRootedDiskPath = isRootedDiskPath; + function isDiskPathRoot(path) { + var rootLength = getEncodedRootLength(path); + return rootLength > 0 && rootLength === path.length; + } + ts.isDiskPathRoot = isDiskPathRoot; + function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) { + return !isRootedDiskPath(absoluteOrRelativePath) + ? absoluteOrRelativePath + : ts.getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, false); + } + ts.convertToRelativePath = convertToRelativePath; + function pathComponents(path, rootLength) { + var root = path.substring(0, rootLength); + var rest = path.substring(rootLength).split(ts.directorySeparator); + if (rest.length && !ts.lastOrUndefined(rest)) + rest.pop(); + return [root].concat(rest); + } + function getPathComponents(path, currentDirectory) { + if (currentDirectory === void 0) { currentDirectory = ""; } + path = ts.combinePaths(currentDirectory, path); + var rootLength = getRootLength(path); + return pathComponents(path, rootLength); + } + ts.getPathComponents = getPathComponents; + function reducePathComponents(components) { + if (!ts.some(components)) + return []; + var reduced = [components[0]]; + for (var i = 1; i < components.length; i++) { + var component = components[i]; + if (!component) + continue; + if (component === ".") + continue; + if (component === "..") { + if (reduced.length > 1) { + if (reduced[reduced.length - 1] !== "..") { + reduced.pop(); + continue; + } + } + else if (reduced[0]) + continue; + } + reduced.push(component); + } + return reduced; + } + ts.reducePathComponents = reducePathComponents; + function getNormalizedPathComponents(path, currentDirectory) { + return reducePathComponents(getPathComponents(path, currentDirectory)); + } + ts.getNormalizedPathComponents = getNormalizedPathComponents; + function getNormalizedAbsolutePath(fileName, currentDirectory) { + return getPathFromPathComponents(getNormalizedPathComponents(fileName, currentDirectory)); + } + ts.getNormalizedAbsolutePath = getNormalizedAbsolutePath; + function getPathFromPathComponents(pathComponents) { + if (pathComponents.length === 0) + return ""; + var root = pathComponents[0] && ts.ensureTrailingDirectorySeparator(pathComponents[0]); + return root + pathComponents.slice(1).join(ts.directorySeparator); + } + ts.getPathFromPathComponents = getPathFromPathComponents; +})(ts || (ts = {})); +(function (ts) { + function getPathComponentsRelativeTo(from, to, stringEqualityComparer, getCanonicalFileName) { + var fromComponents = ts.reducePathComponents(ts.getPathComponents(from)); + var toComponents = ts.reducePathComponents(ts.getPathComponents(to)); + var start; + for (start = 0; start < fromComponents.length && start < toComponents.length; start++) { + var fromComponent = getCanonicalFileName(fromComponents[start]); + var toComponent = getCanonicalFileName(toComponents[start]); + var comparer = start === 0 ? ts.equateStringsCaseInsensitive : stringEqualityComparer; + if (!comparer(fromComponent, toComponent)) + break; + } + if (start === 0) { + return toComponents; + } + var components = toComponents.slice(start); + var relative = []; + for (; start < fromComponents.length; start++) { + relative.push(".."); + } + return [""].concat(relative, components); + } + ts.getPathComponentsRelativeTo = getPathComponentsRelativeTo; + function getRelativePathFromFile(from, to, getCanonicalFileName) { + return ensurePathIsNonModuleName(getRelativePathFromDirectory(ts.getDirectoryPath(from), to, getCanonicalFileName)); + } + ts.getRelativePathFromFile = getRelativePathFromFile; + function getRelativePathFromDirectory(fromDirectory, to, getCanonicalFileNameOrIgnoreCase) { + Debug.assert((ts.getRootLength(fromDirectory) > 0) === (ts.getRootLength(to) > 0), "Paths must either both be absolute or both be relative"); + var getCanonicalFileName = typeof getCanonicalFileNameOrIgnoreCase === "function" ? getCanonicalFileNameOrIgnoreCase : ts.identity; + var ignoreCase = typeof getCanonicalFileNameOrIgnoreCase === "boolean" ? getCanonicalFileNameOrIgnoreCase : false; + var pathComponents = getPathComponentsRelativeTo(fromDirectory, to, ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive, getCanonicalFileName); + return ts.getPathFromPathComponents(pathComponents); + } + ts.getRelativePathFromDirectory = getRelativePathFromDirectory; + function getRelativePathToDirectoryOrUrl(directoryPathOrUrl, relativeOrAbsolutePath, currentDirectory, getCanonicalFileName, isAbsolutePathAnUrl) { + var pathComponents = getPathComponentsRelativeTo(resolvePath(currentDirectory, directoryPathOrUrl), resolvePath(currentDirectory, relativeOrAbsolutePath), ts.equateStringsCaseSensitive, getCanonicalFileName); + var firstComponent = pathComponents[0]; + if (isAbsolutePathAnUrl && ts.isRootedDiskPath(firstComponent)) { + var prefix = firstComponent.charAt(0) === ts.directorySeparator ? "file://" : "file:///"; + pathComponents[0] = prefix + firstComponent; + } + return ts.getPathFromPathComponents(pathComponents); + } + ts.getRelativePathToDirectoryOrUrl = getRelativePathToDirectoryOrUrl; + function ensurePathIsNonModuleName(path) { + return ts.getRootLength(path) === 0 && !ts.pathIsRelative(path) ? "./" + path : path; + } + ts.ensurePathIsNonModuleName = ensurePathIsNonModuleName; + function getBaseFileName(path, extensions, ignoreCase) { + path = ts.normalizeSlashes(path); + var rootLength = ts.getRootLength(path); + if (rootLength === path.length) + return ""; + path = removeTrailingDirectorySeparator(path); + var name = path.slice(Math.max(ts.getRootLength(path), path.lastIndexOf(ts.directorySeparator) + 1)); + var extension = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(name, extensions, ignoreCase) : undefined; + return extension ? name.slice(0, name.length - extension.length) : name; + } + ts.getBaseFileName = getBaseFileName; + function combinePaths(path) { + var paths = []; + for (var _i = 1; _i < arguments.length; _i++) { + paths[_i - 1] = arguments[_i]; + } + if (path) + path = ts.normalizeSlashes(path); + for (var _a = 0, paths_1 = paths; _a < paths_1.length; _a++) { + var relativePath = paths_1[_a]; + if (!relativePath) + continue; + relativePath = ts.normalizeSlashes(relativePath); + if (!path || ts.getRootLength(relativePath) !== 0) { + path = relativePath; + } + else { + path = ensureTrailingDirectorySeparator(path) + relativePath; + } + } + return path; + } + ts.combinePaths = combinePaths; + function resolvePath(path) { + var paths = []; + for (var _i = 1; _i < arguments.length; _i++) { + paths[_i - 1] = arguments[_i]; + } + var combined = ts.some(paths) ? combinePaths.apply(void 0, [path].concat(paths)) : ts.normalizeSlashes(path); + var normalized = ts.getPathFromPathComponents(ts.reducePathComponents(ts.getPathComponents(combined))); + return normalized && hasTrailingDirectorySeparator(combined) ? ensureTrailingDirectorySeparator(normalized) : normalized; + } + ts.resolvePath = resolvePath; + function hasTrailingDirectorySeparator(path) { + if (path.length === 0) + return false; + var ch = path.charCodeAt(path.length - 1); + return ch === 47 || ch === 92; + } + ts.hasTrailingDirectorySeparator = hasTrailingDirectorySeparator; + function removeTrailingDirectorySeparator(path) { + if (hasTrailingDirectorySeparator(path)) { + return path.substr(0, path.length - 1); + } + return path; + } + ts.removeTrailingDirectorySeparator = removeTrailingDirectorySeparator; + function ensureTrailingDirectorySeparator(path) { + if (!hasTrailingDirectorySeparator(path)) { + return path + ts.directorySeparator; + } + return path; + } + ts.ensureTrailingDirectorySeparator = ensureTrailingDirectorySeparator; + function comparePathsWorker(a, b, componentComparer) { + if (a === b) + return 0; + if (a === undefined) + return -1; + if (b === undefined) + return 1; + var aComponents = ts.reducePathComponents(ts.getPathComponents(a)); + var bComponents = ts.reducePathComponents(ts.getPathComponents(b)); + var sharedLength = Math.min(aComponents.length, bComponents.length); + for (var i = 0; i < sharedLength; i++) { + var stringComparer = i === 0 ? ts.compareStringsCaseInsensitive : componentComparer; + var result = stringComparer(aComponents[i], bComponents[i]); + if (result !== 0) { + return result; + } + } + return ts.compareValues(aComponents.length, bComponents.length); + } + function comparePathsCaseSensitive(a, b) { + return comparePathsWorker(a, b, ts.compareStringsCaseSensitive); + } + ts.comparePathsCaseSensitive = comparePathsCaseSensitive; + function comparePathsCaseInsensitive(a, b) { + return comparePathsWorker(a, b, ts.compareStringsCaseInsensitive); + } + ts.comparePathsCaseInsensitive = comparePathsCaseInsensitive; + function comparePaths(a, b, currentDirectory, ignoreCase) { + if (typeof currentDirectory === "string") { + a = combinePaths(currentDirectory, a); + b = combinePaths(currentDirectory, b); + } + else if (typeof currentDirectory === "boolean") { + ignoreCase = currentDirectory; + } + return comparePathsWorker(a, b, ts.getStringComparer(ignoreCase)); + } + ts.comparePaths = comparePaths; + function containsPath(parent, child, currentDirectory, ignoreCase) { + if (typeof currentDirectory === "string") { + parent = combinePaths(currentDirectory, parent); + child = combinePaths(currentDirectory, child); + } + else if (typeof currentDirectory === "boolean") { + ignoreCase = currentDirectory; + } + if (parent === undefined || child === undefined) + return false; + if (parent === child) + return true; + var parentComponents = ts.reducePathComponents(ts.getPathComponents(parent)); + var childComponents = ts.reducePathComponents(ts.getPathComponents(child)); + if (childComponents.length < parentComponents.length) { + return false; + } + var componentEqualityComparer = ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive; + for (var i = 0; i < parentComponents.length; i++) { + var equalityComparer = i === 0 ? ts.equateStringsCaseInsensitive : componentEqualityComparer; + if (!equalityComparer(parentComponents[i], childComponents[i])) { + return false; + } + } + return true; + } + ts.containsPath = containsPath; + function isDirectorySeparator(charCode) { + return charCode === 47 || charCode === 92; + } + function stripLeadingDirectorySeparator(s) { + return isDirectorySeparator(s.charCodeAt(0)) ? s.slice(1) : undefined; + } + function tryRemoveDirectoryPrefix(path, dirPath, getCanonicalFileName) { + var withoutPrefix = ts.tryRemovePrefix(path, dirPath, getCanonicalFileName); + return withoutPrefix === undefined ? undefined : stripLeadingDirectorySeparator(withoutPrefix); + } + ts.tryRemoveDirectoryPrefix = tryRemoveDirectoryPrefix; + var reservedCharacterPattern = /[^\w\s\/]/g; + function regExpEscape(text) { + return text.replace(reservedCharacterPattern, escapeRegExpCharacter); + } + ts.regExpEscape = regExpEscape; + function escapeRegExpCharacter(match) { + return "\\" + match; + } + var wildcardCharCodes = [42, 63]; + function hasExtension(fileName) { + return ts.stringContains(getBaseFileName(fileName), "."); + } + ts.hasExtension = hasExtension; + ts.commonPackageFolders = ["node_modules", "bower_components", "jspm_packages"]; + var implicitExcludePathRegexPattern = "(?!(" + ts.commonPackageFolders.join("|") + ")(/|$))"; + var filesMatcher = { + singleAsteriskRegexFragment: "([^./]|(\\.(?!min\\.js$))?)*", + doubleAsteriskRegexFragment: "(/" + implicitExcludePathRegexPattern + "[^/.][^/]*)*?", + replaceWildcardCharacter: function (match) { return replaceWildcardCharacter(match, filesMatcher.singleAsteriskRegexFragment); } + }; + var directoriesMatcher = { + singleAsteriskRegexFragment: "[^/]*", + doubleAsteriskRegexFragment: "(/" + implicitExcludePathRegexPattern + "[^/.][^/]*)*?", + replaceWildcardCharacter: function (match) { return replaceWildcardCharacter(match, directoriesMatcher.singleAsteriskRegexFragment); } + }; + var excludeMatcher = { + singleAsteriskRegexFragment: "[^/]*", + doubleAsteriskRegexFragment: "(/.+?)?", + replaceWildcardCharacter: function (match) { return replaceWildcardCharacter(match, excludeMatcher.singleAsteriskRegexFragment); } + }; + var wildcardMatchers = { + files: filesMatcher, + directories: directoriesMatcher, + exclude: excludeMatcher + }; + function getRegularExpressionForWildcard(specs, basePath, usage) { + var patterns = getRegularExpressionsForWildcards(specs, basePath, usage); + if (!patterns || !patterns.length) { + return undefined; + } + var pattern = patterns.map(function (pattern) { return "(" + pattern + ")"; }).join("|"); + var terminator = usage === "exclude" ? "($|/)" : "$"; + return "^(" + pattern + ")" + terminator; + } + ts.getRegularExpressionForWildcard = getRegularExpressionForWildcard; + function getRegularExpressionsForWildcards(specs, basePath, usage) { + if (specs === undefined || specs.length === 0) { + return undefined; + } + return ts.flatMap(specs, function (spec) { + return spec && getSubPatternFromSpec(spec, basePath, usage, wildcardMatchers[usage]); + }); + } + ts.getRegularExpressionsForWildcards = getRegularExpressionsForWildcards; + function isImplicitGlob(lastPathComponent) { + return !/[.*?]/.test(lastPathComponent); + } + ts.isImplicitGlob = isImplicitGlob; + function getSubPatternFromSpec(spec, basePath, usage, _a) { + var singleAsteriskRegexFragment = _a.singleAsteriskRegexFragment, doubleAsteriskRegexFragment = _a.doubleAsteriskRegexFragment, replaceWildcardCharacter = _a.replaceWildcardCharacter; + var subpattern = ""; + var hasWrittenComponent = false; + var components = ts.getNormalizedPathComponents(spec, basePath); + var lastComponent = ts.last(components); + if (usage !== "exclude" && lastComponent === "**") { + return undefined; + } + components[0] = removeTrailingDirectorySeparator(components[0]); + if (isImplicitGlob(lastComponent)) { + components.push("**", "*"); + } + var optionalCount = 0; + for (var _i = 0, components_1 = components; _i < components_1.length; _i++) { + var component = components_1[_i]; + if (component === "**") { + subpattern += doubleAsteriskRegexFragment; + } + else { + if (usage === "directories") { + subpattern += "("; + optionalCount++; + } + if (hasWrittenComponent) { + subpattern += ts.directorySeparator; + } + if (usage !== "exclude") { + var componentPattern = ""; + if (component.charCodeAt(0) === 42) { + componentPattern += "([^./]" + singleAsteriskRegexFragment + ")?"; + component = component.substr(1); + } + else if (component.charCodeAt(0) === 63) { + componentPattern += "[^./]"; + component = component.substr(1); + } + componentPattern += component.replace(reservedCharacterPattern, replaceWildcardCharacter); + if (componentPattern !== component) { + subpattern += implicitExcludePathRegexPattern; + } + subpattern += componentPattern; + } + else { + subpattern += component.replace(reservedCharacterPattern, replaceWildcardCharacter); + } + } + hasWrittenComponent = true; + } + while (optionalCount > 0) { + subpattern += ")?"; + optionalCount--; + } + return subpattern; + } + function replaceWildcardCharacter(match, singleAsteriskRegexFragment) { + return match === "*" ? singleAsteriskRegexFragment : match === "?" ? "[^/]" : "\\" + match; + } + function getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory) { + path = ts.normalizePath(path); + currentDirectory = ts.normalizePath(currentDirectory); + var absolutePath = combinePaths(currentDirectory, path); + return { + includeFilePatterns: ts.map(getRegularExpressionsForWildcards(includes, absolutePath, "files"), function (pattern) { return "^" + pattern + "$"; }), + includeFilePattern: getRegularExpressionForWildcard(includes, absolutePath, "files"), + includeDirectoryPattern: getRegularExpressionForWildcard(includes, absolutePath, "directories"), + excludePattern: getRegularExpressionForWildcard(excludes, absolutePath, "exclude"), + basePaths: getBasePaths(path, includes, useCaseSensitiveFileNames) + }; + } + ts.getFileMatcherPatterns = getFileMatcherPatterns; + function getRegexFromPattern(pattern, useCaseSensitiveFileNames) { + return new RegExp(pattern, useCaseSensitiveFileNames ? "" : "i"); + } + ts.getRegexFromPattern = getRegexFromPattern; + function matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries) { + path = ts.normalizePath(path); + currentDirectory = ts.normalizePath(currentDirectory); + var patterns = getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory); + var includeFileRegexes = patterns.includeFilePatterns && patterns.includeFilePatterns.map(function (pattern) { return getRegexFromPattern(pattern, useCaseSensitiveFileNames); }); + var includeDirectoryRegex = patterns.includeDirectoryPattern && getRegexFromPattern(patterns.includeDirectoryPattern, useCaseSensitiveFileNames); + var excludeRegex = patterns.excludePattern && getRegexFromPattern(patterns.excludePattern, useCaseSensitiveFileNames); + var results = includeFileRegexes ? includeFileRegexes.map(function () { return []; }) : [[]]; + for (var _i = 0, _a = patterns.basePaths; _i < _a.length; _i++) { + var basePath = _a[_i]; + visitDirectory(basePath, combinePaths(currentDirectory, basePath), depth); + } + return ts.flatten(results); + function visitDirectory(path, absolutePath, depth) { + var _a = getFileSystemEntries(path), files = _a.files, directories = _a.directories; + var _loop_1 = function (current) { + var name = combinePaths(path, current); + var absoluteName = combinePaths(absolutePath, current); + if (extensions && !ts.fileExtensionIsOneOf(name, extensions)) + return "continue"; + if (excludeRegex && excludeRegex.test(absoluteName)) + return "continue"; + if (!includeFileRegexes) { + results[0].push(name); + } + else { + var includeIndex = ts.findIndex(includeFileRegexes, function (re) { return re.test(absoluteName); }); + if (includeIndex !== -1) { + results[includeIndex].push(name); + } + } + }; + for (var _i = 0, _b = ts.sort(files, ts.compareStringsCaseSensitive); _i < _b.length; _i++) { + var current = _b[_i]; + _loop_1(current); + } + if (depth !== undefined) { + depth--; + if (depth === 0) { + return; + } + } + for (var _c = 0, _d = ts.sort(directories, ts.compareStringsCaseSensitive); _c < _d.length; _c++) { + var current = _d[_c]; + var name = combinePaths(path, current); + var absoluteName = combinePaths(absolutePath, current); + if ((!includeDirectoryRegex || includeDirectoryRegex.test(absoluteName)) && + (!excludeRegex || !excludeRegex.test(absoluteName))) { + visitDirectory(name, absoluteName, depth); + } + } + } + } + ts.matchFiles = matchFiles; + function getBasePaths(path, includes, useCaseSensitiveFileNames) { + var basePaths = [path]; + if (includes) { + var includeBasePaths = []; + for (var _i = 0, includes_1 = includes; _i < includes_1.length; _i++) { + var include = includes_1[_i]; + var absolute = ts.isRootedDiskPath(include) ? include : ts.normalizePath(combinePaths(path, include)); + includeBasePaths.push(getIncludeBasePath(absolute)); + } + includeBasePaths.sort(ts.getStringComparer(!useCaseSensitiveFileNames)); + var _loop_2 = function (includeBasePath) { + if (ts.every(basePaths, function (basePath) { return !containsPath(basePath, includeBasePath, path, !useCaseSensitiveFileNames); })) { + basePaths.push(includeBasePath); + } + }; + for (var _a = 0, includeBasePaths_1 = includeBasePaths; _a < includeBasePaths_1.length; _a++) { + var includeBasePath = includeBasePaths_1[_a]; + _loop_2(includeBasePath); + } + } + return basePaths; + } + function getIncludeBasePath(absolute) { + var wildcardOffset = ts.indexOfAnyCharCode(absolute, wildcardCharCodes); + if (wildcardOffset < 0) { + return !hasExtension(absolute) + ? absolute + : removeTrailingDirectorySeparator(ts.getDirectoryPath(absolute)); + } + return absolute.substring(0, absolute.lastIndexOf(ts.directorySeparator, wildcardOffset)); + } + function ensureScriptKind(fileName, scriptKind) { + return scriptKind || getScriptKindFromFileName(fileName) || 3; + } + ts.ensureScriptKind = ensureScriptKind; + function getScriptKindFromFileName(fileName) { + var ext = fileName.substr(fileName.lastIndexOf(".")); + switch (ext.toLowerCase()) { + case ".js": + return 1; + case ".jsx": + return 2; + case ".ts": + return 3; + case ".tsx": + return 4; + case ".json": + return 6; + default: + return 0; + } + } + ts.getScriptKindFromFileName = getScriptKindFromFileName; + ts.supportedTSExtensions = [".ts", ".tsx", ".d.ts"]; + ts.supportedTSExtensionsWithJson = [".ts", ".tsx", ".d.ts", ".json"]; + ts.supportedTSExtensionsForExtractExtension = [".d.ts", ".ts", ".tsx"]; + ts.supportedJSExtensions = [".js", ".jsx"]; + ts.supportedJSAndJsonExtensions = [".js", ".jsx", ".json"]; + var allSupportedExtensions = ts.supportedTSExtensions.concat(ts.supportedJSExtensions); + var allSupportedExtensionsWithJson = ts.supportedTSExtensions.concat(ts.supportedJSExtensions, [".json"]); + function getSupportedExtensions(options, extraFileExtensions) { + var needJsExtensions = options && options.allowJs; + if (!extraFileExtensions || extraFileExtensions.length === 0) { + return needJsExtensions ? allSupportedExtensions : ts.supportedTSExtensions; + } + var extensions = (needJsExtensions ? allSupportedExtensions : ts.supportedTSExtensions).concat(ts.mapDefined(extraFileExtensions, function (x) { return x.scriptKind === 7 || needJsExtensions && isJSLike(x.scriptKind) ? x.extension : undefined; })); + return ts.deduplicate(extensions, ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive); + } + ts.getSupportedExtensions = getSupportedExtensions; + function getSuppoertedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions) { + if (!options || !options.resolveJsonModule) { + return supportedExtensions; + } + if (supportedExtensions === allSupportedExtensions) { + return allSupportedExtensionsWithJson; + } + if (supportedExtensions === ts.supportedTSExtensions) { + return ts.supportedTSExtensionsWithJson; + } + return supportedExtensions.concat([".json"]); + } + ts.getSuppoertedExtensionsWithJsonIfResolveJsonModule = getSuppoertedExtensionsWithJsonIfResolveJsonModule; + function isJSLike(scriptKind) { + return scriptKind === 1 || scriptKind === 2; + } + function hasJSFileExtension(fileName) { + return ts.some(ts.supportedJSExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + } + ts.hasJSFileExtension = hasJSFileExtension; + function hasJSOrJsonFileExtension(fileName) { + return ts.supportedJSAndJsonExtensions.some(function (ext) { return ts.fileExtensionIs(fileName, ext); }); + } + ts.hasJSOrJsonFileExtension = hasJSOrJsonFileExtension; + function hasTSFileExtension(fileName) { + return ts.some(ts.supportedTSExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + } + ts.hasTSFileExtension = hasTSFileExtension; + function isSupportedSourceFileName(fileName, compilerOptions, extraFileExtensions) { + if (!fileName) { + return false; + } + var supportedExtensions = getSupportedExtensions(compilerOptions, extraFileExtensions); + for (var _i = 0, _a = getSuppoertedExtensionsWithJsonIfResolveJsonModule(compilerOptions, supportedExtensions); _i < _a.length; _i++) { + var extension = _a[_i]; + if (ts.fileExtensionIs(fileName, extension)) { + return true; + } + } + return false; + } + ts.isSupportedSourceFileName = isSupportedSourceFileName; + function getExtensionPriority(path, supportedExtensions) { + for (var i = supportedExtensions.length - 1; i >= 0; i--) { + if (ts.fileExtensionIs(path, supportedExtensions[i])) { + return adjustExtensionPriority(i, supportedExtensions); + } + } + return 0; + } + ts.getExtensionPriority = getExtensionPriority; + function adjustExtensionPriority(extensionPriority, supportedExtensions) { + if (extensionPriority < 2) { + return 0; + } + else if (extensionPriority < supportedExtensions.length) { + return 2; + } + else { + return supportedExtensions.length; + } + } + ts.adjustExtensionPriority = adjustExtensionPriority; + function getNextLowestExtensionPriority(extensionPriority, supportedExtensions) { + if (extensionPriority < 2) { + return 2; + } + else { + return supportedExtensions.length; + } + } + ts.getNextLowestExtensionPriority = getNextLowestExtensionPriority; + var extensionsToRemove = [".d.ts", ".ts", ".js", ".tsx", ".jsx", ".json"]; + function removeFileExtension(path) { + for (var _i = 0, extensionsToRemove_1 = extensionsToRemove; _i < extensionsToRemove_1.length; _i++) { + var ext = extensionsToRemove_1[_i]; + var extensionless = tryRemoveExtension(path, ext); + if (extensionless !== undefined) { + return extensionless; + } + } + return path; + } + ts.removeFileExtension = removeFileExtension; + function tryRemoveExtension(path, extension) { + return ts.fileExtensionIs(path, extension) ? removeExtension(path, extension) : undefined; + } + ts.tryRemoveExtension = tryRemoveExtension; + function removeExtension(path, extension) { + return path.substring(0, path.length - extension.length); + } + ts.removeExtension = removeExtension; + function changeExtension(path, newExtension) { + return changeAnyExtension(path, newExtension, extensionsToRemove, false); + } + ts.changeExtension = changeExtension; + function changeAnyExtension(path, ext, extensions, ignoreCase) { + var pathext = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(path, extensions, ignoreCase) : getAnyExtensionFromPath(path); + return pathext ? path.slice(0, path.length - pathext.length) + (ts.startsWith(ext, ".") ? ext : "." + ext) : path; + } + ts.changeAnyExtension = changeAnyExtension; + var Debug; + (function (Debug) { + function showSymbol(symbol) { + var symbolFlags = ts.SymbolFlags; + return "{ flags: " + (symbolFlags ? showFlags(symbol.flags, symbolFlags) : symbol.flags) + "; declarations: " + ts.map(symbol.declarations, showSyntaxKind) + " }"; + } + Debug.showSymbol = showSymbol; + function showFlags(flags, flagsEnum) { + var out = []; + for (var pow = 0; pow <= 30; pow++) { + var n = 1 << pow; + if (flags & n) { + out.push(flagsEnum[n]); + } + } + return out.join("|"); + } + function showSyntaxKind(node) { + var syntaxKind = ts.SyntaxKind; + return syntaxKind ? syntaxKind[node.kind] : node.kind.toString(); + } + Debug.showSyntaxKind = showSyntaxKind; + })(Debug = ts.Debug || (ts.Debug = {})); + function tryParsePattern(pattern) { + Debug.assert(ts.hasZeroOrOneAsteriskCharacter(pattern)); + var indexOfStar = pattern.indexOf("*"); + return indexOfStar === -1 ? undefined : { + prefix: pattern.substr(0, indexOfStar), + suffix: pattern.substr(indexOfStar + 1) + }; + } + ts.tryParsePattern = tryParsePattern; + function positionIsSynthesized(pos) { + return !(pos >= 0); + } + ts.positionIsSynthesized = positionIsSynthesized; + function extensionIsTS(ext) { + return ext === ".ts" || ext === ".tsx" || ext === ".d.ts"; + } + ts.extensionIsTS = extensionIsTS; + function resolutionExtensionIsTSOrJson(ext) { + return extensionIsTS(ext) || ext === ".json"; + } + ts.resolutionExtensionIsTSOrJson = resolutionExtensionIsTSOrJson; + function extensionFromPath(path) { + var ext = tryGetExtensionFromPath(path); + return ext !== undefined ? ext : Debug.fail("File " + path + " has unknown extension."); + } + ts.extensionFromPath = extensionFromPath; + function isAnySupportedFileExtension(path) { + return tryGetExtensionFromPath(path) !== undefined; + } + ts.isAnySupportedFileExtension = isAnySupportedFileExtension; + function tryGetExtensionFromPath(path) { + return ts.find(extensionsToRemove, function (e) { return ts.fileExtensionIs(path, e); }); + } + ts.tryGetExtensionFromPath = tryGetExtensionFromPath; + function getAnyExtensionFromPathWorker(path, extensions, stringEqualityComparer) { + if (typeof extensions === "string") + extensions = [extensions]; + for (var _i = 0, extensions_2 = extensions; _i < extensions_2.length; _i++) { + var extension = extensions_2[_i]; + if (!ts.startsWith(extension, ".")) + extension = "." + extension; + if (path.length >= extension.length && path.charAt(path.length - extension.length) === ".") { + var pathExtension = path.slice(path.length - extension.length); + if (stringEqualityComparer(pathExtension, extension)) { + return pathExtension; + } + } + } + return ""; + } + function getAnyExtensionFromPath(path, extensions, ignoreCase) { + if (extensions) { + return getAnyExtensionFromPathWorker(path, extensions, ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive); + } + var baseFileName = getBaseFileName(path); + var extensionIndex = baseFileName.lastIndexOf("."); + if (extensionIndex >= 0) { + return baseFileName.substring(extensionIndex); + } + return ""; + } + ts.getAnyExtensionFromPath = getAnyExtensionFromPath; + function isCheckJsEnabledForFile(sourceFile, compilerOptions) { + return sourceFile.checkJsDirective ? sourceFile.checkJsDirective.enabled : compilerOptions.checkJs; + } + ts.isCheckJsEnabledForFile = isCheckJsEnabledForFile; + ts.emptyFileSystemEntries = { + files: ts.emptyArray, + directories: ts.emptyArray + }; + function matchPatternOrExact(patternStrings, candidate) { + var patterns = []; + for (var _i = 0, patternStrings_1 = patternStrings; _i < patternStrings_1.length; _i++) { + var patternString = patternStrings_1[_i]; + var pattern = tryParsePattern(patternString); + if (pattern) { + patterns.push(pattern); + } + else if (patternString === candidate) { + return patternString; + } + } + return ts.findBestPatternMatch(patterns, function (_) { return _; }, candidate); + } + ts.matchPatternOrExact = matchPatternOrExact; + function sliceAfter(arr, value) { + var index = arr.indexOf(value); + Debug.assert(index !== -1); + return arr.slice(index); + } + ts.sliceAfter = sliceAfter; + function minAndMax(arr, getValue) { + Debug.assert(arr.length !== 0); + var min = getValue(arr[0]); + var max = min; + for (var i = 1; i < arr.length; i++) { + var value = getValue(arr[i]); + if (value < min) { + min = value; + } + else if (value > max) { + max = value; + } + } + return { min: min, max: max }; + } + ts.minAndMax = minAndMax; + var NodeSet = (function () { + function NodeSet() { + this.map = ts.createMap(); + } + NodeSet.prototype.add = function (node) { + this.map.set(String(ts.getNodeId(node)), node); + }; + NodeSet.prototype.tryAdd = function (node) { + if (this.has(node)) + return false; + this.add(node); + return true; + }; + NodeSet.prototype.has = function (node) { + return this.map.has(String(ts.getNodeId(node))); + }; + NodeSet.prototype.forEach = function (cb) { + this.map.forEach(cb); + }; + NodeSet.prototype.some = function (pred) { + return ts.forEachEntry(this.map, pred) || false; + }; + return NodeSet; + }()); + ts.NodeSet = NodeSet; + var NodeMap = (function () { + function NodeMap() { + this.map = ts.createMap(); + } + NodeMap.prototype.get = function (node) { + var res = this.map.get(String(ts.getNodeId(node))); + return res && res.value; + }; + NodeMap.prototype.getOrUpdate = function (node, setValue) { + var res = this.get(node); + if (res) + return res; + var value = setValue(); + this.set(node, value); + return value; + }; + NodeMap.prototype.set = function (node, value) { + this.map.set(String(ts.getNodeId(node)), { node: node, value: value }); + }; + NodeMap.prototype.has = function (node) { + return this.map.has(String(ts.getNodeId(node))); + }; + NodeMap.prototype.forEach = function (cb) { + this.map.forEach(function (_a) { + var node = _a.node, value = _a.value; + return cb(value, node); + }); + }; + return NodeMap; + }()); + ts.NodeMap = NodeMap; + function rangeOfNode(node) { + return { pos: ts.getTokenPosOfNode(node), end: node.end }; + } + ts.rangeOfNode = rangeOfNode; + function rangeOfTypeParameters(typeParameters) { + return { pos: typeParameters.pos - 1, end: typeParameters.end + 1 }; + } + ts.rangeOfTypeParameters = rangeOfTypeParameters; + function skipTypeChecking(sourceFile, options) { + return options.skipLibCheck && sourceFile.isDeclarationFile || options.skipDefaultLibCheck && sourceFile.hasNoDefaultLib; + } + ts.skipTypeChecking = skipTypeChecking; + function isJsonEqual(a, b) { + return a === b || typeof a === "object" && a !== null && typeof b === "object" && b !== null && ts.equalOwnProperties(a, b, isJsonEqual); + } + ts.isJsonEqual = isJsonEqual; + function getOrUpdate(map, key, getDefault) { + var got = map.get(key); + if (got === undefined) { + var value = getDefault(); + map.set(key, value); + return value; + } + else { + return got; + } + } + ts.getOrUpdate = getOrUpdate; + function parsePseudoBigInt(stringValue) { + var log2Base; + switch (stringValue.charCodeAt(1)) { + case 98: + case 66: + log2Base = 1; + break; + case 111: + case 79: + log2Base = 3; + break; + case 120: + case 88: + log2Base = 4; + break; + default: + var nIndex = stringValue.length - 1; + var nonZeroStart = 0; + while (stringValue.charCodeAt(nonZeroStart) === 48) { + nonZeroStart++; + } + return stringValue.slice(nonZeroStart, nIndex) || "0"; + } + var startIndex = 2, endIndex = stringValue.length - 1; + var bitsNeeded = (endIndex - startIndex) * log2Base; + var segments = new Uint16Array((bitsNeeded >>> 4) + (bitsNeeded & 15 ? 1 : 0)); + for (var i = endIndex - 1, bitOffset = 0; i >= startIndex; i--, bitOffset += log2Base) { + var segment = bitOffset >>> 4; + var digitChar = stringValue.charCodeAt(i); + var digit = digitChar <= 57 + ? digitChar - 48 + : 10 + digitChar - + (digitChar <= 70 ? 65 : 97); + var shiftedDigit = digit << (bitOffset & 15); + segments[segment] |= shiftedDigit; + var residual = shiftedDigit >>> 16; + if (residual) + segments[segment + 1] |= residual; + } + var base10Value = ""; + var firstNonzeroSegment = segments.length - 1; + var segmentsRemaining = true; + while (segmentsRemaining) { + var mod10 = 0; + segmentsRemaining = false; + for (var segment = firstNonzeroSegment; segment >= 0; segment--) { + var newSegment = mod10 << 16 | segments[segment]; + var segmentValue = (newSegment / 10) | 0; + segments[segment] = segmentValue; + mod10 = newSegment - segmentValue * 10; + if (segmentValue && !segmentsRemaining) { + firstNonzeroSegment = segment; + segmentsRemaining = true; + } + } + base10Value = mod10 + base10Value; + } + return base10Value; + } + ts.parsePseudoBigInt = parsePseudoBigInt; + function pseudoBigIntToString(_a) { + var negative = _a.negative, base10Value = _a.base10Value; + return (negative && base10Value !== "0" ? "-" : "") + base10Value; + } + ts.pseudoBigIntToString = pseudoBigIntToString; +})(ts || (ts = {})); +var ts; +(function (ts) { + var NodeConstructor; + var TokenConstructor; + var IdentifierConstructor; + var SourceFileConstructor; + function createNode(kind, pos, end) { + if (kind === 279) { + return new (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor()))(kind, pos, end); + } + else if (kind === 72) { + return new (IdentifierConstructor || (IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor()))(kind, pos, end); + } + else if (!ts.isNodeKind(kind)) { + return new (TokenConstructor || (TokenConstructor = ts.objectAllocator.getTokenConstructor()))(kind, pos, end); + } + else { + return new (NodeConstructor || (NodeConstructor = ts.objectAllocator.getNodeConstructor()))(kind, pos, end); + } + } + ts.createNode = createNode; + function visitNode(cbNode, node) { + return node && cbNode(node); + } + function visitNodes(cbNode, cbNodes, nodes) { + if (nodes) { + if (cbNodes) { + return cbNodes(nodes); + } + for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) { + var node = nodes_1[_i]; + var result = cbNode(node); + if (result) { + return result; + } + } + } + } + function isJSDocLikeText(text, start) { + return text.charCodeAt(start + 1) === 42 && + text.charCodeAt(start + 2) === 42 && + text.charCodeAt(start + 3) !== 47; + } + ts.isJSDocLikeText = isJSDocLikeText; + function forEachChild(node, cbNode, cbNodes) { + if (!node || node.kind <= 147) { + return; + } + switch (node.kind) { + case 148: + return visitNode(cbNode, node.left) || + visitNode(cbNode, node.right); + case 150: + return visitNode(cbNode, node.name) || + visitNode(cbNode, node.constraint) || + visitNode(cbNode, node.default) || + visitNode(cbNode, node.expression); + case 276: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.exclamationToken) || + visitNode(cbNode, node.equalsToken) || + visitNode(cbNode, node.objectAssignmentInitializer); + case 277: + return visitNode(cbNode, node.expression); + case 151: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.dotDotDotToken) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.type) || + visitNode(cbNode, node.initializer); + case 154: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.exclamationToken) || + visitNode(cbNode, node.type) || + visitNode(cbNode, node.initializer); + case 153: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.type) || + visitNode(cbNode, node.initializer); + case 275: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.initializer); + case 237: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.exclamationToken) || + visitNode(cbNode, node.type) || + visitNode(cbNode, node.initializer); + case 186: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.dotDotDotToken) || + visitNode(cbNode, node.propertyName) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.initializer); + case 165: + case 166: + case 160: + case 161: + case 162: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type); + case 156: + case 155: + case 157: + case 158: + case 159: + case 196: + case 239: + case 197: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.asteriskToken) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.exclamationToken) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type) || + visitNode(cbNode, node.equalsGreaterThanToken) || + visitNode(cbNode, node.body); + case 164: + return visitNode(cbNode, node.typeName) || + visitNodes(cbNode, cbNodes, node.typeArguments); + case 163: + return visitNode(cbNode, node.parameterName) || + visitNode(cbNode, node.type); + case 167: + return visitNode(cbNode, node.exprName); + case 168: + return visitNodes(cbNode, cbNodes, node.members); + case 169: + return visitNode(cbNode, node.elementType); + case 170: + return visitNodes(cbNode, cbNodes, node.elementTypes); + case 173: + case 174: + return visitNodes(cbNode, cbNodes, node.types); + case 175: + return visitNode(cbNode, node.checkType) || + visitNode(cbNode, node.extendsType) || + visitNode(cbNode, node.trueType) || + visitNode(cbNode, node.falseType); + case 176: + return visitNode(cbNode, node.typeParameter); + case 183: + return visitNode(cbNode, node.argument) || + visitNode(cbNode, node.qualifier) || + visitNodes(cbNode, cbNodes, node.typeArguments); + case 177: + case 179: + return visitNode(cbNode, node.type); + case 180: + return visitNode(cbNode, node.objectType) || + visitNode(cbNode, node.indexType); + case 181: + return visitNode(cbNode, node.readonlyToken) || + visitNode(cbNode, node.typeParameter) || + visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.type); + case 182: + return visitNode(cbNode, node.literal); + case 184: + case 185: + return visitNodes(cbNode, cbNodes, node.elements); + case 187: + return visitNodes(cbNode, cbNodes, node.elements); + case 188: + return visitNodes(cbNode, cbNodes, node.properties); + case 189: + return visitNode(cbNode, node.expression) || + visitNode(cbNode, node.name); + case 190: + return visitNode(cbNode, node.expression) || + visitNode(cbNode, node.argumentExpression); + case 191: + case 192: + return visitNode(cbNode, node.expression) || + visitNodes(cbNode, cbNodes, node.typeArguments) || + visitNodes(cbNode, cbNodes, node.arguments); + case 193: + return visitNode(cbNode, node.tag) || + visitNodes(cbNode, cbNodes, node.typeArguments) || + visitNode(cbNode, node.template); + case 194: + return visitNode(cbNode, node.type) || + visitNode(cbNode, node.expression); + case 195: + return visitNode(cbNode, node.expression); + case 198: + return visitNode(cbNode, node.expression); + case 199: + return visitNode(cbNode, node.expression); + case 200: + return visitNode(cbNode, node.expression); + case 202: + return visitNode(cbNode, node.operand); + case 207: + return visitNode(cbNode, node.asteriskToken) || + visitNode(cbNode, node.expression); + case 201: + return visitNode(cbNode, node.expression); + case 203: + return visitNode(cbNode, node.operand); + case 204: + return visitNode(cbNode, node.left) || + visitNode(cbNode, node.operatorToken) || + visitNode(cbNode, node.right); + case 212: + return visitNode(cbNode, node.expression) || + visitNode(cbNode, node.type); + case 213: + return visitNode(cbNode, node.expression); + case 214: + return visitNode(cbNode, node.name); + case 205: + return visitNode(cbNode, node.condition) || + visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.whenTrue) || + visitNode(cbNode, node.colonToken) || + visitNode(cbNode, node.whenFalse); + case 208: + return visitNode(cbNode, node.expression); + case 218: + case 245: + return visitNodes(cbNode, cbNodes, node.statements); + case 279: + return visitNodes(cbNode, cbNodes, node.statements) || + visitNode(cbNode, node.endOfFileToken); + case 219: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.declarationList); + case 238: + return visitNodes(cbNode, cbNodes, node.declarations); + case 221: + return visitNode(cbNode, node.expression); + case 222: + return visitNode(cbNode, node.expression) || + visitNode(cbNode, node.thenStatement) || + visitNode(cbNode, node.elseStatement); + case 223: + return visitNode(cbNode, node.statement) || + visitNode(cbNode, node.expression); + case 224: + return visitNode(cbNode, node.expression) || + visitNode(cbNode, node.statement); + case 225: + return visitNode(cbNode, node.initializer) || + visitNode(cbNode, node.condition) || + visitNode(cbNode, node.incrementor) || + visitNode(cbNode, node.statement); + case 226: + return visitNode(cbNode, node.initializer) || + visitNode(cbNode, node.expression) || + visitNode(cbNode, node.statement); + case 227: + return visitNode(cbNode, node.awaitModifier) || + visitNode(cbNode, node.initializer) || + visitNode(cbNode, node.expression) || + visitNode(cbNode, node.statement); + case 228: + case 229: + return visitNode(cbNode, node.label); + case 230: + return visitNode(cbNode, node.expression); + case 231: + return visitNode(cbNode, node.expression) || + visitNode(cbNode, node.statement); + case 232: + return visitNode(cbNode, node.expression) || + visitNode(cbNode, node.caseBlock); + case 246: + return visitNodes(cbNode, cbNodes, node.clauses); + case 271: + return visitNode(cbNode, node.expression) || + visitNodes(cbNode, cbNodes, node.statements); + case 272: + return visitNodes(cbNode, cbNodes, node.statements); + case 233: + return visitNode(cbNode, node.label) || + visitNode(cbNode, node.statement); + case 234: + return visitNode(cbNode, node.expression); + case 235: + return visitNode(cbNode, node.tryBlock) || + visitNode(cbNode, node.catchClause) || + visitNode(cbNode, node.finallyBlock); + case 274: + return visitNode(cbNode, node.variableDeclaration) || + visitNode(cbNode, node.block); + case 152: + return visitNode(cbNode, node.expression); + case 240: + case 209: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.heritageClauses) || + visitNodes(cbNode, cbNodes, node.members); + case 241: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.heritageClauses) || + visitNodes(cbNode, cbNodes, node.members); + case 242: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNode(cbNode, node.type); + case 243: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNodes(cbNode, cbNodes, node.members); + case 278: + return visitNode(cbNode, node.name) || + visitNode(cbNode, node.initializer); + case 244: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.body); + case 248: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.moduleReference); + case 249: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.importClause) || + visitNode(cbNode, node.moduleSpecifier); + case 250: + return visitNode(cbNode, node.name) || + visitNode(cbNode, node.namedBindings); + case 247: + return visitNode(cbNode, node.name); + case 251: + return visitNode(cbNode, node.name); + case 252: + case 256: + return visitNodes(cbNode, cbNodes, node.elements); + case 255: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.exportClause) || + visitNode(cbNode, node.moduleSpecifier); + case 253: + case 257: + return visitNode(cbNode, node.propertyName) || + visitNode(cbNode, node.name); + case 254: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.expression); + case 206: + return visitNode(cbNode, node.head) || visitNodes(cbNode, cbNodes, node.templateSpans); + case 216: + return visitNode(cbNode, node.expression) || visitNode(cbNode, node.literal); + case 149: + return visitNode(cbNode, node.expression); + case 273: + return visitNodes(cbNode, cbNodes, node.types); + case 211: + return visitNode(cbNode, node.expression) || + visitNodes(cbNode, cbNodes, node.typeArguments); + case 259: + return visitNode(cbNode, node.expression); + case 258: + return visitNodes(cbNode, cbNodes, node.decorators); + case 309: + return visitNodes(cbNode, cbNodes, node.elements); + case 260: + return visitNode(cbNode, node.openingElement) || + visitNodes(cbNode, cbNodes, node.children) || + visitNode(cbNode, node.closingElement); + case 264: + return visitNode(cbNode, node.openingFragment) || + visitNodes(cbNode, cbNodes, node.children) || + visitNode(cbNode, node.closingFragment); + case 261: + case 262: + return visitNode(cbNode, node.tagName) || + visitNodes(cbNode, cbNodes, node.typeArguments) || + visitNode(cbNode, node.attributes); + case 268: + return visitNodes(cbNode, cbNodes, node.properties); + case 267: + return visitNode(cbNode, node.name) || + visitNode(cbNode, node.initializer); + case 269: + return visitNode(cbNode, node.expression); + case 270: + return visitNode(cbNode, node.dotDotDotToken) || + visitNode(cbNode, node.expression); + case 263: + return visitNode(cbNode, node.tagName); + case 171: + case 172: + case 283: + case 287: + case 286: + case 288: + case 290: + return visitNode(cbNode, node.type); + case 289: + return visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type); + case 291: + return visitNodes(cbNode, cbNodes, node.tags); + case 299: + case 305: + return visitNode(cbNode, node.tagName) || + (node.isNameFirst + ? visitNode(cbNode, node.name) || + visitNode(cbNode, node.typeExpression) + : visitNode(cbNode, node.typeExpression) || + visitNode(cbNode, node.name)); + case 295: + return visitNode(cbNode, node.tagName) || + visitNode(cbNode, node.class); + case 303: + return visitNode(cbNode, node.tagName) || + visitNode(cbNode, node.constraint) || + visitNodes(cbNode, cbNodes, node.typeParameters); + case 304: + return visitNode(cbNode, node.tagName) || + (node.typeExpression && + node.typeExpression.kind === 283 + ? visitNode(cbNode, node.typeExpression) || + visitNode(cbNode, node.fullName) + : visitNode(cbNode, node.fullName) || + visitNode(cbNode, node.typeExpression)); + case 297: + return visitNode(cbNode, node.tagName) || + visitNode(cbNode, node.fullName) || + visitNode(cbNode, node.typeExpression); + case 300: + case 302: + case 301: + case 298: + return visitNode(cbNode, node.tagName) || + visitNode(cbNode, node.typeExpression); + case 293: + return ts.forEach(node.typeParameters, cbNode) || + ts.forEach(node.parameters, cbNode) || + visitNode(cbNode, node.type); + case 292: + return ts.forEach(node.jsDocPropertyTags, cbNode); + case 294: + case 296: + return visitNode(cbNode, node.tagName); + case 308: + return visitNode(cbNode, node.expression); + } + } + ts.forEachChild = forEachChild; + function createSourceFile(fileName, sourceText, languageVersion, setParentNodes, scriptKind) { + if (setParentNodes === void 0) { setParentNodes = false; } + ts.performance.mark("beforeParse"); + var result; + if (languageVersion === 100) { + result = Parser.parseSourceFile(fileName, sourceText, languageVersion, undefined, setParentNodes, 6); + } + else { + result = Parser.parseSourceFile(fileName, sourceText, languageVersion, undefined, setParentNodes, scriptKind); + } + ts.performance.mark("afterParse"); + ts.performance.measure("Parse", "beforeParse", "afterParse"); + return result; + } + ts.createSourceFile = createSourceFile; + function parseIsolatedEntityName(text, languageVersion) { + return Parser.parseIsolatedEntityName(text, languageVersion); + } + ts.parseIsolatedEntityName = parseIsolatedEntityName; + function parseJsonText(fileName, sourceText) { + return Parser.parseJsonText(fileName, sourceText); + } + ts.parseJsonText = parseJsonText; + function isExternalModule(file) { + return file.externalModuleIndicator !== undefined; + } + ts.isExternalModule = isExternalModule; + function updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks) { + if (aggressiveChecks === void 0) { aggressiveChecks = false; } + var newSourceFile = IncrementalParser.updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks); + newSourceFile.flags |= (sourceFile.flags & 1572864); + return newSourceFile; + } + ts.updateSourceFile = updateSourceFile; + function parseIsolatedJSDocComment(content, start, length) { + var result = Parser.JSDocParser.parseIsolatedJSDocComment(content, start, length); + if (result && result.jsDoc) { + Parser.fixupParentReferences(result.jsDoc); + } + return result; + } + ts.parseIsolatedJSDocComment = parseIsolatedJSDocComment; + function parseJSDocTypeExpressionForTests(content, start, length) { + return Parser.JSDocParser.parseJSDocTypeExpressionForTests(content, start, length); + } + ts.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests; + var Parser; + (function (Parser) { + var scanner = ts.createScanner(6, true); + var disallowInAndDecoratorContext = 2048 | 8192; + var NodeConstructor; + var TokenConstructor; + var IdentifierConstructor; + var SourceFileConstructor; + var sourceFile; + var parseDiagnostics; + var syntaxCursor; + var currentToken; + var sourceText; + var nodeCount; + var identifiers; + var identifierCount; + var parsingContext; + var contextFlags; + var parseErrorBeforeNextFinishedNode = false; + function parseSourceFile(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes, scriptKind) { + if (setParentNodes === void 0) { setParentNodes = false; } + scriptKind = ts.ensureScriptKind(fileName, scriptKind); + if (scriptKind === 6) { + var result_1 = parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes); + ts.convertToObjectWorker(result_1, result_1.parseDiagnostics, false, undefined, undefined); + result_1.referencedFiles = ts.emptyArray; + result_1.typeReferenceDirectives = ts.emptyArray; + result_1.libReferenceDirectives = ts.emptyArray; + result_1.amdDependencies = ts.emptyArray; + result_1.hasNoDefaultLib = false; + result_1.pragmas = ts.emptyMap; + return result_1; + } + initializeState(sourceText, languageVersion, syntaxCursor, scriptKind); + var result = parseSourceFileWorker(fileName, languageVersion, setParentNodes, scriptKind); + clearState(); + return result; + } + Parser.parseSourceFile = parseSourceFile; + function parseIsolatedEntityName(content, languageVersion) { + initializeState(content, languageVersion, undefined, 1); + nextToken(); + var entityName = parseEntityName(true); + var isInvalid = token() === 1 && !parseDiagnostics.length; + clearState(); + return isInvalid ? entityName : undefined; + } + Parser.parseIsolatedEntityName = parseIsolatedEntityName; + function parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes) { + if (languageVersion === void 0) { languageVersion = 2; } + initializeState(sourceText, languageVersion, syntaxCursor, 6); + sourceFile = createSourceFile(fileName, 2, 6, false); + sourceFile.flags = contextFlags; + nextToken(); + var pos = getNodePos(); + if (token() === 1) { + sourceFile.statements = createNodeArray([], pos, pos); + sourceFile.endOfFileToken = parseTokenNode(); + } + else { + var statement = createNode(221); + switch (token()) { + case 22: + statement.expression = parseArrayLiteralExpression(); + break; + case 102: + case 87: + case 96: + statement.expression = parseTokenNode(); + break; + case 39: + if (lookAhead(function () { return nextToken() === 8 && nextToken() !== 57; })) { + statement.expression = parsePrefixUnaryExpression(); + } + else { + statement.expression = parseObjectLiteralExpression(); + } + break; + case 8: + case 10: + if (lookAhead(function () { return nextToken() !== 57; })) { + statement.expression = parseLiteralNode(); + break; + } + default: + statement.expression = parseObjectLiteralExpression(); + break; + } + finishNode(statement); + sourceFile.statements = createNodeArray([statement], pos); + sourceFile.endOfFileToken = parseExpectedToken(1, ts.Diagnostics.Unexpected_token); + } + if (setParentNodes) { + fixupParentReferences(sourceFile); + } + sourceFile.parseDiagnostics = parseDiagnostics; + var result = sourceFile; + clearState(); + return result; + } + Parser.parseJsonText = parseJsonText; + function getLanguageVariant(scriptKind) { + return scriptKind === 4 || scriptKind === 2 || scriptKind === 1 || scriptKind === 6 ? 1 : 0; + } + function initializeState(_sourceText, languageVersion, _syntaxCursor, scriptKind) { + NodeConstructor = ts.objectAllocator.getNodeConstructor(); + TokenConstructor = ts.objectAllocator.getTokenConstructor(); + IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor(); + SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor(); + sourceText = _sourceText; + syntaxCursor = _syntaxCursor; + parseDiagnostics = []; + parsingContext = 0; + identifiers = ts.createMap(); + identifierCount = 0; + nodeCount = 0; + switch (scriptKind) { + case 1: + case 2: + contextFlags = 65536; + break; + case 6: + contextFlags = 65536 | 16777216; + break; + default: + contextFlags = 0; + break; + } + parseErrorBeforeNextFinishedNode = false; + scanner.setText(sourceText); + scanner.setOnError(scanError); + scanner.setScriptTarget(languageVersion); + scanner.setLanguageVariant(getLanguageVariant(scriptKind)); + } + function clearState() { + scanner.setText(""); + scanner.setOnError(undefined); + parseDiagnostics = undefined; + sourceFile = undefined; + identifiers = undefined; + syntaxCursor = undefined; + sourceText = undefined; + } + function parseSourceFileWorker(fileName, languageVersion, setParentNodes, scriptKind) { + var isDeclarationFile = isDeclarationFileName(fileName); + if (isDeclarationFile) { + contextFlags |= 4194304; + } + sourceFile = createSourceFile(fileName, languageVersion, scriptKind, isDeclarationFile); + sourceFile.flags = contextFlags; + nextToken(); + processCommentPragmas(sourceFile, sourceText); + processPragmasIntoFields(sourceFile, reportPragmaDiagnostic); + sourceFile.statements = parseList(0, parseStatement); + ts.Debug.assert(token() === 1); + sourceFile.endOfFileToken = addJSDocComment(parseTokenNode()); + setExternalModuleIndicator(sourceFile); + sourceFile.nodeCount = nodeCount; + sourceFile.identifierCount = identifierCount; + sourceFile.identifiers = identifiers; + sourceFile.parseDiagnostics = parseDiagnostics; + if (setParentNodes) { + fixupParentReferences(sourceFile); + } + return sourceFile; + function reportPragmaDiagnostic(pos, end, diagnostic) { + parseDiagnostics.push(ts.createFileDiagnostic(sourceFile, pos, end, diagnostic)); + } + } + function addJSDocComment(node) { + ts.Debug.assert(!node.jsDoc); + var jsDoc = ts.mapDefined(ts.getJSDocCommentRanges(node, sourceFile.text), function (comment) { return JSDocParser.parseJSDocComment(node, comment.pos, comment.end - comment.pos); }); + if (jsDoc.length) + node.jsDoc = jsDoc; + return node; + } + function fixupParentReferences(rootNode) { + var parent = rootNode; + forEachChild(rootNode, visitNode); + return; + function visitNode(n) { + if (n.parent !== parent) { + n.parent = parent; + var saveParent = parent; + parent = n; + forEachChild(n, visitNode); + if (ts.hasJSDocNodes(n)) { + for (var _i = 0, _a = n.jsDoc; _i < _a.length; _i++) { + var jsDoc = _a[_i]; + jsDoc.parent = n; + parent = jsDoc; + forEachChild(jsDoc, visitNode); + } + } + parent = saveParent; + } + } + } + Parser.fixupParentReferences = fixupParentReferences; + function createSourceFile(fileName, languageVersion, scriptKind, isDeclarationFile) { + var sourceFile = new SourceFileConstructor(279, 0, sourceText.length); + nodeCount++; + sourceFile.text = sourceText; + sourceFile.bindDiagnostics = []; + sourceFile.bindSuggestionDiagnostics = undefined; + sourceFile.languageVersion = languageVersion; + sourceFile.fileName = ts.normalizePath(fileName); + sourceFile.languageVariant = getLanguageVariant(scriptKind); + sourceFile.isDeclarationFile = isDeclarationFile; + sourceFile.scriptKind = scriptKind; + return sourceFile; + } + function setContextFlag(val, flag) { + if (val) { + contextFlags |= flag; + } + else { + contextFlags &= ~flag; + } + } + function setDisallowInContext(val) { + setContextFlag(val, 2048); + } + function setYieldContext(val) { + setContextFlag(val, 4096); + } + function setDecoratorContext(val) { + setContextFlag(val, 8192); + } + function setAwaitContext(val) { + setContextFlag(val, 16384); + } + function doOutsideOfContext(context, func) { + var contextFlagsToClear = context & contextFlags; + if (contextFlagsToClear) { + setContextFlag(false, contextFlagsToClear); + var result = func(); + setContextFlag(true, contextFlagsToClear); + return result; + } + return func(); + } + function doInsideOfContext(context, func) { + var contextFlagsToSet = context & ~contextFlags; + if (contextFlagsToSet) { + setContextFlag(true, contextFlagsToSet); + var result = func(); + setContextFlag(false, contextFlagsToSet); + return result; + } + return func(); + } + function allowInAnd(func) { + return doOutsideOfContext(2048, func); + } + function disallowInAnd(func) { + return doInsideOfContext(2048, func); + } + function doInYieldContext(func) { + return doInsideOfContext(4096, func); + } + function doInDecoratorContext(func) { + return doInsideOfContext(8192, func); + } + function doInAwaitContext(func) { + return doInsideOfContext(16384, func); + } + function doOutsideOfAwaitContext(func) { + return doOutsideOfContext(16384, func); + } + function doInYieldAndAwaitContext(func) { + return doInsideOfContext(4096 | 16384, func); + } + function inContext(flags) { + return (contextFlags & flags) !== 0; + } + function inYieldContext() { + return inContext(4096); + } + function inDisallowInContext() { + return inContext(2048); + } + function inDecoratorContext() { + return inContext(8192); + } + function inAwaitContext() { + return inContext(16384); + } + function parseErrorAtCurrentToken(message, arg0) { + parseErrorAt(scanner.getTokenPos(), scanner.getTextPos(), message, arg0); + } + function parseErrorAtPosition(start, length, message, arg0) { + var lastError = ts.lastOrUndefined(parseDiagnostics); + if (!lastError || start !== lastError.start) { + parseDiagnostics.push(ts.createFileDiagnostic(sourceFile, start, length, message, arg0)); + } + parseErrorBeforeNextFinishedNode = true; + } + function parseErrorAt(start, end, message, arg0) { + parseErrorAtPosition(start, end - start, message, arg0); + } + function parseErrorAtRange(range, message, arg0) { + parseErrorAt(range.pos, range.end, message, arg0); + } + function scanError(message, length) { + parseErrorAtPosition(scanner.getTextPos(), length, message); + } + function getNodePos() { + return scanner.getStartPos(); + } + function token() { + return currentToken; + } + function nextToken() { + return currentToken = scanner.scan(); + } + function reScanGreaterToken() { + return currentToken = scanner.reScanGreaterToken(); + } + function reScanSlashToken() { + return currentToken = scanner.reScanSlashToken(); + } + function reScanTemplateToken() { + return currentToken = scanner.reScanTemplateToken(); + } + function scanJsxIdentifier() { + return currentToken = scanner.scanJsxIdentifier(); + } + function scanJsxText() { + return currentToken = scanner.scanJsxToken(); + } + function scanJsxAttributeValue() { + return currentToken = scanner.scanJsxAttributeValue(); + } + function speculationHelper(callback, isLookAhead) { + var saveToken = currentToken; + var saveParseDiagnosticsLength = parseDiagnostics.length; + var saveParseErrorBeforeNextFinishedNode = parseErrorBeforeNextFinishedNode; + var saveContextFlags = contextFlags; + var result = isLookAhead + ? scanner.lookAhead(callback) + : scanner.tryScan(callback); + ts.Debug.assert(saveContextFlags === contextFlags); + if (!result || isLookAhead) { + currentToken = saveToken; + parseDiagnostics.length = saveParseDiagnosticsLength; + parseErrorBeforeNextFinishedNode = saveParseErrorBeforeNextFinishedNode; + } + return result; + } + function lookAhead(callback) { + return speculationHelper(callback, true); + } + function tryParse(callback) { + return speculationHelper(callback, false); + } + function isIdentifier() { + if (token() === 72) { + return true; + } + if (token() === 117 && inYieldContext()) { + return false; + } + if (token() === 122 && inAwaitContext()) { + return false; + } + return token() > 108; + } + function parseExpected(kind, diagnosticMessage, shouldAdvance) { + if (shouldAdvance === void 0) { shouldAdvance = true; } + if (token() === kind) { + if (shouldAdvance) { + nextToken(); + } + return true; + } + if (diagnosticMessage) { + parseErrorAtCurrentToken(diagnosticMessage); + } + else { + parseErrorAtCurrentToken(ts.Diagnostics._0_expected, ts.tokenToString(kind)); + } + return false; + } + function parseOptional(t) { + if (token() === t) { + nextToken(); + return true; + } + return false; + } + function parseOptionalToken(t) { + if (token() === t) { + return parseTokenNode(); + } + return undefined; + } + function parseExpectedToken(t, diagnosticMessage, arg0) { + return parseOptionalToken(t) || + createMissingNode(t, false, diagnosticMessage || ts.Diagnostics._0_expected, arg0 || ts.tokenToString(t)); + } + function parseTokenNode() { + var node = createNode(token()); + nextToken(); + return finishNode(node); + } + function canParseSemicolon() { + if (token() === 26) { + return true; + } + return token() === 19 || token() === 1 || scanner.hasPrecedingLineBreak(); + } + function parseSemicolon() { + if (canParseSemicolon()) { + if (token() === 26) { + nextToken(); + } + return true; + } + else { + return parseExpected(26); + } + } + function createNode(kind, pos) { + nodeCount++; + var p = pos >= 0 ? pos : scanner.getStartPos(); + return ts.isNodeKind(kind) || kind === 0 ? new NodeConstructor(kind, p, p) : + kind === 72 ? new IdentifierConstructor(kind, p, p) : + new TokenConstructor(kind, p, p); + } + function createNodeWithJSDoc(kind, pos) { + var node = createNode(kind, pos); + if (scanner.getTokenFlags() & 2) { + addJSDocComment(node); + } + return node; + } + function createNodeArray(elements, pos, end) { + var length = elements.length; + var array = (length >= 1 && length <= 4 ? elements.slice() : elements); + array.pos = pos; + array.end = end === undefined ? scanner.getStartPos() : end; + return array; + } + function finishNode(node, end) { + node.end = end === undefined ? scanner.getStartPos() : end; + if (contextFlags) { + node.flags |= contextFlags; + } + if (parseErrorBeforeNextFinishedNode) { + parseErrorBeforeNextFinishedNode = false; + node.flags |= 32768; + } + return node; + } + function createMissingNode(kind, reportAtCurrentPosition, diagnosticMessage, arg0) { + if (reportAtCurrentPosition) { + parseErrorAtPosition(scanner.getStartPos(), 0, diagnosticMessage, arg0); + } + else if (diagnosticMessage) { + parseErrorAtCurrentToken(diagnosticMessage, arg0); + } + var result = createNode(kind); + if (kind === 72) { + result.escapedText = ""; + } + else if (ts.isLiteralKind(kind) || ts.isTemplateLiteralKind(kind)) { + result.text = ""; + } + return finishNode(result); + } + function internIdentifier(text) { + var identifier = identifiers.get(text); + if (identifier === undefined) { + identifiers.set(text, identifier = text); + } + return identifier; + } + function createIdentifier(isIdentifier, diagnosticMessage) { + identifierCount++; + if (isIdentifier) { + var node = createNode(72); + if (token() !== 72) { + node.originalKeywordKind = token(); + } + node.escapedText = ts.escapeLeadingUnderscores(internIdentifier(scanner.getTokenValue())); + nextToken(); + return finishNode(node); + } + var reportAtCurrentPosition = token() === 1; + return createMissingNode(72, reportAtCurrentPosition, diagnosticMessage || ts.Diagnostics.Identifier_expected); + } + function parseIdentifier(diagnosticMessage) { + return createIdentifier(isIdentifier(), diagnosticMessage); + } + function parseIdentifierName(diagnosticMessage) { + return createIdentifier(ts.tokenIsIdentifierOrKeyword(token()), diagnosticMessage); + } + function isLiteralPropertyName() { + return ts.tokenIsIdentifierOrKeyword(token()) || + token() === 10 || + token() === 8; + } + function parsePropertyNameWorker(allowComputedPropertyNames) { + if (token() === 10 || token() === 8) { + var node = parseLiteralNode(); + node.text = internIdentifier(node.text); + return node; + } + if (allowComputedPropertyNames && token() === 22) { + return parseComputedPropertyName(); + } + return parseIdentifierName(); + } + function parsePropertyName() { + return parsePropertyNameWorker(true); + } + function parseComputedPropertyName() { + var node = createNode(149); + parseExpected(22); + node.expression = allowInAnd(parseExpression); + parseExpected(23); + return finishNode(node); + } + function parseContextualModifier(t) { + return token() === t && tryParse(nextTokenCanFollowModifier); + } + function nextTokenIsOnSameLineAndCanFollowModifier() { + nextToken(); + if (scanner.hasPrecedingLineBreak()) { + return false; + } + return canFollowModifier(); + } + function nextTokenCanFollowModifier() { + switch (token()) { + case 77: + return nextToken() === 84; + case 85: + nextToken(); + if (token() === 80) { + return lookAhead(nextTokenCanFollowDefaultKeyword); + } + return token() !== 40 && token() !== 119 && token() !== 18 && canFollowModifier(); + case 80: + return nextTokenCanFollowDefaultKeyword(); + case 116: + case 126: + case 137: + nextToken(); + return canFollowModifier(); + default: + return nextTokenIsOnSameLineAndCanFollowModifier(); + } + } + function parseAnyContextualModifier() { + return ts.isModifierKind(token()) && tryParse(nextTokenCanFollowModifier); + } + function canFollowModifier() { + return token() === 22 + || token() === 18 + || token() === 40 + || token() === 25 + || isLiteralPropertyName(); + } + function nextTokenCanFollowDefaultKeyword() { + nextToken(); + return token() === 76 || token() === 90 || + token() === 110 || + (token() === 118 && lookAhead(nextTokenIsClassKeywordOnSameLine)) || + (token() === 121 && lookAhead(nextTokenIsFunctionKeywordOnSameLine)); + } + function isListElement(parsingContext, inErrorRecovery) { + var node = currentNode(parsingContext); + if (node) { + return true; + } + switch (parsingContext) { + case 0: + case 1: + case 3: + return !(token() === 26 && inErrorRecovery) && isStartOfStatement(); + case 2: + return token() === 74 || token() === 80; + case 4: + return lookAhead(isTypeMemberStart); + case 5: + return lookAhead(isClassMemberStart) || (token() === 26 && !inErrorRecovery); + case 6: + return token() === 22 || isLiteralPropertyName(); + case 12: + switch (token()) { + case 22: + case 40: + case 25: + case 24: + return true; + default: + return isLiteralPropertyName(); + } + case 18: + return isLiteralPropertyName(); + case 9: + return token() === 22 || token() === 25 || isLiteralPropertyName(); + case 7: + if (token() === 18) { + return lookAhead(isValidHeritageClauseObjectLiteral); + } + if (!inErrorRecovery) { + return isStartOfLeftHandSideExpression() && !isHeritageClauseExtendsOrImplementsKeyword(); + } + else { + return isIdentifier() && !isHeritageClauseExtendsOrImplementsKeyword(); + } + case 8: + return isIdentifierOrPattern(); + case 10: + return token() === 27 || token() === 25 || isIdentifierOrPattern(); + case 19: + return isIdentifier(); + case 15: + switch (token()) { + case 27: + case 24: + return true; + } + case 11: + return token() === 25 || isStartOfExpression(); + case 16: + return isStartOfParameter(false); + case 17: + return isStartOfParameter(true); + case 20: + case 21: + return token() === 27 || isStartOfType(); + case 22: + return isHeritageClause(); + case 23: + return ts.tokenIsIdentifierOrKeyword(token()); + case 13: + return ts.tokenIsIdentifierOrKeyword(token()) || token() === 18; + case 14: + return true; + } + return ts.Debug.fail("Non-exhaustive case in 'isListElement'."); + } + function isValidHeritageClauseObjectLiteral() { + ts.Debug.assert(token() === 18); + if (nextToken() === 19) { + var next = nextToken(); + return next === 27 || next === 18 || next === 86 || next === 109; + } + return true; + } + function nextTokenIsIdentifier() { + nextToken(); + return isIdentifier(); + } + function nextTokenIsIdentifierOrKeyword() { + nextToken(); + return ts.tokenIsIdentifierOrKeyword(token()); + } + function nextTokenIsIdentifierOrKeywordOrGreaterThan() { + nextToken(); + return ts.tokenIsIdentifierOrKeywordOrGreaterThan(token()); + } + function isHeritageClauseExtendsOrImplementsKeyword() { + if (token() === 109 || + token() === 86) { + return lookAhead(nextTokenIsStartOfExpression); + } + return false; + } + function nextTokenIsStartOfExpression() { + nextToken(); + return isStartOfExpression(); + } + function nextTokenIsStartOfType() { + nextToken(); + return isStartOfType(); + } + function isListTerminator(kind) { + if (token() === 1) { + return true; + } + switch (kind) { + case 1: + case 2: + case 4: + case 5: + case 6: + case 12: + case 9: + case 23: + return token() === 19; + case 3: + return token() === 19 || token() === 74 || token() === 80; + case 7: + return token() === 18 || token() === 86 || token() === 109; + case 8: + return isVariableDeclaratorListTerminator(); + case 19: + return token() === 30 || token() === 20 || token() === 18 || token() === 86 || token() === 109; + case 11: + return token() === 21 || token() === 26; + case 15: + case 21: + case 10: + return token() === 23; + case 17: + case 16: + case 18: + return token() === 21 || token() === 23; + case 20: + return token() !== 27; + case 22: + return token() === 18 || token() === 19; + case 13: + return token() === 30 || token() === 42; + case 14: + return token() === 28 && lookAhead(nextTokenIsSlash); + default: + return false; + } + } + function isVariableDeclaratorListTerminator() { + if (canParseSemicolon()) { + return true; + } + if (isInOrOfKeyword(token())) { + return true; + } + if (token() === 37) { + return true; + } + return false; + } + function isInSomeParsingContext() { + for (var kind = 0; kind < 24; kind++) { + if (parsingContext & (1 << kind)) { + if (isListElement(kind, true) || isListTerminator(kind)) { + return true; + } + } + } + return false; + } + function parseList(kind, parseElement) { + var saveParsingContext = parsingContext; + parsingContext |= 1 << kind; + var list = []; + var listPos = getNodePos(); + while (!isListTerminator(kind)) { + if (isListElement(kind, false)) { + var element = parseListElement(kind, parseElement); + list.push(element); + continue; + } + if (abortParsingListOrMoveToNextToken(kind)) { + break; + } + } + parsingContext = saveParsingContext; + return createNodeArray(list, listPos); + } + function parseListElement(parsingContext, parseElement) { + var node = currentNode(parsingContext); + if (node) { + return consumeNode(node); + } + return parseElement(); + } + function currentNode(parsingContext) { + if (parseErrorBeforeNextFinishedNode) { + return undefined; + } + if (!syntaxCursor) { + return undefined; + } + var node = syntaxCursor.currentNode(scanner.getStartPos()); + if (ts.nodeIsMissing(node)) { + return undefined; + } + if (node.intersectsChange) { + return undefined; + } + if (ts.containsParseError(node)) { + return undefined; + } + var nodeContextFlags = node.flags & 12679168; + if (nodeContextFlags !== contextFlags) { + return undefined; + } + if (!canReuseNode(node, parsingContext)) { + return undefined; + } + if (node.jsDocCache) { + node.jsDocCache = undefined; + } + return node; + } + function consumeNode(node) { + scanner.setTextPos(node.end); + nextToken(); + return node; + } + function canReuseNode(node, parsingContext) { + switch (parsingContext) { + case 5: + return isReusableClassMember(node); + case 2: + return isReusableSwitchClause(node); + case 0: + case 1: + case 3: + return isReusableStatement(node); + case 6: + return isReusableEnumMember(node); + case 4: + return isReusableTypeMember(node); + case 8: + return isReusableVariableDeclaration(node); + case 17: + case 16: + return isReusableParameter(node); + case 18: + return false; + case 22: + case 19: + case 21: + case 20: + case 11: + case 12: + case 7: + case 13: + case 14: + } + return false; + } + function isReusableClassMember(node) { + if (node) { + switch (node.kind) { + case 157: + case 162: + case 158: + case 159: + case 154: + case 217: + return true; + case 156: + var methodDeclaration = node; + var nameIsConstructor = methodDeclaration.name.kind === 72 && + methodDeclaration.name.originalKeywordKind === 124; + return !nameIsConstructor; + } + } + return false; + } + function isReusableSwitchClause(node) { + if (node) { + switch (node.kind) { + case 271: + case 272: + return true; + } + } + return false; + } + function isReusableStatement(node) { + if (node) { + switch (node.kind) { + case 239: + case 219: + case 218: + case 222: + case 221: + case 234: + case 230: + case 232: + case 229: + case 228: + case 226: + case 227: + case 225: + case 224: + case 231: + case 220: + case 235: + case 233: + case 223: + case 236: + case 249: + case 248: + case 255: + case 254: + case 244: + case 240: + case 241: + case 243: + case 242: + return true; + } + } + return false; + } + function isReusableEnumMember(node) { + return node.kind === 278; + } + function isReusableTypeMember(node) { + if (node) { + switch (node.kind) { + case 161: + case 155: + case 162: + case 153: + case 160: + return true; + } + } + return false; + } + function isReusableVariableDeclaration(node) { + if (node.kind !== 237) { + return false; + } + var variableDeclarator = node; + return variableDeclarator.initializer === undefined; + } + function isReusableParameter(node) { + if (node.kind !== 151) { + return false; + } + var parameter = node; + return parameter.initializer === undefined; + } + function abortParsingListOrMoveToNextToken(kind) { + parseErrorAtCurrentToken(parsingContextErrors(kind)); + if (isInSomeParsingContext()) { + return true; + } + nextToken(); + return false; + } + function parsingContextErrors(context) { + switch (context) { + case 0: return ts.Diagnostics.Declaration_or_statement_expected; + case 1: return ts.Diagnostics.Declaration_or_statement_expected; + case 2: return ts.Diagnostics.case_or_default_expected; + case 3: return ts.Diagnostics.Statement_expected; + case 18: + case 4: return ts.Diagnostics.Property_or_signature_expected; + case 5: return ts.Diagnostics.Unexpected_token_A_constructor_method_accessor_or_property_was_expected; + case 6: return ts.Diagnostics.Enum_member_expected; + case 7: return ts.Diagnostics.Expression_expected; + case 8: return ts.Diagnostics.Variable_declaration_expected; + case 9: return ts.Diagnostics.Property_destructuring_pattern_expected; + case 10: return ts.Diagnostics.Array_element_destructuring_pattern_expected; + case 11: return ts.Diagnostics.Argument_expression_expected; + case 12: return ts.Diagnostics.Property_assignment_expected; + case 15: return ts.Diagnostics.Expression_or_comma_expected; + case 17: return ts.Diagnostics.Parameter_declaration_expected; + case 16: return ts.Diagnostics.Parameter_declaration_expected; + case 19: return ts.Diagnostics.Type_parameter_declaration_expected; + case 20: return ts.Diagnostics.Type_argument_expected; + case 21: return ts.Diagnostics.Type_expected; + case 22: return ts.Diagnostics.Unexpected_token_expected; + case 23: return ts.Diagnostics.Identifier_expected; + case 13: return ts.Diagnostics.Identifier_expected; + case 14: return ts.Diagnostics.Identifier_expected; + default: return undefined; + } + } + function parseDelimitedList(kind, parseElement, considerSemicolonAsDelimiter) { + var saveParsingContext = parsingContext; + parsingContext |= 1 << kind; + var list = []; + var listPos = getNodePos(); + var commaStart = -1; + while (true) { + if (isListElement(kind, false)) { + var startPos = scanner.getStartPos(); + list.push(parseListElement(kind, parseElement)); + commaStart = scanner.getTokenPos(); + if (parseOptional(27)) { + continue; + } + commaStart = -1; + if (isListTerminator(kind)) { + break; + } + parseExpected(27); + if (considerSemicolonAsDelimiter && token() === 26 && !scanner.hasPrecedingLineBreak()) { + nextToken(); + } + if (startPos === scanner.getStartPos()) { + nextToken(); + } + continue; + } + if (isListTerminator(kind)) { + break; + } + if (abortParsingListOrMoveToNextToken(kind)) { + break; + } + } + parsingContext = saveParsingContext; + var result = createNodeArray(list, listPos); + if (commaStart >= 0) { + result.hasTrailingComma = true; + } + return result; + } + function createMissingList() { + var list = createNodeArray([], getNodePos()); + list.isMissingList = true; + return list; + } + function isMissingList(arr) { + return !!arr.isMissingList; + } + function parseBracketedList(kind, parseElement, open, close) { + if (parseExpected(open)) { + var result = parseDelimitedList(kind, parseElement); + parseExpected(close); + return result; + } + return createMissingList(); + } + function parseEntityName(allowReservedWords, diagnosticMessage) { + var entity = allowReservedWords ? parseIdentifierName(diagnosticMessage) : parseIdentifier(diagnosticMessage); + var dotPos = scanner.getStartPos(); + while (parseOptional(24)) { + if (token() === 28) { + entity.jsdocDotPos = dotPos; + break; + } + dotPos = scanner.getStartPos(); + entity = createQualifiedName(entity, parseRightSideOfDot(allowReservedWords)); + } + return entity; + } + function createQualifiedName(entity, name) { + var node = createNode(148, entity.pos); + node.left = entity; + node.right = name; + return finishNode(node); + } + function parseRightSideOfDot(allowIdentifierNames) { + if (scanner.hasPrecedingLineBreak() && ts.tokenIsIdentifierOrKeyword(token())) { + var matchesPattern = lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine); + if (matchesPattern) { + return createMissingNode(72, true, ts.Diagnostics.Identifier_expected); + } + } + return allowIdentifierNames ? parseIdentifierName() : parseIdentifier(); + } + function parseTemplateExpression() { + var template = createNode(206); + template.head = parseTemplateHead(); + ts.Debug.assert(template.head.kind === 15, "Template head has wrong token kind"); + var list = []; + var listPos = getNodePos(); + do { + list.push(parseTemplateSpan()); + } while (ts.last(list).literal.kind === 16); + template.templateSpans = createNodeArray(list, listPos); + return finishNode(template); + } + function parseTemplateSpan() { + var span = createNode(216); + span.expression = allowInAnd(parseExpression); + var literal; + if (token() === 19) { + reScanTemplateToken(); + literal = parseTemplateMiddleOrTemplateTail(); + } + else { + literal = parseExpectedToken(17, ts.Diagnostics._0_expected, ts.tokenToString(19)); + } + span.literal = literal; + return finishNode(span); + } + function parseLiteralNode() { + return parseLiteralLikeNode(token()); + } + function parseTemplateHead() { + var fragment = parseLiteralLikeNode(token()); + ts.Debug.assert(fragment.kind === 15, "Template head has wrong token kind"); + return fragment; + } + function parseTemplateMiddleOrTemplateTail() { + var fragment = parseLiteralLikeNode(token()); + ts.Debug.assert(fragment.kind === 16 || fragment.kind === 17, "Template fragment has wrong token kind"); + return fragment; + } + function parseLiteralLikeNode(kind) { + var node = createNode(kind); + node.text = scanner.getTokenValue(); + if (scanner.hasExtendedUnicodeEscape()) { + node.hasExtendedUnicodeEscape = true; + } + if (scanner.isUnterminated()) { + node.isUnterminated = true; + } + if (node.kind === 8) { + node.numericLiteralFlags = scanner.getTokenFlags() & 1008; + } + nextToken(); + finishNode(node); + return node; + } + function parseTypeReference() { + var node = createNode(164); + node.typeName = parseEntityName(true, ts.Diagnostics.Type_expected); + if (!scanner.hasPrecedingLineBreak() && token() === 28) { + node.typeArguments = parseBracketedList(20, parseType, 28, 30); + } + return finishNode(node); + } + function typeHasArrowFunctionBlockingParseError(node) { + switch (node.kind) { + case 164: + return ts.nodeIsMissing(node.typeName); + case 165: + case 166: { + var _a = node, parameters = _a.parameters, type = _a.type; + return isMissingList(parameters) || typeHasArrowFunctionBlockingParseError(type); + } + case 177: + return typeHasArrowFunctionBlockingParseError(node.type); + default: + return false; + } + } + function parseThisTypePredicate(lhs) { + nextToken(); + var node = createNode(163, lhs.pos); + node.parameterName = lhs; + node.type = parseType(); + return finishNode(node); + } + function parseThisTypeNode() { + var node = createNode(178); + nextToken(); + return finishNode(node); + } + function parseJSDocAllType(postFixEquals) { + var result = createNode(284); + if (postFixEquals) { + return createPostfixType(288, result); + } + else { + nextToken(); + } + return finishNode(result); + } + function parseJSDocNonNullableType() { + var result = createNode(287); + nextToken(); + result.type = parseNonArrayType(); + return finishNode(result); + } + function parseJSDocUnknownOrNullableType() { + var pos = scanner.getStartPos(); + nextToken(); + if (token() === 27 || + token() === 19 || + token() === 21 || + token() === 30 || + token() === 59 || + token() === 50) { + var result = createNode(285, pos); + return finishNode(result); + } + else { + var result = createNode(286, pos); + result.type = parseType(); + return finishNode(result); + } + } + function parseJSDocFunctionType() { + if (lookAhead(nextTokenIsOpenParen)) { + var result = createNodeWithJSDoc(289); + nextToken(); + fillSignature(57, 4 | 32, result); + return finishNode(result); + } + var node = createNode(164); + node.typeName = parseIdentifierName(); + return finishNode(node); + } + function parseJSDocParameter() { + var parameter = createNode(151); + if (token() === 100 || token() === 95) { + parameter.name = parseIdentifierName(); + parseExpected(57); + } + parameter.type = parseJSDocType(); + return finishNode(parameter); + } + function parseJSDocType() { + scanner.setInJSDocType(true); + var dotdotdot = parseOptionalToken(25); + var type = parseTypeOrTypePredicate(); + scanner.setInJSDocType(false); + if (dotdotdot) { + var variadic = createNode(290, dotdotdot.pos); + variadic.type = type; + type = finishNode(variadic); + } + if (token() === 59) { + return createPostfixType(288, type); + } + return type; + } + function parseTypeQuery() { + var node = createNode(167); + parseExpected(104); + node.exprName = parseEntityName(true); + return finishNode(node); + } + function parseTypeParameter() { + var node = createNode(150); + node.name = parseIdentifier(); + if (parseOptional(86)) { + if (isStartOfType() || !isStartOfExpression()) { + node.constraint = parseType(); + } + else { + node.expression = parseUnaryExpressionOrHigher(); + } + } + if (parseOptional(59)) { + node.default = parseType(); + } + return finishNode(node); + } + function parseTypeParameters() { + if (token() === 28) { + return parseBracketedList(19, parseTypeParameter, 28, 30); + } + } + function parseParameterType() { + if (parseOptional(57)) { + return parseType(); + } + return undefined; + } + function isStartOfParameter(isJSDocParameter) { + return token() === 25 || + isIdentifierOrPattern() || + ts.isModifierKind(token()) || + token() === 58 || + isStartOfType(!isJSDocParameter); + } + function parseParameter() { + var node = createNodeWithJSDoc(151); + if (token() === 100) { + node.name = createIdentifier(true); + node.type = parseParameterType(); + return finishNode(node); + } + node.decorators = parseDecorators(); + node.modifiers = parseModifiers(); + node.dotDotDotToken = parseOptionalToken(25); + node.name = parseIdentifierOrPattern(); + if (ts.getFullWidth(node.name) === 0 && !ts.hasModifiers(node) && ts.isModifierKind(token())) { + nextToken(); + } + node.questionToken = parseOptionalToken(56); + node.type = parseParameterType(); + node.initializer = parseInitializer(); + return finishNode(node); + } + function fillSignature(returnToken, flags, signature) { + if (!(flags & 32)) { + signature.typeParameters = parseTypeParameters(); + } + var parametersParsedSuccessfully = parseParameterList(signature, flags); + if (shouldParseReturnType(returnToken, !!(flags & 4))) { + signature.type = parseTypeOrTypePredicate(); + if (typeHasArrowFunctionBlockingParseError(signature.type)) + return false; + } + return parametersParsedSuccessfully; + } + function shouldParseReturnType(returnToken, isType) { + if (returnToken === 37) { + parseExpected(returnToken); + return true; + } + else if (parseOptional(57)) { + return true; + } + else if (isType && token() === 37) { + parseErrorAtCurrentToken(ts.Diagnostics._0_expected, ts.tokenToString(57)); + nextToken(); + return true; + } + return false; + } + function parseParameterList(signature, flags) { + if (!parseExpected(20)) { + signature.parameters = createMissingList(); + return false; + } + var savedYieldContext = inYieldContext(); + var savedAwaitContext = inAwaitContext(); + setYieldContext(!!(flags & 1)); + setAwaitContext(!!(flags & 2)); + signature.parameters = flags & 32 ? + parseDelimitedList(17, parseJSDocParameter) : + parseDelimitedList(16, parseParameter); + setYieldContext(savedYieldContext); + setAwaitContext(savedAwaitContext); + return parseExpected(21); + } + function parseTypeMemberSemicolon() { + if (parseOptional(27)) { + return; + } + parseSemicolon(); + } + function parseSignatureMember(kind) { + var node = createNodeWithJSDoc(kind); + if (kind === 161) { + parseExpected(95); + } + fillSignature(57, 4, node); + parseTypeMemberSemicolon(); + return finishNode(node); + } + function isIndexSignature() { + return token() === 22 && lookAhead(isUnambiguouslyIndexSignature); + } + function isUnambiguouslyIndexSignature() { + nextToken(); + if (token() === 25 || token() === 23) { + return true; + } + if (ts.isModifierKind(token())) { + nextToken(); + if (isIdentifier()) { + return true; + } + } + else if (!isIdentifier()) { + return false; + } + else { + nextToken(); + } + if (token() === 57 || token() === 27) { + return true; + } + if (token() !== 56) { + return false; + } + nextToken(); + return token() === 57 || token() === 27 || token() === 23; + } + function parseIndexSignatureDeclaration(node) { + node.kind = 162; + node.parameters = parseBracketedList(16, parseParameter, 22, 23); + node.type = parseTypeAnnotation(); + parseTypeMemberSemicolon(); + return finishNode(node); + } + function parsePropertyOrMethodSignature(node) { + node.name = parsePropertyName(); + node.questionToken = parseOptionalToken(56); + if (token() === 20 || token() === 28) { + node.kind = 155; + fillSignature(57, 4, node); + } + else { + node.kind = 153; + node.type = parseTypeAnnotation(); + if (token() === 59) { + node.initializer = parseInitializer(); + } + } + parseTypeMemberSemicolon(); + return finishNode(node); + } + function isTypeMemberStart() { + if (token() === 20 || token() === 28) { + return true; + } + var idToken = false; + while (ts.isModifierKind(token())) { + idToken = true; + nextToken(); + } + if (token() === 22) { + return true; + } + if (isLiteralPropertyName()) { + idToken = true; + nextToken(); + } + if (idToken) { + return token() === 20 || + token() === 28 || + token() === 56 || + token() === 57 || + token() === 27 || + canParseSemicolon(); + } + return false; + } + function parseTypeMember() { + if (token() === 20 || token() === 28) { + return parseSignatureMember(160); + } + if (token() === 95 && lookAhead(nextTokenIsOpenParenOrLessThan)) { + return parseSignatureMember(161); + } + var node = createNodeWithJSDoc(0); + node.modifiers = parseModifiers(); + if (isIndexSignature()) { + return parseIndexSignatureDeclaration(node); + } + return parsePropertyOrMethodSignature(node); + } + function nextTokenIsOpenParenOrLessThan() { + nextToken(); + return token() === 20 || token() === 28; + } + function nextTokenIsDot() { + return nextToken() === 24; + } + function nextTokenIsOpenParenOrLessThanOrDot() { + switch (nextToken()) { + case 20: + case 28: + case 24: + return true; + } + return false; + } + function parseTypeLiteral() { + var node = createNode(168); + node.members = parseObjectTypeMembers(); + return finishNode(node); + } + function parseObjectTypeMembers() { + var members; + if (parseExpected(18)) { + members = parseList(4, parseTypeMember); + parseExpected(19); + } + else { + members = createMissingList(); + } + return members; + } + function isStartOfMappedType() { + nextToken(); + if (token() === 38 || token() === 39) { + return nextToken() === 133; + } + if (token() === 133) { + nextToken(); + } + return token() === 22 && nextTokenIsIdentifier() && nextToken() === 93; + } + function parseMappedTypeParameter() { + var node = createNode(150); + node.name = parseIdentifier(); + parseExpected(93); + node.constraint = parseType(); + return finishNode(node); + } + function parseMappedType() { + var node = createNode(181); + parseExpected(18); + if (token() === 133 || token() === 38 || token() === 39) { + node.readonlyToken = parseTokenNode(); + if (node.readonlyToken.kind !== 133) { + parseExpectedToken(133); + } + } + parseExpected(22); + node.typeParameter = parseMappedTypeParameter(); + parseExpected(23); + if (token() === 56 || token() === 38 || token() === 39) { + node.questionToken = parseTokenNode(); + if (node.questionToken.kind !== 56) { + parseExpectedToken(56); + } + } + node.type = parseTypeAnnotation(); + parseSemicolon(); + parseExpected(19); + return finishNode(node); + } + function parseTupleElementType() { + var pos = getNodePos(); + if (parseOptional(25)) { + var node = createNode(172, pos); + node.type = parseType(); + return finishNode(node); + } + var type = parseType(); + if (!(contextFlags & 2097152) && type.kind === 286 && type.pos === type.type.pos) { + type.kind = 171; + } + return type; + } + function parseTupleType() { + var node = createNode(170); + node.elementTypes = parseBracketedList(21, parseTupleElementType, 22, 23); + return finishNode(node); + } + function parseParenthesizedType() { + var node = createNode(177); + parseExpected(20); + node.type = parseType(); + parseExpected(21); + return finishNode(node); + } + function parseFunctionOrConstructorType() { + var pos = getNodePos(); + var kind = parseOptional(95) ? 166 : 165; + var node = createNodeWithJSDoc(kind, pos); + fillSignature(37, 4, node); + return finishNode(node); + } + function parseKeywordAndNoDot() { + var node = parseTokenNode(); + return token() === 24 ? undefined : node; + } + function parseLiteralTypeNode(negative) { + var node = createNode(182); + var unaryMinusExpression; + if (negative) { + unaryMinusExpression = createNode(202); + unaryMinusExpression.operator = 39; + nextToken(); + } + var expression = token() === 102 || token() === 87 + ? parseTokenNode() + : parseLiteralLikeNode(token()); + if (negative) { + unaryMinusExpression.operand = expression; + finishNode(unaryMinusExpression); + expression = unaryMinusExpression; + } + node.literal = expression; + return finishNode(node); + } + function isStartOfTypeOfImportType() { + nextToken(); + return token() === 92; + } + function parseImportType() { + sourceFile.flags |= 524288; + var node = createNode(183); + if (parseOptional(104)) { + node.isTypeOf = true; + } + parseExpected(92); + parseExpected(20); + node.argument = parseType(); + parseExpected(21); + if (parseOptional(24)) { + node.qualifier = parseEntityName(true, ts.Diagnostics.Type_expected); + } + node.typeArguments = tryParseTypeArguments(); + return finishNode(node); + } + function nextTokenIsNumericOrBigIntLiteral() { + nextToken(); + return token() === 8 || token() === 9; + } + function parseNonArrayType() { + switch (token()) { + case 120: + case 143: + case 138: + case 135: + case 146: + case 139: + case 123: + case 141: + case 132: + case 136: + return tryParse(parseKeywordAndNoDot) || parseTypeReference(); + case 40: + return parseJSDocAllType(false); + case 62: + return parseJSDocAllType(true); + case 56: + return parseJSDocUnknownOrNullableType(); + case 90: + return parseJSDocFunctionType(); + case 52: + return parseJSDocNonNullableType(); + case 14: + case 10: + case 8: + case 9: + case 102: + case 87: + return parseLiteralTypeNode(); + case 39: + return lookAhead(nextTokenIsNumericOrBigIntLiteral) ? parseLiteralTypeNode(true) : parseTypeReference(); + case 106: + case 96: + return parseTokenNode(); + case 100: { + var thisKeyword = parseThisTypeNode(); + if (token() === 128 && !scanner.hasPrecedingLineBreak()) { + return parseThisTypePredicate(thisKeyword); + } + else { + return thisKeyword; + } + } + case 104: + return lookAhead(isStartOfTypeOfImportType) ? parseImportType() : parseTypeQuery(); + case 18: + return lookAhead(isStartOfMappedType) ? parseMappedType() : parseTypeLiteral(); + case 22: + return parseTupleType(); + case 20: + return parseParenthesizedType(); + case 92: + return parseImportType(); + default: + return parseTypeReference(); + } + } + function isStartOfType(inStartOfParameter) { + switch (token()) { + case 120: + case 143: + case 138: + case 135: + case 146: + case 123: + case 139: + case 142: + case 106: + case 141: + case 96: + case 100: + case 104: + case 132: + case 18: + case 22: + case 28: + case 50: + case 49: + case 95: + case 10: + case 8: + case 9: + case 102: + case 87: + case 136: + case 40: + case 56: + case 52: + case 25: + case 127: + case 92: + return true; + case 90: + return !inStartOfParameter; + case 39: + return !inStartOfParameter && lookAhead(nextTokenIsNumericOrBigIntLiteral); + case 20: + return !inStartOfParameter && lookAhead(isStartOfParenthesizedOrFunctionType); + default: + return isIdentifier(); + } + } + function isStartOfParenthesizedOrFunctionType() { + nextToken(); + return token() === 21 || isStartOfParameter(false) || isStartOfType(); + } + function parsePostfixTypeOrHigher() { + var type = parseNonArrayType(); + while (!scanner.hasPrecedingLineBreak()) { + switch (token()) { + case 52: + type = createPostfixType(287, type); + break; + case 56: + if (!(contextFlags & 2097152) && lookAhead(nextTokenIsStartOfType)) { + return type; + } + type = createPostfixType(286, type); + break; + case 22: + parseExpected(22); + if (isStartOfType()) { + var node = createNode(180, type.pos); + node.objectType = type; + node.indexType = parseType(); + parseExpected(23); + type = finishNode(node); + } + else { + var node = createNode(169, type.pos); + node.elementType = type; + parseExpected(23); + type = finishNode(node); + } + break; + default: + return type; + } + } + return type; + } + function createPostfixType(kind, type) { + nextToken(); + var postfix = createNode(kind, type.pos); + postfix.type = type; + return finishNode(postfix); + } + function parseTypeOperator(operator) { + var node = createNode(179); + parseExpected(operator); + node.operator = operator; + node.type = parseTypeOperatorOrHigher(); + return finishNode(node); + } + function parseInferType() { + var node = createNode(176); + parseExpected(127); + var typeParameter = createNode(150); + typeParameter.name = parseIdentifier(); + node.typeParameter = finishNode(typeParameter); + return finishNode(node); + } + function parseTypeOperatorOrHigher() { + var operator = token(); + switch (operator) { + case 129: + case 142: + return parseTypeOperator(operator); + case 127: + return parseInferType(); + } + return parsePostfixTypeOrHigher(); + } + function parseUnionOrIntersectionType(kind, parseConstituentType, operator) { + parseOptional(operator); + var type = parseConstituentType(); + if (token() === operator) { + var types = [type]; + while (parseOptional(operator)) { + types.push(parseConstituentType()); + } + var node = createNode(kind, type.pos); + node.types = createNodeArray(types, type.pos); + type = finishNode(node); + } + return type; + } + function parseIntersectionTypeOrHigher() { + return parseUnionOrIntersectionType(174, parseTypeOperatorOrHigher, 49); + } + function parseUnionTypeOrHigher() { + return parseUnionOrIntersectionType(173, parseIntersectionTypeOrHigher, 50); + } + function isStartOfFunctionType() { + if (token() === 28) { + return true; + } + return token() === 20 && lookAhead(isUnambiguouslyStartOfFunctionType); + } + function skipParameterStart() { + if (ts.isModifierKind(token())) { + parseModifiers(); + } + if (isIdentifier() || token() === 100) { + nextToken(); + return true; + } + if (token() === 22 || token() === 18) { + var previousErrorCount = parseDiagnostics.length; + parseIdentifierOrPattern(); + return previousErrorCount === parseDiagnostics.length; + } + return false; + } + function isUnambiguouslyStartOfFunctionType() { + nextToken(); + if (token() === 21 || token() === 25) { + return true; + } + if (skipParameterStart()) { + if (token() === 57 || token() === 27 || + token() === 56 || token() === 59) { + return true; + } + if (token() === 21) { + nextToken(); + if (token() === 37) { + return true; + } + } + } + return false; + } + function parseTypeOrTypePredicate() { + var typePredicateVariable = isIdentifier() && tryParse(parseTypePredicatePrefix); + var type = parseType(); + if (typePredicateVariable) { + var node = createNode(163, typePredicateVariable.pos); + node.parameterName = typePredicateVariable; + node.type = type; + return finishNode(node); + } + else { + return type; + } + } + function parseTypePredicatePrefix() { + var id = parseIdentifier(); + if (token() === 128 && !scanner.hasPrecedingLineBreak()) { + nextToken(); + return id; + } + } + function parseType() { + return doOutsideOfContext(20480, parseTypeWorker); + } + function parseTypeWorker(noConditionalTypes) { + if (isStartOfFunctionType() || token() === 95) { + return parseFunctionOrConstructorType(); + } + var type = parseUnionTypeOrHigher(); + if (!noConditionalTypes && !scanner.hasPrecedingLineBreak() && parseOptional(86)) { + var node = createNode(175, type.pos); + node.checkType = type; + node.extendsType = parseTypeWorker(true); + parseExpected(56); + node.trueType = parseTypeWorker(); + parseExpected(57); + node.falseType = parseTypeWorker(); + return finishNode(node); + } + return type; + } + function parseTypeAnnotation() { + return parseOptional(57) ? parseType() : undefined; + } + function isStartOfLeftHandSideExpression() { + switch (token()) { + case 100: + case 98: + case 96: + case 102: + case 87: + case 8: + case 9: + case 10: + case 14: + case 15: + case 20: + case 22: + case 18: + case 90: + case 76: + case 95: + case 42: + case 64: + case 72: + return true; + case 92: + return lookAhead(nextTokenIsOpenParenOrLessThanOrDot); + default: + return isIdentifier(); + } + } + function isStartOfExpression() { + if (isStartOfLeftHandSideExpression()) { + return true; + } + switch (token()) { + case 38: + case 39: + case 53: + case 52: + case 81: + case 104: + case 106: + case 44: + case 45: + case 28: + case 122: + case 117: + return true; + default: + if (isBinaryOperator()) { + return true; + } + return isIdentifier(); + } + } + function isStartOfExpressionStatement() { + return token() !== 18 && + token() !== 90 && + token() !== 76 && + token() !== 58 && + isStartOfExpression(); + } + function parseExpression() { + var saveDecoratorContext = inDecoratorContext(); + if (saveDecoratorContext) { + setDecoratorContext(false); + } + var expr = parseAssignmentExpressionOrHigher(); + var operatorToken; + while ((operatorToken = parseOptionalToken(27))) { + expr = makeBinaryExpression(expr, operatorToken, parseAssignmentExpressionOrHigher()); + } + if (saveDecoratorContext) { + setDecoratorContext(true); + } + return expr; + } + function parseInitializer() { + return parseOptional(59) ? parseAssignmentExpressionOrHigher() : undefined; + } + function parseAssignmentExpressionOrHigher() { + if (isYieldExpression()) { + return parseYieldExpression(); + } + var arrowExpression = tryParseParenthesizedArrowFunctionExpression() || tryParseAsyncSimpleArrowFunctionExpression(); + if (arrowExpression) { + return arrowExpression; + } + var expr = parseBinaryExpressionOrHigher(0); + if (expr.kind === 72 && token() === 37) { + return parseSimpleArrowFunctionExpression(expr); + } + if (ts.isLeftHandSideExpression(expr) && ts.isAssignmentOperator(reScanGreaterToken())) { + return makeBinaryExpression(expr, parseTokenNode(), parseAssignmentExpressionOrHigher()); + } + return parseConditionalExpressionRest(expr); + } + function isYieldExpression() { + if (token() === 117) { + if (inYieldContext()) { + return true; + } + return lookAhead(nextTokenIsIdentifierOrKeywordOrLiteralOnSameLine); + } + return false; + } + function nextTokenIsIdentifierOnSameLine() { + nextToken(); + return !scanner.hasPrecedingLineBreak() && isIdentifier(); + } + function parseYieldExpression() { + var node = createNode(207); + nextToken(); + if (!scanner.hasPrecedingLineBreak() && + (token() === 40 || isStartOfExpression())) { + node.asteriskToken = parseOptionalToken(40); + node.expression = parseAssignmentExpressionOrHigher(); + return finishNode(node); + } + else { + return finishNode(node); + } + } + function parseSimpleArrowFunctionExpression(identifier, asyncModifier) { + ts.Debug.assert(token() === 37, "parseSimpleArrowFunctionExpression should only have been called if we had a =>"); + var node; + if (asyncModifier) { + node = createNode(197, asyncModifier.pos); + node.modifiers = asyncModifier; + } + else { + node = createNode(197, identifier.pos); + } + var parameter = createNode(151, identifier.pos); + parameter.name = identifier; + finishNode(parameter); + node.parameters = createNodeArray([parameter], parameter.pos, parameter.end); + node.equalsGreaterThanToken = parseExpectedToken(37); + node.body = parseArrowFunctionExpressionBody(!!asyncModifier); + return addJSDocComment(finishNode(node)); + } + function tryParseParenthesizedArrowFunctionExpression() { + var triState = isParenthesizedArrowFunctionExpression(); + if (triState === 0) { + return undefined; + } + var arrowFunction = triState === 1 + ? parseParenthesizedArrowFunctionExpressionHead(true) + : tryParse(parsePossibleParenthesizedArrowFunctionExpressionHead); + if (!arrowFunction) { + return undefined; + } + var isAsync = ts.hasModifier(arrowFunction, 256); + var lastToken = token(); + arrowFunction.equalsGreaterThanToken = parseExpectedToken(37); + arrowFunction.body = (lastToken === 37 || lastToken === 18) + ? parseArrowFunctionExpressionBody(isAsync) + : parseIdentifier(); + return finishNode(arrowFunction); + } + function isParenthesizedArrowFunctionExpression() { + if (token() === 20 || token() === 28 || token() === 121) { + return lookAhead(isParenthesizedArrowFunctionExpressionWorker); + } + if (token() === 37) { + return 1; + } + return 0; + } + function isParenthesizedArrowFunctionExpressionWorker() { + if (token() === 121) { + nextToken(); + if (scanner.hasPrecedingLineBreak()) { + return 0; + } + if (token() !== 20 && token() !== 28) { + return 0; + } + } + var first = token(); + var second = nextToken(); + if (first === 20) { + if (second === 21) { + var third = nextToken(); + switch (third) { + case 37: + case 57: + case 18: + return 1; + default: + return 0; + } + } + if (second === 22 || second === 18) { + return 2; + } + if (second === 25) { + return 1; + } + if (ts.isModifierKind(second) && second !== 121 && lookAhead(nextTokenIsIdentifier)) { + return 1; + } + if (!isIdentifier() && second !== 100) { + return 0; + } + switch (nextToken()) { + case 57: + return 1; + case 56: + nextToken(); + if (token() === 57 || token() === 27 || token() === 59 || token() === 21) { + return 1; + } + return 0; + case 27: + case 59: + case 21: + return 2; + } + return 0; + } + else { + ts.Debug.assert(first === 28); + if (!isIdentifier()) { + return 0; + } + if (sourceFile.languageVariant === 1) { + var isArrowFunctionInJsx = lookAhead(function () { + var third = nextToken(); + if (third === 86) { + var fourth = nextToken(); + switch (fourth) { + case 59: + case 30: + return false; + default: + return true; + } + } + else if (third === 27) { + return true; + } + return false; + }); + if (isArrowFunctionInJsx) { + return 1; + } + return 0; + } + return 2; + } + } + function parsePossibleParenthesizedArrowFunctionExpressionHead() { + return parseParenthesizedArrowFunctionExpressionHead(false); + } + function tryParseAsyncSimpleArrowFunctionExpression() { + if (token() === 121) { + if (lookAhead(isUnParenthesizedAsyncArrowFunctionWorker) === 1) { + var asyncModifier = parseModifiersForArrowFunction(); + var expr = parseBinaryExpressionOrHigher(0); + return parseSimpleArrowFunctionExpression(expr, asyncModifier); + } + } + return undefined; + } + function isUnParenthesizedAsyncArrowFunctionWorker() { + if (token() === 121) { + nextToken(); + if (scanner.hasPrecedingLineBreak() || token() === 37) { + return 0; + } + var expr = parseBinaryExpressionOrHigher(0); + if (!scanner.hasPrecedingLineBreak() && expr.kind === 72 && token() === 37) { + return 1; + } + } + return 0; + } + function parseParenthesizedArrowFunctionExpressionHead(allowAmbiguity) { + var node = createNodeWithJSDoc(197); + node.modifiers = parseModifiersForArrowFunction(); + var isAsync = ts.hasModifier(node, 256) ? 2 : 0; + if (!fillSignature(57, isAsync, node) && !allowAmbiguity) { + return undefined; + } + if (!allowAmbiguity && token() !== 37 && token() !== 18) { + return undefined; + } + return node; + } + function parseArrowFunctionExpressionBody(isAsync) { + if (token() === 18) { + return parseFunctionBlock(isAsync ? 2 : 0); + } + if (token() !== 26 && + token() !== 90 && + token() !== 76 && + isStartOfStatement() && + !isStartOfExpressionStatement()) { + return parseFunctionBlock(16 | (isAsync ? 2 : 0)); + } + return isAsync + ? doInAwaitContext(parseAssignmentExpressionOrHigher) + : doOutsideOfAwaitContext(parseAssignmentExpressionOrHigher); + } + function parseConditionalExpressionRest(leftOperand) { + var questionToken = parseOptionalToken(56); + if (!questionToken) { + return leftOperand; + } + var node = createNode(205, leftOperand.pos); + node.condition = leftOperand; + node.questionToken = questionToken; + node.whenTrue = doOutsideOfContext(disallowInAndDecoratorContext, parseAssignmentExpressionOrHigher); + node.colonToken = parseExpectedToken(57); + node.whenFalse = ts.nodeIsPresent(node.colonToken) + ? parseAssignmentExpressionOrHigher() + : createMissingNode(72, false, ts.Diagnostics._0_expected, ts.tokenToString(57)); + return finishNode(node); + } + function parseBinaryExpressionOrHigher(precedence) { + var leftOperand = parseUnaryExpressionOrHigher(); + return parseBinaryExpressionRest(precedence, leftOperand); + } + function isInOrOfKeyword(t) { + return t === 93 || t === 147; + } + function parseBinaryExpressionRest(precedence, leftOperand) { + while (true) { + reScanGreaterToken(); + var newPrecedence = ts.getBinaryOperatorPrecedence(token()); + var consumeCurrentOperator = token() === 41 ? + newPrecedence >= precedence : + newPrecedence > precedence; + if (!consumeCurrentOperator) { + break; + } + if (token() === 93 && inDisallowInContext()) { + break; + } + if (token() === 119) { + if (scanner.hasPrecedingLineBreak()) { + break; + } + else { + nextToken(); + leftOperand = makeAsExpression(leftOperand, parseType()); + } + } + else { + leftOperand = makeBinaryExpression(leftOperand, parseTokenNode(), parseBinaryExpressionOrHigher(newPrecedence)); + } + } + return leftOperand; + } + function isBinaryOperator() { + if (inDisallowInContext() && token() === 93) { + return false; + } + return ts.getBinaryOperatorPrecedence(token()) > 0; + } + function makeBinaryExpression(left, operatorToken, right) { + var node = createNode(204, left.pos); + node.left = left; + node.operatorToken = operatorToken; + node.right = right; + return finishNode(node); + } + function makeAsExpression(left, right) { + var node = createNode(212, left.pos); + node.expression = left; + node.type = right; + return finishNode(node); + } + function parsePrefixUnaryExpression() { + var node = createNode(202); + node.operator = token(); + nextToken(); + node.operand = parseSimpleUnaryExpression(); + return finishNode(node); + } + function parseDeleteExpression() { + var node = createNode(198); + nextToken(); + node.expression = parseSimpleUnaryExpression(); + return finishNode(node); + } + function parseTypeOfExpression() { + var node = createNode(199); + nextToken(); + node.expression = parseSimpleUnaryExpression(); + return finishNode(node); + } + function parseVoidExpression() { + var node = createNode(200); + nextToken(); + node.expression = parseSimpleUnaryExpression(); + return finishNode(node); + } + function isAwaitExpression() { + if (token() === 122) { + if (inAwaitContext()) { + return true; + } + return lookAhead(nextTokenIsIdentifierOrKeywordOrLiteralOnSameLine); + } + return false; + } + function parseAwaitExpression() { + var node = createNode(201); + nextToken(); + node.expression = parseSimpleUnaryExpression(); + return finishNode(node); + } + function parseUnaryExpressionOrHigher() { + if (isUpdateExpression()) { + var updateExpression = parseUpdateExpression(); + return token() === 41 ? + parseBinaryExpressionRest(ts.getBinaryOperatorPrecedence(token()), updateExpression) : + updateExpression; + } + var unaryOperator = token(); + var simpleUnaryExpression = parseSimpleUnaryExpression(); + if (token() === 41) { + var pos = ts.skipTrivia(sourceText, simpleUnaryExpression.pos); + var end = simpleUnaryExpression.end; + if (simpleUnaryExpression.kind === 194) { + parseErrorAt(pos, end, ts.Diagnostics.A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses); + } + else { + parseErrorAt(pos, end, ts.Diagnostics.An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses, ts.tokenToString(unaryOperator)); + } + } + return simpleUnaryExpression; + } + function parseSimpleUnaryExpression() { + switch (token()) { + case 38: + case 39: + case 53: + case 52: + return parsePrefixUnaryExpression(); + case 81: + return parseDeleteExpression(); + case 104: + return parseTypeOfExpression(); + case 106: + return parseVoidExpression(); + case 28: + return parseTypeAssertion(); + case 122: + if (isAwaitExpression()) { + return parseAwaitExpression(); + } + default: + return parseUpdateExpression(); + } + } + function isUpdateExpression() { + switch (token()) { + case 38: + case 39: + case 53: + case 52: + case 81: + case 104: + case 106: + case 122: + return false; + case 28: + if (sourceFile.languageVariant !== 1) { + return false; + } + default: + return true; + } + } + function parseUpdateExpression() { + if (token() === 44 || token() === 45) { + var node = createNode(202); + node.operator = token(); + nextToken(); + node.operand = parseLeftHandSideExpressionOrHigher(); + return finishNode(node); + } + else if (sourceFile.languageVariant === 1 && token() === 28 && lookAhead(nextTokenIsIdentifierOrKeywordOrGreaterThan)) { + return parseJsxElementOrSelfClosingElementOrFragment(true); + } + var expression = parseLeftHandSideExpressionOrHigher(); + ts.Debug.assert(ts.isLeftHandSideExpression(expression)); + if ((token() === 44 || token() === 45) && !scanner.hasPrecedingLineBreak()) { + var node = createNode(203, expression.pos); + node.operand = expression; + node.operator = token(); + nextToken(); + return finishNode(node); + } + return expression; + } + function parseLeftHandSideExpressionOrHigher() { + var expression; + if (token() === 92) { + if (lookAhead(nextTokenIsOpenParenOrLessThan)) { + sourceFile.flags |= 524288; + expression = parseTokenNode(); + } + else if (lookAhead(nextTokenIsDot)) { + var fullStart = scanner.getStartPos(); + nextToken(); + nextToken(); + var node = createNode(214, fullStart); + node.keywordToken = 92; + node.name = parseIdentifierName(); + expression = finishNode(node); + sourceFile.flags |= 1048576; + } + else { + expression = parseMemberExpressionOrHigher(); + } + } + else { + expression = token() === 98 ? parseSuperExpression() : parseMemberExpressionOrHigher(); + } + return parseCallExpressionRest(expression); + } + function parseMemberExpressionOrHigher() { + var expression = parsePrimaryExpression(); + return parseMemberExpressionRest(expression); + } + function parseSuperExpression() { + var expression = parseTokenNode(); + if (token() === 20 || token() === 24 || token() === 22) { + return expression; + } + var node = createNode(189, expression.pos); + node.expression = expression; + parseExpectedToken(24, ts.Diagnostics.super_must_be_followed_by_an_argument_list_or_member_access); + node.name = parseRightSideOfDot(true); + return finishNode(node); + } + function parseJsxElementOrSelfClosingElementOrFragment(inExpressionContext) { + var opening = parseJsxOpeningOrSelfClosingElementOrOpeningFragment(inExpressionContext); + var result; + if (opening.kind === 262) { + var node = createNode(260, opening.pos); + node.openingElement = opening; + node.children = parseJsxChildren(node.openingElement); + node.closingElement = parseJsxClosingElement(inExpressionContext); + if (!tagNamesAreEquivalent(node.openingElement.tagName, node.closingElement.tagName)) { + parseErrorAtRange(node.closingElement, ts.Diagnostics.Expected_corresponding_JSX_closing_tag_for_0, ts.getTextOfNodeFromSourceText(sourceText, node.openingElement.tagName)); + } + result = finishNode(node); + } + else if (opening.kind === 265) { + var node = createNode(264, opening.pos); + node.openingFragment = opening; + node.children = parseJsxChildren(node.openingFragment); + node.closingFragment = parseJsxClosingFragment(inExpressionContext); + result = finishNode(node); + } + else { + ts.Debug.assert(opening.kind === 261); + result = opening; + } + if (inExpressionContext && token() === 28) { + var invalidElement = tryParse(function () { return parseJsxElementOrSelfClosingElementOrFragment(true); }); + if (invalidElement) { + parseErrorAtCurrentToken(ts.Diagnostics.JSX_expressions_must_have_one_parent_element); + var badNode = createNode(204, result.pos); + badNode.end = invalidElement.end; + badNode.left = result; + badNode.right = invalidElement; + badNode.operatorToken = createMissingNode(27, false, undefined); + badNode.operatorToken.pos = badNode.operatorToken.end = badNode.right.pos; + return badNode; + } + } + return result; + } + function parseJsxText() { + var node = createNode(11); + node.containsOnlyWhiteSpaces = currentToken === 12; + currentToken = scanner.scanJsxToken(); + return finishNode(node); + } + function parseJsxChild(openingTag, token) { + switch (token) { + case 1: + if (ts.isJsxOpeningFragment(openingTag)) { + parseErrorAtRange(openingTag, ts.Diagnostics.JSX_fragment_has_no_corresponding_closing_tag); + } + else { + parseErrorAtRange(openingTag.tagName, ts.Diagnostics.JSX_element_0_has_no_corresponding_closing_tag, ts.getTextOfNodeFromSourceText(sourceText, openingTag.tagName)); + } + return undefined; + case 29: + case 7: + return undefined; + case 11: + case 12: + return parseJsxText(); + case 18: + return parseJsxExpression(false); + case 28: + return parseJsxElementOrSelfClosingElementOrFragment(false); + default: + return ts.Debug.assertNever(token); + } + } + function parseJsxChildren(openingTag) { + var list = []; + var listPos = getNodePos(); + var saveParsingContext = parsingContext; + parsingContext |= 1 << 14; + while (true) { + var child = parseJsxChild(openingTag, currentToken = scanner.reScanJsxToken()); + if (!child) + break; + list.push(child); + } + parsingContext = saveParsingContext; + return createNodeArray(list, listPos); + } + function parseJsxAttributes() { + var jsxAttributes = createNode(268); + jsxAttributes.properties = parseList(13, parseJsxAttribute); + return finishNode(jsxAttributes); + } + function parseJsxOpeningOrSelfClosingElementOrOpeningFragment(inExpressionContext) { + var fullStart = scanner.getStartPos(); + parseExpected(28); + if (token() === 30) { + var node_1 = createNode(265, fullStart); + scanJsxText(); + return finishNode(node_1); + } + var tagName = parseJsxElementName(); + var typeArguments = tryParseTypeArguments(); + var attributes = parseJsxAttributes(); + var node; + if (token() === 30) { + node = createNode(262, fullStart); + scanJsxText(); + } + else { + parseExpected(42); + if (inExpressionContext) { + parseExpected(30); + } + else { + parseExpected(30, undefined, false); + scanJsxText(); + } + node = createNode(261, fullStart); + } + node.tagName = tagName; + node.typeArguments = typeArguments; + node.attributes = attributes; + return finishNode(node); + } + function parseJsxElementName() { + scanJsxIdentifier(); + var expression = token() === 100 ? + parseTokenNode() : parseIdentifierName(); + while (parseOptional(24)) { + var propertyAccess = createNode(189, expression.pos); + propertyAccess.expression = expression; + propertyAccess.name = parseRightSideOfDot(true); + expression = finishNode(propertyAccess); + } + return expression; + } + function parseJsxExpression(inExpressionContext) { + var node = createNode(270); + if (!parseExpected(18)) { + return undefined; + } + if (token() !== 19) { + node.dotDotDotToken = parseOptionalToken(25); + node.expression = parseAssignmentExpressionOrHigher(); + } + if (inExpressionContext) { + parseExpected(19); + } + else { + parseExpected(19, undefined, false); + scanJsxText(); + } + return finishNode(node); + } + function parseJsxAttribute() { + if (token() === 18) { + return parseJsxSpreadAttribute(); + } + scanJsxIdentifier(); + var node = createNode(267); + node.name = parseIdentifierName(); + if (token() === 59) { + switch (scanJsxAttributeValue()) { + case 10: + node.initializer = parseLiteralNode(); + break; + default: + node.initializer = parseJsxExpression(true); + break; + } + } + return finishNode(node); + } + function parseJsxSpreadAttribute() { + var node = createNode(269); + parseExpected(18); + parseExpected(25); + node.expression = parseExpression(); + parseExpected(19); + return finishNode(node); + } + function parseJsxClosingElement(inExpressionContext) { + var node = createNode(263); + parseExpected(29); + node.tagName = parseJsxElementName(); + if (inExpressionContext) { + parseExpected(30); + } + else { + parseExpected(30, undefined, false); + scanJsxText(); + } + return finishNode(node); + } + function parseJsxClosingFragment(inExpressionContext) { + var node = createNode(266); + parseExpected(29); + if (ts.tokenIsIdentifierOrKeyword(token())) { + parseErrorAtRange(parseJsxElementName(), ts.Diagnostics.Expected_corresponding_closing_tag_for_JSX_fragment); + } + if (inExpressionContext) { + parseExpected(30); + } + else { + parseExpected(30, undefined, false); + scanJsxText(); + } + return finishNode(node); + } + function parseTypeAssertion() { + var node = createNode(194); + parseExpected(28); + node.type = parseType(); + parseExpected(30); + node.expression = parseSimpleUnaryExpression(); + return finishNode(node); + } + function parseMemberExpressionRest(expression) { + while (true) { + var dotToken = parseOptionalToken(24); + if (dotToken) { + var propertyAccess = createNode(189, expression.pos); + propertyAccess.expression = expression; + propertyAccess.name = parseRightSideOfDot(true); + expression = finishNode(propertyAccess); + continue; + } + if (token() === 52 && !scanner.hasPrecedingLineBreak()) { + nextToken(); + var nonNullExpression = createNode(213, expression.pos); + nonNullExpression.expression = expression; + expression = finishNode(nonNullExpression); + continue; + } + if (!inDecoratorContext() && parseOptional(22)) { + var indexedAccess = createNode(190, expression.pos); + indexedAccess.expression = expression; + if (token() === 23) { + indexedAccess.argumentExpression = createMissingNode(72, true, ts.Diagnostics.An_element_access_expression_should_take_an_argument); + } + else { + var argument = allowInAnd(parseExpression); + if (ts.isStringOrNumericLiteralLike(argument)) { + argument.text = internIdentifier(argument.text); + } + indexedAccess.argumentExpression = argument; + } + parseExpected(23); + expression = finishNode(indexedAccess); + continue; + } + if (isTemplateStartOfTaggedTemplate()) { + expression = parseTaggedTemplateRest(expression, undefined); + continue; + } + return expression; + } + } + function isTemplateStartOfTaggedTemplate() { + return token() === 14 || token() === 15; + } + function parseTaggedTemplateRest(tag, typeArguments) { + var tagExpression = createNode(193, tag.pos); + tagExpression.tag = tag; + tagExpression.typeArguments = typeArguments; + tagExpression.template = token() === 14 + ? parseLiteralNode() + : parseTemplateExpression(); + return finishNode(tagExpression); + } + function parseCallExpressionRest(expression) { + while (true) { + expression = parseMemberExpressionRest(expression); + if (token() === 28) { + var typeArguments = tryParse(parseTypeArgumentsInExpression); + if (!typeArguments) { + return expression; + } + if (isTemplateStartOfTaggedTemplate()) { + expression = parseTaggedTemplateRest(expression, typeArguments); + continue; + } + var callExpr = createNode(191, expression.pos); + callExpr.expression = expression; + callExpr.typeArguments = typeArguments; + callExpr.arguments = parseArgumentList(); + expression = finishNode(callExpr); + continue; + } + else if (token() === 20) { + var callExpr = createNode(191, expression.pos); + callExpr.expression = expression; + callExpr.arguments = parseArgumentList(); + expression = finishNode(callExpr); + continue; + } + return expression; + } + } + function parseArgumentList() { + parseExpected(20); + var result = parseDelimitedList(11, parseArgumentExpression); + parseExpected(21); + return result; + } + function parseTypeArgumentsInExpression() { + if (!parseOptional(28)) { + return undefined; + } + var typeArguments = parseDelimitedList(20, parseType); + if (!parseExpected(30)) { + return undefined; + } + return typeArguments && canFollowTypeArgumentsInExpression() + ? typeArguments + : undefined; + } + function canFollowTypeArgumentsInExpression() { + switch (token()) { + case 20: + case 14: + case 15: + case 24: + case 21: + case 23: + case 57: + case 26: + case 56: + case 33: + case 35: + case 34: + case 36: + case 54: + case 55: + case 51: + case 49: + case 50: + case 19: + case 1: + return true; + case 27: + case 18: + default: + return false; + } + } + function parsePrimaryExpression() { + switch (token()) { + case 8: + case 9: + case 10: + case 14: + return parseLiteralNode(); + case 100: + case 98: + case 96: + case 102: + case 87: + return parseTokenNode(); + case 20: + return parseParenthesizedExpression(); + case 22: + return parseArrayLiteralExpression(); + case 18: + return parseObjectLiteralExpression(); + case 121: + if (!lookAhead(nextTokenIsFunctionKeywordOnSameLine)) { + break; + } + return parseFunctionExpression(); + case 76: + return parseClassExpression(); + case 90: + return parseFunctionExpression(); + case 95: + return parseNewExpressionOrNewDotTarget(); + case 42: + case 64: + if (reScanSlashToken() === 13) { + return parseLiteralNode(); + } + break; + case 15: + return parseTemplateExpression(); + } + return parseIdentifier(ts.Diagnostics.Expression_expected); + } + function parseParenthesizedExpression() { + var node = createNodeWithJSDoc(195); + parseExpected(20); + node.expression = allowInAnd(parseExpression); + parseExpected(21); + return finishNode(node); + } + function parseSpreadElement() { + var node = createNode(208); + parseExpected(25); + node.expression = parseAssignmentExpressionOrHigher(); + return finishNode(node); + } + function parseArgumentOrArrayLiteralElement() { + return token() === 25 ? parseSpreadElement() : + token() === 27 ? createNode(210) : + parseAssignmentExpressionOrHigher(); + } + function parseArgumentExpression() { + return doOutsideOfContext(disallowInAndDecoratorContext, parseArgumentOrArrayLiteralElement); + } + function parseArrayLiteralExpression() { + var node = createNode(187); + parseExpected(22); + if (scanner.hasPrecedingLineBreak()) { + node.multiLine = true; + } + node.elements = parseDelimitedList(15, parseArgumentOrArrayLiteralElement); + parseExpected(23); + return finishNode(node); + } + function parseObjectLiteralElement() { + var node = createNodeWithJSDoc(0); + if (parseOptionalToken(25)) { + node.kind = 277; + node.expression = parseAssignmentExpressionOrHigher(); + return finishNode(node); + } + node.decorators = parseDecorators(); + node.modifiers = parseModifiers(); + if (parseContextualModifier(126)) { + return parseAccessorDeclaration(node, 158); + } + if (parseContextualModifier(137)) { + return parseAccessorDeclaration(node, 159); + } + var asteriskToken = parseOptionalToken(40); + var tokenIsIdentifier = isIdentifier(); + node.name = parsePropertyName(); + node.questionToken = parseOptionalToken(56); + node.exclamationToken = parseOptionalToken(52); + if (asteriskToken || token() === 20 || token() === 28) { + return parseMethodDeclaration(node, asteriskToken); + } + var isShorthandPropertyAssignment = tokenIsIdentifier && (token() !== 57); + if (isShorthandPropertyAssignment) { + node.kind = 276; + var equalsToken = parseOptionalToken(59); + if (equalsToken) { + node.equalsToken = equalsToken; + node.objectAssignmentInitializer = allowInAnd(parseAssignmentExpressionOrHigher); + } + } + else { + node.kind = 275; + parseExpected(57); + node.initializer = allowInAnd(parseAssignmentExpressionOrHigher); + } + return finishNode(node); + } + function parseObjectLiteralExpression() { + var node = createNode(188); + parseExpected(18); + if (scanner.hasPrecedingLineBreak()) { + node.multiLine = true; + } + node.properties = parseDelimitedList(12, parseObjectLiteralElement, true); + parseExpected(19); + return finishNode(node); + } + function parseFunctionExpression() { + var saveDecoratorContext = inDecoratorContext(); + if (saveDecoratorContext) { + setDecoratorContext(false); + } + var node = createNodeWithJSDoc(196); + node.modifiers = parseModifiers(); + parseExpected(90); + node.asteriskToken = parseOptionalToken(40); + var isGenerator = node.asteriskToken ? 1 : 0; + var isAsync = ts.hasModifier(node, 256) ? 2 : 0; + node.name = + isGenerator && isAsync ? doInYieldAndAwaitContext(parseOptionalIdentifier) : + isGenerator ? doInYieldContext(parseOptionalIdentifier) : + isAsync ? doInAwaitContext(parseOptionalIdentifier) : + parseOptionalIdentifier(); + fillSignature(57, isGenerator | isAsync, node); + node.body = parseFunctionBlock(isGenerator | isAsync); + if (saveDecoratorContext) { + setDecoratorContext(true); + } + return finishNode(node); + } + function parseOptionalIdentifier() { + return isIdentifier() ? parseIdentifier() : undefined; + } + function parseNewExpressionOrNewDotTarget() { + var fullStart = scanner.getStartPos(); + parseExpected(95); + if (parseOptional(24)) { + var node_2 = createNode(214, fullStart); + node_2.keywordToken = 95; + node_2.name = parseIdentifierName(); + return finishNode(node_2); + } + var expression = parsePrimaryExpression(); + var typeArguments; + while (true) { + expression = parseMemberExpressionRest(expression); + typeArguments = tryParse(parseTypeArgumentsInExpression); + if (isTemplateStartOfTaggedTemplate()) { + ts.Debug.assert(!!typeArguments, "Expected a type argument list; all plain tagged template starts should be consumed in 'parseMemberExpressionRest'"); + expression = parseTaggedTemplateRest(expression, typeArguments); + typeArguments = undefined; + } + break; + } + var node = createNode(192, fullStart); + node.expression = expression; + node.typeArguments = typeArguments; + if (node.typeArguments || token() === 20) { + node.arguments = parseArgumentList(); + } + return finishNode(node); + } + function parseBlock(ignoreMissingOpenBrace, diagnosticMessage) { + var node = createNode(218); + if (parseExpected(18, diagnosticMessage) || ignoreMissingOpenBrace) { + if (scanner.hasPrecedingLineBreak()) { + node.multiLine = true; + } + node.statements = parseList(1, parseStatement); + parseExpected(19); + } + else { + node.statements = createMissingList(); + } + return finishNode(node); + } + function parseFunctionBlock(flags, diagnosticMessage) { + var savedYieldContext = inYieldContext(); + setYieldContext(!!(flags & 1)); + var savedAwaitContext = inAwaitContext(); + setAwaitContext(!!(flags & 2)); + var saveDecoratorContext = inDecoratorContext(); + if (saveDecoratorContext) { + setDecoratorContext(false); + } + var block = parseBlock(!!(flags & 16), diagnosticMessage); + if (saveDecoratorContext) { + setDecoratorContext(true); + } + setYieldContext(savedYieldContext); + setAwaitContext(savedAwaitContext); + return block; + } + function parseEmptyStatement() { + var node = createNode(220); + parseExpected(26); + return finishNode(node); + } + function parseIfStatement() { + var node = createNode(222); + parseExpected(91); + parseExpected(20); + node.expression = allowInAnd(parseExpression); + parseExpected(21); + node.thenStatement = parseStatement(); + node.elseStatement = parseOptional(83) ? parseStatement() : undefined; + return finishNode(node); + } + function parseDoStatement() { + var node = createNode(223); + parseExpected(82); + node.statement = parseStatement(); + parseExpected(107); + parseExpected(20); + node.expression = allowInAnd(parseExpression); + parseExpected(21); + parseOptional(26); + return finishNode(node); + } + function parseWhileStatement() { + var node = createNode(224); + parseExpected(107); + parseExpected(20); + node.expression = allowInAnd(parseExpression); + parseExpected(21); + node.statement = parseStatement(); + return finishNode(node); + } + function parseForOrForInOrForOfStatement() { + var pos = getNodePos(); + parseExpected(89); + var awaitToken = parseOptionalToken(122); + parseExpected(20); + var initializer; + if (token() !== 26) { + if (token() === 105 || token() === 111 || token() === 77) { + initializer = parseVariableDeclarationList(true); + } + else { + initializer = disallowInAnd(parseExpression); + } + } + var forOrForInOrForOfStatement; + if (awaitToken ? parseExpected(147) : parseOptional(147)) { + var forOfStatement = createNode(227, pos); + forOfStatement.awaitModifier = awaitToken; + forOfStatement.initializer = initializer; + forOfStatement.expression = allowInAnd(parseAssignmentExpressionOrHigher); + parseExpected(21); + forOrForInOrForOfStatement = forOfStatement; + } + else if (parseOptional(93)) { + var forInStatement = createNode(226, pos); + forInStatement.initializer = initializer; + forInStatement.expression = allowInAnd(parseExpression); + parseExpected(21); + forOrForInOrForOfStatement = forInStatement; + } + else { + var forStatement = createNode(225, pos); + forStatement.initializer = initializer; + parseExpected(26); + if (token() !== 26 && token() !== 21) { + forStatement.condition = allowInAnd(parseExpression); + } + parseExpected(26); + if (token() !== 21) { + forStatement.incrementor = allowInAnd(parseExpression); + } + parseExpected(21); + forOrForInOrForOfStatement = forStatement; + } + forOrForInOrForOfStatement.statement = parseStatement(); + return finishNode(forOrForInOrForOfStatement); + } + function parseBreakOrContinueStatement(kind) { + var node = createNode(kind); + parseExpected(kind === 229 ? 73 : 78); + if (!canParseSemicolon()) { + node.label = parseIdentifier(); + } + parseSemicolon(); + return finishNode(node); + } + function parseReturnStatement() { + var node = createNode(230); + parseExpected(97); + if (!canParseSemicolon()) { + node.expression = allowInAnd(parseExpression); + } + parseSemicolon(); + return finishNode(node); + } + function parseWithStatement() { + var node = createNode(231); + parseExpected(108); + parseExpected(20); + node.expression = allowInAnd(parseExpression); + parseExpected(21); + node.statement = doInsideOfContext(8388608, parseStatement); + return finishNode(node); + } + function parseCaseClause() { + var node = createNode(271); + parseExpected(74); + node.expression = allowInAnd(parseExpression); + parseExpected(57); + node.statements = parseList(3, parseStatement); + return finishNode(node); + } + function parseDefaultClause() { + var node = createNode(272); + parseExpected(80); + parseExpected(57); + node.statements = parseList(3, parseStatement); + return finishNode(node); + } + function parseCaseOrDefaultClause() { + return token() === 74 ? parseCaseClause() : parseDefaultClause(); + } + function parseSwitchStatement() { + var node = createNode(232); + parseExpected(99); + parseExpected(20); + node.expression = allowInAnd(parseExpression); + parseExpected(21); + var caseBlock = createNode(246); + parseExpected(18); + caseBlock.clauses = parseList(2, parseCaseOrDefaultClause); + parseExpected(19); + node.caseBlock = finishNode(caseBlock); + return finishNode(node); + } + function parseThrowStatement() { + var node = createNode(234); + parseExpected(101); + node.expression = scanner.hasPrecedingLineBreak() ? undefined : allowInAnd(parseExpression); + parseSemicolon(); + return finishNode(node); + } + function parseTryStatement() { + var node = createNode(235); + parseExpected(103); + node.tryBlock = parseBlock(false); + node.catchClause = token() === 75 ? parseCatchClause() : undefined; + if (!node.catchClause || token() === 88) { + parseExpected(88); + node.finallyBlock = parseBlock(false); + } + return finishNode(node); + } + function parseCatchClause() { + var result = createNode(274); + parseExpected(75); + if (parseOptional(20)) { + result.variableDeclaration = parseVariableDeclaration(); + parseExpected(21); + } + else { + result.variableDeclaration = undefined; + } + result.block = parseBlock(false); + return finishNode(result); + } + function parseDebuggerStatement() { + var node = createNode(236); + parseExpected(79); + parseSemicolon(); + return finishNode(node); + } + function parseExpressionOrLabeledStatement() { + var node = createNodeWithJSDoc(0); + var expression = allowInAnd(parseExpression); + if (expression.kind === 72 && parseOptional(57)) { + node.kind = 233; + node.label = expression; + node.statement = parseStatement(); + } + else { + node.kind = 221; + node.expression = expression; + parseSemicolon(); + } + return finishNode(node); + } + function nextTokenIsIdentifierOrKeywordOnSameLine() { + nextToken(); + return ts.tokenIsIdentifierOrKeyword(token()) && !scanner.hasPrecedingLineBreak(); + } + function nextTokenIsClassKeywordOnSameLine() { + nextToken(); + return token() === 76 && !scanner.hasPrecedingLineBreak(); + } + function nextTokenIsFunctionKeywordOnSameLine() { + nextToken(); + return token() === 90 && !scanner.hasPrecedingLineBreak(); + } + function nextTokenIsIdentifierOrKeywordOrLiteralOnSameLine() { + nextToken(); + return (ts.tokenIsIdentifierOrKeyword(token()) || token() === 8 || token() === 9 || token() === 10) && !scanner.hasPrecedingLineBreak(); + } + function isDeclaration() { + while (true) { + switch (token()) { + case 105: + case 111: + case 77: + case 90: + case 76: + case 84: + return true; + case 110: + case 140: + return nextTokenIsIdentifierOnSameLine(); + case 130: + case 131: + return nextTokenIsIdentifierOrStringLiteralOnSameLine(); + case 118: + case 121: + case 125: + case 113: + case 114: + case 115: + case 133: + nextToken(); + if (scanner.hasPrecedingLineBreak()) { + return false; + } + continue; + case 145: + nextToken(); + return token() === 18 || token() === 72 || token() === 85; + case 92: + nextToken(); + return token() === 10 || token() === 40 || + token() === 18 || ts.tokenIsIdentifierOrKeyword(token()); + case 85: + nextToken(); + if (token() === 59 || token() === 40 || + token() === 18 || token() === 80 || + token() === 119) { + return true; + } + continue; + case 116: + nextToken(); + continue; + default: + return false; + } + } + } + function isStartOfDeclaration() { + return lookAhead(isDeclaration); + } + function isStartOfStatement() { + switch (token()) { + case 58: + case 26: + case 18: + case 105: + case 111: + case 90: + case 76: + case 84: + case 91: + case 82: + case 107: + case 89: + case 78: + case 73: + case 97: + case 108: + case 99: + case 101: + case 103: + case 79: + case 75: + case 88: + return true; + case 92: + return isStartOfDeclaration() || lookAhead(nextTokenIsOpenParenOrLessThanOrDot); + case 77: + case 85: + return isStartOfDeclaration(); + case 121: + case 125: + case 110: + case 130: + case 131: + case 140: + case 145: + return true; + case 115: + case 113: + case 114: + case 116: + case 133: + return isStartOfDeclaration() || !lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine); + default: + return isStartOfExpression(); + } + } + function nextTokenIsIdentifierOrStartOfDestructuring() { + nextToken(); + return isIdentifier() || token() === 18 || token() === 22; + } + function isLetDeclaration() { + return lookAhead(nextTokenIsIdentifierOrStartOfDestructuring); + } + function parseStatement() { + switch (token()) { + case 26: + return parseEmptyStatement(); + case 18: + return parseBlock(false); + case 105: + return parseVariableStatement(createNodeWithJSDoc(237)); + case 111: + if (isLetDeclaration()) { + return parseVariableStatement(createNodeWithJSDoc(237)); + } + break; + case 90: + return parseFunctionDeclaration(createNodeWithJSDoc(239)); + case 76: + return parseClassDeclaration(createNodeWithJSDoc(240)); + case 91: + return parseIfStatement(); + case 82: + return parseDoStatement(); + case 107: + return parseWhileStatement(); + case 89: + return parseForOrForInOrForOfStatement(); + case 78: + return parseBreakOrContinueStatement(228); + case 73: + return parseBreakOrContinueStatement(229); + case 97: + return parseReturnStatement(); + case 108: + return parseWithStatement(); + case 99: + return parseSwitchStatement(); + case 101: + return parseThrowStatement(); + case 103: + case 75: + case 88: + return parseTryStatement(); + case 79: + return parseDebuggerStatement(); + case 58: + return parseDeclaration(); + case 121: + case 110: + case 140: + case 130: + case 131: + case 125: + case 77: + case 84: + case 85: + case 92: + case 113: + case 114: + case 115: + case 118: + case 116: + case 133: + case 145: + if (isStartOfDeclaration()) { + return parseDeclaration(); + } + break; + } + return parseExpressionOrLabeledStatement(); + } + function isDeclareModifier(modifier) { + return modifier.kind === 125; + } + function parseDeclaration() { + var node = createNodeWithJSDoc(0); + node.decorators = parseDecorators(); + node.modifiers = parseModifiers(); + if (ts.some(node.modifiers, isDeclareModifier)) { + for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) { + var m = _a[_i]; + m.flags |= 4194304; + } + return doInsideOfContext(4194304, function () { return parseDeclarationWorker(node); }); + } + else { + return parseDeclarationWorker(node); + } + } + function parseDeclarationWorker(node) { + switch (token()) { + case 105: + case 111: + case 77: + return parseVariableStatement(node); + case 90: + return parseFunctionDeclaration(node); + case 76: + return parseClassDeclaration(node); + case 110: + return parseInterfaceDeclaration(node); + case 140: + return parseTypeAliasDeclaration(node); + case 84: + return parseEnumDeclaration(node); + case 145: + case 130: + case 131: + return parseModuleDeclaration(node); + case 92: + return parseImportDeclarationOrImportEqualsDeclaration(node); + case 85: + nextToken(); + switch (token()) { + case 80: + case 59: + return parseExportAssignment(node); + case 119: + return parseNamespaceExportDeclaration(node); + default: + return parseExportDeclaration(node); + } + default: + if (node.decorators || node.modifiers) { + var missing = createMissingNode(258, true, ts.Diagnostics.Declaration_expected); + missing.pos = node.pos; + missing.decorators = node.decorators; + missing.modifiers = node.modifiers; + return finishNode(missing); + } + return undefined; + } + } + function nextTokenIsIdentifierOrStringLiteralOnSameLine() { + nextToken(); + return !scanner.hasPrecedingLineBreak() && (isIdentifier() || token() === 10); + } + function parseFunctionBlockOrSemicolon(flags, diagnosticMessage) { + if (token() !== 18 && canParseSemicolon()) { + parseSemicolon(); + return; + } + return parseFunctionBlock(flags, diagnosticMessage); + } + function parseArrayBindingElement() { + if (token() === 27) { + return createNode(210); + } + var node = createNode(186); + node.dotDotDotToken = parseOptionalToken(25); + node.name = parseIdentifierOrPattern(); + node.initializer = parseInitializer(); + return finishNode(node); + } + function parseObjectBindingElement() { + var node = createNode(186); + node.dotDotDotToken = parseOptionalToken(25); + var tokenIsIdentifier = isIdentifier(); + var propertyName = parsePropertyName(); + if (tokenIsIdentifier && token() !== 57) { + node.name = propertyName; + } + else { + parseExpected(57); + node.propertyName = propertyName; + node.name = parseIdentifierOrPattern(); + } + node.initializer = parseInitializer(); + return finishNode(node); + } + function parseObjectBindingPattern() { + var node = createNode(184); + parseExpected(18); + node.elements = parseDelimitedList(9, parseObjectBindingElement); + parseExpected(19); + return finishNode(node); + } + function parseArrayBindingPattern() { + var node = createNode(185); + parseExpected(22); + node.elements = parseDelimitedList(10, parseArrayBindingElement); + parseExpected(23); + return finishNode(node); + } + function isIdentifierOrPattern() { + return token() === 18 || token() === 22 || isIdentifier(); + } + function parseIdentifierOrPattern() { + if (token() === 22) { + return parseArrayBindingPattern(); + } + if (token() === 18) { + return parseObjectBindingPattern(); + } + return parseIdentifier(); + } + function parseVariableDeclarationAllowExclamation() { + return parseVariableDeclaration(true); + } + function parseVariableDeclaration(allowExclamation) { + var node = createNode(237); + node.name = parseIdentifierOrPattern(); + if (allowExclamation && node.name.kind === 72 && + token() === 52 && !scanner.hasPrecedingLineBreak()) { + node.exclamationToken = parseTokenNode(); + } + node.type = parseTypeAnnotation(); + if (!isInOrOfKeyword(token())) { + node.initializer = parseInitializer(); + } + return finishNode(node); + } + function parseVariableDeclarationList(inForStatementInitializer) { + var node = createNode(238); + switch (token()) { + case 105: + break; + case 111: + node.flags |= 1; + break; + case 77: + node.flags |= 2; + break; + default: + ts.Debug.fail(); + } + nextToken(); + if (token() === 147 && lookAhead(canFollowContextualOfKeyword)) { + node.declarations = createMissingList(); + } + else { + var savedDisallowIn = inDisallowInContext(); + setDisallowInContext(inForStatementInitializer); + node.declarations = parseDelimitedList(8, inForStatementInitializer ? parseVariableDeclaration : parseVariableDeclarationAllowExclamation); + setDisallowInContext(savedDisallowIn); + } + return finishNode(node); + } + function canFollowContextualOfKeyword() { + return nextTokenIsIdentifier() && nextToken() === 21; + } + function parseVariableStatement(node) { + node.kind = 219; + node.declarationList = parseVariableDeclarationList(false); + parseSemicolon(); + return finishNode(node); + } + function parseFunctionDeclaration(node) { + node.kind = 239; + parseExpected(90); + node.asteriskToken = parseOptionalToken(40); + node.name = ts.hasModifier(node, 512) ? parseOptionalIdentifier() : parseIdentifier(); + var isGenerator = node.asteriskToken ? 1 : 0; + var isAsync = ts.hasModifier(node, 256) ? 2 : 0; + fillSignature(57, isGenerator | isAsync, node); + node.body = parseFunctionBlockOrSemicolon(isGenerator | isAsync, ts.Diagnostics.or_expected); + return finishNode(node); + } + function parseConstructorDeclaration(node) { + node.kind = 157; + parseExpected(124); + fillSignature(57, 0, node); + node.body = parseFunctionBlockOrSemicolon(0, ts.Diagnostics.or_expected); + return finishNode(node); + } + function parseMethodDeclaration(node, asteriskToken, diagnosticMessage) { + node.kind = 156; + node.asteriskToken = asteriskToken; + var isGenerator = asteriskToken ? 1 : 0; + var isAsync = ts.hasModifier(node, 256) ? 2 : 0; + fillSignature(57, isGenerator | isAsync, node); + node.body = parseFunctionBlockOrSemicolon(isGenerator | isAsync, diagnosticMessage); + return finishNode(node); + } + function parsePropertyDeclaration(node) { + node.kind = 154; + if (!node.questionToken && token() === 52 && !scanner.hasPrecedingLineBreak()) { + node.exclamationToken = parseTokenNode(); + } + node.type = parseTypeAnnotation(); + node.initializer = ts.hasModifier(node, 32) + ? allowInAnd(parseInitializer) + : doOutsideOfContext(4096 | 2048, parseInitializer); + parseSemicolon(); + return finishNode(node); + } + function parsePropertyOrMethodDeclaration(node) { + var asteriskToken = parseOptionalToken(40); + node.name = parsePropertyName(); + node.questionToken = parseOptionalToken(56); + if (asteriskToken || token() === 20 || token() === 28) { + return parseMethodDeclaration(node, asteriskToken, ts.Diagnostics.or_expected); + } + return parsePropertyDeclaration(node); + } + function parseAccessorDeclaration(node, kind) { + node.kind = kind; + node.name = parsePropertyName(); + fillSignature(57, 0, node); + node.body = parseFunctionBlockOrSemicolon(0); + return finishNode(node); + } + function isClassMemberStart() { + var idToken; + if (token() === 58) { + return true; + } + while (ts.isModifierKind(token())) { + idToken = token(); + if (ts.isClassMemberModifier(idToken)) { + return true; + } + nextToken(); + } + if (token() === 40) { + return true; + } + if (isLiteralPropertyName()) { + idToken = token(); + nextToken(); + } + if (token() === 22) { + return true; + } + if (idToken !== undefined) { + if (!ts.isKeyword(idToken) || idToken === 137 || idToken === 126) { + return true; + } + switch (token()) { + case 20: + case 28: + case 52: + case 57: + case 59: + case 56: + return true; + default: + return canParseSemicolon(); + } + } + return false; + } + function parseDecorators() { + var list; + var listPos = getNodePos(); + while (true) { + var decoratorStart = getNodePos(); + if (!parseOptional(58)) { + break; + } + var decorator = createNode(152, decoratorStart); + decorator.expression = doInDecoratorContext(parseLeftHandSideExpressionOrHigher); + finishNode(decorator); + (list || (list = [])).push(decorator); + } + return list && createNodeArray(list, listPos); + } + function parseModifiers(permitInvalidConstAsModifier) { + var list; + var listPos = getNodePos(); + while (true) { + var modifierStart = scanner.getStartPos(); + var modifierKind = token(); + if (token() === 77 && permitInvalidConstAsModifier) { + if (!tryParse(nextTokenIsOnSameLineAndCanFollowModifier)) { + break; + } + } + else { + if (!parseAnyContextualModifier()) { + break; + } + } + var modifier = finishNode(createNode(modifierKind, modifierStart)); + (list || (list = [])).push(modifier); + } + return list && createNodeArray(list, listPos); + } + function parseModifiersForArrowFunction() { + var modifiers; + if (token() === 121) { + var modifierStart = scanner.getStartPos(); + var modifierKind = token(); + nextToken(); + var modifier = finishNode(createNode(modifierKind, modifierStart)); + modifiers = createNodeArray([modifier], modifierStart); + } + return modifiers; + } + function parseClassElement() { + if (token() === 26) { + var result = createNode(217); + nextToken(); + return finishNode(result); + } + var node = createNodeWithJSDoc(0); + node.decorators = parseDecorators(); + node.modifiers = parseModifiers(true); + if (parseContextualModifier(126)) { + return parseAccessorDeclaration(node, 158); + } + if (parseContextualModifier(137)) { + return parseAccessorDeclaration(node, 159); + } + if (token() === 124) { + return parseConstructorDeclaration(node); + } + if (isIndexSignature()) { + return parseIndexSignatureDeclaration(node); + } + if (ts.tokenIsIdentifierOrKeyword(token()) || + token() === 10 || + token() === 8 || + token() === 40 || + token() === 22) { + return parsePropertyOrMethodDeclaration(node); + } + if (node.decorators || node.modifiers) { + node.name = createMissingNode(72, true, ts.Diagnostics.Declaration_expected); + return parsePropertyDeclaration(node); + } + return ts.Debug.fail("Should not have attempted to parse class member declaration."); + } + function parseClassExpression() { + return parseClassDeclarationOrExpression(createNodeWithJSDoc(0), 209); + } + function parseClassDeclaration(node) { + return parseClassDeclarationOrExpression(node, 240); + } + function parseClassDeclarationOrExpression(node, kind) { + node.kind = kind; + parseExpected(76); + node.name = parseNameOfClassDeclarationOrExpression(); + node.typeParameters = parseTypeParameters(); + node.heritageClauses = parseHeritageClauses(); + if (parseExpected(18)) { + node.members = parseClassMembers(); + parseExpected(19); + } + else { + node.members = createMissingList(); + } + return finishNode(node); + } + function parseNameOfClassDeclarationOrExpression() { + return isIdentifier() && !isImplementsClause() + ? parseIdentifier() + : undefined; + } + function isImplementsClause() { + return token() === 109 && lookAhead(nextTokenIsIdentifierOrKeyword); + } + function parseHeritageClauses() { + if (isHeritageClause()) { + return parseList(22, parseHeritageClause); + } + return undefined; + } + function parseHeritageClause() { + var tok = token(); + ts.Debug.assert(tok === 86 || tok === 109); + var node = createNode(273); + node.token = tok; + nextToken(); + node.types = parseDelimitedList(7, parseExpressionWithTypeArguments); + return finishNode(node); + } + function parseExpressionWithTypeArguments() { + var node = createNode(211); + node.expression = parseLeftHandSideExpressionOrHigher(); + node.typeArguments = tryParseTypeArguments(); + return finishNode(node); + } + function tryParseTypeArguments() { + return token() === 28 + ? parseBracketedList(20, parseType, 28, 30) + : undefined; + } + function isHeritageClause() { + return token() === 86 || token() === 109; + } + function parseClassMembers() { + return parseList(5, parseClassElement); + } + function parseInterfaceDeclaration(node) { + node.kind = 241; + parseExpected(110); + node.name = parseIdentifier(); + node.typeParameters = parseTypeParameters(); + node.heritageClauses = parseHeritageClauses(); + node.members = parseObjectTypeMembers(); + return finishNode(node); + } + function parseTypeAliasDeclaration(node) { + node.kind = 242; + parseExpected(140); + node.name = parseIdentifier(); + node.typeParameters = parseTypeParameters(); + parseExpected(59); + node.type = parseType(); + parseSemicolon(); + return finishNode(node); + } + function parseEnumMember() { + var node = createNodeWithJSDoc(278); + node.name = parsePropertyName(); + node.initializer = allowInAnd(parseInitializer); + return finishNode(node); + } + function parseEnumDeclaration(node) { + node.kind = 243; + parseExpected(84); + node.name = parseIdentifier(); + if (parseExpected(18)) { + node.members = parseDelimitedList(6, parseEnumMember); + parseExpected(19); + } + else { + node.members = createMissingList(); + } + return finishNode(node); + } + function parseModuleBlock() { + var node = createNode(245); + if (parseExpected(18)) { + node.statements = parseList(1, parseStatement); + parseExpected(19); + } + else { + node.statements = createMissingList(); + } + return finishNode(node); + } + function parseModuleOrNamespaceDeclaration(node, flags) { + node.kind = 244; + var namespaceFlag = flags & 16; + node.flags |= flags; + node.name = parseIdentifier(); + node.body = parseOptional(24) + ? parseModuleOrNamespaceDeclaration(createNode(0), 4 | namespaceFlag) + : parseModuleBlock(); + return finishNode(node); + } + function parseAmbientExternalModuleDeclaration(node) { + node.kind = 244; + if (token() === 145) { + node.name = parseIdentifier(); + node.flags |= 512; + } + else { + node.name = parseLiteralNode(); + node.name.text = internIdentifier(node.name.text); + } + if (token() === 18) { + node.body = parseModuleBlock(); + } + else { + parseSemicolon(); + } + return finishNode(node); + } + function parseModuleDeclaration(node) { + var flags = 0; + if (token() === 145) { + return parseAmbientExternalModuleDeclaration(node); + } + else if (parseOptional(131)) { + flags |= 16; + } + else { + parseExpected(130); + if (token() === 10) { + return parseAmbientExternalModuleDeclaration(node); + } + } + return parseModuleOrNamespaceDeclaration(node, flags); + } + function isExternalModuleReference() { + return token() === 134 && + lookAhead(nextTokenIsOpenParen); + } + function nextTokenIsOpenParen() { + return nextToken() === 20; + } + function nextTokenIsSlash() { + return nextToken() === 42; + } + function parseNamespaceExportDeclaration(node) { + node.kind = 247; + parseExpected(119); + parseExpected(131); + node.name = parseIdentifier(); + parseSemicolon(); + return finishNode(node); + } + function parseImportDeclarationOrImportEqualsDeclaration(node) { + parseExpected(92); + var afterImportPos = scanner.getStartPos(); + var identifier; + if (isIdentifier()) { + identifier = parseIdentifier(); + if (token() !== 27 && token() !== 144) { + return parseImportEqualsDeclaration(node, identifier); + } + } + node.kind = 249; + if (identifier || + token() === 40 || + token() === 18) { + node.importClause = parseImportClause(identifier, afterImportPos); + parseExpected(144); + } + node.moduleSpecifier = parseModuleSpecifier(); + parseSemicolon(); + return finishNode(node); + } + function parseImportEqualsDeclaration(node, identifier) { + node.kind = 248; + node.name = identifier; + parseExpected(59); + node.moduleReference = parseModuleReference(); + parseSemicolon(); + return finishNode(node); + } + function parseImportClause(identifier, fullStart) { + var importClause = createNode(250, fullStart); + if (identifier) { + importClause.name = identifier; + } + if (!importClause.name || + parseOptional(27)) { + importClause.namedBindings = token() === 40 ? parseNamespaceImport() : parseNamedImportsOrExports(252); + } + return finishNode(importClause); + } + function parseModuleReference() { + return isExternalModuleReference() + ? parseExternalModuleReference() + : parseEntityName(false); + } + function parseExternalModuleReference() { + var node = createNode(259); + parseExpected(134); + parseExpected(20); + node.expression = parseModuleSpecifier(); + parseExpected(21); + return finishNode(node); + } + function parseModuleSpecifier() { + if (token() === 10) { + var result = parseLiteralNode(); + result.text = internIdentifier(result.text); + return result; + } + else { + return parseExpression(); + } + } + function parseNamespaceImport() { + var namespaceImport = createNode(251); + parseExpected(40); + parseExpected(119); + namespaceImport.name = parseIdentifier(); + return finishNode(namespaceImport); + } + function parseNamedImportsOrExports(kind) { + var node = createNode(kind); + node.elements = parseBracketedList(23, kind === 252 ? parseImportSpecifier : parseExportSpecifier, 18, 19); + return finishNode(node); + } + function parseExportSpecifier() { + return parseImportOrExportSpecifier(257); + } + function parseImportSpecifier() { + return parseImportOrExportSpecifier(253); + } + function parseImportOrExportSpecifier(kind) { + var node = createNode(kind); + var checkIdentifierIsKeyword = ts.isKeyword(token()) && !isIdentifier(); + var checkIdentifierStart = scanner.getTokenPos(); + var checkIdentifierEnd = scanner.getTextPos(); + var identifierName = parseIdentifierName(); + if (token() === 119) { + node.propertyName = identifierName; + parseExpected(119); + checkIdentifierIsKeyword = ts.isKeyword(token()) && !isIdentifier(); + checkIdentifierStart = scanner.getTokenPos(); + checkIdentifierEnd = scanner.getTextPos(); + node.name = parseIdentifierName(); + } + else { + node.name = identifierName; + } + if (kind === 253 && checkIdentifierIsKeyword) { + parseErrorAt(checkIdentifierStart, checkIdentifierEnd, ts.Diagnostics.Identifier_expected); + } + return finishNode(node); + } + function parseExportDeclaration(node) { + node.kind = 255; + if (parseOptional(40)) { + parseExpected(144); + node.moduleSpecifier = parseModuleSpecifier(); + } + else { + node.exportClause = parseNamedImportsOrExports(256); + if (token() === 144 || (token() === 10 && !scanner.hasPrecedingLineBreak())) { + parseExpected(144); + node.moduleSpecifier = parseModuleSpecifier(); + } + } + parseSemicolon(); + return finishNode(node); + } + function parseExportAssignment(node) { + node.kind = 254; + if (parseOptional(59)) { + node.isExportEquals = true; + } + else { + parseExpected(80); + } + node.expression = parseAssignmentExpressionOrHigher(); + parseSemicolon(); + return finishNode(node); + } + function setExternalModuleIndicator(sourceFile) { + sourceFile.externalModuleIndicator = + ts.forEach(sourceFile.statements, isAnExternalModuleIndicatorNode) || + getImportMetaIfNecessary(sourceFile); + } + function isAnExternalModuleIndicatorNode(node) { + return ts.hasModifier(node, 1) + || node.kind === 248 && node.moduleReference.kind === 259 + || node.kind === 249 + || node.kind === 254 + || node.kind === 255 + ? node + : undefined; + } + function getImportMetaIfNecessary(sourceFile) { + return sourceFile.flags & 1048576 ? + walkTreeForExternalModuleIndicators(sourceFile) : + undefined; + } + function walkTreeForExternalModuleIndicators(node) { + return isImportMeta(node) ? node : forEachChild(node, walkTreeForExternalModuleIndicators); + } + function isImportMeta(node) { + return ts.isMetaProperty(node) && node.keywordToken === 92 && node.name.escapedText === "meta"; + } + var JSDocParser; + (function (JSDocParser) { + function parseJSDocTypeExpressionForTests(content, start, length) { + initializeState(content, 6, undefined, 1); + sourceFile = createSourceFile("file.js", 6, 1, false); + scanner.setText(content, start, length); + currentToken = scanner.scan(); + var jsDocTypeExpression = parseJSDocTypeExpression(); + var diagnostics = parseDiagnostics; + clearState(); + return jsDocTypeExpression ? { jsDocTypeExpression: jsDocTypeExpression, diagnostics: diagnostics } : undefined; + } + JSDocParser.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests; + function parseJSDocTypeExpression(mayOmitBraces) { + var result = createNode(283); + var hasBrace = (mayOmitBraces ? parseOptional : parseExpected)(18); + result.type = doInsideOfContext(2097152, parseJSDocType); + if (!mayOmitBraces || hasBrace) { + parseExpected(19); + } + fixupParentReferences(result); + return finishNode(result); + } + JSDocParser.parseJSDocTypeExpression = parseJSDocTypeExpression; + function parseIsolatedJSDocComment(content, start, length) { + initializeState(content, 6, undefined, 1); + sourceFile = { languageVariant: 0, text: content }; + var jsDoc = parseJSDocCommentWorker(start, length); + var diagnostics = parseDiagnostics; + clearState(); + return jsDoc ? { jsDoc: jsDoc, diagnostics: diagnostics } : undefined; + } + JSDocParser.parseIsolatedJSDocComment = parseIsolatedJSDocComment; + function parseJSDocComment(parent, start, length) { + var _a; + var saveToken = currentToken; + var saveParseDiagnosticsLength = parseDiagnostics.length; + var saveParseErrorBeforeNextFinishedNode = parseErrorBeforeNextFinishedNode; + var comment = parseJSDocCommentWorker(start, length); + if (comment) { + comment.parent = parent; + } + if (contextFlags & 65536) { + if (!sourceFile.jsDocDiagnostics) { + sourceFile.jsDocDiagnostics = []; + } + (_a = sourceFile.jsDocDiagnostics).push.apply(_a, parseDiagnostics); + } + currentToken = saveToken; + parseDiagnostics.length = saveParseDiagnosticsLength; + parseErrorBeforeNextFinishedNode = saveParseErrorBeforeNextFinishedNode; + return comment; + } + JSDocParser.parseJSDocComment = parseJSDocComment; + function parseJSDocCommentWorker(start, length) { + if (start === void 0) { start = 0; } + var content = sourceText; + var end = length === undefined ? content.length : start + length; + length = end - start; + ts.Debug.assert(start >= 0); + ts.Debug.assert(start <= end); + ts.Debug.assert(end <= content.length); + if (!isJSDocLikeText(content, start)) { + return undefined; + } + var tags; + var tagsPos; + var tagsEnd; + var comments = []; + return scanner.scanRange(start + 3, length - 5, function () { + var state = 1; + var margin; + var indent = start - Math.max(content.lastIndexOf("\n", start), 0) + 4; + function pushComment(text) { + if (!margin) { + margin = indent; + } + comments.push(text); + indent += text.length; + } + nextJSDocToken(); + while (parseOptionalJsdoc(5)) + ; + if (parseOptionalJsdoc(4)) { + state = 0; + indent = 0; + } + loop: while (true) { + switch (token()) { + case 58: + if (state === 0 || state === 1) { + removeTrailingWhitespace(comments); + addTag(parseTag(indent)); + state = 0; + margin = undefined; + indent++; + } + else { + pushComment(scanner.getTokenText()); + } + break; + case 4: + comments.push(scanner.getTokenText()); + state = 0; + indent = 0; + break; + case 40: + var asterisk = scanner.getTokenText(); + if (state === 1 || state === 2) { + state = 2; + pushComment(asterisk); + } + else { + state = 1; + indent += asterisk.length; + } + break; + case 5: + var whitespace = scanner.getTokenText(); + if (state === 2) { + comments.push(whitespace); + } + else if (margin !== undefined && indent + whitespace.length > margin) { + comments.push(whitespace.slice(margin - indent - 1)); + } + indent += whitespace.length; + break; + case 1: + break loop; + default: + state = 2; + pushComment(scanner.getTokenText()); + break; + } + nextJSDocToken(); + } + removeLeadingNewlines(comments); + removeTrailingWhitespace(comments); + return createJSDocComment(); + }); + function removeLeadingNewlines(comments) { + while (comments.length && (comments[0] === "\n" || comments[0] === "\r")) { + comments.shift(); + } + } + function removeTrailingWhitespace(comments) { + while (comments.length && comments[comments.length - 1].trim() === "") { + comments.pop(); + } + } + function createJSDocComment() { + var result = createNode(291, start); + result.tags = tags && createNodeArray(tags, tagsPos, tagsEnd); + result.comment = comments.length ? comments.join("") : undefined; + return finishNode(result, end); + } + function isNextNonwhitespaceTokenEndOfFile() { + while (true) { + nextJSDocToken(); + if (token() === 1) { + return true; + } + if (!(token() === 5 || token() === 4)) { + return false; + } + } + } + function skipWhitespace() { + if (token() === 5 || token() === 4) { + if (lookAhead(isNextNonwhitespaceTokenEndOfFile)) { + return; + } + } + while (token() === 5 || token() === 4) { + nextJSDocToken(); + } + } + function skipWhitespaceOrAsterisk() { + if (token() === 5 || token() === 4) { + if (lookAhead(isNextNonwhitespaceTokenEndOfFile)) { + return; + } + } + var precedingLineBreak = scanner.hasPrecedingLineBreak(); + while ((precedingLineBreak && token() === 40) || token() === 5 || token() === 4) { + if (token() === 4) { + precedingLineBreak = true; + } + else if (token() === 40) { + precedingLineBreak = false; + } + nextJSDocToken(); + } + } + function parseTag(indent) { + ts.Debug.assert(token() === 58); + var start = scanner.getTokenPos(); + nextJSDocToken(); + var tagName = parseJSDocIdentifierName(undefined); + skipWhitespaceOrAsterisk(); + var tag; + switch (tagName.escapedText) { + case "augments": + case "extends": + tag = parseAugmentsTag(start, tagName); + break; + case "class": + case "constructor": + tag = parseClassTag(start, tagName); + break; + case "this": + tag = parseThisTag(start, tagName); + break; + case "enum": + tag = parseEnumTag(start, tagName); + break; + case "arg": + case "argument": + case "param": + return parseParameterOrPropertyTag(start, tagName, 2, indent); + case "return": + case "returns": + tag = parseReturnTag(start, tagName); + break; + case "template": + tag = parseTemplateTag(start, tagName); + break; + case "type": + tag = parseTypeTag(start, tagName); + break; + case "typedef": + tag = parseTypedefTag(start, tagName, indent); + break; + case "callback": + tag = parseCallbackTag(start, tagName, indent); + break; + default: + tag = parseUnknownTag(start, tagName); + break; + } + if (!tag.comment) { + tag.comment = parseTagComments(indent + tag.end - tag.pos); + } + return tag; + } + function parseTagComments(indent) { + var comments = []; + var state = 0; + var margin; + function pushComment(text) { + if (!margin) { + margin = indent; + } + comments.push(text); + indent += text.length; + } + var tok = token(); + loop: while (true) { + switch (tok) { + case 4: + if (state >= 1) { + state = 0; + comments.push(scanner.getTokenText()); + } + indent = 0; + break; + case 58: + scanner.setTextPos(scanner.getTextPos() - 1); + case 1: + break loop; + case 5: + if (state === 2) { + pushComment(scanner.getTokenText()); + } + else { + var whitespace = scanner.getTokenText(); + if (margin !== undefined && indent + whitespace.length > margin) { + comments.push(whitespace.slice(margin - indent - 1)); + } + indent += whitespace.length; + } + break; + case 18: + state = 2; + if (lookAhead(function () { return nextJSDocToken() === 58 && ts.tokenIsIdentifierOrKeyword(nextJSDocToken()) && scanner.getTokenText() === "link"; })) { + pushComment(scanner.getTokenText()); + nextJSDocToken(); + pushComment(scanner.getTokenText()); + nextJSDocToken(); + } + pushComment(scanner.getTokenText()); + break; + case 40: + if (state === 0) { + state = 1; + indent += 1; + break; + } + default: + state = 2; + pushComment(scanner.getTokenText()); + break; + } + tok = nextJSDocToken(); + } + removeLeadingNewlines(comments); + removeTrailingWhitespace(comments); + return comments.length === 0 ? undefined : comments.join(""); + } + function parseUnknownTag(start, tagName) { + var result = createNode(294, start); + result.tagName = tagName; + return finishNode(result); + } + function addTag(tag) { + if (!tag) { + return; + } + if (!tags) { + tags = [tag]; + tagsPos = tag.pos; + } + else { + tags.push(tag); + } + tagsEnd = tag.end; + } + function tryParseTypeExpression() { + skipWhitespaceOrAsterisk(); + return token() === 18 ? parseJSDocTypeExpression() : undefined; + } + function parseBracketNameInPropertyAndParamTag() { + if (token() === 14) { + return { name: createIdentifier(true), isBracketed: false }; + } + var isBracketed = parseOptional(22); + var name = parseJSDocEntityName(); + if (isBracketed) { + skipWhitespace(); + if (parseOptionalToken(59)) { + parseExpression(); + } + parseExpected(23); + } + return { name: name, isBracketed: isBracketed }; + } + function isObjectOrObjectArrayTypeReference(node) { + switch (node.kind) { + case 136: + return true; + case 169: + return isObjectOrObjectArrayTypeReference(node.elementType); + default: + return ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) && node.typeName.escapedText === "Object"; + } + } + function parseParameterOrPropertyTag(start, tagName, target, indent) { + var typeExpression = tryParseTypeExpression(); + var isNameFirst = !typeExpression; + skipWhitespaceOrAsterisk(); + var _a = parseBracketNameInPropertyAndParamTag(), name = _a.name, isBracketed = _a.isBracketed; + skipWhitespace(); + if (isNameFirst) { + typeExpression = tryParseTypeExpression(); + } + var result = target === 1 ? + createNode(305, start) : + createNode(299, start); + var comment = parseTagComments(indent + scanner.getStartPos() - start); + var nestedTypeLiteral = target !== 4 && parseNestedTypeLiteral(typeExpression, name, target, indent); + if (nestedTypeLiteral) { + typeExpression = nestedTypeLiteral; + isNameFirst = true; + } + result.tagName = tagName; + result.typeExpression = typeExpression; + result.name = name; + result.isNameFirst = isNameFirst; + result.isBracketed = isBracketed; + result.comment = comment; + return finishNode(result); + } + function parseNestedTypeLiteral(typeExpression, name, target, indent) { + if (typeExpression && isObjectOrObjectArrayTypeReference(typeExpression.type)) { + var typeLiteralExpression = createNode(283, scanner.getTokenPos()); + var child = void 0; + var jsdocTypeLiteral = void 0; + var start_2 = scanner.getStartPos(); + var children = void 0; + while (child = tryParse(function () { return parseChildParameterOrPropertyTag(target, indent, name); })) { + if (child.kind === 299 || child.kind === 305) { + children = ts.append(children, child); + } + } + if (children) { + jsdocTypeLiteral = createNode(292, start_2); + jsdocTypeLiteral.jsDocPropertyTags = children; + if (typeExpression.type.kind === 169) { + jsdocTypeLiteral.isArrayType = true; + } + typeLiteralExpression.type = finishNode(jsdocTypeLiteral); + return finishNode(typeLiteralExpression); + } + } + } + function parseReturnTag(start, tagName) { + if (ts.forEach(tags, function (t) { return t.kind === 300; })) { + parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText); + } + var result = createNode(300, start); + result.tagName = tagName; + result.typeExpression = tryParseTypeExpression(); + return finishNode(result); + } + function parseTypeTag(start, tagName) { + if (ts.forEach(tags, function (t) { return t.kind === 302; })) { + parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText); + } + var result = createNode(302, start); + result.tagName = tagName; + result.typeExpression = parseJSDocTypeExpression(true); + return finishNode(result); + } + function parseAugmentsTag(start, tagName) { + var result = createNode(295, start); + result.tagName = tagName; + result.class = parseExpressionWithTypeArgumentsForAugments(); + return finishNode(result); + } + function parseExpressionWithTypeArgumentsForAugments() { + var usedBrace = parseOptional(18); + var node = createNode(211); + node.expression = parsePropertyAccessEntityNameExpression(); + node.typeArguments = tryParseTypeArguments(); + var res = finishNode(node); + if (usedBrace) { + parseExpected(19); + } + return res; + } + function parsePropertyAccessEntityNameExpression() { + var node = parseJSDocIdentifierName(); + while (parseOptional(24)) { + var prop = createNode(189, node.pos); + prop.expression = node; + prop.name = parseJSDocIdentifierName(); + node = finishNode(prop); + } + return node; + } + function parseClassTag(start, tagName) { + var tag = createNode(296, start); + tag.tagName = tagName; + return finishNode(tag); + } + function parseThisTag(start, tagName) { + var tag = createNode(301, start); + tag.tagName = tagName; + tag.typeExpression = parseJSDocTypeExpression(true); + skipWhitespace(); + return finishNode(tag); + } + function parseEnumTag(start, tagName) { + var tag = createNode(298, start); + tag.tagName = tagName; + tag.typeExpression = parseJSDocTypeExpression(true); + skipWhitespace(); + return finishNode(tag); + } + function parseTypedefTag(start, tagName, indent) { + var typeExpression = tryParseTypeExpression(); + skipWhitespaceOrAsterisk(); + var typedefTag = createNode(304, start); + typedefTag.tagName = tagName; + typedefTag.fullName = parseJSDocTypeNameWithNamespace(); + typedefTag.name = getJSDocTypeAliasName(typedefTag.fullName); + skipWhitespace(); + typedefTag.comment = parseTagComments(indent); + typedefTag.typeExpression = typeExpression; + var end; + if (!typeExpression || isObjectOrObjectArrayTypeReference(typeExpression.type)) { + var child = void 0; + var jsdocTypeLiteral = void 0; + var childTypeTag = void 0; + while (child = tryParse(function () { return parseChildPropertyTag(indent); })) { + if (!jsdocTypeLiteral) { + jsdocTypeLiteral = createNode(292, start); + } + if (child.kind === 302) { + if (childTypeTag) { + break; + } + else { + childTypeTag = child; + } + } + else { + jsdocTypeLiteral.jsDocPropertyTags = ts.append(jsdocTypeLiteral.jsDocPropertyTags, child); + } + } + if (jsdocTypeLiteral) { + if (typeExpression && typeExpression.type.kind === 169) { + jsdocTypeLiteral.isArrayType = true; + } + typedefTag.typeExpression = childTypeTag && childTypeTag.typeExpression && !isObjectOrObjectArrayTypeReference(childTypeTag.typeExpression.type) ? + childTypeTag.typeExpression : + finishNode(jsdocTypeLiteral); + end = typedefTag.typeExpression.end; + } + } + return finishNode(typedefTag, end || typedefTag.comment !== undefined ? scanner.getStartPos() : (typedefTag.fullName || typedefTag.typeExpression || typedefTag.tagName).end); + } + function parseJSDocTypeNameWithNamespace(nested) { + var pos = scanner.getTokenPos(); + if (!ts.tokenIsIdentifierOrKeyword(token())) { + return undefined; + } + var typeNameOrNamespaceName = parseJSDocIdentifierName(); + if (parseOptional(24)) { + var jsDocNamespaceNode = createNode(244, pos); + if (nested) { + jsDocNamespaceNode.flags |= 4; + } + jsDocNamespaceNode.name = typeNameOrNamespaceName; + jsDocNamespaceNode.body = parseJSDocTypeNameWithNamespace(true); + return finishNode(jsDocNamespaceNode); + } + if (nested) { + typeNameOrNamespaceName.isInJSDocNamespace = true; + } + return typeNameOrNamespaceName; + } + function parseCallbackTag(start, tagName, indent) { + var callbackTag = createNode(297, start); + callbackTag.tagName = tagName; + callbackTag.fullName = parseJSDocTypeNameWithNamespace(); + callbackTag.name = getJSDocTypeAliasName(callbackTag.fullName); + skipWhitespace(); + callbackTag.comment = parseTagComments(indent); + var child; + var jsdocSignature = createNode(293, start); + jsdocSignature.parameters = []; + while (child = tryParse(function () { return parseChildParameterOrPropertyTag(4, indent); })) { + jsdocSignature.parameters = ts.append(jsdocSignature.parameters, child); + } + var returnTag = tryParse(function () { + if (parseOptionalJsdoc(58)) { + var tag = parseTag(indent); + if (tag && tag.kind === 300) { + return tag; + } + } + }); + if (returnTag) { + jsdocSignature.type = returnTag; + } + callbackTag.typeExpression = finishNode(jsdocSignature); + return finishNode(callbackTag); + } + function getJSDocTypeAliasName(fullName) { + if (fullName) { + var rightNode = fullName; + while (true) { + if (ts.isIdentifier(rightNode) || !rightNode.body) { + return ts.isIdentifier(rightNode) ? rightNode : rightNode.name; + } + rightNode = rightNode.body; + } + } + } + function escapedTextsEqual(a, b) { + while (!ts.isIdentifier(a) || !ts.isIdentifier(b)) { + if (!ts.isIdentifier(a) && !ts.isIdentifier(b) && a.right.escapedText === b.right.escapedText) { + a = a.left; + b = b.left; + } + else { + return false; + } + } + return a.escapedText === b.escapedText; + } + function parseChildPropertyTag(indent) { + return parseChildParameterOrPropertyTag(1, indent); + } + function parseChildParameterOrPropertyTag(target, indent, name) { + var canParseTag = true; + var seenAsterisk = false; + while (true) { + switch (nextJSDocToken()) { + case 58: + if (canParseTag) { + var child = tryParseChildTag(target, indent); + if (child && (child.kind === 299 || child.kind === 305) && + target !== 4 && + name && (ts.isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) { + return false; + } + return child; + } + seenAsterisk = false; + break; + case 4: + canParseTag = true; + seenAsterisk = false; + break; + case 40: + if (seenAsterisk) { + canParseTag = false; + } + seenAsterisk = true; + break; + case 72: + canParseTag = false; + break; + case 1: + return false; + } + } + } + function tryParseChildTag(target, indent) { + ts.Debug.assert(token() === 58); + var start = scanner.getStartPos(); + nextJSDocToken(); + var tagName = parseJSDocIdentifierName(); + skipWhitespace(); + var t; + switch (tagName.escapedText) { + case "type": + return target === 1 && parseTypeTag(start, tagName); + case "prop": + case "property": + t = 1; + break; + case "arg": + case "argument": + case "param": + t = 2 | 4; + break; + default: + return false; + } + if (!(target & t)) { + return false; + } + return parseParameterOrPropertyTag(start, tagName, target, indent); + } + function parseTemplateTag(start, tagName) { + var constraint; + if (token() === 18) { + constraint = parseJSDocTypeExpression(); + } + var typeParameters = []; + var typeParametersPos = getNodePos(); + do { + skipWhitespace(); + var typeParameter = createNode(150); + typeParameter.name = parseJSDocIdentifierName(ts.Diagnostics.Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces); + finishNode(typeParameter); + skipWhitespace(); + typeParameters.push(typeParameter); + } while (parseOptionalJsdoc(27)); + var result = createNode(303, start); + result.tagName = tagName; + result.constraint = constraint; + result.typeParameters = createNodeArray(typeParameters, typeParametersPos); + finishNode(result); + return result; + } + function nextJSDocToken() { + return currentToken = scanner.scanJSDocToken(); + } + function parseOptionalJsdoc(t) { + if (token() === t) { + nextJSDocToken(); + return true; + } + return false; + } + function parseJSDocEntityName() { + var entity = parseJSDocIdentifierName(); + if (parseOptional(22)) { + parseExpected(23); + } + while (parseOptional(24)) { + var name = parseJSDocIdentifierName(); + if (parseOptional(22)) { + parseExpected(23); + } + entity = createQualifiedName(entity, name); + } + return entity; + } + function parseJSDocIdentifierName(message) { + if (!ts.tokenIsIdentifierOrKeyword(token())) { + return createMissingNode(72, !message, message || ts.Diagnostics.Identifier_expected); + } + var pos = scanner.getTokenPos(); + var end = scanner.getTextPos(); + var result = createNode(72, pos); + result.escapedText = ts.escapeLeadingUnderscores(scanner.getTokenText()); + finishNode(result, end); + nextJSDocToken(); + return result; + } + } + JSDocParser.parseJSDocCommentWorker = parseJSDocCommentWorker; + })(JSDocParser = Parser.JSDocParser || (Parser.JSDocParser = {})); + })(Parser || (Parser = {})); + var IncrementalParser; + (function (IncrementalParser) { + function updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks) { + aggressiveChecks = aggressiveChecks || ts.Debug.shouldAssert(2); + checkChangeRange(sourceFile, newText, textChangeRange, aggressiveChecks); + if (ts.textChangeRangeIsUnchanged(textChangeRange)) { + return sourceFile; + } + if (sourceFile.statements.length === 0) { + return Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, undefined, true, sourceFile.scriptKind); + } + var incrementalSourceFile = sourceFile; + ts.Debug.assert(!incrementalSourceFile.hasBeenIncrementallyParsed); + incrementalSourceFile.hasBeenIncrementallyParsed = true; + var oldText = sourceFile.text; + var syntaxCursor = createSyntaxCursor(sourceFile); + var changeRange = extendToAffectedRange(sourceFile, textChangeRange); + checkChangeRange(sourceFile, newText, changeRange, aggressiveChecks); + ts.Debug.assert(changeRange.span.start <= textChangeRange.span.start); + ts.Debug.assert(ts.textSpanEnd(changeRange.span) === ts.textSpanEnd(textChangeRange.span)); + ts.Debug.assert(ts.textSpanEnd(ts.textChangeRangeNewSpan(changeRange)) === ts.textSpanEnd(ts.textChangeRangeNewSpan(textChangeRange))); + var delta = ts.textChangeRangeNewSpan(changeRange).length - changeRange.span.length; + updateTokenPositionsAndMarkElements(incrementalSourceFile, changeRange.span.start, ts.textSpanEnd(changeRange.span), ts.textSpanEnd(ts.textChangeRangeNewSpan(changeRange)), delta, oldText, newText, aggressiveChecks); + var result = Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, syntaxCursor, true, sourceFile.scriptKind); + return result; + } + IncrementalParser.updateSourceFile = updateSourceFile; + function moveElementEntirelyPastChangeRange(element, isArray, delta, oldText, newText, aggressiveChecks) { + if (isArray) { + visitArray(element); + } + else { + visitNode(element); + } + return; + function visitNode(node) { + var text = ""; + if (aggressiveChecks && shouldCheckNode(node)) { + text = oldText.substring(node.pos, node.end); + } + if (node._children) { + node._children = undefined; + } + node.pos += delta; + node.end += delta; + if (aggressiveChecks && shouldCheckNode(node)) { + ts.Debug.assert(text === newText.substring(node.pos, node.end)); + } + forEachChild(node, visitNode, visitArray); + if (ts.hasJSDocNodes(node)) { + for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { + var jsDocComment = _a[_i]; + visitNode(jsDocComment); + } + } + checkNodePositions(node, aggressiveChecks); + } + function visitArray(array) { + array._children = undefined; + array.pos += delta; + array.end += delta; + for (var _i = 0, array_8 = array; _i < array_8.length; _i++) { + var node = array_8[_i]; + visitNode(node); + } + } + } + function shouldCheckNode(node) { + switch (node.kind) { + case 10: + case 8: + case 72: + return true; + } + return false; + } + function adjustIntersectingElement(element, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta) { + ts.Debug.assert(element.end >= changeStart, "Adjusting an element that was entirely before the change range"); + ts.Debug.assert(element.pos <= changeRangeOldEnd, "Adjusting an element that was entirely after the change range"); + ts.Debug.assert(element.pos <= element.end); + element.pos = Math.min(element.pos, changeRangeNewEnd); + if (element.end >= changeRangeOldEnd) { + element.end += delta; + } + else { + element.end = Math.min(element.end, changeRangeNewEnd); + } + ts.Debug.assert(element.pos <= element.end); + if (element.parent) { + ts.Debug.assert(element.pos >= element.parent.pos); + ts.Debug.assert(element.end <= element.parent.end); + } + } + function checkNodePositions(node, aggressiveChecks) { + if (aggressiveChecks) { + var pos_2 = node.pos; + var visitNode_1 = function (child) { + ts.Debug.assert(child.pos >= pos_2); + pos_2 = child.end; + }; + if (ts.hasJSDocNodes(node)) { + for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { + var jsDocComment = _a[_i]; + visitNode_1(jsDocComment); + } + } + forEachChild(node, visitNode_1); + ts.Debug.assert(pos_2 <= node.end); + } + } + function updateTokenPositionsAndMarkElements(sourceFile, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta, oldText, newText, aggressiveChecks) { + visitNode(sourceFile); + return; + function visitNode(child) { + ts.Debug.assert(child.pos <= child.end); + if (child.pos > changeRangeOldEnd) { + moveElementEntirelyPastChangeRange(child, false, delta, oldText, newText, aggressiveChecks); + return; + } + var fullEnd = child.end; + if (fullEnd >= changeStart) { + child.intersectsChange = true; + child._children = undefined; + adjustIntersectingElement(child, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta); + forEachChild(child, visitNode, visitArray); + if (ts.hasJSDocNodes(child)) { + for (var _i = 0, _a = child.jsDoc; _i < _a.length; _i++) { + var jsDocComment = _a[_i]; + visitNode(jsDocComment); + } + } + checkNodePositions(child, aggressiveChecks); + return; + } + ts.Debug.assert(fullEnd < changeStart); + } + function visitArray(array) { + ts.Debug.assert(array.pos <= array.end); + if (array.pos > changeRangeOldEnd) { + moveElementEntirelyPastChangeRange(array, true, delta, oldText, newText, aggressiveChecks); + return; + } + var fullEnd = array.end; + if (fullEnd >= changeStart) { + array.intersectsChange = true; + array._children = undefined; + adjustIntersectingElement(array, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta); + for (var _i = 0, array_9 = array; _i < array_9.length; _i++) { + var node = array_9[_i]; + visitNode(node); + } + return; + } + ts.Debug.assert(fullEnd < changeStart); + } + } + function extendToAffectedRange(sourceFile, changeRange) { + var maxLookahead = 1; + var start = changeRange.span.start; + for (var i = 0; start > 0 && i <= maxLookahead; i++) { + var nearestNode = findNearestNodeStartingBeforeOrAtPosition(sourceFile, start); + ts.Debug.assert(nearestNode.pos <= start); + var position = nearestNode.pos; + start = Math.max(0, position - 1); + } + var finalSpan = ts.createTextSpanFromBounds(start, ts.textSpanEnd(changeRange.span)); + var finalLength = changeRange.newLength + (changeRange.span.start - start); + return ts.createTextChangeRange(finalSpan, finalLength); + } + function findNearestNodeStartingBeforeOrAtPosition(sourceFile, position) { + var bestResult = sourceFile; + var lastNodeEntirelyBeforePosition; + forEachChild(sourceFile, visit); + if (lastNodeEntirelyBeforePosition) { + var lastChildOfLastEntireNodeBeforePosition = getLastDescendant(lastNodeEntirelyBeforePosition); + if (lastChildOfLastEntireNodeBeforePosition.pos > bestResult.pos) { + bestResult = lastChildOfLastEntireNodeBeforePosition; + } + } + return bestResult; + function getLastDescendant(node) { + while (true) { + var lastChild = ts.getLastChild(node); + if (lastChild) { + node = lastChild; + } + else { + return node; + } + } + } + function visit(child) { + if (ts.nodeIsMissing(child)) { + return; + } + if (child.pos <= position) { + if (child.pos >= bestResult.pos) { + bestResult = child; + } + if (position < child.end) { + forEachChild(child, visit); + return true; + } + else { + ts.Debug.assert(child.end <= position); + lastNodeEntirelyBeforePosition = child; + } + } + else { + ts.Debug.assert(child.pos > position); + return true; + } + } + } + function checkChangeRange(sourceFile, newText, textChangeRange, aggressiveChecks) { + var oldText = sourceFile.text; + if (textChangeRange) { + ts.Debug.assert((oldText.length - textChangeRange.span.length + textChangeRange.newLength) === newText.length); + if (aggressiveChecks || ts.Debug.shouldAssert(3)) { + var oldTextPrefix = oldText.substr(0, textChangeRange.span.start); + var newTextPrefix = newText.substr(0, textChangeRange.span.start); + ts.Debug.assert(oldTextPrefix === newTextPrefix); + var oldTextSuffix = oldText.substring(ts.textSpanEnd(textChangeRange.span), oldText.length); + var newTextSuffix = newText.substring(ts.textSpanEnd(ts.textChangeRangeNewSpan(textChangeRange)), newText.length); + ts.Debug.assert(oldTextSuffix === newTextSuffix); + } + } + } + function createSyntaxCursor(sourceFile) { + var currentArray = sourceFile.statements; + var currentArrayIndex = 0; + ts.Debug.assert(currentArrayIndex < currentArray.length); + var current = currentArray[currentArrayIndex]; + var lastQueriedPosition = -1; + return { + currentNode: function (position) { + if (position !== lastQueriedPosition) { + if (current && current.end === position && currentArrayIndex < (currentArray.length - 1)) { + currentArrayIndex++; + current = currentArray[currentArrayIndex]; + } + if (!current || current.pos !== position) { + findHighestListElementThatStartsAtPosition(position); + } + } + lastQueriedPosition = position; + ts.Debug.assert(!current || current.pos === position); + return current; + } + }; + function findHighestListElementThatStartsAtPosition(position) { + currentArray = undefined; + currentArrayIndex = -1; + current = undefined; + forEachChild(sourceFile, visitNode, visitArray); + return; + function visitNode(node) { + if (position >= node.pos && position < node.end) { + forEachChild(node, visitNode, visitArray); + return true; + } + return false; + } + function visitArray(array) { + if (position >= array.pos && position < array.end) { + for (var i = 0; i < array.length; i++) { + var child = array[i]; + if (child) { + if (child.pos === position) { + currentArray = array; + currentArrayIndex = i; + current = child; + return true; + } + else { + if (child.pos < position && position < child.end) { + forEachChild(child, visitNode, visitArray); + return true; + } + } + } + } + } + return false; + } + } + } + })(IncrementalParser || (IncrementalParser = {})); + function isDeclarationFileName(fileName) { + return ts.fileExtensionIs(fileName, ".d.ts"); + } + ts.isDeclarationFileName = isDeclarationFileName; + function processCommentPragmas(context, sourceText) { + var triviaScanner = ts.createScanner(context.languageVersion, false, 0, sourceText); + var pragmas = []; + while (true) { + var kind = triviaScanner.scan(); + if (!ts.isTrivia(kind)) { + break; + } + var range = { + kind: triviaScanner.getToken(), + pos: triviaScanner.getTokenPos(), + end: triviaScanner.getTextPos(), + }; + var comment = sourceText.substring(range.pos, range.end); + extractPragmas(pragmas, range, comment); + } + context.pragmas = ts.createMap(); + for (var _i = 0, pragmas_1 = pragmas; _i < pragmas_1.length; _i++) { + var pragma = pragmas_1[_i]; + if (context.pragmas.has(pragma.name)) { + var currentValue = context.pragmas.get(pragma.name); + if (currentValue instanceof Array) { + currentValue.push(pragma.args); + } + else { + context.pragmas.set(pragma.name, [currentValue, pragma.args]); + } + continue; + } + context.pragmas.set(pragma.name, pragma.args); + } + } + ts.processCommentPragmas = processCommentPragmas; + function processPragmasIntoFields(context, reportDiagnostic) { + context.checkJsDirective = undefined; + context.referencedFiles = []; + context.typeReferenceDirectives = []; + context.libReferenceDirectives = []; + context.amdDependencies = []; + context.hasNoDefaultLib = false; + context.pragmas.forEach(function (entryOrList, key) { + switch (key) { + case "reference": { + var referencedFiles_1 = context.referencedFiles; + var typeReferenceDirectives_1 = context.typeReferenceDirectives; + var libReferenceDirectives_1 = context.libReferenceDirectives; + ts.forEach(ts.toArray(entryOrList), function (arg) { + if (arg.arguments["no-default-lib"]) { + context.hasNoDefaultLib = true; + } + else if (arg.arguments.types) { + typeReferenceDirectives_1.push({ pos: arg.arguments.types.pos, end: arg.arguments.types.end, fileName: arg.arguments.types.value }); + } + else if (arg.arguments.lib) { + libReferenceDirectives_1.push({ pos: arg.arguments.lib.pos, end: arg.arguments.lib.end, fileName: arg.arguments.lib.value }); + } + else if (arg.arguments.path) { + referencedFiles_1.push({ pos: arg.arguments.path.pos, end: arg.arguments.path.end, fileName: arg.arguments.path.value }); + } + else { + reportDiagnostic(arg.range.pos, arg.range.end - arg.range.pos, ts.Diagnostics.Invalid_reference_directive_syntax); + } + }); + break; + } + case "amd-dependency": { + context.amdDependencies = ts.map(ts.toArray(entryOrList), function (x) { return ({ name: x.arguments.name, path: x.arguments.path }); }); + break; + } + case "amd-module": { + if (entryOrList instanceof Array) { + for (var _i = 0, entryOrList_1 = entryOrList; _i < entryOrList_1.length; _i++) { + var entry = entryOrList_1[_i]; + if (context.moduleName) { + reportDiagnostic(entry.range.pos, entry.range.end - entry.range.pos, ts.Diagnostics.An_AMD_module_cannot_have_multiple_name_assignments); + } + context.moduleName = entry.arguments.name; + } + } + else { + context.moduleName = entryOrList.arguments.name; + } + break; + } + case "ts-nocheck": + case "ts-check": { + ts.forEach(ts.toArray(entryOrList), function (entry) { + if (!context.checkJsDirective || entry.range.pos > context.checkJsDirective.pos) { + context.checkJsDirective = { + enabled: key === "ts-check", + end: entry.range.end, + pos: entry.range.pos + }; + } + }); + break; + } + case "jsx": return; + default: ts.Debug.fail("Unhandled pragma kind"); + } + }); + } + ts.processPragmasIntoFields = processPragmasIntoFields; + var namedArgRegExCache = ts.createMap(); + function getNamedArgRegEx(name) { + if (namedArgRegExCache.has(name)) { + return namedArgRegExCache.get(name); + } + var result = new RegExp("(\\s" + name + "\\s*=\\s*)('|\")(.+?)\\2", "im"); + namedArgRegExCache.set(name, result); + return result; + } + var tripleSlashXMLCommentStartRegEx = /^\/\/\/\s*<(\S+)\s.*?\/>/im; + var singleLinePragmaRegEx = /^\/\/\/?\s*@(\S+)\s*(.*)\s*$/im; + function extractPragmas(pragmas, range, text) { + var tripleSlash = range.kind === 2 && tripleSlashXMLCommentStartRegEx.exec(text); + if (tripleSlash) { + var name = tripleSlash[1].toLowerCase(); + var pragma = ts.commentPragmas[name]; + if (!pragma || !(pragma.kind & 1)) { + return; + } + if (pragma.args) { + var argument = {}; + for (var _i = 0, _a = pragma.args; _i < _a.length; _i++) { + var arg = _a[_i]; + var matcher = getNamedArgRegEx(arg.name); + var matchResult = matcher.exec(text); + if (!matchResult && !arg.optional) { + return; + } + else if (matchResult) { + if (arg.captureSpan) { + var startPos = range.pos + matchResult.index + matchResult[1].length + matchResult[2].length; + argument[arg.name] = { + value: matchResult[3], + pos: startPos, + end: startPos + matchResult[3].length + }; + } + else { + argument[arg.name] = matchResult[3]; + } + } + } + pragmas.push({ name: name, args: { arguments: argument, range: range } }); + } + else { + pragmas.push({ name: name, args: { arguments: {}, range: range } }); + } + return; + } + var singleLine = range.kind === 2 && singleLinePragmaRegEx.exec(text); + if (singleLine) { + return addPragmaForMatch(pragmas, range, 2, singleLine); + } + if (range.kind === 3) { + var multiLinePragmaRegEx = /\s*@(\S+)\s*(.*)\s*$/gim; + var multiLineMatch = void 0; + while (multiLineMatch = multiLinePragmaRegEx.exec(text)) { + addPragmaForMatch(pragmas, range, 4, multiLineMatch); + } + } + } + function addPragmaForMatch(pragmas, range, kind, match) { + if (!match) + return; + var name = match[1].toLowerCase(); + var pragma = ts.commentPragmas[name]; + if (!pragma || !(pragma.kind & kind)) { + return; + } + var args = match[2]; + var argument = getNamedPragmaArguments(pragma, args); + if (argument === "fail") + return; + pragmas.push({ name: name, args: { arguments: argument, range: range } }); + return; + } + function getNamedPragmaArguments(pragma, text) { + if (!text) + return {}; + if (!pragma.args) + return {}; + var args = text.split(/\s+/); + var argMap = {}; + for (var i = 0; i < pragma.args.length; i++) { + var argument = pragma.args[i]; + if (!args[i] && !argument.optional) { + return "fail"; + } + if (argument.captureSpan) { + return ts.Debug.fail("Capture spans not yet implemented for non-xml pragmas"); + } + argMap[argument.name] = args[i]; + } + return argMap; + } + function tagNamesAreEquivalent(lhs, rhs) { + if (lhs.kind !== rhs.kind) { + return false; + } + if (lhs.kind === 72) { + return lhs.escapedText === rhs.escapedText; + } + if (lhs.kind === 100) { + return true; + } + return lhs.name.escapedText === rhs.name.escapedText && + tagNamesAreEquivalent(lhs.expression, rhs.expression); + } + ts.tagNamesAreEquivalent = tagNamesAreEquivalent; +})(ts || (ts = {})); +var ts; +(function (ts) { + ts.compileOnSaveCommandLineOption = { name: "compileOnSave", type: "boolean" }; + var libEntries = [ + ["es5", "lib.es5.d.ts"], + ["es6", "lib.es2015.d.ts"], + ["es2015", "lib.es2015.d.ts"], + ["es7", "lib.es2016.d.ts"], + ["es2016", "lib.es2016.d.ts"], + ["es2017", "lib.es2017.d.ts"], + ["es2018", "lib.es2018.d.ts"], + ["esnext", "lib.esnext.d.ts"], + ["dom", "lib.dom.d.ts"], + ["dom.iterable", "lib.dom.iterable.d.ts"], + ["webworker", "lib.webworker.d.ts"], + ["webworker.importscripts", "lib.webworker.importscripts.d.ts"], + ["scripthost", "lib.scripthost.d.ts"], + ["es2015.core", "lib.es2015.core.d.ts"], + ["es2015.collection", "lib.es2015.collection.d.ts"], + ["es2015.generator", "lib.es2015.generator.d.ts"], + ["es2015.iterable", "lib.es2015.iterable.d.ts"], + ["es2015.promise", "lib.es2015.promise.d.ts"], + ["es2015.proxy", "lib.es2015.proxy.d.ts"], + ["es2015.reflect", "lib.es2015.reflect.d.ts"], + ["es2015.symbol", "lib.es2015.symbol.d.ts"], + ["es2015.symbol.wellknown", "lib.es2015.symbol.wellknown.d.ts"], + ["es2016.array.include", "lib.es2016.array.include.d.ts"], + ["es2017.object", "lib.es2017.object.d.ts"], + ["es2017.sharedmemory", "lib.es2017.sharedmemory.d.ts"], + ["es2017.string", "lib.es2017.string.d.ts"], + ["es2017.intl", "lib.es2017.intl.d.ts"], + ["es2017.typedarrays", "lib.es2017.typedarrays.d.ts"], + ["es2018.intl", "lib.es2018.intl.d.ts"], + ["es2018.promise", "lib.es2018.promise.d.ts"], + ["es2018.regexp", "lib.es2018.regexp.d.ts"], + ["esnext.array", "lib.esnext.array.d.ts"], + ["esnext.symbol", "lib.esnext.symbol.d.ts"], + ["esnext.asynciterable", "lib.esnext.asynciterable.d.ts"], + ["esnext.intl", "lib.esnext.intl.d.ts"], + ["esnext.bigint", "lib.esnext.bigint.d.ts"] + ]; + ts.libs = libEntries.map(function (entry) { return entry[0]; }); + ts.libMap = ts.createMapFromEntries(libEntries); + ts.commonOptionsWithBuild = [ + { + name: "help", + shortName: "h", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Print_this_message, + }, + { + name: "help", + shortName: "?", + type: "boolean" + }, + { + name: "watch", + shortName: "w", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Watch_input_files, + }, + { + name: "preserveWatchOutput", + type: "boolean", + showInSimplifiedHelpView: false, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen, + }, + { + name: "listFiles", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Print_names_of_files_part_of_the_compilation + }, + { + name: "listEmittedFiles", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Print_names_of_generated_files_part_of_the_compilation + }, + { + name: "pretty", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Stylize_errors_and_messages_using_color_and_context_experimental + }, + { + name: "traceResolution", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Enable_tracing_of_the_name_resolution_process + }, + { + name: "diagnostics", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Show_diagnostic_information + }, + { + name: "extendedDiagnostics", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Show_verbose_diagnostic_information + }, + ]; + ts.optionDeclarations = ts.commonOptionsWithBuild.concat([ + { + name: "all", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Show_all_compiler_options, + }, + { + name: "version", + shortName: "v", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Print_the_compiler_s_version, + }, + { + name: "init", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file, + }, + { + name: "project", + shortName: "p", + type: "string", + isFilePath: true, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Command_line_Options, + paramType: ts.Diagnostics.FILE_OR_DIRECTORY, + description: ts.Diagnostics.Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json, + }, + { + name: "build", + type: "boolean", + shortName: "b", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Build_one_or_more_projects_and_their_dependencies_if_out_of_date + }, + { + name: "showConfig", + type: "boolean", + category: ts.Diagnostics.Command_line_Options, + isCommandLineOnly: true, + description: ts.Diagnostics.Print_the_final_configuration_instead_of_building + }, + { + name: "target", + shortName: "t", + type: ts.createMapFromTemplate({ + es3: 0, + es5: 1, + es6: 2, + es2015: 2, + es2016: 3, + es2017: 4, + es2018: 5, + esnext: 6, + }), + affectsSourceFile: true, + affectsModuleResolution: true, + paramType: ts.Diagnostics.VERSION, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_or_ESNEXT, + }, + { + name: "module", + shortName: "m", + type: ts.createMapFromTemplate({ + none: ts.ModuleKind.None, + commonjs: ts.ModuleKind.CommonJS, + amd: ts.ModuleKind.AMD, + system: ts.ModuleKind.System, + umd: ts.ModuleKind.UMD, + es6: ts.ModuleKind.ES2015, + es2015: ts.ModuleKind.ES2015, + esnext: ts.ModuleKind.ESNext + }), + affectsModuleResolution: true, + paramType: ts.Diagnostics.KIND, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext, + }, + { + name: "lib", + type: "list", + element: { + name: "lib", + type: ts.libMap + }, + affectsModuleResolution: true, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Specify_library_files_to_be_included_in_the_compilation + }, + { + name: "allowJs", + type: "boolean", + affectsModuleResolution: true, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Allow_javascript_files_to_be_compiled + }, + { + name: "checkJs", + type: "boolean", + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Report_errors_in_js_files + }, + { + name: "jsx", + type: ts.createMapFromTemplate({ + "preserve": 1, + "react-native": 3, + "react": 2 + }), + affectsSourceFile: true, + paramType: ts.Diagnostics.KIND, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Specify_JSX_code_generation_Colon_preserve_react_native_or_react, + }, + { + name: "declaration", + shortName: "d", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Generates_corresponding_d_ts_file, + }, + { + name: "declarationMap", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Generates_a_sourcemap_for_each_corresponding_d_ts_file, + }, + { + name: "emitDeclarationOnly", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Only_emit_d_ts_declaration_files, + }, + { + name: "sourceMap", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Generates_corresponding_map_file, + }, + { + name: "outFile", + type: "string", + isFilePath: true, + paramType: ts.Diagnostics.FILE, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Concatenate_and_emit_output_to_single_file, + }, + { + name: "outDir", + type: "string", + isFilePath: true, + paramType: ts.Diagnostics.DIRECTORY, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Redirect_output_structure_to_the_directory, + }, + { + name: "rootDir", + type: "string", + isFilePath: true, + paramType: ts.Diagnostics.LOCATION, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir, + }, + { + name: "composite", + type: "boolean", + isTSConfigOnly: true, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Enable_project_compilation, + }, + { + name: "removeComments", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Do_not_emit_comments_to_output, + }, + { + name: "noEmit", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Do_not_emit_outputs, + }, + { + name: "importHelpers", + type: "boolean", + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Import_emit_helpers_from_tslib + }, + { + name: "downlevelIteration", + type: "boolean", + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Provide_full_support_for_iterables_in_for_of_spread_and_destructuring_when_targeting_ES5_or_ES3 + }, + { + name: "isolatedModules", + type: "boolean", + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule + }, + { + name: "strict", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Strict_Type_Checking_Options, + description: ts.Diagnostics.Enable_all_strict_type_checking_options + }, + { + name: "noImplicitAny", + type: "boolean", + affectsSemanticDiagnostics: true, + strictFlag: true, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Strict_Type_Checking_Options, + description: ts.Diagnostics.Raise_error_on_expressions_and_declarations_with_an_implied_any_type + }, + { + name: "strictNullChecks", + type: "boolean", + affectsSemanticDiagnostics: true, + strictFlag: true, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Strict_Type_Checking_Options, + description: ts.Diagnostics.Enable_strict_null_checks + }, + { + name: "strictFunctionTypes", + type: "boolean", + affectsSemanticDiagnostics: true, + strictFlag: true, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Strict_Type_Checking_Options, + description: ts.Diagnostics.Enable_strict_checking_of_function_types + }, + { + name: "strictBindCallApply", + type: "boolean", + strictFlag: true, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Strict_Type_Checking_Options, + description: ts.Diagnostics.Enable_strict_bind_call_and_apply_methods_on_functions + }, + { + name: "strictPropertyInitialization", + type: "boolean", + affectsSemanticDiagnostics: true, + strictFlag: true, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Strict_Type_Checking_Options, + description: ts.Diagnostics.Enable_strict_checking_of_property_initialization_in_classes + }, + { + name: "noImplicitThis", + type: "boolean", + affectsSemanticDiagnostics: true, + strictFlag: true, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Strict_Type_Checking_Options, + description: ts.Diagnostics.Raise_error_on_this_expressions_with_an_implied_any_type, + }, + { + name: "alwaysStrict", + type: "boolean", + affectsSourceFile: true, + strictFlag: true, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Strict_Type_Checking_Options, + description: ts.Diagnostics.Parse_in_strict_mode_and_emit_use_strict_for_each_source_file + }, + { + name: "noUnusedLocals", + type: "boolean", + affectsSemanticDiagnostics: true, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Additional_Checks, + description: ts.Diagnostics.Report_errors_on_unused_locals, + }, + { + name: "noUnusedParameters", + type: "boolean", + affectsSemanticDiagnostics: true, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Additional_Checks, + description: ts.Diagnostics.Report_errors_on_unused_parameters, + }, + { + name: "noImplicitReturns", + type: "boolean", + affectsSemanticDiagnostics: true, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Additional_Checks, + description: ts.Diagnostics.Report_error_when_not_all_code_paths_in_function_return_a_value + }, + { + name: "noFallthroughCasesInSwitch", + type: "boolean", + affectsBindDiagnostics: true, + affectsSemanticDiagnostics: true, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Additional_Checks, + description: ts.Diagnostics.Report_errors_for_fallthrough_cases_in_switch_statement + }, + { + name: "moduleResolution", + type: ts.createMapFromTemplate({ + node: ts.ModuleResolutionKind.NodeJs, + classic: ts.ModuleResolutionKind.Classic, + }), + affectsModuleResolution: true, + paramType: ts.Diagnostics.STRATEGY, + category: ts.Diagnostics.Module_Resolution_Options, + description: ts.Diagnostics.Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6, + }, + { + name: "baseUrl", + type: "string", + affectsModuleResolution: true, + isFilePath: true, + category: ts.Diagnostics.Module_Resolution_Options, + description: ts.Diagnostics.Base_directory_to_resolve_non_absolute_module_names + }, + { + name: "paths", + type: "object", + affectsModuleResolution: true, + isTSConfigOnly: true, + category: ts.Diagnostics.Module_Resolution_Options, + description: ts.Diagnostics.A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl + }, + { + name: "rootDirs", + type: "list", + isTSConfigOnly: true, + element: { + name: "rootDirs", + type: "string", + isFilePath: true + }, + affectsModuleResolution: true, + category: ts.Diagnostics.Module_Resolution_Options, + description: ts.Diagnostics.List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime + }, + { + name: "typeRoots", + type: "list", + element: { + name: "typeRoots", + type: "string", + isFilePath: true + }, + affectsModuleResolution: true, + category: ts.Diagnostics.Module_Resolution_Options, + description: ts.Diagnostics.List_of_folders_to_include_type_definitions_from + }, + { + name: "types", + type: "list", + element: { + name: "types", + type: "string" + }, + affectsModuleResolution: true, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Module_Resolution_Options, + description: ts.Diagnostics.Type_declaration_files_to_be_included_in_compilation + }, + { + name: "allowSyntheticDefaultImports", + type: "boolean", + affectsSemanticDiagnostics: true, + category: ts.Diagnostics.Module_Resolution_Options, + description: ts.Diagnostics.Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking + }, + { + name: "esModuleInterop", + type: "boolean", + affectsSemanticDiagnostics: true, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Module_Resolution_Options, + description: ts.Diagnostics.Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for_all_imports_Implies_allowSyntheticDefaultImports + }, + { + name: "preserveSymlinks", + type: "boolean", + category: ts.Diagnostics.Module_Resolution_Options, + description: ts.Diagnostics.Do_not_resolve_the_real_path_of_symlinks, + }, + { + name: "sourceRoot", + type: "string", + paramType: ts.Diagnostics.LOCATION, + category: ts.Diagnostics.Source_Map_Options, + description: ts.Diagnostics.Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations, + }, + { + name: "mapRoot", + type: "string", + paramType: ts.Diagnostics.LOCATION, + category: ts.Diagnostics.Source_Map_Options, + description: ts.Diagnostics.Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations, + }, + { + name: "inlineSourceMap", + type: "boolean", + category: ts.Diagnostics.Source_Map_Options, + description: ts.Diagnostics.Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file + }, + { + name: "inlineSources", + type: "boolean", + category: ts.Diagnostics.Source_Map_Options, + description: ts.Diagnostics.Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap_to_be_set + }, + { + name: "experimentalDecorators", + type: "boolean", + category: ts.Diagnostics.Experimental_Options, + description: ts.Diagnostics.Enables_experimental_support_for_ES7_decorators + }, + { + name: "emitDecoratorMetadata", + type: "boolean", + category: ts.Diagnostics.Experimental_Options, + description: ts.Diagnostics.Enables_experimental_support_for_emitting_type_metadata_for_decorators + }, + { + name: "jsxFactory", + type: "string", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h + }, + { + name: "resolveJsonModule", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Include_modules_imported_with_json_extension + }, + { + name: "out", + type: "string", + isFilePath: false, + category: ts.Diagnostics.Advanced_Options, + paramType: ts.Diagnostics.FILE, + description: ts.Diagnostics.Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file, + }, + { + name: "reactNamespace", + type: "string", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react_JSX_emit + }, + { + name: "skipDefaultLibCheck", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files + }, + { + name: "charset", + type: "string", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.The_character_set_of_the_input_files + }, + { + name: "emitBOM", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files + }, + { + name: "locale", + type: "string", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.The_locale_used_when_displaying_messages_to_the_user_e_g_en_us + }, + { + name: "newLine", + type: ts.createMapFromTemplate({ + crlf: 0, + lf: 1 + }), + paramType: ts.Diagnostics.NEWLINE, + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix, + }, + { + name: "noErrorTruncation", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Do_not_truncate_error_messages + }, + { + name: "noLib", + type: "boolean", + affectsModuleResolution: true, + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Do_not_include_the_default_library_file_lib_d_ts + }, + { + name: "noResolve", + type: "boolean", + affectsModuleResolution: true, + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files + }, + { + name: "stripInternal", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Do_not_emit_declarations_for_code_that_has_an_internal_annotation, + }, + { + name: "disableSizeLimit", + type: "boolean", + affectsSourceFile: true, + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Disable_size_limitations_on_JavaScript_projects + }, + { + name: "noImplicitUseStrict", + type: "boolean", + affectsSemanticDiagnostics: true, + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Do_not_emit_use_strict_directives_in_module_output + }, + { + name: "noEmitHelpers", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Do_not_generate_custom_helper_functions_like_extends_in_compiled_output + }, + { + name: "noEmitOnError", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Do_not_emit_outputs_if_any_errors_were_reported, + }, + { + name: "preserveConstEnums", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Do_not_erase_const_enum_declarations_in_generated_code + }, + { + name: "declarationDir", + type: "string", + isFilePath: true, + paramType: ts.Diagnostics.DIRECTORY, + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Output_directory_for_generated_declaration_files + }, + { + name: "skipLibCheck", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Skip_type_checking_of_declaration_files, + }, + { + name: "allowUnusedLabels", + type: "boolean", + affectsBindDiagnostics: true, + affectsSemanticDiagnostics: true, + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Do_not_report_errors_on_unused_labels + }, + { + name: "allowUnreachableCode", + type: "boolean", + affectsBindDiagnostics: true, + affectsSemanticDiagnostics: true, + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Do_not_report_errors_on_unreachable_code + }, + { + name: "suppressExcessPropertyErrors", + type: "boolean", + affectsSemanticDiagnostics: true, + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Suppress_excess_property_checks_for_object_literals, + }, + { + name: "suppressImplicitAnyIndexErrors", + type: "boolean", + affectsSemanticDiagnostics: true, + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures, + }, + { + name: "forceConsistentCasingInFileNames", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Disallow_inconsistently_cased_references_to_the_same_file + }, + { + name: "maxNodeModuleJsDepth", + type: "number", + affectsModuleResolution: true, + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files + }, + { + name: "noStrictGenericChecks", + type: "boolean", + affectsSemanticDiagnostics: true, + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Disable_strict_checking_of_generic_signatures_in_function_types, + }, + { + name: "keyofStringsOnly", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols, + }, + { + name: "plugins", + type: "list", + isTSConfigOnly: true, + element: { + name: "plugin", + type: "object" + }, + description: ts.Diagnostics.List_of_language_service_plugins + } + ]); + ts.semanticDiagnosticsOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsSemanticDiagnostics; }); + ts.moduleResolutionOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsModuleResolution; }); + ts.sourceFileAffectingCompilerOptions = ts.optionDeclarations.filter(function (option) { + return !!option.affectsSourceFile || !!option.affectsModuleResolution || !!option.affectsBindDiagnostics; + }); + ts.buildOpts = ts.commonOptionsWithBuild.concat([ + { + name: "verbose", + shortName: "v", + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Enable_verbose_logging, + type: "boolean" + }, + { + name: "dry", + shortName: "d", + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Show_what_would_be_built_or_deleted_if_specified_with_clean, + type: "boolean" + }, + { + name: "force", + shortName: "f", + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Build_all_projects_including_those_that_appear_to_be_up_to_date, + type: "boolean" + }, + { + name: "clean", + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Delete_the_outputs_of_all_projects, + type: "boolean" + } + ]); + ts.typeAcquisitionDeclarations = [ + { + name: "enableAutoDiscovery", + type: "boolean", + }, + { + name: "enable", + type: "boolean", + }, + { + name: "include", + type: "list", + element: { + name: "include", + type: "string" + } + }, + { + name: "exclude", + type: "list", + element: { + name: "exclude", + type: "string" + } + } + ]; + ts.defaultInitCompilerOptions = { + module: ts.ModuleKind.CommonJS, + target: 1, + strict: true, + esModuleInterop: true + }; + var optionNameMapCache; + function convertEnableAutoDiscoveryToEnable(typeAcquisition) { + if (typeAcquisition && typeAcquisition.enableAutoDiscovery !== undefined && typeAcquisition.enable === undefined) { + return { + enable: typeAcquisition.enableAutoDiscovery, + include: typeAcquisition.include || [], + exclude: typeAcquisition.exclude || [] + }; + } + return typeAcquisition; + } + ts.convertEnableAutoDiscoveryToEnable = convertEnableAutoDiscoveryToEnable; + function getOptionNameMap() { + return optionNameMapCache || (optionNameMapCache = createOptionNameMap(ts.optionDeclarations)); + } + function createOptionNameMap(optionDeclarations) { + var optionNameMap = ts.createMap(); + var shortOptionNames = ts.createMap(); + ts.forEach(optionDeclarations, function (option) { + optionNameMap.set(option.name.toLowerCase(), option); + if (option.shortName) { + shortOptionNames.set(option.shortName, option.name); + } + }); + return { optionNameMap: optionNameMap, shortOptionNames: shortOptionNames }; + } + ts.createOptionNameMap = createOptionNameMap; + function createCompilerDiagnosticForInvalidCustomType(opt) { + return createDiagnosticForInvalidCustomType(opt, ts.createCompilerDiagnostic); + } + ts.createCompilerDiagnosticForInvalidCustomType = createCompilerDiagnosticForInvalidCustomType; + function createDiagnosticForInvalidCustomType(opt, createDiagnostic) { + var namesOfType = ts.arrayFrom(opt.type.keys()).map(function (key) { return "'" + key + "'"; }).join(", "); + return createDiagnostic(ts.Diagnostics.Argument_for_0_option_must_be_Colon_1, "--" + opt.name, namesOfType); + } + function parseCustomTypeOption(opt, value, errors) { + return convertJsonOptionOfCustomType(opt, trimString(value || ""), errors); + } + ts.parseCustomTypeOption = parseCustomTypeOption; + function parseListTypeOption(opt, value, errors) { + if (value === void 0) { value = ""; } + value = trimString(value); + if (ts.startsWith(value, "-")) { + return undefined; + } + if (value === "") { + return []; + } + var values = value.split(","); + switch (opt.element.type) { + case "number": + return ts.map(values, parseInt); + case "string": + return ts.map(values, function (v) { return v || ""; }); + default: + return ts.mapDefined(values, function (v) { return parseCustomTypeOption(opt.element, v, errors); }); + } + } + ts.parseListTypeOption = parseListTypeOption; + function parseCommandLineWorker(getOptionNameMap, _a, commandLine, readFile) { + var unknownOptionDiagnostic = _a[0], optionTypeMismatchDiagnostic = _a[1]; + var options = {}; + var fileNames = []; + var errors = []; + parseStrings(commandLine); + return { + options: options, + fileNames: fileNames, + errors: errors + }; + function parseStrings(args) { + var i = 0; + while (i < args.length) { + var s = args[i]; + i++; + if (s.charCodeAt(0) === 64) { + parseResponseFile(s.slice(1)); + } + else if (s.charCodeAt(0) === 45) { + var opt = getOptionDeclarationFromName(getOptionNameMap, s.slice(s.charCodeAt(1) === 45 ? 2 : 1), true); + if (opt) { + if (opt.isTSConfigOnly) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_can_only_be_specified_in_tsconfig_json_file, opt.name)); + } + else { + if (!args[i] && opt.type !== "boolean") { + errors.push(ts.createCompilerDiagnostic(optionTypeMismatchDiagnostic, opt.name)); + } + switch (opt.type) { + case "number": + options[opt.name] = parseInt(args[i]); + i++; + break; + case "boolean": + var optValue = args[i]; + options[opt.name] = optValue !== "false"; + if (optValue === "false" || optValue === "true") { + i++; + } + break; + case "string": + options[opt.name] = args[i] || ""; + i++; + break; + case "list": + var result = parseListTypeOption(opt, args[i], errors); + options[opt.name] = result || []; + if (result) { + i++; + } + break; + default: + options[opt.name] = parseCustomTypeOption(opt, args[i], errors); + i++; + break; + } + } + } + else { + errors.push(ts.createCompilerDiagnostic(unknownOptionDiagnostic, s)); + } + } + else { + fileNames.push(s); + } + } + } + function parseResponseFile(fileName) { + var text = readFile ? readFile(fileName) : ts.sys.readFile(fileName); + if (!text) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_not_found, fileName)); + return; + } + var args = []; + var pos = 0; + while (true) { + while (pos < text.length && text.charCodeAt(pos) <= 32) + pos++; + if (pos >= text.length) + break; + var start = pos; + if (text.charCodeAt(start) === 34) { + pos++; + while (pos < text.length && text.charCodeAt(pos) !== 34) + pos++; + if (pos < text.length) { + args.push(text.substring(start + 1, pos)); + pos++; + } + else { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unterminated_quoted_string_in_response_file_0, fileName)); + } + } + else { + while (text.charCodeAt(pos) > 32) + pos++; + args.push(text.substring(start, pos)); + } + } + parseStrings(args); + } + } + function parseCommandLine(commandLine, readFile) { + return parseCommandLineWorker(getOptionNameMap, [ + ts.Diagnostics.Unknown_compiler_option_0, + ts.Diagnostics.Compiler_option_0_expects_an_argument + ], commandLine, readFile); + } + ts.parseCommandLine = parseCommandLine; + function getOptionFromName(optionName, allowShort) { + return getOptionDeclarationFromName(getOptionNameMap, optionName, allowShort); + } + ts.getOptionFromName = getOptionFromName; + function getOptionDeclarationFromName(getOptionNameMap, optionName, allowShort) { + if (allowShort === void 0) { allowShort = false; } + optionName = optionName.toLowerCase(); + var _a = getOptionNameMap(), optionNameMap = _a.optionNameMap, shortOptionNames = _a.shortOptionNames; + if (allowShort) { + var short = shortOptionNames.get(optionName); + if (short !== undefined) { + optionName = short; + } + } + return optionNameMap.get(optionName); + } + function parseBuildCommand(args) { + var buildOptionNameMap; + var returnBuildOptionNameMap = function () { return (buildOptionNameMap || (buildOptionNameMap = createOptionNameMap(ts.buildOpts))); }; + var _a = parseCommandLineWorker(returnBuildOptionNameMap, [ + ts.Diagnostics.Unknown_build_option_0, + ts.Diagnostics.Build_option_0_requires_a_value_of_type_1 + ], args), options = _a.options, projects = _a.fileNames, errors = _a.errors; + var buildOptions = options; + if (projects.length === 0) { + projects.push("."); + } + if (buildOptions.clean && buildOptions.force) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "force")); + } + if (buildOptions.clean && buildOptions.verbose) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "verbose")); + } + if (buildOptions.clean && buildOptions.watch) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "watch")); + } + if (buildOptions.watch && buildOptions.dry) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "watch", "dry")); + } + return { buildOptions: buildOptions, projects: projects, errors: errors }; + } + ts.parseBuildCommand = parseBuildCommand; + function getDiagnosticText(_message) { + var _args = []; + for (var _i = 1; _i < arguments.length; _i++) { + _args[_i - 1] = arguments[_i]; + } + var diagnostic = ts.createCompilerDiagnostic.apply(undefined, arguments); + return diagnostic.messageText; + } + function printVersion() { + ts.sys.write(getDiagnosticText(ts.Diagnostics.Version_0, ts.version) + ts.sys.newLine); + } + ts.printVersion = printVersion; + function printHelp(optionsList, syntaxPrefix) { + if (syntaxPrefix === void 0) { syntaxPrefix = ""; } + var output = []; + var syntaxLength = getDiagnosticText(ts.Diagnostics.Syntax_Colon_0, "").length; + var examplesLength = getDiagnosticText(ts.Diagnostics.Examples_Colon_0, "").length; + var marginLength = Math.max(syntaxLength, examplesLength); + var syntax = makePadding(marginLength - syntaxLength); + syntax += "tsc " + syntaxPrefix + "[" + getDiagnosticText(ts.Diagnostics.options) + "] [" + getDiagnosticText(ts.Diagnostics.file) + "...]"; + output.push(getDiagnosticText(ts.Diagnostics.Syntax_Colon_0, syntax)); + output.push(ts.sys.newLine + ts.sys.newLine); + var padding = makePadding(marginLength); + output.push(getDiagnosticText(ts.Diagnostics.Examples_Colon_0, makePadding(marginLength - examplesLength) + "tsc hello.ts") + ts.sys.newLine); + output.push(padding + "tsc --outFile file.js file.ts" + ts.sys.newLine); + output.push(padding + "tsc @args.txt" + ts.sys.newLine); + output.push(padding + "tsc --build tsconfig.json" + ts.sys.newLine); + output.push(ts.sys.newLine); + output.push(getDiagnosticText(ts.Diagnostics.Options_Colon) + ts.sys.newLine); + marginLength = 0; + var usageColumn = []; + var descriptionColumn = []; + var optionsDescriptionMap = ts.createMap(); + for (var _i = 0, optionsList_1 = optionsList; _i < optionsList_1.length; _i++) { + var option = optionsList_1[_i]; + if (!option.description) { + continue; + } + var usageText_1 = " "; + if (option.shortName) { + usageText_1 += "-" + option.shortName; + usageText_1 += getParamType(option); + usageText_1 += ", "; + } + usageText_1 += "--" + option.name; + usageText_1 += getParamType(option); + usageColumn.push(usageText_1); + var description = void 0; + if (option.name === "lib") { + description = getDiagnosticText(option.description); + var element = option.element; + var typeMap = element.type; + optionsDescriptionMap.set(description, ts.arrayFrom(typeMap.keys()).map(function (key) { return "'" + key + "'"; })); + } + else { + description = getDiagnosticText(option.description); + } + descriptionColumn.push(description); + marginLength = Math.max(usageText_1.length, marginLength); + } + var usageText = " @<" + getDiagnosticText(ts.Diagnostics.file) + ">"; + usageColumn.push(usageText); + descriptionColumn.push(getDiagnosticText(ts.Diagnostics.Insert_command_line_options_and_files_from_a_file)); + marginLength = Math.max(usageText.length, marginLength); + for (var i = 0; i < usageColumn.length; i++) { + var usage = usageColumn[i]; + var description = descriptionColumn[i]; + var kindsList = optionsDescriptionMap.get(description); + output.push(usage + makePadding(marginLength - usage.length + 2) + description + ts.sys.newLine); + if (kindsList) { + output.push(makePadding(marginLength + 4)); + for (var _a = 0, kindsList_1 = kindsList; _a < kindsList_1.length; _a++) { + var kind = kindsList_1[_a]; + output.push(kind + " "); + } + output.push(ts.sys.newLine); + } + } + for (var _b = 0, output_1 = output; _b < output_1.length; _b++) { + var line = output_1[_b]; + ts.sys.write(line); + } + return; + function getParamType(option) { + if (option.paramType !== undefined) { + return " " + getDiagnosticText(option.paramType); + } + return ""; + } + function makePadding(paddingLength) { + return Array(paddingLength + 1).join(" "); + } + } + ts.printHelp = printHelp; + function getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host) { + var configFileText; + try { + configFileText = host.readFile(configFileName); + } + catch (e) { + var error = ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, configFileName, e.message); + host.onUnRecoverableConfigFileDiagnostic(error); + return undefined; + } + if (!configFileText) { + var error = ts.createCompilerDiagnostic(ts.Diagnostics.File_0_not_found, configFileName); + host.onUnRecoverableConfigFileDiagnostic(error); + return undefined; + } + var result = ts.parseJsonText(configFileName, configFileText); + var cwd = host.getCurrentDirectory(); + result.path = ts.toPath(configFileName, cwd, ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames)); + result.resolvedPath = result.path; + result.originalFileName = result.fileName; + return parseJsonSourceFileConfigFileContent(result, host, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), cwd), optionsToExtend, ts.getNormalizedAbsolutePath(configFileName, cwd)); + } + ts.getParsedCommandLineOfConfigFile = getParsedCommandLineOfConfigFile; + function readConfigFile(fileName, readFile) { + var textOrDiagnostic = tryReadFile(fileName, readFile); + return ts.isString(textOrDiagnostic) ? parseConfigFileTextToJson(fileName, textOrDiagnostic) : { config: {}, error: textOrDiagnostic }; + } + ts.readConfigFile = readConfigFile; + function parseConfigFileTextToJson(fileName, jsonText) { + var jsonSourceFile = ts.parseJsonText(fileName, jsonText); + return { + config: convertToObject(jsonSourceFile, jsonSourceFile.parseDiagnostics), + error: jsonSourceFile.parseDiagnostics.length ? jsonSourceFile.parseDiagnostics[0] : undefined + }; + } + ts.parseConfigFileTextToJson = parseConfigFileTextToJson; + function readJsonConfigFile(fileName, readFile) { + var textOrDiagnostic = tryReadFile(fileName, readFile); + return ts.isString(textOrDiagnostic) ? ts.parseJsonText(fileName, textOrDiagnostic) : { parseDiagnostics: [textOrDiagnostic] }; + } + ts.readJsonConfigFile = readJsonConfigFile; + function tryReadFile(fileName, readFile) { + var text; + try { + text = readFile(fileName); + } + catch (e) { + return ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, e.message); + } + return text === undefined ? ts.createCompilerDiagnostic(ts.Diagnostics.The_specified_path_does_not_exist_Colon_0, fileName) : text; + } + function commandLineOptionsToMap(options) { + return ts.arrayToMap(options, function (option) { return option.name; }); + } + var _tsconfigRootOptions; + function getTsconfigRootOptionsMap() { + if (_tsconfigRootOptions === undefined) { + _tsconfigRootOptions = { + name: undefined, + type: "object", + elementOptions: commandLineOptionsToMap([ + { + name: "compilerOptions", + type: "object", + elementOptions: commandLineOptionsToMap(ts.optionDeclarations), + extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_compiler_option_0 + }, + { + name: "typingOptions", + type: "object", + elementOptions: commandLineOptionsToMap(ts.typeAcquisitionDeclarations), + extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_type_acquisition_option_0 + }, + { + name: "typeAcquisition", + type: "object", + elementOptions: commandLineOptionsToMap(ts.typeAcquisitionDeclarations), + extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_type_acquisition_option_0 + }, + { + name: "extends", + type: "string" + }, + { + name: "references", + type: "list", + element: { + name: "references", + type: "object" + } + }, + { + name: "files", + type: "list", + element: { + name: "files", + type: "string" + } + }, + { + name: "include", + type: "list", + element: { + name: "include", + type: "string" + } + }, + { + name: "exclude", + type: "list", + element: { + name: "exclude", + type: "string" + } + }, + ts.compileOnSaveCommandLineOption + ]) + }; + } + return _tsconfigRootOptions; + } + function convertToObject(sourceFile, errors) { + return convertToObjectWorker(sourceFile, errors, true, undefined, undefined); + } + ts.convertToObject = convertToObject; + function convertToObjectWorker(sourceFile, errors, returnValue, knownRootOptions, jsonConversionNotifier) { + if (!sourceFile.statements.length) { + return returnValue ? {} : undefined; + } + return convertPropertyValueToJson(sourceFile.statements[0].expression, knownRootOptions); + function isRootOptionMap(knownOptions) { + return knownRootOptions && knownRootOptions.elementOptions === knownOptions; + } + function convertObjectLiteralExpressionToJson(node, knownOptions, extraKeyDiagnosticMessage, parentOption) { + var result = returnValue ? {} : undefined; + for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { + var element = _a[_i]; + if (element.kind !== 275) { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element, ts.Diagnostics.Property_assignment_expected)); + continue; + } + if (element.questionToken) { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.questionToken, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, "?")); + } + if (!isDoubleQuotedString(element.name)) { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, ts.Diagnostics.String_literal_with_double_quotes_expected)); + } + var textOfKey = ts.getTextOfPropertyName(element.name); + var keyText = textOfKey && ts.unescapeLeadingUnderscores(textOfKey); + var option = keyText && knownOptions ? knownOptions.get(keyText) : undefined; + if (keyText && extraKeyDiagnosticMessage && !option) { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, extraKeyDiagnosticMessage, keyText)); + } + var value = convertPropertyValueToJson(element.initializer, option); + if (typeof keyText !== "undefined") { + if (returnValue) { + result[keyText] = value; + } + if (jsonConversionNotifier && + (parentOption || isRootOptionMap(knownOptions))) { + var isValidOptionValue = isCompilerOptionsValue(option, value); + if (parentOption) { + if (isValidOptionValue) { + jsonConversionNotifier.onSetValidOptionKeyValueInParent(parentOption, option, value); + } + } + else if (isRootOptionMap(knownOptions)) { + if (isValidOptionValue) { + jsonConversionNotifier.onSetValidOptionKeyValueInRoot(keyText, element.name, value, element.initializer); + } + else if (!option) { + jsonConversionNotifier.onSetUnknownOptionKeyValueInRoot(keyText, element.name, value, element.initializer); + } + } + } + } + } + return result; + } + function convertArrayLiteralExpressionToJson(elements, elementOption) { + if (!returnValue) { + return elements.forEach(function (element) { return convertPropertyValueToJson(element, elementOption); }); + } + return ts.filter(elements.map(function (element) { return convertPropertyValueToJson(element, elementOption); }), function (v) { return v !== undefined; }); + } + function convertPropertyValueToJson(valueExpression, option) { + switch (valueExpression.kind) { + case 102: + reportInvalidOptionValue(option && option.type !== "boolean"); + return true; + case 87: + reportInvalidOptionValue(option && option.type !== "boolean"); + return false; + case 96: + reportInvalidOptionValue(option && option.name === "extends"); + return null; + case 10: + if (!isDoubleQuotedString(valueExpression)) { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, ts.Diagnostics.String_literal_with_double_quotes_expected)); + } + reportInvalidOptionValue(option && (ts.isString(option.type) && option.type !== "string")); + var text = valueExpression.text; + if (option && !ts.isString(option.type)) { + var customOption = option; + if (!customOption.type.has(text.toLowerCase())) { + errors.push(createDiagnosticForInvalidCustomType(customOption, function (message, arg0, arg1) { return ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, message, arg0, arg1); })); + } + } + return text; + case 8: + reportInvalidOptionValue(option && option.type !== "number"); + return Number(valueExpression.text); + case 202: + if (valueExpression.operator !== 39 || valueExpression.operand.kind !== 8) { + break; + } + reportInvalidOptionValue(option && option.type !== "number"); + return -Number(valueExpression.operand.text); + case 188: + reportInvalidOptionValue(option && option.type !== "object"); + var objectLiteralExpression = valueExpression; + if (option) { + var _a = option, elementOptions = _a.elementOptions, extraKeyDiagnosticMessage = _a.extraKeyDiagnosticMessage, optionName = _a.name; + return convertObjectLiteralExpressionToJson(objectLiteralExpression, elementOptions, extraKeyDiagnosticMessage, optionName); + } + else { + return convertObjectLiteralExpressionToJson(objectLiteralExpression, undefined, undefined, undefined); + } + case 187: + reportInvalidOptionValue(option && option.type !== "list"); + return convertArrayLiteralExpressionToJson(valueExpression.elements, option && option.element); + } + if (option) { + reportInvalidOptionValue(true); + } + else { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, ts.Diagnostics.Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_literal)); + } + return undefined; + function reportInvalidOptionValue(isError) { + if (isError) { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, option.name, getCompilerOptionValueTypeString(option))); + } + } + } + function isDoubleQuotedString(node) { + return ts.isStringLiteral(node) && ts.isStringDoubleQuoted(node, sourceFile); + } + } + ts.convertToObjectWorker = convertToObjectWorker; + function getCompilerOptionValueTypeString(option) { + return option.type === "list" ? + "Array" : + ts.isString(option.type) ? option.type : "string"; + } + function isCompilerOptionsValue(option, value) { + if (option) { + if (isNullOrUndefined(value)) + return true; + if (option.type === "list") { + return ts.isArray(value); + } + var expectedType = ts.isString(option.type) ? option.type : "string"; + return typeof value === expectedType; + } + return false; + } + function convertToTSConfig(configParseResult, configFileName, host) { + var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); + var files = ts.map(ts.filter(configParseResult.fileNames, (!configParseResult.configFileSpecs || !configParseResult.configFileSpecs.validatedIncludeSpecs) ? function (_) { return true; } : matchesSpecs(configFileName, configParseResult.configFileSpecs.validatedIncludeSpecs, configParseResult.configFileSpecs.validatedExcludeSpecs)), function (f) { return ts.getRelativePathFromFile(ts.getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), ts.getNormalizedAbsolutePath(f, host.getCurrentDirectory()), getCanonicalFileName); }); + var optionMap = serializeCompilerOptions(configParseResult.options, { configFilePath: ts.getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), useCaseSensitiveFileNames: host.useCaseSensitiveFileNames }); + var config = __assign({ compilerOptions: __assign({}, ts.arrayFrom(optionMap.entries()).reduce(function (prev, cur) { + var _a; + return (__assign({}, prev, (_a = {}, _a[cur[0]] = cur[1], _a))); + }, {}), { showConfig: undefined, configFile: undefined, configFilePath: undefined, help: undefined, init: undefined, listFiles: undefined, listEmittedFiles: undefined, project: undefined }), references: ts.map(configParseResult.projectReferences, function (r) { return (__assign({}, r, { path: r.originalPath, originalPath: undefined })); }), files: ts.length(files) ? files : undefined }, (configParseResult.configFileSpecs ? { + include: filterSameAsDefaultInclude(configParseResult.configFileSpecs.validatedIncludeSpecs), + exclude: configParseResult.configFileSpecs.validatedExcludeSpecs + } : {}), { compilerOnSave: !!configParseResult.compileOnSave ? true : undefined }); + return config; + } + ts.convertToTSConfig = convertToTSConfig; + function filterSameAsDefaultInclude(specs) { + if (!ts.length(specs)) + return undefined; + if (ts.length(specs) !== 1) + return specs; + if (specs[0] === "**/*") + return undefined; + return specs; + } + function matchesSpecs(path, includeSpecs, excludeSpecs) { + if (!includeSpecs) + return function (_) { return true; }; + var patterns = ts.getFileMatcherPatterns(path, excludeSpecs, includeSpecs, ts.sys.useCaseSensitiveFileNames, ts.sys.getCurrentDirectory()); + var excludeRe = patterns.excludePattern && ts.getRegexFromPattern(patterns.excludePattern, ts.sys.useCaseSensitiveFileNames); + var includeRe = patterns.includeFilePattern && ts.getRegexFromPattern(patterns.includeFilePattern, ts.sys.useCaseSensitiveFileNames); + if (includeRe) { + if (excludeRe) { + return function (path) { return !(includeRe.test(path) && !excludeRe.test(path)); }; + } + return function (path) { return !includeRe.test(path); }; + } + if (excludeRe) { + return function (path) { return excludeRe.test(path); }; + } + return function (_) { return true; }; + } + function getCustomTypeMapOfCommandLineOption(optionDefinition) { + if (optionDefinition.type === "string" || optionDefinition.type === "number" || optionDefinition.type === "boolean") { + return undefined; + } + else if (optionDefinition.type === "list") { + return getCustomTypeMapOfCommandLineOption(optionDefinition.element); + } + else { + return optionDefinition.type; + } + } + function getNameOfCompilerOptionValue(value, customTypeMap) { + return ts.forEachEntry(customTypeMap, function (mapValue, key) { + if (mapValue === value) { + return key; + } + }); + } + function serializeCompilerOptions(options, pathOptions) { + var result = ts.createMap(); + var optionsNameMap = getOptionNameMap().optionNameMap; + var getCanonicalFileName = pathOptions && ts.createGetCanonicalFileName(pathOptions.useCaseSensitiveFileNames); + var _loop_3 = function (name) { + if (ts.hasProperty(options, name)) { + if (optionsNameMap.has(name) && optionsNameMap.get(name).category === ts.Diagnostics.Command_line_Options) { + return "continue"; + } + var value = options[name]; + var optionDefinition = optionsNameMap.get(name.toLowerCase()); + if (optionDefinition) { + var customTypeMap_1 = getCustomTypeMapOfCommandLineOption(optionDefinition); + if (!customTypeMap_1) { + if (pathOptions && optionDefinition.isFilePath) { + result.set(name, ts.getRelativePathFromFile(pathOptions.configFilePath, ts.getNormalizedAbsolutePath(value, ts.getDirectoryPath(pathOptions.configFilePath)), getCanonicalFileName)); + } + else { + result.set(name, value); + } + } + else { + if (optionDefinition.type === "list") { + result.set(name, value.map(function (element) { return getNameOfCompilerOptionValue(element, customTypeMap_1); })); + } + else { + result.set(name, getNameOfCompilerOptionValue(value, customTypeMap_1)); + } + } + } + } + }; + for (var name in options) { + _loop_3(name); + } + return result; + } + function generateTSConfig(options, fileNames, newLine) { + var compilerOptions = ts.extend(options, ts.defaultInitCompilerOptions); + var compilerOptionsMap = serializeCompilerOptions(compilerOptions); + return writeConfigurations(); + function getDefaultValueForOption(option) { + switch (option.type) { + case "number": + return 1; + case "boolean": + return true; + case "string": + return option.isFilePath ? "./" : ""; + case "list": + return []; + case "object": + return {}; + default: + return option.type.keys().next().value; + } + } + function makePadding(paddingLength) { + return Array(paddingLength + 1).join(" "); + } + function isAllowedOption(_a) { + var category = _a.category, name = _a.name; + return category !== undefined + && category !== ts.Diagnostics.Command_line_Options + && (category !== ts.Diagnostics.Advanced_Options || compilerOptionsMap.has(name)); + } + function writeConfigurations() { + var categorizedOptions = ts.createMultiMap(); + for (var _i = 0, optionDeclarations_1 = ts.optionDeclarations; _i < optionDeclarations_1.length; _i++) { + var option = optionDeclarations_1[_i]; + var category = option.category; + if (isAllowedOption(option)) { + categorizedOptions.add(ts.getLocaleSpecificMessage(category), option); + } + } + var marginLength = 0; + var seenKnownKeys = 0; + var nameColumn = []; + var descriptionColumn = []; + categorizedOptions.forEach(function (options, category) { + if (nameColumn.length !== 0) { + nameColumn.push(""); + descriptionColumn.push(""); + } + nameColumn.push("/* " + category + " */"); + descriptionColumn.push(""); + for (var _i = 0, options_1 = options; _i < options_1.length; _i++) { + var option = options_1[_i]; + var optionName = void 0; + if (compilerOptionsMap.has(option.name)) { + optionName = "\"" + option.name + "\": " + JSON.stringify(compilerOptionsMap.get(option.name)) + ((seenKnownKeys += 1) === compilerOptionsMap.size ? "" : ","); + } + else { + optionName = "// \"" + option.name + "\": " + JSON.stringify(getDefaultValueForOption(option)) + ","; + } + nameColumn.push(optionName); + descriptionColumn.push("/* " + (option.description && ts.getLocaleSpecificMessage(option.description) || option.name) + " */"); + marginLength = Math.max(optionName.length, marginLength); + } + }); + var tab = makePadding(2); + var result = []; + result.push("{"); + result.push(tab + "\"compilerOptions\": {"); + for (var i = 0; i < nameColumn.length; i++) { + var optionName = nameColumn[i]; + var description = descriptionColumn[i]; + result.push(optionName && "" + tab + tab + optionName + (description && (makePadding(marginLength - optionName.length + 2) + description))); + } + if (fileNames.length) { + result.push(tab + "},"); + result.push(tab + "\"files\": ["); + for (var i = 0; i < fileNames.length; i++) { + result.push("" + tab + tab + JSON.stringify(fileNames[i]) + (i === fileNames.length - 1 ? "" : ",")); + } + result.push(tab + "]"); + } + else { + result.push(tab + "}"); + } + result.push("}"); + return result.join(newLine); + } + } + ts.generateTSConfig = generateTSConfig; + function parseJsonConfigFileContent(json, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions) { + return parseJsonConfigFileContentWorker(json, undefined, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions); + } + ts.parseJsonConfigFileContent = parseJsonConfigFileContent; + function parseJsonSourceFileConfigFileContent(sourceFile, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions) { + return parseJsonConfigFileContentWorker(undefined, sourceFile, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions); + } + ts.parseJsonSourceFileConfigFileContent = parseJsonSourceFileConfigFileContent; + function setConfigFileInOptions(options, configFile) { + if (configFile) { + Object.defineProperty(options, "configFile", { enumerable: false, writable: false, value: configFile }); + } + } + ts.setConfigFileInOptions = setConfigFileInOptions; + function isNullOrUndefined(x) { + return x === undefined || x === null; + } + function directoryOfCombinedPath(fileName, basePath) { + return ts.getDirectoryPath(ts.getNormalizedAbsolutePath(fileName, basePath)); + } + function parseJsonConfigFileContentWorker(json, sourceFile, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions) { + if (existingOptions === void 0) { existingOptions = {}; } + if (resolutionStack === void 0) { resolutionStack = []; } + if (extraFileExtensions === void 0) { extraFileExtensions = []; } + ts.Debug.assert((json === undefined && sourceFile !== undefined) || (json !== undefined && sourceFile === undefined)); + var errors = []; + var parsedConfig = parseConfig(json, sourceFile, host, basePath, configFileName, resolutionStack, errors); + var raw = parsedConfig.raw; + var options = ts.extend(existingOptions, parsedConfig.options || {}); + options.configFilePath = configFileName && ts.normalizeSlashes(configFileName); + setConfigFileInOptions(options, sourceFile); + var projectReferences; + var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories, spec = _a.spec; + return { + options: options, + fileNames: fileNames, + projectReferences: projectReferences, + typeAcquisition: parsedConfig.typeAcquisition || getDefaultTypeAcquisition(), + raw: raw, + errors: errors, + wildcardDirectories: wildcardDirectories, + compileOnSave: !!raw.compileOnSave, + configFileSpecs: spec + }; + function getFileNames() { + var filesSpecs; + if (ts.hasProperty(raw, "files") && !isNullOrUndefined(raw.files)) { + if (ts.isArray(raw.files)) { + filesSpecs = raw.files; + var hasReferences = ts.hasProperty(raw, "references") && !isNullOrUndefined(raw.references); + var hasZeroOrNoReferences = !hasReferences || raw.references.length === 0; + var hasExtends = ts.hasProperty(raw, "extends"); + if (filesSpecs.length === 0 && hasZeroOrNoReferences && !hasExtends) { + if (sourceFile) { + var fileName = configFileName || "tsconfig.json"; + var diagnosticMessage = ts.Diagnostics.The_files_list_in_config_file_0_is_empty; + var nodeValue = ts.firstDefined(ts.getTsConfigPropArray(sourceFile, "files"), function (property) { return property.initializer; }); + var error = nodeValue + ? ts.createDiagnosticForNodeInSourceFile(sourceFile, nodeValue, diagnosticMessage, fileName) + : ts.createCompilerDiagnostic(diagnosticMessage, fileName); + errors.push(error); + } + else { + createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json"); + } + } + } + else { + createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "files", "Array"); + } + } + var includeSpecs; + if (ts.hasProperty(raw, "include") && !isNullOrUndefined(raw.include)) { + if (ts.isArray(raw.include)) { + includeSpecs = raw.include; + } + else { + createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "include", "Array"); + } + } + var excludeSpecs; + if (ts.hasProperty(raw, "exclude") && !isNullOrUndefined(raw.exclude)) { + if (ts.isArray(raw.exclude)) { + excludeSpecs = raw.exclude; + } + else { + createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "exclude", "Array"); + } + } + else if (raw.compilerOptions) { + var outDir = raw.compilerOptions.outDir; + var declarationDir = raw.compilerOptions.declarationDir; + if (outDir || declarationDir) { + excludeSpecs = [outDir, declarationDir].filter(function (d) { return !!d; }); + } + } + if (filesSpecs === undefined && includeSpecs === undefined) { + includeSpecs = ["**/*"]; + } + var result = matchFileNames(filesSpecs, includeSpecs, excludeSpecs, configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath, options, host, errors, extraFileExtensions, sourceFile); + if (shouldReportNoInputFiles(result, canJsonReportNoInutFiles(raw), resolutionStack)) { + errors.push(getErrorForNoInputFiles(result.spec, configFileName)); + } + if (ts.hasProperty(raw, "references") && !isNullOrUndefined(raw.references)) { + if (ts.isArray(raw.references)) { + for (var _i = 0, _a = raw.references; _i < _a.length; _i++) { + var ref = _a[_i]; + if (typeof ref.path !== "string") { + createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "reference.path", "string"); + } + else { + (projectReferences || (projectReferences = [])).push({ + path: ts.getNormalizedAbsolutePath(ref.path, basePath), + originalPath: ref.path, + prepend: ref.prepend, + circular: ref.circular + }); + } + } + } + else { + createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "references", "Array"); + } + } + return result; + } + function createCompilerDiagnosticOnlyIfJson(message, arg0, arg1) { + if (!sourceFile) { + errors.push(ts.createCompilerDiagnostic(message, arg0, arg1)); + } + } + } + function isErrorNoInputFiles(error) { + return error.code === ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2.code; + } + function getErrorForNoInputFiles(_a, configFileName) { + var includeSpecs = _a.includeSpecs, excludeSpecs = _a.excludeSpecs; + return ts.createCompilerDiagnostic(ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2, configFileName || "tsconfig.json", JSON.stringify(includeSpecs || []), JSON.stringify(excludeSpecs || [])); + } + function shouldReportNoInputFiles(result, canJsonReportNoInutFiles, resolutionStack) { + return result.fileNames.length === 0 && canJsonReportNoInutFiles && (!resolutionStack || resolutionStack.length === 0); + } + function canJsonReportNoInutFiles(raw) { + return !ts.hasProperty(raw, "files") && !ts.hasProperty(raw, "references"); + } + ts.canJsonReportNoInutFiles = canJsonReportNoInutFiles; + function updateErrorForNoInputFiles(result, configFileName, configFileSpecs, configParseDiagnostics, canJsonReportNoInutFiles) { + var existingErrors = configParseDiagnostics.length; + if (shouldReportNoInputFiles(result, canJsonReportNoInutFiles)) { + configParseDiagnostics.push(getErrorForNoInputFiles(configFileSpecs, configFileName)); + } + else { + ts.filterMutate(configParseDiagnostics, function (error) { return !isErrorNoInputFiles(error); }); + } + return existingErrors !== configParseDiagnostics.length; + } + ts.updateErrorForNoInputFiles = updateErrorForNoInputFiles; + function isSuccessfulParsedTsconfig(value) { + return !!value.options; + } + function parseConfig(json, sourceFile, host, basePath, configFileName, resolutionStack, errors) { + basePath = ts.normalizeSlashes(basePath); + var resolvedPath = ts.getNormalizedAbsolutePath(configFileName || "", basePath); + if (resolutionStack.indexOf(resolvedPath) >= 0) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Circularity_detected_while_resolving_configuration_Colon_0, resolutionStack.concat([resolvedPath]).join(" -> "))); + return { raw: json || convertToObject(sourceFile, errors) }; + } + var ownConfig = json ? + parseOwnConfigOfJson(json, host, basePath, configFileName, errors) : + parseOwnConfigOfJsonSourceFile(sourceFile, host, basePath, configFileName, errors); + if (ownConfig.extendedConfigPath) { + resolutionStack = resolutionStack.concat([resolvedPath]); + var extendedConfig = getExtendedConfig(sourceFile, ownConfig.extendedConfigPath, host, basePath, resolutionStack, errors); + if (extendedConfig && isSuccessfulParsedTsconfig(extendedConfig)) { + var baseRaw_1 = extendedConfig.raw; + var raw_1 = ownConfig.raw; + var setPropertyInRawIfNotUndefined = function (propertyName) { + var value = raw_1[propertyName] || baseRaw_1[propertyName]; + if (value) { + raw_1[propertyName] = value; + } + }; + setPropertyInRawIfNotUndefined("include"); + setPropertyInRawIfNotUndefined("exclude"); + setPropertyInRawIfNotUndefined("files"); + if (raw_1.compileOnSave === undefined) { + raw_1.compileOnSave = baseRaw_1.compileOnSave; + } + ownConfig.options = ts.assign({}, extendedConfig.options, ownConfig.options); + } + } + return ownConfig; + } + function parseOwnConfigOfJson(json, host, basePath, configFileName, errors) { + if (ts.hasProperty(json, "excludes")) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude)); + } + var options = convertCompilerOptionsFromJsonWorker(json.compilerOptions, basePath, errors, configFileName); + var typeAcquisition = convertTypeAcquisitionFromJsonWorker(json.typeAcquisition || json.typingOptions, basePath, errors, configFileName); + json.compileOnSave = convertCompileOnSaveOptionFromJson(json, basePath, errors); + var extendedConfigPath; + if (json.extends) { + if (!ts.isString(json.extends)) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "extends", "string")); + } + else { + var newBase = configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath; + extendedConfigPath = getExtendsConfigPath(json.extends, host, newBase, errors, ts.createCompilerDiagnostic); + } + } + return { raw: json, options: options, typeAcquisition: typeAcquisition, extendedConfigPath: extendedConfigPath }; + } + function parseOwnConfigOfJsonSourceFile(sourceFile, host, basePath, configFileName, errors) { + var options = getDefaultCompilerOptions(configFileName); + var typeAcquisition, typingOptionstypeAcquisition; + var extendedConfigPath; + var optionsIterator = { + onSetValidOptionKeyValueInParent: function (parentOption, option, value) { + ts.Debug.assert(parentOption === "compilerOptions" || parentOption === "typeAcquisition" || parentOption === "typingOptions"); + var currentOption = parentOption === "compilerOptions" ? + options : + parentOption === "typeAcquisition" ? + (typeAcquisition || (typeAcquisition = getDefaultTypeAcquisition(configFileName))) : + (typingOptionstypeAcquisition || (typingOptionstypeAcquisition = getDefaultTypeAcquisition(configFileName))); + currentOption[option.name] = normalizeOptionValue(option, basePath, value); + }, + onSetValidOptionKeyValueInRoot: function (key, _keyNode, value, valueNode) { + switch (key) { + case "extends": + var newBase = configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath; + extendedConfigPath = getExtendsConfigPath(value, host, newBase, errors, function (message, arg0) { + return ts.createDiagnosticForNodeInSourceFile(sourceFile, valueNode, message, arg0); + }); + return; + } + }, + onSetUnknownOptionKeyValueInRoot: function (key, keyNode, _value, _valueNode) { + if (key === "excludes") { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, keyNode, ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude)); + } + } + }; + var json = convertToObjectWorker(sourceFile, errors, true, getTsconfigRootOptionsMap(), optionsIterator); + if (!typeAcquisition) { + if (typingOptionstypeAcquisition) { + typeAcquisition = (typingOptionstypeAcquisition.enableAutoDiscovery !== undefined) ? + { + enable: typingOptionstypeAcquisition.enableAutoDiscovery, + include: typingOptionstypeAcquisition.include, + exclude: typingOptionstypeAcquisition.exclude + } : + typingOptionstypeAcquisition; + } + else { + typeAcquisition = getDefaultTypeAcquisition(configFileName); + } + } + return { raw: json, options: options, typeAcquisition: typeAcquisition, extendedConfigPath: extendedConfigPath }; + } + function getExtendsConfigPath(extendedConfig, host, basePath, errors, createDiagnostic) { + extendedConfig = ts.normalizeSlashes(extendedConfig); + if (ts.isRootedDiskPath(extendedConfig) || ts.startsWith(extendedConfig, "./") || ts.startsWith(extendedConfig, "../")) { + var extendedConfigPath = ts.getNormalizedAbsolutePath(extendedConfig, basePath); + if (!host.fileExists(extendedConfigPath) && !ts.endsWith(extendedConfigPath, ".json")) { + extendedConfigPath = extendedConfigPath + ".json"; + if (!host.fileExists(extendedConfigPath)) { + errors.push(createDiagnostic(ts.Diagnostics.File_0_does_not_exist, extendedConfig)); + return undefined; + } + } + return extendedConfigPath; + } + var resolved = ts.nodeModuleNameResolver(extendedConfig, ts.combinePaths(basePath, "tsconfig.json"), { moduleResolution: ts.ModuleResolutionKind.NodeJs }, host, undefined, undefined, true); + if (resolved.resolvedModule) { + return resolved.resolvedModule.resolvedFileName; + } + errors.push(createDiagnostic(ts.Diagnostics.File_0_does_not_exist, extendedConfig)); + return undefined; + } + function getExtendedConfig(sourceFile, extendedConfigPath, host, basePath, resolutionStack, errors) { + var _a; + var extendedResult = readJsonConfigFile(extendedConfigPath, function (path) { return host.readFile(path); }); + if (sourceFile) { + sourceFile.extendedSourceFiles = [extendedResult.fileName]; + } + if (extendedResult.parseDiagnostics.length) { + errors.push.apply(errors, extendedResult.parseDiagnostics); + return undefined; + } + var extendedDirname = ts.getDirectoryPath(extendedConfigPath); + var extendedConfig = parseConfig(undefined, extendedResult, host, extendedDirname, ts.getBaseFileName(extendedConfigPath), resolutionStack, errors); + if (sourceFile && extendedResult.extendedSourceFiles) { + (_a = sourceFile.extendedSourceFiles).push.apply(_a, extendedResult.extendedSourceFiles); + } + if (isSuccessfulParsedTsconfig(extendedConfig)) { + var relativeDifference_1 = ts.convertToRelativePath(extendedDirname, basePath, ts.identity); + var updatePath_1 = function (path) { return ts.isRootedDiskPath(path) ? path : ts.combinePaths(relativeDifference_1, path); }; + var mapPropertiesInRawIfNotUndefined = function (propertyName) { + if (raw_2[propertyName]) { + raw_2[propertyName] = ts.map(raw_2[propertyName], updatePath_1); + } + }; + var raw_2 = extendedConfig.raw; + mapPropertiesInRawIfNotUndefined("include"); + mapPropertiesInRawIfNotUndefined("exclude"); + mapPropertiesInRawIfNotUndefined("files"); + } + return extendedConfig; + } + function convertCompileOnSaveOptionFromJson(jsonOption, basePath, errors) { + if (!ts.hasProperty(jsonOption, ts.compileOnSaveCommandLineOption.name)) { + return false; + } + var result = convertJsonOption(ts.compileOnSaveCommandLineOption, jsonOption.compileOnSave, basePath, errors); + return typeof result === "boolean" && result; + } + function convertCompilerOptionsFromJson(jsonOptions, basePath, configFileName) { + var errors = []; + var options = convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName); + return { options: options, errors: errors }; + } + ts.convertCompilerOptionsFromJson = convertCompilerOptionsFromJson; + function convertTypeAcquisitionFromJson(jsonOptions, basePath, configFileName) { + var errors = []; + var options = convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName); + return { options: options, errors: errors }; + } + ts.convertTypeAcquisitionFromJson = convertTypeAcquisitionFromJson; + function getDefaultCompilerOptions(configFileName) { + var options = configFileName && ts.getBaseFileName(configFileName) === "jsconfig.json" + ? { allowJs: true, maxNodeModuleJsDepth: 2, allowSyntheticDefaultImports: true, skipLibCheck: true, noEmit: true } + : {}; + return options; + } + function convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName) { + var options = getDefaultCompilerOptions(configFileName); + convertOptionsFromJson(ts.optionDeclarations, jsonOptions, basePath, options, ts.Diagnostics.Unknown_compiler_option_0, errors); + if (configFileName) { + options.configFilePath = ts.normalizeSlashes(configFileName); + } + return options; + } + function getDefaultTypeAcquisition(configFileName) { + return { enable: !!configFileName && ts.getBaseFileName(configFileName) === "jsconfig.json", include: [], exclude: [] }; + } + function convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName) { + var options = getDefaultTypeAcquisition(configFileName); + var typeAcquisition = convertEnableAutoDiscoveryToEnable(jsonOptions); + convertOptionsFromJson(ts.typeAcquisitionDeclarations, typeAcquisition, basePath, options, ts.Diagnostics.Unknown_type_acquisition_option_0, errors); + return options; + } + function convertOptionsFromJson(optionDeclarations, jsonOptions, basePath, defaultOptions, diagnosticMessage, errors) { + if (!jsonOptions) { + return; + } + var optionNameMap = commandLineOptionsToMap(optionDeclarations); + for (var id in jsonOptions) { + var opt = optionNameMap.get(id); + if (opt) { + defaultOptions[opt.name] = convertJsonOption(opt, jsonOptions[id], basePath, errors); + } + else { + errors.push(ts.createCompilerDiagnostic(diagnosticMessage, id)); + } + } + } + function convertJsonOption(opt, value, basePath, errors) { + if (isCompilerOptionsValue(opt, value)) { + var optType = opt.type; + if (optType === "list" && ts.isArray(value)) { + return convertJsonOptionOfListType(opt, value, basePath, errors); + } + else if (!ts.isString(optType)) { + return convertJsonOptionOfCustomType(opt, value, errors); + } + return normalizeNonListOptionValue(opt, basePath, value); + } + else { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, opt.name, getCompilerOptionValueTypeString(opt))); + } + } + function normalizeOptionValue(option, basePath, value) { + if (isNullOrUndefined(value)) + return undefined; + if (option.type === "list") { + var listOption_1 = option; + if (listOption_1.element.isFilePath || !ts.isString(listOption_1.element.type)) { + return ts.filter(ts.map(value, function (v) { return normalizeOptionValue(listOption_1.element, basePath, v); }), function (v) { return !!v; }); + } + return value; + } + else if (!ts.isString(option.type)) { + return option.type.get(ts.isString(value) ? value.toLowerCase() : value); + } + return normalizeNonListOptionValue(option, basePath, value); + } + function normalizeNonListOptionValue(option, basePath, value) { + if (option.isFilePath) { + value = ts.normalizePath(ts.combinePaths(basePath, value)); + if (value === "") { + value = "."; + } + } + return value; + } + function convertJsonOptionOfCustomType(opt, value, errors) { + if (isNullOrUndefined(value)) + return undefined; + var key = value.toLowerCase(); + var val = opt.type.get(key); + if (val !== undefined) { + return val; + } + else { + errors.push(createCompilerDiagnosticForInvalidCustomType(opt)); + } + } + function convertJsonOptionOfListType(option, values, basePath, errors) { + return ts.filter(ts.map(values, function (v) { return convertJsonOption(option.element, v, basePath, errors); }), function (v) { return !!v; }); + } + function trimString(s) { + return typeof s.trim === "function" ? s.trim() : s.replace(/^[\s]+|[\s]+$/g, ""); + } + var invalidTrailingRecursionPattern = /(^|\/)\*\*\/?$/; + var invalidDotDotAfterRecursiveWildcardPattern = /(^|\/)\*\*\/(.*\/)?\.\.($|\/)/; + var watchRecursivePattern = /\/[^/]*?[*?][^/]*\//; + var wildcardDirectoryPattern = /^[^*?]*(?=\/[^/]*[*?])/; + function matchFileNames(filesSpecs, includeSpecs, excludeSpecs, basePath, options, host, errors, extraFileExtensions, jsonSourceFile) { + basePath = ts.normalizePath(basePath); + var validatedIncludeSpecs, validatedExcludeSpecs; + if (includeSpecs) { + validatedIncludeSpecs = validateSpecs(includeSpecs, errors, false, jsonSourceFile, "include"); + } + if (excludeSpecs) { + validatedExcludeSpecs = validateSpecs(excludeSpecs, errors, true, jsonSourceFile, "exclude"); + } + var wildcardDirectories = getWildcardDirectories(validatedIncludeSpecs, validatedExcludeSpecs, basePath, host.useCaseSensitiveFileNames); + var spec = { filesSpecs: filesSpecs, includeSpecs: includeSpecs, excludeSpecs: excludeSpecs, validatedIncludeSpecs: validatedIncludeSpecs, validatedExcludeSpecs: validatedExcludeSpecs, wildcardDirectories: wildcardDirectories }; + return getFileNamesFromConfigSpecs(spec, basePath, options, host, extraFileExtensions); + } + function getFileNamesFromConfigSpecs(spec, basePath, options, host, extraFileExtensions) { + if (extraFileExtensions === void 0) { extraFileExtensions = []; } + basePath = ts.normalizePath(basePath); + var keyMapper = host.useCaseSensitiveFileNames ? ts.identity : ts.toLowerCase; + var literalFileMap = ts.createMap(); + var wildcardFileMap = ts.createMap(); + var wildCardJsonFileMap = ts.createMap(); + var filesSpecs = spec.filesSpecs, validatedIncludeSpecs = spec.validatedIncludeSpecs, validatedExcludeSpecs = spec.validatedExcludeSpecs, wildcardDirectories = spec.wildcardDirectories; + var supportedExtensions = ts.getSupportedExtensions(options, extraFileExtensions); + var supportedExtensionsWithJsonIfResolveJsonModule = ts.getSuppoertedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions); + if (filesSpecs) { + for (var _i = 0, filesSpecs_1 = filesSpecs; _i < filesSpecs_1.length; _i++) { + var fileName = filesSpecs_1[_i]; + var file = ts.getNormalizedAbsolutePath(fileName, basePath); + literalFileMap.set(keyMapper(file), file); + } + } + var jsonOnlyIncludeRegexes; + if (validatedIncludeSpecs && validatedIncludeSpecs.length > 0) { + var _loop_4 = function (file) { + if (ts.fileExtensionIs(file, ".json")) { + if (!jsonOnlyIncludeRegexes) { + var includes = validatedIncludeSpecs.filter(function (s) { return ts.endsWith(s, ".json"); }); + var includeFilePatterns = ts.map(ts.getRegularExpressionsForWildcards(includes, basePath, "files"), function (pattern) { return "^" + pattern + "$"; }); + jsonOnlyIncludeRegexes = includeFilePatterns ? includeFilePatterns.map(function (pattern) { return ts.getRegexFromPattern(pattern, host.useCaseSensitiveFileNames); }) : ts.emptyArray; + } + var includeIndex = ts.findIndex(jsonOnlyIncludeRegexes, function (re) { return re.test(file); }); + if (includeIndex !== -1) { + var key_1 = keyMapper(file); + if (!literalFileMap.has(key_1) && !wildCardJsonFileMap.has(key_1)) { + wildCardJsonFileMap.set(key_1, file); + } + } + return "continue"; + } + if (hasFileWithHigherPriorityExtension(file, literalFileMap, wildcardFileMap, supportedExtensions, keyMapper)) { + return "continue"; + } + removeWildcardFilesWithLowerPriorityExtension(file, wildcardFileMap, supportedExtensions, keyMapper); + var key = keyMapper(file); + if (!literalFileMap.has(key) && !wildcardFileMap.has(key)) { + wildcardFileMap.set(key, file); + } + }; + for (var _a = 0, _b = host.readDirectory(basePath, supportedExtensionsWithJsonIfResolveJsonModule, validatedExcludeSpecs, validatedIncludeSpecs, undefined); _a < _b.length; _a++) { + var file = _b[_a]; + _loop_4(file); + } + } + var literalFiles = ts.arrayFrom(literalFileMap.values()); + var wildcardFiles = ts.arrayFrom(wildcardFileMap.values()); + return { + fileNames: literalFiles.concat(wildcardFiles, ts.arrayFrom(wildCardJsonFileMap.values())), + wildcardDirectories: wildcardDirectories, + spec: spec + }; + } + ts.getFileNamesFromConfigSpecs = getFileNamesFromConfigSpecs; + function validateSpecs(specs, errors, allowTrailingRecursion, jsonSourceFile, specKey) { + return specs.filter(function (spec) { + var diag = specToDiagnostic(spec, allowTrailingRecursion); + if (diag !== undefined) { + errors.push(createDiagnostic(diag, spec)); + } + return diag === undefined; + }); + function createDiagnostic(message, spec) { + var element = ts.getTsConfigPropArrayElementValue(jsonSourceFile, specKey, spec); + return element ? + ts.createDiagnosticForNodeInSourceFile(jsonSourceFile, element, message, spec) : + ts.createCompilerDiagnostic(message, spec); + } + } + function specToDiagnostic(spec, allowTrailingRecursion) { + if (!allowTrailingRecursion && invalidTrailingRecursionPattern.test(spec)) { + return ts.Diagnostics.File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0; + } + else if (invalidDotDotAfterRecursiveWildcardPattern.test(spec)) { + return ts.Diagnostics.File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0; + } + } + function getWildcardDirectories(include, exclude, path, useCaseSensitiveFileNames) { + var rawExcludeRegex = ts.getRegularExpressionForWildcard(exclude, path, "exclude"); + var excludeRegex = rawExcludeRegex && new RegExp(rawExcludeRegex, useCaseSensitiveFileNames ? "" : "i"); + var wildcardDirectories = {}; + if (include !== undefined) { + var recursiveKeys = []; + for (var _i = 0, include_1 = include; _i < include_1.length; _i++) { + var file = include_1[_i]; + var spec = ts.normalizePath(ts.combinePaths(path, file)); + if (excludeRegex && excludeRegex.test(spec)) { + continue; + } + var match = getWildcardDirectoryFromSpec(spec, useCaseSensitiveFileNames); + if (match) { + var key = match.key, flags = match.flags; + var existingFlags = wildcardDirectories[key]; + if (existingFlags === undefined || existingFlags < flags) { + wildcardDirectories[key] = flags; + if (flags === 1) { + recursiveKeys.push(key); + } + } + } + } + for (var key in wildcardDirectories) { + if (ts.hasProperty(wildcardDirectories, key)) { + for (var _a = 0, recursiveKeys_1 = recursiveKeys; _a < recursiveKeys_1.length; _a++) { + var recursiveKey = recursiveKeys_1[_a]; + if (key !== recursiveKey && ts.containsPath(recursiveKey, key, path, !useCaseSensitiveFileNames)) { + delete wildcardDirectories[key]; + } + } + } + } + } + return wildcardDirectories; + } + function getWildcardDirectoryFromSpec(spec, useCaseSensitiveFileNames) { + var match = wildcardDirectoryPattern.exec(spec); + if (match) { + return { + key: useCaseSensitiveFileNames ? match[0] : match[0].toLowerCase(), + flags: watchRecursivePattern.test(spec) ? 1 : 0 + }; + } + if (ts.isImplicitGlob(spec)) { + return { key: spec, flags: 1 }; + } + return undefined; + } + function hasFileWithHigherPriorityExtension(file, literalFiles, wildcardFiles, extensions, keyMapper) { + var extensionPriority = ts.getExtensionPriority(file, extensions); + var adjustedExtensionPriority = ts.adjustExtensionPriority(extensionPriority, extensions); + for (var i = 0; i < adjustedExtensionPriority; i++) { + var higherPriorityExtension = extensions[i]; + var higherPriorityPath = keyMapper(ts.changeExtension(file, higherPriorityExtension)); + if (literalFiles.has(higherPriorityPath) || wildcardFiles.has(higherPriorityPath)) { + return true; + } + } + return false; + } + function removeWildcardFilesWithLowerPriorityExtension(file, wildcardFiles, extensions, keyMapper) { + var extensionPriority = ts.getExtensionPriority(file, extensions); + var nextExtensionPriority = ts.getNextLowestExtensionPriority(extensionPriority, extensions); + for (var i = nextExtensionPriority; i < extensions.length; i++) { + var lowerPriorityExtension = extensions[i]; + var lowerPriorityPath = keyMapper(ts.changeExtension(file, lowerPriorityExtension)); + wildcardFiles.delete(lowerPriorityPath); + } + } + function convertCompilerOptionsForTelemetry(opts) { + var out = {}; + for (var key in opts) { + if (opts.hasOwnProperty(key)) { + var type = getOptionFromName(key); + if (type !== undefined) { + out[key] = getOptionValueWithEmptyStrings(opts[key], type); + } + } + } + return out; + } + ts.convertCompilerOptionsForTelemetry = convertCompilerOptionsForTelemetry; + function getOptionValueWithEmptyStrings(value, option) { + switch (option.type) { + case "object": + return ""; + case "string": + return ""; + case "number": + return typeof value === "number" ? value : ""; + case "boolean": + return typeof value === "boolean" ? value : ""; + case "list": + var elementType_1 = option.element; + return ts.isArray(value) ? value.map(function (v) { return getOptionValueWithEmptyStrings(v, elementType_1); }) : ""; + default: + return ts.forEachEntry(option.type, function (optionEnumValue, optionStringValue) { + if (optionEnumValue === value) { + return optionStringValue; + } + }); + } + } +})(ts || (ts = {})); +var ts; +(function (ts) { + function trace(host) { + host.trace(ts.formatMessage.apply(undefined, arguments)); + } + ts.trace = trace; + function isTraceEnabled(compilerOptions, host) { + return !!compilerOptions.traceResolution && host.trace !== undefined; + } + ts.isTraceEnabled = isTraceEnabled; + function withPackageId(packageId, r) { + return r && { path: r.path, extension: r.ext, packageId: packageId }; + } + function noPackageId(r) { + return withPackageId(undefined, r); + } + function removeIgnoredPackageId(r) { + if (r) { + ts.Debug.assert(r.packageId === undefined); + return { path: r.path, ext: r.extension }; + } + } + var Extensions; + (function (Extensions) { + Extensions[Extensions["TypeScript"] = 0] = "TypeScript"; + Extensions[Extensions["JavaScript"] = 1] = "JavaScript"; + Extensions[Extensions["Json"] = 2] = "Json"; + Extensions[Extensions["TSConfig"] = 3] = "TSConfig"; + Extensions[Extensions["DtsOnly"] = 4] = "DtsOnly"; + })(Extensions || (Extensions = {})); + function resolvedTypeScriptOnly(resolved) { + if (!resolved) { + return undefined; + } + ts.Debug.assert(ts.extensionIsTS(resolved.extension)); + return { fileName: resolved.path, packageId: resolved.packageId }; + } + function createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations) { + return { + resolvedModule: resolved && { resolvedFileName: resolved.path, originalPath: resolved.originalPath === true ? undefined : resolved.originalPath, extension: resolved.extension, isExternalLibraryImport: isExternalLibraryImport, packageId: resolved.packageId }, + failedLookupLocations: failedLookupLocations + }; + } + function readPackageJsonField(jsonContent, fieldName, typeOfTag, state) { + if (!ts.hasProperty(jsonContent, fieldName)) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_does_not_have_a_0_field, fieldName); + } + return; + } + var value = jsonContent[fieldName]; + if (typeof value !== typeOfTag || value === null) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_1_got_2, fieldName, typeOfTag, value === null ? "null" : typeof value); + } + return; + } + return value; + } + function readPackageJsonPathField(jsonContent, fieldName, baseDirectory, state) { + var fileName = readPackageJsonField(jsonContent, fieldName, "string", state); + if (fileName === undefined) + return; + var path = ts.normalizePath(ts.combinePaths(baseDirectory, fileName)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, fileName, path); + } + return path; + } + function readPackageJsonTypesFields(jsonContent, baseDirectory, state) { + return readPackageJsonPathField(jsonContent, "typings", baseDirectory, state) + || readPackageJsonPathField(jsonContent, "types", baseDirectory, state); + } + function readPackageJsonTSConfigField(jsonContent, baseDirectory, state) { + return readPackageJsonPathField(jsonContent, "tsconfig", baseDirectory, state); + } + function readPackageJsonMainField(jsonContent, baseDirectory, state) { + return readPackageJsonPathField(jsonContent, "main", baseDirectory, state); + } + function readPackageJsonTypesVersionsField(jsonContent, state) { + var typesVersions = readPackageJsonField(jsonContent, "typesVersions", "object", state); + if (typesVersions === undefined) + return; + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_field_with_version_specific_path_mappings); + } + return typesVersions; + } + function readPackageJsonTypesVersionPaths(jsonContent, state) { + var typesVersions = readPackageJsonTypesVersionsField(jsonContent, state); + if (typesVersions === undefined) + return; + if (state.traceEnabled) { + for (var key in typesVersions) { + if (ts.hasProperty(typesVersions, key) && !ts.VersionRange.tryParse(key)) { + trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range, key); + } + } + } + var result = getPackageJsonTypesVersionsPaths(typesVersions); + if (!result) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_does_not_have_a_typesVersions_entry_that_matches_version_0, ts.versionMajorMinor); + } + return; + } + var bestVersionKey = result.version, bestVersionPaths = result.paths; + if (typeof bestVersionPaths !== "object") { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_1_got_2, "typesVersions['" + bestVersionKey + "']", "object", typeof bestVersionPaths); + } + return; + } + return result; + } + var typeScriptVersion; + function getPackageJsonTypesVersionsPaths(typesVersions) { + if (!typeScriptVersion) + typeScriptVersion = new ts.Version(ts.version); + for (var key in typesVersions) { + if (!ts.hasProperty(typesVersions, key)) + continue; + var keyRange = ts.VersionRange.tryParse(key); + if (keyRange === undefined) { + continue; + } + if (keyRange.test(typeScriptVersion)) { + return { version: key, paths: typesVersions[key] }; + } + } + } + ts.getPackageJsonTypesVersionsPaths = getPackageJsonTypesVersionsPaths; + function getEffectiveTypeRoots(options, host) { + if (options.typeRoots) { + return options.typeRoots; + } + var currentDirectory; + if (options.configFilePath) { + currentDirectory = ts.getDirectoryPath(options.configFilePath); + } + else if (host.getCurrentDirectory) { + currentDirectory = host.getCurrentDirectory(); + } + if (currentDirectory !== undefined) { + return getDefaultTypeRoots(currentDirectory, host); + } + } + ts.getEffectiveTypeRoots = getEffectiveTypeRoots; + function getDefaultTypeRoots(currentDirectory, host) { + if (!host.directoryExists) { + return [ts.combinePaths(currentDirectory, nodeModulesAtTypes)]; + } + var typeRoots; + ts.forEachAncestorDirectory(ts.normalizePath(currentDirectory), function (directory) { + var atTypes = ts.combinePaths(directory, nodeModulesAtTypes); + if (host.directoryExists(atTypes)) { + (typeRoots || (typeRoots = [])).push(atTypes); + } + return undefined; + }); + return typeRoots; + } + var nodeModulesAtTypes = ts.combinePaths("node_modules", "@types"); + function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host, redirectedReference) { + var traceEnabled = isTraceEnabled(options, host); + if (redirectedReference) { + options = redirectedReference.commandLine.options; + } + var failedLookupLocations = []; + var moduleResolutionState = { compilerOptions: options, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; + var typeRoots = getEffectiveTypeRoots(options, host); + if (traceEnabled) { + if (containingFile === undefined) { + if (typeRoots === undefined) { + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set, typeReferenceDirectiveName); + } + else { + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1, typeReferenceDirectiveName, typeRoots); + } + } + else { + if (typeRoots === undefined) { + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set, typeReferenceDirectiveName, containingFile); + } + else { + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_2, typeReferenceDirectiveName, containingFile, typeRoots); + } + } + if (redirectedReference) { + trace(host, ts.Diagnostics.Using_compiler_options_of_project_reference_redirect_0, redirectedReference.sourceFile.fileName); + } + } + var resolved = primaryLookup(); + var primary = true; + if (!resolved) { + resolved = secondaryLookup(); + primary = false; + } + var resolvedTypeReferenceDirective; + if (resolved) { + var fileName = resolved.fileName, packageId = resolved.packageId; + var resolvedFileName = options.preserveSymlinks ? fileName : realPath(fileName, host, traceEnabled); + if (traceEnabled) { + trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFileName, primary); + } + resolvedTypeReferenceDirective = { primary: primary, resolvedFileName: resolvedFileName, packageId: packageId, isExternalLibraryImport: pathContainsNodeModules(fileName) }; + } + return { resolvedTypeReferenceDirective: resolvedTypeReferenceDirective, failedLookupLocations: failedLookupLocations }; + function primaryLookup() { + if (typeRoots && typeRoots.length) { + if (traceEnabled) { + trace(host, ts.Diagnostics.Resolving_with_primary_search_path_0, typeRoots.join(", ")); + } + return ts.firstDefined(typeRoots, function (typeRoot) { + var candidate = ts.combinePaths(typeRoot, typeReferenceDirectiveName); + var candidateDirectory = ts.getDirectoryPath(candidate); + var directoryExists = ts.directoryProbablyExists(candidateDirectory, host); + if (!directoryExists && traceEnabled) { + trace(host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, candidateDirectory); + } + return resolvedTypeScriptOnly(loadNodeModuleFromDirectory(Extensions.DtsOnly, candidate, !directoryExists, moduleResolutionState)); + }); + } + else { + if (traceEnabled) { + trace(host, ts.Diagnostics.Root_directory_cannot_be_determined_skipping_primary_search_paths); + } + } + } + function secondaryLookup() { + var initialLocationForSecondaryLookup = containingFile && ts.getDirectoryPath(containingFile); + if (initialLocationForSecondaryLookup !== undefined) { + if (traceEnabled) { + trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup); + } + var result = void 0; + if (!ts.isExternalModuleNameRelative(typeReferenceDirectiveName)) { + var searchResult = loadModuleFromNearestNodeModulesDirectory(Extensions.DtsOnly, typeReferenceDirectiveName, initialLocationForSecondaryLookup, moduleResolutionState, undefined, undefined); + result = searchResult && searchResult.value; + } + else { + var candidate = ts.normalizePathAndParts(ts.combinePaths(initialLocationForSecondaryLookup, typeReferenceDirectiveName)).path; + result = nodeLoadModuleByRelativeName(Extensions.DtsOnly, candidate, false, moduleResolutionState, true); + } + var resolvedFile = resolvedTypeScriptOnly(result); + if (!resolvedFile && traceEnabled) { + trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName); + } + return resolvedFile; + } + else { + if (traceEnabled) { + trace(host, ts.Diagnostics.Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder); + } + } + } + } + ts.resolveTypeReferenceDirective = resolveTypeReferenceDirective; + function getAutomaticTypeDirectiveNames(options, host) { + if (options.types) { + return options.types; + } + var result = []; + if (host.directoryExists && host.getDirectories) { + var typeRoots = getEffectiveTypeRoots(options, host); + if (typeRoots) { + for (var _i = 0, typeRoots_1 = typeRoots; _i < typeRoots_1.length; _i++) { + var root = typeRoots_1[_i]; + if (host.directoryExists(root)) { + for (var _a = 0, _b = host.getDirectories(root); _a < _b.length; _a++) { + var typeDirectivePath = _b[_a]; + var normalized = ts.normalizePath(typeDirectivePath); + var packageJsonPath = ts.combinePaths(root, normalized, "package.json"); + var isNotNeededPackage = host.fileExists(packageJsonPath) && ts.readJson(packageJsonPath, host).typings === null; + if (!isNotNeededPackage) { + var baseFileName = ts.getBaseFileName(normalized); + if (baseFileName.charCodeAt(0) !== 46) { + result.push(baseFileName); + } + } + } + } + } + } + } + return result; + } + ts.getAutomaticTypeDirectiveNames = getAutomaticTypeDirectiveNames; + function createModuleResolutionCache(currentDirectory, getCanonicalFileName) { + return createModuleResolutionCacheWithMaps(createCacheWithRedirects(), createCacheWithRedirects(), currentDirectory, getCanonicalFileName); + } + ts.createModuleResolutionCache = createModuleResolutionCache; + function createCacheWithRedirects() { + var ownMap = ts.createMap(); + var redirectsMap = ts.createMap(); + return { + ownMap: ownMap, + redirectsMap: redirectsMap, + getOrCreateMapOfCacheRedirects: getOrCreateMapOfCacheRedirects, + clear: clear + }; + function getOrCreateMapOfCacheRedirects(redirectedReference) { + if (!redirectedReference) { + return ownMap; + } + var path = redirectedReference.sourceFile.path; + var redirects = redirectsMap.get(path); + if (!redirects) { + redirects = ts.createMap(); + redirectsMap.set(path, redirects); + } + return redirects; + } + function clear() { + ownMap.clear(); + redirectsMap.clear(); + } + } + ts.createCacheWithRedirects = createCacheWithRedirects; + function createModuleResolutionCacheWithMaps(directoryToModuleNameMap, moduleNameToDirectoryMap, currentDirectory, getCanonicalFileName) { + return { getOrCreateCacheForDirectory: getOrCreateCacheForDirectory, getOrCreateCacheForModuleName: getOrCreateCacheForModuleName }; + function getOrCreateCacheForDirectory(directoryName, redirectedReference) { + var path = ts.toPath(directoryName, currentDirectory, getCanonicalFileName); + return getOrCreateCache(directoryToModuleNameMap, redirectedReference, path, ts.createMap); + } + function getOrCreateCacheForModuleName(nonRelativeModuleName, redirectedReference) { + ts.Debug.assert(!ts.isExternalModuleNameRelative(nonRelativeModuleName)); + return getOrCreateCache(moduleNameToDirectoryMap, redirectedReference, nonRelativeModuleName, createPerModuleNameCache); + } + function getOrCreateCache(cacheWithRedirects, redirectedReference, key, create) { + var cache = cacheWithRedirects.getOrCreateMapOfCacheRedirects(redirectedReference); + var result = cache.get(key); + if (!result) { + result = create(); + cache.set(key, result); + } + return result; + } + function createPerModuleNameCache() { + var directoryPathMap = ts.createMap(); + return { get: get, set: set }; + function get(directory) { + return directoryPathMap.get(ts.toPath(directory, currentDirectory, getCanonicalFileName)); + } + function set(directory, result) { + var path = ts.toPath(directory, currentDirectory, getCanonicalFileName); + if (directoryPathMap.has(path)) { + return; + } + directoryPathMap.set(path, result); + var resolvedFileName = result.resolvedModule && + (result.resolvedModule.originalPath || result.resolvedModule.resolvedFileName); + var commonPrefix = resolvedFileName && getCommonPrefix(path, resolvedFileName); + var current = path; + while (current !== commonPrefix) { + var parent = ts.getDirectoryPath(current); + if (parent === current || directoryPathMap.has(parent)) { + break; + } + directoryPathMap.set(parent, result); + current = parent; + } + } + function getCommonPrefix(directory, resolution) { + var resolutionDirectory = ts.toPath(ts.getDirectoryPath(resolution), currentDirectory, getCanonicalFileName); + var i = 0; + var limit = Math.min(directory.length, resolutionDirectory.length); + while (i < limit && directory.charCodeAt(i) === resolutionDirectory.charCodeAt(i)) { + i++; + } + if (i === directory.length && (resolutionDirectory.length === i || resolutionDirectory[i] === ts.directorySeparator)) { + return directory; + } + var rootLength = ts.getRootLength(directory); + if (i < rootLength) { + return undefined; + } + var sep = directory.lastIndexOf(ts.directorySeparator, i - 1); + if (sep === -1) { + return undefined; + } + return directory.substr(0, Math.max(sep, rootLength)); + } + } + } + ts.createModuleResolutionCacheWithMaps = createModuleResolutionCacheWithMaps; + function resolveModuleNameFromCache(moduleName, containingFile, cache) { + var containingDirectory = ts.getDirectoryPath(containingFile); + var perFolderCache = cache && cache.getOrCreateCacheForDirectory(containingDirectory); + return perFolderCache && perFolderCache.get(moduleName); + } + ts.resolveModuleNameFromCache = resolveModuleNameFromCache; + function resolveModuleName(moduleName, containingFile, compilerOptions, host, cache, redirectedReference) { + var traceEnabled = isTraceEnabled(compilerOptions, host); + if (redirectedReference) { + compilerOptions = redirectedReference.commandLine.options; + } + if (traceEnabled) { + trace(host, ts.Diagnostics.Resolving_module_0_from_1, moduleName, containingFile); + if (redirectedReference) { + trace(host, ts.Diagnostics.Using_compiler_options_of_project_reference_redirect_0, redirectedReference.sourceFile.fileName); + } + } + var containingDirectory = ts.getDirectoryPath(containingFile); + var perFolderCache = cache && cache.getOrCreateCacheForDirectory(containingDirectory, redirectedReference); + var result = perFolderCache && perFolderCache.get(moduleName); + if (result) { + if (traceEnabled) { + trace(host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory); + } + } + else { + var moduleResolution = compilerOptions.moduleResolution; + if (moduleResolution === undefined) { + moduleResolution = ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS ? ts.ModuleResolutionKind.NodeJs : ts.ModuleResolutionKind.Classic; + if (traceEnabled) { + trace(host, ts.Diagnostics.Module_resolution_kind_is_not_specified_using_0, ts.ModuleResolutionKind[moduleResolution]); + } + } + else { + if (traceEnabled) { + trace(host, ts.Diagnostics.Explicitly_specified_module_resolution_kind_Colon_0, ts.ModuleResolutionKind[moduleResolution]); + } + } + switch (moduleResolution) { + case ts.ModuleResolutionKind.NodeJs: + result = nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference); + break; + case ts.ModuleResolutionKind.Classic: + result = classicNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference); + break; + default: + return ts.Debug.fail("Unexpected moduleResolution: " + moduleResolution); + } + if (perFolderCache) { + perFolderCache.set(moduleName, result); + if (!ts.isExternalModuleNameRelative(moduleName)) { + cache.getOrCreateCacheForModuleName(moduleName, redirectedReference).set(containingDirectory, result); + } + } + } + if (traceEnabled) { + if (result.resolvedModule) { + trace(host, ts.Diagnostics.Module_name_0_was_successfully_resolved_to_1, moduleName, result.resolvedModule.resolvedFileName); + } + else { + trace(host, ts.Diagnostics.Module_name_0_was_not_resolved, moduleName); + } + } + return result; + } + ts.resolveModuleName = resolveModuleName; + function tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, state) { + var resolved = tryLoadModuleUsingPathsIfEligible(extensions, moduleName, loader, state); + if (resolved) + return resolved.value; + if (!ts.isExternalModuleNameRelative(moduleName)) { + return tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, state); + } + else { + return tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, state); + } + } + function tryLoadModuleUsingPathsIfEligible(extensions, moduleName, loader, state) { + var _a = state.compilerOptions, baseUrl = _a.baseUrl, paths = _a.paths; + if (baseUrl && paths && !ts.pathIsRelative(moduleName)) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, baseUrl, moduleName); + trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName); + } + return tryLoadModuleUsingPaths(extensions, moduleName, baseUrl, paths, loader, false, state); + } + } + function tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, state) { + if (!state.compilerOptions.rootDirs) { + return undefined; + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0, moduleName); + } + var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); + var matchedRootDir; + var matchedNormalizedPrefix; + for (var _i = 0, _a = state.compilerOptions.rootDirs; _i < _a.length; _i++) { + var rootDir = _a[_i]; + var normalizedRoot = ts.normalizePath(rootDir); + if (!ts.endsWith(normalizedRoot, ts.directorySeparator)) { + normalizedRoot += ts.directorySeparator; + } + var isLongestMatchingPrefix = ts.startsWith(candidate, normalizedRoot) && + (matchedNormalizedPrefix === undefined || matchedNormalizedPrefix.length < normalizedRoot.length); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Checking_if_0_is_the_longest_matching_prefix_for_1_2, normalizedRoot, candidate, isLongestMatchingPrefix); + } + if (isLongestMatchingPrefix) { + matchedNormalizedPrefix = normalizedRoot; + matchedRootDir = rootDir; + } + } + if (matchedNormalizedPrefix) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Longest_matching_prefix_for_0_is_1, candidate, matchedNormalizedPrefix); + } + var suffix = candidate.substr(matchedNormalizedPrefix.length); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, matchedNormalizedPrefix, candidate); + } + var resolvedFileName = loader(extensions, candidate, !ts.directoryProbablyExists(containingDirectory, state.host), state); + if (resolvedFileName) { + return resolvedFileName; + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Trying_other_entries_in_rootDirs); + } + for (var _b = 0, _c = state.compilerOptions.rootDirs; _b < _c.length; _b++) { + var rootDir = _c[_b]; + if (rootDir === matchedRootDir) { + continue; + } + var candidate_1 = ts.combinePaths(ts.normalizePath(rootDir), suffix); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, rootDir, candidate_1); + } + var baseDirectory = ts.getDirectoryPath(candidate_1); + var resolvedFileName_1 = loader(extensions, candidate_1, !ts.directoryProbablyExists(baseDirectory, state.host), state); + if (resolvedFileName_1) { + return resolvedFileName_1; + } + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Module_resolution_using_rootDirs_has_failed); + } + } + return undefined; + } + function tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, state) { + var baseUrl = state.compilerOptions.baseUrl; + if (!baseUrl) { + return undefined; + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, baseUrl, moduleName); + } + var candidate = ts.normalizePath(ts.combinePaths(baseUrl, moduleName)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, baseUrl, candidate); + } + return loader(extensions, candidate, !ts.directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); + } + function resolveJSModule(moduleName, initialDir, host) { + var _a = tryResolveJSModuleWorker(moduleName, initialDir, host), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; + if (!resolvedModule) { + throw new Error("Could not resolve JS module '" + moduleName + "' starting at '" + initialDir + "'. Looked in: " + failedLookupLocations.join(", ")); + } + return resolvedModule.resolvedFileName; + } + ts.resolveJSModule = resolveJSModule; + function tryResolveJSModule(moduleName, initialDir, host) { + var resolvedModule = tryResolveJSModuleWorker(moduleName, initialDir, host).resolvedModule; + return resolvedModule && resolvedModule.resolvedFileName; + } + ts.tryResolveJSModule = tryResolveJSModule; + var jsOnlyExtensions = [Extensions.JavaScript]; + var tsExtensions = [Extensions.TypeScript, Extensions.JavaScript]; + var tsPlusJsonExtensions = tsExtensions.concat([Extensions.Json]); + var tsconfigExtensions = [Extensions.TSConfig]; + function tryResolveJSModuleWorker(moduleName, initialDir, host) { + return nodeModuleNameResolverWorker(moduleName, initialDir, { moduleResolution: ts.ModuleResolutionKind.NodeJs, allowJs: true }, host, undefined, jsOnlyExtensions, undefined); + } + function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference, lookupConfig) { + return nodeModuleNameResolverWorker(moduleName, ts.getDirectoryPath(containingFile), compilerOptions, host, cache, lookupConfig ? tsconfigExtensions : (compilerOptions.resolveJsonModule ? tsPlusJsonExtensions : tsExtensions), redirectedReference); + } + ts.nodeModuleNameResolver = nodeModuleNameResolver; + function nodeModuleNameResolverWorker(moduleName, containingDirectory, compilerOptions, host, cache, extensions, redirectedReference) { + var traceEnabled = isTraceEnabled(compilerOptions, host); + var failedLookupLocations = []; + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; + var result = ts.forEach(extensions, function (ext) { return tryResolve(ext); }); + if (result && result.value) { + var _a = result.value, resolved = _a.resolved, isExternalLibraryImport = _a.isExternalLibraryImport; + return createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations); + } + return { resolvedModule: undefined, failedLookupLocations: failedLookupLocations }; + function tryResolve(extensions) { + var loader = function (extensions, candidate, onlyRecordFailures, state) { return nodeLoadModuleByRelativeName(extensions, candidate, onlyRecordFailures, state, true); }; + var resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, state); + if (resolved) { + return toSearchResult({ resolved: resolved, isExternalLibraryImport: pathContainsNodeModules(resolved.path) }); + } + if (!ts.isExternalModuleNameRelative(moduleName)) { + if (traceEnabled) { + trace(host, ts.Diagnostics.Loading_module_0_from_node_modules_folder_target_file_type_1, moduleName, Extensions[extensions]); + } + var resolved_1 = loadModuleFromNearestNodeModulesDirectory(extensions, moduleName, containingDirectory, state, cache, redirectedReference); + if (!resolved_1) + return undefined; + var resolvedValue = resolved_1.value; + if (!compilerOptions.preserveSymlinks && resolvedValue && !resolvedValue.originalPath) { + var path = realPath(resolvedValue.path, host, traceEnabled); + var originalPath = path === resolvedValue.path ? undefined : resolvedValue.path; + resolvedValue = __assign({}, resolvedValue, { path: path, originalPath: originalPath }); + } + return { value: resolvedValue && { resolved: resolvedValue, isExternalLibraryImport: true } }; + } + else { + var _a = ts.normalizePathAndParts(ts.combinePaths(containingDirectory, moduleName)), candidate = _a.path, parts = _a.parts; + var resolved_2 = nodeLoadModuleByRelativeName(extensions, candidate, false, state, true); + return resolved_2 && toSearchResult({ resolved: resolved_2, isExternalLibraryImport: ts.contains(parts, "node_modules") }); + } + } + } + function realPath(path, host, traceEnabled) { + if (!host.realpath) { + return path; + } + var real = ts.normalizePath(host.realpath(path)); + if (traceEnabled) { + trace(host, ts.Diagnostics.Resolving_real_path_for_0_result_1, path, real); + } + ts.Debug.assert(host.fileExists(real), path + " linked to nonexistent file " + real); + return real; + } + function nodeLoadModuleByRelativeName(extensions, candidate, onlyRecordFailures, state, considerPackageJson) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1, candidate, Extensions[extensions]); + } + if (!ts.hasTrailingDirectorySeparator(candidate)) { + if (!onlyRecordFailures) { + var parentOfCandidate = ts.getDirectoryPath(candidate); + if (!ts.directoryProbablyExists(parentOfCandidate, state.host)) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, parentOfCandidate); + } + onlyRecordFailures = true; + } + } + var resolvedFromFile = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state); + if (resolvedFromFile) { + var nm = considerPackageJson ? parseNodeModuleFromPath(resolvedFromFile) : undefined; + var packageInfo = nm && getPackageJsonInfo(nm.packageDirectory, nm.subModuleName, false, state); + var packageId = packageInfo && packageInfo.packageId; + return withPackageId(packageId, resolvedFromFile); + } + } + if (!onlyRecordFailures) { + var candidateExists = ts.directoryProbablyExists(candidate, state.host); + if (!candidateExists) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, candidate); + } + onlyRecordFailures = true; + } + } + return loadNodeModuleFromDirectory(extensions, candidate, onlyRecordFailures, state, considerPackageJson); + } + ts.nodeModulesPathPart = "/node_modules/"; + function pathContainsNodeModules(path) { + return ts.stringContains(path, ts.nodeModulesPathPart); + } + ts.pathContainsNodeModules = pathContainsNodeModules; + function parseNodeModuleFromPath(resolved) { + var path = ts.normalizePath(resolved.path); + var idx = path.lastIndexOf(ts.nodeModulesPathPart); + if (idx === -1) { + return undefined; + } + var indexAfterNodeModules = idx + ts.nodeModulesPathPart.length; + var indexAfterPackageName = moveToNextDirectorySeparatorIfAvailable(path, indexAfterNodeModules); + if (path.charCodeAt(indexAfterNodeModules) === 64) { + indexAfterPackageName = moveToNextDirectorySeparatorIfAvailable(path, indexAfterPackageName); + } + var packageDirectory = path.slice(0, indexAfterPackageName); + var subModuleName = ts.removeExtension(path.slice(indexAfterPackageName + 1), resolved.ext) + ".d.ts"; + return { packageDirectory: packageDirectory, subModuleName: subModuleName }; + } + function moveToNextDirectorySeparatorIfAvailable(path, prevSeparatorIndex) { + var nextSeparatorIndex = path.indexOf(ts.directorySeparator, prevSeparatorIndex + 1); + return nextSeparatorIndex === -1 ? prevSeparatorIndex : nextSeparatorIndex; + } + function addExtensionAndIndex(path) { + if (path === "") { + return "index.d.ts"; + } + if (ts.endsWith(path, ".d.ts")) { + return path; + } + if (path === "index" || ts.endsWith(path, "/index")) { + return path + ".d.ts"; + } + return path + "/index.d.ts"; + } + function loadModuleFromFileNoPackageId(extensions, candidate, onlyRecordFailures, state) { + return noPackageId(loadModuleFromFile(extensions, candidate, onlyRecordFailures, state)); + } + function loadModuleFromFile(extensions, candidate, onlyRecordFailures, state) { + if (extensions === Extensions.Json || extensions === Extensions.TSConfig) { + var extensionLess = ts.tryRemoveExtension(candidate, ".json"); + return (extensionLess === undefined && extensions === Extensions.Json) ? undefined : tryAddingExtensions(extensionLess || candidate, extensions, onlyRecordFailures, state); + } + var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, onlyRecordFailures, state); + if (resolvedByAddingExtension) { + return resolvedByAddingExtension; + } + if (ts.hasJSFileExtension(candidate)) { + var extensionless = ts.removeFileExtension(candidate); + if (state.traceEnabled) { + var extension = candidate.substring(extensionless.length); + trace(state.host, ts.Diagnostics.File_name_0_has_a_1_extension_stripping_it, candidate, extension); + } + return tryAddingExtensions(extensionless, extensions, onlyRecordFailures, state); + } + } + function tryAddingExtensions(candidate, extensions, onlyRecordFailures, state) { + if (!onlyRecordFailures) { + var directory = ts.getDirectoryPath(candidate); + if (directory) { + onlyRecordFailures = !ts.directoryProbablyExists(directory, state.host); + } + } + switch (extensions) { + case Extensions.DtsOnly: + return tryExtension(".d.ts"); + case Extensions.TypeScript: + return tryExtension(".ts") || tryExtension(".tsx") || tryExtension(".d.ts"); + case Extensions.JavaScript: + return tryExtension(".js") || tryExtension(".jsx"); + case Extensions.TSConfig: + case Extensions.Json: + return tryExtension(".json"); + } + function tryExtension(ext) { + var path = tryFile(candidate + ext, onlyRecordFailures, state); + return path === undefined ? undefined : { path: path, ext: ext }; + } + } + function tryFile(fileName, onlyRecordFailures, state) { + if (!onlyRecordFailures) { + if (state.host.fileExists(fileName)) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_exist_use_it_as_a_name_resolution_result, fileName); + } + return fileName; + } + else { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_does_not_exist, fileName); + } + } + } + state.failedLookupLocations.push(fileName); + return undefined; + } + function loadNodeModuleFromDirectory(extensions, candidate, onlyRecordFailures, state, considerPackageJson) { + if (considerPackageJson === void 0) { considerPackageJson = true; } + var packageInfo = considerPackageJson ? getPackageJsonInfo(candidate, "", onlyRecordFailures, state) : undefined; + var packageId = packageInfo && packageInfo.packageId; + var packageJsonContent = packageInfo && packageInfo.packageJsonContent; + var versionPaths = packageJsonContent && readPackageJsonTypesVersionPaths(packageJsonContent, state); + return withPackageId(packageId, loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths)); + } + function getPackageJsonInfo(packageDirectory, subModuleName, onlyRecordFailures, state) { + var host = state.host, traceEnabled = state.traceEnabled; + var directoryExists = !onlyRecordFailures && ts.directoryProbablyExists(packageDirectory, host); + var packageJsonPath = ts.combinePaths(packageDirectory, "package.json"); + if (directoryExists && host.fileExists(packageJsonPath)) { + var packageJsonContent = ts.readJson(packageJsonPath, host); + if (subModuleName === "") { + var path = readPackageJsonTypesFields(packageJsonContent, packageDirectory, state); + if (typeof path === "string") { + subModuleName = addExtensionAndIndex(path.substring(packageDirectory.length + 1)); + } + else { + var jsPath = readPackageJsonMainField(packageJsonContent, packageDirectory, state); + if (typeof jsPath === "string" && jsPath.length > packageDirectory.length) { + var potentialSubModule_1 = jsPath.substring(packageDirectory.length + 1); + subModuleName = (ts.forEach(ts.supportedJSExtensions, function (extension) { + return ts.tryRemoveExtension(potentialSubModule_1, extension); + }) || potentialSubModule_1) + ".d.ts"; + } + else { + subModuleName = "index.d.ts"; + } + } + } + if (!ts.endsWith(subModuleName, ".d.ts")) { + subModuleName = addExtensionAndIndex(subModuleName); + } + var versionPaths = readPackageJsonTypesVersionPaths(packageJsonContent, state); + var packageId = typeof packageJsonContent.name === "string" && typeof packageJsonContent.version === "string" + ? { name: packageJsonContent.name, subModuleName: subModuleName, version: packageJsonContent.version } + : undefined; + if (traceEnabled) { + if (packageId) { + trace(host, ts.Diagnostics.Found_package_json_at_0_Package_ID_is_1, packageJsonPath, ts.packageIdToString(packageId)); + } + else { + trace(host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); + } + } + return { packageJsonContent: packageJsonContent, packageId: packageId, versionPaths: versionPaths }; + } + else { + if (directoryExists && traceEnabled) { + trace(host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath); + } + state.failedLookupLocations.push(packageJsonPath); + } + } + function loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, jsonContent, versionPaths) { + var packageFile; + if (jsonContent) { + switch (extensions) { + case Extensions.JavaScript: + case Extensions.Json: + packageFile = readPackageJsonMainField(jsonContent, candidate, state); + break; + case Extensions.TypeScript: + packageFile = readPackageJsonTypesFields(jsonContent, candidate, state) || readPackageJsonMainField(jsonContent, candidate, state); + break; + case Extensions.DtsOnly: + packageFile = readPackageJsonTypesFields(jsonContent, candidate, state); + break; + case Extensions.TSConfig: + packageFile = readPackageJsonTSConfigField(jsonContent, candidate, state); + break; + default: + return ts.Debug.assertNever(extensions); + } + } + var loader = function (extensions, candidate, onlyRecordFailures, state) { + var fromFile = tryFile(candidate, onlyRecordFailures, state); + if (fromFile) { + var resolved = resolvedIfExtensionMatches(extensions, fromFile); + if (resolved) { + return noPackageId(resolved); + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_has_an_unsupported_extension_so_skipping_it, fromFile); + } + } + var nextExtensions = extensions === Extensions.DtsOnly ? Extensions.TypeScript : extensions; + return nodeLoadModuleByRelativeName(nextExtensions, candidate, onlyRecordFailures, state, false); + }; + var onlyRecordFailuresForPackageFile = packageFile ? !ts.directoryProbablyExists(ts.getDirectoryPath(packageFile), state.host) : undefined; + var onlyRecordFailuresForIndex = onlyRecordFailures || !ts.directoryProbablyExists(candidate, state.host); + var indexPath = ts.combinePaths(candidate, extensions === Extensions.TSConfig ? "tsconfig" : "index"); + if (versionPaths && (!packageFile || ts.containsPath(candidate, packageFile))) { + var moduleName = ts.getRelativePathFromDirectory(candidate, packageFile || indexPath, false); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2, versionPaths.version, ts.version, moduleName); + } + var result = tryLoadModuleUsingPaths(extensions, moduleName, candidate, versionPaths.paths, loader, onlyRecordFailuresForPackageFile || onlyRecordFailuresForIndex, state); + if (result) { + return removeIgnoredPackageId(result.value); + } + } + var packageFileResult = packageFile && removeIgnoredPackageId(loader(extensions, packageFile, onlyRecordFailuresForPackageFile, state)); + if (packageFileResult) + return packageFileResult; + return loadModuleFromFile(extensions, indexPath, onlyRecordFailuresForIndex, state); + } + function resolvedIfExtensionMatches(extensions, path) { + var ext = ts.tryGetExtensionFromPath(path); + return ext !== undefined && extensionIsOk(extensions, ext) ? { path: path, ext: ext } : undefined; + } + function extensionIsOk(extensions, extension) { + switch (extensions) { + case Extensions.JavaScript: + return extension === ".js" || extension === ".jsx"; + case Extensions.TSConfig: + case Extensions.Json: + return extension === ".json"; + case Extensions.TypeScript: + return extension === ".ts" || extension === ".tsx" || extension === ".d.ts"; + case Extensions.DtsOnly: + return extension === ".d.ts"; + } + } + function parsePackageName(moduleName) { + var idx = moduleName.indexOf(ts.directorySeparator); + if (moduleName[0] === "@") { + idx = moduleName.indexOf(ts.directorySeparator, idx + 1); + } + return idx === -1 ? { packageName: moduleName, rest: "" } : { packageName: moduleName.slice(0, idx), rest: moduleName.slice(idx + 1) }; + } + ts.parsePackageName = parsePackageName; + function loadModuleFromNearestNodeModulesDirectory(extensions, moduleName, directory, state, cache, redirectedReference) { + return loadModuleFromNearestNodeModulesDirectoryWorker(extensions, moduleName, directory, state, false, cache, redirectedReference); + } + function loadModuleFromNearestNodeModulesDirectoryTypesScope(moduleName, directory, state) { + return loadModuleFromNearestNodeModulesDirectoryWorker(Extensions.DtsOnly, moduleName, directory, state, true, undefined, undefined); + } + function loadModuleFromNearestNodeModulesDirectoryWorker(extensions, moduleName, directory, state, typesScopeOnly, cache, redirectedReference) { + var perModuleNameCache = cache && cache.getOrCreateCacheForModuleName(moduleName, redirectedReference); + return ts.forEachAncestorDirectory(ts.normalizeSlashes(directory), function (ancestorDirectory) { + if (ts.getBaseFileName(ancestorDirectory) !== "node_modules") { + var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, ancestorDirectory, state); + if (resolutionFromCache) { + return resolutionFromCache; + } + return toSearchResult(loadModuleFromImmediateNodeModulesDirectory(extensions, moduleName, ancestorDirectory, state, typesScopeOnly)); + } + }); + } + function loadModuleFromImmediateNodeModulesDirectory(extensions, moduleName, directory, state, typesScopeOnly) { + var nodeModulesFolder = ts.combinePaths(directory, "node_modules"); + var nodeModulesFolderExists = ts.directoryProbablyExists(nodeModulesFolder, state.host); + if (!nodeModulesFolderExists && state.traceEnabled) { + trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, nodeModulesFolder); + } + var packageResult = typesScopeOnly ? undefined : loadModuleFromSpecificNodeModulesDirectory(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, state); + if (packageResult) { + return packageResult; + } + if (extensions === Extensions.TypeScript || extensions === Extensions.DtsOnly) { + var nodeModulesAtTypes_1 = ts.combinePaths(nodeModulesFolder, "@types"); + var nodeModulesAtTypesExists = nodeModulesFolderExists; + if (nodeModulesFolderExists && !ts.directoryProbablyExists(nodeModulesAtTypes_1, state.host)) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, nodeModulesAtTypes_1); + } + nodeModulesAtTypesExists = false; + } + return loadModuleFromSpecificNodeModulesDirectory(Extensions.DtsOnly, mangleScopedPackageNameWithTrace(moduleName, state), nodeModulesAtTypes_1, nodeModulesAtTypesExists, state); + } + } + function loadModuleFromSpecificNodeModulesDirectory(extensions, moduleName, nodeModulesDirectory, nodeModulesDirectoryExists, state) { + var candidate = ts.normalizePath(ts.combinePaths(nodeModulesDirectory, moduleName)); + var packageJsonContent; + var packageId; + var versionPaths; + var packageInfo = getPackageJsonInfo(candidate, "", !nodeModulesDirectoryExists, state); + if (packageInfo) { + (packageJsonContent = packageInfo.packageJsonContent, packageId = packageInfo.packageId, versionPaths = packageInfo.versionPaths); + var fromFile = loadModuleFromFile(extensions, candidate, !nodeModulesDirectoryExists, state); + if (fromFile) { + return noPackageId(fromFile); + } + var fromDirectory = loadNodeModuleFromDirectoryWorker(extensions, candidate, !nodeModulesDirectoryExists, state, packageJsonContent, versionPaths); + return withPackageId(packageId, fromDirectory); + } + var loader = function (extensions, candidate, onlyRecordFailures, state) { + var pathAndExtension = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state) || + loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths); + return withPackageId(packageId, pathAndExtension); + }; + var _a = parsePackageName(moduleName), packageName = _a.packageName, rest = _a.rest; + if (rest !== "") { + var packageDirectory = ts.combinePaths(nodeModulesDirectory, packageName); + var packageInfo_1 = getPackageJsonInfo(packageDirectory, rest, !nodeModulesDirectoryExists, state); + if (packageInfo_1) + (packageId = packageInfo_1.packageId, versionPaths = packageInfo_1.versionPaths); + if (versionPaths) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2, versionPaths.version, ts.version, rest); + } + var packageDirectoryExists = nodeModulesDirectoryExists && ts.directoryProbablyExists(packageDirectory, state.host); + var fromPaths = tryLoadModuleUsingPaths(extensions, rest, packageDirectory, versionPaths.paths, loader, !packageDirectoryExists, state); + if (fromPaths) { + return fromPaths.value; + } + } + } + return loader(extensions, candidate, !nodeModulesDirectoryExists, state); + } + function tryLoadModuleUsingPaths(extensions, moduleName, baseDirectory, paths, loader, onlyRecordFailures, state) { + var matchedPattern = ts.matchPatternOrExact(ts.getOwnKeys(paths), moduleName); + if (matchedPattern) { + var matchedStar_1 = ts.isString(matchedPattern) ? undefined : ts.matchedText(matchedPattern, moduleName); + var matchedPatternText = ts.isString(matchedPattern) ? matchedPattern : ts.patternText(matchedPattern); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText); + } + var resolved = ts.forEach(paths[matchedPatternText], function (subst) { + var path = matchedStar_1 ? subst.replace("*", matchedStar_1) : subst; + var candidate = ts.normalizePath(ts.combinePaths(baseDirectory, path)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path); + } + var extension = ts.tryGetExtensionFromPath(candidate); + if (extension !== undefined) { + var path_1 = tryFile(candidate, onlyRecordFailures, state); + if (path_1 !== undefined) { + return noPackageId({ path: path_1, ext: extension }); + } + } + return loader(extensions, candidate, onlyRecordFailures || !ts.directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); + }); + return { value: resolved }; + } + } + var mangledScopedPackageSeparator = "__"; + function mangleScopedPackageNameWithTrace(packageName, state) { + var mangled = mangleScopedPackageName(packageName); + if (state.traceEnabled && mangled !== packageName) { + trace(state.host, ts.Diagnostics.Scoped_package_detected_looking_in_0, mangled); + } + return mangled; + } + function getTypesPackageName(packageName) { + return "@types/" + mangleScopedPackageName(packageName); + } + ts.getTypesPackageName = getTypesPackageName; + function mangleScopedPackageName(packageName) { + if (ts.startsWith(packageName, "@")) { + var replaceSlash = packageName.replace(ts.directorySeparator, mangledScopedPackageSeparator); + if (replaceSlash !== packageName) { + return replaceSlash.slice(1); + } + } + return packageName; + } + ts.mangleScopedPackageName = mangleScopedPackageName; + function getPackageNameFromTypesPackageName(mangledName) { + var withoutAtTypePrefix = ts.removePrefix(mangledName, "@types/"); + if (withoutAtTypePrefix !== mangledName) { + return unmangleScopedPackageName(withoutAtTypePrefix); + } + return mangledName; + } + ts.getPackageNameFromTypesPackageName = getPackageNameFromTypesPackageName; + function unmangleScopedPackageName(typesPackageName) { + return ts.stringContains(typesPackageName, mangledScopedPackageSeparator) ? + "@" + typesPackageName.replace(mangledScopedPackageSeparator, ts.directorySeparator) : + typesPackageName; + } + ts.unmangleScopedPackageName = unmangleScopedPackageName; + function tryFindNonRelativeModuleNameInCache(cache, moduleName, containingDirectory, state) { + var _a; + var result = cache && cache.get(containingDirectory); + if (result) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory); + } + (_a = state.failedLookupLocations).push.apply(_a, result.failedLookupLocations); + return { value: result.resolvedModule && { path: result.resolvedModule.resolvedFileName, originalPath: result.resolvedModule.originalPath || true, extension: result.resolvedModule.extension, packageId: result.resolvedModule.packageId } }; + } + } + function classicNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference) { + var traceEnabled = isTraceEnabled(compilerOptions, host); + var failedLookupLocations = []; + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; + var containingDirectory = ts.getDirectoryPath(containingFile); + var resolved = tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript); + return createResolvedModuleWithFailedLookupLocations(resolved && resolved.value, false, failedLookupLocations); + function tryResolve(extensions) { + var resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFileNoPackageId, state); + if (resolvedUsingSettings) { + return { value: resolvedUsingSettings }; + } + if (!ts.isExternalModuleNameRelative(moduleName)) { + var perModuleNameCache_1 = cache && cache.getOrCreateCacheForModuleName(moduleName, redirectedReference); + var resolved_3 = ts.forEachAncestorDirectory(containingDirectory, function (directory) { + var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache_1, moduleName, directory, state); + if (resolutionFromCache) { + return resolutionFromCache; + } + var searchName = ts.normalizePath(ts.combinePaths(directory, moduleName)); + return toSearchResult(loadModuleFromFileNoPackageId(extensions, searchName, false, state)); + }); + if (resolved_3) { + return resolved_3; + } + if (extensions === Extensions.TypeScript) { + return loadModuleFromNearestNodeModulesDirectoryTypesScope(moduleName, containingDirectory, state); + } + } + else { + var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); + return toSearchResult(loadModuleFromFileNoPackageId(extensions, candidate, false, state)); + } + } + } + ts.classicNameResolver = classicNameResolver; + function loadModuleFromGlobalCache(moduleName, projectName, compilerOptions, host, globalCache) { + var traceEnabled = isTraceEnabled(compilerOptions, host); + if (traceEnabled) { + trace(host, ts.Diagnostics.Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2, projectName, moduleName, globalCache); + } + var failedLookupLocations = []; + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; + var resolved = loadModuleFromImmediateNodeModulesDirectory(Extensions.DtsOnly, moduleName, globalCache, state, false); + return createResolvedModuleWithFailedLookupLocations(resolved, true, failedLookupLocations); + } + ts.loadModuleFromGlobalCache = loadModuleFromGlobalCache; + function toSearchResult(value) { + return value !== undefined ? { value: value } : undefined; + } +})(ts || (ts = {})); +var ts; +(function (ts) { + function getModuleInstanceState(node) { + return node.body ? getModuleInstanceStateWorker(node.body) : 1; + } + ts.getModuleInstanceState = getModuleInstanceState; + function getModuleInstanceStateWorker(node) { + switch (node.kind) { + case 241: + case 242: + return 0; + case 243: + if (ts.isEnumConst(node)) { + return 2; + } + break; + case 249: + case 248: + if (!(ts.hasModifier(node, 1))) { + return 0; + } + break; + case 245: { + var state_1 = 0; + ts.forEachChild(node, function (n) { + var childState = getModuleInstanceStateWorker(n); + switch (childState) { + case 0: + return; + case 2: + state_1 = 2; + return; + case 1: + state_1 = 1; + return true; + default: + ts.Debug.assertNever(childState); + } + }); + return state_1; + } + case 244: + return getModuleInstanceState(node); + case 72: + if (node.isInJSDocNamespace) { + return 0; + } + } + return 1; + } + var binder = createBinder(); + function bindSourceFile(file, options) { + ts.performance.mark("beforeBind"); + binder(file, options); + ts.performance.mark("afterBind"); + ts.performance.measure("Bind", "beforeBind", "afterBind"); + } + ts.bindSourceFile = bindSourceFile; + function createBinder() { + var file; + var options; + var languageVersion; + var parent; + var container; + var thisParentContainer; + var blockScopeContainer; + var lastContainer; + var delayedTypeAliases; + var seenThisKeyword; + var currentFlow; + var currentBreakTarget; + var currentContinueTarget; + var currentReturnTarget; + var currentTrueTarget; + var currentFalseTarget; + var preSwitchCaseFlow; + var activeLabels; + var hasExplicitReturn; + var emitFlags; + var inStrictMode; + var symbolCount = 0; + var Symbol; + var classifiableNames; + var unreachableFlow = { flags: 1 }; + var reportedUnreachableFlow = { flags: 1 }; + var subtreeTransformFlags = 0; + var skipTransformFlagAggregation; + function createDiagnosticForNode(node, message, arg0, arg1, arg2) { + return ts.createDiagnosticForNodeInSourceFile(ts.getSourceFileOfNode(node) || file, node, message, arg0, arg1, arg2); + } + function bindSourceFile(f, opts) { + file = f; + options = opts; + languageVersion = ts.getEmitScriptTarget(options); + inStrictMode = bindInStrictMode(file, opts); + classifiableNames = ts.createUnderscoreEscapedMap(); + symbolCount = 0; + skipTransformFlagAggregation = file.isDeclarationFile; + Symbol = ts.objectAllocator.getSymbolConstructor(); + if (!file.locals) { + bind(file); + file.symbolCount = symbolCount; + file.classifiableNames = classifiableNames; + delayedBindJSDocTypedefTag(); + } + file = undefined; + options = undefined; + languageVersion = undefined; + parent = undefined; + container = undefined; + thisParentContainer = undefined; + blockScopeContainer = undefined; + lastContainer = undefined; + delayedTypeAliases = undefined; + seenThisKeyword = false; + currentFlow = undefined; + currentBreakTarget = undefined; + currentContinueTarget = undefined; + currentReturnTarget = undefined; + currentTrueTarget = undefined; + currentFalseTarget = undefined; + activeLabels = undefined; + hasExplicitReturn = false; + emitFlags = 0; + subtreeTransformFlags = 0; + } + return bindSourceFile; + function bindInStrictMode(file, opts) { + if (ts.getStrictOptionValue(opts, "alwaysStrict") && !file.isDeclarationFile) { + return true; + } + else { + return !!file.externalModuleIndicator; + } + } + function createSymbol(flags, name) { + symbolCount++; + return new Symbol(flags, name); + } + function addDeclarationToSymbol(symbol, node, symbolFlags) { + symbol.flags |= symbolFlags; + node.symbol = symbol; + symbol.declarations = ts.append(symbol.declarations, node); + if (symbolFlags & (32 | 384 | 1536 | 3) && !symbol.exports) { + symbol.exports = ts.createSymbolTable(); + } + if (symbolFlags & (32 | 64 | 2048 | 4096) && !symbol.members) { + symbol.members = ts.createSymbolTable(); + } + if (symbolFlags & 67220415) { + setValueDeclaration(symbol, node); + } + } + function setValueDeclaration(symbol, node) { + var valueDeclaration = symbol.valueDeclaration; + if (!valueDeclaration || + (ts.isAssignmentDeclaration(valueDeclaration) && !ts.isAssignmentDeclaration(node)) || + (valueDeclaration.kind !== node.kind && ts.isEffectiveModuleDeclaration(valueDeclaration))) { + symbol.valueDeclaration = node; + } + } + function getDeclarationName(node) { + if (node.kind === 254) { + return node.isExportEquals ? "export=" : "default"; + } + var name = ts.getNameOfDeclaration(node); + if (name) { + if (ts.isAmbientModule(node)) { + var moduleName = ts.getTextOfIdentifierOrLiteral(name); + return (ts.isGlobalScopeAugmentation(node) ? "__global" : "\"" + moduleName + "\""); + } + if (name.kind === 149) { + var nameExpression = name.expression; + if (ts.isStringOrNumericLiteralLike(nameExpression)) { + return ts.escapeLeadingUnderscores(nameExpression.text); + } + ts.Debug.assert(ts.isWellKnownSymbolSyntactically(nameExpression)); + return ts.getPropertyNameForKnownSymbolName(ts.idText(nameExpression.name)); + } + return ts.isPropertyNameLiteral(name) ? ts.getEscapedTextOfIdentifierOrLiteral(name) : undefined; + } + switch (node.kind) { + case 157: + return "__constructor"; + case 165: + case 160: + case 293: + return "__call"; + case 166: + case 161: + return "__new"; + case 162: + return "__index"; + case 255: + return "__export"; + case 279: + return "export="; + case 204: + if (ts.getAssignmentDeclarationKind(node) === 2) { + return "export="; + } + ts.Debug.fail("Unknown binary declaration kind"); + break; + case 289: + return (ts.isJSDocConstructSignature(node) ? "__new" : "__call"); + case 151: + ts.Debug.assert(node.parent.kind === 289, "Impossible parameter parent kind", function () { return "parent is: " + (ts.SyntaxKind ? ts.SyntaxKind[node.parent.kind] : node.parent.kind) + ", expected JSDocFunctionType"; }); + var functionType = node.parent; + var index = functionType.parameters.indexOf(node); + return "arg" + index; + } + } + function getDisplayName(node) { + return ts.isNamedDeclaration(node) ? ts.declarationNameToString(node.name) : ts.unescapeLeadingUnderscores(ts.Debug.assertDefined(getDeclarationName(node))); + } + function declareSymbol(symbolTable, parent, node, includes, excludes, isReplaceableByMethod) { + ts.Debug.assert(!ts.hasDynamicName(node)); + var isDefaultExport = ts.hasModifier(node, 512); + var name = isDefaultExport && parent ? "default" : getDeclarationName(node); + var symbol; + if (name === undefined) { + symbol = createSymbol(0, "__missing"); + } + else { + symbol = symbolTable.get(name); + if (includes & 2885600) { + classifiableNames.set(name, true); + } + if (!symbol) { + symbolTable.set(name, symbol = createSymbol(0, name)); + if (isReplaceableByMethod) + symbol.isReplaceableByMethod = true; + } + else if (isReplaceableByMethod && !symbol.isReplaceableByMethod) { + return symbol; + } + else if (symbol.flags & excludes) { + if (symbol.isReplaceableByMethod) { + symbolTable.set(name, symbol = createSymbol(0, name)); + } + else if (!(includes & 3 && symbol.flags & 67108864)) { + if (ts.isNamedDeclaration(node)) { + node.name.parent = node; + } + var message_1 = symbol.flags & 2 + ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 + : ts.Diagnostics.Duplicate_identifier_0; + var messageNeedsName_1 = true; + if (symbol.flags & 384 || includes & 384) { + message_1 = ts.Diagnostics.Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations; + messageNeedsName_1 = false; + } + if (symbol.declarations && symbol.declarations.length) { + if (isDefaultExport) { + message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; + messageNeedsName_1 = false; + } + else { + if (symbol.declarations && symbol.declarations.length && + (node.kind === 254 && !node.isExportEquals)) { + message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; + messageNeedsName_1 = false; + } + } + } + var addError = function (decl) { + file.bindDiagnostics.push(createDiagnosticForNode(ts.getNameOfDeclaration(decl) || decl, message_1, messageNeedsName_1 ? getDisplayName(decl) : undefined)); + }; + ts.forEach(symbol.declarations, addError); + addError(node); + symbol = createSymbol(0, name); + } + } + } + addDeclarationToSymbol(symbol, node, includes); + if (symbol.parent) { + ts.Debug.assert(symbol.parent === parent, "Existing symbol parent should match new one"); + } + else { + symbol.parent = parent; + } + return symbol; + } + function declareModuleMember(node, symbolFlags, symbolExcludes) { + var hasExportModifier = ts.getCombinedModifierFlags(node) & 1; + if (symbolFlags & 2097152) { + if (node.kind === 257 || (node.kind === 248 && hasExportModifier)) { + return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); + } + else { + return declareSymbol(container.locals, undefined, node, symbolFlags, symbolExcludes); + } + } + else { + if (ts.isJSDocTypeAlias(node)) + ts.Debug.assert(ts.isInJSFile(node)); + if ((!ts.isAmbientModule(node) && (hasExportModifier || container.flags & 32)) || ts.isJSDocTypeAlias(node)) { + if (ts.hasModifier(node, 512) && !getDeclarationName(node)) { + return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); + } + var exportKind = symbolFlags & 67220415 ? 1048576 : 0; + var local = declareSymbol(container.locals, undefined, node, exportKind, symbolExcludes); + local.exportSymbol = declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); + node.localSymbol = local; + return local; + } + else { + return declareSymbol(container.locals, undefined, node, symbolFlags, symbolExcludes); + } + } + } + function bindContainer(node, containerFlags) { + var saveContainer = container; + var saveThisParentContainer = thisParentContainer; + var savedBlockScopeContainer = blockScopeContainer; + if (containerFlags & 1) { + if (node.kind !== 197) { + thisParentContainer = container; + } + container = blockScopeContainer = node; + if (containerFlags & 32) { + container.locals = ts.createSymbolTable(); + } + addToContainerChain(container); + } + else if (containerFlags & 2) { + blockScopeContainer = node; + blockScopeContainer.locals = undefined; + } + if (containerFlags & 4) { + var saveCurrentFlow = currentFlow; + var saveBreakTarget = currentBreakTarget; + var saveContinueTarget = currentContinueTarget; + var saveReturnTarget = currentReturnTarget; + var saveActiveLabels = activeLabels; + var saveHasExplicitReturn = hasExplicitReturn; + var isIIFE = containerFlags & 16 && !ts.hasModifier(node, 256) && + !node.asteriskToken && !!ts.getImmediatelyInvokedFunctionExpression(node); + if (!isIIFE) { + currentFlow = { flags: 2 }; + if (containerFlags & (16 | 128)) { + currentFlow.container = node; + } + } + currentReturnTarget = isIIFE || node.kind === 157 ? createBranchLabel() : undefined; + currentBreakTarget = undefined; + currentContinueTarget = undefined; + activeLabels = undefined; + hasExplicitReturn = false; + bindChildren(node); + node.flags &= ~1408; + if (!(currentFlow.flags & 1) && containerFlags & 8 && ts.nodeIsPresent(node.body)) { + node.flags |= 128; + if (hasExplicitReturn) + node.flags |= 256; + } + if (node.kind === 279) { + node.flags |= emitFlags; + } + if (currentReturnTarget) { + addAntecedent(currentReturnTarget, currentFlow); + currentFlow = finishFlowLabel(currentReturnTarget); + if (node.kind === 157) { + node.returnFlowNode = currentFlow; + } + } + if (!isIIFE) { + currentFlow = saveCurrentFlow; + } + currentBreakTarget = saveBreakTarget; + currentContinueTarget = saveContinueTarget; + currentReturnTarget = saveReturnTarget; + activeLabels = saveActiveLabels; + hasExplicitReturn = saveHasExplicitReturn; + } + else if (containerFlags & 64) { + seenThisKeyword = false; + bindChildren(node); + node.flags = seenThisKeyword ? node.flags | 64 : node.flags & ~64; + } + else { + bindChildren(node); + } + container = saveContainer; + thisParentContainer = saveThisParentContainer; + blockScopeContainer = savedBlockScopeContainer; + } + function bindChildren(node) { + if (skipTransformFlagAggregation) { + bindChildrenWorker(node); + } + else if (node.transformFlags & 536870912) { + skipTransformFlagAggregation = true; + bindChildrenWorker(node); + skipTransformFlagAggregation = false; + subtreeTransformFlags |= node.transformFlags & ~getTransformFlagsSubtreeExclusions(node.kind); + } + else { + var savedSubtreeTransformFlags = subtreeTransformFlags; + subtreeTransformFlags = 0; + bindChildrenWorker(node); + subtreeTransformFlags = savedSubtreeTransformFlags | computeTransformFlagsForNode(node, subtreeTransformFlags); + } + } + function bindEachFunctionsFirst(nodes) { + bindEach(nodes, function (n) { return n.kind === 239 ? bind(n) : undefined; }); + bindEach(nodes, function (n) { return n.kind !== 239 ? bind(n) : undefined; }); + } + function bindEach(nodes, bindFunction) { + if (bindFunction === void 0) { bindFunction = bind; } + if (nodes === undefined) { + return; + } + if (skipTransformFlagAggregation) { + ts.forEach(nodes, bindFunction); + } + else { + var savedSubtreeTransformFlags = subtreeTransformFlags; + subtreeTransformFlags = 0; + var nodeArrayFlags = 0; + for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) { + var node = nodes_2[_i]; + bindFunction(node); + nodeArrayFlags |= node.transformFlags & ~536870912; + } + nodes.transformFlags = nodeArrayFlags | 536870912; + subtreeTransformFlags |= savedSubtreeTransformFlags; + } + } + function bindEachChild(node) { + ts.forEachChild(node, bind, bindEach); + } + function bindChildrenWorker(node) { + if (checkUnreachable(node)) { + bindEachChild(node); + bindJSDoc(node); + return; + } + switch (node.kind) { + case 224: + bindWhileStatement(node); + break; + case 223: + bindDoStatement(node); + break; + case 225: + bindForStatement(node); + break; + case 226: + case 227: + bindForInOrForOfStatement(node); + break; + case 222: + bindIfStatement(node); + break; + case 230: + case 234: + bindReturnOrThrow(node); + break; + case 229: + case 228: + bindBreakOrContinueStatement(node); + break; + case 235: + bindTryStatement(node); + break; + case 232: + bindSwitchStatement(node); + break; + case 246: + bindCaseBlock(node); + break; + case 271: + bindCaseClause(node); + break; + case 233: + bindLabeledStatement(node); + break; + case 202: + bindPrefixUnaryExpressionFlow(node); + break; + case 203: + bindPostfixUnaryExpressionFlow(node); + break; + case 204: + bindBinaryExpressionFlow(node); + break; + case 198: + bindDeleteExpressionFlow(node); + break; + case 205: + bindConditionalExpressionFlow(node); + break; + case 237: + bindVariableDeclarationFlow(node); + break; + case 191: + bindCallExpressionFlow(node); + break; + case 304: + case 297: + bindJSDocTypeAlias(node); + break; + case 279: { + bindEachFunctionsFirst(node.statements); + bind(node.endOfFileToken); + break; + } + case 218: + case 245: + bindEachFunctionsFirst(node.statements); + break; + default: + bindEachChild(node); + break; + } + bindJSDoc(node); + } + function isNarrowingExpression(expr) { + switch (expr.kind) { + case 72: + case 100: + case 189: + case 190: + return isNarrowableReference(expr); + case 191: + return hasNarrowableArgument(expr); + case 195: + return isNarrowingExpression(expr.expression); + case 204: + return isNarrowingBinaryExpression(expr); + case 202: + return expr.operator === 52 && isNarrowingExpression(expr.operand); + case 199: + return isNarrowingExpression(expr.expression); + } + return false; + } + function isNarrowableReference(expr) { + return expr.kind === 72 || expr.kind === 100 || expr.kind === 98 || + ts.isPropertyAccessExpression(expr) && isNarrowableReference(expr.expression) || + ts.isElementAccessExpression(expr) && expr.argumentExpression && + (ts.isStringLiteral(expr.argumentExpression) || ts.isNumericLiteral(expr.argumentExpression)) && + isNarrowableReference(expr.expression); + } + function hasNarrowableArgument(expr) { + if (expr.arguments) { + for (var _i = 0, _a = expr.arguments; _i < _a.length; _i++) { + var argument = _a[_i]; + if (isNarrowableReference(argument)) { + return true; + } + } + } + if (expr.expression.kind === 189 && + isNarrowableReference(expr.expression.expression)) { + return true; + } + return false; + } + function isNarrowingTypeofOperands(expr1, expr2) { + return ts.isTypeOfExpression(expr1) && isNarrowableOperand(expr1.expression) && ts.isStringLiteralLike(expr2); + } + function isNarrowableInOperands(left, right) { + return ts.isStringLiteralLike(left) && isNarrowingExpression(right); + } + function isNarrowingBinaryExpression(expr) { + switch (expr.operatorToken.kind) { + case 59: + return isNarrowableReference(expr.left); + case 33: + case 34: + case 35: + case 36: + return isNarrowableOperand(expr.left) || isNarrowableOperand(expr.right) || + isNarrowingTypeofOperands(expr.right, expr.left) || isNarrowingTypeofOperands(expr.left, expr.right); + case 94: + return isNarrowableOperand(expr.left); + case 93: + return isNarrowableInOperands(expr.left, expr.right); + case 27: + return isNarrowingExpression(expr.right); + } + return false; + } + function isNarrowableOperand(expr) { + switch (expr.kind) { + case 195: + return isNarrowableOperand(expr.expression); + case 204: + switch (expr.operatorToken.kind) { + case 59: + return isNarrowableOperand(expr.left); + case 27: + return isNarrowableOperand(expr.right); + } + } + return isNarrowableReference(expr); + } + function createBranchLabel() { + return { + flags: 4, + antecedents: undefined + }; + } + function createLoopLabel() { + return { + flags: 8, + antecedents: undefined + }; + } + function setFlowNodeReferenced(flow) { + flow.flags |= flow.flags & 512 ? 1024 : 512; + } + function addAntecedent(label, antecedent) { + if (!(antecedent.flags & 1) && !ts.contains(label.antecedents, antecedent)) { + (label.antecedents || (label.antecedents = [])).push(antecedent); + setFlowNodeReferenced(antecedent); + } + } + function createFlowCondition(flags, antecedent, expression) { + if (antecedent.flags & 1) { + return antecedent; + } + if (!expression) { + return flags & 32 ? antecedent : unreachableFlow; + } + if (expression.kind === 102 && flags & 64 || + expression.kind === 87 && flags & 32) { + return unreachableFlow; + } + if (!isNarrowingExpression(expression)) { + return antecedent; + } + setFlowNodeReferenced(antecedent); + return { flags: flags, expression: expression, antecedent: antecedent }; + } + function createFlowSwitchClause(antecedent, switchStatement, clauseStart, clauseEnd) { + if (!isNarrowingExpression(switchStatement.expression)) { + return antecedent; + } + setFlowNodeReferenced(antecedent); + return { flags: 128, switchStatement: switchStatement, clauseStart: clauseStart, clauseEnd: clauseEnd, antecedent: antecedent }; + } + function createFlowAssignment(antecedent, node) { + setFlowNodeReferenced(antecedent); + return { flags: 16, antecedent: antecedent, node: node }; + } + function createFlowArrayMutation(antecedent, node) { + setFlowNodeReferenced(antecedent); + var res = { flags: 256, antecedent: antecedent, node: node }; + return res; + } + function finishFlowLabel(flow) { + var antecedents = flow.antecedents; + if (!antecedents) { + return unreachableFlow; + } + if (antecedents.length === 1) { + return antecedents[0]; + } + return flow; + } + function isStatementCondition(node) { + var parent = node.parent; + switch (parent.kind) { + case 222: + case 224: + case 223: + return parent.expression === node; + case 225: + case 205: + return parent.condition === node; + } + return false; + } + function isLogicalExpression(node) { + while (true) { + if (node.kind === 195) { + node = node.expression; + } + else if (node.kind === 202 && node.operator === 52) { + node = node.operand; + } + else { + return node.kind === 204 && (node.operatorToken.kind === 54 || + node.operatorToken.kind === 55); + } + } + } + function isTopLevelLogicalExpression(node) { + while (node.parent.kind === 195 || + node.parent.kind === 202 && + node.parent.operator === 52) { + node = node.parent; + } + return !isStatementCondition(node) && !isLogicalExpression(node.parent); + } + function bindCondition(node, trueTarget, falseTarget) { + var saveTrueTarget = currentTrueTarget; + var saveFalseTarget = currentFalseTarget; + currentTrueTarget = trueTarget; + currentFalseTarget = falseTarget; + bind(node); + currentTrueTarget = saveTrueTarget; + currentFalseTarget = saveFalseTarget; + if (!node || !isLogicalExpression(node)) { + addAntecedent(trueTarget, createFlowCondition(32, currentFlow, node)); + addAntecedent(falseTarget, createFlowCondition(64, currentFlow, node)); + } + } + function bindIterativeStatement(node, breakTarget, continueTarget) { + var saveBreakTarget = currentBreakTarget; + var saveContinueTarget = currentContinueTarget; + currentBreakTarget = breakTarget; + currentContinueTarget = continueTarget; + bind(node); + currentBreakTarget = saveBreakTarget; + currentContinueTarget = saveContinueTarget; + } + function bindWhileStatement(node) { + var preWhileLabel = createLoopLabel(); + var preBodyLabel = createBranchLabel(); + var postWhileLabel = createBranchLabel(); + addAntecedent(preWhileLabel, currentFlow); + currentFlow = preWhileLabel; + bindCondition(node.expression, preBodyLabel, postWhileLabel); + currentFlow = finishFlowLabel(preBodyLabel); + bindIterativeStatement(node.statement, postWhileLabel, preWhileLabel); + addAntecedent(preWhileLabel, currentFlow); + currentFlow = finishFlowLabel(postWhileLabel); + } + function bindDoStatement(node) { + var preDoLabel = createLoopLabel(); + var enclosingLabeledStatement = node.parent.kind === 233 + ? ts.lastOrUndefined(activeLabels) + : undefined; + var preConditionLabel = enclosingLabeledStatement ? enclosingLabeledStatement.continueTarget : createBranchLabel(); + var postDoLabel = enclosingLabeledStatement ? enclosingLabeledStatement.breakTarget : createBranchLabel(); + addAntecedent(preDoLabel, currentFlow); + currentFlow = preDoLabel; + bindIterativeStatement(node.statement, postDoLabel, preConditionLabel); + addAntecedent(preConditionLabel, currentFlow); + currentFlow = finishFlowLabel(preConditionLabel); + bindCondition(node.expression, preDoLabel, postDoLabel); + currentFlow = finishFlowLabel(postDoLabel); + } + function bindForStatement(node) { + var preLoopLabel = createLoopLabel(); + var preBodyLabel = createBranchLabel(); + var postLoopLabel = createBranchLabel(); + bind(node.initializer); + addAntecedent(preLoopLabel, currentFlow); + currentFlow = preLoopLabel; + bindCondition(node.condition, preBodyLabel, postLoopLabel); + currentFlow = finishFlowLabel(preBodyLabel); + bindIterativeStatement(node.statement, postLoopLabel, preLoopLabel); + bind(node.incrementor); + addAntecedent(preLoopLabel, currentFlow); + currentFlow = finishFlowLabel(postLoopLabel); + } + function bindForInOrForOfStatement(node) { + var preLoopLabel = createLoopLabel(); + var postLoopLabel = createBranchLabel(); + addAntecedent(preLoopLabel, currentFlow); + currentFlow = preLoopLabel; + if (node.kind === 227) { + bind(node.awaitModifier); + } + bind(node.expression); + addAntecedent(postLoopLabel, currentFlow); + bind(node.initializer); + if (node.initializer.kind !== 238) { + bindAssignmentTargetFlow(node.initializer); + } + bindIterativeStatement(node.statement, postLoopLabel, preLoopLabel); + addAntecedent(preLoopLabel, currentFlow); + currentFlow = finishFlowLabel(postLoopLabel); + } + function bindIfStatement(node) { + var thenLabel = createBranchLabel(); + var elseLabel = createBranchLabel(); + var postIfLabel = createBranchLabel(); + bindCondition(node.expression, thenLabel, elseLabel); + currentFlow = finishFlowLabel(thenLabel); + bind(node.thenStatement); + addAntecedent(postIfLabel, currentFlow); + currentFlow = finishFlowLabel(elseLabel); + bind(node.elseStatement); + addAntecedent(postIfLabel, currentFlow); + currentFlow = finishFlowLabel(postIfLabel); + } + function bindReturnOrThrow(node) { + bind(node.expression); + if (node.kind === 230) { + hasExplicitReturn = true; + if (currentReturnTarget) { + addAntecedent(currentReturnTarget, currentFlow); + } + } + currentFlow = unreachableFlow; + } + function findActiveLabel(name) { + if (activeLabels) { + for (var _i = 0, activeLabels_1 = activeLabels; _i < activeLabels_1.length; _i++) { + var label = activeLabels_1[_i]; + if (label.name === name) { + return label; + } + } + } + return undefined; + } + function bindBreakOrContinueFlow(node, breakTarget, continueTarget) { + var flowLabel = node.kind === 229 ? breakTarget : continueTarget; + if (flowLabel) { + addAntecedent(flowLabel, currentFlow); + currentFlow = unreachableFlow; + } + } + function bindBreakOrContinueStatement(node) { + bind(node.label); + if (node.label) { + var activeLabel = findActiveLabel(node.label.escapedText); + if (activeLabel) { + activeLabel.referenced = true; + bindBreakOrContinueFlow(node, activeLabel.breakTarget, activeLabel.continueTarget); + } + } + else { + bindBreakOrContinueFlow(node, currentBreakTarget, currentContinueTarget); + } + } + function bindTryStatement(node) { + var preFinallyLabel = createBranchLabel(); + var preTryFlow = currentFlow; + bind(node.tryBlock); + addAntecedent(preFinallyLabel, currentFlow); + var flowAfterTry = currentFlow; + var flowAfterCatch = unreachableFlow; + if (node.catchClause) { + currentFlow = preTryFlow; + bind(node.catchClause); + addAntecedent(preFinallyLabel, currentFlow); + flowAfterCatch = currentFlow; + } + if (node.finallyBlock) { + var preFinallyFlow = { flags: 2048, antecedent: preTryFlow, lock: {} }; + addAntecedent(preFinallyLabel, preFinallyFlow); + currentFlow = finishFlowLabel(preFinallyLabel); + bind(node.finallyBlock); + if (!(currentFlow.flags & 1)) { + if ((flowAfterTry.flags & 1) && (flowAfterCatch.flags & 1)) { + currentFlow = flowAfterTry === reportedUnreachableFlow || flowAfterCatch === reportedUnreachableFlow + ? reportedUnreachableFlow + : unreachableFlow; + } + } + if (!(currentFlow.flags & 1)) { + var afterFinallyFlow = { flags: 4096, antecedent: currentFlow }; + preFinallyFlow.lock = afterFinallyFlow; + currentFlow = afterFinallyFlow; + } + } + else { + currentFlow = finishFlowLabel(preFinallyLabel); + } + } + function bindSwitchStatement(node) { + var postSwitchLabel = createBranchLabel(); + bind(node.expression); + var saveBreakTarget = currentBreakTarget; + var savePreSwitchCaseFlow = preSwitchCaseFlow; + currentBreakTarget = postSwitchLabel; + preSwitchCaseFlow = currentFlow; + bind(node.caseBlock); + addAntecedent(postSwitchLabel, currentFlow); + var hasDefault = ts.forEach(node.caseBlock.clauses, function (c) { return c.kind === 272; }); + node.possiblyExhaustive = !hasDefault && !postSwitchLabel.antecedents; + if (!hasDefault) { + addAntecedent(postSwitchLabel, createFlowSwitchClause(preSwitchCaseFlow, node, 0, 0)); + } + currentBreakTarget = saveBreakTarget; + preSwitchCaseFlow = savePreSwitchCaseFlow; + currentFlow = finishFlowLabel(postSwitchLabel); + } + function bindCaseBlock(node) { + var savedSubtreeTransformFlags = subtreeTransformFlags; + subtreeTransformFlags = 0; + var clauses = node.clauses; + var fallthroughFlow = unreachableFlow; + for (var i = 0; i < clauses.length; i++) { + var clauseStart = i; + while (!clauses[i].statements.length && i + 1 < clauses.length) { + bind(clauses[i]); + i++; + } + var preCaseLabel = createBranchLabel(); + addAntecedent(preCaseLabel, createFlowSwitchClause(preSwitchCaseFlow, node.parent, clauseStart, i + 1)); + addAntecedent(preCaseLabel, fallthroughFlow); + currentFlow = finishFlowLabel(preCaseLabel); + var clause = clauses[i]; + bind(clause); + fallthroughFlow = currentFlow; + if (!(currentFlow.flags & 1) && i !== clauses.length - 1 && options.noFallthroughCasesInSwitch) { + errorOnFirstToken(clause, ts.Diagnostics.Fallthrough_case_in_switch); + } + } + clauses.transformFlags = subtreeTransformFlags | 536870912; + subtreeTransformFlags |= savedSubtreeTransformFlags; + } + function bindCaseClause(node) { + var saveCurrentFlow = currentFlow; + currentFlow = preSwitchCaseFlow; + bind(node.expression); + currentFlow = saveCurrentFlow; + bindEach(node.statements); + } + function pushActiveLabel(name, breakTarget, continueTarget) { + var activeLabel = { + name: name, + breakTarget: breakTarget, + continueTarget: continueTarget, + referenced: false + }; + (activeLabels || (activeLabels = [])).push(activeLabel); + return activeLabel; + } + function popActiveLabel() { + activeLabels.pop(); + } + function bindLabeledStatement(node) { + var preStatementLabel = createLoopLabel(); + var postStatementLabel = createBranchLabel(); + bind(node.label); + addAntecedent(preStatementLabel, currentFlow); + var activeLabel = pushActiveLabel(node.label.escapedText, postStatementLabel, preStatementLabel); + bind(node.statement); + popActiveLabel(); + if (!activeLabel.referenced && !options.allowUnusedLabels) { + errorOrSuggestionOnNode(ts.unusedLabelIsError(options), node.label, ts.Diagnostics.Unused_label); + } + if (!node.statement || node.statement.kind !== 223) { + addAntecedent(postStatementLabel, currentFlow); + currentFlow = finishFlowLabel(postStatementLabel); + } + } + function bindDestructuringTargetFlow(node) { + if (node.kind === 204 && node.operatorToken.kind === 59) { + bindAssignmentTargetFlow(node.left); + } + else { + bindAssignmentTargetFlow(node); + } + } + function bindAssignmentTargetFlow(node) { + if (isNarrowableReference(node)) { + currentFlow = createFlowAssignment(currentFlow, node); + } + else if (node.kind === 187) { + for (var _i = 0, _a = node.elements; _i < _a.length; _i++) { + var e = _a[_i]; + if (e.kind === 208) { + bindAssignmentTargetFlow(e.expression); + } + else { + bindDestructuringTargetFlow(e); + } + } + } + else if (node.kind === 188) { + for (var _b = 0, _c = node.properties; _b < _c.length; _b++) { + var p = _c[_b]; + if (p.kind === 275) { + bindDestructuringTargetFlow(p.initializer); + } + else if (p.kind === 276) { + bindAssignmentTargetFlow(p.name); + } + else if (p.kind === 277) { + bindAssignmentTargetFlow(p.expression); + } + } + } + } + function bindLogicalExpression(node, trueTarget, falseTarget) { + var preRightLabel = createBranchLabel(); + if (node.operatorToken.kind === 54) { + bindCondition(node.left, preRightLabel, falseTarget); + } + else { + bindCondition(node.left, trueTarget, preRightLabel); + } + currentFlow = finishFlowLabel(preRightLabel); + bind(node.operatorToken); + bindCondition(node.right, trueTarget, falseTarget); + } + function bindPrefixUnaryExpressionFlow(node) { + if (node.operator === 52) { + var saveTrueTarget = currentTrueTarget; + currentTrueTarget = currentFalseTarget; + currentFalseTarget = saveTrueTarget; + bindEachChild(node); + currentFalseTarget = currentTrueTarget; + currentTrueTarget = saveTrueTarget; + } + else { + bindEachChild(node); + if (node.operator === 44 || node.operator === 45) { + bindAssignmentTargetFlow(node.operand); + } + } + } + function bindPostfixUnaryExpressionFlow(node) { + bindEachChild(node); + if (node.operator === 44 || node.operator === 45) { + bindAssignmentTargetFlow(node.operand); + } + } + function bindBinaryExpressionFlow(node) { + var operator = node.operatorToken.kind; + if (operator === 54 || operator === 55) { + if (isTopLevelLogicalExpression(node)) { + var postExpressionLabel = createBranchLabel(); + bindLogicalExpression(node, postExpressionLabel, postExpressionLabel); + currentFlow = finishFlowLabel(postExpressionLabel); + } + else { + bindLogicalExpression(node, currentTrueTarget, currentFalseTarget); + } + } + else { + bindEachChild(node); + if (ts.isAssignmentOperator(operator) && !ts.isAssignmentTarget(node)) { + bindAssignmentTargetFlow(node.left); + if (operator === 59 && node.left.kind === 190) { + var elementAccess = node.left; + if (isNarrowableOperand(elementAccess.expression)) { + currentFlow = createFlowArrayMutation(currentFlow, node); + } + } + } + } + } + function bindDeleteExpressionFlow(node) { + bindEachChild(node); + if (node.expression.kind === 189) { + bindAssignmentTargetFlow(node.expression); + } + } + function bindConditionalExpressionFlow(node) { + var trueLabel = createBranchLabel(); + var falseLabel = createBranchLabel(); + var postExpressionLabel = createBranchLabel(); + bindCondition(node.condition, trueLabel, falseLabel); + currentFlow = finishFlowLabel(trueLabel); + bind(node.questionToken); + bind(node.whenTrue); + addAntecedent(postExpressionLabel, currentFlow); + currentFlow = finishFlowLabel(falseLabel); + bind(node.colonToken); + bind(node.whenFalse); + addAntecedent(postExpressionLabel, currentFlow); + currentFlow = finishFlowLabel(postExpressionLabel); + } + function bindInitializedVariableFlow(node) { + var name = !ts.isOmittedExpression(node) ? node.name : undefined; + if (ts.isBindingPattern(name)) { + for (var _i = 0, _a = name.elements; _i < _a.length; _i++) { + var child = _a[_i]; + bindInitializedVariableFlow(child); + } + } + else { + currentFlow = createFlowAssignment(currentFlow, node); + } + } + function bindVariableDeclarationFlow(node) { + bindEachChild(node); + if (node.initializer || ts.isForInOrOfStatement(node.parent.parent)) { + bindInitializedVariableFlow(node); + } + } + function bindJSDocTypeAlias(node) { + node.tagName.parent = node; + if (node.fullName) { + setParentPointers(node, node.fullName); + } + } + function bindCallExpressionFlow(node) { + var expr = node.expression; + while (expr.kind === 195) { + expr = expr.expression; + } + if (expr.kind === 196 || expr.kind === 197) { + bindEach(node.typeArguments); + bindEach(node.arguments); + bind(node.expression); + } + else { + bindEachChild(node); + } + if (node.expression.kind === 189) { + var propertyAccess = node.expression; + if (isNarrowableOperand(propertyAccess.expression) && ts.isPushOrUnshiftIdentifier(propertyAccess.name)) { + currentFlow = createFlowArrayMutation(currentFlow, node); + } + } + } + function getContainerFlags(node) { + switch (node.kind) { + case 209: + case 240: + case 243: + case 188: + case 168: + case 292: + case 268: + return 1; + case 241: + return 1 | 64; + case 244: + case 242: + case 181: + return 1 | 32; + case 279: + return 1 | 4 | 32; + case 156: + if (ts.isObjectLiteralOrClassExpressionMethod(node)) { + return 1 | 4 | 32 | 8 | 128; + } + case 157: + case 239: + case 155: + case 158: + case 159: + case 160: + case 293: + case 289: + case 165: + case 161: + case 162: + case 166: + return 1 | 4 | 32 | 8; + case 196: + case 197: + return 1 | 4 | 32 | 8 | 16; + case 245: + return 4; + case 154: + return node.initializer ? 4 : 0; + case 274: + case 225: + case 226: + case 227: + case 246: + return 2; + case 218: + return ts.isFunctionLike(node.parent) ? 0 : 2; + } + return 0; + } + function addToContainerChain(next) { + if (lastContainer) { + lastContainer.nextContainer = next; + } + lastContainer = next; + } + function declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes) { + switch (container.kind) { + case 244: + return declareModuleMember(node, symbolFlags, symbolExcludes); + case 279: + return declareSourceFileMember(node, symbolFlags, symbolExcludes); + case 209: + case 240: + return declareClassMember(node, symbolFlags, symbolExcludes); + case 243: + return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); + case 168: + case 292: + case 188: + case 241: + case 268: + return declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes); + case 165: + case 166: + case 160: + case 161: + case 293: + case 162: + case 156: + case 155: + case 157: + case 158: + case 159: + case 239: + case 196: + case 197: + case 289: + case 304: + case 297: + case 242: + case 181: + return declareSymbol(container.locals, undefined, node, symbolFlags, symbolExcludes); + } + } + function declareClassMember(node, symbolFlags, symbolExcludes) { + return ts.hasModifier(node, 32) + ? declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes) + : declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes); + } + function declareSourceFileMember(node, symbolFlags, symbolExcludes) { + return ts.isExternalModule(file) + ? declareModuleMember(node, symbolFlags, symbolExcludes) + : declareSymbol(file.locals, undefined, node, symbolFlags, symbolExcludes); + } + function hasExportDeclarations(node) { + var body = node.kind === 279 ? node : node.body; + if (body && (body.kind === 279 || body.kind === 245)) { + for (var _i = 0, _a = body.statements; _i < _a.length; _i++) { + var stat = _a[_i]; + if (stat.kind === 255 || stat.kind === 254) { + return true; + } + } + } + return false; + } + function setExportContextFlag(node) { + if (node.flags & 4194304 && !hasExportDeclarations(node)) { + node.flags |= 32; + } + else { + node.flags &= ~32; + } + } + function bindModuleDeclaration(node) { + setExportContextFlag(node); + if (ts.isAmbientModule(node)) { + if (ts.hasModifier(node, 1)) { + errorOnFirstToken(node, ts.Diagnostics.export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always_visible); + } + if (ts.isModuleAugmentationExternal(node)) { + declareModuleSymbol(node); + } + else { + var pattern = void 0; + if (node.name.kind === 10) { + var text = node.name.text; + if (ts.hasZeroOrOneAsteriskCharacter(text)) { + pattern = ts.tryParsePattern(text); + } + else { + errorOnFirstToken(node.name, ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, text); + } + } + var symbol = declareSymbolAndAddToSymbolTable(node, 512, 110735); + file.patternAmbientModules = ts.append(file.patternAmbientModules, pattern && { pattern: pattern, symbol: symbol }); + } + } + else { + var state = declareModuleSymbol(node); + if (state !== 0) { + var symbol = node.symbol; + symbol.constEnumOnlyModule = (!(symbol.flags & (16 | 32 | 256))) + && state === 2 + && symbol.constEnumOnlyModule !== false; + } + } + } + function declareModuleSymbol(node) { + var state = getModuleInstanceState(node); + var instantiated = state !== 0; + declareSymbolAndAddToSymbolTable(node, instantiated ? 512 : 1024, instantiated ? 110735 : 0); + return state; + } + function bindFunctionOrConstructorType(node) { + var symbol = createSymbol(131072, getDeclarationName(node)); + addDeclarationToSymbol(symbol, node, 131072); + var typeLiteralSymbol = createSymbol(2048, "__type"); + addDeclarationToSymbol(typeLiteralSymbol, node, 2048); + typeLiteralSymbol.members = ts.createSymbolTable(); + typeLiteralSymbol.members.set(symbol.escapedName, symbol); + } + function bindObjectLiteralExpression(node) { + if (inStrictMode) { + var seen = ts.createUnderscoreEscapedMap(); + for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { + var prop = _a[_i]; + if (prop.kind === 277 || prop.name.kind !== 72) { + continue; + } + var identifier = prop.name; + var currentKind = prop.kind === 275 || prop.kind === 276 || prop.kind === 156 + ? 1 + : 2; + var existingKind = seen.get(identifier.escapedText); + if (!existingKind) { + seen.set(identifier.escapedText, currentKind); + continue; + } + if (currentKind === 1 && existingKind === 1) { + var span = ts.getErrorSpanForNode(file, identifier); + file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, ts.Diagnostics.An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode)); + } + } + } + return bindAnonymousDeclaration(node, 4096, "__object"); + } + function bindJsxAttributes(node) { + return bindAnonymousDeclaration(node, 4096, "__jsxAttributes"); + } + function bindJsxAttribute(node, symbolFlags, symbolExcludes) { + return declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes); + } + function bindAnonymousDeclaration(node, symbolFlags, name) { + var symbol = createSymbol(symbolFlags, name); + if (symbolFlags & (8 | 106500)) { + symbol.parent = container.symbol; + } + addDeclarationToSymbol(symbol, node, symbolFlags); + return symbol; + } + function bindBlockScopedDeclaration(node, symbolFlags, symbolExcludes) { + switch (blockScopeContainer.kind) { + case 244: + declareModuleMember(node, symbolFlags, symbolExcludes); + break; + case 279: + if (ts.isExternalOrCommonJsModule(container)) { + declareModuleMember(node, symbolFlags, symbolExcludes); + break; + } + default: + if (!blockScopeContainer.locals) { + blockScopeContainer.locals = ts.createSymbolTable(); + addToContainerChain(blockScopeContainer); + } + declareSymbol(blockScopeContainer.locals, undefined, node, symbolFlags, symbolExcludes); + } + } + function delayedBindJSDocTypedefTag() { + if (!delayedTypeAliases) { + return; + } + var saveContainer = container; + var saveLastContainer = lastContainer; + var saveBlockScopeContainer = blockScopeContainer; + var saveParent = parent; + var saveCurrentFlow = currentFlow; + for (var _i = 0, delayedTypeAliases_1 = delayedTypeAliases; _i < delayedTypeAliases_1.length; _i++) { + var typeAlias = delayedTypeAliases_1[_i]; + var host = ts.getJSDocHost(typeAlias); + container = ts.findAncestor(host.parent, function (n) { return !!(getContainerFlags(n) & 1); }) || file; + blockScopeContainer = ts.getEnclosingBlockScopeContainer(host) || file; + currentFlow = { flags: 2 }; + parent = typeAlias; + bind(typeAlias.typeExpression); + if (!typeAlias.fullName || typeAlias.fullName.kind === 72) { + parent = typeAlias.parent; + bindBlockScopedDeclaration(typeAlias, 524288, 67897832); + } + else { + bind(typeAlias.fullName); + } + } + container = saveContainer; + lastContainer = saveLastContainer; + blockScopeContainer = saveBlockScopeContainer; + parent = saveParent; + currentFlow = saveCurrentFlow; + } + function checkStrictModeIdentifier(node) { + if (inStrictMode && + node.originalKeywordKind >= 109 && + node.originalKeywordKind <= 117 && + !ts.isIdentifierName(node) && + !(node.flags & 4194304)) { + if (!file.parseDiagnostics.length) { + file.bindDiagnostics.push(createDiagnosticForNode(node, getStrictModeIdentifierMessage(node), ts.declarationNameToString(node))); + } + } + } + function getStrictModeIdentifierMessage(node) { + if (ts.getContainingClass(node)) { + return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode; + } + if (file.externalModuleIndicator) { + return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode; + } + return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode; + } + function checkStrictModeBinaryExpression(node) { + if (inStrictMode && ts.isLeftHandSideExpression(node.left) && ts.isAssignmentOperator(node.operatorToken.kind)) { + checkStrictModeEvalOrArguments(node, node.left); + } + } + function checkStrictModeCatchClause(node) { + if (inStrictMode && node.variableDeclaration) { + checkStrictModeEvalOrArguments(node, node.variableDeclaration.name); + } + } + function checkStrictModeDeleteExpression(node) { + if (inStrictMode && node.expression.kind === 72) { + var span = ts.getErrorSpanForNode(file, node.expression); + file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, ts.Diagnostics.delete_cannot_be_called_on_an_identifier_in_strict_mode)); + } + } + function isEvalOrArgumentsIdentifier(node) { + return ts.isIdentifier(node) && (node.escapedText === "eval" || node.escapedText === "arguments"); + } + function checkStrictModeEvalOrArguments(contextNode, name) { + if (name && name.kind === 72) { + var identifier = name; + if (isEvalOrArgumentsIdentifier(identifier)) { + var span = ts.getErrorSpanForNode(file, name); + file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, getStrictModeEvalOrArgumentsMessage(contextNode), ts.idText(identifier))); + } + } + } + function getStrictModeEvalOrArgumentsMessage(node) { + if (ts.getContainingClass(node)) { + return ts.Diagnostics.Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode; + } + if (file.externalModuleIndicator) { + return ts.Diagnostics.Invalid_use_of_0_Modules_are_automatically_in_strict_mode; + } + return ts.Diagnostics.Invalid_use_of_0_in_strict_mode; + } + function checkStrictModeFunctionName(node) { + if (inStrictMode) { + checkStrictModeEvalOrArguments(node, node.name); + } + } + function getStrictModeBlockScopeFunctionDeclarationMessage(node) { + if (ts.getContainingClass(node)) { + return ts.Diagnostics.Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_definitions_are_automatically_in_strict_mode; + } + if (file.externalModuleIndicator) { + return ts.Diagnostics.Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_are_automatically_in_strict_mode; + } + return ts.Diagnostics.Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5; + } + function checkStrictModeFunctionDeclaration(node) { + if (languageVersion < 2) { + if (blockScopeContainer.kind !== 279 && + blockScopeContainer.kind !== 244 && + !ts.isFunctionLike(blockScopeContainer)) { + var errorSpan = ts.getErrorSpanForNode(file, node); + file.bindDiagnostics.push(ts.createFileDiagnostic(file, errorSpan.start, errorSpan.length, getStrictModeBlockScopeFunctionDeclarationMessage(node))); + } + } + } + function checkStrictModeNumericLiteral(node) { + if (inStrictMode && node.numericLiteralFlags & 32) { + file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Octal_literals_are_not_allowed_in_strict_mode)); + } + } + function checkStrictModePostfixUnaryExpression(node) { + if (inStrictMode) { + checkStrictModeEvalOrArguments(node, node.operand); + } + } + function checkStrictModePrefixUnaryExpression(node) { + if (inStrictMode) { + if (node.operator === 44 || node.operator === 45) { + checkStrictModeEvalOrArguments(node, node.operand); + } + } + } + function checkStrictModeWithStatement(node) { + if (inStrictMode) { + errorOnFirstToken(node, ts.Diagnostics.with_statements_are_not_allowed_in_strict_mode); + } + } + function checkStrictModeLabeledStatement(node) { + if (inStrictMode && options.target >= 2) { + if (ts.isDeclarationStatement(node.statement) || ts.isVariableStatement(node.statement)) { + errorOnFirstToken(node.label, ts.Diagnostics.A_label_is_not_allowed_here); + } + } + } + function errorOnFirstToken(node, message, arg0, arg1, arg2) { + var span = ts.getSpanOfTokenAtPosition(file, node.pos); + file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, message, arg0, arg1, arg2)); + } + function errorOrSuggestionOnNode(isError, node, message) { + errorOrSuggestionOnRange(isError, node, node, message); + } + function errorOrSuggestionOnRange(isError, startNode, endNode, message) { + addErrorOrSuggestionDiagnostic(isError, { pos: ts.getTokenPosOfNode(startNode, file), end: endNode.end }, message); + } + function addErrorOrSuggestionDiagnostic(isError, range, message) { + var diag = ts.createFileDiagnostic(file, range.pos, range.end - range.pos, message); + if (isError) { + file.bindDiagnostics.push(diag); + } + else { + file.bindSuggestionDiagnostics = ts.append(file.bindSuggestionDiagnostics, __assign({}, diag, { category: ts.DiagnosticCategory.Suggestion })); + } + } + function bind(node) { + if (!node) { + return; + } + node.parent = parent; + var saveInStrictMode = inStrictMode; + bindWorker(node); + if (node.kind > 147) { + var saveParent = parent; + parent = node; + var containerFlags = getContainerFlags(node); + if (containerFlags === 0) { + bindChildren(node); + } + else { + bindContainer(node, containerFlags); + } + parent = saveParent; + } + else if (!skipTransformFlagAggregation && (node.transformFlags & 536870912) === 0) { + subtreeTransformFlags |= computeTransformFlagsForNode(node, 0); + var saveParent = parent; + if (node.kind === 1) + parent = node; + bindJSDoc(node); + parent = saveParent; + } + inStrictMode = saveInStrictMode; + } + function bindJSDoc(node) { + if (ts.hasJSDocNodes(node)) { + if (ts.isInJSFile(node)) { + for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { + var j = _a[_i]; + bind(j); + } + } + else { + for (var _b = 0, _c = node.jsDoc; _b < _c.length; _b++) { + var j = _c[_b]; + setParentPointers(node, j); + } + } + } + } + function updateStrictModeStatementList(statements) { + if (!inStrictMode) { + for (var _i = 0, statements_1 = statements; _i < statements_1.length; _i++) { + var statement = statements_1[_i]; + if (!ts.isPrologueDirective(statement)) { + return; + } + if (isUseStrictPrologueDirective(statement)) { + inStrictMode = true; + return; + } + } + } + } + function isUseStrictPrologueDirective(node) { + var nodeText = ts.getSourceTextOfNodeFromSourceFile(file, node.expression); + return nodeText === '"use strict"' || nodeText === "'use strict'"; + } + function bindWorker(node) { + switch (node.kind) { + case 72: + if (node.isInJSDocNamespace) { + var parentNode = node.parent; + while (parentNode && !ts.isJSDocTypeAlias(parentNode)) { + parentNode = parentNode.parent; + } + bindBlockScopedDeclaration(parentNode, 524288, 67897832); + break; + } + case 100: + if (currentFlow && (ts.isExpression(node) || parent.kind === 276)) { + node.flowNode = currentFlow; + } + return checkStrictModeIdentifier(node); + case 189: + case 190: + if (currentFlow && isNarrowableReference(node)) { + node.flowNode = currentFlow; + } + if (ts.isSpecialPropertyDeclaration(node)) { + bindSpecialPropertyDeclaration(node); + } + if (ts.isInJSFile(node) && + file.commonJsModuleIndicator && + ts.isModuleExportsPropertyAccessExpression(node) && + !lookupSymbolForNameWorker(blockScopeContainer, "module")) { + declareSymbol(file.locals, undefined, node.expression, 1 | 134217728, 67220414); + } + break; + case 204: + var specialKind = ts.getAssignmentDeclarationKind(node); + switch (specialKind) { + case 1: + bindExportsPropertyAssignment(node); + break; + case 2: + bindModuleExportsAssignment(node); + break; + case 3: + bindPrototypePropertyAssignment(node.left, node); + break; + case 6: + bindPrototypeAssignment(node); + break; + case 4: + bindThisPropertyAssignment(node); + break; + case 5: + bindSpecialPropertyAssignment(node); + break; + case 0: + break; + default: + ts.Debug.fail("Unknown binary expression special property assignment kind"); + } + return checkStrictModeBinaryExpression(node); + case 274: + return checkStrictModeCatchClause(node); + case 198: + return checkStrictModeDeleteExpression(node); + case 8: + return checkStrictModeNumericLiteral(node); + case 203: + return checkStrictModePostfixUnaryExpression(node); + case 202: + return checkStrictModePrefixUnaryExpression(node); + case 231: + return checkStrictModeWithStatement(node); + case 233: + return checkStrictModeLabeledStatement(node); + case 178: + seenThisKeyword = true; + return; + case 163: + break; + case 150: + return bindTypeParameter(node); + case 151: + return bindParameter(node); + case 237: + return bindVariableDeclarationOrBindingElement(node); + case 186: + node.flowNode = currentFlow; + return bindVariableDeclarationOrBindingElement(node); + case 154: + case 153: + return bindPropertyWorker(node); + case 275: + case 276: + return bindPropertyOrMethodOrAccessor(node, 4, 0); + case 278: + return bindPropertyOrMethodOrAccessor(node, 8, 68008959); + case 160: + case 161: + case 162: + return declareSymbolAndAddToSymbolTable(node, 131072, 0); + case 156: + case 155: + return bindPropertyOrMethodOrAccessor(node, 8192 | (node.questionToken ? 16777216 : 0), ts.isObjectLiteralMethod(node) ? 0 : 67212223); + case 239: + return bindFunctionDeclaration(node); + case 157: + return declareSymbolAndAddToSymbolTable(node, 16384, 0); + case 158: + return bindPropertyOrMethodOrAccessor(node, 32768, 67154879); + case 159: + return bindPropertyOrMethodOrAccessor(node, 65536, 67187647); + case 165: + case 289: + case 293: + case 166: + return bindFunctionOrConstructorType(node); + case 168: + case 292: + case 181: + return bindAnonymousTypeWorker(node); + case 188: + return bindObjectLiteralExpression(node); + case 196: + case 197: + return bindFunctionExpression(node); + case 191: + var assignmentKind = ts.getAssignmentDeclarationKind(node); + switch (assignmentKind) { + case 7: + return bindObjectDefinePropertyAssignment(node); + case 8: + return bindObjectDefinePropertyExport(node); + case 9: + return bindObjectDefinePrototypeProperty(node); + case 0: + break; + default: + return ts.Debug.fail("Unknown call expression assignment declaration kind"); + } + if (ts.isInJSFile(node)) { + bindCallExpression(node); + } + break; + case 209: + case 240: + inStrictMode = true; + return bindClassLikeDeclaration(node); + case 241: + return bindBlockScopedDeclaration(node, 64, 67897736); + case 242: + return bindBlockScopedDeclaration(node, 524288, 67897832); + case 243: + return bindEnumDeclaration(node); + case 244: + return bindModuleDeclaration(node); + case 268: + return bindJsxAttributes(node); + case 267: + return bindJsxAttribute(node, 4, 0); + case 248: + case 251: + case 253: + case 257: + return declareSymbolAndAddToSymbolTable(node, 2097152, 2097152); + case 247: + return bindNamespaceExportDeclaration(node); + case 250: + return bindImportClause(node); + case 255: + return bindExportDeclaration(node); + case 254: + return bindExportAssignment(node); + case 279: + updateStrictModeStatementList(node.statements); + return bindSourceFileIfExternalModule(); + case 218: + if (!ts.isFunctionLike(node.parent)) { + return; + } + case 245: + return updateStrictModeStatementList(node.statements); + case 299: + if (node.parent.kind === 293) { + return bindParameter(node); + } + if (node.parent.kind !== 292) { + break; + } + case 305: + var propTag = node; + var flags = propTag.isBracketed || propTag.typeExpression && propTag.typeExpression.type.kind === 288 ? + 4 | 16777216 : + 4; + return declareSymbolAndAddToSymbolTable(propTag, flags, 0); + case 304: + case 297: + return (delayedTypeAliases || (delayedTypeAliases = [])).push(node); + } + } + function bindPropertyWorker(node) { + return bindPropertyOrMethodOrAccessor(node, 4 | (node.questionToken ? 16777216 : 0), 0); + } + function bindAnonymousTypeWorker(node) { + return bindAnonymousDeclaration(node, 2048, "__type"); + } + function bindSourceFileIfExternalModule() { + setExportContextFlag(file); + if (ts.isExternalModule(file)) { + bindSourceFileAsExternalModule(); + } + else if (ts.isJsonSourceFile(file)) { + bindSourceFileAsExternalModule(); + var originalSymbol = file.symbol; + declareSymbol(file.symbol.exports, file.symbol, file, 4, 67108863); + file.symbol = originalSymbol; + } + } + function bindSourceFileAsExternalModule() { + bindAnonymousDeclaration(file, 512, "\"" + ts.removeFileExtension(file.fileName) + "\""); + } + function bindExportAssignment(node) { + if (!container.symbol || !container.symbol.exports) { + bindAnonymousDeclaration(node, 2097152, getDeclarationName(node)); + } + else { + var flags = ts.exportAssignmentIsAlias(node) + ? 2097152 + : 4; + var symbol = declareSymbol(container.symbol.exports, container.symbol, node, flags, 67108863); + if (node.isExportEquals) { + setValueDeclaration(symbol, node); + } + } + } + function bindNamespaceExportDeclaration(node) { + if (node.modifiers && node.modifiers.length) { + file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Modifiers_cannot_appear_here)); + } + var diag = !ts.isSourceFile(node.parent) ? ts.Diagnostics.Global_module_exports_may_only_appear_at_top_level + : !ts.isExternalModule(node.parent) ? ts.Diagnostics.Global_module_exports_may_only_appear_in_module_files + : !node.parent.isDeclarationFile ? ts.Diagnostics.Global_module_exports_may_only_appear_in_declaration_files + : undefined; + if (diag) { + file.bindDiagnostics.push(createDiagnosticForNode(node, diag)); + } + else { + file.symbol.globalExports = file.symbol.globalExports || ts.createSymbolTable(); + declareSymbol(file.symbol.globalExports, file.symbol, node, 2097152, 2097152); + } + } + function bindExportDeclaration(node) { + if (!container.symbol || !container.symbol.exports) { + bindAnonymousDeclaration(node, 8388608, getDeclarationName(node)); + } + else if (!node.exportClause) { + declareSymbol(container.symbol.exports, container.symbol, node, 8388608, 0); + } + } + function bindImportClause(node) { + if (node.name) { + declareSymbolAndAddToSymbolTable(node, 2097152, 2097152); + } + } + function setCommonJsModuleIndicator(node) { + if (file.externalModuleIndicator) { + return false; + } + if (!file.commonJsModuleIndicator) { + file.commonJsModuleIndicator = node; + bindSourceFileAsExternalModule(); + } + return true; + } + function bindObjectDefinePropertyExport(node) { + if (!setCommonJsModuleIndicator(node)) { + return; + } + var symbol = forEachIdentifierInEntityName(node.arguments[0], undefined, function (id, symbol) { + if (symbol) { + addDeclarationToSymbol(symbol, id, 1536 | 67108864); + } + return symbol; + }); + if (symbol) { + var flags = 4 | 1048576; + declareSymbol(symbol.exports, symbol, node, flags, 0); + } + } + function bindExportsPropertyAssignment(node) { + if (!setCommonJsModuleIndicator(node)) { + return; + } + var lhs = node.left; + var symbol = forEachIdentifierInEntityName(lhs.expression, undefined, function (id, symbol) { + if (symbol) { + addDeclarationToSymbol(symbol, id, 1536 | 67108864); + } + return symbol; + }); + if (symbol) { + var flags = ts.isClassExpression(node.right) ? + 4 | 1048576 | 32 : + 4 | 1048576; + declareSymbol(symbol.exports, symbol, lhs, flags, 0); + } + } + function bindModuleExportsAssignment(node) { + if (!setCommonJsModuleIndicator(node)) { + return; + } + var assignedExpression = ts.getRightMostAssignedExpression(node.right); + if (ts.isEmptyObjectLiteral(assignedExpression) || container === file && isExportsOrModuleExportsOrAlias(file, assignedExpression)) { + return; + } + var flags = ts.exportAssignmentIsAlias(node) + ? 2097152 + : 4 | 1048576 | 512; + declareSymbol(file.symbol.exports, file.symbol, node, flags | 67108864, 0); + } + function bindThisPropertyAssignment(node) { + ts.Debug.assert(ts.isInJSFile(node)); + var thisContainer = ts.getThisContainer(node, false); + switch (thisContainer.kind) { + case 239: + case 196: + var constructorSymbol = thisContainer.symbol; + if (ts.isBinaryExpression(thisContainer.parent) && thisContainer.parent.operatorToken.kind === 59) { + var l = thisContainer.parent.left; + if (ts.isPropertyAccessEntityNameExpression(l) && ts.isPrototypeAccess(l.expression)) { + constructorSymbol = lookupSymbolForPropertyAccess(l.expression.expression, thisParentContainer); + } + } + if (constructorSymbol) { + constructorSymbol.members = constructorSymbol.members || ts.createSymbolTable(); + declareSymbol(constructorSymbol.members, constructorSymbol, node, 4, 0 & ~4); + } + break; + case 157: + case 154: + case 156: + case 158: + case 159: + var containingClass = thisContainer.parent; + var symbolTable = ts.hasModifier(thisContainer, 32) ? containingClass.symbol.exports : containingClass.symbol.members; + declareSymbol(symbolTable, containingClass.symbol, node, 4, 0, true); + break; + case 279: + break; + default: + ts.Debug.fail(ts.Debug.showSyntaxKind(thisContainer)); + } + } + function bindSpecialPropertyDeclaration(node) { + if (node.expression.kind === 100) { + bindThisPropertyAssignment(node); + } + else if (ts.isPropertyAccessEntityNameExpression(node) && node.parent.parent.kind === 279) { + if (ts.isPrototypeAccess(node.expression)) { + bindPrototypePropertyAssignment(node, node.parent); + } + else { + bindStaticPropertyAssignment(node); + } + } + } + function bindPrototypeAssignment(node) { + node.left.parent = node; + node.right.parent = node; + var lhs = node.left; + bindPropertyAssignment(lhs.expression, lhs, false); + } + function bindObjectDefinePrototypeProperty(node) { + var namespaceSymbol = lookupSymbolForPropertyAccess(node.arguments[0].expression); + bindPotentiallyNewExpandoMemberToNamespace(node, namespaceSymbol, true); + } + function bindPrototypePropertyAssignment(lhs, parent) { + var classPrototype = lhs.expression; + var constructorFunction = classPrototype.expression; + lhs.parent = parent; + constructorFunction.parent = classPrototype; + classPrototype.parent = lhs; + bindPropertyAssignment(constructorFunction, lhs, true); + } + function bindObjectDefinePropertyAssignment(node) { + var namespaceSymbol = lookupSymbolForPropertyAccess(node.arguments[0]); + var isToplevel = node.parent.parent.kind === 279; + namespaceSymbol = bindPotentiallyMissingNamespaces(namespaceSymbol, node.arguments[0], isToplevel, false); + bindPotentiallyNewExpandoMemberToNamespace(node, namespaceSymbol, false); + } + function bindSpecialPropertyAssignment(node) { + var lhs = node.left; + var parentSymbol = lookupSymbolForPropertyAccess(lhs.expression); + if (!ts.isInJSFile(node) && !ts.isFunctionSymbol(parentSymbol)) { + return; + } + node.left.parent = node; + node.right.parent = node; + if (ts.isIdentifier(lhs.expression) && container === file && isNameOfExportsOrModuleExportsAliasDeclaration(file, lhs.expression)) { + bindExportsPropertyAssignment(node); + } + else { + bindStaticPropertyAssignment(lhs); + } + } + function bindStaticPropertyAssignment(node) { + node.expression.parent = node; + bindPropertyAssignment(node.expression, node, false); + } + function bindPotentiallyMissingNamespaces(namespaceSymbol, entityName, isToplevel, isPrototypeProperty) { + if (isToplevel && !isPrototypeProperty && (!namespaceSymbol || !(namespaceSymbol.flags & 1920))) { + var flags_1 = 1536 | 67108864; + var excludeFlags_1 = 110735 & ~67108864; + namespaceSymbol = forEachIdentifierInEntityName(entityName, namespaceSymbol, function (id, symbol, parent) { + if (symbol) { + addDeclarationToSymbol(symbol, id, flags_1); + return symbol; + } + else { + var table = parent ? parent.exports : + file.jsGlobalAugmentations || (file.jsGlobalAugmentations = ts.createSymbolTable()); + return declareSymbol(table, parent, id, flags_1, excludeFlags_1); + } + }); + } + return namespaceSymbol; + } + function bindPotentiallyNewExpandoMemberToNamespace(declaration, namespaceSymbol, isPrototypeProperty) { + if (!namespaceSymbol || !isExpandoSymbol(namespaceSymbol)) { + return; + } + var symbolTable = isPrototypeProperty ? + (namespaceSymbol.members || (namespaceSymbol.members = ts.createSymbolTable())) : + (namespaceSymbol.exports || (namespaceSymbol.exports = ts.createSymbolTable())); + var isMethod = ts.isFunctionLikeDeclaration(ts.getAssignedExpandoInitializer(declaration)); + var includes = isMethod ? 8192 : 4; + var excludes = isMethod ? 67212223 : 0; + declareSymbol(symbolTable, namespaceSymbol, declaration, includes | 67108864, excludes & ~67108864); + } + function bindPropertyAssignment(name, propertyAccess, isPrototypeProperty) { + var namespaceSymbol = lookupSymbolForPropertyAccess(name); + var isToplevel = ts.isBinaryExpression(propertyAccess.parent) + ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 279 + : propertyAccess.parent.parent.kind === 279; + namespaceSymbol = bindPotentiallyMissingNamespaces(namespaceSymbol, propertyAccess.expression, isToplevel, isPrototypeProperty); + bindPotentiallyNewExpandoMemberToNamespace(propertyAccess, namespaceSymbol, isPrototypeProperty); + } + function isExpandoSymbol(symbol) { + if (symbol.flags & (16 | 32 | 1024)) { + return true; + } + var node = symbol.valueDeclaration; + if (node && ts.isCallExpression(node)) { + return !!ts.getAssignedExpandoInitializer(node); + } + var init = !node ? undefined : + ts.isVariableDeclaration(node) ? node.initializer : + ts.isBinaryExpression(node) ? node.right : + ts.isPropertyAccessExpression(node) && ts.isBinaryExpression(node.parent) ? node.parent.right : + undefined; + init = init && ts.getRightMostAssignedExpression(init); + if (init) { + var isPrototypeAssignment = ts.isPrototypeAccess(ts.isVariableDeclaration(node) ? node.name : ts.isBinaryExpression(node) ? node.left : node); + return !!ts.getExpandoInitializer(ts.isBinaryExpression(init) && init.operatorToken.kind === 55 ? init.right : init, isPrototypeAssignment); + } + return false; + } + function getParentOfBinaryExpression(expr) { + while (ts.isBinaryExpression(expr.parent)) { + expr = expr.parent; + } + return expr.parent; + } + function lookupSymbolForPropertyAccess(node, lookupContainer) { + if (lookupContainer === void 0) { lookupContainer = container; } + if (ts.isIdentifier(node)) { + return lookupSymbolForNameWorker(lookupContainer, node.escapedText); + } + else { + var symbol = lookupSymbolForPropertyAccess(node.expression); + return symbol && symbol.exports && symbol.exports.get(node.name.escapedText); + } + } + function forEachIdentifierInEntityName(e, parent, action) { + if (isExportsOrModuleExportsOrAlias(file, e)) { + return file.symbol; + } + else if (ts.isIdentifier(e)) { + return action(e, lookupSymbolForPropertyAccess(e), parent); + } + else { + var s = forEachIdentifierInEntityName(e.expression, parent, action); + if (!s || !s.exports) + return ts.Debug.fail(); + return action(e.name, s.exports.get(e.name.escapedText), s); + } + } + function bindCallExpression(node) { + if (!file.commonJsModuleIndicator && ts.isRequireCall(node, false)) { + setCommonJsModuleIndicator(node); + } + } + function bindClassLikeDeclaration(node) { + if (node.kind === 240) { + bindBlockScopedDeclaration(node, 32, 68008383); + } + else { + var bindingName = node.name ? node.name.escapedText : "__class"; + bindAnonymousDeclaration(node, 32, bindingName); + if (node.name) { + classifiableNames.set(node.name.escapedText, true); + } + } + var symbol = node.symbol; + var prototypeSymbol = createSymbol(4 | 4194304, "prototype"); + var symbolExport = symbol.exports.get(prototypeSymbol.escapedName); + if (symbolExport) { + if (node.name) { + node.name.parent = node; + } + file.bindDiagnostics.push(createDiagnosticForNode(symbolExport.declarations[0], ts.Diagnostics.Duplicate_identifier_0, ts.symbolName(prototypeSymbol))); + } + symbol.exports.set(prototypeSymbol.escapedName, prototypeSymbol); + prototypeSymbol.parent = symbol; + } + function bindEnumDeclaration(node) { + return ts.isEnumConst(node) + ? bindBlockScopedDeclaration(node, 128, 68008831) + : bindBlockScopedDeclaration(node, 256, 68008191); + } + function bindVariableDeclarationOrBindingElement(node) { + if (inStrictMode) { + checkStrictModeEvalOrArguments(node, node.name); + } + if (!ts.isBindingPattern(node.name)) { + var isEnum = ts.isInJSFile(node) && !!ts.getJSDocEnumTag(node); + var enumFlags = (isEnum ? 256 : 0); + var enumExcludes = (isEnum ? 68008191 : 0); + if (ts.isBlockOrCatchScoped(node)) { + bindBlockScopedDeclaration(node, 2 | enumFlags, 67220415 | enumExcludes); + } + else if (ts.isParameterDeclaration(node)) { + declareSymbolAndAddToSymbolTable(node, 1, 67220415); + } + else { + declareSymbolAndAddToSymbolTable(node, 1 | enumFlags, 67220414 | enumExcludes); + } + } + } + function bindParameter(node) { + if (node.kind === 299 && container.kind !== 293) { + return; + } + if (inStrictMode && !(node.flags & 4194304)) { + checkStrictModeEvalOrArguments(node, node.name); + } + if (ts.isBindingPattern(node.name)) { + bindAnonymousDeclaration(node, 1, "__" + node.parent.parameters.indexOf(node)); + } + else { + declareSymbolAndAddToSymbolTable(node, 1, 67220415); + } + if (ts.isParameterPropertyDeclaration(node)) { + var classDeclaration = node.parent.parent; + declareSymbol(classDeclaration.symbol.members, classDeclaration.symbol, node, 4 | (node.questionToken ? 16777216 : 0), 0); + } + } + function bindFunctionDeclaration(node) { + if (!file.isDeclarationFile && !(node.flags & 4194304)) { + if (ts.isAsyncFunction(node)) { + emitFlags |= 1024; + } + } + checkStrictModeFunctionName(node); + if (inStrictMode) { + checkStrictModeFunctionDeclaration(node); + bindBlockScopedDeclaration(node, 16, 67219887); + } + else { + declareSymbolAndAddToSymbolTable(node, 16, 67219887); + } + } + function bindFunctionExpression(node) { + if (!file.isDeclarationFile && !(node.flags & 4194304)) { + if (ts.isAsyncFunction(node)) { + emitFlags |= 1024; + } + } + if (currentFlow) { + node.flowNode = currentFlow; + } + checkStrictModeFunctionName(node); + var bindingName = node.name ? node.name.escapedText : "__function"; + return bindAnonymousDeclaration(node, 16, bindingName); + } + function bindPropertyOrMethodOrAccessor(node, symbolFlags, symbolExcludes) { + if (!file.isDeclarationFile && !(node.flags & 4194304) && ts.isAsyncFunction(node)) { + emitFlags |= 1024; + } + if (currentFlow && ts.isObjectLiteralOrClassExpressionMethod(node)) { + node.flowNode = currentFlow; + } + return ts.hasDynamicName(node) + ? bindAnonymousDeclaration(node, symbolFlags, "__computed") + : declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes); + } + function getInferTypeContainer(node) { + var extendsType = ts.findAncestor(node, function (n) { return n.parent && ts.isConditionalTypeNode(n.parent) && n.parent.extendsType === n; }); + return extendsType && extendsType.parent; + } + function bindTypeParameter(node) { + if (ts.isJSDocTemplateTag(node.parent)) { + var container_1 = ts.find(node.parent.parent.tags, ts.isJSDocTypeAlias) || ts.getHostSignatureFromJSDoc(node.parent); + if (container_1) { + if (!container_1.locals) { + container_1.locals = ts.createSymbolTable(); + } + declareSymbol(container_1.locals, undefined, node, 262144, 67635688); + } + else { + declareSymbolAndAddToSymbolTable(node, 262144, 67635688); + } + } + else if (node.parent.kind === 176) { + var container_2 = getInferTypeContainer(node.parent); + if (container_2) { + if (!container_2.locals) { + container_2.locals = ts.createSymbolTable(); + } + declareSymbol(container_2.locals, undefined, node, 262144, 67635688); + } + else { + bindAnonymousDeclaration(node, 262144, getDeclarationName(node)); + } + } + else { + declareSymbolAndAddToSymbolTable(node, 262144, 67635688); + } + } + function shouldReportErrorOnModuleDeclaration(node) { + var instanceState = getModuleInstanceState(node); + return instanceState === 1 || (instanceState === 2 && !!options.preserveConstEnums); + } + function checkUnreachable(node) { + if (!(currentFlow.flags & 1)) { + return false; + } + if (currentFlow === unreachableFlow) { + var reportError = (ts.isStatementButNotDeclaration(node) && node.kind !== 220) || + node.kind === 240 || + (node.kind === 244 && shouldReportErrorOnModuleDeclaration(node)); + if (reportError) { + currentFlow = reportedUnreachableFlow; + if (!options.allowUnreachableCode) { + var isError_1 = ts.unreachableCodeIsError(options) && + !(node.flags & 4194304) && + (!ts.isVariableStatement(node) || + !!(ts.getCombinedNodeFlags(node.declarationList) & 3) || + node.declarationList.declarations.some(function (d) { return !!d.initializer; })); + eachUnreachableRange(node, function (start, end) { return errorOrSuggestionOnRange(isError_1, start, end, ts.Diagnostics.Unreachable_code_detected); }); + } + } + } + return true; + } + } + function eachUnreachableRange(node, cb) { + if (ts.isStatement(node) && isExecutableStatement(node) && ts.isBlock(node.parent)) { + var statements = node.parent.statements; + var slice_1 = ts.sliceAfter(statements, node); + ts.getRangesWhere(slice_1, isExecutableStatement, function (start, afterEnd) { return cb(slice_1[start], slice_1[afterEnd - 1]); }); + } + else { + cb(node, node); + } + } + function isExecutableStatement(s) { + return !ts.isFunctionDeclaration(s) && !isPurelyTypeDeclaration(s) && !ts.isEnumDeclaration(s) && + !(ts.isVariableStatement(s) && !(ts.getCombinedNodeFlags(s) & (1 | 2)) && s.declarationList.declarations.some(function (d) { return !d.initializer; })); + } + function isPurelyTypeDeclaration(s) { + switch (s.kind) { + case 241: + case 242: + return true; + case 244: + return getModuleInstanceState(s) !== 1; + case 243: + return ts.hasModifier(s, 2048); + default: + return false; + } + } + function isExportsOrModuleExportsOrAlias(sourceFile, node) { + return ts.isExportsIdentifier(node) || + ts.isModuleExportsPropertyAccessExpression(node) || + ts.isIdentifier(node) && isNameOfExportsOrModuleExportsAliasDeclaration(sourceFile, node); + } + ts.isExportsOrModuleExportsOrAlias = isExportsOrModuleExportsOrAlias; + function isNameOfExportsOrModuleExportsAliasDeclaration(sourceFile, node) { + var symbol = lookupSymbolForNameWorker(sourceFile, node.escapedText); + return !!symbol && !!symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && + !!symbol.valueDeclaration.initializer && isExportsOrModuleExportsOrAliasOrAssignment(sourceFile, symbol.valueDeclaration.initializer); + } + function isExportsOrModuleExportsOrAliasOrAssignment(sourceFile, node) { + return isExportsOrModuleExportsOrAlias(sourceFile, node) || + (ts.isAssignmentExpression(node, true) && (isExportsOrModuleExportsOrAliasOrAssignment(sourceFile, node.left) || isExportsOrModuleExportsOrAliasOrAssignment(sourceFile, node.right))); + } + function lookupSymbolForNameWorker(container, name) { + var local = container.locals && container.locals.get(name); + if (local) { + return local.exportSymbol || local; + } + if (ts.isSourceFile(container) && container.jsGlobalAugmentations && container.jsGlobalAugmentations.has(name)) { + return container.jsGlobalAugmentations.get(name); + } + return container.symbol && container.symbol.exports && container.symbol.exports.get(name); + } + function computeTransformFlagsForNode(node, subtreeFlags) { + var kind = node.kind; + switch (kind) { + case 191: + return computeCallExpression(node, subtreeFlags); + case 192: + return computeNewExpression(node, subtreeFlags); + case 244: + return computeModuleDeclaration(node, subtreeFlags); + case 195: + return computeParenthesizedExpression(node, subtreeFlags); + case 204: + return computeBinaryExpression(node, subtreeFlags); + case 221: + return computeExpressionStatement(node, subtreeFlags); + case 151: + return computeParameter(node, subtreeFlags); + case 197: + return computeArrowFunction(node, subtreeFlags); + case 196: + return computeFunctionExpression(node, subtreeFlags); + case 239: + return computeFunctionDeclaration(node, subtreeFlags); + case 237: + return computeVariableDeclaration(node, subtreeFlags); + case 238: + return computeVariableDeclarationList(node, subtreeFlags); + case 219: + return computeVariableStatement(node, subtreeFlags); + case 233: + return computeLabeledStatement(node, subtreeFlags); + case 240: + return computeClassDeclaration(node, subtreeFlags); + case 209: + return computeClassExpression(node, subtreeFlags); + case 273: + return computeHeritageClause(node, subtreeFlags); + case 274: + return computeCatchClause(node, subtreeFlags); + case 211: + return computeExpressionWithTypeArguments(node, subtreeFlags); + case 157: + return computeConstructor(node, subtreeFlags); + case 154: + return computePropertyDeclaration(node, subtreeFlags); + case 156: + return computeMethod(node, subtreeFlags); + case 158: + case 159: + return computeAccessor(node, subtreeFlags); + case 248: + return computeImportEquals(node, subtreeFlags); + case 189: + return computePropertyAccess(node, subtreeFlags); + case 190: + return computeElementAccess(node, subtreeFlags); + default: + return computeOther(node, kind, subtreeFlags); + } + } + ts.computeTransformFlagsForNode = computeTransformFlagsForNode; + function computeCallExpression(node, subtreeFlags) { + var transformFlags = subtreeFlags; + var expression = node.expression; + if (node.typeArguments) { + transformFlags |= 3; + } + if (subtreeFlags & 131072 + || (expression.transformFlags & (33554432 | 67108864))) { + transformFlags |= 192; + if (expression.transformFlags & 67108864) { + transformFlags |= 8192; + } + } + if (expression.kind === 92) { + transformFlags |= 16777216; + if (subtreeFlags & 8192) { + transformFlags |= 16384; + } + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~637666625; + } + function computeNewExpression(node, subtreeFlags) { + var transformFlags = subtreeFlags; + if (node.typeArguments) { + transformFlags |= 3; + } + if (subtreeFlags & 131072) { + transformFlags |= 192; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~637666625; + } + function computeBinaryExpression(node, subtreeFlags) { + var transformFlags = subtreeFlags; + var operatorTokenKind = node.operatorToken.kind; + var leftKind = node.left.kind; + if (operatorTokenKind === 59 && leftKind === 188) { + transformFlags |= 8 | 192 | 3072; + } + else if (operatorTokenKind === 59 && leftKind === 187) { + transformFlags |= 192 | 3072; + } + else if (operatorTokenKind === 41 + || operatorTokenKind === 63) { + transformFlags |= 32; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~637535553; + } + function computeParameter(node, subtreeFlags) { + var transformFlags = subtreeFlags; + var name = node.name; + var initializer = node.initializer; + var dotDotDotToken = node.dotDotDotToken; + if (node.questionToken + || node.type + || (subtreeFlags & 4096 && ts.some(node.decorators)) + || ts.isThisIdentifier(name)) { + transformFlags |= 3; + } + if (ts.hasModifier(node, 92)) { + transformFlags |= 3 | 4096; + } + if (subtreeFlags & 262144) { + transformFlags |= 8; + } + if (subtreeFlags & 2097152 || initializer || dotDotDotToken) { + transformFlags |= 192 | 65536; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~637535553; + } + function computeParenthesizedExpression(node, subtreeFlags) { + var transformFlags = subtreeFlags; + var expression = node.expression; + var expressionKind = expression.kind; + var expressionTransformFlags = expression.transformFlags; + if (expressionKind === 212 + || expressionKind === 194) { + transformFlags |= 3; + } + if (expressionTransformFlags & 1024) { + transformFlags |= 1024; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~536872257; + } + function computeClassDeclaration(node, subtreeFlags) { + var transformFlags; + if (ts.hasModifier(node, 2)) { + transformFlags = 3; + } + else { + transformFlags = subtreeFlags | 192; + if ((subtreeFlags & 4096) + || node.typeParameters) { + transformFlags |= 3; + } + if (subtreeFlags & 32768) { + transformFlags |= 8192; + } + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~638121281; + } + function computeClassExpression(node, subtreeFlags) { + var transformFlags = subtreeFlags | 192; + if (subtreeFlags & 4096 + || node.typeParameters) { + transformFlags |= 3; + } + if (subtreeFlags & 32768) { + transformFlags |= 8192; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~638121281; + } + function computeHeritageClause(node, subtreeFlags) { + var transformFlags = subtreeFlags; + switch (node.token) { + case 86: + transformFlags |= 192; + break; + case 109: + transformFlags |= 3; + break; + default: + ts.Debug.fail("Unexpected token for heritage clause"); + break; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~637535553; + } + function computeCatchClause(node, subtreeFlags) { + var transformFlags = subtreeFlags; + if (!node.variableDeclaration) { + transformFlags |= 8; + } + else if (ts.isBindingPattern(node.variableDeclaration.name)) { + transformFlags |= 192; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~637797697; + } + function computeExpressionWithTypeArguments(node, subtreeFlags) { + var transformFlags = subtreeFlags | 192; + if (node.typeArguments) { + transformFlags |= 3; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~637535553; + } + function computeConstructor(node, subtreeFlags) { + var transformFlags = subtreeFlags; + if (ts.hasModifier(node, 2270) + || !node.body) { + transformFlags |= 3; + } + if (subtreeFlags & 262144) { + transformFlags |= 8; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~653616449; + } + function computeMethod(node, subtreeFlags) { + var transformFlags = subtreeFlags | 192; + if (node.decorators + || ts.hasModifier(node, 2270) + || node.typeParameters + || node.type + || (node.name && ts.isComputedPropertyName(node.name)) + || !node.body) { + transformFlags |= 3; + } + if (subtreeFlags & 262144) { + transformFlags |= 8; + } + if (ts.hasModifier(node, 256)) { + transformFlags |= node.asteriskToken ? 8 : 16; + } + if (node.asteriskToken) { + transformFlags |= 768; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~653616449; + } + function computeAccessor(node, subtreeFlags) { + var transformFlags = subtreeFlags; + if (node.decorators + || ts.hasModifier(node, 2270) + || node.type + || (node.name && ts.isComputedPropertyName(node.name)) + || !node.body) { + transformFlags |= 3; + } + if (subtreeFlags & 262144) { + transformFlags |= 8; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~653616449; + } + function computePropertyDeclaration(node, subtreeFlags) { + var transformFlags = subtreeFlags | 3; + if (node.initializer || ts.isComputedPropertyName(node.name)) { + transformFlags |= 4096; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~637535553; + } + function computeFunctionDeclaration(node, subtreeFlags) { + var transformFlags; + var modifierFlags = ts.getModifierFlags(node); + var body = node.body; + if (!body || (modifierFlags & 2)) { + transformFlags = 3; + } + else { + transformFlags = subtreeFlags | 8388608; + if (modifierFlags & 2270 + || node.typeParameters + || node.type) { + transformFlags |= 3; + } + if (modifierFlags & 256) { + transformFlags |= node.asteriskToken ? 8 : 16; + } + if (subtreeFlags & 262144) { + transformFlags |= 8; + } + if (subtreeFlags & 81920) { + transformFlags |= 192; + } + if (node.asteriskToken) { + transformFlags |= 768; + } + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~653620545; + } + function computeFunctionExpression(node, subtreeFlags) { + var transformFlags = subtreeFlags; + if (ts.hasModifier(node, 2270) + || node.typeParameters + || node.type) { + transformFlags |= 3; + } + if (ts.hasModifier(node, 256)) { + transformFlags |= node.asteriskToken ? 8 : 16; + } + if (subtreeFlags & 262144) { + transformFlags |= 8; + } + if (subtreeFlags & 81920) { + transformFlags |= 192; + } + if (node.asteriskToken) { + transformFlags |= 768; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~653620545; + } + function computeArrowFunction(node, subtreeFlags) { + var transformFlags = subtreeFlags | 192; + if (ts.hasModifier(node, 2270) + || node.typeParameters + || node.type) { + transformFlags |= 3; + } + if (ts.hasModifier(node, 256)) { + transformFlags |= 16; + } + if (subtreeFlags & 262144) { + transformFlags |= 8; + } + if (subtreeFlags & 8192) { + transformFlags |= 16384; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~653604161; + } + function computePropertyAccess(node, subtreeFlags) { + var transformFlags = subtreeFlags; + if (transformFlags & 33554432) { + transformFlags ^= 33554432; + transformFlags |= 67108864 | 16 | 8; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~570426689; + } + function computeElementAccess(node, subtreeFlags) { + var transformFlags = subtreeFlags; + var expression = node.expression; + var expressionFlags = expression.transformFlags; + if (expressionFlags & 33554432) { + transformFlags &= ~33554432; + transformFlags |= 67108864 | 16 | 8; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~570426689; + } + function computeVariableDeclaration(node, subtreeFlags) { + var transformFlags = subtreeFlags; + transformFlags |= 192 | 2097152; + if (subtreeFlags & 262144) { + transformFlags |= 8; + } + if (node.type) { + transformFlags |= 3; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~637535553; + } + function computeVariableStatement(node, subtreeFlags) { + var transformFlags; + var declarationListTransformFlags = node.declarationList.transformFlags; + if (ts.hasModifier(node, 2)) { + transformFlags = 3; + } + else { + transformFlags = subtreeFlags; + if (declarationListTransformFlags & 2097152) { + transformFlags |= 192; + } + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~637535553; + } + function computeLabeledStatement(node, subtreeFlags) { + var transformFlags = subtreeFlags; + if (subtreeFlags & 1048576 + && ts.isIterationStatement(node, true)) { + transformFlags |= 192; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~637535553; + } + function computeImportEquals(node, subtreeFlags) { + var transformFlags = subtreeFlags; + if (!ts.isExternalModuleImportEqualsDeclaration(node)) { + transformFlags |= 3; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~637535553; + } + function computeExpressionStatement(node, subtreeFlags) { + var transformFlags = subtreeFlags; + if (node.expression.transformFlags & 1024) { + transformFlags |= 192; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~637535553; + } + function computeModuleDeclaration(node, subtreeFlags) { + var transformFlags = 3; + var modifierFlags = ts.getModifierFlags(node); + if ((modifierFlags & 2) === 0) { + transformFlags |= subtreeFlags; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~647001409; + } + function computeVariableDeclarationList(node, subtreeFlags) { + var transformFlags = subtreeFlags | 8388608; + if (subtreeFlags & 2097152) { + transformFlags |= 192; + } + if (node.flags & 3) { + transformFlags |= 192 | 1048576; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~639894849; + } + function computeOther(node, kind, subtreeFlags) { + var transformFlags = subtreeFlags; + var excludeFlags = 637535553; + switch (kind) { + case 121: + case 201: + transformFlags |= 8 | 16; + break; + case 194: + case 212: + case 308: + transformFlags |= 3; + excludeFlags = 536872257; + break; + case 115: + case 113: + case 114: + case 118: + case 125: + case 77: + case 243: + case 278: + case 213: + case 133: + transformFlags |= 3; + break; + case 260: + case 261: + case 262: + case 11: + case 263: + case 264: + case 265: + case 266: + case 267: + case 268: + case 269: + case 270: + transformFlags |= 4; + break; + case 14: + case 15: + case 16: + case 17: + case 206: + case 193: + case 276: + case 116: + case 214: + transformFlags |= 192; + break; + case 10: + if (node.hasExtendedUnicodeEscape) { + transformFlags |= 192; + } + break; + case 8: + if (node.numericLiteralFlags & 384) { + transformFlags |= 192; + } + break; + case 9: + transformFlags |= 8; + break; + case 227: + if (node.awaitModifier) { + transformFlags |= 8; + } + transformFlags |= 192; + break; + case 207: + transformFlags |= 8 | 192 | 4194304; + break; + case 120: + case 135: + case 146: + case 132: + case 136: + case 138: + case 123: + case 139: + case 106: + case 150: + case 153: + case 155: + case 160: + case 161: + case 162: + case 163: + case 164: + case 165: + case 166: + case 167: + case 168: + case 169: + case 170: + case 171: + case 172: + case 173: + case 174: + case 175: + case 176: + case 177: + case 241: + case 242: + case 178: + case 179: + case 180: + case 181: + case 182: + case 247: + transformFlags = 3; + excludeFlags = -3; + break; + case 149: + transformFlags |= 524288; + if (subtreeFlags & 8192) { + transformFlags |= 32768; + } + break; + case 208: + transformFlags |= 192 | 131072; + break; + case 277: + transformFlags |= 8 | 262144; + break; + case 98: + transformFlags |= 192 | 33554432; + excludeFlags = 536872257; + break; + case 100: + transformFlags |= 8192; + break; + case 184: + transformFlags |= 192 | 2097152; + if (subtreeFlags & 131072) { + transformFlags |= 8 | 262144; + } + excludeFlags = 637666625; + break; + case 185: + transformFlags |= 192 | 2097152; + excludeFlags = 637666625; + break; + case 186: + transformFlags |= 192; + if (node.dotDotDotToken) { + transformFlags |= 131072; + } + break; + case 152: + transformFlags |= 3 | 4096; + break; + case 188: + excludeFlags = 638358849; + if (subtreeFlags & 524288) { + transformFlags |= 192; + } + if (subtreeFlags & 32768) { + transformFlags |= 8192; + } + if (subtreeFlags & 262144) { + transformFlags |= 8; + } + break; + case 187: + case 192: + excludeFlags = 637666625; + if (subtreeFlags & 131072) { + transformFlags |= 192; + } + break; + case 223: + case 224: + case 225: + case 226: + if (subtreeFlags & 1048576) { + transformFlags |= 192; + } + break; + case 279: + if (subtreeFlags & 16384) { + transformFlags |= 192; + } + break; + case 230: + transformFlags |= 8388608 | 8; + break; + case 228: + case 229: + transformFlags |= 8388608; + break; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~excludeFlags; + } + function getTransformFlagsSubtreeExclusions(kind) { + if (kind >= 163 && kind <= 183) { + return -3; + } + switch (kind) { + case 191: + case 192: + case 187: + return 637666625; + case 244: + return 647001409; + case 151: + return 637535553; + case 197: + return 653604161; + case 196: + case 239: + return 653620545; + case 238: + return 639894849; + case 240: + case 209: + return 638121281; + case 157: + return 653616449; + case 156: + case 158: + case 159: + return 653616449; + case 120: + case 135: + case 146: + case 132: + case 138: + case 136: + case 123: + case 139: + case 106: + case 150: + case 153: + case 155: + case 160: + case 161: + case 162: + case 241: + case 242: + return -3; + case 188: + return 638358849; + case 274: + return 637797697; + case 184: + case 185: + return 637666625; + case 194: + case 212: + case 308: + case 195: + case 98: + return 536872257; + case 189: + case 190: + return 570426689; + default: + return 637535553; + } + } + ts.getTransformFlagsSubtreeExclusions = getTransformFlagsSubtreeExclusions; + function setParentPointers(parent, child) { + child.parent = parent; + ts.forEachChild(child, function (grandchild) { return setParentPointers(child, grandchild); }); + } +})(ts || (ts = {})); +var ts; +(function (ts) { + function createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintOfTypeParameter, getFirstIdentifier) { + return getSymbolWalker; + function getSymbolWalker(accept) { + if (accept === void 0) { accept = function () { return true; }; } + var visitedTypes = []; + var visitedSymbols = []; + return { + walkType: function (type) { + try { + visitType(type); + return { visitedTypes: ts.getOwnValues(visitedTypes), visitedSymbols: ts.getOwnValues(visitedSymbols) }; + } + finally { + ts.clear(visitedTypes); + ts.clear(visitedSymbols); + } + }, + walkSymbol: function (symbol) { + try { + visitSymbol(symbol); + return { visitedTypes: ts.getOwnValues(visitedTypes), visitedSymbols: ts.getOwnValues(visitedSymbols) }; + } + finally { + ts.clear(visitedTypes); + ts.clear(visitedSymbols); + } + }, + }; + function visitType(type) { + if (!type) { + return; + } + if (visitedTypes[type.id]) { + return; + } + visitedTypes[type.id] = type; + var shouldBail = visitSymbol(type.symbol); + if (shouldBail) + return; + if (type.flags & 524288) { + var objectType = type; + var objectFlags = objectType.objectFlags; + if (objectFlags & 4) { + visitTypeReference(type); + } + if (objectFlags & 32) { + visitMappedType(type); + } + if (objectFlags & (1 | 2)) { + visitInterfaceType(type); + } + if (objectFlags & (8 | 16)) { + visitObjectType(objectType); + } + } + if (type.flags & 262144) { + visitTypeParameter(type); + } + if (type.flags & 3145728) { + visitUnionOrIntersectionType(type); + } + if (type.flags & 4194304) { + visitIndexType(type); + } + if (type.flags & 8388608) { + visitIndexedAccessType(type); + } + } + function visitTypeReference(type) { + visitType(type.target); + ts.forEach(type.typeArguments, visitType); + } + function visitTypeParameter(type) { + visitType(getConstraintOfTypeParameter(type)); + } + function visitUnionOrIntersectionType(type) { + ts.forEach(type.types, visitType); + } + function visitIndexType(type) { + visitType(type.type); + } + function visitIndexedAccessType(type) { + visitType(type.objectType); + visitType(type.indexType); + visitType(type.constraint); + } + function visitMappedType(type) { + visitType(type.typeParameter); + visitType(type.constraintType); + visitType(type.templateType); + visitType(type.modifiersType); + } + function visitSignature(signature) { + var typePredicate = getTypePredicateOfSignature(signature); + if (typePredicate) { + visitType(typePredicate.type); + } + ts.forEach(signature.typeParameters, visitType); + for (var _i = 0, _a = signature.parameters; _i < _a.length; _i++) { + var parameter = _a[_i]; + visitSymbol(parameter); + } + visitType(getRestTypeOfSignature(signature)); + visitType(getReturnTypeOfSignature(signature)); + } + function visitInterfaceType(interfaceT) { + visitObjectType(interfaceT); + ts.forEach(interfaceT.typeParameters, visitType); + ts.forEach(getBaseTypes(interfaceT), visitType); + visitType(interfaceT.thisType); + } + function visitObjectType(type) { + var stringIndexType = getIndexTypeOfStructuredType(type, 0); + visitType(stringIndexType); + var numberIndexType = getIndexTypeOfStructuredType(type, 1); + visitType(numberIndexType); + var resolved = resolveStructuredTypeMembers(type); + for (var _i = 0, _a = resolved.callSignatures; _i < _a.length; _i++) { + var signature = _a[_i]; + visitSignature(signature); + } + for (var _b = 0, _c = resolved.constructSignatures; _b < _c.length; _b++) { + var signature = _c[_b]; + visitSignature(signature); + } + for (var _d = 0, _e = resolved.properties; _d < _e.length; _d++) { + var p = _e[_d]; + visitSymbol(p); + } + } + function visitSymbol(symbol) { + if (!symbol) { + return false; + } + var symbolId = ts.getSymbolId(symbol); + if (visitedSymbols[symbolId]) { + return false; + } + visitedSymbols[symbolId] = symbol; + if (!accept(symbol)) { + return true; + } + var t = getTypeOfSymbol(symbol); + visitType(t); + if (symbol.exports) { + symbol.exports.forEach(visitSymbol); + } + ts.forEach(symbol.declarations, function (d) { + if (d.type && d.type.kind === 167) { + var query = d.type; + var entity = getResolvedSymbol(getFirstIdentifier(query.exprName)); + visitSymbol(entity); + } + }); + return false; + } + } + } + ts.createGetSymbolWalker = createGetSymbolWalker; +})(ts || (ts = {})); +var ts; +(function (ts) { + var ambientModuleSymbolRegex = /^".+"$/; + var nextSymbolId = 1; + var nextNodeId = 1; + var nextMergeId = 1; + var nextFlowId = 1; + function getNodeId(node) { + if (!node.id) { + node.id = nextNodeId; + nextNodeId++; + } + return node.id; + } + ts.getNodeId = getNodeId; + function getSymbolId(symbol) { + if (!symbol.id) { + symbol.id = nextSymbolId; + nextSymbolId++; + } + return symbol.id; + } + ts.getSymbolId = getSymbolId; + function isInstantiatedModule(node, preserveConstEnums) { + var moduleState = ts.getModuleInstanceState(node); + return moduleState === 1 || + (preserveConstEnums && moduleState === 2); + } + ts.isInstantiatedModule = isInstantiatedModule; + function createTypeChecker(host, produceDiagnostics) { + var getPackagesSet = ts.memoize(function () { + var set = ts.createMap(); + host.getSourceFiles().forEach(function (sf) { + if (!sf.resolvedModules) + return; + ts.forEachEntry(sf.resolvedModules, function (r) { + if (r && r.packageId) + set.set(r.packageId.name, true); + }); + }); + return set; + }); + var cancellationToken; + var requestedExternalEmitHelpers; + var externalHelpersModule; + var Symbol = ts.objectAllocator.getSymbolConstructor(); + var Type = ts.objectAllocator.getTypeConstructor(); + var Signature = ts.objectAllocator.getSignatureConstructor(); + var typeCount = 0; + var symbolCount = 0; + var enumCount = 0; + var instantiationDepth = 0; + var constraintDepth = 0; + var emptySymbols = ts.createSymbolTable(); + var identityMapper = ts.identity; + var compilerOptions = host.getCompilerOptions(); + var languageVersion = ts.getEmitScriptTarget(compilerOptions); + var moduleKind = ts.getEmitModuleKind(compilerOptions); + var allowSyntheticDefaultImports = ts.getAllowSyntheticDefaultImports(compilerOptions); + var strictNullChecks = ts.getStrictOptionValue(compilerOptions, "strictNullChecks"); + var strictFunctionTypes = ts.getStrictOptionValue(compilerOptions, "strictFunctionTypes"); + var strictBindCallApply = ts.getStrictOptionValue(compilerOptions, "strictBindCallApply"); + var strictPropertyInitialization = ts.getStrictOptionValue(compilerOptions, "strictPropertyInitialization"); + var noImplicitAny = ts.getStrictOptionValue(compilerOptions, "noImplicitAny"); + var noImplicitThis = ts.getStrictOptionValue(compilerOptions, "noImplicitThis"); + var keyofStringsOnly = !!compilerOptions.keyofStringsOnly; + var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 32768; + var emitResolver = createResolver(); + var nodeBuilder = createNodeBuilder(); + var undefinedSymbol = createSymbol(4, "undefined"); + undefinedSymbol.declarations = []; + var argumentsSymbol = createSymbol(4, "arguments"); + var requireSymbol = createSymbol(4, "require"); + var apparentArgumentCount; + var checker = { + getNodeCount: function () { return ts.sum(host.getSourceFiles(), "nodeCount"); }, + getIdentifierCount: function () { return ts.sum(host.getSourceFiles(), "identifierCount"); }, + getSymbolCount: function () { return ts.sum(host.getSourceFiles(), "symbolCount") + symbolCount; }, + getTypeCount: function () { return typeCount; }, + isUndefinedSymbol: function (symbol) { return symbol === undefinedSymbol; }, + isArgumentsSymbol: function (symbol) { return symbol === argumentsSymbol; }, + isUnknownSymbol: function (symbol) { return symbol === unknownSymbol; }, + getMergedSymbol: getMergedSymbol, + getDiagnostics: getDiagnostics, + getGlobalDiagnostics: getGlobalDiagnostics, + getTypeOfSymbolAtLocation: function (symbol, location) { + location = ts.getParseTreeNode(location); + return location ? getTypeOfSymbolAtLocation(symbol, location) : errorType; + }, + getSymbolsOfParameterPropertyDeclaration: function (parameterIn, parameterName) { + var parameter = ts.getParseTreeNode(parameterIn, ts.isParameter); + if (parameter === undefined) + return ts.Debug.fail("Cannot get symbols of a synthetic parameter that cannot be resolved to a parse-tree node."); + return getSymbolsOfParameterPropertyDeclaration(parameter, ts.escapeLeadingUnderscores(parameterName)); + }, + getDeclaredTypeOfSymbol: getDeclaredTypeOfSymbol, + getPropertiesOfType: getPropertiesOfType, + getPropertyOfType: function (type, name) { return getPropertyOfType(type, ts.escapeLeadingUnderscores(name)); }, + getTypeOfPropertyOfType: function (type, name) { return getTypeOfPropertyOfType(type, ts.escapeLeadingUnderscores(name)); }, + getIndexInfoOfType: getIndexInfoOfType, + getSignaturesOfType: getSignaturesOfType, + getIndexTypeOfType: getIndexTypeOfType, + getBaseTypes: getBaseTypes, + getBaseTypeOfLiteralType: getBaseTypeOfLiteralType, + getWidenedType: getWidenedType, + getTypeFromTypeNode: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isTypeNode); + return node ? getTypeFromTypeNode(node) : errorType; + }, + getParameterType: getTypeAtPosition, + getPromisedTypeOfPromise: getPromisedTypeOfPromise, + getReturnTypeOfSignature: getReturnTypeOfSignature, + getNullableType: getNullableType, + getNonNullableType: getNonNullableType, + typeToTypeNode: nodeBuilder.typeToTypeNode, + indexInfoToIndexSignatureDeclaration: nodeBuilder.indexInfoToIndexSignatureDeclaration, + signatureToSignatureDeclaration: nodeBuilder.signatureToSignatureDeclaration, + symbolToEntityName: nodeBuilder.symbolToEntityName, + symbolToExpression: nodeBuilder.symbolToExpression, + symbolToTypeParameterDeclarations: nodeBuilder.symbolToTypeParameterDeclarations, + symbolToParameterDeclaration: nodeBuilder.symbolToParameterDeclaration, + typeParameterToDeclaration: nodeBuilder.typeParameterToDeclaration, + getSymbolsInScope: function (location, meaning) { + location = ts.getParseTreeNode(location); + return location ? getSymbolsInScope(location, meaning) : []; + }, + getSymbolAtLocation: function (node) { + node = ts.getParseTreeNode(node); + return node ? getSymbolAtLocation(node) : undefined; + }, + getShorthandAssignmentValueSymbol: function (node) { + node = ts.getParseTreeNode(node); + return node ? getShorthandAssignmentValueSymbol(node) : undefined; + }, + getExportSpecifierLocalTargetSymbol: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isExportSpecifier); + return node ? getExportSpecifierLocalTargetSymbol(node) : undefined; + }, + getExportSymbolOfSymbol: function (symbol) { + return getMergedSymbol(symbol.exportSymbol || symbol); + }, + getTypeAtLocation: function (node) { + node = ts.getParseTreeNode(node); + return node ? getTypeOfNode(node) : errorType; + }, + getPropertySymbolOfDestructuringAssignment: function (locationIn) { + var location = ts.getParseTreeNode(locationIn, ts.isIdentifier); + return location ? getPropertySymbolOfDestructuringAssignment(location) : undefined; + }, + signatureToString: function (signature, enclosingDeclaration, flags, kind) { + return signatureToString(signature, ts.getParseTreeNode(enclosingDeclaration), flags, kind); + }, + typeToString: function (type, enclosingDeclaration, flags) { + return typeToString(type, ts.getParseTreeNode(enclosingDeclaration), flags); + }, + symbolToString: function (symbol, enclosingDeclaration, meaning, flags) { + return symbolToString(symbol, ts.getParseTreeNode(enclosingDeclaration), meaning, flags); + }, + typePredicateToString: function (predicate, enclosingDeclaration, flags) { + return typePredicateToString(predicate, ts.getParseTreeNode(enclosingDeclaration), flags); + }, + writeSignature: function (signature, enclosingDeclaration, flags, kind, writer) { + return signatureToString(signature, ts.getParseTreeNode(enclosingDeclaration), flags, kind, writer); + }, + writeType: function (type, enclosingDeclaration, flags, writer) { + return typeToString(type, ts.getParseTreeNode(enclosingDeclaration), flags, writer); + }, + writeSymbol: function (symbol, enclosingDeclaration, meaning, flags, writer) { + return symbolToString(symbol, ts.getParseTreeNode(enclosingDeclaration), meaning, flags, writer); + }, + writeTypePredicate: function (predicate, enclosingDeclaration, flags, writer) { + return typePredicateToString(predicate, ts.getParseTreeNode(enclosingDeclaration), flags, writer); + }, + getAugmentedPropertiesOfType: getAugmentedPropertiesOfType, + getRootSymbols: getRootSymbols, + getContextualType: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isExpression); + return node ? getContextualType(node) : undefined; + }, + getContextualTypeForObjectLiteralElement: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isObjectLiteralElementLike); + return node ? getContextualTypeForObjectLiteralElement(node) : undefined; + }, + getContextualTypeForArgumentAtIndex: function (nodeIn, argIndex) { + var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression); + return node && getContextualTypeForArgumentAtIndex(node, argIndex); + }, + getContextualTypeForJsxAttribute: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isJsxAttributeLike); + return node && getContextualTypeForJsxAttribute(node); + }, + isContextSensitive: isContextSensitive, + getFullyQualifiedName: getFullyQualifiedName, + getResolvedSignature: function (node, candidatesOutArray, agumentCount) { + return getResolvedSignatureWorker(node, candidatesOutArray, agumentCount, false); + }, + getResolvedSignatureForSignatureHelp: function (node, candidatesOutArray, agumentCount) { + return getResolvedSignatureWorker(node, candidatesOutArray, agumentCount, true); + }, + getConstantValue: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, canHaveConstantValue); + return node ? getConstantValue(node) : undefined; + }, + isValidPropertyAccess: function (nodeIn, propertyName) { + var node = ts.getParseTreeNode(nodeIn, ts.isPropertyAccessOrQualifiedNameOrImportTypeNode); + return !!node && isValidPropertyAccess(node, ts.escapeLeadingUnderscores(propertyName)); + }, + isValidPropertyAccessForCompletions: function (nodeIn, type, property) { + var node = ts.getParseTreeNode(nodeIn, ts.isPropertyAccessExpression); + return !!node && isValidPropertyAccessForCompletions(node, type, property); + }, + getSignatureFromDeclaration: function (declarationIn) { + var declaration = ts.getParseTreeNode(declarationIn, ts.isFunctionLike); + return declaration ? getSignatureFromDeclaration(declaration) : undefined; + }, + isImplementationOfOverload: function (node) { + var parsed = ts.getParseTreeNode(node, ts.isFunctionLike); + return parsed ? isImplementationOfOverload(parsed) : undefined; + }, + getImmediateAliasedSymbol: getImmediateAliasedSymbol, + getAliasedSymbol: resolveAlias, + getEmitResolver: getEmitResolver, + getExportsOfModule: getExportsOfModuleAsArray, + getExportsAndPropertiesOfModule: getExportsAndPropertiesOfModule, + getSymbolWalker: ts.createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintOfTypeParameter, getFirstIdentifier), + getAmbientModules: getAmbientModules, + getJsxIntrinsicTagNamesAt: getJsxIntrinsicTagNamesAt, + isOptionalParameter: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isParameter); + return node ? isOptionalParameter(node) : false; + }, + tryGetMemberInModuleExports: function (name, symbol) { return tryGetMemberInModuleExports(ts.escapeLeadingUnderscores(name), symbol); }, + tryGetMemberInModuleExportsAndProperties: function (name, symbol) { return tryGetMemberInModuleExportsAndProperties(ts.escapeLeadingUnderscores(name), symbol); }, + tryFindAmbientModuleWithoutAugmentations: function (moduleName) { + return tryFindAmbientModule(moduleName, false); + }, + getApparentType: getApparentType, + getUnionType: getUnionType, + createAnonymousType: createAnonymousType, + createSignature: createSignature, + createSymbol: createSymbol, + createIndexInfo: createIndexInfo, + getAnyType: function () { return anyType; }, + getStringType: function () { return stringType; }, + getNumberType: function () { return numberType; }, + createPromiseType: createPromiseType, + createArrayType: createArrayType, + getElementTypeOfArrayType: getElementTypeOfArrayType, + getBooleanType: function () { return booleanType; }, + getFalseType: function (fresh) { return fresh ? falseType : regularFalseType; }, + getTrueType: function (fresh) { return fresh ? trueType : regularTrueType; }, + getVoidType: function () { return voidType; }, + getUndefinedType: function () { return undefinedType; }, + getNullType: function () { return nullType; }, + getESSymbolType: function () { return esSymbolType; }, + getNeverType: function () { return neverType; }, + isSymbolAccessible: isSymbolAccessible, + getObjectFlags: ts.getObjectFlags, + isArrayLikeType: isArrayLikeType, + isTypeInvalidDueToUnionDiscriminant: isTypeInvalidDueToUnionDiscriminant, + getAllPossiblePropertiesOfTypes: getAllPossiblePropertiesOfTypes, + getSuggestionForNonexistentProperty: function (node, type) { return getSuggestionForNonexistentProperty(node, type); }, + getSuggestionForNonexistentSymbol: function (location, name, meaning) { return getSuggestionForNonexistentSymbol(location, ts.escapeLeadingUnderscores(name), meaning); }, + getSuggestionForNonexistentExport: function (node, target) { return getSuggestionForNonexistentExport(node, target); }, + getBaseConstraintOfType: getBaseConstraintOfType, + getDefaultFromTypeParameter: function (type) { return type && type.flags & 262144 ? getDefaultFromTypeParameter(type) : undefined; }, + resolveName: function (name, location, meaning, excludeGlobals) { + return resolveName(location, ts.escapeLeadingUnderscores(name), meaning, undefined, undefined, false, excludeGlobals); + }, + getJsxNamespace: function (n) { return ts.unescapeLeadingUnderscores(getJsxNamespace(n)); }, + getAccessibleSymbolChain: getAccessibleSymbolChain, + getTypePredicateOfSignature: getTypePredicateOfSignature, + resolveExternalModuleSymbol: resolveExternalModuleSymbol, + tryGetThisTypeAt: function (node) { + node = ts.getParseTreeNode(node); + return node && tryGetThisTypeAt(node); + }, + getTypeArgumentConstraint: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isTypeNode); + return node && getTypeArgumentConstraint(node); + }, + getSuggestionDiagnostics: function (file, ct) { + if (ts.skipTypeChecking(file, compilerOptions)) { + return ts.emptyArray; + } + var diagnostics; + try { + cancellationToken = ct; + checkSourceFile(file); + ts.Debug.assert(!!(getNodeLinks(file).flags & 1)); + diagnostics = ts.addRange(diagnostics, suggestionDiagnostics.get(file.fileName)); + if (!file.isDeclarationFile && (!unusedIsError(0) || !unusedIsError(1))) { + addUnusedDiagnostics(); + } + return diagnostics || ts.emptyArray; + } + finally { + cancellationToken = undefined; + } + function addUnusedDiagnostics() { + checkUnusedIdentifiers(getPotentiallyUnusedIdentifiers(file), function (containingNode, kind, diag) { + if (!ts.containsParseError(containingNode) && !unusedIsError(kind)) { + (diagnostics || (diagnostics = [])).push(__assign({}, diag, { category: ts.DiagnosticCategory.Suggestion })); + } + }); + } + }, + runWithCancellationToken: function (token, callback) { + try { + cancellationToken = token; + return callback(checker); + } + finally { + cancellationToken = undefined; + } + }, + getLocalTypeParametersOfClassOrInterfaceOrTypeAlias: getLocalTypeParametersOfClassOrInterfaceOrTypeAlias, + }; + function getResolvedSignatureWorker(nodeIn, candidatesOutArray, argumentCount, isForSignatureHelp) { + var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression); + apparentArgumentCount = argumentCount; + var res = node ? getResolvedSignature(node, candidatesOutArray, isForSignatureHelp) : undefined; + apparentArgumentCount = undefined; + return res; + } + var tupleTypes = ts.createMap(); + var unionTypes = ts.createMap(); + var intersectionTypes = ts.createMap(); + var literalTypes = ts.createMap(); + var indexedAccessTypes = ts.createMap(); + var evolvingArrayTypes = []; + var undefinedProperties = ts.createMap(); + var unknownSymbol = createSymbol(4, "unknown"); + var resolvingSymbol = createSymbol(0, "__resolving__"); + var anyType = createIntrinsicType(1, "any"); + var autoType = createIntrinsicType(1, "any"); + var wildcardType = createIntrinsicType(1, "any"); + var errorType = createIntrinsicType(1, "error"); + var unknownType = createIntrinsicType(2, "unknown"); + var undefinedType = createIntrinsicType(32768, "undefined"); + var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(32768 | 134217728, "undefined"); + var nullType = createIntrinsicType(65536, "null"); + var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(65536 | 134217728, "null"); + var stringType = createIntrinsicType(4, "string"); + var numberType = createIntrinsicType(8, "number"); + var bigintType = createIntrinsicType(64, "bigint"); + var falseType = createIntrinsicType(512, "false"); + var regularFalseType = createIntrinsicType(512, "false"); + var trueType = createIntrinsicType(512, "true"); + var regularTrueType = createIntrinsicType(512, "true"); + trueType.regularType = regularTrueType; + trueType.freshType = trueType; + regularTrueType.regularType = regularTrueType; + regularTrueType.freshType = trueType; + falseType.regularType = regularFalseType; + falseType.freshType = falseType; + regularFalseType.regularType = regularFalseType; + regularFalseType.freshType = falseType; + var booleanType = createBooleanType([regularFalseType, regularTrueType]); + createBooleanType([regularFalseType, trueType]); + createBooleanType([falseType, regularTrueType]); + createBooleanType([falseType, trueType]); + var esSymbolType = createIntrinsicType(4096, "symbol"); + var voidType = createIntrinsicType(16384, "void"); + var neverType = createIntrinsicType(131072, "never"); + var silentNeverType = createIntrinsicType(131072, "never"); + var implicitNeverType = createIntrinsicType(131072, "never"); + var nonPrimitiveType = createIntrinsicType(67108864, "object"); + var stringNumberSymbolType = getUnionType([stringType, numberType, esSymbolType]); + var keyofConstraintType = keyofStringsOnly ? stringType : stringNumberSymbolType; + var numberOrBigIntType = getUnionType([numberType, bigintType]); + var emptyObjectType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + var emptyJsxObjectType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + emptyJsxObjectType.objectFlags |= 4096; + var emptyTypeLiteralSymbol = createSymbol(2048, "__type"); + emptyTypeLiteralSymbol.members = ts.createSymbolTable(); + var emptyTypeLiteralType = createAnonymousType(emptyTypeLiteralSymbol, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + var emptyGenericType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + emptyGenericType.instantiations = ts.createMap(); + var anyFunctionType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + anyFunctionType.flags |= 536870912; + var noConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + var circularConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + var resolvingDefaultType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + var markerSuperType = createType(262144); + var markerSubType = createType(262144); + markerSubType.constraint = markerSuperType; + var markerOtherType = createType(262144); + var noTypePredicate = createIdentifierTypePredicate("<>", 0, anyType); + var anySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, undefined, 0, false, false); + var unknownSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, errorType, undefined, 0, false, false); + var resolvingSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, undefined, 0, false, false); + var silentNeverSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, silentNeverType, undefined, 0, false, false); + var enumNumberIndexInfo = createIndexInfo(stringType, true); + var globals = ts.createSymbolTable(); + var amalgamatedDuplicates; + var reverseMappedCache = ts.createMap(); + var ambientModulesCache; + var patternAmbientModules; + var globalObjectType; + var globalFunctionType; + var globalCallableFunctionType; + var globalNewableFunctionType; + var globalArrayType; + var globalReadonlyArrayType; + var globalStringType; + var globalNumberType; + var globalBooleanType; + var globalRegExpType; + var globalThisType; + var anyArrayType; + var autoArrayType; + var anyReadonlyArrayType; + var deferredGlobalNonNullableTypeAlias; + var deferredGlobalESSymbolConstructorSymbol; + var deferredGlobalESSymbolType; + var deferredGlobalTypedPropertyDescriptorType; + var deferredGlobalPromiseType; + var deferredGlobalPromiseLikeType; + var deferredGlobalPromiseConstructorSymbol; + var deferredGlobalPromiseConstructorLikeType; + var deferredGlobalIterableType; + var deferredGlobalIteratorType; + var deferredGlobalIterableIteratorType; + var deferredGlobalAsyncIterableType; + var deferredGlobalAsyncIteratorType; + var deferredGlobalAsyncIterableIteratorType; + var deferredGlobalTemplateStringsArrayType; + var deferredGlobalImportMetaType; + var deferredGlobalExtractSymbol; + var deferredGlobalExcludeSymbol; + var deferredGlobalPickSymbol; + var deferredGlobalBigIntType; + var allPotentiallyUnusedIdentifiers = ts.createMap(); + var flowLoopStart = 0; + var flowLoopCount = 0; + var sharedFlowCount = 0; + var flowAnalysisDisabled = false; + var emptyStringType = getLiteralType(""); + var zeroType = getLiteralType(0); + var zeroBigIntType = getLiteralType({ negative: false, base10Value: "0" }); + var resolutionTargets = []; + var resolutionResults = []; + var resolutionPropertyNames = []; + var suggestionCount = 0; + var maximumSuggestionCount = 10; + var mergedSymbols = []; + var symbolLinks = []; + var nodeLinks = []; + var flowLoopCaches = []; + var flowLoopNodes = []; + var flowLoopKeys = []; + var flowLoopTypes = []; + var sharedFlowNodes = []; + var sharedFlowTypes = []; + var potentialThisCollisions = []; + var potentialNewTargetCollisions = []; + var awaitedTypeStack = []; + var diagnostics = ts.createDiagnosticCollection(); + var suggestionDiagnostics = ts.createMultiMap(); + var typeofEQFacts = ts.createMapFromTemplate({ + string: 1, + number: 2, + bigint: 4, + boolean: 8, + symbol: 16, + undefined: 65536, + object: 32, + function: 64 + }); + var typeofNEFacts = ts.createMapFromTemplate({ + string: 256, + number: 512, + bigint: 1024, + boolean: 2048, + symbol: 4096, + undefined: 524288, + object: 8192, + function: 16384 + }); + var typeofTypesByName = ts.createMapFromTemplate({ + string: stringType, + number: numberType, + bigint: bigintType, + boolean: booleanType, + symbol: esSymbolType, + undefined: undefinedType + }); + var typeofType = createTypeofType(); + var _jsxNamespace; + var _jsxFactoryEntity; + var subtypeRelation = ts.createMap(); + var assignableRelation = ts.createMap(); + var definitelyAssignableRelation = ts.createMap(); + var comparableRelation = ts.createMap(); + var identityRelation = ts.createMap(); + var enumRelation = ts.createMap(); + var builtinGlobals = ts.createSymbolTable(); + builtinGlobals.set(undefinedSymbol.escapedName, undefinedSymbol); + var isNotOverloadAndNotAccessor = ts.and(isNotOverload, isNotAccessor); + initializeTypeChecker(); + return checker; + function getJsxNamespace(location) { + if (location) { + var file = ts.getSourceFileOfNode(location); + if (file) { + if (file.localJsxNamespace) { + return file.localJsxNamespace; + } + var jsxPragma = file.pragmas.get("jsx"); + if (jsxPragma) { + var chosenpragma = ts.isArray(jsxPragma) ? jsxPragma[0] : jsxPragma; + file.localJsxFactory = ts.parseIsolatedEntityName(chosenpragma.arguments.factory, languageVersion); + if (file.localJsxFactory) { + return file.localJsxNamespace = getFirstIdentifier(file.localJsxFactory).escapedText; + } + } + } + } + if (!_jsxNamespace) { + _jsxNamespace = "React"; + if (compilerOptions.jsxFactory) { + _jsxFactoryEntity = ts.parseIsolatedEntityName(compilerOptions.jsxFactory, languageVersion); + if (_jsxFactoryEntity) { + _jsxNamespace = getFirstIdentifier(_jsxFactoryEntity).escapedText; + } + } + else if (compilerOptions.reactNamespace) { + _jsxNamespace = ts.escapeLeadingUnderscores(compilerOptions.reactNamespace); + } + } + return _jsxNamespace; + } + function getEmitResolver(sourceFile, cancellationToken) { + getDiagnostics(sourceFile, cancellationToken); + return emitResolver; + } + function lookupOrIssueError(location, message, arg0, arg1, arg2, arg3) { + var diagnostic = location + ? ts.createDiagnosticForNode(location, message, arg0, arg1, arg2, arg3) + : ts.createCompilerDiagnostic(message, arg0, arg1, arg2, arg3); + var existing = diagnostics.lookup(diagnostic); + if (existing) { + return existing; + } + else { + diagnostics.add(diagnostic); + return diagnostic; + } + } + function addRelatedInfo(diagnostic) { + var relatedInformation = []; + for (var _i = 1; _i < arguments.length; _i++) { + relatedInformation[_i - 1] = arguments[_i]; + } + var _a; + if (!diagnostic.relatedInformation) { + diagnostic.relatedInformation = []; + } + (_a = diagnostic.relatedInformation).push.apply(_a, relatedInformation); + return diagnostic; + } + function error(location, message, arg0, arg1, arg2, arg3) { + var diagnostic = location + ? ts.createDiagnosticForNode(location, message, arg0, arg1, arg2, arg3) + : ts.createCompilerDiagnostic(message, arg0, arg1, arg2, arg3); + diagnostics.add(diagnostic); + return diagnostic; + } + function addErrorOrSuggestion(isError, diagnostic) { + if (isError) { + diagnostics.add(diagnostic); + } + else { + suggestionDiagnostics.add(diagnostic.file.fileName, __assign({}, diagnostic, { category: ts.DiagnosticCategory.Suggestion })); + } + } + function errorOrSuggestion(isError, location, message, arg0, arg1, arg2, arg3) { + addErrorOrSuggestion(isError, "message" in message ? ts.createDiagnosticForNode(location, message, arg0, arg1, arg2, arg3) : ts.createDiagnosticForNodeFromMessageChain(location, message)); + } + function createSymbol(flags, name, checkFlags) { + symbolCount++; + var symbol = (new Symbol(flags | 33554432, name)); + symbol.checkFlags = checkFlags || 0; + return symbol; + } + function isTransientSymbol(symbol) { + return (symbol.flags & 33554432) !== 0; + } + function getExcludedSymbolFlags(flags) { + var result = 0; + if (flags & 2) + result |= 67220415; + if (flags & 1) + result |= 67220414; + if (flags & 4) + result |= 0; + if (flags & 8) + result |= 68008959; + if (flags & 16) + result |= 67219887; + if (flags & 32) + result |= 68008383; + if (flags & 64) + result |= 67897736; + if (flags & 256) + result |= 68008191; + if (flags & 128) + result |= 68008831; + if (flags & 512) + result |= 110735; + if (flags & 8192) + result |= 67212223; + if (flags & 32768) + result |= 67154879; + if (flags & 65536) + result |= 67187647; + if (flags & 262144) + result |= 67635688; + if (flags & 524288) + result |= 67897832; + if (flags & 2097152) + result |= 2097152; + return result; + } + function recordMergedSymbol(target, source) { + if (!source.mergeId) { + source.mergeId = nextMergeId; + nextMergeId++; + } + mergedSymbols[source.mergeId] = target; + } + function cloneSymbol(symbol) { + var result = createSymbol(symbol.flags, symbol.escapedName); + result.declarations = symbol.declarations ? symbol.declarations.slice() : []; + result.parent = symbol.parent; + if (symbol.valueDeclaration) + result.valueDeclaration = symbol.valueDeclaration; + if (symbol.constEnumOnlyModule) + result.constEnumOnlyModule = true; + if (symbol.members) + result.members = ts.cloneMap(symbol.members); + if (symbol.exports) + result.exports = ts.cloneMap(symbol.exports); + recordMergedSymbol(result, symbol); + return result; + } + function mergeSymbol(target, source) { + if (!(target.flags & getExcludedSymbolFlags(source.flags)) || + (source.flags | target.flags) & 67108864) { + ts.Debug.assert(source !== target); + if (!(target.flags & 33554432)) { + var resolvedTarget = resolveSymbol(target); + if (resolvedTarget === unknownSymbol) { + return source; + } + target = cloneSymbol(resolvedTarget); + } + if (source.flags & 512 && target.flags & 512 && target.constEnumOnlyModule && !source.constEnumOnlyModule) { + target.constEnumOnlyModule = false; + } + target.flags |= source.flags; + if (source.valueDeclaration && + (!target.valueDeclaration || + ts.isAssignmentDeclaration(target.valueDeclaration) && !ts.isAssignmentDeclaration(source.valueDeclaration) || + ts.isEffectiveModuleDeclaration(target.valueDeclaration) && !ts.isEffectiveModuleDeclaration(source.valueDeclaration))) { + target.valueDeclaration = source.valueDeclaration; + } + ts.addRange(target.declarations, source.declarations); + if (source.members) { + if (!target.members) + target.members = ts.createSymbolTable(); + mergeSymbolTable(target.members, source.members); + } + if (source.exports) { + if (!target.exports) + target.exports = ts.createSymbolTable(); + mergeSymbolTable(target.exports, source.exports); + } + recordMergedSymbol(target, source); + } + else if (target.flags & 1024) { + error(ts.getNameOfDeclaration(source.declarations[0]), ts.Diagnostics.Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity, symbolToString(target)); + } + else { + var isEitherEnum = !!(target.flags & 384 || source.flags & 384); + var isEitherBlockScoped_1 = !!(target.flags & 2 || source.flags & 2); + var message = isEitherEnum + ? ts.Diagnostics.Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations + : isEitherBlockScoped_1 + ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 + : ts.Diagnostics.Duplicate_identifier_0; + var sourceSymbolFile = source.declarations && ts.getSourceFileOfNode(source.declarations[0]); + var targetSymbolFile = target.declarations && ts.getSourceFileOfNode(target.declarations[0]); + var symbolName_1 = symbolToString(source); + if (sourceSymbolFile && targetSymbolFile && amalgamatedDuplicates && !isEitherEnum && sourceSymbolFile !== targetSymbolFile) { + var firstFile_1 = ts.comparePaths(sourceSymbolFile.path, targetSymbolFile.path) === -1 ? sourceSymbolFile : targetSymbolFile; + var secondFile_1 = firstFile_1 === sourceSymbolFile ? targetSymbolFile : sourceSymbolFile; + var filesDuplicates = ts.getOrUpdate(amalgamatedDuplicates, firstFile_1.path + "|" + secondFile_1.path, function () { + return ({ firstFile: firstFile_1, secondFile: secondFile_1, conflictingSymbols: ts.createMap() }); + }); + var conflictingSymbolInfo = ts.getOrUpdate(filesDuplicates.conflictingSymbols, symbolName_1, function () { + return ({ isBlockScoped: isEitherBlockScoped_1, firstFileLocations: [], secondFileLocations: [] }); + }); + addDuplicateLocations(conflictingSymbolInfo.firstFileLocations, source); + addDuplicateLocations(conflictingSymbolInfo.secondFileLocations, target); + } + else { + addDuplicateDeclarationErrorsForSymbols(source, message, symbolName_1, target); + addDuplicateDeclarationErrorsForSymbols(target, message, symbolName_1, source); + } + } + return target; + function addDuplicateLocations(locs, symbol) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + ts.pushIfUnique(locs, (ts.getExpandoInitializer(decl, false) ? ts.getNameOfExpando(decl) : ts.getNameOfDeclaration(decl)) || decl); + } + } + } + function addDuplicateDeclarationErrorsForSymbols(target, message, symbolName, source) { + ts.forEach(target.declarations, function (node) { + var errorNode = (ts.getExpandoInitializer(node, false) ? ts.getNameOfExpando(node) : ts.getNameOfDeclaration(node)) || node; + addDuplicateDeclarationError(errorNode, message, symbolName, source.declarations); + }); + } + function addDuplicateDeclarationError(errorNode, message, symbolName, relatedNodes) { + var err = lookupOrIssueError(errorNode, message, symbolName); + for (var _i = 0, _a = relatedNodes || ts.emptyArray; _i < _a.length; _i++) { + var relatedNode = _a[_i]; + err.relatedInformation = err.relatedInformation || []; + if (ts.length(err.relatedInformation) >= 5) + continue; + addRelatedInfo(err, !ts.length(err.relatedInformation) ? ts.createDiagnosticForNode(relatedNode, ts.Diagnostics._0_was_also_declared_here, symbolName) : ts.createDiagnosticForNode(relatedNode, ts.Diagnostics.and_here)); + } + } + function combineSymbolTables(first, second) { + if (!ts.hasEntries(first)) + return second; + if (!ts.hasEntries(second)) + return first; + var combined = ts.createSymbolTable(); + mergeSymbolTable(combined, first); + mergeSymbolTable(combined, second); + return combined; + } + function mergeSymbolTable(target, source) { + source.forEach(function (sourceSymbol, id) { + var targetSymbol = target.get(id); + target.set(id, targetSymbol ? mergeSymbol(targetSymbol, sourceSymbol) : sourceSymbol); + }); + } + function mergeModuleAugmentation(moduleName) { + var moduleAugmentation = moduleName.parent; + if (moduleAugmentation.symbol.declarations[0] !== moduleAugmentation) { + ts.Debug.assert(moduleAugmentation.symbol.declarations.length > 1); + return; + } + if (ts.isGlobalScopeAugmentation(moduleAugmentation)) { + mergeSymbolTable(globals, moduleAugmentation.symbol.exports); + } + else { + var moduleNotFoundError = !(moduleName.parent.parent.flags & 4194304) + ? ts.Diagnostics.Invalid_module_name_in_augmentation_module_0_cannot_be_found + : undefined; + var mainModule = resolveExternalModuleNameWorker(moduleName, moduleName, moduleNotFoundError, true); + if (!mainModule) { + return; + } + mainModule = resolveExternalModuleSymbol(mainModule); + if (mainModule.flags & 1920) { + mainModule = mergeSymbol(mainModule, moduleAugmentation.symbol); + } + else { + error(moduleName, ts.Diagnostics.Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity, moduleName.text); + } + } + } + function addToSymbolTable(target, source, message) { + source.forEach(function (sourceSymbol, id) { + var targetSymbol = target.get(id); + if (targetSymbol) { + ts.forEach(targetSymbol.declarations, addDeclarationDiagnostic(ts.unescapeLeadingUnderscores(id), message)); + } + else { + target.set(id, sourceSymbol); + } + }); + function addDeclarationDiagnostic(id, message) { + return function (declaration) { return diagnostics.add(ts.createDiagnosticForNode(declaration, message, id)); }; + } + } + function getSymbolLinks(symbol) { + if (symbol.flags & 33554432) + return symbol; + var id = getSymbolId(symbol); + return symbolLinks[id] || (symbolLinks[id] = {}); + } + function getNodeLinks(node) { + var nodeId = getNodeId(node); + return nodeLinks[nodeId] || (nodeLinks[nodeId] = { flags: 0 }); + } + function isGlobalSourceFile(node) { + return node.kind === 279 && !ts.isExternalOrCommonJsModule(node); + } + function getSymbol(symbols, name, meaning) { + if (meaning) { + var symbol = symbols.get(name); + if (symbol) { + ts.Debug.assert((ts.getCheckFlags(symbol) & 1) === 0, "Should never get an instantiated symbol here."); + if (symbol.flags & meaning) { + return symbol; + } + if (symbol.flags & 2097152) { + var target = resolveAlias(symbol); + if (target === unknownSymbol || target.flags & meaning) { + return symbol; + } + } + } + } + } + function getSymbolsOfParameterPropertyDeclaration(parameter, parameterName) { + var constructorDeclaration = parameter.parent; + var classDeclaration = parameter.parent.parent; + var parameterSymbol = getSymbol(constructorDeclaration.locals, parameterName, 67220415); + var propertySymbol = getSymbol(getMembersOfSymbol(classDeclaration.symbol), parameterName, 67220415); + if (parameterSymbol && propertySymbol) { + return [parameterSymbol, propertySymbol]; + } + return ts.Debug.fail("There should exist two symbols, one as property declaration and one as parameter declaration"); + } + function isBlockScopedNameDeclaredBeforeUse(declaration, usage) { + var declarationFile = ts.getSourceFileOfNode(declaration); + var useFile = ts.getSourceFileOfNode(usage); + if (declarationFile !== useFile) { + if ((moduleKind && (declarationFile.externalModuleIndicator || useFile.externalModuleIndicator)) || + (!compilerOptions.outFile && !compilerOptions.out) || + isInTypeQuery(usage) || + declaration.flags & 4194304) { + return true; + } + if (isUsedInFunctionOrInstanceProperty(usage, declaration)) { + return true; + } + var sourceFiles = host.getSourceFiles(); + return sourceFiles.indexOf(declarationFile) <= sourceFiles.indexOf(useFile); + } + if (declaration.pos <= usage.pos) { + if (declaration.kind === 186) { + var errorBindingElement = ts.getAncestor(usage, 186); + if (errorBindingElement) { + return ts.findAncestor(errorBindingElement, ts.isBindingElement) !== ts.findAncestor(declaration, ts.isBindingElement) || + declaration.pos < errorBindingElement.pos; + } + return isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 237), usage); + } + else if (declaration.kind === 237) { + return !isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage); + } + else if (ts.isClassDeclaration(declaration)) { + return !ts.findAncestor(usage, function (n) { return ts.isComputedPropertyName(n) && n.parent.parent === declaration; }); + } + return true; + } + if (usage.parent.kind === 257 || (usage.parent.kind === 254 && usage.parent.isExportEquals)) { + return true; + } + if (usage.kind === 254 && usage.isExportEquals) { + return true; + } + var container = ts.getEnclosingBlockScopeContainer(declaration); + return !!(usage.flags & 2097152) || isInTypeQuery(usage) || isUsedInFunctionOrInstanceProperty(usage, declaration, container); + function isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage) { + var container = ts.getEnclosingBlockScopeContainer(declaration); + switch (declaration.parent.parent.kind) { + case 219: + case 225: + case 227: + if (isSameScopeDescendentOf(usage, declaration, container)) { + return true; + } + break; + } + var grandparent = declaration.parent.parent; + return ts.isForInOrOfStatement(grandparent) && isSameScopeDescendentOf(usage, grandparent.expression, container); + } + function isUsedInFunctionOrInstanceProperty(usage, declaration, container) { + return !!ts.findAncestor(usage, function (current) { + if (current === container) { + return "quit"; + } + if (ts.isFunctionLike(current)) { + return true; + } + var initializerOfProperty = current.parent && + current.parent.kind === 154 && + current.parent.initializer === current; + if (initializerOfProperty) { + if (ts.hasModifier(current.parent, 32)) { + if (declaration.kind === 156) { + return true; + } + } + else { + var isDeclarationInstanceProperty = declaration.kind === 154 && !ts.hasModifier(declaration, 32); + if (!isDeclarationInstanceProperty || ts.getContainingClass(usage) !== ts.getContainingClass(declaration)) { + return true; + } + } + } + return false; + }); + } + } + function resolveName(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, suggestedNameNotFoundMessage) { + if (excludeGlobals === void 0) { excludeGlobals = false; } + return resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, getSymbol, suggestedNameNotFoundMessage); + } + function resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, lookup, suggestedNameNotFoundMessage) { + var originalLocation = location; + var result; + var lastLocation; + var lastSelfReferenceLocation; + var propertyWithInvalidInitializer; + var errorLocation = location; + var grandparent; + var isInExternalModule = false; + loop: while (location) { + if (location.locals && !isGlobalSourceFile(location)) { + if (result = lookup(location.locals, name, meaning)) { + var useResult = true; + if (ts.isFunctionLike(location) && lastLocation && lastLocation !== location.body) { + if (meaning & result.flags & 67897832 && lastLocation.kind !== 291) { + useResult = result.flags & 262144 + ? lastLocation === location.type || + lastLocation.kind === 151 || + lastLocation.kind === 150 + : false; + } + if (meaning & result.flags & 3) { + var functionLocation = location; + if (compilerOptions.target && compilerOptions.target >= 2 && ts.isParameter(lastLocation) && + functionLocation.body && result.valueDeclaration.pos >= functionLocation.body.pos && result.valueDeclaration.end <= functionLocation.body.end) { + useResult = false; + } + else if (result.flags & 1) { + useResult = + lastLocation.kind === 151 || + (lastLocation === location.type && + !!ts.findAncestor(result.valueDeclaration, ts.isParameter)); + } + } + } + else if (location.kind === 175) { + useResult = lastLocation === location.trueType; + } + if (useResult) { + break loop; + } + else { + result = undefined; + } + } + } + switch (location.kind) { + case 279: + if (!ts.isExternalOrCommonJsModule(location)) + break; + isInExternalModule = true; + case 244: + var moduleExports = getSymbolOfNode(location).exports; + if (location.kind === 279 || ts.isAmbientModule(location)) { + if (result = moduleExports.get("default")) { + var localSymbol = ts.getLocalSymbolForExportDefault(result); + if (localSymbol && (result.flags & meaning) && localSymbol.escapedName === name) { + break loop; + } + result = undefined; + } + var moduleExport = moduleExports.get(name); + if (moduleExport && + moduleExport.flags === 2097152 && + ts.getDeclarationOfKind(moduleExport, 257)) { + break; + } + } + if (name !== "default" && (result = lookup(moduleExports, name, meaning & 2623475))) { + if (ts.isSourceFile(location) && location.commonJsModuleIndicator && !result.declarations.some(ts.isJSDocTypeAlias)) { + result = undefined; + } + else { + break loop; + } + } + break; + case 243: + if (result = lookup(getSymbolOfNode(location).exports, name, meaning & 8)) { + break loop; + } + break; + case 154: + case 153: + if (ts.isClassLike(location.parent) && !ts.hasModifier(location, 32)) { + var ctor = findConstructorDeclaration(location.parent); + if (ctor && ctor.locals) { + if (lookup(ctor.locals, name, meaning & 67220415)) { + propertyWithInvalidInitializer = location; + } + } + } + break; + case 240: + case 209: + case 241: + if (result = lookup(getSymbolOfNode(location).members || emptySymbols, name, meaning & 67897832)) { + if (!isTypeParameterSymbolDeclaredInContainer(result, location)) { + result = undefined; + break; + } + if (lastLocation && ts.hasModifier(lastLocation, 32)) { + error(errorLocation, ts.Diagnostics.Static_members_cannot_reference_class_type_parameters); + return undefined; + } + break loop; + } + if (location.kind === 209 && meaning & 32) { + var className = location.name; + if (className && name === className.escapedText) { + result = location.symbol; + break loop; + } + } + break; + case 211: + if (lastLocation === location.expression && location.parent.token === 86) { + var container = location.parent.parent; + if (ts.isClassLike(container) && (result = lookup(getSymbolOfNode(container).members, name, meaning & 67897832))) { + if (nameNotFoundMessage) { + error(errorLocation, ts.Diagnostics.Base_class_expressions_cannot_reference_class_type_parameters); + } + return undefined; + } + } + break; + case 149: + grandparent = location.parent.parent; + if (ts.isClassLike(grandparent) || grandparent.kind === 241) { + if (result = lookup(getSymbolOfNode(grandparent).members, name, meaning & 67897832)) { + error(errorLocation, ts.Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type); + return undefined; + } + } + break; + case 156: + case 155: + case 157: + case 158: + case 159: + case 239: + case 197: + if (meaning & 3 && name === "arguments") { + result = argumentsSymbol; + break loop; + } + break; + case 196: + if (meaning & 3 && name === "arguments") { + result = argumentsSymbol; + break loop; + } + if (meaning & 16) { + var functionName = location.name; + if (functionName && name === functionName.escapedText) { + result = location.symbol; + break loop; + } + } + break; + case 152: + if (location.parent && location.parent.kind === 151) { + location = location.parent; + } + if (location.parent && ts.isClassElement(location.parent)) { + location = location.parent; + } + break; + case 304: + case 297: + location = ts.getJSDocHost(location); + break; + } + if (isSelfReferenceLocation(location)) { + lastSelfReferenceLocation = location; + } + lastLocation = location; + location = location.parent; + } + if (isUse && result && (!lastSelfReferenceLocation || result !== lastSelfReferenceLocation.symbol)) { + result.isReferenced |= meaning; + } + if (!result) { + if (lastLocation) { + ts.Debug.assert(lastLocation.kind === 279); + if (lastLocation.commonJsModuleIndicator && name === "exports" && meaning & lastLocation.symbol.flags) { + return lastLocation.symbol; + } + } + if (!excludeGlobals) { + result = lookup(globals, name, meaning); + } + } + if (!result) { + if (originalLocation && ts.isInJSFile(originalLocation) && originalLocation.parent) { + if (ts.isRequireCall(originalLocation.parent, false)) { + return requireSymbol; + } + } + } + if (!result) { + if (nameNotFoundMessage) { + if (!errorLocation || + !checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) && + !checkAndReportErrorForExtendingInterface(errorLocation) && + !checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) && + !checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) && + !checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning)) { + var suggestion = void 0; + if (suggestedNameNotFoundMessage && suggestionCount < maximumSuggestionCount) { + suggestion = getSuggestedSymbolForNonexistentSymbol(originalLocation, name, meaning); + if (suggestion) { + var suggestionName = symbolToString(suggestion); + var diagnostic = error(errorLocation, suggestedNameNotFoundMessage, diagnosticName(nameArg), suggestionName); + if (suggestion.valueDeclaration) { + addRelatedInfo(diagnostic, ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestionName)); + } + } + } + if (!suggestion) { + error(errorLocation, nameNotFoundMessage, diagnosticName(nameArg)); + } + suggestionCount++; + } + } + return undefined; + } + if (nameNotFoundMessage) { + if (propertyWithInvalidInitializer) { + var propertyName = propertyWithInvalidInitializer.name; + error(errorLocation, ts.Diagnostics.Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor, ts.declarationNameToString(propertyName), diagnosticName(nameArg)); + return undefined; + } + if (errorLocation && + (meaning & 2 || + ((meaning & 32 || meaning & 384) && (meaning & 67220415) === 67220415))) { + var exportOrLocalSymbol = getExportSymbolOfValueSymbolIfExported(result); + if (exportOrLocalSymbol.flags & 2 || exportOrLocalSymbol.flags & 32 || exportOrLocalSymbol.flags & 384) { + checkResolvedBlockScopedVariable(exportOrLocalSymbol, errorLocation); + } + } + if (result && isInExternalModule && (meaning & 67220415) === 67220415 && !(originalLocation.flags & 2097152)) { + if (ts.some(result.declarations, function (d) { return ts.isNamespaceExportDeclaration(d) || ts.isSourceFile(d) && !!d.symbol.globalExports; })) { + error(errorLocation, ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead, ts.unescapeLeadingUnderscores(name)); + } + } + } + return result; + } + function isSelfReferenceLocation(node) { + switch (node.kind) { + case 239: + case 240: + case 241: + case 243: + case 242: + case 244: + return true; + default: + return false; + } + } + function diagnosticName(nameArg) { + return ts.isString(nameArg) ? ts.unescapeLeadingUnderscores(nameArg) : ts.declarationNameToString(nameArg); + } + function isTypeParameterSymbolDeclaredInContainer(symbol, container) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + if (decl.kind === 150) { + var parent = ts.isJSDocTemplateTag(decl.parent) ? ts.getJSDocHost(decl.parent) : decl.parent; + if (parent === container) { + return !(ts.isJSDocTemplateTag(decl.parent) && ts.find(decl.parent.parent.tags, ts.isJSDocTypeAlias)); + } + } + } + return false; + } + function checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) { + if (!ts.isIdentifier(errorLocation) || errorLocation.escapedText !== name || isTypeReferenceIdentifier(errorLocation) || isInTypeQuery(errorLocation)) { + return false; + } + var container = ts.getThisContainer(errorLocation, false); + var location = container; + while (location) { + if (ts.isClassLike(location.parent)) { + var classSymbol = getSymbolOfNode(location.parent); + if (!classSymbol) { + break; + } + var constructorType = getTypeOfSymbol(classSymbol); + if (getPropertyOfType(constructorType, name)) { + error(errorLocation, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_static_member_1_0, diagnosticName(nameArg), symbolToString(classSymbol)); + return true; + } + if (location === container && !ts.hasModifier(location, 32)) { + var instanceType = getDeclaredTypeOfSymbol(classSymbol).thisType; + if (getPropertyOfType(instanceType, name)) { + error(errorLocation, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0, diagnosticName(nameArg)); + return true; + } + } + } + location = location.parent; + } + return false; + } + function checkAndReportErrorForExtendingInterface(errorLocation) { + var expression = getEntityNameForExtendingInterface(errorLocation); + if (expression && resolveEntityName(expression, 64, true)) { + error(errorLocation, ts.Diagnostics.Cannot_extend_an_interface_0_Did_you_mean_implements, ts.getTextOfNode(expression)); + return true; + } + return false; + } + function getEntityNameForExtendingInterface(node) { + switch (node.kind) { + case 72: + case 189: + return node.parent ? getEntityNameForExtendingInterface(node.parent) : undefined; + case 211: + if (ts.isEntityNameExpression(node.expression)) { + return node.expression; + } + default: + return undefined; + } + } + function checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) { + var namespaceMeaning = 1920 | (ts.isInJSFile(errorLocation) ? 67220415 : 0); + if (meaning === namespaceMeaning) { + var symbol = resolveSymbol(resolveName(errorLocation, name, 67897832 & ~namespaceMeaning, undefined, undefined, false)); + var parent = errorLocation.parent; + if (symbol) { + if (ts.isQualifiedName(parent)) { + ts.Debug.assert(parent.left === errorLocation, "Should only be resolving left side of qualified name as a namespace"); + var propName = parent.right.escapedText; + var propType = getPropertyOfType(getDeclaredTypeOfSymbol(symbol), propName); + if (propType) { + error(parent, ts.Diagnostics.Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_property_1_in_0_with_0_1, ts.unescapeLeadingUnderscores(name), ts.unescapeLeadingUnderscores(propName)); + return true; + } + } + error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here, ts.unescapeLeadingUnderscores(name)); + return true; + } + } + return false; + } + function checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) { + if (meaning & (67220415 & ~1024)) { + if (name === "any" || name === "string" || name === "number" || name === "boolean" || name === "never") { + error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, ts.unescapeLeadingUnderscores(name)); + return true; + } + var symbol = resolveSymbol(resolveName(errorLocation, name, 67897832 & ~67220415, undefined, undefined, false)); + if (symbol && !(symbol.flags & 1024)) { + var message = (name === "Promise" || name === "Symbol") + ? ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later + : ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here; + error(errorLocation, message, ts.unescapeLeadingUnderscores(name)); + return true; + } + } + return false; + } + function checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) { + if (meaning & (67220415 & ~1024 & ~67897832)) { + var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 & ~67220415, undefined, undefined, false)); + if (symbol) { + error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_value, ts.unescapeLeadingUnderscores(name)); + return true; + } + } + else if (meaning & (67897832 & ~1024 & ~67220415)) { + var symbol = resolveSymbol(resolveName(errorLocation, name, (512 | 1024) & ~67897832, undefined, undefined, false)); + if (symbol) { + error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_type, ts.unescapeLeadingUnderscores(name)); + return true; + } + } + return false; + } + function checkResolvedBlockScopedVariable(result, errorLocation) { + ts.Debug.assert(!!(result.flags & 2 || result.flags & 32 || result.flags & 384)); + var declaration = ts.find(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) || ts.isClassLike(d) || (d.kind === 243) || ts.isInJSFile(d) && !!ts.getJSDocEnumTag(d); }); + if (declaration === undefined) + return ts.Debug.fail("Declaration to checkResolvedBlockScopedVariable is undefined"); + if (!(declaration.flags & 4194304) && !isBlockScopedNameDeclaredBeforeUse(declaration, errorLocation)) { + var diagnosticMessage = void 0; + var declarationName = ts.declarationNameToString(ts.getNameOfDeclaration(declaration)); + if (result.flags & 2) { + diagnosticMessage = error(errorLocation, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, declarationName); + } + else if (result.flags & 32) { + diagnosticMessage = error(errorLocation, ts.Diagnostics.Class_0_used_before_its_declaration, declarationName); + } + else if (result.flags & 256) { + diagnosticMessage = error(errorLocation, ts.Diagnostics.Enum_0_used_before_its_declaration, declarationName); + } + else { + ts.Debug.assert(!!(result.flags & 128)); + if (compilerOptions.preserveConstEnums) { + diagnosticMessage = error(errorLocation, ts.Diagnostics.Class_0_used_before_its_declaration, declarationName); + } + } + if (diagnosticMessage) { + addRelatedInfo(diagnosticMessage, ts.createDiagnosticForNode(declaration, ts.Diagnostics._0_is_declared_here, declarationName)); + } + } + } + function isSameScopeDescendentOf(initial, parent, stopAt) { + return !!parent && !!ts.findAncestor(initial, function (n) { return n === stopAt || ts.isFunctionLike(n) ? "quit" : n === parent; }); + } + function getAnyImportSyntax(node) { + switch (node.kind) { + case 248: + return node; + case 250: + return node.parent; + case 251: + return node.parent.parent; + case 253: + return node.parent.parent.parent; + default: + return undefined; + } + } + function getDeclarationOfAliasSymbol(symbol) { + return ts.find(symbol.declarations, ts.isAliasSymbolDeclaration); + } + function getTargetOfImportEqualsDeclaration(node, dontResolveAlias) { + if (node.moduleReference.kind === 259) { + return resolveExternalModuleSymbol(resolveExternalModuleName(node, ts.getExternalModuleImportEqualsDeclarationExpression(node))); + } + return getSymbolOfPartOfRightHandSideOfImportEquals(node.moduleReference, dontResolveAlias); + } + function resolveExportByName(moduleSymbol, name, dontResolveAlias) { + var exportValue = moduleSymbol.exports.get("export="); + return exportValue + ? getPropertyOfType(getTypeOfSymbol(exportValue), name) + : resolveSymbol(moduleSymbol.exports.get(name), dontResolveAlias); + } + function isSyntacticDefault(node) { + return ((ts.isExportAssignment(node) && !node.isExportEquals) || ts.hasModifier(node, 512) || ts.isExportSpecifier(node)); + } + function canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias) { + if (!allowSyntheticDefaultImports) { + return false; + } + if (!file || file.isDeclarationFile) { + var defaultExportSymbol = resolveExportByName(moduleSymbol, "default", true); + if (defaultExportSymbol && ts.some(defaultExportSymbol.declarations, isSyntacticDefault)) { + return false; + } + if (resolveExportByName(moduleSymbol, ts.escapeLeadingUnderscores("__esModule"), dontResolveAlias)) { + return false; + } + return true; + } + if (!ts.isSourceFileJS(file)) { + return hasExportAssignmentSymbol(moduleSymbol); + } + return !file.externalModuleIndicator && !resolveExportByName(moduleSymbol, ts.escapeLeadingUnderscores("__esModule"), dontResolveAlias); + } + function getTargetOfImportClause(node, dontResolveAlias) { + var moduleSymbol = resolveExternalModuleName(node, node.parent.moduleSpecifier); + if (moduleSymbol) { + var exportDefaultSymbol = void 0; + if (ts.isShorthandAmbientModuleSymbol(moduleSymbol)) { + exportDefaultSymbol = moduleSymbol; + } + else { + exportDefaultSymbol = resolveExportByName(moduleSymbol, "default", dontResolveAlias); + } + var file = ts.find(moduleSymbol.declarations, ts.isSourceFile); + var hasSyntheticDefault = canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias); + if (!exportDefaultSymbol && !hasSyntheticDefault) { + error(node.name, ts.Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol)); + } + else if (hasSyntheticDefault) { + return resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias); + } + return exportDefaultSymbol; + } + } + function getTargetOfNamespaceImport(node, dontResolveAlias) { + var moduleSpecifier = node.parent.parent.moduleSpecifier; + return resolveESModuleSymbol(resolveExternalModuleName(node, moduleSpecifier), moduleSpecifier, dontResolveAlias); + } + function combineValueAndTypeSymbols(valueSymbol, typeSymbol) { + if (valueSymbol === unknownSymbol && typeSymbol === unknownSymbol) { + return unknownSymbol; + } + if (valueSymbol.flags & (67897832 | 1920)) { + return valueSymbol; + } + var result = createSymbol(valueSymbol.flags | typeSymbol.flags, valueSymbol.escapedName); + result.declarations = ts.deduplicate(ts.concatenate(valueSymbol.declarations, typeSymbol.declarations), ts.equateValues); + result.parent = valueSymbol.parent || typeSymbol.parent; + if (valueSymbol.valueDeclaration) + result.valueDeclaration = valueSymbol.valueDeclaration; + if (typeSymbol.members) + result.members = typeSymbol.members; + if (valueSymbol.exports) + result.exports = valueSymbol.exports; + return result; + } + function getExportOfModule(symbol, name, dontResolveAlias) { + if (symbol.flags & 1536) { + return resolveSymbol(getExportsOfSymbol(symbol).get(name), dontResolveAlias); + } + } + function getPropertyOfVariable(symbol, name) { + if (symbol.flags & 3) { + var typeAnnotation = symbol.valueDeclaration.type; + if (typeAnnotation) { + return resolveSymbol(getPropertyOfType(getTypeFromTypeNode(typeAnnotation), name)); + } + } + } + function getExternalModuleMember(node, specifier, dontResolveAlias) { + if (dontResolveAlias === void 0) { dontResolveAlias = false; } + var moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier); + var targetSymbol = resolveESModuleSymbol(moduleSymbol, node.moduleSpecifier, dontResolveAlias); + if (targetSymbol) { + var name = specifier.propertyName || specifier.name; + if (name.escapedText) { + if (ts.isShorthandAmbientModuleSymbol(moduleSymbol)) { + return moduleSymbol; + } + var symbolFromVariable = void 0; + if (moduleSymbol && moduleSymbol.exports && moduleSymbol.exports.get("export=")) { + symbolFromVariable = getPropertyOfType(getTypeOfSymbol(targetSymbol), name.escapedText); + } + else { + symbolFromVariable = getPropertyOfVariable(targetSymbol, name.escapedText); + } + symbolFromVariable = resolveSymbol(symbolFromVariable, dontResolveAlias); + var symbolFromModule = getExportOfModule(targetSymbol, name.escapedText, dontResolveAlias); + if (!symbolFromModule && allowSyntheticDefaultImports && name.escapedText === "default") { + symbolFromModule = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias); + } + var symbol = symbolFromModule && symbolFromVariable && symbolFromModule !== symbolFromVariable ? + combineValueAndTypeSymbols(symbolFromVariable, symbolFromModule) : + symbolFromModule || symbolFromVariable; + if (!symbol) { + var moduleName = getFullyQualifiedName(moduleSymbol, node); + var declarationName = ts.declarationNameToString(name); + var suggestion = getSuggestedSymbolForNonexistentModule(name, targetSymbol); + if (suggestion !== undefined) { + var suggestionName = symbolToString(suggestion); + var diagnostic = error(name, ts.Diagnostics.Module_0_has_no_exported_member_1_Did_you_mean_2, moduleName, declarationName, suggestionName); + if (suggestion.valueDeclaration) { + addRelatedInfo(diagnostic, ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestionName)); + } + } + else { + error(name, ts.Diagnostics.Module_0_has_no_exported_member_1, moduleName, declarationName); + } + } + return symbol; + } + } + } + function getTargetOfImportSpecifier(node, dontResolveAlias) { + return getExternalModuleMember(node.parent.parent.parent, node, dontResolveAlias); + } + function getTargetOfNamespaceExportDeclaration(node, dontResolveAlias) { + return resolveExternalModuleSymbol(node.parent.symbol, dontResolveAlias); + } + function getTargetOfExportSpecifier(node, meaning, dontResolveAlias) { + return node.parent.parent.moduleSpecifier ? + getExternalModuleMember(node.parent.parent, node, dontResolveAlias) : + resolveEntityName(node.propertyName || node.name, meaning, false, dontResolveAlias); + } + function getTargetOfExportAssignment(node, dontResolveAlias) { + var expression = (ts.isExportAssignment(node) ? node.expression : node.right); + if (ts.isClassExpression(expression)) { + return checkExpression(expression).symbol; + } + var aliasLike = resolveEntityName(expression, 67220415 | 67897832 | 1920, true, dontResolveAlias); + if (aliasLike) { + return aliasLike; + } + checkExpression(expression); + return getNodeLinks(expression).resolvedSymbol; + } + function getTargetOfAliasDeclaration(node, dontRecursivelyResolve) { + if (dontRecursivelyResolve === void 0) { dontRecursivelyResolve = false; } + switch (node.kind) { + case 248: + return getTargetOfImportEqualsDeclaration(node, dontRecursivelyResolve); + case 250: + return getTargetOfImportClause(node, dontRecursivelyResolve); + case 251: + return getTargetOfNamespaceImport(node, dontRecursivelyResolve); + case 253: + return getTargetOfImportSpecifier(node, dontRecursivelyResolve); + case 257: + return getTargetOfExportSpecifier(node, 67220415 | 67897832 | 1920, dontRecursivelyResolve); + case 254: + case 204: + return getTargetOfExportAssignment(node, dontRecursivelyResolve); + case 247: + return getTargetOfNamespaceExportDeclaration(node, dontRecursivelyResolve); + default: + return ts.Debug.fail(); + } + } + function isNonLocalAlias(symbol, excludes) { + if (excludes === void 0) { excludes = 67220415 | 67897832 | 1920; } + if (!symbol) + return false; + return (symbol.flags & (2097152 | excludes)) === 2097152 || !!(symbol.flags & 2097152 && symbol.flags & 67108864); + } + function resolveSymbol(symbol, dontResolveAlias) { + return !dontResolveAlias && isNonLocalAlias(symbol) ? resolveAlias(symbol) : symbol; + } + function resolveAlias(symbol) { + ts.Debug.assert((symbol.flags & 2097152) !== 0, "Should only get Alias here."); + var links = getSymbolLinks(symbol); + if (!links.target) { + links.target = resolvingSymbol; + var node = getDeclarationOfAliasSymbol(symbol); + if (!node) + return ts.Debug.fail(); + var target = getTargetOfAliasDeclaration(node); + if (links.target === resolvingSymbol) { + links.target = target || unknownSymbol; + } + else { + error(node, ts.Diagnostics.Circular_definition_of_import_alias_0, symbolToString(symbol)); + } + } + else if (links.target === resolvingSymbol) { + links.target = unknownSymbol; + } + return links.target; + } + function markExportAsReferenced(node) { + var symbol = getSymbolOfNode(node); + var target = resolveAlias(symbol); + if (target) { + var markAlias = target === unknownSymbol || + ((target.flags & 67220415) && !isConstEnumOrConstEnumOnlyModule(target)); + if (markAlias) { + markAliasSymbolAsReferenced(symbol); + } + } + } + function markAliasSymbolAsReferenced(symbol) { + var links = getSymbolLinks(symbol); + if (!links.referenced) { + links.referenced = true; + var node = getDeclarationOfAliasSymbol(symbol); + if (!node) + return ts.Debug.fail(); + if (node.kind === 254) { + checkExpressionCached(node.expression); + } + else if (node.kind === 257) { + checkExpressionCached(node.propertyName || node.name); + } + else if (ts.isInternalModuleImportEqualsDeclaration(node)) { + checkExpressionCached(node.moduleReference); + } + } + } + function getSymbolOfPartOfRightHandSideOfImportEquals(entityName, dontResolveAlias) { + if (entityName.kind === 72 && ts.isRightSideOfQualifiedNameOrPropertyAccess(entityName)) { + entityName = entityName.parent; + } + if (entityName.kind === 72 || entityName.parent.kind === 148) { + return resolveEntityName(entityName, 1920, false, dontResolveAlias); + } + else { + ts.Debug.assert(entityName.parent.kind === 248); + return resolveEntityName(entityName, 67220415 | 67897832 | 1920, false, dontResolveAlias); + } + } + function getFullyQualifiedName(symbol, containingLocation) { + return symbol.parent ? getFullyQualifiedName(symbol.parent, containingLocation) + "." + symbolToString(symbol) : symbolToString(symbol, containingLocation, undefined, 16 | 4); + } + function resolveEntityName(name, meaning, ignoreErrors, dontResolveAlias, location) { + if (ts.nodeIsMissing(name)) { + return undefined; + } + var namespaceMeaning = 1920 | (ts.isInJSFile(name) ? meaning & 67220415 : 0); + var symbol; + if (name.kind === 72) { + var message = meaning === namespaceMeaning ? ts.Diagnostics.Cannot_find_namespace_0 : getCannotFindNameDiagnosticForName(getFirstIdentifier(name).escapedText); + var symbolFromJSPrototype = ts.isInJSFile(name) ? resolveEntityNameFromAssignmentDeclaration(name, meaning) : undefined; + symbol = resolveName(location || name, name.escapedText, meaning, ignoreErrors || symbolFromJSPrototype ? undefined : message, name, true); + if (!symbol) { + return symbolFromJSPrototype; + } + } + else if (name.kind === 148 || name.kind === 189) { + var left = name.kind === 148 ? name.left : name.expression; + var right = name.kind === 148 ? name.right : name.name; + var namespace = resolveEntityName(left, namespaceMeaning, ignoreErrors, false, location); + if (!namespace || ts.nodeIsMissing(right)) { + return undefined; + } + else if (namespace === unknownSymbol) { + return namespace; + } + if (ts.isInJSFile(name)) { + if (namespace.valueDeclaration && + ts.isVariableDeclaration(namespace.valueDeclaration) && + namespace.valueDeclaration.initializer && + isCommonJsRequire(namespace.valueDeclaration.initializer)) { + var moduleName = namespace.valueDeclaration.initializer.arguments[0]; + var moduleSym = resolveExternalModuleName(moduleName, moduleName); + if (moduleSym) { + var resolvedModuleSymbol = resolveExternalModuleSymbol(moduleSym); + if (resolvedModuleSymbol) { + namespace = resolvedModuleSymbol; + } + } + } + } + symbol = getSymbol(getExportsOfSymbol(namespace), right.escapedText, meaning); + if (!symbol) { + if (!ignoreErrors) { + error(right, ts.Diagnostics.Namespace_0_has_no_exported_member_1, getFullyQualifiedName(namespace), ts.declarationNameToString(right)); + } + return undefined; + } + } + else { + throw ts.Debug.assertNever(name, "Unknown entity name kind."); + } + ts.Debug.assert((ts.getCheckFlags(symbol) & 1) === 0, "Should never get an instantiated symbol here."); + return (symbol.flags & meaning) || dontResolveAlias ? symbol : resolveAlias(symbol); + } + function resolveEntityNameFromAssignmentDeclaration(name, meaning) { + if (isJSDocTypeReference(name.parent)) { + var secondaryLocation = getAssignmentDeclarationLocation(name.parent); + if (secondaryLocation) { + return resolveName(secondaryLocation, name.escapedText, meaning, undefined, name, true); + } + } + } + function getAssignmentDeclarationLocation(node) { + var typeAlias = ts.findAncestor(node, function (node) { return !(ts.isJSDocNode(node) || node.flags & 2097152) ? "quit" : ts.isJSDocTypeAlias(node); }); + if (typeAlias) { + return; + } + var host = ts.getJSDocHost(node); + if (ts.isExpressionStatement(host) && + ts.isBinaryExpression(host.expression) && + ts.getAssignmentDeclarationKind(host.expression) === 3) { + var symbol = getSymbolOfNode(host.expression.left); + if (symbol) { + return getDeclarationOfJSPrototypeContainer(symbol); + } + } + if ((ts.isObjectLiteralMethod(host) || ts.isPropertyAssignment(host)) && + ts.isBinaryExpression(host.parent.parent) && + ts.getAssignmentDeclarationKind(host.parent.parent) === 6) { + var symbol = getSymbolOfNode(host.parent.parent.left); + if (symbol) { + return getDeclarationOfJSPrototypeContainer(symbol); + } + } + var sig = ts.getHostSignatureFromJSDocHost(host); + if (sig) { + var symbol = getSymbolOfNode(sig); + return symbol && symbol.valueDeclaration; + } + } + function getDeclarationOfJSPrototypeContainer(symbol) { + var decl = symbol.parent.valueDeclaration; + if (!decl) { + return undefined; + } + var initializer = ts.isAssignmentDeclaration(decl) ? ts.getAssignedExpandoInitializer(decl) : + ts.hasOnlyExpressionInitializer(decl) ? ts.getDeclaredExpandoInitializer(decl) : + undefined; + return initializer || decl; + } + function resolveExternalModuleName(location, moduleReferenceExpression, ignoreErrors) { + return resolveExternalModuleNameWorker(location, moduleReferenceExpression, ignoreErrors ? undefined : ts.Diagnostics.Cannot_find_module_0); + } + function resolveExternalModuleNameWorker(location, moduleReferenceExpression, moduleNotFoundError, isForAugmentation) { + if (isForAugmentation === void 0) { isForAugmentation = false; } + return ts.isStringLiteralLike(moduleReferenceExpression) + ? resolveExternalModule(location, moduleReferenceExpression.text, moduleNotFoundError, moduleReferenceExpression, isForAugmentation) + : undefined; + } + function resolveExternalModule(location, moduleReference, moduleNotFoundError, errorNode, isForAugmentation) { + if (isForAugmentation === void 0) { isForAugmentation = false; } + if (moduleReference === undefined) { + return; + } + if (ts.startsWith(moduleReference, "@types/")) { + var diag = ts.Diagnostics.Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1; + var withoutAtTypePrefix = ts.removePrefix(moduleReference, "@types/"); + error(errorNode, diag, withoutAtTypePrefix, moduleReference); + } + var ambientModule = tryFindAmbientModule(moduleReference, true); + if (ambientModule) { + return ambientModule; + } + var currentSourceFile = ts.getSourceFileOfNode(location); + var resolvedModule = ts.getResolvedModule(currentSourceFile, moduleReference); + var resolutionDiagnostic = resolvedModule && ts.getResolutionDiagnostic(compilerOptions, resolvedModule); + var sourceFile = resolvedModule && !resolutionDiagnostic && host.getSourceFile(resolvedModule.resolvedFileName); + if (sourceFile) { + if (sourceFile.symbol) { + if (resolvedModule.isExternalLibraryImport && !ts.resolutionExtensionIsTSOrJson(resolvedModule.extension)) { + errorOnImplicitAnyModule(false, errorNode, resolvedModule, moduleReference); + } + return getMergedSymbol(sourceFile.symbol); + } + if (moduleNotFoundError) { + error(errorNode, ts.Diagnostics.File_0_is_not_a_module, sourceFile.fileName); + } + return undefined; + } + if (patternAmbientModules) { + var pattern = ts.findBestPatternMatch(patternAmbientModules, function (_) { return _.pattern; }, moduleReference); + if (pattern) { + return getMergedSymbol(pattern.symbol); + } + } + if (resolvedModule && !ts.resolutionExtensionIsTSOrJson(resolvedModule.extension) && resolutionDiagnostic === undefined || resolutionDiagnostic === ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type) { + if (isForAugmentation) { + var diag = ts.Diagnostics.Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented; + error(errorNode, diag, moduleReference, resolvedModule.resolvedFileName); + } + else { + errorOnImplicitAnyModule(noImplicitAny && !!moduleNotFoundError, errorNode, resolvedModule, moduleReference); + } + return undefined; + } + if (moduleNotFoundError) { + if (ts.pathIsRelative(moduleReference)) { + var sourceFile_1 = ts.getSourceFileOfNode(location); + var redirects = sourceFile_1.redirectedReferences; + if (redirects) { + var normalizedTargetPath = ts.getNormalizedAbsolutePath(moduleReference, ts.getDirectoryPath(sourceFile_1.fileName)); + for (var _i = 0, _a = [".ts", ".tsx"]; _i < _a.length; _i++) { + var ext = _a[_i]; + var probePath = normalizedTargetPath + ext; + if (redirects.indexOf(probePath) >= 0) { + error(errorNode, ts.Diagnostics.Output_file_0_has_not_been_built_from_source_file_1, moduleReference, probePath); + return undefined; + } + } + } + } + if (resolutionDiagnostic) { + error(errorNode, resolutionDiagnostic, moduleReference, resolvedModule.resolvedFileName); + } + else { + var tsExtension = ts.tryExtractTSExtension(moduleReference); + if (tsExtension) { + var diag = ts.Diagnostics.An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead; + error(errorNode, diag, tsExtension, ts.removeExtension(moduleReference, tsExtension)); + } + else if (!compilerOptions.resolveJsonModule && + ts.fileExtensionIs(moduleReference, ".json") && + ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs && + ts.hasJsonModuleEmitEnabled(compilerOptions)) { + error(errorNode, ts.Diagnostics.Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension, moduleReference); + } + else { + error(errorNode, moduleNotFoundError, moduleReference); + } + } + } + return undefined; + } + function errorOnImplicitAnyModule(isError, errorNode, _a, moduleReference) { + var packageId = _a.packageId, resolvedFileName = _a.resolvedFileName; + var errorInfo = !ts.isExternalModuleNameRelative(moduleReference) && packageId + ? typesPackageExists(packageId.name) + ? ts.chainDiagnosticMessages(undefined, ts.Diagnostics.If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1, packageId.name, ts.mangleScopedPackageName(packageId.name)) + : ts.chainDiagnosticMessages(undefined, ts.Diagnostics.Try_npm_install_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, moduleReference, ts.mangleScopedPackageName(packageId.name)) + : undefined; + errorOrSuggestion(isError, errorNode, ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type, moduleReference, resolvedFileName)); + } + function typesPackageExists(packageName) { + return getPackagesSet().has(ts.getTypesPackageName(packageName)); + } + function resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) { + if (moduleSymbol) { + var exportEquals = resolveSymbol(moduleSymbol.exports.get("export="), dontResolveAlias); + var exported = getCommonJsExportEquals(exportEquals, moduleSymbol); + return getMergedSymbol(exported) || moduleSymbol; + } + return undefined; + } + function getCommonJsExportEquals(exported, moduleSymbol) { + if (!exported || exported === unknownSymbol || exported === moduleSymbol || moduleSymbol.exports.size === 1 || exported.flags & 2097152) { + return exported; + } + var merged = cloneSymbol(exported); + if (merged.exports === undefined) { + merged.flags = merged.flags | 512; + merged.exports = ts.createSymbolTable(); + } + moduleSymbol.exports.forEach(function (s, name) { + if (name === "export=") + return; + merged.exports.set(name, merged.exports.has(name) ? mergeSymbol(merged.exports.get(name), s) : s); + }); + return merged; + } + function resolveESModuleSymbol(moduleSymbol, referencingLocation, dontResolveAlias) { + var symbol = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias); + if (!dontResolveAlias && symbol) { + if (!(symbol.flags & (1536 | 3)) && !ts.getDeclarationOfKind(symbol, 279)) { + error(referencingLocation, ts.Diagnostics.Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct, symbolToString(moduleSymbol)); + return symbol; + } + if (compilerOptions.esModuleInterop) { + var referenceParent = referencingLocation.parent; + if ((ts.isImportDeclaration(referenceParent) && ts.getNamespaceDeclarationNode(referenceParent)) || + ts.isImportCall(referenceParent)) { + var type = getTypeOfSymbol(symbol); + var sigs = getSignaturesOfStructuredType(type, 0); + if (!sigs || !sigs.length) { + sigs = getSignaturesOfStructuredType(type, 1); + } + if (sigs && sigs.length) { + var moduleType = getTypeWithSyntheticDefaultImportType(type, symbol, moduleSymbol); + var result = createSymbol(symbol.flags, symbol.escapedName); + result.declarations = symbol.declarations ? symbol.declarations.slice() : []; + result.parent = symbol.parent; + result.target = symbol; + result.originatingImport = referenceParent; + if (symbol.valueDeclaration) + result.valueDeclaration = symbol.valueDeclaration; + if (symbol.constEnumOnlyModule) + result.constEnumOnlyModule = true; + if (symbol.members) + result.members = ts.cloneMap(symbol.members); + if (symbol.exports) + result.exports = ts.cloneMap(symbol.exports); + var resolvedModuleType = resolveStructuredTypeMembers(moduleType); + result.type = createAnonymousType(result, resolvedModuleType.members, ts.emptyArray, ts.emptyArray, resolvedModuleType.stringIndexInfo, resolvedModuleType.numberIndexInfo); + return result; + } + } + } + } + return symbol; + } + function hasExportAssignmentSymbol(moduleSymbol) { + return moduleSymbol.exports.get("export=") !== undefined; + } + function getExportsOfModuleAsArray(moduleSymbol) { + return symbolsToArray(getExportsOfModule(moduleSymbol)); + } + function getExportsAndPropertiesOfModule(moduleSymbol) { + var exports = getExportsOfModuleAsArray(moduleSymbol); + var exportEquals = resolveExternalModuleSymbol(moduleSymbol); + if (exportEquals !== moduleSymbol) { + ts.addRange(exports, getPropertiesOfType(getTypeOfSymbol(exportEquals))); + } + return exports; + } + function tryGetMemberInModuleExports(memberName, moduleSymbol) { + var symbolTable = getExportsOfModule(moduleSymbol); + if (symbolTable) { + return symbolTable.get(memberName); + } + } + function tryGetMemberInModuleExportsAndProperties(memberName, moduleSymbol) { + var symbol = tryGetMemberInModuleExports(memberName, moduleSymbol); + if (symbol) { + return symbol; + } + var exportEquals = resolveExternalModuleSymbol(moduleSymbol); + if (exportEquals === moduleSymbol) { + return undefined; + } + var type = getTypeOfSymbol(exportEquals); + return type.flags & 131068 ? undefined : getPropertyOfType(type, memberName); + } + function getExportsOfSymbol(symbol) { + return symbol.flags & 32 ? getResolvedMembersOrExportsOfSymbol(symbol, "resolvedExports") : + symbol.flags & 1536 ? getExportsOfModule(symbol) : + symbol.exports || emptySymbols; + } + function getExportsOfModule(moduleSymbol) { + var links = getSymbolLinks(moduleSymbol); + return links.resolvedExports || (links.resolvedExports = getExportsOfModuleWorker(moduleSymbol)); + } + function extendExportSymbols(target, source, lookupTable, exportNode) { + if (!source) + return; + source.forEach(function (sourceSymbol, id) { + if (id === "default") + return; + var targetSymbol = target.get(id); + if (!targetSymbol) { + target.set(id, sourceSymbol); + if (lookupTable && exportNode) { + lookupTable.set(id, { + specifierText: ts.getTextOfNode(exportNode.moduleSpecifier) + }); + } + } + else if (lookupTable && exportNode && targetSymbol && resolveSymbol(targetSymbol) !== resolveSymbol(sourceSymbol)) { + var collisionTracker = lookupTable.get(id); + if (!collisionTracker.exportsWithDuplicate) { + collisionTracker.exportsWithDuplicate = [exportNode]; + } + else { + collisionTracker.exportsWithDuplicate.push(exportNode); + } + } + }); + } + function getExportsOfModuleWorker(moduleSymbol) { + var visitedSymbols = []; + moduleSymbol = resolveExternalModuleSymbol(moduleSymbol); + return visit(moduleSymbol) || emptySymbols; + function visit(symbol) { + if (!(symbol && symbol.exports && ts.pushIfUnique(visitedSymbols, symbol))) { + return; + } + var symbols = ts.cloneMap(symbol.exports); + var exportStars = symbol.exports.get("__export"); + if (exportStars) { + var nestedSymbols = ts.createSymbolTable(); + var lookupTable_1 = ts.createMap(); + for (var _i = 0, _a = exportStars.declarations; _i < _a.length; _i++) { + var node = _a[_i]; + var resolvedModule = resolveExternalModuleName(node, node.moduleSpecifier); + var exportedSymbols = visit(resolvedModule); + extendExportSymbols(nestedSymbols, exportedSymbols, lookupTable_1, node); + } + lookupTable_1.forEach(function (_a, id) { + var exportsWithDuplicate = _a.exportsWithDuplicate; + if (id === "export=" || !(exportsWithDuplicate && exportsWithDuplicate.length) || symbols.has(id)) { + return; + } + for (var _i = 0, exportsWithDuplicate_1 = exportsWithDuplicate; _i < exportsWithDuplicate_1.length; _i++) { + var node = exportsWithDuplicate_1[_i]; + diagnostics.add(ts.createDiagnosticForNode(node, ts.Diagnostics.Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambiguity, lookupTable_1.get(id).specifierText, ts.unescapeLeadingUnderscores(id))); + } + }); + extendExportSymbols(symbols, nestedSymbols); + } + return symbols; + } + } + function getMergedSymbol(symbol) { + var merged; + return symbol && symbol.mergeId && (merged = mergedSymbols[symbol.mergeId]) ? merged : symbol; + } + function getSymbolOfNode(node) { + return getMergedSymbol(node.symbol && getLateBoundSymbol(node.symbol)); + } + function getParentOfSymbol(symbol) { + return getMergedSymbol(symbol.parent && getLateBoundSymbol(symbol.parent)); + } + function getAlternativeContainingModules(symbol, enclosingDeclaration) { + var containingFile = ts.getSourceFileOfNode(enclosingDeclaration); + var id = "" + getNodeId(containingFile); + var links = getSymbolLinks(symbol); + var results; + if (links.extendedContainersByFile && (results = links.extendedContainersByFile.get(id))) { + return results; + } + if (containingFile && containingFile.imports) { + for (var _i = 0, _a = containingFile.imports; _i < _a.length; _i++) { + var importRef = _a[_i]; + if (ts.nodeIsSynthesized(importRef)) + continue; + var resolvedModule = resolveExternalModuleName(enclosingDeclaration, importRef, true); + if (!resolvedModule) + continue; + var ref = getAliasForSymbolInContainer(resolvedModule, symbol); + if (!ref) + continue; + results = ts.append(results, resolvedModule); + } + if (ts.length(results)) { + (links.extendedContainersByFile || (links.extendedContainersByFile = ts.createMap())).set(id, results); + return results; + } + } + if (links.extendedContainers) { + return links.extendedContainers; + } + var otherFiles = host.getSourceFiles(); + for (var _b = 0, otherFiles_1 = otherFiles; _b < otherFiles_1.length; _b++) { + var file = otherFiles_1[_b]; + if (!ts.isExternalModule(file)) + continue; + var sym = getSymbolOfNode(file); + var ref = getAliasForSymbolInContainer(sym, symbol); + if (!ref) + continue; + results = ts.append(results, sym); + } + return links.extendedContainers = results || ts.emptyArray; + } + function getContainersOfSymbol(symbol, enclosingDeclaration) { + var container = getParentOfSymbol(symbol); + if (container) { + var additionalContainers = ts.mapDefined(container.declarations, fileSymbolIfFileSymbolExportEqualsContainer); + var reexportContainers = enclosingDeclaration && getAlternativeContainingModules(symbol, enclosingDeclaration); + if (enclosingDeclaration && getAccessibleSymbolChain(container, enclosingDeclaration, 1920, false)) { + return ts.concatenate(ts.concatenate([container], additionalContainers), reexportContainers); + } + var res = ts.append(additionalContainers, container); + return ts.concatenate(res, reexportContainers); + } + var candidates = ts.mapDefined(symbol.declarations, function (d) { return !ts.isAmbientModule(d) && d.parent && hasNonGlobalAugmentationExternalModuleSymbol(d.parent) ? getSymbolOfNode(d.parent) : undefined; }); + if (!ts.length(candidates)) { + return undefined; + } + return ts.mapDefined(candidates, function (candidate) { return getAliasForSymbolInContainer(candidate, symbol) ? candidate : undefined; }); + function fileSymbolIfFileSymbolExportEqualsContainer(d) { + var fileSymbol = getExternalModuleContainer(d); + var exported = fileSymbol && fileSymbol.exports && fileSymbol.exports.get("export="); + return resolveSymbol(exported) === resolveSymbol(container) ? fileSymbol : undefined; + } + } + function getAliasForSymbolInContainer(container, symbol) { + if (container === getParentOfSymbol(symbol)) { + return symbol; + } + var exports = getExportsOfSymbol(container); + var quick = exports.get(symbol.escapedName); + if (quick && symbolRefersToTarget(quick)) { + return quick; + } + return ts.forEachEntry(exports, function (exported) { + if (symbolRefersToTarget(exported)) { + return exported; + } + }); + function symbolRefersToTarget(s) { + if (s === symbol || resolveSymbol(s) === symbol || resolveSymbol(s) === resolveSymbol(symbol)) { + return s; + } + } + } + function getExportSymbolOfValueSymbolIfExported(symbol) { + return getMergedSymbol(symbol && (symbol.flags & 1048576) !== 0 ? symbol.exportSymbol : symbol); + } + function symbolIsValue(symbol) { + return !!(symbol.flags & 67220415 || symbol.flags & 2097152 && resolveAlias(symbol).flags & 67220415); + } + function findConstructorDeclaration(node) { + var members = node.members; + for (var _i = 0, members_2 = members; _i < members_2.length; _i++) { + var member = members_2[_i]; + if (member.kind === 157 && ts.nodeIsPresent(member.body)) { + return member; + } + } + } + function createType(flags) { + var result = new Type(checker, flags); + typeCount++; + result.id = typeCount; + return result; + } + function createIntrinsicType(kind, intrinsicName) { + var type = createType(kind); + type.intrinsicName = intrinsicName; + return type; + } + function createBooleanType(trueFalseTypes) { + var type = getUnionType(trueFalseTypes); + type.flags |= 16; + type.intrinsicName = "boolean"; + return type; + } + function createObjectType(objectFlags, symbol) { + var type = createType(524288); + type.objectFlags = objectFlags; + type.symbol = symbol; + type.members = undefined; + type.properties = undefined; + type.callSignatures = undefined; + type.constructSignatures = undefined; + type.stringIndexInfo = undefined; + type.numberIndexInfo = undefined; + return type; + } + function createTypeofType() { + return getUnionType(ts.arrayFrom(typeofEQFacts.keys(), getLiteralType)); + } + function isReservedMemberName(name) { + return name.charCodeAt(0) === 95 && + name.charCodeAt(1) === 95 && + name.charCodeAt(2) !== 95 && + name.charCodeAt(2) !== 64; + } + function getNamedMembers(members) { + var result; + members.forEach(function (symbol, id) { + if (!isReservedMemberName(id) && symbolIsValue(symbol)) { + (result || (result = [])).push(symbol); + } + }); + return result || ts.emptyArray; + } + function setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo) { + type.members = members; + type.properties = members === emptySymbols ? ts.emptyArray : getNamedMembers(members); + type.callSignatures = callSignatures; + type.constructSignatures = constructSignatures; + type.stringIndexInfo = stringIndexInfo; + type.numberIndexInfo = numberIndexInfo; + return type; + } + function createAnonymousType(symbol, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo) { + return setStructuredTypeMembers(createObjectType(16, symbol), members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + } + function forEachSymbolTableInScope(enclosingDeclaration, callback) { + var result; + for (var location = enclosingDeclaration; location; location = location.parent) { + if (location.locals && !isGlobalSourceFile(location)) { + if (result = callback(location.locals)) { + return result; + } + } + switch (location.kind) { + case 279: + if (!ts.isExternalOrCommonJsModule(location)) { + break; + } + case 244: + if (result = callback(getSymbolOfNode(location).exports)) { + return result; + } + break; + } + } + return callback(globals); + } + function getQualifiedLeftMeaning(rightMeaning) { + return rightMeaning === 67220415 ? 67220415 : 1920; + } + function getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, useOnlyExternalAliasing, visitedSymbolTablesMap) { + if (visitedSymbolTablesMap === void 0) { visitedSymbolTablesMap = ts.createMap(); } + if (!(symbol && !isPropertyOrMethodDeclarationSymbol(symbol))) { + return undefined; + } + var id = "" + getSymbolId(symbol); + var visitedSymbolTables = visitedSymbolTablesMap.get(id); + if (!visitedSymbolTables) { + visitedSymbolTablesMap.set(id, visitedSymbolTables = []); + } + return forEachSymbolTableInScope(enclosingDeclaration, getAccessibleSymbolChainFromSymbolTable); + function getAccessibleSymbolChainFromSymbolTable(symbols, ignoreQualification) { + if (!ts.pushIfUnique(visitedSymbolTables, symbols)) { + return undefined; + } + var result = trySymbolTable(symbols, ignoreQualification); + visitedSymbolTables.pop(); + return result; + } + function canQualifySymbol(symbolFromSymbolTable, meaning) { + return !needsQualification(symbolFromSymbolTable, enclosingDeclaration, meaning) || + !!getAccessibleSymbolChain(symbolFromSymbolTable.parent, enclosingDeclaration, getQualifiedLeftMeaning(meaning), useOnlyExternalAliasing, visitedSymbolTablesMap); + } + function isAccessible(symbolFromSymbolTable, resolvedAliasSymbol, ignoreQualification) { + return symbol === (resolvedAliasSymbol || symbolFromSymbolTable) && + !ts.some(symbolFromSymbolTable.declarations, hasNonGlobalAugmentationExternalModuleSymbol) && + (ignoreQualification || canQualifySymbol(symbolFromSymbolTable, meaning)); + } + function trySymbolTable(symbols, ignoreQualification) { + if (isAccessible(symbols.get(symbol.escapedName), undefined, ignoreQualification)) { + return [symbol]; + } + return ts.forEachEntry(symbols, function (symbolFromSymbolTable) { + if (symbolFromSymbolTable.flags & 2097152 + && symbolFromSymbolTable.escapedName !== "export=" + && symbolFromSymbolTable.escapedName !== "default" + && !(ts.isUMDExportSymbol(symbolFromSymbolTable) && enclosingDeclaration && ts.isExternalModule(ts.getSourceFileOfNode(enclosingDeclaration))) + && (!useOnlyExternalAliasing || ts.some(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration)) + && (ignoreQualification || !ts.getDeclarationOfKind(symbolFromSymbolTable, 257))) { + var resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable); + if (isAccessible(symbolFromSymbolTable, resolvedImportedSymbol, ignoreQualification)) { + return [symbolFromSymbolTable]; + } + var candidateTable = getExportsOfSymbol(resolvedImportedSymbol); + var accessibleSymbolsFromExports = candidateTable && getAccessibleSymbolChainFromSymbolTable(candidateTable, true); + if (accessibleSymbolsFromExports && canQualifySymbol(symbolFromSymbolTable, getQualifiedLeftMeaning(meaning))) { + return [symbolFromSymbolTable].concat(accessibleSymbolsFromExports); + } + } + if (symbolFromSymbolTable.escapedName === symbol.escapedName && symbolFromSymbolTable.exportSymbol) { + if (isAccessible(getMergedSymbol(symbolFromSymbolTable.exportSymbol), undefined, ignoreQualification)) { + return [symbol]; + } + } + }); + } + } + function needsQualification(symbol, enclosingDeclaration, meaning) { + var qualify = false; + forEachSymbolTableInScope(enclosingDeclaration, function (symbolTable) { + var symbolFromSymbolTable = getMergedSymbol(symbolTable.get(symbol.escapedName)); + if (!symbolFromSymbolTable) { + return false; + } + if (symbolFromSymbolTable === symbol) { + return true; + } + symbolFromSymbolTable = (symbolFromSymbolTable.flags & 2097152 && !ts.getDeclarationOfKind(symbolFromSymbolTable, 257)) ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable; + if (symbolFromSymbolTable.flags & meaning) { + qualify = true; + return true; + } + return false; + }); + return qualify; + } + function isPropertyOrMethodDeclarationSymbol(symbol) { + if (symbol.declarations && symbol.declarations.length) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + switch (declaration.kind) { + case 154: + case 156: + case 158: + case 159: + continue; + default: + return false; + } + } + return true; + } + return false; + } + function isTypeSymbolAccessible(typeSymbol, enclosingDeclaration) { + var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67897832, false); + return access.accessibility === 0; + } + function isValueSymbolAccessible(typeSymbol, enclosingDeclaration) { + var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67220415, false); + return access.accessibility === 0; + } + function isAnySymbolAccessible(symbols, enclosingDeclaration, initialSymbol, meaning, shouldComputeAliasesToMakeVisible) { + if (!ts.length(symbols)) + return; + var hadAccessibleChain; + for (var _i = 0, _a = symbols; _i < _a.length; _i++) { + var symbol = _a[_i]; + var accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, false); + if (accessibleSymbolChain) { + hadAccessibleChain = symbol; + var hasAccessibleDeclarations = hasVisibleDeclarations(accessibleSymbolChain[0], shouldComputeAliasesToMakeVisible); + if (hasAccessibleDeclarations) { + return hasAccessibleDeclarations; + } + } + else { + if (ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { + return { + accessibility: 0 + }; + } + } + var containers = getContainersOfSymbol(symbol, enclosingDeclaration); + var firstDecl = ts.first(symbol.declarations); + if (!ts.length(containers) && meaning & 67220415 && firstDecl && ts.isObjectLiteralExpression(firstDecl)) { + if (firstDecl.parent && ts.isVariableDeclaration(firstDecl.parent) && firstDecl === firstDecl.parent.initializer) { + containers = [getSymbolOfNode(firstDecl.parent)]; + } + } + var parentResult = isAnySymbolAccessible(containers, enclosingDeclaration, initialSymbol, initialSymbol === symbol ? getQualifiedLeftMeaning(meaning) : meaning, shouldComputeAliasesToMakeVisible); + if (parentResult) { + return parentResult; + } + } + if (hadAccessibleChain) { + return { + accessibility: 1, + errorSymbolName: symbolToString(initialSymbol, enclosingDeclaration, meaning), + errorModuleName: hadAccessibleChain !== initialSymbol ? symbolToString(hadAccessibleChain, enclosingDeclaration, 1920) : undefined, + }; + } + } + function isSymbolAccessible(symbol, enclosingDeclaration, meaning, shouldComputeAliasesToMakeVisible) { + if (symbol && enclosingDeclaration) { + var result = isAnySymbolAccessible([symbol], enclosingDeclaration, symbol, meaning, shouldComputeAliasesToMakeVisible); + if (result) { + return result; + } + var symbolExternalModule = ts.forEach(symbol.declarations, getExternalModuleContainer); + if (symbolExternalModule) { + var enclosingExternalModule = getExternalModuleContainer(enclosingDeclaration); + if (symbolExternalModule !== enclosingExternalModule) { + return { + accessibility: 2, + errorSymbolName: symbolToString(symbol, enclosingDeclaration, meaning), + errorModuleName: symbolToString(symbolExternalModule) + }; + } + } + return { + accessibility: 1, + errorSymbolName: symbolToString(symbol, enclosingDeclaration, meaning), + }; + } + return { accessibility: 0 }; + } + function getExternalModuleContainer(declaration) { + var node = ts.findAncestor(declaration, hasExternalModuleSymbol); + return node && getSymbolOfNode(node); + } + function hasExternalModuleSymbol(declaration) { + return ts.isAmbientModule(declaration) || (declaration.kind === 279 && ts.isExternalOrCommonJsModule(declaration)); + } + function hasNonGlobalAugmentationExternalModuleSymbol(declaration) { + return ts.isModuleWithStringLiteralName(declaration) || (declaration.kind === 279 && ts.isExternalOrCommonJsModule(declaration)); + } + function hasVisibleDeclarations(symbol, shouldComputeAliasToMakeVisible) { + var aliasesToMakeVisible; + if (!ts.every(symbol.declarations, getIsDeclarationVisible)) { + return undefined; + } + return { accessibility: 0, aliasesToMakeVisible: aliasesToMakeVisible }; + function getIsDeclarationVisible(declaration) { + if (!isDeclarationVisible(declaration)) { + var anyImportSyntax = getAnyImportSyntax(declaration); + if (anyImportSyntax && + !ts.hasModifier(anyImportSyntax, 1) && + isDeclarationVisible(anyImportSyntax.parent)) { + return addVisibleAlias(declaration, anyImportSyntax); + } + else if (ts.isVariableDeclaration(declaration) && ts.isVariableStatement(declaration.parent.parent) && + !ts.hasModifier(declaration.parent.parent, 1) && + isDeclarationVisible(declaration.parent.parent.parent)) { + return addVisibleAlias(declaration, declaration.parent.parent); + } + else if (ts.isLateVisibilityPaintedStatement(declaration) + && !ts.hasModifier(declaration, 1) + && isDeclarationVisible(declaration.parent)) { + return addVisibleAlias(declaration, declaration); + } + return false; + } + return true; + } + function addVisibleAlias(declaration, aliasingStatement) { + if (shouldComputeAliasToMakeVisible) { + getNodeLinks(declaration).isVisible = true; + aliasesToMakeVisible = ts.appendIfUnique(aliasesToMakeVisible, aliasingStatement); + } + return true; + } + } + function isEntityNameVisible(entityName, enclosingDeclaration) { + var meaning; + if (entityName.parent.kind === 167 || + ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent) || + entityName.parent.kind === 149) { + meaning = 67220415 | 1048576; + } + else if (entityName.kind === 148 || entityName.kind === 189 || + entityName.parent.kind === 248) { + meaning = 1920; + } + else { + meaning = 67897832; + } + var firstIdentifier = getFirstIdentifier(entityName); + var symbol = resolveName(enclosingDeclaration, firstIdentifier.escapedText, meaning, undefined, undefined, false); + return (symbol && hasVisibleDeclarations(symbol, true)) || { + accessibility: 1, + errorSymbolName: ts.getTextOfNode(firstIdentifier), + errorNode: firstIdentifier + }; + } + function symbolToString(symbol, enclosingDeclaration, meaning, flags, writer) { + if (flags === void 0) { flags = 4; } + var nodeFlags = 70221824; + if (flags & 2) { + nodeFlags |= 128; + } + if (flags & 1) { + nodeFlags |= 512; + } + if (flags & 8) { + nodeFlags |= 16384; + } + if (flags & 16) { + nodeFlags |= 134217728; + } + var builder = flags & 4 ? nodeBuilder.symbolToExpression : nodeBuilder.symbolToEntityName; + return writer ? symbolToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(symbolToStringWorker); + function symbolToStringWorker(writer) { + var entity = builder(symbol, meaning, enclosingDeclaration, nodeFlags); + var printer = ts.createPrinter({ removeComments: true }); + var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); + printer.writeNode(4, entity, sourceFile, writer); + return writer; + } + } + function signatureToString(signature, enclosingDeclaration, flags, kind, writer) { + if (flags === void 0) { flags = 0; } + return writer ? signatureToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(signatureToStringWorker); + function signatureToStringWorker(writer) { + var sigOutput; + if (flags & 262144) { + sigOutput = kind === 1 ? 166 : 165; + } + else { + sigOutput = kind === 1 ? 161 : 160; + } + var sig = nodeBuilder.signatureToSignatureDeclaration(signature, sigOutput, enclosingDeclaration, toNodeBuilderFlags(flags) | 70221824 | 512); + var printer = ts.createPrinter({ removeComments: true, omitTrailingSemicolon: true }); + var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); + printer.writeNode(4, sig, sourceFile, ts.getTrailingSemicolonOmittingWriter(writer)); + return writer; + } + } + function typeToString(type, enclosingDeclaration, flags, writer) { + if (flags === void 0) { flags = 1048576 | 16384; } + if (writer === void 0) { writer = ts.createTextWriter(""); } + var noTruncation = compilerOptions.noErrorTruncation || flags & 1; + var typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, toNodeBuilderFlags(flags) | 70221824 | (noTruncation ? 1 : 0), writer); + if (typeNode === undefined) + return ts.Debug.fail("should always get typenode"); + var options = { removeComments: true }; + var printer = ts.createPrinter(options); + var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); + printer.writeNode(4, typeNode, sourceFile, writer); + var result = writer.getText(); + var maxLength = noTruncation ? undefined : ts.defaultMaximumTruncationLength * 2; + if (maxLength && result && result.length >= maxLength) { + return result.substr(0, maxLength - "...".length) + "..."; + } + return result; + } + function toNodeBuilderFlags(flags) { + if (flags === void 0) { flags = 0; } + return flags & 9469291; + } + function createNodeBuilder() { + return { + typeToTypeNode: function (type, enclosingDeclaration, flags, tracker) { + return withContext(enclosingDeclaration, flags, tracker, function (context) { return typeToTypeNodeHelper(type, context); }); + }, + indexInfoToIndexSignatureDeclaration: function (indexInfo, kind, enclosingDeclaration, flags, tracker) { + return withContext(enclosingDeclaration, flags, tracker, function (context) { return indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind, context); }); + }, + signatureToSignatureDeclaration: function (signature, kind, enclosingDeclaration, flags, tracker) { + return withContext(enclosingDeclaration, flags, tracker, function (context) { return signatureToSignatureDeclarationHelper(signature, kind, context); }); + }, + symbolToEntityName: function (symbol, meaning, enclosingDeclaration, flags, tracker) { + return withContext(enclosingDeclaration, flags, tracker, function (context) { return symbolToName(symbol, context, meaning, false); }); + }, + symbolToExpression: function (symbol, meaning, enclosingDeclaration, flags, tracker) { + return withContext(enclosingDeclaration, flags, tracker, function (context) { return symbolToExpression(symbol, context, meaning); }); + }, + symbolToTypeParameterDeclarations: function (symbol, enclosingDeclaration, flags, tracker) { + return withContext(enclosingDeclaration, flags, tracker, function (context) { return typeParametersToTypeParameterDeclarations(symbol, context); }); + }, + symbolToParameterDeclaration: function (symbol, enclosingDeclaration, flags, tracker) { + return withContext(enclosingDeclaration, flags, tracker, function (context) { return symbolToParameterDeclaration(symbol, context); }); + }, + typeParameterToDeclaration: function (parameter, enclosingDeclaration, flags, tracker) { + return withContext(enclosingDeclaration, flags, tracker, function (context) { return typeParameterToDeclaration(parameter, context); }); + }, + }; + function withContext(enclosingDeclaration, flags, tracker, cb) { + ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8) === 0); + var context = { + enclosingDeclaration: enclosingDeclaration, + flags: flags || 0, + tracker: tracker && tracker.trackSymbol ? tracker : { trackSymbol: ts.noop, moduleResolverHost: flags & 134217728 ? { + getCommonSourceDirectory: host.getCommonSourceDirectory ? function () { return host.getCommonSourceDirectory(); } : function () { return ""; }, + getSourceFiles: function () { return host.getSourceFiles(); }, + getCurrentDirectory: host.getCurrentDirectory && (function () { return host.getCurrentDirectory(); }) + } : undefined }, + encounteredError: false, + visitedTypes: undefined, + symbolDepth: undefined, + inferTypeParameters: undefined, + approximateLength: 0 + }; + var resultingNode = cb(context); + return context.encounteredError ? undefined : resultingNode; + } + function checkTruncationLength(context) { + if (context.truncating) + return context.truncating; + return context.truncating = !(context.flags & 1) && context.approximateLength > ts.defaultMaximumTruncationLength; + } + function typeToTypeNodeHelper(type, context) { + if (cancellationToken && cancellationToken.throwIfCancellationRequested) { + cancellationToken.throwIfCancellationRequested(); + } + var inTypeAlias = context.flags & 8388608; + context.flags &= ~8388608; + if (!type) { + context.encounteredError = true; + return undefined; + } + if (type.flags & 1) { + context.approximateLength += 3; + return ts.createKeywordTypeNode(120); + } + if (type.flags & 2) { + return ts.createKeywordTypeNode(143); + } + if (type.flags & 4) { + context.approximateLength += 6; + return ts.createKeywordTypeNode(138); + } + if (type.flags & 8) { + context.approximateLength += 6; + return ts.createKeywordTypeNode(135); + } + if (type.flags & 64) { + context.approximateLength += 6; + return ts.createKeywordTypeNode(146); + } + if (type.flags & 16) { + context.approximateLength += 7; + return ts.createKeywordTypeNode(123); + } + if (type.flags & 1024 && !(type.flags & 1048576)) { + var parentSymbol = getParentOfSymbol(type.symbol); + var parentName = symbolToTypeNode(parentSymbol, context, 67897832); + var enumLiteralName = getDeclaredTypeOfSymbol(parentSymbol) === type + ? parentName + : appendReferenceToType(parentName, ts.createTypeReferenceNode(ts.symbolName(type.symbol), undefined)); + return enumLiteralName; + } + if (type.flags & 1056) { + return symbolToTypeNode(type.symbol, context, 67897832); + } + if (type.flags & 128) { + context.approximateLength += (type.value.length + 2); + return ts.createLiteralTypeNode(ts.setEmitFlags(ts.createLiteral(type.value), 16777216)); + } + if (type.flags & 256) { + context.approximateLength += (("" + type.value).length); + return ts.createLiteralTypeNode((ts.createLiteral(type.value))); + } + if (type.flags & 2048) { + context.approximateLength += (ts.pseudoBigIntToString(type.value).length) + 1; + return ts.createLiteralTypeNode((ts.createLiteral(type.value))); + } + if (type.flags & 512) { + context.approximateLength += type.intrinsicName.length; + return type.intrinsicName === "true" ? ts.createTrue() : ts.createFalse(); + } + if (type.flags & 8192) { + if (!(context.flags & 1048576)) { + if (isValueSymbolAccessible(type.symbol, context.enclosingDeclaration)) { + context.approximateLength += 6; + return symbolToTypeNode(type.symbol, context, 67220415); + } + if (context.tracker.reportInaccessibleUniqueSymbolError) { + context.tracker.reportInaccessibleUniqueSymbolError(); + } + } + context.approximateLength += 13; + return ts.createTypeOperatorNode(142, ts.createKeywordTypeNode(139)); + } + if (type.flags & 16384) { + context.approximateLength += 4; + return ts.createKeywordTypeNode(106); + } + if (type.flags & 32768) { + context.approximateLength += 9; + return ts.createKeywordTypeNode(141); + } + if (type.flags & 65536) { + context.approximateLength += 4; + return ts.createKeywordTypeNode(96); + } + if (type.flags & 131072) { + context.approximateLength += 5; + return ts.createKeywordTypeNode(132); + } + if (type.flags & 4096) { + context.approximateLength += 6; + return ts.createKeywordTypeNode(139); + } + if (type.flags & 67108864) { + context.approximateLength += 6; + return ts.createKeywordTypeNode(136); + } + if (type.flags & 262144 && type.isThisType) { + if (context.flags & 4194304) { + if (!context.encounteredError && !(context.flags & 32768)) { + context.encounteredError = true; + } + if (context.tracker.reportInaccessibleThisError) { + context.tracker.reportInaccessibleThisError(); + } + } + context.approximateLength += 4; + return ts.createThis(); + } + var objectFlags = ts.getObjectFlags(type); + if (objectFlags & 4) { + ts.Debug.assert(!!(type.flags & 524288)); + return typeReferenceToTypeNode(type); + } + if (type.flags & 262144 || objectFlags & 3) { + if (type.flags & 262144 && ts.contains(context.inferTypeParameters, type)) { + context.approximateLength += (ts.symbolName(type.symbol).length + 6); + return ts.createInferTypeNode(typeParameterToDeclarationWithConstraint(type, context, undefined)); + } + if (context.flags & 4 && + type.flags & 262144 && + ts.length(type.symbol.declarations) && + ts.isTypeParameterDeclaration(type.symbol.declarations[0]) && + typeParameterShadowsNameInScope(type, context) && + !isTypeSymbolAccessible(type.symbol, context.enclosingDeclaration)) { + var name = type.symbol.declarations[0].name; + context.approximateLength += ts.idText(name).length; + return ts.createTypeReferenceNode(ts.getGeneratedNameForNode(name, 16 | 8), undefined); + } + return type.symbol + ? symbolToTypeNode(type.symbol, context, 67897832) + : ts.createTypeReferenceNode(ts.createIdentifier("?"), undefined); + } + if (!inTypeAlias && type.aliasSymbol && (context.flags & 16384 || isTypeSymbolAccessible(type.aliasSymbol, context.enclosingDeclaration))) { + var typeArgumentNodes = mapToTypeNodes(type.aliasTypeArguments, context); + if (isReservedMemberName(type.aliasSymbol.escapedName) && !(type.aliasSymbol.flags & 32)) + return ts.createTypeReferenceNode(ts.createIdentifier(""), typeArgumentNodes); + return symbolToTypeNode(type.aliasSymbol, context, 67897832, typeArgumentNodes); + } + if (type.flags & (1048576 | 2097152)) { + var types = type.flags & 1048576 ? formatUnionTypes(type.types) : type.types; + if (ts.length(types) === 1) { + return typeToTypeNodeHelper(types[0], context); + } + var typeNodes = mapToTypeNodes(types, context, true); + if (typeNodes && typeNodes.length > 0) { + var unionOrIntersectionTypeNode = ts.createUnionOrIntersectionTypeNode(type.flags & 1048576 ? 173 : 174, typeNodes); + return unionOrIntersectionTypeNode; + } + else { + if (!context.encounteredError && !(context.flags & 262144)) { + context.encounteredError = true; + } + return undefined; + } + } + if (objectFlags & (16 | 32)) { + ts.Debug.assert(!!(type.flags & 524288)); + return createAnonymousTypeNode(type); + } + if (type.flags & 4194304) { + var indexedType = type.type; + context.approximateLength += 6; + var indexTypeNode = typeToTypeNodeHelper(indexedType, context); + return ts.createTypeOperatorNode(indexTypeNode); + } + if (type.flags & 8388608) { + var objectTypeNode = typeToTypeNodeHelper(type.objectType, context); + var indexTypeNode = typeToTypeNodeHelper(type.indexType, context); + context.approximateLength += 2; + return ts.createIndexedAccessTypeNode(objectTypeNode, indexTypeNode); + } + if (type.flags & 16777216) { + var checkTypeNode = typeToTypeNodeHelper(type.checkType, context); + var saveInferTypeParameters = context.inferTypeParameters; + context.inferTypeParameters = type.root.inferTypeParameters; + var extendsTypeNode = typeToTypeNodeHelper(type.extendsType, context); + context.inferTypeParameters = saveInferTypeParameters; + var trueTypeNode = typeToTypeNodeHelper(getTrueTypeFromConditionalType(type), context); + var falseTypeNode = typeToTypeNodeHelper(getFalseTypeFromConditionalType(type), context); + context.approximateLength += 15; + return ts.createConditionalTypeNode(checkTypeNode, extendsTypeNode, trueTypeNode, falseTypeNode); + } + if (type.flags & 33554432) { + return typeToTypeNodeHelper(type.typeVariable, context); + } + return ts.Debug.fail("Should be unreachable."); + function createMappedTypeNodeFromType(type) { + ts.Debug.assert(!!(type.flags & 524288)); + var readonlyToken = type.declaration.readonlyToken ? ts.createToken(type.declaration.readonlyToken.kind) : undefined; + var questionToken = type.declaration.questionToken ? ts.createToken(type.declaration.questionToken.kind) : undefined; + var appropriateConstraintTypeNode; + if (isMappedTypeWithKeyofConstraintDeclaration(type)) { + appropriateConstraintTypeNode = ts.createTypeOperatorNode(typeToTypeNodeHelper(getModifiersTypeFromMappedType(type), context)); + } + else { + appropriateConstraintTypeNode = typeToTypeNodeHelper(getConstraintTypeFromMappedType(type), context); + } + var typeParameterNode = typeParameterToDeclarationWithConstraint(getTypeParameterFromMappedType(type), context, appropriateConstraintTypeNode); + var templateTypeNode = typeToTypeNodeHelper(getTemplateTypeFromMappedType(type), context); + var mappedTypeNode = ts.createMappedTypeNode(readonlyToken, typeParameterNode, questionToken, templateTypeNode); + context.approximateLength += 10; + return ts.setEmitFlags(mappedTypeNode, 1); + } + function createAnonymousTypeNode(type) { + var typeId = "" + type.id; + var symbol = type.symbol; + var id; + if (symbol) { + var isConstructorObject = ts.getObjectFlags(type) & 16 && type.symbol && type.symbol.flags & 32; + id = (isConstructorObject ? "+" : "") + getSymbolId(symbol); + if (isJSConstructor(symbol.valueDeclaration)) { + var isInstanceType = type === getInferredClassType(symbol) ? 67897832 : 67220415; + return symbolToTypeNode(symbol, context, isInstanceType); + } + else if (symbol.flags & 32 && !getBaseTypeVariableOfClass(symbol) && !(symbol.valueDeclaration.kind === 209 && context.flags & 2048) || + symbol.flags & (384 | 512) || + shouldWriteTypeOfFunctionSymbol()) { + return symbolToTypeNode(symbol, context, 67220415); + } + else if (context.visitedTypes && context.visitedTypes.has(typeId)) { + var typeAlias = getTypeAliasForTypeLiteral(type); + if (typeAlias) { + return symbolToTypeNode(typeAlias, context, 67897832); + } + else { + return createElidedInformationPlaceholder(context); + } + } + else { + if (!context.visitedTypes) { + context.visitedTypes = ts.createMap(); + } + if (!context.symbolDepth) { + context.symbolDepth = ts.createMap(); + } + var depth = context.symbolDepth.get(id) || 0; + if (depth > 10) { + return createElidedInformationPlaceholder(context); + } + context.symbolDepth.set(id, depth + 1); + context.visitedTypes.set(typeId, true); + var result = createTypeNodeFromObjectType(type); + context.visitedTypes.delete(typeId); + context.symbolDepth.set(id, depth); + return result; + } + } + else { + return createTypeNodeFromObjectType(type); + } + function shouldWriteTypeOfFunctionSymbol() { + var isStaticMethodSymbol = !!(symbol.flags & 8192) && + ts.some(symbol.declarations, function (declaration) { return ts.hasModifier(declaration, 32); }); + var isNonLocalFunctionSymbol = !!(symbol.flags & 16) && + (symbol.parent || + ts.forEach(symbol.declarations, function (declaration) { + return declaration.parent.kind === 279 || declaration.parent.kind === 245; + })); + if (isStaticMethodSymbol || isNonLocalFunctionSymbol) { + return (!!(context.flags & 4096) || (context.visitedTypes && context.visitedTypes.has(typeId))) && + (!(context.flags & 8) || isValueSymbolAccessible(symbol, context.enclosingDeclaration)); + } + } + } + function createTypeNodeFromObjectType(type) { + if (isGenericMappedType(type)) { + return createMappedTypeNodeFromType(type); + } + var resolved = resolveStructuredTypeMembers(type); + if (!resolved.properties.length && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { + if (!resolved.callSignatures.length && !resolved.constructSignatures.length) { + context.approximateLength += 2; + return ts.setEmitFlags(ts.createTypeLiteralNode(undefined), 1); + } + if (resolved.callSignatures.length === 1 && !resolved.constructSignatures.length) { + var signature = resolved.callSignatures[0]; + var signatureNode = signatureToSignatureDeclarationHelper(signature, 165, context); + return signatureNode; + } + if (resolved.constructSignatures.length === 1 && !resolved.callSignatures.length) { + var signature = resolved.constructSignatures[0]; + var signatureNode = signatureToSignatureDeclarationHelper(signature, 166, context); + return signatureNode; + } + } + var savedFlags = context.flags; + context.flags |= 4194304; + var members = createTypeNodesFromResolvedType(resolved); + context.flags = savedFlags; + var typeLiteralNode = ts.createTypeLiteralNode(members); + context.approximateLength += 2; + return ts.setEmitFlags(typeLiteralNode, (context.flags & 1024) ? 0 : 1); + } + function typeReferenceToTypeNode(type) { + var typeArguments = type.typeArguments || ts.emptyArray; + if (type.target === globalArrayType) { + if (context.flags & 2) { + var typeArgumentNode = typeToTypeNodeHelper(typeArguments[0], context); + return ts.createTypeReferenceNode("Array", [typeArgumentNode]); + } + var elementType = typeToTypeNodeHelper(typeArguments[0], context); + return ts.createArrayTypeNode(elementType); + } + else if (type.target.objectFlags & 8) { + if (typeArguments.length > 0) { + var arity = getTypeReferenceArity(type); + var tupleConstituentNodes = mapToTypeNodes(typeArguments.slice(0, arity), context); + var hasRestElement = type.target.hasRestElement; + if (tupleConstituentNodes) { + for (var i = type.target.minLength; i < Math.min(arity, tupleConstituentNodes.length); i++) { + tupleConstituentNodes[i] = hasRestElement && i === arity - 1 ? + ts.createRestTypeNode(ts.createArrayTypeNode(tupleConstituentNodes[i])) : + ts.createOptionalTypeNode(tupleConstituentNodes[i]); + } + return ts.createTupleTypeNode(tupleConstituentNodes); + } + } + if (context.encounteredError || (context.flags & 524288)) { + return ts.createTupleTypeNode([]); + } + context.encounteredError = true; + return undefined; + } + else if (context.flags & 2048 && + type.symbol.valueDeclaration && + ts.isClassLike(type.symbol.valueDeclaration) && + !isValueSymbolAccessible(type.symbol, context.enclosingDeclaration)) { + return createAnonymousTypeNode(type); + } + else { + var outerTypeParameters = type.target.outerTypeParameters; + var i = 0; + var resultType = void 0; + if (outerTypeParameters) { + var length_1 = outerTypeParameters.length; + while (i < length_1) { + var start = i; + var parent = getParentSymbolOfTypeParameter(outerTypeParameters[i]); + do { + i++; + } while (i < length_1 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent); + if (!ts.rangeEquals(outerTypeParameters, typeArguments, start, i)) { + var typeArgumentSlice = mapToTypeNodes(typeArguments.slice(start, i), context); + var flags_2 = context.flags; + context.flags |= 16; + var ref = symbolToTypeNode(parent, context, 67897832, typeArgumentSlice); + context.flags = flags_2; + resultType = !resultType ? ref : appendReferenceToType(resultType, ref); + } + } + } + var typeArgumentNodes = void 0; + if (typeArguments.length > 0) { + var typeParameterCount = (type.target.typeParameters || ts.emptyArray).length; + typeArgumentNodes = mapToTypeNodes(typeArguments.slice(i, typeParameterCount), context); + } + var flags = context.flags; + context.flags |= 16; + var finalRef = symbolToTypeNode(type.symbol, context, 67897832, typeArgumentNodes); + context.flags = flags; + return !resultType ? finalRef : appendReferenceToType(resultType, finalRef); + } + } + function appendReferenceToType(root, ref) { + if (ts.isImportTypeNode(root)) { + var innerParams = root.typeArguments; + if (root.qualifier) { + (ts.isIdentifier(root.qualifier) ? root.qualifier : root.qualifier.right).typeArguments = innerParams; + } + root.typeArguments = ref.typeArguments; + var ids = getAccessStack(ref); + for (var _i = 0, ids_1 = ids; _i < ids_1.length; _i++) { + var id = ids_1[_i]; + root.qualifier = root.qualifier ? ts.createQualifiedName(root.qualifier, id) : id; + } + return root; + } + else { + var innerParams = root.typeArguments; + (ts.isIdentifier(root.typeName) ? root.typeName : root.typeName.right).typeArguments = innerParams; + root.typeArguments = ref.typeArguments; + var ids = getAccessStack(ref); + for (var _a = 0, ids_2 = ids; _a < ids_2.length; _a++) { + var id = ids_2[_a]; + root.typeName = ts.createQualifiedName(root.typeName, id); + } + return root; + } + } + function getAccessStack(ref) { + var state = ref.typeName; + var ids = []; + while (!ts.isIdentifier(state)) { + ids.unshift(state.right); + state = state.left; + } + ids.unshift(state); + return ids; + } + function createTypeNodesFromResolvedType(resolvedType) { + if (checkTruncationLength(context)) { + return [ts.createPropertySignature(undefined, "...", undefined, undefined, undefined)]; + } + var typeElements = []; + for (var _i = 0, _a = resolvedType.callSignatures; _i < _a.length; _i++) { + var signature = _a[_i]; + typeElements.push(signatureToSignatureDeclarationHelper(signature, 160, context)); + } + for (var _b = 0, _c = resolvedType.constructSignatures; _b < _c.length; _b++) { + var signature = _c[_b]; + typeElements.push(signatureToSignatureDeclarationHelper(signature, 161, context)); + } + if (resolvedType.stringIndexInfo) { + var indexSignature = void 0; + if (resolvedType.objectFlags & 2048) { + indexSignature = indexInfoToIndexSignatureDeclarationHelper(createIndexInfo(anyType, resolvedType.stringIndexInfo.isReadonly, resolvedType.stringIndexInfo.declaration), 0, context); + indexSignature.type = createElidedInformationPlaceholder(context); + } + else { + indexSignature = indexInfoToIndexSignatureDeclarationHelper(resolvedType.stringIndexInfo, 0, context); + } + typeElements.push(indexSignature); + } + if (resolvedType.numberIndexInfo) { + typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.numberIndexInfo, 1, context)); + } + var properties = resolvedType.properties; + if (!properties) { + return typeElements; + } + var i = 0; + for (var _d = 0, properties_1 = properties; _d < properties_1.length; _d++) { + var propertySymbol = properties_1[_d]; + i++; + if (context.flags & 2048) { + if (propertySymbol.flags & 4194304) { + continue; + } + if (ts.getDeclarationModifierFlagsFromSymbol(propertySymbol) & (8 | 16) && context.tracker.reportPrivateInBaseOfClassExpression) { + context.tracker.reportPrivateInBaseOfClassExpression(ts.unescapeLeadingUnderscores(propertySymbol.escapedName)); + } + } + if (checkTruncationLength(context) && (i + 2 < properties.length - 1)) { + typeElements.push(ts.createPropertySignature(undefined, "... " + (properties.length - i) + " more ...", undefined, undefined, undefined)); + addPropertyToElementList(properties[properties.length - 1], context, typeElements); + break; + } + addPropertyToElementList(propertySymbol, context, typeElements); + } + return typeElements.length ? typeElements : undefined; + } + } + function createElidedInformationPlaceholder(context) { + context.approximateLength += 3; + if (!(context.flags & 1)) { + return ts.createTypeReferenceNode(ts.createIdentifier("..."), undefined); + } + return ts.createKeywordTypeNode(120); + } + function addPropertyToElementList(propertySymbol, context, typeElements) { + var propertyIsReverseMapped = !!(ts.getCheckFlags(propertySymbol) & 2048); + var propertyType = propertyIsReverseMapped && context.flags & 33554432 ? + anyType : getTypeOfSymbol(propertySymbol); + var saveEnclosingDeclaration = context.enclosingDeclaration; + context.enclosingDeclaration = undefined; + if (context.tracker.trackSymbol && ts.getCheckFlags(propertySymbol) & 1024) { + var decl = ts.first(propertySymbol.declarations); + if (hasLateBindableName(decl)) { + trackComputedName(decl.name, saveEnclosingDeclaration, context); + } + } + var propertyName = symbolToName(propertySymbol, context, 67220415, true); + context.approximateLength += (ts.symbolName(propertySymbol).length + 1); + context.enclosingDeclaration = saveEnclosingDeclaration; + var optionalToken = propertySymbol.flags & 16777216 ? ts.createToken(56) : undefined; + if (propertySymbol.flags & (16 | 8192) && !getPropertiesOfObjectType(propertyType).length) { + var signatures = getSignaturesOfType(propertyType, 0); + for (var _i = 0, signatures_1 = signatures; _i < signatures_1.length; _i++) { + var signature = signatures_1[_i]; + var methodDeclaration = signatureToSignatureDeclarationHelper(signature, 155, context); + methodDeclaration.name = propertyName; + methodDeclaration.questionToken = optionalToken; + if (propertySymbol.valueDeclaration) { + ts.setCommentRange(methodDeclaration, propertySymbol.valueDeclaration); + } + typeElements.push(methodDeclaration); + } + } + else { + var savedFlags = context.flags; + context.flags |= propertyIsReverseMapped ? 33554432 : 0; + var propertyTypeNode = void 0; + if (propertyIsReverseMapped && !!(savedFlags & 33554432)) { + propertyTypeNode = createElidedInformationPlaceholder(context); + } + else { + propertyTypeNode = propertyType ? typeToTypeNodeHelper(propertyType, context) : ts.createKeywordTypeNode(120); + } + context.flags = savedFlags; + var modifiers = isReadonlySymbol(propertySymbol) ? [ts.createToken(133)] : undefined; + if (modifiers) { + context.approximateLength += 9; + } + var propertySignature = ts.createPropertySignature(modifiers, propertyName, optionalToken, propertyTypeNode, undefined); + if (propertySymbol.valueDeclaration) { + ts.setCommentRange(propertySignature, propertySymbol.valueDeclaration); + } + typeElements.push(propertySignature); + } + } + function mapToTypeNodes(types, context, isBareList) { + if (ts.some(types)) { + if (checkTruncationLength(context)) { + if (!isBareList) { + return [ts.createTypeReferenceNode("...", undefined)]; + } + else if (types.length > 2) { + return [ + typeToTypeNodeHelper(types[0], context), + ts.createTypeReferenceNode("... " + (types.length - 2) + " more ...", undefined), + typeToTypeNodeHelper(types[types.length - 1], context) + ]; + } + } + var result = []; + var i = 0; + for (var _i = 0, types_1 = types; _i < types_1.length; _i++) { + var type = types_1[_i]; + i++; + if (checkTruncationLength(context) && (i + 2 < types.length - 1)) { + result.push(ts.createTypeReferenceNode("... " + (types.length - i) + " more ...", undefined)); + var typeNode_1 = typeToTypeNodeHelper(types[types.length - 1], context); + if (typeNode_1) { + result.push(typeNode_1); + } + break; + } + context.approximateLength += 2; + var typeNode = typeToTypeNodeHelper(type, context); + if (typeNode) { + result.push(typeNode); + } + } + return result; + } + } + function indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind, context) { + var name = ts.getNameFromIndexInfo(indexInfo) || "x"; + var indexerTypeNode = ts.createKeywordTypeNode(kind === 0 ? 138 : 135); + var indexingParameter = ts.createParameter(undefined, undefined, undefined, name, undefined, indexerTypeNode, undefined); + var typeNode = typeToTypeNodeHelper(indexInfo.type || anyType, context); + if (!indexInfo.type && !(context.flags & 2097152)) { + context.encounteredError = true; + } + context.approximateLength += (name.length + 4); + return ts.createIndexSignature(undefined, indexInfo.isReadonly ? [ts.createToken(133)] : undefined, [indexingParameter], typeNode); + } + function signatureToSignatureDeclarationHelper(signature, kind, context) { + var typeParameters; + var typeArguments; + if (context.flags & 32 && signature.target && signature.mapper && signature.target.typeParameters) { + typeArguments = signature.target.typeParameters.map(function (parameter) { return typeToTypeNodeHelper(instantiateType(parameter, signature.mapper), context); }); + } + else { + typeParameters = signature.typeParameters && signature.typeParameters.map(function (parameter) { return typeParameterToDeclaration(parameter, context); }); + } + var parameters = getExpandedParameters(signature).map(function (parameter) { return symbolToParameterDeclaration(parameter, context, kind === 157); }); + if (signature.thisParameter) { + var thisParameter = symbolToParameterDeclaration(signature.thisParameter, context); + parameters.unshift(thisParameter); + } + var returnTypeNode; + var typePredicate = getTypePredicateOfSignature(signature); + if (typePredicate) { + var parameterName = typePredicate.kind === 1 ? + ts.setEmitFlags(ts.createIdentifier(typePredicate.parameterName), 16777216) : + ts.createThisTypeNode(); + var typeNode = typeToTypeNodeHelper(typePredicate.type, context); + returnTypeNode = ts.createTypePredicateNode(parameterName, typeNode); + } + else { + var returnType = getReturnTypeOfSignature(signature); + returnTypeNode = returnType && typeToTypeNodeHelper(returnType, context); + } + if (context.flags & 256) { + if (returnTypeNode && returnTypeNode.kind === 120) { + returnTypeNode = undefined; + } + } + else if (!returnTypeNode) { + returnTypeNode = ts.createKeywordTypeNode(120); + } + context.approximateLength += 3; + return ts.createSignatureDeclaration(kind, typeParameters, parameters, returnTypeNode, typeArguments); + } + function typeParameterShadowsNameInScope(type, context) { + return !!resolveName(context.enclosingDeclaration, type.symbol.escapedName, 67897832, undefined, type.symbol.escapedName, false); + } + function typeParameterToDeclarationWithConstraint(type, context, constraintNode) { + var savedContextFlags = context.flags; + context.flags &= ~512; + var shouldUseGeneratedName = context.flags & 4 && + type.symbol.declarations[0] && + ts.isTypeParameterDeclaration(type.symbol.declarations[0]) && + typeParameterShadowsNameInScope(type, context); + var name = shouldUseGeneratedName + ? ts.getGeneratedNameForNode(type.symbol.declarations[0].name, 16 | 8) + : symbolToName(type.symbol, context, 67897832, true); + var defaultParameter = getDefaultFromTypeParameter(type); + var defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter, context); + context.flags = savedContextFlags; + return ts.createTypeParameterDeclaration(name, constraintNode, defaultParameterNode); + } + function typeParameterToDeclaration(type, context, constraint) { + if (constraint === void 0) { constraint = getConstraintOfTypeParameter(type); } + var constraintNode = constraint && typeToTypeNodeHelper(constraint, context); + return typeParameterToDeclarationWithConstraint(type, context, constraintNode); + } + function symbolToParameterDeclaration(parameterSymbol, context, preserveModifierFlags) { + var parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 151); + if (!parameterDeclaration && !isTransientSymbol(parameterSymbol)) { + parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 299); + } + var parameterType = getTypeOfSymbol(parameterSymbol); + if (parameterDeclaration && isRequiredInitializedParameter(parameterDeclaration)) { + parameterType = getOptionalType(parameterType); + } + var parameterTypeNode = typeToTypeNodeHelper(parameterType, context); + var modifiers = !(context.flags & 8192) && preserveModifierFlags && parameterDeclaration && parameterDeclaration.modifiers ? parameterDeclaration.modifiers.map(ts.getSynthesizedClone) : undefined; + var isRest = parameterDeclaration && ts.isRestParameter(parameterDeclaration) || ts.getCheckFlags(parameterSymbol) & 8192; + var dotDotDotToken = isRest ? ts.createToken(25) : undefined; + var name = parameterDeclaration + ? parameterDeclaration.name ? + parameterDeclaration.name.kind === 72 ? ts.setEmitFlags(ts.getSynthesizedClone(parameterDeclaration.name), 16777216) : + parameterDeclaration.name.kind === 148 ? ts.setEmitFlags(ts.getSynthesizedClone(parameterDeclaration.name.right), 16777216) : + cloneBindingName(parameterDeclaration.name) : + ts.symbolName(parameterSymbol) + : ts.symbolName(parameterSymbol); + var isOptional = parameterDeclaration && isOptionalParameter(parameterDeclaration) || ts.getCheckFlags(parameterSymbol) & 4096; + var questionToken = isOptional ? ts.createToken(56) : undefined; + var parameterNode = ts.createParameter(undefined, modifiers, dotDotDotToken, name, questionToken, parameterTypeNode, undefined); + context.approximateLength += ts.symbolName(parameterSymbol).length + 3; + return parameterNode; + function cloneBindingName(node) { + return elideInitializerAndSetEmitFlags(node); + function elideInitializerAndSetEmitFlags(node) { + if (context.tracker.trackSymbol && ts.isComputedPropertyName(node) && isLateBindableName(node)) { + trackComputedName(node, context.enclosingDeclaration, context); + } + var visited = ts.visitEachChild(node, elideInitializerAndSetEmitFlags, ts.nullTransformationContext, undefined, elideInitializerAndSetEmitFlags); + var clone = ts.nodeIsSynthesized(visited) ? visited : ts.getSynthesizedClone(visited); + if (clone.kind === 186) { + clone.initializer = undefined; + } + return ts.setEmitFlags(clone, 1 | 16777216); + } + } + } + function trackComputedName(node, enclosingDeclaration, context) { + if (!context.tracker.trackSymbol) + return; + var firstIdentifier = getFirstIdentifier(node.expression); + var name = resolveName(firstIdentifier, firstIdentifier.escapedText, 67220415 | 1048576, undefined, undefined, true); + if (name) { + context.tracker.trackSymbol(name, enclosingDeclaration, 67220415); + } + } + function lookupSymbolChain(symbol, context, meaning, yieldModuleSymbol) { + context.tracker.trackSymbol(symbol, context.enclosingDeclaration, meaning); + var chain; + var isTypeParameter = symbol.flags & 262144; + if (!isTypeParameter && (context.enclosingDeclaration || context.flags & 64) && !(context.flags & 134217728)) { + chain = ts.Debug.assertDefined(getSymbolChain(symbol, meaning, true)); + ts.Debug.assert(chain && chain.length > 0); + } + else { + chain = [symbol]; + } + return chain; + function getSymbolChain(symbol, meaning, endOfChain) { + var accessibleSymbolChain = getAccessibleSymbolChain(symbol, context.enclosingDeclaration, meaning, !!(context.flags & 128)); + var parentSpecifiers; + if (!accessibleSymbolChain || + needsQualification(accessibleSymbolChain[0], context.enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) { + var parents_1 = getContainersOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol, context.enclosingDeclaration); + if (ts.length(parents_1)) { + parentSpecifiers = parents_1.map(function (symbol) { + return ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol) + ? getSpecifierForModuleSymbol(symbol, context) + : undefined; + }); + var indices = parents_1.map(function (_, i) { return i; }); + indices.sort(sortByBestName); + var sortedParents = indices.map(function (i) { return parents_1[i]; }); + for (var _i = 0, sortedParents_1 = sortedParents; _i < sortedParents_1.length; _i++) { + var parent = sortedParents_1[_i]; + var parentChain = getSymbolChain(parent, getQualifiedLeftMeaning(meaning), false); + if (parentChain) { + accessibleSymbolChain = parentChain.concat(accessibleSymbolChain || [getAliasForSymbolInContainer(parent, symbol) || symbol]); + break; + } + } + } + } + if (accessibleSymbolChain) { + return accessibleSymbolChain; + } + if (endOfChain || + !(symbol.flags & (2048 | 4096))) { + if (!endOfChain && !yieldModuleSymbol && !!ts.forEach(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { + return; + } + return [symbol]; + } + function sortByBestName(a, b) { + var specifierA = parentSpecifiers[a]; + var specifierB = parentSpecifiers[b]; + if (specifierA && specifierB) { + var isBRelative = ts.pathIsRelative(specifierB); + if (ts.pathIsRelative(specifierA) === isBRelative) { + return ts.moduleSpecifiers.countPathComponents(specifierA) - ts.moduleSpecifiers.countPathComponents(specifierB); + } + if (isBRelative) { + return -1; + } + return 1; + } + return 0; + } + } + } + function typeParametersToTypeParameterDeclarations(symbol, context) { + var typeParameterNodes; + var targetSymbol = getTargetSymbol(symbol); + if (targetSymbol.flags & (32 | 64 | 524288)) { + typeParameterNodes = ts.createNodeArray(ts.map(getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol), function (tp) { return typeParameterToDeclaration(tp, context); })); + } + return typeParameterNodes; + } + function lookupTypeParameterNodes(chain, index, context) { + ts.Debug.assert(chain && 0 <= index && index < chain.length); + var symbol = chain[index]; + var typeParameterNodes; + if (context.flags & 512 && index < (chain.length - 1)) { + var parentSymbol = symbol; + var nextSymbol = chain[index + 1]; + if (ts.getCheckFlags(nextSymbol) & 1) { + var params = getTypeParametersOfClassOrInterface(parentSymbol.flags & 2097152 ? resolveAlias(parentSymbol) : parentSymbol); + typeParameterNodes = mapToTypeNodes(ts.map(params, nextSymbol.mapper), context); + } + else { + typeParameterNodes = typeParametersToTypeParameterDeclarations(symbol, context); + } + } + return typeParameterNodes; + } + function getTopmostIndexedAccessType(top) { + if (ts.isIndexedAccessTypeNode(top.objectType)) { + return getTopmostIndexedAccessType(top.objectType); + } + return top; + } + function getSpecifierForModuleSymbol(symbol, context) { + var file = ts.getDeclarationOfKind(symbol, 279); + if (file && file.moduleName !== undefined) { + return file.moduleName; + } + if (!file) { + if (context.tracker.trackReferencedAmbientModule) { + var ambientDecls = ts.filter(symbol.declarations, ts.isAmbientModule); + if (ts.length(ambientDecls)) { + for (var _i = 0, ambientDecls_1 = ambientDecls; _i < ambientDecls_1.length; _i++) { + var decl = ambientDecls_1[_i]; + context.tracker.trackReferencedAmbientModule(decl, symbol); + } + } + } + if (ambientModuleSymbolRegex.test(symbol.escapedName)) { + return symbol.escapedName.substring(1, symbol.escapedName.length - 1); + } + } + if (!context.enclosingDeclaration || !context.tracker.moduleResolverHost) { + if (ambientModuleSymbolRegex.test(symbol.escapedName)) { + return symbol.escapedName.substring(1, symbol.escapedName.length - 1); + } + return ts.getSourceFileOfNode(ts.getNonAugmentationDeclaration(symbol)).fileName; + } + var contextFile = ts.getSourceFileOfNode(ts.getOriginalNode(context.enclosingDeclaration)); + var links = getSymbolLinks(symbol); + var specifier = links.specifierCache && links.specifierCache.get(contextFile.path); + if (!specifier) { + var isBundle_1 = (compilerOptions.out || compilerOptions.outFile); + var moduleResolverHost = context.tracker.moduleResolverHost; + var specifierCompilerOptions = isBundle_1 ? __assign({}, compilerOptions, { baseUrl: moduleResolverHost.getCommonSourceDirectory() }) : compilerOptions; + specifier = ts.first(ts.moduleSpecifiers.getModuleSpecifiers(symbol, specifierCompilerOptions, contextFile, moduleResolverHost, host.getSourceFiles(), { importModuleSpecifierPreference: isBundle_1 ? "non-relative" : "relative" }, host.redirectTargetsMap)); + links.specifierCache = links.specifierCache || ts.createMap(); + links.specifierCache.set(contextFile.path, specifier); + } + return specifier; + } + function symbolToTypeNode(symbol, context, meaning, overrideTypeArguments) { + var chain = lookupSymbolChain(symbol, context, meaning, !(context.flags & 16384)); + var isTypeOf = meaning === 67220415; + if (ts.some(chain[0].declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { + var nonRootParts = chain.length > 1 ? createAccessFromSymbolChain(chain, chain.length - 1, 1) : undefined; + var typeParameterNodes = overrideTypeArguments || lookupTypeParameterNodes(chain, 0, context); + var specifier = getSpecifierForModuleSymbol(chain[0], context); + if (!(context.flags & 67108864) && ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs && specifier.indexOf("/node_modules/") >= 0) { + context.encounteredError = true; + if (context.tracker.reportLikelyUnsafeImportRequiredError) { + context.tracker.reportLikelyUnsafeImportRequiredError(specifier); + } + } + var lit = ts.createLiteralTypeNode(ts.createLiteral(specifier)); + if (context.tracker.trackExternalModuleSymbolOfImportTypeNode) + context.tracker.trackExternalModuleSymbolOfImportTypeNode(chain[0]); + context.approximateLength += specifier.length + 10; + if (!nonRootParts || ts.isEntityName(nonRootParts)) { + if (nonRootParts) { + var lastId = ts.isIdentifier(nonRootParts) ? nonRootParts : nonRootParts.right; + lastId.typeArguments = undefined; + } + return ts.createImportTypeNode(lit, nonRootParts, typeParameterNodes, isTypeOf); + } + else { + var splitNode = getTopmostIndexedAccessType(nonRootParts); + var qualifier = splitNode.objectType.typeName; + return ts.createIndexedAccessTypeNode(ts.createImportTypeNode(lit, qualifier, typeParameterNodes, isTypeOf), splitNode.indexType); + } + } + var entityName = createAccessFromSymbolChain(chain, chain.length - 1, 0); + if (ts.isIndexedAccessTypeNode(entityName)) { + return entityName; + } + if (isTypeOf) { + return ts.createTypeQueryNode(entityName); + } + else { + var lastId = ts.isIdentifier(entityName) ? entityName : entityName.right; + var lastTypeArgs = lastId.typeArguments; + lastId.typeArguments = undefined; + return ts.createTypeReferenceNode(entityName, lastTypeArgs); + } + function createAccessFromSymbolChain(chain, index, stopper) { + var typeParameterNodes = index === (chain.length - 1) ? overrideTypeArguments : lookupTypeParameterNodes(chain, index, context); + var symbol = chain[index]; + if (index === 0) { + context.flags |= 16777216; + } + var symbolName = getNameOfSymbolAsWritten(symbol, context); + context.approximateLength += symbolName.length + 1; + if (index === 0) { + context.flags ^= 16777216; + } + var parent = chain[index - 1]; + if (!(context.flags & 16) && parent && getMembersOfSymbol(parent) && getMembersOfSymbol(parent).get(symbol.escapedName) === symbol) { + var LHS = createAccessFromSymbolChain(chain, index - 1, stopper); + if (ts.isIndexedAccessTypeNode(LHS)) { + return ts.createIndexedAccessTypeNode(LHS, ts.createLiteralTypeNode(ts.createLiteral(symbolName))); + } + else { + return ts.createIndexedAccessTypeNode(ts.createTypeReferenceNode(LHS, typeParameterNodes), ts.createLiteralTypeNode(ts.createLiteral(symbolName))); + } + } + var identifier = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216); + identifier.symbol = symbol; + if (index > stopper) { + var LHS = createAccessFromSymbolChain(chain, index - 1, stopper); + if (!ts.isEntityName(LHS)) { + return ts.Debug.fail("Impossible construct - an export of an indexed access cannot be reachable"); + } + return ts.createQualifiedName(LHS, identifier); + } + return identifier; + } + } + function symbolToName(symbol, context, meaning, expectsIdentifier) { + var chain = lookupSymbolChain(symbol, context, meaning); + if (expectsIdentifier && chain.length !== 1 + && !context.encounteredError + && !(context.flags & 65536)) { + context.encounteredError = true; + } + return createEntityNameFromSymbolChain(chain, chain.length - 1); + function createEntityNameFromSymbolChain(chain, index) { + var typeParameterNodes = lookupTypeParameterNodes(chain, index, context); + var symbol = chain[index]; + if (index === 0) { + context.flags |= 16777216; + } + var symbolName = getNameOfSymbolAsWritten(symbol, context); + if (index === 0) { + context.flags ^= 16777216; + } + var identifier = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216); + identifier.symbol = symbol; + return index > 0 ? ts.createQualifiedName(createEntityNameFromSymbolChain(chain, index - 1), identifier) : identifier; + } + } + function symbolToExpression(symbol, context, meaning) { + var chain = lookupSymbolChain(symbol, context, meaning); + return createExpressionFromSymbolChain(chain, chain.length - 1); + function createExpressionFromSymbolChain(chain, index) { + var typeParameterNodes = lookupTypeParameterNodes(chain, index, context); + var symbol = chain[index]; + if (ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { + return ts.createLiteral(getSpecifierForModuleSymbol(symbol, context)); + } + if (index === 0) { + context.flags |= 16777216; + } + var symbolName = getNameOfSymbolAsWritten(symbol, context); + if (index === 0) { + context.flags ^= 16777216; + } + var firstChar = symbolName.charCodeAt(0); + var canUsePropertyAccess = ts.isIdentifierStart(firstChar, languageVersion); + if (index === 0 || canUsePropertyAccess) { + var identifier = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216); + identifier.symbol = symbol; + return index > 0 ? ts.createPropertyAccess(createExpressionFromSymbolChain(chain, index - 1), identifier) : identifier; + } + else { + if (firstChar === 91) { + symbolName = symbolName.substring(1, symbolName.length - 1); + firstChar = symbolName.charCodeAt(0); + } + var expression = void 0; + if (ts.isSingleOrDoubleQuote(firstChar)) { + expression = ts.createLiteral(symbolName.substring(1, symbolName.length - 1).replace(/\\./g, function (s) { return s.substring(1); })); + expression.singleQuote = firstChar === 39; + } + else if (("" + +symbolName) === symbolName) { + expression = ts.createLiteral(+symbolName); + } + if (!expression) { + expression = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216); + expression.symbol = symbol; + } + return ts.createElementAccess(createExpressionFromSymbolChain(chain, index - 1), expression); + } + } + } + } + function typePredicateToString(typePredicate, enclosingDeclaration, flags, writer) { + if (flags === void 0) { flags = 16384; } + return writer ? typePredicateToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(typePredicateToStringWorker); + function typePredicateToStringWorker(writer) { + var predicate = ts.createTypePredicateNode(typePredicate.kind === 1 ? ts.createIdentifier(typePredicate.parameterName) : ts.createThisTypeNode(), nodeBuilder.typeToTypeNode(typePredicate.type, enclosingDeclaration, toNodeBuilderFlags(flags) | 70221824 | 512)); + var printer = ts.createPrinter({ removeComments: true }); + var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); + printer.writeNode(4, predicate, sourceFile, writer); + return writer; + } + } + function formatUnionTypes(types) { + var result = []; + var flags = 0; + for (var i = 0; i < types.length; i++) { + var t = types[i]; + flags |= t.flags; + if (!(t.flags & 98304)) { + if (t.flags & (512 | 1024)) { + var baseType = t.flags & 512 ? booleanType : getBaseTypeOfEnumLiteralType(t); + if (baseType.flags & 1048576) { + var count = baseType.types.length; + if (i + count <= types.length && getRegularTypeOfLiteralType(types[i + count - 1]) === getRegularTypeOfLiteralType(baseType.types[count - 1])) { + result.push(baseType); + i += count - 1; + continue; + } + } + } + result.push(t); + } + } + if (flags & 65536) + result.push(nullType); + if (flags & 32768) + result.push(undefinedType); + return result || types; + } + function visibilityToString(flags) { + if (flags === 8) { + return "private"; + } + if (flags === 16) { + return "protected"; + } + return "public"; + } + function getTypeAliasForTypeLiteral(type) { + if (type.symbol && type.symbol.flags & 2048) { + var node = ts.findAncestor(type.symbol.declarations[0].parent, function (n) { return n.kind !== 177; }); + if (node.kind === 242) { + return getSymbolOfNode(node); + } + } + return undefined; + } + function isTopLevelInExternalModuleAugmentation(node) { + return node && node.parent && + node.parent.kind === 245 && + ts.isExternalModuleAugmentation(node.parent.parent); + } + function isDefaultBindingContext(location) { + return location.kind === 279 || ts.isAmbientModule(location); + } + function getNameOfSymbolAsWritten(symbol, context) { + if (context && symbol.escapedName === "default" && !(context.flags & 16384) && + (!(context.flags & 16777216) || + !symbol.declarations || + (context.enclosingDeclaration && ts.findAncestor(symbol.declarations[0], isDefaultBindingContext) !== ts.findAncestor(context.enclosingDeclaration, isDefaultBindingContext)))) { + return "default"; + } + if (symbol.declarations && symbol.declarations.length) { + var declaration = symbol.declarations[0]; + var name = ts.getNameOfDeclaration(declaration); + if (name) { + if (ts.isCallExpression(declaration) && ts.isBindableObjectDefinePropertyCall(declaration)) { + return ts.symbolName(symbol); + } + return ts.declarationNameToString(name); + } + if (declaration.parent && declaration.parent.kind === 237) { + return ts.declarationNameToString(declaration.parent.name); + } + switch (declaration.kind) { + case 209: + case 196: + case 197: + if (context && !context.encounteredError && !(context.flags & 131072)) { + context.encounteredError = true; + } + return declaration.kind === 209 ? "(Anonymous class)" : "(Anonymous function)"; + } + } + var nameType = symbol.nameType; + if (nameType) { + if (nameType.flags & 128 && !ts.isIdentifierText(nameType.value, compilerOptions.target)) { + return "\"" + ts.escapeString(nameType.value, 34) + "\""; + } + if (nameType && nameType.flags & 8192) { + return "[" + getNameOfSymbolAsWritten(nameType.symbol, context) + "]"; + } + } + return ts.symbolName(symbol); + } + function isDeclarationVisible(node) { + if (node) { + var links = getNodeLinks(node); + if (links.isVisible === undefined) { + links.isVisible = !!determineIfDeclarationIsVisible(); + } + return links.isVisible; + } + return false; + function determineIfDeclarationIsVisible() { + switch (node.kind) { + case 297: + case 304: + return !!(node.parent && node.parent.parent && node.parent.parent.parent && ts.isSourceFile(node.parent.parent.parent)); + case 186: + return isDeclarationVisible(node.parent.parent); + case 237: + if (ts.isBindingPattern(node.name) && + !node.name.elements.length) { + return false; + } + case 244: + case 240: + case 241: + case 242: + case 239: + case 243: + case 248: + if (ts.isExternalModuleAugmentation(node)) { + return true; + } + var parent = getDeclarationContainer(node); + if (!(ts.getCombinedModifierFlags(node) & 1) && + !(node.kind !== 248 && parent.kind !== 279 && parent.flags & 4194304)) { + return isGlobalSourceFile(parent); + } + return isDeclarationVisible(parent); + case 154: + case 153: + case 158: + case 159: + case 156: + case 155: + if (ts.hasModifier(node, 8 | 16)) { + return false; + } + case 157: + case 161: + case 160: + case 162: + case 151: + case 245: + case 165: + case 166: + case 168: + case 164: + case 169: + case 170: + case 173: + case 174: + case 177: + return isDeclarationVisible(node.parent); + case 250: + case 251: + case 253: + return false; + case 150: + case 279: + case 247: + return true; + case 254: + return false; + default: + return false; + } + } + } + function collectLinkedAliases(node, setVisibility) { + var exportSymbol; + if (node.parent && node.parent.kind === 254) { + exportSymbol = resolveName(node, node.escapedText, 67220415 | 67897832 | 1920 | 2097152, undefined, node, false); + } + else if (node.parent.kind === 257) { + exportSymbol = getTargetOfExportSpecifier(node.parent, 67220415 | 67897832 | 1920 | 2097152); + } + var result; + if (exportSymbol) { + buildVisibleNodeList(exportSymbol.declarations); + } + return result; + function buildVisibleNodeList(declarations) { + ts.forEach(declarations, function (declaration) { + var resultNode = getAnyImportSyntax(declaration) || declaration; + if (setVisibility) { + getNodeLinks(declaration).isVisible = true; + } + else { + result = result || []; + ts.pushIfUnique(result, resultNode); + } + if (ts.isInternalModuleImportEqualsDeclaration(declaration)) { + var internalModuleReference = declaration.moduleReference; + var firstIdentifier = getFirstIdentifier(internalModuleReference); + var importSymbol = resolveName(declaration, firstIdentifier.escapedText, 67220415 | 67897832 | 1920, undefined, undefined, false); + if (importSymbol) { + buildVisibleNodeList(importSymbol.declarations); + } + } + }); + } + } + function pushTypeResolution(target, propertyName) { + var resolutionCycleStartIndex = findResolutionCycleStartIndex(target, propertyName); + if (resolutionCycleStartIndex >= 0) { + var length_2 = resolutionTargets.length; + for (var i = resolutionCycleStartIndex; i < length_2; i++) { + resolutionResults[i] = false; + } + return false; + } + resolutionTargets.push(target); + resolutionResults.push(true); + resolutionPropertyNames.push(propertyName); + return true; + } + function findResolutionCycleStartIndex(target, propertyName) { + for (var i = resolutionTargets.length - 1; i >= 0; i--) { + if (hasType(resolutionTargets[i], resolutionPropertyNames[i])) { + return -1; + } + if (resolutionTargets[i] === target && resolutionPropertyNames[i] === propertyName) { + return i; + } + } + return -1; + } + function hasType(target, propertyName) { + switch (propertyName) { + case 0: + return !!getSymbolLinks(target).type; + case 5: + return !!(getNodeLinks(target).resolvedEnumType); + case 2: + return !!getSymbolLinks(target).declaredType; + case 1: + return !!target.resolvedBaseConstructorType; + case 3: + return !!target.resolvedReturnType; + case 4: + return !!target.immediateBaseConstraint; + case 6: + return !!getSymbolLinks(target).resolvedJSDocType; + } + return ts.Debug.assertNever(propertyName); + } + function popTypeResolution() { + resolutionTargets.pop(); + resolutionPropertyNames.pop(); + return resolutionResults.pop(); + } + function getDeclarationContainer(node) { + return ts.findAncestor(ts.getRootDeclaration(node), function (node) { + switch (node.kind) { + case 237: + case 238: + case 253: + case 252: + case 251: + case 250: + return false; + default: + return true; + } + }).parent; + } + function getTypeOfPrototypeProperty(prototype) { + var classType = getDeclaredTypeOfSymbol(getParentOfSymbol(prototype)); + return classType.typeParameters ? createTypeReference(classType, ts.map(classType.typeParameters, function (_) { return anyType; })) : classType; + } + function getTypeOfPropertyOfType(type, name) { + var prop = getPropertyOfType(type, name); + return prop ? getTypeOfSymbol(prop) : undefined; + } + function isTypeAny(type) { + return type && (type.flags & 1) !== 0; + } + function getTypeForBindingElementParent(node) { + var symbol = getSymbolOfNode(node); + return symbol && getSymbolLinks(symbol).type || getTypeForVariableLikeDeclaration(node, false); + } + function isComputedNonLiteralName(name) { + return name.kind === 149 && !ts.isStringOrNumericLiteralLike(name.expression); + } + function getRestType(source, properties, symbol) { + source = filterType(source, function (t) { return !(t.flags & 98304); }); + if (source.flags & 131072) { + return emptyObjectType; + } + if (source.flags & 1048576) { + return mapType(source, function (t) { return getRestType(t, properties, symbol); }); + } + var omitKeyType = getUnionType(ts.map(properties, getLiteralTypeFromPropertyName)); + if (isGenericObjectType(source) || isGenericIndexType(omitKeyType)) { + if (omitKeyType.flags & 131072) { + return source; + } + var pickTypeAlias = getGlobalPickSymbol(); + var excludeTypeAlias = getGlobalExcludeSymbol(); + if (!pickTypeAlias || !excludeTypeAlias) { + return errorType; + } + var pickKeys = getTypeAliasInstantiation(excludeTypeAlias, [getIndexType(source), omitKeyType]); + return getTypeAliasInstantiation(pickTypeAlias, [source, pickKeys]); + } + var members = ts.createSymbolTable(); + for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) { + var prop = _a[_i]; + if (!isTypeAssignableTo(getLiteralTypeFromProperty(prop, 8576), omitKeyType) + && !(ts.getDeclarationModifierFlagsFromSymbol(prop) & (8 | 16)) + && isSpreadableProperty(prop)) { + members.set(prop.escapedName, getSpreadSymbol(prop)); + } + } + var stringIndexInfo = getIndexInfoOfType(source, 0); + var numberIndexInfo = getIndexInfoOfType(source, 1); + return createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); + } + function getTypeForBindingElement(declaration) { + var pattern = declaration.parent; + var parentType = getTypeForBindingElementParent(pattern.parent); + if (parentType === errorType) { + return errorType; + } + if (!parentType) { + return declaration.initializer ? checkDeclarationInitializer(declaration) : parentType; + } + if (isTypeAny(parentType)) { + return parentType; + } + if (strictNullChecks && declaration.flags & 4194304 && ts.isParameterDeclaration(declaration)) { + parentType = getNonNullableType(parentType); + } + var type; + if (pattern.kind === 184) { + if (declaration.dotDotDotToken) { + if (parentType.flags & 2 || !isValidSpreadType(parentType)) { + error(declaration, ts.Diagnostics.Rest_types_may_only_be_created_from_object_types); + return errorType; + } + var literalMembers = []; + for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (!element.dotDotDotToken) { + literalMembers.push(element.propertyName || element.name); + } + } + type = getRestType(parentType, literalMembers, declaration.symbol); + } + else { + var name = declaration.propertyName || declaration.name; + var exprType = getLiteralTypeFromPropertyName(name); + var declaredType = checkIndexedAccessIndexType(getIndexedAccessType(parentType, exprType, name), name); + type = getFlowTypeOfReference(declaration, getConstraintForLocation(declaredType, declaration.name)); + } + } + else { + var elementType = checkIteratedTypeOrElementType(parentType, pattern, false, false); + var index_1 = pattern.elements.indexOf(declaration); + if (declaration.dotDotDotToken) { + type = everyType(parentType, isTupleType) ? + mapType(parentType, function (t) { return sliceTupleType(t, index_1); }) : + createArrayType(elementType); + } + else { + var index_2 = pattern.elements.indexOf(declaration); + type = everyType(parentType, isTupleLikeType) ? + getTupleElementType(parentType, index_2) || declaration.initializer && checkDeclarationInitializer(declaration) : + elementType; + if (!type) { + if (isTupleType(parentType)) { + error(declaration, ts.Diagnostics.Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2, typeToString(parentType), getTypeReferenceArity(parentType), pattern.elements.length); + } + else { + error(declaration, ts.Diagnostics.Type_0_has_no_property_1, typeToString(parentType), "" + index_2); + } + return errorType; + } + } + } + if (strictNullChecks && declaration.initializer && !(getFalsyFlags(checkDeclarationInitializer(declaration)) & 32768)) { + type = getTypeWithFacts(type, 524288); + } + return declaration.initializer && !ts.getEffectiveTypeAnnotationNode(ts.walkUpBindingElementsAndPatterns(declaration)) ? + getUnionType([type, checkDeclarationInitializer(declaration)], 2) : + type; + } + function getTypeForDeclarationFromJSDocComment(declaration) { + var jsdocType = ts.getJSDocType(declaration); + if (jsdocType) { + return getTypeFromTypeNode(jsdocType); + } + return undefined; + } + function isNullOrUndefined(node) { + var expr = ts.skipParentheses(node); + return expr.kind === 96 || expr.kind === 72 && getResolvedSymbol(expr) === undefinedSymbol; + } + function isEmptyArrayLiteral(node) { + var expr = ts.skipParentheses(node); + return expr.kind === 187 && expr.elements.length === 0; + } + function addOptionality(type, optional) { + if (optional === void 0) { optional = true; } + return strictNullChecks && optional ? getOptionalType(type) : type; + } + function getTypeForVariableLikeDeclaration(declaration, includeOptionality) { + if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 226) { + var indexType = getIndexType(getNonNullableTypeIfNeeded(checkExpression(declaration.parent.parent.expression))); + return indexType.flags & (262144 | 4194304) ? getExtractStringType(indexType) : stringType; + } + if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 227) { + var forOfStatement = declaration.parent.parent; + return checkRightHandSideOfForOf(forOfStatement.expression, forOfStatement.awaitModifier) || anyType; + } + if (ts.isBindingPattern(declaration.parent)) { + return getTypeForBindingElement(declaration); + } + var isOptional = includeOptionality && (ts.isParameter(declaration) && isJSDocOptionalParameter(declaration) + || !ts.isBindingElement(declaration) && !ts.isVariableDeclaration(declaration) && !!declaration.questionToken); + var declaredType = tryGetTypeFromEffectiveTypeNode(declaration); + if (declaredType) { + return addOptionality(declaredType, isOptional); + } + if ((noImplicitAny || ts.isInJSFile(declaration)) && + declaration.kind === 237 && !ts.isBindingPattern(declaration.name) && + !(ts.getCombinedModifierFlags(declaration) & 1) && !(declaration.flags & 4194304)) { + if (!(ts.getCombinedNodeFlags(declaration) & 2) && (!declaration.initializer || isNullOrUndefined(declaration.initializer))) { + return autoType; + } + if (declaration.initializer && isEmptyArrayLiteral(declaration.initializer)) { + return autoArrayType; + } + } + if (declaration.kind === 151) { + var func = declaration.parent; + if (func.kind === 159 && !hasNonBindableDynamicName(func)) { + var getter = ts.getDeclarationOfKind(getSymbolOfNode(declaration.parent), 158); + if (getter) { + var getterSignature = getSignatureFromDeclaration(getter); + var thisParameter = getAccessorThisParameter(func); + if (thisParameter && declaration === thisParameter) { + ts.Debug.assert(!thisParameter.type); + return getTypeOfSymbol(getterSignature.thisParameter); + } + return getReturnTypeOfSignature(getterSignature); + } + } + if (ts.isInJSFile(declaration)) { + var typeTag = ts.getJSDocType(func); + if (typeTag && ts.isFunctionTypeNode(typeTag)) { + return getTypeAtPosition(getSignatureFromDeclaration(typeTag), func.parameters.indexOf(declaration)); + } + } + var type = declaration.symbol.escapedName === "this" ? getContextualThisParameterType(func) : getContextuallyTypedParameterType(declaration); + if (type) { + return addOptionality(type, isOptional); + } + } + else if (ts.isInJSFile(declaration)) { + var containerObjectType = getJSContainerObjectType(declaration, getSymbolOfNode(declaration), ts.getDeclaredExpandoInitializer(declaration)); + if (containerObjectType) { + return containerObjectType; + } + } + if (declaration.initializer) { + var type = checkDeclarationInitializer(declaration); + return addOptionality(type, isOptional); + } + if (ts.isJsxAttribute(declaration)) { + return trueType; + } + if (ts.isBindingPattern(declaration.name)) { + return getTypeFromBindingPattern(declaration.name, false, true); + } + return undefined; + } + function getWidenedTypeFromAssignmentDeclaration(symbol, resolvedSymbol) { + var container = ts.getAssignedExpandoInitializer(symbol.valueDeclaration); + if (container) { + var tag = ts.getJSDocTypeTag(container); + if (tag && tag.typeExpression) { + return getTypeFromTypeNode(tag.typeExpression); + } + var containerObjectType = getJSContainerObjectType(symbol.valueDeclaration, symbol, container); + return containerObjectType || getWidenedLiteralType(checkExpressionCached(container)); + } + var definedInConstructor = false; + var definedInMethod = false; + var jsdocType; + var types; + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + var expression = (ts.isBinaryExpression(declaration) || ts.isCallExpression(declaration)) ? declaration : + ts.isPropertyAccessExpression(declaration) ? ts.isBinaryExpression(declaration.parent) ? declaration.parent : declaration : + undefined; + if (!expression) { + return errorType; + } + var kind = ts.isPropertyAccessExpression(expression) ? ts.getAssignmentDeclarationPropertyAccessKind(expression) : ts.getAssignmentDeclarationKind(expression); + if (kind === 4) { + if (isDeclarationInConstructor(expression)) { + definedInConstructor = true; + } + else { + definedInMethod = true; + } + } + if (!ts.isCallExpression(expression)) { + jsdocType = getJSDocTypeFromAssignmentDeclaration(jsdocType, expression, symbol, declaration); + } + if (!jsdocType) { + (types || (types = [])).push((ts.isBinaryExpression(expression) || ts.isCallExpression(expression)) ? getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) : neverType); + } + } + var type = jsdocType; + if (!type) { + var constructorTypes = definedInConstructor ? getConstructorDefinedThisAssignmentTypes(types, symbol.declarations) : undefined; + if (definedInMethod) { + var propType = getTypeOfAssignmentDeclarationPropertyOfBaseType(symbol); + if (propType) { + (constructorTypes || (constructorTypes = [])).push(propType); + definedInConstructor = true; + } + } + var sourceTypes = ts.some(constructorTypes, function (t) { return !!(t.flags & ~(98304 | 134217728)); }) ? constructorTypes : types; + type = getUnionType(sourceTypes, 2); + } + var widened = getWidenedType(addOptionality(type, definedInMethod && !definedInConstructor)); + if (filterType(widened, function (t) { return !!(t.flags & ~98304); }) === neverType) { + reportImplicitAny(symbol.valueDeclaration, anyType); + return anyType; + } + return widened; + } + function getJSContainerObjectType(decl, symbol, init) { + if (!ts.isInJSFile(decl) || !init || !ts.isObjectLiteralExpression(init) || init.properties.length) { + return undefined; + } + var exports = ts.createSymbolTable(); + while (ts.isBinaryExpression(decl) || ts.isPropertyAccessExpression(decl)) { + var s_1 = getSymbolOfNode(decl); + if (s_1 && ts.hasEntries(s_1.exports)) { + mergeSymbolTable(exports, s_1.exports); + } + decl = ts.isBinaryExpression(decl) ? decl.parent : decl.parent.parent; + } + var s = getSymbolOfNode(decl); + if (s && ts.hasEntries(s.exports)) { + mergeSymbolTable(exports, s.exports); + } + var type = createAnonymousType(symbol, exports, ts.emptyArray, ts.emptyArray, undefined, undefined); + type.objectFlags |= 16384; + return type; + } + function getJSDocTypeFromAssignmentDeclaration(declaredType, expression, _symbol, declaration) { + var typeNode = ts.getJSDocType(expression.parent); + if (typeNode) { + var type = getWidenedType(getTypeFromTypeNode(typeNode)); + if (!declaredType) { + return type; + } + else if (declaredType !== errorType && type !== errorType && !isTypeIdenticalTo(declaredType, type)) { + errorNextVariableOrPropertyDeclarationMustHaveSameType(declaredType, declaration, type); + } + } + return declaredType; + } + function getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) { + if (ts.isCallExpression(expression)) { + if (resolvedSymbol) { + return getTypeOfSymbol(resolvedSymbol); + } + var objectLitType = checkExpressionCached(expression.arguments[2]); + var valueType = getTypeOfPropertyOfType(objectLitType, "value"); + if (valueType) { + return valueType; + } + var getFunc = getTypeOfPropertyOfType(objectLitType, "get"); + if (getFunc) { + var getSig = getSingleCallSignature(getFunc); + if (getSig) { + return getReturnTypeOfSignature(getSig); + } + } + var setFunc = getTypeOfPropertyOfType(objectLitType, "set"); + if (setFunc) { + var setSig = getSingleCallSignature(setFunc); + if (setSig) { + return getTypeOfFirstParameterOfSignature(setSig); + } + } + return anyType; + } + var type = resolvedSymbol ? getTypeOfSymbol(resolvedSymbol) : getWidenedLiteralType(checkExpressionCached(expression.right)); + if (type.flags & 524288 && + kind === 2 && + symbol.escapedName === "export=") { + var exportedType_1 = resolveStructuredTypeMembers(type); + var members_3 = ts.createSymbolTable(); + ts.copyEntries(exportedType_1.members, members_3); + if (resolvedSymbol && !resolvedSymbol.exports) { + resolvedSymbol.exports = ts.createSymbolTable(); + } + (resolvedSymbol || symbol).exports.forEach(function (s, name) { + if (members_3.has(name)) { + var exportedMember = exportedType_1.members.get(name); + var union = createSymbol(s.flags | exportedMember.flags, name); + union.type = getUnionType([getTypeOfSymbol(s), getTypeOfSymbol(exportedMember)]); + members_3.set(name, union); + } + else { + members_3.set(name, s); + } + }); + var result = createAnonymousType(exportedType_1.symbol, members_3, exportedType_1.callSignatures, exportedType_1.constructSignatures, exportedType_1.stringIndexInfo, exportedType_1.numberIndexInfo); + result.objectFlags |= (ts.getObjectFlags(type) & 16384); + return result; + } + if (isEmptyArrayLiteralType(type)) { + reportImplicitAny(expression, anyArrayType); + return anyArrayType; + } + return type; + } + function isDeclarationInConstructor(expression) { + var thisContainer = ts.getThisContainer(expression, false); + return thisContainer.kind === 157 || + thisContainer.kind === 239 || + (thisContainer.kind === 196 && !ts.isPrototypePropertyAssignment(thisContainer.parent)); + } + function getConstructorDefinedThisAssignmentTypes(types, declarations) { + ts.Debug.assert(types.length === declarations.length); + return types.filter(function (_, i) { + var declaration = declarations[i]; + var expression = ts.isBinaryExpression(declaration) ? declaration : + ts.isBinaryExpression(declaration.parent) ? declaration.parent : undefined; + return expression && isDeclarationInConstructor(expression); + }); + } + function getTypeOfAssignmentDeclarationPropertyOfBaseType(property) { + var parentDeclaration = ts.forEach(property.declarations, function (d) { + var parent = ts.getThisContainer(d, false).parent; + return ts.isClassLike(parent) && parent; + }); + if (parentDeclaration) { + var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(parentDeclaration)); + var baseClassType = classType && getBaseTypes(classType)[0]; + if (baseClassType) { + return getTypeOfPropertyOfType(baseClassType, property.escapedName); + } + } + } + function getTypeFromBindingElement(element, includePatternInType, reportErrors) { + if (element.initializer) { + return addOptionality(checkDeclarationInitializer(element)); + } + if (ts.isBindingPattern(element.name)) { + return getTypeFromBindingPattern(element.name, includePatternInType, reportErrors); + } + if (reportErrors && !declarationBelongsToPrivateAmbientMember(element)) { + reportImplicitAny(element, anyType); + } + return anyType; + } + function getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) { + var members = ts.createSymbolTable(); + var stringIndexInfo; + var objectFlags = 128; + ts.forEach(pattern.elements, function (e) { + var name = e.propertyName || e.name; + if (isComputedNonLiteralName(name)) { + objectFlags |= 512; + return; + } + if (e.dotDotDotToken) { + stringIndexInfo = createIndexInfo(anyType, false); + return; + } + var text = ts.getTextOfPropertyName(name); + var flags = 4 | (e.initializer ? 16777216 : 0); + var symbol = createSymbol(flags, text); + symbol.type = getTypeFromBindingElement(e, includePatternInType, reportErrors); + symbol.bindingElement = e; + members.set(symbol.escapedName, symbol); + }); + var result = createAnonymousType(undefined, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, undefined); + result.flags |= 268435456; + result.objectFlags |= objectFlags; + if (includePatternInType) { + result.pattern = pattern; + } + return result; + } + function getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors) { + var elements = pattern.elements; + var lastElement = ts.lastOrUndefined(elements); + var hasRestElement = !!(lastElement && lastElement.kind === 186 && lastElement.dotDotDotToken); + if (elements.length === 0 || elements.length === 1 && hasRestElement) { + return languageVersion >= 2 ? createIterableType(anyType) : anyArrayType; + } + var elementTypes = ts.map(elements, function (e) { return ts.isOmittedExpression(e) ? anyType : getTypeFromBindingElement(e, includePatternInType, reportErrors); }); + var minLength = ts.findLastIndex(elements, function (e) { return !ts.isOmittedExpression(e) && !hasDefaultValue(e); }, elements.length - (hasRestElement ? 2 : 1)) + 1; + var result = createTupleType(elementTypes, minLength, hasRestElement); + if (includePatternInType) { + result = cloneTypeReference(result); + result.pattern = pattern; + } + return result; + } + function getTypeFromBindingPattern(pattern, includePatternInType, reportErrors) { + if (includePatternInType === void 0) { includePatternInType = false; } + if (reportErrors === void 0) { reportErrors = false; } + return pattern.kind === 184 + ? getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) + : getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors); + } + function getWidenedTypeForVariableLikeDeclaration(declaration, reportErrors) { + return widenTypeForVariableLikeDeclaration(getTypeForVariableLikeDeclaration(declaration, true), declaration, reportErrors); + } + function widenTypeForVariableLikeDeclaration(type, declaration, reportErrors) { + if (type) { + if (reportErrors) { + reportErrorsFromWidening(declaration, type); + } + if (type.flags & 8192 && (ts.isBindingElement(declaration) || !declaration.type) && type.symbol !== getSymbolOfNode(declaration)) { + type = esSymbolType; + } + return getWidenedType(type); + } + type = ts.isParameter(declaration) && declaration.dotDotDotToken ? anyArrayType : anyType; + if (reportErrors) { + if (!declarationBelongsToPrivateAmbientMember(declaration)) { + reportImplicitAny(declaration, type); + } + } + return type; + } + function declarationBelongsToPrivateAmbientMember(declaration) { + var root = ts.getRootDeclaration(declaration); + var memberDeclaration = root.kind === 151 ? root.parent : root; + return isPrivateWithinAmbient(memberDeclaration); + } + function tryGetTypeFromEffectiveTypeNode(declaration) { + var typeNode = ts.getEffectiveTypeAnnotationNode(declaration); + if (typeNode) { + return getTypeFromTypeNode(typeNode); + } + } + function getTypeOfVariableOrParameterOrProperty(symbol) { + var links = getSymbolLinks(symbol); + return links.type || (links.type = getTypeOfVariableOrParameterOrPropertyWorker(symbol)); + } + function getTypeOfVariableOrParameterOrPropertyWorker(symbol) { + if (symbol.flags & 4194304) { + return getTypeOfPrototypeProperty(symbol); + } + if (symbol === requireSymbol) { + return anyType; + } + if (symbol.flags & 134217728) { + var fileSymbol = getSymbolOfNode(ts.getSourceFileOfNode(symbol.valueDeclaration)); + var members = ts.createSymbolTable(); + members.set("exports", fileSymbol); + return createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, undefined, undefined); + } + var declaration = symbol.valueDeclaration; + if (ts.isCatchClauseVariableDeclarationOrBindingElement(declaration)) { + return anyType; + } + if (ts.isSourceFile(declaration)) { + var jsonSourceFile = ts.cast(declaration, ts.isJsonSourceFile); + if (!jsonSourceFile.statements.length) { + return emptyObjectType; + } + var type_1 = getWidenedLiteralType(checkExpression(jsonSourceFile.statements[0].expression)); + if (type_1.flags & 524288) { + return getRegularTypeOfObjectLiteral(type_1); + } + return type_1; + } + if (declaration.kind === 254) { + return widenTypeForVariableLikeDeclaration(checkExpressionCached(declaration.expression), declaration); + } + if (!pushTypeResolution(symbol, 0)) { + return errorType; + } + var type; + if (ts.isInJSFile(declaration) && + (ts.isCallExpression(declaration) || ts.isBinaryExpression(declaration) || ts.isPropertyAccessExpression(declaration) && ts.isBinaryExpression(declaration.parent))) { + type = getWidenedTypeFromAssignmentDeclaration(symbol); + } + else if (ts.isJSDocPropertyLikeTag(declaration) + || ts.isPropertyAccessExpression(declaration) + || ts.isIdentifier(declaration) + || ts.isClassDeclaration(declaration) + || ts.isFunctionDeclaration(declaration) + || (ts.isMethodDeclaration(declaration) && !ts.isObjectLiteralMethod(declaration)) + || ts.isMethodSignature(declaration)) { + if (symbol.flags & (16 | 8192 | 32 | 384 | 512)) { + return getTypeOfFuncClassEnumModule(symbol); + } + type = ts.isBinaryExpression(declaration.parent) ? + getWidenedTypeFromAssignmentDeclaration(symbol) : + tryGetTypeFromEffectiveTypeNode(declaration) || anyType; + } + else if (ts.isPropertyAssignment(declaration)) { + type = tryGetTypeFromEffectiveTypeNode(declaration) || checkPropertyAssignment(declaration); + } + else if (ts.isJsxAttribute(declaration)) { + type = tryGetTypeFromEffectiveTypeNode(declaration) || checkJsxAttribute(declaration); + } + else if (ts.isShorthandPropertyAssignment(declaration)) { + type = tryGetTypeFromEffectiveTypeNode(declaration) || checkExpressionForMutableLocation(declaration.name, 0); + } + else if (ts.isObjectLiteralMethod(declaration)) { + type = tryGetTypeFromEffectiveTypeNode(declaration) || checkObjectLiteralMethod(declaration, 0); + } + else if (ts.isParameter(declaration) + || ts.isPropertyDeclaration(declaration) + || ts.isPropertySignature(declaration) + || ts.isVariableDeclaration(declaration) + || ts.isBindingElement(declaration)) { + type = getWidenedTypeForVariableLikeDeclaration(declaration, true); + } + else if (ts.isEnumDeclaration(declaration)) { + type = getTypeOfFuncClassEnumModule(symbol); + } + else if (ts.isEnumMember(declaration)) { + type = getTypeOfEnumMember(symbol); + } + else { + return ts.Debug.fail("Unhandled declaration kind! " + ts.Debug.showSyntaxKind(declaration) + " for " + ts.Debug.showSymbol(symbol)); + } + if (!popTypeResolution()) { + type = reportCircularityError(symbol); + } + return type; + } + function getAnnotatedAccessorTypeNode(accessor) { + if (accessor) { + if (accessor.kind === 158) { + var getterTypeAnnotation = ts.getEffectiveReturnTypeNode(accessor); + return getterTypeAnnotation; + } + else { + var setterTypeAnnotation = ts.getEffectiveSetAccessorTypeAnnotationNode(accessor); + return setterTypeAnnotation; + } + } + return undefined; + } + function getAnnotatedAccessorType(accessor) { + var node = getAnnotatedAccessorTypeNode(accessor); + return node && getTypeFromTypeNode(node); + } + function getAnnotatedAccessorThisParameter(accessor) { + var parameter = getAccessorThisParameter(accessor); + return parameter && parameter.symbol; + } + function getThisTypeOfDeclaration(declaration) { + return getThisTypeOfSignature(getSignatureFromDeclaration(declaration)); + } + function getTypeOfAccessors(symbol) { + var links = getSymbolLinks(symbol); + return links.type || (links.type = getTypeOfAccessorsWorker(symbol)); + } + function getTypeOfAccessorsWorker(symbol) { + var getter = ts.getDeclarationOfKind(symbol, 158); + var setter = ts.getDeclarationOfKind(symbol, 159); + if (getter && ts.isInJSFile(getter)) { + var jsDocType = getTypeForDeclarationFromJSDocComment(getter); + if (jsDocType) { + return jsDocType; + } + } + if (!pushTypeResolution(symbol, 0)) { + return errorType; + } + var type; + var getterReturnType = getAnnotatedAccessorType(getter); + if (getterReturnType) { + type = getterReturnType; + } + else { + var setterParameterType = getAnnotatedAccessorType(setter); + if (setterParameterType) { + type = setterParameterType; + } + else { + if (getter && getter.body) { + type = getReturnTypeFromBody(getter); + } + else { + if (setter) { + errorOrSuggestion(noImplicitAny, setter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation, symbolToString(symbol)); + } + else { + ts.Debug.assert(!!getter, "there must existed getter as we are current checking either setter or getter in this function"); + errorOrSuggestion(noImplicitAny, getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); + } + type = anyType; + } + } + } + if (!popTypeResolution()) { + type = anyType; + if (noImplicitAny) { + var getter_1 = ts.getDeclarationOfKind(symbol, 158); + error(getter_1, ts.Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, symbolToString(symbol)); + } + } + return type; + } + function getBaseTypeVariableOfClass(symbol) { + var baseConstructorType = getBaseConstructorTypeOfClass(getDeclaredTypeOfClassOrInterface(symbol)); + return baseConstructorType.flags & 8650752 ? baseConstructorType : undefined; + } + function getTypeOfFuncClassEnumModule(symbol) { + var links = getSymbolLinks(symbol); + var originalLinks = links; + if (!links.type) { + var jsDeclaration = ts.getDeclarationOfExpando(symbol.valueDeclaration); + if (jsDeclaration) { + var jsSymbol = getSymbolOfNode(jsDeclaration); + if (jsSymbol && (ts.hasEntries(jsSymbol.exports) || ts.hasEntries(jsSymbol.members))) { + symbol = cloneSymbol(symbol); + links = symbol; + if (ts.hasEntries(jsSymbol.exports)) { + symbol.exports = symbol.exports || ts.createSymbolTable(); + mergeSymbolTable(symbol.exports, jsSymbol.exports); + } + if (ts.hasEntries(jsSymbol.members)) { + symbol.members = symbol.members || ts.createSymbolTable(); + mergeSymbolTable(symbol.members, jsSymbol.members); + } + } + } + originalLinks.type = links.type = getTypeOfFuncClassEnumModuleWorker(symbol); + } + return links.type; + } + function getTypeOfFuncClassEnumModuleWorker(symbol) { + var declaration = symbol.valueDeclaration; + if (symbol.flags & 1536 && ts.isShorthandAmbientModuleSymbol(symbol)) { + return anyType; + } + else if (declaration.kind === 204 || + declaration.kind === 189 && declaration.parent.kind === 204) { + return getWidenedTypeFromAssignmentDeclaration(symbol); + } + else if (symbol.flags & 512 && declaration && ts.isSourceFile(declaration) && declaration.commonJsModuleIndicator) { + var resolvedModule = resolveExternalModuleSymbol(symbol); + if (resolvedModule !== symbol) { + if (!pushTypeResolution(symbol, 0)) { + return errorType; + } + var exportEquals = getMergedSymbol(symbol.exports.get("export=")); + var type_2 = getWidenedTypeFromAssignmentDeclaration(exportEquals, exportEquals === resolvedModule ? undefined : resolvedModule); + if (!popTypeResolution()) { + return reportCircularityError(symbol); + } + return type_2; + } + } + var type = createObjectType(16, symbol); + if (symbol.flags & 32) { + var baseTypeVariable = getBaseTypeVariableOfClass(symbol); + return baseTypeVariable ? getIntersectionType([type, baseTypeVariable]) : type; + } + else { + return strictNullChecks && symbol.flags & 16777216 ? getOptionalType(type) : type; + } + } + function getTypeOfEnumMember(symbol) { + var links = getSymbolLinks(symbol); + return links.type || (links.type = getDeclaredTypeOfEnumMember(symbol)); + } + function getTypeOfAlias(symbol) { + var links = getSymbolLinks(symbol); + if (!links.type) { + var targetSymbol = resolveAlias(symbol); + links.type = targetSymbol.flags & 67220415 + ? getTypeOfSymbol(targetSymbol) + : errorType; + } + return links.type; + } + function getTypeOfInstantiatedSymbol(symbol) { + var links = getSymbolLinks(symbol); + if (!links.type) { + if (!pushTypeResolution(symbol, 0)) { + return links.type = errorType; + } + var type = instantiateType(getTypeOfSymbol(links.target), links.mapper); + if (!popTypeResolution()) { + type = reportCircularityError(symbol); + } + links.type = type; + } + return links.type; + } + function reportCircularityError(symbol) { + if (ts.getEffectiveTypeAnnotationNode(symbol.valueDeclaration)) { + error(symbol.valueDeclaration, ts.Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_type_annotation, symbolToString(symbol)); + return errorType; + } + if (noImplicitAny) { + error(symbol.valueDeclaration, ts.Diagnostics._0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer, symbolToString(symbol)); + } + return anyType; + } + function getTypeOfSymbol(symbol) { + if (ts.getCheckFlags(symbol) & 1) { + return getTypeOfInstantiatedSymbol(symbol); + } + if (ts.getCheckFlags(symbol) & 2048) { + return getTypeOfReverseMappedSymbol(symbol); + } + if (symbol.flags & (3 | 4)) { + return getTypeOfVariableOrParameterOrProperty(symbol); + } + if (symbol.flags & (16 | 8192 | 32 | 384 | 512)) { + return getTypeOfFuncClassEnumModule(symbol); + } + if (symbol.flags & 8) { + return getTypeOfEnumMember(symbol); + } + if (symbol.flags & 98304) { + return getTypeOfAccessors(symbol); + } + if (symbol.flags & 2097152) { + return getTypeOfAlias(symbol); + } + return errorType; + } + function isReferenceToType(type, target) { + return type !== undefined + && target !== undefined + && (ts.getObjectFlags(type) & 4) !== 0 + && type.target === target; + } + function getTargetType(type) { + return ts.getObjectFlags(type) & 4 ? type.target : type; + } + function hasBaseType(type, checkBase) { + return check(type); + function check(type) { + if (ts.getObjectFlags(type) & (3 | 4)) { + var target = getTargetType(type); + return target === checkBase || ts.some(getBaseTypes(target), check); + } + else if (type.flags & 2097152) { + return ts.some(type.types, check); + } + return false; + } + } + function appendTypeParameters(typeParameters, declarations) { + for (var _i = 0, declarations_2 = declarations; _i < declarations_2.length; _i++) { + var declaration = declarations_2[_i]; + typeParameters = ts.appendIfUnique(typeParameters, getDeclaredTypeOfTypeParameter(getSymbolOfNode(declaration))); + } + return typeParameters; + } + function getOuterTypeParameters(node, includeThisTypes) { + while (true) { + node = node.parent; + if (!node) { + return undefined; + } + switch (node.kind) { + case 240: + case 209: + case 241: + case 160: + case 161: + case 155: + case 165: + case 166: + case 289: + case 239: + case 156: + case 196: + case 197: + case 242: + case 303: + case 304: + case 297: + case 181: + case 175: + var outerTypeParameters = getOuterTypeParameters(node, includeThisTypes); + if (node.kind === 181) { + return ts.append(outerTypeParameters, getDeclaredTypeOfTypeParameter(getSymbolOfNode(node.typeParameter))); + } + else if (node.kind === 175) { + return ts.concatenate(outerTypeParameters, getInferTypeParameters(node)); + } + var outerAndOwnTypeParameters = appendTypeParameters(outerTypeParameters, ts.getEffectiveTypeParameterDeclarations(node)); + var thisType = includeThisTypes && + (node.kind === 240 || node.kind === 209 || node.kind === 241) && + getDeclaredTypeOfClassOrInterface(getSymbolOfNode(node)).thisType; + return thisType ? ts.append(outerAndOwnTypeParameters, thisType) : outerAndOwnTypeParameters; + } + } + } + function getOuterTypeParametersOfClassOrInterface(symbol) { + var declaration = symbol.flags & 32 ? symbol.valueDeclaration : ts.getDeclarationOfKind(symbol, 241); + return getOuterTypeParameters(declaration); + } + function getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) { + var result; + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var node = _a[_i]; + if (node.kind === 241 || + node.kind === 240 || + node.kind === 209 || + ts.isTypeAlias(node)) { + var declaration = node; + result = appendTypeParameters(result, ts.getEffectiveTypeParameterDeclarations(declaration)); + } + } + return result; + } + function getTypeParametersOfClassOrInterface(symbol) { + return ts.concatenate(getOuterTypeParametersOfClassOrInterface(symbol), getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol)); + } + function isMixinConstructorType(type) { + var signatures = getSignaturesOfType(type, 1); + if (signatures.length === 1) { + var s = signatures[0]; + return !s.typeParameters && s.parameters.length === 1 && s.hasRestParameter && getTypeOfParameter(s.parameters[0]) === anyArrayType; + } + return false; + } + function isConstructorType(type) { + if (isValidBaseType(type) && getSignaturesOfType(type, 1).length > 0) { + return true; + } + if (type.flags & 8650752) { + var constraint = getBaseConstraintOfType(type); + return !!constraint && isValidBaseType(constraint) && isMixinConstructorType(constraint); + } + return isJSConstructorType(type); + } + function getBaseTypeNodeOfClass(type) { + return ts.getEffectiveBaseTypeNode(type.symbol.valueDeclaration); + } + function getConstructorsForTypeArguments(type, typeArgumentNodes, location) { + var typeArgCount = ts.length(typeArgumentNodes); + var isJavascript = ts.isInJSFile(location); + return ts.filter(getSignaturesOfType(type, 1), function (sig) { return (isJavascript || typeArgCount >= getMinTypeArgumentCount(sig.typeParameters)) && typeArgCount <= ts.length(sig.typeParameters); }); + } + function getInstantiatedConstructorsForTypeArguments(type, typeArgumentNodes, location) { + var signatures = getConstructorsForTypeArguments(type, typeArgumentNodes, location); + var typeArguments = ts.map(typeArgumentNodes, getTypeFromTypeNode); + return ts.sameMap(signatures, function (sig) { return ts.some(sig.typeParameters) ? getSignatureInstantiation(sig, typeArguments, ts.isInJSFile(location)) : sig; }); + } + function getBaseConstructorTypeOfClass(type) { + if (!type.resolvedBaseConstructorType) { + var decl = type.symbol.valueDeclaration; + var extended = ts.getEffectiveBaseTypeNode(decl); + var baseTypeNode = getBaseTypeNodeOfClass(type); + if (!baseTypeNode) { + return type.resolvedBaseConstructorType = undefinedType; + } + if (!pushTypeResolution(type, 1)) { + return errorType; + } + var baseConstructorType = checkExpression(baseTypeNode.expression); + if (extended && baseTypeNode !== extended) { + ts.Debug.assert(!extended.typeArguments); + checkExpression(extended.expression); + } + if (baseConstructorType.flags & (524288 | 2097152)) { + resolveStructuredTypeMembers(baseConstructorType); + } + if (!popTypeResolution()) { + error(type.symbol.valueDeclaration, ts.Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_base_expression, symbolToString(type.symbol)); + return type.resolvedBaseConstructorType = errorType; + } + if (!(baseConstructorType.flags & 1) && baseConstructorType !== nullWideningType && !isConstructorType(baseConstructorType)) { + var err = error(baseTypeNode.expression, ts.Diagnostics.Type_0_is_not_a_constructor_function_type, typeToString(baseConstructorType)); + if (baseConstructorType.flags & 262144) { + var constraint = getConstraintFromTypeParameter(baseConstructorType); + var ctorReturn = unknownType; + if (constraint) { + var ctorSig = getSignaturesOfType(constraint, 1); + if (ctorSig[0]) { + ctorReturn = getReturnTypeOfSignature(ctorSig[0]); + } + } + addRelatedInfo(err, ts.createDiagnosticForNode(baseConstructorType.symbol.declarations[0], ts.Diagnostics.Did_you_mean_for_0_to_be_constrained_to_type_new_args_Colon_any_1, symbolToString(baseConstructorType.symbol), typeToString(ctorReturn))); + } + return type.resolvedBaseConstructorType = errorType; + } + type.resolvedBaseConstructorType = baseConstructorType; + } + return type.resolvedBaseConstructorType; + } + function getBaseTypes(type) { + if (!type.resolvedBaseTypes) { + if (type.objectFlags & 8) { + type.resolvedBaseTypes = [createArrayType(getUnionType(type.typeParameters || ts.emptyArray))]; + } + else if (type.symbol.flags & (32 | 64)) { + if (type.symbol.flags & 32) { + resolveBaseTypesOfClass(type); + } + if (type.symbol.flags & 64) { + resolveBaseTypesOfInterface(type); + } + } + else { + ts.Debug.fail("type must be class or interface"); + } + } + return type.resolvedBaseTypes; + } + function resolveBaseTypesOfClass(type) { + type.resolvedBaseTypes = ts.resolvingEmptyArray; + var baseConstructorType = getApparentType(getBaseConstructorTypeOfClass(type)); + if (!(baseConstructorType.flags & (524288 | 2097152 | 1))) { + return type.resolvedBaseTypes = ts.emptyArray; + } + var baseTypeNode = getBaseTypeNodeOfClass(type); + var typeArgs = typeArgumentsFromTypeReferenceNode(baseTypeNode); + var baseType; + var originalBaseType = isJSConstructorType(baseConstructorType) ? baseConstructorType : + baseConstructorType.symbol ? getDeclaredTypeOfSymbol(baseConstructorType.symbol) : + undefined; + if (baseConstructorType.symbol && baseConstructorType.symbol.flags & 32 && + areAllOuterTypeParametersApplied(originalBaseType)) { + baseType = getTypeFromClassOrInterfaceReference(baseTypeNode, baseConstructorType.symbol, typeArgs); + } + else if (baseConstructorType.flags & 1) { + baseType = baseConstructorType; + } + else if (isJSConstructorType(baseConstructorType)) { + baseType = !baseTypeNode.typeArguments && getJSClassType(baseConstructorType.symbol) || anyType; + } + else { + var constructors = getInstantiatedConstructorsForTypeArguments(baseConstructorType, baseTypeNode.typeArguments, baseTypeNode); + if (!constructors.length) { + error(baseTypeNode.expression, ts.Diagnostics.No_base_constructor_has_the_specified_number_of_type_arguments); + return type.resolvedBaseTypes = ts.emptyArray; + } + baseType = getReturnTypeOfSignature(constructors[0]); + } + if (baseType === errorType) { + return type.resolvedBaseTypes = ts.emptyArray; + } + if (!isValidBaseType(baseType)) { + error(baseTypeNode.expression, ts.Diagnostics.Base_constructor_return_type_0_is_not_an_object_type_or_intersection_of_object_types_with_statically_known_members, typeToString(baseType)); + return type.resolvedBaseTypes = ts.emptyArray; + } + if (type === baseType || hasBaseType(baseType, type)) { + error(type.symbol.valueDeclaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, undefined, 2)); + return type.resolvedBaseTypes = ts.emptyArray; + } + if (type.resolvedBaseTypes === ts.resolvingEmptyArray) { + type.members = undefined; + } + return type.resolvedBaseTypes = [baseType]; + } + function areAllOuterTypeParametersApplied(type) { + var outerTypeParameters = type.outerTypeParameters; + if (outerTypeParameters) { + var last_1 = outerTypeParameters.length - 1; + var typeArguments = type.typeArguments; + return outerTypeParameters[last_1].symbol !== typeArguments[last_1].symbol; + } + return true; + } + function isValidBaseType(type) { + return !!(type.flags & (524288 | 67108864 | 1)) && !isGenericMappedType(type) || + !!(type.flags & 2097152) && ts.every(type.types, isValidBaseType); + } + function resolveBaseTypesOfInterface(type) { + type.resolvedBaseTypes = type.resolvedBaseTypes || ts.emptyArray; + for (var _i = 0, _a = type.symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (declaration.kind === 241 && ts.getInterfaceBaseTypeNodes(declaration)) { + for (var _b = 0, _c = ts.getInterfaceBaseTypeNodes(declaration); _b < _c.length; _b++) { + var node = _c[_b]; + var baseType = getTypeFromTypeNode(node); + if (baseType !== errorType) { + if (isValidBaseType(baseType)) { + if (type !== baseType && !hasBaseType(baseType, type)) { + if (type.resolvedBaseTypes === ts.emptyArray) { + type.resolvedBaseTypes = [baseType]; + } + else { + type.resolvedBaseTypes.push(baseType); + } + } + else { + error(declaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, undefined, 2)); + } + } + else { + error(node, ts.Diagnostics.An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_members); + } + } + } + } + } + } + function isThislessInterface(symbol) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (declaration.kind === 241) { + if (declaration.flags & 64) { + return false; + } + var baseTypeNodes = ts.getInterfaceBaseTypeNodes(declaration); + if (baseTypeNodes) { + for (var _b = 0, baseTypeNodes_1 = baseTypeNodes; _b < baseTypeNodes_1.length; _b++) { + var node = baseTypeNodes_1[_b]; + if (ts.isEntityNameExpression(node.expression)) { + var baseSymbol = resolveEntityName(node.expression, 67897832, true); + if (!baseSymbol || !(baseSymbol.flags & 64) || getDeclaredTypeOfClassOrInterface(baseSymbol).thisType) { + return false; + } + } + } + } + } + } + return true; + } + function getDeclaredTypeOfClassOrInterface(symbol) { + var links = getSymbolLinks(symbol); + if (!links.declaredType) { + var kind = symbol.flags & 32 ? 1 : 2; + var type = links.declaredType = createObjectType(kind, symbol); + var outerTypeParameters = getOuterTypeParametersOfClassOrInterface(symbol); + var localTypeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); + if (outerTypeParameters || localTypeParameters || kind === 1 || !isThislessInterface(symbol)) { + type.objectFlags |= 4; + type.typeParameters = ts.concatenate(outerTypeParameters, localTypeParameters); + type.outerTypeParameters = outerTypeParameters; + type.localTypeParameters = localTypeParameters; + type.instantiations = ts.createMap(); + type.instantiations.set(getTypeListId(type.typeParameters), type); + type.target = type; + type.typeArguments = type.typeParameters; + type.thisType = createType(262144); + type.thisType.isThisType = true; + type.thisType.symbol = symbol; + type.thisType.constraint = type; + } + } + return links.declaredType; + } + function getDeclaredTypeOfTypeAlias(symbol) { + var links = getSymbolLinks(symbol); + if (!links.declaredType) { + if (!pushTypeResolution(symbol, 2)) { + return errorType; + } + var declaration = ts.find(symbol.declarations, function (d) { + return ts.isJSDocTypeAlias(d) || d.kind === 242; + }); + var typeNode = ts.isJSDocTypeAlias(declaration) ? declaration.typeExpression : declaration.type; + var type = typeNode ? getTypeFromTypeNode(typeNode) : errorType; + if (popTypeResolution()) { + var typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); + if (typeParameters) { + links.typeParameters = typeParameters; + links.instantiations = ts.createMap(); + links.instantiations.set(getTypeListId(typeParameters), type); + } + } + else { + type = errorType; + error(declaration.name, ts.Diagnostics.Type_alias_0_circularly_references_itself, symbolToString(symbol)); + } + links.declaredType = type; + } + return links.declaredType; + } + function isStringConcatExpression(expr) { + if (expr.kind === 10) { + return true; + } + else if (expr.kind === 204) { + return isStringConcatExpression(expr.left) && isStringConcatExpression(expr.right); + } + return false; + } + function isLiteralEnumMember(member) { + var expr = member.initializer; + if (!expr) { + return !(member.flags & 4194304); + } + switch (expr.kind) { + case 10: + case 8: + return true; + case 202: + return expr.operator === 39 && + expr.operand.kind === 8; + case 72: + return ts.nodeIsMissing(expr) || !!getSymbolOfNode(member.parent).exports.get(expr.escapedText); + case 204: + return isStringConcatExpression(expr); + default: + return false; + } + } + function getEnumKind(symbol) { + var links = getSymbolLinks(symbol); + if (links.enumKind !== undefined) { + return links.enumKind; + } + var hasNonLiteralMember = false; + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (declaration.kind === 243) { + for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { + var member = _c[_b]; + if (member.initializer && member.initializer.kind === 10) { + return links.enumKind = 1; + } + if (!isLiteralEnumMember(member)) { + hasNonLiteralMember = true; + } + } + } + } + return links.enumKind = hasNonLiteralMember ? 0 : 1; + } + function getBaseTypeOfEnumLiteralType(type) { + return type.flags & 1024 && !(type.flags & 1048576) ? getDeclaredTypeOfSymbol(getParentOfSymbol(type.symbol)) : type; + } + function getDeclaredTypeOfEnum(symbol) { + var links = getSymbolLinks(symbol); + if (links.declaredType) { + return links.declaredType; + } + if (getEnumKind(symbol) === 1) { + enumCount++; + var memberTypeList = []; + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (declaration.kind === 243) { + for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { + var member = _c[_b]; + var memberType = getFreshTypeOfLiteralType(getLiteralType(getEnumMemberValue(member), enumCount, getSymbolOfNode(member))); + getSymbolLinks(getSymbolOfNode(member)).declaredType = memberType; + memberTypeList.push(getRegularTypeOfLiteralType(memberType)); + } + } + } + if (memberTypeList.length) { + var enumType_1 = getUnionType(memberTypeList, 1, symbol, undefined); + if (enumType_1.flags & 1048576) { + enumType_1.flags |= 1024; + enumType_1.symbol = symbol; + } + return links.declaredType = enumType_1; + } + } + var enumType = createType(32); + enumType.symbol = symbol; + return links.declaredType = enumType; + } + function getDeclaredTypeOfEnumMember(symbol) { + var links = getSymbolLinks(symbol); + if (!links.declaredType) { + var enumType = getDeclaredTypeOfEnum(getParentOfSymbol(symbol)); + if (!links.declaredType) { + links.declaredType = enumType; + } + } + return links.declaredType; + } + function getDeclaredTypeOfTypeParameter(symbol) { + var links = getSymbolLinks(symbol); + if (!links.declaredType) { + var type = createType(262144); + type.symbol = symbol; + links.declaredType = type; + } + return links.declaredType; + } + function getDeclaredTypeOfAlias(symbol) { + var links = getSymbolLinks(symbol); + if (!links.declaredType) { + links.declaredType = getDeclaredTypeOfSymbol(resolveAlias(symbol)); + } + return links.declaredType; + } + function getDeclaredTypeOfSymbol(symbol) { + return tryGetDeclaredTypeOfSymbol(symbol) || errorType; + } + function tryGetDeclaredTypeOfSymbol(symbol) { + if (symbol.flags & (32 | 64)) { + return getDeclaredTypeOfClassOrInterface(symbol); + } + if (symbol.flags & 524288) { + return getDeclaredTypeOfTypeAlias(symbol); + } + if (symbol.flags & 262144) { + return getDeclaredTypeOfTypeParameter(symbol); + } + if (symbol.flags & 384) { + return getDeclaredTypeOfEnum(symbol); + } + if (symbol.flags & 8) { + return getDeclaredTypeOfEnumMember(symbol); + } + if (symbol.flags & 2097152) { + return getDeclaredTypeOfAlias(symbol); + } + return undefined; + } + function isThislessType(node) { + switch (node.kind) { + case 120: + case 143: + case 138: + case 135: + case 146: + case 123: + case 139: + case 136: + case 106: + case 141: + case 96: + case 132: + case 182: + return true; + case 169: + return isThislessType(node.elementType); + case 164: + return !node.typeArguments || node.typeArguments.every(isThislessType); + } + return false; + } + function isThislessTypeParameter(node) { + var constraint = ts.getEffectiveConstraintOfTypeParameter(node); + return !constraint || isThislessType(constraint); + } + function isThislessVariableLikeDeclaration(node) { + var typeNode = ts.getEffectiveTypeAnnotationNode(node); + return typeNode ? isThislessType(typeNode) : !ts.hasInitializer(node); + } + function isThislessFunctionLikeDeclaration(node) { + var returnType = ts.getEffectiveReturnTypeNode(node); + var typeParameters = ts.getEffectiveTypeParameterDeclarations(node); + return (node.kind === 157 || (!!returnType && isThislessType(returnType))) && + node.parameters.every(isThislessVariableLikeDeclaration) && + typeParameters.every(isThislessTypeParameter); + } + function isThisless(symbol) { + if (symbol.declarations && symbol.declarations.length === 1) { + var declaration = symbol.declarations[0]; + if (declaration) { + switch (declaration.kind) { + case 154: + case 153: + return isThislessVariableLikeDeclaration(declaration); + case 156: + case 155: + case 157: + return isThislessFunctionLikeDeclaration(declaration); + } + } + } + return false; + } + function createInstantiatedSymbolTable(symbols, mapper, mappingThisOnly) { + var result = ts.createSymbolTable(); + for (var _i = 0, symbols_2 = symbols; _i < symbols_2.length; _i++) { + var symbol = symbols_2[_i]; + result.set(symbol.escapedName, mappingThisOnly && isThisless(symbol) ? symbol : instantiateSymbol(symbol, mapper)); + } + return result; + } + function addInheritedMembers(symbols, baseSymbols) { + for (var _i = 0, baseSymbols_1 = baseSymbols; _i < baseSymbols_1.length; _i++) { + var s = baseSymbols_1[_i]; + if (!symbols.has(s.escapedName)) { + symbols.set(s.escapedName, s); + } + } + } + function resolveDeclaredMembers(type) { + if (!type.declaredProperties) { + var symbol = type.symbol; + var members = getMembersOfSymbol(symbol); + type.declaredProperties = getNamedMembers(members); + type.declaredCallSignatures = ts.emptyArray; + type.declaredConstructSignatures = ts.emptyArray; + type.declaredCallSignatures = getSignaturesOfSymbol(members.get("__call")); + type.declaredConstructSignatures = getSignaturesOfSymbol(members.get("__new")); + type.declaredStringIndexInfo = getIndexInfoOfSymbol(symbol, 0); + type.declaredNumberIndexInfo = getIndexInfoOfSymbol(symbol, 1); + } + return type; + } + function isTypeUsableAsLateBoundName(type) { + return !!(type.flags & 8576); + } + function isLateBindableName(node) { + return ts.isComputedPropertyName(node) + && ts.isEntityNameExpression(node.expression) + && isTypeUsableAsLateBoundName(checkComputedPropertyName(node)); + } + function isLateBoundName(name) { + return name.charCodeAt(0) === 95 && + name.charCodeAt(1) === 95 && + name.charCodeAt(2) === 64; + } + function hasLateBindableName(node) { + var name = ts.getNameOfDeclaration(node); + return !!name && isLateBindableName(name); + } + function hasNonBindableDynamicName(node) { + return ts.hasDynamicName(node) && !hasLateBindableName(node); + } + function isNonBindableDynamicName(node) { + return ts.isDynamicName(node) && !isLateBindableName(node); + } + function getLateBoundNameFromType(type) { + if (type.flags & 8192) { + return "__@" + type.symbol.escapedName + "@" + getSymbolId(type.symbol); + } + if (type.flags & (128 | 256)) { + return ts.escapeLeadingUnderscores("" + type.value); + } + return ts.Debug.fail(); + } + function addDeclarationToLateBoundSymbol(symbol, member, symbolFlags) { + ts.Debug.assert(!!(ts.getCheckFlags(symbol) & 1024), "Expected a late-bound symbol."); + symbol.flags |= symbolFlags; + getSymbolLinks(member.symbol).lateSymbol = symbol; + if (!symbol.declarations) { + symbol.declarations = [member]; + } + else { + symbol.declarations.push(member); + } + if (symbolFlags & 67220415) { + if (!symbol.valueDeclaration || symbol.valueDeclaration.kind !== member.kind) { + symbol.valueDeclaration = member; + } + } + } + function lateBindMember(parent, earlySymbols, lateSymbols, decl) { + ts.Debug.assert(!!decl.symbol, "The member is expected to have a symbol."); + var links = getNodeLinks(decl); + if (!links.resolvedSymbol) { + links.resolvedSymbol = decl.symbol; + var type = checkComputedPropertyName(decl.name); + if (isTypeUsableAsLateBoundName(type)) { + var memberName = getLateBoundNameFromType(type); + var symbolFlags = decl.symbol.flags; + var lateSymbol = lateSymbols.get(memberName); + if (!lateSymbol) + lateSymbols.set(memberName, lateSymbol = createSymbol(0, memberName, 1024)); + var earlySymbol = earlySymbols && earlySymbols.get(memberName); + if (lateSymbol.flags & getExcludedSymbolFlags(symbolFlags) || earlySymbol) { + var declarations = earlySymbol ? ts.concatenate(earlySymbol.declarations, lateSymbol.declarations) : lateSymbol.declarations; + var name_2 = ts.declarationNameToString(decl.name); + ts.forEach(declarations, function (declaration) { return error(ts.getNameOfDeclaration(declaration) || declaration, ts.Diagnostics.Duplicate_declaration_0, name_2); }); + error(decl.name || decl, ts.Diagnostics.Duplicate_declaration_0, name_2); + lateSymbol = createSymbol(0, memberName, 1024); + } + lateSymbol.nameType = type; + addDeclarationToLateBoundSymbol(lateSymbol, decl, symbolFlags); + if (lateSymbol.parent) { + ts.Debug.assert(lateSymbol.parent === parent, "Existing symbol parent should match new one"); + } + else { + lateSymbol.parent = parent; + } + return links.resolvedSymbol = lateSymbol; + } + } + return links.resolvedSymbol; + } + function getResolvedMembersOrExportsOfSymbol(symbol, resolutionKind) { + var links = getSymbolLinks(symbol); + if (!links[resolutionKind]) { + var isStatic = resolutionKind === "resolvedExports"; + var earlySymbols = !isStatic ? symbol.members : + symbol.flags & 1536 ? getExportsOfModuleWorker(symbol) : + symbol.exports; + links[resolutionKind] = earlySymbols || emptySymbols; + var lateSymbols = ts.createSymbolTable(); + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + var members = ts.getMembersOfDeclaration(decl); + if (members) { + for (var _b = 0, members_4 = members; _b < members_4.length; _b++) { + var member = members_4[_b]; + if (isStatic === ts.hasStaticModifier(member) && hasLateBindableName(member)) { + lateBindMember(symbol, earlySymbols, lateSymbols, member); + } + } + } + } + links[resolutionKind] = combineSymbolTables(earlySymbols, lateSymbols) || emptySymbols; + } + return links[resolutionKind]; + } + function getMembersOfSymbol(symbol) { + return symbol.flags & 6240 + ? getResolvedMembersOrExportsOfSymbol(symbol, "resolvedMembers") + : symbol.members || emptySymbols; + } + function getLateBoundSymbol(symbol) { + if (symbol.flags & 106500 && symbol.escapedName === "__computed") { + var links = getSymbolLinks(symbol); + if (!links.lateSymbol && ts.some(symbol.declarations, hasLateBindableName)) { + if (ts.some(symbol.declarations, ts.hasStaticModifier)) { + getExportsOfSymbol(symbol.parent); + } + else { + getMembersOfSymbol(symbol.parent); + } + } + return links.lateSymbol || (links.lateSymbol = symbol); + } + return symbol; + } + function getTypeWithThisArgument(type, thisArgument, needApparentType) { + if (ts.getObjectFlags(type) & 4) { + var target = type.target; + var typeArguments = type.typeArguments; + if (ts.length(target.typeParameters) === ts.length(typeArguments)) { + var ref = createTypeReference(target, ts.concatenate(typeArguments, [thisArgument || target.thisType])); + return needApparentType ? getApparentType(ref) : ref; + } + } + else if (type.flags & 2097152) { + return getIntersectionType(ts.map(type.types, function (t) { return getTypeWithThisArgument(t, thisArgument, needApparentType); })); + } + return needApparentType ? getApparentType(type) : type; + } + function resolveObjectTypeMembers(type, source, typeParameters, typeArguments) { + var mapper; + var members; + var callSignatures; + var constructSignatures; + var stringIndexInfo; + var numberIndexInfo; + if (ts.rangeEquals(typeParameters, typeArguments, 0, typeParameters.length)) { + mapper = identityMapper; + members = source.symbol ? getMembersOfSymbol(source.symbol) : ts.createSymbolTable(source.declaredProperties); + callSignatures = source.declaredCallSignatures; + constructSignatures = source.declaredConstructSignatures; + stringIndexInfo = source.declaredStringIndexInfo; + numberIndexInfo = source.declaredNumberIndexInfo; + } + else { + mapper = createTypeMapper(typeParameters, typeArguments); + members = createInstantiatedSymbolTable(source.declaredProperties, mapper, typeParameters.length === 1); + callSignatures = instantiateSignatures(source.declaredCallSignatures, mapper); + constructSignatures = instantiateSignatures(source.declaredConstructSignatures, mapper); + stringIndexInfo = instantiateIndexInfo(source.declaredStringIndexInfo, mapper); + numberIndexInfo = instantiateIndexInfo(source.declaredNumberIndexInfo, mapper); + } + var baseTypes = getBaseTypes(source); + if (baseTypes.length) { + if (source.symbol && members === getMembersOfSymbol(source.symbol)) { + members = ts.createSymbolTable(source.declaredProperties); + } + setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + var thisArgument = ts.lastOrUndefined(typeArguments); + for (var _i = 0, baseTypes_1 = baseTypes; _i < baseTypes_1.length; _i++) { + var baseType = baseTypes_1[_i]; + var instantiatedBaseType = thisArgument ? getTypeWithThisArgument(instantiateType(baseType, mapper), thisArgument) : baseType; + addInheritedMembers(members, getPropertiesOfType(instantiatedBaseType)); + callSignatures = ts.concatenate(callSignatures, getSignaturesOfType(instantiatedBaseType, 0)); + constructSignatures = ts.concatenate(constructSignatures, getSignaturesOfType(instantiatedBaseType, 1)); + if (!stringIndexInfo) { + stringIndexInfo = instantiatedBaseType === anyType ? + createIndexInfo(anyType, false) : + getIndexInfoOfType(instantiatedBaseType, 0); + } + numberIndexInfo = numberIndexInfo || getIndexInfoOfType(instantiatedBaseType, 1); + } + } + setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + } + function resolveClassOrInterfaceMembers(type) { + resolveObjectTypeMembers(type, resolveDeclaredMembers(type), ts.emptyArray, ts.emptyArray); + } + function resolveTypeReferenceMembers(type) { + var source = resolveDeclaredMembers(type.target); + var typeParameters = ts.concatenate(source.typeParameters, [source.thisType]); + var typeArguments = type.typeArguments && type.typeArguments.length === typeParameters.length ? + type.typeArguments : ts.concatenate(type.typeArguments, [type]); + resolveObjectTypeMembers(type, source, typeParameters, typeArguments); + } + function createSignature(declaration, typeParameters, thisParameter, parameters, resolvedReturnType, resolvedTypePredicate, minArgumentCount, hasRestParameter, hasLiteralTypes) { + var sig = new Signature(checker); + sig.declaration = declaration; + sig.typeParameters = typeParameters; + sig.parameters = parameters; + sig.thisParameter = thisParameter; + sig.resolvedReturnType = resolvedReturnType; + sig.resolvedTypePredicate = resolvedTypePredicate; + sig.minArgumentCount = minArgumentCount; + sig.hasRestParameter = hasRestParameter; + sig.hasLiteralTypes = hasLiteralTypes; + sig.target = undefined; + sig.mapper = undefined; + return sig; + } + function cloneSignature(sig) { + return createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, undefined, undefined, sig.minArgumentCount, sig.hasRestParameter, sig.hasLiteralTypes); + } + function getExpandedParameters(sig) { + if (sig.hasRestParameter) { + var restIndex_1 = sig.parameters.length - 1; + var restParameter = sig.parameters[restIndex_1]; + var restType = getTypeOfSymbol(restParameter); + if (isTupleType(restType)) { + var elementTypes = restType.typeArguments || ts.emptyArray; + var minLength_1 = restType.target.minLength; + var tupleRestIndex_1 = restType.target.hasRestElement ? elementTypes.length - 1 : -1; + var restParams = ts.map(elementTypes, function (t, i) { + var name = getParameterNameAtPosition(sig, restIndex_1 + i); + var checkFlags = i === tupleRestIndex_1 ? 8192 : + i >= minLength_1 ? 4096 : 0; + var symbol = createSymbol(1, name, checkFlags); + symbol.type = i === tupleRestIndex_1 ? createArrayType(t) : t; + return symbol; + }); + return ts.concatenate(sig.parameters.slice(0, restIndex_1), restParams); + } + } + return sig.parameters; + } + function getDefaultConstructSignatures(classType) { + var baseConstructorType = getBaseConstructorTypeOfClass(classType); + var baseSignatures = getSignaturesOfType(baseConstructorType, 1); + if (baseSignatures.length === 0) { + return [createSignature(undefined, classType.localTypeParameters, undefined, ts.emptyArray, classType, undefined, 0, false, false)]; + } + var baseTypeNode = getBaseTypeNodeOfClass(classType); + var isJavaScript = ts.isInJSFile(baseTypeNode); + var typeArguments = typeArgumentsFromTypeReferenceNode(baseTypeNode); + var typeArgCount = ts.length(typeArguments); + var result = []; + for (var _i = 0, baseSignatures_1 = baseSignatures; _i < baseSignatures_1.length; _i++) { + var baseSig = baseSignatures_1[_i]; + var minTypeArgumentCount = getMinTypeArgumentCount(baseSig.typeParameters); + var typeParamCount = ts.length(baseSig.typeParameters); + if (isJavaScript || typeArgCount >= minTypeArgumentCount && typeArgCount <= typeParamCount) { + var sig = typeParamCount ? createSignatureInstantiation(baseSig, fillMissingTypeArguments(typeArguments, baseSig.typeParameters, minTypeArgumentCount, isJavaScript)) : cloneSignature(baseSig); + sig.typeParameters = classType.localTypeParameters; + sig.resolvedReturnType = classType; + result.push(sig); + } + } + return result; + } + function findMatchingSignature(signatureList, signature, partialMatch, ignoreThisTypes, ignoreReturnTypes) { + for (var _i = 0, signatureList_1 = signatureList; _i < signatureList_1.length; _i++) { + var s = signatureList_1[_i]; + if (compareSignaturesIdentical(s, signature, partialMatch, ignoreThisTypes, ignoreReturnTypes, partialMatch ? compareTypesSubtypeOf : compareTypesIdentical)) { + return s; + } + } + } + function findMatchingSignatures(signatureLists, signature, listIndex) { + if (signature.typeParameters) { + if (listIndex > 0) { + return undefined; + } + for (var i = 1; i < signatureLists.length; i++) { + if (!findMatchingSignature(signatureLists[i], signature, false, false, false)) { + return undefined; + } + } + return [signature]; + } + var result; + for (var i = 0; i < signatureLists.length; i++) { + var match = i === listIndex ? signature : findMatchingSignature(signatureLists[i], signature, true, true, true); + if (!match) { + return undefined; + } + result = ts.appendIfUnique(result, match); + } + return result; + } + function getUnionSignatures(signatureLists) { + var result; + for (var i = 0; i < signatureLists.length; i++) { + for (var _i = 0, _a = signatureLists[i]; _i < _a.length; _i++) { + var signature = _a[_i]; + if (!result || !findMatchingSignature(result, signature, false, true, true)) { + var unionSignatures = findMatchingSignatures(signatureLists, signature, i); + if (unionSignatures) { + var s = signature; + if (unionSignatures.length > 1) { + var thisParameter = signature.thisParameter; + if (ts.forEach(unionSignatures, function (sig) { return sig.thisParameter; })) { + var thisType = getUnionType(ts.map(unionSignatures, function (sig) { return sig.thisParameter ? getTypeOfSymbol(sig.thisParameter) : anyType; }), 2); + thisParameter = createSymbolWithType(signature.thisParameter, thisType); + } + s = cloneSignature(signature); + s.thisParameter = thisParameter; + s.unionSignatures = unionSignatures; + } + (result || (result = [])).push(s); + } + } + } + } + return result || ts.emptyArray; + } + function getUnionIndexInfo(types, kind) { + var indexTypes = []; + var isAnyReadonly = false; + for (var _i = 0, types_2 = types; _i < types_2.length; _i++) { + var type = types_2[_i]; + var indexInfo = getIndexInfoOfType(type, kind); + if (!indexInfo) { + return undefined; + } + indexTypes.push(indexInfo.type); + isAnyReadonly = isAnyReadonly || indexInfo.isReadonly; + } + return createIndexInfo(getUnionType(indexTypes, 2), isAnyReadonly); + } + function resolveUnionTypeMembers(type) { + var callSignatures = getUnionSignatures(ts.map(type.types, function (t) { return getSignaturesOfType(t, 0); })); + var constructSignatures = getUnionSignatures(ts.map(type.types, function (t) { return getSignaturesOfType(t, 1); })); + var stringIndexInfo = getUnionIndexInfo(type.types, 0); + var numberIndexInfo = getUnionIndexInfo(type.types, 1); + setStructuredTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + } + function intersectTypes(type1, type2) { + return !type1 ? type2 : !type2 ? type1 : getIntersectionType([type1, type2]); + } + function intersectIndexInfos(info1, info2) { + return !info1 ? info2 : !info2 ? info1 : createIndexInfo(getIntersectionType([info1.type, info2.type]), info1.isReadonly && info2.isReadonly); + } + function unionSpreadIndexInfos(info1, info2) { + return info1 && info2 && createIndexInfo(getUnionType([info1.type, info2.type]), info1.isReadonly || info2.isReadonly); + } + function includeMixinType(type, types, index) { + var mixedTypes = []; + for (var i = 0; i < types.length; i++) { + if (i === index) { + mixedTypes.push(type); + } + else if (isMixinConstructorType(types[i])) { + mixedTypes.push(getReturnTypeOfSignature(getSignaturesOfType(types[i], 1)[0])); + } + } + return getIntersectionType(mixedTypes); + } + function resolveIntersectionTypeMembers(type) { + var callSignatures = ts.emptyArray; + var constructSignatures = ts.emptyArray; + var stringIndexInfo; + var numberIndexInfo; + var types = type.types; + var mixinCount = ts.countWhere(types, isMixinConstructorType); + var _loop_5 = function (i) { + var t = type.types[i]; + if (mixinCount === 0 || mixinCount === types.length && i === 0 || !isMixinConstructorType(t)) { + var signatures = getSignaturesOfType(t, 1); + if (signatures.length && mixinCount > 0) { + signatures = ts.map(signatures, function (s) { + var clone = cloneSignature(s); + clone.resolvedReturnType = includeMixinType(getReturnTypeOfSignature(s), types, i); + return clone; + }); + } + constructSignatures = ts.concatenate(constructSignatures, signatures); + } + callSignatures = ts.concatenate(callSignatures, getSignaturesOfType(t, 0)); + stringIndexInfo = intersectIndexInfos(stringIndexInfo, getIndexInfoOfType(t, 0)); + numberIndexInfo = intersectIndexInfos(numberIndexInfo, getIndexInfoOfType(t, 1)); + }; + for (var i = 0; i < types.length; i++) { + _loop_5(i); + } + setStructuredTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + } + function resolveAnonymousTypeMembers(type) { + var symbol = type.symbol; + if (type.target) { + setStructuredTypeMembers(type, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + var members = createInstantiatedSymbolTable(getPropertiesOfObjectType(type.target), type.mapper, false); + var callSignatures = instantiateSignatures(getSignaturesOfType(type.target, 0), type.mapper); + var constructSignatures = instantiateSignatures(getSignaturesOfType(type.target, 1), type.mapper); + var stringIndexInfo = instantiateIndexInfo(getIndexInfoOfType(type.target, 0), type.mapper); + var numberIndexInfo = instantiateIndexInfo(getIndexInfoOfType(type.target, 1), type.mapper); + setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + } + else if (symbol.flags & 2048) { + setStructuredTypeMembers(type, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + var members = getMembersOfSymbol(symbol); + var callSignatures = getSignaturesOfSymbol(members.get("__call")); + var constructSignatures = getSignaturesOfSymbol(members.get("__new")); + var stringIndexInfo = getIndexInfoOfSymbol(symbol, 0); + var numberIndexInfo = getIndexInfoOfSymbol(symbol, 1); + setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + } + else { + var members = emptySymbols; + var stringIndexInfo = void 0; + if (symbol.exports) { + members = getExportsOfSymbol(symbol); + } + setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, undefined, undefined); + if (symbol.flags & 32) { + var classType = getDeclaredTypeOfClassOrInterface(symbol); + var baseConstructorType = getBaseConstructorTypeOfClass(classType); + if (baseConstructorType.flags & (524288 | 2097152 | 8650752)) { + members = ts.createSymbolTable(getNamedMembers(members)); + addInheritedMembers(members, getPropertiesOfType(baseConstructorType)); + } + else if (baseConstructorType === anyType) { + stringIndexInfo = createIndexInfo(anyType, false); + } + } + var numberIndexInfo = symbol.flags & 384 ? enumNumberIndexInfo : undefined; + setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); + if (symbol.flags & (16 | 8192)) { + type.callSignatures = getSignaturesOfSymbol(symbol); + type.constructSignatures = ts.filter(type.callSignatures, function (sig) { return isJSConstructor(sig.declaration); }); + } + if (symbol.flags & 32) { + var classType = getDeclaredTypeOfClassOrInterface(symbol); + var constructSignatures = getSignaturesOfSymbol(symbol.members.get("__constructor")); + if (!constructSignatures.length) { + constructSignatures = getDefaultConstructSignatures(classType); + } + type.constructSignatures = constructSignatures; + } + } + } + function resolveReverseMappedTypeMembers(type) { + var indexInfo = getIndexInfoOfType(type.source, 0); + var modifiers = getMappedTypeModifiers(type.mappedType); + var readonlyMask = modifiers & 1 ? false : true; + var optionalMask = modifiers & 4 ? 0 : 16777216; + var stringIndexInfo = indexInfo && createIndexInfo(inferReverseMappedType(indexInfo.type, type.mappedType, type.constraintType), readonlyMask && indexInfo.isReadonly); + var members = ts.createSymbolTable(); + for (var _i = 0, _a = getPropertiesOfType(type.source); _i < _a.length; _i++) { + var prop = _a[_i]; + var checkFlags = 2048 | (readonlyMask && isReadonlySymbol(prop) ? 8 : 0); + var inferredProp = createSymbol(4 | prop.flags & optionalMask, prop.escapedName, checkFlags); + inferredProp.declarations = prop.declarations; + inferredProp.nameType = prop.nameType; + inferredProp.propertyType = getTypeOfSymbol(prop); + inferredProp.mappedType = type.mappedType; + inferredProp.constraintType = type.constraintType; + members.set(prop.escapedName, inferredProp); + } + setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, undefined); + } + function resolveMappedTypeMembers(type) { + var members = ts.createSymbolTable(); + var stringIndexInfo; + var numberIndexInfo; + setStructuredTypeMembers(type, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + var typeParameter = getTypeParameterFromMappedType(type); + var constraintType = getConstraintTypeFromMappedType(type); + var templateType = getTemplateTypeFromMappedType(type.target || type); + var modifiersType = getApparentType(getModifiersTypeFromMappedType(type)); + var templateModifiers = getMappedTypeModifiers(type); + var include = keyofStringsOnly ? 128 : 8576; + if (isMappedTypeWithKeyofConstraintDeclaration(type)) { + for (var _i = 0, _a = getPropertiesOfType(modifiersType); _i < _a.length; _i++) { + var prop = _a[_i]; + addMemberForKeyType(getLiteralTypeFromProperty(prop, include)); + } + if (modifiersType.flags & 1 || getIndexInfoOfType(modifiersType, 0)) { + addMemberForKeyType(stringType); + } + if (!keyofStringsOnly && getIndexInfoOfType(modifiersType, 1)) { + addMemberForKeyType(numberType); + } + } + else { + var iterationType = constraintType.flags & 4194304 ? getIndexType(getApparentType(constraintType.type)) : constraintType; + forEachType(iterationType, addMemberForKeyType); + } + setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); + function addMemberForKeyType(t) { + var templateMapper = combineTypeMappers(type.mapper, createTypeMapper([typeParameter], [t])); + var propType = instantiateType(templateType, templateMapper); + if (t.flags & 8576) { + var propName = getLateBoundNameFromType(t); + var modifiersProp = getPropertyOfType(modifiersType, propName); + var isOptional = !!(templateModifiers & 4 || + !(templateModifiers & 8) && modifiersProp && modifiersProp.flags & 16777216); + var isReadonly = !!(templateModifiers & 1 || + !(templateModifiers & 2) && modifiersProp && isReadonlySymbol(modifiersProp)); + var prop = createSymbol(4 | (isOptional ? 16777216 : 0), propName, isReadonly ? 8 : 0); + prop.type = strictNullChecks && isOptional && !isTypeAssignableTo(undefinedType, propType) ? getOptionalType(propType) : + strictNullChecks && !isOptional && modifiersProp && modifiersProp.flags & 16777216 ? getTypeWithFacts(propType, 524288) : + propType; + if (modifiersProp) { + prop.syntheticOrigin = modifiersProp; + prop.declarations = modifiersProp.declarations; + } + prop.nameType = t; + members.set(propName, prop); + } + else if (t.flags & (1 | 4)) { + stringIndexInfo = createIndexInfo(propType, !!(templateModifiers & 1)); + } + else if (t.flags & 8) { + numberIndexInfo = createIndexInfo(propType, !!(templateModifiers & 1)); + } + } + } + function getTypeParameterFromMappedType(type) { + return type.typeParameter || + (type.typeParameter = getDeclaredTypeOfTypeParameter(getSymbolOfNode(type.declaration.typeParameter))); + } + function getConstraintTypeFromMappedType(type) { + return type.constraintType || + (type.constraintType = getConstraintOfTypeParameter(getTypeParameterFromMappedType(type)) || errorType); + } + function getTemplateTypeFromMappedType(type) { + return type.templateType || + (type.templateType = type.declaration.type ? + instantiateType(addOptionality(getTypeFromTypeNode(type.declaration.type), !!(getMappedTypeModifiers(type) & 4)), type.mapper || identityMapper) : + errorType); + } + function getConstraintDeclarationForMappedType(type) { + return ts.getEffectiveConstraintOfTypeParameter(type.declaration.typeParameter); + } + function isMappedTypeWithKeyofConstraintDeclaration(type) { + var constraintDeclaration = getConstraintDeclarationForMappedType(type); + return constraintDeclaration.kind === 179 && + constraintDeclaration.operator === 129; + } + function getModifiersTypeFromMappedType(type) { + if (!type.modifiersType) { + if (isMappedTypeWithKeyofConstraintDeclaration(type)) { + type.modifiersType = instantiateType(getTypeFromTypeNode(getConstraintDeclarationForMappedType(type).type), type.mapper || identityMapper); + } + else { + var declaredType = getTypeFromMappedTypeNode(type.declaration); + var constraint = getConstraintTypeFromMappedType(declaredType); + var extendedConstraint = constraint && constraint.flags & 262144 ? getConstraintOfTypeParameter(constraint) : constraint; + type.modifiersType = extendedConstraint && extendedConstraint.flags & 4194304 ? instantiateType(extendedConstraint.type, type.mapper || identityMapper) : emptyObjectType; + } + } + return type.modifiersType; + } + function getMappedTypeModifiers(type) { + var declaration = type.declaration; + return (declaration.readonlyToken ? declaration.readonlyToken.kind === 39 ? 2 : 1 : 0) | + (declaration.questionToken ? declaration.questionToken.kind === 39 ? 8 : 4 : 0); + } + function getMappedTypeOptionality(type) { + var modifiers = getMappedTypeModifiers(type); + return modifiers & 8 ? -1 : modifiers & 4 ? 1 : 0; + } + function getCombinedMappedTypeOptionality(type) { + var optionality = getMappedTypeOptionality(type); + var modifiersType = getModifiersTypeFromMappedType(type); + return optionality || (isGenericMappedType(modifiersType) ? getMappedTypeOptionality(modifiersType) : 0); + } + function isPartialMappedType(type) { + return !!(ts.getObjectFlags(type) & 32 && getMappedTypeModifiers(type) & 4); + } + function isGenericMappedType(type) { + return !!(ts.getObjectFlags(type) & 32) && isGenericIndexType(getConstraintTypeFromMappedType(type)); + } + function resolveStructuredTypeMembers(type) { + if (!type.members) { + if (type.flags & 524288) { + if (type.objectFlags & 4) { + resolveTypeReferenceMembers(type); + } + else if (type.objectFlags & 3) { + resolveClassOrInterfaceMembers(type); + } + else if (type.objectFlags & 2048) { + resolveReverseMappedTypeMembers(type); + } + else if (type.objectFlags & 16) { + resolveAnonymousTypeMembers(type); + } + else if (type.objectFlags & 32) { + resolveMappedTypeMembers(type); + } + } + else if (type.flags & 1048576) { + resolveUnionTypeMembers(type); + } + else if (type.flags & 2097152) { + resolveIntersectionTypeMembers(type); + } + } + return type; + } + function getPropertiesOfObjectType(type) { + if (type.flags & 524288) { + return resolveStructuredTypeMembers(type).properties; + } + return ts.emptyArray; + } + function getPropertyOfObjectType(type, name) { + if (type.flags & 524288) { + var resolved = resolveStructuredTypeMembers(type); + var symbol = resolved.members.get(name); + if (symbol && symbolIsValue(symbol)) { + return symbol; + } + } + } + function getPropertiesOfUnionOrIntersectionType(type) { + if (!type.resolvedProperties) { + var members = ts.createSymbolTable(); + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var current = _a[_i]; + for (var _b = 0, _c = getPropertiesOfType(current); _b < _c.length; _b++) { + var prop = _c[_b]; + if (!members.has(prop.escapedName)) { + var combinedProp = getPropertyOfUnionOrIntersectionType(type, prop.escapedName); + if (combinedProp) { + members.set(prop.escapedName, combinedProp); + } + } + } + if (type.flags & 1048576) { + break; + } + } + type.resolvedProperties = getNamedMembers(members); + } + return type.resolvedProperties; + } + function getPropertiesOfType(type) { + type = getApparentType(type); + return type.flags & 3145728 ? + getPropertiesOfUnionOrIntersectionType(type) : + getPropertiesOfObjectType(type); + } + function isTypeInvalidDueToUnionDiscriminant(contextualType, obj) { + var list = obj.properties; + return list.some(function (property) { + var name = property.name && ts.getTextOfPropertyName(property.name); + var expected = name === undefined ? undefined : getTypeOfPropertyOfType(contextualType, name); + return !!expected && typeIsLiteralType(expected) && !isTypeIdenticalTo(getTypeOfNode(property), expected); + }); + } + function getAllPossiblePropertiesOfTypes(types) { + var unionType = getUnionType(types); + if (!(unionType.flags & 1048576)) { + return getAugmentedPropertiesOfType(unionType); + } + var props = ts.createSymbolTable(); + for (var _i = 0, types_3 = types; _i < types_3.length; _i++) { + var memberType = types_3[_i]; + for (var _a = 0, _b = getAugmentedPropertiesOfType(memberType); _a < _b.length; _a++) { + var escapedName = _b[_a].escapedName; + if (!props.has(escapedName)) { + var prop = createUnionOrIntersectionProperty(unionType, escapedName); + if (prop) + props.set(escapedName, prop); + } + } + } + return ts.arrayFrom(props.values()); + } + function getConstraintOfType(type) { + return type.flags & 262144 ? getConstraintOfTypeParameter(type) : + type.flags & 8388608 ? getConstraintOfIndexedAccess(type) : + type.flags & 16777216 ? getConstraintOfConditionalType(type) : + getBaseConstraintOfType(type); + } + function getConstraintOfTypeParameter(typeParameter) { + return hasNonCircularBaseConstraint(typeParameter) ? getConstraintFromTypeParameter(typeParameter) : undefined; + } + function getConstraintOfIndexedAccess(type) { + var objectType = getConstraintOfType(type.objectType) || type.objectType; + if (objectType !== type.objectType) { + var constraint = getIndexedAccessType(objectType, type.indexType, undefined, errorType); + if (constraint && constraint !== errorType) { + return constraint; + } + } + var baseConstraint = getBaseConstraintOfType(type); + return baseConstraint && baseConstraint !== type ? baseConstraint : undefined; + } + function getDefaultConstraintOfConditionalType(type) { + if (!type.resolvedDefaultConstraint) { + var rootTrueType = type.root.trueType; + var rootTrueConstraint = !(rootTrueType.flags & 33554432) + ? rootTrueType + : (rootTrueType.substitute).flags & 3 + ? rootTrueType.typeVariable + : getIntersectionType([rootTrueType.substitute, rootTrueType.typeVariable]); + type.resolvedDefaultConstraint = getUnionType([instantiateType(rootTrueConstraint, type.combinedMapper || type.mapper), getFalseTypeFromConditionalType(type)]); + } + return type.resolvedDefaultConstraint; + } + function getConstraintOfDistributiveConditionalType(type) { + if (type.root.isDistributive) { + var simplified = getSimplifiedType(type.checkType); + var constraint = simplified === type.checkType ? getConstraintOfType(simplified) : simplified; + if (constraint) { + var mapper = makeUnaryTypeMapper(type.root.checkType, constraint); + var instantiated = getConditionalTypeInstantiation(type, combineTypeMappers(mapper, type.mapper)); + if (!(instantiated.flags & 131072)) { + return instantiated; + } + } + } + return undefined; + } + function getConstraintOfConditionalType(type) { + return getConstraintOfDistributiveConditionalType(type) || getDefaultConstraintOfConditionalType(type); + } + function getUnionConstraintOfIntersection(type, targetIsUnion) { + var constraints; + var hasDisjointDomainType = false; + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (t.flags & 63176704) { + var constraint = getConstraintOfType(t); + while (constraint && constraint.flags & (262144 | 4194304 | 16777216)) { + constraint = getConstraintOfType(constraint); + } + if (constraint) { + if (!(constraint.flags & 1048576)) { + return undefined; + } + constraints = ts.append(constraints, constraint); + } + } + else if (t.flags & 67238908) { + hasDisjointDomainType = true; + } + } + if (constraints && (targetIsUnion || hasDisjointDomainType)) { + if (hasDisjointDomainType) { + for (var _b = 0, _c = type.types; _b < _c.length; _b++) { + var t = _c[_b]; + if (t.flags & 67238908) { + constraints = ts.append(constraints, t); + } + } + } + return getIntersectionType(constraints); + } + return undefined; + } + function getBaseConstraintOfType(type) { + if (type.flags & (58982400 | 3145728)) { + var constraint = getResolvedBaseConstraint(type); + return constraint !== noConstraintType && constraint !== circularConstraintType ? constraint : undefined; + } + return type.flags & 4194304 ? keyofConstraintType : undefined; + } + function getBaseConstraintOrType(type) { + return getBaseConstraintOfType(type) || type; + } + function hasNonCircularBaseConstraint(type) { + return getResolvedBaseConstraint(type) !== circularConstraintType; + } + function getResolvedBaseConstraint(type) { + var nonTerminating = false; + return type.resolvedBaseConstraint || + (type.resolvedBaseConstraint = getTypeWithThisArgument(getImmediateBaseConstraint(type), type)); + function getImmediateBaseConstraint(t) { + if (!t.immediateBaseConstraint) { + if (!pushTypeResolution(t, 4)) { + return circularConstraintType; + } + if (constraintDepth === 50) { + nonTerminating = true; + return t.immediateBaseConstraint = noConstraintType; + } + constraintDepth++; + var result = computeBaseConstraint(getSimplifiedType(t)); + constraintDepth--; + if (!popTypeResolution() || nonTerminating) { + result = circularConstraintType; + } + t.immediateBaseConstraint = result || noConstraintType; + } + return t.immediateBaseConstraint; + } + function getBaseConstraint(t) { + var c = getImmediateBaseConstraint(t); + return c !== noConstraintType && c !== circularConstraintType ? c : undefined; + } + function computeBaseConstraint(t) { + if (t.flags & 262144) { + var constraint = getConstraintFromTypeParameter(t); + return t.isThisType || !constraint ? + constraint : + getBaseConstraint(constraint); + } + if (t.flags & 3145728) { + var types = t.types; + var baseTypes = []; + for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { + var type_3 = types_4[_i]; + var baseType = getBaseConstraint(type_3); + if (baseType) { + baseTypes.push(baseType); + } + } + return t.flags & 1048576 && baseTypes.length === types.length ? getUnionType(baseTypes) : + t.flags & 2097152 && baseTypes.length ? getIntersectionType(baseTypes) : + undefined; + } + if (t.flags & 4194304) { + return keyofConstraintType; + } + if (t.flags & 8388608) { + var baseObjectType = getBaseConstraint(t.objectType); + var baseIndexType = getBaseConstraint(t.indexType); + var baseIndexedAccess = baseObjectType && baseIndexType ? getIndexedAccessType(baseObjectType, baseIndexType, undefined, errorType) : undefined; + return baseIndexedAccess && baseIndexedAccess !== errorType ? getBaseConstraint(baseIndexedAccess) : undefined; + } + if (t.flags & 16777216) { + var constraint = getConstraintOfConditionalType(t); + return constraint && getBaseConstraint(constraint); + } + if (t.flags & 33554432) { + return getBaseConstraint(t.substitute); + } + return t; + } + } + function getApparentTypeOfIntersectionType(type) { + return type.resolvedApparentType || (type.resolvedApparentType = getTypeWithThisArgument(type, type, true)); + } + function getResolvedTypeParameterDefault(typeParameter) { + if (!typeParameter.default) { + if (typeParameter.target) { + var targetDefault = getResolvedTypeParameterDefault(typeParameter.target); + typeParameter.default = targetDefault ? instantiateType(targetDefault, typeParameter.mapper) : noConstraintType; + } + else { + typeParameter.default = resolvingDefaultType; + var defaultDeclaration = typeParameter.symbol && ts.forEach(typeParameter.symbol.declarations, function (decl) { return ts.isTypeParameterDeclaration(decl) && decl.default; }); + var defaultType = defaultDeclaration ? getTypeFromTypeNode(defaultDeclaration) : noConstraintType; + if (typeParameter.default === resolvingDefaultType) { + typeParameter.default = defaultType; + } + } + } + else if (typeParameter.default === resolvingDefaultType) { + typeParameter.default = circularConstraintType; + } + return typeParameter.default; + } + function getDefaultFromTypeParameter(typeParameter) { + var defaultType = getResolvedTypeParameterDefault(typeParameter); + return defaultType !== noConstraintType && defaultType !== circularConstraintType ? defaultType : undefined; + } + function hasNonCircularTypeParameterDefault(typeParameter) { + return getResolvedTypeParameterDefault(typeParameter) !== circularConstraintType; + } + function hasTypeParameterDefault(typeParameter) { + return !!(typeParameter.symbol && ts.forEach(typeParameter.symbol.declarations, function (decl) { return ts.isTypeParameterDeclaration(decl) && decl.default; })); + } + function getApparentTypeOfMappedType(type) { + return type.resolvedApparentType || (type.resolvedApparentType = getResolvedApparentTypeOfMappedType(type)); + } + function getResolvedApparentTypeOfMappedType(type) { + var typeVariable = getHomomorphicTypeVariable(type); + if (typeVariable) { + var constraint = getConstraintOfTypeParameter(typeVariable); + if (constraint && (isArrayType(constraint) || isReadonlyArrayType(constraint) || isTupleType(constraint))) { + var mapper = makeUnaryTypeMapper(typeVariable, constraint); + return instantiateType(type, combineTypeMappers(mapper, type.mapper)); + } + } + return type; + } + function getApparentType(type) { + var t = type.flags & 63176704 ? getBaseConstraintOfType(type) || emptyObjectType : type; + return ts.getObjectFlags(t) & 32 ? getApparentTypeOfMappedType(t) : + t.flags & 2097152 ? getApparentTypeOfIntersectionType(t) : + t.flags & 132 ? globalStringType : + t.flags & 296 ? globalNumberType : + t.flags & 2112 ? getGlobalBigIntType(languageVersion >= 6) : + t.flags & 528 ? globalBooleanType : + t.flags & 12288 ? getGlobalESSymbolType(languageVersion >= 2) : + t.flags & 67108864 ? emptyObjectType : + t.flags & 4194304 ? keyofConstraintType : + t; + } + function createUnionOrIntersectionProperty(containingType, name) { + var props; + var indexTypes; + var isUnion = containingType.flags & 1048576; + var excludeModifiers = isUnion ? 24 : 0; + var commonFlags = isUnion ? 0 : 16777216; + var syntheticFlag = 4; + var checkFlags = 0; + for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) { + var current = _a[_i]; + var type = getApparentType(current); + if (type !== errorType) { + var prop = getPropertyOfType(type, name); + var modifiers = prop ? ts.getDeclarationModifierFlagsFromSymbol(prop) : 0; + if (prop && !(modifiers & excludeModifiers)) { + commonFlags &= prop.flags; + props = ts.appendIfUnique(props, prop); + checkFlags |= (isReadonlySymbol(prop) ? 8 : 0) | + (!(modifiers & 24) ? 64 : 0) | + (modifiers & 16 ? 128 : 0) | + (modifiers & 8 ? 256 : 0) | + (modifiers & 32 ? 512 : 0); + if (!isPrototypeProperty(prop)) { + syntheticFlag = 2; + } + } + else if (isUnion) { + var indexInfo = !isLateBoundName(name) && (isNumericLiteralName(name) && getIndexInfoOfType(type, 1) || getIndexInfoOfType(type, 0)); + if (indexInfo) { + checkFlags |= indexInfo.isReadonly ? 8 : 0; + indexTypes = ts.append(indexTypes, isTupleType(type) ? getRestTypeOfTupleType(type) || undefinedType : indexInfo.type); + } + else { + checkFlags |= 16; + } + } + } + } + if (!props) { + return undefined; + } + if (props.length === 1 && !(checkFlags & 16) && !indexTypes) { + return props[0]; + } + var declarations; + var commonType; + var nameType; + var propTypes = []; + var first = true; + var commonValueDeclaration; + var hasNonUniformValueDeclaration = false; + for (var _b = 0, props_1 = props; _b < props_1.length; _b++) { + var prop = props_1[_b]; + if (!commonValueDeclaration) { + commonValueDeclaration = prop.valueDeclaration; + } + else if (prop.valueDeclaration !== commonValueDeclaration) { + hasNonUniformValueDeclaration = true; + } + declarations = ts.addRange(declarations, prop.declarations); + var type = getTypeOfSymbol(prop); + if (first) { + commonType = type; + nameType = prop.nameType; + first = false; + } + else { + if (type !== commonType) { + checkFlags |= 32; + } + } + propTypes.push(type); + } + ts.addRange(propTypes, indexTypes); + var result = createSymbol(4 | commonFlags, name, syntheticFlag | checkFlags); + result.containingType = containingType; + if (!hasNonUniformValueDeclaration && commonValueDeclaration) { + result.valueDeclaration = commonValueDeclaration; + } + result.declarations = declarations; + result.nameType = nameType; + result.type = isUnion ? getUnionType(propTypes) : getIntersectionType(propTypes); + return result; + } + function getUnionOrIntersectionProperty(type, name) { + var properties = type.propertyCache || (type.propertyCache = ts.createSymbolTable()); + var property = properties.get(name); + if (!property) { + property = createUnionOrIntersectionProperty(type, name); + if (property) { + properties.set(name, property); + } + } + return property; + } + function getPropertyOfUnionOrIntersectionType(type, name) { + var property = getUnionOrIntersectionProperty(type, name); + return property && !(ts.getCheckFlags(property) & 16) ? property : undefined; + } + function getPropertyOfType(type, name) { + type = getApparentType(type); + if (type.flags & 524288) { + var resolved = resolveStructuredTypeMembers(type); + var symbol = resolved.members.get(name); + if (symbol && symbolIsValue(symbol)) { + return symbol; + } + var functionType = resolved === anyFunctionType ? globalFunctionType : + resolved.callSignatures.length ? globalCallableFunctionType : + resolved.constructSignatures.length ? globalNewableFunctionType : + undefined; + if (functionType) { + var symbol_1 = getPropertyOfObjectType(functionType, name); + if (symbol_1) { + return symbol_1; + } + } + return getPropertyOfObjectType(globalObjectType, name); + } + if (type.flags & 3145728) { + return getPropertyOfUnionOrIntersectionType(type, name); + } + return undefined; + } + function getSignaturesOfStructuredType(type, kind) { + if (type.flags & 3670016) { + var resolved = resolveStructuredTypeMembers(type); + return kind === 0 ? resolved.callSignatures : resolved.constructSignatures; + } + return ts.emptyArray; + } + function getSignaturesOfType(type, kind) { + return getSignaturesOfStructuredType(getApparentType(type), kind); + } + function getIndexInfoOfStructuredType(type, kind) { + if (type.flags & 3670016) { + var resolved = resolveStructuredTypeMembers(type); + return kind === 0 ? resolved.stringIndexInfo : resolved.numberIndexInfo; + } + } + function getIndexTypeOfStructuredType(type, kind) { + var info = getIndexInfoOfStructuredType(type, kind); + return info && info.type; + } + function getIndexInfoOfType(type, kind) { + return getIndexInfoOfStructuredType(getApparentType(type), kind); + } + function getIndexTypeOfType(type, kind) { + return getIndexTypeOfStructuredType(getApparentType(type), kind); + } + function getImplicitIndexTypeOfType(type, kind) { + if (isObjectTypeWithInferableIndex(type)) { + var propTypes = []; + for (var _i = 0, _a = getPropertiesOfType(type); _i < _a.length; _i++) { + var prop = _a[_i]; + if (kind === 0 || isNumericLiteralName(prop.escapedName)) { + propTypes.push(getTypeOfSymbol(prop)); + } + } + if (propTypes.length) { + return getUnionType(propTypes, 2); + } + } + return undefined; + } + function getTypeParametersFromDeclaration(declaration) { + var result; + for (var _i = 0, _a = ts.getEffectiveTypeParameterDeclarations(declaration); _i < _a.length; _i++) { + var node = _a[_i]; + result = ts.appendIfUnique(result, getDeclaredTypeOfTypeParameter(node.symbol)); + } + return result; + } + function symbolsToArray(symbols) { + var result = []; + symbols.forEach(function (symbol, id) { + if (!isReservedMemberName(id)) { + result.push(symbol); + } + }); + return result; + } + function isJSDocOptionalParameter(node) { + return ts.isInJSFile(node) && (node.type && node.type.kind === 288 + || ts.getJSDocParameterTags(node).some(function (_a) { + var isBracketed = _a.isBracketed, typeExpression = _a.typeExpression; + return isBracketed || !!typeExpression && typeExpression.type.kind === 288; + })); + } + function tryFindAmbientModule(moduleName, withAugmentations) { + if (ts.isExternalModuleNameRelative(moduleName)) { + return undefined; + } + var symbol = getSymbol(globals, '"' + moduleName + '"', 512); + return symbol && withAugmentations ? getMergedSymbol(symbol) : symbol; + } + function isOptionalParameter(node) { + if (ts.hasQuestionToken(node) || isOptionalJSDocParameterTag(node) || isJSDocOptionalParameter(node)) { + return true; + } + if (node.initializer) { + var signature = getSignatureFromDeclaration(node.parent); + var parameterIndex = node.parent.parameters.indexOf(node); + ts.Debug.assert(parameterIndex >= 0); + return parameterIndex >= getMinArgumentCount(signature); + } + var iife = ts.getImmediatelyInvokedFunctionExpression(node.parent); + if (iife) { + return !node.type && + !node.dotDotDotToken && + node.parent.parameters.indexOf(node) >= iife.arguments.length; + } + return false; + } + function isOptionalJSDocParameterTag(node) { + if (!ts.isJSDocParameterTag(node)) { + return false; + } + var isBracketed = node.isBracketed, typeExpression = node.typeExpression; + return isBracketed || !!typeExpression && typeExpression.type.kind === 288; + } + function createIdentifierTypePredicate(parameterName, parameterIndex, type) { + return { kind: 1, parameterName: parameterName, parameterIndex: parameterIndex, type: type }; + } + function createThisTypePredicate(type) { + return { kind: 0, type: type }; + } + function getMinTypeArgumentCount(typeParameters) { + var minTypeArgumentCount = 0; + if (typeParameters) { + for (var i = 0; i < typeParameters.length; i++) { + if (!hasTypeParameterDefault(typeParameters[i])) { + minTypeArgumentCount = i + 1; + } + } + } + return minTypeArgumentCount; + } + function fillMissingTypeArguments(typeArguments, typeParameters, minTypeArgumentCount, isJavaScriptImplicitAny) { + var numTypeParameters = ts.length(typeParameters); + if (!numTypeParameters) { + return []; + } + var numTypeArguments = ts.length(typeArguments); + if (isJavaScriptImplicitAny || (numTypeArguments >= minTypeArgumentCount && numTypeArguments <= numTypeParameters)) { + var result = typeArguments ? typeArguments.slice() : []; + var baseDefaultType_1 = getDefaultTypeArgumentType(isJavaScriptImplicitAny); + var circularityMapper = createTypeMapper(typeParameters, ts.map(typeParameters, function () { return baseDefaultType_1; })); + for (var i = numTypeArguments; i < numTypeParameters; i++) { + result[i] = instantiateType(getConstraintFromTypeParameter(typeParameters[i]) || baseDefaultType_1, circularityMapper); + } + for (var i = numTypeArguments; i < numTypeParameters; i++) { + var mapper = createTypeMapper(typeParameters, result); + var defaultType = getDefaultFromTypeParameter(typeParameters[i]); + if (isJavaScriptImplicitAny && defaultType && isTypeIdenticalTo(defaultType, emptyObjectType)) { + defaultType = anyType; + } + result[i] = defaultType ? instantiateType(defaultType, mapper) : baseDefaultType_1; + } + result.length = typeParameters.length; + return result; + } + return typeArguments && typeArguments.slice(); + } + function getSignatureFromDeclaration(declaration) { + var links = getNodeLinks(declaration); + if (!links.resolvedSignature) { + var parameters = []; + var hasLiteralTypes = false; + var minArgumentCount = 0; + var thisParameter = void 0; + var hasThisParameter = false; + var iife = ts.getImmediatelyInvokedFunctionExpression(declaration); + var isJSConstructSignature = ts.isJSDocConstructSignature(declaration); + var isUntypedSignatureInJSFile = !iife && + ts.isInJSFile(declaration) && + ts.isValueSignatureDeclaration(declaration) && + !ts.hasJSDocParameterTags(declaration) && + !ts.getJSDocType(declaration); + for (var i = isJSConstructSignature ? 1 : 0; i < declaration.parameters.length; i++) { + var param = declaration.parameters[i]; + var paramSymbol = param.symbol; + var type = ts.isJSDocParameterTag(param) ? (param.typeExpression && param.typeExpression.type) : param.type; + if (paramSymbol && !!(paramSymbol.flags & 4) && !ts.isBindingPattern(param.name)) { + var resolvedSymbol = resolveName(param, paramSymbol.escapedName, 67220415, undefined, undefined, false); + paramSymbol = resolvedSymbol; + } + if (i === 0 && paramSymbol.escapedName === "this") { + hasThisParameter = true; + thisParameter = param.symbol; + } + else { + parameters.push(paramSymbol); + } + if (type && type.kind === 182) { + hasLiteralTypes = true; + } + var isOptionalParameter_1 = isOptionalJSDocParameterTag(param) || + param.initializer || param.questionToken || param.dotDotDotToken || + iife && parameters.length > iife.arguments.length && !type || + isUntypedSignatureInJSFile || + isJSDocOptionalParameter(param); + if (!isOptionalParameter_1) { + minArgumentCount = parameters.length; + } + } + if ((declaration.kind === 158 || declaration.kind === 159) && + !hasNonBindableDynamicName(declaration) && + (!hasThisParameter || !thisParameter)) { + var otherKind = declaration.kind === 158 ? 159 : 158; + var other = ts.getDeclarationOfKind(getSymbolOfNode(declaration), otherKind); + if (other) { + thisParameter = getAnnotatedAccessorThisParameter(other); + } + } + var classType = declaration.kind === 157 ? + getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)) + : undefined; + var typeParameters = classType ? classType.localTypeParameters : getTypeParametersFromDeclaration(declaration); + var hasRestLikeParameter = ts.hasRestParameter(declaration) || ts.isInJSFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters); + links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, undefined, undefined, minArgumentCount, hasRestLikeParameter, hasLiteralTypes); + } + return links.resolvedSignature; + } + function maybeAddJsSyntheticRestParameter(declaration, parameters) { + if (ts.isJSDocSignature(declaration) || !containsArgumentsReference(declaration)) { + return false; + } + var lastParam = ts.lastOrUndefined(declaration.parameters); + var lastParamTags = lastParam ? ts.getJSDocParameterTags(lastParam) : ts.getJSDocTags(declaration).filter(ts.isJSDocParameterTag); + var lastParamVariadicType = ts.firstDefined(lastParamTags, function (p) { + return p.typeExpression && ts.isJSDocVariadicType(p.typeExpression.type) ? p.typeExpression.type : undefined; + }); + var syntheticArgsSymbol = createSymbol(3, "args", 8192); + syntheticArgsSymbol.type = lastParamVariadicType ? createArrayType(getTypeFromTypeNode(lastParamVariadicType.type)) : anyArrayType; + if (lastParamVariadicType) { + parameters.pop(); + } + parameters.push(syntheticArgsSymbol); + return true; + } + function getSignatureOfTypeTag(node) { + var typeTag = ts.isInJSFile(node) ? ts.getJSDocTypeTag(node) : undefined; + var signature = typeTag && typeTag.typeExpression && getSingleCallSignature(getTypeFromTypeNode(typeTag.typeExpression)); + return signature && getErasedSignature(signature); + } + function getReturnTypeOfTypeTag(node) { + var signature = getSignatureOfTypeTag(node); + return signature && getReturnTypeOfSignature(signature); + } + function containsArgumentsReference(declaration) { + var links = getNodeLinks(declaration); + if (links.containsArgumentsReference === undefined) { + if (links.flags & 8192) { + links.containsArgumentsReference = true; + } + else { + links.containsArgumentsReference = traverse(declaration.body); + } + } + return links.containsArgumentsReference; + function traverse(node) { + if (!node) + return false; + switch (node.kind) { + case 72: + return node.escapedText === "arguments" && ts.isExpressionNode(node); + case 154: + case 156: + case 158: + case 159: + return node.name.kind === 149 + && traverse(node.name); + default: + return !ts.nodeStartsNewLexicalEnvironment(node) && !ts.isPartOfTypeNode(node) && !!ts.forEachChild(node, traverse); + } + } + } + function getSignaturesOfSymbol(symbol) { + if (!symbol) + return ts.emptyArray; + var result = []; + for (var i = 0; i < symbol.declarations.length; i++) { + var decl = symbol.declarations[i]; + if (!ts.isFunctionLike(decl)) + continue; + if (i > 0 && decl.body) { + var previous = symbol.declarations[i - 1]; + if (decl.parent === previous.parent && decl.kind === previous.kind && decl.pos === previous.end) { + continue; + } + } + result.push(getSignatureFromDeclaration(decl)); + } + return result; + } + function resolveExternalModuleTypeByLiteral(name) { + var moduleSym = resolveExternalModuleName(name, name); + if (moduleSym) { + var resolvedModuleSymbol = resolveExternalModuleSymbol(moduleSym); + if (resolvedModuleSymbol) { + return getTypeOfSymbol(resolvedModuleSymbol); + } + } + return anyType; + } + function getThisTypeOfSignature(signature) { + if (signature.thisParameter) { + return getTypeOfSymbol(signature.thisParameter); + } + } + function signatureHasTypePredicate(signature) { + return getTypePredicateOfSignature(signature) !== undefined; + } + function getTypePredicateOfSignature(signature) { + if (!signature.resolvedTypePredicate) { + if (signature.target) { + var targetTypePredicate = getTypePredicateOfSignature(signature.target); + signature.resolvedTypePredicate = targetTypePredicate ? instantiateTypePredicate(targetTypePredicate, signature.mapper) : noTypePredicate; + } + else if (signature.unionSignatures) { + signature.resolvedTypePredicate = getUnionTypePredicate(signature.unionSignatures) || noTypePredicate; + } + else { + var type = signature.declaration && ts.getEffectiveReturnTypeNode(signature.declaration); + var jsdocPredicate = void 0; + if (!type && ts.isInJSFile(signature.declaration)) { + var jsdocSignature = getSignatureOfTypeTag(signature.declaration); + if (jsdocSignature && signature !== jsdocSignature) { + jsdocPredicate = getTypePredicateOfSignature(jsdocSignature); + } + } + signature.resolvedTypePredicate = type && ts.isTypePredicateNode(type) ? + createTypePredicateFromTypePredicateNode(type, signature.declaration) : + jsdocPredicate || noTypePredicate; + } + ts.Debug.assert(!!signature.resolvedTypePredicate); + } + return signature.resolvedTypePredicate === noTypePredicate ? undefined : signature.resolvedTypePredicate; + } + function createTypePredicateFromTypePredicateNode(node, func) { + var parameterName = node.parameterName; + var type = getTypeFromTypeNode(node.type); + if (parameterName.kind === 72) { + return createIdentifierTypePredicate(parameterName.escapedText, getTypePredicateParameterIndex(func.parameters, parameterName), type); + } + else { + return createThisTypePredicate(type); + } + } + function getTypePredicateParameterIndex(parameterList, parameter) { + for (var i = 0; i < parameterList.length; i++) { + var param = parameterList[i]; + if (param.name.kind === 72 && param.name.escapedText === parameter.escapedText) { + return i; + } + } + return -1; + } + function getReturnTypeOfSignature(signature) { + if (!signature.resolvedReturnType) { + if (!pushTypeResolution(signature, 3)) { + return errorType; + } + var type = signature.target ? instantiateType(getReturnTypeOfSignature(signature.target), signature.mapper) : + signature.unionSignatures ? getUnionType(ts.map(signature.unionSignatures, getReturnTypeOfSignature), 2) : + getReturnTypeFromAnnotation(signature.declaration) || + isJSConstructor(signature.declaration) && getJSClassType(getSymbolOfNode(signature.declaration)) || + (ts.nodeIsMissing(signature.declaration.body) ? anyType : getReturnTypeFromBody(signature.declaration)); + if (!popTypeResolution()) { + if (signature.declaration) { + var typeNode = ts.getEffectiveReturnTypeNode(signature.declaration); + if (typeNode) { + error(typeNode, ts.Diagnostics.Return_type_annotation_circularly_references_itself); + } + else if (noImplicitAny) { + var declaration = signature.declaration; + var name = ts.getNameOfDeclaration(declaration); + if (name) { + error(name, ts.Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, ts.declarationNameToString(name)); + } + else { + error(declaration, ts.Diagnostics.Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions); + } + } + } + type = anyType; + } + signature.resolvedReturnType = type; + } + return signature.resolvedReturnType; + } + function getReturnTypeFromAnnotation(declaration) { + if (declaration.kind === 157) { + return getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)); + } + if (ts.isJSDocConstructSignature(declaration)) { + return getTypeFromTypeNode(declaration.parameters[0].type); + } + var typeNode = ts.getEffectiveReturnTypeNode(declaration); + if (typeNode) { + return getTypeFromTypeNode(typeNode); + } + if (declaration.kind === 158 && !hasNonBindableDynamicName(declaration)) { + var jsDocType = ts.isInJSFile(declaration) && getTypeForDeclarationFromJSDocComment(declaration); + if (jsDocType) { + return jsDocType; + } + var setter = ts.getDeclarationOfKind(getSymbolOfNode(declaration), 159); + var setterType = getAnnotatedAccessorType(setter); + if (setterType) { + return setterType; + } + } + return getReturnTypeOfTypeTag(declaration); + } + function isResolvingReturnTypeOfSignature(signature) { + return !signature.resolvedReturnType && findResolutionCycleStartIndex(signature, 3) >= 0; + } + function getRestTypeOfSignature(signature) { + return tryGetRestTypeOfSignature(signature) || anyType; + } + function tryGetRestTypeOfSignature(signature) { + if (signature.hasRestParameter) { + var sigRestType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); + var restType = isTupleType(sigRestType) ? getRestTypeOfTupleType(sigRestType) : sigRestType; + return restType && getIndexTypeOfType(restType, 1); + } + return undefined; + } + function getSignatureInstantiation(signature, typeArguments, isJavascript) { + return getSignatureInstantiationWithoutFillingInTypeArguments(signature, fillMissingTypeArguments(typeArguments, signature.typeParameters, getMinTypeArgumentCount(signature.typeParameters), isJavascript)); + } + function getSignatureInstantiationWithoutFillingInTypeArguments(signature, typeArguments) { + var instantiations = signature.instantiations || (signature.instantiations = ts.createMap()); + var id = getTypeListId(typeArguments); + var instantiation = instantiations.get(id); + if (!instantiation) { + instantiations.set(id, instantiation = createSignatureInstantiation(signature, typeArguments)); + } + return instantiation; + } + function createSignatureInstantiation(signature, typeArguments) { + return instantiateSignature(signature, createSignatureTypeMapper(signature, typeArguments), true); + } + function createSignatureTypeMapper(signature, typeArguments) { + return createTypeMapper(signature.typeParameters, typeArguments); + } + function getErasedSignature(signature) { + return signature.typeParameters ? + signature.erasedSignatureCache || (signature.erasedSignatureCache = createErasedSignature(signature)) : + signature; + } + function createErasedSignature(signature) { + return instantiateSignature(signature, createTypeEraser(signature.typeParameters), true); + } + function getCanonicalSignature(signature) { + return signature.typeParameters ? + signature.canonicalSignatureCache || (signature.canonicalSignatureCache = createCanonicalSignature(signature)) : + signature; + } + function createCanonicalSignature(signature) { + return getSignatureInstantiation(signature, ts.map(signature.typeParameters, function (tp) { return tp.target && !getConstraintOfTypeParameter(tp.target) ? tp.target : tp; }), ts.isInJSFile(signature.declaration)); + } + function getBaseSignature(signature) { + var typeParameters = signature.typeParameters; + if (typeParameters) { + var typeEraser_1 = createTypeEraser(typeParameters); + var baseConstraints = ts.map(typeParameters, function (tp) { return instantiateType(getBaseConstraintOfType(tp), typeEraser_1) || emptyObjectType; }); + return instantiateSignature(signature, createTypeMapper(typeParameters, baseConstraints), true); + } + return signature; + } + function getOrCreateTypeFromSignature(signature) { + if (!signature.isolatedSignatureType) { + var isConstructor = signature.declaration.kind === 157 || signature.declaration.kind === 161; + var type = createObjectType(16); + type.members = emptySymbols; + type.properties = ts.emptyArray; + type.callSignatures = !isConstructor ? [signature] : ts.emptyArray; + type.constructSignatures = isConstructor ? [signature] : ts.emptyArray; + signature.isolatedSignatureType = type; + } + return signature.isolatedSignatureType; + } + function getIndexSymbol(symbol) { + return symbol.members.get("__index"); + } + function getIndexDeclarationOfSymbol(symbol, kind) { + var syntaxKind = kind === 1 ? 135 : 138; + var indexSymbol = getIndexSymbol(symbol); + if (indexSymbol) { + for (var _i = 0, _a = indexSymbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + var node = ts.cast(decl, ts.isIndexSignatureDeclaration); + if (node.parameters.length === 1) { + var parameter = node.parameters[0]; + if (parameter.type && parameter.type.kind === syntaxKind) { + return node; + } + } + } + } + return undefined; + } + function createIndexInfo(type, isReadonly, declaration) { + return { type: type, isReadonly: isReadonly, declaration: declaration }; + } + function getIndexInfoOfSymbol(symbol, kind) { + var declaration = getIndexDeclarationOfSymbol(symbol, kind); + if (declaration) { + return createIndexInfo(declaration.type ? getTypeFromTypeNode(declaration.type) : anyType, ts.hasModifier(declaration, 64), declaration); + } + return undefined; + } + function getConstraintDeclaration(type) { + var decl = type.symbol && ts.getDeclarationOfKind(type.symbol, 150); + return decl && ts.getEffectiveConstraintOfTypeParameter(decl); + } + function getInferredTypeParameterConstraint(typeParameter) { + var inferences; + if (typeParameter.symbol) { + for (var _i = 0, _a = typeParameter.symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (declaration.parent.kind === 176) { + var grandParent = declaration.parent.parent; + if (grandParent.kind === 164) { + var typeReference = grandParent; + var typeParameters = getTypeParametersForTypeReference(typeReference); + if (typeParameters) { + var index = typeReference.typeArguments.indexOf(declaration.parent); + if (index < typeParameters.length) { + var declaredConstraint = getConstraintOfTypeParameter(typeParameters[index]); + if (declaredConstraint) { + var mapper = createTypeMapper(typeParameters, getEffectiveTypeArguments(typeReference, typeParameters)); + var constraint = instantiateType(declaredConstraint, mapper); + if (constraint !== typeParameter) { + inferences = ts.append(inferences, constraint); + } + } + } + } + } + else if (grandParent.kind === 151 && grandParent.dotDotDotToken) { + inferences = ts.append(inferences, createArrayType(unknownType)); + } + } + } + } + return inferences && getIntersectionType(inferences); + } + function getConstraintFromTypeParameter(typeParameter) { + if (!typeParameter.constraint) { + if (typeParameter.target) { + var targetConstraint = getConstraintOfTypeParameter(typeParameter.target); + typeParameter.constraint = targetConstraint ? instantiateType(targetConstraint, typeParameter.mapper) : noConstraintType; + } + else { + var constraintDeclaration = getConstraintDeclaration(typeParameter); + typeParameter.constraint = constraintDeclaration ? getTypeFromTypeNode(constraintDeclaration) : + getInferredTypeParameterConstraint(typeParameter) || noConstraintType; + } + } + return typeParameter.constraint === noConstraintType ? undefined : typeParameter.constraint; + } + function getParentSymbolOfTypeParameter(typeParameter) { + var tp = ts.getDeclarationOfKind(typeParameter.symbol, 150); + var host = ts.isJSDocTemplateTag(tp.parent) ? ts.getHostSignatureFromJSDoc(tp.parent) : tp.parent; + return host && getSymbolOfNode(host); + } + function getTypeListId(types) { + var result = ""; + if (types) { + var length_3 = types.length; + var i = 0; + while (i < length_3) { + var startId = types[i].id; + var count = 1; + while (i + count < length_3 && types[i + count].id === startId + count) { + count++; + } + if (result.length) { + result += ","; + } + result += startId; + if (count > 1) { + result += ":" + count; + } + i += count; + } + } + return result; + } + function getPropagatingFlagsOfTypes(types, excludeKinds) { + var result = 0; + for (var _i = 0, types_5 = types; _i < types_5.length; _i++) { + var type = types_5[_i]; + if (!(type.flags & excludeKinds)) { + result |= type.flags; + } + } + return result & 939524096; + } + function createTypeReference(target, typeArguments) { + var id = getTypeListId(typeArguments); + var type = target.instantiations.get(id); + if (!type) { + type = createObjectType(4, target.symbol); + target.instantiations.set(id, type); + type.flags |= typeArguments ? getPropagatingFlagsOfTypes(typeArguments, 0) : 0; + type.target = target; + type.typeArguments = typeArguments; + } + return type; + } + function cloneTypeReference(source) { + var type = createType(source.flags); + type.symbol = source.symbol; + type.objectFlags = source.objectFlags; + type.target = source.target; + type.typeArguments = source.typeArguments; + return type; + } + function getTypeReferenceArity(type) { + return ts.length(type.target.typeParameters); + } + function getTypeFromClassOrInterfaceReference(node, symbol, typeArgs) { + var type = getDeclaredTypeOfSymbol(getMergedSymbol(symbol)); + var typeParameters = type.localTypeParameters; + if (typeParameters) { + var numTypeArguments = ts.length(node.typeArguments); + var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters); + var isJs = ts.isInJSFile(node); + var isJsImplicitAny = !noImplicitAny && isJs; + if (!isJsImplicitAny && (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length)) { + var missingAugmentsTag = isJs && ts.isExpressionWithTypeArguments(node) && !ts.isJSDocAugmentsTag(node.parent); + var diag = minTypeArgumentCount === typeParameters.length + ? missingAugmentsTag + ? ts.Diagnostics.Expected_0_type_arguments_provide_these_with_an_extends_tag + : ts.Diagnostics.Generic_type_0_requires_1_type_argument_s + : missingAugmentsTag + ? ts.Diagnostics.Expected_0_1_type_arguments_provide_these_with_an_extends_tag + : ts.Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments; + var typeStr = typeToString(type, undefined, 2); + error(node, diag, typeStr, minTypeArgumentCount, typeParameters.length); + if (!isJs) { + return errorType; + } + } + var typeArguments = ts.concatenate(type.outerTypeParameters, fillMissingTypeArguments(typeArgs, typeParameters, minTypeArgumentCount, isJs)); + return createTypeReference(type, typeArguments); + } + return checkNoTypeArguments(node, symbol) ? type : errorType; + } + function getTypeAliasInstantiation(symbol, typeArguments) { + var type = getDeclaredTypeOfSymbol(symbol); + var links = getSymbolLinks(symbol); + var typeParameters = links.typeParameters; + var id = getTypeListId(typeArguments); + var instantiation = links.instantiations.get(id); + if (!instantiation) { + links.instantiations.set(id, instantiation = instantiateType(type, createTypeMapper(typeParameters, fillMissingTypeArguments(typeArguments, typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJSFile(symbol.valueDeclaration))))); + } + return instantiation; + } + function getTypeFromTypeAliasReference(node, symbol, typeArguments) { + var type = getDeclaredTypeOfSymbol(symbol); + var typeParameters = getSymbolLinks(symbol).typeParameters; + if (typeParameters) { + var numTypeArguments = ts.length(node.typeArguments); + var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters); + if (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length) { + error(node, minTypeArgumentCount === typeParameters.length + ? ts.Diagnostics.Generic_type_0_requires_1_type_argument_s + : ts.Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments, symbolToString(symbol), minTypeArgumentCount, typeParameters.length); + return errorType; + } + return getTypeAliasInstantiation(symbol, typeArguments); + } + return checkNoTypeArguments(node, symbol) ? type : errorType; + } + function getTypeReferenceName(node) { + switch (node.kind) { + case 164: + return node.typeName; + case 211: + var expr = node.expression; + if (ts.isEntityNameExpression(expr)) { + return expr; + } + } + return undefined; + } + function resolveTypeReferenceName(typeReferenceName, meaning) { + if (!typeReferenceName) { + return unknownSymbol; + } + return resolveEntityName(typeReferenceName, meaning) || unknownSymbol; + } + function getTypeReferenceType(node, symbol) { + var typeArguments = typeArgumentsFromTypeReferenceNode(node); + if (symbol === unknownSymbol) { + return errorType; + } + var type = getTypeReferenceTypeWorker(node, symbol, typeArguments); + if (type) { + return type; + } + var enumTag = ts.isInJSFile(node) && symbol.valueDeclaration && ts.getJSDocEnumTag(symbol.valueDeclaration); + if (enumTag) { + var links = getNodeLinks(enumTag); + if (!pushTypeResolution(enumTag, 5)) { + return errorType; + } + var type_4 = enumTag.typeExpression ? getTypeFromTypeNode(enumTag.typeExpression) : errorType; + if (!popTypeResolution()) { + type_4 = errorType; + error(node, ts.Diagnostics.Enum_type_0_circularly_references_itself, symbolToString(symbol)); + } + return (links.resolvedEnumType = type_4); + } + var res = tryGetDeclaredTypeOfSymbol(symbol); + if (res) { + return checkNoTypeArguments(node, symbol) ? + res.flags & 262144 ? getConstrainedTypeVariable(res, node) : getRegularTypeOfLiteralType(res) : + errorType; + } + if (!(symbol.flags & 67220415 && isJSDocTypeReference(node))) { + return errorType; + } + var jsdocType = getJSDocTypeReference(node, symbol, typeArguments); + if (jsdocType) { + return jsdocType; + } + resolveTypeReferenceName(getTypeReferenceName(node), 67897832); + return getTypeOfSymbol(symbol); + } + function getJSDocTypeReference(node, symbol, typeArguments) { + if (!pushTypeResolution(symbol, 6)) { + return errorType; + } + var assignedType = getAssignedClassType(symbol); + var valueType = getTypeOfSymbol(symbol); + var referenceType = valueType.symbol && valueType.symbol !== symbol && !isInferredClassType(valueType) && getTypeReferenceTypeWorker(node, valueType.symbol, typeArguments); + if (!popTypeResolution()) { + getSymbolLinks(symbol).resolvedJSDocType = errorType; + error(node, ts.Diagnostics.JSDoc_type_0_circularly_references_itself, symbolToString(symbol)); + return errorType; + } + if (referenceType || assignedType) { + var type = (referenceType && assignedType ? getIntersectionType([assignedType, referenceType]) : referenceType || assignedType); + return getSymbolLinks(symbol).resolvedJSDocType = type; + } + } + function getTypeReferenceTypeWorker(node, symbol, typeArguments) { + if (symbol.flags & (32 | 64)) { + if (symbol.valueDeclaration && ts.isBinaryExpression(symbol.valueDeclaration.parent)) { + var jsdocType = getJSDocTypeReference(node, symbol, typeArguments); + if (jsdocType) { + return jsdocType; + } + } + return getTypeFromClassOrInterfaceReference(node, symbol, typeArguments); + } + if (symbol.flags & 524288) { + return getTypeFromTypeAliasReference(node, symbol, typeArguments); + } + if (symbol.flags & 16 && + isJSDocTypeReference(node) && + (symbol.members || ts.getJSDocClassTag(symbol.valueDeclaration))) { + return getInferredClassType(symbol); + } + } + function getSubstitutionType(typeVariable, substitute) { + var result = createType(33554432); + result.typeVariable = typeVariable; + result.substitute = substitute; + return result; + } + function isUnaryTupleTypeNode(node) { + return node.kind === 170 && node.elementTypes.length === 1; + } + function getImpliedConstraint(typeVariable, checkNode, extendsNode) { + return isUnaryTupleTypeNode(checkNode) && isUnaryTupleTypeNode(extendsNode) ? getImpliedConstraint(typeVariable, checkNode.elementTypes[0], extendsNode.elementTypes[0]) : + getActualTypeVariable(getTypeFromTypeNode(checkNode)) === typeVariable ? getTypeFromTypeNode(extendsNode) : + undefined; + } + function getConstrainedTypeVariable(typeVariable, node) { + var constraints; + while (node && !ts.isStatement(node) && node.kind !== 291) { + var parent = node.parent; + if (parent.kind === 175 && node === parent.trueType) { + var constraint = getImpliedConstraint(typeVariable, parent.checkType, parent.extendsType); + if (constraint) { + constraints = ts.append(constraints, constraint); + } + } + node = parent; + } + return constraints ? getSubstitutionType(typeVariable, getIntersectionType(ts.append(constraints, typeVariable))) : typeVariable; + } + function isJSDocTypeReference(node) { + return !!(node.flags & 2097152) && (node.kind === 164 || node.kind === 183); + } + function checkNoTypeArguments(node, symbol) { + if (node.typeArguments) { + error(node, ts.Diagnostics.Type_0_is_not_generic, symbol ? symbolToString(symbol) : node.typeName ? ts.declarationNameToString(node.typeName) : "(anonymous)"); + return false; + } + return true; + } + function getIntendedTypeFromJSDocTypeReference(node) { + if (ts.isIdentifier(node.typeName)) { + var typeArgs = node.typeArguments; + switch (node.typeName.escapedText) { + case "String": + checkNoTypeArguments(node); + return stringType; + case "Number": + checkNoTypeArguments(node); + return numberType; + case "Boolean": + checkNoTypeArguments(node); + return booleanType; + case "Void": + checkNoTypeArguments(node); + return voidType; + case "Undefined": + checkNoTypeArguments(node); + return undefinedType; + case "Null": + checkNoTypeArguments(node); + return nullType; + case "Function": + case "function": + checkNoTypeArguments(node); + return globalFunctionType; + case "Array": + case "array": + return !typeArgs || !typeArgs.length ? anyArrayType : undefined; + case "Promise": + case "promise": + return !typeArgs || !typeArgs.length ? createPromiseType(anyType) : undefined; + case "Object": + if (typeArgs && typeArgs.length === 2) { + if (ts.isJSDocIndexSignature(node)) { + var indexed = getTypeFromTypeNode(typeArgs[0]); + var target = getTypeFromTypeNode(typeArgs[1]); + var index = createIndexInfo(target, false); + return createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, indexed === stringType ? index : undefined, indexed === numberType ? index : undefined); + } + return anyType; + } + checkNoTypeArguments(node); + return anyType; + } + } + } + function getTypeFromJSDocNullableTypeNode(node) { + var type = getTypeFromTypeNode(node.type); + return strictNullChecks ? getNullableType(type, 65536) : type; + } + function getTypeFromTypeReference(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + var symbol = void 0; + var type = void 0; + var meaning = 67897832; + if (isJSDocTypeReference(node)) { + type = getIntendedTypeFromJSDocTypeReference(node); + meaning |= 67220415; + } + if (!type) { + symbol = resolveTypeReferenceName(getTypeReferenceName(node), meaning); + type = getTypeReferenceType(node, symbol); + } + links.resolvedSymbol = symbol; + links.resolvedType = type; + } + return links.resolvedType; + } + function typeArgumentsFromTypeReferenceNode(node) { + return ts.map(node.typeArguments, getTypeFromTypeNode); + } + function getTypeFromTypeQueryNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + links.resolvedType = getRegularTypeOfLiteralType(getWidenedType(checkExpression(node.exprName))); + } + return links.resolvedType; + } + function getTypeOfGlobalSymbol(symbol, arity) { + function getTypeDeclaration(symbol) { + var declarations = symbol.declarations; + for (var _i = 0, declarations_3 = declarations; _i < declarations_3.length; _i++) { + var declaration = declarations_3[_i]; + switch (declaration.kind) { + case 240: + case 241: + case 243: + return declaration; + } + } + } + if (!symbol) { + return arity ? emptyGenericType : emptyObjectType; + } + var type = getDeclaredTypeOfSymbol(symbol); + if (!(type.flags & 524288)) { + error(getTypeDeclaration(symbol), ts.Diagnostics.Global_type_0_must_be_a_class_or_interface_type, ts.symbolName(symbol)); + return arity ? emptyGenericType : emptyObjectType; + } + if (ts.length(type.typeParameters) !== arity) { + error(getTypeDeclaration(symbol), ts.Diagnostics.Global_type_0_must_have_1_type_parameter_s, ts.symbolName(symbol), arity); + return arity ? emptyGenericType : emptyObjectType; + } + return type; + } + function getGlobalValueSymbol(name, reportErrors) { + return getGlobalSymbol(name, 67220415, reportErrors ? ts.Diagnostics.Cannot_find_global_value_0 : undefined); + } + function getGlobalTypeSymbol(name, reportErrors) { + return getGlobalSymbol(name, 67897832, reportErrors ? ts.Diagnostics.Cannot_find_global_type_0 : undefined); + } + function getGlobalSymbol(name, meaning, diagnostic) { + return resolveName(undefined, name, meaning, diagnostic, name, false); + } + function getGlobalType(name, arity, reportErrors) { + var symbol = getGlobalTypeSymbol(name, reportErrors); + return symbol || reportErrors ? getTypeOfGlobalSymbol(symbol, arity) : undefined; + } + function getGlobalTypedPropertyDescriptorType() { + return deferredGlobalTypedPropertyDescriptorType || (deferredGlobalTypedPropertyDescriptorType = getGlobalType("TypedPropertyDescriptor", 1, true)) || emptyGenericType; + } + function getGlobalTemplateStringsArrayType() { + return deferredGlobalTemplateStringsArrayType || (deferredGlobalTemplateStringsArrayType = getGlobalType("TemplateStringsArray", 0, true)) || emptyObjectType; + } + function getGlobalImportMetaType() { + return deferredGlobalImportMetaType || (deferredGlobalImportMetaType = getGlobalType("ImportMeta", 0, true)) || emptyObjectType; + } + function getGlobalESSymbolConstructorSymbol(reportErrors) { + return deferredGlobalESSymbolConstructorSymbol || (deferredGlobalESSymbolConstructorSymbol = getGlobalValueSymbol("Symbol", reportErrors)); + } + function getGlobalESSymbolType(reportErrors) { + return deferredGlobalESSymbolType || (deferredGlobalESSymbolType = getGlobalType("Symbol", 0, reportErrors)) || emptyObjectType; + } + function getGlobalPromiseType(reportErrors) { + return deferredGlobalPromiseType || (deferredGlobalPromiseType = getGlobalType("Promise", 1, reportErrors)) || emptyGenericType; + } + function getGlobalPromiseLikeType(reportErrors) { + return deferredGlobalPromiseLikeType || (deferredGlobalPromiseLikeType = getGlobalType("PromiseLike", 1, reportErrors)) || emptyGenericType; + } + function getGlobalPromiseConstructorSymbol(reportErrors) { + return deferredGlobalPromiseConstructorSymbol || (deferredGlobalPromiseConstructorSymbol = getGlobalValueSymbol("Promise", reportErrors)); + } + function getGlobalPromiseConstructorLikeType(reportErrors) { + return deferredGlobalPromiseConstructorLikeType || (deferredGlobalPromiseConstructorLikeType = getGlobalType("PromiseConstructorLike", 0, reportErrors)) || emptyObjectType; + } + function getGlobalAsyncIterableType(reportErrors) { + return deferredGlobalAsyncIterableType || (deferredGlobalAsyncIterableType = getGlobalType("AsyncIterable", 1, reportErrors)) || emptyGenericType; + } + function getGlobalAsyncIteratorType(reportErrors) { + return deferredGlobalAsyncIteratorType || (deferredGlobalAsyncIteratorType = getGlobalType("AsyncIterator", 1, reportErrors)) || emptyGenericType; + } + function getGlobalAsyncIterableIteratorType(reportErrors) { + return deferredGlobalAsyncIterableIteratorType || (deferredGlobalAsyncIterableIteratorType = getGlobalType("AsyncIterableIterator", 1, reportErrors)) || emptyGenericType; + } + function getGlobalIterableType(reportErrors) { + return deferredGlobalIterableType || (deferredGlobalIterableType = getGlobalType("Iterable", 1, reportErrors)) || emptyGenericType; + } + function getGlobalIteratorType(reportErrors) { + return deferredGlobalIteratorType || (deferredGlobalIteratorType = getGlobalType("Iterator", 1, reportErrors)) || emptyGenericType; + } + function getGlobalIterableIteratorType(reportErrors) { + return deferredGlobalIterableIteratorType || (deferredGlobalIterableIteratorType = getGlobalType("IterableIterator", 1, reportErrors)) || emptyGenericType; + } + function getGlobalTypeOrUndefined(name, arity) { + if (arity === void 0) { arity = 0; } + var symbol = getGlobalSymbol(name, 67897832, undefined); + return symbol && getTypeOfGlobalSymbol(symbol, arity); + } + function getGlobalExtractSymbol() { + return deferredGlobalExtractSymbol || (deferredGlobalExtractSymbol = getGlobalSymbol("Extract", 524288, ts.Diagnostics.Cannot_find_global_type_0)); + } + function getGlobalExcludeSymbol() { + return deferredGlobalExcludeSymbol || (deferredGlobalExcludeSymbol = getGlobalSymbol("Exclude", 524288, ts.Diagnostics.Cannot_find_global_type_0)); + } + function getGlobalPickSymbol() { + return deferredGlobalPickSymbol || (deferredGlobalPickSymbol = getGlobalSymbol("Pick", 524288, ts.Diagnostics.Cannot_find_global_type_0)); + } + function getGlobalBigIntType(reportErrors) { + return deferredGlobalBigIntType || (deferredGlobalBigIntType = getGlobalType("BigInt", 0, reportErrors)) || emptyObjectType; + } + function createTypeFromGenericGlobalType(genericGlobalType, typeArguments) { + return genericGlobalType !== emptyGenericType ? createTypeReference(genericGlobalType, typeArguments) : emptyObjectType; + } + function createTypedPropertyDescriptorType(propertyType) { + return createTypeFromGenericGlobalType(getGlobalTypedPropertyDescriptorType(), [propertyType]); + } + function createAsyncIterableType(iteratedType) { + return createTypeFromGenericGlobalType(getGlobalAsyncIterableType(true), [iteratedType]); + } + function createAsyncIterableIteratorType(iteratedType) { + return createTypeFromGenericGlobalType(getGlobalAsyncIterableIteratorType(true), [iteratedType]); + } + function createIterableType(iteratedType) { + return createTypeFromGenericGlobalType(getGlobalIterableType(true), [iteratedType]); + } + function createIterableIteratorType(iteratedType) { + return createTypeFromGenericGlobalType(getGlobalIterableIteratorType(true), [iteratedType]); + } + function createArrayType(elementType) { + return createTypeFromGenericGlobalType(globalArrayType, [elementType]); + } + function createReadonlyArrayType(elementType) { + return createTypeFromGenericGlobalType(globalReadonlyArrayType, [elementType]); + } + function getTypeFromArrayTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + links.resolvedType = createArrayType(getTypeFromTypeNode(node.elementType)); + } + return links.resolvedType; + } + function createTupleTypeOfArity(arity, minLength, hasRestElement, associatedNames) { + var typeParameters; + var properties = []; + var maxLength = hasRestElement ? arity - 1 : arity; + if (arity) { + typeParameters = new Array(arity); + for (var i = 0; i < arity; i++) { + var typeParameter = typeParameters[i] = createType(262144); + if (i < maxLength) { + var property = createSymbol(4 | (i >= minLength ? 16777216 : 0), "" + i); + property.type = typeParameter; + properties.push(property); + } + } + } + var literalTypes = []; + for (var i = minLength; i <= maxLength; i++) + literalTypes.push(getLiteralType(i)); + var lengthSymbol = createSymbol(4, "length"); + lengthSymbol.type = hasRestElement ? numberType : getUnionType(literalTypes); + properties.push(lengthSymbol); + var type = createObjectType(8 | 4); + type.typeParameters = typeParameters; + type.outerTypeParameters = undefined; + type.localTypeParameters = typeParameters; + type.instantiations = ts.createMap(); + type.instantiations.set(getTypeListId(type.typeParameters), type); + type.target = type; + type.typeArguments = type.typeParameters; + type.thisType = createType(262144); + type.thisType.isThisType = true; + type.thisType.constraint = type; + type.declaredProperties = properties; + type.declaredCallSignatures = ts.emptyArray; + type.declaredConstructSignatures = ts.emptyArray; + type.declaredStringIndexInfo = undefined; + type.declaredNumberIndexInfo = undefined; + type.minLength = minLength; + type.hasRestElement = hasRestElement; + type.associatedNames = associatedNames; + return type; + } + function getTupleTypeOfArity(arity, minLength, hasRestElement, associatedNames) { + var key = arity + (hasRestElement ? "+" : ",") + minLength + (associatedNames && associatedNames.length ? "," + associatedNames.join(",") : ""); + var type = tupleTypes.get(key); + if (!type) { + tupleTypes.set(key, type = createTupleTypeOfArity(arity, minLength, hasRestElement, associatedNames)); + } + return type; + } + function createTupleType(elementTypes, minLength, hasRestElement, associatedNames) { + if (minLength === void 0) { minLength = elementTypes.length; } + if (hasRestElement === void 0) { hasRestElement = false; } + var arity = elementTypes.length; + if (arity === 1 && hasRestElement) { + return createArrayType(elementTypes[0]); + } + var tupleType = getTupleTypeOfArity(arity, minLength, arity > 0 && hasRestElement, associatedNames); + return elementTypes.length ? createTypeReference(tupleType, elementTypes) : tupleType; + } + function getTypeFromTupleTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + var lastElement = ts.lastOrUndefined(node.elementTypes); + var restElement_1 = lastElement && lastElement.kind === 172 ? lastElement : undefined; + var minLength = ts.findLastIndex(node.elementTypes, function (n) { return n.kind !== 171 && n !== restElement_1; }) + 1; + var elementTypes = ts.map(node.elementTypes, function (n) { + var type = getTypeFromTypeNode(n); + return n === restElement_1 && getIndexTypeOfType(type, 1) || type; + }); + links.resolvedType = createTupleType(elementTypes, minLength, !!restElement_1); + } + return links.resolvedType; + } + function sliceTupleType(type, index) { + var tuple = type.target; + if (tuple.hasRestElement) { + index = Math.min(index, getTypeReferenceArity(type) - 1); + } + return createTupleType((type.typeArguments || ts.emptyArray).slice(index), Math.max(0, tuple.minLength - index), tuple.hasRestElement, tuple.associatedNames && tuple.associatedNames.slice(index)); + } + function getTypeFromOptionalTypeNode(node) { + var type = getTypeFromTypeNode(node.type); + return strictNullChecks ? getOptionalType(type) : type; + } + function getTypeId(type) { + return type.id; + } + function containsType(types, type) { + return ts.binarySearch(types, type, getTypeId, ts.compareValues) >= 0; + } + function insertType(types, type) { + var index = ts.binarySearch(types, type, getTypeId, ts.compareValues); + if (index < 0) { + types.splice(~index, 0, type); + return true; + } + return false; + } + function isEmptyIntersectionType(type) { + var combined = 0; + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (t.flags & 109440 && combined & 109440) { + return true; + } + combined |= t.flags; + if (combined & 98304 && combined & (524288 | 67108864) || + combined & 67108864 && combined & (67238908 & ~67108864) || + combined & 132 && combined & (67238908 & ~132) || + combined & 296 && combined & (67238908 & ~296) || + combined & 2112 && combined & (67238908 & ~2112) || + combined & 12288 && combined & (67238908 & ~12288) || + combined & 49152 && combined & (67238908 & ~49152)) { + return true; + } + } + return false; + } + function addTypeToUnion(typeSet, includes, type) { + var flags = type.flags; + if (flags & 1048576) { + return addTypesToUnion(typeSet, includes, type.types); + } + if (!(flags & 131072 || flags & 2097152 && isEmptyIntersectionType(type))) { + includes |= flags & ~939524096; + if (type === wildcardType) + includes |= 268435456; + if (!strictNullChecks && flags & 98304) { + if (!(flags & 134217728)) + includes |= 134217728; + } + else { + var len = typeSet.length; + var index = len && type.id > typeSet[len - 1].id ? ~len : ts.binarySearch(typeSet, type, getTypeId, ts.compareValues); + if (index < 0) { + typeSet.splice(~index, 0, type); + } + } + } + return includes; + } + function addTypesToUnion(typeSet, includes, types) { + for (var _i = 0, types_6 = types; _i < types_6.length; _i++) { + var type = types_6[_i]; + includes = addTypeToUnion(typeSet, includes, type); + } + return includes; + } + function isSubtypeOfAny(source, targets) { + for (var _i = 0, targets_1 = targets; _i < targets_1.length; _i++) { + var target = targets_1[_i]; + if (source !== target && isTypeSubtypeOf(source, target) && (!(ts.getObjectFlags(getTargetType(source)) & 1) || + !(ts.getObjectFlags(getTargetType(target)) & 1) || + isTypeDerivedFrom(source, target))) { + return true; + } + } + return false; + } + function isSetOfLiteralsFromSameEnum(types) { + var first = types[0]; + if (first.flags & 1024) { + var firstEnum = getParentOfSymbol(first.symbol); + for (var i = 1; i < types.length; i++) { + var other = types[i]; + if (!(other.flags & 1024) || (firstEnum !== getParentOfSymbol(other.symbol))) { + return false; + } + } + return true; + } + return false; + } + function removeSubtypes(types) { + if (types.length === 0 || isSetOfLiteralsFromSameEnum(types)) { + return; + } + var i = types.length; + while (i > 0) { + i--; + if (isSubtypeOfAny(types[i], types)) { + ts.orderedRemoveItemAt(types, i); + } + } + } + function removeRedundantLiteralTypes(types, includes) { + var i = types.length; + while (i > 0) { + i--; + var t = types[i]; + var remove = t.flags & 128 && includes & 4 || + t.flags & 256 && includes & 8 || + t.flags & 2048 && includes & 64 || + t.flags & 8192 && includes & 4096 || + isFreshLiteralType(t) && containsType(types, t.regularType); + if (remove) { + ts.orderedRemoveItemAt(types, i); + } + } + } + function getUnionType(types, unionReduction, aliasSymbol, aliasTypeArguments) { + if (unionReduction === void 0) { unionReduction = 1; } + if (types.length === 0) { + return neverType; + } + if (types.length === 1) { + return types[0]; + } + var typeSet = []; + var includes = addTypesToUnion(typeSet, 0, types); + if (unionReduction !== 0) { + if (includes & 3) { + return includes & 1 ? includes & 268435456 ? wildcardType : anyType : unknownType; + } + switch (unionReduction) { + case 1: + if (includes & 8576 | 512) { + removeRedundantLiteralTypes(typeSet, includes); + } + break; + case 2: + removeSubtypes(typeSet); + break; + } + if (typeSet.length === 0) { + return includes & 65536 ? includes & 134217728 ? nullType : nullWideningType : + includes & 32768 ? includes & 134217728 ? undefinedType : undefinedWideningType : + neverType; + } + } + return getUnionTypeFromSortedList(typeSet, !(includes & 66994211), aliasSymbol, aliasTypeArguments); + } + function getUnionTypePredicate(signatures) { + var first; + var types = []; + for (var _i = 0, signatures_2 = signatures; _i < signatures_2.length; _i++) { + var sig = signatures_2[_i]; + var pred = getTypePredicateOfSignature(sig); + if (!pred) { + continue; + } + if (first) { + if (!typePredicateKindsMatch(first, pred)) { + return undefined; + } + } + else { + first = pred; + } + types.push(pred.type); + } + if (!first) { + return undefined; + } + var unionType = getUnionType(types); + return ts.isIdentifierTypePredicate(first) + ? createIdentifierTypePredicate(first.parameterName, first.parameterIndex, unionType) + : createThisTypePredicate(unionType); + } + function typePredicateKindsMatch(a, b) { + return ts.isIdentifierTypePredicate(a) + ? ts.isIdentifierTypePredicate(b) && a.parameterIndex === b.parameterIndex + : !ts.isIdentifierTypePredicate(b); + } + function getUnionTypeFromSortedList(types, primitiveTypesOnly, aliasSymbol, aliasTypeArguments) { + if (types.length === 0) { + return neverType; + } + if (types.length === 1) { + return types[0]; + } + var id = getTypeListId(types); + var type = unionTypes.get(id); + if (!type) { + var propagatedFlags = getPropagatingFlagsOfTypes(types, 98304); + type = createType(1048576 | propagatedFlags); + unionTypes.set(id, type); + type.types = types; + type.primitiveTypesOnly = primitiveTypesOnly; + type.aliasSymbol = aliasSymbol; + type.aliasTypeArguments = aliasTypeArguments; + } + return type; + } + function getTypeFromUnionTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + var aliasSymbol = getAliasSymbolForTypeNode(node); + links.resolvedType = getUnionType(ts.map(node.types, getTypeFromTypeNode), 1, aliasSymbol, getTypeArgumentsForAliasSymbol(aliasSymbol)); + } + return links.resolvedType; + } + function addTypeToIntersection(typeSet, includes, type) { + var flags = type.flags; + if (flags & 2097152) { + return addTypesToIntersection(typeSet, includes, type.types); + } + if (isEmptyAnonymousObjectType(type)) { + if (!(includes & 536870912)) { + includes |= 536870912; + typeSet.push(type); + } + } + else { + includes |= flags & ~939524096; + if (flags & 3) { + if (type === wildcardType) + includes |= 268435456; + } + else if ((strictNullChecks || !(flags & 98304)) && !ts.contains(typeSet, type)) { + typeSet.push(type); + } + } + return includes; + } + function addTypesToIntersection(typeSet, includes, types) { + for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { + var type = types_7[_i]; + includes = addTypeToIntersection(typeSet, includes, getRegularTypeOfLiteralType(type)); + } + return includes; + } + function removeRedundantPrimitiveTypes(types, includes) { + var i = types.length; + while (i > 0) { + i--; + var t = types[i]; + var remove = t.flags & 4 && includes & 128 || + t.flags & 8 && includes & 256 || + t.flags & 64 && includes & 2048 || + t.flags & 4096 && includes & 8192; + if (remove) { + ts.orderedRemoveItemAt(types, i); + } + } + } + function eachUnionContains(unionTypes, type) { + for (var _i = 0, unionTypes_1 = unionTypes; _i < unionTypes_1.length; _i++) { + var u = unionTypes_1[_i]; + if (!containsType(u.types, type)) { + var primitive = type.flags & 128 ? stringType : + type.flags & 256 ? numberType : + type.flags & 2048 ? bigintType : + type.flags & 8192 ? esSymbolType : + undefined; + if (!primitive || !containsType(u.types, primitive)) { + return false; + } + } + } + return true; + } + function intersectUnionsOfPrimitiveTypes(types) { + var unionTypes; + var index = ts.findIndex(types, function (t) { return !!(t.flags & 1048576) && t.primitiveTypesOnly; }); + if (index < 0) { + return false; + } + var i = index + 1; + while (i < types.length) { + var t = types[i]; + if (t.flags & 1048576 && t.primitiveTypesOnly) { + (unionTypes || (unionTypes = [types[index]])).push(t); + ts.orderedRemoveItemAt(types, i); + } + else { + i++; + } + } + if (!unionTypes) { + return false; + } + var checked = []; + var result = []; + for (var _i = 0, unionTypes_2 = unionTypes; _i < unionTypes_2.length; _i++) { + var u = unionTypes_2[_i]; + for (var _a = 0, _b = u.types; _a < _b.length; _a++) { + var t = _b[_a]; + if (insertType(checked, t)) { + if (eachUnionContains(unionTypes, t)) { + insertType(result, t); + } + } + } + } + types[index] = getUnionTypeFromSortedList(result, true); + return true; + } + function getIntersectionType(types, aliasSymbol, aliasTypeArguments) { + var typeSet = []; + var includes = addTypesToIntersection(typeSet, 0, types); + if (includes & 131072) { + return neverType; + } + if (includes & 1) { + return includes & 268435456 ? wildcardType : anyType; + } + if (!strictNullChecks && includes & 98304) { + return includes & 32768 ? undefinedType : nullType; + } + if (includes & 4 && includes & 128 || + includes & 8 && includes & 256 || + includes & 64 && includes & 2048 || + includes & 4096 && includes & 8192) { + removeRedundantPrimitiveTypes(typeSet, includes); + } + if (includes & 536870912 && includes & 524288) { + ts.orderedRemoveItemAt(typeSet, ts.findIndex(typeSet, isEmptyAnonymousObjectType)); + } + if (typeSet.length === 0) { + return unknownType; + } + if (typeSet.length === 1) { + return typeSet[0]; + } + if (includes & 1048576) { + if (intersectUnionsOfPrimitiveTypes(typeSet)) { + return getIntersectionType(typeSet, aliasSymbol, aliasTypeArguments); + } + var unionIndex_1 = ts.findIndex(typeSet, function (t) { return (t.flags & 1048576) !== 0; }); + var unionType = typeSet[unionIndex_1]; + return getUnionType(ts.map(unionType.types, function (t) { return getIntersectionType(ts.replaceElement(typeSet, unionIndex_1, t)); }), 1, aliasSymbol, aliasTypeArguments); + } + var id = getTypeListId(typeSet); + var type = intersectionTypes.get(id); + if (!type) { + var propagatedFlags = getPropagatingFlagsOfTypes(typeSet, 98304); + type = createType(2097152 | propagatedFlags); + intersectionTypes.set(id, type); + type.types = typeSet; + type.aliasSymbol = aliasSymbol; + type.aliasTypeArguments = aliasTypeArguments; + } + return type; + } + function getTypeFromIntersectionTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + var aliasSymbol = getAliasSymbolForTypeNode(node); + links.resolvedType = getIntersectionType(ts.map(node.types, getTypeFromTypeNode), aliasSymbol, getTypeArgumentsForAliasSymbol(aliasSymbol)); + } + return links.resolvedType; + } + function createIndexType(type, stringsOnly) { + var result = createType(4194304); + result.type = type; + result.stringsOnly = stringsOnly; + return result; + } + function getIndexTypeForGenericType(type, stringsOnly) { + return stringsOnly ? + type.resolvedStringIndexType || (type.resolvedStringIndexType = createIndexType(type, true)) : + type.resolvedIndexType || (type.resolvedIndexType = createIndexType(type, false)); + } + function getLiteralTypeFromPropertyName(name) { + return ts.isIdentifier(name) ? getLiteralType(ts.unescapeLeadingUnderscores(name.escapedText)) : + getRegularTypeOfLiteralType(ts.isComputedPropertyName(name) ? checkComputedPropertyName(name) : checkExpression(name)); + } + function getBigIntLiteralType(node) { + return getLiteralType({ + negative: false, + base10Value: ts.parsePseudoBigInt(node.text) + }); + } + function getLiteralTypeFromProperty(prop, include) { + if (!(ts.getDeclarationModifierFlagsFromSymbol(prop) & 24)) { + var type = getLateBoundSymbol(prop).nameType; + if (!type && !ts.isKnownSymbol(prop)) { + if (prop.escapedName === "default") { + type = getLiteralType("default"); + } + else { + var name = prop.valueDeclaration && ts.getNameOfDeclaration(prop.valueDeclaration); + type = name && getLiteralTypeFromPropertyName(name) || getLiteralType(ts.symbolName(prop)); + } + } + if (type && type.flags & include) { + return type; + } + } + return neverType; + } + function getLiteralTypeFromProperties(type, include) { + return getUnionType(ts.map(getPropertiesOfType(type), function (t) { return getLiteralTypeFromProperty(t, include); })); + } + function getNonEnumNumberIndexInfo(type) { + var numberIndexInfo = getIndexInfoOfType(type, 1); + return numberIndexInfo !== enumNumberIndexInfo ? numberIndexInfo : undefined; + } + function getIndexType(type, stringsOnly) { + if (stringsOnly === void 0) { stringsOnly = keyofStringsOnly; } + return type.flags & 1048576 ? getIntersectionType(ts.map(type.types, function (t) { return getIndexType(t, stringsOnly); })) : + type.flags & 2097152 ? getUnionType(ts.map(type.types, function (t) { return getIndexType(t, stringsOnly); })) : + maybeTypeOfKind(type, 58982400) ? getIndexTypeForGenericType(type, stringsOnly) : + ts.getObjectFlags(type) & 32 ? getConstraintTypeFromMappedType(type) : + type === wildcardType ? wildcardType : + type.flags & 1 ? keyofConstraintType : + stringsOnly ? getIndexInfoOfType(type, 0) ? stringType : getLiteralTypeFromProperties(type, 128) : + getIndexInfoOfType(type, 0) ? getUnionType([stringType, numberType, getLiteralTypeFromProperties(type, 8192)]) : + getNonEnumNumberIndexInfo(type) ? getUnionType([numberType, getLiteralTypeFromProperties(type, 128 | 8192)]) : + getLiteralTypeFromProperties(type, 8576); + } + function getExtractStringType(type) { + if (keyofStringsOnly) { + return type; + } + var extractTypeAlias = getGlobalExtractSymbol(); + return extractTypeAlias ? getTypeAliasInstantiation(extractTypeAlias, [type, stringType]) : stringType; + } + function getIndexTypeOrString(type) { + var indexType = getExtractStringType(getIndexType(type)); + return indexType.flags & 131072 ? stringType : indexType; + } + function getTypeFromTypeOperatorNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + switch (node.operator) { + case 129: + links.resolvedType = getIndexType(getTypeFromTypeNode(node.type)); + break; + case 142: + links.resolvedType = node.type.kind === 139 + ? getESSymbolLikeTypeForNode(ts.walkUpParenthesizedTypes(node.parent)) + : errorType; + break; + } + } + return links.resolvedType; + } + function createIndexedAccessType(objectType, indexType) { + var type = createType(8388608); + type.objectType = objectType; + type.indexType = indexType; + return type; + } + function isJSLiteralType(type) { + if (noImplicitAny) { + return false; + } + if (ts.getObjectFlags(type) & 16384) { + return true; + } + if (type.flags & 1048576) { + return ts.every(type.types, isJSLiteralType); + } + if (type.flags & 2097152) { + return ts.some(type.types, isJSLiteralType); + } + if (type.flags & 63176704) { + return isJSLiteralType(getResolvedBaseConstraint(type)); + } + return false; + } + function getPropertyTypeForIndexType(objectType, indexType, accessNode, cacheSymbol, missingType) { + var accessExpression = accessNode && accessNode.kind === 190 ? accessNode : undefined; + var propName = isTypeUsableAsLateBoundName(indexType) + ? getLateBoundNameFromType(indexType) + : accessExpression && checkThatExpressionIsProperSymbolReference(accessExpression.argumentExpression, indexType, false) + ? ts.getPropertyNameForKnownSymbolName(ts.idText(accessExpression.argumentExpression.name)) + : accessNode && ts.isPropertyName(accessNode) + ? ts.getPropertyNameForPropertyNameNode(accessNode) + : undefined; + if (propName !== undefined) { + var prop = getPropertyOfType(objectType, propName); + if (prop) { + if (accessExpression) { + markPropertyAsReferenced(prop, accessExpression, accessExpression.expression.kind === 100); + if (ts.isAssignmentTarget(accessExpression) && (isReferenceToReadonlyEntity(accessExpression, prop) || isReferenceThroughNamespaceImport(accessExpression))) { + error(accessExpression.argumentExpression, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, symbolToString(prop)); + return missingType; + } + if (cacheSymbol) { + getNodeLinks(accessNode).resolvedSymbol = prop; + } + } + var propType = getTypeOfSymbol(prop); + return accessExpression && ts.getAssignmentTargetKind(accessExpression) !== 1 ? + getFlowTypeOfReference(accessExpression, propType) : + propType; + } + if (everyType(objectType, isTupleType) && isNumericLiteralName(propName) && +propName >= 0) { + if (accessNode && everyType(objectType, function (t) { return !t.target.hasRestElement; })) { + var indexNode = getIndexNodeForAccessExpression(accessNode); + error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(propName), typeToString(objectType)); + } + return mapType(objectType, function (t) { return getRestTypeOfTupleType(t) || undefinedType; }); + } + } + if (!(indexType.flags & 98304) && isTypeAssignableToKind(indexType, 132 | 296 | 12288)) { + if (objectType.flags & (1 | 131072)) { + return objectType; + } + var indexInfo = isTypeAssignableToKind(indexType, 296) && getIndexInfoOfType(objectType, 1) || + getIndexInfoOfType(objectType, 0) || + undefined; + if (indexInfo) { + if (accessNode && !isTypeAssignableToKind(indexType, 4 | 8)) { + var indexNode = getIndexNodeForAccessExpression(accessNode); + error(indexNode, ts.Diagnostics.Type_0_cannot_be_used_as_an_index_type, typeToString(indexType)); + } + else if (accessExpression && indexInfo.isReadonly && (ts.isAssignmentTarget(accessExpression) || ts.isDeleteTarget(accessExpression))) { + error(accessExpression, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(objectType)); + } + return indexInfo.type; + } + if (indexType.flags & 131072) { + return neverType; + } + if (isJSLiteralType(objectType)) { + return anyType; + } + if (accessExpression && !isConstEnumObjectType(objectType)) { + if (noImplicitAny && !compilerOptions.suppressImplicitAnyIndexErrors) { + if (propName !== undefined && typeHasStaticProperty(propName, objectType)) { + error(accessExpression, ts.Diagnostics.Property_0_is_a_static_member_of_type_1, propName, typeToString(objectType)); + } + else if (getIndexTypeOfType(objectType, 1)) { + error(accessExpression.argumentExpression, ts.Diagnostics.Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number); + } + else { + var suggestion = void 0; + if (propName !== undefined && (suggestion = getSuggestionForNonexistentProperty(propName, objectType))) { + if (suggestion !== undefined) { + error(accessExpression.argumentExpression, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2, propName, typeToString(objectType), suggestion); + } + } + else { + error(accessExpression, ts.Diagnostics.Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature, typeToString(objectType)); + } + } + } + return missingType; + } + } + if (isJSLiteralType(objectType)) { + return anyType; + } + if (accessNode) { + var indexNode = getIndexNodeForAccessExpression(accessNode); + if (indexType.flags & (128 | 256)) { + error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, "" + indexType.value, typeToString(objectType)); + } + else if (indexType.flags & (4 | 8)) { + error(indexNode, ts.Diagnostics.Type_0_has_no_matching_index_signature_for_type_1, typeToString(objectType), typeToString(indexType)); + } + else { + error(indexNode, ts.Diagnostics.Type_0_cannot_be_used_as_an_index_type, typeToString(indexType)); + } + } + if (isTypeAny(indexType)) { + return indexType; + } + return missingType; + } + function getIndexNodeForAccessExpression(accessNode) { + return accessNode.kind === 190 + ? accessNode.argumentExpression + : accessNode.kind === 180 + ? accessNode.indexType + : accessNode.kind === 149 + ? accessNode.expression + : accessNode; + } + function isGenericObjectType(type) { + return maybeTypeOfKind(type, 58982400 | 134217728); + } + function isGenericIndexType(type) { + return maybeTypeOfKind(type, 58982400 | 4194304); + } + function getSimplifiedType(type) { + return type.flags & 8388608 ? getSimplifiedIndexedAccessType(type) : type; + } + function distributeIndexOverObjectType(objectType, indexType) { + if (objectType.flags & 1048576) { + return mapType(objectType, function (t) { return getSimplifiedType(getIndexedAccessType(t, indexType)); }); + } + if (objectType.flags & 2097152) { + return getIntersectionType(ts.map(objectType.types, function (t) { return getSimplifiedType(getIndexedAccessType(t, indexType)); })); + } + } + function getSimplifiedIndexedAccessType(type) { + if (type.simplified) { + return type.simplified === circularConstraintType ? type : type.simplified; + } + type.simplified = circularConstraintType; + var objectType = getSimplifiedType(type.objectType); + var indexType = getSimplifiedType(type.indexType); + if (indexType.flags & 1048576) { + return type.simplified = mapType(indexType, function (t) { return getSimplifiedType(getIndexedAccessType(objectType, t)); }); + } + if (!(indexType.flags & 63176704)) { + var simplified = distributeIndexOverObjectType(objectType, indexType); + if (simplified) { + return type.simplified = simplified; + } + } + if (isGenericMappedType(objectType)) { + return type.simplified = substituteIndexedMappedType(objectType, type); + } + if (objectType.flags & 262144) { + var constraint = getConstraintOfTypeParameter(objectType); + if (constraint && isGenericMappedType(constraint)) { + return type.simplified = substituteIndexedMappedType(constraint, type); + } + } + return type.simplified = type; + } + function substituteIndexedMappedType(objectType, type) { + var mapper = createTypeMapper([getTypeParameterFromMappedType(objectType)], [type.indexType]); + var templateMapper = combineTypeMappers(objectType.mapper, mapper); + return instantiateType(getTemplateTypeFromMappedType(objectType), templateMapper); + } + function getIndexedAccessType(objectType, indexType, accessNode, missingType) { + if (missingType === void 0) { missingType = accessNode ? errorType : unknownType; } + if (objectType === wildcardType || indexType === wildcardType) { + return wildcardType; + } + if (isGenericIndexType(indexType) || !(accessNode && accessNode.kind !== 180) && isGenericObjectType(objectType)) { + if (objectType.flags & 3) { + return objectType; + } + var id = objectType.id + "," + indexType.id; + var type = indexedAccessTypes.get(id); + if (!type) { + indexedAccessTypes.set(id, type = createIndexedAccessType(objectType, indexType)); + } + return type; + } + var apparentObjectType = getApparentType(objectType); + if (indexType.flags & 1048576 && !(indexType.flags & 16)) { + var propTypes = []; + var wasMissingProp = false; + for (var _i = 0, _a = indexType.types; _i < _a.length; _i++) { + var t = _a[_i]; + var propType = getPropertyTypeForIndexType(apparentObjectType, t, accessNode, false, missingType); + if (propType === missingType) { + if (!accessNode) { + return missingType; + } + else { + wasMissingProp = true; + } + } + propTypes.push(propType); + } + if (wasMissingProp) { + return missingType; + } + return getUnionType(propTypes); + } + return getPropertyTypeForIndexType(apparentObjectType, indexType, accessNode, true, missingType); + } + function getTypeFromIndexedAccessTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + var objectType = getTypeFromTypeNode(node.objectType); + var indexType = getTypeFromTypeNode(node.indexType); + var resolved = getIndexedAccessType(objectType, indexType, node); + links.resolvedType = resolved.flags & 8388608 && + resolved.objectType === objectType && + resolved.indexType === indexType ? + getConstrainedTypeVariable(resolved, node) : resolved; + } + return links.resolvedType; + } + function getTypeFromMappedTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + var type = createObjectType(32, node.symbol); + type.declaration = node; + type.aliasSymbol = getAliasSymbolForTypeNode(node); + type.aliasTypeArguments = getTypeArgumentsForAliasSymbol(type.aliasSymbol); + links.resolvedType = type; + getConstraintTypeFromMappedType(type); + } + return links.resolvedType; + } + function getActualTypeVariable(type) { + return type.flags & 33554432 ? type.typeVariable : type; + } + function getConditionalType(root, mapper) { + var checkType = instantiateType(root.checkType, mapper); + var extendsType = instantiateType(root.extendsType, mapper); + if (checkType === wildcardType || extendsType === wildcardType) { + return wildcardType; + } + var isDeferred = root.isDistributive && maybeTypeOfKind(checkType, 63176704); + var combinedMapper; + if (root.inferTypeParameters) { + var context = createInferenceContext(root.inferTypeParameters, undefined, 0); + if (!isDeferred) { + inferTypes(context.inferences, checkType, extendsType, 32 | 64); + } + combinedMapper = combineTypeMappers(mapper, context); + } + if (!isDeferred) { + if (extendsType.flags & 3) { + return instantiateType(root.trueType, mapper); + } + if (checkType.flags & 1) { + return getUnionType([instantiateType(root.trueType, combinedMapper || mapper), instantiateType(root.falseType, mapper)]); + } + var inferredExtendsType = combinedMapper ? instantiateType(root.extendsType, combinedMapper) : extendsType; + if (!isTypeAssignableTo(getWildcardInstantiation(checkType), getWildcardInstantiation(inferredExtendsType))) { + return instantiateType(root.falseType, mapper); + } + if (checkTypeRelatedTo(checkType, inferredExtendsType, definitelyAssignableRelation, undefined)) { + return instantiateType(root.trueType, combinedMapper || mapper); + } + } + var erasedCheckType = getActualTypeVariable(checkType); + var result = createType(16777216); + result.root = root; + result.checkType = erasedCheckType; + result.extendsType = extendsType; + result.mapper = mapper; + result.combinedMapper = combinedMapper; + result.aliasSymbol = root.aliasSymbol; + result.aliasTypeArguments = instantiateTypes(root.aliasTypeArguments, mapper); + return result; + } + function getTrueTypeFromConditionalType(type) { + return type.resolvedTrueType || (type.resolvedTrueType = instantiateType(type.root.trueType, type.mapper)); + } + function getFalseTypeFromConditionalType(type) { + return type.resolvedFalseType || (type.resolvedFalseType = instantiateType(type.root.falseType, type.mapper)); + } + function getInferTypeParameters(node) { + var result; + if (node.locals) { + node.locals.forEach(function (symbol) { + if (symbol.flags & 262144) { + result = ts.append(result, getDeclaredTypeOfSymbol(symbol)); + } + }); + } + return result; + } + function isPossiblyReferencedInConditionalType(tp, node) { + if (isTypeParameterPossiblyReferenced(tp, node)) { + return true; + } + while (node) { + if (node.kind === 175) { + if (isTypeParameterPossiblyReferenced(tp, node.extendsType)) { + return true; + } + } + node = node.parent; + } + return false; + } + function getTypeFromConditionalTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + var checkType = getTypeFromTypeNode(node.checkType); + var aliasSymbol = getAliasSymbolForTypeNode(node); + var aliasTypeArguments = getTypeArgumentsForAliasSymbol(aliasSymbol); + var allOuterTypeParameters = getOuterTypeParameters(node, true); + var outerTypeParameters = aliasTypeArguments ? allOuterTypeParameters : ts.filter(allOuterTypeParameters, function (tp) { return isPossiblyReferencedInConditionalType(tp, node); }); + var root = { + node: node, + checkType: checkType, + extendsType: getTypeFromTypeNode(node.extendsType), + trueType: getTypeFromTypeNode(node.trueType), + falseType: getTypeFromTypeNode(node.falseType), + isDistributive: !!(checkType.flags & 262144), + inferTypeParameters: getInferTypeParameters(node), + outerTypeParameters: outerTypeParameters, + instantiations: undefined, + aliasSymbol: aliasSymbol, + aliasTypeArguments: aliasTypeArguments + }; + links.resolvedType = getConditionalType(root, undefined); + if (outerTypeParameters) { + root.instantiations = ts.createMap(); + root.instantiations.set(getTypeListId(outerTypeParameters), links.resolvedType); + } + } + return links.resolvedType; + } + function getTypeFromInferTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + links.resolvedType = getDeclaredTypeOfTypeParameter(getSymbolOfNode(node.typeParameter)); + } + return links.resolvedType; + } + function getIdentifierChain(node) { + if (ts.isIdentifier(node)) { + return [node]; + } + else { + return ts.append(getIdentifierChain(node.left), node.right); + } + } + function getTypeFromImportTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + if (node.isTypeOf && node.typeArguments) { + error(node, ts.Diagnostics.Type_arguments_cannot_be_used_here); + links.resolvedSymbol = unknownSymbol; + return links.resolvedType = errorType; + } + if (!ts.isLiteralImportTypeNode(node)) { + error(node.argument, ts.Diagnostics.String_literal_expected); + links.resolvedSymbol = unknownSymbol; + return links.resolvedType = errorType; + } + var targetMeaning = node.isTypeOf ? 67220415 : node.flags & 2097152 ? 67220415 | 67897832 : 67897832; + var innerModuleSymbol = resolveExternalModuleName(node, node.argument.literal); + if (!innerModuleSymbol) { + links.resolvedSymbol = unknownSymbol; + return links.resolvedType = errorType; + } + var moduleSymbol = resolveExternalModuleSymbol(innerModuleSymbol, false); + if (!ts.nodeIsMissing(node.qualifier)) { + var nameStack = getIdentifierChain(node.qualifier); + var currentNamespace = moduleSymbol; + var current = void 0; + while (current = nameStack.shift()) { + var meaning = nameStack.length ? 1920 : targetMeaning; + var next = getSymbol(getExportsOfSymbol(getMergedSymbol(resolveSymbol(currentNamespace))), current.escapedText, meaning); + if (!next) { + error(current, ts.Diagnostics.Namespace_0_has_no_exported_member_1, getFullyQualifiedName(currentNamespace), ts.declarationNameToString(current)); + return links.resolvedType = errorType; + } + getNodeLinks(current).resolvedSymbol = next; + getNodeLinks(current.parent).resolvedSymbol = next; + currentNamespace = next; + } + resolveImportSymbolType(node, links, currentNamespace, targetMeaning); + } + else { + if (moduleSymbol.flags & targetMeaning) { + resolveImportSymbolType(node, links, moduleSymbol, targetMeaning); + } + else { + var errorMessage = targetMeaning === 67220415 + ? ts.Diagnostics.Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here + : ts.Diagnostics.Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0; + error(node, errorMessage, node.argument.literal.text); + links.resolvedSymbol = unknownSymbol; + links.resolvedType = errorType; + } + } + } + return links.resolvedType; + } + function resolveImportSymbolType(node, links, symbol, meaning) { + var resolvedSymbol = resolveSymbol(symbol); + links.resolvedSymbol = resolvedSymbol; + if (meaning === 67220415) { + return links.resolvedType = getTypeOfSymbol(symbol); + } + else { + return links.resolvedType = getTypeReferenceType(node, resolvedSymbol); + } + } + function getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + var aliasSymbol = getAliasSymbolForTypeNode(node); + if (getMembersOfSymbol(node.symbol).size === 0 && !aliasSymbol) { + links.resolvedType = emptyTypeLiteralType; + } + else { + var type = createObjectType(16, node.symbol); + type.aliasSymbol = aliasSymbol; + type.aliasTypeArguments = getTypeArgumentsForAliasSymbol(aliasSymbol); + if (ts.isJSDocTypeLiteral(node) && node.isArrayType) { + type = createArrayType(type); + } + links.resolvedType = type; + } + } + return links.resolvedType; + } + function getAliasSymbolForTypeNode(node) { + return ts.isTypeAlias(node.parent) ? getSymbolOfNode(node.parent) : undefined; + } + function getTypeArgumentsForAliasSymbol(symbol) { + return symbol ? getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) : undefined; + } + function isNonGenericObjectType(type) { + return !!(type.flags & 524288) && !isGenericMappedType(type); + } + function getSpreadType(left, right, symbol, typeFlags, objectFlags) { + if (left.flags & 1 || right.flags & 1) { + return anyType; + } + if (left.flags & 2 || right.flags & 2) { + return unknownType; + } + if (left.flags & 131072) { + return right; + } + if (right.flags & 131072) { + return left; + } + if (left.flags & 1048576) { + return mapType(left, function (t) { return getSpreadType(t, right, symbol, typeFlags, objectFlags); }); + } + if (right.flags & 1048576) { + return mapType(right, function (t) { return getSpreadType(left, t, symbol, typeFlags, objectFlags); }); + } + if (right.flags & (528 | 296 | 2112 | 132 | 1056 | 67108864 | 4194304)) { + return left; + } + if (isGenericObjectType(left) || isGenericObjectType(right)) { + if (isEmptyObjectType(left)) { + return right; + } + if (left.flags & 2097152) { + var types = left.types; + var lastLeft = types[types.length - 1]; + if (isNonGenericObjectType(lastLeft) && isNonGenericObjectType(right)) { + return getIntersectionType(ts.concatenate(types.slice(0, types.length - 1), [getSpreadType(lastLeft, right, symbol, typeFlags, objectFlags)])); + } + } + return getIntersectionType([left, right]); + } + var members = ts.createSymbolTable(); + var skippedPrivateMembers = ts.createUnderscoreEscapedMap(); + var stringIndexInfo; + var numberIndexInfo; + if (left === emptyObjectType) { + stringIndexInfo = getIndexInfoOfType(right, 0); + numberIndexInfo = getIndexInfoOfType(right, 1); + } + else { + stringIndexInfo = unionSpreadIndexInfos(getIndexInfoOfType(left, 0), getIndexInfoOfType(right, 0)); + numberIndexInfo = unionSpreadIndexInfos(getIndexInfoOfType(left, 1), getIndexInfoOfType(right, 1)); + } + for (var _i = 0, _a = getPropertiesOfType(right); _i < _a.length; _i++) { + var rightProp = _a[_i]; + if (ts.getDeclarationModifierFlagsFromSymbol(rightProp) & (8 | 16)) { + skippedPrivateMembers.set(rightProp.escapedName, true); + } + else if (isSpreadableProperty(rightProp)) { + members.set(rightProp.escapedName, getSpreadSymbol(rightProp)); + } + } + for (var _b = 0, _c = getPropertiesOfType(left); _b < _c.length; _b++) { + var leftProp = _c[_b]; + if (skippedPrivateMembers.has(leftProp.escapedName) || !isSpreadableProperty(leftProp)) { + continue; + } + if (members.has(leftProp.escapedName)) { + var rightProp = members.get(leftProp.escapedName); + var rightType = getTypeOfSymbol(rightProp); + if (rightProp.flags & 16777216) { + var declarations = ts.concatenate(leftProp.declarations, rightProp.declarations); + var flags = 4 | (leftProp.flags & 16777216); + var result = createSymbol(flags, leftProp.escapedName); + result.type = getUnionType([getTypeOfSymbol(leftProp), getTypeWithFacts(rightType, 524288)]); + result.leftSpread = leftProp; + result.rightSpread = rightProp; + result.declarations = declarations; + result.nameType = leftProp.nameType; + members.set(leftProp.escapedName, result); + } + } + else { + members.set(leftProp.escapedName, getSpreadSymbol(leftProp)); + } + } + var spread = createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, getNonReadonlyIndexSignature(stringIndexInfo), getNonReadonlyIndexSignature(numberIndexInfo)); + spread.flags |= 268435456 | typeFlags; + spread.objectFlags |= 128 | 1024 | objectFlags; + return spread; + } + function isSpreadableProperty(prop) { + return !(prop.flags & (8192 | 32768 | 65536)) || + !prop.declarations.some(function (decl) { return ts.isClassLike(decl.parent); }); + } + function getSpreadSymbol(prop) { + var isReadonly = isReadonlySymbol(prop); + var isSetonlyAccessor = prop.flags & 65536 && !(prop.flags & 32768); + if (!isReadonly && !isSetonlyAccessor) { + return prop; + } + var flags = 4 | (prop.flags & 16777216); + var result = createSymbol(flags, prop.escapedName); + result.type = isSetonlyAccessor ? undefinedType : getTypeOfSymbol(prop); + result.declarations = prop.declarations; + result.nameType = prop.nameType; + result.syntheticOrigin = prop; + return result; + } + function getNonReadonlyIndexSignature(index) { + if (index && index.isReadonly) { + return createIndexInfo(index.type, false, index.declaration); + } + return index; + } + function createLiteralType(flags, value, symbol) { + var type = createType(flags); + type.symbol = symbol; + type.value = value; + return type; + } + function getFreshTypeOfLiteralType(type) { + if (type.flags & 2944) { + if (!type.freshType) { + var freshType = createLiteralType(type.flags, type.value, type.symbol); + freshType.regularType = type; + freshType.freshType = freshType; + type.freshType = freshType; + } + return type.freshType; + } + return type; + } + function getRegularTypeOfLiteralType(type) { + return type.flags & 2944 ? type.regularType : + type.flags & 1048576 ? getUnionType(ts.sameMap(type.types, getRegularTypeOfLiteralType)) : + type; + } + function isFreshLiteralType(type) { + return !!(type.flags & 2944) && type.freshType === type; + } + function getLiteralType(value, enumId, symbol) { + var qualifier = typeof value === "number" ? "#" : typeof value === "string" ? "@" : "n"; + var key = (enumId ? enumId : "") + qualifier + (typeof value === "object" ? ts.pseudoBigIntToString(value) : value); + var type = literalTypes.get(key); + if (!type) { + var flags = (typeof value === "number" ? 256 : + typeof value === "string" ? 128 : 2048) | + (enumId ? 1024 : 0); + literalTypes.set(key, type = createLiteralType(flags, value, symbol)); + type.regularType = type; + } + return type; + } + function getTypeFromLiteralTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + links.resolvedType = getRegularTypeOfLiteralType(checkExpression(node.literal)); + } + return links.resolvedType; + } + function createUniqueESSymbolType(symbol) { + var type = createType(8192); + type.symbol = symbol; + return type; + } + function getESSymbolLikeTypeForNode(node) { + if (ts.isValidESSymbolDeclaration(node)) { + var symbol = getSymbolOfNode(node); + var links = getSymbolLinks(symbol); + return links.uniqueESSymbolType || (links.uniqueESSymbolType = createUniqueESSymbolType(symbol)); + } + return esSymbolType; + } + function getThisType(node) { + var container = ts.getThisContainer(node, false); + var parent = container && container.parent; + if (parent && (ts.isClassLike(parent) || parent.kind === 241)) { + if (!ts.hasModifier(container, 32) && + (container.kind !== 157 || ts.isNodeDescendantOf(node, container.body))) { + return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(parent)).thisType; + } + } + error(node, ts.Diagnostics.A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface); + return errorType; + } + function getTypeFromThisTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + links.resolvedType = getThisType(node); + } + return links.resolvedType; + } + function getTypeFromTypeNode(node) { + switch (node.kind) { + case 120: + case 284: + case 285: + return anyType; + case 143: + return unknownType; + case 138: + return stringType; + case 135: + return numberType; + case 146: + return bigintType; + case 123: + return booleanType; + case 139: + return esSymbolType; + case 106: + return voidType; + case 141: + return undefinedType; + case 96: + return nullType; + case 132: + return neverType; + case 136: + return node.flags & 65536 ? anyType : nonPrimitiveType; + case 178: + case 100: + return getTypeFromThisTypeNode(node); + case 182: + return getTypeFromLiteralTypeNode(node); + case 164: + return getTypeFromTypeReference(node); + case 163: + return booleanType; + case 211: + return getTypeFromTypeReference(node); + case 167: + return getTypeFromTypeQueryNode(node); + case 169: + return getTypeFromArrayTypeNode(node); + case 170: + return getTypeFromTupleTypeNode(node); + case 171: + return getTypeFromOptionalTypeNode(node); + case 173: + return getTypeFromUnionTypeNode(node); + case 174: + return getTypeFromIntersectionTypeNode(node); + case 286: + return getTypeFromJSDocNullableTypeNode(node); + case 288: + return addOptionality(getTypeFromTypeNode(node.type)); + case 177: + case 172: + case 287: + case 283: + return getTypeFromTypeNode(node.type); + case 290: + return getTypeFromJSDocVariadicType(node); + case 165: + case 166: + case 168: + case 292: + case 289: + case 293: + return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node); + case 179: + return getTypeFromTypeOperatorNode(node); + case 180: + return getTypeFromIndexedAccessTypeNode(node); + case 181: + return getTypeFromMappedTypeNode(node); + case 175: + return getTypeFromConditionalTypeNode(node); + case 176: + return getTypeFromInferTypeNode(node); + case 183: + return getTypeFromImportTypeNode(node); + case 72: + case 148: + var symbol = getSymbolAtLocation(node); + return symbol ? getDeclaredTypeOfSymbol(symbol) : errorType; + default: + return errorType; + } + } + function instantiateList(items, mapper, instantiator) { + if (items && items.length) { + for (var i = 0; i < items.length; i++) { + var item = items[i]; + var mapped = instantiator(item, mapper); + if (item !== mapped) { + var result = i === 0 ? [] : items.slice(0, i); + result.push(mapped); + for (i++; i < items.length; i++) { + result.push(instantiator(items[i], mapper)); + } + return result; + } + } + } + return items; + } + function instantiateTypes(types, mapper) { + return instantiateList(types, mapper, instantiateType); + } + function instantiateSignatures(signatures, mapper) { + return instantiateList(signatures, mapper, instantiateSignature); + } + function makeUnaryTypeMapper(source, target) { + return function (t) { return t === source ? target : t; }; + } + function makeBinaryTypeMapper(source1, target1, source2, target2) { + return function (t) { return t === source1 ? target1 : t === source2 ? target2 : t; }; + } + function makeArrayTypeMapper(sources, targets) { + return function (t) { + for (var i = 0; i < sources.length; i++) { + if (t === sources[i]) { + return targets ? targets[i] : anyType; + } + } + return t; + }; + } + function createTypeMapper(sources, targets) { + ts.Debug.assert(targets === undefined || sources.length === targets.length); + return sources.length === 1 ? makeUnaryTypeMapper(sources[0], targets ? targets[0] : anyType) : + sources.length === 2 ? makeBinaryTypeMapper(sources[0], targets ? targets[0] : anyType, sources[1], targets ? targets[1] : anyType) : + makeArrayTypeMapper(sources, targets); + } + function createTypeEraser(sources) { + return createTypeMapper(sources, undefined); + } + function createBackreferenceMapper(typeParameters, index) { + return function (t) { return typeParameters.indexOf(t) >= index ? emptyObjectType : t; }; + } + function isInferenceContext(mapper) { + return !!mapper.typeParameters; + } + function cloneTypeMapper(mapper) { + return mapper && isInferenceContext(mapper) ? + createInferenceContext(mapper.typeParameters, mapper.signature, mapper.flags | 1, mapper.compareTypes, mapper.inferences) : + mapper; + } + function combineTypeMappers(mapper1, mapper2) { + if (!mapper1) + return mapper2; + if (!mapper2) + return mapper1; + return function (t) { return instantiateType(mapper1(t), mapper2); }; + } + function createReplacementMapper(source, target, baseMapper) { + return function (t) { return t === source ? target : baseMapper(t); }; + } + function wildcardMapper(type) { + return type.flags & 262144 ? wildcardType : type; + } + function cloneTypeParameter(typeParameter) { + var result = createType(262144); + result.symbol = typeParameter.symbol; + result.target = typeParameter; + return result; + } + function instantiateTypePredicate(predicate, mapper) { + if (ts.isIdentifierTypePredicate(predicate)) { + return { + kind: 1, + parameterName: predicate.parameterName, + parameterIndex: predicate.parameterIndex, + type: instantiateType(predicate.type, mapper) + }; + } + else { + return { + kind: 0, + type: instantiateType(predicate.type, mapper) + }; + } + } + function instantiateSignature(signature, mapper, eraseTypeParameters) { + var freshTypeParameters; + if (signature.typeParameters && !eraseTypeParameters) { + freshTypeParameters = ts.map(signature.typeParameters, cloneTypeParameter); + mapper = combineTypeMappers(createTypeMapper(signature.typeParameters, freshTypeParameters), mapper); + for (var _i = 0, freshTypeParameters_1 = freshTypeParameters; _i < freshTypeParameters_1.length; _i++) { + var tp = freshTypeParameters_1[_i]; + tp.mapper = mapper; + } + } + var result = createSignature(signature.declaration, freshTypeParameters, signature.thisParameter && instantiateSymbol(signature.thisParameter, mapper), instantiateList(signature.parameters, mapper, instantiateSymbol), undefined, undefined, signature.minArgumentCount, signature.hasRestParameter, signature.hasLiteralTypes); + result.target = signature; + result.mapper = mapper; + return result; + } + function instantiateSymbol(symbol, mapper) { + var links = getSymbolLinks(symbol); + if (links.type && !maybeTypeOfKind(links.type, 524288 | 63176704)) { + return symbol; + } + if (ts.getCheckFlags(symbol) & 1) { + symbol = links.target; + mapper = combineTypeMappers(links.mapper, mapper); + } + var result = createSymbol(symbol.flags, symbol.escapedName, 1 | ts.getCheckFlags(symbol) & (1024 | 4096 | 8192)); + result.declarations = symbol.declarations; + result.parent = symbol.parent; + result.target = symbol; + result.mapper = mapper; + if (symbol.valueDeclaration) { + result.valueDeclaration = symbol.valueDeclaration; + } + if (symbol.nameType) { + result.nameType = symbol.nameType; + } + return result; + } + function getAnonymousTypeInstantiation(type, mapper) { + var target = type.objectFlags & 64 ? type.target : type; + var symbol = target.symbol; + var links = getSymbolLinks(symbol); + var typeParameters = links.outerTypeParameters; + if (!typeParameters) { + var declaration_1 = symbol.declarations[0]; + if (ts.isInJSFile(declaration_1)) { + var paramTag = ts.findAncestor(declaration_1, ts.isJSDocParameterTag); + if (paramTag) { + var paramSymbol = ts.getParameterSymbolFromJSDoc(paramTag); + if (paramSymbol) { + declaration_1 = paramSymbol.valueDeclaration; + } + } + } + var outerTypeParameters = getOuterTypeParameters(declaration_1, true); + if (isJSConstructor(declaration_1)) { + var templateTagParameters = getTypeParametersFromDeclaration(declaration_1); + outerTypeParameters = ts.addRange(outerTypeParameters, templateTagParameters); + } + typeParameters = outerTypeParameters || ts.emptyArray; + typeParameters = symbol.flags & 2048 && !target.aliasTypeArguments ? + ts.filter(typeParameters, function (tp) { return isTypeParameterPossiblyReferenced(tp, declaration_1); }) : + typeParameters; + links.outerTypeParameters = typeParameters; + if (typeParameters.length) { + links.instantiations = ts.createMap(); + links.instantiations.set(getTypeListId(typeParameters), target); + } + } + if (typeParameters.length) { + var combinedMapper = type.objectFlags & 64 ? combineTypeMappers(type.mapper, mapper) : mapper; + var typeArguments = ts.map(typeParameters, combinedMapper); + var id = getTypeListId(typeArguments); + var result = links.instantiations.get(id); + if (!result) { + var newMapper = createTypeMapper(typeParameters, typeArguments); + result = target.objectFlags & 32 ? instantiateMappedType(target, newMapper) : instantiateAnonymousType(target, newMapper); + links.instantiations.set(id, result); + } + return result; + } + return type; + } + function maybeTypeParameterReference(node) { + return !(node.kind === 148 || + node.parent.kind === 164 && node.parent.typeArguments && node === node.parent.typeName); + } + function isTypeParameterPossiblyReferenced(tp, node) { + if (tp.symbol && tp.symbol.declarations && tp.symbol.declarations.length === 1) { + var container_3 = tp.symbol.declarations[0].parent; + if (ts.findAncestor(node, function (n) { return n.kind === 218 ? "quit" : n === container_3; })) { + return !!ts.forEachChild(node, containsReference); + } + } + return true; + function containsReference(node) { + switch (node.kind) { + case 178: + return !!tp.isThisType; + case 72: + return !tp.isThisType && ts.isPartOfTypeNode(node) && maybeTypeParameterReference(node) && + getTypeFromTypeNode(node) === tp; + case 167: + return true; + } + return !!ts.forEachChild(node, containsReference); + } + } + function getHomomorphicTypeVariable(type) { + var constraintType = getConstraintTypeFromMappedType(type); + if (constraintType.flags & 4194304) { + var typeVariable = constraintType.type; + if (typeVariable.flags & 262144) { + return typeVariable; + } + } + return undefined; + } + function instantiateMappedType(type, mapper) { + var typeVariable = getHomomorphicTypeVariable(type); + if (typeVariable) { + var mappedTypeVariable = instantiateType(typeVariable, mapper); + if (typeVariable !== mappedTypeVariable) { + if (type.instantiating) { + return errorType; + } + type.instantiating = true; + var result = mapType(mappedTypeVariable, function (t) { + if (t.flags & (3 | 58982400 | 524288 | 2097152) && t !== wildcardType) { + var replacementMapper = createReplacementMapper(typeVariable, t, mapper); + return isArrayType(t) ? createArrayType(instantiateMappedTypeTemplate(type, numberType, true, replacementMapper)) : + isReadonlyArrayType(t) ? createReadonlyArrayType(instantiateMappedTypeTemplate(type, numberType, true, replacementMapper)) : + isTupleType(t) ? instantiateMappedTupleType(t, type, replacementMapper) : + instantiateAnonymousType(type, replacementMapper); + } + return t; + }); + type.instantiating = false; + return result; + } + } + return instantiateAnonymousType(type, mapper); + } + function instantiateMappedTupleType(tupleType, mappedType, mapper) { + var minLength = tupleType.target.minLength; + var elementTypes = ts.map(tupleType.typeArguments || ts.emptyArray, function (_, i) { + return instantiateMappedTypeTemplate(mappedType, getLiteralType("" + i), i >= minLength, mapper); + }); + var modifiers = getMappedTypeModifiers(mappedType); + var newMinLength = modifiers & 4 ? 0 : + modifiers & 8 ? getTypeReferenceArity(tupleType) - (tupleType.target.hasRestElement ? 1 : 0) : + minLength; + return createTupleType(elementTypes, newMinLength, tupleType.target.hasRestElement, tupleType.target.associatedNames); + } + function instantiateMappedTypeTemplate(type, key, isOptional, mapper) { + var templateMapper = combineTypeMappers(mapper, createTypeMapper([getTypeParameterFromMappedType(type)], [key])); + var propType = instantiateType(getTemplateTypeFromMappedType(type.target || type), templateMapper); + var modifiers = getMappedTypeModifiers(type); + return strictNullChecks && modifiers & 4 && !isTypeAssignableTo(undefinedType, propType) ? getOptionalType(propType) : + strictNullChecks && modifiers & 8 && isOptional ? getTypeWithFacts(propType, 524288) : + propType; + } + function instantiateAnonymousType(type, mapper) { + var result = createObjectType(type.objectFlags | 64, type.symbol); + if (type.objectFlags & 32) { + result.declaration = type.declaration; + var origTypeParameter = getTypeParameterFromMappedType(type); + var freshTypeParameter = cloneTypeParameter(origTypeParameter); + result.typeParameter = freshTypeParameter; + mapper = combineTypeMappers(makeUnaryTypeMapper(origTypeParameter, freshTypeParameter), mapper); + freshTypeParameter.mapper = mapper; + } + result.target = type; + result.mapper = mapper; + result.aliasSymbol = type.aliasSymbol; + result.aliasTypeArguments = instantiateTypes(type.aliasTypeArguments, mapper); + return result; + } + function getConditionalTypeInstantiation(type, mapper) { + var root = type.root; + if (root.outerTypeParameters) { + var typeArguments = ts.map(root.outerTypeParameters, mapper); + var id = getTypeListId(typeArguments); + var result = root.instantiations.get(id); + if (!result) { + var newMapper = createTypeMapper(root.outerTypeParameters, typeArguments); + result = instantiateConditionalType(root, newMapper); + root.instantiations.set(id, result); + } + return result; + } + return type; + } + function instantiateConditionalType(root, mapper) { + if (root.isDistributive) { + var checkType_1 = root.checkType; + var instantiatedType = mapper(checkType_1); + if (checkType_1 !== instantiatedType && instantiatedType.flags & (1048576 | 131072)) { + return mapType(instantiatedType, function (t) { return getConditionalType(root, createReplacementMapper(checkType_1, t, mapper)); }); + } + } + return getConditionalType(root, mapper); + } + function instantiateType(type, mapper) { + if (!type || !mapper || mapper === identityMapper) { + return type; + } + if (instantiationDepth === 50) { + return errorType; + } + instantiationDepth++; + var result = instantiateTypeWorker(type, mapper); + instantiationDepth--; + return result; + } + function instantiateTypeWorker(type, mapper) { + var flags = type.flags; + if (flags & 262144) { + return mapper(type); + } + if (flags & 524288) { + var objectFlags = type.objectFlags; + if (objectFlags & 16) { + return type.symbol && type.symbol.flags & (16 | 8192 | 32 | 2048 | 4096) && type.symbol.declarations ? + getAnonymousTypeInstantiation(type, mapper) : type; + } + if (objectFlags & 32) { + return getAnonymousTypeInstantiation(type, mapper); + } + if (objectFlags & 4) { + var typeArguments = type.typeArguments; + var newTypeArguments = instantiateTypes(typeArguments, mapper); + return newTypeArguments !== typeArguments ? createTypeReference(type.target, newTypeArguments) : type; + } + return type; + } + if (flags & 1048576 && !(flags & 131068)) { + var types = type.types; + var newTypes = instantiateTypes(types, mapper); + return newTypes !== types ? getUnionType(newTypes, 1, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type; + } + if (flags & 2097152) { + var types = type.types; + var newTypes = instantiateTypes(types, mapper); + return newTypes !== types ? getIntersectionType(newTypes, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type; + } + if (flags & 4194304) { + return getIndexType(instantiateType(type.type, mapper)); + } + if (flags & 8388608) { + return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper)); + } + if (flags & 16777216) { + return getConditionalTypeInstantiation(type, combineTypeMappers(type.mapper, mapper)); + } + if (flags & 33554432) { + return instantiateType(type.typeVariable, mapper); + } + return type; + } + function getWildcardInstantiation(type) { + return type.flags & (131068 | 3 | 131072) ? type : + type.wildcardInstantiation || (type.wildcardInstantiation = instantiateType(type, wildcardMapper)); + } + function instantiateIndexInfo(info, mapper) { + return info && createIndexInfo(instantiateType(info.type, mapper), info.isReadonly, info.declaration); + } + function isContextSensitive(node) { + ts.Debug.assert(node.kind !== 156 || ts.isObjectLiteralMethod(node)); + switch (node.kind) { + case 196: + case 197: + case 156: + return isContextSensitiveFunctionLikeDeclaration(node); + case 188: + return ts.some(node.properties, isContextSensitive); + case 187: + return ts.some(node.elements, isContextSensitive); + case 205: + return isContextSensitive(node.whenTrue) || + isContextSensitive(node.whenFalse); + case 204: + return node.operatorToken.kind === 55 && + (isContextSensitive(node.left) || isContextSensitive(node.right)); + case 275: + return isContextSensitive(node.initializer); + case 195: + return isContextSensitive(node.expression); + case 268: + return ts.some(node.properties, isContextSensitive) || ts.isJsxOpeningElement(node.parent) && ts.some(node.parent.parent.children, isContextSensitive); + case 267: { + var initializer = node.initializer; + return !!initializer && isContextSensitive(initializer); + } + case 270: { + var expression = node.expression; + return !!expression && isContextSensitive(expression); + } + } + return false; + } + function isContextSensitiveFunctionLikeDeclaration(node) { + if (node.typeParameters) { + return false; + } + if (ts.some(node.parameters, function (p) { return !ts.getEffectiveTypeAnnotationNode(p); })) { + return true; + } + if (node.kind !== 197) { + var parameter = ts.firstOrUndefined(node.parameters); + if (!(parameter && ts.parameterIsThisKeyword(parameter))) { + return true; + } + } + return hasContextSensitiveReturnExpression(node); + } + function hasContextSensitiveReturnExpression(node) { + var body = node.body; + return body.kind === 218 ? false : isContextSensitive(body); + } + function isContextSensitiveFunctionOrObjectLiteralMethod(func) { + return (ts.isInJSFile(func) && ts.isFunctionDeclaration(func) || isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && + isContextSensitiveFunctionLikeDeclaration(func); + } + function getTypeWithoutSignatures(type) { + if (type.flags & 524288) { + var resolved = resolveStructuredTypeMembers(type); + if (resolved.constructSignatures.length || resolved.callSignatures.length) { + var result = createObjectType(16, type.symbol); + result.members = resolved.members; + result.properties = resolved.properties; + result.callSignatures = ts.emptyArray; + result.constructSignatures = ts.emptyArray; + return result; + } + } + else if (type.flags & 2097152) { + return getIntersectionType(ts.map(type.types, getTypeWithoutSignatures)); + } + return type; + } + function isTypeIdenticalTo(source, target) { + return isTypeRelatedTo(source, target, identityRelation); + } + function compareTypesIdentical(source, target) { + return isTypeRelatedTo(source, target, identityRelation) ? -1 : 0; + } + function compareTypesAssignable(source, target) { + return isTypeRelatedTo(source, target, assignableRelation) ? -1 : 0; + } + function compareTypesSubtypeOf(source, target) { + return isTypeRelatedTo(source, target, subtypeRelation) ? -1 : 0; + } + function isTypeSubtypeOf(source, target) { + return isTypeRelatedTo(source, target, subtypeRelation); + } + function isTypeAssignableTo(source, target) { + return isTypeRelatedTo(source, target, assignableRelation); + } + function isTypeDerivedFrom(source, target) { + return source.flags & 1048576 ? ts.every(source.types, function (t) { return isTypeDerivedFrom(t, target); }) : + target.flags & 1048576 ? ts.some(target.types, function (t) { return isTypeDerivedFrom(source, t); }) : + source.flags & 58982400 ? isTypeDerivedFrom(getBaseConstraintOfType(source) || emptyObjectType, target) : + target === globalObjectType ? !!(source.flags & (524288 | 67108864)) : + target === globalFunctionType ? !!(source.flags & 524288) && isFunctionObjectType(source) : + hasBaseType(source, getTargetType(target)); + } + function isTypeComparableTo(source, target) { + return isTypeRelatedTo(source, target, comparableRelation); + } + function areTypesComparable(type1, type2) { + return isTypeComparableTo(type1, type2) || isTypeComparableTo(type2, type1); + } + function checkTypeAssignableTo(source, target, errorNode, headMessage, containingMessageChain, errorOutputObject) { + return checkTypeRelatedTo(source, target, assignableRelation, errorNode, headMessage, containingMessageChain, errorOutputObject); + } + function checkTypeAssignableToAndOptionallyElaborate(source, target, errorNode, expr, headMessage, containingMessageChain) { + return checkTypeRelatedToAndOptionallyElaborate(source, target, assignableRelation, errorNode, expr, headMessage, containingMessageChain); + } + function checkTypeRelatedToAndOptionallyElaborate(source, target, relation, errorNode, expr, headMessage, containingMessageChain) { + if (isTypeRelatedTo(source, target, relation)) + return true; + if (!errorNode || !elaborateError(expr, source, target, relation, headMessage)) { + return checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain); + } + return false; + } + function isOrHasGenericConditional(type) { + return !!(type.flags & 16777216 || (type.flags & 2097152 && ts.some(type.types, isOrHasGenericConditional))); + } + function elaborateError(node, source, target, relation, headMessage) { + if (!node || isOrHasGenericConditional(target)) + return false; + if (!checkTypeRelatedTo(source, target, relation, undefined) && elaborateDidYouMeanToCallOrConstruct(node, source, target, relation, headMessage)) { + return true; + } + switch (node.kind) { + case 270: + case 195: + return elaborateError(node.expression, source, target, relation, headMessage); + case 204: + switch (node.operatorToken.kind) { + case 59: + case 27: + return elaborateError(node.right, source, target, relation, headMessage); + } + break; + case 188: + return elaborateObjectLiteral(node, source, target, relation); + case 187: + return elaborateArrayLiteral(node, source, target, relation); + case 268: + return elaborateJsxAttributes(node, source, target, relation); + case 197: + return elaborateArrowFunction(node, source, target, relation); + } + return false; + } + function elaborateDidYouMeanToCallOrConstruct(node, source, target, relation, headMessage) { + var callSignatures = getSignaturesOfType(source, 0); + var constructSignatures = getSignaturesOfType(source, 1); + for (var _i = 0, _a = [constructSignatures, callSignatures]; _i < _a.length; _i++) { + var signatures = _a[_i]; + if (ts.some(signatures, function (s) { + var returnType = getReturnTypeOfSignature(s); + return !(returnType.flags & (1 | 131072)) && checkTypeRelatedTo(returnType, target, relation, undefined); + })) { + var resultObj = {}; + checkTypeAssignableTo(source, target, node, headMessage, undefined, resultObj); + var diagnostic = resultObj.error; + addRelatedInfo(diagnostic, ts.createDiagnosticForNode(node, signatures === constructSignatures ? ts.Diagnostics.Did_you_mean_to_use_new_with_this_expression : ts.Diagnostics.Did_you_mean_to_call_this_expression)); + return true; + } + } + return false; + } + function elaborateArrowFunction(node, source, target, relation) { + if (ts.isBlock(node.body)) { + return false; + } + if (ts.some(node.parameters, ts.hasType)) { + return false; + } + var sourceSig = getSingleCallSignature(source); + if (!sourceSig) { + return false; + } + var targetSignatures = getSignaturesOfType(target, 0); + if (!ts.length(targetSignatures)) { + return false; + } + var returnExpression = node.body; + var sourceReturn = getReturnTypeOfSignature(sourceSig); + var targetReturn = getUnionType(ts.map(targetSignatures, getReturnTypeOfSignature)); + if (!checkTypeRelatedTo(sourceReturn, targetReturn, relation, undefined)) { + var elaborated = returnExpression && elaborateError(returnExpression, sourceReturn, targetReturn, relation, undefined); + if (elaborated) { + return elaborated; + } + var resultObj = {}; + checkTypeRelatedTo(sourceReturn, targetReturn, relation, returnExpression, undefined, undefined, resultObj); + if (resultObj.error) { + if (target.symbol && ts.length(target.symbol.declarations)) { + addRelatedInfo(resultObj.error, ts.createDiagnosticForNode(target.symbol.declarations[0], ts.Diagnostics.The_expected_type_comes_from_the_return_type_of_this_signature)); + } + return true; + } + } + return false; + } + function elaborateElementwise(iterator, source, target, relation) { + var reportedError = false; + for (var status = iterator.next(); !status.done; status = iterator.next()) { + var _a = status.value, prop = _a.errorNode, next = _a.innerExpression, nameType = _a.nameType, errorMessage = _a.errorMessage; + var targetPropType = getIndexedAccessType(target, nameType, undefined, errorType); + if (targetPropType === errorType || targetPropType.flags & 8388608) + continue; + var sourcePropType = getIndexedAccessType(source, nameType, undefined, errorType); + if (sourcePropType !== errorType && targetPropType !== errorType && !checkTypeRelatedTo(sourcePropType, targetPropType, relation, undefined)) { + var elaborated = next && elaborateError(next, sourcePropType, targetPropType, relation, undefined); + if (elaborated) { + reportedError = true; + } + else { + var resultObj = {}; + var specificSource = next ? checkExpressionForMutableLocation(next, 0, sourcePropType) : sourcePropType; + var result = checkTypeRelatedTo(specificSource, targetPropType, relation, prop, errorMessage, undefined, resultObj); + if (result && specificSource !== sourcePropType) { + checkTypeRelatedTo(sourcePropType, targetPropType, relation, prop, errorMessage, undefined, resultObj); + } + if (resultObj.error) { + var reportedDiag = resultObj.error; + var propertyName = isTypeUsableAsLateBoundName(nameType) ? getLateBoundNameFromType(nameType) : undefined; + var targetProp = propertyName !== undefined ? getPropertyOfType(target, propertyName) : undefined; + var issuedElaboration = false; + if (!targetProp) { + var indexInfo = isTypeAssignableToKind(nameType, 296) && getIndexInfoOfType(target, 1) || + getIndexInfoOfType(target, 0) || + undefined; + if (indexInfo && indexInfo.declaration && !ts.getSourceFileOfNode(indexInfo.declaration).hasNoDefaultLib) { + issuedElaboration = true; + addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(indexInfo.declaration, ts.Diagnostics.The_expected_type_comes_from_this_index_signature)); + } + } + if (!issuedElaboration && (targetProp && ts.length(targetProp.declarations) || target.symbol && ts.length(target.symbol.declarations))) { + var targetNode = targetProp && ts.length(targetProp.declarations) ? targetProp.declarations[0] : target.symbol.declarations[0]; + if (!ts.getSourceFileOfNode(targetNode).hasNoDefaultLib) { + addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(targetNode, ts.Diagnostics.The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1, propertyName && !(nameType.flags & 8192) ? ts.unescapeLeadingUnderscores(propertyName) : typeToString(nameType), typeToString(target))); + } + } + } + reportedError = true; + } + } + } + return reportedError; + } + function generateJsxAttributes(node) { + var _i, _a, prop; + return __generator(this, function (_b) { + switch (_b.label) { + case 0: + if (!ts.length(node.properties)) + return [2]; + _i = 0, _a = node.properties; + _b.label = 1; + case 1: + if (!(_i < _a.length)) return [3, 4]; + prop = _a[_i]; + if (ts.isJsxSpreadAttribute(prop)) + return [3, 3]; + return [4, { errorNode: prop.name, innerExpression: prop.initializer, nameType: getLiteralType(ts.idText(prop.name)) }]; + case 2: + _b.sent(); + _b.label = 3; + case 3: + _i++; + return [3, 1]; + case 4: return [2]; + } + }); + } + function elaborateJsxAttributes(node, source, target, relation) { + return elaborateElementwise(generateJsxAttributes(node), source, target, relation); + } + function generateLimitedTupleElements(node, target) { + var len, i, elem, nameType; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + len = ts.length(node.elements); + if (!len) + return [2]; + i = 0; + _a.label = 1; + case 1: + if (!(i < len)) return [3, 4]; + if (isTupleLikeType(target) && !getPropertyOfType(target, ("" + i))) + return [3, 3]; + elem = node.elements[i]; + if (ts.isOmittedExpression(elem)) + return [3, 3]; + nameType = getLiteralType(i); + return [4, { errorNode: elem, innerExpression: elem, nameType: nameType }]; + case 2: + _a.sent(); + _a.label = 3; + case 3: + i++; + return [3, 1]; + case 4: return [2]; + } + }); + } + function elaborateArrayLiteral(node, source, target, relation) { + if (isTupleLikeType(source)) { + return elaborateElementwise(generateLimitedTupleElements(node, target), source, target, relation); + } + var tupleizedType = checkArrayLiteral(node, 3, true); + if (isTupleLikeType(tupleizedType)) { + return elaborateElementwise(generateLimitedTupleElements(node, target), tupleizedType, target, relation); + } + return false; + } + function generateObjectLiteralElements(node) { + var _i, _a, prop, type, _b; + return __generator(this, function (_c) { + switch (_c.label) { + case 0: + if (!ts.length(node.properties)) + return [2]; + _i = 0, _a = node.properties; + _c.label = 1; + case 1: + if (!(_i < _a.length)) return [3, 8]; + prop = _a[_i]; + if (ts.isSpreadAssignment(prop)) + return [3, 7]; + type = getLiteralTypeFromProperty(getSymbolOfNode(prop), 8576); + if (!type || (type.flags & 131072)) { + return [3, 7]; + } + _b = prop.kind; + switch (_b) { + case 159: return [3, 2]; + case 158: return [3, 2]; + case 156: return [3, 2]; + case 276: return [3, 2]; + case 275: return [3, 4]; + } + return [3, 6]; + case 2: return [4, { errorNode: prop.name, innerExpression: undefined, nameType: type }]; + case 3: + _c.sent(); + return [3, 7]; + case 4: return [4, { errorNode: prop.name, innerExpression: prop.initializer, nameType: type, errorMessage: isComputedNonLiteralName(prop.name) ? ts.Diagnostics.Type_of_computed_property_s_value_is_0_which_is_not_assignable_to_type_1 : undefined }]; + case 5: + _c.sent(); + return [3, 7]; + case 6: + ts.Debug.assertNever(prop); + _c.label = 7; + case 7: + _i++; + return [3, 1]; + case 8: return [2]; + } + }); + } + function elaborateObjectLiteral(node, source, target, relation) { + return elaborateElementwise(generateObjectLiteralElements(node), source, target, relation); + } + function checkTypeComparableTo(source, target, errorNode, headMessage, containingMessageChain) { + return checkTypeRelatedTo(source, target, comparableRelation, errorNode, headMessage, containingMessageChain); + } + function isSignatureAssignableTo(source, target, ignoreReturnTypes) { + return compareSignaturesRelated(source, target, 0, ignoreReturnTypes, false, undefined, compareTypesAssignable) !== 0; + } + function compareSignaturesRelated(source, target, callbackCheck, ignoreReturnTypes, reportErrors, errorReporter, compareTypes) { + if (source === target) { + return -1; + } + var targetCount = getParameterCount(target); + if (!hasEffectiveRestParameter(target) && getMinArgumentCount(source) > targetCount) { + return 0; + } + if (source.typeParameters && source.typeParameters !== target.typeParameters) { + target = getCanonicalSignature(target); + source = instantiateSignatureInContextOf(source, target, undefined, compareTypes); + } + var sourceCount = getParameterCount(source); + var sourceRestType = getNonArrayRestType(source); + var targetRestType = getNonArrayRestType(target); + if (sourceRestType && targetRestType && sourceCount !== targetCount) { + return 0; + } + var kind = target.declaration ? target.declaration.kind : 0; + var strictVariance = !callbackCheck && strictFunctionTypes && kind !== 156 && + kind !== 155 && kind !== 157; + var result = -1; + var sourceThisType = getThisTypeOfSignature(source); + if (sourceThisType && sourceThisType !== voidType) { + var targetThisType = getThisTypeOfSignature(target); + if (targetThisType) { + var related = !strictVariance && compareTypes(sourceThisType, targetThisType, false) + || compareTypes(targetThisType, sourceThisType, reportErrors); + if (!related) { + if (reportErrors) { + errorReporter(ts.Diagnostics.The_this_types_of_each_signature_are_incompatible); + } + return 0; + } + result &= related; + } + } + var paramCount = sourceRestType || targetRestType ? Math.min(sourceCount, targetCount) : Math.max(sourceCount, targetCount); + var restIndex = sourceRestType || targetRestType ? paramCount - 1 : -1; + for (var i = 0; i < paramCount; i++) { + var sourceType = i === restIndex ? getRestTypeAtPosition(source, i) : getTypeAtPosition(source, i); + var targetType = i === restIndex ? getRestTypeAtPosition(target, i) : getTypeAtPosition(target, i); + var sourceSig = callbackCheck ? undefined : getSingleCallSignature(getNonNullableType(sourceType)); + var targetSig = callbackCheck ? undefined : getSingleCallSignature(getNonNullableType(targetType)); + var callbacks = sourceSig && targetSig && !signatureHasTypePredicate(sourceSig) && !signatureHasTypePredicate(targetSig) && + (getFalsyFlags(sourceType) & 98304) === (getFalsyFlags(targetType) & 98304); + var related = callbacks ? + compareSignaturesRelated(targetSig, sourceSig, strictVariance ? 2 : 1, false, reportErrors, errorReporter, compareTypes) : + !callbackCheck && !strictVariance && compareTypes(sourceType, targetType, false) || compareTypes(targetType, sourceType, reportErrors); + if (!related) { + if (reportErrors) { + errorReporter(ts.Diagnostics.Types_of_parameters_0_and_1_are_incompatible, ts.unescapeLeadingUnderscores(getParameterNameAtPosition(source, i)), ts.unescapeLeadingUnderscores(getParameterNameAtPosition(target, i))); + } + return 0; + } + result &= related; + } + if (!ignoreReturnTypes) { + var targetReturnType = (target.declaration && isJSConstructor(target.declaration)) ? + getJSClassType(target.declaration.symbol) : getReturnTypeOfSignature(target); + if (targetReturnType === voidType) { + return result; + } + var sourceReturnType = (source.declaration && isJSConstructor(source.declaration)) ? + getJSClassType(source.declaration.symbol) : getReturnTypeOfSignature(source); + var targetTypePredicate = getTypePredicateOfSignature(target); + if (targetTypePredicate) { + var sourceTypePredicate = getTypePredicateOfSignature(source); + if (sourceTypePredicate) { + result &= compareTypePredicateRelatedTo(sourceTypePredicate, targetTypePredicate, source.declaration, target.declaration, reportErrors, errorReporter, compareTypes); + } + else if (ts.isIdentifierTypePredicate(targetTypePredicate)) { + if (reportErrors) { + errorReporter(ts.Diagnostics.Signature_0_must_be_a_type_predicate, signatureToString(source)); + } + return 0; + } + } + else { + result &= callbackCheck === 1 && compareTypes(targetReturnType, sourceReturnType, false) || + compareTypes(sourceReturnType, targetReturnType, reportErrors); + } + } + return result; + } + function compareTypePredicateRelatedTo(source, target, sourceDeclaration, targetDeclaration, reportErrors, errorReporter, compareTypes) { + if (source.kind !== target.kind) { + if (reportErrors) { + errorReporter(ts.Diagnostics.A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard); + errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target)); + } + return 0; + } + if (source.kind === 1) { + var targetPredicate = target; + var sourceIndex = source.parameterIndex - (ts.getThisParameter(sourceDeclaration) ? 1 : 0); + var targetIndex = targetPredicate.parameterIndex - (ts.getThisParameter(targetDeclaration) ? 1 : 0); + if (sourceIndex !== targetIndex) { + if (reportErrors) { + errorReporter(ts.Diagnostics.Parameter_0_is_not_in_the_same_position_as_parameter_1, source.parameterName, targetPredicate.parameterName); + errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target)); + } + return 0; + } + } + var related = compareTypes(source.type, target.type, reportErrors); + if (related === 0 && reportErrors) { + errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target)); + } + return related; + } + function isImplementationCompatibleWithOverload(implementation, overload) { + var erasedSource = getErasedSignature(implementation); + var erasedTarget = getErasedSignature(overload); + var sourceReturnType = getReturnTypeOfSignature(erasedSource); + var targetReturnType = getReturnTypeOfSignature(erasedTarget); + if (targetReturnType === voidType + || isTypeRelatedTo(targetReturnType, sourceReturnType, assignableRelation) + || isTypeRelatedTo(sourceReturnType, targetReturnType, assignableRelation)) { + return isSignatureAssignableTo(erasedSource, erasedTarget, true); + } + return false; + } + function isEmptyResolvedType(t) { + return t.properties.length === 0 && + t.callSignatures.length === 0 && + t.constructSignatures.length === 0 && + !t.stringIndexInfo && + !t.numberIndexInfo; + } + function isEmptyObjectType(type) { + return type.flags & 524288 ? isEmptyResolvedType(resolveStructuredTypeMembers(type)) : + type.flags & 67108864 ? true : + type.flags & 1048576 ? ts.some(type.types, isEmptyObjectType) : + type.flags & 2097152 ? ts.every(type.types, isEmptyObjectType) : + false; + } + function isEmptyAnonymousObjectType(type) { + return !!(ts.getObjectFlags(type) & 16) && isEmptyObjectType(type); + } + function isEnumTypeRelatedTo(sourceSymbol, targetSymbol, errorReporter) { + if (sourceSymbol === targetSymbol) { + return true; + } + var id = getSymbolId(sourceSymbol) + "," + getSymbolId(targetSymbol); + var relation = enumRelation.get(id); + if (relation !== undefined && !(relation === 2 && errorReporter)) { + return relation === 1; + } + if (sourceSymbol.escapedName !== targetSymbol.escapedName || !(sourceSymbol.flags & 256) || !(targetSymbol.flags & 256)) { + enumRelation.set(id, 3); + return false; + } + var targetEnumType = getTypeOfSymbol(targetSymbol); + for (var _i = 0, _a = getPropertiesOfType(getTypeOfSymbol(sourceSymbol)); _i < _a.length; _i++) { + var property = _a[_i]; + if (property.flags & 8) { + var targetProperty = getPropertyOfType(targetEnumType, property.escapedName); + if (!targetProperty || !(targetProperty.flags & 8)) { + if (errorReporter) { + errorReporter(ts.Diagnostics.Property_0_is_missing_in_type_1, ts.symbolName(property), typeToString(getDeclaredTypeOfSymbol(targetSymbol), undefined, 64)); + enumRelation.set(id, 3); + } + else { + enumRelation.set(id, 2); + } + return false; + } + } + } + enumRelation.set(id, 1); + return true; + } + function isSimpleTypeRelatedTo(source, target, relation, errorReporter) { + var s = source.flags; + var t = target.flags; + if (t & 3 || s & 131072 || source === wildcardType) + return true; + if (t & 131072) + return false; + if (s & 132 && t & 4) + return true; + if (s & 128 && s & 1024 && + t & 128 && !(t & 1024) && + source.value === target.value) + return true; + if (s & 296 && t & 8) + return true; + if (s & 256 && s & 1024 && + t & 256 && !(t & 1024) && + source.value === target.value) + return true; + if (s & 2112 && t & 64) + return true; + if (s & 528 && t & 16) + return true; + if (s & 12288 && t & 4096) + return true; + if (s & 32 && t & 32 && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) + return true; + if (s & 1024 && t & 1024) { + if (s & 1048576 && t & 1048576 && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) + return true; + if (s & 2944 && t & 2944 && + source.value === target.value && + isEnumTypeRelatedTo(getParentOfSymbol(source.symbol), getParentOfSymbol(target.symbol), errorReporter)) + return true; + } + if (s & 32768 && (!strictNullChecks || t & (32768 | 16384))) + return true; + if (s & 65536 && (!strictNullChecks || t & 65536)) + return true; + if (s & 524288 && t & 67108864) + return true; + if (s & 8192 || t & 8192) + return false; + if (relation === assignableRelation || relation === definitelyAssignableRelation || relation === comparableRelation) { + if (s & 1) + return true; + if (s & (8 | 256) && !(s & 1024) && (t & 32 || t & 256 && t & 1024)) + return true; + } + return false; + } + function isTypeRelatedTo(source, target, relation) { + if (isFreshLiteralType(source)) { + source = source.regularType; + } + if (isFreshLiteralType(target)) { + target = target.regularType; + } + if (source === target || + relation === comparableRelation && !(target.flags & 131072) && isSimpleTypeRelatedTo(target, source, relation) || + relation !== identityRelation && isSimpleTypeRelatedTo(source, target, relation)) { + return true; + } + if (source.flags & 524288 && target.flags & 524288) { + var related = relation.get(getRelationKey(source, target, relation)); + if (related !== undefined) { + return related === 1; + } + } + if (source.flags & 66846720 || target.flags & 66846720) { + return checkTypeRelatedTo(source, target, relation, undefined); + } + return false; + } + function isIgnoredJsxProperty(source, sourceProp, targetMemberType) { + return ts.getObjectFlags(source) & 4096 && !(isUnhyphenatedJsxName(sourceProp.escapedName) || targetMemberType); + } + function checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain, errorOutputContainer) { + var errorInfo; + var relatedInfo; + var maybeKeys; + var sourceStack; + var targetStack; + var maybeCount = 0; + var depth = 0; + var expandingFlags = 0; + var overflow = false; + var suppressNextError = false; + ts.Debug.assert(relation !== identityRelation || !errorNode, "no error reporting in identity checking"); + var result = isRelatedTo(source, target, !!errorNode, headMessage); + if (overflow) { + error(errorNode, ts.Diagnostics.Excessive_stack_depth_comparing_types_0_and_1, typeToString(source), typeToString(target)); + } + else if (errorInfo) { + if (containingMessageChain) { + var chain_1 = containingMessageChain(); + if (chain_1) { + errorInfo = ts.concatenateDiagnosticMessageChains(chain_1, errorInfo); + } + } + var relatedInformation = void 0; + if (headMessage && errorNode && !result && source.symbol) { + var links = getSymbolLinks(source.symbol); + if (links.originatingImport && !ts.isImportCall(links.originatingImport)) { + var helpfulRetry = checkTypeRelatedTo(getTypeOfSymbol(links.target), target, relation, undefined); + if (helpfulRetry) { + var diag_1 = ts.createDiagnosticForNode(links.originatingImport, ts.Diagnostics.Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_Consider_using_a_default_import_or_import_require_here_instead); + relatedInformation = ts.append(relatedInformation, diag_1); + } + } + } + var diag = ts.createDiagnosticForNodeFromMessageChain(errorNode, errorInfo, relatedInformation); + if (relatedInfo) { + addRelatedInfo.apply(void 0, [diag].concat(relatedInfo)); + } + if (errorOutputContainer) { + errorOutputContainer.error = diag; + } + diagnostics.add(diag); + } + return result !== 0; + function reportError(message, arg0, arg1, arg2, arg3) { + ts.Debug.assert(!!errorNode); + errorInfo = ts.chainDiagnosticMessages(errorInfo, message, arg0, arg1, arg2, arg3); + } + function associateRelatedInfo(info) { + ts.Debug.assert(!!errorInfo); + if (!relatedInfo) { + relatedInfo = [info]; + } + else { + relatedInfo.push(info); + } + } + function reportRelationError(message, source, target) { + var sourceType = typeToString(source); + var targetType = typeToString(target); + if (sourceType === targetType) { + sourceType = typeToString(source, undefined, 64); + targetType = typeToString(target, undefined, 64); + } + if (!message) { + if (relation === comparableRelation) { + message = ts.Diagnostics.Type_0_is_not_comparable_to_type_1; + } + else if (sourceType === targetType) { + message = ts.Diagnostics.Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated; + } + else { + message = ts.Diagnostics.Type_0_is_not_assignable_to_type_1; + } + } + reportError(message, sourceType, targetType); + } + function tryElaborateErrorsForPrimitivesAndObjects(source, target) { + var sourceType = typeToString(source); + var targetType = typeToString(target); + if ((globalStringType === source && stringType === target) || + (globalNumberType === source && numberType === target) || + (globalBooleanType === source && booleanType === target) || + (getGlobalESSymbolType(false) === source && esSymbolType === target)) { + reportError(ts.Diagnostics._0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible, targetType, sourceType); + } + } + function isUnionOrIntersectionTypeWithoutNullableConstituents(type) { + if (!(type.flags & 3145728)) { + return false; + } + var seenNonNullable = false; + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (t.flags & 98304) { + continue; + } + if (seenNonNullable) { + return true; + } + seenNonNullable = true; + } + return false; + } + function isRelatedTo(source, target, reportErrors, headMessage, isApparentIntersectionConstituent) { + if (reportErrors === void 0) { reportErrors = false; } + if (isFreshLiteralType(source)) { + source = source.regularType; + } + if (isFreshLiteralType(target)) { + target = target.regularType; + } + if (source.flags & 33554432) { + source = relation === definitelyAssignableRelation ? source.typeVariable : source.substitute; + } + if (target.flags & 33554432) { + target = target.typeVariable; + } + if (source.flags & 8388608) { + source = getSimplifiedType(source); + } + if (target.flags & 8388608) { + target = getSimplifiedType(target); + } + if (target.flags & 1048576 && source.flags & 524288 && + target.types.length <= 3 && maybeTypeOfKind(target, 98304)) { + var nullStrippedTarget = extractTypesOfKind(target, ~98304); + if (!(nullStrippedTarget.flags & (1048576 | 131072))) { + target = nullStrippedTarget; + } + } + if (source === target) + return -1; + if (relation === identityRelation) { + return isIdenticalTo(source, target); + } + if (relation === comparableRelation && !(target.flags & 131072) && isSimpleTypeRelatedTo(target, source, relation) || + isSimpleTypeRelatedTo(source, target, relation, reportErrors ? reportError : undefined)) + return -1; + var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096); + if (isObjectLiteralType(source) && ts.getObjectFlags(source) & 32768) { + var discriminantType = target.flags & 1048576 ? findMatchingDiscriminantType(source, target) : undefined; + if (hasExcessProperties(source, target, discriminantType, reportErrors)) { + if (reportErrors) { + reportRelationError(headMessage, source, target); + } + return 0; + } + if (isUnionOrIntersectionTypeWithoutNullableConstituents(target) && !discriminantType) { + source = getRegularTypeOfObjectLiteral(source); + } + } + if (relation !== comparableRelation && !isApparentIntersectionConstituent && + source.flags & (131068 | 524288 | 2097152) && source !== globalObjectType && + target.flags & (524288 | 2097152) && isWeakType(target) && + (getPropertiesOfType(source).length > 0 || typeHasCallOrConstructSignatures(source)) && + !hasCommonProperties(source, target, isComparingJsxAttributes)) { + if (reportErrors) { + var calls = getSignaturesOfType(source, 0); + var constructs = getSignaturesOfType(source, 1); + if (calls.length > 0 && isRelatedTo(getReturnTypeOfSignature(calls[0]), target, false) || + constructs.length > 0 && isRelatedTo(getReturnTypeOfSignature(constructs[0]), target, false)) { + reportError(ts.Diagnostics.Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it, typeToString(source), typeToString(target)); + } + else { + reportError(ts.Diagnostics.Type_0_has_no_properties_in_common_with_type_1, typeToString(source), typeToString(target)); + } + } + return 0; + } + var result = 0; + var saveErrorInfo = errorInfo; + var isIntersectionConstituent = !!isApparentIntersectionConstituent; + if (source.flags & 1048576) { + result = relation === comparableRelation ? + someTypeRelatedToType(source, target, reportErrors && !(source.flags & 131068)) : + eachTypeRelatedToType(source, target, reportErrors && !(source.flags & 131068)); + } + else { + if (target.flags & 1048576) { + result = typeRelatedToSomeType(source, target, reportErrors && !(source.flags & 131068) && !(target.flags & 131068)); + } + else if (target.flags & 2097152) { + isIntersectionConstituent = true; + result = typeRelatedToEachType(source, target, reportErrors); + } + else if (source.flags & 2097152) { + result = someTypeRelatedToType(source, target, false); + } + if (!result && (source.flags & 66846720 || target.flags & 66846720)) { + if (result = recursiveTypeRelatedTo(source, target, reportErrors, isIntersectionConstituent)) { + errorInfo = saveErrorInfo; + } + } + } + if (!result && source.flags & 2097152) { + var constraint = getUnionConstraintOfIntersection(source, !!(target.flags & 1048576)); + if (constraint) { + if (result = isRelatedTo(constraint, target, reportErrors, undefined, isIntersectionConstituent)) { + errorInfo = saveErrorInfo; + } + } + } + if (!result && reportErrors) { + var maybeSuppress = suppressNextError; + suppressNextError = false; + if (source.flags & 524288 && target.flags & 131068) { + tryElaborateErrorsForPrimitivesAndObjects(source, target); + } + else if (source.symbol && source.flags & 524288 && globalObjectType === source) { + reportError(ts.Diagnostics.The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead); + } + else if (isComparingJsxAttributes && target.flags & 2097152) { + var targetTypes = target.types; + var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes, errorNode); + var intrinsicClassAttributes = getJsxType(JsxNames.IntrinsicClassAttributes, errorNode); + if (intrinsicAttributes !== errorType && intrinsicClassAttributes !== errorType && + (ts.contains(targetTypes, intrinsicAttributes) || ts.contains(targetTypes, intrinsicClassAttributes))) { + return result; + } + } + if (!headMessage && maybeSuppress) { + return result; + } + reportRelationError(headMessage, source, target); + } + return result; + } + function isIdenticalTo(source, target) { + var result; + var flags = source.flags & target.flags; + if (flags & 524288 || flags & 8388608 || flags & 16777216 || flags & 4194304 || flags & 33554432) { + return recursiveTypeRelatedTo(source, target, false, false); + } + if (flags & (1048576 | 2097152)) { + if (result = eachTypeRelatedToSomeType(source, target)) { + if (result &= eachTypeRelatedToSomeType(target, source)) { + return result; + } + } + } + return 0; + } + function hasExcessProperties(source, target, discriminant, reportErrors) { + if (!noImplicitAny && ts.getObjectFlags(target) & 16384) { + return false; + } + if (maybeTypeOfKind(target, 524288) && !(ts.getObjectFlags(target) & 512)) { + var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096); + if ((relation === assignableRelation || relation === definitelyAssignableRelation || relation === comparableRelation) && + (isTypeSubsetOf(globalObjectType, target) || (!isComparingJsxAttributes && isEmptyObjectType(target)))) { + return false; + } + if (discriminant) { + return hasExcessProperties(source, discriminant, undefined, reportErrors); + } + var _loop_6 = function (prop) { + if (shouldCheckAsExcessProperty(prop, source.symbol) && !isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { + if (reportErrors) { + if (!errorNode) + return { value: ts.Debug.fail() }; + if (ts.isJsxAttributes(errorNode) || ts.isJsxOpeningLikeElement(errorNode) || ts.isJsxOpeningLikeElement(errorNode.parent)) { + reportError(ts.Diagnostics.Property_0_does_not_exist_on_type_1, symbolToString(prop), typeToString(target)); + } + else { + var objectLiteralDeclaration_1 = source.symbol && ts.firstOrUndefined(source.symbol.declarations); + var suggestion = void 0; + if (prop.valueDeclaration && ts.findAncestor(prop.valueDeclaration, function (d) { return d === objectLiteralDeclaration_1; })) { + var propDeclaration = prop.valueDeclaration; + ts.Debug.assertNode(propDeclaration, ts.isObjectLiteralElementLike); + errorNode = propDeclaration; + var name = propDeclaration.name; + if (ts.isIdentifier(name)) { + suggestion = getSuggestionForNonexistentProperty(name, target); + } + } + if (suggestion !== undefined) { + reportError(ts.Diagnostics.Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_write_2, symbolToString(prop), typeToString(target), suggestion); + } + else { + reportError(ts.Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(prop), typeToString(target)); + } + } + } + return { value: true }; + } + }; + for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) { + var prop = _a[_i]; + var state_2 = _loop_6(prop); + if (typeof state_2 === "object") + return state_2.value; + } + } + return false; + } + function shouldCheckAsExcessProperty(prop, container) { + return prop.valueDeclaration && container.valueDeclaration && prop.valueDeclaration.parent === container.valueDeclaration; + } + function eachTypeRelatedToSomeType(source, target) { + var result = -1; + var sourceTypes = source.types; + for (var _i = 0, sourceTypes_1 = sourceTypes; _i < sourceTypes_1.length; _i++) { + var sourceType = sourceTypes_1[_i]; + var related = typeRelatedToSomeType(sourceType, target, false); + if (!related) { + return 0; + } + result &= related; + } + return result; + } + function typeRelatedToSomeType(source, target, reportErrors) { + var targetTypes = target.types; + if (target.flags & 1048576 && containsType(targetTypes, source)) { + return -1; + } + for (var _i = 0, targetTypes_1 = targetTypes; _i < targetTypes_1.length; _i++) { + var type = targetTypes_1[_i]; + var related = isRelatedTo(source, type, false); + if (related) { + return related; + } + } + if (reportErrors) { + var bestMatchingType = findMatchingDiscriminantType(source, target) || + findMatchingTypeReferenceOrTypeAliasReference(source, target) || + findBestTypeForObjectLiteral(source, target) || + findBestTypeForInvokable(source, target) || + findMostOverlappyType(source, target); + isRelatedTo(source, bestMatchingType || targetTypes[targetTypes.length - 1], true); + } + return 0; + } + function findMatchingTypeReferenceOrTypeAliasReference(source, unionTarget) { + var sourceObjectFlags = ts.getObjectFlags(source); + if (sourceObjectFlags & (4 | 16) && unionTarget.flags & 1048576) { + return ts.find(unionTarget.types, function (target) { + if (target.flags & 524288) { + var overlapObjFlags = sourceObjectFlags & ts.getObjectFlags(target); + if (overlapObjFlags & 4) { + return source.target === target.target; + } + if (overlapObjFlags & 16) { + return !!source.aliasSymbol && source.aliasSymbol === target.aliasSymbol; + } + } + return false; + }); + } + } + function findBestTypeForObjectLiteral(source, unionTarget) { + if (ts.getObjectFlags(source) & 128 && forEachType(unionTarget, isArrayLikeType)) { + return ts.find(unionTarget.types, function (t) { return !isArrayLikeType(t); }); + } + } + function findBestTypeForInvokable(source, unionTarget) { + var signatureKind = 0; + var hasSignatures = getSignaturesOfType(source, signatureKind).length > 0 || + (signatureKind = 1, getSignaturesOfType(source, signatureKind).length > 0); + if (hasSignatures) { + return ts.find(unionTarget.types, function (t) { return getSignaturesOfType(t, signatureKind).length > 0; }); + } + } + function findMostOverlappyType(source, unionTarget) { + var bestMatch; + var matchingCount = 0; + for (var _i = 0, _a = unionTarget.types; _i < _a.length; _i++) { + var target_1 = _a[_i]; + var overlap = getIntersectionType([getIndexType(source), getIndexType(target_1)]); + if (overlap.flags & 4194304) { + bestMatch = target_1; + matchingCount = Infinity; + } + else if (overlap.flags & 1048576) { + var len = ts.length(overlap.types); + if (len >= matchingCount) { + bestMatch = target_1; + matchingCount = len; + } + } + else if (!(overlap.flags & 131072) && 1 >= matchingCount) { + bestMatch = target_1; + matchingCount = 1; + } + } + return bestMatch; + } + function findMatchingDiscriminantType(source, target) { + if (target.flags & 1048576) { + var sourceProperties = getPropertiesOfObjectType(source); + if (sourceProperties) { + var sourcePropertiesFiltered = findDiscriminantProperties(sourceProperties, target); + if (sourcePropertiesFiltered) { + return discriminateTypeByDiscriminableItems(target, ts.map(sourcePropertiesFiltered, function (p) { return [function () { return getTypeOfSymbol(p); }, p.escapedName]; }), isRelatedTo); + } + } + } + return undefined; + } + function typeRelatedToEachType(source, target, reportErrors) { + var result = -1; + var targetTypes = target.types; + for (var _i = 0, targetTypes_2 = targetTypes; _i < targetTypes_2.length; _i++) { + var targetType = targetTypes_2[_i]; + var related = isRelatedTo(source, targetType, reportErrors, undefined, true); + if (!related) { + return 0; + } + result &= related; + } + return result; + } + function someTypeRelatedToType(source, target, reportErrors) { + var sourceTypes = source.types; + if (source.flags & 1048576 && containsType(sourceTypes, target)) { + return -1; + } + var len = sourceTypes.length; + for (var i = 0; i < len; i++) { + var related = isRelatedTo(sourceTypes[i], target, reportErrors && i === len - 1); + if (related) { + return related; + } + } + return 0; + } + function eachTypeRelatedToType(source, target, reportErrors) { + var result = -1; + var sourceTypes = source.types; + for (var _i = 0, sourceTypes_2 = sourceTypes; _i < sourceTypes_2.length; _i++) { + var sourceType = sourceTypes_2[_i]; + var related = isRelatedTo(sourceType, target, reportErrors); + if (!related) { + return 0; + } + result &= related; + } + return result; + } + function typeArgumentsRelatedTo(sources, targets, variances, reportErrors) { + if (sources === void 0) { sources = ts.emptyArray; } + if (targets === void 0) { targets = ts.emptyArray; } + if (variances === void 0) { variances = ts.emptyArray; } + if (sources.length !== targets.length && relation === identityRelation) { + return 0; + } + var length = sources.length <= targets.length ? sources.length : targets.length; + var result = -1; + for (var i = 0; i < length; i++) { + var variance = i < variances.length ? variances[i] : 1; + if (variance !== 4) { + var s = sources[i]; + var t = targets[i]; + var related = -1; + if (variance === 1) { + related = isRelatedTo(s, t, reportErrors); + } + else if (variance === 2) { + related = isRelatedTo(t, s, reportErrors); + } + else if (variance === 3) { + related = isRelatedTo(t, s, false); + if (!related) { + related = isRelatedTo(s, t, reportErrors); + } + } + else { + related = isRelatedTo(s, t, reportErrors); + if (related) { + related &= isRelatedTo(t, s, reportErrors); + } + } + if (!related) { + return 0; + } + result &= related; + } + } + return result; + } + function recursiveTypeRelatedTo(source, target, reportErrors, isIntersectionConstituent) { + if (overflow) { + return 0; + } + var id = getRelationKey(source, target, relation); + var related = relation.get(id); + if (related !== undefined) { + if (reportErrors && related === 2) { + } + else { + return related === 1 ? -1 : 0; + } + } + if (!maybeKeys) { + maybeKeys = []; + sourceStack = []; + targetStack = []; + } + else { + for (var i = 0; i < maybeCount; i++) { + if (id === maybeKeys[i]) { + return 1; + } + } + if (depth === 100) { + overflow = true; + return 0; + } + } + var maybeStart = maybeCount; + maybeKeys[maybeCount] = id; + maybeCount++; + sourceStack[depth] = source; + targetStack[depth] = target; + depth++; + var saveExpandingFlags = expandingFlags; + if (!(expandingFlags & 1) && isDeeplyNestedType(source, sourceStack, depth)) + expandingFlags |= 1; + if (!(expandingFlags & 2) && isDeeplyNestedType(target, targetStack, depth)) + expandingFlags |= 2; + var result = expandingFlags !== 3 ? structuredTypeRelatedTo(source, target, reportErrors, isIntersectionConstituent) : 1; + expandingFlags = saveExpandingFlags; + depth--; + if (result) { + if (result === -1 || depth === 0) { + for (var i = maybeStart; i < maybeCount; i++) { + relation.set(maybeKeys[i], 1); + } + maybeCount = maybeStart; + } + } + else { + relation.set(id, reportErrors ? 3 : 2); + maybeCount = maybeStart; + } + return result; + } + function getConstraintForRelation(type) { + return relation === definitelyAssignableRelation ? undefined : getConstraintOfType(type); + } + function structuredTypeRelatedTo(source, target, reportErrors, isIntersectionConstituent) { + var flags = source.flags & target.flags; + if (relation === identityRelation && !(flags & 524288)) { + if (flags & 4194304) { + return isRelatedTo(source.type, target.type, false); + } + var result_2 = 0; + if (flags & 8388608) { + if (result_2 = isRelatedTo(source.objectType, target.objectType, false)) { + if (result_2 &= isRelatedTo(source.indexType, target.indexType, false)) { + return result_2; + } + } + } + if (flags & 16777216) { + if (source.root.isDistributive === target.root.isDistributive) { + if (result_2 = isRelatedTo(source.checkType, target.checkType, false)) { + if (result_2 &= isRelatedTo(source.extendsType, target.extendsType, false)) { + if (result_2 &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), false)) { + if (result_2 &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), false)) { + return result_2; + } + } + } + } + } + } + if (flags & 33554432) { + return isRelatedTo(source.substitute, target.substitute, false); + } + return 0; + } + var result; + var originalErrorInfo; + var saveErrorInfo = errorInfo; + if (source.flags & (524288 | 16777216) && source.aliasSymbol && + source.aliasTypeArguments && source.aliasSymbol === target.aliasSymbol && + !(source.aliasTypeArgumentsContainsMarker || target.aliasTypeArgumentsContainsMarker)) { + var variances = getAliasVariances(source.aliasSymbol); + if (result = typeArgumentsRelatedTo(source.aliasTypeArguments, target.aliasTypeArguments, variances, reportErrors)) { + return result; + } + originalErrorInfo = errorInfo; + errorInfo = saveErrorInfo; + } + if (target.flags & 262144) { + if (ts.getObjectFlags(source) & 32 && isRelatedTo(getIndexType(target), getConstraintTypeFromMappedType(source))) { + if (!(getMappedTypeModifiers(source) & 4)) { + var templateType = getTemplateTypeFromMappedType(source); + var indexedAccessType = getIndexedAccessType(target, getTypeParameterFromMappedType(source)); + if (result = isRelatedTo(templateType, indexedAccessType, reportErrors)) { + return result; + } + } + } + } + else if (target.flags & 4194304) { + if (source.flags & 4194304) { + if (result = isRelatedTo(target.type, source.type, false)) { + return result; + } + } + if (relation !== definitelyAssignableRelation) { + var simplified = getSimplifiedType(target.type); + var constraint = simplified !== target.type ? simplified : getConstraintOfType(target.type); + if (constraint) { + if (isRelatedTo(source, getIndexType(constraint, target.stringsOnly), reportErrors) === -1) { + return -1; + } + } + } + } + else if (target.flags & 8388608) { + if (relation !== identityRelation && !(isGenericObjectType(target.objectType) && isGenericIndexType(target.indexType))) { + var constraint = getBaseConstraintOfType(target); + if (constraint && constraint !== target) { + if (result = isRelatedTo(source, constraint, reportErrors)) { + return result; + } + } + } + } + else if (isGenericMappedType(target)) { + var template = getTemplateTypeFromMappedType(target); + var modifiers = getMappedTypeModifiers(target); + if (!(modifiers & 8)) { + if (template.flags & 8388608 && template.objectType === source && + template.indexType === getTypeParameterFromMappedType(target)) { + return -1; + } + if (!isGenericMappedType(source) && isRelatedTo(getConstraintTypeFromMappedType(target), getIndexType(source))) { + var indexedAccessType = getIndexedAccessType(source, getTypeParameterFromMappedType(target)); + var templateType = getTemplateTypeFromMappedType(target); + if (result = isRelatedTo(indexedAccessType, templateType, reportErrors)) { + return result; + } + } + originalErrorInfo = errorInfo; + errorInfo = saveErrorInfo; + } + } + if (source.flags & 8650752) { + if (source.flags & 8388608 && target.flags & 8388608) { + if (result = isRelatedTo(source.objectType, target.objectType, reportErrors)) { + result &= isRelatedTo(source.indexType, target.indexType, reportErrors); + } + if (result) { + errorInfo = saveErrorInfo; + return result; + } + } + var constraint = getConstraintForRelation(source); + if (!constraint || (source.flags & 262144 && constraint.flags & 3)) { + if (result = isRelatedTo(emptyObjectType, extractTypesOfKind(target, ~67108864))) { + errorInfo = saveErrorInfo; + return result; + } + } + else if (result = isRelatedTo(constraint, target, false, undefined, isIntersectionConstituent)) { + errorInfo = saveErrorInfo; + return result; + } + else if (result = isRelatedTo(getTypeWithThisArgument(constraint, source), target, reportErrors, undefined, isIntersectionConstituent)) { + errorInfo = saveErrorInfo; + return result; + } + } + else if (source.flags & 4194304) { + if (result = isRelatedTo(keyofConstraintType, target, reportErrors)) { + errorInfo = saveErrorInfo; + return result; + } + } + else if (source.flags & 16777216) { + if (target.flags & 16777216) { + if (isTypeIdenticalTo(source.extendsType, target.extendsType) && + (isRelatedTo(source.checkType, target.checkType) || isRelatedTo(target.checkType, source.checkType))) { + if (result = isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), reportErrors)) { + result &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), reportErrors); + } + if (result) { + errorInfo = saveErrorInfo; + return result; + } + } + } + else if (relation !== definitelyAssignableRelation) { + var distributiveConstraint = getConstraintOfDistributiveConditionalType(source); + if (distributiveConstraint) { + if (result = isRelatedTo(distributiveConstraint, target, reportErrors)) { + errorInfo = saveErrorInfo; + return result; + } + } + var defaultConstraint = getDefaultConstraintOfConditionalType(source); + if (defaultConstraint) { + if (result = isRelatedTo(defaultConstraint, target, reportErrors)) { + errorInfo = saveErrorInfo; + return result; + } + } + } + } + else { + if (isPartialMappedType(target) && !isGenericMappedType(source) && isEmptyObjectType(source)) { + return -1; + } + if (isGenericMappedType(target)) { + if (isGenericMappedType(source)) { + if (result = mappedTypeRelatedTo(source, target, reportErrors)) { + errorInfo = saveErrorInfo; + return result; + } + } + return 0; + } + if (relation === definitelyAssignableRelation && isGenericMappedType(source)) { + return 0; + } + var sourceIsPrimitive = !!(source.flags & 131068); + if (relation !== identityRelation) { + source = getApparentType(source); + } + if (ts.getObjectFlags(source) & 4 && ts.getObjectFlags(target) & 4 && source.target === target.target && + !(ts.getObjectFlags(source) & 8192 || ts.getObjectFlags(target) & 8192)) { + var variances = getVariances(source.target); + if (result = typeArgumentsRelatedTo(source.typeArguments, target.typeArguments, variances, reportErrors)) { + return result; + } + if (variances !== ts.emptyArray && !hasCovariantVoidArgument(target, variances)) { + if (!(reportErrors && ts.some(variances, function (v) { return v === 0; }))) { + return 0; + } + originalErrorInfo = errorInfo; + errorInfo = saveErrorInfo; + } + } + else if (isTupleType(source) && (isArrayType(target) || isReadonlyArrayType(target)) || isArrayType(source) && isReadonlyArrayType(target)) { + return isRelatedTo(getIndexTypeOfType(source, 1) || anyType, getIndexTypeOfType(target, 1) || anyType, reportErrors); + } + if (source.flags & (524288 | 2097152) && target.flags & 524288) { + var reportStructuralErrors = reportErrors && errorInfo === saveErrorInfo && !sourceIsPrimitive; + result = propertiesRelatedTo(source, target, reportStructuralErrors); + if (result) { + result &= signaturesRelatedTo(source, target, 0, reportStructuralErrors); + if (result) { + result &= signaturesRelatedTo(source, target, 1, reportStructuralErrors); + if (result) { + result &= indexTypesRelatedTo(source, target, 0, sourceIsPrimitive, reportStructuralErrors); + if (result) { + result &= indexTypesRelatedTo(source, target, 1, sourceIsPrimitive, reportStructuralErrors); + } + } + } + } + if (result) { + if (!originalErrorInfo) { + errorInfo = saveErrorInfo; + return result; + } + errorInfo = originalErrorInfo; + } + } + } + return 0; + } + function mappedTypeRelatedTo(source, target, reportErrors) { + var modifiersRelated = relation === comparableRelation || (relation === identityRelation ? getMappedTypeModifiers(source) === getMappedTypeModifiers(target) : + getCombinedMappedTypeOptionality(source) <= getCombinedMappedTypeOptionality(target)); + if (modifiersRelated) { + var result_3; + if (result_3 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) { + var mapper = createTypeMapper([getTypeParameterFromMappedType(source)], [getTypeParameterFromMappedType(target)]); + return result_3 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); + } + } + return 0; + } + function propertiesRelatedTo(source, target, reportErrors) { + if (relation === identityRelation) { + return propertiesIdenticalTo(source, target); + } + var requireOptionalProperties = relation === subtypeRelation && !isObjectLiteralType(source) && !isEmptyArrayLiteralType(source) && !isTupleType(source); + var unmatchedProperty = getUnmatchedProperty(source, target, requireOptionalProperties); + if (unmatchedProperty) { + if (reportErrors) { + var props = ts.arrayFrom(getUnmatchedProperties(source, target, requireOptionalProperties)); + if (!headMessage || (headMessage.code !== ts.Diagnostics.Class_0_incorrectly_implements_interface_1.code && + headMessage.code !== ts.Diagnostics.Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass.code)) { + suppressNextError = true; + } + if (props.length === 1) { + var propName = symbolToString(unmatchedProperty); + reportError(ts.Diagnostics.Property_0_is_missing_in_type_1_but_required_in_type_2, propName, typeToString(source), typeToString(target)); + if (ts.length(unmatchedProperty.declarations)) { + associateRelatedInfo(ts.createDiagnosticForNode(unmatchedProperty.declarations[0], ts.Diagnostics._0_is_declared_here, propName)); + } + } + else if (props.length > 5) { + reportError(ts.Diagnostics.Type_0_is_missing_the_following_properties_from_type_1_Colon_2_and_3_more, typeToString(source), typeToString(target), ts.map(props.slice(0, 4), function (p) { return symbolToString(p); }).join(", "), props.length - 4); + } + else { + reportError(ts.Diagnostics.Type_0_is_missing_the_following_properties_from_type_1_Colon_2, typeToString(source), typeToString(target), ts.map(props, function (p) { return symbolToString(p); }).join(", ")); + } + } + return 0; + } + if (isObjectLiteralType(target)) { + for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) { + var sourceProp = _a[_i]; + if (!getPropertyOfObjectType(target, sourceProp.escapedName)) { + var sourceType = getTypeOfSymbol(sourceProp); + if (!(sourceType === undefinedType || sourceType === undefinedWideningType)) { + if (reportErrors) { + reportError(ts.Diagnostics.Property_0_does_not_exist_on_type_1, symbolToString(sourceProp), typeToString(target)); + } + return 0; + } + } + } + } + var result = -1; + if (isTupleType(target)) { + var targetRestType = getRestTypeOfTupleType(target); + if (targetRestType) { + if (!isTupleType(source)) { + return 0; + } + var sourceRestType = getRestTypeOfTupleType(source); + if (sourceRestType && !isRelatedTo(sourceRestType, targetRestType, reportErrors)) { + if (reportErrors) { + reportError(ts.Diagnostics.Rest_signatures_are_incompatible); + } + return 0; + } + var targetCount = getTypeReferenceArity(target) - 1; + var sourceCount = getTypeReferenceArity(source) - (sourceRestType ? 1 : 0); + for (var i = targetCount; i < sourceCount; i++) { + var related = isRelatedTo(source.typeArguments[i], targetRestType, reportErrors); + if (!related) { + if (reportErrors) { + reportError(ts.Diagnostics.Property_0_is_incompatible_with_rest_element_type, "" + i); + } + return 0; + } + result &= related; + } + } + } + var properties = getPropertiesOfObjectType(target); + for (var _b = 0, properties_2 = properties; _b < properties_2.length; _b++) { + var targetProp = properties_2[_b]; + if (!(targetProp.flags & 4194304)) { + var sourceProp = getPropertyOfType(source, targetProp.escapedName); + if (sourceProp && sourceProp !== targetProp) { + if (isIgnoredJsxProperty(source, sourceProp, getTypeOfSymbol(targetProp))) { + continue; + } + var sourcePropFlags = ts.getDeclarationModifierFlagsFromSymbol(sourceProp); + var targetPropFlags = ts.getDeclarationModifierFlagsFromSymbol(targetProp); + if (sourcePropFlags & 8 || targetPropFlags & 8) { + var hasDifferingDeclarations = sourceProp.valueDeclaration !== targetProp.valueDeclaration; + if (ts.getCheckFlags(sourceProp) & 256 && hasDifferingDeclarations) { + if (reportErrors) { + reportError(ts.Diagnostics.Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1, symbolToString(sourceProp), typeToString(source)); + } + return 0; + } + if (hasDifferingDeclarations) { + if (reportErrors) { + if (sourcePropFlags & 8 && targetPropFlags & 8) { + reportError(ts.Diagnostics.Types_have_separate_declarations_of_a_private_property_0, symbolToString(targetProp)); + } + else { + reportError(ts.Diagnostics.Property_0_is_private_in_type_1_but_not_in_type_2, symbolToString(targetProp), typeToString(sourcePropFlags & 8 ? source : target), typeToString(sourcePropFlags & 8 ? target : source)); + } + } + return 0; + } + } + else if (targetPropFlags & 16) { + if (!isValidOverrideOf(sourceProp, targetProp)) { + if (reportErrors) { + reportError(ts.Diagnostics.Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2, symbolToString(targetProp), typeToString(getDeclaringClass(sourceProp) || source), typeToString(getDeclaringClass(targetProp) || target)); + } + return 0; + } + } + else if (sourcePropFlags & 16) { + if (reportErrors) { + reportError(ts.Diagnostics.Property_0_is_protected_in_type_1_but_public_in_type_2, symbolToString(targetProp), typeToString(source), typeToString(target)); + } + return 0; + } + var related = isRelatedTo(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp), reportErrors); + if (!related) { + if (reportErrors) { + reportError(ts.Diagnostics.Types_of_property_0_are_incompatible, symbolToString(targetProp)); + } + return 0; + } + result &= related; + if (relation !== comparableRelation && sourceProp.flags & 16777216 && !(targetProp.flags & 16777216)) { + if (reportErrors) { + reportError(ts.Diagnostics.Property_0_is_optional_in_type_1_but_required_in_type_2, symbolToString(targetProp), typeToString(source), typeToString(target)); + } + return 0; + } + } + } + } + return result; + } + function propertiesIdenticalTo(source, target) { + if (!(source.flags & 524288 && target.flags & 524288)) { + return 0; + } + var sourceProperties = getPropertiesOfObjectType(source); + var targetProperties = getPropertiesOfObjectType(target); + if (sourceProperties.length !== targetProperties.length) { + return 0; + } + var result = -1; + for (var _i = 0, sourceProperties_1 = sourceProperties; _i < sourceProperties_1.length; _i++) { + var sourceProp = sourceProperties_1[_i]; + var targetProp = getPropertyOfObjectType(target, sourceProp.escapedName); + if (!targetProp) { + return 0; + } + var related = compareProperties(sourceProp, targetProp, isRelatedTo); + if (!related) { + return 0; + } + result &= related; + } + return result; + } + function signaturesRelatedTo(source, target, kind, reportErrors) { + if (relation === identityRelation) { + return signaturesIdenticalTo(source, target, kind); + } + if (target === anyFunctionType || source === anyFunctionType) { + return -1; + } + var sourceIsJSConstructor = source.symbol && isJSConstructor(source.symbol.valueDeclaration); + var targetIsJSConstructor = target.symbol && isJSConstructor(target.symbol.valueDeclaration); + var sourceSignatures = getSignaturesOfType(source, (sourceIsJSConstructor && kind === 1) ? + 0 : kind); + var targetSignatures = getSignaturesOfType(target, (targetIsJSConstructor && kind === 1) ? + 0 : kind); + if (kind === 1 && sourceSignatures.length && targetSignatures.length) { + if (ts.isAbstractConstructorType(source) && !ts.isAbstractConstructorType(target)) { + if (reportErrors) { + reportError(ts.Diagnostics.Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type); + } + return 0; + } + if (!constructorVisibilitiesAreCompatible(sourceSignatures[0], targetSignatures[0], reportErrors)) { + return 0; + } + } + var result = -1; + var saveErrorInfo = errorInfo; + if (ts.getObjectFlags(source) & 64 && ts.getObjectFlags(target) & 64 && source.symbol === target.symbol) { + for (var i = 0; i < targetSignatures.length; i++) { + var related = signatureRelatedTo(sourceSignatures[i], targetSignatures[i], true, reportErrors); + if (!related) { + return 0; + } + result &= related; + } + } + else if (sourceSignatures.length === 1 && targetSignatures.length === 1) { + var eraseGenerics = relation === comparableRelation || !!compilerOptions.noStrictGenericChecks; + result = signatureRelatedTo(sourceSignatures[0], targetSignatures[0], eraseGenerics, reportErrors); + } + else { + outer: for (var _i = 0, targetSignatures_1 = targetSignatures; _i < targetSignatures_1.length; _i++) { + var t = targetSignatures_1[_i]; + var shouldElaborateErrors = reportErrors; + for (var _a = 0, sourceSignatures_1 = sourceSignatures; _a < sourceSignatures_1.length; _a++) { + var s = sourceSignatures_1[_a]; + var related = signatureRelatedTo(s, t, true, shouldElaborateErrors); + if (related) { + result &= related; + errorInfo = saveErrorInfo; + continue outer; + } + shouldElaborateErrors = false; + } + if (shouldElaborateErrors) { + reportError(ts.Diagnostics.Type_0_provides_no_match_for_the_signature_1, typeToString(source), signatureToString(t, undefined, undefined, kind)); + } + return 0; + } + } + return result; + } + function signatureRelatedTo(source, target, erase, reportErrors) { + return compareSignaturesRelated(erase ? getErasedSignature(source) : source, erase ? getErasedSignature(target) : target, 0, false, reportErrors, reportError, isRelatedTo); + } + function signaturesIdenticalTo(source, target, kind) { + var sourceSignatures = getSignaturesOfType(source, kind); + var targetSignatures = getSignaturesOfType(target, kind); + if (sourceSignatures.length !== targetSignatures.length) { + return 0; + } + var result = -1; + for (var i = 0; i < sourceSignatures.length; i++) { + var related = compareSignaturesIdentical(sourceSignatures[i], targetSignatures[i], false, false, false, isRelatedTo); + if (!related) { + return 0; + } + result &= related; + } + return result; + } + function eachPropertyRelatedTo(source, target, kind, reportErrors) { + var result = -1; + for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) { + var prop = _a[_i]; + if (isIgnoredJsxProperty(source, prop, undefined)) { + continue; + } + if (prop.nameType && prop.nameType.flags & 8192) { + continue; + } + if (kind === 0 || isNumericLiteralName(prop.escapedName)) { + var related = isRelatedTo(getTypeOfSymbol(prop), target, reportErrors); + if (!related) { + if (reportErrors) { + reportError(ts.Diagnostics.Property_0_is_incompatible_with_index_signature, symbolToString(prop)); + } + return 0; + } + result &= related; + } + } + return result; + } + function indexInfoRelatedTo(sourceInfo, targetInfo, reportErrors) { + var related = isRelatedTo(sourceInfo.type, targetInfo.type, reportErrors); + if (!related && reportErrors) { + reportError(ts.Diagnostics.Index_signatures_are_incompatible); + } + return related; + } + function indexTypesRelatedTo(source, target, kind, sourceIsPrimitive, reportErrors) { + if (relation === identityRelation) { + return indexTypesIdenticalTo(source, target, kind); + } + var targetInfo = getIndexInfoOfType(target, kind); + if (!targetInfo || targetInfo.type.flags & 3 && !sourceIsPrimitive) { + return -1; + } + var sourceInfo = getIndexInfoOfType(source, kind) || + kind === 1 && getIndexInfoOfType(source, 0); + if (sourceInfo) { + return indexInfoRelatedTo(sourceInfo, targetInfo, reportErrors); + } + if (isGenericMappedType(source)) { + return (kind === 0 && isRelatedTo(getTemplateTypeFromMappedType(source), targetInfo.type, reportErrors)); + } + if (isObjectTypeWithInferableIndex(source)) { + var related = -1; + if (kind === 0) { + var sourceNumberInfo = getIndexInfoOfType(source, 1); + if (sourceNumberInfo) { + related = indexInfoRelatedTo(sourceNumberInfo, targetInfo, reportErrors); + } + } + if (related) { + related &= eachPropertyRelatedTo(source, targetInfo.type, kind, reportErrors); + } + return related; + } + if (reportErrors) { + reportError(ts.Diagnostics.Index_signature_is_missing_in_type_0, typeToString(source)); + } + return 0; + } + function indexTypesIdenticalTo(source, target, indexKind) { + var targetInfo = getIndexInfoOfType(target, indexKind); + var sourceInfo = getIndexInfoOfType(source, indexKind); + if (!sourceInfo && !targetInfo) { + return -1; + } + if (sourceInfo && targetInfo && sourceInfo.isReadonly === targetInfo.isReadonly) { + return isRelatedTo(sourceInfo.type, targetInfo.type); + } + return 0; + } + function constructorVisibilitiesAreCompatible(sourceSignature, targetSignature, reportErrors) { + if (!sourceSignature.declaration || !targetSignature.declaration) { + return true; + } + var sourceAccessibility = ts.getSelectedModifierFlags(sourceSignature.declaration, 24); + var targetAccessibility = ts.getSelectedModifierFlags(targetSignature.declaration, 24); + if (targetAccessibility === 8) { + return true; + } + if (targetAccessibility === 16 && sourceAccessibility !== 8) { + return true; + } + if (targetAccessibility !== 16 && !sourceAccessibility) { + return true; + } + if (reportErrors) { + reportError(ts.Diagnostics.Cannot_assign_a_0_constructor_type_to_a_1_constructor_type, visibilityToString(sourceAccessibility), visibilityToString(targetAccessibility)); + } + return false; + } + } + function discriminateTypeByDiscriminableItems(target, discriminators, related, defaultValue) { + var match; + for (var _i = 0, discriminators_1 = discriminators; _i < discriminators_1.length; _i++) { + var _a = discriminators_1[_i], getDiscriminatingType = _a[0], propertyName = _a[1]; + for (var _b = 0, _c = target.types; _b < _c.length; _b++) { + var type = _c[_b]; + var targetType = getTypeOfPropertyOfType(type, propertyName); + if (targetType && related(getDiscriminatingType(), targetType)) { + if (match) { + if (type === match) + continue; + return defaultValue; + } + match = type; + } + } + } + return match || defaultValue; + } + function isWeakType(type) { + if (type.flags & 524288) { + var resolved = resolveStructuredTypeMembers(type); + return resolved.callSignatures.length === 0 && resolved.constructSignatures.length === 0 && + !resolved.stringIndexInfo && !resolved.numberIndexInfo && + resolved.properties.length > 0 && + ts.every(resolved.properties, function (p) { return !!(p.flags & 16777216); }); + } + if (type.flags & 2097152) { + return ts.every(type.types, isWeakType); + } + return false; + } + function hasCommonProperties(source, target, isComparingJsxAttributes) { + for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) { + var prop = _a[_i]; + if (isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { + return true; + } + } + return false; + } + function getMarkerTypeReference(type, source, target) { + var result = createTypeReference(type, ts.map(type.typeParameters, function (t) { return t === source ? target : t; })); + result.objectFlags |= 8192; + return result; + } + function getAliasVariances(symbol) { + var links = getSymbolLinks(symbol); + return getVariancesWorker(links.typeParameters, links, function (_links, param, marker) { + var type = getTypeAliasInstantiation(symbol, instantiateTypes(links.typeParameters, makeUnaryTypeMapper(param, marker))); + type.aliasTypeArgumentsContainsMarker = true; + return type; + }); + } + function getVariancesWorker(typeParameters, cache, createMarkerType) { + if (typeParameters === void 0) { typeParameters = ts.emptyArray; } + var variances = cache.variances; + if (!variances) { + cache.variances = ts.emptyArray; + variances = []; + for (var _i = 0, typeParameters_1 = typeParameters; _i < typeParameters_1.length; _i++) { + var tp = typeParameters_1[_i]; + var typeWithSuper = createMarkerType(cache, tp, markerSuperType); + var typeWithSub = createMarkerType(cache, tp, markerSubType); + var variance = (isTypeAssignableTo(typeWithSub, typeWithSuper) ? 1 : 0) | + (isTypeAssignableTo(typeWithSuper, typeWithSub) ? 2 : 0); + if (variance === 3 && isTypeAssignableTo(createMarkerType(cache, tp, markerOtherType), typeWithSuper)) { + variance = 4; + } + variances.push(variance); + } + cache.variances = variances; + } + return variances; + } + function getVariances(type) { + if (!strictFunctionTypes) { + return ts.emptyArray; + } + if (type === globalArrayType || type === globalReadonlyArrayType) { + return ts.emptyArray; + } + return getVariancesWorker(type.typeParameters, type, getMarkerTypeReference); + } + function hasCovariantVoidArgument(type, variances) { + for (var i = 0; i < variances.length; i++) { + if (variances[i] === 1 && type.typeArguments[i].flags & 16384) { + return true; + } + } + return false; + } + function isUnconstrainedTypeParameter(type) { + return type.flags & 262144 && !getConstraintOfTypeParameter(type); + } + function isTypeReferenceWithGenericArguments(type) { + return !!(ts.getObjectFlags(type) & 4) && ts.some(type.typeArguments, function (t) { return isUnconstrainedTypeParameter(t) || isTypeReferenceWithGenericArguments(t); }); + } + function getTypeReferenceId(type, typeParameters, depth) { + if (depth === void 0) { depth = 0; } + var result = "" + type.target.id; + for (var _i = 0, _a = type.typeArguments; _i < _a.length; _i++) { + var t = _a[_i]; + if (isUnconstrainedTypeParameter(t)) { + var index = typeParameters.indexOf(t); + if (index < 0) { + index = typeParameters.length; + typeParameters.push(t); + } + result += "=" + index; + } + else if (depth < 4 && isTypeReferenceWithGenericArguments(t)) { + result += "<" + getTypeReferenceId(t, typeParameters, depth + 1) + ">"; + } + else { + result += "-" + t.id; + } + } + return result; + } + function getRelationKey(source, target, relation) { + if (relation === identityRelation && source.id > target.id) { + var temp = source; + source = target; + target = temp; + } + if (isTypeReferenceWithGenericArguments(source) && isTypeReferenceWithGenericArguments(target)) { + var typeParameters = []; + return getTypeReferenceId(source, typeParameters) + "," + getTypeReferenceId(target, typeParameters); + } + return source.id + "," + target.id; + } + function forEachProperty(prop, callback) { + if (ts.getCheckFlags(prop) & 6) { + for (var _i = 0, _a = prop.containingType.types; _i < _a.length; _i++) { + var t = _a[_i]; + var p = getPropertyOfType(t, prop.escapedName); + var result = p && forEachProperty(p, callback); + if (result) { + return result; + } + } + return undefined; + } + return callback(prop); + } + function getDeclaringClass(prop) { + return prop.parent && prop.parent.flags & 32 ? getDeclaredTypeOfSymbol(getParentOfSymbol(prop)) : undefined; + } + function isPropertyInClassDerivedFrom(prop, baseClass) { + return forEachProperty(prop, function (sp) { + var sourceClass = getDeclaringClass(sp); + return sourceClass ? hasBaseType(sourceClass, baseClass) : false; + }); + } + function isValidOverrideOf(sourceProp, targetProp) { + return !forEachProperty(targetProp, function (tp) { return ts.getDeclarationModifierFlagsFromSymbol(tp) & 16 ? + !isPropertyInClassDerivedFrom(sourceProp, getDeclaringClass(tp)) : false; }); + } + function isClassDerivedFromDeclaringClasses(checkClass, prop) { + return forEachProperty(prop, function (p) { return ts.getDeclarationModifierFlagsFromSymbol(p) & 16 ? + !hasBaseType(checkClass, getDeclaringClass(p)) : false; }) ? undefined : checkClass; + } + function isDeeplyNestedType(type, stack, depth) { + if (depth >= 5 && type.flags & 524288) { + var symbol = type.symbol; + if (symbol) { + var count = 0; + for (var i = 0; i < depth; i++) { + var t = stack[i]; + if (t.flags & 524288 && t.symbol === symbol) { + count++; + if (count >= 5) + return true; + } + } + } + } + return false; + } + function isPropertyIdenticalTo(sourceProp, targetProp) { + return compareProperties(sourceProp, targetProp, compareTypesIdentical) !== 0; + } + function compareProperties(sourceProp, targetProp, compareTypes) { + if (sourceProp === targetProp) { + return -1; + } + var sourcePropAccessibility = ts.getDeclarationModifierFlagsFromSymbol(sourceProp) & 24; + var targetPropAccessibility = ts.getDeclarationModifierFlagsFromSymbol(targetProp) & 24; + if (sourcePropAccessibility !== targetPropAccessibility) { + return 0; + } + if (sourcePropAccessibility) { + if (getTargetSymbol(sourceProp) !== getTargetSymbol(targetProp)) { + return 0; + } + } + else { + if ((sourceProp.flags & 16777216) !== (targetProp.flags & 16777216)) { + return 0; + } + } + if (isReadonlySymbol(sourceProp) !== isReadonlySymbol(targetProp)) { + return 0; + } + return compareTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); + } + function isMatchingSignature(source, target, partialMatch) { + var sourceParameterCount = getParameterCount(source); + var targetParameterCount = getParameterCount(target); + var sourceMinArgumentCount = getMinArgumentCount(source); + var targetMinArgumentCount = getMinArgumentCount(target); + var sourceHasRestParameter = hasEffectiveRestParameter(source); + var targetHasRestParameter = hasEffectiveRestParameter(target); + if (sourceParameterCount === targetParameterCount && + sourceMinArgumentCount === targetMinArgumentCount && + sourceHasRestParameter === targetHasRestParameter) { + return true; + } + if (partialMatch && sourceMinArgumentCount <= targetMinArgumentCount) { + return true; + } + return false; + } + function compareSignaturesIdentical(source, target, partialMatch, ignoreThisTypes, ignoreReturnTypes, compareTypes) { + if (source === target) { + return -1; + } + if (!(isMatchingSignature(source, target, partialMatch))) { + return 0; + } + if (ts.length(source.typeParameters) !== ts.length(target.typeParameters)) { + return 0; + } + source = getErasedSignature(source); + target = getErasedSignature(target); + var result = -1; + if (!ignoreThisTypes) { + var sourceThisType = getThisTypeOfSignature(source); + if (sourceThisType) { + var targetThisType = getThisTypeOfSignature(target); + if (targetThisType) { + var related = compareTypes(sourceThisType, targetThisType); + if (!related) { + return 0; + } + result &= related; + } + } + } + var targetLen = getParameterCount(target); + for (var i = 0; i < targetLen; i++) { + var s = getTypeAtPosition(source, i); + var t = getTypeAtPosition(target, i); + var related = compareTypes(t, s); + if (!related) { + return 0; + } + result &= related; + } + if (!ignoreReturnTypes) { + var sourceTypePredicate = getTypePredicateOfSignature(source); + var targetTypePredicate = getTypePredicateOfSignature(target); + result &= sourceTypePredicate !== undefined || targetTypePredicate !== undefined + ? compareTypePredicatesIdentical(sourceTypePredicate, targetTypePredicate, compareTypes) + : compareTypes(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target)); + } + return result; + } + function compareTypePredicatesIdentical(source, target, compareTypes) { + return source === undefined || target === undefined || !typePredicateKindsMatch(source, target) ? 0 : compareTypes(source.type, target.type); + } + function literalTypesWithSameBaseType(types) { + var commonBaseType; + for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { + var t = types_8[_i]; + var baseType = getBaseTypeOfLiteralType(t); + if (!commonBaseType) { + commonBaseType = baseType; + } + if (baseType === t || baseType !== commonBaseType) { + return false; + } + } + return true; + } + function getSupertypeOrUnion(types) { + return literalTypesWithSameBaseType(types) ? + getUnionType(types) : + ts.reduceLeft(types, function (s, t) { return isTypeSubtypeOf(s, t) ? t : s; }); + } + function getCommonSupertype(types) { + if (!strictNullChecks) { + return getSupertypeOrUnion(types); + } + var primaryTypes = ts.filter(types, function (t) { return !(t.flags & 98304); }); + return primaryTypes.length ? + getNullableType(getSupertypeOrUnion(primaryTypes), getFalsyFlagsOfTypes(types) & 98304) : + getUnionType(types, 2); + } + function getCommonSubtype(types) { + return ts.reduceLeft(types, function (s, t) { return isTypeSubtypeOf(t, s) ? t : s; }); + } + function isArrayType(type) { + return !!(ts.getObjectFlags(type) & 4) && type.target === globalArrayType; + } + function isReadonlyArrayType(type) { + return !!(ts.getObjectFlags(type) & 4) && type.target === globalReadonlyArrayType; + } + function getElementTypeOfArrayType(type) { + return isArrayType(type) && type.typeArguments ? type.typeArguments[0] : undefined; + } + function isArrayLikeType(type) { + return ts.getObjectFlags(type) & 4 && (type.target === globalArrayType || type.target === globalReadonlyArrayType) || + !(type.flags & 98304) && isTypeAssignableTo(type, anyReadonlyArrayType); + } + function isEmptyArrayLiteralType(type) { + var elementType = isArrayType(type) ? type.typeArguments[0] : undefined; + return elementType === undefinedWideningType || elementType === implicitNeverType; + } + function isTupleLikeType(type) { + return isTupleType(type) || !!getPropertyOfType(type, "0"); + } + function getTupleElementType(type, index) { + var propType = getTypeOfPropertyOfType(type, "" + index); + if (propType) { + return propType; + } + if (everyType(type, isTupleType) && !everyType(type, function (t) { return !t.target.hasRestElement; })) { + return mapType(type, function (t) { return getRestTypeOfTupleType(t) || undefinedType; }); + } + return undefined; + } + function isNeitherUnitTypeNorNever(type) { + return !(type.flags & (109440 | 131072)); + } + function isUnitType(type) { + return !!(type.flags & 109440); + } + function isLiteralType(type) { + return type.flags & 16 ? true : + type.flags & 1048576 ? type.flags & 1024 ? true : ts.every(type.types, isUnitType) : + isUnitType(type); + } + function getBaseTypeOfLiteralType(type) { + return type.flags & 1024 ? getBaseTypeOfEnumLiteralType(type) : + type.flags & 128 ? stringType : + type.flags & 256 ? numberType : + type.flags & 2048 ? bigintType : + type.flags & 512 ? booleanType : + type.flags & 1048576 ? getUnionType(ts.sameMap(type.types, getBaseTypeOfLiteralType)) : + type; + } + function getWidenedLiteralType(type) { + return type.flags & 1024 && isFreshLiteralType(type) ? getBaseTypeOfEnumLiteralType(type) : + type.flags & 128 && isFreshLiteralType(type) ? stringType : + type.flags & 256 && isFreshLiteralType(type) ? numberType : + type.flags & 2048 && isFreshLiteralType(type) ? bigintType : + type.flags & 512 && isFreshLiteralType(type) ? booleanType : + type.flags & 1048576 ? getUnionType(ts.sameMap(type.types, getWidenedLiteralType)) : + type; + } + function getWidenedUniqueESSymbolType(type) { + return type.flags & 8192 ? esSymbolType : + type.flags & 1048576 ? getUnionType(ts.sameMap(type.types, getWidenedUniqueESSymbolType)) : + type; + } + function getWidenedLiteralLikeTypeForContextualType(type, contextualType) { + if (!isLiteralOfContextualType(type, contextualType)) { + type = getWidenedUniqueESSymbolType(getWidenedLiteralType(type)); + } + return type; + } + function isTupleType(type) { + return !!(ts.getObjectFlags(type) & 4 && type.target.objectFlags & 8); + } + function getRestTypeOfTupleType(type) { + return type.target.hasRestElement ? type.typeArguments[type.target.typeParameters.length - 1] : undefined; + } + function getRestArrayTypeOfTupleType(type) { + var restType = getRestTypeOfTupleType(type); + return restType && createArrayType(restType); + } + function getLengthOfTupleType(type) { + return getTypeReferenceArity(type) - (type.target.hasRestElement ? 1 : 0); + } + function isZeroBigInt(_a) { + var value = _a.value; + return value.base10Value === "0"; + } + function getFalsyFlagsOfTypes(types) { + var result = 0; + for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { + var t = types_9[_i]; + result |= getFalsyFlags(t); + } + return result; + } + function getFalsyFlags(type) { + return type.flags & 1048576 ? getFalsyFlagsOfTypes(type.types) : + type.flags & 128 ? type.value === "" ? 128 : 0 : + type.flags & 256 ? type.value === 0 ? 256 : 0 : + type.flags & 2048 ? isZeroBigInt(type) ? 2048 : 0 : + type.flags & 512 ? (type === falseType || type === regularFalseType) ? 512 : 0 : + type.flags & 117724; + } + function removeDefinitelyFalsyTypes(type) { + return getFalsyFlags(type) & 117632 ? + filterType(type, function (t) { return !(getFalsyFlags(t) & 117632); }) : + type; + } + function extractDefinitelyFalsyTypes(type) { + return mapType(type, getDefinitelyFalsyPartOfType); + } + function getDefinitelyFalsyPartOfType(type) { + return type.flags & 4 ? emptyStringType : + type.flags & 8 ? zeroType : + type.flags & 64 ? zeroBigIntType : + type === regularFalseType || + type === falseType || + type.flags & (16384 | 32768 | 65536) || + type.flags & 128 && type.value === "" || + type.flags & 256 && type.value === 0 || + type.flags & 2048 && isZeroBigInt(type) ? type : + neverType; + } + function getNullableType(type, flags) { + var missing = (flags & ~type.flags) & (32768 | 65536); + return missing === 0 ? type : + missing === 32768 ? getUnionType([type, undefinedType]) : + missing === 65536 ? getUnionType([type, nullType]) : + getUnionType([type, undefinedType, nullType]); + } + function getOptionalType(type) { + ts.Debug.assert(strictNullChecks); + return type.flags & 32768 ? type : getUnionType([type, undefinedType]); + } + function getGlobalNonNullableTypeInstantiation(type) { + if (!deferredGlobalNonNullableTypeAlias) { + deferredGlobalNonNullableTypeAlias = getGlobalSymbol("NonNullable", 524288, undefined) || unknownSymbol; + } + if (deferredGlobalNonNullableTypeAlias !== unknownSymbol) { + return getTypeAliasInstantiation(deferredGlobalNonNullableTypeAlias, [type]); + } + return getTypeWithFacts(type, 2097152); + } + function getNonNullableType(type) { + return strictNullChecks ? getGlobalNonNullableTypeInstantiation(type) : type; + } + function isObjectTypeWithInferableIndex(type) { + return type.symbol && (type.symbol.flags & (4096 | 2048 | 512)) !== 0 && + !typeHasCallOrConstructSignatures(type); + } + function createSymbolWithType(source, type) { + var symbol = createSymbol(source.flags, source.escapedName); + symbol.declarations = source.declarations; + symbol.parent = source.parent; + symbol.type = type; + symbol.target = source; + if (source.valueDeclaration) { + symbol.valueDeclaration = source.valueDeclaration; + } + if (source.nameType) { + symbol.nameType = source.nameType; + } + return symbol; + } + function transformTypeOfMembers(type, f) { + var members = ts.createSymbolTable(); + for (var _i = 0, _a = getPropertiesOfObjectType(type); _i < _a.length; _i++) { + var property = _a[_i]; + var original = getTypeOfSymbol(property); + var updated = f(original); + members.set(property.escapedName, updated === original ? property : createSymbolWithType(property, updated)); + } + return members; + } + function getRegularTypeOfObjectLiteral(type) { + if (!(isObjectLiteralType(type) && ts.getObjectFlags(type) & 32768)) { + return type; + } + var regularType = type.regularType; + if (regularType) { + return regularType; + } + var resolved = type; + var members = transformTypeOfMembers(type, getRegularTypeOfObjectLiteral); + var regularNew = createAnonymousType(resolved.symbol, members, resolved.callSignatures, resolved.constructSignatures, resolved.stringIndexInfo, resolved.numberIndexInfo); + regularNew.flags = resolved.flags; + regularNew.objectFlags |= 128 | (ts.getObjectFlags(resolved) & 16384); + type.regularType = regularNew; + return regularNew; + } + function createWideningContext(parent, propertyName, siblings) { + return { parent: parent, propertyName: propertyName, siblings: siblings, resolvedProperties: undefined }; + } + function getSiblingsOfContext(context) { + if (!context.siblings) { + var siblings_1 = []; + for (var _i = 0, _a = getSiblingsOfContext(context.parent); _i < _a.length; _i++) { + var type = _a[_i]; + if (isObjectLiteralType(type)) { + var prop = getPropertyOfObjectType(type, context.propertyName); + if (prop) { + forEachType(getTypeOfSymbol(prop), function (t) { + siblings_1.push(t); + }); + } + } + } + context.siblings = siblings_1; + } + return context.siblings; + } + function getPropertiesOfContext(context) { + if (!context.resolvedProperties) { + var names = ts.createMap(); + for (var _i = 0, _a = getSiblingsOfContext(context); _i < _a.length; _i++) { + var t = _a[_i]; + if (isObjectLiteralType(t) && !(ts.getObjectFlags(t) & 1024)) { + for (var _b = 0, _c = getPropertiesOfType(t); _b < _c.length; _b++) { + var prop = _c[_b]; + names.set(prop.escapedName, prop); + } + } + } + context.resolvedProperties = ts.arrayFrom(names.values()); + } + return context.resolvedProperties; + } + function getWidenedProperty(prop, context) { + if (!(prop.flags & 4)) { + return prop; + } + var original = getTypeOfSymbol(prop); + var propContext = context && createWideningContext(context, prop.escapedName, undefined); + var widened = getWidenedTypeWithContext(original, propContext); + return widened === original ? prop : createSymbolWithType(prop, widened); + } + function getUndefinedProperty(prop) { + var cached = undefinedProperties.get(prop.escapedName); + if (cached) { + return cached; + } + var result = createSymbolWithType(prop, undefinedType); + result.flags |= 16777216; + undefinedProperties.set(prop.escapedName, result); + return result; + } + function getWidenedTypeOfObjectLiteral(type, context) { + var members = ts.createSymbolTable(); + for (var _i = 0, _a = getPropertiesOfObjectType(type); _i < _a.length; _i++) { + var prop = _a[_i]; + members.set(prop.escapedName, getWidenedProperty(prop, context)); + } + if (context) { + for (var _b = 0, _c = getPropertiesOfContext(context); _b < _c.length; _b++) { + var prop = _c[_b]; + if (!members.has(prop.escapedName)) { + members.set(prop.escapedName, getUndefinedProperty(prop)); + } + } + } + var stringIndexInfo = getIndexInfoOfType(type, 0); + var numberIndexInfo = getIndexInfoOfType(type, 1); + var result = createAnonymousType(type.symbol, members, ts.emptyArray, ts.emptyArray, stringIndexInfo && createIndexInfo(getWidenedType(stringIndexInfo.type), stringIndexInfo.isReadonly), numberIndexInfo && createIndexInfo(getWidenedType(numberIndexInfo.type), numberIndexInfo.isReadonly)); + result.objectFlags |= (ts.getObjectFlags(type) & 16384); + return result; + } + function getWidenedType(type) { + return getWidenedTypeWithContext(type, undefined); + } + function getWidenedTypeWithContext(type, context) { + if (type.flags & 402653184) { + if (type.flags & 98304) { + return anyType; + } + if (isObjectLiteralType(type)) { + return getWidenedTypeOfObjectLiteral(type, context); + } + if (type.flags & 1048576) { + var unionContext_1 = context || createWideningContext(undefined, undefined, type.types); + var widenedTypes = ts.sameMap(type.types, function (t) { return t.flags & 98304 ? t : getWidenedTypeWithContext(t, unionContext_1); }); + return getUnionType(widenedTypes, ts.some(widenedTypes, isEmptyObjectType) ? 2 : 1); + } + if (isArrayType(type) || isTupleType(type)) { + return createTypeReference(type.target, ts.sameMap(type.typeArguments, getWidenedType)); + } + } + return type; + } + function reportWideningErrorsInType(type) { + var errorReported = false; + if (type.flags & 134217728) { + if (type.flags & 1048576) { + if (ts.some(type.types, isEmptyObjectType)) { + errorReported = true; + } + else { + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (reportWideningErrorsInType(t)) { + errorReported = true; + } + } + } + } + if (isArrayType(type) || isTupleType(type)) { + for (var _b = 0, _c = type.typeArguments; _b < _c.length; _b++) { + var t = _c[_b]; + if (reportWideningErrorsInType(t)) { + errorReported = true; + } + } + } + if (isObjectLiteralType(type)) { + for (var _d = 0, _e = getPropertiesOfObjectType(type); _d < _e.length; _d++) { + var p = _e[_d]; + var t = getTypeOfSymbol(p); + if (t.flags & 134217728) { + if (!reportWideningErrorsInType(t)) { + error(p.valueDeclaration, ts.Diagnostics.Object_literal_s_property_0_implicitly_has_an_1_type, symbolToString(p), typeToString(getWidenedType(t))); + } + errorReported = true; + } + } + } + } + return errorReported; + } + function reportImplicitAny(declaration, type) { + var typeAsString = typeToString(getWidenedType(type)); + if (ts.isInJSFile(declaration) && !ts.isCheckJsEnabledForFile(ts.getSourceFileOfNode(declaration), compilerOptions)) { + return; + } + var diagnostic; + switch (declaration.kind) { + case 204: + case 154: + case 153: + diagnostic = noImplicitAny ? ts.Diagnostics.Member_0_implicitly_has_an_1_type : ts.Diagnostics.Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage; + break; + case 151: + var param = declaration; + if (ts.isIdentifier(param.name) && + (ts.isCallSignatureDeclaration(param.parent) || ts.isMethodSignature(param.parent) || ts.isFunctionTypeNode(param.parent)) && + param.parent.parameters.indexOf(param) > -1 && + (resolveName(param, param.name.escapedText, 67897832, undefined, param.name.escapedText, true) || + param.name.originalKeywordKind && ts.isTypeNodeKind(param.name.originalKeywordKind))) { + var newName = "arg" + param.parent.parameters.indexOf(param); + errorOrSuggestion(noImplicitAny, declaration, ts.Diagnostics.Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1, newName, ts.declarationNameToString(param.name)); + return; + } + diagnostic = declaration.dotDotDotToken ? + noImplicitAny ? ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type : ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage : + noImplicitAny ? ts.Diagnostics.Parameter_0_implicitly_has_an_1_type : ts.Diagnostics.Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage; + break; + case 186: + diagnostic = ts.Diagnostics.Binding_element_0_implicitly_has_an_1_type; + break; + case 289: + error(declaration, ts.Diagnostics.Function_type_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString); + return; + case 239: + case 156: + case 155: + case 158: + case 159: + case 196: + case 197: + if (noImplicitAny && !declaration.name) { + error(declaration, ts.Diagnostics.Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString); + return; + } + diagnostic = noImplicitAny ? ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type : ts.Diagnostics._0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage; + break; + case 181: + if (noImplicitAny) { + error(declaration, ts.Diagnostics.Mapped_object_type_implicitly_has_an_any_template_type); + } + return; + default: + diagnostic = noImplicitAny ? ts.Diagnostics.Variable_0_implicitly_has_an_1_type : ts.Diagnostics.Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage; + } + errorOrSuggestion(noImplicitAny, declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString); + } + function reportErrorsFromWidening(declaration, type) { + if (produceDiagnostics && noImplicitAny && type.flags & 134217728) { + if (!reportWideningErrorsInType(type)) { + reportImplicitAny(declaration, type); + } + } + } + function forEachMatchingParameterType(source, target, callback) { + var sourceCount = getParameterCount(source); + var targetCount = getParameterCount(target); + var sourceRestType = getEffectiveRestType(source); + var targetRestType = getEffectiveRestType(target); + var targetNonRestCount = targetRestType ? targetCount - 1 : targetCount; + var paramCount = sourceRestType ? targetNonRestCount : Math.min(sourceCount, targetNonRestCount); + var sourceThisType = getThisTypeOfSignature(source); + if (sourceThisType) { + var targetThisType = getThisTypeOfSignature(target); + if (targetThisType) { + callback(sourceThisType, targetThisType); + } + } + for (var i = 0; i < paramCount; i++) { + callback(getTypeAtPosition(source, i), getTypeAtPosition(target, i)); + } + if (targetRestType) { + callback(getRestTypeAtPosition(source, paramCount), targetRestType); + } + } + function createInferenceContext(typeParameters, signature, flags, compareTypes, baseInferences) { + var inferences = baseInferences ? baseInferences.map(cloneInferenceInfo) : typeParameters.map(createInferenceInfo); + var context = mapper; + context.typeParameters = typeParameters; + context.signature = signature; + context.inferences = inferences; + context.flags = flags; + context.compareTypes = compareTypes || compareTypesAssignable; + return context; + function mapper(t) { + for (var i = 0; i < inferences.length; i++) { + if (t === inferences[i].typeParameter) { + inferences[i].isFixed = true; + return getInferredType(context, i); + } + } + return t; + } + } + function createInferenceInfo(typeParameter) { + return { + typeParameter: typeParameter, + candidates: undefined, + contraCandidates: undefined, + inferredType: undefined, + priority: undefined, + topLevel: true, + isFixed: false + }; + } + function cloneInferenceInfo(inference) { + return { + typeParameter: inference.typeParameter, + candidates: inference.candidates && inference.candidates.slice(), + contraCandidates: inference.contraCandidates && inference.contraCandidates.slice(), + inferredType: inference.inferredType, + priority: inference.priority, + topLevel: inference.topLevel, + isFixed: inference.isFixed + }; + } + function couldContainTypeVariables(type) { + var objectFlags = ts.getObjectFlags(type); + return !!(type.flags & 63176704 || + objectFlags & 4 && ts.forEach(type.typeArguments, couldContainTypeVariables) || + objectFlags & 16 && type.symbol && type.symbol.flags & (16 | 8192 | 2048 | 32) || + objectFlags & 32 || + type.flags & 3145728 && couldUnionOrIntersectionContainTypeVariables(type)); + } + function couldUnionOrIntersectionContainTypeVariables(type) { + if (type.couldContainTypeVariables === undefined) { + type.couldContainTypeVariables = ts.some(type.types, couldContainTypeVariables); + } + return type.couldContainTypeVariables; + } + function isTypeParameterAtTopLevel(type, typeParameter) { + return type === typeParameter || !!(type.flags & 3145728) && ts.some(type.types, function (t) { return isTypeParameterAtTopLevel(t, typeParameter); }); + } + function createEmptyObjectTypeFromStringLiteral(type) { + var members = ts.createSymbolTable(); + forEachType(type, function (t) { + if (!(t.flags & 128)) { + return; + } + var name = ts.escapeLeadingUnderscores(t.value); + var literalProp = createSymbol(4, name); + literalProp.type = anyType; + if (t.symbol) { + literalProp.declarations = t.symbol.declarations; + literalProp.valueDeclaration = t.symbol.valueDeclaration; + } + members.set(name, literalProp); + }); + var indexInfo = type.flags & 4 ? createIndexInfo(emptyObjectType, false) : undefined; + return createAnonymousType(undefined, members, ts.emptyArray, ts.emptyArray, indexInfo, undefined); + } + function inferTypeForHomomorphicMappedType(source, target, constraint) { + var key = source.id + "," + target.id + "," + constraint.id; + if (reverseMappedCache.has(key)) { + return reverseMappedCache.get(key); + } + reverseMappedCache.set(key, undefined); + var type = createReverseMappedType(source, target, constraint); + reverseMappedCache.set(key, type); + return type; + } + function createReverseMappedType(source, target, constraint) { + var properties = getPropertiesOfType(source); + if (properties.length === 0 && !getIndexInfoOfType(source, 0)) { + return undefined; + } + for (var _i = 0, properties_3 = properties; _i < properties_3.length; _i++) { + var prop = properties_3[_i]; + if (getTypeOfSymbol(prop).flags & 536870912) { + return undefined; + } + } + if (isArrayType(source)) { + return createArrayType(inferReverseMappedType(source.typeArguments[0], target, constraint)); + } + if (isReadonlyArrayType(source)) { + return createReadonlyArrayType(inferReverseMappedType(source.typeArguments[0], target, constraint)); + } + if (isTupleType(source)) { + var elementTypes = ts.map(source.typeArguments || ts.emptyArray, function (t) { return inferReverseMappedType(t, target, constraint); }); + var minLength = getMappedTypeModifiers(target) & 4 ? + getTypeReferenceArity(source) - (source.target.hasRestElement ? 1 : 0) : source.target.minLength; + return createTupleType(elementTypes, minLength, source.target.hasRestElement, source.target.associatedNames); + } + var reversed = createObjectType(2048 | 16, undefined); + reversed.source = source; + reversed.mappedType = target; + reversed.constraintType = constraint; + return reversed; + } + function getTypeOfReverseMappedSymbol(symbol) { + return inferReverseMappedType(symbol.propertyType, symbol.mappedType, symbol.constraintType); + } + function inferReverseMappedType(sourceType, target, constraint) { + var typeParameter = getIndexedAccessType(constraint.type, getTypeParameterFromMappedType(target)); + var templateType = getTemplateTypeFromMappedType(target); + var inference = createInferenceInfo(typeParameter); + inferTypes([inference], sourceType, templateType); + return getTypeFromInference(inference); + } + function getUnmatchedProperties(source, target, requireOptionalProperties) { + var properties, _i, properties_4, targetProp, sourceProp; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + properties = target.flags & 2097152 ? getPropertiesOfUnionOrIntersectionType(target) : getPropertiesOfObjectType(target); + _i = 0, properties_4 = properties; + _a.label = 1; + case 1: + if (!(_i < properties_4.length)) return [3, 4]; + targetProp = properties_4[_i]; + if (!(requireOptionalProperties || !(targetProp.flags & 16777216))) return [3, 3]; + sourceProp = getPropertyOfType(source, targetProp.escapedName); + if (!!sourceProp) return [3, 3]; + return [4, targetProp]; + case 2: + _a.sent(); + _a.label = 3; + case 3: + _i++; + return [3, 1]; + case 4: return [2]; + } + }); + } + function getUnmatchedProperty(source, target, requireOptionalProperties) { + return getUnmatchedProperties(source, target, requireOptionalProperties).next().value; + } + function tupleTypesDefinitelyUnrelated(source, target) { + return target.target.minLength > source.target.minLength || + !getRestTypeOfTupleType(target) && (!!getRestTypeOfTupleType(source) || getLengthOfTupleType(target) < getLengthOfTupleType(source)); + } + function typesDefinitelyUnrelated(source, target) { + return isTupleType(source) && isTupleType(target) && tupleTypesDefinitelyUnrelated(source, target) || + !!getUnmatchedProperty(source, target, false) && !!getUnmatchedProperty(target, source, false); + } + function getTypeFromInference(inference) { + return inference.candidates ? getUnionType(inference.candidates, 2) : + inference.contraCandidates ? getIntersectionType(inference.contraCandidates) : + emptyObjectType; + } + function inferTypes(inferences, originalSource, originalTarget, priority) { + if (priority === void 0) { priority = 0; } + var symbolStack; + var visited; + var contravariant = false; + var bivariant = false; + var propagationType; + var allowComplexConstraintInference = true; + inferFromTypes(originalSource, originalTarget); + function inferFromTypes(source, target) { + if (!couldContainTypeVariables(target)) { + return; + } + if (source === wildcardType) { + var savePropagationType = propagationType; + propagationType = source; + inferFromTypes(target, target); + propagationType = savePropagationType; + return; + } + if (source.aliasSymbol && source.aliasTypeArguments && source.aliasSymbol === target.aliasSymbol) { + var sourceTypes = source.aliasTypeArguments; + var targetTypes = target.aliasTypeArguments; + for (var i = 0; i < sourceTypes.length; i++) { + inferFromTypes(sourceTypes[i], targetTypes[i]); + } + return; + } + if (source.flags & 1048576 && target.flags & 1048576 && !(source.flags & 1024 && target.flags & 1024) || + source.flags & 2097152 && target.flags & 2097152) { + if (source === target) { + for (var _i = 0, _a = source.types; _i < _a.length; _i++) { + var t = _a[_i]; + inferFromTypes(t, t); + } + return; + } + var matchingTypes = void 0; + for (var _b = 0, _c = source.types; _b < _c.length; _b++) { + var t = _c[_b]; + if (typeIdenticalToSomeType(t, target.types)) { + (matchingTypes || (matchingTypes = [])).push(t); + inferFromTypes(t, t); + } + else if (t.flags & (256 | 128)) { + var b = getBaseTypeOfLiteralType(t); + if (typeIdenticalToSomeType(b, target.types)) { + (matchingTypes || (matchingTypes = [])).push(t, b); + } + } + } + if (matchingTypes) { + source = removeTypesFromUnionOrIntersection(source, matchingTypes); + target = removeTypesFromUnionOrIntersection(target, matchingTypes); + } + } + if (target.flags & 8650752) { + if (source.flags & 536870912 || source === silentNeverType || (priority & 8 && (source === autoType || source === autoArrayType))) { + return; + } + var inference = getInferenceInfoForType(target); + if (inference) { + if (!inference.isFixed) { + if (inference.priority === undefined || priority < inference.priority) { + inference.candidates = undefined; + inference.contraCandidates = undefined; + inference.priority = priority; + } + if (priority === inference.priority) { + var candidate = propagationType || source; + if (contravariant && !bivariant) { + inference.contraCandidates = ts.appendIfUnique(inference.contraCandidates, candidate); + } + else { + inference.candidates = ts.appendIfUnique(inference.candidates, candidate); + } + } + if (!(priority & 8) && target.flags & 262144 && !isTypeParameterAtTopLevel(originalTarget, target)) { + inference.topLevel = false; + } + } + return; + } + else { + var simplified = getSimplifiedType(target); + if (simplified !== target) { + inferFromTypesOnce(source, simplified); + } + else if (target.flags & 8388608) { + var indexType = getSimplifiedType(target.indexType); + if (indexType.flags & 63176704) { + var simplified_1 = distributeIndexOverObjectType(getSimplifiedType(target.objectType), indexType); + if (simplified_1 && simplified_1 !== target) { + inferFromTypesOnce(source, simplified_1); + } + } + } + } + } + if (ts.getObjectFlags(source) & 4 && ts.getObjectFlags(target) & 4 && source.target === target.target) { + var sourceTypes = source.typeArguments || ts.emptyArray; + var targetTypes = target.typeArguments || ts.emptyArray; + var count = sourceTypes.length < targetTypes.length ? sourceTypes.length : targetTypes.length; + var variances = getVariances(source.target); + for (var i = 0; i < count; i++) { + if (i < variances.length && variances[i] === 2) { + inferFromContravariantTypes(sourceTypes[i], targetTypes[i]); + } + else { + inferFromTypes(sourceTypes[i], targetTypes[i]); + } + } + } + else if (source.flags & 4194304 && target.flags & 4194304) { + contravariant = !contravariant; + inferFromTypes(source.type, target.type); + contravariant = !contravariant; + } + else if ((isLiteralType(source) || source.flags & 4) && target.flags & 4194304) { + var empty = createEmptyObjectTypeFromStringLiteral(source); + contravariant = !contravariant; + var savePriority = priority; + priority |= 16; + inferFromTypes(empty, target.type); + priority = savePriority; + contravariant = !contravariant; + } + else if (source.flags & 8388608 && target.flags & 8388608) { + inferFromTypes(source.objectType, target.objectType); + inferFromTypes(source.indexType, target.indexType); + } + else if (source.flags & 16777216 && target.flags & 16777216) { + inferFromTypes(source.checkType, target.checkType); + inferFromTypes(source.extendsType, target.extendsType); + inferFromTypes(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target)); + inferFromTypes(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target)); + } + else if (target.flags & 16777216) { + inferFromTypes(source, getUnionType([getTrueTypeFromConditionalType(target), getFalseTypeFromConditionalType(target)])); + } + else if (target.flags & 3145728) { + var targetTypes = target.types; + var typeVariableCount = 0; + var typeVariable = void 0; + for (var _d = 0, targetTypes_3 = targetTypes; _d < targetTypes_3.length; _d++) { + var t = targetTypes_3[_d]; + if (getInferenceInfoForType(t)) { + typeVariable = t; + typeVariableCount++; + } + else { + inferFromTypes(source, t); + } + } + if (typeVariableCount === 1) { + var savePriority = priority; + priority |= 1; + inferFromTypes(source, typeVariable); + priority = savePriority; + } + } + else if (source.flags & 1048576) { + var sourceTypes = source.types; + for (var _e = 0, sourceTypes_3 = sourceTypes; _e < sourceTypes_3.length; _e++) { + var sourceType = sourceTypes_3[_e]; + inferFromTypes(sourceType, target); + } + } + else { + if (!(priority & 32 && source.flags & (2097152 | 63176704))) { + var apparentSource = getApparentType(source); + if (apparentSource !== source && allowComplexConstraintInference && !(apparentSource.flags & (524288 | 2097152))) { + allowComplexConstraintInference = false; + return inferFromTypes(apparentSource, target); + } + source = apparentSource; + } + if (source.flags & (524288 | 2097152)) { + var key = source.id + "," + target.id; + if (visited && visited.get(key)) { + return; + } + (visited || (visited = ts.createMap())).set(key, true); + var isNonConstructorObject = target.flags & 524288 && + !(ts.getObjectFlags(target) & 16 && target.symbol && target.symbol.flags & 32); + var symbol = isNonConstructorObject ? target.symbol : undefined; + if (symbol) { + if (ts.contains(symbolStack, symbol)) { + return; + } + (symbolStack || (symbolStack = [])).push(symbol); + inferFromObjectTypes(source, target); + symbolStack.pop(); + } + else { + inferFromObjectTypes(source, target); + } + } + } + function inferFromTypesOnce(source, target) { + var key = source.id + "," + target.id; + if (!visited || !visited.get(key)) { + (visited || (visited = ts.createMap())).set(key, true); + inferFromTypes(source, target); + } + } + } + function inferFromContravariantTypes(source, target) { + if (strictFunctionTypes || priority & 64) { + contravariant = !contravariant; + inferFromTypes(source, target); + contravariant = !contravariant; + } + else { + inferFromTypes(source, target); + } + } + function getInferenceInfoForType(type) { + if (type.flags & 8650752) { + for (var _i = 0, inferences_1 = inferences; _i < inferences_1.length; _i++) { + var inference = inferences_1[_i]; + if (type === inference.typeParameter) { + return inference; + } + } + } + return undefined; + } + function inferFromMappedTypeConstraint(source, target, constraintType) { + if (constraintType.flags & 1048576) { + var result = false; + for (var _i = 0, _a = constraintType.types; _i < _a.length; _i++) { + var type = _a[_i]; + result = inferFromMappedTypeConstraint(source, target, type) || result; + } + return result; + } + if (constraintType.flags & 4194304) { + var inference = getInferenceInfoForType(constraintType.type); + if (inference && !inference.isFixed) { + var inferredType = inferTypeForHomomorphicMappedType(source, target, constraintType); + if (inferredType) { + var savePriority = priority; + priority |= 2; + inferFromTypes(inferredType, inference.typeParameter); + priority = savePriority; + } + } + return true; + } + if (constraintType.flags & 262144) { + var savePriority = priority; + priority |= 4; + inferFromTypes(getIndexType(source), constraintType); + priority = savePriority; + inferFromTypes(getUnionType(ts.map(getPropertiesOfType(source), getTypeOfSymbol)), getTemplateTypeFromMappedType(target)); + return true; + } + return false; + } + function inferFromObjectTypes(source, target) { + if (isGenericMappedType(source) && isGenericMappedType(target)) { + inferFromTypes(getConstraintTypeFromMappedType(source), getConstraintTypeFromMappedType(target)); + inferFromTypes(getTemplateTypeFromMappedType(source), getTemplateTypeFromMappedType(target)); + } + if (ts.getObjectFlags(target) & 32) { + var constraintType = getConstraintTypeFromMappedType(target); + if (inferFromMappedTypeConstraint(source, target, constraintType)) { + return; + } + } + if (!typesDefinitelyUnrelated(source, target)) { + inferFromProperties(source, target); + inferFromSignatures(source, target, 0); + inferFromSignatures(source, target, 1); + inferFromIndexTypes(source, target); + } + } + function inferFromProperties(source, target) { + if (isTupleType(source)) { + if (isTupleType(target)) { + var sourceLength = getLengthOfTupleType(source); + var targetLength = getLengthOfTupleType(target); + var sourceRestType = getRestTypeOfTupleType(source); + var targetRestType = getRestTypeOfTupleType(target); + var fixedLength = targetLength < sourceLength || sourceRestType ? targetLength : sourceLength; + for (var i = 0; i < fixedLength; i++) { + inferFromTypes(i < sourceLength ? source.typeArguments[i] : sourceRestType, target.typeArguments[i]); + } + if (targetRestType) { + var types = fixedLength < sourceLength ? source.typeArguments.slice(fixedLength, sourceLength) : []; + if (sourceRestType) { + types.push(sourceRestType); + } + if (types.length) { + inferFromTypes(getUnionType(types), targetRestType); + } + } + return; + } + if (isArrayType(target)) { + inferFromIndexTypes(source, target); + return; + } + } + var properties = getPropertiesOfObjectType(target); + for (var _i = 0, properties_5 = properties; _i < properties_5.length; _i++) { + var targetProp = properties_5[_i]; + var sourceProp = getPropertyOfType(source, targetProp.escapedName); + if (sourceProp) { + inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); + } + } + } + function inferFromSignatures(source, target, kind) { + var sourceSignatures = getSignaturesOfType(source, kind); + var targetSignatures = getSignaturesOfType(target, kind); + var sourceLen = sourceSignatures.length; + var targetLen = targetSignatures.length; + var len = sourceLen < targetLen ? sourceLen : targetLen; + var skipParameters = !!(source.flags & 536870912); + for (var i = 0; i < len; i++) { + inferFromSignature(getBaseSignature(sourceSignatures[sourceLen - len + i]), getBaseSignature(targetSignatures[targetLen - len + i]), skipParameters); + } + } + function inferFromSignature(source, target, skipParameters) { + if (!skipParameters) { + var saveBivariant = bivariant; + var kind = target.declaration ? target.declaration.kind : 0; + bivariant = bivariant || kind === 156 || kind === 155 || kind === 157; + forEachMatchingParameterType(source, target, inferFromContravariantTypes); + bivariant = saveBivariant; + } + var sourceTypePredicate = getTypePredicateOfSignature(source); + var targetTypePredicate = getTypePredicateOfSignature(target); + if (sourceTypePredicate && targetTypePredicate && sourceTypePredicate.kind === targetTypePredicate.kind) { + inferFromTypes(sourceTypePredicate.type, targetTypePredicate.type); + } + else { + inferFromTypes(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target)); + } + } + function inferFromIndexTypes(source, target) { + var targetStringIndexType = getIndexTypeOfType(target, 0); + if (targetStringIndexType) { + var sourceIndexType = getIndexTypeOfType(source, 0) || + getImplicitIndexTypeOfType(source, 0); + if (sourceIndexType) { + inferFromTypes(sourceIndexType, targetStringIndexType); + } + } + var targetNumberIndexType = getIndexTypeOfType(target, 1); + if (targetNumberIndexType) { + var sourceIndexType = getIndexTypeOfType(source, 1) || + getIndexTypeOfType(source, 0) || + getImplicitIndexTypeOfType(source, 1); + if (sourceIndexType) { + inferFromTypes(sourceIndexType, targetNumberIndexType); + } + } + } + } + function typeIdenticalToSomeType(type, types) { + for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { + var t = types_10[_i]; + if (isTypeIdenticalTo(t, type)) { + return true; + } + } + return false; + } + function removeTypesFromUnionOrIntersection(type, typesToRemove) { + var reducedTypes = []; + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (!typeIdenticalToSomeType(t, typesToRemove)) { + reducedTypes.push(t); + } + } + return type.flags & 1048576 ? getUnionType(reducedTypes) : getIntersectionType(reducedTypes); + } + function hasPrimitiveConstraint(type) { + var constraint = getConstraintOfTypeParameter(type); + return !!constraint && maybeTypeOfKind(constraint.flags & 16777216 ? getDefaultConstraintOfConditionalType(constraint) : constraint, 131068 | 4194304); + } + function isObjectLiteralType(type) { + return !!(ts.getObjectFlags(type) & 128); + } + function widenObjectLiteralCandidates(candidates) { + if (candidates.length > 1) { + var objectLiterals = ts.filter(candidates, isObjectLiteralType); + if (objectLiterals.length) { + var objectLiteralsType = getWidenedType(getUnionType(objectLiterals, 2)); + return ts.concatenate(ts.filter(candidates, function (t) { return !isObjectLiteralType(t); }), [objectLiteralsType]); + } + } + return candidates; + } + function getContravariantInference(inference) { + return inference.priority & 28 ? getIntersectionType(inference.contraCandidates) : getCommonSubtype(inference.contraCandidates); + } + function getCovariantInference(inference, signature) { + var candidates = widenObjectLiteralCandidates(inference.candidates); + var primitiveConstraint = hasPrimitiveConstraint(inference.typeParameter); + var widenLiteralTypes = !primitiveConstraint && inference.topLevel && + (inference.isFixed || !isTypeParameterAtTopLevel(getReturnTypeOfSignature(signature), inference.typeParameter)); + var baseCandidates = primitiveConstraint ? ts.sameMap(candidates, getRegularTypeOfLiteralType) : + widenLiteralTypes ? ts.sameMap(candidates, getWidenedLiteralType) : + candidates; + var unwidenedType = inference.priority & 28 ? + getUnionType(baseCandidates, 2) : + getCommonSupertype(baseCandidates); + return getWidenedType(unwidenedType); + } + function getInferredType(context, index) { + var inference = context.inferences[index]; + var inferredType = inference.inferredType; + if (!inferredType) { + var signature = context.signature; + if (signature) { + var inferredCovariantType = inference.candidates ? getCovariantInference(inference, signature) : undefined; + if (inference.contraCandidates) { + var inferredContravariantType = getContravariantInference(inference); + inferredType = inferredCovariantType && !(inferredCovariantType.flags & 131072) && + isTypeSubtypeOf(inferredCovariantType, inferredContravariantType) ? + inferredCovariantType : inferredContravariantType; + } + else if (inferredCovariantType) { + inferredType = inferredCovariantType; + } + else if (context.flags & 1) { + inferredType = silentNeverType; + } + else { + var defaultType = getDefaultFromTypeParameter(inference.typeParameter); + if (defaultType) { + inferredType = instantiateType(defaultType, combineTypeMappers(createBackreferenceMapper(context.signature.typeParameters, index), context)); + } + else { + inferredType = getDefaultTypeArgumentType(!!(context.flags & 2)); + } + } + } + else { + inferredType = getTypeFromInference(inference); + } + inference.inferredType = inferredType; + var constraint = getConstraintOfTypeParameter(inference.typeParameter); + if (constraint) { + var instantiatedConstraint = instantiateType(constraint, context); + if (!context.compareTypes(inferredType, getTypeWithThisArgument(instantiatedConstraint, inferredType))) { + inference.inferredType = inferredType = instantiatedConstraint; + } + } + } + return inferredType; + } + function getDefaultTypeArgumentType(isInJavaScriptFile) { + return isInJavaScriptFile ? anyType : emptyObjectType; + } + function getInferredTypes(context) { + var result = []; + for (var i = 0; i < context.inferences.length; i++) { + result.push(getInferredType(context, i)); + } + return result; + } + function getCannotFindNameDiagnosticForName(name) { + switch (name) { + case "document": + case "console": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom; + case "$": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_and_then_add_jquery_to_the_types_field_in_your_tsconfig; + case "describe": + case "suite": + case "it": + case "test": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha_and_then_add_jest_or_mocha_to_the_types_field_in_your_tsconfig; + case "process": + case "require": + case "Buffer": + case "module": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_and_then_add_node_to_the_types_field_in_your_tsconfig; + case "Map": + case "Set": + case "Promise": + case "Symbol": + case "WeakMap": + case "WeakSet": + case "Iterator": + case "AsyncIterator": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later; + default: return ts.Diagnostics.Cannot_find_name_0; + } + } + function getResolvedSymbol(node) { + var links = getNodeLinks(node); + if (!links.resolvedSymbol) { + links.resolvedSymbol = !ts.nodeIsMissing(node) && + resolveName(node, node.escapedText, 67220415 | 1048576, getCannotFindNameDiagnosticForName(node.escapedText), node, !ts.isWriteOnlyAccess(node), false, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1) || unknownSymbol; + } + return links.resolvedSymbol; + } + function isInTypeQuery(node) { + return !!ts.findAncestor(node, function (n) { return n.kind === 167 ? true : n.kind === 72 || n.kind === 148 ? false : "quit"; }); + } + function getFlowCacheKey(node) { + if (node.kind === 72) { + var symbol = getResolvedSymbol(node); + return symbol !== unknownSymbol ? (isConstraintPosition(node) ? "@" : "") + getSymbolId(symbol) : undefined; + } + if (node.kind === 100) { + return "0"; + } + if (node.kind === 189) { + var key = getFlowCacheKey(node.expression); + return key && key + "." + ts.idText(node.name); + } + if (node.kind === 186) { + var container = node.parent.parent; + var key = container.kind === 186 ? getFlowCacheKey(container) : (container.initializer && getFlowCacheKey(container.initializer)); + var text = getBindingElementNameText(node); + var result = key && text && (key + "." + text); + return result; + } + return undefined; + } + function getBindingElementNameText(element) { + var parent = element.parent; + if (parent.kind === 184) { + var name = element.propertyName || element.name; + switch (name.kind) { + case 72: + return ts.idText(name); + case 149: + return ts.isStringOrNumericLiteralLike(name.expression) ? name.expression.text : undefined; + case 10: + case 8: + return name.text; + default: + ts.Debug.fail("Unexpected name kind for binding element name"); + } + } + else { + return "" + parent.elements.indexOf(element); + } + } + function isMatchingReference(source, target) { + switch (source.kind) { + case 72: + return target.kind === 72 && getResolvedSymbol(source) === getResolvedSymbol(target) || + (target.kind === 237 || target.kind === 186) && + getExportSymbolOfValueSymbolIfExported(getResolvedSymbol(source)) === getSymbolOfNode(target); + case 100: + return target.kind === 100; + case 98: + return target.kind === 98; + case 189: + case 190: + return (ts.isPropertyAccessExpression(target) || ts.isElementAccessExpression(target)) && + getAccessedPropertyName(source) === getAccessedPropertyName(target) && + isMatchingReference(source.expression, target.expression); + case 186: + if (target.kind !== 189) + return false; + var t = target; + if (t.name.escapedText !== getBindingElementNameText(source)) + return false; + if (source.parent.parent.kind === 186 && isMatchingReference(source.parent.parent, t.expression)) { + return true; + } + if (source.parent.parent.kind === 237) { + var maybeId = source.parent.parent.initializer; + return !!maybeId && isMatchingReference(maybeId, t.expression); + } + } + return false; + } + function getAccessedPropertyName(access) { + return ts.isPropertyAccessExpression(access) ? access.name.escapedText : + ts.isStringLiteral(access.argumentExpression) || ts.isNumericLiteral(access.argumentExpression) ? ts.escapeLeadingUnderscores(access.argumentExpression.text) : + undefined; + } + function containsMatchingReference(source, target) { + while (source.kind === 189) { + source = source.expression; + if (isMatchingReference(source, target)) { + return true; + } + } + return false; + } + function containsMatchingReferenceDiscriminant(source, target) { + return target.kind === 189 && + containsMatchingReference(source, target.expression) && + isDiscriminantProperty(getDeclaredTypeOfReference(target.expression), target.name.escapedText); + } + function getDeclaredTypeOfReference(expr) { + if (expr.kind === 72) { + return getTypeOfSymbol(getResolvedSymbol(expr)); + } + if (expr.kind === 189) { + var type = getDeclaredTypeOfReference(expr.expression); + return type && getTypeOfPropertyOfType(type, expr.name.escapedText); + } + return undefined; + } + function isDiscriminantType(type) { + if (type.flags & 1048576) { + if (type.flags & (16 | 1024)) { + return true; + } + var combined = 0; + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var t = _a[_i]; + combined |= t.flags; + } + if (combined & 109440 && !(combined & 63176704)) { + return true; + } + } + return false; + } + function isDiscriminantProperty(type, name) { + if (type && type.flags & 1048576) { + var prop = getUnionOrIntersectionProperty(type, name); + if (prop && ts.getCheckFlags(prop) & 2) { + if (prop.isDiscriminantProperty === undefined) { + prop.isDiscriminantProperty = !!(prop.checkFlags & 32) && isDiscriminantType(getTypeOfSymbol(prop)); + } + return !!prop.isDiscriminantProperty; + } + } + return false; + } + function hasNarrowableDeclaredType(expr) { + var type = getDeclaredTypeOfReference(expr); + return !!(type && type.flags & 1048576); + } + function findDiscriminantProperties(sourceProperties, target) { + var result; + for (var _i = 0, sourceProperties_2 = sourceProperties; _i < sourceProperties_2.length; _i++) { + var sourceProperty = sourceProperties_2[_i]; + if (isDiscriminantProperty(target, sourceProperty.escapedName)) { + if (result) { + result.push(sourceProperty); + continue; + } + result = [sourceProperty]; + } + } + return result; + } + function isOrContainsMatchingReference(source, target) { + return isMatchingReference(source, target) || containsMatchingReference(source, target); + } + function hasMatchingArgument(callExpression, reference) { + if (callExpression.arguments) { + for (var _i = 0, _a = callExpression.arguments; _i < _a.length; _i++) { + var argument = _a[_i]; + if (isOrContainsMatchingReference(reference, argument)) { + return true; + } + } + } + if (callExpression.expression.kind === 189 && + isOrContainsMatchingReference(reference, callExpression.expression.expression)) { + return true; + } + return false; + } + function getFlowNodeId(flow) { + if (!flow.id) { + flow.id = nextFlowId; + nextFlowId++; + } + return flow.id; + } + function typeMaybeAssignableTo(source, target) { + if (!(source.flags & 1048576)) { + return isTypeAssignableTo(source, target); + } + for (var _i = 0, _a = source.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (isTypeAssignableTo(t, target)) { + return true; + } + } + return false; + } + function getAssignmentReducedType(declaredType, assignedType) { + if (declaredType !== assignedType) { + if (assignedType.flags & 131072) { + return assignedType; + } + var reducedType = filterType(declaredType, function (t) { return typeMaybeAssignableTo(assignedType, t); }); + if (assignedType.flags & 512 && isFreshLiteralType(assignedType)) { + reducedType = mapType(reducedType, getFreshTypeOfLiteralType); + } + if (isTypeAssignableTo(assignedType, reducedType)) { + return reducedType; + } + } + return declaredType; + } + function getTypeFactsOfTypes(types) { + var result = 0; + for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { + var t = types_11[_i]; + result |= getTypeFacts(t); + } + return result; + } + function isFunctionObjectType(type) { + var resolved = resolveStructuredTypeMembers(type); + return !!(resolved.callSignatures.length || resolved.constructSignatures.length || + resolved.members.get("bind") && isTypeSubtypeOf(type, globalFunctionType)); + } + function getTypeFacts(type) { + var flags = type.flags; + if (flags & 4) { + return strictNullChecks ? 16317953 : 16776705; + } + if (flags & 128) { + var isEmpty = type.value === ""; + return strictNullChecks ? + isEmpty ? 12123649 : 7929345 : + isEmpty ? 12582401 : 16776705; + } + if (flags & (8 | 32)) { + return strictNullChecks ? 16317698 : 16776450; + } + if (flags & 256) { + var isZero = type.value === 0; + return strictNullChecks ? + isZero ? 12123394 : 7929090 : + isZero ? 12582146 : 16776450; + } + if (flags & 64) { + return strictNullChecks ? 16317188 : 16775940; + } + if (flags & 2048) { + var isZero = isZeroBigInt(type); + return strictNullChecks ? + isZero ? 12122884 : 7928580 : + isZero ? 12581636 : 16775940; + } + if (flags & 16) { + return strictNullChecks ? 16316168 : 16774920; + } + if (flags & 528) { + return strictNullChecks ? + (type === falseType || type === regularFalseType) ? 12121864 : 7927560 : + (type === falseType || type === regularFalseType) ? 12580616 : 16774920; + } + if (flags & 524288) { + return ts.getObjectFlags(type) & 16 && isEmptyObjectType(type) ? + strictNullChecks ? 16318463 : 16777215 : + isFunctionObjectType(type) ? + strictNullChecks ? 7880640 : 16728000 : + strictNullChecks ? 7888800 : 16736160; + } + if (flags & (16384 | 32768)) { + return 9830144; + } + if (flags & 65536) { + return 9363232; + } + if (flags & 12288) { + return strictNullChecks ? 7925520 : 16772880; + } + if (flags & 67108864) { + return strictNullChecks ? 7888800 : 16736160; + } + if (flags & 63176704) { + return getTypeFacts(getBaseConstraintOfType(type) || emptyObjectType); + } + if (flags & 3145728) { + return getTypeFactsOfTypes(type.types); + } + return 16777215; + } + function getTypeWithFacts(type, include) { + return filterType(type, function (t) { return (getTypeFacts(t) & include) !== 0; }); + } + function getTypeWithDefault(type, defaultExpression) { + if (defaultExpression) { + var defaultType = getTypeOfExpression(defaultExpression); + return getUnionType([getTypeWithFacts(type, 524288), defaultType]); + } + return type; + } + function getTypeOfDestructuredProperty(type, name) { + var text = ts.getTextOfPropertyName(name); + return getConstraintForLocation(getTypeOfPropertyOfType(type, text), name) || + isNumericLiteralName(text) && getIndexTypeOfType(type, 1) || + getIndexTypeOfType(type, 0) || + errorType; + } + function getTypeOfDestructuredArrayElement(type, index) { + return everyType(type, isTupleLikeType) && getTupleElementType(type, index) || + checkIteratedTypeOrElementType(type, undefined, false, false) || + errorType; + } + function getTypeOfDestructuredSpreadExpression(type) { + return createArrayType(checkIteratedTypeOrElementType(type, undefined, false, false) || errorType); + } + function getAssignedTypeOfBinaryExpression(node) { + var isDestructuringDefaultAssignment = node.parent.kind === 187 && isDestructuringAssignmentTarget(node.parent) || + node.parent.kind === 275 && isDestructuringAssignmentTarget(node.parent.parent); + return isDestructuringDefaultAssignment ? + getTypeWithDefault(getAssignedType(node), node.right) : + getTypeOfExpression(node.right); + } + function isDestructuringAssignmentTarget(parent) { + return parent.parent.kind === 204 && parent.parent.left === parent || + parent.parent.kind === 227 && parent.parent.initializer === parent; + } + function getAssignedTypeOfArrayLiteralElement(node, element) { + return getTypeOfDestructuredArrayElement(getAssignedType(node), node.elements.indexOf(element)); + } + function getAssignedTypeOfSpreadExpression(node) { + return getTypeOfDestructuredSpreadExpression(getAssignedType(node.parent)); + } + function getAssignedTypeOfPropertyAssignment(node) { + return getTypeOfDestructuredProperty(getAssignedType(node.parent), node.name); + } + function getAssignedTypeOfShorthandPropertyAssignment(node) { + return getTypeWithDefault(getAssignedTypeOfPropertyAssignment(node), node.objectAssignmentInitializer); + } + function getAssignedType(node) { + var parent = node.parent; + switch (parent.kind) { + case 226: + return stringType; + case 227: + return checkRightHandSideOfForOf(parent.expression, parent.awaitModifier) || errorType; + case 204: + return getAssignedTypeOfBinaryExpression(parent); + case 198: + return undefinedType; + case 187: + return getAssignedTypeOfArrayLiteralElement(parent, node); + case 208: + return getAssignedTypeOfSpreadExpression(parent); + case 275: + return getAssignedTypeOfPropertyAssignment(parent); + case 276: + return getAssignedTypeOfShorthandPropertyAssignment(parent); + } + return errorType; + } + function getInitialTypeOfBindingElement(node) { + var pattern = node.parent; + var parentType = getInitialType(pattern.parent); + var type = pattern.kind === 184 ? + getTypeOfDestructuredProperty(parentType, node.propertyName || node.name) : + !node.dotDotDotToken ? + getTypeOfDestructuredArrayElement(parentType, pattern.elements.indexOf(node)) : + getTypeOfDestructuredSpreadExpression(parentType); + return getTypeWithDefault(type, node.initializer); + } + function getTypeOfInitializer(node) { + var links = getNodeLinks(node); + return links.resolvedType || getTypeOfExpression(node); + } + function getInitialTypeOfVariableDeclaration(node) { + if (node.initializer) { + return getTypeOfInitializer(node.initializer); + } + if (node.parent.parent.kind === 226) { + return stringType; + } + if (node.parent.parent.kind === 227) { + return checkRightHandSideOfForOf(node.parent.parent.expression, node.parent.parent.awaitModifier) || errorType; + } + return errorType; + } + function getInitialType(node) { + return node.kind === 237 ? + getInitialTypeOfVariableDeclaration(node) : + getInitialTypeOfBindingElement(node); + } + function getInitialOrAssignedType(node, reference) { + return getConstraintForLocation(node.kind === 237 || node.kind === 186 ? + getInitialType(node) : + getAssignedType(node), reference); + } + function isEmptyArrayAssignment(node) { + return node.kind === 237 && node.initializer && + isEmptyArrayLiteral(node.initializer) || + node.kind !== 186 && node.parent.kind === 204 && + isEmptyArrayLiteral(node.parent.right); + } + function getReferenceCandidate(node) { + switch (node.kind) { + case 195: + return getReferenceCandidate(node.expression); + case 204: + switch (node.operatorToken.kind) { + case 59: + return getReferenceCandidate(node.left); + case 27: + return getReferenceCandidate(node.right); + } + } + return node; + } + function getReferenceRoot(node) { + var parent = node.parent; + return parent.kind === 195 || + parent.kind === 204 && parent.operatorToken.kind === 59 && parent.left === node || + parent.kind === 204 && parent.operatorToken.kind === 27 && parent.right === node ? + getReferenceRoot(parent) : node; + } + function getTypeOfSwitchClause(clause) { + if (clause.kind === 271) { + return getRegularTypeOfLiteralType(getTypeOfExpression(clause.expression)); + } + return neverType; + } + function getSwitchClauseTypes(switchStatement) { + var links = getNodeLinks(switchStatement); + if (!links.switchTypes) { + links.switchTypes = []; + for (var _i = 0, _a = switchStatement.caseBlock.clauses; _i < _a.length; _i++) { + var clause = _a[_i]; + links.switchTypes.push(getTypeOfSwitchClause(clause)); + } + } + return links.switchTypes; + } + function getSwitchClauseTypeOfWitnesses(switchStatement) { + var witnesses = []; + for (var _i = 0, _a = switchStatement.caseBlock.clauses; _i < _a.length; _i++) { + var clause = _a[_i]; + if (clause.kind === 271) { + if (clause.expression.kind === 10) { + witnesses.push(clause.expression.text); + continue; + } + return ts.emptyArray; + } + witnesses.push(undefined); + } + return witnesses; + } + function eachTypeContainedIn(source, types) { + return source.flags & 1048576 ? !ts.forEach(source.types, function (t) { return !ts.contains(types, t); }) : ts.contains(types, source); + } + function isTypeSubsetOf(source, target) { + return source === target || target.flags & 1048576 && isTypeSubsetOfUnion(source, target); + } + function isTypeSubsetOfUnion(source, target) { + if (source.flags & 1048576) { + for (var _i = 0, _a = source.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (!containsType(target.types, t)) { + return false; + } + } + return true; + } + if (source.flags & 1024 && getBaseTypeOfEnumLiteralType(source) === target) { + return true; + } + return containsType(target.types, source); + } + function forEachType(type, f) { + return type.flags & 1048576 ? ts.forEach(type.types, f) : f(type); + } + function everyType(type, f) { + return type.flags & 1048576 ? ts.every(type.types, f) : f(type); + } + function filterType(type, f) { + if (type.flags & 1048576) { + var types = type.types; + var filtered = ts.filter(types, f); + return filtered === types ? type : getUnionTypeFromSortedList(filtered, type.primitiveTypesOnly); + } + return f(type) ? type : neverType; + } + function mapType(type, mapper, noReductions) { + if (type.flags & 131072) { + return type; + } + if (!(type.flags & 1048576)) { + return mapper(type); + } + var types = type.types; + var mappedType; + var mappedTypes; + for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { + var current = types_12[_i]; + var t = mapper(current); + if (t) { + if (!mappedType) { + mappedType = t; + } + else if (!mappedTypes) { + mappedTypes = [mappedType, t]; + } + else { + mappedTypes.push(t); + } + } + } + return mappedTypes ? getUnionType(mappedTypes, noReductions ? 0 : 1) : mappedType; + } + function extractTypesOfKind(type, kind) { + return filterType(type, function (t) { return (t.flags & kind) !== 0; }); + } + function replacePrimitivesWithLiterals(typeWithPrimitives, typeWithLiterals) { + if (isTypeSubsetOf(stringType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 128) || + isTypeSubsetOf(numberType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 256) || + isTypeSubsetOf(bigintType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 2048)) { + return mapType(typeWithPrimitives, function (t) { + return t.flags & 4 ? extractTypesOfKind(typeWithLiterals, 4 | 128) : + t.flags & 8 ? extractTypesOfKind(typeWithLiterals, 8 | 256) : + t.flags & 64 ? extractTypesOfKind(typeWithLiterals, 64 | 2048) : + t; + }); + } + return typeWithPrimitives; + } + function isIncomplete(flowType) { + return flowType.flags === 0; + } + function getTypeFromFlowType(flowType) { + return flowType.flags === 0 ? flowType.type : flowType; + } + function createFlowType(type, incomplete) { + return incomplete ? { flags: 0, type: type } : type; + } + function createEvolvingArrayType(elementType) { + var result = createObjectType(256); + result.elementType = elementType; + return result; + } + function getEvolvingArrayType(elementType) { + return evolvingArrayTypes[elementType.id] || (evolvingArrayTypes[elementType.id] = createEvolvingArrayType(elementType)); + } + function addEvolvingArrayElementType(evolvingArrayType, node) { + var elementType = getBaseTypeOfLiteralType(getContextFreeTypeOfExpression(node)); + return isTypeSubsetOf(elementType, evolvingArrayType.elementType) ? evolvingArrayType : getEvolvingArrayType(getUnionType([evolvingArrayType.elementType, elementType])); + } + function createFinalArrayType(elementType) { + return elementType.flags & 131072 ? + autoArrayType : + createArrayType(elementType.flags & 1048576 ? + getUnionType(elementType.types, 2) : + elementType); + } + function getFinalArrayType(evolvingArrayType) { + return evolvingArrayType.finalArrayType || (evolvingArrayType.finalArrayType = createFinalArrayType(evolvingArrayType.elementType)); + } + function finalizeEvolvingArrayType(type) { + return ts.getObjectFlags(type) & 256 ? getFinalArrayType(type) : type; + } + function getElementTypeOfEvolvingArrayType(type) { + return ts.getObjectFlags(type) & 256 ? type.elementType : neverType; + } + function isEvolvingArrayTypeList(types) { + var hasEvolvingArrayType = false; + for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { + var t = types_13[_i]; + if (!(t.flags & 131072)) { + if (!(ts.getObjectFlags(t) & 256)) { + return false; + } + hasEvolvingArrayType = true; + } + } + return hasEvolvingArrayType; + } + function getUnionOrEvolvingArrayType(types, subtypeReduction) { + return isEvolvingArrayTypeList(types) ? + getEvolvingArrayType(getUnionType(ts.map(types, getElementTypeOfEvolvingArrayType))) : + getUnionType(ts.sameMap(types, finalizeEvolvingArrayType), subtypeReduction); + } + function isEvolvingArrayOperationTarget(node) { + var root = getReferenceRoot(node); + var parent = root.parent; + var isLengthPushOrUnshift = parent.kind === 189 && (parent.name.escapedText === "length" || + parent.parent.kind === 191 && ts.isPushOrUnshiftIdentifier(parent.name)); + var isElementAssignment = parent.kind === 190 && + parent.expression === root && + parent.parent.kind === 204 && + parent.parent.operatorToken.kind === 59 && + parent.parent.left === parent && + !ts.isAssignmentTarget(parent.parent) && + isTypeAssignableToKind(getTypeOfExpression(parent.argumentExpression), 296); + return isLengthPushOrUnshift || isElementAssignment; + } + function maybeTypePredicateCall(node) { + var links = getNodeLinks(node); + if (links.maybeTypePredicate === undefined) { + links.maybeTypePredicate = getMaybeTypePredicate(node); + } + return links.maybeTypePredicate; + } + function getMaybeTypePredicate(node) { + if (node.expression.kind !== 98) { + var funcType = checkNonNullExpression(node.expression); + if (funcType !== silentNeverType) { + var apparentType = getApparentType(funcType); + return apparentType !== errorType && ts.some(getSignaturesOfType(apparentType, 0), signatureHasTypePredicate); + } + } + return false; + } + function reportFlowControlError(node) { + var block = ts.findAncestor(node, ts.isFunctionOrModuleBlock); + var sourceFile = ts.getSourceFileOfNode(node); + var span = ts.getSpanOfTokenAtPosition(sourceFile, block.statements.pos); + diagnostics.add(ts.createFileDiagnostic(sourceFile, span.start, span.length, ts.Diagnostics.The_containing_function_or_module_body_is_too_large_for_control_flow_analysis)); + } + function getFlowTypeOfReference(reference, declaredType, initialType, flowContainer, couldBeUninitialized) { + if (initialType === void 0) { initialType = declaredType; } + var key; + var flowDepth = 0; + if (flowAnalysisDisabled) { + return errorType; + } + if (!reference.flowNode || !couldBeUninitialized && !(declaredType.flags & 133970943)) { + return declaredType; + } + var sharedFlowStart = sharedFlowCount; + var evolvedType = getTypeFromFlowType(getTypeAtFlowNode(reference.flowNode)); + sharedFlowCount = sharedFlowStart; + var resultType = ts.getObjectFlags(evolvedType) & 256 && isEvolvingArrayOperationTarget(reference) ? autoArrayType : finalizeEvolvingArrayType(evolvedType); + if (reference.parent && reference.parent.kind === 213 && getTypeWithFacts(resultType, 2097152).flags & 131072) { + return declaredType; + } + return resultType; + function getTypeAtFlowNode(flow) { + if (flowDepth === 2000) { + flowAnalysisDisabled = true; + reportFlowControlError(reference); + return errorType; + } + flowDepth++; + while (true) { + var flags = flow.flags; + if (flags & 1024) { + for (var i = sharedFlowStart; i < sharedFlowCount; i++) { + if (sharedFlowNodes[i] === flow) { + flowDepth--; + return sharedFlowTypes[i]; + } + } + } + var type = void 0; + if (flags & 4096) { + flow.locked = true; + type = getTypeAtFlowNode(flow.antecedent); + flow.locked = false; + } + else if (flags & 2048) { + flow = flow.antecedent; + continue; + } + else if (flags & 16) { + type = getTypeAtFlowAssignment(flow); + if (!type) { + flow = flow.antecedent; + continue; + } + } + else if (flags & 96) { + type = getTypeAtFlowCondition(flow); + } + else if (flags & 128) { + type = getTypeAtSwitchClause(flow); + } + else if (flags & 12) { + if (flow.antecedents.length === 1) { + flow = flow.antecedents[0]; + continue; + } + type = flags & 4 ? + getTypeAtFlowBranchLabel(flow) : + getTypeAtFlowLoopLabel(flow); + } + else if (flags & 256) { + type = getTypeAtFlowArrayMutation(flow); + if (!type) { + flow = flow.antecedent; + continue; + } + } + else if (flags & 2) { + var container = flow.container; + if (container && container !== flowContainer && + reference.kind !== 189 && + reference.kind !== 190 && + reference.kind !== 100) { + flow = container.flowNode; + continue; + } + type = initialType; + } + else { + type = convertAutoToAny(declaredType); + } + if (flags & 1024) { + sharedFlowNodes[sharedFlowCount] = flow; + sharedFlowTypes[sharedFlowCount] = type; + sharedFlowCount++; + } + flowDepth--; + return type; + } + } + function getTypeAtFlowAssignment(flow) { + var node = flow.node; + if (isMatchingReference(reference, node)) { + if (ts.getAssignmentTargetKind(node) === 2) { + var flowType = getTypeAtFlowNode(flow.antecedent); + return createFlowType(getBaseTypeOfLiteralType(getTypeFromFlowType(flowType)), isIncomplete(flowType)); + } + if (declaredType === autoType || declaredType === autoArrayType) { + if (isEmptyArrayAssignment(node)) { + return getEvolvingArrayType(neverType); + } + var assignedType = getBaseTypeOfLiteralType(getInitialOrAssignedType(node, reference)); + return isTypeAssignableTo(assignedType, declaredType) ? assignedType : anyArrayType; + } + if (declaredType.flags & 1048576) { + return getAssignmentReducedType(declaredType, getInitialOrAssignedType(node, reference)); + } + return declaredType; + } + if (containsMatchingReference(reference, node)) { + if (ts.isVariableDeclaration(node) && (ts.isInJSFile(node) || ts.isVarConst(node))) { + var init = ts.getDeclaredExpandoInitializer(node); + if (init && (init.kind === 196 || init.kind === 197)) { + return getTypeAtFlowNode(flow.antecedent); + } + } + return declaredType; + } + if (ts.isVariableDeclaration(node) && node.parent.parent.kind === 226 && isMatchingReference(reference, node.parent.parent.expression)) { + return getNonNullableTypeIfNeeded(getTypeFromFlowType(getTypeAtFlowNode(flow.antecedent))); + } + return undefined; + } + function getTypeAtFlowArrayMutation(flow) { + if (declaredType === autoType || declaredType === autoArrayType) { + var node = flow.node; + var expr = node.kind === 191 ? + node.expression.expression : + node.left.expression; + if (isMatchingReference(reference, getReferenceCandidate(expr))) { + var flowType = getTypeAtFlowNode(flow.antecedent); + var type = getTypeFromFlowType(flowType); + if (ts.getObjectFlags(type) & 256) { + var evolvedType_1 = type; + if (node.kind === 191) { + for (var _i = 0, _a = node.arguments; _i < _a.length; _i++) { + var arg = _a[_i]; + evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, arg); + } + } + else { + var indexType = getContextFreeTypeOfExpression(node.left.argumentExpression); + if (isTypeAssignableToKind(indexType, 296)) { + evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, node.right); + } + } + return evolvedType_1 === type ? flowType : createFlowType(evolvedType_1, isIncomplete(flowType)); + } + return flowType; + } + } + return undefined; + } + function getTypeAtFlowCondition(flow) { + var flowType = getTypeAtFlowNode(flow.antecedent); + var type = getTypeFromFlowType(flowType); + if (type.flags & 131072) { + return flowType; + } + var assumeTrue = (flow.flags & 32) !== 0; + var nonEvolvingType = finalizeEvolvingArrayType(type); + var narrowedType = narrowType(nonEvolvingType, flow.expression, assumeTrue); + if (narrowedType === nonEvolvingType) { + return flowType; + } + var incomplete = isIncomplete(flowType); + var resultType = incomplete && narrowedType.flags & 131072 ? silentNeverType : narrowedType; + return createFlowType(resultType, incomplete); + } + function getTypeAtSwitchClause(flow) { + var expr = flow.switchStatement.expression; + if (containsMatchingReferenceDiscriminant(reference, expr)) { + return declaredType; + } + var flowType = getTypeAtFlowNode(flow.antecedent); + var type = getTypeFromFlowType(flowType); + if (isMatchingReference(reference, expr)) { + type = narrowTypeBySwitchOnDiscriminant(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); + } + else if (isMatchingReferenceDiscriminant(expr, type)) { + type = narrowTypeByDiscriminant(type, expr, function (t) { return narrowTypeBySwitchOnDiscriminant(t, flow.switchStatement, flow.clauseStart, flow.clauseEnd); }); + } + else if (expr.kind === 199 && isMatchingReference(reference, expr.expression)) { + type = narrowBySwitchOnTypeOf(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); + } + return createFlowType(type, isIncomplete(flowType)); + } + function getTypeAtFlowBranchLabel(flow) { + var antecedentTypes = []; + var subtypeReduction = false; + var seenIncomplete = false; + for (var _i = 0, _a = flow.antecedents; _i < _a.length; _i++) { + var antecedent = _a[_i]; + if (antecedent.flags & 2048 && antecedent.lock.locked) { + continue; + } + var flowType = getTypeAtFlowNode(antecedent); + var type = getTypeFromFlowType(flowType); + if (type === declaredType && declaredType === initialType) { + return type; + } + ts.pushIfUnique(antecedentTypes, type); + if (!isTypeSubsetOf(type, declaredType)) { + subtypeReduction = true; + } + if (isIncomplete(flowType)) { + seenIncomplete = true; + } + } + return createFlowType(getUnionOrEvolvingArrayType(antecedentTypes, subtypeReduction ? 2 : 1), seenIncomplete); + } + function getTypeAtFlowLoopLabel(flow) { + var id = getFlowNodeId(flow); + var cache = flowLoopCaches[id] || (flowLoopCaches[id] = ts.createMap()); + if (!key) { + key = getFlowCacheKey(reference); + if (!key) { + return declaredType; + } + } + var cached = cache.get(key); + if (cached) { + return cached; + } + for (var i = flowLoopStart; i < flowLoopCount; i++) { + if (flowLoopNodes[i] === flow && flowLoopKeys[i] === key && flowLoopTypes[i].length) { + return createFlowType(getUnionOrEvolvingArrayType(flowLoopTypes[i], 1), true); + } + } + var antecedentTypes = []; + var subtypeReduction = false; + var firstAntecedentType; + flowLoopNodes[flowLoopCount] = flow; + flowLoopKeys[flowLoopCount] = key; + flowLoopTypes[flowLoopCount] = antecedentTypes; + for (var _i = 0, _a = flow.antecedents; _i < _a.length; _i++) { + var antecedent = _a[_i]; + flowLoopCount++; + var flowType = getTypeAtFlowNode(antecedent); + flowLoopCount--; + if (!firstAntecedentType) { + firstAntecedentType = flowType; + } + var type = getTypeFromFlowType(flowType); + var cached_1 = cache.get(key); + if (cached_1) { + return cached_1; + } + ts.pushIfUnique(antecedentTypes, type); + if (!isTypeSubsetOf(type, declaredType)) { + subtypeReduction = true; + } + if (type === declaredType) { + break; + } + } + var result = getUnionOrEvolvingArrayType(antecedentTypes, subtypeReduction ? 2 : 1); + if (isIncomplete(firstAntecedentType)) { + return createFlowType(result, true); + } + cache.set(key, result); + return result; + } + function isMatchingReferenceDiscriminant(expr, computedType) { + if (!(computedType.flags & 1048576) || + expr.kind !== 189 && expr.kind !== 190) { + return false; + } + var access = expr; + var name = getAccessedPropertyName(access); + if (!name) { + return false; + } + return isMatchingReference(reference, access.expression) && isDiscriminantProperty(computedType, name); + } + function narrowTypeByDiscriminant(type, access, narrowType) { + var propName = getAccessedPropertyName(access); + if (!propName) { + return type; + } + var propType = getTypeOfPropertyOfType(type, propName); + var narrowedPropType = propType && narrowType(propType); + return propType === narrowedPropType ? type : filterType(type, function (t) { return isTypeComparableTo(getTypeOfPropertyOfType(t, propName), narrowedPropType); }); + } + function narrowTypeByTruthiness(type, expr, assumeTrue) { + if (isMatchingReference(reference, expr)) { + return getTypeWithFacts(type, assumeTrue ? 4194304 : 8388608); + } + if (isMatchingReferenceDiscriminant(expr, declaredType)) { + return narrowTypeByDiscriminant(type, expr, function (t) { return getTypeWithFacts(t, assumeTrue ? 4194304 : 8388608); }); + } + if (containsMatchingReferenceDiscriminant(reference, expr)) { + return declaredType; + } + return type; + } + function isTypePresencePossible(type, propName, assumeTrue) { + if (getIndexInfoOfType(type, 0)) { + return true; + } + var prop = getPropertyOfType(type, propName); + if (prop) { + return prop.flags & 16777216 ? true : assumeTrue; + } + return !assumeTrue; + } + function narrowByInKeyword(type, literal, assumeTrue) { + if ((type.flags & (1048576 | 524288)) || (type.flags & 262144 && type.isThisType)) { + var propName_1 = ts.escapeLeadingUnderscores(literal.text); + return filterType(type, function (t) { return isTypePresencePossible(t, propName_1, assumeTrue); }); + } + return type; + } + function narrowTypeByBinaryExpression(type, expr, assumeTrue) { + switch (expr.operatorToken.kind) { + case 59: + return narrowTypeByTruthiness(type, expr.left, assumeTrue); + case 33: + case 34: + case 35: + case 36: + var operator_1 = expr.operatorToken.kind; + var left_1 = getReferenceCandidate(expr.left); + var right_1 = getReferenceCandidate(expr.right); + if (left_1.kind === 199 && ts.isStringLiteralLike(right_1)) { + return narrowTypeByTypeof(type, left_1, operator_1, right_1, assumeTrue); + } + if (right_1.kind === 199 && ts.isStringLiteralLike(left_1)) { + return narrowTypeByTypeof(type, right_1, operator_1, left_1, assumeTrue); + } + if (isMatchingReference(reference, left_1)) { + return narrowTypeByEquality(type, operator_1, right_1, assumeTrue); + } + if (isMatchingReference(reference, right_1)) { + return narrowTypeByEquality(type, operator_1, left_1, assumeTrue); + } + if (isMatchingReferenceDiscriminant(left_1, declaredType)) { + return narrowTypeByDiscriminant(type, left_1, function (t) { return narrowTypeByEquality(t, operator_1, right_1, assumeTrue); }); + } + if (isMatchingReferenceDiscriminant(right_1, declaredType)) { + return narrowTypeByDiscriminant(type, right_1, function (t) { return narrowTypeByEquality(t, operator_1, left_1, assumeTrue); }); + } + if (containsMatchingReferenceDiscriminant(reference, left_1) || containsMatchingReferenceDiscriminant(reference, right_1)) { + return declaredType; + } + break; + case 94: + return narrowTypeByInstanceof(type, expr, assumeTrue); + case 93: + var target = getReferenceCandidate(expr.right); + if (ts.isStringLiteralLike(expr.left) && isMatchingReference(reference, target)) { + return narrowByInKeyword(type, expr.left, assumeTrue); + } + break; + case 27: + return narrowType(type, expr.right, assumeTrue); + } + return type; + } + function narrowTypeByEquality(type, operator, value, assumeTrue) { + if (type.flags & 1) { + return type; + } + if (operator === 34 || operator === 36) { + assumeTrue = !assumeTrue; + } + var valueType = getTypeOfExpression(value); + if (valueType.flags & 98304) { + if (!strictNullChecks) { + return type; + } + var doubleEquals = operator === 33 || operator === 34; + var facts = doubleEquals ? + assumeTrue ? 262144 : 2097152 : + valueType.flags & 65536 ? + assumeTrue ? 131072 : 1048576 : + assumeTrue ? 65536 : 524288; + return getTypeWithFacts(type, facts); + } + if (type.flags & 67637251) { + return type; + } + if (assumeTrue) { + var narrowedType = filterType(type, function (t) { return areTypesComparable(t, valueType); }); + return narrowedType.flags & 131072 ? type : replacePrimitivesWithLiterals(narrowedType, valueType); + } + if (isUnitType(valueType)) { + var regularType_1 = getRegularTypeOfLiteralType(valueType); + return filterType(type, function (t) { return getRegularTypeOfLiteralType(t) !== regularType_1; }); + } + return type; + } + function narrowTypeByTypeof(type, typeOfExpr, operator, literal, assumeTrue) { + var target = getReferenceCandidate(typeOfExpr.expression); + if (!isMatchingReference(reference, target)) { + if (containsMatchingReference(reference, target) && hasNarrowableDeclaredType(target)) { + return declaredType; + } + return type; + } + if (operator === 34 || operator === 36) { + assumeTrue = !assumeTrue; + } + if (type.flags & 1 && literal.text === "function") { + return type; + } + var facts = assumeTrue ? + typeofEQFacts.get(literal.text) || 128 : + typeofNEFacts.get(literal.text) || 32768; + return getTypeWithFacts(assumeTrue ? mapType(type, narrowTypeForTypeof) : type, facts); + function narrowTypeForTypeof(type) { + if (type.flags & 2 && literal.text === "object") { + return getUnionType([nonPrimitiveType, nullType]); + } + var targetType = literal.text === "function" ? globalFunctionType : typeofTypesByName.get(literal.text); + if (targetType) { + if (isTypeSubtypeOf(type, targetType)) { + return type; + } + if (isTypeSubtypeOf(targetType, type)) { + return targetType; + } + if (type.flags & 63176704) { + var constraint = getBaseConstraintOfType(type) || anyType; + if (isTypeSubtypeOf(targetType, constraint)) { + return getIntersectionType([type, targetType]); + } + } + } + return type; + } + } + function narrowTypeBySwitchOnDiscriminant(type, switchStatement, clauseStart, clauseEnd) { + var switchTypes = getSwitchClauseTypes(switchStatement); + if (!switchTypes.length) { + return type; + } + var clauseTypes = switchTypes.slice(clauseStart, clauseEnd); + var hasDefaultClause = clauseStart === clauseEnd || ts.contains(clauseTypes, neverType); + var discriminantType = getUnionType(clauseTypes); + var caseType = discriminantType.flags & 131072 ? neverType : + replacePrimitivesWithLiterals(filterType(type, function (t) { return areTypesComparable(discriminantType, t); }), discriminantType); + if (!hasDefaultClause) { + return caseType; + } + var defaultType = filterType(type, function (t) { return !(isUnitType(t) && ts.contains(switchTypes, getRegularTypeOfLiteralType(t))); }); + return caseType.flags & 131072 ? defaultType : getUnionType([caseType, defaultType]); + } + function getImpliedTypeFromTypeofCase(type, text) { + switch (text) { + case "function": + return type.flags & 1 ? type : globalFunctionType; + case "object": + return type.flags & 2 ? getUnionType([nonPrimitiveType, nullType]) : type; + default: + return typeofTypesByName.get(text) || type; + } + } + function narrowTypeForTypeofSwitch(candidate) { + return function (type) { + if (isTypeSubtypeOf(candidate, type)) { + return candidate; + } + if (type.flags & 63176704) { + var constraint = getBaseConstraintOfType(type) || anyType; + if (isTypeSubtypeOf(candidate, constraint)) { + return getIntersectionType([type, candidate]); + } + } + return type; + }; + } + function narrowBySwitchOnTypeOf(type, switchStatement, clauseStart, clauseEnd) { + var switchWitnesses = getSwitchClauseTypeOfWitnesses(switchStatement); + if (!switchWitnesses.length) { + return type; + } + var defaultCaseLocation = ts.findIndex(switchWitnesses, function (elem) { return elem === undefined; }); + var hasDefaultClause = clauseStart === clauseEnd || (defaultCaseLocation >= clauseStart && defaultCaseLocation < clauseEnd); + var clauseWitnesses; + var switchFacts; + if (defaultCaseLocation > -1) { + var witnesses = switchWitnesses.filter(function (witness) { return witness !== undefined; }); + var fixedClauseStart = defaultCaseLocation < clauseStart ? clauseStart - 1 : clauseStart; + var fixedClauseEnd = defaultCaseLocation < clauseEnd ? clauseEnd - 1 : clauseEnd; + clauseWitnesses = witnesses.slice(fixedClauseStart, fixedClauseEnd); + switchFacts = getFactsFromTypeofSwitch(fixedClauseStart, fixedClauseEnd, witnesses, hasDefaultClause); + } + else { + clauseWitnesses = switchWitnesses.slice(clauseStart, clauseEnd); + switchFacts = getFactsFromTypeofSwitch(clauseStart, clauseEnd, switchWitnesses, hasDefaultClause); + } + if (hasDefaultClause) { + return filterType(type, function (t) { return (getTypeFacts(t) & switchFacts) === switchFacts; }); + } + var impliedType = getTypeWithFacts(getUnionType(clauseWitnesses.map(function (text) { return getImpliedTypeFromTypeofCase(type, text); })), switchFacts); + if (impliedType.flags & 1048576) { + impliedType = getAssignmentReducedType(impliedType, getBaseConstraintOrType(type)); + } + return getTypeWithFacts(mapType(type, narrowTypeForTypeofSwitch(impliedType)), switchFacts); + } + function narrowTypeByInstanceof(type, expr, assumeTrue) { + var left = getReferenceCandidate(expr.left); + if (!isMatchingReference(reference, left)) { + if (containsMatchingReference(reference, left) && hasNarrowableDeclaredType(left)) { + return declaredType; + } + return type; + } + var rightType = getTypeOfExpression(expr.right); + if (!isTypeDerivedFrom(rightType, globalFunctionType)) { + return type; + } + var targetType; + var prototypeProperty = getPropertyOfType(rightType, "prototype"); + if (prototypeProperty) { + var prototypePropertyType = getTypeOfSymbol(prototypeProperty); + if (!isTypeAny(prototypePropertyType)) { + targetType = prototypePropertyType; + } + } + if (isTypeAny(type) && (targetType === globalObjectType || targetType === globalFunctionType)) { + return type; + } + if (!targetType) { + var constructSignatures = getSignaturesOfType(rightType, 1); + targetType = constructSignatures.length ? + getUnionType(ts.map(constructSignatures, function (signature) { return getReturnTypeOfSignature(getErasedSignature(signature)); })) : + emptyObjectType; + } + return getNarrowedType(type, targetType, assumeTrue, isTypeDerivedFrom); + } + function getNarrowedType(type, candidate, assumeTrue, isRelated) { + if (!assumeTrue) { + return filterType(type, function (t) { return !isRelated(t, candidate); }); + } + if (type.flags & 1048576) { + var assignableType = filterType(type, function (t) { return isRelated(t, candidate); }); + if (!(assignableType.flags & 131072)) { + return assignableType; + } + } + return isTypeSubtypeOf(candidate, type) ? candidate : + isTypeAssignableTo(type, candidate) ? type : + isTypeAssignableTo(candidate, type) ? candidate : + getIntersectionType([type, candidate]); + } + function narrowTypeByTypePredicate(type, callExpression, assumeTrue) { + if (!hasMatchingArgument(callExpression, reference) || !maybeTypePredicateCall(callExpression)) { + return type; + } + var signature = getResolvedSignature(callExpression); + var predicate = getTypePredicateOfSignature(signature); + if (!predicate) { + return type; + } + if (isTypeAny(type) && (predicate.type === globalObjectType || predicate.type === globalFunctionType)) { + return type; + } + if (ts.isIdentifierTypePredicate(predicate)) { + var predicateArgument = callExpression.arguments[predicate.parameterIndex - (signature.thisParameter ? 1 : 0)]; + if (predicateArgument) { + if (isMatchingReference(reference, predicateArgument)) { + return getNarrowedType(type, predicate.type, assumeTrue, isTypeSubtypeOf); + } + if (containsMatchingReference(reference, predicateArgument)) { + return declaredType; + } + } + } + else { + var invokedExpression = ts.skipParentheses(callExpression.expression); + if (invokedExpression.kind === 190 || invokedExpression.kind === 189) { + var accessExpression = invokedExpression; + var possibleReference = ts.skipParentheses(accessExpression.expression); + if (isMatchingReference(reference, possibleReference)) { + return getNarrowedType(type, predicate.type, assumeTrue, isTypeSubtypeOf); + } + if (containsMatchingReference(reference, possibleReference)) { + return declaredType; + } + } + } + return type; + } + function narrowType(type, expr, assumeTrue) { + switch (expr.kind) { + case 72: + case 100: + case 98: + case 189: + case 190: + return narrowTypeByTruthiness(type, expr, assumeTrue); + case 191: + return narrowTypeByTypePredicate(type, expr, assumeTrue); + case 195: + return narrowType(type, expr.expression, assumeTrue); + case 204: + return narrowTypeByBinaryExpression(type, expr, assumeTrue); + case 202: + if (expr.operator === 52) { + return narrowType(type, expr.operand, !assumeTrue); + } + break; + } + return type; + } + } + function getTypeOfSymbolAtLocation(symbol, location) { + symbol = symbol.exportSymbol || symbol; + if (location.kind === 72) { + if (ts.isRightSideOfQualifiedNameOrPropertyAccess(location)) { + location = location.parent; + } + if (ts.isExpressionNode(location) && !ts.isAssignmentTarget(location)) { + var type = getTypeOfExpression(location); + if (getExportSymbolOfValueSymbolIfExported(getNodeLinks(location).resolvedSymbol) === symbol) { + return type; + } + } + } + return getTypeOfSymbol(symbol); + } + function getControlFlowContainer(node) { + return ts.findAncestor(node.parent, function (node) { + return ts.isFunctionLike(node) && !ts.getImmediatelyInvokedFunctionExpression(node) || + node.kind === 245 || + node.kind === 279 || + node.kind === 154; + }); + } + function isParameterAssigned(symbol) { + var func = ts.getRootDeclaration(symbol.valueDeclaration).parent; + var links = getNodeLinks(func); + if (!(links.flags & 8388608)) { + links.flags |= 8388608; + if (!hasParentWithAssignmentsMarked(func)) { + markParameterAssignments(func); + } + } + return symbol.isAssigned || false; + } + function hasParentWithAssignmentsMarked(node) { + return !!ts.findAncestor(node.parent, function (node) { return ts.isFunctionLike(node) && !!(getNodeLinks(node).flags & 8388608); }); + } + function markParameterAssignments(node) { + if (node.kind === 72) { + if (ts.isAssignmentTarget(node)) { + var symbol = getResolvedSymbol(node); + if (symbol.valueDeclaration && ts.getRootDeclaration(symbol.valueDeclaration).kind === 151) { + symbol.isAssigned = true; + } + } + } + else { + ts.forEachChild(node, markParameterAssignments); + } + } + function isConstVariable(symbol) { + return symbol.flags & 3 && (getDeclarationNodeFlagsFromSymbol(symbol) & 2) !== 0 && getTypeOfSymbol(symbol) !== autoArrayType; + } + function removeOptionalityFromDeclaredType(declaredType, declaration) { + var annotationIncludesUndefined = strictNullChecks && + declaration.kind === 151 && + declaration.initializer && + getFalsyFlags(declaredType) & 32768 && + !(getFalsyFlags(checkExpression(declaration.initializer)) & 32768); + return annotationIncludesUndefined ? getTypeWithFacts(declaredType, 524288) : declaredType; + } + function isConstraintPosition(node) { + var parent = node.parent; + return parent.kind === 189 || + parent.kind === 191 && parent.expression === node || + parent.kind === 190 && parent.expression === node || + parent.kind === 186 && parent.name === node && !!parent.initializer; + } + function typeHasNullableConstraint(type) { + return type.flags & 58982400 && maybeTypeOfKind(getBaseConstraintOfType(type) || emptyObjectType, 98304); + } + function getConstraintForLocation(type, node) { + if (type && isConstraintPosition(node) && forEachType(type, typeHasNullableConstraint)) { + return mapType(getWidenedType(type), getBaseConstraintOrType); + } + return type; + } + function markAliasReferenced(symbol, location) { + if (isNonLocalAlias(symbol, 67220415) && !isInTypeQuery(location) && !isConstEnumOrConstEnumOnlyModule(resolveAlias(symbol))) { + markAliasSymbolAsReferenced(symbol); + } + } + function checkIdentifier(node) { + var symbol = getResolvedSymbol(node); + if (symbol === unknownSymbol) { + return errorType; + } + if (symbol === argumentsSymbol) { + var container = ts.getContainingFunction(node); + if (languageVersion < 2) { + if (container.kind === 197) { + error(node, ts.Diagnostics.The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_standard_function_expression); + } + else if (ts.hasModifier(container, 256)) { + error(node, ts.Diagnostics.The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_using_a_standard_function_or_method); + } + } + getNodeLinks(container).flags |= 8192; + return getTypeOfSymbol(symbol); + } + if (!(node.parent && ts.isPropertyAccessExpression(node.parent) && node.parent.expression === node)) { + markAliasReferenced(symbol, node); + } + var localOrExportSymbol = getExportSymbolOfValueSymbolIfExported(symbol); + var declaration = localOrExportSymbol.valueDeclaration; + if (localOrExportSymbol.flags & 32) { + if (declaration.kind === 240 + && ts.nodeIsDecorated(declaration)) { + var container = ts.getContainingClass(node); + while (container !== undefined) { + if (container === declaration && container.name !== node) { + getNodeLinks(declaration).flags |= 16777216; + getNodeLinks(node).flags |= 33554432; + break; + } + container = ts.getContainingClass(container); + } + } + else if (declaration.kind === 209) { + var container = ts.getThisContainer(node, false); + while (container.kind !== 279) { + if (container.parent === declaration) { + if (container.kind === 154 && ts.hasModifier(container, 32)) { + getNodeLinks(declaration).flags |= 16777216; + getNodeLinks(node).flags |= 33554432; + } + break; + } + container = ts.getThisContainer(container, false); + } + } + } + checkNestedBlockScopedBinding(node, symbol); + var type = getConstraintForLocation(getTypeOfSymbol(localOrExportSymbol), node); + var assignmentKind = ts.getAssignmentTargetKind(node); + if (assignmentKind) { + if (!(localOrExportSymbol.flags & 3) && + !(ts.isInJSFile(node) && localOrExportSymbol.flags & 512)) { + error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_not_a_variable, symbolToString(symbol)); + return errorType; + } + if (isReadonlySymbol(localOrExportSymbol)) { + if (localOrExportSymbol.flags & 3) { + error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant, symbolToString(symbol)); + } + else { + error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, symbolToString(symbol)); + } + return errorType; + } + } + var isAlias = localOrExportSymbol.flags & 2097152; + if (localOrExportSymbol.flags & 3) { + if (assignmentKind === 1) { + return type; + } + } + else if (isAlias) { + declaration = ts.find(symbol.declarations, isSomeImportDeclaration); + } + else { + return type; + } + if (!declaration) { + return type; + } + var isParameter = ts.getRootDeclaration(declaration).kind === 151; + var declarationContainer = getControlFlowContainer(declaration); + var flowContainer = getControlFlowContainer(node); + var isOuterVariable = flowContainer !== declarationContainer; + var isSpreadDestructuringAssignmentTarget = node.parent && node.parent.parent && ts.isSpreadAssignment(node.parent) && isDestructuringAssignmentTarget(node.parent.parent); + var isModuleExports = symbol.flags & 134217728; + while (flowContainer !== declarationContainer && (flowContainer.kind === 196 || + flowContainer.kind === 197 || ts.isObjectLiteralOrClassExpressionMethod(flowContainer)) && + (isConstVariable(localOrExportSymbol) || isParameter && !isParameterAssigned(localOrExportSymbol))) { + flowContainer = getControlFlowContainer(flowContainer); + } + var assumeInitialized = isParameter || isAlias || isOuterVariable || isSpreadDestructuringAssignmentTarget || isModuleExports || + type !== autoType && type !== autoArrayType && (!strictNullChecks || (type.flags & 3) !== 0 || + isInTypeQuery(node) || node.parent.kind === 257) || + node.parent.kind === 213 || + declaration.kind === 237 && declaration.exclamationToken || + declaration.flags & 4194304; + var initialType = assumeInitialized ? (isParameter ? removeOptionalityFromDeclaredType(type, declaration) : type) : + type === autoType || type === autoArrayType ? undefinedType : + getOptionalType(type); + var flowType = getFlowTypeOfReference(node, type, initialType, flowContainer, !assumeInitialized); + if (!isEvolvingArrayOperationTarget(node) && (type === autoType || type === autoArrayType)) { + if (flowType === autoType || flowType === autoArrayType) { + if (noImplicitAny) { + error(ts.getNameOfDeclaration(declaration), ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined, symbolToString(symbol), typeToString(flowType)); + error(node, ts.Diagnostics.Variable_0_implicitly_has_an_1_type, symbolToString(symbol), typeToString(flowType)); + } + return convertAutoToAny(flowType); + } + } + else if (!assumeInitialized && !(getFalsyFlags(type) & 32768) && getFalsyFlags(flowType) & 32768) { + error(node, ts.Diagnostics.Variable_0_is_used_before_being_assigned, symbolToString(symbol)); + return type; + } + return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType; + } + function isInsideFunction(node, threshold) { + return !!ts.findAncestor(node, function (n) { return n === threshold ? "quit" : ts.isFunctionLike(n); }); + } + function getPartOfForStatementContainingNode(node, container) { + return ts.findAncestor(node, function (n) { return n === container ? "quit" : n === container.initializer || n === container.condition || n === container.incrementor || n === container.statement; }); + } + function checkNestedBlockScopedBinding(node, symbol) { + if (languageVersion >= 2 || + (symbol.flags & (2 | 32)) === 0 || + symbol.valueDeclaration.parent.kind === 274) { + return; + } + var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); + var usedInFunction = isInsideFunction(node.parent, container); + var current = container; + var containedInIterationStatement = false; + while (current && !ts.nodeStartsNewLexicalEnvironment(current)) { + if (ts.isIterationStatement(current, false)) { + containedInIterationStatement = true; + break; + } + current = current.parent; + } + if (containedInIterationStatement) { + if (usedInFunction) { + var capturesBlockScopeBindingInLoopBody = true; + if (ts.isForStatement(container) && + ts.getAncestor(symbol.valueDeclaration, 238).parent === container) { + var part = getPartOfForStatementContainingNode(node.parent, container); + if (part) { + var links = getNodeLinks(part); + links.flags |= 131072; + var capturedBindings = links.capturedBlockScopeBindings || (links.capturedBlockScopeBindings = []); + ts.pushIfUnique(capturedBindings, symbol); + if (part === container.initializer) { + capturesBlockScopeBindingInLoopBody = false; + } + } + } + if (capturesBlockScopeBindingInLoopBody) { + getNodeLinks(current).flags |= 65536; + } + } + if (container.kind === 225 && + ts.getAncestor(symbol.valueDeclaration, 238).parent === container && + isAssignedInBodyOfForStatement(node, container)) { + getNodeLinks(symbol.valueDeclaration).flags |= 4194304; + } + getNodeLinks(symbol.valueDeclaration).flags |= 524288; + } + if (usedInFunction) { + getNodeLinks(symbol.valueDeclaration).flags |= 262144; + } + } + function isBindingCapturedByNode(node, decl) { + var links = getNodeLinks(node); + return !!links && ts.contains(links.capturedBlockScopeBindings, getSymbolOfNode(decl)); + } + function isAssignedInBodyOfForStatement(node, container) { + var current = node; + while (current.parent.kind === 195) { + current = current.parent; + } + var isAssigned = false; + if (ts.isAssignmentTarget(current)) { + isAssigned = true; + } + else if ((current.parent.kind === 202 || current.parent.kind === 203)) { + var expr = current.parent; + isAssigned = expr.operator === 44 || expr.operator === 45; + } + if (!isAssigned) { + return false; + } + return !!ts.findAncestor(current, function (n) { return n === container ? "quit" : n === container.statement; }); + } + function captureLexicalThis(node, container) { + getNodeLinks(node).flags |= 2; + if (container.kind === 154 || container.kind === 157) { + var classNode = container.parent; + getNodeLinks(classNode).flags |= 4; + } + else { + getNodeLinks(container).flags |= 4; + } + } + function findFirstSuperCall(n) { + if (ts.isSuperCall(n)) { + return n; + } + else if (ts.isFunctionLike(n)) { + return undefined; + } + return ts.forEachChild(n, findFirstSuperCall); + } + function getSuperCallInConstructor(constructor) { + var links = getNodeLinks(constructor); + if (links.hasSuperCall === undefined) { + links.superCall = findFirstSuperCall(constructor.body); + links.hasSuperCall = links.superCall ? true : false; + } + return links.superCall; + } + function classDeclarationExtendsNull(classDecl) { + var classSymbol = getSymbolOfNode(classDecl); + var classInstanceType = getDeclaredTypeOfSymbol(classSymbol); + var baseConstructorType = getBaseConstructorTypeOfClass(classInstanceType); + return baseConstructorType === nullWideningType; + } + function checkThisBeforeSuper(node, container, diagnosticMessage) { + var containingClassDecl = container.parent; + var baseTypeNode = ts.getEffectiveBaseTypeNode(containingClassDecl); + if (baseTypeNode && !classDeclarationExtendsNull(containingClassDecl)) { + var superCall = getSuperCallInConstructor(container); + if (!superCall || superCall.end > node.pos) { + error(node, diagnosticMessage); + } + } + } + function checkThisExpression(node) { + var container = ts.getThisContainer(node, true); + var capturedByArrowFunction = false; + if (container.kind === 157) { + checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class); + } + if (container.kind === 197) { + container = ts.getThisContainer(container, false); + capturedByArrowFunction = true; + } + switch (container.kind) { + case 244: + error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_module_or_namespace_body); + break; + case 243: + error(node, ts.Diagnostics.this_cannot_be_referenced_in_current_location); + break; + case 157: + if (isInConstructorArgumentInitializer(node, container)) { + error(node, ts.Diagnostics.this_cannot_be_referenced_in_constructor_arguments); + } + break; + case 154: + case 153: + if (ts.hasModifier(container, 32)) { + error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_static_property_initializer); + } + break; + case 149: + error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_computed_property_name); + break; + } + if (capturedByArrowFunction && languageVersion < 2) { + captureLexicalThis(node, container); + } + var type = tryGetThisTypeAt(node, container); + if (!type && noImplicitThis) { + var diag = error(node, capturedByArrowFunction && container.kind === 279 ? + ts.Diagnostics.The_containing_arrow_function_captures_the_global_value_of_this_which_implicitly_has_type_any : + ts.Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation); + if (!ts.isSourceFile(container)) { + var outsideThis = tryGetThisTypeAt(container); + if (outsideThis) { + addRelatedInfo(diag, ts.createDiagnosticForNode(container, ts.Diagnostics.An_outer_value_of_this_is_shadowed_by_this_container)); + } + } + } + return type || anyType; + } + function tryGetThisTypeAt(node, container) { + if (container === void 0) { container = ts.getThisContainer(node, false); } + var isInJS = ts.isInJSFile(node); + if (ts.isFunctionLike(container) && + (!isInParameterInitializerBeforeContainingFunction(node) || ts.getThisParameter(container))) { + var className = getClassNameFromPrototypeMethod(container); + if (isInJS && className) { + var classSymbol = checkExpression(className).symbol; + if (classSymbol && classSymbol.members && (classSymbol.flags & 16)) { + var classType = getJSClassType(classSymbol); + if (classType) { + return getFlowTypeOfReference(node, classType); + } + } + } + else if (isInJS && + (container.kind === 196 || container.kind === 239) && + ts.getJSDocClassTag(container)) { + var classType = getJSClassType(container.symbol); + if (classType) { + return getFlowTypeOfReference(node, classType); + } + } + var thisType = getThisTypeOfDeclaration(container) || getContextualThisParameterType(container); + if (thisType) { + return getFlowTypeOfReference(node, thisType); + } + } + if (ts.isClassLike(container.parent)) { + var symbol = getSymbolOfNode(container.parent); + var type = ts.hasModifier(container, 32) ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol).thisType; + return getFlowTypeOfReference(node, type); + } + if (isInJS) { + var type = getTypeForThisExpressionFromJSDoc(container); + if (type && type !== errorType) { + return getFlowTypeOfReference(node, type); + } + } + } + function getClassNameFromPrototypeMethod(container) { + if (container.kind === 196 && + ts.isBinaryExpression(container.parent) && + ts.getAssignmentDeclarationKind(container.parent) === 3) { + return container.parent + .left + .expression + .expression; + } + else if (container.kind === 156 && + container.parent.kind === 188 && + ts.isBinaryExpression(container.parent.parent) && + ts.getAssignmentDeclarationKind(container.parent.parent) === 6) { + return container.parent.parent.left.expression; + } + else if (container.kind === 196 && + container.parent.kind === 275 && + container.parent.parent.kind === 188 && + ts.isBinaryExpression(container.parent.parent.parent) && + ts.getAssignmentDeclarationKind(container.parent.parent.parent) === 6) { + return container.parent.parent.parent.left.expression; + } + else if (container.kind === 196 && + ts.isPropertyAssignment(container.parent) && + ts.isIdentifier(container.parent.name) && + (container.parent.name.escapedText === "value" || container.parent.name.escapedText === "get" || container.parent.name.escapedText === "set") && + ts.isObjectLiteralExpression(container.parent.parent) && + ts.isCallExpression(container.parent.parent.parent) && + container.parent.parent.parent.arguments[2] === container.parent.parent && + ts.getAssignmentDeclarationKind(container.parent.parent.parent) === 9) { + return container.parent.parent.parent.arguments[0].expression; + } + else if (ts.isMethodDeclaration(container) && + ts.isIdentifier(container.name) && + (container.name.escapedText === "value" || container.name.escapedText === "get" || container.name.escapedText === "set") && + ts.isObjectLiteralExpression(container.parent) && + ts.isCallExpression(container.parent.parent) && + container.parent.parent.arguments[2] === container.parent && + ts.getAssignmentDeclarationKind(container.parent.parent) === 9) { + return container.parent.parent.arguments[0].expression; + } + } + function getTypeForThisExpressionFromJSDoc(node) { + var jsdocType = ts.getJSDocType(node); + if (jsdocType && jsdocType.kind === 289) { + var jsDocFunctionType = jsdocType; + if (jsDocFunctionType.parameters.length > 0 && + jsDocFunctionType.parameters[0].name && + jsDocFunctionType.parameters[0].name.escapedText === "this") { + return getTypeFromTypeNode(jsDocFunctionType.parameters[0].type); + } + } + var thisTag = ts.getJSDocThisTag(node); + if (thisTag && thisTag.typeExpression) { + return getTypeFromTypeNode(thisTag.typeExpression); + } + } + function isInConstructorArgumentInitializer(node, constructorDecl) { + return !!ts.findAncestor(node, function (n) { return n === constructorDecl ? "quit" : n.kind === 151; }); + } + function checkSuperExpression(node) { + var isCallExpression = node.parent.kind === 191 && node.parent.expression === node; + var container = ts.getSuperContainer(node, true); + var needToCaptureLexicalThis = false; + if (!isCallExpression) { + while (container && container.kind === 197) { + container = ts.getSuperContainer(container, true); + needToCaptureLexicalThis = languageVersion < 2; + } + } + var canUseSuperExpression = isLegalUsageOfSuperExpression(container); + var nodeCheckFlag = 0; + if (!canUseSuperExpression) { + var current = ts.findAncestor(node, function (n) { return n === container ? "quit" : n.kind === 149; }); + if (current && current.kind === 149) { + error(node, ts.Diagnostics.super_cannot_be_referenced_in_a_computed_property_name); + } + else if (isCallExpression) { + error(node, ts.Diagnostics.Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors); + } + else if (!container || !container.parent || !(ts.isClassLike(container.parent) || container.parent.kind === 188)) { + error(node, ts.Diagnostics.super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions); + } + else { + error(node, ts.Diagnostics.super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_derived_class); + } + return errorType; + } + if (!isCallExpression && container.kind === 157) { + checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class); + } + if (ts.hasModifier(container, 32) || isCallExpression) { + nodeCheckFlag = 512; + } + else { + nodeCheckFlag = 256; + } + getNodeLinks(node).flags |= nodeCheckFlag; + if (container.kind === 156 && ts.hasModifier(container, 256)) { + if (ts.isSuperProperty(node.parent) && ts.isAssignmentTarget(node.parent)) { + getNodeLinks(container).flags |= 4096; + } + else { + getNodeLinks(container).flags |= 2048; + } + } + if (needToCaptureLexicalThis) { + captureLexicalThis(node.parent, container); + } + if (container.parent.kind === 188) { + if (languageVersion < 2) { + error(node, ts.Diagnostics.super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_higher); + return errorType; + } + else { + return anyType; + } + } + var classLikeDeclaration = container.parent; + if (!ts.getEffectiveBaseTypeNode(classLikeDeclaration)) { + error(node, ts.Diagnostics.super_can_only_be_referenced_in_a_derived_class); + return errorType; + } + var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(classLikeDeclaration)); + var baseClassType = classType && getBaseTypes(classType)[0]; + if (!baseClassType) { + return errorType; + } + if (container.kind === 157 && isInConstructorArgumentInitializer(node, container)) { + error(node, ts.Diagnostics.super_cannot_be_referenced_in_constructor_arguments); + return errorType; + } + return nodeCheckFlag === 512 + ? getBaseConstructorTypeOfClass(classType) + : getTypeWithThisArgument(baseClassType, classType.thisType); + function isLegalUsageOfSuperExpression(container) { + if (!container) { + return false; + } + if (isCallExpression) { + return container.kind === 157; + } + else { + if (ts.isClassLike(container.parent) || container.parent.kind === 188) { + if (ts.hasModifier(container, 32)) { + return container.kind === 156 || + container.kind === 155 || + container.kind === 158 || + container.kind === 159; + } + else { + return container.kind === 156 || + container.kind === 155 || + container.kind === 158 || + container.kind === 159 || + container.kind === 154 || + container.kind === 153 || + container.kind === 157; + } + } + } + return false; + } + } + function getContainingObjectLiteral(func) { + return (func.kind === 156 || + func.kind === 158 || + func.kind === 159) && func.parent.kind === 188 ? func.parent : + func.kind === 196 && func.parent.kind === 275 ? func.parent.parent : + undefined; + } + function getThisTypeArgument(type) { + return ts.getObjectFlags(type) & 4 && type.target === globalThisType ? type.typeArguments[0] : undefined; + } + function getThisTypeFromContextualType(type) { + return mapType(type, function (t) { + return t.flags & 2097152 ? ts.forEach(t.types, getThisTypeArgument) : getThisTypeArgument(t); + }); + } + function getContextualThisParameterType(func) { + if (func.kind === 197) { + return undefined; + } + if (isContextSensitiveFunctionOrObjectLiteralMethod(func)) { + var contextualSignature = getContextualSignature(func); + if (contextualSignature) { + var thisParameter = contextualSignature.thisParameter; + if (thisParameter) { + return getTypeOfSymbol(thisParameter); + } + } + } + var inJs = ts.isInJSFile(func); + if (noImplicitThis || inJs) { + var containingLiteral = getContainingObjectLiteral(func); + if (containingLiteral) { + var contextualType = getApparentTypeOfContextualType(containingLiteral); + var literal = containingLiteral; + var type = contextualType; + while (type) { + var thisType = getThisTypeFromContextualType(type); + if (thisType) { + return instantiateType(thisType, getContextualMapper(containingLiteral)); + } + if (literal.parent.kind !== 275) { + break; + } + literal = literal.parent.parent; + type = getApparentTypeOfContextualType(literal); + } + return contextualType ? getNonNullableType(contextualType) : checkExpressionCached(containingLiteral); + } + var parent = func.parent; + if (parent.kind === 204 && parent.operatorToken.kind === 59) { + var target = parent.left; + if (target.kind === 189 || target.kind === 190) { + var expression = target.expression; + if (inJs && ts.isIdentifier(expression)) { + var sourceFile = ts.getSourceFileOfNode(parent); + if (sourceFile.commonJsModuleIndicator && getResolvedSymbol(expression) === sourceFile.symbol) { + return undefined; + } + } + return checkExpressionCached(expression); + } + } + } + return undefined; + } + function getContextuallyTypedParameterType(parameter) { + var func = parameter.parent; + if (!isContextSensitiveFunctionOrObjectLiteralMethod(func)) { + return undefined; + } + var iife = ts.getImmediatelyInvokedFunctionExpression(func); + if (iife && iife.arguments) { + var args = getEffectiveCallArguments(iife); + var indexOfParameter = func.parameters.indexOf(parameter); + if (parameter.dotDotDotToken) { + return getSpreadArgumentType(args, indexOfParameter, args.length, anyType, undefined); + } + var links = getNodeLinks(iife); + var cached = links.resolvedSignature; + links.resolvedSignature = anySignature; + var type = indexOfParameter < args.length ? + getWidenedLiteralType(checkExpression(args[indexOfParameter])) : + parameter.initializer ? undefined : undefinedWideningType; + links.resolvedSignature = cached; + return type; + } + var contextualSignature = getContextualSignature(func); + if (contextualSignature) { + var index = func.parameters.indexOf(parameter) - (ts.getThisParameter(func) ? 1 : 0); + return parameter.dotDotDotToken && ts.lastOrUndefined(func.parameters) === parameter ? + getRestTypeAtPosition(contextualSignature, index) : + tryGetTypeAtPosition(contextualSignature, index); + } + } + function getContextualTypeForInitializerExpression(node) { + var declaration = node.parent; + if (ts.hasInitializer(declaration) && node === declaration.initializer) { + var typeNode = ts.getEffectiveTypeAnnotationNode(declaration); + if (typeNode) { + return getTypeFromTypeNode(typeNode); + } + if (declaration.kind === 151) { + var type = getContextuallyTypedParameterType(declaration); + if (type) { + return type; + } + } + if (ts.isBindingPattern(declaration.name)) { + return getTypeFromBindingPattern(declaration.name, true, false); + } + if (ts.isBindingPattern(declaration.parent)) { + var parentDeclaration = declaration.parent.parent; + var name = declaration.propertyName || declaration.name; + if (parentDeclaration.kind !== 186) { + var parentTypeNode = ts.getEffectiveTypeAnnotationNode(parentDeclaration); + if (parentTypeNode && !ts.isBindingPattern(name)) { + var text = ts.getTextOfPropertyName(name); + if (text) { + return getTypeOfPropertyOfType(getTypeFromTypeNode(parentTypeNode), text); + } + } + } + } + } + return undefined; + } + function getContextualTypeForReturnExpression(node) { + var func = ts.getContainingFunction(node); + if (func) { + var functionFlags = ts.getFunctionFlags(func); + if (functionFlags & 1) { + return undefined; + } + var contextualReturnType = getContextualReturnType(func); + if (contextualReturnType) { + if (functionFlags & 2) { + var contextualAwaitedType = getAwaitedTypeOfPromise(contextualReturnType); + return contextualAwaitedType && getUnionType([contextualAwaitedType, createPromiseLikeType(contextualAwaitedType)]); + } + return contextualReturnType; + } + } + return undefined; + } + function getContextualTypeForAwaitOperand(node) { + var contextualType = getContextualType(node); + if (contextualType) { + var contextualAwaitedType = getAwaitedType(contextualType); + return contextualAwaitedType && getUnionType([contextualAwaitedType, createPromiseLikeType(contextualAwaitedType)]); + } + return undefined; + } + function getContextualTypeForYieldOperand(node) { + var func = ts.getContainingFunction(node); + if (func) { + var functionFlags = ts.getFunctionFlags(func); + var contextualReturnType = getContextualReturnType(func); + if (contextualReturnType) { + return node.asteriskToken + ? contextualReturnType + : getIteratedTypeOfGenerator(contextualReturnType, (functionFlags & 2) !== 0); + } + } + return undefined; + } + function isInParameterInitializerBeforeContainingFunction(node) { + var inBindingInitializer = false; + while (node.parent && !ts.isFunctionLike(node.parent)) { + if (ts.isParameter(node.parent) && (inBindingInitializer || node.parent.initializer === node)) { + return true; + } + if (ts.isBindingElement(node.parent) && node.parent.initializer === node) { + inBindingInitializer = true; + } + node = node.parent; + } + return false; + } + function getContextualReturnType(functionDecl) { + var returnType = getReturnTypeFromAnnotation(functionDecl); + if (returnType) { + return returnType; + } + var signature = getContextualSignatureForFunctionLikeDeclaration(functionDecl); + if (signature && !isResolvingReturnTypeOfSignature(signature)) { + return getReturnTypeOfSignature(signature); + } + return undefined; + } + function getContextualTypeForArgument(callTarget, arg) { + var args = getEffectiveCallArguments(callTarget); + var argIndex = args.indexOf(arg); + return argIndex === -1 ? undefined : getContextualTypeForArgumentAtIndex(callTarget, argIndex); + } + function getContextualTypeForArgumentAtIndex(callTarget, argIndex) { + var signature = getNodeLinks(callTarget).resolvedSignature === resolvingSignature ? resolvingSignature : getResolvedSignature(callTarget); + if (ts.isJsxOpeningLikeElement(callTarget) && argIndex === 0) { + return getEffectiveFirstArgumentForJsxSignature(signature, callTarget); + } + return getTypeAtPosition(signature, argIndex); + } + function getContextualTypeForSubstitutionExpression(template, substitutionExpression) { + if (template.parent.kind === 193) { + return getContextualTypeForArgument(template.parent, substitutionExpression); + } + return undefined; + } + function getContextualTypeForBinaryOperand(node) { + var binaryExpression = node.parent; + var left = binaryExpression.left, operatorToken = binaryExpression.operatorToken, right = binaryExpression.right; + switch (operatorToken.kind) { + case 59: + if (node !== right) { + return undefined; + } + var contextSensitive = getIsContextSensitiveAssignmentOrContextType(binaryExpression); + if (!contextSensitive) { + return undefined; + } + return contextSensitive === true ? getTypeOfExpression(left) : contextSensitive; + case 55: + var type = getContextualType(binaryExpression); + return !type && node === right && !ts.isDefaultedExpandoInitializer(binaryExpression) ? + getTypeOfExpression(left) : type; + case 54: + case 27: + return node === right ? getContextualType(binaryExpression) : undefined; + default: + return undefined; + } + } + function getIsContextSensitiveAssignmentOrContextType(binaryExpression) { + var kind = ts.getAssignmentDeclarationKind(binaryExpression); + switch (kind) { + case 0: + return true; + case 5: + case 1: + case 6: + case 3: + if (!binaryExpression.left.symbol) { + return true; + } + else { + var decl = binaryExpression.left.symbol.valueDeclaration; + if (!decl) { + return false; + } + var lhs = binaryExpression.left; + var overallAnnotation = ts.getEffectiveTypeAnnotationNode(decl); + if (overallAnnotation) { + return getTypeFromTypeNode(overallAnnotation); + } + else if (ts.isIdentifier(lhs.expression)) { + var id = lhs.expression; + var parentSymbol = resolveName(id, id.escapedText, 67220415, undefined, id.escapedText, true); + if (parentSymbol) { + var annotated = ts.getEffectiveTypeAnnotationNode(parentSymbol.valueDeclaration); + if (annotated) { + var type = getTypeOfPropertyOfContextualType(getTypeFromTypeNode(annotated), lhs.name.escapedText); + return type || false; + } + return false; + } + } + return !ts.isInJSFile(decl); + } + case 2: + case 4: + if (!binaryExpression.symbol) + return true; + if (binaryExpression.symbol.valueDeclaration) { + var annotated = ts.getEffectiveTypeAnnotationNode(binaryExpression.symbol.valueDeclaration); + if (annotated) { + var type = getTypeFromTypeNode(annotated); + if (type) { + return type; + } + } + } + if (kind === 2) + return false; + var thisAccess = binaryExpression.left; + if (!ts.isObjectLiteralMethod(ts.getThisContainer(thisAccess.expression, false))) { + return false; + } + var thisType = checkThisExpression(thisAccess.expression); + return thisType && getTypeOfPropertyOfContextualType(thisType, thisAccess.name.escapedText) || false; + case 7: + case 8: + case 9: + return ts.Debug.fail("Does not apply"); + default: + return ts.Debug.assertNever(kind); + } + } + function getTypeOfPropertyOfContextualType(type, name) { + return mapType(type, function (t) { + if (t.flags & 3670016) { + var prop = getPropertyOfType(t, name); + if (prop) { + return getTypeOfSymbol(prop); + } + if (isTupleType(t)) { + var restType = getRestTypeOfTupleType(t); + if (restType && isNumericLiteralName(name) && +name >= 0) { + return restType; + } + } + return isNumericLiteralName(name) && getIndexTypeOfContextualType(t, 1) || + getIndexTypeOfContextualType(t, 0); + } + return undefined; + }, true); + } + function getIndexTypeOfContextualType(type, kind) { + return mapType(type, function (t) { return getIndexTypeOfStructuredType(t, kind); }, true); + } + function getContextualTypeForObjectLiteralMethod(node) { + ts.Debug.assert(ts.isObjectLiteralMethod(node)); + if (node.flags & 8388608) { + return undefined; + } + return getContextualTypeForObjectLiteralElement(node); + } + function getContextualTypeForObjectLiteralElement(element) { + var objectLiteral = element.parent; + var type = getApparentTypeOfContextualType(objectLiteral); + if (type) { + if (!hasNonBindableDynamicName(element)) { + var symbolName_2 = getSymbolOfNode(element).escapedName; + var propertyType = getTypeOfPropertyOfContextualType(type, symbolName_2); + if (propertyType) { + return propertyType; + } + } + return isNumericName(element.name) && getIndexTypeOfContextualType(type, 1) || + getIndexTypeOfContextualType(type, 0); + } + return undefined; + } + function getContextualTypeForElementExpression(arrayContextualType, index) { + return arrayContextualType && (getTypeOfPropertyOfContextualType(arrayContextualType, "" + index) + || getIteratedTypeOrElementType(arrayContextualType, undefined, false, false, false)); + } + function getContextualTypeForConditionalOperand(node) { + var conditional = node.parent; + return node === conditional.whenTrue || node === conditional.whenFalse ? getContextualType(conditional) : undefined; + } + function getContextualTypeForChildJsxExpression(node) { + var attributesType = getApparentTypeOfContextualType(node.openingElement.tagName); + var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(node)); + return attributesType && !isTypeAny(attributesType) && jsxChildrenPropertyName && jsxChildrenPropertyName !== "" ? getTypeOfPropertyOfContextualType(attributesType, jsxChildrenPropertyName) : undefined; + } + function getContextualTypeForJsxExpression(node) { + var exprParent = node.parent; + return ts.isJsxAttributeLike(exprParent) + ? getContextualType(node) + : ts.isJsxElement(exprParent) + ? getContextualTypeForChildJsxExpression(exprParent) + : undefined; + } + function getContextualTypeForJsxAttribute(attribute) { + if (ts.isJsxAttribute(attribute)) { + var attributesType = getApparentTypeOfContextualType(attribute.parent); + if (!attributesType || isTypeAny(attributesType)) { + return undefined; + } + return getTypeOfPropertyOfContextualType(attributesType, attribute.name.escapedText); + } + else { + return getContextualType(attribute.parent); + } + } + function isPossiblyDiscriminantValue(node) { + switch (node.kind) { + case 10: + case 8: + case 9: + case 14: + case 102: + case 87: + case 96: + case 72: + case 141: + return true; + case 189: + case 195: + return isPossiblyDiscriminantValue(node.expression); + case 270: + return !node.expression || isPossiblyDiscriminantValue(node.expression); + } + return false; + } + function discriminateContextualTypeByObjectMembers(node, contextualType) { + return discriminateTypeByDiscriminableItems(contextualType, ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 275 && isPossiblyDiscriminantValue(p.initializer) && isDiscriminantProperty(contextualType, p.symbol.escapedName); }), function (prop) { return [function () { return checkExpression(prop.initializer); }, prop.symbol.escapedName]; }), isTypeAssignableTo, contextualType); + } + function discriminateContextualTypeByJSXAttributes(node, contextualType) { + return discriminateTypeByDiscriminableItems(contextualType, ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 267 && isDiscriminantProperty(contextualType, p.symbol.escapedName) && (!p.initializer || isPossiblyDiscriminantValue(p.initializer)); }), function (prop) { return [!prop.initializer ? (function () { return trueType; }) : (function () { return checkExpression(prop.initializer); }), prop.symbol.escapedName]; }), isTypeAssignableTo, contextualType); + } + function getApparentTypeOfContextualType(node) { + var contextualType = getContextualType(node); + contextualType = contextualType && mapType(contextualType, getApparentType); + if (contextualType && contextualType.flags & 1048576) { + if (ts.isObjectLiteralExpression(node)) { + return discriminateContextualTypeByObjectMembers(node, contextualType); + } + else if (ts.isJsxAttributes(node)) { + return discriminateContextualTypeByJSXAttributes(node, contextualType); + } + } + return contextualType; + } + function getContextualType(node) { + if (node.flags & 8388608) { + return undefined; + } + if (node.contextualType) { + return node.contextualType; + } + var parent = node.parent; + switch (parent.kind) { + case 237: + case 151: + case 154: + case 153: + case 186: + return getContextualTypeForInitializerExpression(node); + case 197: + case 230: + return getContextualTypeForReturnExpression(node); + case 207: + return getContextualTypeForYieldOperand(parent); + case 201: + return getContextualTypeForAwaitOperand(parent); + case 191: + case 192: + return getContextualTypeForArgument(parent, node); + case 194: + case 212: + return getTypeFromTypeNode(parent.type); + case 204: + return getContextualTypeForBinaryOperand(node); + case 275: + case 276: + return getContextualTypeForObjectLiteralElement(parent); + case 277: + return getApparentTypeOfContextualType(parent.parent); + case 187: { + var arrayLiteral = parent; + var type = getApparentTypeOfContextualType(arrayLiteral); + return getContextualTypeForElementExpression(type, ts.indexOfNode(arrayLiteral.elements, node)); + } + case 205: + return getContextualTypeForConditionalOperand(node); + case 216: + ts.Debug.assert(parent.parent.kind === 206); + return getContextualTypeForSubstitutionExpression(parent.parent, node); + case 195: { + var tag = ts.isInJSFile(parent) ? ts.getJSDocTypeTag(parent) : undefined; + return tag ? getTypeFromTypeNode(tag.typeExpression.type) : getContextualType(parent); + } + case 270: + return getContextualTypeForJsxExpression(parent); + case 267: + case 269: + return getContextualTypeForJsxAttribute(parent); + case 262: + case 261: + return getContextualJsxElementAttributesType(parent); + } + return undefined; + } + function getContextualMapper(node) { + var ancestor = ts.findAncestor(node, function (n) { return !!n.contextualMapper; }); + return ancestor ? ancestor.contextualMapper : identityMapper; + } + function getContextualJsxElementAttributesType(node) { + if (ts.isJsxOpeningElement(node) && node.parent.contextualType) { + return node.parent.contextualType; + } + return getContextualTypeForArgumentAtIndex(node, 0); + } + function getEffectiveFirstArgumentForJsxSignature(signature, node) { + return getJsxReferenceKind(node) !== 0 ? getJsxPropsTypeFromCallSignature(signature, node) : getJsxPropsTypeFromClassType(signature, node); + } + function getJsxPropsTypeFromCallSignature(sig, context) { + var propsType = getTypeOfFirstParameterOfSignatureWithFallback(sig, emptyObjectType); + propsType = getJsxManagedAttributesFromLocatedAttributes(context, getJsxNamespaceAt(context), propsType); + var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes, context); + if (intrinsicAttribs !== errorType) { + propsType = intersectTypes(intrinsicAttribs, propsType); + } + return propsType; + } + function getJsxPropsTypeForSignatureFromMember(sig, forcedLookupLocation) { + var instanceType = getReturnTypeOfSignature(sig); + return isTypeAny(instanceType) ? instanceType : getTypeOfPropertyOfType(instanceType, forcedLookupLocation); + } + function getStaticTypeOfReferencedJsxConstructor(context) { + if (isJsxIntrinsicIdentifier(context.tagName)) { + var result = getIntrinsicAttributesTypeFromJsxOpeningLikeElement(context); + var fakeSignature = createSignatureForJSXIntrinsic(context, result); + return getOrCreateTypeFromSignature(fakeSignature); + } + var tagType = checkExpressionCached(context.tagName); + if (tagType.flags & 128) { + var result = getIntrinsicAttributesTypeFromStringLiteralType(tagType, context); + if (!result) { + return errorType; + } + var fakeSignature = createSignatureForJSXIntrinsic(context, result); + return getOrCreateTypeFromSignature(fakeSignature); + } + return tagType; + } + function getJsxManagedAttributesFromLocatedAttributes(context, ns, attributesType) { + var managedSym = getJsxLibraryManagedAttributes(ns); + if (managedSym) { + var declaredManagedType = getDeclaredTypeOfSymbol(managedSym); + var ctorType = getStaticTypeOfReferencedJsxConstructor(context); + if (ts.length(declaredManagedType.typeParameters) >= 2) { + var args = fillMissingTypeArguments([ctorType, attributesType], declaredManagedType.typeParameters, 2, ts.isInJSFile(context)); + return createTypeReference(declaredManagedType, args); + } + else if (ts.length(declaredManagedType.aliasTypeArguments) >= 2) { + var args = fillMissingTypeArguments([ctorType, attributesType], declaredManagedType.aliasTypeArguments, 2, ts.isInJSFile(context)); + return getTypeAliasInstantiation(declaredManagedType.aliasSymbol, args); + } + } + return attributesType; + } + function getJsxPropsTypeFromClassType(sig, context) { + var ns = getJsxNamespaceAt(context); + var forcedLookupLocation = getJsxElementPropertiesName(ns); + var attributesType = forcedLookupLocation === undefined + ? getTypeOfFirstParameterOfSignatureWithFallback(sig, emptyObjectType) + : forcedLookupLocation === "" + ? getReturnTypeOfSignature(sig) + : getJsxPropsTypeForSignatureFromMember(sig, forcedLookupLocation); + if (!attributesType) { + if (!!forcedLookupLocation && !!ts.length(context.attributes.properties)) { + error(context, ts.Diagnostics.JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property, ts.unescapeLeadingUnderscores(forcedLookupLocation)); + } + return emptyObjectType; + } + attributesType = getJsxManagedAttributesFromLocatedAttributes(context, ns, attributesType); + if (isTypeAny(attributesType)) { + return attributesType; + } + else { + var apparentAttributesType = attributesType; + var intrinsicClassAttribs = getJsxType(JsxNames.IntrinsicClassAttributes, context); + if (intrinsicClassAttribs !== errorType) { + var typeParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(intrinsicClassAttribs.symbol); + var hostClassType = getReturnTypeOfSignature(sig); + apparentAttributesType = intersectTypes(typeParams + ? createTypeReference(intrinsicClassAttribs, fillMissingTypeArguments([hostClassType], typeParams, getMinTypeArgumentCount(typeParams), ts.isInJSFile(context))) + : intrinsicClassAttribs, apparentAttributesType); + } + var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes, context); + if (intrinsicAttribs !== errorType) { + apparentAttributesType = intersectTypes(intrinsicAttribs, apparentAttributesType); + } + return apparentAttributesType; + } + } + function getContextualCallSignature(type, node) { + var signatures = getSignaturesOfType(type, 0); + if (signatures.length === 1) { + var signature = signatures[0]; + if (!isAritySmaller(signature, node)) { + return signature; + } + } + } + function isAritySmaller(signature, target) { + var targetParameterCount = 0; + for (; targetParameterCount < target.parameters.length; targetParameterCount++) { + var param = target.parameters[targetParameterCount]; + if (param.initializer || param.questionToken || param.dotDotDotToken || isJSDocOptionalParameter(param)) { + break; + } + } + if (target.parameters.length && ts.parameterIsThisKeyword(target.parameters[0])) { + targetParameterCount--; + } + return !hasEffectiveRestParameter(signature) && getParameterCount(signature) < targetParameterCount; + } + function isFunctionExpressionOrArrowFunction(node) { + return node.kind === 196 || node.kind === 197; + } + function getContextualSignatureForFunctionLikeDeclaration(node) { + return isFunctionExpressionOrArrowFunction(node) || ts.isObjectLiteralMethod(node) + ? getContextualSignature(node) + : undefined; + } + function getContextualTypeForFunctionLikeDeclaration(node) { + return ts.isObjectLiteralMethod(node) ? + getContextualTypeForObjectLiteralMethod(node) : + getApparentTypeOfContextualType(node); + } + function getContextualSignature(node) { + ts.Debug.assert(node.kind !== 156 || ts.isObjectLiteralMethod(node)); + var typeTagSignature = getSignatureOfTypeTag(node); + if (typeTagSignature) { + return typeTagSignature; + } + var type = getContextualTypeForFunctionLikeDeclaration(node); + if (!type) { + return undefined; + } + if (!(type.flags & 1048576)) { + return getContextualCallSignature(type, node); + } + var signatureList; + var types = type.types; + for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { + var current = types_14[_i]; + var signature = getContextualCallSignature(current, node); + if (signature) { + if (!signatureList) { + signatureList = [signature]; + } + else if (!compareSignaturesIdentical(signatureList[0], signature, false, true, true, compareTypesIdentical)) { + return undefined; + } + else { + signatureList.push(signature); + } + } + } + var result; + if (signatureList) { + result = cloneSignature(signatureList[0]); + result.unionSignatures = signatureList; + } + return result; + } + function checkSpreadExpression(node, checkMode) { + if (languageVersion < 2 && compilerOptions.downlevelIteration) { + checkExternalEmitHelpers(node, 1536); + } + var arrayOrIterableType = checkExpression(node.expression, checkMode); + return checkIteratedTypeOrElementType(arrayOrIterableType, node.expression, false, false); + } + function hasDefaultValue(node) { + return (node.kind === 186 && !!node.initializer) || + (node.kind === 204 && node.operatorToken.kind === 59); + } + function checkArrayLiteral(node, checkMode, forceTuple) { + var elements = node.elements; + var elementCount = elements.length; + var hasNonEndingSpreadElement = false; + var elementTypes = []; + var inDestructuringPattern = ts.isAssignmentTarget(node); + var contextualType = getApparentTypeOfContextualType(node); + for (var index = 0; index < elementCount; index++) { + var e = elements[index]; + if (inDestructuringPattern && e.kind === 208) { + var restArrayType = checkExpression(e.expression, checkMode, forceTuple); + var restElementType = getIndexTypeOfType(restArrayType, 1) || + getIteratedTypeOrElementType(restArrayType, undefined, false, false, false); + if (restElementType) { + elementTypes.push(restElementType); + } + } + else { + var elementContextualType = getContextualTypeForElementExpression(contextualType, index); + var type = checkExpressionForMutableLocation(e, checkMode, elementContextualType, forceTuple); + elementTypes.push(type); + } + if (index < elementCount - 1 && e.kind === 208) { + hasNonEndingSpreadElement = true; + } + } + if (!hasNonEndingSpreadElement) { + var hasRestElement = elementCount > 0 && elements[elementCount - 1].kind === 208; + var minLength = elementCount - (hasRestElement ? 1 : 0); + var tupleResult = void 0; + if (inDestructuringPattern && minLength > 0) { + var type = cloneTypeReference(createTupleType(elementTypes, minLength, hasRestElement)); + type.pattern = node; + return type; + } + else if (tupleResult = getArrayLiteralTupleTypeIfApplicable(elementTypes, contextualType, hasRestElement, elementCount)) { + return tupleResult; + } + else if (forceTuple) { + return createTupleType(elementTypes, minLength, hasRestElement); + } + } + return getArrayLiteralType(elementTypes, 2); + } + function getArrayLiteralTupleTypeIfApplicable(elementTypes, contextualType, hasRestElement, elementCount) { + if (elementCount === void 0) { elementCount = elementTypes.length; } + if (contextualType && forEachType(contextualType, isTupleLikeType)) { + var minLength = elementCount - (hasRestElement ? 1 : 0); + var pattern = contextualType.pattern; + if (!hasRestElement && pattern && (pattern.kind === 185 || pattern.kind === 187)) { + var patternElements = pattern.elements; + for (var i = elementCount; i < patternElements.length; i++) { + var e = patternElements[i]; + if (hasDefaultValue(e)) { + elementTypes.push(contextualType.typeArguments[i]); + } + else if (i < patternElements.length - 1 || !(e.kind === 186 && e.dotDotDotToken || e.kind === 208)) { + if (e.kind !== 210) { + error(e, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); + } + elementTypes.push(strictNullChecks ? implicitNeverType : undefinedWideningType); + } + } + } + return createTupleType(elementTypes, minLength, hasRestElement); + } + } + function getArrayLiteralType(elementTypes, unionReduction) { + if (unionReduction === void 0) { unionReduction = 1; } + return createArrayType(elementTypes.length ? + getUnionType(elementTypes, unionReduction) : + strictNullChecks ? implicitNeverType : undefinedWideningType); + } + function isNumericName(name) { + switch (name.kind) { + case 149: + return isNumericComputedName(name); + case 72: + return isNumericLiteralName(name.escapedText); + case 8: + case 10: + return isNumericLiteralName(name.text); + default: + return false; + } + } + function isNumericComputedName(name) { + return isTypeAssignableToKind(checkComputedPropertyName(name), 296); + } + function isInfinityOrNaNString(name) { + return name === "Infinity" || name === "-Infinity" || name === "NaN"; + } + function isNumericLiteralName(name) { + return (+name).toString() === name; + } + function checkComputedPropertyName(node) { + var links = getNodeLinks(node.expression); + if (!links.resolvedType) { + links.resolvedType = checkExpression(node.expression); + if (links.resolvedType.flags & 98304 || + !isTypeAssignableToKind(links.resolvedType, 132 | 296 | 12288) && + !isTypeAssignableTo(links.resolvedType, stringNumberSymbolType)) { + error(node, ts.Diagnostics.A_computed_property_name_must_be_of_type_string_number_symbol_or_any); + } + else { + checkThatExpressionIsProperSymbolReference(node.expression, links.resolvedType, true); + } + } + return links.resolvedType; + } + function getObjectLiteralIndexInfo(propertyNodes, offset, properties, kind) { + var propTypes = []; + for (var i = 0; i < properties.length; i++) { + if (kind === 0 || isNumericName(propertyNodes[i + offset].name)) { + propTypes.push(getTypeOfSymbol(properties[i])); + } + } + var unionType = propTypes.length ? getUnionType(propTypes, 2) : undefinedType; + return createIndexInfo(unionType, false); + } + function getImmediateAliasedSymbol(symbol) { + ts.Debug.assert((symbol.flags & 2097152) !== 0, "Should only get Alias here."); + var links = getSymbolLinks(symbol); + if (!links.immediateTarget) { + var node = getDeclarationOfAliasSymbol(symbol); + if (!node) + return ts.Debug.fail(); + links.immediateTarget = getTargetOfAliasDeclaration(node, true); + } + return links.immediateTarget; + } + function checkObjectLiteral(node, checkMode) { + var inDestructuringPattern = ts.isAssignmentTarget(node); + checkGrammarObjectLiteralExpression(node, inDestructuringPattern); + var propertiesTable; + var propertiesArray = []; + var spread = emptyObjectType; + var propagatedFlags = 0; + var contextualType = getApparentTypeOfContextualType(node); + var contextualTypeHasPattern = contextualType && contextualType.pattern && + (contextualType.pattern.kind === 184 || contextualType.pattern.kind === 188); + var isInJavascript = ts.isInJSFile(node) && !ts.isInJsonFile(node); + var enumTag = ts.getJSDocEnumTag(node); + var isJSObjectLiteral = !contextualType && isInJavascript && !enumTag; + var typeFlags = 0; + var patternWithComputedProperties = false; + var hasComputedStringProperty = false; + var hasComputedNumberProperty = false; + propertiesTable = ts.createSymbolTable(); + var offset = 0; + for (var i = 0; i < node.properties.length; i++) { + var memberDecl = node.properties[i]; + var member = getSymbolOfNode(memberDecl); + var computedNameType = memberDecl.name && memberDecl.name.kind === 149 && !ts.isWellKnownSymbolSyntactically(memberDecl.name.expression) ? + checkComputedPropertyName(memberDecl.name) : undefined; + if (memberDecl.kind === 275 || + memberDecl.kind === 276 || + ts.isObjectLiteralMethod(memberDecl)) { + var type = memberDecl.kind === 275 ? checkPropertyAssignment(memberDecl, checkMode) : + memberDecl.kind === 276 ? checkExpressionForMutableLocation(memberDecl.name, checkMode) : + checkObjectLiteralMethod(memberDecl, checkMode); + if (isInJavascript) { + var jsDocType = getTypeForDeclarationFromJSDocComment(memberDecl); + if (jsDocType) { + checkTypeAssignableTo(type, jsDocType, memberDecl); + type = jsDocType; + } + else if (enumTag && enumTag.typeExpression) { + checkTypeAssignableTo(type, getTypeFromTypeNode(enumTag.typeExpression), memberDecl); + } + } + typeFlags |= type.flags; + var nameType = computedNameType && computedNameType.flags & 8576 ? + computedNameType : undefined; + var prop = nameType ? + createSymbol(4 | member.flags, getLateBoundNameFromType(nameType), 1024) : + createSymbol(4 | member.flags, member.escapedName); + if (nameType) { + prop.nameType = nameType; + } + if (inDestructuringPattern) { + var isOptional = (memberDecl.kind === 275 && hasDefaultValue(memberDecl.initializer)) || + (memberDecl.kind === 276 && memberDecl.objectAssignmentInitializer); + if (isOptional) { + prop.flags |= 16777216; + } + } + else if (contextualTypeHasPattern && !(ts.getObjectFlags(contextualType) & 512)) { + var impliedProp = getPropertyOfType(contextualType, member.escapedName); + if (impliedProp) { + prop.flags |= impliedProp.flags & 16777216; + } + else if (!compilerOptions.suppressExcessPropertyErrors && !getIndexInfoOfType(contextualType, 0)) { + error(memberDecl.name, ts.Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(member), typeToString(contextualType)); + } + } + prop.declarations = member.declarations; + prop.parent = member.parent; + if (member.valueDeclaration) { + prop.valueDeclaration = member.valueDeclaration; + } + prop.type = type; + prop.target = member; + member = prop; + } + else if (memberDecl.kind === 277) { + if (languageVersion < 2) { + checkExternalEmitHelpers(memberDecl, 2); + } + if (propertiesArray.length > 0) { + spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, propagatedFlags, 32768); + propertiesArray = []; + propertiesTable = ts.createSymbolTable(); + hasComputedStringProperty = false; + hasComputedNumberProperty = false; + typeFlags = 0; + } + var type = checkExpression(memberDecl.expression); + if (!isValidSpreadType(type)) { + error(memberDecl, ts.Diagnostics.Spread_types_may_only_be_created_from_object_types); + return errorType; + } + spread = getSpreadType(spread, type, node.symbol, propagatedFlags, 32768); + offset = i + 1; + continue; + } + else { + ts.Debug.assert(memberDecl.kind === 158 || memberDecl.kind === 159); + checkNodeDeferred(memberDecl); + } + if (computedNameType && !(computedNameType.flags & 8576)) { + if (isTypeAssignableTo(computedNameType, stringNumberSymbolType)) { + if (isTypeAssignableTo(computedNameType, numberType)) { + hasComputedNumberProperty = true; + } + else { + hasComputedStringProperty = true; + } + if (inDestructuringPattern) { + patternWithComputedProperties = true; + } + } + } + else { + propertiesTable.set(member.escapedName, member); + } + propertiesArray.push(member); + } + if (contextualTypeHasPattern) { + for (var _i = 0, _a = getPropertiesOfType(contextualType); _i < _a.length; _i++) { + var prop = _a[_i]; + if (!propertiesTable.get(prop.escapedName) && !(spread && getPropertyOfType(spread, prop.escapedName))) { + if (!(prop.flags & 16777216)) { + error(prop.valueDeclaration || prop.bindingElement, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); + } + propertiesTable.set(prop.escapedName, prop); + propertiesArray.push(prop); + } + } + } + if (spread !== emptyObjectType) { + if (propertiesArray.length > 0) { + spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, propagatedFlags, 32768); + } + return spread; + } + return createObjectLiteralType(); + function createObjectLiteralType() { + var stringIndexInfo = hasComputedStringProperty ? getObjectLiteralIndexInfo(node.properties, offset, propertiesArray, 0) : undefined; + var numberIndexInfo = hasComputedNumberProperty ? getObjectLiteralIndexInfo(node.properties, offset, propertiesArray, 1) : undefined; + var result = createAnonymousType(node.symbol, propertiesTable, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); + result.flags |= 268435456 | typeFlags & 939524096; + result.objectFlags |= 128 | freshObjectLiteralFlag; + if (isJSObjectLiteral) { + result.objectFlags |= 16384; + } + if (patternWithComputedProperties) { + result.objectFlags |= 512; + } + if (inDestructuringPattern) { + result.pattern = node; + } + propagatedFlags |= result.flags & 939524096; + return result; + } + } + function isValidSpreadType(type) { + return !!(type.flags & (3 | 67108864 | 524288 | 58982400) || + getFalsyFlags(type) & 117632 && isValidSpreadType(removeDefinitelyFalsyTypes(type)) || + type.flags & 3145728 && ts.every(type.types, isValidSpreadType)); + } + function checkJsxSelfClosingElementDeferred(node) { + checkJsxOpeningLikeElementOrOpeningFragment(node); + } + function checkJsxSelfClosingElement(node, _checkMode) { + checkNodeDeferred(node); + return getJsxElementTypeAt(node) || anyType; + } + function checkJsxElementDeferred(node) { + checkJsxOpeningLikeElementOrOpeningFragment(node.openingElement); + if (isJsxIntrinsicIdentifier(node.closingElement.tagName)) { + getIntrinsicTagSymbol(node.closingElement); + } + else { + checkExpression(node.closingElement.tagName); + } + checkJsxChildren(node); + } + function checkJsxElement(node, _checkMode) { + checkNodeDeferred(node); + return getJsxElementTypeAt(node) || anyType; + } + function checkJsxFragment(node) { + checkJsxOpeningLikeElementOrOpeningFragment(node.openingFragment); + if (compilerOptions.jsx === 2 && (compilerOptions.jsxFactory || ts.getSourceFileOfNode(node).pragmas.has("jsx"))) { + error(node, compilerOptions.jsxFactory + ? ts.Diagnostics.JSX_fragment_is_not_supported_when_using_jsxFactory + : ts.Diagnostics.JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma); + } + checkJsxChildren(node); + return getJsxElementTypeAt(node) || anyType; + } + function isUnhyphenatedJsxName(name) { + return !ts.stringContains(name, "-"); + } + function isJsxIntrinsicIdentifier(tagName) { + return tagName.kind === 72 && ts.isIntrinsicJsxName(tagName.escapedText); + } + function checkJsxAttribute(node, checkMode) { + return node.initializer + ? checkExpressionForMutableLocation(node.initializer, checkMode) + : trueType; + } + function createJsxAttributesTypeFromAttributesProperty(openingLikeElement, checkMode) { + var attributes = openingLikeElement.attributes; + var attributesTable = ts.createSymbolTable(); + var spread = emptyJsxObjectType; + var hasSpreadAnyType = false; + var typeToIntersect; + var explicitlySpecifyChildrenAttribute = false; + var typeFlags = 0; + var objectFlags = 4096; + var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(openingLikeElement)); + for (var _i = 0, _a = attributes.properties; _i < _a.length; _i++) { + var attributeDecl = _a[_i]; + var member = attributeDecl.symbol; + if (ts.isJsxAttribute(attributeDecl)) { + var exprType = checkJsxAttribute(attributeDecl, checkMode); + typeFlags |= exprType.flags & 939524096; + var attributeSymbol = createSymbol(4 | 33554432 | member.flags, member.escapedName); + attributeSymbol.declarations = member.declarations; + attributeSymbol.parent = member.parent; + if (member.valueDeclaration) { + attributeSymbol.valueDeclaration = member.valueDeclaration; + } + attributeSymbol.type = exprType; + attributeSymbol.target = member; + attributesTable.set(attributeSymbol.escapedName, attributeSymbol); + if (attributeDecl.name.escapedText === jsxChildrenPropertyName) { + explicitlySpecifyChildrenAttribute = true; + } + } + else { + ts.Debug.assert(attributeDecl.kind === 269); + if (attributesTable.size > 0) { + spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, typeFlags, objectFlags); + attributesTable = ts.createSymbolTable(); + } + var exprType = checkExpressionCached(attributeDecl.expression, checkMode); + if (isTypeAny(exprType)) { + hasSpreadAnyType = true; + } + if (isValidSpreadType(exprType)) { + spread = getSpreadType(spread, exprType, attributes.symbol, typeFlags, objectFlags); + } + else { + typeToIntersect = typeToIntersect ? getIntersectionType([typeToIntersect, exprType]) : exprType; + } + } + } + if (!hasSpreadAnyType) { + if (attributesTable.size > 0) { + spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, typeFlags, objectFlags); + } + } + var parent = openingLikeElement.parent.kind === 260 ? openingLikeElement.parent : undefined; + if (parent && parent.openingElement === openingLikeElement && parent.children.length > 0) { + var childrenTypes = checkJsxChildren(parent, checkMode); + if (!hasSpreadAnyType && jsxChildrenPropertyName && jsxChildrenPropertyName !== "") { + if (explicitlySpecifyChildrenAttribute) { + error(attributes, ts.Diagnostics._0_are_specified_twice_The_attribute_named_0_will_be_overwritten, ts.unescapeLeadingUnderscores(jsxChildrenPropertyName)); + } + var contextualType = getApparentTypeOfContextualType(openingLikeElement.attributes); + var childrenContextualType = contextualType && getTypeOfPropertyOfContextualType(contextualType, jsxChildrenPropertyName); + var childrenPropSymbol = createSymbol(4 | 33554432, jsxChildrenPropertyName); + childrenPropSymbol.type = childrenTypes.length === 1 ? + childrenTypes[0] : + (getArrayLiteralTupleTypeIfApplicable(childrenTypes, childrenContextualType, false) || createArrayType(getUnionType(childrenTypes))); + var childPropMap = ts.createSymbolTable(); + childPropMap.set(jsxChildrenPropertyName, childrenPropSymbol); + spread = getSpreadType(spread, createAnonymousType(attributes.symbol, childPropMap, ts.emptyArray, ts.emptyArray, undefined, undefined), attributes.symbol, typeFlags, objectFlags); + } + } + if (hasSpreadAnyType) { + return anyType; + } + if (typeToIntersect && spread !== emptyJsxObjectType) { + return getIntersectionType([typeToIntersect, spread]); + } + return typeToIntersect || (spread === emptyJsxObjectType ? createJsxAttributesType() : spread); + function createJsxAttributesType() { + objectFlags |= freshObjectLiteralFlag; + var result = createAnonymousType(attributes.symbol, attributesTable, ts.emptyArray, ts.emptyArray, undefined, undefined); + result.flags |= 268435456 | typeFlags; + result.objectFlags |= 128 | objectFlags; + return result; + } + } + function checkJsxChildren(node, checkMode) { + var childrenTypes = []; + for (var _i = 0, _a = node.children; _i < _a.length; _i++) { + var child = _a[_i]; + if (child.kind === 11) { + if (!child.containsOnlyWhiteSpaces) { + childrenTypes.push(stringType); + } + } + else { + childrenTypes.push(checkExpressionForMutableLocation(child, checkMode)); + } + } + return childrenTypes; + } + function checkJsxAttributes(node, checkMode) { + return createJsxAttributesTypeFromAttributesProperty(node.parent, checkMode); + } + function getJsxType(name, location) { + var namespace = getJsxNamespaceAt(location); + var exports = namespace && getExportsOfSymbol(namespace); + var typeSymbol = exports && getSymbol(exports, name, 67897832); + return typeSymbol ? getDeclaredTypeOfSymbol(typeSymbol) : errorType; + } + function getIntrinsicTagSymbol(node) { + var links = getNodeLinks(node); + if (!links.resolvedSymbol) { + var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements, node); + if (intrinsicElementsType !== errorType) { + if (!ts.isIdentifier(node.tagName)) + return ts.Debug.fail(); + var intrinsicProp = getPropertyOfType(intrinsicElementsType, node.tagName.escapedText); + if (intrinsicProp) { + links.jsxFlags |= 1; + return links.resolvedSymbol = intrinsicProp; + } + var indexSignatureType = getIndexTypeOfType(intrinsicElementsType, 0); + if (indexSignatureType) { + links.jsxFlags |= 2; + return links.resolvedSymbol = intrinsicElementsType.symbol; + } + error(node, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.idText(node.tagName), "JSX." + JsxNames.IntrinsicElements); + return links.resolvedSymbol = unknownSymbol; + } + else { + if (noImplicitAny) { + error(node, ts.Diagnostics.JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists, ts.unescapeLeadingUnderscores(JsxNames.IntrinsicElements)); + } + return links.resolvedSymbol = unknownSymbol; + } + } + return links.resolvedSymbol; + } + function getJsxNamespaceAt(location) { + var links = location && getNodeLinks(location); + if (links && links.jsxNamespace) { + return links.jsxNamespace; + } + if (!links || links.jsxNamespace !== false) { + var namespaceName = getJsxNamespace(location); + var resolvedNamespace = resolveName(location, namespaceName, 1920, undefined, namespaceName, false); + if (resolvedNamespace) { + var candidate = getSymbol(getExportsOfSymbol(resolveSymbol(resolvedNamespace)), JsxNames.JSX, 1920); + if (candidate) { + if (links) { + links.jsxNamespace = candidate; + } + return candidate; + } + if (links) { + links.jsxNamespace = false; + } + } + } + return getGlobalSymbol(JsxNames.JSX, 1920, undefined); + } + function getNameFromJsxElementAttributesContainer(nameOfAttribPropContainer, jsxNamespace) { + var jsxElementAttribPropInterfaceSym = jsxNamespace && getSymbol(jsxNamespace.exports, nameOfAttribPropContainer, 67897832); + var jsxElementAttribPropInterfaceType = jsxElementAttribPropInterfaceSym && getDeclaredTypeOfSymbol(jsxElementAttribPropInterfaceSym); + var propertiesOfJsxElementAttribPropInterface = jsxElementAttribPropInterfaceType && getPropertiesOfType(jsxElementAttribPropInterfaceType); + if (propertiesOfJsxElementAttribPropInterface) { + if (propertiesOfJsxElementAttribPropInterface.length === 0) { + return ""; + } + else if (propertiesOfJsxElementAttribPropInterface.length === 1) { + return propertiesOfJsxElementAttribPropInterface[0].escapedName; + } + else if (propertiesOfJsxElementAttribPropInterface.length > 1) { + error(jsxElementAttribPropInterfaceSym.declarations[0], ts.Diagnostics.The_global_type_JSX_0_may_not_have_more_than_one_property, ts.unescapeLeadingUnderscores(nameOfAttribPropContainer)); + } + } + return undefined; + } + function getJsxLibraryManagedAttributes(jsxNamespace) { + return jsxNamespace && getSymbol(jsxNamespace.exports, JsxNames.LibraryManagedAttributes, 67897832); + } + function getJsxElementPropertiesName(jsxNamespace) { + return getNameFromJsxElementAttributesContainer(JsxNames.ElementAttributesPropertyNameContainer, jsxNamespace); + } + function getJsxElementChildrenPropertyName(jsxNamespace) { + return getNameFromJsxElementAttributesContainer(JsxNames.ElementChildrenAttributeNameContainer, jsxNamespace); + } + function getUninstantiatedJsxSignaturesOfType(elementType, caller) { + if (elementType.flags & 4) { + return [anySignature]; + } + else if (elementType.flags & 128) { + var intrinsicType = getIntrinsicAttributesTypeFromStringLiteralType(elementType, caller); + if (!intrinsicType) { + error(caller, ts.Diagnostics.Property_0_does_not_exist_on_type_1, elementType.value, "JSX." + JsxNames.IntrinsicElements); + return ts.emptyArray; + } + else { + var fakeSignature = createSignatureForJSXIntrinsic(caller, intrinsicType); + return [fakeSignature]; + } + } + var apparentElemType = getApparentType(elementType); + var signatures = getSignaturesOfType(apparentElemType, 1); + if (signatures.length === 0) { + signatures = getSignaturesOfType(apparentElemType, 0); + } + if (signatures.length === 0 && apparentElemType.flags & 1048576) { + signatures = getUnionSignatures(ts.map(apparentElemType.types, function (t) { return getUninstantiatedJsxSignaturesOfType(t, caller); })); + } + return signatures; + } + function getIntrinsicAttributesTypeFromStringLiteralType(type, location) { + var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements, location); + if (intrinsicElementsType !== errorType) { + var stringLiteralTypeName = type.value; + var intrinsicProp = getPropertyOfType(intrinsicElementsType, ts.escapeLeadingUnderscores(stringLiteralTypeName)); + if (intrinsicProp) { + return getTypeOfSymbol(intrinsicProp); + } + var indexSignatureType = getIndexTypeOfType(intrinsicElementsType, 0); + if (indexSignatureType) { + return indexSignatureType; + } + return undefined; + } + return anyType; + } + function checkJsxReturnAssignableToAppropriateBound(refKind, elemInstanceType, openingLikeElement) { + if (refKind === 1) { + var sfcReturnConstraint = getJsxStatelessElementTypeAt(openingLikeElement); + if (sfcReturnConstraint) { + checkTypeRelatedTo(elemInstanceType, sfcReturnConstraint, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); + } + } + else if (refKind === 0) { + var classConstraint = getJsxElementClassTypeAt(openingLikeElement); + if (classConstraint) { + checkTypeRelatedTo(elemInstanceType, classConstraint, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); + } + } + else { + var sfcReturnConstraint = getJsxStatelessElementTypeAt(openingLikeElement); + var classConstraint = getJsxElementClassTypeAt(openingLikeElement); + if (!sfcReturnConstraint || !classConstraint) { + return; + } + var combined = getUnionType([sfcReturnConstraint, classConstraint]); + checkTypeRelatedTo(elemInstanceType, combined, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); + } + } + function getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node) { + ts.Debug.assert(isJsxIntrinsicIdentifier(node.tagName)); + var links = getNodeLinks(node); + if (!links.resolvedJsxElementAttributesType) { + var symbol = getIntrinsicTagSymbol(node); + if (links.jsxFlags & 1) { + return links.resolvedJsxElementAttributesType = getTypeOfSymbol(symbol); + } + else if (links.jsxFlags & 2) { + return links.resolvedJsxElementAttributesType = getIndexInfoOfSymbol(symbol, 0).type; + } + else { + return links.resolvedJsxElementAttributesType = errorType; + } + } + return links.resolvedJsxElementAttributesType; + } + function getJsxElementClassTypeAt(location) { + var type = getJsxType(JsxNames.ElementClass, location); + if (type === errorType) + return undefined; + return type; + } + function getJsxElementTypeAt(location) { + return getJsxType(JsxNames.Element, location); + } + function getJsxStatelessElementTypeAt(location) { + var jsxElementType = getJsxElementTypeAt(location); + if (jsxElementType) { + return getUnionType([jsxElementType, nullType]); + } + } + function getJsxIntrinsicTagNamesAt(location) { + var intrinsics = getJsxType(JsxNames.IntrinsicElements, location); + return intrinsics ? getPropertiesOfType(intrinsics) : ts.emptyArray; + } + function checkJsxPreconditions(errorNode) { + if ((compilerOptions.jsx || 0) === 0) { + error(errorNode, ts.Diagnostics.Cannot_use_JSX_unless_the_jsx_flag_is_provided); + } + if (getJsxElementTypeAt(errorNode) === undefined) { + if (noImplicitAny) { + error(errorNode, ts.Diagnostics.JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist); + } + } + } + function checkJsxOpeningLikeElementOrOpeningFragment(node) { + var isNodeOpeningLikeElement = ts.isJsxOpeningLikeElement(node); + if (isNodeOpeningLikeElement) { + checkGrammarJsxElement(node); + } + checkJsxPreconditions(node); + var reactRefErr = diagnostics && compilerOptions.jsx === 2 ? ts.Diagnostics.Cannot_find_name_0 : undefined; + var reactNamespace = getJsxNamespace(node); + var reactLocation = isNodeOpeningLikeElement ? node.tagName : node; + var reactSym = resolveName(reactLocation, reactNamespace, 67220415, reactRefErr, reactNamespace, true); + if (reactSym) { + reactSym.isReferenced = 67108863; + if (reactSym.flags & 2097152 && !isConstEnumOrConstEnumOnlyModule(resolveAlias(reactSym))) { + markAliasSymbolAsReferenced(reactSym); + } + } + if (isNodeOpeningLikeElement) { + var sig = getResolvedSignature(node); + checkJsxReturnAssignableToAppropriateBound(getJsxReferenceKind(node), getReturnTypeOfSignature(sig), node); + } + } + function isKnownProperty(targetType, name, isComparingJsxAttributes) { + if (targetType.flags & 524288) { + var resolved = resolveStructuredTypeMembers(targetType); + if (resolved.stringIndexInfo || + resolved.numberIndexInfo && isNumericLiteralName(name) || + getPropertyOfObjectType(targetType, name) || + isComparingJsxAttributes && !isUnhyphenatedJsxName(name)) { + return true; + } + } + else if (targetType.flags & 3145728) { + for (var _i = 0, _a = targetType.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (isKnownProperty(t, name, isComparingJsxAttributes)) { + return true; + } + } + } + else if (targetType.flags & 16777216) { + return isKnownProperty(targetType.root.trueType, name, isComparingJsxAttributes) || + isKnownProperty(targetType.root.falseType, name, isComparingJsxAttributes); + } + return false; + } + function checkJsxExpression(node, checkMode) { + if (node.expression) { + var type = checkExpression(node.expression, checkMode); + if (node.dotDotDotToken && type !== anyType && !isArrayType(type)) { + error(node, ts.Diagnostics.JSX_spread_child_must_be_an_array_type); + } + return type; + } + else { + return errorType; + } + } + function getDeclarationNodeFlagsFromSymbol(s) { + return s.valueDeclaration ? ts.getCombinedNodeFlags(s.valueDeclaration) : 0; + } + function isPrototypeProperty(symbol) { + if (symbol.flags & 8192 || ts.getCheckFlags(symbol) & 4) { + return true; + } + if (ts.isInJSFile(symbol.valueDeclaration)) { + var parent = symbol.valueDeclaration.parent; + return parent && ts.isBinaryExpression(parent) && + ts.getAssignmentDeclarationKind(parent) === 3; + } + } + function checkPropertyAccessibility(node, isSuper, type, prop) { + var flags = ts.getDeclarationModifierFlagsFromSymbol(prop); + var errorNode = node.kind === 148 ? node.right : node.kind === 183 ? node : node.name; + if (ts.getCheckFlags(prop) & 256) { + error(errorNode, ts.Diagnostics.Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1, symbolToString(prop), typeToString(type)); + return false; + } + if (isSuper) { + if (languageVersion < 2) { + if (symbolHasNonMethodDeclaration(prop)) { + error(errorNode, ts.Diagnostics.Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword); + return false; + } + } + if (flags & 128) { + error(errorNode, ts.Diagnostics.Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression, symbolToString(prop), typeToString(getDeclaringClass(prop))); + return false; + } + } + if ((flags & 128) && ts.isThisProperty(node) && symbolHasNonMethodDeclaration(prop)) { + var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop)); + if (declaringClassDeclaration && isNodeUsedDuringClassInitialization(node)) { + error(errorNode, ts.Diagnostics.Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor, symbolToString(prop), ts.getTextOfIdentifierOrLiteral(declaringClassDeclaration.name)); + return false; + } + } + if (!(flags & 24)) { + return true; + } + if (flags & 8) { + var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop)); + if (!isNodeWithinClass(node, declaringClassDeclaration)) { + error(errorNode, ts.Diagnostics.Property_0_is_private_and_only_accessible_within_class_1, symbolToString(prop), typeToString(getDeclaringClass(prop))); + return false; + } + return true; + } + if (isSuper) { + return true; + } + var enclosingClass = forEachEnclosingClass(node, function (enclosingDeclaration) { + var enclosingClass = getDeclaredTypeOfSymbol(getSymbolOfNode(enclosingDeclaration)); + return isClassDerivedFromDeclaringClasses(enclosingClass, prop) ? enclosingClass : undefined; + }); + if (!enclosingClass) { + var thisParameter = void 0; + if (flags & 32 || !(thisParameter = getThisParameterFromNodeContext(node)) || !thisParameter.type) { + error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses, symbolToString(prop), typeToString(getDeclaringClass(prop) || type)); + return false; + } + var thisType = getTypeFromTypeNode(thisParameter.type); + enclosingClass = ((thisType.flags & 262144) ? getConstraintOfTypeParameter(thisType) : thisType); + } + if (flags & 32) { + return true; + } + if (type.flags & 262144) { + type = type.isThisType ? getConstraintOfTypeParameter(type) : getBaseConstraintOfType(type); + } + if (!type || !hasBaseType(type, enclosingClass)) { + error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1, symbolToString(prop), typeToString(enclosingClass)); + return false; + } + return true; + } + function getThisParameterFromNodeContext(node) { + var thisContainer = ts.getThisContainer(node, false); + return thisContainer && ts.isFunctionLike(thisContainer) ? ts.getThisParameter(thisContainer) : undefined; + } + function symbolHasNonMethodDeclaration(symbol) { + return !!forEachProperty(symbol, function (prop) { return !(prop.flags & 8192); }); + } + function checkNonNullExpression(node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic) { + return checkNonNullType(checkExpression(node), node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic); + } + function getNonNullableTypeIfNeeded(type) { + var kind = (strictNullChecks ? getFalsyFlags(type) : type.flags) & 98304; + if (kind) { + return getNonNullableType(type); + } + return type; + } + function checkNonNullType(type, node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic) { + if (type.flags & 2) { + error(node, ts.Diagnostics.Object_is_of_type_unknown); + return errorType; + } + var kind = (strictNullChecks ? getFalsyFlags(type) : type.flags) & 98304; + if (kind) { + error(node, kind & 32768 ? kind & 65536 ? + (nullOrUndefinedDiagnostic || ts.Diagnostics.Object_is_possibly_null_or_undefined) : + (undefinedDiagnostic || ts.Diagnostics.Object_is_possibly_undefined) : + (nullDiagnostic || ts.Diagnostics.Object_is_possibly_null)); + var t = getNonNullableType(type); + return t.flags & (98304 | 131072) ? errorType : t; + } + return type; + } + function checkPropertyAccessExpression(node) { + return checkPropertyAccessExpressionOrQualifiedName(node, node.expression, node.name); + } + function checkQualifiedName(node) { + return checkPropertyAccessExpressionOrQualifiedName(node, node.left, node.right); + } + function checkPropertyAccessExpressionOrQualifiedName(node, left, right) { + var propType; + var leftType = checkNonNullExpression(left); + var parentSymbol = getNodeLinks(left).resolvedSymbol; + var apparentType = getApparentType(getWidenedType(leftType)); + if (isTypeAny(apparentType) || apparentType === silentNeverType) { + if (ts.isIdentifier(left) && parentSymbol) { + markAliasReferenced(parentSymbol, node); + } + return apparentType; + } + var assignmentKind = ts.getAssignmentTargetKind(node); + var prop = getPropertyOfType(apparentType, right.escapedText); + if (ts.isIdentifier(left) && parentSymbol && !(prop && isConstEnumOrConstEnumOnlyModule(prop))) { + markAliasReferenced(parentSymbol, node); + } + if (!prop) { + var indexInfo = getIndexInfoOfType(apparentType, 0); + if (!(indexInfo && indexInfo.type)) { + if (isJSLiteralType(leftType)) { + return anyType; + } + if (right.escapedText && !checkAndReportErrorForExtendingInterface(node)) { + reportNonexistentProperty(right, leftType.flags & 262144 && leftType.isThisType ? apparentType : leftType); + } + return errorType; + } + if (indexInfo.isReadonly && (ts.isAssignmentTarget(node) || ts.isDeleteTarget(node))) { + error(node, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(apparentType)); + } + propType = indexInfo.type; + } + else { + checkPropertyNotUsedBeforeDeclaration(prop, node, right); + markPropertyAsReferenced(prop, node, left.kind === 100); + getNodeLinks(node).resolvedSymbol = prop; + checkPropertyAccessibility(node, left.kind === 98, apparentType, prop); + if (assignmentKind) { + if (isReferenceToReadonlyEntity(node, prop) || isReferenceThroughNamespaceImport(node)) { + error(right, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, ts.idText(right)); + return errorType; + } + } + propType = getConstraintForLocation(getTypeOfSymbol(prop), node); + } + if (node.kind !== 189 || + assignmentKind === 1 || + prop && !(prop.flags & (3 | 4 | 98304)) && !(prop.flags & 8192 && propType.flags & 1048576)) { + return propType; + } + var assumeUninitialized = false; + if (strictNullChecks && strictPropertyInitialization && left.kind === 100) { + var declaration = prop && prop.valueDeclaration; + if (declaration && isInstancePropertyWithoutInitializer(declaration)) { + var flowContainer = getControlFlowContainer(node); + if (flowContainer.kind === 157 && flowContainer.parent === declaration.parent) { + assumeUninitialized = true; + } + } + } + else if (strictNullChecks && prop && prop.valueDeclaration && + ts.isPropertyAccessExpression(prop.valueDeclaration) && + ts.getAssignmentDeclarationPropertyAccessKind(prop.valueDeclaration) && + getControlFlowContainer(node) === getControlFlowContainer(prop.valueDeclaration)) { + assumeUninitialized = true; + } + var flowType = getFlowTypeOfReference(node, propType, assumeUninitialized ? getOptionalType(propType) : propType); + if (assumeUninitialized && !(getFalsyFlags(propType) & 32768) && getFalsyFlags(flowType) & 32768) { + error(right, ts.Diagnostics.Property_0_is_used_before_being_assigned, symbolToString(prop)); + return propType; + } + return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType; + } + function checkPropertyNotUsedBeforeDeclaration(prop, node, right) { + var valueDeclaration = prop.valueDeclaration; + if (!valueDeclaration) { + return; + } + var diagnosticMessage; + var declarationName = ts.idText(right); + if (isInPropertyInitializer(node) && + !isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right) + && !isPropertyDeclaredInAncestorClass(prop)) { + diagnosticMessage = error(right, ts.Diagnostics.Property_0_is_used_before_its_initialization, declarationName); + } + else if (valueDeclaration.kind === 240 && + node.parent.kind !== 164 && + !(valueDeclaration.flags & 4194304) && + !isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right)) { + diagnosticMessage = error(right, ts.Diagnostics.Class_0_used_before_its_declaration, declarationName); + } + if (diagnosticMessage) { + addRelatedInfo(diagnosticMessage, ts.createDiagnosticForNode(valueDeclaration, ts.Diagnostics._0_is_declared_here, declarationName)); + } + } + function isInPropertyInitializer(node) { + return !!ts.findAncestor(node, function (node) { + switch (node.kind) { + case 154: + return true; + case 275: + return false; + default: + return ts.isExpressionNode(node) ? false : "quit"; + } + }); + } + function isPropertyDeclaredInAncestorClass(prop) { + if (!(prop.parent.flags & 32)) { + return false; + } + var classType = getTypeOfSymbol(prop.parent); + while (true) { + classType = classType.symbol && getSuperClass(classType); + if (!classType) { + return false; + } + var superProperty = getPropertyOfType(classType, prop.escapedName); + if (superProperty && superProperty.valueDeclaration) { + return true; + } + } + } + function getSuperClass(classType) { + var x = getBaseTypes(classType); + if (x.length === 0) { + return undefined; + } + return getIntersectionType(x); + } + function reportNonexistentProperty(propNode, containingType) { + var errorInfo; + var relatedInfo; + if (containingType.flags & 1048576 && !(containingType.flags & 131068)) { + for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) { + var subtype = _a[_i]; + if (!getPropertyOfType(subtype, propNode.escapedText)) { + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(subtype)); + break; + } + } + } + if (typeHasStaticProperty(propNode.escapedText, containingType)) { + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_is_a_static_member_of_type_1, ts.declarationNameToString(propNode), typeToString(containingType)); + } + else { + var promisedType = getPromisedTypeOfPromise(containingType); + if (promisedType && getPropertyOfType(promisedType, propNode.escapedText)) { + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_forget_to_use_await, ts.declarationNameToString(propNode), typeToString(containingType)); + } + else { + var suggestion = getSuggestedSymbolForNonexistentProperty(propNode, containingType); + if (suggestion !== undefined) { + var suggestedName = ts.symbolName(suggestion); + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2, ts.declarationNameToString(propNode), typeToString(containingType), suggestedName); + relatedInfo = suggestion.valueDeclaration && ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestedName); + } + else { + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(containingType)); + } + } + } + var resultDiagnostic = ts.createDiagnosticForNodeFromMessageChain(propNode, errorInfo); + if (relatedInfo) { + addRelatedInfo(resultDiagnostic, relatedInfo); + } + diagnostics.add(resultDiagnostic); + } + function typeHasStaticProperty(propName, containingType) { + var prop = containingType.symbol && getPropertyOfType(getTypeOfSymbol(containingType.symbol), propName); + return prop !== undefined && prop.valueDeclaration && ts.hasModifier(prop.valueDeclaration, 32); + } + function getSuggestedSymbolForNonexistentProperty(name, containingType) { + return getSpellingSuggestionForName(ts.isString(name) ? name : ts.idText(name), getPropertiesOfType(containingType), 67220415); + } + function getSuggestionForNonexistentProperty(name, containingType) { + var suggestion = getSuggestedSymbolForNonexistentProperty(name, containingType); + return suggestion && ts.symbolName(suggestion); + } + function getSuggestedSymbolForNonexistentSymbol(location, outerName, meaning) { + ts.Debug.assert(outerName !== undefined, "outername should always be defined"); + var result = resolveNameHelper(location, outerName, meaning, undefined, outerName, false, false, function (symbols, name, meaning) { + ts.Debug.assertEqual(outerName, name, "name should equal outerName"); + var symbol = getSymbol(symbols, name, meaning); + return symbol || getSpellingSuggestionForName(ts.unescapeLeadingUnderscores(name), ts.arrayFrom(symbols.values()), meaning); + }); + return result; + } + function getSuggestionForNonexistentSymbol(location, outerName, meaning) { + var symbolResult = getSuggestedSymbolForNonexistentSymbol(location, outerName, meaning); + return symbolResult && ts.symbolName(symbolResult); + } + function getSuggestedSymbolForNonexistentModule(name, targetModule) { + return targetModule.exports && getSpellingSuggestionForName(ts.idText(name), getExportsOfModuleAsArray(targetModule), 2623475); + } + function getSuggestionForNonexistentExport(name, targetModule) { + var suggestion = getSuggestedSymbolForNonexistentModule(name, targetModule); + return suggestion && ts.symbolName(suggestion); + } + function getSpellingSuggestionForName(name, symbols, meaning) { + return ts.getSpellingSuggestion(name, symbols, getCandidateName); + function getCandidateName(candidate) { + var candidateName = ts.symbolName(candidate); + return !ts.startsWith(candidateName, "\"") && candidate.flags & meaning ? candidateName : undefined; + } + } + function markPropertyAsReferenced(prop, nodeForCheckWriteOnly, isThisAccess) { + if (!prop || !(prop.flags & 106500) || !prop.valueDeclaration || !ts.hasModifier(prop.valueDeclaration, 8)) { + return; + } + if (nodeForCheckWriteOnly && ts.isWriteOnlyAccess(nodeForCheckWriteOnly) && !(prop.flags & 65536 && !(prop.flags & 32768))) { + return; + } + if (isThisAccess) { + var containingMethod = ts.findAncestor(nodeForCheckWriteOnly, ts.isFunctionLikeDeclaration); + if (containingMethod && containingMethod.symbol === prop) { + return; + } + } + (ts.getCheckFlags(prop) & 1 ? getSymbolLinks(prop).target : prop).isReferenced = 67108863; + } + function isValidPropertyAccess(node, propertyName) { + switch (node.kind) { + case 189: + return isValidPropertyAccessWithType(node, node.expression.kind === 98, propertyName, getWidenedType(checkExpression(node.expression))); + case 148: + return isValidPropertyAccessWithType(node, false, propertyName, getWidenedType(checkExpression(node.left))); + case 183: + return isValidPropertyAccessWithType(node, false, propertyName, getTypeFromTypeNode(node)); + } + } + function isValidPropertyAccessForCompletions(node, type, property) { + return isValidPropertyAccessWithType(node, node.kind !== 183 && node.expression.kind === 98, property.escapedName, type) + && (!(property.flags & 8192) || isValidMethodAccess(property, type)); + } + function isValidMethodAccess(method, actualThisType) { + var propType = getTypeOfPropertyOfType(actualThisType, method.escapedName); + var signatures = getSignaturesOfType(getNonNullableType(propType), 0); + ts.Debug.assert(signatures.length !== 0); + return signatures.some(function (sig) { + var signatureThisType = getThisTypeOfSignature(sig); + return !signatureThisType || isTypeAssignableTo(actualThisType, getInstantiatedSignatureThisType(sig, signatureThisType, actualThisType)); + }); + } + function getInstantiatedSignatureThisType(sig, signatureThisType, actualThisType) { + if (!sig.typeParameters) { + return signatureThisType; + } + var context = createInferenceContext(sig.typeParameters, sig, 0); + inferTypes(context.inferences, actualThisType, signatureThisType); + return instantiateType(signatureThisType, createSignatureTypeMapper(sig, getInferredTypes(context))); + } + function isValidPropertyAccessWithType(node, isSuper, propertyName, type) { + if (type === errorType || isTypeAny(type)) { + return true; + } + var prop = getPropertyOfType(type, propertyName); + return prop ? checkPropertyAccessibility(node, isSuper, type, prop) + : ts.isInJSFile(node) && (type.flags & 1048576) !== 0 && type.types.some(function (elementType) { return isValidPropertyAccessWithType(node, isSuper, propertyName, elementType); }); + } + function getForInVariableSymbol(node) { + var initializer = node.initializer; + if (initializer.kind === 238) { + var variable = initializer.declarations[0]; + if (variable && !ts.isBindingPattern(variable.name)) { + return getSymbolOfNode(variable); + } + } + else if (initializer.kind === 72) { + return getResolvedSymbol(initializer); + } + return undefined; + } + function hasNumericPropertyNames(type) { + return getIndexTypeOfType(type, 1) && !getIndexTypeOfType(type, 0); + } + function isForInVariableForNumericPropertyNames(expr) { + var e = ts.skipParentheses(expr); + if (e.kind === 72) { + var symbol = getResolvedSymbol(e); + if (symbol.flags & 3) { + var child = expr; + var node = expr.parent; + while (node) { + if (node.kind === 226 && + child === node.statement && + getForInVariableSymbol(node) === symbol && + hasNumericPropertyNames(getTypeOfExpression(node.expression))) { + return true; + } + child = node; + node = node.parent; + } + } + } + return false; + } + function checkIndexedAccess(node) { + var objectType = checkNonNullExpression(node.expression); + var indexExpression = node.argumentExpression; + if (!indexExpression) { + var sourceFile = ts.getSourceFileOfNode(node); + if (node.parent.kind === 192 && node.parent.expression === node) { + var start = ts.skipTrivia(sourceFile.text, node.expression.end); + var end = node.end; + grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead); + } + else { + var start = node.end - "]".length; + var end = node.end; + grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.Expression_expected); + } + return errorType; + } + var indexType = checkExpression(indexExpression); + if (objectType === errorType || objectType === silentNeverType) { + return objectType; + } + if (isConstEnumObjectType(objectType) && indexExpression.kind !== 10) { + error(indexExpression, ts.Diagnostics.A_const_enum_member_can_only_be_accessed_using_a_string_literal); + return errorType; + } + return checkIndexedAccessIndexType(getIndexedAccessType(objectType, isForInVariableForNumericPropertyNames(indexExpression) ? numberType : indexType, node), node); + } + function checkThatExpressionIsProperSymbolReference(expression, expressionType, reportError) { + if (expressionType === errorType) { + return false; + } + if (!ts.isWellKnownSymbolSyntactically(expression)) { + return false; + } + if ((expressionType.flags & 12288) === 0) { + if (reportError) { + error(expression, ts.Diagnostics.A_computed_property_name_of_the_form_0_must_be_of_type_symbol, ts.getTextOfNode(expression)); + } + return false; + } + var leftHandSide = expression.expression; + var leftHandSideSymbol = getResolvedSymbol(leftHandSide); + if (!leftHandSideSymbol) { + return false; + } + var globalESSymbol = getGlobalESSymbolConstructorSymbol(true); + if (!globalESSymbol) { + return false; + } + if (leftHandSideSymbol !== globalESSymbol) { + if (reportError) { + error(leftHandSide, ts.Diagnostics.Symbol_reference_does_not_refer_to_the_global_Symbol_constructor_object); + } + return false; + } + return true; + } + function callLikeExpressionMayHaveTypeArguments(node) { + return ts.isCallOrNewExpression(node) || ts.isTaggedTemplateExpression(node) || ts.isJsxOpeningLikeElement(node); + } + function resolveUntypedCall(node) { + if (callLikeExpressionMayHaveTypeArguments(node)) { + ts.forEach(node.typeArguments, checkSourceElement); + } + if (node.kind === 193) { + checkExpression(node.template); + } + else if (ts.isJsxOpeningLikeElement(node)) { + checkExpression(node.attributes); + } + else if (node.kind !== 152) { + ts.forEach(node.arguments, function (argument) { + checkExpression(argument); + }); + } + return anySignature; + } + function resolveErrorCall(node) { + resolveUntypedCall(node); + return unknownSignature; + } + function reorderCandidates(signatures, result) { + var lastParent; + var lastSymbol; + var cutoffIndex = 0; + var index; + var specializedIndex = -1; + var spliceIndex; + ts.Debug.assert(!result.length); + for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { + var signature = signatures_3[_i]; + var symbol = signature.declaration && getSymbolOfNode(signature.declaration); + var parent = signature.declaration && signature.declaration.parent; + if (!lastSymbol || symbol === lastSymbol) { + if (lastParent && parent === lastParent) { + index = index + 1; + } + else { + lastParent = parent; + index = cutoffIndex; + } + } + else { + index = cutoffIndex = result.length; + lastParent = parent; + } + lastSymbol = symbol; + if (signature.hasLiteralTypes) { + specializedIndex++; + spliceIndex = specializedIndex; + cutoffIndex++; + } + else { + spliceIndex = index; + } + result.splice(spliceIndex, 0, signature); + } + } + function isSpreadArgument(arg) { + return !!arg && (arg.kind === 208 || arg.kind === 215 && arg.isSpread); + } + function getSpreadArgumentIndex(args) { + return ts.findIndex(args, isSpreadArgument); + } + function acceptsVoid(t) { + return !!(t.flags & 16384); + } + function hasCorrectArity(node, args, signature, signatureHelpTrailingComma) { + if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; } + var argCount; + var callIsIncomplete = false; + var effectiveParameterCount = getParameterCount(signature); + var effectiveMinimumArguments = getMinArgumentCount(signature); + if (node.kind === 193) { + argCount = args.length; + if (node.template.kind === 206) { + var lastSpan = ts.last(node.template.templateSpans); + callIsIncomplete = ts.nodeIsMissing(lastSpan.literal) || !!lastSpan.literal.isUnterminated; + } + else { + var templateLiteral = node.template; + ts.Debug.assert(templateLiteral.kind === 14); + callIsIncomplete = !!templateLiteral.isUnterminated; + } + } + else if (node.kind === 152) { + argCount = getDecoratorArgumentCount(node, signature); + } + else if (ts.isJsxOpeningLikeElement(node)) { + callIsIncomplete = node.attributes.end === node.end; + if (callIsIncomplete) { + return true; + } + argCount = effectiveMinimumArguments === 0 ? args.length : 1; + effectiveParameterCount = args.length === 0 ? effectiveParameterCount : 1; + effectiveMinimumArguments = Math.min(effectiveMinimumArguments, 1); + } + else { + if (!node.arguments) { + ts.Debug.assert(node.kind === 192); + return getMinArgumentCount(signature) === 0; + } + argCount = signatureHelpTrailingComma ? args.length + 1 : args.length; + callIsIncomplete = node.arguments.end === node.end; + var spreadArgIndex = getSpreadArgumentIndex(args); + if (spreadArgIndex >= 0) { + return spreadArgIndex >= getMinArgumentCount(signature) && (hasEffectiveRestParameter(signature) || spreadArgIndex < getParameterCount(signature)); + } + } + if (!hasEffectiveRestParameter(signature) && argCount > effectiveParameterCount) { + return false; + } + if (callIsIncomplete || argCount >= effectiveMinimumArguments) { + return true; + } + for (var i = argCount; i < effectiveMinimumArguments; i++) { + var type = getTypeAtPosition(signature, i); + if (filterType(type, acceptsVoid).flags & 131072) { + return false; + } + } + return true; + } + function hasCorrectTypeArgumentArity(signature, typeArguments) { + var numTypeParameters = ts.length(signature.typeParameters); + var minTypeArgumentCount = getMinTypeArgumentCount(signature.typeParameters); + return !typeArguments || + (typeArguments.length >= minTypeArgumentCount && typeArguments.length <= numTypeParameters); + } + function getSingleCallSignature(type) { + if (type.flags & 524288) { + var resolved = resolveStructuredTypeMembers(type); + if (resolved.callSignatures.length === 1 && resolved.constructSignatures.length === 0 && + resolved.properties.length === 0 && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { + return resolved.callSignatures[0]; + } + } + return undefined; + } + function instantiateSignatureInContextOf(signature, contextualSignature, contextualMapper, compareTypes) { + var context = createInferenceContext(signature.typeParameters, signature, 0, compareTypes); + var sourceSignature = contextualMapper ? instantiateSignature(contextualSignature, contextualMapper) : contextualSignature; + forEachMatchingParameterType(sourceSignature, signature, function (source, target) { + inferTypes(context.inferences, source, target); + }); + if (!contextualMapper) { + inferTypes(context.inferences, getReturnTypeOfSignature(contextualSignature), getReturnTypeOfSignature(signature), 8); + } + return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJSFile(contextualSignature.declaration)); + } + function inferJsxTypeArguments(node, signature, excludeArgument, context) { + var paramType = getEffectiveFirstArgumentForJsxSignature(signature, node); + var checkAttrType = checkExpressionWithContextualType(node.attributes, paramType, excludeArgument && excludeArgument[0] !== undefined ? identityMapper : context); + inferTypes(context.inferences, checkAttrType, paramType); + return getInferredTypes(context); + } + function inferTypeArguments(node, signature, args, excludeArgument, context) { + for (var _i = 0, _a = context.inferences; _i < _a.length; _i++) { + var inference = _a[_i]; + if (!inference.isFixed) { + inference.inferredType = undefined; + } + } + if (ts.isJsxOpeningLikeElement(node)) { + return inferJsxTypeArguments(node, signature, excludeArgument, context); + } + if (node.kind !== 152) { + var contextualType = getContextualType(node); + if (contextualType) { + var instantiatedType = instantiateType(contextualType, cloneTypeMapper(getContextualMapper(node))); + var contextualSignature = getSingleCallSignature(instantiatedType); + var inferenceSourceType = contextualSignature && contextualSignature.typeParameters ? + getOrCreateTypeFromSignature(getSignatureInstantiationWithoutFillingInTypeArguments(contextualSignature, contextualSignature.typeParameters)) : + instantiatedType; + var inferenceTargetType = getReturnTypeOfSignature(signature); + inferTypes(context.inferences, inferenceSourceType, inferenceTargetType, 8); + } + } + var thisType = getThisTypeOfSignature(signature); + if (thisType) { + var thisArgumentNode = getThisArgumentOfCall(node); + var thisArgumentType = thisArgumentNode ? checkExpression(thisArgumentNode) : voidType; + inferTypes(context.inferences, thisArgumentType, thisType); + } + var restType = getNonArrayRestType(signature); + var argCount = restType ? Math.min(getParameterCount(signature) - 1, args.length) : args.length; + for (var i = 0; i < argCount; i++) { + var arg = args[i]; + if (arg.kind !== 210) { + var paramType = getTypeAtPosition(signature, i); + var mapper = excludeArgument && excludeArgument[i] !== undefined ? identityMapper : context; + var argType = checkExpressionWithContextualType(arg, paramType, mapper); + inferTypes(context.inferences, argType, paramType); + } + } + if (restType) { + var spreadType = getSpreadArgumentType(args, argCount, args.length, restType, context); + inferTypes(context.inferences, spreadType, restType); + } + return getInferredTypes(context); + } + function getArrayifiedType(type) { + if (forEachType(type, function (t) { return !(t.flags & (1 | 63176704) || isArrayType(t) || isTupleType(t)); })) { + return createArrayType(getIndexTypeOfType(type, 1) || errorType); + } + return type; + } + function getSpreadArgumentType(args, index, argCount, restType, context) { + if (index >= argCount - 1) { + var arg = args[argCount - 1]; + if (isSpreadArgument(arg)) { + return arg.kind === 215 ? + createArrayType(arg.type) : + getArrayifiedType(checkExpressionWithContextualType(arg.expression, restType, context)); + } + } + var contextualType = getIndexTypeOfType(restType, 1) || anyType; + var hasPrimitiveContextualType = maybeTypeOfKind(contextualType, 131068 | 4194304); + var types = []; + var spreadIndex = -1; + for (var i = index; i < argCount; i++) { + var argType = checkExpressionWithContextualType(args[i], contextualType, context); + if (spreadIndex < 0 && isSpreadArgument(args[i])) { + spreadIndex = i - index; + } + types.push(hasPrimitiveContextualType ? getRegularTypeOfLiteralType(argType) : getWidenedLiteralType(argType)); + } + return spreadIndex < 0 ? + createTupleType(types) : + createTupleType(ts.append(types.slice(0, spreadIndex), getUnionType(types.slice(spreadIndex))), spreadIndex, true); + } + function checkTypeArguments(signature, typeArgumentNodes, reportErrors, headMessage) { + var isJavascript = ts.isInJSFile(signature.declaration); + var typeParameters = signature.typeParameters; + var typeArgumentTypes = fillMissingTypeArguments(ts.map(typeArgumentNodes, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), isJavascript); + var mapper; + for (var i = 0; i < typeArgumentNodes.length; i++) { + ts.Debug.assert(typeParameters[i] !== undefined, "Should not call checkTypeArguments with too many type arguments"); + var constraint = getConstraintOfTypeParameter(typeParameters[i]); + if (constraint) { + var errorInfo = reportErrors && headMessage ? (function () { return ts.chainDiagnosticMessages(undefined, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); }) : undefined; + var typeArgumentHeadMessage = headMessage || ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1; + if (!mapper) { + mapper = createTypeMapper(typeParameters, typeArgumentTypes); + } + var typeArgument = typeArgumentTypes[i]; + if (!checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), reportErrors ? typeArgumentNodes[i] : undefined, typeArgumentHeadMessage, errorInfo)) { + return undefined; + } + } + } + return typeArgumentTypes; + } + function getJsxReferenceKind(node) { + if (isJsxIntrinsicIdentifier(node.tagName)) { + return 2; + } + var tagType = getApparentType(checkExpression(node.tagName)); + if (ts.length(getSignaturesOfType(tagType, 1))) { + return 0; + } + if (ts.length(getSignaturesOfType(tagType, 0))) { + return 1; + } + return 2; + } + function checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation, excludeArgument, reportErrors) { + var paramType = getEffectiveFirstArgumentForJsxSignature(signature, node); + var attributesType = checkExpressionWithContextualType(node.attributes, paramType, excludeArgument && excludeArgument[0] ? identityMapper : undefined); + return checkTypeRelatedToAndOptionallyElaborate(attributesType, paramType, relation, reportErrors ? node.tagName : undefined, node.attributes); + } + function checkApplicableSignature(node, args, signature, relation, excludeArgument, reportErrors) { + if (ts.isJsxOpeningLikeElement(node)) { + return checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation, excludeArgument, reportErrors); + } + var thisType = getThisTypeOfSignature(signature); + if (thisType && thisType !== voidType && node.kind !== 192) { + var thisArgumentNode = getThisArgumentOfCall(node); + var thisArgumentType = thisArgumentNode ? checkExpression(thisArgumentNode) : voidType; + var errorNode = reportErrors ? (thisArgumentNode || node) : undefined; + var headMessage_1 = ts.Diagnostics.The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1; + if (!checkTypeRelatedTo(thisArgumentType, thisType, relation, errorNode, headMessage_1)) { + return false; + } + } + var headMessage = ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1; + var restType = getNonArrayRestType(signature); + var argCount = restType ? Math.min(getParameterCount(signature) - 1, args.length) : args.length; + for (var i = 0; i < argCount; i++) { + var arg = args[i]; + if (arg.kind !== 210) { + var paramType = getTypeAtPosition(signature, i); + var argType = checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); + var checkArgType = excludeArgument ? getRegularTypeOfObjectLiteral(argType) : argType; + if (!checkTypeRelatedToAndOptionallyElaborate(checkArgType, paramType, relation, reportErrors ? arg : undefined, arg, headMessage)) { + return false; + } + } + } + if (restType) { + var spreadType = getSpreadArgumentType(args, argCount, args.length, restType, undefined); + var errorNode = reportErrors ? argCount < args.length ? args[argCount] : node : undefined; + return checkTypeRelatedTo(spreadType, restType, relation, errorNode, headMessage); + } + return true; + } + function getThisArgumentOfCall(node) { + if (node.kind === 191) { + var callee = ts.skipOuterExpressions(node.expression); + if (callee.kind === 189 || callee.kind === 190) { + return callee.expression; + } + } + } + function createSyntheticExpression(parent, type, isSpread) { + var result = ts.createNode(215, parent.pos, parent.end); + result.parent = parent; + result.type = type; + result.isSpread = isSpread || false; + return result; + } + function getEffectiveCallArguments(node) { + if (node.kind === 193) { + var template = node.template; + var args_4 = [createSyntheticExpression(template, getGlobalTemplateStringsArrayType())]; + if (template.kind === 206) { + ts.forEach(template.templateSpans, function (span) { + args_4.push(span.expression); + }); + } + return args_4; + } + if (node.kind === 152) { + return getEffectiveDecoratorArguments(node); + } + if (ts.isJsxOpeningLikeElement(node)) { + return node.attributes.properties.length > 0 || (ts.isJsxOpeningElement(node) && node.parent.children.length > 0) ? [node.attributes] : ts.emptyArray; + } + var args = node.arguments || ts.emptyArray; + var length = args.length; + if (length && isSpreadArgument(args[length - 1]) && getSpreadArgumentIndex(args) === length - 1) { + var spreadArgument_1 = args[length - 1]; + var type = checkExpressionCached(spreadArgument_1.expression); + if (isTupleType(type)) { + var typeArguments = type.typeArguments || ts.emptyArray; + var restIndex_2 = type.target.hasRestElement ? typeArguments.length - 1 : -1; + var syntheticArgs = ts.map(typeArguments, function (t, i) { return createSyntheticExpression(spreadArgument_1, t, i === restIndex_2); }); + return ts.concatenate(args.slice(0, length - 1), syntheticArgs); + } + } + return args; + } + function getEffectiveDecoratorArguments(node) { + var parent = node.parent; + var expr = node.expression; + switch (parent.kind) { + case 240: + case 209: + return [ + createSyntheticExpression(expr, getTypeOfSymbol(getSymbolOfNode(parent))) + ]; + case 151: + var func = parent.parent; + return [ + createSyntheticExpression(expr, parent.parent.kind === 157 ? getTypeOfSymbol(getSymbolOfNode(func)) : errorType), + createSyntheticExpression(expr, anyType), + createSyntheticExpression(expr, numberType) + ]; + case 154: + case 156: + case 158: + case 159: + var hasPropDesc = parent.kind !== 154 && languageVersion !== 0; + return [ + createSyntheticExpression(expr, getParentTypeOfClassElement(parent)), + createSyntheticExpression(expr, getClassElementPropertyKeyType(parent)), + createSyntheticExpression(expr, hasPropDesc ? createTypedPropertyDescriptorType(getTypeOfNode(parent)) : anyType) + ]; + } + return ts.Debug.fail(); + } + function getDecoratorArgumentCount(node, signature) { + switch (node.parent.kind) { + case 240: + case 209: + return 1; + case 154: + return 2; + case 156: + case 158: + case 159: + return languageVersion === 0 || signature.parameters.length <= 2 ? 2 : 3; + case 151: + return 3; + default: + return ts.Debug.fail(); + } + } + function getArgumentArityError(node, signatures, args) { + var min = Number.POSITIVE_INFINITY; + var max = Number.NEGATIVE_INFINITY; + var belowArgCount = Number.NEGATIVE_INFINITY; + var aboveArgCount = Number.POSITIVE_INFINITY; + var argCount = args.length; + var closestSignature; + for (var _i = 0, signatures_4 = signatures; _i < signatures_4.length; _i++) { + var sig = signatures_4[_i]; + var minCount = getMinArgumentCount(sig); + var maxCount = getParameterCount(sig); + if (minCount < argCount && minCount > belowArgCount) + belowArgCount = minCount; + if (argCount < maxCount && maxCount < aboveArgCount) + aboveArgCount = maxCount; + if (minCount < min) { + min = minCount; + closestSignature = sig; + } + max = Math.max(max, maxCount); + } + var hasRestParameter = ts.some(signatures, hasEffectiveRestParameter); + var paramRange = hasRestParameter ? min : + min < max ? min + "-" + max : + min; + var hasSpreadArgument = getSpreadArgumentIndex(args) > -1; + if (argCount <= max && hasSpreadArgument) { + argCount--; + } + var related; + if (closestSignature && getMinArgumentCount(closestSignature) > argCount && closestSignature.declaration) { + var paramDecl = closestSignature.declaration.parameters[closestSignature.thisParameter ? argCount + 1 : argCount]; + if (paramDecl) { + related = ts.createDiagnosticForNode(paramDecl, ts.isBindingPattern(paramDecl.name) ? ts.Diagnostics.An_argument_matching_this_binding_pattern_was_not_provided : ts.Diagnostics.An_argument_for_0_was_not_provided, !paramDecl.name ? argCount : !ts.isBindingPattern(paramDecl.name) ? ts.idText(getFirstIdentifier(paramDecl.name)) : undefined); + } + } + if (hasRestParameter || hasSpreadArgument) { + var error_1 = hasRestParameter && hasSpreadArgument ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1_or_more : + hasRestParameter ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1 : + ts.Diagnostics.Expected_0_arguments_but_got_1_or_more; + var diagnostic_1 = ts.createDiagnosticForNode(node, error_1, paramRange, argCount); + return related ? addRelatedInfo(diagnostic_1, related) : diagnostic_1; + } + if (min < argCount && argCount < max) { + return ts.createDiagnosticForNode(node, ts.Diagnostics.No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments, argCount, belowArgCount, aboveArgCount); + } + var diagnostic = ts.createDiagnosticForNode(node, ts.Diagnostics.Expected_0_arguments_but_got_1, paramRange, argCount); + return related ? addRelatedInfo(diagnostic, related) : diagnostic; + } + function getTypeArgumentArityError(node, signatures, typeArguments) { + var min = Infinity; + var max = -Infinity; + for (var _i = 0, signatures_5 = signatures; _i < signatures_5.length; _i++) { + var sig = signatures_5[_i]; + min = Math.min(min, getMinTypeArgumentCount(sig.typeParameters)); + max = Math.max(max, ts.length(sig.typeParameters)); + } + var paramCount = min === max ? min : min + "-" + max; + return ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), typeArguments, ts.Diagnostics.Expected_0_type_arguments_but_got_1, paramCount, typeArguments.length); + } + function resolveCall(node, signatures, candidatesOutArray, isForSignatureHelp, fallbackError) { + var isTaggedTemplate = node.kind === 193; + var isDecorator = node.kind === 152; + var isJsxOpeningOrSelfClosingElement = ts.isJsxOpeningLikeElement(node); + var reportErrors = !candidatesOutArray; + var typeArguments; + if (!isDecorator) { + typeArguments = node.typeArguments; + if (isTaggedTemplate || isJsxOpeningOrSelfClosingElement || node.expression.kind !== 98) { + ts.forEach(typeArguments, checkSourceElement); + } + } + var candidates = candidatesOutArray || []; + reorderCandidates(signatures, candidates); + if (!candidates.length) { + if (reportErrors) { + diagnostics.add(ts.createDiagnosticForNode(node, ts.Diagnostics.Call_target_does_not_contain_any_signatures)); + } + return resolveErrorCall(node); + } + var args = getEffectiveCallArguments(node); + var isSingleNonGenericCandidate = candidates.length === 1 && !candidates[0].typeParameters; + var excludeArgument = !isDecorator && !isSingleNonGenericCandidate ? getExcludeArgument(args) : undefined; + var candidateForArgumentError; + var candidateForArgumentArityError; + var candidateForTypeArgumentError; + var result; + var signatureHelpTrailingComma = isForSignatureHelp && node.kind === 191 && node.arguments.hasTrailingComma; + if (candidates.length > 1) { + result = chooseOverload(candidates, subtypeRelation, signatureHelpTrailingComma); + } + if (!result) { + result = chooseOverload(candidates, assignableRelation, signatureHelpTrailingComma); + } + if (result) { + return result; + } + if (reportErrors) { + if (candidateForArgumentError) { + checkApplicableSignature(node, args, candidateForArgumentError, assignableRelation, undefined, true); + } + else if (candidateForArgumentArityError) { + diagnostics.add(getArgumentArityError(node, [candidateForArgumentArityError], args)); + } + else if (candidateForTypeArgumentError) { + checkTypeArguments(candidateForTypeArgumentError, node.typeArguments, true, fallbackError); + } + else { + var signaturesWithCorrectTypeArgumentArity = ts.filter(signatures, function (s) { return hasCorrectTypeArgumentArity(s, typeArguments); }); + if (signaturesWithCorrectTypeArgumentArity.length === 0) { + diagnostics.add(getTypeArgumentArityError(node, signatures, typeArguments)); + } + else if (!isDecorator) { + diagnostics.add(getArgumentArityError(node, signaturesWithCorrectTypeArgumentArity, args)); + } + else if (fallbackError) { + diagnostics.add(ts.createDiagnosticForNode(node, fallbackError)); + } + } + } + return produceDiagnostics || !args ? resolveErrorCall(node) : getCandidateForOverloadFailure(node, candidates, args, !!candidatesOutArray); + function chooseOverload(candidates, relation, signatureHelpTrailingComma) { + if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; } + candidateForArgumentError = undefined; + candidateForArgumentArityError = undefined; + candidateForTypeArgumentError = undefined; + if (isSingleNonGenericCandidate) { + var candidate = candidates[0]; + if (typeArguments || !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) { + return undefined; + } + if (!checkApplicableSignature(node, args, candidate, relation, excludeArgument, false)) { + candidateForArgumentError = candidate; + return undefined; + } + return candidate; + } + for (var candidateIndex = 0; candidateIndex < candidates.length; candidateIndex++) { + var candidate = candidates[candidateIndex]; + if (!hasCorrectTypeArgumentArity(candidate, typeArguments) || !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) { + continue; + } + var checkCandidate = void 0; + var inferenceContext = void 0; + if (candidate.typeParameters) { + var typeArgumentTypes = void 0; + if (typeArguments) { + typeArgumentTypes = checkTypeArguments(candidate, typeArguments, false); + if (!typeArgumentTypes) { + candidateForTypeArgumentError = candidate; + continue; + } + } + else { + inferenceContext = createInferenceContext(candidate.typeParameters, candidate, ts.isInJSFile(node) ? 2 : 0); + typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); + } + checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration)); + if (getNonArrayRestType(candidate) && !hasCorrectArity(node, args, checkCandidate, signatureHelpTrailingComma)) { + candidateForArgumentArityError = checkCandidate; + continue; + } + } + else { + checkCandidate = candidate; + } + if (!checkApplicableSignature(node, args, checkCandidate, relation, excludeArgument, false)) { + if (!candidateForArgumentError || getEffectiveRestType(candidateForArgumentError) || !getEffectiveRestType(checkCandidate)) { + candidateForArgumentError = checkCandidate; + } + continue; + } + if (excludeArgument) { + excludeArgument = undefined; + if (inferenceContext) { + var typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); + checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration)); + } + if (!checkApplicableSignature(node, args, checkCandidate, relation, excludeArgument, false)) { + if (!candidateForArgumentError || getEffectiveRestType(candidateForArgumentError) || !getEffectiveRestType(checkCandidate)) { + candidateForArgumentError = checkCandidate; + } + continue; + } + } + candidates[candidateIndex] = checkCandidate; + return checkCandidate; + } + return undefined; + } + } + function getExcludeArgument(args) { + var excludeArgument; + for (var i = 0; i < args.length; i++) { + if (isContextSensitive(args[i])) { + if (!excludeArgument) { + excludeArgument = new Array(args.length); + } + excludeArgument[i] = true; + } + } + return excludeArgument; + } + function getCandidateForOverloadFailure(node, candidates, args, hasCandidatesOutArray) { + ts.Debug.assert(candidates.length > 0); + return hasCandidatesOutArray || candidates.length === 1 || candidates.some(function (c) { return !!c.typeParameters; }) + ? pickLongestCandidateSignature(node, candidates, args) + : createUnionOfSignaturesForOverloadFailure(candidates); + } + function createUnionOfSignaturesForOverloadFailure(candidates) { + var thisParameters = ts.mapDefined(candidates, function (c) { return c.thisParameter; }); + var thisParameter; + if (thisParameters.length) { + thisParameter = createCombinedSymbolFromTypes(thisParameters, thisParameters.map(getTypeOfParameter)); + } + var _a = ts.minAndMax(candidates, getNumNonRestParameters), minArgumentCount = _a.min, maxNonRestParam = _a.max; + var parameters = []; + var _loop_7 = function (i) { + var symbols = ts.mapDefined(candidates, function (_a) { + var parameters = _a.parameters, hasRestParameter = _a.hasRestParameter; + return hasRestParameter ? + i < parameters.length - 1 ? parameters[i] : ts.last(parameters) : + i < parameters.length ? parameters[i] : undefined; + }); + ts.Debug.assert(symbols.length !== 0); + parameters.push(createCombinedSymbolFromTypes(symbols, ts.mapDefined(candidates, function (candidate) { return tryGetTypeAtPosition(candidate, i); }))); + }; + for (var i = 0; i < maxNonRestParam; i++) { + _loop_7(i); + } + var restParameterSymbols = ts.mapDefined(candidates, function (c) { return c.hasRestParameter ? ts.last(c.parameters) : undefined; }); + var hasRestParameter = restParameterSymbols.length !== 0; + if (hasRestParameter) { + var type = createArrayType(getUnionType(ts.mapDefined(candidates, tryGetRestTypeOfSignature), 2)); + parameters.push(createCombinedSymbolForOverloadFailure(restParameterSymbols, type)); + } + return createSignature(candidates[0].declaration, undefined, thisParameter, parameters, getIntersectionType(candidates.map(getReturnTypeOfSignature)), undefined, minArgumentCount, hasRestParameter, candidates.some(function (c) { return c.hasLiteralTypes; })); + } + function getNumNonRestParameters(signature) { + var numParams = signature.parameters.length; + return signature.hasRestParameter ? numParams - 1 : numParams; + } + function createCombinedSymbolFromTypes(sources, types) { + return createCombinedSymbolForOverloadFailure(sources, getUnionType(types, 2)); + } + function createCombinedSymbolForOverloadFailure(sources, type) { + return createSymbolWithType(ts.first(sources), type); + } + function pickLongestCandidateSignature(node, candidates, args) { + var bestIndex = getLongestCandidateIndex(candidates, apparentArgumentCount === undefined ? args.length : apparentArgumentCount); + var candidate = candidates[bestIndex]; + var typeParameters = candidate.typeParameters; + if (!typeParameters) { + return candidate; + } + var typeArgumentNodes = callLikeExpressionMayHaveTypeArguments(node) ? node.typeArguments : undefined; + var instantiated = typeArgumentNodes + ? createSignatureInstantiation(candidate, getTypeArgumentsFromNodes(typeArgumentNodes, typeParameters, ts.isInJSFile(node))) + : inferSignatureInstantiationForOverloadFailure(node, typeParameters, candidate, args); + candidates[bestIndex] = instantiated; + return instantiated; + } + function getTypeArgumentsFromNodes(typeArgumentNodes, typeParameters, isJs) { + var typeArguments = typeArgumentNodes.map(getTypeOfNode); + while (typeArguments.length > typeParameters.length) { + typeArguments.pop(); + } + while (typeArguments.length < typeParameters.length) { + typeArguments.push(getConstraintOfTypeParameter(typeParameters[typeArguments.length]) || getDefaultTypeArgumentType(isJs)); + } + return typeArguments; + } + function inferSignatureInstantiationForOverloadFailure(node, typeParameters, candidate, args) { + var inferenceContext = createInferenceContext(typeParameters, candidate, ts.isInJSFile(node) ? 2 : 0); + var typeArgumentTypes = inferTypeArguments(node, candidate, args, getExcludeArgument(args), inferenceContext); + return createSignatureInstantiation(candidate, typeArgumentTypes); + } + function getLongestCandidateIndex(candidates, argsCount) { + var maxParamsIndex = -1; + var maxParams = -1; + for (var i = 0; i < candidates.length; i++) { + var candidate = candidates[i]; + var paramCount = getParameterCount(candidate); + if (hasEffectiveRestParameter(candidate) || paramCount >= argsCount) { + return i; + } + if (paramCount > maxParams) { + maxParams = paramCount; + maxParamsIndex = i; + } + } + return maxParamsIndex; + } + function resolveCallExpression(node, candidatesOutArray, isForSignatureHelp) { + if (node.expression.kind === 98) { + var superType = checkSuperExpression(node.expression); + if (isTypeAny(superType)) { + for (var _i = 0, _a = node.arguments; _i < _a.length; _i++) { + var arg = _a[_i]; + checkExpression(arg); + } + return anySignature; + } + if (superType !== errorType) { + var baseTypeNode = ts.getEffectiveBaseTypeNode(ts.getContainingClass(node)); + if (baseTypeNode) { + var baseConstructors = getInstantiatedConstructorsForTypeArguments(superType, baseTypeNode.typeArguments, baseTypeNode); + return resolveCall(node, baseConstructors, candidatesOutArray, isForSignatureHelp); + } + } + return resolveUntypedCall(node); + } + var funcType = checkNonNullExpression(node.expression, ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_null, ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_undefined, ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_null_or_undefined); + if (funcType === silentNeverType) { + return silentNeverSignature; + } + var apparentType = getApparentType(funcType); + if (apparentType === errorType) { + return resolveErrorCall(node); + } + var callSignatures = getSignaturesOfType(apparentType, 0); + var numConstructSignatures = getSignaturesOfType(apparentType, 1).length; + if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, numConstructSignatures)) { + if (funcType !== errorType && node.typeArguments) { + error(node, ts.Diagnostics.Untyped_function_calls_may_not_accept_type_arguments); + } + return resolveUntypedCall(node); + } + if (!callSignatures.length) { + if (numConstructSignatures) { + error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType)); + } + else { + var relatedInformation = void 0; + if (node.arguments.length === 1) { + var text = ts.getSourceFileOfNode(node).text; + if (ts.isLineBreak(text.charCodeAt(ts.skipTrivia(text, node.expression.end, true) - 1))) { + relatedInformation = ts.createDiagnosticForNode(node.expression, ts.Diagnostics.It_is_highly_likely_that_you_are_missing_a_semicolon); + } + } + invocationError(node, apparentType, 0, relatedInformation); + } + return resolveErrorCall(node); + } + if (callSignatures.some(function (sig) { return ts.isInJSFile(sig.declaration) && !!ts.getJSDocClassTag(sig.declaration); })) { + error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType)); + return resolveErrorCall(node); + } + return resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp); + } + function isUntypedFunctionCall(funcType, apparentFuncType, numCallSignatures, numConstructSignatures) { + return isTypeAny(funcType) || isTypeAny(apparentFuncType) && funcType.flags & 262144 || + !numCallSignatures && !numConstructSignatures && !(apparentFuncType.flags & (1048576 | 131072)) && isTypeAssignableTo(funcType, globalFunctionType); + } + function resolveNewExpression(node, candidatesOutArray, isForSignatureHelp) { + if (node.arguments && languageVersion < 1) { + var spreadIndex = getSpreadArgumentIndex(node.arguments); + if (spreadIndex >= 0) { + error(node.arguments[spreadIndex], ts.Diagnostics.Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher); + } + } + var expressionType = checkNonNullExpression(node.expression); + if (expressionType === silentNeverType) { + return silentNeverSignature; + } + expressionType = getApparentType(expressionType); + if (expressionType === errorType) { + return resolveErrorCall(node); + } + if (isTypeAny(expressionType)) { + if (node.typeArguments) { + error(node, ts.Diagnostics.Untyped_function_calls_may_not_accept_type_arguments); + } + return resolveUntypedCall(node); + } + var constructSignatures = getSignaturesOfType(expressionType, 1); + if (constructSignatures.length) { + if (!isConstructorAccessible(node, constructSignatures[0])) { + return resolveErrorCall(node); + } + var valueDecl = expressionType.symbol && ts.getClassLikeDeclarationOfSymbol(expressionType.symbol); + if (valueDecl && ts.hasModifier(valueDecl, 128)) { + error(node, ts.Diagnostics.Cannot_create_an_instance_of_an_abstract_class); + return resolveErrorCall(node); + } + return resolveCall(node, constructSignatures, candidatesOutArray, isForSignatureHelp); + } + var callSignatures = getSignaturesOfType(expressionType, 0); + if (callSignatures.length) { + var signature = resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp); + if (!noImplicitAny) { + if (signature.declaration && !isJSConstructor(signature.declaration) && getReturnTypeOfSignature(signature) !== voidType) { + error(node, ts.Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword); + } + if (getThisTypeOfSignature(signature) === voidType) { + error(node, ts.Diagnostics.A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void); + } + } + return signature; + } + invocationError(node, expressionType, 1); + return resolveErrorCall(node); + } + function typeHasProtectedAccessibleBase(target, type) { + var baseTypes = getBaseTypes(type); + if (!ts.length(baseTypes)) { + return false; + } + var firstBase = baseTypes[0]; + if (firstBase.flags & 2097152) { + var types = firstBase.types; + var mixinCount = ts.countWhere(types, isMixinConstructorType); + var i = 0; + for (var _i = 0, _a = firstBase.types; _i < _a.length; _i++) { + var intersectionMember = _a[_i]; + i++; + if (mixinCount === 0 || mixinCount === types.length && i === 0 || !isMixinConstructorType(intersectionMember)) { + if (ts.getObjectFlags(intersectionMember) & (1 | 2)) { + if (intersectionMember.symbol === target) { + return true; + } + if (typeHasProtectedAccessibleBase(target, intersectionMember)) { + return true; + } + } + } + } + return false; + } + if (firstBase.symbol === target) { + return true; + } + return typeHasProtectedAccessibleBase(target, firstBase); + } + function isConstructorAccessible(node, signature) { + if (!signature || !signature.declaration) { + return true; + } + var declaration = signature.declaration; + var modifiers = ts.getSelectedModifierFlags(declaration, 24); + if (!modifiers) { + return true; + } + var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(declaration.parent.symbol); + var declaringClass = getDeclaredTypeOfSymbol(declaration.parent.symbol); + if (!isNodeWithinClass(node, declaringClassDeclaration)) { + var containingClass = ts.getContainingClass(node); + if (containingClass && modifiers & 16) { + var containingType = getTypeOfNode(containingClass); + if (typeHasProtectedAccessibleBase(declaration.parent.symbol, containingType)) { + return true; + } + } + if (modifiers & 8) { + error(node, ts.Diagnostics.Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration, typeToString(declaringClass)); + } + if (modifiers & 16) { + error(node, ts.Diagnostics.Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration, typeToString(declaringClass)); + } + return false; + } + return true; + } + function invocationError(node, apparentType, kind, relatedInformation) { + var diagnostic = error(node, (kind === 0 ? + ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures : + ts.Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature), typeToString(apparentType)); + invocationErrorRecovery(apparentType, kind, relatedInformation ? addRelatedInfo(diagnostic, relatedInformation) : diagnostic); + } + function invocationErrorRecovery(apparentType, kind, diagnostic) { + if (!apparentType.symbol) { + return; + } + var importNode = getSymbolLinks(apparentType.symbol).originatingImport; + if (importNode && !ts.isImportCall(importNode)) { + var sigs = getSignaturesOfType(getTypeOfSymbol(getSymbolLinks(apparentType.symbol).target), kind); + if (!sigs || !sigs.length) + return; + addRelatedInfo(diagnostic, ts.createDiagnosticForNode(importNode, ts.Diagnostics.Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_Consider_using_a_default_import_or_import_require_here_instead)); + } + } + function resolveTaggedTemplateExpression(node, candidatesOutArray, isForSignatureHelp) { + var tagType = checkExpression(node.tag); + var apparentType = getApparentType(tagType); + if (apparentType === errorType) { + return resolveErrorCall(node); + } + var callSignatures = getSignaturesOfType(apparentType, 0); + var numConstructSignatures = getSignaturesOfType(apparentType, 1).length; + if (isUntypedFunctionCall(tagType, apparentType, callSignatures.length, numConstructSignatures)) { + return resolveUntypedCall(node); + } + if (!callSignatures.length) { + invocationError(node, apparentType, 0); + return resolveErrorCall(node); + } + return resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp); + } + function getDiagnosticHeadMessageForDecoratorResolution(node) { + switch (node.parent.kind) { + case 240: + case 209: + return ts.Diagnostics.Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression; + case 151: + return ts.Diagnostics.Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression; + case 154: + return ts.Diagnostics.Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression; + case 156: + case 158: + case 159: + return ts.Diagnostics.Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression; + default: + return ts.Debug.fail(); + } + } + function resolveDecorator(node, candidatesOutArray, isForSignatureHelp) { + var funcType = checkExpression(node.expression); + var apparentType = getApparentType(funcType); + if (apparentType === errorType) { + return resolveErrorCall(node); + } + var callSignatures = getSignaturesOfType(apparentType, 0); + var numConstructSignatures = getSignaturesOfType(apparentType, 1).length; + if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, numConstructSignatures)) { + return resolveUntypedCall(node); + } + if (isPotentiallyUncalledDecorator(node, callSignatures)) { + var nodeStr = ts.getTextOfNode(node.expression, false); + error(node, ts.Diagnostics._0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write_0, nodeStr); + return resolveErrorCall(node); + } + var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); + if (!callSignatures.length) { + var errorInfo = ts.chainDiagnosticMessages(undefined, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures, typeToString(apparentType)); + errorInfo = ts.chainDiagnosticMessages(errorInfo, headMessage); + var diag = ts.createDiagnosticForNodeFromMessageChain(node, errorInfo); + diagnostics.add(diag); + invocationErrorRecovery(apparentType, 0, diag); + return resolveErrorCall(node); + } + return resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp, headMessage); + } + function createSignatureForJSXIntrinsic(node, result) { + var namespace = getJsxNamespaceAt(node); + var exports = namespace && getExportsOfSymbol(namespace); + var typeSymbol = exports && getSymbol(exports, JsxNames.Element, 67897832); + var returnNode = typeSymbol && nodeBuilder.symbolToEntityName(typeSymbol, 67897832, node); + var declaration = ts.createFunctionTypeNode(undefined, [ts.createParameter(undefined, undefined, undefined, "props", undefined, nodeBuilder.typeToTypeNode(result, node))], returnNode ? ts.createTypeReferenceNode(returnNode, undefined) : ts.createKeywordTypeNode(120)); + var parameterSymbol = createSymbol(1, "props"); + parameterSymbol.type = result; + return createSignature(declaration, undefined, undefined, [parameterSymbol], typeSymbol ? getDeclaredTypeOfSymbol(typeSymbol) : errorType, undefined, 1, false, false); + } + function resolveJsxOpeningLikeElement(node, candidatesOutArray, isForSignatureHelp) { + if (isJsxIntrinsicIdentifier(node.tagName)) { + var result = getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node); + var fakeSignature = createSignatureForJSXIntrinsic(node, result); + checkTypeAssignableToAndOptionallyElaborate(checkExpressionWithContextualType(node.attributes, getEffectiveFirstArgumentForJsxSignature(fakeSignature, node), undefined), result, node.tagName, node.attributes); + return fakeSignature; + } + var exprTypes = checkExpression(node.tagName); + var apparentType = getApparentType(exprTypes); + if (apparentType === errorType) { + return resolveErrorCall(node); + } + var signatures = getUninstantiatedJsxSignaturesOfType(exprTypes, node); + if (isUntypedFunctionCall(exprTypes, apparentType, signatures.length, 0)) { + return resolveUntypedCall(node); + } + if (signatures.length === 0) { + error(node.tagName, ts.Diagnostics.JSX_element_type_0_does_not_have_any_construct_or_call_signatures, ts.getTextOfNode(node.tagName)); + return resolveErrorCall(node); + } + return resolveCall(node, signatures, candidatesOutArray, isForSignatureHelp); + } + function isPotentiallyUncalledDecorator(decorator, signatures) { + return signatures.length && ts.every(signatures, function (signature) { + return signature.minArgumentCount === 0 && + !signature.hasRestParameter && + signature.parameters.length < getDecoratorArgumentCount(decorator, signature); + }); + } + function resolveSignature(node, candidatesOutArray, isForSignatureHelp) { + switch (node.kind) { + case 191: + return resolveCallExpression(node, candidatesOutArray, isForSignatureHelp); + case 192: + return resolveNewExpression(node, candidatesOutArray, isForSignatureHelp); + case 193: + return resolveTaggedTemplateExpression(node, candidatesOutArray, isForSignatureHelp); + case 152: + return resolveDecorator(node, candidatesOutArray, isForSignatureHelp); + case 262: + case 261: + return resolveJsxOpeningLikeElement(node, candidatesOutArray, isForSignatureHelp); + } + throw ts.Debug.assertNever(node, "Branch in 'resolveSignature' should be unreachable."); + } + function getResolvedSignature(node, candidatesOutArray, isForSignatureHelp) { + if (isForSignatureHelp === void 0) { isForSignatureHelp = false; } + var links = getNodeLinks(node); + var cached = links.resolvedSignature; + if (cached && cached !== resolvingSignature && !candidatesOutArray) { + return cached; + } + links.resolvedSignature = resolvingSignature; + var result = resolveSignature(node, candidatesOutArray, isForSignatureHelp); + links.resolvedSignature = flowLoopStart === flowLoopCount ? result : cached; + return result; + } + function isJSConstructor(node) { + if (!node || !ts.isInJSFile(node)) { + return false; + } + var func = ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node) ? node : + ts.isVariableDeclaration(node) && node.initializer && ts.isFunctionExpression(node.initializer) ? node.initializer : + undefined; + if (func) { + if (ts.getJSDocClassTag(node)) + return true; + var symbol = getSymbolOfNode(func); + return !!symbol && symbol.members !== undefined; + } + return false; + } + function isJSConstructorType(type) { + if (type.flags & 524288) { + var resolved = resolveStructuredTypeMembers(type); + return resolved.callSignatures.length === 1 && isJSConstructor(resolved.callSignatures[0].declaration); + } + return false; + } + function getJSClassType(symbol) { + var inferred; + if (isJSConstructor(symbol.valueDeclaration)) { + inferred = getInferredClassType(symbol); + } + var assigned = getAssignedClassType(symbol); + var valueType = getTypeOfSymbol(symbol); + if (valueType.symbol && !isInferredClassType(valueType) && isJSConstructor(valueType.symbol.valueDeclaration)) { + inferred = getInferredClassType(valueType.symbol); + } + return assigned && inferred ? + getIntersectionType([inferred, assigned]) : + assigned || inferred; + } + function getAssignedClassType(symbol) { + var decl = symbol.valueDeclaration; + var assignmentSymbol = decl && decl.parent && + (ts.isFunctionDeclaration(decl) && getSymbolOfNode(decl) || + ts.isBinaryExpression(decl.parent) && getSymbolOfNode(decl.parent.left) || + ts.isVariableDeclaration(decl.parent) && getSymbolOfNode(decl.parent)); + var prototype = assignmentSymbol && assignmentSymbol.exports && assignmentSymbol.exports.get("prototype"); + var init = prototype && prototype.valueDeclaration && getAssignedJSPrototype(prototype.valueDeclaration); + return init ? checkExpression(init) : undefined; + } + function getAssignedJSPrototype(node) { + if (!node.parent) { + return false; + } + var parent = node.parent; + while (parent && parent.kind === 189) { + parent = parent.parent; + } + if (parent && ts.isBinaryExpression(parent) && ts.isPrototypeAccess(parent.left) && parent.operatorToken.kind === 59) { + var right = ts.getInitializerOfBinaryExpression(parent); + return ts.isObjectLiteralExpression(right) && right; + } + } + function getInferredClassType(symbol) { + var links = getSymbolLinks(symbol); + if (!links.inferredClassType) { + links.inferredClassType = createAnonymousType(symbol, getMembersOfSymbol(symbol) || emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + } + return links.inferredClassType; + } + function isInferredClassType(type) { + return type.symbol + && ts.getObjectFlags(type) & 16 + && getSymbolLinks(type.symbol).inferredClassType === type; + } + function checkCallExpression(node) { + if (!checkGrammarTypeArguments(node, node.typeArguments)) + checkGrammarArguments(node.arguments); + var signature = getResolvedSignature(node); + if (node.expression.kind === 98) { + return voidType; + } + if (node.kind === 192) { + var declaration = signature.declaration; + if (declaration && + declaration.kind !== 157 && + declaration.kind !== 161 && + declaration.kind !== 166 && + !ts.isJSDocConstructSignature(declaration)) { + var funcSymbol = checkExpression(node.expression).symbol; + if (!funcSymbol && node.expression.kind === 72) { + funcSymbol = getResolvedSymbol(node.expression); + } + var type = funcSymbol && getJSClassType(funcSymbol); + if (type) { + return signature.target ? instantiateType(type, signature.mapper) : type; + } + if (noImplicitAny) { + error(node, ts.Diagnostics.new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type); + } + return anyType; + } + } + if (ts.isInJSFile(node) && isCommonJsRequire(node)) { + return resolveExternalModuleTypeByLiteral(node.arguments[0]); + } + var returnType = getReturnTypeOfSignature(signature); + if (returnType.flags & 12288 && isSymbolOrSymbolForCall(node)) { + return getESSymbolLikeTypeForNode(ts.walkUpParenthesizedExpressions(node.parent)); + } + var jsAssignmentType; + if (ts.isInJSFile(node)) { + var decl = ts.getDeclarationOfExpando(node); + if (decl) { + var jsSymbol = getSymbolOfNode(decl); + if (jsSymbol && ts.hasEntries(jsSymbol.exports)) { + jsAssignmentType = createAnonymousType(jsSymbol, jsSymbol.exports, ts.emptyArray, ts.emptyArray, undefined, undefined); + jsAssignmentType.objectFlags |= 16384; + } + } + } + return jsAssignmentType ? getIntersectionType([returnType, jsAssignmentType]) : returnType; + } + function isSymbolOrSymbolForCall(node) { + if (!ts.isCallExpression(node)) + return false; + var left = node.expression; + if (ts.isPropertyAccessExpression(left) && left.name.escapedText === "for") { + left = left.expression; + } + if (!ts.isIdentifier(left) || left.escapedText !== "Symbol") { + return false; + } + var globalESSymbol = getGlobalESSymbolConstructorSymbol(false); + if (!globalESSymbol) { + return false; + } + return globalESSymbol === resolveName(left, "Symbol", 67220415, undefined, undefined, false); + } + function checkImportCallExpression(node) { + if (!checkGrammarArguments(node.arguments)) + checkGrammarImportCallExpression(node); + if (node.arguments.length === 0) { + return createPromiseReturnType(node, anyType); + } + var specifier = node.arguments[0]; + var specifierType = checkExpressionCached(specifier); + for (var i = 1; i < node.arguments.length; ++i) { + checkExpressionCached(node.arguments[i]); + } + if (specifierType.flags & 32768 || specifierType.flags & 65536 || !isTypeAssignableTo(specifierType, stringType)) { + error(specifier, ts.Diagnostics.Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0, typeToString(specifierType)); + } + var moduleSymbol = resolveExternalModuleName(node, specifier); + if (moduleSymbol) { + var esModuleSymbol = resolveESModuleSymbol(moduleSymbol, specifier, true); + if (esModuleSymbol) { + return createPromiseReturnType(node, getTypeWithSyntheticDefaultImportType(getTypeOfSymbol(esModuleSymbol), esModuleSymbol, moduleSymbol)); + } + } + return createPromiseReturnType(node, anyType); + } + function getTypeWithSyntheticDefaultImportType(type, symbol, originalSymbol) { + if (allowSyntheticDefaultImports && type && type !== errorType) { + var synthType = type; + if (!synthType.syntheticType) { + var file = ts.find(originalSymbol.declarations, ts.isSourceFile); + var hasSyntheticDefault = canHaveSyntheticDefault(file, originalSymbol, false); + if (hasSyntheticDefault) { + var memberTable = ts.createSymbolTable(); + var newSymbol = createSymbol(2097152, "default"); + newSymbol.nameType = getLiteralType("default"); + newSymbol.target = resolveSymbol(symbol); + memberTable.set("default", newSymbol); + var anonymousSymbol = createSymbol(2048, "__type"); + var defaultContainingObject = createAnonymousType(anonymousSymbol, memberTable, ts.emptyArray, ts.emptyArray, undefined, undefined); + anonymousSymbol.type = defaultContainingObject; + synthType.syntheticType = isValidSpreadType(type) ? getSpreadType(type, defaultContainingObject, anonymousSymbol, 0, 0) : defaultContainingObject; + } + else { + synthType.syntheticType = type; + } + } + return synthType.syntheticType; + } + return type; + } + function isCommonJsRequire(node) { + if (!ts.isRequireCall(node, true)) { + return false; + } + if (!ts.isIdentifier(node.expression)) + return ts.Debug.fail(); + var resolvedRequire = resolveName(node.expression, node.expression.escapedText, 67220415, undefined, undefined, true); + if (resolvedRequire === requireSymbol) { + return true; + } + if (resolvedRequire.flags & 2097152) { + return false; + } + var targetDeclarationKind = resolvedRequire.flags & 16 + ? 239 + : resolvedRequire.flags & 3 + ? 237 + : 0; + if (targetDeclarationKind !== 0) { + var decl = ts.getDeclarationOfKind(resolvedRequire, targetDeclarationKind); + return !!decl && !!(decl.flags & 4194304); + } + return false; + } + function checkTaggedTemplateExpression(node) { + checkGrammarTypeArguments(node, node.typeArguments); + if (languageVersion < 2) { + checkExternalEmitHelpers(node, 65536); + } + return getReturnTypeOfSignature(getResolvedSignature(node)); + } + function checkAssertion(node) { + return checkAssertionWorker(node, node.type, node.expression); + } + function checkAssertionWorker(errNode, type, expression, checkMode) { + var exprType = getRegularTypeOfObjectLiteral(getBaseTypeOfLiteralType(checkExpression(expression, checkMode))); + checkSourceElement(type); + var targetType = getTypeFromTypeNode(type); + if (produceDiagnostics && targetType !== errorType) { + var widenedType = getWidenedType(exprType); + if (!isTypeComparableTo(targetType, widenedType)) { + checkTypeComparableTo(exprType, targetType, errNode, ts.Diagnostics.Conversion_of_type_0_to_type_1_may_be_a_mistake_because_neither_type_sufficiently_overlaps_with_the_other_If_this_was_intentional_convert_the_expression_to_unknown_first); + } + } + return targetType; + } + function checkNonNullAssertion(node) { + return getNonNullableType(checkExpression(node.expression)); + } + function checkMetaProperty(node) { + checkGrammarMetaProperty(node); + if (node.keywordToken === 95) { + return checkNewTargetMetaProperty(node); + } + if (node.keywordToken === 92) { + return checkImportMetaProperty(node); + } + return ts.Debug.assertNever(node.keywordToken); + } + function checkNewTargetMetaProperty(node) { + var container = ts.getNewTargetContainer(node); + if (!container) { + error(node, ts.Diagnostics.Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constructor, "new.target"); + return errorType; + } + else if (container.kind === 157) { + var symbol = getSymbolOfNode(container.parent); + return getTypeOfSymbol(symbol); + } + else { + var symbol = getSymbolOfNode(container); + return getTypeOfSymbol(symbol); + } + } + function checkImportMetaProperty(node) { + if (languageVersion < 6 || moduleKind < ts.ModuleKind.ESNext) { + error(node, ts.Diagnostics.The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_options); + } + var file = ts.getSourceFileOfNode(node); + ts.Debug.assert(!!(file.flags & 1048576), "Containing file is missing import meta node flag."); + ts.Debug.assert(!!file.externalModuleIndicator, "Containing file should be a module."); + return node.name.escapedText === "meta" ? getGlobalImportMetaType() : errorType; + } + function getTypeOfParameter(symbol) { + var type = getTypeOfSymbol(symbol); + if (strictNullChecks) { + var declaration = symbol.valueDeclaration; + if (declaration && ts.hasInitializer(declaration)) { + return getOptionalType(type); + } + } + return type; + } + function getParameterNameAtPosition(signature, pos) { + var paramCount = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); + if (pos < paramCount) { + return signature.parameters[pos].escapedName; + } + var restParameter = signature.parameters[paramCount] || unknownSymbol; + var restType = getTypeOfSymbol(restParameter); + if (isTupleType(restType)) { + var associatedNames = restType.target.associatedNames; + var index = pos - paramCount; + return associatedNames ? associatedNames[index] : restParameter.escapedName + "_" + index; + } + return restParameter.escapedName; + } + function getTypeAtPosition(signature, pos) { + return tryGetTypeAtPosition(signature, pos) || anyType; + } + function tryGetTypeAtPosition(signature, pos) { + var paramCount = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); + if (pos < paramCount) { + return getTypeOfParameter(signature.parameters[pos]); + } + if (signature.hasRestParameter) { + var restType = getTypeOfSymbol(signature.parameters[paramCount]); + if (isTupleType(restType)) { + if (pos - paramCount < getLengthOfTupleType(restType)) { + return restType.typeArguments[pos - paramCount]; + } + return getRestTypeOfTupleType(restType); + } + return getIndexTypeOfType(restType, 1); + } + return undefined; + } + function getRestTypeAtPosition(source, pos) { + var paramCount = getParameterCount(source); + var restType = getEffectiveRestType(source); + if (restType && pos === paramCount - 1) { + return restType; + } + var start = restType ? Math.min(pos, paramCount - 1) : pos; + var types = []; + var names = []; + for (var i = start; i < paramCount; i++) { + types.push(getTypeAtPosition(source, i)); + names.push(getParameterNameAtPosition(source, i)); + } + var minArgumentCount = getMinArgumentCount(source); + var minLength = minArgumentCount < start ? 0 : minArgumentCount - start; + return createTupleType(types, minLength, !!restType, names); + } + function getParameterCount(signature) { + var length = signature.parameters.length; + if (signature.hasRestParameter) { + var restType = getTypeOfSymbol(signature.parameters[length - 1]); + if (isTupleType(restType)) { + return length + (restType.typeArguments || ts.emptyArray).length - 1; + } + } + return length; + } + function getMinArgumentCount(signature) { + if (signature.hasRestParameter) { + var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); + if (isTupleType(restType)) { + var minLength = restType.target.minLength; + if (minLength > 0) { + return signature.parameters.length - 1 + minLength; + } + } + } + return signature.minArgumentCount; + } + function hasEffectiveRestParameter(signature) { + if (signature.hasRestParameter) { + var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); + return !isTupleType(restType) || restType.target.hasRestElement; + } + return false; + } + function getEffectiveRestType(signature) { + if (signature.hasRestParameter) { + var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); + return isTupleType(restType) ? getRestArrayTypeOfTupleType(restType) : restType; + } + return undefined; + } + function getNonArrayRestType(signature) { + var restType = getEffectiveRestType(signature); + return restType && !isArrayType(restType) && !isTypeAny(restType) ? restType : undefined; + } + function getTypeOfFirstParameterOfSignature(signature) { + return getTypeOfFirstParameterOfSignatureWithFallback(signature, neverType); + } + function getTypeOfFirstParameterOfSignatureWithFallback(signature, fallbackType) { + return signature.parameters.length > 0 ? getTypeAtPosition(signature, 0) : fallbackType; + } + function inferFromAnnotatedParameters(signature, context, mapper) { + var len = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); + for (var i = 0; i < len; i++) { + var declaration = signature.parameters[i].valueDeclaration; + if (declaration.type) { + var typeNode = ts.getEffectiveTypeAnnotationNode(declaration); + if (typeNode) { + inferTypes(mapper.inferences, getTypeFromTypeNode(typeNode), getTypeAtPosition(context, i)); + } + } + } + } + function assignContextualParameterTypes(signature, context) { + signature.typeParameters = context.typeParameters; + if (context.thisParameter) { + var parameter = signature.thisParameter; + if (!parameter || parameter.valueDeclaration && !parameter.valueDeclaration.type) { + if (!parameter) { + signature.thisParameter = createSymbolWithType(context.thisParameter, undefined); + } + assignTypeToParameterAndFixTypeParameters(signature.thisParameter, getTypeOfSymbol(context.thisParameter)); + } + } + var len = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); + for (var i = 0; i < len; i++) { + var parameter = signature.parameters[i]; + if (!ts.getEffectiveTypeAnnotationNode(parameter.valueDeclaration)) { + var contextualParameterType = getTypeAtPosition(context, i); + assignTypeToParameterAndFixTypeParameters(parameter, contextualParameterType); + } + } + if (signature.hasRestParameter) { + var parameter = ts.last(signature.parameters); + if (isTransientSymbol(parameter) || !ts.getEffectiveTypeAnnotationNode(parameter.valueDeclaration)) { + var contextualParameterType = getRestTypeAtPosition(context, len); + assignTypeToParameterAndFixTypeParameters(parameter, contextualParameterType); + } + } + } + function assignBindingElementTypes(pattern) { + for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (!ts.isOmittedExpression(element)) { + if (element.name.kind === 72) { + getSymbolLinks(getSymbolOfNode(element)).type = getTypeForBindingElement(element); + } + else { + assignBindingElementTypes(element.name); + } + } + } + } + function assignTypeToParameterAndFixTypeParameters(parameter, contextualType) { + var links = getSymbolLinks(parameter); + if (!links.type) { + links.type = contextualType; + var decl = parameter.valueDeclaration; + if (decl.name.kind !== 72) { + if (links.type === emptyObjectType) { + links.type = getTypeFromBindingPattern(decl.name); + } + assignBindingElementTypes(decl.name); + } + } + } + function createPromiseType(promisedType) { + var globalPromiseType = getGlobalPromiseType(true); + if (globalPromiseType !== emptyGenericType) { + promisedType = getAwaitedType(promisedType) || emptyObjectType; + return createTypeReference(globalPromiseType, [promisedType]); + } + return emptyObjectType; + } + function createPromiseLikeType(promisedType) { + var globalPromiseLikeType = getGlobalPromiseLikeType(true); + if (globalPromiseLikeType !== emptyGenericType) { + promisedType = getAwaitedType(promisedType) || emptyObjectType; + return createTypeReference(globalPromiseLikeType, [promisedType]); + } + return emptyObjectType; + } + function createPromiseReturnType(func, promisedType) { + var promiseType = createPromiseType(promisedType); + if (promiseType === emptyObjectType) { + error(func, ts.isImportCall(func) ? + ts.Diagnostics.A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option : + ts.Diagnostics.An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option); + return errorType; + } + else if (!getGlobalPromiseConstructorSymbol(true)) { + error(func, ts.isImportCall(func) ? + ts.Diagnostics.A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option : + ts.Diagnostics.An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option); + } + return promiseType; + } + function getReturnTypeFromBody(func, checkMode) { + if (!func.body) { + return errorType; + } + var functionFlags = ts.getFunctionFlags(func); + var type; + if (func.body.kind !== 218) { + type = checkExpressionCached(func.body, checkMode); + if (functionFlags & 2) { + type = checkAwaitedType(type, func, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); + } + } + else { + var types = checkAndAggregateReturnExpressionTypes(func, checkMode); + if (functionFlags & 1) { + types = ts.concatenate(checkAndAggregateYieldOperandTypes(func, checkMode), types); + if (!types || types.length === 0) { + var iterableIteratorAny = functionFlags & 2 + ? createAsyncIterableIteratorType(anyType) + : createIterableIteratorType(anyType); + if (noImplicitAny) { + error(func.asteriskToken, ts.Diagnostics.Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_type, typeToString(iterableIteratorAny)); + } + return iterableIteratorAny; + } + } + else { + if (!types) { + return functionFlags & 2 + ? createPromiseReturnType(func, neverType) + : neverType; + } + if (types.length === 0) { + return functionFlags & 2 + ? createPromiseReturnType(func, voidType) + : voidType; + } + } + type = getUnionType(types, 2); + } + var contextualSignature = getContextualSignatureForFunctionLikeDeclaration(func); + if (!contextualSignature) { + reportErrorsFromWidening(func, type); + } + if (isUnitType(type)) { + var contextualType = !contextualSignature ? undefined : + contextualSignature === getSignatureFromDeclaration(func) ? type : + getReturnTypeOfSignature(contextualSignature); + if (contextualType) { + switch (functionFlags & 3) { + case 3: + contextualType = getIteratedTypeOfGenerator(contextualType, true); + break; + case 1: + contextualType = getIteratedTypeOfGenerator(contextualType, false); + break; + case 2: + contextualType = getPromisedTypeOfPromise(contextualType); + break; + } + } + type = getWidenedLiteralLikeTypeForContextualType(type, contextualType); + } + var widenedType = getWidenedType(type); + switch (functionFlags & 3) { + case 3: + return createAsyncIterableIteratorType(widenedType); + case 1: + return createIterableIteratorType(widenedType); + case 2: + return createPromiseType(widenedType); + default: + return widenedType; + } + } + function checkAndAggregateYieldOperandTypes(func, checkMode) { + var aggregatedTypes = []; + var isAsync = (ts.getFunctionFlags(func) & 2) !== 0; + ts.forEachYieldExpression(func.body, function (yieldExpression) { + ts.pushIfUnique(aggregatedTypes, getYieldedTypeOfYieldExpression(yieldExpression, isAsync, checkMode)); + }); + return aggregatedTypes; + } + function getYieldedTypeOfYieldExpression(node, isAsync, checkMode) { + var errorNode = node.expression || node; + var expressionType = node.expression ? checkExpression(node.expression, checkMode) : undefinedWideningType; + var yieldedType = node.asteriskToken ? checkIteratedTypeOrElementType(expressionType, errorNode, false, isAsync) : expressionType; + return !isAsync ? yieldedType : getAwaitedType(yieldedType, errorNode, node.asteriskToken + ? ts.Diagnostics.Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member + : ts.Diagnostics.Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); + } + function getFactsFromTypeofSwitch(start, end, witnesses, hasDefault) { + var facts = 0; + if (hasDefault) { + for (var i = end; i < witnesses.length; i++) { + facts |= typeofNEFacts.get(witnesses[i]) || 32768; + } + for (var i = start; i < end; i++) { + facts &= ~(typeofNEFacts.get(witnesses[i]) || 0); + } + for (var i = 0; i < start; i++) { + facts |= typeofNEFacts.get(witnesses[i]) || 32768; + } + } + else { + for (var i = start; i < end; i++) { + facts |= typeofEQFacts.get(witnesses[i]) || 128; + } + for (var i = 0; i < start; i++) { + facts &= ~(typeofEQFacts.get(witnesses[i]) || 0); + } + } + return facts; + } + function isExhaustiveSwitchStatement(node) { + if (!node.possiblyExhaustive) { + return false; + } + if (node.expression.kind === 199) { + var operandType = getTypeOfExpression(node.expression.expression); + var witnesses = getSwitchClauseTypeOfWitnesses(node); + var notEqualFacts_1 = getFactsFromTypeofSwitch(0, 0, witnesses, true); + var type_5 = getBaseConstraintOfType(operandType) || operandType; + return !!(filterType(type_5, function (t) { return (getTypeFacts(t) & notEqualFacts_1) === notEqualFacts_1; }).flags & 131072); + } + var type = getTypeOfExpression(node.expression); + if (!isLiteralType(type)) { + return false; + } + var switchTypes = getSwitchClauseTypes(node); + if (!switchTypes.length || ts.some(switchTypes, isNeitherUnitTypeNorNever)) { + return false; + } + return eachTypeContainedIn(mapType(type, getRegularTypeOfLiteralType), switchTypes); + } + function functionHasImplicitReturn(func) { + if (!(func.flags & 128)) { + return false; + } + if (ts.some(func.body.statements, function (statement) { return statement.kind === 232 && isExhaustiveSwitchStatement(statement); })) { + return false; + } + return true; + } + function checkAndAggregateReturnExpressionTypes(func, checkMode) { + var functionFlags = ts.getFunctionFlags(func); + var aggregatedTypes = []; + var hasReturnWithNoExpression = functionHasImplicitReturn(func); + var hasReturnOfTypeNever = false; + ts.forEachReturnStatement(func.body, function (returnStatement) { + var expr = returnStatement.expression; + if (expr) { + var type = checkExpressionCached(expr, checkMode); + if (functionFlags & 2) { + type = checkAwaitedType(type, func, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); + } + if (type.flags & 131072) { + hasReturnOfTypeNever = true; + } + ts.pushIfUnique(aggregatedTypes, type); + } + else { + hasReturnWithNoExpression = true; + } + }); + if (aggregatedTypes.length === 0 && !hasReturnWithNoExpression && (hasReturnOfTypeNever || mayReturnNever(func))) { + return undefined; + } + if (strictNullChecks && aggregatedTypes.length && hasReturnWithNoExpression && + !(isJSConstructor(func) && aggregatedTypes.some(function (t) { return t.symbol === func.symbol; }))) { + ts.pushIfUnique(aggregatedTypes, undefinedType); + } + return aggregatedTypes; + } + function mayReturnNever(func) { + switch (func.kind) { + case 196: + case 197: + return true; + case 156: + return func.parent.kind === 188; + default: + return false; + } + } + function checkAllCodePathsInNonVoidFunctionReturnOrThrow(func, returnType) { + if (!produceDiagnostics) { + return; + } + if (returnType && maybeTypeOfKind(returnType, 1 | 16384)) { + return; + } + if (func.kind === 155 || ts.nodeIsMissing(func.body) || func.body.kind !== 218 || !functionHasImplicitReturn(func)) { + return; + } + var hasExplicitReturn = func.flags & 256; + if (returnType && returnType.flags & 131072) { + error(ts.getEffectiveReturnTypeNode(func), ts.Diagnostics.A_function_returning_never_cannot_have_a_reachable_end_point); + } + else if (returnType && !hasExplicitReturn) { + error(ts.getEffectiveReturnTypeNode(func), ts.Diagnostics.A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value); + } + else if (returnType && strictNullChecks && !isTypeAssignableTo(undefinedType, returnType)) { + error(ts.getEffectiveReturnTypeNode(func), ts.Diagnostics.Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined); + } + else if (compilerOptions.noImplicitReturns) { + if (!returnType) { + if (!hasExplicitReturn) { + return; + } + var inferredReturnType = getReturnTypeOfSignature(getSignatureFromDeclaration(func)); + if (isUnwrappedReturnTypeVoidOrAny(func, inferredReturnType)) { + return; + } + } + error(ts.getEffectiveReturnTypeNode(func) || func, ts.Diagnostics.Not_all_code_paths_return_a_value); + } + } + function checkFunctionExpressionOrObjectLiteralMethod(node, checkMode) { + ts.Debug.assert(node.kind !== 156 || ts.isObjectLiteralMethod(node)); + checkNodeDeferred(node); + if (checkMode === 1 && isContextSensitive(node)) { + if (!ts.getEffectiveReturnTypeNode(node) && hasContextSensitiveReturnExpression(node)) { + var links_1 = getNodeLinks(node); + if (links_1.contextFreeType) { + return links_1.contextFreeType; + } + var returnType = getReturnTypeFromBody(node, checkMode); + var returnOnlySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, returnType, undefined, 0, false, false); + var returnOnlyType = createAnonymousType(node.symbol, emptySymbols, [returnOnlySignature], ts.emptyArray, undefined, undefined); + returnOnlyType.flags |= 536870912; + return links_1.contextFreeType = returnOnlyType; + } + return anyFunctionType; + } + var hasGrammarError = checkGrammarFunctionLikeDeclaration(node); + if (!hasGrammarError && node.kind === 196) { + checkGrammarForGenerator(node); + } + var links = getNodeLinks(node); + var type = getTypeOfSymbol(getMergedSymbol(node.symbol)); + if (isTypeAny(type)) { + return type; + } + if (!(links.flags & 1024)) { + var contextualSignature = getContextualSignature(node); + if (!(links.flags & 1024)) { + links.flags |= 1024; + if (contextualSignature) { + var signature = getSignaturesOfType(type, 0)[0]; + if (isContextSensitive(node)) { + var contextualMapper = getContextualMapper(node); + if (checkMode === 2) { + inferFromAnnotatedParameters(signature, contextualSignature, contextualMapper); + } + var instantiatedContextualSignature = contextualMapper === identityMapper ? + contextualSignature : instantiateSignature(contextualSignature, contextualMapper); + assignContextualParameterTypes(signature, instantiatedContextualSignature); + } + if (!getReturnTypeFromAnnotation(node) && !signature.resolvedReturnType) { + var returnType = getReturnTypeFromBody(node, checkMode); + if (!signature.resolvedReturnType) { + signature.resolvedReturnType = returnType; + } + } + } + checkSignatureDeclaration(node); + } + } + return type; + } + function getReturnOrPromisedType(node, functionFlags) { + var type = getReturnTypeFromAnnotation(node); + return type && ((functionFlags & 3) === 2) ? + getAwaitedType(type) || errorType : type; + } + function checkFunctionExpressionOrObjectLiteralMethodDeferred(node) { + ts.Debug.assert(node.kind !== 156 || ts.isObjectLiteralMethod(node)); + var functionFlags = ts.getFunctionFlags(node); + var returnOrPromisedType = getReturnOrPromisedType(node, functionFlags); + if ((functionFlags & 1) === 0) { + checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnOrPromisedType); + } + if (node.body) { + if (!ts.getEffectiveReturnTypeNode(node)) { + getReturnTypeOfSignature(getSignatureFromDeclaration(node)); + } + if (node.body.kind === 218) { + checkSourceElement(node.body); + } + else { + var exprType = checkExpression(node.body); + if (returnOrPromisedType) { + if ((functionFlags & 3) === 2) { + var awaitedType = checkAwaitedType(exprType, node.body, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); + checkTypeAssignableToAndOptionallyElaborate(awaitedType, returnOrPromisedType, node.body, node.body); + } + else { + checkTypeAssignableToAndOptionallyElaborate(exprType, returnOrPromisedType, node.body, node.body); + } + } + } + } + } + function checkArithmeticOperandType(operand, type, diagnostic) { + if (!isTypeAssignableTo(type, numberOrBigIntType)) { + error(operand, diagnostic); + return false; + } + return true; + } + function isReadonlyAssignmentDeclaration(d) { + if (!ts.isCallExpression(d)) { + return false; + } + if (!ts.isBindableObjectDefinePropertyCall(d)) { + return false; + } + var objectLitType = checkExpressionCached(d.arguments[2]); + var valueType = getTypeOfPropertyOfType(objectLitType, "value"); + if (valueType) { + var writableProp = getPropertyOfType(objectLitType, "writable"); + var writableType = writableProp && getTypeOfSymbol(writableProp); + if (!writableType || writableType === falseType || writableType === regularFalseType) { + return true; + } + if (writableProp && writableProp.valueDeclaration && ts.isPropertyAssignment(writableProp.valueDeclaration)) { + var initializer = writableProp.valueDeclaration.initializer; + var rawOriginalType = checkExpression(initializer); + if (rawOriginalType === falseType || rawOriginalType === regularFalseType) { + return true; + } + } + return false; + } + var setProp = getPropertyOfType(objectLitType, "set"); + return !setProp; + } + function isReadonlySymbol(symbol) { + return !!(ts.getCheckFlags(symbol) & 8 || + symbol.flags & 4 && ts.getDeclarationModifierFlagsFromSymbol(symbol) & 64 || + symbol.flags & 3 && getDeclarationNodeFlagsFromSymbol(symbol) & 2 || + symbol.flags & 98304 && !(symbol.flags & 65536) || + symbol.flags & 8 || + ts.some(symbol.declarations, isReadonlyAssignmentDeclaration)); + } + function isReferenceToReadonlyEntity(expr, symbol) { + if (isReadonlySymbol(symbol)) { + if (symbol.flags & 4 && + (expr.kind === 189 || expr.kind === 190) && + expr.expression.kind === 100) { + var func = ts.getContainingFunction(expr); + if (!(func && func.kind === 157)) { + return true; + } + return !symbol.valueDeclaration || !(func.parent === symbol.valueDeclaration.parent || func === symbol.valueDeclaration.parent); + } + return true; + } + return false; + } + function isReferenceThroughNamespaceImport(expr) { + if (expr.kind === 189 || expr.kind === 190) { + var node = ts.skipParentheses(expr.expression); + if (node.kind === 72) { + var symbol = getNodeLinks(node).resolvedSymbol; + if (symbol.flags & 2097152) { + var declaration = getDeclarationOfAliasSymbol(symbol); + return !!declaration && declaration.kind === 251; + } + } + } + return false; + } + function checkReferenceExpression(expr, invalidReferenceMessage) { + var node = ts.skipOuterExpressions(expr, 2 | 1); + if (node.kind !== 72 && node.kind !== 189 && node.kind !== 190) { + error(expr, invalidReferenceMessage); + return false; + } + return true; + } + function checkDeleteExpression(node) { + checkExpression(node.expression); + var expr = ts.skipParentheses(node.expression); + if (expr.kind !== 189 && expr.kind !== 190) { + error(expr, ts.Diagnostics.The_operand_of_a_delete_operator_must_be_a_property_reference); + return booleanType; + } + var links = getNodeLinks(expr); + var symbol = getExportSymbolOfValueSymbolIfExported(links.resolvedSymbol); + if (symbol && isReadonlySymbol(symbol)) { + error(expr, ts.Diagnostics.The_operand_of_a_delete_operator_cannot_be_a_read_only_property); + } + return booleanType; + } + function checkTypeOfExpression(node) { + checkExpression(node.expression); + return typeofType; + } + function checkVoidExpression(node) { + checkExpression(node.expression); + return undefinedWideningType; + } + function checkAwaitExpression(node) { + if (produceDiagnostics) { + if (!(node.flags & 16384)) { + grammarErrorOnFirstToken(node, ts.Diagnostics.await_expression_is_only_allowed_within_an_async_function); + } + if (isInParameterInitializerBeforeContainingFunction(node)) { + error(node, ts.Diagnostics.await_expressions_cannot_be_used_in_a_parameter_initializer); + } + } + var operandType = checkExpression(node.expression); + return checkAwaitedType(operandType, node, ts.Diagnostics.Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); + } + function checkPrefixUnaryExpression(node) { + var operandType = checkExpression(node.operand); + if (operandType === silentNeverType) { + return silentNeverType; + } + switch (node.operand.kind) { + case 8: + switch (node.operator) { + case 39: + return getFreshTypeOfLiteralType(getLiteralType(-node.operand.text)); + case 38: + return getFreshTypeOfLiteralType(getLiteralType(+node.operand.text)); + } + break; + case 9: + if (node.operator === 39) { + return getFreshTypeOfLiteralType(getLiteralType({ + negative: true, + base10Value: ts.parsePseudoBigInt(node.operand.text) + })); + } + } + switch (node.operator) { + case 38: + case 39: + case 53: + checkNonNullType(operandType, node.operand); + if (maybeTypeOfKind(operandType, 12288)) { + error(node.operand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(node.operator)); + } + if (node.operator === 38) { + if (maybeTypeOfKind(operandType, 2112)) { + error(node.operand, ts.Diagnostics.Operator_0_cannot_be_applied_to_type_1, ts.tokenToString(node.operator), typeToString(operandType)); + } + return numberType; + } + return getUnaryResultType(operandType); + case 52: + checkTruthinessExpression(node.operand); + var facts = getTypeFacts(operandType) & (4194304 | 8388608); + return facts === 4194304 ? falseType : + facts === 8388608 ? trueType : + booleanType; + case 44: + case 45: + var ok = checkArithmeticOperandType(node.operand, checkNonNullType(operandType, node.operand), ts.Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_bigint_or_an_enum_type); + if (ok) { + checkReferenceExpression(node.operand, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access); + } + return getUnaryResultType(operandType); + } + return errorType; + } + function checkPostfixUnaryExpression(node) { + var operandType = checkExpression(node.operand); + if (operandType === silentNeverType) { + return silentNeverType; + } + var ok = checkArithmeticOperandType(node.operand, checkNonNullType(operandType, node.operand), ts.Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_bigint_or_an_enum_type); + if (ok) { + checkReferenceExpression(node.operand, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access); + } + return getUnaryResultType(operandType); + } + function getUnaryResultType(operandType) { + if (maybeTypeOfKind(operandType, 2112)) { + return isTypeAssignableToKind(operandType, 3) || maybeTypeOfKind(operandType, 296) + ? numberOrBigIntType + : bigintType; + } + return numberType; + } + function maybeTypeOfKind(type, kind) { + if (type.flags & kind & ~134217728 || kind & 134217728 && isGenericMappedType(type)) { + return true; + } + if (type.flags & 3145728) { + var types = type.types; + for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { + var t = types_15[_i]; + if (maybeTypeOfKind(t, kind)) { + return true; + } + } + } + return false; + } + function isTypeAssignableToKind(source, kind, strict) { + if (source.flags & kind) { + return true; + } + if (strict && source.flags & (3 | 16384 | 32768 | 65536)) { + return false; + } + return !!(kind & 296) && isTypeAssignableTo(source, numberType) || + !!(kind & 2112) && isTypeAssignableTo(source, bigintType) || + !!(kind & 132) && isTypeAssignableTo(source, stringType) || + !!(kind & 528) && isTypeAssignableTo(source, booleanType) || + !!(kind & 16384) && isTypeAssignableTo(source, voidType) || + !!(kind & 131072) && isTypeAssignableTo(source, neverType) || + !!(kind & 65536) && isTypeAssignableTo(source, nullType) || + !!(kind & 32768) && isTypeAssignableTo(source, undefinedType) || + !!(kind & 4096) && isTypeAssignableTo(source, esSymbolType) || + !!(kind & 67108864) && isTypeAssignableTo(source, nonPrimitiveType); + } + function allTypesAssignableToKind(source, kind, strict) { + return source.flags & 1048576 ? + ts.every(source.types, function (subType) { return allTypesAssignableToKind(subType, kind, strict); }) : + isTypeAssignableToKind(source, kind, strict); + } + function isConstEnumObjectType(type) { + return !!(ts.getObjectFlags(type) & 16) && !!type.symbol && isConstEnumSymbol(type.symbol); + } + function isConstEnumSymbol(symbol) { + return (symbol.flags & 128) !== 0; + } + function checkInstanceOfExpression(left, right, leftType, rightType) { + if (leftType === silentNeverType || rightType === silentNeverType) { + return silentNeverType; + } + if (!isTypeAny(leftType) && + allTypesAssignableToKind(leftType, 131068)) { + error(left, ts.Diagnostics.The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter); + } + if (!(isTypeAny(rightType) || typeHasCallOrConstructSignatures(rightType) || isTypeSubtypeOf(rightType, globalFunctionType))) { + error(right, ts.Diagnostics.The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_Function_interface_type); + } + return booleanType; + } + function checkInExpression(left, right, leftType, rightType) { + if (leftType === silentNeverType || rightType === silentNeverType) { + return silentNeverType; + } + leftType = checkNonNullType(leftType, left); + rightType = checkNonNullType(rightType, right); + if (!(isTypeComparableTo(leftType, stringType) || isTypeAssignableToKind(leftType, 296 | 12288))) { + error(left, ts.Diagnostics.The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol); + } + if (!isTypeAssignableToKind(rightType, 67108864 | 58982400)) { + error(right, ts.Diagnostics.The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter); + } + return booleanType; + } + function checkObjectLiteralAssignment(node, sourceType, rightIsThis) { + var properties = node.properties; + if (strictNullChecks && properties.length === 0) { + return checkNonNullType(sourceType, node); + } + for (var _i = 0, properties_6 = properties; _i < properties_6.length; _i++) { + var p = properties_6[_i]; + checkObjectLiteralDestructuringPropertyAssignment(sourceType, p, properties, rightIsThis); + } + return sourceType; + } + function checkObjectLiteralDestructuringPropertyAssignment(objectLiteralType, property, allProperties, rightIsThis) { + if (rightIsThis === void 0) { rightIsThis = false; } + if (property.kind === 275 || property.kind === 276) { + var name = property.name; + if (name.kind === 149) { + checkComputedPropertyName(name); + } + if (isComputedNonLiteralName(name)) { + return undefined; + } + var type = getTypeOfObjectLiteralDestructuringProperty(objectLiteralType, name, property, rightIsThis); + if (type) { + return checkDestructuringAssignment(property.kind === 276 ? property : property.initializer, type); + } + else { + error(name, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(objectLiteralType), ts.declarationNameToString(name)); + } + } + else if (property.kind === 277) { + if (languageVersion < 6) { + checkExternalEmitHelpers(property, 4); + } + var nonRestNames = []; + if (allProperties) { + for (var i = 0; i < allProperties.length - 1; i++) { + nonRestNames.push(allProperties[i].name); + } + } + var type = getRestType(objectLiteralType, nonRestNames, objectLiteralType.symbol); + checkGrammarForDisallowedTrailingComma(allProperties, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma); + return checkDestructuringAssignment(property.expression, type); + } + else { + error(property, ts.Diagnostics.Property_assignment_expected); + } + } + function getTypeOfObjectLiteralDestructuringProperty(objectLiteralType, name, property, rightIsThis) { + if (isTypeAny(objectLiteralType)) { + return objectLiteralType; + } + var type; + var text = ts.getTextOfPropertyName(name); + if (text) { + var prop = getPropertyOfType(objectLiteralType, text); + if (prop) { + markPropertyAsReferenced(prop, property, rightIsThis); + checkPropertyAccessibility(property, false, objectLiteralType, prop); + type = getTypeOfSymbol(prop); + } + type = type || (isNumericLiteralName(text) ? getIndexTypeOfType(objectLiteralType, 1) : undefined); + } + return type || getIndexTypeOfType(objectLiteralType, 0); + } + function checkArrayLiteralAssignment(node, sourceType, checkMode) { + var elements = node.elements; + if (languageVersion < 2 && compilerOptions.downlevelIteration) { + checkExternalEmitHelpers(node, 512); + } + var elementType = checkIteratedTypeOrElementType(sourceType, node, false, false) || errorType; + for (var i = 0; i < elements.length; i++) { + checkArrayLiteralDestructuringElementAssignment(node, sourceType, i, elementType, checkMode); + } + return sourceType; + } + function checkArrayLiteralDestructuringElementAssignment(node, sourceType, elementIndex, elementType, checkMode) { + var elements = node.elements; + var element = elements[elementIndex]; + if (element.kind !== 210) { + if (element.kind !== 208) { + var propName = "" + elementIndex; + var type = isTypeAny(sourceType) ? sourceType : + everyType(sourceType, isTupleLikeType) ? getTupleElementType(sourceType, elementIndex) : + elementType; + if (type) { + return checkDestructuringAssignment(element, type, checkMode); + } + checkExpression(element); + if (isTupleType(sourceType)) { + error(element, ts.Diagnostics.Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2, typeToString(sourceType), getTypeReferenceArity(sourceType), elements.length); + } + else { + error(element, ts.Diagnostics.Type_0_has_no_property_1, typeToString(sourceType), propName); + } + } + else { + if (elementIndex < elements.length - 1) { + error(element, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern); + } + else { + var restExpression = element.expression; + if (restExpression.kind === 204 && restExpression.operatorToken.kind === 59) { + error(restExpression.operatorToken, ts.Diagnostics.A_rest_element_cannot_have_an_initializer); + } + else { + checkGrammarForDisallowedTrailingComma(node.elements, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma); + var type = everyType(sourceType, isTupleType) ? + mapType(sourceType, function (t) { return sliceTupleType(t, elementIndex); }) : + createArrayType(elementType); + return checkDestructuringAssignment(restExpression, type, checkMode); + } + } + } + } + return undefined; + } + function checkDestructuringAssignment(exprOrAssignment, sourceType, checkMode, rightIsThis) { + var target; + if (exprOrAssignment.kind === 276) { + var prop = exprOrAssignment; + if (prop.objectAssignmentInitializer) { + if (strictNullChecks && + !(getFalsyFlags(checkExpression(prop.objectAssignmentInitializer)) & 32768)) { + sourceType = getTypeWithFacts(sourceType, 524288); + } + checkBinaryLikeExpression(prop.name, prop.equalsToken, prop.objectAssignmentInitializer, checkMode); + } + target = exprOrAssignment.name; + } + else { + target = exprOrAssignment; + } + if (target.kind === 204 && target.operatorToken.kind === 59) { + checkBinaryExpression(target, checkMode); + target = target.left; + } + if (target.kind === 188) { + return checkObjectLiteralAssignment(target, sourceType, rightIsThis); + } + if (target.kind === 187) { + return checkArrayLiteralAssignment(target, sourceType, checkMode); + } + return checkReferenceAssignment(target, sourceType, checkMode); + } + function checkReferenceAssignment(target, sourceType, checkMode) { + var targetType = checkExpression(target, checkMode); + var error = target.parent.kind === 277 ? + ts.Diagnostics.The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access : + ts.Diagnostics.The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access; + if (checkReferenceExpression(target, error)) { + checkTypeAssignableToAndOptionallyElaborate(sourceType, targetType, target, target); + } + return sourceType; + } + function isSideEffectFree(node) { + node = ts.skipParentheses(node); + switch (node.kind) { + case 72: + case 10: + case 13: + case 193: + case 206: + case 14: + case 8: + case 9: + case 102: + case 87: + case 96: + case 141: + case 196: + case 209: + case 197: + case 187: + case 188: + case 199: + case 213: + case 261: + case 260: + return true; + case 205: + return isSideEffectFree(node.whenTrue) && + isSideEffectFree(node.whenFalse); + case 204: + if (ts.isAssignmentOperator(node.operatorToken.kind)) { + return false; + } + return isSideEffectFree(node.left) && + isSideEffectFree(node.right); + case 202: + case 203: + switch (node.operator) { + case 52: + case 38: + case 39: + case 53: + return true; + } + return false; + case 200: + case 194: + case 212: + default: + return false; + } + } + function isTypeEqualityComparableTo(source, target) { + return (target.flags & 98304) !== 0 || isTypeComparableTo(source, target); + } + function checkBinaryExpression(node, checkMode) { + if (ts.isInJSFile(node) && ts.getAssignedExpandoInitializer(node)) { + return checkExpression(node.right, checkMode); + } + return checkBinaryLikeExpression(node.left, node.operatorToken, node.right, checkMode, node); + } + function checkBinaryLikeExpression(left, operatorToken, right, checkMode, errorNode) { + var operator = operatorToken.kind; + if (operator === 59 && (left.kind === 188 || left.kind === 187)) { + return checkDestructuringAssignment(left, checkExpression(right, checkMode), checkMode, right.kind === 100); + } + var leftType; + if (operator === 54 || operator === 55) { + leftType = checkTruthinessExpression(left, checkMode); + } + else { + leftType = checkExpression(left, checkMode); + } + var rightType = checkExpression(right, checkMode); + switch (operator) { + case 40: + case 41: + case 62: + case 63: + case 42: + case 64: + case 43: + case 65: + case 39: + case 61: + case 46: + case 66: + case 47: + case 67: + case 48: + case 68: + case 50: + case 70: + case 51: + case 71: + case 49: + case 69: + if (leftType === silentNeverType || rightType === silentNeverType) { + return silentNeverType; + } + leftType = checkNonNullType(leftType, left); + rightType = checkNonNullType(rightType, right); + var suggestedOperator = void 0; + if ((leftType.flags & 528) && + (rightType.flags & 528) && + (suggestedOperator = getSuggestedBooleanOperator(operatorToken.kind)) !== undefined) { + error(errorNode || operatorToken, ts.Diagnostics.The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead, ts.tokenToString(operatorToken.kind), ts.tokenToString(suggestedOperator)); + return numberType; + } + else { + var leftOk = checkArithmeticOperandType(left, leftType, ts.Diagnostics.The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type); + var rightOk = checkArithmeticOperandType(right, rightType, ts.Diagnostics.The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type); + var resultType_1; + if ((isTypeAssignableToKind(leftType, 3) && isTypeAssignableToKind(rightType, 3)) || + !(maybeTypeOfKind(leftType, 2112) || maybeTypeOfKind(rightType, 2112))) { + resultType_1 = numberType; + } + else if (isTypeAssignableToKind(leftType, 2112) && isTypeAssignableToKind(rightType, 2112)) { + switch (operator) { + case 48: + case 68: + reportOperatorError(); + } + resultType_1 = bigintType; + } + else { + reportOperatorError(); + resultType_1 = errorType; + } + if (leftOk && rightOk) { + checkAssignmentOperator(resultType_1); + } + return resultType_1; + } + case 38: + case 60: + if (leftType === silentNeverType || rightType === silentNeverType) { + return silentNeverType; + } + if (!isTypeAssignableToKind(leftType, 132) && !isTypeAssignableToKind(rightType, 132)) { + leftType = checkNonNullType(leftType, left); + rightType = checkNonNullType(rightType, right); + } + var resultType = void 0; + if (isTypeAssignableToKind(leftType, 296, true) && isTypeAssignableToKind(rightType, 296, true)) { + resultType = numberType; + } + else if (isTypeAssignableToKind(leftType, 2112, true) && isTypeAssignableToKind(rightType, 2112, true)) { + resultType = bigintType; + } + else if (isTypeAssignableToKind(leftType, 132, true) || isTypeAssignableToKind(rightType, 132, true)) { + resultType = stringType; + } + else if (isTypeAny(leftType) || isTypeAny(rightType)) { + resultType = leftType === errorType || rightType === errorType ? errorType : anyType; + } + if (resultType && !checkForDisallowedESSymbolOperand(operator)) { + return resultType; + } + if (!resultType) { + reportOperatorError(); + return anyType; + } + if (operator === 60) { + checkAssignmentOperator(resultType); + } + return resultType; + case 28: + case 30: + case 31: + case 32: + if (checkForDisallowedESSymbolOperand(operator)) { + leftType = getBaseTypeOfLiteralType(checkNonNullType(leftType, left)); + rightType = getBaseTypeOfLiteralType(checkNonNullType(rightType, right)); + if (!(isTypeComparableTo(leftType, rightType) || isTypeComparableTo(rightType, leftType) || + (isTypeAssignableTo(leftType, numberOrBigIntType) && isTypeAssignableTo(rightType, numberOrBigIntType)))) { + reportOperatorError(); + } + } + return booleanType; + case 33: + case 34: + case 35: + case 36: + var leftIsLiteral = isLiteralType(leftType); + var rightIsLiteral = isLiteralType(rightType); + if (!leftIsLiteral || !rightIsLiteral) { + leftType = leftIsLiteral ? getBaseTypeOfLiteralType(leftType) : leftType; + rightType = rightIsLiteral ? getBaseTypeOfLiteralType(rightType) : rightType; + } + if (!isTypeEqualityComparableTo(leftType, rightType) && !isTypeEqualityComparableTo(rightType, leftType)) { + reportOperatorError(); + } + return booleanType; + case 94: + return checkInstanceOfExpression(left, right, leftType, rightType); + case 93: + return checkInExpression(left, right, leftType, rightType); + case 54: + return getTypeFacts(leftType) & 4194304 ? + getUnionType([extractDefinitelyFalsyTypes(strictNullChecks ? leftType : getBaseTypeOfLiteralType(rightType)), rightType]) : + leftType; + case 55: + return getTypeFacts(leftType) & 8388608 ? + getUnionType([removeDefinitelyFalsyTypes(leftType), rightType], 2) : + leftType; + case 59: + var declKind = ts.isBinaryExpression(left.parent) ? ts.getAssignmentDeclarationKind(left.parent) : 0; + checkAssignmentDeclaration(declKind, rightType); + if (isAssignmentDeclaration(declKind)) { + if (!(rightType.flags & 524288) || + declKind !== 2 && + declKind !== 6 && + !isEmptyObjectType(rightType) && + !isFunctionObjectType(rightType) && + !(ts.getObjectFlags(rightType) & 1)) { + checkAssignmentOperator(rightType); + } + return leftType; + } + else { + checkAssignmentOperator(rightType); + return getRegularTypeOfObjectLiteral(rightType); + } + case 27: + if (!compilerOptions.allowUnreachableCode && isSideEffectFree(left) && !isEvalNode(right)) { + error(left, ts.Diagnostics.Left_side_of_comma_operator_is_unused_and_has_no_side_effects); + } + return rightType; + default: + return ts.Debug.fail(); + } + function checkAssignmentDeclaration(kind, rightType) { + if (kind === 2) { + for (var _i = 0, _a = getPropertiesOfObjectType(rightType); _i < _a.length; _i++) { + var prop = _a[_i]; + var propType = getTypeOfSymbol(prop); + if (propType.symbol && propType.symbol.flags & 32) { + var name = prop.escapedName; + var symbol = resolveName(prop.valueDeclaration, name, 67897832, undefined, name, false); + if (symbol && symbol.declarations.some(ts.isJSDocTypedefTag)) { + grammarErrorOnNode(symbol.declarations[0], ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name)); + return grammarErrorOnNode(prop.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name)); + } + } + } + } + } + function isEvalNode(node) { + return node.kind === 72 && node.escapedText === "eval"; + } + function checkForDisallowedESSymbolOperand(operator) { + var offendingSymbolOperand = maybeTypeOfKind(leftType, 12288) ? left : + maybeTypeOfKind(rightType, 12288) ? right : + undefined; + if (offendingSymbolOperand) { + error(offendingSymbolOperand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(operator)); + return false; + } + return true; + } + function getSuggestedBooleanOperator(operator) { + switch (operator) { + case 50: + case 70: + return 55; + case 51: + case 71: + return 36; + case 49: + case 69: + return 54; + default: + return undefined; + } + } + function checkAssignmentOperator(valueType) { + if (produceDiagnostics && ts.isAssignmentOperator(operator)) { + if (checkReferenceExpression(left, ts.Diagnostics.The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access) + && (!ts.isIdentifier(left) || ts.unescapeLeadingUnderscores(left.escapedText) !== "exports")) { + checkTypeAssignableToAndOptionallyElaborate(valueType, leftType, left, right); + } + } + } + function isAssignmentDeclaration(kind) { + switch (kind) { + case 2: + return true; + case 1: + case 5: + case 6: + case 3: + case 4: + var symbol = getSymbolOfNode(left); + var init = ts.getAssignedExpandoInitializer(right); + return init && ts.isObjectLiteralExpression(init) && + symbol && ts.hasEntries(symbol.exports); + default: + return false; + } + } + function reportOperatorError() { + var leftStr = typeToString(leftType); + var rightStr = typeToString(rightType); + var errNode = errorNode || operatorToken; + if (!tryGiveBetterPrimaryError(errNode, leftStr, rightStr)) { + error(errNode, ts.Diagnostics.Operator_0_cannot_be_applied_to_types_1_and_2, ts.tokenToString(operatorToken.kind), leftStr, rightStr); + } + } + function tryGiveBetterPrimaryError(errNode, leftStr, rightStr) { + switch (operatorToken.kind) { + case 35: + case 33: + return error(errNode, ts.Diagnostics.This_condition_will_always_return_0_since_the_types_1_and_2_have_no_overlap, "false", leftStr, rightStr); + case 36: + case 34: + return error(errNode, ts.Diagnostics.This_condition_will_always_return_0_since_the_types_1_and_2_have_no_overlap, "true", leftStr, rightStr); + } + return undefined; + } + } + function isYieldExpressionInClass(node) { + var current = node; + var parent = node.parent; + while (parent) { + if (ts.isFunctionLike(parent) && current === parent.body) { + return false; + } + else if (ts.isClassLike(current)) { + return true; + } + current = parent; + parent = parent.parent; + } + return false; + } + function checkYieldExpression(node) { + if (produceDiagnostics) { + if (!(node.flags & 4096) || isYieldExpressionInClass(node)) { + grammarErrorOnFirstToken(node, ts.Diagnostics.A_yield_expression_is_only_allowed_in_a_generator_body); + } + if (isInParameterInitializerBeforeContainingFunction(node)) { + error(node, ts.Diagnostics.yield_expressions_cannot_be_used_in_a_parameter_initializer); + } + } + var func = ts.getContainingFunction(node); + if (!func) + return anyType; + var functionFlags = ts.getFunctionFlags(func); + if (!(functionFlags & 1)) { + return anyType; + } + if (node.asteriskToken) { + if ((functionFlags & 3) === 3 && + languageVersion < 6) { + checkExternalEmitHelpers(node, 26624); + } + if ((functionFlags & 3) === 1 && + languageVersion < 2 && compilerOptions.downlevelIteration) { + checkExternalEmitHelpers(node, 256); + } + } + var isAsync = (functionFlags & 2) !== 0; + var yieldedType = getYieldedTypeOfYieldExpression(node, isAsync); + var returnType = getReturnTypeFromAnnotation(func); + if (returnType) { + var signatureElementType = getIteratedTypeOfGenerator(returnType, isAsync) || anyType; + checkTypeAssignableToAndOptionallyElaborate(yieldedType, signatureElementType, node.expression || node, node.expression); + } + return anyType; + } + function checkConditionalExpression(node, checkMode) { + checkTruthinessExpression(node.condition); + var type1 = checkExpression(node.whenTrue, checkMode); + var type2 = checkExpression(node.whenFalse, checkMode); + return getUnionType([type1, type2], 2); + } + function checkTemplateExpression(node) { + ts.forEach(node.templateSpans, function (templateSpan) { + if (maybeTypeOfKind(checkExpression(templateSpan.expression), 12288)) { + error(templateSpan.expression, ts.Diagnostics.Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_in_String); + } + }); + return stringType; + } + function getContextNode(node) { + if (node.kind === 268 && !ts.isJsxSelfClosingElement(node.parent)) { + return node.parent.parent; + } + return node; + } + function checkExpressionWithContextualType(node, contextualType, contextualMapper) { + var context = getContextNode(node); + var saveContextualType = context.contextualType; + var saveContextualMapper = context.contextualMapper; + context.contextualType = contextualType; + context.contextualMapper = contextualMapper; + var checkMode = contextualMapper === identityMapper ? 1 : + contextualMapper ? 2 : 3; + var result = checkExpression(node, checkMode); + context.contextualType = saveContextualType; + context.contextualMapper = saveContextualMapper; + return result; + } + function checkExpressionCached(node, checkMode) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + if (checkMode) { + return checkExpression(node, checkMode); + } + var saveFlowLoopStart = flowLoopStart; + flowLoopStart = flowLoopCount; + links.resolvedType = checkExpression(node, checkMode); + flowLoopStart = saveFlowLoopStart; + } + return links.resolvedType; + } + function isTypeAssertion(node) { + node = ts.skipParentheses(node); + return node.kind === 194 || node.kind === 212; + } + function checkDeclarationInitializer(declaration) { + var initializer = ts.getEffectiveInitializer(declaration); + var type = getTypeOfExpression(initializer, true); + var widened = ts.getCombinedNodeFlags(declaration) & 2 || + ts.isDeclarationReadonly(declaration) || + isTypeAssertion(initializer) ? type : getWidenedLiteralType(type); + if (ts.isInJSFile(declaration)) { + if (widened.flags & 98304) { + reportImplicitAny(declaration, anyType); + return anyType; + } + else if (isEmptyArrayLiteralType(widened)) { + reportImplicitAny(declaration, anyArrayType); + return anyArrayType; + } + } + return widened; + } + function isLiteralOfContextualType(candidateType, contextualType) { + if (contextualType) { + if (contextualType.flags & 3145728) { + var types = contextualType.types; + return ts.some(types, function (t) { return isLiteralOfContextualType(candidateType, t); }); + } + if (contextualType.flags & 58982400) { + var constraint = getBaseConstraintOfType(contextualType) || emptyObjectType; + return maybeTypeOfKind(constraint, 4) && maybeTypeOfKind(candidateType, 128) || + maybeTypeOfKind(constraint, 8) && maybeTypeOfKind(candidateType, 256) || + maybeTypeOfKind(constraint, 64) && maybeTypeOfKind(candidateType, 2048) || + maybeTypeOfKind(constraint, 4096) && maybeTypeOfKind(candidateType, 8192) || + isLiteralOfContextualType(candidateType, constraint); + } + return !!(contextualType.flags & (128 | 4194304) && maybeTypeOfKind(candidateType, 128) || + contextualType.flags & 256 && maybeTypeOfKind(candidateType, 256) || + contextualType.flags & 2048 && maybeTypeOfKind(candidateType, 2048) || + contextualType.flags & 512 && maybeTypeOfKind(candidateType, 512) || + contextualType.flags & 8192 && maybeTypeOfKind(candidateType, 8192)); + } + return false; + } + function checkExpressionForMutableLocation(node, checkMode, contextualType, forceTuple) { + if (arguments.length === 2) { + contextualType = getContextualType(node); + } + var type = checkExpression(node, checkMode, forceTuple); + return isTypeAssertion(node) ? type : + getWidenedLiteralLikeTypeForContextualType(type, contextualType); + } + function checkPropertyAssignment(node, checkMode) { + if (node.name.kind === 149) { + checkComputedPropertyName(node.name); + } + return checkExpressionForMutableLocation(node.initializer, checkMode); + } + function checkObjectLiteralMethod(node, checkMode) { + checkGrammarMethod(node); + if (node.name.kind === 149) { + checkComputedPropertyName(node.name); + } + var uninstantiatedType = checkFunctionExpressionOrObjectLiteralMethod(node, checkMode); + return instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode); + } + function instantiateTypeWithSingleGenericCallSignature(node, type, checkMode) { + if (checkMode === 2) { + var signature = getSingleCallSignature(type); + if (signature && signature.typeParameters) { + var contextualType = getApparentTypeOfContextualType(node); + if (contextualType) { + var contextualSignature = getSingleCallSignature(getNonNullableType(contextualType)); + if (contextualSignature && !contextualSignature.typeParameters) { + return getOrCreateTypeFromSignature(instantiateSignatureInContextOf(signature, contextualSignature, getContextualMapper(node))); + } + } + } + } + return type; + } + function getTypeOfExpression(node, cache) { + var expr = ts.skipParentheses(node); + if (expr.kind === 191 && expr.expression.kind !== 98 && !ts.isRequireCall(expr, true) && !isSymbolOrSymbolForCall(expr)) { + var funcType = checkNonNullExpression(expr.expression); + var signature = getSingleCallSignature(funcType); + if (signature && !signature.typeParameters) { + return getReturnTypeOfSignature(signature); + } + } + else if (expr.kind === 194 || expr.kind === 212) { + return getTypeFromTypeNode(expr.type); + } + return cache ? checkExpressionCached(node) : checkExpression(node); + } + function getContextFreeTypeOfExpression(node) { + var links = getNodeLinks(node); + if (links.contextFreeType) { + return links.contextFreeType; + } + var saveContextualType = node.contextualType; + node.contextualType = anyType; + var type = links.contextFreeType = checkExpression(node, 1); + node.contextualType = saveContextualType; + return type; + } + function checkExpression(node, checkMode, forceTuple) { + var type; + if (node.kind === 148) { + type = checkQualifiedName(node); + } + else { + var uninstantiatedType = checkExpressionWorker(node, checkMode, forceTuple); + type = instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode); + } + if (isConstEnumObjectType(type)) { + var ok = (node.parent.kind === 189 && node.parent.expression === node) || + (node.parent.kind === 190 && node.parent.expression === node) || + ((node.kind === 72 || node.kind === 148) && isInRightSideOfImportOrExportAssignment(node) || + (node.parent.kind === 167 && node.parent.exprName === node)); + if (!ok) { + error(node, ts.Diagnostics.const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment_or_type_query); + } + } + return type; + } + function checkParenthesizedExpression(node, checkMode) { + var tag = ts.isInJSFile(node) ? ts.getJSDocTypeTag(node) : undefined; + if (tag) { + return checkAssertionWorker(tag, tag.typeExpression.type, node.expression, checkMode); + } + return checkExpression(node.expression, checkMode); + } + function checkExpressionWorker(node, checkMode, forceTuple) { + switch (node.kind) { + case 72: + return checkIdentifier(node); + case 100: + return checkThisExpression(node); + case 98: + return checkSuperExpression(node); + case 96: + return nullWideningType; + case 14: + case 10: + return getFreshTypeOfLiteralType(getLiteralType(node.text)); + case 8: + checkGrammarNumericLiteral(node); + return getFreshTypeOfLiteralType(getLiteralType(+node.text)); + case 9: + checkGrammarBigIntLiteral(node); + return getFreshTypeOfLiteralType(getBigIntLiteralType(node)); + case 102: + return trueType; + case 87: + return falseType; + case 206: + return checkTemplateExpression(node); + case 13: + return globalRegExpType; + case 187: + return checkArrayLiteral(node, checkMode, forceTuple); + case 188: + return checkObjectLiteral(node, checkMode); + case 189: + return checkPropertyAccessExpression(node); + case 190: + return checkIndexedAccess(node); + case 191: + if (node.expression.kind === 92) { + return checkImportCallExpression(node); + } + case 192: + return checkCallExpression(node); + case 193: + return checkTaggedTemplateExpression(node); + case 195: + return checkParenthesizedExpression(node, checkMode); + case 209: + return checkClassExpression(node); + case 196: + case 197: + return checkFunctionExpressionOrObjectLiteralMethod(node, checkMode); + case 199: + return checkTypeOfExpression(node); + case 194: + case 212: + return checkAssertion(node); + case 213: + return checkNonNullAssertion(node); + case 214: + return checkMetaProperty(node); + case 198: + return checkDeleteExpression(node); + case 200: + return checkVoidExpression(node); + case 201: + return checkAwaitExpression(node); + case 202: + return checkPrefixUnaryExpression(node); + case 203: + return checkPostfixUnaryExpression(node); + case 204: + return checkBinaryExpression(node, checkMode); + case 205: + return checkConditionalExpression(node, checkMode); + case 208: + return checkSpreadExpression(node, checkMode); + case 210: + return undefinedWideningType; + case 207: + return checkYieldExpression(node); + case 215: + return node.type; + case 270: + return checkJsxExpression(node, checkMode); + case 260: + return checkJsxElement(node, checkMode); + case 261: + return checkJsxSelfClosingElement(node, checkMode); + case 264: + return checkJsxFragment(node); + case 268: + return checkJsxAttributes(node, checkMode); + case 262: + ts.Debug.fail("Shouldn't ever directly check a JsxOpeningElement"); + } + return errorType; + } + function checkTypeParameter(node) { + if (node.expression) { + grammarErrorOnFirstToken(node.expression, ts.Diagnostics.Type_expected); + } + checkSourceElement(node.constraint); + checkSourceElement(node.default); + var typeParameter = getDeclaredTypeOfTypeParameter(getSymbolOfNode(node)); + if (!hasNonCircularBaseConstraint(typeParameter)) { + error(ts.getEffectiveConstraintOfTypeParameter(node), ts.Diagnostics.Type_parameter_0_has_a_circular_constraint, typeToString(typeParameter)); + } + if (!hasNonCircularTypeParameterDefault(typeParameter)) { + error(node.default, ts.Diagnostics.Type_parameter_0_has_a_circular_default, typeToString(typeParameter)); + } + var constraintType = getConstraintOfTypeParameter(typeParameter); + var defaultType = getDefaultFromTypeParameter(typeParameter); + if (constraintType && defaultType) { + checkTypeAssignableTo(defaultType, getTypeWithThisArgument(constraintType, defaultType), node.default, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); + } + if (produceDiagnostics) { + checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_parameter_name_cannot_be_0); + } + } + function checkParameter(node) { + checkGrammarDecoratorsAndModifiers(node); + checkVariableLikeDeclaration(node); + var func = ts.getContainingFunction(node); + if (ts.hasModifier(node, 92)) { + if (!(func.kind === 157 && ts.nodeIsPresent(func.body))) { + error(node, ts.Diagnostics.A_parameter_property_is_only_allowed_in_a_constructor_implementation); + } + } + if (node.questionToken && ts.isBindingPattern(node.name) && func.body) { + error(node, ts.Diagnostics.A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature); + } + if (node.name && ts.isIdentifier(node.name) && (node.name.escapedText === "this" || node.name.escapedText === "new")) { + if (func.parameters.indexOf(node) !== 0) { + error(node, ts.Diagnostics.A_0_parameter_must_be_the_first_parameter, node.name.escapedText); + } + if (func.kind === 157 || func.kind === 161 || func.kind === 166) { + error(node, ts.Diagnostics.A_constructor_cannot_have_a_this_parameter); + } + if (func.kind === 197) { + error(node, ts.Diagnostics.An_arrow_function_cannot_have_a_this_parameter); + } + } + if (node.dotDotDotToken && !ts.isBindingPattern(node.name) && !isTypeAssignableTo(getTypeOfSymbol(node.symbol), anyArrayType)) { + error(node, ts.Diagnostics.A_rest_parameter_must_be_of_an_array_type); + } + } + function checkTypePredicate(node) { + var parent = getTypePredicateParent(node); + if (!parent) { + error(node, ts.Diagnostics.A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods); + return; + } + var typePredicate = getTypePredicateOfSignature(getSignatureFromDeclaration(parent)); + if (!typePredicate) { + return; + } + checkSourceElement(node.type); + var parameterName = node.parameterName; + if (ts.isThisTypePredicate(typePredicate)) { + getTypeFromThisTypeNode(parameterName); + } + else { + if (typePredicate.parameterIndex >= 0) { + if (parent.parameters[typePredicate.parameterIndex].dotDotDotToken) { + error(parameterName, ts.Diagnostics.A_type_predicate_cannot_reference_a_rest_parameter); + } + else { + var leadingError = function () { return ts.chainDiagnosticMessages(undefined, ts.Diagnostics.A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type); }; + checkTypeAssignableTo(typePredicate.type, getTypeOfNode(parent.parameters[typePredicate.parameterIndex]), node.type, undefined, leadingError); + } + } + else if (parameterName) { + var hasReportedError = false; + for (var _i = 0, _a = parent.parameters; _i < _a.length; _i++) { + var name = _a[_i].name; + if (ts.isBindingPattern(name) && + checkIfTypePredicateVariableIsDeclaredInBindingPattern(name, parameterName, typePredicate.parameterName)) { + hasReportedError = true; + break; + } + } + if (!hasReportedError) { + error(node.parameterName, ts.Diagnostics.Cannot_find_parameter_0, typePredicate.parameterName); + } + } + } + } + function getTypePredicateParent(node) { + switch (node.parent.kind) { + case 197: + case 160: + case 239: + case 196: + case 165: + case 156: + case 155: + var parent = node.parent; + if (node === parent.type) { + return parent; + } + } + } + function checkIfTypePredicateVariableIsDeclaredInBindingPattern(pattern, predicateVariableNode, predicateVariableName) { + for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (ts.isOmittedExpression(element)) { + continue; + } + var name = element.name; + if (name.kind === 72 && name.escapedText === predicateVariableName) { + error(predicateVariableNode, ts.Diagnostics.A_type_predicate_cannot_reference_element_0_in_a_binding_pattern, predicateVariableName); + return true; + } + else if (name.kind === 185 || name.kind === 184) { + if (checkIfTypePredicateVariableIsDeclaredInBindingPattern(name, predicateVariableNode, predicateVariableName)) { + return true; + } + } + } + } + function checkSignatureDeclaration(node) { + if (node.kind === 162) { + checkGrammarIndexSignature(node); + } + else if (node.kind === 165 || node.kind === 239 || node.kind === 166 || + node.kind === 160 || node.kind === 157 || + node.kind === 161) { + checkGrammarFunctionLikeDeclaration(node); + } + var functionFlags = ts.getFunctionFlags(node); + if (!(functionFlags & 4)) { + if ((functionFlags & 3) === 3 && languageVersion < 6) { + checkExternalEmitHelpers(node, 6144); + } + if ((functionFlags & 3) === 2 && languageVersion < 4) { + checkExternalEmitHelpers(node, 64); + } + if ((functionFlags & 3) !== 0 && languageVersion < 2) { + checkExternalEmitHelpers(node, 128); + } + } + checkTypeParameters(node.typeParameters); + ts.forEach(node.parameters, checkParameter); + if (node.type) { + checkSourceElement(node.type); + } + if (produceDiagnostics) { + checkCollisionWithArgumentsInGeneratedCode(node); + var returnTypeNode = ts.getEffectiveReturnTypeNode(node); + if (noImplicitAny && !returnTypeNode) { + switch (node.kind) { + case 161: + error(node, ts.Diagnostics.Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type); + break; + case 160: + error(node, ts.Diagnostics.Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type); + break; + } + } + if (returnTypeNode) { + var functionFlags_1 = ts.getFunctionFlags(node); + if ((functionFlags_1 & (4 | 1)) === 1) { + var returnType = getTypeFromTypeNode(returnTypeNode); + if (returnType === voidType) { + error(returnTypeNode, ts.Diagnostics.A_generator_cannot_have_a_void_type_annotation); + } + else { + var generatorElementType = getIteratedTypeOfGenerator(returnType, (functionFlags_1 & 2) !== 0) || anyType; + var iterableIteratorInstantiation = functionFlags_1 & 2 + ? createAsyncIterableIteratorType(generatorElementType) + : createIterableIteratorType(generatorElementType); + checkTypeAssignableTo(iterableIteratorInstantiation, returnType, returnTypeNode); + } + } + else if ((functionFlags_1 & 3) === 2) { + checkAsyncFunctionReturnType(node, returnTypeNode); + } + } + if (node.kind !== 162 && node.kind !== 289) { + registerForUnusedIdentifiersCheck(node); + } + } + } + function checkClassForDuplicateDeclarations(node) { + var instanceNames = ts.createUnderscoreEscapedMap(); + var staticNames = ts.createUnderscoreEscapedMap(); + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + if (member.kind === 157) { + for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { + var param = _c[_b]; + if (ts.isParameterPropertyDeclaration(param) && !ts.isBindingPattern(param.name)) { + addName(instanceNames, param.name, param.name.escapedText, 3); + } + } + } + else { + var isStatic = ts.hasModifier(member, 32); + var names = isStatic ? staticNames : instanceNames; + var name = member.name; + var memberName = name && ts.getPropertyNameForPropertyNameNode(name); + if (name && memberName) { + switch (member.kind) { + case 158: + addName(names, name, memberName, 1); + break; + case 159: + addName(names, name, memberName, 2); + break; + case 154: + addName(names, name, memberName, 3); + break; + case 156: + addName(names, name, memberName, 4); + break; + } + } + } + } + function addName(names, location, name, meaning) { + var prev = names.get(name); + if (prev) { + if (prev & 4) { + if (meaning !== 4) { + error(location, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(location)); + } + } + else if (prev & meaning) { + error(location, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(location)); + } + else { + names.set(name, prev | meaning); + } + } + else { + names.set(name, meaning); + } + } + } + function checkClassForStaticPropertyNameConflicts(node) { + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + var memberNameNode = member.name; + var isStatic = ts.hasModifier(member, 32); + if (isStatic && memberNameNode) { + var memberName = ts.getPropertyNameForPropertyNameNode(memberNameNode); + switch (memberName) { + case "name": + case "length": + case "caller": + case "arguments": + case "prototype": + var message = ts.Diagnostics.Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1; + var className = getNameOfSymbolAsWritten(getSymbolOfNode(node)); + error(memberNameNode, message, memberName, className); + break; + } + } + } + } + function checkObjectTypeForDuplicateDeclarations(node) { + var names = ts.createMap(); + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + if (member.kind === 153) { + var memberName = void 0; + var name = member.name; + switch (name.kind) { + case 10: + case 8: + memberName = name.text; + break; + case 72: + memberName = ts.idText(name); + break; + default: + continue; + } + if (names.get(memberName)) { + error(ts.getNameOfDeclaration(member.symbol.valueDeclaration), ts.Diagnostics.Duplicate_identifier_0, memberName); + error(member.name, ts.Diagnostics.Duplicate_identifier_0, memberName); + } + else { + names.set(memberName, true); + } + } + } + } + function checkTypeForDuplicateIndexSignatures(node) { + if (node.kind === 241) { + var nodeSymbol = getSymbolOfNode(node); + if (nodeSymbol.declarations.length > 0 && nodeSymbol.declarations[0] !== node) { + return; + } + } + var indexSymbol = getIndexSymbol(getSymbolOfNode(node)); + if (indexSymbol) { + var seenNumericIndexer = false; + var seenStringIndexer = false; + for (var _i = 0, _a = indexSymbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + var declaration = decl; + if (declaration.parameters.length === 1 && declaration.parameters[0].type) { + switch (declaration.parameters[0].type.kind) { + case 138: + if (!seenStringIndexer) { + seenStringIndexer = true; + } + else { + error(declaration, ts.Diagnostics.Duplicate_string_index_signature); + } + break; + case 135: + if (!seenNumericIndexer) { + seenNumericIndexer = true; + } + else { + error(declaration, ts.Diagnostics.Duplicate_number_index_signature); + } + break; + } + } + } + } + } + function checkPropertyDeclaration(node) { + if (!checkGrammarDecoratorsAndModifiers(node) && !checkGrammarProperty(node)) + checkGrammarComputedPropertyName(node.name); + checkVariableLikeDeclaration(node); + } + function checkMethodDeclaration(node) { + if (!checkGrammarMethod(node)) + checkGrammarComputedPropertyName(node.name); + checkFunctionOrMethodDeclaration(node); + if (ts.hasModifier(node, 128) && node.kind === 156 && node.body) { + error(node, ts.Diagnostics.Method_0_cannot_have_an_implementation_because_it_is_marked_abstract, ts.declarationNameToString(node.name)); + } + } + function checkConstructorDeclaration(node) { + checkSignatureDeclaration(node); + if (!checkGrammarConstructorTypeParameters(node)) + checkGrammarConstructorTypeAnnotation(node); + checkSourceElement(node.body); + var symbol = getSymbolOfNode(node); + var firstDeclaration = ts.getDeclarationOfKind(symbol, node.kind); + if (node === firstDeclaration) { + checkFunctionOrConstructorSymbol(symbol); + } + if (ts.nodeIsMissing(node.body)) { + return; + } + if (!produceDiagnostics) { + return; + } + function isInstancePropertyWithInitializer(n) { + return n.kind === 154 && + !ts.hasModifier(n, 32) && + !!n.initializer; + } + var containingClassDecl = node.parent; + if (ts.getEffectiveBaseTypeNode(containingClassDecl)) { + captureLexicalThis(node.parent, containingClassDecl); + var classExtendsNull = classDeclarationExtendsNull(containingClassDecl); + var superCall = getSuperCallInConstructor(node); + if (superCall) { + if (classExtendsNull) { + error(superCall, ts.Diagnostics.A_constructor_cannot_contain_a_super_call_when_its_class_extends_null); + } + var superCallShouldBeFirst = ts.some(node.parent.members, isInstancePropertyWithInitializer) || + ts.some(node.parameters, function (p) { return ts.hasModifier(p, 92); }); + if (superCallShouldBeFirst) { + var statements = node.body.statements; + var superCallStatement = void 0; + for (var _i = 0, statements_2 = statements; _i < statements_2.length; _i++) { + var statement = statements_2[_i]; + if (statement.kind === 221 && ts.isSuperCall(statement.expression)) { + superCallStatement = statement; + break; + } + if (!ts.isPrologueDirective(statement)) { + break; + } + } + if (!superCallStatement) { + error(node, ts.Diagnostics.A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_properties_or_has_parameter_properties); + } + } + } + else if (!classExtendsNull) { + error(node, ts.Diagnostics.Constructors_for_derived_classes_must_contain_a_super_call); + } + } + } + function checkAccessorDeclaration(node) { + if (produceDiagnostics) { + if (!checkGrammarFunctionLikeDeclaration(node) && !checkGrammarAccessor(node)) + checkGrammarComputedPropertyName(node.name); + checkDecorators(node); + checkSignatureDeclaration(node); + if (node.kind === 158) { + if (!(node.flags & 4194304) && ts.nodeIsPresent(node.body) && (node.flags & 128)) { + if (!(node.flags & 256)) { + error(node.name, ts.Diagnostics.A_get_accessor_must_return_a_value); + } + } + } + if (node.name.kind === 149) { + checkComputedPropertyName(node.name); + } + if (!hasNonBindableDynamicName(node)) { + var otherKind = node.kind === 158 ? 159 : 158; + var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(node), otherKind); + if (otherAccessor) { + var nodeFlags = ts.getModifierFlags(node); + var otherFlags = ts.getModifierFlags(otherAccessor); + if ((nodeFlags & 28) !== (otherFlags & 28)) { + error(node.name, ts.Diagnostics.Getter_and_setter_accessors_do_not_agree_in_visibility); + } + if ((nodeFlags & 128) !== (otherFlags & 128)) { + error(node.name, ts.Diagnostics.Accessors_must_both_be_abstract_or_non_abstract); + } + checkAccessorDeclarationTypesIdentical(node, otherAccessor, getAnnotatedAccessorType, ts.Diagnostics.get_and_set_accessor_must_have_the_same_type); + checkAccessorDeclarationTypesIdentical(node, otherAccessor, getThisTypeOfDeclaration, ts.Diagnostics.get_and_set_accessor_must_have_the_same_this_type); + } + } + var returnType = getTypeOfAccessors(getSymbolOfNode(node)); + if (node.kind === 158) { + checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnType); + } + } + checkSourceElement(node.body); + } + function checkAccessorDeclarationTypesIdentical(first, second, getAnnotatedType, message) { + var firstType = getAnnotatedType(first); + var secondType = getAnnotatedType(second); + if (firstType && secondType && !isTypeIdenticalTo(firstType, secondType)) { + error(first, message); + } + } + function checkMissingDeclaration(node) { + checkDecorators(node); + } + function getEffectiveTypeArguments(node, typeParameters) { + return fillMissingTypeArguments(ts.map(node.typeArguments, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJSFile(node)); + } + function checkTypeArgumentConstraints(node, typeParameters) { + var typeArguments; + var mapper; + var result = true; + for (var i = 0; i < typeParameters.length; i++) { + var constraint = getConstraintOfTypeParameter(typeParameters[i]); + if (constraint) { + if (!typeArguments) { + typeArguments = getEffectiveTypeArguments(node, typeParameters); + mapper = createTypeMapper(typeParameters, typeArguments); + } + result = result && checkTypeAssignableTo(typeArguments[i], instantiateType(constraint, mapper), node.typeArguments[i], ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); + } + } + return result; + } + function getTypeParametersForTypeReference(node) { + var type = getTypeFromTypeReference(node); + if (type !== errorType) { + var symbol = getNodeLinks(node).resolvedSymbol; + if (symbol) { + return symbol.flags & 524288 && getSymbolLinks(symbol).typeParameters || + (ts.getObjectFlags(type) & 4 ? type.target.localTypeParameters : undefined); + } + } + return undefined; + } + function checkTypeReferenceNode(node) { + checkGrammarTypeArguments(node, node.typeArguments); + if (node.kind === 164 && node.typeName.jsdocDotPos !== undefined && !ts.isInJSFile(node) && !ts.isInJSDoc(node)) { + grammarErrorAtPos(node, node.typeName.jsdocDotPos, 1, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments); + } + var type = getTypeFromTypeReference(node); + if (type !== errorType) { + if (node.typeArguments) { + ts.forEach(node.typeArguments, checkSourceElement); + if (produceDiagnostics) { + var typeParameters = getTypeParametersForTypeReference(node); + if (typeParameters) { + checkTypeArgumentConstraints(node, typeParameters); + } + } + } + if (type.flags & 32 && getNodeLinks(node).resolvedSymbol.flags & 8) { + error(node, ts.Diagnostics.Enum_type_0_has_members_with_initializers_that_are_not_literals, typeToString(type)); + } + } + } + function getTypeArgumentConstraint(node) { + var typeReferenceNode = ts.tryCast(node.parent, ts.isTypeReferenceType); + if (!typeReferenceNode) + return undefined; + var typeParameters = getTypeParametersForTypeReference(typeReferenceNode); + var constraint = getConstraintOfTypeParameter(typeParameters[typeReferenceNode.typeArguments.indexOf(node)]); + return constraint && instantiateType(constraint, createTypeMapper(typeParameters, getEffectiveTypeArguments(typeReferenceNode, typeParameters))); + } + function checkTypeQuery(node) { + getTypeFromTypeQueryNode(node); + } + function checkTypeLiteral(node) { + ts.forEach(node.members, checkSourceElement); + if (produceDiagnostics) { + var type = getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node); + checkIndexConstraints(type); + checkTypeForDuplicateIndexSignatures(node); + checkObjectTypeForDuplicateDeclarations(node); + } + } + function checkArrayType(node) { + checkSourceElement(node.elementType); + } + function checkTupleType(node) { + var elementTypes = node.elementTypes; + var seenOptionalElement = false; + for (var i = 0; i < elementTypes.length; i++) { + var e = elementTypes[i]; + if (e.kind === 172) { + if (i !== elementTypes.length - 1) { + grammarErrorOnNode(e, ts.Diagnostics.A_rest_element_must_be_last_in_a_tuple_type); + break; + } + if (!isArrayType(getTypeFromTypeNode(e))) { + error(e, ts.Diagnostics.A_rest_element_type_must_be_an_array_type); + } + } + else if (e.kind === 171) { + seenOptionalElement = true; + } + else if (seenOptionalElement) { + grammarErrorOnNode(e, ts.Diagnostics.A_required_element_cannot_follow_an_optional_element); + break; + } + } + checkGrammarForDisallowedTrailingComma(node.elementTypes); + ts.forEach(node.elementTypes, checkSourceElement); + } + function checkUnionOrIntersectionType(node) { + ts.forEach(node.types, checkSourceElement); + } + function checkIndexedAccessIndexType(type, accessNode) { + if (!(type.flags & 8388608)) { + return type; + } + var objectType = type.objectType; + var indexType = type.indexType; + if (isTypeAssignableTo(indexType, getIndexType(objectType, false))) { + if (accessNode.kind === 190 && ts.isAssignmentTarget(accessNode) && + ts.getObjectFlags(objectType) & 32 && getMappedTypeModifiers(objectType) & 1) { + error(accessNode, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(objectType)); + } + return type; + } + if (getIndexInfoOfType(getApparentType(objectType), 1) && isTypeAssignableToKind(indexType, 296)) { + return type; + } + error(accessNode, ts.Diagnostics.Type_0_cannot_be_used_to_index_type_1, typeToString(indexType), typeToString(objectType)); + return type; + } + function checkIndexedAccessType(node) { + checkSourceElement(node.objectType); + checkSourceElement(node.indexType); + checkIndexedAccessIndexType(getTypeFromIndexedAccessTypeNode(node), node); + } + function checkMappedType(node) { + checkSourceElement(node.typeParameter); + checkSourceElement(node.type); + if (!node.type) { + reportImplicitAny(node, anyType); + } + var type = getTypeFromMappedTypeNode(node); + var constraintType = getConstraintTypeFromMappedType(type); + checkTypeAssignableTo(constraintType, keyofConstraintType, ts.getEffectiveConstraintOfTypeParameter(node.typeParameter)); + } + function checkThisType(node) { + getTypeFromThisTypeNode(node); + } + function checkTypeOperator(node) { + checkGrammarTypeOperatorNode(node); + checkSourceElement(node.type); + } + function checkConditionalType(node) { + ts.forEachChild(node, checkSourceElement); + } + function checkInferType(node) { + if (!ts.findAncestor(node, function (n) { return n.parent && n.parent.kind === 175 && n.parent.extendsType === n; })) { + grammarErrorOnNode(node, ts.Diagnostics.infer_declarations_are_only_permitted_in_the_extends_clause_of_a_conditional_type); + } + checkSourceElement(node.typeParameter); + registerForUnusedIdentifiersCheck(node); + } + function checkImportType(node) { + checkSourceElement(node.argument); + getTypeFromTypeNode(node); + } + function isPrivateWithinAmbient(node) { + return ts.hasModifier(node, 8) && !!(node.flags & 4194304); + } + function getEffectiveDeclarationFlags(n, flagsToCheck) { + var flags = ts.getCombinedModifierFlags(n); + if (n.parent.kind !== 241 && + n.parent.kind !== 240 && + n.parent.kind !== 209 && + n.flags & 4194304) { + if (!(flags & 2) && !(ts.isModuleBlock(n.parent) && ts.isModuleDeclaration(n.parent.parent) && ts.isGlobalScopeAugmentation(n.parent.parent))) { + flags |= 1; + } + flags |= 2; + } + return flags & flagsToCheck; + } + function checkFunctionOrConstructorSymbol(symbol) { + if (!produceDiagnostics) { + return; + } + function getCanonicalOverload(overloads, implementation) { + var implementationSharesContainerWithFirstOverload = implementation !== undefined && implementation.parent === overloads[0].parent; + return implementationSharesContainerWithFirstOverload ? implementation : overloads[0]; + } + function checkFlagAgreementBetweenOverloads(overloads, implementation, flagsToCheck, someOverloadFlags, allOverloadFlags) { + var someButNotAllOverloadFlags = someOverloadFlags ^ allOverloadFlags; + if (someButNotAllOverloadFlags !== 0) { + var canonicalFlags_1 = getEffectiveDeclarationFlags(getCanonicalOverload(overloads, implementation), flagsToCheck); + ts.forEach(overloads, function (o) { + var deviation = getEffectiveDeclarationFlags(o, flagsToCheck) ^ canonicalFlags_1; + if (deviation & 1) { + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_exported_or_non_exported); + } + else if (deviation & 2) { + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_ambient_or_non_ambient); + } + else if (deviation & (8 | 16)) { + error(ts.getNameOfDeclaration(o) || o, ts.Diagnostics.Overload_signatures_must_all_be_public_private_or_protected); + } + else if (deviation & 128) { + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_abstract_or_non_abstract); + } + }); + } + } + function checkQuestionTokenAgreementBetweenOverloads(overloads, implementation, someHaveQuestionToken, allHaveQuestionToken) { + if (someHaveQuestionToken !== allHaveQuestionToken) { + var canonicalHasQuestionToken_1 = ts.hasQuestionToken(getCanonicalOverload(overloads, implementation)); + ts.forEach(overloads, function (o) { + var deviation = ts.hasQuestionToken(o) !== canonicalHasQuestionToken_1; + if (deviation) { + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_optional_or_required); + } + }); + } + } + var flagsToCheck = 1 | 2 | 8 | 16 | 128; + var someNodeFlags = 0; + var allNodeFlags = flagsToCheck; + var someHaveQuestionToken = false; + var allHaveQuestionToken = true; + var hasOverloads = false; + var bodyDeclaration; + var lastSeenNonAmbientDeclaration; + var previousDeclaration; + var declarations = symbol.declarations; + var isConstructor = (symbol.flags & 16384) !== 0; + function reportImplementationExpectedError(node) { + if (node.name && ts.nodeIsMissing(node.name)) { + return; + } + var seen = false; + var subsequentNode = ts.forEachChild(node.parent, function (c) { + if (seen) { + return c; + } + else { + seen = c === node; + } + }); + if (subsequentNode && subsequentNode.pos === node.end) { + if (subsequentNode.kind === node.kind) { + var errorNode_1 = subsequentNode.name || subsequentNode; + var subsequentName = subsequentNode.name; + if (node.name && subsequentName && + (ts.isComputedPropertyName(node.name) && ts.isComputedPropertyName(subsequentName) || + !ts.isComputedPropertyName(node.name) && !ts.isComputedPropertyName(subsequentName) && ts.getEscapedTextOfIdentifierOrLiteral(node.name) === ts.getEscapedTextOfIdentifierOrLiteral(subsequentName))) { + var reportError = (node.kind === 156 || node.kind === 155) && + ts.hasModifier(node, 32) !== ts.hasModifier(subsequentNode, 32); + if (reportError) { + var diagnostic = ts.hasModifier(node, 32) ? ts.Diagnostics.Function_overload_must_be_static : ts.Diagnostics.Function_overload_must_not_be_static; + error(errorNode_1, diagnostic); + } + return; + } + else if (ts.nodeIsPresent(subsequentNode.body)) { + error(errorNode_1, ts.Diagnostics.Function_implementation_name_must_be_0, ts.declarationNameToString(node.name)); + return; + } + } + } + var errorNode = node.name || node; + if (isConstructor) { + error(errorNode, ts.Diagnostics.Constructor_implementation_is_missing); + } + else { + if (ts.hasModifier(node, 128)) { + error(errorNode, ts.Diagnostics.All_declarations_of_an_abstract_method_must_be_consecutive); + } + else { + error(errorNode, ts.Diagnostics.Function_implementation_is_missing_or_not_immediately_following_the_declaration); + } + } + } + var duplicateFunctionDeclaration = false; + var multipleConstructorImplementation = false; + for (var _i = 0, declarations_4 = declarations; _i < declarations_4.length; _i++) { + var current = declarations_4[_i]; + var node = current; + var inAmbientContext = node.flags & 4194304; + var inAmbientContextOrInterface = node.parent.kind === 241 || node.parent.kind === 168 || inAmbientContext; + if (inAmbientContextOrInterface) { + previousDeclaration = undefined; + } + if (node.kind === 239 || node.kind === 156 || node.kind === 155 || node.kind === 157) { + var currentNodeFlags = getEffectiveDeclarationFlags(node, flagsToCheck); + someNodeFlags |= currentNodeFlags; + allNodeFlags &= currentNodeFlags; + someHaveQuestionToken = someHaveQuestionToken || ts.hasQuestionToken(node); + allHaveQuestionToken = allHaveQuestionToken && ts.hasQuestionToken(node); + if (ts.nodeIsPresent(node.body) && bodyDeclaration) { + if (isConstructor) { + multipleConstructorImplementation = true; + } + else { + duplicateFunctionDeclaration = true; + } + } + else if (previousDeclaration && previousDeclaration.parent === node.parent && previousDeclaration.end !== node.pos) { + reportImplementationExpectedError(previousDeclaration); + } + if (ts.nodeIsPresent(node.body)) { + if (!bodyDeclaration) { + bodyDeclaration = node; + } + } + else { + hasOverloads = true; + } + previousDeclaration = node; + if (!inAmbientContextOrInterface) { + lastSeenNonAmbientDeclaration = node; + } + } + } + if (multipleConstructorImplementation) { + ts.forEach(declarations, function (declaration) { + error(declaration, ts.Diagnostics.Multiple_constructor_implementations_are_not_allowed); + }); + } + if (duplicateFunctionDeclaration) { + ts.forEach(declarations, function (declaration) { + error(ts.getNameOfDeclaration(declaration), ts.Diagnostics.Duplicate_function_implementation); + }); + } + if (lastSeenNonAmbientDeclaration && !lastSeenNonAmbientDeclaration.body && + !ts.hasModifier(lastSeenNonAmbientDeclaration, 128) && !lastSeenNonAmbientDeclaration.questionToken) { + reportImplementationExpectedError(lastSeenNonAmbientDeclaration); + } + if (hasOverloads) { + checkFlagAgreementBetweenOverloads(declarations, bodyDeclaration, flagsToCheck, someNodeFlags, allNodeFlags); + checkQuestionTokenAgreementBetweenOverloads(declarations, bodyDeclaration, someHaveQuestionToken, allHaveQuestionToken); + if (bodyDeclaration) { + var signatures = getSignaturesOfSymbol(symbol); + var bodySignature = getSignatureFromDeclaration(bodyDeclaration); + for (var _a = 0, signatures_6 = signatures; _a < signatures_6.length; _a++) { + var signature = signatures_6[_a]; + if (!isImplementationCompatibleWithOverload(bodySignature, signature)) { + error(signature.declaration, ts.Diagnostics.Overload_signature_is_not_compatible_with_function_implementation); + break; + } + } + } + } + } + function checkExportsOnMergedDeclarations(node) { + if (!produceDiagnostics) { + return; + } + var symbol = node.localSymbol; + if (!symbol) { + symbol = getSymbolOfNode(node); + if (!symbol.exportSymbol) { + return; + } + } + if (ts.getDeclarationOfKind(symbol, node.kind) !== node) { + return; + } + var exportedDeclarationSpaces = 0; + var nonExportedDeclarationSpaces = 0; + var defaultExportedDeclarationSpaces = 0; + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var d = _a[_i]; + var declarationSpaces = getDeclarationSpaces(d); + var effectiveDeclarationFlags = getEffectiveDeclarationFlags(d, 1 | 512); + if (effectiveDeclarationFlags & 1) { + if (effectiveDeclarationFlags & 512) { + defaultExportedDeclarationSpaces |= declarationSpaces; + } + else { + exportedDeclarationSpaces |= declarationSpaces; + } + } + else { + nonExportedDeclarationSpaces |= declarationSpaces; + } + } + var nonDefaultExportedDeclarationSpaces = exportedDeclarationSpaces | nonExportedDeclarationSpaces; + var commonDeclarationSpacesForExportsAndLocals = exportedDeclarationSpaces & nonExportedDeclarationSpaces; + var commonDeclarationSpacesForDefaultAndNonDefault = defaultExportedDeclarationSpaces & nonDefaultExportedDeclarationSpaces; + if (commonDeclarationSpacesForExportsAndLocals || commonDeclarationSpacesForDefaultAndNonDefault) { + for (var _b = 0, _c = symbol.declarations; _b < _c.length; _b++) { + var d = _c[_b]; + var declarationSpaces = getDeclarationSpaces(d); + var name = ts.getNameOfDeclaration(d); + if (declarationSpaces & commonDeclarationSpacesForDefaultAndNonDefault) { + error(name, ts.Diagnostics.Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead, ts.declarationNameToString(name)); + } + else if (declarationSpaces & commonDeclarationSpacesForExportsAndLocals) { + error(name, ts.Diagnostics.Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local, ts.declarationNameToString(name)); + } + } + } + function getDeclarationSpaces(decl) { + var d = decl; + switch (d.kind) { + case 241: + case 242: + case 304: + case 297: + return 2; + case 244: + return ts.isAmbientModule(d) || ts.getModuleInstanceState(d) !== 0 + ? 4 | 1 + : 4; + case 240: + case 243: + return 2 | 1; + case 279: + return 2 | 1 | 4; + case 254: + if (!ts.isEntityNameExpression(d.expression)) { + return 1; + } + d = d.expression; + case 248: + case 251: + case 250: + var result_4 = 0; + var target = resolveAlias(getSymbolOfNode(d)); + ts.forEach(target.declarations, function (d) { result_4 |= getDeclarationSpaces(d); }); + return result_4; + case 237: + case 186: + case 239: + case 253: + return 1; + default: + return ts.Debug.fail(ts.Debug.showSyntaxKind(d)); + } + } + } + function getAwaitedTypeOfPromise(type, errorNode, diagnosticMessage) { + var promisedType = getPromisedTypeOfPromise(type, errorNode); + return promisedType && getAwaitedType(promisedType, errorNode, diagnosticMessage); + } + function getPromisedTypeOfPromise(promise, errorNode) { + if (isTypeAny(promise)) { + return undefined; + } + var typeAsPromise = promise; + if (typeAsPromise.promisedTypeOfPromise) { + return typeAsPromise.promisedTypeOfPromise; + } + if (isReferenceToType(promise, getGlobalPromiseType(false))) { + return typeAsPromise.promisedTypeOfPromise = promise.typeArguments[0]; + } + var thenFunction = getTypeOfPropertyOfType(promise, "then"); + if (isTypeAny(thenFunction)) { + return undefined; + } + var thenSignatures = thenFunction ? getSignaturesOfType(thenFunction, 0) : ts.emptyArray; + if (thenSignatures.length === 0) { + if (errorNode) { + error(errorNode, ts.Diagnostics.A_promise_must_have_a_then_method); + } + return undefined; + } + var onfulfilledParameterType = getTypeWithFacts(getUnionType(ts.map(thenSignatures, getTypeOfFirstParameterOfSignature)), 2097152); + if (isTypeAny(onfulfilledParameterType)) { + return undefined; + } + var onfulfilledParameterSignatures = getSignaturesOfType(onfulfilledParameterType, 0); + if (onfulfilledParameterSignatures.length === 0) { + if (errorNode) { + error(errorNode, ts.Diagnostics.The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback); + } + return undefined; + } + return typeAsPromise.promisedTypeOfPromise = getUnionType(ts.map(onfulfilledParameterSignatures, getTypeOfFirstParameterOfSignature), 2); + } + function checkAwaitedType(type, errorNode, diagnosticMessage) { + return getAwaitedType(type, errorNode, diagnosticMessage) || errorType; + } + function getAwaitedType(type, errorNode, diagnosticMessage) { + var typeAsAwaitable = type; + if (typeAsAwaitable.awaitedTypeOfType) { + return typeAsAwaitable.awaitedTypeOfType; + } + if (isTypeAny(type)) { + return typeAsAwaitable.awaitedTypeOfType = type; + } + if (type.flags & 1048576) { + var types = void 0; + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var constituentType = _a[_i]; + types = ts.append(types, getAwaitedType(constituentType, errorNode, diagnosticMessage)); + } + if (!types) { + return undefined; + } + return typeAsAwaitable.awaitedTypeOfType = getUnionType(types); + } + var promisedType = getPromisedTypeOfPromise(type); + if (promisedType) { + if (type.id === promisedType.id || awaitedTypeStack.indexOf(promisedType.id) >= 0) { + if (errorNode) { + error(errorNode, ts.Diagnostics.Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method); + } + return undefined; + } + awaitedTypeStack.push(type.id); + var awaitedType = getAwaitedType(promisedType, errorNode, diagnosticMessage); + awaitedTypeStack.pop(); + if (!awaitedType) { + return undefined; + } + return typeAsAwaitable.awaitedTypeOfType = awaitedType; + } + var thenFunction = getTypeOfPropertyOfType(type, "then"); + if (thenFunction && getSignaturesOfType(thenFunction, 0).length > 0) { + if (errorNode) { + if (!diagnosticMessage) + return ts.Debug.fail(); + error(errorNode, diagnosticMessage); + } + return undefined; + } + return typeAsAwaitable.awaitedTypeOfType = type; + } + function checkAsyncFunctionReturnType(node, returnTypeNode) { + var returnType = getTypeFromTypeNode(returnTypeNode); + if (languageVersion >= 2) { + if (returnType === errorType) { + return; + } + var globalPromiseType = getGlobalPromiseType(true); + if (globalPromiseType !== emptyGenericType && !isReferenceToType(returnType, globalPromiseType)) { + error(returnTypeNode, ts.Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type); + return; + } + } + else { + markTypeNodeAsReferenced(returnTypeNode); + if (returnType === errorType) { + return; + } + var promiseConstructorName = ts.getEntityNameFromTypeNode(returnTypeNode); + if (promiseConstructorName === undefined) { + error(returnTypeNode, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, typeToString(returnType)); + return; + } + var promiseConstructorSymbol = resolveEntityName(promiseConstructorName, 67220415, true); + var promiseConstructorType = promiseConstructorSymbol ? getTypeOfSymbol(promiseConstructorSymbol) : errorType; + if (promiseConstructorType === errorType) { + if (promiseConstructorName.kind === 72 && promiseConstructorName.escapedText === "Promise" && getTargetType(returnType) === getGlobalPromiseType(false)) { + error(returnTypeNode, ts.Diagnostics.An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option); + } + else { + error(returnTypeNode, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, ts.entityNameToString(promiseConstructorName)); + } + return; + } + var globalPromiseConstructorLikeType = getGlobalPromiseConstructorLikeType(true); + if (globalPromiseConstructorLikeType === emptyObjectType) { + error(returnTypeNode, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, ts.entityNameToString(promiseConstructorName)); + return; + } + if (!checkTypeAssignableTo(promiseConstructorType, globalPromiseConstructorLikeType, returnTypeNode, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value)) { + return; + } + var rootName = promiseConstructorName && getFirstIdentifier(promiseConstructorName); + var collidingSymbol = getSymbol(node.locals, rootName.escapedText, 67220415); + if (collidingSymbol) { + error(collidingSymbol.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, ts.idText(rootName), ts.entityNameToString(promiseConstructorName)); + return; + } + } + checkAwaitedType(returnType, node, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); + } + function checkDecorator(node) { + var signature = getResolvedSignature(node); + var returnType = getReturnTypeOfSignature(signature); + if (returnType.flags & 1) { + return; + } + var expectedReturnType; + var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); + var errorInfo; + switch (node.parent.kind) { + case 240: + var classSymbol = getSymbolOfNode(node.parent); + var classConstructorType = getTypeOfSymbol(classSymbol); + expectedReturnType = getUnionType([classConstructorType, voidType]); + break; + case 151: + expectedReturnType = voidType; + errorInfo = ts.chainDiagnosticMessages(undefined, ts.Diagnostics.The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any); + break; + case 154: + expectedReturnType = voidType; + errorInfo = ts.chainDiagnosticMessages(undefined, ts.Diagnostics.The_return_type_of_a_property_decorator_function_must_be_either_void_or_any); + break; + case 156: + case 158: + case 159: + var methodType = getTypeOfNode(node.parent); + var descriptorType = createTypedPropertyDescriptorType(methodType); + expectedReturnType = getUnionType([descriptorType, voidType]); + break; + default: + return ts.Debug.fail(); + } + checkTypeAssignableTo(returnType, expectedReturnType, node, headMessage, function () { return errorInfo; }); + } + function markTypeNodeAsReferenced(node) { + markEntityNameOrEntityExpressionAsReference(node && ts.getEntityNameFromTypeNode(node)); + } + function markEntityNameOrEntityExpressionAsReference(typeName) { + if (!typeName) + return; + var rootName = getFirstIdentifier(typeName); + var meaning = (typeName.kind === 72 ? 67897832 : 1920) | 2097152; + var rootSymbol = resolveName(rootName, rootName.escapedText, meaning, undefined, undefined, true); + if (rootSymbol + && rootSymbol.flags & 2097152 + && symbolIsValue(rootSymbol) + && !isConstEnumOrConstEnumOnlyModule(resolveAlias(rootSymbol))) { + markAliasSymbolAsReferenced(rootSymbol); + } + } + function markDecoratorMedataDataTypeNodeAsReferenced(node) { + var entityName = getEntityNameForDecoratorMetadata(node); + if (entityName && ts.isEntityName(entityName)) { + markEntityNameOrEntityExpressionAsReference(entityName); + } + } + function getEntityNameForDecoratorMetadata(node) { + if (node) { + switch (node.kind) { + case 174: + case 173: + return getEntityNameForDecoratorMetadataFromTypeList(node.types); + case 175: + return getEntityNameForDecoratorMetadataFromTypeList([node.trueType, node.falseType]); + case 177: + return getEntityNameForDecoratorMetadata(node.type); + case 164: + return node.typeName; + } + } + } + function getEntityNameForDecoratorMetadataFromTypeList(types) { + var commonEntityName; + for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { + var typeNode = types_16[_i]; + while (typeNode.kind === 177) { + typeNode = typeNode.type; + } + if (typeNode.kind === 132) { + continue; + } + if (!strictNullChecks && (typeNode.kind === 96 || typeNode.kind === 141)) { + continue; + } + var individualEntityName = getEntityNameForDecoratorMetadata(typeNode); + if (!individualEntityName) { + return undefined; + } + if (commonEntityName) { + if (!ts.isIdentifier(commonEntityName) || + !ts.isIdentifier(individualEntityName) || + commonEntityName.escapedText !== individualEntityName.escapedText) { + return undefined; + } + } + else { + commonEntityName = individualEntityName; + } + } + return commonEntityName; + } + function getParameterTypeNodeForDecoratorCheck(node) { + var typeNode = ts.getEffectiveTypeAnnotationNode(node); + return ts.isRestParameter(node) ? ts.getRestParameterElementType(typeNode) : typeNode; + } + function checkDecorators(node) { + if (!node.decorators) { + return; + } + if (!ts.nodeCanBeDecorated(node, node.parent, node.parent.parent)) { + return; + } + if (!compilerOptions.experimentalDecorators) { + error(node, ts.Diagnostics.Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_to_remove_this_warning); + } + var firstDecorator = node.decorators[0]; + checkExternalEmitHelpers(firstDecorator, 8); + if (node.kind === 151) { + checkExternalEmitHelpers(firstDecorator, 32); + } + if (compilerOptions.emitDecoratorMetadata) { + checkExternalEmitHelpers(firstDecorator, 16); + switch (node.kind) { + case 240: + var constructor = ts.getFirstConstructorWithBody(node); + if (constructor) { + for (var _i = 0, _a = constructor.parameters; _i < _a.length; _i++) { + var parameter = _a[_i]; + markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); + } + } + break; + case 158: + case 159: + var otherKind = node.kind === 158 ? 159 : 158; + var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(node), otherKind); + markDecoratorMedataDataTypeNodeAsReferenced(getAnnotatedAccessorTypeNode(node) || otherAccessor && getAnnotatedAccessorTypeNode(otherAccessor)); + break; + case 156: + for (var _b = 0, _c = node.parameters; _b < _c.length; _b++) { + var parameter = _c[_b]; + markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); + } + markDecoratorMedataDataTypeNodeAsReferenced(ts.getEffectiveReturnTypeNode(node)); + break; + case 154: + markDecoratorMedataDataTypeNodeAsReferenced(ts.getEffectiveTypeAnnotationNode(node)); + break; + case 151: + markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(node)); + var containingSignature = node.parent; + for (var _d = 0, _e = containingSignature.parameters; _d < _e.length; _d++) { + var parameter = _e[_d]; + markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); + } + break; + } + } + ts.forEach(node.decorators, checkDecorator); + } + function checkFunctionDeclaration(node) { + if (produceDiagnostics) { + checkFunctionOrMethodDeclaration(node); + checkGrammarForGenerator(node); + checkCollisionWithRequireExportsInGeneratedCode(node, node.name); + checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); + } + } + function checkJSDocTypeAliasTag(node) { + if (!node.typeExpression) { + error(node.name, ts.Diagnostics.JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags); + } + if (node.name) { + checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_alias_name_cannot_be_0); + } + checkSourceElement(node.typeExpression); + } + function checkJSDocTemplateTag(node) { + checkSourceElement(node.constraint); + for (var _i = 0, _a = node.typeParameters; _i < _a.length; _i++) { + var tp = _a[_i]; + checkSourceElement(tp); + } + } + function checkJSDocTypeTag(node) { + checkSourceElement(node.typeExpression); + } + function checkJSDocParameterTag(node) { + checkSourceElement(node.typeExpression); + if (!ts.getParameterSymbolFromJSDoc(node)) { + var decl = ts.getHostSignatureFromJSDoc(node); + if (decl) { + var i = ts.getJSDocTags(decl).filter(ts.isJSDocParameterTag).indexOf(node); + if (i > -1 && i < decl.parameters.length && ts.isBindingPattern(decl.parameters[i].name)) { + return; + } + if (!containsArgumentsReference(decl)) { + error(node.name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name, ts.idText(node.name.kind === 148 ? node.name.right : node.name)); + } + else if (ts.findLast(ts.getJSDocTags(decl), ts.isJSDocParameterTag) === node && + node.typeExpression && node.typeExpression.type && + !isArrayType(getTypeFromTypeNode(node.typeExpression.type))) { + error(node.name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_had_an_array_type, ts.idText(node.name.kind === 148 ? node.name.right : node.name)); + } + } + } + } + function checkJSDocFunctionType(node) { + if (produceDiagnostics && !node.type && !ts.isJSDocConstructSignature(node)) { + reportImplicitAny(node, anyType); + } + checkSignatureDeclaration(node); + } + function checkJSDocAugmentsTag(node) { + var classLike = ts.getJSDocHost(node); + if (!ts.isClassDeclaration(classLike) && !ts.isClassExpression(classLike)) { + error(classLike, ts.Diagnostics.JSDoc_0_is_not_attached_to_a_class, ts.idText(node.tagName)); + return; + } + var augmentsTags = ts.getJSDocTags(classLike).filter(ts.isJSDocAugmentsTag); + ts.Debug.assert(augmentsTags.length > 0); + if (augmentsTags.length > 1) { + error(augmentsTags[1], ts.Diagnostics.Class_declarations_cannot_have_more_than_one_augments_or_extends_tag); + } + var name = getIdentifierFromEntityNameExpression(node.class.expression); + var extend = ts.getClassExtendsHeritageElement(classLike); + if (extend) { + var className = getIdentifierFromEntityNameExpression(extend.expression); + if (className && name.escapedText !== className.escapedText) { + error(name, ts.Diagnostics.JSDoc_0_1_does_not_match_the_extends_2_clause, ts.idText(node.tagName), ts.idText(name), ts.idText(className)); + } + } + } + function getIdentifierFromEntityNameExpression(node) { + switch (node.kind) { + case 72: + return node; + case 189: + return node.name; + default: + return undefined; + } + } + function checkFunctionOrMethodDeclaration(node) { + checkDecorators(node); + checkSignatureDeclaration(node); + var functionFlags = ts.getFunctionFlags(node); + if (node.name && node.name.kind === 149) { + checkComputedPropertyName(node.name); + } + if (!hasNonBindableDynamicName(node)) { + var symbol = getSymbolOfNode(node); + var localSymbol = node.localSymbol || symbol; + var firstDeclaration = ts.find(localSymbol.declarations, function (declaration) { return declaration.kind === node.kind && !(declaration.flags & 65536); }); + if (node === firstDeclaration) { + checkFunctionOrConstructorSymbol(localSymbol); + } + if (symbol.parent) { + if (ts.getDeclarationOfKind(symbol, node.kind) === node) { + checkFunctionOrConstructorSymbol(symbol); + } + } + } + var body = node.kind === 155 ? undefined : node.body; + checkSourceElement(body); + if ((functionFlags & 1) === 0) { + var returnOrPromisedType = getReturnOrPromisedType(node, functionFlags); + checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnOrPromisedType); + } + if (produceDiagnostics && !ts.getEffectiveReturnTypeNode(node)) { + if (ts.nodeIsMissing(body) && !isPrivateWithinAmbient(node)) { + reportImplicitAny(node, anyType); + } + if (functionFlags & 1 && ts.nodeIsPresent(body)) { + getReturnTypeOfSignature(getSignatureFromDeclaration(node)); + } + } + if (ts.isInJSFile(node)) { + var typeTag = ts.getJSDocTypeTag(node); + if (typeTag && typeTag.typeExpression && !getContextualCallSignature(getTypeFromTypeNode(typeTag.typeExpression), node)) { + error(typeTag, ts.Diagnostics.The_type_of_a_function_declaration_must_match_the_function_s_signature); + } + } + } + function registerForUnusedIdentifiersCheck(node) { + if (produceDiagnostics && !(node.flags & 4194304)) { + var sourceFile = ts.getSourceFileOfNode(node); + var potentiallyUnusedIdentifiers = allPotentiallyUnusedIdentifiers.get(sourceFile.path); + if (!potentiallyUnusedIdentifiers) { + potentiallyUnusedIdentifiers = []; + allPotentiallyUnusedIdentifiers.set(sourceFile.path, potentiallyUnusedIdentifiers); + } + potentiallyUnusedIdentifiers.push(node); + } + } + function checkUnusedIdentifiers(potentiallyUnusedIdentifiers, addDiagnostic) { + for (var _i = 0, potentiallyUnusedIdentifiers_1 = potentiallyUnusedIdentifiers; _i < potentiallyUnusedIdentifiers_1.length; _i++) { + var node = potentiallyUnusedIdentifiers_1[_i]; + switch (node.kind) { + case 240: + case 209: + checkUnusedClassMembers(node, addDiagnostic); + checkUnusedTypeParameters(node, addDiagnostic); + break; + case 279: + case 244: + case 218: + case 246: + case 225: + case 226: + case 227: + checkUnusedLocalsAndParameters(node, addDiagnostic); + break; + case 157: + case 196: + case 239: + case 197: + case 156: + case 158: + case 159: + if (node.body) { + checkUnusedLocalsAndParameters(node, addDiagnostic); + } + checkUnusedTypeParameters(node, addDiagnostic); + break; + case 155: + case 160: + case 161: + case 165: + case 166: + case 242: + case 241: + checkUnusedTypeParameters(node, addDiagnostic); + break; + case 176: + checkUnusedInferTypeParameter(node, addDiagnostic); + break; + default: + ts.Debug.assertNever(node, "Node should not have been registered for unused identifiers check"); + } + } + } + function errorUnusedLocal(declaration, name, addDiagnostic) { + var node = ts.getNameOfDeclaration(declaration) || declaration; + var message = isTypeDeclaration(declaration) ? ts.Diagnostics._0_is_declared_but_never_used : ts.Diagnostics._0_is_declared_but_its_value_is_never_read; + addDiagnostic(declaration, 0, ts.createDiagnosticForNode(node, message, name)); + } + function isIdentifierThatStartsWithUnderscore(node) { + return ts.isIdentifier(node) && ts.idText(node).charCodeAt(0) === 95; + } + function checkUnusedClassMembers(node, addDiagnostic) { + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + switch (member.kind) { + case 156: + case 154: + case 158: + case 159: + if (member.kind === 159 && member.symbol.flags & 32768) { + break; + } + var symbol = getSymbolOfNode(member); + if (!symbol.isReferenced && ts.hasModifier(member, 8)) { + addDiagnostic(member, 0, ts.createDiagnosticForNode(member.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, symbolToString(symbol))); + } + break; + case 157: + for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { + var parameter = _c[_b]; + if (!parameter.symbol.isReferenced && ts.hasModifier(parameter, 8)) { + addDiagnostic(parameter, 0, ts.createDiagnosticForNode(parameter.name, ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read, ts.symbolName(parameter.symbol))); + } + } + break; + case 162: + case 217: + break; + default: + ts.Debug.fail(); + } + } + } + function checkUnusedInferTypeParameter(node, addDiagnostic) { + var typeParameter = node.typeParameter; + if (isTypeParameterUnused(typeParameter)) { + addDiagnostic(node, 1, ts.createDiagnosticForNode(node, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(typeParameter.name))); + } + } + function checkUnusedTypeParameters(node, addDiagnostic) { + if (ts.last(getSymbolOfNode(node).declarations) !== node) + return; + var typeParameters = ts.getEffectiveTypeParameterDeclarations(node); + var seenParentsWithEveryUnused = new ts.NodeSet(); + for (var _i = 0, typeParameters_2 = typeParameters; _i < typeParameters_2.length; _i++) { + var typeParameter = typeParameters_2[_i]; + if (!isTypeParameterUnused(typeParameter)) + continue; + var name = ts.idText(typeParameter.name); + var parent = typeParameter.parent; + if (parent.kind !== 176 && parent.typeParameters.every(isTypeParameterUnused)) { + if (seenParentsWithEveryUnused.tryAdd(parent)) { + var range = ts.isJSDocTemplateTag(parent) + ? ts.rangeOfNode(parent) + : ts.rangeOfTypeParameters(parent.typeParameters); + var only = typeParameters.length === 1; + var message = only ? ts.Diagnostics._0_is_declared_but_its_value_is_never_read : ts.Diagnostics.All_type_parameters_are_unused; + var arg0 = only ? name : undefined; + addDiagnostic(typeParameter, 1, ts.createFileDiagnostic(ts.getSourceFileOfNode(parent), range.pos, range.end - range.pos, message, arg0)); + } + } + else { + addDiagnostic(typeParameter, 1, ts.createDiagnosticForNode(typeParameter, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, name)); + } + } + } + function isTypeParameterUnused(typeParameter) { + return !(getMergedSymbol(typeParameter.symbol).isReferenced & 262144) && !isIdentifierThatStartsWithUnderscore(typeParameter.name); + } + function addToGroup(map, key, value, getKey) { + var keyString = String(getKey(key)); + var group = map.get(keyString); + if (group) { + group[1].push(value); + } + else { + map.set(keyString, [key, [value]]); + } + } + function tryGetRootParameterDeclaration(node) { + return ts.tryCast(ts.getRootDeclaration(node), ts.isParameter); + } + function checkUnusedLocalsAndParameters(nodeWithLocals, addDiagnostic) { + if (nodeWithLocals.flags & 4194304) + return; + var unusedImports = ts.createMap(); + var unusedDestructures = ts.createMap(); + var unusedVariables = ts.createMap(); + nodeWithLocals.locals.forEach(function (local) { + if (local.flags & 262144 ? !(local.flags & 3 && !(local.isReferenced & 3)) : local.isReferenced || local.exportSymbol) { + return; + } + for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (ts.isAmbientModule(declaration) || + (ts.isVariableDeclaration(declaration) && ts.isForInOrOfStatement(declaration.parent.parent) || isImportedDeclaration(declaration)) && isIdentifierThatStartsWithUnderscore(declaration.name)) { + continue; + } + if (isImportedDeclaration(declaration)) { + addToGroup(unusedImports, importClauseFromImported(declaration), declaration, getNodeId); + } + else if (ts.isBindingElement(declaration) && ts.isObjectBindingPattern(declaration.parent)) { + var lastElement = ts.last(declaration.parent.elements); + if (declaration === lastElement || !ts.last(declaration.parent.elements).dotDotDotToken) { + addToGroup(unusedDestructures, declaration.parent, declaration, getNodeId); + } + } + else if (ts.isVariableDeclaration(declaration)) { + addToGroup(unusedVariables, declaration.parent, declaration, getNodeId); + } + else { + var parameter = local.valueDeclaration && tryGetRootParameterDeclaration(local.valueDeclaration); + var name = local.valueDeclaration && ts.getNameOfDeclaration(local.valueDeclaration); + if (parameter && name) { + if (!ts.isParameterPropertyDeclaration(parameter) && !ts.parameterIsThisKeyword(parameter) && !isIdentifierThatStartsWithUnderscore(name)) { + addDiagnostic(parameter, 1, ts.createDiagnosticForNode(name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.symbolName(local))); + } + } + else { + errorUnusedLocal(declaration, ts.symbolName(local), addDiagnostic); + } + } + } + }); + unusedImports.forEach(function (_a) { + var importClause = _a[0], unuseds = _a[1]; + var importDecl = importClause.parent; + var nDeclarations = (importClause.name ? 1 : 0) + + (importClause.namedBindings ? + (importClause.namedBindings.kind === 251 ? 1 : importClause.namedBindings.elements.length) + : 0); + if (nDeclarations === unuseds.length) { + addDiagnostic(importDecl, 0, unuseds.length === 1 + ? ts.createDiagnosticForNode(importDecl, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(ts.first(unuseds).name)) + : ts.createDiagnosticForNode(importDecl, ts.Diagnostics.All_imports_in_import_declaration_are_unused)); + } + else { + for (var _i = 0, unuseds_1 = unuseds; _i < unuseds_1.length; _i++) { + var unused = unuseds_1[_i]; + errorUnusedLocal(unused, ts.idText(unused.name), addDiagnostic); + } + } + }); + unusedDestructures.forEach(function (_a) { + var bindingPattern = _a[0], bindingElements = _a[1]; + var kind = tryGetRootParameterDeclaration(bindingPattern.parent) ? 1 : 0; + if (bindingPattern.elements.length === bindingElements.length) { + if (bindingElements.length === 1 && bindingPattern.parent.kind === 237 && bindingPattern.parent.parent.kind === 238) { + addToGroup(unusedVariables, bindingPattern.parent.parent, bindingPattern.parent, getNodeId); + } + else { + addDiagnostic(bindingPattern, kind, bindingElements.length === 1 + ? ts.createDiagnosticForNode(bindingPattern, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(ts.first(bindingElements).name)) + : ts.createDiagnosticForNode(bindingPattern, ts.Diagnostics.All_destructured_elements_are_unused)); + } + } + else { + for (var _i = 0, bindingElements_1 = bindingElements; _i < bindingElements_1.length; _i++) { + var e = bindingElements_1[_i]; + addDiagnostic(e, kind, ts.createDiagnosticForNode(e, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(e.name))); + } + } + }); + unusedVariables.forEach(function (_a) { + var declarationList = _a[0], declarations = _a[1]; + if (declarationList.declarations.length === declarations.length) { + addDiagnostic(declarationList, 0, declarations.length === 1 + ? ts.createDiagnosticForNode(ts.first(declarations).name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(ts.first(declarations).name)) + : ts.createDiagnosticForNode(declarationList.parent.kind === 219 ? declarationList.parent : declarationList, ts.Diagnostics.All_variables_are_unused)); + } + else { + for (var _i = 0, declarations_5 = declarations; _i < declarations_5.length; _i++) { + var decl = declarations_5[_i]; + addDiagnostic(decl, 0, ts.createDiagnosticForNode(decl, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(decl.name))); + } + } + }); + } + function bindingNameText(name) { + switch (name.kind) { + case 72: + return ts.idText(name); + case 185: + case 184: + return bindingNameText(ts.cast(ts.first(name.elements), ts.isBindingElement).name); + default: + return ts.Debug.assertNever(name); + } + } + function isImportedDeclaration(node) { + return node.kind === 250 || node.kind === 253 || node.kind === 251; + } + function importClauseFromImported(decl) { + return decl.kind === 250 ? decl : decl.kind === 251 ? decl.parent : decl.parent.parent; + } + function checkBlock(node) { + if (node.kind === 218) { + checkGrammarStatementInAmbientContext(node); + } + if (ts.isFunctionOrModuleBlock(node)) { + var saveFlowAnalysisDisabled = flowAnalysisDisabled; + ts.forEach(node.statements, checkSourceElement); + flowAnalysisDisabled = saveFlowAnalysisDisabled; + } + else { + ts.forEach(node.statements, checkSourceElement); + } + if (node.locals) { + registerForUnusedIdentifiersCheck(node); + } + } + function checkCollisionWithArgumentsInGeneratedCode(node) { + if (languageVersion >= 2 || compilerOptions.noEmit || !ts.hasRestParameter(node) || node.flags & 4194304 || ts.nodeIsMissing(node.body)) { + return; + } + ts.forEach(node.parameters, function (p) { + if (p.name && !ts.isBindingPattern(p.name) && p.name.escapedText === argumentsSymbol.escapedName) { + error(p, ts.Diagnostics.Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters); + } + }); + } + function needCollisionCheckForIdentifier(node, identifier, name) { + if (!(identifier && identifier.escapedText === name)) { + return false; + } + if (node.kind === 154 || + node.kind === 153 || + node.kind === 156 || + node.kind === 155 || + node.kind === 158 || + node.kind === 159) { + return false; + } + if (node.flags & 4194304) { + return false; + } + var root = ts.getRootDeclaration(node); + if (root.kind === 151 && ts.nodeIsMissing(root.parent.body)) { + return false; + } + return true; + } + function checkIfThisIsCapturedInEnclosingScope(node) { + ts.findAncestor(node, function (current) { + if (getNodeCheckFlags(current) & 4) { + var isDeclaration_1 = node.kind !== 72; + if (isDeclaration_1) { + error(ts.getNameOfDeclaration(node), ts.Diagnostics.Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference); + } + else { + error(node, ts.Diagnostics.Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference); + } + return true; + } + return false; + }); + } + function checkIfNewTargetIsCapturedInEnclosingScope(node) { + ts.findAncestor(node, function (current) { + if (getNodeCheckFlags(current) & 8) { + var isDeclaration_2 = node.kind !== 72; + if (isDeclaration_2) { + error(ts.getNameOfDeclaration(node), ts.Diagnostics.Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference); + } + else { + error(node, ts.Diagnostics.Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta_property_reference); + } + return true; + } + return false; + }); + } + function checkCollisionWithRequireExportsInGeneratedCode(node, name) { + if (moduleKind >= ts.ModuleKind.ES2015 || compilerOptions.noEmit) { + return; + } + if (!needCollisionCheckForIdentifier(node, name, "require") && !needCollisionCheckForIdentifier(node, name, "exports")) { + return; + } + if (ts.isModuleDeclaration(node) && ts.getModuleInstanceState(node) !== 1) { + return; + } + var parent = getDeclarationContainer(node); + if (parent.kind === 279 && ts.isExternalOrCommonJsModule(parent)) { + error(name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module, ts.declarationNameToString(name), ts.declarationNameToString(name)); + } + } + function checkCollisionWithGlobalPromiseInGeneratedCode(node, name) { + if (languageVersion >= 4 || compilerOptions.noEmit || !needCollisionCheckForIdentifier(node, name, "Promise")) { + return; + } + if (ts.isModuleDeclaration(node) && ts.getModuleInstanceState(node) !== 1) { + return; + } + var parent = getDeclarationContainer(node); + if (parent.kind === 279 && ts.isExternalOrCommonJsModule(parent) && parent.flags & 1024) { + error(name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_functions, ts.declarationNameToString(name), ts.declarationNameToString(name)); + } + } + function checkVarDeclaredNamesNotShadowed(node) { + if ((ts.getCombinedNodeFlags(node) & 3) !== 0 || ts.isParameterDeclaration(node)) { + return; + } + if (node.kind === 237 && !node.initializer) { + return; + } + var symbol = getSymbolOfNode(node); + if (symbol.flags & 1) { + if (!ts.isIdentifier(node.name)) + return ts.Debug.fail(); + var localDeclarationSymbol = resolveName(node, node.name.escapedText, 3, undefined, undefined, false); + if (localDeclarationSymbol && + localDeclarationSymbol !== symbol && + localDeclarationSymbol.flags & 2) { + if (getDeclarationNodeFlagsFromSymbol(localDeclarationSymbol) & 3) { + var varDeclList = ts.getAncestor(localDeclarationSymbol.valueDeclaration, 238); + var container = varDeclList.parent.kind === 219 && varDeclList.parent.parent + ? varDeclList.parent.parent + : undefined; + var namesShareScope = container && + (container.kind === 218 && ts.isFunctionLike(container.parent) || + container.kind === 245 || + container.kind === 244 || + container.kind === 279); + if (!namesShareScope) { + var name = symbolToString(localDeclarationSymbol); + error(node, ts.Diagnostics.Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1, name, name); + } + } + } + } + } + function checkParameterInitializer(node) { + if (ts.getRootDeclaration(node).kind !== 151) { + return; + } + var func = ts.getContainingFunction(node); + visit(node.initializer); + function visit(n) { + if (ts.isTypeNode(n) || ts.isDeclarationName(n)) { + return; + } + if (n.kind === 189) { + return visit(n.expression); + } + else if (n.kind === 72) { + var symbol = resolveName(n, n.escapedText, 67220415 | 2097152, undefined, undefined, false); + if (!symbol || symbol === unknownSymbol || !symbol.valueDeclaration) { + return; + } + if (symbol.valueDeclaration === node) { + error(n, ts.Diagnostics.Parameter_0_cannot_be_referenced_in_its_initializer, ts.declarationNameToString(node.name)); + return; + } + var enclosingContainer = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); + if (enclosingContainer === func) { + if (symbol.valueDeclaration.kind === 151 || + symbol.valueDeclaration.kind === 186) { + if (symbol.valueDeclaration.pos < node.pos) { + return; + } + if (ts.findAncestor(n, function (current) { + if (current === node.initializer) { + return "quit"; + } + return ts.isFunctionLike(current.parent) || + (current.parent.kind === 154 && + !(ts.hasModifier(current.parent, 32)) && + ts.isClassLike(current.parent.parent)); + })) { + return; + } + } + error(n, ts.Diagnostics.Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it, ts.declarationNameToString(node.name), ts.declarationNameToString(n)); + } + } + else { + return ts.forEachChild(n, visit); + } + } + } + function convertAutoToAny(type) { + return type === autoType ? anyType : type === autoArrayType ? anyArrayType : type; + } + function checkVariableLikeDeclaration(node) { + checkDecorators(node); + if (!ts.isBindingElement(node)) { + checkSourceElement(node.type); + } + if (!node.name) { + return; + } + if (node.name.kind === 149) { + checkComputedPropertyName(node.name); + if (node.initializer) { + checkExpressionCached(node.initializer); + } + } + if (node.kind === 186) { + if (node.parent.kind === 184 && languageVersion < 6) { + checkExternalEmitHelpers(node, 4); + } + if (node.propertyName && node.propertyName.kind === 149) { + checkComputedPropertyName(node.propertyName); + } + var parent = node.parent.parent; + var parentType = getTypeForBindingElementParent(parent); + var name = node.propertyName || node.name; + if (!ts.isBindingPattern(name)) { + var nameText = ts.getTextOfPropertyName(name); + if (nameText) { + var property = getPropertyOfType(parentType, nameText); + if (property) { + markPropertyAsReferenced(property, undefined, false); + checkPropertyAccessibility(parent, !!parent.initializer && parent.initializer.kind === 98, parentType, property); + } + } + } + } + if (ts.isBindingPattern(node.name)) { + if (node.name.kind === 185 && languageVersion < 2 && compilerOptions.downlevelIteration) { + checkExternalEmitHelpers(node, 512); + } + ts.forEach(node.name.elements, checkSourceElement); + } + if (node.initializer && ts.getRootDeclaration(node).kind === 151 && ts.nodeIsMissing(ts.getContainingFunction(node).body)) { + error(node, ts.Diagnostics.A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation); + return; + } + if (ts.isBindingPattern(node.name)) { + if (node.initializer && node.parent.parent.kind !== 226) { + var initializerType = checkExpressionCached(node.initializer); + if (strictNullChecks && node.name.elements.length === 0) { + checkNonNullType(initializerType, node); + } + else { + checkTypeAssignableToAndOptionallyElaborate(initializerType, getWidenedTypeForVariableLikeDeclaration(node), node, node.initializer); + } + checkParameterInitializer(node); + } + return; + } + var symbol = getSymbolOfNode(node); + var type = convertAutoToAny(getTypeOfSymbol(symbol)); + if (node === symbol.valueDeclaration) { + var initializer = ts.getEffectiveInitializer(node); + if (initializer) { + var isJSObjectLiteralInitializer = ts.isInJSFile(node) && + ts.isObjectLiteralExpression(initializer) && + (initializer.properties.length === 0 || ts.isPrototypeAccess(node.name)) && + ts.hasEntries(symbol.exports); + if (!isJSObjectLiteralInitializer && node.parent.parent.kind !== 226) { + checkTypeAssignableToAndOptionallyElaborate(checkExpressionCached(initializer), type, node, initializer, undefined); + checkParameterInitializer(node); + } + } + if (symbol.declarations.length > 1) { + if (ts.some(symbol.declarations, function (d) { return d !== node && ts.isVariableLike(d) && !areDeclarationFlagsIdentical(d, node); })) { + error(node.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); + } + } + } + else { + var declarationType = convertAutoToAny(getWidenedTypeForVariableLikeDeclaration(node)); + if (type !== errorType && declarationType !== errorType && + !isTypeIdenticalTo(type, declarationType) && + !(symbol.flags & 67108864)) { + errorNextVariableOrPropertyDeclarationMustHaveSameType(type, node, declarationType); + } + if (node.initializer) { + checkTypeAssignableToAndOptionallyElaborate(checkExpressionCached(node.initializer), declarationType, node, node.initializer, undefined); + } + if (!areDeclarationFlagsIdentical(node, symbol.valueDeclaration)) { + error(node.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); + } + } + if (node.kind !== 154 && node.kind !== 153) { + checkExportsOnMergedDeclarations(node); + if (node.kind === 237 || node.kind === 186) { + checkVarDeclaredNamesNotShadowed(node); + } + checkCollisionWithRequireExportsInGeneratedCode(node, node.name); + checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); + } + } + function errorNextVariableOrPropertyDeclarationMustHaveSameType(firstType, nextDeclaration, nextType) { + var nextDeclarationName = ts.getNameOfDeclaration(nextDeclaration); + var message = nextDeclaration.kind === 154 || nextDeclaration.kind === 153 + ? ts.Diagnostics.Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_type_2 + : ts.Diagnostics.Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2; + error(nextDeclarationName, message, ts.declarationNameToString(nextDeclarationName), typeToString(firstType), typeToString(nextType)); + } + function areDeclarationFlagsIdentical(left, right) { + if ((left.kind === 151 && right.kind === 237) || + (left.kind === 237 && right.kind === 151)) { + return true; + } + if (ts.hasQuestionToken(left) !== ts.hasQuestionToken(right)) { + return false; + } + var interestingFlags = 8 | + 16 | + 256 | + 128 | + 64 | + 32; + return ts.getSelectedModifierFlags(left, interestingFlags) === ts.getSelectedModifierFlags(right, interestingFlags); + } + function checkVariableDeclaration(node) { + checkGrammarVariableDeclaration(node); + return checkVariableLikeDeclaration(node); + } + function checkBindingElement(node) { + checkGrammarBindingElement(node); + return checkVariableLikeDeclaration(node); + } + function checkVariableStatement(node) { + if (!checkGrammarDecoratorsAndModifiers(node) && !checkGrammarVariableDeclarationList(node.declarationList)) + checkGrammarForDisallowedLetOrConstStatement(node); + ts.forEach(node.declarationList.declarations, checkSourceElement); + } + function checkExpressionStatement(node) { + checkGrammarStatementInAmbientContext(node); + checkExpression(node.expression); + } + function checkIfStatement(node) { + checkGrammarStatementInAmbientContext(node); + checkTruthinessExpression(node.expression); + checkSourceElement(node.thenStatement); + if (node.thenStatement.kind === 220) { + error(node.thenStatement, ts.Diagnostics.The_body_of_an_if_statement_cannot_be_the_empty_statement); + } + checkSourceElement(node.elseStatement); + } + function checkDoStatement(node) { + checkGrammarStatementInAmbientContext(node); + checkSourceElement(node.statement); + checkTruthinessExpression(node.expression); + } + function checkWhileStatement(node) { + checkGrammarStatementInAmbientContext(node); + checkTruthinessExpression(node.expression); + checkSourceElement(node.statement); + } + function checkTruthinessExpression(node, checkMode) { + var type = checkExpression(node, checkMode); + if (type.flags & 16384) { + error(node, ts.Diagnostics.An_expression_of_type_void_cannot_be_tested_for_truthiness); + } + return type; + } + function checkForStatement(node) { + if (!checkGrammarStatementInAmbientContext(node)) { + if (node.initializer && node.initializer.kind === 238) { + checkGrammarVariableDeclarationList(node.initializer); + } + } + if (node.initializer) { + if (node.initializer.kind === 238) { + ts.forEach(node.initializer.declarations, checkVariableDeclaration); + } + else { + checkExpression(node.initializer); + } + } + if (node.condition) + checkTruthinessExpression(node.condition); + if (node.incrementor) + checkExpression(node.incrementor); + checkSourceElement(node.statement); + if (node.locals) { + registerForUnusedIdentifiersCheck(node); + } + } + function checkForOfStatement(node) { + checkGrammarForInOrForOfStatement(node); + if (node.awaitModifier) { + var functionFlags = ts.getFunctionFlags(ts.getContainingFunction(node)); + if ((functionFlags & (4 | 2)) === 2 && languageVersion < 6) { + checkExternalEmitHelpers(node, 16384); + } + } + else if (compilerOptions.downlevelIteration && languageVersion < 2) { + checkExternalEmitHelpers(node, 256); + } + if (node.initializer.kind === 238) { + checkForInOrForOfVariableDeclaration(node); + } + else { + var varExpr = node.initializer; + var iteratedType = checkRightHandSideOfForOf(node.expression, node.awaitModifier); + if (varExpr.kind === 187 || varExpr.kind === 188) { + checkDestructuringAssignment(varExpr, iteratedType || errorType); + } + else { + var leftType = checkExpression(varExpr); + checkReferenceExpression(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access); + if (iteratedType) { + checkTypeAssignableToAndOptionallyElaborate(iteratedType, leftType, varExpr, node.expression); + } + } + } + checkSourceElement(node.statement); + if (node.locals) { + registerForUnusedIdentifiersCheck(node); + } + } + function checkForInStatement(node) { + checkGrammarForInOrForOfStatement(node); + var rightType = getNonNullableTypeIfNeeded(checkExpression(node.expression)); + if (node.initializer.kind === 238) { + var variable = node.initializer.declarations[0]; + if (variable && ts.isBindingPattern(variable.name)) { + error(variable.name, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern); + } + checkForInOrForOfVariableDeclaration(node); + } + else { + var varExpr = node.initializer; + var leftType = checkExpression(varExpr); + if (varExpr.kind === 187 || varExpr.kind === 188) { + error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern); + } + else if (!isTypeAssignableTo(getIndexTypeOrString(rightType), leftType)) { + error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any); + } + else { + checkReferenceExpression(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access); + } + } + if (rightType === neverType || !isTypeAssignableToKind(rightType, 67108864 | 58982400)) { + error(node.expression, ts.Diagnostics.The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_but_here_has_type_0, typeToString(rightType)); + } + checkSourceElement(node.statement); + if (node.locals) { + registerForUnusedIdentifiersCheck(node); + } + } + function checkForInOrForOfVariableDeclaration(iterationStatement) { + var variableDeclarationList = iterationStatement.initializer; + if (variableDeclarationList.declarations.length >= 1) { + var decl = variableDeclarationList.declarations[0]; + checkVariableDeclaration(decl); + } + } + function checkRightHandSideOfForOf(rhsExpression, awaitModifier) { + var expressionType = checkNonNullExpression(rhsExpression); + return checkIteratedTypeOrElementType(expressionType, rhsExpression, true, awaitModifier !== undefined); + } + function checkIteratedTypeOrElementType(inputType, errorNode, allowStringInput, allowAsyncIterables) { + if (isTypeAny(inputType)) { + return inputType; + } + return getIteratedTypeOrElementType(inputType, errorNode, allowStringInput, allowAsyncIterables, true) || anyType; + } + function getIteratedTypeOrElementType(inputType, errorNode, allowStringInput, allowAsyncIterables, checkAssignability) { + if (inputType === neverType) { + reportTypeNotIterableError(errorNode, inputType, allowAsyncIterables); + return undefined; + } + var uplevelIteration = languageVersion >= 2; + var downlevelIteration = !uplevelIteration && compilerOptions.downlevelIteration; + if (uplevelIteration || downlevelIteration || allowAsyncIterables) { + var iteratedType = getIteratedTypeOfIterable(inputType, uplevelIteration ? errorNode : undefined, allowAsyncIterables, true, checkAssignability); + if (iteratedType || uplevelIteration) { + return iteratedType; + } + } + var arrayType = inputType; + var reportedError = false; + var hasStringConstituent = false; + if (allowStringInput) { + if (arrayType.flags & 1048576) { + var arrayTypes = inputType.types; + var filteredTypes = ts.filter(arrayTypes, function (t) { return !(t.flags & 132); }); + if (filteredTypes !== arrayTypes) { + arrayType = getUnionType(filteredTypes, 2); + } + } + else if (arrayType.flags & 132) { + arrayType = neverType; + } + hasStringConstituent = arrayType !== inputType; + if (hasStringConstituent) { + if (languageVersion < 1) { + if (errorNode) { + error(errorNode, ts.Diagnostics.Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher); + reportedError = true; + } + } + if (arrayType.flags & 131072) { + return stringType; + } + } + } + if (!isArrayLikeType(arrayType)) { + if (errorNode && !reportedError) { + var isIterable = !!getIteratedTypeOfIterable(inputType, undefined, allowAsyncIterables, true, checkAssignability); + var diagnostic = !allowStringInput || hasStringConstituent + ? downlevelIteration + ? ts.Diagnostics.Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator + : isIterable + ? ts.Diagnostics.Type_0_is_not_an_array_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators + : ts.Diagnostics.Type_0_is_not_an_array_type + : downlevelIteration + ? ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator + : isIterable + ? ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators + : ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type; + error(errorNode, diagnostic, typeToString(arrayType)); + } + return hasStringConstituent ? stringType : undefined; + } + var arrayElementType = getIndexTypeOfType(arrayType, 1); + if (hasStringConstituent && arrayElementType) { + if (arrayElementType.flags & 132) { + return stringType; + } + return getUnionType([arrayElementType, stringType], 2); + } + return arrayElementType; + } + function getIteratedTypeOfIterable(type, errorNode, allowAsyncIterables, allowSyncIterables, checkAssignability) { + if (isTypeAny(type)) { + return undefined; + } + return mapType(type, getIteratedType); + function getIteratedType(type) { + var typeAsIterable = type; + if (allowAsyncIterables) { + if (typeAsIterable.iteratedTypeOfAsyncIterable) { + return typeAsIterable.iteratedTypeOfAsyncIterable; + } + if (isReferenceToType(type, getGlobalAsyncIterableType(false)) || + isReferenceToType(type, getGlobalAsyncIterableIteratorType(false))) { + return typeAsIterable.iteratedTypeOfAsyncIterable = type.typeArguments[0]; + } + } + if (allowSyncIterables) { + if (typeAsIterable.iteratedTypeOfIterable) { + return allowAsyncIterables + ? typeAsIterable.iteratedTypeOfAsyncIterable = getAwaitedType(typeAsIterable.iteratedTypeOfIterable) + : typeAsIterable.iteratedTypeOfIterable; + } + if (isReferenceToType(type, getGlobalIterableType(false)) || + isReferenceToType(type, getGlobalIterableIteratorType(false))) { + return allowAsyncIterables + ? typeAsIterable.iteratedTypeOfAsyncIterable = getAwaitedType(type.typeArguments[0]) + : typeAsIterable.iteratedTypeOfIterable = type.typeArguments[0]; + } + } + var asyncMethodType = allowAsyncIterables && getTypeOfPropertyOfType(type, ts.getPropertyNameForKnownSymbolName("asyncIterator")); + var methodType = asyncMethodType || (allowSyncIterables ? getTypeOfPropertyOfType(type, ts.getPropertyNameForKnownSymbolName("iterator")) : undefined); + if (isTypeAny(methodType)) { + return undefined; + } + var signatures = methodType ? getSignaturesOfType(methodType, 0) : undefined; + if (!ts.some(signatures)) { + if (errorNode) { + reportTypeNotIterableError(errorNode, type, allowAsyncIterables); + errorNode = undefined; + } + return undefined; + } + var returnType = getUnionType(ts.map(signatures, getReturnTypeOfSignature), 2); + var iteratedType = getIteratedTypeOfIterator(returnType, errorNode, !!asyncMethodType); + if (checkAssignability && errorNode && iteratedType) { + checkTypeAssignableTo(type, asyncMethodType + ? createAsyncIterableType(iteratedType) + : createIterableType(iteratedType), errorNode); + } + if (iteratedType) { + return allowAsyncIterables + ? typeAsIterable.iteratedTypeOfAsyncIterable = asyncMethodType ? iteratedType : getAwaitedType(iteratedType) + : typeAsIterable.iteratedTypeOfIterable = iteratedType; + } + } + } + function reportTypeNotIterableError(errorNode, type, allowAsyncIterables) { + error(errorNode, allowAsyncIterables + ? ts.Diagnostics.Type_0_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator + : ts.Diagnostics.Type_0_must_have_a_Symbol_iterator_method_that_returns_an_iterator, typeToString(type)); + } + function getIteratedTypeOfIterator(type, errorNode, isAsyncIterator) { + if (isTypeAny(type)) { + return undefined; + } + var typeAsIterator = type; + if (isAsyncIterator ? typeAsIterator.iteratedTypeOfAsyncIterator : typeAsIterator.iteratedTypeOfIterator) { + return isAsyncIterator ? typeAsIterator.iteratedTypeOfAsyncIterator : typeAsIterator.iteratedTypeOfIterator; + } + var getIteratorType = isAsyncIterator ? getGlobalAsyncIteratorType : getGlobalIteratorType; + if (isReferenceToType(type, getIteratorType(false))) { + return isAsyncIterator + ? typeAsIterator.iteratedTypeOfAsyncIterator = type.typeArguments[0] + : typeAsIterator.iteratedTypeOfIterator = type.typeArguments[0]; + } + var nextMethod = getTypeOfPropertyOfType(type, "next"); + if (isTypeAny(nextMethod)) { + return undefined; + } + var nextMethodSignatures = nextMethod ? getSignaturesOfType(nextMethod, 0) : ts.emptyArray; + if (nextMethodSignatures.length === 0) { + if (errorNode) { + error(errorNode, isAsyncIterator + ? ts.Diagnostics.An_async_iterator_must_have_a_next_method + : ts.Diagnostics.An_iterator_must_have_a_next_method); + } + return undefined; + } + var nextResult = getUnionType(ts.map(nextMethodSignatures, getReturnTypeOfSignature), 2); + if (isTypeAny(nextResult)) { + return undefined; + } + if (isAsyncIterator) { + nextResult = getAwaitedTypeOfPromise(nextResult, errorNode, ts.Diagnostics.The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property); + if (isTypeAny(nextResult)) { + return undefined; + } + } + var nextValue = nextResult && getTypeOfPropertyOfType(nextResult, "value"); + if (!nextValue) { + if (errorNode) { + error(errorNode, isAsyncIterator + ? ts.Diagnostics.The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property + : ts.Diagnostics.The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property); + } + return undefined; + } + return isAsyncIterator + ? typeAsIterator.iteratedTypeOfAsyncIterator = nextValue + : typeAsIterator.iteratedTypeOfIterator = nextValue; + } + function getIteratedTypeOfGenerator(returnType, isAsyncGenerator) { + if (isTypeAny(returnType)) { + return undefined; + } + return getIteratedTypeOfIterable(returnType, undefined, isAsyncGenerator, !isAsyncGenerator, false) + || getIteratedTypeOfIterator(returnType, undefined, isAsyncGenerator); + } + function checkBreakOrContinueStatement(node) { + if (!checkGrammarStatementInAmbientContext(node)) + checkGrammarBreakOrContinueStatement(node); + } + function isUnwrappedReturnTypeVoidOrAny(func, returnType) { + var unwrappedReturnType = (ts.getFunctionFlags(func) & 3) === 2 + ? getPromisedTypeOfPromise(returnType) + : returnType; + return !!unwrappedReturnType && maybeTypeOfKind(unwrappedReturnType, 16384 | 3); + } + function checkReturnStatement(node) { + if (checkGrammarStatementInAmbientContext(node)) { + return; + } + var func = ts.getContainingFunction(node); + if (!func) { + grammarErrorOnFirstToken(node, ts.Diagnostics.A_return_statement_can_only_be_used_within_a_function_body); + return; + } + var signature = getSignatureFromDeclaration(func); + var returnType = getReturnTypeOfSignature(signature); + var functionFlags = ts.getFunctionFlags(func); + var isGenerator = functionFlags & 1; + if (strictNullChecks || node.expression || returnType.flags & 131072) { + var exprType = node.expression ? checkExpressionCached(node.expression) : undefinedType; + if (isGenerator) { + return; + } + else if (func.kind === 159) { + if (node.expression) { + error(node, ts.Diagnostics.Setters_cannot_return_a_value); + } + } + else if (func.kind === 157) { + if (node.expression && !checkTypeAssignableToAndOptionallyElaborate(exprType, returnType, node, node.expression)) { + error(node, ts.Diagnostics.Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class); + } + } + else if (getReturnTypeFromAnnotation(func)) { + if (functionFlags & 2) { + var promisedType = getPromisedTypeOfPromise(returnType); + var awaitedType = checkAwaitedType(exprType, node, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); + if (promisedType) { + checkTypeAssignableTo(awaitedType, promisedType, node); + } + } + else { + checkTypeAssignableToAndOptionallyElaborate(exprType, returnType, node, node.expression); + } + } + } + else if (func.kind !== 157 && compilerOptions.noImplicitReturns && !isUnwrappedReturnTypeVoidOrAny(func, returnType) && !isGenerator) { + error(node, ts.Diagnostics.Not_all_code_paths_return_a_value); + } + } + function checkWithStatement(node) { + if (!checkGrammarStatementInAmbientContext(node)) { + if (node.flags & 16384) { + grammarErrorOnFirstToken(node, ts.Diagnostics.with_statements_are_not_allowed_in_an_async_function_block); + } + } + checkExpression(node.expression); + var sourceFile = ts.getSourceFileOfNode(node); + if (!hasParseDiagnostics(sourceFile)) { + var start = ts.getSpanOfTokenAtPosition(sourceFile, node.pos).start; + var end = node.statement.pos; + grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any); + } + } + function checkSwitchStatement(node) { + checkGrammarStatementInAmbientContext(node); + var firstDefaultClause; + var hasDuplicateDefaultClause = false; + var expressionType = checkExpression(node.expression); + var expressionIsLiteral = isLiteralType(expressionType); + ts.forEach(node.caseBlock.clauses, function (clause) { + if (clause.kind === 272 && !hasDuplicateDefaultClause) { + if (firstDefaultClause === undefined) { + firstDefaultClause = clause; + } + else { + var sourceFile = ts.getSourceFileOfNode(node); + var start = ts.skipTrivia(sourceFile.text, clause.pos); + var end = clause.statements.length > 0 ? clause.statements[0].pos : clause.end; + grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.A_default_clause_cannot_appear_more_than_once_in_a_switch_statement); + hasDuplicateDefaultClause = true; + } + } + if (produceDiagnostics && clause.kind === 271) { + var caseType = checkExpression(clause.expression); + var caseIsLiteral = isLiteralType(caseType); + var comparedExpressionType = expressionType; + if (!caseIsLiteral || !expressionIsLiteral) { + caseType = caseIsLiteral ? getBaseTypeOfLiteralType(caseType) : caseType; + comparedExpressionType = getBaseTypeOfLiteralType(expressionType); + } + if (!isTypeEqualityComparableTo(comparedExpressionType, caseType)) { + checkTypeComparableTo(caseType, comparedExpressionType, clause.expression, undefined); + } + } + ts.forEach(clause.statements, checkSourceElement); + }); + if (node.caseBlock.locals) { + registerForUnusedIdentifiersCheck(node.caseBlock); + } + } + function checkLabeledStatement(node) { + if (!checkGrammarStatementInAmbientContext(node)) { + ts.findAncestor(node.parent, function (current) { + if (ts.isFunctionLike(current)) { + return "quit"; + } + if (current.kind === 233 && current.label.escapedText === node.label.escapedText) { + grammarErrorOnNode(node.label, ts.Diagnostics.Duplicate_label_0, ts.getTextOfNode(node.label)); + return true; + } + return false; + }); + } + checkSourceElement(node.statement); + } + function checkThrowStatement(node) { + if (!checkGrammarStatementInAmbientContext(node)) { + if (node.expression === undefined) { + grammarErrorAfterFirstToken(node, ts.Diagnostics.Line_break_not_permitted_here); + } + } + if (node.expression) { + checkExpression(node.expression); + } + } + function checkTryStatement(node) { + checkGrammarStatementInAmbientContext(node); + checkBlock(node.tryBlock); + var catchClause = node.catchClause; + if (catchClause) { + if (catchClause.variableDeclaration) { + if (catchClause.variableDeclaration.type) { + grammarErrorOnFirstToken(catchClause.variableDeclaration.type, ts.Diagnostics.Catch_clause_variable_cannot_have_a_type_annotation); + } + else if (catchClause.variableDeclaration.initializer) { + grammarErrorOnFirstToken(catchClause.variableDeclaration.initializer, ts.Diagnostics.Catch_clause_variable_cannot_have_an_initializer); + } + else { + var blockLocals_1 = catchClause.block.locals; + if (blockLocals_1) { + ts.forEachKey(catchClause.locals, function (caughtName) { + var blockLocal = blockLocals_1.get(caughtName); + if (blockLocal && (blockLocal.flags & 2) !== 0) { + grammarErrorOnNode(blockLocal.valueDeclaration, ts.Diagnostics.Cannot_redeclare_identifier_0_in_catch_clause, caughtName); + } + }); + } + } + } + checkBlock(catchClause.block); + } + if (node.finallyBlock) { + checkBlock(node.finallyBlock); + } + } + function checkIndexConstraints(type) { + var declaredNumberIndexer = getIndexDeclarationOfSymbol(type.symbol, 1); + var declaredStringIndexer = getIndexDeclarationOfSymbol(type.symbol, 0); + var stringIndexType = getIndexTypeOfType(type, 0); + var numberIndexType = getIndexTypeOfType(type, 1); + if (stringIndexType || numberIndexType) { + ts.forEach(getPropertiesOfObjectType(type), function (prop) { + var propType = getTypeOfSymbol(prop); + checkIndexConstraintForProperty(prop, propType, type, declaredStringIndexer, stringIndexType, 0); + checkIndexConstraintForProperty(prop, propType, type, declaredNumberIndexer, numberIndexType, 1); + }); + var classDeclaration = type.symbol.valueDeclaration; + if (ts.getObjectFlags(type) & 1 && ts.isClassLike(classDeclaration)) { + for (var _i = 0, _a = classDeclaration.members; _i < _a.length; _i++) { + var member = _a[_i]; + if (!ts.hasModifier(member, 32) && hasNonBindableDynamicName(member)) { + var symbol = getSymbolOfNode(member); + var propType = getTypeOfSymbol(symbol); + checkIndexConstraintForProperty(symbol, propType, type, declaredStringIndexer, stringIndexType, 0); + checkIndexConstraintForProperty(symbol, propType, type, declaredNumberIndexer, numberIndexType, 1); + } + } + } + } + var errorNode; + if (stringIndexType && numberIndexType) { + errorNode = declaredNumberIndexer || declaredStringIndexer; + if (!errorNode && (ts.getObjectFlags(type) & 2)) { + var someBaseTypeHasBothIndexers = ts.forEach(getBaseTypes(type), function (base) { return getIndexTypeOfType(base, 0) && getIndexTypeOfType(base, 1); }); + errorNode = someBaseTypeHasBothIndexers ? undefined : type.symbol.declarations[0]; + } + } + if (errorNode && !isTypeAssignableTo(numberIndexType, stringIndexType)) { + error(errorNode, ts.Diagnostics.Numeric_index_type_0_is_not_assignable_to_string_index_type_1, typeToString(numberIndexType), typeToString(stringIndexType)); + } + function checkIndexConstraintForProperty(prop, propertyType, containingType, indexDeclaration, indexType, indexKind) { + if (!indexType || ts.isKnownSymbol(prop)) { + return; + } + var propDeclaration = prop.valueDeclaration; + var name = propDeclaration && ts.getNameOfDeclaration(propDeclaration); + if (indexKind === 1 && !(name ? isNumericName(name) : isNumericLiteralName(prop.escapedName))) { + return; + } + var errorNode; + if (propDeclaration && name && + (propDeclaration.kind === 204 || + name.kind === 149 || + prop.parent === containingType.symbol)) { + errorNode = propDeclaration; + } + else if (indexDeclaration) { + errorNode = indexDeclaration; + } + else if (ts.getObjectFlags(containingType) & 2) { + var someBaseClassHasBothPropertyAndIndexer = ts.forEach(getBaseTypes(containingType), function (base) { return getPropertyOfObjectType(base, prop.escapedName) && getIndexTypeOfType(base, indexKind); }); + errorNode = someBaseClassHasBothPropertyAndIndexer ? undefined : containingType.symbol.declarations[0]; + } + if (errorNode && !isTypeAssignableTo(propertyType, indexType)) { + var errorMessage = indexKind === 0 + ? ts.Diagnostics.Property_0_of_type_1_is_not_assignable_to_string_index_type_2 + : ts.Diagnostics.Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2; + error(errorNode, errorMessage, symbolToString(prop), typeToString(propertyType), typeToString(indexType)); + } + } + } + function checkTypeNameIsReserved(name, message) { + switch (name.escapedText) { + case "any": + case "unknown": + case "number": + case "bigint": + case "boolean": + case "string": + case "symbol": + case "void": + case "object": + error(name, message, name.escapedText); + } + } + function checkClassNameCollisionWithObject(name) { + if (languageVersion === 1 && name.escapedText === "Object" + && moduleKind !== ts.ModuleKind.ES2015 && moduleKind !== ts.ModuleKind.ESNext) { + error(name, ts.Diagnostics.Class_name_cannot_be_Object_when_targeting_ES5_with_module_0, ts.ModuleKind[moduleKind]); + } + } + function checkTypeParameters(typeParameterDeclarations) { + if (typeParameterDeclarations) { + var seenDefault = false; + for (var i = 0; i < typeParameterDeclarations.length; i++) { + var node = typeParameterDeclarations[i]; + checkTypeParameter(node); + if (produceDiagnostics) { + if (node.default) { + seenDefault = true; + } + else if (seenDefault) { + error(node, ts.Diagnostics.Required_type_parameters_may_not_follow_optional_type_parameters); + } + for (var j = 0; j < i; j++) { + if (typeParameterDeclarations[j].symbol === node.symbol) { + error(node.name, ts.Diagnostics.Duplicate_identifier_0, ts.declarationNameToString(node.name)); + } + } + } + } + } + } + function checkTypeParameterListsIdentical(symbol) { + if (symbol.declarations.length === 1) { + return; + } + var links = getSymbolLinks(symbol); + if (!links.typeParametersChecked) { + links.typeParametersChecked = true; + var declarations = getClassOrInterfaceDeclarationsOfSymbol(symbol); + if (declarations.length <= 1) { + return; + } + var type = getDeclaredTypeOfSymbol(symbol); + if (!areTypeParametersIdentical(declarations, type.localTypeParameters)) { + var name = symbolToString(symbol); + for (var _i = 0, declarations_6 = declarations; _i < declarations_6.length; _i++) { + var declaration = declarations_6[_i]; + error(declaration.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_type_parameters, name); + } + } + } + } + function areTypeParametersIdentical(declarations, targetParameters) { + var maxTypeArgumentCount = ts.length(targetParameters); + var minTypeArgumentCount = getMinTypeArgumentCount(targetParameters); + for (var _i = 0, declarations_7 = declarations; _i < declarations_7.length; _i++) { + var declaration = declarations_7[_i]; + var sourceParameters = ts.getEffectiveTypeParameterDeclarations(declaration); + var numTypeParameters = sourceParameters.length; + if (numTypeParameters < minTypeArgumentCount || numTypeParameters > maxTypeArgumentCount) { + return false; + } + for (var i = 0; i < numTypeParameters; i++) { + var source = sourceParameters[i]; + var target = targetParameters[i]; + if (source.name.escapedText !== target.symbol.escapedName) { + return false; + } + var constraint = ts.getEffectiveConstraintOfTypeParameter(source); + var sourceConstraint = constraint && getTypeFromTypeNode(constraint); + var targetConstraint = getConstraintOfTypeParameter(target); + if (sourceConstraint) { + if (!targetConstraint || !isTypeIdenticalTo(sourceConstraint, targetConstraint)) { + return false; + } + } + var sourceDefault = source.default && getTypeFromTypeNode(source.default); + var targetDefault = getDefaultFromTypeParameter(target); + if (sourceDefault && targetDefault && !isTypeIdenticalTo(sourceDefault, targetDefault)) { + return false; + } + } + } + return true; + } + function checkClassExpression(node) { + checkClassLikeDeclaration(node); + checkNodeDeferred(node); + return getTypeOfSymbol(getSymbolOfNode(node)); + } + function checkClassExpressionDeferred(node) { + ts.forEach(node.members, checkSourceElement); + registerForUnusedIdentifiersCheck(node); + } + function checkClassDeclaration(node) { + if (!node.name && !ts.hasModifier(node, 512)) { + grammarErrorOnFirstToken(node, ts.Diagnostics.A_class_declaration_without_the_default_modifier_must_have_a_name); + } + checkClassLikeDeclaration(node); + ts.forEach(node.members, checkSourceElement); + registerForUnusedIdentifiersCheck(node); + } + function checkClassLikeDeclaration(node) { + checkGrammarClassLikeDeclaration(node); + checkDecorators(node); + if (node.name) { + checkTypeNameIsReserved(node.name, ts.Diagnostics.Class_name_cannot_be_0); + checkCollisionWithRequireExportsInGeneratedCode(node, node.name); + checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); + if (!(node.flags & 4194304)) { + checkClassNameCollisionWithObject(node.name); + } + } + checkTypeParameters(ts.getEffectiveTypeParameterDeclarations(node)); + checkExportsOnMergedDeclarations(node); + var symbol = getSymbolOfNode(node); + var type = getDeclaredTypeOfSymbol(symbol); + var typeWithThis = getTypeWithThisArgument(type); + var staticType = getTypeOfSymbol(symbol); + checkTypeParameterListsIdentical(symbol); + checkClassForDuplicateDeclarations(node); + if (!(node.flags & 4194304)) { + checkClassForStaticPropertyNameConflicts(node); + } + var baseTypeNode = ts.getEffectiveBaseTypeNode(node); + if (baseTypeNode) { + if (languageVersion < 2) { + checkExternalEmitHelpers(baseTypeNode.parent, 1); + } + var baseTypes = getBaseTypes(type); + if (baseTypes.length && produceDiagnostics) { + var baseType_1 = baseTypes[0]; + var baseConstructorType = getBaseConstructorTypeOfClass(type); + var staticBaseType = getApparentType(baseConstructorType); + checkBaseTypeAccessibility(staticBaseType, baseTypeNode); + checkSourceElement(baseTypeNode.expression); + var extendsNode = ts.getClassExtendsHeritageElement(node); + if (extendsNode && extendsNode !== baseTypeNode) { + checkExpression(extendsNode.expression); + } + if (ts.some(baseTypeNode.typeArguments)) { + ts.forEach(baseTypeNode.typeArguments, checkSourceElement); + for (var _i = 0, _a = getConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments, baseTypeNode); _i < _a.length; _i++) { + var constructor = _a[_i]; + if (!checkTypeArgumentConstraints(baseTypeNode, constructor.typeParameters)) { + break; + } + } + } + var baseWithThis = getTypeWithThisArgument(baseType_1, type.thisType); + if (!checkTypeAssignableTo(typeWithThis, baseWithThis, undefined)) { + issueMemberSpecificError(node, typeWithThis, baseWithThis, ts.Diagnostics.Class_0_incorrectly_extends_base_class_1); + } + else { + checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, ts.Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1); + } + if (baseConstructorType.flags & 8650752 && !isMixinConstructorType(staticType)) { + error(node.name || node, ts.Diagnostics.A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any); + } + if (!(staticBaseType.symbol && staticBaseType.symbol.flags & 32) && !(baseConstructorType.flags & 8650752)) { + var constructors = getInstantiatedConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments, baseTypeNode); + if (ts.forEach(constructors, function (sig) { return !isJSConstructor(sig.declaration) && getReturnTypeOfSignature(sig) !== baseType_1; })) { + error(baseTypeNode.expression, ts.Diagnostics.Base_constructors_must_all_have_the_same_return_type); + } + } + checkKindsOfPropertyMemberOverrides(type, baseType_1); + } + } + var implementedTypeNodes = ts.getClassImplementsHeritageClauseElements(node); + if (implementedTypeNodes) { + for (var _b = 0, implementedTypeNodes_1 = implementedTypeNodes; _b < implementedTypeNodes_1.length; _b++) { + var typeRefNode = implementedTypeNodes_1[_b]; + if (!ts.isEntityNameExpression(typeRefNode.expression)) { + error(typeRefNode.expression, ts.Diagnostics.A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments); + } + checkTypeReferenceNode(typeRefNode); + if (produceDiagnostics) { + var t = getTypeFromTypeNode(typeRefNode); + if (t !== errorType) { + if (isValidBaseType(t)) { + var genericDiag = t.symbol && t.symbol.flags & 32 ? + ts.Diagnostics.Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass : + ts.Diagnostics.Class_0_incorrectly_implements_interface_1; + var baseWithThis = getTypeWithThisArgument(t, type.thisType); + if (!checkTypeAssignableTo(typeWithThis, baseWithThis, undefined)) { + issueMemberSpecificError(node, typeWithThis, baseWithThis, genericDiag); + } + } + else { + error(typeRefNode, ts.Diagnostics.A_class_can_only_implement_an_object_type_or_intersection_of_object_types_with_statically_known_members); + } + } + } + } + } + if (produceDiagnostics) { + checkIndexConstraints(type); + checkTypeForDuplicateIndexSignatures(node); + checkPropertyInitialization(node); + } + } + function issueMemberSpecificError(node, typeWithThis, baseWithThis, broadDiag) { + var issuedMemberError = false; + var _loop_8 = function (member) { + if (ts.hasStaticModifier(member)) { + return "continue"; + } + var declaredProp = member.name && getSymbolAtLocation(member.name) || getSymbolAtLocation(member); + if (declaredProp) { + var prop = getPropertyOfType(typeWithThis, declaredProp.escapedName); + var baseProp = getPropertyOfType(baseWithThis, declaredProp.escapedName); + if (prop && baseProp) { + var rootChain = function () { return ts.chainDiagnosticMessages(undefined, ts.Diagnostics.Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2, symbolToString(declaredProp), typeToString(typeWithThis), typeToString(baseWithThis)); }; + if (!checkTypeAssignableTo(getTypeOfSymbol(prop), getTypeOfSymbol(baseProp), member.name || member, undefined, rootChain)) { + issuedMemberError = true; + } + } + } + }; + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + _loop_8(member); + } + if (!issuedMemberError) { + checkTypeAssignableTo(typeWithThis, baseWithThis, node.name || node, broadDiag); + } + } + function checkBaseTypeAccessibility(type, node) { + var signatures = getSignaturesOfType(type, 1); + if (signatures.length) { + var declaration = signatures[0].declaration; + if (declaration && ts.hasModifier(declaration, 8)) { + var typeClassDeclaration = ts.getClassLikeDeclarationOfSymbol(type.symbol); + if (!isNodeWithinClass(node, typeClassDeclaration)) { + error(node, ts.Diagnostics.Cannot_extend_a_class_0_Class_constructor_is_marked_as_private, getFullyQualifiedName(type.symbol)); + } + } + } + } + function getTargetSymbol(s) { + return ts.getCheckFlags(s) & 1 ? s.target : s; + } + function getClassOrInterfaceDeclarationsOfSymbol(symbol) { + return ts.filter(symbol.declarations, function (d) { + return d.kind === 240 || d.kind === 241; + }); + } + function checkKindsOfPropertyMemberOverrides(type, baseType) { + var baseProperties = getPropertiesOfType(baseType); + for (var _i = 0, baseProperties_1 = baseProperties; _i < baseProperties_1.length; _i++) { + var baseProperty = baseProperties_1[_i]; + var base = getTargetSymbol(baseProperty); + if (base.flags & 4194304) { + continue; + } + var derived = getTargetSymbol(getPropertyOfObjectType(type, base.escapedName)); + var baseDeclarationFlags = ts.getDeclarationModifierFlagsFromSymbol(base); + ts.Debug.assert(!!derived, "derived should point to something, even if it is the base class' declaration."); + if (derived) { + if (derived === base) { + var derivedClassDecl = ts.getClassLikeDeclarationOfSymbol(type.symbol); + if (baseDeclarationFlags & 128 && (!derivedClassDecl || !ts.hasModifier(derivedClassDecl, 128))) { + if (derivedClassDecl.kind === 209) { + error(derivedClassDecl, ts.Diagnostics.Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1, symbolToString(baseProperty), typeToString(baseType)); + } + else { + error(derivedClassDecl, ts.Diagnostics.Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2, typeToString(type), symbolToString(baseProperty), typeToString(baseType)); + } + } + } + else { + var derivedDeclarationFlags = ts.getDeclarationModifierFlagsFromSymbol(derived); + if (baseDeclarationFlags & 8 || derivedDeclarationFlags & 8) { + continue; + } + if (isPrototypeProperty(base) || base.flags & 98308 && derived.flags & 98308) { + continue; + } + var errorMessage = void 0; + if (isPrototypeProperty(base)) { + if (derived.flags & 98304) { + errorMessage = ts.Diagnostics.Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor; + } + else { + errorMessage = ts.Diagnostics.Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_property; + } + } + else if (base.flags & 98304) { + errorMessage = ts.Diagnostics.Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function; + } + else { + errorMessage = ts.Diagnostics.Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_function; + } + error(ts.getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage, typeToString(baseType), symbolToString(base), typeToString(type)); + } + } + } + } + function checkInheritedPropertiesAreIdentical(type, typeNode) { + var baseTypes = getBaseTypes(type); + if (baseTypes.length < 2) { + return true; + } + var seen = ts.createUnderscoreEscapedMap(); + ts.forEach(resolveDeclaredMembers(type).declaredProperties, function (p) { seen.set(p.escapedName, { prop: p, containingType: type }); }); + var ok = true; + for (var _i = 0, baseTypes_2 = baseTypes; _i < baseTypes_2.length; _i++) { + var base = baseTypes_2[_i]; + var properties = getPropertiesOfType(getTypeWithThisArgument(base, type.thisType)); + for (var _a = 0, properties_7 = properties; _a < properties_7.length; _a++) { + var prop = properties_7[_a]; + var existing = seen.get(prop.escapedName); + if (!existing) { + seen.set(prop.escapedName, { prop: prop, containingType: base }); + } + else { + var isInheritedProperty = existing.containingType !== type; + if (isInheritedProperty && !isPropertyIdenticalTo(existing.prop, prop)) { + ok = false; + var typeName1 = typeToString(existing.containingType); + var typeName2 = typeToString(base); + var errorInfo = ts.chainDiagnosticMessages(undefined, ts.Diagnostics.Named_property_0_of_types_1_and_2_are_not_identical, symbolToString(prop), typeName1, typeName2); + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Interface_0_cannot_simultaneously_extend_types_1_and_2, typeToString(type), typeName1, typeName2); + diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(typeNode, errorInfo)); + } + } + } + } + return ok; + } + function checkPropertyInitialization(node) { + if (!strictNullChecks || !strictPropertyInitialization || node.flags & 4194304) { + return; + } + var constructor = findConstructorDeclaration(node); + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + if (isInstancePropertyWithoutInitializer(member)) { + var propName = member.name; + if (ts.isIdentifier(propName)) { + var type = getTypeOfSymbol(getSymbolOfNode(member)); + if (!(type.flags & 3 || getFalsyFlags(type) & 32768)) { + if (!constructor || !isPropertyInitializedInConstructor(propName, type, constructor)) { + error(member.name, ts.Diagnostics.Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor, ts.declarationNameToString(propName)); + } + } + } + } + } + } + function isInstancePropertyWithoutInitializer(node) { + return node.kind === 154 && + !ts.hasModifier(node, 32 | 128) && + !node.exclamationToken && + !node.initializer; + } + function isPropertyInitializedInConstructor(propName, propType, constructor) { + var reference = ts.createPropertyAccess(ts.createThis(), propName); + reference.expression.parent = reference; + reference.parent = constructor; + reference.flowNode = constructor.returnFlowNode; + var flowType = getFlowTypeOfReference(reference, propType, getOptionalType(propType)); + return !(getFalsyFlags(flowType) & 32768); + } + function checkInterfaceDeclaration(node) { + if (!checkGrammarDecoratorsAndModifiers(node)) + checkGrammarInterfaceDeclaration(node); + checkTypeParameters(node.typeParameters); + if (produceDiagnostics) { + checkTypeNameIsReserved(node.name, ts.Diagnostics.Interface_name_cannot_be_0); + checkExportsOnMergedDeclarations(node); + var symbol = getSymbolOfNode(node); + checkTypeParameterListsIdentical(symbol); + var firstInterfaceDecl = ts.getDeclarationOfKind(symbol, 241); + if (node === firstInterfaceDecl) { + var type = getDeclaredTypeOfSymbol(symbol); + var typeWithThis = getTypeWithThisArgument(type); + if (checkInheritedPropertiesAreIdentical(type, node.name)) { + for (var _i = 0, _a = getBaseTypes(type); _i < _a.length; _i++) { + var baseType = _a[_i]; + checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(baseType, type.thisType), node.name, ts.Diagnostics.Interface_0_incorrectly_extends_interface_1); + } + checkIndexConstraints(type); + } + } + checkObjectTypeForDuplicateDeclarations(node); + } + ts.forEach(ts.getInterfaceBaseTypeNodes(node), function (heritageElement) { + if (!ts.isEntityNameExpression(heritageElement.expression)) { + error(heritageElement.expression, ts.Diagnostics.An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments); + } + checkTypeReferenceNode(heritageElement); + }); + ts.forEach(node.members, checkSourceElement); + if (produceDiagnostics) { + checkTypeForDuplicateIndexSignatures(node); + registerForUnusedIdentifiersCheck(node); + } + } + function checkTypeAliasDeclaration(node) { + checkGrammarDecoratorsAndModifiers(node); + checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_alias_name_cannot_be_0); + checkTypeParameters(node.typeParameters); + checkSourceElement(node.type); + registerForUnusedIdentifiersCheck(node); + } + function computeEnumMemberValues(node) { + var nodeLinks = getNodeLinks(node); + if (!(nodeLinks.flags & 16384)) { + nodeLinks.flags |= 16384; + var autoValue = 0; + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + var value = computeMemberValue(member, autoValue); + getNodeLinks(member).enumMemberValue = value; + autoValue = typeof value === "number" ? value + 1 : undefined; + } + } + } + function computeMemberValue(member, autoValue) { + if (isComputedNonLiteralName(member.name)) { + error(member.name, ts.Diagnostics.Computed_property_names_are_not_allowed_in_enums); + } + else { + var text = ts.getTextOfPropertyName(member.name); + if (isNumericLiteralName(text) && !isInfinityOrNaNString(text)) { + error(member.name, ts.Diagnostics.An_enum_member_cannot_have_a_numeric_name); + } + } + if (member.initializer) { + return computeConstantValue(member); + } + if (member.parent.flags & 4194304 && !ts.isEnumConst(member.parent)) { + return undefined; + } + if (autoValue !== undefined) { + return autoValue; + } + error(member.name, ts.Diagnostics.Enum_member_must_have_initializer); + return undefined; + } + function computeConstantValue(member) { + var enumKind = getEnumKind(getSymbolOfNode(member.parent)); + var isConstEnum = ts.isEnumConst(member.parent); + var initializer = member.initializer; + var value = enumKind === 1 && !isLiteralEnumMember(member) ? undefined : evaluate(initializer); + if (value !== undefined) { + if (isConstEnum && typeof value === "number" && !isFinite(value)) { + error(initializer, isNaN(value) ? + ts.Diagnostics.const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN : + ts.Diagnostics.const_enum_member_initializer_was_evaluated_to_a_non_finite_value); + } + } + else if (enumKind === 1) { + error(initializer, ts.Diagnostics.Computed_values_are_not_permitted_in_an_enum_with_string_valued_members); + return 0; + } + else if (isConstEnum) { + error(initializer, ts.Diagnostics.In_const_enum_declarations_member_initializer_must_be_constant_expression); + } + else if (member.parent.flags & 4194304) { + error(initializer, ts.Diagnostics.In_ambient_enum_declarations_member_initializer_must_be_constant_expression); + } + else { + checkTypeAssignableTo(checkExpression(initializer), getDeclaredTypeOfSymbol(getSymbolOfNode(member.parent)), initializer, undefined); + } + return value; + function evaluate(expr) { + switch (expr.kind) { + case 202: + var value_2 = evaluate(expr.operand); + if (typeof value_2 === "number") { + switch (expr.operator) { + case 38: return value_2; + case 39: return -value_2; + case 53: return ~value_2; + } + } + break; + case 204: + var left = evaluate(expr.left); + var right = evaluate(expr.right); + if (typeof left === "number" && typeof right === "number") { + switch (expr.operatorToken.kind) { + case 50: return left | right; + case 49: return left & right; + case 47: return left >> right; + case 48: return left >>> right; + case 46: return left << right; + case 51: return left ^ right; + case 40: return left * right; + case 42: return left / right; + case 38: return left + right; + case 39: return left - right; + case 43: return left % right; + case 41: return Math.pow(left, right); + } + } + else if (typeof left === "string" && typeof right === "string" && expr.operatorToken.kind === 38) { + return left + right; + } + break; + case 10: + return expr.text; + case 8: + checkGrammarNumericLiteral(expr); + return +expr.text; + case 195: + return evaluate(expr.expression); + case 72: + var identifier = expr; + if (isInfinityOrNaNString(identifier.escapedText)) { + return +(identifier.escapedText); + } + return ts.nodeIsMissing(expr) ? 0 : evaluateEnumMember(expr, getSymbolOfNode(member.parent), identifier.escapedText); + case 190: + case 189: + var ex = expr; + if (isConstantMemberAccess(ex)) { + var type = getTypeOfExpression(ex.expression); + if (type.symbol && type.symbol.flags & 384) { + var name = void 0; + if (ex.kind === 189) { + name = ex.name.escapedText; + } + else { + var argument = ex.argumentExpression; + ts.Debug.assert(ts.isLiteralExpression(argument)); + name = ts.escapeLeadingUnderscores(argument.text); + } + return evaluateEnumMember(expr, type.symbol, name); + } + } + break; + } + return undefined; + } + function evaluateEnumMember(expr, enumSymbol, name) { + var memberSymbol = enumSymbol.exports.get(name); + if (memberSymbol) { + var declaration = memberSymbol.valueDeclaration; + if (declaration !== member) { + if (isBlockScopedNameDeclaredBeforeUse(declaration, member)) { + return getEnumMemberValue(declaration); + } + error(expr, ts.Diagnostics.A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums); + return 0; + } + } + return undefined; + } + } + function isConstantMemberAccess(node) { + return node.kind === 72 || + node.kind === 189 && isConstantMemberAccess(node.expression) || + node.kind === 190 && isConstantMemberAccess(node.expression) && + node.argumentExpression.kind === 10; + } + function checkEnumDeclaration(node) { + if (!produceDiagnostics) { + return; + } + checkGrammarDecoratorsAndModifiers(node); + checkTypeNameIsReserved(node.name, ts.Diagnostics.Enum_name_cannot_be_0); + checkCollisionWithRequireExportsInGeneratedCode(node, node.name); + checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); + checkExportsOnMergedDeclarations(node); + computeEnumMemberValues(node); + var enumIsConst = ts.isEnumConst(node); + if (compilerOptions.isolatedModules && enumIsConst && node.flags & 4194304) { + error(node.name, ts.Diagnostics.Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided); + } + var enumSymbol = getSymbolOfNode(node); + var firstDeclaration = ts.getDeclarationOfKind(enumSymbol, node.kind); + if (node === firstDeclaration) { + if (enumSymbol.declarations.length > 1) { + ts.forEach(enumSymbol.declarations, function (decl) { + if (ts.isEnumDeclaration(decl) && ts.isEnumConst(decl) !== enumIsConst) { + error(ts.getNameOfDeclaration(decl), ts.Diagnostics.Enum_declarations_must_all_be_const_or_non_const); + } + }); + } + var seenEnumMissingInitialInitializer_1 = false; + ts.forEach(enumSymbol.declarations, function (declaration) { + if (declaration.kind !== 243) { + return false; + } + var enumDeclaration = declaration; + if (!enumDeclaration.members.length) { + return false; + } + var firstEnumMember = enumDeclaration.members[0]; + if (!firstEnumMember.initializer) { + if (seenEnumMissingInitialInitializer_1) { + error(firstEnumMember.name, ts.Diagnostics.In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enum_element); + } + else { + seenEnumMissingInitialInitializer_1 = true; + } + } + }); + } + } + function getFirstNonAmbientClassOrFunctionDeclaration(symbol) { + var declarations = symbol.declarations; + for (var _i = 0, declarations_8 = declarations; _i < declarations_8.length; _i++) { + var declaration = declarations_8[_i]; + if ((declaration.kind === 240 || + (declaration.kind === 239 && ts.nodeIsPresent(declaration.body))) && + !(declaration.flags & 4194304)) { + return declaration; + } + } + return undefined; + } + function inSameLexicalScope(node1, node2) { + var container1 = ts.getEnclosingBlockScopeContainer(node1); + var container2 = ts.getEnclosingBlockScopeContainer(node2); + if (isGlobalSourceFile(container1)) { + return isGlobalSourceFile(container2); + } + else if (isGlobalSourceFile(container2)) { + return false; + } + else { + return container1 === container2; + } + } + function checkModuleDeclaration(node) { + if (produceDiagnostics) { + var isGlobalAugmentation = ts.isGlobalScopeAugmentation(node); + var inAmbientContext = node.flags & 4194304; + if (isGlobalAugmentation && !inAmbientContext) { + error(node.name, ts.Diagnostics.Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambient_context); + } + var isAmbientExternalModule = ts.isAmbientModule(node); + var contextErrorMessage = isAmbientExternalModule + ? ts.Diagnostics.An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file + : ts.Diagnostics.A_namespace_declaration_is_only_allowed_in_a_namespace_or_module; + if (checkGrammarModuleElementContext(node, contextErrorMessage)) { + return; + } + if (!checkGrammarDecoratorsAndModifiers(node)) { + if (!inAmbientContext && node.name.kind === 10) { + grammarErrorOnNode(node.name, ts.Diagnostics.Only_ambient_modules_can_use_quoted_names); + } + } + if (ts.isIdentifier(node.name)) { + checkCollisionWithRequireExportsInGeneratedCode(node, node.name); + checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); + } + checkExportsOnMergedDeclarations(node); + var symbol = getSymbolOfNode(node); + if (symbol.flags & 512 + && symbol.declarations.length > 1 + && !inAmbientContext + && isInstantiatedModule(node, !!compilerOptions.preserveConstEnums || !!compilerOptions.isolatedModules)) { + var firstNonAmbientClassOrFunc = getFirstNonAmbientClassOrFunctionDeclaration(symbol); + if (firstNonAmbientClassOrFunc) { + if (ts.getSourceFileOfNode(node) !== ts.getSourceFileOfNode(firstNonAmbientClassOrFunc)) { + error(node.name, ts.Diagnostics.A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merged); + } + else if (node.pos < firstNonAmbientClassOrFunc.pos) { + error(node.name, ts.Diagnostics.A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged); + } + } + var mergedClass = ts.getDeclarationOfKind(symbol, 240); + if (mergedClass && + inSameLexicalScope(node, mergedClass)) { + getNodeLinks(node).flags |= 32768; + } + } + if (isAmbientExternalModule) { + if (ts.isExternalModuleAugmentation(node)) { + var checkBody = isGlobalAugmentation || (getSymbolOfNode(node).flags & 33554432); + if (checkBody && node.body) { + for (var _i = 0, _a = node.body.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + checkModuleAugmentationElement(statement, isGlobalAugmentation); + } + } + } + else if (isGlobalSourceFile(node.parent)) { + if (isGlobalAugmentation) { + error(node.name, ts.Diagnostics.Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_declarations); + } + else if (ts.isExternalModuleNameRelative(ts.getTextOfIdentifierOrLiteral(node.name))) { + error(node.name, ts.Diagnostics.Ambient_module_declaration_cannot_specify_relative_module_name); + } + } + else { + if (isGlobalAugmentation) { + error(node.name, ts.Diagnostics.Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_declarations); + } + else { + error(node.name, ts.Diagnostics.Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces); + } + } + } + } + if (node.body) { + checkSourceElement(node.body); + if (!ts.isGlobalScopeAugmentation(node)) { + registerForUnusedIdentifiersCheck(node); + } + } + } + function checkModuleAugmentationElement(node, isGlobalAugmentation) { + switch (node.kind) { + case 219: + for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + checkModuleAugmentationElement(decl, isGlobalAugmentation); + } + break; + case 254: + case 255: + grammarErrorOnFirstToken(node, ts.Diagnostics.Exports_and_export_assignments_are_not_permitted_in_module_augmentations); + break; + case 248: + case 249: + grammarErrorOnFirstToken(node, ts.Diagnostics.Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_module); + break; + case 186: + case 237: + var name = node.name; + if (ts.isBindingPattern(name)) { + for (var _b = 0, _c = name.elements; _b < _c.length; _b++) { + var el = _c[_b]; + checkModuleAugmentationElement(el, isGlobalAugmentation); + } + break; + } + case 240: + case 243: + case 239: + case 241: + case 244: + case 242: + if (isGlobalAugmentation) { + return; + } + var symbol = getSymbolOfNode(node); + if (symbol) { + var reportError = !(symbol.flags & 33554432); + if (!reportError) { + reportError = !!symbol.parent && ts.isExternalModuleAugmentation(symbol.parent.declarations[0]); + } + } + break; + } + } + function getFirstIdentifier(node) { + switch (node.kind) { + case 72: + return node; + case 148: + do { + node = node.left; + } while (node.kind !== 72); + return node; + case 189: + do { + node = node.expression; + } while (node.kind !== 72); + return node; + } + } + function checkExternalImportOrExportDeclaration(node) { + var moduleName = ts.getExternalModuleName(node); + if (!moduleName || ts.nodeIsMissing(moduleName)) { + return false; + } + if (!ts.isStringLiteral(moduleName)) { + error(moduleName, ts.Diagnostics.String_literal_expected); + return false; + } + var inAmbientExternalModule = node.parent.kind === 245 && ts.isAmbientModule(node.parent.parent); + if (node.parent.kind !== 279 && !inAmbientExternalModule) { + error(moduleName, node.kind === 255 ? + ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace : + ts.Diagnostics.Import_declarations_in_a_namespace_cannot_reference_a_module); + return false; + } + if (inAmbientExternalModule && ts.isExternalModuleNameRelative(moduleName.text)) { + if (!isTopLevelInExternalModuleAugmentation(node)) { + error(node, ts.Diagnostics.Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relative_module_name); + return false; + } + } + return true; + } + function checkAliasSymbol(node) { + var symbol = getSymbolOfNode(node); + var target = resolveAlias(symbol); + if (target !== unknownSymbol) { + var excludedMeanings = (symbol.flags & (67220415 | 1048576) ? 67220415 : 0) | + (symbol.flags & 67897832 ? 67897832 : 0) | + (symbol.flags & 1920 ? 1920 : 0); + if (target.flags & excludedMeanings) { + var message = node.kind === 257 ? + ts.Diagnostics.Export_declaration_conflicts_with_exported_declaration_of_0 : + ts.Diagnostics.Import_declaration_conflicts_with_local_declaration_of_0; + error(node, message, symbolToString(symbol)); + } + if (compilerOptions.isolatedModules + && node.kind === 257 + && !(target.flags & 67220415) + && !(node.flags & 4194304)) { + error(node, ts.Diagnostics.Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided); + } + } + } + function checkImportBinding(node) { + checkCollisionWithRequireExportsInGeneratedCode(node, node.name); + checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); + checkAliasSymbol(node); + } + function checkImportDeclaration(node) { + if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_import_declaration_can_only_be_used_in_a_namespace_or_module)) { + return; + } + if (!checkGrammarDecoratorsAndModifiers(node) && ts.hasModifiers(node)) { + grammarErrorOnFirstToken(node, ts.Diagnostics.An_import_declaration_cannot_have_modifiers); + } + if (checkExternalImportOrExportDeclaration(node)) { + var importClause = node.importClause; + if (importClause) { + if (importClause.name) { + checkImportBinding(importClause); + } + if (importClause.namedBindings) { + if (importClause.namedBindings.kind === 251) { + checkImportBinding(importClause.namedBindings); + } + else { + var moduleExisted = resolveExternalModuleName(node, node.moduleSpecifier); + if (moduleExisted) { + ts.forEach(importClause.namedBindings.elements, checkImportBinding); + } + } + } + } + } + } + function checkImportEqualsDeclaration(node) { + if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_import_declaration_can_only_be_used_in_a_namespace_or_module)) { + return; + } + checkGrammarDecoratorsAndModifiers(node); + if (ts.isInternalModuleImportEqualsDeclaration(node) || checkExternalImportOrExportDeclaration(node)) { + checkImportBinding(node); + if (ts.hasModifier(node, 1)) { + markExportAsReferenced(node); + } + if (node.moduleReference.kind !== 259) { + var target = resolveAlias(getSymbolOfNode(node)); + if (target !== unknownSymbol) { + if (target.flags & 67220415) { + var moduleName = getFirstIdentifier(node.moduleReference); + if (!(resolveEntityName(moduleName, 67220415 | 1920).flags & 1920)) { + error(moduleName, ts.Diagnostics.Module_0_is_hidden_by_a_local_declaration_with_the_same_name, ts.declarationNameToString(moduleName)); + } + } + if (target.flags & 67897832) { + checkTypeNameIsReserved(node.name, ts.Diagnostics.Import_name_cannot_be_0); + } + } + } + else { + if (moduleKind >= ts.ModuleKind.ES2015 && !(node.flags & 4194304)) { + grammarErrorOnNode(node, ts.Diagnostics.Import_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_import_Asterisk_as_ns_from_mod_import_a_from_mod_import_d_from_mod_or_another_module_format_instead); + } + } + } + } + function checkExportDeclaration(node) { + if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_export_declaration_can_only_be_used_in_a_module)) { + return; + } + if (!checkGrammarDecoratorsAndModifiers(node) && ts.hasModifiers(node)) { + grammarErrorOnFirstToken(node, ts.Diagnostics.An_export_declaration_cannot_have_modifiers); + } + if (!node.moduleSpecifier || checkExternalImportOrExportDeclaration(node)) { + if (node.exportClause) { + ts.forEach(node.exportClause.elements, checkExportSpecifier); + var inAmbientExternalModule = node.parent.kind === 245 && ts.isAmbientModule(node.parent.parent); + var inAmbientNamespaceDeclaration = !inAmbientExternalModule && node.parent.kind === 245 && + !node.moduleSpecifier && node.flags & 4194304; + if (node.parent.kind !== 279 && !inAmbientExternalModule && !inAmbientNamespaceDeclaration) { + error(node, ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace); + } + } + else { + var moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier); + if (moduleSymbol && hasExportAssignmentSymbol(moduleSymbol)) { + error(node.moduleSpecifier, ts.Diagnostics.Module_0_uses_export_and_cannot_be_used_with_export_Asterisk, symbolToString(moduleSymbol)); + } + if (moduleKind !== ts.ModuleKind.System && moduleKind !== ts.ModuleKind.ES2015 && moduleKind !== ts.ModuleKind.ESNext) { + checkExternalEmitHelpers(node, 32768); + } + } + } + } + function checkGrammarModuleElementContext(node, errorMessage) { + var isInAppropriateContext = node.parent.kind === 279 || node.parent.kind === 245 || node.parent.kind === 244; + if (!isInAppropriateContext) { + grammarErrorOnFirstToken(node, errorMessage); + } + return !isInAppropriateContext; + } + function checkExportSpecifier(node) { + checkAliasSymbol(node); + if (ts.getEmitDeclarations(compilerOptions)) { + collectLinkedAliases(node.propertyName || node.name, true); + } + if (!node.parent.parent.moduleSpecifier) { + var exportedName = node.propertyName || node.name; + var symbol = resolveName(exportedName, exportedName.escapedText, 67220415 | 67897832 | 1920 | 2097152, undefined, undefined, true); + if (symbol && (symbol === undefinedSymbol || isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { + error(exportedName, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, ts.idText(exportedName)); + } + else { + markExportAsReferenced(node); + } + } + } + function checkExportAssignment(node) { + if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_export_assignment_can_only_be_used_in_a_module)) { + return; + } + var container = node.parent.kind === 279 ? node.parent : node.parent.parent; + if (container.kind === 244 && !ts.isAmbientModule(container)) { + if (node.isExportEquals) { + error(node, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_namespace); + } + else { + error(node, ts.Diagnostics.A_default_export_can_only_be_used_in_an_ECMAScript_style_module); + } + return; + } + if (!checkGrammarDecoratorsAndModifiers(node) && ts.hasModifiers(node)) { + grammarErrorOnFirstToken(node, ts.Diagnostics.An_export_assignment_cannot_have_modifiers); + } + if (node.expression.kind === 72) { + markExportAsReferenced(node); + if (ts.getEmitDeclarations(compilerOptions)) { + collectLinkedAliases(node.expression, true); + } + } + else { + checkExpressionCached(node.expression); + } + checkExternalModuleExports(container); + if ((node.flags & 4194304) && !ts.isEntityNameExpression(node.expression)) { + grammarErrorOnNode(node.expression, ts.Diagnostics.The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context); + } + if (node.isExportEquals && !(node.flags & 4194304)) { + if (moduleKind >= ts.ModuleKind.ES2015) { + grammarErrorOnNode(node, ts.Diagnostics.Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or_another_module_format_instead); + } + else if (moduleKind === ts.ModuleKind.System) { + grammarErrorOnNode(node, ts.Diagnostics.Export_assignment_is_not_supported_when_module_flag_is_system); + } + } + } + function hasExportedMembers(moduleSymbol) { + return ts.forEachEntry(moduleSymbol.exports, function (_, id) { return id !== "export="; }); + } + function checkExternalModuleExports(node) { + var moduleSymbol = getSymbolOfNode(node); + var links = getSymbolLinks(moduleSymbol); + if (!links.exportsChecked) { + var exportEqualsSymbol = moduleSymbol.exports.get("export="); + if (exportEqualsSymbol && hasExportedMembers(moduleSymbol)) { + var declaration = getDeclarationOfAliasSymbol(exportEqualsSymbol) || exportEqualsSymbol.valueDeclaration; + if (!isTopLevelInExternalModuleAugmentation(declaration) && !ts.isInJSFile(declaration)) { + error(declaration, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements); + } + } + var exports_1 = getExportsOfModule(moduleSymbol); + if (exports_1) { + exports_1.forEach(function (_a, id) { + var declarations = _a.declarations, flags = _a.flags; + if (id === "__export") { + return; + } + if (flags & (1920 | 64 | 384)) { + return; + } + var exportedDeclarationsCount = ts.countWhere(declarations, isNotOverloadAndNotAccessor); + if (flags & 524288 && exportedDeclarationsCount <= 2) { + return; + } + if (exportedDeclarationsCount > 1) { + for (var _i = 0, declarations_9 = declarations; _i < declarations_9.length; _i++) { + var declaration = declarations_9[_i]; + if (isNotOverload(declaration)) { + diagnostics.add(ts.createDiagnosticForNode(declaration, ts.Diagnostics.Cannot_redeclare_exported_variable_0, ts.unescapeLeadingUnderscores(id))); + } + } + } + }); + } + links.exportsChecked = true; + } + } + function isNotAccessor(declaration) { + return !ts.isAccessor(declaration); + } + function isNotOverload(declaration) { + return (declaration.kind !== 239 && declaration.kind !== 156) || + !!declaration.body; + } + function checkSourceElement(node) { + if (!node) { + return; + } + if (ts.isInJSFile(node)) { + ts.forEach(node.jsDoc, function (_a) { + var tags = _a.tags; + return ts.forEach(tags, checkSourceElement); + }); + } + var kind = node.kind; + if (cancellationToken) { + switch (kind) { + case 244: + case 240: + case 241: + case 239: + cancellationToken.throwIfCancellationRequested(); + } + } + switch (kind) { + case 150: + return checkTypeParameter(node); + case 151: + return checkParameter(node); + case 154: + case 153: + return checkPropertyDeclaration(node); + case 165: + case 166: + case 160: + case 161: + case 162: + return checkSignatureDeclaration(node); + case 156: + case 155: + return checkMethodDeclaration(node); + case 157: + return checkConstructorDeclaration(node); + case 158: + case 159: + return checkAccessorDeclaration(node); + case 164: + return checkTypeReferenceNode(node); + case 163: + return checkTypePredicate(node); + case 167: + return checkTypeQuery(node); + case 168: + return checkTypeLiteral(node); + case 169: + return checkArrayType(node); + case 170: + return checkTupleType(node); + case 173: + case 174: + return checkUnionOrIntersectionType(node); + case 177: + case 171: + case 172: + return checkSourceElement(node.type); + case 178: + return checkThisType(node); + case 179: + return checkTypeOperator(node); + case 175: + return checkConditionalType(node); + case 176: + return checkInferType(node); + case 183: + return checkImportType(node); + case 295: + return checkJSDocAugmentsTag(node); + case 304: + case 297: + return checkJSDocTypeAliasTag(node); + case 303: + return checkJSDocTemplateTag(node); + case 302: + return checkJSDocTypeTag(node); + case 299: + return checkJSDocParameterTag(node); + case 289: + checkJSDocFunctionType(node); + case 287: + case 286: + case 284: + case 285: + case 292: + checkJSDocTypeIsInJsFile(node); + ts.forEachChild(node, checkSourceElement); + return; + case 290: + checkJSDocVariadicType(node); + return; + case 283: + return checkSourceElement(node.type); + case 180: + return checkIndexedAccessType(node); + case 181: + return checkMappedType(node); + case 239: + return checkFunctionDeclaration(node); + case 218: + case 245: + return checkBlock(node); + case 219: + return checkVariableStatement(node); + case 221: + return checkExpressionStatement(node); + case 222: + return checkIfStatement(node); + case 223: + return checkDoStatement(node); + case 224: + return checkWhileStatement(node); + case 225: + return checkForStatement(node); + case 226: + return checkForInStatement(node); + case 227: + return checkForOfStatement(node); + case 228: + case 229: + return checkBreakOrContinueStatement(node); + case 230: + return checkReturnStatement(node); + case 231: + return checkWithStatement(node); + case 232: + return checkSwitchStatement(node); + case 233: + return checkLabeledStatement(node); + case 234: + return checkThrowStatement(node); + case 235: + return checkTryStatement(node); + case 237: + return checkVariableDeclaration(node); + case 186: + return checkBindingElement(node); + case 240: + return checkClassDeclaration(node); + case 241: + return checkInterfaceDeclaration(node); + case 242: + return checkTypeAliasDeclaration(node); + case 243: + return checkEnumDeclaration(node); + case 244: + return checkModuleDeclaration(node); + case 249: + return checkImportDeclaration(node); + case 248: + return checkImportEqualsDeclaration(node); + case 255: + return checkExportDeclaration(node); + case 254: + return checkExportAssignment(node); + case 220: + case 236: + checkGrammarStatementInAmbientContext(node); + return; + case 258: + return checkMissingDeclaration(node); + } + } + function checkJSDocTypeIsInJsFile(node) { + if (!ts.isInJSFile(node)) { + grammarErrorOnNode(node, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments); + } + } + function checkJSDocVariadicType(node) { + checkJSDocTypeIsInJsFile(node); + checkSourceElement(node.type); + var parent = node.parent; + if (ts.isParameter(parent) && ts.isJSDocFunctionType(parent.parent)) { + if (ts.last(parent.parent.parameters) !== parent) { + error(node, ts.Diagnostics.A_rest_parameter_must_be_last_in_a_parameter_list); + } + return; + } + if (!ts.isJSDocTypeExpression(parent)) { + error(node, ts.Diagnostics.JSDoc_may_only_appear_in_the_last_parameter_of_a_signature); + } + var paramTag = node.parent.parent; + if (!ts.isJSDocParameterTag(paramTag)) { + error(node, ts.Diagnostics.JSDoc_may_only_appear_in_the_last_parameter_of_a_signature); + return; + } + var param = ts.getParameterSymbolFromJSDoc(paramTag); + if (!param) { + return; + } + var host = ts.getHostSignatureFromJSDoc(paramTag); + if (!host || ts.last(host.parameters).symbol !== param) { + error(node, ts.Diagnostics.A_rest_parameter_must_be_last_in_a_parameter_list); + } + } + function getTypeFromJSDocVariadicType(node) { + var type = getTypeFromTypeNode(node.type); + var parent = node.parent; + var paramTag = node.parent.parent; + if (ts.isJSDocTypeExpression(node.parent) && ts.isJSDocParameterTag(paramTag)) { + var host_1 = ts.getHostSignatureFromJSDoc(paramTag); + if (host_1) { + var lastParamDeclaration = ts.lastOrUndefined(host_1.parameters); + var symbol = ts.getParameterSymbolFromJSDoc(paramTag); + if (!lastParamDeclaration || + symbol && lastParamDeclaration.symbol === symbol && ts.isRestParameter(lastParamDeclaration)) { + return createArrayType(type); + } + } + } + if (ts.isParameter(parent) && ts.isJSDocFunctionType(parent.parent)) { + return createArrayType(type); + } + return addOptionality(type); + } + function checkNodeDeferred(node) { + var enclosingFile = ts.getSourceFileOfNode(node); + var links = getNodeLinks(enclosingFile); + if (!(links.flags & 1)) { + links.deferredNodes = links.deferredNodes || ts.createMap(); + var id = "" + getNodeId(node); + links.deferredNodes.set(id, node); + } + } + function checkDeferredNodes(context) { + var links = getNodeLinks(context); + if (!links.deferredNodes) { + return; + } + links.deferredNodes.forEach(function (node) { + switch (node.kind) { + case 196: + case 197: + case 156: + case 155: + checkFunctionExpressionOrObjectLiteralMethodDeferred(node); + break; + case 158: + case 159: + checkAccessorDeclaration(node); + break; + case 209: + checkClassExpressionDeferred(node); + break; + case 261: + checkJsxSelfClosingElementDeferred(node); + break; + case 260: + checkJsxElementDeferred(node); + break; + } + }); + } + function checkSourceFile(node) { + ts.performance.mark("beforeCheck"); + checkSourceFileWorker(node); + ts.performance.mark("afterCheck"); + ts.performance.measure("Check", "beforeCheck", "afterCheck"); + } + function unusedIsError(kind) { + switch (kind) { + case 0: + return !!compilerOptions.noUnusedLocals; + case 1: + return !!compilerOptions.noUnusedParameters; + default: + return ts.Debug.assertNever(kind); + } + } + function getPotentiallyUnusedIdentifiers(sourceFile) { + return allPotentiallyUnusedIdentifiers.get(sourceFile.path) || ts.emptyArray; + } + function checkSourceFileWorker(node) { + var links = getNodeLinks(node); + if (!(links.flags & 1)) { + if (ts.skipTypeChecking(node, compilerOptions)) { + return; + } + checkGrammarSourceFile(node); + ts.clear(potentialThisCollisions); + ts.clear(potentialNewTargetCollisions); + ts.forEach(node.statements, checkSourceElement); + checkSourceElement(node.endOfFileToken); + checkDeferredNodes(node); + if (ts.isExternalOrCommonJsModule(node)) { + registerForUnusedIdentifiersCheck(node); + } + if (!node.isDeclarationFile && (compilerOptions.noUnusedLocals || compilerOptions.noUnusedParameters)) { + checkUnusedIdentifiers(getPotentiallyUnusedIdentifiers(node), function (containingNode, kind, diag) { + if (!ts.containsParseError(containingNode) && unusedIsError(kind)) { + diagnostics.add(diag); + } + }); + } + if (ts.isExternalOrCommonJsModule(node)) { + checkExternalModuleExports(node); + } + if (potentialThisCollisions.length) { + ts.forEach(potentialThisCollisions, checkIfThisIsCapturedInEnclosingScope); + ts.clear(potentialThisCollisions); + } + if (potentialNewTargetCollisions.length) { + ts.forEach(potentialNewTargetCollisions, checkIfNewTargetIsCapturedInEnclosingScope); + ts.clear(potentialNewTargetCollisions); + } + links.flags |= 1; + } + } + function getDiagnostics(sourceFile, ct) { + try { + cancellationToken = ct; + return getDiagnosticsWorker(sourceFile); + } + finally { + cancellationToken = undefined; + } + } + function getDiagnosticsWorker(sourceFile) { + throwIfNonDiagnosticsProducing(); + if (sourceFile) { + var previousGlobalDiagnostics = diagnostics.getGlobalDiagnostics(); + var previousGlobalDiagnosticsSize = previousGlobalDiagnostics.length; + checkSourceFile(sourceFile); + var semanticDiagnostics = diagnostics.getDiagnostics(sourceFile.fileName); + var currentGlobalDiagnostics = diagnostics.getGlobalDiagnostics(); + if (currentGlobalDiagnostics !== previousGlobalDiagnostics) { + var deferredGlobalDiagnostics = ts.relativeComplement(previousGlobalDiagnostics, currentGlobalDiagnostics, ts.compareDiagnostics); + return ts.concatenate(deferredGlobalDiagnostics, semanticDiagnostics); + } + else if (previousGlobalDiagnosticsSize === 0 && currentGlobalDiagnostics.length > 0) { + return ts.concatenate(currentGlobalDiagnostics, semanticDiagnostics); + } + return semanticDiagnostics; + } + ts.forEach(host.getSourceFiles(), checkSourceFile); + return diagnostics.getDiagnostics(); + } + function getGlobalDiagnostics() { + throwIfNonDiagnosticsProducing(); + return diagnostics.getGlobalDiagnostics(); + } + function throwIfNonDiagnosticsProducing() { + if (!produceDiagnostics) { + throw new Error("Trying to get diagnostics from a type checker that does not produce them."); + } + } + function getSymbolsInScope(location, meaning) { + if (location.flags & 8388608) { + return []; + } + var symbols = ts.createSymbolTable(); + var isStatic = false; + populateSymbols(); + symbols.delete("this"); + return symbolsToArray(symbols); + function populateSymbols() { + while (location) { + if (location.locals && !isGlobalSourceFile(location)) { + copySymbols(location.locals, meaning); + } + switch (location.kind) { + case 279: + if (!ts.isExternalOrCommonJsModule(location)) + break; + case 244: + copySymbols(getSymbolOfNode(location).exports, meaning & 2623475); + break; + case 243: + copySymbols(getSymbolOfNode(location).exports, meaning & 8); + break; + case 209: + var className = location.name; + if (className) { + copySymbol(location.symbol, meaning); + } + case 240: + case 241: + if (!isStatic) { + copySymbols(getMembersOfSymbol(getSymbolOfNode(location)), meaning & 67897832); + } + break; + case 196: + var funcName = location.name; + if (funcName) { + copySymbol(location.symbol, meaning); + } + break; + } + if (ts.introducesArgumentsExoticObject(location)) { + copySymbol(argumentsSymbol, meaning); + } + isStatic = ts.hasModifier(location, 32); + location = location.parent; + } + copySymbols(globals, meaning); + } + function copySymbol(symbol, meaning) { + if (ts.getCombinedLocalAndExportSymbolFlags(symbol) & meaning) { + var id = symbol.escapedName; + if (!symbols.has(id)) { + symbols.set(id, symbol); + } + } + } + function copySymbols(source, meaning) { + if (meaning) { + source.forEach(function (symbol) { + copySymbol(symbol, meaning); + }); + } + } + } + function isTypeDeclarationName(name) { + return name.kind === 72 && + isTypeDeclaration(name.parent) && + name.parent.name === name; + } + function isTypeDeclaration(node) { + switch (node.kind) { + case 150: + case 240: + case 241: + case 242: + case 243: + return true; + default: + return false; + } + } + function isTypeReferenceIdentifier(node) { + while (node.parent.kind === 148) { + node = node.parent; + } + return node.parent.kind === 164; + } + function isHeritageClauseElementIdentifier(node) { + while (node.parent.kind === 189) { + node = node.parent; + } + return node.parent.kind === 211; + } + function forEachEnclosingClass(node, callback) { + var result; + while (true) { + node = ts.getContainingClass(node); + if (!node) + break; + if (result = callback(node)) + break; + } + return result; + } + function isNodeUsedDuringClassInitialization(node) { + return !!ts.findAncestor(node, function (element) { + if (ts.isConstructorDeclaration(element) && ts.nodeIsPresent(element.body) || ts.isPropertyDeclaration(element)) { + return true; + } + else if (ts.isClassLike(element) || ts.isFunctionLikeDeclaration(element)) { + return "quit"; + } + return false; + }); + } + function isNodeWithinClass(node, classDeclaration) { + return !!forEachEnclosingClass(node, function (n) { return n === classDeclaration; }); + } + function getLeftSideOfImportEqualsOrExportAssignment(nodeOnRightSide) { + while (nodeOnRightSide.parent.kind === 148) { + nodeOnRightSide = nodeOnRightSide.parent; + } + if (nodeOnRightSide.parent.kind === 248) { + return nodeOnRightSide.parent.moduleReference === nodeOnRightSide ? nodeOnRightSide.parent : undefined; + } + if (nodeOnRightSide.parent.kind === 254) { + return nodeOnRightSide.parent.expression === nodeOnRightSide ? nodeOnRightSide.parent : undefined; + } + return undefined; + } + function isInRightSideOfImportOrExportAssignment(node) { + return getLeftSideOfImportEqualsOrExportAssignment(node) !== undefined; + } + function getSpecialPropertyAssignmentSymbolFromEntityName(entityName) { + var specialPropertyAssignmentKind = ts.getAssignmentDeclarationKind(entityName.parent.parent); + switch (specialPropertyAssignmentKind) { + case 1: + case 3: + return getSymbolOfNode(entityName.parent); + case 4: + case 2: + case 5: + return getSymbolOfNode(entityName.parent.parent); + } + } + function isImportTypeQualifierPart(node) { + var parent = node.parent; + while (ts.isQualifiedName(parent)) { + node = parent; + parent = parent.parent; + } + if (parent && parent.kind === 183 && parent.qualifier === node) { + return parent; + } + return undefined; + } + function getSymbolOfEntityNameOrPropertyAccessExpression(entityName) { + if (ts.isDeclarationName(entityName)) { + return getSymbolOfNode(entityName.parent); + } + if (ts.isInJSFile(entityName) && + entityName.parent.kind === 189 && + entityName.parent === entityName.parent.parent.left) { + var specialPropertyAssignmentSymbol = getSpecialPropertyAssignmentSymbolFromEntityName(entityName); + if (specialPropertyAssignmentSymbol) { + return specialPropertyAssignmentSymbol; + } + } + if (entityName.parent.kind === 254 && ts.isEntityNameExpression(entityName)) { + var success = resolveEntityName(entityName, 67220415 | 67897832 | 1920 | 2097152, true); + if (success && success !== unknownSymbol) { + return success; + } + } + else if (!ts.isPropertyAccessExpression(entityName) && isInRightSideOfImportOrExportAssignment(entityName)) { + var importEqualsDeclaration = ts.getAncestor(entityName, 248); + ts.Debug.assert(importEqualsDeclaration !== undefined); + return getSymbolOfPartOfRightHandSideOfImportEquals(entityName, true); + } + if (!ts.isPropertyAccessExpression(entityName)) { + var possibleImportNode = isImportTypeQualifierPart(entityName); + if (possibleImportNode) { + getTypeFromTypeNode(possibleImportNode); + var sym = getNodeLinks(entityName).resolvedSymbol; + return sym === unknownSymbol ? undefined : sym; + } + } + while (ts.isRightSideOfQualifiedNameOrPropertyAccess(entityName)) { + entityName = entityName.parent; + } + if (isHeritageClauseElementIdentifier(entityName)) { + var meaning = 0; + if (entityName.parent.kind === 211) { + meaning = 67897832; + if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent)) { + meaning |= 67220415; + } + } + else { + meaning = 1920; + } + meaning |= 2097152; + var entityNameSymbol = ts.isEntityNameExpression(entityName) ? resolveEntityName(entityName, meaning) : undefined; + if (entityNameSymbol) { + return entityNameSymbol; + } + } + if (entityName.parent.kind === 299) { + return ts.getParameterSymbolFromJSDoc(entityName.parent); + } + if (entityName.parent.kind === 150 && entityName.parent.parent.kind === 303) { + ts.Debug.assert(!ts.isInJSFile(entityName)); + var typeParameter = ts.getTypeParameterFromJsDoc(entityName.parent); + return typeParameter && typeParameter.symbol; + } + if (ts.isExpressionNode(entityName)) { + if (ts.nodeIsMissing(entityName)) { + return undefined; + } + if (entityName.kind === 72) { + if (ts.isJSXTagName(entityName) && isJsxIntrinsicIdentifier(entityName)) { + var symbol = getIntrinsicTagSymbol(entityName.parent); + return symbol === unknownSymbol ? undefined : symbol; + } + return resolveEntityName(entityName, 67220415, false, true); + } + else if (entityName.kind === 189 || entityName.kind === 148) { + var links = getNodeLinks(entityName); + if (links.resolvedSymbol) { + return links.resolvedSymbol; + } + if (entityName.kind === 189) { + checkPropertyAccessExpression(entityName); + } + else { + checkQualifiedName(entityName); + } + return links.resolvedSymbol; + } + } + else if (isTypeReferenceIdentifier(entityName)) { + var meaning = entityName.parent.kind === 164 ? 67897832 : 1920; + return resolveEntityName(entityName, meaning, false, true); + } + if (entityName.parent.kind === 163) { + return resolveEntityName(entityName, 1); + } + return undefined; + } + function getSymbolAtLocation(node) { + if (node.kind === 279) { + return ts.isExternalModule(node) ? getMergedSymbol(node.symbol) : undefined; + } + var parent = node.parent; + var grandParent = parent.parent; + if (node.flags & 8388608) { + return undefined; + } + if (isDeclarationNameOrImportPropertyName(node)) { + var parentSymbol = getSymbolOfNode(parent); + return ts.isImportOrExportSpecifier(node.parent) && node.parent.propertyName === node + ? getImmediateAliasedSymbol(parentSymbol) + : parentSymbol; + } + else if (ts.isLiteralComputedPropertyDeclarationName(node)) { + return getSymbolOfNode(parent.parent); + } + if (node.kind === 72) { + if (isInRightSideOfImportOrExportAssignment(node)) { + return getSymbolOfEntityNameOrPropertyAccessExpression(node); + } + else if (parent.kind === 186 && + grandParent.kind === 184 && + node === parent.propertyName) { + var typeOfPattern = getTypeOfNode(grandParent); + var propertyDeclaration = getPropertyOfType(typeOfPattern, node.escapedText); + if (propertyDeclaration) { + return propertyDeclaration; + } + } + } + switch (node.kind) { + case 72: + case 189: + case 148: + return getSymbolOfEntityNameOrPropertyAccessExpression(node); + case 100: + var container = ts.getThisContainer(node, false); + if (ts.isFunctionLike(container)) { + var sig = getSignatureFromDeclaration(container); + if (sig.thisParameter) { + return sig.thisParameter; + } + } + if (ts.isInExpressionContext(node)) { + return checkExpression(node).symbol; + } + case 178: + return getTypeFromThisTypeNode(node).symbol; + case 98: + return checkExpression(node).symbol; + case 124: + var constructorDeclaration = node.parent; + if (constructorDeclaration && constructorDeclaration.kind === 157) { + return constructorDeclaration.parent.symbol; + } + return undefined; + case 10: + case 14: + if ((ts.isExternalModuleImportEqualsDeclaration(node.parent.parent) && ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node) || + ((node.parent.kind === 249 || node.parent.kind === 255) && node.parent.moduleSpecifier === node) || + ((ts.isInJSFile(node) && ts.isRequireCall(node.parent, false)) || ts.isImportCall(node.parent)) || + (ts.isLiteralTypeNode(node.parent) && ts.isLiteralImportTypeNode(node.parent.parent) && node.parent.parent.argument === node.parent)) { + return resolveExternalModuleName(node, node); + } + if (ts.isCallExpression(parent) && ts.isBindableObjectDefinePropertyCall(parent) && parent.arguments[1] === node) { + return getSymbolOfNode(parent); + } + case 8: + var objectType = ts.isElementAccessExpression(parent) + ? parent.argumentExpression === node ? getTypeOfExpression(parent.expression) : undefined + : ts.isLiteralTypeNode(parent) && ts.isIndexedAccessTypeNode(grandParent) + ? getTypeFromTypeNode(grandParent.objectType) + : undefined; + return objectType && getPropertyOfType(objectType, ts.escapeLeadingUnderscores(node.text)); + case 80: + case 90: + case 37: + case 76: + return getSymbolOfNode(node.parent); + case 183: + return ts.isLiteralImportTypeNode(node) ? getSymbolAtLocation(node.argument.literal) : undefined; + case 85: + return ts.isExportAssignment(node.parent) ? ts.Debug.assertDefined(node.parent.symbol) : undefined; + default: + return undefined; + } + } + function getShorthandAssignmentValueSymbol(location) { + if (location && location.kind === 276) { + return resolveEntityName(location.name, 67220415 | 2097152); + } + return undefined; + } + function getExportSpecifierLocalTargetSymbol(node) { + return node.parent.parent.moduleSpecifier ? + getExternalModuleMember(node.parent.parent, node) : + resolveEntityName(node.propertyName || node.name, 67220415 | 67897832 | 1920 | 2097152); + } + function getTypeOfNode(node) { + if (node.flags & 8388608) { + return errorType; + } + var classDecl = ts.tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node); + var classType = classDecl && getDeclaredTypeOfClassOrInterface(getSymbolOfNode(classDecl.class)); + if (ts.isPartOfTypeNode(node)) { + var typeFromTypeNode = getTypeFromTypeNode(node); + return classType ? getTypeWithThisArgument(typeFromTypeNode, classType.thisType) : typeFromTypeNode; + } + if (ts.isExpressionNode(node)) { + return getRegularTypeOfExpression(node); + } + if (classType && !classDecl.isImplements) { + var baseType = ts.firstOrUndefined(getBaseTypes(classType)); + return baseType ? getTypeWithThisArgument(baseType, classType.thisType) : errorType; + } + if (isTypeDeclaration(node)) { + var symbol = getSymbolOfNode(node); + return getDeclaredTypeOfSymbol(symbol); + } + if (isTypeDeclarationName(node)) { + var symbol = getSymbolAtLocation(node); + return symbol ? getDeclaredTypeOfSymbol(symbol) : errorType; + } + if (ts.isDeclaration(node)) { + var symbol = getSymbolOfNode(node); + return getTypeOfSymbol(symbol); + } + if (isDeclarationNameOrImportPropertyName(node)) { + var symbol = getSymbolAtLocation(node); + return symbol ? getTypeOfSymbol(symbol) : errorType; + } + if (ts.isBindingPattern(node)) { + return getTypeForVariableLikeDeclaration(node.parent, true) || errorType; + } + if (isInRightSideOfImportOrExportAssignment(node)) { + var symbol = getSymbolAtLocation(node); + if (symbol) { + var declaredType = getDeclaredTypeOfSymbol(symbol); + return declaredType !== errorType ? declaredType : getTypeOfSymbol(symbol); + } + } + return errorType; + } + function getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr) { + ts.Debug.assert(expr.kind === 188 || expr.kind === 187); + if (expr.parent.kind === 227) { + var iteratedType = checkRightHandSideOfForOf(expr.parent.expression, expr.parent.awaitModifier); + return checkDestructuringAssignment(expr, iteratedType || errorType); + } + if (expr.parent.kind === 204) { + var iteratedType = getTypeOfExpression(expr.parent.right); + return checkDestructuringAssignment(expr, iteratedType || errorType); + } + if (expr.parent.kind === 275) { + var typeOfParentObjectLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr.parent.parent); + return checkObjectLiteralDestructuringPropertyAssignment(typeOfParentObjectLiteral || errorType, expr.parent); + } + ts.Debug.assert(expr.parent.kind === 187); + var typeOfArrayLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr.parent); + var elementType = checkIteratedTypeOrElementType(typeOfArrayLiteral || errorType, expr.parent, false, false) || errorType; + return checkArrayLiteralDestructuringElementAssignment(expr.parent, typeOfArrayLiteral, expr.parent.elements.indexOf(expr), elementType || errorType); + } + function getPropertySymbolOfDestructuringAssignment(location) { + var typeOfObjectLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(location.parent.parent); + return typeOfObjectLiteral && getPropertyOfType(typeOfObjectLiteral, location.escapedText); + } + function getRegularTypeOfExpression(expr) { + if (ts.isRightSideOfQualifiedNameOrPropertyAccess(expr)) { + expr = expr.parent; + } + return getRegularTypeOfLiteralType(getTypeOfExpression(expr)); + } + function getParentTypeOfClassElement(node) { + var classSymbol = getSymbolOfNode(node.parent); + return ts.hasModifier(node, 32) + ? getTypeOfSymbol(classSymbol) + : getDeclaredTypeOfSymbol(classSymbol); + } + function getClassElementPropertyKeyType(element) { + var name = element.name; + switch (name.kind) { + case 72: + return getLiteralType(ts.idText(name)); + case 8: + case 10: + return getLiteralType(name.text); + case 149: + var nameType = checkComputedPropertyName(name); + return isTypeAssignableToKind(nameType, 12288) ? nameType : stringType; + default: + ts.Debug.fail("Unsupported property name."); + return errorType; + } + } + function getAugmentedPropertiesOfType(type) { + type = getApparentType(type); + var propsByName = ts.createSymbolTable(getPropertiesOfType(type)); + var functionType = getSignaturesOfType(type, 0).length ? globalCallableFunctionType : + getSignaturesOfType(type, 1).length ? globalNewableFunctionType : + undefined; + if (functionType) { + ts.forEach(getPropertiesOfType(functionType), function (p) { + if (!propsByName.has(p.escapedName)) { + propsByName.set(p.escapedName, p); + } + }); + } + return getNamedMembers(propsByName); + } + function typeHasCallOrConstructSignatures(type) { + return ts.typeHasCallOrConstructSignatures(type, checker); + } + function getRootSymbols(symbol) { + var roots = getImmediateRootSymbols(symbol); + return roots ? ts.flatMap(roots, getRootSymbols) : [symbol]; + } + function getImmediateRootSymbols(symbol) { + if (ts.getCheckFlags(symbol) & 6) { + return ts.mapDefined(getSymbolLinks(symbol).containingType.types, function (type) { return getPropertyOfType(type, symbol.escapedName); }); + } + else if (symbol.flags & 33554432) { + var _a = symbol, leftSpread = _a.leftSpread, rightSpread = _a.rightSpread, syntheticOrigin = _a.syntheticOrigin; + return leftSpread ? [leftSpread, rightSpread] + : syntheticOrigin ? [syntheticOrigin] + : ts.singleElementArray(tryGetAliasTarget(symbol)); + } + return undefined; + } + function tryGetAliasTarget(symbol) { + var target; + var next = symbol; + while (next = getSymbolLinks(next).target) { + target = next; + } + return target; + } + function isArgumentsLocalBinding(nodeIn) { + if (!ts.isGeneratedIdentifier(nodeIn)) { + var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier); + if (node) { + var isPropertyName_1 = node.parent.kind === 189 && node.parent.name === node; + return !isPropertyName_1 && getReferencedValueSymbol(node) === argumentsSymbol; + } + } + return false; + } + function moduleExportsSomeValue(moduleReferenceExpression) { + var moduleSymbol = resolveExternalModuleName(moduleReferenceExpression.parent, moduleReferenceExpression); + if (!moduleSymbol || ts.isShorthandAmbientModuleSymbol(moduleSymbol)) { + return true; + } + var hasExportAssignment = hasExportAssignmentSymbol(moduleSymbol); + moduleSymbol = resolveExternalModuleSymbol(moduleSymbol); + var symbolLinks = getSymbolLinks(moduleSymbol); + if (symbolLinks.exportsSomeValue === undefined) { + symbolLinks.exportsSomeValue = hasExportAssignment + ? !!(moduleSymbol.flags & 67220415) + : ts.forEachEntry(getExportsOfModule(moduleSymbol), isValue); + } + return symbolLinks.exportsSomeValue; + function isValue(s) { + s = resolveSymbol(s); + return s && !!(s.flags & 67220415); + } + } + function isNameOfModuleOrEnumDeclaration(node) { + return ts.isModuleOrEnumDeclaration(node.parent) && node === node.parent.name; + } + function getReferencedExportContainer(nodeIn, prefixLocals) { + var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier); + if (node) { + var symbol = getReferencedValueSymbol(node, isNameOfModuleOrEnumDeclaration(node)); + if (symbol) { + if (symbol.flags & 1048576) { + var exportSymbol = getMergedSymbol(symbol.exportSymbol); + if (!prefixLocals && exportSymbol.flags & 944 && !(exportSymbol.flags & 3)) { + return undefined; + } + symbol = exportSymbol; + } + var parentSymbol_1 = getParentOfSymbol(symbol); + if (parentSymbol_1) { + if (parentSymbol_1.flags & 512 && parentSymbol_1.valueDeclaration.kind === 279) { + var symbolFile = parentSymbol_1.valueDeclaration; + var referenceFile = ts.getSourceFileOfNode(node); + var symbolIsUmdExport = symbolFile !== referenceFile; + return symbolIsUmdExport ? undefined : symbolFile; + } + return ts.findAncestor(node.parent, function (n) { return ts.isModuleOrEnumDeclaration(n) && getSymbolOfNode(n) === parentSymbol_1; }); + } + } + } + } + function getReferencedImportDeclaration(nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier); + if (node) { + var symbol = getReferencedValueSymbol(node); + if (isNonLocalAlias(symbol, 67220415)) { + return getDeclarationOfAliasSymbol(symbol); + } + } + return undefined; + } + function isSymbolOfDeclarationWithCollidingName(symbol) { + if (symbol.flags & 418) { + var links = getSymbolLinks(symbol); + if (links.isDeclarationWithCollidingName === undefined) { + var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); + if (ts.isStatementWithLocals(container)) { + var nodeLinks_1 = getNodeLinks(symbol.valueDeclaration); + if (resolveName(container.parent, symbol.escapedName, 67220415, undefined, undefined, false)) { + links.isDeclarationWithCollidingName = true; + } + else if (nodeLinks_1.flags & 262144) { + var isDeclaredInLoop = nodeLinks_1.flags & 524288; + var inLoopInitializer = ts.isIterationStatement(container, false); + var inLoopBodyBlock = container.kind === 218 && ts.isIterationStatement(container.parent, false); + links.isDeclarationWithCollidingName = !ts.isBlockScopedContainerTopLevel(container) && (!isDeclaredInLoop || (!inLoopInitializer && !inLoopBodyBlock)); + } + else { + links.isDeclarationWithCollidingName = false; + } + } + } + return links.isDeclarationWithCollidingName; + } + return false; + } + function getReferencedDeclarationWithCollidingName(nodeIn) { + if (!ts.isGeneratedIdentifier(nodeIn)) { + var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier); + if (node) { + var symbol = getReferencedValueSymbol(node); + if (symbol && isSymbolOfDeclarationWithCollidingName(symbol)) { + return symbol.valueDeclaration; + } + } + } + return undefined; + } + function isDeclarationWithCollidingName(nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isDeclaration); + if (node) { + var symbol = getSymbolOfNode(node); + if (symbol) { + return isSymbolOfDeclarationWithCollidingName(symbol); + } + } + return false; + } + function isValueAliasDeclaration(node) { + switch (node.kind) { + case 248: + case 250: + case 251: + case 253: + case 257: + return isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol); + case 255: + var exportClause = node.exportClause; + return !!exportClause && ts.some(exportClause.elements, isValueAliasDeclaration); + case 254: + return node.expression + && node.expression.kind === 72 + ? isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol) + : true; + } + return false; + } + function isTopLevelValueImportEqualsWithEntityName(nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isImportEqualsDeclaration); + if (node === undefined || node.parent.kind !== 279 || !ts.isInternalModuleImportEqualsDeclaration(node)) { + return false; + } + var isValue = isAliasResolvedToValue(getSymbolOfNode(node)); + return isValue && node.moduleReference && !ts.nodeIsMissing(node.moduleReference); + } + function isAliasResolvedToValue(symbol) { + var target = resolveAlias(symbol); + if (target === unknownSymbol) { + return true; + } + return !!(target.flags & 67220415) && + (compilerOptions.preserveConstEnums || !isConstEnumOrConstEnumOnlyModule(target)); + } + function isConstEnumOrConstEnumOnlyModule(s) { + return isConstEnumSymbol(s) || !!s.constEnumOnlyModule; + } + function isReferencedAliasDeclaration(node, checkChildren) { + if (ts.isAliasSymbolDeclaration(node)) { + var symbol = getSymbolOfNode(node); + if (symbol && getSymbolLinks(symbol).referenced) { + return true; + } + var target = getSymbolLinks(symbol).target; + if (target && ts.getModifierFlags(node) & 1 && + target.flags & 67220415 && (compilerOptions.preserveConstEnums || !isConstEnumOrConstEnumOnlyModule(target))) { + return true; + } + } + if (checkChildren) { + return !!ts.forEachChild(node, function (node) { return isReferencedAliasDeclaration(node, checkChildren); }); + } + return false; + } + function isImplementationOfOverload(node) { + if (ts.nodeIsPresent(node.body)) { + if (ts.isGetAccessor(node) || ts.isSetAccessor(node)) + return false; + var symbol = getSymbolOfNode(node); + var signaturesOfSymbol = getSignaturesOfSymbol(symbol); + return signaturesOfSymbol.length > 1 || + (signaturesOfSymbol.length === 1 && signaturesOfSymbol[0].declaration !== node); + } + return false; + } + function isRequiredInitializedParameter(parameter) { + return !!strictNullChecks && + !isOptionalParameter(parameter) && + !ts.isJSDocParameterTag(parameter) && + !!parameter.initializer && + !ts.hasModifier(parameter, 92); + } + function isOptionalUninitializedParameterProperty(parameter) { + return strictNullChecks && + isOptionalParameter(parameter) && + !parameter.initializer && + ts.hasModifier(parameter, 92); + } + function isExpandoFunctionDeclaration(node) { + var declaration = ts.getParseTreeNode(node, ts.isFunctionDeclaration); + if (!declaration) { + return false; + } + var symbol = getSymbolOfNode(declaration); + if (!symbol || !(symbol.flags & 16)) { + return false; + } + return !!ts.forEachEntry(getExportsOfSymbol(symbol), function (p) { return p.flags & 67220415 && ts.isPropertyAccessExpression(p.valueDeclaration); }); + } + function getPropertiesOfContainerFunction(node) { + var declaration = ts.getParseTreeNode(node, ts.isFunctionDeclaration); + if (!declaration) { + return ts.emptyArray; + } + var symbol = getSymbolOfNode(declaration); + return symbol && getPropertiesOfType(getTypeOfSymbol(symbol)) || ts.emptyArray; + } + function getNodeCheckFlags(node) { + return getNodeLinks(node).flags || 0; + } + function getEnumMemberValue(node) { + computeEnumMemberValues(node.parent); + return getNodeLinks(node).enumMemberValue; + } + function canHaveConstantValue(node) { + switch (node.kind) { + case 278: + case 189: + case 190: + return true; + } + return false; + } + function getConstantValue(node) { + if (node.kind === 278) { + return getEnumMemberValue(node); + } + var symbol = getNodeLinks(node).resolvedSymbol; + if (symbol && (symbol.flags & 8)) { + var member = symbol.valueDeclaration; + if (ts.isEnumConst(member.parent)) { + return getEnumMemberValue(member); + } + } + return undefined; + } + function isFunctionType(type) { + return !!(type.flags & 524288) && getSignaturesOfType(type, 0).length > 0; + } + function getTypeReferenceSerializationKind(typeNameIn, location) { + var typeName = ts.getParseTreeNode(typeNameIn, ts.isEntityName); + if (!typeName) + return ts.TypeReferenceSerializationKind.Unknown; + if (location) { + location = ts.getParseTreeNode(location); + if (!location) + return ts.TypeReferenceSerializationKind.Unknown; + } + var valueSymbol = resolveEntityName(typeName, 67220415, true, false, location); + var typeSymbol = resolveEntityName(typeName, 67897832, true, false, location); + if (valueSymbol && valueSymbol === typeSymbol) { + var globalPromiseSymbol = getGlobalPromiseConstructorSymbol(false); + if (globalPromiseSymbol && valueSymbol === globalPromiseSymbol) { + return ts.TypeReferenceSerializationKind.Promise; + } + var constructorType = getTypeOfSymbol(valueSymbol); + if (constructorType && isConstructorType(constructorType)) { + return ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue; + } + } + if (!typeSymbol) { + return ts.TypeReferenceSerializationKind.Unknown; + } + var type = getDeclaredTypeOfSymbol(typeSymbol); + if (type === errorType) { + return ts.TypeReferenceSerializationKind.Unknown; + } + else if (type.flags & 3) { + return ts.TypeReferenceSerializationKind.ObjectType; + } + else if (isTypeAssignableToKind(type, 16384 | 98304 | 131072)) { + return ts.TypeReferenceSerializationKind.VoidNullableOrNeverType; + } + else if (isTypeAssignableToKind(type, 528)) { + return ts.TypeReferenceSerializationKind.BooleanType; + } + else if (isTypeAssignableToKind(type, 296)) { + return ts.TypeReferenceSerializationKind.NumberLikeType; + } + else if (isTypeAssignableToKind(type, 2112)) { + return ts.TypeReferenceSerializationKind.BigIntLikeType; + } + else if (isTypeAssignableToKind(type, 132)) { + return ts.TypeReferenceSerializationKind.StringLikeType; + } + else if (isTupleType(type)) { + return ts.TypeReferenceSerializationKind.ArrayLikeType; + } + else if (isTypeAssignableToKind(type, 12288)) { + return ts.TypeReferenceSerializationKind.ESSymbolType; + } + else if (isFunctionType(type)) { + return ts.TypeReferenceSerializationKind.TypeWithCallSignature; + } + else if (isArrayType(type)) { + return ts.TypeReferenceSerializationKind.ArrayLikeType; + } + else { + return ts.TypeReferenceSerializationKind.ObjectType; + } + } + function createTypeOfDeclaration(declarationIn, enclosingDeclaration, flags, tracker, addUndefined) { + var declaration = ts.getParseTreeNode(declarationIn, ts.isVariableLikeOrAccessor); + if (!declaration) { + return ts.createToken(120); + } + var symbol = getSymbolOfNode(declaration); + var type = symbol && !(symbol.flags & (2048 | 131072)) + ? getWidenedLiteralType(getTypeOfSymbol(symbol)) + : errorType; + if (type.flags & 8192 && + type.symbol === symbol) { + flags |= 1048576; + } + if (addUndefined) { + type = getOptionalType(type); + } + return nodeBuilder.typeToTypeNode(type, enclosingDeclaration, flags | 1024, tracker); + } + function createReturnTypeOfSignatureDeclaration(signatureDeclarationIn, enclosingDeclaration, flags, tracker) { + var signatureDeclaration = ts.getParseTreeNode(signatureDeclarationIn, ts.isFunctionLike); + if (!signatureDeclaration) { + return ts.createToken(120); + } + var signature = getSignatureFromDeclaration(signatureDeclaration); + return nodeBuilder.typeToTypeNode(getReturnTypeOfSignature(signature), enclosingDeclaration, flags | 1024, tracker); + } + function createTypeOfExpression(exprIn, enclosingDeclaration, flags, tracker) { + var expr = ts.getParseTreeNode(exprIn, ts.isExpression); + if (!expr) { + return ts.createToken(120); + } + var type = getWidenedType(getRegularTypeOfExpression(expr)); + return nodeBuilder.typeToTypeNode(type, enclosingDeclaration, flags | 1024, tracker); + } + function hasGlobalName(name) { + return globals.has(ts.escapeLeadingUnderscores(name)); + } + function getReferencedValueSymbol(reference, startInDeclarationContainer) { + var resolvedSymbol = getNodeLinks(reference).resolvedSymbol; + if (resolvedSymbol) { + return resolvedSymbol; + } + var location = reference; + if (startInDeclarationContainer) { + var parent = reference.parent; + if (ts.isDeclaration(parent) && reference === parent.name) { + location = getDeclarationContainer(parent); + } + } + return resolveName(location, reference.escapedText, 67220415 | 1048576 | 2097152, undefined, undefined, true); + } + function getReferencedValueDeclaration(referenceIn) { + if (!ts.isGeneratedIdentifier(referenceIn)) { + var reference = ts.getParseTreeNode(referenceIn, ts.isIdentifier); + if (reference) { + var symbol = getReferencedValueSymbol(reference); + if (symbol) { + return getExportSymbolOfValueSymbolIfExported(symbol).valueDeclaration; + } + } + } + return undefined; + } + function isLiteralConstDeclaration(node) { + if (ts.isDeclarationReadonly(node) || ts.isVariableDeclaration(node) && ts.isVarConst(node)) { + return isFreshLiteralType(getTypeOfSymbol(getSymbolOfNode(node))); + } + return false; + } + function literalTypeToNode(type, enclosing, tracker) { + var enumResult = type.flags & 1024 ? nodeBuilder.symbolToExpression(type.symbol, 67220415, enclosing, undefined, tracker) + : type === trueType ? ts.createTrue() : type === falseType && ts.createFalse(); + return enumResult || ts.createLiteral(type.value); + } + function createLiteralConstValue(node, tracker) { + var type = getTypeOfSymbol(getSymbolOfNode(node)); + return literalTypeToNode(type, node, tracker); + } + function createResolver() { + var resolvedTypeReferenceDirectives = host.getResolvedTypeReferenceDirectives(); + var fileToDirective; + if (resolvedTypeReferenceDirectives) { + fileToDirective = ts.createMap(); + resolvedTypeReferenceDirectives.forEach(function (resolvedDirective, key) { + if (!resolvedDirective || !resolvedDirective.resolvedFileName) { + return; + } + var file = host.getSourceFile(resolvedDirective.resolvedFileName); + fileToDirective.set(file.path, key); + }); + } + return { + getReferencedExportContainer: getReferencedExportContainer, + getReferencedImportDeclaration: getReferencedImportDeclaration, + getReferencedDeclarationWithCollidingName: getReferencedDeclarationWithCollidingName, + isDeclarationWithCollidingName: isDeclarationWithCollidingName, + isValueAliasDeclaration: function (node) { + node = ts.getParseTreeNode(node); + return node ? isValueAliasDeclaration(node) : true; + }, + hasGlobalName: hasGlobalName, + isReferencedAliasDeclaration: function (node, checkChildren) { + node = ts.getParseTreeNode(node); + return node ? isReferencedAliasDeclaration(node, checkChildren) : true; + }, + getNodeCheckFlags: function (node) { + node = ts.getParseTreeNode(node); + return node ? getNodeCheckFlags(node) : 0; + }, + isTopLevelValueImportEqualsWithEntityName: isTopLevelValueImportEqualsWithEntityName, + isDeclarationVisible: isDeclarationVisible, + isImplementationOfOverload: isImplementationOfOverload, + isRequiredInitializedParameter: isRequiredInitializedParameter, + isOptionalUninitializedParameterProperty: isOptionalUninitializedParameterProperty, + isExpandoFunctionDeclaration: isExpandoFunctionDeclaration, + getPropertiesOfContainerFunction: getPropertiesOfContainerFunction, + createTypeOfDeclaration: createTypeOfDeclaration, + createReturnTypeOfSignatureDeclaration: createReturnTypeOfSignatureDeclaration, + createTypeOfExpression: createTypeOfExpression, + createLiteralConstValue: createLiteralConstValue, + isSymbolAccessible: isSymbolAccessible, + isEntityNameVisible: isEntityNameVisible, + getConstantValue: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, canHaveConstantValue); + return node ? getConstantValue(node) : undefined; + }, + collectLinkedAliases: collectLinkedAliases, + getReferencedValueDeclaration: getReferencedValueDeclaration, + getTypeReferenceSerializationKind: getTypeReferenceSerializationKind, + isOptionalParameter: isOptionalParameter, + moduleExportsSomeValue: moduleExportsSomeValue, + isArgumentsLocalBinding: isArgumentsLocalBinding, + getExternalModuleFileFromDeclaration: getExternalModuleFileFromDeclaration, + getTypeReferenceDirectivesForEntityName: getTypeReferenceDirectivesForEntityName, + getTypeReferenceDirectivesForSymbol: getTypeReferenceDirectivesForSymbol, + isLiteralConstDeclaration: isLiteralConstDeclaration, + isLateBound: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isDeclaration); + var symbol = node && getSymbolOfNode(node); + return !!(symbol && ts.getCheckFlags(symbol) & 1024); + }, + getJsxFactoryEntity: function (location) { return location ? (getJsxNamespace(location), (ts.getSourceFileOfNode(location).localJsxFactory || _jsxFactoryEntity)) : _jsxFactoryEntity; }, + getAllAccessorDeclarations: function (accessor) { + accessor = ts.getParseTreeNode(accessor, ts.isGetOrSetAccessorDeclaration); + var otherKind = accessor.kind === 159 ? 158 : 159; + var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(accessor), otherKind); + var firstAccessor = otherAccessor && (otherAccessor.pos < accessor.pos) ? otherAccessor : accessor; + var secondAccessor = otherAccessor && (otherAccessor.pos < accessor.pos) ? accessor : otherAccessor; + var setAccessor = accessor.kind === 159 ? accessor : otherAccessor; + var getAccessor = accessor.kind === 158 ? accessor : otherAccessor; + return { + firstAccessor: firstAccessor, + secondAccessor: secondAccessor, + setAccessor: setAccessor, + getAccessor: getAccessor + }; + }, + getSymbolOfExternalModuleSpecifier: function (moduleName) { return resolveExternalModuleNameWorker(moduleName, moduleName, undefined); }, + isBindingCapturedByNode: function (node, decl) { + var parseNode = ts.getParseTreeNode(node); + var parseDecl = ts.getParseTreeNode(decl); + return !!parseNode && !!parseDecl && (ts.isVariableDeclaration(parseDecl) || ts.isBindingElement(parseDecl)) && isBindingCapturedByNode(parseNode, parseDecl); + } + }; + function isInHeritageClause(node) { + return node.parent && node.parent.kind === 211 && node.parent.parent && node.parent.parent.kind === 273; + } + function getTypeReferenceDirectivesForEntityName(node) { + if (!fileToDirective) { + return undefined; + } + var meaning = 67897832 | 1920; + if ((node.kind === 72 && isInTypeQuery(node)) || (node.kind === 189 && !isInHeritageClause(node))) { + meaning = 67220415 | 1048576; + } + var symbol = resolveEntityName(node, meaning, true); + return symbol && symbol !== unknownSymbol ? getTypeReferenceDirectivesForSymbol(symbol, meaning) : undefined; + } + function getTypeReferenceDirectivesForSymbol(symbol, meaning) { + if (!fileToDirective) { + return undefined; + } + if (!isSymbolFromTypeDeclarationFile(symbol)) { + return undefined; + } + var typeReferenceDirectives; + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + if (decl.symbol && decl.symbol.flags & meaning) { + var file = ts.getSourceFileOfNode(decl); + var typeReferenceDirective = fileToDirective.get(file.path); + if (typeReferenceDirective) { + (typeReferenceDirectives || (typeReferenceDirectives = [])).push(typeReferenceDirective); + } + else { + return undefined; + } + } + } + return typeReferenceDirectives; + } + function isSymbolFromTypeDeclarationFile(symbol) { + if (!symbol.declarations) { + return false; + } + var current = symbol; + while (true) { + var parent = getParentOfSymbol(current); + if (parent) { + current = parent; + } + else { + break; + } + } + if (current.valueDeclaration && current.valueDeclaration.kind === 279 && current.flags & 512) { + return false; + } + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + var file = ts.getSourceFileOfNode(decl); + if (fileToDirective.has(file.path)) { + return true; + } + } + return false; + } + } + function getExternalModuleFileFromDeclaration(declaration) { + var specifier = declaration.kind === 244 ? ts.tryCast(declaration.name, ts.isStringLiteral) : ts.getExternalModuleName(declaration); + var moduleSymbol = resolveExternalModuleNameWorker(specifier, specifier, undefined); + if (!moduleSymbol) { + return undefined; + } + return ts.getDeclarationOfKind(moduleSymbol, 279); + } + function initializeTypeChecker() { + for (var _i = 0, _a = host.getSourceFiles(); _i < _a.length; _i++) { + var file = _a[_i]; + ts.bindSourceFile(file, compilerOptions); + } + amalgamatedDuplicates = ts.createMap(); + var augmentations; + for (var _b = 0, _c = host.getSourceFiles(); _b < _c.length; _b++) { + var file = _c[_b]; + if (file.redirectInfo) { + continue; + } + if (!ts.isExternalOrCommonJsModule(file)) { + mergeSymbolTable(globals, file.locals); + } + if (file.jsGlobalAugmentations) { + mergeSymbolTable(globals, file.jsGlobalAugmentations); + } + if (file.patternAmbientModules && file.patternAmbientModules.length) { + patternAmbientModules = ts.concatenate(patternAmbientModules, file.patternAmbientModules); + } + if (file.moduleAugmentations.length) { + (augmentations || (augmentations = [])).push(file.moduleAugmentations); + } + if (file.symbol && file.symbol.globalExports) { + var source = file.symbol.globalExports; + source.forEach(function (sourceSymbol, id) { + if (!globals.has(id)) { + globals.set(id, sourceSymbol); + } + }); + } + } + if (augmentations) { + for (var _d = 0, augmentations_1 = augmentations; _d < augmentations_1.length; _d++) { + var list = augmentations_1[_d]; + for (var _e = 0, list_1 = list; _e < list_1.length; _e++) { + var augmentation = list_1[_e]; + if (!ts.isGlobalScopeAugmentation(augmentation.parent)) + continue; + mergeModuleAugmentation(augmentation); + } + } + } + addToSymbolTable(globals, builtinGlobals, ts.Diagnostics.Declaration_name_conflicts_with_built_in_global_identifier_0); + getSymbolLinks(undefinedSymbol).type = undefinedWideningType; + getSymbolLinks(argumentsSymbol).type = getGlobalType("IArguments", 0, true); + getSymbolLinks(unknownSymbol).type = errorType; + globalArrayType = getGlobalType("Array", 1, true); + globalObjectType = getGlobalType("Object", 0, true); + globalFunctionType = getGlobalType("Function", 0, true); + globalCallableFunctionType = strictBindCallApply && getGlobalType("CallableFunction", 0, true) || globalFunctionType; + globalNewableFunctionType = strictBindCallApply && getGlobalType("NewableFunction", 0, true) || globalFunctionType; + globalStringType = getGlobalType("String", 0, true); + globalNumberType = getGlobalType("Number", 0, true); + globalBooleanType = getGlobalType("Boolean", 0, true); + globalRegExpType = getGlobalType("RegExp", 0, true); + anyArrayType = createArrayType(anyType); + autoArrayType = createArrayType(autoType); + if (autoArrayType === emptyObjectType) { + autoArrayType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + } + globalReadonlyArrayType = getGlobalTypeOrUndefined("ReadonlyArray", 1); + anyReadonlyArrayType = globalReadonlyArrayType ? createTypeFromGenericGlobalType(globalReadonlyArrayType, [anyType]) : anyArrayType; + globalThisType = getGlobalTypeOrUndefined("ThisType", 1); + if (augmentations) { + for (var _f = 0, augmentations_2 = augmentations; _f < augmentations_2.length; _f++) { + var list = augmentations_2[_f]; + for (var _g = 0, list_2 = list; _g < list_2.length; _g++) { + var augmentation = list_2[_g]; + if (ts.isGlobalScopeAugmentation(augmentation.parent)) + continue; + mergeModuleAugmentation(augmentation); + } + } + } + amalgamatedDuplicates.forEach(function (_a) { + var firstFile = _a.firstFile, secondFile = _a.secondFile, conflictingSymbols = _a.conflictingSymbols; + if (conflictingSymbols.size < 8) { + conflictingSymbols.forEach(function (_a, symbolName) { + var isBlockScoped = _a.isBlockScoped, firstFileLocations = _a.firstFileLocations, secondFileLocations = _a.secondFileLocations; + var message = isBlockScoped ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 : ts.Diagnostics.Duplicate_identifier_0; + for (var _i = 0, firstFileLocations_1 = firstFileLocations; _i < firstFileLocations_1.length; _i++) { + var node = firstFileLocations_1[_i]; + addDuplicateDeclarationError(node, message, symbolName, secondFileLocations); + } + for (var _b = 0, secondFileLocations_1 = secondFileLocations; _b < secondFileLocations_1.length; _b++) { + var node = secondFileLocations_1[_b]; + addDuplicateDeclarationError(node, message, symbolName, firstFileLocations); + } + }); + } + else { + var list = ts.arrayFrom(conflictingSymbols.keys()).join(", "); + diagnostics.add(addRelatedInfo(ts.createDiagnosticForNode(firstFile, ts.Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list), ts.createDiagnosticForNode(secondFile, ts.Diagnostics.Conflicts_are_in_this_file))); + diagnostics.add(addRelatedInfo(ts.createDiagnosticForNode(secondFile, ts.Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list), ts.createDiagnosticForNode(firstFile, ts.Diagnostics.Conflicts_are_in_this_file))); + } + }); + amalgamatedDuplicates = undefined; + } + function checkExternalEmitHelpers(location, helpers) { + if ((requestedExternalEmitHelpers & helpers) !== helpers && compilerOptions.importHelpers) { + var sourceFile = ts.getSourceFileOfNode(location); + if (ts.isEffectiveExternalModule(sourceFile, compilerOptions) && !(location.flags & 4194304)) { + var helpersModule = resolveHelpersModule(sourceFile, location); + if (helpersModule !== unknownSymbol) { + var uncheckedHelpers = helpers & ~requestedExternalEmitHelpers; + for (var helper = 1; helper <= 65536; helper <<= 1) { + if (uncheckedHelpers & helper) { + var name = getHelperName(helper); + var symbol = getSymbol(helpersModule.exports, ts.escapeLeadingUnderscores(name), 67220415); + if (!symbol) { + error(location, ts.Diagnostics.This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1, ts.externalHelpersModuleNameText, name); + } + } + } + } + requestedExternalEmitHelpers |= helpers; + } + } + } + function getHelperName(helper) { + switch (helper) { + case 1: return "__extends"; + case 2: return "__assign"; + case 4: return "__rest"; + case 8: return "__decorate"; + case 16: return "__metadata"; + case 32: return "__param"; + case 64: return "__awaiter"; + case 128: return "__generator"; + case 256: return "__values"; + case 512: return "__read"; + case 1024: return "__spread"; + case 2048: return "__await"; + case 4096: return "__asyncGenerator"; + case 8192: return "__asyncDelegator"; + case 16384: return "__asyncValues"; + case 32768: return "__exportStar"; + case 65536: return "__makeTemplateObject"; + default: return ts.Debug.fail("Unrecognized helper"); + } + } + function resolveHelpersModule(node, errorNode) { + if (!externalHelpersModule) { + externalHelpersModule = resolveExternalModule(node, ts.externalHelpersModuleNameText, ts.Diagnostics.This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found, errorNode) || unknownSymbol; + } + return externalHelpersModule; + } + function checkGrammarDecoratorsAndModifiers(node) { + return checkGrammarDecorators(node) || checkGrammarModifiers(node); + } + function checkGrammarDecorators(node) { + if (!node.decorators) { + return false; + } + if (!ts.nodeCanBeDecorated(node, node.parent, node.parent.parent)) { + if (node.kind === 156 && !ts.nodeIsPresent(node.body)) { + return grammarErrorOnFirstToken(node, ts.Diagnostics.A_decorator_can_only_decorate_a_method_implementation_not_an_overload); + } + else { + return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_are_not_valid_here); + } + } + else if (node.kind === 158 || node.kind === 159) { + var accessors = ts.getAllAccessorDeclarations(node.parent.members, node); + if (accessors.firstAccessor.decorators && node === accessors.secondAccessor) { + return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name); + } + } + return false; + } + function checkGrammarModifiers(node) { + var quickResult = reportObviousModifierErrors(node); + if (quickResult !== undefined) { + return quickResult; + } + var lastStatic, lastDeclare, lastAsync, lastReadonly; + var flags = 0; + for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) { + var modifier = _a[_i]; + if (modifier.kind !== 133) { + if (node.kind === 153 || node.kind === 155) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_type_member, ts.tokenToString(modifier.kind)); + } + if (node.kind === 162) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_an_index_signature, ts.tokenToString(modifier.kind)); + } + } + switch (modifier.kind) { + case 77: + if (node.kind !== 243) { + return grammarErrorOnNode(node, ts.Diagnostics.A_class_member_cannot_have_the_0_keyword, ts.tokenToString(77)); + } + break; + case 115: + case 114: + case 113: + var text = visibilityToString(ts.modifierToFlag(modifier.kind)); + if (flags & 28) { + return grammarErrorOnNode(modifier, ts.Diagnostics.Accessibility_modifier_already_seen); + } + else if (flags & 32) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "static"); + } + else if (flags & 64) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "readonly"); + } + else if (flags & 256) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "async"); + } + else if (node.parent.kind === 245 || node.parent.kind === 279) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, text); + } + else if (flags & 128) { + if (modifier.kind === 113) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, text, "abstract"); + } + else { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "abstract"); + } + } + flags |= ts.modifierToFlag(modifier.kind); + break; + case 116: + if (flags & 32) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "static"); + } + else if (flags & 64) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "readonly"); + } + else if (flags & 256) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "async"); + } + else if (node.parent.kind === 245 || node.parent.kind === 279) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, "static"); + } + else if (node.kind === 151) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "static"); + } + else if (flags & 128) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "abstract"); + } + flags |= 32; + lastStatic = modifier; + break; + case 133: + if (flags & 64) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "readonly"); + } + else if (node.kind !== 154 && node.kind !== 153 && node.kind !== 162 && node.kind !== 151) { + return grammarErrorOnNode(modifier, ts.Diagnostics.readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature); + } + flags |= 64; + lastReadonly = modifier; + break; + case 85: + if (flags & 1) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "export"); + } + else if (flags & 2) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "declare"); + } + else if (flags & 128) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "abstract"); + } + else if (flags & 256) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "async"); + } + else if (node.parent.kind === 240) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_class_element, "export"); + } + else if (node.kind === 151) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "export"); + } + flags |= 1; + break; + case 80: + var container = node.parent.kind === 279 ? node.parent : node.parent.parent; + if (container.kind === 244 && !ts.isAmbientModule(container)) { + return grammarErrorOnNode(modifier, ts.Diagnostics.A_default_export_can_only_be_used_in_an_ECMAScript_style_module); + } + flags |= 512; + break; + case 125: + if (flags & 2) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "declare"); + } + else if (flags & 256) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async"); + } + else if (node.parent.kind === 240) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_class_element, "declare"); + } + else if (node.kind === 151) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "declare"); + } + else if ((node.parent.flags & 4194304) && node.parent.kind === 245) { + return grammarErrorOnNode(modifier, ts.Diagnostics.A_declare_modifier_cannot_be_used_in_an_already_ambient_context); + } + flags |= 2; + lastDeclare = modifier; + break; + case 118: + if (flags & 128) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "abstract"); + } + if (node.kind !== 240) { + if (node.kind !== 156 && + node.kind !== 154 && + node.kind !== 158 && + node.kind !== 159) { + return grammarErrorOnNode(modifier, ts.Diagnostics.abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration); + } + if (!(node.parent.kind === 240 && ts.hasModifier(node.parent, 128))) { + return grammarErrorOnNode(modifier, ts.Diagnostics.Abstract_methods_can_only_appear_within_an_abstract_class); + } + if (flags & 32) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "abstract"); + } + if (flags & 8) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "private", "abstract"); + } + } + flags |= 128; + break; + case 121: + if (flags & 256) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "async"); + } + else if (flags & 2 || node.parent.flags & 4194304) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async"); + } + else if (node.kind === 151) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "async"); + } + flags |= 256; + lastAsync = modifier; + break; + } + } + if (node.kind === 157) { + if (flags & 32) { + return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "static"); + } + if (flags & 128) { + return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "abstract"); + } + else if (flags & 256) { + return grammarErrorOnNode(lastAsync, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "async"); + } + else if (flags & 64) { + return grammarErrorOnNode(lastReadonly, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "readonly"); + } + return false; + } + else if ((node.kind === 249 || node.kind === 248) && flags & 2) { + return grammarErrorOnNode(lastDeclare, ts.Diagnostics.A_0_modifier_cannot_be_used_with_an_import_declaration, "declare"); + } + else if (node.kind === 151 && (flags & 92) && ts.isBindingPattern(node.name)) { + return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_may_not_be_declared_using_a_binding_pattern); + } + else if (node.kind === 151 && (flags & 92) && node.dotDotDotToken) { + return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_cannot_be_declared_using_a_rest_parameter); + } + if (flags & 256) { + return checkGrammarAsyncModifier(node, lastAsync); + } + return false; + } + function reportObviousModifierErrors(node) { + return !node.modifiers + ? false + : shouldReportBadModifier(node) + ? grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here) + : undefined; + } + function shouldReportBadModifier(node) { + switch (node.kind) { + case 158: + case 159: + case 157: + case 154: + case 153: + case 156: + case 155: + case 162: + case 244: + case 249: + case 248: + case 255: + case 254: + case 196: + case 197: + case 151: + return false; + default: + if (node.parent.kind === 245 || node.parent.kind === 279) { + return false; + } + switch (node.kind) { + case 239: + return nodeHasAnyModifiersExcept(node, 121); + case 240: + return nodeHasAnyModifiersExcept(node, 118); + case 241: + case 219: + case 242: + return true; + case 243: + return nodeHasAnyModifiersExcept(node, 77); + default: + ts.Debug.fail(); + return false; + } + } + } + function nodeHasAnyModifiersExcept(node, allowedModifier) { + return node.modifiers.length > 1 || node.modifiers[0].kind !== allowedModifier; + } + function checkGrammarAsyncModifier(node, asyncModifier) { + switch (node.kind) { + case 156: + case 239: + case 196: + case 197: + return false; + } + return grammarErrorOnNode(asyncModifier, ts.Diagnostics._0_modifier_cannot_be_used_here, "async"); + } + function checkGrammarForDisallowedTrailingComma(list, diag) { + if (diag === void 0) { diag = ts.Diagnostics.Trailing_comma_not_allowed; } + if (list && list.hasTrailingComma) { + return grammarErrorAtPos(list[0], list.end - ",".length, ",".length, diag); + } + return false; + } + function checkGrammarTypeParameterList(typeParameters, file) { + if (typeParameters && typeParameters.length === 0) { + var start = typeParameters.pos - "<".length; + var end = ts.skipTrivia(file.text, typeParameters.end) + ">".length; + return grammarErrorAtPos(file, start, end - start, ts.Diagnostics.Type_parameter_list_cannot_be_empty); + } + return false; + } + function checkGrammarParameterList(parameters) { + var seenOptionalParameter = false; + var parameterCount = parameters.length; + for (var i = 0; i < parameterCount; i++) { + var parameter = parameters[i]; + if (parameter.dotDotDotToken) { + if (i !== (parameterCount - 1)) { + return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.A_rest_parameter_must_be_last_in_a_parameter_list); + } + if (!(parameter.flags & 4194304)) { + checkGrammarForDisallowedTrailingComma(parameters, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma); + } + if (ts.isBindingPattern(parameter.name)) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.A_rest_element_cannot_contain_a_binding_pattern); + } + if (parameter.questionToken) { + return grammarErrorOnNode(parameter.questionToken, ts.Diagnostics.A_rest_parameter_cannot_be_optional); + } + if (parameter.initializer) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.A_rest_parameter_cannot_have_an_initializer); + } + } + else if (parameter.questionToken) { + seenOptionalParameter = true; + if (parameter.initializer) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.Parameter_cannot_have_question_mark_and_initializer); + } + } + else if (seenOptionalParameter && !parameter.initializer) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.A_required_parameter_cannot_follow_an_optional_parameter); + } + } + } + function getNonSimpleParameters(parameters) { + return ts.filter(parameters, function (parameter) { return !!parameter.initializer || ts.isBindingPattern(parameter.name) || ts.isRestParameter(parameter); }); + } + function checkGrammarForUseStrictSimpleParameterList(node) { + if (languageVersion >= 3) { + var useStrictDirective_1 = node.body && ts.isBlock(node.body) && ts.findUseStrictPrologue(node.body.statements); + if (useStrictDirective_1) { + var nonSimpleParameters = getNonSimpleParameters(node.parameters); + if (ts.length(nonSimpleParameters)) { + ts.forEach(nonSimpleParameters, function (parameter) { + addRelatedInfo(error(parameter, ts.Diagnostics.This_parameter_is_not_allowed_with_use_strict_directive), ts.createDiagnosticForNode(useStrictDirective_1, ts.Diagnostics.use_strict_directive_used_here)); + }); + var diagnostics_1 = nonSimpleParameters.map(function (parameter, index) { return (index === 0 ? ts.createDiagnosticForNode(parameter, ts.Diagnostics.Non_simple_parameter_declared_here) : ts.createDiagnosticForNode(parameter, ts.Diagnostics.and_here)); }); + addRelatedInfo.apply(void 0, [error(useStrictDirective_1, ts.Diagnostics.use_strict_directive_cannot_be_used_with_non_simple_parameter_list)].concat(diagnostics_1)); + return true; + } + } + } + return false; + } + function checkGrammarFunctionLikeDeclaration(node) { + var file = ts.getSourceFileOfNode(node); + return checkGrammarDecoratorsAndModifiers(node) || checkGrammarTypeParameterList(node.typeParameters, file) || + checkGrammarParameterList(node.parameters) || checkGrammarArrowFunction(node, file) || + (ts.isFunctionLikeDeclaration(node) && checkGrammarForUseStrictSimpleParameterList(node)); + } + function checkGrammarClassLikeDeclaration(node) { + var file = ts.getSourceFileOfNode(node); + return checkGrammarClassDeclarationHeritageClauses(node) || checkGrammarTypeParameterList(node.typeParameters, file); + } + function checkGrammarArrowFunction(node, file) { + if (!ts.isArrowFunction(node)) { + return false; + } + var equalsGreaterThanToken = node.equalsGreaterThanToken; + var startLine = ts.getLineAndCharacterOfPosition(file, equalsGreaterThanToken.pos).line; + var endLine = ts.getLineAndCharacterOfPosition(file, equalsGreaterThanToken.end).line; + return startLine !== endLine && grammarErrorOnNode(equalsGreaterThanToken, ts.Diagnostics.Line_terminator_not_permitted_before_arrow); + } + function checkGrammarIndexSignatureParameters(node) { + var parameter = node.parameters[0]; + if (node.parameters.length !== 1) { + if (parameter) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_must_have_exactly_one_parameter); + } + else { + return grammarErrorOnNode(node, ts.Diagnostics.An_index_signature_must_have_exactly_one_parameter); + } + } + if (parameter.dotDotDotToken) { + return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.An_index_signature_cannot_have_a_rest_parameter); + } + if (ts.hasModifiers(parameter)) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_cannot_have_an_accessibility_modifier); + } + if (parameter.questionToken) { + return grammarErrorOnNode(parameter.questionToken, ts.Diagnostics.An_index_signature_parameter_cannot_have_a_question_mark); + } + if (parameter.initializer) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_cannot_have_an_initializer); + } + if (!parameter.type) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_must_have_a_type_annotation); + } + if (parameter.type.kind !== 138 && parameter.type.kind !== 135) { + var type = getTypeFromTypeNode(parameter.type); + if (type.flags & 4 || type.flags & 8) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead, ts.getTextOfNode(parameter.name), typeToString(type), typeToString(getTypeFromTypeNode(node.type))); + } + if (type.flags & 1048576 && allTypesAssignableToKind(type, 128, true)) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead); + } + return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_must_be_string_or_number); + } + if (!node.type) { + return grammarErrorOnNode(node, ts.Diagnostics.An_index_signature_must_have_a_type_annotation); + } + return false; + } + function checkGrammarIndexSignature(node) { + return checkGrammarDecoratorsAndModifiers(node) || checkGrammarIndexSignatureParameters(node); + } + function checkGrammarForAtLeastOneTypeArgument(node, typeArguments) { + if (typeArguments && typeArguments.length === 0) { + var sourceFile = ts.getSourceFileOfNode(node); + var start = typeArguments.pos - "<".length; + var end = ts.skipTrivia(sourceFile.text, typeArguments.end) + ">".length; + return grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.Type_argument_list_cannot_be_empty); + } + return false; + } + function checkGrammarTypeArguments(node, typeArguments) { + return checkGrammarForDisallowedTrailingComma(typeArguments) || + checkGrammarForAtLeastOneTypeArgument(node, typeArguments); + } + function checkGrammarForOmittedArgument(args) { + if (args) { + for (var _i = 0, args_5 = args; _i < args_5.length; _i++) { + var arg = args_5[_i]; + if (arg.kind === 210) { + return grammarErrorAtPos(arg, arg.pos, 0, ts.Diagnostics.Argument_expression_expected); + } + } + } + return false; + } + function checkGrammarArguments(args) { + return checkGrammarForOmittedArgument(args); + } + function checkGrammarHeritageClause(node) { + var types = node.types; + if (checkGrammarForDisallowedTrailingComma(types)) { + return true; + } + if (types && types.length === 0) { + var listType = ts.tokenToString(node.token); + return grammarErrorAtPos(node, types.pos, 0, ts.Diagnostics._0_list_cannot_be_empty, listType); + } + return ts.some(types, checkGrammarExpressionWithTypeArguments); + } + function checkGrammarExpressionWithTypeArguments(node) { + return checkGrammarTypeArguments(node, node.typeArguments); + } + function checkGrammarClassDeclarationHeritageClauses(node) { + var seenExtendsClause = false; + var seenImplementsClause = false; + if (!checkGrammarDecoratorsAndModifiers(node) && node.heritageClauses) { + for (var _i = 0, _a = node.heritageClauses; _i < _a.length; _i++) { + var heritageClause = _a[_i]; + if (heritageClause.token === 86) { + if (seenExtendsClause) { + return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.extends_clause_already_seen); + } + if (seenImplementsClause) { + return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.extends_clause_must_precede_implements_clause); + } + if (heritageClause.types.length > 1) { + return grammarErrorOnFirstToken(heritageClause.types[1], ts.Diagnostics.Classes_can_only_extend_a_single_class); + } + seenExtendsClause = true; + } + else { + ts.Debug.assert(heritageClause.token === 109); + if (seenImplementsClause) { + return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.implements_clause_already_seen); + } + seenImplementsClause = true; + } + checkGrammarHeritageClause(heritageClause); + } + } + } + function checkGrammarInterfaceDeclaration(node) { + var seenExtendsClause = false; + if (node.heritageClauses) { + for (var _i = 0, _a = node.heritageClauses; _i < _a.length; _i++) { + var heritageClause = _a[_i]; + if (heritageClause.token === 86) { + if (seenExtendsClause) { + return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.extends_clause_already_seen); + } + seenExtendsClause = true; + } + else { + ts.Debug.assert(heritageClause.token === 109); + return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.Interface_declaration_cannot_have_implements_clause); + } + checkGrammarHeritageClause(heritageClause); + } + } + return false; + } + function checkGrammarComputedPropertyName(node) { + if (node.kind !== 149) { + return false; + } + var computedPropertyName = node; + if (computedPropertyName.expression.kind === 204 && computedPropertyName.expression.operatorToken.kind === 27) { + return grammarErrorOnNode(computedPropertyName.expression, ts.Diagnostics.A_comma_expression_is_not_allowed_in_a_computed_property_name); + } + return false; + } + function checkGrammarForGenerator(node) { + if (node.asteriskToken) { + ts.Debug.assert(node.kind === 239 || + node.kind === 196 || + node.kind === 156); + if (node.flags & 4194304) { + return grammarErrorOnNode(node.asteriskToken, ts.Diagnostics.Generators_are_not_allowed_in_an_ambient_context); + } + if (!node.body) { + return grammarErrorOnNode(node.asteriskToken, ts.Diagnostics.An_overload_signature_cannot_be_declared_as_a_generator); + } + } + } + function checkGrammarForInvalidQuestionMark(questionToken, message) { + return !!questionToken && grammarErrorOnNode(questionToken, message); + } + function checkGrammarForInvalidExclamationToken(exclamationToken, message) { + return !!exclamationToken && grammarErrorOnNode(exclamationToken, message); + } + function checkGrammarObjectLiteralExpression(node, inDestructuring) { + var seen = ts.createUnderscoreEscapedMap(); + for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { + var prop = _a[_i]; + if (prop.kind === 277) { + continue; + } + var name = prop.name; + if (name.kind === 149) { + checkGrammarComputedPropertyName(name); + } + if (prop.kind === 276 && !inDestructuring && prop.objectAssignmentInitializer) { + return grammarErrorOnNode(prop.equalsToken, ts.Diagnostics.can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment); + } + if (prop.modifiers) { + for (var _b = 0, _c = prop.modifiers; _b < _c.length; _b++) { + var mod = _c[_b]; + if (mod.kind !== 121 || prop.kind !== 156) { + grammarErrorOnNode(mod, ts.Diagnostics._0_modifier_cannot_be_used_here, ts.getTextOfNode(mod)); + } + } + } + var currentKind = void 0; + switch (prop.kind) { + case 276: + checkGrammarForInvalidExclamationToken(prop.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context); + case 275: + checkGrammarForInvalidQuestionMark(prop.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional); + if (name.kind === 8) { + checkGrammarNumericLiteral(name); + } + case 156: + currentKind = 1; + break; + case 158: + currentKind = 2; + break; + case 159: + currentKind = 4; + break; + default: + throw ts.Debug.assertNever(prop, "Unexpected syntax kind:" + prop.kind); + } + var effectiveName = ts.getPropertyNameForPropertyNameNode(name); + if (effectiveName === undefined) { + continue; + } + var existingKind = seen.get(effectiveName); + if (!existingKind) { + seen.set(effectiveName, currentKind); + } + else { + if (currentKind === 1 && existingKind === 1) { + grammarErrorOnNode(name, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(name)); + } + else if ((currentKind & 6) && (existingKind & 6)) { + if (existingKind !== 6 && currentKind !== existingKind) { + seen.set(effectiveName, currentKind | existingKind); + } + else { + return grammarErrorOnNode(name, ts.Diagnostics.An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name); + } + } + else { + return grammarErrorOnNode(name, ts.Diagnostics.An_object_literal_cannot_have_property_and_accessor_with_the_same_name); + } + } + } + } + function checkGrammarJsxElement(node) { + checkGrammarTypeArguments(node, node.typeArguments); + var seen = ts.createUnderscoreEscapedMap(); + for (var _i = 0, _a = node.attributes.properties; _i < _a.length; _i++) { + var attr = _a[_i]; + if (attr.kind === 269) { + continue; + } + var name = attr.name, initializer = attr.initializer; + if (!seen.get(name.escapedText)) { + seen.set(name.escapedText, true); + } + else { + return grammarErrorOnNode(name, ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name); + } + if (initializer && initializer.kind === 270 && !initializer.expression) { + return grammarErrorOnNode(initializer, ts.Diagnostics.JSX_attributes_must_only_be_assigned_a_non_empty_expression); + } + } + } + function checkGrammarForInOrForOfStatement(forInOrOfStatement) { + if (checkGrammarStatementInAmbientContext(forInOrOfStatement)) { + return true; + } + if (forInOrOfStatement.kind === 227 && forInOrOfStatement.awaitModifier) { + if ((forInOrOfStatement.flags & 16384) === 0) { + return grammarErrorOnNode(forInOrOfStatement.awaitModifier, ts.Diagnostics.A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator); + } + } + if (forInOrOfStatement.initializer.kind === 238) { + var variableList = forInOrOfStatement.initializer; + if (!checkGrammarVariableDeclarationList(variableList)) { + var declarations = variableList.declarations; + if (!declarations.length) { + return false; + } + if (declarations.length > 1) { + var diagnostic = forInOrOfStatement.kind === 226 + ? ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement + : ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement; + return grammarErrorOnFirstToken(variableList.declarations[1], diagnostic); + } + var firstDeclaration = declarations[0]; + if (firstDeclaration.initializer) { + var diagnostic = forInOrOfStatement.kind === 226 + ? ts.Diagnostics.The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer + : ts.Diagnostics.The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer; + return grammarErrorOnNode(firstDeclaration.name, diagnostic); + } + if (firstDeclaration.type) { + var diagnostic = forInOrOfStatement.kind === 226 + ? ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation + : ts.Diagnostics.The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation; + return grammarErrorOnNode(firstDeclaration, diagnostic); + } + } + } + return false; + } + function checkGrammarAccessor(accessor) { + var kind = accessor.kind; + if (languageVersion < 1) { + return grammarErrorOnNode(accessor.name, ts.Diagnostics.Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher); + } + else if (accessor.flags & 4194304) { + return grammarErrorOnNode(accessor.name, ts.Diagnostics.An_accessor_cannot_be_declared_in_an_ambient_context); + } + else if (accessor.body === undefined && !ts.hasModifier(accessor, 128)) { + return grammarErrorAtPos(accessor, accessor.end - 1, ";".length, ts.Diagnostics._0_expected, "{"); + } + else if (accessor.body && ts.hasModifier(accessor, 128)) { + return grammarErrorOnNode(accessor, ts.Diagnostics.An_abstract_accessor_cannot_have_an_implementation); + } + else if (accessor.typeParameters) { + return grammarErrorOnNode(accessor.name, ts.Diagnostics.An_accessor_cannot_have_type_parameters); + } + else if (!doesAccessorHaveCorrectParameterCount(accessor)) { + return grammarErrorOnNode(accessor.name, kind === 158 ? + ts.Diagnostics.A_get_accessor_cannot_have_parameters : + ts.Diagnostics.A_set_accessor_must_have_exactly_one_parameter); + } + else if (kind === 159) { + if (accessor.type) { + return grammarErrorOnNode(accessor.name, ts.Diagnostics.A_set_accessor_cannot_have_a_return_type_annotation); + } + else { + var parameter = accessor.parameters[0]; + if (parameter.dotDotDotToken) { + return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.A_set_accessor_cannot_have_rest_parameter); + } + else if (parameter.questionToken) { + return grammarErrorOnNode(parameter.questionToken, ts.Diagnostics.A_set_accessor_cannot_have_an_optional_parameter); + } + else if (parameter.initializer) { + return grammarErrorOnNode(accessor.name, ts.Diagnostics.A_set_accessor_parameter_cannot_have_an_initializer); + } + } + } + return false; + } + function doesAccessorHaveCorrectParameterCount(accessor) { + return getAccessorThisParameter(accessor) || accessor.parameters.length === (accessor.kind === 158 ? 0 : 1); + } + function getAccessorThisParameter(accessor) { + if (accessor.parameters.length === (accessor.kind === 158 ? 1 : 2)) { + return ts.getThisParameter(accessor); + } + } + function checkGrammarTypeOperatorNode(node) { + if (node.operator === 142) { + if (node.type.kind !== 139) { + return grammarErrorOnNode(node.type, ts.Diagnostics._0_expected, ts.tokenToString(139)); + } + var parent = ts.walkUpParenthesizedTypes(node.parent); + switch (parent.kind) { + case 237: + var decl = parent; + if (decl.name.kind !== 72) { + return grammarErrorOnNode(node, ts.Diagnostics.unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name); + } + if (!ts.isVariableDeclarationInVariableStatement(decl)) { + return grammarErrorOnNode(node, ts.Diagnostics.unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement); + } + if (!(decl.parent.flags & 2)) { + return grammarErrorOnNode(parent.name, ts.Diagnostics.A_variable_whose_type_is_a_unique_symbol_type_must_be_const); + } + break; + case 154: + if (!ts.hasModifier(parent, 32) || + !ts.hasModifier(parent, 64)) { + return grammarErrorOnNode(parent.name, ts.Diagnostics.A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly); + } + break; + case 153: + if (!ts.hasModifier(parent, 64)) { + return grammarErrorOnNode(parent.name, ts.Diagnostics.A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly); + } + break; + default: + return grammarErrorOnNode(node, ts.Diagnostics.unique_symbol_types_are_not_allowed_here); + } + } + } + function checkGrammarForInvalidDynamicName(node, message) { + if (isNonBindableDynamicName(node)) { + return grammarErrorOnNode(node, message); + } + } + function checkGrammarMethod(node) { + if (checkGrammarFunctionLikeDeclaration(node)) { + return true; + } + if (node.kind === 156) { + if (node.parent.kind === 188) { + if (node.modifiers && !(node.modifiers.length === 1 && ts.first(node.modifiers).kind === 121)) { + return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); + } + else if (checkGrammarForInvalidQuestionMark(node.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional)) { + return true; + } + else if (checkGrammarForInvalidExclamationToken(node.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context)) { + return true; + } + else if (node.body === undefined) { + return grammarErrorAtPos(node, node.end - 1, ";".length, ts.Diagnostics._0_expected, "{"); + } + } + if (checkGrammarForGenerator(node)) { + return true; + } + } + if (ts.isClassLike(node.parent)) { + if (node.flags & 4194304) { + return checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type); + } + else if (node.kind === 156 && !node.body) { + return checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type); + } + } + else if (node.parent.kind === 241) { + return checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type); + } + else if (node.parent.kind === 168) { + return checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type); + } + } + function checkGrammarBreakOrContinueStatement(node) { + var current = node; + while (current) { + if (ts.isFunctionLike(current)) { + return grammarErrorOnNode(node, ts.Diagnostics.Jump_target_cannot_cross_function_boundary); + } + switch (current.kind) { + case 233: + if (node.label && current.label.escapedText === node.label.escapedText) { + var isMisplacedContinueLabel = node.kind === 228 + && !ts.isIterationStatement(current.statement, true); + if (isMisplacedContinueLabel) { + return grammarErrorOnNode(node, ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement); + } + return false; + } + break; + case 232: + if (node.kind === 229 && !node.label) { + return false; + } + break; + default: + if (ts.isIterationStatement(current, false) && !node.label) { + return false; + } + break; + } + current = current.parent; + } + if (node.label) { + var message = node.kind === 229 + ? ts.Diagnostics.A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement + : ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement; + return grammarErrorOnNode(node, message); + } + else { + var message = node.kind === 229 + ? ts.Diagnostics.A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement + : ts.Diagnostics.A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement; + return grammarErrorOnNode(node, message); + } + } + function checkGrammarBindingElement(node) { + if (node.dotDotDotToken) { + var elements = node.parent.elements; + if (node !== ts.last(elements)) { + return grammarErrorOnNode(node, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern); + } + checkGrammarForDisallowedTrailingComma(elements, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma); + if (node.propertyName) { + return grammarErrorOnNode(node.name, ts.Diagnostics.A_rest_element_cannot_have_a_property_name); + } + if (node.initializer) { + return grammarErrorAtPos(node, node.initializer.pos - 1, 1, ts.Diagnostics.A_rest_element_cannot_have_an_initializer); + } + } + } + function isStringOrNumberLiteralExpression(expr) { + return expr.kind === 10 || expr.kind === 8 || + expr.kind === 202 && expr.operator === 39 && + expr.operand.kind === 8; + } + function isBigIntLiteralExpression(expr) { + return expr.kind === 9 || + expr.kind === 202 && expr.operator === 39 && + expr.operand.kind === 9; + } + function isSimpleLiteralEnumReference(expr) { + if ((ts.isPropertyAccessExpression(expr) || (ts.isElementAccessExpression(expr) && isStringOrNumberLiteralExpression(expr.argumentExpression))) && + ts.isEntityNameExpression(expr.expression)) + return !!(checkExpressionCached(expr).flags & 1024); + } + function checkAmbientInitializer(node) { + var initializer = node.initializer; + if (initializer) { + var isInvalidInitializer = !(isStringOrNumberLiteralExpression(initializer) || + isSimpleLiteralEnumReference(initializer) || + initializer.kind === 102 || initializer.kind === 87 || + isBigIntLiteralExpression(initializer)); + var isConstOrReadonly = ts.isDeclarationReadonly(node) || ts.isVariableDeclaration(node) && ts.isVarConst(node); + if (isConstOrReadonly && !node.type) { + if (isInvalidInitializer) { + return grammarErrorOnNode(initializer, ts.Diagnostics.A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_reference); + } + } + else { + return grammarErrorOnNode(initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); + } + if (!isConstOrReadonly || isInvalidInitializer) { + return grammarErrorOnNode(initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); + } + } + } + function checkGrammarVariableDeclaration(node) { + if (node.parent.parent.kind !== 226 && node.parent.parent.kind !== 227) { + if (node.flags & 4194304) { + checkAmbientInitializer(node); + } + else if (!node.initializer) { + if (ts.isBindingPattern(node.name) && !ts.isBindingPattern(node.parent)) { + return grammarErrorOnNode(node, ts.Diagnostics.A_destructuring_declaration_must_have_an_initializer); + } + if (ts.isVarConst(node)) { + return grammarErrorOnNode(node, ts.Diagnostics.const_declarations_must_be_initialized); + } + } + } + if (node.exclamationToken && (node.parent.parent.kind !== 219 || !node.type || node.initializer || node.flags & 4194304)) { + return grammarErrorOnNode(node.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context); + } + if (compilerOptions.module !== ts.ModuleKind.ES2015 && compilerOptions.module !== ts.ModuleKind.ESNext && compilerOptions.module !== ts.ModuleKind.System && !compilerOptions.noEmit && + !(node.parent.parent.flags & 4194304) && ts.hasModifier(node.parent.parent, 1)) { + checkESModuleMarker(node.name); + } + var checkLetConstNames = (ts.isLet(node) || ts.isVarConst(node)); + return checkLetConstNames && checkGrammarNameInLetOrConstDeclarations(node.name); + } + function checkESModuleMarker(name) { + if (name.kind === 72) { + if (ts.idText(name) === "__esModule") { + return grammarErrorOnNode(name, ts.Diagnostics.Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules); + } + } + else { + var elements = name.elements; + for (var _i = 0, elements_1 = elements; _i < elements_1.length; _i++) { + var element = elements_1[_i]; + if (!ts.isOmittedExpression(element)) { + return checkESModuleMarker(element.name); + } + } + } + return false; + } + function checkGrammarNameInLetOrConstDeclarations(name) { + if (name.kind === 72) { + if (name.originalKeywordKind === 111) { + return grammarErrorOnNode(name, ts.Diagnostics.let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations); + } + } + else { + var elements = name.elements; + for (var _i = 0, elements_2 = elements; _i < elements_2.length; _i++) { + var element = elements_2[_i]; + if (!ts.isOmittedExpression(element)) { + checkGrammarNameInLetOrConstDeclarations(element.name); + } + } + } + return false; + } + function checkGrammarVariableDeclarationList(declarationList) { + var declarations = declarationList.declarations; + if (checkGrammarForDisallowedTrailingComma(declarationList.declarations)) { + return true; + } + if (!declarationList.declarations.length) { + return grammarErrorAtPos(declarationList, declarations.pos, declarations.end - declarations.pos, ts.Diagnostics.Variable_declaration_list_cannot_be_empty); + } + return false; + } + function allowLetAndConstDeclarations(parent) { + switch (parent.kind) { + case 222: + case 223: + case 224: + case 231: + case 225: + case 226: + case 227: + return false; + case 233: + return allowLetAndConstDeclarations(parent.parent); + } + return true; + } + function checkGrammarForDisallowedLetOrConstStatement(node) { + if (!allowLetAndConstDeclarations(node.parent)) { + if (ts.isLet(node.declarationList)) { + return grammarErrorOnNode(node, ts.Diagnostics.let_declarations_can_only_be_declared_inside_a_block); + } + else if (ts.isVarConst(node.declarationList)) { + return grammarErrorOnNode(node, ts.Diagnostics.const_declarations_can_only_be_declared_inside_a_block); + } + } + } + function checkGrammarMetaProperty(node) { + var escapedText = node.name.escapedText; + switch (node.keywordToken) { + case 95: + if (escapedText !== "target") { + return grammarErrorOnNode(node.name, ts.Diagnostics._0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2, node.name.escapedText, ts.tokenToString(node.keywordToken), "target"); + } + break; + case 92: + if (escapedText !== "meta") { + return grammarErrorOnNode(node.name, ts.Diagnostics._0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2, node.name.escapedText, ts.tokenToString(node.keywordToken), "meta"); + } + break; + } + } + function hasParseDiagnostics(sourceFile) { + return sourceFile.parseDiagnostics.length > 0; + } + function grammarErrorOnFirstToken(node, message, arg0, arg1, arg2) { + var sourceFile = ts.getSourceFileOfNode(node); + if (!hasParseDiagnostics(sourceFile)) { + var span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos); + diagnostics.add(ts.createFileDiagnostic(sourceFile, span.start, span.length, message, arg0, arg1, arg2)); + return true; + } + return false; + } + function grammarErrorAtPos(nodeForSourceFile, start, length, message, arg0, arg1, arg2) { + var sourceFile = ts.getSourceFileOfNode(nodeForSourceFile); + if (!hasParseDiagnostics(sourceFile)) { + diagnostics.add(ts.createFileDiagnostic(sourceFile, start, length, message, arg0, arg1, arg2)); + return true; + } + return false; + } + function grammarErrorOnNode(node, message, arg0, arg1, arg2) { + var sourceFile = ts.getSourceFileOfNode(node); + if (!hasParseDiagnostics(sourceFile)) { + diagnostics.add(ts.createDiagnosticForNode(node, message, arg0, arg1, arg2)); + return true; + } + return false; + } + function checkGrammarConstructorTypeParameters(node) { + var jsdocTypeParameters = ts.isInJSFile(node) ? ts.getJSDocTypeParameterDeclarations(node) : undefined; + var range = node.typeParameters || jsdocTypeParameters && ts.firstOrUndefined(jsdocTypeParameters); + if (range) { + var pos = range.pos === range.end ? range.pos : ts.skipTrivia(ts.getSourceFileOfNode(node).text, range.pos); + return grammarErrorAtPos(node, pos, range.end - pos, ts.Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration); + } + } + function checkGrammarConstructorTypeAnnotation(node) { + var type = ts.getEffectiveReturnTypeNode(node); + if (type) { + return grammarErrorOnNode(type, ts.Diagnostics.Type_annotation_cannot_appear_on_a_constructor_declaration); + } + } + function checkGrammarProperty(node) { + if (ts.isClassLike(node.parent)) { + if (checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_class_property_declaration_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type)) { + return true; + } + } + else if (node.parent.kind === 241) { + if (checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type)) { + return true; + } + if (node.initializer) { + return grammarErrorOnNode(node.initializer, ts.Diagnostics.An_interface_property_cannot_have_an_initializer); + } + } + else if (node.parent.kind === 168) { + if (checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type)) { + return true; + } + if (node.initializer) { + return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_type_literal_property_cannot_have_an_initializer); + } + } + if (node.flags & 4194304) { + checkAmbientInitializer(node); + } + if (ts.isPropertyDeclaration(node) && node.exclamationToken && (!ts.isClassLike(node.parent) || !node.type || node.initializer || + node.flags & 4194304 || ts.hasModifier(node, 32 | 128))) { + return grammarErrorOnNode(node.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context); + } + } + function checkGrammarTopLevelElementForRequiredDeclareModifier(node) { + if (node.kind === 241 || + node.kind === 242 || + node.kind === 249 || + node.kind === 248 || + node.kind === 255 || + node.kind === 254 || + node.kind === 247 || + ts.hasModifier(node, 2 | 1 | 512)) { + return false; + } + return grammarErrorOnFirstToken(node, ts.Diagnostics.A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file); + } + function checkGrammarTopLevelElementsForRequiredDeclareModifier(file) { + for (var _i = 0, _a = file.statements; _i < _a.length; _i++) { + var decl = _a[_i]; + if (ts.isDeclaration(decl) || decl.kind === 219) { + if (checkGrammarTopLevelElementForRequiredDeclareModifier(decl)) { + return true; + } + } + } + return false; + } + function checkGrammarSourceFile(node) { + return !!(node.flags & 4194304) && checkGrammarTopLevelElementsForRequiredDeclareModifier(node); + } + function checkGrammarStatementInAmbientContext(node) { + if (node.flags & 4194304) { + if (ts.isAccessor(node.parent)) { + return getNodeLinks(node).hasReportedStatementInAmbientContext = true; + } + var links = getNodeLinks(node); + if (!links.hasReportedStatementInAmbientContext && ts.isFunctionLike(node.parent)) { + return getNodeLinks(node).hasReportedStatementInAmbientContext = grammarErrorOnFirstToken(node, ts.Diagnostics.An_implementation_cannot_be_declared_in_ambient_contexts); + } + if (node.parent.kind === 218 || node.parent.kind === 245 || node.parent.kind === 279) { + var links_2 = getNodeLinks(node.parent); + if (!links_2.hasReportedStatementInAmbientContext) { + return links_2.hasReportedStatementInAmbientContext = grammarErrorOnFirstToken(node, ts.Diagnostics.Statements_are_not_allowed_in_ambient_contexts); + } + } + else { + } + } + return false; + } + function checkGrammarNumericLiteral(node) { + if (node.numericLiteralFlags & 32) { + var diagnosticMessage = void 0; + if (languageVersion >= 1) { + diagnosticMessage = ts.Diagnostics.Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0; + } + else if (ts.isChildOfNodeWithKind(node, 182)) { + diagnosticMessage = ts.Diagnostics.Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0; + } + else if (ts.isChildOfNodeWithKind(node, 278)) { + diagnosticMessage = ts.Diagnostics.Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0; + } + if (diagnosticMessage) { + var withMinus = ts.isPrefixUnaryExpression(node.parent) && node.parent.operator === 39; + var literal = (withMinus ? "-" : "") + "0o" + node.text; + return grammarErrorOnNode(withMinus ? node.parent : node, diagnosticMessage, literal); + } + } + return false; + } + function checkGrammarBigIntLiteral(node) { + var literalType = ts.isLiteralTypeNode(node.parent) || + ts.isPrefixUnaryExpression(node.parent) && ts.isLiteralTypeNode(node.parent.parent); + if (!literalType) { + if (languageVersion < 6) { + if (grammarErrorOnNode(node, ts.Diagnostics.BigInt_literals_are_not_available_when_targeting_lower_than_ESNext)) { + return true; + } + } + } + return false; + } + function grammarErrorAfterFirstToken(node, message, arg0, arg1, arg2) { + var sourceFile = ts.getSourceFileOfNode(node); + if (!hasParseDiagnostics(sourceFile)) { + var span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos); + diagnostics.add(ts.createFileDiagnostic(sourceFile, ts.textSpanEnd(span), 0, message, arg0, arg1, arg2)); + return true; + } + return false; + } + function getAmbientModules() { + if (!ambientModulesCache) { + ambientModulesCache = []; + globals.forEach(function (global, sym) { + if (ambientModuleSymbolRegex.test(sym)) { + ambientModulesCache.push(global); + } + }); + } + return ambientModulesCache; + } + function checkGrammarImportCallExpression(node) { + if (moduleKind === ts.ModuleKind.ES2015) { + return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext); + } + if (node.typeArguments) { + return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_import_cannot_have_type_arguments); + } + var nodeArguments = node.arguments; + if (nodeArguments.length !== 1) { + return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_import_must_have_one_specifier_as_an_argument); + } + if (ts.isSpreadElement(nodeArguments[0])) { + return grammarErrorOnNode(nodeArguments[0], ts.Diagnostics.Specifier_of_dynamic_import_cannot_be_spread_element); + } + return false; + } + } + ts.createTypeChecker = createTypeChecker; + function isDeclarationNameOrImportPropertyName(name) { + switch (name.parent.kind) { + case 253: + case 257: + return ts.isIdentifier(name); + default: + return ts.isDeclarationName(name); + } + } + function isSomeImportDeclaration(decl) { + switch (decl.kind) { + case 250: + case 248: + case 251: + case 253: + return true; + case 72: + return decl.parent.kind === 253; + default: + return false; + } + } + var JsxNames; + (function (JsxNames) { + JsxNames.JSX = "JSX"; + JsxNames.IntrinsicElements = "IntrinsicElements"; + JsxNames.ElementClass = "ElementClass"; + JsxNames.ElementAttributesPropertyNameContainer = "ElementAttributesProperty"; + JsxNames.ElementChildrenAttributeNameContainer = "ElementChildrenAttribute"; + JsxNames.Element = "Element"; + JsxNames.IntrinsicAttributes = "IntrinsicAttributes"; + JsxNames.IntrinsicClassAttributes = "IntrinsicClassAttributes"; + JsxNames.LibraryManagedAttributes = "LibraryManagedAttributes"; + })(JsxNames || (JsxNames = {})); + function typeIsLiteralType(type) { + return !!(type.flags & 2944); + } +})(ts || (ts = {})); +var ts; +(function (ts) { + function createSynthesizedNode(kind) { + var node = ts.createNode(kind, -1, -1); + node.flags |= 8; + return node; + } + function updateNode(updated, original) { + if (updated !== original) { + setOriginalNode(updated, original); + setTextRange(updated, original); + ts.aggregateTransformFlags(updated); + } + return updated; + } + ts.updateNode = updateNode; + function createNodeArray(elements, hasTrailingComma) { + if (!elements || elements === ts.emptyArray) { + elements = []; + } + else if (ts.isNodeArray(elements)) { + return elements; + } + var array = elements; + array.pos = -1; + array.end = -1; + array.hasTrailingComma = hasTrailingComma; + return array; + } + ts.createNodeArray = createNodeArray; + function getSynthesizedClone(node) { + if (node === undefined) { + return node; + } + var clone = createSynthesizedNode(node.kind); + clone.flags |= node.flags; + setOriginalNode(clone, node); + for (var key in node) { + if (clone.hasOwnProperty(key) || !node.hasOwnProperty(key)) { + continue; + } + clone[key] = node[key]; + } + return clone; + } + ts.getSynthesizedClone = getSynthesizedClone; + function createLiteral(value, isSingleQuote) { + if (typeof value === "number") { + return createNumericLiteral(value + ""); + } + if (typeof value === "object" && "base10Value" in value) { + return createBigIntLiteral(ts.pseudoBigIntToString(value) + "n"); + } + if (typeof value === "boolean") { + return value ? createTrue() : createFalse(); + } + if (ts.isString(value)) { + var res = createStringLiteral(value); + if (isSingleQuote) + res.singleQuote = true; + return res; + } + return createLiteralFromNode(value); + } + ts.createLiteral = createLiteral; + function createNumericLiteral(value) { + var node = createSynthesizedNode(8); + node.text = value; + node.numericLiteralFlags = 0; + return node; + } + ts.createNumericLiteral = createNumericLiteral; + function createBigIntLiteral(value) { + var node = createSynthesizedNode(9); + node.text = value; + return node; + } + ts.createBigIntLiteral = createBigIntLiteral; + function createStringLiteral(text) { + var node = createSynthesizedNode(10); + node.text = text; + return node; + } + ts.createStringLiteral = createStringLiteral; + function createRegularExpressionLiteral(text) { + var node = createSynthesizedNode(13); + node.text = text; + return node; + } + ts.createRegularExpressionLiteral = createRegularExpressionLiteral; + function createLiteralFromNode(sourceNode) { + var node = createStringLiteral(ts.getTextOfIdentifierOrLiteral(sourceNode)); + node.textSourceNode = sourceNode; + return node; + } + function createIdentifier(text, typeArguments) { + var node = createSynthesizedNode(72); + node.escapedText = ts.escapeLeadingUnderscores(text); + node.originalKeywordKind = text ? ts.stringToToken(text) : 0; + node.autoGenerateFlags = 0; + node.autoGenerateId = 0; + if (typeArguments) { + node.typeArguments = createNodeArray(typeArguments); + } + return node; + } + ts.createIdentifier = createIdentifier; + function updateIdentifier(node, typeArguments) { + return node.typeArguments !== typeArguments + ? updateNode(createIdentifier(ts.idText(node), typeArguments), node) + : node; + } + ts.updateIdentifier = updateIdentifier; + var nextAutoGenerateId = 0; + function createTempVariable(recordTempVariable, reservedInNestedScopes) { + var name = createIdentifier(""); + name.autoGenerateFlags = 1; + name.autoGenerateId = nextAutoGenerateId; + nextAutoGenerateId++; + if (recordTempVariable) { + recordTempVariable(name); + } + if (reservedInNestedScopes) { + name.autoGenerateFlags |= 8; + } + return name; + } + ts.createTempVariable = createTempVariable; + function createLoopVariable() { + var name = createIdentifier(""); + name.autoGenerateFlags = 2; + name.autoGenerateId = nextAutoGenerateId; + nextAutoGenerateId++; + return name; + } + ts.createLoopVariable = createLoopVariable; + function createUniqueName(text) { + var name = createIdentifier(text); + name.autoGenerateFlags = 3; + name.autoGenerateId = nextAutoGenerateId; + nextAutoGenerateId++; + return name; + } + ts.createUniqueName = createUniqueName; + function createOptimisticUniqueName(text) { + var name = createIdentifier(text); + name.autoGenerateFlags = 3 | 16; + name.autoGenerateId = nextAutoGenerateId; + nextAutoGenerateId++; + return name; + } + ts.createOptimisticUniqueName = createOptimisticUniqueName; + function createFileLevelUniqueName(text) { + var name = createOptimisticUniqueName(text); + name.autoGenerateFlags |= 32; + return name; + } + ts.createFileLevelUniqueName = createFileLevelUniqueName; + function getGeneratedNameForNode(node, flags) { + var name = createIdentifier(node && ts.isIdentifier(node) ? ts.idText(node) : ""); + name.autoGenerateFlags = 4 | flags; + name.autoGenerateId = nextAutoGenerateId; + name.original = node; + nextAutoGenerateId++; + return name; + } + ts.getGeneratedNameForNode = getGeneratedNameForNode; + function createToken(token) { + return createSynthesizedNode(token); + } + ts.createToken = createToken; + function createSuper() { + return createSynthesizedNode(98); + } + ts.createSuper = createSuper; + function createThis() { + return createSynthesizedNode(100); + } + ts.createThis = createThis; + function createNull() { + return createSynthesizedNode(96); + } + ts.createNull = createNull; + function createTrue() { + return createSynthesizedNode(102); + } + ts.createTrue = createTrue; + function createFalse() { + return createSynthesizedNode(87); + } + ts.createFalse = createFalse; + function createModifier(kind) { + return createToken(kind); + } + ts.createModifier = createModifier; + function createModifiersFromModifierFlags(flags) { + var result = []; + if (flags & 1) { + result.push(createModifier(85)); + } + if (flags & 2) { + result.push(createModifier(125)); + } + if (flags & 512) { + result.push(createModifier(80)); + } + if (flags & 2048) { + result.push(createModifier(77)); + } + if (flags & 4) { + result.push(createModifier(115)); + } + if (flags & 8) { + result.push(createModifier(113)); + } + if (flags & 16) { + result.push(createModifier(114)); + } + if (flags & 128) { + result.push(createModifier(118)); + } + if (flags & 32) { + result.push(createModifier(116)); + } + if (flags & 64) { + result.push(createModifier(133)); + } + if (flags & 256) { + result.push(createModifier(121)); + } + return result; + } + ts.createModifiersFromModifierFlags = createModifiersFromModifierFlags; + function createQualifiedName(left, right) { + var node = createSynthesizedNode(148); + node.left = left; + node.right = asName(right); + return node; + } + ts.createQualifiedName = createQualifiedName; + function updateQualifiedName(node, left, right) { + return node.left !== left + || node.right !== right + ? updateNode(createQualifiedName(left, right), node) + : node; + } + ts.updateQualifiedName = updateQualifiedName; + function parenthesizeForComputedName(expression) { + return ts.isCommaSequence(expression) + ? createParen(expression) + : expression; + } + function createComputedPropertyName(expression) { + var node = createSynthesizedNode(149); + node.expression = parenthesizeForComputedName(expression); + return node; + } + ts.createComputedPropertyName = createComputedPropertyName; + function updateComputedPropertyName(node, expression) { + return node.expression !== expression + ? updateNode(createComputedPropertyName(expression), node) + : node; + } + ts.updateComputedPropertyName = updateComputedPropertyName; + function createTypeParameterDeclaration(name, constraint, defaultType) { + var node = createSynthesizedNode(150); + node.name = asName(name); + node.constraint = constraint; + node.default = defaultType; + return node; + } + ts.createTypeParameterDeclaration = createTypeParameterDeclaration; + function updateTypeParameterDeclaration(node, name, constraint, defaultType) { + return node.name !== name + || node.constraint !== constraint + || node.default !== defaultType + ? updateNode(createTypeParameterDeclaration(name, constraint, defaultType), node) + : node; + } + ts.updateTypeParameterDeclaration = updateTypeParameterDeclaration; + function createParameter(decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer) { + var node = createSynthesizedNode(151); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.dotDotDotToken = dotDotDotToken; + node.name = asName(name); + node.questionToken = questionToken; + node.type = type; + node.initializer = initializer ? ts.parenthesizeExpressionForList(initializer) : undefined; + return node; + } + ts.createParameter = createParameter; + function updateParameter(node, decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.dotDotDotToken !== dotDotDotToken + || node.name !== name + || node.questionToken !== questionToken + || node.type !== type + || node.initializer !== initializer + ? updateNode(createParameter(decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer), node) + : node; + } + ts.updateParameter = updateParameter; + function createDecorator(expression) { + var node = createSynthesizedNode(152); + node.expression = ts.parenthesizeForAccess(expression); + return node; + } + ts.createDecorator = createDecorator; + function updateDecorator(node, expression) { + return node.expression !== expression + ? updateNode(createDecorator(expression), node) + : node; + } + ts.updateDecorator = updateDecorator; + function createPropertySignature(modifiers, name, questionToken, type, initializer) { + var node = createSynthesizedNode(153); + node.modifiers = asNodeArray(modifiers); + node.name = asName(name); + node.questionToken = questionToken; + node.type = type; + node.initializer = initializer; + return node; + } + ts.createPropertySignature = createPropertySignature; + function updatePropertySignature(node, modifiers, name, questionToken, type, initializer) { + return node.modifiers !== modifiers + || node.name !== name + || node.questionToken !== questionToken + || node.type !== type + || node.initializer !== initializer + ? updateNode(createPropertySignature(modifiers, name, questionToken, type, initializer), node) + : node; + } + ts.updatePropertySignature = updatePropertySignature; + function createProperty(decorators, modifiers, name, questionOrExclamationToken, type, initializer) { + var node = createSynthesizedNode(154); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.name = asName(name); + node.questionToken = questionOrExclamationToken !== undefined && questionOrExclamationToken.kind === 56 ? questionOrExclamationToken : undefined; + node.exclamationToken = questionOrExclamationToken !== undefined && questionOrExclamationToken.kind === 52 ? questionOrExclamationToken : undefined; + node.type = type; + node.initializer = initializer; + return node; + } + ts.createProperty = createProperty; + function updateProperty(node, decorators, modifiers, name, questionOrExclamationToken, type, initializer) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.name !== name + || node.questionToken !== (questionOrExclamationToken !== undefined && questionOrExclamationToken.kind === 56 ? questionOrExclamationToken : undefined) + || node.exclamationToken !== (questionOrExclamationToken !== undefined && questionOrExclamationToken.kind === 52 ? questionOrExclamationToken : undefined) + || node.type !== type + || node.initializer !== initializer + ? updateNode(createProperty(decorators, modifiers, name, questionOrExclamationToken, type, initializer), node) + : node; + } + ts.updateProperty = updateProperty; + function createMethodSignature(typeParameters, parameters, type, name, questionToken) { + var node = createSignatureDeclaration(155, typeParameters, parameters, type); + node.name = asName(name); + node.questionToken = questionToken; + return node; + } + ts.createMethodSignature = createMethodSignature; + function updateMethodSignature(node, typeParameters, parameters, type, name, questionToken) { + return node.typeParameters !== typeParameters + || node.parameters !== parameters + || node.type !== type + || node.name !== name + || node.questionToken !== questionToken + ? updateNode(createMethodSignature(typeParameters, parameters, type, name, questionToken), node) + : node; + } + ts.updateMethodSignature = updateMethodSignature; + function createMethod(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { + var node = createSynthesizedNode(156); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.asteriskToken = asteriskToken; + node.name = asName(name); + node.questionToken = questionToken; + node.typeParameters = asNodeArray(typeParameters); + node.parameters = createNodeArray(parameters); + node.type = type; + node.body = body; + return node; + } + ts.createMethod = createMethod; + function updateMethod(node, decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.asteriskToken !== asteriskToken + || node.name !== name + || node.questionToken !== questionToken + || node.typeParameters !== typeParameters + || node.parameters !== parameters + || node.type !== type + || node.body !== body + ? updateNode(createMethod(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body), node) + : node; + } + ts.updateMethod = updateMethod; + function createConstructor(decorators, modifiers, parameters, body) { + var node = createSynthesizedNode(157); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.typeParameters = undefined; + node.parameters = createNodeArray(parameters); + node.type = undefined; + node.body = body; + return node; + } + ts.createConstructor = createConstructor; + function updateConstructor(node, decorators, modifiers, parameters, body) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.parameters !== parameters + || node.body !== body + ? updateNode(createConstructor(decorators, modifiers, parameters, body), node) + : node; + } + ts.updateConstructor = updateConstructor; + function createGetAccessor(decorators, modifiers, name, parameters, type, body) { + var node = createSynthesizedNode(158); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.name = asName(name); + node.typeParameters = undefined; + node.parameters = createNodeArray(parameters); + node.type = type; + node.body = body; + return node; + } + ts.createGetAccessor = createGetAccessor; + function updateGetAccessor(node, decorators, modifiers, name, parameters, type, body) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.name !== name + || node.parameters !== parameters + || node.type !== type + || node.body !== body + ? updateNode(createGetAccessor(decorators, modifiers, name, parameters, type, body), node) + : node; + } + ts.updateGetAccessor = updateGetAccessor; + function createSetAccessor(decorators, modifiers, name, parameters, body) { + var node = createSynthesizedNode(159); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.name = asName(name); + node.typeParameters = undefined; + node.parameters = createNodeArray(parameters); + node.body = body; + return node; + } + ts.createSetAccessor = createSetAccessor; + function updateSetAccessor(node, decorators, modifiers, name, parameters, body) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.name !== name + || node.parameters !== parameters + || node.body !== body + ? updateNode(createSetAccessor(decorators, modifiers, name, parameters, body), node) + : node; + } + ts.updateSetAccessor = updateSetAccessor; + function createCallSignature(typeParameters, parameters, type) { + return createSignatureDeclaration(160, typeParameters, parameters, type); + } + ts.createCallSignature = createCallSignature; + function updateCallSignature(node, typeParameters, parameters, type) { + return updateSignatureDeclaration(node, typeParameters, parameters, type); + } + ts.updateCallSignature = updateCallSignature; + function createConstructSignature(typeParameters, parameters, type) { + return createSignatureDeclaration(161, typeParameters, parameters, type); + } + ts.createConstructSignature = createConstructSignature; + function updateConstructSignature(node, typeParameters, parameters, type) { + return updateSignatureDeclaration(node, typeParameters, parameters, type); + } + ts.updateConstructSignature = updateConstructSignature; + function createIndexSignature(decorators, modifiers, parameters, type) { + var node = createSynthesizedNode(162); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.parameters = createNodeArray(parameters); + node.type = type; + return node; + } + ts.createIndexSignature = createIndexSignature; + function updateIndexSignature(node, decorators, modifiers, parameters, type) { + return node.parameters !== parameters + || node.type !== type + || node.decorators !== decorators + || node.modifiers !== modifiers + ? updateNode(createIndexSignature(decorators, modifiers, parameters, type), node) + : node; + } + ts.updateIndexSignature = updateIndexSignature; + function createSignatureDeclaration(kind, typeParameters, parameters, type, typeArguments) { + var node = createSynthesizedNode(kind); + node.typeParameters = asNodeArray(typeParameters); + node.parameters = asNodeArray(parameters); + node.type = type; + node.typeArguments = asNodeArray(typeArguments); + return node; + } + ts.createSignatureDeclaration = createSignatureDeclaration; + function updateSignatureDeclaration(node, typeParameters, parameters, type) { + return node.typeParameters !== typeParameters + || node.parameters !== parameters + || node.type !== type + ? updateNode(createSignatureDeclaration(node.kind, typeParameters, parameters, type), node) + : node; + } + function createKeywordTypeNode(kind) { + return createSynthesizedNode(kind); + } + ts.createKeywordTypeNode = createKeywordTypeNode; + function createTypePredicateNode(parameterName, type) { + var node = createSynthesizedNode(163); + node.parameterName = asName(parameterName); + node.type = type; + return node; + } + ts.createTypePredicateNode = createTypePredicateNode; + function updateTypePredicateNode(node, parameterName, type) { + return node.parameterName !== parameterName + || node.type !== type + ? updateNode(createTypePredicateNode(parameterName, type), node) + : node; + } + ts.updateTypePredicateNode = updateTypePredicateNode; + function createTypeReferenceNode(typeName, typeArguments) { + var node = createSynthesizedNode(164); + node.typeName = asName(typeName); + node.typeArguments = typeArguments && ts.parenthesizeTypeParameters(typeArguments); + return node; + } + ts.createTypeReferenceNode = createTypeReferenceNode; + function updateTypeReferenceNode(node, typeName, typeArguments) { + return node.typeName !== typeName + || node.typeArguments !== typeArguments + ? updateNode(createTypeReferenceNode(typeName, typeArguments), node) + : node; + } + ts.updateTypeReferenceNode = updateTypeReferenceNode; + function createFunctionTypeNode(typeParameters, parameters, type) { + return createSignatureDeclaration(165, typeParameters, parameters, type); + } + ts.createFunctionTypeNode = createFunctionTypeNode; + function updateFunctionTypeNode(node, typeParameters, parameters, type) { + return updateSignatureDeclaration(node, typeParameters, parameters, type); + } + ts.updateFunctionTypeNode = updateFunctionTypeNode; + function createConstructorTypeNode(typeParameters, parameters, type) { + return createSignatureDeclaration(166, typeParameters, parameters, type); + } + ts.createConstructorTypeNode = createConstructorTypeNode; + function updateConstructorTypeNode(node, typeParameters, parameters, type) { + return updateSignatureDeclaration(node, typeParameters, parameters, type); + } + ts.updateConstructorTypeNode = updateConstructorTypeNode; + function createTypeQueryNode(exprName) { + var node = createSynthesizedNode(167); + node.exprName = exprName; + return node; + } + ts.createTypeQueryNode = createTypeQueryNode; + function updateTypeQueryNode(node, exprName) { + return node.exprName !== exprName + ? updateNode(createTypeQueryNode(exprName), node) + : node; + } + ts.updateTypeQueryNode = updateTypeQueryNode; + function createTypeLiteralNode(members) { + var node = createSynthesizedNode(168); + node.members = createNodeArray(members); + return node; + } + ts.createTypeLiteralNode = createTypeLiteralNode; + function updateTypeLiteralNode(node, members) { + return node.members !== members + ? updateNode(createTypeLiteralNode(members), node) + : node; + } + ts.updateTypeLiteralNode = updateTypeLiteralNode; + function createArrayTypeNode(elementType) { + var node = createSynthesizedNode(169); + node.elementType = ts.parenthesizeArrayTypeMember(elementType); + return node; + } + ts.createArrayTypeNode = createArrayTypeNode; + function updateArrayTypeNode(node, elementType) { + return node.elementType !== elementType + ? updateNode(createArrayTypeNode(elementType), node) + : node; + } + ts.updateArrayTypeNode = updateArrayTypeNode; + function createTupleTypeNode(elementTypes) { + var node = createSynthesizedNode(170); + node.elementTypes = createNodeArray(elementTypes); + return node; + } + ts.createTupleTypeNode = createTupleTypeNode; + function updateTupleTypeNode(node, elementTypes) { + return node.elementTypes !== elementTypes + ? updateNode(createTupleTypeNode(elementTypes), node) + : node; + } + ts.updateTupleTypeNode = updateTupleTypeNode; + function createOptionalTypeNode(type) { + var node = createSynthesizedNode(171); + node.type = ts.parenthesizeArrayTypeMember(type); + return node; + } + ts.createOptionalTypeNode = createOptionalTypeNode; + function updateOptionalTypeNode(node, type) { + return node.type !== type + ? updateNode(createOptionalTypeNode(type), node) + : node; + } + ts.updateOptionalTypeNode = updateOptionalTypeNode; + function createRestTypeNode(type) { + var node = createSynthesizedNode(172); + node.type = type; + return node; + } + ts.createRestTypeNode = createRestTypeNode; + function updateRestTypeNode(node, type) { + return node.type !== type + ? updateNode(createRestTypeNode(type), node) + : node; + } + ts.updateRestTypeNode = updateRestTypeNode; + function createUnionTypeNode(types) { + return createUnionOrIntersectionTypeNode(173, types); + } + ts.createUnionTypeNode = createUnionTypeNode; + function updateUnionTypeNode(node, types) { + return updateUnionOrIntersectionTypeNode(node, types); + } + ts.updateUnionTypeNode = updateUnionTypeNode; + function createIntersectionTypeNode(types) { + return createUnionOrIntersectionTypeNode(174, types); + } + ts.createIntersectionTypeNode = createIntersectionTypeNode; + function updateIntersectionTypeNode(node, types) { + return updateUnionOrIntersectionTypeNode(node, types); + } + ts.updateIntersectionTypeNode = updateIntersectionTypeNode; + function createUnionOrIntersectionTypeNode(kind, types) { + var node = createSynthesizedNode(kind); + node.types = ts.parenthesizeElementTypeMembers(types); + return node; + } + ts.createUnionOrIntersectionTypeNode = createUnionOrIntersectionTypeNode; + function updateUnionOrIntersectionTypeNode(node, types) { + return node.types !== types + ? updateNode(createUnionOrIntersectionTypeNode(node.kind, types), node) + : node; + } + function createConditionalTypeNode(checkType, extendsType, trueType, falseType) { + var node = createSynthesizedNode(175); + node.checkType = ts.parenthesizeConditionalTypeMember(checkType); + node.extendsType = ts.parenthesizeConditionalTypeMember(extendsType); + node.trueType = trueType; + node.falseType = falseType; + return node; + } + ts.createConditionalTypeNode = createConditionalTypeNode; + function updateConditionalTypeNode(node, checkType, extendsType, trueType, falseType) { + return node.checkType !== checkType + || node.extendsType !== extendsType + || node.trueType !== trueType + || node.falseType !== falseType + ? updateNode(createConditionalTypeNode(checkType, extendsType, trueType, falseType), node) + : node; + } + ts.updateConditionalTypeNode = updateConditionalTypeNode; + function createInferTypeNode(typeParameter) { + var node = createSynthesizedNode(176); + node.typeParameter = typeParameter; + return node; + } + ts.createInferTypeNode = createInferTypeNode; + function updateInferTypeNode(node, typeParameter) { + return node.typeParameter !== typeParameter + ? updateNode(createInferTypeNode(typeParameter), node) + : node; + } + ts.updateInferTypeNode = updateInferTypeNode; + function createImportTypeNode(argument, qualifier, typeArguments, isTypeOf) { + var node = createSynthesizedNode(183); + node.argument = argument; + node.qualifier = qualifier; + node.typeArguments = asNodeArray(typeArguments); + node.isTypeOf = isTypeOf; + return node; + } + ts.createImportTypeNode = createImportTypeNode; + function updateImportTypeNode(node, argument, qualifier, typeArguments, isTypeOf) { + return node.argument !== argument + || node.qualifier !== qualifier + || node.typeArguments !== typeArguments + || node.isTypeOf !== isTypeOf + ? updateNode(createImportTypeNode(argument, qualifier, typeArguments, isTypeOf), node) + : node; + } + ts.updateImportTypeNode = updateImportTypeNode; + function createParenthesizedType(type) { + var node = createSynthesizedNode(177); + node.type = type; + return node; + } + ts.createParenthesizedType = createParenthesizedType; + function updateParenthesizedType(node, type) { + return node.type !== type + ? updateNode(createParenthesizedType(type), node) + : node; + } + ts.updateParenthesizedType = updateParenthesizedType; + function createThisTypeNode() { + return createSynthesizedNode(178); + } + ts.createThisTypeNode = createThisTypeNode; + function createTypeOperatorNode(operatorOrType, type) { + var node = createSynthesizedNode(179); + node.operator = typeof operatorOrType === "number" ? operatorOrType : 129; + node.type = ts.parenthesizeElementTypeMember(typeof operatorOrType === "number" ? type : operatorOrType); + return node; + } + ts.createTypeOperatorNode = createTypeOperatorNode; + function updateTypeOperatorNode(node, type) { + return node.type !== type ? updateNode(createTypeOperatorNode(node.operator, type), node) : node; + } + ts.updateTypeOperatorNode = updateTypeOperatorNode; + function createIndexedAccessTypeNode(objectType, indexType) { + var node = createSynthesizedNode(180); + node.objectType = ts.parenthesizeElementTypeMember(objectType); + node.indexType = indexType; + return node; + } + ts.createIndexedAccessTypeNode = createIndexedAccessTypeNode; + function updateIndexedAccessTypeNode(node, objectType, indexType) { + return node.objectType !== objectType + || node.indexType !== indexType + ? updateNode(createIndexedAccessTypeNode(objectType, indexType), node) + : node; + } + ts.updateIndexedAccessTypeNode = updateIndexedAccessTypeNode; + function createMappedTypeNode(readonlyToken, typeParameter, questionToken, type) { + var node = createSynthesizedNode(181); + node.readonlyToken = readonlyToken; + node.typeParameter = typeParameter; + node.questionToken = questionToken; + node.type = type; + return node; + } + ts.createMappedTypeNode = createMappedTypeNode; + function updateMappedTypeNode(node, readonlyToken, typeParameter, questionToken, type) { + return node.readonlyToken !== readonlyToken + || node.typeParameter !== typeParameter + || node.questionToken !== questionToken + || node.type !== type + ? updateNode(createMappedTypeNode(readonlyToken, typeParameter, questionToken, type), node) + : node; + } + ts.updateMappedTypeNode = updateMappedTypeNode; + function createLiteralTypeNode(literal) { + var node = createSynthesizedNode(182); + node.literal = literal; + return node; + } + ts.createLiteralTypeNode = createLiteralTypeNode; + function updateLiteralTypeNode(node, literal) { + return node.literal !== literal + ? updateNode(createLiteralTypeNode(literal), node) + : node; + } + ts.updateLiteralTypeNode = updateLiteralTypeNode; + function createObjectBindingPattern(elements) { + var node = createSynthesizedNode(184); + node.elements = createNodeArray(elements); + return node; + } + ts.createObjectBindingPattern = createObjectBindingPattern; + function updateObjectBindingPattern(node, elements) { + return node.elements !== elements + ? updateNode(createObjectBindingPattern(elements), node) + : node; + } + ts.updateObjectBindingPattern = updateObjectBindingPattern; + function createArrayBindingPattern(elements) { + var node = createSynthesizedNode(185); + node.elements = createNodeArray(elements); + return node; + } + ts.createArrayBindingPattern = createArrayBindingPattern; + function updateArrayBindingPattern(node, elements) { + return node.elements !== elements + ? updateNode(createArrayBindingPattern(elements), node) + : node; + } + ts.updateArrayBindingPattern = updateArrayBindingPattern; + function createBindingElement(dotDotDotToken, propertyName, name, initializer) { + var node = createSynthesizedNode(186); + node.dotDotDotToken = dotDotDotToken; + node.propertyName = asName(propertyName); + node.name = asName(name); + node.initializer = initializer; + return node; + } + ts.createBindingElement = createBindingElement; + function updateBindingElement(node, dotDotDotToken, propertyName, name, initializer) { + return node.propertyName !== propertyName + || node.dotDotDotToken !== dotDotDotToken + || node.name !== name + || node.initializer !== initializer + ? updateNode(createBindingElement(dotDotDotToken, propertyName, name, initializer), node) + : node; + } + ts.updateBindingElement = updateBindingElement; + function createArrayLiteral(elements, multiLine) { + var node = createSynthesizedNode(187); + node.elements = ts.parenthesizeListElements(createNodeArray(elements)); + if (multiLine) + node.multiLine = true; + return node; + } + ts.createArrayLiteral = createArrayLiteral; + function updateArrayLiteral(node, elements) { + return node.elements !== elements + ? updateNode(createArrayLiteral(elements, node.multiLine), node) + : node; + } + ts.updateArrayLiteral = updateArrayLiteral; + function createObjectLiteral(properties, multiLine) { + var node = createSynthesizedNode(188); + node.properties = createNodeArray(properties); + if (multiLine) + node.multiLine = true; + return node; + } + ts.createObjectLiteral = createObjectLiteral; + function updateObjectLiteral(node, properties) { + return node.properties !== properties + ? updateNode(createObjectLiteral(properties, node.multiLine), node) + : node; + } + ts.updateObjectLiteral = updateObjectLiteral; + function createPropertyAccess(expression, name) { + var node = createSynthesizedNode(189); + node.expression = ts.parenthesizeForAccess(expression); + node.name = asName(name); + setEmitFlags(node, 131072); + return node; + } + ts.createPropertyAccess = createPropertyAccess; + function updatePropertyAccess(node, expression, name) { + return node.expression !== expression + || node.name !== name + ? updateNode(setEmitFlags(createPropertyAccess(expression, name), ts.getEmitFlags(node)), node) + : node; + } + ts.updatePropertyAccess = updatePropertyAccess; + function createElementAccess(expression, index) { + var node = createSynthesizedNode(190); + node.expression = ts.parenthesizeForAccess(expression); + node.argumentExpression = asExpression(index); + return node; + } + ts.createElementAccess = createElementAccess; + function updateElementAccess(node, expression, argumentExpression) { + return node.expression !== expression + || node.argumentExpression !== argumentExpression + ? updateNode(createElementAccess(expression, argumentExpression), node) + : node; + } + ts.updateElementAccess = updateElementAccess; + function createCall(expression, typeArguments, argumentsArray) { + var node = createSynthesizedNode(191); + node.expression = ts.parenthesizeForAccess(expression); + node.typeArguments = asNodeArray(typeArguments); + node.arguments = ts.parenthesizeListElements(createNodeArray(argumentsArray)); + return node; + } + ts.createCall = createCall; + function updateCall(node, expression, typeArguments, argumentsArray) { + return node.expression !== expression + || node.typeArguments !== typeArguments + || node.arguments !== argumentsArray + ? updateNode(createCall(expression, typeArguments, argumentsArray), node) + : node; + } + ts.updateCall = updateCall; + function createNew(expression, typeArguments, argumentsArray) { + var node = createSynthesizedNode(192); + node.expression = ts.parenthesizeForNew(expression); + node.typeArguments = asNodeArray(typeArguments); + node.arguments = argumentsArray ? ts.parenthesizeListElements(createNodeArray(argumentsArray)) : undefined; + return node; + } + ts.createNew = createNew; + function updateNew(node, expression, typeArguments, argumentsArray) { + return node.expression !== expression + || node.typeArguments !== typeArguments + || node.arguments !== argumentsArray + ? updateNode(createNew(expression, typeArguments, argumentsArray), node) + : node; + } + ts.updateNew = updateNew; + function createTaggedTemplate(tag, typeArgumentsOrTemplate, template) { + var node = createSynthesizedNode(193); + node.tag = ts.parenthesizeForAccess(tag); + if (template) { + node.typeArguments = asNodeArray(typeArgumentsOrTemplate); + node.template = template; + } + else { + node.typeArguments = undefined; + node.template = typeArgumentsOrTemplate; + } + return node; + } + ts.createTaggedTemplate = createTaggedTemplate; + function updateTaggedTemplate(node, tag, typeArgumentsOrTemplate, template) { + return node.tag !== tag + || (template + ? node.typeArguments !== typeArgumentsOrTemplate || node.template !== template + : node.typeArguments !== undefined || node.template !== typeArgumentsOrTemplate) + ? updateNode(createTaggedTemplate(tag, typeArgumentsOrTemplate, template), node) + : node; + } + ts.updateTaggedTemplate = updateTaggedTemplate; + function createTypeAssertion(type, expression) { + var node = createSynthesizedNode(194); + node.type = type; + node.expression = ts.parenthesizePrefixOperand(expression); + return node; + } + ts.createTypeAssertion = createTypeAssertion; + function updateTypeAssertion(node, type, expression) { + return node.type !== type + || node.expression !== expression + ? updateNode(createTypeAssertion(type, expression), node) + : node; + } + ts.updateTypeAssertion = updateTypeAssertion; + function createParen(expression) { + var node = createSynthesizedNode(195); + node.expression = expression; + return node; + } + ts.createParen = createParen; + function updateParen(node, expression) { + return node.expression !== expression + ? updateNode(createParen(expression), node) + : node; + } + ts.updateParen = updateParen; + function createFunctionExpression(modifiers, asteriskToken, name, typeParameters, parameters, type, body) { + var node = createSynthesizedNode(196); + node.modifiers = asNodeArray(modifiers); + node.asteriskToken = asteriskToken; + node.name = asName(name); + node.typeParameters = asNodeArray(typeParameters); + node.parameters = createNodeArray(parameters); + node.type = type; + node.body = body; + return node; + } + ts.createFunctionExpression = createFunctionExpression; + function updateFunctionExpression(node, modifiers, asteriskToken, name, typeParameters, parameters, type, body) { + return node.name !== name + || node.modifiers !== modifiers + || node.asteriskToken !== asteriskToken + || node.typeParameters !== typeParameters + || node.parameters !== parameters + || node.type !== type + || node.body !== body + ? updateNode(createFunctionExpression(modifiers, asteriskToken, name, typeParameters, parameters, type, body), node) + : node; + } + ts.updateFunctionExpression = updateFunctionExpression; + function createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body) { + var node = createSynthesizedNode(197); + node.modifiers = asNodeArray(modifiers); + node.typeParameters = asNodeArray(typeParameters); + node.parameters = createNodeArray(parameters); + node.type = type; + node.equalsGreaterThanToken = equalsGreaterThanToken || createToken(37); + node.body = ts.parenthesizeConciseBody(body); + return node; + } + ts.createArrowFunction = createArrowFunction; + function updateArrowFunction(node, modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body) { + return node.modifiers !== modifiers + || node.typeParameters !== typeParameters + || node.parameters !== parameters + || node.type !== type + || node.equalsGreaterThanToken !== equalsGreaterThanToken + || node.body !== body + ? updateNode(createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body), node) + : node; + } + ts.updateArrowFunction = updateArrowFunction; + function createDelete(expression) { + var node = createSynthesizedNode(198); + node.expression = ts.parenthesizePrefixOperand(expression); + return node; + } + ts.createDelete = createDelete; + function updateDelete(node, expression) { + return node.expression !== expression + ? updateNode(createDelete(expression), node) + : node; + } + ts.updateDelete = updateDelete; + function createTypeOf(expression) { + var node = createSynthesizedNode(199); + node.expression = ts.parenthesizePrefixOperand(expression); + return node; + } + ts.createTypeOf = createTypeOf; + function updateTypeOf(node, expression) { + return node.expression !== expression + ? updateNode(createTypeOf(expression), node) + : node; + } + ts.updateTypeOf = updateTypeOf; + function createVoid(expression) { + var node = createSynthesizedNode(200); + node.expression = ts.parenthesizePrefixOperand(expression); + return node; + } + ts.createVoid = createVoid; + function updateVoid(node, expression) { + return node.expression !== expression + ? updateNode(createVoid(expression), node) + : node; + } + ts.updateVoid = updateVoid; + function createAwait(expression) { + var node = createSynthesizedNode(201); + node.expression = ts.parenthesizePrefixOperand(expression); + return node; + } + ts.createAwait = createAwait; + function updateAwait(node, expression) { + return node.expression !== expression + ? updateNode(createAwait(expression), node) + : node; + } + ts.updateAwait = updateAwait; + function createPrefix(operator, operand) { + var node = createSynthesizedNode(202); + node.operator = operator; + node.operand = ts.parenthesizePrefixOperand(operand); + return node; + } + ts.createPrefix = createPrefix; + function updatePrefix(node, operand) { + return node.operand !== operand + ? updateNode(createPrefix(node.operator, operand), node) + : node; + } + ts.updatePrefix = updatePrefix; + function createPostfix(operand, operator) { + var node = createSynthesizedNode(203); + node.operand = ts.parenthesizePostfixOperand(operand); + node.operator = operator; + return node; + } + ts.createPostfix = createPostfix; + function updatePostfix(node, operand) { + return node.operand !== operand + ? updateNode(createPostfix(operand, node.operator), node) + : node; + } + ts.updatePostfix = updatePostfix; + function createBinary(left, operator, right) { + var node = createSynthesizedNode(204); + var operatorToken = asToken(operator); + var operatorKind = operatorToken.kind; + node.left = ts.parenthesizeBinaryOperand(operatorKind, left, true, undefined); + node.operatorToken = operatorToken; + node.right = ts.parenthesizeBinaryOperand(operatorKind, right, false, node.left); + return node; + } + ts.createBinary = createBinary; + function updateBinary(node, left, right, operator) { + return node.left !== left + || node.right !== right + ? updateNode(createBinary(left, operator || node.operatorToken, right), node) + : node; + } + ts.updateBinary = updateBinary; + function createConditional(condition, questionTokenOrWhenTrue, whenTrueOrWhenFalse, colonToken, whenFalse) { + var node = createSynthesizedNode(205); + node.condition = ts.parenthesizeForConditionalHead(condition); + node.questionToken = whenFalse ? questionTokenOrWhenTrue : createToken(56); + node.whenTrue = ts.parenthesizeSubexpressionOfConditionalExpression(whenFalse ? whenTrueOrWhenFalse : questionTokenOrWhenTrue); + node.colonToken = whenFalse ? colonToken : createToken(57); + node.whenFalse = ts.parenthesizeSubexpressionOfConditionalExpression(whenFalse ? whenFalse : whenTrueOrWhenFalse); + return node; + } + ts.createConditional = createConditional; + function updateConditional(node, condition, questionToken, whenTrue, colonToken, whenFalse) { + return node.condition !== condition + || node.questionToken !== questionToken + || node.whenTrue !== whenTrue + || node.colonToken !== colonToken + || node.whenFalse !== whenFalse + ? updateNode(createConditional(condition, questionToken, whenTrue, colonToken, whenFalse), node) + : node; + } + ts.updateConditional = updateConditional; + function createTemplateExpression(head, templateSpans) { + var node = createSynthesizedNode(206); + node.head = head; + node.templateSpans = createNodeArray(templateSpans); + return node; + } + ts.createTemplateExpression = createTemplateExpression; + function updateTemplateExpression(node, head, templateSpans) { + return node.head !== head + || node.templateSpans !== templateSpans + ? updateNode(createTemplateExpression(head, templateSpans), node) + : node; + } + ts.updateTemplateExpression = updateTemplateExpression; + function createTemplateHead(text) { + var node = createSynthesizedNode(15); + node.text = text; + return node; + } + ts.createTemplateHead = createTemplateHead; + function createTemplateMiddle(text) { + var node = createSynthesizedNode(16); + node.text = text; + return node; + } + ts.createTemplateMiddle = createTemplateMiddle; + function createTemplateTail(text) { + var node = createSynthesizedNode(17); + node.text = text; + return node; + } + ts.createTemplateTail = createTemplateTail; + function createNoSubstitutionTemplateLiteral(text) { + var node = createSynthesizedNode(14); + node.text = text; + return node; + } + ts.createNoSubstitutionTemplateLiteral = createNoSubstitutionTemplateLiteral; + function createYield(asteriskTokenOrExpression, expression) { + var node = createSynthesizedNode(207); + node.asteriskToken = asteriskTokenOrExpression && asteriskTokenOrExpression.kind === 40 ? asteriskTokenOrExpression : undefined; + node.expression = asteriskTokenOrExpression && asteriskTokenOrExpression.kind !== 40 ? asteriskTokenOrExpression : expression; + return node; + } + ts.createYield = createYield; + function updateYield(node, asteriskToken, expression) { + return node.expression !== expression + || node.asteriskToken !== asteriskToken + ? updateNode(createYield(asteriskToken, expression), node) + : node; + } + ts.updateYield = updateYield; + function createSpread(expression) { + var node = createSynthesizedNode(208); + node.expression = ts.parenthesizeExpressionForList(expression); + return node; + } + ts.createSpread = createSpread; + function updateSpread(node, expression) { + return node.expression !== expression + ? updateNode(createSpread(expression), node) + : node; + } + ts.updateSpread = updateSpread; + function createClassExpression(modifiers, name, typeParameters, heritageClauses, members) { + var node = createSynthesizedNode(209); + node.decorators = undefined; + node.modifiers = asNodeArray(modifiers); + node.name = asName(name); + node.typeParameters = asNodeArray(typeParameters); + node.heritageClauses = asNodeArray(heritageClauses); + node.members = createNodeArray(members); + return node; + } + ts.createClassExpression = createClassExpression; + function updateClassExpression(node, modifiers, name, typeParameters, heritageClauses, members) { + return node.modifiers !== modifiers + || node.name !== name + || node.typeParameters !== typeParameters + || node.heritageClauses !== heritageClauses + || node.members !== members + ? updateNode(createClassExpression(modifiers, name, typeParameters, heritageClauses, members), node) + : node; + } + ts.updateClassExpression = updateClassExpression; + function createOmittedExpression() { + return createSynthesizedNode(210); + } + ts.createOmittedExpression = createOmittedExpression; + function createExpressionWithTypeArguments(typeArguments, expression) { + var node = createSynthesizedNode(211); + node.expression = ts.parenthesizeForAccess(expression); + node.typeArguments = asNodeArray(typeArguments); + return node; + } + ts.createExpressionWithTypeArguments = createExpressionWithTypeArguments; + function updateExpressionWithTypeArguments(node, typeArguments, expression) { + return node.typeArguments !== typeArguments + || node.expression !== expression + ? updateNode(createExpressionWithTypeArguments(typeArguments, expression), node) + : node; + } + ts.updateExpressionWithTypeArguments = updateExpressionWithTypeArguments; + function createAsExpression(expression, type) { + var node = createSynthesizedNode(212); + node.expression = expression; + node.type = type; + return node; + } + ts.createAsExpression = createAsExpression; + function updateAsExpression(node, expression, type) { + return node.expression !== expression + || node.type !== type + ? updateNode(createAsExpression(expression, type), node) + : node; + } + ts.updateAsExpression = updateAsExpression; + function createNonNullExpression(expression) { + var node = createSynthesizedNode(213); + node.expression = ts.parenthesizeForAccess(expression); + return node; + } + ts.createNonNullExpression = createNonNullExpression; + function updateNonNullExpression(node, expression) { + return node.expression !== expression + ? updateNode(createNonNullExpression(expression), node) + : node; + } + ts.updateNonNullExpression = updateNonNullExpression; + function createMetaProperty(keywordToken, name) { + var node = createSynthesizedNode(214); + node.keywordToken = keywordToken; + node.name = name; + return node; + } + ts.createMetaProperty = createMetaProperty; + function updateMetaProperty(node, name) { + return node.name !== name + ? updateNode(createMetaProperty(node.keywordToken, name), node) + : node; + } + ts.updateMetaProperty = updateMetaProperty; + function createTemplateSpan(expression, literal) { + var node = createSynthesizedNode(216); + node.expression = expression; + node.literal = literal; + return node; + } + ts.createTemplateSpan = createTemplateSpan; + function updateTemplateSpan(node, expression, literal) { + return node.expression !== expression + || node.literal !== literal + ? updateNode(createTemplateSpan(expression, literal), node) + : node; + } + ts.updateTemplateSpan = updateTemplateSpan; + function createSemicolonClassElement() { + return createSynthesizedNode(217); + } + ts.createSemicolonClassElement = createSemicolonClassElement; + function createBlock(statements, multiLine) { + var block = createSynthesizedNode(218); + block.statements = createNodeArray(statements); + if (multiLine) + block.multiLine = multiLine; + return block; + } + ts.createBlock = createBlock; + function updateBlock(node, statements) { + return node.statements !== statements + ? updateNode(createBlock(statements, node.multiLine), node) + : node; + } + ts.updateBlock = updateBlock; + function createVariableStatement(modifiers, declarationList) { + var node = createSynthesizedNode(219); + node.decorators = undefined; + node.modifiers = asNodeArray(modifiers); + node.declarationList = ts.isArray(declarationList) ? createVariableDeclarationList(declarationList) : declarationList; + return node; + } + ts.createVariableStatement = createVariableStatement; + function updateVariableStatement(node, modifiers, declarationList) { + return node.modifiers !== modifiers + || node.declarationList !== declarationList + ? updateNode(createVariableStatement(modifiers, declarationList), node) + : node; + } + ts.updateVariableStatement = updateVariableStatement; + function createEmptyStatement() { + return createSynthesizedNode(220); + } + ts.createEmptyStatement = createEmptyStatement; + function createExpressionStatement(expression) { + var node = createSynthesizedNode(221); + node.expression = ts.parenthesizeExpressionForExpressionStatement(expression); + return node; + } + ts.createExpressionStatement = createExpressionStatement; + function updateExpressionStatement(node, expression) { + return node.expression !== expression + ? updateNode(createExpressionStatement(expression), node) + : node; + } + ts.updateExpressionStatement = updateExpressionStatement; + ts.createStatement = createExpressionStatement; + ts.updateStatement = updateExpressionStatement; + function createIf(expression, thenStatement, elseStatement) { + var node = createSynthesizedNode(222); + node.expression = expression; + node.thenStatement = thenStatement; + node.elseStatement = elseStatement; + return node; + } + ts.createIf = createIf; + function updateIf(node, expression, thenStatement, elseStatement) { + return node.expression !== expression + || node.thenStatement !== thenStatement + || node.elseStatement !== elseStatement + ? updateNode(createIf(expression, thenStatement, elseStatement), node) + : node; + } + ts.updateIf = updateIf; + function createDo(statement, expression) { + var node = createSynthesizedNode(223); + node.statement = statement; + node.expression = expression; + return node; + } + ts.createDo = createDo; + function updateDo(node, statement, expression) { + return node.statement !== statement + || node.expression !== expression + ? updateNode(createDo(statement, expression), node) + : node; + } + ts.updateDo = updateDo; + function createWhile(expression, statement) { + var node = createSynthesizedNode(224); + node.expression = expression; + node.statement = statement; + return node; + } + ts.createWhile = createWhile; + function updateWhile(node, expression, statement) { + return node.expression !== expression + || node.statement !== statement + ? updateNode(createWhile(expression, statement), node) + : node; + } + ts.updateWhile = updateWhile; + function createFor(initializer, condition, incrementor, statement) { + var node = createSynthesizedNode(225); + node.initializer = initializer; + node.condition = condition; + node.incrementor = incrementor; + node.statement = statement; + return node; + } + ts.createFor = createFor; + function updateFor(node, initializer, condition, incrementor, statement) { + return node.initializer !== initializer + || node.condition !== condition + || node.incrementor !== incrementor + || node.statement !== statement + ? updateNode(createFor(initializer, condition, incrementor, statement), node) + : node; + } + ts.updateFor = updateFor; + function createForIn(initializer, expression, statement) { + var node = createSynthesizedNode(226); + node.initializer = initializer; + node.expression = expression; + node.statement = statement; + return node; + } + ts.createForIn = createForIn; + function updateForIn(node, initializer, expression, statement) { + return node.initializer !== initializer + || node.expression !== expression + || node.statement !== statement + ? updateNode(createForIn(initializer, expression, statement), node) + : node; + } + ts.updateForIn = updateForIn; + function createForOf(awaitModifier, initializer, expression, statement) { + var node = createSynthesizedNode(227); + node.awaitModifier = awaitModifier; + node.initializer = initializer; + node.expression = expression; + node.statement = statement; + return node; + } + ts.createForOf = createForOf; + function updateForOf(node, awaitModifier, initializer, expression, statement) { + return node.awaitModifier !== awaitModifier + || node.initializer !== initializer + || node.expression !== expression + || node.statement !== statement + ? updateNode(createForOf(awaitModifier, initializer, expression, statement), node) + : node; + } + ts.updateForOf = updateForOf; + function createContinue(label) { + var node = createSynthesizedNode(228); + node.label = asName(label); + return node; + } + ts.createContinue = createContinue; + function updateContinue(node, label) { + return node.label !== label + ? updateNode(createContinue(label), node) + : node; + } + ts.updateContinue = updateContinue; + function createBreak(label) { + var node = createSynthesizedNode(229); + node.label = asName(label); + return node; + } + ts.createBreak = createBreak; + function updateBreak(node, label) { + return node.label !== label + ? updateNode(createBreak(label), node) + : node; + } + ts.updateBreak = updateBreak; + function createReturn(expression) { + var node = createSynthesizedNode(230); + node.expression = expression; + return node; + } + ts.createReturn = createReturn; + function updateReturn(node, expression) { + return node.expression !== expression + ? updateNode(createReturn(expression), node) + : node; + } + ts.updateReturn = updateReturn; + function createWith(expression, statement) { + var node = createSynthesizedNode(231); + node.expression = expression; + node.statement = statement; + return node; + } + ts.createWith = createWith; + function updateWith(node, expression, statement) { + return node.expression !== expression + || node.statement !== statement + ? updateNode(createWith(expression, statement), node) + : node; + } + ts.updateWith = updateWith; + function createSwitch(expression, caseBlock) { + var node = createSynthesizedNode(232); + node.expression = ts.parenthesizeExpressionForList(expression); + node.caseBlock = caseBlock; + return node; + } + ts.createSwitch = createSwitch; + function updateSwitch(node, expression, caseBlock) { + return node.expression !== expression + || node.caseBlock !== caseBlock + ? updateNode(createSwitch(expression, caseBlock), node) + : node; + } + ts.updateSwitch = updateSwitch; + function createLabel(label, statement) { + var node = createSynthesizedNode(233); + node.label = asName(label); + node.statement = statement; + return node; + } + ts.createLabel = createLabel; + function updateLabel(node, label, statement) { + return node.label !== label + || node.statement !== statement + ? updateNode(createLabel(label, statement), node) + : node; + } + ts.updateLabel = updateLabel; + function createThrow(expression) { + var node = createSynthesizedNode(234); + node.expression = expression; + return node; + } + ts.createThrow = createThrow; + function updateThrow(node, expression) { + return node.expression !== expression + ? updateNode(createThrow(expression), node) + : node; + } + ts.updateThrow = updateThrow; + function createTry(tryBlock, catchClause, finallyBlock) { + var node = createSynthesizedNode(235); + node.tryBlock = tryBlock; + node.catchClause = catchClause; + node.finallyBlock = finallyBlock; + return node; + } + ts.createTry = createTry; + function updateTry(node, tryBlock, catchClause, finallyBlock) { + return node.tryBlock !== tryBlock + || node.catchClause !== catchClause + || node.finallyBlock !== finallyBlock + ? updateNode(createTry(tryBlock, catchClause, finallyBlock), node) + : node; + } + ts.updateTry = updateTry; + function createDebuggerStatement() { + return createSynthesizedNode(236); + } + ts.createDebuggerStatement = createDebuggerStatement; + function createVariableDeclaration(name, type, initializer) { + var node = createSynthesizedNode(237); + node.name = asName(name); + node.type = type; + node.initializer = initializer !== undefined ? ts.parenthesizeExpressionForList(initializer) : undefined; + return node; + } + ts.createVariableDeclaration = createVariableDeclaration; + function updateVariableDeclaration(node, name, type, initializer) { + return node.name !== name + || node.type !== type + || node.initializer !== initializer + ? updateNode(createVariableDeclaration(name, type, initializer), node) + : node; + } + ts.updateVariableDeclaration = updateVariableDeclaration; + function createVariableDeclarationList(declarations, flags) { + if (flags === void 0) { flags = 0; } + var node = createSynthesizedNode(238); + node.flags |= flags & 3; + node.declarations = createNodeArray(declarations); + return node; + } + ts.createVariableDeclarationList = createVariableDeclarationList; + function updateVariableDeclarationList(node, declarations) { + return node.declarations !== declarations + ? updateNode(createVariableDeclarationList(declarations, node.flags), node) + : node; + } + ts.updateVariableDeclarationList = updateVariableDeclarationList; + function createFunctionDeclaration(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body) { + var node = createSynthesizedNode(239); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.asteriskToken = asteriskToken; + node.name = asName(name); + node.typeParameters = asNodeArray(typeParameters); + node.parameters = createNodeArray(parameters); + node.type = type; + node.body = body; + return node; + } + ts.createFunctionDeclaration = createFunctionDeclaration; + function updateFunctionDeclaration(node, decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.asteriskToken !== asteriskToken + || node.name !== name + || node.typeParameters !== typeParameters + || node.parameters !== parameters + || node.type !== type + || node.body !== body + ? updateNode(createFunctionDeclaration(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body), node) + : node; + } + ts.updateFunctionDeclaration = updateFunctionDeclaration; + function createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) { + var node = createSynthesizedNode(240); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.name = asName(name); + node.typeParameters = asNodeArray(typeParameters); + node.heritageClauses = asNodeArray(heritageClauses); + node.members = createNodeArray(members); + return node; + } + ts.createClassDeclaration = createClassDeclaration; + function updateClassDeclaration(node, decorators, modifiers, name, typeParameters, heritageClauses, members) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.name !== name + || node.typeParameters !== typeParameters + || node.heritageClauses !== heritageClauses + || node.members !== members + ? updateNode(createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members), node) + : node; + } + ts.updateClassDeclaration = updateClassDeclaration; + function createInterfaceDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) { + var node = createSynthesizedNode(241); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.name = asName(name); + node.typeParameters = asNodeArray(typeParameters); + node.heritageClauses = asNodeArray(heritageClauses); + node.members = createNodeArray(members); + return node; + } + ts.createInterfaceDeclaration = createInterfaceDeclaration; + function updateInterfaceDeclaration(node, decorators, modifiers, name, typeParameters, heritageClauses, members) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.name !== name + || node.typeParameters !== typeParameters + || node.heritageClauses !== heritageClauses + || node.members !== members + ? updateNode(createInterfaceDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members), node) + : node; + } + ts.updateInterfaceDeclaration = updateInterfaceDeclaration; + function createTypeAliasDeclaration(decorators, modifiers, name, typeParameters, type) { + var node = createSynthesizedNode(242); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.name = asName(name); + node.typeParameters = asNodeArray(typeParameters); + node.type = type; + return node; + } + ts.createTypeAliasDeclaration = createTypeAliasDeclaration; + function updateTypeAliasDeclaration(node, decorators, modifiers, name, typeParameters, type) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.name !== name + || node.typeParameters !== typeParameters + || node.type !== type + ? updateNode(createTypeAliasDeclaration(decorators, modifiers, name, typeParameters, type), node) + : node; + } + ts.updateTypeAliasDeclaration = updateTypeAliasDeclaration; + function createEnumDeclaration(decorators, modifiers, name, members) { + var node = createSynthesizedNode(243); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.name = asName(name); + node.members = createNodeArray(members); + return node; + } + ts.createEnumDeclaration = createEnumDeclaration; + function updateEnumDeclaration(node, decorators, modifiers, name, members) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.name !== name + || node.members !== members + ? updateNode(createEnumDeclaration(decorators, modifiers, name, members), node) + : node; + } + ts.updateEnumDeclaration = updateEnumDeclaration; + function createModuleDeclaration(decorators, modifiers, name, body, flags) { + if (flags === void 0) { flags = 0; } + var node = createSynthesizedNode(244); + node.flags |= flags & (16 | 4 | 512); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.name = name; + node.body = body; + return node; + } + ts.createModuleDeclaration = createModuleDeclaration; + function updateModuleDeclaration(node, decorators, modifiers, name, body) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.name !== name + || node.body !== body + ? updateNode(createModuleDeclaration(decorators, modifiers, name, body, node.flags), node) + : node; + } + ts.updateModuleDeclaration = updateModuleDeclaration; + function createModuleBlock(statements) { + var node = createSynthesizedNode(245); + node.statements = createNodeArray(statements); + return node; + } + ts.createModuleBlock = createModuleBlock; + function updateModuleBlock(node, statements) { + return node.statements !== statements + ? updateNode(createModuleBlock(statements), node) + : node; + } + ts.updateModuleBlock = updateModuleBlock; + function createCaseBlock(clauses) { + var node = createSynthesizedNode(246); + node.clauses = createNodeArray(clauses); + return node; + } + ts.createCaseBlock = createCaseBlock; + function updateCaseBlock(node, clauses) { + return node.clauses !== clauses + ? updateNode(createCaseBlock(clauses), node) + : node; + } + ts.updateCaseBlock = updateCaseBlock; + function createNamespaceExportDeclaration(name) { + var node = createSynthesizedNode(247); + node.name = asName(name); + return node; + } + ts.createNamespaceExportDeclaration = createNamespaceExportDeclaration; + function updateNamespaceExportDeclaration(node, name) { + return node.name !== name + ? updateNode(createNamespaceExportDeclaration(name), node) + : node; + } + ts.updateNamespaceExportDeclaration = updateNamespaceExportDeclaration; + function createImportEqualsDeclaration(decorators, modifiers, name, moduleReference) { + var node = createSynthesizedNode(248); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.name = asName(name); + node.moduleReference = moduleReference; + return node; + } + ts.createImportEqualsDeclaration = createImportEqualsDeclaration; + function updateImportEqualsDeclaration(node, decorators, modifiers, name, moduleReference) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.name !== name + || node.moduleReference !== moduleReference + ? updateNode(createImportEqualsDeclaration(decorators, modifiers, name, moduleReference), node) + : node; + } + ts.updateImportEqualsDeclaration = updateImportEqualsDeclaration; + function createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier) { + var node = createSynthesizedNode(249); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.importClause = importClause; + node.moduleSpecifier = moduleSpecifier; + return node; + } + ts.createImportDeclaration = createImportDeclaration; + function updateImportDeclaration(node, decorators, modifiers, importClause, moduleSpecifier) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.importClause !== importClause + || node.moduleSpecifier !== moduleSpecifier + ? updateNode(createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier), node) + : node; + } + ts.updateImportDeclaration = updateImportDeclaration; + function createImportClause(name, namedBindings) { + var node = createSynthesizedNode(250); + node.name = name; + node.namedBindings = namedBindings; + return node; + } + ts.createImportClause = createImportClause; + function updateImportClause(node, name, namedBindings) { + return node.name !== name + || node.namedBindings !== namedBindings + ? updateNode(createImportClause(name, namedBindings), node) + : node; + } + ts.updateImportClause = updateImportClause; + function createNamespaceImport(name) { + var node = createSynthesizedNode(251); + node.name = name; + return node; + } + ts.createNamespaceImport = createNamespaceImport; + function updateNamespaceImport(node, name) { + return node.name !== name + ? updateNode(createNamespaceImport(name), node) + : node; + } + ts.updateNamespaceImport = updateNamespaceImport; + function createNamedImports(elements) { + var node = createSynthesizedNode(252); + node.elements = createNodeArray(elements); + return node; + } + ts.createNamedImports = createNamedImports; + function updateNamedImports(node, elements) { + return node.elements !== elements + ? updateNode(createNamedImports(elements), node) + : node; + } + ts.updateNamedImports = updateNamedImports; + function createImportSpecifier(propertyName, name) { + var node = createSynthesizedNode(253); + node.propertyName = propertyName; + node.name = name; + return node; + } + ts.createImportSpecifier = createImportSpecifier; + function updateImportSpecifier(node, propertyName, name) { + return node.propertyName !== propertyName + || node.name !== name + ? updateNode(createImportSpecifier(propertyName, name), node) + : node; + } + ts.updateImportSpecifier = updateImportSpecifier; + function createExportAssignment(decorators, modifiers, isExportEquals, expression) { + var node = createSynthesizedNode(254); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.isExportEquals = isExportEquals; + node.expression = isExportEquals ? ts.parenthesizeBinaryOperand(59, expression, false, undefined) : ts.parenthesizeDefaultExpression(expression); + return node; + } + ts.createExportAssignment = createExportAssignment; + function updateExportAssignment(node, decorators, modifiers, expression) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.expression !== expression + ? updateNode(createExportAssignment(decorators, modifiers, node.isExportEquals, expression), node) + : node; + } + ts.updateExportAssignment = updateExportAssignment; + function createExportDeclaration(decorators, modifiers, exportClause, moduleSpecifier) { + var node = createSynthesizedNode(255); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.exportClause = exportClause; + node.moduleSpecifier = moduleSpecifier; + return node; + } + ts.createExportDeclaration = createExportDeclaration; + function updateExportDeclaration(node, decorators, modifiers, exportClause, moduleSpecifier) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.exportClause !== exportClause + || node.moduleSpecifier !== moduleSpecifier + ? updateNode(createExportDeclaration(decorators, modifiers, exportClause, moduleSpecifier), node) + : node; + } + ts.updateExportDeclaration = updateExportDeclaration; + function createNamedExports(elements) { + var node = createSynthesizedNode(256); + node.elements = createNodeArray(elements); + return node; + } + ts.createNamedExports = createNamedExports; + function updateNamedExports(node, elements) { + return node.elements !== elements + ? updateNode(createNamedExports(elements), node) + : node; + } + ts.updateNamedExports = updateNamedExports; + function createExportSpecifier(propertyName, name) { + var node = createSynthesizedNode(257); + node.propertyName = asName(propertyName); + node.name = asName(name); + return node; + } + ts.createExportSpecifier = createExportSpecifier; + function updateExportSpecifier(node, propertyName, name) { + return node.propertyName !== propertyName + || node.name !== name + ? updateNode(createExportSpecifier(propertyName, name), node) + : node; + } + ts.updateExportSpecifier = updateExportSpecifier; + function createExternalModuleReference(expression) { + var node = createSynthesizedNode(259); + node.expression = expression; + return node; + } + ts.createExternalModuleReference = createExternalModuleReference; + function updateExternalModuleReference(node, expression) { + return node.expression !== expression + ? updateNode(createExternalModuleReference(expression), node) + : node; + } + ts.updateExternalModuleReference = updateExternalModuleReference; + function createJSDocTypeExpression(type) { + var node = createSynthesizedNode(283); + node.type = type; + return node; + } + ts.createJSDocTypeExpression = createJSDocTypeExpression; + function createJSDocTypeTag(typeExpression, comment) { + var tag = createJSDocTag(302, "type"); + tag.typeExpression = typeExpression; + tag.comment = comment; + return tag; + } + ts.createJSDocTypeTag = createJSDocTypeTag; + function createJSDocReturnTag(typeExpression, comment) { + var tag = createJSDocTag(300, "returns"); + tag.typeExpression = typeExpression; + tag.comment = comment; + return tag; + } + ts.createJSDocReturnTag = createJSDocReturnTag; + function createJSDocParamTag(name, isBracketed, typeExpression, comment) { + var tag = createJSDocTag(299, "param"); + tag.typeExpression = typeExpression; + tag.name = name; + tag.isBracketed = isBracketed; + tag.comment = comment; + return tag; + } + ts.createJSDocParamTag = createJSDocParamTag; + function createJSDocComment(comment, tags) { + var node = createSynthesizedNode(291); + node.comment = comment; + node.tags = tags; + return node; + } + ts.createJSDocComment = createJSDocComment; + function createJSDocTag(kind, tagName) { + var node = createSynthesizedNode(kind); + node.tagName = createIdentifier(tagName); + return node; + } + function createJsxElement(openingElement, children, closingElement) { + var node = createSynthesizedNode(260); + node.openingElement = openingElement; + node.children = createNodeArray(children); + node.closingElement = closingElement; + return node; + } + ts.createJsxElement = createJsxElement; + function updateJsxElement(node, openingElement, children, closingElement) { + return node.openingElement !== openingElement + || node.children !== children + || node.closingElement !== closingElement + ? updateNode(createJsxElement(openingElement, children, closingElement), node) + : node; + } + ts.updateJsxElement = updateJsxElement; + function createJsxSelfClosingElement(tagName, typeArguments, attributes) { + var node = createSynthesizedNode(261); + node.tagName = tagName; + node.typeArguments = asNodeArray(typeArguments); + node.attributes = attributes; + return node; + } + ts.createJsxSelfClosingElement = createJsxSelfClosingElement; + function updateJsxSelfClosingElement(node, tagName, typeArguments, attributes) { + return node.tagName !== tagName + || node.typeArguments !== typeArguments + || node.attributes !== attributes + ? updateNode(createJsxSelfClosingElement(tagName, typeArguments, attributes), node) + : node; + } + ts.updateJsxSelfClosingElement = updateJsxSelfClosingElement; + function createJsxOpeningElement(tagName, typeArguments, attributes) { + var node = createSynthesizedNode(262); + node.tagName = tagName; + node.typeArguments = asNodeArray(typeArguments); + node.attributes = attributes; + return node; + } + ts.createJsxOpeningElement = createJsxOpeningElement; + function updateJsxOpeningElement(node, tagName, typeArguments, attributes) { + return node.tagName !== tagName + || node.typeArguments !== typeArguments + || node.attributes !== attributes + ? updateNode(createJsxOpeningElement(tagName, typeArguments, attributes), node) + : node; + } + ts.updateJsxOpeningElement = updateJsxOpeningElement; + function createJsxClosingElement(tagName) { + var node = createSynthesizedNode(263); + node.tagName = tagName; + return node; + } + ts.createJsxClosingElement = createJsxClosingElement; + function updateJsxClosingElement(node, tagName) { + return node.tagName !== tagName + ? updateNode(createJsxClosingElement(tagName), node) + : node; + } + ts.updateJsxClosingElement = updateJsxClosingElement; + function createJsxFragment(openingFragment, children, closingFragment) { + var node = createSynthesizedNode(264); + node.openingFragment = openingFragment; + node.children = createNodeArray(children); + node.closingFragment = closingFragment; + return node; + } + ts.createJsxFragment = createJsxFragment; + function updateJsxFragment(node, openingFragment, children, closingFragment) { + return node.openingFragment !== openingFragment + || node.children !== children + || node.closingFragment !== closingFragment + ? updateNode(createJsxFragment(openingFragment, children, closingFragment), node) + : node; + } + ts.updateJsxFragment = updateJsxFragment; + function createJsxAttribute(name, initializer) { + var node = createSynthesizedNode(267); + node.name = name; + node.initializer = initializer; + return node; + } + ts.createJsxAttribute = createJsxAttribute; + function updateJsxAttribute(node, name, initializer) { + return node.name !== name + || node.initializer !== initializer + ? updateNode(createJsxAttribute(name, initializer), node) + : node; + } + ts.updateJsxAttribute = updateJsxAttribute; + function createJsxAttributes(properties) { + var node = createSynthesizedNode(268); + node.properties = createNodeArray(properties); + return node; + } + ts.createJsxAttributes = createJsxAttributes; + function updateJsxAttributes(node, properties) { + return node.properties !== properties + ? updateNode(createJsxAttributes(properties), node) + : node; + } + ts.updateJsxAttributes = updateJsxAttributes; + function createJsxSpreadAttribute(expression) { + var node = createSynthesizedNode(269); + node.expression = expression; + return node; + } + ts.createJsxSpreadAttribute = createJsxSpreadAttribute; + function updateJsxSpreadAttribute(node, expression) { + return node.expression !== expression + ? updateNode(createJsxSpreadAttribute(expression), node) + : node; + } + ts.updateJsxSpreadAttribute = updateJsxSpreadAttribute; + function createJsxExpression(dotDotDotToken, expression) { + var node = createSynthesizedNode(270); + node.dotDotDotToken = dotDotDotToken; + node.expression = expression; + return node; + } + ts.createJsxExpression = createJsxExpression; + function updateJsxExpression(node, expression) { + return node.expression !== expression + ? updateNode(createJsxExpression(node.dotDotDotToken, expression), node) + : node; + } + ts.updateJsxExpression = updateJsxExpression; + function createCaseClause(expression, statements) { + var node = createSynthesizedNode(271); + node.expression = ts.parenthesizeExpressionForList(expression); + node.statements = createNodeArray(statements); + return node; + } + ts.createCaseClause = createCaseClause; + function updateCaseClause(node, expression, statements) { + return node.expression !== expression + || node.statements !== statements + ? updateNode(createCaseClause(expression, statements), node) + : node; + } + ts.updateCaseClause = updateCaseClause; + function createDefaultClause(statements) { + var node = createSynthesizedNode(272); + node.statements = createNodeArray(statements); + return node; + } + ts.createDefaultClause = createDefaultClause; + function updateDefaultClause(node, statements) { + return node.statements !== statements + ? updateNode(createDefaultClause(statements), node) + : node; + } + ts.updateDefaultClause = updateDefaultClause; + function createHeritageClause(token, types) { + var node = createSynthesizedNode(273); + node.token = token; + node.types = createNodeArray(types); + return node; + } + ts.createHeritageClause = createHeritageClause; + function updateHeritageClause(node, types) { + return node.types !== types + ? updateNode(createHeritageClause(node.token, types), node) + : node; + } + ts.updateHeritageClause = updateHeritageClause; + function createCatchClause(variableDeclaration, block) { + var node = createSynthesizedNode(274); + node.variableDeclaration = ts.isString(variableDeclaration) ? createVariableDeclaration(variableDeclaration) : variableDeclaration; + node.block = block; + return node; + } + ts.createCatchClause = createCatchClause; + function updateCatchClause(node, variableDeclaration, block) { + return node.variableDeclaration !== variableDeclaration + || node.block !== block + ? updateNode(createCatchClause(variableDeclaration, block), node) + : node; + } + ts.updateCatchClause = updateCatchClause; + function createPropertyAssignment(name, initializer) { + var node = createSynthesizedNode(275); + node.name = asName(name); + node.questionToken = undefined; + node.initializer = ts.parenthesizeExpressionForList(initializer); + return node; + } + ts.createPropertyAssignment = createPropertyAssignment; + function updatePropertyAssignment(node, name, initializer) { + return node.name !== name + || node.initializer !== initializer + ? updateNode(createPropertyAssignment(name, initializer), node) + : node; + } + ts.updatePropertyAssignment = updatePropertyAssignment; + function createShorthandPropertyAssignment(name, objectAssignmentInitializer) { + var node = createSynthesizedNode(276); + node.name = asName(name); + node.objectAssignmentInitializer = objectAssignmentInitializer !== undefined ? ts.parenthesizeExpressionForList(objectAssignmentInitializer) : undefined; + return node; + } + ts.createShorthandPropertyAssignment = createShorthandPropertyAssignment; + function updateShorthandPropertyAssignment(node, name, objectAssignmentInitializer) { + return node.name !== name + || node.objectAssignmentInitializer !== objectAssignmentInitializer + ? updateNode(createShorthandPropertyAssignment(name, objectAssignmentInitializer), node) + : node; + } + ts.updateShorthandPropertyAssignment = updateShorthandPropertyAssignment; + function createSpreadAssignment(expression) { + var node = createSynthesizedNode(277); + node.expression = expression !== undefined ? ts.parenthesizeExpressionForList(expression) : undefined; + return node; + } + ts.createSpreadAssignment = createSpreadAssignment; + function updateSpreadAssignment(node, expression) { + return node.expression !== expression + ? updateNode(createSpreadAssignment(expression), node) + : node; + } + ts.updateSpreadAssignment = updateSpreadAssignment; + function createEnumMember(name, initializer) { + var node = createSynthesizedNode(278); + node.name = asName(name); + node.initializer = initializer && ts.parenthesizeExpressionForList(initializer); + return node; + } + ts.createEnumMember = createEnumMember; + function updateEnumMember(node, name, initializer) { + return node.name !== name + || node.initializer !== initializer + ? updateNode(createEnumMember(name, initializer), node) + : node; + } + ts.updateEnumMember = updateEnumMember; + function updateSourceFileNode(node, statements, isDeclarationFile, referencedFiles, typeReferences, hasNoDefaultLib, libReferences) { + if (node.statements !== statements || + (isDeclarationFile !== undefined && node.isDeclarationFile !== isDeclarationFile) || + (referencedFiles !== undefined && node.referencedFiles !== referencedFiles) || + (typeReferences !== undefined && node.typeReferenceDirectives !== typeReferences) || + (libReferences !== undefined && node.libReferenceDirectives !== libReferences) || + (hasNoDefaultLib !== undefined && node.hasNoDefaultLib !== hasNoDefaultLib)) { + var updated = createSynthesizedNode(279); + updated.flags |= node.flags; + updated.statements = createNodeArray(statements); + updated.endOfFileToken = node.endOfFileToken; + updated.fileName = node.fileName; + updated.path = node.path; + updated.text = node.text; + updated.isDeclarationFile = isDeclarationFile === undefined ? node.isDeclarationFile : isDeclarationFile; + updated.referencedFiles = referencedFiles === undefined ? node.referencedFiles : referencedFiles; + updated.typeReferenceDirectives = typeReferences === undefined ? node.typeReferenceDirectives : typeReferences; + updated.hasNoDefaultLib = hasNoDefaultLib === undefined ? node.hasNoDefaultLib : hasNoDefaultLib; + updated.libReferenceDirectives = libReferences === undefined ? node.libReferenceDirectives : libReferences; + if (node.amdDependencies !== undefined) + updated.amdDependencies = node.amdDependencies; + if (node.moduleName !== undefined) + updated.moduleName = node.moduleName; + if (node.languageVariant !== undefined) + updated.languageVariant = node.languageVariant; + if (node.renamedDependencies !== undefined) + updated.renamedDependencies = node.renamedDependencies; + if (node.languageVersion !== undefined) + updated.languageVersion = node.languageVersion; + if (node.scriptKind !== undefined) + updated.scriptKind = node.scriptKind; + if (node.externalModuleIndicator !== undefined) + updated.externalModuleIndicator = node.externalModuleIndicator; + if (node.commonJsModuleIndicator !== undefined) + updated.commonJsModuleIndicator = node.commonJsModuleIndicator; + if (node.identifiers !== undefined) + updated.identifiers = node.identifiers; + if (node.nodeCount !== undefined) + updated.nodeCount = node.nodeCount; + if (node.identifierCount !== undefined) + updated.identifierCount = node.identifierCount; + if (node.symbolCount !== undefined) + updated.symbolCount = node.symbolCount; + if (node.parseDiagnostics !== undefined) + updated.parseDiagnostics = node.parseDiagnostics; + if (node.bindDiagnostics !== undefined) + updated.bindDiagnostics = node.bindDiagnostics; + if (node.bindSuggestionDiagnostics !== undefined) + updated.bindSuggestionDiagnostics = node.bindSuggestionDiagnostics; + if (node.lineMap !== undefined) + updated.lineMap = node.lineMap; + if (node.classifiableNames !== undefined) + updated.classifiableNames = node.classifiableNames; + if (node.resolvedModules !== undefined) + updated.resolvedModules = node.resolvedModules; + if (node.resolvedTypeReferenceDirectiveNames !== undefined) + updated.resolvedTypeReferenceDirectiveNames = node.resolvedTypeReferenceDirectiveNames; + if (node.imports !== undefined) + updated.imports = node.imports; + if (node.moduleAugmentations !== undefined) + updated.moduleAugmentations = node.moduleAugmentations; + if (node.pragmas !== undefined) + updated.pragmas = node.pragmas; + if (node.localJsxFactory !== undefined) + updated.localJsxFactory = node.localJsxFactory; + if (node.localJsxNamespace !== undefined) + updated.localJsxNamespace = node.localJsxNamespace; + return updateNode(updated, node); + } + return node; + } + ts.updateSourceFileNode = updateSourceFileNode; + function getMutableClone(node) { + var clone = getSynthesizedClone(node); + clone.pos = node.pos; + clone.end = node.end; + clone.parent = node.parent; + return clone; + } + ts.getMutableClone = getMutableClone; + function createNotEmittedStatement(original) { + var node = createSynthesizedNode(307); + node.original = original; + setTextRange(node, original); + return node; + } + ts.createNotEmittedStatement = createNotEmittedStatement; + function createEndOfDeclarationMarker(original) { + var node = createSynthesizedNode(311); + node.emitNode = {}; + node.original = original; + return node; + } + ts.createEndOfDeclarationMarker = createEndOfDeclarationMarker; + function createMergeDeclarationMarker(original) { + var node = createSynthesizedNode(310); + node.emitNode = {}; + node.original = original; + return node; + } + ts.createMergeDeclarationMarker = createMergeDeclarationMarker; + function createPartiallyEmittedExpression(expression, original) { + var node = createSynthesizedNode(308); + node.expression = expression; + node.original = original; + setTextRange(node, original); + return node; + } + ts.createPartiallyEmittedExpression = createPartiallyEmittedExpression; + function updatePartiallyEmittedExpression(node, expression) { + if (node.expression !== expression) { + return updateNode(createPartiallyEmittedExpression(expression, node.original), node); + } + return node; + } + ts.updatePartiallyEmittedExpression = updatePartiallyEmittedExpression; + function flattenCommaElements(node) { + if (ts.nodeIsSynthesized(node) && !ts.isParseTreeNode(node) && !node.original && !node.emitNode && !node.id) { + if (node.kind === 309) { + return node.elements; + } + if (ts.isBinaryExpression(node) && node.operatorToken.kind === 27) { + return [node.left, node.right]; + } + } + return node; + } + function createCommaList(elements) { + var node = createSynthesizedNode(309); + node.elements = createNodeArray(ts.sameFlatMap(elements, flattenCommaElements)); + return node; + } + ts.createCommaList = createCommaList; + function updateCommaList(node, elements) { + return node.elements !== elements + ? updateNode(createCommaList(elements), node) + : node; + } + ts.updateCommaList = updateCommaList; + function createBundle(sourceFiles, prepends) { + if (prepends === void 0) { prepends = ts.emptyArray; } + var node = ts.createNode(280); + node.prepends = prepends; + node.sourceFiles = sourceFiles; + return node; + } + ts.createBundle = createBundle; + function createUnparsedSourceFile(text, mapPath, map) { + var node = ts.createNode(281); + node.text = text; + node.sourceMapPath = mapPath; + node.sourceMapText = map; + return node; + } + ts.createUnparsedSourceFile = createUnparsedSourceFile; + function createInputFiles(javascript, declaration, javascriptMapPath, javascriptMapText, declarationMapPath, declarationMapText) { + var node = ts.createNode(282); + node.javascriptText = javascript; + node.javascriptMapPath = javascriptMapPath; + node.javascriptMapText = javascriptMapText; + node.declarationText = declaration; + node.declarationMapPath = declarationMapPath; + node.declarationMapText = declarationMapText; + return node; + } + ts.createInputFiles = createInputFiles; + function updateBundle(node, sourceFiles, prepends) { + if (prepends === void 0) { prepends = ts.emptyArray; } + if (node.sourceFiles !== sourceFiles || node.prepends !== prepends) { + return createBundle(sourceFiles, prepends); + } + return node; + } + ts.updateBundle = updateBundle; + function createImmediatelyInvokedFunctionExpression(statements, param, paramValue) { + return createCall(createFunctionExpression(undefined, undefined, undefined, undefined, param ? [param] : [], undefined, createBlock(statements, true)), undefined, paramValue ? [paramValue] : []); + } + ts.createImmediatelyInvokedFunctionExpression = createImmediatelyInvokedFunctionExpression; + function createImmediatelyInvokedArrowFunction(statements, param, paramValue) { + return createCall(createArrowFunction(undefined, undefined, param ? [param] : [], undefined, undefined, createBlock(statements, true)), undefined, paramValue ? [paramValue] : []); + } + ts.createImmediatelyInvokedArrowFunction = createImmediatelyInvokedArrowFunction; + function createComma(left, right) { + return createBinary(left, 27, right); + } + ts.createComma = createComma; + function createLessThan(left, right) { + return createBinary(left, 28, right); + } + ts.createLessThan = createLessThan; + function createAssignment(left, right) { + return createBinary(left, 59, right); + } + ts.createAssignment = createAssignment; + function createStrictEquality(left, right) { + return createBinary(left, 35, right); + } + ts.createStrictEquality = createStrictEquality; + function createStrictInequality(left, right) { + return createBinary(left, 36, right); + } + ts.createStrictInequality = createStrictInequality; + function createAdd(left, right) { + return createBinary(left, 38, right); + } + ts.createAdd = createAdd; + function createSubtract(left, right) { + return createBinary(left, 39, right); + } + ts.createSubtract = createSubtract; + function createPostfixIncrement(operand) { + return createPostfix(operand, 44); + } + ts.createPostfixIncrement = createPostfixIncrement; + function createLogicalAnd(left, right) { + return createBinary(left, 54, right); + } + ts.createLogicalAnd = createLogicalAnd; + function createLogicalOr(left, right) { + return createBinary(left, 55, right); + } + ts.createLogicalOr = createLogicalOr; + function createLogicalNot(operand) { + return createPrefix(52, operand); + } + ts.createLogicalNot = createLogicalNot; + function createVoidZero() { + return createVoid(createLiteral(0)); + } + ts.createVoidZero = createVoidZero; + function createExportDefault(expression) { + return createExportAssignment(undefined, undefined, false, expression); + } + ts.createExportDefault = createExportDefault; + function createExternalModuleExport(exportName) { + return createExportDeclaration(undefined, undefined, createNamedExports([createExportSpecifier(undefined, exportName)])); + } + ts.createExternalModuleExport = createExternalModuleExport; + function asName(name) { + return ts.isString(name) ? createIdentifier(name) : name; + } + function asExpression(value) { + return ts.isString(value) || typeof value === "number" ? createLiteral(value) : value; + } + function asNodeArray(array) { + return array ? createNodeArray(array) : undefined; + } + function asToken(value) { + return typeof value === "number" ? createToken(value) : value; + } + function disposeEmitNodes(sourceFile) { + sourceFile = ts.getSourceFileOfNode(ts.getParseTreeNode(sourceFile)); + var emitNode = sourceFile && sourceFile.emitNode; + var annotatedNodes = emitNode && emitNode.annotatedNodes; + if (annotatedNodes) { + for (var _i = 0, annotatedNodes_1 = annotatedNodes; _i < annotatedNodes_1.length; _i++) { + var node = annotatedNodes_1[_i]; + node.emitNode = undefined; + } + } + } + ts.disposeEmitNodes = disposeEmitNodes; + function getOrCreateEmitNode(node) { + if (!node.emitNode) { + if (ts.isParseTreeNode(node)) { + if (node.kind === 279) { + return node.emitNode = { annotatedNodes: [node] }; + } + var sourceFile = ts.getSourceFileOfNode(node); + getOrCreateEmitNode(sourceFile).annotatedNodes.push(node); + } + node.emitNode = {}; + } + return node.emitNode; + } + ts.getOrCreateEmitNode = getOrCreateEmitNode; + function setTextRange(range, location) { + if (location) { + range.pos = location.pos; + range.end = location.end; + } + return range; + } + ts.setTextRange = setTextRange; + function setEmitFlags(node, emitFlags) { + getOrCreateEmitNode(node).flags = emitFlags; + return node; + } + ts.setEmitFlags = setEmitFlags; + function addEmitFlags(node, emitFlags) { + var emitNode = getOrCreateEmitNode(node); + emitNode.flags = emitNode.flags | emitFlags; + return node; + } + ts.addEmitFlags = addEmitFlags; + function getSourceMapRange(node) { + var emitNode = node.emitNode; + return (emitNode && emitNode.sourceMapRange) || node; + } + ts.getSourceMapRange = getSourceMapRange; + function setSourceMapRange(node, range) { + getOrCreateEmitNode(node).sourceMapRange = range; + return node; + } + ts.setSourceMapRange = setSourceMapRange; + var SourceMapSource; + function createSourceMapSource(fileName, text, skipTrivia) { + return new (SourceMapSource || (SourceMapSource = ts.objectAllocator.getSourceMapSourceConstructor()))(fileName, text, skipTrivia); + } + ts.createSourceMapSource = createSourceMapSource; + function getTokenSourceMapRange(node, token) { + var emitNode = node.emitNode; + var tokenSourceMapRanges = emitNode && emitNode.tokenSourceMapRanges; + return tokenSourceMapRanges && tokenSourceMapRanges[token]; + } + ts.getTokenSourceMapRange = getTokenSourceMapRange; + function setTokenSourceMapRange(node, token, range) { + var emitNode = getOrCreateEmitNode(node); + var tokenSourceMapRanges = emitNode.tokenSourceMapRanges || (emitNode.tokenSourceMapRanges = []); + tokenSourceMapRanges[token] = range; + return node; + } + ts.setTokenSourceMapRange = setTokenSourceMapRange; + function getStartsOnNewLine(node) { + var emitNode = node.emitNode; + return emitNode && emitNode.startsOnNewLine; + } + ts.getStartsOnNewLine = getStartsOnNewLine; + function setStartsOnNewLine(node, newLine) { + getOrCreateEmitNode(node).startsOnNewLine = newLine; + return node; + } + ts.setStartsOnNewLine = setStartsOnNewLine; + function getCommentRange(node) { + var emitNode = node.emitNode; + return (emitNode && emitNode.commentRange) || node; + } + ts.getCommentRange = getCommentRange; + function setCommentRange(node, range) { + getOrCreateEmitNode(node).commentRange = range; + return node; + } + ts.setCommentRange = setCommentRange; + function getSyntheticLeadingComments(node) { + var emitNode = node.emitNode; + return emitNode && emitNode.leadingComments; + } + ts.getSyntheticLeadingComments = getSyntheticLeadingComments; + function setSyntheticLeadingComments(node, comments) { + getOrCreateEmitNode(node).leadingComments = comments; + return node; + } + ts.setSyntheticLeadingComments = setSyntheticLeadingComments; + function addSyntheticLeadingComment(node, kind, text, hasTrailingNewLine) { + return setSyntheticLeadingComments(node, ts.append(getSyntheticLeadingComments(node), { kind: kind, pos: -1, end: -1, hasTrailingNewLine: hasTrailingNewLine, text: text })); + } + ts.addSyntheticLeadingComment = addSyntheticLeadingComment; + function getSyntheticTrailingComments(node) { + var emitNode = node.emitNode; + return emitNode && emitNode.trailingComments; + } + ts.getSyntheticTrailingComments = getSyntheticTrailingComments; + function setSyntheticTrailingComments(node, comments) { + getOrCreateEmitNode(node).trailingComments = comments; + return node; + } + ts.setSyntheticTrailingComments = setSyntheticTrailingComments; + function addSyntheticTrailingComment(node, kind, text, hasTrailingNewLine) { + return setSyntheticTrailingComments(node, ts.append(getSyntheticTrailingComments(node), { kind: kind, pos: -1, end: -1, hasTrailingNewLine: hasTrailingNewLine, text: text })); + } + ts.addSyntheticTrailingComment = addSyntheticTrailingComment; + function moveSyntheticComments(node, original) { + setSyntheticLeadingComments(node, getSyntheticLeadingComments(original)); + setSyntheticTrailingComments(node, getSyntheticTrailingComments(original)); + var emit = getOrCreateEmitNode(original); + emit.leadingComments = undefined; + emit.trailingComments = undefined; + return node; + } + ts.moveSyntheticComments = moveSyntheticComments; + function getConstantValue(node) { + var emitNode = node.emitNode; + return emitNode && emitNode.constantValue; + } + ts.getConstantValue = getConstantValue; + function setConstantValue(node, value) { + var emitNode = getOrCreateEmitNode(node); + emitNode.constantValue = value; + return node; + } + ts.setConstantValue = setConstantValue; + function addEmitHelper(node, helper) { + var emitNode = getOrCreateEmitNode(node); + emitNode.helpers = ts.append(emitNode.helpers, helper); + return node; + } + ts.addEmitHelper = addEmitHelper; + function addEmitHelpers(node, helpers) { + if (ts.some(helpers)) { + var emitNode = getOrCreateEmitNode(node); + for (var _i = 0, helpers_1 = helpers; _i < helpers_1.length; _i++) { + var helper = helpers_1[_i]; + emitNode.helpers = ts.appendIfUnique(emitNode.helpers, helper); + } + } + return node; + } + ts.addEmitHelpers = addEmitHelpers; + function removeEmitHelper(node, helper) { + var emitNode = node.emitNode; + if (emitNode) { + var helpers = emitNode.helpers; + if (helpers) { + return ts.orderedRemoveItem(helpers, helper); + } + } + return false; + } + ts.removeEmitHelper = removeEmitHelper; + function getEmitHelpers(node) { + var emitNode = node.emitNode; + return emitNode && emitNode.helpers; + } + ts.getEmitHelpers = getEmitHelpers; + function moveEmitHelpers(source, target, predicate) { + var sourceEmitNode = source.emitNode; + var sourceEmitHelpers = sourceEmitNode && sourceEmitNode.helpers; + if (!ts.some(sourceEmitHelpers)) + return; + var targetEmitNode = getOrCreateEmitNode(target); + var helpersRemoved = 0; + for (var i = 0; i < sourceEmitHelpers.length; i++) { + var helper = sourceEmitHelpers[i]; + if (predicate(helper)) { + helpersRemoved++; + targetEmitNode.helpers = ts.appendIfUnique(targetEmitNode.helpers, helper); + } + else if (helpersRemoved > 0) { + sourceEmitHelpers[i - helpersRemoved] = helper; + } + } + if (helpersRemoved > 0) { + sourceEmitHelpers.length -= helpersRemoved; + } + } + ts.moveEmitHelpers = moveEmitHelpers; + function compareEmitHelpers(x, y) { + if (x === y) + return 0; + if (x.priority === y.priority) + return 0; + if (x.priority === undefined) + return 1; + if (y.priority === undefined) + return -1; + return ts.compareValues(x.priority, y.priority); + } + ts.compareEmitHelpers = compareEmitHelpers; + function setOriginalNode(node, original) { + node.original = original; + if (original) { + var emitNode = original.emitNode; + if (emitNode) + node.emitNode = mergeEmitNode(emitNode, node.emitNode); + } + return node; + } + ts.setOriginalNode = setOriginalNode; + function mergeEmitNode(sourceEmitNode, destEmitNode) { + var flags = sourceEmitNode.flags, leadingComments = sourceEmitNode.leadingComments, trailingComments = sourceEmitNode.trailingComments, commentRange = sourceEmitNode.commentRange, sourceMapRange = sourceEmitNode.sourceMapRange, tokenSourceMapRanges = sourceEmitNode.tokenSourceMapRanges, constantValue = sourceEmitNode.constantValue, helpers = sourceEmitNode.helpers, startsOnNewLine = sourceEmitNode.startsOnNewLine; + if (!destEmitNode) + destEmitNode = {}; + if (leadingComments) + destEmitNode.leadingComments = ts.addRange(leadingComments.slice(), destEmitNode.leadingComments); + if (trailingComments) + destEmitNode.trailingComments = ts.addRange(trailingComments.slice(), destEmitNode.trailingComments); + if (flags) + destEmitNode.flags = flags; + if (commentRange) + destEmitNode.commentRange = commentRange; + if (sourceMapRange) + destEmitNode.sourceMapRange = sourceMapRange; + if (tokenSourceMapRanges) + destEmitNode.tokenSourceMapRanges = mergeTokenSourceMapRanges(tokenSourceMapRanges, destEmitNode.tokenSourceMapRanges); + if (constantValue !== undefined) + destEmitNode.constantValue = constantValue; + if (helpers) + destEmitNode.helpers = ts.addRange(destEmitNode.helpers, helpers); + if (startsOnNewLine !== undefined) + destEmitNode.startsOnNewLine = startsOnNewLine; + return destEmitNode; + } + function mergeTokenSourceMapRanges(sourceRanges, destRanges) { + if (!destRanges) + destRanges = []; + for (var key in sourceRanges) { + destRanges[key] = sourceRanges[key]; + } + return destRanges; + } +})(ts || (ts = {})); +(function (ts) { + ts.nullTransformationContext = { + enableEmitNotification: ts.noop, + enableSubstitution: ts.noop, + endLexicalEnvironment: function () { return undefined; }, + getCompilerOptions: ts.notImplemented, + getEmitHost: ts.notImplemented, + getEmitResolver: ts.notImplemented, + hoistFunctionDeclaration: ts.noop, + hoistVariableDeclaration: ts.noop, + isEmitNotificationEnabled: ts.notImplemented, + isSubstitutionEnabled: ts.notImplemented, + onEmitNode: ts.noop, + onSubstituteNode: ts.notImplemented, + readEmitHelpers: ts.notImplemented, + requestEmitHelper: ts.noop, + resumeLexicalEnvironment: ts.noop, + startLexicalEnvironment: ts.noop, + suspendLexicalEnvironment: ts.noop, + addDiagnostic: ts.noop, + }; + function createTypeCheck(value, tag) { + return tag === "undefined" + ? ts.createStrictEquality(value, ts.createVoidZero()) + : ts.createStrictEquality(ts.createTypeOf(value), ts.createLiteral(tag)); + } + ts.createTypeCheck = createTypeCheck; + function createMemberAccessForPropertyName(target, memberName, location) { + if (ts.isComputedPropertyName(memberName)) { + return ts.setTextRange(ts.createElementAccess(target, memberName.expression), location); + } + else { + var expression = ts.setTextRange(ts.isIdentifier(memberName) + ? ts.createPropertyAccess(target, memberName) + : ts.createElementAccess(target, memberName), memberName); + ts.getOrCreateEmitNode(expression).flags |= 64; + return expression; + } + } + ts.createMemberAccessForPropertyName = createMemberAccessForPropertyName; + function createFunctionCall(func, thisArg, argumentsList, location) { + return ts.setTextRange(ts.createCall(ts.createPropertyAccess(func, "call"), undefined, [ + thisArg + ].concat(argumentsList)), location); + } + ts.createFunctionCall = createFunctionCall; + function createFunctionApply(func, thisArg, argumentsExpression, location) { + return ts.setTextRange(ts.createCall(ts.createPropertyAccess(func, "apply"), undefined, [ + thisArg, + argumentsExpression + ]), location); + } + ts.createFunctionApply = createFunctionApply; + function createArraySlice(array, start) { + var argumentsList = []; + if (start !== undefined) { + argumentsList.push(typeof start === "number" ? ts.createLiteral(start) : start); + } + return ts.createCall(ts.createPropertyAccess(array, "slice"), undefined, argumentsList); + } + ts.createArraySlice = createArraySlice; + function createArrayConcat(array, values) { + return ts.createCall(ts.createPropertyAccess(array, "concat"), undefined, values); + } + ts.createArrayConcat = createArrayConcat; + function createMathPow(left, right, location) { + return ts.setTextRange(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Math"), "pow"), undefined, [left, right]), location); + } + ts.createMathPow = createMathPow; + function createReactNamespace(reactNamespace, parent) { + var react = ts.createIdentifier(reactNamespace || "React"); + react.flags &= ~8; + react.parent = ts.getParseTreeNode(parent); + return react; + } + function createJsxFactoryExpressionFromEntityName(jsxFactory, parent) { + if (ts.isQualifiedName(jsxFactory)) { + var left = createJsxFactoryExpressionFromEntityName(jsxFactory.left, parent); + var right = ts.createIdentifier(ts.idText(jsxFactory.right)); + right.escapedText = jsxFactory.right.escapedText; + return ts.createPropertyAccess(left, right); + } + else { + return createReactNamespace(ts.idText(jsxFactory), parent); + } + } + function createJsxFactoryExpression(jsxFactoryEntity, reactNamespace, parent) { + return jsxFactoryEntity ? + createJsxFactoryExpressionFromEntityName(jsxFactoryEntity, parent) : + ts.createPropertyAccess(createReactNamespace(reactNamespace, parent), "createElement"); + } + function createExpressionForJsxElement(jsxFactoryEntity, reactNamespace, tagName, props, children, parentElement, location) { + var argumentsList = [tagName]; + if (props) { + argumentsList.push(props); + } + if (children && children.length > 0) { + if (!props) { + argumentsList.push(ts.createNull()); + } + if (children.length > 1) { + for (var _i = 0, children_1 = children; _i < children_1.length; _i++) { + var child = children_1[_i]; + startOnNewLine(child); + argumentsList.push(child); + } + } + else { + argumentsList.push(children[0]); + } + } + return ts.setTextRange(ts.createCall(createJsxFactoryExpression(jsxFactoryEntity, reactNamespace, parentElement), undefined, argumentsList), location); + } + ts.createExpressionForJsxElement = createExpressionForJsxElement; + function createExpressionForJsxFragment(jsxFactoryEntity, reactNamespace, children, parentElement, location) { + var tagName = ts.createPropertyAccess(createReactNamespace(reactNamespace, parentElement), "Fragment"); + var argumentsList = [tagName]; + argumentsList.push(ts.createNull()); + if (children && children.length > 0) { + if (children.length > 1) { + for (var _i = 0, children_2 = children; _i < children_2.length; _i++) { + var child = children_2[_i]; + startOnNewLine(child); + argumentsList.push(child); + } + } + else { + argumentsList.push(children[0]); + } + } + return ts.setTextRange(ts.createCall(createJsxFactoryExpression(jsxFactoryEntity, reactNamespace, parentElement), undefined, argumentsList), location); + } + ts.createExpressionForJsxFragment = createExpressionForJsxFragment; + function getHelperName(name) { + return ts.setEmitFlags(ts.createIdentifier(name), 4096 | 2); + } + ts.getHelperName = getHelperName; + var valuesHelper = { + name: "typescript:values", + scoped: false, + text: "\n var __values = (this && this.__values) || function (o) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator], i = 0;\n if (m) return m.call(o);\n return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n };" + }; + function createValuesHelper(context, expression, location) { + context.requestEmitHelper(valuesHelper); + return ts.setTextRange(ts.createCall(getHelperName("__values"), undefined, [expression]), location); + } + ts.createValuesHelper = createValuesHelper; + var readHelper = { + name: "typescript:read", + scoped: false, + text: "\n var __read = (this && this.__read) || function (o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m) return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n }\n catch (error) { e = { error: error }; }\n finally {\n try {\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\n }\n finally { if (e) throw e.error; }\n }\n return ar;\n };" + }; + function createReadHelper(context, iteratorRecord, count, location) { + context.requestEmitHelper(readHelper); + return ts.setTextRange(ts.createCall(getHelperName("__read"), undefined, count !== undefined + ? [iteratorRecord, ts.createLiteral(count)] + : [iteratorRecord]), location); + } + ts.createReadHelper = createReadHelper; + var spreadHelper = { + name: "typescript:spread", + scoped: false, + text: "\n var __spread = (this && this.__spread) || function () {\n for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i]));\n return ar;\n };" + }; + function createSpreadHelper(context, argumentList, location) { + context.requestEmitHelper(readHelper); + context.requestEmitHelper(spreadHelper); + return ts.setTextRange(ts.createCall(getHelperName("__spread"), undefined, argumentList), location); + } + ts.createSpreadHelper = createSpreadHelper; + function createForOfBindingStatement(node, boundValue) { + if (ts.isVariableDeclarationList(node)) { + var firstDeclaration = ts.first(node.declarations); + var updatedDeclaration = ts.updateVariableDeclaration(firstDeclaration, firstDeclaration.name, undefined, boundValue); + return ts.setTextRange(ts.createVariableStatement(undefined, ts.updateVariableDeclarationList(node, [updatedDeclaration])), node); + } + else { + var updatedExpression = ts.setTextRange(ts.createAssignment(node, boundValue), node); + return ts.setTextRange(ts.createStatement(updatedExpression), node); + } + } + ts.createForOfBindingStatement = createForOfBindingStatement; + function insertLeadingStatement(dest, source) { + if (ts.isBlock(dest)) { + return ts.updateBlock(dest, ts.setTextRange(ts.createNodeArray([source].concat(dest.statements)), dest.statements)); + } + else { + return ts.createBlock(ts.createNodeArray([dest, source]), true); + } + } + ts.insertLeadingStatement = insertLeadingStatement; + function restoreEnclosingLabel(node, outermostLabeledStatement, afterRestoreLabelCallback) { + if (!outermostLabeledStatement) { + return node; + } + var updated = ts.updateLabel(outermostLabeledStatement, outermostLabeledStatement.label, outermostLabeledStatement.statement.kind === 233 + ? restoreEnclosingLabel(node, outermostLabeledStatement.statement) + : node); + if (afterRestoreLabelCallback) { + afterRestoreLabelCallback(outermostLabeledStatement); + } + return updated; + } + ts.restoreEnclosingLabel = restoreEnclosingLabel; + function shouldBeCapturedInTempVariable(node, cacheIdentifiers) { + var target = ts.skipParentheses(node); + switch (target.kind) { + case 72: + return cacheIdentifiers; + case 100: + case 8: + case 9: + case 10: + return false; + case 187: + var elements = target.elements; + if (elements.length === 0) { + return false; + } + return true; + case 188: + return target.properties.length > 0; + default: + return true; + } + } + function createCallBinding(expression, recordTempVariable, languageVersion, cacheIdentifiers) { + if (cacheIdentifiers === void 0) { cacheIdentifiers = false; } + var callee = skipOuterExpressions(expression, 7); + var thisArg; + var target; + if (ts.isSuperProperty(callee)) { + thisArg = ts.createThis(); + target = callee; + } + else if (callee.kind === 98) { + thisArg = ts.createThis(); + target = languageVersion < 2 + ? ts.setTextRange(ts.createIdentifier("_super"), callee) + : callee; + } + else if (ts.getEmitFlags(callee) & 4096) { + thisArg = ts.createVoidZero(); + target = parenthesizeForAccess(callee); + } + else { + switch (callee.kind) { + case 189: { + if (shouldBeCapturedInTempVariable(callee.expression, cacheIdentifiers)) { + thisArg = ts.createTempVariable(recordTempVariable); + target = ts.createPropertyAccess(ts.setTextRange(ts.createAssignment(thisArg, callee.expression), callee.expression), callee.name); + ts.setTextRange(target, callee); + } + else { + thisArg = callee.expression; + target = callee; + } + break; + } + case 190: { + if (shouldBeCapturedInTempVariable(callee.expression, cacheIdentifiers)) { + thisArg = ts.createTempVariable(recordTempVariable); + target = ts.createElementAccess(ts.setTextRange(ts.createAssignment(thisArg, callee.expression), callee.expression), callee.argumentExpression); + ts.setTextRange(target, callee); + } + else { + thisArg = callee.expression; + target = callee; + } + break; + } + default: { + thisArg = ts.createVoidZero(); + target = parenthesizeForAccess(expression); + break; + } + } + } + return { target: target, thisArg: thisArg }; + } + ts.createCallBinding = createCallBinding; + function inlineExpressions(expressions) { + return expressions.length > 10 + ? ts.createCommaList(expressions) + : ts.reduceLeft(expressions, ts.createComma); + } + ts.inlineExpressions = inlineExpressions; + function createExpressionFromEntityName(node) { + if (ts.isQualifiedName(node)) { + var left = createExpressionFromEntityName(node.left); + var right = ts.getMutableClone(node.right); + return ts.setTextRange(ts.createPropertyAccess(left, right), node); + } + else { + return ts.getMutableClone(node); + } + } + ts.createExpressionFromEntityName = createExpressionFromEntityName; + function createExpressionForPropertyName(memberName) { + if (ts.isIdentifier(memberName)) { + return ts.createLiteral(memberName); + } + else if (ts.isComputedPropertyName(memberName)) { + return ts.getMutableClone(memberName.expression); + } + else { + return ts.getMutableClone(memberName); + } + } + ts.createExpressionForPropertyName = createExpressionForPropertyName; + function createExpressionForObjectLiteralElementLike(node, property, receiver) { + switch (property.kind) { + case 158: + case 159: + return createExpressionForAccessorDeclaration(node.properties, property, receiver, !!node.multiLine); + case 275: + return createExpressionForPropertyAssignment(property, receiver); + case 276: + return createExpressionForShorthandPropertyAssignment(property, receiver); + case 156: + return createExpressionForMethodDeclaration(property, receiver); + } + } + ts.createExpressionForObjectLiteralElementLike = createExpressionForObjectLiteralElementLike; + function createExpressionForAccessorDeclaration(properties, property, receiver, multiLine) { + var _a = ts.getAllAccessorDeclarations(properties, property), firstAccessor = _a.firstAccessor, getAccessor = _a.getAccessor, setAccessor = _a.setAccessor; + if (property === firstAccessor) { + var properties_8 = []; + if (getAccessor) { + var getterFunction = ts.createFunctionExpression(getAccessor.modifiers, undefined, undefined, undefined, getAccessor.parameters, undefined, getAccessor.body); + ts.setTextRange(getterFunction, getAccessor); + ts.setOriginalNode(getterFunction, getAccessor); + var getter = ts.createPropertyAssignment("get", getterFunction); + properties_8.push(getter); + } + if (setAccessor) { + var setterFunction = ts.createFunctionExpression(setAccessor.modifiers, undefined, undefined, undefined, setAccessor.parameters, undefined, setAccessor.body); + ts.setTextRange(setterFunction, setAccessor); + ts.setOriginalNode(setterFunction, setAccessor); + var setter = ts.createPropertyAssignment("set", setterFunction); + properties_8.push(setter); + } + properties_8.push(ts.createPropertyAssignment("enumerable", ts.createTrue())); + properties_8.push(ts.createPropertyAssignment("configurable", ts.createTrue())); + var expression = ts.setTextRange(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"), undefined, [ + receiver, + createExpressionForPropertyName(property.name), + ts.createObjectLiteral(properties_8, multiLine) + ]), firstAccessor); + return ts.aggregateTransformFlags(expression); + } + return undefined; + } + function createExpressionForPropertyAssignment(property, receiver) { + return ts.aggregateTransformFlags(ts.setOriginalNode(ts.setTextRange(ts.createAssignment(createMemberAccessForPropertyName(receiver, property.name, property.name), property.initializer), property), property)); + } + function createExpressionForShorthandPropertyAssignment(property, receiver) { + return ts.aggregateTransformFlags(ts.setOriginalNode(ts.setTextRange(ts.createAssignment(createMemberAccessForPropertyName(receiver, property.name, property.name), ts.getSynthesizedClone(property.name)), property), property)); + } + function createExpressionForMethodDeclaration(method, receiver) { + return ts.aggregateTransformFlags(ts.setOriginalNode(ts.setTextRange(ts.createAssignment(createMemberAccessForPropertyName(receiver, method.name, method.name), ts.setOriginalNode(ts.setTextRange(ts.createFunctionExpression(method.modifiers, method.asteriskToken, undefined, undefined, method.parameters, undefined, method.body), method), method)), method), method)); + } + function getInternalName(node, allowComments, allowSourceMaps) { + return getName(node, allowComments, allowSourceMaps, 16384 | 32768); + } + ts.getInternalName = getInternalName; + function isInternalName(node) { + return (ts.getEmitFlags(node) & 32768) !== 0; + } + ts.isInternalName = isInternalName; + function getLocalName(node, allowComments, allowSourceMaps) { + return getName(node, allowComments, allowSourceMaps, 16384); + } + ts.getLocalName = getLocalName; + function isLocalName(node) { + return (ts.getEmitFlags(node) & 16384) !== 0; + } + ts.isLocalName = isLocalName; + function getExportName(node, allowComments, allowSourceMaps) { + return getName(node, allowComments, allowSourceMaps, 8192); + } + ts.getExportName = getExportName; + function isExportName(node) { + return (ts.getEmitFlags(node) & 8192) !== 0; + } + ts.isExportName = isExportName; + function getDeclarationName(node, allowComments, allowSourceMaps) { + return getName(node, allowComments, allowSourceMaps); + } + ts.getDeclarationName = getDeclarationName; + function getName(node, allowComments, allowSourceMaps, emitFlags) { + if (emitFlags === void 0) { emitFlags = 0; } + var nodeName = ts.getNameOfDeclaration(node); + if (nodeName && ts.isIdentifier(nodeName) && !ts.isGeneratedIdentifier(nodeName)) { + var name = ts.getMutableClone(nodeName); + emitFlags |= ts.getEmitFlags(nodeName); + if (!allowSourceMaps) + emitFlags |= 48; + if (!allowComments) + emitFlags |= 1536; + if (emitFlags) + ts.setEmitFlags(name, emitFlags); + return name; + } + return ts.getGeneratedNameForNode(node); + } + function getExternalModuleOrNamespaceExportName(ns, node, allowComments, allowSourceMaps) { + if (ns && ts.hasModifier(node, 1)) { + return getNamespaceMemberName(ns, getName(node), allowComments, allowSourceMaps); + } + return getExportName(node, allowComments, allowSourceMaps); + } + ts.getExternalModuleOrNamespaceExportName = getExternalModuleOrNamespaceExportName; + function getNamespaceMemberName(ns, name, allowComments, allowSourceMaps) { + var qualifiedName = ts.createPropertyAccess(ns, ts.nodeIsSynthesized(name) ? name : ts.getSynthesizedClone(name)); + ts.setTextRange(qualifiedName, name); + var emitFlags = 0; + if (!allowSourceMaps) + emitFlags |= 48; + if (!allowComments) + emitFlags |= 1536; + if (emitFlags) + ts.setEmitFlags(qualifiedName, emitFlags); + return qualifiedName; + } + ts.getNamespaceMemberName = getNamespaceMemberName; + function convertToFunctionBody(node, multiLine) { + return ts.isBlock(node) ? node : ts.setTextRange(ts.createBlock([ts.setTextRange(ts.createReturn(node), node)], multiLine), node); + } + ts.convertToFunctionBody = convertToFunctionBody; + function convertFunctionDeclarationToExpression(node) { + if (!node.body) + return ts.Debug.fail(); + var updated = ts.createFunctionExpression(node.modifiers, node.asteriskToken, node.name, node.typeParameters, node.parameters, node.type, node.body); + ts.setOriginalNode(updated, node); + ts.setTextRange(updated, node); + if (ts.getStartsOnNewLine(node)) { + ts.setStartsOnNewLine(updated, true); + } + ts.aggregateTransformFlags(updated); + return updated; + } + ts.convertFunctionDeclarationToExpression = convertFunctionDeclarationToExpression; + function isUseStrictPrologue(node) { + return ts.isStringLiteral(node.expression) && node.expression.text === "use strict"; + } + function addPrologue(target, source, ensureUseStrict, visitor) { + var offset = addStandardPrologue(target, source, ensureUseStrict); + return addCustomPrologue(target, source, offset, visitor); + } + ts.addPrologue = addPrologue; + function addStandardPrologue(target, source, ensureUseStrict) { + ts.Debug.assert(target.length === 0, "Prologue directives should be at the first statement in the target statements array"); + var foundUseStrict = false; + var statementOffset = 0; + var numStatements = source.length; + while (statementOffset < numStatements) { + var statement = source[statementOffset]; + if (ts.isPrologueDirective(statement)) { + if (isUseStrictPrologue(statement)) { + foundUseStrict = true; + } + target.push(statement); + } + else { + break; + } + statementOffset++; + } + if (ensureUseStrict && !foundUseStrict) { + target.push(startOnNewLine(ts.createStatement(ts.createLiteral("use strict")))); + } + return statementOffset; + } + ts.addStandardPrologue = addStandardPrologue; + function addCustomPrologue(target, source, statementOffset, visitor) { + var numStatements = source.length; + while (statementOffset !== undefined && statementOffset < numStatements) { + var statement = source[statementOffset]; + if (ts.getEmitFlags(statement) & 1048576) { + ts.append(target, visitor ? ts.visitNode(statement, visitor, ts.isStatement) : statement); + } + else { + break; + } + statementOffset++; + } + return statementOffset; + } + ts.addCustomPrologue = addCustomPrologue; + function findUseStrictPrologue(statements) { + for (var _i = 0, statements_3 = statements; _i < statements_3.length; _i++) { + var statement = statements_3[_i]; + if (ts.isPrologueDirective(statement)) { + if (isUseStrictPrologue(statement)) { + return statement; + } + } + else { + break; + } + } + return undefined; + } + ts.findUseStrictPrologue = findUseStrictPrologue; + function startsWithUseStrict(statements) { + var firstStatement = ts.firstOrUndefined(statements); + return firstStatement !== undefined + && ts.isPrologueDirective(firstStatement) + && isUseStrictPrologue(firstStatement); + } + ts.startsWithUseStrict = startsWithUseStrict; + function ensureUseStrict(statements) { + var foundUseStrict = findUseStrictPrologue(statements); + if (!foundUseStrict) { + return ts.setTextRange(ts.createNodeArray([ + startOnNewLine(ts.createStatement(ts.createLiteral("use strict"))) + ].concat(statements)), statements); + } + return statements; + } + ts.ensureUseStrict = ensureUseStrict; + function parenthesizeBinaryOperand(binaryOperator, operand, isLeftSideOfBinary, leftOperand) { + var skipped = ts.skipPartiallyEmittedExpressions(operand); + if (skipped.kind === 195) { + return operand; + } + return binaryOperandNeedsParentheses(binaryOperator, operand, isLeftSideOfBinary, leftOperand) + ? ts.createParen(operand) + : operand; + } + ts.parenthesizeBinaryOperand = parenthesizeBinaryOperand; + function binaryOperandNeedsParentheses(binaryOperator, operand, isLeftSideOfBinary, leftOperand) { + var binaryOperatorPrecedence = ts.getOperatorPrecedence(204, binaryOperator); + var binaryOperatorAssociativity = ts.getOperatorAssociativity(204, binaryOperator); + var emittedOperand = ts.skipPartiallyEmittedExpressions(operand); + if (!isLeftSideOfBinary && operand.kind === 197 && binaryOperatorPrecedence > 4) { + return true; + } + var operandPrecedence = ts.getExpressionPrecedence(emittedOperand); + switch (ts.compareValues(operandPrecedence, binaryOperatorPrecedence)) { + case -1: + if (!isLeftSideOfBinary + && binaryOperatorAssociativity === 1 + && operand.kind === 207) { + return false; + } + return true; + case 1: + return false; + case 0: + if (isLeftSideOfBinary) { + return binaryOperatorAssociativity === 1; + } + else { + if (ts.isBinaryExpression(emittedOperand) + && emittedOperand.operatorToken.kind === binaryOperator) { + if (operatorHasAssociativeProperty(binaryOperator)) { + return false; + } + if (binaryOperator === 38) { + var leftKind = leftOperand ? getLiteralKindOfBinaryPlusOperand(leftOperand) : 0; + if (ts.isLiteralKind(leftKind) && leftKind === getLiteralKindOfBinaryPlusOperand(emittedOperand)) { + return false; + } + } + } + var operandAssociativity = ts.getExpressionAssociativity(emittedOperand); + return operandAssociativity === 0; + } + } + } + function operatorHasAssociativeProperty(binaryOperator) { + return binaryOperator === 40 + || binaryOperator === 50 + || binaryOperator === 49 + || binaryOperator === 51; + } + function getLiteralKindOfBinaryPlusOperand(node) { + node = ts.skipPartiallyEmittedExpressions(node); + if (ts.isLiteralKind(node.kind)) { + return node.kind; + } + if (node.kind === 204 && node.operatorToken.kind === 38) { + if (node.cachedLiteralKind !== undefined) { + return node.cachedLiteralKind; + } + var leftKind = getLiteralKindOfBinaryPlusOperand(node.left); + var literalKind = ts.isLiteralKind(leftKind) + && leftKind === getLiteralKindOfBinaryPlusOperand(node.right) + ? leftKind + : 0; + node.cachedLiteralKind = literalKind; + return literalKind; + } + return 0; + } + function parenthesizeForConditionalHead(condition) { + var conditionalPrecedence = ts.getOperatorPrecedence(205, 56); + var emittedCondition = ts.skipPartiallyEmittedExpressions(condition); + var conditionPrecedence = ts.getExpressionPrecedence(emittedCondition); + if (ts.compareValues(conditionPrecedence, conditionalPrecedence) === -1) { + return ts.createParen(condition); + } + return condition; + } + ts.parenthesizeForConditionalHead = parenthesizeForConditionalHead; + function parenthesizeSubexpressionOfConditionalExpression(e) { + var emittedExpression = ts.skipPartiallyEmittedExpressions(e); + return isCommaSequence(emittedExpression) + ? ts.createParen(e) + : e; + } + ts.parenthesizeSubexpressionOfConditionalExpression = parenthesizeSubexpressionOfConditionalExpression; + function parenthesizeDefaultExpression(e) { + var check = ts.skipPartiallyEmittedExpressions(e); + var needsParens = isCommaSequence(check); + if (!needsParens) { + switch (getLeftmostExpression(check, false).kind) { + case 209: + case 196: + needsParens = true; + } + } + return needsParens ? ts.createParen(e) : e; + } + ts.parenthesizeDefaultExpression = parenthesizeDefaultExpression; + function parenthesizeForNew(expression) { + var leftmostExpr = getLeftmostExpression(expression, true); + switch (leftmostExpr.kind) { + case 191: + return ts.createParen(expression); + case 192: + return !leftmostExpr.arguments + ? ts.createParen(expression) + : expression; + } + return parenthesizeForAccess(expression); + } + ts.parenthesizeForNew = parenthesizeForNew; + function parenthesizeForAccess(expression) { + var emittedExpression = ts.skipPartiallyEmittedExpressions(expression); + if (ts.isLeftHandSideExpression(emittedExpression) + && (emittedExpression.kind !== 192 || emittedExpression.arguments)) { + return expression; + } + return ts.setTextRange(ts.createParen(expression), expression); + } + ts.parenthesizeForAccess = parenthesizeForAccess; + function parenthesizePostfixOperand(operand) { + return ts.isLeftHandSideExpression(operand) + ? operand + : ts.setTextRange(ts.createParen(operand), operand); + } + ts.parenthesizePostfixOperand = parenthesizePostfixOperand; + function parenthesizePrefixOperand(operand) { + return ts.isUnaryExpression(operand) + ? operand + : ts.setTextRange(ts.createParen(operand), operand); + } + ts.parenthesizePrefixOperand = parenthesizePrefixOperand; + function parenthesizeListElements(elements) { + var result; + for (var i = 0; i < elements.length; i++) { + var element = parenthesizeExpressionForList(elements[i]); + if (result !== undefined || element !== elements[i]) { + if (result === undefined) { + result = elements.slice(0, i); + } + result.push(element); + } + } + if (result !== undefined) { + return ts.setTextRange(ts.createNodeArray(result, elements.hasTrailingComma), elements); + } + return elements; + } + ts.parenthesizeListElements = parenthesizeListElements; + function parenthesizeExpressionForList(expression) { + var emittedExpression = ts.skipPartiallyEmittedExpressions(expression); + var expressionPrecedence = ts.getExpressionPrecedence(emittedExpression); + var commaPrecedence = ts.getOperatorPrecedence(204, 27); + return expressionPrecedence > commaPrecedence + ? expression + : ts.setTextRange(ts.createParen(expression), expression); + } + ts.parenthesizeExpressionForList = parenthesizeExpressionForList; + function parenthesizeExpressionForExpressionStatement(expression) { + var emittedExpression = ts.skipPartiallyEmittedExpressions(expression); + if (ts.isCallExpression(emittedExpression)) { + var callee = emittedExpression.expression; + var kind = ts.skipPartiallyEmittedExpressions(callee).kind; + if (kind === 196 || kind === 197) { + var mutableCall = ts.getMutableClone(emittedExpression); + mutableCall.expression = ts.setTextRange(ts.createParen(callee), callee); + return recreateOuterExpressions(expression, mutableCall, 4); + } + } + var leftmostExpressionKind = getLeftmostExpression(emittedExpression, false).kind; + if (leftmostExpressionKind === 188 || leftmostExpressionKind === 196) { + return ts.setTextRange(ts.createParen(expression), expression); + } + return expression; + } + ts.parenthesizeExpressionForExpressionStatement = parenthesizeExpressionForExpressionStatement; + function parenthesizeConditionalTypeMember(member) { + return member.kind === 175 ? ts.createParenthesizedType(member) : member; + } + ts.parenthesizeConditionalTypeMember = parenthesizeConditionalTypeMember; + function parenthesizeElementTypeMember(member) { + switch (member.kind) { + case 173: + case 174: + case 165: + case 166: + return ts.createParenthesizedType(member); + } + return parenthesizeConditionalTypeMember(member); + } + ts.parenthesizeElementTypeMember = parenthesizeElementTypeMember; + function parenthesizeArrayTypeMember(member) { + switch (member.kind) { + case 167: + case 179: + case 176: + return ts.createParenthesizedType(member); + } + return parenthesizeElementTypeMember(member); + } + ts.parenthesizeArrayTypeMember = parenthesizeArrayTypeMember; + function parenthesizeElementTypeMembers(members) { + return ts.createNodeArray(ts.sameMap(members, parenthesizeElementTypeMember)); + } + ts.parenthesizeElementTypeMembers = parenthesizeElementTypeMembers; + function parenthesizeTypeParameters(typeParameters) { + if (ts.some(typeParameters)) { + var params = []; + for (var i = 0; i < typeParameters.length; ++i) { + var entry = typeParameters[i]; + params.push(i === 0 && ts.isFunctionOrConstructorTypeNode(entry) && entry.typeParameters ? + ts.createParenthesizedType(entry) : + entry); + } + return ts.createNodeArray(params); + } + } + ts.parenthesizeTypeParameters = parenthesizeTypeParameters; + function getLeftmostExpression(node, stopAtCallExpressions) { + while (true) { + switch (node.kind) { + case 203: + node = node.operand; + continue; + case 204: + node = node.left; + continue; + case 205: + node = node.condition; + continue; + case 193: + node = node.tag; + continue; + case 191: + if (stopAtCallExpressions) { + return node; + } + case 212: + case 190: + case 189: + case 213: + case 308: + node = node.expression; + continue; + } + return node; + } + } + function parenthesizeConciseBody(body) { + if (!ts.isBlock(body) && (isCommaSequence(body) || getLeftmostExpression(body, false).kind === 188)) { + return ts.setTextRange(ts.createParen(body), body); + } + return body; + } + ts.parenthesizeConciseBody = parenthesizeConciseBody; + function isCommaSequence(node) { + return node.kind === 204 && node.operatorToken.kind === 27 || + node.kind === 309; + } + ts.isCommaSequence = isCommaSequence; + function isOuterExpression(node, kinds) { + if (kinds === void 0) { kinds = 7; } + switch (node.kind) { + case 195: + return (kinds & 1) !== 0; + case 194: + case 212: + case 213: + return (kinds & 2) !== 0; + case 308: + return (kinds & 4) !== 0; + } + return false; + } + ts.isOuterExpression = isOuterExpression; + function skipOuterExpressions(node, kinds) { + if (kinds === void 0) { kinds = 7; } + var previousNode; + do { + previousNode = node; + if (kinds & 1) { + node = ts.skipParentheses(node); + } + if (kinds & 2) { + node = skipAssertions(node); + } + if (kinds & 4) { + node = ts.skipPartiallyEmittedExpressions(node); + } + } while (previousNode !== node); + return node; + } + ts.skipOuterExpressions = skipOuterExpressions; + function skipAssertions(node) { + while (ts.isAssertionExpression(node) || node.kind === 213) { + node = node.expression; + } + return node; + } + ts.skipAssertions = skipAssertions; + function updateOuterExpression(outerExpression, expression) { + switch (outerExpression.kind) { + case 195: return ts.updateParen(outerExpression, expression); + case 194: return ts.updateTypeAssertion(outerExpression, outerExpression.type, expression); + case 212: return ts.updateAsExpression(outerExpression, expression, outerExpression.type); + case 213: return ts.updateNonNullExpression(outerExpression, expression); + case 308: return ts.updatePartiallyEmittedExpression(outerExpression, expression); + } + } + function isIgnorableParen(node) { + return node.kind === 195 + && ts.nodeIsSynthesized(node) + && ts.nodeIsSynthesized(ts.getSourceMapRange(node)) + && ts.nodeIsSynthesized(ts.getCommentRange(node)) + && !ts.some(ts.getSyntheticLeadingComments(node)) + && !ts.some(ts.getSyntheticTrailingComments(node)); + } + function recreateOuterExpressions(outerExpression, innerExpression, kinds) { + if (kinds === void 0) { kinds = 7; } + if (outerExpression && isOuterExpression(outerExpression, kinds) && !isIgnorableParen(outerExpression)) { + return updateOuterExpression(outerExpression, recreateOuterExpressions(outerExpression.expression, innerExpression)); + } + return innerExpression; + } + ts.recreateOuterExpressions = recreateOuterExpressions; + function startOnNewLine(node) { + return ts.setStartsOnNewLine(node, true); + } + ts.startOnNewLine = startOnNewLine; + function getExternalHelpersModuleName(node) { + var parseNode = ts.getOriginalNode(node, ts.isSourceFile); + var emitNode = parseNode && parseNode.emitNode; + return emitNode && emitNode.externalHelpersModuleName; + } + ts.getExternalHelpersModuleName = getExternalHelpersModuleName; + function getOrCreateExternalHelpersModuleNameIfNeeded(node, compilerOptions, hasExportStarsToExportValues, hasImportStarOrImportDefault) { + if (compilerOptions.importHelpers && ts.isEffectiveExternalModule(node, compilerOptions)) { + var externalHelpersModuleName = getExternalHelpersModuleName(node); + if (externalHelpersModuleName) { + return externalHelpersModuleName; + } + var moduleKind = ts.getEmitModuleKind(compilerOptions); + var create = (hasExportStarsToExportValues || (compilerOptions.esModuleInterop && hasImportStarOrImportDefault)) + && moduleKind !== ts.ModuleKind.System + && moduleKind !== ts.ModuleKind.ES2015 + && moduleKind !== ts.ModuleKind.ESNext; + if (!create) { + var helpers = ts.getEmitHelpers(node); + if (helpers) { + for (var _i = 0, helpers_2 = helpers; _i < helpers_2.length; _i++) { + var helper = helpers_2[_i]; + if (!helper.scoped) { + create = true; + break; + } + } + } + } + if (create) { + var parseNode = ts.getOriginalNode(node, ts.isSourceFile); + var emitNode = ts.getOrCreateEmitNode(parseNode); + return emitNode.externalHelpersModuleName || (emitNode.externalHelpersModuleName = ts.createUniqueName(ts.externalHelpersModuleNameText)); + } + } + } + ts.getOrCreateExternalHelpersModuleNameIfNeeded = getOrCreateExternalHelpersModuleNameIfNeeded; + function getLocalNameForExternalImport(node, sourceFile) { + var namespaceDeclaration = ts.getNamespaceDeclarationNode(node); + if (namespaceDeclaration && !ts.isDefaultImport(node)) { + var name = namespaceDeclaration.name; + return ts.isGeneratedIdentifier(name) ? name : ts.createIdentifier(ts.getSourceTextOfNodeFromSourceFile(sourceFile, name) || ts.idText(name)); + } + if (node.kind === 249 && node.importClause) { + return ts.getGeneratedNameForNode(node); + } + if (node.kind === 255 && node.moduleSpecifier) { + return ts.getGeneratedNameForNode(node); + } + return undefined; + } + ts.getLocalNameForExternalImport = getLocalNameForExternalImport; + function getExternalModuleNameLiteral(importNode, sourceFile, host, resolver, compilerOptions) { + var moduleName = ts.getExternalModuleName(importNode); + if (moduleName.kind === 10) { + return tryGetModuleNameFromDeclaration(importNode, host, resolver, compilerOptions) + || tryRenameExternalModule(moduleName, sourceFile) + || ts.getSynthesizedClone(moduleName); + } + return undefined; + } + ts.getExternalModuleNameLiteral = getExternalModuleNameLiteral; + function tryRenameExternalModule(moduleName, sourceFile) { + var rename = sourceFile.renamedDependencies && sourceFile.renamedDependencies.get(moduleName.text); + return rename && ts.createLiteral(rename); + } + function tryGetModuleNameFromFile(file, host, options) { + if (!file) { + return undefined; + } + if (file.moduleName) { + return ts.createLiteral(file.moduleName); + } + if (!file.isDeclarationFile && (options.out || options.outFile)) { + return ts.createLiteral(ts.getExternalModuleNameFromPath(host, file.fileName)); + } + return undefined; + } + ts.tryGetModuleNameFromFile = tryGetModuleNameFromFile; + function tryGetModuleNameFromDeclaration(declaration, host, resolver, compilerOptions) { + return tryGetModuleNameFromFile(resolver.getExternalModuleFileFromDeclaration(declaration), host, compilerOptions); + } + function getInitializerOfBindingOrAssignmentElement(bindingElement) { + if (ts.isDeclarationBindingElement(bindingElement)) { + return bindingElement.initializer; + } + if (ts.isPropertyAssignment(bindingElement)) { + var initializer = bindingElement.initializer; + return ts.isAssignmentExpression(initializer, true) + ? initializer.right + : undefined; + } + if (ts.isShorthandPropertyAssignment(bindingElement)) { + return bindingElement.objectAssignmentInitializer; + } + if (ts.isAssignmentExpression(bindingElement, true)) { + return bindingElement.right; + } + if (ts.isSpreadElement(bindingElement)) { + return getInitializerOfBindingOrAssignmentElement(bindingElement.expression); + } + } + ts.getInitializerOfBindingOrAssignmentElement = getInitializerOfBindingOrAssignmentElement; + function getTargetOfBindingOrAssignmentElement(bindingElement) { + if (ts.isDeclarationBindingElement(bindingElement)) { + return bindingElement.name; + } + if (ts.isObjectLiteralElementLike(bindingElement)) { + switch (bindingElement.kind) { + case 275: + return getTargetOfBindingOrAssignmentElement(bindingElement.initializer); + case 276: + return bindingElement.name; + case 277: + return getTargetOfBindingOrAssignmentElement(bindingElement.expression); + } + return undefined; + } + if (ts.isAssignmentExpression(bindingElement, true)) { + return getTargetOfBindingOrAssignmentElement(bindingElement.left); + } + if (ts.isSpreadElement(bindingElement)) { + return getTargetOfBindingOrAssignmentElement(bindingElement.expression); + } + return bindingElement; + } + ts.getTargetOfBindingOrAssignmentElement = getTargetOfBindingOrAssignmentElement; + function getRestIndicatorOfBindingOrAssignmentElement(bindingElement) { + switch (bindingElement.kind) { + case 151: + case 186: + return bindingElement.dotDotDotToken; + case 208: + case 277: + return bindingElement; + } + return undefined; + } + ts.getRestIndicatorOfBindingOrAssignmentElement = getRestIndicatorOfBindingOrAssignmentElement; + function getPropertyNameOfBindingOrAssignmentElement(bindingElement) { + switch (bindingElement.kind) { + case 186: + if (bindingElement.propertyName) { + var propertyName = bindingElement.propertyName; + return ts.isComputedPropertyName(propertyName) && isStringOrNumericLiteral(propertyName.expression) + ? propertyName.expression + : propertyName; + } + break; + case 275: + if (bindingElement.name) { + var propertyName = bindingElement.name; + return ts.isComputedPropertyName(propertyName) && isStringOrNumericLiteral(propertyName.expression) + ? propertyName.expression + : propertyName; + } + break; + case 277: + return bindingElement.name; + } + var target = getTargetOfBindingOrAssignmentElement(bindingElement); + if (target && ts.isPropertyName(target)) { + return ts.isComputedPropertyName(target) && isStringOrNumericLiteral(target.expression) + ? target.expression + : target; + } + ts.Debug.fail("Invalid property name for binding element."); + } + ts.getPropertyNameOfBindingOrAssignmentElement = getPropertyNameOfBindingOrAssignmentElement; + function isStringOrNumericLiteral(node) { + var kind = node.kind; + return kind === 10 + || kind === 8; + } + function getElementsOfBindingOrAssignmentPattern(name) { + switch (name.kind) { + case 184: + case 185: + case 187: + return name.elements; + case 188: + return name.properties; + } + } + ts.getElementsOfBindingOrAssignmentPattern = getElementsOfBindingOrAssignmentPattern; + function convertToArrayAssignmentElement(element) { + if (ts.isBindingElement(element)) { + if (element.dotDotDotToken) { + ts.Debug.assertNode(element.name, ts.isIdentifier); + return ts.setOriginalNode(ts.setTextRange(ts.createSpread(element.name), element), element); + } + var expression = convertToAssignmentElementTarget(element.name); + return element.initializer + ? ts.setOriginalNode(ts.setTextRange(ts.createAssignment(expression, element.initializer), element), element) + : expression; + } + ts.Debug.assertNode(element, ts.isExpression); + return element; + } + ts.convertToArrayAssignmentElement = convertToArrayAssignmentElement; + function convertToObjectAssignmentElement(element) { + if (ts.isBindingElement(element)) { + if (element.dotDotDotToken) { + ts.Debug.assertNode(element.name, ts.isIdentifier); + return ts.setOriginalNode(ts.setTextRange(ts.createSpreadAssignment(element.name), element), element); + } + if (element.propertyName) { + var expression = convertToAssignmentElementTarget(element.name); + return ts.setOriginalNode(ts.setTextRange(ts.createPropertyAssignment(element.propertyName, element.initializer ? ts.createAssignment(expression, element.initializer) : expression), element), element); + } + ts.Debug.assertNode(element.name, ts.isIdentifier); + return ts.setOriginalNode(ts.setTextRange(ts.createShorthandPropertyAssignment(element.name, element.initializer), element), element); + } + ts.Debug.assertNode(element, ts.isObjectLiteralElementLike); + return element; + } + ts.convertToObjectAssignmentElement = convertToObjectAssignmentElement; + function convertToAssignmentPattern(node) { + switch (node.kind) { + case 185: + case 187: + return convertToArrayAssignmentPattern(node); + case 184: + case 188: + return convertToObjectAssignmentPattern(node); + } + } + ts.convertToAssignmentPattern = convertToAssignmentPattern; + function convertToObjectAssignmentPattern(node) { + if (ts.isObjectBindingPattern(node)) { + return ts.setOriginalNode(ts.setTextRange(ts.createObjectLiteral(ts.map(node.elements, convertToObjectAssignmentElement)), node), node); + } + ts.Debug.assertNode(node, ts.isObjectLiteralExpression); + return node; + } + ts.convertToObjectAssignmentPattern = convertToObjectAssignmentPattern; + function convertToArrayAssignmentPattern(node) { + if (ts.isArrayBindingPattern(node)) { + return ts.setOriginalNode(ts.setTextRange(ts.createArrayLiteral(ts.map(node.elements, convertToArrayAssignmentElement)), node), node); + } + ts.Debug.assertNode(node, ts.isArrayLiteralExpression); + return node; + } + ts.convertToArrayAssignmentPattern = convertToArrayAssignmentPattern; + function convertToAssignmentElementTarget(node) { + if (ts.isBindingPattern(node)) { + return convertToAssignmentPattern(node); + } + ts.Debug.assertNode(node, ts.isExpression); + return node; + } + ts.convertToAssignmentElementTarget = convertToAssignmentElementTarget; +})(ts || (ts = {})); +var ts; +(function (ts) { + var isTypeNodeOrTypeParameterDeclaration = ts.or(ts.isTypeNode, ts.isTypeParameterDeclaration); + function visitNode(node, visitor, test, lift) { + if (node === undefined || visitor === undefined) { + return node; + } + ts.aggregateTransformFlags(node); + var visited = visitor(node); + if (visited === node) { + return node; + } + var visitedNode; + if (visited === undefined) { + return undefined; + } + else if (ts.isArray(visited)) { + visitedNode = (lift || extractSingleNode)(visited); + } + else { + visitedNode = visited; + } + ts.Debug.assertNode(visitedNode, test); + ts.aggregateTransformFlags(visitedNode); + return visitedNode; + } + ts.visitNode = visitNode; + function visitNodes(nodes, visitor, test, start, count) { + if (nodes === undefined || visitor === undefined) { + return nodes; + } + var updated; + var length = nodes.length; + if (start === undefined || start < 0) { + start = 0; + } + if (count === undefined || count > length - start) { + count = length - start; + } + if (start > 0 || count < length) { + updated = ts.createNodeArray([], nodes.hasTrailingComma && start + count === length); + } + for (var i = 0; i < count; i++) { + var node = nodes[i + start]; + ts.aggregateTransformFlags(node); + var visited = node !== undefined ? visitor(node) : undefined; + if (updated !== undefined || visited === undefined || visited !== node) { + if (updated === undefined) { + updated = ts.createNodeArray(nodes.slice(0, i), nodes.hasTrailingComma); + ts.setTextRange(updated, nodes); + } + if (visited) { + if (ts.isArray(visited)) { + for (var _i = 0, visited_1 = visited; _i < visited_1.length; _i++) { + var visitedNode = visited_1[_i]; + ts.Debug.assertNode(visitedNode, test); + ts.aggregateTransformFlags(visitedNode); + updated.push(visitedNode); + } + } + else { + ts.Debug.assertNode(visited, test); + ts.aggregateTransformFlags(visited); + updated.push(visited); + } + } + } + } + return updated || nodes; + } + ts.visitNodes = visitNodes; + function visitLexicalEnvironment(statements, visitor, context, start, ensureUseStrict) { + context.startLexicalEnvironment(); + statements = visitNodes(statements, visitor, ts.isStatement, start); + if (ensureUseStrict && !ts.startsWithUseStrict(statements)) { + statements = ts.setTextRange(ts.createNodeArray([ts.createExpressionStatement(ts.createLiteral("use strict"))].concat(statements)), statements); + } + var declarations = context.endLexicalEnvironment(); + return ts.setTextRange(ts.createNodeArray(ts.concatenate(declarations, statements)), statements); + } + ts.visitLexicalEnvironment = visitLexicalEnvironment; + function visitParameterList(nodes, visitor, context, nodesVisitor) { + if (nodesVisitor === void 0) { nodesVisitor = visitNodes; } + context.startLexicalEnvironment(); + var updated = nodesVisitor(nodes, visitor, ts.isParameterDeclaration); + context.suspendLexicalEnvironment(); + return updated; + } + ts.visitParameterList = visitParameterList; + function visitFunctionBody(node, visitor, context) { + context.resumeLexicalEnvironment(); + var updated = visitNode(node, visitor, ts.isConciseBody); + var declarations = context.endLexicalEnvironment(); + if (ts.some(declarations)) { + var block = ts.convertToFunctionBody(updated); + var statements = ts.mergeLexicalEnvironment(block.statements, declarations); + return ts.updateBlock(block, statements); + } + return updated; + } + ts.visitFunctionBody = visitFunctionBody; + function visitEachChild(node, visitor, context, nodesVisitor, tokenVisitor) { + if (nodesVisitor === void 0) { nodesVisitor = visitNodes; } + if (node === undefined) { + return undefined; + } + var kind = node.kind; + if ((kind > 0 && kind <= 147) || kind === 178) { + return node; + } + switch (kind) { + case 72: + return ts.updateIdentifier(node, nodesVisitor(node.typeArguments, visitor, isTypeNodeOrTypeParameterDeclaration)); + case 148: + return ts.updateQualifiedName(node, visitNode(node.left, visitor, ts.isEntityName), visitNode(node.right, visitor, ts.isIdentifier)); + case 149: + return ts.updateComputedPropertyName(node, visitNode(node.expression, visitor, ts.isExpression)); + case 150: + return ts.updateTypeParameterDeclaration(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.constraint, visitor, ts.isTypeNode), visitNode(node.default, visitor, ts.isTypeNode)); + case 151: + return ts.updateParameter(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.dotDotDotToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isBindingName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); + case 152: + return ts.updateDecorator(node, visitNode(node.expression, visitor, ts.isExpression)); + case 153: + return ts.updatePropertySignature(node, nodesVisitor(node.modifiers, visitor, ts.isToken), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); + case 154: + return ts.updateProperty(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); + case 155: + return ts.updateMethodSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken)); + case 156: + return ts.updateMethod(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); + case 157: + return ts.updateConstructor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context)); + case 158: + return ts.updateGetAccessor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); + case 159: + return ts.updateSetAccessor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context)); + case 160: + return ts.updateCallSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); + case 161: + return ts.updateConstructSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); + case 162: + return ts.updateIndexSignature(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); + case 163: + return ts.updateTypePredicateNode(node, visitNode(node.parameterName, visitor), visitNode(node.type, visitor, ts.isTypeNode)); + case 164: + return ts.updateTypeReferenceNode(node, visitNode(node.typeName, visitor, ts.isEntityName), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode)); + case 165: + return ts.updateFunctionTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); + case 166: + return ts.updateConstructorTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); + case 167: + return ts.updateTypeQueryNode(node, visitNode(node.exprName, visitor, ts.isEntityName)); + case 168: + return ts.updateTypeLiteralNode(node, nodesVisitor(node.members, visitor, ts.isTypeElement)); + case 169: + return ts.updateArrayTypeNode(node, visitNode(node.elementType, visitor, ts.isTypeNode)); + case 170: + return ts.updateTupleTypeNode(node, nodesVisitor(node.elementTypes, visitor, ts.isTypeNode)); + case 171: + return ts.updateOptionalTypeNode(node, visitNode(node.type, visitor, ts.isTypeNode)); + case 172: + return ts.updateRestTypeNode(node, visitNode(node.type, visitor, ts.isTypeNode)); + case 173: + return ts.updateUnionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode)); + case 174: + return ts.updateIntersectionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode)); + case 175: + return ts.updateConditionalTypeNode(node, visitNode(node.checkType, visitor, ts.isTypeNode), visitNode(node.extendsType, visitor, ts.isTypeNode), visitNode(node.trueType, visitor, ts.isTypeNode), visitNode(node.falseType, visitor, ts.isTypeNode)); + case 176: + return ts.updateInferTypeNode(node, visitNode(node.typeParameter, visitor, ts.isTypeParameterDeclaration)); + case 183: + return ts.updateImportTypeNode(node, visitNode(node.argument, visitor, ts.isTypeNode), visitNode(node.qualifier, visitor, ts.isEntityName), visitNodes(node.typeArguments, visitor, ts.isTypeNode), node.isTypeOf); + case 177: + return ts.updateParenthesizedType(node, visitNode(node.type, visitor, ts.isTypeNode)); + case 179: + return ts.updateTypeOperatorNode(node, visitNode(node.type, visitor, ts.isTypeNode)); + case 180: + return ts.updateIndexedAccessTypeNode(node, visitNode(node.objectType, visitor, ts.isTypeNode), visitNode(node.indexType, visitor, ts.isTypeNode)); + case 181: + return ts.updateMappedTypeNode(node, visitNode(node.readonlyToken, tokenVisitor, ts.isToken), visitNode(node.typeParameter, visitor, ts.isTypeParameterDeclaration), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode)); + case 182: + return ts.updateLiteralTypeNode(node, visitNode(node.literal, visitor, ts.isExpression)); + case 184: + return ts.updateObjectBindingPattern(node, nodesVisitor(node.elements, visitor, ts.isBindingElement)); + case 185: + return ts.updateArrayBindingPattern(node, nodesVisitor(node.elements, visitor, ts.isArrayBindingElement)); + case 186: + return ts.updateBindingElement(node, visitNode(node.dotDotDotToken, tokenVisitor, ts.isToken), visitNode(node.propertyName, visitor, ts.isPropertyName), visitNode(node.name, visitor, ts.isBindingName), visitNode(node.initializer, visitor, ts.isExpression)); + case 187: + return ts.updateArrayLiteral(node, nodesVisitor(node.elements, visitor, ts.isExpression)); + case 188: + return ts.updateObjectLiteral(node, nodesVisitor(node.properties, visitor, ts.isObjectLiteralElementLike)); + case 189: + return ts.updatePropertyAccess(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.name, visitor, ts.isIdentifier)); + case 190: + return ts.updateElementAccess(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.argumentExpression, visitor, ts.isExpression)); + case 191: + return ts.updateCall(node, visitNode(node.expression, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression)); + case 192: + return ts.updateNew(node, visitNode(node.expression, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression)); + case 193: + return ts.updateTaggedTemplate(node, visitNode(node.tag, visitor, ts.isExpression), visitNodes(node.typeArguments, visitor, ts.isExpression), visitNode(node.template, visitor, ts.isTemplateLiteral)); + case 194: + return ts.updateTypeAssertion(node, visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.expression, visitor, ts.isExpression)); + case 195: + return ts.updateParen(node, visitNode(node.expression, visitor, ts.isExpression)); + case 196: + return ts.updateFunctionExpression(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); + case 197: + return ts.updateArrowFunction(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.equalsGreaterThanToken, visitor, ts.isToken), visitFunctionBody(node.body, visitor, context)); + case 198: + return ts.updateDelete(node, visitNode(node.expression, visitor, ts.isExpression)); + case 199: + return ts.updateTypeOf(node, visitNode(node.expression, visitor, ts.isExpression)); + case 200: + return ts.updateVoid(node, visitNode(node.expression, visitor, ts.isExpression)); + case 201: + return ts.updateAwait(node, visitNode(node.expression, visitor, ts.isExpression)); + case 202: + return ts.updatePrefix(node, visitNode(node.operand, visitor, ts.isExpression)); + case 203: + return ts.updatePostfix(node, visitNode(node.operand, visitor, ts.isExpression)); + case 204: + return ts.updateBinary(node, visitNode(node.left, visitor, ts.isExpression), visitNode(node.right, visitor, ts.isExpression), visitNode(node.operatorToken, visitor, ts.isToken)); + case 205: + return ts.updateConditional(node, visitNode(node.condition, visitor, ts.isExpression), visitNode(node.questionToken, visitor, ts.isToken), visitNode(node.whenTrue, visitor, ts.isExpression), visitNode(node.colonToken, visitor, ts.isToken), visitNode(node.whenFalse, visitor, ts.isExpression)); + case 206: + return ts.updateTemplateExpression(node, visitNode(node.head, visitor, ts.isTemplateHead), nodesVisitor(node.templateSpans, visitor, ts.isTemplateSpan)); + case 207: + return ts.updateYield(node, visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.expression, visitor, ts.isExpression)); + case 208: + return ts.updateSpread(node, visitNode(node.expression, visitor, ts.isExpression)); + case 209: + return ts.updateClassExpression(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement)); + case 211: + return ts.updateExpressionWithTypeArguments(node, nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), visitNode(node.expression, visitor, ts.isExpression)); + case 212: + return ts.updateAsExpression(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.type, visitor, ts.isTypeNode)); + case 213: + return ts.updateNonNullExpression(node, visitNode(node.expression, visitor, ts.isExpression)); + case 214: + return ts.updateMetaProperty(node, visitNode(node.name, visitor, ts.isIdentifier)); + case 216: + return ts.updateTemplateSpan(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.literal, visitor, ts.isTemplateMiddleOrTemplateTail)); + case 218: + return ts.updateBlock(node, nodesVisitor(node.statements, visitor, ts.isStatement)); + case 219: + return ts.updateVariableStatement(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.declarationList, visitor, ts.isVariableDeclarationList)); + case 221: + return ts.updateExpressionStatement(node, visitNode(node.expression, visitor, ts.isExpression)); + case 222: + return ts.updateIf(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.thenStatement, visitor, ts.isStatement, ts.liftToBlock), visitNode(node.elseStatement, visitor, ts.isStatement, ts.liftToBlock)); + case 223: + return ts.updateDo(node, visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock), visitNode(node.expression, visitor, ts.isExpression)); + case 224: + return ts.updateWhile(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); + case 225: + return ts.updateFor(node, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.condition, visitor, ts.isExpression), visitNode(node.incrementor, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); + case 226: + return ts.updateForIn(node, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); + case 227: + return ts.updateForOf(node, visitNode(node.awaitModifier, visitor, ts.isToken), visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); + case 228: + return ts.updateContinue(node, visitNode(node.label, visitor, ts.isIdentifier)); + case 229: + return ts.updateBreak(node, visitNode(node.label, visitor, ts.isIdentifier)); + case 230: + return ts.updateReturn(node, visitNode(node.expression, visitor, ts.isExpression)); + case 231: + return ts.updateWith(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); + case 232: + return ts.updateSwitch(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.caseBlock, visitor, ts.isCaseBlock)); + case 233: + return ts.updateLabel(node, visitNode(node.label, visitor, ts.isIdentifier), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); + case 234: + return ts.updateThrow(node, visitNode(node.expression, visitor, ts.isExpression)); + case 235: + return ts.updateTry(node, visitNode(node.tryBlock, visitor, ts.isBlock), visitNode(node.catchClause, visitor, ts.isCatchClause), visitNode(node.finallyBlock, visitor, ts.isBlock)); + case 237: + return ts.updateVariableDeclaration(node, visitNode(node.name, visitor, ts.isBindingName), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); + case 238: + return ts.updateVariableDeclarationList(node, nodesVisitor(node.declarations, visitor, ts.isVariableDeclaration)); + case 239: + return ts.updateFunctionDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); + case 240: + return ts.updateClassDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement)); + case 241: + return ts.updateInterfaceDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isTypeElement)); + case 242: + return ts.updateTypeAliasDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); + case 243: + return ts.updateEnumDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.members, visitor, ts.isEnumMember)); + case 244: + return ts.updateModuleDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.body, visitor, ts.isModuleBody)); + case 245: + return ts.updateModuleBlock(node, nodesVisitor(node.statements, visitor, ts.isStatement)); + case 246: + return ts.updateCaseBlock(node, nodesVisitor(node.clauses, visitor, ts.isCaseOrDefaultClause)); + case 247: + return ts.updateNamespaceExportDeclaration(node, visitNode(node.name, visitor, ts.isIdentifier)); + case 248: + return ts.updateImportEqualsDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.moduleReference, visitor, ts.isModuleReference)); + case 249: + return ts.updateImportDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.importClause, visitor, ts.isImportClause), visitNode(node.moduleSpecifier, visitor, ts.isExpression)); + case 250: + return ts.updateImportClause(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.namedBindings, visitor, ts.isNamedImportBindings)); + case 251: + return ts.updateNamespaceImport(node, visitNode(node.name, visitor, ts.isIdentifier)); + case 252: + return ts.updateNamedImports(node, nodesVisitor(node.elements, visitor, ts.isImportSpecifier)); + case 253: + return ts.updateImportSpecifier(node, visitNode(node.propertyName, visitor, ts.isIdentifier), visitNode(node.name, visitor, ts.isIdentifier)); + case 254: + return ts.updateExportAssignment(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.expression, visitor, ts.isExpression)); + case 255: + return ts.updateExportDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.exportClause, visitor, ts.isNamedExports), visitNode(node.moduleSpecifier, visitor, ts.isExpression)); + case 256: + return ts.updateNamedExports(node, nodesVisitor(node.elements, visitor, ts.isExportSpecifier)); + case 257: + return ts.updateExportSpecifier(node, visitNode(node.propertyName, visitor, ts.isIdentifier), visitNode(node.name, visitor, ts.isIdentifier)); + case 259: + return ts.updateExternalModuleReference(node, visitNode(node.expression, visitor, ts.isExpression)); + case 260: + return ts.updateJsxElement(node, visitNode(node.openingElement, visitor, ts.isJsxOpeningElement), nodesVisitor(node.children, visitor, ts.isJsxChild), visitNode(node.closingElement, visitor, ts.isJsxClosingElement)); + case 261: + return ts.updateJsxSelfClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), visitNode(node.attributes, visitor, ts.isJsxAttributes)); + case 262: + return ts.updateJsxOpeningElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), visitNode(node.attributes, visitor, ts.isJsxAttributes)); + case 263: + return ts.updateJsxClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression)); + case 264: + return ts.updateJsxFragment(node, visitNode(node.openingFragment, visitor, ts.isJsxOpeningFragment), nodesVisitor(node.children, visitor, ts.isJsxChild), visitNode(node.closingFragment, visitor, ts.isJsxClosingFragment)); + case 267: + return ts.updateJsxAttribute(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.initializer, visitor, ts.isStringLiteralOrJsxExpression)); + case 268: + return ts.updateJsxAttributes(node, nodesVisitor(node.properties, visitor, ts.isJsxAttributeLike)); + case 269: + return ts.updateJsxSpreadAttribute(node, visitNode(node.expression, visitor, ts.isExpression)); + case 270: + return ts.updateJsxExpression(node, visitNode(node.expression, visitor, ts.isExpression)); + case 271: + return ts.updateCaseClause(node, visitNode(node.expression, visitor, ts.isExpression), nodesVisitor(node.statements, visitor, ts.isStatement)); + case 272: + return ts.updateDefaultClause(node, nodesVisitor(node.statements, visitor, ts.isStatement)); + case 273: + return ts.updateHeritageClause(node, nodesVisitor(node.types, visitor, ts.isExpressionWithTypeArguments)); + case 274: + return ts.updateCatchClause(node, visitNode(node.variableDeclaration, visitor, ts.isVariableDeclaration), visitNode(node.block, visitor, ts.isBlock)); + case 275: + return ts.updatePropertyAssignment(node, visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.initializer, visitor, ts.isExpression)); + case 276: + return ts.updateShorthandPropertyAssignment(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.objectAssignmentInitializer, visitor, ts.isExpression)); + case 277: + return ts.updateSpreadAssignment(node, visitNode(node.expression, visitor, ts.isExpression)); + case 278: + return ts.updateEnumMember(node, visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.initializer, visitor, ts.isExpression)); + case 279: + return ts.updateSourceFileNode(node, visitLexicalEnvironment(node.statements, visitor, context)); + case 308: + return ts.updatePartiallyEmittedExpression(node, visitNode(node.expression, visitor, ts.isExpression)); + case 309: + return ts.updateCommaList(node, nodesVisitor(node.elements, visitor, ts.isExpression)); + default: + return node; + } + } + ts.visitEachChild = visitEachChild; + function extractSingleNode(nodes) { + ts.Debug.assert(nodes.length <= 1, "Too many nodes written to output."); + return ts.singleOrUndefined(nodes); + } +})(ts || (ts = {})); +(function (ts) { + function reduceNode(node, f, initial) { + return node ? f(initial, node) : initial; + } + function reduceNodeArray(nodes, f, initial) { + return nodes ? f(initial, nodes) : initial; + } + function reduceEachChild(node, initial, cbNode, cbNodeArray) { + if (node === undefined) { + return initial; + } + var reduceNodes = cbNodeArray ? reduceNodeArray : ts.reduceLeft; + var cbNodes = cbNodeArray || cbNode; + var kind = node.kind; + if ((kind > 0 && kind <= 147)) { + return initial; + } + if ((kind >= 163 && kind <= 182)) { + return initial; + } + var result = initial; + switch (node.kind) { + case 217: + case 220: + case 210: + case 236: + case 307: + break; + case 148: + result = reduceNode(node.left, cbNode, result); + result = reduceNode(node.right, cbNode, result); + break; + case 149: + result = reduceNode(node.expression, cbNode, result); + break; + case 151: + result = reduceNodes(node.decorators, cbNodes, result); + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.type, cbNode, result); + result = reduceNode(node.initializer, cbNode, result); + break; + case 152: + result = reduceNode(node.expression, cbNode, result); + break; + case 153: + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.questionToken, cbNode, result); + result = reduceNode(node.type, cbNode, result); + result = reduceNode(node.initializer, cbNode, result); + break; + case 154: + result = reduceNodes(node.decorators, cbNodes, result); + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.type, cbNode, result); + result = reduceNode(node.initializer, cbNode, result); + break; + case 156: + result = reduceNodes(node.decorators, cbNodes, result); + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNodes(node.typeParameters, cbNodes, result); + result = reduceNodes(node.parameters, cbNodes, result); + result = reduceNode(node.type, cbNode, result); + result = reduceNode(node.body, cbNode, result); + break; + case 157: + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNodes(node.parameters, cbNodes, result); + result = reduceNode(node.body, cbNode, result); + break; + case 158: + result = reduceNodes(node.decorators, cbNodes, result); + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNodes(node.parameters, cbNodes, result); + result = reduceNode(node.type, cbNode, result); + result = reduceNode(node.body, cbNode, result); + break; + case 159: + result = reduceNodes(node.decorators, cbNodes, result); + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNodes(node.parameters, cbNodes, result); + result = reduceNode(node.body, cbNode, result); + break; + case 184: + case 185: + result = reduceNodes(node.elements, cbNodes, result); + break; + case 186: + result = reduceNode(node.propertyName, cbNode, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.initializer, cbNode, result); + break; + case 187: + result = reduceNodes(node.elements, cbNodes, result); + break; + case 188: + result = reduceNodes(node.properties, cbNodes, result); + break; + case 189: + result = reduceNode(node.expression, cbNode, result); + result = reduceNode(node.name, cbNode, result); + break; + case 190: + result = reduceNode(node.expression, cbNode, result); + result = reduceNode(node.argumentExpression, cbNode, result); + break; + case 191: + result = reduceNode(node.expression, cbNode, result); + result = reduceNodes(node.typeArguments, cbNodes, result); + result = reduceNodes(node.arguments, cbNodes, result); + break; + case 192: + result = reduceNode(node.expression, cbNode, result); + result = reduceNodes(node.typeArguments, cbNodes, result); + result = reduceNodes(node.arguments, cbNodes, result); + break; + case 193: + result = reduceNode(node.tag, cbNode, result); + result = reduceNodes(node.typeArguments, cbNodes, result); + result = reduceNode(node.template, cbNode, result); + break; + case 194: + result = reduceNode(node.type, cbNode, result); + result = reduceNode(node.expression, cbNode, result); + break; + case 196: + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNodes(node.typeParameters, cbNodes, result); + result = reduceNodes(node.parameters, cbNodes, result); + result = reduceNode(node.type, cbNode, result); + result = reduceNode(node.body, cbNode, result); + break; + case 197: + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNodes(node.typeParameters, cbNodes, result); + result = reduceNodes(node.parameters, cbNodes, result); + result = reduceNode(node.type, cbNode, result); + result = reduceNode(node.body, cbNode, result); + break; + case 195: + case 198: + case 199: + case 200: + case 201: + case 207: + case 208: + case 213: + result = reduceNode(node.expression, cbNode, result); + break; + case 202: + case 203: + result = reduceNode(node.operand, cbNode, result); + break; + case 204: + result = reduceNode(node.left, cbNode, result); + result = reduceNode(node.right, cbNode, result); + break; + case 205: + result = reduceNode(node.condition, cbNode, result); + result = reduceNode(node.whenTrue, cbNode, result); + result = reduceNode(node.whenFalse, cbNode, result); + break; + case 206: + result = reduceNode(node.head, cbNode, result); + result = reduceNodes(node.templateSpans, cbNodes, result); + break; + case 209: + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNodes(node.typeParameters, cbNodes, result); + result = reduceNodes(node.heritageClauses, cbNodes, result); + result = reduceNodes(node.members, cbNodes, result); + break; + case 211: + result = reduceNode(node.expression, cbNode, result); + result = reduceNodes(node.typeArguments, cbNodes, result); + break; + case 212: + result = reduceNode(node.expression, cbNode, result); + result = reduceNode(node.type, cbNode, result); + break; + case 216: + result = reduceNode(node.expression, cbNode, result); + result = reduceNode(node.literal, cbNode, result); + break; + case 218: + result = reduceNodes(node.statements, cbNodes, result); + break; + case 219: + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.declarationList, cbNode, result); + break; + case 221: + result = reduceNode(node.expression, cbNode, result); + break; + case 222: + result = reduceNode(node.expression, cbNode, result); + result = reduceNode(node.thenStatement, cbNode, result); + result = reduceNode(node.elseStatement, cbNode, result); + break; + case 223: + result = reduceNode(node.statement, cbNode, result); + result = reduceNode(node.expression, cbNode, result); + break; + case 224: + case 231: + result = reduceNode(node.expression, cbNode, result); + result = reduceNode(node.statement, cbNode, result); + break; + case 225: + result = reduceNode(node.initializer, cbNode, result); + result = reduceNode(node.condition, cbNode, result); + result = reduceNode(node.incrementor, cbNode, result); + result = reduceNode(node.statement, cbNode, result); + break; + case 226: + case 227: + result = reduceNode(node.initializer, cbNode, result); + result = reduceNode(node.expression, cbNode, result); + result = reduceNode(node.statement, cbNode, result); + break; + case 230: + case 234: + result = reduceNode(node.expression, cbNode, result); + break; + case 232: + result = reduceNode(node.expression, cbNode, result); + result = reduceNode(node.caseBlock, cbNode, result); + break; + case 233: + result = reduceNode(node.label, cbNode, result); + result = reduceNode(node.statement, cbNode, result); + break; + case 235: + result = reduceNode(node.tryBlock, cbNode, result); + result = reduceNode(node.catchClause, cbNode, result); + result = reduceNode(node.finallyBlock, cbNode, result); + break; + case 237: + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.type, cbNode, result); + result = reduceNode(node.initializer, cbNode, result); + break; + case 238: + result = reduceNodes(node.declarations, cbNodes, result); + break; + case 239: + result = reduceNodes(node.decorators, cbNodes, result); + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNodes(node.typeParameters, cbNodes, result); + result = reduceNodes(node.parameters, cbNodes, result); + result = reduceNode(node.type, cbNode, result); + result = reduceNode(node.body, cbNode, result); + break; + case 240: + result = reduceNodes(node.decorators, cbNodes, result); + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNodes(node.typeParameters, cbNodes, result); + result = reduceNodes(node.heritageClauses, cbNodes, result); + result = reduceNodes(node.members, cbNodes, result); + break; + case 243: + result = reduceNodes(node.decorators, cbNodes, result); + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNodes(node.members, cbNodes, result); + break; + case 244: + result = reduceNodes(node.decorators, cbNodes, result); + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.body, cbNode, result); + break; + case 245: + result = reduceNodes(node.statements, cbNodes, result); + break; + case 246: + result = reduceNodes(node.clauses, cbNodes, result); + break; + case 248: + result = reduceNodes(node.decorators, cbNodes, result); + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.moduleReference, cbNode, result); + break; + case 249: + result = reduceNodes(node.decorators, cbNodes, result); + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.importClause, cbNode, result); + result = reduceNode(node.moduleSpecifier, cbNode, result); + break; + case 250: + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.namedBindings, cbNode, result); + break; + case 251: + result = reduceNode(node.name, cbNode, result); + break; + case 252: + case 256: + result = reduceNodes(node.elements, cbNodes, result); + break; + case 253: + case 257: + result = reduceNode(node.propertyName, cbNode, result); + result = reduceNode(node.name, cbNode, result); + break; + case 254: + result = ts.reduceLeft(node.decorators, cbNode, result); + result = ts.reduceLeft(node.modifiers, cbNode, result); + result = reduceNode(node.expression, cbNode, result); + break; + case 255: + result = ts.reduceLeft(node.decorators, cbNode, result); + result = ts.reduceLeft(node.modifiers, cbNode, result); + result = reduceNode(node.exportClause, cbNode, result); + result = reduceNode(node.moduleSpecifier, cbNode, result); + break; + case 259: + result = reduceNode(node.expression, cbNode, result); + break; + case 260: + result = reduceNode(node.openingElement, cbNode, result); + result = ts.reduceLeft(node.children, cbNode, result); + result = reduceNode(node.closingElement, cbNode, result); + break; + case 264: + result = reduceNode(node.openingFragment, cbNode, result); + result = ts.reduceLeft(node.children, cbNode, result); + result = reduceNode(node.closingFragment, cbNode, result); + break; + case 261: + case 262: + result = reduceNode(node.tagName, cbNode, result); + result = reduceNodes(node.typeArguments, cbNode, result); + result = reduceNode(node.attributes, cbNode, result); + break; + case 268: + result = reduceNodes(node.properties, cbNodes, result); + break; + case 263: + result = reduceNode(node.tagName, cbNode, result); + break; + case 267: + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.initializer, cbNode, result); + break; + case 269: + result = reduceNode(node.expression, cbNode, result); + break; + case 270: + result = reduceNode(node.expression, cbNode, result); + break; + case 271: + result = reduceNode(node.expression, cbNode, result); + case 272: + result = reduceNodes(node.statements, cbNodes, result); + break; + case 273: + result = reduceNodes(node.types, cbNodes, result); + break; + case 274: + result = reduceNode(node.variableDeclaration, cbNode, result); + result = reduceNode(node.block, cbNode, result); + break; + case 275: + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.initializer, cbNode, result); + break; + case 276: + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.objectAssignmentInitializer, cbNode, result); + break; + case 277: + result = reduceNode(node.expression, cbNode, result); + break; + case 278: + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.initializer, cbNode, result); + break; + case 279: + result = reduceNodes(node.statements, cbNodes, result); + break; + case 308: + result = reduceNode(node.expression, cbNode, result); + break; + case 309: + result = reduceNodes(node.elements, cbNodes, result); + break; + default: + break; + } + return result; + } + ts.reduceEachChild = reduceEachChild; + function mergeLexicalEnvironment(statements, declarations) { + if (!ts.some(declarations)) { + return statements; + } + return ts.isNodeArray(statements) + ? ts.setTextRange(ts.createNodeArray(ts.addStatementsAfterPrologue(statements.slice(), declarations)), statements) + : ts.addStatementsAfterPrologue(statements, declarations); + } + ts.mergeLexicalEnvironment = mergeLexicalEnvironment; + function liftToBlock(nodes) { + Debug.assert(ts.every(nodes, ts.isStatement), "Cannot lift nodes to a Block."); + return ts.singleOrUndefined(nodes) || ts.createBlock(nodes); + } + ts.liftToBlock = liftToBlock; + function aggregateTransformFlags(node) { + aggregateTransformFlagsForNode(node); + return node; + } + ts.aggregateTransformFlags = aggregateTransformFlags; + function aggregateTransformFlagsForNode(node) { + if (node === undefined) { + return 0; + } + if (node.transformFlags & 536870912) { + return node.transformFlags & ~ts.getTransformFlagsSubtreeExclusions(node.kind); + } + var subtreeFlags = aggregateTransformFlagsForSubtree(node); + return ts.computeTransformFlagsForNode(node, subtreeFlags); + } + function aggregateTransformFlagsForNodeArray(nodes) { + if (nodes === undefined) { + return 0; + } + var subtreeFlags = 0; + var nodeArrayFlags = 0; + for (var _i = 0, nodes_3 = nodes; _i < nodes_3.length; _i++) { + var node = nodes_3[_i]; + subtreeFlags |= aggregateTransformFlagsForNode(node); + nodeArrayFlags |= node.transformFlags & ~536870912; + } + nodes.transformFlags = nodeArrayFlags | 536870912; + return subtreeFlags; + } + function aggregateTransformFlagsForSubtree(node) { + if (ts.hasModifier(node, 2) || (ts.isTypeNode(node) && node.kind !== 211)) { + return 0; + } + return reduceEachChild(node, 0, aggregateTransformFlagsForChildNode, aggregateTransformFlagsForChildNodes); + } + function aggregateTransformFlagsForChildNode(transformFlags, node) { + return transformFlags | aggregateTransformFlagsForNode(node); + } + function aggregateTransformFlagsForChildNodes(transformFlags, nodes) { + return transformFlags | aggregateTransformFlagsForNodeArray(nodes); + } + var Debug; + (function (Debug) { + var isDebugInfoEnabled = false; + function failBadSyntaxKind(node, message) { + return Debug.fail((message || "Unexpected node.") + "\r\nNode " + ts.formatSyntaxKind(node.kind) + " was unexpected.", failBadSyntaxKind); + } + Debug.failBadSyntaxKind = failBadSyntaxKind; + Debug.assertEachNode = Debug.shouldAssert(1) + ? function (nodes, test, message) { return Debug.assert(test === undefined || ts.every(nodes, test), message || "Unexpected node.", function () { return "Node array did not pass test '" + Debug.getFunctionName(test) + "'."; }, Debug.assertEachNode); } + : ts.noop; + Debug.assertNode = Debug.shouldAssert(1) + ? function (node, test, message) { return Debug.assert(test === undefined || test(node), message || "Unexpected node.", function () { return "Node " + ts.formatSyntaxKind(node.kind) + " did not pass test '" + Debug.getFunctionName(test) + "'."; }, Debug.assertNode); } + : ts.noop; + Debug.assertOptionalNode = Debug.shouldAssert(1) + ? function (node, test, message) { return Debug.assert(test === undefined || node === undefined || test(node), message || "Unexpected node.", function () { return "Node " + ts.formatSyntaxKind(node.kind) + " did not pass test '" + Debug.getFunctionName(test) + "'."; }, Debug.assertOptionalNode); } + : ts.noop; + Debug.assertOptionalToken = Debug.shouldAssert(1) + ? function (node, kind, message) { return Debug.assert(kind === undefined || node === undefined || node.kind === kind, message || "Unexpected node.", function () { return "Node " + ts.formatSyntaxKind(node.kind) + " was not a '" + ts.formatSyntaxKind(kind) + "' token."; }, Debug.assertOptionalToken); } + : ts.noop; + Debug.assertMissingNode = Debug.shouldAssert(1) + ? function (node, message) { return Debug.assert(node === undefined, message || "Unexpected node.", function () { return "Node " + ts.formatSyntaxKind(node.kind) + " was unexpected'."; }, Debug.assertMissingNode); } + : ts.noop; + function enableDebugInfo() { + if (isDebugInfoEnabled) + return; + Object.defineProperties(ts.objectAllocator.getSymbolConstructor().prototype, { + __debugFlags: { get: function () { return ts.formatSymbolFlags(this.flags); } } + }); + Object.defineProperties(ts.objectAllocator.getTypeConstructor().prototype, { + __debugFlags: { get: function () { return ts.formatTypeFlags(this.flags); } }, + __debugObjectFlags: { get: function () { return this.flags & 524288 ? ts.formatObjectFlags(this.objectFlags) : ""; } }, + __debugTypeToString: { value: function () { return this.checker.typeToString(this); } }, + }); + var nodeConstructors = [ + ts.objectAllocator.getNodeConstructor(), + ts.objectAllocator.getIdentifierConstructor(), + ts.objectAllocator.getTokenConstructor(), + ts.objectAllocator.getSourceFileConstructor() + ]; + for (var _i = 0, nodeConstructors_1 = nodeConstructors; _i < nodeConstructors_1.length; _i++) { + var ctor = nodeConstructors_1[_i]; + if (!ctor.prototype.hasOwnProperty("__debugKind")) { + Object.defineProperties(ctor.prototype, { + __debugKind: { get: function () { return ts.formatSyntaxKind(this.kind); } }, + __debugModifierFlags: { get: function () { return ts.formatModifierFlags(ts.getModifierFlagsNoCache(this)); } }, + __debugTransformFlags: { get: function () { return ts.formatTransformFlags(this.transformFlags); } }, + __debugEmitFlags: { get: function () { return ts.formatEmitFlags(ts.getEmitFlags(this)); } }, + __debugGetText: { + value: function (includeTrivia) { + if (ts.nodeIsSynthesized(this)) + return ""; + var parseNode = ts.getParseTreeNode(this); + var sourceFile = parseNode && ts.getSourceFileOfNode(parseNode); + return sourceFile ? ts.getSourceTextOfNodeFromSourceFile(sourceFile, parseNode, includeTrivia) : ""; + } + } + }); + } + } + isDebugInfoEnabled = true; + } + Debug.enableDebugInfo = enableDebugInfo; + })(Debug = ts.Debug || (ts.Debug = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + function createSourceMapGenerator(host, file, sourceRoot, sourcesDirectoryPath, generatorOptions) { + var _a = generatorOptions.extendedDiagnostics + ? ts.performance.createTimer("Source Map", "beforeSourcemap", "afterSourcemap") + : ts.performance.nullTimer, enter = _a.enter, exit = _a.exit; + var rawSources = []; + var sources = []; + var sourceToSourceIndexMap = ts.createMap(); + var sourcesContent; + var names = []; + var nameToNameIndexMap; + var mappings = ""; + var lastGeneratedLine = 0; + var lastGeneratedCharacter = 0; + var lastSourceIndex = 0; + var lastSourceLine = 0; + var lastSourceCharacter = 0; + var lastNameIndex = 0; + var hasLast = false; + var pendingGeneratedLine = 0; + var pendingGeneratedCharacter = 0; + var pendingSourceIndex = 0; + var pendingSourceLine = 0; + var pendingSourceCharacter = 0; + var pendingNameIndex = 0; + var hasPending = false; + var hasPendingSource = false; + var hasPendingName = false; + return { + getSources: function () { return rawSources; }, + addSource: addSource, + setSourceContent: setSourceContent, + addName: addName, + addMapping: addMapping, + appendSourceMap: appendSourceMap, + toJSON: toJSON, + toString: function () { return JSON.stringify(toJSON()); } + }; + function addSource(fileName) { + enter(); + var source = ts.getRelativePathToDirectoryOrUrl(sourcesDirectoryPath, fileName, host.getCurrentDirectory(), host.getCanonicalFileName, true); + var sourceIndex = sourceToSourceIndexMap.get(source); + if (sourceIndex === undefined) { + sourceIndex = sources.length; + sources.push(source); + rawSources.push(fileName); + sourceToSourceIndexMap.set(source, sourceIndex); + } + exit(); + return sourceIndex; + } + function setSourceContent(sourceIndex, content) { + enter(); + if (content !== null) { + if (!sourcesContent) + sourcesContent = []; + while (sourcesContent.length < sourceIndex) { + sourcesContent.push(null); + } + sourcesContent[sourceIndex] = content; + } + exit(); + } + function addName(name) { + enter(); + if (!nameToNameIndexMap) + nameToNameIndexMap = ts.createMap(); + var nameIndex = nameToNameIndexMap.get(name); + if (nameIndex === undefined) { + nameIndex = names.length; + names.push(name); + nameToNameIndexMap.set(name, nameIndex); + } + exit(); + return nameIndex; + } + function isNewGeneratedPosition(generatedLine, generatedCharacter) { + return !hasPending + || pendingGeneratedLine !== generatedLine + || pendingGeneratedCharacter !== generatedCharacter; + } + function isBacktrackingSourcePosition(sourceIndex, sourceLine, sourceCharacter) { + return sourceIndex !== undefined + && sourceLine !== undefined + && sourceCharacter !== undefined + && pendingSourceIndex === sourceIndex + && (pendingSourceLine > sourceLine + || pendingSourceLine === sourceLine && pendingSourceCharacter > sourceCharacter); + } + function addMapping(generatedLine, generatedCharacter, sourceIndex, sourceLine, sourceCharacter, nameIndex) { + ts.Debug.assert(generatedLine >= pendingGeneratedLine, "generatedLine cannot backtrack"); + ts.Debug.assert(generatedCharacter >= 0, "generatedCharacter cannot be negative"); + ts.Debug.assert(sourceIndex === undefined || sourceIndex >= 0, "sourceIndex cannot be negative"); + ts.Debug.assert(sourceLine === undefined || sourceLine >= 0, "sourceLine cannot be negative"); + ts.Debug.assert(sourceCharacter === undefined || sourceCharacter >= 0, "sourceCharacter cannot be negative"); + enter(); + if (isNewGeneratedPosition(generatedLine, generatedCharacter) || + isBacktrackingSourcePosition(sourceIndex, sourceLine, sourceCharacter)) { + commitPendingMapping(); + pendingGeneratedLine = generatedLine; + pendingGeneratedCharacter = generatedCharacter; + hasPendingSource = false; + hasPendingName = false; + hasPending = true; + } + if (sourceIndex !== undefined && sourceLine !== undefined && sourceCharacter !== undefined) { + pendingSourceIndex = sourceIndex; + pendingSourceLine = sourceLine; + pendingSourceCharacter = sourceCharacter; + hasPendingSource = true; + if (nameIndex !== undefined) { + pendingNameIndex = nameIndex; + hasPendingName = true; + } + } + exit(); + } + function appendSourceMap(generatedLine, generatedCharacter, map, sourceMapPath) { + var _a; + ts.Debug.assert(generatedLine >= pendingGeneratedLine, "generatedLine cannot backtrack"); + ts.Debug.assert(generatedCharacter >= 0, "generatedCharacter cannot be negative"); + enter(); + var sourceIndexToNewSourceIndexMap = []; + var nameIndexToNewNameIndexMap; + var mappingIterator = decodeMappings(map.mappings); + for (var _b = mappingIterator.next(), raw = _b.value, done = _b.done; !done; _a = mappingIterator.next(), raw = _a.value, done = _a.done, _a) { + var newSourceIndex = void 0; + var newSourceLine = void 0; + var newSourceCharacter = void 0; + var newNameIndex = void 0; + if (raw.sourceIndex !== undefined) { + newSourceIndex = sourceIndexToNewSourceIndexMap[raw.sourceIndex]; + if (newSourceIndex === undefined) { + var rawPath = map.sources[raw.sourceIndex]; + var relativePath = map.sourceRoot ? ts.combinePaths(map.sourceRoot, rawPath) : rawPath; + var combinedPath = ts.combinePaths(ts.getDirectoryPath(sourceMapPath), relativePath); + sourceIndexToNewSourceIndexMap[raw.sourceIndex] = newSourceIndex = addSource(combinedPath); + if (map.sourcesContent && typeof map.sourcesContent[raw.sourceIndex] === "string") { + setSourceContent(newSourceIndex, map.sourcesContent[raw.sourceIndex]); + } + } + newSourceLine = raw.sourceLine; + newSourceCharacter = raw.sourceCharacter; + if (map.names && raw.nameIndex !== undefined) { + if (!nameIndexToNewNameIndexMap) + nameIndexToNewNameIndexMap = []; + newNameIndex = nameIndexToNewNameIndexMap[raw.nameIndex]; + if (newNameIndex === undefined) { + nameIndexToNewNameIndexMap[raw.nameIndex] = newNameIndex = addName(map.names[raw.nameIndex]); + } + } + } + var newGeneratedLine = raw.generatedLine + generatedLine; + var newGeneratedCharacter = raw.generatedLine === 0 ? raw.generatedCharacter + generatedCharacter : raw.generatedCharacter; + addMapping(newGeneratedLine, newGeneratedCharacter, newSourceIndex, newSourceLine, newSourceCharacter, newNameIndex); + } + exit(); + } + function shouldCommitMapping() { + return !hasLast + || lastGeneratedLine !== pendingGeneratedLine + || lastGeneratedCharacter !== pendingGeneratedCharacter + || lastSourceIndex !== pendingSourceIndex + || lastSourceLine !== pendingSourceLine + || lastSourceCharacter !== pendingSourceCharacter + || lastNameIndex !== pendingNameIndex; + } + function commitPendingMapping() { + if (!hasPending || !shouldCommitMapping()) { + return; + } + enter(); + if (lastGeneratedLine < pendingGeneratedLine) { + do { + mappings += ";"; + lastGeneratedLine++; + lastGeneratedCharacter = 0; + } while (lastGeneratedLine < pendingGeneratedLine); + } + else { + ts.Debug.assertEqual(lastGeneratedLine, pendingGeneratedLine, "generatedLine cannot backtrack"); + if (hasLast) { + mappings += ","; + } + } + mappings += base64VLQFormatEncode(pendingGeneratedCharacter - lastGeneratedCharacter); + lastGeneratedCharacter = pendingGeneratedCharacter; + if (hasPendingSource) { + mappings += base64VLQFormatEncode(pendingSourceIndex - lastSourceIndex); + lastSourceIndex = pendingSourceIndex; + mappings += base64VLQFormatEncode(pendingSourceLine - lastSourceLine); + lastSourceLine = pendingSourceLine; + mappings += base64VLQFormatEncode(pendingSourceCharacter - lastSourceCharacter); + lastSourceCharacter = pendingSourceCharacter; + if (hasPendingName) { + mappings += base64VLQFormatEncode(pendingNameIndex - lastNameIndex); + lastNameIndex = pendingNameIndex; + } + } + hasLast = true; + exit(); + } + function toJSON() { + commitPendingMapping(); + return { + version: 3, + file: file, + sourceRoot: sourceRoot, + sources: sources, + names: names, + mappings: mappings, + sourcesContent: sourcesContent, + }; + } + } + ts.createSourceMapGenerator = createSourceMapGenerator; + var sourceMapCommentRegExp = /^\/\/[@#] source[M]appingURL=(.+)\s*$/; + var whitespaceOrMapCommentRegExp = /^\s*(\/\/[@#] .*)?$/; + function tryGetSourceMappingURL(text, lineStarts) { + if (lineStarts === void 0) { lineStarts = ts.computeLineStarts(text); } + for (var index = lineStarts.length - 1; index >= 0; index--) { + var line = text.substring(lineStarts[index], lineStarts[index + 1]); + var comment = sourceMapCommentRegExp.exec(line); + if (comment) { + return comment[1]; + } + else if (!line.match(whitespaceOrMapCommentRegExp)) { + break; + } + } + } + ts.tryGetSourceMappingURL = tryGetSourceMappingURL; + function isStringOrNull(x) { + return typeof x === "string" || x === null; + } + function isRawSourceMap(x) { + return x !== null + && typeof x === "object" + && x.version === 3 + && typeof x.file === "string" + && typeof x.mappings === "string" + && ts.isArray(x.sources) && ts.every(x.sources, ts.isString) + && (x.sourceRoot === undefined || x.sourceRoot === null || typeof x.sourceRoot === "string") + && (x.sourcesContent === undefined || x.sourcesContent === null || ts.isArray(x.sourcesContent) && ts.every(x.sourcesContent, isStringOrNull)) + && (x.names === undefined || x.names === null || ts.isArray(x.names) && ts.every(x.names, ts.isString)); + } + ts.isRawSourceMap = isRawSourceMap; + function tryParseRawSourceMap(text) { + try { + var parsed = JSON.parse(text); + if (isRawSourceMap(parsed)) { + return parsed; + } + } + catch (_a) { + } + return undefined; + } + ts.tryParseRawSourceMap = tryParseRawSourceMap; + function decodeMappings(mappings) { + var done = false; + var pos = 0; + var generatedLine = 0; + var generatedCharacter = 0; + var sourceIndex = 0; + var sourceLine = 0; + var sourceCharacter = 0; + var nameIndex = 0; + var error; + return { + get pos() { return pos; }, + get error() { return error; }, + get state() { return captureMapping(true, true); }, + next: function () { + while (!done && pos < mappings.length) { + var ch = mappings.charCodeAt(pos); + if (ch === 59) { + generatedLine++; + generatedCharacter = 0; + pos++; + continue; + } + if (ch === 44) { + pos++; + continue; + } + var hasSource = false; + var hasName = false; + generatedCharacter += base64VLQFormatDecode(); + if (hasReportedError()) + return stopIterating(); + if (generatedCharacter < 0) + return setErrorAndStopIterating("Invalid generatedCharacter found"); + if (!isSourceMappingSegmentEnd()) { + hasSource = true; + sourceIndex += base64VLQFormatDecode(); + if (hasReportedError()) + return stopIterating(); + if (sourceIndex < 0) + return setErrorAndStopIterating("Invalid sourceIndex found"); + if (isSourceMappingSegmentEnd()) + return setErrorAndStopIterating("Unsupported Format: No entries after sourceIndex"); + sourceLine += base64VLQFormatDecode(); + if (hasReportedError()) + return stopIterating(); + if (sourceLine < 0) + return setErrorAndStopIterating("Invalid sourceLine found"); + if (isSourceMappingSegmentEnd()) + return setErrorAndStopIterating("Unsupported Format: No entries after sourceLine"); + sourceCharacter += base64VLQFormatDecode(); + if (hasReportedError()) + return stopIterating(); + if (sourceCharacter < 0) + return setErrorAndStopIterating("Invalid sourceCharacter found"); + if (!isSourceMappingSegmentEnd()) { + hasName = true; + nameIndex += base64VLQFormatDecode(); + if (hasReportedError()) + return stopIterating(); + if (nameIndex < 0) + return setErrorAndStopIterating("Invalid nameIndex found"); + if (!isSourceMappingSegmentEnd()) + return setErrorAndStopIterating("Unsupported Error Format: Entries after nameIndex"); + } + } + return { value: captureMapping(hasSource, hasName), done: done }; + } + return stopIterating(); + } + }; + function captureMapping(hasSource, hasName) { + return { + generatedLine: generatedLine, + generatedCharacter: generatedCharacter, + sourceIndex: hasSource ? sourceIndex : undefined, + sourceLine: hasSource ? sourceLine : undefined, + sourceCharacter: hasSource ? sourceCharacter : undefined, + nameIndex: hasName ? nameIndex : undefined + }; + } + function stopIterating() { + done = true; + return { value: undefined, done: true }; + } + function setError(message) { + if (error === undefined) { + error = message; + } + } + function setErrorAndStopIterating(message) { + setError(message); + return stopIterating(); + } + function hasReportedError() { + return error !== undefined; + } + function isSourceMappingSegmentEnd() { + return (pos === mappings.length || + mappings.charCodeAt(pos) === 44 || + mappings.charCodeAt(pos) === 59); + } + function base64VLQFormatDecode() { + var moreDigits = true; + var shiftCount = 0; + var value = 0; + for (; moreDigits; pos++) { + if (pos >= mappings.length) + return setError("Error in decoding base64VLQFormatDecode, past the mapping string"), -1; + var currentByte = base64FormatDecode(mappings.charCodeAt(pos)); + if (currentByte === -1) + return setError("Invalid character in VLQ"), -1; + moreDigits = (currentByte & 32) !== 0; + value = value | ((currentByte & 31) << shiftCount); + shiftCount += 5; + } + if ((value & 1) === 0) { + value = value >> 1; + } + else { + value = value >> 1; + value = -value; + } + return value; + } + } + ts.decodeMappings = decodeMappings; + function sameMapping(left, right) { + return left === right + || left.generatedLine === right.generatedLine + && left.generatedCharacter === right.generatedCharacter + && left.sourceIndex === right.sourceIndex + && left.sourceLine === right.sourceLine + && left.sourceCharacter === right.sourceCharacter + && left.nameIndex === right.nameIndex; + } + ts.sameMapping = sameMapping; + function isSourceMapping(mapping) { + return mapping.sourceIndex !== undefined + && mapping.sourceLine !== undefined + && mapping.sourceCharacter !== undefined; + } + ts.isSourceMapping = isSourceMapping; + function base64FormatEncode(value) { + return value >= 0 && value < 26 ? 65 + value : + value >= 26 && value < 52 ? 97 + value - 26 : + value >= 52 && value < 62 ? 48 + value - 52 : + value === 62 ? 43 : + value === 63 ? 47 : + ts.Debug.fail(value + ": not a base64 value"); + } + function base64FormatDecode(ch) { + return ch >= 65 && ch <= 90 ? ch - 65 : + ch >= 97 && ch <= 122 ? ch - 97 + 26 : + ch >= 48 && ch <= 57 ? ch - 48 + 52 : + ch === 43 ? 62 : + ch === 47 ? 63 : + -1; + } + function base64VLQFormatEncode(inValue) { + if (inValue < 0) { + inValue = ((-inValue) << 1) + 1; + } + else { + inValue = inValue << 1; + } + var encodedStr = ""; + do { + var currentDigit = inValue & 31; + inValue = inValue >> 5; + if (inValue > 0) { + currentDigit = currentDigit | 32; + } + encodedStr = encodedStr + String.fromCharCode(base64FormatEncode(currentDigit)); + } while (inValue > 0); + return encodedStr; + } + function isSourceMappedPosition(value) { + return value.sourceIndex !== undefined + && value.sourcePosition !== undefined; + } + function sameMappedPosition(left, right) { + return left.generatedPosition === right.generatedPosition + && left.sourceIndex === right.sourceIndex + && left.sourcePosition === right.sourcePosition; + } + function compareSourcePositions(left, right) { + return ts.compareValues(left.sourceIndex, right.sourceIndex); + } + function compareGeneratedPositions(left, right) { + return ts.compareValues(left.generatedPosition, right.generatedPosition); + } + function getSourcePositionOfMapping(value) { + return value.sourcePosition; + } + function getGeneratedPositionOfMapping(value) { + return value.generatedPosition; + } + function createDocumentPositionMapper(host, map, mapPath) { + var mapDirectory = ts.getDirectoryPath(mapPath); + var sourceRoot = map.sourceRoot ? ts.getNormalizedAbsolutePath(map.sourceRoot, mapDirectory) : mapDirectory; + var generatedAbsoluteFilePath = ts.getNormalizedAbsolutePath(map.file, mapDirectory); + var generatedCanonicalFilePath = host.getCanonicalFileName(generatedAbsoluteFilePath); + var generatedFile = host.getSourceFileLike(generatedCanonicalFilePath); + var sourceFileAbsolutePaths = map.sources.map(function (source) { return ts.getNormalizedAbsolutePath(source, sourceRoot); }); + var sourceFileCanonicalPaths = sourceFileAbsolutePaths.map(function (source) { return host.getCanonicalFileName(source); }); + var sourceToSourceIndexMap = ts.createMapFromEntries(sourceFileCanonicalPaths.map(function (source, i) { return [source, i]; })); + var decodedMappings; + var generatedMappings; + var sourceMappings; + return { + getSourcePosition: getSourcePosition, + getGeneratedPosition: getGeneratedPosition + }; + function processMapping(mapping) { + var generatedPosition = generatedFile !== undefined + ? ts.getPositionOfLineAndCharacterWithEdits(generatedFile, mapping.generatedLine, mapping.generatedCharacter) + : -1; + var source; + var sourcePosition; + if (isSourceMapping(mapping)) { + var sourceFilePath = sourceFileCanonicalPaths[mapping.sourceIndex]; + var sourceFile = host.getSourceFileLike(sourceFilePath); + source = map.sources[mapping.sourceIndex]; + sourcePosition = sourceFile !== undefined + ? ts.getPositionOfLineAndCharacterWithEdits(sourceFile, mapping.sourceLine, mapping.sourceCharacter) + : -1; + } + return { + generatedPosition: generatedPosition, + source: source, + sourceIndex: mapping.sourceIndex, + sourcePosition: sourcePosition, + nameIndex: mapping.nameIndex + }; + } + function getDecodedMappings() { + if (decodedMappings === undefined) { + var decoder = decodeMappings(map.mappings); + var mappings = ts.arrayFrom(decoder, processMapping); + if (decoder.error !== undefined) { + if (host.log) { + host.log("Encountered error while decoding sourcemap: " + decoder.error); + } + decodedMappings = ts.emptyArray; + } + else { + decodedMappings = mappings; + } + } + return decodedMappings; + } + function getSourceMappings(sourceIndex) { + if (sourceMappings === undefined) { + var lists = []; + for (var _i = 0, _a = getDecodedMappings(); _i < _a.length; _i++) { + var mapping = _a[_i]; + if (!isSourceMappedPosition(mapping)) + continue; + var list = lists[mapping.sourceIndex]; + if (!list) + lists[mapping.sourceIndex] = list = []; + list.push(mapping); + } + sourceMappings = lists.map(function (list) { return ts.sortAndDeduplicate(list, compareSourcePositions, sameMappedPosition); }); + } + return sourceMappings[sourceIndex]; + } + function getGeneratedMappings() { + if (generatedMappings === undefined) { + var list = []; + for (var _i = 0, _a = getDecodedMappings(); _i < _a.length; _i++) { + var mapping = _a[_i]; + list.push(mapping); + } + generatedMappings = ts.sortAndDeduplicate(list, compareGeneratedPositions, sameMappedPosition); + } + return generatedMappings; + } + function getGeneratedPosition(loc) { + var sourceIndex = sourceToSourceIndexMap.get(host.getCanonicalFileName(loc.fileName)); + if (sourceIndex === undefined) + return loc; + var sourceMappings = getSourceMappings(sourceIndex); + if (!ts.some(sourceMappings)) + return loc; + var targetIndex = ts.binarySearchKey(sourceMappings, loc.pos, getSourcePositionOfMapping, ts.compareValues); + if (targetIndex < 0) { + targetIndex = ~targetIndex; + } + var mapping = sourceMappings[targetIndex]; + if (mapping === undefined || mapping.sourceIndex !== sourceIndex) { + return loc; + } + return { fileName: generatedAbsoluteFilePath, pos: mapping.generatedPosition }; + } + function getSourcePosition(loc) { + var generatedMappings = getGeneratedMappings(); + if (!ts.some(generatedMappings)) + return loc; + var targetIndex = ts.binarySearchKey(generatedMappings, loc.pos, getGeneratedPositionOfMapping, ts.compareValues); + if (targetIndex < 0) { + targetIndex = ~targetIndex; + } + var mapping = generatedMappings[targetIndex]; + if (mapping === undefined || !isSourceMappedPosition(mapping)) { + return loc; + } + return { fileName: sourceFileAbsolutePaths[mapping.sourceIndex], pos: mapping.sourcePosition }; + } + } + ts.createDocumentPositionMapper = createDocumentPositionMapper; + ts.identitySourceMapConsumer = { + getSourcePosition: ts.identity, + getGeneratedPosition: ts.identity + }; +})(ts || (ts = {})); +var ts; +(function (ts) { + function getOriginalNodeId(node) { + node = ts.getOriginalNode(node); + return node ? ts.getNodeId(node) : 0; + } + ts.getOriginalNodeId = getOriginalNodeId; + function containsDefaultReference(node) { + if (!node) + return false; + if (!ts.isNamedImports(node)) + return false; + return ts.some(node.elements, isNamedDefaultReference); + } + function isNamedDefaultReference(e) { + return e.propertyName !== undefined && e.propertyName.escapedText === "default"; + } + function chainBundle(transformSourceFile) { + return transformSourceFileOrBundle; + function transformSourceFileOrBundle(node) { + return node.kind === 279 ? transformSourceFile(node) : transformBundle(node); + } + function transformBundle(node) { + return ts.createBundle(ts.map(node.sourceFiles, transformSourceFile), node.prepends); + } + } + ts.chainBundle = chainBundle; + function getImportNeedsImportStarHelper(node) { + if (!!ts.getNamespaceDeclarationNode(node)) { + return true; + } + var bindings = node.importClause && node.importClause.namedBindings; + if (!bindings) { + return false; + } + if (!ts.isNamedImports(bindings)) + return false; + var defaultRefCount = 0; + for (var _i = 0, _a = bindings.elements; _i < _a.length; _i++) { + var binding = _a[_i]; + if (isNamedDefaultReference(binding)) { + defaultRefCount++; + } + } + return (defaultRefCount > 0 && defaultRefCount !== bindings.elements.length) || (!!(bindings.elements.length - defaultRefCount) && ts.isDefaultImport(node)); + } + ts.getImportNeedsImportStarHelper = getImportNeedsImportStarHelper; + function getImportNeedsImportDefaultHelper(node) { + return !getImportNeedsImportStarHelper(node) && (ts.isDefaultImport(node) || (!!node.importClause && ts.isNamedImports(node.importClause.namedBindings) && containsDefaultReference(node.importClause.namedBindings))); + } + ts.getImportNeedsImportDefaultHelper = getImportNeedsImportDefaultHelper; + function collectExternalModuleInfo(sourceFile, resolver, compilerOptions) { + var externalImports = []; + var exportSpecifiers = ts.createMultiMap(); + var exportedBindings = []; + var uniqueExports = ts.createMap(); + var exportedNames; + var hasExportDefault = false; + var exportEquals; + var hasExportStarsToExportValues = false; + var hasImportStarOrImportDefault = false; + for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { + var node = _a[_i]; + switch (node.kind) { + case 249: + externalImports.push(node); + hasImportStarOrImportDefault = hasImportStarOrImportDefault || getImportNeedsImportStarHelper(node) || getImportNeedsImportDefaultHelper(node); + break; + case 248: + if (node.moduleReference.kind === 259) { + externalImports.push(node); + } + break; + case 255: + if (node.moduleSpecifier) { + if (!node.exportClause) { + externalImports.push(node); + hasExportStarsToExportValues = true; + } + else { + externalImports.push(node); + } + } + else { + for (var _b = 0, _c = node.exportClause.elements; _b < _c.length; _b++) { + var specifier = _c[_b]; + if (!uniqueExports.get(ts.idText(specifier.name))) { + var name = specifier.propertyName || specifier.name; + exportSpecifiers.add(ts.idText(name), specifier); + var decl = resolver.getReferencedImportDeclaration(name) + || resolver.getReferencedValueDeclaration(name); + if (decl) { + multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(decl), specifier.name); + } + uniqueExports.set(ts.idText(specifier.name), true); + exportedNames = ts.append(exportedNames, specifier.name); + } + } + } + break; + case 254: + if (node.isExportEquals && !exportEquals) { + exportEquals = node; + } + break; + case 219: + if (ts.hasModifier(node, 1)) { + for (var _d = 0, _e = node.declarationList.declarations; _d < _e.length; _d++) { + var decl = _e[_d]; + exportedNames = collectExportedVariableInfo(decl, uniqueExports, exportedNames); + } + } + break; + case 239: + if (ts.hasModifier(node, 1)) { + if (ts.hasModifier(node, 512)) { + if (!hasExportDefault) { + multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), ts.getDeclarationName(node)); + hasExportDefault = true; + } + } + else { + var name = node.name; + if (!uniqueExports.get(ts.idText(name))) { + multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), name); + uniqueExports.set(ts.idText(name), true); + exportedNames = ts.append(exportedNames, name); + } + } + } + break; + case 240: + if (ts.hasModifier(node, 1)) { + if (ts.hasModifier(node, 512)) { + if (!hasExportDefault) { + multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), ts.getDeclarationName(node)); + hasExportDefault = true; + } + } + else { + var name = node.name; + if (name && !uniqueExports.get(ts.idText(name))) { + multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), name); + uniqueExports.set(ts.idText(name), true); + exportedNames = ts.append(exportedNames, name); + } + } + } + break; + } + } + var externalHelpersModuleName = ts.getOrCreateExternalHelpersModuleNameIfNeeded(sourceFile, compilerOptions, hasExportStarsToExportValues, hasImportStarOrImportDefault); + var externalHelpersImportDeclaration = externalHelpersModuleName && ts.createImportDeclaration(undefined, undefined, ts.createImportClause(undefined, ts.createNamespaceImport(externalHelpersModuleName)), ts.createLiteral(ts.externalHelpersModuleNameText)); + if (externalHelpersImportDeclaration) { + ts.addEmitFlags(externalHelpersImportDeclaration, 67108864); + externalImports.unshift(externalHelpersImportDeclaration); + } + return { externalImports: externalImports, exportSpecifiers: exportSpecifiers, exportEquals: exportEquals, hasExportStarsToExportValues: hasExportStarsToExportValues, exportedBindings: exportedBindings, exportedNames: exportedNames, externalHelpersImportDeclaration: externalHelpersImportDeclaration }; + } + ts.collectExternalModuleInfo = collectExternalModuleInfo; + function collectExportedVariableInfo(decl, uniqueExports, exportedNames) { + if (ts.isBindingPattern(decl.name)) { + for (var _i = 0, _a = decl.name.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (!ts.isOmittedExpression(element)) { + exportedNames = collectExportedVariableInfo(element, uniqueExports, exportedNames); + } + } + } + else if (!ts.isGeneratedIdentifier(decl.name)) { + var text = ts.idText(decl.name); + if (!uniqueExports.get(text)) { + uniqueExports.set(text, true); + exportedNames = ts.append(exportedNames, decl.name); + } + } + return exportedNames; + } + function multiMapSparseArrayAdd(map, key, value) { + var values = map[key]; + if (values) { + values.push(value); + } + else { + map[key] = values = [value]; + } + return values; + } + function isSimpleCopiableExpression(expression) { + return ts.isStringLiteralLike(expression) || + expression.kind === 8 || + ts.isKeyword(expression.kind) || + ts.isIdentifier(expression); + } + ts.isSimpleCopiableExpression = isSimpleCopiableExpression; + function helperString(input) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + return function (uniqueName) { + var result = ""; + for (var i = 0; i < args.length; i++) { + result += input[i]; + result += uniqueName(args[i]); + } + result += input[input.length - 1]; + return result; + }; + } + ts.helperString = helperString; +})(ts || (ts = {})); +var ts; +(function (ts) { + function flattenDestructuringAssignment(node, visitor, context, level, needsValue, createAssignmentCallback) { + var location = node; + var value; + if (ts.isDestructuringAssignment(node)) { + value = node.right; + while (ts.isEmptyArrayLiteral(node.left) || ts.isEmptyObjectLiteral(node.left)) { + if (ts.isDestructuringAssignment(value)) { + location = node = value; + value = node.right; + } + else { + return ts.visitNode(value, visitor, ts.isExpression); + } + } + } + var expressions; + var flattenContext = { + context: context, + level: level, + downlevelIteration: !!context.getCompilerOptions().downlevelIteration, + hoistTempVariables: true, + emitExpression: emitExpression, + emitBindingOrAssignment: emitBindingOrAssignment, + createArrayBindingOrAssignmentPattern: makeArrayAssignmentPattern, + createObjectBindingOrAssignmentPattern: makeObjectAssignmentPattern, + createArrayBindingOrAssignmentElement: makeAssignmentElement, + visitor: visitor + }; + if (value) { + value = ts.visitNode(value, visitor, ts.isExpression); + if (ts.isIdentifier(value) && bindingOrAssignmentElementAssignsToName(node, value.escapedText)) { + value = ensureIdentifier(flattenContext, value, false, location); + } + else if (needsValue) { + value = ensureIdentifier(flattenContext, value, true, location); + } + else if (ts.nodeIsSynthesized(node)) { + location = value; + } + } + flattenBindingOrAssignmentElement(flattenContext, node, value, location, ts.isDestructuringAssignment(node)); + if (value && needsValue) { + if (!ts.some(expressions)) { + return value; + } + expressions.push(value); + } + return ts.aggregateTransformFlags(ts.inlineExpressions(expressions)) || ts.createOmittedExpression(); + function emitExpression(expression) { + ts.setEmitFlags(expression, 64); + ts.aggregateTransformFlags(expression); + expressions = ts.append(expressions, expression); + } + function emitBindingOrAssignment(target, value, location, original) { + ts.Debug.assertNode(target, createAssignmentCallback ? ts.isIdentifier : ts.isExpression); + var expression = createAssignmentCallback + ? createAssignmentCallback(target, value, location) + : ts.setTextRange(ts.createAssignment(ts.visitNode(target, visitor, ts.isExpression), value), location); + expression.original = original; + emitExpression(expression); + } + } + ts.flattenDestructuringAssignment = flattenDestructuringAssignment; + function bindingOrAssignmentElementAssignsToName(element, escapedName) { + var target = ts.getTargetOfBindingOrAssignmentElement(element); + if (ts.isBindingOrAssignmentPattern(target)) { + return bindingOrAssignmentPatternAssignsToName(target, escapedName); + } + else if (ts.isIdentifier(target)) { + return target.escapedText === escapedName; + } + return false; + } + function bindingOrAssignmentPatternAssignsToName(pattern, escapedName) { + var elements = ts.getElementsOfBindingOrAssignmentPattern(pattern); + for (var _i = 0, elements_3 = elements; _i < elements_3.length; _i++) { + var element = elements_3[_i]; + if (bindingOrAssignmentElementAssignsToName(element, escapedName)) { + return true; + } + } + return false; + } + function flattenDestructuringBinding(node, visitor, context, level, rval, hoistTempVariables, skipInitializer) { + if (hoistTempVariables === void 0) { hoistTempVariables = false; } + var pendingExpressions; + var pendingDeclarations = []; + var declarations = []; + var flattenContext = { + context: context, + level: level, + downlevelIteration: !!context.getCompilerOptions().downlevelIteration, + hoistTempVariables: hoistTempVariables, + emitExpression: emitExpression, + emitBindingOrAssignment: emitBindingOrAssignment, + createArrayBindingOrAssignmentPattern: makeArrayBindingPattern, + createObjectBindingOrAssignmentPattern: makeObjectBindingPattern, + createArrayBindingOrAssignmentElement: makeBindingElement, + visitor: visitor + }; + if (ts.isVariableDeclaration(node)) { + var initializer = ts.getInitializerOfBindingOrAssignmentElement(node); + if (initializer && ts.isIdentifier(initializer) && bindingOrAssignmentElementAssignsToName(node, initializer.escapedText)) { + initializer = ensureIdentifier(flattenContext, initializer, false, initializer); + node = ts.updateVariableDeclaration(node, node.name, node.type, initializer); + } + } + flattenBindingOrAssignmentElement(flattenContext, node, rval, node, skipInitializer); + if (pendingExpressions) { + var temp = ts.createTempVariable(undefined); + if (hoistTempVariables) { + var value = ts.inlineExpressions(pendingExpressions); + pendingExpressions = undefined; + emitBindingOrAssignment(temp, value, undefined, undefined); + } + else { + context.hoistVariableDeclaration(temp); + var pendingDeclaration = ts.last(pendingDeclarations); + pendingDeclaration.pendingExpressions = ts.append(pendingDeclaration.pendingExpressions, ts.createAssignment(temp, pendingDeclaration.value)); + ts.addRange(pendingDeclaration.pendingExpressions, pendingExpressions); + pendingDeclaration.value = temp; + } + } + for (var _i = 0, pendingDeclarations_1 = pendingDeclarations; _i < pendingDeclarations_1.length; _i++) { + var _a = pendingDeclarations_1[_i], pendingExpressions_1 = _a.pendingExpressions, name = _a.name, value = _a.value, location = _a.location, original = _a.original; + var variable = ts.createVariableDeclaration(name, undefined, pendingExpressions_1 ? ts.inlineExpressions(ts.append(pendingExpressions_1, value)) : value); + variable.original = original; + ts.setTextRange(variable, location); + if (ts.isIdentifier(name)) { + ts.setEmitFlags(variable, 64); + } + ts.aggregateTransformFlags(variable); + declarations.push(variable); + } + return declarations; + function emitExpression(value) { + pendingExpressions = ts.append(pendingExpressions, value); + } + function emitBindingOrAssignment(target, value, location, original) { + ts.Debug.assertNode(target, ts.isBindingName); + if (pendingExpressions) { + value = ts.inlineExpressions(ts.append(pendingExpressions, value)); + pendingExpressions = undefined; + } + pendingDeclarations.push({ pendingExpressions: pendingExpressions, name: target, value: value, location: location, original: original }); + } + } + ts.flattenDestructuringBinding = flattenDestructuringBinding; + function flattenBindingOrAssignmentElement(flattenContext, element, value, location, skipInitializer) { + if (!skipInitializer) { + var initializer = ts.visitNode(ts.getInitializerOfBindingOrAssignmentElement(element), flattenContext.visitor, ts.isExpression); + if (initializer) { + value = value ? createDefaultValueCheck(flattenContext, value, initializer, location) : initializer; + } + else if (!value) { + value = ts.createVoidZero(); + } + } + var bindingTarget = ts.getTargetOfBindingOrAssignmentElement(element); + if (ts.isObjectBindingOrAssignmentPattern(bindingTarget)) { + flattenObjectBindingOrAssignmentPattern(flattenContext, element, bindingTarget, value, location); + } + else if (ts.isArrayBindingOrAssignmentPattern(bindingTarget)) { + flattenArrayBindingOrAssignmentPattern(flattenContext, element, bindingTarget, value, location); + } + else { + flattenContext.emitBindingOrAssignment(bindingTarget, value, location, element); + } + } + function flattenObjectBindingOrAssignmentPattern(flattenContext, parent, pattern, value, location) { + var elements = ts.getElementsOfBindingOrAssignmentPattern(pattern); + var numElements = elements.length; + if (numElements !== 1) { + var reuseIdentifierExpressions = !ts.isDeclarationBindingElement(parent) || numElements !== 0; + value = ensureIdentifier(flattenContext, value, reuseIdentifierExpressions, location); + } + var bindingElements; + var computedTempVariables; + for (var i = 0; i < numElements; i++) { + var element = elements[i]; + if (!ts.getRestIndicatorOfBindingOrAssignmentElement(element)) { + var propertyName = ts.getPropertyNameOfBindingOrAssignmentElement(element); + if (flattenContext.level >= 1 + && !(element.transformFlags & (131072 | 262144)) + && !(ts.getTargetOfBindingOrAssignmentElement(element).transformFlags & (131072 | 262144)) + && !ts.isComputedPropertyName(propertyName)) { + bindingElements = ts.append(bindingElements, element); + } + else { + if (bindingElements) { + flattenContext.emitBindingOrAssignment(flattenContext.createObjectBindingOrAssignmentPattern(bindingElements), value, location, pattern); + bindingElements = undefined; + } + var rhsValue = createDestructuringPropertyAccess(flattenContext, value, propertyName); + if (ts.isComputedPropertyName(propertyName)) { + computedTempVariables = ts.append(computedTempVariables, rhsValue.argumentExpression); + } + flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, element); + } + } + else if (i === numElements - 1) { + if (bindingElements) { + flattenContext.emitBindingOrAssignment(flattenContext.createObjectBindingOrAssignmentPattern(bindingElements), value, location, pattern); + bindingElements = undefined; + } + var rhsValue = createRestCall(flattenContext.context, value, elements, computedTempVariables, pattern); + flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, element); + } + } + if (bindingElements) { + flattenContext.emitBindingOrAssignment(flattenContext.createObjectBindingOrAssignmentPattern(bindingElements), value, location, pattern); + } + } + function flattenArrayBindingOrAssignmentPattern(flattenContext, parent, pattern, value, location) { + var elements = ts.getElementsOfBindingOrAssignmentPattern(pattern); + var numElements = elements.length; + if (flattenContext.level < 1 && flattenContext.downlevelIteration) { + value = ensureIdentifier(flattenContext, ts.createReadHelper(flattenContext.context, value, numElements > 0 && ts.getRestIndicatorOfBindingOrAssignmentElement(elements[numElements - 1]) + ? undefined + : numElements, location), false, location); + } + else if (numElements !== 1 && (flattenContext.level < 1 || numElements === 0) + || ts.every(elements, ts.isOmittedExpression)) { + var reuseIdentifierExpressions = !ts.isDeclarationBindingElement(parent) || numElements !== 0; + value = ensureIdentifier(flattenContext, value, reuseIdentifierExpressions, location); + } + var bindingElements; + var restContainingElements; + for (var i = 0; i < numElements; i++) { + var element = elements[i]; + if (flattenContext.level >= 1) { + if (element.transformFlags & 262144) { + var temp = ts.createTempVariable(undefined); + if (flattenContext.hoistTempVariables) { + flattenContext.context.hoistVariableDeclaration(temp); + } + restContainingElements = ts.append(restContainingElements, [temp, element]); + bindingElements = ts.append(bindingElements, flattenContext.createArrayBindingOrAssignmentElement(temp)); + } + else { + bindingElements = ts.append(bindingElements, element); + } + } + else if (ts.isOmittedExpression(element)) { + continue; + } + else if (!ts.getRestIndicatorOfBindingOrAssignmentElement(element)) { + var rhsValue = ts.createElementAccess(value, i); + flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, element); + } + else if (i === numElements - 1) { + var rhsValue = ts.createArraySlice(value, i); + flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, element); + } + } + if (bindingElements) { + flattenContext.emitBindingOrAssignment(flattenContext.createArrayBindingOrAssignmentPattern(bindingElements), value, location, pattern); + } + if (restContainingElements) { + for (var _i = 0, restContainingElements_1 = restContainingElements; _i < restContainingElements_1.length; _i++) { + var _a = restContainingElements_1[_i], id = _a[0], element = _a[1]; + flattenBindingOrAssignmentElement(flattenContext, element, id, element); + } + } + } + function createDefaultValueCheck(flattenContext, value, defaultValue, location) { + value = ensureIdentifier(flattenContext, value, true, location); + return ts.createConditional(ts.createTypeCheck(value, "undefined"), defaultValue, value); + } + function createDestructuringPropertyAccess(flattenContext, value, propertyName) { + if (ts.isComputedPropertyName(propertyName)) { + var argumentExpression = ensureIdentifier(flattenContext, ts.visitNode(propertyName.expression, flattenContext.visitor), false, propertyName); + return ts.createElementAccess(value, argumentExpression); + } + else if (ts.isStringOrNumericLiteralLike(propertyName)) { + var argumentExpression = ts.getSynthesizedClone(propertyName); + argumentExpression.text = argumentExpression.text; + return ts.createElementAccess(value, argumentExpression); + } + else { + var name = ts.createIdentifier(ts.idText(propertyName)); + return ts.createPropertyAccess(value, name); + } + } + function ensureIdentifier(flattenContext, value, reuseIdentifierExpressions, location) { + if (ts.isIdentifier(value) && reuseIdentifierExpressions) { + return value; + } + else { + var temp = ts.createTempVariable(undefined); + if (flattenContext.hoistTempVariables) { + flattenContext.context.hoistVariableDeclaration(temp); + flattenContext.emitExpression(ts.setTextRange(ts.createAssignment(temp, value), location)); + } + else { + flattenContext.emitBindingOrAssignment(temp, value, location, undefined); + } + return temp; + } + } + function makeArrayBindingPattern(elements) { + ts.Debug.assertEachNode(elements, ts.isArrayBindingElement); + return ts.createArrayBindingPattern(elements); + } + function makeArrayAssignmentPattern(elements) { + return ts.createArrayLiteral(ts.map(elements, ts.convertToArrayAssignmentElement)); + } + function makeObjectBindingPattern(elements) { + ts.Debug.assertEachNode(elements, ts.isBindingElement); + return ts.createObjectBindingPattern(elements); + } + function makeObjectAssignmentPattern(elements) { + return ts.createObjectLiteral(ts.map(elements, ts.convertToObjectAssignmentElement)); + } + function makeBindingElement(name) { + return ts.createBindingElement(undefined, undefined, name); + } + function makeAssignmentElement(name) { + return name; + } + var restHelper = { + name: "typescript:rest", + scoped: false, + text: "\n var __rest = (this && this.__rest) || function (s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) if (e.indexOf(p[i]) < 0)\n t[p[i]] = s[p[i]];\n return t;\n };" + }; + function createRestCall(context, value, elements, computedTempVariables, location) { + context.requestEmitHelper(restHelper); + var propertyNames = []; + var computedTempVariableOffset = 0; + for (var i = 0; i < elements.length - 1; i++) { + var propertyName = ts.getPropertyNameOfBindingOrAssignmentElement(elements[i]); + if (propertyName) { + if (ts.isComputedPropertyName(propertyName)) { + var temp = computedTempVariables[computedTempVariableOffset]; + computedTempVariableOffset++; + propertyNames.push(ts.createConditional(ts.createTypeCheck(temp, "symbol"), temp, ts.createAdd(temp, ts.createLiteral("")))); + } + else { + propertyNames.push(ts.createLiteral(propertyName)); + } + } + } + return ts.createCall(ts.getHelperName("__rest"), undefined, [ + value, + ts.setTextRange(ts.createArrayLiteral(propertyNames), location) + ]); + } +})(ts || (ts = {})); +var ts; +(function (ts) { + var USE_NEW_TYPE_METADATA_FORMAT = false; + function transformTypeScript(context) { + var startLexicalEnvironment = context.startLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; + var resolver = context.getEmitResolver(); + var compilerOptions = context.getCompilerOptions(); + var strictNullChecks = ts.getStrictOptionValue(compilerOptions, "strictNullChecks"); + var languageVersion = ts.getEmitScriptTarget(compilerOptions); + var moduleKind = ts.getEmitModuleKind(compilerOptions); + var previousOnEmitNode = context.onEmitNode; + var previousOnSubstituteNode = context.onSubstituteNode; + context.onEmitNode = onEmitNode; + context.onSubstituteNode = onSubstituteNode; + context.enableSubstitution(189); + context.enableSubstitution(190); + var currentSourceFile; + var currentNamespace; + var currentNamespaceContainerName; + var currentLexicalScope; + var currentNameScope; + var currentScopeFirstDeclarationsOfName; + var enabledSubstitutions; + var classAliases; + var applicableSubstitutions; + var pendingExpressions; + return transformSourceFileOrBundle; + function transformSourceFileOrBundle(node) { + if (node.kind === 280) { + return transformBundle(node); + } + return transformSourceFile(node); + } + function transformBundle(node) { + return ts.createBundle(node.sourceFiles.map(transformSourceFile), ts.mapDefined(node.prepends, function (prepend) { + if (prepend.kind === 282) { + return ts.createUnparsedSourceFile(prepend.javascriptText, prepend.javascriptMapPath, prepend.javascriptMapText); + } + return prepend; + })); + } + function transformSourceFile(node) { + if (node.isDeclarationFile) { + return node; + } + currentSourceFile = node; + var visited = saveStateAndInvoke(node, visitSourceFile); + ts.addEmitHelpers(visited, context.readEmitHelpers()); + currentSourceFile = undefined; + return visited; + } + function saveStateAndInvoke(node, f) { + var savedCurrentScope = currentLexicalScope; + var savedCurrentNameScope = currentNameScope; + var savedCurrentScopeFirstDeclarationsOfName = currentScopeFirstDeclarationsOfName; + onBeforeVisitNode(node); + var visited = f(node); + if (currentLexicalScope !== savedCurrentScope) { + currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName; + } + currentLexicalScope = savedCurrentScope; + currentNameScope = savedCurrentNameScope; + return visited; + } + function onBeforeVisitNode(node) { + switch (node.kind) { + case 279: + case 246: + case 245: + case 218: + currentLexicalScope = node; + currentNameScope = undefined; + currentScopeFirstDeclarationsOfName = undefined; + break; + case 240: + case 239: + if (ts.hasModifier(node, 2)) { + break; + } + if (node.name) { + recordEmittedDeclarationInScope(node); + } + else { + ts.Debug.assert(node.kind === 240 || ts.hasModifier(node, 512)); + } + if (ts.isClassDeclaration(node)) { + currentNameScope = node; + } + break; + } + } + function visitor(node) { + return saveStateAndInvoke(node, visitorWorker); + } + function visitorWorker(node) { + if (node.transformFlags & 1) { + return visitTypeScript(node); + } + else if (node.transformFlags & 2) { + return ts.visitEachChild(node, visitor, context); + } + return node; + } + function sourceElementVisitor(node) { + return saveStateAndInvoke(node, sourceElementVisitorWorker); + } + function sourceElementVisitorWorker(node) { + switch (node.kind) { + case 249: + case 248: + case 254: + case 255: + return visitEllidableStatement(node); + default: + return visitorWorker(node); + } + } + function visitEllidableStatement(node) { + var parsed = ts.getParseTreeNode(node); + if (parsed !== node) { + if (node.transformFlags & 2) { + return ts.visitEachChild(node, visitor, context); + } + return node; + } + switch (node.kind) { + case 249: + return visitImportDeclaration(node); + case 248: + return visitImportEqualsDeclaration(node); + case 254: + return visitExportAssignment(node); + case 255: + return visitExportDeclaration(node); + default: + ts.Debug.fail("Unhandled ellided statement"); + } + } + function namespaceElementVisitor(node) { + return saveStateAndInvoke(node, namespaceElementVisitorWorker); + } + function namespaceElementVisitorWorker(node) { + if (node.kind === 255 || + node.kind === 249 || + node.kind === 250 || + (node.kind === 248 && + node.moduleReference.kind === 259)) { + return undefined; + } + else if (node.transformFlags & 1 || ts.hasModifier(node, 1)) { + return visitTypeScript(node); + } + else if (node.transformFlags & 2) { + return ts.visitEachChild(node, visitor, context); + } + return node; + } + function classElementVisitor(node) { + return saveStateAndInvoke(node, classElementVisitorWorker); + } + function classElementVisitorWorker(node) { + switch (node.kind) { + case 157: + return undefined; + case 154: + case 162: + case 158: + case 159: + case 156: + return visitorWorker(node); + case 217: + return node; + default: + return ts.Debug.failBadSyntaxKind(node); + } + } + function modifierVisitor(node) { + if (ts.modifierToFlag(node.kind) & 2270) { + return undefined; + } + else if (currentNamespace && node.kind === 85) { + return undefined; + } + return node; + } + function visitTypeScript(node) { + if (ts.hasModifier(node, 2) && ts.isStatement(node)) { + return ts.createNotEmittedStatement(node); + } + switch (node.kind) { + case 85: + case 80: + return currentNamespace ? undefined : node; + case 115: + case 113: + case 114: + case 118: + case 77: + case 125: + case 133: + case 169: + case 170: + case 171: + case 172: + case 168: + case 163: + case 150: + case 120: + case 143: + case 123: + case 138: + case 135: + case 132: + case 106: + case 139: + case 166: + case 165: + case 167: + case 164: + case 173: + case 174: + case 175: + case 177: + case 178: + case 179: + case 180: + case 181: + case 182: + case 162: + case 152: + case 242: + return undefined; + case 154: + return visitPropertyDeclaration(node); + case 247: + return undefined; + case 157: + return visitConstructor(node); + case 241: + return ts.createNotEmittedStatement(node); + case 240: + return visitClassDeclaration(node); + case 209: + return visitClassExpression(node); + case 273: + return visitHeritageClause(node); + case 211: + return visitExpressionWithTypeArguments(node); + case 156: + return visitMethodDeclaration(node); + case 158: + return visitGetAccessor(node); + case 159: + return visitSetAccessor(node); + case 239: + return visitFunctionDeclaration(node); + case 196: + return visitFunctionExpression(node); + case 197: + return visitArrowFunction(node); + case 151: + return visitParameter(node); + case 195: + return visitParenthesizedExpression(node); + case 194: + case 212: + return visitAssertionExpression(node); + case 191: + return visitCallExpression(node); + case 192: + return visitNewExpression(node); + case 193: + return visitTaggedTemplateExpression(node); + case 213: + return visitNonNullExpression(node); + case 243: + return visitEnumDeclaration(node); + case 219: + return visitVariableStatement(node); + case 237: + return visitVariableDeclaration(node); + case 244: + return visitModuleDeclaration(node); + case 248: + return visitImportEqualsDeclaration(node); + default: + return ts.Debug.failBadSyntaxKind(node); + } + } + function visitSourceFile(node) { + var alwaysStrict = ts.getStrictOptionValue(compilerOptions, "alwaysStrict") && + !(ts.isExternalModule(node) && moduleKind >= ts.ModuleKind.ES2015) && + !ts.isJsonSourceFile(node); + return ts.updateSourceFileNode(node, ts.visitLexicalEnvironment(node.statements, sourceElementVisitor, context, 0, alwaysStrict)); + } + function shouldEmitDecorateCallForClass(node) { + if (node.decorators && node.decorators.length > 0) { + return true; + } + var constructor = ts.getFirstConstructorWithBody(node); + if (constructor) { + return ts.forEach(constructor.parameters, shouldEmitDecorateCallForParameter); + } + return false; + } + function shouldEmitDecorateCallForParameter(parameter) { + return parameter.decorators !== undefined && parameter.decorators.length > 0; + } + function getClassFacts(node, staticProperties) { + var facts = 0; + if (ts.some(staticProperties)) + facts |= 1; + var extendsClauseElement = ts.getEffectiveBaseTypeNode(node); + if (extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 96) + facts |= 64; + if (shouldEmitDecorateCallForClass(node)) + facts |= 2; + if (ts.childIsDecorated(node)) + facts |= 4; + if (isExportOfNamespace(node)) + facts |= 8; + else if (isDefaultExternalModuleExport(node)) + facts |= 32; + else if (isNamedExternalModuleExport(node)) + facts |= 16; + if (languageVersion <= 1 && (facts & 7)) + facts |= 128; + return facts; + } + function visitClassDeclaration(node) { + var savedPendingExpressions = pendingExpressions; + pendingExpressions = undefined; + var staticProperties = getInitializedProperties(node, true); + var facts = getClassFacts(node, staticProperties); + if (facts & 128) { + context.startLexicalEnvironment(); + } + var name = node.name || (facts & 5 ? ts.getGeneratedNameForNode(node) : undefined); + var classStatement = facts & 2 + ? createClassDeclarationHeadWithDecorators(node, name, facts) + : createClassDeclarationHeadWithoutDecorators(node, name, facts); + var statements = [classStatement]; + if (ts.some(pendingExpressions)) { + statements.push(ts.createExpressionStatement(ts.inlineExpressions(pendingExpressions))); + } + pendingExpressions = savedPendingExpressions; + if (facts & 1) { + addInitializedPropertyStatements(statements, staticProperties, facts & 128 ? ts.getInternalName(node) : ts.getLocalName(node)); + } + addClassElementDecorationStatements(statements, node, false); + addClassElementDecorationStatements(statements, node, true); + addConstructorDecorationStatement(statements, node); + if (facts & 128) { + var closingBraceLocation = ts.createTokenRange(ts.skipTrivia(currentSourceFile.text, node.members.end), 19); + var localName = ts.getInternalName(node); + var outer = ts.createPartiallyEmittedExpression(localName); + outer.end = closingBraceLocation.end; + ts.setEmitFlags(outer, 1536); + var statement = ts.createReturn(outer); + statement.pos = closingBraceLocation.pos; + ts.setEmitFlags(statement, 1536 | 384); + statements.push(statement); + ts.addStatementsAfterPrologue(statements, context.endLexicalEnvironment()); + var iife = ts.createImmediatelyInvokedArrowFunction(statements); + ts.setEmitFlags(iife, 33554432); + var varStatement = ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(ts.getLocalName(node, false, false), undefined, iife) + ])); + ts.setOriginalNode(varStatement, node); + ts.setCommentRange(varStatement, node); + ts.setSourceMapRange(varStatement, ts.moveRangePastDecorators(node)); + ts.startOnNewLine(varStatement); + statements = [varStatement]; + } + if (facts & 8) { + addExportMemberAssignment(statements, node); + } + else if (facts & 128 || facts & 2) { + if (facts & 32) { + statements.push(ts.createExportDefault(ts.getLocalName(node, false, true))); + } + else if (facts & 16) { + statements.push(ts.createExternalModuleExport(ts.getLocalName(node, false, true))); + } + } + if (statements.length > 1) { + statements.push(ts.createEndOfDeclarationMarker(node)); + ts.setEmitFlags(classStatement, ts.getEmitFlags(classStatement) | 4194304); + } + return ts.singleOrMany(statements); + } + function createClassDeclarationHeadWithoutDecorators(node, name, facts) { + var modifiers = !(facts & 128) + ? ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier) + : undefined; + var classDeclaration = ts.createClassDeclaration(undefined, modifiers, name, undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node, (facts & 64) !== 0)); + var emitFlags = ts.getEmitFlags(node); + if (facts & 1) { + emitFlags |= 32; + } + ts.setTextRange(classDeclaration, node); + ts.setOriginalNode(classDeclaration, node); + ts.setEmitFlags(classDeclaration, emitFlags); + return classDeclaration; + } + function createClassDeclarationHeadWithDecorators(node, name, facts) { + var location = ts.moveRangePastDecorators(node); + var classAlias = getClassAliasIfNeeded(node); + var declName = ts.getLocalName(node, false, true); + var heritageClauses = ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause); + var members = transformClassMembers(node, (facts & 64) !== 0); + var classExpression = ts.createClassExpression(undefined, name, undefined, heritageClauses, members); + ts.setOriginalNode(classExpression, node); + ts.setTextRange(classExpression, location); + var statement = ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(declName, undefined, classAlias ? ts.createAssignment(classAlias, classExpression) : classExpression) + ], 1)); + ts.setOriginalNode(statement, node); + ts.setTextRange(statement, location); + ts.setCommentRange(statement, node); + return statement; + } + function visitClassExpression(node) { + var savedPendingExpressions = pendingExpressions; + pendingExpressions = undefined; + var staticProperties = getInitializedProperties(node, true); + var heritageClauses = ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause); + var members = transformClassMembers(node, ts.some(heritageClauses, function (c) { return c.token === 86; })); + var classExpression = ts.createClassExpression(undefined, node.name, undefined, heritageClauses, members); + ts.setOriginalNode(classExpression, node); + ts.setTextRange(classExpression, node); + if (ts.some(staticProperties) || ts.some(pendingExpressions)) { + var expressions = []; + var isClassWithConstructorReference = resolver.getNodeCheckFlags(node) & 16777216; + var temp = ts.createTempVariable(hoistVariableDeclaration, !!isClassWithConstructorReference); + if (isClassWithConstructorReference) { + enableSubstitutionForClassAliases(); + var alias = ts.getSynthesizedClone(temp); + alias.autoGenerateFlags &= ~8; + classAliases[ts.getOriginalNodeId(node)] = alias; + } + ts.setEmitFlags(classExpression, 65536 | ts.getEmitFlags(classExpression)); + expressions.push(ts.startOnNewLine(ts.createAssignment(temp, classExpression))); + ts.addRange(expressions, ts.map(pendingExpressions, ts.startOnNewLine)); + pendingExpressions = savedPendingExpressions; + ts.addRange(expressions, generateInitializedPropertyExpressions(staticProperties, temp)); + expressions.push(ts.startOnNewLine(temp)); + return ts.inlineExpressions(expressions); + } + pendingExpressions = savedPendingExpressions; + return classExpression; + } + function transformClassMembers(node, isDerivedClass) { + var members = []; + var constructor = transformConstructor(node, isDerivedClass); + if (constructor) { + members.push(constructor); + } + ts.addRange(members, ts.visitNodes(node.members, classElementVisitor, ts.isClassElement)); + return ts.setTextRange(ts.createNodeArray(members), node.members); + } + function transformConstructor(node, isDerivedClass) { + var constructor = ts.getFirstConstructorWithBody(node); + var hasInstancePropertyWithInitializer = ts.forEach(node.members, isInstanceInitializedProperty); + var hasParameterPropertyAssignments = constructor && + constructor.transformFlags & 4096 && + ts.forEach(constructor.parameters, isParameterWithPropertyAssignment); + if (!hasInstancePropertyWithInitializer && !hasParameterPropertyAssignments) { + return ts.visitEachChild(constructor, visitor, context); + } + var parameters = transformConstructorParameters(constructor); + var body = transformConstructorBody(node, constructor, isDerivedClass); + return ts.startOnNewLine(ts.setOriginalNode(ts.setTextRange(ts.createConstructor(undefined, undefined, parameters, body), constructor || node), constructor)); + } + function transformConstructorParameters(constructor) { + return ts.visitParameterList(constructor && constructor.parameters, visitor, context) + || []; + } + function transformConstructorBody(node, constructor, isDerivedClass) { + var statements = []; + var indexOfFirstStatement = 0; + resumeLexicalEnvironment(); + if (constructor) { + indexOfFirstStatement = addPrologueDirectivesAndInitialSuperCall(constructor, statements); + var propertyAssignments = getParametersWithPropertyAssignments(constructor); + ts.addRange(statements, ts.map(propertyAssignments, transformParameterWithPropertyAssignment)); + } + else if (isDerivedClass) { + statements.push(ts.createExpressionStatement(ts.createCall(ts.createSuper(), undefined, [ts.createSpread(ts.createIdentifier("arguments"))]))); + } + var properties = getInitializedProperties(node, false); + addInitializedPropertyStatements(statements, properties, ts.createThis()); + if (constructor) { + ts.addRange(statements, ts.visitNodes(constructor.body.statements, visitor, ts.isStatement, indexOfFirstStatement)); + } + statements = ts.mergeLexicalEnvironment(statements, endLexicalEnvironment()); + return ts.setTextRange(ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), constructor ? constructor.body.statements : node.members), true), constructor ? constructor.body : undefined); + } + function addPrologueDirectivesAndInitialSuperCall(ctor, result) { + if (ctor.body) { + var statements = ctor.body.statements; + var index = ts.addPrologue(result, statements, false, visitor); + if (index === statements.length) { + return index; + } + var statement = statements[index]; + if (statement.kind === 221 && ts.isSuperCall(statement.expression)) { + result.push(ts.visitNode(statement, visitor, ts.isStatement)); + return index + 1; + } + return index; + } + return 0; + } + function getParametersWithPropertyAssignments(node) { + return ts.filter(node.parameters, isParameterWithPropertyAssignment); + } + function isParameterWithPropertyAssignment(parameter) { + return ts.hasModifier(parameter, 92) + && ts.isIdentifier(parameter.name); + } + function transformParameterWithPropertyAssignment(node) { + ts.Debug.assert(ts.isIdentifier(node.name)); + var name = node.name; + var propertyName = ts.getMutableClone(name); + ts.setEmitFlags(propertyName, 1536 | 48); + var localName = ts.getMutableClone(name); + ts.setEmitFlags(localName, 1536); + return ts.startOnNewLine(ts.setEmitFlags(ts.setTextRange(ts.createExpressionStatement(ts.createAssignment(ts.setTextRange(ts.createPropertyAccess(ts.createThis(), propertyName), node.name), localName)), ts.moveRangePos(node, -1)), 1536)); + } + function getInitializedProperties(node, isStatic) { + return ts.filter(node.members, isStatic ? isStaticInitializedProperty : isInstanceInitializedProperty); + } + function isStaticInitializedProperty(member) { + return isInitializedProperty(member, true); + } + function isInstanceInitializedProperty(member) { + return isInitializedProperty(member, false); + } + function isInitializedProperty(member, isStatic) { + return member.kind === 154 + && isStatic === ts.hasModifier(member, 32) + && member.initializer !== undefined; + } + function addInitializedPropertyStatements(statements, properties, receiver) { + for (var _i = 0, properties_9 = properties; _i < properties_9.length; _i++) { + var property = properties_9[_i]; + var statement = ts.createExpressionStatement(transformInitializedProperty(property, receiver)); + ts.setSourceMapRange(statement, ts.moveRangePastModifiers(property)); + ts.setCommentRange(statement, property); + ts.setOriginalNode(statement, property); + statements.push(statement); + } + } + function generateInitializedPropertyExpressions(properties, receiver) { + var expressions = []; + for (var _i = 0, properties_10 = properties; _i < properties_10.length; _i++) { + var property = properties_10[_i]; + var expression = transformInitializedProperty(property, receiver); + ts.startOnNewLine(expression); + ts.setSourceMapRange(expression, ts.moveRangePastModifiers(property)); + ts.setCommentRange(expression, property); + ts.setOriginalNode(expression, property); + expressions.push(expression); + } + return expressions; + } + function transformInitializedProperty(property, receiver) { + var propertyName = ts.isComputedPropertyName(property.name) && !isSimpleInlineableExpression(property.name.expression) + ? ts.updateComputedPropertyName(property.name, ts.getGeneratedNameForNode(property.name)) + : property.name; + var initializer = ts.visitNode(property.initializer, visitor, ts.isExpression); + var memberAccess = ts.createMemberAccessForPropertyName(receiver, propertyName, propertyName); + return ts.createAssignment(memberAccess, initializer); + } + function getDecoratedClassElements(node, isStatic) { + return ts.filter(node.members, isStatic ? function (m) { return isStaticDecoratedClassElement(m, node); } : function (m) { return isInstanceDecoratedClassElement(m, node); }); + } + function isStaticDecoratedClassElement(member, parent) { + return isDecoratedClassElement(member, true, parent); + } + function isInstanceDecoratedClassElement(member, parent) { + return isDecoratedClassElement(member, false, parent); + } + function isDecoratedClassElement(member, isStatic, parent) { + return ts.nodeOrChildIsDecorated(member, parent) + && isStatic === ts.hasModifier(member, 32); + } + function getDecoratorsOfParameters(node) { + var decorators; + if (node) { + var parameters = node.parameters; + for (var i = 0; i < parameters.length; i++) { + var parameter = parameters[i]; + if (decorators || parameter.decorators) { + if (!decorators) { + decorators = new Array(parameters.length); + } + decorators[i] = parameter.decorators; + } + } + } + return decorators; + } + function getAllDecoratorsOfConstructor(node) { + var decorators = node.decorators; + var parameters = getDecoratorsOfParameters(ts.getFirstConstructorWithBody(node)); + if (!decorators && !parameters) { + return undefined; + } + return { + decorators: decorators, + parameters: parameters + }; + } + function getAllDecoratorsOfClassElement(node, member) { + switch (member.kind) { + case 158: + case 159: + return getAllDecoratorsOfAccessors(node, member); + case 156: + return getAllDecoratorsOfMethod(member); + case 154: + return getAllDecoratorsOfProperty(member); + default: + return undefined; + } + } + function getAllDecoratorsOfAccessors(node, accessor) { + if (!accessor.body) { + return undefined; + } + var _a = ts.getAllAccessorDeclarations(node.members, accessor), firstAccessor = _a.firstAccessor, secondAccessor = _a.secondAccessor, setAccessor = _a.setAccessor; + var firstAccessorWithDecorators = firstAccessor.decorators ? firstAccessor : secondAccessor && secondAccessor.decorators ? secondAccessor : undefined; + if (!firstAccessorWithDecorators || accessor !== firstAccessorWithDecorators) { + return undefined; + } + var decorators = firstAccessorWithDecorators.decorators; + var parameters = getDecoratorsOfParameters(setAccessor); + if (!decorators && !parameters) { + return undefined; + } + return { decorators: decorators, parameters: parameters }; + } + function getAllDecoratorsOfMethod(method) { + if (!method.body) { + return undefined; + } + var decorators = method.decorators; + var parameters = getDecoratorsOfParameters(method); + if (!decorators && !parameters) { + return undefined; + } + return { decorators: decorators, parameters: parameters }; + } + function getAllDecoratorsOfProperty(property) { + var decorators = property.decorators; + if (!decorators) { + return undefined; + } + return { decorators: decorators }; + } + function transformAllDecoratorsOfDeclaration(node, container, allDecorators) { + if (!allDecorators) { + return undefined; + } + var decoratorExpressions = []; + ts.addRange(decoratorExpressions, ts.map(allDecorators.decorators, transformDecorator)); + ts.addRange(decoratorExpressions, ts.flatMap(allDecorators.parameters, transformDecoratorsOfParameter)); + addTypeMetadata(node, container, decoratorExpressions); + return decoratorExpressions; + } + function addClassElementDecorationStatements(statements, node, isStatic) { + ts.addRange(statements, ts.map(generateClassElementDecorationExpressions(node, isStatic), expressionToStatement)); + } + function generateClassElementDecorationExpressions(node, isStatic) { + var members = getDecoratedClassElements(node, isStatic); + var expressions; + for (var _i = 0, members_5 = members; _i < members_5.length; _i++) { + var member = members_5[_i]; + var expression = generateClassElementDecorationExpression(node, member); + if (expression) { + if (!expressions) { + expressions = [expression]; + } + else { + expressions.push(expression); + } + } + } + return expressions; + } + function generateClassElementDecorationExpression(node, member) { + var allDecorators = getAllDecoratorsOfClassElement(node, member); + var decoratorExpressions = transformAllDecoratorsOfDeclaration(member, node, allDecorators); + if (!decoratorExpressions) { + return undefined; + } + var prefix = getClassMemberPrefix(node, member); + var memberName = getExpressionForPropertyName(member, true); + var descriptor = languageVersion > 0 + ? member.kind === 154 + ? ts.createVoidZero() + : ts.createNull() + : undefined; + var helper = createDecorateHelper(context, decoratorExpressions, prefix, memberName, descriptor, ts.moveRangePastDecorators(member)); + ts.setEmitFlags(helper, 1536); + return helper; + } + function addConstructorDecorationStatement(statements, node) { + var expression = generateConstructorDecorationExpression(node); + if (expression) { + statements.push(ts.setOriginalNode(ts.createExpressionStatement(expression), node)); + } + } + function generateConstructorDecorationExpression(node) { + var allDecorators = getAllDecoratorsOfConstructor(node); + var decoratorExpressions = transformAllDecoratorsOfDeclaration(node, node, allDecorators); + if (!decoratorExpressions) { + return undefined; + } + var classAlias = classAliases && classAliases[ts.getOriginalNodeId(node)]; + var localName = ts.getLocalName(node, false, true); + var decorate = createDecorateHelper(context, decoratorExpressions, localName); + var expression = ts.createAssignment(localName, classAlias ? ts.createAssignment(classAlias, decorate) : decorate); + ts.setEmitFlags(expression, 1536); + ts.setSourceMapRange(expression, ts.moveRangePastDecorators(node)); + return expression; + } + function transformDecorator(decorator) { + return ts.visitNode(decorator.expression, visitor, ts.isExpression); + } + function transformDecoratorsOfParameter(decorators, parameterOffset) { + var expressions; + if (decorators) { + expressions = []; + for (var _i = 0, decorators_1 = decorators; _i < decorators_1.length; _i++) { + var decorator = decorators_1[_i]; + var helper = createParamHelper(context, transformDecorator(decorator), parameterOffset, decorator.expression); + ts.setEmitFlags(helper, 1536); + expressions.push(helper); + } + } + return expressions; + } + function addTypeMetadata(node, container, decoratorExpressions) { + if (USE_NEW_TYPE_METADATA_FORMAT) { + addNewTypeMetadata(node, container, decoratorExpressions); + } + else { + addOldTypeMetadata(node, container, decoratorExpressions); + } + } + function addOldTypeMetadata(node, container, decoratorExpressions) { + if (compilerOptions.emitDecoratorMetadata) { + if (shouldAddTypeMetadata(node)) { + decoratorExpressions.push(createMetadataHelper(context, "design:type", serializeTypeOfNode(node))); + } + if (shouldAddParamTypesMetadata(node)) { + decoratorExpressions.push(createMetadataHelper(context, "design:paramtypes", serializeParameterTypesOfNode(node, container))); + } + if (shouldAddReturnTypeMetadata(node)) { + decoratorExpressions.push(createMetadataHelper(context, "design:returntype", serializeReturnTypeOfNode(node))); + } + } + } + function addNewTypeMetadata(node, container, decoratorExpressions) { + if (compilerOptions.emitDecoratorMetadata) { + var properties = void 0; + if (shouldAddTypeMetadata(node)) { + (properties || (properties = [])).push(ts.createPropertyAssignment("type", ts.createArrowFunction(undefined, undefined, [], undefined, ts.createToken(37), serializeTypeOfNode(node)))); + } + if (shouldAddParamTypesMetadata(node)) { + (properties || (properties = [])).push(ts.createPropertyAssignment("paramTypes", ts.createArrowFunction(undefined, undefined, [], undefined, ts.createToken(37), serializeParameterTypesOfNode(node, container)))); + } + if (shouldAddReturnTypeMetadata(node)) { + (properties || (properties = [])).push(ts.createPropertyAssignment("returnType", ts.createArrowFunction(undefined, undefined, [], undefined, ts.createToken(37), serializeReturnTypeOfNode(node)))); + } + if (properties) { + decoratorExpressions.push(createMetadataHelper(context, "design:typeinfo", ts.createObjectLiteral(properties, true))); + } + } + } + function shouldAddTypeMetadata(node) { + var kind = node.kind; + return kind === 156 + || kind === 158 + || kind === 159 + || kind === 154; + } + function shouldAddReturnTypeMetadata(node) { + return node.kind === 156; + } + function shouldAddParamTypesMetadata(node) { + switch (node.kind) { + case 240: + case 209: + return ts.getFirstConstructorWithBody(node) !== undefined; + case 156: + case 158: + case 159: + return true; + } + return false; + } + function getAccessorTypeNode(node) { + var accessors = resolver.getAllAccessorDeclarations(node); + return accessors.setAccessor && ts.getSetAccessorTypeAnnotationNode(accessors.setAccessor) + || accessors.getAccessor && ts.getEffectiveReturnTypeNode(accessors.getAccessor); + } + function serializeTypeOfNode(node) { + switch (node.kind) { + case 154: + case 151: + return serializeTypeNode(node.type); + case 159: + case 158: + return serializeTypeNode(getAccessorTypeNode(node)); + case 240: + case 209: + case 156: + return ts.createIdentifier("Function"); + default: + return ts.createVoidZero(); + } + } + function serializeParameterTypesOfNode(node, container) { + var valueDeclaration = ts.isClassLike(node) + ? ts.getFirstConstructorWithBody(node) + : ts.isFunctionLike(node) && ts.nodeIsPresent(node.body) + ? node + : undefined; + var expressions = []; + if (valueDeclaration) { + var parameters = getParametersOfDecoratedDeclaration(valueDeclaration, container); + var numParameters = parameters.length; + for (var i = 0; i < numParameters; i++) { + var parameter = parameters[i]; + if (i === 0 && ts.isIdentifier(parameter.name) && parameter.name.escapedText === "this") { + continue; + } + if (parameter.dotDotDotToken) { + expressions.push(serializeTypeNode(ts.getRestParameterElementType(parameter.type))); + } + else { + expressions.push(serializeTypeOfNode(parameter)); + } + } + } + return ts.createArrayLiteral(expressions); + } + function getParametersOfDecoratedDeclaration(node, container) { + if (container && node.kind === 158) { + var setAccessor = ts.getAllAccessorDeclarations(container.members, node).setAccessor; + if (setAccessor) { + return setAccessor.parameters; + } + } + return node.parameters; + } + function serializeReturnTypeOfNode(node) { + if (ts.isFunctionLike(node) && node.type) { + return serializeTypeNode(node.type); + } + else if (ts.isAsyncFunction(node)) { + return ts.createIdentifier("Promise"); + } + return ts.createVoidZero(); + } + function serializeTypeNode(node) { + if (node === undefined) { + return ts.createIdentifier("Object"); + } + switch (node.kind) { + case 106: + case 141: + case 96: + case 132: + return ts.createVoidZero(); + case 177: + return serializeTypeNode(node.type); + case 165: + case 166: + return ts.createIdentifier("Function"); + case 169: + case 170: + return ts.createIdentifier("Array"); + case 163: + case 123: + return ts.createIdentifier("Boolean"); + case 138: + return ts.createIdentifier("String"); + case 136: + return ts.createIdentifier("Object"); + case 182: + switch (node.literal.kind) { + case 10: + return ts.createIdentifier("String"); + case 8: + return ts.createIdentifier("Number"); + case 9: + return getGlobalBigIntNameWithFallback(); + case 102: + case 87: + return ts.createIdentifier("Boolean"); + default: + return ts.Debug.failBadSyntaxKind(node.literal); + } + case 135: + return ts.createIdentifier("Number"); + case 146: + return getGlobalBigIntNameWithFallback(); + case 139: + return languageVersion < 2 + ? getGlobalSymbolNameWithFallback() + : ts.createIdentifier("Symbol"); + case 164: + return serializeTypeReferenceNode(node); + case 174: + case 173: + return serializeTypeList(node.types); + case 175: + return serializeTypeList([node.trueType, node.falseType]); + case 167: + case 179: + case 180: + case 181: + case 168: + case 120: + case 143: + case 178: + case 183: + break; + default: + return ts.Debug.failBadSyntaxKind(node); + } + return ts.createIdentifier("Object"); + } + function serializeTypeList(types) { + var serializedUnion; + for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { + var typeNode = types_17[_i]; + while (typeNode.kind === 177) { + typeNode = typeNode.type; + } + if (typeNode.kind === 132) { + continue; + } + if (!strictNullChecks && (typeNode.kind === 96 || typeNode.kind === 141)) { + continue; + } + var serializedIndividual = serializeTypeNode(typeNode); + if (ts.isIdentifier(serializedIndividual) && serializedIndividual.escapedText === "Object") { + return serializedIndividual; + } + else if (serializedUnion) { + if (!ts.isIdentifier(serializedUnion) || + !ts.isIdentifier(serializedIndividual) || + serializedUnion.escapedText !== serializedIndividual.escapedText) { + return ts.createIdentifier("Object"); + } + } + else { + serializedUnion = serializedIndividual; + } + } + return serializedUnion || ts.createVoidZero(); + } + function serializeTypeReferenceNode(node) { + var kind = resolver.getTypeReferenceSerializationKind(node.typeName, currentNameScope || currentLexicalScope); + switch (kind) { + case ts.TypeReferenceSerializationKind.Unknown: + if (ts.findAncestor(node, function (n) { return n.parent && ts.isConditionalTypeNode(n.parent) && (n.parent.trueType === n || n.parent.falseType === n); })) { + return ts.createIdentifier("Object"); + } + var serialized = serializeEntityNameAsExpressionFallback(node.typeName); + var temp = ts.createTempVariable(hoistVariableDeclaration); + return ts.createConditional(ts.createTypeCheck(ts.createAssignment(temp, serialized), "function"), temp, ts.createIdentifier("Object")); + case ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue: + return serializeEntityNameAsExpression(node.typeName); + case ts.TypeReferenceSerializationKind.VoidNullableOrNeverType: + return ts.createVoidZero(); + case ts.TypeReferenceSerializationKind.BigIntLikeType: + return getGlobalBigIntNameWithFallback(); + case ts.TypeReferenceSerializationKind.BooleanType: + return ts.createIdentifier("Boolean"); + case ts.TypeReferenceSerializationKind.NumberLikeType: + return ts.createIdentifier("Number"); + case ts.TypeReferenceSerializationKind.StringLikeType: + return ts.createIdentifier("String"); + case ts.TypeReferenceSerializationKind.ArrayLikeType: + return ts.createIdentifier("Array"); + case ts.TypeReferenceSerializationKind.ESSymbolType: + return languageVersion < 2 + ? getGlobalSymbolNameWithFallback() + : ts.createIdentifier("Symbol"); + case ts.TypeReferenceSerializationKind.TypeWithCallSignature: + return ts.createIdentifier("Function"); + case ts.TypeReferenceSerializationKind.Promise: + return ts.createIdentifier("Promise"); + case ts.TypeReferenceSerializationKind.ObjectType: + return ts.createIdentifier("Object"); + default: + return ts.Debug.assertNever(kind); + } + } + function createCheckedValue(left, right) { + return ts.createLogicalAnd(ts.createStrictInequality(ts.createTypeOf(left), ts.createLiteral("undefined")), right); + } + function serializeEntityNameAsExpressionFallback(node) { + if (node.kind === 72) { + var copied = serializeEntityNameAsExpression(node); + return createCheckedValue(copied, copied); + } + if (node.left.kind === 72) { + return createCheckedValue(serializeEntityNameAsExpression(node.left), serializeEntityNameAsExpression(node)); + } + var left = serializeEntityNameAsExpressionFallback(node.left); + var temp = ts.createTempVariable(hoistVariableDeclaration); + return ts.createLogicalAnd(ts.createLogicalAnd(left.left, ts.createStrictInequality(ts.createAssignment(temp, left.right), ts.createVoidZero())), ts.createPropertyAccess(temp, node.right)); + } + function serializeEntityNameAsExpression(node) { + switch (node.kind) { + case 72: + var name = ts.getMutableClone(node); + name.flags &= ~8; + name.original = undefined; + name.parent = ts.getParseTreeNode(currentLexicalScope); + return name; + case 148: + return serializeQualifiedNameAsExpression(node); + } + } + function serializeQualifiedNameAsExpression(node) { + return ts.createPropertyAccess(serializeEntityNameAsExpression(node.left), node.right); + } + function getGlobalSymbolNameWithFallback() { + return ts.createConditional(ts.createTypeCheck(ts.createIdentifier("Symbol"), "function"), ts.createIdentifier("Symbol"), ts.createIdentifier("Object")); + } + function getGlobalBigIntNameWithFallback() { + return languageVersion < 6 + ? ts.createConditional(ts.createTypeCheck(ts.createIdentifier("BigInt"), "function"), ts.createIdentifier("BigInt"), ts.createIdentifier("Object")) + : ts.createIdentifier("BigInt"); + } + function isSimpleInlineableExpression(expression) { + return !ts.isIdentifier(expression) && ts.isSimpleCopiableExpression(expression) || + ts.isWellKnownSymbolSyntactically(expression); + } + function getExpressionForPropertyName(member, generateNameForComputedPropertyName) { + var name = member.name; + if (ts.isComputedPropertyName(name)) { + return generateNameForComputedPropertyName && !isSimpleInlineableExpression(name.expression) + ? ts.getGeneratedNameForNode(name) + : name.expression; + } + else if (ts.isIdentifier(name)) { + return ts.createLiteral(ts.idText(name)); + } + else { + return ts.getSynthesizedClone(name); + } + } + function getPropertyNameExpressionIfNeeded(name, shouldHoist, omitSimple) { + if (ts.isComputedPropertyName(name)) { + var expression = ts.visitNode(name.expression, visitor, ts.isExpression); + var innerExpression = ts.skipPartiallyEmittedExpressions(expression); + var inlinable = isSimpleInlineableExpression(innerExpression); + if (!inlinable && shouldHoist) { + var generatedName = ts.getGeneratedNameForNode(name); + hoistVariableDeclaration(generatedName); + return ts.createAssignment(generatedName, expression); + } + return (omitSimple && (inlinable || ts.isIdentifier(innerExpression))) ? undefined : expression; + } + } + function visitPropertyNameOfClassElement(member) { + var name = member.name; + var expr = getPropertyNameExpressionIfNeeded(name, ts.some(member.decorators), false); + if (expr) { + if (ts.some(pendingExpressions)) { + expr = ts.inlineExpressions(pendingExpressions.concat([expr])); + pendingExpressions.length = 0; + } + return ts.updateComputedPropertyName(name, expr); + } + else { + return name; + } + } + function visitHeritageClause(node) { + if (node.token === 86) { + var types = ts.visitNodes(node.types, visitor, ts.isExpressionWithTypeArguments, 0, 1); + return ts.setTextRange(ts.createHeritageClause(86, types), node); + } + return undefined; + } + function visitExpressionWithTypeArguments(node) { + return ts.updateExpressionWithTypeArguments(node, undefined, ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression)); + } + function shouldEmitFunctionLikeDeclaration(node) { + return !ts.nodeIsMissing(node.body); + } + function visitPropertyDeclaration(node) { + var expr = getPropertyNameExpressionIfNeeded(node.name, ts.some(node.decorators) || !!node.initializer, true); + if (expr && !isSimpleInlineableExpression(expr)) { + (pendingExpressions || (pendingExpressions = [])).push(expr); + } + return undefined; + } + function visitConstructor(node) { + if (!shouldEmitFunctionLikeDeclaration(node)) { + return undefined; + } + return ts.updateConstructor(node, ts.visitNodes(node.decorators, visitor, ts.isDecorator), ts.visitNodes(node.modifiers, visitor, ts.isModifier), ts.visitParameterList(node.parameters, visitor, context), ts.visitFunctionBody(node.body, visitor, context)); + } + function visitMethodDeclaration(node) { + if (!shouldEmitFunctionLikeDeclaration(node)) { + return undefined; + } + var updated = ts.updateMethod(node, undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, visitPropertyNameOfClassElement(node), undefined, undefined, ts.visitParameterList(node.parameters, visitor, context), undefined, ts.visitFunctionBody(node.body, visitor, context)); + if (updated !== node) { + ts.setCommentRange(updated, node); + ts.setSourceMapRange(updated, ts.moveRangePastDecorators(node)); + } + return updated; + } + function shouldEmitAccessorDeclaration(node) { + return !(ts.nodeIsMissing(node.body) && ts.hasModifier(node, 128)); + } + function visitGetAccessor(node) { + if (!shouldEmitAccessorDeclaration(node)) { + return undefined; + } + var updated = ts.updateGetAccessor(node, undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), visitPropertyNameOfClassElement(node), ts.visitParameterList(node.parameters, visitor, context), undefined, ts.visitFunctionBody(node.body, visitor, context) || ts.createBlock([])); + if (updated !== node) { + ts.setCommentRange(updated, node); + ts.setSourceMapRange(updated, ts.moveRangePastDecorators(node)); + } + return updated; + } + function visitSetAccessor(node) { + if (!shouldEmitAccessorDeclaration(node)) { + return undefined; + } + var updated = ts.updateSetAccessor(node, undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), visitPropertyNameOfClassElement(node), ts.visitParameterList(node.parameters, visitor, context), ts.visitFunctionBody(node.body, visitor, context) || ts.createBlock([])); + if (updated !== node) { + ts.setCommentRange(updated, node); + ts.setSourceMapRange(updated, ts.moveRangePastDecorators(node)); + } + return updated; + } + function visitFunctionDeclaration(node) { + if (!shouldEmitFunctionLikeDeclaration(node)) { + return ts.createNotEmittedStatement(node); + } + var updated = ts.updateFunctionDeclaration(node, undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, node.name, undefined, ts.visitParameterList(node.parameters, visitor, context), undefined, ts.visitFunctionBody(node.body, visitor, context) || ts.createBlock([])); + if (isExportOfNamespace(node)) { + var statements = [updated]; + addExportMemberAssignment(statements, node); + return statements; + } + return updated; + } + function visitFunctionExpression(node) { + if (!shouldEmitFunctionLikeDeclaration(node)) { + return ts.createOmittedExpression(); + } + var updated = ts.updateFunctionExpression(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, node.name, undefined, ts.visitParameterList(node.parameters, visitor, context), undefined, ts.visitFunctionBody(node.body, visitor, context) || ts.createBlock([])); + return updated; + } + function visitArrowFunction(node) { + var updated = ts.updateArrowFunction(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), undefined, ts.visitParameterList(node.parameters, visitor, context), undefined, node.equalsGreaterThanToken, ts.visitFunctionBody(node.body, visitor, context)); + return updated; + } + function visitParameter(node) { + if (ts.parameterIsThisKeyword(node)) { + return undefined; + } + var parameter = ts.createParameter(undefined, undefined, node.dotDotDotToken, ts.visitNode(node.name, visitor, ts.isBindingName), undefined, undefined, ts.visitNode(node.initializer, visitor, ts.isExpression)); + ts.setOriginalNode(parameter, node); + ts.setTextRange(parameter, ts.moveRangePastModifiers(node)); + ts.setCommentRange(parameter, node); + ts.setSourceMapRange(parameter, ts.moveRangePastModifiers(node)); + ts.setEmitFlags(parameter.name, 32); + return parameter; + } + function visitVariableStatement(node) { + if (isExportOfNamespace(node)) { + var variables = ts.getInitializedVariables(node.declarationList); + if (variables.length === 0) { + return undefined; + } + return ts.setTextRange(ts.createExpressionStatement(ts.inlineExpressions(ts.map(variables, transformInitializedVariable))), node); + } + else { + return ts.visitEachChild(node, visitor, context); + } + } + function transformInitializedVariable(node) { + var name = node.name; + if (ts.isBindingPattern(name)) { + return ts.flattenDestructuringAssignment(node, visitor, context, 0, false, createNamespaceExportExpression); + } + else { + return ts.setTextRange(ts.createAssignment(getNamespaceMemberNameWithSourceMapsAndWithoutComments(name), ts.visitNode(node.initializer, visitor, ts.isExpression)), node); + } + } + function visitVariableDeclaration(node) { + return ts.updateVariableDeclaration(node, ts.visitNode(node.name, visitor, ts.isBindingName), undefined, ts.visitNode(node.initializer, visitor, ts.isExpression)); + } + function visitParenthesizedExpression(node) { + var innerExpression = ts.skipOuterExpressions(node.expression, ~2); + if (ts.isAssertionExpression(innerExpression)) { + var expression = ts.visitNode(node.expression, visitor, ts.isExpression); + if (ts.length(ts.getLeadingCommentRangesOfNode(expression, currentSourceFile))) { + return ts.updateParen(node, expression); + } + return ts.createPartiallyEmittedExpression(expression, node); + } + return ts.visitEachChild(node, visitor, context); + } + function visitAssertionExpression(node) { + var expression = ts.visitNode(node.expression, visitor, ts.isExpression); + return ts.createPartiallyEmittedExpression(expression, node); + } + function visitNonNullExpression(node) { + var expression = ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression); + return ts.createPartiallyEmittedExpression(expression, node); + } + function visitCallExpression(node) { + return ts.updateCall(node, ts.visitNode(node.expression, visitor, ts.isExpression), undefined, ts.visitNodes(node.arguments, visitor, ts.isExpression)); + } + function visitNewExpression(node) { + return ts.updateNew(node, ts.visitNode(node.expression, visitor, ts.isExpression), undefined, ts.visitNodes(node.arguments, visitor, ts.isExpression)); + } + function visitTaggedTemplateExpression(node) { + return ts.updateTaggedTemplate(node, ts.visitNode(node.tag, visitor, ts.isExpression), undefined, ts.visitNode(node.template, visitor, ts.isExpression)); + } + function shouldEmitEnumDeclaration(node) { + return !ts.isEnumConst(node) + || compilerOptions.preserveConstEnums + || compilerOptions.isolatedModules; + } + function visitEnumDeclaration(node) { + if (!shouldEmitEnumDeclaration(node)) { + return undefined; + } + var statements = []; + var emitFlags = 2; + var varAdded = addVarForEnumOrModuleDeclaration(statements, node); + if (varAdded) { + if (moduleKind !== ts.ModuleKind.System || currentLexicalScope !== currentSourceFile) { + emitFlags |= 512; + } + } + var parameterName = getNamespaceParameterName(node); + var containerName = getNamespaceContainerName(node); + var exportName = ts.hasModifier(node, 1) + ? ts.getExternalModuleOrNamespaceExportName(currentNamespaceContainerName, node, false, true) + : ts.getLocalName(node, false, true); + var moduleArg = ts.createLogicalOr(exportName, ts.createAssignment(exportName, ts.createObjectLiteral())); + if (hasNamespaceQualifiedExportName(node)) { + var localName = ts.getLocalName(node, false, true); + moduleArg = ts.createAssignment(localName, moduleArg); + } + var enumStatement = ts.createExpressionStatement(ts.createCall(ts.createFunctionExpression(undefined, undefined, undefined, undefined, [ts.createParameter(undefined, undefined, undefined, parameterName)], undefined, transformEnumBody(node, containerName)), undefined, [moduleArg])); + ts.setOriginalNode(enumStatement, node); + if (varAdded) { + ts.setSyntheticLeadingComments(enumStatement, undefined); + ts.setSyntheticTrailingComments(enumStatement, undefined); + } + ts.setTextRange(enumStatement, node); + ts.addEmitFlags(enumStatement, emitFlags); + statements.push(enumStatement); + statements.push(ts.createEndOfDeclarationMarker(node)); + return statements; + } + function transformEnumBody(node, localName) { + var savedCurrentNamespaceLocalName = currentNamespaceContainerName; + currentNamespaceContainerName = localName; + var statements = []; + startLexicalEnvironment(); + var members = ts.map(node.members, transformEnumMember); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + ts.addRange(statements, members); + currentNamespaceContainerName = savedCurrentNamespaceLocalName; + return ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), node.members), true); + } + function transformEnumMember(member) { + var name = getExpressionForPropertyName(member, false); + var valueExpression = transformEnumMemberDeclarationValue(member); + var innerAssignment = ts.createAssignment(ts.createElementAccess(currentNamespaceContainerName, name), valueExpression); + var outerAssignment = valueExpression.kind === 10 ? + innerAssignment : + ts.createAssignment(ts.createElementAccess(currentNamespaceContainerName, innerAssignment), name); + return ts.setTextRange(ts.createExpressionStatement(ts.setTextRange(outerAssignment, member)), member); + } + function transformEnumMemberDeclarationValue(member) { + var value = resolver.getConstantValue(member); + if (value !== undefined) { + return ts.createLiteral(value); + } + else { + enableSubstitutionForNonQualifiedEnumMembers(); + if (member.initializer) { + return ts.visitNode(member.initializer, visitor, ts.isExpression); + } + else { + return ts.createVoidZero(); + } + } + } + function shouldEmitModuleDeclaration(node) { + return ts.isInstantiatedModule(node, !!compilerOptions.preserveConstEnums || !!compilerOptions.isolatedModules); + } + function hasNamespaceQualifiedExportName(node) { + return isExportOfNamespace(node) + || (isExternalModuleExport(node) + && moduleKind !== ts.ModuleKind.ES2015 + && moduleKind !== ts.ModuleKind.ESNext + && moduleKind !== ts.ModuleKind.System); + } + function recordEmittedDeclarationInScope(node) { + if (!currentScopeFirstDeclarationsOfName) { + currentScopeFirstDeclarationsOfName = ts.createUnderscoreEscapedMap(); + } + var name = declaredNameInScope(node); + if (!currentScopeFirstDeclarationsOfName.has(name)) { + currentScopeFirstDeclarationsOfName.set(name, node); + } + } + function isFirstEmittedDeclarationInScope(node) { + if (currentScopeFirstDeclarationsOfName) { + var name = declaredNameInScope(node); + return currentScopeFirstDeclarationsOfName.get(name) === node; + } + return true; + } + function declaredNameInScope(node) { + ts.Debug.assertNode(node.name, ts.isIdentifier); + return node.name.escapedText; + } + function addVarForEnumOrModuleDeclaration(statements, node) { + var statement = ts.createVariableStatement(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.createVariableDeclarationList([ + ts.createVariableDeclaration(ts.getLocalName(node, false, true)) + ], currentLexicalScope.kind === 279 ? 0 : 1)); + ts.setOriginalNode(statement, node); + recordEmittedDeclarationInScope(node); + if (isFirstEmittedDeclarationInScope(node)) { + if (node.kind === 243) { + ts.setSourceMapRange(statement.declarationList, node); + } + else { + ts.setSourceMapRange(statement, node); + } + ts.setCommentRange(statement, node); + ts.addEmitFlags(statement, 1024 | 4194304); + statements.push(statement); + return true; + } + else { + var mergeMarker = ts.createMergeDeclarationMarker(statement); + ts.setEmitFlags(mergeMarker, 1536 | 4194304); + statements.push(mergeMarker); + return false; + } + } + function visitModuleDeclaration(node) { + if (!shouldEmitModuleDeclaration(node)) { + return ts.createNotEmittedStatement(node); + } + ts.Debug.assertNode(node.name, ts.isIdentifier, "A TypeScript namespace should have an Identifier name."); + enableSubstitutionForNamespaceExports(); + var statements = []; + var emitFlags = 2; + var varAdded = addVarForEnumOrModuleDeclaration(statements, node); + if (varAdded) { + if (moduleKind !== ts.ModuleKind.System || currentLexicalScope !== currentSourceFile) { + emitFlags |= 512; + } + } + var parameterName = getNamespaceParameterName(node); + var containerName = getNamespaceContainerName(node); + var exportName = ts.hasModifier(node, 1) + ? ts.getExternalModuleOrNamespaceExportName(currentNamespaceContainerName, node, false, true) + : ts.getLocalName(node, false, true); + var moduleArg = ts.createLogicalOr(exportName, ts.createAssignment(exportName, ts.createObjectLiteral())); + if (hasNamespaceQualifiedExportName(node)) { + var localName = ts.getLocalName(node, false, true); + moduleArg = ts.createAssignment(localName, moduleArg); + } + var moduleStatement = ts.createExpressionStatement(ts.createCall(ts.createFunctionExpression(undefined, undefined, undefined, undefined, [ts.createParameter(undefined, undefined, undefined, parameterName)], undefined, transformModuleBody(node, containerName)), undefined, [moduleArg])); + ts.setOriginalNode(moduleStatement, node); + if (varAdded) { + ts.setSyntheticLeadingComments(moduleStatement, undefined); + ts.setSyntheticTrailingComments(moduleStatement, undefined); + } + ts.setTextRange(moduleStatement, node); + ts.addEmitFlags(moduleStatement, emitFlags); + statements.push(moduleStatement); + statements.push(ts.createEndOfDeclarationMarker(node)); + return statements; + } + function transformModuleBody(node, namespaceLocalName) { + var savedCurrentNamespaceContainerName = currentNamespaceContainerName; + var savedCurrentNamespace = currentNamespace; + var savedCurrentScopeFirstDeclarationsOfName = currentScopeFirstDeclarationsOfName; + currentNamespaceContainerName = namespaceLocalName; + currentNamespace = node; + currentScopeFirstDeclarationsOfName = undefined; + var statements = []; + startLexicalEnvironment(); + var statementsLocation; + var blockLocation; + var body = node.body; + if (body.kind === 245) { + saveStateAndInvoke(body, function (body) { return ts.addRange(statements, ts.visitNodes(body.statements, namespaceElementVisitor, ts.isStatement)); }); + statementsLocation = body.statements; + blockLocation = body; + } + else { + var result = visitModuleDeclaration(body); + if (result) { + if (ts.isArray(result)) { + ts.addRange(statements, result); + } + else { + statements.push(result); + } + } + var moduleBlock = getInnerMostModuleDeclarationFromDottedModule(node).body; + statementsLocation = ts.moveRangePos(moduleBlock.statements, -1); + } + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + currentNamespaceContainerName = savedCurrentNamespaceContainerName; + currentNamespace = savedCurrentNamespace; + currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName; + var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), statementsLocation), true); + ts.setTextRange(block, blockLocation); + if (body.kind !== 245) { + ts.setEmitFlags(block, ts.getEmitFlags(block) | 1536); + } + return block; + } + function getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration) { + if (moduleDeclaration.body.kind === 244) { + var recursiveInnerModule = getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration.body); + return recursiveInnerModule || moduleDeclaration.body; + } + } + function visitImportDeclaration(node) { + if (!node.importClause) { + return node; + } + var importClause = ts.visitNode(node.importClause, visitImportClause, ts.isImportClause); + return importClause + ? ts.updateImportDeclaration(node, undefined, undefined, importClause, node.moduleSpecifier) + : undefined; + } + function visitImportClause(node) { + var name = resolver.isReferencedAliasDeclaration(node) ? node.name : undefined; + var namedBindings = ts.visitNode(node.namedBindings, visitNamedImportBindings, ts.isNamedImportBindings); + return (name || namedBindings) ? ts.updateImportClause(node, name, namedBindings) : undefined; + } + function visitNamedImportBindings(node) { + if (node.kind === 251) { + return resolver.isReferencedAliasDeclaration(node) ? node : undefined; + } + else { + var elements = ts.visitNodes(node.elements, visitImportSpecifier, ts.isImportSpecifier); + return ts.some(elements) ? ts.updateNamedImports(node, elements) : undefined; + } + } + function visitImportSpecifier(node) { + return resolver.isReferencedAliasDeclaration(node) ? node : undefined; + } + function visitExportAssignment(node) { + return resolver.isValueAliasDeclaration(node) + ? ts.visitEachChild(node, visitor, context) + : undefined; + } + function visitExportDeclaration(node) { + if (!node.exportClause) { + return compilerOptions.isolatedModules || resolver.moduleExportsSomeValue(node.moduleSpecifier) ? node : undefined; + } + if (!resolver.isValueAliasDeclaration(node)) { + return undefined; + } + var exportClause = ts.visitNode(node.exportClause, visitNamedExports, ts.isNamedExports); + return exportClause + ? ts.updateExportDeclaration(node, undefined, undefined, exportClause, node.moduleSpecifier) + : undefined; + } + function visitNamedExports(node) { + var elements = ts.visitNodes(node.elements, visitExportSpecifier, ts.isExportSpecifier); + return ts.some(elements) ? ts.updateNamedExports(node, elements) : undefined; + } + function visitExportSpecifier(node) { + return resolver.isValueAliasDeclaration(node) ? node : undefined; + } + function shouldEmitImportEqualsDeclaration(node) { + return resolver.isReferencedAliasDeclaration(node) + || (!ts.isExternalModule(currentSourceFile) + && resolver.isTopLevelValueImportEqualsWithEntityName(node)); + } + function visitImportEqualsDeclaration(node) { + if (ts.isExternalModuleImportEqualsDeclaration(node)) { + return resolver.isReferencedAliasDeclaration(node) + ? ts.visitEachChild(node, visitor, context) + : undefined; + } + if (!shouldEmitImportEqualsDeclaration(node)) { + return undefined; + } + var moduleReference = ts.createExpressionFromEntityName(node.moduleReference); + ts.setEmitFlags(moduleReference, 1536 | 2048); + if (isNamedExternalModuleExport(node) || !isExportOfNamespace(node)) { + return ts.setOriginalNode(ts.setTextRange(ts.createVariableStatement(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.createVariableDeclarationList([ + ts.setOriginalNode(ts.createVariableDeclaration(node.name, undefined, moduleReference), node) + ])), node), node); + } + else { + return ts.setOriginalNode(createNamespaceExport(node.name, moduleReference, node), node); + } + } + function isExportOfNamespace(node) { + return currentNamespace !== undefined && ts.hasModifier(node, 1); + } + function isExternalModuleExport(node) { + return currentNamespace === undefined && ts.hasModifier(node, 1); + } + function isNamedExternalModuleExport(node) { + return isExternalModuleExport(node) + && !ts.hasModifier(node, 512); + } + function isDefaultExternalModuleExport(node) { + return isExternalModuleExport(node) + && ts.hasModifier(node, 512); + } + function expressionToStatement(expression) { + return ts.createExpressionStatement(expression); + } + function addExportMemberAssignment(statements, node) { + var expression = ts.createAssignment(ts.getExternalModuleOrNamespaceExportName(currentNamespaceContainerName, node, false, true), ts.getLocalName(node)); + ts.setSourceMapRange(expression, ts.createRange(node.name ? node.name.pos : node.pos, node.end)); + var statement = ts.createExpressionStatement(expression); + ts.setSourceMapRange(statement, ts.createRange(-1, node.end)); + statements.push(statement); + } + function createNamespaceExport(exportName, exportValue, location) { + return ts.setTextRange(ts.createExpressionStatement(ts.createAssignment(ts.getNamespaceMemberName(currentNamespaceContainerName, exportName, false, true), exportValue)), location); + } + function createNamespaceExportExpression(exportName, exportValue, location) { + return ts.setTextRange(ts.createAssignment(getNamespaceMemberNameWithSourceMapsAndWithoutComments(exportName), exportValue), location); + } + function getNamespaceMemberNameWithSourceMapsAndWithoutComments(name) { + return ts.getNamespaceMemberName(currentNamespaceContainerName, name, false, true); + } + function getNamespaceParameterName(node) { + var name = ts.getGeneratedNameForNode(node); + ts.setSourceMapRange(name, node.name); + return name; + } + function getNamespaceContainerName(node) { + return ts.getGeneratedNameForNode(node); + } + function getClassAliasIfNeeded(node) { + if (resolver.getNodeCheckFlags(node) & 16777216) { + enableSubstitutionForClassAliases(); + var classAlias = ts.createUniqueName(node.name && !ts.isGeneratedIdentifier(node.name) ? ts.idText(node.name) : "default"); + classAliases[ts.getOriginalNodeId(node)] = classAlias; + hoistVariableDeclaration(classAlias); + return classAlias; + } + } + function getClassPrototype(node) { + return ts.createPropertyAccess(ts.getDeclarationName(node), "prototype"); + } + function getClassMemberPrefix(node, member) { + return ts.hasModifier(member, 32) + ? ts.getDeclarationName(node) + : getClassPrototype(node); + } + function enableSubstitutionForNonQualifiedEnumMembers() { + if ((enabledSubstitutions & 8) === 0) { + enabledSubstitutions |= 8; + context.enableSubstitution(72); + } + } + function enableSubstitutionForClassAliases() { + if ((enabledSubstitutions & 1) === 0) { + enabledSubstitutions |= 1; + context.enableSubstitution(72); + classAliases = []; + } + } + function enableSubstitutionForNamespaceExports() { + if ((enabledSubstitutions & 2) === 0) { + enabledSubstitutions |= 2; + context.enableSubstitution(72); + context.enableSubstitution(276); + context.enableEmitNotification(244); + } + } + function isTransformedModuleDeclaration(node) { + return ts.getOriginalNode(node).kind === 244; + } + function isTransformedEnumDeclaration(node) { + return ts.getOriginalNode(node).kind === 243; + } + function onEmitNode(hint, node, emitCallback) { + var savedApplicableSubstitutions = applicableSubstitutions; + var savedCurrentSourceFile = currentSourceFile; + if (ts.isSourceFile(node)) { + currentSourceFile = node; + } + if (enabledSubstitutions & 2 && isTransformedModuleDeclaration(node)) { + applicableSubstitutions |= 2; + } + if (enabledSubstitutions & 8 && isTransformedEnumDeclaration(node)) { + applicableSubstitutions |= 8; + } + previousOnEmitNode(hint, node, emitCallback); + applicableSubstitutions = savedApplicableSubstitutions; + currentSourceFile = savedCurrentSourceFile; + } + function onSubstituteNode(hint, node) { + node = previousOnSubstituteNode(hint, node); + if (hint === 1) { + return substituteExpression(node); + } + else if (ts.isShorthandPropertyAssignment(node)) { + return substituteShorthandPropertyAssignment(node); + } + return node; + } + function substituteShorthandPropertyAssignment(node) { + if (enabledSubstitutions & 2) { + var name = node.name; + var exportedName = trySubstituteNamespaceExportedName(name); + if (exportedName) { + if (node.objectAssignmentInitializer) { + var initializer = ts.createAssignment(exportedName, node.objectAssignmentInitializer); + return ts.setTextRange(ts.createPropertyAssignment(name, initializer), node); + } + return ts.setTextRange(ts.createPropertyAssignment(name, exportedName), node); + } + } + return node; + } + function substituteExpression(node) { + switch (node.kind) { + case 72: + return substituteExpressionIdentifier(node); + case 189: + return substitutePropertyAccessExpression(node); + case 190: + return substituteElementAccessExpression(node); + } + return node; + } + function substituteExpressionIdentifier(node) { + return trySubstituteClassAlias(node) + || trySubstituteNamespaceExportedName(node) + || node; + } + function trySubstituteClassAlias(node) { + if (enabledSubstitutions & 1) { + if (resolver.getNodeCheckFlags(node) & 33554432) { + var declaration = resolver.getReferencedValueDeclaration(node); + if (declaration) { + var classAlias = classAliases[declaration.id]; + if (classAlias) { + var clone_1 = ts.getSynthesizedClone(classAlias); + ts.setSourceMapRange(clone_1, node); + ts.setCommentRange(clone_1, node); + return clone_1; + } + } + } + } + return undefined; + } + function trySubstituteNamespaceExportedName(node) { + if (enabledSubstitutions & applicableSubstitutions && !ts.isGeneratedIdentifier(node) && !ts.isLocalName(node)) { + var container = resolver.getReferencedExportContainer(node, false); + if (container && container.kind !== 279) { + var substitute = (applicableSubstitutions & 2 && container.kind === 244) || + (applicableSubstitutions & 8 && container.kind === 243); + if (substitute) { + return ts.setTextRange(ts.createPropertyAccess(ts.getGeneratedNameForNode(container), node), node); + } + } + } + return undefined; + } + function substitutePropertyAccessExpression(node) { + return substituteConstantValue(node); + } + function substituteElementAccessExpression(node) { + return substituteConstantValue(node); + } + function substituteConstantValue(node) { + var constantValue = tryGetConstEnumValue(node); + if (constantValue !== undefined) { + ts.setConstantValue(node, constantValue); + var substitute = ts.createLiteral(constantValue); + if (!compilerOptions.removeComments) { + var propertyName = ts.isPropertyAccessExpression(node) + ? ts.declarationNameToString(node.name) + : ts.getTextOfNode(node.argumentExpression); + ts.addSyntheticTrailingComment(substitute, 3, " " + propertyName + " "); + } + return substitute; + } + return node; + } + function tryGetConstEnumValue(node) { + if (compilerOptions.isolatedModules) { + return undefined; + } + return ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node) ? resolver.getConstantValue(node) : undefined; + } + } + ts.transformTypeScript = transformTypeScript; + function createDecorateHelper(context, decoratorExpressions, target, memberName, descriptor, location) { + var argumentsArray = []; + argumentsArray.push(ts.createArrayLiteral(decoratorExpressions, true)); + argumentsArray.push(target); + if (memberName) { + argumentsArray.push(memberName); + if (descriptor) { + argumentsArray.push(descriptor); + } + } + context.requestEmitHelper(decorateHelper); + return ts.setTextRange(ts.createCall(ts.getHelperName("__decorate"), undefined, argumentsArray), location); + } + var decorateHelper = { + name: "typescript:decorate", + scoped: false, + priority: 2, + text: "\n var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n };" + }; + function createMetadataHelper(context, metadataKey, metadataValue) { + context.requestEmitHelper(metadataHelper); + return ts.createCall(ts.getHelperName("__metadata"), undefined, [ + ts.createLiteral(metadataKey), + metadataValue + ]); + } + var metadataHelper = { + name: "typescript:metadata", + scoped: false, + priority: 3, + text: "\n var __metadata = (this && this.__metadata) || function (k, v) {\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(k, v);\n };" + }; + function createParamHelper(context, expression, parameterOffset, location) { + context.requestEmitHelper(paramHelper); + return ts.setTextRange(ts.createCall(ts.getHelperName("__param"), undefined, [ + ts.createLiteral(parameterOffset), + expression + ]), location); + } + var paramHelper = { + name: "typescript:param", + scoped: false, + priority: 4, + text: "\n var __param = (this && this.__param) || function (paramIndex, decorator) {\n return function (target, key) { decorator(target, key, paramIndex); }\n };" + }; +})(ts || (ts = {})); +var ts; +(function (ts) { + function transformES2017(context) { + var resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; + var resolver = context.getEmitResolver(); + var compilerOptions = context.getCompilerOptions(); + var languageVersion = ts.getEmitScriptTarget(compilerOptions); + var enabledSubstitutions; + var enclosingSuperContainerFlags = 0; + var enclosingFunctionParameterNames; + var capturedSuperProperties; + var hasSuperElementAccess; + var substitutedSuperAccessors = []; + var previousOnEmitNode = context.onEmitNode; + var previousOnSubstituteNode = context.onSubstituteNode; + context.onEmitNode = onEmitNode; + context.onSubstituteNode = onSubstituteNode; + return ts.chainBundle(transformSourceFile); + function transformSourceFile(node) { + if (node.isDeclarationFile) { + return node; + } + var visited = ts.visitEachChild(node, visitor, context); + ts.addEmitHelpers(visited, context.readEmitHelpers()); + return visited; + } + function visitor(node) { + if ((node.transformFlags & 16) === 0) { + return node; + } + switch (node.kind) { + case 121: + return undefined; + case 201: + return visitAwaitExpression(node); + case 156: + return visitMethodDeclaration(node); + case 239: + return visitFunctionDeclaration(node); + case 196: + return visitFunctionExpression(node); + case 197: + return visitArrowFunction(node); + case 189: + if (capturedSuperProperties && ts.isPropertyAccessExpression(node) && node.expression.kind === 98) { + capturedSuperProperties.set(node.name.escapedText, true); + } + return ts.visitEachChild(node, visitor, context); + case 190: + if (capturedSuperProperties && node.expression.kind === 98) { + hasSuperElementAccess = true; + } + return ts.visitEachChild(node, visitor, context); + default: + return ts.visitEachChild(node, visitor, context); + } + } + function asyncBodyVisitor(node) { + if (ts.isNodeWithPossibleHoistedDeclaration(node)) { + switch (node.kind) { + case 219: + return visitVariableStatementInAsyncBody(node); + case 225: + return visitForStatementInAsyncBody(node); + case 226: + return visitForInStatementInAsyncBody(node); + case 227: + return visitForOfStatementInAsyncBody(node); + case 274: + return visitCatchClauseInAsyncBody(node); + case 218: + case 232: + case 246: + case 271: + case 272: + case 235: + case 223: + case 224: + case 222: + case 231: + case 233: + return ts.visitEachChild(node, asyncBodyVisitor, context); + default: + return ts.Debug.assertNever(node, "Unhandled node."); + } + } + return visitor(node); + } + function visitCatchClauseInAsyncBody(node) { + var catchClauseNames = ts.createUnderscoreEscapedMap(); + recordDeclarationName(node.variableDeclaration, catchClauseNames); + var catchClauseUnshadowedNames; + catchClauseNames.forEach(function (_, escapedName) { + if (enclosingFunctionParameterNames.has(escapedName)) { + if (!catchClauseUnshadowedNames) { + catchClauseUnshadowedNames = ts.cloneMap(enclosingFunctionParameterNames); + } + catchClauseUnshadowedNames.delete(escapedName); + } + }); + if (catchClauseUnshadowedNames) { + var savedEnclosingFunctionParameterNames = enclosingFunctionParameterNames; + enclosingFunctionParameterNames = catchClauseUnshadowedNames; + var result = ts.visitEachChild(node, asyncBodyVisitor, context); + enclosingFunctionParameterNames = savedEnclosingFunctionParameterNames; + return result; + } + else { + return ts.visitEachChild(node, asyncBodyVisitor, context); + } + } + function visitVariableStatementInAsyncBody(node) { + if (isVariableDeclarationListWithCollidingName(node.declarationList)) { + var expression = visitVariableDeclarationListWithCollidingNames(node.declarationList, false); + return expression ? ts.createExpressionStatement(expression) : undefined; + } + return ts.visitEachChild(node, visitor, context); + } + function visitForInStatementInAsyncBody(node) { + return ts.updateForIn(node, isVariableDeclarationListWithCollidingName(node.initializer) + ? visitVariableDeclarationListWithCollidingNames(node.initializer, true) + : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitNode(node.statement, asyncBodyVisitor, ts.isStatement, ts.liftToBlock)); + } + function visitForOfStatementInAsyncBody(node) { + return ts.updateForOf(node, ts.visitNode(node.awaitModifier, visitor, ts.isToken), isVariableDeclarationListWithCollidingName(node.initializer) + ? visitVariableDeclarationListWithCollidingNames(node.initializer, true) + : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitNode(node.statement, asyncBodyVisitor, ts.isStatement, ts.liftToBlock)); + } + function visitForStatementInAsyncBody(node) { + var initializer = node.initializer; + return ts.updateFor(node, isVariableDeclarationListWithCollidingName(initializer) + ? visitVariableDeclarationListWithCollidingNames(initializer, false) + : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.condition, visitor, ts.isExpression), ts.visitNode(node.incrementor, visitor, ts.isExpression), ts.visitNode(node.statement, asyncBodyVisitor, ts.isStatement, ts.liftToBlock)); + } + function visitAwaitExpression(node) { + return ts.setOriginalNode(ts.setTextRange(ts.createYield(undefined, ts.visitNode(node.expression, visitor, ts.isExpression)), node), node); + } + function visitMethodDeclaration(node) { + return ts.updateMethod(node, undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, node.name, undefined, undefined, ts.visitParameterList(node.parameters, visitor, context), undefined, ts.getFunctionFlags(node) & 2 + ? transformAsyncFunctionBody(node) + : ts.visitFunctionBody(node.body, visitor, context)); + } + function visitFunctionDeclaration(node) { + return ts.updateFunctionDeclaration(node, undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, node.name, undefined, ts.visitParameterList(node.parameters, visitor, context), undefined, ts.getFunctionFlags(node) & 2 + ? transformAsyncFunctionBody(node) + : ts.visitFunctionBody(node.body, visitor, context)); + } + function visitFunctionExpression(node) { + return ts.updateFunctionExpression(node, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, node.name, undefined, ts.visitParameterList(node.parameters, visitor, context), undefined, ts.getFunctionFlags(node) & 2 + ? transformAsyncFunctionBody(node) + : ts.visitFunctionBody(node.body, visitor, context)); + } + function visitArrowFunction(node) { + return ts.updateArrowFunction(node, ts.visitNodes(node.modifiers, visitor, ts.isModifier), undefined, ts.visitParameterList(node.parameters, visitor, context), undefined, node.equalsGreaterThanToken, ts.getFunctionFlags(node) & 2 + ? transformAsyncFunctionBody(node) + : ts.visitFunctionBody(node.body, visitor, context)); + } + function recordDeclarationName(_a, names) { + var name = _a.name; + if (ts.isIdentifier(name)) { + names.set(name.escapedText, true); + } + else { + for (var _i = 0, _b = name.elements; _i < _b.length; _i++) { + var element = _b[_i]; + if (!ts.isOmittedExpression(element)) { + recordDeclarationName(element, names); + } + } + } + } + function isVariableDeclarationListWithCollidingName(node) { + return !!node + && ts.isVariableDeclarationList(node) + && !(node.flags & 3) + && node.declarations.some(collidesWithParameterName); + } + function visitVariableDeclarationListWithCollidingNames(node, hasReceiver) { + hoistVariableDeclarationList(node); + var variables = ts.getInitializedVariables(node); + if (variables.length === 0) { + if (hasReceiver) { + return ts.visitNode(ts.convertToAssignmentElementTarget(node.declarations[0].name), visitor, ts.isExpression); + } + return undefined; + } + return ts.inlineExpressions(ts.map(variables, transformInitializedVariable)); + } + function hoistVariableDeclarationList(node) { + ts.forEach(node.declarations, hoistVariable); + } + function hoistVariable(_a) { + var name = _a.name; + if (ts.isIdentifier(name)) { + hoistVariableDeclaration(name); + } + else { + for (var _i = 0, _b = name.elements; _i < _b.length; _i++) { + var element = _b[_i]; + if (!ts.isOmittedExpression(element)) { + hoistVariable(element); + } + } + } + } + function transformInitializedVariable(node) { + var converted = ts.setSourceMapRange(ts.createAssignment(ts.convertToAssignmentElementTarget(node.name), node.initializer), node); + return ts.visitNode(converted, visitor, ts.isExpression); + } + function collidesWithParameterName(_a) { + var name = _a.name; + if (ts.isIdentifier(name)) { + return enclosingFunctionParameterNames.has(name.escapedText); + } + else { + for (var _i = 0, _b = name.elements; _i < _b.length; _i++) { + var element = _b[_i]; + if (!ts.isOmittedExpression(element) && collidesWithParameterName(element)) { + return true; + } + } + } + return false; + } + function transformAsyncFunctionBody(node) { + resumeLexicalEnvironment(); + var original = ts.getOriginalNode(node, ts.isFunctionLike); + var nodeType = original.type; + var promiseConstructor = languageVersion < 2 ? getPromiseConstructor(nodeType) : undefined; + var isArrowFunction = node.kind === 197; + var hasLexicalArguments = (resolver.getNodeCheckFlags(node) & 8192) !== 0; + var savedEnclosingFunctionParameterNames = enclosingFunctionParameterNames; + enclosingFunctionParameterNames = ts.createUnderscoreEscapedMap(); + for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { + var parameter = _a[_i]; + recordDeclarationName(parameter, enclosingFunctionParameterNames); + } + var savedCapturedSuperProperties = capturedSuperProperties; + var savedHasSuperElementAccess = hasSuperElementAccess; + capturedSuperProperties = ts.createUnderscoreEscapedMap(); + hasSuperElementAccess = false; + var result; + if (!isArrowFunction) { + var statements = []; + var statementOffset = ts.addPrologue(statements, node.body.statements, false, visitor); + statements.push(ts.createReturn(createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, transformAsyncFunctionBodyWorker(node.body, statementOffset)))); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + var emitSuperHelpers = languageVersion >= 2 && resolver.getNodeCheckFlags(node) & (4096 | 2048); + if (emitSuperHelpers) { + enableSubstitutionForAsyncMethodsWithSuper(); + var variableStatement = createSuperAccessVariableStatement(resolver, node, capturedSuperProperties); + substitutedSuperAccessors[ts.getNodeId(variableStatement)] = true; + ts.addStatementsAfterPrologue(statements, [variableStatement]); + } + var block = ts.createBlock(statements, true); + ts.setTextRange(block, node.body); + if (emitSuperHelpers && hasSuperElementAccess) { + if (resolver.getNodeCheckFlags(node) & 4096) { + ts.addEmitHelper(block, ts.advancedAsyncSuperHelper); + } + else if (resolver.getNodeCheckFlags(node) & 2048) { + ts.addEmitHelper(block, ts.asyncSuperHelper); + } + } + result = block; + } + else { + var expression = createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, transformAsyncFunctionBodyWorker(node.body)); + var declarations = endLexicalEnvironment(); + if (ts.some(declarations)) { + var block = ts.convertToFunctionBody(expression); + result = ts.updateBlock(block, ts.setTextRange(ts.createNodeArray(ts.concatenate(declarations, block.statements)), block.statements)); + } + else { + result = expression; + } + } + enclosingFunctionParameterNames = savedEnclosingFunctionParameterNames; + capturedSuperProperties = savedCapturedSuperProperties; + hasSuperElementAccess = savedHasSuperElementAccess; + return result; + } + function transformAsyncFunctionBodyWorker(body, start) { + if (ts.isBlock(body)) { + return ts.updateBlock(body, ts.visitNodes(body.statements, asyncBodyVisitor, ts.isStatement, start)); + } + else { + return ts.convertToFunctionBody(ts.visitNode(body, asyncBodyVisitor, ts.isConciseBody)); + } + } + function getPromiseConstructor(type) { + var typeName = type && ts.getEntityNameFromTypeNode(type); + if (typeName && ts.isEntityName(typeName)) { + var serializationKind = resolver.getTypeReferenceSerializationKind(typeName); + if (serializationKind === ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue + || serializationKind === ts.TypeReferenceSerializationKind.Unknown) { + return typeName; + } + } + return undefined; + } + function enableSubstitutionForAsyncMethodsWithSuper() { + if ((enabledSubstitutions & 1) === 0) { + enabledSubstitutions |= 1; + context.enableSubstitution(191); + context.enableSubstitution(189); + context.enableSubstitution(190); + context.enableEmitNotification(240); + context.enableEmitNotification(156); + context.enableEmitNotification(158); + context.enableEmitNotification(159); + context.enableEmitNotification(157); + context.enableEmitNotification(219); + } + } + function onEmitNode(hint, node, emitCallback) { + if (enabledSubstitutions & 1 && isSuperContainer(node)) { + var superContainerFlags = resolver.getNodeCheckFlags(node) & (2048 | 4096); + if (superContainerFlags !== enclosingSuperContainerFlags) { + var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags; + enclosingSuperContainerFlags = superContainerFlags; + previousOnEmitNode(hint, node, emitCallback); + enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags; + return; + } + } + else if (enabledSubstitutions && substitutedSuperAccessors[ts.getNodeId(node)]) { + var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags; + enclosingSuperContainerFlags = 0; + previousOnEmitNode(hint, node, emitCallback); + enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags; + return; + } + previousOnEmitNode(hint, node, emitCallback); + } + function onSubstituteNode(hint, node) { + node = previousOnSubstituteNode(hint, node); + if (hint === 1 && enclosingSuperContainerFlags) { + return substituteExpression(node); + } + return node; + } + function substituteExpression(node) { + switch (node.kind) { + case 189: + return substitutePropertyAccessExpression(node); + case 190: + return substituteElementAccessExpression(node); + case 191: + return substituteCallExpression(node); + } + return node; + } + function substitutePropertyAccessExpression(node) { + if (node.expression.kind === 98) { + return ts.setTextRange(ts.createPropertyAccess(ts.createFileLevelUniqueName("_super"), node.name), node); + } + return node; + } + function substituteElementAccessExpression(node) { + if (node.expression.kind === 98) { + return createSuperElementAccessInAsyncMethod(node.argumentExpression, node); + } + return node; + } + function substituteCallExpression(node) { + var expression = node.expression; + if (ts.isSuperProperty(expression)) { + var argumentExpression = ts.isPropertyAccessExpression(expression) + ? substitutePropertyAccessExpression(expression) + : substituteElementAccessExpression(expression); + return ts.createCall(ts.createPropertyAccess(argumentExpression, "call"), undefined, [ + ts.createThis() + ].concat(node.arguments)); + } + return node; + } + function isSuperContainer(node) { + var kind = node.kind; + return kind === 240 + || kind === 157 + || kind === 156 + || kind === 158 + || kind === 159; + } + function createSuperElementAccessInAsyncMethod(argumentExpression, location) { + if (enclosingSuperContainerFlags & 4096) { + return ts.setTextRange(ts.createPropertyAccess(ts.createCall(ts.createFileLevelUniqueName("_superIndex"), undefined, [argumentExpression]), "value"), location); + } + else { + return ts.setTextRange(ts.createCall(ts.createFileLevelUniqueName("_superIndex"), undefined, [argumentExpression]), location); + } + } + } + ts.transformES2017 = transformES2017; + function createSuperAccessVariableStatement(resolver, node, names) { + var hasBinding = (resolver.getNodeCheckFlags(node) & 4096) !== 0; + var accessors = []; + names.forEach(function (_, key) { + var name = ts.unescapeLeadingUnderscores(key); + var getterAndSetter = []; + getterAndSetter.push(ts.createPropertyAssignment("get", ts.createArrowFunction(undefined, undefined, [], undefined, undefined, ts.createPropertyAccess(ts.createSuper(), name)))); + if (hasBinding) { + getterAndSetter.push(ts.createPropertyAssignment("set", ts.createArrowFunction(undefined, undefined, [ + ts.createParameter(undefined, undefined, undefined, "v", undefined, undefined, undefined) + ], undefined, undefined, ts.createAssignment(ts.createPropertyAccess(ts.createSuper(), name), ts.createIdentifier("v"))))); + } + accessors.push(ts.createPropertyAssignment(name, ts.createObjectLiteral(getterAndSetter))); + }); + return ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(ts.createFileLevelUniqueName("_super"), undefined, ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "create"), undefined, [ + ts.createNull(), + ts.createObjectLiteral(accessors, true) + ])) + ], 2)); + } + ts.createSuperAccessVariableStatement = createSuperAccessVariableStatement; + var awaiterHelper = { + name: "typescript:awaiter", + scoped: false, + priority: 5, + text: "\n var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n };" + }; + function createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, body) { + context.requestEmitHelper(awaiterHelper); + var generatorFunc = ts.createFunctionExpression(undefined, ts.createToken(40), undefined, undefined, [], undefined, body); + (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 262144 | 524288; + return ts.createCall(ts.getHelperName("__awaiter"), undefined, [ + ts.createThis(), + hasLexicalArguments ? ts.createIdentifier("arguments") : ts.createVoidZero(), + promiseConstructor ? ts.createExpressionFromEntityName(promiseConstructor) : ts.createVoidZero(), + generatorFunc + ]); + } + ts.asyncSuperHelper = { + name: "typescript:async-super", + scoped: true, + text: ts.helperString(__makeTemplateObject(["\n const ", " = name => super[name];"], ["\n const ", " = name => super[name];"]), "_superIndex") + }; + ts.advancedAsyncSuperHelper = { + name: "typescript:advanced-async-super", + scoped: true, + text: ts.helperString(__makeTemplateObject(["\n const ", " = (function (geti, seti) {\n const cache = Object.create(null);\n return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } });\n })(name => super[name], (name, value) => super[name] = value);"], ["\n const ", " = (function (geti, seti) {\n const cache = Object.create(null);\n return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } });\n })(name => super[name], (name, value) => super[name] = value);"]), "_superIndex") + }; +})(ts || (ts = {})); +var ts; +(function (ts) { + function transformESNext(context) { + var resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; + var resolver = context.getEmitResolver(); + var compilerOptions = context.getCompilerOptions(); + var languageVersion = ts.getEmitScriptTarget(compilerOptions); + var previousOnEmitNode = context.onEmitNode; + context.onEmitNode = onEmitNode; + var previousOnSubstituteNode = context.onSubstituteNode; + context.onSubstituteNode = onSubstituteNode; + var enabledSubstitutions; + var enclosingFunctionFlags; + var enclosingSuperContainerFlags = 0; + var capturedSuperProperties; + var hasSuperElementAccess; + var substitutedSuperAccessors = []; + return ts.chainBundle(transformSourceFile); + function transformSourceFile(node) { + if (node.isDeclarationFile) { + return node; + } + var visited = ts.visitEachChild(node, visitor, context); + ts.addEmitHelpers(visited, context.readEmitHelpers()); + return visited; + } + function visitor(node) { + return visitorWorker(node, false); + } + function visitorNoDestructuringValue(node) { + return visitorWorker(node, true); + } + function visitorNoAsyncModifier(node) { + if (node.kind === 121) { + return undefined; + } + return node; + } + function visitorWorker(node, noDestructuringValue) { + if ((node.transformFlags & 8) === 0) { + return node; + } + switch (node.kind) { + case 201: + return visitAwaitExpression(node); + case 207: + return visitYieldExpression(node); + case 230: + return visitReturnStatement(node); + case 233: + return visitLabeledStatement(node); + case 188: + return visitObjectLiteralExpression(node); + case 204: + return visitBinaryExpression(node, noDestructuringValue); + case 237: + return visitVariableDeclaration(node); + case 227: + return visitForOfStatement(node, undefined); + case 225: + return visitForStatement(node); + case 200: + return visitVoidExpression(node); + case 157: + return visitConstructorDeclaration(node); + case 156: + return visitMethodDeclaration(node); + case 158: + return visitGetAccessorDeclaration(node); + case 159: + return visitSetAccessorDeclaration(node); + case 239: + return visitFunctionDeclaration(node); + case 196: + return visitFunctionExpression(node); + case 197: + return visitArrowFunction(node); + case 151: + return visitParameter(node); + case 221: + return visitExpressionStatement(node); + case 195: + return visitParenthesizedExpression(node, noDestructuringValue); + case 274: + return visitCatchClause(node); + case 189: + if (capturedSuperProperties && ts.isPropertyAccessExpression(node) && node.expression.kind === 98) { + capturedSuperProperties.set(node.name.escapedText, true); + } + return ts.visitEachChild(node, visitor, context); + case 190: + if (capturedSuperProperties && node.expression.kind === 98) { + hasSuperElementAccess = true; + } + return ts.visitEachChild(node, visitor, context); + default: + return ts.visitEachChild(node, visitor, context); + } + } + function visitAwaitExpression(node) { + if (enclosingFunctionFlags & 2 && enclosingFunctionFlags & 1) { + return ts.setOriginalNode(ts.setTextRange(ts.createYield(createAwaitHelper(context, ts.visitNode(node.expression, visitor, ts.isExpression))), node), node); + } + return ts.visitEachChild(node, visitor, context); + } + function visitYieldExpression(node) { + if (enclosingFunctionFlags & 2 && enclosingFunctionFlags & 1) { + if (node.asteriskToken) { + var expression = ts.visitNode(node.expression, visitor, ts.isExpression); + return ts.setOriginalNode(ts.setTextRange(ts.createYield(createAwaitHelper(context, ts.updateYield(node, node.asteriskToken, createAsyncDelegatorHelper(context, createAsyncValuesHelper(context, expression, expression), expression)))), node), node); + } + return ts.setOriginalNode(ts.setTextRange(ts.createYield(createDownlevelAwait(node.expression + ? ts.visitNode(node.expression, visitor, ts.isExpression) + : ts.createVoidZero())), node), node); + } + return ts.visitEachChild(node, visitor, context); + } + function visitReturnStatement(node) { + if (enclosingFunctionFlags & 2 && enclosingFunctionFlags & 1) { + return ts.updateReturn(node, createDownlevelAwait(node.expression ? ts.visitNode(node.expression, visitor, ts.isExpression) : ts.createVoidZero())); + } + return ts.visitEachChild(node, visitor, context); + } + function visitLabeledStatement(node) { + if (enclosingFunctionFlags & 2) { + var statement = ts.unwrapInnermostStatementOfLabel(node); + if (statement.kind === 227 && statement.awaitModifier) { + return visitForOfStatement(statement, node); + } + return ts.restoreEnclosingLabel(ts.visitEachChild(statement, visitor, context), node); + } + return ts.visitEachChild(node, visitor, context); + } + function chunkObjectLiteralElements(elements) { + var chunkObject; + var objects = []; + for (var _i = 0, elements_4 = elements; _i < elements_4.length; _i++) { + var e = elements_4[_i]; + if (e.kind === 277) { + if (chunkObject) { + objects.push(ts.createObjectLiteral(chunkObject)); + chunkObject = undefined; + } + var target = e.expression; + objects.push(ts.visitNode(target, visitor, ts.isExpression)); + } + else { + chunkObject = ts.append(chunkObject, e.kind === 275 + ? ts.createPropertyAssignment(e.name, ts.visitNode(e.initializer, visitor, ts.isExpression)) + : ts.visitNode(e, visitor, ts.isObjectLiteralElementLike)); + } + } + if (chunkObject) { + objects.push(ts.createObjectLiteral(chunkObject)); + } + return objects; + } + function visitObjectLiteralExpression(node) { + if (node.transformFlags & 262144) { + var objects = chunkObjectLiteralElements(node.properties); + if (objects.length && objects[0].kind !== 188) { + objects.unshift(ts.createObjectLiteral()); + } + return createAssignHelper(context, objects); + } + return ts.visitEachChild(node, visitor, context); + } + function visitExpressionStatement(node) { + return ts.visitEachChild(node, visitorNoDestructuringValue, context); + } + function visitParenthesizedExpression(node, noDestructuringValue) { + return ts.visitEachChild(node, noDestructuringValue ? visitorNoDestructuringValue : visitor, context); + } + function visitCatchClause(node) { + if (!node.variableDeclaration) { + return ts.updateCatchClause(node, ts.createVariableDeclaration(ts.createTempVariable(undefined)), ts.visitNode(node.block, visitor, ts.isBlock)); + } + return ts.visitEachChild(node, visitor, context); + } + function visitBinaryExpression(node, noDestructuringValue) { + if (ts.isDestructuringAssignment(node) && node.left.transformFlags & 262144) { + return ts.flattenDestructuringAssignment(node, visitor, context, 1, !noDestructuringValue); + } + else if (node.operatorToken.kind === 27) { + return ts.updateBinary(node, ts.visitNode(node.left, visitorNoDestructuringValue, ts.isExpression), ts.visitNode(node.right, noDestructuringValue ? visitorNoDestructuringValue : visitor, ts.isExpression)); + } + return ts.visitEachChild(node, visitor, context); + } + function visitVariableDeclaration(node) { + if (ts.isBindingPattern(node.name) && node.name.transformFlags & 262144) { + return ts.flattenDestructuringBinding(node, visitor, context, 1); + } + return ts.visitEachChild(node, visitor, context); + } + function visitForStatement(node) { + return ts.updateFor(node, ts.visitNode(node.initializer, visitorNoDestructuringValue, ts.isForInitializer), ts.visitNode(node.condition, visitor, ts.isExpression), ts.visitNode(node.incrementor, visitor, ts.isExpression), ts.visitNode(node.statement, visitor, ts.isStatement)); + } + function visitVoidExpression(node) { + return ts.visitEachChild(node, visitorNoDestructuringValue, context); + } + function visitForOfStatement(node, outermostLabeledStatement) { + if (node.initializer.transformFlags & 262144) { + node = transformForOfStatementWithObjectRest(node); + } + if (node.awaitModifier) { + return transformForAwaitOfStatement(node, outermostLabeledStatement); + } + else { + return ts.restoreEnclosingLabel(ts.visitEachChild(node, visitor, context), outermostLabeledStatement); + } + } + function transformForOfStatementWithObjectRest(node) { + var initializerWithoutParens = ts.skipParentheses(node.initializer); + if (ts.isVariableDeclarationList(initializerWithoutParens) || ts.isAssignmentPattern(initializerWithoutParens)) { + var bodyLocation = void 0; + var statementsLocation = void 0; + var temp = ts.createTempVariable(undefined); + var statements = [ts.createForOfBindingStatement(initializerWithoutParens, temp)]; + if (ts.isBlock(node.statement)) { + ts.addRange(statements, node.statement.statements); + bodyLocation = node.statement; + statementsLocation = node.statement.statements; + } + else if (node.statement) { + ts.append(statements, node.statement); + bodyLocation = node.statement; + statementsLocation = node.statement; + } + return ts.updateForOf(node, node.awaitModifier, ts.setTextRange(ts.createVariableDeclarationList([ + ts.setTextRange(ts.createVariableDeclaration(temp), node.initializer) + ], 1), node.initializer), node.expression, ts.setTextRange(ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), statementsLocation), true), bodyLocation)); + } + return node; + } + function convertForOfStatementHead(node, boundValue) { + var binding = ts.createForOfBindingStatement(node.initializer, boundValue); + var bodyLocation; + var statementsLocation; + var statements = [ts.visitNode(binding, visitor, ts.isStatement)]; + var statement = ts.visitNode(node.statement, visitor, ts.isStatement); + if (ts.isBlock(statement)) { + ts.addRange(statements, statement.statements); + bodyLocation = statement; + statementsLocation = statement.statements; + } + else { + statements.push(statement); + } + return ts.setEmitFlags(ts.setTextRange(ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), statementsLocation), true), bodyLocation), 48 | 384); + } + function createDownlevelAwait(expression) { + return enclosingFunctionFlags & 1 + ? ts.createYield(undefined, createAwaitHelper(context, expression)) + : ts.createAwait(expression); + } + function transformForAwaitOfStatement(node, outermostLabeledStatement) { + var expression = ts.visitNode(node.expression, visitor, ts.isExpression); + var iterator = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(expression) : ts.createTempVariable(undefined); + var result = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(iterator) : ts.createTempVariable(undefined); + var errorRecord = ts.createUniqueName("e"); + var catchVariable = ts.getGeneratedNameForNode(errorRecord); + var returnMethod = ts.createTempVariable(undefined); + var callValues = createAsyncValuesHelper(context, expression, node.expression); + var callNext = ts.createCall(ts.createPropertyAccess(iterator, "next"), undefined, []); + var getDone = ts.createPropertyAccess(result, "done"); + var getValue = ts.createPropertyAccess(result, "value"); + var callReturn = ts.createFunctionCall(returnMethod, iterator, []); + hoistVariableDeclaration(errorRecord); + hoistVariableDeclaration(returnMethod); + var forStatement = ts.setEmitFlags(ts.setTextRange(ts.createFor(ts.setEmitFlags(ts.setTextRange(ts.createVariableDeclarationList([ + ts.setTextRange(ts.createVariableDeclaration(iterator, undefined, callValues), node.expression), + ts.createVariableDeclaration(result) + ]), node.expression), 2097152), ts.createComma(ts.createAssignment(result, createDownlevelAwait(callNext)), ts.createLogicalNot(getDone)), undefined, convertForOfStatementHead(node, getValue)), node), 256); + return ts.createTry(ts.createBlock([ + ts.restoreEnclosingLabel(forStatement, outermostLabeledStatement) + ]), ts.createCatchClause(ts.createVariableDeclaration(catchVariable), ts.setEmitFlags(ts.createBlock([ + ts.createExpressionStatement(ts.createAssignment(errorRecord, ts.createObjectLiteral([ + ts.createPropertyAssignment("error", catchVariable) + ]))) + ]), 1)), ts.createBlock([ + ts.createTry(ts.createBlock([ + ts.setEmitFlags(ts.createIf(ts.createLogicalAnd(ts.createLogicalAnd(result, ts.createLogicalNot(getDone)), ts.createAssignment(returnMethod, ts.createPropertyAccess(iterator, "return"))), ts.createExpressionStatement(createDownlevelAwait(callReturn))), 1) + ]), undefined, ts.setEmitFlags(ts.createBlock([ + ts.setEmitFlags(ts.createIf(errorRecord, ts.createThrow(ts.createPropertyAccess(errorRecord, "error"))), 1) + ]), 1)) + ])); + } + function visitParameter(node) { + if (node.transformFlags & 262144) { + return ts.updateParameter(node, undefined, undefined, node.dotDotDotToken, ts.getGeneratedNameForNode(node), undefined, undefined, ts.visitNode(node.initializer, visitor, ts.isExpression)); + } + return ts.visitEachChild(node, visitor, context); + } + function visitConstructorDeclaration(node) { + var savedEnclosingFunctionFlags = enclosingFunctionFlags; + enclosingFunctionFlags = 0; + var updated = ts.updateConstructor(node, undefined, node.modifiers, ts.visitParameterList(node.parameters, visitor, context), transformFunctionBody(node)); + enclosingFunctionFlags = savedEnclosingFunctionFlags; + return updated; + } + function visitGetAccessorDeclaration(node) { + var savedEnclosingFunctionFlags = enclosingFunctionFlags; + enclosingFunctionFlags = 0; + var updated = ts.updateGetAccessor(node, undefined, node.modifiers, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitParameterList(node.parameters, visitor, context), undefined, transformFunctionBody(node)); + enclosingFunctionFlags = savedEnclosingFunctionFlags; + return updated; + } + function visitSetAccessorDeclaration(node) { + var savedEnclosingFunctionFlags = enclosingFunctionFlags; + enclosingFunctionFlags = 0; + var updated = ts.updateSetAccessor(node, undefined, node.modifiers, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitParameterList(node.parameters, visitor, context), transformFunctionBody(node)); + enclosingFunctionFlags = savedEnclosingFunctionFlags; + return updated; + } + function visitMethodDeclaration(node) { + var savedEnclosingFunctionFlags = enclosingFunctionFlags; + enclosingFunctionFlags = ts.getFunctionFlags(node); + var updated = ts.updateMethod(node, undefined, enclosingFunctionFlags & 1 + ? ts.visitNodes(node.modifiers, visitorNoAsyncModifier, ts.isModifier) + : node.modifiers, enclosingFunctionFlags & 2 + ? undefined + : node.asteriskToken, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitNode(undefined, visitor, ts.isToken), undefined, ts.visitParameterList(node.parameters, visitor, context), undefined, enclosingFunctionFlags & 2 && enclosingFunctionFlags & 1 + ? transformAsyncGeneratorFunctionBody(node) + : transformFunctionBody(node)); + enclosingFunctionFlags = savedEnclosingFunctionFlags; + return updated; + } + function visitFunctionDeclaration(node) { + var savedEnclosingFunctionFlags = enclosingFunctionFlags; + enclosingFunctionFlags = ts.getFunctionFlags(node); + var updated = ts.updateFunctionDeclaration(node, undefined, enclosingFunctionFlags & 1 + ? ts.visitNodes(node.modifiers, visitorNoAsyncModifier, ts.isModifier) + : node.modifiers, enclosingFunctionFlags & 2 + ? undefined + : node.asteriskToken, node.name, undefined, ts.visitParameterList(node.parameters, visitor, context), undefined, enclosingFunctionFlags & 2 && enclosingFunctionFlags & 1 + ? transformAsyncGeneratorFunctionBody(node) + : transformFunctionBody(node)); + enclosingFunctionFlags = savedEnclosingFunctionFlags; + return updated; + } + function visitArrowFunction(node) { + var savedEnclosingFunctionFlags = enclosingFunctionFlags; + enclosingFunctionFlags = ts.getFunctionFlags(node); + var updated = ts.updateArrowFunction(node, node.modifiers, undefined, ts.visitParameterList(node.parameters, visitor, context), undefined, node.equalsGreaterThanToken, transformFunctionBody(node)); + enclosingFunctionFlags = savedEnclosingFunctionFlags; + return updated; + } + function visitFunctionExpression(node) { + var savedEnclosingFunctionFlags = enclosingFunctionFlags; + enclosingFunctionFlags = ts.getFunctionFlags(node); + var updated = ts.updateFunctionExpression(node, enclosingFunctionFlags & 1 + ? ts.visitNodes(node.modifiers, visitorNoAsyncModifier, ts.isModifier) + : node.modifiers, enclosingFunctionFlags & 2 + ? undefined + : node.asteriskToken, node.name, undefined, ts.visitParameterList(node.parameters, visitor, context), undefined, enclosingFunctionFlags & 2 && enclosingFunctionFlags & 1 + ? transformAsyncGeneratorFunctionBody(node) + : transformFunctionBody(node)); + enclosingFunctionFlags = savedEnclosingFunctionFlags; + return updated; + } + function transformAsyncGeneratorFunctionBody(node) { + resumeLexicalEnvironment(); + var statements = []; + var statementOffset = ts.addPrologue(statements, node.body.statements, false, visitor); + appendObjectRestAssignmentsIfNeeded(statements, node); + var savedCapturedSuperProperties = capturedSuperProperties; + var savedHasSuperElementAccess = hasSuperElementAccess; + capturedSuperProperties = ts.createUnderscoreEscapedMap(); + hasSuperElementAccess = false; + var returnStatement = ts.createReturn(createAsyncGeneratorHelper(context, ts.createFunctionExpression(undefined, ts.createToken(40), node.name && ts.getGeneratedNameForNode(node.name), undefined, [], undefined, ts.updateBlock(node.body, ts.visitLexicalEnvironment(node.body.statements, visitor, context, statementOffset))))); + var emitSuperHelpers = languageVersion >= 2 && resolver.getNodeCheckFlags(node) & (4096 | 2048); + if (emitSuperHelpers) { + enableSubstitutionForAsyncMethodsWithSuper(); + var variableStatement = ts.createSuperAccessVariableStatement(resolver, node, capturedSuperProperties); + substitutedSuperAccessors[ts.getNodeId(variableStatement)] = true; + ts.addStatementsAfterPrologue(statements, [variableStatement]); + } + statements.push(returnStatement); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + var block = ts.updateBlock(node.body, statements); + if (emitSuperHelpers && hasSuperElementAccess) { + if (resolver.getNodeCheckFlags(node) & 4096) { + ts.addEmitHelper(block, ts.advancedAsyncSuperHelper); + } + else if (resolver.getNodeCheckFlags(node) & 2048) { + ts.addEmitHelper(block, ts.asyncSuperHelper); + } + } + capturedSuperProperties = savedCapturedSuperProperties; + hasSuperElementAccess = savedHasSuperElementAccess; + return block; + } + function transformFunctionBody(node) { + resumeLexicalEnvironment(); + var statementOffset = 0; + var statements = []; + var body = ts.visitNode(node.body, visitor, ts.isConciseBody); + if (ts.isBlock(body)) { + statementOffset = ts.addPrologue(statements, body.statements, false, visitor); + } + ts.addRange(statements, appendObjectRestAssignmentsIfNeeded(undefined, node)); + var leadingStatements = endLexicalEnvironment(); + if (statementOffset > 0 || ts.some(statements) || ts.some(leadingStatements)) { + var block = ts.convertToFunctionBody(body, true); + ts.addStatementsAfterPrologue(statements, leadingStatements); + ts.addRange(statements, block.statements.slice(statementOffset)); + return ts.updateBlock(block, ts.setTextRange(ts.createNodeArray(statements), block.statements)); + } + return body; + } + function appendObjectRestAssignmentsIfNeeded(statements, node) { + for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { + var parameter = _a[_i]; + if (parameter.transformFlags & 262144) { + var temp = ts.getGeneratedNameForNode(parameter); + var declarations = ts.flattenDestructuringBinding(parameter, visitor, context, 1, temp, false, true); + if (ts.some(declarations)) { + var statement = ts.createVariableStatement(undefined, ts.createVariableDeclarationList(declarations)); + ts.setEmitFlags(statement, 1048576); + statements = ts.append(statements, statement); + } + } + } + return statements; + } + function enableSubstitutionForAsyncMethodsWithSuper() { + if ((enabledSubstitutions & 1) === 0) { + enabledSubstitutions |= 1; + context.enableSubstitution(191); + context.enableSubstitution(189); + context.enableSubstitution(190); + context.enableEmitNotification(240); + context.enableEmitNotification(156); + context.enableEmitNotification(158); + context.enableEmitNotification(159); + context.enableEmitNotification(157); + context.enableEmitNotification(219); + } + } + function onEmitNode(hint, node, emitCallback) { + if (enabledSubstitutions & 1 && isSuperContainer(node)) { + var superContainerFlags = resolver.getNodeCheckFlags(node) & (2048 | 4096); + if (superContainerFlags !== enclosingSuperContainerFlags) { + var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags; + enclosingSuperContainerFlags = superContainerFlags; + previousOnEmitNode(hint, node, emitCallback); + enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags; + return; + } + } + else if (enabledSubstitutions && substitutedSuperAccessors[ts.getNodeId(node)]) { + var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags; + enclosingSuperContainerFlags = 0; + previousOnEmitNode(hint, node, emitCallback); + enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags; + return; + } + previousOnEmitNode(hint, node, emitCallback); + } + function onSubstituteNode(hint, node) { + node = previousOnSubstituteNode(hint, node); + if (hint === 1 && enclosingSuperContainerFlags) { + return substituteExpression(node); + } + return node; + } + function substituteExpression(node) { + switch (node.kind) { + case 189: + return substitutePropertyAccessExpression(node); + case 190: + return substituteElementAccessExpression(node); + case 191: + return substituteCallExpression(node); + } + return node; + } + function substitutePropertyAccessExpression(node) { + if (node.expression.kind === 98) { + return ts.setTextRange(ts.createPropertyAccess(ts.createFileLevelUniqueName("_super"), node.name), node); + } + return node; + } + function substituteElementAccessExpression(node) { + if (node.expression.kind === 98) { + return createSuperElementAccessInAsyncMethod(node.argumentExpression, node); + } + return node; + } + function substituteCallExpression(node) { + var expression = node.expression; + if (ts.isSuperProperty(expression)) { + var argumentExpression = ts.isPropertyAccessExpression(expression) + ? substitutePropertyAccessExpression(expression) + : substituteElementAccessExpression(expression); + return ts.createCall(ts.createPropertyAccess(argumentExpression, "call"), undefined, [ + ts.createThis() + ].concat(node.arguments)); + } + return node; + } + function isSuperContainer(node) { + var kind = node.kind; + return kind === 240 + || kind === 157 + || kind === 156 + || kind === 158 + || kind === 159; + } + function createSuperElementAccessInAsyncMethod(argumentExpression, location) { + if (enclosingSuperContainerFlags & 4096) { + return ts.setTextRange(ts.createPropertyAccess(ts.createCall(ts.createIdentifier("_superIndex"), undefined, [argumentExpression]), "value"), location); + } + else { + return ts.setTextRange(ts.createCall(ts.createIdentifier("_superIndex"), undefined, [argumentExpression]), location); + } + } + } + ts.transformESNext = transformESNext; + var assignHelper = { + name: "typescript:assign", + scoped: false, + priority: 1, + text: "\n var __assign = (this && this.__assign) || function () {\n __assign = Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n };\n return __assign.apply(this, arguments);\n };" + }; + function createAssignHelper(context, attributesSegments) { + if (context.getCompilerOptions().target >= 2) { + return ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "assign"), undefined, attributesSegments); + } + context.requestEmitHelper(assignHelper); + return ts.createCall(ts.getHelperName("__assign"), undefined, attributesSegments); + } + ts.createAssignHelper = createAssignHelper; + var awaitHelper = { + name: "typescript:await", + scoped: false, + text: "\n var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }" + }; + function createAwaitHelper(context, expression) { + context.requestEmitHelper(awaitHelper); + return ts.createCall(ts.getHelperName("__await"), undefined, [expression]); + } + var asyncGeneratorHelper = { + name: "typescript:asyncGenerator", + scoped: false, + text: "\n var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\n function fulfill(value) { resume(\"next\", value); }\n function reject(value) { resume(\"throw\", value); }\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\n };" + }; + function createAsyncGeneratorHelper(context, generatorFunc) { + context.requestEmitHelper(awaitHelper); + context.requestEmitHelper(asyncGeneratorHelper); + (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 262144; + return ts.createCall(ts.getHelperName("__asyncGenerator"), undefined, [ + ts.createThis(), + ts.createIdentifier("arguments"), + generatorFunc + ]); + } + var asyncDelegator = { + name: "typescript:asyncDelegator", + scoped: false, + text: "\n var __asyncDelegator = (this && this.__asyncDelegator) || function (o) {\n var i, p;\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; } : f; }\n };" + }; + function createAsyncDelegatorHelper(context, expression, location) { + context.requestEmitHelper(awaitHelper); + context.requestEmitHelper(asyncDelegator); + return ts.setTextRange(ts.createCall(ts.getHelperName("__asyncDelegator"), undefined, [expression]), location); + } + var asyncValues = { + name: "typescript:asyncValues", + scoped: false, + text: "\n var __asyncValues = (this && this.__asyncValues) || function (o) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var m = o[Symbol.asyncIterator], i;\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\n };" + }; + function createAsyncValuesHelper(context, expression, location) { + context.requestEmitHelper(asyncValues); + return ts.setTextRange(ts.createCall(ts.getHelperName("__asyncValues"), undefined, [expression]), location); + } +})(ts || (ts = {})); +var ts; +(function (ts) { + function transformJsx(context) { + var compilerOptions = context.getCompilerOptions(); + var currentSourceFile; + return ts.chainBundle(transformSourceFile); + function transformSourceFile(node) { + if (node.isDeclarationFile) { + return node; + } + currentSourceFile = node; + var visited = ts.visitEachChild(node, visitor, context); + ts.addEmitHelpers(visited, context.readEmitHelpers()); + return visited; + } + function visitor(node) { + if (node.transformFlags & 4) { + return visitorWorker(node); + } + else { + return node; + } + } + function visitorWorker(node) { + switch (node.kind) { + case 260: + return visitJsxElement(node, false); + case 261: + return visitJsxSelfClosingElement(node, false); + case 264: + return visitJsxFragment(node, false); + case 270: + return visitJsxExpression(node); + default: + return ts.visitEachChild(node, visitor, context); + } + } + function transformJsxChildToExpression(node) { + switch (node.kind) { + case 11: + return visitJsxText(node); + case 270: + return visitJsxExpression(node); + case 260: + return visitJsxElement(node, true); + case 261: + return visitJsxSelfClosingElement(node, true); + case 264: + return visitJsxFragment(node, true); + default: + return ts.Debug.failBadSyntaxKind(node); + } + } + function visitJsxElement(node, isChild) { + return visitJsxOpeningLikeElement(node.openingElement, node.children, isChild, node); + } + function visitJsxSelfClosingElement(node, isChild) { + return visitJsxOpeningLikeElement(node, undefined, isChild, node); + } + function visitJsxFragment(node, isChild) { + return visitJsxOpeningFragment(node.openingFragment, node.children, isChild, node); + } + function visitJsxOpeningLikeElement(node, children, isChild, location) { + var tagName = getTagName(node); + var objectProperties; + var attrs = node.attributes.properties; + if (attrs.length === 0) { + objectProperties = ts.createNull(); + } + else { + var segments = ts.flatten(ts.spanMap(attrs, ts.isJsxSpreadAttribute, function (attrs, isSpread) { return isSpread + ? ts.map(attrs, transformJsxSpreadAttributeToExpression) + : ts.createObjectLiteral(ts.map(attrs, transformJsxAttributeToObjectLiteralElement)); })); + if (ts.isJsxSpreadAttribute(attrs[0])) { + segments.unshift(ts.createObjectLiteral()); + } + objectProperties = ts.singleOrUndefined(segments); + if (!objectProperties) { + objectProperties = ts.createAssignHelper(context, segments); + } + } + var element = ts.createExpressionForJsxElement(context.getEmitResolver().getJsxFactoryEntity(currentSourceFile), compilerOptions.reactNamespace, tagName, objectProperties, ts.mapDefined(children, transformJsxChildToExpression), node, location); + if (isChild) { + ts.startOnNewLine(element); + } + return element; + } + function visitJsxOpeningFragment(node, children, isChild, location) { + var element = ts.createExpressionForJsxFragment(context.getEmitResolver().getJsxFactoryEntity(currentSourceFile), compilerOptions.reactNamespace, ts.mapDefined(children, transformJsxChildToExpression), node, location); + if (isChild) { + ts.startOnNewLine(element); + } + return element; + } + function transformJsxSpreadAttributeToExpression(node) { + return ts.visitNode(node.expression, visitor, ts.isExpression); + } + function transformJsxAttributeToObjectLiteralElement(node) { + var name = getAttributeName(node); + var expression = transformJsxAttributeInitializer(node.initializer); + return ts.createPropertyAssignment(name, expression); + } + function transformJsxAttributeInitializer(node) { + if (node === undefined) { + return ts.createTrue(); + } + else if (node.kind === 10) { + var literal = ts.createLiteral(tryDecodeEntities(node.text) || node.text); + literal.singleQuote = node.singleQuote !== undefined ? node.singleQuote : !ts.isStringDoubleQuoted(node, currentSourceFile); + return ts.setTextRange(literal, node); + } + else if (node.kind === 270) { + if (node.expression === undefined) { + return ts.createTrue(); + } + return visitJsxExpression(node); + } + else { + return ts.Debug.failBadSyntaxKind(node); + } + } + function visitJsxText(node) { + var fixed = fixupWhitespaceAndDecodeEntities(ts.getTextOfNode(node, true)); + return fixed === undefined ? undefined : ts.createLiteral(fixed); + } + function fixupWhitespaceAndDecodeEntities(text) { + var acc; + var firstNonWhitespace = 0; + var lastNonWhitespace = -1; + for (var i = 0; i < text.length; i++) { + var c = text.charCodeAt(i); + if (ts.isLineBreak(c)) { + if (firstNonWhitespace !== -1 && lastNonWhitespace !== -1) { + acc = addLineOfJsxText(acc, text.substr(firstNonWhitespace, lastNonWhitespace - firstNonWhitespace + 1)); + } + firstNonWhitespace = -1; + } + else if (!ts.isWhiteSpaceSingleLine(c)) { + lastNonWhitespace = i; + if (firstNonWhitespace === -1) { + firstNonWhitespace = i; + } + } + } + return firstNonWhitespace !== -1 + ? addLineOfJsxText(acc, text.substr(firstNonWhitespace)) + : acc; + } + function addLineOfJsxText(acc, trimmedLine) { + var decoded = decodeEntities(trimmedLine); + return acc === undefined ? decoded : acc + " " + decoded; + } + function decodeEntities(text) { + return text.replace(/&((#((\d+)|x([\da-fA-F]+)))|(\w+));/g, function (match, _all, _number, _digits, decimal, hex, word) { + if (decimal) { + return String.fromCharCode(parseInt(decimal, 10)); + } + else if (hex) { + return String.fromCharCode(parseInt(hex, 16)); + } + else { + var ch = entities.get(word); + return ch ? String.fromCharCode(ch) : match; + } + }); + } + function tryDecodeEntities(text) { + var decoded = decodeEntities(text); + return decoded === text ? undefined : decoded; + } + function getTagName(node) { + if (node.kind === 260) { + return getTagName(node.openingElement); + } + else { + var name = node.tagName; + if (ts.isIdentifier(name) && ts.isIntrinsicJsxName(name.escapedText)) { + return ts.createLiteral(ts.idText(name)); + } + else { + return ts.createExpressionFromEntityName(name); + } + } + } + function getAttributeName(node) { + var name = node.name; + var text = ts.idText(name); + if (/^[A-Za-z_]\w*$/.test(text)) { + return name; + } + else { + return ts.createLiteral(text); + } + } + function visitJsxExpression(node) { + return ts.visitNode(node.expression, visitor, ts.isExpression); + } + } + ts.transformJsx = transformJsx; + var entities = ts.createMapFromTemplate({ + quot: 0x0022, + amp: 0x0026, + apos: 0x0027, + lt: 0x003C, + gt: 0x003E, + nbsp: 0x00A0, + iexcl: 0x00A1, + cent: 0x00A2, + pound: 0x00A3, + curren: 0x00A4, + yen: 0x00A5, + brvbar: 0x00A6, + sect: 0x00A7, + uml: 0x00A8, + copy: 0x00A9, + ordf: 0x00AA, + laquo: 0x00AB, + not: 0x00AC, + shy: 0x00AD, + reg: 0x00AE, + macr: 0x00AF, + deg: 0x00B0, + plusmn: 0x00B1, + sup2: 0x00B2, + sup3: 0x00B3, + acute: 0x00B4, + micro: 0x00B5, + para: 0x00B6, + middot: 0x00B7, + cedil: 0x00B8, + sup1: 0x00B9, + ordm: 0x00BA, + raquo: 0x00BB, + frac14: 0x00BC, + frac12: 0x00BD, + frac34: 0x00BE, + iquest: 0x00BF, + Agrave: 0x00C0, + Aacute: 0x00C1, + Acirc: 0x00C2, + Atilde: 0x00C3, + Auml: 0x00C4, + Aring: 0x00C5, + AElig: 0x00C6, + Ccedil: 0x00C7, + Egrave: 0x00C8, + Eacute: 0x00C9, + Ecirc: 0x00CA, + Euml: 0x00CB, + Igrave: 0x00CC, + Iacute: 0x00CD, + Icirc: 0x00CE, + Iuml: 0x00CF, + ETH: 0x00D0, + Ntilde: 0x00D1, + Ograve: 0x00D2, + Oacute: 0x00D3, + Ocirc: 0x00D4, + Otilde: 0x00D5, + Ouml: 0x00D6, + times: 0x00D7, + Oslash: 0x00D8, + Ugrave: 0x00D9, + Uacute: 0x00DA, + Ucirc: 0x00DB, + Uuml: 0x00DC, + Yacute: 0x00DD, + THORN: 0x00DE, + szlig: 0x00DF, + agrave: 0x00E0, + aacute: 0x00E1, + acirc: 0x00E2, + atilde: 0x00E3, + auml: 0x00E4, + aring: 0x00E5, + aelig: 0x00E6, + ccedil: 0x00E7, + egrave: 0x00E8, + eacute: 0x00E9, + ecirc: 0x00EA, + euml: 0x00EB, + igrave: 0x00EC, + iacute: 0x00ED, + icirc: 0x00EE, + iuml: 0x00EF, + eth: 0x00F0, + ntilde: 0x00F1, + ograve: 0x00F2, + oacute: 0x00F3, + ocirc: 0x00F4, + otilde: 0x00F5, + ouml: 0x00F6, + divide: 0x00F7, + oslash: 0x00F8, + ugrave: 0x00F9, + uacute: 0x00FA, + ucirc: 0x00FB, + uuml: 0x00FC, + yacute: 0x00FD, + thorn: 0x00FE, + yuml: 0x00FF, + OElig: 0x0152, + oelig: 0x0153, + Scaron: 0x0160, + scaron: 0x0161, + Yuml: 0x0178, + fnof: 0x0192, + circ: 0x02C6, + tilde: 0x02DC, + Alpha: 0x0391, + Beta: 0x0392, + Gamma: 0x0393, + Delta: 0x0394, + Epsilon: 0x0395, + Zeta: 0x0396, + Eta: 0x0397, + Theta: 0x0398, + Iota: 0x0399, + Kappa: 0x039A, + Lambda: 0x039B, + Mu: 0x039C, + Nu: 0x039D, + Xi: 0x039E, + Omicron: 0x039F, + Pi: 0x03A0, + Rho: 0x03A1, + Sigma: 0x03A3, + Tau: 0x03A4, + Upsilon: 0x03A5, + Phi: 0x03A6, + Chi: 0x03A7, + Psi: 0x03A8, + Omega: 0x03A9, + alpha: 0x03B1, + beta: 0x03B2, + gamma: 0x03B3, + delta: 0x03B4, + epsilon: 0x03B5, + zeta: 0x03B6, + eta: 0x03B7, + theta: 0x03B8, + iota: 0x03B9, + kappa: 0x03BA, + lambda: 0x03BB, + mu: 0x03BC, + nu: 0x03BD, + xi: 0x03BE, + omicron: 0x03BF, + pi: 0x03C0, + rho: 0x03C1, + sigmaf: 0x03C2, + sigma: 0x03C3, + tau: 0x03C4, + upsilon: 0x03C5, + phi: 0x03C6, + chi: 0x03C7, + psi: 0x03C8, + omega: 0x03C9, + thetasym: 0x03D1, + upsih: 0x03D2, + piv: 0x03D6, + ensp: 0x2002, + emsp: 0x2003, + thinsp: 0x2009, + zwnj: 0x200C, + zwj: 0x200D, + lrm: 0x200E, + rlm: 0x200F, + ndash: 0x2013, + mdash: 0x2014, + lsquo: 0x2018, + rsquo: 0x2019, + sbquo: 0x201A, + ldquo: 0x201C, + rdquo: 0x201D, + bdquo: 0x201E, + dagger: 0x2020, + Dagger: 0x2021, + bull: 0x2022, + hellip: 0x2026, + permil: 0x2030, + prime: 0x2032, + Prime: 0x2033, + lsaquo: 0x2039, + rsaquo: 0x203A, + oline: 0x203E, + frasl: 0x2044, + euro: 0x20AC, + image: 0x2111, + weierp: 0x2118, + real: 0x211C, + trade: 0x2122, + alefsym: 0x2135, + larr: 0x2190, + uarr: 0x2191, + rarr: 0x2192, + darr: 0x2193, + harr: 0x2194, + crarr: 0x21B5, + lArr: 0x21D0, + uArr: 0x21D1, + rArr: 0x21D2, + dArr: 0x21D3, + hArr: 0x21D4, + forall: 0x2200, + part: 0x2202, + exist: 0x2203, + empty: 0x2205, + nabla: 0x2207, + isin: 0x2208, + notin: 0x2209, + ni: 0x220B, + prod: 0x220F, + sum: 0x2211, + minus: 0x2212, + lowast: 0x2217, + radic: 0x221A, + prop: 0x221D, + infin: 0x221E, + ang: 0x2220, + and: 0x2227, + or: 0x2228, + cap: 0x2229, + cup: 0x222A, + int: 0x222B, + there4: 0x2234, + sim: 0x223C, + cong: 0x2245, + asymp: 0x2248, + ne: 0x2260, + equiv: 0x2261, + le: 0x2264, + ge: 0x2265, + sub: 0x2282, + sup: 0x2283, + nsub: 0x2284, + sube: 0x2286, + supe: 0x2287, + oplus: 0x2295, + otimes: 0x2297, + perp: 0x22A5, + sdot: 0x22C5, + lceil: 0x2308, + rceil: 0x2309, + lfloor: 0x230A, + rfloor: 0x230B, + lang: 0x2329, + rang: 0x232A, + loz: 0x25CA, + spades: 0x2660, + clubs: 0x2663, + hearts: 0x2665, + diams: 0x2666 + }); +})(ts || (ts = {})); +var ts; +(function (ts) { + function transformES2016(context) { + var hoistVariableDeclaration = context.hoistVariableDeclaration; + return ts.chainBundle(transformSourceFile); + function transformSourceFile(node) { + if (node.isDeclarationFile) { + return node; + } + return ts.visitEachChild(node, visitor, context); + } + function visitor(node) { + if ((node.transformFlags & 32) === 0) { + return node; + } + switch (node.kind) { + case 204: + return visitBinaryExpression(node); + default: + return ts.visitEachChild(node, visitor, context); + } + } + function visitBinaryExpression(node) { + switch (node.operatorToken.kind) { + case 63: + return visitExponentiationAssignmentExpression(node); + case 41: + return visitExponentiationExpression(node); + default: + return ts.visitEachChild(node, visitor, context); + } + } + function visitExponentiationAssignmentExpression(node) { + var target; + var value; + var left = ts.visitNode(node.left, visitor, ts.isExpression); + var right = ts.visitNode(node.right, visitor, ts.isExpression); + if (ts.isElementAccessExpression(left)) { + var expressionTemp = ts.createTempVariable(hoistVariableDeclaration); + var argumentExpressionTemp = ts.createTempVariable(hoistVariableDeclaration); + target = ts.setTextRange(ts.createElementAccess(ts.setTextRange(ts.createAssignment(expressionTemp, left.expression), left.expression), ts.setTextRange(ts.createAssignment(argumentExpressionTemp, left.argumentExpression), left.argumentExpression)), left); + value = ts.setTextRange(ts.createElementAccess(expressionTemp, argumentExpressionTemp), left); + } + else if (ts.isPropertyAccessExpression(left)) { + var expressionTemp = ts.createTempVariable(hoistVariableDeclaration); + target = ts.setTextRange(ts.createPropertyAccess(ts.setTextRange(ts.createAssignment(expressionTemp, left.expression), left.expression), left.name), left); + value = ts.setTextRange(ts.createPropertyAccess(expressionTemp, left.name), left); + } + else { + target = left; + value = left; + } + return ts.setTextRange(ts.createAssignment(target, ts.createMathPow(value, right, node)), node); + } + function visitExponentiationExpression(node) { + var left = ts.visitNode(node.left, visitor, ts.isExpression); + var right = ts.visitNode(node.right, visitor, ts.isExpression); + return ts.createMathPow(left, right, node); + } + } + ts.transformES2016 = transformES2016; +})(ts || (ts = {})); +var ts; +(function (ts) { + function transformES2015(context) { + var startLexicalEnvironment = context.startLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; + var compilerOptions = context.getCompilerOptions(); + var resolver = context.getEmitResolver(); + var previousOnSubstituteNode = context.onSubstituteNode; + var previousOnEmitNode = context.onEmitNode; + context.onEmitNode = onEmitNode; + context.onSubstituteNode = onSubstituteNode; + var currentSourceFile; + var currentText; + var hierarchyFacts; + var taggedTemplateStringDeclarations; + function recordTaggedTemplateString(temp) { + taggedTemplateStringDeclarations = ts.append(taggedTemplateStringDeclarations, ts.createVariableDeclaration(temp)); + } + var convertedLoopState; + var enabledSubstitutions; + return ts.chainBundle(transformSourceFile); + function transformSourceFile(node) { + if (node.isDeclarationFile) { + return node; + } + currentSourceFile = node; + currentText = node.text; + var visited = visitSourceFile(node); + ts.addEmitHelpers(visited, context.readEmitHelpers()); + currentSourceFile = undefined; + currentText = undefined; + taggedTemplateStringDeclarations = undefined; + hierarchyFacts = 0; + return visited; + } + function enterSubtree(excludeFacts, includeFacts) { + var ancestorFacts = hierarchyFacts; + hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & 16383; + return ancestorFacts; + } + function exitSubtree(ancestorFacts, excludeFacts, includeFacts) { + hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & -16384 | ancestorFacts; + } + function isReturnVoidStatementInConstructorWithCapturedSuper(node) { + return (hierarchyFacts & 4096) !== 0 + && node.kind === 230 + && !node.expression; + } + function shouldVisitNode(node) { + return (node.transformFlags & 128) !== 0 + || convertedLoopState !== undefined + || (hierarchyFacts & 4096 && (ts.isStatement(node) || (node.kind === 218))) + || (ts.isIterationStatement(node, false) && shouldConvertIterationStatement(node)) + || (ts.getEmitFlags(node) & 33554432) !== 0; + } + function visitor(node) { + if (shouldVisitNode(node)) { + return visitJavaScript(node); + } + else { + return node; + } + } + function functionBodyVisitor(node) { + if (shouldVisitNode(node)) { + return visitBlock(node, true); + } + return node; + } + function callExpressionVisitor(node) { + if (node.kind === 98) { + return visitSuperKeyword(true); + } + return visitor(node); + } + function visitJavaScript(node) { + switch (node.kind) { + case 116: + return undefined; + case 240: + return visitClassDeclaration(node); + case 209: + return visitClassExpression(node); + case 151: + return visitParameter(node); + case 239: + return visitFunctionDeclaration(node); + case 197: + return visitArrowFunction(node); + case 196: + return visitFunctionExpression(node); + case 237: + return visitVariableDeclaration(node); + case 72: + return visitIdentifier(node); + case 238: + return visitVariableDeclarationList(node); + case 232: + return visitSwitchStatement(node); + case 246: + return visitCaseBlock(node); + case 218: + return visitBlock(node, false); + case 229: + case 228: + return visitBreakOrContinueStatement(node); + case 233: + return visitLabeledStatement(node); + case 223: + case 224: + return visitDoOrWhileStatement(node, undefined); + case 225: + return visitForStatement(node, undefined); + case 226: + return visitForInStatement(node, undefined); + case 227: + return visitForOfStatement(node, undefined); + case 221: + return visitExpressionStatement(node); + case 188: + return visitObjectLiteralExpression(node); + case 274: + return visitCatchClause(node); + case 276: + return visitShorthandPropertyAssignment(node); + case 149: + return visitComputedPropertyName(node); + case 187: + return visitArrayLiteralExpression(node); + case 191: + return visitCallExpression(node); + case 192: + return visitNewExpression(node); + case 195: + return visitParenthesizedExpression(node, true); + case 204: + return visitBinaryExpression(node, true); + case 14: + case 15: + case 16: + case 17: + return visitTemplateLiteral(node); + case 10: + return visitStringLiteral(node); + case 8: + return visitNumericLiteral(node); + case 193: + return visitTaggedTemplateExpression(node); + case 206: + return visitTemplateExpression(node); + case 207: + return visitYieldExpression(node); + case 208: + return visitSpreadElement(node); + case 98: + return visitSuperKeyword(false); + case 100: + return visitThisKeyword(node); + case 214: + return visitMetaProperty(node); + case 156: + return visitMethodDeclaration(node); + case 158: + case 159: + return visitAccessorDeclaration(node); + case 219: + return visitVariableStatement(node); + case 230: + return visitReturnStatement(node); + default: + return ts.visitEachChild(node, visitor, context); + } + } + function visitSourceFile(node) { + var ancestorFacts = enterSubtree(3968, 64); + var statements = []; + startLexicalEnvironment(); + var statementOffset = ts.addStandardPrologue(statements, node.statements, false); + addCaptureThisForNodeIfNeeded(statements, node); + statementOffset = ts.addCustomPrologue(statements, node.statements, statementOffset, visitor); + ts.addRange(statements, ts.visitNodes(node.statements, visitor, ts.isStatement, statementOffset)); + if (taggedTemplateStringDeclarations) { + statements.push(ts.createVariableStatement(undefined, ts.createVariableDeclarationList(taggedTemplateStringDeclarations))); + } + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + exitSubtree(ancestorFacts, 0, 0); + return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements)); + } + function visitSwitchStatement(node) { + if (convertedLoopState !== undefined) { + var savedAllowedNonLabeledJumps = convertedLoopState.allowedNonLabeledJumps; + convertedLoopState.allowedNonLabeledJumps |= 2; + var result = ts.visitEachChild(node, visitor, context); + convertedLoopState.allowedNonLabeledJumps = savedAllowedNonLabeledJumps; + return result; + } + return ts.visitEachChild(node, visitor, context); + } + function visitCaseBlock(node) { + var ancestorFacts = enterSubtree(4032, 0); + var updated = ts.visitEachChild(node, visitor, context); + exitSubtree(ancestorFacts, 0, 0); + return updated; + } + function returnCapturedThis(node) { + return ts.setOriginalNode(ts.createReturn(ts.createFileLevelUniqueName("_this")), node); + } + function visitReturnStatement(node) { + if (convertedLoopState) { + convertedLoopState.nonLocalJumps |= 8; + if (isReturnVoidStatementInConstructorWithCapturedSuper(node)) { + node = returnCapturedThis(node); + } + return ts.createReturn(ts.createObjectLiteral([ + ts.createPropertyAssignment(ts.createIdentifier("value"), node.expression + ? ts.visitNode(node.expression, visitor, ts.isExpression) + : ts.createVoidZero()) + ])); + } + else if (isReturnVoidStatementInConstructorWithCapturedSuper(node)) { + return returnCapturedThis(node); + } + return ts.visitEachChild(node, visitor, context); + } + function visitThisKeyword(node) { + if (convertedLoopState) { + if (hierarchyFacts & 2) { + convertedLoopState.containsLexicalThis = true; + return node; + } + return convertedLoopState.thisName || (convertedLoopState.thisName = ts.createUniqueName("this")); + } + return node; + } + function visitIdentifier(node) { + if (!convertedLoopState) { + return node; + } + if (ts.isGeneratedIdentifier(node)) { + return node; + } + if (node.escapedText !== "arguments" || !resolver.isArgumentsLocalBinding(node)) { + return node; + } + return convertedLoopState.argumentsName || (convertedLoopState.argumentsName = ts.createUniqueName("arguments")); + } + function visitBreakOrContinueStatement(node) { + if (convertedLoopState) { + var jump = node.kind === 229 ? 2 : 4; + var canUseBreakOrContinue = (node.label && convertedLoopState.labels && convertedLoopState.labels.get(ts.idText(node.label))) || + (!node.label && (convertedLoopState.allowedNonLabeledJumps & jump)); + if (!canUseBreakOrContinue) { + var labelMarker = void 0; + var label = node.label; + if (!label) { + if (node.kind === 229) { + convertedLoopState.nonLocalJumps |= 2; + labelMarker = "break"; + } + else { + convertedLoopState.nonLocalJumps |= 4; + labelMarker = "continue"; + } + } + else { + if (node.kind === 229) { + labelMarker = "break-" + label.escapedText; + setLabeledJump(convertedLoopState, true, ts.idText(label), labelMarker); + } + else { + labelMarker = "continue-" + label.escapedText; + setLabeledJump(convertedLoopState, false, ts.idText(label), labelMarker); + } + } + var returnExpression = ts.createLiteral(labelMarker); + if (convertedLoopState.loopOutParameters.length) { + var outParams = convertedLoopState.loopOutParameters; + var expr = void 0; + for (var i = 0; i < outParams.length; i++) { + var copyExpr = copyOutParameter(outParams[i], 1); + if (i === 0) { + expr = copyExpr; + } + else { + expr = ts.createBinary(expr, 27, copyExpr); + } + } + returnExpression = ts.createBinary(expr, 27, returnExpression); + } + return ts.createReturn(returnExpression); + } + } + return ts.visitEachChild(node, visitor, context); + } + function visitClassDeclaration(node) { + var variable = ts.createVariableDeclaration(ts.getLocalName(node, true), undefined, transformClassLikeDeclarationToExpression(node)); + ts.setOriginalNode(variable, node); + var statements = []; + var statement = ts.createVariableStatement(undefined, ts.createVariableDeclarationList([variable])); + ts.setOriginalNode(statement, node); + ts.setTextRange(statement, node); + ts.startOnNewLine(statement); + statements.push(statement); + if (ts.hasModifier(node, 1)) { + var exportStatement = ts.hasModifier(node, 512) + ? ts.createExportDefault(ts.getLocalName(node)) + : ts.createExternalModuleExport(ts.getLocalName(node)); + ts.setOriginalNode(exportStatement, statement); + statements.push(exportStatement); + } + var emitFlags = ts.getEmitFlags(node); + if ((emitFlags & 4194304) === 0) { + statements.push(ts.createEndOfDeclarationMarker(node)); + ts.setEmitFlags(statement, emitFlags | 4194304); + } + return ts.singleOrMany(statements); + } + function visitClassExpression(node) { + return transformClassLikeDeclarationToExpression(node); + } + function transformClassLikeDeclarationToExpression(node) { + if (node.name) { + enableSubstitutionsForBlockScopedBindings(); + } + var extendsClauseElement = ts.getEffectiveBaseTypeNode(node); + var classFunction = ts.createFunctionExpression(undefined, undefined, undefined, undefined, extendsClauseElement ? [ts.createParameter(undefined, undefined, undefined, ts.createFileLevelUniqueName("_super"))] : [], undefined, transformClassBody(node, extendsClauseElement)); + ts.setEmitFlags(classFunction, (ts.getEmitFlags(node) & 65536) | 524288); + var inner = ts.createPartiallyEmittedExpression(classFunction); + inner.end = node.end; + ts.setEmitFlags(inner, 1536); + var outer = ts.createPartiallyEmittedExpression(inner); + outer.end = ts.skipTrivia(currentText, node.pos); + ts.setEmitFlags(outer, 1536); + var result = ts.createParen(ts.createCall(outer, undefined, extendsClauseElement + ? [ts.visitNode(extendsClauseElement.expression, visitor, ts.isExpression)] + : [])); + ts.addSyntheticLeadingComment(result, 3, "* @class "); + return result; + } + function transformClassBody(node, extendsClauseElement) { + var statements = []; + startLexicalEnvironment(); + addExtendsHelperIfNeeded(statements, node, extendsClauseElement); + addConstructor(statements, node, extendsClauseElement); + addClassMembers(statements, node); + var closingBraceLocation = ts.createTokenRange(ts.skipTrivia(currentText, node.members.end), 19); + var localName = ts.getInternalName(node); + var outer = ts.createPartiallyEmittedExpression(localName); + outer.end = closingBraceLocation.end; + ts.setEmitFlags(outer, 1536); + var statement = ts.createReturn(outer); + statement.pos = closingBraceLocation.pos; + ts.setEmitFlags(statement, 1536 | 384); + statements.push(statement); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), node.members), true); + ts.setEmitFlags(block, 1536); + return block; + } + function addExtendsHelperIfNeeded(statements, node, extendsClauseElement) { + if (extendsClauseElement) { + statements.push(ts.setTextRange(ts.createExpressionStatement(createExtendsHelper(context, ts.getInternalName(node))), extendsClauseElement)); + } + } + function addConstructor(statements, node, extendsClauseElement) { + var savedConvertedLoopState = convertedLoopState; + convertedLoopState = undefined; + var ancestorFacts = enterSubtree(16278, 73); + var constructor = ts.getFirstConstructorWithBody(node); + var hasSynthesizedSuper = hasSynthesizedDefaultSuperCall(constructor, extendsClauseElement !== undefined); + var constructorFunction = ts.createFunctionDeclaration(undefined, undefined, undefined, ts.getInternalName(node), undefined, transformConstructorParameters(constructor, hasSynthesizedSuper), undefined, transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper)); + ts.setTextRange(constructorFunction, constructor || node); + if (extendsClauseElement) { + ts.setEmitFlags(constructorFunction, 8); + } + statements.push(constructorFunction); + exitSubtree(ancestorFacts, 49152, 0); + convertedLoopState = savedConvertedLoopState; + } + function transformConstructorParameters(constructor, hasSynthesizedSuper) { + return ts.visitParameterList(constructor && !hasSynthesizedSuper ? constructor.parameters : undefined, visitor, context) + || []; + } + function transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper) { + var statements = []; + resumeLexicalEnvironment(); + var statementOffset = -1; + if (hasSynthesizedSuper) { + statementOffset = 0; + } + else if (constructor) { + statementOffset = ts.addStandardPrologue(statements, constructor.body.statements, false); + } + if (constructor) { + addDefaultValueAssignmentsIfNeeded(statements, constructor); + addRestParameterIfNeeded(statements, constructor, hasSynthesizedSuper); + if (!hasSynthesizedSuper) { + statementOffset = ts.addCustomPrologue(statements, constructor.body.statements, statementOffset, visitor); + } + ts.Debug.assert(statementOffset >= 0, "statementOffset not initialized correctly!"); + } + var isDerivedClass = !!extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 96; + var superCaptureStatus = declareOrCaptureOrReturnThisForConstructorIfNeeded(statements, constructor, isDerivedClass, hasSynthesizedSuper, statementOffset); + if (superCaptureStatus === 1 || superCaptureStatus === 2) { + statementOffset++; + } + if (constructor) { + if (superCaptureStatus === 1) { + hierarchyFacts |= 4096; + } + ts.addRange(statements, ts.visitNodes(constructor.body.statements, visitor, ts.isStatement, statementOffset)); + } + if (isDerivedClass + && superCaptureStatus !== 2 + && !(constructor && isSufficientlyCoveredByReturnStatements(constructor.body))) { + statements.push(ts.createReturn(ts.createFileLevelUniqueName("_this"))); + } + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + if (constructor) { + prependCaptureNewTargetIfNeeded(statements, constructor, false); + } + var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), constructor ? constructor.body.statements : node.members), true); + ts.setTextRange(block, constructor ? constructor.body : node); + if (!constructor) { + ts.setEmitFlags(block, 1536); + } + return block; + } + function isSufficientlyCoveredByReturnStatements(statement) { + if (statement.kind === 230) { + return true; + } + else if (statement.kind === 222) { + var ifStatement = statement; + if (ifStatement.elseStatement) { + return isSufficientlyCoveredByReturnStatements(ifStatement.thenStatement) && + isSufficientlyCoveredByReturnStatements(ifStatement.elseStatement); + } + } + else if (statement.kind === 218) { + var lastStatement = ts.lastOrUndefined(statement.statements); + if (lastStatement && isSufficientlyCoveredByReturnStatements(lastStatement)) { + return true; + } + } + return false; + } + function declareOrCaptureOrReturnThisForConstructorIfNeeded(statements, ctor, isDerivedClass, hasSynthesizedSuper, statementOffset) { + if (!isDerivedClass) { + if (ctor) { + addCaptureThisForNodeIfNeeded(statements, ctor); + } + return 0; + } + if (!ctor) { + statements.push(ts.createReturn(createDefaultSuperCallOrThis())); + return 2; + } + if (hasSynthesizedSuper) { + captureThisForNode(statements, ctor, createDefaultSuperCallOrThis()); + enableSubstitutionsForCapturedThis(); + return 1; + } + var firstStatement; + var superCallExpression; + var ctorStatements = ctor.body.statements; + if (statementOffset < ctorStatements.length) { + firstStatement = ctorStatements[statementOffset]; + if (firstStatement.kind === 221 && ts.isSuperCall(firstStatement.expression)) { + superCallExpression = visitImmediateSuperCallInBody(firstStatement.expression); + } + } + if (superCallExpression + && statementOffset === ctorStatements.length - 1 + && !(ctor.transformFlags & (8192 | 16384))) { + var returnStatement = ts.createReturn(superCallExpression); + if (superCallExpression.kind !== 204 + || superCallExpression.left.kind !== 191) { + ts.Debug.fail("Assumed generated super call would have form 'super.call(...) || this'."); + } + ts.setCommentRange(returnStatement, ts.getCommentRange(ts.setEmitFlags(superCallExpression.left, 1536))); + statements.push(returnStatement); + return 2; + } + captureThisForNode(statements, ctor, superCallExpression || createActualThis()); + if (superCallExpression) { + return 1; + } + return 0; + } + function createActualThis() { + return ts.setEmitFlags(ts.createThis(), 4); + } + function createDefaultSuperCallOrThis() { + return ts.createLogicalOr(ts.createLogicalAnd(ts.createStrictInequality(ts.createFileLevelUniqueName("_super"), ts.createNull()), ts.createFunctionApply(ts.createFileLevelUniqueName("_super"), createActualThis(), ts.createIdentifier("arguments"))), createActualThis()); + } + function visitParameter(node) { + if (node.dotDotDotToken) { + return undefined; + } + else if (ts.isBindingPattern(node.name)) { + return ts.setOriginalNode(ts.setTextRange(ts.createParameter(undefined, undefined, undefined, ts.getGeneratedNameForNode(node), undefined, undefined, undefined), node), node); + } + else if (node.initializer) { + return ts.setOriginalNode(ts.setTextRange(ts.createParameter(undefined, undefined, undefined, node.name, undefined, undefined, undefined), node), node); + } + else { + return node; + } + } + function shouldAddDefaultValueAssignments(node) { + return (node.transformFlags & 65536) !== 0; + } + function addDefaultValueAssignmentsIfNeeded(statements, node) { + if (!shouldAddDefaultValueAssignments(node)) { + return; + } + for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { + var parameter = _a[_i]; + var name = parameter.name, initializer = parameter.initializer, dotDotDotToken = parameter.dotDotDotToken; + if (dotDotDotToken) { + continue; + } + if (ts.isBindingPattern(name)) { + addDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer); + } + else if (initializer) { + addDefaultValueAssignmentForInitializer(statements, parameter, name, initializer); + } + } + } + function addDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer) { + var temp = ts.getGeneratedNameForNode(parameter); + if (name.elements.length > 0) { + statements.push(ts.setEmitFlags(ts.createVariableStatement(undefined, ts.createVariableDeclarationList(ts.flattenDestructuringBinding(parameter, visitor, context, 0, temp))), 1048576)); + } + else if (initializer) { + statements.push(ts.setEmitFlags(ts.createExpressionStatement(ts.createAssignment(temp, ts.visitNode(initializer, visitor, ts.isExpression))), 1048576)); + } + } + function addDefaultValueAssignmentForInitializer(statements, parameter, name, initializer) { + initializer = ts.visitNode(initializer, visitor, ts.isExpression); + var statement = ts.createIf(ts.createTypeCheck(ts.getSynthesizedClone(name), "undefined"), ts.setEmitFlags(ts.setTextRange(ts.createBlock([ + ts.createExpressionStatement(ts.setEmitFlags(ts.setTextRange(ts.createAssignment(ts.setEmitFlags(ts.getMutableClone(name), 48), ts.setEmitFlags(initializer, 48 | ts.getEmitFlags(initializer) | 1536)), parameter), 1536)) + ]), parameter), 1 | 32 | 384 | 1536)); + ts.startOnNewLine(statement); + ts.setTextRange(statement, parameter); + ts.setEmitFlags(statement, 384 | 32 | 1048576 | 1536); + statements.push(statement); + } + function shouldAddRestParameter(node, inConstructorWithSynthesizedSuper) { + return node && node.dotDotDotToken && node.name.kind === 72 && !inConstructorWithSynthesizedSuper; + } + function addRestParameterIfNeeded(statements, node, inConstructorWithSynthesizedSuper) { + var parameter = ts.lastOrUndefined(node.parameters); + if (!shouldAddRestParameter(parameter, inConstructorWithSynthesizedSuper)) { + return; + } + var declarationName = ts.getMutableClone(parameter.name); + ts.setEmitFlags(declarationName, 48); + var expressionName = ts.getSynthesizedClone(parameter.name); + var restIndex = node.parameters.length - 1; + var temp = ts.createLoopVariable(); + statements.push(ts.setEmitFlags(ts.setTextRange(ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(declarationName, undefined, ts.createArrayLiteral([])) + ])), parameter), 1048576)); + var forStatement = ts.createFor(ts.setTextRange(ts.createVariableDeclarationList([ + ts.createVariableDeclaration(temp, undefined, ts.createLiteral(restIndex)) + ]), parameter), ts.setTextRange(ts.createLessThan(temp, ts.createPropertyAccess(ts.createIdentifier("arguments"), "length")), parameter), ts.setTextRange(ts.createPostfixIncrement(temp), parameter), ts.createBlock([ + ts.startOnNewLine(ts.setTextRange(ts.createExpressionStatement(ts.createAssignment(ts.createElementAccess(expressionName, restIndex === 0 + ? temp + : ts.createSubtract(temp, ts.createLiteral(restIndex))), ts.createElementAccess(ts.createIdentifier("arguments"), temp))), parameter)) + ])); + ts.setEmitFlags(forStatement, 1048576); + ts.startOnNewLine(forStatement); + statements.push(forStatement); + } + function addCaptureThisForNodeIfNeeded(statements, node) { + if (node.transformFlags & 16384 && node.kind !== 197) { + captureThisForNode(statements, node, ts.createThis()); + } + } + function captureThisForNode(statements, node, initializer) { + enableSubstitutionsForCapturedThis(); + var captureThisStatement = ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(ts.createFileLevelUniqueName("_this"), undefined, initializer) + ])); + ts.setEmitFlags(captureThisStatement, 1536 | 1048576); + ts.setSourceMapRange(captureThisStatement, node); + statements.push(captureThisStatement); + } + function prependCaptureNewTargetIfNeeded(statements, node, copyOnWrite) { + if (hierarchyFacts & 16384) { + var newTarget = void 0; + switch (node.kind) { + case 197: + return statements; + case 156: + case 158: + case 159: + newTarget = ts.createVoidZero(); + break; + case 157: + newTarget = ts.createPropertyAccess(ts.setEmitFlags(ts.createThis(), 4), "constructor"); + break; + case 239: + case 196: + newTarget = ts.createConditional(ts.createLogicalAnd(ts.setEmitFlags(ts.createThis(), 4), ts.createBinary(ts.setEmitFlags(ts.createThis(), 4), 94, ts.getLocalName(node))), ts.createPropertyAccess(ts.setEmitFlags(ts.createThis(), 4), "constructor"), ts.createVoidZero()); + break; + default: + return ts.Debug.failBadSyntaxKind(node); + } + var captureNewTargetStatement = ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(ts.createFileLevelUniqueName("_newTarget"), undefined, newTarget) + ])); + if (copyOnWrite) { + return [captureNewTargetStatement].concat(statements); + } + statements.unshift(captureNewTargetStatement); + } + return statements; + } + function addClassMembers(statements, node) { + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + switch (member.kind) { + case 217: + statements.push(transformSemicolonClassElementToStatement(member)); + break; + case 156: + statements.push(transformClassMethodDeclarationToStatement(getClassMemberPrefix(node, member), member, node)); + break; + case 158: + case 159: + var accessors = ts.getAllAccessorDeclarations(node.members, member); + if (member === accessors.firstAccessor) { + statements.push(transformAccessorsToStatement(getClassMemberPrefix(node, member), accessors, node)); + } + break; + case 157: + break; + default: + ts.Debug.failBadSyntaxKind(node); + break; + } + } + } + function transformSemicolonClassElementToStatement(member) { + return ts.setTextRange(ts.createEmptyStatement(), member); + } + function transformClassMethodDeclarationToStatement(receiver, member, container) { + var ancestorFacts = enterSubtree(0, 0); + var commentRange = ts.getCommentRange(member); + var sourceMapRange = ts.getSourceMapRange(member); + var memberName = ts.createMemberAccessForPropertyName(receiver, ts.visitNode(member.name, visitor, ts.isPropertyName), member.name); + var memberFunction = transformFunctionLikeToExpression(member, member, undefined, container); + ts.setEmitFlags(memberFunction, 1536); + ts.setSourceMapRange(memberFunction, sourceMapRange); + var statement = ts.setTextRange(ts.createExpressionStatement(ts.createAssignment(memberName, memberFunction)), member); + ts.setOriginalNode(statement, member); + ts.setCommentRange(statement, commentRange); + ts.setEmitFlags(statement, 48); + exitSubtree(ancestorFacts, 49152, hierarchyFacts & 49152 ? 16384 : 0); + return statement; + } + function transformAccessorsToStatement(receiver, accessors, container) { + var statement = ts.createExpressionStatement(transformAccessorsToExpression(receiver, accessors, container, false)); + ts.setEmitFlags(statement, 1536); + ts.setSourceMapRange(statement, ts.getSourceMapRange(accessors.firstAccessor)); + return statement; + } + function transformAccessorsToExpression(receiver, _a, container, startsOnNewLine) { + var firstAccessor = _a.firstAccessor, getAccessor = _a.getAccessor, setAccessor = _a.setAccessor; + var ancestorFacts = enterSubtree(0, 0); + var target = ts.getMutableClone(receiver); + ts.setEmitFlags(target, 1536 | 32); + ts.setSourceMapRange(target, firstAccessor.name); + var propertyName = ts.createExpressionForPropertyName(ts.visitNode(firstAccessor.name, visitor, ts.isPropertyName)); + ts.setEmitFlags(propertyName, 1536 | 16); + ts.setSourceMapRange(propertyName, firstAccessor.name); + var properties = []; + if (getAccessor) { + var getterFunction = transformFunctionLikeToExpression(getAccessor, undefined, undefined, container); + ts.setSourceMapRange(getterFunction, ts.getSourceMapRange(getAccessor)); + ts.setEmitFlags(getterFunction, 512); + var getter = ts.createPropertyAssignment("get", getterFunction); + ts.setCommentRange(getter, ts.getCommentRange(getAccessor)); + properties.push(getter); + } + if (setAccessor) { + var setterFunction = transformFunctionLikeToExpression(setAccessor, undefined, undefined, container); + ts.setSourceMapRange(setterFunction, ts.getSourceMapRange(setAccessor)); + ts.setEmitFlags(setterFunction, 512); + var setter = ts.createPropertyAssignment("set", setterFunction); + ts.setCommentRange(setter, ts.getCommentRange(setAccessor)); + properties.push(setter); + } + properties.push(ts.createPropertyAssignment("enumerable", ts.createTrue()), ts.createPropertyAssignment("configurable", ts.createTrue())); + var call = ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"), undefined, [ + target, + propertyName, + ts.createObjectLiteral(properties, true) + ]); + if (startsOnNewLine) { + ts.startOnNewLine(call); + } + exitSubtree(ancestorFacts, 49152, hierarchyFacts & 49152 ? 16384 : 0); + return call; + } + function visitArrowFunction(node) { + if (node.transformFlags & 8192) { + enableSubstitutionsForCapturedThis(); + } + var savedConvertedLoopState = convertedLoopState; + convertedLoopState = undefined; + var ancestorFacts = enterSubtree(16256, 66); + var func = ts.createFunctionExpression(undefined, undefined, undefined, undefined, ts.visitParameterList(node.parameters, visitor, context), undefined, transformFunctionBody(node)); + ts.setTextRange(func, node); + ts.setOriginalNode(func, node); + ts.setEmitFlags(func, 8); + exitSubtree(ancestorFacts, 0, 0); + convertedLoopState = savedConvertedLoopState; + return func; + } + function visitFunctionExpression(node) { + var ancestorFacts = ts.getEmitFlags(node) & 262144 + ? enterSubtree(16278, 69) + : enterSubtree(16286, 65); + var savedConvertedLoopState = convertedLoopState; + convertedLoopState = undefined; + var parameters = ts.visitParameterList(node.parameters, visitor, context); + var body = node.transformFlags & 64 + ? transformFunctionBody(node) + : visitFunctionBodyDownLevel(node); + var name = hierarchyFacts & 16384 + ? ts.getLocalName(node) + : node.name; + exitSubtree(ancestorFacts, 49152, 0); + convertedLoopState = savedConvertedLoopState; + return ts.updateFunctionExpression(node, undefined, node.asteriskToken, name, undefined, parameters, undefined, body); + } + function visitFunctionDeclaration(node) { + var savedConvertedLoopState = convertedLoopState; + convertedLoopState = undefined; + var ancestorFacts = enterSubtree(16286, 65); + var parameters = ts.visitParameterList(node.parameters, visitor, context); + var body = node.transformFlags & 64 + ? transformFunctionBody(node) + : visitFunctionBodyDownLevel(node); + var name = hierarchyFacts & 16384 + ? ts.getLocalName(node) + : node.name; + exitSubtree(ancestorFacts, 49152, 0); + convertedLoopState = savedConvertedLoopState; + return ts.updateFunctionDeclaration(node, undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, name, undefined, parameters, undefined, body); + } + function transformFunctionLikeToExpression(node, location, name, container) { + var savedConvertedLoopState = convertedLoopState; + convertedLoopState = undefined; + var ancestorFacts = container && ts.isClassLike(container) && !ts.hasModifier(node, 32) + ? enterSubtree(16286, 65 | 8) + : enterSubtree(16286, 65); + var parameters = ts.visitParameterList(node.parameters, visitor, context); + var body = transformFunctionBody(node); + if (hierarchyFacts & 16384 && !name && (node.kind === 239 || node.kind === 196)) { + name = ts.getGeneratedNameForNode(node); + } + exitSubtree(ancestorFacts, 49152, 0); + convertedLoopState = savedConvertedLoopState; + return ts.setOriginalNode(ts.setTextRange(ts.createFunctionExpression(undefined, node.asteriskToken, name, undefined, parameters, undefined, body), location), node); + } + function transformFunctionBody(node) { + var multiLine = false; + var singleLine = false; + var statementsLocation; + var closeBraceLocation; + var leadingStatements = []; + var statements = []; + var body = node.body; + var statementOffset; + resumeLexicalEnvironment(); + if (ts.isBlock(body)) { + statementOffset = ts.addStandardPrologue(leadingStatements, body.statements, false); + } + addCaptureThisForNodeIfNeeded(leadingStatements, node); + addDefaultValueAssignmentsIfNeeded(leadingStatements, node); + addRestParameterIfNeeded(leadingStatements, node, false); + if (ts.isBlock(body)) { + statementOffset = ts.addCustomPrologue(leadingStatements, body.statements, statementOffset, visitor); + statementsLocation = body.statements; + ts.addRange(statements, ts.visitNodes(body.statements, visitor, ts.isStatement, statementOffset)); + if (!multiLine && body.multiLine) { + multiLine = true; + } + } + else { + ts.Debug.assert(node.kind === 197); + statementsLocation = ts.moveRangeEnd(body, -1); + var equalsGreaterThanToken = node.equalsGreaterThanToken; + if (!ts.nodeIsSynthesized(equalsGreaterThanToken) && !ts.nodeIsSynthesized(body)) { + if (ts.rangeEndIsOnSameLineAsRangeStart(equalsGreaterThanToken, body, currentSourceFile)) { + singleLine = true; + } + else { + multiLine = true; + } + } + var expression = ts.visitNode(body, visitor, ts.isExpression); + var returnStatement = ts.createReturn(expression); + ts.setTextRange(returnStatement, body); + ts.moveSyntheticComments(returnStatement, body); + ts.setEmitFlags(returnStatement, 384 | 32 | 1024); + statements.push(returnStatement); + closeBraceLocation = body; + } + var lexicalEnvironment = context.endLexicalEnvironment(); + ts.addStatementsAfterPrologue(statements, lexicalEnvironment); + prependCaptureNewTargetIfNeeded(statements, node, false); + if (ts.some(leadingStatements) || ts.some(lexicalEnvironment)) { + multiLine = true; + } + var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(leadingStatements.concat(statements)), statementsLocation), multiLine); + ts.setTextRange(block, node.body); + if (!multiLine && singleLine) { + ts.setEmitFlags(block, 1); + } + if (closeBraceLocation) { + ts.setTokenSourceMapRange(block, 19, closeBraceLocation); + } + ts.setOriginalNode(block, node.body); + return block; + } + function visitFunctionBodyDownLevel(node) { + var updated = ts.visitFunctionBody(node.body, functionBodyVisitor, context); + return ts.updateBlock(updated, ts.setTextRange(ts.createNodeArray(prependCaptureNewTargetIfNeeded(updated.statements, node, true)), updated.statements)); + } + function visitBlock(node, isFunctionBody) { + if (isFunctionBody) { + return ts.visitEachChild(node, visitor, context); + } + var ancestorFacts = hierarchyFacts & 256 + ? enterSubtree(4032, 512) + : enterSubtree(3904, 128); + var updated = ts.visitEachChild(node, visitor, context); + exitSubtree(ancestorFacts, 0, 0); + return updated; + } + function visitExpressionStatement(node) { + switch (node.expression.kind) { + case 195: + return ts.updateExpressionStatement(node, visitParenthesizedExpression(node.expression, false)); + case 204: + return ts.updateExpressionStatement(node, visitBinaryExpression(node.expression, false)); + } + return ts.visitEachChild(node, visitor, context); + } + function visitParenthesizedExpression(node, needsDestructuringValue) { + if (!needsDestructuringValue) { + switch (node.expression.kind) { + case 195: + return ts.updateParen(node, visitParenthesizedExpression(node.expression, false)); + case 204: + return ts.updateParen(node, visitBinaryExpression(node.expression, false)); + } + } + return ts.visitEachChild(node, visitor, context); + } + function visitBinaryExpression(node, needsDestructuringValue) { + if (ts.isDestructuringAssignment(node)) { + return ts.flattenDestructuringAssignment(node, visitor, context, 0, needsDestructuringValue); + } + return ts.visitEachChild(node, visitor, context); + } + function visitVariableStatement(node) { + var ancestorFacts = enterSubtree(0, ts.hasModifier(node, 1) ? 32 : 0); + var updated; + if (convertedLoopState && (node.declarationList.flags & 3) === 0) { + var assignments = void 0; + for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + hoistVariableDeclarationDeclaredInConvertedLoop(convertedLoopState, decl); + if (decl.initializer) { + var assignment = void 0; + if (ts.isBindingPattern(decl.name)) { + assignment = ts.flattenDestructuringAssignment(decl, visitor, context, 0); + } + else { + assignment = ts.createBinary(decl.name, 59, ts.visitNode(decl.initializer, visitor, ts.isExpression)); + ts.setTextRange(assignment, decl); + } + assignments = ts.append(assignments, assignment); + } + } + if (assignments) { + updated = ts.setTextRange(ts.createExpressionStatement(ts.inlineExpressions(assignments)), node); + } + else { + updated = undefined; + } + } + else { + updated = ts.visitEachChild(node, visitor, context); + } + exitSubtree(ancestorFacts, 0, 0); + return updated; + } + function visitVariableDeclarationList(node) { + if (node.transformFlags & 64) { + if (node.flags & 3) { + enableSubstitutionsForBlockScopedBindings(); + } + var declarations = ts.flatMap(node.declarations, node.flags & 1 + ? visitVariableDeclarationInLetDeclarationList + : visitVariableDeclaration); + var declarationList = ts.createVariableDeclarationList(declarations); + ts.setOriginalNode(declarationList, node); + ts.setTextRange(declarationList, node); + ts.setCommentRange(declarationList, node); + if (node.transformFlags & 2097152 + && (ts.isBindingPattern(node.declarations[0].name) || ts.isBindingPattern(ts.last(node.declarations).name))) { + ts.setSourceMapRange(declarationList, getRangeUnion(declarations)); + } + return declarationList; + } + return ts.visitEachChild(node, visitor, context); + } + function getRangeUnion(declarations) { + var pos = -1, end = -1; + for (var _i = 0, declarations_10 = declarations; _i < declarations_10.length; _i++) { + var node = declarations_10[_i]; + pos = pos === -1 ? node.pos : node.pos === -1 ? pos : Math.min(pos, node.pos); + end = Math.max(end, node.end); + } + return ts.createRange(pos, end); + } + function shouldEmitExplicitInitializerForLetDeclaration(node) { + var flags = resolver.getNodeCheckFlags(node); + var isCapturedInFunction = flags & 262144; + var isDeclaredInLoop = flags & 524288; + var emittedAsTopLevel = (hierarchyFacts & 64) !== 0 + || (isCapturedInFunction + && isDeclaredInLoop + && (hierarchyFacts & 512) !== 0); + var emitExplicitInitializer = !emittedAsTopLevel + && (hierarchyFacts & 2048) === 0 + && (!resolver.isDeclarationWithCollidingName(node) + || (isDeclaredInLoop + && !isCapturedInFunction + && (hierarchyFacts & (1024 | 2048)) === 0)); + return emitExplicitInitializer; + } + function visitVariableDeclarationInLetDeclarationList(node) { + var name = node.name; + if (ts.isBindingPattern(name)) { + return visitVariableDeclaration(node); + } + if (!node.initializer && shouldEmitExplicitInitializerForLetDeclaration(node)) { + var clone_2 = ts.getMutableClone(node); + clone_2.initializer = ts.createVoidZero(); + return clone_2; + } + return ts.visitEachChild(node, visitor, context); + } + function visitVariableDeclaration(node) { + var ancestorFacts = enterSubtree(32, 0); + var updated; + if (ts.isBindingPattern(node.name)) { + updated = ts.flattenDestructuringBinding(node, visitor, context, 0, undefined, (ancestorFacts & 32) !== 0); + } + else { + updated = ts.visitEachChild(node, visitor, context); + } + exitSubtree(ancestorFacts, 0, 0); + return updated; + } + function recordLabel(node) { + convertedLoopState.labels.set(ts.idText(node.label), true); + } + function resetLabel(node) { + convertedLoopState.labels.set(ts.idText(node.label), false); + } + function visitLabeledStatement(node) { + if (convertedLoopState && !convertedLoopState.labels) { + convertedLoopState.labels = ts.createMap(); + } + var statement = ts.unwrapInnermostStatementOfLabel(node, convertedLoopState && recordLabel); + return ts.isIterationStatement(statement, false) + ? visitIterationStatement(statement, node) + : ts.restoreEnclosingLabel(ts.visitNode(statement, visitor, ts.isStatement, ts.liftToBlock), node, convertedLoopState && resetLabel); + } + function visitIterationStatement(node, outermostLabeledStatement) { + switch (node.kind) { + case 223: + case 224: + return visitDoOrWhileStatement(node, outermostLabeledStatement); + case 225: + return visitForStatement(node, outermostLabeledStatement); + case 226: + return visitForInStatement(node, outermostLabeledStatement); + case 227: + return visitForOfStatement(node, outermostLabeledStatement); + } + } + function visitIterationStatementWithFacts(excludeFacts, includeFacts, node, outermostLabeledStatement, convert) { + var ancestorFacts = enterSubtree(excludeFacts, includeFacts); + var updated = convertIterationStatementBodyIfNecessary(node, outermostLabeledStatement, convert); + exitSubtree(ancestorFacts, 0, 0); + return updated; + } + function visitDoOrWhileStatement(node, outermostLabeledStatement) { + return visitIterationStatementWithFacts(0, 256, node, outermostLabeledStatement); + } + function visitForStatement(node, outermostLabeledStatement) { + return visitIterationStatementWithFacts(3008, 1280, node, outermostLabeledStatement); + } + function visitForInStatement(node, outermostLabeledStatement) { + return visitIterationStatementWithFacts(1984, 2304, node, outermostLabeledStatement); + } + function visitForOfStatement(node, outermostLabeledStatement) { + return visitIterationStatementWithFacts(1984, 2304, node, outermostLabeledStatement, compilerOptions.downlevelIteration ? convertForOfStatementForIterable : convertForOfStatementForArray); + } + function convertForOfStatementHead(node, boundValue, convertedLoopBodyStatements) { + var statements = []; + var initializer = node.initializer; + if (ts.isVariableDeclarationList(initializer)) { + if (node.initializer.flags & 3) { + enableSubstitutionsForBlockScopedBindings(); + } + var firstOriginalDeclaration = ts.firstOrUndefined(initializer.declarations); + if (firstOriginalDeclaration && ts.isBindingPattern(firstOriginalDeclaration.name)) { + var declarations = ts.flattenDestructuringBinding(firstOriginalDeclaration, visitor, context, 0, boundValue); + var declarationList = ts.setTextRange(ts.createVariableDeclarationList(declarations), node.initializer); + ts.setOriginalNode(declarationList, node.initializer); + ts.setSourceMapRange(declarationList, ts.createRange(declarations[0].pos, ts.last(declarations).end)); + statements.push(ts.createVariableStatement(undefined, declarationList)); + } + else { + statements.push(ts.setTextRange(ts.createVariableStatement(undefined, ts.setOriginalNode(ts.setTextRange(ts.createVariableDeclarationList([ + ts.createVariableDeclaration(firstOriginalDeclaration ? firstOriginalDeclaration.name : ts.createTempVariable(undefined), undefined, boundValue) + ]), ts.moveRangePos(initializer, -1)), initializer)), ts.moveRangeEnd(initializer, -1))); + } + } + else { + var assignment = ts.createAssignment(initializer, boundValue); + if (ts.isDestructuringAssignment(assignment)) { + ts.aggregateTransformFlags(assignment); + statements.push(ts.createExpressionStatement(visitBinaryExpression(assignment, false))); + } + else { + assignment.end = initializer.end; + statements.push(ts.setTextRange(ts.createExpressionStatement(ts.visitNode(assignment, visitor, ts.isExpression)), ts.moveRangeEnd(initializer, -1))); + } + } + if (convertedLoopBodyStatements) { + return createSyntheticBlockForConvertedStatements(ts.addRange(statements, convertedLoopBodyStatements)); + } + else { + var statement = ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock); + if (ts.isBlock(statement)) { + return ts.updateBlock(statement, ts.setTextRange(ts.createNodeArray(ts.concatenate(statements, statement.statements)), statement.statements)); + } + else { + statements.push(statement); + return createSyntheticBlockForConvertedStatements(statements); + } + } + } + function createSyntheticBlockForConvertedStatements(statements) { + return ts.setEmitFlags(ts.createBlock(ts.createNodeArray(statements), true), 48 | 384); + } + function convertForOfStatementForArray(node, outermostLabeledStatement, convertedLoopBodyStatements) { + var expression = ts.visitNode(node.expression, visitor, ts.isExpression); + var counter = ts.createLoopVariable(); + var rhsReference = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(expression) : ts.createTempVariable(undefined); + ts.setEmitFlags(expression, 48 | ts.getEmitFlags(expression)); + var forStatement = ts.setTextRange(ts.createFor(ts.setEmitFlags(ts.setTextRange(ts.createVariableDeclarationList([ + ts.setTextRange(ts.createVariableDeclaration(counter, undefined, ts.createLiteral(0)), ts.moveRangePos(node.expression, -1)), + ts.setTextRange(ts.createVariableDeclaration(rhsReference, undefined, expression), node.expression) + ]), node.expression), 2097152), ts.setTextRange(ts.createLessThan(counter, ts.createPropertyAccess(rhsReference, "length")), node.expression), ts.setTextRange(ts.createPostfixIncrement(counter), node.expression), convertForOfStatementHead(node, ts.createElementAccess(rhsReference, counter), convertedLoopBodyStatements)), node); + ts.setEmitFlags(forStatement, 256); + ts.setTextRange(forStatement, node); + return ts.restoreEnclosingLabel(forStatement, outermostLabeledStatement, convertedLoopState && resetLabel); + } + function convertForOfStatementForIterable(node, outermostLabeledStatement, convertedLoopBodyStatements) { + var expression = ts.visitNode(node.expression, visitor, ts.isExpression); + var iterator = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(expression) : ts.createTempVariable(undefined); + var result = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(iterator) : ts.createTempVariable(undefined); + var errorRecord = ts.createUniqueName("e"); + var catchVariable = ts.getGeneratedNameForNode(errorRecord); + var returnMethod = ts.createTempVariable(undefined); + var values = ts.createValuesHelper(context, expression, node.expression); + var next = ts.createCall(ts.createPropertyAccess(iterator, "next"), undefined, []); + hoistVariableDeclaration(errorRecord); + hoistVariableDeclaration(returnMethod); + var forStatement = ts.setEmitFlags(ts.setTextRange(ts.createFor(ts.setEmitFlags(ts.setTextRange(ts.createVariableDeclarationList([ + ts.setTextRange(ts.createVariableDeclaration(iterator, undefined, values), node.expression), + ts.createVariableDeclaration(result, undefined, next) + ]), node.expression), 2097152), ts.createLogicalNot(ts.createPropertyAccess(result, "done")), ts.createAssignment(result, next), convertForOfStatementHead(node, ts.createPropertyAccess(result, "value"), convertedLoopBodyStatements)), node), 256); + return ts.createTry(ts.createBlock([ + ts.restoreEnclosingLabel(forStatement, outermostLabeledStatement, convertedLoopState && resetLabel) + ]), ts.createCatchClause(ts.createVariableDeclaration(catchVariable), ts.setEmitFlags(ts.createBlock([ + ts.createExpressionStatement(ts.createAssignment(errorRecord, ts.createObjectLiteral([ + ts.createPropertyAssignment("error", catchVariable) + ]))) + ]), 1)), ts.createBlock([ + ts.createTry(ts.createBlock([ + ts.setEmitFlags(ts.createIf(ts.createLogicalAnd(ts.createLogicalAnd(result, ts.createLogicalNot(ts.createPropertyAccess(result, "done"))), ts.createAssignment(returnMethod, ts.createPropertyAccess(iterator, "return"))), ts.createExpressionStatement(ts.createFunctionCall(returnMethod, iterator, []))), 1), + ]), undefined, ts.setEmitFlags(ts.createBlock([ + ts.setEmitFlags(ts.createIf(errorRecord, ts.createThrow(ts.createPropertyAccess(errorRecord, "error"))), 1) + ]), 1)) + ])); + } + function visitObjectLiteralExpression(node) { + var properties = node.properties; + var numProperties = properties.length; + var numInitialProperties = numProperties; + var numInitialPropertiesWithoutYield = numProperties; + for (var i = 0; i < numProperties; i++) { + var property = properties[i]; + if ((property.transformFlags & 4194304 && hierarchyFacts & 4) + && i < numInitialPropertiesWithoutYield) { + numInitialPropertiesWithoutYield = i; + } + if (property.name.kind === 149) { + numInitialProperties = i; + break; + } + } + if (numInitialProperties !== numProperties) { + if (numInitialPropertiesWithoutYield < numInitialProperties) { + numInitialProperties = numInitialPropertiesWithoutYield; + } + var temp = ts.createTempVariable(hoistVariableDeclaration); + var expressions = []; + var assignment = ts.createAssignment(temp, ts.setEmitFlags(ts.createObjectLiteral(ts.visitNodes(properties, visitor, ts.isObjectLiteralElementLike, 0, numInitialProperties), node.multiLine), 65536)); + if (node.multiLine) { + ts.startOnNewLine(assignment); + } + expressions.push(assignment); + addObjectLiteralMembers(expressions, node, temp, numInitialProperties); + expressions.push(node.multiLine ? ts.startOnNewLine(ts.getMutableClone(temp)) : temp); + return ts.inlineExpressions(expressions); + } + return ts.visitEachChild(node, visitor, context); + } + function shouldConvertPartOfIterationStatement(node) { + return (resolver.getNodeCheckFlags(node) & 131072) !== 0; + } + function shouldConvertInitializerOfForStatement(node) { + return ts.isForStatement(node) && !!node.initializer && shouldConvertPartOfIterationStatement(node.initializer); + } + function shouldConvertConditionOfForStatement(node) { + return ts.isForStatement(node) && !!node.condition && shouldConvertPartOfIterationStatement(node.condition); + } + function shouldConvertIncrementorOfForStatement(node) { + return ts.isForStatement(node) && !!node.incrementor && shouldConvertPartOfIterationStatement(node.incrementor); + } + function shouldConvertIterationStatement(node) { + return shouldConvertBodyOfIterationStatement(node) + || shouldConvertInitializerOfForStatement(node); + } + function shouldConvertBodyOfIterationStatement(node) { + return (resolver.getNodeCheckFlags(node) & 65536) !== 0; + } + function hoistVariableDeclarationDeclaredInConvertedLoop(state, node) { + if (!state.hoistedLocalVariables) { + state.hoistedLocalVariables = []; + } + visit(node.name); + function visit(node) { + if (node.kind === 72) { + state.hoistedLocalVariables.push(node); + } + else { + for (var _i = 0, _a = node.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (!ts.isOmittedExpression(element)) { + visit(element.name); + } + } + } + } + } + function convertIterationStatementBodyIfNecessary(node, outermostLabeledStatement, convert) { + if (!shouldConvertIterationStatement(node)) { + var saveAllowedNonLabeledJumps = void 0; + if (convertedLoopState) { + saveAllowedNonLabeledJumps = convertedLoopState.allowedNonLabeledJumps; + convertedLoopState.allowedNonLabeledJumps = 2 | 4; + } + var result = convert + ? convert(node, outermostLabeledStatement, undefined) + : ts.restoreEnclosingLabel(ts.visitEachChild(node, visitor, context), outermostLabeledStatement, convertedLoopState && resetLabel); + if (convertedLoopState) { + convertedLoopState.allowedNonLabeledJumps = saveAllowedNonLabeledJumps; + } + return result; + } + var currentState = createConvertedLoopState(node); + var statements = []; + var outerConvertedLoopState = convertedLoopState; + convertedLoopState = currentState; + var initializerFunction = shouldConvertInitializerOfForStatement(node) ? createFunctionForInitializerOfForStatement(node, currentState) : undefined; + var bodyFunction = shouldConvertBodyOfIterationStatement(node) ? createFunctionForBodyOfIterationStatement(node, currentState, outerConvertedLoopState) : undefined; + convertedLoopState = outerConvertedLoopState; + if (initializerFunction) + statements.push(initializerFunction.functionDeclaration); + if (bodyFunction) + statements.push(bodyFunction.functionDeclaration); + addExtraDeclarationsForConvertedLoop(statements, currentState, outerConvertedLoopState); + if (initializerFunction) { + statements.push(generateCallToConvertedLoopInitializer(initializerFunction.functionName, initializerFunction.containsYield)); + } + var loop; + if (bodyFunction) { + if (convert) { + loop = convert(node, outermostLabeledStatement, bodyFunction.part); + } + else { + var clone_3 = convertIterationStatementCore(node, initializerFunction, ts.createBlock(bodyFunction.part, true)); + ts.aggregateTransformFlags(clone_3); + loop = ts.restoreEnclosingLabel(clone_3, outermostLabeledStatement, convertedLoopState && resetLabel); + } + } + else { + var clone_4 = convertIterationStatementCore(node, initializerFunction, ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); + ts.aggregateTransformFlags(clone_4); + loop = ts.restoreEnclosingLabel(clone_4, outermostLabeledStatement, convertedLoopState && resetLabel); + } + statements.push(loop); + return statements; + } + function convertIterationStatementCore(node, initializerFunction, convertedLoopBody) { + switch (node.kind) { + case 225: return convertForStatement(node, initializerFunction, convertedLoopBody); + case 226: return convertForInStatement(node, convertedLoopBody); + case 227: return convertForOfStatement(node, convertedLoopBody); + case 223: return convertDoStatement(node, convertedLoopBody); + case 224: return convertWhileStatement(node, convertedLoopBody); + default: return ts.Debug.failBadSyntaxKind(node, "IterationStatement expected"); + } + } + function convertForStatement(node, initializerFunction, convertedLoopBody) { + var shouldConvertCondition = node.condition && shouldConvertPartOfIterationStatement(node.condition); + var shouldConvertIncrementor = shouldConvertCondition || node.incrementor && shouldConvertPartOfIterationStatement(node.incrementor); + return ts.updateFor(node, ts.visitNode(initializerFunction ? initializerFunction.part : node.initializer, visitor, ts.isForInitializer), ts.visitNode(shouldConvertCondition ? undefined : node.condition, visitor, ts.isExpression), ts.visitNode(shouldConvertIncrementor ? undefined : node.incrementor, visitor, ts.isExpression), convertedLoopBody); + } + function convertForOfStatement(node, convertedLoopBody) { + return ts.updateForOf(node, undefined, ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), convertedLoopBody); + } + function convertForInStatement(node, convertedLoopBody) { + return ts.updateForIn(node, ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), convertedLoopBody); + } + function convertDoStatement(node, convertedLoopBody) { + return ts.updateDo(node, convertedLoopBody, ts.visitNode(node.expression, visitor, ts.isExpression)); + } + function convertWhileStatement(node, convertedLoopBody) { + return ts.updateWhile(node, ts.visitNode(node.expression, visitor, ts.isExpression), convertedLoopBody); + } + function createConvertedLoopState(node) { + var loopInitializer; + switch (node.kind) { + case 225: + case 226: + case 227: + var initializer = node.initializer; + if (initializer && initializer.kind === 238) { + loopInitializer = initializer; + } + break; + } + var loopParameters = []; + var loopOutParameters = []; + if (loopInitializer && (ts.getCombinedNodeFlags(loopInitializer) & 3)) { + var hasCapturedBindingsInForInitializer = shouldConvertInitializerOfForStatement(node); + for (var _i = 0, _a = loopInitializer.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + processLoopVariableDeclaration(node, decl, loopParameters, loopOutParameters, hasCapturedBindingsInForInitializer); + } + } + var currentState = { loopParameters: loopParameters, loopOutParameters: loopOutParameters }; + if (convertedLoopState) { + if (convertedLoopState.argumentsName) { + currentState.argumentsName = convertedLoopState.argumentsName; + } + if (convertedLoopState.thisName) { + currentState.thisName = convertedLoopState.thisName; + } + if (convertedLoopState.hoistedLocalVariables) { + currentState.hoistedLocalVariables = convertedLoopState.hoistedLocalVariables; + } + } + return currentState; + } + function addExtraDeclarationsForConvertedLoop(statements, state, outerState) { + var extraVariableDeclarations; + if (state.argumentsName) { + if (outerState) { + outerState.argumentsName = state.argumentsName; + } + else { + (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(state.argumentsName, undefined, ts.createIdentifier("arguments"))); + } + } + if (state.thisName) { + if (outerState) { + outerState.thisName = state.thisName; + } + else { + (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(state.thisName, undefined, ts.createIdentifier("this"))); + } + } + if (state.hoistedLocalVariables) { + if (outerState) { + outerState.hoistedLocalVariables = state.hoistedLocalVariables; + } + else { + if (!extraVariableDeclarations) { + extraVariableDeclarations = []; + } + for (var _i = 0, _a = state.hoistedLocalVariables; _i < _a.length; _i++) { + var identifier = _a[_i]; + extraVariableDeclarations.push(ts.createVariableDeclaration(identifier)); + } + } + } + if (state.loopOutParameters.length) { + if (!extraVariableDeclarations) { + extraVariableDeclarations = []; + } + for (var _b = 0, _c = state.loopOutParameters; _b < _c.length; _b++) { + var outParam = _c[_b]; + extraVariableDeclarations.push(ts.createVariableDeclaration(outParam.outParamName)); + } + } + if (state.conditionVariable) { + if (!extraVariableDeclarations) { + extraVariableDeclarations = []; + } + extraVariableDeclarations.push(ts.createVariableDeclaration(state.conditionVariable, undefined, ts.createFalse())); + } + if (extraVariableDeclarations) { + statements.push(ts.createVariableStatement(undefined, ts.createVariableDeclarationList(extraVariableDeclarations))); + } + } + function createOutVariable(p) { + return ts.createVariableDeclaration(p.originalName, undefined, p.outParamName); + } + function createFunctionForInitializerOfForStatement(node, currentState) { + var functionName = ts.createUniqueName("_loop_init"); + var containsYield = (node.initializer.transformFlags & 4194304) !== 0; + var emitFlags = 0; + if (currentState.containsLexicalThis) + emitFlags |= 8; + if (containsYield && hierarchyFacts & 4) + emitFlags |= 262144; + var statements = []; + statements.push(ts.createVariableStatement(undefined, node.initializer)); + copyOutParameters(currentState.loopOutParameters, 2, 1, statements); + var functionDeclaration = ts.createVariableStatement(undefined, ts.setEmitFlags(ts.createVariableDeclarationList([ + ts.createVariableDeclaration(functionName, undefined, ts.setEmitFlags(ts.createFunctionExpression(undefined, containsYield ? ts.createToken(40) : undefined, undefined, undefined, undefined, undefined, ts.visitNode(ts.createBlock(statements, true), visitor, ts.isBlock)), emitFlags)) + ]), 2097152)); + var part = ts.createVariableDeclarationList(ts.map(currentState.loopOutParameters, createOutVariable)); + return { functionName: functionName, containsYield: containsYield, functionDeclaration: functionDeclaration, part: part }; + } + function createFunctionForBodyOfIterationStatement(node, currentState, outerState) { + var functionName = ts.createUniqueName("_loop"); + startLexicalEnvironment(); + var statement = ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock); + var lexicalEnvironment = endLexicalEnvironment(); + var statements = []; + if (shouldConvertConditionOfForStatement(node) || shouldConvertIncrementorOfForStatement(node)) { + currentState.conditionVariable = ts.createUniqueName("inc"); + statements.push(ts.createIf(currentState.conditionVariable, ts.createStatement(ts.visitNode(node.incrementor, visitor, ts.isExpression)), ts.createStatement(ts.createAssignment(currentState.conditionVariable, ts.createTrue())))); + if (shouldConvertConditionOfForStatement(node)) { + statements.push(ts.createIf(ts.createPrefix(52, ts.visitNode(node.condition, visitor, ts.isExpression)), ts.visitNode(ts.createBreak(), visitor, ts.isStatement))); + } + } + if (ts.isBlock(statement)) { + ts.addRange(statements, statement.statements); + } + else { + statements.push(statement); + } + copyOutParameters(currentState.loopOutParameters, 1, 1, statements); + ts.addStatementsAfterPrologue(statements, lexicalEnvironment); + var loopBody = ts.createBlock(statements, true); + if (ts.isBlock(statement)) + ts.setOriginalNode(loopBody, statement); + var containsYield = (node.statement.transformFlags & 4194304) !== 0; + var emitFlags = 0; + if (currentState.containsLexicalThis) + emitFlags |= 8; + if (containsYield && (hierarchyFacts & 4) !== 0) + emitFlags |= 262144; + var functionDeclaration = ts.createVariableStatement(undefined, ts.setEmitFlags(ts.createVariableDeclarationList([ + ts.createVariableDeclaration(functionName, undefined, ts.setEmitFlags(ts.createFunctionExpression(undefined, containsYield ? ts.createToken(40) : undefined, undefined, undefined, currentState.loopParameters, undefined, loopBody), emitFlags)) + ]), 2097152)); + var part = generateCallToConvertedLoop(functionName, currentState, outerState, containsYield); + return { functionName: functionName, containsYield: containsYield, functionDeclaration: functionDeclaration, part: part }; + } + function copyOutParameter(outParam, copyDirection) { + var source = copyDirection === 0 ? outParam.outParamName : outParam.originalName; + var target = copyDirection === 0 ? outParam.originalName : outParam.outParamName; + return ts.createBinary(target, 59, source); + } + function copyOutParameters(outParams, partFlags, copyDirection, statements) { + for (var _i = 0, outParams_1 = outParams; _i < outParams_1.length; _i++) { + var outParam = outParams_1[_i]; + if (outParam.flags & partFlags) { + statements.push(ts.createExpressionStatement(copyOutParameter(outParam, copyDirection))); + } + } + } + function generateCallToConvertedLoopInitializer(initFunctionExpressionName, containsYield) { + var call = ts.createCall(initFunctionExpressionName, undefined, []); + var callResult = containsYield + ? ts.createYield(ts.createToken(40), ts.setEmitFlags(call, 8388608)) + : call; + return ts.createStatement(callResult); + } + function generateCallToConvertedLoop(loopFunctionExpressionName, state, outerState, containsYield) { + var statements = []; + var isSimpleLoop = !(state.nonLocalJumps & ~4) && + !state.labeledNonLocalBreaks && + !state.labeledNonLocalContinues; + var call = ts.createCall(loopFunctionExpressionName, undefined, ts.map(state.loopParameters, function (p) { return p.name; })); + var callResult = containsYield + ? ts.createYield(ts.createToken(40), ts.setEmitFlags(call, 8388608)) + : call; + if (isSimpleLoop) { + statements.push(ts.createExpressionStatement(callResult)); + copyOutParameters(state.loopOutParameters, 1, 0, statements); + } + else { + var loopResultName = ts.createUniqueName("state"); + var stateVariable = ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(loopResultName, undefined, callResult)])); + statements.push(stateVariable); + copyOutParameters(state.loopOutParameters, 1, 0, statements); + if (state.nonLocalJumps & 8) { + var returnStatement = void 0; + if (outerState) { + outerState.nonLocalJumps |= 8; + returnStatement = ts.createReturn(loopResultName); + } + else { + returnStatement = ts.createReturn(ts.createPropertyAccess(loopResultName, "value")); + } + statements.push(ts.createIf(ts.createBinary(ts.createTypeOf(loopResultName), 35, ts.createLiteral("object")), returnStatement)); + } + if (state.nonLocalJumps & 2) { + statements.push(ts.createIf(ts.createBinary(loopResultName, 35, ts.createLiteral("break")), ts.createBreak())); + } + if (state.labeledNonLocalBreaks || state.labeledNonLocalContinues) { + var caseClauses = []; + processLabeledJumps(state.labeledNonLocalBreaks, true, loopResultName, outerState, caseClauses); + processLabeledJumps(state.labeledNonLocalContinues, false, loopResultName, outerState, caseClauses); + statements.push(ts.createSwitch(loopResultName, ts.createCaseBlock(caseClauses))); + } + } + return statements; + } + function setLabeledJump(state, isBreak, labelText, labelMarker) { + if (isBreak) { + if (!state.labeledNonLocalBreaks) { + state.labeledNonLocalBreaks = ts.createMap(); + } + state.labeledNonLocalBreaks.set(labelText, labelMarker); + } + else { + if (!state.labeledNonLocalContinues) { + state.labeledNonLocalContinues = ts.createMap(); + } + state.labeledNonLocalContinues.set(labelText, labelMarker); + } + } + function processLabeledJumps(table, isBreak, loopResultName, outerLoop, caseClauses) { + if (!table) { + return; + } + table.forEach(function (labelMarker, labelText) { + var statements = []; + if (!outerLoop || (outerLoop.labels && outerLoop.labels.get(labelText))) { + var label = ts.createIdentifier(labelText); + statements.push(isBreak ? ts.createBreak(label) : ts.createContinue(label)); + } + else { + setLabeledJump(outerLoop, isBreak, labelText, labelMarker); + statements.push(ts.createReturn(loopResultName)); + } + caseClauses.push(ts.createCaseClause(ts.createLiteral(labelMarker), statements)); + }); + } + function processLoopVariableDeclaration(container, decl, loopParameters, loopOutParameters, hasCapturedBindingsInForInitializer) { + var name = decl.name; + if (ts.isBindingPattern(name)) { + for (var _i = 0, _a = name.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (!ts.isOmittedExpression(element)) { + processLoopVariableDeclaration(container, element, loopParameters, loopOutParameters, hasCapturedBindingsInForInitializer); + } + } + } + else { + loopParameters.push(ts.createParameter(undefined, undefined, undefined, name)); + var checkFlags = resolver.getNodeCheckFlags(decl); + if (checkFlags & 4194304 || hasCapturedBindingsInForInitializer) { + var outParamName = ts.createUniqueName("out_" + ts.idText(name)); + var flags = 0; + if (checkFlags & 4194304) { + flags |= 1; + } + if (ts.isForStatement(container) && container.initializer && resolver.isBindingCapturedByNode(container.initializer, decl)) { + flags |= 2; + } + loopOutParameters.push({ flags: flags, originalName: name, outParamName: outParamName }); + } + } + } + function addObjectLiteralMembers(expressions, node, receiver, start) { + var properties = node.properties; + var numProperties = properties.length; + for (var i = start; i < numProperties; i++) { + var property = properties[i]; + switch (property.kind) { + case 158: + case 159: + var accessors = ts.getAllAccessorDeclarations(node.properties, property); + if (property === accessors.firstAccessor) { + expressions.push(transformAccessorsToExpression(receiver, accessors, node, !!node.multiLine)); + } + break; + case 156: + expressions.push(transformObjectLiteralMethodDeclarationToExpression(property, receiver, node, node.multiLine)); + break; + case 275: + expressions.push(transformPropertyAssignmentToExpression(property, receiver, node.multiLine)); + break; + case 276: + expressions.push(transformShorthandPropertyAssignmentToExpression(property, receiver, node.multiLine)); + break; + default: + ts.Debug.failBadSyntaxKind(node); + break; + } + } + } + function transformPropertyAssignmentToExpression(property, receiver, startsOnNewLine) { + var expression = ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(property.name, visitor, ts.isPropertyName)), ts.visitNode(property.initializer, visitor, ts.isExpression)); + ts.setTextRange(expression, property); + if (startsOnNewLine) { + ts.startOnNewLine(expression); + } + return expression; + } + function transformShorthandPropertyAssignmentToExpression(property, receiver, startsOnNewLine) { + var expression = ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(property.name, visitor, ts.isPropertyName)), ts.getSynthesizedClone(property.name)); + ts.setTextRange(expression, property); + if (startsOnNewLine) { + ts.startOnNewLine(expression); + } + return expression; + } + function transformObjectLiteralMethodDeclarationToExpression(method, receiver, container, startsOnNewLine) { + var ancestorFacts = enterSubtree(0, 0); + var expression = ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(method.name, visitor, ts.isPropertyName)), transformFunctionLikeToExpression(method, method, undefined, container)); + ts.setTextRange(expression, method); + if (startsOnNewLine) { + ts.startOnNewLine(expression); + } + exitSubtree(ancestorFacts, 49152, hierarchyFacts & 49152 ? 16384 : 0); + return expression; + } + function visitCatchClause(node) { + var ancestorFacts = enterSubtree(4032, 0); + var updated; + ts.Debug.assert(!!node.variableDeclaration, "Catch clause variable should always be present when downleveling ES2015."); + if (ts.isBindingPattern(node.variableDeclaration.name)) { + var temp = ts.createTempVariable(undefined); + var newVariableDeclaration = ts.createVariableDeclaration(temp); + ts.setTextRange(newVariableDeclaration, node.variableDeclaration); + var vars = ts.flattenDestructuringBinding(node.variableDeclaration, visitor, context, 0, temp); + var list = ts.createVariableDeclarationList(vars); + ts.setTextRange(list, node.variableDeclaration); + var destructure = ts.createVariableStatement(undefined, list); + updated = ts.updateCatchClause(node, newVariableDeclaration, addStatementToStartOfBlock(node.block, destructure)); + } + else { + updated = ts.visitEachChild(node, visitor, context); + } + exitSubtree(ancestorFacts, 0, 0); + return updated; + } + function addStatementToStartOfBlock(block, statement) { + var transformedStatements = ts.visitNodes(block.statements, visitor, ts.isStatement); + return ts.updateBlock(block, [statement].concat(transformedStatements)); + } + function visitMethodDeclaration(node) { + ts.Debug.assert(!ts.isComputedPropertyName(node.name)); + var functionExpression = transformFunctionLikeToExpression(node, ts.moveRangePos(node, -1), undefined, undefined); + ts.setEmitFlags(functionExpression, 512 | ts.getEmitFlags(functionExpression)); + return ts.setTextRange(ts.createPropertyAssignment(node.name, functionExpression), node); + } + function visitAccessorDeclaration(node) { + ts.Debug.assert(!ts.isComputedPropertyName(node.name)); + var savedConvertedLoopState = convertedLoopState; + convertedLoopState = undefined; + var ancestorFacts = enterSubtree(16286, 65); + var updated; + var parameters = ts.visitParameterList(node.parameters, visitor, context); + var body = node.transformFlags & (16384 | 128) + ? transformFunctionBody(node) + : visitFunctionBodyDownLevel(node); + if (node.kind === 158) { + updated = ts.updateGetAccessor(node, node.decorators, node.modifiers, node.name, parameters, node.type, body); + } + else { + updated = ts.updateSetAccessor(node, node.decorators, node.modifiers, node.name, parameters, body); + } + exitSubtree(ancestorFacts, 49152, 0); + convertedLoopState = savedConvertedLoopState; + return updated; + } + function visitShorthandPropertyAssignment(node) { + return ts.setTextRange(ts.createPropertyAssignment(node.name, ts.getSynthesizedClone(node.name)), node); + } + function visitComputedPropertyName(node) { + var ancestorFacts = enterSubtree(0, 8192); + var updated = ts.visitEachChild(node, visitor, context); + exitSubtree(ancestorFacts, 49152, hierarchyFacts & 49152 ? 32768 : 0); + return updated; + } + function visitYieldExpression(node) { + return ts.visitEachChild(node, visitor, context); + } + function visitArrayLiteralExpression(node) { + if (node.transformFlags & 64) { + return transformAndSpreadElements(node.elements, true, !!node.multiLine, !!node.elements.hasTrailingComma); + } + return ts.visitEachChild(node, visitor, context); + } + function visitCallExpression(node) { + if (ts.getEmitFlags(node) & 33554432) { + return visitTypeScriptClassWrapper(node); + } + if (node.transformFlags & 64) { + return visitCallExpressionWithPotentialCapturedThisAssignment(node, true); + } + return ts.updateCall(node, ts.visitNode(node.expression, callExpressionVisitor, ts.isExpression), undefined, ts.visitNodes(node.arguments, visitor, ts.isExpression)); + } + function visitTypeScriptClassWrapper(node) { + var body = ts.cast(ts.cast(ts.skipOuterExpressions(node.expression), ts.isArrowFunction).body, ts.isBlock); + var isVariableStatementWithInitializer = function (stmt) { return ts.isVariableStatement(stmt) && !!ts.first(stmt.declarationList.declarations).initializer; }; + var bodyStatements = ts.visitNodes(body.statements, visitor, ts.isStatement); + var classStatements = ts.filter(bodyStatements, isVariableStatementWithInitializer); + var remainingStatements = ts.filter(bodyStatements, function (stmt) { return !isVariableStatementWithInitializer(stmt); }); + var varStatement = ts.cast(ts.first(classStatements), ts.isVariableStatement); + var variable = varStatement.declarationList.declarations[0]; + var initializer = ts.skipOuterExpressions(variable.initializer); + var aliasAssignment = ts.tryCast(initializer, ts.isAssignmentExpression); + var call = ts.cast(aliasAssignment ? ts.skipOuterExpressions(aliasAssignment.right) : initializer, ts.isCallExpression); + var func = ts.cast(ts.skipOuterExpressions(call.expression), ts.isFunctionExpression); + var funcStatements = func.body.statements; + var classBodyStart = 0; + var classBodyEnd = -1; + var statements = []; + if (aliasAssignment) { + var extendsCall = ts.tryCast(funcStatements[classBodyStart], ts.isExpressionStatement); + if (extendsCall) { + statements.push(extendsCall); + classBodyStart++; + } + statements.push(funcStatements[classBodyStart]); + classBodyStart++; + statements.push(ts.createExpressionStatement(ts.createAssignment(aliasAssignment.left, ts.cast(variable.name, ts.isIdentifier)))); + } + while (!ts.isReturnStatement(ts.elementAt(funcStatements, classBodyEnd))) { + classBodyEnd--; + } + ts.addRange(statements, funcStatements, classBodyStart, classBodyEnd); + if (classBodyEnd < -1) { + ts.addRange(statements, funcStatements, classBodyEnd + 1); + } + ts.addRange(statements, remainingStatements); + ts.addRange(statements, classStatements, 1); + return ts.recreateOuterExpressions(node.expression, ts.recreateOuterExpressions(variable.initializer, ts.recreateOuterExpressions(aliasAssignment && aliasAssignment.right, ts.updateCall(call, ts.recreateOuterExpressions(call.expression, ts.updateFunctionExpression(func, undefined, undefined, undefined, undefined, func.parameters, undefined, ts.updateBlock(func.body, statements))), undefined, call.arguments)))); + } + function visitImmediateSuperCallInBody(node) { + return visitCallExpressionWithPotentialCapturedThisAssignment(node, false); + } + function visitCallExpressionWithPotentialCapturedThisAssignment(node, assignToCapturedThis) { + if (node.transformFlags & 131072 || + node.expression.kind === 98 || + ts.isSuperProperty(ts.skipOuterExpressions(node.expression))) { + var _a = ts.createCallBinding(node.expression, hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg; + if (node.expression.kind === 98) { + ts.setEmitFlags(thisArg, 4); + } + var resultingCall = void 0; + if (node.transformFlags & 131072) { + resultingCall = ts.createFunctionApply(ts.visitNode(target, callExpressionVisitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), transformAndSpreadElements(node.arguments, false, false, false)); + } + else { + resultingCall = ts.createFunctionCall(ts.visitNode(target, callExpressionVisitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), ts.visitNodes(node.arguments, visitor, ts.isExpression), node); + } + if (node.expression.kind === 98) { + var actualThis = ts.createThis(); + ts.setEmitFlags(actualThis, 4); + var initializer = ts.createLogicalOr(resultingCall, actualThis); + resultingCall = assignToCapturedThis + ? ts.createAssignment(ts.createFileLevelUniqueName("_this"), initializer) + : initializer; + } + return ts.setOriginalNode(resultingCall, node); + } + return ts.visitEachChild(node, visitor, context); + } + function visitNewExpression(node) { + if (node.transformFlags & 131072) { + var _a = ts.createCallBinding(ts.createPropertyAccess(node.expression, "bind"), hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg; + return ts.createNew(ts.createFunctionApply(ts.visitNode(target, visitor, ts.isExpression), thisArg, transformAndSpreadElements(ts.createNodeArray([ts.createVoidZero()].concat(node.arguments)), false, false, false)), undefined, []); + } + return ts.visitEachChild(node, visitor, context); + } + function transformAndSpreadElements(elements, needsUniqueCopy, multiLine, hasTrailingComma) { + var numElements = elements.length; + var segments = ts.flatten(ts.spanMap(elements, partitionSpread, function (partition, visitPartition, _start, end) { + return visitPartition(partition, multiLine, hasTrailingComma && end === numElements); + })); + if (compilerOptions.downlevelIteration) { + if (segments.length === 1) { + var firstSegment = segments[0]; + if (ts.isCallExpression(firstSegment) + && ts.isIdentifier(firstSegment.expression) + && (ts.getEmitFlags(firstSegment.expression) & 4096) + && firstSegment.expression.escapedText === "___spread") { + return segments[0]; + } + } + return ts.createSpreadHelper(context, segments); + } + else { + if (segments.length === 1) { + var firstElement = elements[0]; + return needsUniqueCopy && ts.isSpreadElement(firstElement) && firstElement.expression.kind !== 187 + ? ts.createArraySlice(segments[0]) + : segments[0]; + } + return ts.createArrayConcat(segments.shift(), segments); + } + } + function partitionSpread(node) { + return ts.isSpreadElement(node) + ? visitSpanOfSpreads + : visitSpanOfNonSpreads; + } + function visitSpanOfSpreads(chunk) { + return ts.map(chunk, visitExpressionOfSpread); + } + function visitSpanOfNonSpreads(chunk, multiLine, hasTrailingComma) { + return ts.createArrayLiteral(ts.visitNodes(ts.createNodeArray(chunk, hasTrailingComma), visitor, ts.isExpression), multiLine); + } + function visitSpreadElement(node) { + return ts.visitNode(node.expression, visitor, ts.isExpression); + } + function visitExpressionOfSpread(node) { + return ts.visitNode(node.expression, visitor, ts.isExpression); + } + function visitTemplateLiteral(node) { + return ts.setTextRange(ts.createLiteral(node.text), node); + } + function visitStringLiteral(node) { + if (node.hasExtendedUnicodeEscape) { + return ts.setTextRange(ts.createLiteral(node.text), node); + } + return node; + } + function visitNumericLiteral(node) { + if (node.numericLiteralFlags & 384) { + return ts.setTextRange(ts.createNumericLiteral(node.text), node); + } + return node; + } + function visitTaggedTemplateExpression(node) { + var tag = ts.visitNode(node.tag, visitor, ts.isExpression); + var templateArguments = [undefined]; + var cookedStrings = []; + var rawStrings = []; + var template = node.template; + if (ts.isNoSubstitutionTemplateLiteral(template)) { + cookedStrings.push(ts.createLiteral(template.text)); + rawStrings.push(getRawLiteral(template)); + } + else { + cookedStrings.push(ts.createLiteral(template.head.text)); + rawStrings.push(getRawLiteral(template.head)); + for (var _i = 0, _a = template.templateSpans; _i < _a.length; _i++) { + var templateSpan = _a[_i]; + cookedStrings.push(ts.createLiteral(templateSpan.literal.text)); + rawStrings.push(getRawLiteral(templateSpan.literal)); + templateArguments.push(ts.visitNode(templateSpan.expression, visitor, ts.isExpression)); + } + } + var helperCall = createTemplateObjectHelper(context, ts.createArrayLiteral(cookedStrings), ts.createArrayLiteral(rawStrings)); + if (ts.isExternalModule(currentSourceFile)) { + var tempVar = ts.createUniqueName("templateObject"); + recordTaggedTemplateString(tempVar); + templateArguments[0] = ts.createLogicalOr(tempVar, ts.createAssignment(tempVar, helperCall)); + } + else { + templateArguments[0] = helperCall; + } + return ts.createCall(tag, undefined, templateArguments); + } + function getRawLiteral(node) { + var text = ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node); + var isLast = node.kind === 14 || node.kind === 17; + text = text.substring(1, text.length - (isLast ? 1 : 2)); + text = text.replace(/\r\n?/g, "\n"); + return ts.setTextRange(ts.createLiteral(text), node); + } + function visitTemplateExpression(node) { + var expressions = []; + addTemplateHead(expressions, node); + addTemplateSpans(expressions, node); + var expression = ts.reduceLeft(expressions, ts.createAdd); + if (ts.nodeIsSynthesized(expression)) { + expression.pos = node.pos; + expression.end = node.end; + } + return expression; + } + function shouldAddTemplateHead(node) { + ts.Debug.assert(node.templateSpans.length !== 0); + return node.head.text.length !== 0 || node.templateSpans[0].literal.text.length === 0; + } + function addTemplateHead(expressions, node) { + if (!shouldAddTemplateHead(node)) { + return; + } + expressions.push(ts.createLiteral(node.head.text)); + } + function addTemplateSpans(expressions, node) { + for (var _i = 0, _a = node.templateSpans; _i < _a.length; _i++) { + var span = _a[_i]; + expressions.push(ts.visitNode(span.expression, visitor, ts.isExpression)); + if (span.literal.text.length !== 0) { + expressions.push(ts.createLiteral(span.literal.text)); + } + } + } + function visitSuperKeyword(isExpressionOfCall) { + return hierarchyFacts & 8 + && !isExpressionOfCall + ? ts.createPropertyAccess(ts.createFileLevelUniqueName("_super"), "prototype") + : ts.createFileLevelUniqueName("_super"); + } + function visitMetaProperty(node) { + if (node.keywordToken === 95 && node.name.escapedText === "target") { + if (hierarchyFacts & 8192) { + hierarchyFacts |= 32768; + } + else { + hierarchyFacts |= 16384; + } + return ts.createFileLevelUniqueName("_newTarget"); + } + return node; + } + function onEmitNode(hint, node, emitCallback) { + if (enabledSubstitutions & 1 && ts.isFunctionLike(node)) { + var ancestorFacts = enterSubtree(16286, ts.getEmitFlags(node) & 8 + ? 65 | 16 + : 65); + previousOnEmitNode(hint, node, emitCallback); + exitSubtree(ancestorFacts, 0, 0); + return; + } + previousOnEmitNode(hint, node, emitCallback); + } + function enableSubstitutionsForBlockScopedBindings() { + if ((enabledSubstitutions & 2) === 0) { + enabledSubstitutions |= 2; + context.enableSubstitution(72); + } + } + function enableSubstitutionsForCapturedThis() { + if ((enabledSubstitutions & 1) === 0) { + enabledSubstitutions |= 1; + context.enableSubstitution(100); + context.enableEmitNotification(157); + context.enableEmitNotification(156); + context.enableEmitNotification(158); + context.enableEmitNotification(159); + context.enableEmitNotification(197); + context.enableEmitNotification(196); + context.enableEmitNotification(239); + } + } + function onSubstituteNode(hint, node) { + node = previousOnSubstituteNode(hint, node); + if (hint === 1) { + return substituteExpression(node); + } + if (ts.isIdentifier(node)) { + return substituteIdentifier(node); + } + return node; + } + function substituteIdentifier(node) { + if (enabledSubstitutions & 2 && !ts.isInternalName(node)) { + var original = ts.getParseTreeNode(node, ts.isIdentifier); + if (original && isNameOfDeclarationWithCollidingName(original)) { + return ts.setTextRange(ts.getGeneratedNameForNode(original), node); + } + } + return node; + } + function isNameOfDeclarationWithCollidingName(node) { + switch (node.parent.kind) { + case 186: + case 240: + case 243: + case 237: + return node.parent.name === node + && resolver.isDeclarationWithCollidingName(node.parent); + } + return false; + } + function substituteExpression(node) { + switch (node.kind) { + case 72: + return substituteExpressionIdentifier(node); + case 100: + return substituteThisKeyword(node); + } + return node; + } + function substituteExpressionIdentifier(node) { + if (enabledSubstitutions & 2 && !ts.isInternalName(node)) { + var declaration = resolver.getReferencedDeclarationWithCollidingName(node); + if (declaration && !(ts.isClassLike(declaration) && isPartOfClassBody(declaration, node))) { + return ts.setTextRange(ts.getGeneratedNameForNode(ts.getNameOfDeclaration(declaration)), node); + } + } + return node; + } + function isPartOfClassBody(declaration, node) { + var currentNode = ts.getParseTreeNode(node); + if (!currentNode || currentNode === declaration || currentNode.end <= declaration.pos || currentNode.pos >= declaration.end) { + return false; + } + var blockScope = ts.getEnclosingBlockScopeContainer(declaration); + while (currentNode) { + if (currentNode === blockScope || currentNode === declaration) { + return false; + } + if (ts.isClassElement(currentNode) && currentNode.parent === declaration) { + return true; + } + currentNode = currentNode.parent; + } + return false; + } + function substituteThisKeyword(node) { + if (enabledSubstitutions & 1 + && hierarchyFacts & 16) { + return ts.setTextRange(ts.createFileLevelUniqueName("_this"), node); + } + return node; + } + function getClassMemberPrefix(node, member) { + return ts.hasModifier(member, 32) + ? ts.getInternalName(node) + : ts.createPropertyAccess(ts.getInternalName(node), "prototype"); + } + function hasSynthesizedDefaultSuperCall(constructor, hasExtendsClause) { + if (!constructor || !hasExtendsClause) { + return false; + } + if (ts.some(constructor.parameters)) { + return false; + } + var statement = ts.firstOrUndefined(constructor.body.statements); + if (!statement || !ts.nodeIsSynthesized(statement) || statement.kind !== 221) { + return false; + } + var statementExpression = statement.expression; + if (!ts.nodeIsSynthesized(statementExpression) || statementExpression.kind !== 191) { + return false; + } + var callTarget = statementExpression.expression; + if (!ts.nodeIsSynthesized(callTarget) || callTarget.kind !== 98) { + return false; + } + var callArgument = ts.singleOrUndefined(statementExpression.arguments); + if (!callArgument || !ts.nodeIsSynthesized(callArgument) || callArgument.kind !== 208) { + return false; + } + var expression = callArgument.expression; + return ts.isIdentifier(expression) && expression.escapedText === "arguments"; + } + } + ts.transformES2015 = transformES2015; + function createExtendsHelper(context, name) { + context.requestEmitHelper(extendsHelper); + return ts.createCall(ts.getHelperName("__extends"), undefined, [ + name, + ts.createFileLevelUniqueName("_super") + ]); + } + function createTemplateObjectHelper(context, cooked, raw) { + context.requestEmitHelper(templateObjectHelper); + return ts.createCall(ts.getHelperName("__makeTemplateObject"), undefined, [ + cooked, + raw + ]); + } + var extendsHelper = { + name: "typescript:extends", + scoped: false, + priority: 0, + text: "\n var __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return extendStatics(d, b);\n };\n\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n })();" + }; + var templateObjectHelper = { + name: "typescript:makeTemplateObject", + scoped: false, + priority: 0, + text: "\n var __makeTemplateObject = (this && this.__makeTemplateObject) || function (cooked, raw) {\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\n return cooked;\n };" + }; +})(ts || (ts = {})); +var ts; +(function (ts) { + function transformES5(context) { + var compilerOptions = context.getCompilerOptions(); + var previousOnEmitNode; + var noSubstitution; + if (compilerOptions.jsx === 1 || compilerOptions.jsx === 3) { + previousOnEmitNode = context.onEmitNode; + context.onEmitNode = onEmitNode; + context.enableEmitNotification(262); + context.enableEmitNotification(263); + context.enableEmitNotification(261); + noSubstitution = []; + } + var previousOnSubstituteNode = context.onSubstituteNode; + context.onSubstituteNode = onSubstituteNode; + context.enableSubstitution(189); + context.enableSubstitution(275); + return ts.chainBundle(transformSourceFile); + function transformSourceFile(node) { + return node; + } + function onEmitNode(hint, node, emitCallback) { + switch (node.kind) { + case 262: + case 263: + case 261: + var tagName = node.tagName; + noSubstitution[ts.getOriginalNodeId(tagName)] = true; + break; + } + previousOnEmitNode(hint, node, emitCallback); + } + function onSubstituteNode(hint, node) { + if (node.id && noSubstitution && noSubstitution[node.id]) { + return previousOnSubstituteNode(hint, node); + } + node = previousOnSubstituteNode(hint, node); + if (ts.isPropertyAccessExpression(node)) { + return substitutePropertyAccessExpression(node); + } + else if (ts.isPropertyAssignment(node)) { + return substitutePropertyAssignment(node); + } + return node; + } + function substitutePropertyAccessExpression(node) { + var literalName = trySubstituteReservedName(node.name); + if (literalName) { + return ts.setTextRange(ts.createElementAccess(node.expression, literalName), node); + } + return node; + } + function substitutePropertyAssignment(node) { + var literalName = ts.isIdentifier(node.name) && trySubstituteReservedName(node.name); + if (literalName) { + return ts.updatePropertyAssignment(node, literalName, node.initializer); + } + return node; + } + function trySubstituteReservedName(name) { + var token = name.originalKeywordKind || (ts.nodeIsSynthesized(name) ? ts.stringToToken(ts.idText(name)) : undefined); + if (token !== undefined && token >= 73 && token <= 108) { + return ts.setTextRange(ts.createLiteral(name), name); + } + return undefined; + } + } + ts.transformES5 = transformES5; +})(ts || (ts = {})); +var ts; +(function (ts) { + function getInstructionName(instruction) { + switch (instruction) { + case 2: return "return"; + case 3: return "break"; + case 4: return "yield"; + case 5: return "yield*"; + case 7: return "endfinally"; + default: return undefined; + } + } + function transformGenerators(context) { + var resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistFunctionDeclaration = context.hoistFunctionDeclaration, hoistVariableDeclaration = context.hoistVariableDeclaration; + var compilerOptions = context.getCompilerOptions(); + var languageVersion = ts.getEmitScriptTarget(compilerOptions); + var resolver = context.getEmitResolver(); + var previousOnSubstituteNode = context.onSubstituteNode; + context.onSubstituteNode = onSubstituteNode; + var renamedCatchVariables; + var renamedCatchVariableDeclarations; + var inGeneratorFunctionBody; + var inStatementContainingYield; + var blocks; + var blockOffsets; + var blockActions; + var blockStack; + var labelOffsets; + var labelExpressions; + var nextLabelId = 1; + var operations; + var operationArguments; + var operationLocations; + var state; + var blockIndex = 0; + var labelNumber = 0; + var labelNumbers; + var lastOperationWasAbrupt; + var lastOperationWasCompletion; + var clauses; + var statements; + var exceptionBlockStack; + var currentExceptionBlock; + var withBlockStack; + return ts.chainBundle(transformSourceFile); + function transformSourceFile(node) { + if (node.isDeclarationFile || (node.transformFlags & 512) === 0) { + return node; + } + var visited = ts.visitEachChild(node, visitor, context); + ts.addEmitHelpers(visited, context.readEmitHelpers()); + return visited; + } + function visitor(node) { + var transformFlags = node.transformFlags; + if (inStatementContainingYield) { + return visitJavaScriptInStatementContainingYield(node); + } + else if (inGeneratorFunctionBody) { + return visitJavaScriptInGeneratorFunctionBody(node); + } + else if (transformFlags & 256) { + return visitGenerator(node); + } + else if (transformFlags & 512) { + return ts.visitEachChild(node, visitor, context); + } + else { + return node; + } + } + function visitJavaScriptInStatementContainingYield(node) { + switch (node.kind) { + case 223: + return visitDoStatement(node); + case 224: + return visitWhileStatement(node); + case 232: + return visitSwitchStatement(node); + case 233: + return visitLabeledStatement(node); + default: + return visitJavaScriptInGeneratorFunctionBody(node); + } + } + function visitJavaScriptInGeneratorFunctionBody(node) { + switch (node.kind) { + case 239: + return visitFunctionDeclaration(node); + case 196: + return visitFunctionExpression(node); + case 158: + case 159: + return visitAccessorDeclaration(node); + case 219: + return visitVariableStatement(node); + case 225: + return visitForStatement(node); + case 226: + return visitForInStatement(node); + case 229: + return visitBreakStatement(node); + case 228: + return visitContinueStatement(node); + case 230: + return visitReturnStatement(node); + default: + if (node.transformFlags & 4194304) { + return visitJavaScriptContainingYield(node); + } + else if (node.transformFlags & (512 | 8388608)) { + return ts.visitEachChild(node, visitor, context); + } + else { + return node; + } + } + } + function visitJavaScriptContainingYield(node) { + switch (node.kind) { + case 204: + return visitBinaryExpression(node); + case 205: + return visitConditionalExpression(node); + case 207: + return visitYieldExpression(node); + case 187: + return visitArrayLiteralExpression(node); + case 188: + return visitObjectLiteralExpression(node); + case 190: + return visitElementAccessExpression(node); + case 191: + return visitCallExpression(node); + case 192: + return visitNewExpression(node); + default: + return ts.visitEachChild(node, visitor, context); + } + } + function visitGenerator(node) { + switch (node.kind) { + case 239: + return visitFunctionDeclaration(node); + case 196: + return visitFunctionExpression(node); + default: + return ts.Debug.failBadSyntaxKind(node); + } + } + function visitFunctionDeclaration(node) { + if (node.asteriskToken) { + node = ts.setOriginalNode(ts.setTextRange(ts.createFunctionDeclaration(undefined, node.modifiers, undefined, node.name, undefined, ts.visitParameterList(node.parameters, visitor, context), undefined, transformGeneratorFunctionBody(node.body)), node), node); + } + else { + var savedInGeneratorFunctionBody = inGeneratorFunctionBody; + var savedInStatementContainingYield = inStatementContainingYield; + inGeneratorFunctionBody = false; + inStatementContainingYield = false; + node = ts.visitEachChild(node, visitor, context); + inGeneratorFunctionBody = savedInGeneratorFunctionBody; + inStatementContainingYield = savedInStatementContainingYield; + } + if (inGeneratorFunctionBody) { + hoistFunctionDeclaration(node); + return undefined; + } + else { + return node; + } + } + function visitFunctionExpression(node) { + if (node.asteriskToken) { + node = ts.setOriginalNode(ts.setTextRange(ts.createFunctionExpression(undefined, undefined, node.name, undefined, ts.visitParameterList(node.parameters, visitor, context), undefined, transformGeneratorFunctionBody(node.body)), node), node); + } + else { + var savedInGeneratorFunctionBody = inGeneratorFunctionBody; + var savedInStatementContainingYield = inStatementContainingYield; + inGeneratorFunctionBody = false; + inStatementContainingYield = false; + node = ts.visitEachChild(node, visitor, context); + inGeneratorFunctionBody = savedInGeneratorFunctionBody; + inStatementContainingYield = savedInStatementContainingYield; + } + return node; + } + function visitAccessorDeclaration(node) { + var savedInGeneratorFunctionBody = inGeneratorFunctionBody; + var savedInStatementContainingYield = inStatementContainingYield; + inGeneratorFunctionBody = false; + inStatementContainingYield = false; + node = ts.visitEachChild(node, visitor, context); + inGeneratorFunctionBody = savedInGeneratorFunctionBody; + inStatementContainingYield = savedInStatementContainingYield; + return node; + } + function transformGeneratorFunctionBody(body) { + var statements = []; + var savedInGeneratorFunctionBody = inGeneratorFunctionBody; + var savedInStatementContainingYield = inStatementContainingYield; + var savedBlocks = blocks; + var savedBlockOffsets = blockOffsets; + var savedBlockActions = blockActions; + var savedBlockStack = blockStack; + var savedLabelOffsets = labelOffsets; + var savedLabelExpressions = labelExpressions; + var savedNextLabelId = nextLabelId; + var savedOperations = operations; + var savedOperationArguments = operationArguments; + var savedOperationLocations = operationLocations; + var savedState = state; + inGeneratorFunctionBody = true; + inStatementContainingYield = false; + blocks = undefined; + blockOffsets = undefined; + blockActions = undefined; + blockStack = undefined; + labelOffsets = undefined; + labelExpressions = undefined; + nextLabelId = 1; + operations = undefined; + operationArguments = undefined; + operationLocations = undefined; + state = ts.createTempVariable(undefined); + resumeLexicalEnvironment(); + var statementOffset = ts.addPrologue(statements, body.statements, false, visitor); + transformAndEmitStatements(body.statements, statementOffset); + var buildResult = build(); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + statements.push(ts.createReturn(buildResult)); + inGeneratorFunctionBody = savedInGeneratorFunctionBody; + inStatementContainingYield = savedInStatementContainingYield; + blocks = savedBlocks; + blockOffsets = savedBlockOffsets; + blockActions = savedBlockActions; + blockStack = savedBlockStack; + labelOffsets = savedLabelOffsets; + labelExpressions = savedLabelExpressions; + nextLabelId = savedNextLabelId; + operations = savedOperations; + operationArguments = savedOperationArguments; + operationLocations = savedOperationLocations; + state = savedState; + return ts.setTextRange(ts.createBlock(statements, body.multiLine), body); + } + function visitVariableStatement(node) { + if (node.transformFlags & 4194304) { + transformAndEmitVariableDeclarationList(node.declarationList); + return undefined; + } + else { + if (ts.getEmitFlags(node) & 1048576) { + return node; + } + for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { + var variable = _a[_i]; + hoistVariableDeclaration(variable.name); + } + var variables = ts.getInitializedVariables(node.declarationList); + if (variables.length === 0) { + return undefined; + } + return ts.setSourceMapRange(ts.createExpressionStatement(ts.inlineExpressions(ts.map(variables, transformInitializedVariable))), node); + } + } + function visitBinaryExpression(node) { + var assoc = ts.getExpressionAssociativity(node); + switch (assoc) { + case 0: + return visitLeftAssociativeBinaryExpression(node); + case 1: + return visitRightAssociativeBinaryExpression(node); + default: + return ts.Debug.assertNever(assoc); + } + } + function isCompoundAssignment(kind) { + return kind >= 60 + && kind <= 71; + } + function getOperatorForCompoundAssignment(kind) { + switch (kind) { + case 60: return 38; + case 61: return 39; + case 62: return 40; + case 63: return 41; + case 64: return 42; + case 65: return 43; + case 66: return 46; + case 67: return 47; + case 68: return 48; + case 69: return 49; + case 70: return 50; + case 71: return 51; + } + } + function visitRightAssociativeBinaryExpression(node) { + var left = node.left, right = node.right; + if (containsYield(right)) { + var target = void 0; + switch (left.kind) { + case 189: + target = ts.updatePropertyAccess(left, cacheExpression(ts.visitNode(left.expression, visitor, ts.isLeftHandSideExpression)), left.name); + break; + case 190: + target = ts.updateElementAccess(left, cacheExpression(ts.visitNode(left.expression, visitor, ts.isLeftHandSideExpression)), cacheExpression(ts.visitNode(left.argumentExpression, visitor, ts.isExpression))); + break; + default: + target = ts.visitNode(left, visitor, ts.isExpression); + break; + } + var operator = node.operatorToken.kind; + if (isCompoundAssignment(operator)) { + return ts.setTextRange(ts.createAssignment(target, ts.setTextRange(ts.createBinary(cacheExpression(target), getOperatorForCompoundAssignment(operator), ts.visitNode(right, visitor, ts.isExpression)), node)), node); + } + else { + return ts.updateBinary(node, target, ts.visitNode(right, visitor, ts.isExpression)); + } + } + return ts.visitEachChild(node, visitor, context); + } + function visitLeftAssociativeBinaryExpression(node) { + if (containsYield(node.right)) { + if (ts.isLogicalOperator(node.operatorToken.kind)) { + return visitLogicalBinaryExpression(node); + } + else if (node.operatorToken.kind === 27) { + return visitCommaExpression(node); + } + var clone_5 = ts.getMutableClone(node); + clone_5.left = cacheExpression(ts.visitNode(node.left, visitor, ts.isExpression)); + clone_5.right = ts.visitNode(node.right, visitor, ts.isExpression); + return clone_5; + } + return ts.visitEachChild(node, visitor, context); + } + function visitLogicalBinaryExpression(node) { + var resultLabel = defineLabel(); + var resultLocal = declareLocal(); + emitAssignment(resultLocal, ts.visitNode(node.left, visitor, ts.isExpression), node.left); + if (node.operatorToken.kind === 54) { + emitBreakWhenFalse(resultLabel, resultLocal, node.left); + } + else { + emitBreakWhenTrue(resultLabel, resultLocal, node.left); + } + emitAssignment(resultLocal, ts.visitNode(node.right, visitor, ts.isExpression), node.right); + markLabel(resultLabel); + return resultLocal; + } + function visitCommaExpression(node) { + var pendingExpressions = []; + visit(node.left); + visit(node.right); + return ts.inlineExpressions(pendingExpressions); + function visit(node) { + if (ts.isBinaryExpression(node) && node.operatorToken.kind === 27) { + visit(node.left); + visit(node.right); + } + else { + if (containsYield(node) && pendingExpressions.length > 0) { + emitWorker(1, [ts.createExpressionStatement(ts.inlineExpressions(pendingExpressions))]); + pendingExpressions = []; + } + pendingExpressions.push(ts.visitNode(node, visitor, ts.isExpression)); + } + } + } + function visitConditionalExpression(node) { + if (containsYield(node.whenTrue) || containsYield(node.whenFalse)) { + var whenFalseLabel = defineLabel(); + var resultLabel = defineLabel(); + var resultLocal = declareLocal(); + emitBreakWhenFalse(whenFalseLabel, ts.visitNode(node.condition, visitor, ts.isExpression), node.condition); + emitAssignment(resultLocal, ts.visitNode(node.whenTrue, visitor, ts.isExpression), node.whenTrue); + emitBreak(resultLabel); + markLabel(whenFalseLabel); + emitAssignment(resultLocal, ts.visitNode(node.whenFalse, visitor, ts.isExpression), node.whenFalse); + markLabel(resultLabel); + return resultLocal; + } + return ts.visitEachChild(node, visitor, context); + } + function visitYieldExpression(node) { + var resumeLabel = defineLabel(); + var expression = ts.visitNode(node.expression, visitor, ts.isExpression); + if (node.asteriskToken) { + var iterator = (ts.getEmitFlags(node.expression) & 8388608) === 0 + ? ts.createValuesHelper(context, expression, node) + : expression; + emitYieldStar(iterator, node); + } + else { + emitYield(expression, node); + } + markLabel(resumeLabel); + return createGeneratorResume(node); + } + function visitArrayLiteralExpression(node) { + return visitElements(node.elements, undefined, undefined, node.multiLine); + } + function visitElements(elements, leadingElement, location, multiLine) { + var numInitialElements = countInitialNodesWithoutYield(elements); + var temp; + if (numInitialElements > 0) { + temp = declareLocal(); + var initialElements = ts.visitNodes(elements, visitor, ts.isExpression, 0, numInitialElements); + emitAssignment(temp, ts.createArrayLiteral(leadingElement + ? [leadingElement].concat(initialElements) : initialElements)); + leadingElement = undefined; + } + var expressions = ts.reduceLeft(elements, reduceElement, [], numInitialElements); + return temp + ? ts.createArrayConcat(temp, [ts.createArrayLiteral(expressions, multiLine)]) + : ts.setTextRange(ts.createArrayLiteral(leadingElement ? [leadingElement].concat(expressions) : expressions, multiLine), location); + function reduceElement(expressions, element) { + if (containsYield(element) && expressions.length > 0) { + var hasAssignedTemp = temp !== undefined; + if (!temp) { + temp = declareLocal(); + } + emitAssignment(temp, hasAssignedTemp + ? ts.createArrayConcat(temp, [ts.createArrayLiteral(expressions, multiLine)]) + : ts.createArrayLiteral(leadingElement ? [leadingElement].concat(expressions) : expressions, multiLine)); + leadingElement = undefined; + expressions = []; + } + expressions.push(ts.visitNode(element, visitor, ts.isExpression)); + return expressions; + } + } + function visitObjectLiteralExpression(node) { + var properties = node.properties; + var multiLine = node.multiLine; + var numInitialProperties = countInitialNodesWithoutYield(properties); + var temp = declareLocal(); + emitAssignment(temp, ts.createObjectLiteral(ts.visitNodes(properties, visitor, ts.isObjectLiteralElementLike, 0, numInitialProperties), multiLine)); + var expressions = ts.reduceLeft(properties, reduceProperty, [], numInitialProperties); + expressions.push(multiLine ? ts.startOnNewLine(ts.getMutableClone(temp)) : temp); + return ts.inlineExpressions(expressions); + function reduceProperty(expressions, property) { + if (containsYield(property) && expressions.length > 0) { + emitStatement(ts.createExpressionStatement(ts.inlineExpressions(expressions))); + expressions = []; + } + var expression = ts.createExpressionForObjectLiteralElementLike(node, property, temp); + var visited = ts.visitNode(expression, visitor, ts.isExpression); + if (visited) { + if (multiLine) { + ts.startOnNewLine(visited); + } + expressions.push(visited); + } + return expressions; + } + } + function visitElementAccessExpression(node) { + if (containsYield(node.argumentExpression)) { + var clone_6 = ts.getMutableClone(node); + clone_6.expression = cacheExpression(ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression)); + clone_6.argumentExpression = ts.visitNode(node.argumentExpression, visitor, ts.isExpression); + return clone_6; + } + return ts.visitEachChild(node, visitor, context); + } + function visitCallExpression(node) { + if (!ts.isImportCall(node) && ts.forEach(node.arguments, containsYield)) { + var _a = ts.createCallBinding(node.expression, hoistVariableDeclaration, languageVersion, true), target = _a.target, thisArg = _a.thisArg; + return ts.setOriginalNode(ts.createFunctionApply(cacheExpression(ts.visitNode(target, visitor, ts.isLeftHandSideExpression)), thisArg, visitElements(node.arguments), node), node); + } + return ts.visitEachChild(node, visitor, context); + } + function visitNewExpression(node) { + if (ts.forEach(node.arguments, containsYield)) { + var _a = ts.createCallBinding(ts.createPropertyAccess(node.expression, "bind"), hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg; + return ts.setOriginalNode(ts.setTextRange(ts.createNew(ts.createFunctionApply(cacheExpression(ts.visitNode(target, visitor, ts.isExpression)), thisArg, visitElements(node.arguments, ts.createVoidZero())), undefined, []), node), node); + } + return ts.visitEachChild(node, visitor, context); + } + function transformAndEmitStatements(statements, start) { + if (start === void 0) { start = 0; } + var numStatements = statements.length; + for (var i = start; i < numStatements; i++) { + transformAndEmitStatement(statements[i]); + } + } + function transformAndEmitEmbeddedStatement(node) { + if (ts.isBlock(node)) { + transformAndEmitStatements(node.statements); + } + else { + transformAndEmitStatement(node); + } + } + function transformAndEmitStatement(node) { + var savedInStatementContainingYield = inStatementContainingYield; + if (!inStatementContainingYield) { + inStatementContainingYield = containsYield(node); + } + transformAndEmitStatementWorker(node); + inStatementContainingYield = savedInStatementContainingYield; + } + function transformAndEmitStatementWorker(node) { + switch (node.kind) { + case 218: + return transformAndEmitBlock(node); + case 221: + return transformAndEmitExpressionStatement(node); + case 222: + return transformAndEmitIfStatement(node); + case 223: + return transformAndEmitDoStatement(node); + case 224: + return transformAndEmitWhileStatement(node); + case 225: + return transformAndEmitForStatement(node); + case 226: + return transformAndEmitForInStatement(node); + case 228: + return transformAndEmitContinueStatement(node); + case 229: + return transformAndEmitBreakStatement(node); + case 230: + return transformAndEmitReturnStatement(node); + case 231: + return transformAndEmitWithStatement(node); + case 232: + return transformAndEmitSwitchStatement(node); + case 233: + return transformAndEmitLabeledStatement(node); + case 234: + return transformAndEmitThrowStatement(node); + case 235: + return transformAndEmitTryStatement(node); + default: + return emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + } + function transformAndEmitBlock(node) { + if (containsYield(node)) { + transformAndEmitStatements(node.statements); + } + else { + emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + } + function transformAndEmitExpressionStatement(node) { + emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + function transformAndEmitVariableDeclarationList(node) { + for (var _i = 0, _a = node.declarations; _i < _a.length; _i++) { + var variable = _a[_i]; + var name = ts.getSynthesizedClone(variable.name); + ts.setCommentRange(name, variable.name); + hoistVariableDeclaration(name); + } + var variables = ts.getInitializedVariables(node); + var numVariables = variables.length; + var variablesWritten = 0; + var pendingExpressions = []; + while (variablesWritten < numVariables) { + for (var i = variablesWritten; i < numVariables; i++) { + var variable = variables[i]; + if (containsYield(variable.initializer) && pendingExpressions.length > 0) { + break; + } + pendingExpressions.push(transformInitializedVariable(variable)); + } + if (pendingExpressions.length) { + emitStatement(ts.createExpressionStatement(ts.inlineExpressions(pendingExpressions))); + variablesWritten += pendingExpressions.length; + pendingExpressions = []; + } + } + return undefined; + } + function transformInitializedVariable(node) { + return ts.setSourceMapRange(ts.createAssignment(ts.setSourceMapRange(ts.getSynthesizedClone(node.name), node.name), ts.visitNode(node.initializer, visitor, ts.isExpression)), node); + } + function transformAndEmitIfStatement(node) { + if (containsYield(node)) { + if (containsYield(node.thenStatement) || containsYield(node.elseStatement)) { + var endLabel = defineLabel(); + var elseLabel = node.elseStatement ? defineLabel() : undefined; + emitBreakWhenFalse(node.elseStatement ? elseLabel : endLabel, ts.visitNode(node.expression, visitor, ts.isExpression), node.expression); + transformAndEmitEmbeddedStatement(node.thenStatement); + if (node.elseStatement) { + emitBreak(endLabel); + markLabel(elseLabel); + transformAndEmitEmbeddedStatement(node.elseStatement); + } + markLabel(endLabel); + } + else { + emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + } + else { + emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + } + function transformAndEmitDoStatement(node) { + if (containsYield(node)) { + var conditionLabel = defineLabel(); + var loopLabel = defineLabel(); + beginLoopBlock(conditionLabel); + markLabel(loopLabel); + transformAndEmitEmbeddedStatement(node.statement); + markLabel(conditionLabel); + emitBreakWhenTrue(loopLabel, ts.visitNode(node.expression, visitor, ts.isExpression)); + endLoopBlock(); + } + else { + emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + } + function visitDoStatement(node) { + if (inStatementContainingYield) { + beginScriptLoopBlock(); + node = ts.visitEachChild(node, visitor, context); + endLoopBlock(); + return node; + } + else { + return ts.visitEachChild(node, visitor, context); + } + } + function transformAndEmitWhileStatement(node) { + if (containsYield(node)) { + var loopLabel = defineLabel(); + var endLabel = beginLoopBlock(loopLabel); + markLabel(loopLabel); + emitBreakWhenFalse(endLabel, ts.visitNode(node.expression, visitor, ts.isExpression)); + transformAndEmitEmbeddedStatement(node.statement); + emitBreak(loopLabel); + endLoopBlock(); + } + else { + emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + } + function visitWhileStatement(node) { + if (inStatementContainingYield) { + beginScriptLoopBlock(); + node = ts.visitEachChild(node, visitor, context); + endLoopBlock(); + return node; + } + else { + return ts.visitEachChild(node, visitor, context); + } + } + function transformAndEmitForStatement(node) { + if (containsYield(node)) { + var conditionLabel = defineLabel(); + var incrementLabel = defineLabel(); + var endLabel = beginLoopBlock(incrementLabel); + if (node.initializer) { + var initializer = node.initializer; + if (ts.isVariableDeclarationList(initializer)) { + transformAndEmitVariableDeclarationList(initializer); + } + else { + emitStatement(ts.setTextRange(ts.createExpressionStatement(ts.visitNode(initializer, visitor, ts.isExpression)), initializer)); + } + } + markLabel(conditionLabel); + if (node.condition) { + emitBreakWhenFalse(endLabel, ts.visitNode(node.condition, visitor, ts.isExpression)); + } + transformAndEmitEmbeddedStatement(node.statement); + markLabel(incrementLabel); + if (node.incrementor) { + emitStatement(ts.setTextRange(ts.createExpressionStatement(ts.visitNode(node.incrementor, visitor, ts.isExpression)), node.incrementor)); + } + emitBreak(conditionLabel); + endLoopBlock(); + } + else { + emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + } + function visitForStatement(node) { + if (inStatementContainingYield) { + beginScriptLoopBlock(); + } + var initializer = node.initializer; + if (initializer && ts.isVariableDeclarationList(initializer)) { + for (var _i = 0, _a = initializer.declarations; _i < _a.length; _i++) { + var variable = _a[_i]; + hoistVariableDeclaration(variable.name); + } + var variables = ts.getInitializedVariables(initializer); + node = ts.updateFor(node, variables.length > 0 + ? ts.inlineExpressions(ts.map(variables, transformInitializedVariable)) + : undefined, ts.visitNode(node.condition, visitor, ts.isExpression), ts.visitNode(node.incrementor, visitor, ts.isExpression), ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); + } + else { + node = ts.visitEachChild(node, visitor, context); + } + if (inStatementContainingYield) { + endLoopBlock(); + } + return node; + } + function transformAndEmitForInStatement(node) { + if (containsYield(node)) { + var keysArray = declareLocal(); + var key = declareLocal(); + var keysIndex = ts.createLoopVariable(); + var initializer = node.initializer; + hoistVariableDeclaration(keysIndex); + emitAssignment(keysArray, ts.createArrayLiteral()); + emitStatement(ts.createForIn(key, ts.visitNode(node.expression, visitor, ts.isExpression), ts.createExpressionStatement(ts.createCall(ts.createPropertyAccess(keysArray, "push"), undefined, [key])))); + emitAssignment(keysIndex, ts.createLiteral(0)); + var conditionLabel = defineLabel(); + var incrementLabel = defineLabel(); + var endLabel = beginLoopBlock(incrementLabel); + markLabel(conditionLabel); + emitBreakWhenFalse(endLabel, ts.createLessThan(keysIndex, ts.createPropertyAccess(keysArray, "length"))); + var variable = void 0; + if (ts.isVariableDeclarationList(initializer)) { + for (var _i = 0, _a = initializer.declarations; _i < _a.length; _i++) { + var variable_1 = _a[_i]; + hoistVariableDeclaration(variable_1.name); + } + variable = ts.getSynthesizedClone(initializer.declarations[0].name); + } + else { + variable = ts.visitNode(initializer, visitor, ts.isExpression); + ts.Debug.assert(ts.isLeftHandSideExpression(variable)); + } + emitAssignment(variable, ts.createElementAccess(keysArray, keysIndex)); + transformAndEmitEmbeddedStatement(node.statement); + markLabel(incrementLabel); + emitStatement(ts.createExpressionStatement(ts.createPostfixIncrement(keysIndex))); + emitBreak(conditionLabel); + endLoopBlock(); + } + else { + emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + } + function visitForInStatement(node) { + if (inStatementContainingYield) { + beginScriptLoopBlock(); + } + var initializer = node.initializer; + if (ts.isVariableDeclarationList(initializer)) { + for (var _i = 0, _a = initializer.declarations; _i < _a.length; _i++) { + var variable = _a[_i]; + hoistVariableDeclaration(variable.name); + } + node = ts.updateForIn(node, initializer.declarations[0].name, ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); + } + else { + node = ts.visitEachChild(node, visitor, context); + } + if (inStatementContainingYield) { + endLoopBlock(); + } + return node; + } + function transformAndEmitContinueStatement(node) { + var label = findContinueTarget(node.label ? ts.idText(node.label) : undefined); + if (label > 0) { + emitBreak(label, node); + } + else { + emitStatement(node); + } + } + function visitContinueStatement(node) { + if (inStatementContainingYield) { + var label = findContinueTarget(node.label && ts.idText(node.label)); + if (label > 0) { + return createInlineBreak(label, node); + } + } + return ts.visitEachChild(node, visitor, context); + } + function transformAndEmitBreakStatement(node) { + var label = findBreakTarget(node.label ? ts.idText(node.label) : undefined); + if (label > 0) { + emitBreak(label, node); + } + else { + emitStatement(node); + } + } + function visitBreakStatement(node) { + if (inStatementContainingYield) { + var label = findBreakTarget(node.label && ts.idText(node.label)); + if (label > 0) { + return createInlineBreak(label, node); + } + } + return ts.visitEachChild(node, visitor, context); + } + function transformAndEmitReturnStatement(node) { + emitReturn(ts.visitNode(node.expression, visitor, ts.isExpression), node); + } + function visitReturnStatement(node) { + return createInlineReturn(ts.visitNode(node.expression, visitor, ts.isExpression), node); + } + function transformAndEmitWithStatement(node) { + if (containsYield(node)) { + beginWithBlock(cacheExpression(ts.visitNode(node.expression, visitor, ts.isExpression))); + transformAndEmitEmbeddedStatement(node.statement); + endWithBlock(); + } + else { + emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + } + function transformAndEmitSwitchStatement(node) { + if (containsYield(node.caseBlock)) { + var caseBlock = node.caseBlock; + var numClauses = caseBlock.clauses.length; + var endLabel = beginSwitchBlock(); + var expression = cacheExpression(ts.visitNode(node.expression, visitor, ts.isExpression)); + var clauseLabels = []; + var defaultClauseIndex = -1; + for (var i = 0; i < numClauses; i++) { + var clause = caseBlock.clauses[i]; + clauseLabels.push(defineLabel()); + if (clause.kind === 272 && defaultClauseIndex === -1) { + defaultClauseIndex = i; + } + } + var clausesWritten = 0; + var pendingClauses = []; + while (clausesWritten < numClauses) { + var defaultClausesSkipped = 0; + for (var i = clausesWritten; i < numClauses; i++) { + var clause = caseBlock.clauses[i]; + if (clause.kind === 271) { + if (containsYield(clause.expression) && pendingClauses.length > 0) { + break; + } + pendingClauses.push(ts.createCaseClause(ts.visitNode(clause.expression, visitor, ts.isExpression), [ + createInlineBreak(clauseLabels[i], clause.expression) + ])); + } + else { + defaultClausesSkipped++; + } + } + if (pendingClauses.length) { + emitStatement(ts.createSwitch(expression, ts.createCaseBlock(pendingClauses))); + clausesWritten += pendingClauses.length; + pendingClauses = []; + } + if (defaultClausesSkipped > 0) { + clausesWritten += defaultClausesSkipped; + defaultClausesSkipped = 0; + } + } + if (defaultClauseIndex >= 0) { + emitBreak(clauseLabels[defaultClauseIndex]); + } + else { + emitBreak(endLabel); + } + for (var i = 0; i < numClauses; i++) { + markLabel(clauseLabels[i]); + transformAndEmitStatements(caseBlock.clauses[i].statements); + } + endSwitchBlock(); + } + else { + emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + } + function visitSwitchStatement(node) { + if (inStatementContainingYield) { + beginScriptSwitchBlock(); + } + node = ts.visitEachChild(node, visitor, context); + if (inStatementContainingYield) { + endSwitchBlock(); + } + return node; + } + function transformAndEmitLabeledStatement(node) { + if (containsYield(node)) { + beginLabeledBlock(ts.idText(node.label)); + transformAndEmitEmbeddedStatement(node.statement); + endLabeledBlock(); + } + else { + emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + } + function visitLabeledStatement(node) { + if (inStatementContainingYield) { + beginScriptLabeledBlock(ts.idText(node.label)); + } + node = ts.visitEachChild(node, visitor, context); + if (inStatementContainingYield) { + endLabeledBlock(); + } + return node; + } + function transformAndEmitThrowStatement(node) { + emitThrow(ts.visitNode(node.expression, visitor, ts.isExpression), node); + } + function transformAndEmitTryStatement(node) { + if (containsYield(node)) { + beginExceptionBlock(); + transformAndEmitEmbeddedStatement(node.tryBlock); + if (node.catchClause) { + beginCatchBlock(node.catchClause.variableDeclaration); + transformAndEmitEmbeddedStatement(node.catchClause.block); + } + if (node.finallyBlock) { + beginFinallyBlock(); + transformAndEmitEmbeddedStatement(node.finallyBlock); + } + endExceptionBlock(); + } + else { + emitStatement(ts.visitEachChild(node, visitor, context)); + } + } + function containsYield(node) { + return !!node && (node.transformFlags & 4194304) !== 0; + } + function countInitialNodesWithoutYield(nodes) { + var numNodes = nodes.length; + for (var i = 0; i < numNodes; i++) { + if (containsYield(nodes[i])) { + return i; + } + } + return -1; + } + function onSubstituteNode(hint, node) { + node = previousOnSubstituteNode(hint, node); + if (hint === 1) { + return substituteExpression(node); + } + return node; + } + function substituteExpression(node) { + if (ts.isIdentifier(node)) { + return substituteExpressionIdentifier(node); + } + return node; + } + function substituteExpressionIdentifier(node) { + if (!ts.isGeneratedIdentifier(node) && renamedCatchVariables && renamedCatchVariables.has(ts.idText(node))) { + var original = ts.getOriginalNode(node); + if (ts.isIdentifier(original) && original.parent) { + var declaration = resolver.getReferencedValueDeclaration(original); + if (declaration) { + var name = renamedCatchVariableDeclarations[ts.getOriginalNodeId(declaration)]; + if (name) { + var clone_7 = ts.getMutableClone(name); + ts.setSourceMapRange(clone_7, node); + ts.setCommentRange(clone_7, node); + return clone_7; + } + } + } + } + return node; + } + function cacheExpression(node) { + var temp; + if (ts.isGeneratedIdentifier(node) || ts.getEmitFlags(node) & 4096) { + return node; + } + temp = ts.createTempVariable(hoistVariableDeclaration); + emitAssignment(temp, node, node); + return temp; + } + function declareLocal(name) { + var temp = name + ? ts.createUniqueName(name) + : ts.createTempVariable(undefined); + hoistVariableDeclaration(temp); + return temp; + } + function defineLabel() { + if (!labelOffsets) { + labelOffsets = []; + } + var label = nextLabelId; + nextLabelId++; + labelOffsets[label] = -1; + return label; + } + function markLabel(label) { + ts.Debug.assert(labelOffsets !== undefined, "No labels were defined."); + labelOffsets[label] = operations ? operations.length : 0; + } + function beginBlock(block) { + if (!blocks) { + blocks = []; + blockActions = []; + blockOffsets = []; + blockStack = []; + } + var index = blockActions.length; + blockActions[index] = 0; + blockOffsets[index] = operations ? operations.length : 0; + blocks[index] = block; + blockStack.push(block); + return index; + } + function endBlock() { + var block = peekBlock(); + if (block === undefined) + return ts.Debug.fail("beginBlock was never called."); + var index = blockActions.length; + blockActions[index] = 1; + blockOffsets[index] = operations ? operations.length : 0; + blocks[index] = block; + blockStack.pop(); + return block; + } + function peekBlock() { + return ts.lastOrUndefined(blockStack); + } + function peekBlockKind() { + var block = peekBlock(); + return block && block.kind; + } + function beginWithBlock(expression) { + var startLabel = defineLabel(); + var endLabel = defineLabel(); + markLabel(startLabel); + beginBlock({ + kind: 1, + expression: expression, + startLabel: startLabel, + endLabel: endLabel + }); + } + function endWithBlock() { + ts.Debug.assert(peekBlockKind() === 1); + var block = endBlock(); + markLabel(block.endLabel); + } + function beginExceptionBlock() { + var startLabel = defineLabel(); + var endLabel = defineLabel(); + markLabel(startLabel); + beginBlock({ + kind: 0, + state: 0, + startLabel: startLabel, + endLabel: endLabel + }); + emitNop(); + return endLabel; + } + function beginCatchBlock(variable) { + ts.Debug.assert(peekBlockKind() === 0); + var name; + if (ts.isGeneratedIdentifier(variable.name)) { + name = variable.name; + hoistVariableDeclaration(variable.name); + } + else { + var text = ts.idText(variable.name); + name = declareLocal(text); + if (!renamedCatchVariables) { + renamedCatchVariables = ts.createMap(); + renamedCatchVariableDeclarations = []; + context.enableSubstitution(72); + } + renamedCatchVariables.set(text, true); + renamedCatchVariableDeclarations[ts.getOriginalNodeId(variable)] = name; + } + var exception = peekBlock(); + ts.Debug.assert(exception.state < 1); + var endLabel = exception.endLabel; + emitBreak(endLabel); + var catchLabel = defineLabel(); + markLabel(catchLabel); + exception.state = 1; + exception.catchVariable = name; + exception.catchLabel = catchLabel; + emitAssignment(name, ts.createCall(ts.createPropertyAccess(state, "sent"), undefined, [])); + emitNop(); + } + function beginFinallyBlock() { + ts.Debug.assert(peekBlockKind() === 0); + var exception = peekBlock(); + ts.Debug.assert(exception.state < 2); + var endLabel = exception.endLabel; + emitBreak(endLabel); + var finallyLabel = defineLabel(); + markLabel(finallyLabel); + exception.state = 2; + exception.finallyLabel = finallyLabel; + } + function endExceptionBlock() { + ts.Debug.assert(peekBlockKind() === 0); + var exception = endBlock(); + var state = exception.state; + if (state < 2) { + emitBreak(exception.endLabel); + } + else { + emitEndfinally(); + } + markLabel(exception.endLabel); + emitNop(); + exception.state = 3; + } + function beginScriptLoopBlock() { + beginBlock({ + kind: 3, + isScript: true, + breakLabel: -1, + continueLabel: -1 + }); + } + function beginLoopBlock(continueLabel) { + var breakLabel = defineLabel(); + beginBlock({ + kind: 3, + isScript: false, + breakLabel: breakLabel, + continueLabel: continueLabel, + }); + return breakLabel; + } + function endLoopBlock() { + ts.Debug.assert(peekBlockKind() === 3); + var block = endBlock(); + var breakLabel = block.breakLabel; + if (!block.isScript) { + markLabel(breakLabel); + } + } + function beginScriptSwitchBlock() { + beginBlock({ + kind: 2, + isScript: true, + breakLabel: -1 + }); + } + function beginSwitchBlock() { + var breakLabel = defineLabel(); + beginBlock({ + kind: 2, + isScript: false, + breakLabel: breakLabel, + }); + return breakLabel; + } + function endSwitchBlock() { + ts.Debug.assert(peekBlockKind() === 2); + var block = endBlock(); + var breakLabel = block.breakLabel; + if (!block.isScript) { + markLabel(breakLabel); + } + } + function beginScriptLabeledBlock(labelText) { + beginBlock({ + kind: 4, + isScript: true, + labelText: labelText, + breakLabel: -1 + }); + } + function beginLabeledBlock(labelText) { + var breakLabel = defineLabel(); + beginBlock({ + kind: 4, + isScript: false, + labelText: labelText, + breakLabel: breakLabel + }); + } + function endLabeledBlock() { + ts.Debug.assert(peekBlockKind() === 4); + var block = endBlock(); + if (!block.isScript) { + markLabel(block.breakLabel); + } + } + function supportsUnlabeledBreak(block) { + return block.kind === 2 + || block.kind === 3; + } + function supportsLabeledBreakOrContinue(block) { + return block.kind === 4; + } + function supportsUnlabeledContinue(block) { + return block.kind === 3; + } + function hasImmediateContainingLabeledBlock(labelText, start) { + for (var j = start; j >= 0; j--) { + var containingBlock = blockStack[j]; + if (supportsLabeledBreakOrContinue(containingBlock)) { + if (containingBlock.labelText === labelText) { + return true; + } + } + else { + break; + } + } + return false; + } + function findBreakTarget(labelText) { + if (blockStack) { + if (labelText) { + for (var i = blockStack.length - 1; i >= 0; i--) { + var block = blockStack[i]; + if (supportsLabeledBreakOrContinue(block) && block.labelText === labelText) { + return block.breakLabel; + } + else if (supportsUnlabeledBreak(block) && hasImmediateContainingLabeledBlock(labelText, i - 1)) { + return block.breakLabel; + } + } + } + else { + for (var i = blockStack.length - 1; i >= 0; i--) { + var block = blockStack[i]; + if (supportsUnlabeledBreak(block)) { + return block.breakLabel; + } + } + } + } + return 0; + } + function findContinueTarget(labelText) { + if (blockStack) { + if (labelText) { + for (var i = blockStack.length - 1; i >= 0; i--) { + var block = blockStack[i]; + if (supportsUnlabeledContinue(block) && hasImmediateContainingLabeledBlock(labelText, i - 1)) { + return block.continueLabel; + } + } + } + else { + for (var i = blockStack.length - 1; i >= 0; i--) { + var block = blockStack[i]; + if (supportsUnlabeledContinue(block)) { + return block.continueLabel; + } + } + } + } + return 0; + } + function createLabel(label) { + if (label !== undefined && label > 0) { + if (labelExpressions === undefined) { + labelExpressions = []; + } + var expression = ts.createLiteral(-1); + if (labelExpressions[label] === undefined) { + labelExpressions[label] = [expression]; + } + else { + labelExpressions[label].push(expression); + } + return expression; + } + return ts.createOmittedExpression(); + } + function createInstruction(instruction) { + var literal = ts.createLiteral(instruction); + ts.addSyntheticTrailingComment(literal, 3, getInstructionName(instruction)); + return literal; + } + function createInlineBreak(label, location) { + ts.Debug.assertLessThan(0, label, "Invalid label"); + return ts.setTextRange(ts.createReturn(ts.createArrayLiteral([ + createInstruction(3), + createLabel(label) + ])), location); + } + function createInlineReturn(expression, location) { + return ts.setTextRange(ts.createReturn(ts.createArrayLiteral(expression + ? [createInstruction(2), expression] + : [createInstruction(2)])), location); + } + function createGeneratorResume(location) { + return ts.setTextRange(ts.createCall(ts.createPropertyAccess(state, "sent"), undefined, []), location); + } + function emitNop() { + emitWorker(0); + } + function emitStatement(node) { + if (node) { + emitWorker(1, [node]); + } + else { + emitNop(); + } + } + function emitAssignment(left, right, location) { + emitWorker(2, [left, right], location); + } + function emitBreak(label, location) { + emitWorker(3, [label], location); + } + function emitBreakWhenTrue(label, condition, location) { + emitWorker(4, [label, condition], location); + } + function emitBreakWhenFalse(label, condition, location) { + emitWorker(5, [label, condition], location); + } + function emitYieldStar(expression, location) { + emitWorker(7, [expression], location); + } + function emitYield(expression, location) { + emitWorker(6, [expression], location); + } + function emitReturn(expression, location) { + emitWorker(8, [expression], location); + } + function emitThrow(expression, location) { + emitWorker(9, [expression], location); + } + function emitEndfinally() { + emitWorker(10); + } + function emitWorker(code, args, location) { + if (operations === undefined) { + operations = []; + operationArguments = []; + operationLocations = []; + } + if (labelOffsets === undefined) { + markLabel(defineLabel()); + } + var operationIndex = operations.length; + operations[operationIndex] = code; + operationArguments[operationIndex] = args; + operationLocations[operationIndex] = location; + } + function build() { + blockIndex = 0; + labelNumber = 0; + labelNumbers = undefined; + lastOperationWasAbrupt = false; + lastOperationWasCompletion = false; + clauses = undefined; + statements = undefined; + exceptionBlockStack = undefined; + currentExceptionBlock = undefined; + withBlockStack = undefined; + var buildResult = buildStatements(); + return createGeneratorHelper(context, ts.setEmitFlags(ts.createFunctionExpression(undefined, undefined, undefined, undefined, [ts.createParameter(undefined, undefined, undefined, state)], undefined, ts.createBlock(buildResult, buildResult.length > 0)), 524288)); + } + function buildStatements() { + if (operations) { + for (var operationIndex = 0; operationIndex < operations.length; operationIndex++) { + writeOperation(operationIndex); + } + flushFinalLabel(operations.length); + } + else { + flushFinalLabel(0); + } + if (clauses) { + var labelExpression = ts.createPropertyAccess(state, "label"); + var switchStatement = ts.createSwitch(labelExpression, ts.createCaseBlock(clauses)); + return [ts.startOnNewLine(switchStatement)]; + } + if (statements) { + return statements; + } + return []; + } + function flushLabel() { + if (!statements) { + return; + } + appendLabel(!lastOperationWasAbrupt); + lastOperationWasAbrupt = false; + lastOperationWasCompletion = false; + labelNumber++; + } + function flushFinalLabel(operationIndex) { + if (isFinalLabelReachable(operationIndex)) { + tryEnterLabel(operationIndex); + withBlockStack = undefined; + writeReturn(undefined, undefined); + } + if (statements && clauses) { + appendLabel(false); + } + updateLabelExpressions(); + } + function isFinalLabelReachable(operationIndex) { + if (!lastOperationWasCompletion) { + return true; + } + if (!labelOffsets || !labelExpressions) { + return false; + } + for (var label = 0; label < labelOffsets.length; label++) { + if (labelOffsets[label] === operationIndex && labelExpressions[label]) { + return true; + } + } + return false; + } + function appendLabel(markLabelEnd) { + if (!clauses) { + clauses = []; + } + if (statements) { + if (withBlockStack) { + for (var i = withBlockStack.length - 1; i >= 0; i--) { + var withBlock = withBlockStack[i]; + statements = [ts.createWith(withBlock.expression, ts.createBlock(statements))]; + } + } + if (currentExceptionBlock) { + var startLabel = currentExceptionBlock.startLabel, catchLabel = currentExceptionBlock.catchLabel, finallyLabel = currentExceptionBlock.finallyLabel, endLabel = currentExceptionBlock.endLabel; + statements.unshift(ts.createExpressionStatement(ts.createCall(ts.createPropertyAccess(ts.createPropertyAccess(state, "trys"), "push"), undefined, [ + ts.createArrayLiteral([ + createLabel(startLabel), + createLabel(catchLabel), + createLabel(finallyLabel), + createLabel(endLabel) + ]) + ]))); + currentExceptionBlock = undefined; + } + if (markLabelEnd) { + statements.push(ts.createExpressionStatement(ts.createAssignment(ts.createPropertyAccess(state, "label"), ts.createLiteral(labelNumber + 1)))); + } + } + clauses.push(ts.createCaseClause(ts.createLiteral(labelNumber), statements || [])); + statements = undefined; + } + function tryEnterLabel(operationIndex) { + if (!labelOffsets) { + return; + } + for (var label = 0; label < labelOffsets.length; label++) { + if (labelOffsets[label] === operationIndex) { + flushLabel(); + if (labelNumbers === undefined) { + labelNumbers = []; + } + if (labelNumbers[labelNumber] === undefined) { + labelNumbers[labelNumber] = [label]; + } + else { + labelNumbers[labelNumber].push(label); + } + } + } + } + function updateLabelExpressions() { + if (labelExpressions !== undefined && labelNumbers !== undefined) { + for (var labelNumber_1 = 0; labelNumber_1 < labelNumbers.length; labelNumber_1++) { + var labels = labelNumbers[labelNumber_1]; + if (labels !== undefined) { + for (var _i = 0, labels_1 = labels; _i < labels_1.length; _i++) { + var label = labels_1[_i]; + var expressions = labelExpressions[label]; + if (expressions !== undefined) { + for (var _a = 0, expressions_1 = expressions; _a < expressions_1.length; _a++) { + var expression = expressions_1[_a]; + expression.text = String(labelNumber_1); + } + } + } + } + } + } + } + function tryEnterOrLeaveBlock(operationIndex) { + if (blocks) { + for (; blockIndex < blockActions.length && blockOffsets[blockIndex] <= operationIndex; blockIndex++) { + var block = blocks[blockIndex]; + var blockAction = blockActions[blockIndex]; + switch (block.kind) { + case 0: + if (blockAction === 0) { + if (!exceptionBlockStack) { + exceptionBlockStack = []; + } + if (!statements) { + statements = []; + } + exceptionBlockStack.push(currentExceptionBlock); + currentExceptionBlock = block; + } + else if (blockAction === 1) { + currentExceptionBlock = exceptionBlockStack.pop(); + } + break; + case 1: + if (blockAction === 0) { + if (!withBlockStack) { + withBlockStack = []; + } + withBlockStack.push(block); + } + else if (blockAction === 1) { + withBlockStack.pop(); + } + break; + } + } + } + } + function writeOperation(operationIndex) { + tryEnterLabel(operationIndex); + tryEnterOrLeaveBlock(operationIndex); + if (lastOperationWasAbrupt) { + return; + } + lastOperationWasAbrupt = false; + lastOperationWasCompletion = false; + var opcode = operations[operationIndex]; + if (opcode === 0) { + return; + } + else if (opcode === 10) { + return writeEndfinally(); + } + var args = operationArguments[operationIndex]; + if (opcode === 1) { + return writeStatement(args[0]); + } + var location = operationLocations[operationIndex]; + switch (opcode) { + case 2: + return writeAssign(args[0], args[1], location); + case 3: + return writeBreak(args[0], location); + case 4: + return writeBreakWhenTrue(args[0], args[1], location); + case 5: + return writeBreakWhenFalse(args[0], args[1], location); + case 6: + return writeYield(args[0], location); + case 7: + return writeYieldStar(args[0], location); + case 8: + return writeReturn(args[0], location); + case 9: + return writeThrow(args[0], location); + } + } + function writeStatement(statement) { + if (statement) { + if (!statements) { + statements = [statement]; + } + else { + statements.push(statement); + } + } + } + function writeAssign(left, right, operationLocation) { + writeStatement(ts.setTextRange(ts.createExpressionStatement(ts.createAssignment(left, right)), operationLocation)); + } + function writeThrow(expression, operationLocation) { + lastOperationWasAbrupt = true; + lastOperationWasCompletion = true; + writeStatement(ts.setTextRange(ts.createThrow(expression), operationLocation)); + } + function writeReturn(expression, operationLocation) { + lastOperationWasAbrupt = true; + lastOperationWasCompletion = true; + writeStatement(ts.setEmitFlags(ts.setTextRange(ts.createReturn(ts.createArrayLiteral(expression + ? [createInstruction(2), expression] + : [createInstruction(2)])), operationLocation), 384)); + } + function writeBreak(label, operationLocation) { + lastOperationWasAbrupt = true; + writeStatement(ts.setEmitFlags(ts.setTextRange(ts.createReturn(ts.createArrayLiteral([ + createInstruction(3), + createLabel(label) + ])), operationLocation), 384)); + } + function writeBreakWhenTrue(label, condition, operationLocation) { + writeStatement(ts.setEmitFlags(ts.createIf(condition, ts.setEmitFlags(ts.setTextRange(ts.createReturn(ts.createArrayLiteral([ + createInstruction(3), + createLabel(label) + ])), operationLocation), 384)), 1)); + } + function writeBreakWhenFalse(label, condition, operationLocation) { + writeStatement(ts.setEmitFlags(ts.createIf(ts.createLogicalNot(condition), ts.setEmitFlags(ts.setTextRange(ts.createReturn(ts.createArrayLiteral([ + createInstruction(3), + createLabel(label) + ])), operationLocation), 384)), 1)); + } + function writeYield(expression, operationLocation) { + lastOperationWasAbrupt = true; + writeStatement(ts.setEmitFlags(ts.setTextRange(ts.createReturn(ts.createArrayLiteral(expression + ? [createInstruction(4), expression] + : [createInstruction(4)])), operationLocation), 384)); + } + function writeYieldStar(expression, operationLocation) { + lastOperationWasAbrupt = true; + writeStatement(ts.setEmitFlags(ts.setTextRange(ts.createReturn(ts.createArrayLiteral([ + createInstruction(5), + expression + ])), operationLocation), 384)); + } + function writeEndfinally() { + lastOperationWasAbrupt = true; + writeStatement(ts.createReturn(ts.createArrayLiteral([ + createInstruction(7) + ]))); + } + } + ts.transformGenerators = transformGenerators; + function createGeneratorHelper(context, body) { + context.requestEmitHelper(generatorHelper); + return ts.createCall(ts.getHelperName("__generator"), undefined, [ts.createThis(), body]); + } + var generatorHelper = { + name: "typescript:generator", + scoped: false, + priority: 6, + text: "\n var __generator = (this && this.__generator) || function (thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (_) try {\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [op[0] & 2, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n };" + }; +})(ts || (ts = {})); +var ts; +(function (ts) { + function transformModule(context) { + function getTransformModuleDelegate(moduleKind) { + switch (moduleKind) { + case ts.ModuleKind.AMD: return transformAMDModule; + case ts.ModuleKind.UMD: return transformUMDModule; + default: return transformCommonJSModule; + } + } + var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; + var compilerOptions = context.getCompilerOptions(); + var resolver = context.getEmitResolver(); + var host = context.getEmitHost(); + var languageVersion = ts.getEmitScriptTarget(compilerOptions); + var moduleKind = ts.getEmitModuleKind(compilerOptions); + var previousOnSubstituteNode = context.onSubstituteNode; + var previousOnEmitNode = context.onEmitNode; + context.onSubstituteNode = onSubstituteNode; + context.onEmitNode = onEmitNode; + context.enableSubstitution(72); + context.enableSubstitution(204); + context.enableSubstitution(202); + context.enableSubstitution(203); + context.enableSubstitution(276); + context.enableEmitNotification(279); + var moduleInfoMap = []; + var deferredExports = []; + var currentSourceFile; + var currentModuleInfo; + var noSubstitution; + var needUMDDynamicImportHelper; + return ts.chainBundle(transformSourceFile); + function transformSourceFile(node) { + if (node.isDeclarationFile || + !(ts.isEffectiveExternalModule(node, compilerOptions) || + node.transformFlags & 16777216 || + (ts.isJsonSourceFile(node) && ts.hasJsonModuleEmitEnabled(compilerOptions) && (compilerOptions.out || compilerOptions.outFile)))) { + return node; + } + currentSourceFile = node; + currentModuleInfo = ts.collectExternalModuleInfo(node, resolver, compilerOptions); + moduleInfoMap[ts.getOriginalNodeId(node)] = currentModuleInfo; + var transformModule = getTransformModuleDelegate(moduleKind); + var updated = transformModule(node); + currentSourceFile = undefined; + currentModuleInfo = undefined; + needUMDDynamicImportHelper = false; + return ts.aggregateTransformFlags(updated); + } + function shouldEmitUnderscoreUnderscoreESModule() { + if (!currentModuleInfo.exportEquals && ts.isExternalModule(currentSourceFile)) { + return true; + } + return false; + } + function transformCommonJSModule(node) { + startLexicalEnvironment(); + var statements = []; + var ensureUseStrict = ts.getStrictOptionValue(compilerOptions, "alwaysStrict") || (!compilerOptions.noImplicitUseStrict && ts.isExternalModule(currentSourceFile)); + var statementOffset = ts.addPrologue(statements, node.statements, ensureUseStrict, sourceElementVisitor); + if (shouldEmitUnderscoreUnderscoreESModule()) { + ts.append(statements, createUnderscoreUnderscoreESModule()); + } + ts.append(statements, ts.visitNode(currentModuleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement)); + ts.addRange(statements, ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset)); + addExportEqualsIfNeeded(statements, false); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + var updated = ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements)); + if (currentModuleInfo.hasExportStarsToExportValues && !compilerOptions.importHelpers) { + ts.addEmitHelper(updated, exportStarHelper); + } + ts.addEmitHelpers(updated, context.readEmitHelpers()); + return updated; + } + function transformAMDModule(node) { + var define = ts.createIdentifier("define"); + var moduleName = ts.tryGetModuleNameFromFile(node, host, compilerOptions); + var jsonSourceFile = ts.isJsonSourceFile(node) && node; + var _a = collectAsynchronousDependencies(node, true), aliasedModuleNames = _a.aliasedModuleNames, unaliasedModuleNames = _a.unaliasedModuleNames, importAliasNames = _a.importAliasNames; + var updated = ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray([ + ts.createExpressionStatement(ts.createCall(define, undefined, (moduleName ? [moduleName] : []).concat([ + ts.createArrayLiteral(jsonSourceFile ? ts.emptyArray : [ + ts.createLiteral("require"), + ts.createLiteral("exports") + ].concat(aliasedModuleNames, unaliasedModuleNames)), + jsonSourceFile ? + jsonSourceFile.statements.length ? jsonSourceFile.statements[0].expression : ts.createObjectLiteral() : + ts.createFunctionExpression(undefined, undefined, undefined, undefined, [ + ts.createParameter(undefined, undefined, undefined, "require"), + ts.createParameter(undefined, undefined, undefined, "exports") + ].concat(importAliasNames), undefined, transformAsynchronousModuleBody(node)) + ]))) + ]), node.statements)); + ts.addEmitHelpers(updated, context.readEmitHelpers()); + return updated; + } + function transformUMDModule(node) { + var _a = collectAsynchronousDependencies(node, false), aliasedModuleNames = _a.aliasedModuleNames, unaliasedModuleNames = _a.unaliasedModuleNames, importAliasNames = _a.importAliasNames; + var moduleName = ts.tryGetModuleNameFromFile(node, host, compilerOptions); + var umdHeader = ts.createFunctionExpression(undefined, undefined, undefined, undefined, [ts.createParameter(undefined, undefined, undefined, "factory")], undefined, ts.setTextRange(ts.createBlock([ + ts.createIf(ts.createLogicalAnd(ts.createTypeCheck(ts.createIdentifier("module"), "object"), ts.createTypeCheck(ts.createPropertyAccess(ts.createIdentifier("module"), "exports"), "object")), ts.createBlock([ + ts.createVariableStatement(undefined, [ + ts.createVariableDeclaration("v", undefined, ts.createCall(ts.createIdentifier("factory"), undefined, [ + ts.createIdentifier("require"), + ts.createIdentifier("exports") + ])) + ]), + ts.setEmitFlags(ts.createIf(ts.createStrictInequality(ts.createIdentifier("v"), ts.createIdentifier("undefined")), ts.createExpressionStatement(ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier("module"), "exports"), ts.createIdentifier("v")))), 1) + ]), ts.createIf(ts.createLogicalAnd(ts.createTypeCheck(ts.createIdentifier("define"), "function"), ts.createPropertyAccess(ts.createIdentifier("define"), "amd")), ts.createBlock([ + ts.createExpressionStatement(ts.createCall(ts.createIdentifier("define"), undefined, (moduleName ? [moduleName] : []).concat([ + ts.createArrayLiteral([ + ts.createLiteral("require"), + ts.createLiteral("exports") + ].concat(aliasedModuleNames, unaliasedModuleNames)), + ts.createIdentifier("factory") + ]))) + ]))) + ], true), undefined)); + var updated = ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray([ + ts.createExpressionStatement(ts.createCall(umdHeader, undefined, [ + ts.createFunctionExpression(undefined, undefined, undefined, undefined, [ + ts.createParameter(undefined, undefined, undefined, "require"), + ts.createParameter(undefined, undefined, undefined, "exports") + ].concat(importAliasNames), undefined, transformAsynchronousModuleBody(node)) + ])) + ]), node.statements)); + ts.addEmitHelpers(updated, context.readEmitHelpers()); + return updated; + } + function collectAsynchronousDependencies(node, includeNonAmdDependencies) { + var aliasedModuleNames = []; + var unaliasedModuleNames = []; + var importAliasNames = []; + for (var _i = 0, _a = node.amdDependencies; _i < _a.length; _i++) { + var amdDependency = _a[_i]; + if (amdDependency.name) { + aliasedModuleNames.push(ts.createLiteral(amdDependency.path)); + importAliasNames.push(ts.createParameter(undefined, undefined, undefined, amdDependency.name)); + } + else { + unaliasedModuleNames.push(ts.createLiteral(amdDependency.path)); + } + } + for (var _b = 0, _c = currentModuleInfo.externalImports; _b < _c.length; _b++) { + var importNode = _c[_b]; + var externalModuleName = ts.getExternalModuleNameLiteral(importNode, currentSourceFile, host, resolver, compilerOptions); + var importAliasName = ts.getLocalNameForExternalImport(importNode, currentSourceFile); + if (externalModuleName) { + if (includeNonAmdDependencies && importAliasName) { + ts.setEmitFlags(importAliasName, 4); + aliasedModuleNames.push(externalModuleName); + importAliasNames.push(ts.createParameter(undefined, undefined, undefined, importAliasName)); + } + else { + unaliasedModuleNames.push(externalModuleName); + } + } + } + return { aliasedModuleNames: aliasedModuleNames, unaliasedModuleNames: unaliasedModuleNames, importAliasNames: importAliasNames }; + } + function getAMDImportExpressionForImport(node) { + if (ts.isImportEqualsDeclaration(node) || ts.isExportDeclaration(node) || !ts.getExternalModuleNameLiteral(node, currentSourceFile, host, resolver, compilerOptions)) { + return undefined; + } + var name = ts.getLocalNameForExternalImport(node, currentSourceFile); + var expr = getHelperExpressionForImport(node, name); + if (expr === name) { + return undefined; + } + return ts.createExpressionStatement(ts.createAssignment(name, expr)); + } + function transformAsynchronousModuleBody(node) { + startLexicalEnvironment(); + var statements = []; + var statementOffset = ts.addPrologue(statements, node.statements, !compilerOptions.noImplicitUseStrict, sourceElementVisitor); + if (shouldEmitUnderscoreUnderscoreESModule()) { + ts.append(statements, createUnderscoreUnderscoreESModule()); + } + ts.append(statements, ts.visitNode(currentModuleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement)); + if (moduleKind === ts.ModuleKind.AMD) { + ts.addRange(statements, ts.mapDefined(currentModuleInfo.externalImports, getAMDImportExpressionForImport)); + } + ts.addRange(statements, ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset)); + addExportEqualsIfNeeded(statements, true); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + var body = ts.createBlock(statements, true); + if (currentModuleInfo.hasExportStarsToExportValues && !compilerOptions.importHelpers) { + ts.addEmitHelper(body, exportStarHelper); + } + if (needUMDDynamicImportHelper) { + ts.addEmitHelper(body, dynamicImportUMDHelper); + } + return body; + } + function addExportEqualsIfNeeded(statements, emitAsReturn) { + if (currentModuleInfo.exportEquals) { + var expressionResult = ts.visitNode(currentModuleInfo.exportEquals.expression, moduleExpressionElementVisitor); + if (expressionResult) { + if (emitAsReturn) { + var statement = ts.createReturn(expressionResult); + ts.setTextRange(statement, currentModuleInfo.exportEquals); + ts.setEmitFlags(statement, 384 | 1536); + statements.push(statement); + } + else { + var statement = ts.createExpressionStatement(ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier("module"), "exports"), expressionResult)); + ts.setTextRange(statement, currentModuleInfo.exportEquals); + ts.setEmitFlags(statement, 1536); + statements.push(statement); + } + } + } + } + function sourceElementVisitor(node) { + switch (node.kind) { + case 249: + return visitImportDeclaration(node); + case 248: + return visitImportEqualsDeclaration(node); + case 255: + return visitExportDeclaration(node); + case 254: + return visitExportAssignment(node); + case 219: + return visitVariableStatement(node); + case 239: + return visitFunctionDeclaration(node); + case 240: + return visitClassDeclaration(node); + case 310: + return visitMergeDeclarationMarker(node); + case 311: + return visitEndOfDeclarationMarker(node); + default: + return ts.visitEachChild(node, moduleExpressionElementVisitor, context); + } + } + function moduleExpressionElementVisitor(node) { + if (!(node.transformFlags & 16777216) && !(node.transformFlags & 2048)) { + return node; + } + if (ts.isImportCall(node)) { + return visitImportCallExpression(node); + } + else if (node.transformFlags & 1024 && ts.isBinaryExpression(node)) { + return visitDestructuringAssignment(node); + } + else { + return ts.visitEachChild(node, moduleExpressionElementVisitor, context); + } + } + function destructuringNeedsFlattening(node) { + if (ts.isObjectLiteralExpression(node)) { + for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { + var elem = _a[_i]; + switch (elem.kind) { + case 275: + if (destructuringNeedsFlattening(elem.initializer)) { + return true; + } + break; + case 276: + if (destructuringNeedsFlattening(elem.name)) { + return true; + } + break; + case 277: + if (destructuringNeedsFlattening(elem.expression)) { + return true; + } + break; + case 156: + case 158: + case 159: + return false; + default: ts.Debug.assertNever(elem, "Unhandled object member kind"); + } + } + } + else if (ts.isArrayLiteralExpression(node)) { + for (var _b = 0, _c = node.elements; _b < _c.length; _b++) { + var elem = _c[_b]; + if (ts.isSpreadElement(elem)) { + if (destructuringNeedsFlattening(elem.expression)) { + return true; + } + } + else if (destructuringNeedsFlattening(elem)) { + return true; + } + } + } + else if (ts.isIdentifier(node)) { + return ts.length(getExports(node)) > (ts.isExportName(node) ? 1 : 0); + } + return false; + } + function visitDestructuringAssignment(node) { + if (destructuringNeedsFlattening(node.left)) { + return ts.flattenDestructuringAssignment(node, moduleExpressionElementVisitor, context, 0, false, createAllExportExpressions); + } + return ts.visitEachChild(node, moduleExpressionElementVisitor, context); + } + function visitImportCallExpression(node) { + var argument = ts.visitNode(ts.firstOrUndefined(node.arguments), moduleExpressionElementVisitor); + var containsLexicalThis = !!(node.transformFlags & 8192); + switch (compilerOptions.module) { + case ts.ModuleKind.AMD: + return createImportCallExpressionAMD(argument, containsLexicalThis); + case ts.ModuleKind.UMD: + return createImportCallExpressionUMD(argument, containsLexicalThis); + case ts.ModuleKind.CommonJS: + default: + return createImportCallExpressionCommonJS(argument, containsLexicalThis); + } + } + function createImportCallExpressionUMD(arg, containsLexicalThis) { + needUMDDynamicImportHelper = true; + if (ts.isSimpleCopiableExpression(arg)) { + var argClone = ts.isGeneratedIdentifier(arg) ? arg : ts.isStringLiteral(arg) ? ts.createLiteral(arg) : ts.setEmitFlags(ts.setTextRange(ts.getSynthesizedClone(arg), arg), 1536); + return ts.createConditional(ts.createIdentifier("__syncRequire"), createImportCallExpressionCommonJS(arg, containsLexicalThis), createImportCallExpressionAMD(argClone, containsLexicalThis)); + } + else { + var temp = ts.createTempVariable(hoistVariableDeclaration); + return ts.createComma(ts.createAssignment(temp, arg), ts.createConditional(ts.createIdentifier("__syncRequire"), createImportCallExpressionCommonJS(temp, containsLexicalThis), createImportCallExpressionAMD(temp, containsLexicalThis))); + } + } + function createImportCallExpressionAMD(arg, containsLexicalThis) { + var resolve = ts.createUniqueName("resolve"); + var reject = ts.createUniqueName("reject"); + var parameters = [ + ts.createParameter(undefined, undefined, undefined, resolve), + ts.createParameter(undefined, undefined, undefined, reject) + ]; + var body = ts.createBlock([ + ts.createExpressionStatement(ts.createCall(ts.createIdentifier("require"), undefined, [ts.createArrayLiteral([arg || ts.createOmittedExpression()]), resolve, reject])) + ]); + var func; + if (languageVersion >= 2) { + func = ts.createArrowFunction(undefined, undefined, parameters, undefined, undefined, body); + } + else { + func = ts.createFunctionExpression(undefined, undefined, undefined, undefined, parameters, undefined, body); + if (containsLexicalThis) { + ts.setEmitFlags(func, 8); + } + } + var promise = ts.createNew(ts.createIdentifier("Promise"), undefined, [func]); + if (compilerOptions.esModuleInterop) { + context.requestEmitHelper(importStarHelper); + return ts.createCall(ts.createPropertyAccess(promise, ts.createIdentifier("then")), undefined, [ts.getHelperName("__importStar")]); + } + return promise; + } + function createImportCallExpressionCommonJS(arg, containsLexicalThis) { + var promiseResolveCall = ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Promise"), "resolve"), undefined, []); + var requireCall = ts.createCall(ts.createIdentifier("require"), undefined, arg ? [arg] : []); + if (compilerOptions.esModuleInterop) { + context.requestEmitHelper(importStarHelper); + requireCall = ts.createCall(ts.getHelperName("__importStar"), undefined, [requireCall]); + } + var func; + if (languageVersion >= 2) { + func = ts.createArrowFunction(undefined, undefined, [], undefined, undefined, requireCall); + } + else { + func = ts.createFunctionExpression(undefined, undefined, undefined, undefined, [], undefined, ts.createBlock([ts.createReturn(requireCall)])); + if (containsLexicalThis) { + ts.setEmitFlags(func, 8); + } + } + return ts.createCall(ts.createPropertyAccess(promiseResolveCall, "then"), undefined, [func]); + } + function getHelperExpressionForImport(node, innerExpr) { + if (!compilerOptions.esModuleInterop || ts.getEmitFlags(node) & 67108864) { + return innerExpr; + } + if (ts.getImportNeedsImportStarHelper(node)) { + context.requestEmitHelper(importStarHelper); + return ts.createCall(ts.getHelperName("__importStar"), undefined, [innerExpr]); + } + if (ts.getImportNeedsImportDefaultHelper(node)) { + context.requestEmitHelper(importDefaultHelper); + return ts.createCall(ts.getHelperName("__importDefault"), undefined, [innerExpr]); + } + return innerExpr; + } + function visitImportDeclaration(node) { + var statements; + var namespaceDeclaration = ts.getNamespaceDeclarationNode(node); + if (moduleKind !== ts.ModuleKind.AMD) { + if (!node.importClause) { + return ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(createRequireCall(node)), node), node); + } + else { + var variables = []; + if (namespaceDeclaration && !ts.isDefaultImport(node)) { + variables.push(ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name), undefined, getHelperExpressionForImport(node, createRequireCall(node)))); + } + else { + variables.push(ts.createVariableDeclaration(ts.getGeneratedNameForNode(node), undefined, getHelperExpressionForImport(node, createRequireCall(node)))); + if (namespaceDeclaration && ts.isDefaultImport(node)) { + variables.push(ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name), undefined, ts.getGeneratedNameForNode(node))); + } + } + statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createVariableStatement(undefined, ts.createVariableDeclarationList(variables, languageVersion >= 2 ? 2 : 0)), node), node)); + } + } + else if (namespaceDeclaration && ts.isDefaultImport(node)) { + statements = ts.append(statements, ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ + ts.setOriginalNode(ts.setTextRange(ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name), undefined, ts.getGeneratedNameForNode(node)), node), node) + ], languageVersion >= 2 ? 2 : 0))); + } + if (hasAssociatedEndOfDeclarationMarker(node)) { + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportsOfImportDeclaration(deferredExports[id], node); + } + else { + statements = appendExportsOfImportDeclaration(statements, node); + } + return ts.singleOrMany(statements); + } + function createRequireCall(importNode) { + var moduleName = ts.getExternalModuleNameLiteral(importNode, currentSourceFile, host, resolver, compilerOptions); + var args = []; + if (moduleName) { + args.push(moduleName); + } + return ts.createCall(ts.createIdentifier("require"), undefined, args); + } + function visitImportEqualsDeclaration(node) { + ts.Debug.assert(ts.isExternalModuleImportEqualsDeclaration(node), "import= for internal module references should be handled in an earlier transformer."); + var statements; + if (moduleKind !== ts.ModuleKind.AMD) { + if (ts.hasModifier(node, 1)) { + statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(createExportExpression(node.name, createRequireCall(node))), node), node)); + } + else { + statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(ts.getSynthesizedClone(node.name), undefined, createRequireCall(node)) + ], languageVersion >= 2 ? 2 : 0)), node), node)); + } + } + else { + if (ts.hasModifier(node, 1)) { + statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(createExportExpression(ts.getExportName(node), ts.getLocalName(node))), node), node)); + } + } + if (hasAssociatedEndOfDeclarationMarker(node)) { + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportsOfImportEqualsDeclaration(deferredExports[id], node); + } + else { + statements = appendExportsOfImportEqualsDeclaration(statements, node); + } + return ts.singleOrMany(statements); + } + function visitExportDeclaration(node) { + if (!node.moduleSpecifier) { + return undefined; + } + var generatedName = ts.getGeneratedNameForNode(node); + if (node.exportClause) { + var statements = []; + if (moduleKind !== ts.ModuleKind.AMD) { + statements.push(ts.setOriginalNode(ts.setTextRange(ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(generatedName, undefined, createRequireCall(node)) + ])), node), node)); + } + for (var _i = 0, _a = node.exportClause.elements; _i < _a.length; _i++) { + var specifier = _a[_i]; + var exportedValue = ts.createPropertyAccess(generatedName, specifier.propertyName || specifier.name); + statements.push(ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(createExportExpression(ts.getExportName(specifier), exportedValue)), specifier), specifier)); + } + return ts.singleOrMany(statements); + } + else { + return ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(createExportStarHelper(context, moduleKind !== ts.ModuleKind.AMD ? createRequireCall(node) : generatedName)), node), node); + } + } + function visitExportAssignment(node) { + if (node.isExportEquals) { + return undefined; + } + var statements; + var original = node.original; + if (original && hasAssociatedEndOfDeclarationMarker(original)) { + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportStatement(deferredExports[id], ts.createIdentifier("default"), ts.visitNode(node.expression, moduleExpressionElementVisitor), node, true); + } + else { + statements = appendExportStatement(statements, ts.createIdentifier("default"), ts.visitNode(node.expression, moduleExpressionElementVisitor), node, true); + } + return ts.singleOrMany(statements); + } + function visitFunctionDeclaration(node) { + var statements; + if (ts.hasModifier(node, 1)) { + statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createFunctionDeclaration(undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, ts.getDeclarationName(node, true, true), undefined, ts.visitNodes(node.parameters, moduleExpressionElementVisitor), undefined, ts.visitEachChild(node.body, moduleExpressionElementVisitor, context)), node), node)); + } + else { + statements = ts.append(statements, ts.visitEachChild(node, moduleExpressionElementVisitor, context)); + } + if (hasAssociatedEndOfDeclarationMarker(node)) { + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node); + } + else { + statements = appendExportsOfHoistedDeclaration(statements, node); + } + return ts.singleOrMany(statements); + } + function visitClassDeclaration(node) { + var statements; + if (ts.hasModifier(node, 1)) { + statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createClassDeclaration(undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.getDeclarationName(node, true, true), undefined, ts.visitNodes(node.heritageClauses, moduleExpressionElementVisitor), ts.visitNodes(node.members, moduleExpressionElementVisitor)), node), node)); + } + else { + statements = ts.append(statements, ts.visitEachChild(node, moduleExpressionElementVisitor, context)); + } + if (hasAssociatedEndOfDeclarationMarker(node)) { + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node); + } + else { + statements = appendExportsOfHoistedDeclaration(statements, node); + } + return ts.singleOrMany(statements); + } + function visitVariableStatement(node) { + var statements; + var variables; + var expressions; + if (ts.hasModifier(node, 1)) { + var modifiers = void 0; + for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { + var variable = _a[_i]; + if (ts.isIdentifier(variable.name) && ts.isLocalName(variable.name)) { + if (!modifiers) { + modifiers = ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier); + } + variables = ts.append(variables, variable); + } + else if (variable.initializer) { + expressions = ts.append(expressions, transformInitializedVariable(variable)); + } + } + if (variables) { + statements = ts.append(statements, ts.updateVariableStatement(node, modifiers, ts.updateVariableDeclarationList(node.declarationList, variables))); + } + if (expressions) { + statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(ts.inlineExpressions(expressions)), node), node)); + } + } + else { + statements = ts.append(statements, ts.visitEachChild(node, moduleExpressionElementVisitor, context)); + } + if (hasAssociatedEndOfDeclarationMarker(node)) { + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node); + } + else { + statements = appendExportsOfVariableStatement(statements, node); + } + return ts.singleOrMany(statements); + } + function createAllExportExpressions(name, value, location) { + var exportedNames = getExports(name); + if (exportedNames) { + var expression = ts.isExportName(name) ? value : ts.createAssignment(name, value); + for (var _i = 0, exportedNames_1 = exportedNames; _i < exportedNames_1.length; _i++) { + var exportName = exportedNames_1[_i]; + ts.setEmitFlags(expression, 4); + expression = createExportExpression(exportName, expression, location); + } + return expression; + } + return ts.createAssignment(name, value); + } + function transformInitializedVariable(node) { + if (ts.isBindingPattern(node.name)) { + return ts.flattenDestructuringAssignment(ts.visitNode(node, moduleExpressionElementVisitor), undefined, context, 0, false, createAllExportExpressions); + } + else { + return ts.createAssignment(ts.setTextRange(ts.createPropertyAccess(ts.createIdentifier("exports"), node.name), node.name), ts.visitNode(node.initializer, moduleExpressionElementVisitor)); + } + } + function visitMergeDeclarationMarker(node) { + if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 219) { + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node.original); + } + return node; + } + function hasAssociatedEndOfDeclarationMarker(node) { + return (ts.getEmitFlags(node) & 4194304) !== 0; + } + function visitEndOfDeclarationMarker(node) { + var id = ts.getOriginalNodeId(node); + var statements = deferredExports[id]; + if (statements) { + delete deferredExports[id]; + return ts.append(statements, node); + } + return node; + } + function appendExportsOfImportDeclaration(statements, decl) { + if (currentModuleInfo.exportEquals) { + return statements; + } + var importClause = decl.importClause; + if (!importClause) { + return statements; + } + if (importClause.name) { + statements = appendExportsOfDeclaration(statements, importClause); + } + var namedBindings = importClause.namedBindings; + if (namedBindings) { + switch (namedBindings.kind) { + case 251: + statements = appendExportsOfDeclaration(statements, namedBindings); + break; + case 252: + for (var _i = 0, _a = namedBindings.elements; _i < _a.length; _i++) { + var importBinding = _a[_i]; + statements = appendExportsOfDeclaration(statements, importBinding); + } + break; + } + } + return statements; + } + function appendExportsOfImportEqualsDeclaration(statements, decl) { + if (currentModuleInfo.exportEquals) { + return statements; + } + return appendExportsOfDeclaration(statements, decl); + } + function appendExportsOfVariableStatement(statements, node) { + if (currentModuleInfo.exportEquals) { + return statements; + } + for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + statements = appendExportsOfBindingElement(statements, decl); + } + return statements; + } + function appendExportsOfBindingElement(statements, decl) { + if (currentModuleInfo.exportEquals) { + return statements; + } + if (ts.isBindingPattern(decl.name)) { + for (var _i = 0, _a = decl.name.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (!ts.isOmittedExpression(element)) { + statements = appendExportsOfBindingElement(statements, element); + } + } + } + else if (!ts.isGeneratedIdentifier(decl.name)) { + statements = appendExportsOfDeclaration(statements, decl); + } + return statements; + } + function appendExportsOfHoistedDeclaration(statements, decl) { + if (currentModuleInfo.exportEquals) { + return statements; + } + if (ts.hasModifier(decl, 1)) { + var exportName = ts.hasModifier(decl, 512) ? ts.createIdentifier("default") : ts.getDeclarationName(decl); + statements = appendExportStatement(statements, exportName, ts.getLocalName(decl), decl); + } + if (decl.name) { + statements = appendExportsOfDeclaration(statements, decl); + } + return statements; + } + function appendExportsOfDeclaration(statements, decl) { + var name = ts.getDeclarationName(decl); + var exportSpecifiers = currentModuleInfo.exportSpecifiers.get(ts.idText(name)); + if (exportSpecifiers) { + for (var _i = 0, exportSpecifiers_1 = exportSpecifiers; _i < exportSpecifiers_1.length; _i++) { + var exportSpecifier = exportSpecifiers_1[_i]; + statements = appendExportStatement(statements, exportSpecifier.name, name, exportSpecifier.name); + } + } + return statements; + } + function appendExportStatement(statements, exportName, expression, location, allowComments) { + statements = ts.append(statements, createExportStatement(exportName, expression, location, allowComments)); + return statements; + } + function createUnderscoreUnderscoreESModule() { + var statement; + if (languageVersion === 0) { + statement = ts.createExpressionStatement(createExportExpression(ts.createIdentifier("__esModule"), ts.createLiteral(true))); + } + else { + statement = ts.createExpressionStatement(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"), undefined, [ + ts.createIdentifier("exports"), + ts.createLiteral("__esModule"), + ts.createObjectLiteral([ + ts.createPropertyAssignment("value", ts.createLiteral(true)) + ]) + ])); + } + ts.setEmitFlags(statement, 1048576); + return statement; + } + function createExportStatement(name, value, location, allowComments) { + var statement = ts.setTextRange(ts.createExpressionStatement(createExportExpression(name, value)), location); + ts.startOnNewLine(statement); + if (!allowComments) { + ts.setEmitFlags(statement, 1536); + } + return statement; + } + function createExportExpression(name, value, location) { + return ts.setTextRange(ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier("exports"), ts.getSynthesizedClone(name)), value), location); + } + function modifierVisitor(node) { + switch (node.kind) { + case 85: + case 80: + return undefined; + } + return node; + } + function onEmitNode(hint, node, emitCallback) { + if (node.kind === 279) { + currentSourceFile = node; + currentModuleInfo = moduleInfoMap[ts.getOriginalNodeId(currentSourceFile)]; + noSubstitution = []; + previousOnEmitNode(hint, node, emitCallback); + currentSourceFile = undefined; + currentModuleInfo = undefined; + noSubstitution = undefined; + } + else { + previousOnEmitNode(hint, node, emitCallback); + } + } + function onSubstituteNode(hint, node) { + node = previousOnSubstituteNode(hint, node); + if (node.id && noSubstitution[node.id]) { + return node; + } + if (hint === 1) { + return substituteExpression(node); + } + else if (ts.isShorthandPropertyAssignment(node)) { + return substituteShorthandPropertyAssignment(node); + } + return node; + } + function substituteShorthandPropertyAssignment(node) { + var name = node.name; + var exportedOrImportedName = substituteExpressionIdentifier(name); + if (exportedOrImportedName !== name) { + if (node.objectAssignmentInitializer) { + var initializer = ts.createAssignment(exportedOrImportedName, node.objectAssignmentInitializer); + return ts.setTextRange(ts.createPropertyAssignment(name, initializer), node); + } + return ts.setTextRange(ts.createPropertyAssignment(name, exportedOrImportedName), node); + } + return node; + } + function substituteExpression(node) { + switch (node.kind) { + case 72: + return substituteExpressionIdentifier(node); + case 204: + return substituteBinaryExpression(node); + case 203: + case 202: + return substituteUnaryExpression(node); + } + return node; + } + function substituteExpressionIdentifier(node) { + if (ts.getEmitFlags(node) & 4096) { + var externalHelpersModuleName = ts.getExternalHelpersModuleName(currentSourceFile); + if (externalHelpersModuleName) { + return ts.createPropertyAccess(externalHelpersModuleName, node); + } + return node; + } + if (!ts.isGeneratedIdentifier(node) && !ts.isLocalName(node)) { + var exportContainer = resolver.getReferencedExportContainer(node, ts.isExportName(node)); + if (exportContainer && exportContainer.kind === 279) { + return ts.setTextRange(ts.createPropertyAccess(ts.createIdentifier("exports"), ts.getSynthesizedClone(node)), node); + } + var importDeclaration = resolver.getReferencedImportDeclaration(node); + if (importDeclaration) { + if (ts.isImportClause(importDeclaration)) { + return ts.setTextRange(ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent), ts.createIdentifier("default")), node); + } + else if (ts.isImportSpecifier(importDeclaration)) { + var name = importDeclaration.propertyName || importDeclaration.name; + return ts.setTextRange(ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent.parent.parent), ts.getSynthesizedClone(name)), node); + } + } + } + return node; + } + function substituteBinaryExpression(node) { + if (ts.isAssignmentOperator(node.operatorToken.kind) + && ts.isIdentifier(node.left) + && !ts.isGeneratedIdentifier(node.left) + && !ts.isLocalName(node.left) + && !ts.isDeclarationNameOfEnumOrNamespace(node.left)) { + var exportedNames = getExports(node.left); + if (exportedNames) { + var expression = node; + for (var _i = 0, exportedNames_2 = exportedNames; _i < exportedNames_2.length; _i++) { + var exportName = exportedNames_2[_i]; + noSubstitution[ts.getNodeId(expression)] = true; + expression = createExportExpression(exportName, expression, node); + } + return expression; + } + } + return node; + } + function substituteUnaryExpression(node) { + if ((node.operator === 44 || node.operator === 45) + && ts.isIdentifier(node.operand) + && !ts.isGeneratedIdentifier(node.operand) + && !ts.isLocalName(node.operand) + && !ts.isDeclarationNameOfEnumOrNamespace(node.operand)) { + var exportedNames = getExports(node.operand); + if (exportedNames) { + var expression = node.kind === 203 + ? ts.setTextRange(ts.createBinary(node.operand, ts.createToken(node.operator === 44 ? 60 : 61), ts.createLiteral(1)), node) + : node; + for (var _i = 0, exportedNames_3 = exportedNames; _i < exportedNames_3.length; _i++) { + var exportName = exportedNames_3[_i]; + noSubstitution[ts.getNodeId(expression)] = true; + expression = createExportExpression(exportName, expression); + } + return expression; + } + } + return node; + } + function getExports(name) { + if (!ts.isGeneratedIdentifier(name)) { + var valueDeclaration = resolver.getReferencedImportDeclaration(name) + || resolver.getReferencedValueDeclaration(name); + if (valueDeclaration) { + return currentModuleInfo + && currentModuleInfo.exportedBindings[ts.getOriginalNodeId(valueDeclaration)]; + } + } + } + } + ts.transformModule = transformModule; + var exportStarHelper = { + name: "typescript:export-star", + scoped: true, + text: "\n function __export(m) {\n for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\n }" + }; + function createExportStarHelper(context, module) { + var compilerOptions = context.getCompilerOptions(); + return compilerOptions.importHelpers + ? ts.createCall(ts.getHelperName("__exportStar"), undefined, [module, ts.createIdentifier("exports")]) + : ts.createCall(ts.createIdentifier("__export"), undefined, [module]); + } + var dynamicImportUMDHelper = { + name: "typescript:dynamicimport-sync-require", + scoped: true, + text: "\n var __syncRequire = typeof module === \"object\" && typeof module.exports === \"object\";" + }; + var importStarHelper = { + name: "typescript:commonjsimportstar", + scoped: false, + text: "\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];\n result[\"default\"] = mod;\n return result;\n};" + }; + var importDefaultHelper = { + name: "typescript:commonjsimportdefault", + scoped: false, + text: "\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};" + }; +})(ts || (ts = {})); +var ts; +(function (ts) { + function transformSystemModule(context) { + var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; + var compilerOptions = context.getCompilerOptions(); + var resolver = context.getEmitResolver(); + var host = context.getEmitHost(); + var previousOnSubstituteNode = context.onSubstituteNode; + var previousOnEmitNode = context.onEmitNode; + context.onSubstituteNode = onSubstituteNode; + context.onEmitNode = onEmitNode; + context.enableSubstitution(72); + context.enableSubstitution(276); + context.enableSubstitution(204); + context.enableSubstitution(202); + context.enableSubstitution(203); + context.enableEmitNotification(279); + var moduleInfoMap = []; + var deferredExports = []; + var exportFunctionsMap = []; + var noSubstitutionMap = []; + var currentSourceFile; + var moduleInfo; + var exportFunction; + var contextObject; + var hoistedStatements; + var enclosingBlockScopedContainer; + var noSubstitution; + return ts.chainBundle(transformSourceFile); + function transformSourceFile(node) { + if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 16777216)) { + return node; + } + var id = ts.getOriginalNodeId(node); + currentSourceFile = node; + enclosingBlockScopedContainer = node; + moduleInfo = moduleInfoMap[id] = ts.collectExternalModuleInfo(node, resolver, compilerOptions); + exportFunction = ts.createUniqueName("exports"); + exportFunctionsMap[id] = exportFunction; + contextObject = ts.createUniqueName("context"); + var dependencyGroups = collectDependencyGroups(moduleInfo.externalImports); + var moduleBodyBlock = createSystemModuleBody(node, dependencyGroups); + var moduleBodyFunction = ts.createFunctionExpression(undefined, undefined, undefined, undefined, [ + ts.createParameter(undefined, undefined, undefined, exportFunction), + ts.createParameter(undefined, undefined, undefined, contextObject) + ], undefined, moduleBodyBlock); + var moduleName = ts.tryGetModuleNameFromFile(node, host, compilerOptions); + var dependencies = ts.createArrayLiteral(ts.map(dependencyGroups, function (dependencyGroup) { return dependencyGroup.name; })); + var updated = ts.setEmitFlags(ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray([ + ts.createExpressionStatement(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("System"), "register"), undefined, moduleName + ? [moduleName, dependencies, moduleBodyFunction] + : [dependencies, moduleBodyFunction])) + ]), node.statements)), 1024); + if (!(compilerOptions.outFile || compilerOptions.out)) { + ts.moveEmitHelpers(updated, moduleBodyBlock, function (helper) { return !helper.scoped; }); + } + if (noSubstitution) { + noSubstitutionMap[id] = noSubstitution; + noSubstitution = undefined; + } + currentSourceFile = undefined; + moduleInfo = undefined; + exportFunction = undefined; + contextObject = undefined; + hoistedStatements = undefined; + enclosingBlockScopedContainer = undefined; + return ts.aggregateTransformFlags(updated); + } + function collectDependencyGroups(externalImports) { + var groupIndices = ts.createMap(); + var dependencyGroups = []; + for (var _i = 0, externalImports_1 = externalImports; _i < externalImports_1.length; _i++) { + var externalImport = externalImports_1[_i]; + var externalModuleName = ts.getExternalModuleNameLiteral(externalImport, currentSourceFile, host, resolver, compilerOptions); + if (externalModuleName) { + var text = externalModuleName.text; + var groupIndex = groupIndices.get(text); + if (groupIndex !== undefined) { + dependencyGroups[groupIndex].externalImports.push(externalImport); + } + else { + groupIndices.set(text, dependencyGroups.length); + dependencyGroups.push({ + name: externalModuleName, + externalImports: [externalImport] + }); + } + } + } + return dependencyGroups; + } + function createSystemModuleBody(node, dependencyGroups) { + var statements = []; + startLexicalEnvironment(); + var ensureUseStrict = ts.getStrictOptionValue(compilerOptions, "alwaysStrict") || (!compilerOptions.noImplicitUseStrict && ts.isExternalModule(currentSourceFile)); + var statementOffset = ts.addPrologue(statements, node.statements, ensureUseStrict, sourceElementVisitor); + statements.push(ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration("__moduleName", undefined, ts.createLogicalAnd(contextObject, ts.createPropertyAccess(contextObject, "id"))) + ]))); + ts.visitNode(moduleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement); + var executeStatements = ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset); + ts.addRange(statements, hoistedStatements); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + var exportStarFunction = addExportStarIfNeeded(statements); + var moduleObject = ts.createObjectLiteral([ + ts.createPropertyAssignment("setters", createSettersArray(exportStarFunction, dependencyGroups)), + ts.createPropertyAssignment("execute", ts.createFunctionExpression(undefined, undefined, undefined, undefined, [], undefined, ts.createBlock(executeStatements, true))) + ]); + moduleObject.multiLine = true; + statements.push(ts.createReturn(moduleObject)); + return ts.createBlock(statements, true); + } + function addExportStarIfNeeded(statements) { + if (!moduleInfo.hasExportStarsToExportValues) { + return; + } + if (!moduleInfo.exportedNames && moduleInfo.exportSpecifiers.size === 0) { + var hasExportDeclarationWithExportClause = false; + for (var _i = 0, _a = moduleInfo.externalImports; _i < _a.length; _i++) { + var externalImport = _a[_i]; + if (externalImport.kind === 255 && externalImport.exportClause) { + hasExportDeclarationWithExportClause = true; + break; + } + } + if (!hasExportDeclarationWithExportClause) { + var exportStarFunction_1 = createExportStarFunction(undefined); + statements.push(exportStarFunction_1); + return exportStarFunction_1.name; + } + } + var exportedNames = []; + if (moduleInfo.exportedNames) { + for (var _b = 0, _c = moduleInfo.exportedNames; _b < _c.length; _b++) { + var exportedLocalName = _c[_b]; + if (exportedLocalName.escapedText === "default") { + continue; + } + exportedNames.push(ts.createPropertyAssignment(ts.createLiteral(exportedLocalName), ts.createTrue())); + } + } + for (var _d = 0, _e = moduleInfo.externalImports; _d < _e.length; _d++) { + var externalImport = _e[_d]; + if (externalImport.kind !== 255) { + continue; + } + if (!externalImport.exportClause) { + continue; + } + for (var _f = 0, _g = externalImport.exportClause.elements; _f < _g.length; _f++) { + var element = _g[_f]; + exportedNames.push(ts.createPropertyAssignment(ts.createLiteral(ts.idText(element.name || element.propertyName)), ts.createTrue())); + } + } + var exportedNamesStorageRef = ts.createUniqueName("exportedNames"); + statements.push(ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(exportedNamesStorageRef, undefined, ts.createObjectLiteral(exportedNames, true)) + ]))); + var exportStarFunction = createExportStarFunction(exportedNamesStorageRef); + statements.push(exportStarFunction); + return exportStarFunction.name; + } + function createExportStarFunction(localNames) { + var exportStarFunction = ts.createUniqueName("exportStar"); + var m = ts.createIdentifier("m"); + var n = ts.createIdentifier("n"); + var exports = ts.createIdentifier("exports"); + var condition = ts.createStrictInequality(n, ts.createLiteral("default")); + if (localNames) { + condition = ts.createLogicalAnd(condition, ts.createLogicalNot(ts.createCall(ts.createPropertyAccess(localNames, "hasOwnProperty"), undefined, [n]))); + } + return ts.createFunctionDeclaration(undefined, undefined, undefined, exportStarFunction, undefined, [ts.createParameter(undefined, undefined, undefined, m)], undefined, ts.createBlock([ + ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(exports, undefined, ts.createObjectLiteral([])) + ])), + ts.createForIn(ts.createVariableDeclarationList([ + ts.createVariableDeclaration(n, undefined) + ]), m, ts.createBlock([ + ts.setEmitFlags(ts.createIf(condition, ts.createExpressionStatement(ts.createAssignment(ts.createElementAccess(exports, n), ts.createElementAccess(m, n)))), 1) + ])), + ts.createExpressionStatement(ts.createCall(exportFunction, undefined, [exports])) + ], true)); + } + function createSettersArray(exportStarFunction, dependencyGroups) { + var setters = []; + for (var _i = 0, dependencyGroups_1 = dependencyGroups; _i < dependencyGroups_1.length; _i++) { + var group_1 = dependencyGroups_1[_i]; + var localName = ts.forEach(group_1.externalImports, function (i) { return ts.getLocalNameForExternalImport(i, currentSourceFile); }); + var parameterName = localName ? ts.getGeneratedNameForNode(localName) : ts.createUniqueName(""); + var statements = []; + for (var _a = 0, _b = group_1.externalImports; _a < _b.length; _a++) { + var entry = _b[_a]; + var importVariableName = ts.getLocalNameForExternalImport(entry, currentSourceFile); + switch (entry.kind) { + case 249: + if (!entry.importClause) { + break; + } + case 248: + ts.Debug.assert(importVariableName !== undefined); + statements.push(ts.createExpressionStatement(ts.createAssignment(importVariableName, parameterName))); + break; + case 255: + ts.Debug.assert(importVariableName !== undefined); + if (entry.exportClause) { + var properties = []; + for (var _c = 0, _d = entry.exportClause.elements; _c < _d.length; _c++) { + var e = _d[_c]; + properties.push(ts.createPropertyAssignment(ts.createLiteral(ts.idText(e.name)), ts.createElementAccess(parameterName, ts.createLiteral(ts.idText(e.propertyName || e.name))))); + } + statements.push(ts.createExpressionStatement(ts.createCall(exportFunction, undefined, [ts.createObjectLiteral(properties, true)]))); + } + else { + statements.push(ts.createExpressionStatement(ts.createCall(exportStarFunction, undefined, [parameterName]))); + } + break; + } + } + setters.push(ts.createFunctionExpression(undefined, undefined, undefined, undefined, [ts.createParameter(undefined, undefined, undefined, parameterName)], undefined, ts.createBlock(statements, true))); + } + return ts.createArrayLiteral(setters, true); + } + function sourceElementVisitor(node) { + switch (node.kind) { + case 249: + return visitImportDeclaration(node); + case 248: + return visitImportEqualsDeclaration(node); + case 255: + return undefined; + case 254: + return visitExportAssignment(node); + default: + return nestedElementVisitor(node); + } + } + function visitImportDeclaration(node) { + var statements; + if (node.importClause) { + hoistVariableDeclaration(ts.getLocalNameForExternalImport(node, currentSourceFile)); + } + if (hasAssociatedEndOfDeclarationMarker(node)) { + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportsOfImportDeclaration(deferredExports[id], node); + } + else { + statements = appendExportsOfImportDeclaration(statements, node); + } + return ts.singleOrMany(statements); + } + function visitImportEqualsDeclaration(node) { + ts.Debug.assert(ts.isExternalModuleImportEqualsDeclaration(node), "import= for internal module references should be handled in an earlier transformer."); + var statements; + hoistVariableDeclaration(ts.getLocalNameForExternalImport(node, currentSourceFile)); + if (hasAssociatedEndOfDeclarationMarker(node)) { + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportsOfImportEqualsDeclaration(deferredExports[id], node); + } + else { + statements = appendExportsOfImportEqualsDeclaration(statements, node); + } + return ts.singleOrMany(statements); + } + function visitExportAssignment(node) { + if (node.isExportEquals) { + return undefined; + } + var expression = ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression); + var original = node.original; + if (original && hasAssociatedEndOfDeclarationMarker(original)) { + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportStatement(deferredExports[id], ts.createIdentifier("default"), expression, true); + } + else { + return createExportStatement(ts.createIdentifier("default"), expression, true); + } + } + function visitFunctionDeclaration(node) { + if (ts.hasModifier(node, 1)) { + hoistedStatements = ts.append(hoistedStatements, ts.updateFunctionDeclaration(node, node.decorators, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, ts.getDeclarationName(node, true, true), undefined, ts.visitNodes(node.parameters, destructuringAndImportCallVisitor, ts.isParameterDeclaration), undefined, ts.visitNode(node.body, destructuringAndImportCallVisitor, ts.isBlock))); + } + else { + hoistedStatements = ts.append(hoistedStatements, ts.visitEachChild(node, destructuringAndImportCallVisitor, context)); + } + if (hasAssociatedEndOfDeclarationMarker(node)) { + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node); + } + else { + hoistedStatements = appendExportsOfHoistedDeclaration(hoistedStatements, node); + } + return undefined; + } + function visitClassDeclaration(node) { + var statements; + var name = ts.getLocalName(node); + hoistVariableDeclaration(name); + statements = ts.append(statements, ts.setTextRange(ts.createExpressionStatement(ts.createAssignment(name, ts.setTextRange(ts.createClassExpression(undefined, node.name, undefined, ts.visitNodes(node.heritageClauses, destructuringAndImportCallVisitor, ts.isHeritageClause), ts.visitNodes(node.members, destructuringAndImportCallVisitor, ts.isClassElement)), node))), node)); + if (hasAssociatedEndOfDeclarationMarker(node)) { + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node); + } + else { + statements = appendExportsOfHoistedDeclaration(statements, node); + } + return ts.singleOrMany(statements); + } + function visitVariableStatement(node) { + if (!shouldHoistVariableDeclarationList(node.declarationList)) { + return ts.visitNode(node, destructuringAndImportCallVisitor, ts.isStatement); + } + var expressions; + var isExportedDeclaration = ts.hasModifier(node, 1); + var isMarkedDeclaration = hasAssociatedEndOfDeclarationMarker(node); + for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { + var variable = _a[_i]; + if (variable.initializer) { + expressions = ts.append(expressions, transformInitializedVariable(variable, isExportedDeclaration && !isMarkedDeclaration)); + } + else { + hoistBindingElement(variable); + } + } + var statements; + if (expressions) { + statements = ts.append(statements, ts.setTextRange(ts.createExpressionStatement(ts.inlineExpressions(expressions)), node)); + } + if (isMarkedDeclaration) { + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node, isExportedDeclaration); + } + else { + statements = appendExportsOfVariableStatement(statements, node, false); + } + return ts.singleOrMany(statements); + } + function hoistBindingElement(node) { + if (ts.isBindingPattern(node.name)) { + for (var _i = 0, _a = node.name.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (!ts.isOmittedExpression(element)) { + hoistBindingElement(element); + } + } + } + else { + hoistVariableDeclaration(ts.getSynthesizedClone(node.name)); + } + } + function shouldHoistVariableDeclarationList(node) { + return (ts.getEmitFlags(node) & 2097152) === 0 + && (enclosingBlockScopedContainer.kind === 279 + || (ts.getOriginalNode(node).flags & 3) === 0); + } + function transformInitializedVariable(node, isExportedDeclaration) { + var createAssignment = isExportedDeclaration ? createExportedVariableAssignment : createNonExportedVariableAssignment; + return ts.isBindingPattern(node.name) + ? ts.flattenDestructuringAssignment(node, destructuringAndImportCallVisitor, context, 0, false, createAssignment) + : node.initializer ? createAssignment(node.name, ts.visitNode(node.initializer, destructuringAndImportCallVisitor, ts.isExpression)) : node.name; + } + function createExportedVariableAssignment(name, value, location) { + return createVariableAssignment(name, value, location, true); + } + function createNonExportedVariableAssignment(name, value, location) { + return createVariableAssignment(name, value, location, false); + } + function createVariableAssignment(name, value, location, isExportedDeclaration) { + hoistVariableDeclaration(ts.getSynthesizedClone(name)); + return isExportedDeclaration + ? createExportExpression(name, preventSubstitution(ts.setTextRange(ts.createAssignment(name, value), location))) + : preventSubstitution(ts.setTextRange(ts.createAssignment(name, value), location)); + } + function visitMergeDeclarationMarker(node) { + if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 219) { + var id = ts.getOriginalNodeId(node); + var isExportedDeclaration = ts.hasModifier(node.original, 1); + deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node.original, isExportedDeclaration); + } + return node; + } + function hasAssociatedEndOfDeclarationMarker(node) { + return (ts.getEmitFlags(node) & 4194304) !== 0; + } + function visitEndOfDeclarationMarker(node) { + var id = ts.getOriginalNodeId(node); + var statements = deferredExports[id]; + if (statements) { + delete deferredExports[id]; + return ts.append(statements, node); + } + else { + var original = ts.getOriginalNode(node); + if (ts.isModuleOrEnumDeclaration(original)) { + return ts.append(appendExportsOfDeclaration(statements, original), node); + } + } + return node; + } + function appendExportsOfImportDeclaration(statements, decl) { + if (moduleInfo.exportEquals) { + return statements; + } + var importClause = decl.importClause; + if (!importClause) { + return statements; + } + if (importClause.name) { + statements = appendExportsOfDeclaration(statements, importClause); + } + var namedBindings = importClause.namedBindings; + if (namedBindings) { + switch (namedBindings.kind) { + case 251: + statements = appendExportsOfDeclaration(statements, namedBindings); + break; + case 252: + for (var _i = 0, _a = namedBindings.elements; _i < _a.length; _i++) { + var importBinding = _a[_i]; + statements = appendExportsOfDeclaration(statements, importBinding); + } + break; + } + } + return statements; + } + function appendExportsOfImportEqualsDeclaration(statements, decl) { + if (moduleInfo.exportEquals) { + return statements; + } + return appendExportsOfDeclaration(statements, decl); + } + function appendExportsOfVariableStatement(statements, node, exportSelf) { + if (moduleInfo.exportEquals) { + return statements; + } + for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + if (decl.initializer || exportSelf) { + statements = appendExportsOfBindingElement(statements, decl, exportSelf); + } + } + return statements; + } + function appendExportsOfBindingElement(statements, decl, exportSelf) { + if (moduleInfo.exportEquals) { + return statements; + } + if (ts.isBindingPattern(decl.name)) { + for (var _i = 0, _a = decl.name.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (!ts.isOmittedExpression(element)) { + statements = appendExportsOfBindingElement(statements, element, exportSelf); + } + } + } + else if (!ts.isGeneratedIdentifier(decl.name)) { + var excludeName = void 0; + if (exportSelf) { + statements = appendExportStatement(statements, decl.name, ts.getLocalName(decl)); + excludeName = ts.idText(decl.name); + } + statements = appendExportsOfDeclaration(statements, decl, excludeName); + } + return statements; + } + function appendExportsOfHoistedDeclaration(statements, decl) { + if (moduleInfo.exportEquals) { + return statements; + } + var excludeName; + if (ts.hasModifier(decl, 1)) { + var exportName = ts.hasModifier(decl, 512) ? ts.createLiteral("default") : decl.name; + statements = appendExportStatement(statements, exportName, ts.getLocalName(decl)); + excludeName = ts.getTextOfIdentifierOrLiteral(exportName); + } + if (decl.name) { + statements = appendExportsOfDeclaration(statements, decl, excludeName); + } + return statements; + } + function appendExportsOfDeclaration(statements, decl, excludeName) { + if (moduleInfo.exportEquals) { + return statements; + } + var name = ts.getDeclarationName(decl); + var exportSpecifiers = moduleInfo.exportSpecifiers.get(ts.idText(name)); + if (exportSpecifiers) { + for (var _i = 0, exportSpecifiers_2 = exportSpecifiers; _i < exportSpecifiers_2.length; _i++) { + var exportSpecifier = exportSpecifiers_2[_i]; + if (exportSpecifier.name.escapedText !== excludeName) { + statements = appendExportStatement(statements, exportSpecifier.name, name); + } + } + } + return statements; + } + function appendExportStatement(statements, exportName, expression, allowComments) { + statements = ts.append(statements, createExportStatement(exportName, expression, allowComments)); + return statements; + } + function createExportStatement(name, value, allowComments) { + var statement = ts.createExpressionStatement(createExportExpression(name, value)); + ts.startOnNewLine(statement); + if (!allowComments) { + ts.setEmitFlags(statement, 1536); + } + return statement; + } + function createExportExpression(name, value) { + var exportName = ts.isIdentifier(name) ? ts.createLiteral(name) : name; + ts.setEmitFlags(value, ts.getEmitFlags(value) | 1536); + return ts.setCommentRange(ts.createCall(exportFunction, undefined, [exportName, value]), value); + } + function nestedElementVisitor(node) { + switch (node.kind) { + case 219: + return visitVariableStatement(node); + case 239: + return visitFunctionDeclaration(node); + case 240: + return visitClassDeclaration(node); + case 225: + return visitForStatement(node); + case 226: + return visitForInStatement(node); + case 227: + return visitForOfStatement(node); + case 223: + return visitDoStatement(node); + case 224: + return visitWhileStatement(node); + case 233: + return visitLabeledStatement(node); + case 231: + return visitWithStatement(node); + case 232: + return visitSwitchStatement(node); + case 246: + return visitCaseBlock(node); + case 271: + return visitCaseClause(node); + case 272: + return visitDefaultClause(node); + case 235: + return visitTryStatement(node); + case 274: + return visitCatchClause(node); + case 218: + return visitBlock(node); + case 310: + return visitMergeDeclarationMarker(node); + case 311: + return visitEndOfDeclarationMarker(node); + default: + return destructuringAndImportCallVisitor(node); + } + } + function visitForStatement(node) { + var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; + enclosingBlockScopedContainer = node; + node = ts.updateFor(node, node.initializer && visitForInitializer(node.initializer), ts.visitNode(node.condition, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.incrementor, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement)); + enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; + return node; + } + function visitForInStatement(node) { + var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; + enclosingBlockScopedContainer = node; + node = ts.updateForIn(node, visitForInitializer(node.initializer), ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock)); + enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; + return node; + } + function visitForOfStatement(node) { + var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; + enclosingBlockScopedContainer = node; + node = ts.updateForOf(node, node.awaitModifier, visitForInitializer(node.initializer), ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock)); + enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; + return node; + } + function shouldHoistForInitializer(node) { + return ts.isVariableDeclarationList(node) + && shouldHoistVariableDeclarationList(node); + } + function visitForInitializer(node) { + if (shouldHoistForInitializer(node)) { + var expressions = void 0; + for (var _i = 0, _a = node.declarations; _i < _a.length; _i++) { + var variable = _a[_i]; + expressions = ts.append(expressions, transformInitializedVariable(variable, false)); + if (!variable.initializer) { + hoistBindingElement(variable); + } + } + return expressions ? ts.inlineExpressions(expressions) : ts.createOmittedExpression(); + } + else { + return ts.visitEachChild(node, nestedElementVisitor, context); + } + } + function visitDoStatement(node) { + return ts.updateDo(node, ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock), ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression)); + } + function visitWhileStatement(node) { + return ts.updateWhile(node, ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock)); + } + function visitLabeledStatement(node) { + return ts.updateLabel(node, node.label, ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock)); + } + function visitWithStatement(node) { + return ts.updateWith(node, ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock)); + } + function visitSwitchStatement(node) { + return ts.updateSwitch(node, ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.caseBlock, nestedElementVisitor, ts.isCaseBlock)); + } + function visitCaseBlock(node) { + var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; + enclosingBlockScopedContainer = node; + node = ts.updateCaseBlock(node, ts.visitNodes(node.clauses, nestedElementVisitor, ts.isCaseOrDefaultClause)); + enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; + return node; + } + function visitCaseClause(node) { + return ts.updateCaseClause(node, ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNodes(node.statements, nestedElementVisitor, ts.isStatement)); + } + function visitDefaultClause(node) { + return ts.visitEachChild(node, nestedElementVisitor, context); + } + function visitTryStatement(node) { + return ts.visitEachChild(node, nestedElementVisitor, context); + } + function visitCatchClause(node) { + var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; + enclosingBlockScopedContainer = node; + node = ts.updateCatchClause(node, node.variableDeclaration, ts.visitNode(node.block, nestedElementVisitor, ts.isBlock)); + enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; + return node; + } + function visitBlock(node) { + var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; + enclosingBlockScopedContainer = node; + node = ts.visitEachChild(node, nestedElementVisitor, context); + enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; + return node; + } + function destructuringAndImportCallVisitor(node) { + if (node.transformFlags & 1024 + && node.kind === 204) { + return visitDestructuringAssignment(node); + } + else if (ts.isImportCall(node)) { + return visitImportCallExpression(node); + } + else if ((node.transformFlags & 2048) || (node.transformFlags & 16777216)) { + return ts.visitEachChild(node, destructuringAndImportCallVisitor, context); + } + else { + return node; + } + } + function visitImportCallExpression(node) { + return ts.createCall(ts.createPropertyAccess(contextObject, ts.createIdentifier("import")), undefined, ts.some(node.arguments) ? [ts.visitNode(node.arguments[0], destructuringAndImportCallVisitor)] : []); + } + function visitDestructuringAssignment(node) { + if (hasExportedReferenceInDestructuringTarget(node.left)) { + return ts.flattenDestructuringAssignment(node, destructuringAndImportCallVisitor, context, 0, true); + } + return ts.visitEachChild(node, destructuringAndImportCallVisitor, context); + } + function hasExportedReferenceInDestructuringTarget(node) { + if (ts.isAssignmentExpression(node, true)) { + return hasExportedReferenceInDestructuringTarget(node.left); + } + else if (ts.isSpreadElement(node)) { + return hasExportedReferenceInDestructuringTarget(node.expression); + } + else if (ts.isObjectLiteralExpression(node)) { + return ts.some(node.properties, hasExportedReferenceInDestructuringTarget); + } + else if (ts.isArrayLiteralExpression(node)) { + return ts.some(node.elements, hasExportedReferenceInDestructuringTarget); + } + else if (ts.isShorthandPropertyAssignment(node)) { + return hasExportedReferenceInDestructuringTarget(node.name); + } + else if (ts.isPropertyAssignment(node)) { + return hasExportedReferenceInDestructuringTarget(node.initializer); + } + else if (ts.isIdentifier(node)) { + var container = resolver.getReferencedExportContainer(node); + return container !== undefined && container.kind === 279; + } + else { + return false; + } + } + function modifierVisitor(node) { + switch (node.kind) { + case 85: + case 80: + return undefined; + } + return node; + } + function onEmitNode(hint, node, emitCallback) { + if (node.kind === 279) { + var id = ts.getOriginalNodeId(node); + currentSourceFile = node; + moduleInfo = moduleInfoMap[id]; + exportFunction = exportFunctionsMap[id]; + noSubstitution = noSubstitutionMap[id]; + if (noSubstitution) { + delete noSubstitutionMap[id]; + } + previousOnEmitNode(hint, node, emitCallback); + currentSourceFile = undefined; + moduleInfo = undefined; + exportFunction = undefined; + noSubstitution = undefined; + } + else { + previousOnEmitNode(hint, node, emitCallback); + } + } + function onSubstituteNode(hint, node) { + node = previousOnSubstituteNode(hint, node); + if (isSubstitutionPrevented(node)) { + return node; + } + if (hint === 1) { + return substituteExpression(node); + } + else if (hint === 4) { + return substituteUnspecified(node); + } + return node; + } + function substituteUnspecified(node) { + switch (node.kind) { + case 276: + return substituteShorthandPropertyAssignment(node); + } + return node; + } + function substituteShorthandPropertyAssignment(node) { + var name = node.name; + if (!ts.isGeneratedIdentifier(name) && !ts.isLocalName(name)) { + var importDeclaration = resolver.getReferencedImportDeclaration(name); + if (importDeclaration) { + if (ts.isImportClause(importDeclaration)) { + return ts.setTextRange(ts.createPropertyAssignment(ts.getSynthesizedClone(name), ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent), ts.createIdentifier("default"))), node); + } + else if (ts.isImportSpecifier(importDeclaration)) { + return ts.setTextRange(ts.createPropertyAssignment(ts.getSynthesizedClone(name), ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent.parent.parent), ts.getSynthesizedClone(importDeclaration.propertyName || importDeclaration.name))), node); + } + } + } + return node; + } + function substituteExpression(node) { + switch (node.kind) { + case 72: + return substituteExpressionIdentifier(node); + case 204: + return substituteBinaryExpression(node); + case 202: + case 203: + return substituteUnaryExpression(node); + } + return node; + } + function substituteExpressionIdentifier(node) { + if (ts.getEmitFlags(node) & 4096) { + var externalHelpersModuleName = ts.getExternalHelpersModuleName(currentSourceFile); + if (externalHelpersModuleName) { + return ts.createPropertyAccess(externalHelpersModuleName, node); + } + return node; + } + if (!ts.isGeneratedIdentifier(node) && !ts.isLocalName(node)) { + var importDeclaration = resolver.getReferencedImportDeclaration(node); + if (importDeclaration) { + if (ts.isImportClause(importDeclaration)) { + return ts.setTextRange(ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent), ts.createIdentifier("default")), node); + } + else if (ts.isImportSpecifier(importDeclaration)) { + return ts.setTextRange(ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent.parent.parent), ts.getSynthesizedClone(importDeclaration.propertyName || importDeclaration.name)), node); + } + } + } + return node; + } + function substituteBinaryExpression(node) { + if (ts.isAssignmentOperator(node.operatorToken.kind) + && ts.isIdentifier(node.left) + && !ts.isGeneratedIdentifier(node.left) + && !ts.isLocalName(node.left) + && !ts.isDeclarationNameOfEnumOrNamespace(node.left)) { + var exportedNames = getExports(node.left); + if (exportedNames) { + var expression = node; + for (var _i = 0, exportedNames_4 = exportedNames; _i < exportedNames_4.length; _i++) { + var exportName = exportedNames_4[_i]; + expression = createExportExpression(exportName, preventSubstitution(expression)); + } + return expression; + } + } + return node; + } + function substituteUnaryExpression(node) { + if ((node.operator === 44 || node.operator === 45) + && ts.isIdentifier(node.operand) + && !ts.isGeneratedIdentifier(node.operand) + && !ts.isLocalName(node.operand) + && !ts.isDeclarationNameOfEnumOrNamespace(node.operand)) { + var exportedNames = getExports(node.operand); + if (exportedNames) { + var expression = node.kind === 203 + ? ts.setTextRange(ts.createPrefix(node.operator, node.operand), node) + : node; + for (var _i = 0, exportedNames_5 = exportedNames; _i < exportedNames_5.length; _i++) { + var exportName = exportedNames_5[_i]; + expression = createExportExpression(exportName, preventSubstitution(expression)); + } + if (node.kind === 203) { + expression = node.operator === 44 + ? ts.createSubtract(preventSubstitution(expression), ts.createLiteral(1)) + : ts.createAdd(preventSubstitution(expression), ts.createLiteral(1)); + } + return expression; + } + } + return node; + } + function getExports(name) { + var exportedNames; + if (!ts.isGeneratedIdentifier(name)) { + var valueDeclaration = resolver.getReferencedImportDeclaration(name) + || resolver.getReferencedValueDeclaration(name); + if (valueDeclaration) { + var exportContainer = resolver.getReferencedExportContainer(name, false); + if (exportContainer && exportContainer.kind === 279) { + exportedNames = ts.append(exportedNames, ts.getDeclarationName(valueDeclaration)); + } + exportedNames = ts.addRange(exportedNames, moduleInfo && moduleInfo.exportedBindings[ts.getOriginalNodeId(valueDeclaration)]); + } + } + return exportedNames; + } + function preventSubstitution(node) { + if (noSubstitution === undefined) + noSubstitution = []; + noSubstitution[ts.getNodeId(node)] = true; + return node; + } + function isSubstitutionPrevented(node) { + return noSubstitution && node.id && noSubstitution[node.id]; + } + } + ts.transformSystemModule = transformSystemModule; +})(ts || (ts = {})); +var ts; +(function (ts) { + function transformES2015Module(context) { + var compilerOptions = context.getCompilerOptions(); + var previousOnEmitNode = context.onEmitNode; + var previousOnSubstituteNode = context.onSubstituteNode; + context.onEmitNode = onEmitNode; + context.onSubstituteNode = onSubstituteNode; + context.enableEmitNotification(279); + context.enableSubstitution(72); + var currentSourceFile; + return ts.chainBundle(transformSourceFile); + function transformSourceFile(node) { + if (node.isDeclarationFile) { + return node; + } + if (ts.isExternalModule(node) || compilerOptions.isolatedModules) { + var externalHelpersModuleName = ts.getOrCreateExternalHelpersModuleNameIfNeeded(node, compilerOptions); + if (externalHelpersModuleName) { + var statements = []; + var statementOffset = ts.addPrologue(statements, node.statements); + var tslibImport = ts.createImportDeclaration(undefined, undefined, ts.createImportClause(undefined, ts.createNamespaceImport(externalHelpersModuleName)), ts.createLiteral(ts.externalHelpersModuleNameText)); + ts.addEmitFlags(tslibImport, 67108864); + ts.append(statements, tslibImport); + ts.addRange(statements, ts.visitNodes(node.statements, visitor, ts.isStatement, statementOffset)); + return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements)); + } + else { + return ts.visitEachChild(node, visitor, context); + } + } + return node; + } + function visitor(node) { + switch (node.kind) { + case 248: + return undefined; + case 254: + return visitExportAssignment(node); + } + return node; + } + function visitExportAssignment(node) { + return node.isExportEquals ? undefined : node; + } + function onEmitNode(hint, node, emitCallback) { + if (ts.isSourceFile(node)) { + currentSourceFile = node; + previousOnEmitNode(hint, node, emitCallback); + currentSourceFile = undefined; + } + else { + previousOnEmitNode(hint, node, emitCallback); + } + } + function onSubstituteNode(hint, node) { + node = previousOnSubstituteNode(hint, node); + if (ts.isIdentifier(node) && hint === 1) { + return substituteExpressionIdentifier(node); + } + return node; + } + function substituteExpressionIdentifier(node) { + if (ts.getEmitFlags(node) & 4096) { + var externalHelpersModuleName = ts.getExternalHelpersModuleName(currentSourceFile); + if (externalHelpersModuleName) { + return ts.createPropertyAccess(externalHelpersModuleName, node); + } + } + return node; + } + } + ts.transformES2015Module = transformES2015Module; +})(ts || (ts = {})); +var ts; +(function (ts) { + function canProduceDiagnostics(node) { + return ts.isVariableDeclaration(node) || + ts.isPropertyDeclaration(node) || + ts.isPropertySignature(node) || + ts.isBindingElement(node) || + ts.isSetAccessor(node) || + ts.isGetAccessor(node) || + ts.isConstructSignatureDeclaration(node) || + ts.isCallSignatureDeclaration(node) || + ts.isMethodDeclaration(node) || + ts.isMethodSignature(node) || + ts.isFunctionDeclaration(node) || + ts.isParameter(node) || + ts.isTypeParameterDeclaration(node) || + ts.isExpressionWithTypeArguments(node) || + ts.isImportEqualsDeclaration(node) || + ts.isTypeAliasDeclaration(node) || + ts.isConstructorDeclaration(node) || + ts.isIndexSignatureDeclaration(node); + } + ts.canProduceDiagnostics = canProduceDiagnostics; + function createGetSymbolAccessibilityDiagnosticForNodeName(node) { + if (ts.isSetAccessor(node) || ts.isGetAccessor(node)) { + return getAccessorNameVisibilityError; + } + else if (ts.isMethodSignature(node) || ts.isMethodDeclaration(node)) { + return getMethodNameVisibilityError; + } + else { + return createGetSymbolAccessibilityDiagnosticForNode(node); + } + function getAccessorNameVisibilityError(symbolAccessibilityResult) { + var diagnosticMessage = getAccessorNameVisibilityDiagnosticMessage(symbolAccessibilityResult); + return diagnosticMessage !== undefined ? { + diagnosticMessage: diagnosticMessage, + errorNode: node, + typeName: node.name + } : undefined; + } + function getAccessorNameVisibilityDiagnosticMessage(symbolAccessibilityResult) { + if (ts.hasModifier(node, 32)) { + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 ? + ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1; + } + else if (node.parent.kind === 240) { + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 ? + ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_private_name_1; + } + else { + return symbolAccessibilityResult.errorModuleName ? + ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_private_name_1; + } + } + function getMethodNameVisibilityError(symbolAccessibilityResult) { + var diagnosticMessage = getMethodNameVisibilityDiagnosticMessage(symbolAccessibilityResult); + return diagnosticMessage !== undefined ? { + diagnosticMessage: diagnosticMessage, + errorNode: node, + typeName: node.name + } : undefined; + } + function getMethodNameVisibilityDiagnosticMessage(symbolAccessibilityResult) { + if (ts.hasModifier(node, 32)) { + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 ? + ts.Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_private_name_1; + } + else if (node.parent.kind === 240) { + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 ? + ts.Diagnostics.Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Public_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Public_method_0_of_exported_class_has_or_is_using_private_name_1; + } + else { + return symbolAccessibilityResult.errorModuleName ? + ts.Diagnostics.Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Method_0_of_exported_interface_has_or_is_using_private_name_1; + } + } + } + ts.createGetSymbolAccessibilityDiagnosticForNodeName = createGetSymbolAccessibilityDiagnosticForNodeName; + function createGetSymbolAccessibilityDiagnosticForNode(node) { + if (ts.isVariableDeclaration(node) || ts.isPropertyDeclaration(node) || ts.isPropertySignature(node) || ts.isBindingElement(node) || ts.isConstructorDeclaration(node)) { + return getVariableDeclarationTypeVisibilityError; + } + else if (ts.isSetAccessor(node) || ts.isGetAccessor(node)) { + return getAccessorDeclarationTypeVisibilityError; + } + else if (ts.isConstructSignatureDeclaration(node) || ts.isCallSignatureDeclaration(node) || ts.isMethodDeclaration(node) || ts.isMethodSignature(node) || ts.isFunctionDeclaration(node) || ts.isIndexSignatureDeclaration(node)) { + return getReturnTypeVisibilityError; + } + else if (ts.isParameter(node)) { + if (ts.isParameterPropertyDeclaration(node) && ts.hasModifier(node.parent, 8)) { + return getVariableDeclarationTypeVisibilityError; + } + return getParameterDeclarationTypeVisibilityError; + } + else if (ts.isTypeParameterDeclaration(node)) { + return getTypeParameterConstraintVisibilityError; + } + else if (ts.isExpressionWithTypeArguments(node)) { + return getHeritageClauseVisibilityError; + } + else if (ts.isImportEqualsDeclaration(node)) { + return getImportEntityNameVisibilityError; + } + else if (ts.isTypeAliasDeclaration(node)) { + return getTypeAliasDeclarationVisibilityError; + } + else { + return ts.Debug.assertNever(node, "Attempted to set a declaration diagnostic context for unhandled node kind: " + ts.SyntaxKind[node.kind]); + } + function getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) { + if (node.kind === 237 || node.kind === 186) { + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 ? + ts.Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Exported_variable_0_has_or_is_using_private_name_1; + } + else if (node.kind === 154 || node.kind === 153 || + (node.kind === 151 && ts.hasModifier(node.parent, 8))) { + if (ts.hasModifier(node, 32)) { + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 ? + ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1; + } + else if (node.parent.kind === 240 || node.kind === 151) { + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 ? + ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_private_name_1; + } + else { + return symbolAccessibilityResult.errorModuleName ? + ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_private_name_1; + } + } + } + function getVariableDeclarationTypeVisibilityError(symbolAccessibilityResult) { + var diagnosticMessage = getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult); + return diagnosticMessage !== undefined ? { + diagnosticMessage: diagnosticMessage, + errorNode: node, + typeName: node.name + } : undefined; + } + function getAccessorDeclarationTypeVisibilityError(symbolAccessibilityResult) { + var diagnosticMessage; + if (node.kind === 159) { + if (ts.hasModifier(node, 32)) { + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + ts.Diagnostics.Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1; + } + else { + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + ts.Diagnostics.Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_private_name_1; + } + } + else { + if (ts.hasModifier(node, 32)) { + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 ? + ts.Diagnostics.Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_private_name_1; + } + else { + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 ? + ts.Diagnostics.Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Return_type_of_public_getter_0_from_exported_class_has_or_is_using_private_name_1; + } + } + return { + diagnosticMessage: diagnosticMessage, + errorNode: node.name, + typeName: node.name + }; + } + function getReturnTypeVisibilityError(symbolAccessibilityResult) { + var diagnosticMessage; + switch (node.kind) { + case 161: + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + ts.Diagnostics.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : + ts.Diagnostics.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0; + break; + case 160: + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + ts.Diagnostics.Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : + ts.Diagnostics.Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0; + break; + case 162: + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + ts.Diagnostics.Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : + ts.Diagnostics.Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0; + break; + case 156: + case 155: + if (ts.hasModifier(node, 32)) { + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 ? + ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : + ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1 : + ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0; + } + else if (node.parent.kind === 240) { + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 ? + ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : + ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1 : + ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0; + } + else { + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + ts.Diagnostics.Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : + ts.Diagnostics.Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0; + } + break; + case 239: + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 ? + ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : + ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1 : + ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_private_name_0; + break; + default: + return ts.Debug.fail("This is unknown kind for signature: " + node.kind); + } + return { + diagnosticMessage: diagnosticMessage, + errorNode: node.name || node + }; + } + function getParameterDeclarationTypeVisibilityError(symbolAccessibilityResult) { + var diagnosticMessage = getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult); + return diagnosticMessage !== undefined ? { + diagnosticMessage: diagnosticMessage, + errorNode: node, + typeName: node.name + } : undefined; + } + function getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) { + switch (node.parent.kind) { + case 157: + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 ? + ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1; + case 161: + case 166: + return symbolAccessibilityResult.errorModuleName ? + ts.Diagnostics.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1; + case 160: + return symbolAccessibilityResult.errorModuleName ? + ts.Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1; + case 162: + return symbolAccessibilityResult.errorModuleName ? + ts.Diagnostics.Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1; + case 156: + case 155: + if (ts.hasModifier(node.parent, 32)) { + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 ? + ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1; + } + else if (node.parent.parent.kind === 240) { + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 ? + ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1; + } + else { + return symbolAccessibilityResult.errorModuleName ? + ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1; + } + case 239: + case 165: + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 ? + ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_private_name_1; + default: + return ts.Debug.fail("Unknown parent for parameter: " + ts.SyntaxKind[node.parent.kind]); + } + } + function getTypeParameterConstraintVisibilityError() { + var diagnosticMessage; + switch (node.parent.kind) { + case 240: + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_class_has_or_is_using_private_name_1; + break; + case 241: + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1; + break; + case 161: + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1; + break; + case 160: + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1; + break; + case 156: + case 155: + if (ts.hasModifier(node.parent, 32)) { + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1; + } + else if (node.parent.parent.kind === 240) { + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1; + } + else { + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1; + } + break; + case 239: + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_function_has_or_is_using_private_name_1; + break; + case 242: + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1; + break; + default: + return ts.Debug.fail("This is unknown parent for type parameter: " + node.parent.kind); + } + return { + diagnosticMessage: diagnosticMessage, + errorNode: node, + typeName: node.name + }; + } + function getHeritageClauseVisibilityError() { + var diagnosticMessage; + if (node.parent.parent.kind === 240) { + diagnosticMessage = ts.isHeritageClause(node.parent) && node.parent.token === 109 ? + ts.Diagnostics.Implements_clause_of_exported_class_0_has_or_is_using_private_name_1 : + ts.Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1; + } + else { + diagnosticMessage = ts.Diagnostics.extends_clause_of_exported_interface_0_has_or_is_using_private_name_1; + } + return { + diagnosticMessage: diagnosticMessage, + errorNode: node, + typeName: ts.getNameOfDeclaration(node.parent.parent) + }; + } + function getImportEntityNameVisibilityError() { + return { + diagnosticMessage: ts.Diagnostics.Import_declaration_0_is_using_private_name_1, + errorNode: node, + typeName: node.name + }; + } + function getTypeAliasDeclarationVisibilityError() { + return { + diagnosticMessage: ts.Diagnostics.Exported_type_alias_0_has_or_is_using_private_name_1, + errorNode: node.type, + typeName: node.name + }; + } + } + ts.createGetSymbolAccessibilityDiagnosticForNode = createGetSymbolAccessibilityDiagnosticForNode; +})(ts || (ts = {})); +var ts; +(function (ts) { + function getDeclarationDiagnostics(host, resolver, file) { + if (file && ts.isSourceFileJS(file)) { + return []; + } + var compilerOptions = host.getCompilerOptions(); + var result = ts.transformNodes(resolver, host, compilerOptions, file ? [file] : ts.filter(host.getSourceFiles(), ts.isSourceFileNotJS), [transformDeclarations], false); + return result.diagnostics; + } + ts.getDeclarationDiagnostics = getDeclarationDiagnostics; + var declarationEmitNodeBuilderFlags = 1024 | + 2048 | + 4096 | + 8 | + 524288 | + 4 | + 1; + function transformDeclarations(context) { + var throwDiagnostic = function () { return ts.Debug.fail("Diagnostic emitted without context"); }; + var getSymbolAccessibilityDiagnostic = throwDiagnostic; + var needsDeclare = true; + var isBundledEmit = false; + var resultHasExternalModuleIndicator = false; + var needsScopeFixMarker = false; + var resultHasScopeMarker = false; + var enclosingDeclaration; + var necessaryTypeReferences; + var lateMarkedStatements; + var lateStatementReplacementMap; + var suppressNewDiagnosticContexts; + var exportedModulesFromDeclarationEmit; + var host = context.getEmitHost(); + var symbolTracker = { + trackSymbol: trackSymbol, + reportInaccessibleThisError: reportInaccessibleThisError, + reportInaccessibleUniqueSymbolError: reportInaccessibleUniqueSymbolError, + reportPrivateInBaseOfClassExpression: reportPrivateInBaseOfClassExpression, + reportLikelyUnsafeImportRequiredError: reportLikelyUnsafeImportRequiredError, + moduleResolverHost: host, + trackReferencedAmbientModule: trackReferencedAmbientModule, + trackExternalModuleSymbolOfImportTypeNode: trackExternalModuleSymbolOfImportTypeNode + }; + var errorNameNode; + var currentSourceFile; + var refs; + var libs; + var resolver = context.getEmitResolver(); + var options = context.getCompilerOptions(); + var newLine = ts.getNewLineCharacter(options); + var noResolve = options.noResolve, stripInternal = options.stripInternal; + return transformRoot; + function recordTypeReferenceDirectivesIfNecessary(typeReferenceDirectives) { + if (!typeReferenceDirectives) { + return; + } + necessaryTypeReferences = necessaryTypeReferences || ts.createMap(); + for (var _i = 0, typeReferenceDirectives_2 = typeReferenceDirectives; _i < typeReferenceDirectives_2.length; _i++) { + var ref = typeReferenceDirectives_2[_i]; + necessaryTypeReferences.set(ref, true); + } + } + function trackReferencedAmbientModule(node, symbol) { + var directives = resolver.getTypeReferenceDirectivesForSymbol(symbol, 67108863); + if (ts.length(directives)) { + return recordTypeReferenceDirectivesIfNecessary(directives); + } + var container = ts.getSourceFileOfNode(node); + refs.set("" + ts.getOriginalNodeId(container), container); + } + function handleSymbolAccessibilityError(symbolAccessibilityResult) { + if (symbolAccessibilityResult.accessibility === 0) { + if (symbolAccessibilityResult && symbolAccessibilityResult.aliasesToMakeVisible) { + if (!lateMarkedStatements) { + lateMarkedStatements = symbolAccessibilityResult.aliasesToMakeVisible; + } + else { + for (var _i = 0, _a = symbolAccessibilityResult.aliasesToMakeVisible; _i < _a.length; _i++) { + var ref = _a[_i]; + ts.pushIfUnique(lateMarkedStatements, ref); + } + } + } + } + else { + var errorInfo = getSymbolAccessibilityDiagnostic(symbolAccessibilityResult); + if (errorInfo) { + if (errorInfo.typeName) { + context.addDiagnostic(ts.createDiagnosticForNode(symbolAccessibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, ts.getTextOfNode(errorInfo.typeName), symbolAccessibilityResult.errorSymbolName, symbolAccessibilityResult.errorModuleName)); + } + else { + context.addDiagnostic(ts.createDiagnosticForNode(symbolAccessibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, symbolAccessibilityResult.errorSymbolName, symbolAccessibilityResult.errorModuleName)); + } + } + } + } + function trackExternalModuleSymbolOfImportTypeNode(symbol) { + if (!isBundledEmit) { + (exportedModulesFromDeclarationEmit || (exportedModulesFromDeclarationEmit = [])).push(symbol); + } + } + function trackSymbol(symbol, enclosingDeclaration, meaning) { + if (symbol.flags & 262144) + return; + handleSymbolAccessibilityError(resolver.isSymbolAccessible(symbol, enclosingDeclaration, meaning, true)); + recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForSymbol(symbol, meaning)); + } + function reportPrivateInBaseOfClassExpression(propertyName) { + if (errorNameNode) { + context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.Property_0_of_exported_class_expression_may_not_be_private_or_protected, propertyName)); + } + } + function reportInaccessibleUniqueSymbolError() { + if (errorNameNode) { + context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary, ts.declarationNameToString(errorNameNode), "unique symbol")); + } + } + function reportInaccessibleThisError() { + if (errorNameNode) { + context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary, ts.declarationNameToString(errorNameNode), "this")); + } + } + function reportLikelyUnsafeImportRequiredError(specifier) { + if (errorNameNode) { + context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_annotation_is_necessary, ts.declarationNameToString(errorNameNode), specifier)); + } + } + function transformRoot(node) { + if (node.kind === 279 && (node.isDeclarationFile || ts.isSourceFileJS(node))) { + return node; + } + if (node.kind === 280) { + isBundledEmit = true; + refs = ts.createMap(); + libs = ts.createMap(); + var hasNoDefaultLib_1 = false; + var bundle = ts.createBundle(ts.map(node.sourceFiles, function (sourceFile) { + if (sourceFile.isDeclarationFile || ts.isSourceFileJS(sourceFile)) + return undefined; + hasNoDefaultLib_1 = hasNoDefaultLib_1 || sourceFile.hasNoDefaultLib; + currentSourceFile = sourceFile; + enclosingDeclaration = sourceFile; + lateMarkedStatements = undefined; + suppressNewDiagnosticContexts = false; + lateStatementReplacementMap = ts.createMap(); + getSymbolAccessibilityDiagnostic = throwDiagnostic; + needsScopeFixMarker = false; + resultHasScopeMarker = false; + collectReferences(sourceFile, refs); + collectLibs(sourceFile, libs); + if (ts.isExternalModule(sourceFile)) { + resultHasExternalModuleIndicator = false; + needsDeclare = false; + var statements_4 = ts.visitNodes(sourceFile.statements, visitDeclarationStatements); + var newFile = ts.updateSourceFileNode(sourceFile, [ts.createModuleDeclaration([], [ts.createModifier(125)], ts.createLiteral(ts.getResolvedExternalModuleName(context.getEmitHost(), sourceFile)), ts.createModuleBlock(ts.setTextRange(ts.createNodeArray(transformAndReplaceLatePaintedStatements(statements_4)), sourceFile.statements)))], true, [], [], false, []); + return newFile; + } + needsDeclare = true; + var updated = ts.visitNodes(sourceFile.statements, visitDeclarationStatements); + return ts.updateSourceFileNode(sourceFile, transformAndReplaceLatePaintedStatements(updated), true, [], [], false, []); + }), ts.mapDefined(node.prepends, function (prepend) { + if (prepend.kind === 282) { + return ts.createUnparsedSourceFile(prepend.declarationText, prepend.declarationMapPath, prepend.declarationMapText); + } + })); + bundle.syntheticFileReferences = []; + bundle.syntheticTypeReferences = getFileReferencesForUsedTypeReferences(); + bundle.syntheticLibReferences = getLibReferences(); + bundle.hasNoDefaultLib = hasNoDefaultLib_1; + var outputFilePath_1 = ts.getDirectoryPath(ts.normalizeSlashes(ts.getOutputPathsFor(node, host, true).declarationFilePath)); + var referenceVisitor_1 = mapReferencesIntoArray(bundle.syntheticFileReferences, outputFilePath_1); + refs.forEach(referenceVisitor_1); + return bundle; + } + needsDeclare = true; + needsScopeFixMarker = false; + resultHasScopeMarker = false; + enclosingDeclaration = node; + currentSourceFile = node; + getSymbolAccessibilityDiagnostic = throwDiagnostic; + isBundledEmit = false; + resultHasExternalModuleIndicator = false; + suppressNewDiagnosticContexts = false; + lateMarkedStatements = undefined; + lateStatementReplacementMap = ts.createMap(); + necessaryTypeReferences = undefined; + refs = collectReferences(currentSourceFile, ts.createMap()); + libs = collectLibs(currentSourceFile, ts.createMap()); + var references = []; + var outputFilePath = ts.getDirectoryPath(ts.normalizeSlashes(ts.getOutputPathsFor(node, host, true).declarationFilePath)); + var referenceVisitor = mapReferencesIntoArray(references, outputFilePath); + var statements = ts.visitNodes(node.statements, visitDeclarationStatements); + var combinedStatements = ts.setTextRange(ts.createNodeArray(transformAndReplaceLatePaintedStatements(statements)), node.statements); + refs.forEach(referenceVisitor); + var emittedImports = ts.filter(combinedStatements, ts.isAnyImportSyntax); + if (ts.isExternalModule(node) && (!resultHasExternalModuleIndicator || (needsScopeFixMarker && !resultHasScopeMarker))) { + combinedStatements = ts.setTextRange(ts.createNodeArray(combinedStatements.concat([ts.createExportDeclaration(undefined, undefined, ts.createNamedExports([]), undefined)])), combinedStatements); + } + var updated = ts.updateSourceFileNode(node, combinedStatements, true, references, getFileReferencesForUsedTypeReferences(), node.hasNoDefaultLib, getLibReferences()); + updated.exportedModulesFromDeclarationEmit = exportedModulesFromDeclarationEmit; + return updated; + function getLibReferences() { + return ts.map(ts.arrayFrom(libs.keys()), function (lib) { return ({ fileName: lib, pos: -1, end: -1 }); }); + } + function getFileReferencesForUsedTypeReferences() { + return necessaryTypeReferences ? ts.mapDefined(ts.arrayFrom(necessaryTypeReferences.keys()), getFileReferenceForTypeName) : []; + } + function getFileReferenceForTypeName(typeName) { + if (emittedImports) { + for (var _i = 0, emittedImports_1 = emittedImports; _i < emittedImports_1.length; _i++) { + var importStatement = emittedImports_1[_i]; + if (ts.isImportEqualsDeclaration(importStatement) && ts.isExternalModuleReference(importStatement.moduleReference)) { + var expr = importStatement.moduleReference.expression; + if (ts.isStringLiteralLike(expr) && expr.text === typeName) { + return undefined; + } + } + else if (ts.isImportDeclaration(importStatement) && ts.isStringLiteral(importStatement.moduleSpecifier) && importStatement.moduleSpecifier.text === typeName) { + return undefined; + } + } + } + return { fileName: typeName, pos: -1, end: -1 }; + } + function mapReferencesIntoArray(references, outputFilePath) { + return function (file) { + var declFileName; + if (file.isDeclarationFile) { + declFileName = file.fileName; + } + else { + if (isBundledEmit && ts.contains(node.sourceFiles, file)) + return; + var paths = ts.getOutputPathsFor(file, host, true); + declFileName = paths.declarationFilePath || paths.jsFilePath || file.fileName; + } + if (declFileName) { + var fileName = ts.getRelativePathToDirectoryOrUrl(outputFilePath, declFileName, host.getCurrentDirectory(), host.getCanonicalFileName, false); + if (ts.startsWith(fileName, "./") && ts.hasExtension(fileName)) { + fileName = fileName.substring(2); + } + if (ts.startsWith(fileName, "node_modules/") || fileName.indexOf("/node_modules/") !== -1) { + return; + } + references.push({ pos: -1, end: -1, fileName: fileName }); + } + }; + } + } + function collectReferences(sourceFile, ret) { + if (noResolve || ts.isSourceFileJS(sourceFile)) + return ret; + ts.forEach(sourceFile.referencedFiles, function (f) { + var elem = ts.tryResolveScriptReference(host, sourceFile, f); + if (elem) { + ret.set("" + ts.getOriginalNodeId(elem), elem); + } + }); + return ret; + } + function collectLibs(sourceFile, ret) { + ts.forEach(sourceFile.libReferenceDirectives, function (ref) { + var lib = host.getLibFileFromReference(ref); + if (lib) { + ret.set(ref.fileName.toLocaleLowerCase(), true); + } + }); + return ret; + } + function filterBindingPatternInitializers(name) { + if (name.kind === 72) { + return name; + } + else { + if (name.kind === 185) { + return ts.updateArrayBindingPattern(name, ts.visitNodes(name.elements, visitBindingElement)); + } + else { + return ts.updateObjectBindingPattern(name, ts.visitNodes(name.elements, visitBindingElement)); + } + } + function visitBindingElement(elem) { + if (elem.kind === 210) { + return elem; + } + return ts.updateBindingElement(elem, elem.dotDotDotToken, elem.propertyName, filterBindingPatternInitializers(elem.name), shouldPrintWithInitializer(elem) ? elem.initializer : undefined); + } + } + function ensureParameter(p, modifierMask) { + var oldDiag; + if (!suppressNewDiagnosticContexts) { + oldDiag = getSymbolAccessibilityDiagnostic; + getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(p); + } + var newParam = ts.updateParameter(p, undefined, maskModifiers(p, modifierMask), p.dotDotDotToken, filterBindingPatternInitializers(p.name), resolver.isOptionalParameter(p) ? (p.questionToken || ts.createToken(56)) : undefined, ensureType(p, p.type, true), ensureNoInitializer(p)); + if (!suppressNewDiagnosticContexts) { + getSymbolAccessibilityDiagnostic = oldDiag; + } + return newParam; + } + function shouldPrintWithInitializer(node) { + return canHaveLiteralInitializer(node) && resolver.isLiteralConstDeclaration(ts.getParseTreeNode(node)); + } + function ensureNoInitializer(node) { + if (shouldPrintWithInitializer(node)) { + return resolver.createLiteralConstValue(ts.getParseTreeNode(node), symbolTracker); + } + return undefined; + } + function ensureType(node, type, ignorePrivate) { + if (!ignorePrivate && ts.hasModifier(node, 8)) { + return; + } + if (shouldPrintWithInitializer(node)) { + return; + } + var shouldUseResolverType = node.kind === 151 && + (resolver.isRequiredInitializedParameter(node) || + resolver.isOptionalUninitializedParameterProperty(node)); + if (type && !shouldUseResolverType) { + return ts.visitNode(type, visitDeclarationSubtree); + } + if (!ts.getParseTreeNode(node)) { + return type ? ts.visitNode(type, visitDeclarationSubtree) : ts.createKeywordTypeNode(120); + } + if (node.kind === 159) { + return ts.createKeywordTypeNode(120); + } + errorNameNode = node.name; + var oldDiag; + if (!suppressNewDiagnosticContexts) { + oldDiag = getSymbolAccessibilityDiagnostic; + getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(node); + } + if (node.kind === 237 || node.kind === 186) { + return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker)); + } + if (node.kind === 151 + || node.kind === 154 + || node.kind === 153) { + if (!node.initializer) + return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker, shouldUseResolverType)); + return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker, shouldUseResolverType) || resolver.createTypeOfExpression(node.initializer, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker)); + } + return cleanup(resolver.createReturnTypeOfSignatureDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker)); + function cleanup(returnValue) { + errorNameNode = undefined; + if (!suppressNewDiagnosticContexts) { + getSymbolAccessibilityDiagnostic = oldDiag; + } + return returnValue || ts.createKeywordTypeNode(120); + } + } + function isDeclarationAndNotVisible(node) { + node = ts.getParseTreeNode(node); + switch (node.kind) { + case 239: + case 244: + case 241: + case 240: + case 242: + case 243: + return !resolver.isDeclarationVisible(node); + case 237: + return !getBindingNameVisible(node); + case 248: + case 249: + case 255: + case 254: + return false; + } + return false; + } + function getBindingNameVisible(elem) { + if (ts.isOmittedExpression(elem)) { + return false; + } + if (ts.isBindingPattern(elem.name)) { + return ts.some(elem.name.elements, getBindingNameVisible); + } + else { + return resolver.isDeclarationVisible(elem); + } + } + function updateParamsList(node, params, modifierMask) { + if (ts.hasModifier(node, 8)) { + return undefined; + } + var newParams = ts.map(params, function (p) { return ensureParameter(p, modifierMask); }); + if (!newParams) { + return undefined; + } + return ts.createNodeArray(newParams, params.hasTrailingComma); + } + function ensureTypeParams(node, params) { + return ts.hasModifier(node, 8) ? undefined : ts.visitNodes(params, visitDeclarationSubtree); + } + function isEnclosingDeclaration(node) { + return ts.isSourceFile(node) + || ts.isTypeAliasDeclaration(node) + || ts.isModuleDeclaration(node) + || ts.isClassDeclaration(node) + || ts.isInterfaceDeclaration(node) + || ts.isFunctionLike(node) + || ts.isIndexSignatureDeclaration(node) + || ts.isMappedTypeNode(node); + } + function checkEntityNameVisibility(entityName, enclosingDeclaration) { + var visibilityResult = resolver.isEntityNameVisible(entityName, enclosingDeclaration); + handleSymbolAccessibilityError(visibilityResult); + recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForEntityName(entityName)); + } + function preserveJsDoc(updated, original) { + if (ts.hasJSDocNodes(updated) && ts.hasJSDocNodes(original)) { + updated.jsDoc = original.jsDoc; + } + return ts.setCommentRange(updated, ts.getCommentRange(original)); + } + function rewriteModuleSpecifier(parent, input) { + if (!input) + return undefined; + resultHasExternalModuleIndicator = resultHasExternalModuleIndicator || (parent.kind !== 244 && parent.kind !== 183); + if (ts.isStringLiteralLike(input)) { + if (isBundledEmit) { + var newName = ts.getExternalModuleNameFromDeclaration(context.getEmitHost(), resolver, parent); + if (newName) { + return ts.createLiteral(newName); + } + } + else { + var symbol = resolver.getSymbolOfExternalModuleSpecifier(input); + if (symbol) { + (exportedModulesFromDeclarationEmit || (exportedModulesFromDeclarationEmit = [])).push(symbol); + } + } + } + return input; + } + function transformImportEqualsDeclaration(decl) { + if (!resolver.isDeclarationVisible(decl)) + return; + if (decl.moduleReference.kind === 259) { + var specifier = ts.getExternalModuleImportEqualsDeclarationExpression(decl); + return ts.updateImportEqualsDeclaration(decl, undefined, decl.modifiers, decl.name, ts.updateExternalModuleReference(decl.moduleReference, rewriteModuleSpecifier(decl, specifier))); + } + else { + var oldDiag = getSymbolAccessibilityDiagnostic; + getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(decl); + checkEntityNameVisibility(decl.moduleReference, enclosingDeclaration); + getSymbolAccessibilityDiagnostic = oldDiag; + return decl; + } + } + function transformImportDeclaration(decl) { + if (!decl.importClause) { + return ts.updateImportDeclaration(decl, undefined, decl.modifiers, decl.importClause, rewriteModuleSpecifier(decl, decl.moduleSpecifier)); + } + var visibleDefaultBinding = decl.importClause && decl.importClause.name && resolver.isDeclarationVisible(decl.importClause) ? decl.importClause.name : undefined; + if (!decl.importClause.namedBindings) { + return visibleDefaultBinding && ts.updateImportDeclaration(decl, undefined, decl.modifiers, ts.updateImportClause(decl.importClause, visibleDefaultBinding, undefined), rewriteModuleSpecifier(decl, decl.moduleSpecifier)); + } + if (decl.importClause.namedBindings.kind === 251) { + var namedBindings = resolver.isDeclarationVisible(decl.importClause.namedBindings) ? decl.importClause.namedBindings : undefined; + return visibleDefaultBinding || namedBindings ? ts.updateImportDeclaration(decl, undefined, decl.modifiers, ts.updateImportClause(decl.importClause, visibleDefaultBinding, namedBindings), rewriteModuleSpecifier(decl, decl.moduleSpecifier)) : undefined; + } + var bindingList = ts.mapDefined(decl.importClause.namedBindings.elements, function (b) { return resolver.isDeclarationVisible(b) ? b : undefined; }); + if ((bindingList && bindingList.length) || visibleDefaultBinding) { + return ts.updateImportDeclaration(decl, undefined, decl.modifiers, ts.updateImportClause(decl.importClause, visibleDefaultBinding, bindingList && bindingList.length ? ts.updateNamedImports(decl.importClause.namedBindings, bindingList) : undefined), rewriteModuleSpecifier(decl, decl.moduleSpecifier)); + } + } + function transformAndReplaceLatePaintedStatements(statements) { + while (ts.length(lateMarkedStatements)) { + var i = lateMarkedStatements.shift(); + if (!ts.isLateVisibilityPaintedStatement(i)) { + return ts.Debug.fail("Late replaced statement was found which is not handled by the declaration transformer!: " + (ts.SyntaxKind ? ts.SyntaxKind[i.kind] : i.kind)); + } + var result = transformTopLevelDeclaration(i, true); + lateStatementReplacementMap.set("" + ts.getOriginalNodeId(i), result); + } + return ts.visitNodes(statements, visitLateVisibilityMarkedStatements); + function visitLateVisibilityMarkedStatements(statement) { + if (ts.isLateVisibilityPaintedStatement(statement)) { + var key = "" + ts.getOriginalNodeId(statement); + if (lateStatementReplacementMap.has(key)) { + var result = lateStatementReplacementMap.get(key); + lateStatementReplacementMap.delete(key); + if (result && ts.isSourceFile(statement.parent)) { + if (ts.isArray(result) ? ts.some(result, needsScopeMarker) : needsScopeMarker(result)) { + needsScopeFixMarker = true; + } + if (ts.isArray(result) ? ts.some(result, isExternalModuleIndicator) : isExternalModuleIndicator(result)) { + resultHasExternalModuleIndicator = true; + } + } + return result; + } + } + return statement; + } + } + function isExternalModuleIndicator(result) { + return ts.isAnyImportOrReExport(result) || ts.isExportAssignment(result) || ts.hasModifier(result, 1); + } + function needsScopeMarker(result) { + return !ts.isAnyImportOrReExport(result) && !ts.isExportAssignment(result) && !ts.hasModifier(result, 1) && !ts.isAmbientModule(result); + } + function visitDeclarationSubtree(input) { + if (shouldStripInternal(input)) + return; + if (ts.isDeclaration(input)) { + if (isDeclarationAndNotVisible(input)) + return; + if (ts.hasDynamicName(input) && !resolver.isLateBound(ts.getParseTreeNode(input))) { + return; + } + } + if (ts.isFunctionLike(input) && resolver.isImplementationOfOverload(input)) + return; + if (ts.isSemicolonClassElement(input)) + return; + var previousEnclosingDeclaration; + if (isEnclosingDeclaration(input)) { + previousEnclosingDeclaration = enclosingDeclaration; + enclosingDeclaration = input; + } + var oldDiag = getSymbolAccessibilityDiagnostic; + if (ts.isMethodDeclaration(input) || ts.isMethodSignature(input)) { + if (ts.hasModifier(input, 8)) { + if (input.symbol && input.symbol.declarations && input.symbol.declarations[0] !== input) + return; + return cleanup(ts.createProperty(undefined, ensureModifiers(input), input.name, undefined, undefined, undefined)); + } + } + var canProdiceDiagnostic = ts.canProduceDiagnostics(input); + if (canProdiceDiagnostic && !suppressNewDiagnosticContexts) { + getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(input); + } + if (ts.isTypeQueryNode(input)) { + checkEntityNameVisibility(input.exprName, enclosingDeclaration); + } + var oldWithinObjectLiteralType = suppressNewDiagnosticContexts; + var shouldEnterSuppressNewDiagnosticsContextContext = ((input.kind === 168 || input.kind === 181) && input.parent.kind !== 242); + if (shouldEnterSuppressNewDiagnosticsContextContext) { + suppressNewDiagnosticContexts = true; + } + if (isProcessedComponent(input)) { + switch (input.kind) { + case 211: { + if ((ts.isEntityName(input.expression) || ts.isEntityNameExpression(input.expression))) { + checkEntityNameVisibility(input.expression, enclosingDeclaration); + } + var node = ts.visitEachChild(input, visitDeclarationSubtree, context); + return cleanup(ts.updateExpressionWithTypeArguments(node, ts.parenthesizeTypeParameters(node.typeArguments), node.expression)); + } + case 164: { + checkEntityNameVisibility(input.typeName, enclosingDeclaration); + var node = ts.visitEachChild(input, visitDeclarationSubtree, context); + return cleanup(ts.updateTypeReferenceNode(node, node.typeName, ts.parenthesizeTypeParameters(node.typeArguments))); + } + case 161: + return cleanup(ts.updateConstructSignature(input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type))); + case 157: { + var isPrivate = ts.hasModifier(input, 8); + var ctor = ts.createSignatureDeclaration(157, isPrivate ? undefined : ensureTypeParams(input, input.typeParameters), isPrivate ? undefined : updateParamsList(input, input.parameters, 0), undefined); + ctor.modifiers = ts.createNodeArray(ensureModifiers(input)); + return cleanup(ctor); + } + case 156: { + var sig = ts.createSignatureDeclaration(155, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type)); + sig.name = input.name; + sig.modifiers = ts.createNodeArray(ensureModifiers(input)); + sig.questionToken = input.questionToken; + return cleanup(sig); + } + case 158: { + var newNode = ensureAccessor(input); + return cleanup(newNode); + } + case 159: { + var newNode = ensureAccessor(input); + return cleanup(newNode); + } + case 154: + return cleanup(ts.updateProperty(input, undefined, ensureModifiers(input), input.name, input.questionToken, !ts.hasModifier(input, 8) ? ensureType(input, input.type) : undefined, ensureNoInitializer(input))); + case 153: + return cleanup(ts.updatePropertySignature(input, ensureModifiers(input), input.name, input.questionToken, !ts.hasModifier(input, 8) ? ensureType(input, input.type) : undefined, ensureNoInitializer(input))); + case 155: { + return cleanup(ts.updateMethodSignature(input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type), input.name, input.questionToken)); + } + case 160: { + return cleanup(ts.updateCallSignature(input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type))); + } + case 162: { + return cleanup(ts.updateIndexSignature(input, undefined, ensureModifiers(input), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree) || ts.createKeywordTypeNode(120))); + } + case 237: { + if (ts.isBindingPattern(input.name)) { + return recreateBindingPattern(input.name); + } + shouldEnterSuppressNewDiagnosticsContextContext = true; + suppressNewDiagnosticContexts = true; + return cleanup(ts.updateVariableDeclaration(input, input.name, ensureType(input, input.type), ensureNoInitializer(input))); + } + case 150: { + if (isPrivateMethodTypeParameter(input) && (input.default || input.constraint)) { + return cleanup(ts.updateTypeParameterDeclaration(input, input.name, undefined, undefined)); + } + return cleanup(ts.visitEachChild(input, visitDeclarationSubtree, context)); + } + case 175: { + var checkType = ts.visitNode(input.checkType, visitDeclarationSubtree); + var extendsType = ts.visitNode(input.extendsType, visitDeclarationSubtree); + var oldEnclosingDecl = enclosingDeclaration; + enclosingDeclaration = input.trueType; + var trueType = ts.visitNode(input.trueType, visitDeclarationSubtree); + enclosingDeclaration = oldEnclosingDecl; + var falseType = ts.visitNode(input.falseType, visitDeclarationSubtree); + return cleanup(ts.updateConditionalTypeNode(input, checkType, extendsType, trueType, falseType)); + } + case 165: { + return cleanup(ts.updateFunctionTypeNode(input, ts.visitNodes(input.typeParameters, visitDeclarationSubtree), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree))); + } + case 166: { + return cleanup(ts.updateConstructorTypeNode(input, ts.visitNodes(input.typeParameters, visitDeclarationSubtree), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree))); + } + case 183: { + if (!ts.isLiteralImportTypeNode(input)) + return cleanup(input); + return cleanup(ts.updateImportTypeNode(input, ts.updateLiteralTypeNode(input.argument, rewriteModuleSpecifier(input, input.argument.literal)), input.qualifier, ts.visitNodes(input.typeArguments, visitDeclarationSubtree, ts.isTypeNode), input.isTypeOf)); + } + default: ts.Debug.assertNever(input, "Attempted to process unhandled node kind: " + ts.SyntaxKind[input.kind]); + } + } + return cleanup(ts.visitEachChild(input, visitDeclarationSubtree, context)); + function cleanup(returnValue) { + if (returnValue && canProdiceDiagnostic && ts.hasDynamicName(input)) { + checkName(input); + } + if (isEnclosingDeclaration(input)) { + enclosingDeclaration = previousEnclosingDeclaration; + } + if (canProdiceDiagnostic && !suppressNewDiagnosticContexts) { + getSymbolAccessibilityDiagnostic = oldDiag; + } + if (shouldEnterSuppressNewDiagnosticsContextContext) { + suppressNewDiagnosticContexts = oldWithinObjectLiteralType; + } + if (returnValue === input) { + return returnValue; + } + return returnValue && ts.setOriginalNode(preserveJsDoc(returnValue, input), input); + } + } + function isPrivateMethodTypeParameter(node) { + return node.parent.kind === 156 && ts.hasModifier(node.parent, 8); + } + function visitDeclarationStatements(input) { + if (!isPreservedDeclarationStatement(input)) { + return; + } + if (shouldStripInternal(input)) + return; + switch (input.kind) { + case 255: { + if (ts.isSourceFile(input.parent)) { + resultHasExternalModuleIndicator = true; + resultHasScopeMarker = true; + } + return ts.updateExportDeclaration(input, undefined, input.modifiers, input.exportClause, rewriteModuleSpecifier(input, input.moduleSpecifier)); + } + case 254: { + if (ts.isSourceFile(input.parent)) { + resultHasExternalModuleIndicator = true; + resultHasScopeMarker = true; + } + if (input.expression.kind === 72) { + return input; + } + else { + var newId = ts.createOptimisticUniqueName("_default"); + getSymbolAccessibilityDiagnostic = function () { return ({ + diagnosticMessage: ts.Diagnostics.Default_export_of_the_module_has_or_is_using_private_name_0, + errorNode: input + }); }; + var varDecl = ts.createVariableDeclaration(newId, resolver.createTypeOfExpression(input.expression, input, declarationEmitNodeBuilderFlags, symbolTracker), undefined); + var statement = ts.createVariableStatement(needsDeclare ? [ts.createModifier(125)] : [], ts.createVariableDeclarationList([varDecl], 2)); + return [statement, ts.updateExportAssignment(input, input.decorators, input.modifiers, newId)]; + } + } + } + var result = transformTopLevelDeclaration(input); + lateStatementReplacementMap.set("" + ts.getOriginalNodeId(input), result); + return input; + } + function transformTopLevelDeclaration(input, isPrivate) { + if (shouldStripInternal(input)) + return; + switch (input.kind) { + case 248: { + return transformImportEqualsDeclaration(input); + } + case 249: { + return transformImportDeclaration(input); + } + } + if (ts.isDeclaration(input) && isDeclarationAndNotVisible(input)) + return; + if (ts.isFunctionLike(input) && resolver.isImplementationOfOverload(input)) + return; + var previousEnclosingDeclaration; + if (isEnclosingDeclaration(input)) { + previousEnclosingDeclaration = enclosingDeclaration; + enclosingDeclaration = input; + } + var canProdiceDiagnostic = ts.canProduceDiagnostics(input); + var oldDiag = getSymbolAccessibilityDiagnostic; + if (canProdiceDiagnostic) { + getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(input); + } + var previousNeedsDeclare = needsDeclare; + switch (input.kind) { + case 242: + return cleanup(ts.updateTypeAliasDeclaration(input, undefined, ensureModifiers(input, isPrivate), input.name, ts.visitNodes(input.typeParameters, visitDeclarationSubtree, ts.isTypeParameterDeclaration), ts.visitNode(input.type, visitDeclarationSubtree, ts.isTypeNode))); + case 241: { + return cleanup(ts.updateInterfaceDeclaration(input, undefined, ensureModifiers(input, isPrivate), input.name, ensureTypeParams(input, input.typeParameters), transformHeritageClauses(input.heritageClauses), ts.visitNodes(input.members, visitDeclarationSubtree))); + } + case 239: { + var clean = cleanup(ts.updateFunctionDeclaration(input, undefined, ensureModifiers(input, isPrivate), undefined, input.name, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type), undefined)); + if (clean && resolver.isExpandoFunctionDeclaration(input)) { + var declarations = ts.mapDefined(resolver.getPropertiesOfContainerFunction(input), function (p) { + if (!ts.isPropertyAccessExpression(p.valueDeclaration)) { + return undefined; + } + var type = resolver.createTypeOfDeclaration(p.valueDeclaration, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker); + var varDecl = ts.createVariableDeclaration(ts.unescapeLeadingUnderscores(p.escapedName), type, undefined); + return ts.createVariableStatement(undefined, ts.createVariableDeclarationList([varDecl])); + }); + var namespaceDecl = ts.createModuleDeclaration(undefined, ensureModifiers(input, isPrivate), input.name, ts.createModuleBlock(declarations), 16); + return [clean, namespaceDecl]; + } + else { + return clean; + } + } + case 244: { + needsDeclare = false; + var inner = input.body; + if (inner && inner.kind === 245) { + var statements = ts.visitNodes(inner.statements, visitDeclarationStatements); + var body = ts.updateModuleBlock(inner, transformAndReplaceLatePaintedStatements(statements)); + needsDeclare = previousNeedsDeclare; + var mods = ensureModifiers(input, isPrivate); + return cleanup(ts.updateModuleDeclaration(input, undefined, mods, ts.isExternalModuleAugmentation(input) ? rewriteModuleSpecifier(input, input.name) : input.name, body)); + } + else { + needsDeclare = previousNeedsDeclare; + var mods = ensureModifiers(input, isPrivate); + needsDeclare = false; + ts.visitNode(inner, visitDeclarationStatements); + var id = "" + ts.getOriginalNodeId(inner); + var body = lateStatementReplacementMap.get(id); + lateStatementReplacementMap.delete(id); + return cleanup(ts.updateModuleDeclaration(input, undefined, mods, input.name, body)); + } + } + case 240: { + var modifiers = ts.createNodeArray(ensureModifiers(input, isPrivate)); + var typeParameters = ensureTypeParams(input, input.typeParameters); + var ctor = ts.getFirstConstructorWithBody(input); + var parameterProperties = void 0; + if (ctor) { + var oldDiag_1 = getSymbolAccessibilityDiagnostic; + parameterProperties = ts.compact(ts.flatMap(ctor.parameters, function (param) { + if (!ts.hasModifier(param, 92)) + return; + getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(param); + if (param.name.kind === 72) { + return preserveJsDoc(ts.createProperty(undefined, ensureModifiers(param), param.name, param.questionToken, ensureType(param, param.type), ensureNoInitializer(param)), param); + } + else { + return walkBindingPattern(param.name); + } + function walkBindingPattern(pattern) { + var elems; + for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) { + var elem = _a[_i]; + if (ts.isOmittedExpression(elem)) + continue; + if (ts.isBindingPattern(elem.name)) { + elems = ts.concatenate(elems, walkBindingPattern(elem.name)); + } + elems = elems || []; + elems.push(ts.createProperty(undefined, ensureModifiers(param), elem.name, undefined, ensureType(elem, undefined), undefined)); + } + return elems; + } + })); + getSymbolAccessibilityDiagnostic = oldDiag_1; + } + var members = ts.createNodeArray(ts.concatenate(parameterProperties, ts.visitNodes(input.members, visitDeclarationSubtree))); + var extendsClause_1 = ts.getEffectiveBaseTypeNode(input); + if (extendsClause_1 && !ts.isEntityNameExpression(extendsClause_1.expression) && extendsClause_1.expression.kind !== 96) { + var newId_1 = ts.createOptimisticUniqueName(ts.unescapeLeadingUnderscores(input.name.escapedText) + "_base"); + getSymbolAccessibilityDiagnostic = function () { return ({ + diagnosticMessage: ts.Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1, + errorNode: extendsClause_1, + typeName: input.name + }); }; + var varDecl = ts.createVariableDeclaration(newId_1, resolver.createTypeOfExpression(extendsClause_1.expression, input, declarationEmitNodeBuilderFlags, symbolTracker), undefined); + var statement = ts.createVariableStatement(needsDeclare ? [ts.createModifier(125)] : [], ts.createVariableDeclarationList([varDecl], 2)); + var heritageClauses = ts.createNodeArray(ts.map(input.heritageClauses, function (clause) { + if (clause.token === 86) { + var oldDiag_2 = getSymbolAccessibilityDiagnostic; + getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(clause.types[0]); + var newClause = ts.updateHeritageClause(clause, ts.map(clause.types, function (t) { return ts.updateExpressionWithTypeArguments(t, ts.visitNodes(t.typeArguments, visitDeclarationSubtree), newId_1); })); + getSymbolAccessibilityDiagnostic = oldDiag_2; + return newClause; + } + return ts.updateHeritageClause(clause, ts.visitNodes(ts.createNodeArray(ts.filter(clause.types, function (t) { return ts.isEntityNameExpression(t.expression) || t.expression.kind === 96; })), visitDeclarationSubtree)); + })); + return [statement, cleanup(ts.updateClassDeclaration(input, undefined, modifiers, input.name, typeParameters, heritageClauses, members))]; + } + else { + var heritageClauses = transformHeritageClauses(input.heritageClauses); + return cleanup(ts.updateClassDeclaration(input, undefined, modifiers, input.name, typeParameters, heritageClauses, members)); + } + } + case 219: { + return cleanup(transformVariableStatement(input, isPrivate)); + } + case 243: { + return cleanup(ts.updateEnumDeclaration(input, undefined, ts.createNodeArray(ensureModifiers(input, isPrivate)), input.name, ts.createNodeArray(ts.mapDefined(input.members, function (m) { + if (shouldStripInternal(m)) + return; + var constValue = resolver.getConstantValue(m); + return preserveJsDoc(ts.updateEnumMember(m, m.name, constValue !== undefined ? ts.createLiteral(constValue) : undefined), m); + })))); + } + } + return ts.Debug.assertNever(input, "Unhandled top-level node in declaration emit: " + ts.SyntaxKind[input.kind]); + function cleanup(node) { + if (isEnclosingDeclaration(input)) { + enclosingDeclaration = previousEnclosingDeclaration; + } + if (canProdiceDiagnostic) { + getSymbolAccessibilityDiagnostic = oldDiag; + } + if (input.kind === 244) { + needsDeclare = previousNeedsDeclare; + } + if (node === input) { + return node; + } + return node && ts.setOriginalNode(preserveJsDoc(node, input), input); + } + } + function transformVariableStatement(input, privateDeclaration) { + if (!ts.forEach(input.declarationList.declarations, getBindingNameVisible)) + return; + var nodes = ts.visitNodes(input.declarationList.declarations, visitDeclarationSubtree); + if (!ts.length(nodes)) + return; + return ts.updateVariableStatement(input, ts.createNodeArray(ensureModifiers(input, privateDeclaration)), ts.updateVariableDeclarationList(input.declarationList, nodes)); + } + function recreateBindingPattern(d) { + return ts.flatten(ts.mapDefined(d.elements, function (e) { return recreateBindingElement(e); })); + } + function recreateBindingElement(e) { + if (e.kind === 210) { + return; + } + if (e.name) { + if (!getBindingNameVisible(e)) + return; + if (ts.isBindingPattern(e.name)) { + return recreateBindingPattern(e.name); + } + else { + return ts.createVariableDeclaration(e.name, ensureType(e, undefined), undefined); + } + } + } + function checkName(node) { + var oldDiag; + if (!suppressNewDiagnosticContexts) { + oldDiag = getSymbolAccessibilityDiagnostic; + getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNodeName(node); + } + errorNameNode = node.name; + ts.Debug.assert(resolver.isLateBound(ts.getParseTreeNode(node))); + var decl = node; + var entityName = decl.name.expression; + checkEntityNameVisibility(entityName, enclosingDeclaration); + if (!suppressNewDiagnosticContexts) { + getSymbolAccessibilityDiagnostic = oldDiag; + } + errorNameNode = undefined; + } + function hasInternalAnnotation(range) { + var comment = currentSourceFile.text.substring(range.pos, range.end); + return ts.stringContains(comment, "@internal"); + } + function shouldStripInternal(node) { + if (stripInternal && node) { + var leadingCommentRanges = ts.getLeadingCommentRangesOfNode(ts.getParseTreeNode(node), currentSourceFile); + if (ts.forEach(leadingCommentRanges, hasInternalAnnotation)) { + return true; + } + } + return false; + } + function isScopeMarker(node) { + return ts.isExportAssignment(node) || ts.isExportDeclaration(node); + } + function hasScopeMarker(node) { + if (ts.isModuleBlock(node)) { + return ts.some(node.statements, isScopeMarker); + } + return false; + } + function ensureModifiers(node, privateDeclaration) { + var currentFlags = ts.getModifierFlags(node); + var newFlags = ensureModifierFlags(node, privateDeclaration); + if (currentFlags === newFlags) { + return node.modifiers; + } + return ts.createModifiersFromModifierFlags(newFlags); + } + function ensureModifierFlags(node, privateDeclaration) { + var mask = 3071 ^ (4 | 256); + var additions = (needsDeclare && !isAlwaysType(node)) ? 2 : 0; + var parentIsFile = node.parent.kind === 279; + if (!parentIsFile || (isBundledEmit && parentIsFile && ts.isExternalModule(node.parent))) { + mask ^= ((privateDeclaration || (isBundledEmit && parentIsFile) || hasScopeMarker(node.parent) ? 0 : 1) | 2); + additions = 0; + } + return maskModifierFlags(node, mask, additions); + } + function ensureAccessor(node) { + var accessors = resolver.getAllAccessorDeclarations(node); + if (node.kind !== accessors.firstAccessor.kind) { + return; + } + var accessorType = getTypeAnnotationFromAccessor(node); + if (!accessorType && accessors.secondAccessor) { + accessorType = getTypeAnnotationFromAccessor(accessors.secondAccessor); + getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(accessors.secondAccessor); + } + var prop = ts.createProperty(undefined, maskModifiers(node, undefined, (!accessors.setAccessor) ? 64 : 0), node.name, node.questionToken, ensureType(node, accessorType), undefined); + var leadingsSyntheticCommentRanges = accessors.secondAccessor && ts.getLeadingCommentRangesOfNode(accessors.secondAccessor, currentSourceFile); + if (leadingsSyntheticCommentRanges) { + var _loop_9 = function (range) { + if (range.kind === 3) { + var text = currentSourceFile.text.slice(range.pos + 2, range.end - 2); + var lines = text.split(/\r\n?|\n/g); + if (lines.length > 1) { + var lastLines = lines.slice(1); + var indentation_1 = ts.guessIndentation(lastLines); + text = [lines[0]].concat(ts.map(lastLines, function (l) { return l.slice(indentation_1); })).join(newLine); + } + ts.addSyntheticLeadingComment(prop, range.kind, text, range.hasTrailingNewLine); + } + }; + for (var _i = 0, leadingsSyntheticCommentRanges_1 = leadingsSyntheticCommentRanges; _i < leadingsSyntheticCommentRanges_1.length; _i++) { + var range = leadingsSyntheticCommentRanges_1[_i]; + _loop_9(range); + } + } + return prop; + } + function transformHeritageClauses(nodes) { + return ts.createNodeArray(ts.filter(ts.map(nodes, function (clause) { return ts.updateHeritageClause(clause, ts.visitNodes(ts.createNodeArray(ts.filter(clause.types, function (t) { + return ts.isEntityNameExpression(t.expression) || (clause.token === 86 && t.expression.kind === 96); + })), visitDeclarationSubtree)); }), function (clause) { return clause.types && !!clause.types.length; })); + } + } + ts.transformDeclarations = transformDeclarations; + function isAlwaysType(node) { + if (node.kind === 241) { + return true; + } + return false; + } + function maskModifiers(node, modifierMask, modifierAdditions) { + return ts.createModifiersFromModifierFlags(maskModifierFlags(node, modifierMask, modifierAdditions)); + } + function maskModifierFlags(node, modifierMask, modifierAdditions) { + if (modifierMask === void 0) { modifierMask = 3071 ^ 4; } + if (modifierAdditions === void 0) { modifierAdditions = 0; } + var flags = (ts.getModifierFlags(node) & modifierMask) | modifierAdditions; + if (flags & 512 && !(flags & 1)) { + flags ^= 1; + } + if (flags & 512 && flags & 2) { + flags ^= 2; + } + return flags; + } + function getTypeAnnotationFromAccessor(accessor) { + if (accessor) { + return accessor.kind === 158 + ? accessor.type + : accessor.parameters.length > 0 + ? accessor.parameters[0].type + : undefined; + } + } + function canHaveLiteralInitializer(node) { + switch (node.kind) { + case 154: + case 153: + return !ts.hasModifier(node, 8); + case 151: + case 237: + return true; + } + return false; + } + function isPreservedDeclarationStatement(node) { + switch (node.kind) { + case 239: + case 244: + case 248: + case 241: + case 240: + case 242: + case 243: + case 219: + case 249: + case 255: + case 254: + return true; + } + return false; + } + function isProcessedComponent(node) { + switch (node.kind) { + case 161: + case 157: + case 156: + case 158: + case 159: + case 154: + case 153: + case 155: + case 160: + case 162: + case 237: + case 150: + case 211: + case 164: + case 175: + case 165: + case 166: + case 183: + return true; + } + return false; + } +})(ts || (ts = {})); +var ts; +(function (ts) { + function getModuleTransformer(moduleKind) { + switch (moduleKind) { + case ts.ModuleKind.ESNext: + case ts.ModuleKind.ES2015: + return ts.transformES2015Module; + case ts.ModuleKind.System: + return ts.transformSystemModule; + default: + return ts.transformModule; + } + } + function getTransformers(compilerOptions, customTransformers) { + var jsx = compilerOptions.jsx; + var languageVersion = ts.getEmitScriptTarget(compilerOptions); + var moduleKind = ts.getEmitModuleKind(compilerOptions); + var transformers = []; + ts.addRange(transformers, customTransformers && customTransformers.before); + transformers.push(ts.transformTypeScript); + if (jsx === 2) { + transformers.push(ts.transformJsx); + } + if (languageVersion < 6) { + transformers.push(ts.transformESNext); + } + if (languageVersion < 4) { + transformers.push(ts.transformES2017); + } + if (languageVersion < 3) { + transformers.push(ts.transformES2016); + } + if (languageVersion < 2) { + transformers.push(ts.transformES2015); + transformers.push(ts.transformGenerators); + } + transformers.push(getModuleTransformer(moduleKind)); + if (languageVersion < 1) { + transformers.push(ts.transformES5); + } + ts.addRange(transformers, customTransformers && customTransformers.after); + return transformers; + } + ts.getTransformers = getTransformers; + function noEmitSubstitution(_hint, node) { + return node; + } + ts.noEmitSubstitution = noEmitSubstitution; + function noEmitNotification(hint, node, callback) { + callback(hint, node); + } + ts.noEmitNotification = noEmitNotification; + function transformNodes(resolver, host, options, nodes, transformers, allowDtsFiles) { + var enabledSyntaxKindFeatures = new Array(312); + var lexicalEnvironmentVariableDeclarations; + var lexicalEnvironmentFunctionDeclarations; + var lexicalEnvironmentVariableDeclarationsStack = []; + var lexicalEnvironmentFunctionDeclarationsStack = []; + var lexicalEnvironmentStackOffset = 0; + var lexicalEnvironmentSuspended = false; + var emitHelpers; + var onSubstituteNode = noEmitSubstitution; + var onEmitNode = noEmitNotification; + var state = 0; + var diagnostics = []; + var context = { + getCompilerOptions: function () { return options; }, + getEmitResolver: function () { return resolver; }, + getEmitHost: function () { return host; }, + startLexicalEnvironment: startLexicalEnvironment, + suspendLexicalEnvironment: suspendLexicalEnvironment, + resumeLexicalEnvironment: resumeLexicalEnvironment, + endLexicalEnvironment: endLexicalEnvironment, + hoistVariableDeclaration: hoistVariableDeclaration, + hoistFunctionDeclaration: hoistFunctionDeclaration, + requestEmitHelper: requestEmitHelper, + readEmitHelpers: readEmitHelpers, + enableSubstitution: enableSubstitution, + enableEmitNotification: enableEmitNotification, + isSubstitutionEnabled: isSubstitutionEnabled, + isEmitNotificationEnabled: isEmitNotificationEnabled, + get onSubstituteNode() { return onSubstituteNode; }, + set onSubstituteNode(value) { + ts.Debug.assert(state < 1, "Cannot modify transformation hooks after initialization has completed."); + ts.Debug.assert(value !== undefined, "Value must not be 'undefined'"); + onSubstituteNode = value; + }, + get onEmitNode() { return onEmitNode; }, + set onEmitNode(value) { + ts.Debug.assert(state < 1, "Cannot modify transformation hooks after initialization has completed."); + ts.Debug.assert(value !== undefined, "Value must not be 'undefined'"); + onEmitNode = value; + }, + addDiagnostic: function (diag) { + diagnostics.push(diag); + } + }; + for (var _i = 0, nodes_4 = nodes; _i < nodes_4.length; _i++) { + var node = nodes_4[_i]; + ts.disposeEmitNodes(ts.getSourceFileOfNode(ts.getParseTreeNode(node))); + } + ts.performance.mark("beforeTransform"); + var transformation = ts.chain.apply(void 0, transformers)(context); + state = 1; + var transformed = ts.map(nodes, allowDtsFiles ? transformation : transformRoot); + state = 2; + ts.performance.mark("afterTransform"); + ts.performance.measure("transformTime", "beforeTransform", "afterTransform"); + return { + transformed: transformed, + substituteNode: substituteNode, + emitNodeWithNotification: emitNodeWithNotification, + dispose: dispose, + diagnostics: diagnostics + }; + function transformRoot(node) { + return node && (!ts.isSourceFile(node) || !node.isDeclarationFile) ? transformation(node) : node; + } + function enableSubstitution(kind) { + ts.Debug.assert(state < 2, "Cannot modify the transformation context after transformation has completed."); + enabledSyntaxKindFeatures[kind] |= 1; + } + function isSubstitutionEnabled(node) { + return (enabledSyntaxKindFeatures[node.kind] & 1) !== 0 + && (ts.getEmitFlags(node) & 4) === 0; + } + function substituteNode(hint, node) { + ts.Debug.assert(state < 3, "Cannot substitute a node after the result is disposed."); + return node && isSubstitutionEnabled(node) && onSubstituteNode(hint, node) || node; + } + function enableEmitNotification(kind) { + ts.Debug.assert(state < 2, "Cannot modify the transformation context after transformation has completed."); + enabledSyntaxKindFeatures[kind] |= 2; + } + function isEmitNotificationEnabled(node) { + return (enabledSyntaxKindFeatures[node.kind] & 2) !== 0 + || (ts.getEmitFlags(node) & 2) !== 0; + } + function emitNodeWithNotification(hint, node, emitCallback) { + ts.Debug.assert(state < 3, "Cannot invoke TransformationResult callbacks after the result is disposed."); + if (node) { + if (isEmitNotificationEnabled(node)) { + onEmitNode(hint, node, emitCallback); + } + else { + emitCallback(hint, node); + } + } + } + function hoistVariableDeclaration(name) { + ts.Debug.assert(state > 0, "Cannot modify the lexical environment during initialization."); + ts.Debug.assert(state < 2, "Cannot modify the lexical environment after transformation has completed."); + var decl = ts.setEmitFlags(ts.createVariableDeclaration(name), 64); + if (!lexicalEnvironmentVariableDeclarations) { + lexicalEnvironmentVariableDeclarations = [decl]; + } + else { + lexicalEnvironmentVariableDeclarations.push(decl); + } + } + function hoistFunctionDeclaration(func) { + ts.Debug.assert(state > 0, "Cannot modify the lexical environment during initialization."); + ts.Debug.assert(state < 2, "Cannot modify the lexical environment after transformation has completed."); + if (!lexicalEnvironmentFunctionDeclarations) { + lexicalEnvironmentFunctionDeclarations = [func]; + } + else { + lexicalEnvironmentFunctionDeclarations.push(func); + } + } + function startLexicalEnvironment() { + ts.Debug.assert(state > 0, "Cannot modify the lexical environment during initialization."); + ts.Debug.assert(state < 2, "Cannot modify the lexical environment after transformation has completed."); + ts.Debug.assert(!lexicalEnvironmentSuspended, "Lexical environment is suspended."); + lexicalEnvironmentVariableDeclarationsStack[lexicalEnvironmentStackOffset] = lexicalEnvironmentVariableDeclarations; + lexicalEnvironmentFunctionDeclarationsStack[lexicalEnvironmentStackOffset] = lexicalEnvironmentFunctionDeclarations; + lexicalEnvironmentStackOffset++; + lexicalEnvironmentVariableDeclarations = undefined; + lexicalEnvironmentFunctionDeclarations = undefined; + } + function suspendLexicalEnvironment() { + ts.Debug.assert(state > 0, "Cannot modify the lexical environment during initialization."); + ts.Debug.assert(state < 2, "Cannot modify the lexical environment after transformation has completed."); + ts.Debug.assert(!lexicalEnvironmentSuspended, "Lexical environment is already suspended."); + lexicalEnvironmentSuspended = true; + } + function resumeLexicalEnvironment() { + ts.Debug.assert(state > 0, "Cannot modify the lexical environment during initialization."); + ts.Debug.assert(state < 2, "Cannot modify the lexical environment after transformation has completed."); + ts.Debug.assert(lexicalEnvironmentSuspended, "Lexical environment is not suspended."); + lexicalEnvironmentSuspended = false; + } + function endLexicalEnvironment() { + ts.Debug.assert(state > 0, "Cannot modify the lexical environment during initialization."); + ts.Debug.assert(state < 2, "Cannot modify the lexical environment after transformation has completed."); + ts.Debug.assert(!lexicalEnvironmentSuspended, "Lexical environment is suspended."); + var statements; + if (lexicalEnvironmentVariableDeclarations || lexicalEnvironmentFunctionDeclarations) { + if (lexicalEnvironmentFunctionDeclarations) { + statements = lexicalEnvironmentFunctionDeclarations.slice(); + } + if (lexicalEnvironmentVariableDeclarations) { + var statement = ts.createVariableStatement(undefined, ts.createVariableDeclarationList(lexicalEnvironmentVariableDeclarations)); + if (!statements) { + statements = [statement]; + } + else { + statements.push(statement); + } + } + } + lexicalEnvironmentStackOffset--; + lexicalEnvironmentVariableDeclarations = lexicalEnvironmentVariableDeclarationsStack[lexicalEnvironmentStackOffset]; + lexicalEnvironmentFunctionDeclarations = lexicalEnvironmentFunctionDeclarationsStack[lexicalEnvironmentStackOffset]; + if (lexicalEnvironmentStackOffset === 0) { + lexicalEnvironmentVariableDeclarationsStack = []; + lexicalEnvironmentFunctionDeclarationsStack = []; + } + return statements; + } + function requestEmitHelper(helper) { + ts.Debug.assert(state > 0, "Cannot modify the transformation context during initialization."); + ts.Debug.assert(state < 2, "Cannot modify the transformation context after transformation has completed."); + ts.Debug.assert(!helper.scoped, "Cannot request a scoped emit helper."); + emitHelpers = ts.append(emitHelpers, helper); + } + function readEmitHelpers() { + ts.Debug.assert(state > 0, "Cannot modify the transformation context during initialization."); + ts.Debug.assert(state < 2, "Cannot modify the transformation context after transformation has completed."); + var helpers = emitHelpers; + emitHelpers = undefined; + return helpers; + } + function dispose() { + if (state < 3) { + for (var _i = 0, nodes_5 = nodes; _i < nodes_5.length; _i++) { + var node = nodes_5[_i]; + ts.disposeEmitNodes(ts.getSourceFileOfNode(ts.getParseTreeNode(node))); + } + lexicalEnvironmentVariableDeclarations = undefined; + lexicalEnvironmentVariableDeclarationsStack = undefined; + lexicalEnvironmentFunctionDeclarations = undefined; + lexicalEnvironmentFunctionDeclarationsStack = undefined; + onSubstituteNode = undefined; + onEmitNode = undefined; + emitHelpers = undefined; + state = 3; + } + } + } + ts.transformNodes = transformNodes; +})(ts || (ts = {})); +var ts; +(function (ts) { + var infoExtension = ".tsbundleinfo"; + var brackets = createBracketsMap(); + var syntheticParent = { pos: -1, end: -1 }; + function forEachEmittedFile(host, action, sourceFilesOrTargetSourceFile, emitOnlyDtsFiles) { + if (emitOnlyDtsFiles === void 0) { emitOnlyDtsFiles = false; } + var sourceFiles = ts.isArray(sourceFilesOrTargetSourceFile) ? sourceFilesOrTargetSourceFile : ts.getSourceFilesToEmit(host, sourceFilesOrTargetSourceFile); + var options = host.getCompilerOptions(); + if (options.outFile || options.out) { + if (sourceFiles.length) { + var bundle = ts.createBundle(sourceFiles, host.getPrependNodes()); + var result = action(getOutputPathsFor(bundle, host, emitOnlyDtsFiles), bundle); + if (result) { + return result; + } + } + } + else { + for (var _a = 0, sourceFiles_1 = sourceFiles; _a < sourceFiles_1.length; _a++) { + var sourceFile = sourceFiles_1[_a]; + var result = action(getOutputPathsFor(sourceFile, host, emitOnlyDtsFiles), sourceFile); + if (result) { + return result; + } + } + } + } + ts.forEachEmittedFile = forEachEmittedFile; + function getOutputPathsFor(sourceFile, host, forceDtsPaths) { + var options = host.getCompilerOptions(); + if (sourceFile.kind === 280) { + var outPath = options.outFile || options.out; + var jsFilePath = options.emitDeclarationOnly ? undefined : outPath; + var sourceMapFilePath = jsFilePath && getSourceMapFilePath(jsFilePath, options); + var declarationFilePath = (forceDtsPaths || ts.getEmitDeclarations(options)) ? ts.removeFileExtension(outPath) + ".d.ts" : undefined; + var declarationMapPath = declarationFilePath && ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; + var bundleInfoPath = options.references && jsFilePath ? (ts.removeFileExtension(jsFilePath) + infoExtension) : undefined; + return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, bundleInfoPath: bundleInfoPath }; + } + else { + var ownOutputFilePath = ts.getOwnEmitOutputFilePath(sourceFile.fileName, host, getOutputExtension(sourceFile, options)); + var isJsonEmittedToSameLocation = ts.isJsonSourceFile(sourceFile) && + ts.comparePaths(sourceFile.fileName, ownOutputFilePath, host.getCurrentDirectory(), !host.useCaseSensitiveFileNames()) === 0; + var jsFilePath = options.emitDeclarationOnly || isJsonEmittedToSameLocation ? undefined : ownOutputFilePath; + var sourceMapFilePath = !jsFilePath || ts.isJsonSourceFile(sourceFile) ? undefined : getSourceMapFilePath(jsFilePath, options); + var isJs = ts.isSourceFileJS(sourceFile); + var declarationFilePath = ((forceDtsPaths || ts.getEmitDeclarations(options)) && !isJs) ? ts.getDeclarationEmitOutputFilePath(sourceFile.fileName, host) : undefined; + var declarationMapPath = declarationFilePath && ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; + return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, bundleInfoPath: undefined }; + } + } + ts.getOutputPathsFor = getOutputPathsFor; + function getSourceMapFilePath(jsFilePath, options) { + return (options.sourceMap && !options.inlineSourceMap) ? jsFilePath + ".map" : undefined; + } + function createDefaultBundleInfo() { + return { + originalOffset: -1, + totalLength: -1 + }; + } + function getOutputExtension(sourceFile, options) { + if (ts.isJsonSourceFile(sourceFile)) { + return ".json"; + } + if (options.jsx === 1) { + if (ts.isSourceFileJS(sourceFile)) { + if (ts.fileExtensionIs(sourceFile.fileName, ".jsx")) { + return ".jsx"; + } + } + else if (sourceFile.languageVariant === 1) { + return ".jsx"; + } + } + return ".js"; + } + ts.getOutputExtension = getOutputExtension; + function emitFiles(resolver, host, targetSourceFile, emitOnlyDtsFiles, transformers, declarationTransformers) { + var compilerOptions = host.getCompilerOptions(); + var sourceMapDataList = (compilerOptions.sourceMap || compilerOptions.inlineSourceMap || ts.getAreDeclarationMapsEnabled(compilerOptions)) ? [] : undefined; + var emittedFilesList = compilerOptions.listEmittedFiles ? [] : undefined; + var emitterDiagnostics = ts.createDiagnosticCollection(); + var newLine = ts.getNewLineCharacter(compilerOptions, function () { return host.getNewLine(); }); + var writer = ts.createTextWriter(newLine); + var _a = ts.performance.createTimer("printTime", "beforePrint", "afterPrint"), enter = _a.enter, exit = _a.exit; + var bundleInfo = createDefaultBundleInfo(); + var emitSkipped = false; + var exportedModulesFromDeclarationEmit; + enter(); + forEachEmittedFile(host, emitSourceFileOrBundle, ts.getSourceFilesToEmit(host, targetSourceFile), emitOnlyDtsFiles); + exit(); + return { + emitSkipped: emitSkipped, + diagnostics: emitterDiagnostics.getDiagnostics(), + emittedFiles: emittedFilesList, + sourceMaps: sourceMapDataList, + exportedModulesFromDeclarationEmit: exportedModulesFromDeclarationEmit + }; + function emitSourceFileOrBundle(_a, sourceFileOrBundle) { + var jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, bundleInfoPath = _a.bundleInfoPath; + emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, bundleInfoPath); + emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath); + if (!emitSkipped && emittedFilesList) { + if (!emitOnlyDtsFiles) { + if (jsFilePath) { + emittedFilesList.push(jsFilePath); + } + if (sourceMapFilePath) { + emittedFilesList.push(sourceMapFilePath); + } + if (bundleInfoPath) { + emittedFilesList.push(bundleInfoPath); + } + } + if (declarationFilePath) { + emittedFilesList.push(declarationFilePath); + } + if (declarationMapPath) { + emittedFilesList.push(declarationMapPath); + } + } + } + function emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, bundleInfoPath) { + if (emitOnlyDtsFiles || !jsFilePath) { + return; + } + if ((jsFilePath && host.isEmitBlocked(jsFilePath)) || compilerOptions.noEmit) { + emitSkipped = true; + return; + } + var transform = ts.transformNodes(resolver, host, compilerOptions, [sourceFileOrBundle], transformers, false); + var printerOptions = { + removeComments: compilerOptions.removeComments, + newLine: compilerOptions.newLine, + noEmitHelpers: compilerOptions.noEmitHelpers, + module: compilerOptions.module, + target: compilerOptions.target, + sourceMap: compilerOptions.sourceMap, + inlineSourceMap: compilerOptions.inlineSourceMap, + inlineSources: compilerOptions.inlineSources, + extendedDiagnostics: compilerOptions.extendedDiagnostics, + }; + var printer = createPrinter(printerOptions, { + hasGlobalName: resolver.hasGlobalName, + onEmitNode: transform.emitNodeWithNotification, + substituteNode: transform.substituteNode, + }); + ts.Debug.assert(transform.transformed.length === 1, "Should only see one output from the transform"); + printSourceFileOrBundle(jsFilePath, sourceMapFilePath, transform.transformed[0], bundleInfoPath, printer, compilerOptions); + transform.dispose(); + } + function emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath) { + if (!(declarationFilePath && !ts.isInJSFile(sourceFileOrBundle))) { + return; + } + var sourceFiles = ts.isSourceFile(sourceFileOrBundle) ? [sourceFileOrBundle] : sourceFileOrBundle.sourceFiles; + var nonJsFiles = ts.filter(sourceFiles, ts.isSourceFileNotJS); + var inputListOrBundle = (compilerOptions.outFile || compilerOptions.out) ? [ts.createBundle(nonJsFiles, !ts.isSourceFile(sourceFileOrBundle) ? sourceFileOrBundle.prepends : undefined)] : nonJsFiles; + if (emitOnlyDtsFiles && !ts.getEmitDeclarations(compilerOptions)) { + nonJsFiles.forEach(collectLinkedAliases); + } + var declarationTransform = ts.transformNodes(resolver, host, compilerOptions, inputListOrBundle, ts.concatenate([ts.transformDeclarations], declarationTransformers), false); + if (ts.length(declarationTransform.diagnostics)) { + for (var _a = 0, _b = declarationTransform.diagnostics; _a < _b.length; _a++) { + var diagnostic = _b[_a]; + emitterDiagnostics.add(diagnostic); + } + } + var printerOptions = { + removeComments: compilerOptions.removeComments, + newLine: compilerOptions.newLine, + noEmitHelpers: true, + module: compilerOptions.module, + target: compilerOptions.target, + sourceMap: compilerOptions.sourceMap, + inlineSourceMap: compilerOptions.inlineSourceMap, + extendedDiagnostics: compilerOptions.extendedDiagnostics, + onlyPrintJsDocStyle: true, + }; + var declarationPrinter = createPrinter(printerOptions, { + hasGlobalName: resolver.hasGlobalName, + onEmitNode: declarationTransform.emitNodeWithNotification, + substituteNode: declarationTransform.substituteNode, + }); + var declBlocked = (!!declarationTransform.diagnostics && !!declarationTransform.diagnostics.length) || !!host.isEmitBlocked(declarationFilePath) || !!compilerOptions.noEmit; + emitSkipped = emitSkipped || declBlocked; + if (!declBlocked || emitOnlyDtsFiles) { + ts.Debug.assert(declarationTransform.transformed.length === 1, "Should only see one output from the decl transform"); + printSourceFileOrBundle(declarationFilePath, declarationMapPath, declarationTransform.transformed[0], undefined, declarationPrinter, { + sourceMap: compilerOptions.declarationMap, + sourceRoot: compilerOptions.sourceRoot, + mapRoot: compilerOptions.mapRoot, + extendedDiagnostics: compilerOptions.extendedDiagnostics, + }); + if (emitOnlyDtsFiles && declarationTransform.transformed[0].kind === 279) { + var sourceFile = declarationTransform.transformed[0]; + exportedModulesFromDeclarationEmit = sourceFile.exportedModulesFromDeclarationEmit; + } + } + declarationTransform.dispose(); + } + function collectLinkedAliases(node) { + if (ts.isExportAssignment(node)) { + if (node.expression.kind === 72) { + resolver.collectLinkedAliases(node.expression, true); + } + return; + } + else if (ts.isExportSpecifier(node)) { + resolver.collectLinkedAliases(node.propertyName || node.name, true); + return; + } + ts.forEachChild(node, collectLinkedAliases); + } + function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle, bundleInfoPath, printer, mapOptions) { + var bundle = sourceFileOrBundle.kind === 280 ? sourceFileOrBundle : undefined; + var sourceFile = sourceFileOrBundle.kind === 279 ? sourceFileOrBundle : undefined; + var sourceFiles = bundle ? bundle.sourceFiles : [sourceFile]; + var sourceMapGenerator; + if (shouldEmitSourceMaps(mapOptions, sourceFileOrBundle)) { + sourceMapGenerator = ts.createSourceMapGenerator(host, ts.getBaseFileName(ts.normalizeSlashes(jsFilePath)), getSourceRoot(mapOptions), getSourceMapDirectory(mapOptions, jsFilePath, sourceFile), mapOptions); + } + if (bundle) { + printer.writeBundle(bundle, bundleInfo, writer, sourceMapGenerator); + } + else { + printer.writeFile(sourceFile, writer, sourceMapGenerator); + } + if (sourceMapGenerator) { + if (sourceMapDataList) { + sourceMapDataList.push({ + inputSourceFileNames: sourceMapGenerator.getSources(), + sourceMap: sourceMapGenerator.toJSON() + }); + } + var sourceMappingURL = getSourceMappingURL(mapOptions, sourceMapGenerator, jsFilePath, sourceMapFilePath, sourceFile); + if (sourceMappingURL) { + if (!writer.isAtStartOfLine()) + writer.rawWrite(newLine); + writer.writeComment("//# " + "sourceMappingURL" + "=" + sourceMappingURL); + } + if (sourceMapFilePath) { + var sourceMap = sourceMapGenerator.toString(); + ts.writeFile(host, emitterDiagnostics, sourceMapFilePath, sourceMap, false, sourceFiles); + } + } + else { + writer.writeLine(); + } + ts.writeFile(host, emitterDiagnostics, jsFilePath, writer.getText(), !!compilerOptions.emitBOM, sourceFiles); + if (bundleInfoPath) { + bundleInfo.totalLength = writer.getTextPos(); + ts.writeFile(host, emitterDiagnostics, bundleInfoPath, JSON.stringify(bundleInfo, undefined, 2), false); + } + writer.clear(); + bundleInfo = createDefaultBundleInfo(); + } + function shouldEmitSourceMaps(mapOptions, sourceFileOrBundle) { + return (mapOptions.sourceMap || mapOptions.inlineSourceMap) + && (sourceFileOrBundle.kind !== 279 || !ts.fileExtensionIs(sourceFileOrBundle.fileName, ".json")); + } + function getSourceRoot(mapOptions) { + var sourceRoot = ts.normalizeSlashes(mapOptions.sourceRoot || ""); + return sourceRoot ? ts.ensureTrailingDirectorySeparator(sourceRoot) : sourceRoot; + } + function getSourceMapDirectory(mapOptions, filePath, sourceFile) { + if (mapOptions.sourceRoot) + return host.getCommonSourceDirectory(); + if (mapOptions.mapRoot) { + var sourceMapDir = ts.normalizeSlashes(mapOptions.mapRoot); + if (sourceFile) { + sourceMapDir = ts.getDirectoryPath(ts.getSourceFilePathInNewDir(sourceFile.fileName, host, sourceMapDir)); + } + if (ts.getRootLength(sourceMapDir) === 0) { + sourceMapDir = ts.combinePaths(host.getCommonSourceDirectory(), sourceMapDir); + } + return sourceMapDir; + } + return ts.getDirectoryPath(ts.normalizePath(filePath)); + } + function getSourceMappingURL(mapOptions, sourceMapGenerator, filePath, sourceMapFilePath, sourceFile) { + if (mapOptions.inlineSourceMap) { + var sourceMapText = sourceMapGenerator.toString(); + var base64SourceMapText = ts.base64encode(ts.sys, sourceMapText); + return "data:application/json;base64," + base64SourceMapText; + } + var sourceMapFile = ts.getBaseFileName(ts.normalizeSlashes(ts.Debug.assertDefined(sourceMapFilePath))); + if (mapOptions.mapRoot) { + var sourceMapDir = ts.normalizeSlashes(mapOptions.mapRoot); + if (sourceFile) { + sourceMapDir = ts.getDirectoryPath(ts.getSourceFilePathInNewDir(sourceFile.fileName, host, sourceMapDir)); + } + if (ts.getRootLength(sourceMapDir) === 0) { + sourceMapDir = ts.combinePaths(host.getCommonSourceDirectory(), sourceMapDir); + return ts.getRelativePathToDirectoryOrUrl(ts.getDirectoryPath(ts.normalizePath(filePath)), ts.combinePaths(sourceMapDir, sourceMapFile), host.getCurrentDirectory(), host.getCanonicalFileName, true); + } + else { + return ts.combinePaths(sourceMapDir, sourceMapFile); + } + } + return sourceMapFile; + } + } + ts.emitFiles = emitFiles; + function createPrinter(printerOptions, handlers) { + if (printerOptions === void 0) { printerOptions = {}; } + if (handlers === void 0) { handlers = {}; } + var hasGlobalName = handlers.hasGlobalName, _a = handlers.onEmitNode, onEmitNode = _a === void 0 ? ts.noEmitNotification : _a, _b = handlers.substituteNode, substituteNode = _b === void 0 ? ts.noEmitSubstitution : _b, onBeforeEmitNodeArray = handlers.onBeforeEmitNodeArray, onAfterEmitNodeArray = handlers.onAfterEmitNodeArray, onBeforeEmitToken = handlers.onBeforeEmitToken, onAfterEmitToken = handlers.onAfterEmitToken; + var extendedDiagnostics = !!printerOptions.extendedDiagnostics; + var newLine = ts.getNewLineCharacter(printerOptions); + var moduleKind = ts.getEmitModuleKind(printerOptions); + var bundledHelpers = ts.createMap(); + var currentSourceFile; + var nodeIdToGeneratedName; + var autoGeneratedIdToGeneratedName; + var generatedNames; + var tempFlagsStack; + var tempFlags; + var reservedNamesStack; + var reservedNames; + var writer; + var ownWriter; + var write = writeBase; + var isOwnFileEmit; + var sourceMapsDisabled = true; + var sourceMapGenerator; + var sourceMapSource; + var sourceMapSourceIndex = -1; + var containerPos = -1; + var containerEnd = -1; + var declarationListContainerEnd = -1; + var currentLineMap; + var detachedCommentsInfo; + var hasWrittenComment = false; + var commentsDisabled = !!printerOptions.removeComments; + var _c = ts.performance.createTimerIf(extendedDiagnostics, "commentTime", "beforeComment", "afterComment"), enterComment = _c.enter, exitComment = _c.exit; + reset(); + return { + printNode: printNode, + printList: printList, + printFile: printFile, + printBundle: printBundle, + writeNode: writeNode, + writeList: writeList, + writeFile: writeFile, + writeBundle: writeBundle + }; + function printNode(hint, node, sourceFile) { + switch (hint) { + case 0: + ts.Debug.assert(ts.isSourceFile(node), "Expected a SourceFile node."); + break; + case 2: + ts.Debug.assert(ts.isIdentifier(node), "Expected an Identifier node."); + break; + case 1: + ts.Debug.assert(ts.isExpression(node), "Expected an Expression node."); + break; + } + switch (node.kind) { + case 279: return printFile(node); + case 280: return printBundle(node); + case 281: return printUnparsedSource(node); + } + writeNode(hint, node, sourceFile, beginPrint()); + return endPrint(); + } + function printList(format, nodes, sourceFile) { + writeList(format, nodes, sourceFile, beginPrint()); + return endPrint(); + } + function printBundle(bundle) { + writeBundle(bundle, undefined, beginPrint(), undefined); + return endPrint(); + } + function printFile(sourceFile) { + writeFile(sourceFile, beginPrint(), undefined); + return endPrint(); + } + function printUnparsedSource(unparsed) { + writeUnparsedSource(unparsed, beginPrint()); + return endPrint(); + } + function writeNode(hint, node, sourceFile, output) { + var previousWriter = writer; + setWriter(output, undefined); + print(hint, node, sourceFile); + reset(); + writer = previousWriter; + } + function writeList(format, nodes, sourceFile, output) { + var previousWriter = writer; + setWriter(output, undefined); + if (sourceFile) { + setSourceFile(sourceFile); + } + emitList(syntheticParent, nodes, format); + reset(); + writer = previousWriter; + } + function writeBundle(bundle, bundleInfo, output, sourceMapGenerator) { + isOwnFileEmit = false; + var previousWriter = writer; + setWriter(output, sourceMapGenerator); + emitShebangIfNeeded(bundle); + emitPrologueDirectivesIfNeeded(bundle); + emitHelpers(bundle); + emitSyntheticTripleSlashReferencesIfNeeded(bundle); + for (var _a = 0, _b = bundle.prepends; _a < _b.length; _a++) { + var prepend = _b[_a]; + writeLine(); + print(4, prepend, undefined); + } + if (bundleInfo) { + bundleInfo.originalOffset = writer.getTextPos(); + } + for (var _c = 0, _d = bundle.sourceFiles; _c < _d.length; _c++) { + var sourceFile = _d[_c]; + print(0, sourceFile, sourceFile); + } + reset(); + writer = previousWriter; + } + function writeUnparsedSource(unparsed, output) { + var previousWriter = writer; + setWriter(output, undefined); + print(4, unparsed, undefined); + reset(); + writer = previousWriter; + } + function writeFile(sourceFile, output, sourceMapGenerator) { + isOwnFileEmit = true; + var previousWriter = writer; + setWriter(output, sourceMapGenerator); + emitShebangIfNeeded(sourceFile); + emitPrologueDirectivesIfNeeded(sourceFile); + print(0, sourceFile, sourceFile); + reset(); + writer = previousWriter; + } + function beginPrint() { + return ownWriter || (ownWriter = ts.createTextWriter(newLine)); + } + function endPrint() { + var text = ownWriter.getText(); + ownWriter.clear(); + return text; + } + function print(hint, node, sourceFile) { + if (sourceFile) { + setSourceFile(sourceFile); + } + var pipelinePhase = getPipelinePhase(0, node); + pipelinePhase(hint, node); + } + function setSourceFile(sourceFile) { + currentSourceFile = sourceFile; + currentLineMap = undefined; + detachedCommentsInfo = undefined; + if (sourceFile) { + setSourceMapSource(sourceFile); + } + } + function setWriter(_writer, _sourceMapGenerator) { + if (_writer && printerOptions.omitTrailingSemicolon) { + _writer = ts.getTrailingSemicolonOmittingWriter(_writer); + } + writer = _writer; + sourceMapGenerator = _sourceMapGenerator; + sourceMapsDisabled = !writer || !sourceMapGenerator; + } + function reset() { + nodeIdToGeneratedName = []; + autoGeneratedIdToGeneratedName = []; + generatedNames = ts.createMap(); + tempFlagsStack = []; + tempFlags = 0; + reservedNamesStack = []; + currentSourceFile = undefined; + currentLineMap = undefined; + detachedCommentsInfo = undefined; + setWriter(undefined, undefined); + } + function getCurrentLineMap() { + return currentLineMap || (currentLineMap = ts.getLineStarts(currentSourceFile)); + } + function emit(node) { + if (node === undefined) + return; + var pipelinePhase = getPipelinePhase(0, node); + pipelinePhase(4, node); + } + function emitIdentifierName(node) { + if (node === undefined) + return; + var pipelinePhase = getPipelinePhase(0, node); + pipelinePhase(2, node); + } + function emitExpression(node) { + if (node === undefined) + return; + var pipelinePhase = getPipelinePhase(0, node); + pipelinePhase(1, node); + } + function getPipelinePhase(phase, node) { + switch (phase) { + case 0: + if (onEmitNode !== ts.noEmitNotification) { + return pipelineEmitWithNotification; + } + case 1: + if (substituteNode !== ts.noEmitSubstitution) { + return pipelineEmitWithSubstitution; + } + case 2: + if (!commentsDisabled && node.kind !== 279) { + return pipelineEmitWithComments; + } + case 3: + if (!sourceMapsDisabled && node.kind !== 279 && !ts.isInJsonFile(node)) { + return pipelineEmitWithSourceMap; + } + case 4: + return pipelineEmitWithHint; + default: + return ts.Debug.assertNever(phase); + } + } + function getNextPipelinePhase(currentPhase, node) { + return getPipelinePhase(currentPhase + 1, node); + } + function pipelineEmitWithNotification(hint, node) { + var pipelinePhase = getNextPipelinePhase(0, node); + onEmitNode(hint, node, pipelinePhase); + } + function pipelineEmitWithHint(hint, node) { + if (hint === 0) + return emitSourceFile(ts.cast(node, ts.isSourceFile)); + if (hint === 2) + return emitIdentifier(ts.cast(node, ts.isIdentifier)); + if (hint === 3) + return emitMappedTypeParameter(ts.cast(node, ts.isTypeParameterDeclaration)); + if (hint === 5) { + ts.Debug.assertNode(node, ts.isEmptyStatement); + return emitEmptyStatement(true); + } + if (hint === 4) { + if (ts.isKeyword(node.kind)) + return writeTokenNode(node, writeKeyword); + switch (node.kind) { + case 15: + case 16: + case 17: + return emitLiteral(node); + case 281: + return emitUnparsedSource(node); + case 72: + return emitIdentifier(node); + case 148: + return emitQualifiedName(node); + case 149: + return emitComputedPropertyName(node); + case 150: + return emitTypeParameter(node); + case 151: + return emitParameter(node); + case 152: + return emitDecorator(node); + case 153: + return emitPropertySignature(node); + case 154: + return emitPropertyDeclaration(node); + case 155: + return emitMethodSignature(node); + case 156: + return emitMethodDeclaration(node); + case 157: + return emitConstructor(node); + case 158: + case 159: + return emitAccessorDeclaration(node); + case 160: + return emitCallSignature(node); + case 161: + return emitConstructSignature(node); + case 162: + return emitIndexSignature(node); + case 163: + return emitTypePredicate(node); + case 164: + return emitTypeReference(node); + case 165: + return emitFunctionType(node); + case 289: + return emitJSDocFunctionType(node); + case 166: + return emitConstructorType(node); + case 167: + return emitTypeQuery(node); + case 168: + return emitTypeLiteral(node); + case 169: + return emitArrayType(node); + case 170: + return emitTupleType(node); + case 171: + return emitOptionalType(node); + case 173: + return emitUnionType(node); + case 174: + return emitIntersectionType(node); + case 175: + return emitConditionalType(node); + case 176: + return emitInferType(node); + case 177: + return emitParenthesizedType(node); + case 211: + return emitExpressionWithTypeArguments(node); + case 178: + return emitThisType(); + case 179: + return emitTypeOperator(node); + case 180: + return emitIndexedAccessType(node); + case 181: + return emitMappedType(node); + case 182: + return emitLiteralType(node); + case 183: + return emitImportTypeNode(node); + case 284: + writePunctuation("*"); + return; + case 285: + writePunctuation("?"); + return; + case 286: + return emitJSDocNullableType(node); + case 287: + return emitJSDocNonNullableType(node); + case 288: + return emitJSDocOptionalType(node); + case 172: + case 290: + return emitRestOrJSDocVariadicType(node); + case 184: + return emitObjectBindingPattern(node); + case 185: + return emitArrayBindingPattern(node); + case 186: + return emitBindingElement(node); + case 216: + return emitTemplateSpan(node); + case 217: + return emitSemicolonClassElement(); + case 218: + return emitBlock(node); + case 219: + return emitVariableStatement(node); + case 220: + return emitEmptyStatement(false); + case 221: + return emitExpressionStatement(node); + case 222: + return emitIfStatement(node); + case 223: + return emitDoStatement(node); + case 224: + return emitWhileStatement(node); + case 225: + return emitForStatement(node); + case 226: + return emitForInStatement(node); + case 227: + return emitForOfStatement(node); + case 228: + return emitContinueStatement(node); + case 229: + return emitBreakStatement(node); + case 230: + return emitReturnStatement(node); + case 231: + return emitWithStatement(node); + case 232: + return emitSwitchStatement(node); + case 233: + return emitLabeledStatement(node); + case 234: + return emitThrowStatement(node); + case 235: + return emitTryStatement(node); + case 236: + return emitDebuggerStatement(node); + case 237: + return emitVariableDeclaration(node); + case 238: + return emitVariableDeclarationList(node); + case 239: + return emitFunctionDeclaration(node); + case 240: + return emitClassDeclaration(node); + case 241: + return emitInterfaceDeclaration(node); + case 242: + return emitTypeAliasDeclaration(node); + case 243: + return emitEnumDeclaration(node); + case 244: + return emitModuleDeclaration(node); + case 245: + return emitModuleBlock(node); + case 246: + return emitCaseBlock(node); + case 247: + return emitNamespaceExportDeclaration(node); + case 248: + return emitImportEqualsDeclaration(node); + case 249: + return emitImportDeclaration(node); + case 250: + return emitImportClause(node); + case 251: + return emitNamespaceImport(node); + case 252: + return emitNamedImports(node); + case 253: + return emitImportSpecifier(node); + case 254: + return emitExportAssignment(node); + case 255: + return emitExportDeclaration(node); + case 256: + return emitNamedExports(node); + case 257: + return emitExportSpecifier(node); + case 258: + return; + case 259: + return emitExternalModuleReference(node); + case 11: + return emitJsxText(node); + case 262: + case 265: + return emitJsxOpeningElementOrFragment(node); + case 263: + case 266: + return emitJsxClosingElementOrFragment(node); + case 267: + return emitJsxAttribute(node); + case 268: + return emitJsxAttributes(node); + case 269: + return emitJsxSpreadAttribute(node); + case 270: + return emitJsxExpression(node); + case 271: + return emitCaseClause(node); + case 272: + return emitDefaultClause(node); + case 273: + return emitHeritageClause(node); + case 274: + return emitCatchClause(node); + case 275: + return emitPropertyAssignment(node); + case 276: + return emitShorthandPropertyAssignment(node); + case 277: + return emitSpreadAssignment(node); + case 278: + return emitEnumMember(node); + case 299: + case 305: + return emitJSDocPropertyLikeTag(node); + case 300: + case 302: + case 301: + case 298: + return emitJSDocSimpleTypedTag(node); + case 295: + return emitJSDocAugmentsTag(node); + case 303: + return emitJSDocTemplateTag(node); + case 304: + return emitJSDocTypedefTag(node); + case 297: + return emitJSDocCallbackTag(node); + case 293: + return emitJSDocSignature(node); + case 292: + return emitJSDocTypeLiteral(node); + case 296: + case 294: + return emitJSDocSimpleTag(node); + case 291: + return emitJSDoc(node); + } + if (ts.isExpression(node)) { + hint = 1; + if (substituteNode !== ts.noEmitSubstitution) { + node = substituteNode(hint, node); + } + } + else if (ts.isToken(node)) { + return writeTokenNode(node, writePunctuation); + } + } + if (hint === 1) { + switch (node.kind) { + case 8: + case 9: + return emitNumericOrBigIntLiteral(node); + case 10: + case 13: + case 14: + return emitLiteral(node); + case 72: + return emitIdentifier(node); + case 87: + case 96: + case 98: + case 102: + case 100: + case 92: + writeTokenNode(node, writeKeyword); + return; + case 187: + return emitArrayLiteralExpression(node); + case 188: + return emitObjectLiteralExpression(node); + case 189: + return emitPropertyAccessExpression(node); + case 190: + return emitElementAccessExpression(node); + case 191: + return emitCallExpression(node); + case 192: + return emitNewExpression(node); + case 193: + return emitTaggedTemplateExpression(node); + case 194: + return emitTypeAssertionExpression(node); + case 195: + return emitParenthesizedExpression(node); + case 196: + return emitFunctionExpression(node); + case 197: + return emitArrowFunction(node); + case 198: + return emitDeleteExpression(node); + case 199: + return emitTypeOfExpression(node); + case 200: + return emitVoidExpression(node); + case 201: + return emitAwaitExpression(node); + case 202: + return emitPrefixUnaryExpression(node); + case 203: + return emitPostfixUnaryExpression(node); + case 204: + return emitBinaryExpression(node); + case 205: + return emitConditionalExpression(node); + case 206: + return emitTemplateExpression(node); + case 207: + return emitYieldExpression(node); + case 208: + return emitSpreadExpression(node); + case 209: + return emitClassExpression(node); + case 210: + return; + case 212: + return emitAsExpression(node); + case 213: + return emitNonNullExpression(node); + case 214: + return emitMetaProperty(node); + case 260: + return emitJsxElement(node); + case 261: + return emitJsxSelfClosingElement(node); + case 264: + return emitJsxFragment(node); + case 308: + return emitPartiallyEmittedExpression(node); + case 309: + return emitCommaList(node); + } + } + } + function emitMappedTypeParameter(node) { + emit(node.name); + writeSpace(); + writeKeyword("in"); + writeSpace(); + emit(node.constraint); + } + function pipelineEmitWithSubstitution(hint, node) { + var pipelinePhase = getNextPipelinePhase(1, node); + pipelinePhase(hint, substituteNode(hint, node)); + } + function emitHelpers(node) { + var helpersEmitted = false; + var bundle = node.kind === 280 ? node : undefined; + if (bundle && moduleKind === ts.ModuleKind.None) { + return; + } + var numNodes = bundle ? bundle.sourceFiles.length : 1; + for (var i = 0; i < numNodes; i++) { + var currentNode = bundle ? bundle.sourceFiles[i] : node; + var sourceFile = ts.isSourceFile(currentNode) ? currentNode : currentSourceFile; + var shouldSkip = printerOptions.noEmitHelpers || ts.getExternalHelpersModuleName(sourceFile) !== undefined; + var shouldBundle = ts.isSourceFile(currentNode) && !isOwnFileEmit; + var helpers = ts.getEmitHelpers(currentNode); + if (helpers) { + for (var _a = 0, _b = ts.stableSort(helpers, ts.compareEmitHelpers); _a < _b.length; _a++) { + var helper = _b[_a]; + if (!helper.scoped) { + if (shouldSkip) + continue; + if (shouldBundle) { + if (bundledHelpers.get(helper.name)) { + continue; + } + bundledHelpers.set(helper.name, true); + } + } + else if (bundle) { + continue; + } + if (typeof helper.text === "string") { + writeLines(helper.text); + } + else { + writeLines(helper.text(makeFileLevelOptimisticUniqueName)); + } + helpersEmitted = true; + } + } + } + return helpersEmitted; + } + function emitNumericOrBigIntLiteral(node) { + emitLiteral(node); + } + function emitLiteral(node) { + var text = getLiteralTextOfNode(node, printerOptions.neverAsciiEscape); + if ((printerOptions.sourceMap || printerOptions.inlineSourceMap) + && (node.kind === 10 || ts.isTemplateLiteralKind(node.kind))) { + writeLiteral(text); + } + else { + writeStringLiteral(text); + } + } + function emitUnparsedSource(unparsed) { + writer.rawWrite(unparsed.text); + } + function emitIdentifier(node) { + var writeText = node.symbol ? writeSymbol : write; + writeText(getTextOfNode(node, false), node.symbol); + emitList(node, node.typeArguments, 53776); + } + function emitQualifiedName(node) { + emitEntityName(node.left); + writePunctuation("."); + emit(node.right); + } + function emitEntityName(node) { + if (node.kind === 72) { + emitExpression(node); + } + else { + emit(node); + } + } + function emitComputedPropertyName(node) { + writePunctuation("["); + emitExpression(node.expression); + writePunctuation("]"); + } + function emitTypeParameter(node) { + emit(node.name); + if (node.constraint) { + writeSpace(); + writeKeyword("extends"); + writeSpace(); + emit(node.constraint); + } + if (node.default) { + writeSpace(); + writeOperator("="); + writeSpace(); + emit(node.default); + } + } + function emitParameter(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + emit(node.dotDotDotToken); + emitNodeWithWriter(node.name, writeParameter); + emit(node.questionToken); + if (node.parent && node.parent.kind === 289 && !node.name) { + emit(node.type); + } + else { + emitTypeAnnotation(node.type); + } + emitInitializer(node.initializer, node.type ? node.type.end : node.questionToken ? node.questionToken.end : node.name ? node.name.end : node.modifiers ? node.modifiers.end : node.decorators ? node.decorators.end : node.pos, node); + } + function emitDecorator(decorator) { + writePunctuation("@"); + emitExpression(decorator.expression); + } + function emitPropertySignature(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + emitNodeWithWriter(node.name, writeProperty); + emit(node.questionToken); + emitTypeAnnotation(node.type); + writeTrailingSemicolon(); + } + function emitPropertyDeclaration(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + emit(node.name); + emit(node.questionToken); + emit(node.exclamationToken); + emitTypeAnnotation(node.type); + emitInitializer(node.initializer, node.type ? node.type.end : node.questionToken ? node.questionToken.end : node.name.end, node); + writeTrailingSemicolon(); + } + function emitMethodSignature(node) { + pushNameGenerationScope(node); + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + emit(node.name); + emit(node.questionToken); + emitTypeParameters(node, node.typeParameters); + emitParameters(node, node.parameters); + emitTypeAnnotation(node.type); + writeTrailingSemicolon(); + popNameGenerationScope(node); + } + function emitMethodDeclaration(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + emit(node.asteriskToken); + emit(node.name); + emit(node.questionToken); + emitSignatureAndBody(node, emitSignatureHead); + } + function emitConstructor(node) { + emitModifiers(node, node.modifiers); + writeKeyword("constructor"); + emitSignatureAndBody(node, emitSignatureHead); + } + function emitAccessorDeclaration(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + writeKeyword(node.kind === 158 ? "get" : "set"); + writeSpace(); + emit(node.name); + emitSignatureAndBody(node, emitSignatureHead); + } + function emitCallSignature(node) { + pushNameGenerationScope(node); + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + emitTypeParameters(node, node.typeParameters); + emitParameters(node, node.parameters); + emitTypeAnnotation(node.type); + writeTrailingSemicolon(); + popNameGenerationScope(node); + } + function emitConstructSignature(node) { + pushNameGenerationScope(node); + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + writeKeyword("new"); + writeSpace(); + emitTypeParameters(node, node.typeParameters); + emitParameters(node, node.parameters); + emitTypeAnnotation(node.type); + writeTrailingSemicolon(); + popNameGenerationScope(node); + } + function emitIndexSignature(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + emitParametersForIndexSignature(node, node.parameters); + emitTypeAnnotation(node.type); + writeTrailingSemicolon(); + } + function emitSemicolonClassElement() { + writeTrailingSemicolon(); + } + function emitTypePredicate(node) { + emit(node.parameterName); + writeSpace(); + writeKeyword("is"); + writeSpace(); + emit(node.type); + } + function emitTypeReference(node) { + emit(node.typeName); + emitTypeArguments(node, node.typeArguments); + } + function emitFunctionType(node) { + pushNameGenerationScope(node); + emitTypeParameters(node, node.typeParameters); + emitParametersForArrow(node, node.parameters); + writeSpace(); + writePunctuation("=>"); + writeSpace(); + emit(node.type); + popNameGenerationScope(node); + } + function emitJSDocFunctionType(node) { + writeKeyword("function"); + emitParameters(node, node.parameters); + writePunctuation(":"); + emit(node.type); + } + function emitJSDocNullableType(node) { + writePunctuation("?"); + emit(node.type); + } + function emitJSDocNonNullableType(node) { + writePunctuation("!"); + emit(node.type); + } + function emitJSDocOptionalType(node) { + emit(node.type); + writePunctuation("="); + } + function emitConstructorType(node) { + pushNameGenerationScope(node); + writeKeyword("new"); + writeSpace(); + emitTypeParameters(node, node.typeParameters); + emitParameters(node, node.parameters); + writeSpace(); + writePunctuation("=>"); + writeSpace(); + emit(node.type); + popNameGenerationScope(node); + } + function emitTypeQuery(node) { + writeKeyword("typeof"); + writeSpace(); + emit(node.exprName); + } + function emitTypeLiteral(node) { + writePunctuation("{"); + var flags = ts.getEmitFlags(node) & 1 ? 768 : 32897; + emitList(node, node.members, flags | 524288); + writePunctuation("}"); + } + function emitArrayType(node) { + emit(node.elementType); + writePunctuation("["); + writePunctuation("]"); + } + function emitRestOrJSDocVariadicType(node) { + writePunctuation("..."); + emit(node.type); + } + function emitTupleType(node) { + writePunctuation("["); + emitList(node, node.elementTypes, 528); + writePunctuation("]"); + } + function emitOptionalType(node) { + emit(node.type); + writePunctuation("?"); + } + function emitUnionType(node) { + emitList(node, node.types, 516); + } + function emitIntersectionType(node) { + emitList(node, node.types, 520); + } + function emitConditionalType(node) { + emit(node.checkType); + writeSpace(); + writeKeyword("extends"); + writeSpace(); + emit(node.extendsType); + writeSpace(); + writePunctuation("?"); + writeSpace(); + emit(node.trueType); + writeSpace(); + writePunctuation(":"); + writeSpace(); + emit(node.falseType); + } + function emitInferType(node) { + writeKeyword("infer"); + writeSpace(); + emit(node.typeParameter); + } + function emitParenthesizedType(node) { + writePunctuation("("); + emit(node.type); + writePunctuation(")"); + } + function emitThisType() { + writeKeyword("this"); + } + function emitTypeOperator(node) { + writeTokenText(node.operator, writeKeyword); + writeSpace(); + emit(node.type); + } + function emitIndexedAccessType(node) { + emit(node.objectType); + writePunctuation("["); + emit(node.indexType); + writePunctuation("]"); + } + function emitMappedType(node) { + var emitFlags = ts.getEmitFlags(node); + writePunctuation("{"); + if (emitFlags & 1) { + writeSpace(); + } + else { + writeLine(); + increaseIndent(); + } + if (node.readonlyToken) { + emit(node.readonlyToken); + if (node.readonlyToken.kind !== 133) { + writeKeyword("readonly"); + } + writeSpace(); + } + writePunctuation("["); + var pipelinePhase = getPipelinePhase(0, node.typeParameter); + pipelinePhase(3, node.typeParameter); + writePunctuation("]"); + if (node.questionToken) { + emit(node.questionToken); + if (node.questionToken.kind !== 56) { + writePunctuation("?"); + } + } + writePunctuation(":"); + writeSpace(); + emit(node.type); + writeTrailingSemicolon(); + if (emitFlags & 1) { + writeSpace(); + } + else { + writeLine(); + decreaseIndent(); + } + writePunctuation("}"); + } + function emitLiteralType(node) { + emitExpression(node.literal); + } + function emitImportTypeNode(node) { + if (node.isTypeOf) { + writeKeyword("typeof"); + writeSpace(); + } + writeKeyword("import"); + writePunctuation("("); + emit(node.argument); + writePunctuation(")"); + if (node.qualifier) { + writePunctuation("."); + emit(node.qualifier); + } + emitTypeArguments(node, node.typeArguments); + } + function emitObjectBindingPattern(node) { + writePunctuation("{"); + emitList(node, node.elements, 525136); + writePunctuation("}"); + } + function emitArrayBindingPattern(node) { + writePunctuation("["); + emitList(node, node.elements, 524880); + writePunctuation("]"); + } + function emitBindingElement(node) { + emit(node.dotDotDotToken); + if (node.propertyName) { + emit(node.propertyName); + writePunctuation(":"); + writeSpace(); + } + emit(node.name); + emitInitializer(node.initializer, node.name.end, node); + } + function emitArrayLiteralExpression(node) { + var elements = node.elements; + var preferNewLine = node.multiLine ? 65536 : 0; + emitExpressionList(node, elements, 8914 | preferNewLine); + } + function emitObjectLiteralExpression(node) { + ts.forEach(node.properties, generateMemberNames); + var indentedFlag = ts.getEmitFlags(node) & 65536; + if (indentedFlag) { + increaseIndent(); + } + var preferNewLine = node.multiLine ? 65536 : 0; + var allowTrailingComma = currentSourceFile.languageVersion >= 1 && !ts.isJsonSourceFile(currentSourceFile) ? 64 : 0; + emitList(node, node.properties, 526226 | allowTrailingComma | preferNewLine); + if (indentedFlag) { + decreaseIndent(); + } + } + function emitPropertyAccessExpression(node) { + var indentBeforeDot = false; + var indentAfterDot = false; + if (!(ts.getEmitFlags(node) & 131072)) { + var dotRangeStart = node.expression.end; + var dotRangeEnd = ts.skipTrivia(currentSourceFile.text, node.expression.end) + 1; + var dotToken = ts.createToken(24); + dotToken.pos = dotRangeStart; + dotToken.end = dotRangeEnd; + indentBeforeDot = needsIndentation(node, node.expression, dotToken); + indentAfterDot = needsIndentation(node, dotToken, node.name); + } + emitExpression(node.expression); + increaseIndentIf(indentBeforeDot, false); + var shouldEmitDotDot = !indentBeforeDot && needsDotDotForPropertyAccess(node.expression); + if (shouldEmitDotDot) { + writePunctuation("."); + } + emitTokenWithComment(24, node.expression.end, writePunctuation, node); + increaseIndentIf(indentAfterDot, false); + emit(node.name); + decreaseIndentIf(indentBeforeDot, indentAfterDot); + } + function needsDotDotForPropertyAccess(expression) { + expression = ts.skipPartiallyEmittedExpressions(expression); + if (ts.isNumericLiteral(expression)) { + var text = getLiteralTextOfNode(expression, true); + return !expression.numericLiteralFlags + && !ts.stringContains(text, ts.tokenToString(24)); + } + else if (ts.isPropertyAccessExpression(expression) || ts.isElementAccessExpression(expression)) { + var constantValue = ts.getConstantValue(expression); + return typeof constantValue === "number" && isFinite(constantValue) + && Math.floor(constantValue) === constantValue + && printerOptions.removeComments; + } + } + function emitElementAccessExpression(node) { + emitExpression(node.expression); + emitTokenWithComment(22, node.expression.end, writePunctuation, node); + emitExpression(node.argumentExpression); + emitTokenWithComment(23, node.argumentExpression.end, writePunctuation, node); + } + function emitCallExpression(node) { + emitExpression(node.expression); + emitTypeArguments(node, node.typeArguments); + emitExpressionList(node, node.arguments, 2576); + } + function emitNewExpression(node) { + emitTokenWithComment(95, node.pos, writeKeyword, node); + writeSpace(); + emitExpression(node.expression); + emitTypeArguments(node, node.typeArguments); + emitExpressionList(node, node.arguments, 18960); + } + function emitTaggedTemplateExpression(node) { + emitExpression(node.tag); + emitTypeArguments(node, node.typeArguments); + writeSpace(); + emitExpression(node.template); + } + function emitTypeAssertionExpression(node) { + writePunctuation("<"); + emit(node.type); + writePunctuation(">"); + emitExpression(node.expression); + } + function emitParenthesizedExpression(node) { + var openParenPos = emitTokenWithComment(20, node.pos, writePunctuation, node); + emitExpression(node.expression); + emitTokenWithComment(21, node.expression ? node.expression.end : openParenPos, writePunctuation, node); + } + function emitFunctionExpression(node) { + generateNameIfNeeded(node.name); + emitFunctionDeclarationOrExpression(node); + } + function emitArrowFunction(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + emitSignatureAndBody(node, emitArrowFunctionHead); + } + function emitArrowFunctionHead(node) { + emitTypeParameters(node, node.typeParameters); + emitParametersForArrow(node, node.parameters); + emitTypeAnnotation(node.type); + writeSpace(); + emit(node.equalsGreaterThanToken); + } + function emitDeleteExpression(node) { + emitTokenWithComment(81, node.pos, writeKeyword, node); + writeSpace(); + emitExpression(node.expression); + } + function emitTypeOfExpression(node) { + emitTokenWithComment(104, node.pos, writeKeyword, node); + writeSpace(); + emitExpression(node.expression); + } + function emitVoidExpression(node) { + emitTokenWithComment(106, node.pos, writeKeyword, node); + writeSpace(); + emitExpression(node.expression); + } + function emitAwaitExpression(node) { + emitTokenWithComment(122, node.pos, writeKeyword, node); + writeSpace(); + emitExpression(node.expression); + } + function emitPrefixUnaryExpression(node) { + writeTokenText(node.operator, writeOperator); + if (shouldEmitWhitespaceBeforeOperand(node)) { + writeSpace(); + } + emitExpression(node.operand); + } + function shouldEmitWhitespaceBeforeOperand(node) { + var operand = node.operand; + return operand.kind === 202 + && ((node.operator === 38 && (operand.operator === 38 || operand.operator === 44)) + || (node.operator === 39 && (operand.operator === 39 || operand.operator === 45))); + } + function emitPostfixUnaryExpression(node) { + emitExpression(node.operand); + writeTokenText(node.operator, writeOperator); + } + function emitBinaryExpression(node) { + var isCommaOperator = node.operatorToken.kind !== 27; + var indentBeforeOperator = needsIndentation(node, node.left, node.operatorToken); + var indentAfterOperator = needsIndentation(node, node.operatorToken, node.right); + emitExpression(node.left); + increaseIndentIf(indentBeforeOperator, isCommaOperator); + emitLeadingCommentsOfPosition(node.operatorToken.pos); + writeTokenNode(node.operatorToken, node.operatorToken.kind === 93 ? writeKeyword : writeOperator); + emitTrailingCommentsOfPosition(node.operatorToken.end, true); + increaseIndentIf(indentAfterOperator, true); + emitExpression(node.right); + decreaseIndentIf(indentBeforeOperator, indentAfterOperator); + } + function emitConditionalExpression(node) { + var indentBeforeQuestion = needsIndentation(node, node.condition, node.questionToken); + var indentAfterQuestion = needsIndentation(node, node.questionToken, node.whenTrue); + var indentBeforeColon = needsIndentation(node, node.whenTrue, node.colonToken); + var indentAfterColon = needsIndentation(node, node.colonToken, node.whenFalse); + emitExpression(node.condition); + increaseIndentIf(indentBeforeQuestion, true); + emit(node.questionToken); + increaseIndentIf(indentAfterQuestion, true); + emitExpression(node.whenTrue); + decreaseIndentIf(indentBeforeQuestion, indentAfterQuestion); + increaseIndentIf(indentBeforeColon, true); + emit(node.colonToken); + increaseIndentIf(indentAfterColon, true); + emitExpression(node.whenFalse); + decreaseIndentIf(indentBeforeColon, indentAfterColon); + } + function emitTemplateExpression(node) { + emit(node.head); + emitList(node, node.templateSpans, 262144); + } + function emitYieldExpression(node) { + emitTokenWithComment(117, node.pos, writeKeyword, node); + emit(node.asteriskToken); + emitExpressionWithLeadingSpace(node.expression); + } + function emitSpreadExpression(node) { + emitTokenWithComment(25, node.pos, writePunctuation, node); + emitExpression(node.expression); + } + function emitClassExpression(node) { + generateNameIfNeeded(node.name); + emitClassDeclarationOrExpression(node); + } + function emitExpressionWithTypeArguments(node) { + emitExpression(node.expression); + emitTypeArguments(node, node.typeArguments); + } + function emitAsExpression(node) { + emitExpression(node.expression); + if (node.type) { + writeSpace(); + writeKeyword("as"); + writeSpace(); + emit(node.type); + } + } + function emitNonNullExpression(node) { + emitExpression(node.expression); + writeOperator("!"); + } + function emitMetaProperty(node) { + writeToken(node.keywordToken, node.pos, writePunctuation); + writePunctuation("."); + emit(node.name); + } + function emitTemplateSpan(node) { + emitExpression(node.expression); + emit(node.literal); + } + function emitBlock(node) { + emitBlockStatements(node, !node.multiLine && isEmptyBlock(node)); + } + function emitBlockStatements(node, forceSingleLine) { + emitTokenWithComment(18, node.pos, writePunctuation, node); + var format = forceSingleLine || ts.getEmitFlags(node) & 1 ? 768 : 129; + emitList(node, node.statements, format); + emitTokenWithComment(19, node.statements.end, writePunctuation, node, !!(format & 1)); + } + function emitVariableStatement(node) { + emitModifiers(node, node.modifiers); + emit(node.declarationList); + writeTrailingSemicolon(); + } + function emitEmptyStatement(isEmbeddedStatement) { + if (isEmbeddedStatement) { + writePunctuation(";"); + } + else { + writeTrailingSemicolon(); + } + } + function emitExpressionStatement(node) { + emitExpression(node.expression); + if (!ts.isJsonSourceFile(currentSourceFile) || ts.nodeIsSynthesized(node.expression)) { + writeTrailingSemicolon(); + } + } + function emitIfStatement(node) { + var openParenPos = emitTokenWithComment(91, node.pos, writeKeyword, node); + writeSpace(); + emitTokenWithComment(20, openParenPos, writePunctuation, node); + emitExpression(node.expression); + emitTokenWithComment(21, node.expression.end, writePunctuation, node); + emitEmbeddedStatement(node, node.thenStatement); + if (node.elseStatement) { + writeLineOrSpace(node); + emitTokenWithComment(83, node.thenStatement.end, writeKeyword, node); + if (node.elseStatement.kind === 222) { + writeSpace(); + emit(node.elseStatement); + } + else { + emitEmbeddedStatement(node, node.elseStatement); + } + } + } + function emitWhileClause(node, startPos) { + var openParenPos = emitTokenWithComment(107, startPos, writeKeyword, node); + writeSpace(); + emitTokenWithComment(20, openParenPos, writePunctuation, node); + emitExpression(node.expression); + emitTokenWithComment(21, node.expression.end, writePunctuation, node); + } + function emitDoStatement(node) { + emitTokenWithComment(82, node.pos, writeKeyword, node); + emitEmbeddedStatement(node, node.statement); + if (ts.isBlock(node.statement)) { + writeSpace(); + } + else { + writeLineOrSpace(node); + } + emitWhileClause(node, node.statement.end); + writePunctuation(";"); + } + function emitWhileStatement(node) { + emitWhileClause(node, node.pos); + emitEmbeddedStatement(node, node.statement); + } + function emitForStatement(node) { + var openParenPos = emitTokenWithComment(89, node.pos, writeKeyword, node); + writeSpace(); + var pos = emitTokenWithComment(20, openParenPos, writePunctuation, node); + emitForBinding(node.initializer); + pos = emitTokenWithComment(26, node.initializer ? node.initializer.end : pos, writePunctuation, node); + emitExpressionWithLeadingSpace(node.condition); + pos = emitTokenWithComment(26, node.condition ? node.condition.end : pos, writePunctuation, node); + emitExpressionWithLeadingSpace(node.incrementor); + emitTokenWithComment(21, node.incrementor ? node.incrementor.end : pos, writePunctuation, node); + emitEmbeddedStatement(node, node.statement); + } + function emitForInStatement(node) { + var openParenPos = emitTokenWithComment(89, node.pos, writeKeyword, node); + writeSpace(); + emitTokenWithComment(20, openParenPos, writePunctuation, node); + emitForBinding(node.initializer); + writeSpace(); + emitTokenWithComment(93, node.initializer.end, writeKeyword, node); + writeSpace(); + emitExpression(node.expression); + emitTokenWithComment(21, node.expression.end, writePunctuation, node); + emitEmbeddedStatement(node, node.statement); + } + function emitForOfStatement(node) { + var openParenPos = emitTokenWithComment(89, node.pos, writeKeyword, node); + writeSpace(); + emitWithTrailingSpace(node.awaitModifier); + emitTokenWithComment(20, openParenPos, writePunctuation, node); + emitForBinding(node.initializer); + writeSpace(); + emitTokenWithComment(147, node.initializer.end, writeKeyword, node); + writeSpace(); + emitExpression(node.expression); + emitTokenWithComment(21, node.expression.end, writePunctuation, node); + emitEmbeddedStatement(node, node.statement); + } + function emitForBinding(node) { + if (node !== undefined) { + if (node.kind === 238) { + emit(node); + } + else { + emitExpression(node); + } + } + } + function emitContinueStatement(node) { + emitTokenWithComment(78, node.pos, writeKeyword, node); + emitWithLeadingSpace(node.label); + writeTrailingSemicolon(); + } + function emitBreakStatement(node) { + emitTokenWithComment(73, node.pos, writeKeyword, node); + emitWithLeadingSpace(node.label); + writeTrailingSemicolon(); + } + function emitTokenWithComment(token, pos, writer, contextNode, indentLeading) { + var node = ts.getParseTreeNode(contextNode); + var isSimilarNode = node && node.kind === contextNode.kind; + var startPos = pos; + if (isSimilarNode) { + pos = ts.skipTrivia(currentSourceFile.text, pos); + } + if (emitLeadingCommentsOfPosition && isSimilarNode && contextNode.pos !== startPos) { + var needsIndent = indentLeading && !ts.positionsAreOnSameLine(startPos, pos, currentSourceFile); + if (needsIndent) { + increaseIndent(); + } + emitLeadingCommentsOfPosition(startPos); + if (needsIndent) { + decreaseIndent(); + } + } + pos = writeTokenText(token, writer, pos); + if (emitTrailingCommentsOfPosition && isSimilarNode && contextNode.end !== pos) { + emitTrailingCommentsOfPosition(pos, true); + } + return pos; + } + function emitReturnStatement(node) { + emitTokenWithComment(97, node.pos, writeKeyword, node); + emitExpressionWithLeadingSpace(node.expression); + writeTrailingSemicolon(); + } + function emitWithStatement(node) { + var openParenPos = emitTokenWithComment(108, node.pos, writeKeyword, node); + writeSpace(); + emitTokenWithComment(20, openParenPos, writePunctuation, node); + emitExpression(node.expression); + emitTokenWithComment(21, node.expression.end, writePunctuation, node); + emitEmbeddedStatement(node, node.statement); + } + function emitSwitchStatement(node) { + var openParenPos = emitTokenWithComment(99, node.pos, writeKeyword, node); + writeSpace(); + emitTokenWithComment(20, openParenPos, writePunctuation, node); + emitExpression(node.expression); + emitTokenWithComment(21, node.expression.end, writePunctuation, node); + writeSpace(); + emit(node.caseBlock); + } + function emitLabeledStatement(node) { + emit(node.label); + emitTokenWithComment(57, node.label.end, writePunctuation, node); + writeSpace(); + emit(node.statement); + } + function emitThrowStatement(node) { + emitTokenWithComment(101, node.pos, writeKeyword, node); + emitExpressionWithLeadingSpace(node.expression); + writeTrailingSemicolon(); + } + function emitTryStatement(node) { + emitTokenWithComment(103, node.pos, writeKeyword, node); + writeSpace(); + emit(node.tryBlock); + if (node.catchClause) { + writeLineOrSpace(node); + emit(node.catchClause); + } + if (node.finallyBlock) { + writeLineOrSpace(node); + emitTokenWithComment(88, (node.catchClause || node.tryBlock).end, writeKeyword, node); + writeSpace(); + emit(node.finallyBlock); + } + } + function emitDebuggerStatement(node) { + writeToken(79, node.pos, writeKeyword); + writeTrailingSemicolon(); + } + function emitVariableDeclaration(node) { + emit(node.name); + emitTypeAnnotation(node.type); + emitInitializer(node.initializer, node.type ? node.type.end : node.name.end, node); + } + function emitVariableDeclarationList(node) { + writeKeyword(ts.isLet(node) ? "let" : ts.isVarConst(node) ? "const" : "var"); + writeSpace(); + emitList(node, node.declarations, 528); + } + function emitFunctionDeclaration(node) { + emitFunctionDeclarationOrExpression(node); + } + function emitFunctionDeclarationOrExpression(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + writeKeyword("function"); + emit(node.asteriskToken); + writeSpace(); + emitIdentifierName(node.name); + emitSignatureAndBody(node, emitSignatureHead); + } + function emitBlockCallback(_hint, body) { + emitBlockFunctionBody(body); + } + function emitSignatureAndBody(node, emitSignatureHead) { + var body = node.body; + if (body) { + if (ts.isBlock(body)) { + var indentedFlag = ts.getEmitFlags(node) & 65536; + if (indentedFlag) { + increaseIndent(); + } + pushNameGenerationScope(node); + ts.forEach(node.parameters, generateNames); + generateNames(node.body); + emitSignatureHead(node); + if (onEmitNode) { + onEmitNode(4, body, emitBlockCallback); + } + else { + emitBlockFunctionBody(body); + } + popNameGenerationScope(node); + if (indentedFlag) { + decreaseIndent(); + } + } + else { + emitSignatureHead(node); + writeSpace(); + emitExpression(body); + } + } + else { + emitSignatureHead(node); + writeTrailingSemicolon(); + } + } + function emitSignatureHead(node) { + emitTypeParameters(node, node.typeParameters); + emitParameters(node, node.parameters); + emitTypeAnnotation(node.type); + } + function shouldEmitBlockFunctionBodyOnSingleLine(body) { + if (ts.getEmitFlags(body) & 1) { + return true; + } + if (body.multiLine) { + return false; + } + if (!ts.nodeIsSynthesized(body) && !ts.rangeIsOnSingleLine(body, currentSourceFile)) { + return false; + } + if (shouldWriteLeadingLineTerminator(body, body.statements, 2) + || shouldWriteClosingLineTerminator(body, body.statements, 2)) { + return false; + } + var previousStatement; + for (var _a = 0, _b = body.statements; _a < _b.length; _a++) { + var statement = _b[_a]; + if (shouldWriteSeparatingLineTerminator(previousStatement, statement, 2)) { + return false; + } + previousStatement = statement; + } + return true; + } + function emitBlockFunctionBody(body) { + writeSpace(); + writePunctuation("{"); + increaseIndent(); + var emitBlockFunctionBody = shouldEmitBlockFunctionBodyOnSingleLine(body) + ? emitBlockFunctionBodyOnSingleLine + : emitBlockFunctionBodyWorker; + if (emitBodyWithDetachedComments) { + emitBodyWithDetachedComments(body, body.statements, emitBlockFunctionBody); + } + else { + emitBlockFunctionBody(body); + } + decreaseIndent(); + writeToken(19, body.statements.end, writePunctuation, body); + } + function emitBlockFunctionBodyOnSingleLine(body) { + emitBlockFunctionBodyWorker(body, true); + } + function emitBlockFunctionBodyWorker(body, emitBlockFunctionBodyOnSingleLine) { + var statementOffset = emitPrologueDirectives(body.statements, true); + var pos = writer.getTextPos(); + emitHelpers(body); + if (statementOffset === 0 && pos === writer.getTextPos() && emitBlockFunctionBodyOnSingleLine) { + decreaseIndent(); + emitList(body, body.statements, 768); + increaseIndent(); + } + else { + emitList(body, body.statements, 1, statementOffset); + } + } + function emitClassDeclaration(node) { + emitClassDeclarationOrExpression(node); + } + function emitClassDeclarationOrExpression(node) { + ts.forEach(node.members, generateMemberNames); + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + writeKeyword("class"); + if (node.name) { + writeSpace(); + emitIdentifierName(node.name); + } + var indentedFlag = ts.getEmitFlags(node) & 65536; + if (indentedFlag) { + increaseIndent(); + } + emitTypeParameters(node, node.typeParameters); + emitList(node, node.heritageClauses, 0); + writeSpace(); + writePunctuation("{"); + emitList(node, node.members, 129); + writePunctuation("}"); + if (indentedFlag) { + decreaseIndent(); + } + } + function emitInterfaceDeclaration(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + writeKeyword("interface"); + writeSpace(); + emit(node.name); + emitTypeParameters(node, node.typeParameters); + emitList(node, node.heritageClauses, 512); + writeSpace(); + writePunctuation("{"); + emitList(node, node.members, 129); + writePunctuation("}"); + } + function emitTypeAliasDeclaration(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + writeKeyword("type"); + writeSpace(); + emit(node.name); + emitTypeParameters(node, node.typeParameters); + writeSpace(); + writePunctuation("="); + writeSpace(); + emit(node.type); + writeTrailingSemicolon(); + } + function emitEnumDeclaration(node) { + emitModifiers(node, node.modifiers); + writeKeyword("enum"); + writeSpace(); + emit(node.name); + writeSpace(); + writePunctuation("{"); + emitList(node, node.members, 145); + writePunctuation("}"); + } + function emitModuleDeclaration(node) { + emitModifiers(node, node.modifiers); + if (~node.flags & 512) { + writeKeyword(node.flags & 16 ? "namespace" : "module"); + writeSpace(); + } + emit(node.name); + var body = node.body; + if (!body) + return writeTrailingSemicolon(); + while (body.kind === 244) { + writePunctuation("."); + emit(body.name); + body = body.body; + } + writeSpace(); + emit(body); + } + function emitModuleBlock(node) { + pushNameGenerationScope(node); + ts.forEach(node.statements, generateNames); + emitBlockStatements(node, isEmptyBlock(node)); + popNameGenerationScope(node); + } + function emitCaseBlock(node) { + emitTokenWithComment(18, node.pos, writePunctuation, node); + emitList(node, node.clauses, 129); + emitTokenWithComment(19, node.clauses.end, writePunctuation, node, true); + } + function emitImportEqualsDeclaration(node) { + emitModifiers(node, node.modifiers); + emitTokenWithComment(92, node.modifiers ? node.modifiers.end : node.pos, writeKeyword, node); + writeSpace(); + emit(node.name); + writeSpace(); + emitTokenWithComment(59, node.name.end, writePunctuation, node); + writeSpace(); + emitModuleReference(node.moduleReference); + writeTrailingSemicolon(); + } + function emitModuleReference(node) { + if (node.kind === 72) { + emitExpression(node); + } + else { + emit(node); + } + } + function emitImportDeclaration(node) { + emitModifiers(node, node.modifiers); + emitTokenWithComment(92, node.modifiers ? node.modifiers.end : node.pos, writeKeyword, node); + writeSpace(); + if (node.importClause) { + emit(node.importClause); + writeSpace(); + emitTokenWithComment(144, node.importClause.end, writeKeyword, node); + writeSpace(); + } + emitExpression(node.moduleSpecifier); + writeTrailingSemicolon(); + } + function emitImportClause(node) { + emit(node.name); + if (node.name && node.namedBindings) { + emitTokenWithComment(27, node.name.end, writePunctuation, node); + writeSpace(); + } + emit(node.namedBindings); + } + function emitNamespaceImport(node) { + var asPos = emitTokenWithComment(40, node.pos, writePunctuation, node); + writeSpace(); + emitTokenWithComment(119, asPos, writeKeyword, node); + writeSpace(); + emit(node.name); + } + function emitNamedImports(node) { + emitNamedImportsOrExports(node); + } + function emitImportSpecifier(node) { + emitImportOrExportSpecifier(node); + } + function emitExportAssignment(node) { + var nextPos = emitTokenWithComment(85, node.pos, writeKeyword, node); + writeSpace(); + if (node.isExportEquals) { + emitTokenWithComment(59, nextPos, writeOperator, node); + } + else { + emitTokenWithComment(80, nextPos, writeKeyword, node); + } + writeSpace(); + emitExpression(node.expression); + writeTrailingSemicolon(); + } + function emitExportDeclaration(node) { + var nextPos = emitTokenWithComment(85, node.pos, writeKeyword, node); + writeSpace(); + if (node.exportClause) { + emit(node.exportClause); + } + else { + nextPos = emitTokenWithComment(40, nextPos, writePunctuation, node); + } + if (node.moduleSpecifier) { + writeSpace(); + var fromPos = node.exportClause ? node.exportClause.end : nextPos; + emitTokenWithComment(144, fromPos, writeKeyword, node); + writeSpace(); + emitExpression(node.moduleSpecifier); + } + writeTrailingSemicolon(); + } + function emitNamespaceExportDeclaration(node) { + var nextPos = emitTokenWithComment(85, node.pos, writeKeyword, node); + writeSpace(); + nextPos = emitTokenWithComment(119, nextPos, writeKeyword, node); + writeSpace(); + nextPos = emitTokenWithComment(131, nextPos, writeKeyword, node); + writeSpace(); + emit(node.name); + writeTrailingSemicolon(); + } + function emitNamedExports(node) { + emitNamedImportsOrExports(node); + } + function emitExportSpecifier(node) { + emitImportOrExportSpecifier(node); + } + function emitNamedImportsOrExports(node) { + writePunctuation("{"); + emitList(node, node.elements, 525136); + writePunctuation("}"); + } + function emitImportOrExportSpecifier(node) { + if (node.propertyName) { + emit(node.propertyName); + writeSpace(); + emitTokenWithComment(119, node.propertyName.end, writeKeyword, node); + writeSpace(); + } + emit(node.name); + } + function emitExternalModuleReference(node) { + writeKeyword("require"); + writePunctuation("("); + emitExpression(node.expression); + writePunctuation(")"); + } + function emitJsxElement(node) { + emit(node.openingElement); + emitList(node, node.children, 262144); + emit(node.closingElement); + } + function emitJsxSelfClosingElement(node) { + writePunctuation("<"); + emitJsxTagName(node.tagName); + writeSpace(); + emit(node.attributes); + writePunctuation("/>"); + } + function emitJsxFragment(node) { + emit(node.openingFragment); + emitList(node, node.children, 262144); + emit(node.closingFragment); + } + function emitJsxOpeningElementOrFragment(node) { + writePunctuation("<"); + if (ts.isJsxOpeningElement(node)) { + emitJsxTagName(node.tagName); + if (node.attributes.properties && node.attributes.properties.length > 0) { + writeSpace(); + } + emit(node.attributes); + } + writePunctuation(">"); + } + function emitJsxText(node) { + writer.writeLiteral(getTextOfNode(node, true)); + } + function emitJsxClosingElementOrFragment(node) { + writePunctuation(""); + } + function emitJsxAttributes(node) { + emitList(node, node.properties, 262656); + } + function emitJsxAttribute(node) { + emit(node.name); + emitNodeWithPrefix("=", writePunctuation, node.initializer, emit); + } + function emitJsxSpreadAttribute(node) { + writePunctuation("{..."); + emitExpression(node.expression); + writePunctuation("}"); + } + function emitJsxExpression(node) { + if (node.expression) { + writePunctuation("{"); + emit(node.dotDotDotToken); + emitExpression(node.expression); + writePunctuation("}"); + } + } + function emitJsxTagName(node) { + if (node.kind === 72) { + emitExpression(node); + } + else { + emit(node); + } + } + function emitCaseClause(node) { + emitTokenWithComment(74, node.pos, writeKeyword, node); + writeSpace(); + emitExpression(node.expression); + emitCaseOrDefaultClauseRest(node, node.statements, node.expression.end); + } + function emitDefaultClause(node) { + var pos = emitTokenWithComment(80, node.pos, writeKeyword, node); + emitCaseOrDefaultClauseRest(node, node.statements, pos); + } + function emitCaseOrDefaultClauseRest(parentNode, statements, colonPos) { + var emitAsSingleStatement = statements.length === 1 && + (ts.nodeIsSynthesized(parentNode) || + ts.nodeIsSynthesized(statements[0]) || + ts.rangeStartPositionsAreOnSameLine(parentNode, statements[0], currentSourceFile)); + var format = 163969; + if (emitAsSingleStatement) { + writeToken(57, colonPos, writePunctuation, parentNode); + writeSpace(); + format &= ~(1 | 128); + } + else { + emitTokenWithComment(57, colonPos, writePunctuation, parentNode); + } + emitList(parentNode, statements, format); + } + function emitHeritageClause(node) { + writeSpace(); + writeTokenText(node.token, writeKeyword); + writeSpace(); + emitList(node, node.types, 528); + } + function emitCatchClause(node) { + var openParenPos = emitTokenWithComment(75, node.pos, writeKeyword, node); + writeSpace(); + if (node.variableDeclaration) { + emitTokenWithComment(20, openParenPos, writePunctuation, node); + emit(node.variableDeclaration); + emitTokenWithComment(21, node.variableDeclaration.end, writePunctuation, node); + writeSpace(); + } + emit(node.block); + } + function emitPropertyAssignment(node) { + emit(node.name); + writePunctuation(":"); + writeSpace(); + var initializer = node.initializer; + if (emitTrailingCommentsOfPosition && (ts.getEmitFlags(initializer) & 512) === 0) { + var commentRange = ts.getCommentRange(initializer); + emitTrailingCommentsOfPosition(commentRange.pos); + } + emitExpression(initializer); + } + function emitShorthandPropertyAssignment(node) { + emit(node.name); + if (node.objectAssignmentInitializer) { + writeSpace(); + writePunctuation("="); + writeSpace(); + emitExpression(node.objectAssignmentInitializer); + } + } + function emitSpreadAssignment(node) { + if (node.expression) { + emitTokenWithComment(25, node.pos, writePunctuation, node); + emitExpression(node.expression); + } + } + function emitEnumMember(node) { + emit(node.name); + emitInitializer(node.initializer, node.name.end, node); + } + function emitJSDoc(node) { + write("/**"); + if (node.comment) { + var lines = node.comment.split(/\r\n?|\n/g); + for (var _a = 0, lines_2 = lines; _a < lines_2.length; _a++) { + var line = lines_2[_a]; + writeLine(); + writeSpace(); + writePunctuation("*"); + writeSpace(); + write(line); + } + } + if (node.tags) { + if (node.tags.length === 1 && node.tags[0].kind === 302 && !node.comment) { + writeSpace(); + emit(node.tags[0]); + } + else { + emitList(node, node.tags, 33); + } + } + writeSpace(); + write("*/"); + } + function emitJSDocSimpleTypedTag(tag) { + emitJSDocTagName(tag.tagName); + emitJSDocTypeExpression(tag.typeExpression); + emitJSDocComment(tag.comment); + } + function emitJSDocAugmentsTag(tag) { + emitJSDocTagName(tag.tagName); + writeSpace(); + writePunctuation("{"); + emit(tag.class); + writePunctuation("}"); + emitJSDocComment(tag.comment); + } + function emitJSDocTemplateTag(tag) { + emitJSDocTagName(tag.tagName); + emitJSDocTypeExpression(tag.constraint); + writeSpace(); + emitList(tag, tag.typeParameters, 528); + emitJSDocComment(tag.comment); + } + function emitJSDocTypedefTag(tag) { + emitJSDocTagName(tag.tagName); + if (tag.typeExpression) { + if (tag.typeExpression.kind === 283) { + emitJSDocTypeExpression(tag.typeExpression); + } + else { + writeSpace(); + writePunctuation("{"); + write("Object"); + if (tag.typeExpression.isArrayType) { + writePunctuation("["); + writePunctuation("]"); + } + writePunctuation("}"); + } + } + if (tag.fullName) { + writeSpace(); + emit(tag.fullName); + } + emitJSDocComment(tag.comment); + if (tag.typeExpression && tag.typeExpression.kind === 292) { + emitJSDocTypeLiteral(tag.typeExpression); + } + } + function emitJSDocCallbackTag(tag) { + emitJSDocTagName(tag.tagName); + if (tag.name) { + writeSpace(); + emit(tag.name); + } + emitJSDocComment(tag.comment); + emitJSDocSignature(tag.typeExpression); + } + function emitJSDocSimpleTag(tag) { + emitJSDocTagName(tag.tagName); + emitJSDocComment(tag.comment); + } + function emitJSDocTypeLiteral(lit) { + emitList(lit, ts.createNodeArray(lit.jsDocPropertyTags), 33); + } + function emitJSDocSignature(sig) { + if (sig.typeParameters) { + emitList(sig, ts.createNodeArray(sig.typeParameters), 33); + } + if (sig.parameters) { + emitList(sig, ts.createNodeArray(sig.parameters), 33); + } + if (sig.type) { + writeLine(); + writeSpace(); + writePunctuation("*"); + writeSpace(); + emit(sig.type); + } + } + function emitJSDocPropertyLikeTag(param) { + emitJSDocTagName(param.tagName); + emitJSDocTypeExpression(param.typeExpression); + writeSpace(); + if (param.isBracketed) { + writePunctuation("["); + } + emit(param.name); + if (param.isBracketed) { + writePunctuation("]"); + } + emitJSDocComment(param.comment); + } + function emitJSDocTagName(tagName) { + writePunctuation("@"); + emit(tagName); + } + function emitJSDocComment(comment) { + if (comment) { + writeSpace(); + write(comment); + } + } + function emitJSDocTypeExpression(typeExpression) { + if (typeExpression) { + writeSpace(); + writePunctuation("{"); + emit(typeExpression.type); + writePunctuation("}"); + } + } + function emitSourceFile(node) { + writeLine(); + var statements = node.statements; + if (emitBodyWithDetachedComments) { + var shouldEmitDetachedComment = statements.length === 0 || + !ts.isPrologueDirective(statements[0]) || + ts.nodeIsSynthesized(statements[0]); + if (shouldEmitDetachedComment) { + emitBodyWithDetachedComments(node, statements, emitSourceFileWorker); + return; + } + } + emitSourceFileWorker(node); + } + function emitSyntheticTripleSlashReferencesIfNeeded(node) { + emitTripleSlashDirectives(!!node.hasNoDefaultLib, node.syntheticFileReferences || [], node.syntheticTypeReferences || [], node.syntheticLibReferences || []); + } + function emitTripleSlashDirectivesIfNeeded(node) { + if (node.isDeclarationFile) + emitTripleSlashDirectives(node.hasNoDefaultLib, node.referencedFiles, node.typeReferenceDirectives, node.libReferenceDirectives); + } + function emitTripleSlashDirectives(hasNoDefaultLib, files, types, libs) { + if (hasNoDefaultLib) { + writeComment("/// "); + writeLine(); + } + if (currentSourceFile && currentSourceFile.moduleName) { + writeComment("/// "); + writeLine(); + } + if (currentSourceFile && currentSourceFile.amdDependencies) { + for (var _a = 0, _b = currentSourceFile.amdDependencies; _a < _b.length; _a++) { + var dep = _b[_a]; + if (dep.name) { + writeComment("/// "); + } + else { + writeComment("/// "); + } + writeLine(); + } + } + for (var _c = 0, files_1 = files; _c < files_1.length; _c++) { + var directive = files_1[_c]; + writeComment("/// "); + writeLine(); + } + for (var _d = 0, types_18 = types; _d < types_18.length; _d++) { + var directive = types_18[_d]; + writeComment("/// "); + writeLine(); + } + for (var _e = 0, libs_1 = libs; _e < libs_1.length; _e++) { + var directive = libs_1[_e]; + writeComment("/// "); + writeLine(); + } + } + function emitSourceFileWorker(node) { + var statements = node.statements; + pushNameGenerationScope(node); + ts.forEach(node.statements, generateNames); + emitHelpers(node); + var index = ts.findIndex(statements, function (statement) { return !ts.isPrologueDirective(statement); }); + emitTripleSlashDirectivesIfNeeded(node); + emitList(node, statements, 1, index === -1 ? statements.length : index); + popNameGenerationScope(node); + } + function emitPartiallyEmittedExpression(node) { + emitExpression(node.expression); + } + function emitCommaList(node) { + emitExpressionList(node, node.elements, 528); + } + function emitPrologueDirectives(statements, startWithNewLine, seenPrologueDirectives) { + for (var i = 0; i < statements.length; i++) { + var statement = statements[i]; + if (ts.isPrologueDirective(statement)) { + var shouldEmitPrologueDirective = seenPrologueDirectives ? !seenPrologueDirectives.has(statement.expression.text) : true; + if (shouldEmitPrologueDirective) { + if (startWithNewLine || i > 0) { + writeLine(); + } + emit(statement); + if (seenPrologueDirectives) { + seenPrologueDirectives.set(statement.expression.text, true); + } + } + } + else { + return i; + } + } + return statements.length; + } + function emitPrologueDirectivesIfNeeded(sourceFileOrBundle) { + if (ts.isSourceFile(sourceFileOrBundle)) { + setSourceFile(sourceFileOrBundle); + emitPrologueDirectives(sourceFileOrBundle.statements); + } + else { + var seenPrologueDirectives = ts.createMap(); + for (var _a = 0, _b = sourceFileOrBundle.sourceFiles; _a < _b.length; _a++) { + var sourceFile = _b[_a]; + setSourceFile(sourceFile); + emitPrologueDirectives(sourceFile.statements, true, seenPrologueDirectives); + } + setSourceFile(undefined); + } + } + function emitShebangIfNeeded(sourceFileOrBundle) { + if (ts.isSourceFile(sourceFileOrBundle)) { + var shebang = ts.getShebang(sourceFileOrBundle.text); + if (shebang) { + writeComment(shebang); + writeLine(); + return true; + } + } + else { + for (var _a = 0, _b = sourceFileOrBundle.sourceFiles; _a < _b.length; _a++) { + var sourceFile = _b[_a]; + if (emitShebangIfNeeded(sourceFile)) { + break; + } + } + } + } + function emitNodeWithWriter(node, writer) { + if (!node) + return; + var savedWrite = write; + write = writer; + emit(node); + write = savedWrite; + } + function emitModifiers(node, modifiers) { + if (modifiers && modifiers.length) { + emitList(node, modifiers, 262656); + writeSpace(); + } + } + function emitTypeAnnotation(node) { + if (node) { + writePunctuation(":"); + writeSpace(); + emit(node); + } + } + function emitInitializer(node, equalCommentStartPos, container) { + if (node) { + writeSpace(); + emitTokenWithComment(59, equalCommentStartPos, writeOperator, container); + writeSpace(); + emitExpression(node); + } + } + function emitNodeWithPrefix(prefix, prefixWriter, node, emit) { + if (node) { + prefixWriter(prefix); + emit(node); + } + } + function emitWithLeadingSpace(node) { + if (node) { + writeSpace(); + emit(node); + } + } + function emitExpressionWithLeadingSpace(node) { + if (node) { + writeSpace(); + emitExpression(node); + } + } + function emitWithTrailingSpace(node) { + if (node) { + emit(node); + writeSpace(); + } + } + function emitEmbeddedStatement(parent, node) { + if (ts.isBlock(node) || ts.getEmitFlags(parent) & 1) { + writeSpace(); + emit(node); + } + else { + writeLine(); + increaseIndent(); + if (ts.isEmptyStatement(node)) { + var pipelinePhase = getPipelinePhase(0, node); + pipelinePhase(5, node); + } + else { + emit(node); + } + decreaseIndent(); + } + } + function emitDecorators(parentNode, decorators) { + emitList(parentNode, decorators, 49153); + } + function emitTypeArguments(parentNode, typeArguments) { + emitList(parentNode, typeArguments, 53776); + } + function emitTypeParameters(parentNode, typeParameters) { + if (ts.isFunctionLike(parentNode) && parentNode.typeArguments) { + return emitTypeArguments(parentNode, parentNode.typeArguments); + } + emitList(parentNode, typeParameters, 53776); + } + function emitParameters(parentNode, parameters) { + emitList(parentNode, parameters, 2576); + } + function canEmitSimpleArrowHead(parentNode, parameters) { + var parameter = ts.singleOrUndefined(parameters); + return parameter + && parameter.pos === parentNode.pos + && ts.isArrowFunction(parentNode) + && !parentNode.type + && !ts.some(parentNode.decorators) + && !ts.some(parentNode.modifiers) + && !ts.some(parentNode.typeParameters) + && !ts.some(parameter.decorators) + && !ts.some(parameter.modifiers) + && !parameter.dotDotDotToken + && !parameter.questionToken + && !parameter.type + && !parameter.initializer + && ts.isIdentifier(parameter.name); + } + function emitParametersForArrow(parentNode, parameters) { + if (canEmitSimpleArrowHead(parentNode, parameters)) { + emitList(parentNode, parameters, 2576 & ~2048); + } + else { + emitParameters(parentNode, parameters); + } + } + function emitParametersForIndexSignature(parentNode, parameters) { + emitList(parentNode, parameters, 8848); + } + function emitList(parentNode, children, format, start, count) { + emitNodeList(emit, parentNode, children, format, start, count); + } + function emitExpressionList(parentNode, children, format, start, count) { + emitNodeList(emitExpression, parentNode, children, format, start, count); + } + function writeDelimiter(format) { + switch (format & 60) { + case 0: + break; + case 16: + writePunctuation(","); + break; + case 4: + writeSpace(); + writePunctuation("|"); + break; + case 32: + writeSpace(); + writePunctuation("*"); + writeSpace(); + break; + case 8: + writeSpace(); + writePunctuation("&"); + break; + } + } + function emitNodeList(emit, parentNode, children, format, start, count) { + if (start === void 0) { start = 0; } + if (count === void 0) { count = children ? children.length - start : 0; } + var isUndefined = children === undefined; + if (isUndefined && format & 16384) { + return; + } + var isEmpty = children === undefined || start >= children.length || count === 0; + if (isEmpty && format & 32768) { + if (onBeforeEmitNodeArray) { + onBeforeEmitNodeArray(children); + } + if (onAfterEmitNodeArray) { + onAfterEmitNodeArray(children); + } + return; + } + if (format & 15360) { + writePunctuation(getOpeningBracket(format)); + if (isEmpty && !isUndefined) { + emitTrailingCommentsOfPosition(children.pos, true); + } + } + if (onBeforeEmitNodeArray) { + onBeforeEmitNodeArray(children); + } + if (isEmpty) { + if (format & 1) { + writeLine(); + } + else if (format & 256 && !(format & 524288)) { + writeSpace(); + } + } + else { + var mayEmitInterveningComments = (format & 262144) === 0; + var shouldEmitInterveningComments = mayEmitInterveningComments; + if (shouldWriteLeadingLineTerminator(parentNode, children, format)) { + writeLine(); + shouldEmitInterveningComments = false; + } + else if (format & 256) { + writeSpace(); + } + if (format & 128) { + increaseIndent(); + } + var previousSibling = void 0; + var shouldDecreaseIndentAfterEmit = false; + for (var i = 0; i < count; i++) { + var child = children[start + i]; + if (format & 32) { + writeLine(); + writeDelimiter(format); + } + else if (previousSibling) { + if (format & 60 && previousSibling.end !== parentNode.end) { + emitLeadingCommentsOfPosition(previousSibling.end); + } + writeDelimiter(format); + if (shouldWriteSeparatingLineTerminator(previousSibling, child, format)) { + if ((format & (3 | 128)) === 0) { + increaseIndent(); + shouldDecreaseIndentAfterEmit = true; + } + writeLine(); + shouldEmitInterveningComments = false; + } + else if (previousSibling && format & 512) { + writeSpace(); + } + } + if (shouldEmitInterveningComments) { + if (emitTrailingCommentsOfPosition) { + var commentRange = ts.getCommentRange(child); + emitTrailingCommentsOfPosition(commentRange.pos); + } + } + else { + shouldEmitInterveningComments = mayEmitInterveningComments; + } + emit(child); + if (shouldDecreaseIndentAfterEmit) { + decreaseIndent(); + shouldDecreaseIndentAfterEmit = false; + } + previousSibling = child; + } + var hasTrailingComma = (format & 64) && children.hasTrailingComma; + if (format & 16 && hasTrailingComma) { + writePunctuation(","); + } + if (previousSibling && format & 60 && previousSibling.end !== parentNode.end && !(ts.getEmitFlags(previousSibling) & 1024)) { + emitLeadingCommentsOfPosition(previousSibling.end); + } + if (format & 128) { + decreaseIndent(); + } + if (shouldWriteClosingLineTerminator(parentNode, children, format)) { + writeLine(); + } + else if (format & 256) { + writeSpace(); + } + } + if (onAfterEmitNodeArray) { + onAfterEmitNodeArray(children); + } + if (format & 15360) { + if (isEmpty && !isUndefined) { + emitLeadingCommentsOfPosition(children.end); + } + writePunctuation(getClosingBracket(format)); + } + } + function writeLiteral(s) { + writer.writeLiteral(s); + } + function writeStringLiteral(s) { + writer.writeStringLiteral(s); + } + function writeBase(s) { + writer.write(s); + } + function writeSymbol(s, sym) { + writer.writeSymbol(s, sym); + } + function writePunctuation(s) { + writer.writePunctuation(s); + } + function writeTrailingSemicolon() { + writer.writeTrailingSemicolon(";"); + } + function writeKeyword(s) { + writer.writeKeyword(s); + } + function writeOperator(s) { + writer.writeOperator(s); + } + function writeParameter(s) { + writer.writeParameter(s); + } + function writeComment(s) { + writer.writeComment(s); + } + function writeSpace() { + writer.writeSpace(" "); + } + function writeProperty(s) { + writer.writeProperty(s); + } + function writeLine() { + writer.writeLine(); + } + function increaseIndent() { + writer.increaseIndent(); + } + function decreaseIndent() { + writer.decreaseIndent(); + } + function writeToken(token, pos, writer, contextNode) { + return !sourceMapsDisabled + ? emitTokenWithSourceMap(contextNode, token, writer, pos, writeTokenText) + : writeTokenText(token, writer, pos); + } + function writeTokenNode(node, writer) { + if (onBeforeEmitToken) { + onBeforeEmitToken(node); + } + writer(ts.tokenToString(node.kind)); + if (onAfterEmitToken) { + onAfterEmitToken(node); + } + } + function writeTokenText(token, writer, pos) { + var tokenString = ts.tokenToString(token); + writer(tokenString); + return pos < 0 ? pos : pos + tokenString.length; + } + function writeLineOrSpace(node) { + if (ts.getEmitFlags(node) & 1) { + writeSpace(); + } + else { + writeLine(); + } + } + function writeLines(text) { + var lines = text.split(/\r\n?|\n/g); + var indentation = ts.guessIndentation(lines); + for (var _a = 0, lines_3 = lines; _a < lines_3.length; _a++) { + var lineText = lines_3[_a]; + var line = indentation ? lineText.slice(indentation) : lineText; + if (line.length) { + writeLine(); + write(line); + writer.rawWrite(newLine); + } + } + } + function increaseIndentIf(value, writeSpaceIfNotIndenting) { + if (value) { + increaseIndent(); + writeLine(); + } + else if (writeSpaceIfNotIndenting) { + writeSpace(); + } + } + function decreaseIndentIf(value1, value2) { + if (value1) { + decreaseIndent(); + } + if (value2) { + decreaseIndent(); + } + } + function shouldWriteLeadingLineTerminator(parentNode, children, format) { + if (format & 1) { + return true; + } + if (format & 2) { + if (format & 65536) { + return true; + } + var firstChild = children[0]; + if (firstChild === undefined) { + return !ts.rangeIsOnSingleLine(parentNode, currentSourceFile); + } + else if (ts.positionIsSynthesized(parentNode.pos) || ts.nodeIsSynthesized(firstChild)) { + return synthesizedNodeStartsOnNewLine(firstChild, format); + } + else { + return !ts.rangeStartPositionsAreOnSameLine(parentNode, firstChild, currentSourceFile); + } + } + else { + return false; + } + } + function shouldWriteSeparatingLineTerminator(previousNode, nextNode, format) { + if (format & 1) { + return true; + } + else if (format & 2) { + if (previousNode === undefined || nextNode === undefined) { + return false; + } + else if (ts.nodeIsSynthesized(previousNode) || ts.nodeIsSynthesized(nextNode)) { + return synthesizedNodeStartsOnNewLine(previousNode, format) || synthesizedNodeStartsOnNewLine(nextNode, format); + } + else { + return !ts.rangeEndIsOnSameLineAsRangeStart(previousNode, nextNode, currentSourceFile); + } + } + else { + return ts.getStartsOnNewLine(nextNode); + } + } + function shouldWriteClosingLineTerminator(parentNode, children, format) { + if (format & 1) { + return (format & 131072) === 0; + } + else if (format & 2) { + if (format & 65536) { + return true; + } + var lastChild = ts.lastOrUndefined(children); + if (lastChild === undefined) { + return !ts.rangeIsOnSingleLine(parentNode, currentSourceFile); + } + else if (ts.positionIsSynthesized(parentNode.pos) || ts.nodeIsSynthesized(lastChild)) { + return synthesizedNodeStartsOnNewLine(lastChild, format); + } + else { + return !ts.rangeEndPositionsAreOnSameLine(parentNode, lastChild, currentSourceFile); + } + } + else { + return false; + } + } + function synthesizedNodeStartsOnNewLine(node, format) { + if (ts.nodeIsSynthesized(node)) { + var startsOnNewLine = ts.getStartsOnNewLine(node); + if (startsOnNewLine === undefined) { + return (format & 65536) !== 0; + } + return startsOnNewLine; + } + return (format & 65536) !== 0; + } + function needsIndentation(parent, node1, node2) { + parent = skipSynthesizedParentheses(parent); + node1 = skipSynthesizedParentheses(node1); + node2 = skipSynthesizedParentheses(node2); + if (ts.getStartsOnNewLine(node2)) { + return true; + } + return !ts.nodeIsSynthesized(parent) + && !ts.nodeIsSynthesized(node1) + && !ts.nodeIsSynthesized(node2) + && !ts.rangeEndIsOnSameLineAsRangeStart(node1, node2, currentSourceFile); + } + function isEmptyBlock(block) { + return block.statements.length === 0 + && ts.rangeEndIsOnSameLineAsRangeStart(block, block, currentSourceFile); + } + function skipSynthesizedParentheses(node) { + while (node.kind === 195 && ts.nodeIsSynthesized(node)) { + node = node.expression; + } + return node; + } + function getTextOfNode(node, includeTrivia) { + if (ts.isGeneratedIdentifier(node)) { + return generateName(node); + } + else if (ts.isIdentifier(node) && (ts.nodeIsSynthesized(node) || !node.parent || !currentSourceFile || (node.parent && currentSourceFile && ts.getSourceFileOfNode(node) !== ts.getOriginalNode(currentSourceFile)))) { + return ts.idText(node); + } + else if (node.kind === 10 && node.textSourceNode) { + return getTextOfNode(node.textSourceNode, includeTrivia); + } + else if (ts.isLiteralExpression(node) && (ts.nodeIsSynthesized(node) || !node.parent)) { + return node.text; + } + return ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node, includeTrivia); + } + function getLiteralTextOfNode(node, neverAsciiEscape) { + if (node.kind === 10 && node.textSourceNode) { + var textSourceNode = node.textSourceNode; + if (ts.isIdentifier(textSourceNode)) { + return neverAsciiEscape || (ts.getEmitFlags(node) & 16777216) ? + "\"" + ts.escapeString(getTextOfNode(textSourceNode)) + "\"" : + "\"" + ts.escapeNonAsciiString(getTextOfNode(textSourceNode)) + "\""; + } + else { + return getLiteralTextOfNode(textSourceNode, neverAsciiEscape); + } + } + return ts.getLiteralText(node, currentSourceFile, neverAsciiEscape); + } + function pushNameGenerationScope(node) { + if (node && ts.getEmitFlags(node) & 524288) { + return; + } + tempFlagsStack.push(tempFlags); + tempFlags = 0; + reservedNamesStack.push(reservedNames); + } + function popNameGenerationScope(node) { + if (node && ts.getEmitFlags(node) & 524288) { + return; + } + tempFlags = tempFlagsStack.pop(); + reservedNames = reservedNamesStack.pop(); + } + function reserveNameInNestedScopes(name) { + if (!reservedNames || reservedNames === ts.lastOrUndefined(reservedNamesStack)) { + reservedNames = ts.createMap(); + } + reservedNames.set(name, true); + } + function generateNames(node) { + if (!node) + return; + switch (node.kind) { + case 218: + ts.forEach(node.statements, generateNames); + break; + case 233: + case 231: + case 223: + case 224: + generateNames(node.statement); + break; + case 222: + generateNames(node.thenStatement); + generateNames(node.elseStatement); + break; + case 225: + case 227: + case 226: + generateNames(node.initializer); + generateNames(node.statement); + break; + case 232: + generateNames(node.caseBlock); + break; + case 246: + ts.forEach(node.clauses, generateNames); + break; + case 271: + case 272: + ts.forEach(node.statements, generateNames); + break; + case 235: + generateNames(node.tryBlock); + generateNames(node.catchClause); + generateNames(node.finallyBlock); + break; + case 274: + generateNames(node.variableDeclaration); + generateNames(node.block); + break; + case 219: + generateNames(node.declarationList); + break; + case 238: + ts.forEach(node.declarations, generateNames); + break; + case 237: + case 151: + case 186: + case 240: + generateNameIfNeeded(node.name); + break; + case 239: + generateNameIfNeeded(node.name); + if (ts.getEmitFlags(node) & 524288) { + ts.forEach(node.parameters, generateNames); + generateNames(node.body); + } + break; + case 184: + case 185: + ts.forEach(node.elements, generateNames); + break; + case 249: + generateNames(node.importClause); + break; + case 250: + generateNameIfNeeded(node.name); + generateNames(node.namedBindings); + break; + case 251: + generateNameIfNeeded(node.name); + break; + case 252: + ts.forEach(node.elements, generateNames); + break; + case 253: + generateNameIfNeeded(node.propertyName || node.name); + break; + } + } + function generateMemberNames(node) { + if (!node) + return; + switch (node.kind) { + case 275: + case 276: + case 154: + case 156: + case 158: + case 159: + generateNameIfNeeded(node.name); + break; + } + } + function generateNameIfNeeded(name) { + if (name) { + if (ts.isGeneratedIdentifier(name)) { + generateName(name); + } + else if (ts.isBindingPattern(name)) { + generateNames(name); + } + } + } + function generateName(name) { + if ((name.autoGenerateFlags & 7) === 4) { + return generateNameCached(getNodeForGeneratedName(name), name.autoGenerateFlags); + } + else { + var autoGenerateId = name.autoGenerateId; + return autoGeneratedIdToGeneratedName[autoGenerateId] || (autoGeneratedIdToGeneratedName[autoGenerateId] = makeName(name)); + } + } + function generateNameCached(node, flags) { + var nodeId = ts.getNodeId(node); + return nodeIdToGeneratedName[nodeId] || (nodeIdToGeneratedName[nodeId] = generateNameForNode(node, flags)); + } + function isUniqueName(name) { + return isFileLevelUniqueName(name) + && !generatedNames.has(name) + && !(reservedNames && reservedNames.has(name)); + } + function isFileLevelUniqueName(name) { + return currentSourceFile ? ts.isFileLevelUniqueName(currentSourceFile, name, hasGlobalName) : true; + } + function isUniqueLocalName(name, container) { + for (var node = container; ts.isNodeDescendantOf(node, container); node = node.nextContainer) { + if (node.locals) { + var local = node.locals.get(ts.escapeLeadingUnderscores(name)); + if (local && local.flags & (67220415 | 1048576 | 2097152)) { + return false; + } + } + } + return true; + } + function makeTempVariableName(flags, reservedInNestedScopes) { + if (flags && !(tempFlags & flags)) { + var name = flags === 268435456 ? "_i" : "_n"; + if (isUniqueName(name)) { + tempFlags |= flags; + if (reservedInNestedScopes) { + reserveNameInNestedScopes(name); + } + return name; + } + } + while (true) { + var count = tempFlags & 268435455; + tempFlags++; + if (count !== 8 && count !== 13) { + var name = count < 26 + ? "_" + String.fromCharCode(97 + count) + : "_" + (count - 26); + if (isUniqueName(name)) { + if (reservedInNestedScopes) { + reserveNameInNestedScopes(name); + } + return name; + } + } + } + } + function makeUniqueName(baseName, checkFn, optimistic, scoped) { + if (checkFn === void 0) { checkFn = isUniqueName; } + if (optimistic) { + if (checkFn(baseName)) { + if (scoped) { + reserveNameInNestedScopes(baseName); + } + else { + generatedNames.set(baseName, true); + } + return baseName; + } + } + if (baseName.charCodeAt(baseName.length - 1) !== 95) { + baseName += "_"; + } + var i = 1; + while (true) { + var generatedName = baseName + i; + if (checkFn(generatedName)) { + if (scoped) { + reserveNameInNestedScopes(generatedName); + } + else { + generatedNames.set(generatedName, true); + } + return generatedName; + } + i++; + } + } + function makeFileLevelOptimisticUniqueName(name) { + return makeUniqueName(name, isFileLevelUniqueName, true); + } + function generateNameForModuleOrEnum(node) { + var name = getTextOfNode(node.name); + return isUniqueLocalName(name, node) ? name : makeUniqueName(name); + } + function generateNameForImportOrExportDeclaration(node) { + var expr = ts.getExternalModuleName(node); + var baseName = ts.isStringLiteral(expr) ? + ts.makeIdentifierFromModuleName(expr.text) : "module"; + return makeUniqueName(baseName); + } + function generateNameForExportDefault() { + return makeUniqueName("default"); + } + function generateNameForClassExpression() { + return makeUniqueName("class"); + } + function generateNameForMethodOrAccessor(node) { + if (ts.isIdentifier(node.name)) { + return generateNameCached(node.name); + } + return makeTempVariableName(0); + } + function generateNameForNode(node, flags) { + switch (node.kind) { + case 72: + return makeUniqueName(getTextOfNode(node), isUniqueName, !!(flags & 16), !!(flags & 8)); + case 244: + case 243: + return generateNameForModuleOrEnum(node); + case 249: + case 255: + return generateNameForImportOrExportDeclaration(node); + case 239: + case 240: + case 254: + return generateNameForExportDefault(); + case 209: + return generateNameForClassExpression(); + case 156: + case 158: + case 159: + return generateNameForMethodOrAccessor(node); + default: + return makeTempVariableName(0); + } + } + function makeName(name) { + switch (name.autoGenerateFlags & 7) { + case 1: + return makeTempVariableName(0, !!(name.autoGenerateFlags & 8)); + case 2: + return makeTempVariableName(268435456, !!(name.autoGenerateFlags & 8)); + case 3: + return makeUniqueName(ts.idText(name), (name.autoGenerateFlags & 32) ? isFileLevelUniqueName : isUniqueName, !!(name.autoGenerateFlags & 16), !!(name.autoGenerateFlags & 8)); + } + return ts.Debug.fail("Unsupported GeneratedIdentifierKind."); + } + function getNodeForGeneratedName(name) { + var autoGenerateId = name.autoGenerateId; + var node = name; + var original = node.original; + while (original) { + node = original; + if (ts.isIdentifier(node) + && !!(node.autoGenerateFlags & 4) + && node.autoGenerateId !== autoGenerateId) { + break; + } + original = node.original; + } + return node; + } + function pipelineEmitWithComments(hint, node) { + enterComment(); + hasWrittenComment = false; + var emitFlags = ts.getEmitFlags(node); + var _a = ts.getCommentRange(node), pos = _a.pos, end = _a.end; + var isEmittedNode = node.kind !== 307; + var skipLeadingComments = pos < 0 || (emitFlags & 512) !== 0 || node.kind === 11; + var skipTrailingComments = end < 0 || (emitFlags & 1024) !== 0 || node.kind === 11; + var savedContainerPos = containerPos; + var savedContainerEnd = containerEnd; + var savedDeclarationListContainerEnd = declarationListContainerEnd; + if ((pos > 0 || end > 0) && pos !== end) { + if (!skipLeadingComments) { + emitLeadingComments(pos, isEmittedNode); + } + if (!skipLeadingComments || (pos >= 0 && (emitFlags & 512) !== 0)) { + containerPos = pos; + } + if (!skipTrailingComments || (end >= 0 && (emitFlags & 1024) !== 0)) { + containerEnd = end; + if (node.kind === 238) { + declarationListContainerEnd = end; + } + } + } + ts.forEach(ts.getSyntheticLeadingComments(node), emitLeadingSynthesizedComment); + exitComment(); + var pipelinePhase = getNextPipelinePhase(2, node); + if (emitFlags & 2048) { + commentsDisabled = true; + pipelinePhase(hint, node); + commentsDisabled = false; + } + else { + pipelinePhase(hint, node); + } + enterComment(); + ts.forEach(ts.getSyntheticTrailingComments(node), emitTrailingSynthesizedComment); + if ((pos > 0 || end > 0) && pos !== end) { + containerPos = savedContainerPos; + containerEnd = savedContainerEnd; + declarationListContainerEnd = savedDeclarationListContainerEnd; + if (!skipTrailingComments && isEmittedNode) { + emitTrailingComments(end); + } + } + exitComment(); + } + function emitLeadingSynthesizedComment(comment) { + if (comment.kind === 2) { + writer.writeLine(); + } + writeSynthesizedComment(comment); + if (comment.hasTrailingNewLine || comment.kind === 2) { + writer.writeLine(); + } + else { + writer.writeSpace(" "); + } + } + function emitTrailingSynthesizedComment(comment) { + if (!writer.isAtStartOfLine()) { + writer.writeSpace(" "); + } + writeSynthesizedComment(comment); + if (comment.hasTrailingNewLine) { + writer.writeLine(); + } + } + function writeSynthesizedComment(comment) { + var text = formatSynthesizedComment(comment); + var lineMap = comment.kind === 3 ? ts.computeLineStarts(text) : undefined; + ts.writeCommentRange(text, lineMap, writer, 0, text.length, newLine); + } + function formatSynthesizedComment(comment) { + return comment.kind === 3 + ? "/*" + comment.text + "*/" + : "//" + comment.text; + } + function emitBodyWithDetachedComments(node, detachedRange, emitCallback) { + enterComment(); + var pos = detachedRange.pos, end = detachedRange.end; + var emitFlags = ts.getEmitFlags(node); + var skipLeadingComments = pos < 0 || (emitFlags & 512) !== 0; + var skipTrailingComments = commentsDisabled || end < 0 || (emitFlags & 1024) !== 0; + if (!skipLeadingComments) { + emitDetachedCommentsAndUpdateCommentsInfo(detachedRange); + } + exitComment(); + if (emitFlags & 2048 && !commentsDisabled) { + commentsDisabled = true; + emitCallback(node); + commentsDisabled = false; + } + else { + emitCallback(node); + } + enterComment(); + if (!skipTrailingComments) { + emitLeadingComments(detachedRange.end, true); + if (hasWrittenComment && !writer.isAtStartOfLine()) { + writer.writeLine(); + } + } + exitComment(); + } + function emitLeadingComments(pos, isEmittedNode) { + hasWrittenComment = false; + if (isEmittedNode) { + forEachLeadingCommentToEmit(pos, emitLeadingComment); + } + else if (pos === 0) { + forEachLeadingCommentToEmit(pos, emitTripleSlashLeadingComment); + } + } + function emitTripleSlashLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos) { + if (isTripleSlashComment(commentPos, commentEnd)) { + emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos); + } + } + function shouldWriteComment(text, pos) { + if (printerOptions.onlyPrintJsDocStyle) { + return (ts.isJSDocLikeText(text, pos) || ts.isPinnedComment(text, pos)); + } + return true; + } + function emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos) { + if (!shouldWriteComment(currentSourceFile.text, commentPos)) + return; + if (!hasWrittenComment) { + ts.emitNewLineBeforeLeadingCommentOfPosition(getCurrentLineMap(), writer, rangePos, commentPos); + hasWrittenComment = true; + } + emitPos(commentPos); + ts.writeCommentRange(currentSourceFile.text, getCurrentLineMap(), writer, commentPos, commentEnd, newLine); + emitPos(commentEnd); + if (hasTrailingNewLine) { + writer.writeLine(); + } + else if (kind === 3) { + writer.writeSpace(" "); + } + } + function emitLeadingCommentsOfPosition(pos) { + if (commentsDisabled || pos === -1) { + return; + } + emitLeadingComments(pos, true); + } + function emitTrailingComments(pos) { + forEachTrailingCommentToEmit(pos, emitTrailingComment); + } + function emitTrailingComment(commentPos, commentEnd, _kind, hasTrailingNewLine) { + if (!shouldWriteComment(currentSourceFile.text, commentPos)) + return; + if (!writer.isAtStartOfLine()) { + writer.writeSpace(" "); + } + emitPos(commentPos); + ts.writeCommentRange(currentSourceFile.text, getCurrentLineMap(), writer, commentPos, commentEnd, newLine); + emitPos(commentEnd); + if (hasTrailingNewLine) { + writer.writeLine(); + } + } + function emitTrailingCommentsOfPosition(pos, prefixSpace) { + if (commentsDisabled) { + return; + } + enterComment(); + forEachTrailingCommentToEmit(pos, prefixSpace ? emitTrailingComment : emitTrailingCommentOfPosition); + exitComment(); + } + function emitTrailingCommentOfPosition(commentPos, commentEnd, _kind, hasTrailingNewLine) { + emitPos(commentPos); + ts.writeCommentRange(currentSourceFile.text, getCurrentLineMap(), writer, commentPos, commentEnd, newLine); + emitPos(commentEnd); + if (hasTrailingNewLine) { + writer.writeLine(); + } + else { + writer.writeSpace(" "); + } + } + function forEachLeadingCommentToEmit(pos, cb) { + if (currentSourceFile && (containerPos === -1 || pos !== containerPos)) { + if (hasDetachedComments(pos)) { + forEachLeadingCommentWithoutDetachedComments(cb); + } + else { + ts.forEachLeadingCommentRange(currentSourceFile.text, pos, cb, pos); + } + } + } + function forEachTrailingCommentToEmit(end, cb) { + if (currentSourceFile && (containerEnd === -1 || (end !== containerEnd && end !== declarationListContainerEnd))) { + ts.forEachTrailingCommentRange(currentSourceFile.text, end, cb); + } + } + function hasDetachedComments(pos) { + return detachedCommentsInfo !== undefined && ts.last(detachedCommentsInfo).nodePos === pos; + } + function forEachLeadingCommentWithoutDetachedComments(cb) { + var pos = ts.last(detachedCommentsInfo).detachedCommentEndPos; + if (detachedCommentsInfo.length - 1) { + detachedCommentsInfo.pop(); + } + else { + detachedCommentsInfo = undefined; + } + ts.forEachLeadingCommentRange(currentSourceFile.text, pos, cb, pos); + } + function emitDetachedCommentsAndUpdateCommentsInfo(range) { + var currentDetachedCommentInfo = ts.emitDetachedComments(currentSourceFile.text, getCurrentLineMap(), writer, emitComment, range, newLine, commentsDisabled); + if (currentDetachedCommentInfo) { + if (detachedCommentsInfo) { + detachedCommentsInfo.push(currentDetachedCommentInfo); + } + else { + detachedCommentsInfo = [currentDetachedCommentInfo]; + } + } + } + function emitComment(text, lineMap, writer, commentPos, commentEnd, newLine) { + if (!shouldWriteComment(currentSourceFile.text, commentPos)) + return; + emitPos(commentPos); + ts.writeCommentRange(text, lineMap, writer, commentPos, commentEnd, newLine); + emitPos(commentEnd); + } + function isTripleSlashComment(commentPos, commentEnd) { + return ts.isRecognizedTripleSlashComment(currentSourceFile.text, commentPos, commentEnd); + } + function pipelineEmitWithSourceMap(hint, node) { + var pipelinePhase = getNextPipelinePhase(3, node); + if (ts.isUnparsedSource(node) && node.sourceMapText !== undefined) { + var parsed = ts.tryParseRawSourceMap(node.sourceMapText); + if (parsed) { + sourceMapGenerator.appendSourceMap(writer.getLine(), writer.getColumn(), parsed, node.sourceMapPath); + } + pipelinePhase(hint, node); + } + else { + var _a = ts.getSourceMapRange(node), pos = _a.pos, end = _a.end, _b = _a.source, source = _b === void 0 ? sourceMapSource : _b; + var emitFlags = ts.getEmitFlags(node); + if (node.kind !== 307 + && (emitFlags & 16) === 0 + && pos >= 0) { + emitSourcePos(source, skipSourceTrivia(source, pos)); + } + if (emitFlags & 64) { + sourceMapsDisabled = true; + pipelinePhase(hint, node); + sourceMapsDisabled = false; + } + else { + pipelinePhase(hint, node); + } + if (node.kind !== 307 + && (emitFlags & 32) === 0 + && end >= 0) { + emitSourcePos(source, end); + } + } + } + function skipSourceTrivia(source, pos) { + return source.skipTrivia ? source.skipTrivia(pos) : ts.skipTrivia(sourceMapSource.text, pos); + } + function emitPos(pos) { + if (sourceMapsDisabled || ts.positionIsSynthesized(pos) || isJsonSourceMapSource(sourceMapSource)) { + return; + } + var _a = ts.getLineAndCharacterOfPosition(currentSourceFile, pos), sourceLine = _a.line, sourceCharacter = _a.character; + sourceMapGenerator.addMapping(writer.getLine(), writer.getColumn(), sourceMapSourceIndex, sourceLine, sourceCharacter, undefined); + } + function emitSourcePos(source, pos) { + if (source !== sourceMapSource) { + var savedSourceMapSource = sourceMapSource; + setSourceMapSource(source); + emitPos(pos); + setSourceMapSource(savedSourceMapSource); + } + else { + emitPos(pos); + } + } + function emitTokenWithSourceMap(node, token, writer, tokenPos, emitCallback) { + if (sourceMapsDisabled || node && ts.isInJsonFile(node)) { + return emitCallback(token, writer, tokenPos); + } + var emitNode = node && node.emitNode; + var emitFlags = emitNode && emitNode.flags || 0; + var range = emitNode && emitNode.tokenSourceMapRanges && emitNode.tokenSourceMapRanges[token]; + var source = range && range.source || sourceMapSource; + tokenPos = skipSourceTrivia(source, range ? range.pos : tokenPos); + if ((emitFlags & 128) === 0 && tokenPos >= 0) { + emitSourcePos(source, tokenPos); + } + tokenPos = emitCallback(token, writer, tokenPos); + if (range) + tokenPos = range.end; + if ((emitFlags & 256) === 0 && tokenPos >= 0) { + emitSourcePos(source, tokenPos); + } + return tokenPos; + } + function setSourceMapSource(source) { + if (sourceMapsDisabled) { + return; + } + sourceMapSource = source; + if (isJsonSourceMapSource(source)) { + return; + } + sourceMapSourceIndex = sourceMapGenerator.addSource(source.fileName); + if (printerOptions.inlineSources) { + sourceMapGenerator.setSourceContent(sourceMapSourceIndex, source.text); + } + } + function isJsonSourceMapSource(sourceFile) { + return ts.fileExtensionIs(sourceFile.fileName, ".json"); + } + } + ts.createPrinter = createPrinter; + function createBracketsMap() { + var brackets = []; + brackets[1024] = ["{", "}"]; + brackets[2048] = ["(", ")"]; + brackets[4096] = ["<", ">"]; + brackets[8192] = ["[", "]"]; + return brackets; + } + function getOpeningBracket(format) { + return brackets[format & 15360][0]; + } + function getClosingBracket(format) { + return brackets[format & 15360][1]; + } +})(ts || (ts = {})); +var ts; +(function (ts) { + function createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensitiveFileNames) { + if (!host.getDirectories || !host.readDirectory) { + return undefined; + } + var cachedReadDirectoryResult = ts.createMap(); + var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); + return { + useCaseSensitiveFileNames: useCaseSensitiveFileNames, + fileExists: fileExists, + readFile: function (path, encoding) { return host.readFile(path, encoding); }, + directoryExists: host.directoryExists && directoryExists, + getDirectories: getDirectories, + readDirectory: readDirectory, + createDirectory: host.createDirectory && createDirectory, + writeFile: host.writeFile && writeFile, + addOrDeleteFileOrDirectory: addOrDeleteFileOrDirectory, + addOrDeleteFile: addOrDeleteFile, + clearCache: clearCache + }; + function toPath(fileName) { + return ts.toPath(fileName, currentDirectory, getCanonicalFileName); + } + function getCachedFileSystemEntries(rootDirPath) { + return cachedReadDirectoryResult.get(ts.ensureTrailingDirectorySeparator(rootDirPath)); + } + function getCachedFileSystemEntriesForBaseDir(path) { + return getCachedFileSystemEntries(ts.getDirectoryPath(path)); + } + function getBaseNameOfFileName(fileName) { + return ts.getBaseFileName(ts.normalizePath(fileName)); + } + function createCachedFileSystemEntries(rootDir, rootDirPath) { + var resultFromHost = { + files: ts.map(host.readDirectory(rootDir, undefined, undefined, ["*.*"]), getBaseNameOfFileName) || [], + directories: host.getDirectories(rootDir) || [] + }; + cachedReadDirectoryResult.set(ts.ensureTrailingDirectorySeparator(rootDirPath), resultFromHost); + return resultFromHost; + } + function tryReadDirectory(rootDir, rootDirPath) { + rootDirPath = ts.ensureTrailingDirectorySeparator(rootDirPath); + var cachedResult = getCachedFileSystemEntries(rootDirPath); + if (cachedResult) { + return cachedResult; + } + try { + return createCachedFileSystemEntries(rootDir, rootDirPath); + } + catch (_e) { + ts.Debug.assert(!cachedReadDirectoryResult.has(ts.ensureTrailingDirectorySeparator(rootDirPath))); + return undefined; + } + } + function fileNameEqual(name1, name2) { + return getCanonicalFileName(name1) === getCanonicalFileName(name2); + } + function hasEntry(entries, name) { + return ts.some(entries, function (file) { return fileNameEqual(file, name); }); + } + function updateFileSystemEntry(entries, baseName, isValid) { + if (hasEntry(entries, baseName)) { + if (!isValid) { + return ts.filterMutate(entries, function (entry) { return !fileNameEqual(entry, baseName); }); + } + } + else if (isValid) { + return entries.push(baseName); + } + } + function writeFile(fileName, data, writeByteOrderMark) { + var path = toPath(fileName); + var result = getCachedFileSystemEntriesForBaseDir(path); + if (result) { + updateFilesOfFileSystemEntry(result, getBaseNameOfFileName(fileName), true); + } + return host.writeFile(fileName, data, writeByteOrderMark); + } + function fileExists(fileName) { + var path = toPath(fileName); + var result = getCachedFileSystemEntriesForBaseDir(path); + return result && hasEntry(result.files, getBaseNameOfFileName(fileName)) || + host.fileExists(fileName); + } + function directoryExists(dirPath) { + var path = toPath(dirPath); + return cachedReadDirectoryResult.has(ts.ensureTrailingDirectorySeparator(path)) || host.directoryExists(dirPath); + } + function createDirectory(dirPath) { + var path = toPath(dirPath); + var result = getCachedFileSystemEntriesForBaseDir(path); + var baseFileName = getBaseNameOfFileName(dirPath); + if (result) { + updateFileSystemEntry(result.directories, baseFileName, true); + } + host.createDirectory(dirPath); + } + function getDirectories(rootDir) { + var rootDirPath = toPath(rootDir); + var result = tryReadDirectory(rootDir, rootDirPath); + if (result) { + return result.directories.slice(); + } + return host.getDirectories(rootDir); + } + function readDirectory(rootDir, extensions, excludes, includes, depth) { + var rootDirPath = toPath(rootDir); + var result = tryReadDirectory(rootDir, rootDirPath); + if (result) { + return ts.matchFiles(rootDir, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries); + } + return host.readDirectory(rootDir, extensions, excludes, includes, depth); + function getFileSystemEntries(dir) { + var path = toPath(dir); + if (path === rootDirPath) { + return result; + } + return tryReadDirectory(dir, path) || ts.emptyFileSystemEntries; + } + } + function addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath) { + var existingResult = getCachedFileSystemEntries(fileOrDirectoryPath); + if (existingResult) { + clearCache(); + return undefined; + } + var parentResult = getCachedFileSystemEntriesForBaseDir(fileOrDirectoryPath); + if (!parentResult) { + return undefined; + } + if (!host.directoryExists) { + clearCache(); + return undefined; + } + var baseName = getBaseNameOfFileName(fileOrDirectory); + var fsQueryResult = { + fileExists: host.fileExists(fileOrDirectoryPath), + directoryExists: host.directoryExists(fileOrDirectoryPath) + }; + if (fsQueryResult.directoryExists || hasEntry(parentResult.directories, baseName)) { + clearCache(); + } + else { + updateFilesOfFileSystemEntry(parentResult, baseName, fsQueryResult.fileExists); + } + return fsQueryResult; + } + function addOrDeleteFile(fileName, filePath, eventKind) { + if (eventKind === ts.FileWatcherEventKind.Changed) { + return; + } + var parentResult = getCachedFileSystemEntriesForBaseDir(filePath); + if (parentResult) { + updateFilesOfFileSystemEntry(parentResult, getBaseNameOfFileName(fileName), eventKind === ts.FileWatcherEventKind.Created); + } + } + function updateFilesOfFileSystemEntry(parentResult, baseName, fileExists) { + updateFileSystemEntry(parentResult.files, baseName, fileExists); + } + function clearCache() { + cachedReadDirectoryResult.clear(); + } + } + ts.createCachedDirectoryStructureHost = createCachedDirectoryStructureHost; + var ConfigFileProgramReloadLevel; + (function (ConfigFileProgramReloadLevel) { + ConfigFileProgramReloadLevel[ConfigFileProgramReloadLevel["None"] = 0] = "None"; + ConfigFileProgramReloadLevel[ConfigFileProgramReloadLevel["Partial"] = 1] = "Partial"; + ConfigFileProgramReloadLevel[ConfigFileProgramReloadLevel["Full"] = 2] = "Full"; + })(ConfigFileProgramReloadLevel = ts.ConfigFileProgramReloadLevel || (ts.ConfigFileProgramReloadLevel = {})); + function updateMissingFilePathsWatch(program, missingFileWatches, createMissingFileWatch) { + var missingFilePaths = program.getMissingFilePaths(); + var newMissingFilePathMap = ts.arrayToSet(missingFilePaths); + ts.mutateMap(missingFileWatches, newMissingFilePathMap, { + createNewValue: createMissingFileWatch, + onDeleteValue: ts.closeFileWatcher + }); + } + ts.updateMissingFilePathsWatch = updateMissingFilePathsWatch; + function updateWatchingWildcardDirectories(existingWatchedForWildcards, wildcardDirectories, watchDirectory) { + ts.mutateMap(existingWatchedForWildcards, wildcardDirectories, { + createNewValue: createWildcardDirectoryWatcher, + onDeleteValue: closeFileWatcherOf, + onExistingValue: updateWildcardDirectoryWatcher + }); + function createWildcardDirectoryWatcher(directory, flags) { + return { + watcher: watchDirectory(directory, flags), + flags: flags + }; + } + function updateWildcardDirectoryWatcher(existingWatcher, flags, directory) { + if (existingWatcher.flags === flags) { + return; + } + existingWatcher.watcher.close(); + existingWatchedForWildcards.set(directory, createWildcardDirectoryWatcher(directory, flags)); + } + } + ts.updateWatchingWildcardDirectories = updateWatchingWildcardDirectories; + function isEmittedFileOfProgram(program, file) { + if (!program) { + return false; + } + return program.isEmittedFile(file); + } + ts.isEmittedFileOfProgram = isEmittedFileOfProgram; + var WatchLogLevel; + (function (WatchLogLevel) { + WatchLogLevel[WatchLogLevel["None"] = 0] = "None"; + WatchLogLevel[WatchLogLevel["TriggerOnly"] = 1] = "TriggerOnly"; + WatchLogLevel[WatchLogLevel["Verbose"] = 2] = "Verbose"; + })(WatchLogLevel = ts.WatchLogLevel || (ts.WatchLogLevel = {})); + function getWatchFactory(watchLogLevel, log, getDetailWatchInfo) { + return getWatchFactoryWith(watchLogLevel, log, getDetailWatchInfo, watchFile, watchDirectory); + } + ts.getWatchFactory = getWatchFactory; + function getWatchFactoryWith(watchLogLevel, log, getDetailWatchInfo, watchFile, watchDirectory) { + var createFileWatcher = getCreateFileWatcher(watchLogLevel, watchFile); + var createFilePathWatcher = watchLogLevel === WatchLogLevel.None ? watchFilePath : createFileWatcher; + var createDirectoryWatcher = getCreateFileWatcher(watchLogLevel, watchDirectory); + return { + watchFile: function (host, file, callback, pollingInterval, detailInfo1, detailInfo2) { + return createFileWatcher(host, file, callback, pollingInterval, undefined, detailInfo1, detailInfo2, watchFile, log, "FileWatcher", getDetailWatchInfo); + }, + watchFilePath: function (host, file, callback, pollingInterval, path, detailInfo1, detailInfo2) { + return createFilePathWatcher(host, file, callback, pollingInterval, path, detailInfo1, detailInfo2, watchFile, log, "FileWatcher", getDetailWatchInfo); + }, + watchDirectory: function (host, directory, callback, flags, detailInfo1, detailInfo2) { + return createDirectoryWatcher(host, directory, callback, flags, undefined, detailInfo1, detailInfo2, watchDirectory, log, "DirectoryWatcher", getDetailWatchInfo); + } + }; + function watchFilePath(host, file, callback, pollingInterval, path) { + return watchFile(host, file, function (fileName, eventKind) { return callback(fileName, eventKind, path); }, pollingInterval); + } + } + function watchFile(host, file, callback, pollingInterval) { + return host.watchFile(file, callback, pollingInterval); + } + function watchDirectory(host, directory, callback, flags) { + return host.watchDirectory(directory, callback, (flags & 1) !== 0); + } + function getCreateFileWatcher(watchLogLevel, addWatch) { + switch (watchLogLevel) { + case WatchLogLevel.None: + return addWatch; + case WatchLogLevel.TriggerOnly: + return createFileWatcherWithTriggerLogging; + case WatchLogLevel.Verbose: + return addWatch === watchDirectory ? createDirectoryWatcherWithLogging : createFileWatcherWithLogging; + } + } + function createFileWatcherWithLogging(host, file, cb, flags, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo) { + log(watchCaption + ":: Added:: " + getWatchInfo(file, flags, detailInfo1, detailInfo2, getDetailWatchInfo)); + var watcher = createFileWatcherWithTriggerLogging(host, file, cb, flags, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo); + return { + close: function () { + log(watchCaption + ":: Close:: " + getWatchInfo(file, flags, detailInfo1, detailInfo2, getDetailWatchInfo)); + watcher.close(); + } + }; + } + function createDirectoryWatcherWithLogging(host, file, cb, flags, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo) { + var watchInfo = watchCaption + ":: Added:: " + getWatchInfo(file, flags, detailInfo1, detailInfo2, getDetailWatchInfo); + log(watchInfo); + var start = ts.timestamp(); + var watcher = createFileWatcherWithTriggerLogging(host, file, cb, flags, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo); + var elapsed = ts.timestamp() - start; + log("Elapsed:: " + elapsed + "ms " + watchInfo); + return { + close: function () { + var watchInfo = watchCaption + ":: Close:: " + getWatchInfo(file, flags, detailInfo1, detailInfo2, getDetailWatchInfo); + log(watchInfo); + var start = ts.timestamp(); + watcher.close(); + var elapsed = ts.timestamp() - start; + log("Elapsed:: " + elapsed + "ms " + watchInfo); + } + }; + } + function createFileWatcherWithTriggerLogging(host, file, cb, flags, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo) { + return addWatch(host, file, function (fileName, cbOptional) { + var triggerredInfo = watchCaption + ":: Triggered with " + fileName + " " + (cbOptional !== undefined ? cbOptional : "") + ":: " + getWatchInfo(file, flags, detailInfo1, detailInfo2, getDetailWatchInfo); + log(triggerredInfo); + var start = ts.timestamp(); + cb(fileName, cbOptional, passThrough); + var elapsed = ts.timestamp() - start; + log("Elapsed:: " + elapsed + "ms " + triggerredInfo); + }, flags); + } + function getWatchInfo(file, flags, detailInfo1, detailInfo2, getDetailWatchInfo) { + return "WatchInfo: " + file + " " + flags + " " + (getDetailWatchInfo ? getDetailWatchInfo(detailInfo1, detailInfo2) : detailInfo1); + } + function closeFileWatcherOf(objWithWatcher) { + objWithWatcher.watcher.close(); + } + ts.closeFileWatcherOf = closeFileWatcherOf; +})(ts || (ts = {})); +var ts; +(function (ts) { + var ignoreDiagnosticCommentRegEx = /(^\s*$)|(^\s*\/\/\/?\s*(@ts-ignore)?)/; + function findConfigFile(searchPath, fileExists, configName) { + if (configName === void 0) { configName = "tsconfig.json"; } + return ts.forEachAncestorDirectory(searchPath, function (ancestor) { + var fileName = ts.combinePaths(ancestor, configName); + return fileExists(fileName) ? fileName : undefined; + }); + } + ts.findConfigFile = findConfigFile; + function resolveTripleslashReference(moduleName, containingFile) { + var basePath = ts.getDirectoryPath(containingFile); + var referencedFileName = ts.isRootedDiskPath(moduleName) ? moduleName : ts.combinePaths(basePath, moduleName); + return ts.normalizePath(referencedFileName); + } + ts.resolveTripleslashReference = resolveTripleslashReference; + function computeCommonSourceDirectoryOfFilenames(fileNames, currentDirectory, getCanonicalFileName) { + var commonPathComponents; + var failed = ts.forEach(fileNames, function (sourceFile) { + var sourcePathComponents = ts.getNormalizedPathComponents(sourceFile, currentDirectory); + sourcePathComponents.pop(); + if (!commonPathComponents) { + commonPathComponents = sourcePathComponents; + return; + } + var n = Math.min(commonPathComponents.length, sourcePathComponents.length); + for (var i = 0; i < n; i++) { + if (getCanonicalFileName(commonPathComponents[i]) !== getCanonicalFileName(sourcePathComponents[i])) { + if (i === 0) { + return true; + } + commonPathComponents.length = i; + break; + } + } + if (sourcePathComponents.length < commonPathComponents.length) { + commonPathComponents.length = sourcePathComponents.length; + } + }); + if (failed) { + return ""; + } + if (!commonPathComponents) { + return currentDirectory; + } + return ts.getPathFromPathComponents(commonPathComponents); + } + ts.computeCommonSourceDirectoryOfFilenames = computeCommonSourceDirectoryOfFilenames; + function createCompilerHost(options, setParentNodes) { + return createCompilerHostWorker(options, setParentNodes); + } + ts.createCompilerHost = createCompilerHost; + function createCompilerHostWorker(options, setParentNodes, system) { + if (system === void 0) { system = ts.sys; } + var existingDirectories = ts.createMap(); + function getCanonicalFileName(fileName) { + return system.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); + } + function getSourceFile(fileName, languageVersion, onError) { + var text; + try { + ts.performance.mark("beforeIORead"); + text = compilerHost.readFile(fileName); + ts.performance.mark("afterIORead"); + ts.performance.measure("I/O Read", "beforeIORead", "afterIORead"); + } + catch (e) { + if (onError) { + onError(e.message); + } + text = ""; + } + return text !== undefined ? ts.createSourceFile(fileName, text, languageVersion, setParentNodes) : undefined; + } + function directoryExists(directoryPath) { + if (existingDirectories.has(directoryPath)) { + return true; + } + if (system.directoryExists(directoryPath)) { + existingDirectories.set(directoryPath, true); + return true; + } + return false; + } + function ensureDirectoriesExist(directoryPath) { + if (directoryPath.length > ts.getRootLength(directoryPath) && !directoryExists(directoryPath)) { + var parentDirectory = ts.getDirectoryPath(directoryPath); + ensureDirectoriesExist(parentDirectory); + if (compilerHost.createDirectory) { + compilerHost.createDirectory(directoryPath); + } + else { + system.createDirectory(directoryPath); + } + } + } + var outputFingerprints; + function writeFileIfUpdated(fileName, data, writeByteOrderMark) { + if (!outputFingerprints) { + outputFingerprints = ts.createMap(); + } + var hash = system.createHash(data); + var mtimeBefore = system.getModifiedTime(fileName); + if (mtimeBefore) { + var fingerprint = outputFingerprints.get(fileName); + if (fingerprint && + fingerprint.byteOrderMark === writeByteOrderMark && + fingerprint.hash === hash && + fingerprint.mtime.getTime() === mtimeBefore.getTime()) { + return; + } + } + system.writeFile(fileName, data, writeByteOrderMark); + var mtimeAfter = system.getModifiedTime(fileName) || ts.missingFileModifiedTime; + outputFingerprints.set(fileName, { + hash: hash, + byteOrderMark: writeByteOrderMark, + mtime: mtimeAfter + }); + } + function writeFile(fileName, data, writeByteOrderMark, onError) { + try { + ts.performance.mark("beforeIOWrite"); + ensureDirectoriesExist(ts.getDirectoryPath(ts.normalizePath(fileName))); + if (ts.isWatchSet(options) && system.createHash && system.getModifiedTime) { + writeFileIfUpdated(fileName, data, writeByteOrderMark); + } + else { + system.writeFile(fileName, data, writeByteOrderMark); + } + ts.performance.mark("afterIOWrite"); + ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite"); + } + catch (e) { + if (onError) { + onError(e.message); + } + } + } + function getDefaultLibLocation() { + return ts.getDirectoryPath(ts.normalizePath(system.getExecutingFilePath())); + } + var newLine = ts.getNewLineCharacter(options, function () { return system.newLine; }); + var realpath = system.realpath && (function (path) { return system.realpath(path); }); + var compilerHost = { + getSourceFile: getSourceFile, + getDefaultLibLocation: getDefaultLibLocation, + getDefaultLibFileName: function (options) { return ts.combinePaths(getDefaultLibLocation(), ts.getDefaultLibFileName(options)); }, + writeFile: writeFile, + getCurrentDirectory: ts.memoize(function () { return system.getCurrentDirectory(); }), + useCaseSensitiveFileNames: function () { return system.useCaseSensitiveFileNames; }, + getCanonicalFileName: getCanonicalFileName, + getNewLine: function () { return newLine; }, + fileExists: function (fileName) { return system.fileExists(fileName); }, + readFile: function (fileName) { return system.readFile(fileName); }, + trace: function (s) { return system.write(s + newLine); }, + directoryExists: function (directoryName) { return system.directoryExists(directoryName); }, + getEnvironmentVariable: function (name) { return system.getEnvironmentVariable ? system.getEnvironmentVariable(name) : ""; }, + getDirectories: function (path) { return system.getDirectories(path); }, + realpath: realpath, + readDirectory: function (path, extensions, include, exclude, depth) { return system.readDirectory(path, extensions, include, exclude, depth); }, + createDirectory: function (d) { return system.createDirectory(d); } + }; + return compilerHost; + } + ts.createCompilerHostWorker = createCompilerHostWorker; + function changeCompilerHostToUseCache(host, toPath, useCacheForSourceFile) { + var originalReadFile = host.readFile; + var originalFileExists = host.fileExists; + var originalDirectoryExists = host.directoryExists; + var originalCreateDirectory = host.createDirectory; + var originalWriteFile = host.writeFile; + var originalGetSourceFile = host.getSourceFile; + var readFileCache = ts.createMap(); + var fileExistsCache = ts.createMap(); + var directoryExistsCache = ts.createMap(); + var sourceFileCache = ts.createMap(); + var readFileWithCache = function (fileName) { + var key = toPath(fileName); + var value = readFileCache.get(key); + if (value !== undefined) + return value || undefined; + return setReadFileCache(key, fileName); + }; + var setReadFileCache = function (key, fileName) { + var newValue = originalReadFile.call(host, fileName); + readFileCache.set(key, newValue || false); + return newValue; + }; + host.readFile = function (fileName) { + var key = toPath(fileName); + var value = readFileCache.get(key); + if (value !== undefined) + return value; + if (!ts.fileExtensionIs(fileName, ".json")) { + return originalReadFile.call(host, fileName); + } + return setReadFileCache(key, fileName); + }; + if (useCacheForSourceFile) { + host.getSourceFile = function (fileName, languageVersion, onError, shouldCreateNewSourceFile) { + var key = toPath(fileName); + var value = sourceFileCache.get(key); + if (value) + return value; + var sourceFile = originalGetSourceFile.call(host, fileName, languageVersion, onError, shouldCreateNewSourceFile); + if (sourceFile && (ts.isDeclarationFileName(fileName) || ts.fileExtensionIs(fileName, ".json"))) { + sourceFileCache.set(key, sourceFile); + } + return sourceFile; + }; + } + host.fileExists = function (fileName) { + var key = toPath(fileName); + var value = fileExistsCache.get(key); + if (value !== undefined) + return value; + var newValue = originalFileExists.call(host, fileName); + fileExistsCache.set(key, !!newValue); + return newValue; + }; + host.writeFile = function (fileName, data, writeByteOrderMark, onError, sourceFiles) { + var key = toPath(fileName); + fileExistsCache.delete(key); + var value = readFileCache.get(key); + if (value && value !== data) { + readFileCache.delete(key); + sourceFileCache.delete(key); + } + else if (useCacheForSourceFile) { + var sourceFile = sourceFileCache.get(key); + if (sourceFile && sourceFile.text !== data) { + sourceFileCache.delete(key); + } + } + originalWriteFile.call(host, fileName, data, writeByteOrderMark, onError, sourceFiles); + }; + if (originalDirectoryExists && originalCreateDirectory) { + host.directoryExists = function (directory) { + var key = toPath(directory); + var value = directoryExistsCache.get(key); + if (value !== undefined) + return value; + var newValue = originalDirectoryExists.call(host, directory); + directoryExistsCache.set(key, !!newValue); + return newValue; + }; + host.createDirectory = function (directory) { + var key = toPath(directory); + directoryExistsCache.delete(key); + originalCreateDirectory.call(host, directory); + }; + } + return { + originalReadFile: originalReadFile, + originalFileExists: originalFileExists, + originalDirectoryExists: originalDirectoryExists, + originalCreateDirectory: originalCreateDirectory, + originalWriteFile: originalWriteFile, + originalGetSourceFile: originalGetSourceFile, + readFileWithCache: readFileWithCache + }; + } + ts.changeCompilerHostToUseCache = changeCompilerHostToUseCache; + function getPreEmitDiagnostics(program, sourceFile, cancellationToken) { + var diagnostics = program.getConfigFileParsingDiagnostics().concat(program.getOptionsDiagnostics(cancellationToken), program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken)); + if (ts.getEmitDeclarations(program.getCompilerOptions())) { + ts.addRange(diagnostics, program.getDeclarationDiagnostics(sourceFile, cancellationToken)); + } + return ts.sortAndDeduplicateDiagnostics(diagnostics); + } + ts.getPreEmitDiagnostics = getPreEmitDiagnostics; + function formatDiagnostics(diagnostics, host) { + var output = ""; + for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { + var diagnostic = diagnostics_2[_i]; + output += formatDiagnostic(diagnostic, host); + } + return output; + } + ts.formatDiagnostics = formatDiagnostics; + function formatDiagnostic(diagnostic, host) { + var errorMessage = ts.diagnosticCategoryName(diagnostic) + " TS" + diagnostic.code + ": " + flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine()) + host.getNewLine(); + if (diagnostic.file) { + var _a = ts.getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start), line = _a.line, character = _a.character; + var fileName = diagnostic.file.fileName; + var relativeFileName = ts.convertToRelativePath(fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); }); + return relativeFileName + "(" + (line + 1) + "," + (character + 1) + "): " + errorMessage; + } + return errorMessage; + } + ts.formatDiagnostic = formatDiagnostic; + var ForegroundColorEscapeSequences; + (function (ForegroundColorEscapeSequences) { + ForegroundColorEscapeSequences["Grey"] = "\u001B[90m"; + ForegroundColorEscapeSequences["Red"] = "\u001B[91m"; + ForegroundColorEscapeSequences["Yellow"] = "\u001B[93m"; + ForegroundColorEscapeSequences["Blue"] = "\u001B[94m"; + ForegroundColorEscapeSequences["Cyan"] = "\u001B[96m"; + })(ForegroundColorEscapeSequences = ts.ForegroundColorEscapeSequences || (ts.ForegroundColorEscapeSequences = {})); + var gutterStyleSequence = "\u001b[7m"; + var gutterSeparator = " "; + var resetEscapeSequence = "\u001b[0m"; + var ellipsis = "..."; + var halfIndent = " "; + var indent = " "; + function getCategoryFormat(category) { + switch (category) { + case ts.DiagnosticCategory.Error: return ForegroundColorEscapeSequences.Red; + case ts.DiagnosticCategory.Warning: return ForegroundColorEscapeSequences.Yellow; + case ts.DiagnosticCategory.Suggestion: return ts.Debug.fail("Should never get an Info diagnostic on the command line."); + case ts.DiagnosticCategory.Message: return ForegroundColorEscapeSequences.Blue; + } + } + function formatColorAndReset(text, formatStyle) { + return formatStyle + text + resetEscapeSequence; + } + ts.formatColorAndReset = formatColorAndReset; + function padLeft(s, length) { + while (s.length < length) { + s = " " + s; + } + return s; + } + function formatCodeSpan(file, start, length, indent, squiggleColor, host) { + var _a = ts.getLineAndCharacterOfPosition(file, start), firstLine = _a.line, firstLineChar = _a.character; + var _b = ts.getLineAndCharacterOfPosition(file, start + length), lastLine = _b.line, lastLineChar = _b.character; + var lastLineInFile = ts.getLineAndCharacterOfPosition(file, file.text.length).line; + var hasMoreThanFiveLines = (lastLine - firstLine) >= 4; + var gutterWidth = (lastLine + 1 + "").length; + if (hasMoreThanFiveLines) { + gutterWidth = Math.max(ellipsis.length, gutterWidth); + } + var context = ""; + for (var i = firstLine; i <= lastLine; i++) { + context += host.getNewLine(); + if (hasMoreThanFiveLines && firstLine + 1 < i && i < lastLine - 1) { + context += indent + formatColorAndReset(padLeft(ellipsis, gutterWidth), gutterStyleSequence) + gutterSeparator + host.getNewLine(); + i = lastLine - 1; + } + var lineStart = ts.getPositionOfLineAndCharacter(file, i, 0); + var lineEnd = i < lastLineInFile ? ts.getPositionOfLineAndCharacter(file, i + 1, 0) : file.text.length; + var lineContent = file.text.slice(lineStart, lineEnd); + lineContent = lineContent.replace(/\s+$/g, ""); + lineContent = lineContent.replace("\t", " "); + context += indent + formatColorAndReset(padLeft(i + 1 + "", gutterWidth), gutterStyleSequence) + gutterSeparator; + context += lineContent + host.getNewLine(); + context += indent + formatColorAndReset(padLeft("", gutterWidth), gutterStyleSequence) + gutterSeparator; + context += squiggleColor; + if (i === firstLine) { + var lastCharForLine = i === lastLine ? lastLineChar : undefined; + context += lineContent.slice(0, firstLineChar).replace(/\S/g, " "); + context += lineContent.slice(firstLineChar, lastCharForLine).replace(/./g, "~"); + } + else if (i === lastLine) { + context += lineContent.slice(0, lastLineChar).replace(/./g, "~"); + } + else { + context += lineContent.replace(/./g, "~"); + } + context += resetEscapeSequence; + } + return context; + } + function formatLocation(file, start, host, color) { + if (color === void 0) { color = formatColorAndReset; } + var _a = ts.getLineAndCharacterOfPosition(file, start), firstLine = _a.line, firstLineChar = _a.character; + var relativeFileName = host ? ts.convertToRelativePath(file.fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); }) : file.fileName; + var output = ""; + output += color(relativeFileName, ForegroundColorEscapeSequences.Cyan); + output += ":"; + output += color("" + (firstLine + 1), ForegroundColorEscapeSequences.Yellow); + output += ":"; + output += color("" + (firstLineChar + 1), ForegroundColorEscapeSequences.Yellow); + return output; + } + ts.formatLocation = formatLocation; + function formatDiagnosticsWithColorAndContext(diagnostics, host) { + var output = ""; + for (var _i = 0, diagnostics_3 = diagnostics; _i < diagnostics_3.length; _i++) { + var diagnostic = diagnostics_3[_i]; + if (diagnostic.file) { + var file = diagnostic.file, start = diagnostic.start; + output += formatLocation(file, start, host); + output += " - "; + } + output += formatColorAndReset(ts.diagnosticCategoryName(diagnostic), getCategoryFormat(diagnostic.category)); + output += formatColorAndReset(" TS" + diagnostic.code + ": ", ForegroundColorEscapeSequences.Grey); + output += flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine()); + if (diagnostic.file) { + output += host.getNewLine(); + output += formatCodeSpan(diagnostic.file, diagnostic.start, diagnostic.length, "", getCategoryFormat(diagnostic.category), host); + if (diagnostic.relatedInformation) { + output += host.getNewLine(); + for (var _a = 0, _b = diagnostic.relatedInformation; _a < _b.length; _a++) { + var _c = _b[_a], file = _c.file, start = _c.start, length_4 = _c.length, messageText = _c.messageText; + if (file) { + output += host.getNewLine(); + output += halfIndent + formatLocation(file, start, host); + output += formatCodeSpan(file, start, length_4, indent, ForegroundColorEscapeSequences.Cyan, host); + } + output += host.getNewLine(); + output += indent + flattenDiagnosticMessageText(messageText, host.getNewLine()); + } + } + } + output += host.getNewLine(); + } + return output; + } + ts.formatDiagnosticsWithColorAndContext = formatDiagnosticsWithColorAndContext; + function flattenDiagnosticMessageText(messageText, newLine) { + if (ts.isString(messageText)) { + return messageText; + } + else { + var diagnosticChain = messageText; + var result = ""; + var indent_1 = 0; + while (diagnosticChain) { + if (indent_1) { + result += newLine; + for (var i = 0; i < indent_1; i++) { + result += " "; + } + } + result += diagnosticChain.messageText; + indent_1++; + diagnosticChain = diagnosticChain.next; + } + return result; + } + } + ts.flattenDiagnosticMessageText = flattenDiagnosticMessageText; + function loadWithLocalCache(names, containingFile, redirectedReference, loader) { + if (names.length === 0) { + return []; + } + var resolutions = []; + var cache = ts.createMap(); + for (var _i = 0, names_1 = names; _i < names_1.length; _i++) { + var name = names_1[_i]; + var result = void 0; + if (cache.has(name)) { + result = cache.get(name); + } + else { + cache.set(name, result = loader(name, containingFile, redirectedReference)); + } + resolutions.push(result); + } + return resolutions; + } + function isProgramUptoDate(program, rootFileNames, newOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, projectReferences) { + if (!program || hasChangedAutomaticTypeDirectiveNames) { + return false; + } + if (program.getRootFileNames().length !== rootFileNames.length) { + return false; + } + var seenResolvedRefs; + if (!ts.arrayIsEqualTo(program.getProjectReferences(), projectReferences, projectReferenceUptoDate)) { + return false; + } + if (program.getSourceFiles().some(sourceFileNotUptoDate)) { + return false; + } + if (program.getMissingFilePaths().some(fileExists)) { + return false; + } + var currentOptions = program.getCompilerOptions(); + if (!ts.compareDataObjects(currentOptions, newOptions)) { + return false; + } + if (currentOptions.configFile && newOptions.configFile) { + return currentOptions.configFile.text === newOptions.configFile.text; + } + return true; + function sourceFileNotUptoDate(sourceFile) { + return !sourceFileVersionUptoDate(sourceFile) || + hasInvalidatedResolution(sourceFile.path); + } + function sourceFileVersionUptoDate(sourceFile) { + return sourceFile.version === getSourceVersion(sourceFile.resolvedPath); + } + function projectReferenceUptoDate(oldRef, newRef, index) { + if (!ts.projectReferenceIsEqualTo(oldRef, newRef)) { + return false; + } + return resolvedProjectReferenceUptoDate(program.getResolvedProjectReferences()[index], oldRef); + } + function resolvedProjectReferenceUptoDate(oldResolvedRef, oldRef) { + if (oldResolvedRef) { + if (ts.contains(seenResolvedRefs, oldResolvedRef)) { + return true; + } + if (!sourceFileVersionUptoDate(oldResolvedRef.sourceFile)) { + return false; + } + (seenResolvedRefs || (seenResolvedRefs = [])).push(oldResolvedRef); + return !ts.forEach(oldResolvedRef.references, function (childResolvedRef, index) { + return !resolvedProjectReferenceUptoDate(childResolvedRef, oldResolvedRef.commandLine.projectReferences[index]); + }); + } + return !fileExists(resolveProjectReferencePath(oldRef)); + } + } + ts.isProgramUptoDate = isProgramUptoDate; + function getConfigFileParsingDiagnostics(configFileParseResult) { + return configFileParseResult.options.configFile ? configFileParseResult.options.configFile.parseDiagnostics.concat(configFileParseResult.errors) : + configFileParseResult.errors; + } + ts.getConfigFileParsingDiagnostics = getConfigFileParsingDiagnostics; + function shouldProgramCreateNewSourceFiles(program, newOptions) { + if (!program) + return false; + var oldOptions = program.getCompilerOptions(); + return !!ts.sourceFileAffectingCompilerOptions.some(function (option) { + return !ts.isJsonEqual(ts.getCompilerOptionValue(oldOptions, option), ts.getCompilerOptionValue(newOptions, option)); + }); + } + function createCreateProgramOptions(rootNames, options, host, oldProgram, configFileParsingDiagnostics) { + return { + rootNames: rootNames, + options: options, + host: host, + oldProgram: oldProgram, + configFileParsingDiagnostics: configFileParsingDiagnostics + }; + } + function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _configFileParsingDiagnostics) { + var createProgramOptions = ts.isArray(rootNamesOrOptions) ? createCreateProgramOptions(rootNamesOrOptions, _options, _host, _oldProgram, _configFileParsingDiagnostics) : rootNamesOrOptions; + var rootNames = createProgramOptions.rootNames, options = createProgramOptions.options, configFileParsingDiagnostics = createProgramOptions.configFileParsingDiagnostics, projectReferences = createProgramOptions.projectReferences; + var oldProgram = createProgramOptions.oldProgram; + var program; + var processingDefaultLibFiles; + var processingOtherFiles; + var files; + var commonSourceDirectory; + var diagnosticsProducingTypeChecker; + var noDiagnosticsTypeChecker; + var classifiableNames; + var ambientModuleNameToUnmodifiedFileName = ts.createMap(); + var cachedSemanticDiagnosticsForFile = {}; + var cachedDeclarationDiagnosticsForFile = {}; + var resolvedTypeReferenceDirectives = ts.createMap(); + var fileProcessingDiagnostics = ts.createDiagnosticCollection(); + var maxNodeModuleJsDepth = typeof options.maxNodeModuleJsDepth === "number" ? options.maxNodeModuleJsDepth : 0; + var currentNodeModulesDepth = 0; + var modulesWithElidedImports = ts.createMap(); + var sourceFilesFoundSearchingNodeModules = ts.createMap(); + ts.performance.mark("beforeProgram"); + var host = createProgramOptions.host || createCompilerHost(options); + var configParsingHost = parseConfigHostFromCompilerHost(host); + var skipDefaultLib = options.noLib; + var getDefaultLibraryFileName = ts.memoize(function () { return host.getDefaultLibFileName(options); }); + var defaultLibraryPath = host.getDefaultLibLocation ? host.getDefaultLibLocation() : ts.getDirectoryPath(getDefaultLibraryFileName()); + var programDiagnostics = ts.createDiagnosticCollection(); + var currentDirectory = host.getCurrentDirectory(); + var supportedExtensions = ts.getSupportedExtensions(options); + var supportedExtensionsWithJsonIfResolveJsonModule = ts.getSuppoertedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions); + var hasEmitBlockingDiagnostics = ts.createMap(); + var _compilerOptionsObjectLiteralSyntax; + var moduleResolutionCache; + var resolveModuleNamesWorker; + var hasInvalidatedResolution = host.hasInvalidatedResolution || ts.returnFalse; + if (host.resolveModuleNames) { + resolveModuleNamesWorker = function (moduleNames, containingFile, reusedNames, redirectedReference) { return host.resolveModuleNames(ts.Debug.assertEachDefined(moduleNames), containingFile, reusedNames, redirectedReference).map(function (resolved) { + if (!resolved || resolved.extension !== undefined) { + return resolved; + } + var withExtension = ts.clone(resolved); + withExtension.extension = ts.extensionFromPath(resolved.resolvedFileName); + return withExtension; + }); }; + } + else { + moduleResolutionCache = ts.createModuleResolutionCache(currentDirectory, function (x) { return host.getCanonicalFileName(x); }); + var loader_1 = function (moduleName, containingFile, redirectedReference) { return ts.resolveModuleName(moduleName, containingFile, options, host, moduleResolutionCache, redirectedReference).resolvedModule; }; + resolveModuleNamesWorker = function (moduleNames, containingFile, _reusedNames, redirectedReference) { return loadWithLocalCache(ts.Debug.assertEachDefined(moduleNames), containingFile, redirectedReference, loader_1); }; + } + var resolveTypeReferenceDirectiveNamesWorker; + if (host.resolveTypeReferenceDirectives) { + resolveTypeReferenceDirectiveNamesWorker = function (typeDirectiveNames, containingFile, redirectedReference) { return host.resolveTypeReferenceDirectives(ts.Debug.assertEachDefined(typeDirectiveNames), containingFile, redirectedReference); }; + } + else { + var loader_2 = function (typesRef, containingFile, redirectedReference) { return ts.resolveTypeReferenceDirective(typesRef, containingFile, options, host, redirectedReference).resolvedTypeReferenceDirective; }; + resolveTypeReferenceDirectiveNamesWorker = function (typeReferenceDirectiveNames, containingFile, redirectedReference) { return loadWithLocalCache(ts.Debug.assertEachDefined(typeReferenceDirectiveNames), containingFile, redirectedReference, loader_2); }; + } + var packageIdToSourceFile = ts.createMap(); + var sourceFileToPackageName = ts.createMap(); + var redirectTargetsMap = ts.createMultiMap(); + var filesByName = ts.createMap(); + var missingFilePaths; + var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createMap() : undefined; + var resolvedProjectReferences; + var projectReferenceRedirects; + var mapFromFileToProjectReferenceRedirects; + var shouldCreateNewSourceFile = shouldProgramCreateNewSourceFiles(oldProgram, options); + var structuralIsReused = tryReuseStructureFromOldProgram(); + if (structuralIsReused !== 2) { + processingDefaultLibFiles = []; + processingOtherFiles = []; + if (projectReferences) { + if (!resolvedProjectReferences) { + resolvedProjectReferences = projectReferences.map(parseProjectReferenceConfigFile); + } + if (rootNames.length) { + for (var _i = 0, resolvedProjectReferences_1 = resolvedProjectReferences; _i < resolvedProjectReferences_1.length; _i++) { + var parsedRef = resolvedProjectReferences_1[_i]; + if (parsedRef) { + var out = parsedRef.commandLine.options.outFile || parsedRef.commandLine.options.out; + if (out) { + var dtsOutfile = ts.changeExtension(out, ".d.ts"); + processSourceFile(dtsOutfile, false, false, undefined); + } + } + } + } + } + ts.forEach(rootNames, function (name) { return processRootFile(name, false, false); }); + var typeReferences = rootNames.length ? ts.getAutomaticTypeDirectiveNames(options, host) : ts.emptyArray; + if (typeReferences.length) { + var containingDirectory = options.configFilePath ? ts.getDirectoryPath(options.configFilePath) : host.getCurrentDirectory(); + var containingFilename = ts.combinePaths(containingDirectory, "__inferred type names__.ts"); + var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeReferences, containingFilename); + for (var i = 0; i < typeReferences.length; i++) { + processTypeReferenceDirective(typeReferences[i], resolutions[i]); + } + } + if (rootNames.length && !skipDefaultLib) { + var defaultLibraryFileName = getDefaultLibraryFileName(); + if (!options.lib && defaultLibraryFileName) { + processRootFile(defaultLibraryFileName, true, false); + } + else { + ts.forEach(options.lib, function (libFileName) { + processRootFile(ts.combinePaths(defaultLibraryPath, libFileName), true, false); + }); + } + } + missingFilePaths = ts.arrayFrom(filesByName.keys(), function (p) { return p; }).filter(function (p) { return !filesByName.get(p); }); + files = ts.stableSort(processingDefaultLibFiles, compareDefaultLibFiles).concat(processingOtherFiles); + processingDefaultLibFiles = undefined; + processingOtherFiles = undefined; + } + ts.Debug.assert(!!missingFilePaths); + if (oldProgram && host.onReleaseOldSourceFile) { + var oldSourceFiles = oldProgram.getSourceFiles(); + for (var _a = 0, oldSourceFiles_1 = oldSourceFiles; _a < oldSourceFiles_1.length; _a++) { + var oldSourceFile = oldSourceFiles_1[_a]; + var newFile = getSourceFileByPath(oldSourceFile.resolvedPath); + if (shouldCreateNewSourceFile || !newFile || + (oldSourceFile.resolvedPath === oldSourceFile.path && newFile.resolvedPath !== oldSourceFile.path)) { + host.onReleaseOldSourceFile(oldSourceFile, oldProgram.getCompilerOptions(), !!getSourceFileByPath(oldSourceFile.path)); + } + } + oldProgram.forEachResolvedProjectReference(function (resolvedProjectReference, resolvedProjectReferencePath) { + if (resolvedProjectReference && !getResolvedProjectReferenceByPath(resolvedProjectReferencePath)) { + host.onReleaseOldSourceFile(resolvedProjectReference.sourceFile, oldProgram.getCompilerOptions(), false); + } + }); + } + oldProgram = undefined; + program = { + getRootFileNames: function () { return rootNames; }, + getSourceFile: getSourceFile, + getSourceFileByPath: getSourceFileByPath, + getSourceFiles: function () { return files; }, + getMissingFilePaths: function () { return missingFilePaths; }, + getCompilerOptions: function () { return options; }, + getSyntacticDiagnostics: getSyntacticDiagnostics, + getOptionsDiagnostics: getOptionsDiagnostics, + getGlobalDiagnostics: getGlobalDiagnostics, + getSemanticDiagnostics: getSemanticDiagnostics, + getSuggestionDiagnostics: getSuggestionDiagnostics, + getDeclarationDiagnostics: getDeclarationDiagnostics, + getTypeChecker: getTypeChecker, + getClassifiableNames: getClassifiableNames, + getDiagnosticsProducingTypeChecker: getDiagnosticsProducingTypeChecker, + getCommonSourceDirectory: getCommonSourceDirectory, + emit: emit, + getCurrentDirectory: function () { return currentDirectory; }, + getNodeCount: function () { return getDiagnosticsProducingTypeChecker().getNodeCount(); }, + getIdentifierCount: function () { return getDiagnosticsProducingTypeChecker().getIdentifierCount(); }, + getSymbolCount: function () { return getDiagnosticsProducingTypeChecker().getSymbolCount(); }, + getTypeCount: function () { return getDiagnosticsProducingTypeChecker().getTypeCount(); }, + getFileProcessingDiagnostics: function () { return fileProcessingDiagnostics; }, + getResolvedTypeReferenceDirectives: function () { return resolvedTypeReferenceDirectives; }, + isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary, + isSourceFileDefaultLibrary: isSourceFileDefaultLibrary, + dropDiagnosticsProducingTypeChecker: dropDiagnosticsProducingTypeChecker, + getSourceFileFromReference: getSourceFileFromReference, + getLibFileFromReference: getLibFileFromReference, + sourceFileToPackageName: sourceFileToPackageName, + redirectTargetsMap: redirectTargetsMap, + isEmittedFile: isEmittedFile, + getConfigFileParsingDiagnostics: getConfigFileParsingDiagnostics, + getResolvedModuleWithFailedLookupLocationsFromCache: getResolvedModuleWithFailedLookupLocationsFromCache, + getProjectReferences: getProjectReferences, + getResolvedProjectReferences: getResolvedProjectReferences, + getProjectReferenceRedirect: getProjectReferenceRedirect, + getResolvedProjectReferenceToRedirect: getResolvedProjectReferenceToRedirect, + getResolvedProjectReferenceByPath: getResolvedProjectReferenceByPath, + forEachResolvedProjectReference: forEachResolvedProjectReference + }; + verifyCompilerOptions(); + ts.performance.mark("afterProgram"); + ts.performance.measure("Program", "beforeProgram", "afterProgram"); + return program; + function compareDefaultLibFiles(a, b) { + return ts.compareValues(getDefaultLibFilePriority(a), getDefaultLibFilePriority(b)); + } + function getDefaultLibFilePriority(a) { + if (ts.containsPath(defaultLibraryPath, a.fileName, false)) { + var basename = ts.getBaseFileName(a.fileName); + if (basename === "lib.d.ts" || basename === "lib.es6.d.ts") + return 0; + var name = ts.removeSuffix(ts.removePrefix(basename, "lib."), ".d.ts"); + var index = ts.libs.indexOf(name); + if (index !== -1) + return index + 1; + } + return ts.libs.length + 2; + } + function getResolvedModuleWithFailedLookupLocationsFromCache(moduleName, containingFile) { + return moduleResolutionCache && ts.resolveModuleNameFromCache(moduleName, containingFile, moduleResolutionCache); + } + function toPath(fileName) { + return ts.toPath(fileName, currentDirectory, getCanonicalFileName); + } + function getCommonSourceDirectory() { + if (commonSourceDirectory === undefined) { + var emittedFiles = ts.filter(files, function (file) { return ts.sourceFileMayBeEmitted(file, options, isSourceFileFromExternalLibrary); }); + if (options.rootDir && checkSourceFilesBelongToPath(emittedFiles, options.rootDir)) { + commonSourceDirectory = ts.getNormalizedAbsolutePath(options.rootDir, currentDirectory); + } + else if (options.composite && options.configFilePath) { + commonSourceDirectory = ts.getDirectoryPath(ts.normalizeSlashes(options.configFilePath)); + checkSourceFilesBelongToPath(emittedFiles, commonSourceDirectory); + } + else { + commonSourceDirectory = computeCommonSourceDirectory(emittedFiles); + } + if (commonSourceDirectory && commonSourceDirectory[commonSourceDirectory.length - 1] !== ts.directorySeparator) { + commonSourceDirectory += ts.directorySeparator; + } + } + return commonSourceDirectory; + } + function getClassifiableNames() { + if (!classifiableNames) { + getTypeChecker(); + classifiableNames = ts.createUnderscoreEscapedMap(); + for (var _i = 0, files_2 = files; _i < files_2.length; _i++) { + var sourceFile = files_2[_i]; + ts.copyEntries(sourceFile.classifiableNames, classifiableNames); + } + } + return classifiableNames; + } + function resolveModuleNamesReusingOldState(moduleNames, containingFile, file) { + if (structuralIsReused === 0 && !file.ambientModuleNames.length) { + return resolveModuleNamesWorker(moduleNames, containingFile, undefined, getResolvedProjectReferenceToRedirect(file.originalFileName)); + } + var oldSourceFile = oldProgram && oldProgram.getSourceFile(containingFile); + if (oldSourceFile !== file && file.resolvedModules) { + var result_5 = []; + for (var _i = 0, moduleNames_1 = moduleNames; _i < moduleNames_1.length; _i++) { + var moduleName = moduleNames_1[_i]; + var resolvedModule = file.resolvedModules.get(moduleName); + result_5.push(resolvedModule); + } + return result_5; + } + var unknownModuleNames; + var result; + var reusedNames; + var predictedToResolveToAmbientModuleMarker = {}; + for (var i = 0; i < moduleNames.length; i++) { + var moduleName = moduleNames[i]; + if (file === oldSourceFile && !hasInvalidatedResolution(oldSourceFile.path)) { + var oldResolvedModule = oldSourceFile && oldSourceFile.resolvedModules.get(moduleName); + if (oldResolvedModule) { + if (ts.isTraceEnabled(options, host)) { + ts.trace(host, ts.Diagnostics.Reusing_resolution_of_module_0_to_file_1_from_old_program, moduleName, containingFile); + } + (result || (result = new Array(moduleNames.length)))[i] = oldResolvedModule; + (reusedNames || (reusedNames = [])).push(moduleName); + continue; + } + } + var resolvesToAmbientModuleInNonModifiedFile = false; + if (ts.contains(file.ambientModuleNames, moduleName)) { + resolvesToAmbientModuleInNonModifiedFile = true; + if (ts.isTraceEnabled(options, host)) { + ts.trace(host, ts.Diagnostics.Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1, moduleName, containingFile); + } + } + else { + resolvesToAmbientModuleInNonModifiedFile = moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName); + } + if (resolvesToAmbientModuleInNonModifiedFile) { + (result || (result = new Array(moduleNames.length)))[i] = predictedToResolveToAmbientModuleMarker; + } + else { + (unknownModuleNames || (unknownModuleNames = [])).push(moduleName); + } + } + var resolutions = unknownModuleNames && unknownModuleNames.length + ? resolveModuleNamesWorker(unknownModuleNames, containingFile, reusedNames, getResolvedProjectReferenceToRedirect(file.originalFileName)) + : ts.emptyArray; + if (!result) { + ts.Debug.assert(resolutions.length === moduleNames.length); + return resolutions; + } + var j = 0; + for (var i = 0; i < result.length; i++) { + if (result[i]) { + if (result[i] === predictedToResolveToAmbientModuleMarker) { + result[i] = undefined; + } + } + else { + result[i] = resolutions[j]; + j++; + } + } + ts.Debug.assert(j === resolutions.length); + return result; + function moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName) { + var resolutionToFile = ts.getResolvedModule(oldSourceFile, moduleName); + var resolvedFile = resolutionToFile && oldProgram.getSourceFile(resolutionToFile.resolvedFileName); + if (resolutionToFile && resolvedFile && !resolvedFile.externalModuleIndicator) { + return false; + } + var unmodifiedFile = ambientModuleNameToUnmodifiedFileName.get(moduleName); + if (!unmodifiedFile) { + return false; + } + if (ts.isTraceEnabled(options, host)) { + ts.trace(host, ts.Diagnostics.Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified, moduleName, unmodifiedFile); + } + return true; + } + } + function canReuseProjectReferences() { + return !forEachProjectReference(oldProgram.getProjectReferences(), oldProgram.getResolvedProjectReferences(), function (oldResolvedRef, index, parent) { + var newRef = (parent ? parent.commandLine.projectReferences : projectReferences)[index]; + var newResolvedRef = parseProjectReferenceConfigFile(newRef); + if (oldResolvedRef) { + return !newResolvedRef || newResolvedRef.sourceFile !== oldResolvedRef.sourceFile; + } + else { + return newResolvedRef !== undefined; + } + }, function (oldProjectReferences, parent) { + var newReferences = parent ? getResolvedProjectReferenceByPath(parent.sourceFile.path).commandLine.projectReferences : projectReferences; + return !ts.arrayIsEqualTo(oldProjectReferences, newReferences, ts.projectReferenceIsEqualTo); + }); + } + function tryReuseStructureFromOldProgram() { + if (!oldProgram) { + return 0; + } + var oldOptions = oldProgram.getCompilerOptions(); + if (ts.changesAffectModuleResolution(oldOptions, options)) { + return oldProgram.structureIsReused = 0; + } + ts.Debug.assert(!(oldProgram.structureIsReused & (2 | 1))); + var oldRootNames = oldProgram.getRootFileNames(); + if (!ts.arrayIsEqualTo(oldRootNames, rootNames)) { + return oldProgram.structureIsReused = 0; + } + if (!ts.arrayIsEqualTo(options.types, oldOptions.types)) { + return oldProgram.structureIsReused = 0; + } + if (!canReuseProjectReferences()) { + return oldProgram.structureIsReused = 0; + } + if (projectReferences) { + resolvedProjectReferences = projectReferences.map(parseProjectReferenceConfigFile); + } + var newSourceFiles = []; + var modifiedSourceFiles = []; + oldProgram.structureIsReused = 2; + if (oldProgram.getMissingFilePaths().some(function (missingFilePath) { return host.fileExists(missingFilePath); })) { + return oldProgram.structureIsReused = 0; + } + var oldSourceFiles = oldProgram.getSourceFiles(); + var seenPackageNames = ts.createMap(); + for (var _i = 0, oldSourceFiles_2 = oldSourceFiles; _i < oldSourceFiles_2.length; _i++) { + var oldSourceFile = oldSourceFiles_2[_i]; + var newSourceFile = host.getSourceFileByPath + ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.resolvedPath, options.target, undefined, shouldCreateNewSourceFile) + : host.getSourceFile(oldSourceFile.fileName, options.target, undefined, shouldCreateNewSourceFile); + if (!newSourceFile) { + return oldProgram.structureIsReused = 0; + } + ts.Debug.assert(!newSourceFile.redirectInfo, "Host should not return a redirect source file from `getSourceFile`"); + var fileChanged = void 0; + if (oldSourceFile.redirectInfo) { + if (newSourceFile !== oldSourceFile.redirectInfo.unredirected) { + return oldProgram.structureIsReused = 0; + } + fileChanged = false; + newSourceFile = oldSourceFile; + } + else if (oldProgram.redirectTargetsMap.has(oldSourceFile.path)) { + if (newSourceFile !== oldSourceFile) { + return oldProgram.structureIsReused = 0; + } + fileChanged = false; + } + else { + fileChanged = newSourceFile !== oldSourceFile; + } + newSourceFile.path = oldSourceFile.path; + newSourceFile.originalFileName = oldSourceFile.originalFileName; + newSourceFile.resolvedPath = oldSourceFile.resolvedPath; + newSourceFile.fileName = oldSourceFile.fileName; + var packageName = oldProgram.sourceFileToPackageName.get(oldSourceFile.path); + if (packageName !== undefined) { + var prevKind = seenPackageNames.get(packageName); + var newKind = fileChanged ? 1 : 0; + if ((prevKind !== undefined && newKind === 1) || prevKind === 1) { + return oldProgram.structureIsReused = 0; + } + seenPackageNames.set(packageName, newKind); + } + if (fileChanged) { + if (!ts.arrayIsEqualTo(oldSourceFile.libReferenceDirectives, newSourceFile.libReferenceDirectives, fileReferenceIsEqualTo)) { + return oldProgram.structureIsReused = 0; + } + if (oldSourceFile.hasNoDefaultLib !== newSourceFile.hasNoDefaultLib) { + oldProgram.structureIsReused = 1; + } + if (!ts.arrayIsEqualTo(oldSourceFile.referencedFiles, newSourceFile.referencedFiles, fileReferenceIsEqualTo)) { + oldProgram.structureIsReused = 1; + } + collectExternalModuleReferences(newSourceFile); + if (!ts.arrayIsEqualTo(oldSourceFile.imports, newSourceFile.imports, moduleNameIsEqualTo)) { + oldProgram.structureIsReused = 1; + } + if (!ts.arrayIsEqualTo(oldSourceFile.moduleAugmentations, newSourceFile.moduleAugmentations, moduleNameIsEqualTo)) { + oldProgram.structureIsReused = 1; + } + if ((oldSourceFile.flags & 1572864) !== (newSourceFile.flags & 1572864)) { + oldProgram.structureIsReused = 1; + } + if (!ts.arrayIsEqualTo(oldSourceFile.typeReferenceDirectives, newSourceFile.typeReferenceDirectives, fileReferenceIsEqualTo)) { + oldProgram.structureIsReused = 1; + } + modifiedSourceFiles.push({ oldFile: oldSourceFile, newFile: newSourceFile }); + } + else if (hasInvalidatedResolution(oldSourceFile.path)) { + oldProgram.structureIsReused = 1; + modifiedSourceFiles.push({ oldFile: oldSourceFile, newFile: newSourceFile }); + } + newSourceFiles.push(newSourceFile); + } + if (oldProgram.structureIsReused !== 2) { + return oldProgram.structureIsReused; + } + var modifiedFiles = modifiedSourceFiles.map(function (f) { return f.oldFile; }); + for (var _a = 0, oldSourceFiles_3 = oldSourceFiles; _a < oldSourceFiles_3.length; _a++) { + var oldFile = oldSourceFiles_3[_a]; + if (!ts.contains(modifiedFiles, oldFile)) { + for (var _b = 0, _c = oldFile.ambientModuleNames; _b < _c.length; _b++) { + var moduleName = _c[_b]; + ambientModuleNameToUnmodifiedFileName.set(moduleName, oldFile.fileName); + } + } + } + for (var _d = 0, modifiedSourceFiles_1 = modifiedSourceFiles; _d < modifiedSourceFiles_1.length; _d++) { + var _e = modifiedSourceFiles_1[_d], oldSourceFile = _e.oldFile, newSourceFile = _e.newFile; + var newSourceFilePath = ts.getNormalizedAbsolutePath(newSourceFile.originalFileName, currentDirectory); + if (resolveModuleNamesWorker) { + var moduleNames = getModuleNames(newSourceFile); + var resolutions = resolveModuleNamesReusingOldState(moduleNames, newSourceFilePath, newSourceFile); + var resolutionsChanged = ts.hasChangesInResolutions(moduleNames, resolutions, oldSourceFile.resolvedModules, ts.moduleResolutionIsEqualTo); + if (resolutionsChanged) { + oldProgram.structureIsReused = 1; + newSourceFile.resolvedModules = ts.zipToMap(moduleNames, resolutions); + } + else { + newSourceFile.resolvedModules = oldSourceFile.resolvedModules; + } + } + if (resolveTypeReferenceDirectiveNamesWorker) { + var typesReferenceDirectives = ts.map(newSourceFile.typeReferenceDirectives, function (ref) { return ref.fileName.toLocaleLowerCase(); }); + var resolutions = resolveTypeReferenceDirectiveNamesWorker(typesReferenceDirectives, newSourceFilePath, getResolvedProjectReferenceToRedirect(newSourceFile.originalFileName)); + var resolutionsChanged = ts.hasChangesInResolutions(typesReferenceDirectives, resolutions, oldSourceFile.resolvedTypeReferenceDirectiveNames, ts.typeDirectiveIsEqualTo); + if (resolutionsChanged) { + oldProgram.structureIsReused = 1; + newSourceFile.resolvedTypeReferenceDirectiveNames = ts.zipToMap(typesReferenceDirectives, resolutions); + } + else { + newSourceFile.resolvedTypeReferenceDirectiveNames = oldSourceFile.resolvedTypeReferenceDirectiveNames; + } + } + } + if (oldProgram.structureIsReused !== 2) { + return oldProgram.structureIsReused; + } + if (host.hasChangedAutomaticTypeDirectiveNames) { + return oldProgram.structureIsReused = 1; + } + missingFilePaths = oldProgram.getMissingFilePaths(); + for (var _f = 0, newSourceFiles_1 = newSourceFiles; _f < newSourceFiles_1.length; _f++) { + var newSourceFile = newSourceFiles_1[_f]; + var filePath = newSourceFile.path; + addFileToFilesByName(newSourceFile, filePath, newSourceFile.resolvedPath); + if (oldProgram.isSourceFileFromExternalLibrary(oldProgram.getSourceFileByPath(filePath))) { + sourceFilesFoundSearchingNodeModules.set(filePath, true); + } + } + files = newSourceFiles; + fileProcessingDiagnostics = oldProgram.getFileProcessingDiagnostics(); + for (var _g = 0, modifiedSourceFiles_2 = modifiedSourceFiles; _g < modifiedSourceFiles_2.length; _g++) { + var modifiedFile = modifiedSourceFiles_2[_g]; + fileProcessingDiagnostics.reattachFileDiagnostics(modifiedFile.newFile); + } + resolvedTypeReferenceDirectives = oldProgram.getResolvedTypeReferenceDirectives(); + sourceFileToPackageName = oldProgram.sourceFileToPackageName; + redirectTargetsMap = oldProgram.redirectTargetsMap; + return oldProgram.structureIsReused = 2; + } + function getEmitHost(writeFileCallback) { + return __assign({ getPrependNodes: getPrependNodes, + getCanonicalFileName: getCanonicalFileName, getCommonSourceDirectory: program.getCommonSourceDirectory, getCompilerOptions: program.getCompilerOptions, getCurrentDirectory: function () { return currentDirectory; }, getNewLine: function () { return host.getNewLine(); }, getSourceFile: program.getSourceFile, getSourceFileByPath: program.getSourceFileByPath, getSourceFiles: program.getSourceFiles, getLibFileFromReference: program.getLibFileFromReference, isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary, writeFile: writeFileCallback || (function (fileName, data, writeByteOrderMark, onError, sourceFiles) { return host.writeFile(fileName, data, writeByteOrderMark, onError, sourceFiles); }), isEmitBlocked: isEmitBlocked, readFile: function (f) { return host.readFile(f); }, fileExists: function (f) { + var path = toPath(f); + if (getSourceFileByPath(path)) + return true; + if (ts.contains(missingFilePaths, path)) + return false; + return host.fileExists(f); + } }, (host.directoryExists ? { directoryExists: function (f) { return host.directoryExists(f); } } : {}), { useCaseSensitiveFileNames: function () { return host.useCaseSensitiveFileNames(); } }); + } + function getResolvedProjectReferences() { + return resolvedProjectReferences; + } + function getProjectReferences() { + return projectReferences; + } + function getPrependNodes() { + if (!projectReferences) { + return ts.emptyArray; + } + var nodes = []; + for (var i = 0; i < projectReferences.length; i++) { + var ref = projectReferences[i]; + var resolvedRefOpts = resolvedProjectReferences[i].commandLine; + if (ref.prepend && resolvedRefOpts && resolvedRefOpts.options) { + var out = resolvedRefOpts.options.outFile || resolvedRefOpts.options.out; + if (!out) + continue; + var dtsFilename = ts.changeExtension(out, ".d.ts"); + var js = host.readFile(out) || "/* Input file " + out + " was missing */\r\n"; + var jsMapPath = out + ".map"; + var jsMap = host.readFile(jsMapPath); + var dts = host.readFile(dtsFilename) || "/* Input file " + dtsFilename + " was missing */\r\n"; + var dtsMapPath = dtsFilename + ".map"; + var dtsMap = host.readFile(dtsMapPath); + var node = ts.createInputFiles(js, dts, jsMap && jsMapPath, jsMap, dtsMap && dtsMapPath, dtsMap); + nodes.push(node); + } + } + return nodes; + } + function isSourceFileFromExternalLibrary(file) { + return !!sourceFilesFoundSearchingNodeModules.get(file.path); + } + function isSourceFileDefaultLibrary(file) { + if (file.hasNoDefaultLib) { + return true; + } + if (!options.noLib) { + return false; + } + var equalityComparer = host.useCaseSensitiveFileNames() ? ts.equateStringsCaseSensitive : ts.equateStringsCaseInsensitive; + if (!options.lib) { + return equalityComparer(file.fileName, getDefaultLibraryFileName()); + } + else { + return ts.some(options.lib, function (libFileName) { return equalityComparer(file.fileName, ts.combinePaths(defaultLibraryPath, libFileName)); }); + } + } + function getDiagnosticsProducingTypeChecker() { + return diagnosticsProducingTypeChecker || (diagnosticsProducingTypeChecker = ts.createTypeChecker(program, true)); + } + function dropDiagnosticsProducingTypeChecker() { + diagnosticsProducingTypeChecker = undefined; + } + function getTypeChecker() { + return noDiagnosticsTypeChecker || (noDiagnosticsTypeChecker = ts.createTypeChecker(program, false)); + } + function emit(sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles, transformers) { + return runWithCancellationToken(function () { return emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles, transformers); }); + } + function isEmitBlocked(emitFileName) { + return hasEmitBlockingDiagnostics.has(toPath(emitFileName)); + } + function emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles, customTransformers) { + var declarationDiagnostics = []; + if (!emitOnlyDtsFiles) { + if (options.noEmit) { + return { diagnostics: declarationDiagnostics, sourceMaps: undefined, emittedFiles: undefined, emitSkipped: true }; + } + if (options.noEmitOnError) { + var diagnostics = program.getOptionsDiagnostics(cancellationToken).concat(program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken)); + if (diagnostics.length === 0 && ts.getEmitDeclarations(program.getCompilerOptions())) { + declarationDiagnostics = program.getDeclarationDiagnostics(undefined, cancellationToken); + } + if (diagnostics.length > 0 || declarationDiagnostics.length > 0) { + return { + diagnostics: ts.concatenate(diagnostics, declarationDiagnostics), + sourceMaps: undefined, + emittedFiles: undefined, + emitSkipped: true + }; + } + } + } + var emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile, cancellationToken); + ts.performance.mark("beforeEmit"); + var transformers = emitOnlyDtsFiles ? [] : ts.getTransformers(options, customTransformers); + var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile, emitOnlyDtsFiles, transformers, customTransformers && customTransformers.afterDeclarations); + ts.performance.mark("afterEmit"); + ts.performance.measure("Emit", "beforeEmit", "afterEmit"); + return emitResult; + } + function getSourceFile(fileName) { + return getSourceFileByPath(toPath(fileName)); + } + function getSourceFileByPath(path) { + return filesByName.get(path); + } + function getDiagnosticsHelper(sourceFile, getDiagnostics, cancellationToken) { + if (sourceFile) { + return getDiagnostics(sourceFile, cancellationToken); + } + return ts.sortAndDeduplicateDiagnostics(ts.flatMap(program.getSourceFiles(), function (sourceFile) { + if (cancellationToken) { + cancellationToken.throwIfCancellationRequested(); + } + return getDiagnostics(sourceFile, cancellationToken); + })); + } + function getSyntacticDiagnostics(sourceFile, cancellationToken) { + return getDiagnosticsHelper(sourceFile, getSyntacticDiagnosticsForFile, cancellationToken); + } + function getSemanticDiagnostics(sourceFile, cancellationToken) { + return getDiagnosticsHelper(sourceFile, getSemanticDiagnosticsForFile, cancellationToken); + } + function getDeclarationDiagnostics(sourceFile, cancellationToken) { + var options = program.getCompilerOptions(); + if (!sourceFile || options.out || options.outFile) { + return getDeclarationDiagnosticsWorker(sourceFile, cancellationToken); + } + else { + return getDiagnosticsHelper(sourceFile, getDeclarationDiagnosticsForFile, cancellationToken); + } + } + function getSyntacticDiagnosticsForFile(sourceFile) { + if (ts.isSourceFileJS(sourceFile)) { + if (!sourceFile.additionalSyntacticDiagnostics) { + sourceFile.additionalSyntacticDiagnostics = getJSSyntacticDiagnosticsForFile(sourceFile); + } + return ts.concatenate(sourceFile.additionalSyntacticDiagnostics, sourceFile.parseDiagnostics); + } + return sourceFile.parseDiagnostics; + } + function runWithCancellationToken(func) { + try { + return func(); + } + catch (e) { + if (e instanceof ts.OperationCanceledException) { + noDiagnosticsTypeChecker = undefined; + diagnosticsProducingTypeChecker = undefined; + } + throw e; + } + } + function getSemanticDiagnosticsForFile(sourceFile, cancellationToken) { + return getAndCacheDiagnostics(sourceFile, cancellationToken, cachedSemanticDiagnosticsForFile, getSemanticDiagnosticsForFileNoCache); + } + function getSemanticDiagnosticsForFileNoCache(sourceFile, cancellationToken) { + return runWithCancellationToken(function () { + if (ts.skipTypeChecking(sourceFile, options)) { + return ts.emptyArray; + } + var typeChecker = getDiagnosticsProducingTypeChecker(); + ts.Debug.assert(!!sourceFile.bindDiagnostics); + var isCheckJs = ts.isCheckJsEnabledForFile(sourceFile, options); + var includeBindAndCheckDiagnostics = sourceFile.scriptKind === 3 || sourceFile.scriptKind === 4 || + sourceFile.scriptKind === 5 || isCheckJs || sourceFile.scriptKind === 7; + var bindDiagnostics = includeBindAndCheckDiagnostics ? sourceFile.bindDiagnostics : ts.emptyArray; + var checkDiagnostics = includeBindAndCheckDiagnostics ? typeChecker.getDiagnostics(sourceFile, cancellationToken) : ts.emptyArray; + var fileProcessingDiagnosticsInFile = fileProcessingDiagnostics.getDiagnostics(sourceFile.fileName); + var programDiagnosticsInFile = programDiagnostics.getDiagnostics(sourceFile.fileName); + var diagnostics; + for (var _i = 0, _a = [bindDiagnostics, checkDiagnostics, fileProcessingDiagnosticsInFile, programDiagnosticsInFile, isCheckJs ? sourceFile.jsDocDiagnostics : undefined]; _i < _a.length; _i++) { + var diags = _a[_i]; + if (diags) { + for (var _b = 0, diags_1 = diags; _b < diags_1.length; _b++) { + var diag = diags_1[_b]; + if (shouldReportDiagnostic(diag)) { + diagnostics = ts.append(diagnostics, diag); + } + } + } + } + return diagnostics; + }); + } + function getSuggestionDiagnostics(sourceFile, cancellationToken) { + return runWithCancellationToken(function () { + return getDiagnosticsProducingTypeChecker().getSuggestionDiagnostics(sourceFile, cancellationToken); + }); + } + function shouldReportDiagnostic(diagnostic) { + var file = diagnostic.file, start = diagnostic.start; + if (file) { + var lineStarts = ts.getLineStarts(file); + var line = ts.computeLineAndCharacterOfPosition(lineStarts, start).line; + while (line > 0) { + var previousLineText = file.text.slice(lineStarts[line - 1], lineStarts[line]); + var result = ignoreDiagnosticCommentRegEx.exec(previousLineText); + if (!result) { + return true; + } + if (result[3]) { + return false; + } + line--; + } + } + return true; + } + function getJSSyntacticDiagnosticsForFile(sourceFile) { + return runWithCancellationToken(function () { + var diagnostics = []; + var parent = sourceFile; + walk(sourceFile); + return diagnostics; + function walk(node) { + switch (parent.kind) { + case 151: + case 154: + if (parent.questionToken === node) { + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, "?")); + return; + } + case 156: + case 155: + case 157: + case 158: + case 159: + case 196: + case 239: + case 197: + case 237: + if (parent.type === node) { + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.types_can_only_be_used_in_a_ts_file)); + return; + } + } + switch (node.kind) { + case 248: + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.import_can_only_be_used_in_a_ts_file)); + return; + case 254: + if (node.isExportEquals) { + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.export_can_only_be_used_in_a_ts_file)); + return; + } + break; + case 273: + var heritageClause = node; + if (heritageClause.token === 109) { + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.implements_clauses_can_only_be_used_in_a_ts_file)); + return; + } + break; + case 241: + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.interface_declarations_can_only_be_used_in_a_ts_file)); + return; + case 244: + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.module_declarations_can_only_be_used_in_a_ts_file)); + return; + case 242: + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.type_aliases_can_only_be_used_in_a_ts_file)); + return; + case 243: + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.enum_declarations_can_only_be_used_in_a_ts_file)); + return; + case 213: + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.non_null_assertions_can_only_be_used_in_a_ts_file)); + return; + case 212: + diagnostics.push(createDiagnosticForNode(node.type, ts.Diagnostics.type_assertion_expressions_can_only_be_used_in_a_ts_file)); + return; + case 194: + ts.Debug.fail(); + } + var prevParent = parent; + parent = node; + ts.forEachChild(node, walk, walkArray); + parent = prevParent; + } + function walkArray(nodes) { + if (parent.decorators === nodes && !options.experimentalDecorators) { + diagnostics.push(createDiagnosticForNode(parent, ts.Diagnostics.Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_to_remove_this_warning)); + } + switch (parent.kind) { + case 240: + case 156: + case 155: + case 157: + case 158: + case 159: + case 196: + case 239: + case 197: + if (nodes === parent.typeParameters) { + diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.type_parameter_declarations_can_only_be_used_in_a_ts_file)); + return; + } + case 219: + if (nodes === parent.modifiers) { + return checkModifiers(nodes, parent.kind === 219); + } + break; + case 154: + if (nodes === parent.modifiers) { + for (var _i = 0, _a = nodes; _i < _a.length; _i++) { + var modifier = _a[_i]; + if (modifier.kind !== 116) { + diagnostics.push(createDiagnosticForNode(modifier, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, ts.tokenToString(modifier.kind))); + } + } + return; + } + break; + case 151: + if (nodes === parent.modifiers) { + diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.parameter_modifiers_can_only_be_used_in_a_ts_file)); + return; + } + break; + case 191: + case 192: + case 211: + case 261: + case 262: + if (nodes === parent.typeArguments) { + diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.type_arguments_can_only_be_used_in_a_ts_file)); + return; + } + break; + } + for (var _b = 0, nodes_6 = nodes; _b < nodes_6.length; _b++) { + var node = nodes_6[_b]; + walk(node); + } + } + function checkModifiers(modifiers, isConstValid) { + for (var _i = 0, modifiers_1 = modifiers; _i < modifiers_1.length; _i++) { + var modifier = modifiers_1[_i]; + switch (modifier.kind) { + case 77: + if (isConstValid) { + continue; + } + case 115: + case 113: + case 114: + case 133: + case 125: + case 118: + diagnostics.push(createDiagnosticForNode(modifier, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, ts.tokenToString(modifier.kind))); + break; + case 116: + case 85: + case 80: + } + } + } + function createDiagnosticForNodeArray(nodes, message, arg0, arg1, arg2) { + var start = nodes.pos; + return ts.createFileDiagnostic(sourceFile, start, nodes.end - start, message, arg0, arg1, arg2); + } + function createDiagnosticForNode(node, message, arg0, arg1, arg2) { + return ts.createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2); + } + }); + } + function getDeclarationDiagnosticsWorker(sourceFile, cancellationToken) { + return getAndCacheDiagnostics(sourceFile, cancellationToken, cachedDeclarationDiagnosticsForFile, getDeclarationDiagnosticsForFileNoCache); + } + function getDeclarationDiagnosticsForFileNoCache(sourceFile, cancellationToken) { + return runWithCancellationToken(function () { + var resolver = getDiagnosticsProducingTypeChecker().getEmitResolver(sourceFile, cancellationToken); + return ts.getDeclarationDiagnostics(getEmitHost(ts.noop), resolver, sourceFile); + }); + } + function getAndCacheDiagnostics(sourceFile, cancellationToken, cache, getDiagnostics) { + var cachedResult = sourceFile + ? cache.perFile && cache.perFile.get(sourceFile.path) + : cache.allDiagnostics; + if (cachedResult) { + return cachedResult; + } + var result = getDiagnostics(sourceFile, cancellationToken) || ts.emptyArray; + if (sourceFile) { + if (!cache.perFile) { + cache.perFile = ts.createMap(); + } + cache.perFile.set(sourceFile.path, result); + } + else { + cache.allDiagnostics = result; + } + return result; + } + function getDeclarationDiagnosticsForFile(sourceFile, cancellationToken) { + return sourceFile.isDeclarationFile ? [] : getDeclarationDiagnosticsWorker(sourceFile, cancellationToken); + } + function getOptionsDiagnostics() { + return ts.sortAndDeduplicateDiagnostics(ts.concatenate(fileProcessingDiagnostics.getGlobalDiagnostics(), ts.concatenate(programDiagnostics.getGlobalDiagnostics(), getOptionsDiagnosticsOfConfigFile()))); + } + function getOptionsDiagnosticsOfConfigFile() { + if (!options.configFile) { + return ts.emptyArray; + } + var diagnostics = programDiagnostics.getDiagnostics(options.configFile.fileName); + forEachResolvedProjectReference(function (resolvedRef) { + if (resolvedRef) { + diagnostics = ts.concatenate(diagnostics, programDiagnostics.getDiagnostics(resolvedRef.sourceFile.fileName)); + } + }); + return diagnostics; + } + function getGlobalDiagnostics() { + return rootNames.length ? ts.sortAndDeduplicateDiagnostics(getDiagnosticsProducingTypeChecker().getGlobalDiagnostics().slice()) : ts.emptyArray; + } + function getConfigFileParsingDiagnostics() { + return configFileParsingDiagnostics || ts.emptyArray; + } + function processRootFile(fileName, isDefaultLib, ignoreNoDefaultLib) { + processSourceFile(ts.normalizePath(fileName), isDefaultLib, ignoreNoDefaultLib, undefined); + } + function fileReferenceIsEqualTo(a, b) { + return a.fileName === b.fileName; + } + function moduleNameIsEqualTo(a, b) { + return a.kind === 72 + ? b.kind === 72 && a.escapedText === b.escapedText + : b.kind === 10 && a.text === b.text; + } + function collectExternalModuleReferences(file) { + if (file.imports) { + return; + } + var isJavaScriptFile = ts.isSourceFileJS(file); + var isExternalModuleFile = ts.isExternalModule(file); + var imports; + var moduleAugmentations; + var ambientModules; + if (options.importHelpers + && (options.isolatedModules || isExternalModuleFile) + && !file.isDeclarationFile) { + var externalHelpersModuleReference = ts.createLiteral(ts.externalHelpersModuleNameText); + var importDecl = ts.createImportDeclaration(undefined, undefined, undefined, externalHelpersModuleReference); + ts.addEmitFlags(importDecl, 67108864); + externalHelpersModuleReference.parent = importDecl; + importDecl.parent = file; + imports = [externalHelpersModuleReference]; + } + for (var _i = 0, _a = file.statements; _i < _a.length; _i++) { + var node = _a[_i]; + collectModuleReferences(node, false); + } + if ((file.flags & 524288) || isJavaScriptFile) { + collectDynamicImportOrRequireCalls(file); + } + file.imports = imports || ts.emptyArray; + file.moduleAugmentations = moduleAugmentations || ts.emptyArray; + file.ambientModuleNames = ambientModules || ts.emptyArray; + return; + function collectModuleReferences(node, inAmbientModule) { + if (ts.isAnyImportOrReExport(node)) { + var moduleNameExpr = ts.getExternalModuleName(node); + if (moduleNameExpr && ts.isStringLiteral(moduleNameExpr) && moduleNameExpr.text && (!inAmbientModule || !ts.isExternalModuleNameRelative(moduleNameExpr.text))) { + imports = ts.append(imports, moduleNameExpr); + } + } + else if (ts.isModuleDeclaration(node)) { + if (ts.isAmbientModule(node) && (inAmbientModule || ts.hasModifier(node, 2) || file.isDeclarationFile)) { + var nameText = ts.getTextOfIdentifierOrLiteral(node.name); + if (isExternalModuleFile || (inAmbientModule && !ts.isExternalModuleNameRelative(nameText))) { + (moduleAugmentations || (moduleAugmentations = [])).push(node.name); + } + else if (!inAmbientModule) { + if (file.isDeclarationFile) { + (ambientModules || (ambientModules = [])).push(nameText); + } + var body = node.body; + if (body) { + for (var _i = 0, _a = body.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + collectModuleReferences(statement, true); + } + } + } + } + } + } + function collectDynamicImportOrRequireCalls(file) { + var r = /import|require/g; + while (r.exec(file.text) !== null) { + var node = getNodeAtPosition(file, r.lastIndex); + if (ts.isRequireCall(node, true)) { + imports = ts.append(imports, node.arguments[0]); + } + else if (ts.isImportCall(node) && node.arguments.length === 1 && ts.isStringLiteralLike(node.arguments[0])) { + imports = ts.append(imports, node.arguments[0]); + } + else if (ts.isLiteralImportTypeNode(node)) { + imports = ts.append(imports, node.argument.literal); + } + } + } + function getNodeAtPosition(sourceFile, position) { + var current = sourceFile; + var getContainingChild = function (child) { + if (child.pos <= position && (position < child.end || (position === child.end && (child.kind === 1)))) { + return child; + } + }; + while (true) { + var child = isJavaScriptFile && ts.hasJSDocNodes(current) && ts.forEach(current.jsDoc, getContainingChild) || ts.forEachChild(current, getContainingChild); + if (!child) { + return current; + } + current = child; + } + } + } + function getLibFileFromReference(ref) { + var libName = ref.fileName.toLocaleLowerCase(); + var libFileName = ts.libMap.get(libName); + if (libFileName) { + return getSourceFile(ts.combinePaths(defaultLibraryPath, libFileName)); + } + } + function getSourceFileFromReference(referencingFile, ref) { + return getSourceFileFromReferenceWorker(resolveTripleslashReference(ref.fileName, referencingFile.fileName), function (fileName) { return filesByName.get(toPath(fileName)); }); + } + function getSourceFileFromReferenceWorker(fileName, getSourceFile, fail, refFile) { + if (ts.hasExtension(fileName)) { + if (!options.allowNonTsExtensions && !ts.forEach(supportedExtensionsWithJsonIfResolveJsonModule, function (extension) { return ts.fileExtensionIs(host.getCanonicalFileName(fileName), extension); })) { + if (fail) + fail(ts.Diagnostics.File_0_has_unsupported_extension_The_only_supported_extensions_are_1, fileName, "'" + supportedExtensions.join("', '") + "'"); + return undefined; + } + var sourceFile = getSourceFile(fileName); + if (fail) { + if (!sourceFile) { + var redirect = getProjectReferenceRedirect(fileName); + if (redirect) { + fail(ts.Diagnostics.Output_file_0_has_not_been_built_from_source_file_1, redirect, fileName); + } + else { + fail(ts.Diagnostics.File_0_not_found, fileName); + } + } + else if (refFile && host.getCanonicalFileName(fileName) === host.getCanonicalFileName(refFile.fileName)) { + fail(ts.Diagnostics.A_file_cannot_have_a_reference_to_itself); + } + } + return sourceFile; + } + else { + var sourceFileNoExtension = options.allowNonTsExtensions && getSourceFile(fileName); + if (sourceFileNoExtension) + return sourceFileNoExtension; + if (fail && options.allowNonTsExtensions) { + fail(ts.Diagnostics.File_0_not_found, fileName); + return undefined; + } + var sourceFileWithAddedExtension = ts.forEach(supportedExtensions, function (extension) { return getSourceFile(fileName + extension); }); + if (fail && !sourceFileWithAddedExtension) + fail(ts.Diagnostics.File_0_not_found, fileName + ".ts"); + return sourceFileWithAddedExtension; + } + } + function processSourceFile(fileName, isDefaultLib, ignoreNoDefaultLib, packageId, refFile, refPos, refEnd) { + getSourceFileFromReferenceWorker(fileName, function (fileName) { return findSourceFile(fileName, toPath(fileName), isDefaultLib, ignoreNoDefaultLib, refFile, refPos, refEnd, packageId); }, function (diagnostic) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + fileProcessingDiagnostics.add(refFile !== undefined && refEnd !== undefined && refPos !== undefined + ? ts.createFileDiagnostic.apply(void 0, [refFile, refPos, refEnd - refPos, diagnostic].concat(args)) : ts.createCompilerDiagnostic.apply(void 0, [diagnostic].concat(args))); + }, refFile); + } + function reportFileNamesDifferOnlyInCasingError(fileName, existingFileName, refFile, refPos, refEnd) { + if (refFile !== undefined && refPos !== undefined && refEnd !== undefined) { + fileProcessingDiagnostics.add(ts.createFileDiagnostic(refFile, refPos, refEnd - refPos, ts.Diagnostics.File_name_0_differs_from_already_included_file_name_1_only_in_casing, fileName, existingFileName)); + } + else { + fileProcessingDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_name_0_differs_from_already_included_file_name_1_only_in_casing, fileName, existingFileName)); + } + } + function createRedirectSourceFile(redirectTarget, unredirected, fileName, path, resolvedPath, originalFileName) { + var redirect = Object.create(redirectTarget); + redirect.fileName = fileName; + redirect.path = path; + redirect.resolvedPath = resolvedPath; + redirect.originalFileName = originalFileName; + redirect.redirectInfo = { redirectTarget: redirectTarget, unredirected: unredirected }; + sourceFilesFoundSearchingNodeModules.set(path, currentNodeModulesDepth > 0); + Object.defineProperties(redirect, { + id: { + get: function () { return this.redirectInfo.redirectTarget.id; }, + set: function (value) { this.redirectInfo.redirectTarget.id = value; }, + }, + symbol: { + get: function () { return this.redirectInfo.redirectTarget.symbol; }, + set: function (value) { this.redirectInfo.redirectTarget.symbol = value; }, + }, + }); + return redirect; + } + function findSourceFile(fileName, path, isDefaultLib, ignoreNoDefaultLib, refFile, refPos, refEnd, packageId) { + var originalFileName = fileName; + if (filesByName.has(path)) { + var file_1 = filesByName.get(path); + if (file_1 && options.forceConsistentCasingInFileNames) { + var inputName = fileName; + var checkedName = file_1.fileName; + var isRedirect = toPath(checkedName) !== toPath(inputName); + if (isRedirect) { + inputName = getProjectReferenceRedirect(fileName) || fileName; + } + if (ts.getNormalizedAbsolutePath(checkedName, currentDirectory) !== ts.getNormalizedAbsolutePath(inputName, currentDirectory)) { + reportFileNamesDifferOnlyInCasingError(inputName, checkedName, refFile, refPos, refEnd); + } + } + if (file_1 && sourceFilesFoundSearchingNodeModules.get(file_1.path) && currentNodeModulesDepth === 0) { + sourceFilesFoundSearchingNodeModules.set(file_1.path, false); + if (!options.noResolve) { + processReferencedFiles(file_1, isDefaultLib); + processTypeReferenceDirectives(file_1); + } + processLibReferenceDirectives(file_1); + modulesWithElidedImports.set(file_1.path, false); + processImportedModules(file_1); + } + else if (file_1 && modulesWithElidedImports.get(file_1.path)) { + if (currentNodeModulesDepth < maxNodeModuleJsDepth) { + modulesWithElidedImports.set(file_1.path, false); + processImportedModules(file_1); + } + } + return file_1; + } + var redirectedPath; + if (refFile) { + var redirect = getProjectReferenceRedirect(fileName); + if (redirect) { + (refFile.redirectedReferences || (refFile.redirectedReferences = [])).push(fileName); + fileName = redirect; + redirectedPath = toPath(redirect); + } + } + var file = host.getSourceFile(fileName, options.target, function (hostErrorMessage) { + if (refFile !== undefined && refPos !== undefined && refEnd !== undefined) { + fileProcessingDiagnostics.add(ts.createFileDiagnostic(refFile, refPos, refEnd - refPos, ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, hostErrorMessage)); + } + else { + fileProcessingDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, hostErrorMessage)); + } + }, shouldCreateNewSourceFile); + if (packageId) { + var packageIdKey = ts.packageIdToString(packageId); + var fileFromPackageId = packageIdToSourceFile.get(packageIdKey); + if (fileFromPackageId) { + var dupFile = createRedirectSourceFile(fileFromPackageId, file, fileName, path, toPath(fileName), originalFileName); + redirectTargetsMap.add(fileFromPackageId.path, fileName); + addFileToFilesByName(dupFile, path, redirectedPath); + sourceFileToPackageName.set(path, packageId.name); + processingOtherFiles.push(dupFile); + return dupFile; + } + else if (file) { + packageIdToSourceFile.set(packageIdKey, file); + sourceFileToPackageName.set(path, packageId.name); + } + } + addFileToFilesByName(file, path, redirectedPath); + if (file) { + sourceFilesFoundSearchingNodeModules.set(path, currentNodeModulesDepth > 0); + file.path = path; + file.resolvedPath = toPath(fileName); + file.originalFileName = originalFileName; + if (host.useCaseSensitiveFileNames()) { + var pathLowerCase = path.toLowerCase(); + var existingFile = filesByNameIgnoreCase.get(pathLowerCase); + if (existingFile) { + reportFileNamesDifferOnlyInCasingError(fileName, existingFile.fileName, refFile, refPos, refEnd); + } + else { + filesByNameIgnoreCase.set(pathLowerCase, file); + } + } + skipDefaultLib = skipDefaultLib || (file.hasNoDefaultLib && !ignoreNoDefaultLib); + if (!options.noResolve) { + processReferencedFiles(file, isDefaultLib); + processTypeReferenceDirectives(file); + } + processLibReferenceDirectives(file); + processImportedModules(file); + if (isDefaultLib) { + processingDefaultLibFiles.push(file); + } + else { + processingOtherFiles.push(file); + } + } + return file; + } + function addFileToFilesByName(file, path, redirectedPath) { + filesByName.set(path, file); + if (redirectedPath) { + filesByName.set(redirectedPath, file); + } + } + function getProjectReferenceRedirect(fileName) { + if (!resolvedProjectReferences || !resolvedProjectReferences.length || ts.fileExtensionIs(fileName, ".d.ts") || !ts.fileExtensionIsOneOf(fileName, ts.supportedTSExtensions)) { + return undefined; + } + var referencedProject = getResolvedProjectReferenceToRedirect(fileName); + if (!referencedProject) { + return undefined; + } + var out = referencedProject.commandLine.options.outFile || referencedProject.commandLine.options.out; + return out ? + ts.changeExtension(out, ".d.ts") : + ts.getOutputDeclarationFileName(fileName, referencedProject.commandLine); + } + function getResolvedProjectReferenceToRedirect(fileName) { + if (mapFromFileToProjectReferenceRedirects === undefined) { + mapFromFileToProjectReferenceRedirects = ts.createMap(); + forEachResolvedProjectReference(function (referencedProject, referenceProjectPath) { + if (referencedProject && + toPath(options.configFilePath) !== referenceProjectPath) { + referencedProject.commandLine.fileNames.forEach(function (f) { + return mapFromFileToProjectReferenceRedirects.set(toPath(f), referenceProjectPath); + }); + } + }); + } + var referencedProjectPath = mapFromFileToProjectReferenceRedirects.get(toPath(fileName)); + return referencedProjectPath && getResolvedProjectReferenceByPath(referencedProjectPath); + } + function forEachResolvedProjectReference(cb) { + return forEachProjectReference(projectReferences, resolvedProjectReferences, function (resolvedRef, index, parent) { + var ref = (parent ? parent.commandLine.projectReferences : projectReferences)[index]; + var resolvedRefPath = toPath(resolveProjectReferencePath(ref)); + return cb(resolvedRef, resolvedRefPath); + }); + } + function forEachProjectReference(projectReferences, resolvedProjectReferences, cbResolvedRef, cbRef) { + var seenResolvedRefs; + return worker(projectReferences, resolvedProjectReferences, undefined, cbResolvedRef, cbRef); + function worker(projectReferences, resolvedProjectReferences, parent, cbResolvedRef, cbRef) { + if (cbRef) { + var result = cbRef(projectReferences, parent); + if (result) { + return result; + } + } + return ts.forEach(resolvedProjectReferences, function (resolvedRef, index) { + if (ts.contains(seenResolvedRefs, resolvedRef)) { + return undefined; + } + var result = cbResolvedRef(resolvedRef, index, parent); + if (result) { + return result; + } + if (!resolvedRef) + return undefined; + (seenResolvedRefs || (seenResolvedRefs = [])).push(resolvedRef); + return worker(resolvedRef.commandLine.projectReferences, resolvedRef.references, resolvedRef, cbResolvedRef, cbRef); + }); + } + } + function getResolvedProjectReferenceByPath(projectReferencePath) { + if (!projectReferenceRedirects) { + return undefined; + } + return projectReferenceRedirects.get(projectReferencePath) || undefined; + } + function processReferencedFiles(file, isDefaultLib) { + ts.forEach(file.referencedFiles, function (ref) { + var referencedFileName = resolveTripleslashReference(ref.fileName, file.originalFileName); + processSourceFile(referencedFileName, isDefaultLib, false, undefined, file, ref.pos, ref.end); + }); + } + function processTypeReferenceDirectives(file) { + var typeDirectives = ts.map(file.typeReferenceDirectives, function (ref) { return ref.fileName.toLocaleLowerCase(); }); + if (!typeDirectives) { + return; + } + var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeDirectives, file.originalFileName, getResolvedProjectReferenceToRedirect(file.originalFileName)); + for (var i = 0; i < typeDirectives.length; i++) { + var ref = file.typeReferenceDirectives[i]; + var resolvedTypeReferenceDirective = resolutions[i]; + var fileName = ref.fileName.toLocaleLowerCase(); + ts.setResolvedTypeReferenceDirective(file, fileName, resolvedTypeReferenceDirective); + processTypeReferenceDirective(fileName, resolvedTypeReferenceDirective, file, ref.pos, ref.end); + } + } + function processTypeReferenceDirective(typeReferenceDirective, resolvedTypeReferenceDirective, refFile, refPos, refEnd) { + var previousResolution = resolvedTypeReferenceDirectives.get(typeReferenceDirective); + if (previousResolution && previousResolution.primary) { + return; + } + var saveResolution = true; + if (resolvedTypeReferenceDirective) { + if (resolvedTypeReferenceDirective.isExternalLibraryImport) + currentNodeModulesDepth++; + if (resolvedTypeReferenceDirective.primary) { + processSourceFile(resolvedTypeReferenceDirective.resolvedFileName, false, false, resolvedTypeReferenceDirective.packageId, refFile, refPos, refEnd); + } + else { + if (previousResolution) { + if (resolvedTypeReferenceDirective.resolvedFileName !== previousResolution.resolvedFileName) { + var otherFileText = host.readFile(resolvedTypeReferenceDirective.resolvedFileName); + if (otherFileText !== getSourceFile(previousResolution.resolvedFileName).text) { + fileProcessingDiagnostics.add(createDiagnostic(refFile, refPos, refEnd, ts.Diagnostics.Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict, typeReferenceDirective, resolvedTypeReferenceDirective.resolvedFileName, previousResolution.resolvedFileName)); + } + } + saveResolution = false; + } + else { + processSourceFile(resolvedTypeReferenceDirective.resolvedFileName, false, false, resolvedTypeReferenceDirective.packageId, refFile, refPos, refEnd); + } + } + if (resolvedTypeReferenceDirective.isExternalLibraryImport) + currentNodeModulesDepth--; + } + else { + fileProcessingDiagnostics.add(createDiagnostic(refFile, refPos, refEnd, ts.Diagnostics.Cannot_find_type_definition_file_for_0, typeReferenceDirective)); + } + if (saveResolution) { + resolvedTypeReferenceDirectives.set(typeReferenceDirective, resolvedTypeReferenceDirective); + } + } + function processLibReferenceDirectives(file) { + ts.forEach(file.libReferenceDirectives, function (libReference) { + var libName = libReference.fileName.toLocaleLowerCase(); + var libFileName = ts.libMap.get(libName); + if (libFileName) { + processRootFile(ts.combinePaths(defaultLibraryPath, libFileName), true, true); + } + else { + var unqualifiedLibName = ts.removeSuffix(ts.removePrefix(libName, "lib."), ".d.ts"); + var suggestion = ts.getSpellingSuggestion(unqualifiedLibName, ts.libs, ts.identity); + var message = suggestion ? ts.Diagnostics.Cannot_find_lib_definition_for_0_Did_you_mean_1 : ts.Diagnostics.Cannot_find_lib_definition_for_0; + fileProcessingDiagnostics.add(createDiagnostic(file, libReference.pos, libReference.end, message, libName, suggestion)); + } + }); + } + function createDiagnostic(refFile, refPos, refEnd, message) { + var args = []; + for (var _i = 4; _i < arguments.length; _i++) { + args[_i - 4] = arguments[_i]; + } + if (refFile === undefined || refPos === undefined || refEnd === undefined) { + return ts.createCompilerDiagnostic.apply(void 0, [message].concat(args)); + } + else { + return ts.createFileDiagnostic.apply(void 0, [refFile, refPos, refEnd - refPos, message].concat(args)); + } + } + function getCanonicalFileName(fileName) { + return host.getCanonicalFileName(fileName); + } + function processImportedModules(file) { + collectExternalModuleReferences(file); + if (file.imports.length || file.moduleAugmentations.length) { + var moduleNames = getModuleNames(file); + var resolutions = resolveModuleNamesReusingOldState(moduleNames, ts.getNormalizedAbsolutePath(file.originalFileName, currentDirectory), file); + ts.Debug.assert(resolutions.length === moduleNames.length); + for (var i = 0; i < moduleNames.length; i++) { + var resolution = resolutions[i]; + ts.setResolvedModule(file, moduleNames[i], resolution); + if (!resolution) { + continue; + } + var isFromNodeModulesSearch = resolution.isExternalLibraryImport; + var isJsFile = !ts.resolutionExtensionIsTSOrJson(resolution.extension); + var isJsFileFromNodeModules = isFromNodeModulesSearch && isJsFile; + var resolvedFileName = resolution.resolvedFileName; + if (isFromNodeModulesSearch) { + currentNodeModulesDepth++; + } + var elideImport = isJsFileFromNodeModules && currentNodeModulesDepth > maxNodeModuleJsDepth; + var shouldAddFile = resolvedFileName + && !getResolutionDiagnostic(options, resolution) + && !options.noResolve + && i < file.imports.length + && !elideImport + && !(isJsFile && !options.allowJs) + && (ts.isInJSFile(file.imports[i]) || !(file.imports[i].flags & 2097152)); + if (elideImport) { + modulesWithElidedImports.set(file.path, true); + } + else if (shouldAddFile) { + var path = toPath(resolvedFileName); + var pos = ts.skipTrivia(file.text, file.imports[i].pos); + findSourceFile(resolvedFileName, path, false, false, file, pos, file.imports[i].end, resolution.packageId); + } + if (isFromNodeModulesSearch) { + currentNodeModulesDepth--; + } + } + } + else { + file.resolvedModules = undefined; + } + } + function computeCommonSourceDirectory(sourceFiles) { + var fileNames = ts.mapDefined(sourceFiles, function (file) { return file.isDeclarationFile ? undefined : file.fileName; }); + return computeCommonSourceDirectoryOfFilenames(fileNames, currentDirectory, getCanonicalFileName); + } + function checkSourceFilesBelongToPath(sourceFiles, rootDirectory) { + var allFilesBelongToPath = true; + var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory)); + for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) { + var sourceFile = sourceFiles_2[_i]; + if (!sourceFile.isDeclarationFile) { + var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); + if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, sourceFile.fileName, rootDirectory)); + allFilesBelongToPath = false; + } + } + } + return allFilesBelongToPath; + } + function parseProjectReferenceConfigFile(ref) { + if (!projectReferenceRedirects) { + projectReferenceRedirects = ts.createMap(); + } + var refPath = resolveProjectReferencePath(ref); + var sourceFilePath = toPath(refPath); + var fromCache = projectReferenceRedirects.get(sourceFilePath); + if (fromCache !== undefined) { + return fromCache || undefined; + } + var basePath = ts.getNormalizedAbsolutePath(ts.getDirectoryPath(refPath), host.getCurrentDirectory()); + var sourceFile = host.getSourceFile(refPath, 100); + addFileToFilesByName(sourceFile, sourceFilePath, undefined); + if (sourceFile === undefined) { + projectReferenceRedirects.set(sourceFilePath, false); + return undefined; + } + sourceFile.path = sourceFilePath; + sourceFile.resolvedPath = sourceFilePath; + sourceFile.originalFileName = refPath; + var commandLine = ts.parseJsonSourceFileConfigFileContent(sourceFile, configParsingHost, basePath, undefined, refPath); + var resolvedRef = { commandLine: commandLine, sourceFile: sourceFile }; + projectReferenceRedirects.set(sourceFilePath, resolvedRef); + if (commandLine.projectReferences) { + resolvedRef.references = commandLine.projectReferences.map(parseProjectReferenceConfigFile); + } + return resolvedRef; + } + function verifyCompilerOptions() { + if (options.strictPropertyInitialization && !ts.getStrictOptionValue(options, "strictNullChecks")) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "strictPropertyInitialization", "strictNullChecks"); + } + if (options.isolatedModules) { + if (ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, getEmitDeclarationOptionName(options), "isolatedModules"); + } + if (options.noEmitOnError) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmitOnError", "isolatedModules"); + } + if (options.out) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "out", "isolatedModules"); + } + if (options.outFile) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "outFile", "isolatedModules"); + } + } + if (options.inlineSourceMap) { + if (options.sourceMap) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "sourceMap", "inlineSourceMap"); + } + if (options.mapRoot) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "mapRoot", "inlineSourceMap"); + } + } + if (options.paths && options.baseUrl === undefined) { + createDiagnosticForOptionName(ts.Diagnostics.Option_paths_cannot_be_used_without_specifying_baseUrl_option, "paths"); + } + if (options.composite) { + if (options.declaration === false) { + createDiagnosticForOptionName(ts.Diagnostics.Composite_projects_may_not_disable_declaration_emit, "declaration"); + } + } + verifyProjectReferences(); + if (options.composite) { + var sourceFiles = files.filter(function (f) { return !f.isDeclarationFile; }); + if (rootNames.length < sourceFiles.length) { + var normalizedRootNames = rootNames.map(function (r) { return ts.normalizePath(r).toLowerCase(); }); + for (var _i = 0, _a = sourceFiles.map(function (f) { return ts.normalizePath(f.path).toLowerCase(); }); _i < _a.length; _i++) { + var file = _a[_i]; + if (normalizedRootNames.indexOf(file) === -1) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern, file)); + } + } + } + } + if (options.paths) { + for (var key in options.paths) { + if (!ts.hasProperty(options.paths, key)) { + continue; + } + if (!ts.hasZeroOrOneAsteriskCharacter(key)) { + createDiagnosticForOptionPaths(true, key, ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, key); + } + if (ts.isArray(options.paths[key])) { + var len = options.paths[key].length; + if (len === 0) { + createDiagnosticForOptionPaths(false, key, ts.Diagnostics.Substitutions_for_pattern_0_shouldn_t_be_an_empty_array, key); + } + for (var i = 0; i < len; i++) { + var subst = options.paths[key][i]; + var typeOfSubst = typeof subst; + if (typeOfSubst === "string") { + if (!ts.hasZeroOrOneAsteriskCharacter(subst)) { + createDiagnosticForOptionPathKeyValue(key, i, ts.Diagnostics.Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character, subst, key); + } + } + else { + createDiagnosticForOptionPathKeyValue(key, i, ts.Diagnostics.Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2, subst, key, typeOfSubst); + } + } + } + else { + createDiagnosticForOptionPaths(false, key, ts.Diagnostics.Substitutions_for_pattern_0_should_be_an_array, key); + } + } + } + if (!options.sourceMap && !options.inlineSourceMap) { + if (options.inlineSources) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided, "inlineSources"); + } + if (options.sourceRoot) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided, "sourceRoot"); + } + } + if (options.out && options.outFile) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "out", "outFile"); + } + if (options.mapRoot && !(options.sourceMap || options.declarationMap)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "mapRoot", "sourceMap", "declarationMap"); + } + if (options.declarationDir) { + if (!ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "declarationDir", "declaration", "composite"); + } + if (options.out || options.outFile) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "declarationDir", options.out ? "out" : "outFile"); + } + } + if (options.declarationMap && !ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "declarationMap", "declaration", "composite"); + } + if (options.lib && options.noLib) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "lib", "noLib"); + } + if (options.noImplicitUseStrict && ts.getStrictOptionValue(options, "alwaysStrict")) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noImplicitUseStrict", "alwaysStrict"); + } + var languageVersion = options.target || 0; + var outFile = options.outFile || options.out; + var firstNonAmbientExternalModuleSourceFile = ts.find(files, function (f) { return ts.isExternalModule(f) && !f.isDeclarationFile; }); + if (options.isolatedModules) { + if (options.module === ts.ModuleKind.None && languageVersion < 2) { + createDiagnosticForOptionName(ts.Diagnostics.Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher, "isolatedModules", "target"); + } + var firstNonExternalModuleSourceFile = ts.find(files, function (f) { return !ts.isExternalModule(f) && !f.isDeclarationFile && f.scriptKind !== 6; }); + if (firstNonExternalModuleSourceFile) { + var span = ts.getErrorSpanForNode(firstNonExternalModuleSourceFile, firstNonExternalModuleSourceFile); + programDiagnostics.add(ts.createFileDiagnostic(firstNonExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided)); + } + } + else if (firstNonAmbientExternalModuleSourceFile && languageVersion < 2 && options.module === ts.ModuleKind.None) { + var span = ts.getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, firstNonAmbientExternalModuleSourceFile.externalModuleIndicator); + programDiagnostics.add(ts.createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_use_imports_exports_or_module_augmentations_when_module_is_none)); + } + if (outFile && !options.emitDeclarationOnly) { + if (options.module && !(options.module === ts.ModuleKind.AMD || options.module === ts.ModuleKind.System)) { + createDiagnosticForOptionName(ts.Diagnostics.Only_amd_and_system_modules_are_supported_alongside_0, options.out ? "out" : "outFile", "module"); + } + else if (options.module === undefined && firstNonAmbientExternalModuleSourceFile) { + var span = ts.getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, firstNonAmbientExternalModuleSourceFile.externalModuleIndicator); + programDiagnostics.add(ts.createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system, options.out ? "out" : "outFile")); + } + } + if (options.resolveJsonModule) { + if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { + createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy, "resolveJsonModule"); + } + else if (!ts.hasJsonModuleEmitEnabled(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_esNext, "resolveJsonModule", "module"); + } + } + if (options.outDir || + options.sourceRoot || + options.mapRoot) { + var dir = getCommonSourceDirectory(); + if (options.outDir && dir === "" && files.some(function (file) { return ts.getRootLength(file.fileName) > 1; })) { + createDiagnosticForOptionName(ts.Diagnostics.Cannot_find_the_common_subdirectory_path_for_the_input_files, "outDir"); + } + } + if (!options.noEmit && options.allowJs && ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "allowJs", getEmitDeclarationOptionName(options)); + } + if (options.checkJs && !options.allowJs) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "checkJs", "allowJs")); + } + if (options.emitDeclarationOnly) { + if (!ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "emitDeclarationOnly", "declaration", "composite"); + } + if (options.noEmit) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "emitDeclarationOnly", "noEmit"); + } + } + if (options.emitDecoratorMetadata && + !options.experimentalDecorators) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDecoratorMetadata", "experimentalDecorators"); + } + if (options.jsxFactory) { + if (options.reactNamespace) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "reactNamespace", "jsxFactory"); + } + if (!ts.parseIsolatedEntityName(options.jsxFactory, languageVersion)) { + createOptionValueDiagnostic("jsxFactory", ts.Diagnostics.Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name, options.jsxFactory); + } + } + else if (options.reactNamespace && !ts.isIdentifierText(options.reactNamespace, languageVersion)) { + createOptionValueDiagnostic("reactNamespace", ts.Diagnostics.Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier, options.reactNamespace); + } + if (!options.noEmit && !options.suppressOutputPathCheck) { + var emitHost = getEmitHost(); + var emitFilesSeen_1 = ts.createMap(); + ts.forEachEmittedFile(emitHost, function (emitFileNames) { + if (!options.emitDeclarationOnly) { + verifyEmitFilePath(emitFileNames.jsFilePath, emitFilesSeen_1); + } + verifyEmitFilePath(emitFileNames.declarationFilePath, emitFilesSeen_1); + }); + } + function verifyEmitFilePath(emitFileName, emitFilesSeen) { + if (emitFileName) { + var emitFilePath = toPath(emitFileName); + if (filesByName.has(emitFilePath)) { + var chain_2; + if (!options.configFilePath) { + chain_2 = ts.chainDiagnosticMessages(undefined, ts.Diagnostics.Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig); + } + chain_2 = ts.chainDiagnosticMessages(chain_2, ts.Diagnostics.Cannot_write_file_0_because_it_would_overwrite_input_file, emitFileName); + blockEmittingOfFile(emitFileName, ts.createCompilerDiagnosticFromMessageChain(chain_2)); + } + var emitFileKey = !host.useCaseSensitiveFileNames() ? emitFilePath.toLocaleLowerCase() : emitFilePath; + if (emitFilesSeen.has(emitFileKey)) { + blockEmittingOfFile(emitFileName, ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files, emitFileName)); + } + else { + emitFilesSeen.set(emitFileKey, true); + } + } + } + } + function verifyProjectReferences() { + forEachProjectReference(projectReferences, resolvedProjectReferences, function (resolvedRef, index, parent) { + var ref = (parent ? parent.commandLine.projectReferences : projectReferences)[index]; + var parentFile = parent && parent.sourceFile; + if (!resolvedRef) { + createDiagnosticForReference(parentFile, index, ts.Diagnostics.File_0_not_found, ref.path); + return; + } + var options = resolvedRef.commandLine.options; + if (!options.composite) { + var inputs = parent ? parent.commandLine.fileNames : rootNames; + if (inputs.length) { + createDiagnosticForReference(parentFile, index, ts.Diagnostics.Referenced_project_0_must_have_setting_composite_Colon_true, ref.path); + } + } + if (ref.prepend) { + var out = options.outFile || options.out; + if (out) { + if (!host.fileExists(out)) { + createDiagnosticForReference(parentFile, index, ts.Diagnostics.Output_file_0_from_project_1_does_not_exist, out, ref.path); + } + } + else { + createDiagnosticForReference(parentFile, index, ts.Diagnostics.Cannot_prepend_project_0_because_it_does_not_have_outFile_set, ref.path); + } + } + }); + } + function createDiagnosticForOptionPathKeyValue(key, valueIndex, message, arg0, arg1, arg2) { + var needCompilerDiagnostic = true; + var pathsSyntax = getOptionPathsSyntax(); + for (var _i = 0, pathsSyntax_1 = pathsSyntax; _i < pathsSyntax_1.length; _i++) { + var pathProp = pathsSyntax_1[_i]; + if (ts.isObjectLiteralExpression(pathProp.initializer)) { + for (var _a = 0, _b = ts.getPropertyAssignment(pathProp.initializer, key); _a < _b.length; _a++) { + var keyProps = _b[_a]; + var initializer = keyProps.initializer; + if (ts.isArrayLiteralExpression(initializer) && initializer.elements.length > valueIndex) { + programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(options.configFile, initializer.elements[valueIndex], message, arg0, arg1, arg2)); + needCompilerDiagnostic = false; + } + } + } + } + if (needCompilerDiagnostic) { + programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1, arg2)); + } + } + function createDiagnosticForOptionPaths(onKey, key, message, arg0) { + var needCompilerDiagnostic = true; + var pathsSyntax = getOptionPathsSyntax(); + for (var _i = 0, pathsSyntax_2 = pathsSyntax; _i < pathsSyntax_2.length; _i++) { + var pathProp = pathsSyntax_2[_i]; + if (ts.isObjectLiteralExpression(pathProp.initializer) && + createOptionDiagnosticInObjectLiteralSyntax(pathProp.initializer, onKey, key, undefined, message, arg0)) { + needCompilerDiagnostic = false; + } + } + if (needCompilerDiagnostic) { + programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0)); + } + } + function getOptionsSyntaxByName(name) { + var compilerOptionsObjectLiteralSyntax = getCompilerOptionsObjectLiteralSyntax(); + if (compilerOptionsObjectLiteralSyntax) { + return ts.getPropertyAssignment(compilerOptionsObjectLiteralSyntax, name); + } + return undefined; + } + function getOptionPathsSyntax() { + return getOptionsSyntaxByName("paths") || ts.emptyArray; + } + function createDiagnosticForOptionName(message, option1, option2, option3) { + createDiagnosticForOption(true, option1, option2, message, option1, option2, option3); + } + function createOptionValueDiagnostic(option1, message, arg0) { + createDiagnosticForOption(false, option1, undefined, message, arg0); + } + function createDiagnosticForReference(sourceFile, index, message, arg0, arg1) { + var referencesSyntax = ts.firstDefined(ts.getTsConfigPropArray(sourceFile || options.configFile, "references"), function (property) { return ts.isArrayLiteralExpression(property.initializer) ? property.initializer : undefined; }); + if (referencesSyntax && referencesSyntax.elements.length > index) { + programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(sourceFile || options.configFile, referencesSyntax.elements[index], message, arg0, arg1)); + } + else { + programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1)); + } + } + function createDiagnosticForOption(onKey, option1, option2, message, arg0, arg1, arg2) { + var compilerOptionsObjectLiteralSyntax = getCompilerOptionsObjectLiteralSyntax(); + var needCompilerDiagnostic = !compilerOptionsObjectLiteralSyntax || + !createOptionDiagnosticInObjectLiteralSyntax(compilerOptionsObjectLiteralSyntax, onKey, option1, option2, message, arg0, arg1, arg2); + if (needCompilerDiagnostic) { + programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1, arg2)); + } + } + function getCompilerOptionsObjectLiteralSyntax() { + if (_compilerOptionsObjectLiteralSyntax === undefined) { + _compilerOptionsObjectLiteralSyntax = null; + var jsonObjectLiteral = ts.getTsConfigObjectLiteralExpression(options.configFile); + if (jsonObjectLiteral) { + for (var _i = 0, _a = ts.getPropertyAssignment(jsonObjectLiteral, "compilerOptions"); _i < _a.length; _i++) { + var prop = _a[_i]; + if (ts.isObjectLiteralExpression(prop.initializer)) { + _compilerOptionsObjectLiteralSyntax = prop.initializer; + break; + } + } + } + } + return _compilerOptionsObjectLiteralSyntax; + } + function createOptionDiagnosticInObjectLiteralSyntax(objectLiteral, onKey, key1, key2, message, arg0, arg1, arg2) { + var props = ts.getPropertyAssignment(objectLiteral, key1, key2); + for (var _i = 0, props_2 = props; _i < props_2.length; _i++) { + var prop = props_2[_i]; + programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(options.configFile, onKey ? prop.name : prop.initializer, message, arg0, arg1, arg2)); + } + return !!props.length; + } + function blockEmittingOfFile(emitFileName, diag) { + hasEmitBlockingDiagnostics.set(toPath(emitFileName), true); + programDiagnostics.add(diag); + } + function isEmittedFile(file) { + if (options.noEmit) { + return false; + } + var filePath = toPath(file); + if (getSourceFileByPath(filePath)) { + return false; + } + var out = options.outFile || options.out; + if (out) { + return isSameFile(filePath, out) || isSameFile(filePath, ts.removeFileExtension(out) + ".d.ts"); + } + if (options.declarationDir && ts.containsPath(options.declarationDir, filePath, currentDirectory, !host.useCaseSensitiveFileNames())) { + return true; + } + if (options.outDir) { + return ts.containsPath(options.outDir, filePath, currentDirectory, !host.useCaseSensitiveFileNames()); + } + if (ts.fileExtensionIsOneOf(filePath, ts.supportedJSExtensions) || ts.fileExtensionIs(filePath, ".d.ts")) { + var filePathWithoutExtension = ts.removeFileExtension(filePath); + return !!getSourceFileByPath((filePathWithoutExtension + ".ts")) || + !!getSourceFileByPath((filePathWithoutExtension + ".tsx")); + } + return false; + } + function isSameFile(file1, file2) { + return ts.comparePaths(file1, file2, currentDirectory, !host.useCaseSensitiveFileNames()) === 0; + } + } + ts.createProgram = createProgram; + function parseConfigHostFromCompilerHost(host) { + return { + fileExists: function (f) { return host.fileExists(f); }, + readDirectory: function (root, extensions, excludes, includes, depth) { + ts.Debug.assertDefined(host.readDirectory, "'CompilerHost.readDirectory' must be implemented to correctly process 'projectReferences'"); + return host.readDirectory(root, extensions, excludes, includes, depth); + }, + readFile: function (f) { return host.readFile(f); }, + useCaseSensitiveFileNames: host.useCaseSensitiveFileNames(), + getCurrentDirectory: function () { return host.getCurrentDirectory(); }, + onUnRecoverableConfigFileDiagnostic: function () { return undefined; }, + trace: host.trace ? function (s) { return host.trace(s); } : undefined + }; + } + ts.parseConfigHostFromCompilerHost = parseConfigHostFromCompilerHost; + function resolveProjectReferencePath(hostOrRef, ref) { + var passedInRef = ref ? ref : hostOrRef; + return ts.resolveConfigFileProjectName(passedInRef.path); + } + ts.resolveProjectReferencePath = resolveProjectReferencePath; + function getEmitDeclarationOptionName(options) { + return options.declaration ? "declaration" : "composite"; + } + function getResolutionDiagnostic(options, _a) { + var extension = _a.extension; + switch (extension) { + case ".ts": + case ".d.ts": + return undefined; + case ".tsx": + return needJsx(); + case ".jsx": + return needJsx() || needAllowJs(); + case ".js": + return needAllowJs(); + case ".json": + return needResolveJsonModule(); + } + function needJsx() { + return options.jsx ? undefined : ts.Diagnostics.Module_0_was_resolved_to_1_but_jsx_is_not_set; + } + function needAllowJs() { + return options.allowJs || !ts.getStrictOptionValue(options, "noImplicitAny") ? undefined : ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type; + } + function needResolveJsonModule() { + return options.resolveJsonModule ? undefined : ts.Diagnostics.Module_0_was_resolved_to_1_but_resolveJsonModule_is_not_used; + } + } + ts.getResolutionDiagnostic = getResolutionDiagnostic; + function getModuleNames(_a) { + var imports = _a.imports, moduleAugmentations = _a.moduleAugmentations; + var res = imports.map(function (i) { return i.text; }); + for (var _i = 0, moduleAugmentations_1 = moduleAugmentations; _i < moduleAugmentations_1.length; _i++) { + var aug = moduleAugmentations_1[_i]; + if (aug.kind === 10) { + res.push(aug.text); + } + } + return res; + } +})(ts || (ts = {})); +var ts; +(function (ts) { + function getFileEmitOutput(program, sourceFile, emitOnlyDtsFiles, cancellationToken, customTransformers) { + var outputFiles = []; + var emitResult = program.emit(sourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); + return { outputFiles: outputFiles, emitSkipped: emitResult.emitSkipped, exportedModulesFromDeclarationEmit: emitResult.exportedModulesFromDeclarationEmit }; + function writeFile(fileName, text, writeByteOrderMark) { + outputFiles.push({ name: fileName, writeByteOrderMark: writeByteOrderMark, text: text }); + } + } + ts.getFileEmitOutput = getFileEmitOutput; +})(ts || (ts = {})); +(function (ts) { + var BuilderState; + (function (BuilderState) { + function getReferencedFileFromImportedModuleSymbol(symbol) { + if (symbol.declarations && symbol.declarations[0]) { + var declarationSourceFile = ts.getSourceFileOfNode(symbol.declarations[0]); + return declarationSourceFile && declarationSourceFile.resolvedPath; + } + } + function getReferencedFileFromImportLiteral(checker, importName) { + var symbol = checker.getSymbolAtLocation(importName); + return symbol && getReferencedFileFromImportedModuleSymbol(symbol); + } + function getReferencedFileFromFileName(program, fileName, sourceFileDirectory, getCanonicalFileName) { + return ts.toPath(program.getProjectReferenceRedirect(fileName) || fileName, sourceFileDirectory, getCanonicalFileName); + } + function getReferencedFiles(program, sourceFile, getCanonicalFileName) { + var referencedFiles; + if (sourceFile.imports && sourceFile.imports.length > 0) { + var checker = program.getTypeChecker(); + for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { + var importName = _a[_i]; + var declarationSourceFilePath = getReferencedFileFromImportLiteral(checker, importName); + if (declarationSourceFilePath) { + addReferencedFile(declarationSourceFilePath); + } + } + } + var sourceFileDirectory = ts.getDirectoryPath(sourceFile.path); + if (sourceFile.referencedFiles && sourceFile.referencedFiles.length > 0) { + for (var _b = 0, _c = sourceFile.referencedFiles; _b < _c.length; _b++) { + var referencedFile = _c[_b]; + var referencedPath = getReferencedFileFromFileName(program, referencedFile.fileName, sourceFileDirectory, getCanonicalFileName); + addReferencedFile(referencedPath); + } + } + if (sourceFile.resolvedTypeReferenceDirectiveNames) { + sourceFile.resolvedTypeReferenceDirectiveNames.forEach(function (resolvedTypeReferenceDirective) { + if (!resolvedTypeReferenceDirective) { + return; + } + var fileName = resolvedTypeReferenceDirective.resolvedFileName; + var typeFilePath = getReferencedFileFromFileName(program, fileName, sourceFileDirectory, getCanonicalFileName); + addReferencedFile(typeFilePath); + }); + } + if (sourceFile.moduleAugmentations.length) { + var checker = program.getTypeChecker(); + for (var _d = 0, _e = sourceFile.moduleAugmentations; _d < _e.length; _d++) { + var moduleName = _e[_d]; + if (!ts.isStringLiteral(moduleName)) { + continue; + } + var symbol = checker.getSymbolAtLocation(moduleName); + if (!symbol) { + continue; + } + addReferenceFromAmbientModule(symbol); + } + } + for (var _f = 0, _g = program.getTypeChecker().getAmbientModules(); _f < _g.length; _f++) { + var ambientModule = _g[_f]; + if (ambientModule.declarations.length > 1) { + addReferenceFromAmbientModule(ambientModule); + } + } + return referencedFiles; + function addReferenceFromAmbientModule(symbol) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + var declarationSourceFile = ts.getSourceFileOfNode(declaration); + if (declarationSourceFile && + declarationSourceFile !== sourceFile) { + addReferencedFile(declarationSourceFile.resolvedPath); + } + } + } + function addReferencedFile(referencedPath) { + if (!referencedFiles) { + referencedFiles = ts.createMap(); + } + referencedFiles.set(referencedPath, true); + } + } + function canReuseOldState(newReferencedMap, oldState) { + return oldState && !oldState.referencedMap === !newReferencedMap; + } + BuilderState.canReuseOldState = canReuseOldState; + function create(newProgram, getCanonicalFileName, oldState) { + var fileInfos = ts.createMap(); + var referencedMap = newProgram.getCompilerOptions().module !== ts.ModuleKind.None ? ts.createMap() : undefined; + var exportedModulesMap = referencedMap ? ts.createMap() : undefined; + var hasCalledUpdateShapeSignature = ts.createMap(); + var useOldState = canReuseOldState(referencedMap, oldState); + for (var _i = 0, _a = newProgram.getSourceFiles(); _i < _a.length; _i++) { + var sourceFile = _a[_i]; + var version_1 = sourceFile.version; + var oldInfo = useOldState ? oldState.fileInfos.get(sourceFile.path) : undefined; + if (referencedMap) { + var newReferences = getReferencedFiles(newProgram, sourceFile, getCanonicalFileName); + if (newReferences) { + referencedMap.set(sourceFile.path, newReferences); + } + if (useOldState) { + var exportedModules = oldState.exportedModulesMap.get(sourceFile.path); + if (exportedModules) { + exportedModulesMap.set(sourceFile.path, exportedModules); + } + } + } + fileInfos.set(sourceFile.path, { version: version_1, signature: oldInfo && oldInfo.signature }); + } + return { + fileInfos: fileInfos, + referencedMap: referencedMap, + exportedModulesMap: exportedModulesMap, + hasCalledUpdateShapeSignature: hasCalledUpdateShapeSignature, + allFilesExcludingDefaultLibraryFile: undefined, + allFileNames: undefined + }; + } + BuilderState.create = create; + function getFilesAffectedBy(state, programOfThisState, path, cancellationToken, computeHash, cacheToUpdateSignature, exportedModulesMapCache) { + var signatureCache = cacheToUpdateSignature || ts.createMap(); + var sourceFile = programOfThisState.getSourceFileByPath(path); + if (!sourceFile) { + return ts.emptyArray; + } + if (!updateShapeSignature(state, programOfThisState, sourceFile, signatureCache, cancellationToken, computeHash, exportedModulesMapCache)) { + return [sourceFile]; + } + var result = (state.referencedMap ? getFilesAffectedByUpdatedShapeWhenModuleEmit : getFilesAffectedByUpdatedShapeWhenNonModuleEmit)(state, programOfThisState, sourceFile, signatureCache, cancellationToken, computeHash, exportedModulesMapCache); + if (!cacheToUpdateSignature) { + updateSignaturesFromCache(state, signatureCache); + } + return result; + } + BuilderState.getFilesAffectedBy = getFilesAffectedBy; + function updateSignaturesFromCache(state, signatureCache) { + signatureCache.forEach(function (signature, path) { + state.fileInfos.get(path).signature = signature; + state.hasCalledUpdateShapeSignature.set(path, true); + }); + } + BuilderState.updateSignaturesFromCache = updateSignaturesFromCache; + function updateShapeSignature(state, programOfThisState, sourceFile, cacheToUpdateSignature, cancellationToken, computeHash, exportedModulesMapCache) { + ts.Debug.assert(!!sourceFile); + ts.Debug.assert(!exportedModulesMapCache || !!state.exportedModulesMap, "Compute visible to outside map only if visibleToOutsideReferencedMap present in the state"); + if (state.hasCalledUpdateShapeSignature.has(sourceFile.path) || cacheToUpdateSignature.has(sourceFile.path)) { + return false; + } + var info = state.fileInfos.get(sourceFile.path); + if (!info) + return ts.Debug.fail(); + var prevSignature = info.signature; + var latestSignature; + if (sourceFile.isDeclarationFile) { + latestSignature = sourceFile.version; + if (exportedModulesMapCache && latestSignature !== prevSignature) { + var references = state.referencedMap ? state.referencedMap.get(sourceFile.path) : undefined; + exportedModulesMapCache.set(sourceFile.path, references || false); + } + } + else { + var emitOutput = ts.getFileEmitOutput(programOfThisState, sourceFile, true, cancellationToken); + if (emitOutput.outputFiles && emitOutput.outputFiles.length > 0) { + latestSignature = computeHash(emitOutput.outputFiles[0].text); + if (exportedModulesMapCache && latestSignature !== prevSignature) { + updateExportedModules(sourceFile, emitOutput.exportedModulesFromDeclarationEmit, exportedModulesMapCache); + } + } + else { + latestSignature = prevSignature; + } + } + cacheToUpdateSignature.set(sourceFile.path, latestSignature); + return !prevSignature || latestSignature !== prevSignature; + } + function updateExportedModules(sourceFile, exportedModulesFromDeclarationEmit, exportedModulesMapCache) { + if (!exportedModulesFromDeclarationEmit) { + exportedModulesMapCache.set(sourceFile.path, false); + return; + } + var exportedModules; + exportedModulesFromDeclarationEmit.forEach(function (symbol) { return addExportedModule(getReferencedFileFromImportedModuleSymbol(symbol)); }); + exportedModulesMapCache.set(sourceFile.path, exportedModules || false); + function addExportedModule(exportedModulePath) { + if (exportedModulePath) { + if (!exportedModules) { + exportedModules = ts.createMap(); + } + exportedModules.set(exportedModulePath, true); + } + } + } + function updateExportedFilesMapFromCache(state, exportedModulesMapCache) { + if (exportedModulesMapCache) { + ts.Debug.assert(!!state.exportedModulesMap); + exportedModulesMapCache.forEach(function (exportedModules, path) { + if (exportedModules) { + state.exportedModulesMap.set(path, exportedModules); + } + else { + state.exportedModulesMap.delete(path); + } + }); + } + } + BuilderState.updateExportedFilesMapFromCache = updateExportedFilesMapFromCache; + function getAllDependencies(state, programOfThisState, sourceFile) { + var _a; + var compilerOptions = programOfThisState.getCompilerOptions(); + if (compilerOptions.outFile || compilerOptions.out) { + return getAllFileNames(state, programOfThisState); + } + if (!state.referencedMap || isFileAffectingGlobalScope(sourceFile)) { + return getAllFileNames(state, programOfThisState); + } + var seenMap = ts.createMap(); + var queue = [sourceFile.path]; + while (queue.length) { + var path = queue.pop(); + if (!seenMap.has(path)) { + seenMap.set(path, true); + var references = state.referencedMap.get(path); + if (references) { + var iterator = references.keys(); + for (var _b = iterator.next(), value = _b.value, done = _b.done; !done; _a = iterator.next(), value = _a.value, done = _a.done, _a) { + queue.push(value); + } + } + } + } + return ts.arrayFrom(ts.mapDefinedIterator(seenMap.keys(), function (path) { + var file = programOfThisState.getSourceFileByPath(path); + return file ? file.fileName : path; + })); + } + BuilderState.getAllDependencies = getAllDependencies; + function getAllFileNames(state, programOfThisState) { + if (!state.allFileNames) { + var sourceFiles = programOfThisState.getSourceFiles(); + state.allFileNames = sourceFiles === ts.emptyArray ? ts.emptyArray : sourceFiles.map(function (file) { return file.fileName; }); + } + return state.allFileNames; + } + function getReferencedByPaths(state, referencedFilePath) { + return ts.arrayFrom(ts.mapDefinedIterator(state.referencedMap.entries(), function (_a) { + var filePath = _a[0], referencesInFile = _a[1]; + return referencesInFile.has(referencedFilePath) ? filePath : undefined; + })); + } + function containsOnlyAmbientModules(sourceFile) { + for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + if (!ts.isModuleWithStringLiteralName(statement)) { + return false; + } + } + return true; + } + function containsGlobalScopeAugmentation(sourceFile) { + return ts.some(sourceFile.moduleAugmentations, function (augmentation) { return ts.isGlobalScopeAugmentation(augmentation.parent); }); + } + function isFileAffectingGlobalScope(sourceFile) { + return containsGlobalScopeAugmentation(sourceFile) || + !ts.isExternalModule(sourceFile) && !containsOnlyAmbientModules(sourceFile); + } + function getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, firstSourceFile) { + if (state.allFilesExcludingDefaultLibraryFile) { + return state.allFilesExcludingDefaultLibraryFile; + } + var result; + addSourceFile(firstSourceFile); + for (var _i = 0, _a = programOfThisState.getSourceFiles(); _i < _a.length; _i++) { + var sourceFile = _a[_i]; + if (sourceFile !== firstSourceFile) { + addSourceFile(sourceFile); + } + } + state.allFilesExcludingDefaultLibraryFile = result || ts.emptyArray; + return state.allFilesExcludingDefaultLibraryFile; + function addSourceFile(sourceFile) { + if (!programOfThisState.isSourceFileDefaultLibrary(sourceFile)) { + (result || (result = [])).push(sourceFile); + } + } + } + function getFilesAffectedByUpdatedShapeWhenNonModuleEmit(state, programOfThisState, sourceFileWithUpdatedShape) { + var compilerOptions = programOfThisState.getCompilerOptions(); + if (compilerOptions && (compilerOptions.out || compilerOptions.outFile)) { + return [sourceFileWithUpdatedShape]; + } + return getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, sourceFileWithUpdatedShape); + } + function getFilesAffectedByUpdatedShapeWhenModuleEmit(state, programOfThisState, sourceFileWithUpdatedShape, cacheToUpdateSignature, cancellationToken, computeHash, exportedModulesMapCache) { + if (isFileAffectingGlobalScope(sourceFileWithUpdatedShape)) { + return getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, sourceFileWithUpdatedShape); + } + var compilerOptions = programOfThisState.getCompilerOptions(); + if (compilerOptions && (compilerOptions.isolatedModules || compilerOptions.out || compilerOptions.outFile)) { + return [sourceFileWithUpdatedShape]; + } + var seenFileNamesMap = ts.createMap(); + seenFileNamesMap.set(sourceFileWithUpdatedShape.path, sourceFileWithUpdatedShape); + var queue = getReferencedByPaths(state, sourceFileWithUpdatedShape.path); + while (queue.length > 0) { + var currentPath = queue.pop(); + if (!seenFileNamesMap.has(currentPath)) { + var currentSourceFile = programOfThisState.getSourceFileByPath(currentPath); + seenFileNamesMap.set(currentPath, currentSourceFile); + if (currentSourceFile && updateShapeSignature(state, programOfThisState, currentSourceFile, cacheToUpdateSignature, cancellationToken, computeHash, exportedModulesMapCache)) { + queue.push.apply(queue, getReferencedByPaths(state, currentPath)); + } + } + } + return ts.arrayFrom(ts.mapDefinedIterator(seenFileNamesMap.values(), function (value) { return value; })); + } + })(BuilderState = ts.BuilderState || (ts.BuilderState = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + function hasSameKeys(map1, map2) { + return map1 === map2 || map1 !== undefined && map2 !== undefined && map1.size === map2.size && !ts.forEachKey(map1, function (key) { return !map2.has(key); }); + } + function createBuilderProgramState(newProgram, getCanonicalFileName, oldState) { + var state = ts.BuilderState.create(newProgram, getCanonicalFileName, oldState); + state.program = newProgram; + var compilerOptions = newProgram.getCompilerOptions(); + if (!compilerOptions.outFile && !compilerOptions.out) { + state.semanticDiagnosticsPerFile = ts.createMap(); + } + state.changedFilesSet = ts.createMap(); + var useOldState = ts.BuilderState.canReuseOldState(state.referencedMap, oldState); + var oldCompilerOptions = useOldState ? oldState.program.getCompilerOptions() : undefined; + var canCopySemanticDiagnostics = useOldState && oldState.semanticDiagnosticsPerFile && !!state.semanticDiagnosticsPerFile && + !ts.compilerOptionsAffectSemanticDiagnostics(compilerOptions, oldCompilerOptions); + if (useOldState) { + if (!oldState.currentChangedFilePath) { + ts.Debug.assert(!oldState.affectedFiles && (!oldState.currentAffectedFilesSignatures || !oldState.currentAffectedFilesSignatures.size), "Cannot reuse if only few affected files of currentChangedFile were iterated"); + } + if (canCopySemanticDiagnostics) { + ts.Debug.assert(!ts.forEachKey(oldState.changedFilesSet, function (path) { return oldState.semanticDiagnosticsPerFile.has(path); }), "Semantic diagnostics shouldnt be available for changed files"); + } + ts.copyEntries(oldState.changedFilesSet, state.changedFilesSet); + } + var referencedMap = state.referencedMap; + var oldReferencedMap = useOldState ? oldState.referencedMap : undefined; + var copyDeclarationFileDiagnostics = canCopySemanticDiagnostics && !compilerOptions.skipLibCheck === !oldCompilerOptions.skipLibCheck; + var copyLibFileDiagnostics = copyDeclarationFileDiagnostics && !compilerOptions.skipDefaultLibCheck === !oldCompilerOptions.skipDefaultLibCheck; + state.fileInfos.forEach(function (info, sourceFilePath) { + var oldInfo; + var newReferences; + if (!useOldState || + !(oldInfo = oldState.fileInfos.get(sourceFilePath)) || + oldInfo.version !== info.version || + !hasSameKeys(newReferences = referencedMap && referencedMap.get(sourceFilePath), oldReferencedMap && oldReferencedMap.get(sourceFilePath)) || + newReferences && ts.forEachKey(newReferences, function (path) { return !state.fileInfos.has(path) && oldState.fileInfos.has(path); })) { + state.changedFilesSet.set(sourceFilePath, true); + } + else if (canCopySemanticDiagnostics) { + var sourceFile = state.program.getSourceFileByPath(sourceFilePath); + if (sourceFile.isDeclarationFile && !copyDeclarationFileDiagnostics) { + return; + } + if (sourceFile.hasNoDefaultLib && !copyLibFileDiagnostics) { + return; + } + var diagnostics = oldState.semanticDiagnosticsPerFile.get(sourceFilePath); + if (diagnostics) { + state.semanticDiagnosticsPerFile.set(sourceFilePath, diagnostics); + if (!state.semanticDiagnosticsFromOldState) { + state.semanticDiagnosticsFromOldState = ts.createMap(); + } + state.semanticDiagnosticsFromOldState.set(sourceFilePath, true); + } + } + }); + return state; + } + function assertSourceFileOkWithoutNextAffectedCall(state, sourceFile) { + ts.Debug.assert(!sourceFile || !state.affectedFiles || state.affectedFiles[state.affectedFilesIndex - 1] !== sourceFile || !state.semanticDiagnosticsPerFile.has(sourceFile.path)); + } + function getNextAffectedFile(state, cancellationToken, computeHash) { + while (true) { + var affectedFiles = state.affectedFiles; + if (affectedFiles) { + var seenAffectedFiles = state.seenAffectedFiles; + var affectedFilesIndex = state.affectedFilesIndex; + while (affectedFilesIndex < affectedFiles.length) { + var affectedFile = affectedFiles[affectedFilesIndex]; + if (!seenAffectedFiles.has(affectedFile.path)) { + state.affectedFilesIndex = affectedFilesIndex; + cleanSemanticDiagnosticsOfAffectedFile(state, affectedFile); + return affectedFile; + } + seenAffectedFiles.set(affectedFile.path, true); + affectedFilesIndex++; + } + state.changedFilesSet.delete(state.currentChangedFilePath); + state.currentChangedFilePath = undefined; + ts.BuilderState.updateSignaturesFromCache(state, state.currentAffectedFilesSignatures); + state.currentAffectedFilesSignatures.clear(); + ts.BuilderState.updateExportedFilesMapFromCache(state, state.currentAffectedFilesExportedModulesMap); + state.affectedFiles = undefined; + } + var nextKey = state.changedFilesSet.keys().next(); + if (nextKey.done) { + return undefined; + } + var compilerOptions = state.program.getCompilerOptions(); + if (compilerOptions.outFile || compilerOptions.out) { + ts.Debug.assert(!state.semanticDiagnosticsPerFile); + return state.program; + } + state.currentAffectedFilesSignatures = state.currentAffectedFilesSignatures || ts.createMap(); + if (state.exportedModulesMap) { + state.currentAffectedFilesExportedModulesMap = state.currentAffectedFilesExportedModulesMap || ts.createMap(); + } + state.affectedFiles = ts.BuilderState.getFilesAffectedBy(state, state.program, nextKey.value, cancellationToken, computeHash, state.currentAffectedFilesSignatures, state.currentAffectedFilesExportedModulesMap); + state.currentChangedFilePath = nextKey.value; + state.affectedFilesIndex = 0; + state.seenAffectedFiles = state.seenAffectedFiles || ts.createMap(); + } + } + function cleanSemanticDiagnosticsOfAffectedFile(state, affectedFile) { + if (removeSemanticDiagnosticsOf(state, affectedFile.path)) { + return; + } + if (state.allFilesExcludingDefaultLibraryFile === state.affectedFiles && !state.cleanedDiagnosticsOfLibFiles) { + state.cleanedDiagnosticsOfLibFiles = true; + var options_2 = state.program.getCompilerOptions(); + if (ts.forEach(state.program.getSourceFiles(), function (f) { + return state.program.isSourceFileDefaultLibrary(f) && + !ts.skipTypeChecking(f, options_2) && + removeSemanticDiagnosticsOf(state, f.path); + })) { + return; + } + } + if (!state.exportedModulesMap || state.affectedFiles.length === 1 || !state.changedFilesSet.has(affectedFile.path)) { + return; + } + ts.Debug.assert(!!state.currentAffectedFilesExportedModulesMap); + var seenFileAndExportsOfFile = ts.createMap(); + if (ts.forEachEntry(state.currentAffectedFilesExportedModulesMap, function (exportedModules, exportedFromPath) { + return exportedModules && + exportedModules.has(affectedFile.path) && + removeSemanticDiagnosticsOfFilesReferencingPath(state, exportedFromPath, seenFileAndExportsOfFile); + })) { + return; + } + ts.forEachEntry(state.exportedModulesMap, function (exportedModules, exportedFromPath) { + return !state.currentAffectedFilesExportedModulesMap.has(exportedFromPath) && + exportedModules.has(affectedFile.path) && + removeSemanticDiagnosticsOfFilesReferencingPath(state, exportedFromPath, seenFileAndExportsOfFile); + }); + } + function removeSemanticDiagnosticsOfFilesReferencingPath(state, referencedPath, seenFileAndExportsOfFile) { + return ts.forEachEntry(state.referencedMap, function (referencesInFile, filePath) { + return referencesInFile.has(referencedPath) && removeSemanticDiagnosticsOfFileAndExportsOfFile(state, filePath, seenFileAndExportsOfFile); + }); + } + function removeSemanticDiagnosticsOfFileAndExportsOfFile(state, filePath, seenFileAndExportsOfFile) { + if (!ts.addToSeen(seenFileAndExportsOfFile, filePath)) { + return false; + } + if (removeSemanticDiagnosticsOf(state, filePath)) { + return true; + } + ts.Debug.assert(!!state.currentAffectedFilesExportedModulesMap); + if (ts.forEachEntry(state.currentAffectedFilesExportedModulesMap, function (exportedModules, exportedFromPath) { + return exportedModules && + exportedModules.has(filePath) && + removeSemanticDiagnosticsOfFileAndExportsOfFile(state, exportedFromPath, seenFileAndExportsOfFile); + })) { + return true; + } + return !!ts.forEachEntry(state.exportedModulesMap, function (exportedModules, exportedFromPath) { + return !state.currentAffectedFilesExportedModulesMap.has(exportedFromPath) && + exportedModules.has(filePath) && + removeSemanticDiagnosticsOfFileAndExportsOfFile(state, exportedFromPath, seenFileAndExportsOfFile); + }); + } + function removeSemanticDiagnosticsOf(state, path) { + if (!state.semanticDiagnosticsFromOldState) { + return true; + } + state.semanticDiagnosticsFromOldState.delete(path); + state.semanticDiagnosticsPerFile.delete(path); + return !state.semanticDiagnosticsFromOldState.size; + } + function doneWithAffectedFile(state, affected) { + if (affected === state.program) { + state.changedFilesSet.clear(); + } + else { + state.seenAffectedFiles.set(affected.path, true); + state.affectedFilesIndex++; + } + } + function toAffectedFileResult(state, result, affected) { + doneWithAffectedFile(state, affected); + return { result: result, affected: affected }; + } + function getSemanticDiagnosticsOfFile(state, sourceFile, cancellationToken) { + var path = sourceFile.path; + var cachedDiagnostics = state.semanticDiagnosticsPerFile.get(path); + if (cachedDiagnostics) { + return cachedDiagnostics; + } + var diagnostics = state.program.getSemanticDiagnostics(sourceFile, cancellationToken); + state.semanticDiagnosticsPerFile.set(path, diagnostics); + return diagnostics; + } + var BuilderProgramKind; + (function (BuilderProgramKind) { + BuilderProgramKind[BuilderProgramKind["SemanticDiagnosticsBuilderProgram"] = 0] = "SemanticDiagnosticsBuilderProgram"; + BuilderProgramKind[BuilderProgramKind["EmitAndSemanticDiagnosticsBuilderProgram"] = 1] = "EmitAndSemanticDiagnosticsBuilderProgram"; + })(BuilderProgramKind = ts.BuilderProgramKind || (ts.BuilderProgramKind = {})); + function getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { + var host; + var newProgram; + var oldProgram; + if (newProgramOrRootNames === undefined) { + ts.Debug.assert(hostOrOptions === undefined); + host = oldProgramOrHost; + oldProgram = configFileParsingDiagnosticsOrOldProgram; + ts.Debug.assert(!!oldProgram); + newProgram = oldProgram.getProgram(); + } + else if (ts.isArray(newProgramOrRootNames)) { + oldProgram = configFileParsingDiagnosticsOrOldProgram; + newProgram = ts.createProgram({ + rootNames: newProgramOrRootNames, + options: hostOrOptions, + host: oldProgramOrHost, + oldProgram: oldProgram && oldProgram.getProgram(), + configFileParsingDiagnostics: configFileParsingDiagnostics, + projectReferences: projectReferences + }); + host = oldProgramOrHost; + } + else { + newProgram = newProgramOrRootNames; + host = hostOrOptions; + oldProgram = oldProgramOrHost; + configFileParsingDiagnostics = configFileParsingDiagnosticsOrOldProgram; + } + return { host: host, newProgram: newProgram, oldProgram: oldProgram, configFileParsingDiagnostics: configFileParsingDiagnostics || ts.emptyArray }; + } + ts.getBuilderCreationParameters = getBuilderCreationParameters; + function createBuilderProgram(kind, _a) { + var newProgram = _a.newProgram, host = _a.host, oldProgram = _a.oldProgram, configFileParsingDiagnostics = _a.configFileParsingDiagnostics; + var oldState = oldProgram && oldProgram.getState(); + if (oldState && newProgram === oldState.program && configFileParsingDiagnostics === newProgram.getConfigFileParsingDiagnostics()) { + newProgram = undefined; + oldState = undefined; + return oldProgram; + } + var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames()); + var computeHash = host.createHash || ts.identity; + var state = createBuilderProgramState(newProgram, getCanonicalFileName, oldState); + newProgram = undefined; + oldProgram = undefined; + oldState = undefined; + var result = { + getState: function () { return state; }, + getProgram: function () { return state.program; }, + getCompilerOptions: function () { return state.program.getCompilerOptions(); }, + getSourceFile: function (fileName) { return state.program.getSourceFile(fileName); }, + getSourceFiles: function () { return state.program.getSourceFiles(); }, + getOptionsDiagnostics: function (cancellationToken) { return state.program.getOptionsDiagnostics(cancellationToken); }, + getGlobalDiagnostics: function (cancellationToken) { return state.program.getGlobalDiagnostics(cancellationToken); }, + getConfigFileParsingDiagnostics: function () { return configFileParsingDiagnostics || state.program.getConfigFileParsingDiagnostics(); }, + getSyntacticDiagnostics: function (sourceFile, cancellationToken) { return state.program.getSyntacticDiagnostics(sourceFile, cancellationToken); }, + getSemanticDiagnostics: getSemanticDiagnostics, + emit: emit, + getAllDependencies: function (sourceFile) { return ts.BuilderState.getAllDependencies(state, state.program, sourceFile); }, + getCurrentDirectory: function () { return state.program.getCurrentDirectory(); } + }; + if (kind === BuilderProgramKind.SemanticDiagnosticsBuilderProgram) { + result.getSemanticDiagnosticsOfNextAffectedFile = getSemanticDiagnosticsOfNextAffectedFile; + } + else if (kind === BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram) { + result.emitNextAffectedFile = emitNextAffectedFile; + } + else { + ts.notImplemented(); + } + return result; + function emitNextAffectedFile(writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) { + var affected = getNextAffectedFile(state, cancellationToken, computeHash); + if (!affected) { + return undefined; + } + return toAffectedFileResult(state, state.program.emit(affected === state.program ? undefined : affected, writeFile || host.writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers), affected); + } + function emit(targetSourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) { + if (kind === BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram) { + assertSourceFileOkWithoutNextAffectedCall(state, targetSourceFile); + if (!targetSourceFile) { + var sourceMaps = []; + var emitSkipped = false; + var diagnostics = void 0; + var emittedFiles = []; + var affectedEmitResult = void 0; + while (affectedEmitResult = emitNextAffectedFile(writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers)) { + emitSkipped = emitSkipped || affectedEmitResult.result.emitSkipped; + diagnostics = ts.addRange(diagnostics, affectedEmitResult.result.diagnostics); + emittedFiles = ts.addRange(emittedFiles, affectedEmitResult.result.emittedFiles); + sourceMaps = ts.addRange(sourceMaps, affectedEmitResult.result.sourceMaps); + } + return { + emitSkipped: emitSkipped, + diagnostics: diagnostics || ts.emptyArray, + emittedFiles: emittedFiles, + sourceMaps: sourceMaps + }; + } + } + return state.program.emit(targetSourceFile, writeFile || host.writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); + } + function getSemanticDiagnosticsOfNextAffectedFile(cancellationToken, ignoreSourceFile) { + while (true) { + var affected = getNextAffectedFile(state, cancellationToken, computeHash); + if (!affected) { + return undefined; + } + else if (affected === state.program) { + return toAffectedFileResult(state, state.program.getSemanticDiagnostics(undefined, cancellationToken), affected); + } + if (ignoreSourceFile && ignoreSourceFile(affected)) { + doneWithAffectedFile(state, affected); + continue; + } + return toAffectedFileResult(state, getSemanticDiagnosticsOfFile(state, affected, cancellationToken), affected); + } + } + function getSemanticDiagnostics(sourceFile, cancellationToken) { + assertSourceFileOkWithoutNextAffectedCall(state, sourceFile); + var compilerOptions = state.program.getCompilerOptions(); + if (compilerOptions.outFile || compilerOptions.out) { + ts.Debug.assert(!state.semanticDiagnosticsPerFile); + return state.program.getSemanticDiagnostics(sourceFile, cancellationToken); + } + if (sourceFile) { + return getSemanticDiagnosticsOfFile(state, sourceFile, cancellationToken); + } + if (kind === BuilderProgramKind.SemanticDiagnosticsBuilderProgram) { + var affected = void 0; + while (affected = getNextAffectedFile(state, cancellationToken, computeHash)) { + doneWithAffectedFile(state, affected); + } + } + var diagnostics; + for (var _i = 0, _a = state.program.getSourceFiles(); _i < _a.length; _i++) { + var sourceFile_2 = _a[_i]; + diagnostics = ts.addRange(diagnostics, getSemanticDiagnosticsOfFile(state, sourceFile_2, cancellationToken)); + } + return diagnostics || ts.emptyArray; + } + } + ts.createBuilderProgram = createBuilderProgram; +})(ts || (ts = {})); +(function (ts) { + function createSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { + return ts.createBuilderProgram(ts.BuilderProgramKind.SemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences)); + } + ts.createSemanticDiagnosticsBuilderProgram = createSemanticDiagnosticsBuilderProgram; + function createEmitAndSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { + return ts.createBuilderProgram(ts.BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences)); + } + ts.createEmitAndSemanticDiagnosticsBuilderProgram = createEmitAndSemanticDiagnosticsBuilderProgram; + function createAbstractBuilder(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { + var program = ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences).newProgram; + return { + getProgram: function () { return program; }, + getState: ts.notImplemented, + getCompilerOptions: ts.notImplemented, + getSourceFile: ts.notImplemented, + getSourceFiles: ts.notImplemented, + getOptionsDiagnostics: ts.notImplemented, + getGlobalDiagnostics: ts.notImplemented, + getConfigFileParsingDiagnostics: ts.notImplemented, + getSyntacticDiagnostics: ts.notImplemented, + getSemanticDiagnostics: ts.notImplemented, + emit: ts.notImplemented, + getAllDependencies: ts.notImplemented, + getCurrentDirectory: ts.notImplemented + }; + } + ts.createAbstractBuilder = createAbstractBuilder; +})(ts || (ts = {})); +var ts; +(function (ts) { + function isPathInNodeModulesStartingWithDot(path) { + return ts.stringContains(path, "/node_modules/."); + } + ts.isPathInNodeModulesStartingWithDot = isPathInNodeModulesStartingWithDot; + ts.maxNumberOfFilesToIterateForInvalidation = 256; + function createResolutionCache(resolutionHost, rootDirForResolution, logChangesWhenResolvingModule) { + var filesWithChangedSetOfUnresolvedImports; + var filesWithInvalidatedResolutions; + var filesWithInvalidatedNonRelativeUnresolvedImports; + var allFilesHaveInvalidatedResolution = false; + var nonRelativeExternalModuleResolutions = ts.createMultiMap(); + var getCurrentDirectory = ts.memoize(function () { return resolutionHost.getCurrentDirectory(); }); + var cachedDirectoryStructureHost = resolutionHost.getCachedDirectoryStructureHost(); + var resolvedModuleNames = ts.createMap(); + var perDirectoryResolvedModuleNames = ts.createCacheWithRedirects(); + var nonRelativeModuleNameCache = ts.createCacheWithRedirects(); + var moduleResolutionCache = ts.createModuleResolutionCacheWithMaps(perDirectoryResolvedModuleNames, nonRelativeModuleNameCache, getCurrentDirectory(), resolutionHost.getCanonicalFileName); + var resolvedTypeReferenceDirectives = ts.createMap(); + var perDirectoryResolvedTypeReferenceDirectives = ts.createCacheWithRedirects(); + var failedLookupDefaultExtensions = [".ts", ".tsx", ".js", ".jsx", ".json"]; + var customFailedLookupPaths = ts.createMap(); + var directoryWatchesOfFailedLookups = ts.createMap(); + var rootDir = rootDirForResolution && ts.removeTrailingDirectorySeparator(ts.getNormalizedAbsolutePath(rootDirForResolution, getCurrentDirectory())); + var rootPath = (rootDir && resolutionHost.toPath(rootDir)); + var typeRootsWatches = ts.createMap(); + return { + startRecordingFilesWithChangedResolutions: startRecordingFilesWithChangedResolutions, + finishRecordingFilesWithChangedResolutions: finishRecordingFilesWithChangedResolutions, + startCachingPerDirectoryResolution: clearPerDirectoryResolutions, + finishCachingPerDirectoryResolution: finishCachingPerDirectoryResolution, + resolveModuleNames: resolveModuleNames, + getResolvedModuleWithFailedLookupLocationsFromCache: getResolvedModuleWithFailedLookupLocationsFromCache, + resolveTypeReferenceDirectives: resolveTypeReferenceDirectives, + removeResolutionsFromProjectReferenceRedirects: removeResolutionsFromProjectReferenceRedirects, + removeResolutionsOfFile: removeResolutionsOfFile, + invalidateResolutionOfFile: invalidateResolutionOfFile, + setFilesWithInvalidatedNonRelativeUnresolvedImports: setFilesWithInvalidatedNonRelativeUnresolvedImports, + createHasInvalidatedResolution: createHasInvalidatedResolution, + updateTypeRootsWatch: updateTypeRootsWatch, + closeTypeRootsWatch: closeTypeRootsWatch, + clear: clear + }; + function getResolvedModule(resolution) { + return resolution.resolvedModule; + } + function getResolvedTypeReferenceDirective(resolution) { + return resolution.resolvedTypeReferenceDirective; + } + function isInDirectoryPath(dir, file) { + if (dir === undefined || file.length <= dir.length) { + return false; + } + return ts.startsWith(file, dir) && file[dir.length] === ts.directorySeparator; + } + function clear() { + ts.clearMap(directoryWatchesOfFailedLookups, ts.closeFileWatcherOf); + customFailedLookupPaths.clear(); + nonRelativeExternalModuleResolutions.clear(); + closeTypeRootsWatch(); + resolvedModuleNames.clear(); + resolvedTypeReferenceDirectives.clear(); + allFilesHaveInvalidatedResolution = false; + clearPerDirectoryResolutions(); + } + function startRecordingFilesWithChangedResolutions() { + filesWithChangedSetOfUnresolvedImports = []; + } + function finishRecordingFilesWithChangedResolutions() { + var collected = filesWithChangedSetOfUnresolvedImports; + filesWithChangedSetOfUnresolvedImports = undefined; + return collected; + } + function isFileWithInvalidatedNonRelativeUnresolvedImports(path) { + if (!filesWithInvalidatedNonRelativeUnresolvedImports) { + return false; + } + var value = filesWithInvalidatedNonRelativeUnresolvedImports.get(path); + return !!value && !!value.length; + } + function createHasInvalidatedResolution(forceAllFilesAsInvalidated) { + if (allFilesHaveInvalidatedResolution || forceAllFilesAsInvalidated) { + filesWithInvalidatedResolutions = undefined; + return ts.returnTrue; + } + var collected = filesWithInvalidatedResolutions; + filesWithInvalidatedResolutions = undefined; + return function (path) { return (!!collected && collected.has(path)) || + isFileWithInvalidatedNonRelativeUnresolvedImports(path); }; + } + function clearPerDirectoryResolutions() { + perDirectoryResolvedModuleNames.clear(); + nonRelativeModuleNameCache.clear(); + perDirectoryResolvedTypeReferenceDirectives.clear(); + nonRelativeExternalModuleResolutions.forEach(watchFailedLookupLocationOfNonRelativeModuleResolutions); + nonRelativeExternalModuleResolutions.clear(); + } + function finishCachingPerDirectoryResolution() { + allFilesHaveInvalidatedResolution = false; + filesWithInvalidatedNonRelativeUnresolvedImports = undefined; + clearPerDirectoryResolutions(); + directoryWatchesOfFailedLookups.forEach(function (watcher, path) { + if (watcher.refCount === 0) { + directoryWatchesOfFailedLookups.delete(path); + watcher.watcher.close(); + } + }); + } + function resolveModuleName(moduleName, containingFile, compilerOptions, host, redirectedReference) { + var primaryResult = ts.resolveModuleName(moduleName, containingFile, compilerOptions, host, moduleResolutionCache, redirectedReference); + if (!resolutionHost.getGlobalCache) { + return primaryResult; + } + var globalCache = resolutionHost.getGlobalCache(); + if (globalCache !== undefined && !ts.isExternalModuleNameRelative(moduleName) && !(primaryResult.resolvedModule && ts.extensionIsTS(primaryResult.resolvedModule.extension))) { + var _a = ts.loadModuleFromGlobalCache(moduleName, resolutionHost.projectName, compilerOptions, host, globalCache), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; + if (resolvedModule) { + return { resolvedModule: resolvedModule, failedLookupLocations: ts.addRange(primaryResult.failedLookupLocations, failedLookupLocations) }; + } + } + return primaryResult; + } + function resolveNamesWithLocalCache(names, containingFile, redirectedReference, cache, perDirectoryCacheWithRedirects, loader, getResolutionWithResolvedFileName, shouldRetryResolution, reusedNames, logChanges) { + var path = resolutionHost.toPath(containingFile); + var resolutionsInFile = cache.get(path) || cache.set(path, ts.createMap()).get(path); + var dirPath = ts.getDirectoryPath(path); + var perDirectoryCache = perDirectoryCacheWithRedirects.getOrCreateMapOfCacheRedirects(redirectedReference); + var perDirectoryResolution = perDirectoryCache.get(dirPath); + if (!perDirectoryResolution) { + perDirectoryResolution = ts.createMap(); + perDirectoryCache.set(dirPath, perDirectoryResolution); + } + var resolvedModules = []; + var compilerOptions = resolutionHost.getCompilationSettings(); + var hasInvalidatedNonRelativeUnresolvedImport = logChanges && isFileWithInvalidatedNonRelativeUnresolvedImports(path); + var program = resolutionHost.getCurrentProgram(); + var oldRedirect = program && program.getResolvedProjectReferenceToRedirect(containingFile); + var unmatchedRedirects = oldRedirect ? + !redirectedReference || redirectedReference.sourceFile.path !== oldRedirect.sourceFile.path : + !!redirectedReference; + var seenNamesInFile = ts.createMap(); + for (var _i = 0, names_2 = names; _i < names_2.length; _i++) { + var name = names_2[_i]; + var resolution = resolutionsInFile.get(name); + if (!seenNamesInFile.has(name) && + allFilesHaveInvalidatedResolution || unmatchedRedirects || !resolution || resolution.isInvalidated || + (hasInvalidatedNonRelativeUnresolvedImport && !ts.isExternalModuleNameRelative(name) && shouldRetryResolution(resolution))) { + var existingResolution = resolution; + var resolutionInDirectory = perDirectoryResolution.get(name); + if (resolutionInDirectory) { + resolution = resolutionInDirectory; + } + else { + resolution = loader(name, containingFile, compilerOptions, resolutionHost, redirectedReference); + perDirectoryResolution.set(name, resolution); + } + resolutionsInFile.set(name, resolution); + watchFailedLookupLocationsOfExternalModuleResolutions(name, resolution); + if (existingResolution) { + stopWatchFailedLookupLocationOfResolution(existingResolution); + } + if (logChanges && filesWithChangedSetOfUnresolvedImports && !resolutionIsEqualTo(existingResolution, resolution)) { + filesWithChangedSetOfUnresolvedImports.push(path); + logChanges = false; + } + } + ts.Debug.assert(resolution !== undefined && !resolution.isInvalidated); + seenNamesInFile.set(name, true); + resolvedModules.push(getResolutionWithResolvedFileName(resolution)); + } + resolutionsInFile.forEach(function (resolution, name) { + if (!seenNamesInFile.has(name) && !ts.contains(reusedNames, name)) { + stopWatchFailedLookupLocationOfResolution(resolution); + resolutionsInFile.delete(name); + } + }); + return resolvedModules; + function resolutionIsEqualTo(oldResolution, newResolution) { + if (oldResolution === newResolution) { + return true; + } + if (!oldResolution || !newResolution) { + return false; + } + var oldResult = getResolutionWithResolvedFileName(oldResolution); + var newResult = getResolutionWithResolvedFileName(newResolution); + if (oldResult === newResult) { + return true; + } + if (!oldResult || !newResult) { + return false; + } + return oldResult.resolvedFileName === newResult.resolvedFileName; + } + } + function resolveTypeReferenceDirectives(typeDirectiveNames, containingFile, redirectedReference) { + return resolveNamesWithLocalCache(typeDirectiveNames, containingFile, redirectedReference, resolvedTypeReferenceDirectives, perDirectoryResolvedTypeReferenceDirectives, ts.resolveTypeReferenceDirective, getResolvedTypeReferenceDirective, function (resolution) { return resolution.resolvedTypeReferenceDirective === undefined; }, undefined, false); + } + function resolveModuleNames(moduleNames, containingFile, reusedNames, redirectedReference) { + return resolveNamesWithLocalCache(moduleNames, containingFile, redirectedReference, resolvedModuleNames, perDirectoryResolvedModuleNames, resolveModuleName, getResolvedModule, function (resolution) { return !resolution.resolvedModule || !ts.resolutionExtensionIsTSOrJson(resolution.resolvedModule.extension); }, reusedNames, logChangesWhenResolvingModule); + } + function getResolvedModuleWithFailedLookupLocationsFromCache(moduleName, containingFile) { + var cache = resolvedModuleNames.get(resolutionHost.toPath(containingFile)); + return cache && cache.get(moduleName); + } + function isNodeModulesDirectory(dirPath) { + return ts.endsWith(dirPath, "/node_modules"); + } + function isNodeModulesAtTypesDirectory(dirPath) { + return ts.endsWith(dirPath, "/node_modules/@types"); + } + function canWatchDirectory(dirPath) { + var rootLength = ts.getRootLength(dirPath); + if (dirPath.length === rootLength) { + return false; + } + var nextDirectorySeparator = dirPath.indexOf(ts.directorySeparator, rootLength); + if (nextDirectorySeparator === -1) { + return false; + } + if (dirPath.charCodeAt(0) !== 47 && + dirPath.substr(rootLength, nextDirectorySeparator).search(/users/i) === -1) { + return true; + } + for (var searchIndex = nextDirectorySeparator + 1, searchLevels = 2; searchLevels > 0; searchLevels--) { + searchIndex = dirPath.indexOf(ts.directorySeparator, searchIndex) + 1; + if (searchIndex === 0) { + return false; + } + } + return true; + } + function getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath) { + if (isInDirectoryPath(rootPath, failedLookupLocationPath)) { + failedLookupLocation = ts.isRootedDiskPath(failedLookupLocation) ? ts.normalizePath(failedLookupLocation) : ts.getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory()); + ts.Debug.assert(failedLookupLocation.length === failedLookupLocationPath.length, "FailedLookup: " + failedLookupLocation + " failedLookupLocationPath: " + failedLookupLocationPath); + var subDirectoryInRoot = failedLookupLocationPath.indexOf(ts.directorySeparator, rootPath.length + 1); + if (subDirectoryInRoot !== -1) { + return { dir: failedLookupLocation.substr(0, subDirectoryInRoot), dirPath: failedLookupLocationPath.substr(0, subDirectoryInRoot) }; + } + else { + return { dir: rootDir, dirPath: rootPath, nonRecursive: false }; + } + } + return getDirectoryToWatchFromFailedLookupLocationDirectory(ts.getDirectoryPath(ts.getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory())), ts.getDirectoryPath(failedLookupLocationPath)); + } + function getDirectoryToWatchFromFailedLookupLocationDirectory(dir, dirPath) { + while (ts.pathContainsNodeModules(dirPath)) { + dir = ts.getDirectoryPath(dir); + dirPath = ts.getDirectoryPath(dirPath); + } + if (isNodeModulesDirectory(dirPath)) { + return canWatchDirectory(ts.getDirectoryPath(dirPath)) ? { dir: dir, dirPath: dirPath } : undefined; + } + var nonRecursive = true; + var subDirectoryPath, subDirectory; + if (rootPath !== undefined) { + while (!isInDirectoryPath(dirPath, rootPath)) { + var parentPath = ts.getDirectoryPath(dirPath); + if (parentPath === dirPath) { + break; + } + nonRecursive = false; + subDirectoryPath = dirPath; + subDirectory = dir; + dirPath = parentPath; + dir = ts.getDirectoryPath(dir); + } + } + return canWatchDirectory(dirPath) ? { dir: subDirectory || dir, dirPath: subDirectoryPath || dirPath, nonRecursive: nonRecursive } : undefined; + } + function isPathWithDefaultFailedLookupExtension(path) { + return ts.fileExtensionIsOneOf(path, failedLookupDefaultExtensions); + } + function watchFailedLookupLocationsOfExternalModuleResolutions(name, resolution) { + if (resolution.failedLookupLocations && resolution.failedLookupLocations.length) { + if (resolution.refCount) { + resolution.refCount++; + } + else { + resolution.refCount = 1; + if (ts.isExternalModuleNameRelative(name)) { + watchFailedLookupLocationOfResolution(resolution); + } + else { + nonRelativeExternalModuleResolutions.add(name, resolution); + } + } + } + } + function watchFailedLookupLocationOfResolution(resolution) { + ts.Debug.assert(!!resolution.refCount); + var failedLookupLocations = resolution.failedLookupLocations; + var setAtRoot = false; + for (var _i = 0, failedLookupLocations_1 = failedLookupLocations; _i < failedLookupLocations_1.length; _i++) { + var failedLookupLocation = failedLookupLocations_1[_i]; + var failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation); + var toWatch = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath); + if (toWatch) { + var dir = toWatch.dir, dirPath = toWatch.dirPath, nonRecursive = toWatch.nonRecursive; + if (!isPathWithDefaultFailedLookupExtension(failedLookupLocationPath)) { + var refCount = customFailedLookupPaths.get(failedLookupLocationPath) || 0; + customFailedLookupPaths.set(failedLookupLocationPath, refCount + 1); + } + if (dirPath === rootPath) { + ts.Debug.assert(!nonRecursive); + setAtRoot = true; + } + else { + setDirectoryWatcher(dir, dirPath, nonRecursive); + } + } + } + if (setAtRoot) { + setDirectoryWatcher(rootDir, rootPath, true); + } + } + function setRefCountToUndefined(resolution) { + resolution.refCount = undefined; + } + function watchFailedLookupLocationOfNonRelativeModuleResolutions(resolutions, name) { + var program = resolutionHost.getCurrentProgram(); + var updateResolution = program && program.getTypeChecker().tryFindAmbientModuleWithoutAugmentations(name) ? + setRefCountToUndefined : watchFailedLookupLocationOfResolution; + resolutions.forEach(updateResolution); + } + function setDirectoryWatcher(dir, dirPath, nonRecursive) { + var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath); + if (dirWatcher) { + ts.Debug.assert(!!nonRecursive === !!dirWatcher.nonRecursive); + dirWatcher.refCount++; + } + else { + directoryWatchesOfFailedLookups.set(dirPath, { watcher: createDirectoryWatcher(dir, dirPath, nonRecursive), refCount: 1, nonRecursive: nonRecursive }); + } + } + function stopWatchFailedLookupLocationOfResolution(resolution) { + if (!resolution.refCount) { + return; + } + resolution.refCount--; + if (resolution.refCount) { + return; + } + var failedLookupLocations = resolution.failedLookupLocations; + var removeAtRoot = false; + for (var _i = 0, failedLookupLocations_2 = failedLookupLocations; _i < failedLookupLocations_2.length; _i++) { + var failedLookupLocation = failedLookupLocations_2[_i]; + var failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation); + var toWatch = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath); + if (toWatch) { + var dirPath = toWatch.dirPath; + var refCount = customFailedLookupPaths.get(failedLookupLocationPath); + if (refCount) { + if (refCount === 1) { + customFailedLookupPaths.delete(failedLookupLocationPath); + } + else { + ts.Debug.assert(refCount > 1); + customFailedLookupPaths.set(failedLookupLocationPath, refCount - 1); + } + } + if (dirPath === rootPath) { + removeAtRoot = true; + } + else { + removeDirectoryWatcher(dirPath); + } + } + } + if (removeAtRoot) { + removeDirectoryWatcher(rootPath); + } + } + function removeDirectoryWatcher(dirPath) { + var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath); + dirWatcher.refCount--; + } + function createDirectoryWatcher(directory, dirPath, nonRecursive) { + return resolutionHost.watchDirectoryOfFailedLookupLocation(directory, function (fileOrDirectory) { + var fileOrDirectoryPath = resolutionHost.toPath(fileOrDirectory); + if (cachedDirectoryStructureHost) { + cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); + } + if (!allFilesHaveInvalidatedResolution && invalidateResolutionOfFailedLookupLocation(fileOrDirectoryPath, dirPath === fileOrDirectoryPath)) { + resolutionHost.onInvalidatedResolution(); + } + }, nonRecursive ? 0 : 1); + } + function removeResolutionsOfFileFromCache(cache, filePath) { + var resolutions = cache.get(filePath); + if (resolutions) { + resolutions.forEach(stopWatchFailedLookupLocationOfResolution); + cache.delete(filePath); + } + } + function removeResolutionsFromProjectReferenceRedirects(filePath) { + if (!ts.fileExtensionIs(filePath, ".json")) { + return; + } + var program = resolutionHost.getCurrentProgram(); + if (!program) { + return; + } + var resolvedProjectReference = program.getResolvedProjectReferenceByPath(filePath); + if (!resolvedProjectReference) { + return; + } + resolvedProjectReference.commandLine.fileNames.forEach(function (f) { return removeResolutionsOfFile(resolutionHost.toPath(f)); }); + } + function removeResolutionsOfFile(filePath) { + removeResolutionsOfFileFromCache(resolvedModuleNames, filePath); + removeResolutionsOfFileFromCache(resolvedTypeReferenceDirectives, filePath); + } + function invalidateResolutionCache(cache, isInvalidatedResolution, getResolutionWithResolvedFileName) { + var seen = ts.createMap(); + cache.forEach(function (resolutions, containingFilePath) { + var dirPath = ts.getDirectoryPath(containingFilePath); + var seenInDir = seen.get(dirPath); + if (!seenInDir) { + seenInDir = ts.createMap(); + seen.set(dirPath, seenInDir); + } + resolutions.forEach(function (resolution, name) { + if (seenInDir.has(name)) { + return; + } + seenInDir.set(name, true); + if (!resolution.isInvalidated && isInvalidatedResolution(resolution, getResolutionWithResolvedFileName)) { + resolution.isInvalidated = true; + (filesWithInvalidatedResolutions || (filesWithInvalidatedResolutions = ts.createMap())).set(containingFilePath, true); + } + }); + }); + } + function hasReachedResolutionIterationLimit() { + var maxSize = resolutionHost.maxNumberOfFilesToIterateForInvalidation || ts.maxNumberOfFilesToIterateForInvalidation; + return resolvedModuleNames.size > maxSize || resolvedTypeReferenceDirectives.size > maxSize; + } + function invalidateResolutions(isInvalidatedResolution) { + if (hasReachedResolutionIterationLimit()) { + allFilesHaveInvalidatedResolution = true; + return; + } + invalidateResolutionCache(resolvedModuleNames, isInvalidatedResolution, getResolvedModule); + invalidateResolutionCache(resolvedTypeReferenceDirectives, isInvalidatedResolution, getResolvedTypeReferenceDirective); + } + function invalidateResolutionOfFile(filePath) { + removeResolutionsOfFile(filePath); + invalidateResolutions(function (resolution, getResolutionWithResolvedFileName) { + var result = getResolutionWithResolvedFileName(resolution); + return !!result && resolutionHost.toPath(result.resolvedFileName) === filePath; + }); + } + function setFilesWithInvalidatedNonRelativeUnresolvedImports(filesMap) { + ts.Debug.assert(filesWithInvalidatedNonRelativeUnresolvedImports === filesMap || filesWithInvalidatedNonRelativeUnresolvedImports === undefined); + filesWithInvalidatedNonRelativeUnresolvedImports = filesMap; + } + function invalidateResolutionOfFailedLookupLocation(fileOrDirectoryPath, isCreatingWatchedDirectory) { + var isChangedFailedLookupLocation; + if (isCreatingWatchedDirectory) { + isChangedFailedLookupLocation = function (location) { return isInDirectoryPath(fileOrDirectoryPath, resolutionHost.toPath(location)); }; + } + else { + if (isPathInNodeModulesStartingWithDot(fileOrDirectoryPath)) + return false; + var dirOfFileOrDirectory = ts.getDirectoryPath(fileOrDirectoryPath); + if (isNodeModulesAtTypesDirectory(fileOrDirectoryPath) || isNodeModulesDirectory(fileOrDirectoryPath) || + isNodeModulesAtTypesDirectory(dirOfFileOrDirectory) || isNodeModulesDirectory(dirOfFileOrDirectory)) { + isChangedFailedLookupLocation = function (location) { + var locationPath = resolutionHost.toPath(location); + return locationPath === fileOrDirectoryPath || ts.startsWith(resolutionHost.toPath(location), fileOrDirectoryPath); + }; + } + else { + if (!isPathWithDefaultFailedLookupExtension(fileOrDirectoryPath) && !customFailedLookupPaths.has(fileOrDirectoryPath)) { + return false; + } + if (ts.isEmittedFileOfProgram(resolutionHost.getCurrentProgram(), fileOrDirectoryPath)) { + return false; + } + isChangedFailedLookupLocation = function (location) { return resolutionHost.toPath(location) === fileOrDirectoryPath; }; + } + } + var hasChangedFailedLookupLocation = function (resolution) { return ts.some(resolution.failedLookupLocations, isChangedFailedLookupLocation); }; + var invalidatedFilesCount = filesWithInvalidatedResolutions && filesWithInvalidatedResolutions.size; + invalidateResolutions(hasChangedFailedLookupLocation); + return allFilesHaveInvalidatedResolution || filesWithInvalidatedResolutions && filesWithInvalidatedResolutions.size !== invalidatedFilesCount; + } + function closeTypeRootsWatch() { + ts.clearMap(typeRootsWatches, ts.closeFileWatcher); + } + function getDirectoryToWatchFailedLookupLocationFromTypeRoot(typeRoot, typeRootPath) { + if (allFilesHaveInvalidatedResolution) { + return undefined; + } + if (isInDirectoryPath(rootPath, typeRootPath)) { + return rootPath; + } + var toWatch = getDirectoryToWatchFromFailedLookupLocationDirectory(typeRoot, typeRootPath); + return toWatch && directoryWatchesOfFailedLookups.has(toWatch.dirPath) ? toWatch.dirPath : undefined; + } + function createTypeRootsWatch(typeRootPath, typeRoot) { + return resolutionHost.watchTypeRootsDirectory(typeRoot, function (fileOrDirectory) { + var fileOrDirectoryPath = resolutionHost.toPath(fileOrDirectory); + if (cachedDirectoryStructureHost) { + cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); + } + resolutionHost.onChangedAutomaticTypeDirectiveNames(); + var dirPath = getDirectoryToWatchFailedLookupLocationFromTypeRoot(typeRoot, typeRootPath); + if (dirPath && invalidateResolutionOfFailedLookupLocation(fileOrDirectoryPath, dirPath === fileOrDirectoryPath)) { + resolutionHost.onInvalidatedResolution(); + } + }, 1); + } + function updateTypeRootsWatch() { + var options = resolutionHost.getCompilationSettings(); + if (options.types) { + closeTypeRootsWatch(); + return; + } + var typeRoots = ts.getEffectiveTypeRoots(options, { directoryExists: directoryExistsForTypeRootWatch, getCurrentDirectory: getCurrentDirectory }); + if (typeRoots) { + ts.mutateMap(typeRootsWatches, ts.arrayToMap(typeRoots, function (tr) { return resolutionHost.toPath(tr); }), { + createNewValue: createTypeRootsWatch, + onDeleteValue: ts.closeFileWatcher + }); + } + else { + closeTypeRootsWatch(); + } + } + function directoryExistsForTypeRootWatch(nodeTypesDirectory) { + var dir = ts.getDirectoryPath(ts.getDirectoryPath(nodeTypesDirectory)); + var dirPath = resolutionHost.toPath(dir); + return dirPath === rootPath || canWatchDirectory(dirPath); + } + } + ts.createResolutionCache = createResolutionCache; +})(ts || (ts = {})); +var ts; +(function (ts) { + var moduleSpecifiers; + (function (moduleSpecifiers) { + function getPreferences(_a, compilerOptions, importingSourceFile) { + var importModuleSpecifierPreference = _a.importModuleSpecifierPreference, importModuleSpecifierEnding = _a.importModuleSpecifierEnding; + return { + relativePreference: importModuleSpecifierPreference === "relative" ? 0 : importModuleSpecifierPreference === "non-relative" ? 1 : 2, + ending: getEnding(), + }; + function getEnding() { + switch (importModuleSpecifierEnding) { + case "minimal": return 0; + case "index": return 1; + case "js": return 2; + default: return usesJsExtensionOnImports(importingSourceFile) ? 2 + : ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.NodeJs ? 1 : 0; + } + } + } + function getPreferencesForUpdate(compilerOptions, oldImportSpecifier) { + return { + relativePreference: ts.isExternalModuleNameRelative(oldImportSpecifier) ? 0 : 1, + ending: ts.hasJSOrJsonFileExtension(oldImportSpecifier) ? 2 + : ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.NodeJs || ts.endsWith(oldImportSpecifier, "index") ? 1 : 0, + }; + } + function updateModuleSpecifier(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, oldImportSpecifier) { + var res = getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, getPreferencesForUpdate(compilerOptions, oldImportSpecifier)); + if (res === oldImportSpecifier) + return undefined; + return res; + } + moduleSpecifiers.updateModuleSpecifier = updateModuleSpecifier; + function getModuleSpecifier(compilerOptions, importingSourceFile, importingSourceFileName, toFileName, host, files, preferences, redirectTargetsMap) { + if (preferences === void 0) { preferences = {}; } + return getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, getPreferences(preferences, compilerOptions, importingSourceFile)); + } + moduleSpecifiers.getModuleSpecifier = getModuleSpecifier; + function getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, preferences) { + var info = getInfo(importingSourceFileName, host); + var modulePaths = getAllModulePaths(files, importingSourceFileName, toFileName, info.getCanonicalFileName, host, redirectTargetsMap); + return ts.firstDefined(modulePaths, function (moduleFileName) { return tryGetModuleNameAsNodeModule(moduleFileName, info, host, compilerOptions); }) || + getLocalModuleSpecifier(toFileName, info, compilerOptions, preferences); + } + function getModuleSpecifiers(moduleSymbol, compilerOptions, importingSourceFile, host, files, userPreferences, redirectTargetsMap) { + var ambient = tryGetModuleNameFromAmbientModule(moduleSymbol); + if (ambient) + return [ambient]; + var info = getInfo(importingSourceFile.path, host); + var moduleSourceFile = ts.getSourceFileOfNode(moduleSymbol.valueDeclaration || ts.getNonAugmentationDeclaration(moduleSymbol)); + var modulePaths = getAllModulePaths(files, importingSourceFile.path, moduleSourceFile.fileName, info.getCanonicalFileName, host, redirectTargetsMap); + var preferences = getPreferences(userPreferences, compilerOptions, importingSourceFile); + var global = ts.mapDefined(modulePaths, function (moduleFileName) { return tryGetModuleNameAsNodeModule(moduleFileName, info, host, compilerOptions); }); + return global.length ? global : modulePaths.map(function (moduleFileName) { return getLocalModuleSpecifier(moduleFileName, info, compilerOptions, preferences); }); + } + moduleSpecifiers.getModuleSpecifiers = getModuleSpecifiers; + function getInfo(importingSourceFileName, host) { + var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames ? host.useCaseSensitiveFileNames() : true); + var sourceDirectory = ts.getDirectoryPath(importingSourceFileName); + return { getCanonicalFileName: getCanonicalFileName, sourceDirectory: sourceDirectory }; + } + function getLocalModuleSpecifier(moduleFileName, _a, compilerOptions, _b) { + var getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory; + var ending = _b.ending, relativePreference = _b.relativePreference; + var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths, rootDirs = compilerOptions.rootDirs; + var relativePath = rootDirs && tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName) || + removeExtensionAndIndexPostFix(ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, moduleFileName, getCanonicalFileName)), ending, compilerOptions); + if (!baseUrl || relativePreference === 0) { + return relativePath; + } + var relativeToBaseUrl = getRelativePathIfInDirectory(moduleFileName, baseUrl, getCanonicalFileName); + if (!relativeToBaseUrl) { + return relativePath; + } + var importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, ending, compilerOptions); + var fromPaths = paths && tryGetModuleNameFromPaths(ts.removeFileExtension(relativeToBaseUrl), importRelativeToBaseUrl, paths); + var nonRelative = fromPaths === undefined ? importRelativeToBaseUrl : fromPaths; + if (relativePreference === 1) { + return nonRelative; + } + if (relativePreference !== 2) + ts.Debug.assertNever(relativePreference); + return isPathRelativeToParent(nonRelative) || countPathComponents(relativePath) < countPathComponents(nonRelative) ? relativePath : nonRelative; + } + function countPathComponents(path) { + var count = 0; + for (var i = ts.startsWith(path, "./") ? 2 : 0; i < path.length; i++) { + if (path.charCodeAt(i) === 47) + count++; + } + return count; + } + moduleSpecifiers.countPathComponents = countPathComponents; + function usesJsExtensionOnImports(_a) { + var imports = _a.imports; + return ts.firstDefined(imports, function (_a) { + var text = _a.text; + return ts.pathIsRelative(text) ? ts.hasJSOrJsonFileExtension(text) : undefined; + }) || false; + } + function stringsEqual(a, b, getCanonicalFileName) { + return getCanonicalFileName(a) === getCanonicalFileName(b); + } + function isNodeModulesOrScopedPackageDirectory(s, getCanonicalFileName) { + return getCanonicalFileName(s) === "node_modules" || ts.startsWith(s, "@"); + } + function guessDirectorySymlink(a, b, cwd, getCanonicalFileName) { + var aParts = ts.getPathComponents(ts.toPath(a, cwd, getCanonicalFileName)); + var bParts = ts.getPathComponents(ts.toPath(b, cwd, getCanonicalFileName)); + while (!isNodeModulesOrScopedPackageDirectory(aParts[aParts.length - 2], getCanonicalFileName) && + !isNodeModulesOrScopedPackageDirectory(bParts[bParts.length - 2], getCanonicalFileName) && + stringsEqual(aParts[aParts.length - 1], bParts[bParts.length - 1], getCanonicalFileName)) { + aParts.pop(); + bParts.pop(); + } + return [ts.getPathFromPathComponents(aParts), ts.getPathFromPathComponents(bParts)]; + } + function discoverProbableSymlinks(files, getCanonicalFileName, cwd) { + var result = ts.createMap(); + var symlinks = ts.mapDefined(files, function (sf) { + return sf.resolvedModules && ts.firstDefinedIterator(sf.resolvedModules.values(), function (res) { + return res && res.originalPath && res.resolvedFileName !== res.originalPath ? [res.resolvedFileName, res.originalPath] : undefined; + }); + }); + for (var _i = 0, symlinks_1 = symlinks; _i < symlinks_1.length; _i++) { + var _a = symlinks_1[_i], resolvedPath = _a[0], originalPath = _a[1]; + var _b = guessDirectorySymlink(resolvedPath, originalPath, cwd, getCanonicalFileName), commonResolved = _b[0], commonOriginal = _b[1]; + result.set(commonOriginal, commonResolved); + } + return result; + } + function getAllModulePaths(files, importingFileName, importedFileName, getCanonicalFileName, host, redirectTargetsMap) { + var redirects = redirectTargetsMap.get(importedFileName); + var importedFileNames = redirects ? redirects.concat([importedFileName]) : [importedFileName]; + var cwd = host.getCurrentDirectory ? host.getCurrentDirectory() : ""; + var targets = importedFileNames.map(function (f) { return ts.getNormalizedAbsolutePath(f, cwd); }); + var links = discoverProbableSymlinks(files, getCanonicalFileName, cwd); + var result = []; + var compareStrings = (!host.useCaseSensitiveFileNames || host.useCaseSensitiveFileNames()) ? ts.compareStringsCaseSensitive : ts.compareStringsCaseInsensitive; + links.forEach(function (resolved, path) { + if (ts.startsWithDirectory(importingFileName, resolved, getCanonicalFileName)) { + return; + } + var target = targets.find(function (t) { return compareStrings(t.slice(0, resolved.length + 1), resolved + "/") === 0; }); + if (target === undefined) + return; + var relative = ts.getRelativePathFromDirectory(resolved, target, getCanonicalFileName); + var option = ts.resolvePath(path, relative); + if (!host.fileExists || host.fileExists(option)) { + result.push(option); + } + }); + result.push.apply(result, targets); + return result; + } + function tryGetModuleNameFromAmbientModule(moduleSymbol) { + var decl = ts.find(moduleSymbol.declarations, function (d) { return ts.isNonGlobalAmbientModule(d) && (!ts.isExternalModuleAugmentation(d) || !ts.isExternalModuleNameRelative(ts.getTextOfIdentifierOrLiteral(d.name))); }); + if (decl) { + return decl.name.text; + } + } + function tryGetModuleNameFromPaths(relativeToBaseUrlWithIndex, relativeToBaseUrl, paths) { + for (var key in paths) { + for (var _i = 0, _a = paths[key]; _i < _a.length; _i++) { + var patternText_1 = _a[_i]; + var pattern = ts.removeFileExtension(ts.normalizePath(patternText_1)); + var indexOfStar = pattern.indexOf("*"); + if (indexOfStar !== -1) { + var prefix = pattern.substr(0, indexOfStar); + var suffix = pattern.substr(indexOfStar + 1); + if (relativeToBaseUrl.length >= prefix.length + suffix.length && + ts.startsWith(relativeToBaseUrl, prefix) && + ts.endsWith(relativeToBaseUrl, suffix) || + !suffix && relativeToBaseUrl === ts.removeTrailingDirectorySeparator(prefix)) { + var matchedStar = relativeToBaseUrl.substr(prefix.length, relativeToBaseUrl.length - suffix.length); + return key.replace("*", matchedStar); + } + } + else if (pattern === relativeToBaseUrl || pattern === relativeToBaseUrlWithIndex) { + return key; + } + } + } + } + function tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName) { + var normalizedTargetPath = getPathRelativeToRootDirs(moduleFileName, rootDirs, getCanonicalFileName); + if (normalizedTargetPath === undefined) { + return undefined; + } + var normalizedSourcePath = getPathRelativeToRootDirs(sourceDirectory, rootDirs, getCanonicalFileName); + var relativePath = normalizedSourcePath !== undefined ? ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(normalizedSourcePath, normalizedTargetPath, getCanonicalFileName)) : normalizedTargetPath; + return ts.removeFileExtension(relativePath); + } + function tryGetModuleNameAsNodeModule(moduleFileName, _a, host, options) { + var getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory; + if (!host.fileExists || !host.readFile) { + return undefined; + } + var parts = getNodeModulePathParts(moduleFileName); + if (!parts) { + return undefined; + } + var packageRootPath = moduleFileName.substring(0, parts.packageRootIndex); + var packageJsonPath = ts.combinePaths(packageRootPath, "package.json"); + var packageJsonContent = host.fileExists(packageJsonPath) + ? JSON.parse(host.readFile(packageJsonPath)) + : undefined; + var versionPaths = packageJsonContent && packageJsonContent.typesVersions + ? ts.getPackageJsonTypesVersionsPaths(packageJsonContent.typesVersions) + : undefined; + if (versionPaths) { + var subModuleName = moduleFileName.slice(parts.packageRootIndex + 1); + var fromPaths = tryGetModuleNameFromPaths(ts.removeFileExtension(subModuleName), removeExtensionAndIndexPostFix(subModuleName, 0, options), versionPaths.paths); + if (fromPaths !== undefined) { + moduleFileName = ts.combinePaths(moduleFileName.slice(0, parts.packageRootIndex), fromPaths); + } + } + var moduleSpecifier = getDirectoryOrExtensionlessFileName(moduleFileName); + if (!ts.startsWith(sourceDirectory, getCanonicalFileName(moduleSpecifier.substring(0, parts.topLevelNodeModulesIndex)))) + return undefined; + var nodeModulesDirectoryName = moduleSpecifier.substring(parts.topLevelPackageNameIndex + 1); + var packageName = ts.getPackageNameFromTypesPackageName(nodeModulesDirectoryName); + return ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs && packageName === nodeModulesDirectoryName ? undefined : packageName; + function getDirectoryOrExtensionlessFileName(path) { + if (packageJsonContent) { + var mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main; + if (mainFileRelative) { + var mainExportFile = ts.toPath(mainFileRelative, packageRootPath, getCanonicalFileName); + if (ts.removeFileExtension(mainExportFile) === ts.removeFileExtension(getCanonicalFileName(path))) { + return packageRootPath; + } + } + } + var fullModulePathWithoutExtension = ts.removeFileExtension(path); + if (getCanonicalFileName(fullModulePathWithoutExtension.substring(parts.fileNameIndex)) === "/index" && !tryGetAnyFileFromPath(host, fullModulePathWithoutExtension.substring(0, parts.fileNameIndex))) { + return fullModulePathWithoutExtension.substring(0, parts.fileNameIndex); + } + return fullModulePathWithoutExtension; + } + } + function tryGetAnyFileFromPath(host, path) { + if (!host.fileExists) + return; + var extensions = ts.getSupportedExtensions({ allowJs: true }, [{ extension: "node", isMixedContent: false }, { extension: "json", isMixedContent: false, scriptKind: 6 }]); + for (var _i = 0, extensions_3 = extensions; _i < extensions_3.length; _i++) { + var e = extensions_3[_i]; + var fullPath = path + e; + if (host.fileExists(fullPath)) { + return fullPath; + } + } + } + function getNodeModulePathParts(fullPath) { + var topLevelNodeModulesIndex = 0; + var topLevelPackageNameIndex = 0; + var packageRootIndex = 0; + var fileNameIndex = 0; + var partStart = 0; + var partEnd = 0; + var state = 0; + while (partEnd >= 0) { + partStart = partEnd; + partEnd = fullPath.indexOf("/", partStart + 1); + switch (state) { + case 0: + if (fullPath.indexOf(ts.nodeModulesPathPart, partStart) === partStart) { + topLevelNodeModulesIndex = partStart; + topLevelPackageNameIndex = partEnd; + state = 1; + } + break; + case 1: + case 2: + if (state === 1 && fullPath.charAt(partStart + 1) === "@") { + state = 2; + } + else { + packageRootIndex = partEnd; + state = 3; + } + break; + case 3: + if (fullPath.indexOf(ts.nodeModulesPathPart, partStart) === partStart) { + state = 1; + } + else { + state = 3; + } + break; + } + } + fileNameIndex = partStart; + return state > 1 ? { topLevelNodeModulesIndex: topLevelNodeModulesIndex, topLevelPackageNameIndex: topLevelPackageNameIndex, packageRootIndex: packageRootIndex, fileNameIndex: fileNameIndex } : undefined; + } + function getPathRelativeToRootDirs(path, rootDirs, getCanonicalFileName) { + return ts.firstDefined(rootDirs, function (rootDir) { + var relativePath = getRelativePathIfInDirectory(path, rootDir, getCanonicalFileName); + return isPathRelativeToParent(relativePath) ? undefined : relativePath; + }); + } + function removeExtensionAndIndexPostFix(fileName, ending, options) { + if (ts.fileExtensionIs(fileName, ".json")) + return fileName; + var noExtension = ts.removeFileExtension(fileName); + switch (ending) { + case 0: + return ts.removeSuffix(noExtension, "/index"); + case 1: + return noExtension; + case 2: + return noExtension + getJSExtensionForFile(fileName, options); + default: + return ts.Debug.assertNever(ending); + } + } + function getJSExtensionForFile(fileName, options) { + var ext = ts.extensionFromPath(fileName); + switch (ext) { + case ".ts": + case ".d.ts": + return ".js"; + case ".tsx": + return options.jsx === 1 ? ".jsx" : ".js"; + case ".js": + case ".jsx": + case ".json": + return ext; + default: + return ts.Debug.assertNever(ext); + } + } + function getRelativePathIfInDirectory(path, directoryPath, getCanonicalFileName) { + var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, false); + return ts.isRootedDiskPath(relativePath) ? undefined : relativePath; + } + function isPathRelativeToParent(path) { + return ts.startsWith(path, ".."); + } + })(moduleSpecifiers = ts.moduleSpecifiers || (ts.moduleSpecifiers = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + var sysFormatDiagnosticsHost = ts.sys ? { + getCurrentDirectory: function () { return ts.sys.getCurrentDirectory(); }, + getNewLine: function () { return ts.sys.newLine; }, + getCanonicalFileName: ts.createGetCanonicalFileName(ts.sys.useCaseSensitiveFileNames) + } : undefined; + function createDiagnosticReporter(system, pretty) { + var host = system === ts.sys ? sysFormatDiagnosticsHost : { + getCurrentDirectory: function () { return system.getCurrentDirectory(); }, + getNewLine: function () { return system.newLine; }, + getCanonicalFileName: ts.createGetCanonicalFileName(system.useCaseSensitiveFileNames), + }; + if (!pretty) { + return function (diagnostic) { return system.write(ts.formatDiagnostic(diagnostic, host)); }; + } + var diagnostics = new Array(1); + return function (diagnostic) { + diagnostics[0] = diagnostic; + system.write(ts.formatDiagnosticsWithColorAndContext(diagnostics, host) + host.getNewLine()); + diagnostics[0] = undefined; + }; + } + ts.createDiagnosticReporter = createDiagnosticReporter; + function clearScreenIfNotWatchingForFileChanges(system, diagnostic, options) { + if (system.clearScreen && + !options.preserveWatchOutput && + !options.extendedDiagnostics && + !options.diagnostics && + ts.contains(ts.screenStartingMessageCodes, diagnostic.code)) { + system.clearScreen(); + return true; + } + return false; + } + ts.screenStartingMessageCodes = [ + ts.Diagnostics.Starting_compilation_in_watch_mode.code, + ts.Diagnostics.File_change_detected_Starting_incremental_compilation.code, + ]; + function getPlainDiagnosticFollowingNewLines(diagnostic, newLine) { + return ts.contains(ts.screenStartingMessageCodes, diagnostic.code) + ? newLine + newLine + : newLine; + } + function createWatchStatusReporter(system, pretty) { + return pretty ? + function (diagnostic, newLine, options) { + clearScreenIfNotWatchingForFileChanges(system, diagnostic, options); + var output = "[" + ts.formatColorAndReset(new Date().toLocaleTimeString(), ts.ForegroundColorEscapeSequences.Grey) + "] "; + output += "" + ts.flattenDiagnosticMessageText(diagnostic.messageText, system.newLine) + (newLine + newLine); + system.write(output); + } : + function (diagnostic, newLine, options) { + var output = ""; + if (!clearScreenIfNotWatchingForFileChanges(system, diagnostic, options)) { + output += newLine; + } + output += new Date().toLocaleTimeString() + " - "; + output += "" + ts.flattenDiagnosticMessageText(diagnostic.messageText, system.newLine) + getPlainDiagnosticFollowingNewLines(diagnostic, newLine); + system.write(output); + }; + } + ts.createWatchStatusReporter = createWatchStatusReporter; + function parseConfigFileWithSystem(configFileName, optionsToExtend, system, reportDiagnostic) { + var host = system; + host.onUnRecoverableConfigFileDiagnostic = function (diagnostic) { return reportUnrecoverableDiagnostic(ts.sys, reportDiagnostic, diagnostic); }; + var result = ts.getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host); + host.onUnRecoverableConfigFileDiagnostic = undefined; + return result; + } + ts.parseConfigFileWithSystem = parseConfigFileWithSystem; + function getErrorCountForSummary(diagnostics) { + return ts.countWhere(diagnostics, function (diagnostic) { return diagnostic.category === ts.DiagnosticCategory.Error; }); + } + ts.getErrorCountForSummary = getErrorCountForSummary; + function getWatchErrorSummaryDiagnosticMessage(errorCount) { + return errorCount === 1 ? + ts.Diagnostics.Found_1_error_Watching_for_file_changes : + ts.Diagnostics.Found_0_errors_Watching_for_file_changes; + } + ts.getWatchErrorSummaryDiagnosticMessage = getWatchErrorSummaryDiagnosticMessage; + function getErrorSummaryText(errorCount, newLine) { + if (errorCount === 0) + return ""; + var d = ts.createCompilerDiagnostic(errorCount === 1 ? ts.Diagnostics.Found_1_error : ts.Diagnostics.Found_0_errors, errorCount); + return "" + newLine + ts.flattenDiagnosticMessageText(d.messageText, newLine) + newLine + newLine; + } + ts.getErrorSummaryText = getErrorSummaryText; + function emitFilesAndReportErrors(program, reportDiagnostic, writeFileName, reportSummary, writeFile) { + var diagnostics = program.getConfigFileParsingDiagnostics().slice(); + var configFileParsingDiagnosticsLength = diagnostics.length; + ts.addRange(diagnostics, program.getSyntacticDiagnostics()); + var reportSemanticDiagnostics = false; + if (diagnostics.length === configFileParsingDiagnosticsLength) { + ts.addRange(diagnostics, program.getOptionsDiagnostics()); + ts.addRange(diagnostics, program.getGlobalDiagnostics()); + if (diagnostics.length === configFileParsingDiagnosticsLength) { + reportSemanticDiagnostics = true; + } + } + var _a = program.emit(undefined, writeFile), emittedFiles = _a.emittedFiles, emitSkipped = _a.emitSkipped, emitDiagnostics = _a.diagnostics; + ts.addRange(diagnostics, emitDiagnostics); + if (reportSemanticDiagnostics) { + ts.addRange(diagnostics, program.getSemanticDiagnostics()); + } + ts.sortAndDeduplicateDiagnostics(diagnostics).forEach(reportDiagnostic); + if (writeFileName) { + var currentDir_1 = program.getCurrentDirectory(); + ts.forEach(emittedFiles, function (file) { + var filepath = ts.getNormalizedAbsolutePath(file, currentDir_1); + writeFileName("TSFILE: " + filepath); + }); + if (program.getCompilerOptions().listFiles) { + ts.forEach(program.getSourceFiles(), function (file) { + writeFileName(file.fileName); + }); + } + } + if (reportSummary) { + reportSummary(getErrorCountForSummary(diagnostics)); + } + if (emitSkipped && diagnostics.length > 0) { + return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; + } + else if (diagnostics.length > 0) { + return ts.ExitStatus.DiagnosticsPresent_OutputsGenerated; + } + return ts.ExitStatus.Success; + } + ts.emitFilesAndReportErrors = emitFilesAndReportErrors; + var noopFileWatcher = { close: ts.noop }; + function createWatchHost(system, reportWatchStatus) { + if (system === void 0) { system = ts.sys; } + var onWatchStatusChange = reportWatchStatus || createWatchStatusReporter(system); + return { + onWatchStatusChange: onWatchStatusChange, + watchFile: system.watchFile ? (function (path, callback, pollingInterval) { return system.watchFile(path, callback, pollingInterval); }) : function () { return noopFileWatcher; }, + watchDirectory: system.watchDirectory ? (function (path, callback, recursive) { return system.watchDirectory(path, callback, recursive); }) : function () { return noopFileWatcher; }, + setTimeout: system.setTimeout ? (function (callback, ms) { + var args = []; + for (var _i = 2; _i < arguments.length; _i++) { + args[_i - 2] = arguments[_i]; + } + var _a; + return (_a = system.setTimeout).call.apply(_a, [system, callback, ms].concat(args)); + }) : ts.noop, + clearTimeout: system.clearTimeout ? (function (timeoutId) { return system.clearTimeout(timeoutId); }) : ts.noop + }; + } + ts.createWatchHost = createWatchHost; + function createWatchCompilerHost(system, createProgram, reportDiagnostic, reportWatchStatus) { + if (system === void 0) { system = ts.sys; } + if (!createProgram) { + createProgram = ts.createEmitAndSemanticDiagnosticsBuilderProgram; + } + var host = system; + host; + var useCaseSensitiveFileNames = function () { return system.useCaseSensitiveFileNames; }; + var writeFileName = function (s) { return system.write(s + system.newLine); }; + var _a = createWatchHost(system, reportWatchStatus), onWatchStatusChange = _a.onWatchStatusChange, watchFile = _a.watchFile, watchDirectory = _a.watchDirectory, setTimeout = _a.setTimeout, clearTimeout = _a.clearTimeout; + return { + useCaseSensitiveFileNames: useCaseSensitiveFileNames, + getNewLine: function () { return system.newLine; }, + getCurrentDirectory: function () { return system.getCurrentDirectory(); }, + getDefaultLibLocation: getDefaultLibLocation, + getDefaultLibFileName: function (options) { return ts.combinePaths(getDefaultLibLocation(), ts.getDefaultLibFileName(options)); }, + fileExists: function (path) { return system.fileExists(path); }, + readFile: function (path, encoding) { return system.readFile(path, encoding); }, + directoryExists: function (path) { return system.directoryExists(path); }, + getDirectories: function (path) { return system.getDirectories(path); }, + readDirectory: function (path, extensions, exclude, include, depth) { return system.readDirectory(path, extensions, exclude, include, depth); }, + realpath: system.realpath && (function (path) { return system.realpath(path); }), + getEnvironmentVariable: system.getEnvironmentVariable && (function (name) { return system.getEnvironmentVariable(name); }), + watchFile: watchFile, + watchDirectory: watchDirectory, + setTimeout: setTimeout, + clearTimeout: clearTimeout, + trace: function (s) { return system.write(s); }, + onWatchStatusChange: onWatchStatusChange, + createDirectory: function (path) { return system.createDirectory(path); }, + writeFile: function (path, data, writeByteOrderMark) { return system.writeFile(path, data, writeByteOrderMark); }, + onCachedDirectoryStructureHostCreate: function (cacheHost) { return host = cacheHost || system; }, + createHash: system.createHash && (function (s) { return system.createHash(s); }), + createProgram: createProgram, + afterProgramCreate: emitFilesAndReportErrorUsingBuilder + }; + function getDefaultLibLocation() { + return ts.getDirectoryPath(ts.normalizePath(system.getExecutingFilePath())); + } + function emitFilesAndReportErrorUsingBuilder(builderProgram) { + var compilerOptions = builderProgram.getCompilerOptions(); + var newLine = ts.getNewLineCharacter(compilerOptions, function () { return system.newLine; }); + emitFilesAndReportErrors(builderProgram, reportDiagnostic, writeFileName, function (errorCount) { return onWatchStatusChange(ts.createCompilerDiagnostic(getWatchErrorSummaryDiagnosticMessage(errorCount), errorCount), newLine, compilerOptions); }); + } + } + function reportUnrecoverableDiagnostic(system, reportDiagnostic, diagnostic) { + reportDiagnostic(diagnostic); + system.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); + } + function createWatchCompilerHostOfConfigFile(configFileName, optionsToExtend, system, createProgram, reportDiagnostic, reportWatchStatus) { + var diagnosticReporter = reportDiagnostic || createDiagnosticReporter(system); + var host = createWatchCompilerHost(system, createProgram, diagnosticReporter, reportWatchStatus); + host.onUnRecoverableConfigFileDiagnostic = function (diagnostic) { return reportUnrecoverableDiagnostic(system, diagnosticReporter, diagnostic); }; + host.configFileName = configFileName; + host.optionsToExtend = optionsToExtend; + return host; + } + ts.createWatchCompilerHostOfConfigFile = createWatchCompilerHostOfConfigFile; + function createWatchCompilerHostOfFilesAndCompilerOptions(rootFiles, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences) { + var host = createWatchCompilerHost(system, createProgram, reportDiagnostic || createDiagnosticReporter(system), reportWatchStatus); + host.rootFiles = rootFiles; + host.options = options; + host.projectReferences = projectReferences; + return host; + } + ts.createWatchCompilerHostOfFilesAndCompilerOptions = createWatchCompilerHostOfFilesAndCompilerOptions; +})(ts || (ts = {})); +(function (ts) { + function createWatchCompilerHost(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences) { + if (ts.isArray(rootFilesOrConfigFileName)) { + return ts.createWatchCompilerHostOfFilesAndCompilerOptions(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences); + } + else { + return ts.createWatchCompilerHostOfConfigFile(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus); + } + } + ts.createWatchCompilerHost = createWatchCompilerHost; + var initialVersion = 1; + function createWatchProgram(host) { + var builderProgram; + var reloadLevel; + var missingFilesMap; + var watchedWildcardDirectories; + var timerToUpdateProgram; + var sourceFilesCache = ts.createMap(); + var missingFilePathsRequestedForRelease; + var hasChangedCompilerOptions = false; + var hasChangedAutomaticTypeDirectiveNames = false; + var useCaseSensitiveFileNames = host.useCaseSensitiveFileNames(); + var currentDirectory = host.getCurrentDirectory(); + var getCurrentDirectory = function () { return currentDirectory; }; + var readFile = function (path, encoding) { return host.readFile(path, encoding); }; + var configFileName = host.configFileName, _a = host.optionsToExtend, optionsToExtendForConfigFile = _a === void 0 ? {} : _a, createProgram = host.createProgram; + var rootFileNames = host.rootFiles, compilerOptions = host.options, projectReferences = host.projectReferences; + var configFileSpecs; + var configFileParsingDiagnostics; + var canConfigFileJsonReportNoInputFiles = false; + var hasChangedConfigFileParsingErrors = false; + var cachedDirectoryStructureHost = configFileName === undefined ? undefined : ts.createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensitiveFileNames); + if (cachedDirectoryStructureHost && host.onCachedDirectoryStructureHostCreate) { + host.onCachedDirectoryStructureHostCreate(cachedDirectoryStructureHost); + } + var directoryStructureHost = cachedDirectoryStructureHost || host; + var parseConfigFileHost = { + useCaseSensitiveFileNames: useCaseSensitiveFileNames, + readDirectory: function (path, extensions, exclude, include, depth) { return directoryStructureHost.readDirectory(path, extensions, exclude, include, depth); }, + fileExists: function (path) { return host.fileExists(path); }, + readFile: readFile, + getCurrentDirectory: getCurrentDirectory, + onUnRecoverableConfigFileDiagnostic: host.onUnRecoverableConfigFileDiagnostic, + trace: host.trace ? function (s) { return host.trace(s); } : undefined + }; + var newLine = updateNewLine(); + if (configFileName && host.configFileParsingResult) { + setConfigFileParsingResult(host.configFileParsingResult); + newLine = updateNewLine(); + } + reportWatchDiagnostic(ts.Diagnostics.Starting_compilation_in_watch_mode); + if (configFileName && !host.configFileParsingResult) { + newLine = ts.getNewLineCharacter(optionsToExtendForConfigFile, function () { return host.getNewLine(); }); + ts.Debug.assert(!rootFileNames); + parseConfigFile(); + newLine = updateNewLine(); + } + var trace = host.trace && (function (s) { host.trace(s + newLine); }); + var watchLogLevel = trace ? compilerOptions.extendedDiagnostics ? ts.WatchLogLevel.Verbose : + compilerOptions.diagnostics ? ts.WatchLogLevel.TriggerOnly : ts.WatchLogLevel.None : ts.WatchLogLevel.None; + var writeLog = watchLogLevel !== ts.WatchLogLevel.None ? trace : ts.noop; + var _b = ts.getWatchFactory(watchLogLevel, writeLog), watchFile = _b.watchFile, watchFilePath = _b.watchFilePath, watchDirectory = _b.watchDirectory; + var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); + writeLog("Current directory: " + currentDirectory + " CaseSensitiveFileNames: " + useCaseSensitiveFileNames); + if (configFileName) { + watchFile(host, configFileName, scheduleProgramReload, ts.PollingInterval.High, "Config file"); + } + var compilerHost = { + getSourceFile: function (fileName, languageVersion, onError, shouldCreateNewSourceFile) { return getVersionedSourceFileByPath(fileName, toPath(fileName), languageVersion, onError, shouldCreateNewSourceFile); }, + getSourceFileByPath: getVersionedSourceFileByPath, + getDefaultLibLocation: host.getDefaultLibLocation && (function () { return host.getDefaultLibLocation(); }), + getDefaultLibFileName: function (options) { return host.getDefaultLibFileName(options); }, + writeFile: writeFile, + getCurrentDirectory: getCurrentDirectory, + useCaseSensitiveFileNames: function () { return useCaseSensitiveFileNames; }, + getCanonicalFileName: getCanonicalFileName, + getNewLine: function () { return newLine; }, + fileExists: fileExists, + readFile: readFile, + trace: trace, + directoryExists: directoryStructureHost.directoryExists && (function (path) { return directoryStructureHost.directoryExists(path); }), + getDirectories: (directoryStructureHost.getDirectories && (function (path) { return directoryStructureHost.getDirectories(path); })), + realpath: host.realpath && (function (s) { return host.realpath(s); }), + getEnvironmentVariable: host.getEnvironmentVariable ? (function (name) { return host.getEnvironmentVariable(name); }) : (function () { return ""; }), + onReleaseOldSourceFile: onReleaseOldSourceFile, + createHash: host.createHash && (function (data) { return host.createHash(data); }), + toPath: toPath, + getCompilationSettings: function () { return compilerOptions; }, + watchDirectoryOfFailedLookupLocation: function (dir, cb, flags) { return watchDirectory(host, dir, cb, flags, "Failed Lookup Locations"); }, + watchTypeRootsDirectory: function (dir, cb, flags) { return watchDirectory(host, dir, cb, flags, "Type roots"); }, + getCachedDirectoryStructureHost: function () { return cachedDirectoryStructureHost; }, + onInvalidatedResolution: scheduleProgramUpdate, + onChangedAutomaticTypeDirectiveNames: function () { + hasChangedAutomaticTypeDirectiveNames = true; + scheduleProgramUpdate(); + }, + maxNumberOfFilesToIterateForInvalidation: host.maxNumberOfFilesToIterateForInvalidation, + getCurrentProgram: getCurrentProgram, + writeLog: writeLog, + readDirectory: function (path, extensions, exclude, include, depth) { return directoryStructureHost.readDirectory(path, extensions, exclude, include, depth); }, + }; + var resolutionCache = ts.createResolutionCache(compilerHost, configFileName ? + ts.getDirectoryPath(ts.getNormalizedAbsolutePath(configFileName, currentDirectory)) : + currentDirectory, false); + compilerHost.resolveModuleNames = host.resolveModuleNames ? + (function (moduleNames, containingFile, reusedNames, redirectedReference) { return host.resolveModuleNames(moduleNames, containingFile, reusedNames, redirectedReference); }) : + (function (moduleNames, containingFile, reusedNames, redirectedReference) { return resolutionCache.resolveModuleNames(moduleNames, containingFile, reusedNames, redirectedReference); }); + compilerHost.resolveTypeReferenceDirectives = host.resolveTypeReferenceDirectives ? + (function (typeDirectiveNames, containingFile, redirectedReference) { return host.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile, redirectedReference); }) : + (function (typeDirectiveNames, containingFile, redirectedReference) { return resolutionCache.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile, redirectedReference); }); + var userProvidedResolution = !!host.resolveModuleNames || !!host.resolveTypeReferenceDirectives; + synchronizeProgram(); + watchConfigFileWildCardDirectories(); + return configFileName ? + { getCurrentProgram: getCurrentBuilderProgram, getProgram: synchronizeProgram } : + { getCurrentProgram: getCurrentBuilderProgram, getProgram: synchronizeProgram, updateRootFileNames: updateRootFileNames }; + function getCurrentBuilderProgram() { + return builderProgram; + } + function getCurrentProgram() { + return builderProgram && builderProgram.getProgram(); + } + function synchronizeProgram() { + writeLog("Synchronizing program"); + var program = getCurrentProgram(); + if (hasChangedCompilerOptions) { + newLine = updateNewLine(); + if (program && ts.changesAffectModuleResolution(program.getCompilerOptions(), compilerOptions)) { + resolutionCache.clear(); + } + } + var hasInvalidatedResolution = resolutionCache.createHasInvalidatedResolution(userProvidedResolution); + if (ts.isProgramUptoDate(getCurrentProgram(), rootFileNames, compilerOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, projectReferences)) { + if (hasChangedConfigFileParsingErrors) { + builderProgram = createProgram(undefined, undefined, compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences); + hasChangedConfigFileParsingErrors = false; + } + } + else { + createNewProgram(program, hasInvalidatedResolution); + } + if (host.afterProgramCreate) { + host.afterProgramCreate(builderProgram); + } + return builderProgram; + } + function createNewProgram(program, hasInvalidatedResolution) { + if (watchLogLevel !== ts.WatchLogLevel.None) { + writeLog("CreatingProgramWith::"); + writeLog(" roots: " + JSON.stringify(rootFileNames)); + writeLog(" options: " + JSON.stringify(compilerOptions)); + } + var needsUpdateInTypeRootWatch = hasChangedCompilerOptions || !program; + hasChangedCompilerOptions = false; + hasChangedConfigFileParsingErrors = false; + resolutionCache.startCachingPerDirectoryResolution(); + compilerHost.hasInvalidatedResolution = hasInvalidatedResolution; + compilerHost.hasChangedAutomaticTypeDirectiveNames = hasChangedAutomaticTypeDirectiveNames; + builderProgram = createProgram(rootFileNames, compilerOptions, compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences); + resolutionCache.finishCachingPerDirectoryResolution(); + ts.updateMissingFilePathsWatch(builderProgram.getProgram(), missingFilesMap || (missingFilesMap = ts.createMap()), watchMissingFilePath); + if (needsUpdateInTypeRootWatch) { + resolutionCache.updateTypeRootsWatch(); + } + if (missingFilePathsRequestedForRelease) { + for (var _i = 0, missingFilePathsRequestedForRelease_1 = missingFilePathsRequestedForRelease; _i < missingFilePathsRequestedForRelease_1.length; _i++) { + var missingFilePath = missingFilePathsRequestedForRelease_1[_i]; + if (!missingFilesMap.has(missingFilePath)) { + sourceFilesCache.delete(missingFilePath); + } + } + missingFilePathsRequestedForRelease = undefined; + } + } + function updateRootFileNames(files) { + ts.Debug.assert(!configFileName, "Cannot update root file names with config file watch mode"); + rootFileNames = files; + scheduleProgramUpdate(); + } + function updateNewLine() { + return ts.getNewLineCharacter(compilerOptions || optionsToExtendForConfigFile, function () { return host.getNewLine(); }); + } + function toPath(fileName) { + return ts.toPath(fileName, currentDirectory, getCanonicalFileName); + } + function isFileMissingOnHost(hostSourceFile) { + return typeof hostSourceFile === "number"; + } + function isFilePresentOnHost(hostSourceFile) { + return !!hostSourceFile.sourceFile; + } + function fileExists(fileName) { + var path = toPath(fileName); + if (isFileMissingOnHost(sourceFilesCache.get(path))) { + return true; + } + return directoryStructureHost.fileExists(fileName); + } + function getVersionedSourceFileByPath(fileName, path, languageVersion, onError, shouldCreateNewSourceFile) { + var hostSourceFile = sourceFilesCache.get(path); + if (isFileMissingOnHost(hostSourceFile)) { + return undefined; + } + if (!hostSourceFile || shouldCreateNewSourceFile || !isFilePresentOnHost(hostSourceFile) || hostSourceFile.version.toString() !== hostSourceFile.sourceFile.version) { + var sourceFile = getNewSourceFile(); + if (hostSourceFile) { + if (shouldCreateNewSourceFile) { + hostSourceFile.version++; + } + if (sourceFile) { + hostSourceFile.sourceFile = sourceFile; + sourceFile.version = hostSourceFile.version.toString(); + if (!hostSourceFile.fileWatcher) { + hostSourceFile.fileWatcher = watchFilePath(host, fileName, onSourceFileChange, ts.PollingInterval.Low, path, "Source file"); + } + } + else { + if (isFilePresentOnHost(hostSourceFile)) { + hostSourceFile.fileWatcher.close(); + } + sourceFilesCache.set(path, hostSourceFile.version); + } + } + else { + if (sourceFile) { + sourceFile.version = initialVersion.toString(); + var fileWatcher = watchFilePath(host, fileName, onSourceFileChange, ts.PollingInterval.Low, path, "Source file"); + sourceFilesCache.set(path, { sourceFile: sourceFile, version: initialVersion, fileWatcher: fileWatcher }); + } + else { + sourceFilesCache.set(path, initialVersion); + } + } + return sourceFile; + } + return hostSourceFile.sourceFile; + function getNewSourceFile() { + var text; + try { + ts.performance.mark("beforeIORead"); + text = host.readFile(fileName, compilerOptions.charset); + ts.performance.mark("afterIORead"); + ts.performance.measure("I/O Read", "beforeIORead", "afterIORead"); + } + catch (e) { + if (onError) { + onError(e.message); + } + } + return text !== undefined ? ts.createSourceFile(fileName, text, languageVersion) : undefined; + } + } + function nextSourceFileVersion(path) { + var hostSourceFile = sourceFilesCache.get(path); + if (hostSourceFile !== undefined) { + if (isFileMissingOnHost(hostSourceFile)) { + sourceFilesCache.set(path, { version: Number(hostSourceFile) + 1 }); + } + else { + hostSourceFile.version++; + } + } + } + function getSourceVersion(path) { + var hostSourceFile = sourceFilesCache.get(path); + return !hostSourceFile || isFileMissingOnHost(hostSourceFile) ? undefined : hostSourceFile.version.toString(); + } + function onReleaseOldSourceFile(oldSourceFile, _oldOptions, hasSourceFileByPath) { + var hostSourceFileInfo = sourceFilesCache.get(oldSourceFile.resolvedPath); + if (hostSourceFileInfo) { + if (isFileMissingOnHost(hostSourceFileInfo)) { + (missingFilePathsRequestedForRelease || (missingFilePathsRequestedForRelease = [])).push(oldSourceFile.path); + } + else if (hostSourceFileInfo.sourceFile === oldSourceFile) { + if (hostSourceFileInfo.fileWatcher) { + hostSourceFileInfo.fileWatcher.close(); + } + sourceFilesCache.delete(oldSourceFile.resolvedPath); + if (!hasSourceFileByPath) { + resolutionCache.removeResolutionsOfFile(oldSourceFile.path); + } + } + } + } + function reportWatchDiagnostic(message) { + if (host.onWatchStatusChange) { + host.onWatchStatusChange(ts.createCompilerDiagnostic(message), newLine, compilerOptions || optionsToExtendForConfigFile); + } + } + function scheduleProgramUpdate() { + if (!host.setTimeout || !host.clearTimeout) { + return; + } + if (timerToUpdateProgram) { + host.clearTimeout(timerToUpdateProgram); + } + writeLog("Scheduling update"); + timerToUpdateProgram = host.setTimeout(updateProgram, 250); + } + function scheduleProgramReload() { + ts.Debug.assert(!!configFileName); + reloadLevel = ts.ConfigFileProgramReloadLevel.Full; + scheduleProgramUpdate(); + } + function updateProgram() { + timerToUpdateProgram = undefined; + reportWatchDiagnostic(ts.Diagnostics.File_change_detected_Starting_incremental_compilation); + switch (reloadLevel) { + case ts.ConfigFileProgramReloadLevel.Partial: + return reloadFileNamesFromConfigFile(); + case ts.ConfigFileProgramReloadLevel.Full: + return reloadConfigFile(); + default: + synchronizeProgram(); + return; + } + } + function reloadFileNamesFromConfigFile() { + writeLog("Reloading new file names and options"); + var result = ts.getFileNamesFromConfigSpecs(configFileSpecs, ts.getDirectoryPath(configFileName), compilerOptions, parseConfigFileHost); + if (ts.updateErrorForNoInputFiles(result, configFileName, configFileSpecs, configFileParsingDiagnostics, canConfigFileJsonReportNoInputFiles)) { + hasChangedConfigFileParsingErrors = true; + } + rootFileNames = result.fileNames; + synchronizeProgram(); + } + function reloadConfigFile() { + writeLog("Reloading config file: " + configFileName); + reloadLevel = ts.ConfigFileProgramReloadLevel.None; + if (cachedDirectoryStructureHost) { + cachedDirectoryStructureHost.clearCache(); + } + parseConfigFile(); + hasChangedCompilerOptions = true; + synchronizeProgram(); + watchConfigFileWildCardDirectories(); + } + function parseConfigFile() { + setConfigFileParsingResult(ts.getParsedCommandLineOfConfigFile(configFileName, optionsToExtendForConfigFile, parseConfigFileHost)); + } + function setConfigFileParsingResult(configFileParseResult) { + rootFileNames = configFileParseResult.fileNames; + compilerOptions = configFileParseResult.options; + configFileSpecs = configFileParseResult.configFileSpecs; + projectReferences = configFileParseResult.projectReferences; + configFileParsingDiagnostics = ts.getConfigFileParsingDiagnostics(configFileParseResult).slice(); + canConfigFileJsonReportNoInputFiles = ts.canJsonReportNoInutFiles(configFileParseResult.raw); + hasChangedConfigFileParsingErrors = true; + } + function onSourceFileChange(fileName, eventKind, path) { + updateCachedSystemWithFile(fileName, path, eventKind); + if (eventKind === ts.FileWatcherEventKind.Deleted && sourceFilesCache.get(path)) { + resolutionCache.invalidateResolutionOfFile(path); + } + resolutionCache.removeResolutionsFromProjectReferenceRedirects(path); + nextSourceFileVersion(path); + scheduleProgramUpdate(); + } + function updateCachedSystemWithFile(fileName, path, eventKind) { + if (cachedDirectoryStructureHost) { + cachedDirectoryStructureHost.addOrDeleteFile(fileName, path, eventKind); + } + } + function watchMissingFilePath(missingFilePath) { + return watchFilePath(host, missingFilePath, onMissingFileChange, ts.PollingInterval.Medium, missingFilePath, "Missing file"); + } + function onMissingFileChange(fileName, eventKind, missingFilePath) { + updateCachedSystemWithFile(fileName, missingFilePath, eventKind); + if (eventKind === ts.FileWatcherEventKind.Created && missingFilesMap.has(missingFilePath)) { + missingFilesMap.get(missingFilePath).close(); + missingFilesMap.delete(missingFilePath); + nextSourceFileVersion(missingFilePath); + scheduleProgramUpdate(); + } + } + function watchConfigFileWildCardDirectories() { + if (configFileSpecs) { + ts.updateWatchingWildcardDirectories(watchedWildcardDirectories || (watchedWildcardDirectories = ts.createMap()), ts.createMapFromTemplate(configFileSpecs.wildcardDirectories), watchWildcardDirectory); + } + else if (watchedWildcardDirectories) { + ts.clearMap(watchedWildcardDirectories, ts.closeFileWatcherOf); + } + } + function watchWildcardDirectory(directory, flags) { + return watchDirectory(host, directory, function (fileOrDirectory) { + ts.Debug.assert(!!configFileName); + var fileOrDirectoryPath = toPath(fileOrDirectory); + if (cachedDirectoryStructureHost) { + cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); + } + nextSourceFileVersion(fileOrDirectoryPath); + if (ts.isPathInNodeModulesStartingWithDot(fileOrDirectoryPath)) + return; + if (fileOrDirectoryPath !== directory && ts.hasExtension(fileOrDirectoryPath) && !ts.isSupportedSourceFileName(fileOrDirectory, compilerOptions)) { + writeLog("Project: " + configFileName + " Detected file add/remove of non supported extension: " + fileOrDirectory); + return; + } + if (reloadLevel !== ts.ConfigFileProgramReloadLevel.Full) { + reloadLevel = ts.ConfigFileProgramReloadLevel.Partial; + scheduleProgramUpdate(); + } + }, flags, "Wild card directories"); + } + function ensureDirectoriesExist(directoryPath) { + if (directoryPath.length > ts.getRootLength(directoryPath) && !host.directoryExists(directoryPath)) { + var parentDirectory = ts.getDirectoryPath(directoryPath); + ensureDirectoriesExist(parentDirectory); + host.createDirectory(directoryPath); + } + } + function writeFile(fileName, text, writeByteOrderMark, onError) { + try { + ts.performance.mark("beforeIOWrite"); + ensureDirectoriesExist(ts.getDirectoryPath(ts.normalizePath(fileName))); + host.writeFile(fileName, text, writeByteOrderMark); + ts.performance.mark("afterIOWrite"); + ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite"); + } + catch (e) { + if (onError) { + onError(e.message); + } + } + } + } + ts.createWatchProgram = createWatchProgram; +})(ts || (ts = {})); +var ts; +(function (ts) { + var minimumDate = new Date(-8640000000000000); + var maximumDate = new Date(8640000000000000); + var BuildResultFlags; + (function (BuildResultFlags) { + BuildResultFlags[BuildResultFlags["None"] = 0] = "None"; + BuildResultFlags[BuildResultFlags["Success"] = 1] = "Success"; + BuildResultFlags[BuildResultFlags["DeclarationOutputUnchanged"] = 2] = "DeclarationOutputUnchanged"; + BuildResultFlags[BuildResultFlags["ConfigFileErrors"] = 4] = "ConfigFileErrors"; + BuildResultFlags[BuildResultFlags["SyntaxErrors"] = 8] = "SyntaxErrors"; + BuildResultFlags[BuildResultFlags["TypeErrors"] = 16] = "TypeErrors"; + BuildResultFlags[BuildResultFlags["DeclarationEmitErrors"] = 32] = "DeclarationEmitErrors"; + BuildResultFlags[BuildResultFlags["EmitErrors"] = 64] = "EmitErrors"; + BuildResultFlags[BuildResultFlags["AnyErrors"] = 124] = "AnyErrors"; + })(BuildResultFlags || (BuildResultFlags = {})); + var UpToDateStatusType; + (function (UpToDateStatusType) { + UpToDateStatusType[UpToDateStatusType["Unbuildable"] = 0] = "Unbuildable"; + UpToDateStatusType[UpToDateStatusType["UpToDate"] = 1] = "UpToDate"; + UpToDateStatusType[UpToDateStatusType["UpToDateWithUpstreamTypes"] = 2] = "UpToDateWithUpstreamTypes"; + UpToDateStatusType[UpToDateStatusType["OutputMissing"] = 3] = "OutputMissing"; + UpToDateStatusType[UpToDateStatusType["OutOfDateWithSelf"] = 4] = "OutOfDateWithSelf"; + UpToDateStatusType[UpToDateStatusType["OutOfDateWithUpstream"] = 5] = "OutOfDateWithUpstream"; + UpToDateStatusType[UpToDateStatusType["UpstreamOutOfDate"] = 6] = "UpstreamOutOfDate"; + UpToDateStatusType[UpToDateStatusType["UpstreamBlocked"] = 7] = "UpstreamBlocked"; + UpToDateStatusType[UpToDateStatusType["ComputingUpstream"] = 8] = "ComputingUpstream"; + UpToDateStatusType[UpToDateStatusType["ContainerOnly"] = 9] = "ContainerOnly"; + })(UpToDateStatusType = ts.UpToDateStatusType || (ts.UpToDateStatusType = {})); + function createFileMap(toPath) { + var lookup = ts.createMap(); + return { + setValue: setValue, + getValue: getValue, + removeKey: removeKey, + forEach: forEach, + hasKey: hasKey, + getSize: getSize, + clear: clear + }; + function forEach(action) { + lookup.forEach(action); + } + function hasKey(fileName) { + return lookup.has(toPath(fileName)); + } + function removeKey(fileName) { + lookup.delete(toPath(fileName)); + } + function setValue(fileName, value) { + lookup.set(toPath(fileName), value); + } + function getValue(fileName) { + return lookup.get(toPath(fileName)); + } + function getSize() { + return lookup.size; + } + function clear() { + lookup.clear(); + } + } + function getOrCreateValueFromConfigFileMap(configFileMap, resolved, createT) { + var existingValue = configFileMap.getValue(resolved); + var newValue; + if (!existingValue) { + newValue = createT(); + configFileMap.setValue(resolved, newValue); + } + return existingValue || newValue; + } + function getOrCreateValueMapFromConfigFileMap(configFileMap, resolved) { + return getOrCreateValueFromConfigFileMap(configFileMap, resolved, ts.createMap); + } + function getOutputDeclarationFileName(inputFileName, configFile) { + var relativePath = ts.getRelativePathFromDirectory(rootDirOfOptions(configFile.options, configFile.options.configFilePath), inputFileName, true); + var outputPath = ts.resolvePath(configFile.options.declarationDir || configFile.options.outDir || ts.getDirectoryPath(configFile.options.configFilePath), relativePath); + return ts.changeExtension(outputPath, ".d.ts"); + } + ts.getOutputDeclarationFileName = getOutputDeclarationFileName; + function getOutputJSFileName(inputFileName, configFile) { + var relativePath = ts.getRelativePathFromDirectory(rootDirOfOptions(configFile.options, configFile.options.configFilePath), inputFileName, true); + var outputPath = ts.resolvePath(configFile.options.outDir || ts.getDirectoryPath(configFile.options.configFilePath), relativePath); + var newExtension = ts.fileExtensionIs(inputFileName, ".json") ? ".json" : + ts.fileExtensionIs(inputFileName, ".tsx") && configFile.options.jsx === 1 ? ".jsx" : ".js"; + return ts.changeExtension(outputPath, newExtension); + } + function getOutputFileNames(inputFileName, configFile) { + if (configFile.options.outFile || configFile.options.out || ts.fileExtensionIs(inputFileName, ".d.ts")) { + return ts.emptyArray; + } + var outputs = []; + var js = getOutputJSFileName(inputFileName, configFile); + outputs.push(js); + if (configFile.options.sourceMap) { + outputs.push(js + ".map"); + } + if (ts.getEmitDeclarations(configFile.options) && !ts.fileExtensionIs(inputFileName, ".json")) { + var dts = getOutputDeclarationFileName(inputFileName, configFile); + outputs.push(dts); + if (configFile.options.declarationMap) { + outputs.push(dts + ".map"); + } + } + return outputs; + } + function getOutFileOutputs(project) { + var out = project.options.outFile || project.options.out; + if (!out) { + return ts.Debug.fail("outFile must be set"); + } + var outputs = []; + outputs.push(out); + if (project.options.sourceMap) { + outputs.push(out + ".map"); + } + if (ts.getEmitDeclarations(project.options)) { + var dts = ts.changeExtension(out, ".d.ts"); + outputs.push(dts); + if (project.options.declarationMap) { + outputs.push(dts + ".map"); + } + } + return outputs; + } + function rootDirOfOptions(opts, configFileName) { + return opts.rootDir || ts.getDirectoryPath(configFileName); + } + function newer(date1, date2) { + return date2 > date1 ? date2 : date1; + } + function isDeclarationFile(fileName) { + return ts.fileExtensionIs(fileName, ".d.ts"); + } + function createBuilderStatusReporter(system, pretty) { + return function (diagnostic) { + var output = pretty ? "[" + ts.formatColorAndReset(new Date().toLocaleTimeString(), ts.ForegroundColorEscapeSequences.Grey) + "] " : new Date().toLocaleTimeString() + " - "; + output += "" + ts.flattenDiagnosticMessageText(diagnostic.messageText, system.newLine) + (system.newLine + system.newLine); + system.write(output); + }; + } + ts.createBuilderStatusReporter = createBuilderStatusReporter; + function createSolutionBuilderHostBase(system, reportDiagnostic, reportSolutionBuilderStatus) { + if (system === void 0) { system = ts.sys; } + var host = ts.createCompilerHostWorker({}, undefined, system); + host.getModifiedTime = system.getModifiedTime ? function (path) { return system.getModifiedTime(path); } : function () { return undefined; }; + host.setModifiedTime = system.setModifiedTime ? function (path, date) { return system.setModifiedTime(path, date); } : ts.noop; + host.deleteFile = system.deleteFile ? function (path) { return system.deleteFile(path); } : ts.noop; + host.reportDiagnostic = reportDiagnostic || ts.createDiagnosticReporter(system); + host.reportSolutionBuilderStatus = reportSolutionBuilderStatus || createBuilderStatusReporter(system); + return host; + } + function createSolutionBuilderHost(system, reportDiagnostic, reportSolutionBuilderStatus, reportErrorSummary) { + if (system === void 0) { system = ts.sys; } + var host = createSolutionBuilderHostBase(system, reportDiagnostic, reportSolutionBuilderStatus); + host.reportErrorSummary = reportErrorSummary; + return host; + } + ts.createSolutionBuilderHost = createSolutionBuilderHost; + function createSolutionBuilderWithWatchHost(system, reportDiagnostic, reportSolutionBuilderStatus, reportWatchStatus) { + var host = createSolutionBuilderHostBase(system, reportDiagnostic, reportSolutionBuilderStatus); + var watchHost = ts.createWatchHost(system, reportWatchStatus); + host.onWatchStatusChange = watchHost.onWatchStatusChange; + host.watchFile = watchHost.watchFile; + host.watchDirectory = watchHost.watchDirectory; + host.setTimeout = watchHost.setTimeout; + host.clearTimeout = watchHost.clearTimeout; + return host; + } + ts.createSolutionBuilderWithWatchHost = createSolutionBuilderWithWatchHost; + function getCompilerOptionsOfBuildOptions(buildOptions) { + var result = {}; + ts.commonOptionsWithBuild.forEach(function (option) { + result[option.name] = buildOptions[option.name]; + }); + return result; + } + function createSolutionBuilder(host, rootNames, defaultOptions) { + var hostWithWatch = host; + var currentDirectory = host.getCurrentDirectory(); + var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames()); + var parseConfigFileHost = ts.parseConfigHostFromCompilerHost(host); + var options = defaultOptions; + var baseCompilerOptions = getCompilerOptionsOfBuildOptions(options); + var configFileCache = createFileMap(toPath); + var unchangedOutputs = createFileMap(toPath); + var projectStatus = createFileMap(toPath); + var missingRoots = ts.createMap(); + var globalDependencyGraph; + var writeFileName = function (s) { return host.trace && host.trace(s); }; + var readFileWithCache = function (f) { return host.readFile(f); }; + var diagnostics = createFileMap(toPath); + var projectPendingBuild = createFileMap(toPath); + var projectErrorsReported = createFileMap(toPath); + var invalidatedProjectQueue = []; + var nextProjectToBuild = 0; + var timerToBuildInvalidatedProject; + var reportFileChangeDetected = false; + var allWatchedWildcardDirectories = createFileMap(toPath); + var allWatchedInputFiles = createFileMap(toPath); + var allWatchedConfigFiles = createFileMap(toPath); + return { + buildAllProjects: buildAllProjects, + getUpToDateStatusOfFile: getUpToDateStatusOfFile, + cleanAllProjects: cleanAllProjects, + resetBuildContext: resetBuildContext, + getBuildGraph: getBuildGraph, + invalidateProject: invalidateProject, + buildInvalidatedProject: buildInvalidatedProject, + resolveProjectName: resolveProjectName, + startWatching: startWatching + }; + function toPath(fileName) { + return ts.toPath(fileName, currentDirectory, getCanonicalFileName); + } + function resetBuildContext(opts) { + if (opts === void 0) { opts = defaultOptions; } + options = opts; + baseCompilerOptions = getCompilerOptionsOfBuildOptions(options); + configFileCache.clear(); + unchangedOutputs.clear(); + projectStatus.clear(); + missingRoots.clear(); + globalDependencyGraph = undefined; + diagnostics.clear(); + projectPendingBuild.clear(); + projectErrorsReported.clear(); + invalidatedProjectQueue.length = 0; + nextProjectToBuild = 0; + if (timerToBuildInvalidatedProject) { + clearTimeout(timerToBuildInvalidatedProject); + timerToBuildInvalidatedProject = undefined; + } + reportFileChangeDetected = false; + ts.clearMap(allWatchedWildcardDirectories, function (wildCardWatches) { return ts.clearMap(wildCardWatches, ts.closeFileWatcherOf); }); + ts.clearMap(allWatchedInputFiles, function (inputFileWatches) { return ts.clearMap(inputFileWatches, ts.closeFileWatcher); }); + ts.clearMap(allWatchedConfigFiles, ts.closeFileWatcher); + } + function isParsedCommandLine(entry) { + return !!entry.options; + } + function parseConfigFile(configFilePath) { + var value = configFileCache.getValue(configFilePath); + if (value) { + return isParsedCommandLine(value) ? value : undefined; + } + var diagnostic; + parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = function (d) { return diagnostic = d; }; + var parsed = ts.getParsedCommandLineOfConfigFile(configFilePath, baseCompilerOptions, parseConfigFileHost); + parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = ts.noop; + configFileCache.setValue(configFilePath, parsed || diagnostic); + return parsed; + } + function reportStatus(message) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + host.reportSolutionBuilderStatus(ts.createCompilerDiagnostic.apply(void 0, [message].concat(args))); + } + function reportWatchStatus(message) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + if (hostWithWatch.onWatchStatusChange) { + hostWithWatch.onWatchStatusChange(ts.createCompilerDiagnostic.apply(void 0, [message].concat(args)), host.getNewLine(), baseCompilerOptions); + } + } + function startWatching() { + var graph = getGlobalDependencyGraph(); + for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { + var resolved = _a[_i]; + watchConfigFile(resolved); + var cfg = parseConfigFile(resolved); + if (cfg) { + watchWildCardDirectories(resolved, cfg); + watchInputFiles(resolved, cfg); + } + } + } + function watchConfigFile(resolved) { + if (options.watch && !allWatchedConfigFiles.hasKey(resolved)) { + allWatchedConfigFiles.setValue(resolved, hostWithWatch.watchFile(resolved, function () { + invalidateProjectAndScheduleBuilds(resolved, ts.ConfigFileProgramReloadLevel.Full); + })); + } + } + function watchWildCardDirectories(resolved, parsed) { + if (!options.watch) + return; + ts.updateWatchingWildcardDirectories(getOrCreateValueMapFromConfigFileMap(allWatchedWildcardDirectories, resolved), ts.createMapFromTemplate(parsed.configFileSpecs.wildcardDirectories), function (dir, flags) { + return hostWithWatch.watchDirectory(dir, function (fileOrDirectory) { + var fileOrDirectoryPath = toPath(fileOrDirectory); + if (fileOrDirectoryPath !== toPath(dir) && ts.hasExtension(fileOrDirectoryPath) && !ts.isSupportedSourceFileName(fileOrDirectory, parsed.options)) { + return; + } + if (isOutputFile(fileOrDirectory, parsed)) { + return; + } + invalidateProjectAndScheduleBuilds(resolved, ts.ConfigFileProgramReloadLevel.Partial); + }, !!(flags & 1)); + }); + } + function watchInputFiles(resolved, parsed) { + if (!options.watch) + return; + ts.mutateMap(getOrCreateValueMapFromConfigFileMap(allWatchedInputFiles, resolved), ts.arrayToMap(parsed.fileNames, toPath), { + createNewValue: function (_key, input) { return hostWithWatch.watchFile(input, function () { + invalidateProjectAndScheduleBuilds(resolved, ts.ConfigFileProgramReloadLevel.None); + }); }, + onDeleteValue: ts.closeFileWatcher, + }); + } + function isOutputFile(fileName, configFile) { + if (configFile.options.noEmit) + return false; + if (!ts.fileExtensionIs(fileName, ".d.ts") && + (ts.fileExtensionIs(fileName, ".ts") || ts.fileExtensionIs(fileName, ".tsx"))) { + return false; + } + var out = configFile.options.outFile || configFile.options.out; + if (out && (isSameFile(fileName, out) || isSameFile(fileName, ts.removeFileExtension(out) + ".d.ts"))) { + return true; + } + if (configFile.options.declarationDir && ts.containsPath(configFile.options.declarationDir, fileName, currentDirectory, !host.useCaseSensitiveFileNames())) { + return true; + } + if (configFile.options.outDir && ts.containsPath(configFile.options.outDir, fileName, currentDirectory, !host.useCaseSensitiveFileNames())) { + return true; + } + return !ts.forEach(configFile.fileNames, function (inputFile) { return isSameFile(fileName, inputFile); }); + } + function isSameFile(file1, file2) { + return ts.comparePaths(file1, file2, currentDirectory, !host.useCaseSensitiveFileNames()) === 0; + } + function invalidateProjectAndScheduleBuilds(resolved, reloadLevel) { + reportFileChangeDetected = true; + invalidateResolvedProject(resolved, reloadLevel); + scheduleBuildInvalidatedProject(); + } + function getUpToDateStatusOfFile(configFileName) { + return getUpToDateStatus(parseConfigFile(configFileName)); + } + function getBuildGraph(configFileNames) { + return createDependencyGraph(resolveProjectNames(configFileNames)); + } + function getGlobalDependencyGraph() { + return globalDependencyGraph || (globalDependencyGraph = getBuildGraph(rootNames)); + } + function getUpToDateStatus(project) { + if (project === undefined) { + return { type: UpToDateStatusType.Unbuildable, reason: "File deleted mid-build" }; + } + var prior = projectStatus.getValue(project.options.configFilePath); + if (prior !== undefined) { + return prior; + } + var actual = getUpToDateStatusWorker(project); + projectStatus.setValue(project.options.configFilePath, actual); + return actual; + } + function getUpToDateStatusWorker(project) { + var newestInputFileName = undefined; + var newestInputFileTime = minimumDate; + for (var _i = 0, _a = project.fileNames; _i < _a.length; _i++) { + var inputFile = _a[_i]; + if (!host.fileExists(inputFile)) { + return { + type: UpToDateStatusType.Unbuildable, + reason: inputFile + " does not exist" + }; + } + var inputTime = host.getModifiedTime(inputFile) || ts.missingFileModifiedTime; + if (inputTime > newestInputFileTime) { + newestInputFileName = inputFile; + newestInputFileTime = inputTime; + } + } + var outputs = getAllProjectOutputs(project); + if (outputs.length === 0) { + return { + type: UpToDateStatusType.ContainerOnly + }; + } + var oldestOutputFileName = "(none)"; + var oldestOutputFileTime = maximumDate; + var newestOutputFileName = "(none)"; + var newestOutputFileTime = minimumDate; + var missingOutputFileName; + var newestDeclarationFileContentChangedTime = minimumDate; + var isOutOfDateWithInputs = false; + for (var _b = 0, outputs_1 = outputs; _b < outputs_1.length; _b++) { + var output = outputs_1[_b]; + if (!host.fileExists(output)) { + missingOutputFileName = output; + break; + } + var outputTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; + if (outputTime < oldestOutputFileTime) { + oldestOutputFileTime = outputTime; + oldestOutputFileName = output; + } + if (outputTime < newestInputFileTime) { + isOutOfDateWithInputs = true; + break; + } + if (outputTime > newestOutputFileTime) { + newestOutputFileTime = outputTime; + newestOutputFileName = output; + } + if (isDeclarationFile(output)) { + var unchangedTime = unchangedOutputs.getValue(output); + if (unchangedTime !== undefined) { + newestDeclarationFileContentChangedTime = newer(unchangedTime, newestDeclarationFileContentChangedTime); + } + else { + var outputModifiedTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; + newestDeclarationFileContentChangedTime = newer(newestDeclarationFileContentChangedTime, outputModifiedTime); + } + } + } + var pseudoUpToDate = false; + var usesPrepend = false; + var upstreamChangedProject; + if (project.projectReferences) { + projectStatus.setValue(project.options.configFilePath, { type: UpToDateStatusType.ComputingUpstream }); + for (var _c = 0, _d = project.projectReferences; _c < _d.length; _c++) { + var ref = _d[_c]; + usesPrepend = usesPrepend || !!(ref.prepend); + var resolvedRef = ts.resolveProjectReferencePath(ref); + var refStatus = getUpToDateStatus(parseConfigFile(resolvedRef)); + if (refStatus.type === UpToDateStatusType.ComputingUpstream) { + continue; + } + if (refStatus.type === UpToDateStatusType.Unbuildable) { + return { + type: UpToDateStatusType.UpstreamBlocked, + upstreamProjectName: ref.path + }; + } + if (refStatus.type !== UpToDateStatusType.UpToDate) { + return { + type: UpToDateStatusType.UpstreamOutOfDate, + upstreamProjectName: ref.path + }; + } + if (refStatus.newestInputFileTime && refStatus.newestInputFileTime <= oldestOutputFileTime) { + continue; + } + if (refStatus.newestDeclarationFileContentChangedTime && refStatus.newestDeclarationFileContentChangedTime <= oldestOutputFileTime) { + pseudoUpToDate = true; + upstreamChangedProject = ref.path; + continue; + } + ts.Debug.assert(oldestOutputFileName !== undefined, "Should have an oldest output filename here"); + return { + type: UpToDateStatusType.OutOfDateWithUpstream, + outOfDateOutputFileName: oldestOutputFileName, + newerProjectName: ref.path + }; + } + } + if (missingOutputFileName !== undefined) { + return { + type: UpToDateStatusType.OutputMissing, + missingOutputFileName: missingOutputFileName + }; + } + if (isOutOfDateWithInputs) { + return { + type: UpToDateStatusType.OutOfDateWithSelf, + outOfDateOutputFileName: oldestOutputFileName, + newerInputFileName: newestInputFileName + }; + } + if (usesPrepend && pseudoUpToDate) { + return { + type: UpToDateStatusType.OutOfDateWithUpstream, + outOfDateOutputFileName: oldestOutputFileName, + newerProjectName: upstreamChangedProject + }; + } + return { + type: pseudoUpToDate ? UpToDateStatusType.UpToDateWithUpstreamTypes : UpToDateStatusType.UpToDate, + newestDeclarationFileContentChangedTime: newestDeclarationFileContentChangedTime, + newestInputFileTime: newestInputFileTime, + newestOutputFileTime: newestOutputFileTime, + newestInputFileName: newestInputFileName, + newestOutputFileName: newestOutputFileName, + oldestOutputFileName: oldestOutputFileName + }; + } + function invalidateProject(configFileName, reloadLevel) { + invalidateResolvedProject(resolveProjectName(configFileName), reloadLevel); + } + function invalidateResolvedProject(resolved, reloadLevel) { + if (reloadLevel === ts.ConfigFileProgramReloadLevel.Full) { + configFileCache.removeKey(resolved); + globalDependencyGraph = undefined; + } + projectStatus.removeKey(resolved); + diagnostics.removeKey(resolved); + addProjToQueue(resolved, reloadLevel); + } + function addProjToQueue(proj, reloadLevel) { + var value = projectPendingBuild.getValue(proj); + if (value === undefined) { + projectPendingBuild.setValue(proj, reloadLevel || ts.ConfigFileProgramReloadLevel.None); + invalidatedProjectQueue.push(proj); + } + else if (value < (reloadLevel || ts.ConfigFileProgramReloadLevel.None)) { + projectPendingBuild.setValue(proj, reloadLevel || ts.ConfigFileProgramReloadLevel.None); + } + } + function getNextInvalidatedProject() { + if (nextProjectToBuild < invalidatedProjectQueue.length) { + var project = invalidatedProjectQueue[nextProjectToBuild]; + nextProjectToBuild++; + var reloadLevel = projectPendingBuild.getValue(project); + projectPendingBuild.removeKey(project); + if (!projectPendingBuild.getSize()) { + invalidatedProjectQueue.length = 0; + nextProjectToBuild = 0; + } + return { project: project, reloadLevel: reloadLevel }; + } + } + function hasPendingInvalidatedProjects() { + return !!projectPendingBuild.getSize(); + } + function scheduleBuildInvalidatedProject() { + if (!hostWithWatch.setTimeout || !hostWithWatch.clearTimeout) { + return; + } + if (timerToBuildInvalidatedProject) { + hostWithWatch.clearTimeout(timerToBuildInvalidatedProject); + } + timerToBuildInvalidatedProject = hostWithWatch.setTimeout(buildInvalidatedProject, 250); + } + function buildInvalidatedProject() { + timerToBuildInvalidatedProject = undefined; + if (reportFileChangeDetected) { + reportFileChangeDetected = false; + projectErrorsReported.clear(); + reportWatchStatus(ts.Diagnostics.File_change_detected_Starting_incremental_compilation); + } + var buildProject = getNextInvalidatedProject(); + if (buildProject) { + buildSingleInvalidatedProject(buildProject.project, buildProject.reloadLevel); + if (hasPendingInvalidatedProjects()) { + if (options.watch && !timerToBuildInvalidatedProject) { + scheduleBuildInvalidatedProject(); + } + } + else { + reportErrorSummary(); + } + } + } + function reportErrorSummary() { + if (options.watch || host.reportErrorSummary) { + getGlobalDependencyGraph().buildQueue.forEach(function (project) { + if (!projectErrorsReported.hasKey(project)) { + reportErrors(diagnostics.getValue(project) || ts.emptyArray); + } + }); + var totalErrors_1 = 0; + diagnostics.forEach(function (singleProjectErrors) { return totalErrors_1 += ts.getErrorCountForSummary(singleProjectErrors); }); + if (options.watch) { + reportWatchStatus(ts.getWatchErrorSummaryDiagnosticMessage(totalErrors_1), totalErrors_1); + } + else { + host.reportErrorSummary(totalErrors_1); + } + } + } + function buildSingleInvalidatedProject(resolved, reloadLevel) { + var proj = parseConfigFile(resolved); + if (!proj) { + reportParseConfigFileDiagnostic(resolved); + return; + } + if (reloadLevel === ts.ConfigFileProgramReloadLevel.Full) { + watchConfigFile(resolved); + watchWildCardDirectories(resolved, proj); + watchInputFiles(resolved, proj); + } + else if (reloadLevel === ts.ConfigFileProgramReloadLevel.Partial) { + var result = ts.getFileNamesFromConfigSpecs(proj.configFileSpecs, ts.getDirectoryPath(resolved), proj.options, parseConfigFileHost); + ts.updateErrorForNoInputFiles(result, resolved, proj.configFileSpecs, proj.errors, ts.canJsonReportNoInutFiles(proj.raw)); + proj.fileNames = result.fileNames; + watchInputFiles(resolved, proj); + } + var status = getUpToDateStatus(proj); + verboseReportProjectStatus(resolved, status); + if (status.type === UpToDateStatusType.UpstreamBlocked) { + if (options.verbose) + reportStatus(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, resolved, status.upstreamProjectName); + return; + } + var buildResult = buildSingleProject(resolved); + var dependencyGraph = getGlobalDependencyGraph(); + var referencingProjects = dependencyGraph.referencingProjectsMap.getValue(resolved); + if (!referencingProjects) + return; + for (var _i = 0, _a = dependencyGraph.buildQueue; _i < _a.length; _i++) { + var project = _a[_i]; + var prepend = referencingProjects.getValue(project); + if (prepend || (prepend !== undefined && !(buildResult & BuildResultFlags.DeclarationOutputUnchanged))) { + addProjToQueue(project); + } + } + } + function createDependencyGraph(roots) { + var temporaryMarks = createFileMap(toPath); + var permanentMarks = createFileMap(toPath); + var circularityReportStack = []; + var buildOrder = []; + var referencingProjectsMap = createFileMap(toPath); + for (var _i = 0, roots_1 = roots; _i < roots_1.length; _i++) { + var root = roots_1[_i]; + visit(root); + } + return { + buildQueue: buildOrder, + referencingProjectsMap: referencingProjectsMap + }; + function visit(projPath, inCircularContext) { + if (permanentMarks.hasKey(projPath)) + return; + if (temporaryMarks.hasKey(projPath)) { + if (!inCircularContext) { + reportStatus(ts.Diagnostics.Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0, circularityReportStack.join("\r\n")); + } + return; + } + temporaryMarks.setValue(projPath, true); + circularityReportStack.push(projPath); + var parsed = parseConfigFile(projPath); + if (parsed && parsed.projectReferences) { + for (var _i = 0, _a = parsed.projectReferences; _i < _a.length; _i++) { + var ref = _a[_i]; + var resolvedRefPath = resolveProjectName(ref.path); + visit(resolvedRefPath, inCircularContext || ref.circular); + var referencingProjects = getOrCreateValueFromConfigFileMap(referencingProjectsMap, resolvedRefPath, function () { return createFileMap(toPath); }); + referencingProjects.setValue(projPath, !!ref.prepend); + } + } + circularityReportStack.pop(); + permanentMarks.setValue(projPath, true); + buildOrder.push(projPath); + } + } + function buildSingleProject(proj) { + if (options.dry) { + reportStatus(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj); + return BuildResultFlags.Success; + } + if (options.verbose) + reportStatus(ts.Diagnostics.Building_project_0, proj); + var resultFlags = BuildResultFlags.None; + resultFlags |= BuildResultFlags.DeclarationOutputUnchanged; + var configFile = parseConfigFile(proj); + if (!configFile) { + resultFlags |= BuildResultFlags.ConfigFileErrors; + reportParseConfigFileDiagnostic(proj); + projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Config file errors" }); + return resultFlags; + } + if (configFile.fileNames.length === 0) { + reportAndStoreErrors(proj, configFile.errors); + return BuildResultFlags.None; + } + var programOptions = { + projectReferences: configFile.projectReferences, + host: host, + rootNames: configFile.fileNames, + options: configFile.options, + configFileParsingDiagnostics: configFile.errors + }; + if (host.beforeCreateProgram) { + host.beforeCreateProgram(options); + } + var program = ts.createProgram(programOptions); + var syntaxDiagnostics = program.getOptionsDiagnostics().concat(program.getConfigFileParsingDiagnostics(), program.getSyntacticDiagnostics()); + if (syntaxDiagnostics.length) { + return buildErrors(syntaxDiagnostics, BuildResultFlags.SyntaxErrors, "Syntactic"); + } + var semanticDiagnostics = program.getSemanticDiagnostics(); + if (semanticDiagnostics.length) { + return buildErrors(semanticDiagnostics, BuildResultFlags.TypeErrors, "Semantic"); + } + var newestDeclarationFileContentChangedTime = minimumDate; + var anyDtsChanged = false; + var declDiagnostics; + var reportDeclarationDiagnostics = function (d) { return (declDiagnostics || (declDiagnostics = [])).push(d); }; + var outputFiles = []; + ts.emitFilesAndReportErrors(program, reportDeclarationDiagnostics, writeFileName, undefined, function (name, text, writeByteOrderMark) { return outputFiles.push({ name: name, text: text, writeByteOrderMark: writeByteOrderMark }); }); + if (declDiagnostics) { + return buildErrors(declDiagnostics, BuildResultFlags.DeclarationEmitErrors, "Declaration file"); + } + var emitterDiagnostics = ts.createDiagnosticCollection(); + outputFiles.forEach(function (_a) { + var name = _a.name, text = _a.text, writeByteOrderMark = _a.writeByteOrderMark; + var priorChangeTime; + if (!anyDtsChanged && isDeclarationFile(name)) { + if (host.fileExists(name) && readFileWithCache(name) === text) { + priorChangeTime = host.getModifiedTime(name); + } + else { + resultFlags &= ~BuildResultFlags.DeclarationOutputUnchanged; + anyDtsChanged = true; + } + } + ts.writeFile(host, emitterDiagnostics, name, text, writeByteOrderMark); + if (priorChangeTime !== undefined) { + newestDeclarationFileContentChangedTime = newer(priorChangeTime, newestDeclarationFileContentChangedTime); + unchangedOutputs.setValue(name, priorChangeTime); + } + }); + var emitDiagnostics = emitterDiagnostics.getDiagnostics(); + if (emitDiagnostics.length) { + return buildErrors(emitDiagnostics, BuildResultFlags.EmitErrors, "Emit"); + } + var status = { + type: UpToDateStatusType.UpToDate, + newestDeclarationFileContentChangedTime: anyDtsChanged ? maximumDate : newestDeclarationFileContentChangedTime + }; + diagnostics.removeKey(proj); + projectStatus.setValue(proj, status); + if (host.afterProgramEmitAndDiagnostics) { + host.afterProgramEmitAndDiagnostics(program); + } + return resultFlags; + function buildErrors(diagnostics, errorFlags, errorType) { + resultFlags |= errorFlags; + reportAndStoreErrors(proj, diagnostics); + projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: errorType + " errors" }); + if (host.afterProgramEmitAndDiagnostics) { + host.afterProgramEmitAndDiagnostics(program); + } + return resultFlags; + } + } + function updateOutputTimestamps(proj) { + if (options.dry) { + return reportStatus(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj.options.configFilePath); + } + if (options.verbose) { + reportStatus(ts.Diagnostics.Updating_output_timestamps_of_project_0, proj.options.configFilePath); + } + var now = new Date(); + var outputs = getAllProjectOutputs(proj); + var priorNewestUpdateTime = minimumDate; + for (var _i = 0, outputs_2 = outputs; _i < outputs_2.length; _i++) { + var file = outputs_2[_i]; + if (isDeclarationFile(file)) { + priorNewestUpdateTime = newer(priorNewestUpdateTime, host.getModifiedTime(file) || ts.missingFileModifiedTime); + } + host.setModifiedTime(file, now); + } + projectStatus.setValue(proj.options.configFilePath, { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: priorNewestUpdateTime }); + } + function getFilesToClean() { + var graph = getGlobalDependencyGraph(); + var filesToDelete = []; + for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { + var proj = _a[_i]; + var parsed = parseConfigFile(proj); + if (parsed === undefined) { + reportParseConfigFileDiagnostic(proj); + continue; + } + var outputs = getAllProjectOutputs(parsed); + for (var _b = 0, outputs_3 = outputs; _b < outputs_3.length; _b++) { + var output = outputs_3[_b]; + if (host.fileExists(output)) { + filesToDelete.push(output); + } + } + } + return filesToDelete; + } + function cleanAllProjects() { + var filesToDelete = getFilesToClean(); + if (options.dry) { + reportStatus(ts.Diagnostics.A_non_dry_build_would_delete_the_following_files_Colon_0, filesToDelete.map(function (f) { return "\r\n * " + f; }).join("")); + return ts.ExitStatus.Success; + } + for (var _i = 0, filesToDelete_1 = filesToDelete; _i < filesToDelete_1.length; _i++) { + var output = filesToDelete_1[_i]; + host.deleteFile(output); + } + return ts.ExitStatus.Success; + } + function resolveProjectName(name) { + return resolveConfigFileProjectName(ts.resolvePath(host.getCurrentDirectory(), name)); + } + function resolveProjectNames(configFileNames) { + return configFileNames.map(resolveProjectName); + } + function buildAllProjects() { + if (options.watch) { + reportWatchStatus(ts.Diagnostics.Starting_compilation_in_watch_mode); + } + var _a = ts.changeCompilerHostToUseCache(host, toPath, true), originalReadFile = _a.originalReadFile, originalFileExists = _a.originalFileExists, originalDirectoryExists = _a.originalDirectoryExists, originalCreateDirectory = _a.originalCreateDirectory, originalWriteFile = _a.originalWriteFile, originalGetSourceFile = _a.originalGetSourceFile, newReadFileWithCache = _a.readFileWithCache; + var savedReadFileWithCache = readFileWithCache; + readFileWithCache = newReadFileWithCache; + var graph = getGlobalDependencyGraph(); + reportBuildQueue(graph); + var anyFailed = false; + for (var _i = 0, _b = graph.buildQueue; _i < _b.length; _i++) { + var next = _b[_i]; + var proj = parseConfigFile(next); + if (proj === undefined) { + reportParseConfigFileDiagnostic(next); + anyFailed = true; + break; + } + var errors = proj.errors; + var status = getUpToDateStatus(proj); + verboseReportProjectStatus(next, status); + var projName = proj.options.configFilePath; + if (status.type === UpToDateStatusType.UpToDate && !options.force) { + reportAndStoreErrors(next, errors); + if (defaultOptions.dry) { + reportStatus(ts.Diagnostics.Project_0_is_up_to_date, projName); + } + continue; + } + if (status.type === UpToDateStatusType.UpToDateWithUpstreamTypes && !options.force) { + reportAndStoreErrors(next, errors); + updateOutputTimestamps(proj); + continue; + } + if (status.type === UpToDateStatusType.UpstreamBlocked) { + reportAndStoreErrors(next, errors); + if (options.verbose) + reportStatus(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, projName, status.upstreamProjectName); + continue; + } + if (status.type === UpToDateStatusType.ContainerOnly) { + reportAndStoreErrors(next, errors); + continue; + } + var buildResult = buildSingleProject(next); + anyFailed = anyFailed || !!(buildResult & BuildResultFlags.AnyErrors); + } + reportErrorSummary(); + host.readFile = originalReadFile; + host.fileExists = originalFileExists; + host.directoryExists = originalDirectoryExists; + host.createDirectory = originalCreateDirectory; + host.writeFile = originalWriteFile; + readFileWithCache = savedReadFileWithCache; + host.getSourceFile = originalGetSourceFile; + return anyFailed ? ts.ExitStatus.DiagnosticsPresent_OutputsSkipped : ts.ExitStatus.Success; + } + function reportParseConfigFileDiagnostic(proj) { + reportAndStoreErrors(proj, [configFileCache.getValue(proj)]); + } + function reportAndStoreErrors(proj, errors) { + reportErrors(errors); + projectErrorsReported.setValue(proj, true); + diagnostics.setValue(proj, errors); + } + function reportErrors(errors) { + errors.forEach(function (err) { return host.reportDiagnostic(err); }); + } + function reportBuildQueue(graph) { + if (options.verbose) { + reportStatus(ts.Diagnostics.Projects_in_this_build_Colon_0, graph.buildQueue.map(function (s) { return "\r\n * " + relName(s); }).join("")); + } + } + function relName(path) { + return ts.convertToRelativePath(path, host.getCurrentDirectory(), function (f) { return host.getCanonicalFileName(f); }); + } + function verboseReportProjectStatus(configFileName, status) { + if (!options.verbose) + return; + return formatUpToDateStatus(configFileName, status, relName, reportStatus); + } + } + ts.createSolutionBuilder = createSolutionBuilder; + function resolveConfigFileProjectName(project) { + if (ts.fileExtensionIs(project, ".json")) { + return project; + } + return ts.combinePaths(project, "tsconfig.json"); + } + ts.resolveConfigFileProjectName = resolveConfigFileProjectName; + function getAllProjectOutputs(project) { + if (project.options.outFile || project.options.out) { + return getOutFileOutputs(project); + } + else { + var outputs = []; + for (var _i = 0, _a = project.fileNames; _i < _a.length; _i++) { + var inputFile = _a[_i]; + outputs.push.apply(outputs, getOutputFileNames(inputFile, project)); + } + return outputs; + } + } + ts.getAllProjectOutputs = getAllProjectOutputs; + function formatUpToDateStatus(configFileName, status, relName, formatMessage) { + switch (status.type) { + case UpToDateStatusType.OutOfDateWithSelf: + return formatMessage(ts.Diagnostics.Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2, relName(configFileName), relName(status.outOfDateOutputFileName), relName(status.newerInputFileName)); + case UpToDateStatusType.OutOfDateWithUpstream: + return formatMessage(ts.Diagnostics.Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2, relName(configFileName), relName(status.outOfDateOutputFileName), relName(status.newerProjectName)); + case UpToDateStatusType.OutputMissing: + return formatMessage(ts.Diagnostics.Project_0_is_out_of_date_because_output_file_1_does_not_exist, relName(configFileName), relName(status.missingOutputFileName)); + case UpToDateStatusType.UpToDate: + if (status.newestInputFileTime !== undefined) { + return formatMessage(ts.Diagnostics.Project_0_is_up_to_date_because_newest_input_1_is_older_than_oldest_output_2, relName(configFileName), relName(status.newestInputFileName || ""), relName(status.oldestOutputFileName || "")); + } + break; + case UpToDateStatusType.UpToDateWithUpstreamTypes: + return formatMessage(ts.Diagnostics.Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies, relName(configFileName)); + case UpToDateStatusType.UpstreamOutOfDate: + return formatMessage(ts.Diagnostics.Project_0_is_out_of_date_because_its_dependency_1_is_out_of_date, relName(configFileName), relName(status.upstreamProjectName)); + case UpToDateStatusType.UpstreamBlocked: + return formatMessage(ts.Diagnostics.Project_0_can_t_be_built_because_its_dependency_1_has_errors, relName(configFileName), relName(status.upstreamProjectName)); + case UpToDateStatusType.Unbuildable: + return formatMessage(ts.Diagnostics.Failed_to_parse_file_0_Colon_1, relName(configFileName), status.reason); + case UpToDateStatusType.ContainerOnly: + case UpToDateStatusType.ComputingUpstream: + break; + default: + ts.assertType(status); + } + } + ts.formatUpToDateStatus = formatUpToDateStatus; +})(ts || (ts = {})); +var ts; +(function (ts) { + function inspectModule(fileNameToRequire) { + return inspectValue(ts.removeFileExtension(ts.getBaseFileName(fileNameToRequire)), tryRequire(fileNameToRequire)); + } + ts.inspectModule = inspectModule; + function inspectValue(name, value) { + return getValueInfo(name, value, getRecurser()); + } + ts.inspectValue = inspectValue; + function getRecurser() { + var seen = new Set(); + var nameStack = []; + return function (obj, name, cbOk, cbFail) { + if (seen.has(obj) || nameStack.length > 4) { + return cbFail(seen.has(obj), nameStack); + } + seen.add(obj); + nameStack.push(name); + var res = cbOk(); + nameStack.pop(); + seen.delete(obj); + return res; + }; + } + function getValueInfo(name, value, recurser) { + return recurser(value, name, function () { + if (typeof value === "function") + return getFunctionOrClassInfo(value, name, recurser); + if (typeof value === "object") { + var builtin = getBuiltinType(name, value, recurser); + if (builtin !== undefined) + return builtin; + var entries = getEntriesOfObject(value); + var hasNontrivialPrototype = Object.getPrototypeOf(value) !== Object.prototype; + var members = ts.flatMap(entries, function (_a) { + var key = _a.key, value = _a.value; + return getValueInfo(key, value, recurser); + }); + return { kind: 3, name: name, hasNontrivialPrototype: hasNontrivialPrototype, members: members }; + } + return { kind: 0, name: name, typeName: isNullOrUndefined(value) ? "any" : typeof value }; + }, function (isCircularReference, keyStack) { return anyValue(name, " " + (isCircularReference ? "Circular reference" : "Too-deep object hierarchy") + " from " + keyStack.join(".")); }); + } + function getFunctionOrClassInfo(fn, name, recurser) { + var prototypeMembers = getPrototypeMembers(fn, recurser); + var namespaceMembers = ts.flatMap(getEntriesOfObject(fn), function (_a) { + var key = _a.key, value = _a.value; + return getValueInfo(key, value, recurser); + }); + var toString = ts.cast(Function.prototype.toString.call(fn), ts.isString); + var source = ts.stringContains(toString, "{ [native code] }") ? getFunctionLength(fn) : toString; + return { kind: 2, name: name, source: source, namespaceMembers: namespaceMembers, prototypeMembers: prototypeMembers }; + } + var builtins = ts.memoize(function () { + var map = ts.createMap(); + for (var _i = 0, _a = getEntriesOfObject(global); _i < _a.length; _i++) { + var _b = _a[_i], key = _b.key, value = _b.value; + if (typeof value === "function" && typeof value.prototype === "object" && value !== Object) { + map.set(key, value); + } + } + return map; + }); + function getBuiltinType(name, value, recurser) { + return ts.isArray(value) + ? { name: name, kind: 1, inner: value.length && getValueInfo("element", ts.first(value), recurser) || anyValue(name) } + : ts.forEachEntry(builtins(), function (builtin, builtinName) { + return value instanceof builtin ? { kind: 0, name: name, typeName: builtinName } : undefined; + }); + } + function getPrototypeMembers(fn, recurser) { + var prototype = fn.prototype; + return typeof prototype !== "object" || prototype === null ? ts.emptyArray : ts.mapDefined(getEntriesOfObject(prototype), function (_a) { + var key = _a.key, value = _a.value; + return key === "constructor" ? undefined : getValueInfo(key, value, recurser); + }); + } + var ignoredProperties = new Set(["arguments", "caller", "constructor", "eval", "super_"]); + var reservedFunctionProperties = new Set(Object.getOwnPropertyNames(ts.noop)); + function getEntriesOfObject(obj) { + var seen = ts.createMap(); + var entries = []; + var chain = obj; + while (!isNullOrUndefined(chain) && chain !== Object.prototype && chain !== Function.prototype) { + for (var _i = 0, _a = Object.getOwnPropertyNames(chain); _i < _a.length; _i++) { + var key = _a[_i]; + if (!isJsPrivate(key) && + !ignoredProperties.has(key) && + (typeof obj !== "function" || !reservedFunctionProperties.has(key)) && + ts.addToSeen(seen, key)) { + var value = safeGetPropertyOfObject(chain, key); + if (!(key === "toString" && typeof value === "function" && value.length === 0)) { + entries.push({ key: key, value: value }); + } + } + } + chain = Object.getPrototypeOf(chain); + } + return entries.sort(function (e1, e2) { return ts.compareStringsCaseSensitive(e1.key, e2.key); }); + } + function getFunctionLength(fn) { + return ts.tryCast(safeGetPropertyOfObject(fn, "length"), ts.isNumber) || 0; + } + function safeGetPropertyOfObject(obj, key) { + var desc = Object.getOwnPropertyDescriptor(obj, key); + return desc && desc.value; + } + function isNullOrUndefined(value) { + return value == null; + } + function anyValue(name, comment) { + return { kind: 0, name: name, typeName: "any", comment: comment }; + } + function isJsPrivate(name) { + return name.startsWith("_"); + } + ts.isJsPrivate = isJsPrivate; + function tryRequire(fileNameToRequire) { + try { + return require(fileNameToRequire); + } + catch (_a) { + return undefined; + } + } +})(ts || (ts = {})); +//# sourceMappingURL=compiler.release.js.map +var ts; +(function (ts) { + function countLines(program) { + var count = 0; + ts.forEach(program.getSourceFiles(), function (file) { + count += ts.getLineStarts(file).length; + }); + return count; + } + var reportDiagnostic = ts.createDiagnosticReporter(ts.sys); + function updateReportDiagnostic(options) { + if (shouldBePretty(options)) { + reportDiagnostic = ts.createDiagnosticReporter(ts.sys, /*pretty*/ true); + } + } + function defaultIsPretty() { + return !!ts.sys.writeOutputIsTTY && ts.sys.writeOutputIsTTY(); + } + function shouldBePretty(options) { + if (!options || typeof options.pretty === "undefined") { + return defaultIsPretty(); + } + return options.pretty; + } + function padLeft(s, length) { + while (s.length < length) { + s = " " + s; + } + return s; + } + function padRight(s, length) { + while (s.length < length) { + s = s + " "; + } + return s; + } + function getOptionsForHelp(commandLine) { + // Sort our options by their names, (e.g. "--noImplicitAny" comes before "--watch") + return !!commandLine.options.all ? + ts.sort(ts.optionDeclarations, function (a, b) { return ts.compareStringsCaseInsensitive(a.name, b.name); }) : + ts.filter(ts.optionDeclarations.slice(), function (v) { return !!v.showInSimplifiedHelpView; }); + } + function executeCommandLine(args) { + if (args.length > 0 && args[0].charCodeAt(0) === 45 /* minus */) { + var firstOption = args[0].slice(args[0].charCodeAt(1) === 45 /* minus */ ? 2 : 1).toLowerCase(); + if (firstOption === "build" || firstOption === "b") { + return performBuild(args.slice(1)); + } + } + var commandLine = ts.parseCommandLine(args); + if (commandLine.options.build) { + reportDiagnostic(ts.createCompilerDiagnostic(ts.Diagnostics.Option_build_must_be_the_first_command_line_argument)); + return ts.sys.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); + } + // Configuration file name (if any) + var configFileName; + if (commandLine.options.locale) { + ts.validateLocaleAndSetLanguage(commandLine.options.locale, ts.sys, commandLine.errors); + } + // If there are any errors due to command line parsing and/or + // setting up localization, report them and quit. + if (commandLine.errors.length > 0) { + commandLine.errors.forEach(reportDiagnostic); + return ts.sys.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); + } + if (commandLine.options.init) { + writeConfigFile(commandLine.options, commandLine.fileNames); + return ts.sys.exit(ts.ExitStatus.Success); + } + if (commandLine.options.version) { + ts.printVersion(); + return ts.sys.exit(ts.ExitStatus.Success); + } + if (commandLine.options.help || commandLine.options.all) { + ts.printVersion(); + ts.printHelp(getOptionsForHelp(commandLine)); + return ts.sys.exit(ts.ExitStatus.Success); + } + if (commandLine.options.project) { + if (commandLine.fileNames.length !== 0) { + reportDiagnostic(ts.createCompilerDiagnostic(ts.Diagnostics.Option_project_cannot_be_mixed_with_source_files_on_a_command_line)); + return ts.sys.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); + } + var fileOrDirectory = ts.normalizePath(commandLine.options.project); + if (!fileOrDirectory /* current directory "." */ || ts.sys.directoryExists(fileOrDirectory)) { + configFileName = ts.combinePaths(fileOrDirectory, "tsconfig.json"); + if (!ts.sys.fileExists(configFileName)) { + reportDiagnostic(ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_find_a_tsconfig_json_file_at_the_specified_directory_Colon_0, commandLine.options.project)); + return ts.sys.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); + } + } + else { + configFileName = fileOrDirectory; + if (!ts.sys.fileExists(configFileName)) { + reportDiagnostic(ts.createCompilerDiagnostic(ts.Diagnostics.The_specified_path_does_not_exist_Colon_0, commandLine.options.project)); + return ts.sys.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); + } + } + } + else if (commandLine.fileNames.length === 0) { + var searchPath = ts.normalizePath(ts.sys.getCurrentDirectory()); + configFileName = ts.findConfigFile(searchPath, ts.sys.fileExists); + } + if (commandLine.fileNames.length === 0 && !configFileName) { + ts.printVersion(); + ts.printHelp(getOptionsForHelp(commandLine)); + return ts.sys.exit(ts.ExitStatus.Success); + } + var commandLineOptions = commandLine.options; + if (configFileName) { + var configParseResult = ts.parseConfigFileWithSystem(configFileName, commandLineOptions, ts.sys, reportDiagnostic); // TODO: GH#18217 + if (commandLineOptions.showConfig) { + // tslint:disable-next-line:no-null-keyword + ts.sys.write(JSON.stringify(ts.convertToTSConfig(configParseResult, configFileName, ts.sys), null, 4) + ts.sys.newLine); + return ts.sys.exit(ts.ExitStatus.Success); + } + updateReportDiagnostic(configParseResult.options); + if (ts.isWatchSet(configParseResult.options)) { + reportWatchModeWithoutSysSupport(); + createWatchOfConfigFile(configParseResult, commandLineOptions); + } + else { + performCompilation(configParseResult.fileNames, configParseResult.projectReferences, configParseResult.options, ts.getConfigFileParsingDiagnostics(configParseResult)); + } + } + else { + if (commandLineOptions.showConfig) { + // tslint:disable-next-line:no-null-keyword + ts.sys.write(JSON.stringify(ts.convertToTSConfig(commandLine, ts.combinePaths(ts.sys.getCurrentDirectory(), "tsconfig.json"), ts.sys), null, 4) + ts.sys.newLine); + return ts.sys.exit(ts.ExitStatus.Success); + } + updateReportDiagnostic(commandLineOptions); + if (ts.isWatchSet(commandLineOptions)) { + reportWatchModeWithoutSysSupport(); + createWatchOfFilesAndCompilerOptions(commandLine.fileNames, commandLineOptions); + } + else { + performCompilation(commandLine.fileNames, /*references*/ undefined, commandLineOptions); + } + } + } + ts.executeCommandLine = executeCommandLine; + function reportWatchModeWithoutSysSupport() { + if (!ts.sys.watchFile || !ts.sys.watchDirectory) { + reportDiagnostic(ts.createCompilerDiagnostic(ts.Diagnostics.The_current_host_does_not_support_the_0_option, "--watch")); + ts.sys.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); + } + } + function performBuild(args) { + var _a = ts.parseBuildCommand(args), buildOptions = _a.buildOptions, projects = _a.projects, errors = _a.errors; + if (errors.length > 0) { + errors.forEach(reportDiagnostic); + return ts.sys.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); + } + if (buildOptions.help) { + ts.printVersion(); + ts.printHelp(ts.buildOpts, "--build "); + return ts.sys.exit(ts.ExitStatus.Success); + } + // Update to pretty if host supports it + updateReportDiagnostic(); + if (projects.length === 0) { + ts.printVersion(); + ts.printHelp(ts.buildOpts, "--build "); + return ts.sys.exit(ts.ExitStatus.Success); + } + if (!ts.sys.getModifiedTime || !ts.sys.setModifiedTime || (buildOptions.clean && !ts.sys.deleteFile)) { + reportDiagnostic(ts.createCompilerDiagnostic(ts.Diagnostics.The_current_host_does_not_support_the_0_option, "--build")); + return ts.sys.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); + } + if (buildOptions.watch) { + reportWatchModeWithoutSysSupport(); + } + // TODO: change this to host if watch => watchHost otherwiue without watch + var buildHost = buildOptions.watch ? + ts.createSolutionBuilderWithWatchHost(ts.sys, reportDiagnostic, ts.createBuilderStatusReporter(ts.sys, shouldBePretty()), createWatchStatusReporter()) : + ts.createSolutionBuilderHost(ts.sys, reportDiagnostic, ts.createBuilderStatusReporter(ts.sys, shouldBePretty()), createReportErrorSummary(buildOptions)); + buildHost.beforeCreateProgram = enableStatistics; + buildHost.afterProgramEmitAndDiagnostics = reportStatistics; + var builder = ts.createSolutionBuilder(buildHost, projects, buildOptions); + if (buildOptions.clean) { + return ts.sys.exit(builder.cleanAllProjects()); + } + if (buildOptions.watch) { + builder.buildAllProjects(); + return builder.startWatching(); + } + return ts.sys.exit(builder.buildAllProjects()); + } + function createReportErrorSummary(options) { + return shouldBePretty(options) ? + function (errorCount) { return ts.sys.write(ts.getErrorSummaryText(errorCount, ts.sys.newLine)); } : + undefined; + } + function performCompilation(rootNames, projectReferences, options, configFileParsingDiagnostics) { + var host = ts.createCompilerHost(options); + var currentDirectory = host.getCurrentDirectory(); + var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames()); + ts.changeCompilerHostToUseCache(host, function (fileName) { return ts.toPath(fileName, currentDirectory, getCanonicalFileName); }, /*useCacheForSourceFile*/ false); + enableStatistics(options); + var programOptions = { + rootNames: rootNames, + options: options, + projectReferences: projectReferences, + host: host, + configFileParsingDiagnostics: configFileParsingDiagnostics + }; + var program = ts.createProgram(programOptions); + var exitStatus = ts.emitFilesAndReportErrors(program, reportDiagnostic, function (s) { return ts.sys.write(s + ts.sys.newLine); }, createReportErrorSummary(options)); + reportStatistics(program); + return ts.sys.exit(exitStatus); + } + function updateWatchCompilationHost(watchCompilerHost) { + var compileUsingBuilder = watchCompilerHost.createProgram; + watchCompilerHost.createProgram = function (rootNames, options, host, oldProgram, configFileParsingDiagnostics, projectReferences) { + ts.Debug.assert(rootNames !== undefined || (options === undefined && !!oldProgram)); + if (options !== undefined) { + enableStatistics(options); + } + return compileUsingBuilder(rootNames, options, host, oldProgram, configFileParsingDiagnostics, projectReferences); + }; + var emitFilesUsingBuilder = watchCompilerHost.afterProgramCreate; // TODO: GH#18217 + watchCompilerHost.afterProgramCreate = function (builderProgram) { + emitFilesUsingBuilder(builderProgram); + reportStatistics(builderProgram.getProgram()); + }; + } + function createWatchStatusReporter(options) { + return ts.createWatchStatusReporter(ts.sys, shouldBePretty(options)); + } + function createWatchOfConfigFile(configParseResult, optionsToExtend) { + var watchCompilerHost = ts.createWatchCompilerHostOfConfigFile(configParseResult.options.configFilePath, optionsToExtend, ts.sys, /*createProgram*/ undefined, reportDiagnostic, createWatchStatusReporter(configParseResult.options)); // TODO: GH#18217 + updateWatchCompilationHost(watchCompilerHost); + watchCompilerHost.configFileParsingResult = configParseResult; + ts.createWatchProgram(watchCompilerHost); + } + function createWatchOfFilesAndCompilerOptions(rootFiles, options) { + var watchCompilerHost = ts.createWatchCompilerHostOfFilesAndCompilerOptions(rootFiles, options, ts.sys, /*createProgram*/ undefined, reportDiagnostic, createWatchStatusReporter(options)); + updateWatchCompilationHost(watchCompilerHost); + ts.createWatchProgram(watchCompilerHost); + } + function enableStatistics(compilerOptions) { + if (compilerOptions.diagnostics || compilerOptions.extendedDiagnostics) { + ts.performance.enable(); + } + } + function reportStatistics(program) { + var statistics; + var compilerOptions = program.getCompilerOptions(); + if (compilerOptions.diagnostics || compilerOptions.extendedDiagnostics) { + statistics = []; + var memoryUsed = ts.sys.getMemoryUsage ? ts.sys.getMemoryUsage() : -1; + reportCountStatistic("Files", program.getSourceFiles().length); + reportCountStatistic("Lines", countLines(program)); + reportCountStatistic("Nodes", program.getNodeCount()); + reportCountStatistic("Identifiers", program.getIdentifierCount()); + reportCountStatistic("Symbols", program.getSymbolCount()); + reportCountStatistic("Types", program.getTypeCount()); + if (memoryUsed >= 0) { + reportStatisticalValue("Memory used", Math.round(memoryUsed / 1000) + "K"); + } + var programTime = ts.performance.getDuration("Program"); + var bindTime = ts.performance.getDuration("Bind"); + var checkTime = ts.performance.getDuration("Check"); + var emitTime = ts.performance.getDuration("Emit"); + if (compilerOptions.extendedDiagnostics) { + ts.performance.forEachMeasure(function (name, duration) { return reportTimeStatistic(name + " time", duration); }); + } + else { + // Individual component times. + // Note: To match the behavior of previous versions of the compiler, the reported parse time includes + // I/O read time and processing time for triple-slash references and module imports, and the reported + // emit time includes I/O write time. We preserve this behavior so we can accurately compare times. + reportTimeStatistic("I/O read", ts.performance.getDuration("I/O Read")); + reportTimeStatistic("I/O write", ts.performance.getDuration("I/O Write")); + reportTimeStatistic("Parse time", programTime); + reportTimeStatistic("Bind time", bindTime); + reportTimeStatistic("Check time", checkTime); + reportTimeStatistic("Emit time", emitTime); + } + reportTimeStatistic("Total time", programTime + bindTime + checkTime + emitTime); + reportStatistics(); + ts.performance.disable(); + } + function reportStatistics() { + var nameSize = 0; + var valueSize = 0; + for (var _i = 0, statistics_1 = statistics; _i < statistics_1.length; _i++) { + var _a = statistics_1[_i], name = _a.name, value = _a.value; + if (name.length > nameSize) { + nameSize = name.length; + } + if (value.length > valueSize) { + valueSize = value.length; + } + } + for (var _b = 0, statistics_2 = statistics; _b < statistics_2.length; _b++) { + var _c = statistics_2[_b], name = _c.name, value = _c.value; + ts.sys.write(padRight(name + ":", nameSize + 2) + padLeft(value.toString(), valueSize) + ts.sys.newLine); + } + } + function reportStatisticalValue(name, value) { + statistics.push({ name: name, value: value }); + } + function reportCountStatistic(name, count) { + reportStatisticalValue(name, "" + count); + } + function reportTimeStatistic(name, time) { + reportStatisticalValue(name, (time / 1000).toFixed(2) + "s"); + } + } + function writeConfigFile(options, fileNames) { + var currentDirectory = ts.sys.getCurrentDirectory(); + var file = ts.normalizePath(ts.combinePaths(currentDirectory, "tsconfig.json")); + if (ts.sys.fileExists(file)) { + reportDiagnostic(ts.createCompilerDiagnostic(ts.Diagnostics.A_tsconfig_json_file_is_already_defined_at_Colon_0, file)); + } + else { + ts.sys.writeFile(file, ts.generateTSConfig(options, fileNames, ts.sys.newLine)); + reportDiagnostic(ts.createCompilerDiagnostic(ts.Diagnostics.Successfully_created_a_tsconfig_json_file)); + } + return; + } +})(ts || (ts = {})); +if (ts.Debug.isDebugging) { + ts.Debug.enableDebugInfo(); +} +if (ts.sys.tryEnableSourceMapsForHost && /^development$/i.test(ts.sys.getEnvironmentVariable("NODE_ENV"))) { + ts.sys.tryEnableSourceMapsForHost(); +} +if (ts.sys.setBlocking) { + ts.sys.setBlocking(); +} +ts.executeCommandLine(ts.sys.args); diff --git a/node_modules/typescript/lib/tsserver.js b/node_modules/typescript/lib/tsserver.js new file mode 100644 index 0000000..e8a957a --- /dev/null +++ b/node_modules/typescript/lib/tsserver.js @@ -0,0 +1,127465 @@ +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + + +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +var __assign = (this && this.__assign) || function () { + __assign = Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; + }; + return __assign.apply(this, arguments); +}; +"use strict"; +var __assign = (this && this.__assign) || function () { + __assign = Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; + }; + return __assign.apply(this, arguments); +}; +var __generator = (this && this.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } +}; +var __makeTemplateObject = (this && this.__makeTemplateObject) || function (cooked, raw) { + if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } + return cooked; +}; +var ts; +(function (ts) { + // WARNING: The script `configureNightly.ts` uses a regexp to parse out these values. + // If changing the text in this section, be sure to test `configureNightly` too. + ts.versionMajorMinor = "3.2"; + /** The version of the TypeScript compiler release */ + ts.version = ts.versionMajorMinor + ".2"; +})(ts || (ts = {})); +(function (ts) { + /* @internal */ + var Comparison; + (function (Comparison) { + Comparison[Comparison["LessThan"] = -1] = "LessThan"; + Comparison[Comparison["EqualTo"] = 0] = "EqualTo"; + Comparison[Comparison["GreaterThan"] = 1] = "GreaterThan"; + })(Comparison = ts.Comparison || (ts.Comparison = {})); +})(ts || (ts = {})); +/* @internal */ +(function (ts) { + ts.emptyArray = []; + /** Create a MapLike with good performance. */ + function createDictionaryObject() { + var map = Object.create(/*prototype*/ null); // tslint:disable-line:no-null-keyword + // Using 'delete' on an object causes V8 to put the object in dictionary mode. + // This disables creation of hidden classes, which are expensive when an object is + // constantly changing shape. + map.__ = undefined; + delete map.__; + return map; + } + /** Create a new map. If a template object is provided, the map will copy entries from it. */ + function createMap() { + return new ts.MapCtr(); + } + ts.createMap = createMap; + function createMapFromEntries(entries) { + var map = createMap(); + for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) { + var _a = entries_1[_i], key = _a[0], value = _a[1]; + map.set(key, value); + } + return map; + } + ts.createMapFromEntries = createMapFromEntries; + function createMapFromTemplate(template) { + var map = new ts.MapCtr(); + // Copies keys/values from template. Note that for..in will not throw if + // template is undefined, and instead will just exit the loop. + for (var key in template) { + if (hasOwnProperty.call(template, key)) { + map.set(key, template[key]); + } + } + return map; + } + ts.createMapFromTemplate = createMapFromTemplate; + // Internet Explorer's Map doesn't support iteration, so don't use it. + // tslint:disable-next-line no-in-operator variable-name + ts.MapCtr = typeof Map !== "undefined" && "entries" in Map.prototype ? Map : shimMap(); + // Keep the class inside a function so it doesn't get compiled if it's not used. + function shimMap() { + var MapIterator = /** @class */ (function () { + function MapIterator(data, selector) { + this.index = 0; + this.data = data; + this.selector = selector; + this.keys = Object.keys(data); + } + MapIterator.prototype.next = function () { + var index = this.index; + if (index < this.keys.length) { + this.index++; + return { value: this.selector(this.data, this.keys[index]), done: false }; + } + return { value: undefined, done: true }; + }; + return MapIterator; + }()); + return /** @class */ (function () { + function class_1() { + this.data = createDictionaryObject(); + this.size = 0; + } + class_1.prototype.get = function (key) { + return this.data[key]; + }; + class_1.prototype.set = function (key, value) { + if (!this.has(key)) { + this.size++; + } + this.data[key] = value; + return this; + }; + class_1.prototype.has = function (key) { + // tslint:disable-next-line:no-in-operator + return key in this.data; + }; + class_1.prototype.delete = function (key) { + if (this.has(key)) { + this.size--; + delete this.data[key]; + return true; + } + return false; + }; + class_1.prototype.clear = function () { + this.data = createDictionaryObject(); + this.size = 0; + }; + class_1.prototype.keys = function () { + return new MapIterator(this.data, function (_data, key) { return key; }); + }; + class_1.prototype.values = function () { + return new MapIterator(this.data, function (data, key) { return data[key]; }); + }; + class_1.prototype.entries = function () { + return new MapIterator(this.data, function (data, key) { return [key, data[key]]; }); + }; + class_1.prototype.forEach = function (action) { + for (var key in this.data) { + action(this.data[key], key); + } + }; + return class_1; + }()); + } + function length(array) { + return array ? array.length : 0; + } + ts.length = length; + /** + * Iterates through 'array' by index and performs the callback on each element of array until the callback + * returns a truthy value, then returns that value. + * If no such value is found, the callback is applied to each element of array and undefined is returned. + */ + function forEach(array, callback) { + if (array) { + for (var i = 0; i < array.length; i++) { + var result = callback(array[i], i); + if (result) { + return result; + } + } + } + return undefined; + } + ts.forEach = forEach; + /** Like `forEach`, but suitable for use with numbers and strings (which may be falsy). */ + function firstDefined(array, callback) { + if (array === undefined) { + return undefined; + } + for (var i = 0; i < array.length; i++) { + var result = callback(array[i], i); + if (result !== undefined) { + return result; + } + } + return undefined; + } + ts.firstDefined = firstDefined; + function firstDefinedIterator(iter, callback) { + while (true) { + var _a = iter.next(), value = _a.value, done = _a.done; + if (done) { + return undefined; + } + var result = callback(value); + if (result !== undefined) { + return result; + } + } + } + ts.firstDefinedIterator = firstDefinedIterator; + function zipWith(arrayA, arrayB, callback) { + var result = []; + Debug.assertEqual(arrayA.length, arrayB.length); + for (var i = 0; i < arrayA.length; i++) { + result.push(callback(arrayA[i], arrayB[i], i)); + } + return result; + } + ts.zipWith = zipWith; + function zipToIterator(arrayA, arrayB) { + Debug.assertEqual(arrayA.length, arrayB.length); + var i = 0; + return { + next: function () { + if (i === arrayA.length) { + return { value: undefined, done: true }; + } + i++; + return { value: [arrayA[i - 1], arrayB[i - 1]], done: false }; + } + }; + } + ts.zipToIterator = zipToIterator; + function zipToMap(keys, values) { + Debug.assert(keys.length === values.length); + var map = createMap(); + for (var i = 0; i < keys.length; ++i) { + map.set(keys[i], values[i]); + } + return map; + } + ts.zipToMap = zipToMap; + /** + * Iterates through `array` by index and performs the callback on each element of array until the callback + * returns a falsey value, then returns false. + * If no such value is found, the callback is applied to each element of array and `true` is returned. + */ + function every(array, callback) { + if (array) { + for (var i = 0; i < array.length; i++) { + if (!callback(array[i], i)) { + return false; + } + } + } + return true; + } + ts.every = every; + function find(array, predicate) { + for (var i = 0; i < array.length; i++) { + var value = array[i]; + if (predicate(value, i)) { + return value; + } + } + return undefined; + } + ts.find = find; + function findLast(array, predicate) { + for (var i = array.length - 1; i >= 0; i--) { + var value = array[i]; + if (predicate(value, i)) { + return value; + } + } + return undefined; + } + ts.findLast = findLast; + /** Works like Array.prototype.findIndex, returning `-1` if no element satisfying the predicate is found. */ + function findIndex(array, predicate, startIndex) { + for (var i = startIndex || 0; i < array.length; i++) { + if (predicate(array[i], i)) { + return i; + } + } + return -1; + } + ts.findIndex = findIndex; + function findLastIndex(array, predicate, startIndex) { + for (var i = startIndex === undefined ? array.length - 1 : startIndex; i >= 0; i--) { + if (predicate(array[i], i)) { + return i; + } + } + return -1; + } + ts.findLastIndex = findLastIndex; + /** + * Returns the first truthy result of `callback`, or else fails. + * This is like `forEach`, but never returns undefined. + */ + function findMap(array, callback) { + for (var i = 0; i < array.length; i++) { + var result = callback(array[i], i); + if (result) { + return result; + } + } + return Debug.fail(); + } + ts.findMap = findMap; + function contains(array, value, equalityComparer) { + if (equalityComparer === void 0) { equalityComparer = equateValues; } + if (array) { + for (var _i = 0, array_1 = array; _i < array_1.length; _i++) { + var v = array_1[_i]; + if (equalityComparer(v, value)) { + return true; + } + } + } + return false; + } + ts.contains = contains; + function arraysEqual(a, b, equalityComparer) { + if (equalityComparer === void 0) { equalityComparer = equateValues; } + return a.length === b.length && a.every(function (x, i) { return equalityComparer(x, b[i]); }); + } + ts.arraysEqual = arraysEqual; + function indexOfAnyCharCode(text, charCodes, start) { + for (var i = start || 0; i < text.length; i++) { + if (contains(charCodes, text.charCodeAt(i))) { + return i; + } + } + return -1; + } + ts.indexOfAnyCharCode = indexOfAnyCharCode; + function countWhere(array, predicate) { + var count = 0; + if (array) { + for (var i = 0; i < array.length; i++) { + var v = array[i]; + if (predicate(v, i)) { + count++; + } + } + } + return count; + } + ts.countWhere = countWhere; + function filter(array, f) { + if (array) { + var len = array.length; + var i = 0; + while (i < len && f(array[i])) + i++; + if (i < len) { + var result = array.slice(0, i); + i++; + while (i < len) { + var item = array[i]; + if (f(item)) { + result.push(item); + } + i++; + } + return result; + } + } + return array; + } + ts.filter = filter; + function filterMutate(array, f) { + var outIndex = 0; + for (var i = 0; i < array.length; i++) { + if (f(array[i], i, array)) { + array[outIndex] = array[i]; + outIndex++; + } + } + array.length = outIndex; + } + ts.filterMutate = filterMutate; + function clear(array) { + array.length = 0; + } + ts.clear = clear; + function map(array, f) { + var result; + if (array) { + result = []; + for (var i = 0; i < array.length; i++) { + result.push(f(array[i], i)); + } + } + return result; + } + ts.map = map; + function mapIterator(iter, mapFn) { + return { + next: function () { + var iterRes = iter.next(); + return iterRes.done ? iterRes : { value: mapFn(iterRes.value), done: false }; + } + }; + } + ts.mapIterator = mapIterator; + function sameMap(array, f) { + if (array) { + for (var i = 0; i < array.length; i++) { + var item = array[i]; + var mapped = f(item, i); + if (item !== mapped) { + var result = array.slice(0, i); + result.push(mapped); + for (i++; i < array.length; i++) { + result.push(f(array[i], i)); + } + return result; + } + } + } + return array; + } + ts.sameMap = sameMap; + function flatten(array) { + var result; + if (array) { + result = []; + for (var _i = 0, array_2 = array; _i < array_2.length; _i++) { + var v = array_2[_i]; + if (v) { + if (isArray(v)) { + addRange(result, v); + } + else { + result.push(v); + } + } + } + } + return result; + } + ts.flatten = flatten; + /** + * Maps an array. If the mapped value is an array, it is spread into the result. + * + * @param array The array to map. + * @param mapfn The callback used to map the result into one or more values. + */ + function flatMap(array, mapfn) { + var result; + if (array) { + for (var i = 0; i < array.length; i++) { + var v = mapfn(array[i], i); + if (v) { + if (isArray(v)) { + result = addRange(result, v); + } + else { + result = append(result, v); + } + } + } + } + return result || ts.emptyArray; + } + ts.flatMap = flatMap; + function flatMapToMutable(array, mapfn) { + var result = []; + if (array) { + for (var i = 0; i < array.length; i++) { + var v = mapfn(array[i], i); + if (v) { + if (isArray(v)) { + addRange(result, v); + } + else { + result.push(v); + } + } + } + } + return result; + } + ts.flatMapToMutable = flatMapToMutable; + function flatMapIterator(iter, mapfn) { + var first = iter.next(); + if (first.done) { + return ts.emptyIterator; + } + var currentIter = getIterator(first.value); + return { + next: function () { + while (true) { + var currentRes = currentIter.next(); + if (!currentRes.done) { + return currentRes; + } + var iterRes = iter.next(); + if (iterRes.done) { + return iterRes; + } + currentIter = getIterator(iterRes.value); + } + }, + }; + function getIterator(x) { + var res = mapfn(x); + return res === undefined ? ts.emptyIterator : isArray(res) ? arrayIterator(res) : res; + } + } + ts.flatMapIterator = flatMapIterator; + function sameFlatMap(array, mapfn) { + var result; + if (array) { + for (var i = 0; i < array.length; i++) { + var item = array[i]; + var mapped = mapfn(item, i); + if (result || item !== mapped || isArray(mapped)) { + if (!result) { + result = array.slice(0, i); + } + if (isArray(mapped)) { + addRange(result, mapped); + } + else { + result.push(mapped); + } + } + } + } + return result || array; + } + ts.sameFlatMap = sameFlatMap; + function mapAllOrFail(array, mapFn) { + var result = []; + for (var i = 0; i < array.length; i++) { + var mapped = mapFn(array[i], i); + if (mapped === undefined) { + return undefined; + } + result.push(mapped); + } + return result; + } + ts.mapAllOrFail = mapAllOrFail; + function mapDefined(array, mapFn) { + var result = []; + if (array) { + for (var i = 0; i < array.length; i++) { + var mapped = mapFn(array[i], i); + if (mapped !== undefined) { + result.push(mapped); + } + } + } + return result; + } + ts.mapDefined = mapDefined; + function mapDefinedIterator(iter, mapFn) { + return { + next: function () { + while (true) { + var res = iter.next(); + if (res.done) { + return res; + } + var value = mapFn(res.value); + if (value !== undefined) { + return { value: value, done: false }; + } + } + } + }; + } + ts.mapDefinedIterator = mapDefinedIterator; + ts.emptyIterator = { next: function () { return ({ value: undefined, done: true }); } }; + function singleIterator(value) { + var done = false; + return { + next: function () { + var wasDone = done; + done = true; + return wasDone ? { value: undefined, done: true } : { value: value, done: false }; + } + }; + } + ts.singleIterator = singleIterator; + function spanMap(array, keyfn, mapfn) { + var result; + if (array) { + result = []; + var len = array.length; + var previousKey = void 0; + var key = void 0; + var start = 0; + var pos = 0; + while (start < len) { + while (pos < len) { + var value = array[pos]; + key = keyfn(value, pos); + if (pos === 0) { + previousKey = key; + } + else if (key !== previousKey) { + break; + } + pos++; + } + if (start < pos) { + var v = mapfn(array.slice(start, pos), previousKey, start, pos); + if (v) { + result.push(v); + } + start = pos; + } + previousKey = key; + pos++; + } + } + return result; + } + ts.spanMap = spanMap; + function mapEntries(map, f) { + if (!map) { + return undefined; + } + var result = createMap(); + map.forEach(function (value, key) { + var _a = f(key, value), newKey = _a[0], newValue = _a[1]; + result.set(newKey, newValue); + }); + return result; + } + ts.mapEntries = mapEntries; + function some(array, predicate) { + if (array) { + if (predicate) { + for (var _i = 0, array_3 = array; _i < array_3.length; _i++) { + var v = array_3[_i]; + if (predicate(v)) { + return true; + } + } + } + else { + return array.length > 0; + } + } + return false; + } + ts.some = some; + /** Calls the callback with (start, afterEnd) index pairs for each range where 'pred' is true. */ + function getRangesWhere(arr, pred, cb) { + var start; + for (var i = 0; i < arr.length; i++) { + if (pred(arr[i])) { + start = start === undefined ? i : start; + } + else { + if (start !== undefined) { + cb(start, i); + start = undefined; + } + } + } + if (start !== undefined) + cb(start, arr.length); + } + ts.getRangesWhere = getRangesWhere; + function concatenate(array1, array2) { + if (!some(array2)) + return array1; + if (!some(array1)) + return array2; + return array1.concat(array2); + } + ts.concatenate = concatenate; + function deduplicateRelational(array, equalityComparer, comparer) { + // Perform a stable sort of the array. This ensures the first entry in a list of + // duplicates remains the first entry in the result. + var indices = array.map(function (_, i) { return i; }); + stableSortIndices(array, indices, comparer); + var last = array[indices[0]]; + var deduplicated = [indices[0]]; + for (var i = 1; i < indices.length; i++) { + var index = indices[i]; + var item = array[index]; + if (!equalityComparer(last, item)) { + deduplicated.push(index); + last = item; + } + } + // restore original order + deduplicated.sort(); + return deduplicated.map(function (i) { return array[i]; }); + } + function deduplicateEquality(array, equalityComparer) { + var result = []; + for (var _i = 0, array_4 = array; _i < array_4.length; _i++) { + var item = array_4[_i]; + pushIfUnique(result, item, equalityComparer); + } + return result; + } + /** + * Deduplicates an unsorted array. + * @param equalityComparer An optional `EqualityComparer` used to determine if two values are duplicates. + * @param comparer An optional `Comparer` used to sort entries before comparison, though the + * result will remain in the original order in `array`. + */ + function deduplicate(array, equalityComparer, comparer) { + return array.length === 0 ? [] : + array.length === 1 ? array.slice() : + comparer ? deduplicateRelational(array, equalityComparer, comparer) : + deduplicateEquality(array, equalityComparer); + } + ts.deduplicate = deduplicate; + /** + * Deduplicates an array that has already been sorted. + */ + function deduplicateSorted(array, comparer) { + if (array.length === 0) + return ts.emptyArray; + var last = array[0]; + var deduplicated = [last]; + for (var i = 1; i < array.length; i++) { + var next = array[i]; + switch (comparer(next, last)) { + // equality comparison + case true: + // relational comparison + case 0 /* EqualTo */: + continue; + case -1 /* LessThan */: + // If `array` is sorted, `next` should **never** be less than `last`. + return Debug.fail("Array is unsorted."); + } + deduplicated.push(last = next); + } + return deduplicated; + } + function insertSorted(array, insert, compare) { + if (array.length === 0) { + array.push(insert); + return; + } + var insertIndex = binarySearch(array, insert, identity, compare); + if (insertIndex < 0) { + array.splice(~insertIndex, 0, insert); + } + } + ts.insertSorted = insertSorted; + function sortAndDeduplicate(array, comparer, equalityComparer) { + return deduplicateSorted(sort(array, comparer), equalityComparer || comparer || compareStringsCaseSensitive); + } + ts.sortAndDeduplicate = sortAndDeduplicate; + function arrayIsEqualTo(array1, array2, equalityComparer) { + if (equalityComparer === void 0) { equalityComparer = equateValues; } + if (!array1 || !array2) { + return array1 === array2; + } + if (array1.length !== array2.length) { + return false; + } + for (var i = 0; i < array1.length; i++) { + if (!equalityComparer(array1[i], array2[i], i)) { + return false; + } + } + return true; + } + ts.arrayIsEqualTo = arrayIsEqualTo; + function compact(array) { + var result; + if (array) { + for (var i = 0; i < array.length; i++) { + var v = array[i]; + if (result || !v) { + if (!result) { + result = array.slice(0, i); + } + if (v) { + result.push(v); + } + } + } + } + return result || array; + } + ts.compact = compact; + /** + * Gets the relative complement of `arrayA` with respect to `arrayB`, returning the elements that + * are not present in `arrayA` but are present in `arrayB`. Assumes both arrays are sorted + * based on the provided comparer. + */ + function relativeComplement(arrayA, arrayB, comparer) { + if (!arrayB || !arrayA || arrayB.length === 0 || arrayA.length === 0) + return arrayB; + var result = []; + loopB: for (var offsetA = 0, offsetB = 0; offsetB < arrayB.length; offsetB++) { + if (offsetB > 0) { + // Ensure `arrayB` is properly sorted. + Debug.assertGreaterThanOrEqual(comparer(arrayB[offsetB], arrayB[offsetB - 1]), 0 /* EqualTo */); + } + loopA: for (var startA = offsetA; offsetA < arrayA.length; offsetA++) { + if (offsetA > startA) { + // Ensure `arrayA` is properly sorted. We only need to perform this check if + // `offsetA` has changed since we entered the loop. + Debug.assertGreaterThanOrEqual(comparer(arrayA[offsetA], arrayA[offsetA - 1]), 0 /* EqualTo */); + } + switch (comparer(arrayB[offsetB], arrayA[offsetA])) { + case -1 /* LessThan */: + // If B is less than A, B does not exist in arrayA. Add B to the result and + // move to the next element in arrayB without changing the current position + // in arrayA. + result.push(arrayB[offsetB]); + continue loopB; + case 0 /* EqualTo */: + // If B is equal to A, B exists in arrayA. Move to the next element in + // arrayB without adding B to the result or changing the current position + // in arrayA. + continue loopB; + case 1 /* GreaterThan */: + // If B is greater than A, we need to keep looking for B in arrayA. Move to + // the next element in arrayA and recheck. + continue loopA; + } + } + } + return result; + } + ts.relativeComplement = relativeComplement; + function sum(array, prop) { + var result = 0; + for (var _i = 0, array_5 = array; _i < array_5.length; _i++) { + var v = array_5[_i]; + result += v[prop]; + } + return result; + } + ts.sum = sum; + function append(to, value) { + if (value === undefined) + return to; + if (to === undefined) + return [value]; + to.push(value); + return to; + } + ts.append = append; + /** + * Gets the actual offset into an array for a relative offset. Negative offsets indicate a + * position offset from the end of the array. + */ + function toOffset(array, offset) { + return offset < 0 ? array.length + offset : offset; + } + function addRange(to, from, start, end) { + if (from === undefined || from.length === 0) + return to; + if (to === undefined) + return from.slice(start, end); + start = start === undefined ? 0 : toOffset(from, start); + end = end === undefined ? from.length : toOffset(from, end); + for (var i = start; i < end && i < from.length; i++) { + if (from[i] !== undefined) { + to.push(from[i]); + } + } + return to; + } + ts.addRange = addRange; + /** + * @return Whether the value was added. + */ + function pushIfUnique(array, toAdd, equalityComparer) { + if (contains(array, toAdd, equalityComparer)) { + return false; + } + else { + array.push(toAdd); + return true; + } + } + ts.pushIfUnique = pushIfUnique; + /** + * Unlike `pushIfUnique`, this can take `undefined` as an input, and returns a new array. + */ + function appendIfUnique(array, toAdd, equalityComparer) { + if (array) { + pushIfUnique(array, toAdd, equalityComparer); + return array; + } + else { + return [toAdd]; + } + } + ts.appendIfUnique = appendIfUnique; + function stableSortIndices(array, indices, comparer) { + // sort indices by value then position + indices.sort(function (x, y) { return comparer(array[x], array[y]) || compareValues(x, y); }); + } + /** + * Returns a new sorted array. + */ + function sort(array, comparer) { + return (array.length === 0 ? array : array.slice().sort(comparer)); + } + ts.sort = sort; + function arrayIterator(array) { + var i = 0; + return { next: function () { + if (i === array.length) { + return { value: undefined, done: true }; + } + else { + i++; + return { value: array[i - 1], done: false }; + } + } }; + } + ts.arrayIterator = arrayIterator; + /** + * Stable sort of an array. Elements equal to each other maintain their relative position in the array. + */ + function stableSort(array, comparer) { + var indices = array.map(function (_, i) { return i; }); + stableSortIndices(array, indices, comparer); + return indices.map(function (i) { return array[i]; }); + } + ts.stableSort = stableSort; + function rangeEquals(array1, array2, pos, end) { + while (pos < end) { + if (array1[pos] !== array2[pos]) { + return false; + } + pos++; + } + return true; + } + ts.rangeEquals = rangeEquals; + /** + * Returns the element at a specific offset in an array if non-empty, `undefined` otherwise. + * A negative offset indicates the element should be retrieved from the end of the array. + */ + function elementAt(array, offset) { + if (array) { + offset = toOffset(array, offset); + if (offset < array.length) { + return array[offset]; + } + } + return undefined; + } + ts.elementAt = elementAt; + /** + * Returns the first element of an array if non-empty, `undefined` otherwise. + */ + function firstOrUndefined(array) { + return array.length === 0 ? undefined : array[0]; + } + ts.firstOrUndefined = firstOrUndefined; + function first(array) { + Debug.assert(array.length !== 0); + return array[0]; + } + ts.first = first; + /** + * Returns the last element of an array if non-empty, `undefined` otherwise. + */ + function lastOrUndefined(array) { + return array.length === 0 ? undefined : array[array.length - 1]; + } + ts.lastOrUndefined = lastOrUndefined; + function last(array) { + Debug.assert(array.length !== 0); + return array[array.length - 1]; + } + ts.last = last; + /** + * Returns the only element of an array if it contains only one element, `undefined` otherwise. + */ + function singleOrUndefined(array) { + return array && array.length === 1 + ? array[0] + : undefined; + } + ts.singleOrUndefined = singleOrUndefined; + function singleOrMany(array) { + return array && array.length === 1 + ? array[0] + : array; + } + ts.singleOrMany = singleOrMany; + function replaceElement(array, index, value) { + var result = array.slice(0); + result[index] = value; + return result; + } + ts.replaceElement = replaceElement; + /** + * Performs a binary search, finding the index at which `value` occurs in `array`. + * If no such index is found, returns the 2's-complement of first index at which + * `array[index]` exceeds `value`. + * @param array A sorted array whose first element must be no larger than number + * @param value The value to be searched for in the array. + * @param keySelector A callback used to select the search key from `value` and each element of + * `array`. + * @param keyComparer A callback used to compare two keys in a sorted array. + * @param offset An offset into `array` at which to start the search. + */ + function binarySearch(array, value, keySelector, keyComparer, offset) { + return binarySearchKey(array, keySelector(value), keySelector, keyComparer, offset); + } + ts.binarySearch = binarySearch; + /** + * Performs a binary search, finding the index at which an object with `key` occurs in `array`. + * If no such index is found, returns the 2's-complement of first index at which + * `array[index]` exceeds `key`. + * @param array A sorted array whose first element must be no larger than number + * @param key The key to be searched for in the array. + * @param keySelector A callback used to select the search key from each element of `array`. + * @param keyComparer A callback used to compare two keys in a sorted array. + * @param offset An offset into `array` at which to start the search. + */ + function binarySearchKey(array, key, keySelector, keyComparer, offset) { + if (!some(array)) { + return -1; + } + var low = offset || 0; + var high = array.length - 1; + while (low <= high) { + var middle = low + ((high - low) >> 1); + var midKey = keySelector(array[middle]); + switch (keyComparer(midKey, key)) { + case -1 /* LessThan */: + low = middle + 1; + break; + case 0 /* EqualTo */: + return middle; + case 1 /* GreaterThan */: + high = middle - 1; + break; + } + } + return ~low; + } + ts.binarySearchKey = binarySearchKey; + function reduceLeft(array, f, initial, start, count) { + if (array && array.length > 0) { + var size = array.length; + if (size > 0) { + var pos = start === undefined || start < 0 ? 0 : start; + var end = count === undefined || pos + count > size - 1 ? size - 1 : pos + count; + var result = void 0; + if (arguments.length <= 2) { + result = array[pos]; + pos++; + } + else { + result = initial; + } + while (pos <= end) { + result = f(result, array[pos], pos); + pos++; + } + return result; + } + } + return initial; + } + ts.reduceLeft = reduceLeft; + var hasOwnProperty = Object.prototype.hasOwnProperty; + /** + * Indicates whether a map-like contains an own property with the specified key. + * + * @param map A map-like. + * @param key A property key. + */ + function hasProperty(map, key) { + return hasOwnProperty.call(map, key); + } + ts.hasProperty = hasProperty; + /** + * Gets the value of an owned property in a map-like. + * + * @param map A map-like. + * @param key A property key. + */ + function getProperty(map, key) { + return hasOwnProperty.call(map, key) ? map[key] : undefined; + } + ts.getProperty = getProperty; + /** + * Gets the owned, enumerable property keys of a map-like. + */ + function getOwnKeys(map) { + var keys = []; + for (var key in map) { + if (hasOwnProperty.call(map, key)) { + keys.push(key); + } + } + return keys; + } + ts.getOwnKeys = getOwnKeys; + function getOwnValues(sparseArray) { + var values = []; + for (var key in sparseArray) { + if (hasOwnProperty.call(sparseArray, key)) { + values.push(sparseArray[key]); + } + } + return values; + } + ts.getOwnValues = getOwnValues; + function arrayFrom(iterator, map) { + var _a; + var result = []; + for (var _b = iterator.next(), value = _b.value, done = _b.done; !done; _a = iterator.next(), value = _a.value, done = _a.done, _a) { + result.push(map ? map(value) : value); + } + return result; + } + ts.arrayFrom = arrayFrom; + function assign(t) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + for (var _a = 0, args_1 = args; _a < args_1.length; _a++) { + var arg = args_1[_a]; + for (var p in arg) { + if (hasProperty(arg, p)) { + t[p] = arg[p]; // TODO: GH#23368 + } + } + } + return t; + } + ts.assign = assign; + /** + * Performs a shallow equality comparison of the contents of two map-likes. + * + * @param left A map-like whose properties should be compared. + * @param right A map-like whose properties should be compared. + */ + function equalOwnProperties(left, right, equalityComparer) { + if (equalityComparer === void 0) { equalityComparer = equateValues; } + if (left === right) + return true; + if (!left || !right) + return false; + for (var key in left) { + if (hasOwnProperty.call(left, key)) { + if (!hasOwnProperty.call(right, key)) + return false; + if (!equalityComparer(left[key], right[key])) + return false; + } + } + for (var key in right) { + if (hasOwnProperty.call(right, key)) { + if (!hasOwnProperty.call(left, key)) + return false; + } + } + return true; + } + ts.equalOwnProperties = equalOwnProperties; + function arrayToMap(array, makeKey, makeValue) { + if (makeValue === void 0) { makeValue = identity; } + var result = createMap(); + for (var _i = 0, array_6 = array; _i < array_6.length; _i++) { + var value = array_6[_i]; + var key = makeKey(value); + if (key !== undefined) + result.set(key, makeValue(value)); + } + return result; + } + ts.arrayToMap = arrayToMap; + function arrayToNumericMap(array, makeKey, makeValue) { + if (makeValue === void 0) { makeValue = identity; } + var result = []; + for (var _i = 0, array_7 = array; _i < array_7.length; _i++) { + var value = array_7[_i]; + result[makeKey(value)] = makeValue(value); + } + return result; + } + ts.arrayToNumericMap = arrayToNumericMap; + function arrayToMultiMap(values, makeKey, makeValue) { + if (makeValue === void 0) { makeValue = identity; } + var result = createMultiMap(); + for (var _i = 0, values_1 = values; _i < values_1.length; _i++) { + var value = values_1[_i]; + result.add(makeKey(value), makeValue(value)); + } + return result; + } + ts.arrayToMultiMap = arrayToMultiMap; + function group(values, getGroupId) { + return arrayFrom(arrayToMultiMap(values, getGroupId).values()); + } + ts.group = group; + function clone(object) { + var result = {}; + for (var id in object) { + if (hasOwnProperty.call(object, id)) { + result[id] = object[id]; + } + } + return result; + } + ts.clone = clone; + function extend(first, second) { + var result = {}; + for (var id in second) { + if (hasOwnProperty.call(second, id)) { + result[id] = second[id]; + } + } + for (var id in first) { + if (hasOwnProperty.call(first, id)) { + result[id] = first[id]; + } + } + return result; + } + ts.extend = extend; + function createMultiMap() { + var map = createMap(); + map.add = multiMapAdd; + map.remove = multiMapRemove; + return map; + } + ts.createMultiMap = createMultiMap; + function multiMapAdd(key, value) { + var values = this.get(key); + if (values) { + values.push(value); + } + else { + this.set(key, values = [value]); + } + return values; + } + function multiMapRemove(key, value) { + var values = this.get(key); + if (values) { + unorderedRemoveItem(values, value); + if (!values.length) { + this.delete(key); + } + } + } + /** + * Tests whether a value is an array. + */ + function isArray(value) { + return Array.isArray ? Array.isArray(value) : value instanceof Array; + } + ts.isArray = isArray; + function toArray(value) { + return isArray(value) ? value : [value]; + } + ts.toArray = toArray; + /** + * Tests whether a value is string + */ + function isString(text) { + return typeof text === "string"; + } + ts.isString = isString; + function isNumber(x) { + return typeof x === "number"; + } + ts.isNumber = isNumber; + function tryCast(value, test) { + return value !== undefined && test(value) ? value : undefined; + } + ts.tryCast = tryCast; + function cast(value, test) { + if (value !== undefined && test(value)) + return value; + return Debug.fail("Invalid cast. The supplied value " + value + " did not pass the test '" + Debug.getFunctionName(test) + "'."); + } + ts.cast = cast; + /** Does nothing. */ + function noop(_) { } // tslint:disable-line no-empty + ts.noop = noop; + /** Do nothing and return false */ + function returnFalse() { return false; } + ts.returnFalse = returnFalse; + /** Do nothing and return true */ + function returnTrue() { return true; } + ts.returnTrue = returnTrue; + /** Returns its argument. */ + function identity(x) { return x; } + ts.identity = identity; + /** Returns lower case string */ + function toLowerCase(x) { return x.toLowerCase(); } + ts.toLowerCase = toLowerCase; + /** Throws an error because a function is not implemented. */ + function notImplemented() { + throw new Error("Not implemented"); + } + ts.notImplemented = notImplemented; + function memoize(callback) { + var value; + return function () { + if (callback) { + value = callback(); + callback = undefined; + } + return value; + }; + } + ts.memoize = memoize; + function chain(a, b, c, d, e) { + if (e) { + var args_2 = []; + for (var i = 0; i < arguments.length; i++) { + args_2[i] = arguments[i]; + } + return function (t) { return compose.apply(void 0, map(args_2, function (f) { return f(t); })); }; + } + else if (d) { + return function (t) { return compose(a(t), b(t), c(t), d(t)); }; + } + else if (c) { + return function (t) { return compose(a(t), b(t), c(t)); }; + } + else if (b) { + return function (t) { return compose(a(t), b(t)); }; + } + else if (a) { + return function (t) { return compose(a(t)); }; + } + else { + return function (_) { return function (u) { return u; }; }; + } + } + ts.chain = chain; + function compose(a, b, c, d, e) { + if (e) { + var args_3 = []; + for (var i = 0; i < arguments.length; i++) { + args_3[i] = arguments[i]; + } + return function (t) { return reduceLeft(args_3, function (u, f) { return f(u); }, t); }; + } + else if (d) { + return function (t) { return d(c(b(a(t)))); }; + } + else if (c) { + return function (t) { return c(b(a(t))); }; + } + else if (b) { + return function (t) { return b(a(t)); }; + } + else if (a) { + return function (t) { return a(t); }; + } + else { + return function (t) { return t; }; + } + } + ts.compose = compose; + var AssertionLevel; + (function (AssertionLevel) { + AssertionLevel[AssertionLevel["None"] = 0] = "None"; + AssertionLevel[AssertionLevel["Normal"] = 1] = "Normal"; + AssertionLevel[AssertionLevel["Aggressive"] = 2] = "Aggressive"; + AssertionLevel[AssertionLevel["VeryAggressive"] = 3] = "VeryAggressive"; + })(AssertionLevel = ts.AssertionLevel || (ts.AssertionLevel = {})); + var Debug; + (function (Debug) { + Debug.currentAssertionLevel = 0 /* None */; + Debug.isDebugging = false; + function shouldAssert(level) { + return Debug.currentAssertionLevel >= level; + } + Debug.shouldAssert = shouldAssert; + function assert(expression, message, verboseDebugInfo, stackCrawlMark) { + if (!expression) { + if (verboseDebugInfo) { + message += "\r\nVerbose Debug Information: " + (typeof verboseDebugInfo === "string" ? verboseDebugInfo : verboseDebugInfo()); + } + fail(message ? "False expression: " + message : "False expression.", stackCrawlMark || assert); + } + } + Debug.assert = assert; + function assertEqual(a, b, msg, msg2) { + if (a !== b) { + var message = msg ? msg2 ? msg + " " + msg2 : msg : ""; + fail("Expected " + a + " === " + b + ". " + message); + } + } + Debug.assertEqual = assertEqual; + function assertLessThan(a, b, msg) { + if (a >= b) { + fail("Expected " + a + " < " + b + ". " + (msg || "")); + } + } + Debug.assertLessThan = assertLessThan; + function assertLessThanOrEqual(a, b) { + if (a > b) { + fail("Expected " + a + " <= " + b); + } + } + Debug.assertLessThanOrEqual = assertLessThanOrEqual; + function assertGreaterThanOrEqual(a, b) { + if (a < b) { + fail("Expected " + a + " >= " + b); + } + } + Debug.assertGreaterThanOrEqual = assertGreaterThanOrEqual; + function fail(message, stackCrawlMark) { + debugger; + var e = new Error(message ? "Debug Failure. " + message : "Debug Failure."); + if (Error.captureStackTrace) { + Error.captureStackTrace(e, stackCrawlMark || fail); + } + throw e; + } + Debug.fail = fail; + function assertDefined(value, message) { + if (value === undefined || value === null) + return fail(message); + return value; + } + Debug.assertDefined = assertDefined; + function assertEachDefined(value, message) { + for (var _i = 0, value_1 = value; _i < value_1.length; _i++) { + var v = value_1[_i]; + assertDefined(v, message); + } + return value; + } + Debug.assertEachDefined = assertEachDefined; + function assertNever(member, message, stackCrawlMark) { + if (message === void 0) { message = "Illegal value:"; } + var detail = "kind" in member && "pos" in member ? "SyntaxKind: " + Debug.showSyntaxKind(member) : JSON.stringify(member); + return fail(message + " " + detail, stackCrawlMark || assertNever); + } + Debug.assertNever = assertNever; + function getFunctionName(func) { + if (typeof func !== "function") { + return ""; + } + else if (func.hasOwnProperty("name")) { + return func.name; + } + else { + var text = Function.prototype.toString.call(func); + var match = /^function\s+([\w\$]+)\s*\(/.exec(text); + return match ? match[1] : ""; + } + } + Debug.getFunctionName = getFunctionName; + })(Debug = ts.Debug || (ts.Debug = {})); + function equateValues(a, b) { + return a === b; + } + ts.equateValues = equateValues; + /** + * Compare the equality of two strings using a case-sensitive ordinal comparison. + * + * Case-sensitive comparisons compare both strings one code-point at a time using the integer + * value of each code-point after applying `toUpperCase` to each string. We always map both + * strings to their upper-case form as some unicode characters do not properly round-trip to + * lowercase (such as `ẞ` (German sharp capital s)). + */ + function equateStringsCaseInsensitive(a, b) { + return a === b + || a !== undefined + && b !== undefined + && a.toUpperCase() === b.toUpperCase(); + } + ts.equateStringsCaseInsensitive = equateStringsCaseInsensitive; + /** + * Compare the equality of two strings using a case-sensitive ordinal comparison. + * + * Case-sensitive comparisons compare both strings one code-point at a time using the + * integer value of each code-point. + */ + function equateStringsCaseSensitive(a, b) { + return equateValues(a, b); + } + ts.equateStringsCaseSensitive = equateStringsCaseSensitive; + function compareComparableValues(a, b) { + return a === b ? 0 /* EqualTo */ : + a === undefined ? -1 /* LessThan */ : + b === undefined ? 1 /* GreaterThan */ : + a < b ? -1 /* LessThan */ : + 1 /* GreaterThan */; + } + /** + * Compare two numeric values for their order relative to each other. + * To compare strings, use any of the `compareStrings` functions. + */ + function compareValues(a, b) { + return compareComparableValues(a, b); + } + ts.compareValues = compareValues; + function min(a, b, compare) { + return compare(a, b) === -1 /* LessThan */ ? a : b; + } + ts.min = min; + /** + * Compare two strings using a case-insensitive ordinal comparison. + * + * Ordinal comparisons are based on the difference between the unicode code points of both + * strings. Characters with multiple unicode representations are considered unequal. Ordinal + * comparisons provide predictable ordering, but place "a" after "B". + * + * Case-insensitive comparisons compare both strings one code-point at a time using the integer + * value of each code-point after applying `toUpperCase` to each string. We always map both + * strings to their upper-case form as some unicode characters do not properly round-trip to + * lowercase (such as `ẞ` (German sharp capital s)). + */ + function compareStringsCaseInsensitive(a, b) { + if (a === b) + return 0 /* EqualTo */; + if (a === undefined) + return -1 /* LessThan */; + if (b === undefined) + return 1 /* GreaterThan */; + a = a.toUpperCase(); + b = b.toUpperCase(); + return a < b ? -1 /* LessThan */ : a > b ? 1 /* GreaterThan */ : 0 /* EqualTo */; + } + ts.compareStringsCaseInsensitive = compareStringsCaseInsensitive; + /** + * Compare two strings using a case-sensitive ordinal comparison. + * + * Ordinal comparisons are based on the difference between the unicode code points of both + * strings. Characters with multiple unicode representations are considered unequal. Ordinal + * comparisons provide predictable ordering, but place "a" after "B". + * + * Case-sensitive comparisons compare both strings one code-point at a time using the integer + * value of each code-point. + */ + function compareStringsCaseSensitive(a, b) { + return compareComparableValues(a, b); + } + ts.compareStringsCaseSensitive = compareStringsCaseSensitive; + function getStringComparer(ignoreCase) { + return ignoreCase ? compareStringsCaseInsensitive : compareStringsCaseSensitive; + } + ts.getStringComparer = getStringComparer; + /** + * Creates a string comparer for use with string collation in the UI. + */ + var createUIStringComparer = (function () { + var defaultComparer; + var enUSComparer; + var stringComparerFactory = getStringComparerFactory(); + return createStringComparer; + function compareWithCallback(a, b, comparer) { + if (a === b) + return 0 /* EqualTo */; + if (a === undefined) + return -1 /* LessThan */; + if (b === undefined) + return 1 /* GreaterThan */; + var value = comparer(a, b); + return value < 0 ? -1 /* LessThan */ : value > 0 ? 1 /* GreaterThan */ : 0 /* EqualTo */; + } + function createIntlCollatorStringComparer(locale) { + // Intl.Collator.prototype.compare is bound to the collator. See NOTE in + // http://www.ecma-international.org/ecma-402/2.0/#sec-Intl.Collator.prototype.compare + var comparer = new Intl.Collator(locale, { usage: "sort", sensitivity: "variant" }).compare; + return function (a, b) { return compareWithCallback(a, b, comparer); }; + } + function createLocaleCompareStringComparer(locale) { + // if the locale is not the default locale (`undefined`), use the fallback comparer. + if (locale !== undefined) + return createFallbackStringComparer(); + return function (a, b) { return compareWithCallback(a, b, compareStrings); }; + function compareStrings(a, b) { + return a.localeCompare(b); + } + } + function createFallbackStringComparer() { + // An ordinal comparison puts "A" after "b", but for the UI we want "A" before "b". + // We first sort case insensitively. So "Aaa" will come before "baa". + // Then we sort case sensitively, so "aaa" will come before "Aaa". + // + // For case insensitive comparisons we always map both strings to their + // upper-case form as some unicode characters do not properly round-trip to + // lowercase (such as `ẞ` (German sharp capital s)). + return function (a, b) { return compareWithCallback(a, b, compareDictionaryOrder); }; + function compareDictionaryOrder(a, b) { + return compareStrings(a.toUpperCase(), b.toUpperCase()) || compareStrings(a, b); + } + function compareStrings(a, b) { + return a < b ? -1 /* LessThan */ : a > b ? 1 /* GreaterThan */ : 0 /* EqualTo */; + } + } + function getStringComparerFactory() { + // If the host supports Intl, we use it for comparisons using the default locale. + if (typeof Intl === "object" && typeof Intl.Collator === "function") { + return createIntlCollatorStringComparer; + } + // If the host does not support Intl, we fall back to localeCompare. + // localeCompare in Node v0.10 is just an ordinal comparison, so don't use it. + if (typeof String.prototype.localeCompare === "function" && + typeof String.prototype.toLocaleUpperCase === "function" && + "a".localeCompare("B") < 0) { + return createLocaleCompareStringComparer; + } + // Otherwise, fall back to ordinal comparison: + return createFallbackStringComparer; + } + function createStringComparer(locale) { + // Hold onto common string comparers. This avoids constantly reallocating comparers during + // tests. + if (locale === undefined) { + return defaultComparer || (defaultComparer = stringComparerFactory(locale)); + } + else if (locale === "en-US") { + return enUSComparer || (enUSComparer = stringComparerFactory(locale)); + } + else { + return stringComparerFactory(locale); + } + } + })(); + var uiComparerCaseSensitive; + var uiLocale; + function getUILocale() { + return uiLocale; + } + ts.getUILocale = getUILocale; + function setUILocale(value) { + if (uiLocale !== value) { + uiLocale = value; + uiComparerCaseSensitive = undefined; + } + } + ts.setUILocale = setUILocale; + /** + * Compare two strings in a using the case-sensitive sort behavior of the UI locale. + * + * Ordering is not predictable between different host locales, but is best for displaying + * ordered data for UI presentation. Characters with multiple unicode representations may + * be considered equal. + * + * Case-sensitive comparisons compare strings that differ in base characters, or + * accents/diacritic marks, or case as unequal. + */ + function compareStringsCaseSensitiveUI(a, b) { + var comparer = uiComparerCaseSensitive || (uiComparerCaseSensitive = createUIStringComparer(uiLocale)); + return comparer(a, b); + } + ts.compareStringsCaseSensitiveUI = compareStringsCaseSensitiveUI; + function compareProperties(a, b, key, comparer) { + return a === b ? 0 /* EqualTo */ : + a === undefined ? -1 /* LessThan */ : + b === undefined ? 1 /* GreaterThan */ : + comparer(a[key], b[key]); + } + ts.compareProperties = compareProperties; + /** True is greater than false. */ + function compareBooleans(a, b) { + return compareValues(a ? 1 : 0, b ? 1 : 0); + } + ts.compareBooleans = compareBooleans; + /** + * Given a name and a list of names that are *not* equal to the name, return a spelling suggestion if there is one that is close enough. + * Names less than length 3 only check for case-insensitive equality, not Levenshtein distance. + * + * If there is a candidate that's the same except for case, return that. + * If there is a candidate that's within one edit of the name, return that. + * Otherwise, return the candidate with the smallest Levenshtein distance, + * except for candidates: + * * With no name + * * Whose length differs from the target name by more than 0.34 of the length of the name. + * * Whose levenshtein distance is more than 0.4 of the length of the name + * (0.4 allows 1 substitution/transposition for every 5 characters, + * and 1 insertion/deletion at 3 characters) + */ + function getSpellingSuggestion(name, candidates, getName) { + var maximumLengthDifference = Math.min(2, Math.floor(name.length * 0.34)); + var bestDistance = Math.floor(name.length * 0.4) + 1; // If the best result isn't better than this, don't bother. + var bestCandidate; + var justCheckExactMatches = false; + var nameLowerCase = name.toLowerCase(); + for (var _i = 0, candidates_1 = candidates; _i < candidates_1.length; _i++) { + var candidate = candidates_1[_i]; + var candidateName = getName(candidate); + if (candidateName !== undefined && Math.abs(candidateName.length - nameLowerCase.length) <= maximumLengthDifference) { + var candidateNameLowerCase = candidateName.toLowerCase(); + if (candidateNameLowerCase === nameLowerCase) { + if (candidateName === name) { + continue; + } + return candidate; + } + if (justCheckExactMatches) { + continue; + } + if (candidateName.length < 3) { + // Don't bother, user would have noticed a 2-character name having an extra character + continue; + } + // Only care about a result better than the best so far. + var distance = levenshteinWithMax(nameLowerCase, candidateNameLowerCase, bestDistance - 1); + if (distance === undefined) { + continue; + } + if (distance < 3) { + justCheckExactMatches = true; + bestCandidate = candidate; + } + else { + Debug.assert(distance < bestDistance); // Else `levenshteinWithMax` should return undefined + bestDistance = distance; + bestCandidate = candidate; + } + } + } + return bestCandidate; + } + ts.getSpellingSuggestion = getSpellingSuggestion; + function levenshteinWithMax(s1, s2, max) { + var previous = new Array(s2.length + 1); + var current = new Array(s2.length + 1); + /** Represents any value > max. We don't care about the particular value. */ + var big = max + 1; + for (var i = 0; i <= s2.length; i++) { + previous[i] = i; + } + for (var i = 1; i <= s1.length; i++) { + var c1 = s1.charCodeAt(i - 1); + var minJ = i > max ? i - max : 1; + var maxJ = s2.length > max + i ? max + i : s2.length; + current[0] = i; + /** Smallest value of the matrix in the ith column. */ + var colMin = i; + for (var j = 1; j < minJ; j++) { + current[j] = big; + } + for (var j = minJ; j <= maxJ; j++) { + var dist = c1 === s2.charCodeAt(j - 1) + ? previous[j - 1] + : Math.min(/*delete*/ previous[j] + 1, /*insert*/ current[j - 1] + 1, /*substitute*/ previous[j - 1] + 2); + current[j] = dist; + colMin = Math.min(colMin, dist); + } + for (var j = maxJ + 1; j <= s2.length; j++) { + current[j] = big; + } + if (colMin > max) { + // Give up -- everything in this column is > max and it can't get better in future columns. + return undefined; + } + var temp = previous; + previous = current; + current = temp; + } + var res = previous[s2.length]; + return res > max ? undefined : res; + } + function endsWith(str, suffix) { + var expectedPos = str.length - suffix.length; + return expectedPos >= 0 && str.indexOf(suffix, expectedPos) === expectedPos; + } + ts.endsWith = endsWith; + function removeSuffix(str, suffix) { + return endsWith(str, suffix) ? str.slice(0, str.length - suffix.length) : str; + } + ts.removeSuffix = removeSuffix; + function tryRemoveSuffix(str, suffix) { + return endsWith(str, suffix) ? str.slice(0, str.length - suffix.length) : undefined; + } + ts.tryRemoveSuffix = tryRemoveSuffix; + function stringContains(str, substring) { + return str.indexOf(substring) !== -1; + } + ts.stringContains = stringContains; + function fileExtensionIs(path, extension) { + return path.length > extension.length && endsWith(path, extension); + } + ts.fileExtensionIs = fileExtensionIs; + function fileExtensionIsOneOf(path, extensions) { + for (var _i = 0, extensions_1 = extensions; _i < extensions_1.length; _i++) { + var extension = extensions_1[_i]; + if (fileExtensionIs(path, extension)) { + return true; + } + } + return false; + } + ts.fileExtensionIsOneOf = fileExtensionIsOneOf; + /** + * Takes a string like "jquery-min.4.2.3" and returns "jquery" + */ + function removeMinAndVersionNumbers(fileName) { + // Match a "." or "-" followed by a version number or 'min' at the end of the name + var trailingMinOrVersion = /[.-]((min)|(\d+(\.\d+)*))$/; + // The "min" or version may both be present, in either order, so try applying the above twice. + return fileName.replace(trailingMinOrVersion, "").replace(trailingMinOrVersion, ""); + } + ts.removeMinAndVersionNumbers = removeMinAndVersionNumbers; + /** Remove an item from an array, moving everything to its right one space left. */ + function orderedRemoveItem(array, item) { + for (var i = 0; i < array.length; i++) { + if (array[i] === item) { + orderedRemoveItemAt(array, i); + return true; + } + } + return false; + } + ts.orderedRemoveItem = orderedRemoveItem; + /** Remove an item by index from an array, moving everything to its right one space left. */ + function orderedRemoveItemAt(array, index) { + // This seems to be faster than either `array.splice(i, 1)` or `array.copyWithin(i, i+ 1)`. + for (var i = index; i < array.length - 1; i++) { + array[i] = array[i + 1]; + } + array.pop(); + } + ts.orderedRemoveItemAt = orderedRemoveItemAt; + function unorderedRemoveItemAt(array, index) { + // Fill in the "hole" left at `index`. + array[index] = array[array.length - 1]; + array.pop(); + } + ts.unorderedRemoveItemAt = unorderedRemoveItemAt; + /** Remove the *first* occurrence of `item` from the array. */ + function unorderedRemoveItem(array, item) { + return unorderedRemoveFirstItemWhere(array, function (element) { return element === item; }); + } + ts.unorderedRemoveItem = unorderedRemoveItem; + /** Remove the *first* element satisfying `predicate`. */ + function unorderedRemoveFirstItemWhere(array, predicate) { + for (var i = 0; i < array.length; i++) { + if (predicate(array[i])) { + unorderedRemoveItemAt(array, i); + return true; + } + } + return false; + } + function createGetCanonicalFileName(useCaseSensitiveFileNames) { + return useCaseSensitiveFileNames ? identity : toLowerCase; + } + ts.createGetCanonicalFileName = createGetCanonicalFileName; + function patternText(_a) { + var prefix = _a.prefix, suffix = _a.suffix; + return prefix + "*" + suffix; + } + ts.patternText = patternText; + /** + * Given that candidate matches pattern, returns the text matching the '*'. + * E.g.: matchedText(tryParsePattern("foo*baz"), "foobarbaz") === "bar" + */ + function matchedText(pattern, candidate) { + Debug.assert(isPatternMatch(pattern, candidate)); + return candidate.substring(pattern.prefix.length, candidate.length - pattern.suffix.length); + } + ts.matchedText = matchedText; + /** Return the object corresponding to the best pattern to match `candidate`. */ + function findBestPatternMatch(values, getPattern, candidate) { + var matchedValue; + // use length of prefix as betterness criteria + var longestMatchPrefixLength = -1; + for (var _i = 0, values_2 = values; _i < values_2.length; _i++) { + var v = values_2[_i]; + var pattern = getPattern(v); + if (isPatternMatch(pattern, candidate) && pattern.prefix.length > longestMatchPrefixLength) { + longestMatchPrefixLength = pattern.prefix.length; + matchedValue = v; + } + } + return matchedValue; + } + ts.findBestPatternMatch = findBestPatternMatch; + function startsWith(str, prefix) { + return str.lastIndexOf(prefix, 0) === 0; + } + ts.startsWith = startsWith; + function removePrefix(str, prefix) { + return startsWith(str, prefix) ? str.substr(prefix.length) : str; + } + ts.removePrefix = removePrefix; + function tryRemovePrefix(str, prefix, getCanonicalFileName) { + if (getCanonicalFileName === void 0) { getCanonicalFileName = identity; } + return startsWith(getCanonicalFileName(str), getCanonicalFileName(prefix)) ? str.substring(prefix.length) : undefined; + } + ts.tryRemovePrefix = tryRemovePrefix; + function isPatternMatch(_a, candidate) { + var prefix = _a.prefix, suffix = _a.suffix; + return candidate.length >= prefix.length + suffix.length && + startsWith(candidate, prefix) && + endsWith(candidate, suffix); + } + function and(f, g) { + return function (arg) { return f(arg) && g(arg); }; + } + ts.and = and; + function or(f, g) { + return function (arg) { return f(arg) || g(arg); }; + } + ts.or = or; + function assertType(_) { } // tslint:disable-line no-empty + ts.assertType = assertType; + function singleElementArray(t) { + return t === undefined ? undefined : [t]; + } + ts.singleElementArray = singleElementArray; + function enumerateInsertsAndDeletes(newItems, oldItems, comparer, inserted, deleted, unchanged) { + unchanged = unchanged || noop; + var newIndex = 0; + var oldIndex = 0; + var newLen = newItems.length; + var oldLen = oldItems.length; + while (newIndex < newLen && oldIndex < oldLen) { + var newItem = newItems[newIndex]; + var oldItem = oldItems[oldIndex]; + var compareResult = comparer(newItem, oldItem); + if (compareResult === -1 /* LessThan */) { + inserted(newItem); + newIndex++; + } + else if (compareResult === 1 /* GreaterThan */) { + deleted(oldItem); + oldIndex++; + } + else { + unchanged(oldItem, newItem); + newIndex++; + oldIndex++; + } + } + while (newIndex < newLen) { + inserted(newItems[newIndex++]); + } + while (oldIndex < oldLen) { + deleted(oldItems[oldIndex++]); + } + } + ts.enumerateInsertsAndDeletes = enumerateInsertsAndDeletes; + function fill(length, cb) { + return new Array(length).fill(0).map(function (_, i) { return cb(i); }); + } + ts.fill = fill; +})(ts || (ts = {})); +/*@internal*/ +var ts; +(function (ts) { + /** Gets a timestamp with (at least) ms resolution */ + ts.timestamp = typeof performance !== "undefined" && performance.now ? function () { return performance.now(); } : Date.now ? Date.now : function () { return +(new Date()); }; +})(ts || (ts = {})); +/*@internal*/ +/** Performance measurements for the compiler. */ +(function (ts) { + var performance; + (function (performance) { + // NOTE: cannot use ts.noop as core.ts loads after this + var profilerEvent = typeof onProfilerEvent === "function" && onProfilerEvent.profiler === true ? onProfilerEvent : function () { }; + var enabled = false; + var profilerStart = 0; + var counts; + var marks; + var measures; + function createTimerIf(condition, measureName, startMarkName, endMarkName) { + return condition ? createTimer(measureName, startMarkName, endMarkName) : performance.nullTimer; + } + performance.createTimerIf = createTimerIf; + function createTimer(measureName, startMarkName, endMarkName) { + var enterCount = 0; + return { + enter: enter, + exit: exit + }; + function enter() { + if (++enterCount === 1) { + mark(startMarkName); + } + } + function exit() { + if (--enterCount === 0) { + mark(endMarkName); + measure(measureName, startMarkName, endMarkName); + } + else if (enterCount < 0) { + ts.Debug.fail("enter/exit count does not match."); + } + } + } + performance.createTimer = createTimer; + performance.nullTimer = { enter: ts.noop, exit: ts.noop }; + /** + * Marks a performance event. + * + * @param markName The name of the mark. + */ + function mark(markName) { + if (enabled) { + marks.set(markName, ts.timestamp()); + counts.set(markName, (counts.get(markName) || 0) + 1); + profilerEvent(markName); + } + } + performance.mark = mark; + /** + * Adds a performance measurement with the specified name. + * + * @param measureName The name of the performance measurement. + * @param startMarkName The name of the starting mark. If not supplied, the point at which the + * profiler was enabled is used. + * @param endMarkName The name of the ending mark. If not supplied, the current timestamp is + * used. + */ + function measure(measureName, startMarkName, endMarkName) { + if (enabled) { + var end = endMarkName && marks.get(endMarkName) || ts.timestamp(); + var start = startMarkName && marks.get(startMarkName) || profilerStart; + measures.set(measureName, (measures.get(measureName) || 0) + (end - start)); + } + } + performance.measure = measure; + /** + * Gets the number of times a marker was encountered. + * + * @param markName The name of the mark. + */ + function getCount(markName) { + return counts && counts.get(markName) || 0; + } + performance.getCount = getCount; + /** + * Gets the total duration of all measurements with the supplied name. + * + * @param measureName The name of the measure whose durations should be accumulated. + */ + function getDuration(measureName) { + return measures && measures.get(measureName) || 0; + } + performance.getDuration = getDuration; + /** + * Iterate over each measure, performing some action + * + * @param cb The action to perform for each measure + */ + function forEachMeasure(cb) { + measures.forEach(function (measure, key) { + cb(key, measure); + }); + } + performance.forEachMeasure = forEachMeasure; + /** Enables (and resets) performance measurements for the compiler. */ + function enable() { + counts = ts.createMap(); + marks = ts.createMap(); + measures = ts.createMap(); + enabled = true; + profilerStart = ts.timestamp(); + } + performance.enable = enable; + /** Disables performance measurements for the compiler. */ + function disable() { + enabled = false; + } + performance.disable = disable; + })(performance = ts.performance || (ts.performance = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + // https://semver.org/#spec-item-2 + // > A normal version number MUST take the form X.Y.Z where X, Y, and Z are non-negative + // > integers, and MUST NOT contain leading zeroes. X is the major version, Y is the minor + // > version, and Z is the patch version. Each element MUST increase numerically. + // + // NOTE: We differ here in that we allow X and X.Y, with missing parts having the default + // value of `0`. + var versionRegExp = /^(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\-([a-z0-9-.]+))?(?:\+([a-z0-9-.]+))?)?)?$/i; + // https://semver.org/#spec-item-9 + // > A pre-release version MAY be denoted by appending a hyphen and a series of dot separated + // > identifiers immediately following the patch version. Identifiers MUST comprise only ASCII + // > alphanumerics and hyphen [0-9A-Za-z-]. Identifiers MUST NOT be empty. Numeric identifiers + // > MUST NOT include leading zeroes. + var prereleaseRegExp = /^(?:0|[1-9]\d*|[a-z-][a-z0-9-]*)(?:\.(?:0|[1-9]\d*|[a-z-][a-z0-9-]*))*$/i; + // https://semver.org/#spec-item-10 + // > Build metadata MAY be denoted by appending a plus sign and a series of dot separated + // > identifiers immediately following the patch or pre-release version. Identifiers MUST + // > comprise only ASCII alphanumerics and hyphen [0-9A-Za-z-]. Identifiers MUST NOT be empty. + var buildRegExp = /^[a-z0-9-]+(?:\.[a-z0-9-]+)*$/i; + // https://semver.org/#spec-item-9 + // > Numeric identifiers MUST NOT include leading zeroes. + var numericIdentifierRegExp = /^(0|[1-9]\d*)$/; + /** + * Describes a precise semantic version number, https://semver.org + */ + var Version = /** @class */ (function () { + function Version(major, minor, patch, prerelease, build) { + if (minor === void 0) { minor = 0; } + if (patch === void 0) { patch = 0; } + if (prerelease === void 0) { prerelease = ""; } + if (build === void 0) { build = ""; } + if (typeof major === "string") { + var result = ts.Debug.assertDefined(tryParseComponents(major), "Invalid version"); + (major = result.major, minor = result.minor, patch = result.patch, prerelease = result.prerelease, build = result.build); + } + ts.Debug.assert(major >= 0, "Invalid argument: major"); + ts.Debug.assert(minor >= 0, "Invalid argument: minor"); + ts.Debug.assert(patch >= 0, "Invalid argument: patch"); + ts.Debug.assert(!prerelease || prereleaseRegExp.test(prerelease), "Invalid argument: prerelease"); + ts.Debug.assert(!build || buildRegExp.test(build), "Invalid argument: build"); + this.major = major; + this.minor = minor; + this.patch = patch; + this.prerelease = prerelease ? prerelease.split(".") : ts.emptyArray; + this.build = build ? build.split(".") : ts.emptyArray; + } + Version.tryParse = function (text) { + var result = tryParseComponents(text); + if (!result) + return undefined; + var major = result.major, minor = result.minor, patch = result.patch, prerelease = result.prerelease, build = result.build; + return new Version(major, minor, patch, prerelease, build); + }; + Version.prototype.compareTo = function (other) { + // https://semver.org/#spec-item-11 + // > Precedence is determined by the first difference when comparing each of these + // > identifiers from left to right as follows: Major, minor, and patch versions are + // > always compared numerically. + // + // https://semver.org/#spec-item-11 + // > Precedence for two pre-release versions with the same major, minor, and patch version + // > MUST be determined by comparing each dot separated identifier from left to right until + // > a difference is found [...] + // + // https://semver.org/#spec-item-11 + // > Build metadata does not figure into precedence + if (this === other) + return 0 /* EqualTo */; + if (other === undefined) + return 1 /* GreaterThan */; + return ts.compareValues(this.major, other.major) + || ts.compareValues(this.minor, other.minor) + || ts.compareValues(this.patch, other.patch) + || comparePrerelaseIdentifiers(this.prerelease, other.prerelease); + }; + Version.prototype.increment = function (field) { + switch (field) { + case "major": return new Version(this.major + 1, 0, 0); + case "minor": return new Version(this.major, this.minor + 1, 0); + case "patch": return new Version(this.major, this.minor, this.patch + 1); + default: return ts.Debug.assertNever(field); + } + }; + Version.prototype.toString = function () { + var result = this.major + "." + this.minor + "." + this.patch; + if (ts.some(this.prerelease)) + result += "-" + this.prerelease.join("."); + if (ts.some(this.build)) + result += "+" + this.build.join("."); + return result; + }; + Version.zero = new Version(0, 0, 0); + return Version; + }()); + ts.Version = Version; + function tryParseComponents(text) { + var match = versionRegExp.exec(text); + if (!match) + return undefined; + var major = match[1], _a = match[2], minor = _a === void 0 ? "0" : _a, _b = match[3], patch = _b === void 0 ? "0" : _b, _c = match[4], prerelease = _c === void 0 ? "" : _c, _d = match[5], build = _d === void 0 ? "" : _d; + if (prerelease && !prereleaseRegExp.test(prerelease)) + return undefined; + if (build && !buildRegExp.test(build)) + return undefined; + return { + major: parseInt(major, 10), + minor: parseInt(minor, 10), + patch: parseInt(patch, 10), + prerelease: prerelease, + build: build + }; + } + function comparePrerelaseIdentifiers(left, right) { + // https://semver.org/#spec-item-11 + // > When major, minor, and patch are equal, a pre-release version has lower precedence + // > than a normal version. + if (left === right) + return 0 /* EqualTo */; + if (left.length === 0) + return right.length === 0 ? 0 /* EqualTo */ : 1 /* GreaterThan */; + if (right.length === 0) + return -1 /* LessThan */; + // https://semver.org/#spec-item-11 + // > Precedence for two pre-release versions with the same major, minor, and patch version + // > MUST be determined by comparing each dot separated identifier from left to right until + // > a difference is found [...] + var length = Math.min(left.length, right.length); + for (var i = 0; i < length; i++) { + var leftIdentifier = left[i]; + var rightIdentifier = right[i]; + if (leftIdentifier === rightIdentifier) + continue; + var leftIsNumeric = numericIdentifierRegExp.test(leftIdentifier); + var rightIsNumeric = numericIdentifierRegExp.test(rightIdentifier); + if (leftIsNumeric || rightIsNumeric) { + // https://semver.org/#spec-item-11 + // > Numeric identifiers always have lower precedence than non-numeric identifiers. + if (leftIsNumeric !== rightIsNumeric) + return leftIsNumeric ? -1 /* LessThan */ : 1 /* GreaterThan */; + // https://semver.org/#spec-item-11 + // > identifiers consisting of only digits are compared numerically + var result = ts.compareValues(+leftIdentifier, +rightIdentifier); + if (result) + return result; + } + else { + // https://semver.org/#spec-item-11 + // > identifiers with letters or hyphens are compared lexically in ASCII sort order. + var result = ts.compareStringsCaseSensitive(leftIdentifier, rightIdentifier); + if (result) + return result; + } + } + // https://semver.org/#spec-item-11 + // > A larger set of pre-release fields has a higher precedence than a smaller set, if all + // > of the preceding identifiers are equal. + return ts.compareValues(left.length, right.length); + } + /** + * Describes a semantic version range, per https://github.com/npm/node-semver#ranges + */ + var VersionRange = /** @class */ (function () { + function VersionRange(spec) { + this._alternatives = spec ? ts.Debug.assertDefined(parseRange(spec), "Invalid range spec.") : ts.emptyArray; + } + VersionRange.tryParse = function (text) { + var sets = parseRange(text); + if (sets) { + var range = new VersionRange(""); + range._alternatives = sets; + return range; + } + return undefined; + }; + VersionRange.prototype.test = function (version) { + if (typeof version === "string") + version = new Version(version); + return testDisjunction(version, this._alternatives); + }; + VersionRange.prototype.toString = function () { + return formatDisjunction(this._alternatives); + }; + return VersionRange; + }()); + ts.VersionRange = VersionRange; + // https://github.com/npm/node-semver#range-grammar + // + // range-set ::= range ( logical-or range ) * + // range ::= hyphen | simple ( ' ' simple ) * | '' + // logical-or ::= ( ' ' ) * '||' ( ' ' ) * + var logicalOrRegExp = /\s*\|\|\s*/g; + var whitespaceRegExp = /\s+/g; + // https://github.com/npm/node-semver#range-grammar + // + // partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )? + // xr ::= 'x' | 'X' | '*' | nr + // nr ::= '0' | ['1'-'9'] ( ['0'-'9'] ) * + // qualifier ::= ( '-' pre )? ( '+' build )? + // pre ::= parts + // build ::= parts + // parts ::= part ( '.' part ) * + // part ::= nr | [-0-9A-Za-z]+ + var partialRegExp = /^([xX*0]|[1-9]\d*)(?:\.([xX*0]|[1-9]\d*)(?:\.([xX*0]|[1-9]\d*)(?:-([a-z0-9-.]+))?(?:\+([a-z0-9-.]+))?)?)?$/i; + // https://github.com/npm/node-semver#range-grammar + // + // hyphen ::= partial ' - ' partial + var hyphenRegExp = /^\s*([a-z0-9-+.*]+)\s+-\s+([a-z0-9-+.*]+)\s*$/i; + // https://github.com/npm/node-semver#range-grammar + // + // simple ::= primitive | partial | tilde | caret + // primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial + // tilde ::= '~' partial + // caret ::= '^' partial + var rangeRegExp = /^\s*(~|\^|<|<=|>|>=|=)?\s*([a-z0-9-+.*]+)$/i; + function parseRange(text) { + var alternatives = []; + for (var _i = 0, _a = text.trim().split(logicalOrRegExp); _i < _a.length; _i++) { + var range = _a[_i]; + if (!range) + continue; + var comparators = []; + var match = hyphenRegExp.exec(range); + if (match) { + if (!parseHyphen(match[1], match[2], comparators)) + return undefined; + } + else { + for (var _b = 0, _c = range.split(whitespaceRegExp); _b < _c.length; _b++) { + var simple = _c[_b]; + var match_1 = rangeRegExp.exec(simple); + if (!match_1 || !parseComparator(match_1[1], match_1[2], comparators)) + return undefined; + } + } + alternatives.push(comparators); + } + return alternatives; + } + function parsePartial(text) { + var match = partialRegExp.exec(text); + if (!match) + return undefined; + var major = match[1], _a = match[2], minor = _a === void 0 ? "*" : _a, _b = match[3], patch = _b === void 0 ? "*" : _b, prerelease = match[4], build = match[5]; + var version = new Version(isWildcard(major) ? 0 : parseInt(major, 10), isWildcard(major) || isWildcard(minor) ? 0 : parseInt(minor, 10), isWildcard(major) || isWildcard(minor) || isWildcard(patch) ? 0 : parseInt(patch, 10), prerelease, build); + return { version: version, major: major, minor: minor, patch: patch }; + } + function parseHyphen(left, right, comparators) { + var leftResult = parsePartial(left); + if (!leftResult) + return false; + var rightResult = parsePartial(right); + if (!rightResult) + return false; + if (!isWildcard(leftResult.major)) { + comparators.push(createComparator(">=", leftResult.version)); + } + if (!isWildcard(rightResult.major)) { + comparators.push(isWildcard(rightResult.minor) ? createComparator("<", rightResult.version.increment("major")) : + isWildcard(rightResult.patch) ? createComparator("<", rightResult.version.increment("minor")) : + createComparator("<=", rightResult.version)); + } + return true; + } + function parseComparator(operator, text, comparators) { + var result = parsePartial(text); + if (!result) + return false; + var version = result.version, major = result.major, minor = result.minor, patch = result.patch; + if (!isWildcard(major)) { + switch (operator) { + case "~": + comparators.push(createComparator(">=", version)); + comparators.push(createComparator("<", version.increment(isWildcard(minor) ? "major" : + "minor"))); + break; + case "^": + comparators.push(createComparator(">=", version)); + comparators.push(createComparator("<", version.increment(version.major > 0 || isWildcard(minor) ? "major" : + version.minor > 0 || isWildcard(patch) ? "minor" : + "patch"))); + break; + case "<": + case ">=": + comparators.push(createComparator(operator, version)); + break; + case "<=": + case ">": + comparators.push(isWildcard(minor) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("major")) : + isWildcard(patch) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("minor")) : + createComparator(operator, version)); + break; + case "=": + case undefined: + if (isWildcard(minor) || isWildcard(patch)) { + comparators.push(createComparator(">=", version)); + comparators.push(createComparator("<", version.increment(isWildcard(minor) ? "major" : "minor"))); + } + else { + comparators.push(createComparator("=", version)); + } + break; + default: + // unrecognized + return false; + } + } + else if (operator === "<" || operator === ">") { + comparators.push(createComparator("<", Version.zero)); + } + return true; + } + function isWildcard(part) { + return part === "*" || part === "x" || part === "X"; + } + function createComparator(operator, operand) { + return { operator: operator, operand: operand }; + } + function testDisjunction(version, alternatives) { + // an empty disjunction is treated as "*" (all versions) + if (alternatives.length === 0) + return true; + for (var _i = 0, alternatives_1 = alternatives; _i < alternatives_1.length; _i++) { + var alternative = alternatives_1[_i]; + if (testAlternative(version, alternative)) + return true; + } + return false; + } + function testAlternative(version, comparators) { + for (var _i = 0, comparators_1 = comparators; _i < comparators_1.length; _i++) { + var comparator = comparators_1[_i]; + if (!testComparator(version, comparator.operator, comparator.operand)) + return false; + } + return true; + } + function testComparator(version, operator, operand) { + var cmp = version.compareTo(operand); + switch (operator) { + case "<": return cmp < 0; + case "<=": return cmp <= 0; + case ">": return cmp > 0; + case ">=": return cmp >= 0; + case "=": return cmp === 0; + default: return ts.Debug.assertNever(operator); + } + } + function formatDisjunction(alternatives) { + return ts.map(alternatives, formatAlternative).join(" || ") || "*"; + } + function formatAlternative(comparators) { + return ts.map(comparators, formatComparator).join(" "); + } + function formatComparator(comparator) { + return "" + comparator.operator + comparator.operand; + } +})(ts || (ts = {})); +var ts; +(function (ts) { + // token > SyntaxKind.Identifier => token is a keyword + // Also, If you add a new SyntaxKind be sure to keep the `Markers` section at the bottom in sync + var SyntaxKind; + (function (SyntaxKind) { + SyntaxKind[SyntaxKind["Unknown"] = 0] = "Unknown"; + SyntaxKind[SyntaxKind["EndOfFileToken"] = 1] = "EndOfFileToken"; + SyntaxKind[SyntaxKind["SingleLineCommentTrivia"] = 2] = "SingleLineCommentTrivia"; + SyntaxKind[SyntaxKind["MultiLineCommentTrivia"] = 3] = "MultiLineCommentTrivia"; + SyntaxKind[SyntaxKind["NewLineTrivia"] = 4] = "NewLineTrivia"; + SyntaxKind[SyntaxKind["WhitespaceTrivia"] = 5] = "WhitespaceTrivia"; + // We detect and preserve #! on the first line + SyntaxKind[SyntaxKind["ShebangTrivia"] = 6] = "ShebangTrivia"; + // We detect and provide better error recovery when we encounter a git merge marker. This + // allows us to edit files with git-conflict markers in them in a much more pleasant manner. + SyntaxKind[SyntaxKind["ConflictMarkerTrivia"] = 7] = "ConflictMarkerTrivia"; + // Literals + SyntaxKind[SyntaxKind["NumericLiteral"] = 8] = "NumericLiteral"; + SyntaxKind[SyntaxKind["BigIntLiteral"] = 9] = "BigIntLiteral"; + SyntaxKind[SyntaxKind["StringLiteral"] = 10] = "StringLiteral"; + SyntaxKind[SyntaxKind["JsxText"] = 11] = "JsxText"; + SyntaxKind[SyntaxKind["JsxTextAllWhiteSpaces"] = 12] = "JsxTextAllWhiteSpaces"; + SyntaxKind[SyntaxKind["RegularExpressionLiteral"] = 13] = "RegularExpressionLiteral"; + SyntaxKind[SyntaxKind["NoSubstitutionTemplateLiteral"] = 14] = "NoSubstitutionTemplateLiteral"; + // Pseudo-literals + SyntaxKind[SyntaxKind["TemplateHead"] = 15] = "TemplateHead"; + SyntaxKind[SyntaxKind["TemplateMiddle"] = 16] = "TemplateMiddle"; + SyntaxKind[SyntaxKind["TemplateTail"] = 17] = "TemplateTail"; + // Punctuation + SyntaxKind[SyntaxKind["OpenBraceToken"] = 18] = "OpenBraceToken"; + SyntaxKind[SyntaxKind["CloseBraceToken"] = 19] = "CloseBraceToken"; + SyntaxKind[SyntaxKind["OpenParenToken"] = 20] = "OpenParenToken"; + SyntaxKind[SyntaxKind["CloseParenToken"] = 21] = "CloseParenToken"; + SyntaxKind[SyntaxKind["OpenBracketToken"] = 22] = "OpenBracketToken"; + SyntaxKind[SyntaxKind["CloseBracketToken"] = 23] = "CloseBracketToken"; + SyntaxKind[SyntaxKind["DotToken"] = 24] = "DotToken"; + SyntaxKind[SyntaxKind["DotDotDotToken"] = 25] = "DotDotDotToken"; + SyntaxKind[SyntaxKind["SemicolonToken"] = 26] = "SemicolonToken"; + SyntaxKind[SyntaxKind["CommaToken"] = 27] = "CommaToken"; + SyntaxKind[SyntaxKind["LessThanToken"] = 28] = "LessThanToken"; + SyntaxKind[SyntaxKind["LessThanSlashToken"] = 29] = "LessThanSlashToken"; + SyntaxKind[SyntaxKind["GreaterThanToken"] = 30] = "GreaterThanToken"; + SyntaxKind[SyntaxKind["LessThanEqualsToken"] = 31] = "LessThanEqualsToken"; + SyntaxKind[SyntaxKind["GreaterThanEqualsToken"] = 32] = "GreaterThanEqualsToken"; + SyntaxKind[SyntaxKind["EqualsEqualsToken"] = 33] = "EqualsEqualsToken"; + SyntaxKind[SyntaxKind["ExclamationEqualsToken"] = 34] = "ExclamationEqualsToken"; + SyntaxKind[SyntaxKind["EqualsEqualsEqualsToken"] = 35] = "EqualsEqualsEqualsToken"; + SyntaxKind[SyntaxKind["ExclamationEqualsEqualsToken"] = 36] = "ExclamationEqualsEqualsToken"; + SyntaxKind[SyntaxKind["EqualsGreaterThanToken"] = 37] = "EqualsGreaterThanToken"; + SyntaxKind[SyntaxKind["PlusToken"] = 38] = "PlusToken"; + SyntaxKind[SyntaxKind["MinusToken"] = 39] = "MinusToken"; + SyntaxKind[SyntaxKind["AsteriskToken"] = 40] = "AsteriskToken"; + SyntaxKind[SyntaxKind["AsteriskAsteriskToken"] = 41] = "AsteriskAsteriskToken"; + SyntaxKind[SyntaxKind["SlashToken"] = 42] = "SlashToken"; + SyntaxKind[SyntaxKind["PercentToken"] = 43] = "PercentToken"; + SyntaxKind[SyntaxKind["PlusPlusToken"] = 44] = "PlusPlusToken"; + SyntaxKind[SyntaxKind["MinusMinusToken"] = 45] = "MinusMinusToken"; + SyntaxKind[SyntaxKind["LessThanLessThanToken"] = 46] = "LessThanLessThanToken"; + SyntaxKind[SyntaxKind["GreaterThanGreaterThanToken"] = 47] = "GreaterThanGreaterThanToken"; + SyntaxKind[SyntaxKind["GreaterThanGreaterThanGreaterThanToken"] = 48] = "GreaterThanGreaterThanGreaterThanToken"; + SyntaxKind[SyntaxKind["AmpersandToken"] = 49] = "AmpersandToken"; + SyntaxKind[SyntaxKind["BarToken"] = 50] = "BarToken"; + SyntaxKind[SyntaxKind["CaretToken"] = 51] = "CaretToken"; + SyntaxKind[SyntaxKind["ExclamationToken"] = 52] = "ExclamationToken"; + SyntaxKind[SyntaxKind["TildeToken"] = 53] = "TildeToken"; + SyntaxKind[SyntaxKind["AmpersandAmpersandToken"] = 54] = "AmpersandAmpersandToken"; + SyntaxKind[SyntaxKind["BarBarToken"] = 55] = "BarBarToken"; + SyntaxKind[SyntaxKind["QuestionToken"] = 56] = "QuestionToken"; + SyntaxKind[SyntaxKind["ColonToken"] = 57] = "ColonToken"; + SyntaxKind[SyntaxKind["AtToken"] = 58] = "AtToken"; + // Assignments + SyntaxKind[SyntaxKind["EqualsToken"] = 59] = "EqualsToken"; + SyntaxKind[SyntaxKind["PlusEqualsToken"] = 60] = "PlusEqualsToken"; + SyntaxKind[SyntaxKind["MinusEqualsToken"] = 61] = "MinusEqualsToken"; + SyntaxKind[SyntaxKind["AsteriskEqualsToken"] = 62] = "AsteriskEqualsToken"; + SyntaxKind[SyntaxKind["AsteriskAsteriskEqualsToken"] = 63] = "AsteriskAsteriskEqualsToken"; + SyntaxKind[SyntaxKind["SlashEqualsToken"] = 64] = "SlashEqualsToken"; + SyntaxKind[SyntaxKind["PercentEqualsToken"] = 65] = "PercentEqualsToken"; + SyntaxKind[SyntaxKind["LessThanLessThanEqualsToken"] = 66] = "LessThanLessThanEqualsToken"; + SyntaxKind[SyntaxKind["GreaterThanGreaterThanEqualsToken"] = 67] = "GreaterThanGreaterThanEqualsToken"; + SyntaxKind[SyntaxKind["GreaterThanGreaterThanGreaterThanEqualsToken"] = 68] = "GreaterThanGreaterThanGreaterThanEqualsToken"; + SyntaxKind[SyntaxKind["AmpersandEqualsToken"] = 69] = "AmpersandEqualsToken"; + SyntaxKind[SyntaxKind["BarEqualsToken"] = 70] = "BarEqualsToken"; + SyntaxKind[SyntaxKind["CaretEqualsToken"] = 71] = "CaretEqualsToken"; + // Identifiers + SyntaxKind[SyntaxKind["Identifier"] = 72] = "Identifier"; + // Reserved words + SyntaxKind[SyntaxKind["BreakKeyword"] = 73] = "BreakKeyword"; + SyntaxKind[SyntaxKind["CaseKeyword"] = 74] = "CaseKeyword"; + SyntaxKind[SyntaxKind["CatchKeyword"] = 75] = "CatchKeyword"; + SyntaxKind[SyntaxKind["ClassKeyword"] = 76] = "ClassKeyword"; + SyntaxKind[SyntaxKind["ConstKeyword"] = 77] = "ConstKeyword"; + SyntaxKind[SyntaxKind["ContinueKeyword"] = 78] = "ContinueKeyword"; + SyntaxKind[SyntaxKind["DebuggerKeyword"] = 79] = "DebuggerKeyword"; + SyntaxKind[SyntaxKind["DefaultKeyword"] = 80] = "DefaultKeyword"; + SyntaxKind[SyntaxKind["DeleteKeyword"] = 81] = "DeleteKeyword"; + SyntaxKind[SyntaxKind["DoKeyword"] = 82] = "DoKeyword"; + SyntaxKind[SyntaxKind["ElseKeyword"] = 83] = "ElseKeyword"; + SyntaxKind[SyntaxKind["EnumKeyword"] = 84] = "EnumKeyword"; + SyntaxKind[SyntaxKind["ExportKeyword"] = 85] = "ExportKeyword"; + SyntaxKind[SyntaxKind["ExtendsKeyword"] = 86] = "ExtendsKeyword"; + SyntaxKind[SyntaxKind["FalseKeyword"] = 87] = "FalseKeyword"; + SyntaxKind[SyntaxKind["FinallyKeyword"] = 88] = "FinallyKeyword"; + SyntaxKind[SyntaxKind["ForKeyword"] = 89] = "ForKeyword"; + SyntaxKind[SyntaxKind["FunctionKeyword"] = 90] = "FunctionKeyword"; + SyntaxKind[SyntaxKind["IfKeyword"] = 91] = "IfKeyword"; + SyntaxKind[SyntaxKind["ImportKeyword"] = 92] = "ImportKeyword"; + SyntaxKind[SyntaxKind["InKeyword"] = 93] = "InKeyword"; + SyntaxKind[SyntaxKind["InstanceOfKeyword"] = 94] = "InstanceOfKeyword"; + SyntaxKind[SyntaxKind["NewKeyword"] = 95] = "NewKeyword"; + SyntaxKind[SyntaxKind["NullKeyword"] = 96] = "NullKeyword"; + SyntaxKind[SyntaxKind["ReturnKeyword"] = 97] = "ReturnKeyword"; + SyntaxKind[SyntaxKind["SuperKeyword"] = 98] = "SuperKeyword"; + SyntaxKind[SyntaxKind["SwitchKeyword"] = 99] = "SwitchKeyword"; + SyntaxKind[SyntaxKind["ThisKeyword"] = 100] = "ThisKeyword"; + SyntaxKind[SyntaxKind["ThrowKeyword"] = 101] = "ThrowKeyword"; + SyntaxKind[SyntaxKind["TrueKeyword"] = 102] = "TrueKeyword"; + SyntaxKind[SyntaxKind["TryKeyword"] = 103] = "TryKeyword"; + SyntaxKind[SyntaxKind["TypeOfKeyword"] = 104] = "TypeOfKeyword"; + SyntaxKind[SyntaxKind["VarKeyword"] = 105] = "VarKeyword"; + SyntaxKind[SyntaxKind["VoidKeyword"] = 106] = "VoidKeyword"; + SyntaxKind[SyntaxKind["WhileKeyword"] = 107] = "WhileKeyword"; + SyntaxKind[SyntaxKind["WithKeyword"] = 108] = "WithKeyword"; + // Strict mode reserved words + SyntaxKind[SyntaxKind["ImplementsKeyword"] = 109] = "ImplementsKeyword"; + SyntaxKind[SyntaxKind["InterfaceKeyword"] = 110] = "InterfaceKeyword"; + SyntaxKind[SyntaxKind["LetKeyword"] = 111] = "LetKeyword"; + SyntaxKind[SyntaxKind["PackageKeyword"] = 112] = "PackageKeyword"; + SyntaxKind[SyntaxKind["PrivateKeyword"] = 113] = "PrivateKeyword"; + SyntaxKind[SyntaxKind["ProtectedKeyword"] = 114] = "ProtectedKeyword"; + SyntaxKind[SyntaxKind["PublicKeyword"] = 115] = "PublicKeyword"; + SyntaxKind[SyntaxKind["StaticKeyword"] = 116] = "StaticKeyword"; + SyntaxKind[SyntaxKind["YieldKeyword"] = 117] = "YieldKeyword"; + // Contextual keywords + SyntaxKind[SyntaxKind["AbstractKeyword"] = 118] = "AbstractKeyword"; + SyntaxKind[SyntaxKind["AsKeyword"] = 119] = "AsKeyword"; + SyntaxKind[SyntaxKind["AnyKeyword"] = 120] = "AnyKeyword"; + SyntaxKind[SyntaxKind["AsyncKeyword"] = 121] = "AsyncKeyword"; + SyntaxKind[SyntaxKind["AwaitKeyword"] = 122] = "AwaitKeyword"; + SyntaxKind[SyntaxKind["BooleanKeyword"] = 123] = "BooleanKeyword"; + SyntaxKind[SyntaxKind["ConstructorKeyword"] = 124] = "ConstructorKeyword"; + SyntaxKind[SyntaxKind["DeclareKeyword"] = 125] = "DeclareKeyword"; + SyntaxKind[SyntaxKind["GetKeyword"] = 126] = "GetKeyword"; + SyntaxKind[SyntaxKind["InferKeyword"] = 127] = "InferKeyword"; + SyntaxKind[SyntaxKind["IsKeyword"] = 128] = "IsKeyword"; + SyntaxKind[SyntaxKind["KeyOfKeyword"] = 129] = "KeyOfKeyword"; + SyntaxKind[SyntaxKind["ModuleKeyword"] = 130] = "ModuleKeyword"; + SyntaxKind[SyntaxKind["NamespaceKeyword"] = 131] = "NamespaceKeyword"; + SyntaxKind[SyntaxKind["NeverKeyword"] = 132] = "NeverKeyword"; + SyntaxKind[SyntaxKind["ReadonlyKeyword"] = 133] = "ReadonlyKeyword"; + SyntaxKind[SyntaxKind["RequireKeyword"] = 134] = "RequireKeyword"; + SyntaxKind[SyntaxKind["NumberKeyword"] = 135] = "NumberKeyword"; + SyntaxKind[SyntaxKind["ObjectKeyword"] = 136] = "ObjectKeyword"; + SyntaxKind[SyntaxKind["SetKeyword"] = 137] = "SetKeyword"; + SyntaxKind[SyntaxKind["StringKeyword"] = 138] = "StringKeyword"; + SyntaxKind[SyntaxKind["SymbolKeyword"] = 139] = "SymbolKeyword"; + SyntaxKind[SyntaxKind["TypeKeyword"] = 140] = "TypeKeyword"; + SyntaxKind[SyntaxKind["UndefinedKeyword"] = 141] = "UndefinedKeyword"; + SyntaxKind[SyntaxKind["UniqueKeyword"] = 142] = "UniqueKeyword"; + SyntaxKind[SyntaxKind["UnknownKeyword"] = 143] = "UnknownKeyword"; + SyntaxKind[SyntaxKind["FromKeyword"] = 144] = "FromKeyword"; + SyntaxKind[SyntaxKind["GlobalKeyword"] = 145] = "GlobalKeyword"; + SyntaxKind[SyntaxKind["BigIntKeyword"] = 146] = "BigIntKeyword"; + SyntaxKind[SyntaxKind["OfKeyword"] = 147] = "OfKeyword"; + // Parse tree nodes + // Names + SyntaxKind[SyntaxKind["QualifiedName"] = 148] = "QualifiedName"; + SyntaxKind[SyntaxKind["ComputedPropertyName"] = 149] = "ComputedPropertyName"; + // Signature elements + SyntaxKind[SyntaxKind["TypeParameter"] = 150] = "TypeParameter"; + SyntaxKind[SyntaxKind["Parameter"] = 151] = "Parameter"; + SyntaxKind[SyntaxKind["Decorator"] = 152] = "Decorator"; + // TypeMember + SyntaxKind[SyntaxKind["PropertySignature"] = 153] = "PropertySignature"; + SyntaxKind[SyntaxKind["PropertyDeclaration"] = 154] = "PropertyDeclaration"; + SyntaxKind[SyntaxKind["MethodSignature"] = 155] = "MethodSignature"; + SyntaxKind[SyntaxKind["MethodDeclaration"] = 156] = "MethodDeclaration"; + SyntaxKind[SyntaxKind["Constructor"] = 157] = "Constructor"; + SyntaxKind[SyntaxKind["GetAccessor"] = 158] = "GetAccessor"; + SyntaxKind[SyntaxKind["SetAccessor"] = 159] = "SetAccessor"; + SyntaxKind[SyntaxKind["CallSignature"] = 160] = "CallSignature"; + SyntaxKind[SyntaxKind["ConstructSignature"] = 161] = "ConstructSignature"; + SyntaxKind[SyntaxKind["IndexSignature"] = 162] = "IndexSignature"; + // Type + SyntaxKind[SyntaxKind["TypePredicate"] = 163] = "TypePredicate"; + SyntaxKind[SyntaxKind["TypeReference"] = 164] = "TypeReference"; + SyntaxKind[SyntaxKind["FunctionType"] = 165] = "FunctionType"; + SyntaxKind[SyntaxKind["ConstructorType"] = 166] = "ConstructorType"; + SyntaxKind[SyntaxKind["TypeQuery"] = 167] = "TypeQuery"; + SyntaxKind[SyntaxKind["TypeLiteral"] = 168] = "TypeLiteral"; + SyntaxKind[SyntaxKind["ArrayType"] = 169] = "ArrayType"; + SyntaxKind[SyntaxKind["TupleType"] = 170] = "TupleType"; + SyntaxKind[SyntaxKind["OptionalType"] = 171] = "OptionalType"; + SyntaxKind[SyntaxKind["RestType"] = 172] = "RestType"; + SyntaxKind[SyntaxKind["UnionType"] = 173] = "UnionType"; + SyntaxKind[SyntaxKind["IntersectionType"] = 174] = "IntersectionType"; + SyntaxKind[SyntaxKind["ConditionalType"] = 175] = "ConditionalType"; + SyntaxKind[SyntaxKind["InferType"] = 176] = "InferType"; + SyntaxKind[SyntaxKind["ParenthesizedType"] = 177] = "ParenthesizedType"; + SyntaxKind[SyntaxKind["ThisType"] = 178] = "ThisType"; + SyntaxKind[SyntaxKind["TypeOperator"] = 179] = "TypeOperator"; + SyntaxKind[SyntaxKind["IndexedAccessType"] = 180] = "IndexedAccessType"; + SyntaxKind[SyntaxKind["MappedType"] = 181] = "MappedType"; + SyntaxKind[SyntaxKind["LiteralType"] = 182] = "LiteralType"; + SyntaxKind[SyntaxKind["ImportType"] = 183] = "ImportType"; + // Binding patterns + SyntaxKind[SyntaxKind["ObjectBindingPattern"] = 184] = "ObjectBindingPattern"; + SyntaxKind[SyntaxKind["ArrayBindingPattern"] = 185] = "ArrayBindingPattern"; + SyntaxKind[SyntaxKind["BindingElement"] = 186] = "BindingElement"; + // Expression + SyntaxKind[SyntaxKind["ArrayLiteralExpression"] = 187] = "ArrayLiteralExpression"; + SyntaxKind[SyntaxKind["ObjectLiteralExpression"] = 188] = "ObjectLiteralExpression"; + SyntaxKind[SyntaxKind["PropertyAccessExpression"] = 189] = "PropertyAccessExpression"; + SyntaxKind[SyntaxKind["ElementAccessExpression"] = 190] = "ElementAccessExpression"; + SyntaxKind[SyntaxKind["CallExpression"] = 191] = "CallExpression"; + SyntaxKind[SyntaxKind["NewExpression"] = 192] = "NewExpression"; + SyntaxKind[SyntaxKind["TaggedTemplateExpression"] = 193] = "TaggedTemplateExpression"; + SyntaxKind[SyntaxKind["TypeAssertionExpression"] = 194] = "TypeAssertionExpression"; + SyntaxKind[SyntaxKind["ParenthesizedExpression"] = 195] = "ParenthesizedExpression"; + SyntaxKind[SyntaxKind["FunctionExpression"] = 196] = "FunctionExpression"; + SyntaxKind[SyntaxKind["ArrowFunction"] = 197] = "ArrowFunction"; + SyntaxKind[SyntaxKind["DeleteExpression"] = 198] = "DeleteExpression"; + SyntaxKind[SyntaxKind["TypeOfExpression"] = 199] = "TypeOfExpression"; + SyntaxKind[SyntaxKind["VoidExpression"] = 200] = "VoidExpression"; + SyntaxKind[SyntaxKind["AwaitExpression"] = 201] = "AwaitExpression"; + SyntaxKind[SyntaxKind["PrefixUnaryExpression"] = 202] = "PrefixUnaryExpression"; + SyntaxKind[SyntaxKind["PostfixUnaryExpression"] = 203] = "PostfixUnaryExpression"; + SyntaxKind[SyntaxKind["BinaryExpression"] = 204] = "BinaryExpression"; + SyntaxKind[SyntaxKind["ConditionalExpression"] = 205] = "ConditionalExpression"; + SyntaxKind[SyntaxKind["TemplateExpression"] = 206] = "TemplateExpression"; + SyntaxKind[SyntaxKind["YieldExpression"] = 207] = "YieldExpression"; + SyntaxKind[SyntaxKind["SpreadElement"] = 208] = "SpreadElement"; + SyntaxKind[SyntaxKind["ClassExpression"] = 209] = "ClassExpression"; + SyntaxKind[SyntaxKind["OmittedExpression"] = 210] = "OmittedExpression"; + SyntaxKind[SyntaxKind["ExpressionWithTypeArguments"] = 211] = "ExpressionWithTypeArguments"; + SyntaxKind[SyntaxKind["AsExpression"] = 212] = "AsExpression"; + SyntaxKind[SyntaxKind["NonNullExpression"] = 213] = "NonNullExpression"; + SyntaxKind[SyntaxKind["MetaProperty"] = 214] = "MetaProperty"; + SyntaxKind[SyntaxKind["SyntheticExpression"] = 215] = "SyntheticExpression"; + // Misc + SyntaxKind[SyntaxKind["TemplateSpan"] = 216] = "TemplateSpan"; + SyntaxKind[SyntaxKind["SemicolonClassElement"] = 217] = "SemicolonClassElement"; + // Element + SyntaxKind[SyntaxKind["Block"] = 218] = "Block"; + SyntaxKind[SyntaxKind["VariableStatement"] = 219] = "VariableStatement"; + SyntaxKind[SyntaxKind["EmptyStatement"] = 220] = "EmptyStatement"; + SyntaxKind[SyntaxKind["ExpressionStatement"] = 221] = "ExpressionStatement"; + SyntaxKind[SyntaxKind["IfStatement"] = 222] = "IfStatement"; + SyntaxKind[SyntaxKind["DoStatement"] = 223] = "DoStatement"; + SyntaxKind[SyntaxKind["WhileStatement"] = 224] = "WhileStatement"; + SyntaxKind[SyntaxKind["ForStatement"] = 225] = "ForStatement"; + SyntaxKind[SyntaxKind["ForInStatement"] = 226] = "ForInStatement"; + SyntaxKind[SyntaxKind["ForOfStatement"] = 227] = "ForOfStatement"; + SyntaxKind[SyntaxKind["ContinueStatement"] = 228] = "ContinueStatement"; + SyntaxKind[SyntaxKind["BreakStatement"] = 229] = "BreakStatement"; + SyntaxKind[SyntaxKind["ReturnStatement"] = 230] = "ReturnStatement"; + SyntaxKind[SyntaxKind["WithStatement"] = 231] = "WithStatement"; + SyntaxKind[SyntaxKind["SwitchStatement"] = 232] = "SwitchStatement"; + SyntaxKind[SyntaxKind["LabeledStatement"] = 233] = "LabeledStatement"; + SyntaxKind[SyntaxKind["ThrowStatement"] = 234] = "ThrowStatement"; + SyntaxKind[SyntaxKind["TryStatement"] = 235] = "TryStatement"; + SyntaxKind[SyntaxKind["DebuggerStatement"] = 236] = "DebuggerStatement"; + SyntaxKind[SyntaxKind["VariableDeclaration"] = 237] = "VariableDeclaration"; + SyntaxKind[SyntaxKind["VariableDeclarationList"] = 238] = "VariableDeclarationList"; + SyntaxKind[SyntaxKind["FunctionDeclaration"] = 239] = "FunctionDeclaration"; + SyntaxKind[SyntaxKind["ClassDeclaration"] = 240] = "ClassDeclaration"; + SyntaxKind[SyntaxKind["InterfaceDeclaration"] = 241] = "InterfaceDeclaration"; + SyntaxKind[SyntaxKind["TypeAliasDeclaration"] = 242] = "TypeAliasDeclaration"; + SyntaxKind[SyntaxKind["EnumDeclaration"] = 243] = "EnumDeclaration"; + SyntaxKind[SyntaxKind["ModuleDeclaration"] = 244] = "ModuleDeclaration"; + SyntaxKind[SyntaxKind["ModuleBlock"] = 245] = "ModuleBlock"; + SyntaxKind[SyntaxKind["CaseBlock"] = 246] = "CaseBlock"; + SyntaxKind[SyntaxKind["NamespaceExportDeclaration"] = 247] = "NamespaceExportDeclaration"; + SyntaxKind[SyntaxKind["ImportEqualsDeclaration"] = 248] = "ImportEqualsDeclaration"; + SyntaxKind[SyntaxKind["ImportDeclaration"] = 249] = "ImportDeclaration"; + SyntaxKind[SyntaxKind["ImportClause"] = 250] = "ImportClause"; + SyntaxKind[SyntaxKind["NamespaceImport"] = 251] = "NamespaceImport"; + SyntaxKind[SyntaxKind["NamedImports"] = 252] = "NamedImports"; + SyntaxKind[SyntaxKind["ImportSpecifier"] = 253] = "ImportSpecifier"; + SyntaxKind[SyntaxKind["ExportAssignment"] = 254] = "ExportAssignment"; + SyntaxKind[SyntaxKind["ExportDeclaration"] = 255] = "ExportDeclaration"; + SyntaxKind[SyntaxKind["NamedExports"] = 256] = "NamedExports"; + SyntaxKind[SyntaxKind["ExportSpecifier"] = 257] = "ExportSpecifier"; + SyntaxKind[SyntaxKind["MissingDeclaration"] = 258] = "MissingDeclaration"; + // Module references + SyntaxKind[SyntaxKind["ExternalModuleReference"] = 259] = "ExternalModuleReference"; + // JSX + SyntaxKind[SyntaxKind["JsxElement"] = 260] = "JsxElement"; + SyntaxKind[SyntaxKind["JsxSelfClosingElement"] = 261] = "JsxSelfClosingElement"; + SyntaxKind[SyntaxKind["JsxOpeningElement"] = 262] = "JsxOpeningElement"; + SyntaxKind[SyntaxKind["JsxClosingElement"] = 263] = "JsxClosingElement"; + SyntaxKind[SyntaxKind["JsxFragment"] = 264] = "JsxFragment"; + SyntaxKind[SyntaxKind["JsxOpeningFragment"] = 265] = "JsxOpeningFragment"; + SyntaxKind[SyntaxKind["JsxClosingFragment"] = 266] = "JsxClosingFragment"; + SyntaxKind[SyntaxKind["JsxAttribute"] = 267] = "JsxAttribute"; + SyntaxKind[SyntaxKind["JsxAttributes"] = 268] = "JsxAttributes"; + SyntaxKind[SyntaxKind["JsxSpreadAttribute"] = 269] = "JsxSpreadAttribute"; + SyntaxKind[SyntaxKind["JsxExpression"] = 270] = "JsxExpression"; + // Clauses + SyntaxKind[SyntaxKind["CaseClause"] = 271] = "CaseClause"; + SyntaxKind[SyntaxKind["DefaultClause"] = 272] = "DefaultClause"; + SyntaxKind[SyntaxKind["HeritageClause"] = 273] = "HeritageClause"; + SyntaxKind[SyntaxKind["CatchClause"] = 274] = "CatchClause"; + // Property assignments + SyntaxKind[SyntaxKind["PropertyAssignment"] = 275] = "PropertyAssignment"; + SyntaxKind[SyntaxKind["ShorthandPropertyAssignment"] = 276] = "ShorthandPropertyAssignment"; + SyntaxKind[SyntaxKind["SpreadAssignment"] = 277] = "SpreadAssignment"; + // Enum + SyntaxKind[SyntaxKind["EnumMember"] = 278] = "EnumMember"; + // Top-level nodes + SyntaxKind[SyntaxKind["SourceFile"] = 279] = "SourceFile"; + SyntaxKind[SyntaxKind["Bundle"] = 280] = "Bundle"; + SyntaxKind[SyntaxKind["UnparsedSource"] = 281] = "UnparsedSource"; + SyntaxKind[SyntaxKind["InputFiles"] = 282] = "InputFiles"; + // JSDoc nodes + SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 283] = "JSDocTypeExpression"; + // The * type + SyntaxKind[SyntaxKind["JSDocAllType"] = 284] = "JSDocAllType"; + // The ? type + SyntaxKind[SyntaxKind["JSDocUnknownType"] = 285] = "JSDocUnknownType"; + SyntaxKind[SyntaxKind["JSDocNullableType"] = 286] = "JSDocNullableType"; + SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 287] = "JSDocNonNullableType"; + SyntaxKind[SyntaxKind["JSDocOptionalType"] = 288] = "JSDocOptionalType"; + SyntaxKind[SyntaxKind["JSDocFunctionType"] = 289] = "JSDocFunctionType"; + SyntaxKind[SyntaxKind["JSDocVariadicType"] = 290] = "JSDocVariadicType"; + SyntaxKind[SyntaxKind["JSDocComment"] = 291] = "JSDocComment"; + SyntaxKind[SyntaxKind["JSDocTypeLiteral"] = 292] = "JSDocTypeLiteral"; + SyntaxKind[SyntaxKind["JSDocSignature"] = 293] = "JSDocSignature"; + SyntaxKind[SyntaxKind["JSDocTag"] = 294] = "JSDocTag"; + SyntaxKind[SyntaxKind["JSDocAugmentsTag"] = 295] = "JSDocAugmentsTag"; + SyntaxKind[SyntaxKind["JSDocClassTag"] = 296] = "JSDocClassTag"; + SyntaxKind[SyntaxKind["JSDocCallbackTag"] = 297] = "JSDocCallbackTag"; + SyntaxKind[SyntaxKind["JSDocEnumTag"] = 298] = "JSDocEnumTag"; + SyntaxKind[SyntaxKind["JSDocParameterTag"] = 299] = "JSDocParameterTag"; + SyntaxKind[SyntaxKind["JSDocReturnTag"] = 300] = "JSDocReturnTag"; + SyntaxKind[SyntaxKind["JSDocThisTag"] = 301] = "JSDocThisTag"; + SyntaxKind[SyntaxKind["JSDocTypeTag"] = 302] = "JSDocTypeTag"; + SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 303] = "JSDocTemplateTag"; + SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 304] = "JSDocTypedefTag"; + SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 305] = "JSDocPropertyTag"; + // Synthesized list + SyntaxKind[SyntaxKind["SyntaxList"] = 306] = "SyntaxList"; + // Transformation nodes + SyntaxKind[SyntaxKind["NotEmittedStatement"] = 307] = "NotEmittedStatement"; + SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 308] = "PartiallyEmittedExpression"; + SyntaxKind[SyntaxKind["CommaListExpression"] = 309] = "CommaListExpression"; + SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 310] = "MergeDeclarationMarker"; + SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 311] = "EndOfDeclarationMarker"; + // Enum value count + SyntaxKind[SyntaxKind["Count"] = 312] = "Count"; + // Markers + SyntaxKind[SyntaxKind["FirstAssignment"] = 59] = "FirstAssignment"; + SyntaxKind[SyntaxKind["LastAssignment"] = 71] = "LastAssignment"; + SyntaxKind[SyntaxKind["FirstCompoundAssignment"] = 60] = "FirstCompoundAssignment"; + SyntaxKind[SyntaxKind["LastCompoundAssignment"] = 71] = "LastCompoundAssignment"; + SyntaxKind[SyntaxKind["FirstReservedWord"] = 73] = "FirstReservedWord"; + SyntaxKind[SyntaxKind["LastReservedWord"] = 108] = "LastReservedWord"; + SyntaxKind[SyntaxKind["FirstKeyword"] = 73] = "FirstKeyword"; + SyntaxKind[SyntaxKind["LastKeyword"] = 147] = "LastKeyword"; + SyntaxKind[SyntaxKind["FirstFutureReservedWord"] = 109] = "FirstFutureReservedWord"; + SyntaxKind[SyntaxKind["LastFutureReservedWord"] = 117] = "LastFutureReservedWord"; + SyntaxKind[SyntaxKind["FirstTypeNode"] = 163] = "FirstTypeNode"; + SyntaxKind[SyntaxKind["LastTypeNode"] = 183] = "LastTypeNode"; + SyntaxKind[SyntaxKind["FirstPunctuation"] = 18] = "FirstPunctuation"; + SyntaxKind[SyntaxKind["LastPunctuation"] = 71] = "LastPunctuation"; + SyntaxKind[SyntaxKind["FirstToken"] = 0] = "FirstToken"; + SyntaxKind[SyntaxKind["LastToken"] = 147] = "LastToken"; + SyntaxKind[SyntaxKind["FirstTriviaToken"] = 2] = "FirstTriviaToken"; + SyntaxKind[SyntaxKind["LastTriviaToken"] = 7] = "LastTriviaToken"; + SyntaxKind[SyntaxKind["FirstLiteralToken"] = 8] = "FirstLiteralToken"; + SyntaxKind[SyntaxKind["LastLiteralToken"] = 14] = "LastLiteralToken"; + SyntaxKind[SyntaxKind["FirstTemplateToken"] = 14] = "FirstTemplateToken"; + SyntaxKind[SyntaxKind["LastTemplateToken"] = 17] = "LastTemplateToken"; + SyntaxKind[SyntaxKind["FirstBinaryOperator"] = 28] = "FirstBinaryOperator"; + SyntaxKind[SyntaxKind["LastBinaryOperator"] = 71] = "LastBinaryOperator"; + SyntaxKind[SyntaxKind["FirstNode"] = 148] = "FirstNode"; + SyntaxKind[SyntaxKind["FirstJSDocNode"] = 283] = "FirstJSDocNode"; + SyntaxKind[SyntaxKind["LastJSDocNode"] = 305] = "LastJSDocNode"; + SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 294] = "FirstJSDocTagNode"; + SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 305] = "LastJSDocTagNode"; + /* @internal */ SyntaxKind[SyntaxKind["FirstContextualKeyword"] = 118] = "FirstContextualKeyword"; + /* @internal */ SyntaxKind[SyntaxKind["LastContextualKeyword"] = 147] = "LastContextualKeyword"; + })(SyntaxKind = ts.SyntaxKind || (ts.SyntaxKind = {})); + var NodeFlags; + (function (NodeFlags) { + NodeFlags[NodeFlags["None"] = 0] = "None"; + NodeFlags[NodeFlags["Let"] = 1] = "Let"; + NodeFlags[NodeFlags["Const"] = 2] = "Const"; + NodeFlags[NodeFlags["NestedNamespace"] = 4] = "NestedNamespace"; + NodeFlags[NodeFlags["Synthesized"] = 8] = "Synthesized"; + NodeFlags[NodeFlags["Namespace"] = 16] = "Namespace"; + NodeFlags[NodeFlags["ExportContext"] = 32] = "ExportContext"; + NodeFlags[NodeFlags["ContainsThis"] = 64] = "ContainsThis"; + NodeFlags[NodeFlags["HasImplicitReturn"] = 128] = "HasImplicitReturn"; + NodeFlags[NodeFlags["HasExplicitReturn"] = 256] = "HasExplicitReturn"; + NodeFlags[NodeFlags["GlobalAugmentation"] = 512] = "GlobalAugmentation"; + NodeFlags[NodeFlags["HasAsyncFunctions"] = 1024] = "HasAsyncFunctions"; + NodeFlags[NodeFlags["DisallowInContext"] = 2048] = "DisallowInContext"; + NodeFlags[NodeFlags["YieldContext"] = 4096] = "YieldContext"; + NodeFlags[NodeFlags["DecoratorContext"] = 8192] = "DecoratorContext"; + NodeFlags[NodeFlags["AwaitContext"] = 16384] = "AwaitContext"; + NodeFlags[NodeFlags["ThisNodeHasError"] = 32768] = "ThisNodeHasError"; + NodeFlags[NodeFlags["JavaScriptFile"] = 65536] = "JavaScriptFile"; + NodeFlags[NodeFlags["ThisNodeOrAnySubNodesHasError"] = 131072] = "ThisNodeOrAnySubNodesHasError"; + NodeFlags[NodeFlags["HasAggregatedChildData"] = 262144] = "HasAggregatedChildData"; + // These flags will be set when the parser encounters a dynamic import expression or 'import.meta' to avoid + // walking the tree if the flags are not set. However, these flags are just a approximation + // (hence why it's named "PossiblyContainsDynamicImport") because once set, the flags never get cleared. + // During editing, if a dynamic import is removed, incremental parsing will *NOT* clear this flag. + // This means that the tree will always be traversed during module resolution, or when looking for external module indicators. + // However, the removal operation should not occur often and in the case of the + // removal, it is likely that users will add the import anyway. + // The advantage of this approach is its simplicity. For the case of batch compilation, + // we guarantee that users won't have to pay the price of walking the tree if a dynamic import isn't used. + /* @internal */ NodeFlags[NodeFlags["PossiblyContainsDynamicImport"] = 524288] = "PossiblyContainsDynamicImport"; + /* @internal */ NodeFlags[NodeFlags["PossiblyContainsImportMeta"] = 1048576] = "PossiblyContainsImportMeta"; + NodeFlags[NodeFlags["JSDoc"] = 2097152] = "JSDoc"; + /* @internal */ NodeFlags[NodeFlags["Ambient"] = 4194304] = "Ambient"; + /* @internal */ NodeFlags[NodeFlags["InWithStatement"] = 8388608] = "InWithStatement"; + NodeFlags[NodeFlags["JsonFile"] = 16777216] = "JsonFile"; + NodeFlags[NodeFlags["BlockScoped"] = 3] = "BlockScoped"; + NodeFlags[NodeFlags["ReachabilityCheckFlags"] = 384] = "ReachabilityCheckFlags"; + NodeFlags[NodeFlags["ReachabilityAndEmitFlags"] = 1408] = "ReachabilityAndEmitFlags"; + // Parsing context flags + NodeFlags[NodeFlags["ContextFlags"] = 12679168] = "ContextFlags"; + // Exclude these flags when parsing a Type + NodeFlags[NodeFlags["TypeExcludesFlags"] = 20480] = "TypeExcludesFlags"; + // Represents all flags that are potentially set once and + // never cleared on SourceFiles which get re-used in between incremental parses. + // See the comment above on `PossiblyContainsDynamicImport` and `PossiblyContainsImportMeta`. + /* @internal */ NodeFlags[NodeFlags["PermanentlySetIncrementalFlags"] = 1572864] = "PermanentlySetIncrementalFlags"; + })(NodeFlags = ts.NodeFlags || (ts.NodeFlags = {})); + var ModifierFlags; + (function (ModifierFlags) { + ModifierFlags[ModifierFlags["None"] = 0] = "None"; + ModifierFlags[ModifierFlags["Export"] = 1] = "Export"; + ModifierFlags[ModifierFlags["Ambient"] = 2] = "Ambient"; + ModifierFlags[ModifierFlags["Public"] = 4] = "Public"; + ModifierFlags[ModifierFlags["Private"] = 8] = "Private"; + ModifierFlags[ModifierFlags["Protected"] = 16] = "Protected"; + ModifierFlags[ModifierFlags["Static"] = 32] = "Static"; + ModifierFlags[ModifierFlags["Readonly"] = 64] = "Readonly"; + ModifierFlags[ModifierFlags["Abstract"] = 128] = "Abstract"; + ModifierFlags[ModifierFlags["Async"] = 256] = "Async"; + ModifierFlags[ModifierFlags["Default"] = 512] = "Default"; + ModifierFlags[ModifierFlags["Const"] = 2048] = "Const"; + ModifierFlags[ModifierFlags["HasComputedFlags"] = 536870912] = "HasComputedFlags"; + ModifierFlags[ModifierFlags["AccessibilityModifier"] = 28] = "AccessibilityModifier"; + // Accessibility modifiers and 'readonly' can be attached to a parameter in a constructor to make it a property. + ModifierFlags[ModifierFlags["ParameterPropertyModifier"] = 92] = "ParameterPropertyModifier"; + ModifierFlags[ModifierFlags["NonPublicAccessibilityModifier"] = 24] = "NonPublicAccessibilityModifier"; + ModifierFlags[ModifierFlags["TypeScriptModifier"] = 2270] = "TypeScriptModifier"; + ModifierFlags[ModifierFlags["ExportDefault"] = 513] = "ExportDefault"; + ModifierFlags[ModifierFlags["All"] = 3071] = "All"; + })(ModifierFlags = ts.ModifierFlags || (ts.ModifierFlags = {})); + var JsxFlags; + (function (JsxFlags) { + JsxFlags[JsxFlags["None"] = 0] = "None"; + /** An element from a named property of the JSX.IntrinsicElements interface */ + JsxFlags[JsxFlags["IntrinsicNamedElement"] = 1] = "IntrinsicNamedElement"; + /** An element inferred from the string index signature of the JSX.IntrinsicElements interface */ + JsxFlags[JsxFlags["IntrinsicIndexedElement"] = 2] = "IntrinsicIndexedElement"; + JsxFlags[JsxFlags["IntrinsicElement"] = 3] = "IntrinsicElement"; + })(JsxFlags = ts.JsxFlags || (ts.JsxFlags = {})); + /* @internal */ + var RelationComparisonResult; + (function (RelationComparisonResult) { + RelationComparisonResult[RelationComparisonResult["Succeeded"] = 1] = "Succeeded"; + RelationComparisonResult[RelationComparisonResult["Failed"] = 2] = "Failed"; + RelationComparisonResult[RelationComparisonResult["FailedAndReported"] = 3] = "FailedAndReported"; + })(RelationComparisonResult = ts.RelationComparisonResult || (ts.RelationComparisonResult = {})); + /*@internal*/ + var GeneratedIdentifierFlags; + (function (GeneratedIdentifierFlags) { + // Kinds + GeneratedIdentifierFlags[GeneratedIdentifierFlags["None"] = 0] = "None"; + GeneratedIdentifierFlags[GeneratedIdentifierFlags["Auto"] = 1] = "Auto"; + GeneratedIdentifierFlags[GeneratedIdentifierFlags["Loop"] = 2] = "Loop"; + GeneratedIdentifierFlags[GeneratedIdentifierFlags["Unique"] = 3] = "Unique"; + GeneratedIdentifierFlags[GeneratedIdentifierFlags["Node"] = 4] = "Node"; + GeneratedIdentifierFlags[GeneratedIdentifierFlags["KindMask"] = 7] = "KindMask"; + // Flags + GeneratedIdentifierFlags[GeneratedIdentifierFlags["ReservedInNestedScopes"] = 8] = "ReservedInNestedScopes"; + GeneratedIdentifierFlags[GeneratedIdentifierFlags["Optimistic"] = 16] = "Optimistic"; + GeneratedIdentifierFlags[GeneratedIdentifierFlags["FileLevel"] = 32] = "FileLevel"; + })(GeneratedIdentifierFlags = ts.GeneratedIdentifierFlags || (ts.GeneratedIdentifierFlags = {})); + /* @internal */ + var TokenFlags; + (function (TokenFlags) { + TokenFlags[TokenFlags["None"] = 0] = "None"; + TokenFlags[TokenFlags["PrecedingLineBreak"] = 1] = "PrecedingLineBreak"; + TokenFlags[TokenFlags["PrecedingJSDocComment"] = 2] = "PrecedingJSDocComment"; + TokenFlags[TokenFlags["Unterminated"] = 4] = "Unterminated"; + TokenFlags[TokenFlags["ExtendedUnicodeEscape"] = 8] = "ExtendedUnicodeEscape"; + TokenFlags[TokenFlags["Scientific"] = 16] = "Scientific"; + TokenFlags[TokenFlags["Octal"] = 32] = "Octal"; + TokenFlags[TokenFlags["HexSpecifier"] = 64] = "HexSpecifier"; + TokenFlags[TokenFlags["BinarySpecifier"] = 128] = "BinarySpecifier"; + TokenFlags[TokenFlags["OctalSpecifier"] = 256] = "OctalSpecifier"; + TokenFlags[TokenFlags["ContainsSeparator"] = 512] = "ContainsSeparator"; + TokenFlags[TokenFlags["BinaryOrOctalSpecifier"] = 384] = "BinaryOrOctalSpecifier"; + TokenFlags[TokenFlags["NumericLiteralFlags"] = 1008] = "NumericLiteralFlags"; + })(TokenFlags = ts.TokenFlags || (ts.TokenFlags = {})); + var FlowFlags; + (function (FlowFlags) { + FlowFlags[FlowFlags["Unreachable"] = 1] = "Unreachable"; + FlowFlags[FlowFlags["Start"] = 2] = "Start"; + FlowFlags[FlowFlags["BranchLabel"] = 4] = "BranchLabel"; + FlowFlags[FlowFlags["LoopLabel"] = 8] = "LoopLabel"; + FlowFlags[FlowFlags["Assignment"] = 16] = "Assignment"; + FlowFlags[FlowFlags["TrueCondition"] = 32] = "TrueCondition"; + FlowFlags[FlowFlags["FalseCondition"] = 64] = "FalseCondition"; + FlowFlags[FlowFlags["SwitchClause"] = 128] = "SwitchClause"; + FlowFlags[FlowFlags["ArrayMutation"] = 256] = "ArrayMutation"; + FlowFlags[FlowFlags["Referenced"] = 512] = "Referenced"; + FlowFlags[FlowFlags["Shared"] = 1024] = "Shared"; + FlowFlags[FlowFlags["PreFinally"] = 2048] = "PreFinally"; + FlowFlags[FlowFlags["AfterFinally"] = 4096] = "AfterFinally"; + FlowFlags[FlowFlags["Label"] = 12] = "Label"; + FlowFlags[FlowFlags["Condition"] = 96] = "Condition"; + })(FlowFlags = ts.FlowFlags || (ts.FlowFlags = {})); + var OperationCanceledException = /** @class */ (function () { + function OperationCanceledException() { + } + return OperationCanceledException; + }()); + ts.OperationCanceledException = OperationCanceledException; + /* @internal */ + var StructureIsReused; + (function (StructureIsReused) { + StructureIsReused[StructureIsReused["Not"] = 0] = "Not"; + StructureIsReused[StructureIsReused["SafeModules"] = 1] = "SafeModules"; + StructureIsReused[StructureIsReused["Completely"] = 2] = "Completely"; + })(StructureIsReused = ts.StructureIsReused || (ts.StructureIsReused = {})); + /** Return code used by getEmitOutput function to indicate status of the function */ + var ExitStatus; + (function (ExitStatus) { + // Compiler ran successfully. Either this was a simple do-nothing compilation (for example, + // when -version or -help was provided, or this was a normal compilation, no diagnostics + // were produced, and all outputs were generated successfully. + ExitStatus[ExitStatus["Success"] = 0] = "Success"; + // Diagnostics were produced and because of them no code was generated. + ExitStatus[ExitStatus["DiagnosticsPresent_OutputsSkipped"] = 1] = "DiagnosticsPresent_OutputsSkipped"; + // Diagnostics were produced and outputs were generated in spite of them. + ExitStatus[ExitStatus["DiagnosticsPresent_OutputsGenerated"] = 2] = "DiagnosticsPresent_OutputsGenerated"; + })(ExitStatus = ts.ExitStatus || (ts.ExitStatus = {})); + /* @internal */ + var UnionReduction; + (function (UnionReduction) { + UnionReduction[UnionReduction["None"] = 0] = "None"; + UnionReduction[UnionReduction["Literal"] = 1] = "Literal"; + UnionReduction[UnionReduction["Subtype"] = 2] = "Subtype"; + })(UnionReduction = ts.UnionReduction || (ts.UnionReduction = {})); + // NOTE: If modifying this enum, must modify `TypeFormatFlags` too! + var NodeBuilderFlags; + (function (NodeBuilderFlags) { + NodeBuilderFlags[NodeBuilderFlags["None"] = 0] = "None"; + // Options + NodeBuilderFlags[NodeBuilderFlags["NoTruncation"] = 1] = "NoTruncation"; + NodeBuilderFlags[NodeBuilderFlags["WriteArrayAsGenericType"] = 2] = "WriteArrayAsGenericType"; + NodeBuilderFlags[NodeBuilderFlags["GenerateNamesForShadowedTypeParams"] = 4] = "GenerateNamesForShadowedTypeParams"; + NodeBuilderFlags[NodeBuilderFlags["UseStructuralFallback"] = 8] = "UseStructuralFallback"; + NodeBuilderFlags[NodeBuilderFlags["ForbidIndexedAccessSymbolReferences"] = 16] = "ForbidIndexedAccessSymbolReferences"; + NodeBuilderFlags[NodeBuilderFlags["WriteTypeArgumentsOfSignature"] = 32] = "WriteTypeArgumentsOfSignature"; + NodeBuilderFlags[NodeBuilderFlags["UseFullyQualifiedType"] = 64] = "UseFullyQualifiedType"; + NodeBuilderFlags[NodeBuilderFlags["UseOnlyExternalAliasing"] = 128] = "UseOnlyExternalAliasing"; + NodeBuilderFlags[NodeBuilderFlags["SuppressAnyReturnType"] = 256] = "SuppressAnyReturnType"; + NodeBuilderFlags[NodeBuilderFlags["WriteTypeParametersInQualifiedName"] = 512] = "WriteTypeParametersInQualifiedName"; + NodeBuilderFlags[NodeBuilderFlags["MultilineObjectLiterals"] = 1024] = "MultilineObjectLiterals"; + NodeBuilderFlags[NodeBuilderFlags["WriteClassExpressionAsTypeLiteral"] = 2048] = "WriteClassExpressionAsTypeLiteral"; + NodeBuilderFlags[NodeBuilderFlags["UseTypeOfFunction"] = 4096] = "UseTypeOfFunction"; + NodeBuilderFlags[NodeBuilderFlags["OmitParameterModifiers"] = 8192] = "OmitParameterModifiers"; + NodeBuilderFlags[NodeBuilderFlags["UseAliasDefinedOutsideCurrentScope"] = 16384] = "UseAliasDefinedOutsideCurrentScope"; + // Error handling + NodeBuilderFlags[NodeBuilderFlags["AllowThisInObjectLiteral"] = 32768] = "AllowThisInObjectLiteral"; + NodeBuilderFlags[NodeBuilderFlags["AllowQualifedNameInPlaceOfIdentifier"] = 65536] = "AllowQualifedNameInPlaceOfIdentifier"; + NodeBuilderFlags[NodeBuilderFlags["AllowAnonymousIdentifier"] = 131072] = "AllowAnonymousIdentifier"; + NodeBuilderFlags[NodeBuilderFlags["AllowEmptyUnionOrIntersection"] = 262144] = "AllowEmptyUnionOrIntersection"; + NodeBuilderFlags[NodeBuilderFlags["AllowEmptyTuple"] = 524288] = "AllowEmptyTuple"; + NodeBuilderFlags[NodeBuilderFlags["AllowUniqueESSymbolType"] = 1048576] = "AllowUniqueESSymbolType"; + NodeBuilderFlags[NodeBuilderFlags["AllowEmptyIndexInfoType"] = 2097152] = "AllowEmptyIndexInfoType"; + // Errors (cont.) + NodeBuilderFlags[NodeBuilderFlags["AllowNodeModulesRelativePaths"] = 67108864] = "AllowNodeModulesRelativePaths"; + /* @internal */ NodeBuilderFlags[NodeBuilderFlags["DoNotIncludeSymbolChain"] = 134217728] = "DoNotIncludeSymbolChain"; + NodeBuilderFlags[NodeBuilderFlags["IgnoreErrors"] = 70221824] = "IgnoreErrors"; + // State + NodeBuilderFlags[NodeBuilderFlags["InObjectTypeLiteral"] = 4194304] = "InObjectTypeLiteral"; + NodeBuilderFlags[NodeBuilderFlags["InTypeAlias"] = 8388608] = "InTypeAlias"; + NodeBuilderFlags[NodeBuilderFlags["InInitialEntityName"] = 16777216] = "InInitialEntityName"; + NodeBuilderFlags[NodeBuilderFlags["InReverseMappedType"] = 33554432] = "InReverseMappedType"; + })(NodeBuilderFlags = ts.NodeBuilderFlags || (ts.NodeBuilderFlags = {})); + // Ensure the shared flags between this and `NodeBuilderFlags` stay in alignment + var TypeFormatFlags; + (function (TypeFormatFlags) { + TypeFormatFlags[TypeFormatFlags["None"] = 0] = "None"; + TypeFormatFlags[TypeFormatFlags["NoTruncation"] = 1] = "NoTruncation"; + TypeFormatFlags[TypeFormatFlags["WriteArrayAsGenericType"] = 2] = "WriteArrayAsGenericType"; + // hole because there's a hole in node builder flags + TypeFormatFlags[TypeFormatFlags["UseStructuralFallback"] = 8] = "UseStructuralFallback"; + // hole because there's a hole in node builder flags + TypeFormatFlags[TypeFormatFlags["WriteTypeArgumentsOfSignature"] = 32] = "WriteTypeArgumentsOfSignature"; + TypeFormatFlags[TypeFormatFlags["UseFullyQualifiedType"] = 64] = "UseFullyQualifiedType"; + // hole because `UseOnlyExternalAliasing` is here in node builder flags, but functions which take old flags use `SymbolFormatFlags` instead + TypeFormatFlags[TypeFormatFlags["SuppressAnyReturnType"] = 256] = "SuppressAnyReturnType"; + // hole because `WriteTypeParametersInQualifiedName` is here in node builder flags, but functions which take old flags use `SymbolFormatFlags` for this instead + TypeFormatFlags[TypeFormatFlags["MultilineObjectLiterals"] = 1024] = "MultilineObjectLiterals"; + TypeFormatFlags[TypeFormatFlags["WriteClassExpressionAsTypeLiteral"] = 2048] = "WriteClassExpressionAsTypeLiteral"; + TypeFormatFlags[TypeFormatFlags["UseTypeOfFunction"] = 4096] = "UseTypeOfFunction"; + TypeFormatFlags[TypeFormatFlags["OmitParameterModifiers"] = 8192] = "OmitParameterModifiers"; + TypeFormatFlags[TypeFormatFlags["UseAliasDefinedOutsideCurrentScope"] = 16384] = "UseAliasDefinedOutsideCurrentScope"; + // even though `T` can't be accessed in the current scope. + // Error Handling + TypeFormatFlags[TypeFormatFlags["AllowUniqueESSymbolType"] = 1048576] = "AllowUniqueESSymbolType"; + // TypeFormatFlags exclusive + TypeFormatFlags[TypeFormatFlags["AddUndefined"] = 131072] = "AddUndefined"; + TypeFormatFlags[TypeFormatFlags["WriteArrowStyleSignature"] = 262144] = "WriteArrowStyleSignature"; + // State + TypeFormatFlags[TypeFormatFlags["InArrayType"] = 524288] = "InArrayType"; + TypeFormatFlags[TypeFormatFlags["InElementType"] = 2097152] = "InElementType"; + TypeFormatFlags[TypeFormatFlags["InFirstTypeArgument"] = 4194304] = "InFirstTypeArgument"; + TypeFormatFlags[TypeFormatFlags["InTypeAlias"] = 8388608] = "InTypeAlias"; + /** @deprecated */ TypeFormatFlags[TypeFormatFlags["WriteOwnNameForAnyLike"] = 0] = "WriteOwnNameForAnyLike"; + TypeFormatFlags[TypeFormatFlags["NodeBuilderFlagsMask"] = 9469291] = "NodeBuilderFlagsMask"; + })(TypeFormatFlags = ts.TypeFormatFlags || (ts.TypeFormatFlags = {})); + var SymbolFormatFlags; + (function (SymbolFormatFlags) { + SymbolFormatFlags[SymbolFormatFlags["None"] = 0] = "None"; + // Write symbols's type argument if it is instantiated symbol + // eg. class C { p: T } <-- Show p as C.p here + // var a: C; + // var p = a.p; <--- Here p is property of C so show it as C.p instead of just C.p + SymbolFormatFlags[SymbolFormatFlags["WriteTypeParametersOrArguments"] = 1] = "WriteTypeParametersOrArguments"; + // Use only external alias information to get the symbol name in the given context + // eg. module m { export class c { } } import x = m.c; + // When this flag is specified m.c will be used to refer to the class instead of alias symbol x + SymbolFormatFlags[SymbolFormatFlags["UseOnlyExternalAliasing"] = 2] = "UseOnlyExternalAliasing"; + // Build symbol name using any nodes needed, instead of just components of an entity name + SymbolFormatFlags[SymbolFormatFlags["AllowAnyNodeKind"] = 4] = "AllowAnyNodeKind"; + // Prefer aliases which are not directly visible + SymbolFormatFlags[SymbolFormatFlags["UseAliasDefinedOutsideCurrentScope"] = 8] = "UseAliasDefinedOutsideCurrentScope"; + // Skip building an accessible symbol chain + /* @internal */ SymbolFormatFlags[SymbolFormatFlags["DoNotIncludeSymbolChain"] = 16] = "DoNotIncludeSymbolChain"; + })(SymbolFormatFlags = ts.SymbolFormatFlags || (ts.SymbolFormatFlags = {})); + /* @internal */ + var SymbolAccessibility; + (function (SymbolAccessibility) { + SymbolAccessibility[SymbolAccessibility["Accessible"] = 0] = "Accessible"; + SymbolAccessibility[SymbolAccessibility["NotAccessible"] = 1] = "NotAccessible"; + SymbolAccessibility[SymbolAccessibility["CannotBeNamed"] = 2] = "CannotBeNamed"; + })(SymbolAccessibility = ts.SymbolAccessibility || (ts.SymbolAccessibility = {})); + /* @internal */ + var SyntheticSymbolKind; + (function (SyntheticSymbolKind) { + SyntheticSymbolKind[SyntheticSymbolKind["UnionOrIntersection"] = 0] = "UnionOrIntersection"; + SyntheticSymbolKind[SyntheticSymbolKind["Spread"] = 1] = "Spread"; + })(SyntheticSymbolKind = ts.SyntheticSymbolKind || (ts.SyntheticSymbolKind = {})); + var TypePredicateKind; + (function (TypePredicateKind) { + TypePredicateKind[TypePredicateKind["This"] = 0] = "This"; + TypePredicateKind[TypePredicateKind["Identifier"] = 1] = "Identifier"; + })(TypePredicateKind = ts.TypePredicateKind || (ts.TypePredicateKind = {})); + /** Indicates how to serialize the name for a TypeReferenceNode when emitting decorator metadata */ + /* @internal */ + var TypeReferenceSerializationKind; + (function (TypeReferenceSerializationKind) { + TypeReferenceSerializationKind[TypeReferenceSerializationKind["Unknown"] = 0] = "Unknown"; + // should be emitted using a safe fallback. + TypeReferenceSerializationKind[TypeReferenceSerializationKind["TypeWithConstructSignatureAndValue"] = 1] = "TypeWithConstructSignatureAndValue"; + // function that can be reached at runtime (e.g. a `class` + // declaration or a `var` declaration for the static side + // of a type, such as the global `Promise` type in lib.d.ts). + TypeReferenceSerializationKind[TypeReferenceSerializationKind["VoidNullableOrNeverType"] = 2] = "VoidNullableOrNeverType"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["NumberLikeType"] = 3] = "NumberLikeType"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["BigIntLikeType"] = 4] = "BigIntLikeType"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["StringLikeType"] = 5] = "StringLikeType"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["BooleanType"] = 6] = "BooleanType"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["ArrayLikeType"] = 7] = "ArrayLikeType"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["ESSymbolType"] = 8] = "ESSymbolType"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["Promise"] = 9] = "Promise"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["TypeWithCallSignature"] = 10] = "TypeWithCallSignature"; + // with call signatures. + TypeReferenceSerializationKind[TypeReferenceSerializationKind["ObjectType"] = 11] = "ObjectType"; + })(TypeReferenceSerializationKind = ts.TypeReferenceSerializationKind || (ts.TypeReferenceSerializationKind = {})); + var SymbolFlags; + (function (SymbolFlags) { + SymbolFlags[SymbolFlags["None"] = 0] = "None"; + SymbolFlags[SymbolFlags["FunctionScopedVariable"] = 1] = "FunctionScopedVariable"; + SymbolFlags[SymbolFlags["BlockScopedVariable"] = 2] = "BlockScopedVariable"; + SymbolFlags[SymbolFlags["Property"] = 4] = "Property"; + SymbolFlags[SymbolFlags["EnumMember"] = 8] = "EnumMember"; + SymbolFlags[SymbolFlags["Function"] = 16] = "Function"; + SymbolFlags[SymbolFlags["Class"] = 32] = "Class"; + SymbolFlags[SymbolFlags["Interface"] = 64] = "Interface"; + SymbolFlags[SymbolFlags["ConstEnum"] = 128] = "ConstEnum"; + SymbolFlags[SymbolFlags["RegularEnum"] = 256] = "RegularEnum"; + SymbolFlags[SymbolFlags["ValueModule"] = 512] = "ValueModule"; + SymbolFlags[SymbolFlags["NamespaceModule"] = 1024] = "NamespaceModule"; + SymbolFlags[SymbolFlags["TypeLiteral"] = 2048] = "TypeLiteral"; + SymbolFlags[SymbolFlags["ObjectLiteral"] = 4096] = "ObjectLiteral"; + SymbolFlags[SymbolFlags["Method"] = 8192] = "Method"; + SymbolFlags[SymbolFlags["Constructor"] = 16384] = "Constructor"; + SymbolFlags[SymbolFlags["GetAccessor"] = 32768] = "GetAccessor"; + SymbolFlags[SymbolFlags["SetAccessor"] = 65536] = "SetAccessor"; + SymbolFlags[SymbolFlags["Signature"] = 131072] = "Signature"; + SymbolFlags[SymbolFlags["TypeParameter"] = 262144] = "TypeParameter"; + SymbolFlags[SymbolFlags["TypeAlias"] = 524288] = "TypeAlias"; + SymbolFlags[SymbolFlags["ExportValue"] = 1048576] = "ExportValue"; + SymbolFlags[SymbolFlags["Alias"] = 2097152] = "Alias"; + SymbolFlags[SymbolFlags["Prototype"] = 4194304] = "Prototype"; + SymbolFlags[SymbolFlags["ExportStar"] = 8388608] = "ExportStar"; + SymbolFlags[SymbolFlags["Optional"] = 16777216] = "Optional"; + SymbolFlags[SymbolFlags["Transient"] = 33554432] = "Transient"; + SymbolFlags[SymbolFlags["Assignment"] = 67108864] = "Assignment"; + SymbolFlags[SymbolFlags["ModuleExports"] = 134217728] = "ModuleExports"; + /* @internal */ + SymbolFlags[SymbolFlags["All"] = 67108863] = "All"; + SymbolFlags[SymbolFlags["Enum"] = 384] = "Enum"; + SymbolFlags[SymbolFlags["Variable"] = 3] = "Variable"; + SymbolFlags[SymbolFlags["Value"] = 67220415] = "Value"; + SymbolFlags[SymbolFlags["Type"] = 67897832] = "Type"; + SymbolFlags[SymbolFlags["Namespace"] = 1920] = "Namespace"; + SymbolFlags[SymbolFlags["Module"] = 1536] = "Module"; + SymbolFlags[SymbolFlags["Accessor"] = 98304] = "Accessor"; + // Variables can be redeclared, but can not redeclare a block-scoped declaration with the + // same name, or any other value that is not a variable, e.g. ValueModule or Class + SymbolFlags[SymbolFlags["FunctionScopedVariableExcludes"] = 67220414] = "FunctionScopedVariableExcludes"; + // Block-scoped declarations are not allowed to be re-declared + // they can not merge with anything in the value space + SymbolFlags[SymbolFlags["BlockScopedVariableExcludes"] = 67220415] = "BlockScopedVariableExcludes"; + SymbolFlags[SymbolFlags["ParameterExcludes"] = 67220415] = "ParameterExcludes"; + SymbolFlags[SymbolFlags["PropertyExcludes"] = 0] = "PropertyExcludes"; + SymbolFlags[SymbolFlags["EnumMemberExcludes"] = 68008959] = "EnumMemberExcludes"; + SymbolFlags[SymbolFlags["FunctionExcludes"] = 67219887] = "FunctionExcludes"; + SymbolFlags[SymbolFlags["ClassExcludes"] = 68008383] = "ClassExcludes"; + SymbolFlags[SymbolFlags["InterfaceExcludes"] = 67897736] = "InterfaceExcludes"; + SymbolFlags[SymbolFlags["RegularEnumExcludes"] = 68008191] = "RegularEnumExcludes"; + SymbolFlags[SymbolFlags["ConstEnumExcludes"] = 68008831] = "ConstEnumExcludes"; + SymbolFlags[SymbolFlags["ValueModuleExcludes"] = 110735] = "ValueModuleExcludes"; + SymbolFlags[SymbolFlags["NamespaceModuleExcludes"] = 0] = "NamespaceModuleExcludes"; + SymbolFlags[SymbolFlags["MethodExcludes"] = 67212223] = "MethodExcludes"; + SymbolFlags[SymbolFlags["GetAccessorExcludes"] = 67154879] = "GetAccessorExcludes"; + SymbolFlags[SymbolFlags["SetAccessorExcludes"] = 67187647] = "SetAccessorExcludes"; + SymbolFlags[SymbolFlags["TypeParameterExcludes"] = 67635688] = "TypeParameterExcludes"; + SymbolFlags[SymbolFlags["TypeAliasExcludes"] = 67897832] = "TypeAliasExcludes"; + SymbolFlags[SymbolFlags["AliasExcludes"] = 2097152] = "AliasExcludes"; + SymbolFlags[SymbolFlags["ModuleMember"] = 2623475] = "ModuleMember"; + SymbolFlags[SymbolFlags["ExportHasLocal"] = 944] = "ExportHasLocal"; + SymbolFlags[SymbolFlags["BlockScoped"] = 418] = "BlockScoped"; + SymbolFlags[SymbolFlags["PropertyOrAccessor"] = 98308] = "PropertyOrAccessor"; + SymbolFlags[SymbolFlags["ClassMember"] = 106500] = "ClassMember"; + /* @internal */ + // The set of things we consider semantically classifiable. Used to speed up the LS during + // classification. + SymbolFlags[SymbolFlags["Classifiable"] = 2885600] = "Classifiable"; + /* @internal */ + SymbolFlags[SymbolFlags["LateBindingContainer"] = 6240] = "LateBindingContainer"; + })(SymbolFlags = ts.SymbolFlags || (ts.SymbolFlags = {})); + /* @internal */ + var EnumKind; + (function (EnumKind) { + EnumKind[EnumKind["Numeric"] = 0] = "Numeric"; + EnumKind[EnumKind["Literal"] = 1] = "Literal"; // Literal enum (each member has a TypeFlags.EnumLiteral type) + })(EnumKind = ts.EnumKind || (ts.EnumKind = {})); + /* @internal */ + var CheckFlags; + (function (CheckFlags) { + CheckFlags[CheckFlags["Instantiated"] = 1] = "Instantiated"; + CheckFlags[CheckFlags["SyntheticProperty"] = 2] = "SyntheticProperty"; + CheckFlags[CheckFlags["SyntheticMethod"] = 4] = "SyntheticMethod"; + CheckFlags[CheckFlags["Readonly"] = 8] = "Readonly"; + CheckFlags[CheckFlags["Partial"] = 16] = "Partial"; + CheckFlags[CheckFlags["HasNonUniformType"] = 32] = "HasNonUniformType"; + CheckFlags[CheckFlags["ContainsPublic"] = 64] = "ContainsPublic"; + CheckFlags[CheckFlags["ContainsProtected"] = 128] = "ContainsProtected"; + CheckFlags[CheckFlags["ContainsPrivate"] = 256] = "ContainsPrivate"; + CheckFlags[CheckFlags["ContainsStatic"] = 512] = "ContainsStatic"; + CheckFlags[CheckFlags["Late"] = 1024] = "Late"; + CheckFlags[CheckFlags["ReverseMapped"] = 2048] = "ReverseMapped"; + CheckFlags[CheckFlags["OptionalParameter"] = 4096] = "OptionalParameter"; + CheckFlags[CheckFlags["RestParameter"] = 8192] = "RestParameter"; + CheckFlags[CheckFlags["Synthetic"] = 6] = "Synthetic"; + })(CheckFlags = ts.CheckFlags || (ts.CheckFlags = {})); + var InternalSymbolName; + (function (InternalSymbolName) { + InternalSymbolName["Call"] = "__call"; + InternalSymbolName["Constructor"] = "__constructor"; + InternalSymbolName["New"] = "__new"; + InternalSymbolName["Index"] = "__index"; + InternalSymbolName["ExportStar"] = "__export"; + InternalSymbolName["Global"] = "__global"; + InternalSymbolName["Missing"] = "__missing"; + InternalSymbolName["Type"] = "__type"; + InternalSymbolName["Object"] = "__object"; + InternalSymbolName["JSXAttributes"] = "__jsxAttributes"; + InternalSymbolName["Class"] = "__class"; + InternalSymbolName["Function"] = "__function"; + InternalSymbolName["Computed"] = "__computed"; + InternalSymbolName["Resolving"] = "__resolving__"; + InternalSymbolName["ExportEquals"] = "export="; + InternalSymbolName["Default"] = "default"; + InternalSymbolName["This"] = "this"; + })(InternalSymbolName = ts.InternalSymbolName || (ts.InternalSymbolName = {})); + /* @internal */ + var NodeCheckFlags; + (function (NodeCheckFlags) { + NodeCheckFlags[NodeCheckFlags["TypeChecked"] = 1] = "TypeChecked"; + NodeCheckFlags[NodeCheckFlags["LexicalThis"] = 2] = "LexicalThis"; + NodeCheckFlags[NodeCheckFlags["CaptureThis"] = 4] = "CaptureThis"; + NodeCheckFlags[NodeCheckFlags["CaptureNewTarget"] = 8] = "CaptureNewTarget"; + NodeCheckFlags[NodeCheckFlags["SuperInstance"] = 256] = "SuperInstance"; + NodeCheckFlags[NodeCheckFlags["SuperStatic"] = 512] = "SuperStatic"; + NodeCheckFlags[NodeCheckFlags["ContextChecked"] = 1024] = "ContextChecked"; + NodeCheckFlags[NodeCheckFlags["AsyncMethodWithSuper"] = 2048] = "AsyncMethodWithSuper"; + NodeCheckFlags[NodeCheckFlags["AsyncMethodWithSuperBinding"] = 4096] = "AsyncMethodWithSuperBinding"; + NodeCheckFlags[NodeCheckFlags["CaptureArguments"] = 8192] = "CaptureArguments"; + NodeCheckFlags[NodeCheckFlags["EnumValuesComputed"] = 16384] = "EnumValuesComputed"; + NodeCheckFlags[NodeCheckFlags["LexicalModuleMergesWithClass"] = 32768] = "LexicalModuleMergesWithClass"; + NodeCheckFlags[NodeCheckFlags["LoopWithCapturedBlockScopedBinding"] = 65536] = "LoopWithCapturedBlockScopedBinding"; + NodeCheckFlags[NodeCheckFlags["ContainsCapturedBlockScopeBinding"] = 131072] = "ContainsCapturedBlockScopeBinding"; + NodeCheckFlags[NodeCheckFlags["CapturedBlockScopedBinding"] = 262144] = "CapturedBlockScopedBinding"; + NodeCheckFlags[NodeCheckFlags["BlockScopedBindingInLoop"] = 524288] = "BlockScopedBindingInLoop"; + NodeCheckFlags[NodeCheckFlags["ClassWithBodyScopedClassBinding"] = 1048576] = "ClassWithBodyScopedClassBinding"; + NodeCheckFlags[NodeCheckFlags["BodyScopedClassBinding"] = 2097152] = "BodyScopedClassBinding"; + NodeCheckFlags[NodeCheckFlags["NeedsLoopOutParameter"] = 4194304] = "NeedsLoopOutParameter"; + NodeCheckFlags[NodeCheckFlags["AssignmentsMarked"] = 8388608] = "AssignmentsMarked"; + NodeCheckFlags[NodeCheckFlags["ClassWithConstructorReference"] = 16777216] = "ClassWithConstructorReference"; + NodeCheckFlags[NodeCheckFlags["ConstructorReferenceInClass"] = 33554432] = "ConstructorReferenceInClass"; + })(NodeCheckFlags = ts.NodeCheckFlags || (ts.NodeCheckFlags = {})); + var TypeFlags; + (function (TypeFlags) { + TypeFlags[TypeFlags["Any"] = 1] = "Any"; + TypeFlags[TypeFlags["Unknown"] = 2] = "Unknown"; + TypeFlags[TypeFlags["String"] = 4] = "String"; + TypeFlags[TypeFlags["Number"] = 8] = "Number"; + TypeFlags[TypeFlags["Boolean"] = 16] = "Boolean"; + TypeFlags[TypeFlags["Enum"] = 32] = "Enum"; + TypeFlags[TypeFlags["BigInt"] = 64] = "BigInt"; + TypeFlags[TypeFlags["StringLiteral"] = 128] = "StringLiteral"; + TypeFlags[TypeFlags["NumberLiteral"] = 256] = "NumberLiteral"; + TypeFlags[TypeFlags["BooleanLiteral"] = 512] = "BooleanLiteral"; + TypeFlags[TypeFlags["EnumLiteral"] = 1024] = "EnumLiteral"; + TypeFlags[TypeFlags["BigIntLiteral"] = 2048] = "BigIntLiteral"; + TypeFlags[TypeFlags["ESSymbol"] = 4096] = "ESSymbol"; + TypeFlags[TypeFlags["UniqueESSymbol"] = 8192] = "UniqueESSymbol"; + TypeFlags[TypeFlags["Void"] = 16384] = "Void"; + TypeFlags[TypeFlags["Undefined"] = 32768] = "Undefined"; + TypeFlags[TypeFlags["Null"] = 65536] = "Null"; + TypeFlags[TypeFlags["Never"] = 131072] = "Never"; + TypeFlags[TypeFlags["TypeParameter"] = 262144] = "TypeParameter"; + TypeFlags[TypeFlags["Object"] = 524288] = "Object"; + TypeFlags[TypeFlags["Union"] = 1048576] = "Union"; + TypeFlags[TypeFlags["Intersection"] = 2097152] = "Intersection"; + TypeFlags[TypeFlags["Index"] = 4194304] = "Index"; + TypeFlags[TypeFlags["IndexedAccess"] = 8388608] = "IndexedAccess"; + TypeFlags[TypeFlags["Conditional"] = 16777216] = "Conditional"; + TypeFlags[TypeFlags["Substitution"] = 33554432] = "Substitution"; + TypeFlags[TypeFlags["NonPrimitive"] = 67108864] = "NonPrimitive"; + /* @internal */ + TypeFlags[TypeFlags["ContainsWideningType"] = 134217728] = "ContainsWideningType"; + /* @internal */ + TypeFlags[TypeFlags["ContainsObjectLiteral"] = 268435456] = "ContainsObjectLiteral"; + /* @internal */ + TypeFlags[TypeFlags["ContainsAnyFunctionType"] = 536870912] = "ContainsAnyFunctionType"; + /* @internal */ + TypeFlags[TypeFlags["AnyOrUnknown"] = 3] = "AnyOrUnknown"; + /* @internal */ + TypeFlags[TypeFlags["Nullable"] = 98304] = "Nullable"; + TypeFlags[TypeFlags["Literal"] = 2944] = "Literal"; + TypeFlags[TypeFlags["Unit"] = 109440] = "Unit"; + TypeFlags[TypeFlags["StringOrNumberLiteral"] = 384] = "StringOrNumberLiteral"; + /* @internal */ + TypeFlags[TypeFlags["StringOrNumberLiteralOrUnique"] = 8576] = "StringOrNumberLiteralOrUnique"; + /* @internal */ + TypeFlags[TypeFlags["DefinitelyFalsy"] = 117632] = "DefinitelyFalsy"; + TypeFlags[TypeFlags["PossiblyFalsy"] = 117724] = "PossiblyFalsy"; + /* @internal */ + TypeFlags[TypeFlags["Intrinsic"] = 67359327] = "Intrinsic"; + /* @internal */ + TypeFlags[TypeFlags["Primitive"] = 131068] = "Primitive"; + TypeFlags[TypeFlags["StringLike"] = 132] = "StringLike"; + TypeFlags[TypeFlags["NumberLike"] = 296] = "NumberLike"; + TypeFlags[TypeFlags["BigIntLike"] = 2112] = "BigIntLike"; + TypeFlags[TypeFlags["BooleanLike"] = 528] = "BooleanLike"; + TypeFlags[TypeFlags["EnumLike"] = 1056] = "EnumLike"; + TypeFlags[TypeFlags["ESSymbolLike"] = 12288] = "ESSymbolLike"; + TypeFlags[TypeFlags["VoidLike"] = 49152] = "VoidLike"; + /* @internal */ + TypeFlags[TypeFlags["DisjointDomains"] = 67238908] = "DisjointDomains"; + TypeFlags[TypeFlags["UnionOrIntersection"] = 3145728] = "UnionOrIntersection"; + TypeFlags[TypeFlags["StructuredType"] = 3670016] = "StructuredType"; + TypeFlags[TypeFlags["TypeVariable"] = 8650752] = "TypeVariable"; + TypeFlags[TypeFlags["InstantiableNonPrimitive"] = 58982400] = "InstantiableNonPrimitive"; + TypeFlags[TypeFlags["InstantiablePrimitive"] = 4194304] = "InstantiablePrimitive"; + TypeFlags[TypeFlags["Instantiable"] = 63176704] = "Instantiable"; + TypeFlags[TypeFlags["StructuredOrInstantiable"] = 66846720] = "StructuredOrInstantiable"; + // 'Narrowable' types are types where narrowing actually narrows. + // This *should* be every type other than null, undefined, void, and never + TypeFlags[TypeFlags["Narrowable"] = 133970943] = "Narrowable"; + TypeFlags[TypeFlags["NotUnionOrUnit"] = 67637251] = "NotUnionOrUnit"; + /* @internal */ + TypeFlags[TypeFlags["NotPrimitiveUnion"] = 66994211] = "NotPrimitiveUnion"; + /* @internal */ + TypeFlags[TypeFlags["RequiresWidening"] = 402653184] = "RequiresWidening"; + /* @internal */ + TypeFlags[TypeFlags["PropagatingFlags"] = 939524096] = "PropagatingFlags"; + // The following flags are used for different purposes during union and intersection type construction + /* @internal */ + TypeFlags[TypeFlags["NonWideningType"] = 134217728] = "NonWideningType"; + /* @internal */ + TypeFlags[TypeFlags["Wildcard"] = 268435456] = "Wildcard"; + /* @internal */ + TypeFlags[TypeFlags["EmptyObject"] = 536870912] = "EmptyObject"; + /* @internal */ + TypeFlags[TypeFlags["ConstructionFlags"] = 939524096] = "ConstructionFlags"; + // The following flag is used for different purposes by maybeTypeOfKind + /* @internal */ + TypeFlags[TypeFlags["GenericMappedType"] = 134217728] = "GenericMappedType"; + })(TypeFlags = ts.TypeFlags || (ts.TypeFlags = {})); + var ObjectFlags; + (function (ObjectFlags) { + ObjectFlags[ObjectFlags["Class"] = 1] = "Class"; + ObjectFlags[ObjectFlags["Interface"] = 2] = "Interface"; + ObjectFlags[ObjectFlags["Reference"] = 4] = "Reference"; + ObjectFlags[ObjectFlags["Tuple"] = 8] = "Tuple"; + ObjectFlags[ObjectFlags["Anonymous"] = 16] = "Anonymous"; + ObjectFlags[ObjectFlags["Mapped"] = 32] = "Mapped"; + ObjectFlags[ObjectFlags["Instantiated"] = 64] = "Instantiated"; + ObjectFlags[ObjectFlags["ObjectLiteral"] = 128] = "ObjectLiteral"; + ObjectFlags[ObjectFlags["EvolvingArray"] = 256] = "EvolvingArray"; + ObjectFlags[ObjectFlags["ObjectLiteralPatternWithComputedProperties"] = 512] = "ObjectLiteralPatternWithComputedProperties"; + ObjectFlags[ObjectFlags["ContainsSpread"] = 1024] = "ContainsSpread"; + ObjectFlags[ObjectFlags["ReverseMapped"] = 2048] = "ReverseMapped"; + ObjectFlags[ObjectFlags["JsxAttributes"] = 4096] = "JsxAttributes"; + ObjectFlags[ObjectFlags["MarkerType"] = 8192] = "MarkerType"; + ObjectFlags[ObjectFlags["JSLiteral"] = 16384] = "JSLiteral"; + ObjectFlags[ObjectFlags["FreshLiteral"] = 32768] = "FreshLiteral"; + ObjectFlags[ObjectFlags["ClassOrInterface"] = 3] = "ClassOrInterface"; + })(ObjectFlags = ts.ObjectFlags || (ts.ObjectFlags = {})); + /* @internal */ + var Variance; + (function (Variance) { + Variance[Variance["Invariant"] = 0] = "Invariant"; + Variance[Variance["Covariant"] = 1] = "Covariant"; + Variance[Variance["Contravariant"] = 2] = "Contravariant"; + Variance[Variance["Bivariant"] = 3] = "Bivariant"; + Variance[Variance["Independent"] = 4] = "Independent"; + })(Variance = ts.Variance || (ts.Variance = {})); + /* @internal */ + var JsxReferenceKind; + (function (JsxReferenceKind) { + JsxReferenceKind[JsxReferenceKind["Component"] = 0] = "Component"; + JsxReferenceKind[JsxReferenceKind["Function"] = 1] = "Function"; + JsxReferenceKind[JsxReferenceKind["Mixed"] = 2] = "Mixed"; + })(JsxReferenceKind = ts.JsxReferenceKind || (ts.JsxReferenceKind = {})); + var SignatureKind; + (function (SignatureKind) { + SignatureKind[SignatureKind["Call"] = 0] = "Call"; + SignatureKind[SignatureKind["Construct"] = 1] = "Construct"; + })(SignatureKind = ts.SignatureKind || (ts.SignatureKind = {})); + var IndexKind; + (function (IndexKind) { + IndexKind[IndexKind["String"] = 0] = "String"; + IndexKind[IndexKind["Number"] = 1] = "Number"; + })(IndexKind = ts.IndexKind || (ts.IndexKind = {})); + var InferencePriority; + (function (InferencePriority) { + InferencePriority[InferencePriority["NakedTypeVariable"] = 1] = "NakedTypeVariable"; + InferencePriority[InferencePriority["HomomorphicMappedType"] = 2] = "HomomorphicMappedType"; + InferencePriority[InferencePriority["MappedTypeConstraint"] = 4] = "MappedTypeConstraint"; + InferencePriority[InferencePriority["ReturnType"] = 8] = "ReturnType"; + InferencePriority[InferencePriority["LiteralKeyof"] = 16] = "LiteralKeyof"; + InferencePriority[InferencePriority["NoConstraints"] = 32] = "NoConstraints"; + InferencePriority[InferencePriority["AlwaysStrict"] = 64] = "AlwaysStrict"; + InferencePriority[InferencePriority["PriorityImpliesCombination"] = 28] = "PriorityImpliesCombination"; + })(InferencePriority = ts.InferencePriority || (ts.InferencePriority = {})); + /* @internal */ + var InferenceFlags; + (function (InferenceFlags) { + InferenceFlags[InferenceFlags["None"] = 0] = "None"; + InferenceFlags[InferenceFlags["NoDefault"] = 1] = "NoDefault"; + InferenceFlags[InferenceFlags["AnyDefault"] = 2] = "AnyDefault"; + })(InferenceFlags = ts.InferenceFlags || (ts.InferenceFlags = {})); + /** + * Ternary values are defined such that + * x & y is False if either x or y is False. + * x & y is Maybe if either x or y is Maybe, but neither x or y is False. + * x & y is True if both x and y are True. + * x | y is False if both x and y are False. + * x | y is Maybe if either x or y is Maybe, but neither x or y is True. + * x | y is True if either x or y is True. + */ + /* @internal */ + var Ternary; + (function (Ternary) { + Ternary[Ternary["False"] = 0] = "False"; + Ternary[Ternary["Maybe"] = 1] = "Maybe"; + Ternary[Ternary["True"] = -1] = "True"; + })(Ternary = ts.Ternary || (ts.Ternary = {})); + /* @internal */ + var AssignmentDeclarationKind; + (function (AssignmentDeclarationKind) { + AssignmentDeclarationKind[AssignmentDeclarationKind["None"] = 0] = "None"; + /// exports.name = expr + AssignmentDeclarationKind[AssignmentDeclarationKind["ExportsProperty"] = 1] = "ExportsProperty"; + /// module.exports = expr + AssignmentDeclarationKind[AssignmentDeclarationKind["ModuleExports"] = 2] = "ModuleExports"; + /// className.prototype.name = expr + AssignmentDeclarationKind[AssignmentDeclarationKind["PrototypeProperty"] = 3] = "PrototypeProperty"; + /// this.name = expr + AssignmentDeclarationKind[AssignmentDeclarationKind["ThisProperty"] = 4] = "ThisProperty"; + // F.name = expr + AssignmentDeclarationKind[AssignmentDeclarationKind["Property"] = 5] = "Property"; + // F.prototype = { ... } + AssignmentDeclarationKind[AssignmentDeclarationKind["Prototype"] = 6] = "Prototype"; + // Object.defineProperty(x, 'name', { value: any, writable?: boolean (false by default) }); + // Object.defineProperty(x, 'name', { get: Function, set: Function }); + // Object.defineProperty(x, 'name', { get: Function }); + // Object.defineProperty(x, 'name', { set: Function }); + AssignmentDeclarationKind[AssignmentDeclarationKind["ObjectDefinePropertyValue"] = 7] = "ObjectDefinePropertyValue"; + // Object.defineProperty(exports || module.exports, 'name', ...); + AssignmentDeclarationKind[AssignmentDeclarationKind["ObjectDefinePropertyExports"] = 8] = "ObjectDefinePropertyExports"; + // Object.defineProperty(Foo.prototype, 'name', ...); + AssignmentDeclarationKind[AssignmentDeclarationKind["ObjectDefinePrototypeProperty"] = 9] = "ObjectDefinePrototypeProperty"; + })(AssignmentDeclarationKind = ts.AssignmentDeclarationKind || (ts.AssignmentDeclarationKind = {})); + var DiagnosticCategory; + (function (DiagnosticCategory) { + DiagnosticCategory[DiagnosticCategory["Warning"] = 0] = "Warning"; + DiagnosticCategory[DiagnosticCategory["Error"] = 1] = "Error"; + DiagnosticCategory[DiagnosticCategory["Suggestion"] = 2] = "Suggestion"; + DiagnosticCategory[DiagnosticCategory["Message"] = 3] = "Message"; + })(DiagnosticCategory = ts.DiagnosticCategory || (ts.DiagnosticCategory = {})); + /* @internal */ + function diagnosticCategoryName(d, lowerCase) { + if (lowerCase === void 0) { lowerCase = true; } + var name = DiagnosticCategory[d.category]; + return lowerCase ? name.toLowerCase() : name; + } + ts.diagnosticCategoryName = diagnosticCategoryName; + var ModuleResolutionKind; + (function (ModuleResolutionKind) { + ModuleResolutionKind[ModuleResolutionKind["Classic"] = 1] = "Classic"; + ModuleResolutionKind[ModuleResolutionKind["NodeJs"] = 2] = "NodeJs"; + })(ModuleResolutionKind = ts.ModuleResolutionKind || (ts.ModuleResolutionKind = {})); + var ModuleKind; + (function (ModuleKind) { + ModuleKind[ModuleKind["None"] = 0] = "None"; + ModuleKind[ModuleKind["CommonJS"] = 1] = "CommonJS"; + ModuleKind[ModuleKind["AMD"] = 2] = "AMD"; + ModuleKind[ModuleKind["UMD"] = 3] = "UMD"; + ModuleKind[ModuleKind["System"] = 4] = "System"; + ModuleKind[ModuleKind["ES2015"] = 5] = "ES2015"; + ModuleKind[ModuleKind["ESNext"] = 6] = "ESNext"; + })(ModuleKind = ts.ModuleKind || (ts.ModuleKind = {})); + var JsxEmit; + (function (JsxEmit) { + JsxEmit[JsxEmit["None"] = 0] = "None"; + JsxEmit[JsxEmit["Preserve"] = 1] = "Preserve"; + JsxEmit[JsxEmit["React"] = 2] = "React"; + JsxEmit[JsxEmit["ReactNative"] = 3] = "ReactNative"; + })(JsxEmit = ts.JsxEmit || (ts.JsxEmit = {})); + var NewLineKind; + (function (NewLineKind) { + NewLineKind[NewLineKind["CarriageReturnLineFeed"] = 0] = "CarriageReturnLineFeed"; + NewLineKind[NewLineKind["LineFeed"] = 1] = "LineFeed"; + })(NewLineKind = ts.NewLineKind || (ts.NewLineKind = {})); + var ScriptKind; + (function (ScriptKind) { + ScriptKind[ScriptKind["Unknown"] = 0] = "Unknown"; + ScriptKind[ScriptKind["JS"] = 1] = "JS"; + ScriptKind[ScriptKind["JSX"] = 2] = "JSX"; + ScriptKind[ScriptKind["TS"] = 3] = "TS"; + ScriptKind[ScriptKind["TSX"] = 4] = "TSX"; + ScriptKind[ScriptKind["External"] = 5] = "External"; + ScriptKind[ScriptKind["JSON"] = 6] = "JSON"; + /** + * Used on extensions that doesn't define the ScriptKind but the content defines it. + * Deferred extensions are going to be included in all project contexts. + */ + ScriptKind[ScriptKind["Deferred"] = 7] = "Deferred"; + })(ScriptKind = ts.ScriptKind || (ts.ScriptKind = {})); + var ScriptTarget; + (function (ScriptTarget) { + ScriptTarget[ScriptTarget["ES3"] = 0] = "ES3"; + ScriptTarget[ScriptTarget["ES5"] = 1] = "ES5"; + ScriptTarget[ScriptTarget["ES2015"] = 2] = "ES2015"; + ScriptTarget[ScriptTarget["ES2016"] = 3] = "ES2016"; + ScriptTarget[ScriptTarget["ES2017"] = 4] = "ES2017"; + ScriptTarget[ScriptTarget["ES2018"] = 5] = "ES2018"; + ScriptTarget[ScriptTarget["ESNext"] = 6] = "ESNext"; + ScriptTarget[ScriptTarget["JSON"] = 100] = "JSON"; + ScriptTarget[ScriptTarget["Latest"] = 6] = "Latest"; + })(ScriptTarget = ts.ScriptTarget || (ts.ScriptTarget = {})); + var LanguageVariant; + (function (LanguageVariant) { + LanguageVariant[LanguageVariant["Standard"] = 0] = "Standard"; + LanguageVariant[LanguageVariant["JSX"] = 1] = "JSX"; + })(LanguageVariant = ts.LanguageVariant || (ts.LanguageVariant = {})); + var WatchDirectoryFlags; + (function (WatchDirectoryFlags) { + WatchDirectoryFlags[WatchDirectoryFlags["None"] = 0] = "None"; + WatchDirectoryFlags[WatchDirectoryFlags["Recursive"] = 1] = "Recursive"; + })(WatchDirectoryFlags = ts.WatchDirectoryFlags || (ts.WatchDirectoryFlags = {})); + /* @internal */ + var CharacterCodes; + (function (CharacterCodes) { + CharacterCodes[CharacterCodes["nullCharacter"] = 0] = "nullCharacter"; + CharacterCodes[CharacterCodes["maxAsciiCharacter"] = 127] = "maxAsciiCharacter"; + CharacterCodes[CharacterCodes["lineFeed"] = 10] = "lineFeed"; + CharacterCodes[CharacterCodes["carriageReturn"] = 13] = "carriageReturn"; + CharacterCodes[CharacterCodes["lineSeparator"] = 8232] = "lineSeparator"; + CharacterCodes[CharacterCodes["paragraphSeparator"] = 8233] = "paragraphSeparator"; + CharacterCodes[CharacterCodes["nextLine"] = 133] = "nextLine"; + // Unicode 3.0 space characters + CharacterCodes[CharacterCodes["space"] = 32] = "space"; + CharacterCodes[CharacterCodes["nonBreakingSpace"] = 160] = "nonBreakingSpace"; + CharacterCodes[CharacterCodes["enQuad"] = 8192] = "enQuad"; + CharacterCodes[CharacterCodes["emQuad"] = 8193] = "emQuad"; + CharacterCodes[CharacterCodes["enSpace"] = 8194] = "enSpace"; + CharacterCodes[CharacterCodes["emSpace"] = 8195] = "emSpace"; + CharacterCodes[CharacterCodes["threePerEmSpace"] = 8196] = "threePerEmSpace"; + CharacterCodes[CharacterCodes["fourPerEmSpace"] = 8197] = "fourPerEmSpace"; + CharacterCodes[CharacterCodes["sixPerEmSpace"] = 8198] = "sixPerEmSpace"; + CharacterCodes[CharacterCodes["figureSpace"] = 8199] = "figureSpace"; + CharacterCodes[CharacterCodes["punctuationSpace"] = 8200] = "punctuationSpace"; + CharacterCodes[CharacterCodes["thinSpace"] = 8201] = "thinSpace"; + CharacterCodes[CharacterCodes["hairSpace"] = 8202] = "hairSpace"; + CharacterCodes[CharacterCodes["zeroWidthSpace"] = 8203] = "zeroWidthSpace"; + CharacterCodes[CharacterCodes["narrowNoBreakSpace"] = 8239] = "narrowNoBreakSpace"; + CharacterCodes[CharacterCodes["ideographicSpace"] = 12288] = "ideographicSpace"; + CharacterCodes[CharacterCodes["mathematicalSpace"] = 8287] = "mathematicalSpace"; + CharacterCodes[CharacterCodes["ogham"] = 5760] = "ogham"; + CharacterCodes[CharacterCodes["_"] = 95] = "_"; + CharacterCodes[CharacterCodes["$"] = 36] = "$"; + CharacterCodes[CharacterCodes["_0"] = 48] = "_0"; + CharacterCodes[CharacterCodes["_1"] = 49] = "_1"; + CharacterCodes[CharacterCodes["_2"] = 50] = "_2"; + CharacterCodes[CharacterCodes["_3"] = 51] = "_3"; + CharacterCodes[CharacterCodes["_4"] = 52] = "_4"; + CharacterCodes[CharacterCodes["_5"] = 53] = "_5"; + CharacterCodes[CharacterCodes["_6"] = 54] = "_6"; + CharacterCodes[CharacterCodes["_7"] = 55] = "_7"; + CharacterCodes[CharacterCodes["_8"] = 56] = "_8"; + CharacterCodes[CharacterCodes["_9"] = 57] = "_9"; + CharacterCodes[CharacterCodes["a"] = 97] = "a"; + CharacterCodes[CharacterCodes["b"] = 98] = "b"; + CharacterCodes[CharacterCodes["c"] = 99] = "c"; + CharacterCodes[CharacterCodes["d"] = 100] = "d"; + CharacterCodes[CharacterCodes["e"] = 101] = "e"; + CharacterCodes[CharacterCodes["f"] = 102] = "f"; + CharacterCodes[CharacterCodes["g"] = 103] = "g"; + CharacterCodes[CharacterCodes["h"] = 104] = "h"; + CharacterCodes[CharacterCodes["i"] = 105] = "i"; + CharacterCodes[CharacterCodes["j"] = 106] = "j"; + CharacterCodes[CharacterCodes["k"] = 107] = "k"; + CharacterCodes[CharacterCodes["l"] = 108] = "l"; + CharacterCodes[CharacterCodes["m"] = 109] = "m"; + CharacterCodes[CharacterCodes["n"] = 110] = "n"; + CharacterCodes[CharacterCodes["o"] = 111] = "o"; + CharacterCodes[CharacterCodes["p"] = 112] = "p"; + CharacterCodes[CharacterCodes["q"] = 113] = "q"; + CharacterCodes[CharacterCodes["r"] = 114] = "r"; + CharacterCodes[CharacterCodes["s"] = 115] = "s"; + CharacterCodes[CharacterCodes["t"] = 116] = "t"; + CharacterCodes[CharacterCodes["u"] = 117] = "u"; + CharacterCodes[CharacterCodes["v"] = 118] = "v"; + CharacterCodes[CharacterCodes["w"] = 119] = "w"; + CharacterCodes[CharacterCodes["x"] = 120] = "x"; + CharacterCodes[CharacterCodes["y"] = 121] = "y"; + CharacterCodes[CharacterCodes["z"] = 122] = "z"; + CharacterCodes[CharacterCodes["A"] = 65] = "A"; + CharacterCodes[CharacterCodes["B"] = 66] = "B"; + CharacterCodes[CharacterCodes["C"] = 67] = "C"; + CharacterCodes[CharacterCodes["D"] = 68] = "D"; + CharacterCodes[CharacterCodes["E"] = 69] = "E"; + CharacterCodes[CharacterCodes["F"] = 70] = "F"; + CharacterCodes[CharacterCodes["G"] = 71] = "G"; + CharacterCodes[CharacterCodes["H"] = 72] = "H"; + CharacterCodes[CharacterCodes["I"] = 73] = "I"; + CharacterCodes[CharacterCodes["J"] = 74] = "J"; + CharacterCodes[CharacterCodes["K"] = 75] = "K"; + CharacterCodes[CharacterCodes["L"] = 76] = "L"; + CharacterCodes[CharacterCodes["M"] = 77] = "M"; + CharacterCodes[CharacterCodes["N"] = 78] = "N"; + CharacterCodes[CharacterCodes["O"] = 79] = "O"; + CharacterCodes[CharacterCodes["P"] = 80] = "P"; + CharacterCodes[CharacterCodes["Q"] = 81] = "Q"; + CharacterCodes[CharacterCodes["R"] = 82] = "R"; + CharacterCodes[CharacterCodes["S"] = 83] = "S"; + CharacterCodes[CharacterCodes["T"] = 84] = "T"; + CharacterCodes[CharacterCodes["U"] = 85] = "U"; + CharacterCodes[CharacterCodes["V"] = 86] = "V"; + CharacterCodes[CharacterCodes["W"] = 87] = "W"; + CharacterCodes[CharacterCodes["X"] = 88] = "X"; + CharacterCodes[CharacterCodes["Y"] = 89] = "Y"; + CharacterCodes[CharacterCodes["Z"] = 90] = "Z"; + CharacterCodes[CharacterCodes["ampersand"] = 38] = "ampersand"; + CharacterCodes[CharacterCodes["asterisk"] = 42] = "asterisk"; + CharacterCodes[CharacterCodes["at"] = 64] = "at"; + CharacterCodes[CharacterCodes["backslash"] = 92] = "backslash"; + CharacterCodes[CharacterCodes["backtick"] = 96] = "backtick"; + CharacterCodes[CharacterCodes["bar"] = 124] = "bar"; + CharacterCodes[CharacterCodes["caret"] = 94] = "caret"; + CharacterCodes[CharacterCodes["closeBrace"] = 125] = "closeBrace"; + CharacterCodes[CharacterCodes["closeBracket"] = 93] = "closeBracket"; + CharacterCodes[CharacterCodes["closeParen"] = 41] = "closeParen"; + CharacterCodes[CharacterCodes["colon"] = 58] = "colon"; + CharacterCodes[CharacterCodes["comma"] = 44] = "comma"; + CharacterCodes[CharacterCodes["dot"] = 46] = "dot"; + CharacterCodes[CharacterCodes["doubleQuote"] = 34] = "doubleQuote"; + CharacterCodes[CharacterCodes["equals"] = 61] = "equals"; + CharacterCodes[CharacterCodes["exclamation"] = 33] = "exclamation"; + CharacterCodes[CharacterCodes["greaterThan"] = 62] = "greaterThan"; + CharacterCodes[CharacterCodes["hash"] = 35] = "hash"; + CharacterCodes[CharacterCodes["lessThan"] = 60] = "lessThan"; + CharacterCodes[CharacterCodes["minus"] = 45] = "minus"; + CharacterCodes[CharacterCodes["openBrace"] = 123] = "openBrace"; + CharacterCodes[CharacterCodes["openBracket"] = 91] = "openBracket"; + CharacterCodes[CharacterCodes["openParen"] = 40] = "openParen"; + CharacterCodes[CharacterCodes["percent"] = 37] = "percent"; + CharacterCodes[CharacterCodes["plus"] = 43] = "plus"; + CharacterCodes[CharacterCodes["question"] = 63] = "question"; + CharacterCodes[CharacterCodes["semicolon"] = 59] = "semicolon"; + CharacterCodes[CharacterCodes["singleQuote"] = 39] = "singleQuote"; + CharacterCodes[CharacterCodes["slash"] = 47] = "slash"; + CharacterCodes[CharacterCodes["tilde"] = 126] = "tilde"; + CharacterCodes[CharacterCodes["backspace"] = 8] = "backspace"; + CharacterCodes[CharacterCodes["formFeed"] = 12] = "formFeed"; + CharacterCodes[CharacterCodes["byteOrderMark"] = 65279] = "byteOrderMark"; + CharacterCodes[CharacterCodes["tab"] = 9] = "tab"; + CharacterCodes[CharacterCodes["verticalTab"] = 11] = "verticalTab"; + })(CharacterCodes = ts.CharacterCodes || (ts.CharacterCodes = {})); + var Extension; + (function (Extension) { + Extension["Ts"] = ".ts"; + Extension["Tsx"] = ".tsx"; + Extension["Dts"] = ".d.ts"; + Extension["Js"] = ".js"; + Extension["Jsx"] = ".jsx"; + Extension["Json"] = ".json"; + })(Extension = ts.Extension || (ts.Extension = {})); + /* @internal */ + var TransformFlags; + (function (TransformFlags) { + TransformFlags[TransformFlags["None"] = 0] = "None"; + // Facts + // - Flags used to indicate that a node or subtree contains syntax that requires transformation. + TransformFlags[TransformFlags["TypeScript"] = 1] = "TypeScript"; + TransformFlags[TransformFlags["ContainsTypeScript"] = 2] = "ContainsTypeScript"; + TransformFlags[TransformFlags["ContainsJsx"] = 4] = "ContainsJsx"; + TransformFlags[TransformFlags["ContainsESNext"] = 8] = "ContainsESNext"; + TransformFlags[TransformFlags["ContainsES2017"] = 16] = "ContainsES2017"; + TransformFlags[TransformFlags["ContainsES2016"] = 32] = "ContainsES2016"; + TransformFlags[TransformFlags["ES2015"] = 64] = "ES2015"; + TransformFlags[TransformFlags["ContainsES2015"] = 128] = "ContainsES2015"; + TransformFlags[TransformFlags["Generator"] = 256] = "Generator"; + TransformFlags[TransformFlags["ContainsGenerator"] = 512] = "ContainsGenerator"; + TransformFlags[TransformFlags["DestructuringAssignment"] = 1024] = "DestructuringAssignment"; + TransformFlags[TransformFlags["ContainsDestructuringAssignment"] = 2048] = "ContainsDestructuringAssignment"; + // Markers + // - Flags used to indicate that a subtree contains a specific transformation. + TransformFlags[TransformFlags["ContainsTypeScriptClassSyntax"] = 4096] = "ContainsTypeScriptClassSyntax"; + TransformFlags[TransformFlags["ContainsLexicalThis"] = 8192] = "ContainsLexicalThis"; + TransformFlags[TransformFlags["ContainsCapturedLexicalThis"] = 16384] = "ContainsCapturedLexicalThis"; + TransformFlags[TransformFlags["ContainsLexicalThisInComputedPropertyName"] = 32768] = "ContainsLexicalThisInComputedPropertyName"; + TransformFlags[TransformFlags["ContainsDefaultValueAssignments"] = 65536] = "ContainsDefaultValueAssignments"; + TransformFlags[TransformFlags["ContainsRestOrSpread"] = 131072] = "ContainsRestOrSpread"; + TransformFlags[TransformFlags["ContainsObjectRestOrSpread"] = 262144] = "ContainsObjectRestOrSpread"; + TransformFlags[TransformFlags["ContainsComputedPropertyName"] = 524288] = "ContainsComputedPropertyName"; + TransformFlags[TransformFlags["ContainsBlockScopedBinding"] = 1048576] = "ContainsBlockScopedBinding"; + TransformFlags[TransformFlags["ContainsBindingPattern"] = 2097152] = "ContainsBindingPattern"; + TransformFlags[TransformFlags["ContainsYield"] = 4194304] = "ContainsYield"; + TransformFlags[TransformFlags["ContainsHoistedDeclarationOrCompletion"] = 8388608] = "ContainsHoistedDeclarationOrCompletion"; + TransformFlags[TransformFlags["ContainsDynamicImport"] = 16777216] = "ContainsDynamicImport"; + TransformFlags[TransformFlags["Super"] = 33554432] = "Super"; + TransformFlags[TransformFlags["ContainsSuper"] = 67108864] = "ContainsSuper"; + // Please leave this as 1 << 29. + // It is the maximum bit we can set before we outgrow the size of a v8 small integer (SMI) on an x86 system. + // It is a good reminder of how much room we have left + TransformFlags[TransformFlags["HasComputedFlags"] = 536870912] = "HasComputedFlags"; + // Assertions + // - Bitmasks that are used to assert facts about the syntax of a node and its subtree. + TransformFlags[TransformFlags["AssertTypeScript"] = 3] = "AssertTypeScript"; + TransformFlags[TransformFlags["AssertJsx"] = 4] = "AssertJsx"; + TransformFlags[TransformFlags["AssertESNext"] = 8] = "AssertESNext"; + TransformFlags[TransformFlags["AssertES2017"] = 16] = "AssertES2017"; + TransformFlags[TransformFlags["AssertES2016"] = 32] = "AssertES2016"; + TransformFlags[TransformFlags["AssertES2015"] = 192] = "AssertES2015"; + TransformFlags[TransformFlags["AssertGenerator"] = 768] = "AssertGenerator"; + TransformFlags[TransformFlags["AssertDestructuringAssignment"] = 3072] = "AssertDestructuringAssignment"; + // Scope Exclusions + // - Bitmasks that exclude flags from propagating out of a specific context + // into the subtree flags of their container. + TransformFlags[TransformFlags["OuterExpressionExcludes"] = 536872257] = "OuterExpressionExcludes"; + TransformFlags[TransformFlags["PropertyAccessExcludes"] = 570426689] = "PropertyAccessExcludes"; + TransformFlags[TransformFlags["NodeExcludes"] = 637535553] = "NodeExcludes"; + TransformFlags[TransformFlags["ArrowFunctionExcludes"] = 653604161] = "ArrowFunctionExcludes"; + TransformFlags[TransformFlags["FunctionExcludes"] = 653620545] = "FunctionExcludes"; + TransformFlags[TransformFlags["ConstructorExcludes"] = 653616449] = "ConstructorExcludes"; + TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = 653616449] = "MethodOrAccessorExcludes"; + TransformFlags[TransformFlags["ClassExcludes"] = 638121281] = "ClassExcludes"; + TransformFlags[TransformFlags["ModuleExcludes"] = 647001409] = "ModuleExcludes"; + TransformFlags[TransformFlags["TypeExcludes"] = -3] = "TypeExcludes"; + TransformFlags[TransformFlags["ObjectLiteralExcludes"] = 638358849] = "ObjectLiteralExcludes"; + TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = 637666625] = "ArrayLiteralOrCallOrNewExcludes"; + TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = 639894849] = "VariableDeclarationListExcludes"; + TransformFlags[TransformFlags["ParameterExcludes"] = 637535553] = "ParameterExcludes"; + TransformFlags[TransformFlags["CatchClauseExcludes"] = 637797697] = "CatchClauseExcludes"; + TransformFlags[TransformFlags["BindingPatternExcludes"] = 637666625] = "BindingPatternExcludes"; + // Masks + // - Additional bitmasks + TransformFlags[TransformFlags["ES2015FunctionSyntaxMask"] = 81920] = "ES2015FunctionSyntaxMask"; + })(TransformFlags = ts.TransformFlags || (ts.TransformFlags = {})); + var EmitFlags; + (function (EmitFlags) { + EmitFlags[EmitFlags["None"] = 0] = "None"; + EmitFlags[EmitFlags["SingleLine"] = 1] = "SingleLine"; + EmitFlags[EmitFlags["AdviseOnEmitNode"] = 2] = "AdviseOnEmitNode"; + EmitFlags[EmitFlags["NoSubstitution"] = 4] = "NoSubstitution"; + EmitFlags[EmitFlags["CapturesThis"] = 8] = "CapturesThis"; + EmitFlags[EmitFlags["NoLeadingSourceMap"] = 16] = "NoLeadingSourceMap"; + EmitFlags[EmitFlags["NoTrailingSourceMap"] = 32] = "NoTrailingSourceMap"; + EmitFlags[EmitFlags["NoSourceMap"] = 48] = "NoSourceMap"; + EmitFlags[EmitFlags["NoNestedSourceMaps"] = 64] = "NoNestedSourceMaps"; + EmitFlags[EmitFlags["NoTokenLeadingSourceMaps"] = 128] = "NoTokenLeadingSourceMaps"; + EmitFlags[EmitFlags["NoTokenTrailingSourceMaps"] = 256] = "NoTokenTrailingSourceMaps"; + EmitFlags[EmitFlags["NoTokenSourceMaps"] = 384] = "NoTokenSourceMaps"; + EmitFlags[EmitFlags["NoLeadingComments"] = 512] = "NoLeadingComments"; + EmitFlags[EmitFlags["NoTrailingComments"] = 1024] = "NoTrailingComments"; + EmitFlags[EmitFlags["NoComments"] = 1536] = "NoComments"; + EmitFlags[EmitFlags["NoNestedComments"] = 2048] = "NoNestedComments"; + EmitFlags[EmitFlags["HelperName"] = 4096] = "HelperName"; + EmitFlags[EmitFlags["ExportName"] = 8192] = "ExportName"; + EmitFlags[EmitFlags["LocalName"] = 16384] = "LocalName"; + EmitFlags[EmitFlags["InternalName"] = 32768] = "InternalName"; + EmitFlags[EmitFlags["Indented"] = 65536] = "Indented"; + EmitFlags[EmitFlags["NoIndentation"] = 131072] = "NoIndentation"; + EmitFlags[EmitFlags["AsyncFunctionBody"] = 262144] = "AsyncFunctionBody"; + EmitFlags[EmitFlags["ReuseTempVariableScope"] = 524288] = "ReuseTempVariableScope"; + EmitFlags[EmitFlags["CustomPrologue"] = 1048576] = "CustomPrologue"; + EmitFlags[EmitFlags["NoHoisting"] = 2097152] = "NoHoisting"; + EmitFlags[EmitFlags["HasEndOfDeclarationMarker"] = 4194304] = "HasEndOfDeclarationMarker"; + EmitFlags[EmitFlags["Iterator"] = 8388608] = "Iterator"; + EmitFlags[EmitFlags["NoAsciiEscaping"] = 16777216] = "NoAsciiEscaping"; + /*@internal*/ EmitFlags[EmitFlags["TypeScriptClassWrapper"] = 33554432] = "TypeScriptClassWrapper"; + /*@internal*/ EmitFlags[EmitFlags["NeverApplyImportHelper"] = 67108864] = "NeverApplyImportHelper"; + })(EmitFlags = ts.EmitFlags || (ts.EmitFlags = {})); + /** + * Used by the checker, this enum keeps track of external emit helpers that should be type + * checked. + */ + /* @internal */ + var ExternalEmitHelpers; + (function (ExternalEmitHelpers) { + ExternalEmitHelpers[ExternalEmitHelpers["Extends"] = 1] = "Extends"; + ExternalEmitHelpers[ExternalEmitHelpers["Assign"] = 2] = "Assign"; + ExternalEmitHelpers[ExternalEmitHelpers["Rest"] = 4] = "Rest"; + ExternalEmitHelpers[ExternalEmitHelpers["Decorate"] = 8] = "Decorate"; + ExternalEmitHelpers[ExternalEmitHelpers["Metadata"] = 16] = "Metadata"; + ExternalEmitHelpers[ExternalEmitHelpers["Param"] = 32] = "Param"; + ExternalEmitHelpers[ExternalEmitHelpers["Awaiter"] = 64] = "Awaiter"; + ExternalEmitHelpers[ExternalEmitHelpers["Generator"] = 128] = "Generator"; + ExternalEmitHelpers[ExternalEmitHelpers["Values"] = 256] = "Values"; + ExternalEmitHelpers[ExternalEmitHelpers["Read"] = 512] = "Read"; + ExternalEmitHelpers[ExternalEmitHelpers["Spread"] = 1024] = "Spread"; + ExternalEmitHelpers[ExternalEmitHelpers["Await"] = 2048] = "Await"; + ExternalEmitHelpers[ExternalEmitHelpers["AsyncGenerator"] = 4096] = "AsyncGenerator"; + ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegator"] = 8192] = "AsyncDelegator"; + ExternalEmitHelpers[ExternalEmitHelpers["AsyncValues"] = 16384] = "AsyncValues"; + ExternalEmitHelpers[ExternalEmitHelpers["ExportStar"] = 32768] = "ExportStar"; + ExternalEmitHelpers[ExternalEmitHelpers["MakeTemplateObject"] = 65536] = "MakeTemplateObject"; + ExternalEmitHelpers[ExternalEmitHelpers["FirstEmitHelper"] = 1] = "FirstEmitHelper"; + ExternalEmitHelpers[ExternalEmitHelpers["LastEmitHelper"] = 65536] = "LastEmitHelper"; + // Helpers included by ES2015 for..of + ExternalEmitHelpers[ExternalEmitHelpers["ForOfIncludes"] = 256] = "ForOfIncludes"; + // Helpers included by ES2017 for..await..of + ExternalEmitHelpers[ExternalEmitHelpers["ForAwaitOfIncludes"] = 16384] = "ForAwaitOfIncludes"; + // Helpers included by ES2017 async generators + ExternalEmitHelpers[ExternalEmitHelpers["AsyncGeneratorIncludes"] = 6144] = "AsyncGeneratorIncludes"; + // Helpers included by yield* in ES2017 async generators + ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegatorIncludes"] = 26624] = "AsyncDelegatorIncludes"; + // Helpers included by ES2015 spread + ExternalEmitHelpers[ExternalEmitHelpers["SpreadIncludes"] = 1536] = "SpreadIncludes"; + })(ExternalEmitHelpers = ts.ExternalEmitHelpers || (ts.ExternalEmitHelpers = {})); + var EmitHint; + (function (EmitHint) { + EmitHint[EmitHint["SourceFile"] = 0] = "SourceFile"; + EmitHint[EmitHint["Expression"] = 1] = "Expression"; + EmitHint[EmitHint["IdentifierName"] = 2] = "IdentifierName"; + EmitHint[EmitHint["MappedTypeParameter"] = 3] = "MappedTypeParameter"; + EmitHint[EmitHint["Unspecified"] = 4] = "Unspecified"; + EmitHint[EmitHint["EmbeddedStatement"] = 5] = "EmbeddedStatement"; + })(EmitHint = ts.EmitHint || (ts.EmitHint = {})); + var ListFormat; + (function (ListFormat) { + ListFormat[ListFormat["None"] = 0] = "None"; + // Line separators + ListFormat[ListFormat["SingleLine"] = 0] = "SingleLine"; + ListFormat[ListFormat["MultiLine"] = 1] = "MultiLine"; + ListFormat[ListFormat["PreserveLines"] = 2] = "PreserveLines"; + ListFormat[ListFormat["LinesMask"] = 3] = "LinesMask"; + // Delimiters + ListFormat[ListFormat["NotDelimited"] = 0] = "NotDelimited"; + ListFormat[ListFormat["BarDelimited"] = 4] = "BarDelimited"; + ListFormat[ListFormat["AmpersandDelimited"] = 8] = "AmpersandDelimited"; + ListFormat[ListFormat["CommaDelimited"] = 16] = "CommaDelimited"; + ListFormat[ListFormat["AsteriskDelimited"] = 32] = "AsteriskDelimited"; + ListFormat[ListFormat["DelimitersMask"] = 60] = "DelimitersMask"; + ListFormat[ListFormat["AllowTrailingComma"] = 64] = "AllowTrailingComma"; + // Whitespace + ListFormat[ListFormat["Indented"] = 128] = "Indented"; + ListFormat[ListFormat["SpaceBetweenBraces"] = 256] = "SpaceBetweenBraces"; + ListFormat[ListFormat["SpaceBetweenSiblings"] = 512] = "SpaceBetweenSiblings"; + // Brackets/Braces + ListFormat[ListFormat["Braces"] = 1024] = "Braces"; + ListFormat[ListFormat["Parenthesis"] = 2048] = "Parenthesis"; + ListFormat[ListFormat["AngleBrackets"] = 4096] = "AngleBrackets"; + ListFormat[ListFormat["SquareBrackets"] = 8192] = "SquareBrackets"; + ListFormat[ListFormat["BracketsMask"] = 15360] = "BracketsMask"; + ListFormat[ListFormat["OptionalIfUndefined"] = 16384] = "OptionalIfUndefined"; + ListFormat[ListFormat["OptionalIfEmpty"] = 32768] = "OptionalIfEmpty"; + ListFormat[ListFormat["Optional"] = 49152] = "Optional"; + // Other + ListFormat[ListFormat["PreferNewLine"] = 65536] = "PreferNewLine"; + ListFormat[ListFormat["NoTrailingNewLine"] = 131072] = "NoTrailingNewLine"; + ListFormat[ListFormat["NoInterveningComments"] = 262144] = "NoInterveningComments"; + ListFormat[ListFormat["NoSpaceIfEmpty"] = 524288] = "NoSpaceIfEmpty"; + ListFormat[ListFormat["SingleElement"] = 1048576] = "SingleElement"; + // Precomputed Formats + ListFormat[ListFormat["Modifiers"] = 262656] = "Modifiers"; + ListFormat[ListFormat["HeritageClauses"] = 512] = "HeritageClauses"; + ListFormat[ListFormat["SingleLineTypeLiteralMembers"] = 768] = "SingleLineTypeLiteralMembers"; + ListFormat[ListFormat["MultiLineTypeLiteralMembers"] = 32897] = "MultiLineTypeLiteralMembers"; + ListFormat[ListFormat["TupleTypeElements"] = 528] = "TupleTypeElements"; + ListFormat[ListFormat["UnionTypeConstituents"] = 516] = "UnionTypeConstituents"; + ListFormat[ListFormat["IntersectionTypeConstituents"] = 520] = "IntersectionTypeConstituents"; + ListFormat[ListFormat["ObjectBindingPatternElements"] = 525136] = "ObjectBindingPatternElements"; + ListFormat[ListFormat["ArrayBindingPatternElements"] = 524880] = "ArrayBindingPatternElements"; + ListFormat[ListFormat["ObjectLiteralExpressionProperties"] = 526226] = "ObjectLiteralExpressionProperties"; + ListFormat[ListFormat["ArrayLiteralExpressionElements"] = 8914] = "ArrayLiteralExpressionElements"; + ListFormat[ListFormat["CommaListElements"] = 528] = "CommaListElements"; + ListFormat[ListFormat["CallExpressionArguments"] = 2576] = "CallExpressionArguments"; + ListFormat[ListFormat["NewExpressionArguments"] = 18960] = "NewExpressionArguments"; + ListFormat[ListFormat["TemplateExpressionSpans"] = 262144] = "TemplateExpressionSpans"; + ListFormat[ListFormat["SingleLineBlockStatements"] = 768] = "SingleLineBlockStatements"; + ListFormat[ListFormat["MultiLineBlockStatements"] = 129] = "MultiLineBlockStatements"; + ListFormat[ListFormat["VariableDeclarationList"] = 528] = "VariableDeclarationList"; + ListFormat[ListFormat["SingleLineFunctionBodyStatements"] = 768] = "SingleLineFunctionBodyStatements"; + ListFormat[ListFormat["MultiLineFunctionBodyStatements"] = 1] = "MultiLineFunctionBodyStatements"; + ListFormat[ListFormat["ClassHeritageClauses"] = 0] = "ClassHeritageClauses"; + ListFormat[ListFormat["ClassMembers"] = 129] = "ClassMembers"; + ListFormat[ListFormat["InterfaceMembers"] = 129] = "InterfaceMembers"; + ListFormat[ListFormat["EnumMembers"] = 145] = "EnumMembers"; + ListFormat[ListFormat["CaseBlockClauses"] = 129] = "CaseBlockClauses"; + ListFormat[ListFormat["NamedImportsOrExportsElements"] = 525136] = "NamedImportsOrExportsElements"; + ListFormat[ListFormat["JsxElementOrFragmentChildren"] = 262144] = "JsxElementOrFragmentChildren"; + ListFormat[ListFormat["JsxElementAttributes"] = 262656] = "JsxElementAttributes"; + ListFormat[ListFormat["CaseOrDefaultClauseStatements"] = 163969] = "CaseOrDefaultClauseStatements"; + ListFormat[ListFormat["HeritageClauseTypes"] = 528] = "HeritageClauseTypes"; + ListFormat[ListFormat["SourceFileStatements"] = 131073] = "SourceFileStatements"; + ListFormat[ListFormat["Decorators"] = 49153] = "Decorators"; + ListFormat[ListFormat["TypeArguments"] = 53776] = "TypeArguments"; + ListFormat[ListFormat["TypeParameters"] = 53776] = "TypeParameters"; + ListFormat[ListFormat["Parameters"] = 2576] = "Parameters"; + ListFormat[ListFormat["IndexSignatureParameters"] = 8848] = "IndexSignatureParameters"; + ListFormat[ListFormat["JSDocComment"] = 33] = "JSDocComment"; + })(ListFormat = ts.ListFormat || (ts.ListFormat = {})); + /* @internal */ + var PragmaKindFlags; + (function (PragmaKindFlags) { + PragmaKindFlags[PragmaKindFlags["None"] = 0] = "None"; + /** + * Triple slash comment of the form + * /// + */ + PragmaKindFlags[PragmaKindFlags["TripleSlashXML"] = 1] = "TripleSlashXML"; + /** + * Single line comment of the form + * // @pragma-name argval1 argval2 + * or + * /// @pragma-name argval1 argval2 + */ + PragmaKindFlags[PragmaKindFlags["SingleLine"] = 2] = "SingleLine"; + /** + * Multiline non-jsdoc pragma of the form + * /* @pragma-name argval1 argval2 * / + */ + PragmaKindFlags[PragmaKindFlags["MultiLine"] = 4] = "MultiLine"; + PragmaKindFlags[PragmaKindFlags["All"] = 7] = "All"; + PragmaKindFlags[PragmaKindFlags["Default"] = 7] = "Default"; + })(PragmaKindFlags = ts.PragmaKindFlags || (ts.PragmaKindFlags = {})); + /** + * This function only exists to cause exact types to be inferred for all the literals within `commentPragmas` + */ + /* @internal */ + function _contextuallyTypePragmas(args) { + return args; + } + // While not strictly a type, this is here because `PragmaMap` needs to be here to be used with `SourceFile`, and we don't + // fancy effectively defining it twice, once in value-space and once in type-space + /* @internal */ + ts.commentPragmas = _contextuallyTypePragmas({ + "reference": { + args: [ + { name: "types", optional: true, captureSpan: true }, + { name: "lib", optional: true, captureSpan: true }, + { name: "path", optional: true, captureSpan: true }, + { name: "no-default-lib", optional: true } + ], + kind: 1 /* TripleSlashXML */ + }, + "amd-dependency": { + args: [{ name: "path" }, { name: "name", optional: true }], + kind: 1 /* TripleSlashXML */ + }, + "amd-module": { + args: [{ name: "name" }], + kind: 1 /* TripleSlashXML */ + }, + "ts-check": { + kind: 2 /* SingleLine */ + }, + "ts-nocheck": { + kind: 2 /* SingleLine */ + }, + "jsx": { + args: [{ name: "factory" }], + kind: 4 /* MultiLine */ + }, + }); +})(ts || (ts = {})); +var ts; +(function (ts) { + /** + * Set a high stack trace limit to provide more information in case of an error. + * Called for command-line and server use cases. + * Not called if TypeScript is used as a library. + */ + /* @internal */ + function setStackTraceLimit() { + if (Error.stackTraceLimit < 100) { // Also tests that we won't set the property if it doesn't exist. + Error.stackTraceLimit = 100; + } + } + ts.setStackTraceLimit = setStackTraceLimit; + var FileWatcherEventKind; + (function (FileWatcherEventKind) { + FileWatcherEventKind[FileWatcherEventKind["Created"] = 0] = "Created"; + FileWatcherEventKind[FileWatcherEventKind["Changed"] = 1] = "Changed"; + FileWatcherEventKind[FileWatcherEventKind["Deleted"] = 2] = "Deleted"; + })(FileWatcherEventKind = ts.FileWatcherEventKind || (ts.FileWatcherEventKind = {})); + /* @internal */ + var PollingInterval; + (function (PollingInterval) { + PollingInterval[PollingInterval["High"] = 2000] = "High"; + PollingInterval[PollingInterval["Medium"] = 500] = "Medium"; + PollingInterval[PollingInterval["Low"] = 250] = "Low"; + })(PollingInterval = ts.PollingInterval || (ts.PollingInterval = {})); + /* @internal */ + ts.missingFileModifiedTime = new Date(0); // Any subsequent modification will occur after this time + function createPollingIntervalBasedLevels(levels) { + var _a; + return _a = {}, + _a[PollingInterval.Low] = levels.Low, + _a[PollingInterval.Medium] = levels.Medium, + _a[PollingInterval.High] = levels.High, + _a; + } + var defaultChunkLevels = { Low: 32, Medium: 64, High: 256 }; + var pollingChunkSize = createPollingIntervalBasedLevels(defaultChunkLevels); + /* @internal */ + ts.unchangedPollThresholds = createPollingIntervalBasedLevels(defaultChunkLevels); + /* @internal */ + function setCustomPollingValues(system) { + if (!system.getEnvironmentVariable) { + return; + } + var pollingIntervalChanged = setCustomLevels("TSC_WATCH_POLLINGINTERVAL", PollingInterval); + pollingChunkSize = getCustomPollingBasedLevels("TSC_WATCH_POLLINGCHUNKSIZE", defaultChunkLevels) || pollingChunkSize; + ts.unchangedPollThresholds = getCustomPollingBasedLevels("TSC_WATCH_UNCHANGEDPOLLTHRESHOLDS", defaultChunkLevels) || ts.unchangedPollThresholds; + function getLevel(envVar, level) { + return system.getEnvironmentVariable(envVar + "_" + level.toUpperCase()); + } + function getCustomLevels(baseVariable) { + var customLevels; + setCustomLevel("Low"); + setCustomLevel("Medium"); + setCustomLevel("High"); + return customLevels; + function setCustomLevel(level) { + var customLevel = getLevel(baseVariable, level); + if (customLevel) { + (customLevels || (customLevels = {}))[level] = Number(customLevel); + } + } + } + function setCustomLevels(baseVariable, levels) { + var customLevels = getCustomLevels(baseVariable); + if (customLevels) { + setLevel("Low"); + setLevel("Medium"); + setLevel("High"); + return true; + } + return false; + function setLevel(level) { + levels[level] = customLevels[level] || levels[level]; + } + } + function getCustomPollingBasedLevels(baseVariable, defaultLevels) { + var customLevels = getCustomLevels(baseVariable); + return (pollingIntervalChanged || customLevels) && + createPollingIntervalBasedLevels(customLevels ? __assign({}, defaultLevels, customLevels) : defaultLevels); + } + } + ts.setCustomPollingValues = setCustomPollingValues; + /* @internal */ + function createDynamicPriorityPollingWatchFile(host) { + var watchedFiles = []; + var changedFilesInLastPoll = []; + var lowPollingIntervalQueue = createPollingIntervalQueue(PollingInterval.Low); + var mediumPollingIntervalQueue = createPollingIntervalQueue(PollingInterval.Medium); + var highPollingIntervalQueue = createPollingIntervalQueue(PollingInterval.High); + return watchFile; + function watchFile(fileName, callback, defaultPollingInterval) { + var file = { + fileName: fileName, + callback: callback, + unchangedPolls: 0, + mtime: getModifiedTime(fileName) + }; + watchedFiles.push(file); + addToPollingIntervalQueue(file, defaultPollingInterval); + return { + close: function () { + file.isClosed = true; + // Remove from watchedFiles + ts.unorderedRemoveItem(watchedFiles, file); + // Do not update polling interval queue since that will happen as part of polling + } + }; + } + function createPollingIntervalQueue(pollingInterval) { + var queue = []; + queue.pollingInterval = pollingInterval; + queue.pollIndex = 0; + queue.pollScheduled = false; + return queue; + } + function pollPollingIntervalQueue(queue) { + queue.pollIndex = pollQueue(queue, queue.pollingInterval, queue.pollIndex, pollingChunkSize[queue.pollingInterval]); + // Set the next polling index and timeout + if (queue.length) { + scheduleNextPoll(queue.pollingInterval); + } + else { + ts.Debug.assert(queue.pollIndex === 0); + queue.pollScheduled = false; + } + } + function pollLowPollingIntervalQueue(queue) { + // Always poll complete list of changedFilesInLastPoll + pollQueue(changedFilesInLastPoll, PollingInterval.Low, /*pollIndex*/ 0, changedFilesInLastPoll.length); + // Finally do the actual polling of the queue + pollPollingIntervalQueue(queue); + // Schedule poll if there are files in changedFilesInLastPoll but no files in the actual queue + // as pollPollingIntervalQueue wont schedule for next poll + if (!queue.pollScheduled && changedFilesInLastPoll.length) { + scheduleNextPoll(PollingInterval.Low); + } + } + function pollQueue(queue, pollingInterval, pollIndex, chunkSize) { + // Max visit would be all elements of the queue + var needsVisit = queue.length; + var definedValueCopyToIndex = pollIndex; + for (var polled = 0; polled < chunkSize && needsVisit > 0; nextPollIndex(), needsVisit--) { + var watchedFile = queue[pollIndex]; + if (!watchedFile) { + continue; + } + else if (watchedFile.isClosed) { + queue[pollIndex] = undefined; + continue; + } + polled++; + var fileChanged = onWatchedFileStat(watchedFile, getModifiedTime(watchedFile.fileName)); + if (watchedFile.isClosed) { + // Closed watcher as part of callback + queue[pollIndex] = undefined; + } + else if (fileChanged) { + watchedFile.unchangedPolls = 0; + // Changed files go to changedFilesInLastPoll queue + if (queue !== changedFilesInLastPoll) { + queue[pollIndex] = undefined; + addChangedFileToLowPollingIntervalQueue(watchedFile); + } + } + else if (watchedFile.unchangedPolls !== ts.unchangedPollThresholds[pollingInterval]) { + watchedFile.unchangedPolls++; + } + else if (queue === changedFilesInLastPoll) { + // Restart unchangedPollCount for unchanged file and move to low polling interval queue + watchedFile.unchangedPolls = 1; + queue[pollIndex] = undefined; + addToPollingIntervalQueue(watchedFile, PollingInterval.Low); + } + else if (pollingInterval !== PollingInterval.High) { + watchedFile.unchangedPolls++; + queue[pollIndex] = undefined; + addToPollingIntervalQueue(watchedFile, pollingInterval === PollingInterval.Low ? PollingInterval.Medium : PollingInterval.High); + } + if (queue[pollIndex]) { + // Copy this file to the non hole location + if (definedValueCopyToIndex < pollIndex) { + queue[definedValueCopyToIndex] = watchedFile; + queue[pollIndex] = undefined; + } + definedValueCopyToIndex++; + } + } + // Return next poll index + return pollIndex; + function nextPollIndex() { + pollIndex++; + if (pollIndex === queue.length) { + if (definedValueCopyToIndex < pollIndex) { + // There are holes from nextDefinedValueIndex to end of queue, change queue size + queue.length = definedValueCopyToIndex; + } + pollIndex = 0; + definedValueCopyToIndex = 0; + } + } + } + function pollingIntervalQueue(pollingInterval) { + switch (pollingInterval) { + case PollingInterval.Low: + return lowPollingIntervalQueue; + case PollingInterval.Medium: + return mediumPollingIntervalQueue; + case PollingInterval.High: + return highPollingIntervalQueue; + } + } + function addToPollingIntervalQueue(file, pollingInterval) { + pollingIntervalQueue(pollingInterval).push(file); + scheduleNextPollIfNotAlreadyScheduled(pollingInterval); + } + function addChangedFileToLowPollingIntervalQueue(file) { + changedFilesInLastPoll.push(file); + scheduleNextPollIfNotAlreadyScheduled(PollingInterval.Low); + } + function scheduleNextPollIfNotAlreadyScheduled(pollingInterval) { + if (!pollingIntervalQueue(pollingInterval).pollScheduled) { + scheduleNextPoll(pollingInterval); + } + } + function scheduleNextPoll(pollingInterval) { + pollingIntervalQueue(pollingInterval).pollScheduled = host.setTimeout(pollingInterval === PollingInterval.Low ? pollLowPollingIntervalQueue : pollPollingIntervalQueue, pollingInterval, pollingIntervalQueue(pollingInterval)); + } + function getModifiedTime(fileName) { + return host.getModifiedTime(fileName) || ts.missingFileModifiedTime; + } + } + ts.createDynamicPriorityPollingWatchFile = createDynamicPriorityPollingWatchFile; + /** + * Returns true if file status changed + */ + /*@internal*/ + function onWatchedFileStat(watchedFile, modifiedTime) { + var oldTime = watchedFile.mtime.getTime(); + var newTime = modifiedTime.getTime(); + if (oldTime !== newTime) { + watchedFile.mtime = modifiedTime; + watchedFile.callback(watchedFile.fileName, getFileWatcherEventKind(oldTime, newTime)); + return true; + } + return false; + } + ts.onWatchedFileStat = onWatchedFileStat; + /*@internal*/ + function getFileWatcherEventKind(oldTime, newTime) { + return oldTime === 0 + ? FileWatcherEventKind.Created + : newTime === 0 + ? FileWatcherEventKind.Deleted + : FileWatcherEventKind.Changed; + } + ts.getFileWatcherEventKind = getFileWatcherEventKind; + /** + * Watch the directory recursively using host provided method to watch child directories + * that means if this is recursive watcher, watch the children directories as well + * (eg on OS that dont support recursive watch using fs.watch use fs.watchFile) + */ + /*@internal*/ + function createRecursiveDirectoryWatcher(host) { + var cache = ts.createMap(); + var callbackCache = ts.createMultiMap(); + var filePathComparer = ts.getStringComparer(!host.useCaseSensitiveFileNames); + var toCanonicalFilePath = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); + return createDirectoryWatcher; + /** + * Create the directory watcher for the dirPath. + */ + function createDirectoryWatcher(dirName, callback) { + var dirPath = toCanonicalFilePath(dirName); + var directoryWatcher = cache.get(dirPath); + if (directoryWatcher) { + directoryWatcher.refCount++; + } + else { + directoryWatcher = { + watcher: host.watchDirectory(dirName, function (fileName) { + // Call the actual callback + callbackCache.forEach(function (callbacks, rootDirName) { + if (rootDirName === dirPath || (ts.startsWith(dirPath, rootDirName) && dirPath[rootDirName.length] === ts.directorySeparator)) { + callbacks.forEach(function (callback) { return callback(fileName); }); + } + }); + // Iterate through existing children and update the watches if needed + updateChildWatches(dirName, dirPath); + }), + refCount: 1, + childWatches: ts.emptyArray + }; + cache.set(dirPath, directoryWatcher); + updateChildWatches(dirName, dirPath); + } + if (callback) { + callbackCache.add(dirPath, callback); + } + return { + dirName: dirName, + close: function () { + var directoryWatcher = ts.Debug.assertDefined(cache.get(dirPath)); + if (callback) + callbackCache.remove(dirPath, callback); + directoryWatcher.refCount--; + if (directoryWatcher.refCount) + return; + cache.delete(dirPath); + ts.closeFileWatcherOf(directoryWatcher); + directoryWatcher.childWatches.forEach(ts.closeFileWatcher); + } + }; + } + function updateChildWatches(dirName, dirPath) { + // Iterate through existing children and update the watches if needed + var parentWatcher = cache.get(dirPath); + if (parentWatcher) { + parentWatcher.childWatches = watchChildDirectories(dirName, parentWatcher.childWatches); + } + } + /** + * Watch the directories in the parentDir + */ + function watchChildDirectories(parentDir, existingChildWatches) { + var newChildWatches; + ts.enumerateInsertsAndDeletes(host.directoryExists(parentDir) ? ts.mapDefined(host.getAccessibleSortedChildDirectories(parentDir), function (child) { + var childFullName = ts.getNormalizedAbsolutePath(child, parentDir); + // Filter our the symbolic link directories since those arent included in recursive watch + // which is same behaviour when recursive: true is passed to fs.watch + return filePathComparer(childFullName, ts.normalizePath(host.realpath(childFullName))) === 0 /* EqualTo */ ? childFullName : undefined; + }) : ts.emptyArray, existingChildWatches, function (child, childWatcher) { return filePathComparer(child, childWatcher.dirName); }, createAndAddChildDirectoryWatcher, ts.closeFileWatcher, addChildDirectoryWatcher); + return newChildWatches || ts.emptyArray; + /** + * Create new childDirectoryWatcher and add it to the new ChildDirectoryWatcher list + */ + function createAndAddChildDirectoryWatcher(childName) { + var result = createDirectoryWatcher(childName); + addChildDirectoryWatcher(result); + } + /** + * Add child directory watcher to the new ChildDirectoryWatcher list + */ + function addChildDirectoryWatcher(childWatcher) { + (newChildWatches || (newChildWatches = [])).push(childWatcher); + } + } + } + ts.createRecursiveDirectoryWatcher = createRecursiveDirectoryWatcher; + function getNodeMajorVersion() { + if (typeof process === "undefined") { + return undefined; + } + var version = process.version; + if (!version) { + return undefined; + } + var dot = version.indexOf("."); + if (dot === -1) { + return undefined; + } + return parseInt(version.substring(1, dot)); + } + ts.getNodeMajorVersion = getNodeMajorVersion; + // TODO: GH#18217 this is used as if it's certainly defined in many places. + ts.sys = (function () { + // NodeJS detects "\uFEFF" at the start of the string and *replaces* it with the actual + // byte order mark from the specified encoding. Using any other byte order mark does + // not actually work. + var byteOrderMarkIndicator = "\uFEFF"; + function getNodeSystem() { + var _fs = require("fs"); + var _path = require("path"); + var _os = require("os"); + // crypto can be absent on reduced node installations + var _crypto; + try { + _crypto = require("crypto"); + } + catch (_a) { + _crypto = undefined; + } + var Buffer = require("buffer").Buffer; + var nodeVersion = getNodeMajorVersion(); + var isNode4OrLater = nodeVersion >= 4; + var platform = _os.platform(); + var useCaseSensitiveFileNames = isFileSystemCaseSensitive(); + var FileSystemEntryKind; + (function (FileSystemEntryKind) { + FileSystemEntryKind[FileSystemEntryKind["File"] = 0] = "File"; + FileSystemEntryKind[FileSystemEntryKind["Directory"] = 1] = "Directory"; + })(FileSystemEntryKind || (FileSystemEntryKind = {})); + var useNonPollingWatchers = process.env.TSC_NONPOLLING_WATCHER; + var tscWatchFile = process.env.TSC_WATCHFILE; + var tscWatchDirectory = process.env.TSC_WATCHDIRECTORY; + var dynamicPollingWatchFile; + var nodeSystem = { + args: process.argv.slice(2), + newLine: _os.EOL, + useCaseSensitiveFileNames: useCaseSensitiveFileNames, + write: function (s) { + process.stdout.write(s); + }, + writeOutputIsTTY: function () { + return process.stdout.isTTY; + }, + readFile: readFile, + writeFile: writeFile, + watchFile: getWatchFile(), + watchDirectory: getWatchDirectory(), + resolvePath: function (path) { return _path.resolve(path); }, + fileExists: fileExists, + directoryExists: directoryExists, + createDirectory: function (directoryName) { + if (!nodeSystem.directoryExists(directoryName)) { + _fs.mkdirSync(directoryName); + } + }, + getExecutingFilePath: function () { + return __filename; + }, + getCurrentDirectory: function () { + return process.cwd(); + }, + getDirectories: getDirectories, + getEnvironmentVariable: function (name) { + return process.env[name] || ""; + }, + readDirectory: readDirectory, + getModifiedTime: getModifiedTime, + setModifiedTime: setModifiedTime, + deleteFile: deleteFile, + createHash: _crypto ? createMD5HashUsingNativeCrypto : generateDjb2Hash, + createSHA256Hash: _crypto ? createSHA256Hash : undefined, + getMemoryUsage: function () { + if (global.gc) { + global.gc(); + } + return process.memoryUsage().heapUsed; + }, + getFileSize: function (path) { + try { + var stat = _fs.statSync(path); + if (stat.isFile()) { + return stat.size; + } + } + catch ( /*ignore*/_a) { /*ignore*/ } + return 0; + }, + exit: function (exitCode) { + process.exit(exitCode); + }, + realpath: realpath, + debugMode: ts.some(process.execArgv, function (arg) { return /^--(inspect|debug)(-brk)?(=\d+)?$/i.test(arg); }), + tryEnableSourceMapsForHost: function () { + try { + require("source-map-support").install(); + } + catch (_a) { + // Could not enable source maps. + } + }, + setTimeout: setTimeout, + clearTimeout: clearTimeout, + clearScreen: function () { + process.stdout.write("\x1Bc"); + }, + setBlocking: function () { + if (process.stdout && process.stdout._handle && process.stdout._handle.setBlocking) { + process.stdout._handle.setBlocking(true); + } + }, + bufferFrom: bufferFrom, + base64decode: function (input) { return bufferFrom(input, "base64").toString("utf8"); }, + base64encode: function (input) { return bufferFrom(input).toString("base64"); }, + }; + return nodeSystem; + function bufferFrom(input, encoding) { + // See https://github.com/Microsoft/TypeScript/issues/25652 + return Buffer.from && Buffer.from !== Int8Array.from + ? Buffer.from(input, encoding) + : new Buffer(input, encoding); + } + function isFileSystemCaseSensitive() { + // win32\win64 are case insensitive platforms + if (platform === "win32" || platform === "win64") { + return false; + } + // If this file exists under a different case, we must be case-insensitve. + return !fileExists(swapCase(__filename)); + } + /** Convert all lowercase chars to uppercase, and vice-versa */ + function swapCase(s) { + return s.replace(/\w/g, function (ch) { + var up = ch.toUpperCase(); + return ch === up ? ch.toLowerCase() : up; + }); + } + function getWatchFile() { + switch (tscWatchFile) { + case "PriorityPollingInterval": + // Use polling interval based on priority when create watch using host.watchFile + return fsWatchFile; + case "DynamicPriorityPolling": + // Use polling interval but change the interval depending on file changes and their default polling interval + return createDynamicPriorityPollingWatchFile({ getModifiedTime: getModifiedTime, setTimeout: setTimeout }); + case "UseFsEvents": + // Use notifications from FS to watch with falling back to fs.watchFile + return watchFileUsingFsWatch; + case "UseFsEventsWithFallbackDynamicPolling": + // Use notifications from FS to watch with falling back to dynamic watch file + dynamicPollingWatchFile = createDynamicPriorityPollingWatchFile({ getModifiedTime: getModifiedTime, setTimeout: setTimeout }); + return createWatchFileUsingDynamicWatchFile(dynamicPollingWatchFile); + case "UseFsEventsOnParentDirectory": + // Use notifications from FS to watch with falling back to fs.watchFile + return createNonPollingWatchFile(); + } + return useNonPollingWatchers ? + createNonPollingWatchFile() : + // Default to do not use polling interval as it is before this experiment branch + function (fileName, callback) { return fsWatchFile(fileName, callback); }; + } + function getWatchDirectory() { + // Node 4.0 `fs.watch` function supports the "recursive" option on both OSX and Windows + // (ref: https://github.com/nodejs/node/pull/2649 and https://github.com/Microsoft/TypeScript/issues/4643) + var fsSupportsRecursive = isNode4OrLater && (process.platform === "win32" || process.platform === "darwin"); + if (fsSupportsRecursive) { + return watchDirectoryUsingFsWatch; + } + var watchDirectory = tscWatchDirectory === "RecursiveDirectoryUsingFsWatchFile" ? + createWatchDirectoryUsing(fsWatchFile) : + tscWatchDirectory === "RecursiveDirectoryUsingDynamicPriorityPolling" ? + createWatchDirectoryUsing(dynamicPollingWatchFile || createDynamicPriorityPollingWatchFile({ getModifiedTime: getModifiedTime, setTimeout: setTimeout })) : + watchDirectoryUsingFsWatch; + var watchDirectoryRecursively = createRecursiveDirectoryWatcher({ + useCaseSensitiveFileNames: useCaseSensitiveFileNames, + directoryExists: directoryExists, + getAccessibleSortedChildDirectories: function (path) { return getAccessibleFileSystemEntries(path).directories; }, + watchDirectory: watchDirectory, + realpath: realpath + }); + return function (directoryName, callback, recursive) { + if (recursive) { + return watchDirectoryRecursively(directoryName, callback); + } + return watchDirectory(directoryName, callback); + }; + } + function createNonPollingWatchFile() { + // One file can have multiple watchers + var fileWatcherCallbacks = ts.createMultiMap(); + var dirWatchers = ts.createMap(); + var toCanonicalName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); + return nonPollingWatchFile; + function nonPollingWatchFile(fileName, callback) { + var filePath = toCanonicalName(fileName); + fileWatcherCallbacks.add(filePath, callback); + var dirPath = ts.getDirectoryPath(filePath) || "."; + var watcher = dirWatchers.get(dirPath) || createDirectoryWatcher(ts.getDirectoryPath(fileName) || ".", dirPath); + watcher.referenceCount++; + return { + close: function () { + if (watcher.referenceCount === 1) { + watcher.close(); + dirWatchers.delete(dirPath); + } + else { + watcher.referenceCount--; + } + fileWatcherCallbacks.remove(filePath, callback); + } + }; + } + function createDirectoryWatcher(dirName, dirPath) { + var watcher = fsWatchDirectory(dirName, function (_eventName, relativeFileName) { + // When files are deleted from disk, the triggered "rename" event would have a relativefileName of "undefined" + if (!ts.isString(relativeFileName)) { + return; + } + var fileName = ts.getNormalizedAbsolutePath(relativeFileName, dirName); + // Some applications save a working file via rename operations + var callbacks = fileName && fileWatcherCallbacks.get(toCanonicalName(fileName)); + if (callbacks) { + for (var _i = 0, callbacks_1 = callbacks; _i < callbacks_1.length; _i++) { + var fileCallback = callbacks_1[_i]; + fileCallback(fileName, FileWatcherEventKind.Changed); + } + } + }); + watcher.referenceCount = 0; + dirWatchers.set(dirPath, watcher); + return watcher; + } + } + function fsWatchFile(fileName, callback, pollingInterval) { + _fs.watchFile(fileName, { persistent: true, interval: pollingInterval || 250 }, fileChanged); + var eventKind; + return { + close: function () { return _fs.unwatchFile(fileName, fileChanged); } + }; + function fileChanged(curr, prev) { + // previous event kind check is to ensure we recongnize the file as previously also missing when it is restored or renamed twice (that is it disappears and reappears) + // In such case, prevTime returned is same as prev time of event when file was deleted as per node documentation + var isPreviouslyDeleted = +prev.mtime === 0 || eventKind === FileWatcherEventKind.Deleted; + if (+curr.mtime === 0) { + if (isPreviouslyDeleted) { + // Already deleted file, no need to callback again + return; + } + eventKind = FileWatcherEventKind.Deleted; + } + else if (isPreviouslyDeleted) { + eventKind = FileWatcherEventKind.Created; + } + // If there is no change in modified time, ignore the event + else if (+curr.mtime === +prev.mtime) { + return; + } + else { + // File changed + eventKind = FileWatcherEventKind.Changed; + } + callback(fileName, eventKind); + } + } + function createFileWatcherCallback(callback) { + return function (_fileName, eventKind) { return callback(eventKind === FileWatcherEventKind.Changed ? "change" : "rename", ""); }; + } + function createFsWatchCallbackForFileWatcherCallback(fileName, callback) { + return function (eventName) { + if (eventName === "rename") { + callback(fileName, fileExists(fileName) ? FileWatcherEventKind.Created : FileWatcherEventKind.Deleted); + } + else { + // Change + callback(fileName, FileWatcherEventKind.Changed); + } + }; + } + function createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback) { + return function (eventName, relativeFileName) { + // In watchDirectory we only care about adding and removing files (when event name is + // "rename"); changes made within files are handled by corresponding fileWatchers (when + // event name is "change") + if (eventName === "rename") { + // When deleting a file, the passed baseFileName is null + callback(!relativeFileName ? directoryName : ts.normalizePath(ts.combinePaths(directoryName, relativeFileName))); + } + }; + } + function fsWatch(fileOrDirectory, entryKind, callback, recursive, fallbackPollingWatchFile, pollingInterval) { + var options; + /** Watcher for the file system entry depending on whether it is missing or present */ + var watcher = !fileSystemEntryExists(fileOrDirectory, entryKind) ? + watchMissingFileSystemEntry() : + watchPresentFileSystemEntry(); + return { + close: function () { + // Close the watcher (either existing file system entry watcher or missing file system entry watcher) + watcher.close(); + watcher = undefined; + } + }; + /** + * Invoke the callback with rename and update the watcher if not closed + * @param createWatcher + */ + function invokeCallbackAndUpdateWatcher(createWatcher) { + // Call the callback for current directory + callback("rename", ""); + // If watcher is not closed, update it + if (watcher) { + watcher.close(); + watcher = createWatcher(); + } + } + /** + * Watch the file or directory that is currently present + * and when the watched file or directory is deleted, switch to missing file system entry watcher + */ + function watchPresentFileSystemEntry() { + // Node 4.0 `fs.watch` function supports the "recursive" option on both OSX and Windows + // (ref: https://github.com/nodejs/node/pull/2649 and https://github.com/Microsoft/TypeScript/issues/4643) + if (options === undefined) { + if (isNode4OrLater && (process.platform === "win32" || process.platform === "darwin")) { + options = { persistent: true, recursive: !!recursive }; + } + else { + options = { persistent: true }; + } + } + try { + var presentWatcher = _fs.watch(fileOrDirectory, options, callback); + // Watch the missing file or directory or error + presentWatcher.on("error", function () { return invokeCallbackAndUpdateWatcher(watchMissingFileSystemEntry); }); + return presentWatcher; + } + catch (e) { + // Catch the exception and use polling instead + // Eg. on linux the number of watches are limited and one could easily exhaust watches and the exception ENOSPC is thrown when creating watcher at that point + // so instead of throwing error, use fs.watchFile + return watchPresentFileSystemEntryWithFsWatchFile(); + } + } + /** + * Watch the file or directory using fs.watchFile since fs.watch threw exception + * Eg. on linux the number of watches are limited and one could easily exhaust watches and the exception ENOSPC is thrown when creating watcher at that point + */ + function watchPresentFileSystemEntryWithFsWatchFile() { + return fallbackPollingWatchFile(fileOrDirectory, createFileWatcherCallback(callback), pollingInterval); + } + /** + * Watch the file or directory that is missing + * and switch to existing file or directory when the missing filesystem entry is created + */ + function watchMissingFileSystemEntry() { + return fallbackPollingWatchFile(fileOrDirectory, function (_fileName, eventKind) { + if (eventKind === FileWatcherEventKind.Created && fileSystemEntryExists(fileOrDirectory, entryKind)) { + // Call the callback for current file or directory + // For now it could be callback for the inner directory creation, + // but just return current directory, better than current no-op + invokeCallbackAndUpdateWatcher(watchPresentFileSystemEntry); + } + }, pollingInterval); + } + } + function watchFileUsingFsWatch(fileName, callback, pollingInterval) { + return fsWatch(fileName, 0 /* File */, createFsWatchCallbackForFileWatcherCallback(fileName, callback), /*recursive*/ false, fsWatchFile, pollingInterval); + } + function createWatchFileUsingDynamicWatchFile(watchFile) { + return function (fileName, callback, pollingInterval) { return fsWatch(fileName, 0 /* File */, createFsWatchCallbackForFileWatcherCallback(fileName, callback), /*recursive*/ false, watchFile, pollingInterval); }; + } + function fsWatchDirectory(directoryName, callback, recursive) { + return fsWatch(directoryName, 1 /* Directory */, callback, !!recursive, fsWatchFile); + } + function watchDirectoryUsingFsWatch(directoryName, callback, recursive) { + return fsWatchDirectory(directoryName, createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback), recursive); + } + function createWatchDirectoryUsing(fsWatchFile) { + return function (directoryName, callback) { return fsWatchFile(directoryName, function () { return callback(directoryName); }, PollingInterval.Medium); }; + } + function readFile(fileName, _encoding) { + if (!fileExists(fileName)) { + return undefined; + } + var buffer = _fs.readFileSync(fileName); + var len = buffer.length; + if (len >= 2 && buffer[0] === 0xFE && buffer[1] === 0xFF) { + // Big endian UTF-16 byte order mark detected. Since big endian is not supported by node.js, + // flip all byte pairs and treat as little endian. + len &= ~1; // Round down to a multiple of 2 + for (var i = 0; i < len; i += 2) { + var temp = buffer[i]; + buffer[i] = buffer[i + 1]; + buffer[i + 1] = temp; + } + return buffer.toString("utf16le", 2); + } + if (len >= 2 && buffer[0] === 0xFF && buffer[1] === 0xFE) { + // Little endian UTF-16 byte order mark detected + return buffer.toString("utf16le", 2); + } + if (len >= 3 && buffer[0] === 0xEF && buffer[1] === 0xBB && buffer[2] === 0xBF) { + // UTF-8 byte order mark detected + return buffer.toString("utf8", 3); + } + // Default is UTF-8 with no byte order mark + return buffer.toString("utf8"); + } + function writeFile(fileName, data, writeByteOrderMark) { + // If a BOM is required, emit one + if (writeByteOrderMark) { + data = byteOrderMarkIndicator + data; + } + var fd; + try { + fd = _fs.openSync(fileName, "w"); + _fs.writeSync(fd, data, /*position*/ undefined, "utf8"); + } + finally { + if (fd !== undefined) { + _fs.closeSync(fd); + } + } + } + function getAccessibleFileSystemEntries(path) { + try { + var entries = _fs.readdirSync(path || ".").sort(); + var files = []; + var directories = []; + for (var _i = 0, entries_2 = entries; _i < entries_2.length; _i++) { + var entry = entries_2[_i]; + // This is necessary because on some file system node fails to exclude + // "." and "..". See https://github.com/nodejs/node/issues/4002 + if (entry === "." || entry === "..") { + continue; + } + var name = ts.combinePaths(path, entry); + var stat = void 0; + try { + stat = _fs.statSync(name); + } + catch (e) { + continue; + } + if (stat.isFile()) { + files.push(entry); + } + else if (stat.isDirectory()) { + directories.push(entry); + } + } + return { files: files, directories: directories }; + } + catch (e) { + return ts.emptyFileSystemEntries; + } + } + function readDirectory(path, extensions, excludes, includes, depth) { + return ts.matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, process.cwd(), depth, getAccessibleFileSystemEntries); + } + function fileSystemEntryExists(path, entryKind) { + try { + var stat = _fs.statSync(path); + switch (entryKind) { + case 0 /* File */: return stat.isFile(); + case 1 /* Directory */: return stat.isDirectory(); + default: return false; + } + } + catch (e) { + return false; + } + } + function fileExists(path) { + return fileSystemEntryExists(path, 0 /* File */); + } + function directoryExists(path) { + return fileSystemEntryExists(path, 1 /* Directory */); + } + function getDirectories(path) { + return ts.filter(_fs.readdirSync(path), function (dir) { return fileSystemEntryExists(ts.combinePaths(path, dir), 1 /* Directory */); }); + } + function realpath(path) { + try { + return _fs.realpathSync(path); + } + catch (_a) { + return path; + } + } + function getModifiedTime(path) { + try { + return _fs.statSync(path).mtime; + } + catch (e) { + return undefined; + } + } + function setModifiedTime(path, time) { + try { + _fs.utimesSync(path, time, time); + } + catch (e) { + return; + } + } + function deleteFile(path) { + try { + return _fs.unlinkSync(path); + } + catch (e) { + return; + } + } + /** + * djb2 hashing algorithm + * http://www.cse.yorku.ca/~oz/hash.html + */ + function generateDjb2Hash(data) { + var chars = data.split("").map(function (str) { return str.charCodeAt(0); }); + return "" + chars.reduce(function (prev, curr) { return ((prev << 5) + prev) + curr; }, 5381); + } + function createMD5HashUsingNativeCrypto(data) { + var hash = _crypto.createHash("md5"); + hash.update(data); + return hash.digest("hex"); + } + function createSHA256Hash(data) { + var hash = _crypto.createHash("sha256"); + hash.update(data); + return hash.digest("hex"); + } + } + function getChakraSystem() { + var realpath = ChakraHost.realpath && (function (path) { return ChakraHost.realpath(path); }); + return { + newLine: ChakraHost.newLine || "\r\n", + args: ChakraHost.args, + useCaseSensitiveFileNames: !!ChakraHost.useCaseSensitiveFileNames, + write: ChakraHost.echo, + readFile: function (path, _encoding) { + // encoding is automatically handled by the implementation in ChakraHost + return ChakraHost.readFile(path); + }, + writeFile: function (path, data, writeByteOrderMark) { + // If a BOM is required, emit one + if (writeByteOrderMark) { + data = byteOrderMarkIndicator + data; + } + ChakraHost.writeFile(path, data); + }, + resolvePath: ChakraHost.resolvePath, + fileExists: ChakraHost.fileExists, + deleteFile: ChakraHost.deleteFile, + getModifiedTime: ChakraHost.getModifiedTime, + setModifiedTime: ChakraHost.setModifiedTime, + directoryExists: ChakraHost.directoryExists, + createDirectory: ChakraHost.createDirectory, + getExecutingFilePath: function () { return ChakraHost.executingFile; }, + getCurrentDirectory: function () { return ChakraHost.currentDirectory; }, + getDirectories: ChakraHost.getDirectories, + getEnvironmentVariable: ChakraHost.getEnvironmentVariable || (function () { return ""; }), + readDirectory: function (path, extensions, excludes, includes, _depth) { + var pattern = ts.getFileMatcherPatterns(path, excludes, includes, !!ChakraHost.useCaseSensitiveFileNames, ChakraHost.currentDirectory); + return ChakraHost.readDirectory(path, extensions, pattern.basePaths, pattern.excludePattern, pattern.includeFilePattern, pattern.includeDirectoryPattern); + }, + exit: ChakraHost.quit, + realpath: realpath + }; + } + function recursiveCreateDirectory(directoryPath, sys) { + var basePath = ts.getDirectoryPath(directoryPath); + var shouldCreateParent = basePath !== "" && directoryPath !== basePath && !sys.directoryExists(basePath); + if (shouldCreateParent) { + recursiveCreateDirectory(basePath, sys); + } + if (shouldCreateParent || !sys.directoryExists(directoryPath)) { + sys.createDirectory(directoryPath); + } + } + var sys; + if (typeof ChakraHost !== "undefined") { + sys = getChakraSystem(); + } + else if (typeof process !== "undefined" && process.nextTick && !process.browser && typeof require !== "undefined") { + // process and process.nextTick checks if current environment is node-like + // process.browser check excludes webpack and browserify + sys = getNodeSystem(); + } + if (sys) { + // patch writefile to create folder before writing the file + var originalWriteFile_1 = sys.writeFile; + sys.writeFile = function (path, data, writeBom) { + var directoryPath = ts.getDirectoryPath(ts.normalizeSlashes(path)); + if (directoryPath && !sys.directoryExists(directoryPath)) { + recursiveCreateDirectory(directoryPath, sys); + } + originalWriteFile_1.call(sys, path, data, writeBom); + }; + } + return sys; + })(); + if (ts.sys && ts.sys.getEnvironmentVariable) { + setCustomPollingValues(ts.sys); + ts.Debug.currentAssertionLevel = /^development$/i.test(ts.sys.getEnvironmentVariable("NODE_ENV")) + ? 1 /* Normal */ + : 0 /* None */; + } + if (ts.sys && ts.sys.debugMode) { + ts.Debug.isDebugging = true; + } +})(ts || (ts = {})); +// +// generated from './diagnosticInformationMap.generated.ts' by 'src/compiler' +/* @internal */ +var ts; +(function (ts) { + function diag(code, category, key, message, reportsUnnecessary) { + return { code: code, category: category, key: key, message: message, reportsUnnecessary: reportsUnnecessary }; + } + // tslint:disable-next-line variable-name + ts.Diagnostics = { + Unterminated_string_literal: diag(1002, ts.DiagnosticCategory.Error, "Unterminated_string_literal_1002", "Unterminated string literal."), + Identifier_expected: diag(1003, ts.DiagnosticCategory.Error, "Identifier_expected_1003", "Identifier expected."), + _0_expected: diag(1005, ts.DiagnosticCategory.Error, "_0_expected_1005", "'{0}' expected."), + A_file_cannot_have_a_reference_to_itself: diag(1006, ts.DiagnosticCategory.Error, "A_file_cannot_have_a_reference_to_itself_1006", "A file cannot have a reference to itself."), + Trailing_comma_not_allowed: diag(1009, ts.DiagnosticCategory.Error, "Trailing_comma_not_allowed_1009", "Trailing comma not allowed."), + Asterisk_Slash_expected: diag(1010, ts.DiagnosticCategory.Error, "Asterisk_Slash_expected_1010", "'*/' expected."), + An_element_access_expression_should_take_an_argument: diag(1011, ts.DiagnosticCategory.Error, "An_element_access_expression_should_take_an_argument_1011", "An element access expression should take an argument."), + Unexpected_token: diag(1012, ts.DiagnosticCategory.Error, "Unexpected_token_1012", "Unexpected token."), + A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma: diag(1013, ts.DiagnosticCategory.Error, "A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma_1013", "A rest parameter or binding pattern may not have a trailing comma."), + A_rest_parameter_must_be_last_in_a_parameter_list: diag(1014, ts.DiagnosticCategory.Error, "A_rest_parameter_must_be_last_in_a_parameter_list_1014", "A rest parameter must be last in a parameter list."), + Parameter_cannot_have_question_mark_and_initializer: diag(1015, ts.DiagnosticCategory.Error, "Parameter_cannot_have_question_mark_and_initializer_1015", "Parameter cannot have question mark and initializer."), + A_required_parameter_cannot_follow_an_optional_parameter: diag(1016, ts.DiagnosticCategory.Error, "A_required_parameter_cannot_follow_an_optional_parameter_1016", "A required parameter cannot follow an optional parameter."), + An_index_signature_cannot_have_a_rest_parameter: diag(1017, ts.DiagnosticCategory.Error, "An_index_signature_cannot_have_a_rest_parameter_1017", "An index signature cannot have a rest parameter."), + An_index_signature_parameter_cannot_have_an_accessibility_modifier: diag(1018, ts.DiagnosticCategory.Error, "An_index_signature_parameter_cannot_have_an_accessibility_modifier_1018", "An index signature parameter cannot have an accessibility modifier."), + An_index_signature_parameter_cannot_have_a_question_mark: diag(1019, ts.DiagnosticCategory.Error, "An_index_signature_parameter_cannot_have_a_question_mark_1019", "An index signature parameter cannot have a question mark."), + An_index_signature_parameter_cannot_have_an_initializer: diag(1020, ts.DiagnosticCategory.Error, "An_index_signature_parameter_cannot_have_an_initializer_1020", "An index signature parameter cannot have an initializer."), + An_index_signature_must_have_a_type_annotation: diag(1021, ts.DiagnosticCategory.Error, "An_index_signature_must_have_a_type_annotation_1021", "An index signature must have a type annotation."), + An_index_signature_parameter_must_have_a_type_annotation: diag(1022, ts.DiagnosticCategory.Error, "An_index_signature_parameter_must_have_a_type_annotation_1022", "An index signature parameter must have a type annotation."), + An_index_signature_parameter_type_must_be_string_or_number: diag(1023, ts.DiagnosticCategory.Error, "An_index_signature_parameter_type_must_be_string_or_number_1023", "An index signature parameter type must be 'string' or 'number'."), + readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature: diag(1024, ts.DiagnosticCategory.Error, "readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024", "'readonly' modifier can only appear on a property declaration or index signature."), + Accessibility_modifier_already_seen: diag(1028, ts.DiagnosticCategory.Error, "Accessibility_modifier_already_seen_1028", "Accessibility modifier already seen."), + _0_modifier_must_precede_1_modifier: diag(1029, ts.DiagnosticCategory.Error, "_0_modifier_must_precede_1_modifier_1029", "'{0}' modifier must precede '{1}' modifier."), + _0_modifier_already_seen: diag(1030, ts.DiagnosticCategory.Error, "_0_modifier_already_seen_1030", "'{0}' modifier already seen."), + _0_modifier_cannot_appear_on_a_class_element: diag(1031, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_a_class_element_1031", "'{0}' modifier cannot appear on a class element."), + super_must_be_followed_by_an_argument_list_or_member_access: diag(1034, ts.DiagnosticCategory.Error, "super_must_be_followed_by_an_argument_list_or_member_access_1034", "'super' must be followed by an argument list or member access."), + Only_ambient_modules_can_use_quoted_names: diag(1035, ts.DiagnosticCategory.Error, "Only_ambient_modules_can_use_quoted_names_1035", "Only ambient modules can use quoted names."), + Statements_are_not_allowed_in_ambient_contexts: diag(1036, ts.DiagnosticCategory.Error, "Statements_are_not_allowed_in_ambient_contexts_1036", "Statements are not allowed in ambient contexts."), + A_declare_modifier_cannot_be_used_in_an_already_ambient_context: diag(1038, ts.DiagnosticCategory.Error, "A_declare_modifier_cannot_be_used_in_an_already_ambient_context_1038", "A 'declare' modifier cannot be used in an already ambient context."), + Initializers_are_not_allowed_in_ambient_contexts: diag(1039, ts.DiagnosticCategory.Error, "Initializers_are_not_allowed_in_ambient_contexts_1039", "Initializers are not allowed in ambient contexts."), + _0_modifier_cannot_be_used_in_an_ambient_context: diag(1040, ts.DiagnosticCategory.Error, "_0_modifier_cannot_be_used_in_an_ambient_context_1040", "'{0}' modifier cannot be used in an ambient context."), + _0_modifier_cannot_be_used_with_a_class_declaration: diag(1041, ts.DiagnosticCategory.Error, "_0_modifier_cannot_be_used_with_a_class_declaration_1041", "'{0}' modifier cannot be used with a class declaration."), + _0_modifier_cannot_be_used_here: diag(1042, ts.DiagnosticCategory.Error, "_0_modifier_cannot_be_used_here_1042", "'{0}' modifier cannot be used here."), + _0_modifier_cannot_appear_on_a_data_property: diag(1043, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_a_data_property_1043", "'{0}' modifier cannot appear on a data property."), + _0_modifier_cannot_appear_on_a_module_or_namespace_element: diag(1044, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_a_module_or_namespace_element_1044", "'{0}' modifier cannot appear on a module or namespace element."), + A_0_modifier_cannot_be_used_with_an_interface_declaration: diag(1045, ts.DiagnosticCategory.Error, "A_0_modifier_cannot_be_used_with_an_interface_declaration_1045", "A '{0}' modifier cannot be used with an interface declaration."), + A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file: diag(1046, ts.DiagnosticCategory.Error, "A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file_1046", "A 'declare' modifier is required for a top level declaration in a .d.ts file."), + A_rest_parameter_cannot_be_optional: diag(1047, ts.DiagnosticCategory.Error, "A_rest_parameter_cannot_be_optional_1047", "A rest parameter cannot be optional."), + A_rest_parameter_cannot_have_an_initializer: diag(1048, ts.DiagnosticCategory.Error, "A_rest_parameter_cannot_have_an_initializer_1048", "A rest parameter cannot have an initializer."), + A_set_accessor_must_have_exactly_one_parameter: diag(1049, ts.DiagnosticCategory.Error, "A_set_accessor_must_have_exactly_one_parameter_1049", "A 'set' accessor must have exactly one parameter."), + A_set_accessor_cannot_have_an_optional_parameter: diag(1051, ts.DiagnosticCategory.Error, "A_set_accessor_cannot_have_an_optional_parameter_1051", "A 'set' accessor cannot have an optional parameter."), + A_set_accessor_parameter_cannot_have_an_initializer: diag(1052, ts.DiagnosticCategory.Error, "A_set_accessor_parameter_cannot_have_an_initializer_1052", "A 'set' accessor parameter cannot have an initializer."), + A_set_accessor_cannot_have_rest_parameter: diag(1053, ts.DiagnosticCategory.Error, "A_set_accessor_cannot_have_rest_parameter_1053", "A 'set' accessor cannot have rest parameter."), + A_get_accessor_cannot_have_parameters: diag(1054, ts.DiagnosticCategory.Error, "A_get_accessor_cannot_have_parameters_1054", "A 'get' accessor cannot have parameters."), + Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value: diag(1055, ts.DiagnosticCategory.Error, "Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Prom_1055", "Type '{0}' is not a valid async function return type in ES5/ES3 because it does not refer to a Promise-compatible constructor value."), + Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher: diag(1056, ts.DiagnosticCategory.Error, "Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher_1056", "Accessors are only available when targeting ECMAScript 5 and higher."), + An_async_function_or_method_must_have_a_valid_awaitable_return_type: diag(1057, ts.DiagnosticCategory.Error, "An_async_function_or_method_must_have_a_valid_awaitable_return_type_1057", "An async function or method must have a valid awaitable return type."), + The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1058, ts.DiagnosticCategory.Error, "The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_t_1058", "The return type of an async function must either be a valid promise or must not contain a callable 'then' member."), + A_promise_must_have_a_then_method: diag(1059, ts.DiagnosticCategory.Error, "A_promise_must_have_a_then_method_1059", "A promise must have a 'then' method."), + The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback: diag(1060, ts.DiagnosticCategory.Error, "The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback_1060", "The first parameter of the 'then' method of a promise must be a callback."), + Enum_member_must_have_initializer: diag(1061, ts.DiagnosticCategory.Error, "Enum_member_must_have_initializer_1061", "Enum member must have initializer."), + Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method: diag(1062, ts.DiagnosticCategory.Error, "Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method_1062", "Type is referenced directly or indirectly in the fulfillment callback of its own 'then' method."), + An_export_assignment_cannot_be_used_in_a_namespace: diag(1063, ts.DiagnosticCategory.Error, "An_export_assignment_cannot_be_used_in_a_namespace_1063", "An export assignment cannot be used in a namespace."), + The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type: diag(1064, ts.DiagnosticCategory.Error, "The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_1064", "The return type of an async function or method must be the global Promise type."), + In_ambient_enum_declarations_member_initializer_must_be_constant_expression: diag(1066, ts.DiagnosticCategory.Error, "In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066", "In ambient enum declarations member initializer must be constant expression."), + Unexpected_token_A_constructor_method_accessor_or_property_was_expected: diag(1068, ts.DiagnosticCategory.Error, "Unexpected_token_A_constructor_method_accessor_or_property_was_expected_1068", "Unexpected token. A constructor, method, accessor, or property was expected."), + Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces: diag(1069, ts.DiagnosticCategory.Error, "Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces_1069", "Unexpected token. A type parameter name was expected without curly braces."), + _0_modifier_cannot_appear_on_a_type_member: diag(1070, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_a_type_member_1070", "'{0}' modifier cannot appear on a type member."), + _0_modifier_cannot_appear_on_an_index_signature: diag(1071, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_an_index_signature_1071", "'{0}' modifier cannot appear on an index signature."), + A_0_modifier_cannot_be_used_with_an_import_declaration: diag(1079, ts.DiagnosticCategory.Error, "A_0_modifier_cannot_be_used_with_an_import_declaration_1079", "A '{0}' modifier cannot be used with an import declaration."), + Invalid_reference_directive_syntax: diag(1084, ts.DiagnosticCategory.Error, "Invalid_reference_directive_syntax_1084", "Invalid 'reference' directive syntax."), + Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0: diag(1085, ts.DiagnosticCategory.Error, "Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0_1085", "Octal literals are not available when targeting ECMAScript 5 and higher. Use the syntax '{0}'."), + An_accessor_cannot_be_declared_in_an_ambient_context: diag(1086, ts.DiagnosticCategory.Error, "An_accessor_cannot_be_declared_in_an_ambient_context_1086", "An accessor cannot be declared in an ambient context."), + _0_modifier_cannot_appear_on_a_constructor_declaration: diag(1089, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_a_constructor_declaration_1089", "'{0}' modifier cannot appear on a constructor declaration."), + _0_modifier_cannot_appear_on_a_parameter: diag(1090, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_a_parameter_1090", "'{0}' modifier cannot appear on a parameter."), + Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement: diag(1091, ts.DiagnosticCategory.Error, "Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement_1091", "Only a single variable declaration is allowed in a 'for...in' statement."), + Type_parameters_cannot_appear_on_a_constructor_declaration: diag(1092, ts.DiagnosticCategory.Error, "Type_parameters_cannot_appear_on_a_constructor_declaration_1092", "Type parameters cannot appear on a constructor declaration."), + Type_annotation_cannot_appear_on_a_constructor_declaration: diag(1093, ts.DiagnosticCategory.Error, "Type_annotation_cannot_appear_on_a_constructor_declaration_1093", "Type annotation cannot appear on a constructor declaration."), + An_accessor_cannot_have_type_parameters: diag(1094, ts.DiagnosticCategory.Error, "An_accessor_cannot_have_type_parameters_1094", "An accessor cannot have type parameters."), + A_set_accessor_cannot_have_a_return_type_annotation: diag(1095, ts.DiagnosticCategory.Error, "A_set_accessor_cannot_have_a_return_type_annotation_1095", "A 'set' accessor cannot have a return type annotation."), + An_index_signature_must_have_exactly_one_parameter: diag(1096, ts.DiagnosticCategory.Error, "An_index_signature_must_have_exactly_one_parameter_1096", "An index signature must have exactly one parameter."), + _0_list_cannot_be_empty: diag(1097, ts.DiagnosticCategory.Error, "_0_list_cannot_be_empty_1097", "'{0}' list cannot be empty."), + Type_parameter_list_cannot_be_empty: diag(1098, ts.DiagnosticCategory.Error, "Type_parameter_list_cannot_be_empty_1098", "Type parameter list cannot be empty."), + Type_argument_list_cannot_be_empty: diag(1099, ts.DiagnosticCategory.Error, "Type_argument_list_cannot_be_empty_1099", "Type argument list cannot be empty."), + Invalid_use_of_0_in_strict_mode: diag(1100, ts.DiagnosticCategory.Error, "Invalid_use_of_0_in_strict_mode_1100", "Invalid use of '{0}' in strict mode."), + with_statements_are_not_allowed_in_strict_mode: diag(1101, ts.DiagnosticCategory.Error, "with_statements_are_not_allowed_in_strict_mode_1101", "'with' statements are not allowed in strict mode."), + delete_cannot_be_called_on_an_identifier_in_strict_mode: diag(1102, ts.DiagnosticCategory.Error, "delete_cannot_be_called_on_an_identifier_in_strict_mode_1102", "'delete' cannot be called on an identifier in strict mode."), + A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator: diag(1103, ts.DiagnosticCategory.Error, "A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator_1103", "A 'for-await-of' statement is only allowed within an async function or async generator."), + A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement: diag(1104, ts.DiagnosticCategory.Error, "A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement_1104", "A 'continue' statement can only be used within an enclosing iteration statement."), + A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement: diag(1105, ts.DiagnosticCategory.Error, "A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement_1105", "A 'break' statement can only be used within an enclosing iteration or switch statement."), + Jump_target_cannot_cross_function_boundary: diag(1107, ts.DiagnosticCategory.Error, "Jump_target_cannot_cross_function_boundary_1107", "Jump target cannot cross function boundary."), + A_return_statement_can_only_be_used_within_a_function_body: diag(1108, ts.DiagnosticCategory.Error, "A_return_statement_can_only_be_used_within_a_function_body_1108", "A 'return' statement can only be used within a function body."), + Expression_expected: diag(1109, ts.DiagnosticCategory.Error, "Expression_expected_1109", "Expression expected."), + Type_expected: diag(1110, ts.DiagnosticCategory.Error, "Type_expected_1110", "Type expected."), + A_default_clause_cannot_appear_more_than_once_in_a_switch_statement: diag(1113, ts.DiagnosticCategory.Error, "A_default_clause_cannot_appear_more_than_once_in_a_switch_statement_1113", "A 'default' clause cannot appear more than once in a 'switch' statement."), + Duplicate_label_0: diag(1114, ts.DiagnosticCategory.Error, "Duplicate_label_0_1114", "Duplicate label '{0}'."), + A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement: diag(1115, ts.DiagnosticCategory.Error, "A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement_1115", "A 'continue' statement can only jump to a label of an enclosing iteration statement."), + A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement: diag(1116, ts.DiagnosticCategory.Error, "A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement_1116", "A 'break' statement can only jump to a label of an enclosing statement."), + An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode: diag(1117, ts.DiagnosticCategory.Error, "An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode_1117", "An object literal cannot have multiple properties with the same name in strict mode."), + An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name: diag(1118, ts.DiagnosticCategory.Error, "An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name_1118", "An object literal cannot have multiple get/set accessors with the same name."), + An_object_literal_cannot_have_property_and_accessor_with_the_same_name: diag(1119, ts.DiagnosticCategory.Error, "An_object_literal_cannot_have_property_and_accessor_with_the_same_name_1119", "An object literal cannot have property and accessor with the same name."), + An_export_assignment_cannot_have_modifiers: diag(1120, ts.DiagnosticCategory.Error, "An_export_assignment_cannot_have_modifiers_1120", "An export assignment cannot have modifiers."), + Octal_literals_are_not_allowed_in_strict_mode: diag(1121, ts.DiagnosticCategory.Error, "Octal_literals_are_not_allowed_in_strict_mode_1121", "Octal literals are not allowed in strict mode."), + Variable_declaration_list_cannot_be_empty: diag(1123, ts.DiagnosticCategory.Error, "Variable_declaration_list_cannot_be_empty_1123", "Variable declaration list cannot be empty."), + Digit_expected: diag(1124, ts.DiagnosticCategory.Error, "Digit_expected_1124", "Digit expected."), + Hexadecimal_digit_expected: diag(1125, ts.DiagnosticCategory.Error, "Hexadecimal_digit_expected_1125", "Hexadecimal digit expected."), + Unexpected_end_of_text: diag(1126, ts.DiagnosticCategory.Error, "Unexpected_end_of_text_1126", "Unexpected end of text."), + Invalid_character: diag(1127, ts.DiagnosticCategory.Error, "Invalid_character_1127", "Invalid character."), + Declaration_or_statement_expected: diag(1128, ts.DiagnosticCategory.Error, "Declaration_or_statement_expected_1128", "Declaration or statement expected."), + Statement_expected: diag(1129, ts.DiagnosticCategory.Error, "Statement_expected_1129", "Statement expected."), + case_or_default_expected: diag(1130, ts.DiagnosticCategory.Error, "case_or_default_expected_1130", "'case' or 'default' expected."), + Property_or_signature_expected: diag(1131, ts.DiagnosticCategory.Error, "Property_or_signature_expected_1131", "Property or signature expected."), + Enum_member_expected: diag(1132, ts.DiagnosticCategory.Error, "Enum_member_expected_1132", "Enum member expected."), + Variable_declaration_expected: diag(1134, ts.DiagnosticCategory.Error, "Variable_declaration_expected_1134", "Variable declaration expected."), + Argument_expression_expected: diag(1135, ts.DiagnosticCategory.Error, "Argument_expression_expected_1135", "Argument expression expected."), + Property_assignment_expected: diag(1136, ts.DiagnosticCategory.Error, "Property_assignment_expected_1136", "Property assignment expected."), + Expression_or_comma_expected: diag(1137, ts.DiagnosticCategory.Error, "Expression_or_comma_expected_1137", "Expression or comma expected."), + Parameter_declaration_expected: diag(1138, ts.DiagnosticCategory.Error, "Parameter_declaration_expected_1138", "Parameter declaration expected."), + Type_parameter_declaration_expected: diag(1139, ts.DiagnosticCategory.Error, "Type_parameter_declaration_expected_1139", "Type parameter declaration expected."), + Type_argument_expected: diag(1140, ts.DiagnosticCategory.Error, "Type_argument_expected_1140", "Type argument expected."), + String_literal_expected: diag(1141, ts.DiagnosticCategory.Error, "String_literal_expected_1141", "String literal expected."), + Line_break_not_permitted_here: diag(1142, ts.DiagnosticCategory.Error, "Line_break_not_permitted_here_1142", "Line break not permitted here."), + or_expected: diag(1144, ts.DiagnosticCategory.Error, "or_expected_1144", "'{' or ';' expected."), + Declaration_expected: diag(1146, ts.DiagnosticCategory.Error, "Declaration_expected_1146", "Declaration expected."), + Import_declarations_in_a_namespace_cannot_reference_a_module: diag(1147, ts.DiagnosticCategory.Error, "Import_declarations_in_a_namespace_cannot_reference_a_module_1147", "Import declarations in a namespace cannot reference a module."), + Cannot_use_imports_exports_or_module_augmentations_when_module_is_none: diag(1148, ts.DiagnosticCategory.Error, "Cannot_use_imports_exports_or_module_augmentations_when_module_is_none_1148", "Cannot use imports, exports, or module augmentations when '--module' is 'none'."), + File_name_0_differs_from_already_included_file_name_1_only_in_casing: diag(1149, ts.DiagnosticCategory.Error, "File_name_0_differs_from_already_included_file_name_1_only_in_casing_1149", "File name '{0}' differs from already included file name '{1}' only in casing."), + new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead: diag(1150, ts.DiagnosticCategory.Error, "new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead_1150", "'new T[]' cannot be used to create an array. Use 'new Array()' instead."), + const_declarations_must_be_initialized: diag(1155, ts.DiagnosticCategory.Error, "const_declarations_must_be_initialized_1155", "'const' declarations must be initialized."), + const_declarations_can_only_be_declared_inside_a_block: diag(1156, ts.DiagnosticCategory.Error, "const_declarations_can_only_be_declared_inside_a_block_1156", "'const' declarations can only be declared inside a block."), + let_declarations_can_only_be_declared_inside_a_block: diag(1157, ts.DiagnosticCategory.Error, "let_declarations_can_only_be_declared_inside_a_block_1157", "'let' declarations can only be declared inside a block."), + Unterminated_template_literal: diag(1160, ts.DiagnosticCategory.Error, "Unterminated_template_literal_1160", "Unterminated template literal."), + Unterminated_regular_expression_literal: diag(1161, ts.DiagnosticCategory.Error, "Unterminated_regular_expression_literal_1161", "Unterminated regular expression literal."), + An_object_member_cannot_be_declared_optional: diag(1162, ts.DiagnosticCategory.Error, "An_object_member_cannot_be_declared_optional_1162", "An object member cannot be declared optional."), + A_yield_expression_is_only_allowed_in_a_generator_body: diag(1163, ts.DiagnosticCategory.Error, "A_yield_expression_is_only_allowed_in_a_generator_body_1163", "A 'yield' expression is only allowed in a generator body."), + Computed_property_names_are_not_allowed_in_enums: diag(1164, ts.DiagnosticCategory.Error, "Computed_property_names_are_not_allowed_in_enums_1164", "Computed property names are not allowed in enums."), + A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: diag(1165, ts.DiagnosticCategory.Error, "A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_t_1165", "A computed property name in an ambient context must refer to an expression whose type is a literal type or a 'unique symbol' type."), + A_computed_property_name_in_a_class_property_declaration_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: diag(1166, ts.DiagnosticCategory.Error, "A_computed_property_name_in_a_class_property_declaration_must_refer_to_an_expression_whose_type_is_a_1166", "A computed property name in a class property declaration must refer to an expression whose type is a literal type or a 'unique symbol' type."), + A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: diag(1168, ts.DiagnosticCategory.Error, "A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_ty_1168", "A computed property name in a method overload must refer to an expression whose type is a literal type or a 'unique symbol' type."), + A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: diag(1169, ts.DiagnosticCategory.Error, "A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_1169", "A computed property name in an interface must refer to an expression whose type is a literal type or a 'unique symbol' type."), + A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: diag(1170, ts.DiagnosticCategory.Error, "A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type__1170", "A computed property name in a type literal must refer to an expression whose type is a literal type or a 'unique symbol' type."), + A_comma_expression_is_not_allowed_in_a_computed_property_name: diag(1171, ts.DiagnosticCategory.Error, "A_comma_expression_is_not_allowed_in_a_computed_property_name_1171", "A comma expression is not allowed in a computed property name."), + extends_clause_already_seen: diag(1172, ts.DiagnosticCategory.Error, "extends_clause_already_seen_1172", "'extends' clause already seen."), + extends_clause_must_precede_implements_clause: diag(1173, ts.DiagnosticCategory.Error, "extends_clause_must_precede_implements_clause_1173", "'extends' clause must precede 'implements' clause."), + Classes_can_only_extend_a_single_class: diag(1174, ts.DiagnosticCategory.Error, "Classes_can_only_extend_a_single_class_1174", "Classes can only extend a single class."), + implements_clause_already_seen: diag(1175, ts.DiagnosticCategory.Error, "implements_clause_already_seen_1175", "'implements' clause already seen."), + Interface_declaration_cannot_have_implements_clause: diag(1176, ts.DiagnosticCategory.Error, "Interface_declaration_cannot_have_implements_clause_1176", "Interface declaration cannot have 'implements' clause."), + Binary_digit_expected: diag(1177, ts.DiagnosticCategory.Error, "Binary_digit_expected_1177", "Binary digit expected."), + Octal_digit_expected: diag(1178, ts.DiagnosticCategory.Error, "Octal_digit_expected_1178", "Octal digit expected."), + Unexpected_token_expected: diag(1179, ts.DiagnosticCategory.Error, "Unexpected_token_expected_1179", "Unexpected token. '{' expected."), + Property_destructuring_pattern_expected: diag(1180, ts.DiagnosticCategory.Error, "Property_destructuring_pattern_expected_1180", "Property destructuring pattern expected."), + Array_element_destructuring_pattern_expected: diag(1181, ts.DiagnosticCategory.Error, "Array_element_destructuring_pattern_expected_1181", "Array element destructuring pattern expected."), + A_destructuring_declaration_must_have_an_initializer: diag(1182, ts.DiagnosticCategory.Error, "A_destructuring_declaration_must_have_an_initializer_1182", "A destructuring declaration must have an initializer."), + An_implementation_cannot_be_declared_in_ambient_contexts: diag(1183, ts.DiagnosticCategory.Error, "An_implementation_cannot_be_declared_in_ambient_contexts_1183", "An implementation cannot be declared in ambient contexts."), + Modifiers_cannot_appear_here: diag(1184, ts.DiagnosticCategory.Error, "Modifiers_cannot_appear_here_1184", "Modifiers cannot appear here."), + Merge_conflict_marker_encountered: diag(1185, ts.DiagnosticCategory.Error, "Merge_conflict_marker_encountered_1185", "Merge conflict marker encountered."), + A_rest_element_cannot_have_an_initializer: diag(1186, ts.DiagnosticCategory.Error, "A_rest_element_cannot_have_an_initializer_1186", "A rest element cannot have an initializer."), + A_parameter_property_may_not_be_declared_using_a_binding_pattern: diag(1187, ts.DiagnosticCategory.Error, "A_parameter_property_may_not_be_declared_using_a_binding_pattern_1187", "A parameter property may not be declared using a binding pattern."), + Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement: diag(1188, ts.DiagnosticCategory.Error, "Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement_1188", "Only a single variable declaration is allowed in a 'for...of' statement."), + The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer: diag(1189, ts.DiagnosticCategory.Error, "The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer_1189", "The variable declaration of a 'for...in' statement cannot have an initializer."), + The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer: diag(1190, ts.DiagnosticCategory.Error, "The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer_1190", "The variable declaration of a 'for...of' statement cannot have an initializer."), + An_import_declaration_cannot_have_modifiers: diag(1191, ts.DiagnosticCategory.Error, "An_import_declaration_cannot_have_modifiers_1191", "An import declaration cannot have modifiers."), + Module_0_has_no_default_export: diag(1192, ts.DiagnosticCategory.Error, "Module_0_has_no_default_export_1192", "Module '{0}' has no default export."), + An_export_declaration_cannot_have_modifiers: diag(1193, ts.DiagnosticCategory.Error, "An_export_declaration_cannot_have_modifiers_1193", "An export declaration cannot have modifiers."), + Export_declarations_are_not_permitted_in_a_namespace: diag(1194, ts.DiagnosticCategory.Error, "Export_declarations_are_not_permitted_in_a_namespace_1194", "Export declarations are not permitted in a namespace."), + Catch_clause_variable_cannot_have_a_type_annotation: diag(1196, ts.DiagnosticCategory.Error, "Catch_clause_variable_cannot_have_a_type_annotation_1196", "Catch clause variable cannot have a type annotation."), + Catch_clause_variable_cannot_have_an_initializer: diag(1197, ts.DiagnosticCategory.Error, "Catch_clause_variable_cannot_have_an_initializer_1197", "Catch clause variable cannot have an initializer."), + An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive: diag(1198, ts.DiagnosticCategory.Error, "An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive_1198", "An extended Unicode escape value must be between 0x0 and 0x10FFFF inclusive."), + Unterminated_Unicode_escape_sequence: diag(1199, ts.DiagnosticCategory.Error, "Unterminated_Unicode_escape_sequence_1199", "Unterminated Unicode escape sequence."), + Line_terminator_not_permitted_before_arrow: diag(1200, ts.DiagnosticCategory.Error, "Line_terminator_not_permitted_before_arrow_1200", "Line terminator not permitted before arrow."), + Import_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_import_Asterisk_as_ns_from_mod_import_a_from_mod_import_d_from_mod_or_another_module_format_instead: diag(1202, ts.DiagnosticCategory.Error, "Import_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_import_Asterisk_as_1202", "Import assignment cannot be used when targeting ECMAScript modules. Consider using 'import * as ns from \"mod\"', 'import {a} from \"mod\"', 'import d from \"mod\"', or another module format instead."), + Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or_another_module_format_instead: diag(1203, ts.DiagnosticCategory.Error, "Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or__1203", "Export assignment cannot be used when targeting ECMAScript modules. Consider using 'export default' or another module format instead."), + Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided: diag(1205, ts.DiagnosticCategory.Error, "Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205", "Cannot re-export a type when the '--isolatedModules' flag is provided."), + Decorators_are_not_valid_here: diag(1206, ts.DiagnosticCategory.Error, "Decorators_are_not_valid_here_1206", "Decorators are not valid here."), + Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name: diag(1207, ts.DiagnosticCategory.Error, "Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name_1207", "Decorators cannot be applied to multiple get/set accessors of the same name."), + Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided: diag(1208, ts.DiagnosticCategory.Error, "Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided_1208", "Cannot compile namespaces when the '--isolatedModules' flag is provided."), + Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided: diag(1209, ts.DiagnosticCategory.Error, "Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided_1209", "Ambient const enums are not allowed when the '--isolatedModules' flag is provided."), + Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode: diag(1210, ts.DiagnosticCategory.Error, "Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode_1210", "Invalid use of '{0}'. Class definitions are automatically in strict mode."), + A_class_declaration_without_the_default_modifier_must_have_a_name: diag(1211, ts.DiagnosticCategory.Error, "A_class_declaration_without_the_default_modifier_must_have_a_name_1211", "A class declaration without the 'default' modifier must have a name."), + Identifier_expected_0_is_a_reserved_word_in_strict_mode: diag(1212, ts.DiagnosticCategory.Error, "Identifier_expected_0_is_a_reserved_word_in_strict_mode_1212", "Identifier expected. '{0}' is a reserved word in strict mode."), + Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode: diag(1213, ts.DiagnosticCategory.Error, "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_stric_1213", "Identifier expected. '{0}' is a reserved word in strict mode. Class definitions are automatically in strict mode."), + Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode: diag(1214, ts.DiagnosticCategory.Error, "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode_1214", "Identifier expected. '{0}' is a reserved word in strict mode. Modules are automatically in strict mode."), + Invalid_use_of_0_Modules_are_automatically_in_strict_mode: diag(1215, ts.DiagnosticCategory.Error, "Invalid_use_of_0_Modules_are_automatically_in_strict_mode_1215", "Invalid use of '{0}'. Modules are automatically in strict mode."), + Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules: diag(1216, ts.DiagnosticCategory.Error, "Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules_1216", "Identifier expected. '__esModule' is reserved as an exported marker when transforming ECMAScript modules."), + Export_assignment_is_not_supported_when_module_flag_is_system: diag(1218, ts.DiagnosticCategory.Error, "Export_assignment_is_not_supported_when_module_flag_is_system_1218", "Export assignment is not supported when '--module' flag is 'system'."), + Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_to_remove_this_warning: diag(1219, ts.DiagnosticCategory.Error, "Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_t_1219", "Experimental support for decorators is a feature that is subject to change in a future release. Set the 'experimentalDecorators' option to remove this warning."), + Generators_are_only_available_when_targeting_ECMAScript_2015_or_higher: diag(1220, ts.DiagnosticCategory.Error, "Generators_are_only_available_when_targeting_ECMAScript_2015_or_higher_1220", "Generators are only available when targeting ECMAScript 2015 or higher."), + Generators_are_not_allowed_in_an_ambient_context: diag(1221, ts.DiagnosticCategory.Error, "Generators_are_not_allowed_in_an_ambient_context_1221", "Generators are not allowed in an ambient context."), + An_overload_signature_cannot_be_declared_as_a_generator: diag(1222, ts.DiagnosticCategory.Error, "An_overload_signature_cannot_be_declared_as_a_generator_1222", "An overload signature cannot be declared as a generator."), + _0_tag_already_specified: diag(1223, ts.DiagnosticCategory.Error, "_0_tag_already_specified_1223", "'{0}' tag already specified."), + Signature_0_must_be_a_type_predicate: diag(1224, ts.DiagnosticCategory.Error, "Signature_0_must_be_a_type_predicate_1224", "Signature '{0}' must be a type predicate."), + Cannot_find_parameter_0: diag(1225, ts.DiagnosticCategory.Error, "Cannot_find_parameter_0_1225", "Cannot find parameter '{0}'."), + Type_predicate_0_is_not_assignable_to_1: diag(1226, ts.DiagnosticCategory.Error, "Type_predicate_0_is_not_assignable_to_1_1226", "Type predicate '{0}' is not assignable to '{1}'."), + Parameter_0_is_not_in_the_same_position_as_parameter_1: diag(1227, ts.DiagnosticCategory.Error, "Parameter_0_is_not_in_the_same_position_as_parameter_1_1227", "Parameter '{0}' is not in the same position as parameter '{1}'."), + A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods: diag(1228, ts.DiagnosticCategory.Error, "A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods_1228", "A type predicate is only allowed in return type position for functions and methods."), + A_type_predicate_cannot_reference_a_rest_parameter: diag(1229, ts.DiagnosticCategory.Error, "A_type_predicate_cannot_reference_a_rest_parameter_1229", "A type predicate cannot reference a rest parameter."), + A_type_predicate_cannot_reference_element_0_in_a_binding_pattern: diag(1230, ts.DiagnosticCategory.Error, "A_type_predicate_cannot_reference_element_0_in_a_binding_pattern_1230", "A type predicate cannot reference element '{0}' in a binding pattern."), + An_export_assignment_can_only_be_used_in_a_module: diag(1231, ts.DiagnosticCategory.Error, "An_export_assignment_can_only_be_used_in_a_module_1231", "An export assignment can only be used in a module."), + An_import_declaration_can_only_be_used_in_a_namespace_or_module: diag(1232, ts.DiagnosticCategory.Error, "An_import_declaration_can_only_be_used_in_a_namespace_or_module_1232", "An import declaration can only be used in a namespace or module."), + An_export_declaration_can_only_be_used_in_a_module: diag(1233, ts.DiagnosticCategory.Error, "An_export_declaration_can_only_be_used_in_a_module_1233", "An export declaration can only be used in a module."), + An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file: diag(1234, ts.DiagnosticCategory.Error, "An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file_1234", "An ambient module declaration is only allowed at the top level in a file."), + A_namespace_declaration_is_only_allowed_in_a_namespace_or_module: diag(1235, ts.DiagnosticCategory.Error, "A_namespace_declaration_is_only_allowed_in_a_namespace_or_module_1235", "A namespace declaration is only allowed in a namespace or module."), + The_return_type_of_a_property_decorator_function_must_be_either_void_or_any: diag(1236, ts.DiagnosticCategory.Error, "The_return_type_of_a_property_decorator_function_must_be_either_void_or_any_1236", "The return type of a property decorator function must be either 'void' or 'any'."), + The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any: diag(1237, ts.DiagnosticCategory.Error, "The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any_1237", "The return type of a parameter decorator function must be either 'void' or 'any'."), + Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression: diag(1238, ts.DiagnosticCategory.Error, "Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression_1238", "Unable to resolve signature of class decorator when called as an expression."), + Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression: diag(1239, ts.DiagnosticCategory.Error, "Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression_1239", "Unable to resolve signature of parameter decorator when called as an expression."), + Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression: diag(1240, ts.DiagnosticCategory.Error, "Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression_1240", "Unable to resolve signature of property decorator when called as an expression."), + Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression: diag(1241, ts.DiagnosticCategory.Error, "Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression_1241", "Unable to resolve signature of method decorator when called as an expression."), + abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration: diag(1242, ts.DiagnosticCategory.Error, "abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration_1242", "'abstract' modifier can only appear on a class, method, or property declaration."), + _0_modifier_cannot_be_used_with_1_modifier: diag(1243, ts.DiagnosticCategory.Error, "_0_modifier_cannot_be_used_with_1_modifier_1243", "'{0}' modifier cannot be used with '{1}' modifier."), + Abstract_methods_can_only_appear_within_an_abstract_class: diag(1244, ts.DiagnosticCategory.Error, "Abstract_methods_can_only_appear_within_an_abstract_class_1244", "Abstract methods can only appear within an abstract class."), + Method_0_cannot_have_an_implementation_because_it_is_marked_abstract: diag(1245, ts.DiagnosticCategory.Error, "Method_0_cannot_have_an_implementation_because_it_is_marked_abstract_1245", "Method '{0}' cannot have an implementation because it is marked abstract."), + An_interface_property_cannot_have_an_initializer: diag(1246, ts.DiagnosticCategory.Error, "An_interface_property_cannot_have_an_initializer_1246", "An interface property cannot have an initializer."), + A_type_literal_property_cannot_have_an_initializer: diag(1247, ts.DiagnosticCategory.Error, "A_type_literal_property_cannot_have_an_initializer_1247", "A type literal property cannot have an initializer."), + A_class_member_cannot_have_the_0_keyword: diag(1248, ts.DiagnosticCategory.Error, "A_class_member_cannot_have_the_0_keyword_1248", "A class member cannot have the '{0}' keyword."), + A_decorator_can_only_decorate_a_method_implementation_not_an_overload: diag(1249, ts.DiagnosticCategory.Error, "A_decorator_can_only_decorate_a_method_implementation_not_an_overload_1249", "A decorator can only decorate a method implementation, not an overload."), + Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5: diag(1250, ts.DiagnosticCategory.Error, "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_1250", "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'."), + Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_definitions_are_automatically_in_strict_mode: diag(1251, ts.DiagnosticCategory.Error, "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_d_1251", "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Class definitions are automatically in strict mode."), + Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_are_automatically_in_strict_mode: diag(1252, ts.DiagnosticCategory.Error, "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_1252", "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Modules are automatically in strict mode."), + _0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag: diag(1253, ts.DiagnosticCategory.Error, "_0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag_1253", "'{0}' tag cannot be used independently as a top level JSDoc tag."), + A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_reference: diag(1254, ts.DiagnosticCategory.Error, "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_refere_1254", "A 'const' initializer in an ambient context must be a string or numeric literal or literal enum reference."), + A_definite_assignment_assertion_is_not_permitted_in_this_context: diag(1255, ts.DiagnosticCategory.Error, "A_definite_assignment_assertion_is_not_permitted_in_this_context_1255", "A definite assignment assertion '!' is not permitted in this context."), + A_rest_element_must_be_last_in_a_tuple_type: diag(1256, ts.DiagnosticCategory.Error, "A_rest_element_must_be_last_in_a_tuple_type_1256", "A rest element must be last in a tuple type."), + A_required_element_cannot_follow_an_optional_element: diag(1257, ts.DiagnosticCategory.Error, "A_required_element_cannot_follow_an_optional_element_1257", "A required element cannot follow an optional element."), + with_statements_are_not_allowed_in_an_async_function_block: diag(1300, ts.DiagnosticCategory.Error, "with_statements_are_not_allowed_in_an_async_function_block_1300", "'with' statements are not allowed in an async function block."), + await_expression_is_only_allowed_within_an_async_function: diag(1308, ts.DiagnosticCategory.Error, "await_expression_is_only_allowed_within_an_async_function_1308", "'await' expression is only allowed within an async function."), + can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment: diag(1312, ts.DiagnosticCategory.Error, "can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment_1312", "'=' can only be used in an object literal property inside a destructuring assignment."), + The_body_of_an_if_statement_cannot_be_the_empty_statement: diag(1313, ts.DiagnosticCategory.Error, "The_body_of_an_if_statement_cannot_be_the_empty_statement_1313", "The body of an 'if' statement cannot be the empty statement."), + Global_module_exports_may_only_appear_in_module_files: diag(1314, ts.DiagnosticCategory.Error, "Global_module_exports_may_only_appear_in_module_files_1314", "Global module exports may only appear in module files."), + Global_module_exports_may_only_appear_in_declaration_files: diag(1315, ts.DiagnosticCategory.Error, "Global_module_exports_may_only_appear_in_declaration_files_1315", "Global module exports may only appear in declaration files."), + Global_module_exports_may_only_appear_at_top_level: diag(1316, ts.DiagnosticCategory.Error, "Global_module_exports_may_only_appear_at_top_level_1316", "Global module exports may only appear at top level."), + A_parameter_property_cannot_be_declared_using_a_rest_parameter: diag(1317, ts.DiagnosticCategory.Error, "A_parameter_property_cannot_be_declared_using_a_rest_parameter_1317", "A parameter property cannot be declared using a rest parameter."), + An_abstract_accessor_cannot_have_an_implementation: diag(1318, ts.DiagnosticCategory.Error, "An_abstract_accessor_cannot_have_an_implementation_1318", "An abstract accessor cannot have an implementation."), + A_default_export_can_only_be_used_in_an_ECMAScript_style_module: diag(1319, ts.DiagnosticCategory.Error, "A_default_export_can_only_be_used_in_an_ECMAScript_style_module_1319", "A default export can only be used in an ECMAScript-style module."), + Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1320, ts.DiagnosticCategory.Error, "Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member_1320", "Type of 'await' operand must either be a valid promise or must not contain a callable 'then' member."), + Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1321, ts.DiagnosticCategory.Error, "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321", "Type of 'yield' operand in an async generator must either be a valid promise or must not contain a callable 'then' member."), + Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1322, ts.DiagnosticCategory.Error, "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322", "Type of iterated elements of a 'yield*' operand must either be a valid promise or must not contain a callable 'then' member."), + Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext: diag(1323, ts.DiagnosticCategory.Error, "Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext_1323", "Dynamic import is only supported when '--module' flag is 'commonjs' or 'esNext'."), + Dynamic_import_must_have_one_specifier_as_an_argument: diag(1324, ts.DiagnosticCategory.Error, "Dynamic_import_must_have_one_specifier_as_an_argument_1324", "Dynamic import must have one specifier as an argument."), + Specifier_of_dynamic_import_cannot_be_spread_element: diag(1325, ts.DiagnosticCategory.Error, "Specifier_of_dynamic_import_cannot_be_spread_element_1325", "Specifier of dynamic import cannot be spread element."), + Dynamic_import_cannot_have_type_arguments: diag(1326, ts.DiagnosticCategory.Error, "Dynamic_import_cannot_have_type_arguments_1326", "Dynamic import cannot have type arguments"), + String_literal_with_double_quotes_expected: diag(1327, ts.DiagnosticCategory.Error, "String_literal_with_double_quotes_expected_1327", "String literal with double quotes expected."), + Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_literal: diag(1328, ts.DiagnosticCategory.Error, "Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_li_1328", "Property value can only be string literal, numeric literal, 'true', 'false', 'null', object literal or array literal."), + _0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write_0: diag(1329, ts.DiagnosticCategory.Error, "_0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write__1329", "'{0}' accepts too few arguments to be used as a decorator here. Did you mean to call it first and write '@{0}()'?"), + A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly: diag(1330, ts.DiagnosticCategory.Error, "A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly_1330", "A property of an interface or type literal whose type is a 'unique symbol' type must be 'readonly'."), + A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly: diag(1331, ts.DiagnosticCategory.Error, "A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly_1331", "A property of a class whose type is a 'unique symbol' type must be both 'static' and 'readonly'."), + A_variable_whose_type_is_a_unique_symbol_type_must_be_const: diag(1332, ts.DiagnosticCategory.Error, "A_variable_whose_type_is_a_unique_symbol_type_must_be_const_1332", "A variable whose type is a 'unique symbol' type must be 'const'."), + unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name: diag(1333, ts.DiagnosticCategory.Error, "unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name_1333", "'unique symbol' types may not be used on a variable declaration with a binding name."), + unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement: diag(1334, ts.DiagnosticCategory.Error, "unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement_1334", "'unique symbol' types are only allowed on variables in a variable statement."), + unique_symbol_types_are_not_allowed_here: diag(1335, ts.DiagnosticCategory.Error, "unique_symbol_types_are_not_allowed_here_1335", "'unique symbol' types are not allowed here."), + An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead: diag(1336, ts.DiagnosticCategory.Error, "An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead_1336", "An index signature parameter type cannot be a type alias. Consider writing '[{0}: {1}]: {2}' instead."), + An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead: diag(1337, ts.DiagnosticCategory.Error, "An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead_1337", "An index signature parameter type cannot be a union type. Consider using a mapped object type instead."), + infer_declarations_are_only_permitted_in_the_extends_clause_of_a_conditional_type: diag(1338, ts.DiagnosticCategory.Error, "infer_declarations_are_only_permitted_in_the_extends_clause_of_a_conditional_type_1338", "'infer' declarations are only permitted in the 'extends' clause of a conditional type."), + Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here: diag(1339, ts.DiagnosticCategory.Error, "Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here_1339", "Module '{0}' does not refer to a value, but is used as a value here."), + Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0: diag(1340, ts.DiagnosticCategory.Error, "Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0_1340", "Module '{0}' does not refer to a type, but is used as a type here. Did you mean 'typeof import('{0}')'?"), + Type_arguments_cannot_be_used_here: diag(1342, ts.DiagnosticCategory.Error, "Type_arguments_cannot_be_used_here_1342", "Type arguments cannot be used here."), + The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_options: diag(1343, ts.DiagnosticCategory.Error, "The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_option_1343", "The 'import.meta' meta-property is only allowed using 'ESNext' for the 'target' and 'module' compiler options."), + A_label_is_not_allowed_here: diag(1344, ts.DiagnosticCategory.Error, "A_label_is_not_allowed_here_1344", "'A label is not allowed here."), + An_expression_of_type_void_cannot_be_tested_for_truthiness: diag(1345, ts.DiagnosticCategory.Error, "An_expression_of_type_void_cannot_be_tested_for_truthiness_1345", "An expression of type 'void' cannot be tested for truthiness"), + This_parameter_is_not_allowed_with_use_strict_directive: diag(1346, ts.DiagnosticCategory.Error, "This_parameter_is_not_allowed_with_use_strict_directive_1346", "This parameter is not allowed with 'use strict' directive."), + use_strict_directive_cannot_be_used_with_non_simple_parameter_list: diag(1347, ts.DiagnosticCategory.Error, "use_strict_directive_cannot_be_used_with_non_simple_parameter_list_1347", "'use strict' directive cannot be used with non-simple parameter list."), + Non_simple_parameter_declared_here: diag(1348, ts.DiagnosticCategory.Error, "Non_simple_parameter_declared_here_1348", "Non-simple parameter declared here."), + use_strict_directive_used_here: diag(1349, ts.DiagnosticCategory.Error, "use_strict_directive_used_here_1349", "'use strict' directive used here."), + Print_the_final_configuration_instead_of_building: diag(1350, ts.DiagnosticCategory.Message, "Print_the_final_configuration_instead_of_building_1350", "Print the final configuration instead of building."), + Duplicate_identifier_0: diag(2300, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_2300", "Duplicate identifier '{0}'."), + Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: diag(2301, ts.DiagnosticCategory.Error, "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301", "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor."), + Static_members_cannot_reference_class_type_parameters: diag(2302, ts.DiagnosticCategory.Error, "Static_members_cannot_reference_class_type_parameters_2302", "Static members cannot reference class type parameters."), + Circular_definition_of_import_alias_0: diag(2303, ts.DiagnosticCategory.Error, "Circular_definition_of_import_alias_0_2303", "Circular definition of import alias '{0}'."), + Cannot_find_name_0: diag(2304, ts.DiagnosticCategory.Error, "Cannot_find_name_0_2304", "Cannot find name '{0}'."), + Module_0_has_no_exported_member_1: diag(2305, ts.DiagnosticCategory.Error, "Module_0_has_no_exported_member_1_2305", "Module '{0}' has no exported member '{1}'."), + File_0_is_not_a_module: diag(2306, ts.DiagnosticCategory.Error, "File_0_is_not_a_module_2306", "File '{0}' is not a module."), + Cannot_find_module_0: diag(2307, ts.DiagnosticCategory.Error, "Cannot_find_module_0_2307", "Cannot find module '{0}'."), + Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambiguity: diag(2308, ts.DiagnosticCategory.Error, "Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambig_2308", "Module {0} has already exported a member named '{1}'. Consider explicitly re-exporting to resolve the ambiguity."), + An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements: diag(2309, ts.DiagnosticCategory.Error, "An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements_2309", "An export assignment cannot be used in a module with other exported elements."), + Type_0_recursively_references_itself_as_a_base_type: diag(2310, ts.DiagnosticCategory.Error, "Type_0_recursively_references_itself_as_a_base_type_2310", "Type '{0}' recursively references itself as a base type."), + A_class_may_only_extend_another_class: diag(2311, ts.DiagnosticCategory.Error, "A_class_may_only_extend_another_class_2311", "A class may only extend another class."), + An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_members: diag(2312, ts.DiagnosticCategory.Error, "An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_me_2312", "An interface can only extend an object type or intersection of object types with statically known members."), + Type_parameter_0_has_a_circular_constraint: diag(2313, ts.DiagnosticCategory.Error, "Type_parameter_0_has_a_circular_constraint_2313", "Type parameter '{0}' has a circular constraint."), + Generic_type_0_requires_1_type_argument_s: diag(2314, ts.DiagnosticCategory.Error, "Generic_type_0_requires_1_type_argument_s_2314", "Generic type '{0}' requires {1} type argument(s)."), + Type_0_is_not_generic: diag(2315, ts.DiagnosticCategory.Error, "Type_0_is_not_generic_2315", "Type '{0}' is not generic."), + Global_type_0_must_be_a_class_or_interface_type: diag(2316, ts.DiagnosticCategory.Error, "Global_type_0_must_be_a_class_or_interface_type_2316", "Global type '{0}' must be a class or interface type."), + Global_type_0_must_have_1_type_parameter_s: diag(2317, ts.DiagnosticCategory.Error, "Global_type_0_must_have_1_type_parameter_s_2317", "Global type '{0}' must have {1} type parameter(s)."), + Cannot_find_global_type_0: diag(2318, ts.DiagnosticCategory.Error, "Cannot_find_global_type_0_2318", "Cannot find global type '{0}'."), + Named_property_0_of_types_1_and_2_are_not_identical: diag(2319, ts.DiagnosticCategory.Error, "Named_property_0_of_types_1_and_2_are_not_identical_2319", "Named property '{0}' of types '{1}' and '{2}' are not identical."), + Interface_0_cannot_simultaneously_extend_types_1_and_2: diag(2320, ts.DiagnosticCategory.Error, "Interface_0_cannot_simultaneously_extend_types_1_and_2_2320", "Interface '{0}' cannot simultaneously extend types '{1}' and '{2}'."), + Excessive_stack_depth_comparing_types_0_and_1: diag(2321, ts.DiagnosticCategory.Error, "Excessive_stack_depth_comparing_types_0_and_1_2321", "Excessive stack depth comparing types '{0}' and '{1}'."), + Type_0_is_not_assignable_to_type_1: diag(2322, ts.DiagnosticCategory.Error, "Type_0_is_not_assignable_to_type_1_2322", "Type '{0}' is not assignable to type '{1}'."), + Cannot_redeclare_exported_variable_0: diag(2323, ts.DiagnosticCategory.Error, "Cannot_redeclare_exported_variable_0_2323", "Cannot redeclare exported variable '{0}'."), + Property_0_is_missing_in_type_1: diag(2324, ts.DiagnosticCategory.Error, "Property_0_is_missing_in_type_1_2324", "Property '{0}' is missing in type '{1}'."), + Property_0_is_private_in_type_1_but_not_in_type_2: diag(2325, ts.DiagnosticCategory.Error, "Property_0_is_private_in_type_1_but_not_in_type_2_2325", "Property '{0}' is private in type '{1}' but not in type '{2}'."), + Types_of_property_0_are_incompatible: diag(2326, ts.DiagnosticCategory.Error, "Types_of_property_0_are_incompatible_2326", "Types of property '{0}' are incompatible."), + Property_0_is_optional_in_type_1_but_required_in_type_2: diag(2327, ts.DiagnosticCategory.Error, "Property_0_is_optional_in_type_1_but_required_in_type_2_2327", "Property '{0}' is optional in type '{1}' but required in type '{2}'."), + Types_of_parameters_0_and_1_are_incompatible: diag(2328, ts.DiagnosticCategory.Error, "Types_of_parameters_0_and_1_are_incompatible_2328", "Types of parameters '{0}' and '{1}' are incompatible."), + Index_signature_is_missing_in_type_0: diag(2329, ts.DiagnosticCategory.Error, "Index_signature_is_missing_in_type_0_2329", "Index signature is missing in type '{0}'."), + Index_signatures_are_incompatible: diag(2330, ts.DiagnosticCategory.Error, "Index_signatures_are_incompatible_2330", "Index signatures are incompatible."), + this_cannot_be_referenced_in_a_module_or_namespace_body: diag(2331, ts.DiagnosticCategory.Error, "this_cannot_be_referenced_in_a_module_or_namespace_body_2331", "'this' cannot be referenced in a module or namespace body."), + this_cannot_be_referenced_in_current_location: diag(2332, ts.DiagnosticCategory.Error, "this_cannot_be_referenced_in_current_location_2332", "'this' cannot be referenced in current location."), + this_cannot_be_referenced_in_constructor_arguments: diag(2333, ts.DiagnosticCategory.Error, "this_cannot_be_referenced_in_constructor_arguments_2333", "'this' cannot be referenced in constructor arguments."), + this_cannot_be_referenced_in_a_static_property_initializer: diag(2334, ts.DiagnosticCategory.Error, "this_cannot_be_referenced_in_a_static_property_initializer_2334", "'this' cannot be referenced in a static property initializer."), + super_can_only_be_referenced_in_a_derived_class: diag(2335, ts.DiagnosticCategory.Error, "super_can_only_be_referenced_in_a_derived_class_2335", "'super' can only be referenced in a derived class."), + super_cannot_be_referenced_in_constructor_arguments: diag(2336, ts.DiagnosticCategory.Error, "super_cannot_be_referenced_in_constructor_arguments_2336", "'super' cannot be referenced in constructor arguments."), + Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors: diag(2337, ts.DiagnosticCategory.Error, "Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors_2337", "Super calls are not permitted outside constructors or in nested functions inside constructors."), + super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_derived_class: diag(2338, ts.DiagnosticCategory.Error, "super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_der_2338", "'super' property access is permitted only in a constructor, member function, or member accessor of a derived class."), + Property_0_does_not_exist_on_type_1: diag(2339, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_2339", "Property '{0}' does not exist on type '{1}'."), + Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword: diag(2340, ts.DiagnosticCategory.Error, "Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword_2340", "Only public and protected methods of the base class are accessible via the 'super' keyword."), + Property_0_is_private_and_only_accessible_within_class_1: diag(2341, ts.DiagnosticCategory.Error, "Property_0_is_private_and_only_accessible_within_class_1_2341", "Property '{0}' is private and only accessible within class '{1}'."), + An_index_expression_argument_must_be_of_type_string_number_symbol_or_any: diag(2342, ts.DiagnosticCategory.Error, "An_index_expression_argument_must_be_of_type_string_number_symbol_or_any_2342", "An index expression argument must be of type 'string', 'number', 'symbol', or 'any'."), + This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1: diag(2343, ts.DiagnosticCategory.Error, "This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1_2343", "This syntax requires an imported helper named '{1}', but module '{0}' has no exported member '{1}'."), + Type_0_does_not_satisfy_the_constraint_1: diag(2344, ts.DiagnosticCategory.Error, "Type_0_does_not_satisfy_the_constraint_1_2344", "Type '{0}' does not satisfy the constraint '{1}'."), + Argument_of_type_0_is_not_assignable_to_parameter_of_type_1: diag(2345, ts.DiagnosticCategory.Error, "Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_2345", "Argument of type '{0}' is not assignable to parameter of type '{1}'."), + Call_target_does_not_contain_any_signatures: diag(2346, ts.DiagnosticCategory.Error, "Call_target_does_not_contain_any_signatures_2346", "Call target does not contain any signatures."), + Untyped_function_calls_may_not_accept_type_arguments: diag(2347, ts.DiagnosticCategory.Error, "Untyped_function_calls_may_not_accept_type_arguments_2347", "Untyped function calls may not accept type arguments."), + Value_of_type_0_is_not_callable_Did_you_mean_to_include_new: diag(2348, ts.DiagnosticCategory.Error, "Value_of_type_0_is_not_callable_Did_you_mean_to_include_new_2348", "Value of type '{0}' is not callable. Did you mean to include 'new'?"), + Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures: diag(2349, ts.DiagnosticCategory.Error, "Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatur_2349", "Cannot invoke an expression whose type lacks a call signature. Type '{0}' has no compatible call signatures."), + Only_a_void_function_can_be_called_with_the_new_keyword: diag(2350, ts.DiagnosticCategory.Error, "Only_a_void_function_can_be_called_with_the_new_keyword_2350", "Only a void function can be called with the 'new' keyword."), + Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature: diag(2351, ts.DiagnosticCategory.Error, "Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature_2351", "Cannot use 'new' with an expression whose type lacks a call or construct signature."), + Conversion_of_type_0_to_type_1_may_be_a_mistake_because_neither_type_sufficiently_overlaps_with_the_other_If_this_was_intentional_convert_the_expression_to_unknown_first: diag(2352, ts.DiagnosticCategory.Error, "Conversion_of_type_0_to_type_1_may_be_a_mistake_because_neither_type_sufficiently_overlaps_with_the__2352", "Conversion of type '{0}' to type '{1}' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first."), + Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1: diag(2353, ts.DiagnosticCategory.Error, "Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1_2353", "Object literal may only specify known properties, and '{0}' does not exist in type '{1}'."), + This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found: diag(2354, ts.DiagnosticCategory.Error, "This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found_2354", "This syntax requires an imported helper but module '{0}' cannot be found."), + A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value: diag(2355, ts.DiagnosticCategory.Error, "A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value_2355", "A function whose declared type is neither 'void' nor 'any' must return a value."), + An_arithmetic_operand_must_be_of_type_any_number_bigint_or_an_enum_type: diag(2356, ts.DiagnosticCategory.Error, "An_arithmetic_operand_must_be_of_type_any_number_bigint_or_an_enum_type_2356", "An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type."), + The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access: diag(2357, ts.DiagnosticCategory.Error, "The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access_2357", "The operand of an increment or decrement operator must be a variable or a property access."), + The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter: diag(2358, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_paramete_2358", "The left-hand side of an 'instanceof' expression must be of type 'any', an object type or a type parameter."), + The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_Function_interface_type: diag(2359, ts.DiagnosticCategory.Error, "The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_F_2359", "The right-hand side of an 'instanceof' expression must be of type 'any' or of a type assignable to the 'Function' interface type."), + The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol: diag(2360, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol_2360", "The left-hand side of an 'in' expression must be of type 'any', 'string', 'number', or 'symbol'."), + The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter: diag(2361, ts.DiagnosticCategory.Error, "The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter_2361", "The right-hand side of an 'in' expression must be of type 'any', an object type or a type parameter."), + The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type: diag(2362, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type_2362", "The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type."), + The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type: diag(2363, ts.DiagnosticCategory.Error, "The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type_2363", "The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type."), + The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access: diag(2364, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access_2364", "The left-hand side of an assignment expression must be a variable or a property access."), + Operator_0_cannot_be_applied_to_types_1_and_2: diag(2365, ts.DiagnosticCategory.Error, "Operator_0_cannot_be_applied_to_types_1_and_2_2365", "Operator '{0}' cannot be applied to types '{1}' and '{2}'."), + Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined: diag(2366, ts.DiagnosticCategory.Error, "Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined_2366", "Function lacks ending return statement and return type does not include 'undefined'."), + This_condition_will_always_return_0_since_the_types_1_and_2_have_no_overlap: diag(2367, ts.DiagnosticCategory.Error, "This_condition_will_always_return_0_since_the_types_1_and_2_have_no_overlap_2367", "This condition will always return '{0}' since the types '{1}' and '{2}' have no overlap."), + Type_parameter_name_cannot_be_0: diag(2368, ts.DiagnosticCategory.Error, "Type_parameter_name_cannot_be_0_2368", "Type parameter name cannot be '{0}'."), + A_parameter_property_is_only_allowed_in_a_constructor_implementation: diag(2369, ts.DiagnosticCategory.Error, "A_parameter_property_is_only_allowed_in_a_constructor_implementation_2369", "A parameter property is only allowed in a constructor implementation."), + A_rest_parameter_must_be_of_an_array_type: diag(2370, ts.DiagnosticCategory.Error, "A_rest_parameter_must_be_of_an_array_type_2370", "A rest parameter must be of an array type."), + A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation: diag(2371, ts.DiagnosticCategory.Error, "A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation_2371", "A parameter initializer is only allowed in a function or constructor implementation."), + Parameter_0_cannot_be_referenced_in_its_initializer: diag(2372, ts.DiagnosticCategory.Error, "Parameter_0_cannot_be_referenced_in_its_initializer_2372", "Parameter '{0}' cannot be referenced in its initializer."), + Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it: diag(2373, ts.DiagnosticCategory.Error, "Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it_2373", "Initializer of parameter '{0}' cannot reference identifier '{1}' declared after it."), + Duplicate_string_index_signature: diag(2374, ts.DiagnosticCategory.Error, "Duplicate_string_index_signature_2374", "Duplicate string index signature."), + Duplicate_number_index_signature: diag(2375, ts.DiagnosticCategory.Error, "Duplicate_number_index_signature_2375", "Duplicate number index signature."), + A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_properties_or_has_parameter_properties: diag(2376, ts.DiagnosticCategory.Error, "A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_proper_2376", "A 'super' call must be the first statement in the constructor when a class contains initialized properties or has parameter properties."), + Constructors_for_derived_classes_must_contain_a_super_call: diag(2377, ts.DiagnosticCategory.Error, "Constructors_for_derived_classes_must_contain_a_super_call_2377", "Constructors for derived classes must contain a 'super' call."), + A_get_accessor_must_return_a_value: diag(2378, ts.DiagnosticCategory.Error, "A_get_accessor_must_return_a_value_2378", "A 'get' accessor must return a value."), + Getter_and_setter_accessors_do_not_agree_in_visibility: diag(2379, ts.DiagnosticCategory.Error, "Getter_and_setter_accessors_do_not_agree_in_visibility_2379", "Getter and setter accessors do not agree in visibility."), + get_and_set_accessor_must_have_the_same_type: diag(2380, ts.DiagnosticCategory.Error, "get_and_set_accessor_must_have_the_same_type_2380", "'get' and 'set' accessor must have the same type."), + A_signature_with_an_implementation_cannot_use_a_string_literal_type: diag(2381, ts.DiagnosticCategory.Error, "A_signature_with_an_implementation_cannot_use_a_string_literal_type_2381", "A signature with an implementation cannot use a string literal type."), + Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature: diag(2382, ts.DiagnosticCategory.Error, "Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature_2382", "Specialized overload signature is not assignable to any non-specialized signature."), + Overload_signatures_must_all_be_exported_or_non_exported: diag(2383, ts.DiagnosticCategory.Error, "Overload_signatures_must_all_be_exported_or_non_exported_2383", "Overload signatures must all be exported or non-exported."), + Overload_signatures_must_all_be_ambient_or_non_ambient: diag(2384, ts.DiagnosticCategory.Error, "Overload_signatures_must_all_be_ambient_or_non_ambient_2384", "Overload signatures must all be ambient or non-ambient."), + Overload_signatures_must_all_be_public_private_or_protected: diag(2385, ts.DiagnosticCategory.Error, "Overload_signatures_must_all_be_public_private_or_protected_2385", "Overload signatures must all be public, private or protected."), + Overload_signatures_must_all_be_optional_or_required: diag(2386, ts.DiagnosticCategory.Error, "Overload_signatures_must_all_be_optional_or_required_2386", "Overload signatures must all be optional or required."), + Function_overload_must_be_static: diag(2387, ts.DiagnosticCategory.Error, "Function_overload_must_be_static_2387", "Function overload must be static."), + Function_overload_must_not_be_static: diag(2388, ts.DiagnosticCategory.Error, "Function_overload_must_not_be_static_2388", "Function overload must not be static."), + Function_implementation_name_must_be_0: diag(2389, ts.DiagnosticCategory.Error, "Function_implementation_name_must_be_0_2389", "Function implementation name must be '{0}'."), + Constructor_implementation_is_missing: diag(2390, ts.DiagnosticCategory.Error, "Constructor_implementation_is_missing_2390", "Constructor implementation is missing."), + Function_implementation_is_missing_or_not_immediately_following_the_declaration: diag(2391, ts.DiagnosticCategory.Error, "Function_implementation_is_missing_or_not_immediately_following_the_declaration_2391", "Function implementation is missing or not immediately following the declaration."), + Multiple_constructor_implementations_are_not_allowed: diag(2392, ts.DiagnosticCategory.Error, "Multiple_constructor_implementations_are_not_allowed_2392", "Multiple constructor implementations are not allowed."), + Duplicate_function_implementation: diag(2393, ts.DiagnosticCategory.Error, "Duplicate_function_implementation_2393", "Duplicate function implementation."), + Overload_signature_is_not_compatible_with_function_implementation: diag(2394, ts.DiagnosticCategory.Error, "Overload_signature_is_not_compatible_with_function_implementation_2394", "Overload signature is not compatible with function implementation."), + Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local: diag(2395, ts.DiagnosticCategory.Error, "Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local_2395", "Individual declarations in merged declaration '{0}' must be all exported or all local."), + Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters: diag(2396, ts.DiagnosticCategory.Error, "Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters_2396", "Duplicate identifier 'arguments'. Compiler uses 'arguments' to initialize rest parameters."), + Declaration_name_conflicts_with_built_in_global_identifier_0: diag(2397, ts.DiagnosticCategory.Error, "Declaration_name_conflicts_with_built_in_global_identifier_0_2397", "Declaration name conflicts with built-in global identifier '{0}'."), + Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference: diag(2399, ts.DiagnosticCategory.Error, "Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference_2399", "Duplicate identifier '_this'. Compiler uses variable declaration '_this' to capture 'this' reference."), + Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference: diag(2400, ts.DiagnosticCategory.Error, "Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference_2400", "Expression resolves to variable declaration '_this' that compiler uses to capture 'this' reference."), + Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference: diag(2401, ts.DiagnosticCategory.Error, "Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference_2401", "Duplicate identifier '_super'. Compiler uses '_super' to capture base class reference."), + Expression_resolves_to_super_that_compiler_uses_to_capture_base_class_reference: diag(2402, ts.DiagnosticCategory.Error, "Expression_resolves_to_super_that_compiler_uses_to_capture_base_class_reference_2402", "Expression resolves to '_super' that compiler uses to capture base class reference."), + Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2: diag(2403, ts.DiagnosticCategory.Error, "Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_t_2403", "Subsequent variable declarations must have the same type. Variable '{0}' must be of type '{1}', but here has type '{2}'."), + The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation: diag(2404, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation_2404", "The left-hand side of a 'for...in' statement cannot use a type annotation."), + The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any: diag(2405, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any_2405", "The left-hand side of a 'for...in' statement must be of type 'string' or 'any'."), + The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access: diag(2406, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access_2406", "The left-hand side of a 'for...in' statement must be a variable or a property access."), + The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_but_here_has_type_0: diag(2407, ts.DiagnosticCategory.Error, "The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_but_2407", "The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter, but here has type '{0}'."), + Setters_cannot_return_a_value: diag(2408, ts.DiagnosticCategory.Error, "Setters_cannot_return_a_value_2408", "Setters cannot return a value."), + Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class: diag(2409, ts.DiagnosticCategory.Error, "Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class_2409", "Return type of constructor signature must be assignable to the instance type of the class."), + The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any: diag(2410, ts.DiagnosticCategory.Error, "The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any_2410", "The 'with' statement is not supported. All symbols in a 'with' block will have type 'any'."), + Property_0_of_type_1_is_not_assignable_to_string_index_type_2: diag(2411, ts.DiagnosticCategory.Error, "Property_0_of_type_1_is_not_assignable_to_string_index_type_2_2411", "Property '{0}' of type '{1}' is not assignable to string index type '{2}'."), + Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2: diag(2412, ts.DiagnosticCategory.Error, "Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2_2412", "Property '{0}' of type '{1}' is not assignable to numeric index type '{2}'."), + Numeric_index_type_0_is_not_assignable_to_string_index_type_1: diag(2413, ts.DiagnosticCategory.Error, "Numeric_index_type_0_is_not_assignable_to_string_index_type_1_2413", "Numeric index type '{0}' is not assignable to string index type '{1}'."), + Class_name_cannot_be_0: diag(2414, ts.DiagnosticCategory.Error, "Class_name_cannot_be_0_2414", "Class name cannot be '{0}'."), + Class_0_incorrectly_extends_base_class_1: diag(2415, ts.DiagnosticCategory.Error, "Class_0_incorrectly_extends_base_class_1_2415", "Class '{0}' incorrectly extends base class '{1}'."), + Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2: diag(2416, ts.DiagnosticCategory.Error, "Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2_2416", "Property '{0}' in type '{1}' is not assignable to the same property in base type '{2}'."), + Class_static_side_0_incorrectly_extends_base_class_static_side_1: diag(2417, ts.DiagnosticCategory.Error, "Class_static_side_0_incorrectly_extends_base_class_static_side_1_2417", "Class static side '{0}' incorrectly extends base class static side '{1}'."), + Type_of_computed_property_s_value_is_0_which_is_not_assignable_to_type_1: diag(2418, ts.DiagnosticCategory.Error, "Type_of_computed_property_s_value_is_0_which_is_not_assignable_to_type_1_2418", "Type of computed property's value is '{0}', which is not assignable to type '{1}'."), + Class_0_incorrectly_implements_interface_1: diag(2420, ts.DiagnosticCategory.Error, "Class_0_incorrectly_implements_interface_1_2420", "Class '{0}' incorrectly implements interface '{1}'."), + A_class_can_only_implement_an_object_type_or_intersection_of_object_types_with_statically_known_members: diag(2422, ts.DiagnosticCategory.Error, "A_class_can_only_implement_an_object_type_or_intersection_of_object_types_with_statically_known_memb_2422", "A class can only implement an object type or intersection of object types with statically known members."), + Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor: diag(2423, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_access_2423", "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member accessor."), + Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_property: diag(2424, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_proper_2424", "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member property."), + Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_function: diag(2425, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_functi_2425", "Class '{0}' defines instance member property '{1}', but extended class '{2}' defines it as instance member function."), + Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function: diag(2426, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_functi_2426", "Class '{0}' defines instance member accessor '{1}', but extended class '{2}' defines it as instance member function."), + Interface_name_cannot_be_0: diag(2427, ts.DiagnosticCategory.Error, "Interface_name_cannot_be_0_2427", "Interface name cannot be '{0}'."), + All_declarations_of_0_must_have_identical_type_parameters: diag(2428, ts.DiagnosticCategory.Error, "All_declarations_of_0_must_have_identical_type_parameters_2428", "All declarations of '{0}' must have identical type parameters."), + Interface_0_incorrectly_extends_interface_1: diag(2430, ts.DiagnosticCategory.Error, "Interface_0_incorrectly_extends_interface_1_2430", "Interface '{0}' incorrectly extends interface '{1}'."), + Enum_name_cannot_be_0: diag(2431, ts.DiagnosticCategory.Error, "Enum_name_cannot_be_0_2431", "Enum name cannot be '{0}'."), + In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enum_element: diag(2432, ts.DiagnosticCategory.Error, "In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enu_2432", "In an enum with multiple declarations, only one declaration can omit an initializer for its first enum element."), + A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merged: diag(2433, ts.DiagnosticCategory.Error, "A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merg_2433", "A namespace declaration cannot be in a different file from a class or function with which it is merged."), + A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged: diag(2434, ts.DiagnosticCategory.Error, "A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged_2434", "A namespace declaration cannot be located prior to a class or function with which it is merged."), + Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces: diag(2435, ts.DiagnosticCategory.Error, "Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces_2435", "Ambient modules cannot be nested in other modules or namespaces."), + Ambient_module_declaration_cannot_specify_relative_module_name: diag(2436, ts.DiagnosticCategory.Error, "Ambient_module_declaration_cannot_specify_relative_module_name_2436", "Ambient module declaration cannot specify relative module name."), + Module_0_is_hidden_by_a_local_declaration_with_the_same_name: diag(2437, ts.DiagnosticCategory.Error, "Module_0_is_hidden_by_a_local_declaration_with_the_same_name_2437", "Module '{0}' is hidden by a local declaration with the same name."), + Import_name_cannot_be_0: diag(2438, ts.DiagnosticCategory.Error, "Import_name_cannot_be_0_2438", "Import name cannot be '{0}'."), + Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relative_module_name: diag(2439, ts.DiagnosticCategory.Error, "Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relati_2439", "Import or export declaration in an ambient module declaration cannot reference module through relative module name."), + Import_declaration_conflicts_with_local_declaration_of_0: diag(2440, ts.DiagnosticCategory.Error, "Import_declaration_conflicts_with_local_declaration_of_0_2440", "Import declaration conflicts with local declaration of '{0}'."), + Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module: diag(2441, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_2441", "Duplicate identifier '{0}'. Compiler reserves name '{1}' in top level scope of a module."), + Types_have_separate_declarations_of_a_private_property_0: diag(2442, ts.DiagnosticCategory.Error, "Types_have_separate_declarations_of_a_private_property_0_2442", "Types have separate declarations of a private property '{0}'."), + Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2: diag(2443, ts.DiagnosticCategory.Error, "Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2_2443", "Property '{0}' is protected but type '{1}' is not a class derived from '{2}'."), + Property_0_is_protected_in_type_1_but_public_in_type_2: diag(2444, ts.DiagnosticCategory.Error, "Property_0_is_protected_in_type_1_but_public_in_type_2_2444", "Property '{0}' is protected in type '{1}' but public in type '{2}'."), + Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses: diag(2445, ts.DiagnosticCategory.Error, "Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses_2445", "Property '{0}' is protected and only accessible within class '{1}' and its subclasses."), + Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1: diag(2446, ts.DiagnosticCategory.Error, "Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1_2446", "Property '{0}' is protected and only accessible through an instance of class '{1}'."), + The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead: diag(2447, ts.DiagnosticCategory.Error, "The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead_2447", "The '{0}' operator is not allowed for boolean types. Consider using '{1}' instead."), + Block_scoped_variable_0_used_before_its_declaration: diag(2448, ts.DiagnosticCategory.Error, "Block_scoped_variable_0_used_before_its_declaration_2448", "Block-scoped variable '{0}' used before its declaration."), + Class_0_used_before_its_declaration: diag(2449, ts.DiagnosticCategory.Error, "Class_0_used_before_its_declaration_2449", "Class '{0}' used before its declaration."), + Enum_0_used_before_its_declaration: diag(2450, ts.DiagnosticCategory.Error, "Enum_0_used_before_its_declaration_2450", "Enum '{0}' used before its declaration."), + Cannot_redeclare_block_scoped_variable_0: diag(2451, ts.DiagnosticCategory.Error, "Cannot_redeclare_block_scoped_variable_0_2451", "Cannot redeclare block-scoped variable '{0}'."), + An_enum_member_cannot_have_a_numeric_name: diag(2452, ts.DiagnosticCategory.Error, "An_enum_member_cannot_have_a_numeric_name_2452", "An enum member cannot have a numeric name."), + The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_type_arguments_explicitly: diag(2453, ts.DiagnosticCategory.Error, "The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_typ_2453", "The type argument for type parameter '{0}' cannot be inferred from the usage. Consider specifying the type arguments explicitly."), + Variable_0_is_used_before_being_assigned: diag(2454, ts.DiagnosticCategory.Error, "Variable_0_is_used_before_being_assigned_2454", "Variable '{0}' is used before being assigned."), + Type_argument_candidate_1_is_not_a_valid_type_argument_because_it_is_not_a_supertype_of_candidate_0: diag(2455, ts.DiagnosticCategory.Error, "Type_argument_candidate_1_is_not_a_valid_type_argument_because_it_is_not_a_supertype_of_candidate_0_2455", "Type argument candidate '{1}' is not a valid type argument because it is not a supertype of candidate '{0}'."), + Type_alias_0_circularly_references_itself: diag(2456, ts.DiagnosticCategory.Error, "Type_alias_0_circularly_references_itself_2456", "Type alias '{0}' circularly references itself."), + Type_alias_name_cannot_be_0: diag(2457, ts.DiagnosticCategory.Error, "Type_alias_name_cannot_be_0_2457", "Type alias name cannot be '{0}'."), + An_AMD_module_cannot_have_multiple_name_assignments: diag(2458, ts.DiagnosticCategory.Error, "An_AMD_module_cannot_have_multiple_name_assignments_2458", "An AMD module cannot have multiple name assignments."), + Type_0_has_no_property_1_and_no_string_index_signature: diag(2459, ts.DiagnosticCategory.Error, "Type_0_has_no_property_1_and_no_string_index_signature_2459", "Type '{0}' has no property '{1}' and no string index signature."), + Type_0_has_no_property_1: diag(2460, ts.DiagnosticCategory.Error, "Type_0_has_no_property_1_2460", "Type '{0}' has no property '{1}'."), + Type_0_is_not_an_array_type: diag(2461, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_2461", "Type '{0}' is not an array type."), + A_rest_element_must_be_last_in_a_destructuring_pattern: diag(2462, ts.DiagnosticCategory.Error, "A_rest_element_must_be_last_in_a_destructuring_pattern_2462", "A rest element must be last in a destructuring pattern."), + A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature: diag(2463, ts.DiagnosticCategory.Error, "A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature_2463", "A binding pattern parameter cannot be optional in an implementation signature."), + A_computed_property_name_must_be_of_type_string_number_symbol_or_any: diag(2464, ts.DiagnosticCategory.Error, "A_computed_property_name_must_be_of_type_string_number_symbol_or_any_2464", "A computed property name must be of type 'string', 'number', 'symbol', or 'any'."), + this_cannot_be_referenced_in_a_computed_property_name: diag(2465, ts.DiagnosticCategory.Error, "this_cannot_be_referenced_in_a_computed_property_name_2465", "'this' cannot be referenced in a computed property name."), + super_cannot_be_referenced_in_a_computed_property_name: diag(2466, ts.DiagnosticCategory.Error, "super_cannot_be_referenced_in_a_computed_property_name_2466", "'super' cannot be referenced in a computed property name."), + A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type: diag(2467, ts.DiagnosticCategory.Error, "A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type_2467", "A computed property name cannot reference a type parameter from its containing type."), + Cannot_find_global_value_0: diag(2468, ts.DiagnosticCategory.Error, "Cannot_find_global_value_0_2468", "Cannot find global value '{0}'."), + The_0_operator_cannot_be_applied_to_type_symbol: diag(2469, ts.DiagnosticCategory.Error, "The_0_operator_cannot_be_applied_to_type_symbol_2469", "The '{0}' operator cannot be applied to type 'symbol'."), + Symbol_reference_does_not_refer_to_the_global_Symbol_constructor_object: diag(2470, ts.DiagnosticCategory.Error, "Symbol_reference_does_not_refer_to_the_global_Symbol_constructor_object_2470", "'Symbol' reference does not refer to the global Symbol constructor object."), + A_computed_property_name_of_the_form_0_must_be_of_type_symbol: diag(2471, ts.DiagnosticCategory.Error, "A_computed_property_name_of_the_form_0_must_be_of_type_symbol_2471", "A computed property name of the form '{0}' must be of type 'symbol'."), + Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher: diag(2472, ts.DiagnosticCategory.Error, "Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher_2472", "Spread operator in 'new' expressions is only available when targeting ECMAScript 5 and higher."), + Enum_declarations_must_all_be_const_or_non_const: diag(2473, ts.DiagnosticCategory.Error, "Enum_declarations_must_all_be_const_or_non_const_2473", "Enum declarations must all be const or non-const."), + In_const_enum_declarations_member_initializer_must_be_constant_expression: diag(2474, ts.DiagnosticCategory.Error, "In_const_enum_declarations_member_initializer_must_be_constant_expression_2474", "In 'const' enum declarations member initializer must be constant expression."), + const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment_or_type_query: diag(2475, ts.DiagnosticCategory.Error, "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475", "'const' enums can only be used in property or index access expressions or the right hand side of an import declaration or export assignment or type query."), + A_const_enum_member_can_only_be_accessed_using_a_string_literal: diag(2476, ts.DiagnosticCategory.Error, "A_const_enum_member_can_only_be_accessed_using_a_string_literal_2476", "A const enum member can only be accessed using a string literal."), + const_enum_member_initializer_was_evaluated_to_a_non_finite_value: diag(2477, ts.DiagnosticCategory.Error, "const_enum_member_initializer_was_evaluated_to_a_non_finite_value_2477", "'const' enum member initializer was evaluated to a non-finite value."), + const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN: diag(2478, ts.DiagnosticCategory.Error, "const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN_2478", "'const' enum member initializer was evaluated to disallowed value 'NaN'."), + Property_0_does_not_exist_on_const_enum_1: diag(2479, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_const_enum_1_2479", "Property '{0}' does not exist on 'const' enum '{1}'."), + let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations: diag(2480, ts.DiagnosticCategory.Error, "let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations_2480", "'let' is not allowed to be used as a name in 'let' or 'const' declarations."), + Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1: diag(2481, ts.DiagnosticCategory.Error, "Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1_2481", "Cannot initialize outer scoped variable '{0}' in the same scope as block scoped declaration '{1}'."), + The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation: diag(2483, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation_2483", "The left-hand side of a 'for...of' statement cannot use a type annotation."), + Export_declaration_conflicts_with_exported_declaration_of_0: diag(2484, ts.DiagnosticCategory.Error, "Export_declaration_conflicts_with_exported_declaration_of_0_2484", "Export declaration conflicts with exported declaration of '{0}'."), + The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access: diag(2487, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access_2487", "The left-hand side of a 'for...of' statement must be a variable or a property access."), + Type_0_must_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2488, ts.DiagnosticCategory.Error, "Type_0_must_have_a_Symbol_iterator_method_that_returns_an_iterator_2488", "Type '{0}' must have a '[Symbol.iterator]()' method that returns an iterator."), + An_iterator_must_have_a_next_method: diag(2489, ts.DiagnosticCategory.Error, "An_iterator_must_have_a_next_method_2489", "An iterator must have a 'next()' method."), + The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property: diag(2490, ts.DiagnosticCategory.Error, "The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property_2490", "The type returned by the 'next()' method of an iterator must have a 'value' property."), + The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern: diag(2491, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern_2491", "The left-hand side of a 'for...in' statement cannot be a destructuring pattern."), + Cannot_redeclare_identifier_0_in_catch_clause: diag(2492, ts.DiagnosticCategory.Error, "Cannot_redeclare_identifier_0_in_catch_clause_2492", "Cannot redeclare identifier '{0}' in catch clause."), + Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2: diag(2493, ts.DiagnosticCategory.Error, "Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2_2493", "Tuple type '{0}' with length '{1}' cannot be assigned to tuple with length '{2}'."), + Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher: diag(2494, ts.DiagnosticCategory.Error, "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494", "Using a string in a 'for...of' statement is only supported in ECMAScript 5 and higher."), + Type_0_is_not_an_array_type_or_a_string_type: diag(2495, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_a_string_type_2495", "Type '{0}' is not an array type or a string type."), + The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_standard_function_expression: diag(2496, ts.DiagnosticCategory.Error, "The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_stand_2496", "The 'arguments' object cannot be referenced in an arrow function in ES3 and ES5. Consider using a standard function expression."), + Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct: diag(2497, ts.DiagnosticCategory.Error, "Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct_2497", "Module '{0}' resolves to a non-module entity and cannot be imported using this construct."), + Module_0_uses_export_and_cannot_be_used_with_export_Asterisk: diag(2498, ts.DiagnosticCategory.Error, "Module_0_uses_export_and_cannot_be_used_with_export_Asterisk_2498", "Module '{0}' uses 'export =' and cannot be used with 'export *'."), + An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments: diag(2499, ts.DiagnosticCategory.Error, "An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments_2499", "An interface can only extend an identifier/qualified-name with optional type arguments."), + A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments: diag(2500, ts.DiagnosticCategory.Error, "A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments_2500", "A class can only implement an identifier/qualified-name with optional type arguments."), + A_rest_element_cannot_contain_a_binding_pattern: diag(2501, ts.DiagnosticCategory.Error, "A_rest_element_cannot_contain_a_binding_pattern_2501", "A rest element cannot contain a binding pattern."), + _0_is_referenced_directly_or_indirectly_in_its_own_type_annotation: diag(2502, ts.DiagnosticCategory.Error, "_0_is_referenced_directly_or_indirectly_in_its_own_type_annotation_2502", "'{0}' is referenced directly or indirectly in its own type annotation."), + Cannot_find_namespace_0: diag(2503, ts.DiagnosticCategory.Error, "Cannot_find_namespace_0_2503", "Cannot find namespace '{0}'."), + Type_0_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator: diag(2504, ts.DiagnosticCategory.Error, "Type_0_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator_2504", "Type '{0}' must have a '[Symbol.asyncIterator]()' method that returns an async iterator."), + A_generator_cannot_have_a_void_type_annotation: diag(2505, ts.DiagnosticCategory.Error, "A_generator_cannot_have_a_void_type_annotation_2505", "A generator cannot have a 'void' type annotation."), + _0_is_referenced_directly_or_indirectly_in_its_own_base_expression: diag(2506, ts.DiagnosticCategory.Error, "_0_is_referenced_directly_or_indirectly_in_its_own_base_expression_2506", "'{0}' is referenced directly or indirectly in its own base expression."), + Type_0_is_not_a_constructor_function_type: diag(2507, ts.DiagnosticCategory.Error, "Type_0_is_not_a_constructor_function_type_2507", "Type '{0}' is not a constructor function type."), + No_base_constructor_has_the_specified_number_of_type_arguments: diag(2508, ts.DiagnosticCategory.Error, "No_base_constructor_has_the_specified_number_of_type_arguments_2508", "No base constructor has the specified number of type arguments."), + Base_constructor_return_type_0_is_not_an_object_type_or_intersection_of_object_types_with_statically_known_members: diag(2509, ts.DiagnosticCategory.Error, "Base_constructor_return_type_0_is_not_an_object_type_or_intersection_of_object_types_with_statically_2509", "Base constructor return type '{0}' is not an object type or intersection of object types with statically known members."), + Base_constructors_must_all_have_the_same_return_type: diag(2510, ts.DiagnosticCategory.Error, "Base_constructors_must_all_have_the_same_return_type_2510", "Base constructors must all have the same return type."), + Cannot_create_an_instance_of_an_abstract_class: diag(2511, ts.DiagnosticCategory.Error, "Cannot_create_an_instance_of_an_abstract_class_2511", "Cannot create an instance of an abstract class."), + Overload_signatures_must_all_be_abstract_or_non_abstract: diag(2512, ts.DiagnosticCategory.Error, "Overload_signatures_must_all_be_abstract_or_non_abstract_2512", "Overload signatures must all be abstract or non-abstract."), + Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression: diag(2513, ts.DiagnosticCategory.Error, "Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression_2513", "Abstract method '{0}' in class '{1}' cannot be accessed via super expression."), + Classes_containing_abstract_methods_must_be_marked_abstract: diag(2514, ts.DiagnosticCategory.Error, "Classes_containing_abstract_methods_must_be_marked_abstract_2514", "Classes containing abstract methods must be marked abstract."), + Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2: diag(2515, ts.DiagnosticCategory.Error, "Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2_2515", "Non-abstract class '{0}' does not implement inherited abstract member '{1}' from class '{2}'."), + All_declarations_of_an_abstract_method_must_be_consecutive: diag(2516, ts.DiagnosticCategory.Error, "All_declarations_of_an_abstract_method_must_be_consecutive_2516", "All declarations of an abstract method must be consecutive."), + Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type: diag(2517, ts.DiagnosticCategory.Error, "Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type_2517", "Cannot assign an abstract constructor type to a non-abstract constructor type."), + A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard: diag(2518, ts.DiagnosticCategory.Error, "A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard_2518", "A 'this'-based type guard is not compatible with a parameter-based type guard."), + An_async_iterator_must_have_a_next_method: diag(2519, ts.DiagnosticCategory.Error, "An_async_iterator_must_have_a_next_method_2519", "An async iterator must have a 'next()' method."), + Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions: diag(2520, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions_2520", "Duplicate identifier '{0}'. Compiler uses declaration '{1}' to support async functions."), + Expression_resolves_to_variable_declaration_0_that_compiler_uses_to_support_async_functions: diag(2521, ts.DiagnosticCategory.Error, "Expression_resolves_to_variable_declaration_0_that_compiler_uses_to_support_async_functions_2521", "Expression resolves to variable declaration '{0}' that compiler uses to support async functions."), + The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_using_a_standard_function_or_method: diag(2522, ts.DiagnosticCategory.Error, "The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_usi_2522", "The 'arguments' object cannot be referenced in an async function or method in ES3 and ES5. Consider using a standard function or method."), + yield_expressions_cannot_be_used_in_a_parameter_initializer: diag(2523, ts.DiagnosticCategory.Error, "yield_expressions_cannot_be_used_in_a_parameter_initializer_2523", "'yield' expressions cannot be used in a parameter initializer."), + await_expressions_cannot_be_used_in_a_parameter_initializer: diag(2524, ts.DiagnosticCategory.Error, "await_expressions_cannot_be_used_in_a_parameter_initializer_2524", "'await' expressions cannot be used in a parameter initializer."), + Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value: diag(2525, ts.DiagnosticCategory.Error, "Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value_2525", "Initializer provides no value for this binding element and the binding element has no default value."), + A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface: diag(2526, ts.DiagnosticCategory.Error, "A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface_2526", "A 'this' type is available only in a non-static member of a class or interface."), + The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary: diag(2527, ts.DiagnosticCategory.Error, "The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary_2527", "The inferred type of '{0}' references an inaccessible '{1}' type. A type annotation is necessary."), + A_module_cannot_have_multiple_default_exports: diag(2528, ts.DiagnosticCategory.Error, "A_module_cannot_have_multiple_default_exports_2528", "A module cannot have multiple default exports."), + Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_functions: diag(2529, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_func_2529", "Duplicate identifier '{0}'. Compiler reserves name '{1}' in top level scope of a module containing async functions."), + Property_0_is_incompatible_with_index_signature: diag(2530, ts.DiagnosticCategory.Error, "Property_0_is_incompatible_with_index_signature_2530", "Property '{0}' is incompatible with index signature."), + Object_is_possibly_null: diag(2531, ts.DiagnosticCategory.Error, "Object_is_possibly_null_2531", "Object is possibly 'null'."), + Object_is_possibly_undefined: diag(2532, ts.DiagnosticCategory.Error, "Object_is_possibly_undefined_2532", "Object is possibly 'undefined'."), + Object_is_possibly_null_or_undefined: diag(2533, ts.DiagnosticCategory.Error, "Object_is_possibly_null_or_undefined_2533", "Object is possibly 'null' or 'undefined'."), + A_function_returning_never_cannot_have_a_reachable_end_point: diag(2534, ts.DiagnosticCategory.Error, "A_function_returning_never_cannot_have_a_reachable_end_point_2534", "A function returning 'never' cannot have a reachable end point."), + Enum_type_0_has_members_with_initializers_that_are_not_literals: diag(2535, ts.DiagnosticCategory.Error, "Enum_type_0_has_members_with_initializers_that_are_not_literals_2535", "Enum type '{0}' has members with initializers that are not literals."), + Type_0_cannot_be_used_to_index_type_1: diag(2536, ts.DiagnosticCategory.Error, "Type_0_cannot_be_used_to_index_type_1_2536", "Type '{0}' cannot be used to index type '{1}'."), + Type_0_has_no_matching_index_signature_for_type_1: diag(2537, ts.DiagnosticCategory.Error, "Type_0_has_no_matching_index_signature_for_type_1_2537", "Type '{0}' has no matching index signature for type '{1}'."), + Type_0_cannot_be_used_as_an_index_type: diag(2538, ts.DiagnosticCategory.Error, "Type_0_cannot_be_used_as_an_index_type_2538", "Type '{0}' cannot be used as an index type."), + Cannot_assign_to_0_because_it_is_not_a_variable: diag(2539, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_not_a_variable_2539", "Cannot assign to '{0}' because it is not a variable."), + Cannot_assign_to_0_because_it_is_a_read_only_property: diag(2540, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_a_read_only_property_2540", "Cannot assign to '{0}' because it is a read-only property."), + The_target_of_an_assignment_must_be_a_variable_or_a_property_access: diag(2541, ts.DiagnosticCategory.Error, "The_target_of_an_assignment_must_be_a_variable_or_a_property_access_2541", "The target of an assignment must be a variable or a property access."), + Index_signature_in_type_0_only_permits_reading: diag(2542, ts.DiagnosticCategory.Error, "Index_signature_in_type_0_only_permits_reading_2542", "Index signature in type '{0}' only permits reading."), + Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference: diag(2543, ts.DiagnosticCategory.Error, "Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_me_2543", "Duplicate identifier '_newTarget'. Compiler uses variable declaration '_newTarget' to capture 'new.target' meta-property reference."), + Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta_property_reference: diag(2544, ts.DiagnosticCategory.Error, "Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta__2544", "Expression resolves to variable declaration '_newTarget' that compiler uses to capture 'new.target' meta-property reference."), + A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any: diag(2545, ts.DiagnosticCategory.Error, "A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any_2545", "A mixin class must have a constructor with a single rest parameter of type 'any[]'."), + Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1: diag(2546, ts.DiagnosticCategory.Error, "Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1_2546", "Property '{0}' has conflicting declarations and is inaccessible in type '{1}'."), + The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property: diag(2547, ts.DiagnosticCategory.Error, "The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value__2547", "The type returned by the 'next()' method of an async iterator must be a promise for a type with a 'value' property."), + Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2548, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548", "Type '{0}' is not an array type or does not have a '[Symbol.iterator]()' method that returns an iterator."), + Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2549, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549", "Type '{0}' is not an array type or a string type or does not have a '[Symbol.iterator]()' method that returns an iterator."), + Property_0_does_not_exist_on_type_1_Did_you_mean_2: diag(2551, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551", "Property '{0}' does not exist on type '{1}'. Did you mean '{2}'?"), + Cannot_find_name_0_Did_you_mean_1: diag(2552, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Did_you_mean_1_2552", "Cannot find name '{0}'. Did you mean '{1}'?"), + Computed_values_are_not_permitted_in_an_enum_with_string_valued_members: diag(2553, ts.DiagnosticCategory.Error, "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553", "Computed values are not permitted in an enum with string valued members."), + Expected_0_arguments_but_got_1: diag(2554, ts.DiagnosticCategory.Error, "Expected_0_arguments_but_got_1_2554", "Expected {0} arguments, but got {1}."), + Expected_at_least_0_arguments_but_got_1: diag(2555, ts.DiagnosticCategory.Error, "Expected_at_least_0_arguments_but_got_1_2555", "Expected at least {0} arguments, but got {1}."), + Expected_0_arguments_but_got_1_or_more: diag(2556, ts.DiagnosticCategory.Error, "Expected_0_arguments_but_got_1_or_more_2556", "Expected {0} arguments, but got {1} or more."), + Expected_at_least_0_arguments_but_got_1_or_more: diag(2557, ts.DiagnosticCategory.Error, "Expected_at_least_0_arguments_but_got_1_or_more_2557", "Expected at least {0} arguments, but got {1} or more."), + Expected_0_type_arguments_but_got_1: diag(2558, ts.DiagnosticCategory.Error, "Expected_0_type_arguments_but_got_1_2558", "Expected {0} type arguments, but got {1}."), + Type_0_has_no_properties_in_common_with_type_1: diag(2559, ts.DiagnosticCategory.Error, "Type_0_has_no_properties_in_common_with_type_1_2559", "Type '{0}' has no properties in common with type '{1}'."), + Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it: diag(2560, ts.DiagnosticCategory.Error, "Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it_2560", "Value of type '{0}' has no properties in common with type '{1}'. Did you mean to call it?"), + Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_write_2: diag(2561, ts.DiagnosticCategory.Error, "Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_writ_2561", "Object literal may only specify known properties, but '{0}' does not exist in type '{1}'. Did you mean to write '{2}'?"), + Base_class_expressions_cannot_reference_class_type_parameters: diag(2562, ts.DiagnosticCategory.Error, "Base_class_expressions_cannot_reference_class_type_parameters_2562", "Base class expressions cannot reference class type parameters."), + The_containing_function_or_module_body_is_too_large_for_control_flow_analysis: diag(2563, ts.DiagnosticCategory.Error, "The_containing_function_or_module_body_is_too_large_for_control_flow_analysis_2563", "The containing function or module body is too large for control flow analysis."), + Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor: diag(2564, ts.DiagnosticCategory.Error, "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor_2564", "Property '{0}' has no initializer and is not definitely assigned in the constructor."), + Property_0_is_used_before_being_assigned: diag(2565, ts.DiagnosticCategory.Error, "Property_0_is_used_before_being_assigned_2565", "Property '{0}' is used before being assigned."), + A_rest_element_cannot_have_a_property_name: diag(2566, ts.DiagnosticCategory.Error, "A_rest_element_cannot_have_a_property_name_2566", "A rest element cannot have a property name."), + Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations: diag(2567, ts.DiagnosticCategory.Error, "Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations_2567", "Enum declarations can only merge with namespace or other enum declarations."), + Type_0_is_not_an_array_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators: diag(2568, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators_2568", "Type '{0}' is not an array type. Use compiler option '--downlevelIteration' to allow iterating of iterators."), + Type_0_is_not_an_array_type_or_a_string_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators: diag(2569, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_a_string_type_Use_compiler_option_downlevelIteration_to_allow_iterati_2569", "Type '{0}' is not an array type or a string type. Use compiler option '--downlevelIteration' to allow iterating of iterators."), + Property_0_does_not_exist_on_type_1_Did_you_forget_to_use_await: diag(2570, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_Did_you_forget_to_use_await_2570", "Property '{0}' does not exist on type '{1}'. Did you forget to use 'await'?"), + Object_is_of_type_unknown: diag(2571, ts.DiagnosticCategory.Error, "Object_is_of_type_unknown_2571", "Object is of type 'unknown'."), + Rest_signatures_are_incompatible: diag(2572, ts.DiagnosticCategory.Error, "Rest_signatures_are_incompatible_2572", "Rest signatures are incompatible."), + Property_0_is_incompatible_with_rest_element_type: diag(2573, ts.DiagnosticCategory.Error, "Property_0_is_incompatible_with_rest_element_type_2573", "Property '{0}' is incompatible with rest element type."), + A_rest_element_type_must_be_an_array_type: diag(2574, ts.DiagnosticCategory.Error, "A_rest_element_type_must_be_an_array_type_2574", "A rest element type must be an array type."), + No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments: diag(2575, ts.DiagnosticCategory.Error, "No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments_2575", "No overload expects {0} arguments, but overloads do exist that expect either {1} or {2} arguments."), + Property_0_is_a_static_member_of_type_1: diag(2576, ts.DiagnosticCategory.Error, "Property_0_is_a_static_member_of_type_1_2576", "Property '{0}' is a static member of type '{1}'"), + Return_type_annotation_circularly_references_itself: diag(2577, ts.DiagnosticCategory.Error, "Return_type_annotation_circularly_references_itself_2577", "Return type annotation circularly references itself."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_and_then_add_node_to_the_types_field_in_your_tsconfig: diag(2580, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_and_th_2580", "Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i @types/node` and then add `node` to the types field in your tsconfig."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_and_then_add_jquery_to_the_types_field_in_your_tsconfig: diag(2581, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_an_2581", "Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i @types/jquery` and then add `jquery` to the types field in your tsconfig."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha_and_then_add_jest_or_mocha_to_the_types_field_in_your_tsconfig: diag(2582, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashje_2582", "Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha` and then add `jest` or `mocha` to the types field in your tsconfig."), + Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later: diag(2583, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2583", "Cannot find name '{0}'. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later."), + Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom: diag(2584, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2584", "Cannot find name '{0}'. Do you need to change your target library? Try changing the `lib` compiler option to include 'dom'."), + _0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later: diag(2585, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_2585", "'{0}' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later."), + Enum_type_0_circularly_references_itself: diag(2586, ts.DiagnosticCategory.Error, "Enum_type_0_circularly_references_itself_2586", "Enum type '{0}' circularly references itself."), + JSDoc_type_0_circularly_references_itself: diag(2587, ts.DiagnosticCategory.Error, "JSDoc_type_0_circularly_references_itself_2587", "JSDoc type '{0}' circularly references itself."), + Cannot_assign_to_0_because_it_is_a_constant: diag(2588, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_a_constant_2588", "Cannot assign to '{0}' because it is a constant."), + JSX_element_attributes_type_0_may_not_be_a_union_type: diag(2600, ts.DiagnosticCategory.Error, "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", "JSX element attributes type '{0}' may not be a union type."), + The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: diag(2601, ts.DiagnosticCategory.Error, "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", "The return type of a JSX element constructor must return an object type."), + JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: diag(2602, ts.DiagnosticCategory.Error, "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist."), + Property_0_in_type_1_is_not_assignable_to_type_2: diag(2603, ts.DiagnosticCategory.Error, "Property_0_in_type_1_is_not_assignable_to_type_2_2603", "Property '{0}' in type '{1}' is not assignable to type '{2}'."), + JSX_element_type_0_does_not_have_any_construct_or_call_signatures: diag(2604, ts.DiagnosticCategory.Error, "JSX_element_type_0_does_not_have_any_construct_or_call_signatures_2604", "JSX element type '{0}' does not have any construct or call signatures."), + JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements: diag(2605, ts.DiagnosticCategory.Error, "JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements_2605", "JSX element type '{0}' is not a constructor function for JSX elements."), + Property_0_of_JSX_spread_attribute_is_not_assignable_to_target_property: diag(2606, ts.DiagnosticCategory.Error, "Property_0_of_JSX_spread_attribute_is_not_assignable_to_target_property_2606", "Property '{0}' of JSX spread attribute is not assignable to target property."), + JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property: diag(2607, ts.DiagnosticCategory.Error, "JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property_2607", "JSX element class does not support attributes because it does not have a '{0}' property."), + The_global_type_JSX_0_may_not_have_more_than_one_property: diag(2608, ts.DiagnosticCategory.Error, "The_global_type_JSX_0_may_not_have_more_than_one_property_2608", "The global type 'JSX.{0}' may not have more than one property."), + JSX_spread_child_must_be_an_array_type: diag(2609, ts.DiagnosticCategory.Error, "JSX_spread_child_must_be_an_array_type_2609", "JSX spread child must be an array type."), + Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity: diag(2649, ts.DiagnosticCategory.Error, "Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity_2649", "Cannot augment module '{0}' with value exports because it resolves to a non-module entity."), + A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums: diag(2651, ts.DiagnosticCategory.Error, "A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_memb_2651", "A member initializer in a enum declaration cannot reference members declared after it, including members defined in other enums."), + Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead: diag(2652, ts.DiagnosticCategory.Error, "Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_d_2652", "Merged declaration '{0}' cannot include a default export declaration. Consider adding a separate 'export default {0}' declaration instead."), + Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1: diag(2653, ts.DiagnosticCategory.Error, "Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1_2653", "Non-abstract class expression does not implement inherited abstract member '{0}' from class '{1}'."), + Exported_external_package_typings_file_cannot_contain_tripleslash_references_Please_contact_the_package_author_to_update_the_package_definition: diag(2654, ts.DiagnosticCategory.Error, "Exported_external_package_typings_file_cannot_contain_tripleslash_references_Please_contact_the_pack_2654", "Exported external package typings file cannot contain tripleslash references. Please contact the package author to update the package definition."), + Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_the_package_definition: diag(2656, ts.DiagnosticCategory.Error, "Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_2656", "Exported external package typings file '{0}' is not a module. Please contact the package author to update the package definition."), + JSX_expressions_must_have_one_parent_element: diag(2657, ts.DiagnosticCategory.Error, "JSX_expressions_must_have_one_parent_element_2657", "JSX expressions must have one parent element."), + Type_0_provides_no_match_for_the_signature_1: diag(2658, ts.DiagnosticCategory.Error, "Type_0_provides_no_match_for_the_signature_1_2658", "Type '{0}' provides no match for the signature '{1}'."), + super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_higher: diag(2659, ts.DiagnosticCategory.Error, "super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_highe_2659", "'super' is only allowed in members of object literal expressions when option 'target' is 'ES2015' or higher."), + super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions: diag(2660, ts.DiagnosticCategory.Error, "super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions_2660", "'super' can only be referenced in members of derived classes or object literal expressions."), + Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module: diag(2661, ts.DiagnosticCategory.Error, "Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module_2661", "Cannot export '{0}'. Only local declarations can be exported from a module."), + Cannot_find_name_0_Did_you_mean_the_static_member_1_0: diag(2662, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Did_you_mean_the_static_member_1_0_2662", "Cannot find name '{0}'. Did you mean the static member '{1}.{0}'?"), + Cannot_find_name_0_Did_you_mean_the_instance_member_this_0: diag(2663, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Did_you_mean_the_instance_member_this_0_2663", "Cannot find name '{0}'. Did you mean the instance member 'this.{0}'?"), + Invalid_module_name_in_augmentation_module_0_cannot_be_found: diag(2664, ts.DiagnosticCategory.Error, "Invalid_module_name_in_augmentation_module_0_cannot_be_found_2664", "Invalid module name in augmentation, module '{0}' cannot be found."), + Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented: diag(2665, ts.DiagnosticCategory.Error, "Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augm_2665", "Invalid module name in augmentation. Module '{0}' resolves to an untyped module at '{1}', which cannot be augmented."), + Exports_and_export_assignments_are_not_permitted_in_module_augmentations: diag(2666, ts.DiagnosticCategory.Error, "Exports_and_export_assignments_are_not_permitted_in_module_augmentations_2666", "Exports and export assignments are not permitted in module augmentations."), + Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_module: diag(2667, ts.DiagnosticCategory.Error, "Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_mod_2667", "Imports are not permitted in module augmentations. Consider moving them to the enclosing external module."), + export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always_visible: diag(2668, ts.DiagnosticCategory.Error, "export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always__2668", "'export' modifier cannot be applied to ambient modules and module augmentations since they are always visible."), + Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_declarations: diag(2669, ts.DiagnosticCategory.Error, "Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_2669", "Augmentations for the global scope can only be directly nested in external modules or ambient module declarations."), + Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambient_context: diag(2670, ts.DiagnosticCategory.Error, "Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambien_2670", "Augmentations for the global scope should have 'declare' modifier unless they appear in already ambient context."), + Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity: diag(2671, ts.DiagnosticCategory.Error, "Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity_2671", "Cannot augment module '{0}' because it resolves to a non-module entity."), + Cannot_assign_a_0_constructor_type_to_a_1_constructor_type: diag(2672, ts.DiagnosticCategory.Error, "Cannot_assign_a_0_constructor_type_to_a_1_constructor_type_2672", "Cannot assign a '{0}' constructor type to a '{1}' constructor type."), + Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration: diag(2673, ts.DiagnosticCategory.Error, "Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration_2673", "Constructor of class '{0}' is private and only accessible within the class declaration."), + Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration: diag(2674, ts.DiagnosticCategory.Error, "Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration_2674", "Constructor of class '{0}' is protected and only accessible within the class declaration."), + Cannot_extend_a_class_0_Class_constructor_is_marked_as_private: diag(2675, ts.DiagnosticCategory.Error, "Cannot_extend_a_class_0_Class_constructor_is_marked_as_private_2675", "Cannot extend a class '{0}'. Class constructor is marked as private."), + Accessors_must_both_be_abstract_or_non_abstract: diag(2676, ts.DiagnosticCategory.Error, "Accessors_must_both_be_abstract_or_non_abstract_2676", "Accessors must both be abstract or non-abstract."), + A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type: diag(2677, ts.DiagnosticCategory.Error, "A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type_2677", "A type predicate's type must be assignable to its parameter's type."), + Type_0_is_not_comparable_to_type_1: diag(2678, ts.DiagnosticCategory.Error, "Type_0_is_not_comparable_to_type_1_2678", "Type '{0}' is not comparable to type '{1}'."), + A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void: diag(2679, ts.DiagnosticCategory.Error, "A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void_2679", "A function that is called with the 'new' keyword cannot have a 'this' type that is 'void'."), + A_0_parameter_must_be_the_first_parameter: diag(2680, ts.DiagnosticCategory.Error, "A_0_parameter_must_be_the_first_parameter_2680", "A '{0}' parameter must be the first parameter."), + A_constructor_cannot_have_a_this_parameter: diag(2681, ts.DiagnosticCategory.Error, "A_constructor_cannot_have_a_this_parameter_2681", "A constructor cannot have a 'this' parameter."), + get_and_set_accessor_must_have_the_same_this_type: diag(2682, ts.DiagnosticCategory.Error, "get_and_set_accessor_must_have_the_same_this_type_2682", "'get' and 'set' accessor must have the same 'this' type."), + this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation: diag(2683, ts.DiagnosticCategory.Error, "this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_2683", "'this' implicitly has type 'any' because it does not have a type annotation."), + The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1: diag(2684, ts.DiagnosticCategory.Error, "The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1_2684", "The 'this' context of type '{0}' is not assignable to method's 'this' of type '{1}'."), + The_this_types_of_each_signature_are_incompatible: diag(2685, ts.DiagnosticCategory.Error, "The_this_types_of_each_signature_are_incompatible_2685", "The 'this' types of each signature are incompatible."), + _0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead: diag(2686, ts.DiagnosticCategory.Error, "_0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead_2686", "'{0}' refers to a UMD global, but the current file is a module. Consider adding an import instead."), + All_declarations_of_0_must_have_identical_modifiers: diag(2687, ts.DiagnosticCategory.Error, "All_declarations_of_0_must_have_identical_modifiers_2687", "All declarations of '{0}' must have identical modifiers."), + Cannot_find_type_definition_file_for_0: diag(2688, ts.DiagnosticCategory.Error, "Cannot_find_type_definition_file_for_0_2688", "Cannot find type definition file for '{0}'."), + Cannot_extend_an_interface_0_Did_you_mean_implements: diag(2689, ts.DiagnosticCategory.Error, "Cannot_extend_an_interface_0_Did_you_mean_implements_2689", "Cannot extend an interface '{0}'. Did you mean 'implements'?"), + An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead: diag(2691, ts.DiagnosticCategory.Error, "An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead_2691", "An import path cannot end with a '{0}' extension. Consider importing '{1}' instead."), + _0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible: diag(2692, ts.DiagnosticCategory.Error, "_0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible_2692", "'{0}' is a primitive, but '{1}' is a wrapper object. Prefer using '{0}' when possible."), + _0_only_refers_to_a_type_but_is_being_used_as_a_value_here: diag(2693, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_2693", "'{0}' only refers to a type, but is being used as a value here."), + Namespace_0_has_no_exported_member_1: diag(2694, ts.DiagnosticCategory.Error, "Namespace_0_has_no_exported_member_1_2694", "Namespace '{0}' has no exported member '{1}'."), + Left_side_of_comma_operator_is_unused_and_has_no_side_effects: diag(2695, ts.DiagnosticCategory.Error, "Left_side_of_comma_operator_is_unused_and_has_no_side_effects_2695", "Left side of comma operator is unused and has no side effects.", /*reportsUnnecessary*/ true), + The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead: diag(2696, ts.DiagnosticCategory.Error, "The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead_2696", "The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead?"), + An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option: diag(2697, ts.DiagnosticCategory.Error, "An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_in_2697", "An async function or method must return a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your `--lib` option."), + Spread_types_may_only_be_created_from_object_types: diag(2698, ts.DiagnosticCategory.Error, "Spread_types_may_only_be_created_from_object_types_2698", "Spread types may only be created from object types."), + Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1: diag(2699, ts.DiagnosticCategory.Error, "Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1_2699", "Static property '{0}' conflicts with built-in property 'Function.{0}' of constructor function '{1}'."), + Rest_types_may_only_be_created_from_object_types: diag(2700, ts.DiagnosticCategory.Error, "Rest_types_may_only_be_created_from_object_types_2700", "Rest types may only be created from object types."), + The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access: diag(2701, ts.DiagnosticCategory.Error, "The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access_2701", "The target of an object rest assignment must be a variable or a property access."), + _0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here: diag(2702, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here_2702", "'{0}' only refers to a type, but is being used as a namespace here."), + The_operand_of_a_delete_operator_must_be_a_property_reference: diag(2703, ts.DiagnosticCategory.Error, "The_operand_of_a_delete_operator_must_be_a_property_reference_2703", "The operand of a delete operator must be a property reference."), + The_operand_of_a_delete_operator_cannot_be_a_read_only_property: diag(2704, ts.DiagnosticCategory.Error, "The_operand_of_a_delete_operator_cannot_be_a_read_only_property_2704", "The operand of a delete operator cannot be a read-only property."), + An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option: diag(2705, ts.DiagnosticCategory.Error, "An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_de_2705", "An async function or method in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your `--lib` option."), + Required_type_parameters_may_not_follow_optional_type_parameters: diag(2706, ts.DiagnosticCategory.Error, "Required_type_parameters_may_not_follow_optional_type_parameters_2706", "Required type parameters may not follow optional type parameters."), + Generic_type_0_requires_between_1_and_2_type_arguments: diag(2707, ts.DiagnosticCategory.Error, "Generic_type_0_requires_between_1_and_2_type_arguments_2707", "Generic type '{0}' requires between {1} and {2} type arguments."), + Cannot_use_namespace_0_as_a_value: diag(2708, ts.DiagnosticCategory.Error, "Cannot_use_namespace_0_as_a_value_2708", "Cannot use namespace '{0}' as a value."), + Cannot_use_namespace_0_as_a_type: diag(2709, ts.DiagnosticCategory.Error, "Cannot_use_namespace_0_as_a_type_2709", "Cannot use namespace '{0}' as a type."), + _0_are_specified_twice_The_attribute_named_0_will_be_overwritten: diag(2710, ts.DiagnosticCategory.Error, "_0_are_specified_twice_The_attribute_named_0_will_be_overwritten_2710", "'{0}' are specified twice. The attribute named '{0}' will be overwritten."), + A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option: diag(2711, ts.DiagnosticCategory.Error, "A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES20_2711", "A dynamic import call returns a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your `--lib` option."), + A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option: diag(2712, ts.DiagnosticCategory.Error, "A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declarat_2712", "A dynamic import call in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your `--lib` option."), + Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_property_1_in_0_with_0_1: diag(2713, ts.DiagnosticCategory.Error, "Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_p_2713", "Cannot access '{0}.{1}' because '{0}' is a type, but not a namespace. Did you mean to retrieve the type of the property '{1}' in '{0}' with '{0}[\"{1}\"]'?"), + The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context: diag(2714, ts.DiagnosticCategory.Error, "The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context_2714", "The expression of an export assignment must be an identifier or qualified name in an ambient context."), + Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor: diag(2715, ts.DiagnosticCategory.Error, "Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor_2715", "Abstract property '{0}' in class '{1}' cannot be accessed in the constructor."), + Type_parameter_0_has_a_circular_default: diag(2716, ts.DiagnosticCategory.Error, "Type_parameter_0_has_a_circular_default_2716", "Type parameter '{0}' has a circular default."), + Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_type_2: diag(2717, ts.DiagnosticCategory.Error, "Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_t_2717", "Subsequent property declarations must have the same type. Property '{0}' must be of type '{1}', but here has type '{2}'."), + Duplicate_declaration_0: diag(2718, ts.DiagnosticCategory.Error, "Duplicate_declaration_0_2718", "Duplicate declaration '{0}'."), + Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated: diag(2719, ts.DiagnosticCategory.Error, "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_2719", "Type '{0}' is not assignable to type '{1}'. Two different types with this name exist, but they are unrelated."), + Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass: diag(2720, ts.DiagnosticCategory.Error, "Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclas_2720", "Class '{0}' incorrectly implements class '{1}'. Did you mean to extend '{1}' and inherit its members as a subclass?"), + Cannot_invoke_an_object_which_is_possibly_null: diag(2721, ts.DiagnosticCategory.Error, "Cannot_invoke_an_object_which_is_possibly_null_2721", "Cannot invoke an object which is possibly 'null'."), + Cannot_invoke_an_object_which_is_possibly_undefined: diag(2722, ts.DiagnosticCategory.Error, "Cannot_invoke_an_object_which_is_possibly_undefined_2722", "Cannot invoke an object which is possibly 'undefined'."), + Cannot_invoke_an_object_which_is_possibly_null_or_undefined: diag(2723, ts.DiagnosticCategory.Error, "Cannot_invoke_an_object_which_is_possibly_null_or_undefined_2723", "Cannot invoke an object which is possibly 'null' or 'undefined'."), + Module_0_has_no_exported_member_1_Did_you_mean_2: diag(2724, ts.DiagnosticCategory.Error, "Module_0_has_no_exported_member_1_Did_you_mean_2_2724", "Module '{0}' has no exported member '{1}'. Did you mean '{2}'?"), + Class_name_cannot_be_Object_when_targeting_ES5_with_module_0: diag(2725, ts.DiagnosticCategory.Error, "Class_name_cannot_be_Object_when_targeting_ES5_with_module_0_2725", "Class name cannot be 'Object' when targeting ES5 with module {0}."), + Cannot_find_lib_definition_for_0: diag(2726, ts.DiagnosticCategory.Error, "Cannot_find_lib_definition_for_0_2726", "Cannot find lib definition for '{0}'."), + Cannot_find_lib_definition_for_0_Did_you_mean_1: diag(2727, ts.DiagnosticCategory.Error, "Cannot_find_lib_definition_for_0_Did_you_mean_1_2727", "Cannot find lib definition for '{0}'. Did you mean '{1}'?"), + _0_is_declared_here: diag(2728, ts.DiagnosticCategory.Message, "_0_is_declared_here_2728", "'{0}' is declared here."), + Property_0_is_used_before_its_initialization: diag(2729, ts.DiagnosticCategory.Error, "Property_0_is_used_before_its_initialization_2729", "Property '{0}' is used before its initialization."), + An_arrow_function_cannot_have_a_this_parameter: diag(2730, ts.DiagnosticCategory.Error, "An_arrow_function_cannot_have_a_this_parameter_2730", "An arrow function cannot have a 'this' parameter."), + Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_in_String: diag(2731, ts.DiagnosticCategory.Error, "Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_i_2731", "Implicit conversion of a 'symbol' to a 'string' will fail at runtime. Consider wrapping this expression in 'String(...)'."), + Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension: diag(2732, ts.DiagnosticCategory.Error, "Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension_2732", "Cannot find module '{0}'. Consider using '--resolveJsonModule' to import module with '.json' extension"), + It_is_highly_likely_that_you_are_missing_a_semicolon: diag(2734, ts.DiagnosticCategory.Error, "It_is_highly_likely_that_you_are_missing_a_semicolon_2734", "It is highly likely that you are missing a semicolon."), + Did_you_mean_for_0_to_be_constrained_to_type_new_args_Colon_any_1: diag(2735, ts.DiagnosticCategory.Error, "Did_you_mean_for_0_to_be_constrained_to_type_new_args_Colon_any_1_2735", "Did you mean for '{0}' to be constrained to type 'new (...args: any[]) => {1}'?"), + Operator_0_cannot_be_applied_to_type_1: diag(2736, ts.DiagnosticCategory.Error, "Operator_0_cannot_be_applied_to_type_1_2736", "Operator '{0}' cannot be applied to type '{1}'."), + BigInt_literals_are_not_available_when_targeting_lower_than_ESNext: diag(2737, ts.DiagnosticCategory.Error, "BigInt_literals_are_not_available_when_targeting_lower_than_ESNext_2737", "BigInt literals are not available when targeting lower than ESNext."), + An_outer_value_of_this_is_shadowed_by_this_container: diag(2738, ts.DiagnosticCategory.Message, "An_outer_value_of_this_is_shadowed_by_this_container_2738", "An outer value of 'this' is shadowed by this container."), + Type_0_is_missing_the_following_properties_from_type_1_Colon_2: diag(2739, ts.DiagnosticCategory.Error, "Type_0_is_missing_the_following_properties_from_type_1_Colon_2_2739", "Type '{0}' is missing the following properties from type '{1}': {2}"), + Type_0_is_missing_the_following_properties_from_type_1_Colon_2_and_3_more: diag(2740, ts.DiagnosticCategory.Error, "Type_0_is_missing_the_following_properties_from_type_1_Colon_2_and_3_more_2740", "Type '{0}' is missing the following properties from type '{1}': {2}, and {3} more."), + Property_0_is_missing_in_type_1_but_required_in_type_2: diag(2741, ts.DiagnosticCategory.Error, "Property_0_is_missing_in_type_1_but_required_in_type_2_2741", "Property '{0}' is missing in type '{1}' but required in type '{2}'."), + The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_annotation_is_necessary: diag(2742, ts.DiagnosticCategory.Error, "The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_a_2742", "The inferred type of '{0}' cannot be named without a reference to '{1}'. This is likely not portable. A type annotation is necessary."), + Import_declaration_0_is_using_private_name_1: diag(4000, ts.DiagnosticCategory.Error, "Import_declaration_0_is_using_private_name_1_4000", "Import declaration '{0}' is using private name '{1}'."), + Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: diag(4002, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", "Type parameter '{0}' of exported class has or is using private name '{1}'."), + Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: diag(4004, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", "Type parameter '{0}' of exported interface has or is using private name '{1}'."), + Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1: diag(4006, ts.DiagnosticCategory.Error, "Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4006", "Type parameter '{0}' of constructor signature from exported interface has or is using private name '{1}'."), + Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1: diag(4008, ts.DiagnosticCategory.Error, "Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4008", "Type parameter '{0}' of call signature from exported interface has or is using private name '{1}'."), + Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1: diag(4010, ts.DiagnosticCategory.Error, "Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4010", "Type parameter '{0}' of public static method from exported class has or is using private name '{1}'."), + Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1: diag(4012, ts.DiagnosticCategory.Error, "Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4012", "Type parameter '{0}' of public method from exported class has or is using private name '{1}'."), + Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1: diag(4014, ts.DiagnosticCategory.Error, "Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4014", "Type parameter '{0}' of method from exported interface has or is using private name '{1}'."), + Type_parameter_0_of_exported_function_has_or_is_using_private_name_1: diag(4016, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_function_has_or_is_using_private_name_1_4016", "Type parameter '{0}' of exported function has or is using private name '{1}'."), + Implements_clause_of_exported_class_0_has_or_is_using_private_name_1: diag(4019, ts.DiagnosticCategory.Error, "Implements_clause_of_exported_class_0_has_or_is_using_private_name_1_4019", "Implements clause of exported class '{0}' has or is using private name '{1}'."), + extends_clause_of_exported_class_0_has_or_is_using_private_name_1: diag(4020, ts.DiagnosticCategory.Error, "extends_clause_of_exported_class_0_has_or_is_using_private_name_1_4020", "'extends' clause of exported class '{0}' has or is using private name '{1}'."), + extends_clause_of_exported_interface_0_has_or_is_using_private_name_1: diag(4022, ts.DiagnosticCategory.Error, "extends_clause_of_exported_interface_0_has_or_is_using_private_name_1_4022", "'extends' clause of exported interface '{0}' has or is using private name '{1}'."), + Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4023, ts.DiagnosticCategory.Error, "Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4023", "Exported variable '{0}' has or is using name '{1}' from external module {2} but cannot be named."), + Exported_variable_0_has_or_is_using_name_1_from_private_module_2: diag(4024, ts.DiagnosticCategory.Error, "Exported_variable_0_has_or_is_using_name_1_from_private_module_2_4024", "Exported variable '{0}' has or is using name '{1}' from private module '{2}'."), + Exported_variable_0_has_or_is_using_private_name_1: diag(4025, ts.DiagnosticCategory.Error, "Exported_variable_0_has_or_is_using_private_name_1_4025", "Exported variable '{0}' has or is using private name '{1}'."), + Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4026, ts.DiagnosticCategory.Error, "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot__4026", "Public static property '{0}' of exported class has or is using name '{1}' from external module {2} but cannot be named."), + Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4027, ts.DiagnosticCategory.Error, "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4027", "Public static property '{0}' of exported class has or is using name '{1}' from private module '{2}'."), + Public_static_property_0_of_exported_class_has_or_is_using_private_name_1: diag(4028, ts.DiagnosticCategory.Error, "Public_static_property_0_of_exported_class_has_or_is_using_private_name_1_4028", "Public static property '{0}' of exported class has or is using private name '{1}'."), + Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4029, ts.DiagnosticCategory.Error, "Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_name_4029", "Public property '{0}' of exported class has or is using name '{1}' from external module {2} but cannot be named."), + Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4030, ts.DiagnosticCategory.Error, "Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4030", "Public property '{0}' of exported class has or is using name '{1}' from private module '{2}'."), + Public_property_0_of_exported_class_has_or_is_using_private_name_1: diag(4031, ts.DiagnosticCategory.Error, "Public_property_0_of_exported_class_has_or_is_using_private_name_1_4031", "Public property '{0}' of exported class has or is using private name '{1}'."), + Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4032, ts.DiagnosticCategory.Error, "Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4032", "Property '{0}' of exported interface has or is using name '{1}' from private module '{2}'."), + Property_0_of_exported_interface_has_or_is_using_private_name_1: diag(4033, ts.DiagnosticCategory.Error, "Property_0_of_exported_interface_has_or_is_using_private_name_1_4033", "Property '{0}' of exported interface has or is using private name '{1}'."), + Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4034, ts.DiagnosticCategory.Error, "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_name_1_from_private_mod_4034", "Parameter type of public static setter '{0}' from exported class has or is using name '{1}' from private module '{2}'."), + Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1: diag(4035, ts.DiagnosticCategory.Error, "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1_4035", "Parameter type of public static setter '{0}' from exported class has or is using private name '{1}'."), + Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4036, ts.DiagnosticCategory.Error, "Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2_4036", "Parameter type of public setter '{0}' from exported class has or is using name '{1}' from private module '{2}'."), + Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_private_name_1: diag(4037, ts.DiagnosticCategory.Error, "Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_private_name_1_4037", "Parameter type of public setter '{0}' from exported class has or is using private name '{1}'."), + Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4038, ts.DiagnosticCategory.Error, "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_external_modul_4038", "Return type of public static getter '{0}' from exported class has or is using name '{1}' from external module {2} but cannot be named."), + Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4039, ts.DiagnosticCategory.Error, "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_4039", "Return type of public static getter '{0}' from exported class has or is using name '{1}' from private module '{2}'."), + Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_private_name_1: diag(4040, ts.DiagnosticCategory.Error, "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_private_name_1_4040", "Return type of public static getter '{0}' from exported class has or is using private name '{1}'."), + Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4041, ts.DiagnosticCategory.Error, "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_4041", "Return type of public getter '{0}' from exported class has or is using name '{1}' from external module {2} but cannot be named."), + Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4042, ts.DiagnosticCategory.Error, "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2_4042", "Return type of public getter '{0}' from exported class has or is using name '{1}' from private module '{2}'."), + Return_type_of_public_getter_0_from_exported_class_has_or_is_using_private_name_1: diag(4043, ts.DiagnosticCategory.Error, "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_private_name_1_4043", "Return type of public getter '{0}' from exported class has or is using private name '{1}'."), + Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1: diag(4044, ts.DiagnosticCategory.Error, "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_mod_4044", "Return type of constructor signature from exported interface has or is using name '{0}' from private module '{1}'."), + Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0: diag(4045, ts.DiagnosticCategory.Error, "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0_4045", "Return type of constructor signature from exported interface has or is using private name '{0}'."), + Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1: diag(4046, ts.DiagnosticCategory.Error, "Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4046", "Return type of call signature from exported interface has or is using name '{0}' from private module '{1}'."), + Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0: diag(4047, ts.DiagnosticCategory.Error, "Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0_4047", "Return type of call signature from exported interface has or is using private name '{0}'."), + Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1: diag(4048, ts.DiagnosticCategory.Error, "Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4048", "Return type of index signature from exported interface has or is using name '{0}' from private module '{1}'."), + Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0: diag(4049, ts.DiagnosticCategory.Error, "Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0_4049", "Return type of index signature from exported interface has or is using private name '{0}'."), + Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: diag(4050, ts.DiagnosticCategory.Error, "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module__4050", "Return type of public static method from exported class has or is using name '{0}' from external module {1} but cannot be named."), + Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1: diag(4051, ts.DiagnosticCategory.Error, "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4051", "Return type of public static method from exported class has or is using name '{0}' from private module '{1}'."), + Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0: diag(4052, ts.DiagnosticCategory.Error, "Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0_4052", "Return type of public static method from exported class has or is using private name '{0}'."), + Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: diag(4053, ts.DiagnosticCategory.Error, "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_c_4053", "Return type of public method from exported class has or is using name '{0}' from external module {1} but cannot be named."), + Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1: diag(4054, ts.DiagnosticCategory.Error, "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4054", "Return type of public method from exported class has or is using name '{0}' from private module '{1}'."), + Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0: diag(4055, ts.DiagnosticCategory.Error, "Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0_4055", "Return type of public method from exported class has or is using private name '{0}'."), + Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1: diag(4056, ts.DiagnosticCategory.Error, "Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4056", "Return type of method from exported interface has or is using name '{0}' from private module '{1}'."), + Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0: diag(4057, ts.DiagnosticCategory.Error, "Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0_4057", "Return type of method from exported interface has or is using private name '{0}'."), + Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: diag(4058, ts.DiagnosticCategory.Error, "Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named_4058", "Return type of exported function has or is using name '{0}' from external module {1} but cannot be named."), + Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1: diag(4059, ts.DiagnosticCategory.Error, "Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1_4059", "Return type of exported function has or is using name '{0}' from private module '{1}'."), + Return_type_of_exported_function_has_or_is_using_private_name_0: diag(4060, ts.DiagnosticCategory.Error, "Return_type_of_exported_function_has_or_is_using_private_name_0_4060", "Return type of exported function has or is using private name '{0}'."), + Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4061, ts.DiagnosticCategory.Error, "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_can_4061", "Parameter '{0}' of constructor from exported class has or is using name '{1}' from external module {2} but cannot be named."), + Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4062, ts.DiagnosticCategory.Error, "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2_4062", "Parameter '{0}' of constructor from exported class has or is using name '{1}' from private module '{2}'."), + Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1: diag(4063, ts.DiagnosticCategory.Error, "Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1_4063", "Parameter '{0}' of constructor from exported class has or is using private name '{1}'."), + Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4064, ts.DiagnosticCategory.Error, "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_mod_4064", "Parameter '{0}' of constructor signature from exported interface has or is using name '{1}' from private module '{2}'."), + Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1: diag(4065, ts.DiagnosticCategory.Error, "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4065", "Parameter '{0}' of constructor signature from exported interface has or is using private name '{1}'."), + Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4066, ts.DiagnosticCategory.Error, "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4066", "Parameter '{0}' of call signature from exported interface has or is using name '{1}' from private module '{2}'."), + Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1: diag(4067, ts.DiagnosticCategory.Error, "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4067", "Parameter '{0}' of call signature from exported interface has or is using private name '{1}'."), + Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4068, ts.DiagnosticCategory.Error, "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module__4068", "Parameter '{0}' of public static method from exported class has or is using name '{1}' from external module {2} but cannot be named."), + Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4069, ts.DiagnosticCategory.Error, "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4069", "Parameter '{0}' of public static method from exported class has or is using name '{1}' from private module '{2}'."), + Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1: diag(4070, ts.DiagnosticCategory.Error, "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4070", "Parameter '{0}' of public static method from exported class has or is using private name '{1}'."), + Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4071, ts.DiagnosticCategory.Error, "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_c_4071", "Parameter '{0}' of public method from exported class has or is using name '{1}' from external module {2} but cannot be named."), + Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4072, ts.DiagnosticCategory.Error, "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4072", "Parameter '{0}' of public method from exported class has or is using name '{1}' from private module '{2}'."), + Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1: diag(4073, ts.DiagnosticCategory.Error, "Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4073", "Parameter '{0}' of public method from exported class has or is using private name '{1}'."), + Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4074, ts.DiagnosticCategory.Error, "Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4074", "Parameter '{0}' of method from exported interface has or is using name '{1}' from private module '{2}'."), + Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1: diag(4075, ts.DiagnosticCategory.Error, "Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4075", "Parameter '{0}' of method from exported interface has or is using private name '{1}'."), + Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4076, ts.DiagnosticCategory.Error, "Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4076", "Parameter '{0}' of exported function has or is using name '{1}' from external module {2} but cannot be named."), + Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2: diag(4077, ts.DiagnosticCategory.Error, "Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2_4077", "Parameter '{0}' of exported function has or is using name '{1}' from private module '{2}'."), + Parameter_0_of_exported_function_has_or_is_using_private_name_1: diag(4078, ts.DiagnosticCategory.Error, "Parameter_0_of_exported_function_has_or_is_using_private_name_1_4078", "Parameter '{0}' of exported function has or is using private name '{1}'."), + Exported_type_alias_0_has_or_is_using_private_name_1: diag(4081, ts.DiagnosticCategory.Error, "Exported_type_alias_0_has_or_is_using_private_name_1_4081", "Exported type alias '{0}' has or is using private name '{1}'."), + Default_export_of_the_module_has_or_is_using_private_name_0: diag(4082, ts.DiagnosticCategory.Error, "Default_export_of_the_module_has_or_is_using_private_name_0_4082", "Default export of the module has or is using private name '{0}'."), + Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1: diag(4083, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1_4083", "Type parameter '{0}' of exported type alias has or is using private name '{1}'."), + Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict: diag(4090, ts.DiagnosticCategory.Error, "Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_librar_4090", "Conflicting definitions for '{0}' found at '{1}' and '{2}'. Consider installing a specific version of this library to resolve the conflict."), + Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4091, ts.DiagnosticCategory.Error, "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4091", "Parameter '{0}' of index signature from exported interface has or is using name '{1}' from private module '{2}'."), + Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1: diag(4092, ts.DiagnosticCategory.Error, "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1_4092", "Parameter '{0}' of index signature from exported interface has or is using private name '{1}'."), + Property_0_of_exported_class_expression_may_not_be_private_or_protected: diag(4094, ts.DiagnosticCategory.Error, "Property_0_of_exported_class_expression_may_not_be_private_or_protected_4094", "Property '{0}' of exported class expression may not be private or protected."), + Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4095, ts.DiagnosticCategory.Error, "Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_4095", "Public static method '{0}' of exported class has or is using name '{1}' from external module {2} but cannot be named."), + Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4096, ts.DiagnosticCategory.Error, "Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4096", "Public static method '{0}' of exported class has or is using name '{1}' from private module '{2}'."), + Public_static_method_0_of_exported_class_has_or_is_using_private_name_1: diag(4097, ts.DiagnosticCategory.Error, "Public_static_method_0_of_exported_class_has_or_is_using_private_name_1_4097", "Public static method '{0}' of exported class has or is using private name '{1}'."), + Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4098, ts.DiagnosticCategory.Error, "Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4098", "Public method '{0}' of exported class has or is using name '{1}' from external module {2} but cannot be named."), + Public_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4099, ts.DiagnosticCategory.Error, "Public_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4099", "Public method '{0}' of exported class has or is using name '{1}' from private module '{2}'."), + Public_method_0_of_exported_class_has_or_is_using_private_name_1: diag(4100, ts.DiagnosticCategory.Error, "Public_method_0_of_exported_class_has_or_is_using_private_name_1_4100", "Public method '{0}' of exported class has or is using private name '{1}'."), + Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4101, ts.DiagnosticCategory.Error, "Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4101", "Method '{0}' of exported interface has or is using name '{1}' from private module '{2}'."), + Method_0_of_exported_interface_has_or_is_using_private_name_1: diag(4102, ts.DiagnosticCategory.Error, "Method_0_of_exported_interface_has_or_is_using_private_name_1_4102", "Method '{0}' of exported interface has or is using private name '{1}'."), + The_current_host_does_not_support_the_0_option: diag(5001, ts.DiagnosticCategory.Error, "The_current_host_does_not_support_the_0_option_5001", "The current host does not support the '{0}' option."), + Cannot_find_the_common_subdirectory_path_for_the_input_files: diag(5009, ts.DiagnosticCategory.Error, "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009", "Cannot find the common subdirectory path for the input files."), + File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: diag(5010, ts.DiagnosticCategory.Error, "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010", "File specification cannot end in a recursive directory wildcard ('**'): '{0}'."), + Cannot_read_file_0_Colon_1: diag(5012, ts.DiagnosticCategory.Error, "Cannot_read_file_0_Colon_1_5012", "Cannot read file '{0}': {1}."), + Failed_to_parse_file_0_Colon_1: diag(5014, ts.DiagnosticCategory.Error, "Failed_to_parse_file_0_Colon_1_5014", "Failed to parse file '{0}': {1}."), + Unknown_compiler_option_0: diag(5023, ts.DiagnosticCategory.Error, "Unknown_compiler_option_0_5023", "Unknown compiler option '{0}'."), + Compiler_option_0_requires_a_value_of_type_1: diag(5024, ts.DiagnosticCategory.Error, "Compiler_option_0_requires_a_value_of_type_1_5024", "Compiler option '{0}' requires a value of type {1}."), + Could_not_write_file_0_Colon_1: diag(5033, ts.DiagnosticCategory.Error, "Could_not_write_file_0_Colon_1_5033", "Could not write file '{0}': {1}."), + Option_project_cannot_be_mixed_with_source_files_on_a_command_line: diag(5042, ts.DiagnosticCategory.Error, "Option_project_cannot_be_mixed_with_source_files_on_a_command_line_5042", "Option 'project' cannot be mixed with source files on a command line."), + Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher: diag(5047, ts.DiagnosticCategory.Error, "Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES_5047", "Option 'isolatedModules' can only be used when either option '--module' is provided or option 'target' is 'ES2015' or higher."), + Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided: diag(5051, ts.DiagnosticCategory.Error, "Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided_5051", "Option '{0} can only be used when either option '--inlineSourceMap' or option '--sourceMap' is provided."), + Option_0_cannot_be_specified_without_specifying_option_1: diag(5052, ts.DiagnosticCategory.Error, "Option_0_cannot_be_specified_without_specifying_option_1_5052", "Option '{0}' cannot be specified without specifying option '{1}'."), + Option_0_cannot_be_specified_with_option_1: diag(5053, ts.DiagnosticCategory.Error, "Option_0_cannot_be_specified_with_option_1_5053", "Option '{0}' cannot be specified with option '{1}'."), + A_tsconfig_json_file_is_already_defined_at_Colon_0: diag(5054, ts.DiagnosticCategory.Error, "A_tsconfig_json_file_is_already_defined_at_Colon_0_5054", "A 'tsconfig.json' file is already defined at: '{0}'."), + Cannot_write_file_0_because_it_would_overwrite_input_file: diag(5055, ts.DiagnosticCategory.Error, "Cannot_write_file_0_because_it_would_overwrite_input_file_5055", "Cannot write file '{0}' because it would overwrite input file."), + Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files: diag(5056, ts.DiagnosticCategory.Error, "Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files_5056", "Cannot write file '{0}' because it would be overwritten by multiple input files."), + Cannot_find_a_tsconfig_json_file_at_the_specified_directory_Colon_0: diag(5057, ts.DiagnosticCategory.Error, "Cannot_find_a_tsconfig_json_file_at_the_specified_directory_Colon_0_5057", "Cannot find a tsconfig.json file at the specified directory: '{0}'."), + The_specified_path_does_not_exist_Colon_0: diag(5058, ts.DiagnosticCategory.Error, "The_specified_path_does_not_exist_Colon_0_5058", "The specified path does not exist: '{0}'."), + Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier: diag(5059, ts.DiagnosticCategory.Error, "Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier_5059", "Invalid value for '--reactNamespace'. '{0}' is not a valid identifier."), + Option_paths_cannot_be_used_without_specifying_baseUrl_option: diag(5060, ts.DiagnosticCategory.Error, "Option_paths_cannot_be_used_without_specifying_baseUrl_option_5060", "Option 'paths' cannot be used without specifying '--baseUrl' option."), + Pattern_0_can_have_at_most_one_Asterisk_character: diag(5061, ts.DiagnosticCategory.Error, "Pattern_0_can_have_at_most_one_Asterisk_character_5061", "Pattern '{0}' can have at most one '*' character."), + Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character: diag(5062, ts.DiagnosticCategory.Error, "Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character_5062", "Substitution '{0}' in pattern '{1}' in can have at most one '*' character."), + Substitutions_for_pattern_0_should_be_an_array: diag(5063, ts.DiagnosticCategory.Error, "Substitutions_for_pattern_0_should_be_an_array_5063", "Substitutions for pattern '{0}' should be an array."), + Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2: diag(5064, ts.DiagnosticCategory.Error, "Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2_5064", "Substitution '{0}' for pattern '{1}' has incorrect type, expected 'string', got '{2}'."), + File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: diag(5065, ts.DiagnosticCategory.Error, "File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildca_5065", "File specification cannot contain a parent directory ('..') that appears after a recursive directory wildcard ('**'): '{0}'."), + Substitutions_for_pattern_0_shouldn_t_be_an_empty_array: diag(5066, ts.DiagnosticCategory.Error, "Substitutions_for_pattern_0_shouldn_t_be_an_empty_array_5066", "Substitutions for pattern '{0}' shouldn't be an empty array."), + Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name: diag(5067, ts.DiagnosticCategory.Error, "Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name_5067", "Invalid value for 'jsxFactory'. '{0}' is not a valid identifier or qualified-name."), + Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig: diag(5068, ts.DiagnosticCategory.Error, "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068", "Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig."), + Option_0_cannot_be_specified_without_specifying_option_1_or_option_2: diag(5069, ts.DiagnosticCategory.Error, "Option_0_cannot_be_specified_without_specifying_option_1_or_option_2_5069", "Option '{0}' cannot be specified without specifying option '{1}' or option '{2}'."), + Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy: diag(5070, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070", "Option '--resolveJsonModule' cannot be specified without 'node' module resolution strategy."), + Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_esNext: diag(5071, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_5071", "Option '--resolveJsonModule' can only be specified when module code generation is 'commonjs', 'amd', 'es2015' or 'esNext'."), + Unknown_build_option_0: diag(5072, ts.DiagnosticCategory.Error, "Unknown_build_option_0_5072", "Unknown build option '{0}'."), + Build_option_0_requires_a_value_of_type_1: diag(5073, ts.DiagnosticCategory.Error, "Build_option_0_requires_a_value_of_type_1_5073", "Build option '{0}' requires a value of type {1}."), + Generates_a_sourcemap_for_each_corresponding_d_ts_file: diag(6000, ts.DiagnosticCategory.Message, "Generates_a_sourcemap_for_each_corresponding_d_ts_file_6000", "Generates a sourcemap for each corresponding '.d.ts' file."), + Concatenate_and_emit_output_to_single_file: diag(6001, ts.DiagnosticCategory.Message, "Concatenate_and_emit_output_to_single_file_6001", "Concatenate and emit output to single file."), + Generates_corresponding_d_ts_file: diag(6002, ts.DiagnosticCategory.Message, "Generates_corresponding_d_ts_file_6002", "Generates corresponding '.d.ts' file."), + Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations: diag(6003, ts.DiagnosticCategory.Message, "Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations_6003", "Specify the location where debugger should locate map files instead of generated locations."), + Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations: diag(6004, ts.DiagnosticCategory.Message, "Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations_6004", "Specify the location where debugger should locate TypeScript files instead of source locations."), + Watch_input_files: diag(6005, ts.DiagnosticCategory.Message, "Watch_input_files_6005", "Watch input files."), + Redirect_output_structure_to_the_directory: diag(6006, ts.DiagnosticCategory.Message, "Redirect_output_structure_to_the_directory_6006", "Redirect output structure to the directory."), + Do_not_erase_const_enum_declarations_in_generated_code: diag(6007, ts.DiagnosticCategory.Message, "Do_not_erase_const_enum_declarations_in_generated_code_6007", "Do not erase const enum declarations in generated code."), + Do_not_emit_outputs_if_any_errors_were_reported: diag(6008, ts.DiagnosticCategory.Message, "Do_not_emit_outputs_if_any_errors_were_reported_6008", "Do not emit outputs if any errors were reported."), + Do_not_emit_comments_to_output: diag(6009, ts.DiagnosticCategory.Message, "Do_not_emit_comments_to_output_6009", "Do not emit comments to output."), + Do_not_emit_outputs: diag(6010, ts.DiagnosticCategory.Message, "Do_not_emit_outputs_6010", "Do not emit outputs."), + Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking: diag(6011, ts.DiagnosticCategory.Message, "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011", "Allow default imports from modules with no default export. This does not affect code emit, just typechecking."), + Skip_type_checking_of_declaration_files: diag(6012, ts.DiagnosticCategory.Message, "Skip_type_checking_of_declaration_files_6012", "Skip type checking of declaration files."), + Do_not_resolve_the_real_path_of_symlinks: diag(6013, ts.DiagnosticCategory.Message, "Do_not_resolve_the_real_path_of_symlinks_6013", "Do not resolve the real path of symlinks."), + Only_emit_d_ts_declaration_files: diag(6014, ts.DiagnosticCategory.Message, "Only_emit_d_ts_declaration_files_6014", "Only emit '.d.ts' declaration files."), + Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_or_ESNEXT: diag(6015, ts.DiagnosticCategory.Message, "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_or_ESNEXT_6015", "Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'."), + Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext: diag(6016, ts.DiagnosticCategory.Message, "Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext_6016", "Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'."), + Print_this_message: diag(6017, ts.DiagnosticCategory.Message, "Print_this_message_6017", "Print this message."), + Print_the_compiler_s_version: diag(6019, ts.DiagnosticCategory.Message, "Print_the_compiler_s_version_6019", "Print the compiler's version."), + Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json: diag(6020, ts.DiagnosticCategory.Message, "Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json_6020", "Compile the project given the path to its configuration file, or to a folder with a 'tsconfig.json'."), + Syntax_Colon_0: diag(6023, ts.DiagnosticCategory.Message, "Syntax_Colon_0_6023", "Syntax: {0}"), + options: diag(6024, ts.DiagnosticCategory.Message, "options_6024", "options"), + file: diag(6025, ts.DiagnosticCategory.Message, "file_6025", "file"), + Examples_Colon_0: diag(6026, ts.DiagnosticCategory.Message, "Examples_Colon_0_6026", "Examples: {0}"), + Options_Colon: diag(6027, ts.DiagnosticCategory.Message, "Options_Colon_6027", "Options:"), + Version_0: diag(6029, ts.DiagnosticCategory.Message, "Version_0_6029", "Version {0}"), + Insert_command_line_options_and_files_from_a_file: diag(6030, ts.DiagnosticCategory.Message, "Insert_command_line_options_and_files_from_a_file_6030", "Insert command line options and files from a file."), + Starting_compilation_in_watch_mode: diag(6031, ts.DiagnosticCategory.Message, "Starting_compilation_in_watch_mode_6031", "Starting compilation in watch mode..."), + File_change_detected_Starting_incremental_compilation: diag(6032, ts.DiagnosticCategory.Message, "File_change_detected_Starting_incremental_compilation_6032", "File change detected. Starting incremental compilation..."), + KIND: diag(6034, ts.DiagnosticCategory.Message, "KIND_6034", "KIND"), + FILE: diag(6035, ts.DiagnosticCategory.Message, "FILE_6035", "FILE"), + VERSION: diag(6036, ts.DiagnosticCategory.Message, "VERSION_6036", "VERSION"), + LOCATION: diag(6037, ts.DiagnosticCategory.Message, "LOCATION_6037", "LOCATION"), + DIRECTORY: diag(6038, ts.DiagnosticCategory.Message, "DIRECTORY_6038", "DIRECTORY"), + STRATEGY: diag(6039, ts.DiagnosticCategory.Message, "STRATEGY_6039", "STRATEGY"), + FILE_OR_DIRECTORY: diag(6040, ts.DiagnosticCategory.Message, "FILE_OR_DIRECTORY_6040", "FILE OR DIRECTORY"), + Generates_corresponding_map_file: diag(6043, ts.DiagnosticCategory.Message, "Generates_corresponding_map_file_6043", "Generates corresponding '.map' file."), + Compiler_option_0_expects_an_argument: diag(6044, ts.DiagnosticCategory.Error, "Compiler_option_0_expects_an_argument_6044", "Compiler option '{0}' expects an argument."), + Unterminated_quoted_string_in_response_file_0: diag(6045, ts.DiagnosticCategory.Error, "Unterminated_quoted_string_in_response_file_0_6045", "Unterminated quoted string in response file '{0}'."), + Argument_for_0_option_must_be_Colon_1: diag(6046, ts.DiagnosticCategory.Error, "Argument_for_0_option_must_be_Colon_1_6046", "Argument for '{0}' option must be: {1}."), + Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1: diag(6048, ts.DiagnosticCategory.Error, "Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1_6048", "Locale must be of the form or -. For example '{0}' or '{1}'."), + Unsupported_locale_0: diag(6049, ts.DiagnosticCategory.Error, "Unsupported_locale_0_6049", "Unsupported locale '{0}'."), + Unable_to_open_file_0: diag(6050, ts.DiagnosticCategory.Error, "Unable_to_open_file_0_6050", "Unable to open file '{0}'."), + Corrupted_locale_file_0: diag(6051, ts.DiagnosticCategory.Error, "Corrupted_locale_file_0_6051", "Corrupted locale file {0}."), + Raise_error_on_expressions_and_declarations_with_an_implied_any_type: diag(6052, ts.DiagnosticCategory.Message, "Raise_error_on_expressions_and_declarations_with_an_implied_any_type_6052", "Raise error on expressions and declarations with an implied 'any' type."), + File_0_not_found: diag(6053, ts.DiagnosticCategory.Error, "File_0_not_found_6053", "File '{0}' not found."), + File_0_has_unsupported_extension_The_only_supported_extensions_are_1: diag(6054, ts.DiagnosticCategory.Error, "File_0_has_unsupported_extension_The_only_supported_extensions_are_1_6054", "File '{0}' has unsupported extension. The only supported extensions are {1}."), + Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures: diag(6055, ts.DiagnosticCategory.Message, "Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures_6055", "Suppress noImplicitAny errors for indexing objects lacking index signatures."), + Do_not_emit_declarations_for_code_that_has_an_internal_annotation: diag(6056, ts.DiagnosticCategory.Message, "Do_not_emit_declarations_for_code_that_has_an_internal_annotation_6056", "Do not emit declarations for code that has an '@internal' annotation."), + Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir: diag(6058, ts.DiagnosticCategory.Message, "Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir_6058", "Specify the root directory of input files. Use to control the output directory structure with --outDir."), + File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files: diag(6059, ts.DiagnosticCategory.Error, "File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files_6059", "File '{0}' is not under 'rootDir' '{1}'. 'rootDir' is expected to contain all source files."), + Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix: diag(6060, ts.DiagnosticCategory.Message, "Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix_6060", "Specify the end of line sequence to be used when emitting files: 'CRLF' (dos) or 'LF' (unix)."), + NEWLINE: diag(6061, ts.DiagnosticCategory.Message, "NEWLINE_6061", "NEWLINE"), + Option_0_can_only_be_specified_in_tsconfig_json_file: diag(6064, ts.DiagnosticCategory.Error, "Option_0_can_only_be_specified_in_tsconfig_json_file_6064", "Option '{0}' can only be specified in 'tsconfig.json' file."), + Enables_experimental_support_for_ES7_decorators: diag(6065, ts.DiagnosticCategory.Message, "Enables_experimental_support_for_ES7_decorators_6065", "Enables experimental support for ES7 decorators."), + Enables_experimental_support_for_emitting_type_metadata_for_decorators: diag(6066, ts.DiagnosticCategory.Message, "Enables_experimental_support_for_emitting_type_metadata_for_decorators_6066", "Enables experimental support for emitting type metadata for decorators."), + Enables_experimental_support_for_ES7_async_functions: diag(6068, ts.DiagnosticCategory.Message, "Enables_experimental_support_for_ES7_async_functions_6068", "Enables experimental support for ES7 async functions."), + Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6: diag(6069, ts.DiagnosticCategory.Message, "Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6_6069", "Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6)."), + Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file: diag(6070, ts.DiagnosticCategory.Message, "Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file_6070", "Initializes a TypeScript project and creates a tsconfig.json file."), + Successfully_created_a_tsconfig_json_file: diag(6071, ts.DiagnosticCategory.Message, "Successfully_created_a_tsconfig_json_file_6071", "Successfully created a tsconfig.json file."), + Suppress_excess_property_checks_for_object_literals: diag(6072, ts.DiagnosticCategory.Message, "Suppress_excess_property_checks_for_object_literals_6072", "Suppress excess property checks for object literals."), + Stylize_errors_and_messages_using_color_and_context_experimental: diag(6073, ts.DiagnosticCategory.Message, "Stylize_errors_and_messages_using_color_and_context_experimental_6073", "Stylize errors and messages using color and context (experimental)."), + Do_not_report_errors_on_unused_labels: diag(6074, ts.DiagnosticCategory.Message, "Do_not_report_errors_on_unused_labels_6074", "Do not report errors on unused labels."), + Report_error_when_not_all_code_paths_in_function_return_a_value: diag(6075, ts.DiagnosticCategory.Message, "Report_error_when_not_all_code_paths_in_function_return_a_value_6075", "Report error when not all code paths in function return a value."), + Report_errors_for_fallthrough_cases_in_switch_statement: diag(6076, ts.DiagnosticCategory.Message, "Report_errors_for_fallthrough_cases_in_switch_statement_6076", "Report errors for fallthrough cases in switch statement."), + Do_not_report_errors_on_unreachable_code: diag(6077, ts.DiagnosticCategory.Message, "Do_not_report_errors_on_unreachable_code_6077", "Do not report errors on unreachable code."), + Disallow_inconsistently_cased_references_to_the_same_file: diag(6078, ts.DiagnosticCategory.Message, "Disallow_inconsistently_cased_references_to_the_same_file_6078", "Disallow inconsistently-cased references to the same file."), + Specify_library_files_to_be_included_in_the_compilation: diag(6079, ts.DiagnosticCategory.Message, "Specify_library_files_to_be_included_in_the_compilation_6079", "Specify library files to be included in the compilation."), + Specify_JSX_code_generation_Colon_preserve_react_native_or_react: diag(6080, ts.DiagnosticCategory.Message, "Specify_JSX_code_generation_Colon_preserve_react_native_or_react_6080", "Specify JSX code generation: 'preserve', 'react-native', or 'react'."), + File_0_has_an_unsupported_extension_so_skipping_it: diag(6081, ts.DiagnosticCategory.Message, "File_0_has_an_unsupported_extension_so_skipping_it_6081", "File '{0}' has an unsupported extension, so skipping it."), + Only_amd_and_system_modules_are_supported_alongside_0: diag(6082, ts.DiagnosticCategory.Error, "Only_amd_and_system_modules_are_supported_alongside_0_6082", "Only 'amd' and 'system' modules are supported alongside --{0}."), + Base_directory_to_resolve_non_absolute_module_names: diag(6083, ts.DiagnosticCategory.Message, "Base_directory_to_resolve_non_absolute_module_names_6083", "Base directory to resolve non-absolute module names."), + Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react_JSX_emit: diag(6084, ts.DiagnosticCategory.Message, "Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react__6084", "[Deprecated] Use '--jsxFactory' instead. Specify the object invoked for createElement when targeting 'react' JSX emit"), + Enable_tracing_of_the_name_resolution_process: diag(6085, ts.DiagnosticCategory.Message, "Enable_tracing_of_the_name_resolution_process_6085", "Enable tracing of the name resolution process."), + Resolving_module_0_from_1: diag(6086, ts.DiagnosticCategory.Message, "Resolving_module_0_from_1_6086", "======== Resolving module '{0}' from '{1}'. ========"), + Explicitly_specified_module_resolution_kind_Colon_0: diag(6087, ts.DiagnosticCategory.Message, "Explicitly_specified_module_resolution_kind_Colon_0_6087", "Explicitly specified module resolution kind: '{0}'."), + Module_resolution_kind_is_not_specified_using_0: diag(6088, ts.DiagnosticCategory.Message, "Module_resolution_kind_is_not_specified_using_0_6088", "Module resolution kind is not specified, using '{0}'."), + Module_name_0_was_successfully_resolved_to_1: diag(6089, ts.DiagnosticCategory.Message, "Module_name_0_was_successfully_resolved_to_1_6089", "======== Module name '{0}' was successfully resolved to '{1}'. ========"), + Module_name_0_was_not_resolved: diag(6090, ts.DiagnosticCategory.Message, "Module_name_0_was_not_resolved_6090", "======== Module name '{0}' was not resolved. ========"), + paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0: diag(6091, ts.DiagnosticCategory.Message, "paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0_6091", "'paths' option is specified, looking for a pattern to match module name '{0}'."), + Module_name_0_matched_pattern_1: diag(6092, ts.DiagnosticCategory.Message, "Module_name_0_matched_pattern_1_6092", "Module name '{0}', matched pattern '{1}'."), + Trying_substitution_0_candidate_module_location_Colon_1: diag(6093, ts.DiagnosticCategory.Message, "Trying_substitution_0_candidate_module_location_Colon_1_6093", "Trying substitution '{0}', candidate module location: '{1}'."), + Resolving_module_name_0_relative_to_base_url_1_2: diag(6094, ts.DiagnosticCategory.Message, "Resolving_module_name_0_relative_to_base_url_1_2_6094", "Resolving module name '{0}' relative to base url '{1}' - '{2}'."), + Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1: diag(6095, ts.DiagnosticCategory.Message, "Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1_6095", "Loading module as file / folder, candidate module location '{0}', target file type '{1}'."), + File_0_does_not_exist: diag(6096, ts.DiagnosticCategory.Message, "File_0_does_not_exist_6096", "File '{0}' does not exist."), + File_0_exist_use_it_as_a_name_resolution_result: diag(6097, ts.DiagnosticCategory.Message, "File_0_exist_use_it_as_a_name_resolution_result_6097", "File '{0}' exist - use it as a name resolution result."), + Loading_module_0_from_node_modules_folder_target_file_type_1: diag(6098, ts.DiagnosticCategory.Message, "Loading_module_0_from_node_modules_folder_target_file_type_1_6098", "Loading module '{0}' from 'node_modules' folder, target file type '{1}'."), + Found_package_json_at_0: diag(6099, ts.DiagnosticCategory.Message, "Found_package_json_at_0_6099", "Found 'package.json' at '{0}'."), + package_json_does_not_have_a_0_field: diag(6100, ts.DiagnosticCategory.Message, "package_json_does_not_have_a_0_field_6100", "'package.json' does not have a '{0}' field."), + package_json_has_0_field_1_that_references_2: diag(6101, ts.DiagnosticCategory.Message, "package_json_has_0_field_1_that_references_2_6101", "'package.json' has '{0}' field '{1}' that references '{2}'."), + Allow_javascript_files_to_be_compiled: diag(6102, ts.DiagnosticCategory.Message, "Allow_javascript_files_to_be_compiled_6102", "Allow javascript files to be compiled."), + Option_0_should_have_array_of_strings_as_a_value: diag(6103, ts.DiagnosticCategory.Error, "Option_0_should_have_array_of_strings_as_a_value_6103", "Option '{0}' should have array of strings as a value."), + Checking_if_0_is_the_longest_matching_prefix_for_1_2: diag(6104, ts.DiagnosticCategory.Message, "Checking_if_0_is_the_longest_matching_prefix_for_1_2_6104", "Checking if '{0}' is the longest matching prefix for '{1}' - '{2}'."), + Expected_type_of_0_field_in_package_json_to_be_1_got_2: diag(6105, ts.DiagnosticCategory.Message, "Expected_type_of_0_field_in_package_json_to_be_1_got_2_6105", "Expected type of '{0}' field in 'package.json' to be '{1}', got '{2}'."), + baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1: diag(6106, ts.DiagnosticCategory.Message, "baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1_6106", "'baseUrl' option is set to '{0}', using this value to resolve non-relative module name '{1}'."), + rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0: diag(6107, ts.DiagnosticCategory.Message, "rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107", "'rootDirs' option is set, using it to resolve relative module name '{0}'."), + Longest_matching_prefix_for_0_is_1: diag(6108, ts.DiagnosticCategory.Message, "Longest_matching_prefix_for_0_is_1_6108", "Longest matching prefix for '{0}' is '{1}'."), + Loading_0_from_the_root_dir_1_candidate_location_2: diag(6109, ts.DiagnosticCategory.Message, "Loading_0_from_the_root_dir_1_candidate_location_2_6109", "Loading '{0}' from the root dir '{1}', candidate location '{2}'."), + Trying_other_entries_in_rootDirs: diag(6110, ts.DiagnosticCategory.Message, "Trying_other_entries_in_rootDirs_6110", "Trying other entries in 'rootDirs'."), + Module_resolution_using_rootDirs_has_failed: diag(6111, ts.DiagnosticCategory.Message, "Module_resolution_using_rootDirs_has_failed_6111", "Module resolution using 'rootDirs' has failed."), + Do_not_emit_use_strict_directives_in_module_output: diag(6112, ts.DiagnosticCategory.Message, "Do_not_emit_use_strict_directives_in_module_output_6112", "Do not emit 'use strict' directives in module output."), + Enable_strict_null_checks: diag(6113, ts.DiagnosticCategory.Message, "Enable_strict_null_checks_6113", "Enable strict null checks."), + Unknown_option_excludes_Did_you_mean_exclude: diag(6114, ts.DiagnosticCategory.Error, "Unknown_option_excludes_Did_you_mean_exclude_6114", "Unknown option 'excludes'. Did you mean 'exclude'?"), + Raise_error_on_this_expressions_with_an_implied_any_type: diag(6115, ts.DiagnosticCategory.Message, "Raise_error_on_this_expressions_with_an_implied_any_type_6115", "Raise error on 'this' expressions with an implied 'any' type."), + Resolving_type_reference_directive_0_containing_file_1_root_directory_2: diag(6116, ts.DiagnosticCategory.Message, "Resolving_type_reference_directive_0_containing_file_1_root_directory_2_6116", "======== Resolving type reference directive '{0}', containing file '{1}', root directory '{2}'. ========"), + Resolving_using_primary_search_paths: diag(6117, ts.DiagnosticCategory.Message, "Resolving_using_primary_search_paths_6117", "Resolving using primary search paths..."), + Resolving_from_node_modules_folder: diag(6118, ts.DiagnosticCategory.Message, "Resolving_from_node_modules_folder_6118", "Resolving from node_modules folder..."), + Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2: diag(6119, ts.DiagnosticCategory.Message, "Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2_6119", "======== Type reference directive '{0}' was successfully resolved to '{1}', primary: {2}. ========"), + Type_reference_directive_0_was_not_resolved: diag(6120, ts.DiagnosticCategory.Message, "Type_reference_directive_0_was_not_resolved_6120", "======== Type reference directive '{0}' was not resolved. ========"), + Resolving_with_primary_search_path_0: diag(6121, ts.DiagnosticCategory.Message, "Resolving_with_primary_search_path_0_6121", "Resolving with primary search path '{0}'."), + Root_directory_cannot_be_determined_skipping_primary_search_paths: diag(6122, ts.DiagnosticCategory.Message, "Root_directory_cannot_be_determined_skipping_primary_search_paths_6122", "Root directory cannot be determined, skipping primary search paths."), + Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set: diag(6123, ts.DiagnosticCategory.Message, "Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set_6123", "======== Resolving type reference directive '{0}', containing file '{1}', root directory not set. ========"), + Type_declaration_files_to_be_included_in_compilation: diag(6124, ts.DiagnosticCategory.Message, "Type_declaration_files_to_be_included_in_compilation_6124", "Type declaration files to be included in compilation."), + Looking_up_in_node_modules_folder_initial_location_0: diag(6125, ts.DiagnosticCategory.Message, "Looking_up_in_node_modules_folder_initial_location_0_6125", "Looking up in 'node_modules' folder, initial location '{0}'."), + Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder: diag(6126, ts.DiagnosticCategory.Message, "Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126", "Containing file is not specified and root directory cannot be determined, skipping lookup in 'node_modules' folder."), + Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1: diag(6127, ts.DiagnosticCategory.Message, "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1_6127", "======== Resolving type reference directive '{0}', containing file not set, root directory '{1}'. ========"), + Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set: diag(6128, ts.DiagnosticCategory.Message, "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set_6128", "======== Resolving type reference directive '{0}', containing file not set, root directory not set. ========"), + Resolving_real_path_for_0_result_1: diag(6130, ts.DiagnosticCategory.Message, "Resolving_real_path_for_0_result_1_6130", "Resolving real path for '{0}', result '{1}'."), + Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system: diag(6131, ts.DiagnosticCategory.Error, "Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system_6131", "Cannot compile modules using option '{0}' unless the '--module' flag is 'amd' or 'system'."), + File_name_0_has_a_1_extension_stripping_it: diag(6132, ts.DiagnosticCategory.Message, "File_name_0_has_a_1_extension_stripping_it_6132", "File name '{0}' has a '{1}' extension - stripping it."), + _0_is_declared_but_its_value_is_never_read: diag(6133, ts.DiagnosticCategory.Error, "_0_is_declared_but_its_value_is_never_read_6133", "'{0}' is declared but its value is never read.", /*reportsUnnecessary*/ true), + Report_errors_on_unused_locals: diag(6134, ts.DiagnosticCategory.Message, "Report_errors_on_unused_locals_6134", "Report errors on unused locals."), + Report_errors_on_unused_parameters: diag(6135, ts.DiagnosticCategory.Message, "Report_errors_on_unused_parameters_6135", "Report errors on unused parameters."), + The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files: diag(6136, ts.DiagnosticCategory.Message, "The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files_6136", "The maximum dependency depth to search under node_modules and load JavaScript files."), + Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1: diag(6137, ts.DiagnosticCategory.Error, "Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1_6137", "Cannot import type declaration files. Consider importing '{0}' instead of '{1}'."), + Property_0_is_declared_but_its_value_is_never_read: diag(6138, ts.DiagnosticCategory.Error, "Property_0_is_declared_but_its_value_is_never_read_6138", "Property '{0}' is declared but its value is never read.", /*reportsUnnecessary*/ true), + Import_emit_helpers_from_tslib: diag(6139, ts.DiagnosticCategory.Message, "Import_emit_helpers_from_tslib_6139", "Import emit helpers from 'tslib'."), + Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2: diag(6140, ts.DiagnosticCategory.Error, "Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using__6140", "Auto discovery for typings is enabled in project '{0}'. Running extra resolution pass for module '{1}' using cache location '{2}'."), + Parse_in_strict_mode_and_emit_use_strict_for_each_source_file: diag(6141, ts.DiagnosticCategory.Message, "Parse_in_strict_mode_and_emit_use_strict_for_each_source_file_6141", "Parse in strict mode and emit \"use strict\" for each source file."), + Module_0_was_resolved_to_1_but_jsx_is_not_set: diag(6142, ts.DiagnosticCategory.Error, "Module_0_was_resolved_to_1_but_jsx_is_not_set_6142", "Module '{0}' was resolved to '{1}', but '--jsx' is not set."), + Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1: diag(6144, ts.DiagnosticCategory.Message, "Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1_6144", "Module '{0}' was resolved as locally declared ambient module in file '{1}'."), + Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified: diag(6145, ts.DiagnosticCategory.Message, "Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified_6145", "Module '{0}' was resolved as ambient module declared in '{1}' since this file was not modified."), + Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h: diag(6146, ts.DiagnosticCategory.Message, "Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h_6146", "Specify the JSX factory function to use when targeting 'react' JSX emit, e.g. 'React.createElement' or 'h'."), + Resolution_for_module_0_was_found_in_cache_from_location_1: diag(6147, ts.DiagnosticCategory.Message, "Resolution_for_module_0_was_found_in_cache_from_location_1_6147", "Resolution for module '{0}' was found in cache from location '{1}'."), + Directory_0_does_not_exist_skipping_all_lookups_in_it: diag(6148, ts.DiagnosticCategory.Message, "Directory_0_does_not_exist_skipping_all_lookups_in_it_6148", "Directory '{0}' does not exist, skipping all lookups in it."), + Show_diagnostic_information: diag(6149, ts.DiagnosticCategory.Message, "Show_diagnostic_information_6149", "Show diagnostic information."), + Show_verbose_diagnostic_information: diag(6150, ts.DiagnosticCategory.Message, "Show_verbose_diagnostic_information_6150", "Show verbose diagnostic information."), + Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file: diag(6151, ts.DiagnosticCategory.Message, "Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file_6151", "Emit a single file with source maps instead of having a separate file."), + Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap_to_be_set: diag(6152, ts.DiagnosticCategory.Message, "Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap__6152", "Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set."), + Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule: diag(6153, ts.DiagnosticCategory.Message, "Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule_6153", "Transpile each file as a separate module (similar to 'ts.transpileModule')."), + Print_names_of_generated_files_part_of_the_compilation: diag(6154, ts.DiagnosticCategory.Message, "Print_names_of_generated_files_part_of_the_compilation_6154", "Print names of generated files part of the compilation."), + Print_names_of_files_part_of_the_compilation: diag(6155, ts.DiagnosticCategory.Message, "Print_names_of_files_part_of_the_compilation_6155", "Print names of files part of the compilation."), + The_locale_used_when_displaying_messages_to_the_user_e_g_en_us: diag(6156, ts.DiagnosticCategory.Message, "The_locale_used_when_displaying_messages_to_the_user_e_g_en_us_6156", "The locale used when displaying messages to the user (e.g. 'en-us')"), + Do_not_generate_custom_helper_functions_like_extends_in_compiled_output: diag(6157, ts.DiagnosticCategory.Message, "Do_not_generate_custom_helper_functions_like_extends_in_compiled_output_6157", "Do not generate custom helper functions like '__extends' in compiled output."), + Do_not_include_the_default_library_file_lib_d_ts: diag(6158, ts.DiagnosticCategory.Message, "Do_not_include_the_default_library_file_lib_d_ts_6158", "Do not include the default library file (lib.d.ts)."), + Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files: diag(6159, ts.DiagnosticCategory.Message, "Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files_6159", "Do not add triple-slash references or imported modules to the list of compiled files."), + Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files: diag(6160, ts.DiagnosticCategory.Message, "Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files_6160", "[Deprecated] Use '--skipLibCheck' instead. Skip type checking of default library declaration files."), + List_of_folders_to_include_type_definitions_from: diag(6161, ts.DiagnosticCategory.Message, "List_of_folders_to_include_type_definitions_from_6161", "List of folders to include type definitions from."), + Disable_size_limitations_on_JavaScript_projects: diag(6162, ts.DiagnosticCategory.Message, "Disable_size_limitations_on_JavaScript_projects_6162", "Disable size limitations on JavaScript projects."), + The_character_set_of_the_input_files: diag(6163, ts.DiagnosticCategory.Message, "The_character_set_of_the_input_files_6163", "The character set of the input files."), + Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files: diag(6164, ts.DiagnosticCategory.Message, "Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files_6164", "Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files."), + Do_not_truncate_error_messages: diag(6165, ts.DiagnosticCategory.Message, "Do_not_truncate_error_messages_6165", "Do not truncate error messages."), + Output_directory_for_generated_declaration_files: diag(6166, ts.DiagnosticCategory.Message, "Output_directory_for_generated_declaration_files_6166", "Output directory for generated declaration files."), + A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl: diag(6167, ts.DiagnosticCategory.Message, "A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl_6167", "A series of entries which re-map imports to lookup locations relative to the 'baseUrl'."), + List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime: diag(6168, ts.DiagnosticCategory.Message, "List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime_6168", "List of root folders whose combined content represents the structure of the project at runtime."), + Show_all_compiler_options: diag(6169, ts.DiagnosticCategory.Message, "Show_all_compiler_options_6169", "Show all compiler options."), + Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file: diag(6170, ts.DiagnosticCategory.Message, "Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file_6170", "[Deprecated] Use '--outFile' instead. Concatenate and emit output to single file"), + Command_line_Options: diag(6171, ts.DiagnosticCategory.Message, "Command_line_Options_6171", "Command-line Options"), + Basic_Options: diag(6172, ts.DiagnosticCategory.Message, "Basic_Options_6172", "Basic Options"), + Strict_Type_Checking_Options: diag(6173, ts.DiagnosticCategory.Message, "Strict_Type_Checking_Options_6173", "Strict Type-Checking Options"), + Module_Resolution_Options: diag(6174, ts.DiagnosticCategory.Message, "Module_Resolution_Options_6174", "Module Resolution Options"), + Source_Map_Options: diag(6175, ts.DiagnosticCategory.Message, "Source_Map_Options_6175", "Source Map Options"), + Additional_Checks: diag(6176, ts.DiagnosticCategory.Message, "Additional_Checks_6176", "Additional Checks"), + Experimental_Options: diag(6177, ts.DiagnosticCategory.Message, "Experimental_Options_6177", "Experimental Options"), + Advanced_Options: diag(6178, ts.DiagnosticCategory.Message, "Advanced_Options_6178", "Advanced Options"), + Provide_full_support_for_iterables_in_for_of_spread_and_destructuring_when_targeting_ES5_or_ES3: diag(6179, ts.DiagnosticCategory.Message, "Provide_full_support_for_iterables_in_for_of_spread_and_destructuring_when_targeting_ES5_or_ES3_6179", "Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'."), + Enable_all_strict_type_checking_options: diag(6180, ts.DiagnosticCategory.Message, "Enable_all_strict_type_checking_options_6180", "Enable all strict type-checking options."), + List_of_language_service_plugins: diag(6181, ts.DiagnosticCategory.Message, "List_of_language_service_plugins_6181", "List of language service plugins."), + Scoped_package_detected_looking_in_0: diag(6182, ts.DiagnosticCategory.Message, "Scoped_package_detected_looking_in_0_6182", "Scoped package detected, looking in '{0}'"), + Reusing_resolution_of_module_0_to_file_1_from_old_program: diag(6183, ts.DiagnosticCategory.Message, "Reusing_resolution_of_module_0_to_file_1_from_old_program_6183", "Reusing resolution of module '{0}' to file '{1}' from old program."), + Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program: diag(6184, ts.DiagnosticCategory.Message, "Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program_6184", "Reusing module resolutions originating in '{0}' since resolutions are unchanged from old program."), + Disable_strict_checking_of_generic_signatures_in_function_types: diag(6185, ts.DiagnosticCategory.Message, "Disable_strict_checking_of_generic_signatures_in_function_types_6185", "Disable strict checking of generic signatures in function types."), + Enable_strict_checking_of_function_types: diag(6186, ts.DiagnosticCategory.Message, "Enable_strict_checking_of_function_types_6186", "Enable strict checking of function types."), + Enable_strict_checking_of_property_initialization_in_classes: diag(6187, ts.DiagnosticCategory.Message, "Enable_strict_checking_of_property_initialization_in_classes_6187", "Enable strict checking of property initialization in classes."), + Numeric_separators_are_not_allowed_here: diag(6188, ts.DiagnosticCategory.Error, "Numeric_separators_are_not_allowed_here_6188", "Numeric separators are not allowed here."), + Multiple_consecutive_numeric_separators_are_not_permitted: diag(6189, ts.DiagnosticCategory.Error, "Multiple_consecutive_numeric_separators_are_not_permitted_6189", "Multiple consecutive numeric separators are not permitted."), + Found_package_json_at_0_Package_ID_is_1: diag(6190, ts.DiagnosticCategory.Message, "Found_package_json_at_0_Package_ID_is_1_6190", "Found 'package.json' at '{0}'. Package ID is '{1}'."), + Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen: diag(6191, ts.DiagnosticCategory.Message, "Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen_6191", "Whether to keep outdated console output in watch mode instead of clearing the screen."), + All_imports_in_import_declaration_are_unused: diag(6192, ts.DiagnosticCategory.Error, "All_imports_in_import_declaration_are_unused_6192", "All imports in import declaration are unused.", /*reportsUnnecessary*/ true), + Found_1_error_Watching_for_file_changes: diag(6193, ts.DiagnosticCategory.Message, "Found_1_error_Watching_for_file_changes_6193", "Found 1 error. Watching for file changes."), + Found_0_errors_Watching_for_file_changes: diag(6194, ts.DiagnosticCategory.Message, "Found_0_errors_Watching_for_file_changes_6194", "Found {0} errors. Watching for file changes."), + Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols: diag(6195, ts.DiagnosticCategory.Message, "Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols_6195", "Resolve 'keyof' to string valued property names only (no numbers or symbols)."), + _0_is_declared_but_never_used: diag(6196, ts.DiagnosticCategory.Error, "_0_is_declared_but_never_used_6196", "'{0}' is declared but never used.", /*reportsUnnecessary*/ true), + Include_modules_imported_with_json_extension: diag(6197, ts.DiagnosticCategory.Message, "Include_modules_imported_with_json_extension_6197", "Include modules imported with '.json' extension"), + All_destructured_elements_are_unused: diag(6198, ts.DiagnosticCategory.Error, "All_destructured_elements_are_unused_6198", "All destructured elements are unused.", /*reportsUnnecessary*/ true), + All_variables_are_unused: diag(6199, ts.DiagnosticCategory.Error, "All_variables_are_unused_6199", "All variables are unused.", /*reportsUnnecessary*/ true), + Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0: diag(6200, ts.DiagnosticCategory.Error, "Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0_6200", "Definitions of the following identifiers conflict with those in another file: {0}"), + Conflicts_are_in_this_file: diag(6201, ts.DiagnosticCategory.Message, "Conflicts_are_in_this_file_6201", "Conflicts are in this file."), + _0_was_also_declared_here: diag(6203, ts.DiagnosticCategory.Message, "_0_was_also_declared_here_6203", "'{0}' was also declared here."), + and_here: diag(6204, ts.DiagnosticCategory.Message, "and_here_6204", "and here."), + All_type_parameters_are_unused: diag(6205, ts.DiagnosticCategory.Error, "All_type_parameters_are_unused_6205", "All type parameters are unused"), + package_json_has_a_typesVersions_field_with_version_specific_path_mappings: diag(6206, ts.DiagnosticCategory.Message, "package_json_has_a_typesVersions_field_with_version_specific_path_mappings_6206", "'package.json' has a 'typesVersions' field with version-specific path mappings."), + package_json_does_not_have_a_typesVersions_entry_that_matches_version_0: diag(6207, ts.DiagnosticCategory.Message, "package_json_does_not_have_a_typesVersions_entry_that_matches_version_0_6207", "'package.json' does not have a 'typesVersions' entry that matches version '{0}'."), + package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2: diag(6208, ts.DiagnosticCategory.Message, "package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_ma_6208", "'package.json' has a 'typesVersions' entry '{0}' that matches compiler version '{1}', looking for a pattern to match module name '{2}'."), + package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range: diag(6209, ts.DiagnosticCategory.Message, "package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range_6209", "'package.json' has a 'typesVersions' entry '{0}' that is not a valid semver range."), + An_argument_for_0_was_not_provided: diag(6210, ts.DiagnosticCategory.Message, "An_argument_for_0_was_not_provided_6210", "An argument for '{0}' was not provided."), + An_argument_matching_this_binding_pattern_was_not_provided: diag(6211, ts.DiagnosticCategory.Message, "An_argument_matching_this_binding_pattern_was_not_provided_6211", "An argument matching this binding pattern was not provided."), + Did_you_mean_to_call_this_expression: diag(6212, ts.DiagnosticCategory.Message, "Did_you_mean_to_call_this_expression_6212", "Did you mean to call this expression?"), + Did_you_mean_to_use_new_with_this_expression: diag(6213, ts.DiagnosticCategory.Message, "Did_you_mean_to_use_new_with_this_expression_6213", "Did you mean to use 'new' with this expression?"), + Enable_strict_bind_call_and_apply_methods_on_functions: diag(6214, ts.DiagnosticCategory.Message, "Enable_strict_bind_call_and_apply_methods_on_functions_6214", "Enable strict 'bind', 'call', and 'apply' methods on functions."), + Using_compiler_options_of_project_reference_redirect_0: diag(6215, ts.DiagnosticCategory.Message, "Using_compiler_options_of_project_reference_redirect_0_6215", "Using compiler options of project reference redirect '{0}'."), + Found_1_error: diag(6216, ts.DiagnosticCategory.Message, "Found_1_error_6216", "Found 1 error."), + Found_0_errors: diag(6217, ts.DiagnosticCategory.Message, "Found_0_errors_6217", "Found {0} errors."), + Projects_to_reference: diag(6300, ts.DiagnosticCategory.Message, "Projects_to_reference_6300", "Projects to reference"), + Enable_project_compilation: diag(6302, ts.DiagnosticCategory.Message, "Enable_project_compilation_6302", "Enable project compilation"), + Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0: diag(6202, ts.DiagnosticCategory.Error, "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202", "Project references may not form a circular graph. Cycle detected: {0}"), + Composite_projects_may_not_disable_declaration_emit: diag(6304, ts.DiagnosticCategory.Error, "Composite_projects_may_not_disable_declaration_emit_6304", "Composite projects may not disable declaration emit."), + Output_file_0_has_not_been_built_from_source_file_1: diag(6305, ts.DiagnosticCategory.Error, "Output_file_0_has_not_been_built_from_source_file_1_6305", "Output file '{0}' has not been built from source file '{1}'."), + Referenced_project_0_must_have_setting_composite_Colon_true: diag(6306, ts.DiagnosticCategory.Error, "Referenced_project_0_must_have_setting_composite_Colon_true_6306", "Referenced project '{0}' must have setting \"composite\": true."), + File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern: diag(6307, ts.DiagnosticCategory.Error, "File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern_6307", "File '{0}' is not in project file list. Projects must list all files or use an 'include' pattern."), + Cannot_prepend_project_0_because_it_does_not_have_outFile_set: diag(6308, ts.DiagnosticCategory.Error, "Cannot_prepend_project_0_because_it_does_not_have_outFile_set_6308", "Cannot prepend project '{0}' because it does not have 'outFile' set"), + Output_file_0_from_project_1_does_not_exist: diag(6309, ts.DiagnosticCategory.Error, "Output_file_0_from_project_1_does_not_exist_6309", "Output file '{0}' from project '{1}' does not exist"), + Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2: diag(6350, ts.DiagnosticCategory.Message, "Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2_6350", "Project '{0}' is out of date because oldest output '{1}' is older than newest input '{2}'"), + Project_0_is_up_to_date_because_newest_input_1_is_older_than_oldest_output_2: diag(6351, ts.DiagnosticCategory.Message, "Project_0_is_up_to_date_because_newest_input_1_is_older_than_oldest_output_2_6351", "Project '{0}' is up to date because newest input '{1}' is older than oldest output '{2}'"), + Project_0_is_out_of_date_because_output_file_1_does_not_exist: diag(6352, ts.DiagnosticCategory.Message, "Project_0_is_out_of_date_because_output_file_1_does_not_exist_6352", "Project '{0}' is out of date because output file '{1}' does not exist"), + Project_0_is_out_of_date_because_its_dependency_1_is_out_of_date: diag(6353, ts.DiagnosticCategory.Message, "Project_0_is_out_of_date_because_its_dependency_1_is_out_of_date_6353", "Project '{0}' is out of date because its dependency '{1}' is out of date"), + Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies: diag(6354, ts.DiagnosticCategory.Message, "Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies_6354", "Project '{0}' is up to date with .d.ts files from its dependencies"), + Projects_in_this_build_Colon_0: diag(6355, ts.DiagnosticCategory.Message, "Projects_in_this_build_Colon_0_6355", "Projects in this build: {0}"), + A_non_dry_build_would_delete_the_following_files_Colon_0: diag(6356, ts.DiagnosticCategory.Message, "A_non_dry_build_would_delete_the_following_files_Colon_0_6356", "A non-dry build would delete the following files: {0}"), + A_non_dry_build_would_build_project_0: diag(6357, ts.DiagnosticCategory.Message, "A_non_dry_build_would_build_project_0_6357", "A non-dry build would build project '{0}'"), + Building_project_0: diag(6358, ts.DiagnosticCategory.Message, "Building_project_0_6358", "Building project '{0}'..."), + Updating_output_timestamps_of_project_0: diag(6359, ts.DiagnosticCategory.Message, "Updating_output_timestamps_of_project_0_6359", "Updating output timestamps of project '{0}'..."), + delete_this_Project_0_is_up_to_date_because_it_was_previously_built: diag(6360, ts.DiagnosticCategory.Message, "delete_this_Project_0_is_up_to_date_because_it_was_previously_built_6360", "delete this - Project '{0}' is up to date because it was previously built"), + Project_0_is_up_to_date: diag(6361, ts.DiagnosticCategory.Message, "Project_0_is_up_to_date_6361", "Project '{0}' is up to date"), + Skipping_build_of_project_0_because_its_dependency_1_has_errors: diag(6362, ts.DiagnosticCategory.Message, "Skipping_build_of_project_0_because_its_dependency_1_has_errors_6362", "Skipping build of project '{0}' because its dependency '{1}' has errors"), + Project_0_can_t_be_built_because_its_dependency_1_has_errors: diag(6363, ts.DiagnosticCategory.Message, "Project_0_can_t_be_built_because_its_dependency_1_has_errors_6363", "Project '{0}' can't be built because its dependency '{1}' has errors"), + Build_one_or_more_projects_and_their_dependencies_if_out_of_date: diag(6364, ts.DiagnosticCategory.Message, "Build_one_or_more_projects_and_their_dependencies_if_out_of_date_6364", "Build one or more projects and their dependencies, if out of date"), + Delete_the_outputs_of_all_projects: diag(6365, ts.DiagnosticCategory.Message, "Delete_the_outputs_of_all_projects_6365", "Delete the outputs of all projects"), + Enable_verbose_logging: diag(6366, ts.DiagnosticCategory.Message, "Enable_verbose_logging_6366", "Enable verbose logging"), + Show_what_would_be_built_or_deleted_if_specified_with_clean: diag(6367, ts.DiagnosticCategory.Message, "Show_what_would_be_built_or_deleted_if_specified_with_clean_6367", "Show what would be built (or deleted, if specified with '--clean')"), + Build_all_projects_including_those_that_appear_to_be_up_to_date: diag(6368, ts.DiagnosticCategory.Message, "Build_all_projects_including_those_that_appear_to_be_up_to_date_6368", "Build all projects, including those that appear to be up to date"), + Option_build_must_be_the_first_command_line_argument: diag(6369, ts.DiagnosticCategory.Error, "Option_build_must_be_the_first_command_line_argument_6369", "Option '--build' must be the first command line argument."), + Options_0_and_1_cannot_be_combined: diag(6370, ts.DiagnosticCategory.Error, "Options_0_and_1_cannot_be_combined_6370", "Options '{0}' and '{1}' cannot be combined."), + The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1: diag(6500, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1_6500", "The expected type comes from property '{0}' which is declared here on type '{1}'"), + The_expected_type_comes_from_this_index_signature: diag(6501, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_this_index_signature_6501", "The expected type comes from this index signature."), + The_expected_type_comes_from_the_return_type_of_this_signature: diag(6502, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_the_return_type_of_this_signature_6502", "The expected type comes from the return type of this signature."), + Variable_0_implicitly_has_an_1_type: diag(7005, ts.DiagnosticCategory.Error, "Variable_0_implicitly_has_an_1_type_7005", "Variable '{0}' implicitly has an '{1}' type."), + Parameter_0_implicitly_has_an_1_type: diag(7006, ts.DiagnosticCategory.Error, "Parameter_0_implicitly_has_an_1_type_7006", "Parameter '{0}' implicitly has an '{1}' type."), + Member_0_implicitly_has_an_1_type: diag(7008, ts.DiagnosticCategory.Error, "Member_0_implicitly_has_an_1_type_7008", "Member '{0}' implicitly has an '{1}' type."), + new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type: diag(7009, ts.DiagnosticCategory.Error, "new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type_7009", "'new' expression, whose target lacks a construct signature, implicitly has an 'any' type."), + _0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type: diag(7010, ts.DiagnosticCategory.Error, "_0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type_7010", "'{0}', which lacks return-type annotation, implicitly has an '{1}' return type."), + Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type: diag(7011, ts.DiagnosticCategory.Error, "Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type_7011", "Function expression, which lacks return-type annotation, implicitly has an '{0}' return type."), + Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: diag(7013, ts.DiagnosticCategory.Error, "Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7013", "Construct signature, which lacks return-type annotation, implicitly has an 'any' return type."), + Function_type_which_lacks_return_type_annotation_implicitly_has_an_0_return_type: diag(7014, ts.DiagnosticCategory.Error, "Function_type_which_lacks_return_type_annotation_implicitly_has_an_0_return_type_7014", "Function type, which lacks return-type annotation, implicitly has an '{0}' return type."), + Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number: diag(7015, ts.DiagnosticCategory.Error, "Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015", "Element implicitly has an 'any' type because index expression is not of type 'number'."), + Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type: diag(7016, ts.DiagnosticCategory.Error, "Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type_7016", "Could not find a declaration file for module '{0}'. '{1}' implicitly has an 'any' type."), + Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature: diag(7017, ts.DiagnosticCategory.Error, "Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature_7017", "Element implicitly has an 'any' type because type '{0}' has no index signature."), + Object_literal_s_property_0_implicitly_has_an_1_type: diag(7018, ts.DiagnosticCategory.Error, "Object_literal_s_property_0_implicitly_has_an_1_type_7018", "Object literal's property '{0}' implicitly has an '{1}' type."), + Rest_parameter_0_implicitly_has_an_any_type: diag(7019, ts.DiagnosticCategory.Error, "Rest_parameter_0_implicitly_has_an_any_type_7019", "Rest parameter '{0}' implicitly has an 'any[]' type."), + Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: diag(7020, ts.DiagnosticCategory.Error, "Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7020", "Call signature, which lacks return-type annotation, implicitly has an 'any' return type."), + _0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer: diag(7022, ts.DiagnosticCategory.Error, "_0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or__7022", "'{0}' implicitly has type 'any' because it does not have a type annotation and is referenced directly or indirectly in its own initializer."), + _0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions: diag(7023, ts.DiagnosticCategory.Error, "_0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_reference_7023", "'{0}' implicitly has return type 'any' because it does not have a return type annotation and is referenced directly or indirectly in one of its return expressions."), + Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions: diag(7024, ts.DiagnosticCategory.Error, "Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_ref_7024", "Function implicitly has return type 'any' because it does not have a return type annotation and is referenced directly or indirectly in one of its return expressions."), + Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_type: diag(7025, ts.DiagnosticCategory.Error, "Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_typ_7025", "Generator implicitly has type '{0}' because it does not yield any values. Consider supplying a return type."), + JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists: diag(7026, ts.DiagnosticCategory.Error, "JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists_7026", "JSX element implicitly has type 'any' because no interface 'JSX.{0}' exists."), + Unreachable_code_detected: diag(7027, ts.DiagnosticCategory.Error, "Unreachable_code_detected_7027", "Unreachable code detected.", /*reportsUnnecessary*/ true), + Unused_label: diag(7028, ts.DiagnosticCategory.Error, "Unused_label_7028", "Unused label.", /*reportsUnnecessary*/ true), + Fallthrough_case_in_switch: diag(7029, ts.DiagnosticCategory.Error, "Fallthrough_case_in_switch_7029", "Fallthrough case in switch."), + Not_all_code_paths_return_a_value: diag(7030, ts.DiagnosticCategory.Error, "Not_all_code_paths_return_a_value_7030", "Not all code paths return a value."), + Binding_element_0_implicitly_has_an_1_type: diag(7031, ts.DiagnosticCategory.Error, "Binding_element_0_implicitly_has_an_1_type_7031", "Binding element '{0}' implicitly has an '{1}' type."), + Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation: diag(7032, ts.DiagnosticCategory.Error, "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032", "Property '{0}' implicitly has type 'any', because its set accessor lacks a parameter type annotation."), + Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation: diag(7033, ts.DiagnosticCategory.Error, "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033", "Property '{0}' implicitly has type 'any', because its get accessor lacks a return type annotation."), + Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined: diag(7034, ts.DiagnosticCategory.Error, "Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined_7034", "Variable '{0}' implicitly has type '{1}' in some locations where its type cannot be determined."), + Try_npm_install_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0: diag(7035, ts.DiagnosticCategory.Error, "Try_npm_install_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_mod_7035", "Try `npm install @types/{1}` if it exists or add a new declaration (.d.ts) file containing `declare module '{0}';`"), + Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0: diag(7036, ts.DiagnosticCategory.Error, "Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036", "Dynamic import's specifier must be of type 'string', but here has type '{0}'."), + Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for_all_imports_Implies_allowSyntheticDefaultImports: diag(7037, ts.DiagnosticCategory.Message, "Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for__7037", "Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'."), + Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_Consider_using_a_default_import_or_import_require_here_instead: diag(7038, ts.DiagnosticCategory.Message, "Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cau_7038", "Type originates at this import. A namespace-style import cannot be called or constructed, and will cause a failure at runtime. Consider using a default import or import require here instead."), + Mapped_object_type_implicitly_has_an_any_template_type: diag(7039, ts.DiagnosticCategory.Error, "Mapped_object_type_implicitly_has_an_any_template_type_7039", "Mapped object type implicitly has an 'any' template type."), + If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1: diag(7040, ts.DiagnosticCategory.Error, "If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_S_7040", "If the '{0}' package actually exposes this module, consider sending a pull request to amend 'https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/{1}`"), + The_containing_arrow_function_captures_the_global_value_of_this_which_implicitly_has_type_any: diag(7041, ts.DiagnosticCategory.Error, "The_containing_arrow_function_captures_the_global_value_of_this_which_implicitly_has_type_any_7041", "The containing arrow function captures the global value of 'this' which implicitly has type 'any'."), + Module_0_was_resolved_to_1_but_resolveJsonModule_is_not_used: diag(7042, ts.DiagnosticCategory.Error, "Module_0_was_resolved_to_1_but_resolveJsonModule_is_not_used_7042", "Module '{0}' was resolved to '{1}', but '--resolveJsonModule' is not used."), + Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage: diag(7043, ts.DiagnosticCategory.Suggestion, "Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7043", "Variable '{0}' implicitly has an '{1}' type, but a better type may be inferred from usage."), + Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage: diag(7044, ts.DiagnosticCategory.Suggestion, "Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7044", "Parameter '{0}' implicitly has an '{1}' type, but a better type may be inferred from usage."), + Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage: diag(7045, ts.DiagnosticCategory.Suggestion, "Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7045", "Member '{0}' implicitly has an '{1}' type, but a better type may be inferred from usage."), + Variable_0_implicitly_has_type_1_in_some_locations_but_a_better_type_may_be_inferred_from_usage: diag(7046, ts.DiagnosticCategory.Suggestion, "Variable_0_implicitly_has_type_1_in_some_locations_but_a_better_type_may_be_inferred_from_usage_7046", "Variable '{0}' implicitly has type '{1}' in some locations, but a better type may be inferred from usage."), + Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage: diag(7047, ts.DiagnosticCategory.Suggestion, "Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage_7047", "Rest parameter '{0}' implicitly has an 'any[]' type, but a better type may be inferred from usage."), + Property_0_implicitly_has_type_any_but_a_better_type_for_its_get_accessor_may_be_inferred_from_usage: diag(7048, ts.DiagnosticCategory.Suggestion, "Property_0_implicitly_has_type_any_but_a_better_type_for_its_get_accessor_may_be_inferred_from_usage_7048", "Property '{0}' implicitly has type 'any', but a better type for its get accessor may be inferred from usage."), + Property_0_implicitly_has_type_any_but_a_better_type_for_its_set_accessor_may_be_inferred_from_usage: diag(7049, ts.DiagnosticCategory.Suggestion, "Property_0_implicitly_has_type_any_but_a_better_type_for_its_set_accessor_may_be_inferred_from_usage_7049", "Property '{0}' implicitly has type 'any', but a better type for its set accessor may be inferred from usage."), + _0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage: diag(7050, ts.DiagnosticCategory.Suggestion, "_0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage_7050", "'{0}' implicitly has an '{1}' return type, but a better type may be inferred from usage."), + Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1: diag(7051, ts.DiagnosticCategory.Error, "Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1_7051", "Parameter has a name but no type. Did you mean '{0}: {1}'?"), + You_cannot_rename_this_element: diag(8000, ts.DiagnosticCategory.Error, "You_cannot_rename_this_element_8000", "You cannot rename this element."), + You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library: diag(8001, ts.DiagnosticCategory.Error, "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001", "You cannot rename elements that are defined in the standard TypeScript library."), + import_can_only_be_used_in_a_ts_file: diag(8002, ts.DiagnosticCategory.Error, "import_can_only_be_used_in_a_ts_file_8002", "'import ... =' can only be used in a .ts file."), + export_can_only_be_used_in_a_ts_file: diag(8003, ts.DiagnosticCategory.Error, "export_can_only_be_used_in_a_ts_file_8003", "'export=' can only be used in a .ts file."), + type_parameter_declarations_can_only_be_used_in_a_ts_file: diag(8004, ts.DiagnosticCategory.Error, "type_parameter_declarations_can_only_be_used_in_a_ts_file_8004", "'type parameter declarations' can only be used in a .ts file."), + implements_clauses_can_only_be_used_in_a_ts_file: diag(8005, ts.DiagnosticCategory.Error, "implements_clauses_can_only_be_used_in_a_ts_file_8005", "'implements clauses' can only be used in a .ts file."), + interface_declarations_can_only_be_used_in_a_ts_file: diag(8006, ts.DiagnosticCategory.Error, "interface_declarations_can_only_be_used_in_a_ts_file_8006", "'interface declarations' can only be used in a .ts file."), + module_declarations_can_only_be_used_in_a_ts_file: diag(8007, ts.DiagnosticCategory.Error, "module_declarations_can_only_be_used_in_a_ts_file_8007", "'module declarations' can only be used in a .ts file."), + type_aliases_can_only_be_used_in_a_ts_file: diag(8008, ts.DiagnosticCategory.Error, "type_aliases_can_only_be_used_in_a_ts_file_8008", "'type aliases' can only be used in a .ts file."), + _0_can_only_be_used_in_a_ts_file: diag(8009, ts.DiagnosticCategory.Error, "_0_can_only_be_used_in_a_ts_file_8009", "'{0}' can only be used in a .ts file."), + types_can_only_be_used_in_a_ts_file: diag(8010, ts.DiagnosticCategory.Error, "types_can_only_be_used_in_a_ts_file_8010", "'types' can only be used in a .ts file."), + type_arguments_can_only_be_used_in_a_ts_file: diag(8011, ts.DiagnosticCategory.Error, "type_arguments_can_only_be_used_in_a_ts_file_8011", "'type arguments' can only be used in a .ts file."), + parameter_modifiers_can_only_be_used_in_a_ts_file: diag(8012, ts.DiagnosticCategory.Error, "parameter_modifiers_can_only_be_used_in_a_ts_file_8012", "'parameter modifiers' can only be used in a .ts file."), + non_null_assertions_can_only_be_used_in_a_ts_file: diag(8013, ts.DiagnosticCategory.Error, "non_null_assertions_can_only_be_used_in_a_ts_file_8013", "'non-null assertions' can only be used in a .ts file."), + enum_declarations_can_only_be_used_in_a_ts_file: diag(8015, ts.DiagnosticCategory.Error, "enum_declarations_can_only_be_used_in_a_ts_file_8015", "'enum declarations' can only be used in a .ts file."), + type_assertion_expressions_can_only_be_used_in_a_ts_file: diag(8016, ts.DiagnosticCategory.Error, "type_assertion_expressions_can_only_be_used_in_a_ts_file_8016", "'type assertion expressions' can only be used in a .ts file."), + Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0: diag(8017, ts.DiagnosticCategory.Error, "Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0_8017", "Octal literal types must use ES2015 syntax. Use the syntax '{0}'."), + Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0: diag(8018, ts.DiagnosticCategory.Error, "Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0_8018", "Octal literals are not allowed in enums members initializer. Use the syntax '{0}'."), + Report_errors_in_js_files: diag(8019, ts.DiagnosticCategory.Message, "Report_errors_in_js_files_8019", "Report errors in .js files."), + JSDoc_types_can_only_be_used_inside_documentation_comments: diag(8020, ts.DiagnosticCategory.Error, "JSDoc_types_can_only_be_used_inside_documentation_comments_8020", "JSDoc types can only be used inside documentation comments."), + JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags: diag(8021, ts.DiagnosticCategory.Error, "JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags_8021", "JSDoc '@typedef' tag should either have a type annotation or be followed by '@property' or '@member' tags."), + JSDoc_0_is_not_attached_to_a_class: diag(8022, ts.DiagnosticCategory.Error, "JSDoc_0_is_not_attached_to_a_class_8022", "JSDoc '@{0}' is not attached to a class."), + JSDoc_0_1_does_not_match_the_extends_2_clause: diag(8023, ts.DiagnosticCategory.Error, "JSDoc_0_1_does_not_match_the_extends_2_clause_8023", "JSDoc '@{0} {1}' does not match the 'extends {2}' clause."), + JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name: diag(8024, ts.DiagnosticCategory.Error, "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_8024", "JSDoc '@param' tag has name '{0}', but there is no parameter with that name."), + Class_declarations_cannot_have_more_than_one_augments_or_extends_tag: diag(8025, ts.DiagnosticCategory.Error, "Class_declarations_cannot_have_more_than_one_augments_or_extends_tag_8025", "Class declarations cannot have more than one `@augments` or `@extends` tag."), + Expected_0_type_arguments_provide_these_with_an_extends_tag: diag(8026, ts.DiagnosticCategory.Error, "Expected_0_type_arguments_provide_these_with_an_extends_tag_8026", "Expected {0} type arguments; provide these with an '@extends' tag."), + Expected_0_1_type_arguments_provide_these_with_an_extends_tag: diag(8027, ts.DiagnosticCategory.Error, "Expected_0_1_type_arguments_provide_these_with_an_extends_tag_8027", "Expected {0}-{1} type arguments; provide these with an '@extends' tag."), + JSDoc_may_only_appear_in_the_last_parameter_of_a_signature: diag(8028, ts.DiagnosticCategory.Error, "JSDoc_may_only_appear_in_the_last_parameter_of_a_signature_8028", "JSDoc '...' may only appear in the last parameter of a signature."), + JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_had_an_array_type: diag(8029, ts.DiagnosticCategory.Error, "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_h_8029", "JSDoc '@param' tag has name '{0}', but there is no parameter with that name. It would match 'arguments' if it had an array type."), + The_type_of_a_function_declaration_must_match_the_function_s_signature: diag(8030, ts.DiagnosticCategory.Error, "The_type_of_a_function_declaration_must_match_the_function_s_signature_8030", "The type of a function declaration must match the function's signature."), + You_cannot_rename_a_module_via_a_global_import: diag(8031, ts.DiagnosticCategory.Error, "You_cannot_rename_a_module_via_a_global_import_8031", "You cannot rename a module via a global import."), + Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_class_extends_clause: diag(9002, ts.DiagnosticCategory.Error, "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002", "Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clause."), + class_expressions_are_not_currently_supported: diag(9003, ts.DiagnosticCategory.Error, "class_expressions_are_not_currently_supported_9003", "'class' expressions are not currently supported."), + Language_service_is_disabled: diag(9004, ts.DiagnosticCategory.Error, "Language_service_is_disabled_9004", "Language service is disabled."), + JSX_attributes_must_only_be_assigned_a_non_empty_expression: diag(17000, ts.DiagnosticCategory.Error, "JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000", "JSX attributes must only be assigned a non-empty 'expression'."), + JSX_elements_cannot_have_multiple_attributes_with_the_same_name: diag(17001, ts.DiagnosticCategory.Error, "JSX_elements_cannot_have_multiple_attributes_with_the_same_name_17001", "JSX elements cannot have multiple attributes with the same name."), + Expected_corresponding_JSX_closing_tag_for_0: diag(17002, ts.DiagnosticCategory.Error, "Expected_corresponding_JSX_closing_tag_for_0_17002", "Expected corresponding JSX closing tag for '{0}'."), + JSX_attribute_expected: diag(17003, ts.DiagnosticCategory.Error, "JSX_attribute_expected_17003", "JSX attribute expected."), + Cannot_use_JSX_unless_the_jsx_flag_is_provided: diag(17004, ts.DiagnosticCategory.Error, "Cannot_use_JSX_unless_the_jsx_flag_is_provided_17004", "Cannot use JSX unless the '--jsx' flag is provided."), + A_constructor_cannot_contain_a_super_call_when_its_class_extends_null: diag(17005, ts.DiagnosticCategory.Error, "A_constructor_cannot_contain_a_super_call_when_its_class_extends_null_17005", "A constructor cannot contain a 'super' call when its class extends 'null'."), + An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses: diag(17006, ts.DiagnosticCategory.Error, "An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_ex_17006", "An unary expression with the '{0}' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses."), + A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses: diag(17007, ts.DiagnosticCategory.Error, "A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Con_17007", "A type assertion expression is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses."), + JSX_element_0_has_no_corresponding_closing_tag: diag(17008, ts.DiagnosticCategory.Error, "JSX_element_0_has_no_corresponding_closing_tag_17008", "JSX element '{0}' has no corresponding closing tag."), + super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class: diag(17009, ts.DiagnosticCategory.Error, "super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class_17009", "'super' must be called before accessing 'this' in the constructor of a derived class."), + Unknown_type_acquisition_option_0: diag(17010, ts.DiagnosticCategory.Error, "Unknown_type_acquisition_option_0_17010", "Unknown type acquisition option '{0}'."), + super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class: diag(17011, ts.DiagnosticCategory.Error, "super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class_17011", "'super' must be called before accessing a property of 'super' in the constructor of a derived class."), + _0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2: diag(17012, ts.DiagnosticCategory.Error, "_0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2_17012", "'{0}' is not a valid meta-property for keyword '{1}'. Did you mean '{2}'?"), + Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constructor: diag(17013, ts.DiagnosticCategory.Error, "Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constru_17013", "Meta-property '{0}' is only allowed in the body of a function declaration, function expression, or constructor."), + JSX_fragment_has_no_corresponding_closing_tag: diag(17014, ts.DiagnosticCategory.Error, "JSX_fragment_has_no_corresponding_closing_tag_17014", "JSX fragment has no corresponding closing tag."), + Expected_corresponding_closing_tag_for_JSX_fragment: diag(17015, ts.DiagnosticCategory.Error, "Expected_corresponding_closing_tag_for_JSX_fragment_17015", "Expected corresponding closing tag for JSX fragment."), + JSX_fragment_is_not_supported_when_using_jsxFactory: diag(17016, ts.DiagnosticCategory.Error, "JSX_fragment_is_not_supported_when_using_jsxFactory_17016", "JSX fragment is not supported when using --jsxFactory"), + JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma: diag(17017, ts.DiagnosticCategory.Error, "JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma_17017", "JSX fragment is not supported when using an inline JSX factory pragma"), + Circularity_detected_while_resolving_configuration_Colon_0: diag(18000, ts.DiagnosticCategory.Error, "Circularity_detected_while_resolving_configuration_Colon_0_18000", "Circularity detected while resolving configuration: {0}"), + A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not: diag(18001, ts.DiagnosticCategory.Error, "A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not_18001", "A path in an 'extends' option must be relative or rooted, but '{0}' is not."), + The_files_list_in_config_file_0_is_empty: diag(18002, ts.DiagnosticCategory.Error, "The_files_list_in_config_file_0_is_empty_18002", "The 'files' list in config file '{0}' is empty."), + No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2: diag(18003, ts.DiagnosticCategory.Error, "No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2_18003", "No inputs were found in config file '{0}'. Specified 'include' paths were '{1}' and 'exclude' paths were '{2}'."), + File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module: diag(80001, ts.DiagnosticCategory.Suggestion, "File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module_80001", "File is a CommonJS module; it may be converted to an ES6 module."), + This_constructor_function_may_be_converted_to_a_class_declaration: diag(80002, ts.DiagnosticCategory.Suggestion, "This_constructor_function_may_be_converted_to_a_class_declaration_80002", "This constructor function may be converted to a class declaration."), + Import_may_be_converted_to_a_default_import: diag(80003, ts.DiagnosticCategory.Suggestion, "Import_may_be_converted_to_a_default_import_80003", "Import may be converted to a default import."), + JSDoc_types_may_be_moved_to_TypeScript_types: diag(80004, ts.DiagnosticCategory.Suggestion, "JSDoc_types_may_be_moved_to_TypeScript_types_80004", "JSDoc types may be moved to TypeScript types."), + require_call_may_be_converted_to_an_import: diag(80005, ts.DiagnosticCategory.Suggestion, "require_call_may_be_converted_to_an_import_80005", "'require' call may be converted to an import."), + This_may_be_converted_to_an_async_function: diag(80006, ts.DiagnosticCategory.Suggestion, "This_may_be_converted_to_an_async_function_80006", "This may be converted to an async function."), + Add_missing_super_call: diag(90001, ts.DiagnosticCategory.Message, "Add_missing_super_call_90001", "Add missing 'super()' call"), + Make_super_call_the_first_statement_in_the_constructor: diag(90002, ts.DiagnosticCategory.Message, "Make_super_call_the_first_statement_in_the_constructor_90002", "Make 'super()' call the first statement in the constructor"), + Change_extends_to_implements: diag(90003, ts.DiagnosticCategory.Message, "Change_extends_to_implements_90003", "Change 'extends' to 'implements'"), + Remove_declaration_for_Colon_0: diag(90004, ts.DiagnosticCategory.Message, "Remove_declaration_for_Colon_0_90004", "Remove declaration for: '{0}'"), + Remove_import_from_0: diag(90005, ts.DiagnosticCategory.Message, "Remove_import_from_0_90005", "Remove import from '{0}'"), + Implement_interface_0: diag(90006, ts.DiagnosticCategory.Message, "Implement_interface_0_90006", "Implement interface '{0}'"), + Implement_inherited_abstract_class: diag(90007, ts.DiagnosticCategory.Message, "Implement_inherited_abstract_class_90007", "Implement inherited abstract class"), + Add_0_to_unresolved_variable: diag(90008, ts.DiagnosticCategory.Message, "Add_0_to_unresolved_variable_90008", "Add '{0}.' to unresolved variable"), + Remove_destructuring: diag(90009, ts.DiagnosticCategory.Message, "Remove_destructuring_90009", "Remove destructuring"), + Remove_variable_statement: diag(90010, ts.DiagnosticCategory.Message, "Remove_variable_statement_90010", "Remove variable statement"), + Remove_template_tag: diag(90011, ts.DiagnosticCategory.Message, "Remove_template_tag_90011", "Remove template tag"), + Remove_type_parameters: diag(90012, ts.DiagnosticCategory.Message, "Remove_type_parameters_90012", "Remove type parameters"), + Import_0_from_module_1: diag(90013, ts.DiagnosticCategory.Message, "Import_0_from_module_1_90013", "Import '{0}' from module \"{1}\""), + Change_0_to_1: diag(90014, ts.DiagnosticCategory.Message, "Change_0_to_1_90014", "Change '{0}' to '{1}'"), + Add_0_to_existing_import_declaration_from_1: diag(90015, ts.DiagnosticCategory.Message, "Add_0_to_existing_import_declaration_from_1_90015", "Add '{0}' to existing import declaration from \"{1}\""), + Declare_property_0: diag(90016, ts.DiagnosticCategory.Message, "Declare_property_0_90016", "Declare property '{0}'"), + Add_index_signature_for_property_0: diag(90017, ts.DiagnosticCategory.Message, "Add_index_signature_for_property_0_90017", "Add index signature for property '{0}'"), + Disable_checking_for_this_file: diag(90018, ts.DiagnosticCategory.Message, "Disable_checking_for_this_file_90018", "Disable checking for this file"), + Ignore_this_error_message: diag(90019, ts.DiagnosticCategory.Message, "Ignore_this_error_message_90019", "Ignore this error message"), + Initialize_property_0_in_the_constructor: diag(90020, ts.DiagnosticCategory.Message, "Initialize_property_0_in_the_constructor_90020", "Initialize property '{0}' in the constructor"), + Initialize_static_property_0: diag(90021, ts.DiagnosticCategory.Message, "Initialize_static_property_0_90021", "Initialize static property '{0}'"), + Change_spelling_to_0: diag(90022, ts.DiagnosticCategory.Message, "Change_spelling_to_0_90022", "Change spelling to '{0}'"), + Declare_method_0: diag(90023, ts.DiagnosticCategory.Message, "Declare_method_0_90023", "Declare method '{0}'"), + Declare_static_method_0: diag(90024, ts.DiagnosticCategory.Message, "Declare_static_method_0_90024", "Declare static method '{0}'"), + Prefix_0_with_an_underscore: diag(90025, ts.DiagnosticCategory.Message, "Prefix_0_with_an_underscore_90025", "Prefix '{0}' with an underscore"), + Rewrite_as_the_indexed_access_type_0: diag(90026, ts.DiagnosticCategory.Message, "Rewrite_as_the_indexed_access_type_0_90026", "Rewrite as the indexed access type '{0}'"), + Declare_static_property_0: diag(90027, ts.DiagnosticCategory.Message, "Declare_static_property_0_90027", "Declare static property '{0}'"), + Call_decorator_expression: diag(90028, ts.DiagnosticCategory.Message, "Call_decorator_expression_90028", "Call decorator expression"), + Add_async_modifier_to_containing_function: diag(90029, ts.DiagnosticCategory.Message, "Add_async_modifier_to_containing_function_90029", "Add async modifier to containing function"), + Replace_infer_0_with_unknown: diag(90030, ts.DiagnosticCategory.Message, "Replace_infer_0_with_unknown_90030", "Replace 'infer {0}' with 'unknown'"), + Replace_all_unused_infer_with_unknown: diag(90031, ts.DiagnosticCategory.Message, "Replace_all_unused_infer_with_unknown_90031", "Replace all unused 'infer' with 'unknown'"), + Import_default_0_from_module_1: diag(90032, ts.DiagnosticCategory.Message, "Import_default_0_from_module_1_90032", "Import default '{0}' from module \"{1}\""), + Add_default_import_0_to_existing_import_declaration_from_1: diag(90033, ts.DiagnosticCategory.Message, "Add_default_import_0_to_existing_import_declaration_from_1_90033", "Add default import '{0}' to existing import declaration from \"{1}\""), + Add_parameter_name: diag(90034, ts.DiagnosticCategory.Message, "Add_parameter_name_90034", "Add parameter name"), + Convert_function_to_an_ES2015_class: diag(95001, ts.DiagnosticCategory.Message, "Convert_function_to_an_ES2015_class_95001", "Convert function to an ES2015 class"), + Convert_function_0_to_class: diag(95002, ts.DiagnosticCategory.Message, "Convert_function_0_to_class_95002", "Convert function '{0}' to class"), + Extract_to_0_in_1: diag(95004, ts.DiagnosticCategory.Message, "Extract_to_0_in_1_95004", "Extract to {0} in {1}"), + Extract_function: diag(95005, ts.DiagnosticCategory.Message, "Extract_function_95005", "Extract function"), + Extract_constant: diag(95006, ts.DiagnosticCategory.Message, "Extract_constant_95006", "Extract constant"), + Extract_to_0_in_enclosing_scope: diag(95007, ts.DiagnosticCategory.Message, "Extract_to_0_in_enclosing_scope_95007", "Extract to {0} in enclosing scope"), + Extract_to_0_in_1_scope: diag(95008, ts.DiagnosticCategory.Message, "Extract_to_0_in_1_scope_95008", "Extract to {0} in {1} scope"), + Annotate_with_type_from_JSDoc: diag(95009, ts.DiagnosticCategory.Message, "Annotate_with_type_from_JSDoc_95009", "Annotate with type from JSDoc"), + Annotate_with_types_from_JSDoc: diag(95010, ts.DiagnosticCategory.Message, "Annotate_with_types_from_JSDoc_95010", "Annotate with types from JSDoc"), + Infer_type_of_0_from_usage: diag(95011, ts.DiagnosticCategory.Message, "Infer_type_of_0_from_usage_95011", "Infer type of '{0}' from usage"), + Infer_parameter_types_from_usage: diag(95012, ts.DiagnosticCategory.Message, "Infer_parameter_types_from_usage_95012", "Infer parameter types from usage"), + Convert_to_default_import: diag(95013, ts.DiagnosticCategory.Message, "Convert_to_default_import_95013", "Convert to default import"), + Install_0: diag(95014, ts.DiagnosticCategory.Message, "Install_0_95014", "Install '{0}'"), + Replace_import_with_0: diag(95015, ts.DiagnosticCategory.Message, "Replace_import_with_0_95015", "Replace import with '{0}'."), + Use_synthetic_default_member: diag(95016, ts.DiagnosticCategory.Message, "Use_synthetic_default_member_95016", "Use synthetic 'default' member."), + Convert_to_ES6_module: diag(95017, ts.DiagnosticCategory.Message, "Convert_to_ES6_module_95017", "Convert to ES6 module"), + Add_undefined_type_to_property_0: diag(95018, ts.DiagnosticCategory.Message, "Add_undefined_type_to_property_0_95018", "Add 'undefined' type to property '{0}'"), + Add_initializer_to_property_0: diag(95019, ts.DiagnosticCategory.Message, "Add_initializer_to_property_0_95019", "Add initializer to property '{0}'"), + Add_definite_assignment_assertion_to_property_0: diag(95020, ts.DiagnosticCategory.Message, "Add_definite_assignment_assertion_to_property_0_95020", "Add definite assignment assertion to property '{0}'"), + Add_all_missing_members: diag(95022, ts.DiagnosticCategory.Message, "Add_all_missing_members_95022", "Add all missing members"), + Infer_all_types_from_usage: diag(95023, ts.DiagnosticCategory.Message, "Infer_all_types_from_usage_95023", "Infer all types from usage"), + Delete_all_unused_declarations: diag(95024, ts.DiagnosticCategory.Message, "Delete_all_unused_declarations_95024", "Delete all unused declarations"), + Prefix_all_unused_declarations_with_where_possible: diag(95025, ts.DiagnosticCategory.Message, "Prefix_all_unused_declarations_with_where_possible_95025", "Prefix all unused declarations with '_' where possible"), + Fix_all_detected_spelling_errors: diag(95026, ts.DiagnosticCategory.Message, "Fix_all_detected_spelling_errors_95026", "Fix all detected spelling errors"), + Add_initializers_to_all_uninitialized_properties: diag(95027, ts.DiagnosticCategory.Message, "Add_initializers_to_all_uninitialized_properties_95027", "Add initializers to all uninitialized properties"), + Add_definite_assignment_assertions_to_all_uninitialized_properties: diag(95028, ts.DiagnosticCategory.Message, "Add_definite_assignment_assertions_to_all_uninitialized_properties_95028", "Add definite assignment assertions to all uninitialized properties"), + Add_undefined_type_to_all_uninitialized_properties: diag(95029, ts.DiagnosticCategory.Message, "Add_undefined_type_to_all_uninitialized_properties_95029", "Add undefined type to all uninitialized properties"), + Change_all_jsdoc_style_types_to_TypeScript: diag(95030, ts.DiagnosticCategory.Message, "Change_all_jsdoc_style_types_to_TypeScript_95030", "Change all jsdoc-style types to TypeScript"), + Change_all_jsdoc_style_types_to_TypeScript_and_add_undefined_to_nullable_types: diag(95031, ts.DiagnosticCategory.Message, "Change_all_jsdoc_style_types_to_TypeScript_and_add_undefined_to_nullable_types_95031", "Change all jsdoc-style types to TypeScript (and add '| undefined' to nullable types)"), + Implement_all_unimplemented_interfaces: diag(95032, ts.DiagnosticCategory.Message, "Implement_all_unimplemented_interfaces_95032", "Implement all unimplemented interfaces"), + Install_all_missing_types_packages: diag(95033, ts.DiagnosticCategory.Message, "Install_all_missing_types_packages_95033", "Install all missing types packages"), + Rewrite_all_as_indexed_access_types: diag(95034, ts.DiagnosticCategory.Message, "Rewrite_all_as_indexed_access_types_95034", "Rewrite all as indexed access types"), + Convert_all_to_default_imports: diag(95035, ts.DiagnosticCategory.Message, "Convert_all_to_default_imports_95035", "Convert all to default imports"), + Make_all_super_calls_the_first_statement_in_their_constructor: diag(95036, ts.DiagnosticCategory.Message, "Make_all_super_calls_the_first_statement_in_their_constructor_95036", "Make all 'super()' calls the first statement in their constructor"), + Add_qualifier_to_all_unresolved_variables_matching_a_member_name: diag(95037, ts.DiagnosticCategory.Message, "Add_qualifier_to_all_unresolved_variables_matching_a_member_name_95037", "Add qualifier to all unresolved variables matching a member name"), + Change_all_extended_interfaces_to_implements: diag(95038, ts.DiagnosticCategory.Message, "Change_all_extended_interfaces_to_implements_95038", "Change all extended interfaces to 'implements'"), + Add_all_missing_super_calls: diag(95039, ts.DiagnosticCategory.Message, "Add_all_missing_super_calls_95039", "Add all missing super calls"), + Implement_all_inherited_abstract_classes: diag(95040, ts.DiagnosticCategory.Message, "Implement_all_inherited_abstract_classes_95040", "Implement all inherited abstract classes"), + Add_all_missing_async_modifiers: diag(95041, ts.DiagnosticCategory.Message, "Add_all_missing_async_modifiers_95041", "Add all missing 'async' modifiers"), + Add_ts_ignore_to_all_error_messages: diag(95042, ts.DiagnosticCategory.Message, "Add_ts_ignore_to_all_error_messages_95042", "Add '@ts-ignore' to all error messages"), + Annotate_everything_with_types_from_JSDoc: diag(95043, ts.DiagnosticCategory.Message, "Annotate_everything_with_types_from_JSDoc_95043", "Annotate everything with types from JSDoc"), + Add_to_all_uncalled_decorators: diag(95044, ts.DiagnosticCategory.Message, "Add_to_all_uncalled_decorators_95044", "Add '()' to all uncalled decorators"), + Convert_all_constructor_functions_to_classes: diag(95045, ts.DiagnosticCategory.Message, "Convert_all_constructor_functions_to_classes_95045", "Convert all constructor functions to classes"), + Generate_get_and_set_accessors: diag(95046, ts.DiagnosticCategory.Message, "Generate_get_and_set_accessors_95046", "Generate 'get' and 'set' accessors"), + Convert_require_to_import: diag(95047, ts.DiagnosticCategory.Message, "Convert_require_to_import_95047", "Convert 'require' to 'import'"), + Convert_all_require_to_import: diag(95048, ts.DiagnosticCategory.Message, "Convert_all_require_to_import_95048", "Convert all 'require' to 'import'"), + Move_to_a_new_file: diag(95049, ts.DiagnosticCategory.Message, "Move_to_a_new_file_95049", "Move to a new file"), + Remove_unreachable_code: diag(95050, ts.DiagnosticCategory.Message, "Remove_unreachable_code_95050", "Remove unreachable code"), + Remove_all_unreachable_code: diag(95051, ts.DiagnosticCategory.Message, "Remove_all_unreachable_code_95051", "Remove all unreachable code"), + Add_missing_typeof: diag(95052, ts.DiagnosticCategory.Message, "Add_missing_typeof_95052", "Add missing 'typeof'"), + Remove_unused_label: diag(95053, ts.DiagnosticCategory.Message, "Remove_unused_label_95053", "Remove unused label"), + Remove_all_unused_labels: diag(95054, ts.DiagnosticCategory.Message, "Remove_all_unused_labels_95054", "Remove all unused labels"), + Convert_0_to_mapped_object_type: diag(95055, ts.DiagnosticCategory.Message, "Convert_0_to_mapped_object_type_95055", "Convert '{0}' to mapped object type"), + Convert_namespace_import_to_named_imports: diag(95056, ts.DiagnosticCategory.Message, "Convert_namespace_import_to_named_imports_95056", "Convert namespace import to named imports"), + Convert_named_imports_to_namespace_import: diag(95057, ts.DiagnosticCategory.Message, "Convert_named_imports_to_namespace_import_95057", "Convert named imports to namespace import"), + Add_or_remove_braces_in_an_arrow_function: diag(95058, ts.DiagnosticCategory.Message, "Add_or_remove_braces_in_an_arrow_function_95058", "Add or remove braces in an arrow function"), + Add_braces_to_arrow_function: diag(95059, ts.DiagnosticCategory.Message, "Add_braces_to_arrow_function_95059", "Add braces to arrow function"), + Remove_braces_from_arrow_function: diag(95060, ts.DiagnosticCategory.Message, "Remove_braces_from_arrow_function_95060", "Remove braces from arrow function"), + Convert_default_export_to_named_export: diag(95061, ts.DiagnosticCategory.Message, "Convert_default_export_to_named_export_95061", "Convert default export to named export"), + Convert_named_export_to_default_export: diag(95062, ts.DiagnosticCategory.Message, "Convert_named_export_to_default_export_95062", "Convert named export to default export"), + Add_missing_enum_member_0: diag(95063, ts.DiagnosticCategory.Message, "Add_missing_enum_member_0_95063", "Add missing enum member '{0}'"), + Add_all_missing_imports: diag(95064, ts.DiagnosticCategory.Message, "Add_all_missing_imports_95064", "Add all missing imports"), + Convert_to_async_function: diag(95065, ts.DiagnosticCategory.Message, "Convert_to_async_function_95065", "Convert to async function"), + Convert_all_to_async_functions: diag(95066, ts.DiagnosticCategory.Message, "Convert_all_to_async_functions_95066", "Convert all to async functions"), + Generate_types_for_0: diag(95067, ts.DiagnosticCategory.Message, "Generate_types_for_0_95067", "Generate types for '{0}'"), + Generate_types_for_all_packages_without_types: diag(95068, ts.DiagnosticCategory.Message, "Generate_types_for_all_packages_without_types_95068", "Generate types for all packages without types"), + Add_unknown_conversion_for_non_overlapping_types: diag(95069, ts.DiagnosticCategory.Message, "Add_unknown_conversion_for_non_overlapping_types_95069", "Add 'unknown' conversion for non-overlapping types"), + Add_unknown_to_all_conversions_of_non_overlapping_types: diag(95070, ts.DiagnosticCategory.Message, "Add_unknown_to_all_conversions_of_non_overlapping_types_95070", "Add 'unknown' to all conversions of non-overlapping types"), + Add_missing_new_operator_to_call: diag(95071, ts.DiagnosticCategory.Message, "Add_missing_new_operator_to_call_95071", "Add missing 'new' operator to call"), + Add_missing_new_operator_to_all_calls: diag(95072, ts.DiagnosticCategory.Message, "Add_missing_new_operator_to_all_calls_95072", "Add missing 'new' operator to all calls"), + Add_names_to_all_parameters_without_names: diag(95073, ts.DiagnosticCategory.Message, "Add_names_to_all_parameters_without_names_95073", "Add names to all parameters without names"), + }; +})(ts || (ts = {})); +var ts; +(function (ts) { + var _a; + /* @internal */ + function tokenIsIdentifierOrKeyword(token) { + return token >= 72 /* Identifier */; + } + ts.tokenIsIdentifierOrKeyword = tokenIsIdentifierOrKeyword; + /* @internal */ + function tokenIsIdentifierOrKeywordOrGreaterThan(token) { + return token === 30 /* GreaterThanToken */ || tokenIsIdentifierOrKeyword(token); + } + ts.tokenIsIdentifierOrKeywordOrGreaterThan = tokenIsIdentifierOrKeywordOrGreaterThan; + var textToKeywordObj = (_a = { + abstract: 118 /* AbstractKeyword */, + any: 120 /* AnyKeyword */, + as: 119 /* AsKeyword */, + bigint: 146 /* BigIntKeyword */, + boolean: 123 /* BooleanKeyword */, + break: 73 /* BreakKeyword */, + case: 74 /* CaseKeyword */, + catch: 75 /* CatchKeyword */, + class: 76 /* ClassKeyword */, + continue: 78 /* ContinueKeyword */, + const: 77 /* ConstKeyword */ + }, + _a["" + "constructor"] = 124 /* ConstructorKeyword */, + _a.debugger = 79 /* DebuggerKeyword */, + _a.declare = 125 /* DeclareKeyword */, + _a.default = 80 /* DefaultKeyword */, + _a.delete = 81 /* DeleteKeyword */, + _a.do = 82 /* DoKeyword */, + _a.else = 83 /* ElseKeyword */, + _a.enum = 84 /* EnumKeyword */, + _a.export = 85 /* ExportKeyword */, + _a.extends = 86 /* ExtendsKeyword */, + _a.false = 87 /* FalseKeyword */, + _a.finally = 88 /* FinallyKeyword */, + _a.for = 89 /* ForKeyword */, + _a.from = 144 /* FromKeyword */, + _a.function = 90 /* FunctionKeyword */, + _a.get = 126 /* GetKeyword */, + _a.if = 91 /* IfKeyword */, + _a.implements = 109 /* ImplementsKeyword */, + _a.import = 92 /* ImportKeyword */, + _a.in = 93 /* InKeyword */, + _a.infer = 127 /* InferKeyword */, + _a.instanceof = 94 /* InstanceOfKeyword */, + _a.interface = 110 /* InterfaceKeyword */, + _a.is = 128 /* IsKeyword */, + _a.keyof = 129 /* KeyOfKeyword */, + _a.let = 111 /* LetKeyword */, + _a.module = 130 /* ModuleKeyword */, + _a.namespace = 131 /* NamespaceKeyword */, + _a.never = 132 /* NeverKeyword */, + _a.new = 95 /* NewKeyword */, + _a.null = 96 /* NullKeyword */, + _a.number = 135 /* NumberKeyword */, + _a.object = 136 /* ObjectKeyword */, + _a.package = 112 /* PackageKeyword */, + _a.private = 113 /* PrivateKeyword */, + _a.protected = 114 /* ProtectedKeyword */, + _a.public = 115 /* PublicKeyword */, + _a.readonly = 133 /* ReadonlyKeyword */, + _a.require = 134 /* RequireKeyword */, + _a.global = 145 /* GlobalKeyword */, + _a.return = 97 /* ReturnKeyword */, + _a.set = 137 /* SetKeyword */, + _a.static = 116 /* StaticKeyword */, + _a.string = 138 /* StringKeyword */, + _a.super = 98 /* SuperKeyword */, + _a.switch = 99 /* SwitchKeyword */, + _a.symbol = 139 /* SymbolKeyword */, + _a.this = 100 /* ThisKeyword */, + _a.throw = 101 /* ThrowKeyword */, + _a.true = 102 /* TrueKeyword */, + _a.try = 103 /* TryKeyword */, + _a.type = 140 /* TypeKeyword */, + _a.typeof = 104 /* TypeOfKeyword */, + _a.undefined = 141 /* UndefinedKeyword */, + _a.unique = 142 /* UniqueKeyword */, + _a.unknown = 143 /* UnknownKeyword */, + _a.var = 105 /* VarKeyword */, + _a.void = 106 /* VoidKeyword */, + _a.while = 107 /* WhileKeyword */, + _a.with = 108 /* WithKeyword */, + _a.yield = 117 /* YieldKeyword */, + _a.async = 121 /* AsyncKeyword */, + _a.await = 122 /* AwaitKeyword */, + _a.of = 147 /* OfKeyword */, + _a); + var textToKeyword = ts.createMapFromTemplate(textToKeywordObj); + var textToToken = ts.createMapFromTemplate(__assign({}, textToKeywordObj, { "{": 18 /* OpenBraceToken */, "}": 19 /* CloseBraceToken */, "(": 20 /* OpenParenToken */, ")": 21 /* CloseParenToken */, "[": 22 /* OpenBracketToken */, "]": 23 /* CloseBracketToken */, ".": 24 /* DotToken */, "...": 25 /* DotDotDotToken */, ";": 26 /* SemicolonToken */, ",": 27 /* CommaToken */, "<": 28 /* LessThanToken */, ">": 30 /* GreaterThanToken */, "<=": 31 /* LessThanEqualsToken */, ">=": 32 /* GreaterThanEqualsToken */, "==": 33 /* EqualsEqualsToken */, "!=": 34 /* ExclamationEqualsToken */, "===": 35 /* EqualsEqualsEqualsToken */, "!==": 36 /* ExclamationEqualsEqualsToken */, "=>": 37 /* EqualsGreaterThanToken */, "+": 38 /* PlusToken */, "-": 39 /* MinusToken */, "**": 41 /* AsteriskAsteriskToken */, "*": 40 /* AsteriskToken */, "/": 42 /* SlashToken */, "%": 43 /* PercentToken */, "++": 44 /* PlusPlusToken */, "--": 45 /* MinusMinusToken */, "<<": 46 /* LessThanLessThanToken */, ">": 47 /* GreaterThanGreaterThanToken */, ">>>": 48 /* GreaterThanGreaterThanGreaterThanToken */, "&": 49 /* AmpersandToken */, "|": 50 /* BarToken */, "^": 51 /* CaretToken */, "!": 52 /* ExclamationToken */, "~": 53 /* TildeToken */, "&&": 54 /* AmpersandAmpersandToken */, "||": 55 /* BarBarToken */, "?": 56 /* QuestionToken */, ":": 57 /* ColonToken */, "=": 59 /* EqualsToken */, "+=": 60 /* PlusEqualsToken */, "-=": 61 /* MinusEqualsToken */, "*=": 62 /* AsteriskEqualsToken */, "**=": 63 /* AsteriskAsteriskEqualsToken */, "/=": 64 /* SlashEqualsToken */, "%=": 65 /* PercentEqualsToken */, "<<=": 66 /* LessThanLessThanEqualsToken */, ">>=": 67 /* GreaterThanGreaterThanEqualsToken */, ">>>=": 68 /* GreaterThanGreaterThanGreaterThanEqualsToken */, "&=": 69 /* AmpersandEqualsToken */, "|=": 70 /* BarEqualsToken */, "^=": 71 /* CaretEqualsToken */, "@": 58 /* AtToken */ })); + /* + As per ECMAScript Language Specification 3th Edition, Section 7.6: Identifiers + IdentifierStart :: + Can contain Unicode 3.0.0 categories: + Uppercase letter (Lu), + Lowercase letter (Ll), + Titlecase letter (Lt), + Modifier letter (Lm), + Other letter (Lo), or + Letter number (Nl). + IdentifierPart :: = + Can contain IdentifierStart + Unicode 3.0.0 categories: + Non-spacing mark (Mn), + Combining spacing mark (Mc), + Decimal number (Nd), or + Connector punctuation (Pc). + + Codepoint ranges for ES3 Identifiers are extracted from the Unicode 3.0.0 specification at: + http://www.unicode.org/Public/3.0-Update/UnicodeData-3.0.0.txt + */ + var unicodeES3IdentifierStart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 543, 546, 563, 592, 685, 688, 696, 699, 705, 720, 721, 736, 740, 750, 750, 890, 890, 902, 902, 904, 906, 908, 908, 910, 929, 931, 974, 976, 983, 986, 1011, 1024, 1153, 1164, 1220, 1223, 1224, 1227, 1228, 1232, 1269, 1272, 1273, 1329, 1366, 1369, 1369, 1377, 1415, 1488, 1514, 1520, 1522, 1569, 1594, 1600, 1610, 1649, 1747, 1749, 1749, 1765, 1766, 1786, 1788, 1808, 1808, 1810, 1836, 1920, 1957, 2309, 2361, 2365, 2365, 2384, 2384, 2392, 2401, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2524, 2525, 2527, 2529, 2544, 2545, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2649, 2652, 2654, 2654, 2674, 2676, 2693, 2699, 2701, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2749, 2749, 2768, 2768, 2784, 2784, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2870, 2873, 2877, 2877, 2908, 2909, 2911, 2913, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 2997, 2999, 3001, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3168, 3169, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3294, 3294, 3296, 3297, 3333, 3340, 3342, 3344, 3346, 3368, 3370, 3385, 3424, 3425, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3585, 3632, 3634, 3635, 3648, 3654, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3760, 3762, 3763, 3773, 3773, 3776, 3780, 3782, 3782, 3804, 3805, 3840, 3840, 3904, 3911, 3913, 3946, 3976, 3979, 4096, 4129, 4131, 4135, 4137, 4138, 4176, 4181, 4256, 4293, 4304, 4342, 4352, 4441, 4447, 4514, 4520, 4601, 4608, 4614, 4616, 4678, 4680, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4742, 4744, 4744, 4746, 4749, 4752, 4782, 4784, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4814, 4816, 4822, 4824, 4846, 4848, 4878, 4880, 4880, 4882, 4885, 4888, 4894, 4896, 4934, 4936, 4954, 5024, 5108, 5121, 5740, 5743, 5750, 5761, 5786, 5792, 5866, 6016, 6067, 6176, 6263, 6272, 6312, 7680, 7835, 7840, 7929, 7936, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8319, 8319, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8497, 8499, 8505, 8544, 8579, 12293, 12295, 12321, 12329, 12337, 12341, 12344, 12346, 12353, 12436, 12445, 12446, 12449, 12538, 12540, 12542, 12549, 12588, 12593, 12686, 12704, 12727, 13312, 19893, 19968, 40869, 40960, 42124, 44032, 55203, 63744, 64045, 64256, 64262, 64275, 64279, 64285, 64285, 64287, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65136, 65138, 65140, 65140, 65142, 65276, 65313, 65338, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500,]; + var unicodeES3IdentifierPart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 543, 546, 563, 592, 685, 688, 696, 699, 705, 720, 721, 736, 740, 750, 750, 768, 846, 864, 866, 890, 890, 902, 902, 904, 906, 908, 908, 910, 929, 931, 974, 976, 983, 986, 1011, 1024, 1153, 1155, 1158, 1164, 1220, 1223, 1224, 1227, 1228, 1232, 1269, 1272, 1273, 1329, 1366, 1369, 1369, 1377, 1415, 1425, 1441, 1443, 1465, 1467, 1469, 1471, 1471, 1473, 1474, 1476, 1476, 1488, 1514, 1520, 1522, 1569, 1594, 1600, 1621, 1632, 1641, 1648, 1747, 1749, 1756, 1759, 1768, 1770, 1773, 1776, 1788, 1808, 1836, 1840, 1866, 1920, 1968, 2305, 2307, 2309, 2361, 2364, 2381, 2384, 2388, 2392, 2403, 2406, 2415, 2433, 2435, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2492, 2492, 2494, 2500, 2503, 2504, 2507, 2509, 2519, 2519, 2524, 2525, 2527, 2531, 2534, 2545, 2562, 2562, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2620, 2620, 2622, 2626, 2631, 2632, 2635, 2637, 2649, 2652, 2654, 2654, 2662, 2676, 2689, 2691, 2693, 2699, 2701, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2748, 2757, 2759, 2761, 2763, 2765, 2768, 2768, 2784, 2784, 2790, 2799, 2817, 2819, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2870, 2873, 2876, 2883, 2887, 2888, 2891, 2893, 2902, 2903, 2908, 2909, 2911, 2913, 2918, 2927, 2946, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 2997, 2999, 3001, 3006, 3010, 3014, 3016, 3018, 3021, 3031, 3031, 3047, 3055, 3073, 3075, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3134, 3140, 3142, 3144, 3146, 3149, 3157, 3158, 3168, 3169, 3174, 3183, 3202, 3203, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3262, 3268, 3270, 3272, 3274, 3277, 3285, 3286, 3294, 3294, 3296, 3297, 3302, 3311, 3330, 3331, 3333, 3340, 3342, 3344, 3346, 3368, 3370, 3385, 3390, 3395, 3398, 3400, 3402, 3405, 3415, 3415, 3424, 3425, 3430, 3439, 3458, 3459, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3530, 3530, 3535, 3540, 3542, 3542, 3544, 3551, 3570, 3571, 3585, 3642, 3648, 3662, 3664, 3673, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3769, 3771, 3773, 3776, 3780, 3782, 3782, 3784, 3789, 3792, 3801, 3804, 3805, 3840, 3840, 3864, 3865, 3872, 3881, 3893, 3893, 3895, 3895, 3897, 3897, 3902, 3911, 3913, 3946, 3953, 3972, 3974, 3979, 3984, 3991, 3993, 4028, 4038, 4038, 4096, 4129, 4131, 4135, 4137, 4138, 4140, 4146, 4150, 4153, 4160, 4169, 4176, 4185, 4256, 4293, 4304, 4342, 4352, 4441, 4447, 4514, 4520, 4601, 4608, 4614, 4616, 4678, 4680, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4742, 4744, 4744, 4746, 4749, 4752, 4782, 4784, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4814, 4816, 4822, 4824, 4846, 4848, 4878, 4880, 4880, 4882, 4885, 4888, 4894, 4896, 4934, 4936, 4954, 4969, 4977, 5024, 5108, 5121, 5740, 5743, 5750, 5761, 5786, 5792, 5866, 6016, 6099, 6112, 6121, 6160, 6169, 6176, 6263, 6272, 6313, 7680, 7835, 7840, 7929, 7936, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8255, 8256, 8319, 8319, 8400, 8412, 8417, 8417, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8497, 8499, 8505, 8544, 8579, 12293, 12295, 12321, 12335, 12337, 12341, 12344, 12346, 12353, 12436, 12441, 12442, 12445, 12446, 12449, 12542, 12549, 12588, 12593, 12686, 12704, 12727, 13312, 19893, 19968, 40869, 40960, 42124, 44032, 55203, 63744, 64045, 64256, 64262, 64275, 64279, 64285, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65056, 65059, 65075, 65076, 65101, 65103, 65136, 65138, 65140, 65140, 65142, 65276, 65296, 65305, 65313, 65338, 65343, 65343, 65345, 65370, 65381, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500,]; + /* + As per ECMAScript Language Specification 5th Edition, Section 7.6: ISyntaxToken Names and Identifiers + IdentifierStart :: + Can contain Unicode 6.2 categories: + Uppercase letter (Lu), + Lowercase letter (Ll), + Titlecase letter (Lt), + Modifier letter (Lm), + Other letter (Lo), or + Letter number (Nl). + IdentifierPart :: + Can contain IdentifierStart + Unicode 6.2 categories: + Non-spacing mark (Mn), + Combining spacing mark (Mc), + Decimal number (Nd), + Connector punctuation (Pc), + , or + . + + Codepoint ranges for ES5 Identifiers are extracted from the Unicode 6.2 specification at: + http://www.unicode.org/Public/6.2.0/ucd/UnicodeData.txt + */ + var unicodeES5IdentifierStart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 705, 710, 721, 736, 740, 748, 748, 750, 750, 880, 884, 886, 887, 890, 893, 902, 902, 904, 906, 908, 908, 910, 929, 931, 1013, 1015, 1153, 1162, 1319, 1329, 1366, 1369, 1369, 1377, 1415, 1488, 1514, 1520, 1522, 1568, 1610, 1646, 1647, 1649, 1747, 1749, 1749, 1765, 1766, 1774, 1775, 1786, 1788, 1791, 1791, 1808, 1808, 1810, 1839, 1869, 1957, 1969, 1969, 1994, 2026, 2036, 2037, 2042, 2042, 2048, 2069, 2074, 2074, 2084, 2084, 2088, 2088, 2112, 2136, 2208, 2208, 2210, 2220, 2308, 2361, 2365, 2365, 2384, 2384, 2392, 2401, 2417, 2423, 2425, 2431, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2493, 2493, 2510, 2510, 2524, 2525, 2527, 2529, 2544, 2545, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2649, 2652, 2654, 2654, 2674, 2676, 2693, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2749, 2749, 2768, 2768, 2784, 2785, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2869, 2873, 2877, 2877, 2908, 2909, 2911, 2913, 2929, 2929, 2947, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 3001, 3024, 3024, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3133, 3133, 3160, 3161, 3168, 3169, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3261, 3261, 3294, 3294, 3296, 3297, 3313, 3314, 3333, 3340, 3342, 3344, 3346, 3386, 3389, 3389, 3406, 3406, 3424, 3425, 3450, 3455, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3585, 3632, 3634, 3635, 3648, 3654, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3760, 3762, 3763, 3773, 3773, 3776, 3780, 3782, 3782, 3804, 3807, 3840, 3840, 3904, 3911, 3913, 3948, 3976, 3980, 4096, 4138, 4159, 4159, 4176, 4181, 4186, 4189, 4193, 4193, 4197, 4198, 4206, 4208, 4213, 4225, 4238, 4238, 4256, 4293, 4295, 4295, 4301, 4301, 4304, 4346, 4348, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4744, 4746, 4749, 4752, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4822, 4824, 4880, 4882, 4885, 4888, 4954, 4992, 5007, 5024, 5108, 5121, 5740, 5743, 5759, 5761, 5786, 5792, 5866, 5870, 5872, 5888, 5900, 5902, 5905, 5920, 5937, 5952, 5969, 5984, 5996, 5998, 6000, 6016, 6067, 6103, 6103, 6108, 6108, 6176, 6263, 6272, 6312, 6314, 6314, 6320, 6389, 6400, 6428, 6480, 6509, 6512, 6516, 6528, 6571, 6593, 6599, 6656, 6678, 6688, 6740, 6823, 6823, 6917, 6963, 6981, 6987, 7043, 7072, 7086, 7087, 7098, 7141, 7168, 7203, 7245, 7247, 7258, 7293, 7401, 7404, 7406, 7409, 7413, 7414, 7424, 7615, 7680, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8305, 8305, 8319, 8319, 8336, 8348, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8505, 8508, 8511, 8517, 8521, 8526, 8526, 8544, 8584, 11264, 11310, 11312, 11358, 11360, 11492, 11499, 11502, 11506, 11507, 11520, 11557, 11559, 11559, 11565, 11565, 11568, 11623, 11631, 11631, 11648, 11670, 11680, 11686, 11688, 11694, 11696, 11702, 11704, 11710, 11712, 11718, 11720, 11726, 11728, 11734, 11736, 11742, 11823, 11823, 12293, 12295, 12321, 12329, 12337, 12341, 12344, 12348, 12353, 12438, 12445, 12447, 12449, 12538, 12540, 12543, 12549, 12589, 12593, 12686, 12704, 12730, 12784, 12799, 13312, 19893, 19968, 40908, 40960, 42124, 42192, 42237, 42240, 42508, 42512, 42527, 42538, 42539, 42560, 42606, 42623, 42647, 42656, 42735, 42775, 42783, 42786, 42888, 42891, 42894, 42896, 42899, 42912, 42922, 43000, 43009, 43011, 43013, 43015, 43018, 43020, 43042, 43072, 43123, 43138, 43187, 43250, 43255, 43259, 43259, 43274, 43301, 43312, 43334, 43360, 43388, 43396, 43442, 43471, 43471, 43520, 43560, 43584, 43586, 43588, 43595, 43616, 43638, 43642, 43642, 43648, 43695, 43697, 43697, 43701, 43702, 43705, 43709, 43712, 43712, 43714, 43714, 43739, 43741, 43744, 43754, 43762, 43764, 43777, 43782, 43785, 43790, 43793, 43798, 43808, 43814, 43816, 43822, 43968, 44002, 44032, 55203, 55216, 55238, 55243, 55291, 63744, 64109, 64112, 64217, 64256, 64262, 64275, 64279, 64285, 64285, 64287, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65136, 65140, 65142, 65276, 65313, 65338, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500,]; + var unicodeES5IdentifierPart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 705, 710, 721, 736, 740, 748, 748, 750, 750, 768, 884, 886, 887, 890, 893, 902, 902, 904, 906, 908, 908, 910, 929, 931, 1013, 1015, 1153, 1155, 1159, 1162, 1319, 1329, 1366, 1369, 1369, 1377, 1415, 1425, 1469, 1471, 1471, 1473, 1474, 1476, 1477, 1479, 1479, 1488, 1514, 1520, 1522, 1552, 1562, 1568, 1641, 1646, 1747, 1749, 1756, 1759, 1768, 1770, 1788, 1791, 1791, 1808, 1866, 1869, 1969, 1984, 2037, 2042, 2042, 2048, 2093, 2112, 2139, 2208, 2208, 2210, 2220, 2276, 2302, 2304, 2403, 2406, 2415, 2417, 2423, 2425, 2431, 2433, 2435, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2492, 2500, 2503, 2504, 2507, 2510, 2519, 2519, 2524, 2525, 2527, 2531, 2534, 2545, 2561, 2563, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2620, 2620, 2622, 2626, 2631, 2632, 2635, 2637, 2641, 2641, 2649, 2652, 2654, 2654, 2662, 2677, 2689, 2691, 2693, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2748, 2757, 2759, 2761, 2763, 2765, 2768, 2768, 2784, 2787, 2790, 2799, 2817, 2819, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2869, 2873, 2876, 2884, 2887, 2888, 2891, 2893, 2902, 2903, 2908, 2909, 2911, 2915, 2918, 2927, 2929, 2929, 2946, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 3001, 3006, 3010, 3014, 3016, 3018, 3021, 3024, 3024, 3031, 3031, 3046, 3055, 3073, 3075, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3133, 3140, 3142, 3144, 3146, 3149, 3157, 3158, 3160, 3161, 3168, 3171, 3174, 3183, 3202, 3203, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3260, 3268, 3270, 3272, 3274, 3277, 3285, 3286, 3294, 3294, 3296, 3299, 3302, 3311, 3313, 3314, 3330, 3331, 3333, 3340, 3342, 3344, 3346, 3386, 3389, 3396, 3398, 3400, 3402, 3406, 3415, 3415, 3424, 3427, 3430, 3439, 3450, 3455, 3458, 3459, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3530, 3530, 3535, 3540, 3542, 3542, 3544, 3551, 3570, 3571, 3585, 3642, 3648, 3662, 3664, 3673, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3769, 3771, 3773, 3776, 3780, 3782, 3782, 3784, 3789, 3792, 3801, 3804, 3807, 3840, 3840, 3864, 3865, 3872, 3881, 3893, 3893, 3895, 3895, 3897, 3897, 3902, 3911, 3913, 3948, 3953, 3972, 3974, 3991, 3993, 4028, 4038, 4038, 4096, 4169, 4176, 4253, 4256, 4293, 4295, 4295, 4301, 4301, 4304, 4346, 4348, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4744, 4746, 4749, 4752, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4822, 4824, 4880, 4882, 4885, 4888, 4954, 4957, 4959, 4992, 5007, 5024, 5108, 5121, 5740, 5743, 5759, 5761, 5786, 5792, 5866, 5870, 5872, 5888, 5900, 5902, 5908, 5920, 5940, 5952, 5971, 5984, 5996, 5998, 6000, 6002, 6003, 6016, 6099, 6103, 6103, 6108, 6109, 6112, 6121, 6155, 6157, 6160, 6169, 6176, 6263, 6272, 6314, 6320, 6389, 6400, 6428, 6432, 6443, 6448, 6459, 6470, 6509, 6512, 6516, 6528, 6571, 6576, 6601, 6608, 6617, 6656, 6683, 6688, 6750, 6752, 6780, 6783, 6793, 6800, 6809, 6823, 6823, 6912, 6987, 6992, 7001, 7019, 7027, 7040, 7155, 7168, 7223, 7232, 7241, 7245, 7293, 7376, 7378, 7380, 7414, 7424, 7654, 7676, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8204, 8205, 8255, 8256, 8276, 8276, 8305, 8305, 8319, 8319, 8336, 8348, 8400, 8412, 8417, 8417, 8421, 8432, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8505, 8508, 8511, 8517, 8521, 8526, 8526, 8544, 8584, 11264, 11310, 11312, 11358, 11360, 11492, 11499, 11507, 11520, 11557, 11559, 11559, 11565, 11565, 11568, 11623, 11631, 11631, 11647, 11670, 11680, 11686, 11688, 11694, 11696, 11702, 11704, 11710, 11712, 11718, 11720, 11726, 11728, 11734, 11736, 11742, 11744, 11775, 11823, 11823, 12293, 12295, 12321, 12335, 12337, 12341, 12344, 12348, 12353, 12438, 12441, 12442, 12445, 12447, 12449, 12538, 12540, 12543, 12549, 12589, 12593, 12686, 12704, 12730, 12784, 12799, 13312, 19893, 19968, 40908, 40960, 42124, 42192, 42237, 42240, 42508, 42512, 42539, 42560, 42607, 42612, 42621, 42623, 42647, 42655, 42737, 42775, 42783, 42786, 42888, 42891, 42894, 42896, 42899, 42912, 42922, 43000, 43047, 43072, 43123, 43136, 43204, 43216, 43225, 43232, 43255, 43259, 43259, 43264, 43309, 43312, 43347, 43360, 43388, 43392, 43456, 43471, 43481, 43520, 43574, 43584, 43597, 43600, 43609, 43616, 43638, 43642, 43643, 43648, 43714, 43739, 43741, 43744, 43759, 43762, 43766, 43777, 43782, 43785, 43790, 43793, 43798, 43808, 43814, 43816, 43822, 43968, 44010, 44012, 44013, 44016, 44025, 44032, 55203, 55216, 55238, 55243, 55291, 63744, 64109, 64112, 64217, 64256, 64262, 64275, 64279, 64285, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65024, 65039, 65056, 65062, 65075, 65076, 65101, 65103, 65136, 65140, 65142, 65276, 65296, 65305, 65313, 65338, 65343, 65343, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500,]; + function lookupInUnicodeMap(code, map) { + // Bail out quickly if it couldn't possibly be in the map. + if (code < map[0]) { + return false; + } + // Perform binary search in one of the Unicode range maps + var lo = 0; + var hi = map.length; + var mid; + while (lo + 1 < hi) { + mid = lo + (hi - lo) / 2; + // mid has to be even to catch a range's beginning + mid -= mid % 2; + if (map[mid] <= code && code <= map[mid + 1]) { + return true; + } + if (code < map[mid]) { + hi = mid; + } + else { + lo = mid + 2; + } + } + return false; + } + /* @internal */ function isUnicodeIdentifierStart(code, languageVersion) { + return languageVersion >= 1 /* ES5 */ ? + lookupInUnicodeMap(code, unicodeES5IdentifierStart) : + lookupInUnicodeMap(code, unicodeES3IdentifierStart); + } + ts.isUnicodeIdentifierStart = isUnicodeIdentifierStart; + function isUnicodeIdentifierPart(code, languageVersion) { + return languageVersion >= 1 /* ES5 */ ? + lookupInUnicodeMap(code, unicodeES5IdentifierPart) : + lookupInUnicodeMap(code, unicodeES3IdentifierPart); + } + function makeReverseMap(source) { + var result = []; + source.forEach(function (value, name) { + result[value] = name; + }); + return result; + } + var tokenStrings = makeReverseMap(textToToken); + function tokenToString(t) { + return tokenStrings[t]; + } + ts.tokenToString = tokenToString; + /* @internal */ + function stringToToken(s) { + return textToToken.get(s); + } + ts.stringToToken = stringToToken; + /* @internal */ + function computeLineStarts(text) { + var result = new Array(); + var pos = 0; + var lineStart = 0; + while (pos < text.length) { + var ch = text.charCodeAt(pos); + pos++; + switch (ch) { + case 13 /* carriageReturn */: + if (text.charCodeAt(pos) === 10 /* lineFeed */) { + pos++; + } + // falls through + case 10 /* lineFeed */: + result.push(lineStart); + lineStart = pos; + break; + default: + if (ch > 127 /* maxAsciiCharacter */ && isLineBreak(ch)) { + result.push(lineStart); + lineStart = pos; + } + break; + } + } + result.push(lineStart); + return result; + } + ts.computeLineStarts = computeLineStarts; + function getPositionOfLineAndCharacter(sourceFile, line, character) { + return computePositionOfLineAndCharacter(getLineStarts(sourceFile), line, character, sourceFile.text); + } + ts.getPositionOfLineAndCharacter = getPositionOfLineAndCharacter; + /* @internal */ + function getPositionOfLineAndCharacterWithEdits(sourceFile, line, character) { + return computePositionOfLineAndCharacter(getLineStarts(sourceFile), line, character, sourceFile.text, /*allowEdits*/ true); + } + ts.getPositionOfLineAndCharacterWithEdits = getPositionOfLineAndCharacterWithEdits; + /* @internal */ + function computePositionOfLineAndCharacter(lineStarts, line, character, debugText, allowEdits) { + if (line < 0 || line >= lineStarts.length) { + if (allowEdits) { + // Clamp line to nearest allowable value + line = line < 0 ? 0 : line >= lineStarts.length ? lineStarts.length - 1 : line; + } + else { + ts.Debug.fail("Bad line number. Line: " + line + ", lineStarts.length: " + lineStarts.length + " , line map is correct? " + (debugText !== undefined ? ts.arraysEqual(lineStarts, computeLineStarts(debugText)) : "unknown")); + } + } + var res = lineStarts[line] + character; + if (allowEdits) { + // Clamp to nearest allowable values to allow the underlying to be edited without crashing (accuracy is lost, instead) + // TODO: Somehow track edits between file as it was during the creation of sourcemap we have and the current file and + // apply them to the computed position to improve accuracy + return res > lineStarts[line + 1] ? lineStarts[line + 1] : typeof debugText === "string" && res > debugText.length ? debugText.length : res; + } + if (line < lineStarts.length - 1) { + ts.Debug.assert(res < lineStarts[line + 1]); + } + else if (debugText !== undefined) { + ts.Debug.assert(res <= debugText.length); // Allow single character overflow for trailing newline + } + return res; + } + ts.computePositionOfLineAndCharacter = computePositionOfLineAndCharacter; + /* @internal */ + function getLineStarts(sourceFile) { + return sourceFile.lineMap || (sourceFile.lineMap = computeLineStarts(sourceFile.text)); + } + ts.getLineStarts = getLineStarts; + /* @internal */ + /** + * We assume the first line starts at position 0 and 'position' is non-negative. + */ + function computeLineAndCharacterOfPosition(lineStarts, position) { + var lineNumber = ts.binarySearch(lineStarts, position, ts.identity, ts.compareValues); + if (lineNumber < 0) { + // If the actual position was not found, + // the binary search returns the 2's-complement of the next line start + // e.g. if the line starts at [5, 10, 23, 80] and the position requested was 20 + // then the search will return -2. + // + // We want the index of the previous line start, so we subtract 1. + // Review 2's-complement if this is confusing. + lineNumber = ~lineNumber - 1; + ts.Debug.assert(lineNumber !== -1, "position cannot precede the beginning of the file"); + } + return { + line: lineNumber, + character: position - lineStarts[lineNumber] + }; + } + ts.computeLineAndCharacterOfPosition = computeLineAndCharacterOfPosition; + function getLineAndCharacterOfPosition(sourceFile, position) { + return computeLineAndCharacterOfPosition(getLineStarts(sourceFile), position); + } + ts.getLineAndCharacterOfPosition = getLineAndCharacterOfPosition; + function isWhiteSpaceLike(ch) { + return isWhiteSpaceSingleLine(ch) || isLineBreak(ch); + } + ts.isWhiteSpaceLike = isWhiteSpaceLike; + /** Does not include line breaks. For that, see isWhiteSpaceLike. */ + function isWhiteSpaceSingleLine(ch) { + // Note: nextLine is in the Zs space, and should be considered to be a whitespace. + // It is explicitly not a line-break as it isn't in the exact set specified by EcmaScript. + return ch === 32 /* space */ || + ch === 9 /* tab */ || + ch === 11 /* verticalTab */ || + ch === 12 /* formFeed */ || + ch === 160 /* nonBreakingSpace */ || + ch === 133 /* nextLine */ || + ch === 5760 /* ogham */ || + ch >= 8192 /* enQuad */ && ch <= 8203 /* zeroWidthSpace */ || + ch === 8239 /* narrowNoBreakSpace */ || + ch === 8287 /* mathematicalSpace */ || + ch === 12288 /* ideographicSpace */ || + ch === 65279 /* byteOrderMark */; + } + ts.isWhiteSpaceSingleLine = isWhiteSpaceSingleLine; + function isLineBreak(ch) { + // ES5 7.3: + // The ECMAScript line terminator characters are listed in Table 3. + // Table 3: Line Terminator Characters + // Code Unit Value Name Formal Name + // \u000A Line Feed + // \u000D Carriage Return + // \u2028 Line separator + // \u2029 Paragraph separator + // Only the characters in Table 3 are treated as line terminators. Other new line or line + // breaking characters are treated as white space but not as line terminators. + return ch === 10 /* lineFeed */ || + ch === 13 /* carriageReturn */ || + ch === 8232 /* lineSeparator */ || + ch === 8233 /* paragraphSeparator */; + } + ts.isLineBreak = isLineBreak; + function isDigit(ch) { + return ch >= 48 /* _0 */ && ch <= 57 /* _9 */; + } + /* @internal */ + function isOctalDigit(ch) { + return ch >= 48 /* _0 */ && ch <= 55 /* _7 */; + } + ts.isOctalDigit = isOctalDigit; + function couldStartTrivia(text, pos) { + // Keep in sync with skipTrivia + var ch = text.charCodeAt(pos); + switch (ch) { + case 13 /* carriageReturn */: + case 10 /* lineFeed */: + case 9 /* tab */: + case 11 /* verticalTab */: + case 12 /* formFeed */: + case 32 /* space */: + case 47 /* slash */: + // starts of normal trivia + case 60 /* lessThan */: + case 124 /* bar */: + case 61 /* equals */: + case 62 /* greaterThan */: + // Starts of conflict marker trivia + return true; + case 35 /* hash */: + // Only if its the beginning can we have #! trivia + return pos === 0; + default: + return ch > 127 /* maxAsciiCharacter */; + } + } + ts.couldStartTrivia = couldStartTrivia; + /* @internal */ + function skipTrivia(text, pos, stopAfterLineBreak, stopAtComments) { + if (stopAtComments === void 0) { stopAtComments = false; } + if (ts.positionIsSynthesized(pos)) { + return pos; + } + // Keep in sync with couldStartTrivia + while (true) { + var ch = text.charCodeAt(pos); + switch (ch) { + case 13 /* carriageReturn */: + if (text.charCodeAt(pos + 1) === 10 /* lineFeed */) { + pos++; + } + // falls through + case 10 /* lineFeed */: + pos++; + if (stopAfterLineBreak) { + return pos; + } + continue; + case 9 /* tab */: + case 11 /* verticalTab */: + case 12 /* formFeed */: + case 32 /* space */: + pos++; + continue; + case 47 /* slash */: + if (stopAtComments) { + break; + } + if (text.charCodeAt(pos + 1) === 47 /* slash */) { + pos += 2; + while (pos < text.length) { + if (isLineBreak(text.charCodeAt(pos))) { + break; + } + pos++; + } + continue; + } + if (text.charCodeAt(pos + 1) === 42 /* asterisk */) { + pos += 2; + while (pos < text.length) { + if (text.charCodeAt(pos) === 42 /* asterisk */ && text.charCodeAt(pos + 1) === 47 /* slash */) { + pos += 2; + break; + } + pos++; + } + continue; + } + break; + case 60 /* lessThan */: + case 124 /* bar */: + case 61 /* equals */: + case 62 /* greaterThan */: + if (isConflictMarkerTrivia(text, pos)) { + pos = scanConflictMarkerTrivia(text, pos); + continue; + } + break; + case 35 /* hash */: + if (pos === 0 && isShebangTrivia(text, pos)) { + pos = scanShebangTrivia(text, pos); + continue; + } + break; + default: + if (ch > 127 /* maxAsciiCharacter */ && (isWhiteSpaceLike(ch))) { + pos++; + continue; + } + break; + } + return pos; + } + } + ts.skipTrivia = skipTrivia; + // All conflict markers consist of the same character repeated seven times. If it is + // a <<<<<<< or >>>>>>> marker then it is also followed by a space. + var mergeConflictMarkerLength = "<<<<<<<".length; + function isConflictMarkerTrivia(text, pos) { + ts.Debug.assert(pos >= 0); + // Conflict markers must be at the start of a line. + if (pos === 0 || isLineBreak(text.charCodeAt(pos - 1))) { + var ch = text.charCodeAt(pos); + if ((pos + mergeConflictMarkerLength) < text.length) { + for (var i = 0; i < mergeConflictMarkerLength; i++) { + if (text.charCodeAt(pos + i) !== ch) { + return false; + } + } + return ch === 61 /* equals */ || + text.charCodeAt(pos + mergeConflictMarkerLength) === 32 /* space */; + } + } + return false; + } + function scanConflictMarkerTrivia(text, pos, error) { + if (error) { + error(ts.Diagnostics.Merge_conflict_marker_encountered, pos, mergeConflictMarkerLength); + } + var ch = text.charCodeAt(pos); + var len = text.length; + if (ch === 60 /* lessThan */ || ch === 62 /* greaterThan */) { + while (pos < len && !isLineBreak(text.charCodeAt(pos))) { + pos++; + } + } + else { + ts.Debug.assert(ch === 124 /* bar */ || ch === 61 /* equals */); + // Consume everything from the start of a ||||||| or ======= marker to the start + // of the next ======= or >>>>>>> marker. + while (pos < len) { + var currentChar = text.charCodeAt(pos); + if ((currentChar === 61 /* equals */ || currentChar === 62 /* greaterThan */) && currentChar !== ch && isConflictMarkerTrivia(text, pos)) { + break; + } + pos++; + } + } + return pos; + } + var shebangTriviaRegex = /^#!.*/; + function isShebangTrivia(text, pos) { + // Shebangs check must only be done at the start of the file + ts.Debug.assert(pos === 0); + return shebangTriviaRegex.test(text); + } + function scanShebangTrivia(text, pos) { + var shebang = shebangTriviaRegex.exec(text)[0]; + pos = pos + shebang.length; + return pos; + } + /** + * Invokes a callback for each comment range following the provided position. + * + * Single-line comment ranges include the leading double-slash characters but not the ending + * line break. Multi-line comment ranges include the leading slash-asterisk and trailing + * asterisk-slash characters. + * + * @param reduce If true, accumulates the result of calling the callback in a fashion similar + * to reduceLeft. If false, iteration stops when the callback returns a truthy value. + * @param text The source text to scan. + * @param pos The position at which to start scanning. + * @param trailing If false, whitespace is skipped until the first line break and comments + * between that location and the next token are returned. If true, comments occurring + * between the given position and the next line break are returned. + * @param cb The callback to execute as each comment range is encountered. + * @param state A state value to pass to each iteration of the callback. + * @param initial An initial value to pass when accumulating results (when "reduce" is true). + * @returns If "reduce" is true, the accumulated value. If "reduce" is false, the first truthy + * return value of the callback. + */ + function iterateCommentRanges(reduce, text, pos, trailing, cb, state, initial) { + var pendingPos; + var pendingEnd; + var pendingKind; + var pendingHasTrailingNewLine; + var hasPendingCommentRange = false; + var collecting = trailing || pos === 0; + var accumulator = initial; + scan: while (pos >= 0 && pos < text.length) { + var ch = text.charCodeAt(pos); + switch (ch) { + case 13 /* carriageReturn */: + if (text.charCodeAt(pos + 1) === 10 /* lineFeed */) { + pos++; + } + // falls through + case 10 /* lineFeed */: + pos++; + if (trailing) { + break scan; + } + collecting = true; + if (hasPendingCommentRange) { + pendingHasTrailingNewLine = true; + } + continue; + case 9 /* tab */: + case 11 /* verticalTab */: + case 12 /* formFeed */: + case 32 /* space */: + pos++; + continue; + case 47 /* slash */: + var nextChar = text.charCodeAt(pos + 1); + var hasTrailingNewLine = false; + if (nextChar === 47 /* slash */ || nextChar === 42 /* asterisk */) { + var kind = nextChar === 47 /* slash */ ? 2 /* SingleLineCommentTrivia */ : 3 /* MultiLineCommentTrivia */; + var startPos = pos; + pos += 2; + if (nextChar === 47 /* slash */) { + while (pos < text.length) { + if (isLineBreak(text.charCodeAt(pos))) { + hasTrailingNewLine = true; + break; + } + pos++; + } + } + else { + while (pos < text.length) { + if (text.charCodeAt(pos) === 42 /* asterisk */ && text.charCodeAt(pos + 1) === 47 /* slash */) { + pos += 2; + break; + } + pos++; + } + } + if (collecting) { + if (hasPendingCommentRange) { + accumulator = cb(pendingPos, pendingEnd, pendingKind, pendingHasTrailingNewLine, state, accumulator); + if (!reduce && accumulator) { + // If we are not reducing and we have a truthy result, return it. + return accumulator; + } + } + pendingPos = startPos; + pendingEnd = pos; + pendingKind = kind; + pendingHasTrailingNewLine = hasTrailingNewLine; + hasPendingCommentRange = true; + } + continue; + } + break scan; + default: + if (ch > 127 /* maxAsciiCharacter */ && (isWhiteSpaceLike(ch))) { + if (hasPendingCommentRange && isLineBreak(ch)) { + pendingHasTrailingNewLine = true; + } + pos++; + continue; + } + break scan; + } + } + if (hasPendingCommentRange) { + accumulator = cb(pendingPos, pendingEnd, pendingKind, pendingHasTrailingNewLine, state, accumulator); + } + return accumulator; + } + function forEachLeadingCommentRange(text, pos, cb, state) { + return iterateCommentRanges(/*reduce*/ false, text, pos, /*trailing*/ false, cb, state); + } + ts.forEachLeadingCommentRange = forEachLeadingCommentRange; + function forEachTrailingCommentRange(text, pos, cb, state) { + return iterateCommentRanges(/*reduce*/ false, text, pos, /*trailing*/ true, cb, state); + } + ts.forEachTrailingCommentRange = forEachTrailingCommentRange; + function reduceEachLeadingCommentRange(text, pos, cb, state, initial) { + return iterateCommentRanges(/*reduce*/ true, text, pos, /*trailing*/ false, cb, state, initial); + } + ts.reduceEachLeadingCommentRange = reduceEachLeadingCommentRange; + function reduceEachTrailingCommentRange(text, pos, cb, state, initial) { + return iterateCommentRanges(/*reduce*/ true, text, pos, /*trailing*/ true, cb, state, initial); + } + ts.reduceEachTrailingCommentRange = reduceEachTrailingCommentRange; + function appendCommentRange(pos, end, kind, hasTrailingNewLine, _state, comments) { + if (!comments) { + comments = []; + } + comments.push({ kind: kind, pos: pos, end: end, hasTrailingNewLine: hasTrailingNewLine }); + return comments; + } + function getLeadingCommentRanges(text, pos) { + return reduceEachLeadingCommentRange(text, pos, appendCommentRange, /*state*/ undefined, /*initial*/ undefined); + } + ts.getLeadingCommentRanges = getLeadingCommentRanges; + function getTrailingCommentRanges(text, pos) { + return reduceEachTrailingCommentRange(text, pos, appendCommentRange, /*state*/ undefined, /*initial*/ undefined); + } + ts.getTrailingCommentRanges = getTrailingCommentRanges; + /** Optionally, get the shebang */ + function getShebang(text) { + var match = shebangTriviaRegex.exec(text); + if (match) { + return match[0]; + } + } + ts.getShebang = getShebang; + function isIdentifierStart(ch, languageVersion) { + return ch >= 65 /* A */ && ch <= 90 /* Z */ || ch >= 97 /* a */ && ch <= 122 /* z */ || + ch === 36 /* $ */ || ch === 95 /* _ */ || + ch > 127 /* maxAsciiCharacter */ && isUnicodeIdentifierStart(ch, languageVersion); + } + ts.isIdentifierStart = isIdentifierStart; + function isIdentifierPart(ch, languageVersion) { + return ch >= 65 /* A */ && ch <= 90 /* Z */ || ch >= 97 /* a */ && ch <= 122 /* z */ || + ch >= 48 /* _0 */ && ch <= 57 /* _9 */ || ch === 36 /* $ */ || ch === 95 /* _ */ || + ch > 127 /* maxAsciiCharacter */ && isUnicodeIdentifierPart(ch, languageVersion); + } + ts.isIdentifierPart = isIdentifierPart; + /* @internal */ + function isIdentifierText(name, languageVersion) { + if (!isIdentifierStart(name.charCodeAt(0), languageVersion)) { + return false; + } + for (var i = 1; i < name.length; i++) { + if (!isIdentifierPart(name.charCodeAt(i), languageVersion)) { + return false; + } + } + return true; + } + ts.isIdentifierText = isIdentifierText; + // Creates a scanner over a (possibly unspecified) range of a piece of text. + function createScanner(languageVersion, skipTrivia, languageVariant, textInitial, onError, start, length) { + if (languageVariant === void 0) { languageVariant = 0 /* Standard */; } + var text = textInitial; + // Current position (end position of text of current token) + var pos; + // end of text + var end; + // Start position of whitespace before current token + var startPos; + // Start position of text of current token + var tokenPos; + var token; + var tokenValue; + var tokenFlags; + var inJSDocType = 0; + setText(text, start, length); + return { + getStartPos: function () { return startPos; }, + getTextPos: function () { return pos; }, + getToken: function () { return token; }, + getTokenPos: function () { return tokenPos; }, + getTokenText: function () { return text.substring(tokenPos, pos); }, + getTokenValue: function () { return tokenValue; }, + hasExtendedUnicodeEscape: function () { return (tokenFlags & 8 /* ExtendedUnicodeEscape */) !== 0; }, + hasPrecedingLineBreak: function () { return (tokenFlags & 1 /* PrecedingLineBreak */) !== 0; }, + isIdentifier: function () { return token === 72 /* Identifier */ || token > 108 /* LastReservedWord */; }, + isReservedWord: function () { return token >= 73 /* FirstReservedWord */ && token <= 108 /* LastReservedWord */; }, + isUnterminated: function () { return (tokenFlags & 4 /* Unterminated */) !== 0; }, + getTokenFlags: function () { return tokenFlags; }, + reScanGreaterToken: reScanGreaterToken, + reScanSlashToken: reScanSlashToken, + reScanTemplateToken: reScanTemplateToken, + scanJsxIdentifier: scanJsxIdentifier, + scanJsxAttributeValue: scanJsxAttributeValue, + reScanJsxToken: reScanJsxToken, + scanJsxToken: scanJsxToken, + scanJSDocToken: scanJSDocToken, + scan: scan, + getText: getText, + setText: setText, + setScriptTarget: setScriptTarget, + setLanguageVariant: setLanguageVariant, + setOnError: setOnError, + setTextPos: setTextPos, + setInJSDocType: setInJSDocType, + tryScan: tryScan, + lookAhead: lookAhead, + scanRange: scanRange, + }; + function error(message, errPos, length) { + if (errPos === void 0) { errPos = pos; } + if (onError) { + var oldPos = pos; + pos = errPos; + onError(message, length || 0); + pos = oldPos; + } + } + function scanNumberFragment() { + var start = pos; + var allowSeparator = false; + var isPreviousTokenSeparator = false; + var result = ""; + while (true) { + var ch = text.charCodeAt(pos); + if (ch === 95 /* _ */) { + tokenFlags |= 512 /* ContainsSeparator */; + if (allowSeparator) { + allowSeparator = false; + isPreviousTokenSeparator = true; + result += text.substring(start, pos); + } + else if (isPreviousTokenSeparator) { + error(ts.Diagnostics.Multiple_consecutive_numeric_separators_are_not_permitted, pos, 1); + } + else { + error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos, 1); + } + pos++; + start = pos; + continue; + } + if (isDigit(ch)) { + allowSeparator = true; + isPreviousTokenSeparator = false; + pos++; + continue; + } + break; + } + if (text.charCodeAt(pos - 1) === 95 /* _ */) { + error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos - 1, 1); + } + return result + text.substring(start, pos); + } + function scanNumber() { + var start = pos; + var mainFragment = scanNumberFragment(); + var decimalFragment; + var scientificFragment; + if (text.charCodeAt(pos) === 46 /* dot */) { + pos++; + decimalFragment = scanNumberFragment(); + } + var end = pos; + if (text.charCodeAt(pos) === 69 /* E */ || text.charCodeAt(pos) === 101 /* e */) { + pos++; + tokenFlags |= 16 /* Scientific */; + if (text.charCodeAt(pos) === 43 /* plus */ || text.charCodeAt(pos) === 45 /* minus */) + pos++; + var preNumericPart = pos; + var finalFragment = scanNumberFragment(); + if (!finalFragment) { + error(ts.Diagnostics.Digit_expected); + } + else { + scientificFragment = text.substring(end, preNumericPart) + finalFragment; + end = pos; + } + } + var result; + if (tokenFlags & 512 /* ContainsSeparator */) { + result = mainFragment; + if (decimalFragment) { + result += "." + decimalFragment; + } + if (scientificFragment) { + result += scientificFragment; + } + } + else { + result = text.substring(start, end); // No need to use all the fragments; no _ removal needed + } + if (decimalFragment !== undefined || tokenFlags & 16 /* Scientific */) { + return { + type: 8 /* NumericLiteral */, + value: "" + +result // if value is not an integer, it can be safely coerced to a number + }; + } + else { + tokenValue = result; + var type = checkBigIntSuffix(); // if value is an integer, check whether it is a bigint + return { type: type, value: tokenValue }; + } + } + function scanOctalDigits() { + var start = pos; + while (isOctalDigit(text.charCodeAt(pos))) { + pos++; + } + return +(text.substring(start, pos)); + } + /** + * Scans the given number of hexadecimal digits in the text, + * returning -1 if the given number is unavailable. + */ + function scanExactNumberOfHexDigits(count, canHaveSeparators) { + var valueString = scanHexDigits(/*minCount*/ count, /*scanAsManyAsPossible*/ false, canHaveSeparators); + return valueString ? parseInt(valueString, 16) : -1; + } + /** + * Scans as many hexadecimal digits as are available in the text, + * returning "" if the given number of digits was unavailable. + */ + function scanMinimumNumberOfHexDigits(count, canHaveSeparators) { + return scanHexDigits(/*minCount*/ count, /*scanAsManyAsPossible*/ true, canHaveSeparators); + } + function scanHexDigits(minCount, scanAsManyAsPossible, canHaveSeparators) { + var valueChars = []; + var allowSeparator = false; + var isPreviousTokenSeparator = false; + while (valueChars.length < minCount || scanAsManyAsPossible) { + var ch = text.charCodeAt(pos); + if (canHaveSeparators && ch === 95 /* _ */) { + tokenFlags |= 512 /* ContainsSeparator */; + if (allowSeparator) { + allowSeparator = false; + isPreviousTokenSeparator = true; + } + else if (isPreviousTokenSeparator) { + error(ts.Diagnostics.Multiple_consecutive_numeric_separators_are_not_permitted, pos, 1); + } + else { + error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos, 1); + } + pos++; + continue; + } + allowSeparator = canHaveSeparators; + if (ch >= 65 /* A */ && ch <= 70 /* F */) { + ch += 97 /* a */ - 65 /* A */; // standardize hex literals to lowercase + } + else if (!((ch >= 48 /* _0 */ && ch <= 57 /* _9 */) || + (ch >= 97 /* a */ && ch <= 102 /* f */))) { + break; + } + valueChars.push(ch); + pos++; + isPreviousTokenSeparator = false; + } + if (valueChars.length < minCount) { + valueChars = []; + } + if (text.charCodeAt(pos - 1) === 95 /* _ */) { + error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos - 1, 1); + } + return String.fromCharCode.apply(String, valueChars); + } + function scanString(jsxAttributeString) { + if (jsxAttributeString === void 0) { jsxAttributeString = false; } + var quote = text.charCodeAt(pos); + pos++; + var result = ""; + var start = pos; + while (true) { + if (pos >= end) { + result += text.substring(start, pos); + tokenFlags |= 4 /* Unterminated */; + error(ts.Diagnostics.Unterminated_string_literal); + break; + } + var ch = text.charCodeAt(pos); + if (ch === quote) { + result += text.substring(start, pos); + pos++; + break; + } + if (ch === 92 /* backslash */ && !jsxAttributeString) { + result += text.substring(start, pos); + result += scanEscapeSequence(); + start = pos; + continue; + } + if (isLineBreak(ch) && !jsxAttributeString) { + result += text.substring(start, pos); + tokenFlags |= 4 /* Unterminated */; + error(ts.Diagnostics.Unterminated_string_literal); + break; + } + pos++; + } + return result; + } + /** + * Sets the current 'tokenValue' and returns a NoSubstitutionTemplateLiteral or + * a literal component of a TemplateExpression. + */ + function scanTemplateAndSetTokenValue() { + var startedWithBacktick = text.charCodeAt(pos) === 96 /* backtick */; + pos++; + var start = pos; + var contents = ""; + var resultingToken; + while (true) { + if (pos >= end) { + contents += text.substring(start, pos); + tokenFlags |= 4 /* Unterminated */; + error(ts.Diagnostics.Unterminated_template_literal); + resultingToken = startedWithBacktick ? 14 /* NoSubstitutionTemplateLiteral */ : 17 /* TemplateTail */; + break; + } + var currChar = text.charCodeAt(pos); + // '`' + if (currChar === 96 /* backtick */) { + contents += text.substring(start, pos); + pos++; + resultingToken = startedWithBacktick ? 14 /* NoSubstitutionTemplateLiteral */ : 17 /* TemplateTail */; + break; + } + // '${' + if (currChar === 36 /* $ */ && pos + 1 < end && text.charCodeAt(pos + 1) === 123 /* openBrace */) { + contents += text.substring(start, pos); + pos += 2; + resultingToken = startedWithBacktick ? 15 /* TemplateHead */ : 16 /* TemplateMiddle */; + break; + } + // Escape character + if (currChar === 92 /* backslash */) { + contents += text.substring(start, pos); + contents += scanEscapeSequence(); + start = pos; + continue; + } + // Speculated ECMAScript 6 Spec 11.8.6.1: + // and LineTerminatorSequences are normalized to for Template Values + if (currChar === 13 /* carriageReturn */) { + contents += text.substring(start, pos); + pos++; + if (pos < end && text.charCodeAt(pos) === 10 /* lineFeed */) { + pos++; + } + contents += "\n"; + start = pos; + continue; + } + pos++; + } + ts.Debug.assert(resultingToken !== undefined); + tokenValue = contents; + return resultingToken; + } + function scanEscapeSequence() { + pos++; + if (pos >= end) { + error(ts.Diagnostics.Unexpected_end_of_text); + return ""; + } + var ch = text.charCodeAt(pos); + pos++; + switch (ch) { + case 48 /* _0 */: + return "\0"; + case 98 /* b */: + return "\b"; + case 116 /* t */: + return "\t"; + case 110 /* n */: + return "\n"; + case 118 /* v */: + return "\v"; + case 102 /* f */: + return "\f"; + case 114 /* r */: + return "\r"; + case 39 /* singleQuote */: + return "\'"; + case 34 /* doubleQuote */: + return "\""; + case 117 /* u */: + // '\u{DDDDDDDD}' + if (pos < end && text.charCodeAt(pos) === 123 /* openBrace */) { + tokenFlags |= 8 /* ExtendedUnicodeEscape */; + pos++; + return scanExtendedUnicodeEscape(); + } + // '\uDDDD' + return scanHexadecimalEscape(/*numDigits*/ 4); + case 120 /* x */: + // '\xDD' + return scanHexadecimalEscape(/*numDigits*/ 2); + // when encountering a LineContinuation (i.e. a backslash and a line terminator sequence), + // the line terminator is interpreted to be "the empty code unit sequence". + case 13 /* carriageReturn */: + if (pos < end && text.charCodeAt(pos) === 10 /* lineFeed */) { + pos++; + } + // falls through + case 10 /* lineFeed */: + case 8232 /* lineSeparator */: + case 8233 /* paragraphSeparator */: + return ""; + default: + return String.fromCharCode(ch); + } + } + function scanHexadecimalEscape(numDigits) { + var escapedValue = scanExactNumberOfHexDigits(numDigits, /*canHaveSeparators*/ false); + if (escapedValue >= 0) { + return String.fromCharCode(escapedValue); + } + else { + error(ts.Diagnostics.Hexadecimal_digit_expected); + return ""; + } + } + function scanExtendedUnicodeEscape() { + var escapedValueString = scanMinimumNumberOfHexDigits(1, /*canHaveSeparators*/ false); + var escapedValue = escapedValueString ? parseInt(escapedValueString, 16) : -1; + var isInvalidExtendedEscape = false; + // Validate the value of the digit + if (escapedValue < 0) { + error(ts.Diagnostics.Hexadecimal_digit_expected); + isInvalidExtendedEscape = true; + } + else if (escapedValue > 0x10FFFF) { + error(ts.Diagnostics.An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive); + isInvalidExtendedEscape = true; + } + if (pos >= end) { + error(ts.Diagnostics.Unexpected_end_of_text); + isInvalidExtendedEscape = true; + } + else if (text.charCodeAt(pos) === 125 /* closeBrace */) { + // Only swallow the following character up if it's a '}'. + pos++; + } + else { + error(ts.Diagnostics.Unterminated_Unicode_escape_sequence); + isInvalidExtendedEscape = true; + } + if (isInvalidExtendedEscape) { + return ""; + } + return utf16EncodeAsString(escapedValue); + } + // Derived from the 10.1.1 UTF16Encoding of the ES6 Spec. + function utf16EncodeAsString(codePoint) { + ts.Debug.assert(0x0 <= codePoint && codePoint <= 0x10FFFF); + if (codePoint <= 65535) { + return String.fromCharCode(codePoint); + } + var codeUnit1 = Math.floor((codePoint - 65536) / 1024) + 0xD800; + var codeUnit2 = ((codePoint - 65536) % 1024) + 0xDC00; + return String.fromCharCode(codeUnit1, codeUnit2); + } + // Current character is known to be a backslash. Check for Unicode escape of the form '\uXXXX' + // and return code point value if valid Unicode escape is found. Otherwise return -1. + function peekUnicodeEscape() { + if (pos + 5 < end && text.charCodeAt(pos + 1) === 117 /* u */) { + var start_1 = pos; + pos += 2; + var value = scanExactNumberOfHexDigits(4, /*canHaveSeparators*/ false); + pos = start_1; + return value; + } + return -1; + } + function scanIdentifierParts() { + var result = ""; + var start = pos; + while (pos < end) { + var ch = text.charCodeAt(pos); + if (isIdentifierPart(ch, languageVersion)) { + pos++; + } + else if (ch === 92 /* backslash */) { + ch = peekUnicodeEscape(); + if (!(ch >= 0 && isIdentifierPart(ch, languageVersion))) { + break; + } + result += text.substring(start, pos); + result += String.fromCharCode(ch); + // Valid Unicode escape is always six characters + pos += 6; + start = pos; + } + else { + break; + } + } + result += text.substring(start, pos); + return result; + } + function getIdentifierToken() { + // Reserved words are between 2 and 11 characters long and start with a lowercase letter + var len = tokenValue.length; + if (len >= 2 && len <= 11) { + var ch = tokenValue.charCodeAt(0); + if (ch >= 97 /* a */ && ch <= 122 /* z */) { + var keyword = textToKeyword.get(tokenValue); + if (keyword !== undefined) { + return token = keyword; + } + } + } + return token = 72 /* Identifier */; + } + function scanBinaryOrOctalDigits(base) { + var value = ""; + // For counting number of digits; Valid binaryIntegerLiteral must have at least one binary digit following B or b. + // Similarly valid octalIntegerLiteral must have at least one octal digit following o or O. + var separatorAllowed = false; + var isPreviousTokenSeparator = false; + while (true) { + var ch = text.charCodeAt(pos); + // Numeric separators are allowed anywhere within a numeric literal, except not at the beginning, or following another separator + if (ch === 95 /* _ */) { + tokenFlags |= 512 /* ContainsSeparator */; + if (separatorAllowed) { + separatorAllowed = false; + isPreviousTokenSeparator = true; + } + else if (isPreviousTokenSeparator) { + error(ts.Diagnostics.Multiple_consecutive_numeric_separators_are_not_permitted, pos, 1); + } + else { + error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos, 1); + } + pos++; + continue; + } + separatorAllowed = true; + if (!isDigit(ch) || ch - 48 /* _0 */ >= base) { + break; + } + value += text[pos]; + pos++; + isPreviousTokenSeparator = false; + } + if (text.charCodeAt(pos - 1) === 95 /* _ */) { + // Literal ends with underscore - not allowed + error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos - 1, 1); + } + return value; + } + function checkBigIntSuffix() { + if (text.charCodeAt(pos) === 110 /* n */) { + tokenValue += "n"; + // Use base 10 instead of base 2 or base 8 for shorter literals + if (tokenFlags & 384 /* BinaryOrOctalSpecifier */) { + tokenValue = ts.parsePseudoBigInt(tokenValue) + "n"; + } + pos++; + return 9 /* BigIntLiteral */; + } + else { // not a bigint, so can convert to number in simplified form + // Number() may not support 0b or 0o, so use parseInt() instead + var numericValue = tokenFlags & 128 /* BinarySpecifier */ + ? parseInt(tokenValue.slice(2), 2) // skip "0b" + : tokenFlags & 256 /* OctalSpecifier */ + ? parseInt(tokenValue.slice(2), 8) // skip "0o" + : +tokenValue; + tokenValue = "" + numericValue; + return 8 /* NumericLiteral */; + } + } + function scan() { + var _a; + startPos = pos; + tokenFlags = 0; + var asteriskSeen = false; + while (true) { + tokenPos = pos; + if (pos >= end) { + return token = 1 /* EndOfFileToken */; + } + var ch = text.charCodeAt(pos); + // Special handling for shebang + if (ch === 35 /* hash */ && pos === 0 && isShebangTrivia(text, pos)) { + pos = scanShebangTrivia(text, pos); + if (skipTrivia) { + continue; + } + else { + return token = 6 /* ShebangTrivia */; + } + } + switch (ch) { + case 10 /* lineFeed */: + case 13 /* carriageReturn */: + tokenFlags |= 1 /* PrecedingLineBreak */; + if (skipTrivia) { + pos++; + continue; + } + else { + if (ch === 13 /* carriageReturn */ && pos + 1 < end && text.charCodeAt(pos + 1) === 10 /* lineFeed */) { + // consume both CR and LF + pos += 2; + } + else { + pos++; + } + return token = 4 /* NewLineTrivia */; + } + case 9 /* tab */: + case 11 /* verticalTab */: + case 12 /* formFeed */: + case 32 /* space */: + case 160 /* nonBreakingSpace */: + case 5760 /* ogham */: + case 8192 /* enQuad */: + case 8193 /* emQuad */: + case 8194 /* enSpace */: + case 8195 /* emSpace */: + case 8196 /* threePerEmSpace */: + case 8197 /* fourPerEmSpace */: + case 8198 /* sixPerEmSpace */: + case 8199 /* figureSpace */: + case 8200 /* punctuationSpace */: + case 8201 /* thinSpace */: + case 8202 /* hairSpace */: + case 8203 /* zeroWidthSpace */: + case 8239 /* narrowNoBreakSpace */: + case 8287 /* mathematicalSpace */: + case 12288 /* ideographicSpace */: + case 65279 /* byteOrderMark */: + if (skipTrivia) { + pos++; + continue; + } + else { + while (pos < end && isWhiteSpaceSingleLine(text.charCodeAt(pos))) { + pos++; + } + return token = 5 /* WhitespaceTrivia */; + } + case 33 /* exclamation */: + if (text.charCodeAt(pos + 1) === 61 /* equals */) { + if (text.charCodeAt(pos + 2) === 61 /* equals */) { + return pos += 3, token = 36 /* ExclamationEqualsEqualsToken */; + } + return pos += 2, token = 34 /* ExclamationEqualsToken */; + } + pos++; + return token = 52 /* ExclamationToken */; + case 34 /* doubleQuote */: + case 39 /* singleQuote */: + tokenValue = scanString(); + return token = 10 /* StringLiteral */; + case 96 /* backtick */: + return token = scanTemplateAndSetTokenValue(); + case 37 /* percent */: + if (text.charCodeAt(pos + 1) === 61 /* equals */) { + return pos += 2, token = 65 /* PercentEqualsToken */; + } + pos++; + return token = 43 /* PercentToken */; + case 38 /* ampersand */: + if (text.charCodeAt(pos + 1) === 38 /* ampersand */) { + return pos += 2, token = 54 /* AmpersandAmpersandToken */; + } + if (text.charCodeAt(pos + 1) === 61 /* equals */) { + return pos += 2, token = 69 /* AmpersandEqualsToken */; + } + pos++; + return token = 49 /* AmpersandToken */; + case 40 /* openParen */: + pos++; + return token = 20 /* OpenParenToken */; + case 41 /* closeParen */: + pos++; + return token = 21 /* CloseParenToken */; + case 42 /* asterisk */: + if (text.charCodeAt(pos + 1) === 61 /* equals */) { + return pos += 2, token = 62 /* AsteriskEqualsToken */; + } + if (text.charCodeAt(pos + 1) === 42 /* asterisk */) { + if (text.charCodeAt(pos + 2) === 61 /* equals */) { + return pos += 3, token = 63 /* AsteriskAsteriskEqualsToken */; + } + return pos += 2, token = 41 /* AsteriskAsteriskToken */; + } + pos++; + if (inJSDocType && !asteriskSeen && (tokenFlags & 1 /* PrecedingLineBreak */)) { + // decoration at the start of a JSDoc comment line + asteriskSeen = true; + continue; + } + return token = 40 /* AsteriskToken */; + case 43 /* plus */: + if (text.charCodeAt(pos + 1) === 43 /* plus */) { + return pos += 2, token = 44 /* PlusPlusToken */; + } + if (text.charCodeAt(pos + 1) === 61 /* equals */) { + return pos += 2, token = 60 /* PlusEqualsToken */; + } + pos++; + return token = 38 /* PlusToken */; + case 44 /* comma */: + pos++; + return token = 27 /* CommaToken */; + case 45 /* minus */: + if (text.charCodeAt(pos + 1) === 45 /* minus */) { + return pos += 2, token = 45 /* MinusMinusToken */; + } + if (text.charCodeAt(pos + 1) === 61 /* equals */) { + return pos += 2, token = 61 /* MinusEqualsToken */; + } + pos++; + return token = 39 /* MinusToken */; + case 46 /* dot */: + if (isDigit(text.charCodeAt(pos + 1))) { + tokenValue = scanNumber().value; + return token = 8 /* NumericLiteral */; + } + if (text.charCodeAt(pos + 1) === 46 /* dot */ && text.charCodeAt(pos + 2) === 46 /* dot */) { + return pos += 3, token = 25 /* DotDotDotToken */; + } + pos++; + return token = 24 /* DotToken */; + case 47 /* slash */: + // Single-line comment + if (text.charCodeAt(pos + 1) === 47 /* slash */) { + pos += 2; + while (pos < end) { + if (isLineBreak(text.charCodeAt(pos))) { + break; + } + pos++; + } + if (skipTrivia) { + continue; + } + else { + return token = 2 /* SingleLineCommentTrivia */; + } + } + // Multi-line comment + if (text.charCodeAt(pos + 1) === 42 /* asterisk */) { + pos += 2; + if (text.charCodeAt(pos) === 42 /* asterisk */ && text.charCodeAt(pos + 1) !== 47 /* slash */) { + tokenFlags |= 2 /* PrecedingJSDocComment */; + } + var commentClosed = false; + while (pos < end) { + var ch_1 = text.charCodeAt(pos); + if (ch_1 === 42 /* asterisk */ && text.charCodeAt(pos + 1) === 47 /* slash */) { + pos += 2; + commentClosed = true; + break; + } + if (isLineBreak(ch_1)) { + tokenFlags |= 1 /* PrecedingLineBreak */; + } + pos++; + } + if (!commentClosed) { + error(ts.Diagnostics.Asterisk_Slash_expected); + } + if (skipTrivia) { + continue; + } + else { + if (!commentClosed) { + tokenFlags |= 4 /* Unterminated */; + } + return token = 3 /* MultiLineCommentTrivia */; + } + } + if (text.charCodeAt(pos + 1) === 61 /* equals */) { + return pos += 2, token = 64 /* SlashEqualsToken */; + } + pos++; + return token = 42 /* SlashToken */; + case 48 /* _0 */: + if (pos + 2 < end && (text.charCodeAt(pos + 1) === 88 /* X */ || text.charCodeAt(pos + 1) === 120 /* x */)) { + pos += 2; + tokenValue = scanMinimumNumberOfHexDigits(1, /*canHaveSeparators*/ true); + if (!tokenValue) { + error(ts.Diagnostics.Hexadecimal_digit_expected); + tokenValue = "0"; + } + tokenValue = "0x" + tokenValue; + tokenFlags |= 64 /* HexSpecifier */; + return token = checkBigIntSuffix(); + } + else if (pos + 2 < end && (text.charCodeAt(pos + 1) === 66 /* B */ || text.charCodeAt(pos + 1) === 98 /* b */)) { + pos += 2; + tokenValue = scanBinaryOrOctalDigits(/* base */ 2); + if (!tokenValue) { + error(ts.Diagnostics.Binary_digit_expected); + tokenValue = "0"; + } + tokenValue = "0b" + tokenValue; + tokenFlags |= 128 /* BinarySpecifier */; + return token = checkBigIntSuffix(); + } + else if (pos + 2 < end && (text.charCodeAt(pos + 1) === 79 /* O */ || text.charCodeAt(pos + 1) === 111 /* o */)) { + pos += 2; + tokenValue = scanBinaryOrOctalDigits(/* base */ 8); + if (!tokenValue) { + error(ts.Diagnostics.Octal_digit_expected); + tokenValue = "0"; + } + tokenValue = "0o" + tokenValue; + tokenFlags |= 256 /* OctalSpecifier */; + return token = checkBigIntSuffix(); + } + // Try to parse as an octal + if (pos + 1 < end && isOctalDigit(text.charCodeAt(pos + 1))) { + tokenValue = "" + scanOctalDigits(); + tokenFlags |= 32 /* Octal */; + return token = 8 /* NumericLiteral */; + } + // This fall-through is a deviation from the EcmaScript grammar. The grammar says that a leading zero + // can only be followed by an octal digit, a dot, or the end of the number literal. However, we are being + // permissive and allowing decimal digits of the form 08* and 09* (which many browsers also do). + // falls through + case 49 /* _1 */: + case 50 /* _2 */: + case 51 /* _3 */: + case 52 /* _4 */: + case 53 /* _5 */: + case 54 /* _6 */: + case 55 /* _7 */: + case 56 /* _8 */: + case 57 /* _9 */: + (_a = scanNumber(), token = _a.type, tokenValue = _a.value); + return token; + case 58 /* colon */: + pos++; + return token = 57 /* ColonToken */; + case 59 /* semicolon */: + pos++; + return token = 26 /* SemicolonToken */; + case 60 /* lessThan */: + if (isConflictMarkerTrivia(text, pos)) { + pos = scanConflictMarkerTrivia(text, pos, error); + if (skipTrivia) { + continue; + } + else { + return token = 7 /* ConflictMarkerTrivia */; + } + } + if (text.charCodeAt(pos + 1) === 60 /* lessThan */) { + if (text.charCodeAt(pos + 2) === 61 /* equals */) { + return pos += 3, token = 66 /* LessThanLessThanEqualsToken */; + } + return pos += 2, token = 46 /* LessThanLessThanToken */; + } + if (text.charCodeAt(pos + 1) === 61 /* equals */) { + return pos += 2, token = 31 /* LessThanEqualsToken */; + } + if (languageVariant === 1 /* JSX */ && + text.charCodeAt(pos + 1) === 47 /* slash */ && + text.charCodeAt(pos + 2) !== 42 /* asterisk */) { + return pos += 2, token = 29 /* LessThanSlashToken */; + } + pos++; + return token = 28 /* LessThanToken */; + case 61 /* equals */: + if (isConflictMarkerTrivia(text, pos)) { + pos = scanConflictMarkerTrivia(text, pos, error); + if (skipTrivia) { + continue; + } + else { + return token = 7 /* ConflictMarkerTrivia */; + } + } + if (text.charCodeAt(pos + 1) === 61 /* equals */) { + if (text.charCodeAt(pos + 2) === 61 /* equals */) { + return pos += 3, token = 35 /* EqualsEqualsEqualsToken */; + } + return pos += 2, token = 33 /* EqualsEqualsToken */; + } + if (text.charCodeAt(pos + 1) === 62 /* greaterThan */) { + return pos += 2, token = 37 /* EqualsGreaterThanToken */; + } + pos++; + return token = 59 /* EqualsToken */; + case 62 /* greaterThan */: + if (isConflictMarkerTrivia(text, pos)) { + pos = scanConflictMarkerTrivia(text, pos, error); + if (skipTrivia) { + continue; + } + else { + return token = 7 /* ConflictMarkerTrivia */; + } + } + pos++; + return token = 30 /* GreaterThanToken */; + case 63 /* question */: + pos++; + return token = 56 /* QuestionToken */; + case 91 /* openBracket */: + pos++; + return token = 22 /* OpenBracketToken */; + case 93 /* closeBracket */: + pos++; + return token = 23 /* CloseBracketToken */; + case 94 /* caret */: + if (text.charCodeAt(pos + 1) === 61 /* equals */) { + return pos += 2, token = 71 /* CaretEqualsToken */; + } + pos++; + return token = 51 /* CaretToken */; + case 123 /* openBrace */: + pos++; + return token = 18 /* OpenBraceToken */; + case 124 /* bar */: + if (isConflictMarkerTrivia(text, pos)) { + pos = scanConflictMarkerTrivia(text, pos, error); + if (skipTrivia) { + continue; + } + else { + return token = 7 /* ConflictMarkerTrivia */; + } + } + if (text.charCodeAt(pos + 1) === 124 /* bar */) { + return pos += 2, token = 55 /* BarBarToken */; + } + if (text.charCodeAt(pos + 1) === 61 /* equals */) { + return pos += 2, token = 70 /* BarEqualsToken */; + } + pos++; + return token = 50 /* BarToken */; + case 125 /* closeBrace */: + pos++; + return token = 19 /* CloseBraceToken */; + case 126 /* tilde */: + pos++; + return token = 53 /* TildeToken */; + case 64 /* at */: + pos++; + return token = 58 /* AtToken */; + case 92 /* backslash */: + var cookedChar = peekUnicodeEscape(); + if (cookedChar >= 0 && isIdentifierStart(cookedChar, languageVersion)) { + pos += 6; + tokenValue = String.fromCharCode(cookedChar) + scanIdentifierParts(); + return token = getIdentifierToken(); + } + error(ts.Diagnostics.Invalid_character); + pos++; + return token = 0 /* Unknown */; + default: + if (isIdentifierStart(ch, languageVersion)) { + pos++; + while (pos < end && isIdentifierPart(ch = text.charCodeAt(pos), languageVersion)) + pos++; + tokenValue = text.substring(tokenPos, pos); + if (ch === 92 /* backslash */) { + tokenValue += scanIdentifierParts(); + } + return token = getIdentifierToken(); + } + else if (isWhiteSpaceSingleLine(ch)) { + pos++; + continue; + } + else if (isLineBreak(ch)) { + tokenFlags |= 1 /* PrecedingLineBreak */; + pos++; + continue; + } + error(ts.Diagnostics.Invalid_character); + pos++; + return token = 0 /* Unknown */; + } + } + } + function reScanGreaterToken() { + if (token === 30 /* GreaterThanToken */) { + if (text.charCodeAt(pos) === 62 /* greaterThan */) { + if (text.charCodeAt(pos + 1) === 62 /* greaterThan */) { + if (text.charCodeAt(pos + 2) === 61 /* equals */) { + return pos += 3, token = 68 /* GreaterThanGreaterThanGreaterThanEqualsToken */; + } + return pos += 2, token = 48 /* GreaterThanGreaterThanGreaterThanToken */; + } + if (text.charCodeAt(pos + 1) === 61 /* equals */) { + return pos += 2, token = 67 /* GreaterThanGreaterThanEqualsToken */; + } + pos++; + return token = 47 /* GreaterThanGreaterThanToken */; + } + if (text.charCodeAt(pos) === 61 /* equals */) { + pos++; + return token = 32 /* GreaterThanEqualsToken */; + } + } + return token; + } + function reScanSlashToken() { + if (token === 42 /* SlashToken */ || token === 64 /* SlashEqualsToken */) { + var p = tokenPos + 1; + var inEscape = false; + var inCharacterClass = false; + while (true) { + // If we reach the end of a file, or hit a newline, then this is an unterminated + // regex. Report error and return what we have so far. + if (p >= end) { + tokenFlags |= 4 /* Unterminated */; + error(ts.Diagnostics.Unterminated_regular_expression_literal); + break; + } + var ch = text.charCodeAt(p); + if (isLineBreak(ch)) { + tokenFlags |= 4 /* Unterminated */; + error(ts.Diagnostics.Unterminated_regular_expression_literal); + break; + } + if (inEscape) { + // Parsing an escape character; + // reset the flag and just advance to the next char. + inEscape = false; + } + else if (ch === 47 /* slash */ && !inCharacterClass) { + // A slash within a character class is permissible, + // but in general it signals the end of the regexp literal. + p++; + break; + } + else if (ch === 91 /* openBracket */) { + inCharacterClass = true; + } + else if (ch === 92 /* backslash */) { + inEscape = true; + } + else if (ch === 93 /* closeBracket */) { + inCharacterClass = false; + } + p++; + } + while (p < end && isIdentifierPart(text.charCodeAt(p), languageVersion)) { + p++; + } + pos = p; + tokenValue = text.substring(tokenPos, pos); + token = 13 /* RegularExpressionLiteral */; + } + return token; + } + /** + * Unconditionally back up and scan a template expression portion. + */ + function reScanTemplateToken() { + ts.Debug.assert(token === 19 /* CloseBraceToken */, "'reScanTemplateToken' should only be called on a '}'"); + pos = tokenPos; + return token = scanTemplateAndSetTokenValue(); + } + function reScanJsxToken() { + pos = tokenPos = startPos; + return token = scanJsxToken(); + } + function scanJsxToken() { + startPos = tokenPos = pos; + if (pos >= end) { + return token = 1 /* EndOfFileToken */; + } + var char = text.charCodeAt(pos); + if (char === 60 /* lessThan */) { + if (text.charCodeAt(pos + 1) === 47 /* slash */) { + pos += 2; + return token = 29 /* LessThanSlashToken */; + } + pos++; + return token = 28 /* LessThanToken */; + } + if (char === 123 /* openBrace */) { + pos++; + return token = 18 /* OpenBraceToken */; + } + // First non-whitespace character on this line. + var firstNonWhitespace = 0; + // These initial values are special because the first line is: + // firstNonWhitespace = 0 to indicate that we want leading whitspace, + while (pos < end) { + char = text.charCodeAt(pos); + if (char === 123 /* openBrace */) { + break; + } + if (char === 60 /* lessThan */) { + if (isConflictMarkerTrivia(text, pos)) { + pos = scanConflictMarkerTrivia(text, pos, error); + return token = 7 /* ConflictMarkerTrivia */; + } + break; + } + // FirstNonWhitespace is 0, then we only see whitespaces so far. If we see a linebreak, we want to ignore that whitespaces. + // i.e (- : whitespace) + //
      ---- + //
      becomes
      + // + //
      ----
      becomes
      ----
      + if (isLineBreak(char) && firstNonWhitespace === 0) { + firstNonWhitespace = -1; + } + else if (!isWhiteSpaceLike(char)) { + firstNonWhitespace = pos; + } + pos++; + } + return firstNonWhitespace === -1 ? 12 /* JsxTextAllWhiteSpaces */ : 11 /* JsxText */; + } + // Scans a JSX identifier; these differ from normal identifiers in that + // they allow dashes + function scanJsxIdentifier() { + if (tokenIsIdentifierOrKeyword(token)) { + var firstCharPosition = pos; + while (pos < end) { + var ch = text.charCodeAt(pos); + if (ch === 45 /* minus */ || ((firstCharPosition === pos) ? isIdentifierStart(ch, languageVersion) : isIdentifierPart(ch, languageVersion))) { + pos++; + } + else { + break; + } + } + tokenValue += text.substring(firstCharPosition, pos); + } + return token; + } + function scanJsxAttributeValue() { + startPos = pos; + switch (text.charCodeAt(pos)) { + case 34 /* doubleQuote */: + case 39 /* singleQuote */: + tokenValue = scanString(/*jsxAttributeString*/ true); + return token = 10 /* StringLiteral */; + default: + // If this scans anything other than `{`, it's a parse error. + return scan(); + } + } + function scanJSDocToken() { + startPos = tokenPos = pos; + tokenFlags = 0; + if (pos >= end) { + return token = 1 /* EndOfFileToken */; + } + var ch = text.charCodeAt(pos); + pos++; + switch (ch) { + case 9 /* tab */: + case 11 /* verticalTab */: + case 12 /* formFeed */: + case 32 /* space */: + while (pos < end && isWhiteSpaceSingleLine(text.charCodeAt(pos))) { + pos++; + } + return token = 5 /* WhitespaceTrivia */; + case 64 /* at */: + return token = 58 /* AtToken */; + case 10 /* lineFeed */: + case 13 /* carriageReturn */: + tokenFlags |= 1 /* PrecedingLineBreak */; + return token = 4 /* NewLineTrivia */; + case 42 /* asterisk */: + return token = 40 /* AsteriskToken */; + case 123 /* openBrace */: + return token = 18 /* OpenBraceToken */; + case 125 /* closeBrace */: + return token = 19 /* CloseBraceToken */; + case 91 /* openBracket */: + return token = 22 /* OpenBracketToken */; + case 93 /* closeBracket */: + return token = 23 /* CloseBracketToken */; + case 60 /* lessThan */: + return token = 28 /* LessThanToken */; + case 61 /* equals */: + return token = 59 /* EqualsToken */; + case 44 /* comma */: + return token = 27 /* CommaToken */; + case 46 /* dot */: + return token = 24 /* DotToken */; + case 96 /* backtick */: + while (pos < end && text.charCodeAt(pos) !== 96 /* backtick */) { + pos++; + } + tokenValue = text.substring(tokenPos + 1, pos); + pos++; + return token = 14 /* NoSubstitutionTemplateLiteral */; + } + if (isIdentifierStart(ch, 6 /* Latest */)) { + while (isIdentifierPart(text.charCodeAt(pos), 6 /* Latest */) && pos < end) { + pos++; + } + tokenValue = text.substring(tokenPos, pos); + return token = getIdentifierToken(); + } + else { + return token = 0 /* Unknown */; + } + } + function speculationHelper(callback, isLookahead) { + var savePos = pos; + var saveStartPos = startPos; + var saveTokenPos = tokenPos; + var saveToken = token; + var saveTokenValue = tokenValue; + var saveTokenFlags = tokenFlags; + var result = callback(); + // If our callback returned something 'falsy' or we're just looking ahead, + // then unconditionally restore us to where we were. + if (!result || isLookahead) { + pos = savePos; + startPos = saveStartPos; + tokenPos = saveTokenPos; + token = saveToken; + tokenValue = saveTokenValue; + tokenFlags = saveTokenFlags; + } + return result; + } + function scanRange(start, length, callback) { + var saveEnd = end; + var savePos = pos; + var saveStartPos = startPos; + var saveTokenPos = tokenPos; + var saveToken = token; + var saveTokenValue = tokenValue; + var saveTokenFlags = tokenFlags; + setText(text, start, length); + var result = callback(); + end = saveEnd; + pos = savePos; + startPos = saveStartPos; + tokenPos = saveTokenPos; + token = saveToken; + tokenValue = saveTokenValue; + tokenFlags = saveTokenFlags; + return result; + } + function lookAhead(callback) { + return speculationHelper(callback, /*isLookahead*/ true); + } + function tryScan(callback) { + return speculationHelper(callback, /*isLookahead*/ false); + } + function getText() { + return text; + } + function setText(newText, start, length) { + text = newText || ""; + end = length === undefined ? text.length : start + length; + setTextPos(start || 0); + } + function setOnError(errorCallback) { + onError = errorCallback; + } + function setScriptTarget(scriptTarget) { + languageVersion = scriptTarget; + } + function setLanguageVariant(variant) { + languageVariant = variant; + } + function setTextPos(textPos) { + ts.Debug.assert(textPos >= 0); + pos = textPos; + startPos = textPos; + tokenPos = textPos; + token = 0 /* Unknown */; + tokenValue = undefined; + tokenFlags = 0; + } + function setInJSDocType(inType) { + inJSDocType += inType ? 1 : -1; + } + } + ts.createScanner = createScanner; +})(ts || (ts = {})); +var ts; +(function (ts) { + function isExternalModuleNameRelative(moduleName) { + // TypeScript 1.0 spec (April 2014): 11.2.1 + // An external module name is "relative" if the first term is "." or "..". + // Update: We also consider a path like `C:\foo.ts` "relative" because we do not search for it in `node_modules` or treat it as an ambient module. + return ts.pathIsRelative(moduleName) || ts.isRootedDiskPath(moduleName); + } + ts.isExternalModuleNameRelative = isExternalModuleNameRelative; + function sortAndDeduplicateDiagnostics(diagnostics) { + return ts.sortAndDeduplicate(diagnostics, ts.compareDiagnostics); + } + ts.sortAndDeduplicateDiagnostics = sortAndDeduplicateDiagnostics; +})(ts || (ts = {})); +/* @internal */ +(function (ts) { + ts.resolvingEmptyArray = []; + ts.emptyMap = ts.createMap(); + ts.emptyUnderscoreEscapedMap = ts.emptyMap; + ts.externalHelpersModuleNameText = "tslib"; + ts.defaultMaximumTruncationLength = 160; + function getDeclarationOfKind(symbol, kind) { + var declarations = symbol.declarations; + if (declarations) { + for (var _i = 0, declarations_1 = declarations; _i < declarations_1.length; _i++) { + var declaration = declarations_1[_i]; + if (declaration.kind === kind) { + return declaration; + } + } + } + return undefined; + } + ts.getDeclarationOfKind = getDeclarationOfKind; + /** Create a new escaped identifier map. */ + function createUnderscoreEscapedMap() { + return new ts.MapCtr(); + } + ts.createUnderscoreEscapedMap = createUnderscoreEscapedMap; + function hasEntries(map) { + return !!map && !!map.size; + } + ts.hasEntries = hasEntries; + function createSymbolTable(symbols) { + var result = ts.createMap(); + if (symbols) { + for (var _i = 0, symbols_1 = symbols; _i < symbols_1.length; _i++) { + var symbol = symbols_1[_i]; + result.set(symbol.escapedName, symbol); + } + } + return result; + } + ts.createSymbolTable = createSymbolTable; + var stringWriter = createSingleLineStringWriter(); + function createSingleLineStringWriter() { + var str = ""; + var writeText = function (text) { return str += text; }; + return { + getText: function () { return str; }, + write: writeText, + rawWrite: writeText, + writeKeyword: writeText, + writeOperator: writeText, + writePunctuation: writeText, + writeSpace: writeText, + writeStringLiteral: writeText, + writeLiteral: writeText, + writeParameter: writeText, + writeProperty: writeText, + writeSymbol: function (s, _) { return writeText(s); }, + writeTrailingSemicolon: writeText, + writeComment: writeText, + getTextPos: function () { return str.length; }, + getLine: function () { return 0; }, + getColumn: function () { return 0; }, + getIndent: function () { return 0; }, + isAtStartOfLine: function () { return false; }, + // Completely ignore indentation for string writers. And map newlines to + // a single space. + writeLine: function () { return str += " "; }, + increaseIndent: ts.noop, + decreaseIndent: ts.noop, + clear: function () { return str = ""; }, + trackSymbol: ts.noop, + reportInaccessibleThisError: ts.noop, + reportInaccessibleUniqueSymbolError: ts.noop, + reportPrivateInBaseOfClassExpression: ts.noop, + }; + } + function toPath(fileName, basePath, getCanonicalFileName) { + var nonCanonicalizedPath = ts.isRootedDiskPath(fileName) + ? ts.normalizePath(fileName) + : ts.getNormalizedAbsolutePath(fileName, basePath); + return getCanonicalFileName(nonCanonicalizedPath); + } + ts.toPath = toPath; + function changesAffectModuleResolution(oldOptions, newOptions) { + return oldOptions.configFilePath !== newOptions.configFilePath || ts.moduleResolutionOptionDeclarations.some(function (o) { + return !ts.isJsonEqual(ts.getCompilerOptionValue(oldOptions, o), ts.getCompilerOptionValue(newOptions, o)); + }); + } + ts.changesAffectModuleResolution = changesAffectModuleResolution; + function findAncestor(node, callback) { + while (node) { + var result = callback(node); + if (result === "quit") { + return undefined; + } + else if (result) { + return node; + } + node = node.parent; + } + return undefined; + } + ts.findAncestor = findAncestor; + function forEachAncestor(node, callback) { + while (true) { + var res = callback(node); + if (res === "quit") + return undefined; + if (res !== undefined) + return res; + if (ts.isSourceFile(node)) + return undefined; + node = node.parent; + } + } + ts.forEachAncestor = forEachAncestor; + function forEachEntry(map, callback) { + var _a; + var iterator = map.entries(); + for (var _b = iterator.next(), pair = _b.value, done = _b.done; !done; _a = iterator.next(), pair = _a.value, done = _a.done, _a) { + var key = pair[0], value = pair[1]; + var result = callback(value, key); + if (result) { + return result; + } + } + return undefined; + } + ts.forEachEntry = forEachEntry; + function forEachKey(map, callback) { + var _a; + var iterator = map.keys(); + for (var _b = iterator.next(), key = _b.value, done = _b.done; !done; _a = iterator.next(), key = _a.value, done = _a.done, _a) { + var result = callback(key); + if (result) { + return result; + } + } + return undefined; + } + ts.forEachKey = forEachKey; + function copyEntries(source, target) { + source.forEach(function (value, key) { + target.set(key, value); + }); + } + ts.copyEntries = copyEntries; + function arrayToSet(array, makeKey) { + return ts.arrayToMap(array, makeKey || (function (s) { return s; }), function () { return true; }); + } + ts.arrayToSet = arrayToSet; + function cloneMap(map) { + var clone = ts.createMap(); + copyEntries(map, clone); + return clone; + } + ts.cloneMap = cloneMap; + function usingSingleLineStringWriter(action) { + var oldString = stringWriter.getText(); + try { + action(stringWriter); + return stringWriter.getText(); + } + finally { + stringWriter.clear(); + stringWriter.writeKeyword(oldString); + } + } + ts.usingSingleLineStringWriter = usingSingleLineStringWriter; + function getFullWidth(node) { + return node.end - node.pos; + } + ts.getFullWidth = getFullWidth; + function getResolvedModule(sourceFile, moduleNameText) { + return sourceFile && sourceFile.resolvedModules && sourceFile.resolvedModules.get(moduleNameText); + } + ts.getResolvedModule = getResolvedModule; + function setResolvedModule(sourceFile, moduleNameText, resolvedModule) { + if (!sourceFile.resolvedModules) { + sourceFile.resolvedModules = ts.createMap(); + } + sourceFile.resolvedModules.set(moduleNameText, resolvedModule); + } + ts.setResolvedModule = setResolvedModule; + function setResolvedTypeReferenceDirective(sourceFile, typeReferenceDirectiveName, resolvedTypeReferenceDirective) { + if (!sourceFile.resolvedTypeReferenceDirectiveNames) { + sourceFile.resolvedTypeReferenceDirectiveNames = ts.createMap(); + } + sourceFile.resolvedTypeReferenceDirectiveNames.set(typeReferenceDirectiveName, resolvedTypeReferenceDirective); + } + ts.setResolvedTypeReferenceDirective = setResolvedTypeReferenceDirective; + function projectReferenceIsEqualTo(oldRef, newRef) { + return oldRef.path === newRef.path && + !oldRef.prepend === !newRef.prepend && + !oldRef.circular === !newRef.circular; + } + ts.projectReferenceIsEqualTo = projectReferenceIsEqualTo; + function moduleResolutionIsEqualTo(oldResolution, newResolution) { + return oldResolution.isExternalLibraryImport === newResolution.isExternalLibraryImport && + oldResolution.extension === newResolution.extension && + oldResolution.resolvedFileName === newResolution.resolvedFileName && + oldResolution.originalPath === newResolution.originalPath && + packageIdIsEqual(oldResolution.packageId, newResolution.packageId); + } + ts.moduleResolutionIsEqualTo = moduleResolutionIsEqualTo; + function packageIdIsEqual(a, b) { + return a === b || !!a && !!b && a.name === b.name && a.subModuleName === b.subModuleName && a.version === b.version; + } + function packageIdToString(_a) { + var name = _a.name, subModuleName = _a.subModuleName, version = _a.version; + var fullName = subModuleName ? name + "/" + subModuleName : name; + return fullName + "@" + version; + } + ts.packageIdToString = packageIdToString; + function typeDirectiveIsEqualTo(oldResolution, newResolution) { + return oldResolution.resolvedFileName === newResolution.resolvedFileName && oldResolution.primary === newResolution.primary; + } + ts.typeDirectiveIsEqualTo = typeDirectiveIsEqualTo; + function hasChangesInResolutions(names, newResolutions, oldResolutions, comparer) { + ts.Debug.assert(names.length === newResolutions.length); + for (var i = 0; i < names.length; i++) { + var newResolution = newResolutions[i]; + var oldResolution = oldResolutions && oldResolutions.get(names[i]); + var changed = oldResolution + ? !newResolution || !comparer(oldResolution, newResolution) + : newResolution; + if (changed) { + return true; + } + } + return false; + } + ts.hasChangesInResolutions = hasChangesInResolutions; + // Returns true if this node contains a parse error anywhere underneath it. + function containsParseError(node) { + aggregateChildData(node); + return (node.flags & 131072 /* ThisNodeOrAnySubNodesHasError */) !== 0; + } + ts.containsParseError = containsParseError; + function aggregateChildData(node) { + if (!(node.flags & 262144 /* HasAggregatedChildData */)) { + // A node is considered to contain a parse error if: + // a) the parser explicitly marked that it had an error + // b) any of it's children reported that it had an error. + var thisNodeOrAnySubNodesHasError = ((node.flags & 32768 /* ThisNodeHasError */) !== 0) || + ts.forEachChild(node, containsParseError); + // If so, mark ourselves accordingly. + if (thisNodeOrAnySubNodesHasError) { + node.flags |= 131072 /* ThisNodeOrAnySubNodesHasError */; + } + // Also mark that we've propagated the child information to this node. This way we can + // always consult the bit directly on this node without needing to check its children + // again. + node.flags |= 262144 /* HasAggregatedChildData */; + } + } + function getSourceFileOfNode(node) { + while (node && node.kind !== 279 /* SourceFile */) { + node = node.parent; + } + return node; + } + ts.getSourceFileOfNode = getSourceFileOfNode; + function isStatementWithLocals(node) { + switch (node.kind) { + case 218 /* Block */: + case 246 /* CaseBlock */: + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + return true; + } + return false; + } + ts.isStatementWithLocals = isStatementWithLocals; + function getStartPositionOfLine(line, sourceFile) { + ts.Debug.assert(line >= 0); + return ts.getLineStarts(sourceFile)[line]; + } + ts.getStartPositionOfLine = getStartPositionOfLine; + // This is a useful function for debugging purposes. + function nodePosToString(node) { + var file = getSourceFileOfNode(node); + var loc = ts.getLineAndCharacterOfPosition(file, node.pos); + return file.fileName + "(" + (loc.line + 1) + "," + (loc.character + 1) + ")"; + } + ts.nodePosToString = nodePosToString; + function getEndLinePosition(line, sourceFile) { + ts.Debug.assert(line >= 0); + var lineStarts = ts.getLineStarts(sourceFile); + var lineIndex = line; + var sourceText = sourceFile.text; + if (lineIndex + 1 === lineStarts.length) { + // last line - return EOF + return sourceText.length - 1; + } + else { + // current line start + var start = lineStarts[lineIndex]; + // take the start position of the next line - 1 = it should be some line break + var pos = lineStarts[lineIndex + 1] - 1; + ts.Debug.assert(ts.isLineBreak(sourceText.charCodeAt(pos))); + // walk backwards skipping line breaks, stop the the beginning of current line. + // i.e: + // + // $ <- end of line for this position should match the start position + while (start <= pos && ts.isLineBreak(sourceText.charCodeAt(pos))) { + pos--; + } + return pos; + } + } + ts.getEndLinePosition = getEndLinePosition; + /** + * Returns a value indicating whether a name is unique globally or within the current file. + * Note: This does not consider whether a name appears as a free identifier or not, so at the expression `x.y` this includes both `x` and `y`. + */ + function isFileLevelUniqueName(sourceFile, name, hasGlobalName) { + return !(hasGlobalName && hasGlobalName(name)) && !sourceFile.identifiers.has(name); + } + ts.isFileLevelUniqueName = isFileLevelUniqueName; + // Returns true if this node is missing from the actual source code. A 'missing' node is different + // from 'undefined/defined'. When a node is undefined (which can happen for optional nodes + // in the tree), it is definitely missing. However, a node may be defined, but still be + // missing. This happens whenever the parser knows it needs to parse something, but can't + // get anything in the source code that it expects at that location. For example: + // + // let a: ; + // + // Here, the Type in the Type-Annotation is not-optional (as there is a colon in the source + // code). So the parser will attempt to parse out a type, and will create an actual node. + // However, this node will be 'missing' in the sense that no actual source-code/tokens are + // contained within it. + function nodeIsMissing(node) { + if (node === undefined) { + return true; + } + return node.pos === node.end && node.pos >= 0 && node.kind !== 1 /* EndOfFileToken */; + } + ts.nodeIsMissing = nodeIsMissing; + function nodeIsPresent(node) { + return !nodeIsMissing(node); + } + ts.nodeIsPresent = nodeIsPresent; + /** + * Prepends statements to an array while taking care of prologue directives. + */ + function addStatementsAfterPrologue(to, from) { + if (from === undefined || from.length === 0) + return to; + var statementIndex = 0; + // skip all prologue directives to insert at the correct position + for (; statementIndex < to.length; ++statementIndex) { + if (!isPrologueDirective(to[statementIndex])) { + break; + } + } + to.splice.apply(to, [statementIndex, 0].concat(from)); + return to; + } + ts.addStatementsAfterPrologue = addStatementsAfterPrologue; + /** + * Determine if the given comment is a triple-slash + * + * @return true if the comment is a triple-slash comment else false + */ + function isRecognizedTripleSlashComment(text, commentPos, commentEnd) { + // Verify this is /// comment, but do the regexp match only when we first can find /// in the comment text + // so that we don't end up computing comment string and doing match for all // comments + if (text.charCodeAt(commentPos + 1) === 47 /* slash */ && + commentPos + 2 < commentEnd && + text.charCodeAt(commentPos + 2) === 47 /* slash */) { + var textSubStr = text.substring(commentPos, commentEnd); + return textSubStr.match(ts.fullTripleSlashReferencePathRegEx) || + textSubStr.match(ts.fullTripleSlashAMDReferencePathRegEx) || + textSubStr.match(fullTripleSlashReferenceTypeReferenceDirectiveRegEx) || + textSubStr.match(defaultLibReferenceRegEx) ? + true : false; + } + return false; + } + ts.isRecognizedTripleSlashComment = isRecognizedTripleSlashComment; + function isPinnedComment(text, start) { + return text.charCodeAt(start + 1) === 42 /* asterisk */ && + text.charCodeAt(start + 2) === 33 /* exclamation */; + } + ts.isPinnedComment = isPinnedComment; + function getTokenPosOfNode(node, sourceFile, includeJsDoc) { + // With nodes that have no width (i.e. 'Missing' nodes), we actually *don't* + // want to skip trivia because this will launch us forward to the next token. + if (nodeIsMissing(node)) { + return node.pos; + } + if (ts.isJSDocNode(node)) { + return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos, /*stopAfterLineBreak*/ false, /*stopAtComments*/ true); + } + if (includeJsDoc && ts.hasJSDocNodes(node)) { + return getTokenPosOfNode(node.jsDoc[0]); + } + // For a syntax list, it is possible that one of its children has JSDocComment nodes, while + // the syntax list itself considers them as normal trivia. Therefore if we simply skip + // trivia for the list, we may have skipped the JSDocComment as well. So we should process its + // first child to determine the actual position of its first token. + if (node.kind === 306 /* SyntaxList */ && node._children.length > 0) { + return getTokenPosOfNode(node._children[0], sourceFile, includeJsDoc); + } + return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos); + } + ts.getTokenPosOfNode = getTokenPosOfNode; + function getNonDecoratorTokenPosOfNode(node, sourceFile) { + if (nodeIsMissing(node) || !node.decorators) { + return getTokenPosOfNode(node, sourceFile); + } + return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.decorators.end); + } + ts.getNonDecoratorTokenPosOfNode = getNonDecoratorTokenPosOfNode; + function getSourceTextOfNodeFromSourceFile(sourceFile, node, includeTrivia) { + if (includeTrivia === void 0) { includeTrivia = false; } + return getTextOfNodeFromSourceText(sourceFile.text, node, includeTrivia); + } + ts.getSourceTextOfNodeFromSourceFile = getSourceTextOfNodeFromSourceFile; + function isJSDocTypeExpressionOrChild(node) { + return node.kind === 283 /* JSDocTypeExpression */ || (node.parent && isJSDocTypeExpressionOrChild(node.parent)); + } + function getTextOfNodeFromSourceText(sourceText, node, includeTrivia) { + if (includeTrivia === void 0) { includeTrivia = false; } + if (nodeIsMissing(node)) { + return ""; + } + var text = sourceText.substring(includeTrivia ? node.pos : ts.skipTrivia(sourceText, node.pos), node.end); + if (isJSDocTypeExpressionOrChild(node)) { + // strip space + asterisk at line start + text = text.replace(/(^|\r?\n|\r)\s*\*\s*/g, "$1"); + } + return text; + } + ts.getTextOfNodeFromSourceText = getTextOfNodeFromSourceText; + function getTextOfNode(node, includeTrivia) { + if (includeTrivia === void 0) { includeTrivia = false; } + return getSourceTextOfNodeFromSourceFile(getSourceFileOfNode(node), node, includeTrivia); + } + ts.getTextOfNode = getTextOfNode; + function getPos(range) { + return range.pos; + } + /** + * Note: it is expected that the `nodeArray` and the `node` are within the same file. + * For example, searching for a `SourceFile` in a `SourceFile[]` wouldn't work. + */ + function indexOfNode(nodeArray, node) { + return ts.binarySearch(nodeArray, node, getPos, ts.compareValues); + } + ts.indexOfNode = indexOfNode; + /** + * Gets flags that control emit behavior of a node. + */ + function getEmitFlags(node) { + var emitNode = node.emitNode; + return emitNode && emitNode.flags || 0; + } + ts.getEmitFlags = getEmitFlags; + function getLiteralText(node, sourceFile, neverAsciiEscape) { + // If we don't need to downlevel and we can reach the original source text using + // the node's parent reference, then simply get the text as it was originally written. + if (!nodeIsSynthesized(node) && node.parent && !((ts.isNumericLiteral(node) && node.numericLiteralFlags & 512 /* ContainsSeparator */) || + ts.isBigIntLiteral(node))) { + return getSourceTextOfNodeFromSourceFile(sourceFile, node); + } + var escapeText = neverAsciiEscape || (getEmitFlags(node) & 16777216 /* NoAsciiEscaping */) ? escapeString : escapeNonAsciiString; + // If we can't reach the original source text, use the canonical form if it's a number, + // or a (possibly escaped) quoted form of the original text if it's string-like. + switch (node.kind) { + case 10 /* StringLiteral */: + if (node.singleQuote) { + return "'" + escapeText(node.text, 39 /* singleQuote */) + "'"; + } + else { + return '"' + escapeText(node.text, 34 /* doubleQuote */) + '"'; + } + case 14 /* NoSubstitutionTemplateLiteral */: + return "`" + escapeText(node.text, 96 /* backtick */) + "`"; + case 15 /* TemplateHead */: + // tslint:disable-next-line no-invalid-template-strings + return "`" + escapeText(node.text, 96 /* backtick */) + "${"; + case 16 /* TemplateMiddle */: + // tslint:disable-next-line no-invalid-template-strings + return "}" + escapeText(node.text, 96 /* backtick */) + "${"; + case 17 /* TemplateTail */: + return "}" + escapeText(node.text, 96 /* backtick */) + "`"; + case 8 /* NumericLiteral */: + case 9 /* BigIntLiteral */: + case 13 /* RegularExpressionLiteral */: + return node.text; + } + return ts.Debug.fail("Literal kind '" + node.kind + "' not accounted for."); + } + ts.getLiteralText = getLiteralText; + function getTextOfConstantValue(value) { + return ts.isString(value) ? '"' + escapeNonAsciiString(value) + '"' : "" + value; + } + ts.getTextOfConstantValue = getTextOfConstantValue; + // Make an identifier from an external module name by extracting the string after the last "/" and replacing + // all non-alphanumeric characters with underscores + function makeIdentifierFromModuleName(moduleName) { + return ts.getBaseFileName(moduleName).replace(/^(\d)/, "_$1").replace(/\W/g, "_"); + } + ts.makeIdentifierFromModuleName = makeIdentifierFromModuleName; + function isBlockOrCatchScoped(declaration) { + return (ts.getCombinedNodeFlags(declaration) & 3 /* BlockScoped */) !== 0 || + isCatchClauseVariableDeclarationOrBindingElement(declaration); + } + ts.isBlockOrCatchScoped = isBlockOrCatchScoped; + function isCatchClauseVariableDeclarationOrBindingElement(declaration) { + var node = getRootDeclaration(declaration); + return node.kind === 237 /* VariableDeclaration */ && node.parent.kind === 274 /* CatchClause */; + } + ts.isCatchClauseVariableDeclarationOrBindingElement = isCatchClauseVariableDeclarationOrBindingElement; + function isAmbientModule(node) { + return ts.isModuleDeclaration(node) && (node.name.kind === 10 /* StringLiteral */ || isGlobalScopeAugmentation(node)); + } + ts.isAmbientModule = isAmbientModule; + function isModuleWithStringLiteralName(node) { + return ts.isModuleDeclaration(node) && node.name.kind === 10 /* StringLiteral */; + } + ts.isModuleWithStringLiteralName = isModuleWithStringLiteralName; + function isNonGlobalAmbientModule(node) { + return ts.isModuleDeclaration(node) && ts.isStringLiteral(node.name); + } + ts.isNonGlobalAmbientModule = isNonGlobalAmbientModule; + /** + * An effective module (namespace) declaration is either + * 1. An actual declaration: namespace X { ... } + * 2. A Javascript declaration, which is: + * An identifier in a nested property access expression: Y in `X.Y.Z = { ... }` + */ + function isEffectiveModuleDeclaration(node) { + return ts.isModuleDeclaration(node) || ts.isIdentifier(node); + } + ts.isEffectiveModuleDeclaration = isEffectiveModuleDeclaration; + /** Given a symbol for a module, checks that it is a shorthand ambient module. */ + function isShorthandAmbientModuleSymbol(moduleSymbol) { + return isShorthandAmbientModule(moduleSymbol.valueDeclaration); + } + ts.isShorthandAmbientModuleSymbol = isShorthandAmbientModuleSymbol; + function isShorthandAmbientModule(node) { + // The only kind of module that can be missing a body is a shorthand ambient module. + return node && node.kind === 244 /* ModuleDeclaration */ && (!node.body); + } + function isBlockScopedContainerTopLevel(node) { + return node.kind === 279 /* SourceFile */ || + node.kind === 244 /* ModuleDeclaration */ || + ts.isFunctionLike(node); + } + ts.isBlockScopedContainerTopLevel = isBlockScopedContainerTopLevel; + function isGlobalScopeAugmentation(module) { + return !!(module.flags & 512 /* GlobalAugmentation */); + } + ts.isGlobalScopeAugmentation = isGlobalScopeAugmentation; + function isExternalModuleAugmentation(node) { + return isAmbientModule(node) && isModuleAugmentationExternal(node); + } + ts.isExternalModuleAugmentation = isExternalModuleAugmentation; + function isModuleAugmentationExternal(node) { + // external module augmentation is a ambient module declaration that is either: + // - defined in the top level scope and source file is an external module + // - defined inside ambient module declaration located in the top level scope and source file not an external module + switch (node.parent.kind) { + case 279 /* SourceFile */: + return ts.isExternalModule(node.parent); + case 245 /* ModuleBlock */: + return isAmbientModule(node.parent.parent) && ts.isSourceFile(node.parent.parent.parent) && !ts.isExternalModule(node.parent.parent.parent); + } + return false; + } + ts.isModuleAugmentationExternal = isModuleAugmentationExternal; + function getNonAugmentationDeclaration(symbol) { + return ts.find(symbol.declarations, function (d) { return !isExternalModuleAugmentation(d) && !(ts.isModuleDeclaration(d) && isGlobalScopeAugmentation(d)); }); + } + ts.getNonAugmentationDeclaration = getNonAugmentationDeclaration; + function isEffectiveExternalModule(node, compilerOptions) { + return ts.isExternalModule(node) || compilerOptions.isolatedModules || ((ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS) && !!node.commonJsModuleIndicator); + } + ts.isEffectiveExternalModule = isEffectiveExternalModule; + function isBlockScope(node, parentNode) { + switch (node.kind) { + case 279 /* SourceFile */: + case 246 /* CaseBlock */: + case 274 /* CatchClause */: + case 244 /* ModuleDeclaration */: + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + case 157 /* Constructor */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + return true; + case 218 /* Block */: + // function block is not considered block-scope container + // see comment in binder.ts: bind(...), case for SyntaxKind.Block + return !ts.isFunctionLike(parentNode); + } + return false; + } + ts.isBlockScope = isBlockScope; + function isDeclarationWithTypeParameters(node) { + switch (node.kind) { + case 297 /* JSDocCallbackTag */: + case 304 /* JSDocTypedefTag */: + case 293 /* JSDocSignature */: + return true; + default: + ts.assertType(node); + return isDeclarationWithTypeParameterChildren(node); + } + } + ts.isDeclarationWithTypeParameters = isDeclarationWithTypeParameters; + function isDeclarationWithTypeParameterChildren(node) { + switch (node.kind) { + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 155 /* MethodSignature */: + case 162 /* IndexSignature */: + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + case 289 /* JSDocFunctionType */: + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 241 /* InterfaceDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 303 /* JSDocTemplateTag */: + case 239 /* FunctionDeclaration */: + case 156 /* MethodDeclaration */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + return true; + default: + ts.assertType(node); + return false; + } + } + ts.isDeclarationWithTypeParameterChildren = isDeclarationWithTypeParameterChildren; + function isAnyImportSyntax(node) { + switch (node.kind) { + case 249 /* ImportDeclaration */: + case 248 /* ImportEqualsDeclaration */: + return true; + default: + return false; + } + } + ts.isAnyImportSyntax = isAnyImportSyntax; + function isLateVisibilityPaintedStatement(node) { + switch (node.kind) { + case 249 /* ImportDeclaration */: + case 248 /* ImportEqualsDeclaration */: + case 219 /* VariableStatement */: + case 240 /* ClassDeclaration */: + case 239 /* FunctionDeclaration */: + case 244 /* ModuleDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 241 /* InterfaceDeclaration */: + case 243 /* EnumDeclaration */: + return true; + default: + return false; + } + } + ts.isLateVisibilityPaintedStatement = isLateVisibilityPaintedStatement; + function isAnyImportOrReExport(node) { + return isAnyImportSyntax(node) || ts.isExportDeclaration(node); + } + ts.isAnyImportOrReExport = isAnyImportOrReExport; + // Gets the nearest enclosing block scope container that has the provided node + // as a descendant, that is not the provided node. + function getEnclosingBlockScopeContainer(node) { + return findAncestor(node.parent, function (current) { return isBlockScope(current, current.parent); }); + } + ts.getEnclosingBlockScopeContainer = getEnclosingBlockScopeContainer; + // Return display name of an identifier + // Computed property names will just be emitted as "[]", where is the source + // text of the expression in the computed property. + function declarationNameToString(name) { + return !name || getFullWidth(name) === 0 ? "(Missing)" : getTextOfNode(name); + } + ts.declarationNameToString = declarationNameToString; + function getNameFromIndexInfo(info) { + return info.declaration ? declarationNameToString(info.declaration.parameters[0].name) : undefined; + } + ts.getNameFromIndexInfo = getNameFromIndexInfo; + function getTextOfPropertyName(name) { + switch (name.kind) { + case 72 /* Identifier */: + return name.escapedText; + case 10 /* StringLiteral */: + case 8 /* NumericLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: + return ts.escapeLeadingUnderscores(name.text); + case 149 /* ComputedPropertyName */: + return isStringOrNumericLiteralLike(name.expression) ? ts.escapeLeadingUnderscores(name.expression.text) : undefined; // TODO: GH#18217 Almost all uses of this assume the result to be defined! + default: + return ts.Debug.assertNever(name); + } + } + ts.getTextOfPropertyName = getTextOfPropertyName; + function entityNameToString(name) { + switch (name.kind) { + case 72 /* Identifier */: + return getFullWidth(name) === 0 ? ts.idText(name) : getTextOfNode(name); + case 148 /* QualifiedName */: + return entityNameToString(name.left) + "." + entityNameToString(name.right); + case 189 /* PropertyAccessExpression */: + return entityNameToString(name.expression) + "." + entityNameToString(name.name); + default: + throw ts.Debug.assertNever(name); + } + } + ts.entityNameToString = entityNameToString; + function createDiagnosticForNode(node, message, arg0, arg1, arg2, arg3) { + var sourceFile = getSourceFileOfNode(node); + return createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2, arg3); + } + ts.createDiagnosticForNode = createDiagnosticForNode; + function createDiagnosticForNodeArray(sourceFile, nodes, message, arg0, arg1, arg2, arg3) { + var start = ts.skipTrivia(sourceFile.text, nodes.pos); + return ts.createFileDiagnostic(sourceFile, start, nodes.end - start, message, arg0, arg1, arg2, arg3); + } + ts.createDiagnosticForNodeArray = createDiagnosticForNodeArray; + function createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2, arg3) { + var span = getErrorSpanForNode(sourceFile, node); + return ts.createFileDiagnostic(sourceFile, span.start, span.length, message, arg0, arg1, arg2, arg3); + } + ts.createDiagnosticForNodeInSourceFile = createDiagnosticForNodeInSourceFile; + function createDiagnosticForNodeFromMessageChain(node, messageChain, relatedInformation) { + var sourceFile = getSourceFileOfNode(node); + var span = getErrorSpanForNode(sourceFile, node); + return { + file: sourceFile, + start: span.start, + length: span.length, + code: messageChain.code, + category: messageChain.category, + messageText: messageChain.next ? messageChain : messageChain.messageText, + relatedInformation: relatedInformation + }; + } + ts.createDiagnosticForNodeFromMessageChain = createDiagnosticForNodeFromMessageChain; + function getSpanOfTokenAtPosition(sourceFile, pos) { + var scanner = ts.createScanner(sourceFile.languageVersion, /*skipTrivia*/ true, sourceFile.languageVariant, sourceFile.text, /*onError:*/ undefined, pos); + scanner.scan(); + var start = scanner.getTokenPos(); + return ts.createTextSpanFromBounds(start, scanner.getTextPos()); + } + ts.getSpanOfTokenAtPosition = getSpanOfTokenAtPosition; + function getErrorSpanForArrowFunction(sourceFile, node) { + var pos = ts.skipTrivia(sourceFile.text, node.pos); + if (node.body && node.body.kind === 218 /* Block */) { + var startLine = ts.getLineAndCharacterOfPosition(sourceFile, node.body.pos).line; + var endLine = ts.getLineAndCharacterOfPosition(sourceFile, node.body.end).line; + if (startLine < endLine) { + // The arrow function spans multiple lines, + // make the error span be the first line, inclusive. + return ts.createTextSpan(pos, getEndLinePosition(startLine, sourceFile) - pos + 1); + } + } + return ts.createTextSpanFromBounds(pos, node.end); + } + function getErrorSpanForNode(sourceFile, node) { + var errorNode = node; + switch (node.kind) { + case 279 /* SourceFile */: + var pos_1 = ts.skipTrivia(sourceFile.text, 0, /*stopAfterLineBreak*/ false); + if (pos_1 === sourceFile.text.length) { + // file is empty - return span for the beginning of the file + return ts.createTextSpan(0, 0); + } + return getSpanOfTokenAtPosition(sourceFile, pos_1); + // This list is a work in progress. Add missing node kinds to improve their error + // spans. + case 237 /* VariableDeclaration */: + case 186 /* BindingElement */: + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 241 /* InterfaceDeclaration */: + case 244 /* ModuleDeclaration */: + case 243 /* EnumDeclaration */: + case 278 /* EnumMember */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 242 /* TypeAliasDeclaration */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + errorNode = node.name; + break; + case 197 /* ArrowFunction */: + return getErrorSpanForArrowFunction(sourceFile, node); + } + if (errorNode === undefined) { + // If we don't have a better node, then just set the error on the first token of + // construct. + return getSpanOfTokenAtPosition(sourceFile, node.pos); + } + var isMissing = nodeIsMissing(errorNode); + var pos = isMissing + ? errorNode.pos + : ts.skipTrivia(sourceFile.text, errorNode.pos); + // These asserts should all be satisfied for a properly constructed `errorNode`. + if (isMissing) { + ts.Debug.assert(pos === errorNode.pos, "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809"); + ts.Debug.assert(pos === errorNode.end, "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809"); + } + else { + ts.Debug.assert(pos >= errorNode.pos, "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809"); + ts.Debug.assert(pos <= errorNode.end, "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809"); + } + return ts.createTextSpanFromBounds(pos, errorNode.end); + } + ts.getErrorSpanForNode = getErrorSpanForNode; + function isExternalOrCommonJsModule(file) { + return (file.externalModuleIndicator || file.commonJsModuleIndicator) !== undefined; + } + ts.isExternalOrCommonJsModule = isExternalOrCommonJsModule; + function isJsonSourceFile(file) { + return file.scriptKind === 6 /* JSON */; + } + ts.isJsonSourceFile = isJsonSourceFile; + function isEnumConst(node) { + return !!(ts.getCombinedModifierFlags(node) & 2048 /* Const */); + } + ts.isEnumConst = isEnumConst; + function isDeclarationReadonly(declaration) { + return !!(ts.getCombinedModifierFlags(declaration) & 64 /* Readonly */ && !ts.isParameterPropertyDeclaration(declaration)); + } + ts.isDeclarationReadonly = isDeclarationReadonly; + function isVarConst(node) { + return !!(ts.getCombinedNodeFlags(node) & 2 /* Const */); + } + ts.isVarConst = isVarConst; + function isLet(node) { + return !!(ts.getCombinedNodeFlags(node) & 1 /* Let */); + } + ts.isLet = isLet; + function isSuperCall(n) { + return n.kind === 191 /* CallExpression */ && n.expression.kind === 98 /* SuperKeyword */; + } + ts.isSuperCall = isSuperCall; + function isImportCall(n) { + return n.kind === 191 /* CallExpression */ && n.expression.kind === 92 /* ImportKeyword */; + } + ts.isImportCall = isImportCall; + function isLiteralImportTypeNode(n) { + return ts.isImportTypeNode(n) && ts.isLiteralTypeNode(n.argument) && ts.isStringLiteral(n.argument.literal); + } + ts.isLiteralImportTypeNode = isLiteralImportTypeNode; + function isPrologueDirective(node) { + return node.kind === 221 /* ExpressionStatement */ + && node.expression.kind === 10 /* StringLiteral */; + } + ts.isPrologueDirective = isPrologueDirective; + function getLeadingCommentRangesOfNode(node, sourceFileOfNode) { + return node.kind !== 11 /* JsxText */ ? ts.getLeadingCommentRanges(sourceFileOfNode.text, node.pos) : undefined; + } + ts.getLeadingCommentRangesOfNode = getLeadingCommentRangesOfNode; + function getJSDocCommentRanges(node, text) { + var commentRanges = (node.kind === 151 /* Parameter */ || + node.kind === 150 /* TypeParameter */ || + node.kind === 196 /* FunctionExpression */ || + node.kind === 197 /* ArrowFunction */ || + node.kind === 195 /* ParenthesizedExpression */) ? + ts.concatenate(ts.getTrailingCommentRanges(text, node.pos), ts.getLeadingCommentRanges(text, node.pos)) : + ts.getLeadingCommentRanges(text, node.pos); + // True if the comment starts with '/**' but not if it is '/**/' + return ts.filter(commentRanges, function (comment) { + return text.charCodeAt(comment.pos + 1) === 42 /* asterisk */ && + text.charCodeAt(comment.pos + 2) === 42 /* asterisk */ && + text.charCodeAt(comment.pos + 3) !== 47 /* slash */; + }); + } + ts.getJSDocCommentRanges = getJSDocCommentRanges; + ts.fullTripleSlashReferencePathRegEx = /^(\/\/\/\s*/; + var fullTripleSlashReferenceTypeReferenceDirectiveRegEx = /^(\/\/\/\s*/; + ts.fullTripleSlashAMDReferencePathRegEx = /^(\/\/\/\s*/; + var defaultLibReferenceRegEx = /^(\/\/\/\s*/; + function isPartOfTypeNode(node) { + if (163 /* FirstTypeNode */ <= node.kind && node.kind <= 183 /* LastTypeNode */) { + return true; + } + switch (node.kind) { + case 120 /* AnyKeyword */: + case 143 /* UnknownKeyword */: + case 135 /* NumberKeyword */: + case 146 /* BigIntKeyword */: + case 138 /* StringKeyword */: + case 123 /* BooleanKeyword */: + case 139 /* SymbolKeyword */: + case 136 /* ObjectKeyword */: + case 141 /* UndefinedKeyword */: + case 132 /* NeverKeyword */: + return true; + case 106 /* VoidKeyword */: + return node.parent.kind !== 200 /* VoidExpression */; + case 211 /* ExpressionWithTypeArguments */: + return !isExpressionWithTypeArgumentsInClassExtendsClause(node); + case 150 /* TypeParameter */: + return node.parent.kind === 181 /* MappedType */ || node.parent.kind === 176 /* InferType */; + // Identifiers and qualified names may be type nodes, depending on their context. Climb + // above them to find the lowest container + case 72 /* Identifier */: + // If the identifier is the RHS of a qualified name, then it's a type iff its parent is. + if (node.parent.kind === 148 /* QualifiedName */ && node.parent.right === node) { + node = node.parent; + } + else if (node.parent.kind === 189 /* PropertyAccessExpression */ && node.parent.name === node) { + node = node.parent; + } + // At this point, node is either a qualified name or an identifier + ts.Debug.assert(node.kind === 72 /* Identifier */ || node.kind === 148 /* QualifiedName */ || node.kind === 189 /* PropertyAccessExpression */, "'node' was expected to be a qualified name, identifier or property access in 'isPartOfTypeNode'."); + // falls through + case 148 /* QualifiedName */: + case 189 /* PropertyAccessExpression */: + case 100 /* ThisKeyword */: { + var parent = node.parent; + if (parent.kind === 167 /* TypeQuery */) { + return false; + } + if (parent.kind === 183 /* ImportType */) { + return !parent.isTypeOf; + } + // Do not recursively call isPartOfTypeNode on the parent. In the example: + // + // let a: A.B.C; + // + // Calling isPartOfTypeNode would consider the qualified name A.B a type node. + // Only C and A.B.C are type nodes. + if (163 /* FirstTypeNode */ <= parent.kind && parent.kind <= 183 /* LastTypeNode */) { + return true; + } + switch (parent.kind) { + case 211 /* ExpressionWithTypeArguments */: + return !isExpressionWithTypeArgumentsInClassExtendsClause(parent); + case 150 /* TypeParameter */: + return node === parent.constraint; + case 303 /* JSDocTemplateTag */: + return node === parent.constraint; + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 151 /* Parameter */: + case 237 /* VariableDeclaration */: + return node === parent.type; + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 157 /* Constructor */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + return node === parent.type; + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 162 /* IndexSignature */: + return node === parent.type; + case 194 /* TypeAssertionExpression */: + return node === parent.type; + case 191 /* CallExpression */: + case 192 /* NewExpression */: + return ts.contains(parent.typeArguments, node); + case 193 /* TaggedTemplateExpression */: + // TODO (drosen): TaggedTemplateExpressions may eventually support type arguments. + return false; + } + } + } + return false; + } + ts.isPartOfTypeNode = isPartOfTypeNode; + function isChildOfNodeWithKind(node, kind) { + while (node) { + if (node.kind === kind) { + return true; + } + node = node.parent; + } + return false; + } + ts.isChildOfNodeWithKind = isChildOfNodeWithKind; + // Warning: This has the same semantics as the forEach family of functions, + // in that traversal terminates in the event that 'visitor' supplies a truthy value. + function forEachReturnStatement(body, visitor) { + return traverse(body); + function traverse(node) { + switch (node.kind) { + case 230 /* ReturnStatement */: + return visitor(node); + case 246 /* CaseBlock */: + case 218 /* Block */: + case 222 /* IfStatement */: + case 223 /* DoStatement */: + case 224 /* WhileStatement */: + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + case 231 /* WithStatement */: + case 232 /* SwitchStatement */: + case 271 /* CaseClause */: + case 272 /* DefaultClause */: + case 233 /* LabeledStatement */: + case 235 /* TryStatement */: + case 274 /* CatchClause */: + return ts.forEachChild(node, traverse); + } + } + } + ts.forEachReturnStatement = forEachReturnStatement; + function forEachYieldExpression(body, visitor) { + return traverse(body); + function traverse(node) { + switch (node.kind) { + case 207 /* YieldExpression */: + visitor(node); + var operand = node.expression; + if (operand) { + traverse(operand); + } + return; + case 243 /* EnumDeclaration */: + case 241 /* InterfaceDeclaration */: + case 244 /* ModuleDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + // These are not allowed inside a generator now, but eventually they may be allowed + // as local types. Regardless, any yield statements contained within them should be + // skipped in this traversal. + return; + default: + if (ts.isFunctionLike(node)) { + if (node.name && node.name.kind === 149 /* ComputedPropertyName */) { + // Note that we will not include methods/accessors of a class because they would require + // first descending into the class. This is by design. + traverse(node.name.expression); + return; + } + } + else if (!isPartOfTypeNode(node)) { + // This is the general case, which should include mostly expressions and statements. + // Also includes NodeArrays. + ts.forEachChild(node, traverse); + } + } + } + } + ts.forEachYieldExpression = forEachYieldExpression; + /** + * Gets the most likely element type for a TypeNode. This is not an exhaustive test + * as it assumes a rest argument can only be an array type (either T[], or Array). + * + * @param node The type node. + */ + function getRestParameterElementType(node) { + if (node && node.kind === 169 /* ArrayType */) { + return node.elementType; + } + else if (node && node.kind === 164 /* TypeReference */) { + return ts.singleOrUndefined(node.typeArguments); + } + else { + return undefined; + } + } + ts.getRestParameterElementType = getRestParameterElementType; + function getMembersOfDeclaration(node) { + switch (node.kind) { + case 241 /* InterfaceDeclaration */: + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 168 /* TypeLiteral */: + return node.members; + case 188 /* ObjectLiteralExpression */: + return node.properties; + } + } + ts.getMembersOfDeclaration = getMembersOfDeclaration; + function isVariableLike(node) { + if (node) { + switch (node.kind) { + case 186 /* BindingElement */: + case 278 /* EnumMember */: + case 151 /* Parameter */: + case 275 /* PropertyAssignment */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 276 /* ShorthandPropertyAssignment */: + case 237 /* VariableDeclaration */: + return true; + } + } + return false; + } + ts.isVariableLike = isVariableLike; + function isVariableLikeOrAccessor(node) { + return isVariableLike(node) || ts.isAccessor(node); + } + ts.isVariableLikeOrAccessor = isVariableLikeOrAccessor; + function isVariableDeclarationInVariableStatement(node) { + return node.parent.kind === 238 /* VariableDeclarationList */ + && node.parent.parent.kind === 219 /* VariableStatement */; + } + ts.isVariableDeclarationInVariableStatement = isVariableDeclarationInVariableStatement; + function isValidESSymbolDeclaration(node) { + return ts.isVariableDeclaration(node) ? isVarConst(node) && ts.isIdentifier(node.name) && isVariableDeclarationInVariableStatement(node) : + ts.isPropertyDeclaration(node) ? hasReadonlyModifier(node) && hasStaticModifier(node) : + ts.isPropertySignature(node) && hasReadonlyModifier(node); + } + ts.isValidESSymbolDeclaration = isValidESSymbolDeclaration; + function introducesArgumentsExoticObject(node) { + switch (node.kind) { + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + return true; + } + return false; + } + ts.introducesArgumentsExoticObject = introducesArgumentsExoticObject; + function unwrapInnermostStatementOfLabel(node, beforeUnwrapLabelCallback) { + while (true) { + if (beforeUnwrapLabelCallback) { + beforeUnwrapLabelCallback(node); + } + if (node.statement.kind !== 233 /* LabeledStatement */) { + return node.statement; + } + node = node.statement; + } + } + ts.unwrapInnermostStatementOfLabel = unwrapInnermostStatementOfLabel; + function isFunctionBlock(node) { + return node && node.kind === 218 /* Block */ && ts.isFunctionLike(node.parent); + } + ts.isFunctionBlock = isFunctionBlock; + function isObjectLiteralMethod(node) { + return node && node.kind === 156 /* MethodDeclaration */ && node.parent.kind === 188 /* ObjectLiteralExpression */; + } + ts.isObjectLiteralMethod = isObjectLiteralMethod; + function isObjectLiteralOrClassExpressionMethod(node) { + return node.kind === 156 /* MethodDeclaration */ && + (node.parent.kind === 188 /* ObjectLiteralExpression */ || + node.parent.kind === 209 /* ClassExpression */); + } + ts.isObjectLiteralOrClassExpressionMethod = isObjectLiteralOrClassExpressionMethod; + function isIdentifierTypePredicate(predicate) { + return predicate && predicate.kind === 1 /* Identifier */; + } + ts.isIdentifierTypePredicate = isIdentifierTypePredicate; + function isThisTypePredicate(predicate) { + return predicate && predicate.kind === 0 /* This */; + } + ts.isThisTypePredicate = isThisTypePredicate; + function getPropertyAssignment(objectLiteral, key, key2) { + return objectLiteral.properties.filter(function (property) { + if (property.kind === 275 /* PropertyAssignment */) { + var propName = getTextOfPropertyName(property.name); + return key === propName || (!!key2 && key2 === propName); + } + return false; + }); + } + ts.getPropertyAssignment = getPropertyAssignment; + function getTsConfigObjectLiteralExpression(tsConfigSourceFile) { + if (tsConfigSourceFile && tsConfigSourceFile.statements.length) { + var expression = tsConfigSourceFile.statements[0].expression; + return ts.tryCast(expression, ts.isObjectLiteralExpression); + } + } + ts.getTsConfigObjectLiteralExpression = getTsConfigObjectLiteralExpression; + function getTsConfigPropArrayElementValue(tsConfigSourceFile, propKey, elementValue) { + return ts.firstDefined(getTsConfigPropArray(tsConfigSourceFile, propKey), function (property) { + return ts.isArrayLiteralExpression(property.initializer) ? + ts.find(property.initializer.elements, function (element) { return ts.isStringLiteral(element) && element.text === elementValue; }) : + undefined; + }); + } + ts.getTsConfigPropArrayElementValue = getTsConfigPropArrayElementValue; + function getTsConfigPropArray(tsConfigSourceFile, propKey) { + var jsonObjectLiteral = getTsConfigObjectLiteralExpression(tsConfigSourceFile); + return jsonObjectLiteral ? getPropertyAssignment(jsonObjectLiteral, propKey) : ts.emptyArray; + } + ts.getTsConfigPropArray = getTsConfigPropArray; + function getContainingFunction(node) { + return findAncestor(node.parent, ts.isFunctionLike); + } + ts.getContainingFunction = getContainingFunction; + function getContainingClass(node) { + return findAncestor(node.parent, ts.isClassLike); + } + ts.getContainingClass = getContainingClass; + function getThisContainer(node, includeArrowFunctions) { + ts.Debug.assert(node.kind !== 279 /* SourceFile */); + while (true) { + node = node.parent; + if (!node) { + return ts.Debug.fail(); // If we never pass in a SourceFile, this should be unreachable, since we'll stop when we reach that. + } + switch (node.kind) { + case 149 /* ComputedPropertyName */: + // If the grandparent node is an object literal (as opposed to a class), + // then the computed property is not a 'this' container. + // A computed property name in a class needs to be a this container + // so that we can error on it. + if (ts.isClassLike(node.parent.parent)) { + return node; + } + // If this is a computed property, then the parent should not + // make it a this container. The parent might be a property + // in an object literal, like a method or accessor. But in order for + // such a parent to be a this container, the reference must be in + // the *body* of the container. + node = node.parent; + break; + case 152 /* Decorator */: + // Decorators are always applied outside of the body of a class or method. + if (node.parent.kind === 151 /* Parameter */ && ts.isClassElement(node.parent.parent)) { + // If the decorator's parent is a Parameter, we resolve the this container from + // the grandparent class declaration. + node = node.parent.parent; + } + else if (ts.isClassElement(node.parent)) { + // If the decorator's parent is a class element, we resolve the 'this' container + // from the parent class declaration. + node = node.parent; + } + break; + case 197 /* ArrowFunction */: + if (!includeArrowFunctions) { + continue; + } + // falls through + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 244 /* ModuleDeclaration */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 162 /* IndexSignature */: + case 243 /* EnumDeclaration */: + case 279 /* SourceFile */: + return node; + } + } + } + ts.getThisContainer = getThisContainer; + function getNewTargetContainer(node) { + var container = getThisContainer(node, /*includeArrowFunctions*/ false); + if (container) { + switch (container.kind) { + case 157 /* Constructor */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + return container; + } + } + return undefined; + } + ts.getNewTargetContainer = getNewTargetContainer; + /** + * Given an super call/property node, returns the closest node where + * - a super call/property access is legal in the node and not legal in the parent node the node. + * i.e. super call is legal in constructor but not legal in the class body. + * - the container is an arrow function (so caller might need to call getSuperContainer again in case it needs to climb higher) + * - a super call/property is definitely illegal in the container (but might be legal in some subnode) + * i.e. super property access is illegal in function declaration but can be legal in the statement list + */ + function getSuperContainer(node, stopOnFunctions) { + while (true) { + node = node.parent; + if (!node) { + return node; + } + switch (node.kind) { + case 149 /* ComputedPropertyName */: + node = node.parent; + break; + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + if (!stopOnFunctions) { + continue; + } + // falls through + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + return node; + case 152 /* Decorator */: + // Decorators are always applied outside of the body of a class or method. + if (node.parent.kind === 151 /* Parameter */ && ts.isClassElement(node.parent.parent)) { + // If the decorator's parent is a Parameter, we resolve the this container from + // the grandparent class declaration. + node = node.parent.parent; + } + else if (ts.isClassElement(node.parent)) { + // If the decorator's parent is a class element, we resolve the 'this' container + // from the parent class declaration. + node = node.parent; + } + break; + } + } + } + ts.getSuperContainer = getSuperContainer; + function getImmediatelyInvokedFunctionExpression(func) { + if (func.kind === 196 /* FunctionExpression */ || func.kind === 197 /* ArrowFunction */) { + var prev = func; + var parent = func.parent; + while (parent.kind === 195 /* ParenthesizedExpression */) { + prev = parent; + parent = parent.parent; + } + if (parent.kind === 191 /* CallExpression */ && parent.expression === prev) { + return parent; + } + } + } + ts.getImmediatelyInvokedFunctionExpression = getImmediatelyInvokedFunctionExpression; + /** + * Determines whether a node is a property or element access expression for `super`. + */ + function isSuperProperty(node) { + var kind = node.kind; + return (kind === 189 /* PropertyAccessExpression */ || kind === 190 /* ElementAccessExpression */) + && node.expression.kind === 98 /* SuperKeyword */; + } + ts.isSuperProperty = isSuperProperty; + /** + * Determines whether a node is a property or element access expression for `this`. + */ + function isThisProperty(node) { + var kind = node.kind; + return (kind === 189 /* PropertyAccessExpression */ || kind === 190 /* ElementAccessExpression */) + && node.expression.kind === 100 /* ThisKeyword */; + } + ts.isThisProperty = isThisProperty; + function getEntityNameFromTypeNode(node) { + switch (node.kind) { + case 164 /* TypeReference */: + return node.typeName; + case 211 /* ExpressionWithTypeArguments */: + return isEntityNameExpression(node.expression) + ? node.expression + : undefined; + case 72 /* Identifier */: + case 148 /* QualifiedName */: + return node; + } + return undefined; + } + ts.getEntityNameFromTypeNode = getEntityNameFromTypeNode; + function getInvokedExpression(node) { + switch (node.kind) { + case 193 /* TaggedTemplateExpression */: + return node.tag; + case 262 /* JsxOpeningElement */: + case 261 /* JsxSelfClosingElement */: + return node.tagName; + default: + return node.expression; + } + } + ts.getInvokedExpression = getInvokedExpression; + function nodeCanBeDecorated(node, parent, grandparent) { + switch (node.kind) { + case 240 /* ClassDeclaration */: + // classes are valid targets + return true; + case 154 /* PropertyDeclaration */: + // property declarations are valid if their parent is a class declaration. + return parent.kind === 240 /* ClassDeclaration */; + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 156 /* MethodDeclaration */: + // if this method has a body and its parent is a class declaration, this is a valid target. + return node.body !== undefined + && parent.kind === 240 /* ClassDeclaration */; + case 151 /* Parameter */: + // if the parameter's parent has a body and its grandparent is a class declaration, this is a valid target; + return parent.body !== undefined + && (parent.kind === 157 /* Constructor */ + || parent.kind === 156 /* MethodDeclaration */ + || parent.kind === 159 /* SetAccessor */) + && grandparent.kind === 240 /* ClassDeclaration */; + } + return false; + } + ts.nodeCanBeDecorated = nodeCanBeDecorated; + function nodeIsDecorated(node, parent, grandparent) { + return node.decorators !== undefined + && nodeCanBeDecorated(node, parent, grandparent); // TODO: GH#18217 + } + ts.nodeIsDecorated = nodeIsDecorated; + function nodeOrChildIsDecorated(node, parent, grandparent) { + return nodeIsDecorated(node, parent, grandparent) || childIsDecorated(node, parent); // TODO: GH#18217 + } + ts.nodeOrChildIsDecorated = nodeOrChildIsDecorated; + function childIsDecorated(node, parent) { + switch (node.kind) { + case 240 /* ClassDeclaration */: + return ts.some(node.members, function (m) { return nodeOrChildIsDecorated(m, node, parent); }); // TODO: GH#18217 + case 156 /* MethodDeclaration */: + case 159 /* SetAccessor */: + return ts.some(node.parameters, function (p) { return nodeIsDecorated(p, node, parent); }); // TODO: GH#18217 + default: + return false; + } + } + ts.childIsDecorated = childIsDecorated; + function isJSXTagName(node) { + var parent = node.parent; + if (parent.kind === 262 /* JsxOpeningElement */ || + parent.kind === 261 /* JsxSelfClosingElement */ || + parent.kind === 263 /* JsxClosingElement */) { + return parent.tagName === node; + } + return false; + } + ts.isJSXTagName = isJSXTagName; + function isExpressionNode(node) { + switch (node.kind) { + case 98 /* SuperKeyword */: + case 96 /* NullKeyword */: + case 102 /* TrueKeyword */: + case 87 /* FalseKeyword */: + case 13 /* RegularExpressionLiteral */: + case 187 /* ArrayLiteralExpression */: + case 188 /* ObjectLiteralExpression */: + case 189 /* PropertyAccessExpression */: + case 190 /* ElementAccessExpression */: + case 191 /* CallExpression */: + case 192 /* NewExpression */: + case 193 /* TaggedTemplateExpression */: + case 212 /* AsExpression */: + case 194 /* TypeAssertionExpression */: + case 213 /* NonNullExpression */: + case 195 /* ParenthesizedExpression */: + case 196 /* FunctionExpression */: + case 209 /* ClassExpression */: + case 197 /* ArrowFunction */: + case 200 /* VoidExpression */: + case 198 /* DeleteExpression */: + case 199 /* TypeOfExpression */: + case 202 /* PrefixUnaryExpression */: + case 203 /* PostfixUnaryExpression */: + case 204 /* BinaryExpression */: + case 205 /* ConditionalExpression */: + case 208 /* SpreadElement */: + case 206 /* TemplateExpression */: + case 14 /* NoSubstitutionTemplateLiteral */: + case 210 /* OmittedExpression */: + case 260 /* JsxElement */: + case 261 /* JsxSelfClosingElement */: + case 264 /* JsxFragment */: + case 207 /* YieldExpression */: + case 201 /* AwaitExpression */: + case 214 /* MetaProperty */: + return true; + case 148 /* QualifiedName */: + while (node.parent.kind === 148 /* QualifiedName */) { + node = node.parent; + } + return node.parent.kind === 167 /* TypeQuery */ || isJSXTagName(node); + case 72 /* Identifier */: + if (node.parent.kind === 167 /* TypeQuery */ || isJSXTagName(node)) { + return true; + } + // falls through + case 8 /* NumericLiteral */: + case 9 /* BigIntLiteral */: + case 10 /* StringLiteral */: + case 100 /* ThisKeyword */: + return isInExpressionContext(node); + default: + return false; + } + } + ts.isExpressionNode = isExpressionNode; + function isInExpressionContext(node) { + var parent = node.parent; + switch (parent.kind) { + case 237 /* VariableDeclaration */: + case 151 /* Parameter */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 278 /* EnumMember */: + case 275 /* PropertyAssignment */: + case 186 /* BindingElement */: + return parent.initializer === node; + case 221 /* ExpressionStatement */: + case 222 /* IfStatement */: + case 223 /* DoStatement */: + case 224 /* WhileStatement */: + case 230 /* ReturnStatement */: + case 231 /* WithStatement */: + case 232 /* SwitchStatement */: + case 271 /* CaseClause */: + case 234 /* ThrowStatement */: + return parent.expression === node; + case 225 /* ForStatement */: + var forStatement = parent; + return (forStatement.initializer === node && forStatement.initializer.kind !== 238 /* VariableDeclarationList */) || + forStatement.condition === node || + forStatement.incrementor === node; + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + var forInStatement = parent; + return (forInStatement.initializer === node && forInStatement.initializer.kind !== 238 /* VariableDeclarationList */) || + forInStatement.expression === node; + case 194 /* TypeAssertionExpression */: + case 212 /* AsExpression */: + return node === parent.expression; + case 216 /* TemplateSpan */: + return node === parent.expression; + case 149 /* ComputedPropertyName */: + return node === parent.expression; + case 152 /* Decorator */: + case 270 /* JsxExpression */: + case 269 /* JsxSpreadAttribute */: + case 277 /* SpreadAssignment */: + return true; + case 211 /* ExpressionWithTypeArguments */: + return parent.expression === node && isExpressionWithTypeArgumentsInClassExtendsClause(parent); + case 276 /* ShorthandPropertyAssignment */: + return parent.objectAssignmentInitializer === node; + default: + return isExpressionNode(parent); + } + } + ts.isInExpressionContext = isInExpressionContext; + function isExternalModuleImportEqualsDeclaration(node) { + return node.kind === 248 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 259 /* ExternalModuleReference */; + } + ts.isExternalModuleImportEqualsDeclaration = isExternalModuleImportEqualsDeclaration; + function getExternalModuleImportEqualsDeclarationExpression(node) { + ts.Debug.assert(isExternalModuleImportEqualsDeclaration(node)); + return node.moduleReference.expression; + } + ts.getExternalModuleImportEqualsDeclarationExpression = getExternalModuleImportEqualsDeclarationExpression; + function isInternalModuleImportEqualsDeclaration(node) { + return node.kind === 248 /* ImportEqualsDeclaration */ && node.moduleReference.kind !== 259 /* ExternalModuleReference */; + } + ts.isInternalModuleImportEqualsDeclaration = isInternalModuleImportEqualsDeclaration; + function isSourceFileJS(file) { + return isInJSFile(file); + } + ts.isSourceFileJS = isSourceFileJS; + function isSourceFileNotJS(file) { + return !isInJSFile(file); + } + ts.isSourceFileNotJS = isSourceFileNotJS; + function isInJSFile(node) { + return !!node && !!(node.flags & 65536 /* JavaScriptFile */); + } + ts.isInJSFile = isInJSFile; + function isInJsonFile(node) { + return !!node && !!(node.flags & 16777216 /* JsonFile */); + } + ts.isInJsonFile = isInJsonFile; + function isInJSDoc(node) { + return !!node && !!(node.flags & 2097152 /* JSDoc */); + } + ts.isInJSDoc = isInJSDoc; + function isJSDocIndexSignature(node) { + return ts.isTypeReferenceNode(node) && + ts.isIdentifier(node.typeName) && + node.typeName.escapedText === "Object" && + node.typeArguments && node.typeArguments.length === 2 && + (node.typeArguments[0].kind === 138 /* StringKeyword */ || node.typeArguments[0].kind === 135 /* NumberKeyword */); + } + ts.isJSDocIndexSignature = isJSDocIndexSignature; + function isRequireCall(callExpression, checkArgumentIsStringLiteralLike) { + if (callExpression.kind !== 191 /* CallExpression */) { + return false; + } + var _a = callExpression, expression = _a.expression, args = _a.arguments; + if (expression.kind !== 72 /* Identifier */ || expression.escapedText !== "require") { + return false; + } + if (args.length !== 1) { + return false; + } + var arg = args[0]; + return !checkArgumentIsStringLiteralLike || ts.isStringLiteralLike(arg); + } + ts.isRequireCall = isRequireCall; + function isSingleOrDoubleQuote(charCode) { + return charCode === 39 /* singleQuote */ || charCode === 34 /* doubleQuote */; + } + ts.isSingleOrDoubleQuote = isSingleOrDoubleQuote; + function isStringDoubleQuoted(str, sourceFile) { + return getSourceTextOfNodeFromSourceFile(sourceFile, str).charCodeAt(0) === 34 /* doubleQuote */; + } + ts.isStringDoubleQuoted = isStringDoubleQuoted; + function getDeclarationOfExpando(node) { + if (!node.parent) { + return undefined; + } + var name; + var decl; + if (ts.isVariableDeclaration(node.parent) && node.parent.initializer === node) { + if (!isInJSFile(node) && !isVarConst(node.parent)) { + return undefined; + } + name = node.parent.name; + decl = node.parent; + } + else if (ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 59 /* EqualsToken */ && node.parent.right === node) { + name = node.parent.left; + decl = name; + } + else if (ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 55 /* BarBarToken */) { + if (ts.isVariableDeclaration(node.parent.parent) && node.parent.parent.initializer === node.parent) { + name = node.parent.parent.name; + decl = node.parent.parent; + } + else if (ts.isBinaryExpression(node.parent.parent) && node.parent.parent.operatorToken.kind === 59 /* EqualsToken */ && node.parent.parent.right === node.parent) { + name = node.parent.parent.left; + decl = name; + } + if (!name || !isEntityNameExpression(name) || !isSameEntityName(name, node.parent.left)) { + return undefined; + } + } + if (!name || !getExpandoInitializer(node, isPrototypeAccess(name))) { + return undefined; + } + return decl; + } + ts.getDeclarationOfExpando = getDeclarationOfExpando; + function isAssignmentDeclaration(decl) { + return ts.isBinaryExpression(decl) || ts.isPropertyAccessExpression(decl) || ts.isIdentifier(decl) || ts.isCallExpression(decl); + } + ts.isAssignmentDeclaration = isAssignmentDeclaration; + /** Get the initializer, taking into account defaulted Javascript initializers */ + function getEffectiveInitializer(node) { + if (isInJSFile(node) && node.initializer && + ts.isBinaryExpression(node.initializer) && node.initializer.operatorToken.kind === 55 /* BarBarToken */ && + node.name && isEntityNameExpression(node.name) && isSameEntityName(node.name, node.initializer.left)) { + return node.initializer.right; + } + return node.initializer; + } + ts.getEffectiveInitializer = getEffectiveInitializer; + /** Get the declaration initializer when it is container-like (See getExpandoInitializer). */ + function getDeclaredExpandoInitializer(node) { + var init = getEffectiveInitializer(node); + return init && getExpandoInitializer(init, isPrototypeAccess(node.name)); + } + ts.getDeclaredExpandoInitializer = getDeclaredExpandoInitializer; + function hasExpandoValueProperty(node, isPrototypeAssignment) { + return ts.forEach(node.properties, function (p) { return ts.isPropertyAssignment(p) && ts.isIdentifier(p.name) && p.name.escapedText === "value" && p.initializer && getExpandoInitializer(p.initializer, isPrototypeAssignment); }); + } + /** + * Get the assignment 'initializer' -- the righthand side-- when the initializer is container-like (See getExpandoInitializer). + * We treat the right hand side of assignments with container-like initalizers as declarations. + */ + function getAssignedExpandoInitializer(node) { + if (node && node.parent && ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 59 /* EqualsToken */) { + var isPrototypeAssignment = isPrototypeAccess(node.parent.left); + return getExpandoInitializer(node.parent.right, isPrototypeAssignment) || + getDefaultedExpandoInitializer(node.parent.left, node.parent.right, isPrototypeAssignment); + } + if (node && ts.isCallExpression(node) && isBindableObjectDefinePropertyCall(node)) { + var result = hasExpandoValueProperty(node.arguments[2], node.arguments[1].text === "prototype"); + if (result) { + return result; + } + } + } + ts.getAssignedExpandoInitializer = getAssignedExpandoInitializer; + /** + * Recognized expando initializers are: + * 1. (function() {})() -- IIFEs + * 2. function() { } -- Function expressions + * 3. class { } -- Class expressions + * 4. {} -- Empty object literals + * 5. { ... } -- Non-empty object literals, when used to initialize a prototype, like `C.prototype = { m() { } }` + * + * This function returns the provided initializer, or undefined if it is not valid. + */ + function getExpandoInitializer(initializer, isPrototypeAssignment) { + if (ts.isCallExpression(initializer)) { + var e = skipParentheses(initializer.expression); + return e.kind === 196 /* FunctionExpression */ || e.kind === 197 /* ArrowFunction */ ? initializer : undefined; + } + if (initializer.kind === 196 /* FunctionExpression */ || + initializer.kind === 209 /* ClassExpression */ || + initializer.kind === 197 /* ArrowFunction */) { + return initializer; + } + if (ts.isObjectLiteralExpression(initializer) && (initializer.properties.length === 0 || isPrototypeAssignment)) { + return initializer; + } + } + ts.getExpandoInitializer = getExpandoInitializer; + /** + * A defaulted expando initializer matches the pattern + * `Lhs = Lhs || ExpandoInitializer` + * or `var Lhs = Lhs || ExpandoInitializer` + * + * The second Lhs is required to be the same as the first except that it may be prefixed with + * 'window.', 'global.' or 'self.' The second Lhs is otherwise ignored by the binder and checker. + */ + function getDefaultedExpandoInitializer(name, initializer, isPrototypeAssignment) { + var e = ts.isBinaryExpression(initializer) && initializer.operatorToken.kind === 55 /* BarBarToken */ && getExpandoInitializer(initializer.right, isPrototypeAssignment); + if (e && isSameEntityName(name, initializer.left)) { + return e; + } + } + function isDefaultedExpandoInitializer(node) { + var name = ts.isVariableDeclaration(node.parent) ? node.parent.name : + ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 59 /* EqualsToken */ ? node.parent.left : + undefined; + return name && getExpandoInitializer(node.right, isPrototypeAccess(name)) && isEntityNameExpression(name) && isSameEntityName(name, node.left); + } + ts.isDefaultedExpandoInitializer = isDefaultedExpandoInitializer; + /** Given an expando initializer, return its declaration name, or the left-hand side of the assignment if it's part of an assignment declaration. */ + function getNameOfExpando(node) { + if (ts.isBinaryExpression(node.parent)) { + var parent = (node.parent.operatorToken.kind === 55 /* BarBarToken */ && ts.isBinaryExpression(node.parent.parent)) ? node.parent.parent : node.parent; + if (parent.operatorToken.kind === 59 /* EqualsToken */ && ts.isIdentifier(parent.left)) { + return parent.left; + } + } + else if (ts.isVariableDeclaration(node.parent)) { + return node.parent.name; + } + } + ts.getNameOfExpando = getNameOfExpando; + /** + * Is the 'declared' name the same as the one in the initializer? + * @return true for identical entity names, as well as ones where the initializer is prefixed with + * 'window', 'self' or 'global'. For example: + * + * var my = my || {} + * var min = window.min || {} + * my.app = self.my.app || class { } + */ + function isSameEntityName(name, initializer) { + if (ts.isIdentifier(name) && ts.isIdentifier(initializer)) { + return name.escapedText === initializer.escapedText; + } + if (ts.isIdentifier(name) && ts.isPropertyAccessExpression(initializer)) { + return (initializer.expression.kind === 100 /* ThisKeyword */ || + ts.isIdentifier(initializer.expression) && + (initializer.expression.escapedText === "window" || + initializer.expression.escapedText === "self" || + initializer.expression.escapedText === "global")) && + isSameEntityName(name, initializer.name); + } + if (ts.isPropertyAccessExpression(name) && ts.isPropertyAccessExpression(initializer)) { + return name.name.escapedText === initializer.name.escapedText && isSameEntityName(name.expression, initializer.expression); + } + return false; + } + function getRightMostAssignedExpression(node) { + while (isAssignmentExpression(node, /*excludeCompoundAssignments*/ true)) { + node = node.right; + } + return node; + } + ts.getRightMostAssignedExpression = getRightMostAssignedExpression; + function isExportsIdentifier(node) { + return ts.isIdentifier(node) && node.escapedText === "exports"; + } + ts.isExportsIdentifier = isExportsIdentifier; + function isModuleExportsPropertyAccessExpression(node) { + return ts.isPropertyAccessExpression(node) && ts.isIdentifier(node.expression) && node.expression.escapedText === "module" && node.name.escapedText === "exports"; + } + ts.isModuleExportsPropertyAccessExpression = isModuleExportsPropertyAccessExpression; + /// Given a BinaryExpression, returns SpecialPropertyAssignmentKind for the various kinds of property + /// assignments we treat as special in the binder + function getAssignmentDeclarationKind(expr) { + var special = getAssignmentDeclarationKindWorker(expr); + return special === 5 /* Property */ || isInJSFile(expr) ? special : 0 /* None */; + } + ts.getAssignmentDeclarationKind = getAssignmentDeclarationKind; + function isBindableObjectDefinePropertyCall(expr) { + return ts.length(expr.arguments) === 3 && + ts.isPropertyAccessExpression(expr.expression) && + ts.isIdentifier(expr.expression.expression) && + ts.idText(expr.expression.expression) === "Object" && + ts.idText(expr.expression.name) === "defineProperty" && + isStringOrNumericLiteralLike(expr.arguments[1]) && + isEntityNameExpression(expr.arguments[0]); + } + ts.isBindableObjectDefinePropertyCall = isBindableObjectDefinePropertyCall; + function getAssignmentDeclarationKindWorker(expr) { + if (ts.isCallExpression(expr)) { + if (!isBindableObjectDefinePropertyCall(expr)) { + return 0 /* None */; + } + var entityName = expr.arguments[0]; + if (isExportsIdentifier(entityName) || isModuleExportsPropertyAccessExpression(entityName)) { + return 8 /* ObjectDefinePropertyExports */; + } + if (ts.isPropertyAccessExpression(entityName) && entityName.name.escapedText === "prototype" && isEntityNameExpression(entityName.expression)) { + return 9 /* ObjectDefinePrototypeProperty */; + } + return 7 /* ObjectDefinePropertyValue */; + } + if (expr.operatorToken.kind !== 59 /* EqualsToken */ || + !ts.isPropertyAccessExpression(expr.left)) { + return 0 /* None */; + } + var lhs = expr.left; + if (isEntityNameExpression(lhs.expression) && lhs.name.escapedText === "prototype" && ts.isObjectLiteralExpression(getInitializerOfBinaryExpression(expr))) { + // F.prototype = { ... } + return 6 /* Prototype */; + } + return getAssignmentDeclarationPropertyAccessKind(lhs); + } + function getAssignmentDeclarationPropertyAccessKind(lhs) { + if (lhs.expression.kind === 100 /* ThisKeyword */) { + return 4 /* ThisProperty */; + } + else if (isModuleExportsPropertyAccessExpression(lhs)) { + // module.exports = expr + return 2 /* ModuleExports */; + } + else if (isEntityNameExpression(lhs.expression)) { + if (isPrototypeAccess(lhs.expression)) { + // F.G....prototype.x = expr + return 3 /* PrototypeProperty */; + } + var nextToLast = lhs; + while (ts.isPropertyAccessExpression(nextToLast.expression)) { + nextToLast = nextToLast.expression; + } + ts.Debug.assert(ts.isIdentifier(nextToLast.expression)); + var id = nextToLast.expression; + if (id.escapedText === "exports" || + id.escapedText === "module" && nextToLast.name.escapedText === "exports") { + // exports.name = expr OR module.exports.name = expr + return 1 /* ExportsProperty */; + } + // F.G...x = expr + return 5 /* Property */; + } + return 0 /* None */; + } + ts.getAssignmentDeclarationPropertyAccessKind = getAssignmentDeclarationPropertyAccessKind; + function getInitializerOfBinaryExpression(expr) { + while (ts.isBinaryExpression(expr.right)) { + expr = expr.right; + } + return expr.right; + } + ts.getInitializerOfBinaryExpression = getInitializerOfBinaryExpression; + function isPrototypePropertyAssignment(node) { + return ts.isBinaryExpression(node) && getAssignmentDeclarationKind(node) === 3 /* PrototypeProperty */; + } + ts.isPrototypePropertyAssignment = isPrototypePropertyAssignment; + function isSpecialPropertyDeclaration(expr) { + return isInJSFile(expr) && + expr.parent && expr.parent.kind === 221 /* ExpressionStatement */ && + !!ts.getJSDocTypeTag(expr.parent); + } + ts.isSpecialPropertyDeclaration = isSpecialPropertyDeclaration; + function isFunctionSymbol(symbol) { + if (!symbol || !symbol.valueDeclaration) { + return false; + } + var decl = symbol.valueDeclaration; + return decl.kind === 239 /* FunctionDeclaration */ || ts.isVariableDeclaration(decl) && decl.initializer && ts.isFunctionLike(decl.initializer); + } + ts.isFunctionSymbol = isFunctionSymbol; + function importFromModuleSpecifier(node) { + return tryGetImportFromModuleSpecifier(node) || ts.Debug.fail(ts.Debug.showSyntaxKind(node.parent)); + } + ts.importFromModuleSpecifier = importFromModuleSpecifier; + function tryGetImportFromModuleSpecifier(node) { + switch (node.parent.kind) { + case 249 /* ImportDeclaration */: + case 255 /* ExportDeclaration */: + return node.parent; + case 259 /* ExternalModuleReference */: + return node.parent.parent; + case 191 /* CallExpression */: + return isImportCall(node.parent) || isRequireCall(node.parent, /*checkArg*/ false) ? node.parent : undefined; + case 182 /* LiteralType */: + ts.Debug.assert(ts.isStringLiteral(node)); + return ts.tryCast(node.parent.parent, ts.isImportTypeNode); + default: + return undefined; + } + } + ts.tryGetImportFromModuleSpecifier = tryGetImportFromModuleSpecifier; + function getExternalModuleName(node) { + switch (node.kind) { + case 249 /* ImportDeclaration */: + case 255 /* ExportDeclaration */: + return node.moduleSpecifier; + case 248 /* ImportEqualsDeclaration */: + return node.moduleReference.kind === 259 /* ExternalModuleReference */ ? node.moduleReference.expression : undefined; + case 183 /* ImportType */: + return isLiteralImportTypeNode(node) ? node.argument.literal : undefined; + default: + return ts.Debug.assertNever(node); + } + } + ts.getExternalModuleName = getExternalModuleName; + function getNamespaceDeclarationNode(node) { + switch (node.kind) { + case 249 /* ImportDeclaration */: + return node.importClause && ts.tryCast(node.importClause.namedBindings, ts.isNamespaceImport); + case 248 /* ImportEqualsDeclaration */: + return node; + case 255 /* ExportDeclaration */: + return undefined; + default: + return ts.Debug.assertNever(node); + } + } + ts.getNamespaceDeclarationNode = getNamespaceDeclarationNode; + function isDefaultImport(node) { + return node.kind === 249 /* ImportDeclaration */ && !!node.importClause && !!node.importClause.name; + } + ts.isDefaultImport = isDefaultImport; + function hasQuestionToken(node) { + if (node) { + switch (node.kind) { + case 151 /* Parameter */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 276 /* ShorthandPropertyAssignment */: + case 275 /* PropertyAssignment */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + return node.questionToken !== undefined; + } + } + return false; + } + ts.hasQuestionToken = hasQuestionToken; + function isJSDocConstructSignature(node) { + var param = ts.isJSDocFunctionType(node) ? ts.firstOrUndefined(node.parameters) : undefined; + var name = ts.tryCast(param && param.name, ts.isIdentifier); + return !!name && name.escapedText === "new"; + } + ts.isJSDocConstructSignature = isJSDocConstructSignature; + function isJSDocTypeAlias(node) { + return node.kind === 304 /* JSDocTypedefTag */ || node.kind === 297 /* JSDocCallbackTag */; + } + ts.isJSDocTypeAlias = isJSDocTypeAlias; + function isTypeAlias(node) { + return isJSDocTypeAlias(node) || ts.isTypeAliasDeclaration(node); + } + ts.isTypeAlias = isTypeAlias; + function getSourceOfAssignment(node) { + return ts.isExpressionStatement(node) && + node.expression && ts.isBinaryExpression(node.expression) && + node.expression.operatorToken.kind === 59 /* EqualsToken */ + ? node.expression.right + : undefined; + } + function getSourceOfDefaultedAssignment(node) { + return ts.isExpressionStatement(node) && + ts.isBinaryExpression(node.expression) && + getAssignmentDeclarationKind(node.expression) !== 0 /* None */ && + ts.isBinaryExpression(node.expression.right) && + node.expression.right.operatorToken.kind === 55 /* BarBarToken */ + ? node.expression.right.right + : undefined; + } + function getSingleInitializerOfVariableStatementOrPropertyDeclaration(node) { + switch (node.kind) { + case 219 /* VariableStatement */: + var v = getSingleVariableOfVariableStatement(node); + return v && v.initializer; + case 154 /* PropertyDeclaration */: + return node.initializer; + case 275 /* PropertyAssignment */: + return node.initializer; + } + } + function getSingleVariableOfVariableStatement(node) { + return ts.isVariableStatement(node) ? ts.firstOrUndefined(node.declarationList.declarations) : undefined; + } + function getNestedModuleDeclaration(node) { + return ts.isModuleDeclaration(node) && + node.body && + node.body.kind === 244 /* ModuleDeclaration */ + ? node.body + : undefined; + } + function getJSDocCommentsAndTags(hostNode) { + var result; + // Pull parameter comments from declaring function as well + if (isVariableLike(hostNode) && ts.hasInitializer(hostNode) && ts.hasJSDocNodes(hostNode.initializer)) { + result = ts.addRange(result, hostNode.initializer.jsDoc); + } + var node = hostNode; + while (node && node.parent) { + if (ts.hasJSDocNodes(node)) { + result = ts.addRange(result, node.jsDoc); + } + if (node.kind === 151 /* Parameter */) { + result = ts.addRange(result, ts.getJSDocParameterTags(node)); + break; + } + if (node.kind === 150 /* TypeParameter */) { + result = ts.addRange(result, ts.getJSDocTypeParameterTags(node)); + break; + } + node = getNextJSDocCommentLocation(node); + } + return result || ts.emptyArray; + } + ts.getJSDocCommentsAndTags = getJSDocCommentsAndTags; + function getNextJSDocCommentLocation(node) { + var parent = node.parent; + if (parent.kind === 275 /* PropertyAssignment */ || + parent.kind === 154 /* PropertyDeclaration */ || + parent.kind === 221 /* ExpressionStatement */ && node.kind === 189 /* PropertyAccessExpression */ || + getNestedModuleDeclaration(parent) || + ts.isBinaryExpression(node) && node.operatorToken.kind === 59 /* EqualsToken */) { + return parent; + } + // Try to recognize this pattern when node is initializer of variable declaration and JSDoc comments are on containing variable statement. + // /** + // * @param {number} name + // * @returns {number} + // */ + // var x = function(name) { return name.length; } + else if (parent.parent && + (getSingleVariableOfVariableStatement(parent.parent) === node || + ts.isBinaryExpression(parent) && parent.operatorToken.kind === 59 /* EqualsToken */)) { + return parent.parent; + } + else if (parent.parent && parent.parent.parent && + (getSingleVariableOfVariableStatement(parent.parent.parent) || + getSingleInitializerOfVariableStatementOrPropertyDeclaration(parent.parent.parent) === node || + getSourceOfDefaultedAssignment(parent.parent.parent))) { + return parent.parent.parent; + } + } + /** Does the opposite of `getJSDocParameterTags`: given a JSDoc parameter, finds the parameter corresponding to it. */ + function getParameterSymbolFromJSDoc(node) { + if (node.symbol) { + return node.symbol; + } + if (!ts.isIdentifier(node.name)) { + return undefined; + } + var name = node.name.escapedText; + var decl = getHostSignatureFromJSDoc(node); + if (!decl) { + return undefined; + } + var parameter = ts.find(decl.parameters, function (p) { return p.name.kind === 72 /* Identifier */ && p.name.escapedText === name; }); + return parameter && parameter.symbol; + } + ts.getParameterSymbolFromJSDoc = getParameterSymbolFromJSDoc; + function getHostSignatureFromJSDoc(node) { + return getHostSignatureFromJSDocHost(getJSDocHost(node)); + } + ts.getHostSignatureFromJSDoc = getHostSignatureFromJSDoc; + function getHostSignatureFromJSDocHost(host) { + var decl = getSourceOfDefaultedAssignment(host) || + getSourceOfAssignment(host) || + getSingleInitializerOfVariableStatementOrPropertyDeclaration(host) || + getSingleVariableOfVariableStatement(host) || + getNestedModuleDeclaration(host) || + host; + return decl && ts.isFunctionLike(decl) ? decl : undefined; + } + ts.getHostSignatureFromJSDocHost = getHostSignatureFromJSDocHost; + function getJSDocHost(node) { + return ts.Debug.assertDefined(findAncestor(node.parent, ts.isJSDoc)).parent; + } + ts.getJSDocHost = getJSDocHost; + function getTypeParameterFromJsDoc(node) { + var name = node.name.escapedText; + var typeParameters = node.parent.parent.parent.typeParameters; + return ts.find(typeParameters, function (p) { return p.name.escapedText === name; }); + } + ts.getTypeParameterFromJsDoc = getTypeParameterFromJsDoc; + function hasRestParameter(s) { + var last = ts.lastOrUndefined(s.parameters); + return !!last && isRestParameter(last); + } + ts.hasRestParameter = hasRestParameter; + function isRestParameter(node) { + var type = ts.isJSDocParameterTag(node) ? (node.typeExpression && node.typeExpression.type) : node.type; + return node.dotDotDotToken !== undefined || !!type && type.kind === 290 /* JSDocVariadicType */; + } + ts.isRestParameter = isRestParameter; + var AssignmentKind; + (function (AssignmentKind) { + AssignmentKind[AssignmentKind["None"] = 0] = "None"; + AssignmentKind[AssignmentKind["Definite"] = 1] = "Definite"; + AssignmentKind[AssignmentKind["Compound"] = 2] = "Compound"; + })(AssignmentKind = ts.AssignmentKind || (ts.AssignmentKind = {})); + function getAssignmentTargetKind(node) { + var parent = node.parent; + while (true) { + switch (parent.kind) { + case 204 /* BinaryExpression */: + var binaryOperator = parent.operatorToken.kind; + return isAssignmentOperator(binaryOperator) && parent.left === node ? + binaryOperator === 59 /* EqualsToken */ ? 1 /* Definite */ : 2 /* Compound */ : + 0 /* None */; + case 202 /* PrefixUnaryExpression */: + case 203 /* PostfixUnaryExpression */: + var unaryOperator = parent.operator; + return unaryOperator === 44 /* PlusPlusToken */ || unaryOperator === 45 /* MinusMinusToken */ ? 2 /* Compound */ : 0 /* None */; + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + return parent.initializer === node ? 1 /* Definite */ : 0 /* None */; + case 195 /* ParenthesizedExpression */: + case 187 /* ArrayLiteralExpression */: + case 208 /* SpreadElement */: + case 213 /* NonNullExpression */: + node = parent; + break; + case 276 /* ShorthandPropertyAssignment */: + if (parent.name !== node) { + return 0 /* None */; + } + node = parent.parent; + break; + case 275 /* PropertyAssignment */: + if (parent.name === node) { + return 0 /* None */; + } + node = parent.parent; + break; + default: + return 0 /* None */; + } + parent = node.parent; + } + } + ts.getAssignmentTargetKind = getAssignmentTargetKind; + // A node is an assignment target if it is on the left hand side of an '=' token, if it is parented by a property + // assignment in an object literal that is an assignment target, or if it is parented by an array literal that is + // an assignment target. Examples include 'a = xxx', '{ p: a } = xxx', '[{ a }] = xxx'. + // (Note that `p` is not a target in the above examples, only `a`.) + function isAssignmentTarget(node) { + return getAssignmentTargetKind(node) !== 0 /* None */; + } + ts.isAssignmentTarget = isAssignmentTarget; + /** + * Indicates whether a node could contain a `var` VariableDeclarationList that contributes to + * the same `var` declaration scope as the node's parent. + */ + function isNodeWithPossibleHoistedDeclaration(node) { + switch (node.kind) { + case 218 /* Block */: + case 219 /* VariableStatement */: + case 231 /* WithStatement */: + case 222 /* IfStatement */: + case 232 /* SwitchStatement */: + case 246 /* CaseBlock */: + case 271 /* CaseClause */: + case 272 /* DefaultClause */: + case 233 /* LabeledStatement */: + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + case 223 /* DoStatement */: + case 224 /* WhileStatement */: + case 235 /* TryStatement */: + case 274 /* CatchClause */: + return true; + } + return false; + } + ts.isNodeWithPossibleHoistedDeclaration = isNodeWithPossibleHoistedDeclaration; + function isValueSignatureDeclaration(node) { + return ts.isFunctionExpression(node) || ts.isArrowFunction(node) || ts.isMethodOrAccessor(node) || ts.isFunctionDeclaration(node) || ts.isConstructorDeclaration(node); + } + ts.isValueSignatureDeclaration = isValueSignatureDeclaration; + function walkUp(node, kind) { + while (node && node.kind === kind) { + node = node.parent; + } + return node; + } + function walkUpParenthesizedTypes(node) { + return walkUp(node, 177 /* ParenthesizedType */); + } + ts.walkUpParenthesizedTypes = walkUpParenthesizedTypes; + function walkUpParenthesizedExpressions(node) { + return walkUp(node, 195 /* ParenthesizedExpression */); + } + ts.walkUpParenthesizedExpressions = walkUpParenthesizedExpressions; + function skipParentheses(node) { + while (node.kind === 195 /* ParenthesizedExpression */) { + node = node.expression; + } + return node; + } + ts.skipParentheses = skipParentheses; + function skipParenthesesUp(node) { + while (node.kind === 195 /* ParenthesizedExpression */) { + node = node.parent; + } + return node; + } + // a node is delete target iff. it is PropertyAccessExpression/ElementAccessExpression with parentheses skipped + function isDeleteTarget(node) { + if (node.kind !== 189 /* PropertyAccessExpression */ && node.kind !== 190 /* ElementAccessExpression */) { + return false; + } + node = walkUpParenthesizedExpressions(node.parent); + return node && node.kind === 198 /* DeleteExpression */; + } + ts.isDeleteTarget = isDeleteTarget; + function isNodeDescendantOf(node, ancestor) { + while (node) { + if (node === ancestor) + return true; + node = node.parent; + } + return false; + } + ts.isNodeDescendantOf = isNodeDescendantOf; + // True if `name` is the name of a declaration node + function isDeclarationName(name) { + return !ts.isSourceFile(name) && !ts.isBindingPattern(name) && ts.isDeclaration(name.parent) && name.parent.name === name; + } + ts.isDeclarationName = isDeclarationName; + // See GH#16030 + function getDeclarationFromName(name) { + var parent = name.parent; + switch (name.kind) { + case 10 /* StringLiteral */: + case 8 /* NumericLiteral */: + if (ts.isComputedPropertyName(parent)) + return parent.parent; + // falls through + case 72 /* Identifier */: + if (ts.isDeclaration(parent)) { + return parent.name === name ? parent : undefined; + } + else if (ts.isQualifiedName(parent)) { + var tag = parent.parent; + return ts.isJSDocParameterTag(tag) && tag.name === parent ? tag : undefined; + } + else { + var binExp = parent.parent; + return ts.isBinaryExpression(binExp) && + getAssignmentDeclarationKind(binExp) !== 0 /* None */ && + (binExp.left.symbol || binExp.symbol) && + ts.getNameOfDeclaration(binExp) === name + ? binExp + : undefined; + } + default: + return undefined; + } + } + ts.getDeclarationFromName = getDeclarationFromName; + function isLiteralComputedPropertyDeclarationName(node) { + return (node.kind === 10 /* StringLiteral */ || node.kind === 8 /* NumericLiteral */) && + node.parent.kind === 149 /* ComputedPropertyName */ && + ts.isDeclaration(node.parent.parent); + } + ts.isLiteralComputedPropertyDeclarationName = isLiteralComputedPropertyDeclarationName; + // Return true if the given identifier is classified as an IdentifierName + function isIdentifierName(node) { + var parent = node.parent; + switch (parent.kind) { + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 278 /* EnumMember */: + case 275 /* PropertyAssignment */: + case 189 /* PropertyAccessExpression */: + // Name in member declaration or property name in property access + return parent.name === node; + case 148 /* QualifiedName */: + // Name on right hand side of dot in a type query or type reference + if (parent.right === node) { + while (parent.kind === 148 /* QualifiedName */) { + parent = parent.parent; + } + return parent.kind === 167 /* TypeQuery */ || parent.kind === 164 /* TypeReference */; + } + return false; + case 186 /* BindingElement */: + case 253 /* ImportSpecifier */: + // Property name in binding element or import specifier + return parent.propertyName === node; + case 257 /* ExportSpecifier */: + case 267 /* JsxAttribute */: + // Any name in an export specifier or JSX Attribute + return true; + } + return false; + } + ts.isIdentifierName = isIdentifierName; + // An alias symbol is created by one of the following declarations: + // import = ... + // import from ... + // import * as from ... + // import { x as } from ... + // export { x as } from ... + // export = + // export default + // module.exports = + function isAliasSymbolDeclaration(node) { + return node.kind === 248 /* ImportEqualsDeclaration */ || + node.kind === 247 /* NamespaceExportDeclaration */ || + node.kind === 250 /* ImportClause */ && !!node.name || + node.kind === 251 /* NamespaceImport */ || + node.kind === 253 /* ImportSpecifier */ || + node.kind === 257 /* ExportSpecifier */ || + node.kind === 254 /* ExportAssignment */ && exportAssignmentIsAlias(node) || + ts.isBinaryExpression(node) && getAssignmentDeclarationKind(node) === 2 /* ModuleExports */ && exportAssignmentIsAlias(node); + } + ts.isAliasSymbolDeclaration = isAliasSymbolDeclaration; + function exportAssignmentIsAlias(node) { + var e = ts.isExportAssignment(node) ? node.expression : node.right; + return isEntityNameExpression(e) || ts.isClassExpression(e); + } + ts.exportAssignmentIsAlias = exportAssignmentIsAlias; + function getEffectiveBaseTypeNode(node) { + if (isInJSFile(node)) { + // Prefer an @augments tag because it may have type parameters. + var tag = ts.getJSDocAugmentsTag(node); + if (tag) { + return tag.class; + } + } + return getClassExtendsHeritageElement(node); + } + ts.getEffectiveBaseTypeNode = getEffectiveBaseTypeNode; + function getClassExtendsHeritageElement(node) { + var heritageClause = getHeritageClause(node.heritageClauses, 86 /* ExtendsKeyword */); + return heritageClause && heritageClause.types.length > 0 ? heritageClause.types[0] : undefined; + } + ts.getClassExtendsHeritageElement = getClassExtendsHeritageElement; + function getClassImplementsHeritageClauseElements(node) { + var heritageClause = getHeritageClause(node.heritageClauses, 109 /* ImplementsKeyword */); + return heritageClause ? heritageClause.types : undefined; + } + ts.getClassImplementsHeritageClauseElements = getClassImplementsHeritageClauseElements; + /** Returns the node in an `extends` or `implements` clause of a class or interface. */ + function getAllSuperTypeNodes(node) { + return ts.isInterfaceDeclaration(node) ? getInterfaceBaseTypeNodes(node) || ts.emptyArray + : ts.isClassLike(node) ? ts.concatenate(ts.singleElementArray(getEffectiveBaseTypeNode(node)), getClassImplementsHeritageClauseElements(node)) || ts.emptyArray + : ts.emptyArray; + } + ts.getAllSuperTypeNodes = getAllSuperTypeNodes; + function getInterfaceBaseTypeNodes(node) { + var heritageClause = getHeritageClause(node.heritageClauses, 86 /* ExtendsKeyword */); + return heritageClause ? heritageClause.types : undefined; + } + ts.getInterfaceBaseTypeNodes = getInterfaceBaseTypeNodes; + function getHeritageClause(clauses, kind) { + if (clauses) { + for (var _i = 0, clauses_1 = clauses; _i < clauses_1.length; _i++) { + var clause = clauses_1[_i]; + if (clause.token === kind) { + return clause; + } + } + } + return undefined; + } + ts.getHeritageClause = getHeritageClause; + function tryResolveScriptReference(host, sourceFile, reference) { + if (!host.getCompilerOptions().noResolve) { + var referenceFileName = ts.isRootedDiskPath(reference.fileName) ? reference.fileName : ts.combinePaths(ts.getDirectoryPath(sourceFile.fileName), reference.fileName); + return host.getSourceFile(referenceFileName); + } + } + ts.tryResolveScriptReference = tryResolveScriptReference; + function getAncestor(node, kind) { + while (node) { + if (node.kind === kind) { + return node; + } + node = node.parent; + } + return undefined; + } + ts.getAncestor = getAncestor; + function isKeyword(token) { + return 73 /* FirstKeyword */ <= token && token <= 147 /* LastKeyword */; + } + ts.isKeyword = isKeyword; + function isContextualKeyword(token) { + return 118 /* FirstContextualKeyword */ <= token && token <= 147 /* LastContextualKeyword */; + } + ts.isContextualKeyword = isContextualKeyword; + function isNonContextualKeyword(token) { + return isKeyword(token) && !isContextualKeyword(token); + } + ts.isNonContextualKeyword = isNonContextualKeyword; + function isStringANonContextualKeyword(name) { + var token = ts.stringToToken(name); + return token !== undefined && isNonContextualKeyword(token); + } + ts.isStringANonContextualKeyword = isStringANonContextualKeyword; + function isIdentifierANonContextualKeyword(_a) { + var originalKeywordKind = _a.originalKeywordKind; + return !!originalKeywordKind && !isContextualKeyword(originalKeywordKind); + } + ts.isIdentifierANonContextualKeyword = isIdentifierANonContextualKeyword; + function isTrivia(token) { + return 2 /* FirstTriviaToken */ <= token && token <= 7 /* LastTriviaToken */; + } + ts.isTrivia = isTrivia; + var FunctionFlags; + (function (FunctionFlags) { + FunctionFlags[FunctionFlags["Normal"] = 0] = "Normal"; + FunctionFlags[FunctionFlags["Generator"] = 1] = "Generator"; + FunctionFlags[FunctionFlags["Async"] = 2] = "Async"; + FunctionFlags[FunctionFlags["Invalid"] = 4] = "Invalid"; + FunctionFlags[FunctionFlags["AsyncGenerator"] = 3] = "AsyncGenerator"; + })(FunctionFlags = ts.FunctionFlags || (ts.FunctionFlags = {})); + function getFunctionFlags(node) { + if (!node) { + return 4 /* Invalid */; + } + var flags = 0 /* Normal */; + switch (node.kind) { + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 156 /* MethodDeclaration */: + if (node.asteriskToken) { + flags |= 1 /* Generator */; + } + // falls through + case 197 /* ArrowFunction */: + if (hasModifier(node, 256 /* Async */)) { + flags |= 2 /* Async */; + } + break; + } + if (!node.body) { + flags |= 4 /* Invalid */; + } + return flags; + } + ts.getFunctionFlags = getFunctionFlags; + function isAsyncFunction(node) { + switch (node.kind) { + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 156 /* MethodDeclaration */: + return node.body !== undefined + && node.asteriskToken === undefined + && hasModifier(node, 256 /* Async */); + } + return false; + } + ts.isAsyncFunction = isAsyncFunction; + function isStringOrNumericLiteralLike(node) { + return ts.isStringLiteralLike(node) || ts.isNumericLiteral(node); + } + ts.isStringOrNumericLiteralLike = isStringOrNumericLiteralLike; + /** + * A declaration has a dynamic name if both of the following are true: + * 1. The declaration has a computed property name + * 2. The computed name is *not* expressed as Symbol., where name + * is a property of the Symbol constructor that denotes a built in + * Symbol. + */ + function hasDynamicName(declaration) { + var name = ts.getNameOfDeclaration(declaration); + return !!name && isDynamicName(name); + } + ts.hasDynamicName = hasDynamicName; + function isDynamicName(name) { + return name.kind === 149 /* ComputedPropertyName */ && + !isStringOrNumericLiteralLike(name.expression) && + !isWellKnownSymbolSyntactically(name.expression); + } + ts.isDynamicName = isDynamicName; + /** + * Checks if the expression is of the form: + * Symbol.name + * where Symbol is literally the word "Symbol", and name is any identifierName + */ + function isWellKnownSymbolSyntactically(node) { + return ts.isPropertyAccessExpression(node) && isESSymbolIdentifier(node.expression); + } + ts.isWellKnownSymbolSyntactically = isWellKnownSymbolSyntactically; + function getPropertyNameForPropertyNameNode(name) { + switch (name.kind) { + case 72 /* Identifier */: + return name.escapedText; + case 10 /* StringLiteral */: + case 8 /* NumericLiteral */: + return ts.escapeLeadingUnderscores(name.text); + case 149 /* ComputedPropertyName */: + var nameExpression = name.expression; + if (isWellKnownSymbolSyntactically(nameExpression)) { + return getPropertyNameForKnownSymbolName(ts.idText(nameExpression.name)); + } + else if (isStringOrNumericLiteralLike(nameExpression)) { + return ts.escapeLeadingUnderscores(nameExpression.text); + } + return undefined; + default: + return ts.Debug.assertNever(name); + } + } + ts.getPropertyNameForPropertyNameNode = getPropertyNameForPropertyNameNode; + function isPropertyNameLiteral(node) { + switch (node.kind) { + case 72 /* Identifier */: + case 10 /* StringLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: + case 8 /* NumericLiteral */: + return true; + default: + return false; + } + } + ts.isPropertyNameLiteral = isPropertyNameLiteral; + function getTextOfIdentifierOrLiteral(node) { + return node.kind === 72 /* Identifier */ ? ts.idText(node) : node.text; + } + ts.getTextOfIdentifierOrLiteral = getTextOfIdentifierOrLiteral; + function getEscapedTextOfIdentifierOrLiteral(node) { + return node.kind === 72 /* Identifier */ ? node.escapedText : ts.escapeLeadingUnderscores(node.text); + } + ts.getEscapedTextOfIdentifierOrLiteral = getEscapedTextOfIdentifierOrLiteral; + function getPropertyNameForKnownSymbolName(symbolName) { + return "__@" + symbolName; + } + ts.getPropertyNameForKnownSymbolName = getPropertyNameForKnownSymbolName; + function isKnownSymbol(symbol) { + return ts.startsWith(symbol.escapedName, "__@"); + } + ts.isKnownSymbol = isKnownSymbol; + /** + * Includes the word "Symbol" with unicode escapes + */ + function isESSymbolIdentifier(node) { + return node.kind === 72 /* Identifier */ && node.escapedText === "Symbol"; + } + ts.isESSymbolIdentifier = isESSymbolIdentifier; + function isPushOrUnshiftIdentifier(node) { + return node.escapedText === "push" || node.escapedText === "unshift"; + } + ts.isPushOrUnshiftIdentifier = isPushOrUnshiftIdentifier; + function isParameterDeclaration(node) { + var root = getRootDeclaration(node); + return root.kind === 151 /* Parameter */; + } + ts.isParameterDeclaration = isParameterDeclaration; + function getRootDeclaration(node) { + while (node.kind === 186 /* BindingElement */) { + node = node.parent.parent; + } + return node; + } + ts.getRootDeclaration = getRootDeclaration; + function nodeStartsNewLexicalEnvironment(node) { + var kind = node.kind; + return kind === 157 /* Constructor */ + || kind === 196 /* FunctionExpression */ + || kind === 239 /* FunctionDeclaration */ + || kind === 197 /* ArrowFunction */ + || kind === 156 /* MethodDeclaration */ + || kind === 158 /* GetAccessor */ + || kind === 159 /* SetAccessor */ + || kind === 244 /* ModuleDeclaration */ + || kind === 279 /* SourceFile */; + } + ts.nodeStartsNewLexicalEnvironment = nodeStartsNewLexicalEnvironment; + function nodeIsSynthesized(range) { + return ts.positionIsSynthesized(range.pos) + || ts.positionIsSynthesized(range.end); + } + ts.nodeIsSynthesized = nodeIsSynthesized; + function getOriginalSourceFile(sourceFile) { + return ts.getParseTreeNode(sourceFile, ts.isSourceFile) || sourceFile; + } + ts.getOriginalSourceFile = getOriginalSourceFile; + var Associativity; + (function (Associativity) { + Associativity[Associativity["Left"] = 0] = "Left"; + Associativity[Associativity["Right"] = 1] = "Right"; + })(Associativity = ts.Associativity || (ts.Associativity = {})); + function getExpressionAssociativity(expression) { + var operator = getOperator(expression); + var hasArguments = expression.kind === 192 /* NewExpression */ && expression.arguments !== undefined; + return getOperatorAssociativity(expression.kind, operator, hasArguments); + } + ts.getExpressionAssociativity = getExpressionAssociativity; + function getOperatorAssociativity(kind, operator, hasArguments) { + switch (kind) { + case 192 /* NewExpression */: + return hasArguments ? 0 /* Left */ : 1 /* Right */; + case 202 /* PrefixUnaryExpression */: + case 199 /* TypeOfExpression */: + case 200 /* VoidExpression */: + case 198 /* DeleteExpression */: + case 201 /* AwaitExpression */: + case 205 /* ConditionalExpression */: + case 207 /* YieldExpression */: + return 1 /* Right */; + case 204 /* BinaryExpression */: + switch (operator) { + case 41 /* AsteriskAsteriskToken */: + case 59 /* EqualsToken */: + case 60 /* PlusEqualsToken */: + case 61 /* MinusEqualsToken */: + case 63 /* AsteriskAsteriskEqualsToken */: + case 62 /* AsteriskEqualsToken */: + case 64 /* SlashEqualsToken */: + case 65 /* PercentEqualsToken */: + case 66 /* LessThanLessThanEqualsToken */: + case 67 /* GreaterThanGreaterThanEqualsToken */: + case 68 /* GreaterThanGreaterThanGreaterThanEqualsToken */: + case 69 /* AmpersandEqualsToken */: + case 71 /* CaretEqualsToken */: + case 70 /* BarEqualsToken */: + return 1 /* Right */; + } + } + return 0 /* Left */; + } + ts.getOperatorAssociativity = getOperatorAssociativity; + function getExpressionPrecedence(expression) { + var operator = getOperator(expression); + var hasArguments = expression.kind === 192 /* NewExpression */ && expression.arguments !== undefined; + return getOperatorPrecedence(expression.kind, operator, hasArguments); + } + ts.getExpressionPrecedence = getExpressionPrecedence; + function getOperator(expression) { + if (expression.kind === 204 /* BinaryExpression */) { + return expression.operatorToken.kind; + } + else if (expression.kind === 202 /* PrefixUnaryExpression */ || expression.kind === 203 /* PostfixUnaryExpression */) { + return expression.operator; + } + else { + return expression.kind; + } + } + ts.getOperator = getOperator; + function getOperatorPrecedence(nodeKind, operatorKind, hasArguments) { + switch (nodeKind) { + case 309 /* CommaListExpression */: + return 0; + case 208 /* SpreadElement */: + return 1; + case 207 /* YieldExpression */: + return 2; + case 205 /* ConditionalExpression */: + return 4; + case 204 /* BinaryExpression */: + switch (operatorKind) { + case 27 /* CommaToken */: + return 0; + case 59 /* EqualsToken */: + case 60 /* PlusEqualsToken */: + case 61 /* MinusEqualsToken */: + case 63 /* AsteriskAsteriskEqualsToken */: + case 62 /* AsteriskEqualsToken */: + case 64 /* SlashEqualsToken */: + case 65 /* PercentEqualsToken */: + case 66 /* LessThanLessThanEqualsToken */: + case 67 /* GreaterThanGreaterThanEqualsToken */: + case 68 /* GreaterThanGreaterThanGreaterThanEqualsToken */: + case 69 /* AmpersandEqualsToken */: + case 71 /* CaretEqualsToken */: + case 70 /* BarEqualsToken */: + return 3; + default: + return getBinaryOperatorPrecedence(operatorKind); + } + case 202 /* PrefixUnaryExpression */: + case 199 /* TypeOfExpression */: + case 200 /* VoidExpression */: + case 198 /* DeleteExpression */: + case 201 /* AwaitExpression */: + return 16; + case 203 /* PostfixUnaryExpression */: + return 17; + case 191 /* CallExpression */: + return 18; + case 192 /* NewExpression */: + return hasArguments ? 19 : 18; + case 193 /* TaggedTemplateExpression */: + case 189 /* PropertyAccessExpression */: + case 190 /* ElementAccessExpression */: + return 19; + case 100 /* ThisKeyword */: + case 98 /* SuperKeyword */: + case 72 /* Identifier */: + case 96 /* NullKeyword */: + case 102 /* TrueKeyword */: + case 87 /* FalseKeyword */: + case 8 /* NumericLiteral */: + case 9 /* BigIntLiteral */: + case 10 /* StringLiteral */: + case 187 /* ArrayLiteralExpression */: + case 188 /* ObjectLiteralExpression */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 209 /* ClassExpression */: + case 260 /* JsxElement */: + case 261 /* JsxSelfClosingElement */: + case 264 /* JsxFragment */: + case 13 /* RegularExpressionLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: + case 206 /* TemplateExpression */: + case 195 /* ParenthesizedExpression */: + case 210 /* OmittedExpression */: + return 20; + default: + return -1; + } + } + ts.getOperatorPrecedence = getOperatorPrecedence; + function getBinaryOperatorPrecedence(kind) { + switch (kind) { + case 55 /* BarBarToken */: + return 5; + case 54 /* AmpersandAmpersandToken */: + return 6; + case 50 /* BarToken */: + return 7; + case 51 /* CaretToken */: + return 8; + case 49 /* AmpersandToken */: + return 9; + case 33 /* EqualsEqualsToken */: + case 34 /* ExclamationEqualsToken */: + case 35 /* EqualsEqualsEqualsToken */: + case 36 /* ExclamationEqualsEqualsToken */: + return 10; + case 28 /* LessThanToken */: + case 30 /* GreaterThanToken */: + case 31 /* LessThanEqualsToken */: + case 32 /* GreaterThanEqualsToken */: + case 94 /* InstanceOfKeyword */: + case 93 /* InKeyword */: + case 119 /* AsKeyword */: + return 11; + case 46 /* LessThanLessThanToken */: + case 47 /* GreaterThanGreaterThanToken */: + case 48 /* GreaterThanGreaterThanGreaterThanToken */: + return 12; + case 38 /* PlusToken */: + case 39 /* MinusToken */: + return 13; + case 40 /* AsteriskToken */: + case 42 /* SlashToken */: + case 43 /* PercentToken */: + return 14; + case 41 /* AsteriskAsteriskToken */: + return 15; + } + // -1 is lower than all other precedences. Returning it will cause binary expression + // parsing to stop. + return -1; + } + ts.getBinaryOperatorPrecedence = getBinaryOperatorPrecedence; + function createDiagnosticCollection() { + var nonFileDiagnostics = []; // See GH#19873 + var filesWithDiagnostics = []; + var fileDiagnostics = ts.createMap(); + var hasReadNonFileDiagnostics = false; + return { + add: add, + lookup: lookup, + getGlobalDiagnostics: getGlobalDiagnostics, + getDiagnostics: getDiagnostics, + reattachFileDiagnostics: reattachFileDiagnostics + }; + function reattachFileDiagnostics(newFile) { + ts.forEach(fileDiagnostics.get(newFile.fileName), function (diagnostic) { return diagnostic.file = newFile; }); + } + function lookup(diagnostic) { + var diagnostics; + if (diagnostic.file) { + diagnostics = fileDiagnostics.get(diagnostic.file.fileName); + } + else { + diagnostics = nonFileDiagnostics; + } + if (!diagnostics) { + return undefined; + } + var result = ts.binarySearch(diagnostics, diagnostic, ts.identity, ts.compareDiagnosticsSkipRelatedInformation); + if (result >= 0) { + return diagnostics[result]; + } + return undefined; + } + function add(diagnostic) { + var diagnostics; + if (diagnostic.file) { + diagnostics = fileDiagnostics.get(diagnostic.file.fileName); + if (!diagnostics) { + diagnostics = []; // See GH#19873 + fileDiagnostics.set(diagnostic.file.fileName, diagnostics); + ts.insertSorted(filesWithDiagnostics, diagnostic.file.fileName, ts.compareStringsCaseSensitive); + } + } + else { + // If we've already read the non-file diagnostics, do not modify the existing array. + if (hasReadNonFileDiagnostics) { + hasReadNonFileDiagnostics = false; + nonFileDiagnostics = nonFileDiagnostics.slice(); + } + diagnostics = nonFileDiagnostics; + } + ts.insertSorted(diagnostics, diagnostic, ts.compareDiagnostics); + } + function getGlobalDiagnostics() { + hasReadNonFileDiagnostics = true; + return nonFileDiagnostics; + } + function getDiagnostics(fileName) { + if (fileName) { + return fileDiagnostics.get(fileName) || []; + } + var fileDiags = ts.flatMapToMutable(filesWithDiagnostics, function (f) { return fileDiagnostics.get(f); }); + if (!nonFileDiagnostics.length) { + return fileDiags; + } + fileDiags.unshift.apply(fileDiags, nonFileDiagnostics); + return fileDiags; + } + } + ts.createDiagnosticCollection = createDiagnosticCollection; + // This consists of the first 19 unprintable ASCII characters, canonical escapes, lineSeparator, + // paragraphSeparator, and nextLine. The latter three are just desirable to suppress new lines in + // the language service. These characters should be escaped when printing, and if any characters are added, + // the map below must be updated. Note that this regexp *does not* include the 'delete' character. + // There is no reason for this other than that JSON.stringify does not handle it either. + var doubleQuoteEscapedCharsRegExp = /[\\\"\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g; + var singleQuoteEscapedCharsRegExp = /[\\\'\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g; + var backtickQuoteEscapedCharsRegExp = /[\\\`\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g; + var escapedCharsMap = ts.createMapFromTemplate({ + "\t": "\\t", + "\v": "\\v", + "\f": "\\f", + "\b": "\\b", + "\r": "\\r", + "\n": "\\n", + "\\": "\\\\", + "\"": "\\\"", + "\'": "\\\'", + "\`": "\\\`", + "\u2028": "\\u2028", + "\u2029": "\\u2029", + "\u0085": "\\u0085" // nextLine + }); + /** + * Based heavily on the abstract 'Quote'/'QuoteJSONString' operation from ECMA-262 (24.3.2.2), + * but augmented for a few select characters (e.g. lineSeparator, paragraphSeparator, nextLine) + * Note that this doesn't actually wrap the input in double quotes. + */ + function escapeString(s, quoteChar) { + var escapedCharsRegExp = quoteChar === 96 /* backtick */ ? backtickQuoteEscapedCharsRegExp : + quoteChar === 39 /* singleQuote */ ? singleQuoteEscapedCharsRegExp : + doubleQuoteEscapedCharsRegExp; + return s.replace(escapedCharsRegExp, getReplacement); + } + ts.escapeString = escapeString; + function getReplacement(c, offset, input) { + if (c.charCodeAt(0) === 0 /* nullCharacter */) { + var lookAhead = input.charCodeAt(offset + c.length); + if (lookAhead >= 48 /* _0 */ && lookAhead <= 57 /* _9 */) { + // If the null character is followed by digits, print as a hex escape to prevent the result from parsing as an octal (which is forbidden in strict mode) + return "\\x00"; + } + // Otherwise, keep printing a literal \0 for the null character + return "\\0"; + } + return escapedCharsMap.get(c) || get16BitUnicodeEscapeSequence(c.charCodeAt(0)); + } + function isIntrinsicJsxName(name) { + var ch = name.charCodeAt(0); + return (ch >= 97 /* a */ && ch <= 122 /* z */) || ts.stringContains(name, "-"); + } + ts.isIntrinsicJsxName = isIntrinsicJsxName; + function get16BitUnicodeEscapeSequence(charCode) { + var hexCharCode = charCode.toString(16).toUpperCase(); + var paddedHexCode = ("0000" + hexCharCode).slice(-4); + return "\\u" + paddedHexCode; + } + var nonAsciiCharacters = /[^\u0000-\u007F]/g; + function escapeNonAsciiString(s, quoteChar) { + s = escapeString(s, quoteChar); + // Replace non-ASCII characters with '\uNNNN' escapes if any exist. + // Otherwise just return the original string. + return nonAsciiCharacters.test(s) ? + s.replace(nonAsciiCharacters, function (c) { return get16BitUnicodeEscapeSequence(c.charCodeAt(0)); }) : + s; + } + ts.escapeNonAsciiString = escapeNonAsciiString; + var indentStrings = ["", " "]; + function getIndentString(level) { + if (indentStrings[level] === undefined) { + indentStrings[level] = getIndentString(level - 1) + indentStrings[1]; + } + return indentStrings[level]; + } + ts.getIndentString = getIndentString; + function getIndentSize() { + return indentStrings[1].length; + } + ts.getIndentSize = getIndentSize; + function createTextWriter(newLine) { + var output; + var indent; + var lineStart; + var lineCount; + var linePos; + function updateLineCountAndPosFor(s) { + var lineStartsOfS = ts.computeLineStarts(s); + if (lineStartsOfS.length > 1) { + lineCount = lineCount + lineStartsOfS.length - 1; + linePos = output.length - s.length + ts.last(lineStartsOfS); + lineStart = (linePos - output.length) === 0; + } + else { + lineStart = false; + } + } + function write(s) { + if (s && s.length) { + if (lineStart) { + s = getIndentString(indent) + s; + lineStart = false; + } + output += s; + updateLineCountAndPosFor(s); + } + } + function reset() { + output = ""; + indent = 0; + lineStart = true; + lineCount = 0; + linePos = 0; + } + function rawWrite(s) { + if (s !== undefined) { + output += s; + updateLineCountAndPosFor(s); + } + } + function writeLiteral(s) { + if (s && s.length) { + write(s); + } + } + function writeLine() { + if (!lineStart) { + output += newLine; + lineCount++; + linePos = output.length; + lineStart = true; + } + } + reset(); + return { + write: write, + rawWrite: rawWrite, + writeLiteral: writeLiteral, + writeLine: writeLine, + increaseIndent: function () { indent++; }, + decreaseIndent: function () { indent--; }, + getIndent: function () { return indent; }, + getTextPos: function () { return output.length; }, + getLine: function () { return lineCount; }, + getColumn: function () { return lineStart ? indent * getIndentSize() : output.length - linePos; }, + getText: function () { return output; }, + isAtStartOfLine: function () { return lineStart; }, + clear: reset, + reportInaccessibleThisError: ts.noop, + reportPrivateInBaseOfClassExpression: ts.noop, + reportInaccessibleUniqueSymbolError: ts.noop, + trackSymbol: ts.noop, + writeKeyword: write, + writeOperator: write, + writeParameter: write, + writeProperty: write, + writePunctuation: write, + writeSpace: write, + writeStringLiteral: write, + writeSymbol: function (s, _) { return write(s); }, + writeTrailingSemicolon: write, + writeComment: write + }; + } + ts.createTextWriter = createTextWriter; + function getTrailingSemicolonOmittingWriter(writer) { + var pendingTrailingSemicolon = false; + function commitPendingTrailingSemicolon() { + if (pendingTrailingSemicolon) { + writer.writeTrailingSemicolon(";"); + pendingTrailingSemicolon = false; + } + } + return __assign({}, writer, { writeTrailingSemicolon: function () { + pendingTrailingSemicolon = true; + }, + writeLiteral: function (s) { + commitPendingTrailingSemicolon(); + writer.writeLiteral(s); + }, + writeStringLiteral: function (s) { + commitPendingTrailingSemicolon(); + writer.writeStringLiteral(s); + }, + writeSymbol: function (s, sym) { + commitPendingTrailingSemicolon(); + writer.writeSymbol(s, sym); + }, + writePunctuation: function (s) { + commitPendingTrailingSemicolon(); + writer.writePunctuation(s); + }, + writeKeyword: function (s) { + commitPendingTrailingSemicolon(); + writer.writeKeyword(s); + }, + writeOperator: function (s) { + commitPendingTrailingSemicolon(); + writer.writeOperator(s); + }, + writeParameter: function (s) { + commitPendingTrailingSemicolon(); + writer.writeParameter(s); + }, + writeSpace: function (s) { + commitPendingTrailingSemicolon(); + writer.writeSpace(s); + }, + writeProperty: function (s) { + commitPendingTrailingSemicolon(); + writer.writeProperty(s); + }, + writeComment: function (s) { + commitPendingTrailingSemicolon(); + writer.writeComment(s); + }, + writeLine: function () { + commitPendingTrailingSemicolon(); + writer.writeLine(); + }, + increaseIndent: function () { + commitPendingTrailingSemicolon(); + writer.increaseIndent(); + }, + decreaseIndent: function () { + commitPendingTrailingSemicolon(); + writer.decreaseIndent(); + } }); + } + ts.getTrailingSemicolonOmittingWriter = getTrailingSemicolonOmittingWriter; + function getResolvedExternalModuleName(host, file, referenceFile) { + return file.moduleName || getExternalModuleNameFromPath(host, file.fileName, referenceFile && referenceFile.fileName); + } + ts.getResolvedExternalModuleName = getResolvedExternalModuleName; + function getExternalModuleNameFromDeclaration(host, resolver, declaration) { + var file = resolver.getExternalModuleFileFromDeclaration(declaration); + if (!file || file.isDeclarationFile) { + return undefined; + } + return getResolvedExternalModuleName(host, file); + } + ts.getExternalModuleNameFromDeclaration = getExternalModuleNameFromDeclaration; + /** + * Resolves a local path to a path which is absolute to the base of the emit + */ + function getExternalModuleNameFromPath(host, fileName, referencePath) { + var getCanonicalFileName = function (f) { return host.getCanonicalFileName(f); }; + var dir = toPath(referencePath ? ts.getDirectoryPath(referencePath) : host.getCommonSourceDirectory(), host.getCurrentDirectory(), getCanonicalFileName); + var filePath = ts.getNormalizedAbsolutePath(fileName, host.getCurrentDirectory()); + var relativePath = ts.getRelativePathToDirectoryOrUrl(dir, filePath, dir, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); + var extensionless = ts.removeFileExtension(relativePath); + return referencePath ? ts.ensurePathIsNonModuleName(extensionless) : extensionless; + } + ts.getExternalModuleNameFromPath = getExternalModuleNameFromPath; + function getOwnEmitOutputFilePath(fileName, host, extension) { + var compilerOptions = host.getCompilerOptions(); + var emitOutputFilePathWithoutExtension; + if (compilerOptions.outDir) { + emitOutputFilePathWithoutExtension = ts.removeFileExtension(getSourceFilePathInNewDir(fileName, host, compilerOptions.outDir)); + } + else { + emitOutputFilePathWithoutExtension = ts.removeFileExtension(fileName); + } + return emitOutputFilePathWithoutExtension + extension; + } + ts.getOwnEmitOutputFilePath = getOwnEmitOutputFilePath; + function getDeclarationEmitOutputFilePath(fileName, host) { + return getDeclarationEmitOutputFilePathWorker(fileName, host.getCompilerOptions(), host.getCurrentDirectory(), host.getCommonSourceDirectory(), function (f) { return host.getCanonicalFileName(f); }); + } + ts.getDeclarationEmitOutputFilePath = getDeclarationEmitOutputFilePath; + function getDeclarationEmitOutputFilePathWorker(fileName, options, currentDirectory, commonSourceDirectory, getCanonicalFileName) { + var outputDir = options.declarationDir || options.outDir; // Prefer declaration folder if specified + var path = outputDir + ? getSourceFilePathInNewDirWorker(fileName, outputDir, currentDirectory, commonSourceDirectory, getCanonicalFileName) + : fileName; + return ts.removeFileExtension(path) + ".d.ts" /* Dts */; + } + ts.getDeclarationEmitOutputFilePathWorker = getDeclarationEmitOutputFilePathWorker; + /** + * Gets the source files that are expected to have an emit output. + * + * Originally part of `forEachExpectedEmitFile`, this functionality was extracted to support + * transformations. + * + * @param host An EmitHost. + * @param targetSourceFile An optional target source file to emit. + */ + function getSourceFilesToEmit(host, targetSourceFile) { + var options = host.getCompilerOptions(); + var isSourceFileFromExternalLibrary = function (file) { return host.isSourceFileFromExternalLibrary(file); }; + if (options.outFile || options.out) { + var moduleKind = ts.getEmitModuleKind(options); + var moduleEmitEnabled_1 = options.emitDeclarationOnly || moduleKind === ts.ModuleKind.AMD || moduleKind === ts.ModuleKind.System; + // Can emit only sources that are not declaration file and are either non module code or module with --module or --target es6 specified + return ts.filter(host.getSourceFiles(), function (sourceFile) { + return (moduleEmitEnabled_1 || !ts.isExternalModule(sourceFile)) && sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary); + }); + } + else { + var sourceFiles = targetSourceFile === undefined ? host.getSourceFiles() : [targetSourceFile]; + return ts.filter(sourceFiles, function (sourceFile) { return sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary); }); + } + } + ts.getSourceFilesToEmit = getSourceFilesToEmit; + /** Don't call this for `--outFile`, just for `--outDir` or plain emit. `--outFile` needs additional checks. */ + function sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary) { + return !(options.noEmitForJsFiles && isSourceFileJS(sourceFile)) && !sourceFile.isDeclarationFile && !isSourceFileFromExternalLibrary(sourceFile); + } + ts.sourceFileMayBeEmitted = sourceFileMayBeEmitted; + function getSourceFilePathInNewDir(fileName, host, newDirPath) { + return getSourceFilePathInNewDirWorker(fileName, newDirPath, host.getCurrentDirectory(), host.getCommonSourceDirectory(), function (f) { return host.getCanonicalFileName(f); }); + } + ts.getSourceFilePathInNewDir = getSourceFilePathInNewDir; + function getSourceFilePathInNewDirWorker(fileName, newDirPath, currentDirectory, commonSourceDirectory, getCanonicalFileName) { + var sourceFilePath = ts.getNormalizedAbsolutePath(fileName, currentDirectory); + var isSourceFileInCommonSourceDirectory = getCanonicalFileName(sourceFilePath).indexOf(getCanonicalFileName(commonSourceDirectory)) === 0; + sourceFilePath = isSourceFileInCommonSourceDirectory ? sourceFilePath.substring(commonSourceDirectory.length) : sourceFilePath; + return ts.combinePaths(newDirPath, sourceFilePath); + } + ts.getSourceFilePathInNewDirWorker = getSourceFilePathInNewDirWorker; + function writeFile(host, diagnostics, fileName, data, writeByteOrderMark, sourceFiles) { + host.writeFile(fileName, data, writeByteOrderMark, function (hostErrorMessage) { + diagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Could_not_write_file_0_Colon_1, fileName, hostErrorMessage)); + }, sourceFiles); + } + ts.writeFile = writeFile; + function getLineOfLocalPosition(currentSourceFile, pos) { + return ts.getLineAndCharacterOfPosition(currentSourceFile, pos).line; + } + ts.getLineOfLocalPosition = getLineOfLocalPosition; + function getLineOfLocalPositionFromLineMap(lineMap, pos) { + return ts.computeLineAndCharacterOfPosition(lineMap, pos).line; + } + ts.getLineOfLocalPositionFromLineMap = getLineOfLocalPositionFromLineMap; + function getFirstConstructorWithBody(node) { + return ts.find(node.members, function (member) { return ts.isConstructorDeclaration(member) && nodeIsPresent(member.body); }); + } + ts.getFirstConstructorWithBody = getFirstConstructorWithBody; + function getSetAccessorValueParameter(accessor) { + if (accessor && accessor.parameters.length > 0) { + var hasThis = accessor.parameters.length === 2 && parameterIsThisKeyword(accessor.parameters[0]); + return accessor.parameters[hasThis ? 1 : 0]; + } + } + /** Get the type annotation for the value parameter. */ + function getSetAccessorTypeAnnotationNode(accessor) { + var parameter = getSetAccessorValueParameter(accessor); + return parameter && parameter.type; + } + ts.getSetAccessorTypeAnnotationNode = getSetAccessorTypeAnnotationNode; + function getThisParameter(signature) { + // callback tags do not currently support this parameters + if (signature.parameters.length && !ts.isJSDocSignature(signature)) { + var thisParameter = signature.parameters[0]; + if (parameterIsThisKeyword(thisParameter)) { + return thisParameter; + } + } + } + ts.getThisParameter = getThisParameter; + function parameterIsThisKeyword(parameter) { + return isThisIdentifier(parameter.name); + } + ts.parameterIsThisKeyword = parameterIsThisKeyword; + function isThisIdentifier(node) { + return !!node && node.kind === 72 /* Identifier */ && identifierIsThisKeyword(node); + } + ts.isThisIdentifier = isThisIdentifier; + function identifierIsThisKeyword(id) { + return id.originalKeywordKind === 100 /* ThisKeyword */; + } + ts.identifierIsThisKeyword = identifierIsThisKeyword; + function getAllAccessorDeclarations(declarations, accessor) { + // TODO: GH#18217 + var firstAccessor; + var secondAccessor; + var getAccessor; + var setAccessor; + if (hasDynamicName(accessor)) { + firstAccessor = accessor; + if (accessor.kind === 158 /* GetAccessor */) { + getAccessor = accessor; + } + else if (accessor.kind === 159 /* SetAccessor */) { + setAccessor = accessor; + } + else { + ts.Debug.fail("Accessor has wrong kind"); + } + } + else { + ts.forEach(declarations, function (member) { + if (ts.isAccessor(member) + && hasModifier(member, 32 /* Static */) === hasModifier(accessor, 32 /* Static */)) { + var memberName = getPropertyNameForPropertyNameNode(member.name); + var accessorName = getPropertyNameForPropertyNameNode(accessor.name); + if (memberName === accessorName) { + if (!firstAccessor) { + firstAccessor = member; + } + else if (!secondAccessor) { + secondAccessor = member; + } + if (member.kind === 158 /* GetAccessor */ && !getAccessor) { + getAccessor = member; + } + if (member.kind === 159 /* SetAccessor */ && !setAccessor) { + setAccessor = member; + } + } + } + }); + } + return { + firstAccessor: firstAccessor, + secondAccessor: secondAccessor, + getAccessor: getAccessor, + setAccessor: setAccessor + }; + } + ts.getAllAccessorDeclarations = getAllAccessorDeclarations; + /** + * Gets the effective type annotation of a variable, parameter, or property. If the node was + * parsed in a JavaScript file, gets the type annotation from JSDoc. + */ + function getEffectiveTypeAnnotationNode(node) { + var type = node.type; + if (type || !isInJSFile(node)) + return type; + return ts.isJSDocPropertyLikeTag(node) ? node.typeExpression && node.typeExpression.type : ts.getJSDocType(node); + } + ts.getEffectiveTypeAnnotationNode = getEffectiveTypeAnnotationNode; + function getTypeAnnotationNode(node) { + return node.type; + } + ts.getTypeAnnotationNode = getTypeAnnotationNode; + /** + * Gets the effective return type annotation of a signature. If the node was parsed in a + * JavaScript file, gets the return type annotation from JSDoc. + */ + function getEffectiveReturnTypeNode(node) { + return ts.isJSDocSignature(node) ? + node.type && node.type.typeExpression && node.type.typeExpression.type : + node.type || (isInJSFile(node) ? ts.getJSDocReturnType(node) : undefined); + } + ts.getEffectiveReturnTypeNode = getEffectiveReturnTypeNode; + function getJSDocTypeParameterDeclarations(node) { + return ts.flatMap(ts.getJSDocTags(node), function (tag) { return isNonTypeAliasTemplate(tag) ? tag.typeParameters : undefined; }); + } + ts.getJSDocTypeParameterDeclarations = getJSDocTypeParameterDeclarations; + /** template tags are only available when a typedef isn't already using them */ + function isNonTypeAliasTemplate(tag) { + return ts.isJSDocTemplateTag(tag) && !(tag.parent.kind === 291 /* JSDocComment */ && tag.parent.tags.some(isJSDocTypeAlias)); + } + /** + * Gets the effective type annotation of the value parameter of a set accessor. If the node + * was parsed in a JavaScript file, gets the type annotation from JSDoc. + */ + function getEffectiveSetAccessorTypeAnnotationNode(node) { + var parameter = getSetAccessorValueParameter(node); + return parameter && getEffectiveTypeAnnotationNode(parameter); + } + ts.getEffectiveSetAccessorTypeAnnotationNode = getEffectiveSetAccessorTypeAnnotationNode; + function emitNewLineBeforeLeadingComments(lineMap, writer, node, leadingComments) { + emitNewLineBeforeLeadingCommentsOfPosition(lineMap, writer, node.pos, leadingComments); + } + ts.emitNewLineBeforeLeadingComments = emitNewLineBeforeLeadingComments; + function emitNewLineBeforeLeadingCommentsOfPosition(lineMap, writer, pos, leadingComments) { + // If the leading comments start on different line than the start of node, write new line + if (leadingComments && leadingComments.length && pos !== leadingComments[0].pos && + getLineOfLocalPositionFromLineMap(lineMap, pos) !== getLineOfLocalPositionFromLineMap(lineMap, leadingComments[0].pos)) { + writer.writeLine(); + } + } + ts.emitNewLineBeforeLeadingCommentsOfPosition = emitNewLineBeforeLeadingCommentsOfPosition; + function emitNewLineBeforeLeadingCommentOfPosition(lineMap, writer, pos, commentPos) { + // If the leading comments start on different line than the start of node, write new line + if (pos !== commentPos && + getLineOfLocalPositionFromLineMap(lineMap, pos) !== getLineOfLocalPositionFromLineMap(lineMap, commentPos)) { + writer.writeLine(); + } + } + ts.emitNewLineBeforeLeadingCommentOfPosition = emitNewLineBeforeLeadingCommentOfPosition; + function emitComments(text, lineMap, writer, comments, leadingSeparator, trailingSeparator, newLine, writeComment) { + if (comments && comments.length > 0) { + if (leadingSeparator) { + writer.writeSpace(" "); + } + var emitInterveningSeparator = false; + for (var _i = 0, comments_1 = comments; _i < comments_1.length; _i++) { + var comment = comments_1[_i]; + if (emitInterveningSeparator) { + writer.writeSpace(" "); + emitInterveningSeparator = false; + } + writeComment(text, lineMap, writer, comment.pos, comment.end, newLine); + if (comment.hasTrailingNewLine) { + writer.writeLine(); + } + else { + emitInterveningSeparator = true; + } + } + if (emitInterveningSeparator && trailingSeparator) { + writer.writeSpace(" "); + } + } + } + ts.emitComments = emitComments; + /** + * Detached comment is a comment at the top of file or function body that is separated from + * the next statement by space. + */ + function emitDetachedComments(text, lineMap, writer, writeComment, node, newLine, removeComments) { + var leadingComments; + var currentDetachedCommentInfo; + if (removeComments) { + // removeComments is true, only reserve pinned comment at the top of file + // For example: + // /*! Pinned Comment */ + // + // var x = 10; + if (node.pos === 0) { + leadingComments = ts.filter(ts.getLeadingCommentRanges(text, node.pos), isPinnedCommentLocal); + } + } + else { + // removeComments is false, just get detached as normal and bypass the process to filter comment + leadingComments = ts.getLeadingCommentRanges(text, node.pos); + } + if (leadingComments) { + var detachedComments = []; + var lastComment = void 0; + for (var _i = 0, leadingComments_1 = leadingComments; _i < leadingComments_1.length; _i++) { + var comment = leadingComments_1[_i]; + if (lastComment) { + var lastCommentLine = getLineOfLocalPositionFromLineMap(lineMap, lastComment.end); + var commentLine = getLineOfLocalPositionFromLineMap(lineMap, comment.pos); + if (commentLine >= lastCommentLine + 2) { + // There was a blank line between the last comment and this comment. This + // comment is not part of the copyright comments. Return what we have so + // far. + break; + } + } + detachedComments.push(comment); + lastComment = comment; + } + if (detachedComments.length) { + // All comments look like they could have been part of the copyright header. Make + // sure there is at least one blank line between it and the node. If not, it's not + // a copyright header. + var lastCommentLine = getLineOfLocalPositionFromLineMap(lineMap, ts.last(detachedComments).end); + var nodeLine = getLineOfLocalPositionFromLineMap(lineMap, ts.skipTrivia(text, node.pos)); + if (nodeLine >= lastCommentLine + 2) { + // Valid detachedComments + emitNewLineBeforeLeadingComments(lineMap, writer, node, leadingComments); + emitComments(text, lineMap, writer, detachedComments, /*leadingSeparator*/ false, /*trailingSeparator*/ true, newLine, writeComment); + currentDetachedCommentInfo = { nodePos: node.pos, detachedCommentEndPos: ts.last(detachedComments).end }; + } + } + } + return currentDetachedCommentInfo; + function isPinnedCommentLocal(comment) { + return isPinnedComment(text, comment.pos); + } + } + ts.emitDetachedComments = emitDetachedComments; + function writeCommentRange(text, lineMap, writer, commentPos, commentEnd, newLine) { + if (text.charCodeAt(commentPos + 1) === 42 /* asterisk */) { + var firstCommentLineAndCharacter = ts.computeLineAndCharacterOfPosition(lineMap, commentPos); + var lineCount = lineMap.length; + var firstCommentLineIndent = void 0; + for (var pos = commentPos, currentLine = firstCommentLineAndCharacter.line; pos < commentEnd; currentLine++) { + var nextLineStart = (currentLine + 1) === lineCount + ? text.length + 1 + : lineMap[currentLine + 1]; + if (pos !== commentPos) { + // If we are not emitting first line, we need to write the spaces to adjust the alignment + if (firstCommentLineIndent === undefined) { + firstCommentLineIndent = calculateIndent(text, lineMap[firstCommentLineAndCharacter.line], commentPos); + } + // These are number of spaces writer is going to write at current indent + var currentWriterIndentSpacing = writer.getIndent() * getIndentSize(); + // Number of spaces we want to be writing + // eg: Assume writer indent + // module m { + // /* starts at character 9 this is line 1 + // * starts at character pos 4 line --1 = 8 - 8 + 3 + // More left indented comment */ --2 = 8 - 8 + 2 + // class c { } + // } + // module m { + // /* this is line 1 -- Assume current writer indent 8 + // * line --3 = 8 - 4 + 5 + // More right indented comment */ --4 = 8 - 4 + 11 + // class c { } + // } + var spacesToEmit = currentWriterIndentSpacing - firstCommentLineIndent + calculateIndent(text, pos, nextLineStart); + if (spacesToEmit > 0) { + var numberOfSingleSpacesToEmit = spacesToEmit % getIndentSize(); + var indentSizeSpaceString = getIndentString((spacesToEmit - numberOfSingleSpacesToEmit) / getIndentSize()); + // Write indent size string ( in eg 1: = "", 2: "" , 3: string with 8 spaces 4: string with 12 spaces + writer.rawWrite(indentSizeSpaceString); + // Emit the single spaces (in eg: 1: 3 spaces, 2: 2 spaces, 3: 1 space, 4: 3 spaces) + while (numberOfSingleSpacesToEmit) { + writer.rawWrite(" "); + numberOfSingleSpacesToEmit--; + } + } + else { + // No spaces to emit write empty string + writer.rawWrite(""); + } + } + // Write the comment line text + writeTrimmedCurrentLine(text, commentEnd, writer, newLine, pos, nextLineStart); + pos = nextLineStart; + } + } + else { + // Single line comment of style //.... + writer.writeComment(text.substring(commentPos, commentEnd)); + } + } + ts.writeCommentRange = writeCommentRange; + function writeTrimmedCurrentLine(text, commentEnd, writer, newLine, pos, nextLineStart) { + var end = Math.min(commentEnd, nextLineStart - 1); + var currentLineText = text.substring(pos, end).replace(/^\s+|\s+$/g, ""); + if (currentLineText) { + // trimmed forward and ending spaces text + writer.writeComment(currentLineText); + if (end !== commentEnd) { + writer.writeLine(); + } + } + else { + // Empty string - make sure we write empty line + writer.rawWrite(newLine); + } + } + function calculateIndent(text, pos, end) { + var currentLineIndent = 0; + for (; pos < end && ts.isWhiteSpaceSingleLine(text.charCodeAt(pos)); pos++) { + if (text.charCodeAt(pos) === 9 /* tab */) { + // Tabs = TabSize = indent size and go to next tabStop + currentLineIndent += getIndentSize() - (currentLineIndent % getIndentSize()); + } + else { + // Single space + currentLineIndent++; + } + } + return currentLineIndent; + } + function hasModifiers(node) { + return getModifierFlags(node) !== 0 /* None */; + } + ts.hasModifiers = hasModifiers; + function hasModifier(node, flags) { + return !!getSelectedModifierFlags(node, flags); + } + ts.hasModifier = hasModifier; + function hasStaticModifier(node) { + return hasModifier(node, 32 /* Static */); + } + ts.hasStaticModifier = hasStaticModifier; + function hasReadonlyModifier(node) { + return hasModifier(node, 64 /* Readonly */); + } + ts.hasReadonlyModifier = hasReadonlyModifier; + function getSelectedModifierFlags(node, flags) { + return getModifierFlags(node) & flags; + } + ts.getSelectedModifierFlags = getSelectedModifierFlags; + function getModifierFlags(node) { + if (node.modifierFlagsCache & 536870912 /* HasComputedFlags */) { + return node.modifierFlagsCache & ~536870912 /* HasComputedFlags */; + } + var flags = getModifierFlagsNoCache(node); + node.modifierFlagsCache = flags | 536870912 /* HasComputedFlags */; + return flags; + } + ts.getModifierFlags = getModifierFlags; + function getModifierFlagsNoCache(node) { + var flags = 0 /* None */; + if (node.modifiers) { + for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) { + var modifier = _a[_i]; + flags |= modifierToFlag(modifier.kind); + } + } + if (node.flags & 4 /* NestedNamespace */ || (node.kind === 72 /* Identifier */ && node.isInJSDocNamespace)) { + flags |= 1 /* Export */; + } + return flags; + } + ts.getModifierFlagsNoCache = getModifierFlagsNoCache; + function modifierToFlag(token) { + switch (token) { + case 116 /* StaticKeyword */: return 32 /* Static */; + case 115 /* PublicKeyword */: return 4 /* Public */; + case 114 /* ProtectedKeyword */: return 16 /* Protected */; + case 113 /* PrivateKeyword */: return 8 /* Private */; + case 118 /* AbstractKeyword */: return 128 /* Abstract */; + case 85 /* ExportKeyword */: return 1 /* Export */; + case 125 /* DeclareKeyword */: return 2 /* Ambient */; + case 77 /* ConstKeyword */: return 2048 /* Const */; + case 80 /* DefaultKeyword */: return 512 /* Default */; + case 121 /* AsyncKeyword */: return 256 /* Async */; + case 133 /* ReadonlyKeyword */: return 64 /* Readonly */; + } + return 0 /* None */; + } + ts.modifierToFlag = modifierToFlag; + function isLogicalOperator(token) { + return token === 55 /* BarBarToken */ + || token === 54 /* AmpersandAmpersandToken */ + || token === 52 /* ExclamationToken */; + } + ts.isLogicalOperator = isLogicalOperator; + function isAssignmentOperator(token) { + return token >= 59 /* FirstAssignment */ && token <= 71 /* LastAssignment */; + } + ts.isAssignmentOperator = isAssignmentOperator; + /** Get `C` given `N` if `N` is in the position `class C extends N` where `N` is an ExpressionWithTypeArguments. */ + function tryGetClassExtendingExpressionWithTypeArguments(node) { + var cls = tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node); + return cls && !cls.isImplements ? cls.class : undefined; + } + ts.tryGetClassExtendingExpressionWithTypeArguments = tryGetClassExtendingExpressionWithTypeArguments; + function tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node) { + return ts.isExpressionWithTypeArguments(node) + && ts.isHeritageClause(node.parent) + && ts.isClassLike(node.parent.parent) + ? { class: node.parent.parent, isImplements: node.parent.token === 109 /* ImplementsKeyword */ } + : undefined; + } + ts.tryGetClassImplementingOrExtendingExpressionWithTypeArguments = tryGetClassImplementingOrExtendingExpressionWithTypeArguments; + function isAssignmentExpression(node, excludeCompoundAssignment) { + return ts.isBinaryExpression(node) + && (excludeCompoundAssignment + ? node.operatorToken.kind === 59 /* EqualsToken */ + : isAssignmentOperator(node.operatorToken.kind)) + && ts.isLeftHandSideExpression(node.left); + } + ts.isAssignmentExpression = isAssignmentExpression; + function isDestructuringAssignment(node) { + if (isAssignmentExpression(node, /*excludeCompoundAssignment*/ true)) { + var kind = node.left.kind; + return kind === 188 /* ObjectLiteralExpression */ + || kind === 187 /* ArrayLiteralExpression */; + } + return false; + } + ts.isDestructuringAssignment = isDestructuringAssignment; + function isExpressionWithTypeArgumentsInClassExtendsClause(node) { + return tryGetClassExtendingExpressionWithTypeArguments(node) !== undefined; + } + ts.isExpressionWithTypeArgumentsInClassExtendsClause = isExpressionWithTypeArgumentsInClassExtendsClause; + function isEntityNameExpression(node) { + return node.kind === 72 /* Identifier */ || isPropertyAccessEntityNameExpression(node); + } + ts.isEntityNameExpression = isEntityNameExpression; + function isPropertyAccessEntityNameExpression(node) { + return ts.isPropertyAccessExpression(node) && isEntityNameExpression(node.expression); + } + ts.isPropertyAccessEntityNameExpression = isPropertyAccessEntityNameExpression; + function isPrototypeAccess(node) { + return ts.isPropertyAccessExpression(node) && node.name.escapedText === "prototype"; + } + ts.isPrototypeAccess = isPrototypeAccess; + function isRightSideOfQualifiedNameOrPropertyAccess(node) { + return (node.parent.kind === 148 /* QualifiedName */ && node.parent.right === node) || + (node.parent.kind === 189 /* PropertyAccessExpression */ && node.parent.name === node); + } + ts.isRightSideOfQualifiedNameOrPropertyAccess = isRightSideOfQualifiedNameOrPropertyAccess; + function isEmptyObjectLiteral(expression) { + return expression.kind === 188 /* ObjectLiteralExpression */ && + expression.properties.length === 0; + } + ts.isEmptyObjectLiteral = isEmptyObjectLiteral; + function isEmptyArrayLiteral(expression) { + return expression.kind === 187 /* ArrayLiteralExpression */ && + expression.elements.length === 0; + } + ts.isEmptyArrayLiteral = isEmptyArrayLiteral; + function getLocalSymbolForExportDefault(symbol) { + return isExportDefaultSymbol(symbol) ? symbol.declarations[0].localSymbol : undefined; + } + ts.getLocalSymbolForExportDefault = getLocalSymbolForExportDefault; + function isExportDefaultSymbol(symbol) { + return symbol && ts.length(symbol.declarations) > 0 && hasModifier(symbol.declarations[0], 512 /* Default */); + } + /** Return ".ts", ".d.ts", or ".tsx", if that is the extension. */ + function tryExtractTSExtension(fileName) { + return ts.find(ts.supportedTSExtensionsForExtractExtension, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + } + ts.tryExtractTSExtension = tryExtractTSExtension; + /** + * Replace each instance of non-ascii characters by one, two, three, or four escape sequences + * representing the UTF-8 encoding of the character, and return the expanded char code list. + */ + function getExpandedCharCodes(input) { + var output = []; + var length = input.length; + for (var i = 0; i < length; i++) { + var charCode = input.charCodeAt(i); + // handle utf8 + if (charCode < 0x80) { + output.push(charCode); + } + else if (charCode < 0x800) { + output.push((charCode >> 6) | 192); + output.push((charCode & 63) | 128); + } + else if (charCode < 0x10000) { + output.push((charCode >> 12) | 224); + output.push(((charCode >> 6) & 63) | 128); + output.push((charCode & 63) | 128); + } + else if (charCode < 0x20000) { + output.push((charCode >> 18) | 240); + output.push(((charCode >> 12) & 63) | 128); + output.push(((charCode >> 6) & 63) | 128); + output.push((charCode & 63) | 128); + } + else { + ts.Debug.assert(false, "Unexpected code point"); + } + } + return output; + } + var base64Digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; + /** + * Converts a string to a base-64 encoded ASCII string. + */ + function convertToBase64(input) { + var result = ""; + var charCodes = getExpandedCharCodes(input); + var i = 0; + var length = charCodes.length; + var byte1, byte2, byte3, byte4; + while (i < length) { + // Convert every 6-bits in the input 3 character points + // into a base64 digit + byte1 = charCodes[i] >> 2; + byte2 = (charCodes[i] & 3) << 4 | charCodes[i + 1] >> 4; + byte3 = (charCodes[i + 1] & 15) << 2 | charCodes[i + 2] >> 6; + byte4 = charCodes[i + 2] & 63; + // We are out of characters in the input, set the extra + // digits to 64 (padding character). + if (i + 1 >= length) { + byte3 = byte4 = 64; + } + else if (i + 2 >= length) { + byte4 = 64; + } + // Write to the output + result += base64Digits.charAt(byte1) + base64Digits.charAt(byte2) + base64Digits.charAt(byte3) + base64Digits.charAt(byte4); + i += 3; + } + return result; + } + ts.convertToBase64 = convertToBase64; + function getStringFromExpandedCharCodes(codes) { + var output = ""; + var i = 0; + var length = codes.length; + while (i < length) { + var charCode = codes[i]; + if (charCode < 0x80) { + output += String.fromCharCode(charCode); + i++; + } + else if ((charCode & 192) === 192) { + var value = charCode & 63; + i++; + var nextCode = codes[i]; + while ((nextCode & 192) === 128) { + value = (value << 6) | (nextCode & 63); + i++; + nextCode = codes[i]; + } + // `value` may be greater than 10FFFF (the maximum unicode codepoint) - JS will just make this into an invalid character for us + output += String.fromCharCode(value); + } + else { + // We don't want to kill the process when decoding fails (due to a following char byte not + // following a leading char), so we just print the (bad) value + output += String.fromCharCode(charCode); + i++; + } + } + return output; + } + function base64encode(host, input) { + if (host && host.base64encode) { + return host.base64encode(input); + } + return convertToBase64(input); + } + ts.base64encode = base64encode; + function base64decode(host, input) { + if (host && host.base64decode) { + return host.base64decode(input); + } + var length = input.length; + var expandedCharCodes = []; + var i = 0; + while (i < length) { + // Stop decoding once padding characters are present + if (input.charCodeAt(i) === base64Digits.charCodeAt(64)) { + break; + } + // convert 4 input digits into three characters, ignoring padding characters at the end + var ch1 = base64Digits.indexOf(input[i]); + var ch2 = base64Digits.indexOf(input[i + 1]); + var ch3 = base64Digits.indexOf(input[i + 2]); + var ch4 = base64Digits.indexOf(input[i + 3]); + var code1 = ((ch1 & 63) << 2) | ((ch2 >> 4) & 3); + var code2 = ((ch2 & 15) << 4) | ((ch3 >> 2) & 15); + var code3 = ((ch3 & 3) << 6) | (ch4 & 63); + if (code2 === 0 && ch3 !== 0) { // code2 decoded to zero, but ch3 was padding - elide code2 and code3 + expandedCharCodes.push(code1); + } + else if (code3 === 0 && ch4 !== 0) { // code3 decoded to zero, but ch4 was padding, elide code3 + expandedCharCodes.push(code1, code2); + } + else { + expandedCharCodes.push(code1, code2, code3); + } + i += 4; + } + return getStringFromExpandedCharCodes(expandedCharCodes); + } + ts.base64decode = base64decode; + function readJson(path, host) { + try { + var jsonText = host.readFile(path); + if (!jsonText) + return {}; + var result = ts.parseConfigFileTextToJson(path, jsonText); + if (result.error) { + return {}; + } + return result.config; + } + catch (e) { + // gracefully handle if readFile fails or returns not JSON + return {}; + } + } + ts.readJson = readJson; + function directoryProbablyExists(directoryName, host) { + // if host does not support 'directoryExists' assume that directory will exist + return !host.directoryExists || host.directoryExists(directoryName); + } + ts.directoryProbablyExists = directoryProbablyExists; + var carriageReturnLineFeed = "\r\n"; + var lineFeed = "\n"; + function getNewLineCharacter(options, getNewLine) { + switch (options.newLine) { + case 0 /* CarriageReturnLineFeed */: + return carriageReturnLineFeed; + case 1 /* LineFeed */: + return lineFeed; + } + return getNewLine ? getNewLine() : ts.sys ? ts.sys.newLine : carriageReturnLineFeed; + } + ts.getNewLineCharacter = getNewLineCharacter; + /** + * Formats an enum value as a string for debugging and debug assertions. + */ + function formatEnum(value, enumObject, isFlags) { + if (value === void 0) { value = 0; } + var members = getEnumMembers(enumObject); + if (value === 0) { + return members.length > 0 && members[0][0] === 0 ? members[0][1] : "0"; + } + if (isFlags) { + var result = ""; + var remainingFlags = value; + for (var i = members.length - 1; i >= 0 && remainingFlags !== 0; i--) { + var _a = members[i], enumValue = _a[0], enumName = _a[1]; + if (enumValue !== 0 && (remainingFlags & enumValue) === enumValue) { + remainingFlags &= ~enumValue; + result = "" + enumName + (result ? ", " : "") + result; + } + } + if (remainingFlags === 0) { + return result; + } + } + else { + for (var _i = 0, members_1 = members; _i < members_1.length; _i++) { + var _b = members_1[_i], enumValue = _b[0], enumName = _b[1]; + if (enumValue === value) { + return enumName; + } + } + } + return value.toString(); + } + function getEnumMembers(enumObject) { + var result = []; + for (var name in enumObject) { + var value = enumObject[name]; + if (typeof value === "number") { + result.push([value, name]); + } + } + return ts.stableSort(result, function (x, y) { return ts.compareValues(x[0], y[0]); }); + } + function formatSyntaxKind(kind) { + return formatEnum(kind, ts.SyntaxKind, /*isFlags*/ false); + } + ts.formatSyntaxKind = formatSyntaxKind; + function formatModifierFlags(flags) { + return formatEnum(flags, ts.ModifierFlags, /*isFlags*/ true); + } + ts.formatModifierFlags = formatModifierFlags; + function formatTransformFlags(flags) { + return formatEnum(flags, ts.TransformFlags, /*isFlags*/ true); + } + ts.formatTransformFlags = formatTransformFlags; + function formatEmitFlags(flags) { + return formatEnum(flags, ts.EmitFlags, /*isFlags*/ true); + } + ts.formatEmitFlags = formatEmitFlags; + function formatSymbolFlags(flags) { + return formatEnum(flags, ts.SymbolFlags, /*isFlags*/ true); + } + ts.formatSymbolFlags = formatSymbolFlags; + function formatTypeFlags(flags) { + return formatEnum(flags, ts.TypeFlags, /*isFlags*/ true); + } + ts.formatTypeFlags = formatTypeFlags; + function formatObjectFlags(flags) { + return formatEnum(flags, ts.ObjectFlags, /*isFlags*/ true); + } + ts.formatObjectFlags = formatObjectFlags; + /** + * Creates a new TextRange from the provided pos and end. + * + * @param pos The start position. + * @param end The end position. + */ + function createRange(pos, end) { + if (end === void 0) { end = pos; } + ts.Debug.assert(end >= pos || end === -1); + return { pos: pos, end: end }; + } + ts.createRange = createRange; + /** + * Creates a new TextRange from a provided range with a new end position. + * + * @param range A TextRange. + * @param end The new end position. + */ + function moveRangeEnd(range, end) { + return createRange(range.pos, end); + } + ts.moveRangeEnd = moveRangeEnd; + /** + * Creates a new TextRange from a provided range with a new start position. + * + * @param range A TextRange. + * @param pos The new Start position. + */ + function moveRangePos(range, pos) { + return createRange(pos, range.end); + } + ts.moveRangePos = moveRangePos; + /** + * Moves the start position of a range past any decorators. + */ + function moveRangePastDecorators(node) { + return node.decorators && node.decorators.length > 0 + ? moveRangePos(node, node.decorators.end) + : node; + } + ts.moveRangePastDecorators = moveRangePastDecorators; + /** + * Moves the start position of a range past any decorators or modifiers. + */ + function moveRangePastModifiers(node) { + return node.modifiers && node.modifiers.length > 0 + ? moveRangePos(node, node.modifiers.end) + : moveRangePastDecorators(node); + } + ts.moveRangePastModifiers = moveRangePastModifiers; + /** + * Determines whether a TextRange has the same start and end positions. + * + * @param range A TextRange. + */ + function isCollapsedRange(range) { + return range.pos === range.end; + } + ts.isCollapsedRange = isCollapsedRange; + /** + * Creates a new TextRange for a token at the provides start position. + * + * @param pos The start position. + * @param token The token. + */ + function createTokenRange(pos, token) { + return createRange(pos, pos + ts.tokenToString(token).length); + } + ts.createTokenRange = createTokenRange; + function rangeIsOnSingleLine(range, sourceFile) { + return rangeStartIsOnSameLineAsRangeEnd(range, range, sourceFile); + } + ts.rangeIsOnSingleLine = rangeIsOnSingleLine; + function rangeStartPositionsAreOnSameLine(range1, range2, sourceFile) { + return positionsAreOnSameLine(getStartPositionOfRange(range1, sourceFile), getStartPositionOfRange(range2, sourceFile), sourceFile); + } + ts.rangeStartPositionsAreOnSameLine = rangeStartPositionsAreOnSameLine; + function rangeEndPositionsAreOnSameLine(range1, range2, sourceFile) { + return positionsAreOnSameLine(range1.end, range2.end, sourceFile); + } + ts.rangeEndPositionsAreOnSameLine = rangeEndPositionsAreOnSameLine; + function rangeStartIsOnSameLineAsRangeEnd(range1, range2, sourceFile) { + return positionsAreOnSameLine(getStartPositionOfRange(range1, sourceFile), range2.end, sourceFile); + } + ts.rangeStartIsOnSameLineAsRangeEnd = rangeStartIsOnSameLineAsRangeEnd; + function rangeEndIsOnSameLineAsRangeStart(range1, range2, sourceFile) { + return positionsAreOnSameLine(range1.end, getStartPositionOfRange(range2, sourceFile), sourceFile); + } + ts.rangeEndIsOnSameLineAsRangeStart = rangeEndIsOnSameLineAsRangeStart; + function positionsAreOnSameLine(pos1, pos2, sourceFile) { + return pos1 === pos2 || + getLineOfLocalPosition(sourceFile, pos1) === getLineOfLocalPosition(sourceFile, pos2); + } + ts.positionsAreOnSameLine = positionsAreOnSameLine; + function getStartPositionOfRange(range, sourceFile) { + return ts.positionIsSynthesized(range.pos) ? -1 : ts.skipTrivia(sourceFile.text, range.pos); + } + ts.getStartPositionOfRange = getStartPositionOfRange; + /** + * Determines whether a name was originally the declaration name of an enum or namespace + * declaration. + */ + function isDeclarationNameOfEnumOrNamespace(node) { + var parseNode = ts.getParseTreeNode(node); + if (parseNode) { + switch (parseNode.parent.kind) { + case 243 /* EnumDeclaration */: + case 244 /* ModuleDeclaration */: + return parseNode === parseNode.parent.name; + } + } + return false; + } + ts.isDeclarationNameOfEnumOrNamespace = isDeclarationNameOfEnumOrNamespace; + function getInitializedVariables(node) { + return ts.filter(node.declarations, isInitializedVariable); + } + ts.getInitializedVariables = getInitializedVariables; + function isInitializedVariable(node) { + return node.initializer !== undefined; + } + function isWatchSet(options) { + // Firefox has Object.prototype.watch + return options.watch && options.hasOwnProperty("watch"); + } + ts.isWatchSet = isWatchSet; + function closeFileWatcher(watcher) { + watcher.close(); + } + ts.closeFileWatcher = closeFileWatcher; + function getCheckFlags(symbol) { + return symbol.flags & 33554432 /* Transient */ ? symbol.checkFlags : 0; + } + ts.getCheckFlags = getCheckFlags; + function getDeclarationModifierFlagsFromSymbol(s) { + if (s.valueDeclaration) { + var flags = ts.getCombinedModifierFlags(s.valueDeclaration); + return s.parent && s.parent.flags & 32 /* Class */ ? flags : flags & ~28 /* AccessibilityModifier */; + } + if (getCheckFlags(s) & 6 /* Synthetic */) { + var checkFlags = s.checkFlags; + var accessModifier = checkFlags & 256 /* ContainsPrivate */ ? 8 /* Private */ : + checkFlags & 64 /* ContainsPublic */ ? 4 /* Public */ : + 16 /* Protected */; + var staticModifier = checkFlags & 512 /* ContainsStatic */ ? 32 /* Static */ : 0; + return accessModifier | staticModifier; + } + if (s.flags & 4194304 /* Prototype */) { + return 4 /* Public */ | 32 /* Static */; + } + return 0; + } + ts.getDeclarationModifierFlagsFromSymbol = getDeclarationModifierFlagsFromSymbol; + function skipAlias(symbol, checker) { + return symbol.flags & 2097152 /* Alias */ ? checker.getAliasedSymbol(symbol) : symbol; + } + ts.skipAlias = skipAlias; + /** See comment on `declareModuleMember` in `binder.ts`. */ + function getCombinedLocalAndExportSymbolFlags(symbol) { + return symbol.exportSymbol ? symbol.exportSymbol.flags | symbol.flags : symbol.flags; + } + ts.getCombinedLocalAndExportSymbolFlags = getCombinedLocalAndExportSymbolFlags; + function isWriteOnlyAccess(node) { + return accessKind(node) === 1 /* Write */; + } + ts.isWriteOnlyAccess = isWriteOnlyAccess; + function isWriteAccess(node) { + return accessKind(node) !== 0 /* Read */; + } + ts.isWriteAccess = isWriteAccess; + var AccessKind; + (function (AccessKind) { + /** Only reads from a variable. */ + AccessKind[AccessKind["Read"] = 0] = "Read"; + /** Only writes to a variable without using the result. E.g.: `x++;`. */ + AccessKind[AccessKind["Write"] = 1] = "Write"; + /** Writes to a variable and uses the result as an expression. E.g.: `f(x++);`. */ + AccessKind[AccessKind["ReadWrite"] = 2] = "ReadWrite"; + })(AccessKind || (AccessKind = {})); + function accessKind(node) { + var parent = node.parent; + if (!parent) + return 0 /* Read */; + switch (parent.kind) { + case 195 /* ParenthesizedExpression */: + return accessKind(parent); + case 203 /* PostfixUnaryExpression */: + case 202 /* PrefixUnaryExpression */: + var operator = parent.operator; + return operator === 44 /* PlusPlusToken */ || operator === 45 /* MinusMinusToken */ ? writeOrReadWrite() : 0 /* Read */; + case 204 /* BinaryExpression */: + var _a = parent, left = _a.left, operatorToken = _a.operatorToken; + return left === node && isAssignmentOperator(operatorToken.kind) ? + operatorToken.kind === 59 /* EqualsToken */ ? 1 /* Write */ : writeOrReadWrite() + : 0 /* Read */; + case 189 /* PropertyAccessExpression */: + return parent.name !== node ? 0 /* Read */ : accessKind(parent); + case 275 /* PropertyAssignment */: { + var parentAccess = accessKind(parent.parent); + // In `({ x: varname }) = { x: 1 }`, the left `x` is a read, the right `x` is a write. + return node === parent.name ? reverseAccessKind(parentAccess) : parentAccess; + } + case 276 /* ShorthandPropertyAssignment */: + // Assume it's the local variable being accessed, since we don't check public properties for --noUnusedLocals. + return node === parent.objectAssignmentInitializer ? 0 /* Read */ : accessKind(parent.parent); + case 187 /* ArrayLiteralExpression */: + return accessKind(parent); + default: + return 0 /* Read */; + } + function writeOrReadWrite() { + // If grandparent is not an ExpressionStatement, this is used as an expression in addition to having a side effect. + return parent.parent && skipParenthesesUp(parent.parent).kind === 221 /* ExpressionStatement */ ? 1 /* Write */ : 2 /* ReadWrite */; + } + } + function reverseAccessKind(a) { + switch (a) { + case 0 /* Read */: + return 1 /* Write */; + case 1 /* Write */: + return 0 /* Read */; + case 2 /* ReadWrite */: + return 2 /* ReadWrite */; + default: + return ts.Debug.assertNever(a); + } + } + function compareDataObjects(dst, src) { + if (!dst || !src || Object.keys(dst).length !== Object.keys(src).length) { + return false; + } + for (var e in dst) { + if (typeof dst[e] === "object") { + if (!compareDataObjects(dst[e], src[e])) { + return false; + } + } + else if (typeof dst[e] !== "function") { + if (dst[e] !== src[e]) { + return false; + } + } + } + return true; + } + ts.compareDataObjects = compareDataObjects; + /** + * clears already present map by calling onDeleteExistingValue callback before deleting that key/value + */ + function clearMap(map, onDeleteValue) { + // Remove all + map.forEach(onDeleteValue); + map.clear(); + } + ts.clearMap = clearMap; + /** + * Mutates the map with newMap such that keys in map will be same as newMap. + */ + function mutateMap(map, newMap, options) { + var createNewValue = options.createNewValue, onDeleteValue = options.onDeleteValue, onExistingValue = options.onExistingValue; + // Needs update + map.forEach(function (existingValue, key) { + var valueInNewMap = newMap.get(key); + // Not present any more in new map, remove it + if (valueInNewMap === undefined) { + map.delete(key); + onDeleteValue(existingValue, key); + } + // If present notify about existing values + else if (onExistingValue) { + onExistingValue(existingValue, valueInNewMap, key); + } + }); + // Add new values that are not already present + newMap.forEach(function (valueInNewMap, key) { + if (!map.has(key)) { + // New values + map.set(key, createNewValue(key, valueInNewMap)); + } + }); + } + ts.mutateMap = mutateMap; + /** Calls `callback` on `directory` and every ancestor directory it has, returning the first defined result. */ + function forEachAncestorDirectory(directory, callback) { + while (true) { + var result = callback(directory); + if (result !== undefined) { + return result; + } + var parentPath = ts.getDirectoryPath(directory); + if (parentPath === directory) { + return undefined; + } + directory = parentPath; + } + } + ts.forEachAncestorDirectory = forEachAncestorDirectory; + // Return true if the given type is the constructor type for an abstract class + function isAbstractConstructorType(type) { + return !!(getObjectFlags(type) & 16 /* Anonymous */) && !!type.symbol && isAbstractConstructorSymbol(type.symbol); + } + ts.isAbstractConstructorType = isAbstractConstructorType; + function isAbstractConstructorSymbol(symbol) { + if (symbol.flags & 32 /* Class */) { + var declaration = getClassLikeDeclarationOfSymbol(symbol); + return !!declaration && hasModifier(declaration, 128 /* Abstract */); + } + return false; + } + ts.isAbstractConstructorSymbol = isAbstractConstructorSymbol; + function getClassLikeDeclarationOfSymbol(symbol) { + return ts.find(symbol.declarations, ts.isClassLike); + } + ts.getClassLikeDeclarationOfSymbol = getClassLikeDeclarationOfSymbol; + function getObjectFlags(type) { + return type.flags & 524288 /* Object */ ? type.objectFlags : 0; + } + ts.getObjectFlags = getObjectFlags; + function typeHasCallOrConstructSignatures(type, checker) { + return checker.getSignaturesOfType(type, 0 /* Call */).length !== 0 || checker.getSignaturesOfType(type, 1 /* Construct */).length !== 0; + } + ts.typeHasCallOrConstructSignatures = typeHasCallOrConstructSignatures; + function forSomeAncestorDirectory(directory, callback) { + return !!forEachAncestorDirectory(directory, function (d) { return callback(d) ? true : undefined; }); + } + ts.forSomeAncestorDirectory = forSomeAncestorDirectory; + function isUMDExportSymbol(symbol) { + return !!symbol && !!symbol.declarations && !!symbol.declarations[0] && ts.isNamespaceExportDeclaration(symbol.declarations[0]); + } + ts.isUMDExportSymbol = isUMDExportSymbol; + function showModuleSpecifier(_a) { + var moduleSpecifier = _a.moduleSpecifier; + return ts.isStringLiteral(moduleSpecifier) ? moduleSpecifier.text : getTextOfNode(moduleSpecifier); + } + ts.showModuleSpecifier = showModuleSpecifier; + function getLastChild(node) { + var lastChild; + ts.forEachChild(node, function (child) { + if (nodeIsPresent(child)) + lastChild = child; + }, function (children) { + // As an optimization, jump straight to the end of the list. + for (var i = children.length - 1; i >= 0; i--) { + if (nodeIsPresent(children[i])) { + lastChild = children[i]; + break; + } + } + }); + return lastChild; + } + ts.getLastChild = getLastChild; + function addToSeen(seen, key, value) { + if (value === void 0) { value = true; } + key = String(key); + if (seen.has(key)) { + return false; + } + seen.set(key, value); + return true; + } + ts.addToSeen = addToSeen; + function isObjectTypeDeclaration(node) { + return ts.isClassLike(node) || ts.isInterfaceDeclaration(node) || ts.isTypeLiteralNode(node); + } + ts.isObjectTypeDeclaration = isObjectTypeDeclaration; + function isTypeNodeKind(kind) { + return (kind >= 163 /* FirstTypeNode */ && kind <= 183 /* LastTypeNode */) + || kind === 120 /* AnyKeyword */ + || kind === 143 /* UnknownKeyword */ + || kind === 135 /* NumberKeyword */ + || kind === 146 /* BigIntKeyword */ + || kind === 136 /* ObjectKeyword */ + || kind === 123 /* BooleanKeyword */ + || kind === 138 /* StringKeyword */ + || kind === 139 /* SymbolKeyword */ + || kind === 100 /* ThisKeyword */ + || kind === 106 /* VoidKeyword */ + || kind === 141 /* UndefinedKeyword */ + || kind === 96 /* NullKeyword */ + || kind === 132 /* NeverKeyword */ + || kind === 211 /* ExpressionWithTypeArguments */ + || kind === 284 /* JSDocAllType */ + || kind === 285 /* JSDocUnknownType */ + || kind === 286 /* JSDocNullableType */ + || kind === 287 /* JSDocNonNullableType */ + || kind === 288 /* JSDocOptionalType */ + || kind === 289 /* JSDocFunctionType */ + || kind === 290 /* JSDocVariadicType */; + } + ts.isTypeNodeKind = isTypeNodeKind; +})(ts || (ts = {})); +(function (ts) { + function getDefaultLibFileName(options) { + switch (options.target) { + case 6 /* ESNext */: + return "lib.esnext.full.d.ts"; + case 5 /* ES2018 */: + return "lib.es2018.full.d.ts"; + case 4 /* ES2017 */: + return "lib.es2017.full.d.ts"; + case 3 /* ES2016 */: + return "lib.es2016.full.d.ts"; + case 2 /* ES2015 */: + return "lib.es6.d.ts"; // We don't use lib.es2015.full.d.ts due to breaking change. + default: + return "lib.d.ts"; + } + } + ts.getDefaultLibFileName = getDefaultLibFileName; + function textSpanEnd(span) { + return span.start + span.length; + } + ts.textSpanEnd = textSpanEnd; + function textSpanIsEmpty(span) { + return span.length === 0; + } + ts.textSpanIsEmpty = textSpanIsEmpty; + function textSpanContainsPosition(span, position) { + return position >= span.start && position < textSpanEnd(span); + } + ts.textSpanContainsPosition = textSpanContainsPosition; + /* @internal */ + function textRangeContainsPositionInclusive(span, position) { + return position >= span.pos && position <= span.end; + } + ts.textRangeContainsPositionInclusive = textRangeContainsPositionInclusive; + // Returns true if 'span' contains 'other'. + function textSpanContainsTextSpan(span, other) { + return other.start >= span.start && textSpanEnd(other) <= textSpanEnd(span); + } + ts.textSpanContainsTextSpan = textSpanContainsTextSpan; + function textSpanOverlapsWith(span, other) { + return textSpanOverlap(span, other) !== undefined; + } + ts.textSpanOverlapsWith = textSpanOverlapsWith; + function textSpanOverlap(span1, span2) { + var overlap = textSpanIntersection(span1, span2); + return overlap && overlap.length === 0 ? undefined : overlap; + } + ts.textSpanOverlap = textSpanOverlap; + function textSpanIntersectsWithTextSpan(span, other) { + return decodedTextSpanIntersectsWith(span.start, span.length, other.start, other.length); + } + ts.textSpanIntersectsWithTextSpan = textSpanIntersectsWithTextSpan; + function textSpanIntersectsWith(span, start, length) { + return decodedTextSpanIntersectsWith(span.start, span.length, start, length); + } + ts.textSpanIntersectsWith = textSpanIntersectsWith; + function decodedTextSpanIntersectsWith(start1, length1, start2, length2) { + var end1 = start1 + length1; + var end2 = start2 + length2; + return start2 <= end1 && end2 >= start1; + } + ts.decodedTextSpanIntersectsWith = decodedTextSpanIntersectsWith; + function textSpanIntersectsWithPosition(span, position) { + return position <= textSpanEnd(span) && position >= span.start; + } + ts.textSpanIntersectsWithPosition = textSpanIntersectsWithPosition; + function textSpanIntersection(span1, span2) { + var start = Math.max(span1.start, span2.start); + var end = Math.min(textSpanEnd(span1), textSpanEnd(span2)); + return start <= end ? createTextSpanFromBounds(start, end) : undefined; + } + ts.textSpanIntersection = textSpanIntersection; + function createTextSpan(start, length) { + if (start < 0) { + throw new Error("start < 0"); + } + if (length < 0) { + throw new Error("length < 0"); + } + return { start: start, length: length }; + } + ts.createTextSpan = createTextSpan; + function createTextSpanFromBounds(start, end) { + return createTextSpan(start, end - start); + } + ts.createTextSpanFromBounds = createTextSpanFromBounds; + function textChangeRangeNewSpan(range) { + return createTextSpan(range.span.start, range.newLength); + } + ts.textChangeRangeNewSpan = textChangeRangeNewSpan; + function textChangeRangeIsUnchanged(range) { + return textSpanIsEmpty(range.span) && range.newLength === 0; + } + ts.textChangeRangeIsUnchanged = textChangeRangeIsUnchanged; + function createTextChangeRange(span, newLength) { + if (newLength < 0) { + throw new Error("newLength < 0"); + } + return { span: span, newLength: newLength }; + } + ts.createTextChangeRange = createTextChangeRange; + ts.unchangedTextChangeRange = createTextChangeRange(createTextSpan(0, 0), 0); + /** + * Called to merge all the changes that occurred across several versions of a script snapshot + * into a single change. i.e. if a user keeps making successive edits to a script we will + * have a text change from V1 to V2, V2 to V3, ..., Vn. + * + * This function will then merge those changes into a single change range valid between V1 and + * Vn. + */ + function collapseTextChangeRangesAcrossMultipleVersions(changes) { + if (changes.length === 0) { + return ts.unchangedTextChangeRange; + } + if (changes.length === 1) { + return changes[0]; + } + // We change from talking about { { oldStart, oldLength }, newLength } to { oldStart, oldEnd, newEnd } + // as it makes things much easier to reason about. + var change0 = changes[0]; + var oldStartN = change0.span.start; + var oldEndN = textSpanEnd(change0.span); + var newEndN = oldStartN + change0.newLength; + for (var i = 1; i < changes.length; i++) { + var nextChange = changes[i]; + // Consider the following case: + // i.e. two edits. The first represents the text change range { { 10, 50 }, 30 }. i.e. The span starting + // at 10, with length 50 is reduced to length 30. The second represents the text change range { { 30, 30 }, 40 }. + // i.e. the span starting at 30 with length 30 is increased to length 40. + // + // 0 10 20 30 40 50 60 70 80 90 100 + // ------------------------------------------------------------------------------------------------------- + // | / + // | /---- + // T1 | /---- + // | /---- + // | /---- + // ------------------------------------------------------------------------------------------------------- + // | \ + // | \ + // T2 | \ + // | \ + // | \ + // ------------------------------------------------------------------------------------------------------- + // + // Merging these turns out to not be too difficult. First, determining the new start of the change is trivial + // it's just the min of the old and new starts. i.e.: + // + // 0 10 20 30 40 50 60 70 80 90 100 + // ------------------------------------------------------------*------------------------------------------ + // | / + // | /---- + // T1 | /---- + // | /---- + // | /---- + // ----------------------------------------$-------------------$------------------------------------------ + // . | \ + // . | \ + // T2 . | \ + // . | \ + // . | \ + // ----------------------------------------------------------------------*-------------------------------- + // + // (Note the dots represent the newly inferred start. + // Determining the new and old end is also pretty simple. Basically it boils down to paying attention to the + // absolute positions at the asterisks, and the relative change between the dollar signs. Basically, we see + // which if the two $'s precedes the other, and we move that one forward until they line up. in this case that + // means: + // + // 0 10 20 30 40 50 60 70 80 90 100 + // --------------------------------------------------------------------------------*---------------------- + // | / + // | /---- + // T1 | /---- + // | /---- + // | /---- + // ------------------------------------------------------------$------------------------------------------ + // . | \ + // . | \ + // T2 . | \ + // . | \ + // . | \ + // ----------------------------------------------------------------------*-------------------------------- + // + // In other words (in this case), we're recognizing that the second edit happened after where the first edit + // ended with a delta of 20 characters (60 - 40). Thus, if we go back in time to where the first edit started + // that's the same as if we started at char 80 instead of 60. + // + // As it so happens, the same logic applies if the second edit precedes the first edit. In that case rather + // than pushing the first edit forward to match the second, we'll push the second edit forward to match the + // first. + // + // In this case that means we have { oldStart: 10, oldEnd: 80, newEnd: 70 } or, in TextChangeRange + // semantics: { { start: 10, length: 70 }, newLength: 60 } + // + // The math then works out as follows. + // If we have { oldStart1, oldEnd1, newEnd1 } and { oldStart2, oldEnd2, newEnd2 } then we can compute the + // final result like so: + // + // { + // oldStart3: Min(oldStart1, oldStart2), + // oldEnd3: Max(oldEnd1, oldEnd1 + (oldEnd2 - newEnd1)), + // newEnd3: Max(newEnd2, newEnd2 + (newEnd1 - oldEnd2)) + // } + var oldStart1 = oldStartN; + var oldEnd1 = oldEndN; + var newEnd1 = newEndN; + var oldStart2 = nextChange.span.start; + var oldEnd2 = textSpanEnd(nextChange.span); + var newEnd2 = oldStart2 + nextChange.newLength; + oldStartN = Math.min(oldStart1, oldStart2); + oldEndN = Math.max(oldEnd1, oldEnd1 + (oldEnd2 - newEnd1)); + newEndN = Math.max(newEnd2, newEnd2 + (newEnd1 - oldEnd2)); + } + return createTextChangeRange(createTextSpanFromBounds(oldStartN, oldEndN), /*newLength*/ newEndN - oldStartN); + } + ts.collapseTextChangeRangesAcrossMultipleVersions = collapseTextChangeRangesAcrossMultipleVersions; + function getTypeParameterOwner(d) { + if (d && d.kind === 150 /* TypeParameter */) { + for (var current = d; current; current = current.parent) { + if (ts.isFunctionLike(current) || ts.isClassLike(current) || current.kind === 241 /* InterfaceDeclaration */) { + return current; + } + } + } + } + ts.getTypeParameterOwner = getTypeParameterOwner; + function isParameterPropertyDeclaration(node) { + return ts.hasModifier(node, 92 /* ParameterPropertyModifier */) && node.parent.kind === 157 /* Constructor */; + } + ts.isParameterPropertyDeclaration = isParameterPropertyDeclaration; + function isEmptyBindingPattern(node) { + if (ts.isBindingPattern(node)) { + return ts.every(node.elements, isEmptyBindingElement); + } + return false; + } + ts.isEmptyBindingPattern = isEmptyBindingPattern; + function isEmptyBindingElement(node) { + if (ts.isOmittedExpression(node)) { + return true; + } + return isEmptyBindingPattern(node.name); + } + ts.isEmptyBindingElement = isEmptyBindingElement; + function walkUpBindingElementsAndPatterns(binding) { + var node = binding.parent; + while (ts.isBindingElement(node.parent)) { + node = node.parent.parent; + } + return node.parent; + } + ts.walkUpBindingElementsAndPatterns = walkUpBindingElementsAndPatterns; + function getCombinedFlags(node, getFlags) { + if (ts.isBindingElement(node)) { + node = walkUpBindingElementsAndPatterns(node); + } + var flags = getFlags(node); + if (node.kind === 237 /* VariableDeclaration */) { + node = node.parent; + } + if (node && node.kind === 238 /* VariableDeclarationList */) { + flags |= getFlags(node); + node = node.parent; + } + if (node && node.kind === 219 /* VariableStatement */) { + flags |= getFlags(node); + } + return flags; + } + function getCombinedModifierFlags(node) { + return getCombinedFlags(node, ts.getModifierFlags); + } + ts.getCombinedModifierFlags = getCombinedModifierFlags; + // Returns the node flags for this node and all relevant parent nodes. This is done so that + // nodes like variable declarations and binding elements can returned a view of their flags + // that includes the modifiers from their container. i.e. flags like export/declare aren't + // stored on the variable declaration directly, but on the containing variable statement + // (if it has one). Similarly, flags for let/const are store on the variable declaration + // list. By calling this function, all those flags are combined so that the client can treat + // the node as if it actually had those flags. + function getCombinedNodeFlags(node) { + return getCombinedFlags(node, function (n) { return n.flags; }); + } + ts.getCombinedNodeFlags = getCombinedNodeFlags; + /** + * Checks to see if the locale is in the appropriate format, + * and if it is, attempts to set the appropriate language. + */ + function validateLocaleAndSetLanguage(locale, sys, errors) { + var matchResult = /^([a-z]+)([_\-]([a-z]+))?$/.exec(locale.toLowerCase()); + if (!matchResult) { + if (errors) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1, "en", "ja-jp")); + } + return; + } + var language = matchResult[1]; + var territory = matchResult[3]; + // First try the entire locale, then fall back to just language if that's all we have. + // Either ways do not fail, and fallback to the English diagnostic strings. + if (!trySetLanguageAndTerritory(language, territory, errors)) { + trySetLanguageAndTerritory(language, /*territory*/ undefined, errors); + } + // Set the UI locale for string collation + ts.setUILocale(locale); + function trySetLanguageAndTerritory(language, territory, errors) { + var compilerFilePath = ts.normalizePath(sys.getExecutingFilePath()); + var containingDirectoryPath = ts.getDirectoryPath(compilerFilePath); + var filePath = ts.combinePaths(containingDirectoryPath, language); + if (territory) { + filePath = filePath + "-" + territory; + } + filePath = sys.resolvePath(ts.combinePaths(filePath, "diagnosticMessages.generated.json")); + if (!sys.fileExists(filePath)) { + return false; + } + // TODO: Add codePage support for readFile? + var fileContents = ""; + try { + fileContents = sys.readFile(filePath); + } + catch (e) { + if (errors) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unable_to_open_file_0, filePath)); + } + return false; + } + try { + // tslint:disable-next-line no-unnecessary-qualifier (making clear this is a global mutation!) + ts.localizedDiagnosticMessages = JSON.parse(fileContents); + } + catch (_a) { + if (errors) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Corrupted_locale_file_0, filePath)); + } + return false; + } + return true; + } + } + ts.validateLocaleAndSetLanguage = validateLocaleAndSetLanguage; + function getOriginalNode(node, nodeTest) { + if (node) { + while (node.original !== undefined) { + node = node.original; + } + } + return !nodeTest || nodeTest(node) ? node : undefined; + } + ts.getOriginalNode = getOriginalNode; + /** + * Gets a value indicating whether a node originated in the parse tree. + * + * @param node The node to test. + */ + function isParseTreeNode(node) { + return (node.flags & 8 /* Synthesized */) === 0; + } + ts.isParseTreeNode = isParseTreeNode; + function getParseTreeNode(node, nodeTest) { + if (node === undefined || isParseTreeNode(node)) { + return node; + } + node = getOriginalNode(node); + if (isParseTreeNode(node) && (!nodeTest || nodeTest(node))) { + return node; + } + return undefined; + } + ts.getParseTreeNode = getParseTreeNode; + /** Add an extra underscore to identifiers that start with two underscores to avoid issues with magic names like '__proto__' */ + function escapeLeadingUnderscores(identifier) { + return (identifier.length >= 2 && identifier.charCodeAt(0) === 95 /* _ */ && identifier.charCodeAt(1) === 95 /* _ */ ? "_" + identifier : identifier); + } + ts.escapeLeadingUnderscores = escapeLeadingUnderscores; + /** + * Remove extra underscore from escaped identifier text content. + * + * @param identifier The escaped identifier text. + * @returns The unescaped identifier text. + */ + function unescapeLeadingUnderscores(identifier) { + var id = identifier; + return id.length >= 3 && id.charCodeAt(0) === 95 /* _ */ && id.charCodeAt(1) === 95 /* _ */ && id.charCodeAt(2) === 95 /* _ */ ? id.substr(1) : id; + } + ts.unescapeLeadingUnderscores = unescapeLeadingUnderscores; + function idText(identifier) { + return unescapeLeadingUnderscores(identifier.escapedText); + } + ts.idText = idText; + function symbolName(symbol) { + return unescapeLeadingUnderscores(symbol.escapedName); + } + ts.symbolName = symbolName; + /** + * A JSDocTypedef tag has an _optional_ name field - if a name is not directly present, we should + * attempt to draw the name from the node the declaration is on (as that declaration is what its' symbol + * will be merged with) + */ + function nameForNamelessJSDocTypedef(declaration) { + var hostNode = declaration.parent.parent; + if (!hostNode) { + return undefined; + } + // Covers classes, functions - any named declaration host node + if (ts.isDeclaration(hostNode)) { + return getDeclarationIdentifier(hostNode); + } + // Covers remaining cases (returning undefined if none match). + switch (hostNode.kind) { + case 219 /* VariableStatement */: + if (hostNode.declarationList && hostNode.declarationList.declarations[0]) { + return getDeclarationIdentifier(hostNode.declarationList.declarations[0]); + } + break; + case 221 /* ExpressionStatement */: + var expr = hostNode.expression; + switch (expr.kind) { + case 189 /* PropertyAccessExpression */: + return expr.name; + case 190 /* ElementAccessExpression */: + var arg = expr.argumentExpression; + if (ts.isIdentifier(arg)) { + return arg; + } + } + break; + case 195 /* ParenthesizedExpression */: { + return getDeclarationIdentifier(hostNode.expression); + } + case 233 /* LabeledStatement */: { + if (ts.isDeclaration(hostNode.statement) || ts.isExpression(hostNode.statement)) { + return getDeclarationIdentifier(hostNode.statement); + } + break; + } + } + } + function getDeclarationIdentifier(node) { + var name = getNameOfDeclaration(node); + return name && ts.isIdentifier(name) ? name : undefined; + } + function getNameOfJSDocTypedef(declaration) { + return declaration.name || nameForNamelessJSDocTypedef(declaration); + } + ts.getNameOfJSDocTypedef = getNameOfJSDocTypedef; + /** @internal */ + function isNamedDeclaration(node) { + return !!node.name; // A 'name' property should always be a DeclarationName. + } + ts.isNamedDeclaration = isNamedDeclaration; + /** @internal */ + function getNonAssignedNameOfDeclaration(declaration) { + switch (declaration.kind) { + case 72 /* Identifier */: + return declaration; + case 305 /* JSDocPropertyTag */: + case 299 /* JSDocParameterTag */: { + var name = declaration.name; + if (name.kind === 148 /* QualifiedName */) { + return name.right; + } + break; + } + case 191 /* CallExpression */: + case 204 /* BinaryExpression */: { + var expr = declaration; + switch (ts.getAssignmentDeclarationKind(expr)) { + case 1 /* ExportsProperty */: + case 4 /* ThisProperty */: + case 5 /* Property */: + case 3 /* PrototypeProperty */: + return expr.left.name; + case 7 /* ObjectDefinePropertyValue */: + case 8 /* ObjectDefinePropertyExports */: + case 9 /* ObjectDefinePrototypeProperty */: + return expr.arguments[1]; + default: + return undefined; + } + } + case 304 /* JSDocTypedefTag */: + return getNameOfJSDocTypedef(declaration); + case 254 /* ExportAssignment */: { + var expression = declaration.expression; + return ts.isIdentifier(expression) ? expression : undefined; + } + } + return declaration.name; + } + ts.getNonAssignedNameOfDeclaration = getNonAssignedNameOfDeclaration; + function getNameOfDeclaration(declaration) { + if (declaration === undefined) + return undefined; + return getNonAssignedNameOfDeclaration(declaration) || + (ts.isFunctionExpression(declaration) || ts.isClassExpression(declaration) ? getAssignedName(declaration) : undefined); + } + ts.getNameOfDeclaration = getNameOfDeclaration; + function getAssignedName(node) { + if (!node.parent) { + return undefined; + } + else if (ts.isPropertyAssignment(node.parent) || ts.isBindingElement(node.parent)) { + return node.parent.name; + } + else if (ts.isBinaryExpression(node.parent) && node === node.parent.right) { + if (ts.isIdentifier(node.parent.left)) { + return node.parent.left; + } + else if (ts.isPropertyAccessExpression(node.parent.left)) { + return node.parent.left.name; + } + } + } + /** + * Gets the JSDoc parameter tags for the node if present. + * + * @remarks Returns any JSDoc param tag whose name matches the provided + * parameter, whether a param tag on a containing function + * expression, or a param tag on a variable declaration whose + * initializer is the containing function. The tags closest to the + * node are returned first, so in the previous example, the param + * tag on the containing function expression would be first. + * + * For binding patterns, parameter tags are matched by position. + */ + function getJSDocParameterTags(param) { + if (param.name) { + if (ts.isIdentifier(param.name)) { + var name_1 = param.name.escapedText; + return getJSDocTags(param.parent).filter(function (tag) { return ts.isJSDocParameterTag(tag) && ts.isIdentifier(tag.name) && tag.name.escapedText === name_1; }); + } + else { + var i = param.parent.parameters.indexOf(param); + ts.Debug.assert(i > -1, "Parameters should always be in their parents' parameter list"); + var paramTags = getJSDocTags(param.parent).filter(ts.isJSDocParameterTag); + if (i < paramTags.length) { + return [paramTags[i]]; + } + } + } + // return empty array for: out-of-order binding patterns and JSDoc function syntax, which has un-named parameters + return ts.emptyArray; + } + ts.getJSDocParameterTags = getJSDocParameterTags; + /** + * Gets the JSDoc type parameter tags for the node if present. + * + * @remarks Returns any JSDoc template tag whose names match the provided + * parameter, whether a template tag on a containing function + * expression, or a template tag on a variable declaration whose + * initializer is the containing function. The tags closest to the + * node are returned first, so in the previous example, the template + * tag on the containing function expression would be first. + */ + function getJSDocTypeParameterTags(param) { + var name = param.name.escapedText; + return getJSDocTags(param.parent).filter(function (tag) { + return ts.isJSDocTemplateTag(tag) && tag.typeParameters.some(function (tp) { return tp.name.escapedText === name; }); + }); + } + ts.getJSDocTypeParameterTags = getJSDocTypeParameterTags; + /** + * Return true if the node has JSDoc parameter tags. + * + * @remarks Includes parameter tags that are not directly on the node, + * for example on a variable declaration whose initializer is a function expression. + */ + function hasJSDocParameterTags(node) { + return !!getFirstJSDocTag(node, ts.isJSDocParameterTag); + } + ts.hasJSDocParameterTags = hasJSDocParameterTags; + /** Gets the JSDoc augments tag for the node if present */ + function getJSDocAugmentsTag(node) { + return getFirstJSDocTag(node, ts.isJSDocAugmentsTag); + } + ts.getJSDocAugmentsTag = getJSDocAugmentsTag; + /** Gets the JSDoc class tag for the node if present */ + function getJSDocClassTag(node) { + return getFirstJSDocTag(node, ts.isJSDocClassTag); + } + ts.getJSDocClassTag = getJSDocClassTag; + /** Gets the JSDoc enum tag for the node if present */ + function getJSDocEnumTag(node) { + return getFirstJSDocTag(node, ts.isJSDocEnumTag); + } + ts.getJSDocEnumTag = getJSDocEnumTag; + /** Gets the JSDoc this tag for the node if present */ + function getJSDocThisTag(node) { + return getFirstJSDocTag(node, ts.isJSDocThisTag); + } + ts.getJSDocThisTag = getJSDocThisTag; + /** Gets the JSDoc return tag for the node if present */ + function getJSDocReturnTag(node) { + return getFirstJSDocTag(node, ts.isJSDocReturnTag); + } + ts.getJSDocReturnTag = getJSDocReturnTag; + /** Gets the JSDoc template tag for the node if present */ + function getJSDocTemplateTag(node) { + return getFirstJSDocTag(node, ts.isJSDocTemplateTag); + } + ts.getJSDocTemplateTag = getJSDocTemplateTag; + /** Gets the JSDoc type tag for the node if present and valid */ + function getJSDocTypeTag(node) { + // We should have already issued an error if there were multiple type jsdocs, so just use the first one. + var tag = getFirstJSDocTag(node, ts.isJSDocTypeTag); + if (tag && tag.typeExpression && tag.typeExpression.type) { + return tag; + } + return undefined; + } + ts.getJSDocTypeTag = getJSDocTypeTag; + /** + * Gets the type node for the node if provided via JSDoc. + * + * @remarks The search includes any JSDoc param tag that relates + * to the provided parameter, for example a type tag on the + * parameter itself, or a param tag on a containing function + * expression, or a param tag on a variable declaration whose + * initializer is the containing function. The tags closest to the + * node are examined first, so in the previous example, the type + * tag directly on the node would be returned. + */ + function getJSDocType(node) { + var tag = getFirstJSDocTag(node, ts.isJSDocTypeTag); + if (!tag && ts.isParameter(node)) { + tag = ts.find(getJSDocParameterTags(node), function (tag) { return !!tag.typeExpression; }); + } + return tag && tag.typeExpression && tag.typeExpression.type; + } + ts.getJSDocType = getJSDocType; + /** + * Gets the return type node for the node if provided via JSDoc return tag or type tag. + * + * @remarks `getJSDocReturnTag` just gets the whole JSDoc tag. This function + * gets the type from inside the braces, after the fat arrow, etc. + */ + function getJSDocReturnType(node) { + var returnTag = getJSDocReturnTag(node); + if (returnTag && returnTag.typeExpression) { + return returnTag.typeExpression.type; + } + var typeTag = getJSDocTypeTag(node); + if (typeTag && typeTag.typeExpression) { + var type = typeTag.typeExpression.type; + if (ts.isTypeLiteralNode(type)) { + var sig = ts.find(type.members, ts.isCallSignatureDeclaration); + return sig && sig.type; + } + if (ts.isFunctionTypeNode(type)) { + return type.type; + } + } + } + ts.getJSDocReturnType = getJSDocReturnType; + /** Get all JSDoc tags related to a node, including those on parent nodes. */ + function getJSDocTags(node) { + var tags = node.jsDocCache; + // If cache is 'null', that means we did the work of searching for JSDoc tags and came up with nothing. + if (tags === undefined) { + var comments = ts.getJSDocCommentsAndTags(node); + ts.Debug.assert(comments.length < 2 || comments[0] !== comments[1]); + node.jsDocCache = tags = ts.flatMap(comments, function (j) { return ts.isJSDoc(j) ? j.tags : j; }); + } + return tags; + } + ts.getJSDocTags = getJSDocTags; + /** Get the first JSDoc tag of a specified kind, or undefined if not present. */ + function getFirstJSDocTag(node, predicate) { + return ts.find(getJSDocTags(node), predicate); + } + /** Gets all JSDoc tags of a specified kind, or undefined if not present. */ + function getAllJSDocTagsOfKind(node, kind) { + return getJSDocTags(node).filter(function (doc) { return doc.kind === kind; }); + } + ts.getAllJSDocTagsOfKind = getAllJSDocTagsOfKind; + /** + * Gets the effective type parameters. If the node was parsed in a + * JavaScript file, gets the type parameters from the `@template` tag from JSDoc. + */ + function getEffectiveTypeParameterDeclarations(node) { + if (ts.isJSDocSignature(node)) { + return ts.emptyArray; + } + if (ts.isJSDocTypeAlias(node)) { + ts.Debug.assert(node.parent.kind === 291 /* JSDocComment */); + return ts.flatMap(node.parent.tags, function (tag) { return ts.isJSDocTemplateTag(tag) ? tag.typeParameters : undefined; }); + } + if (node.typeParameters) { + return node.typeParameters; + } + if (ts.isInJSFile(node)) { + var decls = ts.getJSDocTypeParameterDeclarations(node); + if (decls.length) { + return decls; + } + var typeTag = getJSDocType(node); + if (typeTag && ts.isFunctionTypeNode(typeTag) && typeTag.typeParameters) { + return typeTag.typeParameters; + } + } + return ts.emptyArray; + } + ts.getEffectiveTypeParameterDeclarations = getEffectiveTypeParameterDeclarations; + function getEffectiveConstraintOfTypeParameter(node) { + return node.constraint ? node.constraint + : ts.isJSDocTemplateTag(node.parent) && node === node.parent.typeParameters[0] + ? node.parent.constraint + : undefined; + } + ts.getEffectiveConstraintOfTypeParameter = getEffectiveConstraintOfTypeParameter; +})(ts || (ts = {})); +// Simple node tests of the form `node.kind === SyntaxKind.Foo`. +(function (ts) { + // Literals + function isNumericLiteral(node) { + return node.kind === 8 /* NumericLiteral */; + } + ts.isNumericLiteral = isNumericLiteral; + function isBigIntLiteral(node) { + return node.kind === 9 /* BigIntLiteral */; + } + ts.isBigIntLiteral = isBigIntLiteral; + function isStringLiteral(node) { + return node.kind === 10 /* StringLiteral */; + } + ts.isStringLiteral = isStringLiteral; + function isJsxText(node) { + return node.kind === 11 /* JsxText */; + } + ts.isJsxText = isJsxText; + function isRegularExpressionLiteral(node) { + return node.kind === 13 /* RegularExpressionLiteral */; + } + ts.isRegularExpressionLiteral = isRegularExpressionLiteral; + function isNoSubstitutionTemplateLiteral(node) { + return node.kind === 14 /* NoSubstitutionTemplateLiteral */; + } + ts.isNoSubstitutionTemplateLiteral = isNoSubstitutionTemplateLiteral; + // Pseudo-literals + function isTemplateHead(node) { + return node.kind === 15 /* TemplateHead */; + } + ts.isTemplateHead = isTemplateHead; + function isTemplateMiddle(node) { + return node.kind === 16 /* TemplateMiddle */; + } + ts.isTemplateMiddle = isTemplateMiddle; + function isTemplateTail(node) { + return node.kind === 17 /* TemplateTail */; + } + ts.isTemplateTail = isTemplateTail; + function isIdentifier(node) { + return node.kind === 72 /* Identifier */; + } + ts.isIdentifier = isIdentifier; + // Names + function isQualifiedName(node) { + return node.kind === 148 /* QualifiedName */; + } + ts.isQualifiedName = isQualifiedName; + function isComputedPropertyName(node) { + return node.kind === 149 /* ComputedPropertyName */; + } + ts.isComputedPropertyName = isComputedPropertyName; + // Signature elements + function isTypeParameterDeclaration(node) { + return node.kind === 150 /* TypeParameter */; + } + ts.isTypeParameterDeclaration = isTypeParameterDeclaration; + function isParameter(node) { + return node.kind === 151 /* Parameter */; + } + ts.isParameter = isParameter; + function isDecorator(node) { + return node.kind === 152 /* Decorator */; + } + ts.isDecorator = isDecorator; + // TypeMember + function isPropertySignature(node) { + return node.kind === 153 /* PropertySignature */; + } + ts.isPropertySignature = isPropertySignature; + function isPropertyDeclaration(node) { + return node.kind === 154 /* PropertyDeclaration */; + } + ts.isPropertyDeclaration = isPropertyDeclaration; + function isMethodSignature(node) { + return node.kind === 155 /* MethodSignature */; + } + ts.isMethodSignature = isMethodSignature; + function isMethodDeclaration(node) { + return node.kind === 156 /* MethodDeclaration */; + } + ts.isMethodDeclaration = isMethodDeclaration; + function isConstructorDeclaration(node) { + return node.kind === 157 /* Constructor */; + } + ts.isConstructorDeclaration = isConstructorDeclaration; + function isGetAccessorDeclaration(node) { + return node.kind === 158 /* GetAccessor */; + } + ts.isGetAccessorDeclaration = isGetAccessorDeclaration; + function isSetAccessorDeclaration(node) { + return node.kind === 159 /* SetAccessor */; + } + ts.isSetAccessorDeclaration = isSetAccessorDeclaration; + function isCallSignatureDeclaration(node) { + return node.kind === 160 /* CallSignature */; + } + ts.isCallSignatureDeclaration = isCallSignatureDeclaration; + function isConstructSignatureDeclaration(node) { + return node.kind === 161 /* ConstructSignature */; + } + ts.isConstructSignatureDeclaration = isConstructSignatureDeclaration; + function isIndexSignatureDeclaration(node) { + return node.kind === 162 /* IndexSignature */; + } + ts.isIndexSignatureDeclaration = isIndexSignatureDeclaration; + /* @internal */ + function isGetOrSetAccessorDeclaration(node) { + return node.kind === 159 /* SetAccessor */ || node.kind === 158 /* GetAccessor */; + } + ts.isGetOrSetAccessorDeclaration = isGetOrSetAccessorDeclaration; + // Type + function isTypePredicateNode(node) { + return node.kind === 163 /* TypePredicate */; + } + ts.isTypePredicateNode = isTypePredicateNode; + function isTypeReferenceNode(node) { + return node.kind === 164 /* TypeReference */; + } + ts.isTypeReferenceNode = isTypeReferenceNode; + function isFunctionTypeNode(node) { + return node.kind === 165 /* FunctionType */; + } + ts.isFunctionTypeNode = isFunctionTypeNode; + function isConstructorTypeNode(node) { + return node.kind === 166 /* ConstructorType */; + } + ts.isConstructorTypeNode = isConstructorTypeNode; + function isTypeQueryNode(node) { + return node.kind === 167 /* TypeQuery */; + } + ts.isTypeQueryNode = isTypeQueryNode; + function isTypeLiteralNode(node) { + return node.kind === 168 /* TypeLiteral */; + } + ts.isTypeLiteralNode = isTypeLiteralNode; + function isArrayTypeNode(node) { + return node.kind === 169 /* ArrayType */; + } + ts.isArrayTypeNode = isArrayTypeNode; + function isTupleTypeNode(node) { + return node.kind === 170 /* TupleType */; + } + ts.isTupleTypeNode = isTupleTypeNode; + function isUnionTypeNode(node) { + return node.kind === 173 /* UnionType */; + } + ts.isUnionTypeNode = isUnionTypeNode; + function isIntersectionTypeNode(node) { + return node.kind === 174 /* IntersectionType */; + } + ts.isIntersectionTypeNode = isIntersectionTypeNode; + function isConditionalTypeNode(node) { + return node.kind === 175 /* ConditionalType */; + } + ts.isConditionalTypeNode = isConditionalTypeNode; + function isInferTypeNode(node) { + return node.kind === 176 /* InferType */; + } + ts.isInferTypeNode = isInferTypeNode; + function isParenthesizedTypeNode(node) { + return node.kind === 177 /* ParenthesizedType */; + } + ts.isParenthesizedTypeNode = isParenthesizedTypeNode; + function isThisTypeNode(node) { + return node.kind === 178 /* ThisType */; + } + ts.isThisTypeNode = isThisTypeNode; + function isTypeOperatorNode(node) { + return node.kind === 179 /* TypeOperator */; + } + ts.isTypeOperatorNode = isTypeOperatorNode; + function isIndexedAccessTypeNode(node) { + return node.kind === 180 /* IndexedAccessType */; + } + ts.isIndexedAccessTypeNode = isIndexedAccessTypeNode; + function isMappedTypeNode(node) { + return node.kind === 181 /* MappedType */; + } + ts.isMappedTypeNode = isMappedTypeNode; + function isLiteralTypeNode(node) { + return node.kind === 182 /* LiteralType */; + } + ts.isLiteralTypeNode = isLiteralTypeNode; + function isImportTypeNode(node) { + return node.kind === 183 /* ImportType */; + } + ts.isImportTypeNode = isImportTypeNode; + // Binding patterns + function isObjectBindingPattern(node) { + return node.kind === 184 /* ObjectBindingPattern */; + } + ts.isObjectBindingPattern = isObjectBindingPattern; + function isArrayBindingPattern(node) { + return node.kind === 185 /* ArrayBindingPattern */; + } + ts.isArrayBindingPattern = isArrayBindingPattern; + function isBindingElement(node) { + return node.kind === 186 /* BindingElement */; + } + ts.isBindingElement = isBindingElement; + // Expression + function isArrayLiteralExpression(node) { + return node.kind === 187 /* ArrayLiteralExpression */; + } + ts.isArrayLiteralExpression = isArrayLiteralExpression; + function isObjectLiteralExpression(node) { + return node.kind === 188 /* ObjectLiteralExpression */; + } + ts.isObjectLiteralExpression = isObjectLiteralExpression; + function isPropertyAccessExpression(node) { + return node.kind === 189 /* PropertyAccessExpression */; + } + ts.isPropertyAccessExpression = isPropertyAccessExpression; + function isElementAccessExpression(node) { + return node.kind === 190 /* ElementAccessExpression */; + } + ts.isElementAccessExpression = isElementAccessExpression; + function isCallExpression(node) { + return node.kind === 191 /* CallExpression */; + } + ts.isCallExpression = isCallExpression; + function isNewExpression(node) { + return node.kind === 192 /* NewExpression */; + } + ts.isNewExpression = isNewExpression; + function isTaggedTemplateExpression(node) { + return node.kind === 193 /* TaggedTemplateExpression */; + } + ts.isTaggedTemplateExpression = isTaggedTemplateExpression; + function isTypeAssertion(node) { + return node.kind === 194 /* TypeAssertionExpression */; + } + ts.isTypeAssertion = isTypeAssertion; + function isParenthesizedExpression(node) { + return node.kind === 195 /* ParenthesizedExpression */; + } + ts.isParenthesizedExpression = isParenthesizedExpression; + function skipPartiallyEmittedExpressions(node) { + while (node.kind === 308 /* PartiallyEmittedExpression */) { + node = node.expression; + } + return node; + } + ts.skipPartiallyEmittedExpressions = skipPartiallyEmittedExpressions; + function isFunctionExpression(node) { + return node.kind === 196 /* FunctionExpression */; + } + ts.isFunctionExpression = isFunctionExpression; + function isArrowFunction(node) { + return node.kind === 197 /* ArrowFunction */; + } + ts.isArrowFunction = isArrowFunction; + function isDeleteExpression(node) { + return node.kind === 198 /* DeleteExpression */; + } + ts.isDeleteExpression = isDeleteExpression; + function isTypeOfExpression(node) { + return node.kind === 199 /* TypeOfExpression */; + } + ts.isTypeOfExpression = isTypeOfExpression; + function isVoidExpression(node) { + return node.kind === 200 /* VoidExpression */; + } + ts.isVoidExpression = isVoidExpression; + function isAwaitExpression(node) { + return node.kind === 201 /* AwaitExpression */; + } + ts.isAwaitExpression = isAwaitExpression; + function isPrefixUnaryExpression(node) { + return node.kind === 202 /* PrefixUnaryExpression */; + } + ts.isPrefixUnaryExpression = isPrefixUnaryExpression; + function isPostfixUnaryExpression(node) { + return node.kind === 203 /* PostfixUnaryExpression */; + } + ts.isPostfixUnaryExpression = isPostfixUnaryExpression; + function isBinaryExpression(node) { + return node.kind === 204 /* BinaryExpression */; + } + ts.isBinaryExpression = isBinaryExpression; + function isConditionalExpression(node) { + return node.kind === 205 /* ConditionalExpression */; + } + ts.isConditionalExpression = isConditionalExpression; + function isTemplateExpression(node) { + return node.kind === 206 /* TemplateExpression */; + } + ts.isTemplateExpression = isTemplateExpression; + function isYieldExpression(node) { + return node.kind === 207 /* YieldExpression */; + } + ts.isYieldExpression = isYieldExpression; + function isSpreadElement(node) { + return node.kind === 208 /* SpreadElement */; + } + ts.isSpreadElement = isSpreadElement; + function isClassExpression(node) { + return node.kind === 209 /* ClassExpression */; + } + ts.isClassExpression = isClassExpression; + function isOmittedExpression(node) { + return node.kind === 210 /* OmittedExpression */; + } + ts.isOmittedExpression = isOmittedExpression; + function isExpressionWithTypeArguments(node) { + return node.kind === 211 /* ExpressionWithTypeArguments */; + } + ts.isExpressionWithTypeArguments = isExpressionWithTypeArguments; + function isAsExpression(node) { + return node.kind === 212 /* AsExpression */; + } + ts.isAsExpression = isAsExpression; + function isNonNullExpression(node) { + return node.kind === 213 /* NonNullExpression */; + } + ts.isNonNullExpression = isNonNullExpression; + function isMetaProperty(node) { + return node.kind === 214 /* MetaProperty */; + } + ts.isMetaProperty = isMetaProperty; + // Misc + function isTemplateSpan(node) { + return node.kind === 216 /* TemplateSpan */; + } + ts.isTemplateSpan = isTemplateSpan; + function isSemicolonClassElement(node) { + return node.kind === 217 /* SemicolonClassElement */; + } + ts.isSemicolonClassElement = isSemicolonClassElement; + // Block + function isBlock(node) { + return node.kind === 218 /* Block */; + } + ts.isBlock = isBlock; + function isVariableStatement(node) { + return node.kind === 219 /* VariableStatement */; + } + ts.isVariableStatement = isVariableStatement; + function isEmptyStatement(node) { + return node.kind === 220 /* EmptyStatement */; + } + ts.isEmptyStatement = isEmptyStatement; + function isExpressionStatement(node) { + return node.kind === 221 /* ExpressionStatement */; + } + ts.isExpressionStatement = isExpressionStatement; + function isIfStatement(node) { + return node.kind === 222 /* IfStatement */; + } + ts.isIfStatement = isIfStatement; + function isDoStatement(node) { + return node.kind === 223 /* DoStatement */; + } + ts.isDoStatement = isDoStatement; + function isWhileStatement(node) { + return node.kind === 224 /* WhileStatement */; + } + ts.isWhileStatement = isWhileStatement; + function isForStatement(node) { + return node.kind === 225 /* ForStatement */; + } + ts.isForStatement = isForStatement; + function isForInStatement(node) { + return node.kind === 226 /* ForInStatement */; + } + ts.isForInStatement = isForInStatement; + function isForOfStatement(node) { + return node.kind === 227 /* ForOfStatement */; + } + ts.isForOfStatement = isForOfStatement; + function isContinueStatement(node) { + return node.kind === 228 /* ContinueStatement */; + } + ts.isContinueStatement = isContinueStatement; + function isBreakStatement(node) { + return node.kind === 229 /* BreakStatement */; + } + ts.isBreakStatement = isBreakStatement; + function isBreakOrContinueStatement(node) { + return node.kind === 229 /* BreakStatement */ || node.kind === 228 /* ContinueStatement */; + } + ts.isBreakOrContinueStatement = isBreakOrContinueStatement; + function isReturnStatement(node) { + return node.kind === 230 /* ReturnStatement */; + } + ts.isReturnStatement = isReturnStatement; + function isWithStatement(node) { + return node.kind === 231 /* WithStatement */; + } + ts.isWithStatement = isWithStatement; + function isSwitchStatement(node) { + return node.kind === 232 /* SwitchStatement */; + } + ts.isSwitchStatement = isSwitchStatement; + function isLabeledStatement(node) { + return node.kind === 233 /* LabeledStatement */; + } + ts.isLabeledStatement = isLabeledStatement; + function isThrowStatement(node) { + return node.kind === 234 /* ThrowStatement */; + } + ts.isThrowStatement = isThrowStatement; + function isTryStatement(node) { + return node.kind === 235 /* TryStatement */; + } + ts.isTryStatement = isTryStatement; + function isDebuggerStatement(node) { + return node.kind === 236 /* DebuggerStatement */; + } + ts.isDebuggerStatement = isDebuggerStatement; + function isVariableDeclaration(node) { + return node.kind === 237 /* VariableDeclaration */; + } + ts.isVariableDeclaration = isVariableDeclaration; + function isVariableDeclarationList(node) { + return node.kind === 238 /* VariableDeclarationList */; + } + ts.isVariableDeclarationList = isVariableDeclarationList; + function isFunctionDeclaration(node) { + return node.kind === 239 /* FunctionDeclaration */; + } + ts.isFunctionDeclaration = isFunctionDeclaration; + function isClassDeclaration(node) { + return node.kind === 240 /* ClassDeclaration */; + } + ts.isClassDeclaration = isClassDeclaration; + function isInterfaceDeclaration(node) { + return node.kind === 241 /* InterfaceDeclaration */; + } + ts.isInterfaceDeclaration = isInterfaceDeclaration; + function isTypeAliasDeclaration(node) { + return node.kind === 242 /* TypeAliasDeclaration */; + } + ts.isTypeAliasDeclaration = isTypeAliasDeclaration; + function isEnumDeclaration(node) { + return node.kind === 243 /* EnumDeclaration */; + } + ts.isEnumDeclaration = isEnumDeclaration; + function isModuleDeclaration(node) { + return node.kind === 244 /* ModuleDeclaration */; + } + ts.isModuleDeclaration = isModuleDeclaration; + function isModuleBlock(node) { + return node.kind === 245 /* ModuleBlock */; + } + ts.isModuleBlock = isModuleBlock; + function isCaseBlock(node) { + return node.kind === 246 /* CaseBlock */; + } + ts.isCaseBlock = isCaseBlock; + function isNamespaceExportDeclaration(node) { + return node.kind === 247 /* NamespaceExportDeclaration */; + } + ts.isNamespaceExportDeclaration = isNamespaceExportDeclaration; + function isImportEqualsDeclaration(node) { + return node.kind === 248 /* ImportEqualsDeclaration */; + } + ts.isImportEqualsDeclaration = isImportEqualsDeclaration; + function isImportDeclaration(node) { + return node.kind === 249 /* ImportDeclaration */; + } + ts.isImportDeclaration = isImportDeclaration; + function isImportClause(node) { + return node.kind === 250 /* ImportClause */; + } + ts.isImportClause = isImportClause; + function isNamespaceImport(node) { + return node.kind === 251 /* NamespaceImport */; + } + ts.isNamespaceImport = isNamespaceImport; + function isNamedImports(node) { + return node.kind === 252 /* NamedImports */; + } + ts.isNamedImports = isNamedImports; + function isImportSpecifier(node) { + return node.kind === 253 /* ImportSpecifier */; + } + ts.isImportSpecifier = isImportSpecifier; + function isExportAssignment(node) { + return node.kind === 254 /* ExportAssignment */; + } + ts.isExportAssignment = isExportAssignment; + function isExportDeclaration(node) { + return node.kind === 255 /* ExportDeclaration */; + } + ts.isExportDeclaration = isExportDeclaration; + function isNamedExports(node) { + return node.kind === 256 /* NamedExports */; + } + ts.isNamedExports = isNamedExports; + function isExportSpecifier(node) { + return node.kind === 257 /* ExportSpecifier */; + } + ts.isExportSpecifier = isExportSpecifier; + function isMissingDeclaration(node) { + return node.kind === 258 /* MissingDeclaration */; + } + ts.isMissingDeclaration = isMissingDeclaration; + // Module References + function isExternalModuleReference(node) { + return node.kind === 259 /* ExternalModuleReference */; + } + ts.isExternalModuleReference = isExternalModuleReference; + // JSX + function isJsxElement(node) { + return node.kind === 260 /* JsxElement */; + } + ts.isJsxElement = isJsxElement; + function isJsxSelfClosingElement(node) { + return node.kind === 261 /* JsxSelfClosingElement */; + } + ts.isJsxSelfClosingElement = isJsxSelfClosingElement; + function isJsxOpeningElement(node) { + return node.kind === 262 /* JsxOpeningElement */; + } + ts.isJsxOpeningElement = isJsxOpeningElement; + function isJsxClosingElement(node) { + return node.kind === 263 /* JsxClosingElement */; + } + ts.isJsxClosingElement = isJsxClosingElement; + function isJsxFragment(node) { + return node.kind === 264 /* JsxFragment */; + } + ts.isJsxFragment = isJsxFragment; + function isJsxOpeningFragment(node) { + return node.kind === 265 /* JsxOpeningFragment */; + } + ts.isJsxOpeningFragment = isJsxOpeningFragment; + function isJsxClosingFragment(node) { + return node.kind === 266 /* JsxClosingFragment */; + } + ts.isJsxClosingFragment = isJsxClosingFragment; + function isJsxAttribute(node) { + return node.kind === 267 /* JsxAttribute */; + } + ts.isJsxAttribute = isJsxAttribute; + function isJsxAttributes(node) { + return node.kind === 268 /* JsxAttributes */; + } + ts.isJsxAttributes = isJsxAttributes; + function isJsxSpreadAttribute(node) { + return node.kind === 269 /* JsxSpreadAttribute */; + } + ts.isJsxSpreadAttribute = isJsxSpreadAttribute; + function isJsxExpression(node) { + return node.kind === 270 /* JsxExpression */; + } + ts.isJsxExpression = isJsxExpression; + // Clauses + function isCaseClause(node) { + return node.kind === 271 /* CaseClause */; + } + ts.isCaseClause = isCaseClause; + function isDefaultClause(node) { + return node.kind === 272 /* DefaultClause */; + } + ts.isDefaultClause = isDefaultClause; + function isHeritageClause(node) { + return node.kind === 273 /* HeritageClause */; + } + ts.isHeritageClause = isHeritageClause; + function isCatchClause(node) { + return node.kind === 274 /* CatchClause */; + } + ts.isCatchClause = isCatchClause; + // Property assignments + function isPropertyAssignment(node) { + return node.kind === 275 /* PropertyAssignment */; + } + ts.isPropertyAssignment = isPropertyAssignment; + function isShorthandPropertyAssignment(node) { + return node.kind === 276 /* ShorthandPropertyAssignment */; + } + ts.isShorthandPropertyAssignment = isShorthandPropertyAssignment; + function isSpreadAssignment(node) { + return node.kind === 277 /* SpreadAssignment */; + } + ts.isSpreadAssignment = isSpreadAssignment; + // Enum + function isEnumMember(node) { + return node.kind === 278 /* EnumMember */; + } + ts.isEnumMember = isEnumMember; + // Top-level nodes + function isSourceFile(node) { + return node.kind === 279 /* SourceFile */; + } + ts.isSourceFile = isSourceFile; + function isBundle(node) { + return node.kind === 280 /* Bundle */; + } + ts.isBundle = isBundle; + function isUnparsedSource(node) { + return node.kind === 281 /* UnparsedSource */; + } + ts.isUnparsedSource = isUnparsedSource; + // JSDoc + function isJSDocTypeExpression(node) { + return node.kind === 283 /* JSDocTypeExpression */; + } + ts.isJSDocTypeExpression = isJSDocTypeExpression; + function isJSDocAllType(node) { + return node.kind === 284 /* JSDocAllType */; + } + ts.isJSDocAllType = isJSDocAllType; + function isJSDocUnknownType(node) { + return node.kind === 285 /* JSDocUnknownType */; + } + ts.isJSDocUnknownType = isJSDocUnknownType; + function isJSDocNullableType(node) { + return node.kind === 286 /* JSDocNullableType */; + } + ts.isJSDocNullableType = isJSDocNullableType; + function isJSDocNonNullableType(node) { + return node.kind === 287 /* JSDocNonNullableType */; + } + ts.isJSDocNonNullableType = isJSDocNonNullableType; + function isJSDocOptionalType(node) { + return node.kind === 288 /* JSDocOptionalType */; + } + ts.isJSDocOptionalType = isJSDocOptionalType; + function isJSDocFunctionType(node) { + return node.kind === 289 /* JSDocFunctionType */; + } + ts.isJSDocFunctionType = isJSDocFunctionType; + function isJSDocVariadicType(node) { + return node.kind === 290 /* JSDocVariadicType */; + } + ts.isJSDocVariadicType = isJSDocVariadicType; + function isJSDoc(node) { + return node.kind === 291 /* JSDocComment */; + } + ts.isJSDoc = isJSDoc; + function isJSDocAugmentsTag(node) { + return node.kind === 295 /* JSDocAugmentsTag */; + } + ts.isJSDocAugmentsTag = isJSDocAugmentsTag; + function isJSDocClassTag(node) { + return node.kind === 296 /* JSDocClassTag */; + } + ts.isJSDocClassTag = isJSDocClassTag; + function isJSDocEnumTag(node) { + return node.kind === 298 /* JSDocEnumTag */; + } + ts.isJSDocEnumTag = isJSDocEnumTag; + function isJSDocThisTag(node) { + return node.kind === 301 /* JSDocThisTag */; + } + ts.isJSDocThisTag = isJSDocThisTag; + function isJSDocParameterTag(node) { + return node.kind === 299 /* JSDocParameterTag */; + } + ts.isJSDocParameterTag = isJSDocParameterTag; + function isJSDocReturnTag(node) { + return node.kind === 300 /* JSDocReturnTag */; + } + ts.isJSDocReturnTag = isJSDocReturnTag; + function isJSDocTypeTag(node) { + return node.kind === 302 /* JSDocTypeTag */; + } + ts.isJSDocTypeTag = isJSDocTypeTag; + function isJSDocTemplateTag(node) { + return node.kind === 303 /* JSDocTemplateTag */; + } + ts.isJSDocTemplateTag = isJSDocTemplateTag; + function isJSDocTypedefTag(node) { + return node.kind === 304 /* JSDocTypedefTag */; + } + ts.isJSDocTypedefTag = isJSDocTypedefTag; + function isJSDocPropertyTag(node) { + return node.kind === 305 /* JSDocPropertyTag */; + } + ts.isJSDocPropertyTag = isJSDocPropertyTag; + function isJSDocPropertyLikeTag(node) { + return node.kind === 305 /* JSDocPropertyTag */ || node.kind === 299 /* JSDocParameterTag */; + } + ts.isJSDocPropertyLikeTag = isJSDocPropertyLikeTag; + function isJSDocTypeLiteral(node) { + return node.kind === 292 /* JSDocTypeLiteral */; + } + ts.isJSDocTypeLiteral = isJSDocTypeLiteral; + function isJSDocCallbackTag(node) { + return node.kind === 297 /* JSDocCallbackTag */; + } + ts.isJSDocCallbackTag = isJSDocCallbackTag; + function isJSDocSignature(node) { + return node.kind === 293 /* JSDocSignature */; + } + ts.isJSDocSignature = isJSDocSignature; +})(ts || (ts = {})); +// Node tests +// +// All node tests in the following list should *not* reference parent pointers so that +// they may be used with transformations. +(function (ts) { + /* @internal */ + function isSyntaxList(n) { + return n.kind === 306 /* SyntaxList */; + } + ts.isSyntaxList = isSyntaxList; + /* @internal */ + function isNode(node) { + return isNodeKind(node.kind); + } + ts.isNode = isNode; + /* @internal */ + function isNodeKind(kind) { + return kind >= 148 /* FirstNode */; + } + ts.isNodeKind = isNodeKind; + /** + * True if node is of some token syntax kind. + * For example, this is true for an IfKeyword but not for an IfStatement. + * Literals are considered tokens, except TemplateLiteral, but does include TemplateHead/Middle/Tail. + */ + function isToken(n) { + return n.kind >= 0 /* FirstToken */ && n.kind <= 147 /* LastToken */; + } + ts.isToken = isToken; + // Node Arrays + /* @internal */ + function isNodeArray(array) { + return array.hasOwnProperty("pos") && array.hasOwnProperty("end"); + } + ts.isNodeArray = isNodeArray; + // Literals + /* @internal */ + function isLiteralKind(kind) { + return 8 /* FirstLiteralToken */ <= kind && kind <= 14 /* LastLiteralToken */; + } + ts.isLiteralKind = isLiteralKind; + function isLiteralExpression(node) { + return isLiteralKind(node.kind); + } + ts.isLiteralExpression = isLiteralExpression; + // Pseudo-literals + /* @internal */ + function isTemplateLiteralKind(kind) { + return 14 /* FirstTemplateToken */ <= kind && kind <= 17 /* LastTemplateToken */; + } + ts.isTemplateLiteralKind = isTemplateLiteralKind; + function isTemplateLiteralToken(node) { + return isTemplateLiteralKind(node.kind); + } + ts.isTemplateLiteralToken = isTemplateLiteralToken; + function isTemplateMiddleOrTemplateTail(node) { + var kind = node.kind; + return kind === 16 /* TemplateMiddle */ + || kind === 17 /* TemplateTail */; + } + ts.isTemplateMiddleOrTemplateTail = isTemplateMiddleOrTemplateTail; + function isImportOrExportSpecifier(node) { + return ts.isImportSpecifier(node) || ts.isExportSpecifier(node); + } + ts.isImportOrExportSpecifier = isImportOrExportSpecifier; + function isStringTextContainingNode(node) { + return node.kind === 10 /* StringLiteral */ || isTemplateLiteralKind(node.kind); + } + ts.isStringTextContainingNode = isStringTextContainingNode; + // Identifiers + /* @internal */ + function isGeneratedIdentifier(node) { + return ts.isIdentifier(node) && (node.autoGenerateFlags & 7 /* KindMask */) > 0 /* None */; + } + ts.isGeneratedIdentifier = isGeneratedIdentifier; + // Keywords + /* @internal */ + function isModifierKind(token) { + switch (token) { + case 118 /* AbstractKeyword */: + case 121 /* AsyncKeyword */: + case 77 /* ConstKeyword */: + case 125 /* DeclareKeyword */: + case 80 /* DefaultKeyword */: + case 85 /* ExportKeyword */: + case 115 /* PublicKeyword */: + case 113 /* PrivateKeyword */: + case 114 /* ProtectedKeyword */: + case 133 /* ReadonlyKeyword */: + case 116 /* StaticKeyword */: + return true; + } + return false; + } + ts.isModifierKind = isModifierKind; + /* @internal */ + function isParameterPropertyModifier(kind) { + return !!(ts.modifierToFlag(kind) & 92 /* ParameterPropertyModifier */); + } + ts.isParameterPropertyModifier = isParameterPropertyModifier; + /* @internal */ + function isClassMemberModifier(idToken) { + return isParameterPropertyModifier(idToken) || idToken === 116 /* StaticKeyword */; + } + ts.isClassMemberModifier = isClassMemberModifier; + function isModifier(node) { + return isModifierKind(node.kind); + } + ts.isModifier = isModifier; + function isEntityName(node) { + var kind = node.kind; + return kind === 148 /* QualifiedName */ + || kind === 72 /* Identifier */; + } + ts.isEntityName = isEntityName; + function isPropertyName(node) { + var kind = node.kind; + return kind === 72 /* Identifier */ + || kind === 10 /* StringLiteral */ + || kind === 8 /* NumericLiteral */ + || kind === 149 /* ComputedPropertyName */; + } + ts.isPropertyName = isPropertyName; + function isBindingName(node) { + var kind = node.kind; + return kind === 72 /* Identifier */ + || kind === 184 /* ObjectBindingPattern */ + || kind === 185 /* ArrayBindingPattern */; + } + ts.isBindingName = isBindingName; + // Functions + function isFunctionLike(node) { + return node && isFunctionLikeKind(node.kind); + } + ts.isFunctionLike = isFunctionLike; + /* @internal */ + function isFunctionLikeDeclaration(node) { + return node && isFunctionLikeDeclarationKind(node.kind); + } + ts.isFunctionLikeDeclaration = isFunctionLikeDeclaration; + function isFunctionLikeDeclarationKind(kind) { + switch (kind) { + case 239 /* FunctionDeclaration */: + case 156 /* MethodDeclaration */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + return true; + default: + return false; + } + } + /* @internal */ + function isFunctionLikeKind(kind) { + switch (kind) { + case 155 /* MethodSignature */: + case 160 /* CallSignature */: + case 293 /* JSDocSignature */: + case 161 /* ConstructSignature */: + case 162 /* IndexSignature */: + case 165 /* FunctionType */: + case 289 /* JSDocFunctionType */: + case 166 /* ConstructorType */: + return true; + default: + return isFunctionLikeDeclarationKind(kind); + } + } + ts.isFunctionLikeKind = isFunctionLikeKind; + /* @internal */ + function isFunctionOrModuleBlock(node) { + return ts.isSourceFile(node) || ts.isModuleBlock(node) || ts.isBlock(node) && isFunctionLike(node.parent); + } + ts.isFunctionOrModuleBlock = isFunctionOrModuleBlock; + // Classes + function isClassElement(node) { + var kind = node.kind; + return kind === 157 /* Constructor */ + || kind === 154 /* PropertyDeclaration */ + || kind === 156 /* MethodDeclaration */ + || kind === 158 /* GetAccessor */ + || kind === 159 /* SetAccessor */ + || kind === 162 /* IndexSignature */ + || kind === 217 /* SemicolonClassElement */; + } + ts.isClassElement = isClassElement; + function isClassLike(node) { + return node && (node.kind === 240 /* ClassDeclaration */ || node.kind === 209 /* ClassExpression */); + } + ts.isClassLike = isClassLike; + function isAccessor(node) { + return node && (node.kind === 158 /* GetAccessor */ || node.kind === 159 /* SetAccessor */); + } + ts.isAccessor = isAccessor; + /* @internal */ + function isMethodOrAccessor(node) { + switch (node.kind) { + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + return true; + default: + return false; + } + } + ts.isMethodOrAccessor = isMethodOrAccessor; + // Type members + function isTypeElement(node) { + var kind = node.kind; + return kind === 161 /* ConstructSignature */ + || kind === 160 /* CallSignature */ + || kind === 153 /* PropertySignature */ + || kind === 155 /* MethodSignature */ + || kind === 162 /* IndexSignature */; + } + ts.isTypeElement = isTypeElement; + function isClassOrTypeElement(node) { + return isTypeElement(node) || isClassElement(node); + } + ts.isClassOrTypeElement = isClassOrTypeElement; + function isObjectLiteralElementLike(node) { + var kind = node.kind; + return kind === 275 /* PropertyAssignment */ + || kind === 276 /* ShorthandPropertyAssignment */ + || kind === 277 /* SpreadAssignment */ + || kind === 156 /* MethodDeclaration */ + || kind === 158 /* GetAccessor */ + || kind === 159 /* SetAccessor */; + } + ts.isObjectLiteralElementLike = isObjectLiteralElementLike; + // Type + /** + * Node test that determines whether a node is a valid type node. + * This differs from the `isPartOfTypeNode` function which determines whether a node is *part* + * of a TypeNode. + */ + function isTypeNode(node) { + return ts.isTypeNodeKind(node.kind); + } + ts.isTypeNode = isTypeNode; + function isFunctionOrConstructorTypeNode(node) { + switch (node.kind) { + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + return true; + } + return false; + } + ts.isFunctionOrConstructorTypeNode = isFunctionOrConstructorTypeNode; + // Binding patterns + /* @internal */ + function isBindingPattern(node) { + if (node) { + var kind = node.kind; + return kind === 185 /* ArrayBindingPattern */ + || kind === 184 /* ObjectBindingPattern */; + } + return false; + } + ts.isBindingPattern = isBindingPattern; + /* @internal */ + function isAssignmentPattern(node) { + var kind = node.kind; + return kind === 187 /* ArrayLiteralExpression */ + || kind === 188 /* ObjectLiteralExpression */; + } + ts.isAssignmentPattern = isAssignmentPattern; + /* @internal */ + function isArrayBindingElement(node) { + var kind = node.kind; + return kind === 186 /* BindingElement */ + || kind === 210 /* OmittedExpression */; + } + ts.isArrayBindingElement = isArrayBindingElement; + /** + * Determines whether the BindingOrAssignmentElement is a BindingElement-like declaration + */ + /* @internal */ + function isDeclarationBindingElement(bindingElement) { + switch (bindingElement.kind) { + case 237 /* VariableDeclaration */: + case 151 /* Parameter */: + case 186 /* BindingElement */: + return true; + } + return false; + } + ts.isDeclarationBindingElement = isDeclarationBindingElement; + /** + * Determines whether a node is a BindingOrAssignmentPattern + */ + /* @internal */ + function isBindingOrAssignmentPattern(node) { + return isObjectBindingOrAssignmentPattern(node) + || isArrayBindingOrAssignmentPattern(node); + } + ts.isBindingOrAssignmentPattern = isBindingOrAssignmentPattern; + /** + * Determines whether a node is an ObjectBindingOrAssignmentPattern + */ + /* @internal */ + function isObjectBindingOrAssignmentPattern(node) { + switch (node.kind) { + case 184 /* ObjectBindingPattern */: + case 188 /* ObjectLiteralExpression */: + return true; + } + return false; + } + ts.isObjectBindingOrAssignmentPattern = isObjectBindingOrAssignmentPattern; + /** + * Determines whether a node is an ArrayBindingOrAssignmentPattern + */ + /* @internal */ + function isArrayBindingOrAssignmentPattern(node) { + switch (node.kind) { + case 185 /* ArrayBindingPattern */: + case 187 /* ArrayLiteralExpression */: + return true; + } + return false; + } + ts.isArrayBindingOrAssignmentPattern = isArrayBindingOrAssignmentPattern; + /* @internal */ + function isPropertyAccessOrQualifiedNameOrImportTypeNode(node) { + var kind = node.kind; + return kind === 189 /* PropertyAccessExpression */ + || kind === 148 /* QualifiedName */ + || kind === 183 /* ImportType */; + } + ts.isPropertyAccessOrQualifiedNameOrImportTypeNode = isPropertyAccessOrQualifiedNameOrImportTypeNode; + // Expression + function isPropertyAccessOrQualifiedName(node) { + var kind = node.kind; + return kind === 189 /* PropertyAccessExpression */ + || kind === 148 /* QualifiedName */; + } + ts.isPropertyAccessOrQualifiedName = isPropertyAccessOrQualifiedName; + function isCallLikeExpression(node) { + switch (node.kind) { + case 262 /* JsxOpeningElement */: + case 261 /* JsxSelfClosingElement */: + case 191 /* CallExpression */: + case 192 /* NewExpression */: + case 193 /* TaggedTemplateExpression */: + case 152 /* Decorator */: + return true; + default: + return false; + } + } + ts.isCallLikeExpression = isCallLikeExpression; + function isCallOrNewExpression(node) { + return node.kind === 191 /* CallExpression */ || node.kind === 192 /* NewExpression */; + } + ts.isCallOrNewExpression = isCallOrNewExpression; + function isTemplateLiteral(node) { + var kind = node.kind; + return kind === 206 /* TemplateExpression */ + || kind === 14 /* NoSubstitutionTemplateLiteral */; + } + ts.isTemplateLiteral = isTemplateLiteral; + /* @internal */ + function isLeftHandSideExpression(node) { + return isLeftHandSideExpressionKind(ts.skipPartiallyEmittedExpressions(node).kind); + } + ts.isLeftHandSideExpression = isLeftHandSideExpression; + function isLeftHandSideExpressionKind(kind) { + switch (kind) { + case 189 /* PropertyAccessExpression */: + case 190 /* ElementAccessExpression */: + case 192 /* NewExpression */: + case 191 /* CallExpression */: + case 260 /* JsxElement */: + case 261 /* JsxSelfClosingElement */: + case 264 /* JsxFragment */: + case 193 /* TaggedTemplateExpression */: + case 187 /* ArrayLiteralExpression */: + case 195 /* ParenthesizedExpression */: + case 188 /* ObjectLiteralExpression */: + case 209 /* ClassExpression */: + case 196 /* FunctionExpression */: + case 72 /* Identifier */: + case 13 /* RegularExpressionLiteral */: + case 8 /* NumericLiteral */: + case 9 /* BigIntLiteral */: + case 10 /* StringLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: + case 206 /* TemplateExpression */: + case 87 /* FalseKeyword */: + case 96 /* NullKeyword */: + case 100 /* ThisKeyword */: + case 102 /* TrueKeyword */: + case 98 /* SuperKeyword */: + case 213 /* NonNullExpression */: + case 214 /* MetaProperty */: + case 92 /* ImportKeyword */: // technically this is only an Expression if it's in a CallExpression + return true; + default: + return false; + } + } + /* @internal */ + function isUnaryExpression(node) { + return isUnaryExpressionKind(ts.skipPartiallyEmittedExpressions(node).kind); + } + ts.isUnaryExpression = isUnaryExpression; + function isUnaryExpressionKind(kind) { + switch (kind) { + case 202 /* PrefixUnaryExpression */: + case 203 /* PostfixUnaryExpression */: + case 198 /* DeleteExpression */: + case 199 /* TypeOfExpression */: + case 200 /* VoidExpression */: + case 201 /* AwaitExpression */: + case 194 /* TypeAssertionExpression */: + return true; + default: + return isLeftHandSideExpressionKind(kind); + } + } + /* @internal */ + function isUnaryExpressionWithWrite(expr) { + switch (expr.kind) { + case 203 /* PostfixUnaryExpression */: + return true; + case 202 /* PrefixUnaryExpression */: + return expr.operator === 44 /* PlusPlusToken */ || + expr.operator === 45 /* MinusMinusToken */; + default: + return false; + } + } + ts.isUnaryExpressionWithWrite = isUnaryExpressionWithWrite; + /* @internal */ + /** + * Determines whether a node is an expression based only on its kind. + * Use `isExpressionNode` if not in transforms. + */ + function isExpression(node) { + return isExpressionKind(ts.skipPartiallyEmittedExpressions(node).kind); + } + ts.isExpression = isExpression; + function isExpressionKind(kind) { + switch (kind) { + case 205 /* ConditionalExpression */: + case 207 /* YieldExpression */: + case 197 /* ArrowFunction */: + case 204 /* BinaryExpression */: + case 208 /* SpreadElement */: + case 212 /* AsExpression */: + case 210 /* OmittedExpression */: + case 309 /* CommaListExpression */: + case 308 /* PartiallyEmittedExpression */: + return true; + default: + return isUnaryExpressionKind(kind); + } + } + function isAssertionExpression(node) { + var kind = node.kind; + return kind === 194 /* TypeAssertionExpression */ + || kind === 212 /* AsExpression */; + } + ts.isAssertionExpression = isAssertionExpression; + /* @internal */ + function isPartiallyEmittedExpression(node) { + return node.kind === 308 /* PartiallyEmittedExpression */; + } + ts.isPartiallyEmittedExpression = isPartiallyEmittedExpression; + /* @internal */ + function isNotEmittedStatement(node) { + return node.kind === 307 /* NotEmittedStatement */; + } + ts.isNotEmittedStatement = isNotEmittedStatement; + /* @internal */ + function isNotEmittedOrPartiallyEmittedNode(node) { + return isNotEmittedStatement(node) + || isPartiallyEmittedExpression(node); + } + ts.isNotEmittedOrPartiallyEmittedNode = isNotEmittedOrPartiallyEmittedNode; + function isIterationStatement(node, lookInLabeledStatements) { + switch (node.kind) { + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + case 223 /* DoStatement */: + case 224 /* WhileStatement */: + return true; + case 233 /* LabeledStatement */: + return lookInLabeledStatements && isIterationStatement(node.statement, lookInLabeledStatements); + } + return false; + } + ts.isIterationStatement = isIterationStatement; + /* @internal */ + function isForInOrOfStatement(node) { + return node.kind === 226 /* ForInStatement */ || node.kind === 227 /* ForOfStatement */; + } + ts.isForInOrOfStatement = isForInOrOfStatement; + // Element + /* @internal */ + function isConciseBody(node) { + return ts.isBlock(node) + || isExpression(node); + } + ts.isConciseBody = isConciseBody; + /* @internal */ + function isFunctionBody(node) { + return ts.isBlock(node); + } + ts.isFunctionBody = isFunctionBody; + /* @internal */ + function isForInitializer(node) { + return ts.isVariableDeclarationList(node) + || isExpression(node); + } + ts.isForInitializer = isForInitializer; + /* @internal */ + function isModuleBody(node) { + var kind = node.kind; + return kind === 245 /* ModuleBlock */ + || kind === 244 /* ModuleDeclaration */ + || kind === 72 /* Identifier */; + } + ts.isModuleBody = isModuleBody; + /* @internal */ + function isNamespaceBody(node) { + var kind = node.kind; + return kind === 245 /* ModuleBlock */ + || kind === 244 /* ModuleDeclaration */; + } + ts.isNamespaceBody = isNamespaceBody; + /* @internal */ + function isJSDocNamespaceBody(node) { + var kind = node.kind; + return kind === 72 /* Identifier */ + || kind === 244 /* ModuleDeclaration */; + } + ts.isJSDocNamespaceBody = isJSDocNamespaceBody; + /* @internal */ + function isNamedImportBindings(node) { + var kind = node.kind; + return kind === 252 /* NamedImports */ + || kind === 251 /* NamespaceImport */; + } + ts.isNamedImportBindings = isNamedImportBindings; + /* @internal */ + function isModuleOrEnumDeclaration(node) { + return node.kind === 244 /* ModuleDeclaration */ || node.kind === 243 /* EnumDeclaration */; + } + ts.isModuleOrEnumDeclaration = isModuleOrEnumDeclaration; + function isDeclarationKind(kind) { + return kind === 197 /* ArrowFunction */ + || kind === 186 /* BindingElement */ + || kind === 240 /* ClassDeclaration */ + || kind === 209 /* ClassExpression */ + || kind === 157 /* Constructor */ + || kind === 243 /* EnumDeclaration */ + || kind === 278 /* EnumMember */ + || kind === 257 /* ExportSpecifier */ + || kind === 239 /* FunctionDeclaration */ + || kind === 196 /* FunctionExpression */ + || kind === 158 /* GetAccessor */ + || kind === 250 /* ImportClause */ + || kind === 248 /* ImportEqualsDeclaration */ + || kind === 253 /* ImportSpecifier */ + || kind === 241 /* InterfaceDeclaration */ + || kind === 267 /* JsxAttribute */ + || kind === 156 /* MethodDeclaration */ + || kind === 155 /* MethodSignature */ + || kind === 244 /* ModuleDeclaration */ + || kind === 247 /* NamespaceExportDeclaration */ + || kind === 251 /* NamespaceImport */ + || kind === 151 /* Parameter */ + || kind === 275 /* PropertyAssignment */ + || kind === 154 /* PropertyDeclaration */ + || kind === 153 /* PropertySignature */ + || kind === 159 /* SetAccessor */ + || kind === 276 /* ShorthandPropertyAssignment */ + || kind === 242 /* TypeAliasDeclaration */ + || kind === 150 /* TypeParameter */ + || kind === 237 /* VariableDeclaration */ + || kind === 304 /* JSDocTypedefTag */ + || kind === 297 /* JSDocCallbackTag */ + || kind === 305 /* JSDocPropertyTag */; + } + function isDeclarationStatementKind(kind) { + return kind === 239 /* FunctionDeclaration */ + || kind === 258 /* MissingDeclaration */ + || kind === 240 /* ClassDeclaration */ + || kind === 241 /* InterfaceDeclaration */ + || kind === 242 /* TypeAliasDeclaration */ + || kind === 243 /* EnumDeclaration */ + || kind === 244 /* ModuleDeclaration */ + || kind === 249 /* ImportDeclaration */ + || kind === 248 /* ImportEqualsDeclaration */ + || kind === 255 /* ExportDeclaration */ + || kind === 254 /* ExportAssignment */ + || kind === 247 /* NamespaceExportDeclaration */; + } + function isStatementKindButNotDeclarationKind(kind) { + return kind === 229 /* BreakStatement */ + || kind === 228 /* ContinueStatement */ + || kind === 236 /* DebuggerStatement */ + || kind === 223 /* DoStatement */ + || kind === 221 /* ExpressionStatement */ + || kind === 220 /* EmptyStatement */ + || kind === 226 /* ForInStatement */ + || kind === 227 /* ForOfStatement */ + || kind === 225 /* ForStatement */ + || kind === 222 /* IfStatement */ + || kind === 233 /* LabeledStatement */ + || kind === 230 /* ReturnStatement */ + || kind === 232 /* SwitchStatement */ + || kind === 234 /* ThrowStatement */ + || kind === 235 /* TryStatement */ + || kind === 219 /* VariableStatement */ + || kind === 224 /* WhileStatement */ + || kind === 231 /* WithStatement */ + || kind === 307 /* NotEmittedStatement */ + || kind === 311 /* EndOfDeclarationMarker */ + || kind === 310 /* MergeDeclarationMarker */; + } + /* @internal */ + function isDeclaration(node) { + if (node.kind === 150 /* TypeParameter */) { + return node.parent.kind !== 303 /* JSDocTemplateTag */ || ts.isInJSFile(node); + } + return isDeclarationKind(node.kind); + } + ts.isDeclaration = isDeclaration; + /* @internal */ + function isDeclarationStatement(node) { + return isDeclarationStatementKind(node.kind); + } + ts.isDeclarationStatement = isDeclarationStatement; + /** + * Determines whether the node is a statement that is not also a declaration + */ + /* @internal */ + function isStatementButNotDeclaration(node) { + return isStatementKindButNotDeclarationKind(node.kind); + } + ts.isStatementButNotDeclaration = isStatementButNotDeclaration; + /* @internal */ + function isStatement(node) { + var kind = node.kind; + return isStatementKindButNotDeclarationKind(kind) + || isDeclarationStatementKind(kind) + || isBlockStatement(node); + } + ts.isStatement = isStatement; + function isBlockStatement(node) { + if (node.kind !== 218 /* Block */) + return false; + if (node.parent !== undefined) { + if (node.parent.kind === 235 /* TryStatement */ || node.parent.kind === 274 /* CatchClause */) { + return false; + } + } + return !ts.isFunctionBlock(node); + } + // Module references + /* @internal */ + function isModuleReference(node) { + var kind = node.kind; + return kind === 259 /* ExternalModuleReference */ + || kind === 148 /* QualifiedName */ + || kind === 72 /* Identifier */; + } + ts.isModuleReference = isModuleReference; + // JSX + /* @internal */ + function isJsxTagNameExpression(node) { + var kind = node.kind; + return kind === 100 /* ThisKeyword */ + || kind === 72 /* Identifier */ + || kind === 189 /* PropertyAccessExpression */; + } + ts.isJsxTagNameExpression = isJsxTagNameExpression; + /* @internal */ + function isJsxChild(node) { + var kind = node.kind; + return kind === 260 /* JsxElement */ + || kind === 270 /* JsxExpression */ + || kind === 261 /* JsxSelfClosingElement */ + || kind === 11 /* JsxText */ + || kind === 264 /* JsxFragment */; + } + ts.isJsxChild = isJsxChild; + /* @internal */ + function isJsxAttributeLike(node) { + var kind = node.kind; + return kind === 267 /* JsxAttribute */ + || kind === 269 /* JsxSpreadAttribute */; + } + ts.isJsxAttributeLike = isJsxAttributeLike; + /* @internal */ + function isStringLiteralOrJsxExpression(node) { + var kind = node.kind; + return kind === 10 /* StringLiteral */ + || kind === 270 /* JsxExpression */; + } + ts.isStringLiteralOrJsxExpression = isStringLiteralOrJsxExpression; + function isJsxOpeningLikeElement(node) { + var kind = node.kind; + return kind === 262 /* JsxOpeningElement */ + || kind === 261 /* JsxSelfClosingElement */; + } + ts.isJsxOpeningLikeElement = isJsxOpeningLikeElement; + // Clauses + function isCaseOrDefaultClause(node) { + var kind = node.kind; + return kind === 271 /* CaseClause */ + || kind === 272 /* DefaultClause */; + } + ts.isCaseOrDefaultClause = isCaseOrDefaultClause; + // JSDoc + /** True if node is of some JSDoc syntax kind. */ + /* @internal */ + function isJSDocNode(node) { + return node.kind >= 283 /* FirstJSDocNode */ && node.kind <= 305 /* LastJSDocNode */; + } + ts.isJSDocNode = isJSDocNode; + /** True if node is of a kind that may contain comment text. */ + function isJSDocCommentContainingNode(node) { + return node.kind === 291 /* JSDocComment */ || isJSDocTag(node) || ts.isJSDocTypeLiteral(node) || ts.isJSDocSignature(node); + } + ts.isJSDocCommentContainingNode = isJSDocCommentContainingNode; + // TODO: determine what this does before making it public. + /* @internal */ + function isJSDocTag(node) { + return node.kind >= 294 /* FirstJSDocTagNode */ && node.kind <= 305 /* LastJSDocTagNode */; + } + ts.isJSDocTag = isJSDocTag; + function isSetAccessor(node) { + return node.kind === 159 /* SetAccessor */; + } + ts.isSetAccessor = isSetAccessor; + function isGetAccessor(node) { + return node.kind === 158 /* GetAccessor */; + } + ts.isGetAccessor = isGetAccessor; + /** True if has jsdoc nodes attached to it. */ + /* @internal */ + // TODO: GH#19856 Would like to return `node is Node & { jsDoc: JSDoc[] }` but it causes long compile times + function hasJSDocNodes(node) { + var jsDoc = node.jsDoc; + return !!jsDoc && jsDoc.length > 0; + } + ts.hasJSDocNodes = hasJSDocNodes; + /** True if has type node attached to it. */ + /* @internal */ + function hasType(node) { + return !!node.type; + } + ts.hasType = hasType; + /** True if has initializer node attached to it. */ + /* @internal */ + function hasInitializer(node) { + return !!node.initializer; + } + ts.hasInitializer = hasInitializer; + /** True if has initializer node attached to it. */ + /* @internal */ + function hasOnlyExpressionInitializer(node) { + return hasInitializer(node) && !ts.isForStatement(node) && !ts.isForInStatement(node) && !ts.isForOfStatement(node) && !ts.isJsxAttribute(node); + } + ts.hasOnlyExpressionInitializer = hasOnlyExpressionInitializer; + function isObjectLiteralElement(node) { + return node.kind === 267 /* JsxAttribute */ || node.kind === 269 /* JsxSpreadAttribute */ || isObjectLiteralElementLike(node); + } + ts.isObjectLiteralElement = isObjectLiteralElement; + /* @internal */ + function isTypeReferenceType(node) { + return node.kind === 164 /* TypeReference */ || node.kind === 211 /* ExpressionWithTypeArguments */; + } + ts.isTypeReferenceType = isTypeReferenceType; + var MAX_SMI_X86 = 1073741823; + /* @internal */ + function guessIndentation(lines) { + var indentation = MAX_SMI_X86; + for (var _i = 0, lines_1 = lines; _i < lines_1.length; _i++) { + var line = lines_1[_i]; + if (!line.length) { + continue; + } + var i = 0; + for (; i < line.length && i < indentation; i++) { + if (!ts.isWhiteSpaceLike(line.charCodeAt(i))) { + break; + } + } + if (i < indentation) { + indentation = i; + } + if (indentation === 0) { + return 0; + } + } + return indentation === MAX_SMI_X86 ? undefined : indentation; + } + ts.guessIndentation = guessIndentation; + function isStringLiteralLike(node) { + return node.kind === 10 /* StringLiteral */ || node.kind === 14 /* NoSubstitutionTemplateLiteral */; + } + ts.isStringLiteralLike = isStringLiteralLike; +})(ts || (ts = {})); +/* @internal */ +(function (ts) { + function isNamedImportsOrExports(node) { + return node.kind === 252 /* NamedImports */ || node.kind === 256 /* NamedExports */; + } + ts.isNamedImportsOrExports = isNamedImportsOrExports; + function Symbol(flags, name) { + this.flags = flags; + this.escapedName = name; + this.declarations = undefined; + this.valueDeclaration = undefined; + this.id = undefined; + this.mergeId = undefined; + this.parent = undefined; + } + function Type(checker, flags) { + this.flags = flags; + if (ts.Debug.isDebugging) { + this.checker = checker; + } + } + function Signature() { } // tslint:disable-line no-empty + function Node(kind, pos, end) { + this.pos = pos; + this.end = end; + this.kind = kind; + this.id = 0; + this.flags = 0 /* None */; + this.modifierFlagsCache = 0 /* None */; + this.transformFlags = 0 /* None */; + this.parent = undefined; + this.original = undefined; + } + function SourceMapSource(fileName, text, skipTrivia) { + this.fileName = fileName; + this.text = text; + this.skipTrivia = skipTrivia || (function (pos) { return pos; }); + } + ts.objectAllocator = { + getNodeConstructor: function () { return Node; }, + getTokenConstructor: function () { return Node; }, + getIdentifierConstructor: function () { return Node; }, + getSourceFileConstructor: function () { return Node; }, + getSymbolConstructor: function () { return Symbol; }, + getTypeConstructor: function () { return Type; }, + getSignatureConstructor: function () { return Signature; }, + getSourceMapSourceConstructor: function () { return SourceMapSource; }, + }; + function formatStringFromArgs(text, args, baseIndex) { + if (baseIndex === void 0) { baseIndex = 0; } + return text.replace(/{(\d+)}/g, function (_match, index) { return "" + ts.Debug.assertDefined(args[+index + baseIndex]); }); + } + ts.formatStringFromArgs = formatStringFromArgs; + function getLocaleSpecificMessage(message) { + return ts.localizedDiagnosticMessages && ts.localizedDiagnosticMessages[message.key] || message.message; + } + ts.getLocaleSpecificMessage = getLocaleSpecificMessage; + function createFileDiagnostic(file, start, length, message) { + ts.Debug.assertGreaterThanOrEqual(start, 0); + ts.Debug.assertGreaterThanOrEqual(length, 0); + if (file) { + ts.Debug.assertLessThanOrEqual(start, file.text.length); + ts.Debug.assertLessThanOrEqual(start + length, file.text.length); + } + var text = getLocaleSpecificMessage(message); + if (arguments.length > 4) { + text = formatStringFromArgs(text, arguments, 4); + } + return { + file: file, + start: start, + length: length, + messageText: text, + category: message.category, + code: message.code, + reportsUnnecessary: message.reportsUnnecessary, + }; + } + ts.createFileDiagnostic = createFileDiagnostic; + function formatMessage(_dummy, message) { + var text = getLocaleSpecificMessage(message); + if (arguments.length > 2) { + text = formatStringFromArgs(text, arguments, 2); + } + return text; + } + ts.formatMessage = formatMessage; + function createCompilerDiagnostic(message) { + var text = getLocaleSpecificMessage(message); + if (arguments.length > 1) { + text = formatStringFromArgs(text, arguments, 1); + } + return { + file: undefined, + start: undefined, + length: undefined, + messageText: text, + category: message.category, + code: message.code, + reportsUnnecessary: message.reportsUnnecessary, + }; + } + ts.createCompilerDiagnostic = createCompilerDiagnostic; + function createCompilerDiagnosticFromMessageChain(chain) { + return { + file: undefined, + start: undefined, + length: undefined, + code: chain.code, + category: chain.category, + messageText: chain.next ? chain : chain.messageText, + }; + } + ts.createCompilerDiagnosticFromMessageChain = createCompilerDiagnosticFromMessageChain; + function chainDiagnosticMessages(details, message) { + var text = getLocaleSpecificMessage(message); + if (arguments.length > 2) { + text = formatStringFromArgs(text, arguments, 2); + } + return { + messageText: text, + category: message.category, + code: message.code, + next: details + }; + } + ts.chainDiagnosticMessages = chainDiagnosticMessages; + function concatenateDiagnosticMessageChains(headChain, tailChain) { + var lastChain = headChain; + while (lastChain.next) { + lastChain = lastChain.next; + } + lastChain.next = tailChain; + return headChain; + } + ts.concatenateDiagnosticMessageChains = concatenateDiagnosticMessageChains; + function getDiagnosticFilePath(diagnostic) { + return diagnostic.file ? diagnostic.file.path : undefined; + } + function compareDiagnostics(d1, d2) { + return compareDiagnosticsSkipRelatedInformation(d1, d2) || + compareRelatedInformation(d1, d2) || + 0 /* EqualTo */; + } + ts.compareDiagnostics = compareDiagnostics; + function compareDiagnosticsSkipRelatedInformation(d1, d2) { + return ts.compareStringsCaseSensitive(getDiagnosticFilePath(d1), getDiagnosticFilePath(d2)) || + ts.compareValues(d1.start, d2.start) || + ts.compareValues(d1.length, d2.length) || + ts.compareValues(d1.code, d2.code) || + compareMessageText(d1.messageText, d2.messageText) || + 0 /* EqualTo */; + } + ts.compareDiagnosticsSkipRelatedInformation = compareDiagnosticsSkipRelatedInformation; + function compareRelatedInformation(d1, d2) { + if (!d1.relatedInformation && !d2.relatedInformation) { + return 0 /* EqualTo */; + } + if (d1.relatedInformation && d2.relatedInformation) { + return ts.compareValues(d1.relatedInformation.length, d2.relatedInformation.length) || ts.forEach(d1.relatedInformation, function (d1i, index) { + var d2i = d2.relatedInformation[index]; + return compareDiagnostics(d1i, d2i); // EqualTo is 0, so falsy, and will cause the next item to be compared + }) || 0 /* EqualTo */; + } + return d1.relatedInformation ? -1 /* LessThan */ : 1 /* GreaterThan */; + } + function compareMessageText(t1, t2) { + var text1 = t1; + var text2 = t2; + while (text1 && text2) { + // We still have both chains. + var string1 = ts.isString(text1) ? text1 : text1.messageText; + var string2 = ts.isString(text2) ? text2 : text2.messageText; + var res = ts.compareStringsCaseSensitive(string1, string2); + if (res) { + return res; + } + text1 = ts.isString(text1) ? undefined : text1.next; + text2 = ts.isString(text2) ? undefined : text2.next; + } + if (!text1 && !text2) { + // if the chains are done, then these messages are the same. + return 0 /* EqualTo */; + } + // We still have one chain remaining. The shorter chain should come first. + return text1 ? 1 /* GreaterThan */ : -1 /* LessThan */; + } + function getEmitScriptTarget(compilerOptions) { + return compilerOptions.target || 0 /* ES3 */; + } + ts.getEmitScriptTarget = getEmitScriptTarget; + function getEmitModuleKind(compilerOptions) { + return typeof compilerOptions.module === "number" ? + compilerOptions.module : + getEmitScriptTarget(compilerOptions) >= 2 /* ES2015 */ ? ts.ModuleKind.ES2015 : ts.ModuleKind.CommonJS; + } + ts.getEmitModuleKind = getEmitModuleKind; + function getEmitModuleResolutionKind(compilerOptions) { + var moduleResolution = compilerOptions.moduleResolution; + if (moduleResolution === undefined) { + moduleResolution = getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS ? ts.ModuleResolutionKind.NodeJs : ts.ModuleResolutionKind.Classic; + } + return moduleResolution; + } + ts.getEmitModuleResolutionKind = getEmitModuleResolutionKind; + function hasJsonModuleEmitEnabled(options) { + switch (getEmitModuleKind(options)) { + case ts.ModuleKind.CommonJS: + case ts.ModuleKind.AMD: + case ts.ModuleKind.ES2015: + case ts.ModuleKind.ESNext: + return true; + default: + return false; + } + } + ts.hasJsonModuleEmitEnabled = hasJsonModuleEmitEnabled; + function unreachableCodeIsError(options) { + return options.allowUnreachableCode === false; + } + ts.unreachableCodeIsError = unreachableCodeIsError; + function unusedLabelIsError(options) { + return options.allowUnusedLabels === false; + } + ts.unusedLabelIsError = unusedLabelIsError; + function getAreDeclarationMapsEnabled(options) { + return !!(getEmitDeclarations(options) && options.declarationMap); + } + ts.getAreDeclarationMapsEnabled = getAreDeclarationMapsEnabled; + function getAllowSyntheticDefaultImports(compilerOptions) { + var moduleKind = getEmitModuleKind(compilerOptions); + return compilerOptions.allowSyntheticDefaultImports !== undefined + ? compilerOptions.allowSyntheticDefaultImports + : compilerOptions.esModuleInterop || + moduleKind === ts.ModuleKind.System; + } + ts.getAllowSyntheticDefaultImports = getAllowSyntheticDefaultImports; + function getEmitDeclarations(compilerOptions) { + return !!(compilerOptions.declaration || compilerOptions.composite); + } + ts.getEmitDeclarations = getEmitDeclarations; + function getStrictOptionValue(compilerOptions, flag) { + return compilerOptions[flag] === undefined ? !!compilerOptions.strict : !!compilerOptions[flag]; + } + ts.getStrictOptionValue = getStrictOptionValue; + function compilerOptionsAffectSemanticDiagnostics(newOptions, oldOptions) { + return oldOptions !== newOptions && + ts.semanticDiagnosticsOptionDeclarations.some(function (option) { return !ts.isJsonEqual(getCompilerOptionValue(oldOptions, option), getCompilerOptionValue(newOptions, option)); }); + } + ts.compilerOptionsAffectSemanticDiagnostics = compilerOptionsAffectSemanticDiagnostics; + function getCompilerOptionValue(options, option) { + return option.strictFlag ? getStrictOptionValue(options, option.name) : options[option.name]; + } + ts.getCompilerOptionValue = getCompilerOptionValue; + function hasZeroOrOneAsteriskCharacter(str) { + var seenAsterisk = false; + for (var i = 0; i < str.length; i++) { + if (str.charCodeAt(i) === 42 /* asterisk */) { + if (!seenAsterisk) { + seenAsterisk = true; + } + else { + // have already seen asterisk + return false; + } + } + } + return true; + } + ts.hasZeroOrOneAsteriskCharacter = hasZeroOrOneAsteriskCharacter; + /** + * Internally, we represent paths as strings with '/' as the directory separator. + * When we make system calls (eg: LanguageServiceHost.getDirectory()), + * we expect the host to correctly handle paths in our specified format. + */ + ts.directorySeparator = "/"; + var altDirectorySeparator = "\\"; + var urlSchemeSeparator = "://"; + var backslashRegExp = /\\/g; + /** + * Normalize path separators. + */ + function normalizeSlashes(path) { + return path.replace(backslashRegExp, ts.directorySeparator); + } + ts.normalizeSlashes = normalizeSlashes; + function isVolumeCharacter(charCode) { + return (charCode >= 97 /* a */ && charCode <= 122 /* z */) || + (charCode >= 65 /* A */ && charCode <= 90 /* Z */); + } + function getFileUrlVolumeSeparatorEnd(url, start) { + var ch0 = url.charCodeAt(start); + if (ch0 === 58 /* colon */) + return start + 1; + if (ch0 === 37 /* percent */ && url.charCodeAt(start + 1) === 51 /* _3 */) { + var ch2 = url.charCodeAt(start + 2); + if (ch2 === 97 /* a */ || ch2 === 65 /* A */) + return start + 3; + } + return -1; + } + /** + * Returns length of the root part of a path or URL (i.e. length of "/", "x:/", "//server/share/, file:///user/files"). + * If the root is part of a URL, the twos-complement of the root length is returned. + */ + function getEncodedRootLength(path) { + if (!path) + return 0; + var ch0 = path.charCodeAt(0); + // POSIX or UNC + if (ch0 === 47 /* slash */ || ch0 === 92 /* backslash */) { + if (path.charCodeAt(1) !== ch0) + return 1; // POSIX: "/" (or non-normalized "\") + var p1 = path.indexOf(ch0 === 47 /* slash */ ? ts.directorySeparator : altDirectorySeparator, 2); + if (p1 < 0) + return path.length; // UNC: "//server" or "\\server" + return p1 + 1; // UNC: "//server/" or "\\server\" + } + // DOS + if (isVolumeCharacter(ch0) && path.charCodeAt(1) === 58 /* colon */) { + var ch2 = path.charCodeAt(2); + if (ch2 === 47 /* slash */ || ch2 === 92 /* backslash */) + return 3; // DOS: "c:/" or "c:\" + if (path.length === 2) + return 2; // DOS: "c:" (but not "c:d") + } + // URL + var schemeEnd = path.indexOf(urlSchemeSeparator); + if (schemeEnd !== -1) { + var authorityStart = schemeEnd + urlSchemeSeparator.length; + var authorityEnd = path.indexOf(ts.directorySeparator, authorityStart); + if (authorityEnd !== -1) { // URL: "file:///", "file://server/", "file://server/path" + // For local "file" URLs, include the leading DOS volume (if present). + // Per https://www.ietf.org/rfc/rfc1738.txt, a host of "" or "localhost" is a + // special case interpreted as "the machine from which the URL is being interpreted". + var scheme = path.slice(0, schemeEnd); + var authority = path.slice(authorityStart, authorityEnd); + if (scheme === "file" && (authority === "" || authority === "localhost") && + isVolumeCharacter(path.charCodeAt(authorityEnd + 1))) { + var volumeSeparatorEnd = getFileUrlVolumeSeparatorEnd(path, authorityEnd + 2); + if (volumeSeparatorEnd !== -1) { + if (path.charCodeAt(volumeSeparatorEnd) === 47 /* slash */) { + // URL: "file:///c:/", "file://localhost/c:/", "file:///c%3a/", "file://localhost/c%3a/" + return ~(volumeSeparatorEnd + 1); + } + if (volumeSeparatorEnd === path.length) { + // URL: "file:///c:", "file://localhost/c:", "file:///c$3a", "file://localhost/c%3a" + // but not "file:///c:d" or "file:///c%3ad" + return ~volumeSeparatorEnd; + } + } + } + return ~(authorityEnd + 1); // URL: "file://server/", "http://server/" + } + return ~path.length; // URL: "file://server", "http://server" + } + // relative + return 0; + } + /** + * Returns length of the root part of a path or URL (i.e. length of "/", "x:/", "//server/share/, file:///user/files"). + * + * For example: + * ```ts + * getRootLength("a") === 0 // "" + * getRootLength("/") === 1 // "/" + * getRootLength("c:") === 2 // "c:" + * getRootLength("c:d") === 0 // "" + * getRootLength("c:/") === 3 // "c:/" + * getRootLength("c:\\") === 3 // "c:\\" + * getRootLength("//server") === 7 // "//server" + * getRootLength("//server/share") === 8 // "//server/" + * getRootLength("\\\\server") === 7 // "\\\\server" + * getRootLength("\\\\server\\share") === 8 // "\\\\server\\" + * getRootLength("file:///path") === 8 // "file:///" + * getRootLength("file:///c:") === 10 // "file:///c:" + * getRootLength("file:///c:d") === 8 // "file:///" + * getRootLength("file:///c:/path") === 11 // "file:///c:/" + * getRootLength("file://server") === 13 // "file://server" + * getRootLength("file://server/path") === 14 // "file://server/" + * getRootLength("http://server") === 13 // "http://server" + * getRootLength("http://server/path") === 14 // "http://server/" + * ``` + */ + function getRootLength(path) { + var rootLength = getEncodedRootLength(path); + return rootLength < 0 ? ~rootLength : rootLength; + } + ts.getRootLength = getRootLength; + // TODO(rbuckton): replace references with `resolvePath` + function normalizePath(path) { + return ts.resolvePath(path); + } + ts.normalizePath = normalizePath; + function normalizePathAndParts(path) { + path = normalizeSlashes(path); + var _a = reducePathComponents(getPathComponents(path)), root = _a[0], parts = _a.slice(1); + if (parts.length) { + var joinedParts = root + parts.join(ts.directorySeparator); + return { path: ts.hasTrailingDirectorySeparator(path) ? ts.ensureTrailingDirectorySeparator(joinedParts) : joinedParts, parts: parts }; + } + else { + return { path: root, parts: parts }; + } + } + ts.normalizePathAndParts = normalizePathAndParts; + function getDirectoryPath(path) { + path = normalizeSlashes(path); + // If the path provided is itself the root, then return it. + var rootLength = getRootLength(path); + if (rootLength === path.length) + return path; + // return the leading portion of the path up to the last (non-terminal) directory separator + // but not including any trailing directory separator. + path = ts.removeTrailingDirectorySeparator(path); + return path.slice(0, Math.max(rootLength, path.lastIndexOf(ts.directorySeparator))); + } + ts.getDirectoryPath = getDirectoryPath; + function startsWithDirectory(fileName, directoryName, getCanonicalFileName) { + var canonicalFileName = getCanonicalFileName(fileName); + var canonicalDirectoryName = getCanonicalFileName(directoryName); + return ts.startsWith(canonicalFileName, canonicalDirectoryName + "/") || ts.startsWith(canonicalFileName, canonicalDirectoryName + "\\"); + } + ts.startsWithDirectory = startsWithDirectory; + function isUrl(path) { + return getEncodedRootLength(path) < 0; + } + ts.isUrl = isUrl; + function pathIsRelative(path) { + return /^\.\.?($|[\\/])/.test(path); + } + ts.pathIsRelative = pathIsRelative; + /** + * Determines whether a path is an absolute path (e.g. starts with `/`, or a dos path + * like `c:`, `c:\` or `c:/`). + */ + function isRootedDiskPath(path) { + return getEncodedRootLength(path) > 0; + } + ts.isRootedDiskPath = isRootedDiskPath; + /** + * Determines whether a path consists only of a path root. + */ + function isDiskPathRoot(path) { + var rootLength = getEncodedRootLength(path); + return rootLength > 0 && rootLength === path.length; + } + ts.isDiskPathRoot = isDiskPathRoot; + function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) { + return !isRootedDiskPath(absoluteOrRelativePath) + ? absoluteOrRelativePath + : ts.getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); + } + ts.convertToRelativePath = convertToRelativePath; + function pathComponents(path, rootLength) { + var root = path.substring(0, rootLength); + var rest = path.substring(rootLength).split(ts.directorySeparator); + if (rest.length && !ts.lastOrUndefined(rest)) + rest.pop(); + return [root].concat(rest); + } + /** + * Parse a path into an array containing a root component (at index 0) and zero or more path + * components (at indices > 0). The result is not normalized. + * If the path is relative, the root component is `""`. + * If the path is absolute, the root component includes the first path separator (`/`). + */ + function getPathComponents(path, currentDirectory) { + if (currentDirectory === void 0) { currentDirectory = ""; } + path = ts.combinePaths(currentDirectory, path); + var rootLength = getRootLength(path); + return pathComponents(path, rootLength); + } + ts.getPathComponents = getPathComponents; + /** + * Reduce an array of path components to a more simplified path by navigating any + * `"."` or `".."` entries in the path. + */ + function reducePathComponents(components) { + if (!ts.some(components)) + return []; + var reduced = [components[0]]; + for (var i = 1; i < components.length; i++) { + var component = components[i]; + if (!component) + continue; + if (component === ".") + continue; + if (component === "..") { + if (reduced.length > 1) { + if (reduced[reduced.length - 1] !== "..") { + reduced.pop(); + continue; + } + } + else if (reduced[0]) + continue; + } + reduced.push(component); + } + return reduced; + } + ts.reducePathComponents = reducePathComponents; + /** + * Parse a path into an array containing a root component (at index 0) and zero or more path + * components (at indices > 0). The result is normalized. + * If the path is relative, the root component is `""`. + * If the path is absolute, the root component includes the first path separator (`/`). + */ + function getNormalizedPathComponents(path, currentDirectory) { + return reducePathComponents(getPathComponents(path, currentDirectory)); + } + ts.getNormalizedPathComponents = getNormalizedPathComponents; + function getNormalizedAbsolutePath(fileName, currentDirectory) { + return getPathFromPathComponents(getNormalizedPathComponents(fileName, currentDirectory)); + } + ts.getNormalizedAbsolutePath = getNormalizedAbsolutePath; + /** + * Formats a parsed path consisting of a root component (at index 0) and zero or more path + * segments (at indices > 0). + */ + function getPathFromPathComponents(pathComponents) { + if (pathComponents.length === 0) + return ""; + var root = pathComponents[0] && ts.ensureTrailingDirectorySeparator(pathComponents[0]); + return root + pathComponents.slice(1).join(ts.directorySeparator); + } + ts.getPathFromPathComponents = getPathFromPathComponents; +})(ts || (ts = {})); +/* @internal */ +(function (ts) { + function getPathComponentsRelativeTo(from, to, stringEqualityComparer, getCanonicalFileName) { + var fromComponents = ts.reducePathComponents(ts.getPathComponents(from)); + var toComponents = ts.reducePathComponents(ts.getPathComponents(to)); + var start; + for (start = 0; start < fromComponents.length && start < toComponents.length; start++) { + var fromComponent = getCanonicalFileName(fromComponents[start]); + var toComponent = getCanonicalFileName(toComponents[start]); + var comparer = start === 0 ? ts.equateStringsCaseInsensitive : stringEqualityComparer; + if (!comparer(fromComponent, toComponent)) + break; + } + if (start === 0) { + return toComponents; + } + var components = toComponents.slice(start); + var relative = []; + for (; start < fromComponents.length; start++) { + relative.push(".."); + } + return [""].concat(relative, components); + } + ts.getPathComponentsRelativeTo = getPathComponentsRelativeTo; + function getRelativePathFromFile(from, to, getCanonicalFileName) { + return ensurePathIsNonModuleName(getRelativePathFromDirectory(ts.getDirectoryPath(from), to, getCanonicalFileName)); + } + ts.getRelativePathFromFile = getRelativePathFromFile; + function getRelativePathFromDirectory(fromDirectory, to, getCanonicalFileNameOrIgnoreCase) { + Debug.assert((ts.getRootLength(fromDirectory) > 0) === (ts.getRootLength(to) > 0), "Paths must either both be absolute or both be relative"); + var getCanonicalFileName = typeof getCanonicalFileNameOrIgnoreCase === "function" ? getCanonicalFileNameOrIgnoreCase : ts.identity; + var ignoreCase = typeof getCanonicalFileNameOrIgnoreCase === "boolean" ? getCanonicalFileNameOrIgnoreCase : false; + var pathComponents = getPathComponentsRelativeTo(fromDirectory, to, ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive, getCanonicalFileName); + return ts.getPathFromPathComponents(pathComponents); + } + ts.getRelativePathFromDirectory = getRelativePathFromDirectory; + function getRelativePathToDirectoryOrUrl(directoryPathOrUrl, relativeOrAbsolutePath, currentDirectory, getCanonicalFileName, isAbsolutePathAnUrl) { + var pathComponents = getPathComponentsRelativeTo(resolvePath(currentDirectory, directoryPathOrUrl), resolvePath(currentDirectory, relativeOrAbsolutePath), ts.equateStringsCaseSensitive, getCanonicalFileName); + var firstComponent = pathComponents[0]; + if (isAbsolutePathAnUrl && ts.isRootedDiskPath(firstComponent)) { + var prefix = firstComponent.charAt(0) === ts.directorySeparator ? "file://" : "file:///"; + pathComponents[0] = prefix + firstComponent; + } + return ts.getPathFromPathComponents(pathComponents); + } + ts.getRelativePathToDirectoryOrUrl = getRelativePathToDirectoryOrUrl; + /** + * Ensures a path is either absolute (prefixed with `/` or `c:`) or dot-relative (prefixed + * with `./` or `../`) so as not to be confused with an unprefixed module name. + */ + function ensurePathIsNonModuleName(path) { + return ts.getRootLength(path) === 0 && !ts.pathIsRelative(path) ? "./" + path : path; + } + ts.ensurePathIsNonModuleName = ensurePathIsNonModuleName; + function getBaseFileName(path, extensions, ignoreCase) { + path = ts.normalizeSlashes(path); + // if the path provided is itself the root, then it has not file name. + var rootLength = ts.getRootLength(path); + if (rootLength === path.length) + return ""; + // return the trailing portion of the path starting after the last (non-terminal) directory + // separator but not including any trailing directory separator. + path = removeTrailingDirectorySeparator(path); + var name = path.slice(Math.max(ts.getRootLength(path), path.lastIndexOf(ts.directorySeparator) + 1)); + var extension = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(name, extensions, ignoreCase) : undefined; + return extension ? name.slice(0, name.length - extension.length) : name; + } + ts.getBaseFileName = getBaseFileName; + /** + * Combines paths. If a path is absolute, it replaces any previous path. + */ + function combinePaths(path) { + var paths = []; + for (var _i = 1; _i < arguments.length; _i++) { + paths[_i - 1] = arguments[_i]; + } + if (path) + path = ts.normalizeSlashes(path); + for (var _a = 0, paths_1 = paths; _a < paths_1.length; _a++) { + var relativePath = paths_1[_a]; + if (!relativePath) + continue; + relativePath = ts.normalizeSlashes(relativePath); + if (!path || ts.getRootLength(relativePath) !== 0) { + path = relativePath; + } + else { + path = ensureTrailingDirectorySeparator(path) + relativePath; + } + } + return path; + } + ts.combinePaths = combinePaths; + /** + * Combines and resolves paths. If a path is absolute, it replaces any previous path. Any + * `.` and `..` path components are resolved. + */ + function resolvePath(path) { + var paths = []; + for (var _i = 1; _i < arguments.length; _i++) { + paths[_i - 1] = arguments[_i]; + } + var combined = ts.some(paths) ? combinePaths.apply(void 0, [path].concat(paths)) : ts.normalizeSlashes(path); + var normalized = ts.getPathFromPathComponents(ts.reducePathComponents(ts.getPathComponents(combined))); + return normalized && hasTrailingDirectorySeparator(combined) ? ensureTrailingDirectorySeparator(normalized) : normalized; + } + ts.resolvePath = resolvePath; + /** + * Determines whether a path has a trailing separator (`/` or `\\`). + */ + function hasTrailingDirectorySeparator(path) { + if (path.length === 0) + return false; + var ch = path.charCodeAt(path.length - 1); + return ch === 47 /* slash */ || ch === 92 /* backslash */; + } + ts.hasTrailingDirectorySeparator = hasTrailingDirectorySeparator; + function removeTrailingDirectorySeparator(path) { + if (hasTrailingDirectorySeparator(path)) { + return path.substr(0, path.length - 1); + } + return path; + } + ts.removeTrailingDirectorySeparator = removeTrailingDirectorySeparator; + function ensureTrailingDirectorySeparator(path) { + if (!hasTrailingDirectorySeparator(path)) { + return path + ts.directorySeparator; + } + return path; + } + ts.ensureTrailingDirectorySeparator = ensureTrailingDirectorySeparator; + function comparePathsWorker(a, b, componentComparer) { + if (a === b) + return 0 /* EqualTo */; + if (a === undefined) + return -1 /* LessThan */; + if (b === undefined) + return 1 /* GreaterThan */; + var aComponents = ts.reducePathComponents(ts.getPathComponents(a)); + var bComponents = ts.reducePathComponents(ts.getPathComponents(b)); + var sharedLength = Math.min(aComponents.length, bComponents.length); + for (var i = 0; i < sharedLength; i++) { + var stringComparer = i === 0 ? ts.compareStringsCaseInsensitive : componentComparer; + var result = stringComparer(aComponents[i], bComponents[i]); + if (result !== 0 /* EqualTo */) { + return result; + } + } + return ts.compareValues(aComponents.length, bComponents.length); + } + /** + * Performs a case-sensitive comparison of two paths. + */ + function comparePathsCaseSensitive(a, b) { + return comparePathsWorker(a, b, ts.compareStringsCaseSensitive); + } + ts.comparePathsCaseSensitive = comparePathsCaseSensitive; + /** + * Performs a case-insensitive comparison of two paths. + */ + function comparePathsCaseInsensitive(a, b) { + return comparePathsWorker(a, b, ts.compareStringsCaseInsensitive); + } + ts.comparePathsCaseInsensitive = comparePathsCaseInsensitive; + function comparePaths(a, b, currentDirectory, ignoreCase) { + if (typeof currentDirectory === "string") { + a = combinePaths(currentDirectory, a); + b = combinePaths(currentDirectory, b); + } + else if (typeof currentDirectory === "boolean") { + ignoreCase = currentDirectory; + } + return comparePathsWorker(a, b, ts.getStringComparer(ignoreCase)); + } + ts.comparePaths = comparePaths; + function containsPath(parent, child, currentDirectory, ignoreCase) { + if (typeof currentDirectory === "string") { + parent = combinePaths(currentDirectory, parent); + child = combinePaths(currentDirectory, child); + } + else if (typeof currentDirectory === "boolean") { + ignoreCase = currentDirectory; + } + if (parent === undefined || child === undefined) + return false; + if (parent === child) + return true; + var parentComponents = ts.reducePathComponents(ts.getPathComponents(parent)); + var childComponents = ts.reducePathComponents(ts.getPathComponents(child)); + if (childComponents.length < parentComponents.length) { + return false; + } + var componentEqualityComparer = ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive; + for (var i = 0; i < parentComponents.length; i++) { + var equalityComparer = i === 0 ? ts.equateStringsCaseInsensitive : componentEqualityComparer; + if (!equalityComparer(parentComponents[i], childComponents[i])) { + return false; + } + } + return true; + } + ts.containsPath = containsPath; + function isDirectorySeparator(charCode) { + return charCode === 47 /* slash */ || charCode === 92 /* backslash */; + } + function stripLeadingDirectorySeparator(s) { + return isDirectorySeparator(s.charCodeAt(0)) ? s.slice(1) : undefined; + } + function tryRemoveDirectoryPrefix(path, dirPath, getCanonicalFileName) { + var withoutPrefix = ts.tryRemovePrefix(path, dirPath, getCanonicalFileName); + return withoutPrefix === undefined ? undefined : stripLeadingDirectorySeparator(withoutPrefix); + } + ts.tryRemoveDirectoryPrefix = tryRemoveDirectoryPrefix; + // Reserved characters, forces escaping of any non-word (or digit), non-whitespace character. + // It may be inefficient (we could just match (/[-[\]{}()*+?.,\\^$|#\s]/g), but this is future + // proof. + var reservedCharacterPattern = /[^\w\s\/]/g; + function regExpEscape(text) { + return text.replace(reservedCharacterPattern, escapeRegExpCharacter); + } + ts.regExpEscape = regExpEscape; + function escapeRegExpCharacter(match) { + return "\\" + match; + } + var wildcardCharCodes = [42 /* asterisk */, 63 /* question */]; + function hasExtension(fileName) { + return ts.stringContains(getBaseFileName(fileName), "."); + } + ts.hasExtension = hasExtension; + ts.commonPackageFolders = ["node_modules", "bower_components", "jspm_packages"]; + var implicitExcludePathRegexPattern = "(?!(" + ts.commonPackageFolders.join("|") + ")(/|$))"; + var filesMatcher = { + /** + * Matches any single directory segment unless it is the last segment and a .min.js file + * Breakdown: + * [^./] # matches everything up to the first . character (excluding directory separators) + * (\\.(?!min\\.js$))? # matches . characters but not if they are part of the .min.js file extension + */ + singleAsteriskRegexFragment: "([^./]|(\\.(?!min\\.js$))?)*", + /** + * Regex for the ** wildcard. Matches any number of subdirectories. When used for including + * files or directories, does not match subdirectories that start with a . character + */ + doubleAsteriskRegexFragment: "(/" + implicitExcludePathRegexPattern + "[^/.][^/]*)*?", + replaceWildcardCharacter: function (match) { return replaceWildcardCharacter(match, filesMatcher.singleAsteriskRegexFragment); } + }; + var directoriesMatcher = { + singleAsteriskRegexFragment: "[^/]*", + /** + * Regex for the ** wildcard. Matches any number of subdirectories. When used for including + * files or directories, does not match subdirectories that start with a . character + */ + doubleAsteriskRegexFragment: "(/" + implicitExcludePathRegexPattern + "[^/.][^/]*)*?", + replaceWildcardCharacter: function (match) { return replaceWildcardCharacter(match, directoriesMatcher.singleAsteriskRegexFragment); } + }; + var excludeMatcher = { + singleAsteriskRegexFragment: "[^/]*", + doubleAsteriskRegexFragment: "(/.+?)?", + replaceWildcardCharacter: function (match) { return replaceWildcardCharacter(match, excludeMatcher.singleAsteriskRegexFragment); } + }; + var wildcardMatchers = { + files: filesMatcher, + directories: directoriesMatcher, + exclude: excludeMatcher + }; + function getRegularExpressionForWildcard(specs, basePath, usage) { + var patterns = getRegularExpressionsForWildcards(specs, basePath, usage); + if (!patterns || !patterns.length) { + return undefined; + } + var pattern = patterns.map(function (pattern) { return "(" + pattern + ")"; }).join("|"); + // If excluding, match "foo/bar/baz...", but if including, only allow "foo". + var terminator = usage === "exclude" ? "($|/)" : "$"; + return "^(" + pattern + ")" + terminator; + } + ts.getRegularExpressionForWildcard = getRegularExpressionForWildcard; + function getRegularExpressionsForWildcards(specs, basePath, usage) { + if (specs === undefined || specs.length === 0) { + return undefined; + } + return ts.flatMap(specs, function (spec) { + return spec && getSubPatternFromSpec(spec, basePath, usage, wildcardMatchers[usage]); + }); + } + ts.getRegularExpressionsForWildcards = getRegularExpressionsForWildcards; + /** + * An "includes" path "foo" is implicitly a glob "foo/** /*" (without the space) if its last component has no extension, + * and does not contain any glob characters itself. + */ + function isImplicitGlob(lastPathComponent) { + return !/[.*?]/.test(lastPathComponent); + } + ts.isImplicitGlob = isImplicitGlob; + function getSubPatternFromSpec(spec, basePath, usage, _a) { + var singleAsteriskRegexFragment = _a.singleAsteriskRegexFragment, doubleAsteriskRegexFragment = _a.doubleAsteriskRegexFragment, replaceWildcardCharacter = _a.replaceWildcardCharacter; + var subpattern = ""; + var hasWrittenComponent = false; + var components = ts.getNormalizedPathComponents(spec, basePath); + var lastComponent = ts.last(components); + if (usage !== "exclude" && lastComponent === "**") { + return undefined; + } + // getNormalizedPathComponents includes the separator for the root component. + // We need to remove to create our regex correctly. + components[0] = removeTrailingDirectorySeparator(components[0]); + if (isImplicitGlob(lastComponent)) { + components.push("**", "*"); + } + var optionalCount = 0; + for (var _i = 0, components_1 = components; _i < components_1.length; _i++) { + var component = components_1[_i]; + if (component === "**") { + subpattern += doubleAsteriskRegexFragment; + } + else { + if (usage === "directories") { + subpattern += "("; + optionalCount++; + } + if (hasWrittenComponent) { + subpattern += ts.directorySeparator; + } + if (usage !== "exclude") { + var componentPattern = ""; + // The * and ? wildcards should not match directories or files that start with . if they + // appear first in a component. Dotted directories and files can be included explicitly + // like so: **/.*/.* + if (component.charCodeAt(0) === 42 /* asterisk */) { + componentPattern += "([^./]" + singleAsteriskRegexFragment + ")?"; + component = component.substr(1); + } + else if (component.charCodeAt(0) === 63 /* question */) { + componentPattern += "[^./]"; + component = component.substr(1); + } + componentPattern += component.replace(reservedCharacterPattern, replaceWildcardCharacter); + // Patterns should not include subfolders like node_modules unless they are + // explicitly included as part of the path. + // + // As an optimization, if the component pattern is the same as the component, + // then there definitely were no wildcard characters and we do not need to + // add the exclusion pattern. + if (componentPattern !== component) { + subpattern += implicitExcludePathRegexPattern; + } + subpattern += componentPattern; + } + else { + subpattern += component.replace(reservedCharacterPattern, replaceWildcardCharacter); + } + } + hasWrittenComponent = true; + } + while (optionalCount > 0) { + subpattern += ")?"; + optionalCount--; + } + return subpattern; + } + function replaceWildcardCharacter(match, singleAsteriskRegexFragment) { + return match === "*" ? singleAsteriskRegexFragment : match === "?" ? "[^/]" : "\\" + match; + } + /** @param path directory of the tsconfig.json */ + function getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory) { + path = ts.normalizePath(path); + currentDirectory = ts.normalizePath(currentDirectory); + var absolutePath = combinePaths(currentDirectory, path); + return { + includeFilePatterns: ts.map(getRegularExpressionsForWildcards(includes, absolutePath, "files"), function (pattern) { return "^" + pattern + "$"; }), + includeFilePattern: getRegularExpressionForWildcard(includes, absolutePath, "files"), + includeDirectoryPattern: getRegularExpressionForWildcard(includes, absolutePath, "directories"), + excludePattern: getRegularExpressionForWildcard(excludes, absolutePath, "exclude"), + basePaths: getBasePaths(path, includes, useCaseSensitiveFileNames) + }; + } + ts.getFileMatcherPatterns = getFileMatcherPatterns; + function getRegexFromPattern(pattern, useCaseSensitiveFileNames) { + return new RegExp(pattern, useCaseSensitiveFileNames ? "" : "i"); + } + ts.getRegexFromPattern = getRegexFromPattern; + /** @param path directory of the tsconfig.json */ + function matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries) { + path = ts.normalizePath(path); + currentDirectory = ts.normalizePath(currentDirectory); + var patterns = getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory); + var includeFileRegexes = patterns.includeFilePatterns && patterns.includeFilePatterns.map(function (pattern) { return getRegexFromPattern(pattern, useCaseSensitiveFileNames); }); + var includeDirectoryRegex = patterns.includeDirectoryPattern && getRegexFromPattern(patterns.includeDirectoryPattern, useCaseSensitiveFileNames); + var excludeRegex = patterns.excludePattern && getRegexFromPattern(patterns.excludePattern, useCaseSensitiveFileNames); + // Associate an array of results with each include regex. This keeps results in order of the "include" order. + // If there are no "includes", then just put everything in results[0]. + var results = includeFileRegexes ? includeFileRegexes.map(function () { return []; }) : [[]]; + for (var _i = 0, _a = patterns.basePaths; _i < _a.length; _i++) { + var basePath = _a[_i]; + visitDirectory(basePath, combinePaths(currentDirectory, basePath), depth); + } + return ts.flatten(results); + function visitDirectory(path, absolutePath, depth) { + var _a = getFileSystemEntries(path), files = _a.files, directories = _a.directories; + var _loop_1 = function (current) { + var name = combinePaths(path, current); + var absoluteName = combinePaths(absolutePath, current); + if (extensions && !ts.fileExtensionIsOneOf(name, extensions)) + return "continue"; + if (excludeRegex && excludeRegex.test(absoluteName)) + return "continue"; + if (!includeFileRegexes) { + results[0].push(name); + } + else { + var includeIndex = ts.findIndex(includeFileRegexes, function (re) { return re.test(absoluteName); }); + if (includeIndex !== -1) { + results[includeIndex].push(name); + } + } + }; + for (var _i = 0, _b = ts.sort(files, ts.compareStringsCaseSensitive); _i < _b.length; _i++) { + var current = _b[_i]; + _loop_1(current); + } + if (depth !== undefined) { + depth--; + if (depth === 0) { + return; + } + } + for (var _c = 0, _d = ts.sort(directories, ts.compareStringsCaseSensitive); _c < _d.length; _c++) { + var current = _d[_c]; + var name = combinePaths(path, current); + var absoluteName = combinePaths(absolutePath, current); + if ((!includeDirectoryRegex || includeDirectoryRegex.test(absoluteName)) && + (!excludeRegex || !excludeRegex.test(absoluteName))) { + visitDirectory(name, absoluteName, depth); + } + } + } + } + ts.matchFiles = matchFiles; + /** + * Computes the unique non-wildcard base paths amongst the provided include patterns. + */ + function getBasePaths(path, includes, useCaseSensitiveFileNames) { + // Storage for our results in the form of literal paths (e.g. the paths as written by the user). + var basePaths = [path]; + if (includes) { + // Storage for literal base paths amongst the include patterns. + var includeBasePaths = []; + for (var _i = 0, includes_1 = includes; _i < includes_1.length; _i++) { + var include = includes_1[_i]; + // We also need to check the relative paths by converting them to absolute and normalizing + // in case they escape the base path (e.g "..\somedirectory") + var absolute = ts.isRootedDiskPath(include) ? include : ts.normalizePath(combinePaths(path, include)); + // Append the literal and canonical candidate base paths. + includeBasePaths.push(getIncludeBasePath(absolute)); + } + // Sort the offsets array using either the literal or canonical path representations. + includeBasePaths.sort(ts.getStringComparer(!useCaseSensitiveFileNames)); + var _loop_2 = function (includeBasePath) { + if (ts.every(basePaths, function (basePath) { return !containsPath(basePath, includeBasePath, path, !useCaseSensitiveFileNames); })) { + basePaths.push(includeBasePath); + } + }; + // Iterate over each include base path and include unique base paths that are not a + // subpath of an existing base path + for (var _a = 0, includeBasePaths_1 = includeBasePaths; _a < includeBasePaths_1.length; _a++) { + var includeBasePath = includeBasePaths_1[_a]; + _loop_2(includeBasePath); + } + } + return basePaths; + } + function getIncludeBasePath(absolute) { + var wildcardOffset = ts.indexOfAnyCharCode(absolute, wildcardCharCodes); + if (wildcardOffset < 0) { + // No "*" or "?" in the path + return !hasExtension(absolute) + ? absolute + : removeTrailingDirectorySeparator(ts.getDirectoryPath(absolute)); + } + return absolute.substring(0, absolute.lastIndexOf(ts.directorySeparator, wildcardOffset)); + } + function ensureScriptKind(fileName, scriptKind) { + // Using scriptKind as a condition handles both: + // - 'scriptKind' is unspecified and thus it is `undefined` + // - 'scriptKind' is set and it is `Unknown` (0) + // If the 'scriptKind' is 'undefined' or 'Unknown' then we attempt + // to get the ScriptKind from the file name. If it cannot be resolved + // from the file name then the default 'TS' script kind is returned. + return scriptKind || getScriptKindFromFileName(fileName) || 3 /* TS */; + } + ts.ensureScriptKind = ensureScriptKind; + function getScriptKindFromFileName(fileName) { + var ext = fileName.substr(fileName.lastIndexOf(".")); + switch (ext.toLowerCase()) { + case ".js" /* Js */: + return 1 /* JS */; + case ".jsx" /* Jsx */: + return 2 /* JSX */; + case ".ts" /* Ts */: + return 3 /* TS */; + case ".tsx" /* Tsx */: + return 4 /* TSX */; + case ".json" /* Json */: + return 6 /* JSON */; + default: + return 0 /* Unknown */; + } + } + ts.getScriptKindFromFileName = getScriptKindFromFileName; + /** + * List of supported extensions in order of file resolution precedence. + */ + ts.supportedTSExtensions = [".ts" /* Ts */, ".tsx" /* Tsx */, ".d.ts" /* Dts */]; + ts.supportedTSExtensionsWithJson = [".ts" /* Ts */, ".tsx" /* Tsx */, ".d.ts" /* Dts */, ".json" /* Json */]; + /** Must have ".d.ts" first because if ".ts" goes first, that will be detected as the extension instead of ".d.ts". */ + ts.supportedTSExtensionsForExtractExtension = [".d.ts" /* Dts */, ".ts" /* Ts */, ".tsx" /* Tsx */]; + ts.supportedJSExtensions = [".js" /* Js */, ".jsx" /* Jsx */]; + ts.supportedJSAndJsonExtensions = [".js" /* Js */, ".jsx" /* Jsx */, ".json" /* Json */]; + var allSupportedExtensions = ts.supportedTSExtensions.concat(ts.supportedJSExtensions); + var allSupportedExtensionsWithJson = ts.supportedTSExtensions.concat(ts.supportedJSExtensions, [".json" /* Json */]); + function getSupportedExtensions(options, extraFileExtensions) { + var needJsExtensions = options && options.allowJs; + if (!extraFileExtensions || extraFileExtensions.length === 0) { + return needJsExtensions ? allSupportedExtensions : ts.supportedTSExtensions; + } + var extensions = (needJsExtensions ? allSupportedExtensions : ts.supportedTSExtensions).concat(ts.mapDefined(extraFileExtensions, function (x) { return x.scriptKind === 7 /* Deferred */ || needJsExtensions && isJSLike(x.scriptKind) ? x.extension : undefined; })); + return ts.deduplicate(extensions, ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive); + } + ts.getSupportedExtensions = getSupportedExtensions; + function getSuppoertedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions) { + if (!options || !options.resolveJsonModule) { + return supportedExtensions; + } + if (supportedExtensions === allSupportedExtensions) { + return allSupportedExtensionsWithJson; + } + if (supportedExtensions === ts.supportedTSExtensions) { + return ts.supportedTSExtensionsWithJson; + } + return supportedExtensions.concat([".json" /* Json */]); + } + ts.getSuppoertedExtensionsWithJsonIfResolveJsonModule = getSuppoertedExtensionsWithJsonIfResolveJsonModule; + function isJSLike(scriptKind) { + return scriptKind === 1 /* JS */ || scriptKind === 2 /* JSX */; + } + function hasJSFileExtension(fileName) { + return ts.some(ts.supportedJSExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + } + ts.hasJSFileExtension = hasJSFileExtension; + function hasJSOrJsonFileExtension(fileName) { + return ts.supportedJSAndJsonExtensions.some(function (ext) { return ts.fileExtensionIs(fileName, ext); }); + } + ts.hasJSOrJsonFileExtension = hasJSOrJsonFileExtension; + function hasTSFileExtension(fileName) { + return ts.some(ts.supportedTSExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + } + ts.hasTSFileExtension = hasTSFileExtension; + function isSupportedSourceFileName(fileName, compilerOptions, extraFileExtensions) { + if (!fileName) { + return false; + } + var supportedExtensions = getSupportedExtensions(compilerOptions, extraFileExtensions); + for (var _i = 0, _a = getSuppoertedExtensionsWithJsonIfResolveJsonModule(compilerOptions, supportedExtensions); _i < _a.length; _i++) { + var extension = _a[_i]; + if (ts.fileExtensionIs(fileName, extension)) { + return true; + } + } + return false; + } + ts.isSupportedSourceFileName = isSupportedSourceFileName; + /** + * Extension boundaries by priority. Lower numbers indicate higher priorities, and are + * aligned to the offset of the highest priority extension in the + * allSupportedExtensions array. + */ + var ExtensionPriority; + (function (ExtensionPriority) { + ExtensionPriority[ExtensionPriority["TypeScriptFiles"] = 0] = "TypeScriptFiles"; + ExtensionPriority[ExtensionPriority["DeclarationAndJavaScriptFiles"] = 2] = "DeclarationAndJavaScriptFiles"; + ExtensionPriority[ExtensionPriority["Highest"] = 0] = "Highest"; + ExtensionPriority[ExtensionPriority["Lowest"] = 2] = "Lowest"; + })(ExtensionPriority = ts.ExtensionPriority || (ts.ExtensionPriority = {})); + function getExtensionPriority(path, supportedExtensions) { + for (var i = supportedExtensions.length - 1; i >= 0; i--) { + if (ts.fileExtensionIs(path, supportedExtensions[i])) { + return adjustExtensionPriority(i, supportedExtensions); + } + } + // If its not in the list of supported extensions, this is likely a + // TypeScript file with a non-ts extension + return 0 /* Highest */; + } + ts.getExtensionPriority = getExtensionPriority; + /** + * Adjusts an extension priority to be the highest priority within the same range. + */ + function adjustExtensionPriority(extensionPriority, supportedExtensions) { + if (extensionPriority < 2 /* DeclarationAndJavaScriptFiles */) { + return 0 /* TypeScriptFiles */; + } + else if (extensionPriority < supportedExtensions.length) { + return 2 /* DeclarationAndJavaScriptFiles */; + } + else { + return supportedExtensions.length; + } + } + ts.adjustExtensionPriority = adjustExtensionPriority; + /** + * Gets the next lowest extension priority for a given priority. + */ + function getNextLowestExtensionPriority(extensionPriority, supportedExtensions) { + if (extensionPriority < 2 /* DeclarationAndJavaScriptFiles */) { + return 2 /* DeclarationAndJavaScriptFiles */; + } + else { + return supportedExtensions.length; + } + } + ts.getNextLowestExtensionPriority = getNextLowestExtensionPriority; + var extensionsToRemove = [".d.ts" /* Dts */, ".ts" /* Ts */, ".js" /* Js */, ".tsx" /* Tsx */, ".jsx" /* Jsx */, ".json" /* Json */]; + function removeFileExtension(path) { + for (var _i = 0, extensionsToRemove_1 = extensionsToRemove; _i < extensionsToRemove_1.length; _i++) { + var ext = extensionsToRemove_1[_i]; + var extensionless = tryRemoveExtension(path, ext); + if (extensionless !== undefined) { + return extensionless; + } + } + return path; + } + ts.removeFileExtension = removeFileExtension; + function tryRemoveExtension(path, extension) { + return ts.fileExtensionIs(path, extension) ? removeExtension(path, extension) : undefined; + } + ts.tryRemoveExtension = tryRemoveExtension; + function removeExtension(path, extension) { + return path.substring(0, path.length - extension.length); + } + ts.removeExtension = removeExtension; + function changeExtension(path, newExtension) { + return changeAnyExtension(path, newExtension, extensionsToRemove, /*ignoreCase*/ false); + } + ts.changeExtension = changeExtension; + function changeAnyExtension(path, ext, extensions, ignoreCase) { + var pathext = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(path, extensions, ignoreCase) : getAnyExtensionFromPath(path); + return pathext ? path.slice(0, path.length - pathext.length) + (ts.startsWith(ext, ".") ? ext : "." + ext) : path; + } + ts.changeAnyExtension = changeAnyExtension; + var Debug; + (function (Debug) { + function showSymbol(symbol) { + var symbolFlags = ts.SymbolFlags; + return "{ flags: " + (symbolFlags ? showFlags(symbol.flags, symbolFlags) : symbol.flags) + "; declarations: " + ts.map(symbol.declarations, showSyntaxKind) + " }"; + } + Debug.showSymbol = showSymbol; + function showFlags(flags, flagsEnum) { + var out = []; + for (var pow = 0; pow <= 30; pow++) { + var n = 1 << pow; + if (flags & n) { + out.push(flagsEnum[n]); + } + } + return out.join("|"); + } + function showSyntaxKind(node) { + var syntaxKind = ts.SyntaxKind; + return syntaxKind ? syntaxKind[node.kind] : node.kind.toString(); + } + Debug.showSyntaxKind = showSyntaxKind; + })(Debug = ts.Debug || (ts.Debug = {})); + function tryParsePattern(pattern) { + // This should be verified outside of here and a proper error thrown. + Debug.assert(ts.hasZeroOrOneAsteriskCharacter(pattern)); + var indexOfStar = pattern.indexOf("*"); + return indexOfStar === -1 ? undefined : { + prefix: pattern.substr(0, indexOfStar), + suffix: pattern.substr(indexOfStar + 1) + }; + } + ts.tryParsePattern = tryParsePattern; + function positionIsSynthesized(pos) { + // This is a fast way of testing the following conditions: + // pos === undefined || pos === null || isNaN(pos) || pos < 0; + return !(pos >= 0); + } + ts.positionIsSynthesized = positionIsSynthesized; + /** True if an extension is one of the supported TypeScript extensions. */ + function extensionIsTS(ext) { + return ext === ".ts" /* Ts */ || ext === ".tsx" /* Tsx */ || ext === ".d.ts" /* Dts */; + } + ts.extensionIsTS = extensionIsTS; + function resolutionExtensionIsTSOrJson(ext) { + return extensionIsTS(ext) || ext === ".json" /* Json */; + } + ts.resolutionExtensionIsTSOrJson = resolutionExtensionIsTSOrJson; + /** + * Gets the extension from a path. + * Path must have a valid extension. + */ + function extensionFromPath(path) { + var ext = tryGetExtensionFromPath(path); + return ext !== undefined ? ext : Debug.fail("File " + path + " has unknown extension."); + } + ts.extensionFromPath = extensionFromPath; + function isAnySupportedFileExtension(path) { + return tryGetExtensionFromPath(path) !== undefined; + } + ts.isAnySupportedFileExtension = isAnySupportedFileExtension; + function tryGetExtensionFromPath(path) { + return ts.find(extensionsToRemove, function (e) { return ts.fileExtensionIs(path, e); }); + } + ts.tryGetExtensionFromPath = tryGetExtensionFromPath; + function getAnyExtensionFromPathWorker(path, extensions, stringEqualityComparer) { + if (typeof extensions === "string") + extensions = [extensions]; + for (var _i = 0, extensions_2 = extensions; _i < extensions_2.length; _i++) { + var extension = extensions_2[_i]; + if (!ts.startsWith(extension, ".")) + extension = "." + extension; + if (path.length >= extension.length && path.charAt(path.length - extension.length) === ".") { + var pathExtension = path.slice(path.length - extension.length); + if (stringEqualityComparer(pathExtension, extension)) { + return pathExtension; + } + } + } + return ""; + } + function getAnyExtensionFromPath(path, extensions, ignoreCase) { + // Retrieves any string from the final "." onwards from a base file name. + // Unlike extensionFromPath, which throws an exception on unrecognized extensions. + if (extensions) { + return getAnyExtensionFromPathWorker(path, extensions, ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive); + } + var baseFileName = getBaseFileName(path); + var extensionIndex = baseFileName.lastIndexOf("."); + if (extensionIndex >= 0) { + return baseFileName.substring(extensionIndex); + } + return ""; + } + ts.getAnyExtensionFromPath = getAnyExtensionFromPath; + function isCheckJsEnabledForFile(sourceFile, compilerOptions) { + return sourceFile.checkJsDirective ? sourceFile.checkJsDirective.enabled : compilerOptions.checkJs; + } + ts.isCheckJsEnabledForFile = isCheckJsEnabledForFile; + ts.emptyFileSystemEntries = { + files: ts.emptyArray, + directories: ts.emptyArray + }; + /** + * patternStrings contains both pattern strings (containing "*") and regular strings. + * Return an exact match if possible, or a pattern match, or undefined. + * (These are verified by verifyCompilerOptions to have 0 or 1 "*" characters.) + */ + function matchPatternOrExact(patternStrings, candidate) { + var patterns = []; + for (var _i = 0, patternStrings_1 = patternStrings; _i < patternStrings_1.length; _i++) { + var patternString = patternStrings_1[_i]; + var pattern = tryParsePattern(patternString); + if (pattern) { + patterns.push(pattern); + } + else if (patternString === candidate) { + // pattern was matched as is - no need to search further + return patternString; + } + } + return ts.findBestPatternMatch(patterns, function (_) { return _; }, candidate); + } + ts.matchPatternOrExact = matchPatternOrExact; + function sliceAfter(arr, value) { + var index = arr.indexOf(value); + Debug.assert(index !== -1); + return arr.slice(index); + } + ts.sliceAfter = sliceAfter; + function minAndMax(arr, getValue) { + Debug.assert(arr.length !== 0); + var min = getValue(arr[0]); + var max = min; + for (var i = 1; i < arr.length; i++) { + var value = getValue(arr[i]); + if (value < min) { + min = value; + } + else if (value > max) { + max = value; + } + } + return { min: min, max: max }; + } + ts.minAndMax = minAndMax; + var NodeSet = /** @class */ (function () { + function NodeSet() { + this.map = ts.createMap(); + } + NodeSet.prototype.add = function (node) { + this.map.set(String(ts.getNodeId(node)), node); + }; + NodeSet.prototype.tryAdd = function (node) { + if (this.has(node)) + return false; + this.add(node); + return true; + }; + NodeSet.prototype.has = function (node) { + return this.map.has(String(ts.getNodeId(node))); + }; + NodeSet.prototype.forEach = function (cb) { + this.map.forEach(cb); + }; + NodeSet.prototype.some = function (pred) { + return ts.forEachEntry(this.map, pred) || false; + }; + return NodeSet; + }()); + ts.NodeSet = NodeSet; + var NodeMap = /** @class */ (function () { + function NodeMap() { + this.map = ts.createMap(); + } + NodeMap.prototype.get = function (node) { + var res = this.map.get(String(ts.getNodeId(node))); + return res && res.value; + }; + NodeMap.prototype.getOrUpdate = function (node, setValue) { + var res = this.get(node); + if (res) + return res; + var value = setValue(); + this.set(node, value); + return value; + }; + NodeMap.prototype.set = function (node, value) { + this.map.set(String(ts.getNodeId(node)), { node: node, value: value }); + }; + NodeMap.prototype.has = function (node) { + return this.map.has(String(ts.getNodeId(node))); + }; + NodeMap.prototype.forEach = function (cb) { + this.map.forEach(function (_a) { + var node = _a.node, value = _a.value; + return cb(value, node); + }); + }; + return NodeMap; + }()); + ts.NodeMap = NodeMap; + function rangeOfNode(node) { + return { pos: ts.getTokenPosOfNode(node), end: node.end }; + } + ts.rangeOfNode = rangeOfNode; + function rangeOfTypeParameters(typeParameters) { + // Include the `<>` + return { pos: typeParameters.pos - 1, end: typeParameters.end + 1 }; + } + ts.rangeOfTypeParameters = rangeOfTypeParameters; + function skipTypeChecking(sourceFile, options) { + // If skipLibCheck is enabled, skip reporting errors if file is a declaration file. + // If skipDefaultLibCheck is enabled, skip reporting errors if file contains a + // '/// ' directive. + return options.skipLibCheck && sourceFile.isDeclarationFile || options.skipDefaultLibCheck && sourceFile.hasNoDefaultLib; + } + ts.skipTypeChecking = skipTypeChecking; + function isJsonEqual(a, b) { + return a === b || typeof a === "object" && a !== null && typeof b === "object" && b !== null && ts.equalOwnProperties(a, b, isJsonEqual); + } + ts.isJsonEqual = isJsonEqual; + function getOrUpdate(map, key, getDefault) { + var got = map.get(key); + if (got === undefined) { + var value = getDefault(); + map.set(key, value); + return value; + } + else { + return got; + } + } + ts.getOrUpdate = getOrUpdate; + /** + * Converts a bigint literal string, e.g. `0x1234n`, + * to its decimal string representation, e.g. `4660`. + */ + function parsePseudoBigInt(stringValue) { + var log2Base; + switch (stringValue.charCodeAt(1)) { // "x" in "0x123" + case 98 /* b */: + case 66 /* B */: // 0b or 0B + log2Base = 1; + break; + case 111 /* o */: + case 79 /* O */: // 0o or 0O + log2Base = 3; + break; + case 120 /* x */: + case 88 /* X */: // 0x or 0X + log2Base = 4; + break; + default: // already in decimal; omit trailing "n" + var nIndex = stringValue.length - 1; + // Skip leading 0s + var nonZeroStart = 0; + while (stringValue.charCodeAt(nonZeroStart) === 48 /* _0 */) { + nonZeroStart++; + } + return stringValue.slice(nonZeroStart, nIndex) || "0"; + } + // Omit leading "0b", "0o", or "0x", and trailing "n" + var startIndex = 2, endIndex = stringValue.length - 1; + var bitsNeeded = (endIndex - startIndex) * log2Base; + // Stores the value specified by the string as a LE array of 16-bit integers + // using Uint16 instead of Uint32 so combining steps can use bitwise operators + var segments = new Uint16Array((bitsNeeded >>> 4) + (bitsNeeded & 15 ? 1 : 0)); + // Add the digits, one at a time + for (var i = endIndex - 1, bitOffset = 0; i >= startIndex; i--, bitOffset += log2Base) { + var segment = bitOffset >>> 4; + var digitChar = stringValue.charCodeAt(i); + // Find character range: 0-9 < A-F < a-f + var digit = digitChar <= 57 /* _9 */ + ? digitChar - 48 /* _0 */ + : 10 + digitChar - + (digitChar <= 70 /* F */ ? 65 /* A */ : 97 /* a */); + var shiftedDigit = digit << (bitOffset & 15); + segments[segment] |= shiftedDigit; + var residual = shiftedDigit >>> 16; + if (residual) + segments[segment + 1] |= residual; // overflows segment + } + // Repeatedly divide segments by 10 and add remainder to base10Value + var base10Value = ""; + var firstNonzeroSegment = segments.length - 1; + var segmentsRemaining = true; + while (segmentsRemaining) { + var mod10 = 0; + segmentsRemaining = false; + for (var segment = firstNonzeroSegment; segment >= 0; segment--) { + var newSegment = mod10 << 16 | segments[segment]; + var segmentValue = (newSegment / 10) | 0; + segments[segment] = segmentValue; + mod10 = newSegment - segmentValue * 10; + if (segmentValue && !segmentsRemaining) { + firstNonzeroSegment = segment; + segmentsRemaining = true; + } + } + base10Value = mod10 + base10Value; + } + return base10Value; + } + ts.parsePseudoBigInt = parsePseudoBigInt; + function pseudoBigIntToString(_a) { + var negative = _a.negative, base10Value = _a.base10Value; + return (negative && base10Value !== "0" ? "-" : "") + base10Value; + } + ts.pseudoBigIntToString = pseudoBigIntToString; +})(ts || (ts = {})); +var ts; +(function (ts) { + var SignatureFlags; + (function (SignatureFlags) { + SignatureFlags[SignatureFlags["None"] = 0] = "None"; + SignatureFlags[SignatureFlags["Yield"] = 1] = "Yield"; + SignatureFlags[SignatureFlags["Await"] = 2] = "Await"; + SignatureFlags[SignatureFlags["Type"] = 4] = "Type"; + SignatureFlags[SignatureFlags["IgnoreMissingOpenBrace"] = 16] = "IgnoreMissingOpenBrace"; + SignatureFlags[SignatureFlags["JSDoc"] = 32] = "JSDoc"; + })(SignatureFlags || (SignatureFlags = {})); + // tslint:disable variable-name + var NodeConstructor; + var TokenConstructor; + var IdentifierConstructor; + var SourceFileConstructor; + // tslint:enable variable-name + function createNode(kind, pos, end) { + if (kind === 279 /* SourceFile */) { + return new (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor()))(kind, pos, end); + } + else if (kind === 72 /* Identifier */) { + return new (IdentifierConstructor || (IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor()))(kind, pos, end); + } + else if (!ts.isNodeKind(kind)) { + return new (TokenConstructor || (TokenConstructor = ts.objectAllocator.getTokenConstructor()))(kind, pos, end); + } + else { + return new (NodeConstructor || (NodeConstructor = ts.objectAllocator.getNodeConstructor()))(kind, pos, end); + } + } + ts.createNode = createNode; + function visitNode(cbNode, node) { + return node && cbNode(node); + } + function visitNodes(cbNode, cbNodes, nodes) { + if (nodes) { + if (cbNodes) { + return cbNodes(nodes); + } + for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) { + var node = nodes_1[_i]; + var result = cbNode(node); + if (result) { + return result; + } + } + } + } + /*@internal*/ + function isJSDocLikeText(text, start) { + return text.charCodeAt(start + 1) === 42 /* asterisk */ && + text.charCodeAt(start + 2) === 42 /* asterisk */ && + text.charCodeAt(start + 3) !== 47 /* slash */; + } + ts.isJSDocLikeText = isJSDocLikeText; + /** + * Invokes a callback for each child of the given node. The 'cbNode' callback is invoked for all child nodes + * stored in properties. If a 'cbNodes' callback is specified, it is invoked for embedded arrays; otherwise, + * embedded arrays are flattened and the 'cbNode' callback is invoked for each element. If a callback returns + * a truthy value, iteration stops and that value is returned. Otherwise, undefined is returned. + * + * @param node a given node to visit its children + * @param cbNode a callback to be invoked for all child nodes + * @param cbNodes a callback to be invoked for embedded array + * + * @remarks `forEachChild` must visit the children of a node in the order + * that they appear in the source code. The language service depends on this property to locate nodes by position. + */ + function forEachChild(node, cbNode, cbNodes) { + if (!node || node.kind <= 147 /* LastToken */) { + return; + } + switch (node.kind) { + case 148 /* QualifiedName */: + return visitNode(cbNode, node.left) || + visitNode(cbNode, node.right); + case 150 /* TypeParameter */: + return visitNode(cbNode, node.name) || + visitNode(cbNode, node.constraint) || + visitNode(cbNode, node.default) || + visitNode(cbNode, node.expression); + case 276 /* ShorthandPropertyAssignment */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.exclamationToken) || + visitNode(cbNode, node.equalsToken) || + visitNode(cbNode, node.objectAssignmentInitializer); + case 277 /* SpreadAssignment */: + return visitNode(cbNode, node.expression); + case 151 /* Parameter */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.dotDotDotToken) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.type) || + visitNode(cbNode, node.initializer); + case 154 /* PropertyDeclaration */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.exclamationToken) || + visitNode(cbNode, node.type) || + visitNode(cbNode, node.initializer); + case 153 /* PropertySignature */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.type) || + visitNode(cbNode, node.initializer); + case 275 /* PropertyAssignment */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.initializer); + case 237 /* VariableDeclaration */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.exclamationToken) || + visitNode(cbNode, node.type) || + visitNode(cbNode, node.initializer); + case 186 /* BindingElement */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.dotDotDotToken) || + visitNode(cbNode, node.propertyName) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.initializer); + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 162 /* IndexSignature */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type); + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 196 /* FunctionExpression */: + case 239 /* FunctionDeclaration */: + case 197 /* ArrowFunction */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.asteriskToken) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.exclamationToken) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type) || + visitNode(cbNode, node.equalsGreaterThanToken) || + visitNode(cbNode, node.body); + case 164 /* TypeReference */: + return visitNode(cbNode, node.typeName) || + visitNodes(cbNode, cbNodes, node.typeArguments); + case 163 /* TypePredicate */: + return visitNode(cbNode, node.parameterName) || + visitNode(cbNode, node.type); + case 167 /* TypeQuery */: + return visitNode(cbNode, node.exprName); + case 168 /* TypeLiteral */: + return visitNodes(cbNode, cbNodes, node.members); + case 169 /* ArrayType */: + return visitNode(cbNode, node.elementType); + case 170 /* TupleType */: + return visitNodes(cbNode, cbNodes, node.elementTypes); + case 173 /* UnionType */: + case 174 /* IntersectionType */: + return visitNodes(cbNode, cbNodes, node.types); + case 175 /* ConditionalType */: + return visitNode(cbNode, node.checkType) || + visitNode(cbNode, node.extendsType) || + visitNode(cbNode, node.trueType) || + visitNode(cbNode, node.falseType); + case 176 /* InferType */: + return visitNode(cbNode, node.typeParameter); + case 183 /* ImportType */: + return visitNode(cbNode, node.argument) || + visitNode(cbNode, node.qualifier) || + visitNodes(cbNode, cbNodes, node.typeArguments); + case 177 /* ParenthesizedType */: + case 179 /* TypeOperator */: + return visitNode(cbNode, node.type); + case 180 /* IndexedAccessType */: + return visitNode(cbNode, node.objectType) || + visitNode(cbNode, node.indexType); + case 181 /* MappedType */: + return visitNode(cbNode, node.readonlyToken) || + visitNode(cbNode, node.typeParameter) || + visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.type); + case 182 /* LiteralType */: + return visitNode(cbNode, node.literal); + case 184 /* ObjectBindingPattern */: + case 185 /* ArrayBindingPattern */: + return visitNodes(cbNode, cbNodes, node.elements); + case 187 /* ArrayLiteralExpression */: + return visitNodes(cbNode, cbNodes, node.elements); + case 188 /* ObjectLiteralExpression */: + return visitNodes(cbNode, cbNodes, node.properties); + case 189 /* PropertyAccessExpression */: + return visitNode(cbNode, node.expression) || + visitNode(cbNode, node.name); + case 190 /* ElementAccessExpression */: + return visitNode(cbNode, node.expression) || + visitNode(cbNode, node.argumentExpression); + case 191 /* CallExpression */: + case 192 /* NewExpression */: + return visitNode(cbNode, node.expression) || + visitNodes(cbNode, cbNodes, node.typeArguments) || + visitNodes(cbNode, cbNodes, node.arguments); + case 193 /* TaggedTemplateExpression */: + return visitNode(cbNode, node.tag) || + visitNodes(cbNode, cbNodes, node.typeArguments) || + visitNode(cbNode, node.template); + case 194 /* TypeAssertionExpression */: + return visitNode(cbNode, node.type) || + visitNode(cbNode, node.expression); + case 195 /* ParenthesizedExpression */: + return visitNode(cbNode, node.expression); + case 198 /* DeleteExpression */: + return visitNode(cbNode, node.expression); + case 199 /* TypeOfExpression */: + return visitNode(cbNode, node.expression); + case 200 /* VoidExpression */: + return visitNode(cbNode, node.expression); + case 202 /* PrefixUnaryExpression */: + return visitNode(cbNode, node.operand); + case 207 /* YieldExpression */: + return visitNode(cbNode, node.asteriskToken) || + visitNode(cbNode, node.expression); + case 201 /* AwaitExpression */: + return visitNode(cbNode, node.expression); + case 203 /* PostfixUnaryExpression */: + return visitNode(cbNode, node.operand); + case 204 /* BinaryExpression */: + return visitNode(cbNode, node.left) || + visitNode(cbNode, node.operatorToken) || + visitNode(cbNode, node.right); + case 212 /* AsExpression */: + return visitNode(cbNode, node.expression) || + visitNode(cbNode, node.type); + case 213 /* NonNullExpression */: + return visitNode(cbNode, node.expression); + case 214 /* MetaProperty */: + return visitNode(cbNode, node.name); + case 205 /* ConditionalExpression */: + return visitNode(cbNode, node.condition) || + visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.whenTrue) || + visitNode(cbNode, node.colonToken) || + visitNode(cbNode, node.whenFalse); + case 208 /* SpreadElement */: + return visitNode(cbNode, node.expression); + case 218 /* Block */: + case 245 /* ModuleBlock */: + return visitNodes(cbNode, cbNodes, node.statements); + case 279 /* SourceFile */: + return visitNodes(cbNode, cbNodes, node.statements) || + visitNode(cbNode, node.endOfFileToken); + case 219 /* VariableStatement */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.declarationList); + case 238 /* VariableDeclarationList */: + return visitNodes(cbNode, cbNodes, node.declarations); + case 221 /* ExpressionStatement */: + return visitNode(cbNode, node.expression); + case 222 /* IfStatement */: + return visitNode(cbNode, node.expression) || + visitNode(cbNode, node.thenStatement) || + visitNode(cbNode, node.elseStatement); + case 223 /* DoStatement */: + return visitNode(cbNode, node.statement) || + visitNode(cbNode, node.expression); + case 224 /* WhileStatement */: + return visitNode(cbNode, node.expression) || + visitNode(cbNode, node.statement); + case 225 /* ForStatement */: + return visitNode(cbNode, node.initializer) || + visitNode(cbNode, node.condition) || + visitNode(cbNode, node.incrementor) || + visitNode(cbNode, node.statement); + case 226 /* ForInStatement */: + return visitNode(cbNode, node.initializer) || + visitNode(cbNode, node.expression) || + visitNode(cbNode, node.statement); + case 227 /* ForOfStatement */: + return visitNode(cbNode, node.awaitModifier) || + visitNode(cbNode, node.initializer) || + visitNode(cbNode, node.expression) || + visitNode(cbNode, node.statement); + case 228 /* ContinueStatement */: + case 229 /* BreakStatement */: + return visitNode(cbNode, node.label); + case 230 /* ReturnStatement */: + return visitNode(cbNode, node.expression); + case 231 /* WithStatement */: + return visitNode(cbNode, node.expression) || + visitNode(cbNode, node.statement); + case 232 /* SwitchStatement */: + return visitNode(cbNode, node.expression) || + visitNode(cbNode, node.caseBlock); + case 246 /* CaseBlock */: + return visitNodes(cbNode, cbNodes, node.clauses); + case 271 /* CaseClause */: + return visitNode(cbNode, node.expression) || + visitNodes(cbNode, cbNodes, node.statements); + case 272 /* DefaultClause */: + return visitNodes(cbNode, cbNodes, node.statements); + case 233 /* LabeledStatement */: + return visitNode(cbNode, node.label) || + visitNode(cbNode, node.statement); + case 234 /* ThrowStatement */: + return visitNode(cbNode, node.expression); + case 235 /* TryStatement */: + return visitNode(cbNode, node.tryBlock) || + visitNode(cbNode, node.catchClause) || + visitNode(cbNode, node.finallyBlock); + case 274 /* CatchClause */: + return visitNode(cbNode, node.variableDeclaration) || + visitNode(cbNode, node.block); + case 152 /* Decorator */: + return visitNode(cbNode, node.expression); + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.heritageClauses) || + visitNodes(cbNode, cbNodes, node.members); + case 241 /* InterfaceDeclaration */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.heritageClauses) || + visitNodes(cbNode, cbNodes, node.members); + case 242 /* TypeAliasDeclaration */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNode(cbNode, node.type); + case 243 /* EnumDeclaration */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNodes(cbNode, cbNodes, node.members); + case 278 /* EnumMember */: + return visitNode(cbNode, node.name) || + visitNode(cbNode, node.initializer); + case 244 /* ModuleDeclaration */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.body); + case 248 /* ImportEqualsDeclaration */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.moduleReference); + case 249 /* ImportDeclaration */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.importClause) || + visitNode(cbNode, node.moduleSpecifier); + case 250 /* ImportClause */: + return visitNode(cbNode, node.name) || + visitNode(cbNode, node.namedBindings); + case 247 /* NamespaceExportDeclaration */: + return visitNode(cbNode, node.name); + case 251 /* NamespaceImport */: + return visitNode(cbNode, node.name); + case 252 /* NamedImports */: + case 256 /* NamedExports */: + return visitNodes(cbNode, cbNodes, node.elements); + case 255 /* ExportDeclaration */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.exportClause) || + visitNode(cbNode, node.moduleSpecifier); + case 253 /* ImportSpecifier */: + case 257 /* ExportSpecifier */: + return visitNode(cbNode, node.propertyName) || + visitNode(cbNode, node.name); + case 254 /* ExportAssignment */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.expression); + case 206 /* TemplateExpression */: + return visitNode(cbNode, node.head) || visitNodes(cbNode, cbNodes, node.templateSpans); + case 216 /* TemplateSpan */: + return visitNode(cbNode, node.expression) || visitNode(cbNode, node.literal); + case 149 /* ComputedPropertyName */: + return visitNode(cbNode, node.expression); + case 273 /* HeritageClause */: + return visitNodes(cbNode, cbNodes, node.types); + case 211 /* ExpressionWithTypeArguments */: + return visitNode(cbNode, node.expression) || + visitNodes(cbNode, cbNodes, node.typeArguments); + case 259 /* ExternalModuleReference */: + return visitNode(cbNode, node.expression); + case 258 /* MissingDeclaration */: + return visitNodes(cbNode, cbNodes, node.decorators); + case 309 /* CommaListExpression */: + return visitNodes(cbNode, cbNodes, node.elements); + case 260 /* JsxElement */: + return visitNode(cbNode, node.openingElement) || + visitNodes(cbNode, cbNodes, node.children) || + visitNode(cbNode, node.closingElement); + case 264 /* JsxFragment */: + return visitNode(cbNode, node.openingFragment) || + visitNodes(cbNode, cbNodes, node.children) || + visitNode(cbNode, node.closingFragment); + case 261 /* JsxSelfClosingElement */: + case 262 /* JsxOpeningElement */: + return visitNode(cbNode, node.tagName) || + visitNodes(cbNode, cbNodes, node.typeArguments) || + visitNode(cbNode, node.attributes); + case 268 /* JsxAttributes */: + return visitNodes(cbNode, cbNodes, node.properties); + case 267 /* JsxAttribute */: + return visitNode(cbNode, node.name) || + visitNode(cbNode, node.initializer); + case 269 /* JsxSpreadAttribute */: + return visitNode(cbNode, node.expression); + case 270 /* JsxExpression */: + return visitNode(cbNode, node.dotDotDotToken) || + visitNode(cbNode, node.expression); + case 263 /* JsxClosingElement */: + return visitNode(cbNode, node.tagName); + case 171 /* OptionalType */: + case 172 /* RestType */: + case 283 /* JSDocTypeExpression */: + case 287 /* JSDocNonNullableType */: + case 286 /* JSDocNullableType */: + case 288 /* JSDocOptionalType */: + case 290 /* JSDocVariadicType */: + return visitNode(cbNode, node.type); + case 289 /* JSDocFunctionType */: + return visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type); + case 291 /* JSDocComment */: + return visitNodes(cbNode, cbNodes, node.tags); + case 299 /* JSDocParameterTag */: + case 305 /* JSDocPropertyTag */: + return visitNode(cbNode, node.tagName) || + (node.isNameFirst + ? visitNode(cbNode, node.name) || + visitNode(cbNode, node.typeExpression) + : visitNode(cbNode, node.typeExpression) || + visitNode(cbNode, node.name)); + case 295 /* JSDocAugmentsTag */: + return visitNode(cbNode, node.tagName) || + visitNode(cbNode, node.class); + case 303 /* JSDocTemplateTag */: + return visitNode(cbNode, node.tagName) || + visitNode(cbNode, node.constraint) || + visitNodes(cbNode, cbNodes, node.typeParameters); + case 304 /* JSDocTypedefTag */: + return visitNode(cbNode, node.tagName) || + (node.typeExpression && + node.typeExpression.kind === 283 /* JSDocTypeExpression */ + ? visitNode(cbNode, node.typeExpression) || + visitNode(cbNode, node.fullName) + : visitNode(cbNode, node.fullName) || + visitNode(cbNode, node.typeExpression)); + case 297 /* JSDocCallbackTag */: + return visitNode(cbNode, node.tagName) || + visitNode(cbNode, node.fullName) || + visitNode(cbNode, node.typeExpression); + case 300 /* JSDocReturnTag */: + case 302 /* JSDocTypeTag */: + case 301 /* JSDocThisTag */: + case 298 /* JSDocEnumTag */: + return visitNode(cbNode, node.tagName) || + visitNode(cbNode, node.typeExpression); + case 293 /* JSDocSignature */: + return ts.forEach(node.typeParameters, cbNode) || + ts.forEach(node.parameters, cbNode) || + visitNode(cbNode, node.type); + case 292 /* JSDocTypeLiteral */: + return ts.forEach(node.jsDocPropertyTags, cbNode); + case 294 /* JSDocTag */: + case 296 /* JSDocClassTag */: + return visitNode(cbNode, node.tagName); + case 308 /* PartiallyEmittedExpression */: + return visitNode(cbNode, node.expression); + } + } + ts.forEachChild = forEachChild; + function createSourceFile(fileName, sourceText, languageVersion, setParentNodes, scriptKind) { + if (setParentNodes === void 0) { setParentNodes = false; } + ts.performance.mark("beforeParse"); + var result; + if (languageVersion === 100 /* JSON */) { + result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes, 6 /* JSON */); + } + else { + result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes, scriptKind); + } + ts.performance.mark("afterParse"); + ts.performance.measure("Parse", "beforeParse", "afterParse"); + return result; + } + ts.createSourceFile = createSourceFile; + function parseIsolatedEntityName(text, languageVersion) { + return Parser.parseIsolatedEntityName(text, languageVersion); + } + ts.parseIsolatedEntityName = parseIsolatedEntityName; + /** + * Parse json text into SyntaxTree and return node and parse errors if any + * @param fileName + * @param sourceText + */ + function parseJsonText(fileName, sourceText) { + return Parser.parseJsonText(fileName, sourceText); + } + ts.parseJsonText = parseJsonText; + // See also `isExternalOrCommonJsModule` in utilities.ts + function isExternalModule(file) { + return file.externalModuleIndicator !== undefined; + } + ts.isExternalModule = isExternalModule; + // Produces a new SourceFile for the 'newText' provided. The 'textChangeRange' parameter + // indicates what changed between the 'text' that this SourceFile has and the 'newText'. + // The SourceFile will be created with the compiler attempting to reuse as many nodes from + // this file as possible. + // + // Note: this function mutates nodes from this SourceFile. That means any existing nodes + // from this SourceFile that are being held onto may change as a result (including + // becoming detached from any SourceFile). It is recommended that this SourceFile not + // be used once 'update' is called on it. + function updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks) { + if (aggressiveChecks === void 0) { aggressiveChecks = false; } + var newSourceFile = IncrementalParser.updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks); + // Because new source file node is created, it may not have the flag PossiblyContainDynamicImport. This is the case if there is no new edit to add dynamic import. + // We will manually port the flag to the new source file. + newSourceFile.flags |= (sourceFile.flags & 1572864 /* PermanentlySetIncrementalFlags */); + return newSourceFile; + } + ts.updateSourceFile = updateSourceFile; + /* @internal */ + function parseIsolatedJSDocComment(content, start, length) { + var result = Parser.JSDocParser.parseIsolatedJSDocComment(content, start, length); + if (result && result.jsDoc) { + // because the jsDocComment was parsed out of the source file, it might + // not be covered by the fixupParentReferences. + Parser.fixupParentReferences(result.jsDoc); + } + return result; + } + ts.parseIsolatedJSDocComment = parseIsolatedJSDocComment; + /* @internal */ + // Exposed only for testing. + function parseJSDocTypeExpressionForTests(content, start, length) { + return Parser.JSDocParser.parseJSDocTypeExpressionForTests(content, start, length); + } + ts.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests; + // Implement the parser as a singleton module. We do this for perf reasons because creating + // parser instances can actually be expensive enough to impact us on projects with many source + // files. + var Parser; + (function (Parser) { + // Share a single scanner across all calls to parse a source file. This helps speed things + // up by avoiding the cost of creating/compiling scanners over and over again. + var scanner = ts.createScanner(6 /* Latest */, /*skipTrivia*/ true); + var disallowInAndDecoratorContext = 2048 /* DisallowInContext */ | 8192 /* DecoratorContext */; + // capture constructors in 'initializeState' to avoid null checks + // tslint:disable variable-name + var NodeConstructor; + var TokenConstructor; + var IdentifierConstructor; + var SourceFileConstructor; + // tslint:enable variable-name + var sourceFile; + var parseDiagnostics; + var syntaxCursor; + var currentToken; + var sourceText; + var nodeCount; + var identifiers; + var identifierCount; + var parsingContext; + // Flags that dictate what parsing context we're in. For example: + // Whether or not we are in strict parsing mode. All that changes in strict parsing mode is + // that some tokens that would be considered identifiers may be considered keywords. + // + // When adding more parser context flags, consider which is the more common case that the + // flag will be in. This should be the 'false' state for that flag. The reason for this is + // that we don't store data in our nodes unless the value is in the *non-default* state. So, + // for example, more often than code 'allows-in' (or doesn't 'disallow-in'). We opt for + // 'disallow-in' set to 'false'. Otherwise, if we had 'allowsIn' set to 'true', then almost + // all nodes would need extra state on them to store this info. + // + // Note: 'allowIn' and 'allowYield' track 1:1 with the [in] and [yield] concepts in the ES6 + // grammar specification. + // + // An important thing about these context concepts. By default they are effectively inherited + // while parsing through every grammar production. i.e. if you don't change them, then when + // you parse a sub-production, it will have the same context values as the parent production. + // This is great most of the time. After all, consider all the 'expression' grammar productions + // and how nearly all of them pass along the 'in' and 'yield' context values: + // + // EqualityExpression[In, Yield] : + // RelationalExpression[?In, ?Yield] + // EqualityExpression[?In, ?Yield] == RelationalExpression[?In, ?Yield] + // EqualityExpression[?In, ?Yield] != RelationalExpression[?In, ?Yield] + // EqualityExpression[?In, ?Yield] === RelationalExpression[?In, ?Yield] + // EqualityExpression[?In, ?Yield] !== RelationalExpression[?In, ?Yield] + // + // Where you have to be careful is then understanding what the points are in the grammar + // where the values are *not* passed along. For example: + // + // SingleNameBinding[Yield,GeneratorParameter] + // [+GeneratorParameter]BindingIdentifier[Yield] Initializer[In]opt + // [~GeneratorParameter]BindingIdentifier[?Yield]Initializer[In, ?Yield]opt + // + // Here this is saying that if the GeneratorParameter context flag is set, that we should + // explicitly set the 'yield' context flag to false before calling into the BindingIdentifier + // and we should explicitly unset the 'yield' context flag before calling into the Initializer. + // production. Conversely, if the GeneratorParameter context flag is not set, then we + // should leave the 'yield' context flag alone. + // + // Getting this all correct is tricky and requires careful reading of the grammar to + // understand when these values should be changed versus when they should be inherited. + // + // Note: it should not be necessary to save/restore these flags during speculative/lookahead + // parsing. These context flags are naturally stored and restored through normal recursive + // descent parsing and unwinding. + var contextFlags; + // Whether or not we've had a parse error since creating the last AST node. If we have + // encountered an error, it will be stored on the next AST node we create. Parse errors + // can be broken down into three categories: + // + // 1) An error that occurred during scanning. For example, an unterminated literal, or a + // character that was completely not understood. + // + // 2) A token was expected, but was not present. This type of error is commonly produced + // by the 'parseExpected' function. + // + // 3) A token was present that no parsing function was able to consume. This type of error + // only occurs in the 'abortParsingListOrMoveToNextToken' function when the parser + // decides to skip the token. + // + // In all of these cases, we want to mark the next node as having had an error before it. + // With this mark, we can know in incremental settings if this node can be reused, or if + // we have to reparse it. If we don't keep this information around, we may just reuse the + // node. in that event we would then not produce the same errors as we did before, causing + // significant confusion problems. + // + // Note: it is necessary that this value be saved/restored during speculative/lookahead + // parsing. During lookahead parsing, we will often create a node. That node will have + // this value attached, and then this value will be set back to 'false'. If we decide to + // rewind, we must get back to the same value we had prior to the lookahead. + // + // Note: any errors at the end of the file that do not precede a regular node, should get + // attached to the EOF token. + var parseErrorBeforeNextFinishedNode = false; + function parseSourceFile(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes, scriptKind) { + if (setParentNodes === void 0) { setParentNodes = false; } + scriptKind = ts.ensureScriptKind(fileName, scriptKind); + if (scriptKind === 6 /* JSON */) { + var result_1 = parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes); + ts.convertToObjectWorker(result_1, result_1.parseDiagnostics, /*returnValue*/ false, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined); + result_1.referencedFiles = ts.emptyArray; + result_1.typeReferenceDirectives = ts.emptyArray; + result_1.libReferenceDirectives = ts.emptyArray; + result_1.amdDependencies = ts.emptyArray; + result_1.hasNoDefaultLib = false; + result_1.pragmas = ts.emptyMap; + return result_1; + } + initializeState(sourceText, languageVersion, syntaxCursor, scriptKind); + var result = parseSourceFileWorker(fileName, languageVersion, setParentNodes, scriptKind); + clearState(); + return result; + } + Parser.parseSourceFile = parseSourceFile; + function parseIsolatedEntityName(content, languageVersion) { + // Choice of `isDeclarationFile` should be arbitrary + initializeState(content, languageVersion, /*syntaxCursor*/ undefined, 1 /* JS */); + // Prime the scanner. + nextToken(); + var entityName = parseEntityName(/*allowReservedWords*/ true); + var isInvalid = token() === 1 /* EndOfFileToken */ && !parseDiagnostics.length; + clearState(); + return isInvalid ? entityName : undefined; + } + Parser.parseIsolatedEntityName = parseIsolatedEntityName; + function parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes) { + if (languageVersion === void 0) { languageVersion = 2 /* ES2015 */; } + initializeState(sourceText, languageVersion, syntaxCursor, 6 /* JSON */); + // Set source file so that errors will be reported with this file name + sourceFile = createSourceFile(fileName, 2 /* ES2015 */, 6 /* JSON */, /*isDeclaration*/ false); + sourceFile.flags = contextFlags; + // Prime the scanner. + nextToken(); + var pos = getNodePos(); + if (token() === 1 /* EndOfFileToken */) { + sourceFile.statements = createNodeArray([], pos, pos); + sourceFile.endOfFileToken = parseTokenNode(); + } + else { + var statement = createNode(221 /* ExpressionStatement */); + switch (token()) { + case 22 /* OpenBracketToken */: + statement.expression = parseArrayLiteralExpression(); + break; + case 102 /* TrueKeyword */: + case 87 /* FalseKeyword */: + case 96 /* NullKeyword */: + statement.expression = parseTokenNode(); + break; + case 39 /* MinusToken */: + if (lookAhead(function () { return nextToken() === 8 /* NumericLiteral */ && nextToken() !== 57 /* ColonToken */; })) { + statement.expression = parsePrefixUnaryExpression(); + } + else { + statement.expression = parseObjectLiteralExpression(); + } + break; + case 8 /* NumericLiteral */: + case 10 /* StringLiteral */: + if (lookAhead(function () { return nextToken() !== 57 /* ColonToken */; })) { + statement.expression = parseLiteralNode(); + break; + } + // falls through + default: + statement.expression = parseObjectLiteralExpression(); + break; + } + finishNode(statement); + sourceFile.statements = createNodeArray([statement], pos); + sourceFile.endOfFileToken = parseExpectedToken(1 /* EndOfFileToken */, ts.Diagnostics.Unexpected_token); + } + if (setParentNodes) { + fixupParentReferences(sourceFile); + } + sourceFile.parseDiagnostics = parseDiagnostics; + var result = sourceFile; + clearState(); + return result; + } + Parser.parseJsonText = parseJsonText; + function getLanguageVariant(scriptKind) { + // .tsx and .jsx files are treated as jsx language variant. + return scriptKind === 4 /* TSX */ || scriptKind === 2 /* JSX */ || scriptKind === 1 /* JS */ || scriptKind === 6 /* JSON */ ? 1 /* JSX */ : 0 /* Standard */; + } + function initializeState(_sourceText, languageVersion, _syntaxCursor, scriptKind) { + NodeConstructor = ts.objectAllocator.getNodeConstructor(); + TokenConstructor = ts.objectAllocator.getTokenConstructor(); + IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor(); + SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor(); + sourceText = _sourceText; + syntaxCursor = _syntaxCursor; + parseDiagnostics = []; + parsingContext = 0; + identifiers = ts.createMap(); + identifierCount = 0; + nodeCount = 0; + switch (scriptKind) { + case 1 /* JS */: + case 2 /* JSX */: + contextFlags = 65536 /* JavaScriptFile */; + break; + case 6 /* JSON */: + contextFlags = 65536 /* JavaScriptFile */ | 16777216 /* JsonFile */; + break; + default: + contextFlags = 0 /* None */; + break; + } + parseErrorBeforeNextFinishedNode = false; + // Initialize and prime the scanner before parsing the source elements. + scanner.setText(sourceText); + scanner.setOnError(scanError); + scanner.setScriptTarget(languageVersion); + scanner.setLanguageVariant(getLanguageVariant(scriptKind)); + } + function clearState() { + // Clear out the text the scanner is pointing at, so it doesn't keep anything alive unnecessarily. + scanner.setText(""); + scanner.setOnError(undefined); + // Clear any data. We don't want to accidentally hold onto it for too long. + parseDiagnostics = undefined; + sourceFile = undefined; + identifiers = undefined; + syntaxCursor = undefined; + sourceText = undefined; + } + function parseSourceFileWorker(fileName, languageVersion, setParentNodes, scriptKind) { + var isDeclarationFile = isDeclarationFileName(fileName); + if (isDeclarationFile) { + contextFlags |= 4194304 /* Ambient */; + } + sourceFile = createSourceFile(fileName, languageVersion, scriptKind, isDeclarationFile); + sourceFile.flags = contextFlags; + // Prime the scanner. + nextToken(); + // A member of ReadonlyArray isn't assignable to a member of T[] (and prevents a direct cast) - but this is where we set up those members so they can be readonly in the future + processCommentPragmas(sourceFile, sourceText); + processPragmasIntoFields(sourceFile, reportPragmaDiagnostic); + sourceFile.statements = parseList(0 /* SourceElements */, parseStatement); + ts.Debug.assert(token() === 1 /* EndOfFileToken */); + sourceFile.endOfFileToken = addJSDocComment(parseTokenNode()); + setExternalModuleIndicator(sourceFile); + sourceFile.nodeCount = nodeCount; + sourceFile.identifierCount = identifierCount; + sourceFile.identifiers = identifiers; + sourceFile.parseDiagnostics = parseDiagnostics; + if (setParentNodes) { + fixupParentReferences(sourceFile); + } + return sourceFile; + function reportPragmaDiagnostic(pos, end, diagnostic) { + parseDiagnostics.push(ts.createFileDiagnostic(sourceFile, pos, end, diagnostic)); + } + } + function addJSDocComment(node) { + ts.Debug.assert(!node.jsDoc); // Should only be called once per node + var jsDoc = ts.mapDefined(ts.getJSDocCommentRanges(node, sourceFile.text), function (comment) { return JSDocParser.parseJSDocComment(node, comment.pos, comment.end - comment.pos); }); + if (jsDoc.length) + node.jsDoc = jsDoc; + return node; + } + function fixupParentReferences(rootNode) { + // normally parent references are set during binding. However, for clients that only need + // a syntax tree, and no semantic features, then the binding process is an unnecessary + // overhead. This functions allows us to set all the parents, without all the expense of + // binding. + var parent = rootNode; + forEachChild(rootNode, visitNode); + return; + function visitNode(n) { + // walk down setting parents that differ from the parent we think it should be. This + // allows us to quickly bail out of setting parents for subtrees during incremental + // parsing + if (n.parent !== parent) { + n.parent = parent; + var saveParent = parent; + parent = n; + forEachChild(n, visitNode); + if (ts.hasJSDocNodes(n)) { + for (var _i = 0, _a = n.jsDoc; _i < _a.length; _i++) { + var jsDoc = _a[_i]; + jsDoc.parent = n; + parent = jsDoc; + forEachChild(jsDoc, visitNode); + } + } + parent = saveParent; + } + } + } + Parser.fixupParentReferences = fixupParentReferences; + function createSourceFile(fileName, languageVersion, scriptKind, isDeclarationFile) { + // code from createNode is inlined here so createNode won't have to deal with special case of creating source files + // this is quite rare comparing to other nodes and createNode should be as fast as possible + var sourceFile = new SourceFileConstructor(279 /* SourceFile */, /*pos*/ 0, /* end */ sourceText.length); + nodeCount++; + sourceFile.text = sourceText; + sourceFile.bindDiagnostics = []; + sourceFile.bindSuggestionDiagnostics = undefined; + sourceFile.languageVersion = languageVersion; + sourceFile.fileName = ts.normalizePath(fileName); + sourceFile.languageVariant = getLanguageVariant(scriptKind); + sourceFile.isDeclarationFile = isDeclarationFile; + sourceFile.scriptKind = scriptKind; + return sourceFile; + } + function setContextFlag(val, flag) { + if (val) { + contextFlags |= flag; + } + else { + contextFlags &= ~flag; + } + } + function setDisallowInContext(val) { + setContextFlag(val, 2048 /* DisallowInContext */); + } + function setYieldContext(val) { + setContextFlag(val, 4096 /* YieldContext */); + } + function setDecoratorContext(val) { + setContextFlag(val, 8192 /* DecoratorContext */); + } + function setAwaitContext(val) { + setContextFlag(val, 16384 /* AwaitContext */); + } + function doOutsideOfContext(context, func) { + // contextFlagsToClear will contain only the context flags that are + // currently set that we need to temporarily clear + // We don't just blindly reset to the previous flags to ensure + // that we do not mutate cached flags for the incremental + // parser (ThisNodeHasError, ThisNodeOrAnySubNodesHasError, and + // HasAggregatedChildData). + var contextFlagsToClear = context & contextFlags; + if (contextFlagsToClear) { + // clear the requested context flags + setContextFlag(/*val*/ false, contextFlagsToClear); + var result = func(); + // restore the context flags we just cleared + setContextFlag(/*val*/ true, contextFlagsToClear); + return result; + } + // no need to do anything special as we are not in any of the requested contexts + return func(); + } + function doInsideOfContext(context, func) { + // contextFlagsToSet will contain only the context flags that + // are not currently set that we need to temporarily enable. + // We don't just blindly reset to the previous flags to ensure + // that we do not mutate cached flags for the incremental + // parser (ThisNodeHasError, ThisNodeOrAnySubNodesHasError, and + // HasAggregatedChildData). + var contextFlagsToSet = context & ~contextFlags; + if (contextFlagsToSet) { + // set the requested context flags + setContextFlag(/*val*/ true, contextFlagsToSet); + var result = func(); + // reset the context flags we just set + setContextFlag(/*val*/ false, contextFlagsToSet); + return result; + } + // no need to do anything special as we are already in all of the requested contexts + return func(); + } + function allowInAnd(func) { + return doOutsideOfContext(2048 /* DisallowInContext */, func); + } + function disallowInAnd(func) { + return doInsideOfContext(2048 /* DisallowInContext */, func); + } + function doInYieldContext(func) { + return doInsideOfContext(4096 /* YieldContext */, func); + } + function doInDecoratorContext(func) { + return doInsideOfContext(8192 /* DecoratorContext */, func); + } + function doInAwaitContext(func) { + return doInsideOfContext(16384 /* AwaitContext */, func); + } + function doOutsideOfAwaitContext(func) { + return doOutsideOfContext(16384 /* AwaitContext */, func); + } + function doInYieldAndAwaitContext(func) { + return doInsideOfContext(4096 /* YieldContext */ | 16384 /* AwaitContext */, func); + } + function inContext(flags) { + return (contextFlags & flags) !== 0; + } + function inYieldContext() { + return inContext(4096 /* YieldContext */); + } + function inDisallowInContext() { + return inContext(2048 /* DisallowInContext */); + } + function inDecoratorContext() { + return inContext(8192 /* DecoratorContext */); + } + function inAwaitContext() { + return inContext(16384 /* AwaitContext */); + } + function parseErrorAtCurrentToken(message, arg0) { + parseErrorAt(scanner.getTokenPos(), scanner.getTextPos(), message, arg0); + } + function parseErrorAtPosition(start, length, message, arg0) { + // Don't report another error if it would just be at the same position as the last error. + var lastError = ts.lastOrUndefined(parseDiagnostics); + if (!lastError || start !== lastError.start) { + parseDiagnostics.push(ts.createFileDiagnostic(sourceFile, start, length, message, arg0)); + } + // Mark that we've encountered an error. We'll set an appropriate bit on the next + // node we finish so that it can't be reused incrementally. + parseErrorBeforeNextFinishedNode = true; + } + function parseErrorAt(start, end, message, arg0) { + parseErrorAtPosition(start, end - start, message, arg0); + } + function parseErrorAtRange(range, message, arg0) { + parseErrorAt(range.pos, range.end, message, arg0); + } + function scanError(message, length) { + parseErrorAtPosition(scanner.getTextPos(), length, message); + } + function getNodePos() { + return scanner.getStartPos(); + } + // Use this function to access the current token instead of reading the currentToken + // variable. Since function results aren't narrowed in control flow analysis, this ensures + // that the type checker doesn't make wrong assumptions about the type of the current + // token (e.g. a call to nextToken() changes the current token but the checker doesn't + // reason about this side effect). Mainstream VMs inline simple functions like this, so + // there is no performance penalty. + function token() { + return currentToken; + } + function nextToken() { + return currentToken = scanner.scan(); + } + function reScanGreaterToken() { + return currentToken = scanner.reScanGreaterToken(); + } + function reScanSlashToken() { + return currentToken = scanner.reScanSlashToken(); + } + function reScanTemplateToken() { + return currentToken = scanner.reScanTemplateToken(); + } + function scanJsxIdentifier() { + return currentToken = scanner.scanJsxIdentifier(); + } + function scanJsxText() { + return currentToken = scanner.scanJsxToken(); + } + function scanJsxAttributeValue() { + return currentToken = scanner.scanJsxAttributeValue(); + } + function speculationHelper(callback, isLookAhead) { + // Keep track of the state we'll need to rollback to if lookahead fails (or if the + // caller asked us to always reset our state). + var saveToken = currentToken; + var saveParseDiagnosticsLength = parseDiagnostics.length; + var saveParseErrorBeforeNextFinishedNode = parseErrorBeforeNextFinishedNode; + // Note: it is not actually necessary to save/restore the context flags here. That's + // because the saving/restoring of these flags happens naturally through the recursive + // descent nature of our parser. However, we still store this here just so we can + // assert that invariant holds. + var saveContextFlags = contextFlags; + // If we're only looking ahead, then tell the scanner to only lookahead as well. + // Otherwise, if we're actually speculatively parsing, then tell the scanner to do the + // same. + var result = isLookAhead + ? scanner.lookAhead(callback) + : scanner.tryScan(callback); + ts.Debug.assert(saveContextFlags === contextFlags); + // If our callback returned something 'falsy' or we're just looking ahead, + // then unconditionally restore us to where we were. + if (!result || isLookAhead) { + currentToken = saveToken; + parseDiagnostics.length = saveParseDiagnosticsLength; + parseErrorBeforeNextFinishedNode = saveParseErrorBeforeNextFinishedNode; + } + return result; + } + /** Invokes the provided callback then unconditionally restores the parser to the state it + * was in immediately prior to invoking the callback. The result of invoking the callback + * is returned from this function. + */ + function lookAhead(callback) { + return speculationHelper(callback, /*isLookAhead*/ true); + } + /** Invokes the provided callback. If the callback returns something falsy, then it restores + * the parser to the state it was in immediately prior to invoking the callback. If the + * callback returns something truthy, then the parser state is not rolled back. The result + * of invoking the callback is returned from this function. + */ + function tryParse(callback) { + return speculationHelper(callback, /*isLookAhead*/ false); + } + // Ignore strict mode flag because we will report an error in type checker instead. + function isIdentifier() { + if (token() === 72 /* Identifier */) { + return true; + } + // If we have a 'yield' keyword, and we're in the [yield] context, then 'yield' is + // considered a keyword and is not an identifier. + if (token() === 117 /* YieldKeyword */ && inYieldContext()) { + return false; + } + // If we have a 'await' keyword, and we're in the [Await] context, then 'await' is + // considered a keyword and is not an identifier. + if (token() === 122 /* AwaitKeyword */ && inAwaitContext()) { + return false; + } + return token() > 108 /* LastReservedWord */; + } + function parseExpected(kind, diagnosticMessage, shouldAdvance) { + if (shouldAdvance === void 0) { shouldAdvance = true; } + if (token() === kind) { + if (shouldAdvance) { + nextToken(); + } + return true; + } + // Report specific message if provided with one. Otherwise, report generic fallback message. + if (diagnosticMessage) { + parseErrorAtCurrentToken(diagnosticMessage); + } + else { + parseErrorAtCurrentToken(ts.Diagnostics._0_expected, ts.tokenToString(kind)); + } + return false; + } + function parseOptional(t) { + if (token() === t) { + nextToken(); + return true; + } + return false; + } + function parseOptionalToken(t) { + if (token() === t) { + return parseTokenNode(); + } + return undefined; + } + function parseExpectedToken(t, diagnosticMessage, arg0) { + return parseOptionalToken(t) || + createMissingNode(t, /*reportAtCurrentPosition*/ false, diagnosticMessage || ts.Diagnostics._0_expected, arg0 || ts.tokenToString(t)); + } + function parseTokenNode() { + var node = createNode(token()); + nextToken(); + return finishNode(node); + } + function canParseSemicolon() { + // If there's a real semicolon, then we can always parse it out. + if (token() === 26 /* SemicolonToken */) { + return true; + } + // We can parse out an optional semicolon in ASI cases in the following cases. + return token() === 19 /* CloseBraceToken */ || token() === 1 /* EndOfFileToken */ || scanner.hasPrecedingLineBreak(); + } + function parseSemicolon() { + if (canParseSemicolon()) { + if (token() === 26 /* SemicolonToken */) { + // consume the semicolon if it was explicitly provided. + nextToken(); + } + return true; + } + else { + return parseExpected(26 /* SemicolonToken */); + } + } + function createNode(kind, pos) { + nodeCount++; + var p = pos >= 0 ? pos : scanner.getStartPos(); + return ts.isNodeKind(kind) || kind === 0 /* Unknown */ ? new NodeConstructor(kind, p, p) : + kind === 72 /* Identifier */ ? new IdentifierConstructor(kind, p, p) : + new TokenConstructor(kind, p, p); + } + function createNodeWithJSDoc(kind, pos) { + var node = createNode(kind, pos); + if (scanner.getTokenFlags() & 2 /* PrecedingJSDocComment */) { + addJSDocComment(node); + } + return node; + } + function createNodeArray(elements, pos, end) { + // Since the element list of a node array is typically created by starting with an empty array and + // repeatedly calling push(), the list may not have the optimal memory layout. We invoke slice() for + // small arrays (1 to 4 elements) to give the VM a chance to allocate an optimal representation. + var length = elements.length; + var array = (length >= 1 && length <= 4 ? elements.slice() : elements); + array.pos = pos; + array.end = end === undefined ? scanner.getStartPos() : end; + return array; + } + function finishNode(node, end) { + node.end = end === undefined ? scanner.getStartPos() : end; + if (contextFlags) { + node.flags |= contextFlags; + } + // Keep track on the node if we encountered an error while parsing it. If we did, then + // we cannot reuse the node incrementally. Once we've marked this node, clear out the + // flag so that we don't mark any subsequent nodes. + if (parseErrorBeforeNextFinishedNode) { + parseErrorBeforeNextFinishedNode = false; + node.flags |= 32768 /* ThisNodeHasError */; + } + return node; + } + function createMissingNode(kind, reportAtCurrentPosition, diagnosticMessage, arg0) { + if (reportAtCurrentPosition) { + parseErrorAtPosition(scanner.getStartPos(), 0, diagnosticMessage, arg0); + } + else if (diagnosticMessage) { + parseErrorAtCurrentToken(diagnosticMessage, arg0); + } + var result = createNode(kind); + if (kind === 72 /* Identifier */) { + result.escapedText = ""; + } + else if (ts.isLiteralKind(kind) || ts.isTemplateLiteralKind(kind)) { + result.text = ""; + } + return finishNode(result); + } + function internIdentifier(text) { + var identifier = identifiers.get(text); + if (identifier === undefined) { + identifiers.set(text, identifier = text); + } + return identifier; + } + // An identifier that starts with two underscores has an extra underscore character prepended to it to avoid issues + // with magic property names like '__proto__'. The 'identifiers' object is used to share a single string instance for + // each identifier in order to reduce memory consumption. + function createIdentifier(isIdentifier, diagnosticMessage) { + identifierCount++; + if (isIdentifier) { + var node = createNode(72 /* Identifier */); + // Store original token kind if it is not just an Identifier so we can report appropriate error later in type checker + if (token() !== 72 /* Identifier */) { + node.originalKeywordKind = token(); + } + node.escapedText = ts.escapeLeadingUnderscores(internIdentifier(scanner.getTokenValue())); + nextToken(); + return finishNode(node); + } + // Only for end of file because the error gets reported incorrectly on embedded script tags. + var reportAtCurrentPosition = token() === 1 /* EndOfFileToken */; + return createMissingNode(72 /* Identifier */, reportAtCurrentPosition, diagnosticMessage || ts.Diagnostics.Identifier_expected); + } + function parseIdentifier(diagnosticMessage) { + return createIdentifier(isIdentifier(), diagnosticMessage); + } + function parseIdentifierName(diagnosticMessage) { + return createIdentifier(ts.tokenIsIdentifierOrKeyword(token()), diagnosticMessage); + } + function isLiteralPropertyName() { + return ts.tokenIsIdentifierOrKeyword(token()) || + token() === 10 /* StringLiteral */ || + token() === 8 /* NumericLiteral */; + } + function parsePropertyNameWorker(allowComputedPropertyNames) { + if (token() === 10 /* StringLiteral */ || token() === 8 /* NumericLiteral */) { + var node = parseLiteralNode(); + node.text = internIdentifier(node.text); + return node; + } + if (allowComputedPropertyNames && token() === 22 /* OpenBracketToken */) { + return parseComputedPropertyName(); + } + return parseIdentifierName(); + } + function parsePropertyName() { + return parsePropertyNameWorker(/*allowComputedPropertyNames*/ true); + } + function parseComputedPropertyName() { + // PropertyName [Yield]: + // LiteralPropertyName + // ComputedPropertyName[?Yield] + var node = createNode(149 /* ComputedPropertyName */); + parseExpected(22 /* OpenBracketToken */); + // We parse any expression (including a comma expression). But the grammar + // says that only an assignment expression is allowed, so the grammar checker + // will error if it sees a comma expression. + node.expression = allowInAnd(parseExpression); + parseExpected(23 /* CloseBracketToken */); + return finishNode(node); + } + function parseContextualModifier(t) { + return token() === t && tryParse(nextTokenCanFollowModifier); + } + function nextTokenIsOnSameLineAndCanFollowModifier() { + nextToken(); + if (scanner.hasPrecedingLineBreak()) { + return false; + } + return canFollowModifier(); + } + function nextTokenCanFollowModifier() { + switch (token()) { + case 77 /* ConstKeyword */: + // 'const' is only a modifier if followed by 'enum'. + return nextToken() === 84 /* EnumKeyword */; + case 85 /* ExportKeyword */: + nextToken(); + if (token() === 80 /* DefaultKeyword */) { + return lookAhead(nextTokenCanFollowDefaultKeyword); + } + return token() !== 40 /* AsteriskToken */ && token() !== 119 /* AsKeyword */ && token() !== 18 /* OpenBraceToken */ && canFollowModifier(); + case 80 /* DefaultKeyword */: + return nextTokenCanFollowDefaultKeyword(); + case 116 /* StaticKeyword */: + case 126 /* GetKeyword */: + case 137 /* SetKeyword */: + nextToken(); + return canFollowModifier(); + default: + return nextTokenIsOnSameLineAndCanFollowModifier(); + } + } + function parseAnyContextualModifier() { + return ts.isModifierKind(token()) && tryParse(nextTokenCanFollowModifier); + } + function canFollowModifier() { + return token() === 22 /* OpenBracketToken */ + || token() === 18 /* OpenBraceToken */ + || token() === 40 /* AsteriskToken */ + || token() === 25 /* DotDotDotToken */ + || isLiteralPropertyName(); + } + function nextTokenCanFollowDefaultKeyword() { + nextToken(); + return token() === 76 /* ClassKeyword */ || token() === 90 /* FunctionKeyword */ || + token() === 110 /* InterfaceKeyword */ || + (token() === 118 /* AbstractKeyword */ && lookAhead(nextTokenIsClassKeywordOnSameLine)) || + (token() === 121 /* AsyncKeyword */ && lookAhead(nextTokenIsFunctionKeywordOnSameLine)); + } + // True if positioned at the start of a list element + function isListElement(parsingContext, inErrorRecovery) { + var node = currentNode(parsingContext); + if (node) { + return true; + } + switch (parsingContext) { + case 0 /* SourceElements */: + case 1 /* BlockStatements */: + case 3 /* SwitchClauseStatements */: + // If we're in error recovery, then we don't want to treat ';' as an empty statement. + // The problem is that ';' can show up in far too many contexts, and if we see one + // and assume it's a statement, then we may bail out inappropriately from whatever + // we're parsing. For example, if we have a semicolon in the middle of a class, then + // we really don't want to assume the class is over and we're on a statement in the + // outer module. We just want to consume and move on. + return !(token() === 26 /* SemicolonToken */ && inErrorRecovery) && isStartOfStatement(); + case 2 /* SwitchClauses */: + return token() === 74 /* CaseKeyword */ || token() === 80 /* DefaultKeyword */; + case 4 /* TypeMembers */: + return lookAhead(isTypeMemberStart); + case 5 /* ClassMembers */: + // We allow semicolons as class elements (as specified by ES6) as long as we're + // not in error recovery. If we're in error recovery, we don't want an errant + // semicolon to be treated as a class member (since they're almost always used + // for statements. + return lookAhead(isClassMemberStart) || (token() === 26 /* SemicolonToken */ && !inErrorRecovery); + case 6 /* EnumMembers */: + // Include open bracket computed properties. This technically also lets in indexers, + // which would be a candidate for improved error reporting. + return token() === 22 /* OpenBracketToken */ || isLiteralPropertyName(); + case 12 /* ObjectLiteralMembers */: + switch (token()) { + case 22 /* OpenBracketToken */: + case 40 /* AsteriskToken */: + case 25 /* DotDotDotToken */: + case 24 /* DotToken */: // Not an object literal member, but don't want to close the object (see `tests/cases/fourslash/completionsDotInObjectLiteral.ts`) + return true; + default: + return isLiteralPropertyName(); + } + case 18 /* RestProperties */: + return isLiteralPropertyName(); + case 9 /* ObjectBindingElements */: + return token() === 22 /* OpenBracketToken */ || token() === 25 /* DotDotDotToken */ || isLiteralPropertyName(); + case 7 /* HeritageClauseElement */: + // If we see `{ ... }` then only consume it as an expression if it is followed by `,` or `{` + // That way we won't consume the body of a class in its heritage clause. + if (token() === 18 /* OpenBraceToken */) { + return lookAhead(isValidHeritageClauseObjectLiteral); + } + if (!inErrorRecovery) { + return isStartOfLeftHandSideExpression() && !isHeritageClauseExtendsOrImplementsKeyword(); + } + else { + // If we're in error recovery we tighten up what we're willing to match. + // That way we don't treat something like "this" as a valid heritage clause + // element during recovery. + return isIdentifier() && !isHeritageClauseExtendsOrImplementsKeyword(); + } + case 8 /* VariableDeclarations */: + return isIdentifierOrPattern(); + case 10 /* ArrayBindingElements */: + return token() === 27 /* CommaToken */ || token() === 25 /* DotDotDotToken */ || isIdentifierOrPattern(); + case 19 /* TypeParameters */: + return isIdentifier(); + case 15 /* ArrayLiteralMembers */: + switch (token()) { + case 27 /* CommaToken */: + case 24 /* DotToken */: // Not an array literal member, but don't want to close the array (see `tests/cases/fourslash/completionsDotInArrayLiteralInObjectLiteral.ts`) + return true; + } + // falls through + case 11 /* ArgumentExpressions */: + return token() === 25 /* DotDotDotToken */ || isStartOfExpression(); + case 16 /* Parameters */: + return isStartOfParameter(/*isJSDocParameter*/ false); + case 17 /* JSDocParameters */: + return isStartOfParameter(/*isJSDocParameter*/ true); + case 20 /* TypeArguments */: + case 21 /* TupleElementTypes */: + return token() === 27 /* CommaToken */ || isStartOfType(); + case 22 /* HeritageClauses */: + return isHeritageClause(); + case 23 /* ImportOrExportSpecifiers */: + return ts.tokenIsIdentifierOrKeyword(token()); + case 13 /* JsxAttributes */: + return ts.tokenIsIdentifierOrKeyword(token()) || token() === 18 /* OpenBraceToken */; + case 14 /* JsxChildren */: + return true; + } + return ts.Debug.fail("Non-exhaustive case in 'isListElement'."); + } + function isValidHeritageClauseObjectLiteral() { + ts.Debug.assert(token() === 18 /* OpenBraceToken */); + if (nextToken() === 19 /* CloseBraceToken */) { + // if we see "extends {}" then only treat the {} as what we're extending (and not + // the class body) if we have: + // + // extends {} { + // extends {}, + // extends {} extends + // extends {} implements + var next = nextToken(); + return next === 27 /* CommaToken */ || next === 18 /* OpenBraceToken */ || next === 86 /* ExtendsKeyword */ || next === 109 /* ImplementsKeyword */; + } + return true; + } + function nextTokenIsIdentifier() { + nextToken(); + return isIdentifier(); + } + function nextTokenIsIdentifierOrKeyword() { + nextToken(); + return ts.tokenIsIdentifierOrKeyword(token()); + } + function nextTokenIsIdentifierOrKeywordOrGreaterThan() { + nextToken(); + return ts.tokenIsIdentifierOrKeywordOrGreaterThan(token()); + } + function isHeritageClauseExtendsOrImplementsKeyword() { + if (token() === 109 /* ImplementsKeyword */ || + token() === 86 /* ExtendsKeyword */) { + return lookAhead(nextTokenIsStartOfExpression); + } + return false; + } + function nextTokenIsStartOfExpression() { + nextToken(); + return isStartOfExpression(); + } + function nextTokenIsStartOfType() { + nextToken(); + return isStartOfType(); + } + // True if positioned at a list terminator + function isListTerminator(kind) { + if (token() === 1 /* EndOfFileToken */) { + // Being at the end of the file ends all lists. + return true; + } + switch (kind) { + case 1 /* BlockStatements */: + case 2 /* SwitchClauses */: + case 4 /* TypeMembers */: + case 5 /* ClassMembers */: + case 6 /* EnumMembers */: + case 12 /* ObjectLiteralMembers */: + case 9 /* ObjectBindingElements */: + case 23 /* ImportOrExportSpecifiers */: + return token() === 19 /* CloseBraceToken */; + case 3 /* SwitchClauseStatements */: + return token() === 19 /* CloseBraceToken */ || token() === 74 /* CaseKeyword */ || token() === 80 /* DefaultKeyword */; + case 7 /* HeritageClauseElement */: + return token() === 18 /* OpenBraceToken */ || token() === 86 /* ExtendsKeyword */ || token() === 109 /* ImplementsKeyword */; + case 8 /* VariableDeclarations */: + return isVariableDeclaratorListTerminator(); + case 19 /* TypeParameters */: + // Tokens other than '>' are here for better error recovery + return token() === 30 /* GreaterThanToken */ || token() === 20 /* OpenParenToken */ || token() === 18 /* OpenBraceToken */ || token() === 86 /* ExtendsKeyword */ || token() === 109 /* ImplementsKeyword */; + case 11 /* ArgumentExpressions */: + // Tokens other than ')' are here for better error recovery + return token() === 21 /* CloseParenToken */ || token() === 26 /* SemicolonToken */; + case 15 /* ArrayLiteralMembers */: + case 21 /* TupleElementTypes */: + case 10 /* ArrayBindingElements */: + return token() === 23 /* CloseBracketToken */; + case 17 /* JSDocParameters */: + case 16 /* Parameters */: + case 18 /* RestProperties */: + // Tokens other than ')' and ']' (the latter for index signatures) are here for better error recovery + return token() === 21 /* CloseParenToken */ || token() === 23 /* CloseBracketToken */ /*|| token === SyntaxKind.OpenBraceToken*/; + case 20 /* TypeArguments */: + // All other tokens should cause the type-argument to terminate except comma token + return token() !== 27 /* CommaToken */; + case 22 /* HeritageClauses */: + return token() === 18 /* OpenBraceToken */ || token() === 19 /* CloseBraceToken */; + case 13 /* JsxAttributes */: + return token() === 30 /* GreaterThanToken */ || token() === 42 /* SlashToken */; + case 14 /* JsxChildren */: + return token() === 28 /* LessThanToken */ && lookAhead(nextTokenIsSlash); + default: + return false; + } + } + function isVariableDeclaratorListTerminator() { + // If we can consume a semicolon (either explicitly, or with ASI), then consider us done + // with parsing the list of variable declarators. + if (canParseSemicolon()) { + return true; + } + // in the case where we're parsing the variable declarator of a 'for-in' statement, we + // are done if we see an 'in' keyword in front of us. Same with for-of + if (isInOrOfKeyword(token())) { + return true; + } + // ERROR RECOVERY TWEAK: + // For better error recovery, if we see an '=>' then we just stop immediately. We've got an + // arrow function here and it's going to be very unlikely that we'll resynchronize and get + // another variable declaration. + if (token() === 37 /* EqualsGreaterThanToken */) { + return true; + } + // Keep trying to parse out variable declarators. + return false; + } + // True if positioned at element or terminator of the current list or any enclosing list + function isInSomeParsingContext() { + for (var kind = 0; kind < 24 /* Count */; kind++) { + if (parsingContext & (1 << kind)) { + if (isListElement(kind, /*inErrorRecovery*/ true) || isListTerminator(kind)) { + return true; + } + } + } + return false; + } + // Parses a list of elements + function parseList(kind, parseElement) { + var saveParsingContext = parsingContext; + parsingContext |= 1 << kind; + var list = []; + var listPos = getNodePos(); + while (!isListTerminator(kind)) { + if (isListElement(kind, /*inErrorRecovery*/ false)) { + var element = parseListElement(kind, parseElement); + list.push(element); + continue; + } + if (abortParsingListOrMoveToNextToken(kind)) { + break; + } + } + parsingContext = saveParsingContext; + return createNodeArray(list, listPos); + } + function parseListElement(parsingContext, parseElement) { + var node = currentNode(parsingContext); + if (node) { + return consumeNode(node); + } + return parseElement(); + } + function currentNode(parsingContext) { + // If there is an outstanding parse error that we've encountered, but not attached to + // some node, then we cannot get a node from the old source tree. This is because we + // want to mark the next node we encounter as being unusable. + // + // Note: This may be too conservative. Perhaps we could reuse the node and set the bit + // on it (or its leftmost child) as having the error. For now though, being conservative + // is nice and likely won't ever affect perf. + if (parseErrorBeforeNextFinishedNode) { + return undefined; + } + if (!syntaxCursor) { + // if we don't have a cursor, we could never return a node from the old tree. + return undefined; + } + var node = syntaxCursor.currentNode(scanner.getStartPos()); + // Can't reuse a missing node. + if (ts.nodeIsMissing(node)) { + return undefined; + } + // Can't reuse a node that intersected the change range. + if (node.intersectsChange) { + return undefined; + } + // Can't reuse a node that contains a parse error. This is necessary so that we + // produce the same set of errors again. + if (ts.containsParseError(node)) { + return undefined; + } + // We can only reuse a node if it was parsed under the same strict mode that we're + // currently in. i.e. if we originally parsed a node in non-strict mode, but then + // the user added 'using strict' at the top of the file, then we can't use that node + // again as the presence of strict mode may cause us to parse the tokens in the file + // differently. + // + // Note: we *can* reuse tokens when the strict mode changes. That's because tokens + // are unaffected by strict mode. It's just the parser will decide what to do with it + // differently depending on what mode it is in. + // + // This also applies to all our other context flags as well. + var nodeContextFlags = node.flags & 12679168 /* ContextFlags */; + if (nodeContextFlags !== contextFlags) { + return undefined; + } + // Ok, we have a node that looks like it could be reused. Now verify that it is valid + // in the current list parsing context that we're currently at. + if (!canReuseNode(node, parsingContext)) { + return undefined; + } + if (node.jsDocCache) { + // jsDocCache may include tags from parent nodes, which might have been modified. + node.jsDocCache = undefined; + } + return node; + } + function consumeNode(node) { + // Move the scanner so it is after the node we just consumed. + scanner.setTextPos(node.end); + nextToken(); + return node; + } + function canReuseNode(node, parsingContext) { + switch (parsingContext) { + case 5 /* ClassMembers */: + return isReusableClassMember(node); + case 2 /* SwitchClauses */: + return isReusableSwitchClause(node); + case 0 /* SourceElements */: + case 1 /* BlockStatements */: + case 3 /* SwitchClauseStatements */: + return isReusableStatement(node); + case 6 /* EnumMembers */: + return isReusableEnumMember(node); + case 4 /* TypeMembers */: + return isReusableTypeMember(node); + case 8 /* VariableDeclarations */: + return isReusableVariableDeclaration(node); + case 17 /* JSDocParameters */: + case 16 /* Parameters */: + return isReusableParameter(node); + case 18 /* RestProperties */: + return false; + // Any other lists we do not care about reusing nodes in. But feel free to add if + // you can do so safely. Danger areas involve nodes that may involve speculative + // parsing. If speculative parsing is involved with the node, then the range the + // parser reached while looking ahead might be in the edited range (see the example + // in canReuseVariableDeclaratorNode for a good case of this). + case 22 /* HeritageClauses */: + // This would probably be safe to reuse. There is no speculative parsing with + // heritage clauses. + case 19 /* TypeParameters */: + // This would probably be safe to reuse. There is no speculative parsing with + // type parameters. Note that that's because type *parameters* only occur in + // unambiguous *type* contexts. While type *arguments* occur in very ambiguous + // *expression* contexts. + case 21 /* TupleElementTypes */: + // This would probably be safe to reuse. There is no speculative parsing with + // tuple types. + // Technically, type argument list types are probably safe to reuse. While + // speculative parsing is involved with them (since type argument lists are only + // produced from speculative parsing a < as a type argument list), we only have + // the types because speculative parsing succeeded. Thus, the lookahead never + // went past the end of the list and rewound. + case 20 /* TypeArguments */: + // Note: these are almost certainly not safe to ever reuse. Expressions commonly + // need a large amount of lookahead, and we should not reuse them as they may + // have actually intersected the edit. + case 11 /* ArgumentExpressions */: + // This is not safe to reuse for the same reason as the 'AssignmentExpression' + // cases. i.e. a property assignment may end with an expression, and thus might + // have lookahead far beyond it's old node. + case 12 /* ObjectLiteralMembers */: + // This is probably not safe to reuse. There can be speculative parsing with + // type names in a heritage clause. There can be generic names in the type + // name list, and there can be left hand side expressions (which can have type + // arguments.) + case 7 /* HeritageClauseElement */: + // Perhaps safe to reuse, but it's unlikely we'd see more than a dozen attributes + // on any given element. Same for children. + case 13 /* JsxAttributes */: + case 14 /* JsxChildren */: + } + return false; + } + function isReusableClassMember(node) { + if (node) { + switch (node.kind) { + case 157 /* Constructor */: + case 162 /* IndexSignature */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 154 /* PropertyDeclaration */: + case 217 /* SemicolonClassElement */: + return true; + case 156 /* MethodDeclaration */: + // Method declarations are not necessarily reusable. An object-literal + // may have a method calls "constructor(...)" and we must reparse that + // into an actual .ConstructorDeclaration. + var methodDeclaration = node; + var nameIsConstructor = methodDeclaration.name.kind === 72 /* Identifier */ && + methodDeclaration.name.originalKeywordKind === 124 /* ConstructorKeyword */; + return !nameIsConstructor; + } + } + return false; + } + function isReusableSwitchClause(node) { + if (node) { + switch (node.kind) { + case 271 /* CaseClause */: + case 272 /* DefaultClause */: + return true; + } + } + return false; + } + function isReusableStatement(node) { + if (node) { + switch (node.kind) { + case 239 /* FunctionDeclaration */: + case 219 /* VariableStatement */: + case 218 /* Block */: + case 222 /* IfStatement */: + case 221 /* ExpressionStatement */: + case 234 /* ThrowStatement */: + case 230 /* ReturnStatement */: + case 232 /* SwitchStatement */: + case 229 /* BreakStatement */: + case 228 /* ContinueStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + case 225 /* ForStatement */: + case 224 /* WhileStatement */: + case 231 /* WithStatement */: + case 220 /* EmptyStatement */: + case 235 /* TryStatement */: + case 233 /* LabeledStatement */: + case 223 /* DoStatement */: + case 236 /* DebuggerStatement */: + case 249 /* ImportDeclaration */: + case 248 /* ImportEqualsDeclaration */: + case 255 /* ExportDeclaration */: + case 254 /* ExportAssignment */: + case 244 /* ModuleDeclaration */: + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + case 243 /* EnumDeclaration */: + case 242 /* TypeAliasDeclaration */: + return true; + } + } + return false; + } + function isReusableEnumMember(node) { + return node.kind === 278 /* EnumMember */; + } + function isReusableTypeMember(node) { + if (node) { + switch (node.kind) { + case 161 /* ConstructSignature */: + case 155 /* MethodSignature */: + case 162 /* IndexSignature */: + case 153 /* PropertySignature */: + case 160 /* CallSignature */: + return true; + } + } + return false; + } + function isReusableVariableDeclaration(node) { + if (node.kind !== 237 /* VariableDeclaration */) { + return false; + } + // Very subtle incremental parsing bug. Consider the following code: + // + // let v = new List < A, B + // + // This is actually legal code. It's a list of variable declarators "v = new List() + // + // then we have a problem. "v = new List= 0) { + // Always preserve a trailing comma by marking it on the NodeArray + result.hasTrailingComma = true; + } + return result; + } + function createMissingList() { + var list = createNodeArray([], getNodePos()); + list.isMissingList = true; + return list; + } + function isMissingList(arr) { + return !!arr.isMissingList; + } + function parseBracketedList(kind, parseElement, open, close) { + if (parseExpected(open)) { + var result = parseDelimitedList(kind, parseElement); + parseExpected(close); + return result; + } + return createMissingList(); + } + function parseEntityName(allowReservedWords, diagnosticMessage) { + var entity = allowReservedWords ? parseIdentifierName(diagnosticMessage) : parseIdentifier(diagnosticMessage); + var dotPos = scanner.getStartPos(); + while (parseOptional(24 /* DotToken */)) { + if (token() === 28 /* LessThanToken */) { + // the entity is part of a JSDoc-style generic, so record the trailing dot for later error reporting + entity.jsdocDotPos = dotPos; + break; + } + dotPos = scanner.getStartPos(); + entity = createQualifiedName(entity, parseRightSideOfDot(allowReservedWords)); + } + return entity; + } + function createQualifiedName(entity, name) { + var node = createNode(148 /* QualifiedName */, entity.pos); + node.left = entity; + node.right = name; + return finishNode(node); + } + function parseRightSideOfDot(allowIdentifierNames) { + // Technically a keyword is valid here as all identifiers and keywords are identifier names. + // However, often we'll encounter this in error situations when the identifier or keyword + // is actually starting another valid construct. + // + // So, we check for the following specific case: + // + // name. + // identifierOrKeyword identifierNameOrKeyword + // + // Note: the newlines are important here. For example, if that above code + // were rewritten into: + // + // name.identifierOrKeyword + // identifierNameOrKeyword + // + // Then we would consider it valid. That's because ASI would take effect and + // the code would be implicitly: "name.identifierOrKeyword; identifierNameOrKeyword". + // In the first case though, ASI will not take effect because there is not a + // line terminator after the identifier or keyword. + if (scanner.hasPrecedingLineBreak() && ts.tokenIsIdentifierOrKeyword(token())) { + var matchesPattern = lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine); + if (matchesPattern) { + // Report that we need an identifier. However, report it right after the dot, + // and not on the next token. This is because the next token might actually + // be an identifier and the error would be quite confusing. + return createMissingNode(72 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Identifier_expected); + } + } + return allowIdentifierNames ? parseIdentifierName() : parseIdentifier(); + } + function parseTemplateExpression() { + var template = createNode(206 /* TemplateExpression */); + template.head = parseTemplateHead(); + ts.Debug.assert(template.head.kind === 15 /* TemplateHead */, "Template head has wrong token kind"); + var list = []; + var listPos = getNodePos(); + do { + list.push(parseTemplateSpan()); + } while (ts.last(list).literal.kind === 16 /* TemplateMiddle */); + template.templateSpans = createNodeArray(list, listPos); + return finishNode(template); + } + function parseTemplateSpan() { + var span = createNode(216 /* TemplateSpan */); + span.expression = allowInAnd(parseExpression); + var literal; + if (token() === 19 /* CloseBraceToken */) { + reScanTemplateToken(); + literal = parseTemplateMiddleOrTemplateTail(); + } + else { + literal = parseExpectedToken(17 /* TemplateTail */, ts.Diagnostics._0_expected, ts.tokenToString(19 /* CloseBraceToken */)); + } + span.literal = literal; + return finishNode(span); + } + function parseLiteralNode() { + return parseLiteralLikeNode(token()); + } + function parseTemplateHead() { + var fragment = parseLiteralLikeNode(token()); + ts.Debug.assert(fragment.kind === 15 /* TemplateHead */, "Template head has wrong token kind"); + return fragment; + } + function parseTemplateMiddleOrTemplateTail() { + var fragment = parseLiteralLikeNode(token()); + ts.Debug.assert(fragment.kind === 16 /* TemplateMiddle */ || fragment.kind === 17 /* TemplateTail */, "Template fragment has wrong token kind"); + return fragment; + } + function parseLiteralLikeNode(kind) { + var node = createNode(kind); + node.text = scanner.getTokenValue(); + if (scanner.hasExtendedUnicodeEscape()) { + node.hasExtendedUnicodeEscape = true; + } + if (scanner.isUnterminated()) { + node.isUnterminated = true; + } + // Octal literals are not allowed in strict mode or ES5 + // Note that theoretically the following condition would hold true literals like 009, + // which is not octal.But because of how the scanner separates the tokens, we would + // never get a token like this. Instead, we would get 00 and 9 as two separate tokens. + // We also do not need to check for negatives because any prefix operator would be part of a + // parent unary expression. + if (node.kind === 8 /* NumericLiteral */) { + node.numericLiteralFlags = scanner.getTokenFlags() & 1008 /* NumericLiteralFlags */; + } + nextToken(); + finishNode(node); + return node; + } + // TYPES + function parseTypeReference() { + var node = createNode(164 /* TypeReference */); + node.typeName = parseEntityName(/*allowReservedWords*/ true, ts.Diagnostics.Type_expected); + if (!scanner.hasPrecedingLineBreak() && token() === 28 /* LessThanToken */) { + node.typeArguments = parseBracketedList(20 /* TypeArguments */, parseType, 28 /* LessThanToken */, 30 /* GreaterThanToken */); + } + return finishNode(node); + } + // If true, we should abort parsing an error function. + function typeHasArrowFunctionBlockingParseError(node) { + switch (node.kind) { + case 164 /* TypeReference */: + return ts.nodeIsMissing(node.typeName); + case 165 /* FunctionType */: + case 166 /* ConstructorType */: { + var _a = node, parameters = _a.parameters, type = _a.type; + return isMissingList(parameters) || typeHasArrowFunctionBlockingParseError(type); + } + case 177 /* ParenthesizedType */: + return typeHasArrowFunctionBlockingParseError(node.type); + default: + return false; + } + } + function parseThisTypePredicate(lhs) { + nextToken(); + var node = createNode(163 /* TypePredicate */, lhs.pos); + node.parameterName = lhs; + node.type = parseType(); + return finishNode(node); + } + function parseThisTypeNode() { + var node = createNode(178 /* ThisType */); + nextToken(); + return finishNode(node); + } + function parseJSDocAllType(postFixEquals) { + var result = createNode(284 /* JSDocAllType */); + if (postFixEquals) { + return createPostfixType(288 /* JSDocOptionalType */, result); + } + else { + nextToken(); + } + return finishNode(result); + } + function parseJSDocNonNullableType() { + var result = createNode(287 /* JSDocNonNullableType */); + nextToken(); + result.type = parseNonArrayType(); + return finishNode(result); + } + function parseJSDocUnknownOrNullableType() { + var pos = scanner.getStartPos(); + // skip the ? + nextToken(); + // Need to lookahead to decide if this is a nullable or unknown type. + // Here are cases where we'll pick the unknown type: + // + // Foo(?, + // { a: ? } + // Foo(?) + // Foo + // Foo(?= + // (?| + if (token() === 27 /* CommaToken */ || + token() === 19 /* CloseBraceToken */ || + token() === 21 /* CloseParenToken */ || + token() === 30 /* GreaterThanToken */ || + token() === 59 /* EqualsToken */ || + token() === 50 /* BarToken */) { + var result = createNode(285 /* JSDocUnknownType */, pos); + return finishNode(result); + } + else { + var result = createNode(286 /* JSDocNullableType */, pos); + result.type = parseType(); + return finishNode(result); + } + } + function parseJSDocFunctionType() { + if (lookAhead(nextTokenIsOpenParen)) { + var result = createNodeWithJSDoc(289 /* JSDocFunctionType */); + nextToken(); + fillSignature(57 /* ColonToken */, 4 /* Type */ | 32 /* JSDoc */, result); + return finishNode(result); + } + var node = createNode(164 /* TypeReference */); + node.typeName = parseIdentifierName(); + return finishNode(node); + } + function parseJSDocParameter() { + var parameter = createNode(151 /* Parameter */); + if (token() === 100 /* ThisKeyword */ || token() === 95 /* NewKeyword */) { + parameter.name = parseIdentifierName(); + parseExpected(57 /* ColonToken */); + } + parameter.type = parseJSDocType(); + return finishNode(parameter); + } + function parseJSDocType() { + scanner.setInJSDocType(true); + var dotdotdot = parseOptionalToken(25 /* DotDotDotToken */); + var type = parseTypeOrTypePredicate(); + scanner.setInJSDocType(false); + if (dotdotdot) { + var variadic = createNode(290 /* JSDocVariadicType */, dotdotdot.pos); + variadic.type = type; + type = finishNode(variadic); + } + if (token() === 59 /* EqualsToken */) { + return createPostfixType(288 /* JSDocOptionalType */, type); + } + return type; + } + function parseTypeQuery() { + var node = createNode(167 /* TypeQuery */); + parseExpected(104 /* TypeOfKeyword */); + node.exprName = parseEntityName(/*allowReservedWords*/ true); + return finishNode(node); + } + function parseTypeParameter() { + var node = createNode(150 /* TypeParameter */); + node.name = parseIdentifier(); + if (parseOptional(86 /* ExtendsKeyword */)) { + // It's not uncommon for people to write improper constraints to a generic. If the + // user writes a constraint that is an expression and not an actual type, then parse + // it out as an expression (so we can recover well), but report that a type is needed + // instead. + if (isStartOfType() || !isStartOfExpression()) { + node.constraint = parseType(); + } + else { + // It was not a type, and it looked like an expression. Parse out an expression + // here so we recover well. Note: it is important that we call parseUnaryExpression + // and not parseExpression here. If the user has: + // + // + // + // We do *not* want to consume the `>` as we're consuming the expression for "". + node.expression = parseUnaryExpressionOrHigher(); + } + } + if (parseOptional(59 /* EqualsToken */)) { + node.default = parseType(); + } + return finishNode(node); + } + function parseTypeParameters() { + if (token() === 28 /* LessThanToken */) { + return parseBracketedList(19 /* TypeParameters */, parseTypeParameter, 28 /* LessThanToken */, 30 /* GreaterThanToken */); + } + } + function parseParameterType() { + if (parseOptional(57 /* ColonToken */)) { + return parseType(); + } + return undefined; + } + function isStartOfParameter(isJSDocParameter) { + return token() === 25 /* DotDotDotToken */ || + isIdentifierOrPattern() || + ts.isModifierKind(token()) || + token() === 58 /* AtToken */ || + isStartOfType(/*inStartOfParameter*/ !isJSDocParameter); + } + function parseParameter() { + var node = createNodeWithJSDoc(151 /* Parameter */); + if (token() === 100 /* ThisKeyword */) { + node.name = createIdentifier(/*isIdentifier*/ true); + node.type = parseParameterType(); + return finishNode(node); + } + node.decorators = parseDecorators(); + node.modifiers = parseModifiers(); + node.dotDotDotToken = parseOptionalToken(25 /* DotDotDotToken */); + // FormalParameter [Yield,Await]: + // BindingElement[?Yield,?Await] + node.name = parseIdentifierOrPattern(); + if (ts.getFullWidth(node.name) === 0 && !ts.hasModifiers(node) && ts.isModifierKind(token())) { + // in cases like + // 'use strict' + // function foo(static) + // isParameter('static') === true, because of isModifier('static') + // however 'static' is not a legal identifier in a strict mode. + // so result of this function will be ParameterDeclaration (flags = 0, name = missing, type = undefined, initializer = undefined) + // and current token will not change => parsing of the enclosing parameter list will last till the end of time (or OOM) + // to avoid this we'll advance cursor to the next token. + nextToken(); + } + node.questionToken = parseOptionalToken(56 /* QuestionToken */); + node.type = parseParameterType(); + node.initializer = parseInitializer(); + return finishNode(node); + } + /** + * Note: If returnToken is EqualsGreaterThanToken, `signature.type` will always be defined. + * @returns If return type parsing succeeds + */ + function fillSignature(returnToken, flags, signature) { + if (!(flags & 32 /* JSDoc */)) { + signature.typeParameters = parseTypeParameters(); + } + var parametersParsedSuccessfully = parseParameterList(signature, flags); + if (shouldParseReturnType(returnToken, !!(flags & 4 /* Type */))) { + signature.type = parseTypeOrTypePredicate(); + if (typeHasArrowFunctionBlockingParseError(signature.type)) + return false; + } + return parametersParsedSuccessfully; + } + function shouldParseReturnType(returnToken, isType) { + if (returnToken === 37 /* EqualsGreaterThanToken */) { + parseExpected(returnToken); + return true; + } + else if (parseOptional(57 /* ColonToken */)) { + return true; + } + else if (isType && token() === 37 /* EqualsGreaterThanToken */) { + // This is easy to get backward, especially in type contexts, so parse the type anyway + parseErrorAtCurrentToken(ts.Diagnostics._0_expected, ts.tokenToString(57 /* ColonToken */)); + nextToken(); + return true; + } + return false; + } + // Returns true on success. + function parseParameterList(signature, flags) { + // FormalParameters [Yield,Await]: (modified) + // [empty] + // FormalParameterList[?Yield,Await] + // + // FormalParameter[Yield,Await]: (modified) + // BindingElement[?Yield,Await] + // + // BindingElement [Yield,Await]: (modified) + // SingleNameBinding[?Yield,?Await] + // BindingPattern[?Yield,?Await]Initializer [In, ?Yield,?Await] opt + // + // SingleNameBinding [Yield,Await]: + // BindingIdentifier[?Yield,?Await]Initializer [In, ?Yield,?Await] opt + if (!parseExpected(20 /* OpenParenToken */)) { + signature.parameters = createMissingList(); + return false; + } + var savedYieldContext = inYieldContext(); + var savedAwaitContext = inAwaitContext(); + setYieldContext(!!(flags & 1 /* Yield */)); + setAwaitContext(!!(flags & 2 /* Await */)); + signature.parameters = flags & 32 /* JSDoc */ ? + parseDelimitedList(17 /* JSDocParameters */, parseJSDocParameter) : + parseDelimitedList(16 /* Parameters */, parseParameter); + setYieldContext(savedYieldContext); + setAwaitContext(savedAwaitContext); + return parseExpected(21 /* CloseParenToken */); + } + function parseTypeMemberSemicolon() { + // We allow type members to be separated by commas or (possibly ASI) semicolons. + // First check if it was a comma. If so, we're done with the member. + if (parseOptional(27 /* CommaToken */)) { + return; + } + // Didn't have a comma. We must have a (possible ASI) semicolon. + parseSemicolon(); + } + function parseSignatureMember(kind) { + var node = createNodeWithJSDoc(kind); + if (kind === 161 /* ConstructSignature */) { + parseExpected(95 /* NewKeyword */); + } + fillSignature(57 /* ColonToken */, 4 /* Type */, node); + parseTypeMemberSemicolon(); + return finishNode(node); + } + function isIndexSignature() { + return token() === 22 /* OpenBracketToken */ && lookAhead(isUnambiguouslyIndexSignature); + } + function isUnambiguouslyIndexSignature() { + // The only allowed sequence is: + // + // [id: + // + // However, for error recovery, we also check the following cases: + // + // [... + // [id, + // [id?, + // [id?: + // [id?] + // [public id + // [private id + // [protected id + // [] + // + nextToken(); + if (token() === 25 /* DotDotDotToken */ || token() === 23 /* CloseBracketToken */) { + return true; + } + if (ts.isModifierKind(token())) { + nextToken(); + if (isIdentifier()) { + return true; + } + } + else if (!isIdentifier()) { + return false; + } + else { + // Skip the identifier + nextToken(); + } + // A colon signifies a well formed indexer + // A comma should be a badly formed indexer because comma expressions are not allowed + // in computed properties. + if (token() === 57 /* ColonToken */ || token() === 27 /* CommaToken */) { + return true; + } + // Question mark could be an indexer with an optional property, + // or it could be a conditional expression in a computed property. + if (token() !== 56 /* QuestionToken */) { + return false; + } + // If any of the following tokens are after the question mark, it cannot + // be a conditional expression, so treat it as an indexer. + nextToken(); + return token() === 57 /* ColonToken */ || token() === 27 /* CommaToken */ || token() === 23 /* CloseBracketToken */; + } + function parseIndexSignatureDeclaration(node) { + node.kind = 162 /* IndexSignature */; + node.parameters = parseBracketedList(16 /* Parameters */, parseParameter, 22 /* OpenBracketToken */, 23 /* CloseBracketToken */); + node.type = parseTypeAnnotation(); + parseTypeMemberSemicolon(); + return finishNode(node); + } + function parsePropertyOrMethodSignature(node) { + node.name = parsePropertyName(); + node.questionToken = parseOptionalToken(56 /* QuestionToken */); + if (token() === 20 /* OpenParenToken */ || token() === 28 /* LessThanToken */) { + node.kind = 155 /* MethodSignature */; + // Method signatures don't exist in expression contexts. So they have neither + // [Yield] nor [Await] + fillSignature(57 /* ColonToken */, 4 /* Type */, node); + } + else { + node.kind = 153 /* PropertySignature */; + node.type = parseTypeAnnotation(); + if (token() === 59 /* EqualsToken */) { + // Although type literal properties cannot not have initializers, we attempt + // to parse an initializer so we can report in the checker that an interface + // property or type literal property cannot have an initializer. + node.initializer = parseInitializer(); + } + } + parseTypeMemberSemicolon(); + return finishNode(node); + } + function isTypeMemberStart() { + // Return true if we have the start of a signature member + if (token() === 20 /* OpenParenToken */ || token() === 28 /* LessThanToken */) { + return true; + } + var idToken = false; + // Eat up all modifiers, but hold on to the last one in case it is actually an identifier + while (ts.isModifierKind(token())) { + idToken = true; + nextToken(); + } + // Index signatures and computed property names are type members + if (token() === 22 /* OpenBracketToken */) { + return true; + } + // Try to get the first property-like token following all modifiers + if (isLiteralPropertyName()) { + idToken = true; + nextToken(); + } + // If we were able to get any potential identifier, check that it is + // the start of a member declaration + if (idToken) { + return token() === 20 /* OpenParenToken */ || + token() === 28 /* LessThanToken */ || + token() === 56 /* QuestionToken */ || + token() === 57 /* ColonToken */ || + token() === 27 /* CommaToken */ || + canParseSemicolon(); + } + return false; + } + function parseTypeMember() { + if (token() === 20 /* OpenParenToken */ || token() === 28 /* LessThanToken */) { + return parseSignatureMember(160 /* CallSignature */); + } + if (token() === 95 /* NewKeyword */ && lookAhead(nextTokenIsOpenParenOrLessThan)) { + return parseSignatureMember(161 /* ConstructSignature */); + } + var node = createNodeWithJSDoc(0 /* Unknown */); + node.modifiers = parseModifiers(); + if (isIndexSignature()) { + return parseIndexSignatureDeclaration(node); + } + return parsePropertyOrMethodSignature(node); + } + function nextTokenIsOpenParenOrLessThan() { + nextToken(); + return token() === 20 /* OpenParenToken */ || token() === 28 /* LessThanToken */; + } + function nextTokenIsDot() { + return nextToken() === 24 /* DotToken */; + } + function nextTokenIsOpenParenOrLessThanOrDot() { + switch (nextToken()) { + case 20 /* OpenParenToken */: + case 28 /* LessThanToken */: + case 24 /* DotToken */: + return true; + } + return false; + } + function parseTypeLiteral() { + var node = createNode(168 /* TypeLiteral */); + node.members = parseObjectTypeMembers(); + return finishNode(node); + } + function parseObjectTypeMembers() { + var members; + if (parseExpected(18 /* OpenBraceToken */)) { + members = parseList(4 /* TypeMembers */, parseTypeMember); + parseExpected(19 /* CloseBraceToken */); + } + else { + members = createMissingList(); + } + return members; + } + function isStartOfMappedType() { + nextToken(); + if (token() === 38 /* PlusToken */ || token() === 39 /* MinusToken */) { + return nextToken() === 133 /* ReadonlyKeyword */; + } + if (token() === 133 /* ReadonlyKeyword */) { + nextToken(); + } + return token() === 22 /* OpenBracketToken */ && nextTokenIsIdentifier() && nextToken() === 93 /* InKeyword */; + } + function parseMappedTypeParameter() { + var node = createNode(150 /* TypeParameter */); + node.name = parseIdentifier(); + parseExpected(93 /* InKeyword */); + node.constraint = parseType(); + return finishNode(node); + } + function parseMappedType() { + var node = createNode(181 /* MappedType */); + parseExpected(18 /* OpenBraceToken */); + if (token() === 133 /* ReadonlyKeyword */ || token() === 38 /* PlusToken */ || token() === 39 /* MinusToken */) { + node.readonlyToken = parseTokenNode(); + if (node.readonlyToken.kind !== 133 /* ReadonlyKeyword */) { + parseExpectedToken(133 /* ReadonlyKeyword */); + } + } + parseExpected(22 /* OpenBracketToken */); + node.typeParameter = parseMappedTypeParameter(); + parseExpected(23 /* CloseBracketToken */); + if (token() === 56 /* QuestionToken */ || token() === 38 /* PlusToken */ || token() === 39 /* MinusToken */) { + node.questionToken = parseTokenNode(); + if (node.questionToken.kind !== 56 /* QuestionToken */) { + parseExpectedToken(56 /* QuestionToken */); + } + } + node.type = parseTypeAnnotation(); + parseSemicolon(); + parseExpected(19 /* CloseBraceToken */); + return finishNode(node); + } + function parseTupleElementType() { + var pos = getNodePos(); + if (parseOptional(25 /* DotDotDotToken */)) { + var node = createNode(172 /* RestType */, pos); + node.type = parseType(); + return finishNode(node); + } + var type = parseType(); + if (!(contextFlags & 2097152 /* JSDoc */) && type.kind === 286 /* JSDocNullableType */ && type.pos === type.type.pos) { + type.kind = 171 /* OptionalType */; + } + return type; + } + function parseTupleType() { + var node = createNode(170 /* TupleType */); + node.elementTypes = parseBracketedList(21 /* TupleElementTypes */, parseTupleElementType, 22 /* OpenBracketToken */, 23 /* CloseBracketToken */); + return finishNode(node); + } + function parseParenthesizedType() { + var node = createNode(177 /* ParenthesizedType */); + parseExpected(20 /* OpenParenToken */); + node.type = parseType(); + parseExpected(21 /* CloseParenToken */); + return finishNode(node); + } + function parseFunctionOrConstructorType() { + var pos = getNodePos(); + var kind = parseOptional(95 /* NewKeyword */) ? 166 /* ConstructorType */ : 165 /* FunctionType */; + var node = createNodeWithJSDoc(kind, pos); + fillSignature(37 /* EqualsGreaterThanToken */, 4 /* Type */, node); + return finishNode(node); + } + function parseKeywordAndNoDot() { + var node = parseTokenNode(); + return token() === 24 /* DotToken */ ? undefined : node; + } + function parseLiteralTypeNode(negative) { + var node = createNode(182 /* LiteralType */); + var unaryMinusExpression; + if (negative) { + unaryMinusExpression = createNode(202 /* PrefixUnaryExpression */); + unaryMinusExpression.operator = 39 /* MinusToken */; + nextToken(); + } + var expression = token() === 102 /* TrueKeyword */ || token() === 87 /* FalseKeyword */ + ? parseTokenNode() + : parseLiteralLikeNode(token()); + if (negative) { + unaryMinusExpression.operand = expression; + finishNode(unaryMinusExpression); + expression = unaryMinusExpression; + } + node.literal = expression; + return finishNode(node); + } + function isStartOfTypeOfImportType() { + nextToken(); + return token() === 92 /* ImportKeyword */; + } + function parseImportType() { + sourceFile.flags |= 524288 /* PossiblyContainsDynamicImport */; + var node = createNode(183 /* ImportType */); + if (parseOptional(104 /* TypeOfKeyword */)) { + node.isTypeOf = true; + } + parseExpected(92 /* ImportKeyword */); + parseExpected(20 /* OpenParenToken */); + node.argument = parseType(); + parseExpected(21 /* CloseParenToken */); + if (parseOptional(24 /* DotToken */)) { + node.qualifier = parseEntityName(/*allowReservedWords*/ true, ts.Diagnostics.Type_expected); + } + node.typeArguments = tryParseTypeArguments(); + return finishNode(node); + } + function nextTokenIsNumericOrBigIntLiteral() { + nextToken(); + return token() === 8 /* NumericLiteral */ || token() === 9 /* BigIntLiteral */; + } + function parseNonArrayType() { + switch (token()) { + case 120 /* AnyKeyword */: + case 143 /* UnknownKeyword */: + case 138 /* StringKeyword */: + case 135 /* NumberKeyword */: + case 146 /* BigIntKeyword */: + case 139 /* SymbolKeyword */: + case 123 /* BooleanKeyword */: + case 141 /* UndefinedKeyword */: + case 132 /* NeverKeyword */: + case 136 /* ObjectKeyword */: + // If these are followed by a dot, then parse these out as a dotted type reference instead. + return tryParse(parseKeywordAndNoDot) || parseTypeReference(); + case 40 /* AsteriskToken */: + return parseJSDocAllType(/*postfixEquals*/ false); + case 62 /* AsteriskEqualsToken */: + return parseJSDocAllType(/*postfixEquals*/ true); + case 56 /* QuestionToken */: + return parseJSDocUnknownOrNullableType(); + case 90 /* FunctionKeyword */: + return parseJSDocFunctionType(); + case 52 /* ExclamationToken */: + return parseJSDocNonNullableType(); + case 14 /* NoSubstitutionTemplateLiteral */: + case 10 /* StringLiteral */: + case 8 /* NumericLiteral */: + case 9 /* BigIntLiteral */: + case 102 /* TrueKeyword */: + case 87 /* FalseKeyword */: + return parseLiteralTypeNode(); + case 39 /* MinusToken */: + return lookAhead(nextTokenIsNumericOrBigIntLiteral) ? parseLiteralTypeNode(/*negative*/ true) : parseTypeReference(); + case 106 /* VoidKeyword */: + case 96 /* NullKeyword */: + return parseTokenNode(); + case 100 /* ThisKeyword */: { + var thisKeyword = parseThisTypeNode(); + if (token() === 128 /* IsKeyword */ && !scanner.hasPrecedingLineBreak()) { + return parseThisTypePredicate(thisKeyword); + } + else { + return thisKeyword; + } + } + case 104 /* TypeOfKeyword */: + return lookAhead(isStartOfTypeOfImportType) ? parseImportType() : parseTypeQuery(); + case 18 /* OpenBraceToken */: + return lookAhead(isStartOfMappedType) ? parseMappedType() : parseTypeLiteral(); + case 22 /* OpenBracketToken */: + return parseTupleType(); + case 20 /* OpenParenToken */: + return parseParenthesizedType(); + case 92 /* ImportKeyword */: + return parseImportType(); + default: + return parseTypeReference(); + } + } + function isStartOfType(inStartOfParameter) { + switch (token()) { + case 120 /* AnyKeyword */: + case 143 /* UnknownKeyword */: + case 138 /* StringKeyword */: + case 135 /* NumberKeyword */: + case 146 /* BigIntKeyword */: + case 123 /* BooleanKeyword */: + case 139 /* SymbolKeyword */: + case 142 /* UniqueKeyword */: + case 106 /* VoidKeyword */: + case 141 /* UndefinedKeyword */: + case 96 /* NullKeyword */: + case 100 /* ThisKeyword */: + case 104 /* TypeOfKeyword */: + case 132 /* NeverKeyword */: + case 18 /* OpenBraceToken */: + case 22 /* OpenBracketToken */: + case 28 /* LessThanToken */: + case 50 /* BarToken */: + case 49 /* AmpersandToken */: + case 95 /* NewKeyword */: + case 10 /* StringLiteral */: + case 8 /* NumericLiteral */: + case 9 /* BigIntLiteral */: + case 102 /* TrueKeyword */: + case 87 /* FalseKeyword */: + case 136 /* ObjectKeyword */: + case 40 /* AsteriskToken */: + case 56 /* QuestionToken */: + case 52 /* ExclamationToken */: + case 25 /* DotDotDotToken */: + case 127 /* InferKeyword */: + case 92 /* ImportKeyword */: + return true; + case 90 /* FunctionKeyword */: + return !inStartOfParameter; + case 39 /* MinusToken */: + return !inStartOfParameter && lookAhead(nextTokenIsNumericOrBigIntLiteral); + case 20 /* OpenParenToken */: + // Only consider '(' the start of a type if followed by ')', '...', an identifier, a modifier, + // or something that starts a type. We don't want to consider things like '(1)' a type. + return !inStartOfParameter && lookAhead(isStartOfParenthesizedOrFunctionType); + default: + return isIdentifier(); + } + } + function isStartOfParenthesizedOrFunctionType() { + nextToken(); + return token() === 21 /* CloseParenToken */ || isStartOfParameter(/*isJSDocParameter*/ false) || isStartOfType(); + } + function parsePostfixTypeOrHigher() { + var type = parseNonArrayType(); + while (!scanner.hasPrecedingLineBreak()) { + switch (token()) { + case 52 /* ExclamationToken */: + type = createPostfixType(287 /* JSDocNonNullableType */, type); + break; + case 56 /* QuestionToken */: + // If not in JSDoc and next token is start of a type we have a conditional type + if (!(contextFlags & 2097152 /* JSDoc */) && lookAhead(nextTokenIsStartOfType)) { + return type; + } + type = createPostfixType(286 /* JSDocNullableType */, type); + break; + case 22 /* OpenBracketToken */: + parseExpected(22 /* OpenBracketToken */); + if (isStartOfType()) { + var node = createNode(180 /* IndexedAccessType */, type.pos); + node.objectType = type; + node.indexType = parseType(); + parseExpected(23 /* CloseBracketToken */); + type = finishNode(node); + } + else { + var node = createNode(169 /* ArrayType */, type.pos); + node.elementType = type; + parseExpected(23 /* CloseBracketToken */); + type = finishNode(node); + } + break; + default: + return type; + } + } + return type; + } + function createPostfixType(kind, type) { + nextToken(); + var postfix = createNode(kind, type.pos); + postfix.type = type; + return finishNode(postfix); + } + function parseTypeOperator(operator) { + var node = createNode(179 /* TypeOperator */); + parseExpected(operator); + node.operator = operator; + node.type = parseTypeOperatorOrHigher(); + return finishNode(node); + } + function parseInferType() { + var node = createNode(176 /* InferType */); + parseExpected(127 /* InferKeyword */); + var typeParameter = createNode(150 /* TypeParameter */); + typeParameter.name = parseIdentifier(); + node.typeParameter = finishNode(typeParameter); + return finishNode(node); + } + function parseTypeOperatorOrHigher() { + var operator = token(); + switch (operator) { + case 129 /* KeyOfKeyword */: + case 142 /* UniqueKeyword */: + return parseTypeOperator(operator); + case 127 /* InferKeyword */: + return parseInferType(); + } + return parsePostfixTypeOrHigher(); + } + function parseUnionOrIntersectionType(kind, parseConstituentType, operator) { + parseOptional(operator); + var type = parseConstituentType(); + if (token() === operator) { + var types = [type]; + while (parseOptional(operator)) { + types.push(parseConstituentType()); + } + var node = createNode(kind, type.pos); + node.types = createNodeArray(types, type.pos); + type = finishNode(node); + } + return type; + } + function parseIntersectionTypeOrHigher() { + return parseUnionOrIntersectionType(174 /* IntersectionType */, parseTypeOperatorOrHigher, 49 /* AmpersandToken */); + } + function parseUnionTypeOrHigher() { + return parseUnionOrIntersectionType(173 /* UnionType */, parseIntersectionTypeOrHigher, 50 /* BarToken */); + } + function isStartOfFunctionType() { + if (token() === 28 /* LessThanToken */) { + return true; + } + return token() === 20 /* OpenParenToken */ && lookAhead(isUnambiguouslyStartOfFunctionType); + } + function skipParameterStart() { + if (ts.isModifierKind(token())) { + // Skip modifiers + parseModifiers(); + } + if (isIdentifier() || token() === 100 /* ThisKeyword */) { + nextToken(); + return true; + } + if (token() === 22 /* OpenBracketToken */ || token() === 18 /* OpenBraceToken */) { + // Return true if we can parse an array or object binding pattern with no errors + var previousErrorCount = parseDiagnostics.length; + parseIdentifierOrPattern(); + return previousErrorCount === parseDiagnostics.length; + } + return false; + } + function isUnambiguouslyStartOfFunctionType() { + nextToken(); + if (token() === 21 /* CloseParenToken */ || token() === 25 /* DotDotDotToken */) { + // ( ) + // ( ... + return true; + } + if (skipParameterStart()) { + // We successfully skipped modifiers (if any) and an identifier or binding pattern, + // now see if we have something that indicates a parameter declaration + if (token() === 57 /* ColonToken */ || token() === 27 /* CommaToken */ || + token() === 56 /* QuestionToken */ || token() === 59 /* EqualsToken */) { + // ( xxx : + // ( xxx , + // ( xxx ? + // ( xxx = + return true; + } + if (token() === 21 /* CloseParenToken */) { + nextToken(); + if (token() === 37 /* EqualsGreaterThanToken */) { + // ( xxx ) => + return true; + } + } + } + return false; + } + function parseTypeOrTypePredicate() { + var typePredicateVariable = isIdentifier() && tryParse(parseTypePredicatePrefix); + var type = parseType(); + if (typePredicateVariable) { + var node = createNode(163 /* TypePredicate */, typePredicateVariable.pos); + node.parameterName = typePredicateVariable; + node.type = type; + return finishNode(node); + } + else { + return type; + } + } + function parseTypePredicatePrefix() { + var id = parseIdentifier(); + if (token() === 128 /* IsKeyword */ && !scanner.hasPrecedingLineBreak()) { + nextToken(); + return id; + } + } + function parseType() { + // The rules about 'yield' only apply to actual code/expression contexts. They don't + // apply to 'type' contexts. So we disable these parameters here before moving on. + return doOutsideOfContext(20480 /* TypeExcludesFlags */, parseTypeWorker); + } + function parseTypeWorker(noConditionalTypes) { + if (isStartOfFunctionType() || token() === 95 /* NewKeyword */) { + return parseFunctionOrConstructorType(); + } + var type = parseUnionTypeOrHigher(); + if (!noConditionalTypes && !scanner.hasPrecedingLineBreak() && parseOptional(86 /* ExtendsKeyword */)) { + var node = createNode(175 /* ConditionalType */, type.pos); + node.checkType = type; + // The type following 'extends' is not permitted to be another conditional type + node.extendsType = parseTypeWorker(/*noConditionalTypes*/ true); + parseExpected(56 /* QuestionToken */); + node.trueType = parseTypeWorker(); + parseExpected(57 /* ColonToken */); + node.falseType = parseTypeWorker(); + return finishNode(node); + } + return type; + } + function parseTypeAnnotation() { + return parseOptional(57 /* ColonToken */) ? parseType() : undefined; + } + // EXPRESSIONS + function isStartOfLeftHandSideExpression() { + switch (token()) { + case 100 /* ThisKeyword */: + case 98 /* SuperKeyword */: + case 96 /* NullKeyword */: + case 102 /* TrueKeyword */: + case 87 /* FalseKeyword */: + case 8 /* NumericLiteral */: + case 9 /* BigIntLiteral */: + case 10 /* StringLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: + case 15 /* TemplateHead */: + case 20 /* OpenParenToken */: + case 22 /* OpenBracketToken */: + case 18 /* OpenBraceToken */: + case 90 /* FunctionKeyword */: + case 76 /* ClassKeyword */: + case 95 /* NewKeyword */: + case 42 /* SlashToken */: + case 64 /* SlashEqualsToken */: + case 72 /* Identifier */: + return true; + case 92 /* ImportKeyword */: + return lookAhead(nextTokenIsOpenParenOrLessThanOrDot); + default: + return isIdentifier(); + } + } + function isStartOfExpression() { + if (isStartOfLeftHandSideExpression()) { + return true; + } + switch (token()) { + case 38 /* PlusToken */: + case 39 /* MinusToken */: + case 53 /* TildeToken */: + case 52 /* ExclamationToken */: + case 81 /* DeleteKeyword */: + case 104 /* TypeOfKeyword */: + case 106 /* VoidKeyword */: + case 44 /* PlusPlusToken */: + case 45 /* MinusMinusToken */: + case 28 /* LessThanToken */: + case 122 /* AwaitKeyword */: + case 117 /* YieldKeyword */: + // Yield/await always starts an expression. Either it is an identifier (in which case + // it is definitely an expression). Or it's a keyword (either because we're in + // a generator or async function, or in strict mode (or both)) and it started a yield or await expression. + return true; + default: + // Error tolerance. If we see the start of some binary operator, we consider + // that the start of an expression. That way we'll parse out a missing identifier, + // give a good message about an identifier being missing, and then consume the + // rest of the binary expression. + if (isBinaryOperator()) { + return true; + } + return isIdentifier(); + } + } + function isStartOfExpressionStatement() { + // As per the grammar, none of '{' or 'function' or 'class' can start an expression statement. + return token() !== 18 /* OpenBraceToken */ && + token() !== 90 /* FunctionKeyword */ && + token() !== 76 /* ClassKeyword */ && + token() !== 58 /* AtToken */ && + isStartOfExpression(); + } + function parseExpression() { + // Expression[in]: + // AssignmentExpression[in] + // Expression[in] , AssignmentExpression[in] + // clear the decorator context when parsing Expression, as it should be unambiguous when parsing a decorator + var saveDecoratorContext = inDecoratorContext(); + if (saveDecoratorContext) { + setDecoratorContext(/*val*/ false); + } + var expr = parseAssignmentExpressionOrHigher(); + var operatorToken; + while ((operatorToken = parseOptionalToken(27 /* CommaToken */))) { + expr = makeBinaryExpression(expr, operatorToken, parseAssignmentExpressionOrHigher()); + } + if (saveDecoratorContext) { + setDecoratorContext(/*val*/ true); + } + return expr; + } + function parseInitializer() { + return parseOptional(59 /* EqualsToken */) ? parseAssignmentExpressionOrHigher() : undefined; + } + function parseAssignmentExpressionOrHigher() { + // AssignmentExpression[in,yield]: + // 1) ConditionalExpression[?in,?yield] + // 2) LeftHandSideExpression = AssignmentExpression[?in,?yield] + // 3) LeftHandSideExpression AssignmentOperator AssignmentExpression[?in,?yield] + // 4) ArrowFunctionExpression[?in,?yield] + // 5) AsyncArrowFunctionExpression[in,yield,await] + // 6) [+Yield] YieldExpression[?In] + // + // Note: for ease of implementation we treat productions '2' and '3' as the same thing. + // (i.e. they're both BinaryExpressions with an assignment operator in it). + // First, do the simple check if we have a YieldExpression (production '6'). + if (isYieldExpression()) { + return parseYieldExpression(); + } + // Then, check if we have an arrow function (production '4' and '5') that starts with a parenthesized + // parameter list or is an async arrow function. + // AsyncArrowFunctionExpression: + // 1) async[no LineTerminator here]AsyncArrowBindingIdentifier[?Yield][no LineTerminator here]=>AsyncConciseBody[?In] + // 2) CoverCallExpressionAndAsyncArrowHead[?Yield, ?Await][no LineTerminator here]=>AsyncConciseBody[?In] + // Production (1) of AsyncArrowFunctionExpression is parsed in "tryParseAsyncSimpleArrowFunctionExpression". + // And production (2) is parsed in "tryParseParenthesizedArrowFunctionExpression". + // + // If we do successfully parse arrow-function, we must *not* recurse for productions 1, 2 or 3. An ArrowFunction is + // not a LeftHandSideExpression, nor does it start a ConditionalExpression. So we are done + // with AssignmentExpression if we see one. + var arrowExpression = tryParseParenthesizedArrowFunctionExpression() || tryParseAsyncSimpleArrowFunctionExpression(); + if (arrowExpression) { + return arrowExpression; + } + // Now try to see if we're in production '1', '2' or '3'. A conditional expression can + // start with a LogicalOrExpression, while the assignment productions can only start with + // LeftHandSideExpressions. + // + // So, first, we try to just parse out a BinaryExpression. If we get something that is a + // LeftHandSide or higher, then we can try to parse out the assignment expression part. + // Otherwise, we try to parse out the conditional expression bit. We want to allow any + // binary expression here, so we pass in the 'lowest' precedence here so that it matches + // and consumes anything. + var expr = parseBinaryExpressionOrHigher(/*precedence*/ 0); + // To avoid a look-ahead, we did not handle the case of an arrow function with a single un-parenthesized + // parameter ('x => ...') above. We handle it here by checking if the parsed expression was a single + // identifier and the current token is an arrow. + if (expr.kind === 72 /* Identifier */ && token() === 37 /* EqualsGreaterThanToken */) { + return parseSimpleArrowFunctionExpression(expr); + } + // Now see if we might be in cases '2' or '3'. + // If the expression was a LHS expression, and we have an assignment operator, then + // we're in '2' or '3'. Consume the assignment and return. + // + // Note: we call reScanGreaterToken so that we get an appropriately merged token + // for cases like `> > =` becoming `>>=` + if (ts.isLeftHandSideExpression(expr) && ts.isAssignmentOperator(reScanGreaterToken())) { + return makeBinaryExpression(expr, parseTokenNode(), parseAssignmentExpressionOrHigher()); + } + // It wasn't an assignment or a lambda. This is a conditional expression: + return parseConditionalExpressionRest(expr); + } + function isYieldExpression() { + if (token() === 117 /* YieldKeyword */) { + // If we have a 'yield' keyword, and this is a context where yield expressions are + // allowed, then definitely parse out a yield expression. + if (inYieldContext()) { + return true; + } + // We're in a context where 'yield expr' is not allowed. However, if we can + // definitely tell that the user was trying to parse a 'yield expr' and not + // just a normal expr that start with a 'yield' identifier, then parse out + // a 'yield expr'. We can then report an error later that they are only + // allowed in generator expressions. + // + // for example, if we see 'yield(foo)', then we'll have to treat that as an + // invocation expression of something called 'yield'. However, if we have + // 'yield foo' then that is not legal as a normal expression, so we can + // definitely recognize this as a yield expression. + // + // for now we just check if the next token is an identifier. More heuristics + // can be added here later as necessary. We just need to make sure that we + // don't accidentally consume something legal. + return lookAhead(nextTokenIsIdentifierOrKeywordOrLiteralOnSameLine); + } + return false; + } + function nextTokenIsIdentifierOnSameLine() { + nextToken(); + return !scanner.hasPrecedingLineBreak() && isIdentifier(); + } + function parseYieldExpression() { + var node = createNode(207 /* YieldExpression */); + // YieldExpression[In] : + // yield + // yield [no LineTerminator here] [Lexical goal InputElementRegExp]AssignmentExpression[?In, Yield] + // yield [no LineTerminator here] * [Lexical goal InputElementRegExp]AssignmentExpression[?In, Yield] + nextToken(); + if (!scanner.hasPrecedingLineBreak() && + (token() === 40 /* AsteriskToken */ || isStartOfExpression())) { + node.asteriskToken = parseOptionalToken(40 /* AsteriskToken */); + node.expression = parseAssignmentExpressionOrHigher(); + return finishNode(node); + } + else { + // if the next token is not on the same line as yield. or we don't have an '*' or + // the start of an expression, then this is just a simple "yield" expression. + return finishNode(node); + } + } + function parseSimpleArrowFunctionExpression(identifier, asyncModifier) { + ts.Debug.assert(token() === 37 /* EqualsGreaterThanToken */, "parseSimpleArrowFunctionExpression should only have been called if we had a =>"); + var node; + if (asyncModifier) { + node = createNode(197 /* ArrowFunction */, asyncModifier.pos); + node.modifiers = asyncModifier; + } + else { + node = createNode(197 /* ArrowFunction */, identifier.pos); + } + var parameter = createNode(151 /* Parameter */, identifier.pos); + parameter.name = identifier; + finishNode(parameter); + node.parameters = createNodeArray([parameter], parameter.pos, parameter.end); + node.equalsGreaterThanToken = parseExpectedToken(37 /* EqualsGreaterThanToken */); + node.body = parseArrowFunctionExpressionBody(/*isAsync*/ !!asyncModifier); + return addJSDocComment(finishNode(node)); + } + function tryParseParenthesizedArrowFunctionExpression() { + var triState = isParenthesizedArrowFunctionExpression(); + if (triState === 0 /* False */) { + // It's definitely not a parenthesized arrow function expression. + return undefined; + } + // If we definitely have an arrow function, then we can just parse one, not requiring a + // following => or { token. Otherwise, we *might* have an arrow function. Try to parse + // it out, but don't allow any ambiguity, and return 'undefined' if this could be an + // expression instead. + var arrowFunction = triState === 1 /* True */ + ? parseParenthesizedArrowFunctionExpressionHead(/*allowAmbiguity*/ true) + : tryParse(parsePossibleParenthesizedArrowFunctionExpressionHead); + if (!arrowFunction) { + // Didn't appear to actually be a parenthesized arrow function. Just bail out. + return undefined; + } + var isAsync = ts.hasModifier(arrowFunction, 256 /* Async */); + // If we have an arrow, then try to parse the body. Even if not, try to parse if we + // have an opening brace, just in case we're in an error state. + var lastToken = token(); + arrowFunction.equalsGreaterThanToken = parseExpectedToken(37 /* EqualsGreaterThanToken */); + arrowFunction.body = (lastToken === 37 /* EqualsGreaterThanToken */ || lastToken === 18 /* OpenBraceToken */) + ? parseArrowFunctionExpressionBody(isAsync) + : parseIdentifier(); + return finishNode(arrowFunction); + } + // True -> We definitely expect a parenthesized arrow function here. + // False -> There *cannot* be a parenthesized arrow function here. + // Unknown -> There *might* be a parenthesized arrow function here. + // Speculatively look ahead to be sure, and rollback if not. + function isParenthesizedArrowFunctionExpression() { + if (token() === 20 /* OpenParenToken */ || token() === 28 /* LessThanToken */ || token() === 121 /* AsyncKeyword */) { + return lookAhead(isParenthesizedArrowFunctionExpressionWorker); + } + if (token() === 37 /* EqualsGreaterThanToken */) { + // ERROR RECOVERY TWEAK: + // If we see a standalone => try to parse it as an arrow function expression as that's + // likely what the user intended to write. + return 1 /* True */; + } + // Definitely not a parenthesized arrow function. + return 0 /* False */; + } + function isParenthesizedArrowFunctionExpressionWorker() { + if (token() === 121 /* AsyncKeyword */) { + nextToken(); + if (scanner.hasPrecedingLineBreak()) { + return 0 /* False */; + } + if (token() !== 20 /* OpenParenToken */ && token() !== 28 /* LessThanToken */) { + return 0 /* False */; + } + } + var first = token(); + var second = nextToken(); + if (first === 20 /* OpenParenToken */) { + if (second === 21 /* CloseParenToken */) { + // Simple cases: "() =>", "(): ", and "() {". + // This is an arrow function with no parameters. + // The last one is not actually an arrow function, + // but this is probably what the user intended. + var third = nextToken(); + switch (third) { + case 37 /* EqualsGreaterThanToken */: + case 57 /* ColonToken */: + case 18 /* OpenBraceToken */: + return 1 /* True */; + default: + return 0 /* False */; + } + } + // If encounter "([" or "({", this could be the start of a binding pattern. + // Examples: + // ([ x ]) => { } + // ({ x }) => { } + // ([ x ]) + // ({ x }) + if (second === 22 /* OpenBracketToken */ || second === 18 /* OpenBraceToken */) { + return 2 /* Unknown */; + } + // Simple case: "(..." + // This is an arrow function with a rest parameter. + if (second === 25 /* DotDotDotToken */) { + return 1 /* True */; + } + // Check for "(xxx yyy", where xxx is a modifier and yyy is an identifier. This + // isn't actually allowed, but we want to treat it as a lambda so we can provide + // a good error message. + if (ts.isModifierKind(second) && second !== 121 /* AsyncKeyword */ && lookAhead(nextTokenIsIdentifier)) { + return 1 /* True */; + } + // If we had "(" followed by something that's not an identifier, + // then this definitely doesn't look like a lambda. "this" is not + // valid, but we want to parse it and then give a semantic error. + if (!isIdentifier() && second !== 100 /* ThisKeyword */) { + return 0 /* False */; + } + switch (nextToken()) { + case 57 /* ColonToken */: + // If we have something like "(a:", then we must have a + // type-annotated parameter in an arrow function expression. + return 1 /* True */; + case 56 /* QuestionToken */: + nextToken(); + // If we have "(a?:" or "(a?," or "(a?=" or "(a?)" then it is definitely a lambda. + if (token() === 57 /* ColonToken */ || token() === 27 /* CommaToken */ || token() === 59 /* EqualsToken */ || token() === 21 /* CloseParenToken */) { + return 1 /* True */; + } + // Otherwise it is definitely not a lambda. + return 0 /* False */; + case 27 /* CommaToken */: + case 59 /* EqualsToken */: + case 21 /* CloseParenToken */: + // If we have "(a," or "(a=" or "(a)" this *could* be an arrow function + return 2 /* Unknown */; + } + // It is definitely not an arrow function + return 0 /* False */; + } + else { + ts.Debug.assert(first === 28 /* LessThanToken */); + // If we have "<" not followed by an identifier, + // then this definitely is not an arrow function. + if (!isIdentifier()) { + return 0 /* False */; + } + // JSX overrides + if (sourceFile.languageVariant === 1 /* JSX */) { + var isArrowFunctionInJsx = lookAhead(function () { + var third = nextToken(); + if (third === 86 /* ExtendsKeyword */) { + var fourth = nextToken(); + switch (fourth) { + case 59 /* EqualsToken */: + case 30 /* GreaterThanToken */: + return false; + default: + return true; + } + } + else if (third === 27 /* CommaToken */) { + return true; + } + return false; + }); + if (isArrowFunctionInJsx) { + return 1 /* True */; + } + return 0 /* False */; + } + // This *could* be a parenthesized arrow function. + return 2 /* Unknown */; + } + } + function parsePossibleParenthesizedArrowFunctionExpressionHead() { + return parseParenthesizedArrowFunctionExpressionHead(/*allowAmbiguity*/ false); + } + function tryParseAsyncSimpleArrowFunctionExpression() { + // We do a check here so that we won't be doing unnecessarily call to "lookAhead" + if (token() === 121 /* AsyncKeyword */) { + if (lookAhead(isUnParenthesizedAsyncArrowFunctionWorker) === 1 /* True */) { + var asyncModifier = parseModifiersForArrowFunction(); + var expr = parseBinaryExpressionOrHigher(/*precedence*/ 0); + return parseSimpleArrowFunctionExpression(expr, asyncModifier); + } + } + return undefined; + } + function isUnParenthesizedAsyncArrowFunctionWorker() { + // AsyncArrowFunctionExpression: + // 1) async[no LineTerminator here]AsyncArrowBindingIdentifier[?Yield][no LineTerminator here]=>AsyncConciseBody[?In] + // 2) CoverCallExpressionAndAsyncArrowHead[?Yield, ?Await][no LineTerminator here]=>AsyncConciseBody[?In] + if (token() === 121 /* AsyncKeyword */) { + nextToken(); + // If the "async" is followed by "=>" token then it is not a beginning of an async arrow-function + // but instead a simple arrow-function which will be parsed inside "parseAssignmentExpressionOrHigher" + if (scanner.hasPrecedingLineBreak() || token() === 37 /* EqualsGreaterThanToken */) { + return 0 /* False */; + } + // Check for un-parenthesized AsyncArrowFunction + var expr = parseBinaryExpressionOrHigher(/*precedence*/ 0); + if (!scanner.hasPrecedingLineBreak() && expr.kind === 72 /* Identifier */ && token() === 37 /* EqualsGreaterThanToken */) { + return 1 /* True */; + } + } + return 0 /* False */; + } + function parseParenthesizedArrowFunctionExpressionHead(allowAmbiguity) { + var node = createNodeWithJSDoc(197 /* ArrowFunction */); + node.modifiers = parseModifiersForArrowFunction(); + var isAsync = ts.hasModifier(node, 256 /* Async */) ? 2 /* Await */ : 0 /* None */; + // Arrow functions are never generators. + // + // If we're speculatively parsing a signature for a parenthesized arrow function, then + // we have to have a complete parameter list. Otherwise we might see something like + // a => (b => c) + // And think that "(b =>" was actually a parenthesized arrow function with a missing + // close paren. + if (!fillSignature(57 /* ColonToken */, isAsync, node) && !allowAmbiguity) { + return undefined; + } + // Parsing a signature isn't enough. + // Parenthesized arrow signatures often look like other valid expressions. + // For instance: + // - "(x = 10)" is an assignment expression parsed as a signature with a default parameter value. + // - "(x,y)" is a comma expression parsed as a signature with two parameters. + // - "a ? (b): c" will have "(b):" parsed as a signature with a return type annotation. + // + // So we need just a bit of lookahead to ensure that it can only be a signature. + if (!allowAmbiguity && token() !== 37 /* EqualsGreaterThanToken */ && token() !== 18 /* OpenBraceToken */) { + // Returning undefined here will cause our caller to rewind to where we started from. + return undefined; + } + return node; + } + function parseArrowFunctionExpressionBody(isAsync) { + if (token() === 18 /* OpenBraceToken */) { + return parseFunctionBlock(isAsync ? 2 /* Await */ : 0 /* None */); + } + if (token() !== 26 /* SemicolonToken */ && + token() !== 90 /* FunctionKeyword */ && + token() !== 76 /* ClassKeyword */ && + isStartOfStatement() && + !isStartOfExpressionStatement()) { + // Check if we got a plain statement (i.e. no expression-statements, no function/class expressions/declarations) + // + // Here we try to recover from a potential error situation in the case where the + // user meant to supply a block. For example, if the user wrote: + // + // a => + // let v = 0; + // } + // + // they may be missing an open brace. Check to see if that's the case so we can + // try to recover better. If we don't do this, then the next close curly we see may end + // up preemptively closing the containing construct. + // + // Note: even when 'IgnoreMissingOpenBrace' is passed, parseBody will still error. + return parseFunctionBlock(16 /* IgnoreMissingOpenBrace */ | (isAsync ? 2 /* Await */ : 0 /* None */)); + } + return isAsync + ? doInAwaitContext(parseAssignmentExpressionOrHigher) + : doOutsideOfAwaitContext(parseAssignmentExpressionOrHigher); + } + function parseConditionalExpressionRest(leftOperand) { + // Note: we are passed in an expression which was produced from parseBinaryExpressionOrHigher. + var questionToken = parseOptionalToken(56 /* QuestionToken */); + if (!questionToken) { + return leftOperand; + } + // Note: we explicitly 'allowIn' in the whenTrue part of the condition expression, and + // we do not that for the 'whenFalse' part. + var node = createNode(205 /* ConditionalExpression */, leftOperand.pos); + node.condition = leftOperand; + node.questionToken = questionToken; + node.whenTrue = doOutsideOfContext(disallowInAndDecoratorContext, parseAssignmentExpressionOrHigher); + node.colonToken = parseExpectedToken(57 /* ColonToken */); + node.whenFalse = ts.nodeIsPresent(node.colonToken) + ? parseAssignmentExpressionOrHigher() + : createMissingNode(72 /* Identifier */, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, ts.tokenToString(57 /* ColonToken */)); + return finishNode(node); + } + function parseBinaryExpressionOrHigher(precedence) { + var leftOperand = parseUnaryExpressionOrHigher(); + return parseBinaryExpressionRest(precedence, leftOperand); + } + function isInOrOfKeyword(t) { + return t === 93 /* InKeyword */ || t === 147 /* OfKeyword */; + } + function parseBinaryExpressionRest(precedence, leftOperand) { + while (true) { + // We either have a binary operator here, or we're finished. We call + // reScanGreaterToken so that we merge token sequences like > and = into >= + reScanGreaterToken(); + var newPrecedence = ts.getBinaryOperatorPrecedence(token()); + // Check the precedence to see if we should "take" this operator + // - For left associative operator (all operator but **), consume the operator, + // recursively call the function below, and parse binaryExpression as a rightOperand + // of the caller if the new precedence of the operator is greater then or equal to the current precedence. + // For example: + // a - b - c; + // ^token; leftOperand = b. Return b to the caller as a rightOperand + // a * b - c + // ^token; leftOperand = b. Return b to the caller as a rightOperand + // a - b * c; + // ^token; leftOperand = b. Return b * c to the caller as a rightOperand + // - For right associative operator (**), consume the operator, recursively call the function + // and parse binaryExpression as a rightOperand of the caller if the new precedence of + // the operator is strictly grater than the current precedence + // For example: + // a ** b ** c; + // ^^token; leftOperand = b. Return b ** c to the caller as a rightOperand + // a - b ** c; + // ^^token; leftOperand = b. Return b ** c to the caller as a rightOperand + // a ** b - c + // ^token; leftOperand = b. Return b to the caller as a rightOperand + var consumeCurrentOperator = token() === 41 /* AsteriskAsteriskToken */ ? + newPrecedence >= precedence : + newPrecedence > precedence; + if (!consumeCurrentOperator) { + break; + } + if (token() === 93 /* InKeyword */ && inDisallowInContext()) { + break; + } + if (token() === 119 /* AsKeyword */) { + // Make sure we *do* perform ASI for constructs like this: + // var x = foo + // as (Bar) + // This should be parsed as an initialized variable, followed + // by a function call to 'as' with the argument 'Bar' + if (scanner.hasPrecedingLineBreak()) { + break; + } + else { + nextToken(); + leftOperand = makeAsExpression(leftOperand, parseType()); + } + } + else { + leftOperand = makeBinaryExpression(leftOperand, parseTokenNode(), parseBinaryExpressionOrHigher(newPrecedence)); + } + } + return leftOperand; + } + function isBinaryOperator() { + if (inDisallowInContext() && token() === 93 /* InKeyword */) { + return false; + } + return ts.getBinaryOperatorPrecedence(token()) > 0; + } + function makeBinaryExpression(left, operatorToken, right) { + var node = createNode(204 /* BinaryExpression */, left.pos); + node.left = left; + node.operatorToken = operatorToken; + node.right = right; + return finishNode(node); + } + function makeAsExpression(left, right) { + var node = createNode(212 /* AsExpression */, left.pos); + node.expression = left; + node.type = right; + return finishNode(node); + } + function parsePrefixUnaryExpression() { + var node = createNode(202 /* PrefixUnaryExpression */); + node.operator = token(); + nextToken(); + node.operand = parseSimpleUnaryExpression(); + return finishNode(node); + } + function parseDeleteExpression() { + var node = createNode(198 /* DeleteExpression */); + nextToken(); + node.expression = parseSimpleUnaryExpression(); + return finishNode(node); + } + function parseTypeOfExpression() { + var node = createNode(199 /* TypeOfExpression */); + nextToken(); + node.expression = parseSimpleUnaryExpression(); + return finishNode(node); + } + function parseVoidExpression() { + var node = createNode(200 /* VoidExpression */); + nextToken(); + node.expression = parseSimpleUnaryExpression(); + return finishNode(node); + } + function isAwaitExpression() { + if (token() === 122 /* AwaitKeyword */) { + if (inAwaitContext()) { + return true; + } + // here we are using similar heuristics as 'isYieldExpression' + return lookAhead(nextTokenIsIdentifierOrKeywordOrLiteralOnSameLine); + } + return false; + } + function parseAwaitExpression() { + var node = createNode(201 /* AwaitExpression */); + nextToken(); + node.expression = parseSimpleUnaryExpression(); + return finishNode(node); + } + /** + * Parse ES7 exponential expression and await expression + * + * ES7 ExponentiationExpression: + * 1) UnaryExpression[?Yield] + * 2) UpdateExpression[?Yield] ** ExponentiationExpression[?Yield] + * + */ + function parseUnaryExpressionOrHigher() { + /** + * ES7 UpdateExpression: + * 1) LeftHandSideExpression[?Yield] + * 2) LeftHandSideExpression[?Yield][no LineTerminator here]++ + * 3) LeftHandSideExpression[?Yield][no LineTerminator here]-- + * 4) ++UnaryExpression[?Yield] + * 5) --UnaryExpression[?Yield] + */ + if (isUpdateExpression()) { + var updateExpression = parseUpdateExpression(); + return token() === 41 /* AsteriskAsteriskToken */ ? + parseBinaryExpressionRest(ts.getBinaryOperatorPrecedence(token()), updateExpression) : + updateExpression; + } + /** + * ES7 UnaryExpression: + * 1) UpdateExpression[?yield] + * 2) delete UpdateExpression[?yield] + * 3) void UpdateExpression[?yield] + * 4) typeof UpdateExpression[?yield] + * 5) + UpdateExpression[?yield] + * 6) - UpdateExpression[?yield] + * 7) ~ UpdateExpression[?yield] + * 8) ! UpdateExpression[?yield] + */ + var unaryOperator = token(); + var simpleUnaryExpression = parseSimpleUnaryExpression(); + if (token() === 41 /* AsteriskAsteriskToken */) { + var pos = ts.skipTrivia(sourceText, simpleUnaryExpression.pos); + var end = simpleUnaryExpression.end; + if (simpleUnaryExpression.kind === 194 /* TypeAssertionExpression */) { + parseErrorAt(pos, end, ts.Diagnostics.A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses); + } + else { + parseErrorAt(pos, end, ts.Diagnostics.An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses, ts.tokenToString(unaryOperator)); + } + } + return simpleUnaryExpression; + } + /** + * Parse ES7 simple-unary expression or higher: + * + * ES7 UnaryExpression: + * 1) UpdateExpression[?yield] + * 2) delete UnaryExpression[?yield] + * 3) void UnaryExpression[?yield] + * 4) typeof UnaryExpression[?yield] + * 5) + UnaryExpression[?yield] + * 6) - UnaryExpression[?yield] + * 7) ~ UnaryExpression[?yield] + * 8) ! UnaryExpression[?yield] + * 9) [+Await] await UnaryExpression[?yield] + */ + function parseSimpleUnaryExpression() { + switch (token()) { + case 38 /* PlusToken */: + case 39 /* MinusToken */: + case 53 /* TildeToken */: + case 52 /* ExclamationToken */: + return parsePrefixUnaryExpression(); + case 81 /* DeleteKeyword */: + return parseDeleteExpression(); + case 104 /* TypeOfKeyword */: + return parseTypeOfExpression(); + case 106 /* VoidKeyword */: + return parseVoidExpression(); + case 28 /* LessThanToken */: + // This is modified UnaryExpression grammar in TypeScript + // UnaryExpression (modified): + // < type > UnaryExpression + return parseTypeAssertion(); + case 122 /* AwaitKeyword */: + if (isAwaitExpression()) { + return parseAwaitExpression(); + } + // falls through + default: + return parseUpdateExpression(); + } + } + /** + * Check if the current token can possibly be an ES7 increment expression. + * + * ES7 UpdateExpression: + * LeftHandSideExpression[?Yield] + * LeftHandSideExpression[?Yield][no LineTerminator here]++ + * LeftHandSideExpression[?Yield][no LineTerminator here]-- + * ++LeftHandSideExpression[?Yield] + * --LeftHandSideExpression[?Yield] + */ + function isUpdateExpression() { + // This function is called inside parseUnaryExpression to decide + // whether to call parseSimpleUnaryExpression or call parseUpdateExpression directly + switch (token()) { + case 38 /* PlusToken */: + case 39 /* MinusToken */: + case 53 /* TildeToken */: + case 52 /* ExclamationToken */: + case 81 /* DeleteKeyword */: + case 104 /* TypeOfKeyword */: + case 106 /* VoidKeyword */: + case 122 /* AwaitKeyword */: + return false; + case 28 /* LessThanToken */: + // If we are not in JSX context, we are parsing TypeAssertion which is an UnaryExpression + if (sourceFile.languageVariant !== 1 /* JSX */) { + return false; + } + // We are in JSX context and the token is part of JSXElement. + // falls through + default: + return true; + } + } + /** + * Parse ES7 UpdateExpression. UpdateExpression is used instead of ES6's PostFixExpression. + * + * ES7 UpdateExpression[yield]: + * 1) LeftHandSideExpression[?yield] + * 2) LeftHandSideExpression[?yield] [[no LineTerminator here]]++ + * 3) LeftHandSideExpression[?yield] [[no LineTerminator here]]-- + * 4) ++LeftHandSideExpression[?yield] + * 5) --LeftHandSideExpression[?yield] + * In TypeScript (2), (3) are parsed as PostfixUnaryExpression. (4), (5) are parsed as PrefixUnaryExpression + */ + function parseUpdateExpression() { + if (token() === 44 /* PlusPlusToken */ || token() === 45 /* MinusMinusToken */) { + var node = createNode(202 /* PrefixUnaryExpression */); + node.operator = token(); + nextToken(); + node.operand = parseLeftHandSideExpressionOrHigher(); + return finishNode(node); + } + else if (sourceFile.languageVariant === 1 /* JSX */ && token() === 28 /* LessThanToken */ && lookAhead(nextTokenIsIdentifierOrKeywordOrGreaterThan)) { + // JSXElement is part of primaryExpression + return parseJsxElementOrSelfClosingElementOrFragment(/*inExpressionContext*/ true); + } + var expression = parseLeftHandSideExpressionOrHigher(); + ts.Debug.assert(ts.isLeftHandSideExpression(expression)); + if ((token() === 44 /* PlusPlusToken */ || token() === 45 /* MinusMinusToken */) && !scanner.hasPrecedingLineBreak()) { + var node = createNode(203 /* PostfixUnaryExpression */, expression.pos); + node.operand = expression; + node.operator = token(); + nextToken(); + return finishNode(node); + } + return expression; + } + function parseLeftHandSideExpressionOrHigher() { + // Original Ecma: + // LeftHandSideExpression: See 11.2 + // NewExpression + // CallExpression + // + // Our simplification: + // + // LeftHandSideExpression: See 11.2 + // MemberExpression + // CallExpression + // + // See comment in parseMemberExpressionOrHigher on how we replaced NewExpression with + // MemberExpression to make our lives easier. + // + // to best understand the below code, it's important to see how CallExpression expands + // out into its own productions: + // + // CallExpression: + // MemberExpression Arguments + // CallExpression Arguments + // CallExpression[Expression] + // CallExpression.IdentifierName + // import (AssignmentExpression) + // super Arguments + // super.IdentifierName + // + // Because of the recursion in these calls, we need to bottom out first. There are three + // bottom out states we can run into: 1) We see 'super' which must start either of + // the last two CallExpression productions. 2) We see 'import' which must start import call. + // 3)we have a MemberExpression which either completes the LeftHandSideExpression, + // or starts the beginning of the first four CallExpression productions. + var expression; + if (token() === 92 /* ImportKeyword */) { + if (lookAhead(nextTokenIsOpenParenOrLessThan)) { + // We don't want to eagerly consume all import keyword as import call expression so we look ahead to find "(" + // For example: + // var foo3 = require("subfolder + // import * as foo1 from "module-from-node + // We want this import to be a statement rather than import call expression + sourceFile.flags |= 524288 /* PossiblyContainsDynamicImport */; + expression = parseTokenNode(); + } + else if (lookAhead(nextTokenIsDot)) { + // This is an 'import.*' metaproperty (i.e. 'import.meta') + var fullStart = scanner.getStartPos(); + nextToken(); // advance past the 'import' + nextToken(); // advance past the dot + var node = createNode(214 /* MetaProperty */, fullStart); + node.keywordToken = 92 /* ImportKeyword */; + node.name = parseIdentifierName(); + expression = finishNode(node); + sourceFile.flags |= 1048576 /* PossiblyContainsImportMeta */; + } + else { + expression = parseMemberExpressionOrHigher(); + } + } + else { + expression = token() === 98 /* SuperKeyword */ ? parseSuperExpression() : parseMemberExpressionOrHigher(); + } + // Now, we *may* be complete. However, we might have consumed the start of a + // CallExpression. As such, we need to consume the rest of it here to be complete. + return parseCallExpressionRest(expression); + } + function parseMemberExpressionOrHigher() { + // Note: to make our lives simpler, we decompose the NewExpression productions and + // place ObjectCreationExpression and FunctionExpression into PrimaryExpression. + // like so: + // + // PrimaryExpression : See 11.1 + // this + // Identifier + // Literal + // ArrayLiteral + // ObjectLiteral + // (Expression) + // FunctionExpression + // new MemberExpression Arguments? + // + // MemberExpression : See 11.2 + // PrimaryExpression + // MemberExpression[Expression] + // MemberExpression.IdentifierName + // + // CallExpression : See 11.2 + // MemberExpression + // CallExpression Arguments + // CallExpression[Expression] + // CallExpression.IdentifierName + // + // Technically this is ambiguous. i.e. CallExpression defines: + // + // CallExpression: + // CallExpression Arguments + // + // If you see: "new Foo()" + // + // Then that could be treated as a single ObjectCreationExpression, or it could be + // treated as the invocation of "new Foo". We disambiguate that in code (to match + // the original grammar) by making sure that if we see an ObjectCreationExpression + // we always consume arguments if they are there. So we treat "new Foo()" as an + // object creation only, and not at all as an invocation. Another way to think + // about this is that for every "new" that we see, we will consume an argument list if + // it is there as part of the *associated* object creation node. Any additional + // argument lists we see, will become invocation expressions. + // + // Because there are no other places in the grammar now that refer to FunctionExpression + // or ObjectCreationExpression, it is safe to push down into the PrimaryExpression + // production. + // + // Because CallExpression and MemberExpression are left recursive, we need to bottom out + // of the recursion immediately. So we parse out a primary expression to start with. + var expression = parsePrimaryExpression(); + return parseMemberExpressionRest(expression); + } + function parseSuperExpression() { + var expression = parseTokenNode(); + if (token() === 20 /* OpenParenToken */ || token() === 24 /* DotToken */ || token() === 22 /* OpenBracketToken */) { + return expression; + } + // If we have seen "super" it must be followed by '(' or '.'. + // If it wasn't then just try to parse out a '.' and report an error. + var node = createNode(189 /* PropertyAccessExpression */, expression.pos); + node.expression = expression; + parseExpectedToken(24 /* DotToken */, ts.Diagnostics.super_must_be_followed_by_an_argument_list_or_member_access); + node.name = parseRightSideOfDot(/*allowIdentifierNames*/ true); + return finishNode(node); + } + function parseJsxElementOrSelfClosingElementOrFragment(inExpressionContext) { + var opening = parseJsxOpeningOrSelfClosingElementOrOpeningFragment(inExpressionContext); + var result; + if (opening.kind === 262 /* JsxOpeningElement */) { + var node = createNode(260 /* JsxElement */, opening.pos); + node.openingElement = opening; + node.children = parseJsxChildren(node.openingElement); + node.closingElement = parseJsxClosingElement(inExpressionContext); + if (!tagNamesAreEquivalent(node.openingElement.tagName, node.closingElement.tagName)) { + parseErrorAtRange(node.closingElement, ts.Diagnostics.Expected_corresponding_JSX_closing_tag_for_0, ts.getTextOfNodeFromSourceText(sourceText, node.openingElement.tagName)); + } + result = finishNode(node); + } + else if (opening.kind === 265 /* JsxOpeningFragment */) { + var node = createNode(264 /* JsxFragment */, opening.pos); + node.openingFragment = opening; + node.children = parseJsxChildren(node.openingFragment); + node.closingFragment = parseJsxClosingFragment(inExpressionContext); + result = finishNode(node); + } + else { + ts.Debug.assert(opening.kind === 261 /* JsxSelfClosingElement */); + // Nothing else to do for self-closing elements + result = opening; + } + // If the user writes the invalid code '
      ' in an expression context (i.e. not wrapped in + // an enclosing tag), we'll naively try to parse ^ this as a 'less than' operator and the remainder of the tag + // as garbage, which will cause the formatter to badly mangle the JSX. Perform a speculative parse of a JSX + // element if we see a < token so that we can wrap it in a synthetic binary expression so the formatter + // does less damage and we can report a better error. + // Since JSX elements are invalid < operands anyway, this lookahead parse will only occur in error scenarios + // of one sort or another. + if (inExpressionContext && token() === 28 /* LessThanToken */) { + var invalidElement = tryParse(function () { return parseJsxElementOrSelfClosingElementOrFragment(/*inExpressionContext*/ true); }); + if (invalidElement) { + parseErrorAtCurrentToken(ts.Diagnostics.JSX_expressions_must_have_one_parent_element); + var badNode = createNode(204 /* BinaryExpression */, result.pos); + badNode.end = invalidElement.end; + badNode.left = result; + badNode.right = invalidElement; + badNode.operatorToken = createMissingNode(27 /* CommaToken */, /*reportAtCurrentPosition*/ false, /*diagnosticMessage*/ undefined); // TODO: GH#18217 + badNode.operatorToken.pos = badNode.operatorToken.end = badNode.right.pos; + return badNode; + } + } + return result; + } + function parseJsxText() { + var node = createNode(11 /* JsxText */); + node.containsOnlyWhiteSpaces = currentToken === 12 /* JsxTextAllWhiteSpaces */; + currentToken = scanner.scanJsxToken(); + return finishNode(node); + } + function parseJsxChild(openingTag, token) { + switch (token) { + case 1 /* EndOfFileToken */: + // If we hit EOF, issue the error at the tag that lacks the closing element + // rather than at the end of the file (which is useless) + if (ts.isJsxOpeningFragment(openingTag)) { + parseErrorAtRange(openingTag, ts.Diagnostics.JSX_fragment_has_no_corresponding_closing_tag); + } + else { + parseErrorAtRange(openingTag.tagName, ts.Diagnostics.JSX_element_0_has_no_corresponding_closing_tag, ts.getTextOfNodeFromSourceText(sourceText, openingTag.tagName)); + } + return undefined; + case 29 /* LessThanSlashToken */: + case 7 /* ConflictMarkerTrivia */: + return undefined; + case 11 /* JsxText */: + case 12 /* JsxTextAllWhiteSpaces */: + return parseJsxText(); + case 18 /* OpenBraceToken */: + return parseJsxExpression(/*inExpressionContext*/ false); + case 28 /* LessThanToken */: + return parseJsxElementOrSelfClosingElementOrFragment(/*inExpressionContext*/ false); + default: + return ts.Debug.assertNever(token); + } + } + function parseJsxChildren(openingTag) { + var list = []; + var listPos = getNodePos(); + var saveParsingContext = parsingContext; + parsingContext |= 1 << 14 /* JsxChildren */; + while (true) { + var child = parseJsxChild(openingTag, currentToken = scanner.reScanJsxToken()); + if (!child) + break; + list.push(child); + } + parsingContext = saveParsingContext; + return createNodeArray(list, listPos); + } + function parseJsxAttributes() { + var jsxAttributes = createNode(268 /* JsxAttributes */); + jsxAttributes.properties = parseList(13 /* JsxAttributes */, parseJsxAttribute); + return finishNode(jsxAttributes); + } + function parseJsxOpeningOrSelfClosingElementOrOpeningFragment(inExpressionContext) { + var fullStart = scanner.getStartPos(); + parseExpected(28 /* LessThanToken */); + if (token() === 30 /* GreaterThanToken */) { + // See below for explanation of scanJsxText + var node_1 = createNode(265 /* JsxOpeningFragment */, fullStart); + scanJsxText(); + return finishNode(node_1); + } + var tagName = parseJsxElementName(); + var typeArguments = tryParseTypeArguments(); + var attributes = parseJsxAttributes(); + var node; + if (token() === 30 /* GreaterThanToken */) { + // Closing tag, so scan the immediately-following text with the JSX scanning instead + // of regular scanning to avoid treating illegal characters (e.g. '#') as immediate + // scanning errors + node = createNode(262 /* JsxOpeningElement */, fullStart); + scanJsxText(); + } + else { + parseExpected(42 /* SlashToken */); + if (inExpressionContext) { + parseExpected(30 /* GreaterThanToken */); + } + else { + parseExpected(30 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false); + scanJsxText(); + } + node = createNode(261 /* JsxSelfClosingElement */, fullStart); + } + node.tagName = tagName; + node.typeArguments = typeArguments; + node.attributes = attributes; + return finishNode(node); + } + function parseJsxElementName() { + scanJsxIdentifier(); + // JsxElement can have name in the form of + // propertyAccessExpression + // primaryExpression in the form of an identifier and "this" keyword + // We can't just simply use parseLeftHandSideExpressionOrHigher because then we will start consider class,function etc as a keyword + // We only want to consider "this" as a primaryExpression + var expression = token() === 100 /* ThisKeyword */ ? + parseTokenNode() : parseIdentifierName(); + while (parseOptional(24 /* DotToken */)) { + var propertyAccess = createNode(189 /* PropertyAccessExpression */, expression.pos); + propertyAccess.expression = expression; + propertyAccess.name = parseRightSideOfDot(/*allowIdentifierNames*/ true); + expression = finishNode(propertyAccess); + } + return expression; + } + function parseJsxExpression(inExpressionContext) { + var node = createNode(270 /* JsxExpression */); + if (!parseExpected(18 /* OpenBraceToken */)) { + return undefined; + } + if (token() !== 19 /* CloseBraceToken */) { + node.dotDotDotToken = parseOptionalToken(25 /* DotDotDotToken */); + node.expression = parseAssignmentExpressionOrHigher(); + } + if (inExpressionContext) { + parseExpected(19 /* CloseBraceToken */); + } + else { + parseExpected(19 /* CloseBraceToken */, /*message*/ undefined, /*shouldAdvance*/ false); + scanJsxText(); + } + return finishNode(node); + } + function parseJsxAttribute() { + if (token() === 18 /* OpenBraceToken */) { + return parseJsxSpreadAttribute(); + } + scanJsxIdentifier(); + var node = createNode(267 /* JsxAttribute */); + node.name = parseIdentifierName(); + if (token() === 59 /* EqualsToken */) { + switch (scanJsxAttributeValue()) { + case 10 /* StringLiteral */: + node.initializer = parseLiteralNode(); + break; + default: + node.initializer = parseJsxExpression(/*inExpressionContext*/ true); + break; + } + } + return finishNode(node); + } + function parseJsxSpreadAttribute() { + var node = createNode(269 /* JsxSpreadAttribute */); + parseExpected(18 /* OpenBraceToken */); + parseExpected(25 /* DotDotDotToken */); + node.expression = parseExpression(); + parseExpected(19 /* CloseBraceToken */); + return finishNode(node); + } + function parseJsxClosingElement(inExpressionContext) { + var node = createNode(263 /* JsxClosingElement */); + parseExpected(29 /* LessThanSlashToken */); + node.tagName = parseJsxElementName(); + if (inExpressionContext) { + parseExpected(30 /* GreaterThanToken */); + } + else { + parseExpected(30 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false); + scanJsxText(); + } + return finishNode(node); + } + function parseJsxClosingFragment(inExpressionContext) { + var node = createNode(266 /* JsxClosingFragment */); + parseExpected(29 /* LessThanSlashToken */); + if (ts.tokenIsIdentifierOrKeyword(token())) { + parseErrorAtRange(parseJsxElementName(), ts.Diagnostics.Expected_corresponding_closing_tag_for_JSX_fragment); + } + if (inExpressionContext) { + parseExpected(30 /* GreaterThanToken */); + } + else { + parseExpected(30 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false); + scanJsxText(); + } + return finishNode(node); + } + function parseTypeAssertion() { + var node = createNode(194 /* TypeAssertionExpression */); + parseExpected(28 /* LessThanToken */); + node.type = parseType(); + parseExpected(30 /* GreaterThanToken */); + node.expression = parseSimpleUnaryExpression(); + return finishNode(node); + } + function parseMemberExpressionRest(expression) { + while (true) { + var dotToken = parseOptionalToken(24 /* DotToken */); + if (dotToken) { + var propertyAccess = createNode(189 /* PropertyAccessExpression */, expression.pos); + propertyAccess.expression = expression; + propertyAccess.name = parseRightSideOfDot(/*allowIdentifierNames*/ true); + expression = finishNode(propertyAccess); + continue; + } + if (token() === 52 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) { + nextToken(); + var nonNullExpression = createNode(213 /* NonNullExpression */, expression.pos); + nonNullExpression.expression = expression; + expression = finishNode(nonNullExpression); + continue; + } + // when in the [Decorator] context, we do not parse ElementAccess as it could be part of a ComputedPropertyName + if (!inDecoratorContext() && parseOptional(22 /* OpenBracketToken */)) { + var indexedAccess = createNode(190 /* ElementAccessExpression */, expression.pos); + indexedAccess.expression = expression; + if (token() === 23 /* CloseBracketToken */) { + indexedAccess.argumentExpression = createMissingNode(72 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.An_element_access_expression_should_take_an_argument); + } + else { + var argument = allowInAnd(parseExpression); + if (ts.isStringOrNumericLiteralLike(argument)) { + argument.text = internIdentifier(argument.text); + } + indexedAccess.argumentExpression = argument; + } + parseExpected(23 /* CloseBracketToken */); + expression = finishNode(indexedAccess); + continue; + } + if (isTemplateStartOfTaggedTemplate()) { + expression = parseTaggedTemplateRest(expression, /*typeArguments*/ undefined); + continue; + } + return expression; + } + } + function isTemplateStartOfTaggedTemplate() { + return token() === 14 /* NoSubstitutionTemplateLiteral */ || token() === 15 /* TemplateHead */; + } + function parseTaggedTemplateRest(tag, typeArguments) { + var tagExpression = createNode(193 /* TaggedTemplateExpression */, tag.pos); + tagExpression.tag = tag; + tagExpression.typeArguments = typeArguments; + tagExpression.template = token() === 14 /* NoSubstitutionTemplateLiteral */ + ? parseLiteralNode() + : parseTemplateExpression(); + return finishNode(tagExpression); + } + function parseCallExpressionRest(expression) { + while (true) { + expression = parseMemberExpressionRest(expression); + if (token() === 28 /* LessThanToken */) { + // See if this is the start of a generic invocation. If so, consume it and + // keep checking for postfix expressions. Otherwise, it's just a '<' that's + // part of an arithmetic expression. Break out so we consume it higher in the + // stack. + var typeArguments = tryParse(parseTypeArgumentsInExpression); + if (!typeArguments) { + return expression; + } + if (isTemplateStartOfTaggedTemplate()) { + expression = parseTaggedTemplateRest(expression, typeArguments); + continue; + } + var callExpr = createNode(191 /* CallExpression */, expression.pos); + callExpr.expression = expression; + callExpr.typeArguments = typeArguments; + callExpr.arguments = parseArgumentList(); + expression = finishNode(callExpr); + continue; + } + else if (token() === 20 /* OpenParenToken */) { + var callExpr = createNode(191 /* CallExpression */, expression.pos); + callExpr.expression = expression; + callExpr.arguments = parseArgumentList(); + expression = finishNode(callExpr); + continue; + } + return expression; + } + } + function parseArgumentList() { + parseExpected(20 /* OpenParenToken */); + var result = parseDelimitedList(11 /* ArgumentExpressions */, parseArgumentExpression); + parseExpected(21 /* CloseParenToken */); + return result; + } + function parseTypeArgumentsInExpression() { + if (!parseOptional(28 /* LessThanToken */)) { + return undefined; + } + var typeArguments = parseDelimitedList(20 /* TypeArguments */, parseType); + if (!parseExpected(30 /* GreaterThanToken */)) { + // If it doesn't have the closing `>` then it's definitely not an type argument list. + return undefined; + } + // If we have a '<', then only parse this as a argument list if the type arguments + // are complete and we have an open paren. if we don't, rewind and return nothing. + return typeArguments && canFollowTypeArgumentsInExpression() + ? typeArguments + : undefined; + } + function canFollowTypeArgumentsInExpression() { + switch (token()) { + case 20 /* OpenParenToken */: // foo( + case 14 /* NoSubstitutionTemplateLiteral */: // foo `...` + case 15 /* TemplateHead */: // foo `...${100}...` + // these are the only tokens can legally follow a type argument + // list. So we definitely want to treat them as type arg lists. + case 24 /* DotToken */: // foo. + case 21 /* CloseParenToken */: // foo) + case 23 /* CloseBracketToken */: // foo] + case 57 /* ColonToken */: // foo: + case 26 /* SemicolonToken */: // foo; + case 56 /* QuestionToken */: // foo? + case 33 /* EqualsEqualsToken */: // foo == + case 35 /* EqualsEqualsEqualsToken */: // foo === + case 34 /* ExclamationEqualsToken */: // foo != + case 36 /* ExclamationEqualsEqualsToken */: // foo !== + case 54 /* AmpersandAmpersandToken */: // foo && + case 55 /* BarBarToken */: // foo || + case 51 /* CaretToken */: // foo ^ + case 49 /* AmpersandToken */: // foo & + case 50 /* BarToken */: // foo | + case 19 /* CloseBraceToken */: // foo } + case 1 /* EndOfFileToken */: // foo + // these cases can't legally follow a type arg list. However, they're not legal + // expressions either. The user is probably in the middle of a generic type. So + // treat it as such. + return true; + case 27 /* CommaToken */: // foo, + case 18 /* OpenBraceToken */: // foo { + // We don't want to treat these as type arguments. Otherwise we'll parse this + // as an invocation expression. Instead, we want to parse out the expression + // in isolation from the type arguments. + default: + // Anything else treat as an expression. + return false; + } + } + function parsePrimaryExpression() { + switch (token()) { + case 8 /* NumericLiteral */: + case 9 /* BigIntLiteral */: + case 10 /* StringLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: + return parseLiteralNode(); + case 100 /* ThisKeyword */: + case 98 /* SuperKeyword */: + case 96 /* NullKeyword */: + case 102 /* TrueKeyword */: + case 87 /* FalseKeyword */: + return parseTokenNode(); + case 20 /* OpenParenToken */: + return parseParenthesizedExpression(); + case 22 /* OpenBracketToken */: + return parseArrayLiteralExpression(); + case 18 /* OpenBraceToken */: + return parseObjectLiteralExpression(); + case 121 /* AsyncKeyword */: + // Async arrow functions are parsed earlier in parseAssignmentExpressionOrHigher. + // If we encounter `async [no LineTerminator here] function` then this is an async + // function; otherwise, its an identifier. + if (!lookAhead(nextTokenIsFunctionKeywordOnSameLine)) { + break; + } + return parseFunctionExpression(); + case 76 /* ClassKeyword */: + return parseClassExpression(); + case 90 /* FunctionKeyword */: + return parseFunctionExpression(); + case 95 /* NewKeyword */: + return parseNewExpressionOrNewDotTarget(); + case 42 /* SlashToken */: + case 64 /* SlashEqualsToken */: + if (reScanSlashToken() === 13 /* RegularExpressionLiteral */) { + return parseLiteralNode(); + } + break; + case 15 /* TemplateHead */: + return parseTemplateExpression(); + } + return parseIdentifier(ts.Diagnostics.Expression_expected); + } + function parseParenthesizedExpression() { + var node = createNodeWithJSDoc(195 /* ParenthesizedExpression */); + parseExpected(20 /* OpenParenToken */); + node.expression = allowInAnd(parseExpression); + parseExpected(21 /* CloseParenToken */); + return finishNode(node); + } + function parseSpreadElement() { + var node = createNode(208 /* SpreadElement */); + parseExpected(25 /* DotDotDotToken */); + node.expression = parseAssignmentExpressionOrHigher(); + return finishNode(node); + } + function parseArgumentOrArrayLiteralElement() { + return token() === 25 /* DotDotDotToken */ ? parseSpreadElement() : + token() === 27 /* CommaToken */ ? createNode(210 /* OmittedExpression */) : + parseAssignmentExpressionOrHigher(); + } + function parseArgumentExpression() { + return doOutsideOfContext(disallowInAndDecoratorContext, parseArgumentOrArrayLiteralElement); + } + function parseArrayLiteralExpression() { + var node = createNode(187 /* ArrayLiteralExpression */); + parseExpected(22 /* OpenBracketToken */); + if (scanner.hasPrecedingLineBreak()) { + node.multiLine = true; + } + node.elements = parseDelimitedList(15 /* ArrayLiteralMembers */, parseArgumentOrArrayLiteralElement); + parseExpected(23 /* CloseBracketToken */); + return finishNode(node); + } + function parseObjectLiteralElement() { + var node = createNodeWithJSDoc(0 /* Unknown */); + if (parseOptionalToken(25 /* DotDotDotToken */)) { + node.kind = 277 /* SpreadAssignment */; + node.expression = parseAssignmentExpressionOrHigher(); + return finishNode(node); + } + node.decorators = parseDecorators(); + node.modifiers = parseModifiers(); + if (parseContextualModifier(126 /* GetKeyword */)) { + return parseAccessorDeclaration(node, 158 /* GetAccessor */); + } + if (parseContextualModifier(137 /* SetKeyword */)) { + return parseAccessorDeclaration(node, 159 /* SetAccessor */); + } + var asteriskToken = parseOptionalToken(40 /* AsteriskToken */); + var tokenIsIdentifier = isIdentifier(); + node.name = parsePropertyName(); + // Disallowing of optional property assignments and definite assignment assertion happens in the grammar checker. + node.questionToken = parseOptionalToken(56 /* QuestionToken */); + node.exclamationToken = parseOptionalToken(52 /* ExclamationToken */); + if (asteriskToken || token() === 20 /* OpenParenToken */ || token() === 28 /* LessThanToken */) { + return parseMethodDeclaration(node, asteriskToken); + } + // check if it is short-hand property assignment or normal property assignment + // NOTE: if token is EqualsToken it is interpreted as CoverInitializedName production + // CoverInitializedName[Yield] : + // IdentifierReference[?Yield] Initializer[In, ?Yield] + // this is necessary because ObjectLiteral productions are also used to cover grammar for ObjectAssignmentPattern + var isShorthandPropertyAssignment = tokenIsIdentifier && (token() !== 57 /* ColonToken */); + if (isShorthandPropertyAssignment) { + node.kind = 276 /* ShorthandPropertyAssignment */; + var equalsToken = parseOptionalToken(59 /* EqualsToken */); + if (equalsToken) { + node.equalsToken = equalsToken; + node.objectAssignmentInitializer = allowInAnd(parseAssignmentExpressionOrHigher); + } + } + else { + node.kind = 275 /* PropertyAssignment */; + parseExpected(57 /* ColonToken */); + node.initializer = allowInAnd(parseAssignmentExpressionOrHigher); + } + return finishNode(node); + } + function parseObjectLiteralExpression() { + var node = createNode(188 /* ObjectLiteralExpression */); + parseExpected(18 /* OpenBraceToken */); + if (scanner.hasPrecedingLineBreak()) { + node.multiLine = true; + } + node.properties = parseDelimitedList(12 /* ObjectLiteralMembers */, parseObjectLiteralElement, /*considerSemicolonAsDelimiter*/ true); + parseExpected(19 /* CloseBraceToken */); + return finishNode(node); + } + function parseFunctionExpression() { + // GeneratorExpression: + // function* BindingIdentifier [Yield][opt](FormalParameters[Yield]){ GeneratorBody } + // + // FunctionExpression: + // function BindingIdentifier[opt](FormalParameters){ FunctionBody } + var saveDecoratorContext = inDecoratorContext(); + if (saveDecoratorContext) { + setDecoratorContext(/*val*/ false); + } + var node = createNodeWithJSDoc(196 /* FunctionExpression */); + node.modifiers = parseModifiers(); + parseExpected(90 /* FunctionKeyword */); + node.asteriskToken = parseOptionalToken(40 /* AsteriskToken */); + var isGenerator = node.asteriskToken ? 1 /* Yield */ : 0 /* None */; + var isAsync = ts.hasModifier(node, 256 /* Async */) ? 2 /* Await */ : 0 /* None */; + node.name = + isGenerator && isAsync ? doInYieldAndAwaitContext(parseOptionalIdentifier) : + isGenerator ? doInYieldContext(parseOptionalIdentifier) : + isAsync ? doInAwaitContext(parseOptionalIdentifier) : + parseOptionalIdentifier(); + fillSignature(57 /* ColonToken */, isGenerator | isAsync, node); + node.body = parseFunctionBlock(isGenerator | isAsync); + if (saveDecoratorContext) { + setDecoratorContext(/*val*/ true); + } + return finishNode(node); + } + function parseOptionalIdentifier() { + return isIdentifier() ? parseIdentifier() : undefined; + } + function parseNewExpressionOrNewDotTarget() { + var fullStart = scanner.getStartPos(); + parseExpected(95 /* NewKeyword */); + if (parseOptional(24 /* DotToken */)) { + var node_2 = createNode(214 /* MetaProperty */, fullStart); + node_2.keywordToken = 95 /* NewKeyword */; + node_2.name = parseIdentifierName(); + return finishNode(node_2); + } + var expression = parsePrimaryExpression(); + var typeArguments; + while (true) { + expression = parseMemberExpressionRest(expression); + typeArguments = tryParse(parseTypeArgumentsInExpression); + if (isTemplateStartOfTaggedTemplate()) { + ts.Debug.assert(!!typeArguments, "Expected a type argument list; all plain tagged template starts should be consumed in 'parseMemberExpressionRest'"); + expression = parseTaggedTemplateRest(expression, typeArguments); + typeArguments = undefined; + } + break; + } + var node = createNode(192 /* NewExpression */, fullStart); + node.expression = expression; + node.typeArguments = typeArguments; + if (node.typeArguments || token() === 20 /* OpenParenToken */) { + node.arguments = parseArgumentList(); + } + return finishNode(node); + } + // STATEMENTS + function parseBlock(ignoreMissingOpenBrace, diagnosticMessage) { + var node = createNode(218 /* Block */); + if (parseExpected(18 /* OpenBraceToken */, diagnosticMessage) || ignoreMissingOpenBrace) { + if (scanner.hasPrecedingLineBreak()) { + node.multiLine = true; + } + node.statements = parseList(1 /* BlockStatements */, parseStatement); + parseExpected(19 /* CloseBraceToken */); + } + else { + node.statements = createMissingList(); + } + return finishNode(node); + } + function parseFunctionBlock(flags, diagnosticMessage) { + var savedYieldContext = inYieldContext(); + setYieldContext(!!(flags & 1 /* Yield */)); + var savedAwaitContext = inAwaitContext(); + setAwaitContext(!!(flags & 2 /* Await */)); + // We may be in a [Decorator] context when parsing a function expression or + // arrow function. The body of the function is not in [Decorator] context. + var saveDecoratorContext = inDecoratorContext(); + if (saveDecoratorContext) { + setDecoratorContext(/*val*/ false); + } + var block = parseBlock(!!(flags & 16 /* IgnoreMissingOpenBrace */), diagnosticMessage); + if (saveDecoratorContext) { + setDecoratorContext(/*val*/ true); + } + setYieldContext(savedYieldContext); + setAwaitContext(savedAwaitContext); + return block; + } + function parseEmptyStatement() { + var node = createNode(220 /* EmptyStatement */); + parseExpected(26 /* SemicolonToken */); + return finishNode(node); + } + function parseIfStatement() { + var node = createNode(222 /* IfStatement */); + parseExpected(91 /* IfKeyword */); + parseExpected(20 /* OpenParenToken */); + node.expression = allowInAnd(parseExpression); + parseExpected(21 /* CloseParenToken */); + node.thenStatement = parseStatement(); + node.elseStatement = parseOptional(83 /* ElseKeyword */) ? parseStatement() : undefined; + return finishNode(node); + } + function parseDoStatement() { + var node = createNode(223 /* DoStatement */); + parseExpected(82 /* DoKeyword */); + node.statement = parseStatement(); + parseExpected(107 /* WhileKeyword */); + parseExpected(20 /* OpenParenToken */); + node.expression = allowInAnd(parseExpression); + parseExpected(21 /* CloseParenToken */); + // From: https://mail.mozilla.org/pipermail/es-discuss/2011-August/016188.html + // 157 min --- All allen at wirfs-brock.com CONF --- "do{;}while(false)false" prohibited in + // spec but allowed in consensus reality. Approved -- this is the de-facto standard whereby + // do;while(0)x will have a semicolon inserted before x. + parseOptional(26 /* SemicolonToken */); + return finishNode(node); + } + function parseWhileStatement() { + var node = createNode(224 /* WhileStatement */); + parseExpected(107 /* WhileKeyword */); + parseExpected(20 /* OpenParenToken */); + node.expression = allowInAnd(parseExpression); + parseExpected(21 /* CloseParenToken */); + node.statement = parseStatement(); + return finishNode(node); + } + function parseForOrForInOrForOfStatement() { + var pos = getNodePos(); + parseExpected(89 /* ForKeyword */); + var awaitToken = parseOptionalToken(122 /* AwaitKeyword */); + parseExpected(20 /* OpenParenToken */); + var initializer; + if (token() !== 26 /* SemicolonToken */) { + if (token() === 105 /* VarKeyword */ || token() === 111 /* LetKeyword */ || token() === 77 /* ConstKeyword */) { + initializer = parseVariableDeclarationList(/*inForStatementInitializer*/ true); + } + else { + initializer = disallowInAnd(parseExpression); + } + } + var forOrForInOrForOfStatement; + if (awaitToken ? parseExpected(147 /* OfKeyword */) : parseOptional(147 /* OfKeyword */)) { + var forOfStatement = createNode(227 /* ForOfStatement */, pos); + forOfStatement.awaitModifier = awaitToken; + forOfStatement.initializer = initializer; + forOfStatement.expression = allowInAnd(parseAssignmentExpressionOrHigher); + parseExpected(21 /* CloseParenToken */); + forOrForInOrForOfStatement = forOfStatement; + } + else if (parseOptional(93 /* InKeyword */)) { + var forInStatement = createNode(226 /* ForInStatement */, pos); + forInStatement.initializer = initializer; + forInStatement.expression = allowInAnd(parseExpression); + parseExpected(21 /* CloseParenToken */); + forOrForInOrForOfStatement = forInStatement; + } + else { + var forStatement = createNode(225 /* ForStatement */, pos); + forStatement.initializer = initializer; + parseExpected(26 /* SemicolonToken */); + if (token() !== 26 /* SemicolonToken */ && token() !== 21 /* CloseParenToken */) { + forStatement.condition = allowInAnd(parseExpression); + } + parseExpected(26 /* SemicolonToken */); + if (token() !== 21 /* CloseParenToken */) { + forStatement.incrementor = allowInAnd(parseExpression); + } + parseExpected(21 /* CloseParenToken */); + forOrForInOrForOfStatement = forStatement; + } + forOrForInOrForOfStatement.statement = parseStatement(); + return finishNode(forOrForInOrForOfStatement); + } + function parseBreakOrContinueStatement(kind) { + var node = createNode(kind); + parseExpected(kind === 229 /* BreakStatement */ ? 73 /* BreakKeyword */ : 78 /* ContinueKeyword */); + if (!canParseSemicolon()) { + node.label = parseIdentifier(); + } + parseSemicolon(); + return finishNode(node); + } + function parseReturnStatement() { + var node = createNode(230 /* ReturnStatement */); + parseExpected(97 /* ReturnKeyword */); + if (!canParseSemicolon()) { + node.expression = allowInAnd(parseExpression); + } + parseSemicolon(); + return finishNode(node); + } + function parseWithStatement() { + var node = createNode(231 /* WithStatement */); + parseExpected(108 /* WithKeyword */); + parseExpected(20 /* OpenParenToken */); + node.expression = allowInAnd(parseExpression); + parseExpected(21 /* CloseParenToken */); + node.statement = doInsideOfContext(8388608 /* InWithStatement */, parseStatement); + return finishNode(node); + } + function parseCaseClause() { + var node = createNode(271 /* CaseClause */); + parseExpected(74 /* CaseKeyword */); + node.expression = allowInAnd(parseExpression); + parseExpected(57 /* ColonToken */); + node.statements = parseList(3 /* SwitchClauseStatements */, parseStatement); + return finishNode(node); + } + function parseDefaultClause() { + var node = createNode(272 /* DefaultClause */); + parseExpected(80 /* DefaultKeyword */); + parseExpected(57 /* ColonToken */); + node.statements = parseList(3 /* SwitchClauseStatements */, parseStatement); + return finishNode(node); + } + function parseCaseOrDefaultClause() { + return token() === 74 /* CaseKeyword */ ? parseCaseClause() : parseDefaultClause(); + } + function parseSwitchStatement() { + var node = createNode(232 /* SwitchStatement */); + parseExpected(99 /* SwitchKeyword */); + parseExpected(20 /* OpenParenToken */); + node.expression = allowInAnd(parseExpression); + parseExpected(21 /* CloseParenToken */); + var caseBlock = createNode(246 /* CaseBlock */); + parseExpected(18 /* OpenBraceToken */); + caseBlock.clauses = parseList(2 /* SwitchClauses */, parseCaseOrDefaultClause); + parseExpected(19 /* CloseBraceToken */); + node.caseBlock = finishNode(caseBlock); + return finishNode(node); + } + function parseThrowStatement() { + // ThrowStatement[Yield] : + // throw [no LineTerminator here]Expression[In, ?Yield]; + // Because of automatic semicolon insertion, we need to report error if this + // throw could be terminated with a semicolon. Note: we can't call 'parseExpression' + // directly as that might consume an expression on the following line. + // We just return 'undefined' in that case. The actual error will be reported in the + // grammar walker. + var node = createNode(234 /* ThrowStatement */); + parseExpected(101 /* ThrowKeyword */); + node.expression = scanner.hasPrecedingLineBreak() ? undefined : allowInAnd(parseExpression); + parseSemicolon(); + return finishNode(node); + } + // TODO: Review for error recovery + function parseTryStatement() { + var node = createNode(235 /* TryStatement */); + parseExpected(103 /* TryKeyword */); + node.tryBlock = parseBlock(/*ignoreMissingOpenBrace*/ false); + node.catchClause = token() === 75 /* CatchKeyword */ ? parseCatchClause() : undefined; + // If we don't have a catch clause, then we must have a finally clause. Try to parse + // one out no matter what. + if (!node.catchClause || token() === 88 /* FinallyKeyword */) { + parseExpected(88 /* FinallyKeyword */); + node.finallyBlock = parseBlock(/*ignoreMissingOpenBrace*/ false); + } + return finishNode(node); + } + function parseCatchClause() { + var result = createNode(274 /* CatchClause */); + parseExpected(75 /* CatchKeyword */); + if (parseOptional(20 /* OpenParenToken */)) { + result.variableDeclaration = parseVariableDeclaration(); + parseExpected(21 /* CloseParenToken */); + } + else { + // Keep shape of node to avoid degrading performance. + result.variableDeclaration = undefined; + } + result.block = parseBlock(/*ignoreMissingOpenBrace*/ false); + return finishNode(result); + } + function parseDebuggerStatement() { + var node = createNode(236 /* DebuggerStatement */); + parseExpected(79 /* DebuggerKeyword */); + parseSemicolon(); + return finishNode(node); + } + function parseExpressionOrLabeledStatement() { + // Avoiding having to do the lookahead for a labeled statement by just trying to parse + // out an expression, seeing if it is identifier and then seeing if it is followed by + // a colon. + var node = createNodeWithJSDoc(0 /* Unknown */); + var expression = allowInAnd(parseExpression); + if (expression.kind === 72 /* Identifier */ && parseOptional(57 /* ColonToken */)) { + node.kind = 233 /* LabeledStatement */; + node.label = expression; + node.statement = parseStatement(); + } + else { + node.kind = 221 /* ExpressionStatement */; + node.expression = expression; + parseSemicolon(); + } + return finishNode(node); + } + function nextTokenIsIdentifierOrKeywordOnSameLine() { + nextToken(); + return ts.tokenIsIdentifierOrKeyword(token()) && !scanner.hasPrecedingLineBreak(); + } + function nextTokenIsClassKeywordOnSameLine() { + nextToken(); + return token() === 76 /* ClassKeyword */ && !scanner.hasPrecedingLineBreak(); + } + function nextTokenIsFunctionKeywordOnSameLine() { + nextToken(); + return token() === 90 /* FunctionKeyword */ && !scanner.hasPrecedingLineBreak(); + } + function nextTokenIsIdentifierOrKeywordOrLiteralOnSameLine() { + nextToken(); + return (ts.tokenIsIdentifierOrKeyword(token()) || token() === 8 /* NumericLiteral */ || token() === 9 /* BigIntLiteral */ || token() === 10 /* StringLiteral */) && !scanner.hasPrecedingLineBreak(); + } + function isDeclaration() { + while (true) { + switch (token()) { + case 105 /* VarKeyword */: + case 111 /* LetKeyword */: + case 77 /* ConstKeyword */: + case 90 /* FunctionKeyword */: + case 76 /* ClassKeyword */: + case 84 /* EnumKeyword */: + return true; + // 'declare', 'module', 'namespace', 'interface'* and 'type' are all legal JavaScript identifiers; + // however, an identifier cannot be followed by another identifier on the same line. This is what we + // count on to parse out the respective declarations. For instance, we exploit this to say that + // + // namespace n + // + // can be none other than the beginning of a namespace declaration, but need to respect that JavaScript sees + // + // namespace + // n + // + // as the identifier 'namespace' on one line followed by the identifier 'n' on another. + // We need to look one token ahead to see if it permissible to try parsing a declaration. + // + // *Note*: 'interface' is actually a strict mode reserved word. So while + // + // "use strict" + // interface + // I {} + // + // could be legal, it would add complexity for very little gain. + case 110 /* InterfaceKeyword */: + case 140 /* TypeKeyword */: + return nextTokenIsIdentifierOnSameLine(); + case 130 /* ModuleKeyword */: + case 131 /* NamespaceKeyword */: + return nextTokenIsIdentifierOrStringLiteralOnSameLine(); + case 118 /* AbstractKeyword */: + case 121 /* AsyncKeyword */: + case 125 /* DeclareKeyword */: + case 113 /* PrivateKeyword */: + case 114 /* ProtectedKeyword */: + case 115 /* PublicKeyword */: + case 133 /* ReadonlyKeyword */: + nextToken(); + // ASI takes effect for this modifier. + if (scanner.hasPrecedingLineBreak()) { + return false; + } + continue; + case 145 /* GlobalKeyword */: + nextToken(); + return token() === 18 /* OpenBraceToken */ || token() === 72 /* Identifier */ || token() === 85 /* ExportKeyword */; + case 92 /* ImportKeyword */: + nextToken(); + return token() === 10 /* StringLiteral */ || token() === 40 /* AsteriskToken */ || + token() === 18 /* OpenBraceToken */ || ts.tokenIsIdentifierOrKeyword(token()); + case 85 /* ExportKeyword */: + nextToken(); + if (token() === 59 /* EqualsToken */ || token() === 40 /* AsteriskToken */ || + token() === 18 /* OpenBraceToken */ || token() === 80 /* DefaultKeyword */ || + token() === 119 /* AsKeyword */) { + return true; + } + continue; + case 116 /* StaticKeyword */: + nextToken(); + continue; + default: + return false; + } + } + } + function isStartOfDeclaration() { + return lookAhead(isDeclaration); + } + function isStartOfStatement() { + switch (token()) { + case 58 /* AtToken */: + case 26 /* SemicolonToken */: + case 18 /* OpenBraceToken */: + case 105 /* VarKeyword */: + case 111 /* LetKeyword */: + case 90 /* FunctionKeyword */: + case 76 /* ClassKeyword */: + case 84 /* EnumKeyword */: + case 91 /* IfKeyword */: + case 82 /* DoKeyword */: + case 107 /* WhileKeyword */: + case 89 /* ForKeyword */: + case 78 /* ContinueKeyword */: + case 73 /* BreakKeyword */: + case 97 /* ReturnKeyword */: + case 108 /* WithKeyword */: + case 99 /* SwitchKeyword */: + case 101 /* ThrowKeyword */: + case 103 /* TryKeyword */: + case 79 /* DebuggerKeyword */: + // 'catch' and 'finally' do not actually indicate that the code is part of a statement, + // however, we say they are here so that we may gracefully parse them and error later. + case 75 /* CatchKeyword */: + case 88 /* FinallyKeyword */: + return true; + case 92 /* ImportKeyword */: + return isStartOfDeclaration() || lookAhead(nextTokenIsOpenParenOrLessThanOrDot); + case 77 /* ConstKeyword */: + case 85 /* ExportKeyword */: + return isStartOfDeclaration(); + case 121 /* AsyncKeyword */: + case 125 /* DeclareKeyword */: + case 110 /* InterfaceKeyword */: + case 130 /* ModuleKeyword */: + case 131 /* NamespaceKeyword */: + case 140 /* TypeKeyword */: + case 145 /* GlobalKeyword */: + // When these don't start a declaration, they're an identifier in an expression statement + return true; + case 115 /* PublicKeyword */: + case 113 /* PrivateKeyword */: + case 114 /* ProtectedKeyword */: + case 116 /* StaticKeyword */: + case 133 /* ReadonlyKeyword */: + // When these don't start a declaration, they may be the start of a class member if an identifier + // immediately follows. Otherwise they're an identifier in an expression statement. + return isStartOfDeclaration() || !lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine); + default: + return isStartOfExpression(); + } + } + function nextTokenIsIdentifierOrStartOfDestructuring() { + nextToken(); + return isIdentifier() || token() === 18 /* OpenBraceToken */ || token() === 22 /* OpenBracketToken */; + } + function isLetDeclaration() { + // In ES6 'let' always starts a lexical declaration if followed by an identifier or { + // or [. + return lookAhead(nextTokenIsIdentifierOrStartOfDestructuring); + } + function parseStatement() { + switch (token()) { + case 26 /* SemicolonToken */: + return parseEmptyStatement(); + case 18 /* OpenBraceToken */: + return parseBlock(/*ignoreMissingOpenBrace*/ false); + case 105 /* VarKeyword */: + return parseVariableStatement(createNodeWithJSDoc(237 /* VariableDeclaration */)); + case 111 /* LetKeyword */: + if (isLetDeclaration()) { + return parseVariableStatement(createNodeWithJSDoc(237 /* VariableDeclaration */)); + } + break; + case 90 /* FunctionKeyword */: + return parseFunctionDeclaration(createNodeWithJSDoc(239 /* FunctionDeclaration */)); + case 76 /* ClassKeyword */: + return parseClassDeclaration(createNodeWithJSDoc(240 /* ClassDeclaration */)); + case 91 /* IfKeyword */: + return parseIfStatement(); + case 82 /* DoKeyword */: + return parseDoStatement(); + case 107 /* WhileKeyword */: + return parseWhileStatement(); + case 89 /* ForKeyword */: + return parseForOrForInOrForOfStatement(); + case 78 /* ContinueKeyword */: + return parseBreakOrContinueStatement(228 /* ContinueStatement */); + case 73 /* BreakKeyword */: + return parseBreakOrContinueStatement(229 /* BreakStatement */); + case 97 /* ReturnKeyword */: + return parseReturnStatement(); + case 108 /* WithKeyword */: + return parseWithStatement(); + case 99 /* SwitchKeyword */: + return parseSwitchStatement(); + case 101 /* ThrowKeyword */: + return parseThrowStatement(); + case 103 /* TryKeyword */: + // Include 'catch' and 'finally' for error recovery. + case 75 /* CatchKeyword */: + case 88 /* FinallyKeyword */: + return parseTryStatement(); + case 79 /* DebuggerKeyword */: + return parseDebuggerStatement(); + case 58 /* AtToken */: + return parseDeclaration(); + case 121 /* AsyncKeyword */: + case 110 /* InterfaceKeyword */: + case 140 /* TypeKeyword */: + case 130 /* ModuleKeyword */: + case 131 /* NamespaceKeyword */: + case 125 /* DeclareKeyword */: + case 77 /* ConstKeyword */: + case 84 /* EnumKeyword */: + case 85 /* ExportKeyword */: + case 92 /* ImportKeyword */: + case 113 /* PrivateKeyword */: + case 114 /* ProtectedKeyword */: + case 115 /* PublicKeyword */: + case 118 /* AbstractKeyword */: + case 116 /* StaticKeyword */: + case 133 /* ReadonlyKeyword */: + case 145 /* GlobalKeyword */: + if (isStartOfDeclaration()) { + return parseDeclaration(); + } + break; + } + return parseExpressionOrLabeledStatement(); + } + function isDeclareModifier(modifier) { + return modifier.kind === 125 /* DeclareKeyword */; + } + function parseDeclaration() { + var node = createNodeWithJSDoc(0 /* Unknown */); + node.decorators = parseDecorators(); + node.modifiers = parseModifiers(); + if (ts.some(node.modifiers, isDeclareModifier)) { + for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) { + var m = _a[_i]; + m.flags |= 4194304 /* Ambient */; + } + return doInsideOfContext(4194304 /* Ambient */, function () { return parseDeclarationWorker(node); }); + } + else { + return parseDeclarationWorker(node); + } + } + function parseDeclarationWorker(node) { + switch (token()) { + case 105 /* VarKeyword */: + case 111 /* LetKeyword */: + case 77 /* ConstKeyword */: + return parseVariableStatement(node); + case 90 /* FunctionKeyword */: + return parseFunctionDeclaration(node); + case 76 /* ClassKeyword */: + return parseClassDeclaration(node); + case 110 /* InterfaceKeyword */: + return parseInterfaceDeclaration(node); + case 140 /* TypeKeyword */: + return parseTypeAliasDeclaration(node); + case 84 /* EnumKeyword */: + return parseEnumDeclaration(node); + case 145 /* GlobalKeyword */: + case 130 /* ModuleKeyword */: + case 131 /* NamespaceKeyword */: + return parseModuleDeclaration(node); + case 92 /* ImportKeyword */: + return parseImportDeclarationOrImportEqualsDeclaration(node); + case 85 /* ExportKeyword */: + nextToken(); + switch (token()) { + case 80 /* DefaultKeyword */: + case 59 /* EqualsToken */: + return parseExportAssignment(node); + case 119 /* AsKeyword */: + return parseNamespaceExportDeclaration(node); + default: + return parseExportDeclaration(node); + } + default: + if (node.decorators || node.modifiers) { + // We reached this point because we encountered decorators and/or modifiers and assumed a declaration + // would follow. For recovery and error reporting purposes, return an incomplete declaration. + var missing = createMissingNode(258 /* MissingDeclaration */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected); + missing.pos = node.pos; + missing.decorators = node.decorators; + missing.modifiers = node.modifiers; + return finishNode(missing); + } + return undefined; // TODO: GH#18217 + } + } + function nextTokenIsIdentifierOrStringLiteralOnSameLine() { + nextToken(); + return !scanner.hasPrecedingLineBreak() && (isIdentifier() || token() === 10 /* StringLiteral */); + } + function parseFunctionBlockOrSemicolon(flags, diagnosticMessage) { + if (token() !== 18 /* OpenBraceToken */ && canParseSemicolon()) { + parseSemicolon(); + return; + } + return parseFunctionBlock(flags, diagnosticMessage); + } + // DECLARATIONS + function parseArrayBindingElement() { + if (token() === 27 /* CommaToken */) { + return createNode(210 /* OmittedExpression */); + } + var node = createNode(186 /* BindingElement */); + node.dotDotDotToken = parseOptionalToken(25 /* DotDotDotToken */); + node.name = parseIdentifierOrPattern(); + node.initializer = parseInitializer(); + return finishNode(node); + } + function parseObjectBindingElement() { + var node = createNode(186 /* BindingElement */); + node.dotDotDotToken = parseOptionalToken(25 /* DotDotDotToken */); + var tokenIsIdentifier = isIdentifier(); + var propertyName = parsePropertyName(); + if (tokenIsIdentifier && token() !== 57 /* ColonToken */) { + node.name = propertyName; + } + else { + parseExpected(57 /* ColonToken */); + node.propertyName = propertyName; + node.name = parseIdentifierOrPattern(); + } + node.initializer = parseInitializer(); + return finishNode(node); + } + function parseObjectBindingPattern() { + var node = createNode(184 /* ObjectBindingPattern */); + parseExpected(18 /* OpenBraceToken */); + node.elements = parseDelimitedList(9 /* ObjectBindingElements */, parseObjectBindingElement); + parseExpected(19 /* CloseBraceToken */); + return finishNode(node); + } + function parseArrayBindingPattern() { + var node = createNode(185 /* ArrayBindingPattern */); + parseExpected(22 /* OpenBracketToken */); + node.elements = parseDelimitedList(10 /* ArrayBindingElements */, parseArrayBindingElement); + parseExpected(23 /* CloseBracketToken */); + return finishNode(node); + } + function isIdentifierOrPattern() { + return token() === 18 /* OpenBraceToken */ || token() === 22 /* OpenBracketToken */ || isIdentifier(); + } + function parseIdentifierOrPattern() { + if (token() === 22 /* OpenBracketToken */) { + return parseArrayBindingPattern(); + } + if (token() === 18 /* OpenBraceToken */) { + return parseObjectBindingPattern(); + } + return parseIdentifier(); + } + function parseVariableDeclarationAllowExclamation() { + return parseVariableDeclaration(/*allowExclamation*/ true); + } + function parseVariableDeclaration(allowExclamation) { + var node = createNode(237 /* VariableDeclaration */); + node.name = parseIdentifierOrPattern(); + if (allowExclamation && node.name.kind === 72 /* Identifier */ && + token() === 52 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) { + node.exclamationToken = parseTokenNode(); + } + node.type = parseTypeAnnotation(); + if (!isInOrOfKeyword(token())) { + node.initializer = parseInitializer(); + } + return finishNode(node); + } + function parseVariableDeclarationList(inForStatementInitializer) { + var node = createNode(238 /* VariableDeclarationList */); + switch (token()) { + case 105 /* VarKeyword */: + break; + case 111 /* LetKeyword */: + node.flags |= 1 /* Let */; + break; + case 77 /* ConstKeyword */: + node.flags |= 2 /* Const */; + break; + default: + ts.Debug.fail(); + } + nextToken(); + // The user may have written the following: + // + // for (let of X) { } + // + // In this case, we want to parse an empty declaration list, and then parse 'of' + // as a keyword. The reason this is not automatic is that 'of' is a valid identifier. + // So we need to look ahead to determine if 'of' should be treated as a keyword in + // this context. + // The checker will then give an error that there is an empty declaration list. + if (token() === 147 /* OfKeyword */ && lookAhead(canFollowContextualOfKeyword)) { + node.declarations = createMissingList(); + } + else { + var savedDisallowIn = inDisallowInContext(); + setDisallowInContext(inForStatementInitializer); + node.declarations = parseDelimitedList(8 /* VariableDeclarations */, inForStatementInitializer ? parseVariableDeclaration : parseVariableDeclarationAllowExclamation); + setDisallowInContext(savedDisallowIn); + } + return finishNode(node); + } + function canFollowContextualOfKeyword() { + return nextTokenIsIdentifier() && nextToken() === 21 /* CloseParenToken */; + } + function parseVariableStatement(node) { + node.kind = 219 /* VariableStatement */; + node.declarationList = parseVariableDeclarationList(/*inForStatementInitializer*/ false); + parseSemicolon(); + return finishNode(node); + } + function parseFunctionDeclaration(node) { + node.kind = 239 /* FunctionDeclaration */; + parseExpected(90 /* FunctionKeyword */); + node.asteriskToken = parseOptionalToken(40 /* AsteriskToken */); + node.name = ts.hasModifier(node, 512 /* Default */) ? parseOptionalIdentifier() : parseIdentifier(); + var isGenerator = node.asteriskToken ? 1 /* Yield */ : 0 /* None */; + var isAsync = ts.hasModifier(node, 256 /* Async */) ? 2 /* Await */ : 0 /* None */; + fillSignature(57 /* ColonToken */, isGenerator | isAsync, node); + node.body = parseFunctionBlockOrSemicolon(isGenerator | isAsync, ts.Diagnostics.or_expected); + return finishNode(node); + } + function parseConstructorDeclaration(node) { + node.kind = 157 /* Constructor */; + parseExpected(124 /* ConstructorKeyword */); + fillSignature(57 /* ColonToken */, 0 /* None */, node); + node.body = parseFunctionBlockOrSemicolon(0 /* None */, ts.Diagnostics.or_expected); + return finishNode(node); + } + function parseMethodDeclaration(node, asteriskToken, diagnosticMessage) { + node.kind = 156 /* MethodDeclaration */; + node.asteriskToken = asteriskToken; + var isGenerator = asteriskToken ? 1 /* Yield */ : 0 /* None */; + var isAsync = ts.hasModifier(node, 256 /* Async */) ? 2 /* Await */ : 0 /* None */; + fillSignature(57 /* ColonToken */, isGenerator | isAsync, node); + node.body = parseFunctionBlockOrSemicolon(isGenerator | isAsync, diagnosticMessage); + return finishNode(node); + } + function parsePropertyDeclaration(node) { + node.kind = 154 /* PropertyDeclaration */; + if (!node.questionToken && token() === 52 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) { + node.exclamationToken = parseTokenNode(); + } + node.type = parseTypeAnnotation(); + // For instance properties specifically, since they are evaluated inside the constructor, + // we do *not * want to parse yield expressions, so we specifically turn the yield context + // off. The grammar would look something like this: + // + // MemberVariableDeclaration[Yield]: + // AccessibilityModifier_opt PropertyName TypeAnnotation_opt Initializer_opt[In]; + // AccessibilityModifier_opt static_opt PropertyName TypeAnnotation_opt Initializer_opt[In, ?Yield]; + // + // The checker may still error in the static case to explicitly disallow the yield expression. + node.initializer = ts.hasModifier(node, 32 /* Static */) + ? allowInAnd(parseInitializer) + : doOutsideOfContext(4096 /* YieldContext */ | 2048 /* DisallowInContext */, parseInitializer); + parseSemicolon(); + return finishNode(node); + } + function parsePropertyOrMethodDeclaration(node) { + var asteriskToken = parseOptionalToken(40 /* AsteriskToken */); + node.name = parsePropertyName(); + // Note: this is not legal as per the grammar. But we allow it in the parser and + // report an error in the grammar checker. + node.questionToken = parseOptionalToken(56 /* QuestionToken */); + if (asteriskToken || token() === 20 /* OpenParenToken */ || token() === 28 /* LessThanToken */) { + return parseMethodDeclaration(node, asteriskToken, ts.Diagnostics.or_expected); + } + return parsePropertyDeclaration(node); + } + function parseAccessorDeclaration(node, kind) { + node.kind = kind; + node.name = parsePropertyName(); + fillSignature(57 /* ColonToken */, 0 /* None */, node); + node.body = parseFunctionBlockOrSemicolon(0 /* None */); + return finishNode(node); + } + function isClassMemberStart() { + var idToken; + if (token() === 58 /* AtToken */) { + return true; + } + // Eat up all modifiers, but hold on to the last one in case it is actually an identifier. + while (ts.isModifierKind(token())) { + idToken = token(); + // If the idToken is a class modifier (protected, private, public, and static), it is + // certain that we are starting to parse class member. This allows better error recovery + // Example: + // public foo() ... // true + // public @dec blah ... // true; we will then report an error later + // export public ... // true; we will then report an error later + if (ts.isClassMemberModifier(idToken)) { + return true; + } + nextToken(); + } + if (token() === 40 /* AsteriskToken */) { + return true; + } + // Try to get the first property-like token following all modifiers. + // This can either be an identifier or the 'get' or 'set' keywords. + if (isLiteralPropertyName()) { + idToken = token(); + nextToken(); + } + // Index signatures and computed properties are class members; we can parse. + if (token() === 22 /* OpenBracketToken */) { + return true; + } + // If we were able to get any potential identifier... + if (idToken !== undefined) { + // If we have a non-keyword identifier, or if we have an accessor, then it's safe to parse. + if (!ts.isKeyword(idToken) || idToken === 137 /* SetKeyword */ || idToken === 126 /* GetKeyword */) { + return true; + } + // If it *is* a keyword, but not an accessor, check a little farther along + // to see if it should actually be parsed as a class member. + switch (token()) { + case 20 /* OpenParenToken */: // Method declaration + case 28 /* LessThanToken */: // Generic Method declaration + case 52 /* ExclamationToken */: // Non-null assertion on property name + case 57 /* ColonToken */: // Type Annotation for declaration + case 59 /* EqualsToken */: // Initializer for declaration + case 56 /* QuestionToken */: // Not valid, but permitted so that it gets caught later on. + return true; + default: + // Covers + // - Semicolons (declaration termination) + // - Closing braces (end-of-class, must be declaration) + // - End-of-files (not valid, but permitted so that it gets caught later on) + // - Line-breaks (enabling *automatic semicolon insertion*) + return canParseSemicolon(); + } + } + return false; + } + function parseDecorators() { + var list; + var listPos = getNodePos(); + while (true) { + var decoratorStart = getNodePos(); + if (!parseOptional(58 /* AtToken */)) { + break; + } + var decorator = createNode(152 /* Decorator */, decoratorStart); + decorator.expression = doInDecoratorContext(parseLeftHandSideExpressionOrHigher); + finishNode(decorator); + (list || (list = [])).push(decorator); + } + return list && createNodeArray(list, listPos); + } + /* + * There are situations in which a modifier like 'const' will appear unexpectedly, such as on a class member. + * In those situations, if we are entirely sure that 'const' is not valid on its own (such as when ASI takes effect + * and turns it into a standalone declaration), then it is better to parse it and report an error later. + * + * In such situations, 'permitInvalidConstAsModifier' should be set to true. + */ + function parseModifiers(permitInvalidConstAsModifier) { + var list; + var listPos = getNodePos(); + while (true) { + var modifierStart = scanner.getStartPos(); + var modifierKind = token(); + if (token() === 77 /* ConstKeyword */ && permitInvalidConstAsModifier) { + // We need to ensure that any subsequent modifiers appear on the same line + // so that when 'const' is a standalone declaration, we don't issue an error. + if (!tryParse(nextTokenIsOnSameLineAndCanFollowModifier)) { + break; + } + } + else { + if (!parseAnyContextualModifier()) { + break; + } + } + var modifier = finishNode(createNode(modifierKind, modifierStart)); + (list || (list = [])).push(modifier); + } + return list && createNodeArray(list, listPos); + } + function parseModifiersForArrowFunction() { + var modifiers; + if (token() === 121 /* AsyncKeyword */) { + var modifierStart = scanner.getStartPos(); + var modifierKind = token(); + nextToken(); + var modifier = finishNode(createNode(modifierKind, modifierStart)); + modifiers = createNodeArray([modifier], modifierStart); + } + return modifiers; + } + function parseClassElement() { + if (token() === 26 /* SemicolonToken */) { + var result = createNode(217 /* SemicolonClassElement */); + nextToken(); + return finishNode(result); + } + var node = createNodeWithJSDoc(0 /* Unknown */); + node.decorators = parseDecorators(); + node.modifiers = parseModifiers(/*permitInvalidConstAsModifier*/ true); + if (parseContextualModifier(126 /* GetKeyword */)) { + return parseAccessorDeclaration(node, 158 /* GetAccessor */); + } + if (parseContextualModifier(137 /* SetKeyword */)) { + return parseAccessorDeclaration(node, 159 /* SetAccessor */); + } + if (token() === 124 /* ConstructorKeyword */) { + return parseConstructorDeclaration(node); + } + if (isIndexSignature()) { + return parseIndexSignatureDeclaration(node); + } + // It is very important that we check this *after* checking indexers because + // the [ token can start an index signature or a computed property name + if (ts.tokenIsIdentifierOrKeyword(token()) || + token() === 10 /* StringLiteral */ || + token() === 8 /* NumericLiteral */ || + token() === 40 /* AsteriskToken */ || + token() === 22 /* OpenBracketToken */) { + return parsePropertyOrMethodDeclaration(node); + } + if (node.decorators || node.modifiers) { + // treat this as a property declaration with a missing name. + node.name = createMissingNode(72 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected); + return parsePropertyDeclaration(node); + } + // 'isClassMemberStart' should have hinted not to attempt parsing. + return ts.Debug.fail("Should not have attempted to parse class member declaration."); + } + function parseClassExpression() { + return parseClassDeclarationOrExpression(createNodeWithJSDoc(0 /* Unknown */), 209 /* ClassExpression */); + } + function parseClassDeclaration(node) { + return parseClassDeclarationOrExpression(node, 240 /* ClassDeclaration */); + } + function parseClassDeclarationOrExpression(node, kind) { + node.kind = kind; + parseExpected(76 /* ClassKeyword */); + node.name = parseNameOfClassDeclarationOrExpression(); + node.typeParameters = parseTypeParameters(); + node.heritageClauses = parseHeritageClauses(); + if (parseExpected(18 /* OpenBraceToken */)) { + // ClassTail[Yield,Await] : (Modified) See 14.5 + // ClassHeritage[?Yield,?Await]opt { ClassBody[?Yield,?Await]opt } + node.members = parseClassMembers(); + parseExpected(19 /* CloseBraceToken */); + } + else { + node.members = createMissingList(); + } + return finishNode(node); + } + function parseNameOfClassDeclarationOrExpression() { + // implements is a future reserved word so + // 'class implements' might mean either + // - class expression with omitted name, 'implements' starts heritage clause + // - class with name 'implements' + // 'isImplementsClause' helps to disambiguate between these two cases + return isIdentifier() && !isImplementsClause() + ? parseIdentifier() + : undefined; + } + function isImplementsClause() { + return token() === 109 /* ImplementsKeyword */ && lookAhead(nextTokenIsIdentifierOrKeyword); + } + function parseHeritageClauses() { + // ClassTail[Yield,Await] : (Modified) See 14.5 + // ClassHeritage[?Yield,?Await]opt { ClassBody[?Yield,?Await]opt } + if (isHeritageClause()) { + return parseList(22 /* HeritageClauses */, parseHeritageClause); + } + return undefined; + } + function parseHeritageClause() { + var tok = token(); + ts.Debug.assert(tok === 86 /* ExtendsKeyword */ || tok === 109 /* ImplementsKeyword */); // isListElement() should ensure this. + var node = createNode(273 /* HeritageClause */); + node.token = tok; + nextToken(); + node.types = parseDelimitedList(7 /* HeritageClauseElement */, parseExpressionWithTypeArguments); + return finishNode(node); + } + function parseExpressionWithTypeArguments() { + var node = createNode(211 /* ExpressionWithTypeArguments */); + node.expression = parseLeftHandSideExpressionOrHigher(); + node.typeArguments = tryParseTypeArguments(); + return finishNode(node); + } + function tryParseTypeArguments() { + return token() === 28 /* LessThanToken */ + ? parseBracketedList(20 /* TypeArguments */, parseType, 28 /* LessThanToken */, 30 /* GreaterThanToken */) + : undefined; + } + function isHeritageClause() { + return token() === 86 /* ExtendsKeyword */ || token() === 109 /* ImplementsKeyword */; + } + function parseClassMembers() { + return parseList(5 /* ClassMembers */, parseClassElement); + } + function parseInterfaceDeclaration(node) { + node.kind = 241 /* InterfaceDeclaration */; + parseExpected(110 /* InterfaceKeyword */); + node.name = parseIdentifier(); + node.typeParameters = parseTypeParameters(); + node.heritageClauses = parseHeritageClauses(); + node.members = parseObjectTypeMembers(); + return finishNode(node); + } + function parseTypeAliasDeclaration(node) { + node.kind = 242 /* TypeAliasDeclaration */; + parseExpected(140 /* TypeKeyword */); + node.name = parseIdentifier(); + node.typeParameters = parseTypeParameters(); + parseExpected(59 /* EqualsToken */); + node.type = parseType(); + parseSemicolon(); + return finishNode(node); + } + // In an ambient declaration, the grammar only allows integer literals as initializers. + // In a non-ambient declaration, the grammar allows uninitialized members only in a + // ConstantEnumMemberSection, which starts at the beginning of an enum declaration + // or any time an integer literal initializer is encountered. + function parseEnumMember() { + var node = createNodeWithJSDoc(278 /* EnumMember */); + node.name = parsePropertyName(); + node.initializer = allowInAnd(parseInitializer); + return finishNode(node); + } + function parseEnumDeclaration(node) { + node.kind = 243 /* EnumDeclaration */; + parseExpected(84 /* EnumKeyword */); + node.name = parseIdentifier(); + if (parseExpected(18 /* OpenBraceToken */)) { + node.members = parseDelimitedList(6 /* EnumMembers */, parseEnumMember); + parseExpected(19 /* CloseBraceToken */); + } + else { + node.members = createMissingList(); + } + return finishNode(node); + } + function parseModuleBlock() { + var node = createNode(245 /* ModuleBlock */); + if (parseExpected(18 /* OpenBraceToken */)) { + node.statements = parseList(1 /* BlockStatements */, parseStatement); + parseExpected(19 /* CloseBraceToken */); + } + else { + node.statements = createMissingList(); + } + return finishNode(node); + } + function parseModuleOrNamespaceDeclaration(node, flags) { + node.kind = 244 /* ModuleDeclaration */; + // If we are parsing a dotted namespace name, we want to + // propagate the 'Namespace' flag across the names if set. + var namespaceFlag = flags & 16 /* Namespace */; + node.flags |= flags; + node.name = parseIdentifier(); + node.body = parseOptional(24 /* DotToken */) + ? parseModuleOrNamespaceDeclaration(createNode(0 /* Unknown */), 4 /* NestedNamespace */ | namespaceFlag) + : parseModuleBlock(); + return finishNode(node); + } + function parseAmbientExternalModuleDeclaration(node) { + node.kind = 244 /* ModuleDeclaration */; + if (token() === 145 /* GlobalKeyword */) { + // parse 'global' as name of global scope augmentation + node.name = parseIdentifier(); + node.flags |= 512 /* GlobalAugmentation */; + } + else { + node.name = parseLiteralNode(); + node.name.text = internIdentifier(node.name.text); + } + if (token() === 18 /* OpenBraceToken */) { + node.body = parseModuleBlock(); + } + else { + parseSemicolon(); + } + return finishNode(node); + } + function parseModuleDeclaration(node) { + var flags = 0; + if (token() === 145 /* GlobalKeyword */) { + // global augmentation + return parseAmbientExternalModuleDeclaration(node); + } + else if (parseOptional(131 /* NamespaceKeyword */)) { + flags |= 16 /* Namespace */; + } + else { + parseExpected(130 /* ModuleKeyword */); + if (token() === 10 /* StringLiteral */) { + return parseAmbientExternalModuleDeclaration(node); + } + } + return parseModuleOrNamespaceDeclaration(node, flags); + } + function isExternalModuleReference() { + return token() === 134 /* RequireKeyword */ && + lookAhead(nextTokenIsOpenParen); + } + function nextTokenIsOpenParen() { + return nextToken() === 20 /* OpenParenToken */; + } + function nextTokenIsSlash() { + return nextToken() === 42 /* SlashToken */; + } + function parseNamespaceExportDeclaration(node) { + node.kind = 247 /* NamespaceExportDeclaration */; + parseExpected(119 /* AsKeyword */); + parseExpected(131 /* NamespaceKeyword */); + node.name = parseIdentifier(); + parseSemicolon(); + return finishNode(node); + } + function parseImportDeclarationOrImportEqualsDeclaration(node) { + parseExpected(92 /* ImportKeyword */); + var afterImportPos = scanner.getStartPos(); + var identifier; + if (isIdentifier()) { + identifier = parseIdentifier(); + if (token() !== 27 /* CommaToken */ && token() !== 144 /* FromKeyword */) { + return parseImportEqualsDeclaration(node, identifier); + } + } + // Import statement + node.kind = 249 /* ImportDeclaration */; + // ImportDeclaration: + // import ImportClause from ModuleSpecifier ; + // import ModuleSpecifier; + if (identifier || // import id + token() === 40 /* AsteriskToken */ || // import * + token() === 18 /* OpenBraceToken */) { // import { + node.importClause = parseImportClause(identifier, afterImportPos); + parseExpected(144 /* FromKeyword */); + } + node.moduleSpecifier = parseModuleSpecifier(); + parseSemicolon(); + return finishNode(node); + } + function parseImportEqualsDeclaration(node, identifier) { + node.kind = 248 /* ImportEqualsDeclaration */; + node.name = identifier; + parseExpected(59 /* EqualsToken */); + node.moduleReference = parseModuleReference(); + parseSemicolon(); + return finishNode(node); + } + function parseImportClause(identifier, fullStart) { + // ImportClause: + // ImportedDefaultBinding + // NameSpaceImport + // NamedImports + // ImportedDefaultBinding, NameSpaceImport + // ImportedDefaultBinding, NamedImports + var importClause = createNode(250 /* ImportClause */, fullStart); + if (identifier) { + // ImportedDefaultBinding: + // ImportedBinding + importClause.name = identifier; + } + // If there was no default import or if there is comma token after default import + // parse namespace or named imports + if (!importClause.name || + parseOptional(27 /* CommaToken */)) { + importClause.namedBindings = token() === 40 /* AsteriskToken */ ? parseNamespaceImport() : parseNamedImportsOrExports(252 /* NamedImports */); + } + return finishNode(importClause); + } + function parseModuleReference() { + return isExternalModuleReference() + ? parseExternalModuleReference() + : parseEntityName(/*allowReservedWords*/ false); + } + function parseExternalModuleReference() { + var node = createNode(259 /* ExternalModuleReference */); + parseExpected(134 /* RequireKeyword */); + parseExpected(20 /* OpenParenToken */); + node.expression = parseModuleSpecifier(); + parseExpected(21 /* CloseParenToken */); + return finishNode(node); + } + function parseModuleSpecifier() { + if (token() === 10 /* StringLiteral */) { + var result = parseLiteralNode(); + result.text = internIdentifier(result.text); + return result; + } + else { + // We allow arbitrary expressions here, even though the grammar only allows string + // literals. We check to ensure that it is only a string literal later in the grammar + // check pass. + return parseExpression(); + } + } + function parseNamespaceImport() { + // NameSpaceImport: + // * as ImportedBinding + var namespaceImport = createNode(251 /* NamespaceImport */); + parseExpected(40 /* AsteriskToken */); + parseExpected(119 /* AsKeyword */); + namespaceImport.name = parseIdentifier(); + return finishNode(namespaceImport); + } + function parseNamedImportsOrExports(kind) { + var node = createNode(kind); + // NamedImports: + // { } + // { ImportsList } + // { ImportsList, } + // ImportsList: + // ImportSpecifier + // ImportsList, ImportSpecifier + node.elements = parseBracketedList(23 /* ImportOrExportSpecifiers */, kind === 252 /* NamedImports */ ? parseImportSpecifier : parseExportSpecifier, 18 /* OpenBraceToken */, 19 /* CloseBraceToken */); + return finishNode(node); + } + function parseExportSpecifier() { + return parseImportOrExportSpecifier(257 /* ExportSpecifier */); + } + function parseImportSpecifier() { + return parseImportOrExportSpecifier(253 /* ImportSpecifier */); + } + function parseImportOrExportSpecifier(kind) { + var node = createNode(kind); + // ImportSpecifier: + // BindingIdentifier + // IdentifierName as BindingIdentifier + // ExportSpecifier: + // IdentifierName + // IdentifierName as IdentifierName + var checkIdentifierIsKeyword = ts.isKeyword(token()) && !isIdentifier(); + var checkIdentifierStart = scanner.getTokenPos(); + var checkIdentifierEnd = scanner.getTextPos(); + var identifierName = parseIdentifierName(); + if (token() === 119 /* AsKeyword */) { + node.propertyName = identifierName; + parseExpected(119 /* AsKeyword */); + checkIdentifierIsKeyword = ts.isKeyword(token()) && !isIdentifier(); + checkIdentifierStart = scanner.getTokenPos(); + checkIdentifierEnd = scanner.getTextPos(); + node.name = parseIdentifierName(); + } + else { + node.name = identifierName; + } + if (kind === 253 /* ImportSpecifier */ && checkIdentifierIsKeyword) { + parseErrorAt(checkIdentifierStart, checkIdentifierEnd, ts.Diagnostics.Identifier_expected); + } + return finishNode(node); + } + function parseExportDeclaration(node) { + node.kind = 255 /* ExportDeclaration */; + if (parseOptional(40 /* AsteriskToken */)) { + parseExpected(144 /* FromKeyword */); + node.moduleSpecifier = parseModuleSpecifier(); + } + else { + node.exportClause = parseNamedImportsOrExports(256 /* NamedExports */); + // It is not uncommon to accidentally omit the 'from' keyword. Additionally, in editing scenarios, + // the 'from' keyword can be parsed as a named export when the export clause is unterminated (i.e. `export { from "moduleName";`) + // If we don't have a 'from' keyword, see if we have a string literal such that ASI won't take effect. + if (token() === 144 /* FromKeyword */ || (token() === 10 /* StringLiteral */ && !scanner.hasPrecedingLineBreak())) { + parseExpected(144 /* FromKeyword */); + node.moduleSpecifier = parseModuleSpecifier(); + } + } + parseSemicolon(); + return finishNode(node); + } + function parseExportAssignment(node) { + node.kind = 254 /* ExportAssignment */; + if (parseOptional(59 /* EqualsToken */)) { + node.isExportEquals = true; + } + else { + parseExpected(80 /* DefaultKeyword */); + } + node.expression = parseAssignmentExpressionOrHigher(); + parseSemicolon(); + return finishNode(node); + } + function setExternalModuleIndicator(sourceFile) { + // Try to use the first top-level import/export when available, then + // fall back to looking for an 'import.meta' somewhere in the tree if necessary. + sourceFile.externalModuleIndicator = + ts.forEach(sourceFile.statements, isAnExternalModuleIndicatorNode) || + getImportMetaIfNecessary(sourceFile); + } + function isAnExternalModuleIndicatorNode(node) { + return ts.hasModifier(node, 1 /* Export */) + || node.kind === 248 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 259 /* ExternalModuleReference */ + || node.kind === 249 /* ImportDeclaration */ + || node.kind === 254 /* ExportAssignment */ + || node.kind === 255 /* ExportDeclaration */ + ? node + : undefined; + } + function getImportMetaIfNecessary(sourceFile) { + return sourceFile.flags & 1048576 /* PossiblyContainsImportMeta */ ? + walkTreeForExternalModuleIndicators(sourceFile) : + undefined; + } + function walkTreeForExternalModuleIndicators(node) { + return isImportMeta(node) ? node : forEachChild(node, walkTreeForExternalModuleIndicators); + } + function isImportMeta(node) { + return ts.isMetaProperty(node) && node.keywordToken === 92 /* ImportKeyword */ && node.name.escapedText === "meta"; + } + var ParsingContext; + (function (ParsingContext) { + ParsingContext[ParsingContext["SourceElements"] = 0] = "SourceElements"; + ParsingContext[ParsingContext["BlockStatements"] = 1] = "BlockStatements"; + ParsingContext[ParsingContext["SwitchClauses"] = 2] = "SwitchClauses"; + ParsingContext[ParsingContext["SwitchClauseStatements"] = 3] = "SwitchClauseStatements"; + ParsingContext[ParsingContext["TypeMembers"] = 4] = "TypeMembers"; + ParsingContext[ParsingContext["ClassMembers"] = 5] = "ClassMembers"; + ParsingContext[ParsingContext["EnumMembers"] = 6] = "EnumMembers"; + ParsingContext[ParsingContext["HeritageClauseElement"] = 7] = "HeritageClauseElement"; + ParsingContext[ParsingContext["VariableDeclarations"] = 8] = "VariableDeclarations"; + ParsingContext[ParsingContext["ObjectBindingElements"] = 9] = "ObjectBindingElements"; + ParsingContext[ParsingContext["ArrayBindingElements"] = 10] = "ArrayBindingElements"; + ParsingContext[ParsingContext["ArgumentExpressions"] = 11] = "ArgumentExpressions"; + ParsingContext[ParsingContext["ObjectLiteralMembers"] = 12] = "ObjectLiteralMembers"; + ParsingContext[ParsingContext["JsxAttributes"] = 13] = "JsxAttributes"; + ParsingContext[ParsingContext["JsxChildren"] = 14] = "JsxChildren"; + ParsingContext[ParsingContext["ArrayLiteralMembers"] = 15] = "ArrayLiteralMembers"; + ParsingContext[ParsingContext["Parameters"] = 16] = "Parameters"; + ParsingContext[ParsingContext["JSDocParameters"] = 17] = "JSDocParameters"; + ParsingContext[ParsingContext["RestProperties"] = 18] = "RestProperties"; + ParsingContext[ParsingContext["TypeParameters"] = 19] = "TypeParameters"; + ParsingContext[ParsingContext["TypeArguments"] = 20] = "TypeArguments"; + ParsingContext[ParsingContext["TupleElementTypes"] = 21] = "TupleElementTypes"; + ParsingContext[ParsingContext["HeritageClauses"] = 22] = "HeritageClauses"; + ParsingContext[ParsingContext["ImportOrExportSpecifiers"] = 23] = "ImportOrExportSpecifiers"; + ParsingContext[ParsingContext["Count"] = 24] = "Count"; // Number of parsing contexts + })(ParsingContext || (ParsingContext = {})); + var Tristate; + (function (Tristate) { + Tristate[Tristate["False"] = 0] = "False"; + Tristate[Tristate["True"] = 1] = "True"; + Tristate[Tristate["Unknown"] = 2] = "Unknown"; + })(Tristate || (Tristate = {})); + var JSDocParser; + (function (JSDocParser) { + function parseJSDocTypeExpressionForTests(content, start, length) { + initializeState(content, 6 /* Latest */, /*_syntaxCursor:*/ undefined, 1 /* JS */); + sourceFile = createSourceFile("file.js", 6 /* Latest */, 1 /* JS */, /*isDeclarationFile*/ false); + scanner.setText(content, start, length); + currentToken = scanner.scan(); + var jsDocTypeExpression = parseJSDocTypeExpression(); + var diagnostics = parseDiagnostics; + clearState(); + return jsDocTypeExpression ? { jsDocTypeExpression: jsDocTypeExpression, diagnostics: diagnostics } : undefined; + } + JSDocParser.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests; + // Parses out a JSDoc type expression. + function parseJSDocTypeExpression(mayOmitBraces) { + var result = createNode(283 /* JSDocTypeExpression */); + var hasBrace = (mayOmitBraces ? parseOptional : parseExpected)(18 /* OpenBraceToken */); + result.type = doInsideOfContext(2097152 /* JSDoc */, parseJSDocType); + if (!mayOmitBraces || hasBrace) { + parseExpected(19 /* CloseBraceToken */); + } + fixupParentReferences(result); + return finishNode(result); + } + JSDocParser.parseJSDocTypeExpression = parseJSDocTypeExpression; + function parseIsolatedJSDocComment(content, start, length) { + initializeState(content, 6 /* Latest */, /*_syntaxCursor:*/ undefined, 1 /* JS */); + sourceFile = { languageVariant: 0 /* Standard */, text: content }; // tslint:disable-line no-object-literal-type-assertion + var jsDoc = parseJSDocCommentWorker(start, length); + var diagnostics = parseDiagnostics; + clearState(); + return jsDoc ? { jsDoc: jsDoc, diagnostics: diagnostics } : undefined; + } + JSDocParser.parseIsolatedJSDocComment = parseIsolatedJSDocComment; + function parseJSDocComment(parent, start, length) { + var _a; + var saveToken = currentToken; + var saveParseDiagnosticsLength = parseDiagnostics.length; + var saveParseErrorBeforeNextFinishedNode = parseErrorBeforeNextFinishedNode; + var comment = parseJSDocCommentWorker(start, length); + if (comment) { + comment.parent = parent; + } + if (contextFlags & 65536 /* JavaScriptFile */) { + if (!sourceFile.jsDocDiagnostics) { + sourceFile.jsDocDiagnostics = []; + } + (_a = sourceFile.jsDocDiagnostics).push.apply(_a, parseDiagnostics); + } + currentToken = saveToken; + parseDiagnostics.length = saveParseDiagnosticsLength; + parseErrorBeforeNextFinishedNode = saveParseErrorBeforeNextFinishedNode; + return comment; + } + JSDocParser.parseJSDocComment = parseJSDocComment; + var JSDocState; + (function (JSDocState) { + JSDocState[JSDocState["BeginningOfLine"] = 0] = "BeginningOfLine"; + JSDocState[JSDocState["SawAsterisk"] = 1] = "SawAsterisk"; + JSDocState[JSDocState["SavingComments"] = 2] = "SavingComments"; + })(JSDocState || (JSDocState = {})); + var PropertyLikeParse; + (function (PropertyLikeParse) { + PropertyLikeParse[PropertyLikeParse["Property"] = 1] = "Property"; + PropertyLikeParse[PropertyLikeParse["Parameter"] = 2] = "Parameter"; + PropertyLikeParse[PropertyLikeParse["CallbackParameter"] = 4] = "CallbackParameter"; + })(PropertyLikeParse || (PropertyLikeParse = {})); + function parseJSDocCommentWorker(start, length) { + if (start === void 0) { start = 0; } + var content = sourceText; + var end = length === undefined ? content.length : start + length; + length = end - start; + ts.Debug.assert(start >= 0); + ts.Debug.assert(start <= end); + ts.Debug.assert(end <= content.length); + // Check for /** (JSDoc opening part) + if (!isJSDocLikeText(content, start)) { + return undefined; + } + var tags; + var tagsPos; + var tagsEnd; + var comments = []; + // + 3 for leading /**, - 5 in total for /** */ + return scanner.scanRange(start + 3, length - 5, function () { + // Initially we can parse out a tag. We also have seen a starting asterisk. + // This is so that /** * @type */ doesn't parse. + var state = 1 /* SawAsterisk */; + var margin; + // + 4 for leading '/** ' + var indent = start - Math.max(content.lastIndexOf("\n", start), 0) + 4; + function pushComment(text) { + if (!margin) { + margin = indent; + } + comments.push(text); + indent += text.length; + } + nextJSDocToken(); + while (parseOptionalJsdoc(5 /* WhitespaceTrivia */)) + ; + if (parseOptionalJsdoc(4 /* NewLineTrivia */)) { + state = 0 /* BeginningOfLine */; + indent = 0; + } + loop: while (true) { + switch (token()) { + case 58 /* AtToken */: + if (state === 0 /* BeginningOfLine */ || state === 1 /* SawAsterisk */) { + removeTrailingWhitespace(comments); + addTag(parseTag(indent)); + // NOTE: According to usejsdoc.org, a tag goes to end of line, except the last tag. + // Real-world comments may break this rule, so "BeginningOfLine" will not be a real line beginning + // for malformed examples like `/** @param {string} x @returns {number} the length */` + state = 0 /* BeginningOfLine */; + margin = undefined; + indent++; + } + else { + pushComment(scanner.getTokenText()); + } + break; + case 4 /* NewLineTrivia */: + comments.push(scanner.getTokenText()); + state = 0 /* BeginningOfLine */; + indent = 0; + break; + case 40 /* AsteriskToken */: + var asterisk = scanner.getTokenText(); + if (state === 1 /* SawAsterisk */ || state === 2 /* SavingComments */) { + // If we've already seen an asterisk, then we can no longer parse a tag on this line + state = 2 /* SavingComments */; + pushComment(asterisk); + } + else { + // Ignore the first asterisk on a line + state = 1 /* SawAsterisk */; + indent += asterisk.length; + } + break; + case 5 /* WhitespaceTrivia */: + // only collect whitespace if we're already saving comments or have just crossed the comment indent margin + var whitespace = scanner.getTokenText(); + if (state === 2 /* SavingComments */) { + comments.push(whitespace); + } + else if (margin !== undefined && indent + whitespace.length > margin) { + comments.push(whitespace.slice(margin - indent - 1)); + } + indent += whitespace.length; + break; + case 1 /* EndOfFileToken */: + break loop; + default: + // Anything else is doc comment text. We just save it. Because it + // wasn't a tag, we can no longer parse a tag on this line until we hit the next + // line break. + state = 2 /* SavingComments */; + pushComment(scanner.getTokenText()); + break; + } + nextJSDocToken(); + } + removeLeadingNewlines(comments); + removeTrailingWhitespace(comments); + return createJSDocComment(); + }); + function removeLeadingNewlines(comments) { + while (comments.length && (comments[0] === "\n" || comments[0] === "\r")) { + comments.shift(); + } + } + function removeTrailingWhitespace(comments) { + while (comments.length && comments[comments.length - 1].trim() === "") { + comments.pop(); + } + } + function createJSDocComment() { + var result = createNode(291 /* JSDocComment */, start); + result.tags = tags && createNodeArray(tags, tagsPos, tagsEnd); + result.comment = comments.length ? comments.join("") : undefined; + return finishNode(result, end); + } + function isNextNonwhitespaceTokenEndOfFile() { + // We must use infinite lookahead, as there could be any number of newlines :( + while (true) { + nextJSDocToken(); + if (token() === 1 /* EndOfFileToken */) { + return true; + } + if (!(token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */)) { + return false; + } + } + } + function skipWhitespace() { + if (token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) { + if (lookAhead(isNextNonwhitespaceTokenEndOfFile)) { + return; // Don't skip whitespace prior to EoF (or end of comment) - that shouldn't be included in any node's range + } + } + while (token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) { + nextJSDocToken(); + } + } + function skipWhitespaceOrAsterisk() { + if (token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) { + if (lookAhead(isNextNonwhitespaceTokenEndOfFile)) { + return; // Don't skip whitespace prior to EoF (or end of comment) - that shouldn't be included in any node's range + } + } + var precedingLineBreak = scanner.hasPrecedingLineBreak(); + while ((precedingLineBreak && token() === 40 /* AsteriskToken */) || token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) { + if (token() === 4 /* NewLineTrivia */) { + precedingLineBreak = true; + } + else if (token() === 40 /* AsteriskToken */) { + precedingLineBreak = false; + } + nextJSDocToken(); + } + } + function parseTag(indent) { + ts.Debug.assert(token() === 58 /* AtToken */); + var start = scanner.getTokenPos(); + nextJSDocToken(); + var tagName = parseJSDocIdentifierName(/*message*/ undefined); + skipWhitespaceOrAsterisk(); + var tag; + switch (tagName.escapedText) { + case "augments": + case "extends": + tag = parseAugmentsTag(start, tagName); + break; + case "class": + case "constructor": + tag = parseClassTag(start, tagName); + break; + case "this": + tag = parseThisTag(start, tagName); + break; + case "enum": + tag = parseEnumTag(start, tagName); + break; + case "arg": + case "argument": + case "param": + return parseParameterOrPropertyTag(start, tagName, 2 /* Parameter */, indent); + case "return": + case "returns": + tag = parseReturnTag(start, tagName); + break; + case "template": + tag = parseTemplateTag(start, tagName); + break; + case "type": + tag = parseTypeTag(start, tagName); + break; + case "typedef": + tag = parseTypedefTag(start, tagName, indent); + break; + case "callback": + tag = parseCallbackTag(start, tagName, indent); + break; + default: + tag = parseUnknownTag(start, tagName); + break; + } + if (!tag.comment) { + // some tags, like typedef and callback, have already parsed their comments earlier + tag.comment = parseTagComments(indent + tag.end - tag.pos); + } + return tag; + } + function parseTagComments(indent) { + var comments = []; + var state = 0 /* BeginningOfLine */; + var margin; + function pushComment(text) { + if (!margin) { + margin = indent; + } + comments.push(text); + indent += text.length; + } + var tok = token(); + loop: while (true) { + switch (tok) { + case 4 /* NewLineTrivia */: + if (state >= 1 /* SawAsterisk */) { + state = 0 /* BeginningOfLine */; + comments.push(scanner.getTokenText()); + } + indent = 0; + break; + case 58 /* AtToken */: + scanner.setTextPos(scanner.getTextPos() - 1); + // falls through + case 1 /* EndOfFileToken */: + // Done + break loop; + case 5 /* WhitespaceTrivia */: + if (state === 2 /* SavingComments */) { + pushComment(scanner.getTokenText()); + } + else { + var whitespace = scanner.getTokenText(); + // if the whitespace crosses the margin, take only the whitespace that passes the margin + if (margin !== undefined && indent + whitespace.length > margin) { + comments.push(whitespace.slice(margin - indent - 1)); + } + indent += whitespace.length; + } + break; + case 18 /* OpenBraceToken */: + state = 2 /* SavingComments */; + if (lookAhead(function () { return nextJSDocToken() === 58 /* AtToken */ && ts.tokenIsIdentifierOrKeyword(nextJSDocToken()) && scanner.getTokenText() === "link"; })) { + pushComment(scanner.getTokenText()); + nextJSDocToken(); + pushComment(scanner.getTokenText()); + nextJSDocToken(); + } + pushComment(scanner.getTokenText()); + break; + case 40 /* AsteriskToken */: + if (state === 0 /* BeginningOfLine */) { + // leading asterisks start recording on the *next* (non-whitespace) token + state = 1 /* SawAsterisk */; + indent += 1; + break; + } + // record the * as a comment + // falls through + default: + state = 2 /* SavingComments */; // leading identifiers start recording as well + pushComment(scanner.getTokenText()); + break; + } + tok = nextJSDocToken(); + } + removeLeadingNewlines(comments); + removeTrailingWhitespace(comments); + return comments.length === 0 ? undefined : comments.join(""); + } + function parseUnknownTag(start, tagName) { + var result = createNode(294 /* JSDocTag */, start); + result.tagName = tagName; + return finishNode(result); + } + function addTag(tag) { + if (!tag) { + return; + } + if (!tags) { + tags = [tag]; + tagsPos = tag.pos; + } + else { + tags.push(tag); + } + tagsEnd = tag.end; + } + function tryParseTypeExpression() { + skipWhitespaceOrAsterisk(); + return token() === 18 /* OpenBraceToken */ ? parseJSDocTypeExpression() : undefined; + } + function parseBracketNameInPropertyAndParamTag() { + if (token() === 14 /* NoSubstitutionTemplateLiteral */) { + // a markdown-quoted name: `arg` is not legal jsdoc, but occurs in the wild + return { name: createIdentifier(/*isIdentifier*/ true), isBracketed: false }; + } + // Looking for something like '[foo]', 'foo', '[foo.bar]' or 'foo.bar' + var isBracketed = parseOptional(22 /* OpenBracketToken */); + var name = parseJSDocEntityName(); + if (isBracketed) { + skipWhitespace(); + // May have an optional default, e.g. '[foo = 42]' + if (parseOptionalToken(59 /* EqualsToken */)) { + parseExpression(); + } + parseExpected(23 /* CloseBracketToken */); + } + return { name: name, isBracketed: isBracketed }; + } + function isObjectOrObjectArrayTypeReference(node) { + switch (node.kind) { + case 136 /* ObjectKeyword */: + return true; + case 169 /* ArrayType */: + return isObjectOrObjectArrayTypeReference(node.elementType); + default: + return ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) && node.typeName.escapedText === "Object"; + } + } + function parseParameterOrPropertyTag(start, tagName, target, indent) { + var typeExpression = tryParseTypeExpression(); + var isNameFirst = !typeExpression; + skipWhitespaceOrAsterisk(); + var _a = parseBracketNameInPropertyAndParamTag(), name = _a.name, isBracketed = _a.isBracketed; + skipWhitespace(); + if (isNameFirst) { + typeExpression = tryParseTypeExpression(); + } + var result = target === 1 /* Property */ ? + createNode(305 /* JSDocPropertyTag */, start) : + createNode(299 /* JSDocParameterTag */, start); + var comment = parseTagComments(indent + scanner.getStartPos() - start); + var nestedTypeLiteral = target !== 4 /* CallbackParameter */ && parseNestedTypeLiteral(typeExpression, name, target, indent); + if (nestedTypeLiteral) { + typeExpression = nestedTypeLiteral; + isNameFirst = true; + } + result.tagName = tagName; + result.typeExpression = typeExpression; + result.name = name; + result.isNameFirst = isNameFirst; + result.isBracketed = isBracketed; + result.comment = comment; + return finishNode(result); + } + function parseNestedTypeLiteral(typeExpression, name, target, indent) { + if (typeExpression && isObjectOrObjectArrayTypeReference(typeExpression.type)) { + var typeLiteralExpression = createNode(283 /* JSDocTypeExpression */, scanner.getTokenPos()); + var child = void 0; + var jsdocTypeLiteral = void 0; + var start_2 = scanner.getStartPos(); + var children = void 0; + while (child = tryParse(function () { return parseChildParameterOrPropertyTag(target, indent, name); })) { + if (child.kind === 299 /* JSDocParameterTag */ || child.kind === 305 /* JSDocPropertyTag */) { + children = ts.append(children, child); + } + } + if (children) { + jsdocTypeLiteral = createNode(292 /* JSDocTypeLiteral */, start_2); + jsdocTypeLiteral.jsDocPropertyTags = children; + if (typeExpression.type.kind === 169 /* ArrayType */) { + jsdocTypeLiteral.isArrayType = true; + } + typeLiteralExpression.type = finishNode(jsdocTypeLiteral); + return finishNode(typeLiteralExpression); + } + } + } + function parseReturnTag(start, tagName) { + if (ts.forEach(tags, function (t) { return t.kind === 300 /* JSDocReturnTag */; })) { + parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText); + } + var result = createNode(300 /* JSDocReturnTag */, start); + result.tagName = tagName; + result.typeExpression = tryParseTypeExpression(); + return finishNode(result); + } + function parseTypeTag(start, tagName) { + if (ts.forEach(tags, function (t) { return t.kind === 302 /* JSDocTypeTag */; })) { + parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText); + } + var result = createNode(302 /* JSDocTypeTag */, start); + result.tagName = tagName; + result.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true); + return finishNode(result); + } + function parseAugmentsTag(start, tagName) { + var result = createNode(295 /* JSDocAugmentsTag */, start); + result.tagName = tagName; + result.class = parseExpressionWithTypeArgumentsForAugments(); + return finishNode(result); + } + function parseExpressionWithTypeArgumentsForAugments() { + var usedBrace = parseOptional(18 /* OpenBraceToken */); + var node = createNode(211 /* ExpressionWithTypeArguments */); + node.expression = parsePropertyAccessEntityNameExpression(); + node.typeArguments = tryParseTypeArguments(); + var res = finishNode(node); + if (usedBrace) { + parseExpected(19 /* CloseBraceToken */); + } + return res; + } + function parsePropertyAccessEntityNameExpression() { + var node = parseJSDocIdentifierName(); + while (parseOptional(24 /* DotToken */)) { + var prop = createNode(189 /* PropertyAccessExpression */, node.pos); + prop.expression = node; + prop.name = parseJSDocIdentifierName(); + node = finishNode(prop); + } + return node; + } + function parseClassTag(start, tagName) { + var tag = createNode(296 /* JSDocClassTag */, start); + tag.tagName = tagName; + return finishNode(tag); + } + function parseThisTag(start, tagName) { + var tag = createNode(301 /* JSDocThisTag */, start); + tag.tagName = tagName; + tag.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true); + skipWhitespace(); + return finishNode(tag); + } + function parseEnumTag(start, tagName) { + var tag = createNode(298 /* JSDocEnumTag */, start); + tag.tagName = tagName; + tag.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true); + skipWhitespace(); + return finishNode(tag); + } + function parseTypedefTag(start, tagName, indent) { + var typeExpression = tryParseTypeExpression(); + skipWhitespaceOrAsterisk(); + var typedefTag = createNode(304 /* JSDocTypedefTag */, start); + typedefTag.tagName = tagName; + typedefTag.fullName = parseJSDocTypeNameWithNamespace(); + typedefTag.name = getJSDocTypeAliasName(typedefTag.fullName); + skipWhitespace(); + typedefTag.comment = parseTagComments(indent); + typedefTag.typeExpression = typeExpression; + var end; + if (!typeExpression || isObjectOrObjectArrayTypeReference(typeExpression.type)) { + var child = void 0; + var jsdocTypeLiteral = void 0; + var childTypeTag = void 0; + while (child = tryParse(function () { return parseChildPropertyTag(indent); })) { + if (!jsdocTypeLiteral) { + jsdocTypeLiteral = createNode(292 /* JSDocTypeLiteral */, start); + } + if (child.kind === 302 /* JSDocTypeTag */) { + if (childTypeTag) { + break; + } + else { + childTypeTag = child; + } + } + else { + jsdocTypeLiteral.jsDocPropertyTags = ts.append(jsdocTypeLiteral.jsDocPropertyTags, child); + } + } + if (jsdocTypeLiteral) { + if (typeExpression && typeExpression.type.kind === 169 /* ArrayType */) { + jsdocTypeLiteral.isArrayType = true; + } + typedefTag.typeExpression = childTypeTag && childTypeTag.typeExpression && !isObjectOrObjectArrayTypeReference(childTypeTag.typeExpression.type) ? + childTypeTag.typeExpression : + finishNode(jsdocTypeLiteral); + end = typedefTag.typeExpression.end; + } + } + // Only include the characters between the name end and the next token if a comment was actually parsed out - otherwise it's just whitespace + return finishNode(typedefTag, end || typedefTag.comment !== undefined ? scanner.getStartPos() : (typedefTag.fullName || typedefTag.typeExpression || typedefTag.tagName).end); + } + function parseJSDocTypeNameWithNamespace(nested) { + var pos = scanner.getTokenPos(); + if (!ts.tokenIsIdentifierOrKeyword(token())) { + return undefined; + } + var typeNameOrNamespaceName = parseJSDocIdentifierName(); + if (parseOptional(24 /* DotToken */)) { + var jsDocNamespaceNode = createNode(244 /* ModuleDeclaration */, pos); + if (nested) { + jsDocNamespaceNode.flags |= 4 /* NestedNamespace */; + } + jsDocNamespaceNode.name = typeNameOrNamespaceName; + jsDocNamespaceNode.body = parseJSDocTypeNameWithNamespace(/*nested*/ true); + return finishNode(jsDocNamespaceNode); + } + if (nested) { + typeNameOrNamespaceName.isInJSDocNamespace = true; + } + return typeNameOrNamespaceName; + } + function parseCallbackTag(start, tagName, indent) { + var callbackTag = createNode(297 /* JSDocCallbackTag */, start); + callbackTag.tagName = tagName; + callbackTag.fullName = parseJSDocTypeNameWithNamespace(); + callbackTag.name = getJSDocTypeAliasName(callbackTag.fullName); + skipWhitespace(); + callbackTag.comment = parseTagComments(indent); + var child; + var jsdocSignature = createNode(293 /* JSDocSignature */, start); + jsdocSignature.parameters = []; + while (child = tryParse(function () { return parseChildParameterOrPropertyTag(4 /* CallbackParameter */, indent); })) { + jsdocSignature.parameters = ts.append(jsdocSignature.parameters, child); + } + var returnTag = tryParse(function () { + if (parseOptionalJsdoc(58 /* AtToken */)) { + var tag = parseTag(indent); + if (tag && tag.kind === 300 /* JSDocReturnTag */) { + return tag; + } + } + }); + if (returnTag) { + jsdocSignature.type = returnTag; + } + callbackTag.typeExpression = finishNode(jsdocSignature); + return finishNode(callbackTag); + } + function getJSDocTypeAliasName(fullName) { + if (fullName) { + var rightNode = fullName; + while (true) { + if (ts.isIdentifier(rightNode) || !rightNode.body) { + return ts.isIdentifier(rightNode) ? rightNode : rightNode.name; + } + rightNode = rightNode.body; + } + } + } + function escapedTextsEqual(a, b) { + while (!ts.isIdentifier(a) || !ts.isIdentifier(b)) { + if (!ts.isIdentifier(a) && !ts.isIdentifier(b) && a.right.escapedText === b.right.escapedText) { + a = a.left; + b = b.left; + } + else { + return false; + } + } + return a.escapedText === b.escapedText; + } + function parseChildPropertyTag(indent) { + return parseChildParameterOrPropertyTag(1 /* Property */, indent); + } + function parseChildParameterOrPropertyTag(target, indent, name) { + var canParseTag = true; + var seenAsterisk = false; + while (true) { + switch (nextJSDocToken()) { + case 58 /* AtToken */: + if (canParseTag) { + var child = tryParseChildTag(target, indent); + if (child && (child.kind === 299 /* JSDocParameterTag */ || child.kind === 305 /* JSDocPropertyTag */) && + target !== 4 /* CallbackParameter */ && + name && (ts.isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) { + return false; + } + return child; + } + seenAsterisk = false; + break; + case 4 /* NewLineTrivia */: + canParseTag = true; + seenAsterisk = false; + break; + case 40 /* AsteriskToken */: + if (seenAsterisk) { + canParseTag = false; + } + seenAsterisk = true; + break; + case 72 /* Identifier */: + canParseTag = false; + break; + case 1 /* EndOfFileToken */: + return false; + } + } + } + function tryParseChildTag(target, indent) { + ts.Debug.assert(token() === 58 /* AtToken */); + var start = scanner.getStartPos(); + nextJSDocToken(); + var tagName = parseJSDocIdentifierName(); + skipWhitespace(); + var t; + switch (tagName.escapedText) { + case "type": + return target === 1 /* Property */ && parseTypeTag(start, tagName); + case "prop": + case "property": + t = 1 /* Property */; + break; + case "arg": + case "argument": + case "param": + t = 2 /* Parameter */ | 4 /* CallbackParameter */; + break; + default: + return false; + } + if (!(target & t)) { + return false; + } + return parseParameterOrPropertyTag(start, tagName, target, indent); + } + function parseTemplateTag(start, tagName) { + // the template tag looks like '@template {Constraint} T,U,V' + var constraint; + if (token() === 18 /* OpenBraceToken */) { + constraint = parseJSDocTypeExpression(); + } + var typeParameters = []; + var typeParametersPos = getNodePos(); + do { + skipWhitespace(); + var typeParameter = createNode(150 /* TypeParameter */); + typeParameter.name = parseJSDocIdentifierName(ts.Diagnostics.Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces); + finishNode(typeParameter); + skipWhitespace(); + typeParameters.push(typeParameter); + } while (parseOptionalJsdoc(27 /* CommaToken */)); + var result = createNode(303 /* JSDocTemplateTag */, start); + result.tagName = tagName; + result.constraint = constraint; + result.typeParameters = createNodeArray(typeParameters, typeParametersPos); + finishNode(result); + return result; + } + function nextJSDocToken() { + return currentToken = scanner.scanJSDocToken(); + } + function parseOptionalJsdoc(t) { + if (token() === t) { + nextJSDocToken(); + return true; + } + return false; + } + function parseJSDocEntityName() { + var entity = parseJSDocIdentifierName(); + if (parseOptional(22 /* OpenBracketToken */)) { + parseExpected(23 /* CloseBracketToken */); + // Note that y[] is accepted as an entity name, but the postfix brackets are not saved for checking. + // Technically usejsdoc.org requires them for specifying a property of a type equivalent to Array<{ x: ...}> + // but it's not worth it to enforce that restriction. + } + while (parseOptional(24 /* DotToken */)) { + var name = parseJSDocIdentifierName(); + if (parseOptional(22 /* OpenBracketToken */)) { + parseExpected(23 /* CloseBracketToken */); + } + entity = createQualifiedName(entity, name); + } + return entity; + } + function parseJSDocIdentifierName(message) { + if (!ts.tokenIsIdentifierOrKeyword(token())) { + return createMissingNode(72 /* Identifier */, /*reportAtCurrentPosition*/ !message, message || ts.Diagnostics.Identifier_expected); + } + var pos = scanner.getTokenPos(); + var end = scanner.getTextPos(); + var result = createNode(72 /* Identifier */, pos); + result.escapedText = ts.escapeLeadingUnderscores(scanner.getTokenText()); + finishNode(result, end); + nextJSDocToken(); + return result; + } + } + JSDocParser.parseJSDocCommentWorker = parseJSDocCommentWorker; + })(JSDocParser = Parser.JSDocParser || (Parser.JSDocParser = {})); + })(Parser || (Parser = {})); + var IncrementalParser; + (function (IncrementalParser) { + function updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks) { + aggressiveChecks = aggressiveChecks || ts.Debug.shouldAssert(2 /* Aggressive */); + checkChangeRange(sourceFile, newText, textChangeRange, aggressiveChecks); + if (ts.textChangeRangeIsUnchanged(textChangeRange)) { + // if the text didn't change, then we can just return our current source file as-is. + return sourceFile; + } + if (sourceFile.statements.length === 0) { + // If we don't have any statements in the current source file, then there's no real + // way to incrementally parse. So just do a full parse instead. + return Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, /*syntaxCursor*/ undefined, /*setParentNodes*/ true, sourceFile.scriptKind); + } + // Make sure we're not trying to incrementally update a source file more than once. Once + // we do an update the original source file is considered unusable from that point onwards. + // + // This is because we do incremental parsing in-place. i.e. we take nodes from the old + // tree and give them new positions and parents. From that point on, trusting the old + // tree at all is not possible as far too much of it may violate invariants. + var incrementalSourceFile = sourceFile; + ts.Debug.assert(!incrementalSourceFile.hasBeenIncrementallyParsed); + incrementalSourceFile.hasBeenIncrementallyParsed = true; + var oldText = sourceFile.text; + var syntaxCursor = createSyntaxCursor(sourceFile); + // Make the actual change larger so that we know to reparse anything whose lookahead + // might have intersected the change. + var changeRange = extendToAffectedRange(sourceFile, textChangeRange); + checkChangeRange(sourceFile, newText, changeRange, aggressiveChecks); + // Ensure that extending the affected range only moved the start of the change range + // earlier in the file. + ts.Debug.assert(changeRange.span.start <= textChangeRange.span.start); + ts.Debug.assert(ts.textSpanEnd(changeRange.span) === ts.textSpanEnd(textChangeRange.span)); + ts.Debug.assert(ts.textSpanEnd(ts.textChangeRangeNewSpan(changeRange)) === ts.textSpanEnd(ts.textChangeRangeNewSpan(textChangeRange))); + // The is the amount the nodes after the edit range need to be adjusted. It can be + // positive (if the edit added characters), negative (if the edit deleted characters) + // or zero (if this was a pure overwrite with nothing added/removed). + var delta = ts.textChangeRangeNewSpan(changeRange).length - changeRange.span.length; + // If we added or removed characters during the edit, then we need to go and adjust all + // the nodes after the edit. Those nodes may move forward (if we inserted chars) or they + // may move backward (if we deleted chars). + // + // Doing this helps us out in two ways. First, it means that any nodes/tokens we want + // to reuse are already at the appropriate position in the new text. That way when we + // reuse them, we don't have to figure out if they need to be adjusted. Second, it makes + // it very easy to determine if we can reuse a node. If the node's position is at where + // we are in the text, then we can reuse it. Otherwise we can't. If the node's position + // is ahead of us, then we'll need to rescan tokens. If the node's position is behind + // us, then we'll need to skip it or crumble it as appropriate + // + // We will also adjust the positions of nodes that intersect the change range as well. + // By doing this, we ensure that all the positions in the old tree are consistent, not + // just the positions of nodes entirely before/after the change range. By being + // consistent, we can then easily map from positions to nodes in the old tree easily. + // + // Also, mark any syntax elements that intersect the changed span. We know, up front, + // that we cannot reuse these elements. + updateTokenPositionsAndMarkElements(incrementalSourceFile, changeRange.span.start, ts.textSpanEnd(changeRange.span), ts.textSpanEnd(ts.textChangeRangeNewSpan(changeRange)), delta, oldText, newText, aggressiveChecks); + // Now that we've set up our internal incremental state just proceed and parse the + // source file in the normal fashion. When possible the parser will retrieve and + // reuse nodes from the old tree. + // + // Note: passing in 'true' for setNodeParents is very important. When incrementally + // parsing, we will be reusing nodes from the old tree, and placing it into new + // parents. If we don't set the parents now, we'll end up with an observably + // inconsistent tree. Setting the parents on the new tree should be very fast. We + // will immediately bail out of walking any subtrees when we can see that their parents + // are already correct. + var result = Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, syntaxCursor, /*setParentNodes*/ true, sourceFile.scriptKind); + return result; + } + IncrementalParser.updateSourceFile = updateSourceFile; + function moveElementEntirelyPastChangeRange(element, isArray, delta, oldText, newText, aggressiveChecks) { + if (isArray) { + visitArray(element); + } + else { + visitNode(element); + } + return; + function visitNode(node) { + var text = ""; + if (aggressiveChecks && shouldCheckNode(node)) { + text = oldText.substring(node.pos, node.end); + } + // Ditch any existing LS children we may have created. This way we can avoid + // moving them forward. + if (node._children) { + node._children = undefined; + } + node.pos += delta; + node.end += delta; + if (aggressiveChecks && shouldCheckNode(node)) { + ts.Debug.assert(text === newText.substring(node.pos, node.end)); + } + forEachChild(node, visitNode, visitArray); + if (ts.hasJSDocNodes(node)) { + for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { + var jsDocComment = _a[_i]; + visitNode(jsDocComment); + } + } + checkNodePositions(node, aggressiveChecks); + } + function visitArray(array) { + array._children = undefined; + array.pos += delta; + array.end += delta; + for (var _i = 0, array_8 = array; _i < array_8.length; _i++) { + var node = array_8[_i]; + visitNode(node); + } + } + } + function shouldCheckNode(node) { + switch (node.kind) { + case 10 /* StringLiteral */: + case 8 /* NumericLiteral */: + case 72 /* Identifier */: + return true; + } + return false; + } + function adjustIntersectingElement(element, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta) { + ts.Debug.assert(element.end >= changeStart, "Adjusting an element that was entirely before the change range"); + ts.Debug.assert(element.pos <= changeRangeOldEnd, "Adjusting an element that was entirely after the change range"); + ts.Debug.assert(element.pos <= element.end); + // We have an element that intersects the change range in some way. It may have its + // start, or its end (or both) in the changed range. We want to adjust any part + // that intersects such that the final tree is in a consistent state. i.e. all + // children have spans within the span of their parent, and all siblings are ordered + // properly. + // We may need to update both the 'pos' and the 'end' of the element. + // If the 'pos' is before the start of the change, then we don't need to touch it. + // If it isn't, then the 'pos' must be inside the change. How we update it will + // depend if delta is positive or negative. If delta is positive then we have + // something like: + // + // -------------------AAA----------------- + // -------------------BBBCCCCCCC----------------- + // + // In this case, we consider any node that started in the change range to still be + // starting at the same position. + // + // however, if the delta is negative, then we instead have something like this: + // + // -------------------XXXYYYYYYY----------------- + // -------------------ZZZ----------------- + // + // In this case, any element that started in the 'X' range will keep its position. + // However any element that started after that will have their pos adjusted to be + // at the end of the new range. i.e. any node that started in the 'Y' range will + // be adjusted to have their start at the end of the 'Z' range. + // + // The element will keep its position if possible. Or Move backward to the new-end + // if it's in the 'Y' range. + element.pos = Math.min(element.pos, changeRangeNewEnd); + // If the 'end' is after the change range, then we always adjust it by the delta + // amount. However, if the end is in the change range, then how we adjust it + // will depend on if delta is positive or negative. If delta is positive then we + // have something like: + // + // -------------------AAA----------------- + // -------------------BBBCCCCCCC----------------- + // + // In this case, we consider any node that ended inside the change range to keep its + // end position. + // + // however, if the delta is negative, then we instead have something like this: + // + // -------------------XXXYYYYYYY----------------- + // -------------------ZZZ----------------- + // + // In this case, any element that ended in the 'X' range will keep its position. + // However any element that ended after that will have their pos adjusted to be + // at the end of the new range. i.e. any node that ended in the 'Y' range will + // be adjusted to have their end at the end of the 'Z' range. + if (element.end >= changeRangeOldEnd) { + // Element ends after the change range. Always adjust the end pos. + element.end += delta; + } + else { + // Element ends in the change range. The element will keep its position if + // possible. Or Move backward to the new-end if it's in the 'Y' range. + element.end = Math.min(element.end, changeRangeNewEnd); + } + ts.Debug.assert(element.pos <= element.end); + if (element.parent) { + ts.Debug.assert(element.pos >= element.parent.pos); + ts.Debug.assert(element.end <= element.parent.end); + } + } + function checkNodePositions(node, aggressiveChecks) { + if (aggressiveChecks) { + var pos_2 = node.pos; + var visitNode_1 = function (child) { + ts.Debug.assert(child.pos >= pos_2); + pos_2 = child.end; + }; + if (ts.hasJSDocNodes(node)) { + for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { + var jsDocComment = _a[_i]; + visitNode_1(jsDocComment); + } + } + forEachChild(node, visitNode_1); + ts.Debug.assert(pos_2 <= node.end); + } + } + function updateTokenPositionsAndMarkElements(sourceFile, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta, oldText, newText, aggressiveChecks) { + visitNode(sourceFile); + return; + function visitNode(child) { + ts.Debug.assert(child.pos <= child.end); + if (child.pos > changeRangeOldEnd) { + // Node is entirely past the change range. We need to move both its pos and + // end, forward or backward appropriately. + moveElementEntirelyPastChangeRange(child, /*isArray*/ false, delta, oldText, newText, aggressiveChecks); + return; + } + // Check if the element intersects the change range. If it does, then it is not + // reusable. Also, we'll need to recurse to see what constituent portions we may + // be able to use. + var fullEnd = child.end; + if (fullEnd >= changeStart) { + child.intersectsChange = true; + child._children = undefined; + // Adjust the pos or end (or both) of the intersecting element accordingly. + adjustIntersectingElement(child, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta); + forEachChild(child, visitNode, visitArray); + if (ts.hasJSDocNodes(child)) { + for (var _i = 0, _a = child.jsDoc; _i < _a.length; _i++) { + var jsDocComment = _a[_i]; + visitNode(jsDocComment); + } + } + checkNodePositions(child, aggressiveChecks); + return; + } + // Otherwise, the node is entirely before the change range. No need to do anything with it. + ts.Debug.assert(fullEnd < changeStart); + } + function visitArray(array) { + ts.Debug.assert(array.pos <= array.end); + if (array.pos > changeRangeOldEnd) { + // Array is entirely after the change range. We need to move it, and move any of + // its children. + moveElementEntirelyPastChangeRange(array, /*isArray*/ true, delta, oldText, newText, aggressiveChecks); + return; + } + // Check if the element intersects the change range. If it does, then it is not + // reusable. Also, we'll need to recurse to see what constituent portions we may + // be able to use. + var fullEnd = array.end; + if (fullEnd >= changeStart) { + array.intersectsChange = true; + array._children = undefined; + // Adjust the pos or end (or both) of the intersecting array accordingly. + adjustIntersectingElement(array, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta); + for (var _i = 0, array_9 = array; _i < array_9.length; _i++) { + var node = array_9[_i]; + visitNode(node); + } + return; + } + // Otherwise, the array is entirely before the change range. No need to do anything with it. + ts.Debug.assert(fullEnd < changeStart); + } + } + function extendToAffectedRange(sourceFile, changeRange) { + // Consider the following code: + // void foo() { /; } + // + // If the text changes with an insertion of / just before the semicolon then we end up with: + // void foo() { //; } + // + // If we were to just use the changeRange a is, then we would not rescan the { token + // (as it does not intersect the actual original change range). Because an edit may + // change the token touching it, we actually need to look back *at least* one token so + // that the prior token sees that change. + var maxLookahead = 1; + var start = changeRange.span.start; + // the first iteration aligns us with the change start. subsequent iteration move us to + // the left by maxLookahead tokens. We only need to do this as long as we're not at the + // start of the tree. + for (var i = 0; start > 0 && i <= maxLookahead; i++) { + var nearestNode = findNearestNodeStartingBeforeOrAtPosition(sourceFile, start); + ts.Debug.assert(nearestNode.pos <= start); + var position = nearestNode.pos; + start = Math.max(0, position - 1); + } + var finalSpan = ts.createTextSpanFromBounds(start, ts.textSpanEnd(changeRange.span)); + var finalLength = changeRange.newLength + (changeRange.span.start - start); + return ts.createTextChangeRange(finalSpan, finalLength); + } + function findNearestNodeStartingBeforeOrAtPosition(sourceFile, position) { + var bestResult = sourceFile; + var lastNodeEntirelyBeforePosition; + forEachChild(sourceFile, visit); + if (lastNodeEntirelyBeforePosition) { + var lastChildOfLastEntireNodeBeforePosition = getLastDescendant(lastNodeEntirelyBeforePosition); + if (lastChildOfLastEntireNodeBeforePosition.pos > bestResult.pos) { + bestResult = lastChildOfLastEntireNodeBeforePosition; + } + } + return bestResult; + function getLastDescendant(node) { + while (true) { + var lastChild = ts.getLastChild(node); + if (lastChild) { + node = lastChild; + } + else { + return node; + } + } + } + function visit(child) { + if (ts.nodeIsMissing(child)) { + // Missing nodes are effectively invisible to us. We never even consider them + // When trying to find the nearest node before us. + return; + } + // If the child intersects this position, then this node is currently the nearest + // node that starts before the position. + if (child.pos <= position) { + if (child.pos >= bestResult.pos) { + // This node starts before the position, and is closer to the position than + // the previous best node we found. It is now the new best node. + bestResult = child; + } + // Now, the node may overlap the position, or it may end entirely before the + // position. If it overlaps with the position, then either it, or one of its + // children must be the nearest node before the position. So we can just + // recurse into this child to see if we can find something better. + if (position < child.end) { + // The nearest node is either this child, or one of the children inside + // of it. We've already marked this child as the best so far. Recurse + // in case one of the children is better. + forEachChild(child, visit); + // Once we look at the children of this node, then there's no need to + // continue any further. + return true; + } + else { + ts.Debug.assert(child.end <= position); + // The child ends entirely before this position. Say you have the following + // (where $ is the position) + // + // ? $ : <...> <...> + // + // We would want to find the nearest preceding node in "complex expr 2". + // To support that, we keep track of this node, and once we're done searching + // for a best node, we recurse down this node to see if we can find a good + // result in it. + // + // This approach allows us to quickly skip over nodes that are entirely + // before the position, while still allowing us to find any nodes in the + // last one that might be what we want. + lastNodeEntirelyBeforePosition = child; + } + } + else { + ts.Debug.assert(child.pos > position); + // We're now at a node that is entirely past the position we're searching for. + // This node (and all following nodes) could never contribute to the result, + // so just skip them by returning 'true' here. + return true; + } + } + } + function checkChangeRange(sourceFile, newText, textChangeRange, aggressiveChecks) { + var oldText = sourceFile.text; + if (textChangeRange) { + ts.Debug.assert((oldText.length - textChangeRange.span.length + textChangeRange.newLength) === newText.length); + if (aggressiveChecks || ts.Debug.shouldAssert(3 /* VeryAggressive */)) { + var oldTextPrefix = oldText.substr(0, textChangeRange.span.start); + var newTextPrefix = newText.substr(0, textChangeRange.span.start); + ts.Debug.assert(oldTextPrefix === newTextPrefix); + var oldTextSuffix = oldText.substring(ts.textSpanEnd(textChangeRange.span), oldText.length); + var newTextSuffix = newText.substring(ts.textSpanEnd(ts.textChangeRangeNewSpan(textChangeRange)), newText.length); + ts.Debug.assert(oldTextSuffix === newTextSuffix); + } + } + } + function createSyntaxCursor(sourceFile) { + var currentArray = sourceFile.statements; + var currentArrayIndex = 0; + ts.Debug.assert(currentArrayIndex < currentArray.length); + var current = currentArray[currentArrayIndex]; + var lastQueriedPosition = -1 /* Value */; + return { + currentNode: function (position) { + // Only compute the current node if the position is different than the last time + // we were asked. The parser commonly asks for the node at the same position + // twice. Once to know if can read an appropriate list element at a certain point, + // and then to actually read and consume the node. + if (position !== lastQueriedPosition) { + // Much of the time the parser will need the very next node in the array that + // we just returned a node from.So just simply check for that case and move + // forward in the array instead of searching for the node again. + if (current && current.end === position && currentArrayIndex < (currentArray.length - 1)) { + currentArrayIndex++; + current = currentArray[currentArrayIndex]; + } + // If we don't have a node, or the node we have isn't in the right position, + // then try to find a viable node at the position requested. + if (!current || current.pos !== position) { + findHighestListElementThatStartsAtPosition(position); + } + } + // Cache this query so that we don't do any extra work if the parser calls back + // into us. Note: this is very common as the parser will make pairs of calls like + // 'isListElement -> parseListElement'. If we were unable to find a node when + // called with 'isListElement', we don't want to redo the work when parseListElement + // is called immediately after. + lastQueriedPosition = position; + // Either we don'd have a node, or we have a node at the position being asked for. + ts.Debug.assert(!current || current.pos === position); + return current; + } + }; + // Finds the highest element in the tree we can find that starts at the provided position. + // The element must be a direct child of some node list in the tree. This way after we + // return it, we can easily return its next sibling in the list. + function findHighestListElementThatStartsAtPosition(position) { + // Clear out any cached state about the last node we found. + currentArray = undefined; + currentArrayIndex = -1 /* Value */; + current = undefined; + // Recurse into the source file to find the highest node at this position. + forEachChild(sourceFile, visitNode, visitArray); + return; + function visitNode(node) { + if (position >= node.pos && position < node.end) { + // Position was within this node. Keep searching deeper to find the node. + forEachChild(node, visitNode, visitArray); + // don't proceed any further in the search. + return true; + } + // position wasn't in this node, have to keep searching. + return false; + } + function visitArray(array) { + if (position >= array.pos && position < array.end) { + // position was in this array. Search through this array to see if we find a + // viable element. + for (var i = 0; i < array.length; i++) { + var child = array[i]; + if (child) { + if (child.pos === position) { + // Found the right node. We're done. + currentArray = array; + currentArrayIndex = i; + current = child; + return true; + } + else { + if (child.pos < position && position < child.end) { + // Position in somewhere within this child. Search in it and + // stop searching in this array. + forEachChild(child, visitNode, visitArray); + return true; + } + } + } + } + } + // position wasn't in this array, have to keep searching. + return false; + } + } + } + var InvalidPosition; + (function (InvalidPosition) { + InvalidPosition[InvalidPosition["Value"] = -1] = "Value"; + })(InvalidPosition || (InvalidPosition = {})); + })(IncrementalParser || (IncrementalParser = {})); + /** @internal */ + function isDeclarationFileName(fileName) { + return ts.fileExtensionIs(fileName, ".d.ts" /* Dts */); + } + ts.isDeclarationFileName = isDeclarationFileName; + /*@internal*/ + function processCommentPragmas(context, sourceText) { + var triviaScanner = ts.createScanner(context.languageVersion, /*skipTrivia*/ false, 0 /* Standard */, sourceText); + var pragmas = []; + // Keep scanning all the leading trivia in the file until we get to something that + // isn't trivia. Any single line comment will be analyzed to see if it is a + // reference comment. + while (true) { + var kind = triviaScanner.scan(); + if (!ts.isTrivia(kind)) { + break; + } + var range = { + kind: triviaScanner.getToken(), + pos: triviaScanner.getTokenPos(), + end: triviaScanner.getTextPos(), + }; + var comment = sourceText.substring(range.pos, range.end); + extractPragmas(pragmas, range, comment); + } + context.pragmas = ts.createMap(); + for (var _i = 0, pragmas_1 = pragmas; _i < pragmas_1.length; _i++) { + var pragma = pragmas_1[_i]; + if (context.pragmas.has(pragma.name)) { // TODO: GH#18217 + var currentValue = context.pragmas.get(pragma.name); + if (currentValue instanceof Array) { + currentValue.push(pragma.args); + } + else { + context.pragmas.set(pragma.name, [currentValue, pragma.args]); + } + continue; + } + context.pragmas.set(pragma.name, pragma.args); + } + } + ts.processCommentPragmas = processCommentPragmas; + /*@internal*/ + function processPragmasIntoFields(context, reportDiagnostic) { + context.checkJsDirective = undefined; + context.referencedFiles = []; + context.typeReferenceDirectives = []; + context.libReferenceDirectives = []; + context.amdDependencies = []; + context.hasNoDefaultLib = false; + context.pragmas.forEach(function (entryOrList, key) { + // TODO: The below should be strongly type-guarded and not need casts/explicit annotations, since entryOrList is related to + // key and key is constrained to a union; but it's not (see GH#21483 for at least partial fix) :( + switch (key) { + case "reference": { + var referencedFiles_1 = context.referencedFiles; + var typeReferenceDirectives_1 = context.typeReferenceDirectives; + var libReferenceDirectives_1 = context.libReferenceDirectives; + ts.forEach(ts.toArray(entryOrList), function (arg) { + // TODO: GH#18217 + if (arg.arguments["no-default-lib"]) { + context.hasNoDefaultLib = true; + } + else if (arg.arguments.types) { + typeReferenceDirectives_1.push({ pos: arg.arguments.types.pos, end: arg.arguments.types.end, fileName: arg.arguments.types.value }); + } + else if (arg.arguments.lib) { + libReferenceDirectives_1.push({ pos: arg.arguments.lib.pos, end: arg.arguments.lib.end, fileName: arg.arguments.lib.value }); + } + else if (arg.arguments.path) { + referencedFiles_1.push({ pos: arg.arguments.path.pos, end: arg.arguments.path.end, fileName: arg.arguments.path.value }); + } + else { + reportDiagnostic(arg.range.pos, arg.range.end - arg.range.pos, ts.Diagnostics.Invalid_reference_directive_syntax); + } + }); + break; + } + case "amd-dependency": { + context.amdDependencies = ts.map(ts.toArray(entryOrList), function (x) { return ({ name: x.arguments.name, path: x.arguments.path }); }); // TODO: GH#18217 + break; + } + case "amd-module": { + if (entryOrList instanceof Array) { + for (var _i = 0, entryOrList_1 = entryOrList; _i < entryOrList_1.length; _i++) { + var entry = entryOrList_1[_i]; + if (context.moduleName) { + // TODO: It's probably fine to issue this diagnostic on all instances of the pragma + reportDiagnostic(entry.range.pos, entry.range.end - entry.range.pos, ts.Diagnostics.An_AMD_module_cannot_have_multiple_name_assignments); + } + context.moduleName = entry.arguments.name; + } + } + else { + context.moduleName = entryOrList.arguments.name; + } + break; + } + case "ts-nocheck": + case "ts-check": { + // _last_ of either nocheck or check in a file is the "winner" + ts.forEach(ts.toArray(entryOrList), function (entry) { + if (!context.checkJsDirective || entry.range.pos > context.checkJsDirective.pos) { // TODO: GH#18217 + context.checkJsDirective = { + enabled: key === "ts-check", + end: entry.range.end, + pos: entry.range.pos + }; + } + }); + break; + } + case "jsx": return; // Accessed directly + default: ts.Debug.fail("Unhandled pragma kind"); // Can this be made into an assertNever in the future? + } + }); + } + ts.processPragmasIntoFields = processPragmasIntoFields; + var namedArgRegExCache = ts.createMap(); + function getNamedArgRegEx(name) { + if (namedArgRegExCache.has(name)) { + return namedArgRegExCache.get(name); + } + var result = new RegExp("(\\s" + name + "\\s*=\\s*)('|\")(.+?)\\2", "im"); + namedArgRegExCache.set(name, result); + return result; + } + var tripleSlashXMLCommentStartRegEx = /^\/\/\/\s*<(\S+)\s.*?\/>/im; + var singleLinePragmaRegEx = /^\/\/\/?\s*@(\S+)\s*(.*)\s*$/im; + function extractPragmas(pragmas, range, text) { + var tripleSlash = range.kind === 2 /* SingleLineCommentTrivia */ && tripleSlashXMLCommentStartRegEx.exec(text); + if (tripleSlash) { + var name = tripleSlash[1].toLowerCase(); // Technically unsafe cast, but we do it so the below check to make it safe typechecks + var pragma = ts.commentPragmas[name]; + if (!pragma || !(pragma.kind & 1 /* TripleSlashXML */)) { + return; + } + if (pragma.args) { + var argument = {}; + for (var _i = 0, _a = pragma.args; _i < _a.length; _i++) { + var arg = _a[_i]; + var matcher = getNamedArgRegEx(arg.name); + var matchResult = matcher.exec(text); + if (!matchResult && !arg.optional) { + return; // Missing required argument, don't parse + } + else if (matchResult) { + if (arg.captureSpan) { + var startPos = range.pos + matchResult.index + matchResult[1].length + matchResult[2].length; + argument[arg.name] = { + value: matchResult[3], + pos: startPos, + end: startPos + matchResult[3].length + }; + } + else { + argument[arg.name] = matchResult[3]; + } + } + } + pragmas.push({ name: name, args: { arguments: argument, range: range } }); + } + else { + pragmas.push({ name: name, args: { arguments: {}, range: range } }); + } + return; + } + var singleLine = range.kind === 2 /* SingleLineCommentTrivia */ && singleLinePragmaRegEx.exec(text); + if (singleLine) { + return addPragmaForMatch(pragmas, range, 2 /* SingleLine */, singleLine); + } + if (range.kind === 3 /* MultiLineCommentTrivia */) { + var multiLinePragmaRegEx = /\s*@(\S+)\s*(.*)\s*$/gim; // Defined inline since it uses the "g" flag, which keeps a persistent index (for iterating) + var multiLineMatch = void 0; + while (multiLineMatch = multiLinePragmaRegEx.exec(text)) { + addPragmaForMatch(pragmas, range, 4 /* MultiLine */, multiLineMatch); + } + } + } + function addPragmaForMatch(pragmas, range, kind, match) { + if (!match) + return; + var name = match[1].toLowerCase(); // Technically unsafe cast, but we do it so they below check to make it safe typechecks + var pragma = ts.commentPragmas[name]; + if (!pragma || !(pragma.kind & kind)) { + return; + } + var args = match[2]; // Split on spaces and match up positionally with definition + var argument = getNamedPragmaArguments(pragma, args); + if (argument === "fail") + return; // Missing required argument, fail to parse it + pragmas.push({ name: name, args: { arguments: argument, range: range } }); + return; + } + function getNamedPragmaArguments(pragma, text) { + if (!text) + return {}; + if (!pragma.args) + return {}; + var args = text.split(/\s+/); + var argMap = {}; + for (var i = 0; i < pragma.args.length; i++) { + var argument = pragma.args[i]; + if (!args[i] && !argument.optional) { + return "fail"; + } + if (argument.captureSpan) { + return ts.Debug.fail("Capture spans not yet implemented for non-xml pragmas"); + } + argMap[argument.name] = args[i]; + } + return argMap; + } + /** @internal */ + function tagNamesAreEquivalent(lhs, rhs) { + if (lhs.kind !== rhs.kind) { + return false; + } + if (lhs.kind === 72 /* Identifier */) { + return lhs.escapedText === rhs.escapedText; + } + if (lhs.kind === 100 /* ThisKeyword */) { + return true; + } + // If we are at this statement then we must have PropertyAccessExpression and because tag name in Jsx element can only + // take forms of JsxTagNameExpression which includes an identifier, "this" expression, or another propertyAccessExpression + // it is safe to case the expression property as such. See parseJsxElementName for how we parse tag name in Jsx element + return lhs.name.escapedText === rhs.name.escapedText && + tagNamesAreEquivalent(lhs.expression, rhs.expression); + } + ts.tagNamesAreEquivalent = tagNamesAreEquivalent; +})(ts || (ts = {})); +var ts; +(function (ts) { + /* @internal */ + ts.compileOnSaveCommandLineOption = { name: "compileOnSave", type: "boolean" }; + // NOTE: The order here is important to default lib ordering as entries will have the same + // order in the generated program (see `getDefaultLibPriority` in program.ts). This + // order also affects overload resolution when a type declared in one lib is + // augmented in another lib. + var libEntries = [ + // JavaScript only + ["es5", "lib.es5.d.ts"], + ["es6", "lib.es2015.d.ts"], + ["es2015", "lib.es2015.d.ts"], + ["es7", "lib.es2016.d.ts"], + ["es2016", "lib.es2016.d.ts"], + ["es2017", "lib.es2017.d.ts"], + ["es2018", "lib.es2018.d.ts"], + ["esnext", "lib.esnext.d.ts"], + // Host only + ["dom", "lib.dom.d.ts"], + ["dom.iterable", "lib.dom.iterable.d.ts"], + ["webworker", "lib.webworker.d.ts"], + ["webworker.importscripts", "lib.webworker.importscripts.d.ts"], + ["scripthost", "lib.scripthost.d.ts"], + // ES2015 Or ESNext By-feature options + ["es2015.core", "lib.es2015.core.d.ts"], + ["es2015.collection", "lib.es2015.collection.d.ts"], + ["es2015.generator", "lib.es2015.generator.d.ts"], + ["es2015.iterable", "lib.es2015.iterable.d.ts"], + ["es2015.promise", "lib.es2015.promise.d.ts"], + ["es2015.proxy", "lib.es2015.proxy.d.ts"], + ["es2015.reflect", "lib.es2015.reflect.d.ts"], + ["es2015.symbol", "lib.es2015.symbol.d.ts"], + ["es2015.symbol.wellknown", "lib.es2015.symbol.wellknown.d.ts"], + ["es2016.array.include", "lib.es2016.array.include.d.ts"], + ["es2017.object", "lib.es2017.object.d.ts"], + ["es2017.sharedmemory", "lib.es2017.sharedmemory.d.ts"], + ["es2017.string", "lib.es2017.string.d.ts"], + ["es2017.intl", "lib.es2017.intl.d.ts"], + ["es2017.typedarrays", "lib.es2017.typedarrays.d.ts"], + ["es2018.intl", "lib.es2018.intl.d.ts"], + ["es2018.promise", "lib.es2018.promise.d.ts"], + ["es2018.regexp", "lib.es2018.regexp.d.ts"], + ["esnext.array", "lib.esnext.array.d.ts"], + ["esnext.symbol", "lib.esnext.symbol.d.ts"], + ["esnext.asynciterable", "lib.esnext.asynciterable.d.ts"], + ["esnext.intl", "lib.esnext.intl.d.ts"], + ["esnext.bigint", "lib.esnext.bigint.d.ts"] + ]; + /** + * An array of supported "lib" reference file names used to determine the order for inclusion + * when referenced, as well as for spelling suggestions. This ensures the correct ordering for + * overload resolution when a type declared in one lib is extended by another. + */ + /* @internal */ + ts.libs = libEntries.map(function (entry) { return entry[0]; }); + /** + * A map of lib names to lib files. This map is used both for parsing the "lib" command line + * option as well as for resolving lib reference directives. + */ + /* @internal */ + ts.libMap = ts.createMapFromEntries(libEntries); + /* @internal */ + ts.commonOptionsWithBuild = [ + { + name: "help", + shortName: "h", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Print_this_message, + }, + { + name: "help", + shortName: "?", + type: "boolean" + }, + { + name: "watch", + shortName: "w", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Watch_input_files, + }, + { + name: "preserveWatchOutput", + type: "boolean", + showInSimplifiedHelpView: false, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen, + }, + { + name: "listFiles", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Print_names_of_files_part_of_the_compilation + }, + { + name: "listEmittedFiles", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Print_names_of_generated_files_part_of_the_compilation + }, + { + name: "pretty", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Stylize_errors_and_messages_using_color_and_context_experimental + }, + { + name: "traceResolution", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Enable_tracing_of_the_name_resolution_process + }, + { + name: "diagnostics", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Show_diagnostic_information + }, + { + name: "extendedDiagnostics", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Show_verbose_diagnostic_information + }, + ]; + /* @internal */ + ts.optionDeclarations = ts.commonOptionsWithBuild.concat([ + { + name: "all", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Show_all_compiler_options, + }, + { + name: "version", + shortName: "v", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Print_the_compiler_s_version, + }, + { + name: "init", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file, + }, + { + name: "project", + shortName: "p", + type: "string", + isFilePath: true, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Command_line_Options, + paramType: ts.Diagnostics.FILE_OR_DIRECTORY, + description: ts.Diagnostics.Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json, + }, + { + name: "build", + type: "boolean", + shortName: "b", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Build_one_or_more_projects_and_their_dependencies_if_out_of_date + }, + { + name: "showConfig", + type: "boolean", + category: ts.Diagnostics.Command_line_Options, + isCommandLineOnly: true, + description: ts.Diagnostics.Print_the_final_configuration_instead_of_building + }, + // Basic + { + name: "target", + shortName: "t", + type: ts.createMapFromTemplate({ + es3: 0 /* ES3 */, + es5: 1 /* ES5 */, + es6: 2 /* ES2015 */, + es2015: 2 /* ES2015 */, + es2016: 3 /* ES2016 */, + es2017: 4 /* ES2017 */, + es2018: 5 /* ES2018 */, + esnext: 6 /* ESNext */, + }), + affectsSourceFile: true, + affectsModuleResolution: true, + paramType: ts.Diagnostics.VERSION, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_or_ESNEXT, + }, + { + name: "module", + shortName: "m", + type: ts.createMapFromTemplate({ + none: ts.ModuleKind.None, + commonjs: ts.ModuleKind.CommonJS, + amd: ts.ModuleKind.AMD, + system: ts.ModuleKind.System, + umd: ts.ModuleKind.UMD, + es6: ts.ModuleKind.ES2015, + es2015: ts.ModuleKind.ES2015, + esnext: ts.ModuleKind.ESNext + }), + affectsModuleResolution: true, + paramType: ts.Diagnostics.KIND, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext, + }, + { + name: "lib", + type: "list", + element: { + name: "lib", + type: ts.libMap + }, + affectsModuleResolution: true, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Specify_library_files_to_be_included_in_the_compilation + }, + { + name: "allowJs", + type: "boolean", + affectsModuleResolution: true, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Allow_javascript_files_to_be_compiled + }, + { + name: "checkJs", + type: "boolean", + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Report_errors_in_js_files + }, + { + name: "jsx", + type: ts.createMapFromTemplate({ + "preserve": 1 /* Preserve */, + "react-native": 3 /* ReactNative */, + "react": 2 /* React */ + }), + affectsSourceFile: true, + paramType: ts.Diagnostics.KIND, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Specify_JSX_code_generation_Colon_preserve_react_native_or_react, + }, + { + name: "declaration", + shortName: "d", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Generates_corresponding_d_ts_file, + }, + { + name: "declarationMap", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Generates_a_sourcemap_for_each_corresponding_d_ts_file, + }, + { + name: "emitDeclarationOnly", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Only_emit_d_ts_declaration_files, + }, + { + name: "sourceMap", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Generates_corresponding_map_file, + }, + { + name: "outFile", + type: "string", + isFilePath: true, + paramType: ts.Diagnostics.FILE, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Concatenate_and_emit_output_to_single_file, + }, + { + name: "outDir", + type: "string", + isFilePath: true, + paramType: ts.Diagnostics.DIRECTORY, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Redirect_output_structure_to_the_directory, + }, + { + name: "rootDir", + type: "string", + isFilePath: true, + paramType: ts.Diagnostics.LOCATION, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir, + }, + { + name: "composite", + type: "boolean", + isTSConfigOnly: true, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Enable_project_compilation, + }, + { + name: "removeComments", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Do_not_emit_comments_to_output, + }, + { + name: "noEmit", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Do_not_emit_outputs, + }, + { + name: "importHelpers", + type: "boolean", + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Import_emit_helpers_from_tslib + }, + { + name: "downlevelIteration", + type: "boolean", + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Provide_full_support_for_iterables_in_for_of_spread_and_destructuring_when_targeting_ES5_or_ES3 + }, + { + name: "isolatedModules", + type: "boolean", + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule + }, + // Strict Type Checks + { + name: "strict", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Strict_Type_Checking_Options, + description: ts.Diagnostics.Enable_all_strict_type_checking_options + }, + { + name: "noImplicitAny", + type: "boolean", + affectsSemanticDiagnostics: true, + strictFlag: true, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Strict_Type_Checking_Options, + description: ts.Diagnostics.Raise_error_on_expressions_and_declarations_with_an_implied_any_type + }, + { + name: "strictNullChecks", + type: "boolean", + affectsSemanticDiagnostics: true, + strictFlag: true, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Strict_Type_Checking_Options, + description: ts.Diagnostics.Enable_strict_null_checks + }, + { + name: "strictFunctionTypes", + type: "boolean", + affectsSemanticDiagnostics: true, + strictFlag: true, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Strict_Type_Checking_Options, + description: ts.Diagnostics.Enable_strict_checking_of_function_types + }, + { + name: "strictBindCallApply", + type: "boolean", + strictFlag: true, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Strict_Type_Checking_Options, + description: ts.Diagnostics.Enable_strict_bind_call_and_apply_methods_on_functions + }, + { + name: "strictPropertyInitialization", + type: "boolean", + affectsSemanticDiagnostics: true, + strictFlag: true, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Strict_Type_Checking_Options, + description: ts.Diagnostics.Enable_strict_checking_of_property_initialization_in_classes + }, + { + name: "noImplicitThis", + type: "boolean", + affectsSemanticDiagnostics: true, + strictFlag: true, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Strict_Type_Checking_Options, + description: ts.Diagnostics.Raise_error_on_this_expressions_with_an_implied_any_type, + }, + { + name: "alwaysStrict", + type: "boolean", + affectsSourceFile: true, + strictFlag: true, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Strict_Type_Checking_Options, + description: ts.Diagnostics.Parse_in_strict_mode_and_emit_use_strict_for_each_source_file + }, + // Additional Checks + { + name: "noUnusedLocals", + type: "boolean", + affectsSemanticDiagnostics: true, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Additional_Checks, + description: ts.Diagnostics.Report_errors_on_unused_locals, + }, + { + name: "noUnusedParameters", + type: "boolean", + affectsSemanticDiagnostics: true, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Additional_Checks, + description: ts.Diagnostics.Report_errors_on_unused_parameters, + }, + { + name: "noImplicitReturns", + type: "boolean", + affectsSemanticDiagnostics: true, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Additional_Checks, + description: ts.Diagnostics.Report_error_when_not_all_code_paths_in_function_return_a_value + }, + { + name: "noFallthroughCasesInSwitch", + type: "boolean", + affectsBindDiagnostics: true, + affectsSemanticDiagnostics: true, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Additional_Checks, + description: ts.Diagnostics.Report_errors_for_fallthrough_cases_in_switch_statement + }, + // Module Resolution + { + name: "moduleResolution", + type: ts.createMapFromTemplate({ + node: ts.ModuleResolutionKind.NodeJs, + classic: ts.ModuleResolutionKind.Classic, + }), + affectsModuleResolution: true, + paramType: ts.Diagnostics.STRATEGY, + category: ts.Diagnostics.Module_Resolution_Options, + description: ts.Diagnostics.Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6, + }, + { + name: "baseUrl", + type: "string", + affectsModuleResolution: true, + isFilePath: true, + category: ts.Diagnostics.Module_Resolution_Options, + description: ts.Diagnostics.Base_directory_to_resolve_non_absolute_module_names + }, + { + // this option can only be specified in tsconfig.json + // use type = object to copy the value as-is + name: "paths", + type: "object", + affectsModuleResolution: true, + isTSConfigOnly: true, + category: ts.Diagnostics.Module_Resolution_Options, + description: ts.Diagnostics.A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl + }, + { + // this option can only be specified in tsconfig.json + // use type = object to copy the value as-is + name: "rootDirs", + type: "list", + isTSConfigOnly: true, + element: { + name: "rootDirs", + type: "string", + isFilePath: true + }, + affectsModuleResolution: true, + category: ts.Diagnostics.Module_Resolution_Options, + description: ts.Diagnostics.List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime + }, + { + name: "typeRoots", + type: "list", + element: { + name: "typeRoots", + type: "string", + isFilePath: true + }, + affectsModuleResolution: true, + category: ts.Diagnostics.Module_Resolution_Options, + description: ts.Diagnostics.List_of_folders_to_include_type_definitions_from + }, + { + name: "types", + type: "list", + element: { + name: "types", + type: "string" + }, + affectsModuleResolution: true, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Module_Resolution_Options, + description: ts.Diagnostics.Type_declaration_files_to_be_included_in_compilation + }, + { + name: "allowSyntheticDefaultImports", + type: "boolean", + affectsSemanticDiagnostics: true, + category: ts.Diagnostics.Module_Resolution_Options, + description: ts.Diagnostics.Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking + }, + { + name: "esModuleInterop", + type: "boolean", + affectsSemanticDiagnostics: true, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Module_Resolution_Options, + description: ts.Diagnostics.Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for_all_imports_Implies_allowSyntheticDefaultImports + }, + { + name: "preserveSymlinks", + type: "boolean", + category: ts.Diagnostics.Module_Resolution_Options, + description: ts.Diagnostics.Do_not_resolve_the_real_path_of_symlinks, + }, + // Source Maps + { + name: "sourceRoot", + type: "string", + paramType: ts.Diagnostics.LOCATION, + category: ts.Diagnostics.Source_Map_Options, + description: ts.Diagnostics.Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations, + }, + { + name: "mapRoot", + type: "string", + paramType: ts.Diagnostics.LOCATION, + category: ts.Diagnostics.Source_Map_Options, + description: ts.Diagnostics.Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations, + }, + { + name: "inlineSourceMap", + type: "boolean", + category: ts.Diagnostics.Source_Map_Options, + description: ts.Diagnostics.Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file + }, + { + name: "inlineSources", + type: "boolean", + category: ts.Diagnostics.Source_Map_Options, + description: ts.Diagnostics.Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap_to_be_set + }, + // Experimental + { + name: "experimentalDecorators", + type: "boolean", + category: ts.Diagnostics.Experimental_Options, + description: ts.Diagnostics.Enables_experimental_support_for_ES7_decorators + }, + { + name: "emitDecoratorMetadata", + type: "boolean", + category: ts.Diagnostics.Experimental_Options, + description: ts.Diagnostics.Enables_experimental_support_for_emitting_type_metadata_for_decorators + }, + // Advanced + { + name: "jsxFactory", + type: "string", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h + }, + { + name: "resolveJsonModule", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Include_modules_imported_with_json_extension + }, + { + name: "out", + type: "string", + isFilePath: false, + // for correct behaviour, please use outFile + category: ts.Diagnostics.Advanced_Options, + paramType: ts.Diagnostics.FILE, + description: ts.Diagnostics.Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file, + }, + { + name: "reactNamespace", + type: "string", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react_JSX_emit + }, + { + name: "skipDefaultLibCheck", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files + }, + { + name: "charset", + type: "string", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.The_character_set_of_the_input_files + }, + { + name: "emitBOM", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files + }, + { + name: "locale", + type: "string", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.The_locale_used_when_displaying_messages_to_the_user_e_g_en_us + }, + { + name: "newLine", + type: ts.createMapFromTemplate({ + crlf: 0 /* CarriageReturnLineFeed */, + lf: 1 /* LineFeed */ + }), + paramType: ts.Diagnostics.NEWLINE, + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix, + }, + { + name: "noErrorTruncation", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Do_not_truncate_error_messages + }, + { + name: "noLib", + type: "boolean", + affectsModuleResolution: true, + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Do_not_include_the_default_library_file_lib_d_ts + }, + { + name: "noResolve", + type: "boolean", + affectsModuleResolution: true, + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files + }, + { + name: "stripInternal", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Do_not_emit_declarations_for_code_that_has_an_internal_annotation, + }, + { + name: "disableSizeLimit", + type: "boolean", + affectsSourceFile: true, + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Disable_size_limitations_on_JavaScript_projects + }, + { + name: "noImplicitUseStrict", + type: "boolean", + affectsSemanticDiagnostics: true, + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Do_not_emit_use_strict_directives_in_module_output + }, + { + name: "noEmitHelpers", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Do_not_generate_custom_helper_functions_like_extends_in_compiled_output + }, + { + name: "noEmitOnError", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Do_not_emit_outputs_if_any_errors_were_reported, + }, + { + name: "preserveConstEnums", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Do_not_erase_const_enum_declarations_in_generated_code + }, + { + name: "declarationDir", + type: "string", + isFilePath: true, + paramType: ts.Diagnostics.DIRECTORY, + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Output_directory_for_generated_declaration_files + }, + { + name: "skipLibCheck", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Skip_type_checking_of_declaration_files, + }, + { + name: "allowUnusedLabels", + type: "boolean", + affectsBindDiagnostics: true, + affectsSemanticDiagnostics: true, + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Do_not_report_errors_on_unused_labels + }, + { + name: "allowUnreachableCode", + type: "boolean", + affectsBindDiagnostics: true, + affectsSemanticDiagnostics: true, + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Do_not_report_errors_on_unreachable_code + }, + { + name: "suppressExcessPropertyErrors", + type: "boolean", + affectsSemanticDiagnostics: true, + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Suppress_excess_property_checks_for_object_literals, + }, + { + name: "suppressImplicitAnyIndexErrors", + type: "boolean", + affectsSemanticDiagnostics: true, + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures, + }, + { + name: "forceConsistentCasingInFileNames", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Disallow_inconsistently_cased_references_to_the_same_file + }, + { + name: "maxNodeModuleJsDepth", + type: "number", + affectsModuleResolution: true, + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files + }, + { + name: "noStrictGenericChecks", + type: "boolean", + affectsSemanticDiagnostics: true, + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Disable_strict_checking_of_generic_signatures_in_function_types, + }, + { + name: "keyofStringsOnly", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols, + }, + { + // A list of plugins to load in the language service + name: "plugins", + type: "list", + isTSConfigOnly: true, + element: { + name: "plugin", + type: "object" + }, + description: ts.Diagnostics.List_of_language_service_plugins + } + ]); + /* @internal */ + ts.semanticDiagnosticsOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsSemanticDiagnostics; }); + /* @internal */ + ts.moduleResolutionOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsModuleResolution; }); + /* @internal */ + ts.sourceFileAffectingCompilerOptions = ts.optionDeclarations.filter(function (option) { + return !!option.affectsSourceFile || !!option.affectsModuleResolution || !!option.affectsBindDiagnostics; + }); + /* @internal */ + ts.buildOpts = ts.commonOptionsWithBuild.concat([ + { + name: "verbose", + shortName: "v", + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Enable_verbose_logging, + type: "boolean" + }, + { + name: "dry", + shortName: "d", + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Show_what_would_be_built_or_deleted_if_specified_with_clean, + type: "boolean" + }, + { + name: "force", + shortName: "f", + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Build_all_projects_including_those_that_appear_to_be_up_to_date, + type: "boolean" + }, + { + name: "clean", + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Delete_the_outputs_of_all_projects, + type: "boolean" + } + ]); + /* @internal */ + ts.typeAcquisitionDeclarations = [ + { + /* @deprecated typingOptions.enableAutoDiscovery + * Use typeAcquisition.enable instead. + */ + name: "enableAutoDiscovery", + type: "boolean", + }, + { + name: "enable", + type: "boolean", + }, + { + name: "include", + type: "list", + element: { + name: "include", + type: "string" + } + }, + { + name: "exclude", + type: "list", + element: { + name: "exclude", + type: "string" + } + } + ]; + /* @internal */ + ts.defaultInitCompilerOptions = { + module: ts.ModuleKind.CommonJS, + target: 1 /* ES5 */, + strict: true, + esModuleInterop: true + }; + var optionNameMapCache; + /* @internal */ + function convertEnableAutoDiscoveryToEnable(typeAcquisition) { + // Convert deprecated typingOptions.enableAutoDiscovery to typeAcquisition.enable + if (typeAcquisition && typeAcquisition.enableAutoDiscovery !== undefined && typeAcquisition.enable === undefined) { + return { + enable: typeAcquisition.enableAutoDiscovery, + include: typeAcquisition.include || [], + exclude: typeAcquisition.exclude || [] + }; + } + return typeAcquisition; + } + ts.convertEnableAutoDiscoveryToEnable = convertEnableAutoDiscoveryToEnable; + function getOptionNameMap() { + return optionNameMapCache || (optionNameMapCache = createOptionNameMap(ts.optionDeclarations)); + } + /*@internal*/ + function createOptionNameMap(optionDeclarations) { + var optionNameMap = ts.createMap(); + var shortOptionNames = ts.createMap(); + ts.forEach(optionDeclarations, function (option) { + optionNameMap.set(option.name.toLowerCase(), option); + if (option.shortName) { + shortOptionNames.set(option.shortName, option.name); + } + }); + return { optionNameMap: optionNameMap, shortOptionNames: shortOptionNames }; + } + ts.createOptionNameMap = createOptionNameMap; + /* @internal */ + function createCompilerDiagnosticForInvalidCustomType(opt) { + return createDiagnosticForInvalidCustomType(opt, ts.createCompilerDiagnostic); + } + ts.createCompilerDiagnosticForInvalidCustomType = createCompilerDiagnosticForInvalidCustomType; + function createDiagnosticForInvalidCustomType(opt, createDiagnostic) { + var namesOfType = ts.arrayFrom(opt.type.keys()).map(function (key) { return "'" + key + "'"; }).join(", "); + return createDiagnostic(ts.Diagnostics.Argument_for_0_option_must_be_Colon_1, "--" + opt.name, namesOfType); + } + /* @internal */ + function parseCustomTypeOption(opt, value, errors) { + return convertJsonOptionOfCustomType(opt, trimString(value || ""), errors); + } + ts.parseCustomTypeOption = parseCustomTypeOption; + /* @internal */ + function parseListTypeOption(opt, value, errors) { + if (value === void 0) { value = ""; } + value = trimString(value); + if (ts.startsWith(value, "-")) { + return undefined; + } + if (value === "") { + return []; + } + var values = value.split(","); + switch (opt.element.type) { + case "number": + return ts.map(values, parseInt); + case "string": + return ts.map(values, function (v) { return v || ""; }); + default: + return ts.mapDefined(values, function (v) { return parseCustomTypeOption(opt.element, v, errors); }); + } + } + ts.parseListTypeOption = parseListTypeOption; + function parseCommandLineWorker(getOptionNameMap, _a, commandLine, readFile) { + var unknownOptionDiagnostic = _a[0], optionTypeMismatchDiagnostic = _a[1]; + var options = {}; + var fileNames = []; + var errors = []; + parseStrings(commandLine); + return { + options: options, + fileNames: fileNames, + errors: errors + }; + function parseStrings(args) { + var i = 0; + while (i < args.length) { + var s = args[i]; + i++; + if (s.charCodeAt(0) === 64 /* at */) { + parseResponseFile(s.slice(1)); + } + else if (s.charCodeAt(0) === 45 /* minus */) { + var opt = getOptionDeclarationFromName(getOptionNameMap, s.slice(s.charCodeAt(1) === 45 /* minus */ ? 2 : 1), /*allowShort*/ true); + if (opt) { + if (opt.isTSConfigOnly) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_can_only_be_specified_in_tsconfig_json_file, opt.name)); + } + else { + // Check to see if no argument was provided (e.g. "--locale" is the last command-line argument). + if (!args[i] && opt.type !== "boolean") { + errors.push(ts.createCompilerDiagnostic(optionTypeMismatchDiagnostic, opt.name)); + } + switch (opt.type) { + case "number": + options[opt.name] = parseInt(args[i]); + i++; + break; + case "boolean": + // boolean flag has optional value true, false, others + var optValue = args[i]; + options[opt.name] = optValue !== "false"; + // consume next argument as boolean flag value + if (optValue === "false" || optValue === "true") { + i++; + } + break; + case "string": + options[opt.name] = args[i] || ""; + i++; + break; + case "list": + var result = parseListTypeOption(opt, args[i], errors); + options[opt.name] = result || []; + if (result) { + i++; + } + break; + // If not a primitive, the possible types are specified in what is effectively a map of options. + default: + options[opt.name] = parseCustomTypeOption(opt, args[i], errors); + i++; + break; + } + } + } + else { + errors.push(ts.createCompilerDiagnostic(unknownOptionDiagnostic, s)); + } + } + else { + fileNames.push(s); + } + } + } + function parseResponseFile(fileName) { + var text = readFile ? readFile(fileName) : ts.sys.readFile(fileName); + if (!text) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_not_found, fileName)); + return; + } + var args = []; + var pos = 0; + while (true) { + while (pos < text.length && text.charCodeAt(pos) <= 32 /* space */) + pos++; + if (pos >= text.length) + break; + var start = pos; + if (text.charCodeAt(start) === 34 /* doubleQuote */) { + pos++; + while (pos < text.length && text.charCodeAt(pos) !== 34 /* doubleQuote */) + pos++; + if (pos < text.length) { + args.push(text.substring(start + 1, pos)); + pos++; + } + else { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unterminated_quoted_string_in_response_file_0, fileName)); + } + } + else { + while (text.charCodeAt(pos) > 32 /* space */) + pos++; + args.push(text.substring(start, pos)); + } + } + parseStrings(args); + } + } + function parseCommandLine(commandLine, readFile) { + return parseCommandLineWorker(getOptionNameMap, [ + ts.Diagnostics.Unknown_compiler_option_0, + ts.Diagnostics.Compiler_option_0_expects_an_argument + ], commandLine, readFile); + } + ts.parseCommandLine = parseCommandLine; + /** @internal */ + function getOptionFromName(optionName, allowShort) { + return getOptionDeclarationFromName(getOptionNameMap, optionName, allowShort); + } + ts.getOptionFromName = getOptionFromName; + function getOptionDeclarationFromName(getOptionNameMap, optionName, allowShort) { + if (allowShort === void 0) { allowShort = false; } + optionName = optionName.toLowerCase(); + var _a = getOptionNameMap(), optionNameMap = _a.optionNameMap, shortOptionNames = _a.shortOptionNames; + // Try to translate short option names to their full equivalents. + if (allowShort) { + var short = shortOptionNames.get(optionName); + if (short !== undefined) { + optionName = short; + } + } + return optionNameMap.get(optionName); + } + /*@internal*/ + function parseBuildCommand(args) { + var buildOptionNameMap; + var returnBuildOptionNameMap = function () { return (buildOptionNameMap || (buildOptionNameMap = createOptionNameMap(ts.buildOpts))); }; + var _a = parseCommandLineWorker(returnBuildOptionNameMap, [ + ts.Diagnostics.Unknown_build_option_0, + ts.Diagnostics.Build_option_0_requires_a_value_of_type_1 + ], args), options = _a.options, projects = _a.fileNames, errors = _a.errors; + var buildOptions = options; + if (projects.length === 0) { + // tsc -b invoked with no extra arguments; act as if invoked with "tsc -b ." + projects.push("."); + } + // Nonsensical combinations + if (buildOptions.clean && buildOptions.force) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "force")); + } + if (buildOptions.clean && buildOptions.verbose) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "verbose")); + } + if (buildOptions.clean && buildOptions.watch) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "watch")); + } + if (buildOptions.watch && buildOptions.dry) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "watch", "dry")); + } + return { buildOptions: buildOptions, projects: projects, errors: errors }; + } + ts.parseBuildCommand = parseBuildCommand; + function getDiagnosticText(_message) { + var _args = []; + for (var _i = 1; _i < arguments.length; _i++) { + _args[_i - 1] = arguments[_i]; + } + var diagnostic = ts.createCompilerDiagnostic.apply(undefined, arguments); + return diagnostic.messageText; + } + /* @internal */ + function printVersion() { + ts.sys.write(getDiagnosticText(ts.Diagnostics.Version_0, ts.version) + ts.sys.newLine); + } + ts.printVersion = printVersion; + /* @internal */ + function printHelp(optionsList, syntaxPrefix) { + if (syntaxPrefix === void 0) { syntaxPrefix = ""; } + var output = []; + // We want to align our "syntax" and "examples" commands to a certain margin. + var syntaxLength = getDiagnosticText(ts.Diagnostics.Syntax_Colon_0, "").length; + var examplesLength = getDiagnosticText(ts.Diagnostics.Examples_Colon_0, "").length; + var marginLength = Math.max(syntaxLength, examplesLength); + // Build up the syntactic skeleton. + var syntax = makePadding(marginLength - syntaxLength); + syntax += "tsc " + syntaxPrefix + "[" + getDiagnosticText(ts.Diagnostics.options) + "] [" + getDiagnosticText(ts.Diagnostics.file) + "...]"; + output.push(getDiagnosticText(ts.Diagnostics.Syntax_Colon_0, syntax)); + output.push(ts.sys.newLine + ts.sys.newLine); + // Build up the list of examples. + var padding = makePadding(marginLength); + output.push(getDiagnosticText(ts.Diagnostics.Examples_Colon_0, makePadding(marginLength - examplesLength) + "tsc hello.ts") + ts.sys.newLine); + output.push(padding + "tsc --outFile file.js file.ts" + ts.sys.newLine); + output.push(padding + "tsc @args.txt" + ts.sys.newLine); + output.push(padding + "tsc --build tsconfig.json" + ts.sys.newLine); + output.push(ts.sys.newLine); + output.push(getDiagnosticText(ts.Diagnostics.Options_Colon) + ts.sys.newLine); + // We want our descriptions to align at the same column in our output, + // so we keep track of the longest option usage string. + marginLength = 0; + var usageColumn = []; // Things like "-d, --declaration" go in here. + var descriptionColumn = []; + var optionsDescriptionMap = ts.createMap(); // Map between option.description and list of option.type if it is a kind + for (var _i = 0, optionsList_1 = optionsList; _i < optionsList_1.length; _i++) { + var option = optionsList_1[_i]; + // If an option lacks a description, + // it is not officially supported. + if (!option.description) { + continue; + } + var usageText_1 = " "; + if (option.shortName) { + usageText_1 += "-" + option.shortName; + usageText_1 += getParamType(option); + usageText_1 += ", "; + } + usageText_1 += "--" + option.name; + usageText_1 += getParamType(option); + usageColumn.push(usageText_1); + var description = void 0; + if (option.name === "lib") { + description = getDiagnosticText(option.description); + var element = option.element; + var typeMap = element.type; + optionsDescriptionMap.set(description, ts.arrayFrom(typeMap.keys()).map(function (key) { return "'" + key + "'"; })); + } + else { + description = getDiagnosticText(option.description); + } + descriptionColumn.push(description); + // Set the new margin for the description column if necessary. + marginLength = Math.max(usageText_1.length, marginLength); + } + // Special case that can't fit in the loop. + var usageText = " @<" + getDiagnosticText(ts.Diagnostics.file) + ">"; + usageColumn.push(usageText); + descriptionColumn.push(getDiagnosticText(ts.Diagnostics.Insert_command_line_options_and_files_from_a_file)); + marginLength = Math.max(usageText.length, marginLength); + // Print out each row, aligning all the descriptions on the same column. + for (var i = 0; i < usageColumn.length; i++) { + var usage = usageColumn[i]; + var description = descriptionColumn[i]; + var kindsList = optionsDescriptionMap.get(description); + output.push(usage + makePadding(marginLength - usage.length + 2) + description + ts.sys.newLine); + if (kindsList) { + output.push(makePadding(marginLength + 4)); + for (var _a = 0, kindsList_1 = kindsList; _a < kindsList_1.length; _a++) { + var kind = kindsList_1[_a]; + output.push(kind + " "); + } + output.push(ts.sys.newLine); + } + } + for (var _b = 0, output_1 = output; _b < output_1.length; _b++) { + var line = output_1[_b]; + ts.sys.write(line); + } + return; + function getParamType(option) { + if (option.paramType !== undefined) { + return " " + getDiagnosticText(option.paramType); + } + return ""; + } + function makePadding(paddingLength) { + return Array(paddingLength + 1).join(" "); + } + } + ts.printHelp = printHelp; + /** + * Reads the config file, reports errors if any and exits if the config file cannot be found + */ + function getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host) { + var configFileText; + try { + configFileText = host.readFile(configFileName); + } + catch (e) { + var error = ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, configFileName, e.message); + host.onUnRecoverableConfigFileDiagnostic(error); + return undefined; + } + if (!configFileText) { + var error = ts.createCompilerDiagnostic(ts.Diagnostics.File_0_not_found, configFileName); + host.onUnRecoverableConfigFileDiagnostic(error); + return undefined; + } + var result = ts.parseJsonText(configFileName, configFileText); + var cwd = host.getCurrentDirectory(); + result.path = ts.toPath(configFileName, cwd, ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames)); + result.resolvedPath = result.path; + result.originalFileName = result.fileName; + return parseJsonSourceFileConfigFileContent(result, host, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), cwd), optionsToExtend, ts.getNormalizedAbsolutePath(configFileName, cwd)); + } + ts.getParsedCommandLineOfConfigFile = getParsedCommandLineOfConfigFile; + /** + * Read tsconfig.json file + * @param fileName The path to the config file + */ + function readConfigFile(fileName, readFile) { + var textOrDiagnostic = tryReadFile(fileName, readFile); + return ts.isString(textOrDiagnostic) ? parseConfigFileTextToJson(fileName, textOrDiagnostic) : { config: {}, error: textOrDiagnostic }; + } + ts.readConfigFile = readConfigFile; + /** + * Parse the text of the tsconfig.json file + * @param fileName The path to the config file + * @param jsonText The text of the config file + */ + function parseConfigFileTextToJson(fileName, jsonText) { + var jsonSourceFile = ts.parseJsonText(fileName, jsonText); + return { + config: convertToObject(jsonSourceFile, jsonSourceFile.parseDiagnostics), + error: jsonSourceFile.parseDiagnostics.length ? jsonSourceFile.parseDiagnostics[0] : undefined + }; + } + ts.parseConfigFileTextToJson = parseConfigFileTextToJson; + /** + * Read tsconfig.json file + * @param fileName The path to the config file + */ + function readJsonConfigFile(fileName, readFile) { + var textOrDiagnostic = tryReadFile(fileName, readFile); + return ts.isString(textOrDiagnostic) ? ts.parseJsonText(fileName, textOrDiagnostic) : { parseDiagnostics: [textOrDiagnostic] }; + } + ts.readJsonConfigFile = readJsonConfigFile; + function tryReadFile(fileName, readFile) { + var text; + try { + text = readFile(fileName); + } + catch (e) { + return ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, e.message); + } + return text === undefined ? ts.createCompilerDiagnostic(ts.Diagnostics.The_specified_path_does_not_exist_Colon_0, fileName) : text; + } + function commandLineOptionsToMap(options) { + return ts.arrayToMap(options, function (option) { return option.name; }); + } + var _tsconfigRootOptions; + function getTsconfigRootOptionsMap() { + if (_tsconfigRootOptions === undefined) { + _tsconfigRootOptions = { + name: undefined, + type: "object", + elementOptions: commandLineOptionsToMap([ + { + name: "compilerOptions", + type: "object", + elementOptions: commandLineOptionsToMap(ts.optionDeclarations), + extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_compiler_option_0 + }, + { + name: "typingOptions", + type: "object", + elementOptions: commandLineOptionsToMap(ts.typeAcquisitionDeclarations), + extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_type_acquisition_option_0 + }, + { + name: "typeAcquisition", + type: "object", + elementOptions: commandLineOptionsToMap(ts.typeAcquisitionDeclarations), + extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_type_acquisition_option_0 + }, + { + name: "extends", + type: "string" + }, + { + name: "references", + type: "list", + element: { + name: "references", + type: "object" + } + }, + { + name: "files", + type: "list", + element: { + name: "files", + type: "string" + } + }, + { + name: "include", + type: "list", + element: { + name: "include", + type: "string" + } + }, + { + name: "exclude", + type: "list", + element: { + name: "exclude", + type: "string" + } + }, + ts.compileOnSaveCommandLineOption + ]) + }; + } + return _tsconfigRootOptions; + } + /** + * Convert the json syntax tree into the json value + */ + function convertToObject(sourceFile, errors) { + return convertToObjectWorker(sourceFile, errors, /*returnValue*/ true, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined); + } + ts.convertToObject = convertToObject; + /** + * Convert the json syntax tree into the json value and report errors + * This returns the json value (apart from checking errors) only if returnValue provided is true. + * Otherwise it just checks the errors and returns undefined + */ + /*@internal*/ + function convertToObjectWorker(sourceFile, errors, returnValue, knownRootOptions, jsonConversionNotifier) { + if (!sourceFile.statements.length) { + return returnValue ? {} : undefined; + } + return convertPropertyValueToJson(sourceFile.statements[0].expression, knownRootOptions); + function isRootOptionMap(knownOptions) { + return knownRootOptions && knownRootOptions.elementOptions === knownOptions; + } + function convertObjectLiteralExpressionToJson(node, knownOptions, extraKeyDiagnosticMessage, parentOption) { + var result = returnValue ? {} : undefined; + for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { + var element = _a[_i]; + if (element.kind !== 275 /* PropertyAssignment */) { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element, ts.Diagnostics.Property_assignment_expected)); + continue; + } + if (element.questionToken) { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.questionToken, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, "?")); + } + if (!isDoubleQuotedString(element.name)) { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, ts.Diagnostics.String_literal_with_double_quotes_expected)); + } + var textOfKey = ts.getTextOfPropertyName(element.name); + var keyText = textOfKey && ts.unescapeLeadingUnderscores(textOfKey); + var option = keyText && knownOptions ? knownOptions.get(keyText) : undefined; + if (keyText && extraKeyDiagnosticMessage && !option) { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, extraKeyDiagnosticMessage, keyText)); + } + var value = convertPropertyValueToJson(element.initializer, option); + if (typeof keyText !== "undefined") { + if (returnValue) { + result[keyText] = value; + } + // Notify key value set, if user asked for it + if (jsonConversionNotifier && + // Current callbacks are only on known parent option or if we are setting values in the root + (parentOption || isRootOptionMap(knownOptions))) { + var isValidOptionValue = isCompilerOptionsValue(option, value); + if (parentOption) { + if (isValidOptionValue) { + // Notify option set in the parent if its a valid option value + jsonConversionNotifier.onSetValidOptionKeyValueInParent(parentOption, option, value); + } + } + else if (isRootOptionMap(knownOptions)) { + if (isValidOptionValue) { + // Notify about the valid root key value being set + jsonConversionNotifier.onSetValidOptionKeyValueInRoot(keyText, element.name, value, element.initializer); + } + else if (!option) { + // Notify about the unknown root key value being set + jsonConversionNotifier.onSetUnknownOptionKeyValueInRoot(keyText, element.name, value, element.initializer); + } + } + } + } + } + return result; + } + function convertArrayLiteralExpressionToJson(elements, elementOption) { + if (!returnValue) { + return elements.forEach(function (element) { return convertPropertyValueToJson(element, elementOption); }); + } + // Filter out invalid values + return ts.filter(elements.map(function (element) { return convertPropertyValueToJson(element, elementOption); }), function (v) { return v !== undefined; }); + } + function convertPropertyValueToJson(valueExpression, option) { + switch (valueExpression.kind) { + case 102 /* TrueKeyword */: + reportInvalidOptionValue(option && option.type !== "boolean"); + return true; + case 87 /* FalseKeyword */: + reportInvalidOptionValue(option && option.type !== "boolean"); + return false; + case 96 /* NullKeyword */: + reportInvalidOptionValue(option && option.name === "extends"); // "extends" is the only option we don't allow null/undefined for + return null; // tslint:disable-line:no-null-keyword + case 10 /* StringLiteral */: + if (!isDoubleQuotedString(valueExpression)) { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, ts.Diagnostics.String_literal_with_double_quotes_expected)); + } + reportInvalidOptionValue(option && (ts.isString(option.type) && option.type !== "string")); + var text = valueExpression.text; + if (option && !ts.isString(option.type)) { + var customOption = option; + // Validate custom option type + if (!customOption.type.has(text.toLowerCase())) { + errors.push(createDiagnosticForInvalidCustomType(customOption, function (message, arg0, arg1) { return ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, message, arg0, arg1); })); + } + } + return text; + case 8 /* NumericLiteral */: + reportInvalidOptionValue(option && option.type !== "number"); + return Number(valueExpression.text); + case 202 /* PrefixUnaryExpression */: + if (valueExpression.operator !== 39 /* MinusToken */ || valueExpression.operand.kind !== 8 /* NumericLiteral */) { + break; // not valid JSON syntax + } + reportInvalidOptionValue(option && option.type !== "number"); + return -Number(valueExpression.operand.text); + case 188 /* ObjectLiteralExpression */: + reportInvalidOptionValue(option && option.type !== "object"); + var objectLiteralExpression = valueExpression; + // Currently having element option declaration in the tsconfig with type "object" + // determines if it needs onSetValidOptionKeyValueInParent callback or not + // At moment there are only "compilerOptions", "typeAcquisition" and "typingOptions" + // that satifies it and need it to modify options set in them (for normalizing file paths) + // vs what we set in the json + // If need arises, we can modify this interface and callbacks as needed + if (option) { + var _a = option, elementOptions = _a.elementOptions, extraKeyDiagnosticMessage = _a.extraKeyDiagnosticMessage, optionName = _a.name; + return convertObjectLiteralExpressionToJson(objectLiteralExpression, elementOptions, extraKeyDiagnosticMessage, optionName); + } + else { + return convertObjectLiteralExpressionToJson(objectLiteralExpression, /* knownOptions*/ undefined, + /*extraKeyDiagnosticMessage */ undefined, /*parentOption*/ undefined); + } + case 187 /* ArrayLiteralExpression */: + reportInvalidOptionValue(option && option.type !== "list"); + return convertArrayLiteralExpressionToJson(valueExpression.elements, option && option.element); + } + // Not in expected format + if (option) { + reportInvalidOptionValue(/*isError*/ true); + } + else { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, ts.Diagnostics.Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_literal)); + } + return undefined; + function reportInvalidOptionValue(isError) { + if (isError) { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, option.name, getCompilerOptionValueTypeString(option))); + } + } + } + function isDoubleQuotedString(node) { + return ts.isStringLiteral(node) && ts.isStringDoubleQuoted(node, sourceFile); + } + } + ts.convertToObjectWorker = convertToObjectWorker; + function getCompilerOptionValueTypeString(option) { + return option.type === "list" ? + "Array" : + ts.isString(option.type) ? option.type : "string"; + } + function isCompilerOptionsValue(option, value) { + if (option) { + if (isNullOrUndefined(value)) + return true; // All options are undefinable/nullable + if (option.type === "list") { + return ts.isArray(value); + } + var expectedType = ts.isString(option.type) ? option.type : "string"; + return typeof value === expectedType; + } + return false; + } + /** + * Generate an uncommented, complete tsconfig for use with "--showConfig" + * @param configParseResult options to be generated into tsconfig.json + * @param configFileName name of the parsed config file - output paths will be generated relative to this + * @param host provides current directory and case sensitivity services + */ + /** @internal */ + function convertToTSConfig(configParseResult, configFileName, host) { + var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); + var files = ts.map(ts.filter(configParseResult.fileNames, (!configParseResult.configFileSpecs || !configParseResult.configFileSpecs.validatedIncludeSpecs) ? function (_) { return true; } : matchesSpecs(configFileName, configParseResult.configFileSpecs.validatedIncludeSpecs, configParseResult.configFileSpecs.validatedExcludeSpecs)), function (f) { return ts.getRelativePathFromFile(ts.getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), ts.getNormalizedAbsolutePath(f, host.getCurrentDirectory()), getCanonicalFileName); }); + var optionMap = serializeCompilerOptions(configParseResult.options, { configFilePath: ts.getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), useCaseSensitiveFileNames: host.useCaseSensitiveFileNames }); + var config = __assign({ compilerOptions: __assign({}, ts.arrayFrom(optionMap.entries()).reduce(function (prev, cur) { + var _a; + return (__assign({}, prev, (_a = {}, _a[cur[0]] = cur[1], _a))); + }, {}), { showConfig: undefined, configFile: undefined, configFilePath: undefined, help: undefined, init: undefined, listFiles: undefined, listEmittedFiles: undefined, project: undefined }), references: ts.map(configParseResult.projectReferences, function (r) { return (__assign({}, r, { path: r.originalPath, originalPath: undefined })); }), files: ts.length(files) ? files : undefined }, (configParseResult.configFileSpecs ? { + include: filterSameAsDefaultInclude(configParseResult.configFileSpecs.validatedIncludeSpecs), + exclude: configParseResult.configFileSpecs.validatedExcludeSpecs + } : {}), { compilerOnSave: !!configParseResult.compileOnSave ? true : undefined }); + return config; + } + ts.convertToTSConfig = convertToTSConfig; + function filterSameAsDefaultInclude(specs) { + if (!ts.length(specs)) + return undefined; + if (ts.length(specs) !== 1) + return specs; + if (specs[0] === "**/*") + return undefined; + return specs; + } + function matchesSpecs(path, includeSpecs, excludeSpecs) { + if (!includeSpecs) + return function (_) { return true; }; + var patterns = ts.getFileMatcherPatterns(path, excludeSpecs, includeSpecs, ts.sys.useCaseSensitiveFileNames, ts.sys.getCurrentDirectory()); + var excludeRe = patterns.excludePattern && ts.getRegexFromPattern(patterns.excludePattern, ts.sys.useCaseSensitiveFileNames); + var includeRe = patterns.includeFilePattern && ts.getRegexFromPattern(patterns.includeFilePattern, ts.sys.useCaseSensitiveFileNames); + if (includeRe) { + if (excludeRe) { + return function (path) { return !(includeRe.test(path) && !excludeRe.test(path)); }; + } + return function (path) { return !includeRe.test(path); }; + } + if (excludeRe) { + return function (path) { return excludeRe.test(path); }; + } + return function (_) { return true; }; + } + function getCustomTypeMapOfCommandLineOption(optionDefinition) { + if (optionDefinition.type === "string" || optionDefinition.type === "number" || optionDefinition.type === "boolean") { + // this is of a type CommandLineOptionOfPrimitiveType + return undefined; + } + else if (optionDefinition.type === "list") { + return getCustomTypeMapOfCommandLineOption(optionDefinition.element); + } + else { + return optionDefinition.type; + } + } + function getNameOfCompilerOptionValue(value, customTypeMap) { + // There is a typeMap associated with this command-line option so use it to map value back to its name + return ts.forEachEntry(customTypeMap, function (mapValue, key) { + if (mapValue === value) { + return key; + } + }); + } + function serializeCompilerOptions(options, pathOptions) { + var result = ts.createMap(); + var optionsNameMap = getOptionNameMap().optionNameMap; + var getCanonicalFileName = pathOptions && ts.createGetCanonicalFileName(pathOptions.useCaseSensitiveFileNames); + var _loop_3 = function (name) { + if (ts.hasProperty(options, name)) { + // tsconfig only options cannot be specified via command line, + // so we can assume that only types that can appear here string | number | boolean + if (optionsNameMap.has(name) && optionsNameMap.get(name).category === ts.Diagnostics.Command_line_Options) { + return "continue"; + } + var value = options[name]; + var optionDefinition = optionsNameMap.get(name.toLowerCase()); + if (optionDefinition) { + var customTypeMap_1 = getCustomTypeMapOfCommandLineOption(optionDefinition); + if (!customTypeMap_1) { + // There is no map associated with this compiler option then use the value as-is + // This is the case if the value is expect to be string, number, boolean or list of string + if (pathOptions && optionDefinition.isFilePath) { + result.set(name, ts.getRelativePathFromFile(pathOptions.configFilePath, ts.getNormalizedAbsolutePath(value, ts.getDirectoryPath(pathOptions.configFilePath)), getCanonicalFileName)); + } + else { + result.set(name, value); + } + } + else { + if (optionDefinition.type === "list") { + result.set(name, value.map(function (element) { return getNameOfCompilerOptionValue(element, customTypeMap_1); })); // TODO: GH#18217 + } + else { + // There is a typeMap associated with this command-line option so use it to map value back to its name + result.set(name, getNameOfCompilerOptionValue(value, customTypeMap_1)); + } + } + } + } + }; + for (var name in options) { + _loop_3(name); + } + return result; + } + /** + * Generate tsconfig configuration when running command line "--init" + * @param options commandlineOptions to be generated into tsconfig.json + * @param fileNames array of filenames to be generated into tsconfig.json + */ + /* @internal */ + function generateTSConfig(options, fileNames, newLine) { + var compilerOptions = ts.extend(options, ts.defaultInitCompilerOptions); + var compilerOptionsMap = serializeCompilerOptions(compilerOptions); + return writeConfigurations(); + function getDefaultValueForOption(option) { + switch (option.type) { + case "number": + return 1; + case "boolean": + return true; + case "string": + return option.isFilePath ? "./" : ""; + case "list": + return []; + case "object": + return {}; + default: + return option.type.keys().next().value; + } + } + function makePadding(paddingLength) { + return Array(paddingLength + 1).join(" "); + } + function isAllowedOption(_a) { + var category = _a.category, name = _a.name; + // Skip options which do not have a category or have category `Command_line_Options` + // Exclude all possible `Advanced_Options` in tsconfig.json which were NOT defined in command line + return category !== undefined + && category !== ts.Diagnostics.Command_line_Options + && (category !== ts.Diagnostics.Advanced_Options || compilerOptionsMap.has(name)); + } + function writeConfigurations() { + // Filter applicable options to place in the file + var categorizedOptions = ts.createMultiMap(); + for (var _i = 0, optionDeclarations_1 = ts.optionDeclarations; _i < optionDeclarations_1.length; _i++) { + var option = optionDeclarations_1[_i]; + var category = option.category; + if (isAllowedOption(option)) { + categorizedOptions.add(ts.getLocaleSpecificMessage(category), option); + } + } + // Serialize all options and their descriptions + var marginLength = 0; + var seenKnownKeys = 0; + var nameColumn = []; + var descriptionColumn = []; + categorizedOptions.forEach(function (options, category) { + if (nameColumn.length !== 0) { + nameColumn.push(""); + descriptionColumn.push(""); + } + nameColumn.push("/* " + category + " */"); + descriptionColumn.push(""); + for (var _i = 0, options_1 = options; _i < options_1.length; _i++) { + var option = options_1[_i]; + var optionName = void 0; + if (compilerOptionsMap.has(option.name)) { + optionName = "\"" + option.name + "\": " + JSON.stringify(compilerOptionsMap.get(option.name)) + ((seenKnownKeys += 1) === compilerOptionsMap.size ? "" : ","); + } + else { + optionName = "// \"" + option.name + "\": " + JSON.stringify(getDefaultValueForOption(option)) + ","; + } + nameColumn.push(optionName); + descriptionColumn.push("/* " + (option.description && ts.getLocaleSpecificMessage(option.description) || option.name) + " */"); + marginLength = Math.max(optionName.length, marginLength); + } + }); + // Write the output + var tab = makePadding(2); + var result = []; + result.push("{"); + result.push(tab + "\"compilerOptions\": {"); + // Print out each row, aligning all the descriptions on the same column. + for (var i = 0; i < nameColumn.length; i++) { + var optionName = nameColumn[i]; + var description = descriptionColumn[i]; + result.push(optionName && "" + tab + tab + optionName + (description && (makePadding(marginLength - optionName.length + 2) + description))); + } + if (fileNames.length) { + result.push(tab + "},"); + result.push(tab + "\"files\": ["); + for (var i = 0; i < fileNames.length; i++) { + result.push("" + tab + tab + JSON.stringify(fileNames[i]) + (i === fileNames.length - 1 ? "" : ",")); + } + result.push(tab + "]"); + } + else { + result.push(tab + "}"); + } + result.push("}"); + return result.join(newLine); + } + } + ts.generateTSConfig = generateTSConfig; + /** + * Parse the contents of a config file (tsconfig.json). + * @param json The contents of the config file to parse + * @param host Instance of ParseConfigHost used to enumerate files in folder. + * @param basePath A root directory to resolve relative path entries in the config + * file to. e.g. outDir + */ + function parseJsonConfigFileContent(json, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions) { + return parseJsonConfigFileContentWorker(json, /*sourceFile*/ undefined, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions); + } + ts.parseJsonConfigFileContent = parseJsonConfigFileContent; + /** + * Parse the contents of a config file (tsconfig.json). + * @param jsonNode The contents of the config file to parse + * @param host Instance of ParseConfigHost used to enumerate files in folder. + * @param basePath A root directory to resolve relative path entries in the config + * file to. e.g. outDir + */ + function parseJsonSourceFileConfigFileContent(sourceFile, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions) { + return parseJsonConfigFileContentWorker(/*json*/ undefined, sourceFile, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions); + } + ts.parseJsonSourceFileConfigFileContent = parseJsonSourceFileConfigFileContent; + /*@internal*/ + function setConfigFileInOptions(options, configFile) { + if (configFile) { + Object.defineProperty(options, "configFile", { enumerable: false, writable: false, value: configFile }); + } + } + ts.setConfigFileInOptions = setConfigFileInOptions; + function isNullOrUndefined(x) { + // tslint:disable-next-line:no-null-keyword + return x === undefined || x === null; + } + function directoryOfCombinedPath(fileName, basePath) { + // Use the `getNormalizedAbsolutePath` function to avoid canonicalizing the path, as it must remain noncanonical + // until consistient casing errors are reported + return ts.getDirectoryPath(ts.getNormalizedAbsolutePath(fileName, basePath)); + } + /** + * Parse the contents of a config file from json or json source file (tsconfig.json). + * @param json The contents of the config file to parse + * @param sourceFile sourceFile corresponding to the Json + * @param host Instance of ParseConfigHost used to enumerate files in folder. + * @param basePath A root directory to resolve relative path entries in the config + * file to. e.g. outDir + * @param resolutionStack Only present for backwards-compatibility. Should be empty. + */ + function parseJsonConfigFileContentWorker(json, sourceFile, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions) { + if (existingOptions === void 0) { existingOptions = {}; } + if (resolutionStack === void 0) { resolutionStack = []; } + if (extraFileExtensions === void 0) { extraFileExtensions = []; } + ts.Debug.assert((json === undefined && sourceFile !== undefined) || (json !== undefined && sourceFile === undefined)); + var errors = []; + var parsedConfig = parseConfig(json, sourceFile, host, basePath, configFileName, resolutionStack, errors); + var raw = parsedConfig.raw; + var options = ts.extend(existingOptions, parsedConfig.options || {}); + options.configFilePath = configFileName && ts.normalizeSlashes(configFileName); + setConfigFileInOptions(options, sourceFile); + var projectReferences; + var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories, spec = _a.spec; + return { + options: options, + fileNames: fileNames, + projectReferences: projectReferences, + typeAcquisition: parsedConfig.typeAcquisition || getDefaultTypeAcquisition(), + raw: raw, + errors: errors, + wildcardDirectories: wildcardDirectories, + compileOnSave: !!raw.compileOnSave, + configFileSpecs: spec + }; + function getFileNames() { + var filesSpecs; + if (ts.hasProperty(raw, "files") && !isNullOrUndefined(raw.files)) { + if (ts.isArray(raw.files)) { + filesSpecs = raw.files; + var hasReferences = ts.hasProperty(raw, "references") && !isNullOrUndefined(raw.references); + var hasZeroOrNoReferences = !hasReferences || raw.references.length === 0; + var hasExtends = ts.hasProperty(raw, "extends"); + if (filesSpecs.length === 0 && hasZeroOrNoReferences && !hasExtends) { + if (sourceFile) { + var fileName = configFileName || "tsconfig.json"; + var diagnosticMessage = ts.Diagnostics.The_files_list_in_config_file_0_is_empty; + var nodeValue = ts.firstDefined(ts.getTsConfigPropArray(sourceFile, "files"), function (property) { return property.initializer; }); + var error = nodeValue + ? ts.createDiagnosticForNodeInSourceFile(sourceFile, nodeValue, diagnosticMessage, fileName) + : ts.createCompilerDiagnostic(diagnosticMessage, fileName); + errors.push(error); + } + else { + createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json"); + } + } + } + else { + createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "files", "Array"); + } + } + var includeSpecs; + if (ts.hasProperty(raw, "include") && !isNullOrUndefined(raw.include)) { + if (ts.isArray(raw.include)) { + includeSpecs = raw.include; + } + else { + createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "include", "Array"); + } + } + var excludeSpecs; + if (ts.hasProperty(raw, "exclude") && !isNullOrUndefined(raw.exclude)) { + if (ts.isArray(raw.exclude)) { + excludeSpecs = raw.exclude; + } + else { + createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "exclude", "Array"); + } + } + else if (raw.compilerOptions) { + var outDir = raw.compilerOptions.outDir; + var declarationDir = raw.compilerOptions.declarationDir; + if (outDir || declarationDir) { + excludeSpecs = [outDir, declarationDir].filter(function (d) { return !!d; }); + } + } + if (filesSpecs === undefined && includeSpecs === undefined) { + includeSpecs = ["**/*"]; + } + var result = matchFileNames(filesSpecs, includeSpecs, excludeSpecs, configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath, options, host, errors, extraFileExtensions, sourceFile); + if (shouldReportNoInputFiles(result, canJsonReportNoInutFiles(raw), resolutionStack)) { + errors.push(getErrorForNoInputFiles(result.spec, configFileName)); + } + if (ts.hasProperty(raw, "references") && !isNullOrUndefined(raw.references)) { + if (ts.isArray(raw.references)) { + for (var _i = 0, _a = raw.references; _i < _a.length; _i++) { + var ref = _a[_i]; + if (typeof ref.path !== "string") { + createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "reference.path", "string"); + } + else { + (projectReferences || (projectReferences = [])).push({ + path: ts.getNormalizedAbsolutePath(ref.path, basePath), + originalPath: ref.path, + prepend: ref.prepend, + circular: ref.circular + }); + } + } + } + else { + createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "references", "Array"); + } + } + return result; + } + function createCompilerDiagnosticOnlyIfJson(message, arg0, arg1) { + if (!sourceFile) { + errors.push(ts.createCompilerDiagnostic(message, arg0, arg1)); + } + } + } + function isErrorNoInputFiles(error) { + return error.code === ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2.code; + } + function getErrorForNoInputFiles(_a, configFileName) { + var includeSpecs = _a.includeSpecs, excludeSpecs = _a.excludeSpecs; + return ts.createCompilerDiagnostic(ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2, configFileName || "tsconfig.json", JSON.stringify(includeSpecs || []), JSON.stringify(excludeSpecs || [])); + } + function shouldReportNoInputFiles(result, canJsonReportNoInutFiles, resolutionStack) { + return result.fileNames.length === 0 && canJsonReportNoInutFiles && (!resolutionStack || resolutionStack.length === 0); + } + /*@internal*/ + function canJsonReportNoInutFiles(raw) { + return !ts.hasProperty(raw, "files") && !ts.hasProperty(raw, "references"); + } + ts.canJsonReportNoInutFiles = canJsonReportNoInutFiles; + /*@internal*/ + function updateErrorForNoInputFiles(result, configFileName, configFileSpecs, configParseDiagnostics, canJsonReportNoInutFiles) { + var existingErrors = configParseDiagnostics.length; + if (shouldReportNoInputFiles(result, canJsonReportNoInutFiles)) { + configParseDiagnostics.push(getErrorForNoInputFiles(configFileSpecs, configFileName)); + } + else { + ts.filterMutate(configParseDiagnostics, function (error) { return !isErrorNoInputFiles(error); }); + } + return existingErrors !== configParseDiagnostics.length; + } + ts.updateErrorForNoInputFiles = updateErrorForNoInputFiles; + function isSuccessfulParsedTsconfig(value) { + return !!value.options; + } + /** + * This *just* extracts options/include/exclude/files out of a config file. + * It does *not* resolve the included files. + */ + function parseConfig(json, sourceFile, host, basePath, configFileName, resolutionStack, errors) { + basePath = ts.normalizeSlashes(basePath); + var resolvedPath = ts.getNormalizedAbsolutePath(configFileName || "", basePath); + if (resolutionStack.indexOf(resolvedPath) >= 0) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Circularity_detected_while_resolving_configuration_Colon_0, resolutionStack.concat([resolvedPath]).join(" -> "))); + return { raw: json || convertToObject(sourceFile, errors) }; + } + var ownConfig = json ? + parseOwnConfigOfJson(json, host, basePath, configFileName, errors) : + parseOwnConfigOfJsonSourceFile(sourceFile, host, basePath, configFileName, errors); + if (ownConfig.extendedConfigPath) { + // copy the resolution stack so it is never reused between branches in potential diamond-problem scenarios. + resolutionStack = resolutionStack.concat([resolvedPath]); + var extendedConfig = getExtendedConfig(sourceFile, ownConfig.extendedConfigPath, host, basePath, resolutionStack, errors); + if (extendedConfig && isSuccessfulParsedTsconfig(extendedConfig)) { + var baseRaw_1 = extendedConfig.raw; + var raw_1 = ownConfig.raw; + var setPropertyInRawIfNotUndefined = function (propertyName) { + var value = raw_1[propertyName] || baseRaw_1[propertyName]; + if (value) { + raw_1[propertyName] = value; + } + }; + setPropertyInRawIfNotUndefined("include"); + setPropertyInRawIfNotUndefined("exclude"); + setPropertyInRawIfNotUndefined("files"); + if (raw_1.compileOnSave === undefined) { + raw_1.compileOnSave = baseRaw_1.compileOnSave; + } + ownConfig.options = ts.assign({}, extendedConfig.options, ownConfig.options); + // TODO extend type typeAcquisition + } + } + return ownConfig; + } + function parseOwnConfigOfJson(json, host, basePath, configFileName, errors) { + if (ts.hasProperty(json, "excludes")) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude)); + } + var options = convertCompilerOptionsFromJsonWorker(json.compilerOptions, basePath, errors, configFileName); + // typingOptions has been deprecated and is only supported for backward compatibility purposes. + // It should be removed in future releases - use typeAcquisition instead. + var typeAcquisition = convertTypeAcquisitionFromJsonWorker(json.typeAcquisition || json.typingOptions, basePath, errors, configFileName); + json.compileOnSave = convertCompileOnSaveOptionFromJson(json, basePath, errors); + var extendedConfigPath; + if (json.extends) { + if (!ts.isString(json.extends)) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "extends", "string")); + } + else { + var newBase = configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath; + extendedConfigPath = getExtendsConfigPath(json.extends, host, newBase, errors, ts.createCompilerDiagnostic); + } + } + return { raw: json, options: options, typeAcquisition: typeAcquisition, extendedConfigPath: extendedConfigPath }; + } + function parseOwnConfigOfJsonSourceFile(sourceFile, host, basePath, configFileName, errors) { + var options = getDefaultCompilerOptions(configFileName); + var typeAcquisition, typingOptionstypeAcquisition; + var extendedConfigPath; + var optionsIterator = { + onSetValidOptionKeyValueInParent: function (parentOption, option, value) { + ts.Debug.assert(parentOption === "compilerOptions" || parentOption === "typeAcquisition" || parentOption === "typingOptions"); + var currentOption = parentOption === "compilerOptions" ? + options : + parentOption === "typeAcquisition" ? + (typeAcquisition || (typeAcquisition = getDefaultTypeAcquisition(configFileName))) : + (typingOptionstypeAcquisition || (typingOptionstypeAcquisition = getDefaultTypeAcquisition(configFileName))); + currentOption[option.name] = normalizeOptionValue(option, basePath, value); + }, + onSetValidOptionKeyValueInRoot: function (key, _keyNode, value, valueNode) { + switch (key) { + case "extends": + var newBase = configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath; + extendedConfigPath = getExtendsConfigPath(value, host, newBase, errors, function (message, arg0) { + return ts.createDiagnosticForNodeInSourceFile(sourceFile, valueNode, message, arg0); + }); + return; + } + }, + onSetUnknownOptionKeyValueInRoot: function (key, keyNode, _value, _valueNode) { + if (key === "excludes") { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, keyNode, ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude)); + } + } + }; + var json = convertToObjectWorker(sourceFile, errors, /*returnValue*/ true, getTsconfigRootOptionsMap(), optionsIterator); + if (!typeAcquisition) { + if (typingOptionstypeAcquisition) { + typeAcquisition = (typingOptionstypeAcquisition.enableAutoDiscovery !== undefined) ? + { + enable: typingOptionstypeAcquisition.enableAutoDiscovery, + include: typingOptionstypeAcquisition.include, + exclude: typingOptionstypeAcquisition.exclude + } : + typingOptionstypeAcquisition; + } + else { + typeAcquisition = getDefaultTypeAcquisition(configFileName); + } + } + return { raw: json, options: options, typeAcquisition: typeAcquisition, extendedConfigPath: extendedConfigPath }; + } + function getExtendsConfigPath(extendedConfig, host, basePath, errors, createDiagnostic) { + extendedConfig = ts.normalizeSlashes(extendedConfig); + if (ts.isRootedDiskPath(extendedConfig) || ts.startsWith(extendedConfig, "./") || ts.startsWith(extendedConfig, "../")) { + var extendedConfigPath = ts.getNormalizedAbsolutePath(extendedConfig, basePath); + if (!host.fileExists(extendedConfigPath) && !ts.endsWith(extendedConfigPath, ".json" /* Json */)) { + extendedConfigPath = extendedConfigPath + ".json"; + if (!host.fileExists(extendedConfigPath)) { + errors.push(createDiagnostic(ts.Diagnostics.File_0_does_not_exist, extendedConfig)); + return undefined; + } + } + return extendedConfigPath; + } + // If the path isn't a rooted or relative path, resolve like a module + var resolved = ts.nodeModuleNameResolver(extendedConfig, ts.combinePaths(basePath, "tsconfig.json"), { moduleResolution: ts.ModuleResolutionKind.NodeJs }, host, /*cache*/ undefined, /*projectRefs*/ undefined, /*lookupConfig*/ true); + if (resolved.resolvedModule) { + return resolved.resolvedModule.resolvedFileName; + } + errors.push(createDiagnostic(ts.Diagnostics.File_0_does_not_exist, extendedConfig)); + return undefined; + } + function getExtendedConfig(sourceFile, extendedConfigPath, host, basePath, resolutionStack, errors) { + var _a; + var extendedResult = readJsonConfigFile(extendedConfigPath, function (path) { return host.readFile(path); }); + if (sourceFile) { + sourceFile.extendedSourceFiles = [extendedResult.fileName]; + } + if (extendedResult.parseDiagnostics.length) { + errors.push.apply(errors, extendedResult.parseDiagnostics); + return undefined; + } + var extendedDirname = ts.getDirectoryPath(extendedConfigPath); + var extendedConfig = parseConfig(/*json*/ undefined, extendedResult, host, extendedDirname, ts.getBaseFileName(extendedConfigPath), resolutionStack, errors); + if (sourceFile && extendedResult.extendedSourceFiles) { + (_a = sourceFile.extendedSourceFiles).push.apply(_a, extendedResult.extendedSourceFiles); + } + if (isSuccessfulParsedTsconfig(extendedConfig)) { + // Update the paths to reflect base path + var relativeDifference_1 = ts.convertToRelativePath(extendedDirname, basePath, ts.identity); + var updatePath_1 = function (path) { return ts.isRootedDiskPath(path) ? path : ts.combinePaths(relativeDifference_1, path); }; + var mapPropertiesInRawIfNotUndefined = function (propertyName) { + if (raw_2[propertyName]) { + raw_2[propertyName] = ts.map(raw_2[propertyName], updatePath_1); + } + }; + var raw_2 = extendedConfig.raw; + mapPropertiesInRawIfNotUndefined("include"); + mapPropertiesInRawIfNotUndefined("exclude"); + mapPropertiesInRawIfNotUndefined("files"); + } + return extendedConfig; + } + function convertCompileOnSaveOptionFromJson(jsonOption, basePath, errors) { + if (!ts.hasProperty(jsonOption, ts.compileOnSaveCommandLineOption.name)) { + return false; + } + var result = convertJsonOption(ts.compileOnSaveCommandLineOption, jsonOption.compileOnSave, basePath, errors); + return typeof result === "boolean" && result; + } + function convertCompilerOptionsFromJson(jsonOptions, basePath, configFileName) { + var errors = []; + var options = convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName); + return { options: options, errors: errors }; + } + ts.convertCompilerOptionsFromJson = convertCompilerOptionsFromJson; + function convertTypeAcquisitionFromJson(jsonOptions, basePath, configFileName) { + var errors = []; + var options = convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName); + return { options: options, errors: errors }; + } + ts.convertTypeAcquisitionFromJson = convertTypeAcquisitionFromJson; + function getDefaultCompilerOptions(configFileName) { + var options = configFileName && ts.getBaseFileName(configFileName) === "jsconfig.json" + ? { allowJs: true, maxNodeModuleJsDepth: 2, allowSyntheticDefaultImports: true, skipLibCheck: true, noEmit: true } + : {}; + return options; + } + function convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName) { + var options = getDefaultCompilerOptions(configFileName); + convertOptionsFromJson(ts.optionDeclarations, jsonOptions, basePath, options, ts.Diagnostics.Unknown_compiler_option_0, errors); + if (configFileName) { + options.configFilePath = ts.normalizeSlashes(configFileName); + } + return options; + } + function getDefaultTypeAcquisition(configFileName) { + return { enable: !!configFileName && ts.getBaseFileName(configFileName) === "jsconfig.json", include: [], exclude: [] }; + } + function convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName) { + var options = getDefaultTypeAcquisition(configFileName); + var typeAcquisition = convertEnableAutoDiscoveryToEnable(jsonOptions); + convertOptionsFromJson(ts.typeAcquisitionDeclarations, typeAcquisition, basePath, options, ts.Diagnostics.Unknown_type_acquisition_option_0, errors); + return options; + } + function convertOptionsFromJson(optionDeclarations, jsonOptions, basePath, defaultOptions, diagnosticMessage, errors) { + if (!jsonOptions) { + return; + } + var optionNameMap = commandLineOptionsToMap(optionDeclarations); + for (var id in jsonOptions) { + var opt = optionNameMap.get(id); + if (opt) { + defaultOptions[opt.name] = convertJsonOption(opt, jsonOptions[id], basePath, errors); + } + else { + errors.push(ts.createCompilerDiagnostic(diagnosticMessage, id)); + } + } + } + function convertJsonOption(opt, value, basePath, errors) { + if (isCompilerOptionsValue(opt, value)) { + var optType = opt.type; + if (optType === "list" && ts.isArray(value)) { + return convertJsonOptionOfListType(opt, value, basePath, errors); + } + else if (!ts.isString(optType)) { + return convertJsonOptionOfCustomType(opt, value, errors); + } + return normalizeNonListOptionValue(opt, basePath, value); + } + else { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, opt.name, getCompilerOptionValueTypeString(opt))); + } + } + function normalizeOptionValue(option, basePath, value) { + if (isNullOrUndefined(value)) + return undefined; + if (option.type === "list") { + var listOption_1 = option; + if (listOption_1.element.isFilePath || !ts.isString(listOption_1.element.type)) { + return ts.filter(ts.map(value, function (v) { return normalizeOptionValue(listOption_1.element, basePath, v); }), function (v) { return !!v; }); + } + return value; + } + else if (!ts.isString(option.type)) { + return option.type.get(ts.isString(value) ? value.toLowerCase() : value); + } + return normalizeNonListOptionValue(option, basePath, value); + } + function normalizeNonListOptionValue(option, basePath, value) { + if (option.isFilePath) { + value = ts.normalizePath(ts.combinePaths(basePath, value)); + if (value === "") { + value = "."; + } + } + return value; + } + function convertJsonOptionOfCustomType(opt, value, errors) { + if (isNullOrUndefined(value)) + return undefined; + var key = value.toLowerCase(); + var val = opt.type.get(key); + if (val !== undefined) { + return val; + } + else { + errors.push(createCompilerDiagnosticForInvalidCustomType(opt)); + } + } + function convertJsonOptionOfListType(option, values, basePath, errors) { + return ts.filter(ts.map(values, function (v) { return convertJsonOption(option.element, v, basePath, errors); }), function (v) { return !!v; }); + } + function trimString(s) { + return typeof s.trim === "function" ? s.trim() : s.replace(/^[\s]+|[\s]+$/g, ""); + } + /** + * Tests for a path that ends in a recursive directory wildcard. + * Matches **, \**, **\, and \**\, but not a**b. + * + * NOTE: used \ in place of / above to avoid issues with multiline comments. + * + * Breakdown: + * (^|\/) # matches either the beginning of the string or a directory separator. + * \*\* # matches the recursive directory wildcard "**". + * \/?$ # matches an optional trailing directory separator at the end of the string. + */ + var invalidTrailingRecursionPattern = /(^|\/)\*\*\/?$/; + /** + * Tests for a path where .. appears after a recursive directory wildcard. + * Matches **\..\*, **\a\..\*, and **\.., but not ..\**\* + * + * NOTE: used \ in place of / above to avoid issues with multiline comments. + * + * Breakdown: + * (^|\/) # matches either the beginning of the string or a directory separator. + * \*\*\/ # matches a recursive directory wildcard "**" followed by a directory separator. + * (.*\/)? # optionally matches any number of characters followed by a directory separator. + * \.\. # matches a parent directory path component ".." + * ($|\/) # matches either the end of the string or a directory separator. + */ + var invalidDotDotAfterRecursiveWildcardPattern = /(^|\/)\*\*\/(.*\/)?\.\.($|\/)/; + /** + * Tests for a path containing a wildcard character in a directory component of the path. + * Matches \*\, \?\, and \a*b\, but not \a\ or \a\*. + * + * NOTE: used \ in place of / above to avoid issues with multiline comments. + * + * Breakdown: + * \/ # matches a directory separator. + * [^/]*? # matches any number of characters excluding directory separators (non-greedy). + * [*?] # matches either a wildcard character (* or ?) + * [^/]* # matches any number of characters excluding directory separators (greedy). + * \/ # matches a directory separator. + */ + var watchRecursivePattern = /\/[^/]*?[*?][^/]*\//; + /** + * Matches the portion of a wildcard path that does not contain wildcards. + * Matches \a of \a\*, or \a\b\c of \a\b\c\?\d. + * + * NOTE: used \ in place of / above to avoid issues with multiline comments. + * + * Breakdown: + * ^ # matches the beginning of the string + * [^*?]* # matches any number of non-wildcard characters + * (?=\/[^/]*[*?]) # lookahead that matches a directory separator followed by + * # a path component that contains at least one wildcard character (* or ?). + */ + var wildcardDirectoryPattern = /^[^*?]*(?=\/[^/]*[*?])/; + /** + * Expands an array of file specifications. + * + * @param filesSpecs The literal file names to include. + * @param includeSpecs The wildcard file specifications to include. + * @param excludeSpecs The wildcard file specifications to exclude. + * @param basePath The base path for any relative file specifications. + * @param options Compiler options. + * @param host The host used to resolve files and directories. + * @param errors An array for diagnostic reporting. + */ + function matchFileNames(filesSpecs, includeSpecs, excludeSpecs, basePath, options, host, errors, extraFileExtensions, jsonSourceFile) { + basePath = ts.normalizePath(basePath); + var validatedIncludeSpecs, validatedExcludeSpecs; + // The exclude spec list is converted into a regular expression, which allows us to quickly + // test whether a file or directory should be excluded before recursively traversing the + // file system. + if (includeSpecs) { + validatedIncludeSpecs = validateSpecs(includeSpecs, errors, /*allowTrailingRecursion*/ false, jsonSourceFile, "include"); + } + if (excludeSpecs) { + validatedExcludeSpecs = validateSpecs(excludeSpecs, errors, /*allowTrailingRecursion*/ true, jsonSourceFile, "exclude"); + } + // Wildcard directories (provided as part of a wildcard path) are stored in a + // file map that marks whether it was a regular wildcard match (with a `*` or `?` token), + // or a recursive directory. This information is used by filesystem watchers to monitor for + // new entries in these paths. + var wildcardDirectories = getWildcardDirectories(validatedIncludeSpecs, validatedExcludeSpecs, basePath, host.useCaseSensitiveFileNames); + var spec = { filesSpecs: filesSpecs, includeSpecs: includeSpecs, excludeSpecs: excludeSpecs, validatedIncludeSpecs: validatedIncludeSpecs, validatedExcludeSpecs: validatedExcludeSpecs, wildcardDirectories: wildcardDirectories }; + return getFileNamesFromConfigSpecs(spec, basePath, options, host, extraFileExtensions); + } + /** + * Gets the file names from the provided config file specs that contain, files, include, exclude and + * other properties needed to resolve the file names + * @param spec The config file specs extracted with file names to include, wildcards to include/exclude and other details + * @param basePath The base path for any relative file specifications. + * @param options Compiler options. + * @param host The host used to resolve files and directories. + * @param extraFileExtensions optionaly file extra file extension information from host + */ + /* @internal */ + function getFileNamesFromConfigSpecs(spec, basePath, options, host, extraFileExtensions) { + if (extraFileExtensions === void 0) { extraFileExtensions = []; } + basePath = ts.normalizePath(basePath); + var keyMapper = host.useCaseSensitiveFileNames ? ts.identity : ts.toLowerCase; + // Literal file names (provided via the "files" array in tsconfig.json) are stored in a + // file map with a possibly case insensitive key. We use this map later when when including + // wildcard paths. + var literalFileMap = ts.createMap(); + // Wildcard paths (provided via the "includes" array in tsconfig.json) are stored in a + // file map with a possibly case insensitive key. We use this map to store paths matched + // via wildcard, and to handle extension priority. + var wildcardFileMap = ts.createMap(); + // Wildcard paths of json files (provided via the "includes" array in tsconfig.json) are stored in a + // file map with a possibly case insensitive key. We use this map to store paths matched + // via wildcard of *.json kind + var wildCardJsonFileMap = ts.createMap(); + var filesSpecs = spec.filesSpecs, validatedIncludeSpecs = spec.validatedIncludeSpecs, validatedExcludeSpecs = spec.validatedExcludeSpecs, wildcardDirectories = spec.wildcardDirectories; + // Rather than requery this for each file and filespec, we query the supported extensions + // once and store it on the expansion context. + var supportedExtensions = ts.getSupportedExtensions(options, extraFileExtensions); + var supportedExtensionsWithJsonIfResolveJsonModule = ts.getSuppoertedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions); + // Literal files are always included verbatim. An "include" or "exclude" specification cannot + // remove a literal file. + if (filesSpecs) { + for (var _i = 0, filesSpecs_1 = filesSpecs; _i < filesSpecs_1.length; _i++) { + var fileName = filesSpecs_1[_i]; + var file = ts.getNormalizedAbsolutePath(fileName, basePath); + literalFileMap.set(keyMapper(file), file); + } + } + var jsonOnlyIncludeRegexes; + if (validatedIncludeSpecs && validatedIncludeSpecs.length > 0) { + var _loop_4 = function (file) { + if (ts.fileExtensionIs(file, ".json" /* Json */)) { + // Valid only if *.json specified + if (!jsonOnlyIncludeRegexes) { + var includes = validatedIncludeSpecs.filter(function (s) { return ts.endsWith(s, ".json" /* Json */); }); + var includeFilePatterns = ts.map(ts.getRegularExpressionsForWildcards(includes, basePath, "files"), function (pattern) { return "^" + pattern + "$"; }); + jsonOnlyIncludeRegexes = includeFilePatterns ? includeFilePatterns.map(function (pattern) { return ts.getRegexFromPattern(pattern, host.useCaseSensitiveFileNames); }) : ts.emptyArray; + } + var includeIndex = ts.findIndex(jsonOnlyIncludeRegexes, function (re) { return re.test(file); }); + if (includeIndex !== -1) { + var key_1 = keyMapper(file); + if (!literalFileMap.has(key_1) && !wildCardJsonFileMap.has(key_1)) { + wildCardJsonFileMap.set(key_1, file); + } + } + return "continue"; + } + // If we have already included a literal or wildcard path with a + // higher priority extension, we should skip this file. + // + // This handles cases where we may encounter both .ts and + // .d.ts (or .js if "allowJs" is enabled) in the same + // directory when they are compilation outputs. + if (hasFileWithHigherPriorityExtension(file, literalFileMap, wildcardFileMap, supportedExtensions, keyMapper)) { + return "continue"; + } + // We may have included a wildcard path with a lower priority + // extension due to the user-defined order of entries in the + // "include" array. If there is a lower priority extension in the + // same directory, we should remove it. + removeWildcardFilesWithLowerPriorityExtension(file, wildcardFileMap, supportedExtensions, keyMapper); + var key = keyMapper(file); + if (!literalFileMap.has(key) && !wildcardFileMap.has(key)) { + wildcardFileMap.set(key, file); + } + }; + for (var _a = 0, _b = host.readDirectory(basePath, supportedExtensionsWithJsonIfResolveJsonModule, validatedExcludeSpecs, validatedIncludeSpecs, /*depth*/ undefined); _a < _b.length; _a++) { + var file = _b[_a]; + _loop_4(file); + } + } + var literalFiles = ts.arrayFrom(literalFileMap.values()); + var wildcardFiles = ts.arrayFrom(wildcardFileMap.values()); + return { + fileNames: literalFiles.concat(wildcardFiles, ts.arrayFrom(wildCardJsonFileMap.values())), + wildcardDirectories: wildcardDirectories, + spec: spec + }; + } + ts.getFileNamesFromConfigSpecs = getFileNamesFromConfigSpecs; + function validateSpecs(specs, errors, allowTrailingRecursion, jsonSourceFile, specKey) { + return specs.filter(function (spec) { + var diag = specToDiagnostic(spec, allowTrailingRecursion); + if (diag !== undefined) { + errors.push(createDiagnostic(diag, spec)); + } + return diag === undefined; + }); + function createDiagnostic(message, spec) { + var element = ts.getTsConfigPropArrayElementValue(jsonSourceFile, specKey, spec); + return element ? + ts.createDiagnosticForNodeInSourceFile(jsonSourceFile, element, message, spec) : + ts.createCompilerDiagnostic(message, spec); + } + } + function specToDiagnostic(spec, allowTrailingRecursion) { + if (!allowTrailingRecursion && invalidTrailingRecursionPattern.test(spec)) { + return ts.Diagnostics.File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0; + } + else if (invalidDotDotAfterRecursiveWildcardPattern.test(spec)) { + return ts.Diagnostics.File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0; + } + } + /** + * Gets directories in a set of include patterns that should be watched for changes. + */ + function getWildcardDirectories(include, exclude, path, useCaseSensitiveFileNames) { + // We watch a directory recursively if it contains a wildcard anywhere in a directory segment + // of the pattern: + // + // /a/b/**/d - Watch /a/b recursively to catch changes to any d in any subfolder recursively + // /a/b/*/d - Watch /a/b recursively to catch any d in any immediate subfolder, even if a new subfolder is added + // /a/b - Watch /a/b recursively to catch changes to anything in any recursive subfoler + // + // We watch a directory without recursion if it contains a wildcard in the file segment of + // the pattern: + // + // /a/b/* - Watch /a/b directly to catch any new file + // /a/b/a?z - Watch /a/b directly to catch any new file matching a?z + var rawExcludeRegex = ts.getRegularExpressionForWildcard(exclude, path, "exclude"); + var excludeRegex = rawExcludeRegex && new RegExp(rawExcludeRegex, useCaseSensitiveFileNames ? "" : "i"); + var wildcardDirectories = {}; + if (include !== undefined) { + var recursiveKeys = []; + for (var _i = 0, include_1 = include; _i < include_1.length; _i++) { + var file = include_1[_i]; + var spec = ts.normalizePath(ts.combinePaths(path, file)); + if (excludeRegex && excludeRegex.test(spec)) { + continue; + } + var match = getWildcardDirectoryFromSpec(spec, useCaseSensitiveFileNames); + if (match) { + var key = match.key, flags = match.flags; + var existingFlags = wildcardDirectories[key]; + if (existingFlags === undefined || existingFlags < flags) { + wildcardDirectories[key] = flags; + if (flags === 1 /* Recursive */) { + recursiveKeys.push(key); + } + } + } + } + // Remove any subpaths under an existing recursively watched directory. + for (var key in wildcardDirectories) { + if (ts.hasProperty(wildcardDirectories, key)) { + for (var _a = 0, recursiveKeys_1 = recursiveKeys; _a < recursiveKeys_1.length; _a++) { + var recursiveKey = recursiveKeys_1[_a]; + if (key !== recursiveKey && ts.containsPath(recursiveKey, key, path, !useCaseSensitiveFileNames)) { + delete wildcardDirectories[key]; + } + } + } + } + } + return wildcardDirectories; + } + function getWildcardDirectoryFromSpec(spec, useCaseSensitiveFileNames) { + var match = wildcardDirectoryPattern.exec(spec); + if (match) { + return { + key: useCaseSensitiveFileNames ? match[0] : match[0].toLowerCase(), + flags: watchRecursivePattern.test(spec) ? 1 /* Recursive */ : 0 /* None */ + }; + } + if (ts.isImplicitGlob(spec)) { + return { key: spec, flags: 1 /* Recursive */ }; + } + return undefined; + } + /** + * Determines whether a literal or wildcard file has already been included that has a higher + * extension priority. + * + * @param file The path to the file. + * @param extensionPriority The priority of the extension. + * @param context The expansion context. + */ + function hasFileWithHigherPriorityExtension(file, literalFiles, wildcardFiles, extensions, keyMapper) { + var extensionPriority = ts.getExtensionPriority(file, extensions); + var adjustedExtensionPriority = ts.adjustExtensionPriority(extensionPriority, extensions); + for (var i = 0 /* Highest */; i < adjustedExtensionPriority; i++) { + var higherPriorityExtension = extensions[i]; + var higherPriorityPath = keyMapper(ts.changeExtension(file, higherPriorityExtension)); + if (literalFiles.has(higherPriorityPath) || wildcardFiles.has(higherPriorityPath)) { + return true; + } + } + return false; + } + /** + * Removes files included via wildcard expansion with a lower extension priority that have + * already been included. + * + * @param file The path to the file. + * @param extensionPriority The priority of the extension. + * @param context The expansion context. + */ + function removeWildcardFilesWithLowerPriorityExtension(file, wildcardFiles, extensions, keyMapper) { + var extensionPriority = ts.getExtensionPriority(file, extensions); + var nextExtensionPriority = ts.getNextLowestExtensionPriority(extensionPriority, extensions); + for (var i = nextExtensionPriority; i < extensions.length; i++) { + var lowerPriorityExtension = extensions[i]; + var lowerPriorityPath = keyMapper(ts.changeExtension(file, lowerPriorityExtension)); + wildcardFiles.delete(lowerPriorityPath); + } + } + /** + * Produces a cleaned version of compiler options with personally identifying info (aka, paths) removed. + * Also converts enum values back to strings. + */ + /* @internal */ + function convertCompilerOptionsForTelemetry(opts) { + var out = {}; + for (var key in opts) { + if (opts.hasOwnProperty(key)) { + var type = getOptionFromName(key); + if (type !== undefined) { // Ignore unknown options + out[key] = getOptionValueWithEmptyStrings(opts[key], type); + } + } + } + return out; + } + ts.convertCompilerOptionsForTelemetry = convertCompilerOptionsForTelemetry; + function getOptionValueWithEmptyStrings(value, option) { + switch (option.type) { + case "object": // "paths". Can't get any useful information from the value since we blank out strings, so just return "". + return ""; + case "string": // Could be any arbitrary string -- use empty string instead. + return ""; + case "number": // Allow numbers, but be sure to check it's actually a number. + return typeof value === "number" ? value : ""; + case "boolean": + return typeof value === "boolean" ? value : ""; + case "list": + var elementType_1 = option.element; + return ts.isArray(value) ? value.map(function (v) { return getOptionValueWithEmptyStrings(v, elementType_1); }) : ""; + default: + return ts.forEachEntry(option.type, function (optionEnumValue, optionStringValue) { + if (optionEnumValue === value) { + return optionStringValue; + } + }); // TODO: GH#18217 + } + } +})(ts || (ts = {})); +var ts; +(function (ts) { + function trace(host) { + host.trace(ts.formatMessage.apply(undefined, arguments)); + } + ts.trace = trace; + /* @internal */ + function isTraceEnabled(compilerOptions, host) { + return !!compilerOptions.traceResolution && host.trace !== undefined; + } + ts.isTraceEnabled = isTraceEnabled; + function withPackageId(packageId, r) { + return r && { path: r.path, extension: r.ext, packageId: packageId }; + } + function noPackageId(r) { + return withPackageId(/*packageId*/ undefined, r); + } + function removeIgnoredPackageId(r) { + if (r) { + ts.Debug.assert(r.packageId === undefined); + return { path: r.path, ext: r.extension }; + } + } + /** + * Kinds of file that we are currently looking for. + * Typically there is one pass with Extensions.TypeScript, then a second pass with Extensions.JavaScript. + */ + var Extensions; + (function (Extensions) { + Extensions[Extensions["TypeScript"] = 0] = "TypeScript"; + Extensions[Extensions["JavaScript"] = 1] = "JavaScript"; + Extensions[Extensions["Json"] = 2] = "Json"; + Extensions[Extensions["TSConfig"] = 3] = "TSConfig"; + Extensions[Extensions["DtsOnly"] = 4] = "DtsOnly"; /** Only '.d.ts' */ + })(Extensions || (Extensions = {})); + /** Used with `Extensions.DtsOnly` to extract the path from TypeScript results. */ + function resolvedTypeScriptOnly(resolved) { + if (!resolved) { + return undefined; + } + ts.Debug.assert(ts.extensionIsTS(resolved.extension)); + return { fileName: resolved.path, packageId: resolved.packageId }; + } + function createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations) { + return { + resolvedModule: resolved && { resolvedFileName: resolved.path, originalPath: resolved.originalPath === true ? undefined : resolved.originalPath, extension: resolved.extension, isExternalLibraryImport: isExternalLibraryImport, packageId: resolved.packageId }, + failedLookupLocations: failedLookupLocations + }; + } + function readPackageJsonField(jsonContent, fieldName, typeOfTag, state) { + if (!ts.hasProperty(jsonContent, fieldName)) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_does_not_have_a_0_field, fieldName); + } + return; + } + var value = jsonContent[fieldName]; + if (typeof value !== typeOfTag || value === null) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_1_got_2, fieldName, typeOfTag, value === null ? "null" : typeof value); + } + return; + } + return value; + } + function readPackageJsonPathField(jsonContent, fieldName, baseDirectory, state) { + var fileName = readPackageJsonField(jsonContent, fieldName, "string", state); + if (fileName === undefined) + return; + var path = ts.normalizePath(ts.combinePaths(baseDirectory, fileName)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, fileName, path); + } + return path; + } + function readPackageJsonTypesFields(jsonContent, baseDirectory, state) { + return readPackageJsonPathField(jsonContent, "typings", baseDirectory, state) + || readPackageJsonPathField(jsonContent, "types", baseDirectory, state); + } + function readPackageJsonTSConfigField(jsonContent, baseDirectory, state) { + return readPackageJsonPathField(jsonContent, "tsconfig", baseDirectory, state); + } + function readPackageJsonMainField(jsonContent, baseDirectory, state) { + return readPackageJsonPathField(jsonContent, "main", baseDirectory, state); + } + function readPackageJsonTypesVersionsField(jsonContent, state) { + var typesVersions = readPackageJsonField(jsonContent, "typesVersions", "object", state); + if (typesVersions === undefined) + return; + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_field_with_version_specific_path_mappings); + } + return typesVersions; + } + function readPackageJsonTypesVersionPaths(jsonContent, state) { + var typesVersions = readPackageJsonTypesVersionsField(jsonContent, state); + if (typesVersions === undefined) + return; + if (state.traceEnabled) { + for (var key in typesVersions) { + if (ts.hasProperty(typesVersions, key) && !ts.VersionRange.tryParse(key)) { + trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range, key); + } + } + } + var result = getPackageJsonTypesVersionsPaths(typesVersions); + if (!result) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_does_not_have_a_typesVersions_entry_that_matches_version_0, ts.versionMajorMinor); + } + return; + } + var bestVersionKey = result.version, bestVersionPaths = result.paths; + if (typeof bestVersionPaths !== "object") { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_1_got_2, "typesVersions['" + bestVersionKey + "']", "object", typeof bestVersionPaths); + } + return; + } + return result; + } + var typeScriptVersion; + /* @internal */ + function getPackageJsonTypesVersionsPaths(typesVersions) { + if (!typeScriptVersion) + typeScriptVersion = new ts.Version(ts.version); + for (var key in typesVersions) { + if (!ts.hasProperty(typesVersions, key)) + continue; + var keyRange = ts.VersionRange.tryParse(key); + if (keyRange === undefined) { + continue; + } + // return the first entry whose range matches the current compiler version. + if (keyRange.test(typeScriptVersion)) { + return { version: key, paths: typesVersions[key] }; + } + } + } + ts.getPackageJsonTypesVersionsPaths = getPackageJsonTypesVersionsPaths; + function getEffectiveTypeRoots(options, host) { + if (options.typeRoots) { + return options.typeRoots; + } + var currentDirectory; + if (options.configFilePath) { + currentDirectory = ts.getDirectoryPath(options.configFilePath); + } + else if (host.getCurrentDirectory) { + currentDirectory = host.getCurrentDirectory(); + } + if (currentDirectory !== undefined) { + return getDefaultTypeRoots(currentDirectory, host); + } + } + ts.getEffectiveTypeRoots = getEffectiveTypeRoots; + /** + * Returns the path to every node_modules/@types directory from some ancestor directory. + * Returns undefined if there are none. + */ + function getDefaultTypeRoots(currentDirectory, host) { + if (!host.directoryExists) { + return [ts.combinePaths(currentDirectory, nodeModulesAtTypes)]; + // And if it doesn't exist, tough. + } + var typeRoots; + ts.forEachAncestorDirectory(ts.normalizePath(currentDirectory), function (directory) { + var atTypes = ts.combinePaths(directory, nodeModulesAtTypes); + if (host.directoryExists(atTypes)) { + (typeRoots || (typeRoots = [])).push(atTypes); + } + return undefined; + }); + return typeRoots; + } + var nodeModulesAtTypes = ts.combinePaths("node_modules", "@types"); + /** + * @param {string | undefined} containingFile - file that contains type reference directive, can be undefined if containing file is unknown. + * This is possible in case if resolution is performed for directives specified via 'types' parameter. In this case initial path for secondary lookups + * is assumed to be the same as root directory of the project. + */ + function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host, redirectedReference) { + var traceEnabled = isTraceEnabled(options, host); + if (redirectedReference) { + options = redirectedReference.commandLine.options; + } + var failedLookupLocations = []; + var moduleResolutionState = { compilerOptions: options, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; + var typeRoots = getEffectiveTypeRoots(options, host); + if (traceEnabled) { + if (containingFile === undefined) { + if (typeRoots === undefined) { + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set, typeReferenceDirectiveName); + } + else { + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1, typeReferenceDirectiveName, typeRoots); + } + } + else { + if (typeRoots === undefined) { + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set, typeReferenceDirectiveName, containingFile); + } + else { + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_2, typeReferenceDirectiveName, containingFile, typeRoots); + } + } + if (redirectedReference) { + trace(host, ts.Diagnostics.Using_compiler_options_of_project_reference_redirect_0, redirectedReference.sourceFile.fileName); + } + } + var resolved = primaryLookup(); + var primary = true; + if (!resolved) { + resolved = secondaryLookup(); + primary = false; + } + var resolvedTypeReferenceDirective; + if (resolved) { + var fileName = resolved.fileName, packageId = resolved.packageId; + var resolvedFileName = options.preserveSymlinks ? fileName : realPath(fileName, host, traceEnabled); + if (traceEnabled) { + trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFileName, primary); + } + resolvedTypeReferenceDirective = { primary: primary, resolvedFileName: resolvedFileName, packageId: packageId, isExternalLibraryImport: pathContainsNodeModules(fileName) }; + } + return { resolvedTypeReferenceDirective: resolvedTypeReferenceDirective, failedLookupLocations: failedLookupLocations }; + function primaryLookup() { + // Check primary library paths + if (typeRoots && typeRoots.length) { + if (traceEnabled) { + trace(host, ts.Diagnostics.Resolving_with_primary_search_path_0, typeRoots.join(", ")); + } + return ts.firstDefined(typeRoots, function (typeRoot) { + var candidate = ts.combinePaths(typeRoot, typeReferenceDirectiveName); + var candidateDirectory = ts.getDirectoryPath(candidate); + var directoryExists = ts.directoryProbablyExists(candidateDirectory, host); + if (!directoryExists && traceEnabled) { + trace(host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, candidateDirectory); + } + return resolvedTypeScriptOnly(loadNodeModuleFromDirectory(Extensions.DtsOnly, candidate, !directoryExists, moduleResolutionState)); + }); + } + else { + if (traceEnabled) { + trace(host, ts.Diagnostics.Root_directory_cannot_be_determined_skipping_primary_search_paths); + } + } + } + function secondaryLookup() { + var initialLocationForSecondaryLookup = containingFile && ts.getDirectoryPath(containingFile); + if (initialLocationForSecondaryLookup !== undefined) { + // check secondary locations + if (traceEnabled) { + trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup); + } + var result = void 0; + if (!ts.isExternalModuleNameRelative(typeReferenceDirectiveName)) { + var searchResult = loadModuleFromNearestNodeModulesDirectory(Extensions.DtsOnly, typeReferenceDirectiveName, initialLocationForSecondaryLookup, moduleResolutionState, /*cache*/ undefined, /*redirectedReference*/ undefined); + result = searchResult && searchResult.value; + } + else { + var candidate = ts.normalizePathAndParts(ts.combinePaths(initialLocationForSecondaryLookup, typeReferenceDirectiveName)).path; + result = nodeLoadModuleByRelativeName(Extensions.DtsOnly, candidate, /*onlyRecordFailures*/ false, moduleResolutionState, /*considerPackageJson*/ true); + } + var resolvedFile = resolvedTypeScriptOnly(result); + if (!resolvedFile && traceEnabled) { + trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName); + } + return resolvedFile; + } + else { + if (traceEnabled) { + trace(host, ts.Diagnostics.Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder); + } + } + } + } + ts.resolveTypeReferenceDirective = resolveTypeReferenceDirective; + /** + * Given a set of options, returns the set of type directive names + * that should be included for this program automatically. + * This list could either come from the config file, + * or from enumerating the types root + initial secondary types lookup location. + * More type directives might appear in the program later as a result of loading actual source files; + * this list is only the set of defaults that are implicitly included. + */ + function getAutomaticTypeDirectiveNames(options, host) { + // Use explicit type list from tsconfig.json + if (options.types) { + return options.types; + } + // Walk the primary type lookup locations + var result = []; + if (host.directoryExists && host.getDirectories) { + var typeRoots = getEffectiveTypeRoots(options, host); + if (typeRoots) { + for (var _i = 0, typeRoots_1 = typeRoots; _i < typeRoots_1.length; _i++) { + var root = typeRoots_1[_i]; + if (host.directoryExists(root)) { + for (var _a = 0, _b = host.getDirectories(root); _a < _b.length; _a++) { + var typeDirectivePath = _b[_a]; + var normalized = ts.normalizePath(typeDirectivePath); + var packageJsonPath = ts.combinePaths(root, normalized, "package.json"); + // `types-publisher` sometimes creates packages with `"typings": null` for packages that don't provide their own types. + // See `createNotNeededPackageJSON` in the types-publisher` repo. + // tslint:disable-next-line:no-null-keyword + var isNotNeededPackage = host.fileExists(packageJsonPath) && ts.readJson(packageJsonPath, host).typings === null; + if (!isNotNeededPackage) { + var baseFileName = ts.getBaseFileName(normalized); + // At this stage, skip results with leading dot. + if (baseFileName.charCodeAt(0) !== 46 /* dot */) { + // Return just the type directive names + result.push(baseFileName); + } + } + } + } + } + } + } + return result; + } + ts.getAutomaticTypeDirectiveNames = getAutomaticTypeDirectiveNames; + function createModuleResolutionCache(currentDirectory, getCanonicalFileName) { + return createModuleResolutionCacheWithMaps(createCacheWithRedirects(), createCacheWithRedirects(), currentDirectory, getCanonicalFileName); + } + ts.createModuleResolutionCache = createModuleResolutionCache; + /*@internal*/ + function createCacheWithRedirects() { + var ownMap = ts.createMap(); + var redirectsMap = ts.createMap(); + return { + ownMap: ownMap, + redirectsMap: redirectsMap, + getOrCreateMapOfCacheRedirects: getOrCreateMapOfCacheRedirects, + clear: clear + }; + function getOrCreateMapOfCacheRedirects(redirectedReference) { + if (!redirectedReference) { + return ownMap; + } + var path = redirectedReference.sourceFile.path; + var redirects = redirectsMap.get(path); + if (!redirects) { + redirects = ts.createMap(); + redirectsMap.set(path, redirects); + } + return redirects; + } + function clear() { + ownMap.clear(); + redirectsMap.clear(); + } + } + ts.createCacheWithRedirects = createCacheWithRedirects; + /*@internal*/ + function createModuleResolutionCacheWithMaps(directoryToModuleNameMap, moduleNameToDirectoryMap, currentDirectory, getCanonicalFileName) { + return { getOrCreateCacheForDirectory: getOrCreateCacheForDirectory, getOrCreateCacheForModuleName: getOrCreateCacheForModuleName }; + function getOrCreateCacheForDirectory(directoryName, redirectedReference) { + var path = ts.toPath(directoryName, currentDirectory, getCanonicalFileName); + return getOrCreateCache(directoryToModuleNameMap, redirectedReference, path, ts.createMap); + } + function getOrCreateCacheForModuleName(nonRelativeModuleName, redirectedReference) { + ts.Debug.assert(!ts.isExternalModuleNameRelative(nonRelativeModuleName)); + return getOrCreateCache(moduleNameToDirectoryMap, redirectedReference, nonRelativeModuleName, createPerModuleNameCache); + } + function getOrCreateCache(cacheWithRedirects, redirectedReference, key, create) { + var cache = cacheWithRedirects.getOrCreateMapOfCacheRedirects(redirectedReference); + var result = cache.get(key); + if (!result) { + result = create(); + cache.set(key, result); + } + return result; + } + function createPerModuleNameCache() { + var directoryPathMap = ts.createMap(); + return { get: get, set: set }; + function get(directory) { + return directoryPathMap.get(ts.toPath(directory, currentDirectory, getCanonicalFileName)); + } + /** + * At first this function add entry directory -> module resolution result to the table. + * Then it computes the set of parent folders for 'directory' that should have the same module resolution result + * and for every parent folder in set it adds entry: parent -> module resolution. . + * Lets say we first directory name: /a/b/c/d/e and resolution result is: /a/b/bar.ts. + * Set of parent folders that should have the same result will be: + * [ + * /a/b/c/d, /a/b/c, /a/b + * ] + * this means that request for module resolution from file in any of these folder will be immediately found in cache. + */ + function set(directory, result) { + var path = ts.toPath(directory, currentDirectory, getCanonicalFileName); + // if entry is already in cache do nothing + if (directoryPathMap.has(path)) { + return; + } + directoryPathMap.set(path, result); + var resolvedFileName = result.resolvedModule && + (result.resolvedModule.originalPath || result.resolvedModule.resolvedFileName); + // find common prefix between directory and resolved file name + // this common prefix should be the shortest path that has the same resolution + // directory: /a/b/c/d/e + // resolvedFileName: /a/b/foo.d.ts + // commonPrefix: /a/b + // for failed lookups cache the result for every directory up to root + var commonPrefix = resolvedFileName && getCommonPrefix(path, resolvedFileName); + var current = path; + while (current !== commonPrefix) { + var parent = ts.getDirectoryPath(current); + if (parent === current || directoryPathMap.has(parent)) { + break; + } + directoryPathMap.set(parent, result); + current = parent; + } + } + function getCommonPrefix(directory, resolution) { + var resolutionDirectory = ts.toPath(ts.getDirectoryPath(resolution), currentDirectory, getCanonicalFileName); + // find first position where directory and resolution differs + var i = 0; + var limit = Math.min(directory.length, resolutionDirectory.length); + while (i < limit && directory.charCodeAt(i) === resolutionDirectory.charCodeAt(i)) { + i++; + } + if (i === directory.length && (resolutionDirectory.length === i || resolutionDirectory[i] === ts.directorySeparator)) { + return directory; + } + var rootLength = ts.getRootLength(directory); + if (i < rootLength) { + return undefined; + } + var sep = directory.lastIndexOf(ts.directorySeparator, i - 1); + if (sep === -1) { + return undefined; + } + return directory.substr(0, Math.max(sep, rootLength)); + } + } + } + ts.createModuleResolutionCacheWithMaps = createModuleResolutionCacheWithMaps; + function resolveModuleNameFromCache(moduleName, containingFile, cache) { + var containingDirectory = ts.getDirectoryPath(containingFile); + var perFolderCache = cache && cache.getOrCreateCacheForDirectory(containingDirectory); + return perFolderCache && perFolderCache.get(moduleName); + } + ts.resolveModuleNameFromCache = resolveModuleNameFromCache; + function resolveModuleName(moduleName, containingFile, compilerOptions, host, cache, redirectedReference) { + var traceEnabled = isTraceEnabled(compilerOptions, host); + if (redirectedReference) { + compilerOptions = redirectedReference.commandLine.options; + } + if (traceEnabled) { + trace(host, ts.Diagnostics.Resolving_module_0_from_1, moduleName, containingFile); + if (redirectedReference) { + trace(host, ts.Diagnostics.Using_compiler_options_of_project_reference_redirect_0, redirectedReference.sourceFile.fileName); + } + } + var containingDirectory = ts.getDirectoryPath(containingFile); + var perFolderCache = cache && cache.getOrCreateCacheForDirectory(containingDirectory, redirectedReference); + var result = perFolderCache && perFolderCache.get(moduleName); + if (result) { + if (traceEnabled) { + trace(host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory); + } + } + else { + var moduleResolution = compilerOptions.moduleResolution; + if (moduleResolution === undefined) { + moduleResolution = ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS ? ts.ModuleResolutionKind.NodeJs : ts.ModuleResolutionKind.Classic; + if (traceEnabled) { + trace(host, ts.Diagnostics.Module_resolution_kind_is_not_specified_using_0, ts.ModuleResolutionKind[moduleResolution]); + } + } + else { + if (traceEnabled) { + trace(host, ts.Diagnostics.Explicitly_specified_module_resolution_kind_Colon_0, ts.ModuleResolutionKind[moduleResolution]); + } + } + switch (moduleResolution) { + case ts.ModuleResolutionKind.NodeJs: + result = nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference); + break; + case ts.ModuleResolutionKind.Classic: + result = classicNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference); + break; + default: + return ts.Debug.fail("Unexpected moduleResolution: " + moduleResolution); + } + if (perFolderCache) { + perFolderCache.set(moduleName, result); + if (!ts.isExternalModuleNameRelative(moduleName)) { + // put result in per-module name cache + cache.getOrCreateCacheForModuleName(moduleName, redirectedReference).set(containingDirectory, result); + } + } + } + if (traceEnabled) { + if (result.resolvedModule) { + trace(host, ts.Diagnostics.Module_name_0_was_successfully_resolved_to_1, moduleName, result.resolvedModule.resolvedFileName); + } + else { + trace(host, ts.Diagnostics.Module_name_0_was_not_resolved, moduleName); + } + } + return result; + } + ts.resolveModuleName = resolveModuleName; + /** + * Any module resolution kind can be augmented with optional settings: 'baseUrl', 'paths' and 'rootDirs' - they are used to + * mitigate differences between design time structure of the project and its runtime counterpart so the same import name + * can be resolved successfully by TypeScript compiler and runtime module loader. + * If these settings are set then loading procedure will try to use them to resolve module name and it can of failure it will + * fallback to standard resolution routine. + * + * - baseUrl - this setting controls how non-relative module names are resolved. If this setting is specified then non-relative + * names will be resolved relative to baseUrl: i.e. if baseUrl is '/a/b' then candidate location to resolve module name 'c/d' will + * be '/a/b/c/d' + * - paths - this setting can only be used when baseUrl is specified. allows to tune how non-relative module names + * will be resolved based on the content of the module name. + * Structure of 'paths' compiler options + * 'paths': { + * pattern-1: [...substitutions], + * pattern-2: [...substitutions], + * ... + * pattern-n: [...substitutions] + * } + * Pattern here is a string that can contain zero or one '*' character. During module resolution module name will be matched against + * all patterns in the list. Matching for patterns that don't contain '*' means that module name must be equal to pattern respecting the case. + * If pattern contains '*' then to match pattern "*" module name must start with the and end with . + * denotes part of the module name between and . + * If module name can be matches with multiple patterns then pattern with the longest prefix will be picked. + * After selecting pattern we'll use list of substitutions to get candidate locations of the module and the try to load module + * from the candidate location. + * Substitution is a string that can contain zero or one '*'. To get candidate location from substitution we'll pick every + * substitution in the list and replace '*' with string. If candidate location is not rooted it + * will be converted to absolute using baseUrl. + * For example: + * baseUrl: /a/b/c + * "paths": { + * // match all module names + * "*": [ + * "*", // use matched name as is, + * // will be looked as /a/b/c/ + * + * "folder1/*" // substitution will convert matched name to 'folder1/', + * // since it is not rooted then final candidate location will be /a/b/c/folder1/ + * ], + * // match module names that start with 'components/' + * "components/*": [ "/root/components/*" ] // substitution will convert /components/folder1/ to '/root/components/folder1/', + * // it is rooted so it will be final candidate location + * } + * + * 'rootDirs' allows the project to be spreaded across multiple locations and resolve modules with relative names as if + * they were in the same location. For example lets say there are two files + * '/local/src/content/file1.ts' + * '/shared/components/contracts/src/content/protocols/file2.ts' + * After bundling content of '/shared/components/contracts/src' will be merged with '/local/src' so + * if file1 has the following import 'import {x} from "./protocols/file2"' it will be resolved successfully in runtime. + * 'rootDirs' provides the way to tell compiler that in order to get the whole project it should behave as if content of all + * root dirs were merged together. + * I.e. for the example above 'rootDirs' will have two entries: [ '/local/src', '/shared/components/contracts/src' ]. + * Compiler will first convert './protocols/file2' into absolute path relative to the location of containing file: + * '/local/src/content/protocols/file2' and try to load it - failure. + * Then it will search 'rootDirs' looking for a longest matching prefix of this absolute path and if such prefix is found - absolute path will + * be converted to a path relative to found rootDir entry './content/protocols/file2' (*). As a last step compiler will check all remaining + * entries in 'rootDirs', use them to build absolute path out of (*) and try to resolve module from this location. + */ + function tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, state) { + var resolved = tryLoadModuleUsingPathsIfEligible(extensions, moduleName, loader, state); + if (resolved) + return resolved.value; + if (!ts.isExternalModuleNameRelative(moduleName)) { + return tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, state); + } + else { + return tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, state); + } + } + function tryLoadModuleUsingPathsIfEligible(extensions, moduleName, loader, state) { + var _a = state.compilerOptions, baseUrl = _a.baseUrl, paths = _a.paths; + if (baseUrl && paths && !ts.pathIsRelative(moduleName)) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, baseUrl, moduleName); + trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName); + } + return tryLoadModuleUsingPaths(extensions, moduleName, baseUrl, paths, loader, /*onlyRecordFailures*/ false, state); + } + } + function tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, state) { + if (!state.compilerOptions.rootDirs) { + return undefined; + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0, moduleName); + } + var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); + var matchedRootDir; + var matchedNormalizedPrefix; + for (var _i = 0, _a = state.compilerOptions.rootDirs; _i < _a.length; _i++) { + var rootDir = _a[_i]; + // rootDirs are expected to be absolute + // in case of tsconfig.json this will happen automatically - compiler will expand relative names + // using location of tsconfig.json as base location + var normalizedRoot = ts.normalizePath(rootDir); + if (!ts.endsWith(normalizedRoot, ts.directorySeparator)) { + normalizedRoot += ts.directorySeparator; + } + var isLongestMatchingPrefix = ts.startsWith(candidate, normalizedRoot) && + (matchedNormalizedPrefix === undefined || matchedNormalizedPrefix.length < normalizedRoot.length); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Checking_if_0_is_the_longest_matching_prefix_for_1_2, normalizedRoot, candidate, isLongestMatchingPrefix); + } + if (isLongestMatchingPrefix) { + matchedNormalizedPrefix = normalizedRoot; + matchedRootDir = rootDir; + } + } + if (matchedNormalizedPrefix) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Longest_matching_prefix_for_0_is_1, candidate, matchedNormalizedPrefix); + } + var suffix = candidate.substr(matchedNormalizedPrefix.length); + // first - try to load from a initial location + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, matchedNormalizedPrefix, candidate); + } + var resolvedFileName = loader(extensions, candidate, !ts.directoryProbablyExists(containingDirectory, state.host), state); + if (resolvedFileName) { + return resolvedFileName; + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Trying_other_entries_in_rootDirs); + } + // then try to resolve using remaining entries in rootDirs + for (var _b = 0, _c = state.compilerOptions.rootDirs; _b < _c.length; _b++) { + var rootDir = _c[_b]; + if (rootDir === matchedRootDir) { + // skip the initially matched entry + continue; + } + var candidate_1 = ts.combinePaths(ts.normalizePath(rootDir), suffix); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, rootDir, candidate_1); + } + var baseDirectory = ts.getDirectoryPath(candidate_1); + var resolvedFileName_1 = loader(extensions, candidate_1, !ts.directoryProbablyExists(baseDirectory, state.host), state); + if (resolvedFileName_1) { + return resolvedFileName_1; + } + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Module_resolution_using_rootDirs_has_failed); + } + } + return undefined; + } + function tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, state) { + var baseUrl = state.compilerOptions.baseUrl; + if (!baseUrl) { + return undefined; + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, baseUrl, moduleName); + } + var candidate = ts.normalizePath(ts.combinePaths(baseUrl, moduleName)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, baseUrl, candidate); + } + return loader(extensions, candidate, !ts.directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); + } + /** + * Expose resolution logic to allow us to use Node module resolution logic from arbitrary locations. + * No way to do this with `require()`: https://github.com/nodejs/node/issues/5963 + * Throws an error if the module can't be resolved. + */ + /* @internal */ + function resolveJSModule(moduleName, initialDir, host) { + var _a = tryResolveJSModuleWorker(moduleName, initialDir, host), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; + if (!resolvedModule) { + throw new Error("Could not resolve JS module '" + moduleName + "' starting at '" + initialDir + "'. Looked in: " + failedLookupLocations.join(", ")); + } + return resolvedModule.resolvedFileName; + } + ts.resolveJSModule = resolveJSModule; + /* @internal */ + function tryResolveJSModule(moduleName, initialDir, host) { + var resolvedModule = tryResolveJSModuleWorker(moduleName, initialDir, host).resolvedModule; + return resolvedModule && resolvedModule.resolvedFileName; + } + ts.tryResolveJSModule = tryResolveJSModule; + var jsOnlyExtensions = [Extensions.JavaScript]; + var tsExtensions = [Extensions.TypeScript, Extensions.JavaScript]; + var tsPlusJsonExtensions = tsExtensions.concat([Extensions.Json]); + var tsconfigExtensions = [Extensions.TSConfig]; + function tryResolveJSModuleWorker(moduleName, initialDir, host) { + return nodeModuleNameResolverWorker(moduleName, initialDir, { moduleResolution: ts.ModuleResolutionKind.NodeJs, allowJs: true }, host, /*cache*/ undefined, jsOnlyExtensions, /*redirectedReferences*/ undefined); + } + function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference, lookupConfig) { + return nodeModuleNameResolverWorker(moduleName, ts.getDirectoryPath(containingFile), compilerOptions, host, cache, lookupConfig ? tsconfigExtensions : (compilerOptions.resolveJsonModule ? tsPlusJsonExtensions : tsExtensions), redirectedReference); + } + ts.nodeModuleNameResolver = nodeModuleNameResolver; + function nodeModuleNameResolverWorker(moduleName, containingDirectory, compilerOptions, host, cache, extensions, redirectedReference) { + var traceEnabled = isTraceEnabled(compilerOptions, host); + var failedLookupLocations = []; + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; + var result = ts.forEach(extensions, function (ext) { return tryResolve(ext); }); + if (result && result.value) { + var _a = result.value, resolved = _a.resolved, isExternalLibraryImport = _a.isExternalLibraryImport; + return createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations); + } + return { resolvedModule: undefined, failedLookupLocations: failedLookupLocations }; + function tryResolve(extensions) { + var loader = function (extensions, candidate, onlyRecordFailures, state) { return nodeLoadModuleByRelativeName(extensions, candidate, onlyRecordFailures, state, /*considerPackageJson*/ true); }; + var resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, state); + if (resolved) { + return toSearchResult({ resolved: resolved, isExternalLibraryImport: pathContainsNodeModules(resolved.path) }); + } + if (!ts.isExternalModuleNameRelative(moduleName)) { + if (traceEnabled) { + trace(host, ts.Diagnostics.Loading_module_0_from_node_modules_folder_target_file_type_1, moduleName, Extensions[extensions]); + } + var resolved_1 = loadModuleFromNearestNodeModulesDirectory(extensions, moduleName, containingDirectory, state, cache, redirectedReference); + if (!resolved_1) + return undefined; + var resolvedValue = resolved_1.value; + if (!compilerOptions.preserveSymlinks && resolvedValue && !resolvedValue.originalPath) { + var path = realPath(resolvedValue.path, host, traceEnabled); + var originalPath = path === resolvedValue.path ? undefined : resolvedValue.path; + resolvedValue = __assign({}, resolvedValue, { path: path, originalPath: originalPath }); + } + // For node_modules lookups, get the real path so that multiple accesses to an `npm link`-ed module do not create duplicate files. + return { value: resolvedValue && { resolved: resolvedValue, isExternalLibraryImport: true } }; + } + else { + var _a = ts.normalizePathAndParts(ts.combinePaths(containingDirectory, moduleName)), candidate = _a.path, parts = _a.parts; + var resolved_2 = nodeLoadModuleByRelativeName(extensions, candidate, /*onlyRecordFailures*/ false, state, /*considerPackageJson*/ true); + // Treat explicit "node_modules" import as an external library import. + return resolved_2 && toSearchResult({ resolved: resolved_2, isExternalLibraryImport: ts.contains(parts, "node_modules") }); + } + } + } + function realPath(path, host, traceEnabled) { + if (!host.realpath) { + return path; + } + var real = ts.normalizePath(host.realpath(path)); + if (traceEnabled) { + trace(host, ts.Diagnostics.Resolving_real_path_for_0_result_1, path, real); + } + ts.Debug.assert(host.fileExists(real), path + " linked to nonexistent file " + real); // tslint:disable-line + return real; + } + function nodeLoadModuleByRelativeName(extensions, candidate, onlyRecordFailures, state, considerPackageJson) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1, candidate, Extensions[extensions]); + } + if (!ts.hasTrailingDirectorySeparator(candidate)) { + if (!onlyRecordFailures) { + var parentOfCandidate = ts.getDirectoryPath(candidate); + if (!ts.directoryProbablyExists(parentOfCandidate, state.host)) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, parentOfCandidate); + } + onlyRecordFailures = true; + } + } + var resolvedFromFile = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state); + if (resolvedFromFile) { + var nm = considerPackageJson ? parseNodeModuleFromPath(resolvedFromFile) : undefined; + var packageInfo = nm && getPackageJsonInfo(nm.packageDirectory, nm.subModuleName, /*onlyRecordFailures*/ false, state); + var packageId = packageInfo && packageInfo.packageId; + return withPackageId(packageId, resolvedFromFile); + } + } + if (!onlyRecordFailures) { + var candidateExists = ts.directoryProbablyExists(candidate, state.host); + if (!candidateExists) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, candidate); + } + onlyRecordFailures = true; + } + } + return loadNodeModuleFromDirectory(extensions, candidate, onlyRecordFailures, state, considerPackageJson); + } + /*@internal*/ + ts.nodeModulesPathPart = "/node_modules/"; + /*@internal*/ + function pathContainsNodeModules(path) { + return ts.stringContains(path, ts.nodeModulesPathPart); + } + ts.pathContainsNodeModules = pathContainsNodeModules; + /** + * This will be called on the successfully resolved path from `loadModuleFromFile`. + * (Not neeeded for `loadModuleFromNodeModules` as that looks up the `package.json` as part of resolution.) + * + * packageDirectory is the directory of the package itself. + * subModuleName is the path within the package. + * For `blah/node_modules/foo/index.d.ts` this is { packageDirectory: "foo", subModuleName: "index.d.ts" }. (Part before "/node_modules/" is ignored.) + * For `/node_modules/foo/bar.d.ts` this is { packageDirectory: "foo", subModuleName": "bar/index.d.ts" }. + * For `/node_modules/@types/foo/bar/index.d.ts` this is { packageDirectory: "@types/foo", subModuleName: "bar/index.d.ts" }. + * For `/node_modules/foo/bar/index.d.ts` this is { packageDirectory: "foo", subModuleName": "bar/index.d.ts" }. + */ + function parseNodeModuleFromPath(resolved) { + var path = ts.normalizePath(resolved.path); + var idx = path.lastIndexOf(ts.nodeModulesPathPart); + if (idx === -1) { + return undefined; + } + var indexAfterNodeModules = idx + ts.nodeModulesPathPart.length; + var indexAfterPackageName = moveToNextDirectorySeparatorIfAvailable(path, indexAfterNodeModules); + if (path.charCodeAt(indexAfterNodeModules) === 64 /* at */) { + indexAfterPackageName = moveToNextDirectorySeparatorIfAvailable(path, indexAfterPackageName); + } + var packageDirectory = path.slice(0, indexAfterPackageName); + var subModuleName = ts.removeExtension(path.slice(indexAfterPackageName + 1), resolved.ext) + ".d.ts" /* Dts */; + return { packageDirectory: packageDirectory, subModuleName: subModuleName }; + } + function moveToNextDirectorySeparatorIfAvailable(path, prevSeparatorIndex) { + var nextSeparatorIndex = path.indexOf(ts.directorySeparator, prevSeparatorIndex + 1); + return nextSeparatorIndex === -1 ? prevSeparatorIndex : nextSeparatorIndex; + } + function addExtensionAndIndex(path) { + if (path === "") { + return "index.d.ts"; + } + if (ts.endsWith(path, ".d.ts")) { + return path; + } + if (path === "index" || ts.endsWith(path, "/index")) { + return path + ".d.ts"; + } + return path + "/index.d.ts"; + } + function loadModuleFromFileNoPackageId(extensions, candidate, onlyRecordFailures, state) { + return noPackageId(loadModuleFromFile(extensions, candidate, onlyRecordFailures, state)); + } + /** + * @param {boolean} onlyRecordFailures - if true then function won't try to actually load files but instead record all attempts as failures. This flag is necessary + * in cases when we know upfront that all load attempts will fail (because containing folder does not exists) however we still need to record all failed lookup locations. + */ + function loadModuleFromFile(extensions, candidate, onlyRecordFailures, state) { + if (extensions === Extensions.Json || extensions === Extensions.TSConfig) { + var extensionLess = ts.tryRemoveExtension(candidate, ".json" /* Json */); + return (extensionLess === undefined && extensions === Extensions.Json) ? undefined : tryAddingExtensions(extensionLess || candidate, extensions, onlyRecordFailures, state); + } + // First, try adding an extension. An import of "foo" could be matched by a file "foo.ts", or "foo.js" by "foo.js.ts" + var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, onlyRecordFailures, state); + if (resolvedByAddingExtension) { + return resolvedByAddingExtension; + } + // If that didn't work, try stripping a ".js" or ".jsx" extension and replacing it with a TypeScript one; + // e.g. "./foo.js" can be matched by "./foo.ts" or "./foo.d.ts" + if (ts.hasJSFileExtension(candidate)) { + var extensionless = ts.removeFileExtension(candidate); + if (state.traceEnabled) { + var extension = candidate.substring(extensionless.length); + trace(state.host, ts.Diagnostics.File_name_0_has_a_1_extension_stripping_it, candidate, extension); + } + return tryAddingExtensions(extensionless, extensions, onlyRecordFailures, state); + } + } + /** Try to return an existing file that adds one of the `extensions` to `candidate`. */ + function tryAddingExtensions(candidate, extensions, onlyRecordFailures, state) { + if (!onlyRecordFailures) { + // check if containing folder exists - if it doesn't then just record failures for all supported extensions without disk probing + var directory = ts.getDirectoryPath(candidate); + if (directory) { + onlyRecordFailures = !ts.directoryProbablyExists(directory, state.host); + } + } + switch (extensions) { + case Extensions.DtsOnly: + return tryExtension(".d.ts" /* Dts */); + case Extensions.TypeScript: + return tryExtension(".ts" /* Ts */) || tryExtension(".tsx" /* Tsx */) || tryExtension(".d.ts" /* Dts */); + case Extensions.JavaScript: + return tryExtension(".js" /* Js */) || tryExtension(".jsx" /* Jsx */); + case Extensions.TSConfig: + case Extensions.Json: + return tryExtension(".json" /* Json */); + } + function tryExtension(ext) { + var path = tryFile(candidate + ext, onlyRecordFailures, state); + return path === undefined ? undefined : { path: path, ext: ext }; + } + } + /** Return the file if it exists. */ + function tryFile(fileName, onlyRecordFailures, state) { + if (!onlyRecordFailures) { + if (state.host.fileExists(fileName)) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_exist_use_it_as_a_name_resolution_result, fileName); + } + return fileName; + } + else { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_does_not_exist, fileName); + } + } + } + state.failedLookupLocations.push(fileName); + return undefined; + } + function loadNodeModuleFromDirectory(extensions, candidate, onlyRecordFailures, state, considerPackageJson) { + if (considerPackageJson === void 0) { considerPackageJson = true; } + var packageInfo = considerPackageJson ? getPackageJsonInfo(candidate, "", onlyRecordFailures, state) : undefined; + var packageId = packageInfo && packageInfo.packageId; + var packageJsonContent = packageInfo && packageInfo.packageJsonContent; + var versionPaths = packageJsonContent && readPackageJsonTypesVersionPaths(packageJsonContent, state); + return withPackageId(packageId, loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths)); + } + function getPackageJsonInfo(packageDirectory, subModuleName, onlyRecordFailures, state) { + var host = state.host, traceEnabled = state.traceEnabled; + var directoryExists = !onlyRecordFailures && ts.directoryProbablyExists(packageDirectory, host); + var packageJsonPath = ts.combinePaths(packageDirectory, "package.json"); + if (directoryExists && host.fileExists(packageJsonPath)) { + var packageJsonContent = ts.readJson(packageJsonPath, host); + if (subModuleName === "") { // looking up the root - need to handle types/typings/main redirects for subModuleName + var path = readPackageJsonTypesFields(packageJsonContent, packageDirectory, state); + if (typeof path === "string") { + subModuleName = addExtensionAndIndex(path.substring(packageDirectory.length + 1)); + } + else { + var jsPath = readPackageJsonMainField(packageJsonContent, packageDirectory, state); + if (typeof jsPath === "string" && jsPath.length > packageDirectory.length) { + var potentialSubModule_1 = jsPath.substring(packageDirectory.length + 1); + subModuleName = (ts.forEach(ts.supportedJSExtensions, function (extension) { + return ts.tryRemoveExtension(potentialSubModule_1, extension); + }) || potentialSubModule_1) + ".d.ts" /* Dts */; + } + else { + subModuleName = "index.d.ts"; + } + } + } + if (!ts.endsWith(subModuleName, ".d.ts" /* Dts */)) { + subModuleName = addExtensionAndIndex(subModuleName); + } + var versionPaths = readPackageJsonTypesVersionPaths(packageJsonContent, state); + var packageId = typeof packageJsonContent.name === "string" && typeof packageJsonContent.version === "string" + ? { name: packageJsonContent.name, subModuleName: subModuleName, version: packageJsonContent.version } + : undefined; + if (traceEnabled) { + if (packageId) { + trace(host, ts.Diagnostics.Found_package_json_at_0_Package_ID_is_1, packageJsonPath, ts.packageIdToString(packageId)); + } + else { + trace(host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); + } + } + return { packageJsonContent: packageJsonContent, packageId: packageId, versionPaths: versionPaths }; + } + else { + if (directoryExists && traceEnabled) { + trace(host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath); + } + // record package json as one of failed lookup locations - in the future if this file will appear it will invalidate resolution results + state.failedLookupLocations.push(packageJsonPath); + } + } + function loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, jsonContent, versionPaths) { + var packageFile; + if (jsonContent) { + switch (extensions) { + case Extensions.JavaScript: + case Extensions.Json: + packageFile = readPackageJsonMainField(jsonContent, candidate, state); + break; + case Extensions.TypeScript: + // When resolving typescript modules, try resolving using main field as well + packageFile = readPackageJsonTypesFields(jsonContent, candidate, state) || readPackageJsonMainField(jsonContent, candidate, state); + break; + case Extensions.DtsOnly: + packageFile = readPackageJsonTypesFields(jsonContent, candidate, state); + break; + case Extensions.TSConfig: + packageFile = readPackageJsonTSConfigField(jsonContent, candidate, state); + break; + default: + return ts.Debug.assertNever(extensions); + } + } + var loader = function (extensions, candidate, onlyRecordFailures, state) { + var fromFile = tryFile(candidate, onlyRecordFailures, state); + if (fromFile) { + var resolved = resolvedIfExtensionMatches(extensions, fromFile); + if (resolved) { + return noPackageId(resolved); + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_has_an_unsupported_extension_so_skipping_it, fromFile); + } + } + // Even if extensions is DtsOnly, we can still look up a .ts file as a result of package.json "types" + var nextExtensions = extensions === Extensions.DtsOnly ? Extensions.TypeScript : extensions; + // Don't do package.json lookup recursively, because Node.js' package lookup doesn't. + return nodeLoadModuleByRelativeName(nextExtensions, candidate, onlyRecordFailures, state, /*considerPackageJson*/ false); + }; + var onlyRecordFailuresForPackageFile = packageFile ? !ts.directoryProbablyExists(ts.getDirectoryPath(packageFile), state.host) : undefined; + var onlyRecordFailuresForIndex = onlyRecordFailures || !ts.directoryProbablyExists(candidate, state.host); + var indexPath = ts.combinePaths(candidate, extensions === Extensions.TSConfig ? "tsconfig" : "index"); + if (versionPaths && (!packageFile || ts.containsPath(candidate, packageFile))) { + var moduleName = ts.getRelativePathFromDirectory(candidate, packageFile || indexPath, /*ignoreCase*/ false); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2, versionPaths.version, ts.version, moduleName); + } + var result = tryLoadModuleUsingPaths(extensions, moduleName, candidate, versionPaths.paths, loader, onlyRecordFailuresForPackageFile || onlyRecordFailuresForIndex, state); + if (result) { + return removeIgnoredPackageId(result.value); + } + } + // It won't have a `packageId` set, because we disabled `considerPackageJson`. + var packageFileResult = packageFile && removeIgnoredPackageId(loader(extensions, packageFile, onlyRecordFailuresForPackageFile, state)); + if (packageFileResult) + return packageFileResult; + return loadModuleFromFile(extensions, indexPath, onlyRecordFailuresForIndex, state); + } + /** Resolve from an arbitrarily specified file. Return `undefined` if it has an unsupported extension. */ + function resolvedIfExtensionMatches(extensions, path) { + var ext = ts.tryGetExtensionFromPath(path); + return ext !== undefined && extensionIsOk(extensions, ext) ? { path: path, ext: ext } : undefined; + } + /** True if `extension` is one of the supported `extensions`. */ + function extensionIsOk(extensions, extension) { + switch (extensions) { + case Extensions.JavaScript: + return extension === ".js" /* Js */ || extension === ".jsx" /* Jsx */; + case Extensions.TSConfig: + case Extensions.Json: + return extension === ".json" /* Json */; + case Extensions.TypeScript: + return extension === ".ts" /* Ts */ || extension === ".tsx" /* Tsx */ || extension === ".d.ts" /* Dts */; + case Extensions.DtsOnly: + return extension === ".d.ts" /* Dts */; + } + } + /* @internal */ + function parsePackageName(moduleName) { + var idx = moduleName.indexOf(ts.directorySeparator); + if (moduleName[0] === "@") { + idx = moduleName.indexOf(ts.directorySeparator, idx + 1); + } + return idx === -1 ? { packageName: moduleName, rest: "" } : { packageName: moduleName.slice(0, idx), rest: moduleName.slice(idx + 1) }; + } + ts.parsePackageName = parsePackageName; + function loadModuleFromNearestNodeModulesDirectory(extensions, moduleName, directory, state, cache, redirectedReference) { + return loadModuleFromNearestNodeModulesDirectoryWorker(extensions, moduleName, directory, state, /*typesScopeOnly*/ false, cache, redirectedReference); + } + function loadModuleFromNearestNodeModulesDirectoryTypesScope(moduleName, directory, state) { + // Extensions parameter here doesn't actually matter, because typesOnly ensures we're just doing @types lookup, which is always DtsOnly. + return loadModuleFromNearestNodeModulesDirectoryWorker(Extensions.DtsOnly, moduleName, directory, state, /*typesScopeOnly*/ true, /*cache*/ undefined, /*redirectedReference*/ undefined); + } + function loadModuleFromNearestNodeModulesDirectoryWorker(extensions, moduleName, directory, state, typesScopeOnly, cache, redirectedReference) { + var perModuleNameCache = cache && cache.getOrCreateCacheForModuleName(moduleName, redirectedReference); + return ts.forEachAncestorDirectory(ts.normalizeSlashes(directory), function (ancestorDirectory) { + if (ts.getBaseFileName(ancestorDirectory) !== "node_modules") { + var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, ancestorDirectory, state); + if (resolutionFromCache) { + return resolutionFromCache; + } + return toSearchResult(loadModuleFromImmediateNodeModulesDirectory(extensions, moduleName, ancestorDirectory, state, typesScopeOnly)); + } + }); + } + function loadModuleFromImmediateNodeModulesDirectory(extensions, moduleName, directory, state, typesScopeOnly) { + var nodeModulesFolder = ts.combinePaths(directory, "node_modules"); + var nodeModulesFolderExists = ts.directoryProbablyExists(nodeModulesFolder, state.host); + if (!nodeModulesFolderExists && state.traceEnabled) { + trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, nodeModulesFolder); + } + var packageResult = typesScopeOnly ? undefined : loadModuleFromSpecificNodeModulesDirectory(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, state); + if (packageResult) { + return packageResult; + } + if (extensions === Extensions.TypeScript || extensions === Extensions.DtsOnly) { + var nodeModulesAtTypes_1 = ts.combinePaths(nodeModulesFolder, "@types"); + var nodeModulesAtTypesExists = nodeModulesFolderExists; + if (nodeModulesFolderExists && !ts.directoryProbablyExists(nodeModulesAtTypes_1, state.host)) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, nodeModulesAtTypes_1); + } + nodeModulesAtTypesExists = false; + } + return loadModuleFromSpecificNodeModulesDirectory(Extensions.DtsOnly, mangleScopedPackageNameWithTrace(moduleName, state), nodeModulesAtTypes_1, nodeModulesAtTypesExists, state); + } + } + function loadModuleFromSpecificNodeModulesDirectory(extensions, moduleName, nodeModulesDirectory, nodeModulesDirectoryExists, state) { + var candidate = ts.normalizePath(ts.combinePaths(nodeModulesDirectory, moduleName)); + // First look for a nested package.json, as in `node_modules/foo/bar/package.json`. + var packageJsonContent; + var packageId; + var versionPaths; + var packageInfo = getPackageJsonInfo(candidate, "", !nodeModulesDirectoryExists, state); + if (packageInfo) { + (packageJsonContent = packageInfo.packageJsonContent, packageId = packageInfo.packageId, versionPaths = packageInfo.versionPaths); + var fromFile = loadModuleFromFile(extensions, candidate, !nodeModulesDirectoryExists, state); + if (fromFile) { + return noPackageId(fromFile); + } + var fromDirectory = loadNodeModuleFromDirectoryWorker(extensions, candidate, !nodeModulesDirectoryExists, state, packageJsonContent, versionPaths); + return withPackageId(packageId, fromDirectory); + } + var loader = function (extensions, candidate, onlyRecordFailures, state) { + var pathAndExtension = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state) || + loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths); + return withPackageId(packageId, pathAndExtension); + }; + var _a = parsePackageName(moduleName), packageName = _a.packageName, rest = _a.rest; + if (rest !== "") { // If "rest" is empty, we just did this search above. + var packageDirectory = ts.combinePaths(nodeModulesDirectory, packageName); + // Don't use a "types" or "main" from here because we're not loading the root, but a subdirectory -- just here for the packageId and path mappings. + var packageInfo_1 = getPackageJsonInfo(packageDirectory, rest, !nodeModulesDirectoryExists, state); + if (packageInfo_1) + (packageId = packageInfo_1.packageId, versionPaths = packageInfo_1.versionPaths); + if (versionPaths) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2, versionPaths.version, ts.version, rest); + } + var packageDirectoryExists = nodeModulesDirectoryExists && ts.directoryProbablyExists(packageDirectory, state.host); + var fromPaths = tryLoadModuleUsingPaths(extensions, rest, packageDirectory, versionPaths.paths, loader, !packageDirectoryExists, state); + if (fromPaths) { + return fromPaths.value; + } + } + } + return loader(extensions, candidate, !nodeModulesDirectoryExists, state); + } + function tryLoadModuleUsingPaths(extensions, moduleName, baseDirectory, paths, loader, onlyRecordFailures, state) { + var matchedPattern = ts.matchPatternOrExact(ts.getOwnKeys(paths), moduleName); + if (matchedPattern) { + var matchedStar_1 = ts.isString(matchedPattern) ? undefined : ts.matchedText(matchedPattern, moduleName); + var matchedPatternText = ts.isString(matchedPattern) ? matchedPattern : ts.patternText(matchedPattern); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText); + } + var resolved = ts.forEach(paths[matchedPatternText], function (subst) { + var path = matchedStar_1 ? subst.replace("*", matchedStar_1) : subst; + var candidate = ts.normalizePath(ts.combinePaths(baseDirectory, path)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path); + } + // A path mapping may have an extension, in contrast to an import, which should omit it. + var extension = ts.tryGetExtensionFromPath(candidate); + if (extension !== undefined) { + var path_1 = tryFile(candidate, onlyRecordFailures, state); + if (path_1 !== undefined) { + return noPackageId({ path: path_1, ext: extension }); + } + } + return loader(extensions, candidate, onlyRecordFailures || !ts.directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); + }); + return { value: resolved }; + } + } + /** Double underscores are used in DefinitelyTyped to delimit scoped packages. */ + var mangledScopedPackageSeparator = "__"; + /** For a scoped package, we must look in `@types/foo__bar` instead of `@types/@foo/bar`. */ + function mangleScopedPackageNameWithTrace(packageName, state) { + var mangled = mangleScopedPackageName(packageName); + if (state.traceEnabled && mangled !== packageName) { + trace(state.host, ts.Diagnostics.Scoped_package_detected_looking_in_0, mangled); + } + return mangled; + } + /* @internal */ + function getTypesPackageName(packageName) { + return "@types/" + mangleScopedPackageName(packageName); + } + ts.getTypesPackageName = getTypesPackageName; + /* @internal */ + function mangleScopedPackageName(packageName) { + if (ts.startsWith(packageName, "@")) { + var replaceSlash = packageName.replace(ts.directorySeparator, mangledScopedPackageSeparator); + if (replaceSlash !== packageName) { + return replaceSlash.slice(1); // Take off the "@" + } + } + return packageName; + } + ts.mangleScopedPackageName = mangleScopedPackageName; + /* @internal */ + function getPackageNameFromTypesPackageName(mangledName) { + var withoutAtTypePrefix = ts.removePrefix(mangledName, "@types/"); + if (withoutAtTypePrefix !== mangledName) { + return unmangleScopedPackageName(withoutAtTypePrefix); + } + return mangledName; + } + ts.getPackageNameFromTypesPackageName = getPackageNameFromTypesPackageName; + /* @internal */ + function unmangleScopedPackageName(typesPackageName) { + return ts.stringContains(typesPackageName, mangledScopedPackageSeparator) ? + "@" + typesPackageName.replace(mangledScopedPackageSeparator, ts.directorySeparator) : + typesPackageName; + } + ts.unmangleScopedPackageName = unmangleScopedPackageName; + function tryFindNonRelativeModuleNameInCache(cache, moduleName, containingDirectory, state) { + var _a; + var result = cache && cache.get(containingDirectory); + if (result) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory); + } + (_a = state.failedLookupLocations).push.apply(_a, result.failedLookupLocations); + return { value: result.resolvedModule && { path: result.resolvedModule.resolvedFileName, originalPath: result.resolvedModule.originalPath || true, extension: result.resolvedModule.extension, packageId: result.resolvedModule.packageId } }; + } + } + function classicNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference) { + var traceEnabled = isTraceEnabled(compilerOptions, host); + var failedLookupLocations = []; + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; + var containingDirectory = ts.getDirectoryPath(containingFile); + var resolved = tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript); + // No originalPath because classic resolution doesn't resolve realPath + return createResolvedModuleWithFailedLookupLocations(resolved && resolved.value, /*isExternalLibraryImport*/ false, failedLookupLocations); + function tryResolve(extensions) { + var resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFileNoPackageId, state); + if (resolvedUsingSettings) { + return { value: resolvedUsingSettings }; + } + if (!ts.isExternalModuleNameRelative(moduleName)) { + var perModuleNameCache_1 = cache && cache.getOrCreateCacheForModuleName(moduleName, redirectedReference); + // Climb up parent directories looking for a module. + var resolved_3 = ts.forEachAncestorDirectory(containingDirectory, function (directory) { + var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache_1, moduleName, directory, state); + if (resolutionFromCache) { + return resolutionFromCache; + } + var searchName = ts.normalizePath(ts.combinePaths(directory, moduleName)); + return toSearchResult(loadModuleFromFileNoPackageId(extensions, searchName, /*onlyRecordFailures*/ false, state)); + }); + if (resolved_3) { + return resolved_3; + } + if (extensions === Extensions.TypeScript) { + // If we didn't find the file normally, look it up in @types. + return loadModuleFromNearestNodeModulesDirectoryTypesScope(moduleName, containingDirectory, state); + } + } + else { + var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); + return toSearchResult(loadModuleFromFileNoPackageId(extensions, candidate, /*onlyRecordFailures*/ false, state)); + } + } + } + ts.classicNameResolver = classicNameResolver; + /** + * LSHost may load a module from a global cache of typings. + * This is the minumum code needed to expose that functionality; the rest is in LSHost. + */ + /* @internal */ + function loadModuleFromGlobalCache(moduleName, projectName, compilerOptions, host, globalCache) { + var traceEnabled = isTraceEnabled(compilerOptions, host); + if (traceEnabled) { + trace(host, ts.Diagnostics.Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2, projectName, moduleName, globalCache); + } + var failedLookupLocations = []; + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; + var resolved = loadModuleFromImmediateNodeModulesDirectory(Extensions.DtsOnly, moduleName, globalCache, state, /*typesScopeOnly*/ false); + return createResolvedModuleWithFailedLookupLocations(resolved, /*isExternalLibraryImport*/ true, failedLookupLocations); + } + ts.loadModuleFromGlobalCache = loadModuleFromGlobalCache; + /** + * Wraps value to SearchResult. + * @returns undefined if value is undefined or { value } otherwise + */ + function toSearchResult(value) { + return value !== undefined ? { value: value } : undefined; + } +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var ModuleInstanceState; + (function (ModuleInstanceState) { + ModuleInstanceState[ModuleInstanceState["NonInstantiated"] = 0] = "NonInstantiated"; + ModuleInstanceState[ModuleInstanceState["Instantiated"] = 1] = "Instantiated"; + ModuleInstanceState[ModuleInstanceState["ConstEnumOnly"] = 2] = "ConstEnumOnly"; + })(ModuleInstanceState = ts.ModuleInstanceState || (ts.ModuleInstanceState = {})); + function getModuleInstanceState(node) { + return node.body ? getModuleInstanceStateWorker(node.body) : 1 /* Instantiated */; + } + ts.getModuleInstanceState = getModuleInstanceState; + function getModuleInstanceStateWorker(node) { + // A module is uninstantiated if it contains only + switch (node.kind) { + // 1. interface declarations, type alias declarations + case 241 /* InterfaceDeclaration */: + case 242 /* TypeAliasDeclaration */: + return 0 /* NonInstantiated */; + // 2. const enum declarations + case 243 /* EnumDeclaration */: + if (ts.isEnumConst(node)) { + return 2 /* ConstEnumOnly */; + } + break; + // 3. non-exported import declarations + case 249 /* ImportDeclaration */: + case 248 /* ImportEqualsDeclaration */: + if (!(ts.hasModifier(node, 1 /* Export */))) { + return 0 /* NonInstantiated */; + } + break; + // 4. other uninstantiated module declarations. + case 245 /* ModuleBlock */: { + var state_1 = 0 /* NonInstantiated */; + ts.forEachChild(node, function (n) { + var childState = getModuleInstanceStateWorker(n); + switch (childState) { + case 0 /* NonInstantiated */: + // child is non-instantiated - continue searching + return; + case 2 /* ConstEnumOnly */: + // child is const enum only - record state and continue searching + state_1 = 2 /* ConstEnumOnly */; + return; + case 1 /* Instantiated */: + // child is instantiated - record state and stop + state_1 = 1 /* Instantiated */; + return true; + default: + ts.Debug.assertNever(childState); + } + }); + return state_1; + } + case 244 /* ModuleDeclaration */: + return getModuleInstanceState(node); + case 72 /* Identifier */: + // Only jsdoc typedef definition can exist in jsdoc namespace, and it should + // be considered the same as type alias + if (node.isInJSDocNamespace) { + return 0 /* NonInstantiated */; + } + } + return 1 /* Instantiated */; + } + var ContainerFlags; + (function (ContainerFlags) { + // The current node is not a container, and no container manipulation should happen before + // recursing into it. + ContainerFlags[ContainerFlags["None"] = 0] = "None"; + // The current node is a container. It should be set as the current container (and block- + // container) before recursing into it. The current node does not have locals. Examples: + // + // Classes, ObjectLiterals, TypeLiterals, Interfaces... + ContainerFlags[ContainerFlags["IsContainer"] = 1] = "IsContainer"; + // The current node is a block-scoped-container. It should be set as the current block- + // container before recursing into it. Examples: + // + // Blocks (when not parented by functions), Catch clauses, For/For-in/For-of statements... + ContainerFlags[ContainerFlags["IsBlockScopedContainer"] = 2] = "IsBlockScopedContainer"; + // The current node is the container of a control flow path. The current control flow should + // be saved and restored, and a new control flow initialized within the container. + ContainerFlags[ContainerFlags["IsControlFlowContainer"] = 4] = "IsControlFlowContainer"; + ContainerFlags[ContainerFlags["IsFunctionLike"] = 8] = "IsFunctionLike"; + ContainerFlags[ContainerFlags["IsFunctionExpression"] = 16] = "IsFunctionExpression"; + ContainerFlags[ContainerFlags["HasLocals"] = 32] = "HasLocals"; + ContainerFlags[ContainerFlags["IsInterface"] = 64] = "IsInterface"; + ContainerFlags[ContainerFlags["IsObjectLiteralOrClassExpressionMethod"] = 128] = "IsObjectLiteralOrClassExpressionMethod"; + })(ContainerFlags || (ContainerFlags = {})); + var binder = createBinder(); + function bindSourceFile(file, options) { + ts.performance.mark("beforeBind"); + binder(file, options); + ts.performance.mark("afterBind"); + ts.performance.measure("Bind", "beforeBind", "afterBind"); + } + ts.bindSourceFile = bindSourceFile; + function createBinder() { + var file; + var options; + var languageVersion; + var parent; + var container; + var thisParentContainer; // Container one level up + var blockScopeContainer; + var lastContainer; + var delayedTypeAliases; + var seenThisKeyword; + // state used by control flow analysis + var currentFlow; + var currentBreakTarget; + var currentContinueTarget; + var currentReturnTarget; + var currentTrueTarget; + var currentFalseTarget; + var preSwitchCaseFlow; + var activeLabels; + var hasExplicitReturn; + // state used for emit helpers + var emitFlags; + // If this file is an external module, then it is automatically in strict-mode according to + // ES6. If it is not an external module, then we'll determine if it is in strict mode or + // not depending on if we see "use strict" in certain places or if we hit a class/namespace + // or if compiler options contain alwaysStrict. + var inStrictMode; + var symbolCount = 0; + var Symbol; // tslint:disable-line variable-name + var classifiableNames; + var unreachableFlow = { flags: 1 /* Unreachable */ }; + var reportedUnreachableFlow = { flags: 1 /* Unreachable */ }; + // state used to aggregate transform flags during bind. + var subtreeTransformFlags = 0 /* None */; + var skipTransformFlagAggregation; + /** + * Inside the binder, we may create a diagnostic for an as-yet unbound node (with potentially no parent pointers, implying no accessible source file) + * If so, the node _must_ be in the current file (as that's the only way anything could have traversed to it to yield it as the error node) + * This version of `createDiagnosticForNode` uses the binder's context to account for this, and always yields correct diagnostics even in these situations. + */ + function createDiagnosticForNode(node, message, arg0, arg1, arg2) { + return ts.createDiagnosticForNodeInSourceFile(ts.getSourceFileOfNode(node) || file, node, message, arg0, arg1, arg2); + } + function bindSourceFile(f, opts) { + file = f; + options = opts; + languageVersion = ts.getEmitScriptTarget(options); + inStrictMode = bindInStrictMode(file, opts); + classifiableNames = ts.createUnderscoreEscapedMap(); + symbolCount = 0; + skipTransformFlagAggregation = file.isDeclarationFile; + Symbol = ts.objectAllocator.getSymbolConstructor(); + if (!file.locals) { + bind(file); + file.symbolCount = symbolCount; + file.classifiableNames = classifiableNames; + delayedBindJSDocTypedefTag(); + } + file = undefined; + options = undefined; + languageVersion = undefined; + parent = undefined; + container = undefined; + thisParentContainer = undefined; + blockScopeContainer = undefined; + lastContainer = undefined; + delayedTypeAliases = undefined; + seenThisKeyword = false; + currentFlow = undefined; + currentBreakTarget = undefined; + currentContinueTarget = undefined; + currentReturnTarget = undefined; + currentTrueTarget = undefined; + currentFalseTarget = undefined; + activeLabels = undefined; + hasExplicitReturn = false; + emitFlags = 0 /* None */; + subtreeTransformFlags = 0 /* None */; + } + return bindSourceFile; + function bindInStrictMode(file, opts) { + if (ts.getStrictOptionValue(opts, "alwaysStrict") && !file.isDeclarationFile) { + // bind in strict mode source files with alwaysStrict option + return true; + } + else { + return !!file.externalModuleIndicator; + } + } + function createSymbol(flags, name) { + symbolCount++; + return new Symbol(flags, name); + } + function addDeclarationToSymbol(symbol, node, symbolFlags) { + symbol.flags |= symbolFlags; + node.symbol = symbol; + symbol.declarations = ts.append(symbol.declarations, node); + if (symbolFlags & (32 /* Class */ | 384 /* Enum */ | 1536 /* Module */ | 3 /* Variable */) && !symbol.exports) { + symbol.exports = ts.createSymbolTable(); + } + if (symbolFlags & (32 /* Class */ | 64 /* Interface */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && !symbol.members) { + symbol.members = ts.createSymbolTable(); + } + if (symbolFlags & 67220415 /* Value */) { + setValueDeclaration(symbol, node); + } + } + function setValueDeclaration(symbol, node) { + var valueDeclaration = symbol.valueDeclaration; + if (!valueDeclaration || + (ts.isAssignmentDeclaration(valueDeclaration) && !ts.isAssignmentDeclaration(node)) || + (valueDeclaration.kind !== node.kind && ts.isEffectiveModuleDeclaration(valueDeclaration))) { + // other kinds of value declarations take precedence over modules and assignment declarations + symbol.valueDeclaration = node; + } + } + // Should not be called on a declaration with a computed property name, + // unless it is a well known Symbol. + function getDeclarationName(node) { + if (node.kind === 254 /* ExportAssignment */) { + return node.isExportEquals ? "export=" /* ExportEquals */ : "default" /* Default */; + } + var name = ts.getNameOfDeclaration(node); + if (name) { + if (ts.isAmbientModule(node)) { + var moduleName = ts.getTextOfIdentifierOrLiteral(name); + return (ts.isGlobalScopeAugmentation(node) ? "__global" : "\"" + moduleName + "\""); + } + if (name.kind === 149 /* ComputedPropertyName */) { + var nameExpression = name.expression; + // treat computed property names where expression is string/numeric literal as just string/numeric literal + if (ts.isStringOrNumericLiteralLike(nameExpression)) { + return ts.escapeLeadingUnderscores(nameExpression.text); + } + ts.Debug.assert(ts.isWellKnownSymbolSyntactically(nameExpression)); + return ts.getPropertyNameForKnownSymbolName(ts.idText(nameExpression.name)); + } + return ts.isPropertyNameLiteral(name) ? ts.getEscapedTextOfIdentifierOrLiteral(name) : undefined; + } + switch (node.kind) { + case 157 /* Constructor */: + return "__constructor" /* Constructor */; + case 165 /* FunctionType */: + case 160 /* CallSignature */: + case 293 /* JSDocSignature */: + return "__call" /* Call */; + case 166 /* ConstructorType */: + case 161 /* ConstructSignature */: + return "__new" /* New */; + case 162 /* IndexSignature */: + return "__index" /* Index */; + case 255 /* ExportDeclaration */: + return "__export" /* ExportStar */; + case 279 /* SourceFile */: + // json file should behave as + // module.exports = ... + return "export=" /* ExportEquals */; + case 204 /* BinaryExpression */: + if (ts.getAssignmentDeclarationKind(node) === 2 /* ModuleExports */) { + // module.exports = ... + return "export=" /* ExportEquals */; + } + ts.Debug.fail("Unknown binary declaration kind"); + break; + case 289 /* JSDocFunctionType */: + return (ts.isJSDocConstructSignature(node) ? "__new" /* New */ : "__call" /* Call */); + case 151 /* Parameter */: + // Parameters with names are handled at the top of this function. Parameters + // without names can only come from JSDocFunctionTypes. + ts.Debug.assert(node.parent.kind === 289 /* JSDocFunctionType */, "Impossible parameter parent kind", function () { return "parent is: " + (ts.SyntaxKind ? ts.SyntaxKind[node.parent.kind] : node.parent.kind) + ", expected JSDocFunctionType"; }); + var functionType = node.parent; + var index = functionType.parameters.indexOf(node); + return "arg" + index; + } + } + function getDisplayName(node) { + return ts.isNamedDeclaration(node) ? ts.declarationNameToString(node.name) : ts.unescapeLeadingUnderscores(ts.Debug.assertDefined(getDeclarationName(node))); + } + /** + * Declares a Symbol for the node and adds it to symbols. Reports errors for conflicting identifier names. + * @param symbolTable - The symbol table which node will be added to. + * @param parent - node's parent declaration. + * @param node - The declaration to be added to the symbol table + * @param includes - The SymbolFlags that node has in addition to its declaration type (eg: export, ambient, etc.) + * @param excludes - The flags which node cannot be declared alongside in a symbol table. Used to report forbidden declarations. + */ + function declareSymbol(symbolTable, parent, node, includes, excludes, isReplaceableByMethod) { + ts.Debug.assert(!ts.hasDynamicName(node)); + var isDefaultExport = ts.hasModifier(node, 512 /* Default */); + // The exported symbol for an export default function/class node is always named "default" + var name = isDefaultExport && parent ? "default" /* Default */ : getDeclarationName(node); + var symbol; + if (name === undefined) { + symbol = createSymbol(0 /* None */, "__missing" /* Missing */); + } + else { + // Check and see if the symbol table already has a symbol with this name. If not, + // create a new symbol with this name and add it to the table. Note that we don't + // give the new symbol any flags *yet*. This ensures that it will not conflict + // with the 'excludes' flags we pass in. + // + // If we do get an existing symbol, see if it conflicts with the new symbol we're + // creating. For example, a 'var' symbol and a 'class' symbol will conflict within + // the same symbol table. If we have a conflict, report the issue on each + // declaration we have for this symbol, and then create a new symbol for this + // declaration. + // + // Note that when properties declared in Javascript constructors + // (marked by isReplaceableByMethod) conflict with another symbol, the property loses. + // Always. This allows the common Javascript pattern of overwriting a prototype method + // with an bound instance method of the same type: `this.method = this.method.bind(this)` + // + // If we created a new symbol, either because we didn't have a symbol with this name + // in the symbol table, or we conflicted with an existing symbol, then just add this + // node as the sole declaration of the new symbol. + // + // Otherwise, we'll be merging into a compatible existing symbol (for example when + // you have multiple 'vars' with the same name in the same container). In this case + // just add this node into the declarations list of the symbol. + symbol = symbolTable.get(name); + if (includes & 2885600 /* Classifiable */) { + classifiableNames.set(name, true); + } + if (!symbol) { + symbolTable.set(name, symbol = createSymbol(0 /* None */, name)); + if (isReplaceableByMethod) + symbol.isReplaceableByMethod = true; + } + else if (isReplaceableByMethod && !symbol.isReplaceableByMethod) { + // A symbol already exists, so don't add this as a declaration. + return symbol; + } + else if (symbol.flags & excludes) { + if (symbol.isReplaceableByMethod) { + // Javascript constructor-declared symbols can be discarded in favor of + // prototype symbols like methods. + symbolTable.set(name, symbol = createSymbol(0 /* None */, name)); + } + else if (!(includes & 3 /* Variable */ && symbol.flags & 67108864 /* Assignment */)) { + // Assignment declarations are allowed to merge with variables, no matter what other flags they have. + if (ts.isNamedDeclaration(node)) { + node.name.parent = node; + } + // Report errors every position with duplicate declaration + // Report errors on previous encountered declarations + var message_1 = symbol.flags & 2 /* BlockScopedVariable */ + ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 + : ts.Diagnostics.Duplicate_identifier_0; + var messageNeedsName_1 = true; + if (symbol.flags & 384 /* Enum */ || includes & 384 /* Enum */) { + message_1 = ts.Diagnostics.Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations; + messageNeedsName_1 = false; + } + if (symbol.declarations && symbol.declarations.length) { + // If the current node is a default export of some sort, then check if + // there are any other default exports that we need to error on. + // We'll know whether we have other default exports depending on if `symbol` already has a declaration list set. + if (isDefaultExport) { + message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; + messageNeedsName_1 = false; + } + else { + // This is to properly report an error in the case "export default { }" is after export default of class declaration or function declaration. + // Error on multiple export default in the following case: + // 1. multiple export default of class declaration or function declaration by checking NodeFlags.Default + // 2. multiple export default of export assignment. This one doesn't have NodeFlags.Default on (as export default doesn't considered as modifiers) + if (symbol.declarations && symbol.declarations.length && + (node.kind === 254 /* ExportAssignment */ && !node.isExportEquals)) { + message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; + messageNeedsName_1 = false; + } + } + } + var addError = function (decl) { + file.bindDiagnostics.push(createDiagnosticForNode(ts.getNameOfDeclaration(decl) || decl, message_1, messageNeedsName_1 ? getDisplayName(decl) : undefined)); + }; + ts.forEach(symbol.declarations, addError); + addError(node); + symbol = createSymbol(0 /* None */, name); + } + } + } + addDeclarationToSymbol(symbol, node, includes); + if (symbol.parent) { + ts.Debug.assert(symbol.parent === parent, "Existing symbol parent should match new one"); + } + else { + symbol.parent = parent; + } + return symbol; + } + function declareModuleMember(node, symbolFlags, symbolExcludes) { + var hasExportModifier = ts.getCombinedModifierFlags(node) & 1 /* Export */; + if (symbolFlags & 2097152 /* Alias */) { + if (node.kind === 257 /* ExportSpecifier */ || (node.kind === 248 /* ImportEqualsDeclaration */ && hasExportModifier)) { + return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); + } + else { + return declareSymbol(container.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes); + } + } + else { + // Exported module members are given 2 symbols: A local symbol that is classified with an ExportValue flag, + // and an associated export symbol with all the correct flags set on it. There are 2 main reasons: + // + // 1. We treat locals and exports of the same name as mutually exclusive within a container. + // That means the binder will issue a Duplicate Identifier error if you mix locals and exports + // with the same name in the same container. + // TODO: Make this a more specific error and decouple it from the exclusion logic. + // 2. When we checkIdentifier in the checker, we set its resolved symbol to the local symbol, + // but return the export symbol (by calling getExportSymbolOfValueSymbolIfExported). That way + // when the emitter comes back to it, it knows not to qualify the name if it was found in a containing scope. + // NOTE: Nested ambient modules always should go to to 'locals' table to prevent their automatic merge + // during global merging in the checker. Why? The only case when ambient module is permitted inside another module is module augmentation + // and this case is specially handled. Module augmentations should only be merged with original module definition + // and should never be merged directly with other augmentation, and the latter case would be possible if automatic merge is allowed. + if (ts.isJSDocTypeAlias(node)) + ts.Debug.assert(ts.isInJSFile(node)); // We shouldn't add symbols for JSDoc nodes if not in a JS file. + if ((!ts.isAmbientModule(node) && (hasExportModifier || container.flags & 32 /* ExportContext */)) || ts.isJSDocTypeAlias(node)) { + if (ts.hasModifier(node, 512 /* Default */) && !getDeclarationName(node)) { + return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); // No local symbol for an unnamed default! + } + var exportKind = symbolFlags & 67220415 /* Value */ ? 1048576 /* ExportValue */ : 0; + var local = declareSymbol(container.locals, /*parent*/ undefined, node, exportKind, symbolExcludes); + local.exportSymbol = declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); + node.localSymbol = local; + return local; + } + else { + return declareSymbol(container.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes); + } + } + } + // All container nodes are kept on a linked list in declaration order. This list is used by + // the getLocalNameOfContainer function in the type checker to validate that the local name + // used for a container is unique. + function bindContainer(node, containerFlags) { + // Before we recurse into a node's children, we first save the existing parent, container + // and block-container. Then after we pop out of processing the children, we restore + // these saved values. + var saveContainer = container; + var saveThisParentContainer = thisParentContainer; + var savedBlockScopeContainer = blockScopeContainer; + // Depending on what kind of node this is, we may have to adjust the current container + // and block-container. If the current node is a container, then it is automatically + // considered the current block-container as well. Also, for containers that we know + // may contain locals, we eagerly initialize the .locals field. We do this because + // it's highly likely that the .locals will be needed to place some child in (for example, + // a parameter, or variable declaration). + // + // However, we do not proactively create the .locals for block-containers because it's + // totally normal and common for block-containers to never actually have a block-scoped + // variable in them. We don't want to end up allocating an object for every 'block' we + // run into when most of them won't be necessary. + // + // Finally, if this is a block-container, then we clear out any existing .locals object + // it may contain within it. This happens in incremental scenarios. Because we can be + // reusing a node from a previous compilation, that node may have had 'locals' created + // for it. We must clear this so we don't accidentally move any stale data forward from + // a previous compilation. + if (containerFlags & 1 /* IsContainer */) { + if (node.kind !== 197 /* ArrowFunction */) { + thisParentContainer = container; + } + container = blockScopeContainer = node; + if (containerFlags & 32 /* HasLocals */) { + container.locals = ts.createSymbolTable(); + } + addToContainerChain(container); + } + else if (containerFlags & 2 /* IsBlockScopedContainer */) { + blockScopeContainer = node; + blockScopeContainer.locals = undefined; + } + if (containerFlags & 4 /* IsControlFlowContainer */) { + var saveCurrentFlow = currentFlow; + var saveBreakTarget = currentBreakTarget; + var saveContinueTarget = currentContinueTarget; + var saveReturnTarget = currentReturnTarget; + var saveActiveLabels = activeLabels; + var saveHasExplicitReturn = hasExplicitReturn; + var isIIFE = containerFlags & 16 /* IsFunctionExpression */ && !ts.hasModifier(node, 256 /* Async */) && + !node.asteriskToken && !!ts.getImmediatelyInvokedFunctionExpression(node); + // A non-async, non-generator IIFE is considered part of the containing control flow. Return statements behave + // similarly to break statements that exit to a label just past the statement body. + if (!isIIFE) { + currentFlow = { flags: 2 /* Start */ }; + if (containerFlags & (16 /* IsFunctionExpression */ | 128 /* IsObjectLiteralOrClassExpressionMethod */)) { + currentFlow.container = node; + } + } + // We create a return control flow graph for IIFEs and constructors. For constructors + // we use the return control flow graph in strict property intialization checks. + currentReturnTarget = isIIFE || node.kind === 157 /* Constructor */ ? createBranchLabel() : undefined; + currentBreakTarget = undefined; + currentContinueTarget = undefined; + activeLabels = undefined; + hasExplicitReturn = false; + bindChildren(node); + // Reset all reachability check related flags on node (for incremental scenarios) + node.flags &= ~1408 /* ReachabilityAndEmitFlags */; + if (!(currentFlow.flags & 1 /* Unreachable */) && containerFlags & 8 /* IsFunctionLike */ && ts.nodeIsPresent(node.body)) { + node.flags |= 128 /* HasImplicitReturn */; + if (hasExplicitReturn) + node.flags |= 256 /* HasExplicitReturn */; + } + if (node.kind === 279 /* SourceFile */) { + node.flags |= emitFlags; + } + if (currentReturnTarget) { + addAntecedent(currentReturnTarget, currentFlow); + currentFlow = finishFlowLabel(currentReturnTarget); + if (node.kind === 157 /* Constructor */) { + node.returnFlowNode = currentFlow; + } + } + if (!isIIFE) { + currentFlow = saveCurrentFlow; + } + currentBreakTarget = saveBreakTarget; + currentContinueTarget = saveContinueTarget; + currentReturnTarget = saveReturnTarget; + activeLabels = saveActiveLabels; + hasExplicitReturn = saveHasExplicitReturn; + } + else if (containerFlags & 64 /* IsInterface */) { + seenThisKeyword = false; + bindChildren(node); + node.flags = seenThisKeyword ? node.flags | 64 /* ContainsThis */ : node.flags & ~64 /* ContainsThis */; + } + else { + bindChildren(node); + } + container = saveContainer; + thisParentContainer = saveThisParentContainer; + blockScopeContainer = savedBlockScopeContainer; + } + function bindChildren(node) { + if (skipTransformFlagAggregation) { + bindChildrenWorker(node); + } + else if (node.transformFlags & 536870912 /* HasComputedFlags */) { + skipTransformFlagAggregation = true; + bindChildrenWorker(node); + skipTransformFlagAggregation = false; + subtreeTransformFlags |= node.transformFlags & ~getTransformFlagsSubtreeExclusions(node.kind); + } + else { + var savedSubtreeTransformFlags = subtreeTransformFlags; + subtreeTransformFlags = 0; + bindChildrenWorker(node); + subtreeTransformFlags = savedSubtreeTransformFlags | computeTransformFlagsForNode(node, subtreeTransformFlags); + } + } + function bindEachFunctionsFirst(nodes) { + bindEach(nodes, function (n) { return n.kind === 239 /* FunctionDeclaration */ ? bind(n) : undefined; }); + bindEach(nodes, function (n) { return n.kind !== 239 /* FunctionDeclaration */ ? bind(n) : undefined; }); + } + function bindEach(nodes, bindFunction) { + if (bindFunction === void 0) { bindFunction = bind; } + if (nodes === undefined) { + return; + } + if (skipTransformFlagAggregation) { + ts.forEach(nodes, bindFunction); + } + else { + var savedSubtreeTransformFlags = subtreeTransformFlags; + subtreeTransformFlags = 0 /* None */; + var nodeArrayFlags = 0 /* None */; + for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) { + var node = nodes_2[_i]; + bindFunction(node); + nodeArrayFlags |= node.transformFlags & ~536870912 /* HasComputedFlags */; + } + nodes.transformFlags = nodeArrayFlags | 536870912 /* HasComputedFlags */; + subtreeTransformFlags |= savedSubtreeTransformFlags; + } + } + function bindEachChild(node) { + ts.forEachChild(node, bind, bindEach); + } + function bindChildrenWorker(node) { + if (checkUnreachable(node)) { + bindEachChild(node); + bindJSDoc(node); + return; + } + switch (node.kind) { + case 224 /* WhileStatement */: + bindWhileStatement(node); + break; + case 223 /* DoStatement */: + bindDoStatement(node); + break; + case 225 /* ForStatement */: + bindForStatement(node); + break; + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + bindForInOrForOfStatement(node); + break; + case 222 /* IfStatement */: + bindIfStatement(node); + break; + case 230 /* ReturnStatement */: + case 234 /* ThrowStatement */: + bindReturnOrThrow(node); + break; + case 229 /* BreakStatement */: + case 228 /* ContinueStatement */: + bindBreakOrContinueStatement(node); + break; + case 235 /* TryStatement */: + bindTryStatement(node); + break; + case 232 /* SwitchStatement */: + bindSwitchStatement(node); + break; + case 246 /* CaseBlock */: + bindCaseBlock(node); + break; + case 271 /* CaseClause */: + bindCaseClause(node); + break; + case 233 /* LabeledStatement */: + bindLabeledStatement(node); + break; + case 202 /* PrefixUnaryExpression */: + bindPrefixUnaryExpressionFlow(node); + break; + case 203 /* PostfixUnaryExpression */: + bindPostfixUnaryExpressionFlow(node); + break; + case 204 /* BinaryExpression */: + bindBinaryExpressionFlow(node); + break; + case 198 /* DeleteExpression */: + bindDeleteExpressionFlow(node); + break; + case 205 /* ConditionalExpression */: + bindConditionalExpressionFlow(node); + break; + case 237 /* VariableDeclaration */: + bindVariableDeclarationFlow(node); + break; + case 191 /* CallExpression */: + bindCallExpressionFlow(node); + break; + case 304 /* JSDocTypedefTag */: + case 297 /* JSDocCallbackTag */: + bindJSDocTypeAlias(node); + break; + // In source files and blocks, bind functions first to match hoisting that occurs at runtime + case 279 /* SourceFile */: { + bindEachFunctionsFirst(node.statements); + bind(node.endOfFileToken); + break; + } + case 218 /* Block */: + case 245 /* ModuleBlock */: + bindEachFunctionsFirst(node.statements); + break; + default: + bindEachChild(node); + break; + } + bindJSDoc(node); + } + function isNarrowingExpression(expr) { + switch (expr.kind) { + case 72 /* Identifier */: + case 100 /* ThisKeyword */: + case 189 /* PropertyAccessExpression */: + case 190 /* ElementAccessExpression */: + return isNarrowableReference(expr); + case 191 /* CallExpression */: + return hasNarrowableArgument(expr); + case 195 /* ParenthesizedExpression */: + return isNarrowingExpression(expr.expression); + case 204 /* BinaryExpression */: + return isNarrowingBinaryExpression(expr); + case 202 /* PrefixUnaryExpression */: + return expr.operator === 52 /* ExclamationToken */ && isNarrowingExpression(expr.operand); + case 199 /* TypeOfExpression */: + return isNarrowingExpression(expr.expression); + } + return false; + } + function isNarrowableReference(expr) { + return expr.kind === 72 /* Identifier */ || expr.kind === 100 /* ThisKeyword */ || expr.kind === 98 /* SuperKeyword */ || + ts.isPropertyAccessExpression(expr) && isNarrowableReference(expr.expression) || + ts.isElementAccessExpression(expr) && expr.argumentExpression && + (ts.isStringLiteral(expr.argumentExpression) || ts.isNumericLiteral(expr.argumentExpression)) && + isNarrowableReference(expr.expression); + } + function hasNarrowableArgument(expr) { + if (expr.arguments) { + for (var _i = 0, _a = expr.arguments; _i < _a.length; _i++) { + var argument = _a[_i]; + if (isNarrowableReference(argument)) { + return true; + } + } + } + if (expr.expression.kind === 189 /* PropertyAccessExpression */ && + isNarrowableReference(expr.expression.expression)) { + return true; + } + return false; + } + function isNarrowingTypeofOperands(expr1, expr2) { + return ts.isTypeOfExpression(expr1) && isNarrowableOperand(expr1.expression) && ts.isStringLiteralLike(expr2); + } + function isNarrowableInOperands(left, right) { + return ts.isStringLiteralLike(left) && isNarrowingExpression(right); + } + function isNarrowingBinaryExpression(expr) { + switch (expr.operatorToken.kind) { + case 59 /* EqualsToken */: + return isNarrowableReference(expr.left); + case 33 /* EqualsEqualsToken */: + case 34 /* ExclamationEqualsToken */: + case 35 /* EqualsEqualsEqualsToken */: + case 36 /* ExclamationEqualsEqualsToken */: + return isNarrowableOperand(expr.left) || isNarrowableOperand(expr.right) || + isNarrowingTypeofOperands(expr.right, expr.left) || isNarrowingTypeofOperands(expr.left, expr.right); + case 94 /* InstanceOfKeyword */: + return isNarrowableOperand(expr.left); + case 93 /* InKeyword */: + return isNarrowableInOperands(expr.left, expr.right); + case 27 /* CommaToken */: + return isNarrowingExpression(expr.right); + } + return false; + } + function isNarrowableOperand(expr) { + switch (expr.kind) { + case 195 /* ParenthesizedExpression */: + return isNarrowableOperand(expr.expression); + case 204 /* BinaryExpression */: + switch (expr.operatorToken.kind) { + case 59 /* EqualsToken */: + return isNarrowableOperand(expr.left); + case 27 /* CommaToken */: + return isNarrowableOperand(expr.right); + } + } + return isNarrowableReference(expr); + } + function createBranchLabel() { + return { + flags: 4 /* BranchLabel */, + antecedents: undefined + }; + } + function createLoopLabel() { + return { + flags: 8 /* LoopLabel */, + antecedents: undefined + }; + } + function setFlowNodeReferenced(flow) { + // On first reference we set the Referenced flag, thereafter we set the Shared flag + flow.flags |= flow.flags & 512 /* Referenced */ ? 1024 /* Shared */ : 512 /* Referenced */; + } + function addAntecedent(label, antecedent) { + if (!(antecedent.flags & 1 /* Unreachable */) && !ts.contains(label.antecedents, antecedent)) { + (label.antecedents || (label.antecedents = [])).push(antecedent); + setFlowNodeReferenced(antecedent); + } + } + function createFlowCondition(flags, antecedent, expression) { + if (antecedent.flags & 1 /* Unreachable */) { + return antecedent; + } + if (!expression) { + return flags & 32 /* TrueCondition */ ? antecedent : unreachableFlow; + } + if (expression.kind === 102 /* TrueKeyword */ && flags & 64 /* FalseCondition */ || + expression.kind === 87 /* FalseKeyword */ && flags & 32 /* TrueCondition */) { + return unreachableFlow; + } + if (!isNarrowingExpression(expression)) { + return antecedent; + } + setFlowNodeReferenced(antecedent); + return { flags: flags, expression: expression, antecedent: antecedent }; + } + function createFlowSwitchClause(antecedent, switchStatement, clauseStart, clauseEnd) { + if (!isNarrowingExpression(switchStatement.expression)) { + return antecedent; + } + setFlowNodeReferenced(antecedent); + return { flags: 128 /* SwitchClause */, switchStatement: switchStatement, clauseStart: clauseStart, clauseEnd: clauseEnd, antecedent: antecedent }; + } + function createFlowAssignment(antecedent, node) { + setFlowNodeReferenced(antecedent); + return { flags: 16 /* Assignment */, antecedent: antecedent, node: node }; + } + function createFlowArrayMutation(antecedent, node) { + setFlowNodeReferenced(antecedent); + var res = { flags: 256 /* ArrayMutation */, antecedent: antecedent, node: node }; + return res; + } + function finishFlowLabel(flow) { + var antecedents = flow.antecedents; + if (!antecedents) { + return unreachableFlow; + } + if (antecedents.length === 1) { + return antecedents[0]; + } + return flow; + } + function isStatementCondition(node) { + var parent = node.parent; + switch (parent.kind) { + case 222 /* IfStatement */: + case 224 /* WhileStatement */: + case 223 /* DoStatement */: + return parent.expression === node; + case 225 /* ForStatement */: + case 205 /* ConditionalExpression */: + return parent.condition === node; + } + return false; + } + function isLogicalExpression(node) { + while (true) { + if (node.kind === 195 /* ParenthesizedExpression */) { + node = node.expression; + } + else if (node.kind === 202 /* PrefixUnaryExpression */ && node.operator === 52 /* ExclamationToken */) { + node = node.operand; + } + else { + return node.kind === 204 /* BinaryExpression */ && (node.operatorToken.kind === 54 /* AmpersandAmpersandToken */ || + node.operatorToken.kind === 55 /* BarBarToken */); + } + } + } + function isTopLevelLogicalExpression(node) { + while (node.parent.kind === 195 /* ParenthesizedExpression */ || + node.parent.kind === 202 /* PrefixUnaryExpression */ && + node.parent.operator === 52 /* ExclamationToken */) { + node = node.parent; + } + return !isStatementCondition(node) && !isLogicalExpression(node.parent); + } + function bindCondition(node, trueTarget, falseTarget) { + var saveTrueTarget = currentTrueTarget; + var saveFalseTarget = currentFalseTarget; + currentTrueTarget = trueTarget; + currentFalseTarget = falseTarget; + bind(node); + currentTrueTarget = saveTrueTarget; + currentFalseTarget = saveFalseTarget; + if (!node || !isLogicalExpression(node)) { + addAntecedent(trueTarget, createFlowCondition(32 /* TrueCondition */, currentFlow, node)); + addAntecedent(falseTarget, createFlowCondition(64 /* FalseCondition */, currentFlow, node)); + } + } + function bindIterativeStatement(node, breakTarget, continueTarget) { + var saveBreakTarget = currentBreakTarget; + var saveContinueTarget = currentContinueTarget; + currentBreakTarget = breakTarget; + currentContinueTarget = continueTarget; + bind(node); + currentBreakTarget = saveBreakTarget; + currentContinueTarget = saveContinueTarget; + } + function bindWhileStatement(node) { + var preWhileLabel = createLoopLabel(); + var preBodyLabel = createBranchLabel(); + var postWhileLabel = createBranchLabel(); + addAntecedent(preWhileLabel, currentFlow); + currentFlow = preWhileLabel; + bindCondition(node.expression, preBodyLabel, postWhileLabel); + currentFlow = finishFlowLabel(preBodyLabel); + bindIterativeStatement(node.statement, postWhileLabel, preWhileLabel); + addAntecedent(preWhileLabel, currentFlow); + currentFlow = finishFlowLabel(postWhileLabel); + } + function bindDoStatement(node) { + var preDoLabel = createLoopLabel(); + var enclosingLabeledStatement = node.parent.kind === 233 /* LabeledStatement */ + ? ts.lastOrUndefined(activeLabels) + : undefined; + // if do statement is wrapped in labeled statement then target labels for break/continue with or without + // label should be the same + var preConditionLabel = enclosingLabeledStatement ? enclosingLabeledStatement.continueTarget : createBranchLabel(); + var postDoLabel = enclosingLabeledStatement ? enclosingLabeledStatement.breakTarget : createBranchLabel(); + addAntecedent(preDoLabel, currentFlow); + currentFlow = preDoLabel; + bindIterativeStatement(node.statement, postDoLabel, preConditionLabel); + addAntecedent(preConditionLabel, currentFlow); + currentFlow = finishFlowLabel(preConditionLabel); + bindCondition(node.expression, preDoLabel, postDoLabel); + currentFlow = finishFlowLabel(postDoLabel); + } + function bindForStatement(node) { + var preLoopLabel = createLoopLabel(); + var preBodyLabel = createBranchLabel(); + var postLoopLabel = createBranchLabel(); + bind(node.initializer); + addAntecedent(preLoopLabel, currentFlow); + currentFlow = preLoopLabel; + bindCondition(node.condition, preBodyLabel, postLoopLabel); + currentFlow = finishFlowLabel(preBodyLabel); + bindIterativeStatement(node.statement, postLoopLabel, preLoopLabel); + bind(node.incrementor); + addAntecedent(preLoopLabel, currentFlow); + currentFlow = finishFlowLabel(postLoopLabel); + } + function bindForInOrForOfStatement(node) { + var preLoopLabel = createLoopLabel(); + var postLoopLabel = createBranchLabel(); + addAntecedent(preLoopLabel, currentFlow); + currentFlow = preLoopLabel; + if (node.kind === 227 /* ForOfStatement */) { + bind(node.awaitModifier); + } + bind(node.expression); + addAntecedent(postLoopLabel, currentFlow); + bind(node.initializer); + if (node.initializer.kind !== 238 /* VariableDeclarationList */) { + bindAssignmentTargetFlow(node.initializer); + } + bindIterativeStatement(node.statement, postLoopLabel, preLoopLabel); + addAntecedent(preLoopLabel, currentFlow); + currentFlow = finishFlowLabel(postLoopLabel); + } + function bindIfStatement(node) { + var thenLabel = createBranchLabel(); + var elseLabel = createBranchLabel(); + var postIfLabel = createBranchLabel(); + bindCondition(node.expression, thenLabel, elseLabel); + currentFlow = finishFlowLabel(thenLabel); + bind(node.thenStatement); + addAntecedent(postIfLabel, currentFlow); + currentFlow = finishFlowLabel(elseLabel); + bind(node.elseStatement); + addAntecedent(postIfLabel, currentFlow); + currentFlow = finishFlowLabel(postIfLabel); + } + function bindReturnOrThrow(node) { + bind(node.expression); + if (node.kind === 230 /* ReturnStatement */) { + hasExplicitReturn = true; + if (currentReturnTarget) { + addAntecedent(currentReturnTarget, currentFlow); + } + } + currentFlow = unreachableFlow; + } + function findActiveLabel(name) { + if (activeLabels) { + for (var _i = 0, activeLabels_1 = activeLabels; _i < activeLabels_1.length; _i++) { + var label = activeLabels_1[_i]; + if (label.name === name) { + return label; + } + } + } + return undefined; + } + function bindBreakOrContinueFlow(node, breakTarget, continueTarget) { + var flowLabel = node.kind === 229 /* BreakStatement */ ? breakTarget : continueTarget; + if (flowLabel) { + addAntecedent(flowLabel, currentFlow); + currentFlow = unreachableFlow; + } + } + function bindBreakOrContinueStatement(node) { + bind(node.label); + if (node.label) { + var activeLabel = findActiveLabel(node.label.escapedText); + if (activeLabel) { + activeLabel.referenced = true; + bindBreakOrContinueFlow(node, activeLabel.breakTarget, activeLabel.continueTarget); + } + } + else { + bindBreakOrContinueFlow(node, currentBreakTarget, currentContinueTarget); + } + } + function bindTryStatement(node) { + var preFinallyLabel = createBranchLabel(); + var preTryFlow = currentFlow; + // TODO: Every statement in try block is potentially an exit point! + bind(node.tryBlock); + addAntecedent(preFinallyLabel, currentFlow); + var flowAfterTry = currentFlow; + var flowAfterCatch = unreachableFlow; + if (node.catchClause) { + currentFlow = preTryFlow; + bind(node.catchClause); + addAntecedent(preFinallyLabel, currentFlow); + flowAfterCatch = currentFlow; + } + if (node.finallyBlock) { + // in finally flow is combined from pre-try/flow from try/flow from catch + // pre-flow is necessary to make sure that finally is reachable even if finally flows in both try and finally blocks are unreachable + // also for finally blocks we inject two extra edges into the flow graph. + // first -> edge that connects pre-try flow with the label at the beginning of the finally block, it has lock associated with it + // second -> edge that represents post-finally flow. + // these edges are used in following scenario: + // let a; (1) + // try { a = someOperation(); (2)} + // finally { (3) console.log(a) } (4) + // (5) a + // flow graph for this case looks roughly like this (arrows show ): + // (1-pre-try-flow) <--.. <-- (2-post-try-flow) + // ^ ^ + // |*****(3-pre-finally-label) -----| + // ^ + // |-- ... <-- (4-post-finally-label) <--- (5) + // In case when we walk the flow starting from inside the finally block we want to take edge '*****' into account + // since it ensures that finally is always reachable. However when we start outside the finally block and go through label (5) + // then edge '*****' should be discarded because label 4 is only reachable if post-finally label-4 is reachable + // Simply speaking code inside finally block is treated as reachable as pre-try-flow + // since we conservatively assume that any line in try block can throw or return in which case we'll enter finally. + // However code after finally is reachable only if control flow was not abrupted in try/catch or finally blocks - it should be composed from + // final flows of these blocks without taking pre-try flow into account. + // + // extra edges that we inject allows to control this behavior + // if when walking the flow we step on post-finally edge - we can mark matching pre-finally edge as locked so it will be skipped. + var preFinallyFlow = { flags: 2048 /* PreFinally */, antecedent: preTryFlow, lock: {} }; + addAntecedent(preFinallyLabel, preFinallyFlow); + currentFlow = finishFlowLabel(preFinallyLabel); + bind(node.finallyBlock); + // if flow after finally is unreachable - keep it + // otherwise check if flows after try and after catch are unreachable + // if yes - convert current flow to unreachable + // i.e. + // try { return "1" } finally { console.log(1); } + // console.log(2); // this line should be unreachable even if flow falls out of finally block + if (!(currentFlow.flags & 1 /* Unreachable */)) { + if ((flowAfterTry.flags & 1 /* Unreachable */) && (flowAfterCatch.flags & 1 /* Unreachable */)) { + currentFlow = flowAfterTry === reportedUnreachableFlow || flowAfterCatch === reportedUnreachableFlow + ? reportedUnreachableFlow + : unreachableFlow; + } + } + if (!(currentFlow.flags & 1 /* Unreachable */)) { + var afterFinallyFlow = { flags: 4096 /* AfterFinally */, antecedent: currentFlow }; + preFinallyFlow.lock = afterFinallyFlow; + currentFlow = afterFinallyFlow; + } + } + else { + currentFlow = finishFlowLabel(preFinallyLabel); + } + } + function bindSwitchStatement(node) { + var postSwitchLabel = createBranchLabel(); + bind(node.expression); + var saveBreakTarget = currentBreakTarget; + var savePreSwitchCaseFlow = preSwitchCaseFlow; + currentBreakTarget = postSwitchLabel; + preSwitchCaseFlow = currentFlow; + bind(node.caseBlock); + addAntecedent(postSwitchLabel, currentFlow); + var hasDefault = ts.forEach(node.caseBlock.clauses, function (c) { return c.kind === 272 /* DefaultClause */; }); + // We mark a switch statement as possibly exhaustive if it has no default clause and if all + // case clauses have unreachable end points (e.g. they all return). + node.possiblyExhaustive = !hasDefault && !postSwitchLabel.antecedents; + if (!hasDefault) { + addAntecedent(postSwitchLabel, createFlowSwitchClause(preSwitchCaseFlow, node, 0, 0)); + } + currentBreakTarget = saveBreakTarget; + preSwitchCaseFlow = savePreSwitchCaseFlow; + currentFlow = finishFlowLabel(postSwitchLabel); + } + function bindCaseBlock(node) { + var savedSubtreeTransformFlags = subtreeTransformFlags; + subtreeTransformFlags = 0; + var clauses = node.clauses; + var fallthroughFlow = unreachableFlow; + for (var i = 0; i < clauses.length; i++) { + var clauseStart = i; + while (!clauses[i].statements.length && i + 1 < clauses.length) { + bind(clauses[i]); + i++; + } + var preCaseLabel = createBranchLabel(); + addAntecedent(preCaseLabel, createFlowSwitchClause(preSwitchCaseFlow, node.parent, clauseStart, i + 1)); + addAntecedent(preCaseLabel, fallthroughFlow); + currentFlow = finishFlowLabel(preCaseLabel); + var clause = clauses[i]; + bind(clause); + fallthroughFlow = currentFlow; + if (!(currentFlow.flags & 1 /* Unreachable */) && i !== clauses.length - 1 && options.noFallthroughCasesInSwitch) { + errorOnFirstToken(clause, ts.Diagnostics.Fallthrough_case_in_switch); + } + } + clauses.transformFlags = subtreeTransformFlags | 536870912 /* HasComputedFlags */; + subtreeTransformFlags |= savedSubtreeTransformFlags; + } + function bindCaseClause(node) { + var saveCurrentFlow = currentFlow; + currentFlow = preSwitchCaseFlow; + bind(node.expression); + currentFlow = saveCurrentFlow; + bindEach(node.statements); + } + function pushActiveLabel(name, breakTarget, continueTarget) { + var activeLabel = { + name: name, + breakTarget: breakTarget, + continueTarget: continueTarget, + referenced: false + }; + (activeLabels || (activeLabels = [])).push(activeLabel); + return activeLabel; + } + function popActiveLabel() { + activeLabels.pop(); + } + function bindLabeledStatement(node) { + var preStatementLabel = createLoopLabel(); + var postStatementLabel = createBranchLabel(); + bind(node.label); + addAntecedent(preStatementLabel, currentFlow); + var activeLabel = pushActiveLabel(node.label.escapedText, postStatementLabel, preStatementLabel); + bind(node.statement); + popActiveLabel(); + if (!activeLabel.referenced && !options.allowUnusedLabels) { + errorOrSuggestionOnNode(ts.unusedLabelIsError(options), node.label, ts.Diagnostics.Unused_label); + } + if (!node.statement || node.statement.kind !== 223 /* DoStatement */) { + // do statement sets current flow inside bindDoStatement + addAntecedent(postStatementLabel, currentFlow); + currentFlow = finishFlowLabel(postStatementLabel); + } + } + function bindDestructuringTargetFlow(node) { + if (node.kind === 204 /* BinaryExpression */ && node.operatorToken.kind === 59 /* EqualsToken */) { + bindAssignmentTargetFlow(node.left); + } + else { + bindAssignmentTargetFlow(node); + } + } + function bindAssignmentTargetFlow(node) { + if (isNarrowableReference(node)) { + currentFlow = createFlowAssignment(currentFlow, node); + } + else if (node.kind === 187 /* ArrayLiteralExpression */) { + for (var _i = 0, _a = node.elements; _i < _a.length; _i++) { + var e = _a[_i]; + if (e.kind === 208 /* SpreadElement */) { + bindAssignmentTargetFlow(e.expression); + } + else { + bindDestructuringTargetFlow(e); + } + } + } + else if (node.kind === 188 /* ObjectLiteralExpression */) { + for (var _b = 0, _c = node.properties; _b < _c.length; _b++) { + var p = _c[_b]; + if (p.kind === 275 /* PropertyAssignment */) { + bindDestructuringTargetFlow(p.initializer); + } + else if (p.kind === 276 /* ShorthandPropertyAssignment */) { + bindAssignmentTargetFlow(p.name); + } + else if (p.kind === 277 /* SpreadAssignment */) { + bindAssignmentTargetFlow(p.expression); + } + } + } + } + function bindLogicalExpression(node, trueTarget, falseTarget) { + var preRightLabel = createBranchLabel(); + if (node.operatorToken.kind === 54 /* AmpersandAmpersandToken */) { + bindCondition(node.left, preRightLabel, falseTarget); + } + else { + bindCondition(node.left, trueTarget, preRightLabel); + } + currentFlow = finishFlowLabel(preRightLabel); + bind(node.operatorToken); + bindCondition(node.right, trueTarget, falseTarget); + } + function bindPrefixUnaryExpressionFlow(node) { + if (node.operator === 52 /* ExclamationToken */) { + var saveTrueTarget = currentTrueTarget; + currentTrueTarget = currentFalseTarget; + currentFalseTarget = saveTrueTarget; + bindEachChild(node); + currentFalseTarget = currentTrueTarget; + currentTrueTarget = saveTrueTarget; + } + else { + bindEachChild(node); + if (node.operator === 44 /* PlusPlusToken */ || node.operator === 45 /* MinusMinusToken */) { + bindAssignmentTargetFlow(node.operand); + } + } + } + function bindPostfixUnaryExpressionFlow(node) { + bindEachChild(node); + if (node.operator === 44 /* PlusPlusToken */ || node.operator === 45 /* MinusMinusToken */) { + bindAssignmentTargetFlow(node.operand); + } + } + function bindBinaryExpressionFlow(node) { + var operator = node.operatorToken.kind; + if (operator === 54 /* AmpersandAmpersandToken */ || operator === 55 /* BarBarToken */) { + if (isTopLevelLogicalExpression(node)) { + var postExpressionLabel = createBranchLabel(); + bindLogicalExpression(node, postExpressionLabel, postExpressionLabel); + currentFlow = finishFlowLabel(postExpressionLabel); + } + else { + bindLogicalExpression(node, currentTrueTarget, currentFalseTarget); + } + } + else { + bindEachChild(node); + if (ts.isAssignmentOperator(operator) && !ts.isAssignmentTarget(node)) { + bindAssignmentTargetFlow(node.left); + if (operator === 59 /* EqualsToken */ && node.left.kind === 190 /* ElementAccessExpression */) { + var elementAccess = node.left; + if (isNarrowableOperand(elementAccess.expression)) { + currentFlow = createFlowArrayMutation(currentFlow, node); + } + } + } + } + } + function bindDeleteExpressionFlow(node) { + bindEachChild(node); + if (node.expression.kind === 189 /* PropertyAccessExpression */) { + bindAssignmentTargetFlow(node.expression); + } + } + function bindConditionalExpressionFlow(node) { + var trueLabel = createBranchLabel(); + var falseLabel = createBranchLabel(); + var postExpressionLabel = createBranchLabel(); + bindCondition(node.condition, trueLabel, falseLabel); + currentFlow = finishFlowLabel(trueLabel); + bind(node.questionToken); + bind(node.whenTrue); + addAntecedent(postExpressionLabel, currentFlow); + currentFlow = finishFlowLabel(falseLabel); + bind(node.colonToken); + bind(node.whenFalse); + addAntecedent(postExpressionLabel, currentFlow); + currentFlow = finishFlowLabel(postExpressionLabel); + } + function bindInitializedVariableFlow(node) { + var name = !ts.isOmittedExpression(node) ? node.name : undefined; + if (ts.isBindingPattern(name)) { + for (var _i = 0, _a = name.elements; _i < _a.length; _i++) { + var child = _a[_i]; + bindInitializedVariableFlow(child); + } + } + else { + currentFlow = createFlowAssignment(currentFlow, node); + } + } + function bindVariableDeclarationFlow(node) { + bindEachChild(node); + if (node.initializer || ts.isForInOrOfStatement(node.parent.parent)) { + bindInitializedVariableFlow(node); + } + } + function bindJSDocTypeAlias(node) { + node.tagName.parent = node; + if (node.fullName) { + setParentPointers(node, node.fullName); + } + } + function bindCallExpressionFlow(node) { + // If the target of the call expression is a function expression or arrow function we have + // an immediately invoked function expression (IIFE). Initialize the flowNode property to + // the current control flow (which includes evaluation of the IIFE arguments). + var expr = node.expression; + while (expr.kind === 195 /* ParenthesizedExpression */) { + expr = expr.expression; + } + if (expr.kind === 196 /* FunctionExpression */ || expr.kind === 197 /* ArrowFunction */) { + bindEach(node.typeArguments); + bindEach(node.arguments); + bind(node.expression); + } + else { + bindEachChild(node); + } + if (node.expression.kind === 189 /* PropertyAccessExpression */) { + var propertyAccess = node.expression; + if (isNarrowableOperand(propertyAccess.expression) && ts.isPushOrUnshiftIdentifier(propertyAccess.name)) { + currentFlow = createFlowArrayMutation(currentFlow, node); + } + } + } + function getContainerFlags(node) { + switch (node.kind) { + case 209 /* ClassExpression */: + case 240 /* ClassDeclaration */: + case 243 /* EnumDeclaration */: + case 188 /* ObjectLiteralExpression */: + case 168 /* TypeLiteral */: + case 292 /* JSDocTypeLiteral */: + case 268 /* JsxAttributes */: + return 1 /* IsContainer */; + case 241 /* InterfaceDeclaration */: + return 1 /* IsContainer */ | 64 /* IsInterface */; + case 244 /* ModuleDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 181 /* MappedType */: + return 1 /* IsContainer */ | 32 /* HasLocals */; + case 279 /* SourceFile */: + return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */; + case 156 /* MethodDeclaration */: + if (ts.isObjectLiteralOrClassExpressionMethod(node)) { + return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */ | 128 /* IsObjectLiteralOrClassExpressionMethod */; + } + // falls through + case 157 /* Constructor */: + case 239 /* FunctionDeclaration */: + case 155 /* MethodSignature */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 160 /* CallSignature */: + case 293 /* JSDocSignature */: + case 289 /* JSDocFunctionType */: + case 165 /* FunctionType */: + case 161 /* ConstructSignature */: + case 162 /* IndexSignature */: + case 166 /* ConstructorType */: + return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */; + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */ | 16 /* IsFunctionExpression */; + case 245 /* ModuleBlock */: + return 4 /* IsControlFlowContainer */; + case 154 /* PropertyDeclaration */: + return node.initializer ? 4 /* IsControlFlowContainer */ : 0; + case 274 /* CatchClause */: + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + case 246 /* CaseBlock */: + return 2 /* IsBlockScopedContainer */; + case 218 /* Block */: + // do not treat blocks directly inside a function as a block-scoped-container. + // Locals that reside in this block should go to the function locals. Otherwise 'x' + // would not appear to be a redeclaration of a block scoped local in the following + // example: + // + // function foo() { + // var x; + // let x; + // } + // + // If we placed 'var x' into the function locals and 'let x' into the locals of + // the block, then there would be no collision. + // + // By not creating a new block-scoped-container here, we ensure that both 'var x' + // and 'let x' go into the Function-container's locals, and we do get a collision + // conflict. + return ts.isFunctionLike(node.parent) ? 0 /* None */ : 2 /* IsBlockScopedContainer */; + } + return 0 /* None */; + } + function addToContainerChain(next) { + if (lastContainer) { + lastContainer.nextContainer = next; + } + lastContainer = next; + } + function declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes) { + switch (container.kind) { + // Modules, source files, and classes need specialized handling for how their + // members are declared (for example, a member of a class will go into a specific + // symbol table depending on if it is static or not). We defer to specialized + // handlers to take care of declaring these child members. + case 244 /* ModuleDeclaration */: + return declareModuleMember(node, symbolFlags, symbolExcludes); + case 279 /* SourceFile */: + return declareSourceFileMember(node, symbolFlags, symbolExcludes); + case 209 /* ClassExpression */: + case 240 /* ClassDeclaration */: + return declareClassMember(node, symbolFlags, symbolExcludes); + case 243 /* EnumDeclaration */: + return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); + case 168 /* TypeLiteral */: + case 292 /* JSDocTypeLiteral */: + case 188 /* ObjectLiteralExpression */: + case 241 /* InterfaceDeclaration */: + case 268 /* JsxAttributes */: + // Interface/Object-types always have their children added to the 'members' of + // their container. They are only accessible through an instance of their + // container, and are never in scope otherwise (even inside the body of the + // object / type / interface declaring them). An exception is type parameters, + // which are in scope without qualification (similar to 'locals'). + return declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes); + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 293 /* JSDocSignature */: + case 162 /* IndexSignature */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 289 /* JSDocFunctionType */: + case 304 /* JSDocTypedefTag */: + case 297 /* JSDocCallbackTag */: + case 242 /* TypeAliasDeclaration */: + case 181 /* MappedType */: + // All the children of these container types are never visible through another + // symbol (i.e. through another symbol's 'exports' or 'members'). Instead, + // they're only accessed 'lexically' (i.e. from code that exists underneath + // their container in the tree). To accomplish this, we simply add their declared + // symbol to the 'locals' of the container. These symbols can then be found as + // the type checker walks up the containers, checking them for matching names. + return declareSymbol(container.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes); + } + } + function declareClassMember(node, symbolFlags, symbolExcludes) { + return ts.hasModifier(node, 32 /* Static */) + ? declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes) + : declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes); + } + function declareSourceFileMember(node, symbolFlags, symbolExcludes) { + return ts.isExternalModule(file) + ? declareModuleMember(node, symbolFlags, symbolExcludes) + : declareSymbol(file.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes); + } + function hasExportDeclarations(node) { + var body = node.kind === 279 /* SourceFile */ ? node : node.body; + if (body && (body.kind === 279 /* SourceFile */ || body.kind === 245 /* ModuleBlock */)) { + for (var _i = 0, _a = body.statements; _i < _a.length; _i++) { + var stat = _a[_i]; + if (stat.kind === 255 /* ExportDeclaration */ || stat.kind === 254 /* ExportAssignment */) { + return true; + } + } + } + return false; + } + function setExportContextFlag(node) { + // A declaration source file or ambient module declaration that contains no export declarations (but possibly regular + // declarations with export modifiers) is an export context in which declarations are implicitly exported. + if (node.flags & 4194304 /* Ambient */ && !hasExportDeclarations(node)) { + node.flags |= 32 /* ExportContext */; + } + else { + node.flags &= ~32 /* ExportContext */; + } + } + function bindModuleDeclaration(node) { + setExportContextFlag(node); + if (ts.isAmbientModule(node)) { + if (ts.hasModifier(node, 1 /* Export */)) { + errorOnFirstToken(node, ts.Diagnostics.export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always_visible); + } + if (ts.isModuleAugmentationExternal(node)) { + declareModuleSymbol(node); + } + else { + var pattern = void 0; + if (node.name.kind === 10 /* StringLiteral */) { + var text = node.name.text; + if (ts.hasZeroOrOneAsteriskCharacter(text)) { + pattern = ts.tryParsePattern(text); + } + else { + errorOnFirstToken(node.name, ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, text); + } + } + var symbol = declareSymbolAndAddToSymbolTable(node, 512 /* ValueModule */, 110735 /* ValueModuleExcludes */); + file.patternAmbientModules = ts.append(file.patternAmbientModules, pattern && { pattern: pattern, symbol: symbol }); + } + } + else { + var state = declareModuleSymbol(node); + if (state !== 0 /* NonInstantiated */) { + var symbol = node.symbol; + // if module was already merged with some function, class or non-const enum, treat it as non-const-enum-only + symbol.constEnumOnlyModule = (!(symbol.flags & (16 /* Function */ | 32 /* Class */ | 256 /* RegularEnum */))) + // Current must be `const enum` only + && state === 2 /* ConstEnumOnly */ + // Can't have been set to 'false' in a previous merged symbol. ('undefined' OK) + && symbol.constEnumOnlyModule !== false; + } + } + } + function declareModuleSymbol(node) { + var state = getModuleInstanceState(node); + var instantiated = state !== 0 /* NonInstantiated */; + declareSymbolAndAddToSymbolTable(node, instantiated ? 512 /* ValueModule */ : 1024 /* NamespaceModule */, instantiated ? 110735 /* ValueModuleExcludes */ : 0 /* NamespaceModuleExcludes */); + return state; + } + function bindFunctionOrConstructorType(node) { + // For a given function symbol "<...>(...) => T" we want to generate a symbol identical + // to the one we would get for: { <...>(...): T } + // + // We do that by making an anonymous type literal symbol, and then setting the function + // symbol as its sole member. To the rest of the system, this symbol will be indistinguishable + // from an actual type literal symbol you would have gotten had you used the long form. + var symbol = createSymbol(131072 /* Signature */, getDeclarationName(node)); // TODO: GH#18217 + addDeclarationToSymbol(symbol, node, 131072 /* Signature */); + var typeLiteralSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */); + addDeclarationToSymbol(typeLiteralSymbol, node, 2048 /* TypeLiteral */); + typeLiteralSymbol.members = ts.createSymbolTable(); + typeLiteralSymbol.members.set(symbol.escapedName, symbol); + } + function bindObjectLiteralExpression(node) { + var ElementKind; + (function (ElementKind) { + ElementKind[ElementKind["Property"] = 1] = "Property"; + ElementKind[ElementKind["Accessor"] = 2] = "Accessor"; + })(ElementKind || (ElementKind = {})); + if (inStrictMode) { + var seen = ts.createUnderscoreEscapedMap(); + for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { + var prop = _a[_i]; + if (prop.kind === 277 /* SpreadAssignment */ || prop.name.kind !== 72 /* Identifier */) { + continue; + } + var identifier = prop.name; + // ECMA-262 11.1.5 Object Initializer + // If previous is not undefined then throw a SyntaxError exception if any of the following conditions are true + // a.This production is contained in strict code and IsDataDescriptor(previous) is true and + // IsDataDescriptor(propId.descriptor) is true. + // b.IsDataDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true. + // c.IsAccessorDescriptor(previous) is true and IsDataDescriptor(propId.descriptor) is true. + // d.IsAccessorDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true + // and either both previous and propId.descriptor have[[Get]] fields or both previous and propId.descriptor have[[Set]] fields + var currentKind = prop.kind === 275 /* PropertyAssignment */ || prop.kind === 276 /* ShorthandPropertyAssignment */ || prop.kind === 156 /* MethodDeclaration */ + ? 1 /* Property */ + : 2 /* Accessor */; + var existingKind = seen.get(identifier.escapedText); + if (!existingKind) { + seen.set(identifier.escapedText, currentKind); + continue; + } + if (currentKind === 1 /* Property */ && existingKind === 1 /* Property */) { + var span = ts.getErrorSpanForNode(file, identifier); + file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, ts.Diagnostics.An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode)); + } + } + } + return bindAnonymousDeclaration(node, 4096 /* ObjectLiteral */, "__object" /* Object */); + } + function bindJsxAttributes(node) { + return bindAnonymousDeclaration(node, 4096 /* ObjectLiteral */, "__jsxAttributes" /* JSXAttributes */); + } + function bindJsxAttribute(node, symbolFlags, symbolExcludes) { + return declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes); + } + function bindAnonymousDeclaration(node, symbolFlags, name) { + var symbol = createSymbol(symbolFlags, name); + if (symbolFlags & (8 /* EnumMember */ | 106500 /* ClassMember */)) { + symbol.parent = container.symbol; + } + addDeclarationToSymbol(symbol, node, symbolFlags); + return symbol; + } + function bindBlockScopedDeclaration(node, symbolFlags, symbolExcludes) { + switch (blockScopeContainer.kind) { + case 244 /* ModuleDeclaration */: + declareModuleMember(node, symbolFlags, symbolExcludes); + break; + case 279 /* SourceFile */: + if (ts.isExternalOrCommonJsModule(container)) { + declareModuleMember(node, symbolFlags, symbolExcludes); + break; + } + // falls through + default: + if (!blockScopeContainer.locals) { + blockScopeContainer.locals = ts.createSymbolTable(); + addToContainerChain(blockScopeContainer); + } + declareSymbol(blockScopeContainer.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes); + } + } + function delayedBindJSDocTypedefTag() { + if (!delayedTypeAliases) { + return; + } + var saveContainer = container; + var saveLastContainer = lastContainer; + var saveBlockScopeContainer = blockScopeContainer; + var saveParent = parent; + var saveCurrentFlow = currentFlow; + for (var _i = 0, delayedTypeAliases_1 = delayedTypeAliases; _i < delayedTypeAliases_1.length; _i++) { + var typeAlias = delayedTypeAliases_1[_i]; + var host = ts.getJSDocHost(typeAlias); + container = ts.findAncestor(host.parent, function (n) { return !!(getContainerFlags(n) & 1 /* IsContainer */); }) || file; + blockScopeContainer = ts.getEnclosingBlockScopeContainer(host) || file; + currentFlow = { flags: 2 /* Start */ }; + parent = typeAlias; + bind(typeAlias.typeExpression); + if (!typeAlias.fullName || typeAlias.fullName.kind === 72 /* Identifier */) { + parent = typeAlias.parent; + bindBlockScopedDeclaration(typeAlias, 524288 /* TypeAlias */, 67897832 /* TypeAliasExcludes */); + } + else { + bind(typeAlias.fullName); + } + } + container = saveContainer; + lastContainer = saveLastContainer; + blockScopeContainer = saveBlockScopeContainer; + parent = saveParent; + currentFlow = saveCurrentFlow; + } + // The binder visits every node in the syntax tree so it is a convenient place to perform a single localized + // check for reserved words used as identifiers in strict mode code. + function checkStrictModeIdentifier(node) { + if (inStrictMode && + node.originalKeywordKind >= 109 /* FirstFutureReservedWord */ && + node.originalKeywordKind <= 117 /* LastFutureReservedWord */ && + !ts.isIdentifierName(node) && + !(node.flags & 4194304 /* Ambient */)) { + // Report error only if there are no parse errors in file + if (!file.parseDiagnostics.length) { + file.bindDiagnostics.push(createDiagnosticForNode(node, getStrictModeIdentifierMessage(node), ts.declarationNameToString(node))); + } + } + } + function getStrictModeIdentifierMessage(node) { + // Provide specialized messages to help the user understand why we think they're in + // strict mode. + if (ts.getContainingClass(node)) { + return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode; + } + if (file.externalModuleIndicator) { + return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode; + } + return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode; + } + function checkStrictModeBinaryExpression(node) { + if (inStrictMode && ts.isLeftHandSideExpression(node.left) && ts.isAssignmentOperator(node.operatorToken.kind)) { + // ECMA 262 (Annex C) The identifier eval or arguments may not appear as the LeftHandSideExpression of an + // Assignment operator(11.13) or of a PostfixExpression(11.3) + checkStrictModeEvalOrArguments(node, node.left); + } + } + function checkStrictModeCatchClause(node) { + // It is a SyntaxError if a TryStatement with a Catch occurs within strict code and the Identifier of the + // Catch production is eval or arguments + if (inStrictMode && node.variableDeclaration) { + checkStrictModeEvalOrArguments(node, node.variableDeclaration.name); + } + } + function checkStrictModeDeleteExpression(node) { + // Grammar checking + if (inStrictMode && node.expression.kind === 72 /* Identifier */) { + // When a delete operator occurs within strict mode code, a SyntaxError is thrown if its + // UnaryExpression is a direct reference to a variable, function argument, or function name + var span = ts.getErrorSpanForNode(file, node.expression); + file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, ts.Diagnostics.delete_cannot_be_called_on_an_identifier_in_strict_mode)); + } + } + function isEvalOrArgumentsIdentifier(node) { + return ts.isIdentifier(node) && (node.escapedText === "eval" || node.escapedText === "arguments"); + } + function checkStrictModeEvalOrArguments(contextNode, name) { + if (name && name.kind === 72 /* Identifier */) { + var identifier = name; + if (isEvalOrArgumentsIdentifier(identifier)) { + // We check first if the name is inside class declaration or class expression; if so give explicit message + // otherwise report generic error message. + var span = ts.getErrorSpanForNode(file, name); + file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, getStrictModeEvalOrArgumentsMessage(contextNode), ts.idText(identifier))); + } + } + } + function getStrictModeEvalOrArgumentsMessage(node) { + // Provide specialized messages to help the user understand why we think they're in + // strict mode. + if (ts.getContainingClass(node)) { + return ts.Diagnostics.Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode; + } + if (file.externalModuleIndicator) { + return ts.Diagnostics.Invalid_use_of_0_Modules_are_automatically_in_strict_mode; + } + return ts.Diagnostics.Invalid_use_of_0_in_strict_mode; + } + function checkStrictModeFunctionName(node) { + if (inStrictMode) { + // It is a SyntaxError if the identifier eval or arguments appears within a FormalParameterList of a strict mode FunctionDeclaration or FunctionExpression (13.1)) + checkStrictModeEvalOrArguments(node, node.name); + } + } + function getStrictModeBlockScopeFunctionDeclarationMessage(node) { + // Provide specialized messages to help the user understand why we think they're in + // strict mode. + if (ts.getContainingClass(node)) { + return ts.Diagnostics.Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_definitions_are_automatically_in_strict_mode; + } + if (file.externalModuleIndicator) { + return ts.Diagnostics.Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_are_automatically_in_strict_mode; + } + return ts.Diagnostics.Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5; + } + function checkStrictModeFunctionDeclaration(node) { + if (languageVersion < 2 /* ES2015 */) { + // Report error if function is not top level function declaration + if (blockScopeContainer.kind !== 279 /* SourceFile */ && + blockScopeContainer.kind !== 244 /* ModuleDeclaration */ && + !ts.isFunctionLike(blockScopeContainer)) { + // We check first if the name is inside class declaration or class expression; if so give explicit message + // otherwise report generic error message. + var errorSpan = ts.getErrorSpanForNode(file, node); + file.bindDiagnostics.push(ts.createFileDiagnostic(file, errorSpan.start, errorSpan.length, getStrictModeBlockScopeFunctionDeclarationMessage(node))); + } + } + } + function checkStrictModeNumericLiteral(node) { + if (inStrictMode && node.numericLiteralFlags & 32 /* Octal */) { + file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Octal_literals_are_not_allowed_in_strict_mode)); + } + } + function checkStrictModePostfixUnaryExpression(node) { + // Grammar checking + // The identifier eval or arguments may not appear as the LeftHandSideExpression of an + // Assignment operator(11.13) or of a PostfixExpression(11.3) or as the UnaryExpression + // operated upon by a Prefix Increment(11.4.4) or a Prefix Decrement(11.4.5) operator. + if (inStrictMode) { + checkStrictModeEvalOrArguments(node, node.operand); + } + } + function checkStrictModePrefixUnaryExpression(node) { + // Grammar checking + if (inStrictMode) { + if (node.operator === 44 /* PlusPlusToken */ || node.operator === 45 /* MinusMinusToken */) { + checkStrictModeEvalOrArguments(node, node.operand); + } + } + } + function checkStrictModeWithStatement(node) { + // Grammar checking for withStatement + if (inStrictMode) { + errorOnFirstToken(node, ts.Diagnostics.with_statements_are_not_allowed_in_strict_mode); + } + } + function checkStrictModeLabeledStatement(node) { + // Grammar checking for labeledStatement + if (inStrictMode && options.target >= 2 /* ES2015 */) { + if (ts.isDeclarationStatement(node.statement) || ts.isVariableStatement(node.statement)) { + errorOnFirstToken(node.label, ts.Diagnostics.A_label_is_not_allowed_here); + } + } + } + function errorOnFirstToken(node, message, arg0, arg1, arg2) { + var span = ts.getSpanOfTokenAtPosition(file, node.pos); + file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, message, arg0, arg1, arg2)); + } + function errorOrSuggestionOnNode(isError, node, message) { + errorOrSuggestionOnRange(isError, node, node, message); + } + function errorOrSuggestionOnRange(isError, startNode, endNode, message) { + addErrorOrSuggestionDiagnostic(isError, { pos: ts.getTokenPosOfNode(startNode, file), end: endNode.end }, message); + } + function addErrorOrSuggestionDiagnostic(isError, range, message) { + var diag = ts.createFileDiagnostic(file, range.pos, range.end - range.pos, message); + if (isError) { + file.bindDiagnostics.push(diag); + } + else { + file.bindSuggestionDiagnostics = ts.append(file.bindSuggestionDiagnostics, __assign({}, diag, { category: ts.DiagnosticCategory.Suggestion })); + } + } + function bind(node) { + if (!node) { + return; + } + node.parent = parent; + var saveInStrictMode = inStrictMode; + // Even though in the AST the jsdoc @typedef node belongs to the current node, + // its symbol might be in the same scope with the current node's symbol. Consider: + // + // /** @typedef {string | number} MyType */ + // function foo(); + // + // Here the current node is "foo", which is a container, but the scope of "MyType" should + // not be inside "foo". Therefore we always bind @typedef before bind the parent node, + // and skip binding this tag later when binding all the other jsdoc tags. + // First we bind declaration nodes to a symbol if possible. We'll both create a symbol + // and then potentially add the symbol to an appropriate symbol table. Possible + // destination symbol tables are: + // + // 1) The 'exports' table of the current container's symbol. + // 2) The 'members' table of the current container's symbol. + // 3) The 'locals' table of the current container. + // + // However, not all symbols will end up in any of these tables. 'Anonymous' symbols + // (like TypeLiterals for example) will not be put in any table. + bindWorker(node); + // Then we recurse into the children of the node to bind them as well. For certain + // symbols we do specialized work when we recurse. For example, we'll keep track of + // the current 'container' node when it changes. This helps us know which symbol table + // a local should go into for example. Since terminal nodes are known not to have + // children, as an optimization we don't process those. + if (node.kind > 147 /* LastToken */) { + var saveParent = parent; + parent = node; + var containerFlags = getContainerFlags(node); + if (containerFlags === 0 /* None */) { + bindChildren(node); + } + else { + bindContainer(node, containerFlags); + } + parent = saveParent; + } + else if (!skipTransformFlagAggregation && (node.transformFlags & 536870912 /* HasComputedFlags */) === 0) { + subtreeTransformFlags |= computeTransformFlagsForNode(node, 0); + var saveParent = parent; + if (node.kind === 1 /* EndOfFileToken */) + parent = node; + bindJSDoc(node); + parent = saveParent; + } + inStrictMode = saveInStrictMode; + } + function bindJSDoc(node) { + if (ts.hasJSDocNodes(node)) { + if (ts.isInJSFile(node)) { + for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { + var j = _a[_i]; + bind(j); + } + } + else { + for (var _b = 0, _c = node.jsDoc; _b < _c.length; _b++) { + var j = _c[_b]; + setParentPointers(node, j); + } + } + } + } + function updateStrictModeStatementList(statements) { + if (!inStrictMode) { + for (var _i = 0, statements_1 = statements; _i < statements_1.length; _i++) { + var statement = statements_1[_i]; + if (!ts.isPrologueDirective(statement)) { + return; + } + if (isUseStrictPrologueDirective(statement)) { + inStrictMode = true; + return; + } + } + } + } + /// Should be called only on prologue directives (isPrologueDirective(node) should be true) + function isUseStrictPrologueDirective(node) { + var nodeText = ts.getSourceTextOfNodeFromSourceFile(file, node.expression); + // Note: the node text must be exactly "use strict" or 'use strict'. It is not ok for the + // string to contain unicode escapes (as per ES5). + return nodeText === '"use strict"' || nodeText === "'use strict'"; + } + function bindWorker(node) { + switch (node.kind) { + /* Strict mode checks */ + case 72 /* Identifier */: + // for typedef type names with namespaces, bind the new jsdoc type symbol here + // because it requires all containing namespaces to be in effect, namely the + // current "blockScopeContainer" needs to be set to its immediate namespace parent. + if (node.isInJSDocNamespace) { + var parentNode = node.parent; + while (parentNode && !ts.isJSDocTypeAlias(parentNode)) { + parentNode = parentNode.parent; + } + bindBlockScopedDeclaration(parentNode, 524288 /* TypeAlias */, 67897832 /* TypeAliasExcludes */); + break; + } + // falls through + case 100 /* ThisKeyword */: + if (currentFlow && (ts.isExpression(node) || parent.kind === 276 /* ShorthandPropertyAssignment */)) { + node.flowNode = currentFlow; + } + return checkStrictModeIdentifier(node); + case 189 /* PropertyAccessExpression */: + case 190 /* ElementAccessExpression */: + if (currentFlow && isNarrowableReference(node)) { + node.flowNode = currentFlow; + } + if (ts.isSpecialPropertyDeclaration(node)) { + bindSpecialPropertyDeclaration(node); + } + if (ts.isInJSFile(node) && + file.commonJsModuleIndicator && + ts.isModuleExportsPropertyAccessExpression(node) && + !lookupSymbolForNameWorker(blockScopeContainer, "module")) { + declareSymbol(file.locals, /*parent*/ undefined, node.expression, 1 /* FunctionScopedVariable */ | 134217728 /* ModuleExports */, 67220414 /* FunctionScopedVariableExcludes */); + } + break; + case 204 /* BinaryExpression */: + var specialKind = ts.getAssignmentDeclarationKind(node); + switch (specialKind) { + case 1 /* ExportsProperty */: + bindExportsPropertyAssignment(node); + break; + case 2 /* ModuleExports */: + bindModuleExportsAssignment(node); + break; + case 3 /* PrototypeProperty */: + bindPrototypePropertyAssignment(node.left, node); + break; + case 6 /* Prototype */: + bindPrototypeAssignment(node); + break; + case 4 /* ThisProperty */: + bindThisPropertyAssignment(node); + break; + case 5 /* Property */: + bindSpecialPropertyAssignment(node); + break; + case 0 /* None */: + // Nothing to do + break; + default: + ts.Debug.fail("Unknown binary expression special property assignment kind"); + } + return checkStrictModeBinaryExpression(node); + case 274 /* CatchClause */: + return checkStrictModeCatchClause(node); + case 198 /* DeleteExpression */: + return checkStrictModeDeleteExpression(node); + case 8 /* NumericLiteral */: + return checkStrictModeNumericLiteral(node); + case 203 /* PostfixUnaryExpression */: + return checkStrictModePostfixUnaryExpression(node); + case 202 /* PrefixUnaryExpression */: + return checkStrictModePrefixUnaryExpression(node); + case 231 /* WithStatement */: + return checkStrictModeWithStatement(node); + case 233 /* LabeledStatement */: + return checkStrictModeLabeledStatement(node); + case 178 /* ThisType */: + seenThisKeyword = true; + return; + case 163 /* TypePredicate */: + break; // Binding the children will handle everything + case 150 /* TypeParameter */: + return bindTypeParameter(node); + case 151 /* Parameter */: + return bindParameter(node); + case 237 /* VariableDeclaration */: + return bindVariableDeclarationOrBindingElement(node); + case 186 /* BindingElement */: + node.flowNode = currentFlow; + return bindVariableDeclarationOrBindingElement(node); + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + return bindPropertyWorker(node); + case 275 /* PropertyAssignment */: + case 276 /* ShorthandPropertyAssignment */: + return bindPropertyOrMethodOrAccessor(node, 4 /* Property */, 0 /* PropertyExcludes */); + case 278 /* EnumMember */: + return bindPropertyOrMethodOrAccessor(node, 8 /* EnumMember */, 68008959 /* EnumMemberExcludes */); + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 162 /* IndexSignature */: + return declareSymbolAndAddToSymbolTable(node, 131072 /* Signature */, 0 /* None */); + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + // If this is an ObjectLiteralExpression method, then it sits in the same space + // as other properties in the object literal. So we use SymbolFlags.PropertyExcludes + // so that it will conflict with any other object literal members with the same + // name. + return bindPropertyOrMethodOrAccessor(node, 8192 /* Method */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), ts.isObjectLiteralMethod(node) ? 0 /* PropertyExcludes */ : 67212223 /* MethodExcludes */); + case 239 /* FunctionDeclaration */: + return bindFunctionDeclaration(node); + case 157 /* Constructor */: + return declareSymbolAndAddToSymbolTable(node, 16384 /* Constructor */, /*symbolExcludes:*/ 0 /* None */); + case 158 /* GetAccessor */: + return bindPropertyOrMethodOrAccessor(node, 32768 /* GetAccessor */, 67154879 /* GetAccessorExcludes */); + case 159 /* SetAccessor */: + return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 67187647 /* SetAccessorExcludes */); + case 165 /* FunctionType */: + case 289 /* JSDocFunctionType */: + case 293 /* JSDocSignature */: + case 166 /* ConstructorType */: + return bindFunctionOrConstructorType(node); + case 168 /* TypeLiteral */: + case 292 /* JSDocTypeLiteral */: + case 181 /* MappedType */: + return bindAnonymousTypeWorker(node); + case 188 /* ObjectLiteralExpression */: + return bindObjectLiteralExpression(node); + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + return bindFunctionExpression(node); + case 191 /* CallExpression */: + var assignmentKind = ts.getAssignmentDeclarationKind(node); + switch (assignmentKind) { + case 7 /* ObjectDefinePropertyValue */: + return bindObjectDefinePropertyAssignment(node); + case 8 /* ObjectDefinePropertyExports */: + return bindObjectDefinePropertyExport(node); + case 9 /* ObjectDefinePrototypeProperty */: + return bindObjectDefinePrototypeProperty(node); + case 0 /* None */: + break; // Nothing to do + default: + return ts.Debug.fail("Unknown call expression assignment declaration kind"); + } + if (ts.isInJSFile(node)) { + bindCallExpression(node); + } + break; + // Members of classes, interfaces, and modules + case 209 /* ClassExpression */: + case 240 /* ClassDeclaration */: + // All classes are automatically in strict mode in ES6. + inStrictMode = true; + return bindClassLikeDeclaration(node); + case 241 /* InterfaceDeclaration */: + return bindBlockScopedDeclaration(node, 64 /* Interface */, 67897736 /* InterfaceExcludes */); + case 242 /* TypeAliasDeclaration */: + return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 67897832 /* TypeAliasExcludes */); + case 243 /* EnumDeclaration */: + return bindEnumDeclaration(node); + case 244 /* ModuleDeclaration */: + return bindModuleDeclaration(node); + // Jsx-attributes + case 268 /* JsxAttributes */: + return bindJsxAttributes(node); + case 267 /* JsxAttribute */: + return bindJsxAttribute(node, 4 /* Property */, 0 /* PropertyExcludes */); + // Imports and exports + case 248 /* ImportEqualsDeclaration */: + case 251 /* NamespaceImport */: + case 253 /* ImportSpecifier */: + case 257 /* ExportSpecifier */: + return declareSymbolAndAddToSymbolTable(node, 2097152 /* Alias */, 2097152 /* AliasExcludes */); + case 247 /* NamespaceExportDeclaration */: + return bindNamespaceExportDeclaration(node); + case 250 /* ImportClause */: + return bindImportClause(node); + case 255 /* ExportDeclaration */: + return bindExportDeclaration(node); + case 254 /* ExportAssignment */: + return bindExportAssignment(node); + case 279 /* SourceFile */: + updateStrictModeStatementList(node.statements); + return bindSourceFileIfExternalModule(); + case 218 /* Block */: + if (!ts.isFunctionLike(node.parent)) { + return; + } + // falls through + case 245 /* ModuleBlock */: + return updateStrictModeStatementList(node.statements); + case 299 /* JSDocParameterTag */: + if (node.parent.kind === 293 /* JSDocSignature */) { + return bindParameter(node); + } + if (node.parent.kind !== 292 /* JSDocTypeLiteral */) { + break; + } + // falls through + case 305 /* JSDocPropertyTag */: + var propTag = node; + var flags = propTag.isBracketed || propTag.typeExpression && propTag.typeExpression.type.kind === 288 /* JSDocOptionalType */ ? + 4 /* Property */ | 16777216 /* Optional */ : + 4 /* Property */; + return declareSymbolAndAddToSymbolTable(propTag, flags, 0 /* PropertyExcludes */); + case 304 /* JSDocTypedefTag */: + case 297 /* JSDocCallbackTag */: + return (delayedTypeAliases || (delayedTypeAliases = [])).push(node); + } + } + function bindPropertyWorker(node) { + return bindPropertyOrMethodOrAccessor(node, 4 /* Property */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), 0 /* PropertyExcludes */); + } + function bindAnonymousTypeWorker(node) { + return bindAnonymousDeclaration(node, 2048 /* TypeLiteral */, "__type" /* Type */); + } + function bindSourceFileIfExternalModule() { + setExportContextFlag(file); + if (ts.isExternalModule(file)) { + bindSourceFileAsExternalModule(); + } + else if (ts.isJsonSourceFile(file)) { + bindSourceFileAsExternalModule(); + // Create symbol equivalent for the module.exports = {} + var originalSymbol = file.symbol; + declareSymbol(file.symbol.exports, file.symbol, file, 4 /* Property */, 67108863 /* All */); + file.symbol = originalSymbol; + } + } + function bindSourceFileAsExternalModule() { + bindAnonymousDeclaration(file, 512 /* ValueModule */, "\"" + ts.removeFileExtension(file.fileName) + "\""); + } + function bindExportAssignment(node) { + if (!container.symbol || !container.symbol.exports) { + // Export assignment in some sort of block construct + bindAnonymousDeclaration(node, 2097152 /* Alias */, getDeclarationName(node)); + } + else { + var flags = ts.exportAssignmentIsAlias(node) + // An export default clause with an EntityNameExpression or a class expression exports all meanings of that identifier or expression; + ? 2097152 /* Alias */ + // An export default clause with any other expression exports a value + : 4 /* Property */; + // If there is an `export default x;` alias declaration, can't `export default` anything else. + // (In contrast, you can still have `export default function f() {}` and `export default interface I {}`.) + var symbol = declareSymbol(container.symbol.exports, container.symbol, node, flags, 67108863 /* All */); + if (node.isExportEquals) { + // Will be an error later, since the module already has other exports. Just make sure this has a valueDeclaration set. + setValueDeclaration(symbol, node); + } + } + } + function bindNamespaceExportDeclaration(node) { + if (node.modifiers && node.modifiers.length) { + file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Modifiers_cannot_appear_here)); + } + var diag = !ts.isSourceFile(node.parent) ? ts.Diagnostics.Global_module_exports_may_only_appear_at_top_level + : !ts.isExternalModule(node.parent) ? ts.Diagnostics.Global_module_exports_may_only_appear_in_module_files + : !node.parent.isDeclarationFile ? ts.Diagnostics.Global_module_exports_may_only_appear_in_declaration_files + : undefined; + if (diag) { + file.bindDiagnostics.push(createDiagnosticForNode(node, diag)); + } + else { + file.symbol.globalExports = file.symbol.globalExports || ts.createSymbolTable(); + declareSymbol(file.symbol.globalExports, file.symbol, node, 2097152 /* Alias */, 2097152 /* AliasExcludes */); + } + } + function bindExportDeclaration(node) { + if (!container.symbol || !container.symbol.exports) { + // Export * in some sort of block construct + bindAnonymousDeclaration(node, 8388608 /* ExportStar */, getDeclarationName(node)); + } + else if (!node.exportClause) { + // All export * declarations are collected in an __export symbol + declareSymbol(container.symbol.exports, container.symbol, node, 8388608 /* ExportStar */, 0 /* None */); + } + } + function bindImportClause(node) { + if (node.name) { + declareSymbolAndAddToSymbolTable(node, 2097152 /* Alias */, 2097152 /* AliasExcludes */); + } + } + function setCommonJsModuleIndicator(node) { + if (file.externalModuleIndicator) { + return false; + } + if (!file.commonJsModuleIndicator) { + file.commonJsModuleIndicator = node; + bindSourceFileAsExternalModule(); + } + return true; + } + function bindObjectDefinePropertyExport(node) { + if (!setCommonJsModuleIndicator(node)) { + return; + } + var symbol = forEachIdentifierInEntityName(node.arguments[0], /*parent*/ undefined, function (id, symbol) { + if (symbol) { + addDeclarationToSymbol(symbol, id, 1536 /* Module */ | 67108864 /* Assignment */); + } + return symbol; + }); + if (symbol) { + var flags = 4 /* Property */ | 1048576 /* ExportValue */; + declareSymbol(symbol.exports, symbol, node, flags, 0 /* None */); + } + } + function bindExportsPropertyAssignment(node) { + // When we create a property via 'exports.foo = bar', the 'exports.foo' property access + // expression is the declaration + if (!setCommonJsModuleIndicator(node)) { + return; + } + var lhs = node.left; + var symbol = forEachIdentifierInEntityName(lhs.expression, /*parent*/ undefined, function (id, symbol) { + if (symbol) { + addDeclarationToSymbol(symbol, id, 1536 /* Module */ | 67108864 /* Assignment */); + } + return symbol; + }); + if (symbol) { + var flags = ts.isClassExpression(node.right) ? + 4 /* Property */ | 1048576 /* ExportValue */ | 32 /* Class */ : + 4 /* Property */ | 1048576 /* ExportValue */; + declareSymbol(symbol.exports, symbol, lhs, flags, 0 /* None */); + } + } + function bindModuleExportsAssignment(node) { + // A common practice in node modules is to set 'export = module.exports = {}', this ensures that 'exports' + // is still pointing to 'module.exports'. + // We do not want to consider this as 'export=' since a module can have only one of these. + // Similarly we do not want to treat 'module.exports = exports' as an 'export='. + if (!setCommonJsModuleIndicator(node)) { + return; + } + var assignedExpression = ts.getRightMostAssignedExpression(node.right); + if (ts.isEmptyObjectLiteral(assignedExpression) || container === file && isExportsOrModuleExportsOrAlias(file, assignedExpression)) { + return; + } + // 'module.exports = expr' assignment + var flags = ts.exportAssignmentIsAlias(node) + ? 2097152 /* Alias */ + : 4 /* Property */ | 1048576 /* ExportValue */ | 512 /* ValueModule */; + declareSymbol(file.symbol.exports, file.symbol, node, flags | 67108864 /* Assignment */, 0 /* None */); + } + function bindThisPropertyAssignment(node) { + ts.Debug.assert(ts.isInJSFile(node)); + var thisContainer = ts.getThisContainer(node, /*includeArrowFunctions*/ false); + switch (thisContainer.kind) { + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + var constructorSymbol = thisContainer.symbol; + // For `f.prototype.m = function() { this.x = 0; }`, `this.x = 0` should modify `f`'s members, not the function expression. + if (ts.isBinaryExpression(thisContainer.parent) && thisContainer.parent.operatorToken.kind === 59 /* EqualsToken */) { + var l = thisContainer.parent.left; + if (ts.isPropertyAccessEntityNameExpression(l) && ts.isPrototypeAccess(l.expression)) { + constructorSymbol = lookupSymbolForPropertyAccess(l.expression.expression, thisParentContainer); + } + } + if (constructorSymbol) { + // Declare a 'member' if the container is an ES5 class or ES6 constructor + constructorSymbol.members = constructorSymbol.members || ts.createSymbolTable(); + // It's acceptable for multiple 'this' assignments of the same identifier to occur + declareSymbol(constructorSymbol.members, constructorSymbol, node, 4 /* Property */, 0 /* PropertyExcludes */ & ~4 /* Property */); + } + break; + case 157 /* Constructor */: + case 154 /* PropertyDeclaration */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + // this.foo assignment in a JavaScript class + // Bind this property to the containing class + var containingClass = thisContainer.parent; + var symbolTable = ts.hasModifier(thisContainer, 32 /* Static */) ? containingClass.symbol.exports : containingClass.symbol.members; + declareSymbol(symbolTable, containingClass.symbol, node, 4 /* Property */, 0 /* None */, /*isReplaceableByMethod*/ true); + break; + case 279 /* SourceFile */: + // this.foo assignment in a source file + // Do not bind. It would be nice to support this someday though. + break; + default: + ts.Debug.fail(ts.Debug.showSyntaxKind(thisContainer)); + } + } + function bindSpecialPropertyDeclaration(node) { + if (node.expression.kind === 100 /* ThisKeyword */) { + bindThisPropertyAssignment(node); + } + else if (ts.isPropertyAccessEntityNameExpression(node) && node.parent.parent.kind === 279 /* SourceFile */) { + if (ts.isPrototypeAccess(node.expression)) { + bindPrototypePropertyAssignment(node, node.parent); + } + else { + bindStaticPropertyAssignment(node); + } + } + } + /** For `x.prototype = { p, ... }`, declare members p,... if `x` is function/class/{}, or not declared. */ + function bindPrototypeAssignment(node) { + node.left.parent = node; + node.right.parent = node; + var lhs = node.left; + bindPropertyAssignment(lhs.expression, lhs, /*isPrototypeProperty*/ false); + } + function bindObjectDefinePrototypeProperty(node) { + var namespaceSymbol = lookupSymbolForPropertyAccess(node.arguments[0].expression); + bindPotentiallyNewExpandoMemberToNamespace(node, namespaceSymbol, /*isPrototypeProperty*/ true); + } + /** + * For `x.prototype.y = z`, declare a member `y` on `x` if `x` is a function or class, or not declared. + * Note that jsdoc preceding an ExpressionStatement like `x.prototype.y;` is also treated as a declaration. + */ + function bindPrototypePropertyAssignment(lhs, parent) { + // Look up the function in the local scope, since prototype assignments should + // follow the function declaration + var classPrototype = lhs.expression; + var constructorFunction = classPrototype.expression; + // Fix up parent pointers since we're going to use these nodes before we bind into them + lhs.parent = parent; + constructorFunction.parent = classPrototype; + classPrototype.parent = lhs; + bindPropertyAssignment(constructorFunction, lhs, /*isPrototypeProperty*/ true); + } + function bindObjectDefinePropertyAssignment(node) { + var namespaceSymbol = lookupSymbolForPropertyAccess(node.arguments[0]); + var isToplevel = node.parent.parent.kind === 279 /* SourceFile */; + namespaceSymbol = bindPotentiallyMissingNamespaces(namespaceSymbol, node.arguments[0], isToplevel, /*isPrototypeProperty*/ false); + bindPotentiallyNewExpandoMemberToNamespace(node, namespaceSymbol, /*isPrototypeProperty*/ false); + } + function bindSpecialPropertyAssignment(node) { + var lhs = node.left; + // Class declarations in Typescript do not allow property declarations + var parentSymbol = lookupSymbolForPropertyAccess(lhs.expression); + if (!ts.isInJSFile(node) && !ts.isFunctionSymbol(parentSymbol)) { + return; + } + // Fix up parent pointers since we're going to use these nodes before we bind into them + node.left.parent = node; + node.right.parent = node; + if (ts.isIdentifier(lhs.expression) && container === file && isNameOfExportsOrModuleExportsAliasDeclaration(file, lhs.expression)) { + // This can be an alias for the 'exports' or 'module.exports' names, e.g. + // var util = module.exports; + // util.property = function ... + bindExportsPropertyAssignment(node); + } + else { + bindStaticPropertyAssignment(lhs); + } + } + /** + * For nodes like `x.y = z`, declare a member 'y' on 'x' if x is a function (or IIFE) or class or {}, or not declared. + * Also works for expression statements preceded by JSDoc, like / ** @type number * / x.y; + */ + function bindStaticPropertyAssignment(node) { + node.expression.parent = node; + bindPropertyAssignment(node.expression, node, /*isPrototypeProperty*/ false); + } + function bindPotentiallyMissingNamespaces(namespaceSymbol, entityName, isToplevel, isPrototypeProperty) { + if (isToplevel && !isPrototypeProperty && (!namespaceSymbol || !(namespaceSymbol.flags & 1920 /* Namespace */))) { + // make symbols or add declarations for intermediate containers + var flags_1 = 1536 /* Module */ | 67108864 /* Assignment */; + var excludeFlags_1 = 110735 /* ValueModuleExcludes */ & ~67108864 /* Assignment */; + namespaceSymbol = forEachIdentifierInEntityName(entityName, namespaceSymbol, function (id, symbol, parent) { + if (symbol) { + addDeclarationToSymbol(symbol, id, flags_1); + return symbol; + } + else { + var table = parent ? parent.exports : + file.jsGlobalAugmentations || (file.jsGlobalAugmentations = ts.createSymbolTable()); + return declareSymbol(table, parent, id, flags_1, excludeFlags_1); + } + }); + } + return namespaceSymbol; + } + function bindPotentiallyNewExpandoMemberToNamespace(declaration, namespaceSymbol, isPrototypeProperty) { + if (!namespaceSymbol || !isExpandoSymbol(namespaceSymbol)) { + return; + } + // Set up the members collection if it doesn't exist already + var symbolTable = isPrototypeProperty ? + (namespaceSymbol.members || (namespaceSymbol.members = ts.createSymbolTable())) : + (namespaceSymbol.exports || (namespaceSymbol.exports = ts.createSymbolTable())); + var isMethod = ts.isFunctionLikeDeclaration(ts.getAssignedExpandoInitializer(declaration)); + var includes = isMethod ? 8192 /* Method */ : 4 /* Property */; + var excludes = isMethod ? 67212223 /* MethodExcludes */ : 0 /* PropertyExcludes */; + declareSymbol(symbolTable, namespaceSymbol, declaration, includes | 67108864 /* Assignment */, excludes & ~67108864 /* Assignment */); + } + function bindPropertyAssignment(name, propertyAccess, isPrototypeProperty) { + var namespaceSymbol = lookupSymbolForPropertyAccess(name); + var isToplevel = ts.isBinaryExpression(propertyAccess.parent) + ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 279 /* SourceFile */ + : propertyAccess.parent.parent.kind === 279 /* SourceFile */; + namespaceSymbol = bindPotentiallyMissingNamespaces(namespaceSymbol, propertyAccess.expression, isToplevel, isPrototypeProperty); + bindPotentiallyNewExpandoMemberToNamespace(propertyAccess, namespaceSymbol, isPrototypeProperty); + } + /** + * Javascript expando values are: + * - Functions + * - classes + * - namespaces + * - variables initialized with function expressions + * - with class expressions + * - with empty object literals + * - with non-empty object literals if assigned to the prototype property + */ + function isExpandoSymbol(symbol) { + if (symbol.flags & (16 /* Function */ | 32 /* Class */ | 1024 /* NamespaceModule */)) { + return true; + } + var node = symbol.valueDeclaration; + if (node && ts.isCallExpression(node)) { + return !!ts.getAssignedExpandoInitializer(node); + } + var init = !node ? undefined : + ts.isVariableDeclaration(node) ? node.initializer : + ts.isBinaryExpression(node) ? node.right : + ts.isPropertyAccessExpression(node) && ts.isBinaryExpression(node.parent) ? node.parent.right : + undefined; + init = init && ts.getRightMostAssignedExpression(init); + if (init) { + var isPrototypeAssignment = ts.isPrototypeAccess(ts.isVariableDeclaration(node) ? node.name : ts.isBinaryExpression(node) ? node.left : node); + return !!ts.getExpandoInitializer(ts.isBinaryExpression(init) && init.operatorToken.kind === 55 /* BarBarToken */ ? init.right : init, isPrototypeAssignment); + } + return false; + } + function getParentOfBinaryExpression(expr) { + while (ts.isBinaryExpression(expr.parent)) { + expr = expr.parent; + } + return expr.parent; + } + function lookupSymbolForPropertyAccess(node, lookupContainer) { + if (lookupContainer === void 0) { lookupContainer = container; } + if (ts.isIdentifier(node)) { + return lookupSymbolForNameWorker(lookupContainer, node.escapedText); + } + else { + var symbol = lookupSymbolForPropertyAccess(node.expression); + return symbol && symbol.exports && symbol.exports.get(node.name.escapedText); + } + } + function forEachIdentifierInEntityName(e, parent, action) { + if (isExportsOrModuleExportsOrAlias(file, e)) { + return file.symbol; + } + else if (ts.isIdentifier(e)) { + return action(e, lookupSymbolForPropertyAccess(e), parent); + } + else { + var s = forEachIdentifierInEntityName(e.expression, parent, action); + if (!s || !s.exports) + return ts.Debug.fail(); + return action(e.name, s.exports.get(e.name.escapedText), s); + } + } + function bindCallExpression(node) { + // We're only inspecting call expressions to detect CommonJS modules, so we can skip + // this check if we've already seen the module indicator + if (!file.commonJsModuleIndicator && ts.isRequireCall(node, /*checkArgumentIsStringLiteralLike*/ false)) { + setCommonJsModuleIndicator(node); + } + } + function bindClassLikeDeclaration(node) { + if (node.kind === 240 /* ClassDeclaration */) { + bindBlockScopedDeclaration(node, 32 /* Class */, 68008383 /* ClassExcludes */); + } + else { + var bindingName = node.name ? node.name.escapedText : "__class" /* Class */; + bindAnonymousDeclaration(node, 32 /* Class */, bindingName); + // Add name of class expression into the map for semantic classifier + if (node.name) { + classifiableNames.set(node.name.escapedText, true); + } + } + var symbol = node.symbol; + // TypeScript 1.0 spec (April 2014): 8.4 + // Every class automatically contains a static property member named 'prototype', the + // type of which is an instantiation of the class type with type Any supplied as a type + // argument for each type parameter. It is an error to explicitly declare a static + // property member with the name 'prototype'. + // + // Note: we check for this here because this class may be merging into a module. The + // module might have an exported variable called 'prototype'. We can't allow that as + // that would clash with the built-in 'prototype' for the class. + var prototypeSymbol = createSymbol(4 /* Property */ | 4194304 /* Prototype */, "prototype"); + var symbolExport = symbol.exports.get(prototypeSymbol.escapedName); + if (symbolExport) { + if (node.name) { + node.name.parent = node; + } + file.bindDiagnostics.push(createDiagnosticForNode(symbolExport.declarations[0], ts.Diagnostics.Duplicate_identifier_0, ts.symbolName(prototypeSymbol))); + } + symbol.exports.set(prototypeSymbol.escapedName, prototypeSymbol); + prototypeSymbol.parent = symbol; + } + function bindEnumDeclaration(node) { + return ts.isEnumConst(node) + ? bindBlockScopedDeclaration(node, 128 /* ConstEnum */, 68008831 /* ConstEnumExcludes */) + : bindBlockScopedDeclaration(node, 256 /* RegularEnum */, 68008191 /* RegularEnumExcludes */); + } + function bindVariableDeclarationOrBindingElement(node) { + if (inStrictMode) { + checkStrictModeEvalOrArguments(node, node.name); + } + if (!ts.isBindingPattern(node.name)) { + var isEnum = ts.isInJSFile(node) && !!ts.getJSDocEnumTag(node); + var enumFlags = (isEnum ? 256 /* RegularEnum */ : 0 /* None */); + var enumExcludes = (isEnum ? 68008191 /* RegularEnumExcludes */ : 0 /* None */); + if (ts.isBlockOrCatchScoped(node)) { + bindBlockScopedDeclaration(node, 2 /* BlockScopedVariable */ | enumFlags, 67220415 /* BlockScopedVariableExcludes */ | enumExcludes); + } + else if (ts.isParameterDeclaration(node)) { + // It is safe to walk up parent chain to find whether the node is a destructuring parameter declaration + // because its parent chain has already been set up, since parents are set before descending into children. + // + // If node is a binding element in parameter declaration, we need to use ParameterExcludes. + // Using ParameterExcludes flag allows the compiler to report an error on duplicate identifiers in Parameter Declaration + // For example: + // function foo([a,a]) {} // Duplicate Identifier error + // function bar(a,a) {} // Duplicate Identifier error, parameter declaration in this case is handled in bindParameter + // // which correctly set excluded symbols + declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67220415 /* ParameterExcludes */); + } + else { + declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */ | enumFlags, 67220414 /* FunctionScopedVariableExcludes */ | enumExcludes); + } + } + } + function bindParameter(node) { + if (node.kind === 299 /* JSDocParameterTag */ && container.kind !== 293 /* JSDocSignature */) { + return; + } + if (inStrictMode && !(node.flags & 4194304 /* Ambient */)) { + // It is a SyntaxError if the identifier eval or arguments appears within a FormalParameterList of a + // strict mode FunctionLikeDeclaration or FunctionExpression(13.1) + checkStrictModeEvalOrArguments(node, node.name); + } + if (ts.isBindingPattern(node.name)) { + bindAnonymousDeclaration(node, 1 /* FunctionScopedVariable */, "__" + node.parent.parameters.indexOf(node)); + } + else { + declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67220415 /* ParameterExcludes */); + } + // If this is a property-parameter, then also declare the property symbol into the + // containing class. + if (ts.isParameterPropertyDeclaration(node)) { + var classDeclaration = node.parent.parent; + declareSymbol(classDeclaration.symbol.members, classDeclaration.symbol, node, 4 /* Property */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), 0 /* PropertyExcludes */); + } + } + function bindFunctionDeclaration(node) { + if (!file.isDeclarationFile && !(node.flags & 4194304 /* Ambient */)) { + if (ts.isAsyncFunction(node)) { + emitFlags |= 1024 /* HasAsyncFunctions */; + } + } + checkStrictModeFunctionName(node); + if (inStrictMode) { + checkStrictModeFunctionDeclaration(node); + bindBlockScopedDeclaration(node, 16 /* Function */, 67219887 /* FunctionExcludes */); + } + else { + declareSymbolAndAddToSymbolTable(node, 16 /* Function */, 67219887 /* FunctionExcludes */); + } + } + function bindFunctionExpression(node) { + if (!file.isDeclarationFile && !(node.flags & 4194304 /* Ambient */)) { + if (ts.isAsyncFunction(node)) { + emitFlags |= 1024 /* HasAsyncFunctions */; + } + } + if (currentFlow) { + node.flowNode = currentFlow; + } + checkStrictModeFunctionName(node); + var bindingName = node.name ? node.name.escapedText : "__function" /* Function */; + return bindAnonymousDeclaration(node, 16 /* Function */, bindingName); + } + function bindPropertyOrMethodOrAccessor(node, symbolFlags, symbolExcludes) { + if (!file.isDeclarationFile && !(node.flags & 4194304 /* Ambient */) && ts.isAsyncFunction(node)) { + emitFlags |= 1024 /* HasAsyncFunctions */; + } + if (currentFlow && ts.isObjectLiteralOrClassExpressionMethod(node)) { + node.flowNode = currentFlow; + } + return ts.hasDynamicName(node) + ? bindAnonymousDeclaration(node, symbolFlags, "__computed" /* Computed */) + : declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes); + } + function getInferTypeContainer(node) { + var extendsType = ts.findAncestor(node, function (n) { return n.parent && ts.isConditionalTypeNode(n.parent) && n.parent.extendsType === n; }); + return extendsType && extendsType.parent; + } + function bindTypeParameter(node) { + if (ts.isJSDocTemplateTag(node.parent)) { + var container_1 = ts.find(node.parent.parent.tags, ts.isJSDocTypeAlias) || ts.getHostSignatureFromJSDoc(node.parent); // TODO: GH#18217 + if (container_1) { + if (!container_1.locals) { + container_1.locals = ts.createSymbolTable(); + } + declareSymbol(container_1.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 67635688 /* TypeParameterExcludes */); + } + else { + declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 67635688 /* TypeParameterExcludes */); + } + } + else if (node.parent.kind === 176 /* InferType */) { + var container_2 = getInferTypeContainer(node.parent); + if (container_2) { + if (!container_2.locals) { + container_2.locals = ts.createSymbolTable(); + } + declareSymbol(container_2.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 67635688 /* TypeParameterExcludes */); + } + else { + bindAnonymousDeclaration(node, 262144 /* TypeParameter */, getDeclarationName(node)); // TODO: GH#18217 + } + } + else { + declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 67635688 /* TypeParameterExcludes */); + } + } + // reachability checks + function shouldReportErrorOnModuleDeclaration(node) { + var instanceState = getModuleInstanceState(node); + return instanceState === 1 /* Instantiated */ || (instanceState === 2 /* ConstEnumOnly */ && !!options.preserveConstEnums); + } + function checkUnreachable(node) { + if (!(currentFlow.flags & 1 /* Unreachable */)) { + return false; + } + if (currentFlow === unreachableFlow) { + var reportError = + // report error on all statements except empty ones + (ts.isStatementButNotDeclaration(node) && node.kind !== 220 /* EmptyStatement */) || + // report error on class declarations + node.kind === 240 /* ClassDeclaration */ || + // report error on instantiated modules or const-enums only modules if preserveConstEnums is set + (node.kind === 244 /* ModuleDeclaration */ && shouldReportErrorOnModuleDeclaration(node)); + if (reportError) { + currentFlow = reportedUnreachableFlow; + if (!options.allowUnreachableCode) { + // unreachable code is reported if + // - user has explicitly asked about it AND + // - statement is in not ambient context (statements in ambient context is already an error + // so we should not report extras) AND + // - node is not variable statement OR + // - node is block scoped variable statement OR + // - node is not block scoped variable statement and at least one variable declaration has initializer + // Rationale: we don't want to report errors on non-initialized var's since they are hoisted + // On the other side we do want to report errors on non-initialized 'lets' because of TDZ + var isError_1 = ts.unreachableCodeIsError(options) && + !(node.flags & 4194304 /* Ambient */) && + (!ts.isVariableStatement(node) || + !!(ts.getCombinedNodeFlags(node.declarationList) & 3 /* BlockScoped */) || + node.declarationList.declarations.some(function (d) { return !!d.initializer; })); + eachUnreachableRange(node, function (start, end) { return errorOrSuggestionOnRange(isError_1, start, end, ts.Diagnostics.Unreachable_code_detected); }); + } + } + } + return true; + } + } + function eachUnreachableRange(node, cb) { + if (ts.isStatement(node) && isExecutableStatement(node) && ts.isBlock(node.parent)) { + var statements = node.parent.statements; + var slice_1 = ts.sliceAfter(statements, node); + ts.getRangesWhere(slice_1, isExecutableStatement, function (start, afterEnd) { return cb(slice_1[start], slice_1[afterEnd - 1]); }); + } + else { + cb(node, node); + } + } + // As opposed to a pure declaration like an `interface` + function isExecutableStatement(s) { + // Don't remove statements that can validly be used before they appear. + return !ts.isFunctionDeclaration(s) && !isPurelyTypeDeclaration(s) && !ts.isEnumDeclaration(s) && + // `var x;` may declare a variable used above + !(ts.isVariableStatement(s) && !(ts.getCombinedNodeFlags(s) & (1 /* Let */ | 2 /* Const */)) && s.declarationList.declarations.some(function (d) { return !d.initializer; })); + } + function isPurelyTypeDeclaration(s) { + switch (s.kind) { + case 241 /* InterfaceDeclaration */: + case 242 /* TypeAliasDeclaration */: + return true; + case 244 /* ModuleDeclaration */: + return getModuleInstanceState(s) !== 1 /* Instantiated */; + case 243 /* EnumDeclaration */: + return ts.hasModifier(s, 2048 /* Const */); + default: + return false; + } + } + function isExportsOrModuleExportsOrAlias(sourceFile, node) { + return ts.isExportsIdentifier(node) || + ts.isModuleExportsPropertyAccessExpression(node) || + ts.isIdentifier(node) && isNameOfExportsOrModuleExportsAliasDeclaration(sourceFile, node); + } + ts.isExportsOrModuleExportsOrAlias = isExportsOrModuleExportsOrAlias; + function isNameOfExportsOrModuleExportsAliasDeclaration(sourceFile, node) { + var symbol = lookupSymbolForNameWorker(sourceFile, node.escapedText); + return !!symbol && !!symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && + !!symbol.valueDeclaration.initializer && isExportsOrModuleExportsOrAliasOrAssignment(sourceFile, symbol.valueDeclaration.initializer); + } + function isExportsOrModuleExportsOrAliasOrAssignment(sourceFile, node) { + return isExportsOrModuleExportsOrAlias(sourceFile, node) || + (ts.isAssignmentExpression(node, /*excludeCompoundAssignment*/ true) && (isExportsOrModuleExportsOrAliasOrAssignment(sourceFile, node.left) || isExportsOrModuleExportsOrAliasOrAssignment(sourceFile, node.right))); + } + function lookupSymbolForNameWorker(container, name) { + var local = container.locals && container.locals.get(name); + if (local) { + return local.exportSymbol || local; + } + if (ts.isSourceFile(container) && container.jsGlobalAugmentations && container.jsGlobalAugmentations.has(name)) { + return container.jsGlobalAugmentations.get(name); + } + return container.symbol && container.symbol.exports && container.symbol.exports.get(name); + } + /** + * Computes the transform flags for a node, given the transform flags of its subtree + * + * @param node The node to analyze + * @param subtreeFlags Transform flags computed for this node's subtree + */ + function computeTransformFlagsForNode(node, subtreeFlags) { + var kind = node.kind; + switch (kind) { + case 191 /* CallExpression */: + return computeCallExpression(node, subtreeFlags); + case 192 /* NewExpression */: + return computeNewExpression(node, subtreeFlags); + case 244 /* ModuleDeclaration */: + return computeModuleDeclaration(node, subtreeFlags); + case 195 /* ParenthesizedExpression */: + return computeParenthesizedExpression(node, subtreeFlags); + case 204 /* BinaryExpression */: + return computeBinaryExpression(node, subtreeFlags); + case 221 /* ExpressionStatement */: + return computeExpressionStatement(node, subtreeFlags); + case 151 /* Parameter */: + return computeParameter(node, subtreeFlags); + case 197 /* ArrowFunction */: + return computeArrowFunction(node, subtreeFlags); + case 196 /* FunctionExpression */: + return computeFunctionExpression(node, subtreeFlags); + case 239 /* FunctionDeclaration */: + return computeFunctionDeclaration(node, subtreeFlags); + case 237 /* VariableDeclaration */: + return computeVariableDeclaration(node, subtreeFlags); + case 238 /* VariableDeclarationList */: + return computeVariableDeclarationList(node, subtreeFlags); + case 219 /* VariableStatement */: + return computeVariableStatement(node, subtreeFlags); + case 233 /* LabeledStatement */: + return computeLabeledStatement(node, subtreeFlags); + case 240 /* ClassDeclaration */: + return computeClassDeclaration(node, subtreeFlags); + case 209 /* ClassExpression */: + return computeClassExpression(node, subtreeFlags); + case 273 /* HeritageClause */: + return computeHeritageClause(node, subtreeFlags); + case 274 /* CatchClause */: + return computeCatchClause(node, subtreeFlags); + case 211 /* ExpressionWithTypeArguments */: + return computeExpressionWithTypeArguments(node, subtreeFlags); + case 157 /* Constructor */: + return computeConstructor(node, subtreeFlags); + case 154 /* PropertyDeclaration */: + return computePropertyDeclaration(node, subtreeFlags); + case 156 /* MethodDeclaration */: + return computeMethod(node, subtreeFlags); + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + return computeAccessor(node, subtreeFlags); + case 248 /* ImportEqualsDeclaration */: + return computeImportEquals(node, subtreeFlags); + case 189 /* PropertyAccessExpression */: + return computePropertyAccess(node, subtreeFlags); + case 190 /* ElementAccessExpression */: + return computeElementAccess(node, subtreeFlags); + default: + return computeOther(node, kind, subtreeFlags); + } + } + ts.computeTransformFlagsForNode = computeTransformFlagsForNode; + function computeCallExpression(node, subtreeFlags) { + var transformFlags = subtreeFlags; + var expression = node.expression; + if (node.typeArguments) { + transformFlags |= 3 /* AssertTypeScript */; + } + if (subtreeFlags & 131072 /* ContainsRestOrSpread */ + || (expression.transformFlags & (33554432 /* Super */ | 67108864 /* ContainsSuper */))) { + // If the this node contains a SpreadExpression, or is a super call, then it is an ES6 + // node. + transformFlags |= 192 /* AssertES2015 */; + // super property or element accesses could be inside lambdas, etc, and need a captured `this`, + // while super keyword for super calls (indicated by TransformFlags.Super) does not (since it can only be top-level in a constructor) + if (expression.transformFlags & 67108864 /* ContainsSuper */) { + transformFlags |= 8192 /* ContainsLexicalThis */; + } + } + if (expression.kind === 92 /* ImportKeyword */) { + transformFlags |= 16777216 /* ContainsDynamicImport */; + // A dynamic 'import()' call that contains a lexical 'this' will + // require a captured 'this' when emitting down-level. + if (subtreeFlags & 8192 /* ContainsLexicalThis */) { + transformFlags |= 16384 /* ContainsCapturedLexicalThis */; + } + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~637666625 /* ArrayLiteralOrCallOrNewExcludes */; + } + function computeNewExpression(node, subtreeFlags) { + var transformFlags = subtreeFlags; + if (node.typeArguments) { + transformFlags |= 3 /* AssertTypeScript */; + } + if (subtreeFlags & 131072 /* ContainsRestOrSpread */) { + // If the this node contains a SpreadElementExpression then it is an ES6 + // node. + transformFlags |= 192 /* AssertES2015 */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~637666625 /* ArrayLiteralOrCallOrNewExcludes */; + } + function computeBinaryExpression(node, subtreeFlags) { + var transformFlags = subtreeFlags; + var operatorTokenKind = node.operatorToken.kind; + var leftKind = node.left.kind; + if (operatorTokenKind === 59 /* EqualsToken */ && leftKind === 188 /* ObjectLiteralExpression */) { + // Destructuring object assignments with are ES2015 syntax + // and possibly ESNext if they contain rest + transformFlags |= 8 /* AssertESNext */ | 192 /* AssertES2015 */ | 3072 /* AssertDestructuringAssignment */; + } + else if (operatorTokenKind === 59 /* EqualsToken */ && leftKind === 187 /* ArrayLiteralExpression */) { + // Destructuring assignments are ES2015 syntax. + transformFlags |= 192 /* AssertES2015 */ | 3072 /* AssertDestructuringAssignment */; + } + else if (operatorTokenKind === 41 /* AsteriskAsteriskToken */ + || operatorTokenKind === 63 /* AsteriskAsteriskEqualsToken */) { + // Exponentiation is ES2016 syntax. + transformFlags |= 32 /* AssertES2016 */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~637535553 /* NodeExcludes */; + } + function computeParameter(node, subtreeFlags) { + var transformFlags = subtreeFlags; + var name = node.name; + var initializer = node.initializer; + var dotDotDotToken = node.dotDotDotToken; + // The '?' token, type annotations, decorators, and 'this' parameters are TypeSCript + // syntax. + if (node.questionToken + || node.type + || (subtreeFlags & 4096 /* ContainsTypeScriptClassSyntax */ && ts.some(node.decorators)) + || ts.isThisIdentifier(name)) { + transformFlags |= 3 /* AssertTypeScript */; + } + // If a parameter has an accessibility modifier, then it is TypeScript syntax. + if (ts.hasModifier(node, 92 /* ParameterPropertyModifier */)) { + transformFlags |= 3 /* AssertTypeScript */ | 4096 /* ContainsTypeScriptClassSyntax */; + } + // parameters with object rest destructuring are ES Next syntax + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { + transformFlags |= 8 /* AssertESNext */; + } + // If a parameter has an initializer, a binding pattern or a dotDotDot token, then + // it is ES6 syntax and its container must emit default value assignments or parameter destructuring downlevel. + if (subtreeFlags & 2097152 /* ContainsBindingPattern */ || initializer || dotDotDotToken) { + transformFlags |= 192 /* AssertES2015 */ | 65536 /* ContainsDefaultValueAssignments */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~637535553 /* ParameterExcludes */; + } + function computeParenthesizedExpression(node, subtreeFlags) { + var transformFlags = subtreeFlags; + var expression = node.expression; + var expressionKind = expression.kind; + var expressionTransformFlags = expression.transformFlags; + // If the node is synthesized, it means the emitter put the parentheses there, + // not the user. If we didn't want them, the emitter would not have put them + // there. + if (expressionKind === 212 /* AsExpression */ + || expressionKind === 194 /* TypeAssertionExpression */) { + transformFlags |= 3 /* AssertTypeScript */; + } + // If the expression of a ParenthesizedExpression is a destructuring assignment, + // then the ParenthesizedExpression is a destructuring assignment. + if (expressionTransformFlags & 1024 /* DestructuringAssignment */) { + transformFlags |= 1024 /* DestructuringAssignment */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~536872257 /* OuterExpressionExcludes */; + } + function computeClassDeclaration(node, subtreeFlags) { + var transformFlags; + if (ts.hasModifier(node, 2 /* Ambient */)) { + // An ambient declaration is TypeScript syntax. + transformFlags = 3 /* AssertTypeScript */; + } + else { + // A ClassDeclaration is ES6 syntax. + transformFlags = subtreeFlags | 192 /* AssertES2015 */; + // A class with a parameter property assignment, property initializer, computed property name, or decorator is + // TypeScript syntax. + // An exported declaration may be TypeScript syntax, but is handled by the visitor + // for a namespace declaration. + if ((subtreeFlags & 4096 /* ContainsTypeScriptClassSyntax */) + || node.typeParameters) { + transformFlags |= 3 /* AssertTypeScript */; + } + if (subtreeFlags & 32768 /* ContainsLexicalThisInComputedPropertyName */) { + // A computed property name containing `this` might need to be rewritten, + // so propagate the ContainsLexicalThis flag upward. + transformFlags |= 8192 /* ContainsLexicalThis */; + } + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~638121281 /* ClassExcludes */; + } + function computeClassExpression(node, subtreeFlags) { + // A ClassExpression is ES6 syntax. + var transformFlags = subtreeFlags | 192 /* AssertES2015 */; + // A class with a parameter property assignment, property initializer, or decorator is + // TypeScript syntax. + if (subtreeFlags & 4096 /* ContainsTypeScriptClassSyntax */ + || node.typeParameters) { + transformFlags |= 3 /* AssertTypeScript */; + } + if (subtreeFlags & 32768 /* ContainsLexicalThisInComputedPropertyName */) { + // A computed property name containing `this` might need to be rewritten, + // so propagate the ContainsLexicalThis flag upward. + transformFlags |= 8192 /* ContainsLexicalThis */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~638121281 /* ClassExcludes */; + } + function computeHeritageClause(node, subtreeFlags) { + var transformFlags = subtreeFlags; + switch (node.token) { + case 86 /* ExtendsKeyword */: + // An `extends` HeritageClause is ES6 syntax. + transformFlags |= 192 /* AssertES2015 */; + break; + case 109 /* ImplementsKeyword */: + // An `implements` HeritageClause is TypeScript syntax. + transformFlags |= 3 /* AssertTypeScript */; + break; + default: + ts.Debug.fail("Unexpected token for heritage clause"); + break; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~637535553 /* NodeExcludes */; + } + function computeCatchClause(node, subtreeFlags) { + var transformFlags = subtreeFlags; + if (!node.variableDeclaration) { + transformFlags |= 8 /* AssertESNext */; + } + else if (ts.isBindingPattern(node.variableDeclaration.name)) { + transformFlags |= 192 /* AssertES2015 */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~637797697 /* CatchClauseExcludes */; + } + function computeExpressionWithTypeArguments(node, subtreeFlags) { + // An ExpressionWithTypeArguments is ES6 syntax, as it is used in the + // extends clause of a class. + var transformFlags = subtreeFlags | 192 /* AssertES2015 */; + // If an ExpressionWithTypeArguments contains type arguments, then it + // is TypeScript syntax. + if (node.typeArguments) { + transformFlags |= 3 /* AssertTypeScript */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~637535553 /* NodeExcludes */; + } + function computeConstructor(node, subtreeFlags) { + var transformFlags = subtreeFlags; + // TypeScript-specific modifiers and overloads are TypeScript syntax + if (ts.hasModifier(node, 2270 /* TypeScriptModifier */) + || !node.body) { + transformFlags |= 3 /* AssertTypeScript */; + } + // function declarations with object rest destructuring are ES Next syntax + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { + transformFlags |= 8 /* AssertESNext */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~653616449 /* ConstructorExcludes */; + } + function computeMethod(node, subtreeFlags) { + // A MethodDeclaration is ES6 syntax. + var transformFlags = subtreeFlags | 192 /* AssertES2015 */; + // Decorators, TypeScript-specific modifiers, type parameters, type annotations, and + // overloads are TypeScript syntax. + if (node.decorators + || ts.hasModifier(node, 2270 /* TypeScriptModifier */) + || node.typeParameters + || node.type + || (node.name && ts.isComputedPropertyName(node.name)) // While computed method names aren't typescript, the TS transform must visit them to emit property declarations correctly + || !node.body) { + transformFlags |= 3 /* AssertTypeScript */; + } + // function declarations with object rest destructuring are ES Next syntax + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { + transformFlags |= 8 /* AssertESNext */; + } + // An async method declaration is ES2017 syntax. + if (ts.hasModifier(node, 256 /* Async */)) { + transformFlags |= node.asteriskToken ? 8 /* AssertESNext */ : 16 /* AssertES2017 */; + } + if (node.asteriskToken) { + transformFlags |= 768 /* AssertGenerator */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~653616449 /* MethodOrAccessorExcludes */; + } + function computeAccessor(node, subtreeFlags) { + var transformFlags = subtreeFlags; + // Decorators, TypeScript-specific modifiers, type annotations, and overloads are + // TypeScript syntax. + if (node.decorators + || ts.hasModifier(node, 2270 /* TypeScriptModifier */) + || node.type + || (node.name && ts.isComputedPropertyName(node.name)) // While computed accessor names aren't typescript, the TS transform must visit them to emit property declarations correctly + || !node.body) { + transformFlags |= 3 /* AssertTypeScript */; + } + // function declarations with object rest destructuring are ES Next syntax + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { + transformFlags |= 8 /* AssertESNext */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~653616449 /* MethodOrAccessorExcludes */; + } + function computePropertyDeclaration(node, subtreeFlags) { + // A PropertyDeclaration is TypeScript syntax. + var transformFlags = subtreeFlags | 3 /* AssertTypeScript */; + // If the PropertyDeclaration has an initializer or a computed name, we need to inform its ancestor + // so that it handle the transformation. + if (node.initializer || ts.isComputedPropertyName(node.name)) { + transformFlags |= 4096 /* ContainsTypeScriptClassSyntax */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~637535553 /* NodeExcludes */; + } + function computeFunctionDeclaration(node, subtreeFlags) { + var transformFlags; + var modifierFlags = ts.getModifierFlags(node); + var body = node.body; + if (!body || (modifierFlags & 2 /* Ambient */)) { + // An ambient declaration is TypeScript syntax. + // A FunctionDeclaration without a body is an overload and is TypeScript syntax. + transformFlags = 3 /* AssertTypeScript */; + } + else { + transformFlags = subtreeFlags | 8388608 /* ContainsHoistedDeclarationOrCompletion */; + // TypeScript-specific modifiers, type parameters, and type annotations are TypeScript + // syntax. + if (modifierFlags & 2270 /* TypeScriptModifier */ + || node.typeParameters + || node.type) { + transformFlags |= 3 /* AssertTypeScript */; + } + // An async function declaration is ES2017 syntax. + if (modifierFlags & 256 /* Async */) { + transformFlags |= node.asteriskToken ? 8 /* AssertESNext */ : 16 /* AssertES2017 */; + } + // function declarations with object rest destructuring are ES Next syntax + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { + transformFlags |= 8 /* AssertESNext */; + } + // If a FunctionDeclaration's subtree has marked the container as needing to capture the + // lexical this, or the function contains parameters with initializers, then this node is + // ES6 syntax. + if (subtreeFlags & 81920 /* ES2015FunctionSyntaxMask */) { + transformFlags |= 192 /* AssertES2015 */; + } + // If a FunctionDeclaration is generator function and is the body of a + // transformed async function, then this node can be transformed to a + // down-level generator. + // Currently we do not support transforming any other generator fucntions + // down level. + if (node.asteriskToken) { + transformFlags |= 768 /* AssertGenerator */; + } + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~653620545 /* FunctionExcludes */; + } + function computeFunctionExpression(node, subtreeFlags) { + var transformFlags = subtreeFlags; + // TypeScript-specific modifiers, type parameters, and type annotations are TypeScript + // syntax. + if (ts.hasModifier(node, 2270 /* TypeScriptModifier */) + || node.typeParameters + || node.type) { + transformFlags |= 3 /* AssertTypeScript */; + } + // An async function expression is ES2017 syntax. + if (ts.hasModifier(node, 256 /* Async */)) { + transformFlags |= node.asteriskToken ? 8 /* AssertESNext */ : 16 /* AssertES2017 */; + } + // function expressions with object rest destructuring are ES Next syntax + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { + transformFlags |= 8 /* AssertESNext */; + } + // If a FunctionExpression's subtree has marked the container as needing to capture the + // lexical this, or the function contains parameters with initializers, then this node is + // ES6 syntax. + if (subtreeFlags & 81920 /* ES2015FunctionSyntaxMask */) { + transformFlags |= 192 /* AssertES2015 */; + } + // If a FunctionExpression is generator function and is the body of a + // transformed async function, then this node can be transformed to a + // down-level generator. + if (node.asteriskToken) { + transformFlags |= 768 /* AssertGenerator */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~653620545 /* FunctionExcludes */; + } + function computeArrowFunction(node, subtreeFlags) { + // An ArrowFunction is ES6 syntax, and excludes markers that should not escape the scope of an ArrowFunction. + var transformFlags = subtreeFlags | 192 /* AssertES2015 */; + // TypeScript-specific modifiers, type parameters, and type annotations are TypeScript + // syntax. + if (ts.hasModifier(node, 2270 /* TypeScriptModifier */) + || node.typeParameters + || node.type) { + transformFlags |= 3 /* AssertTypeScript */; + } + // An async arrow function is ES2017 syntax. + if (ts.hasModifier(node, 256 /* Async */)) { + transformFlags |= 16 /* AssertES2017 */; + } + // arrow functions with object rest destructuring are ES Next syntax + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { + transformFlags |= 8 /* AssertESNext */; + } + // If an ArrowFunction contains a lexical this, its container must capture the lexical this. + if (subtreeFlags & 8192 /* ContainsLexicalThis */) { + transformFlags |= 16384 /* ContainsCapturedLexicalThis */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~653604161 /* ArrowFunctionExcludes */; + } + function computePropertyAccess(node, subtreeFlags) { + var transformFlags = subtreeFlags; + // If a PropertyAccessExpression starts with a super keyword, then it is + // ES6 syntax, and requires a lexical `this` binding. + if (transformFlags & 33554432 /* Super */) { + transformFlags ^= 33554432 /* Super */; + // super inside of an async function requires hoisting the super access (ES2017). + // same for super inside of an async generator, which is ESNext. + transformFlags |= 67108864 /* ContainsSuper */ | 16 /* ContainsES2017 */ | 8 /* ContainsESNext */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~570426689 /* PropertyAccessExcludes */; + } + function computeElementAccess(node, subtreeFlags) { + var transformFlags = subtreeFlags; + var expression = node.expression; + var expressionFlags = expression.transformFlags; // We do not want to aggregate flags from the argument expression for super/this capturing + // If an ElementAccessExpression starts with a super keyword, then it is + // ES6 syntax, and requires a lexical `this` binding. + if (expressionFlags & 33554432 /* Super */) { + transformFlags &= ~33554432 /* Super */; + // super inside of an async function requires hoisting the super access (ES2017). + // same for super inside of an async generator, which is ESNext. + transformFlags |= 67108864 /* ContainsSuper */ | 16 /* ContainsES2017 */ | 8 /* ContainsESNext */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~570426689 /* PropertyAccessExcludes */; + } + function computeVariableDeclaration(node, subtreeFlags) { + var transformFlags = subtreeFlags; + transformFlags |= 192 /* AssertES2015 */ | 2097152 /* ContainsBindingPattern */; + // A VariableDeclaration containing ObjectRest is ESNext syntax + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { + transformFlags |= 8 /* AssertESNext */; + } + // Type annotations are TypeScript syntax. + if (node.type) { + transformFlags |= 3 /* AssertTypeScript */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~637535553 /* NodeExcludes */; + } + function computeVariableStatement(node, subtreeFlags) { + var transformFlags; + var declarationListTransformFlags = node.declarationList.transformFlags; + // An ambient declaration is TypeScript syntax. + if (ts.hasModifier(node, 2 /* Ambient */)) { + transformFlags = 3 /* AssertTypeScript */; + } + else { + transformFlags = subtreeFlags; + if (declarationListTransformFlags & 2097152 /* ContainsBindingPattern */) { + transformFlags |= 192 /* AssertES2015 */; + } + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~637535553 /* NodeExcludes */; + } + function computeLabeledStatement(node, subtreeFlags) { + var transformFlags = subtreeFlags; + // A labeled statement containing a block scoped binding *may* need to be transformed from ES6. + if (subtreeFlags & 1048576 /* ContainsBlockScopedBinding */ + && ts.isIterationStatement(node, /*lookInLabeledStatements*/ true)) { + transformFlags |= 192 /* AssertES2015 */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~637535553 /* NodeExcludes */; + } + function computeImportEquals(node, subtreeFlags) { + var transformFlags = subtreeFlags; + // An ImportEqualsDeclaration with a namespace reference is TypeScript. + if (!ts.isExternalModuleImportEqualsDeclaration(node)) { + transformFlags |= 3 /* AssertTypeScript */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~637535553 /* NodeExcludes */; + } + function computeExpressionStatement(node, subtreeFlags) { + var transformFlags = subtreeFlags; + // If the expression of an expression statement is a destructuring assignment, + // then we treat the statement as ES6 so that we can indicate that we do not + // need to hold on to the right-hand side. + if (node.expression.transformFlags & 1024 /* DestructuringAssignment */) { + transformFlags |= 192 /* AssertES2015 */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~637535553 /* NodeExcludes */; + } + function computeModuleDeclaration(node, subtreeFlags) { + var transformFlags = 3 /* AssertTypeScript */; + var modifierFlags = ts.getModifierFlags(node); + if ((modifierFlags & 2 /* Ambient */) === 0) { + transformFlags |= subtreeFlags; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~647001409 /* ModuleExcludes */; + } + function computeVariableDeclarationList(node, subtreeFlags) { + var transformFlags = subtreeFlags | 8388608 /* ContainsHoistedDeclarationOrCompletion */; + if (subtreeFlags & 2097152 /* ContainsBindingPattern */) { + transformFlags |= 192 /* AssertES2015 */; + } + // If a VariableDeclarationList is `let` or `const`, then it is ES6 syntax. + if (node.flags & 3 /* BlockScoped */) { + transformFlags |= 192 /* AssertES2015 */ | 1048576 /* ContainsBlockScopedBinding */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~639894849 /* VariableDeclarationListExcludes */; + } + function computeOther(node, kind, subtreeFlags) { + // Mark transformations needed for each node + var transformFlags = subtreeFlags; + var excludeFlags = 637535553 /* NodeExcludes */; + switch (kind) { + case 121 /* AsyncKeyword */: + case 201 /* AwaitExpression */: + // async/await is ES2017 syntax, but may be ESNext syntax (for async generators) + transformFlags |= 8 /* AssertESNext */ | 16 /* AssertES2017 */; + break; + case 194 /* TypeAssertionExpression */: + case 212 /* AsExpression */: + case 308 /* PartiallyEmittedExpression */: + // These nodes are TypeScript syntax. + transformFlags |= 3 /* AssertTypeScript */; + excludeFlags = 536872257 /* OuterExpressionExcludes */; + break; + case 115 /* PublicKeyword */: + case 113 /* PrivateKeyword */: + case 114 /* ProtectedKeyword */: + case 118 /* AbstractKeyword */: + case 125 /* DeclareKeyword */: + case 77 /* ConstKeyword */: + case 243 /* EnumDeclaration */: + case 278 /* EnumMember */: + case 213 /* NonNullExpression */: + case 133 /* ReadonlyKeyword */: + // These nodes are TypeScript syntax. + transformFlags |= 3 /* AssertTypeScript */; + break; + case 260 /* JsxElement */: + case 261 /* JsxSelfClosingElement */: + case 262 /* JsxOpeningElement */: + case 11 /* JsxText */: + case 263 /* JsxClosingElement */: + case 264 /* JsxFragment */: + case 265 /* JsxOpeningFragment */: + case 266 /* JsxClosingFragment */: + case 267 /* JsxAttribute */: + case 268 /* JsxAttributes */: + case 269 /* JsxSpreadAttribute */: + case 270 /* JsxExpression */: + // These nodes are Jsx syntax. + transformFlags |= 4 /* AssertJsx */; + break; + case 14 /* NoSubstitutionTemplateLiteral */: + case 15 /* TemplateHead */: + case 16 /* TemplateMiddle */: + case 17 /* TemplateTail */: + case 206 /* TemplateExpression */: + case 193 /* TaggedTemplateExpression */: + case 276 /* ShorthandPropertyAssignment */: + case 116 /* StaticKeyword */: + case 214 /* MetaProperty */: + // These nodes are ES6 syntax. + transformFlags |= 192 /* AssertES2015 */; + break; + case 10 /* StringLiteral */: + if (node.hasExtendedUnicodeEscape) { + transformFlags |= 192 /* AssertES2015 */; + } + break; + case 8 /* NumericLiteral */: + if (node.numericLiteralFlags & 384 /* BinaryOrOctalSpecifier */) { + transformFlags |= 192 /* AssertES2015 */; + } + break; + case 9 /* BigIntLiteral */: + transformFlags |= 8 /* AssertESNext */; + break; + case 227 /* ForOfStatement */: + // This node is either ES2015 syntax or ES2017 syntax (if it is a for-await-of). + if (node.awaitModifier) { + transformFlags |= 8 /* AssertESNext */; + } + transformFlags |= 192 /* AssertES2015 */; + break; + case 207 /* YieldExpression */: + // This node is either ES2015 syntax (in a generator) or ES2017 syntax (in an async + // generator). + transformFlags |= 8 /* AssertESNext */ | 192 /* AssertES2015 */ | 4194304 /* ContainsYield */; + break; + case 120 /* AnyKeyword */: + case 135 /* NumberKeyword */: + case 146 /* BigIntKeyword */: + case 132 /* NeverKeyword */: + case 136 /* ObjectKeyword */: + case 138 /* StringKeyword */: + case 123 /* BooleanKeyword */: + case 139 /* SymbolKeyword */: + case 106 /* VoidKeyword */: + case 150 /* TypeParameter */: + case 153 /* PropertySignature */: + case 155 /* MethodSignature */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 162 /* IndexSignature */: + case 163 /* TypePredicate */: + case 164 /* TypeReference */: + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + case 167 /* TypeQuery */: + case 168 /* TypeLiteral */: + case 169 /* ArrayType */: + case 170 /* TupleType */: + case 171 /* OptionalType */: + case 172 /* RestType */: + case 173 /* UnionType */: + case 174 /* IntersectionType */: + case 175 /* ConditionalType */: + case 176 /* InferType */: + case 177 /* ParenthesizedType */: + case 241 /* InterfaceDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 178 /* ThisType */: + case 179 /* TypeOperator */: + case 180 /* IndexedAccessType */: + case 181 /* MappedType */: + case 182 /* LiteralType */: + case 247 /* NamespaceExportDeclaration */: + // Types and signatures are TypeScript syntax, and exclude all other facts. + transformFlags = 3 /* AssertTypeScript */; + excludeFlags = -3 /* TypeExcludes */; + break; + case 149 /* ComputedPropertyName */: + // Even though computed property names are ES6, we don't treat them as such. + // This is so that they can flow through PropertyName transforms unaffected. + // Instead, we mark the container as ES6, so that it can properly handle the transform. + transformFlags |= 524288 /* ContainsComputedPropertyName */; + if (subtreeFlags & 8192 /* ContainsLexicalThis */) { + // A computed method name like `[this.getName()](x: string) { ... }` needs to + // distinguish itself from the normal case of a method body containing `this`: + // `this` inside a method doesn't need to be rewritten (the method provides `this`), + // whereas `this` inside a computed name *might* need to be rewritten if the class/object + // is inside an arrow function: + // `_this = this; () => class K { [_this.getName()]() { ... } }` + // To make this distinction, use ContainsLexicalThisInComputedPropertyName + // instead of ContainsLexicalThis for computed property names + transformFlags |= 32768 /* ContainsLexicalThisInComputedPropertyName */; + } + break; + case 208 /* SpreadElement */: + transformFlags |= 192 /* AssertES2015 */ | 131072 /* ContainsRestOrSpread */; + break; + case 277 /* SpreadAssignment */: + transformFlags |= 8 /* AssertESNext */ | 262144 /* ContainsObjectRestOrSpread */; + break; + case 98 /* SuperKeyword */: + // This node is ES6 syntax. + transformFlags |= 192 /* AssertES2015 */ | 33554432 /* Super */; + excludeFlags = 536872257 /* OuterExpressionExcludes */; // must be set to persist `Super` + break; + case 100 /* ThisKeyword */: + // Mark this node and its ancestors as containing a lexical `this` keyword. + transformFlags |= 8192 /* ContainsLexicalThis */; + break; + case 184 /* ObjectBindingPattern */: + transformFlags |= 192 /* AssertES2015 */ | 2097152 /* ContainsBindingPattern */; + if (subtreeFlags & 131072 /* ContainsRestOrSpread */) { + transformFlags |= 8 /* AssertESNext */ | 262144 /* ContainsObjectRestOrSpread */; + } + excludeFlags = 637666625 /* BindingPatternExcludes */; + break; + case 185 /* ArrayBindingPattern */: + transformFlags |= 192 /* AssertES2015 */ | 2097152 /* ContainsBindingPattern */; + excludeFlags = 637666625 /* BindingPatternExcludes */; + break; + case 186 /* BindingElement */: + transformFlags |= 192 /* AssertES2015 */; + if (node.dotDotDotToken) { + transformFlags |= 131072 /* ContainsRestOrSpread */; + } + break; + case 152 /* Decorator */: + // This node is TypeScript syntax, and marks its container as also being TypeScript syntax. + transformFlags |= 3 /* AssertTypeScript */ | 4096 /* ContainsTypeScriptClassSyntax */; + break; + case 188 /* ObjectLiteralExpression */: + excludeFlags = 638358849 /* ObjectLiteralExcludes */; + if (subtreeFlags & 524288 /* ContainsComputedPropertyName */) { + // If an ObjectLiteralExpression contains a ComputedPropertyName, then it + // is an ES6 node. + transformFlags |= 192 /* AssertES2015 */; + } + if (subtreeFlags & 32768 /* ContainsLexicalThisInComputedPropertyName */) { + // A computed property name containing `this` might need to be rewritten, + // so propagate the ContainsLexicalThis flag upward. + transformFlags |= 8192 /* ContainsLexicalThis */; + } + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { + // If an ObjectLiteralExpression contains a spread element, then it + // is an ES next node. + transformFlags |= 8 /* AssertESNext */; + } + break; + case 187 /* ArrayLiteralExpression */: + case 192 /* NewExpression */: + excludeFlags = 637666625 /* ArrayLiteralOrCallOrNewExcludes */; + if (subtreeFlags & 131072 /* ContainsRestOrSpread */) { + // If the this node contains a SpreadExpression, then it is an ES6 + // node. + transformFlags |= 192 /* AssertES2015 */; + } + break; + case 223 /* DoStatement */: + case 224 /* WhileStatement */: + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + // A loop containing a block scoped binding *may* need to be transformed from ES6. + if (subtreeFlags & 1048576 /* ContainsBlockScopedBinding */) { + transformFlags |= 192 /* AssertES2015 */; + } + break; + case 279 /* SourceFile */: + if (subtreeFlags & 16384 /* ContainsCapturedLexicalThis */) { + transformFlags |= 192 /* AssertES2015 */; + } + break; + case 230 /* ReturnStatement */: + // Return statements may require an `await` in ESNext. + transformFlags |= 8388608 /* ContainsHoistedDeclarationOrCompletion */ | 8 /* AssertESNext */; + break; + case 228 /* ContinueStatement */: + case 229 /* BreakStatement */: + transformFlags |= 8388608 /* ContainsHoistedDeclarationOrCompletion */; + break; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~excludeFlags; + } + /** + * Gets the transform flags to exclude when unioning the transform flags of a subtree. + * + * NOTE: This needs to be kept up-to-date with the exclusions used in `computeTransformFlagsForNode`. + * For performance reasons, `computeTransformFlagsForNode` uses local constant values rather + * than calling this function. + */ + function getTransformFlagsSubtreeExclusions(kind) { + if (kind >= 163 /* FirstTypeNode */ && kind <= 183 /* LastTypeNode */) { + return -3 /* TypeExcludes */; + } + switch (kind) { + case 191 /* CallExpression */: + case 192 /* NewExpression */: + case 187 /* ArrayLiteralExpression */: + return 637666625 /* ArrayLiteralOrCallOrNewExcludes */; + case 244 /* ModuleDeclaration */: + return 647001409 /* ModuleExcludes */; + case 151 /* Parameter */: + return 637535553 /* ParameterExcludes */; + case 197 /* ArrowFunction */: + return 653604161 /* ArrowFunctionExcludes */; + case 196 /* FunctionExpression */: + case 239 /* FunctionDeclaration */: + return 653620545 /* FunctionExcludes */; + case 238 /* VariableDeclarationList */: + return 639894849 /* VariableDeclarationListExcludes */; + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + return 638121281 /* ClassExcludes */; + case 157 /* Constructor */: + return 653616449 /* ConstructorExcludes */; + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + return 653616449 /* MethodOrAccessorExcludes */; + case 120 /* AnyKeyword */: + case 135 /* NumberKeyword */: + case 146 /* BigIntKeyword */: + case 132 /* NeverKeyword */: + case 138 /* StringKeyword */: + case 136 /* ObjectKeyword */: + case 123 /* BooleanKeyword */: + case 139 /* SymbolKeyword */: + case 106 /* VoidKeyword */: + case 150 /* TypeParameter */: + case 153 /* PropertySignature */: + case 155 /* MethodSignature */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 162 /* IndexSignature */: + case 241 /* InterfaceDeclaration */: + case 242 /* TypeAliasDeclaration */: + return -3 /* TypeExcludes */; + case 188 /* ObjectLiteralExpression */: + return 638358849 /* ObjectLiteralExcludes */; + case 274 /* CatchClause */: + return 637797697 /* CatchClauseExcludes */; + case 184 /* ObjectBindingPattern */: + case 185 /* ArrayBindingPattern */: + return 637666625 /* BindingPatternExcludes */; + case 194 /* TypeAssertionExpression */: + case 212 /* AsExpression */: + case 308 /* PartiallyEmittedExpression */: + case 195 /* ParenthesizedExpression */: + case 98 /* SuperKeyword */: + return 536872257 /* OuterExpressionExcludes */; + case 189 /* PropertyAccessExpression */: + case 190 /* ElementAccessExpression */: + return 570426689 /* PropertyAccessExcludes */; + default: + return 637535553 /* NodeExcludes */; + } + } + ts.getTransformFlagsSubtreeExclusions = getTransformFlagsSubtreeExclusions; + /** + * "Binds" JSDoc nodes in TypeScript code. + * Since we will never create symbols for JSDoc, we just set parent pointers instead. + */ + function setParentPointers(parent, child) { + child.parent = parent; + ts.forEachChild(child, function (grandchild) { return setParentPointers(child, grandchild); }); + } +})(ts || (ts = {})); +/** @internal */ +var ts; +(function (ts) { + function createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintOfTypeParameter, getFirstIdentifier) { + return getSymbolWalker; + function getSymbolWalker(accept) { + if (accept === void 0) { accept = function () { return true; }; } + var visitedTypes = []; // Sparse array from id to type + var visitedSymbols = []; // Sparse array from id to symbol + return { + walkType: function (type) { + try { + visitType(type); + return { visitedTypes: ts.getOwnValues(visitedTypes), visitedSymbols: ts.getOwnValues(visitedSymbols) }; + } + finally { + ts.clear(visitedTypes); + ts.clear(visitedSymbols); + } + }, + walkSymbol: function (symbol) { + try { + visitSymbol(symbol); + return { visitedTypes: ts.getOwnValues(visitedTypes), visitedSymbols: ts.getOwnValues(visitedSymbols) }; + } + finally { + ts.clear(visitedTypes); + ts.clear(visitedSymbols); + } + }, + }; + function visitType(type) { + if (!type) { + return; + } + if (visitedTypes[type.id]) { + return; + } + visitedTypes[type.id] = type; + // Reuse visitSymbol to visit the type's symbol, + // but be sure to bail on recuring into the type if accept declines the symbol. + var shouldBail = visitSymbol(type.symbol); + if (shouldBail) + return; + // Visit the type's related types, if any + if (type.flags & 524288 /* Object */) { + var objectType = type; + var objectFlags = objectType.objectFlags; + if (objectFlags & 4 /* Reference */) { + visitTypeReference(type); + } + if (objectFlags & 32 /* Mapped */) { + visitMappedType(type); + } + if (objectFlags & (1 /* Class */ | 2 /* Interface */)) { + visitInterfaceType(type); + } + if (objectFlags & (8 /* Tuple */ | 16 /* Anonymous */)) { + visitObjectType(objectType); + } + } + if (type.flags & 262144 /* TypeParameter */) { + visitTypeParameter(type); + } + if (type.flags & 3145728 /* UnionOrIntersection */) { + visitUnionOrIntersectionType(type); + } + if (type.flags & 4194304 /* Index */) { + visitIndexType(type); + } + if (type.flags & 8388608 /* IndexedAccess */) { + visitIndexedAccessType(type); + } + } + function visitTypeReference(type) { + visitType(type.target); + ts.forEach(type.typeArguments, visitType); + } + function visitTypeParameter(type) { + visitType(getConstraintOfTypeParameter(type)); + } + function visitUnionOrIntersectionType(type) { + ts.forEach(type.types, visitType); + } + function visitIndexType(type) { + visitType(type.type); + } + function visitIndexedAccessType(type) { + visitType(type.objectType); + visitType(type.indexType); + visitType(type.constraint); + } + function visitMappedType(type) { + visitType(type.typeParameter); + visitType(type.constraintType); + visitType(type.templateType); + visitType(type.modifiersType); + } + function visitSignature(signature) { + var typePredicate = getTypePredicateOfSignature(signature); + if (typePredicate) { + visitType(typePredicate.type); + } + ts.forEach(signature.typeParameters, visitType); + for (var _i = 0, _a = signature.parameters; _i < _a.length; _i++) { + var parameter = _a[_i]; + visitSymbol(parameter); + } + visitType(getRestTypeOfSignature(signature)); + visitType(getReturnTypeOfSignature(signature)); + } + function visitInterfaceType(interfaceT) { + visitObjectType(interfaceT); + ts.forEach(interfaceT.typeParameters, visitType); + ts.forEach(getBaseTypes(interfaceT), visitType); + visitType(interfaceT.thisType); + } + function visitObjectType(type) { + var stringIndexType = getIndexTypeOfStructuredType(type, 0 /* String */); + visitType(stringIndexType); + var numberIndexType = getIndexTypeOfStructuredType(type, 1 /* Number */); + visitType(numberIndexType); + // The two checks above *should* have already resolved the type (if needed), so this should be cached + var resolved = resolveStructuredTypeMembers(type); + for (var _i = 0, _a = resolved.callSignatures; _i < _a.length; _i++) { + var signature = _a[_i]; + visitSignature(signature); + } + for (var _b = 0, _c = resolved.constructSignatures; _b < _c.length; _b++) { + var signature = _c[_b]; + visitSignature(signature); + } + for (var _d = 0, _e = resolved.properties; _d < _e.length; _d++) { + var p = _e[_d]; + visitSymbol(p); + } + } + function visitSymbol(symbol) { + if (!symbol) { + return false; + } + var symbolId = ts.getSymbolId(symbol); + if (visitedSymbols[symbolId]) { + return false; + } + visitedSymbols[symbolId] = symbol; + if (!accept(symbol)) { + return true; + } + var t = getTypeOfSymbol(symbol); + visitType(t); // Should handle members on classes and such + if (symbol.exports) { + symbol.exports.forEach(visitSymbol); + } + ts.forEach(symbol.declarations, function (d) { + // Type queries are too far resolved when we just visit the symbol's type + // (their type resolved directly to the member deeply referenced) + // So to get the intervening symbols, we need to check if there's a type + // query node on any of the symbol's declarations and get symbols there + if (d.type && d.type.kind === 167 /* TypeQuery */) { + var query = d.type; + var entity = getResolvedSymbol(getFirstIdentifier(query.exprName)); + visitSymbol(entity); + } + }); + return false; + } + } + } + ts.createGetSymbolWalker = createGetSymbolWalker; +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var ambientModuleSymbolRegex = /^".+"$/; + var nextSymbolId = 1; + var nextNodeId = 1; + var nextMergeId = 1; + var nextFlowId = 1; + function getNodeId(node) { + if (!node.id) { + node.id = nextNodeId; + nextNodeId++; + } + return node.id; + } + ts.getNodeId = getNodeId; + function getSymbolId(symbol) { + if (!symbol.id) { + symbol.id = nextSymbolId; + nextSymbolId++; + } + return symbol.id; + } + ts.getSymbolId = getSymbolId; + function isInstantiatedModule(node, preserveConstEnums) { + var moduleState = ts.getModuleInstanceState(node); + return moduleState === 1 /* Instantiated */ || + (preserveConstEnums && moduleState === 2 /* ConstEnumOnly */); + } + ts.isInstantiatedModule = isInstantiatedModule; + function createTypeChecker(host, produceDiagnostics) { + var getPackagesSet = ts.memoize(function () { + var set = ts.createMap(); + host.getSourceFiles().forEach(function (sf) { + if (!sf.resolvedModules) + return; + ts.forEachEntry(sf.resolvedModules, function (r) { + if (r && r.packageId) + set.set(r.packageId.name, true); + }); + }); + return set; + }); + // Cancellation that controls whether or not we can cancel in the middle of type checking. + // In general cancelling is *not* safe for the type checker. We might be in the middle of + // computing something, and we will leave our internals in an inconsistent state. Callers + // who set the cancellation token should catch if a cancellation exception occurs, and + // should throw away and create a new TypeChecker. + // + // Currently we only support setting the cancellation token when getting diagnostics. This + // is because diagnostics can be quite expensive, and we want to allow hosts to bail out if + // they no longer need the information (for example, if the user started editing again). + var cancellationToken; + var requestedExternalEmitHelpers; + var externalHelpersModule; + // tslint:disable variable-name + var Symbol = ts.objectAllocator.getSymbolConstructor(); + var Type = ts.objectAllocator.getTypeConstructor(); + var Signature = ts.objectAllocator.getSignatureConstructor(); + // tslint:enable variable-name + var typeCount = 0; + var symbolCount = 0; + var enumCount = 0; + var instantiationDepth = 0; + var constraintDepth = 0; + var emptySymbols = ts.createSymbolTable(); + var identityMapper = ts.identity; + var compilerOptions = host.getCompilerOptions(); + var languageVersion = ts.getEmitScriptTarget(compilerOptions); + var moduleKind = ts.getEmitModuleKind(compilerOptions); + var allowSyntheticDefaultImports = ts.getAllowSyntheticDefaultImports(compilerOptions); + var strictNullChecks = ts.getStrictOptionValue(compilerOptions, "strictNullChecks"); + var strictFunctionTypes = ts.getStrictOptionValue(compilerOptions, "strictFunctionTypes"); + var strictBindCallApply = ts.getStrictOptionValue(compilerOptions, "strictBindCallApply"); + var strictPropertyInitialization = ts.getStrictOptionValue(compilerOptions, "strictPropertyInitialization"); + var noImplicitAny = ts.getStrictOptionValue(compilerOptions, "noImplicitAny"); + var noImplicitThis = ts.getStrictOptionValue(compilerOptions, "noImplicitThis"); + var keyofStringsOnly = !!compilerOptions.keyofStringsOnly; + var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 32768 /* FreshLiteral */; + var emitResolver = createResolver(); + var nodeBuilder = createNodeBuilder(); + var undefinedSymbol = createSymbol(4 /* Property */, "undefined"); + undefinedSymbol.declarations = []; + var argumentsSymbol = createSymbol(4 /* Property */, "arguments"); + var requireSymbol = createSymbol(4 /* Property */, "require"); + /** This will be set during calls to `getResolvedSignature` where services determines an apparent number of arguments greater than what is actually provided. */ + var apparentArgumentCount; + // for public members that accept a Node or one of its subtypes, we must guard against + // synthetic nodes created during transformations by calling `getParseTreeNode`. + // for most of these, we perform the guard only on `checker` to avoid any possible + // extra cost of calling `getParseTreeNode` when calling these functions from inside the + // checker. + var checker = { + getNodeCount: function () { return ts.sum(host.getSourceFiles(), "nodeCount"); }, + getIdentifierCount: function () { return ts.sum(host.getSourceFiles(), "identifierCount"); }, + getSymbolCount: function () { return ts.sum(host.getSourceFiles(), "symbolCount") + symbolCount; }, + getTypeCount: function () { return typeCount; }, + isUndefinedSymbol: function (symbol) { return symbol === undefinedSymbol; }, + isArgumentsSymbol: function (symbol) { return symbol === argumentsSymbol; }, + isUnknownSymbol: function (symbol) { return symbol === unknownSymbol; }, + getMergedSymbol: getMergedSymbol, + getDiagnostics: getDiagnostics, + getGlobalDiagnostics: getGlobalDiagnostics, + getTypeOfSymbolAtLocation: function (symbol, location) { + location = ts.getParseTreeNode(location); + return location ? getTypeOfSymbolAtLocation(symbol, location) : errorType; + }, + getSymbolsOfParameterPropertyDeclaration: function (parameterIn, parameterName) { + var parameter = ts.getParseTreeNode(parameterIn, ts.isParameter); + if (parameter === undefined) + return ts.Debug.fail("Cannot get symbols of a synthetic parameter that cannot be resolved to a parse-tree node."); + return getSymbolsOfParameterPropertyDeclaration(parameter, ts.escapeLeadingUnderscores(parameterName)); + }, + getDeclaredTypeOfSymbol: getDeclaredTypeOfSymbol, + getPropertiesOfType: getPropertiesOfType, + getPropertyOfType: function (type, name) { return getPropertyOfType(type, ts.escapeLeadingUnderscores(name)); }, + getTypeOfPropertyOfType: function (type, name) { return getTypeOfPropertyOfType(type, ts.escapeLeadingUnderscores(name)); }, + getIndexInfoOfType: getIndexInfoOfType, + getSignaturesOfType: getSignaturesOfType, + getIndexTypeOfType: getIndexTypeOfType, + getBaseTypes: getBaseTypes, + getBaseTypeOfLiteralType: getBaseTypeOfLiteralType, + getWidenedType: getWidenedType, + getTypeFromTypeNode: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isTypeNode); + return node ? getTypeFromTypeNode(node) : errorType; + }, + getParameterType: getTypeAtPosition, + getPromisedTypeOfPromise: getPromisedTypeOfPromise, + getReturnTypeOfSignature: getReturnTypeOfSignature, + getNullableType: getNullableType, + getNonNullableType: getNonNullableType, + typeToTypeNode: nodeBuilder.typeToTypeNode, + indexInfoToIndexSignatureDeclaration: nodeBuilder.indexInfoToIndexSignatureDeclaration, + signatureToSignatureDeclaration: nodeBuilder.signatureToSignatureDeclaration, + symbolToEntityName: nodeBuilder.symbolToEntityName, + symbolToExpression: nodeBuilder.symbolToExpression, + symbolToTypeParameterDeclarations: nodeBuilder.symbolToTypeParameterDeclarations, + symbolToParameterDeclaration: nodeBuilder.symbolToParameterDeclaration, + typeParameterToDeclaration: nodeBuilder.typeParameterToDeclaration, + getSymbolsInScope: function (location, meaning) { + location = ts.getParseTreeNode(location); + return location ? getSymbolsInScope(location, meaning) : []; + }, + getSymbolAtLocation: function (node) { + node = ts.getParseTreeNode(node); + return node ? getSymbolAtLocation(node) : undefined; + }, + getShorthandAssignmentValueSymbol: function (node) { + node = ts.getParseTreeNode(node); + return node ? getShorthandAssignmentValueSymbol(node) : undefined; + }, + getExportSpecifierLocalTargetSymbol: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isExportSpecifier); + return node ? getExportSpecifierLocalTargetSymbol(node) : undefined; + }, + getExportSymbolOfSymbol: function (symbol) { + return getMergedSymbol(symbol.exportSymbol || symbol); + }, + getTypeAtLocation: function (node) { + node = ts.getParseTreeNode(node); + return node ? getTypeOfNode(node) : errorType; + }, + getPropertySymbolOfDestructuringAssignment: function (locationIn) { + var location = ts.getParseTreeNode(locationIn, ts.isIdentifier); + return location ? getPropertySymbolOfDestructuringAssignment(location) : undefined; + }, + signatureToString: function (signature, enclosingDeclaration, flags, kind) { + return signatureToString(signature, ts.getParseTreeNode(enclosingDeclaration), flags, kind); + }, + typeToString: function (type, enclosingDeclaration, flags) { + return typeToString(type, ts.getParseTreeNode(enclosingDeclaration), flags); + }, + symbolToString: function (symbol, enclosingDeclaration, meaning, flags) { + return symbolToString(symbol, ts.getParseTreeNode(enclosingDeclaration), meaning, flags); + }, + typePredicateToString: function (predicate, enclosingDeclaration, flags) { + return typePredicateToString(predicate, ts.getParseTreeNode(enclosingDeclaration), flags); + }, + writeSignature: function (signature, enclosingDeclaration, flags, kind, writer) { + return signatureToString(signature, ts.getParseTreeNode(enclosingDeclaration), flags, kind, writer); + }, + writeType: function (type, enclosingDeclaration, flags, writer) { + return typeToString(type, ts.getParseTreeNode(enclosingDeclaration), flags, writer); + }, + writeSymbol: function (symbol, enclosingDeclaration, meaning, flags, writer) { + return symbolToString(symbol, ts.getParseTreeNode(enclosingDeclaration), meaning, flags, writer); + }, + writeTypePredicate: function (predicate, enclosingDeclaration, flags, writer) { + return typePredicateToString(predicate, ts.getParseTreeNode(enclosingDeclaration), flags, writer); + }, + getAugmentedPropertiesOfType: getAugmentedPropertiesOfType, + getRootSymbols: getRootSymbols, + getContextualType: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isExpression); + return node ? getContextualType(node) : undefined; + }, + getContextualTypeForObjectLiteralElement: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isObjectLiteralElementLike); + return node ? getContextualTypeForObjectLiteralElement(node) : undefined; + }, + getContextualTypeForArgumentAtIndex: function (nodeIn, argIndex) { + var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression); + return node && getContextualTypeForArgumentAtIndex(node, argIndex); + }, + getContextualTypeForJsxAttribute: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isJsxAttributeLike); + return node && getContextualTypeForJsxAttribute(node); + }, + isContextSensitive: isContextSensitive, + getFullyQualifiedName: getFullyQualifiedName, + getResolvedSignature: function (node, candidatesOutArray, agumentCount) { + return getResolvedSignatureWorker(node, candidatesOutArray, agumentCount, /*isForSignatureHelp*/ false); + }, + getResolvedSignatureForSignatureHelp: function (node, candidatesOutArray, agumentCount) { + return getResolvedSignatureWorker(node, candidatesOutArray, agumentCount, /*isForSignatureHelp*/ true); + }, + getConstantValue: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, canHaveConstantValue); + return node ? getConstantValue(node) : undefined; + }, + isValidPropertyAccess: function (nodeIn, propertyName) { + var node = ts.getParseTreeNode(nodeIn, ts.isPropertyAccessOrQualifiedNameOrImportTypeNode); + return !!node && isValidPropertyAccess(node, ts.escapeLeadingUnderscores(propertyName)); + }, + isValidPropertyAccessForCompletions: function (nodeIn, type, property) { + var node = ts.getParseTreeNode(nodeIn, ts.isPropertyAccessExpression); + return !!node && isValidPropertyAccessForCompletions(node, type, property); + }, + getSignatureFromDeclaration: function (declarationIn) { + var declaration = ts.getParseTreeNode(declarationIn, ts.isFunctionLike); + return declaration ? getSignatureFromDeclaration(declaration) : undefined; + }, + isImplementationOfOverload: function (node) { + var parsed = ts.getParseTreeNode(node, ts.isFunctionLike); + return parsed ? isImplementationOfOverload(parsed) : undefined; + }, + getImmediateAliasedSymbol: getImmediateAliasedSymbol, + getAliasedSymbol: resolveAlias, + getEmitResolver: getEmitResolver, + getExportsOfModule: getExportsOfModuleAsArray, + getExportsAndPropertiesOfModule: getExportsAndPropertiesOfModule, + getSymbolWalker: ts.createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintOfTypeParameter, getFirstIdentifier), + getAmbientModules: getAmbientModules, + getJsxIntrinsicTagNamesAt: getJsxIntrinsicTagNamesAt, + isOptionalParameter: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isParameter); + return node ? isOptionalParameter(node) : false; + }, + tryGetMemberInModuleExports: function (name, symbol) { return tryGetMemberInModuleExports(ts.escapeLeadingUnderscores(name), symbol); }, + tryGetMemberInModuleExportsAndProperties: function (name, symbol) { return tryGetMemberInModuleExportsAndProperties(ts.escapeLeadingUnderscores(name), symbol); }, + tryFindAmbientModuleWithoutAugmentations: function (moduleName) { + // we deliberately exclude augmentations + // since we are only interested in declarations of the module itself + return tryFindAmbientModule(moduleName, /*withAugmentations*/ false); + }, + getApparentType: getApparentType, + getUnionType: getUnionType, + createAnonymousType: createAnonymousType, + createSignature: createSignature, + createSymbol: createSymbol, + createIndexInfo: createIndexInfo, + getAnyType: function () { return anyType; }, + getStringType: function () { return stringType; }, + getNumberType: function () { return numberType; }, + createPromiseType: createPromiseType, + createArrayType: createArrayType, + getElementTypeOfArrayType: getElementTypeOfArrayType, + getBooleanType: function () { return booleanType; }, + getFalseType: function (fresh) { return fresh ? falseType : regularFalseType; }, + getTrueType: function (fresh) { return fresh ? trueType : regularTrueType; }, + getVoidType: function () { return voidType; }, + getUndefinedType: function () { return undefinedType; }, + getNullType: function () { return nullType; }, + getESSymbolType: function () { return esSymbolType; }, + getNeverType: function () { return neverType; }, + isSymbolAccessible: isSymbolAccessible, + getObjectFlags: ts.getObjectFlags, + isArrayLikeType: isArrayLikeType, + isTypeInvalidDueToUnionDiscriminant: isTypeInvalidDueToUnionDiscriminant, + getAllPossiblePropertiesOfTypes: getAllPossiblePropertiesOfTypes, + getSuggestionForNonexistentProperty: function (node, type) { return getSuggestionForNonexistentProperty(node, type); }, + getSuggestionForNonexistentSymbol: function (location, name, meaning) { return getSuggestionForNonexistentSymbol(location, ts.escapeLeadingUnderscores(name), meaning); }, + getSuggestionForNonexistentExport: function (node, target) { return getSuggestionForNonexistentExport(node, target); }, + getBaseConstraintOfType: getBaseConstraintOfType, + getDefaultFromTypeParameter: function (type) { return type && type.flags & 262144 /* TypeParameter */ ? getDefaultFromTypeParameter(type) : undefined; }, + resolveName: function (name, location, meaning, excludeGlobals) { + return resolveName(location, ts.escapeLeadingUnderscores(name), meaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false, excludeGlobals); + }, + getJsxNamespace: function (n) { return ts.unescapeLeadingUnderscores(getJsxNamespace(n)); }, + getAccessibleSymbolChain: getAccessibleSymbolChain, + getTypePredicateOfSignature: getTypePredicateOfSignature, + resolveExternalModuleSymbol: resolveExternalModuleSymbol, + tryGetThisTypeAt: function (node) { + node = ts.getParseTreeNode(node); + return node && tryGetThisTypeAt(node); + }, + getTypeArgumentConstraint: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isTypeNode); + return node && getTypeArgumentConstraint(node); + }, + getSuggestionDiagnostics: function (file, ct) { + if (ts.skipTypeChecking(file, compilerOptions)) { + return ts.emptyArray; + } + var diagnostics; + try { + // Record the cancellation token so it can be checked later on during checkSourceElement. + // Do this in a finally block so we can ensure that it gets reset back to nothing after + // this call is done. + cancellationToken = ct; + // Ensure file is type checked + checkSourceFile(file); + ts.Debug.assert(!!(getNodeLinks(file).flags & 1 /* TypeChecked */)); + diagnostics = ts.addRange(diagnostics, suggestionDiagnostics.get(file.fileName)); + if (!file.isDeclarationFile && (!unusedIsError(0 /* Local */) || !unusedIsError(1 /* Parameter */))) { + addUnusedDiagnostics(); + } + return diagnostics || ts.emptyArray; + } + finally { + cancellationToken = undefined; + } + function addUnusedDiagnostics() { + checkUnusedIdentifiers(getPotentiallyUnusedIdentifiers(file), function (containingNode, kind, diag) { + if (!ts.containsParseError(containingNode) && !unusedIsError(kind)) { + (diagnostics || (diagnostics = [])).push(__assign({}, diag, { category: ts.DiagnosticCategory.Suggestion })); + } + }); + } + }, + runWithCancellationToken: function (token, callback) { + try { + cancellationToken = token; + return callback(checker); + } + finally { + cancellationToken = undefined; + } + }, + getLocalTypeParametersOfClassOrInterfaceOrTypeAlias: getLocalTypeParametersOfClassOrInterfaceOrTypeAlias, + }; + function getResolvedSignatureWorker(nodeIn, candidatesOutArray, argumentCount, isForSignatureHelp) { + var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression); + apparentArgumentCount = argumentCount; + var res = node ? getResolvedSignature(node, candidatesOutArray, isForSignatureHelp) : undefined; + apparentArgumentCount = undefined; + return res; + } + var tupleTypes = ts.createMap(); + var unionTypes = ts.createMap(); + var intersectionTypes = ts.createMap(); + var literalTypes = ts.createMap(); + var indexedAccessTypes = ts.createMap(); + var evolvingArrayTypes = []; + var undefinedProperties = ts.createMap(); + var unknownSymbol = createSymbol(4 /* Property */, "unknown"); + var resolvingSymbol = createSymbol(0, "__resolving__" /* Resolving */); + var anyType = createIntrinsicType(1 /* Any */, "any"); + var autoType = createIntrinsicType(1 /* Any */, "any"); + var wildcardType = createIntrinsicType(1 /* Any */, "any"); + var errorType = createIntrinsicType(1 /* Any */, "error"); + var unknownType = createIntrinsicType(2 /* Unknown */, "unknown"); + var undefinedType = createIntrinsicType(32768 /* Undefined */, "undefined"); + var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(32768 /* Undefined */ | 134217728 /* ContainsWideningType */, "undefined"); + var nullType = createIntrinsicType(65536 /* Null */, "null"); + var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(65536 /* Null */ | 134217728 /* ContainsWideningType */, "null"); + var stringType = createIntrinsicType(4 /* String */, "string"); + var numberType = createIntrinsicType(8 /* Number */, "number"); + var bigintType = createIntrinsicType(64 /* BigInt */, "bigint"); + var falseType = createIntrinsicType(512 /* BooleanLiteral */, "false"); + var regularFalseType = createIntrinsicType(512 /* BooleanLiteral */, "false"); + var trueType = createIntrinsicType(512 /* BooleanLiteral */, "true"); + var regularTrueType = createIntrinsicType(512 /* BooleanLiteral */, "true"); + trueType.regularType = regularTrueType; + trueType.freshType = trueType; + regularTrueType.regularType = regularTrueType; + regularTrueType.freshType = trueType; + falseType.regularType = regularFalseType; + falseType.freshType = falseType; + regularFalseType.regularType = regularFalseType; + regularFalseType.freshType = falseType; + var booleanType = createBooleanType([regularFalseType, regularTrueType]); + // Also mark all combinations of fresh/regular booleans as "Boolean" so they print as `boolean` instead of `true | false` + // (The union is cached, so simply doing the marking here is sufficient) + createBooleanType([regularFalseType, trueType]); + createBooleanType([falseType, regularTrueType]); + createBooleanType([falseType, trueType]); + var esSymbolType = createIntrinsicType(4096 /* ESSymbol */, "symbol"); + var voidType = createIntrinsicType(16384 /* Void */, "void"); + var neverType = createIntrinsicType(131072 /* Never */, "never"); + var silentNeverType = createIntrinsicType(131072 /* Never */, "never"); + var implicitNeverType = createIntrinsicType(131072 /* Never */, "never"); + var nonPrimitiveType = createIntrinsicType(67108864 /* NonPrimitive */, "object"); + var stringNumberSymbolType = getUnionType([stringType, numberType, esSymbolType]); + var keyofConstraintType = keyofStringsOnly ? stringType : stringNumberSymbolType; + var numberOrBigIntType = getUnionType([numberType, bigintType]); + var emptyObjectType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + var emptyJsxObjectType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + emptyJsxObjectType.objectFlags |= 4096 /* JsxAttributes */; + var emptyTypeLiteralSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */); + emptyTypeLiteralSymbol.members = ts.createSymbolTable(); + var emptyTypeLiteralType = createAnonymousType(emptyTypeLiteralSymbol, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + var emptyGenericType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + emptyGenericType.instantiations = ts.createMap(); + var anyFunctionType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + // The anyFunctionType contains the anyFunctionType by definition. The flag is further propagated + // in getPropagatingFlagsOfTypes, and it is checked in inferFromTypes. + anyFunctionType.flags |= 536870912 /* ContainsAnyFunctionType */; + var noConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + var circularConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + var resolvingDefaultType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + var markerSuperType = createType(262144 /* TypeParameter */); + var markerSubType = createType(262144 /* TypeParameter */); + markerSubType.constraint = markerSuperType; + var markerOtherType = createType(262144 /* TypeParameter */); + var noTypePredicate = createIdentifierTypePredicate("<>", 0, anyType); + var anySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + var unknownSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, errorType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + var resolvingSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + var silentNeverSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, silentNeverType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + var enumNumberIndexInfo = createIndexInfo(stringType, /*isReadonly*/ true); + var globals = ts.createSymbolTable(); + /** Key is "/path/to/a.ts|/path/to/b.ts". */ + var amalgamatedDuplicates; + var reverseMappedCache = ts.createMap(); + var ambientModulesCache; + /** + * List of every ambient module with a "*" wildcard. + * Unlike other ambient modules, these can't be stored in `globals` because symbol tables only deal with exact matches. + * This is only used if there is no exact match. + */ + var patternAmbientModules; + var globalObjectType; + var globalFunctionType; + var globalCallableFunctionType; + var globalNewableFunctionType; + var globalArrayType; + var globalReadonlyArrayType; + var globalStringType; + var globalNumberType; + var globalBooleanType; + var globalRegExpType; + var globalThisType; + var anyArrayType; + var autoArrayType; + var anyReadonlyArrayType; + var deferredGlobalNonNullableTypeAlias; + // The library files are only loaded when the feature is used. + // This allows users to just specify library files they want to used through --lib + // and they will not get an error from not having unrelated library files + var deferredGlobalESSymbolConstructorSymbol; + var deferredGlobalESSymbolType; + var deferredGlobalTypedPropertyDescriptorType; + var deferredGlobalPromiseType; + var deferredGlobalPromiseLikeType; + var deferredGlobalPromiseConstructorSymbol; + var deferredGlobalPromiseConstructorLikeType; + var deferredGlobalIterableType; + var deferredGlobalIteratorType; + var deferredGlobalIterableIteratorType; + var deferredGlobalAsyncIterableType; + var deferredGlobalAsyncIteratorType; + var deferredGlobalAsyncIterableIteratorType; + var deferredGlobalTemplateStringsArrayType; + var deferredGlobalImportMetaType; + var deferredGlobalExtractSymbol; + var deferredGlobalExcludeSymbol; + var deferredGlobalPickSymbol; + var deferredGlobalBigIntType; + var allPotentiallyUnusedIdentifiers = ts.createMap(); // key is file name + var flowLoopStart = 0; + var flowLoopCount = 0; + var sharedFlowCount = 0; + var flowAnalysisDisabled = false; + var emptyStringType = getLiteralType(""); + var zeroType = getLiteralType(0); + var zeroBigIntType = getLiteralType({ negative: false, base10Value: "0" }); + var resolutionTargets = []; + var resolutionResults = []; + var resolutionPropertyNames = []; + var suggestionCount = 0; + var maximumSuggestionCount = 10; + var mergedSymbols = []; + var symbolLinks = []; + var nodeLinks = []; + var flowLoopCaches = []; + var flowLoopNodes = []; + var flowLoopKeys = []; + var flowLoopTypes = []; + var sharedFlowNodes = []; + var sharedFlowTypes = []; + var potentialThisCollisions = []; + var potentialNewTargetCollisions = []; + var awaitedTypeStack = []; + var diagnostics = ts.createDiagnosticCollection(); + // Suggestion diagnostics must have a file. Keyed by source file name. + var suggestionDiagnostics = ts.createMultiMap(); + var TypeFacts; + (function (TypeFacts) { + TypeFacts[TypeFacts["None"] = 0] = "None"; + TypeFacts[TypeFacts["TypeofEQString"] = 1] = "TypeofEQString"; + TypeFacts[TypeFacts["TypeofEQNumber"] = 2] = "TypeofEQNumber"; + TypeFacts[TypeFacts["TypeofEQBigInt"] = 4] = "TypeofEQBigInt"; + TypeFacts[TypeFacts["TypeofEQBoolean"] = 8] = "TypeofEQBoolean"; + TypeFacts[TypeFacts["TypeofEQSymbol"] = 16] = "TypeofEQSymbol"; + TypeFacts[TypeFacts["TypeofEQObject"] = 32] = "TypeofEQObject"; + TypeFacts[TypeFacts["TypeofEQFunction"] = 64] = "TypeofEQFunction"; + TypeFacts[TypeFacts["TypeofEQHostObject"] = 128] = "TypeofEQHostObject"; + TypeFacts[TypeFacts["TypeofNEString"] = 256] = "TypeofNEString"; + TypeFacts[TypeFacts["TypeofNENumber"] = 512] = "TypeofNENumber"; + TypeFacts[TypeFacts["TypeofNEBigInt"] = 1024] = "TypeofNEBigInt"; + TypeFacts[TypeFacts["TypeofNEBoolean"] = 2048] = "TypeofNEBoolean"; + TypeFacts[TypeFacts["TypeofNESymbol"] = 4096] = "TypeofNESymbol"; + TypeFacts[TypeFacts["TypeofNEObject"] = 8192] = "TypeofNEObject"; + TypeFacts[TypeFacts["TypeofNEFunction"] = 16384] = "TypeofNEFunction"; + TypeFacts[TypeFacts["TypeofNEHostObject"] = 32768] = "TypeofNEHostObject"; + TypeFacts[TypeFacts["EQUndefined"] = 65536] = "EQUndefined"; + TypeFacts[TypeFacts["EQNull"] = 131072] = "EQNull"; + TypeFacts[TypeFacts["EQUndefinedOrNull"] = 262144] = "EQUndefinedOrNull"; + TypeFacts[TypeFacts["NEUndefined"] = 524288] = "NEUndefined"; + TypeFacts[TypeFacts["NENull"] = 1048576] = "NENull"; + TypeFacts[TypeFacts["NEUndefinedOrNull"] = 2097152] = "NEUndefinedOrNull"; + TypeFacts[TypeFacts["Truthy"] = 4194304] = "Truthy"; + TypeFacts[TypeFacts["Falsy"] = 8388608] = "Falsy"; + TypeFacts[TypeFacts["All"] = 16777215] = "All"; + // The following members encode facts about particular kinds of types for use in the getTypeFacts function. + // The presence of a particular fact means that the given test is true for some (and possibly all) values + // of that kind of type. + TypeFacts[TypeFacts["BaseStringStrictFacts"] = 3735041] = "BaseStringStrictFacts"; + TypeFacts[TypeFacts["BaseStringFacts"] = 12582401] = "BaseStringFacts"; + TypeFacts[TypeFacts["StringStrictFacts"] = 16317953] = "StringStrictFacts"; + TypeFacts[TypeFacts["StringFacts"] = 16776705] = "StringFacts"; + TypeFacts[TypeFacts["EmptyStringStrictFacts"] = 12123649] = "EmptyStringStrictFacts"; + TypeFacts[TypeFacts["EmptyStringFacts"] = 12582401] = "EmptyStringFacts"; + TypeFacts[TypeFacts["NonEmptyStringStrictFacts"] = 7929345] = "NonEmptyStringStrictFacts"; + TypeFacts[TypeFacts["NonEmptyStringFacts"] = 16776705] = "NonEmptyStringFacts"; + TypeFacts[TypeFacts["BaseNumberStrictFacts"] = 3734786] = "BaseNumberStrictFacts"; + TypeFacts[TypeFacts["BaseNumberFacts"] = 12582146] = "BaseNumberFacts"; + TypeFacts[TypeFacts["NumberStrictFacts"] = 16317698] = "NumberStrictFacts"; + TypeFacts[TypeFacts["NumberFacts"] = 16776450] = "NumberFacts"; + TypeFacts[TypeFacts["ZeroNumberStrictFacts"] = 12123394] = "ZeroNumberStrictFacts"; + TypeFacts[TypeFacts["ZeroNumberFacts"] = 12582146] = "ZeroNumberFacts"; + TypeFacts[TypeFacts["NonZeroNumberStrictFacts"] = 7929090] = "NonZeroNumberStrictFacts"; + TypeFacts[TypeFacts["NonZeroNumberFacts"] = 16776450] = "NonZeroNumberFacts"; + TypeFacts[TypeFacts["BaseBigIntStrictFacts"] = 3734276] = "BaseBigIntStrictFacts"; + TypeFacts[TypeFacts["BaseBigIntFacts"] = 12581636] = "BaseBigIntFacts"; + TypeFacts[TypeFacts["BigIntStrictFacts"] = 16317188] = "BigIntStrictFacts"; + TypeFacts[TypeFacts["BigIntFacts"] = 16775940] = "BigIntFacts"; + TypeFacts[TypeFacts["ZeroBigIntStrictFacts"] = 12122884] = "ZeroBigIntStrictFacts"; + TypeFacts[TypeFacts["ZeroBigIntFacts"] = 12581636] = "ZeroBigIntFacts"; + TypeFacts[TypeFacts["NonZeroBigIntStrictFacts"] = 7928580] = "NonZeroBigIntStrictFacts"; + TypeFacts[TypeFacts["NonZeroBigIntFacts"] = 16775940] = "NonZeroBigIntFacts"; + TypeFacts[TypeFacts["BaseBooleanStrictFacts"] = 3733256] = "BaseBooleanStrictFacts"; + TypeFacts[TypeFacts["BaseBooleanFacts"] = 12580616] = "BaseBooleanFacts"; + TypeFacts[TypeFacts["BooleanStrictFacts"] = 16316168] = "BooleanStrictFacts"; + TypeFacts[TypeFacts["BooleanFacts"] = 16774920] = "BooleanFacts"; + TypeFacts[TypeFacts["FalseStrictFacts"] = 12121864] = "FalseStrictFacts"; + TypeFacts[TypeFacts["FalseFacts"] = 12580616] = "FalseFacts"; + TypeFacts[TypeFacts["TrueStrictFacts"] = 7927560] = "TrueStrictFacts"; + TypeFacts[TypeFacts["TrueFacts"] = 16774920] = "TrueFacts"; + TypeFacts[TypeFacts["SymbolStrictFacts"] = 7925520] = "SymbolStrictFacts"; + TypeFacts[TypeFacts["SymbolFacts"] = 16772880] = "SymbolFacts"; + TypeFacts[TypeFacts["ObjectStrictFacts"] = 7888800] = "ObjectStrictFacts"; + TypeFacts[TypeFacts["ObjectFacts"] = 16736160] = "ObjectFacts"; + TypeFacts[TypeFacts["FunctionStrictFacts"] = 7880640] = "FunctionStrictFacts"; + TypeFacts[TypeFacts["FunctionFacts"] = 16728000] = "FunctionFacts"; + TypeFacts[TypeFacts["UndefinedFacts"] = 9830144] = "UndefinedFacts"; + TypeFacts[TypeFacts["NullFacts"] = 9363232] = "NullFacts"; + TypeFacts[TypeFacts["EmptyObjectStrictFacts"] = 16318463] = "EmptyObjectStrictFacts"; + TypeFacts[TypeFacts["EmptyObjectFacts"] = 16777215] = "EmptyObjectFacts"; + })(TypeFacts || (TypeFacts = {})); + var typeofEQFacts = ts.createMapFromTemplate({ + string: 1 /* TypeofEQString */, + number: 2 /* TypeofEQNumber */, + bigint: 4 /* TypeofEQBigInt */, + boolean: 8 /* TypeofEQBoolean */, + symbol: 16 /* TypeofEQSymbol */, + undefined: 65536 /* EQUndefined */, + object: 32 /* TypeofEQObject */, + function: 64 /* TypeofEQFunction */ + }); + var typeofNEFacts = ts.createMapFromTemplate({ + string: 256 /* TypeofNEString */, + number: 512 /* TypeofNENumber */, + bigint: 1024 /* TypeofNEBigInt */, + boolean: 2048 /* TypeofNEBoolean */, + symbol: 4096 /* TypeofNESymbol */, + undefined: 524288 /* NEUndefined */, + object: 8192 /* TypeofNEObject */, + function: 16384 /* TypeofNEFunction */ + }); + var typeofTypesByName = ts.createMapFromTemplate({ + string: stringType, + number: numberType, + bigint: bigintType, + boolean: booleanType, + symbol: esSymbolType, + undefined: undefinedType + }); + var typeofType = createTypeofType(); + var _jsxNamespace; + var _jsxFactoryEntity; + var subtypeRelation = ts.createMap(); + var assignableRelation = ts.createMap(); + var definitelyAssignableRelation = ts.createMap(); + var comparableRelation = ts.createMap(); + var identityRelation = ts.createMap(); + var enumRelation = ts.createMap(); + var TypeSystemPropertyName; + (function (TypeSystemPropertyName) { + TypeSystemPropertyName[TypeSystemPropertyName["Type"] = 0] = "Type"; + TypeSystemPropertyName[TypeSystemPropertyName["ResolvedBaseConstructorType"] = 1] = "ResolvedBaseConstructorType"; + TypeSystemPropertyName[TypeSystemPropertyName["DeclaredType"] = 2] = "DeclaredType"; + TypeSystemPropertyName[TypeSystemPropertyName["ResolvedReturnType"] = 3] = "ResolvedReturnType"; + TypeSystemPropertyName[TypeSystemPropertyName["ImmediateBaseConstraint"] = 4] = "ImmediateBaseConstraint"; + TypeSystemPropertyName[TypeSystemPropertyName["EnumTagType"] = 5] = "EnumTagType"; + TypeSystemPropertyName[TypeSystemPropertyName["JSDocTypeReference"] = 6] = "JSDocTypeReference"; + })(TypeSystemPropertyName || (TypeSystemPropertyName = {})); + var CheckMode; + (function (CheckMode) { + CheckMode[CheckMode["Normal"] = 0] = "Normal"; + CheckMode[CheckMode["SkipContextSensitive"] = 1] = "SkipContextSensitive"; + CheckMode[CheckMode["Inferential"] = 2] = "Inferential"; + CheckMode[CheckMode["Contextual"] = 3] = "Contextual"; + })(CheckMode || (CheckMode = {})); + var CallbackCheck; + (function (CallbackCheck) { + CallbackCheck[CallbackCheck["None"] = 0] = "None"; + CallbackCheck[CallbackCheck["Bivariant"] = 1] = "Bivariant"; + CallbackCheck[CallbackCheck["Strict"] = 2] = "Strict"; + })(CallbackCheck || (CallbackCheck = {})); + var MappedTypeModifiers; + (function (MappedTypeModifiers) { + MappedTypeModifiers[MappedTypeModifiers["IncludeReadonly"] = 1] = "IncludeReadonly"; + MappedTypeModifiers[MappedTypeModifiers["ExcludeReadonly"] = 2] = "ExcludeReadonly"; + MappedTypeModifiers[MappedTypeModifiers["IncludeOptional"] = 4] = "IncludeOptional"; + MappedTypeModifiers[MappedTypeModifiers["ExcludeOptional"] = 8] = "ExcludeOptional"; + })(MappedTypeModifiers || (MappedTypeModifiers = {})); + var ExpandingFlags; + (function (ExpandingFlags) { + ExpandingFlags[ExpandingFlags["None"] = 0] = "None"; + ExpandingFlags[ExpandingFlags["Source"] = 1] = "Source"; + ExpandingFlags[ExpandingFlags["Target"] = 2] = "Target"; + ExpandingFlags[ExpandingFlags["Both"] = 3] = "Both"; + })(ExpandingFlags || (ExpandingFlags = {})); + var MembersOrExportsResolutionKind; + (function (MembersOrExportsResolutionKind) { + MembersOrExportsResolutionKind["resolvedExports"] = "resolvedExports"; + MembersOrExportsResolutionKind["resolvedMembers"] = "resolvedMembers"; + })(MembersOrExportsResolutionKind || (MembersOrExportsResolutionKind = {})); + var UnusedKind; + (function (UnusedKind) { + UnusedKind[UnusedKind["Local"] = 0] = "Local"; + UnusedKind[UnusedKind["Parameter"] = 1] = "Parameter"; + })(UnusedKind || (UnusedKind = {})); + var builtinGlobals = ts.createSymbolTable(); + builtinGlobals.set(undefinedSymbol.escapedName, undefinedSymbol); + var isNotOverloadAndNotAccessor = ts.and(isNotOverload, isNotAccessor); + initializeTypeChecker(); + return checker; + function getJsxNamespace(location) { + if (location) { + var file = ts.getSourceFileOfNode(location); + if (file) { + if (file.localJsxNamespace) { + return file.localJsxNamespace; + } + var jsxPragma = file.pragmas.get("jsx"); + if (jsxPragma) { + var chosenpragma = ts.isArray(jsxPragma) ? jsxPragma[0] : jsxPragma; // TODO: GH#18217 + file.localJsxFactory = ts.parseIsolatedEntityName(chosenpragma.arguments.factory, languageVersion); + if (file.localJsxFactory) { + return file.localJsxNamespace = getFirstIdentifier(file.localJsxFactory).escapedText; + } + } + } + } + if (!_jsxNamespace) { + _jsxNamespace = "React"; + if (compilerOptions.jsxFactory) { + _jsxFactoryEntity = ts.parseIsolatedEntityName(compilerOptions.jsxFactory, languageVersion); + if (_jsxFactoryEntity) { + _jsxNamespace = getFirstIdentifier(_jsxFactoryEntity).escapedText; + } + } + else if (compilerOptions.reactNamespace) { + _jsxNamespace = ts.escapeLeadingUnderscores(compilerOptions.reactNamespace); + } + } + return _jsxNamespace; + } + function getEmitResolver(sourceFile, cancellationToken) { + // Ensure we have all the type information in place for this file so that all the + // emitter questions of this resolver will return the right information. + getDiagnostics(sourceFile, cancellationToken); + return emitResolver; + } + function lookupOrIssueError(location, message, arg0, arg1, arg2, arg3) { + var diagnostic = location + ? ts.createDiagnosticForNode(location, message, arg0, arg1, arg2, arg3) + : ts.createCompilerDiagnostic(message, arg0, arg1, arg2, arg3); + var existing = diagnostics.lookup(diagnostic); + if (existing) { + return existing; + } + else { + diagnostics.add(diagnostic); + return diagnostic; + } + } + function addRelatedInfo(diagnostic) { + var relatedInformation = []; + for (var _i = 1; _i < arguments.length; _i++) { + relatedInformation[_i - 1] = arguments[_i]; + } + var _a; + if (!diagnostic.relatedInformation) { + diagnostic.relatedInformation = []; + } + (_a = diagnostic.relatedInformation).push.apply(_a, relatedInformation); + return diagnostic; + } + function error(location, message, arg0, arg1, arg2, arg3) { + var diagnostic = location + ? ts.createDiagnosticForNode(location, message, arg0, arg1, arg2, arg3) + : ts.createCompilerDiagnostic(message, arg0, arg1, arg2, arg3); + diagnostics.add(diagnostic); + return diagnostic; + } + function addErrorOrSuggestion(isError, diagnostic) { + if (isError) { + diagnostics.add(diagnostic); + } + else { + suggestionDiagnostics.add(diagnostic.file.fileName, __assign({}, diagnostic, { category: ts.DiagnosticCategory.Suggestion })); + } + } + function errorOrSuggestion(isError, location, message, arg0, arg1, arg2, arg3) { + addErrorOrSuggestion(isError, "message" in message ? ts.createDiagnosticForNode(location, message, arg0, arg1, arg2, arg3) : ts.createDiagnosticForNodeFromMessageChain(location, message)); + } + function createSymbol(flags, name, checkFlags) { + symbolCount++; + var symbol = (new Symbol(flags | 33554432 /* Transient */, name)); + symbol.checkFlags = checkFlags || 0; + return symbol; + } + function isTransientSymbol(symbol) { + return (symbol.flags & 33554432 /* Transient */) !== 0; + } + function getExcludedSymbolFlags(flags) { + var result = 0; + if (flags & 2 /* BlockScopedVariable */) + result |= 67220415 /* BlockScopedVariableExcludes */; + if (flags & 1 /* FunctionScopedVariable */) + result |= 67220414 /* FunctionScopedVariableExcludes */; + if (flags & 4 /* Property */) + result |= 0 /* PropertyExcludes */; + if (flags & 8 /* EnumMember */) + result |= 68008959 /* EnumMemberExcludes */; + if (flags & 16 /* Function */) + result |= 67219887 /* FunctionExcludes */; + if (flags & 32 /* Class */) + result |= 68008383 /* ClassExcludes */; + if (flags & 64 /* Interface */) + result |= 67897736 /* InterfaceExcludes */; + if (flags & 256 /* RegularEnum */) + result |= 68008191 /* RegularEnumExcludes */; + if (flags & 128 /* ConstEnum */) + result |= 68008831 /* ConstEnumExcludes */; + if (flags & 512 /* ValueModule */) + result |= 110735 /* ValueModuleExcludes */; + if (flags & 8192 /* Method */) + result |= 67212223 /* MethodExcludes */; + if (flags & 32768 /* GetAccessor */) + result |= 67154879 /* GetAccessorExcludes */; + if (flags & 65536 /* SetAccessor */) + result |= 67187647 /* SetAccessorExcludes */; + if (flags & 262144 /* TypeParameter */) + result |= 67635688 /* TypeParameterExcludes */; + if (flags & 524288 /* TypeAlias */) + result |= 67897832 /* TypeAliasExcludes */; + if (flags & 2097152 /* Alias */) + result |= 2097152 /* AliasExcludes */; + return result; + } + function recordMergedSymbol(target, source) { + if (!source.mergeId) { + source.mergeId = nextMergeId; + nextMergeId++; + } + mergedSymbols[source.mergeId] = target; + } + function cloneSymbol(symbol) { + var result = createSymbol(symbol.flags, symbol.escapedName); + result.declarations = symbol.declarations ? symbol.declarations.slice() : []; + result.parent = symbol.parent; + if (symbol.valueDeclaration) + result.valueDeclaration = symbol.valueDeclaration; + if (symbol.constEnumOnlyModule) + result.constEnumOnlyModule = true; + if (symbol.members) + result.members = ts.cloneMap(symbol.members); + if (symbol.exports) + result.exports = ts.cloneMap(symbol.exports); + recordMergedSymbol(result, symbol); + return result; + } + /** + * Note: if target is transient, then it is mutable, and mergeSymbol with both mutate and return it. + * If target is not transient, mergeSymbol will produce a transient clone, mutate that and return it. + */ + function mergeSymbol(target, source) { + if (!(target.flags & getExcludedSymbolFlags(source.flags)) || + (source.flags | target.flags) & 67108864 /* Assignment */) { + ts.Debug.assert(source !== target); + if (!(target.flags & 33554432 /* Transient */)) { + var resolvedTarget = resolveSymbol(target); + if (resolvedTarget === unknownSymbol) { + return source; + } + target = cloneSymbol(resolvedTarget); + } + // Javascript static-property-assignment declarations always merge, even though they are also values + if (source.flags & 512 /* ValueModule */ && target.flags & 512 /* ValueModule */ && target.constEnumOnlyModule && !source.constEnumOnlyModule) { + // reset flag when merging instantiated module into value module that has only const enums + target.constEnumOnlyModule = false; + } + target.flags |= source.flags; + if (source.valueDeclaration && + (!target.valueDeclaration || + ts.isAssignmentDeclaration(target.valueDeclaration) && !ts.isAssignmentDeclaration(source.valueDeclaration) || + ts.isEffectiveModuleDeclaration(target.valueDeclaration) && !ts.isEffectiveModuleDeclaration(source.valueDeclaration))) { + // other kinds of value declarations take precedence over modules and assignment declarations + target.valueDeclaration = source.valueDeclaration; + } + ts.addRange(target.declarations, source.declarations); + if (source.members) { + if (!target.members) + target.members = ts.createSymbolTable(); + mergeSymbolTable(target.members, source.members); + } + if (source.exports) { + if (!target.exports) + target.exports = ts.createSymbolTable(); + mergeSymbolTable(target.exports, source.exports); + } + recordMergedSymbol(target, source); + } + else if (target.flags & 1024 /* NamespaceModule */) { + error(ts.getNameOfDeclaration(source.declarations[0]), ts.Diagnostics.Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity, symbolToString(target)); + } + else { // error + var isEitherEnum = !!(target.flags & 384 /* Enum */ || source.flags & 384 /* Enum */); + var isEitherBlockScoped_1 = !!(target.flags & 2 /* BlockScopedVariable */ || source.flags & 2 /* BlockScopedVariable */); + var message = isEitherEnum + ? ts.Diagnostics.Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations + : isEitherBlockScoped_1 + ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 + : ts.Diagnostics.Duplicate_identifier_0; + var sourceSymbolFile = source.declarations && ts.getSourceFileOfNode(source.declarations[0]); + var targetSymbolFile = target.declarations && ts.getSourceFileOfNode(target.declarations[0]); + var symbolName_1 = symbolToString(source); + // Collect top-level duplicate identifier errors into one mapping, so we can then merge their diagnostics if there are a bunch + if (sourceSymbolFile && targetSymbolFile && amalgamatedDuplicates && !isEitherEnum && sourceSymbolFile !== targetSymbolFile) { + var firstFile_1 = ts.comparePaths(sourceSymbolFile.path, targetSymbolFile.path) === -1 /* LessThan */ ? sourceSymbolFile : targetSymbolFile; + var secondFile_1 = firstFile_1 === sourceSymbolFile ? targetSymbolFile : sourceSymbolFile; + var filesDuplicates = ts.getOrUpdate(amalgamatedDuplicates, firstFile_1.path + "|" + secondFile_1.path, function () { + return ({ firstFile: firstFile_1, secondFile: secondFile_1, conflictingSymbols: ts.createMap() }); + }); + var conflictingSymbolInfo = ts.getOrUpdate(filesDuplicates.conflictingSymbols, symbolName_1, function () { + return ({ isBlockScoped: isEitherBlockScoped_1, firstFileLocations: [], secondFileLocations: [] }); + }); + addDuplicateLocations(conflictingSymbolInfo.firstFileLocations, source); + addDuplicateLocations(conflictingSymbolInfo.secondFileLocations, target); + } + else { + addDuplicateDeclarationErrorsForSymbols(source, message, symbolName_1, target); + addDuplicateDeclarationErrorsForSymbols(target, message, symbolName_1, source); + } + } + return target; + function addDuplicateLocations(locs, symbol) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + ts.pushIfUnique(locs, (ts.getExpandoInitializer(decl, /*isPrototypeAssignment*/ false) ? ts.getNameOfExpando(decl) : ts.getNameOfDeclaration(decl)) || decl); + } + } + } + function addDuplicateDeclarationErrorsForSymbols(target, message, symbolName, source) { + ts.forEach(target.declarations, function (node) { + var errorNode = (ts.getExpandoInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getNameOfExpando(node) : ts.getNameOfDeclaration(node)) || node; + addDuplicateDeclarationError(errorNode, message, symbolName, source.declarations); + }); + } + function addDuplicateDeclarationError(errorNode, message, symbolName, relatedNodes) { + var err = lookupOrIssueError(errorNode, message, symbolName); + for (var _i = 0, _a = relatedNodes || ts.emptyArray; _i < _a.length; _i++) { + var relatedNode = _a[_i]; + err.relatedInformation = err.relatedInformation || []; + if (ts.length(err.relatedInformation) >= 5) + continue; + addRelatedInfo(err, !ts.length(err.relatedInformation) ? ts.createDiagnosticForNode(relatedNode, ts.Diagnostics._0_was_also_declared_here, symbolName) : ts.createDiagnosticForNode(relatedNode, ts.Diagnostics.and_here)); + } + } + function combineSymbolTables(first, second) { + if (!ts.hasEntries(first)) + return second; + if (!ts.hasEntries(second)) + return first; + var combined = ts.createSymbolTable(); + mergeSymbolTable(combined, first); + mergeSymbolTable(combined, second); + return combined; + } + function mergeSymbolTable(target, source) { + source.forEach(function (sourceSymbol, id) { + var targetSymbol = target.get(id); + target.set(id, targetSymbol ? mergeSymbol(targetSymbol, sourceSymbol) : sourceSymbol); + }); + } + function mergeModuleAugmentation(moduleName) { + var moduleAugmentation = moduleName.parent; + if (moduleAugmentation.symbol.declarations[0] !== moduleAugmentation) { + // this is a combined symbol for multiple augmentations within the same file. + // its symbol already has accumulated information for all declarations + // so we need to add it just once - do the work only for first declaration + ts.Debug.assert(moduleAugmentation.symbol.declarations.length > 1); + return; + } + if (ts.isGlobalScopeAugmentation(moduleAugmentation)) { + mergeSymbolTable(globals, moduleAugmentation.symbol.exports); + } + else { + // find a module that about to be augmented + // do not validate names of augmentations that are defined in ambient context + var moduleNotFoundError = !(moduleName.parent.parent.flags & 4194304 /* Ambient */) + ? ts.Diagnostics.Invalid_module_name_in_augmentation_module_0_cannot_be_found + : undefined; + var mainModule = resolveExternalModuleNameWorker(moduleName, moduleName, moduleNotFoundError, /*isForAugmentation*/ true); + if (!mainModule) { + return; + } + // obtain item referenced by 'export=' + mainModule = resolveExternalModuleSymbol(mainModule); + if (mainModule.flags & 1920 /* Namespace */) { + mainModule = mergeSymbol(mainModule, moduleAugmentation.symbol); + } + else { + // moduleName will be a StringLiteral since this is not `declare global`. + error(moduleName, ts.Diagnostics.Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity, moduleName.text); + } + } + } + function addToSymbolTable(target, source, message) { + source.forEach(function (sourceSymbol, id) { + var targetSymbol = target.get(id); + if (targetSymbol) { + // Error on redeclarations + ts.forEach(targetSymbol.declarations, addDeclarationDiagnostic(ts.unescapeLeadingUnderscores(id), message)); + } + else { + target.set(id, sourceSymbol); + } + }); + function addDeclarationDiagnostic(id, message) { + return function (declaration) { return diagnostics.add(ts.createDiagnosticForNode(declaration, message, id)); }; + } + } + function getSymbolLinks(symbol) { + if (symbol.flags & 33554432 /* Transient */) + return symbol; + var id = getSymbolId(symbol); + return symbolLinks[id] || (symbolLinks[id] = {}); + } + function getNodeLinks(node) { + var nodeId = getNodeId(node); + return nodeLinks[nodeId] || (nodeLinks[nodeId] = { flags: 0 }); + } + function isGlobalSourceFile(node) { + return node.kind === 279 /* SourceFile */ && !ts.isExternalOrCommonJsModule(node); + } + function getSymbol(symbols, name, meaning) { + if (meaning) { + var symbol = symbols.get(name); + if (symbol) { + ts.Debug.assert((ts.getCheckFlags(symbol) & 1 /* Instantiated */) === 0, "Should never get an instantiated symbol here."); + if (symbol.flags & meaning) { + return symbol; + } + if (symbol.flags & 2097152 /* Alias */) { + var target = resolveAlias(symbol); + // Unknown symbol means an error occurred in alias resolution, treat it as positive answer to avoid cascading errors + if (target === unknownSymbol || target.flags & meaning) { + return symbol; + } + } + } + } + // return undefined if we can't find a symbol. + } + /** + * Get symbols that represent parameter-property-declaration as parameter and as property declaration + * @param parameter a parameterDeclaration node + * @param parameterName a name of the parameter to get the symbols for. + * @return a tuple of two symbols + */ + function getSymbolsOfParameterPropertyDeclaration(parameter, parameterName) { + var constructorDeclaration = parameter.parent; + var classDeclaration = parameter.parent.parent; + var parameterSymbol = getSymbol(constructorDeclaration.locals, parameterName, 67220415 /* Value */); + var propertySymbol = getSymbol(getMembersOfSymbol(classDeclaration.symbol), parameterName, 67220415 /* Value */); + if (parameterSymbol && propertySymbol) { + return [parameterSymbol, propertySymbol]; + } + return ts.Debug.fail("There should exist two symbols, one as property declaration and one as parameter declaration"); + } + function isBlockScopedNameDeclaredBeforeUse(declaration, usage) { + var declarationFile = ts.getSourceFileOfNode(declaration); + var useFile = ts.getSourceFileOfNode(usage); + if (declarationFile !== useFile) { + if ((moduleKind && (declarationFile.externalModuleIndicator || useFile.externalModuleIndicator)) || + (!compilerOptions.outFile && !compilerOptions.out) || + isInTypeQuery(usage) || + declaration.flags & 4194304 /* Ambient */) { + // nodes are in different files and order cannot be determined + return true; + } + // declaration is after usage + // can be legal if usage is deferred (i.e. inside function or in initializer of instance property) + if (isUsedInFunctionOrInstanceProperty(usage, declaration)) { + return true; + } + var sourceFiles = host.getSourceFiles(); + return sourceFiles.indexOf(declarationFile) <= sourceFiles.indexOf(useFile); + } + if (declaration.pos <= usage.pos) { + // declaration is before usage + if (declaration.kind === 186 /* BindingElement */) { + // still might be illegal if declaration and usage are both binding elements (eg var [a = b, b = b] = [1, 2]) + var errorBindingElement = ts.getAncestor(usage, 186 /* BindingElement */); + if (errorBindingElement) { + return ts.findAncestor(errorBindingElement, ts.isBindingElement) !== ts.findAncestor(declaration, ts.isBindingElement) || + declaration.pos < errorBindingElement.pos; + } + // or it might be illegal if usage happens before parent variable is declared (eg var [a] = a) + return isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 237 /* VariableDeclaration */), usage); + } + else if (declaration.kind === 237 /* VariableDeclaration */) { + // still might be illegal if usage is in the initializer of the variable declaration (eg var a = a) + return !isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage); + } + else if (ts.isClassDeclaration(declaration)) { + // still might be illegal if the usage is within a computed property name in the class (eg class A { static p = "a"; [A.p]() {} }) + return !ts.findAncestor(usage, function (n) { return ts.isComputedPropertyName(n) && n.parent.parent === declaration; }); + } + return true; + } + // declaration is after usage, but it can still be legal if usage is deferred: + // 1. inside an export specifier + // 2. inside a function + // 3. inside an instance property initializer, a reference to a non-instance property + // 4. inside a static property initializer, a reference to a static method in the same class + // 5. inside a TS export= declaration (since we will move the export statement during emit to avoid TDZ) + // or if usage is in a type context: + // 1. inside a type query (typeof in type position) + // 2. inside a jsdoc comment + if (usage.parent.kind === 257 /* ExportSpecifier */ || (usage.parent.kind === 254 /* ExportAssignment */ && usage.parent.isExportEquals)) { + // export specifiers do not use the variable, they only make it available for use + return true; + } + // When resolving symbols for exports, the `usage` location passed in can be the export site directly + if (usage.kind === 254 /* ExportAssignment */ && usage.isExportEquals) { + return true; + } + var container = ts.getEnclosingBlockScopeContainer(declaration); + return !!(usage.flags & 2097152 /* JSDoc */) || isInTypeQuery(usage) || isUsedInFunctionOrInstanceProperty(usage, declaration, container); + function isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage) { + var container = ts.getEnclosingBlockScopeContainer(declaration); + switch (declaration.parent.parent.kind) { + case 219 /* VariableStatement */: + case 225 /* ForStatement */: + case 227 /* ForOfStatement */: + // variable statement/for/for-of statement case, + // use site should not be inside variable declaration (initializer of declaration or binding element) + if (isSameScopeDescendentOf(usage, declaration, container)) { + return true; + } + break; + } + // ForIn/ForOf case - use site should not be used in expression part + var grandparent = declaration.parent.parent; + return ts.isForInOrOfStatement(grandparent) && isSameScopeDescendentOf(usage, grandparent.expression, container); + } + function isUsedInFunctionOrInstanceProperty(usage, declaration, container) { + return !!ts.findAncestor(usage, function (current) { + if (current === container) { + return "quit"; + } + if (ts.isFunctionLike(current)) { + return true; + } + var initializerOfProperty = current.parent && + current.parent.kind === 154 /* PropertyDeclaration */ && + current.parent.initializer === current; + if (initializerOfProperty) { + if (ts.hasModifier(current.parent, 32 /* Static */)) { + if (declaration.kind === 156 /* MethodDeclaration */) { + return true; + } + } + else { + var isDeclarationInstanceProperty = declaration.kind === 154 /* PropertyDeclaration */ && !ts.hasModifier(declaration, 32 /* Static */); + if (!isDeclarationInstanceProperty || ts.getContainingClass(usage) !== ts.getContainingClass(declaration)) { + return true; + } + } + } + return false; + }); + } + } + /** + * Resolve a given name for a given meaning at a given location. An error is reported if the name was not found and + * the nameNotFoundMessage argument is not undefined. Returns the resolved symbol, or undefined if no symbol with + * the given name can be found. + * + * @param isUse If true, this will count towards --noUnusedLocals / --noUnusedParameters. + */ + function resolveName(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, suggestedNameNotFoundMessage) { + if (excludeGlobals === void 0) { excludeGlobals = false; } + return resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, getSymbol, suggestedNameNotFoundMessage); + } + function resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, lookup, suggestedNameNotFoundMessage) { + var originalLocation = location; // needed for did-you-mean error reporting, which gathers candidates starting from the original location + var result; + var lastLocation; + var lastSelfReferenceLocation; + var propertyWithInvalidInitializer; + var errorLocation = location; + var grandparent; + var isInExternalModule = false; + loop: while (location) { + // Locals of a source file are not in scope (because they get merged into the global symbol table) + if (location.locals && !isGlobalSourceFile(location)) { + if (result = lookup(location.locals, name, meaning)) { + var useResult = true; + if (ts.isFunctionLike(location) && lastLocation && lastLocation !== location.body) { + // symbol lookup restrictions for function-like declarations + // - Type parameters of a function are in scope in the entire function declaration, including the parameter + // list and return type. However, local types are only in scope in the function body. + // - parameters are only in the scope of function body + // This restriction does not apply to JSDoc comment types because they are parented + // at a higher level than type parameters would normally be + if (meaning & result.flags & 67897832 /* Type */ && lastLocation.kind !== 291 /* JSDocComment */) { + useResult = result.flags & 262144 /* TypeParameter */ + // type parameters are visible in parameter list, return type and type parameter list + ? lastLocation === location.type || + lastLocation.kind === 151 /* Parameter */ || + lastLocation.kind === 150 /* TypeParameter */ + // local types not visible outside the function body + : false; + } + if (meaning & result.flags & 3 /* Variable */) { + // expression inside parameter will lookup as normal variable scope when targeting es2015+ + var functionLocation = location; + if (compilerOptions.target && compilerOptions.target >= 2 /* ES2015 */ && ts.isParameter(lastLocation) && + functionLocation.body && result.valueDeclaration.pos >= functionLocation.body.pos && result.valueDeclaration.end <= functionLocation.body.end) { + useResult = false; + } + else if (result.flags & 1 /* FunctionScopedVariable */) { + // parameters are visible only inside function body, parameter list and return type + // technically for parameter list case here we might mix parameters and variables declared in function, + // however it is detected separately when checking initializers of parameters + // to make sure that they reference no variables declared after them. + useResult = + lastLocation.kind === 151 /* Parameter */ || + (lastLocation === location.type && + !!ts.findAncestor(result.valueDeclaration, ts.isParameter)); + } + } + } + else if (location.kind === 175 /* ConditionalType */) { + // A type parameter declared using 'infer T' in a conditional type is visible only in + // the true branch of the conditional type. + useResult = lastLocation === location.trueType; + } + if (useResult) { + break loop; + } + else { + result = undefined; + } + } + } + switch (location.kind) { + case 279 /* SourceFile */: + if (!ts.isExternalOrCommonJsModule(location)) + break; + isInExternalModule = true; + // falls through + case 244 /* ModuleDeclaration */: + var moduleExports = getSymbolOfNode(location).exports; + if (location.kind === 279 /* SourceFile */ || ts.isAmbientModule(location)) { + // It's an external module. First see if the module has an export default and if the local + // name of that export default matches. + if (result = moduleExports.get("default" /* Default */)) { + var localSymbol = ts.getLocalSymbolForExportDefault(result); + if (localSymbol && (result.flags & meaning) && localSymbol.escapedName === name) { + break loop; + } + result = undefined; + } + // Because of module/namespace merging, a module's exports are in scope, + // yet we never want to treat an export specifier as putting a member in scope. + // Therefore, if the name we find is purely an export specifier, it is not actually considered in scope. + // Two things to note about this: + // 1. We have to check this without calling getSymbol. The problem with calling getSymbol + // on an export specifier is that it might find the export specifier itself, and try to + // resolve it as an alias. This will cause the checker to consider the export specifier + // a circular alias reference when it might not be. + // 2. We check === SymbolFlags.Alias in order to check that the symbol is *purely* + // an alias. If we used &, we'd be throwing out symbols that have non alias aspects, + // which is not the desired behavior. + var moduleExport = moduleExports.get(name); + if (moduleExport && + moduleExport.flags === 2097152 /* Alias */ && + ts.getDeclarationOfKind(moduleExport, 257 /* ExportSpecifier */)) { + break; + } + } + // ES6 exports are also visible locally (except for 'default'), but commonjs exports are not (except typedefs) + if (name !== "default" /* Default */ && (result = lookup(moduleExports, name, meaning & 2623475 /* ModuleMember */))) { + if (ts.isSourceFile(location) && location.commonJsModuleIndicator && !result.declarations.some(ts.isJSDocTypeAlias)) { + result = undefined; + } + else { + break loop; + } + } + break; + case 243 /* EnumDeclaration */: + if (result = lookup(getSymbolOfNode(location).exports, name, meaning & 8 /* EnumMember */)) { + break loop; + } + break; + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + // TypeScript 1.0 spec (April 2014): 8.4.1 + // Initializer expressions for instance member variables are evaluated in the scope + // of the class constructor body but are not permitted to reference parameters or + // local variables of the constructor. This effectively means that entities from outer scopes + // by the same name as a constructor parameter or local variable are inaccessible + // in initializer expressions for instance member variables. + if (ts.isClassLike(location.parent) && !ts.hasModifier(location, 32 /* Static */)) { + var ctor = findConstructorDeclaration(location.parent); + if (ctor && ctor.locals) { + if (lookup(ctor.locals, name, meaning & 67220415 /* Value */)) { + // Remember the property node, it will be used later to report appropriate error + propertyWithInvalidInitializer = location; + } + } + } + break; + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 241 /* InterfaceDeclaration */: + // The below is used to lookup type parameters within a class or interface, as they are added to the class/interface locals + // These can never be latebound, so the symbol's raw members are sufficient. `getMembersOfNode` cannot be used, as it would + // trigger resolving late-bound names, which we may already be in the process of doing while we're here! + if (result = lookup(getSymbolOfNode(location).members || emptySymbols, name, meaning & 67897832 /* Type */)) { + if (!isTypeParameterSymbolDeclaredInContainer(result, location)) { + // ignore type parameters not declared in this container + result = undefined; + break; + } + if (lastLocation && ts.hasModifier(lastLocation, 32 /* Static */)) { + // TypeScript 1.0 spec (April 2014): 3.4.1 + // The scope of a type parameter extends over the entire declaration with which the type + // parameter list is associated, with the exception of static member declarations in classes. + error(errorLocation, ts.Diagnostics.Static_members_cannot_reference_class_type_parameters); + return undefined; + } + break loop; + } + if (location.kind === 209 /* ClassExpression */ && meaning & 32 /* Class */) { + var className = location.name; + if (className && name === className.escapedText) { + result = location.symbol; + break loop; + } + } + break; + case 211 /* ExpressionWithTypeArguments */: + // The type parameters of a class are not in scope in the base class expression. + if (lastLocation === location.expression && location.parent.token === 86 /* ExtendsKeyword */) { + var container = location.parent.parent; + if (ts.isClassLike(container) && (result = lookup(getSymbolOfNode(container).members, name, meaning & 67897832 /* Type */))) { + if (nameNotFoundMessage) { + error(errorLocation, ts.Diagnostics.Base_class_expressions_cannot_reference_class_type_parameters); + } + return undefined; + } + } + break; + // It is not legal to reference a class's own type parameters from a computed property name that + // belongs to the class. For example: + // + // function foo() { return '' } + // class C { // <-- Class's own type parameter T + // [foo()]() { } // <-- Reference to T from class's own computed property + // } + // + case 149 /* ComputedPropertyName */: + grandparent = location.parent.parent; + if (ts.isClassLike(grandparent) || grandparent.kind === 241 /* InterfaceDeclaration */) { + // A reference to this grandparent's type parameters would be an error + if (result = lookup(getSymbolOfNode(grandparent).members, name, meaning & 67897832 /* Type */)) { + error(errorLocation, ts.Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type); + return undefined; + } + } + break; + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 239 /* FunctionDeclaration */: + case 197 /* ArrowFunction */: + if (meaning & 3 /* Variable */ && name === "arguments") { + result = argumentsSymbol; + break loop; + } + break; + case 196 /* FunctionExpression */: + if (meaning & 3 /* Variable */ && name === "arguments") { + result = argumentsSymbol; + break loop; + } + if (meaning & 16 /* Function */) { + var functionName = location.name; + if (functionName && name === functionName.escapedText) { + result = location.symbol; + break loop; + } + } + break; + case 152 /* Decorator */: + // Decorators are resolved at the class declaration. Resolving at the parameter + // or member would result in looking up locals in the method. + // + // function y() {} + // class C { + // method(@y x, y) {} // <-- decorator y should be resolved at the class declaration, not the parameter. + // } + // + if (location.parent && location.parent.kind === 151 /* Parameter */) { + location = location.parent; + } + // + // function y() {} + // class C { + // @y method(x, y) {} // <-- decorator y should be resolved at the class declaration, not the method. + // } + // + if (location.parent && ts.isClassElement(location.parent)) { + location = location.parent; + } + break; + case 304 /* JSDocTypedefTag */: + case 297 /* JSDocCallbackTag */: + // js type aliases do not resolve names from their host, so skip past it + location = ts.getJSDocHost(location); + break; + } + if (isSelfReferenceLocation(location)) { + lastSelfReferenceLocation = location; + } + lastLocation = location; + location = location.parent; + } + // We just climbed up parents looking for the name, meaning that we started in a descendant node of `lastLocation`. + // If `result === lastSelfReferenceLocation.symbol`, that means that we are somewhere inside `lastSelfReferenceLocation` looking up a name, and resolving to `lastLocation` itself. + // That means that this is a self-reference of `lastLocation`, and shouldn't count this when considering whether `lastLocation` is used. + if (isUse && result && (!lastSelfReferenceLocation || result !== lastSelfReferenceLocation.symbol)) { + result.isReferenced |= meaning; + } + if (!result) { + if (lastLocation) { + ts.Debug.assert(lastLocation.kind === 279 /* SourceFile */); + if (lastLocation.commonJsModuleIndicator && name === "exports" && meaning & lastLocation.symbol.flags) { + return lastLocation.symbol; + } + } + if (!excludeGlobals) { + result = lookup(globals, name, meaning); + } + } + if (!result) { + if (originalLocation && ts.isInJSFile(originalLocation) && originalLocation.parent) { + if (ts.isRequireCall(originalLocation.parent, /*checkArgumentIsStringLiteralLike*/ false)) { + return requireSymbol; + } + } + } + if (!result) { + if (nameNotFoundMessage) { + if (!errorLocation || + !checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) && // TODO: GH#18217 + !checkAndReportErrorForExtendingInterface(errorLocation) && + !checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) && + !checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) && + !checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning)) { + var suggestion = void 0; + if (suggestedNameNotFoundMessage && suggestionCount < maximumSuggestionCount) { + suggestion = getSuggestedSymbolForNonexistentSymbol(originalLocation, name, meaning); + if (suggestion) { + var suggestionName = symbolToString(suggestion); + var diagnostic = error(errorLocation, suggestedNameNotFoundMessage, diagnosticName(nameArg), suggestionName); + if (suggestion.valueDeclaration) { + addRelatedInfo(diagnostic, ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestionName)); + } + } + } + if (!suggestion) { + error(errorLocation, nameNotFoundMessage, diagnosticName(nameArg)); + } + suggestionCount++; + } + } + return undefined; + } + // Perform extra checks only if error reporting was requested + if (nameNotFoundMessage) { + if (propertyWithInvalidInitializer) { + // We have a match, but the reference occurred within a property initializer and the identifier also binds + // to a local variable in the constructor where the code will be emitted. + var propertyName = propertyWithInvalidInitializer.name; + error(errorLocation, ts.Diagnostics.Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor, ts.declarationNameToString(propertyName), diagnosticName(nameArg)); + return undefined; + } + // Only check for block-scoped variable if we have an error location and are looking for the + // name with variable meaning + // For example, + // declare module foo { + // interface bar {} + // } + // const foo/*1*/: foo/*2*/.bar; + // The foo at /*1*/ and /*2*/ will share same symbol with two meanings: + // block-scoped variable and namespace module. However, only when we + // try to resolve name in /*1*/ which is used in variable position, + // we want to check for block-scoped + if (errorLocation && + (meaning & 2 /* BlockScopedVariable */ || + ((meaning & 32 /* Class */ || meaning & 384 /* Enum */) && (meaning & 67220415 /* Value */) === 67220415 /* Value */))) { + var exportOrLocalSymbol = getExportSymbolOfValueSymbolIfExported(result); + if (exportOrLocalSymbol.flags & 2 /* BlockScopedVariable */ || exportOrLocalSymbol.flags & 32 /* Class */ || exportOrLocalSymbol.flags & 384 /* Enum */) { + checkResolvedBlockScopedVariable(exportOrLocalSymbol, errorLocation); + } + } + // If we're in an external module, we can't reference value symbols created from UMD export declarations + if (result && isInExternalModule && (meaning & 67220415 /* Value */) === 67220415 /* Value */ && !(originalLocation.flags & 2097152 /* JSDoc */)) { + if (ts.some(result.declarations, function (d) { return ts.isNamespaceExportDeclaration(d) || ts.isSourceFile(d) && !!d.symbol.globalExports; })) { + error(errorLocation, ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead, ts.unescapeLeadingUnderscores(name)); // TODO: GH#18217 + } + } + } + return result; + } + function isSelfReferenceLocation(node) { + switch (node.kind) { + case 239 /* FunctionDeclaration */: + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + case 243 /* EnumDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 244 /* ModuleDeclaration */: // For `namespace N { N; }` + return true; + default: + return false; + } + } + function diagnosticName(nameArg) { + return ts.isString(nameArg) ? ts.unescapeLeadingUnderscores(nameArg) : ts.declarationNameToString(nameArg); + } + function isTypeParameterSymbolDeclaredInContainer(symbol, container) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + if (decl.kind === 150 /* TypeParameter */) { + var parent = ts.isJSDocTemplateTag(decl.parent) ? ts.getJSDocHost(decl.parent) : decl.parent; + if (parent === container) { + return !(ts.isJSDocTemplateTag(decl.parent) && ts.find(decl.parent.parent.tags, ts.isJSDocTypeAlias)); // TODO: GH#18217 + } + } + } + return false; + } + function checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) { + if (!ts.isIdentifier(errorLocation) || errorLocation.escapedText !== name || isTypeReferenceIdentifier(errorLocation) || isInTypeQuery(errorLocation)) { + return false; + } + var container = ts.getThisContainer(errorLocation, /*includeArrowFunctions*/ false); + var location = container; + while (location) { + if (ts.isClassLike(location.parent)) { + var classSymbol = getSymbolOfNode(location.parent); + if (!classSymbol) { + break; + } + // Check to see if a static member exists. + var constructorType = getTypeOfSymbol(classSymbol); + if (getPropertyOfType(constructorType, name)) { + error(errorLocation, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_static_member_1_0, diagnosticName(nameArg), symbolToString(classSymbol)); + return true; + } + // No static member is present. + // Check if we're in an instance method and look for a relevant instance member. + if (location === container && !ts.hasModifier(location, 32 /* Static */)) { + var instanceType = getDeclaredTypeOfSymbol(classSymbol).thisType; // TODO: GH#18217 + if (getPropertyOfType(instanceType, name)) { + error(errorLocation, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0, diagnosticName(nameArg)); + return true; + } + } + } + location = location.parent; + } + return false; + } + function checkAndReportErrorForExtendingInterface(errorLocation) { + var expression = getEntityNameForExtendingInterface(errorLocation); + if (expression && resolveEntityName(expression, 64 /* Interface */, /*ignoreErrors*/ true)) { + error(errorLocation, ts.Diagnostics.Cannot_extend_an_interface_0_Did_you_mean_implements, ts.getTextOfNode(expression)); + return true; + } + return false; + } + /** + * Climbs up parents to an ExpressionWithTypeArguments, and returns its expression, + * but returns undefined if that expression is not an EntityNameExpression. + */ + function getEntityNameForExtendingInterface(node) { + switch (node.kind) { + case 72 /* Identifier */: + case 189 /* PropertyAccessExpression */: + return node.parent ? getEntityNameForExtendingInterface(node.parent) : undefined; + case 211 /* ExpressionWithTypeArguments */: + if (ts.isEntityNameExpression(node.expression)) { + return node.expression; + } + // falls through + default: + return undefined; + } + } + function checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) { + var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJSFile(errorLocation) ? 67220415 /* Value */ : 0); + if (meaning === namespaceMeaning) { + var symbol = resolveSymbol(resolveName(errorLocation, name, 67897832 /* Type */ & ~namespaceMeaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + var parent = errorLocation.parent; + if (symbol) { + if (ts.isQualifiedName(parent)) { + ts.Debug.assert(parent.left === errorLocation, "Should only be resolving left side of qualified name as a namespace"); + var propName = parent.right.escapedText; + var propType = getPropertyOfType(getDeclaredTypeOfSymbol(symbol), propName); + if (propType) { + error(parent, ts.Diagnostics.Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_property_1_in_0_with_0_1, ts.unescapeLeadingUnderscores(name), ts.unescapeLeadingUnderscores(propName)); + return true; + } + } + error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here, ts.unescapeLeadingUnderscores(name)); + return true; + } + } + return false; + } + function checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) { + if (meaning & (67220415 /* Value */ & ~1024 /* NamespaceModule */)) { + if (name === "any" || name === "string" || name === "number" || name === "boolean" || name === "never") { + error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, ts.unescapeLeadingUnderscores(name)); + return true; + } + var symbol = resolveSymbol(resolveName(errorLocation, name, 67897832 /* Type */ & ~67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + if (symbol && !(symbol.flags & 1024 /* NamespaceModule */)) { + var message = (name === "Promise" || name === "Symbol") + ? ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later + : ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here; + error(errorLocation, message, ts.unescapeLeadingUnderscores(name)); + return true; + } + } + return false; + } + function checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) { + if (meaning & (67220415 /* Value */ & ~1024 /* NamespaceModule */ & ~67897832 /* Type */)) { + var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 /* NamespaceModule */ & ~67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + if (symbol) { + error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_value, ts.unescapeLeadingUnderscores(name)); + return true; + } + } + else if (meaning & (67897832 /* Type */ & ~1024 /* NamespaceModule */ & ~67220415 /* Value */)) { + var symbol = resolveSymbol(resolveName(errorLocation, name, (512 /* ValueModule */ | 1024 /* NamespaceModule */) & ~67897832 /* Type */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + if (symbol) { + error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_type, ts.unescapeLeadingUnderscores(name)); + return true; + } + } + return false; + } + function checkResolvedBlockScopedVariable(result, errorLocation) { + ts.Debug.assert(!!(result.flags & 2 /* BlockScopedVariable */ || result.flags & 32 /* Class */ || result.flags & 384 /* Enum */)); + // Block-scoped variables cannot be used before their definition + var declaration = ts.find(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) || ts.isClassLike(d) || (d.kind === 243 /* EnumDeclaration */) || ts.isInJSFile(d) && !!ts.getJSDocEnumTag(d); }); + if (declaration === undefined) + return ts.Debug.fail("Declaration to checkResolvedBlockScopedVariable is undefined"); + if (!(declaration.flags & 4194304 /* Ambient */) && !isBlockScopedNameDeclaredBeforeUse(declaration, errorLocation)) { + var diagnosticMessage = void 0; + var declarationName = ts.declarationNameToString(ts.getNameOfDeclaration(declaration)); + if (result.flags & 2 /* BlockScopedVariable */) { + diagnosticMessage = error(errorLocation, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, declarationName); + } + else if (result.flags & 32 /* Class */) { + diagnosticMessage = error(errorLocation, ts.Diagnostics.Class_0_used_before_its_declaration, declarationName); + } + else if (result.flags & 256 /* RegularEnum */) { + diagnosticMessage = error(errorLocation, ts.Diagnostics.Enum_0_used_before_its_declaration, declarationName); + } + else { + ts.Debug.assert(!!(result.flags & 128 /* ConstEnum */)); + if (compilerOptions.preserveConstEnums) { + diagnosticMessage = error(errorLocation, ts.Diagnostics.Class_0_used_before_its_declaration, declarationName); + } + } + if (diagnosticMessage) { + addRelatedInfo(diagnosticMessage, ts.createDiagnosticForNode(declaration, ts.Diagnostics._0_is_declared_here, declarationName)); + } + } + } + /* Starting from 'initial' node walk up the parent chain until 'stopAt' node is reached. + * If at any point current node is equal to 'parent' node - return true. + * Return false if 'stopAt' node is reached or isFunctionLike(current) === true. + */ + function isSameScopeDescendentOf(initial, parent, stopAt) { + return !!parent && !!ts.findAncestor(initial, function (n) { return n === stopAt || ts.isFunctionLike(n) ? "quit" : n === parent; }); + } + function getAnyImportSyntax(node) { + switch (node.kind) { + case 248 /* ImportEqualsDeclaration */: + return node; + case 250 /* ImportClause */: + return node.parent; + case 251 /* NamespaceImport */: + return node.parent.parent; + case 253 /* ImportSpecifier */: + return node.parent.parent.parent; + default: + return undefined; + } + } + function getDeclarationOfAliasSymbol(symbol) { + return ts.find(symbol.declarations, ts.isAliasSymbolDeclaration); + } + function getTargetOfImportEqualsDeclaration(node, dontResolveAlias) { + if (node.moduleReference.kind === 259 /* ExternalModuleReference */) { + return resolveExternalModuleSymbol(resolveExternalModuleName(node, ts.getExternalModuleImportEqualsDeclarationExpression(node))); + } + return getSymbolOfPartOfRightHandSideOfImportEquals(node.moduleReference, dontResolveAlias); + } + function resolveExportByName(moduleSymbol, name, dontResolveAlias) { + var exportValue = moduleSymbol.exports.get("export=" /* ExportEquals */); + return exportValue + ? getPropertyOfType(getTypeOfSymbol(exportValue), name) + : resolveSymbol(moduleSymbol.exports.get(name), dontResolveAlias); + } + function isSyntacticDefault(node) { + return ((ts.isExportAssignment(node) && !node.isExportEquals) || ts.hasModifier(node, 512 /* Default */) || ts.isExportSpecifier(node)); + } + function canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias) { + if (!allowSyntheticDefaultImports) { + return false; + } + // Declaration files (and ambient modules) + if (!file || file.isDeclarationFile) { + // Definitely cannot have a synthetic default if they have a syntactic default member specified + var defaultExportSymbol = resolveExportByName(moduleSymbol, "default" /* Default */, /*dontResolveAlias*/ true); // Dont resolve alias because we want the immediately exported symbol's declaration + if (defaultExportSymbol && ts.some(defaultExportSymbol.declarations, isSyntacticDefault)) { + return false; + } + // It _might_ still be incorrect to assume there is no __esModule marker on the import at runtime, even if there is no `default` member + // So we check a bit more, + if (resolveExportByName(moduleSymbol, ts.escapeLeadingUnderscores("__esModule"), dontResolveAlias)) { + // If there is an `__esModule` specified in the declaration (meaning someone explicitly added it or wrote it in their code), + // it definitely is a module and does not have a synthetic default + return false; + } + // There are _many_ declaration files not written with esmodules in mind that still get compiled into a format with __esModule set + // Meaning there may be no default at runtime - however to be on the permissive side, we allow access to a synthetic default member + // as there is no marker to indicate if the accompanying JS has `__esModule` or not, or is even native esm + return true; + } + // TypeScript files never have a synthetic default (as they are always emitted with an __esModule marker) _unless_ they contain an export= statement + if (!ts.isSourceFileJS(file)) { + return hasExportAssignmentSymbol(moduleSymbol); + } + // JS files have a synthetic default if they do not contain ES2015+ module syntax (export = is not valid in js) _and_ do not have an __esModule marker + return !file.externalModuleIndicator && !resolveExportByName(moduleSymbol, ts.escapeLeadingUnderscores("__esModule"), dontResolveAlias); + } + function getTargetOfImportClause(node, dontResolveAlias) { + var moduleSymbol = resolveExternalModuleName(node, node.parent.moduleSpecifier); + if (moduleSymbol) { + var exportDefaultSymbol = void 0; + if (ts.isShorthandAmbientModuleSymbol(moduleSymbol)) { + exportDefaultSymbol = moduleSymbol; + } + else { + exportDefaultSymbol = resolveExportByName(moduleSymbol, "default" /* Default */, dontResolveAlias); + } + var file = ts.find(moduleSymbol.declarations, ts.isSourceFile); + var hasSyntheticDefault = canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias); + if (!exportDefaultSymbol && !hasSyntheticDefault) { + error(node.name, ts.Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol)); + } + else if (hasSyntheticDefault) { + // per emit behavior, a synthetic default overrides a "real" .default member if `__esModule` is not present + return resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias); + } + return exportDefaultSymbol; + } + } + function getTargetOfNamespaceImport(node, dontResolveAlias) { + var moduleSpecifier = node.parent.parent.moduleSpecifier; + return resolveESModuleSymbol(resolveExternalModuleName(node, moduleSpecifier), moduleSpecifier, dontResolveAlias); + } + // This function creates a synthetic symbol that combines the value side of one symbol with the + // type/namespace side of another symbol. Consider this example: + // + // declare module graphics { + // interface Point { + // x: number; + // y: number; + // } + // } + // declare var graphics: { + // Point: new (x: number, y: number) => graphics.Point; + // } + // declare module "graphics" { + // export = graphics; + // } + // + // An 'import { Point } from "graphics"' needs to create a symbol that combines the value side 'Point' + // property with the type/namespace side interface 'Point'. + function combineValueAndTypeSymbols(valueSymbol, typeSymbol) { + if (valueSymbol === unknownSymbol && typeSymbol === unknownSymbol) { + return unknownSymbol; + } + if (valueSymbol.flags & (67897832 /* Type */ | 1920 /* Namespace */)) { + return valueSymbol; + } + var result = createSymbol(valueSymbol.flags | typeSymbol.flags, valueSymbol.escapedName); + result.declarations = ts.deduplicate(ts.concatenate(valueSymbol.declarations, typeSymbol.declarations), ts.equateValues); + result.parent = valueSymbol.parent || typeSymbol.parent; + if (valueSymbol.valueDeclaration) + result.valueDeclaration = valueSymbol.valueDeclaration; + if (typeSymbol.members) + result.members = typeSymbol.members; + if (valueSymbol.exports) + result.exports = valueSymbol.exports; + return result; + } + function getExportOfModule(symbol, name, dontResolveAlias) { + if (symbol.flags & 1536 /* Module */) { + return resolveSymbol(getExportsOfSymbol(symbol).get(name), dontResolveAlias); + } + } + function getPropertyOfVariable(symbol, name) { + if (symbol.flags & 3 /* Variable */) { + var typeAnnotation = symbol.valueDeclaration.type; + if (typeAnnotation) { + return resolveSymbol(getPropertyOfType(getTypeFromTypeNode(typeAnnotation), name)); + } + } + } + function getExternalModuleMember(node, specifier, dontResolveAlias) { + if (dontResolveAlias === void 0) { dontResolveAlias = false; } + var moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier); // TODO: GH#18217 + var targetSymbol = resolveESModuleSymbol(moduleSymbol, node.moduleSpecifier, dontResolveAlias); + if (targetSymbol) { + var name = specifier.propertyName || specifier.name; + if (name.escapedText) { + if (ts.isShorthandAmbientModuleSymbol(moduleSymbol)) { + return moduleSymbol; + } + var symbolFromVariable = void 0; + // First check if module was specified with "export=". If so, get the member from the resolved type + if (moduleSymbol && moduleSymbol.exports && moduleSymbol.exports.get("export=" /* ExportEquals */)) { + symbolFromVariable = getPropertyOfType(getTypeOfSymbol(targetSymbol), name.escapedText); + } + else { + symbolFromVariable = getPropertyOfVariable(targetSymbol, name.escapedText); + } + // if symbolFromVariable is export - get its final target + symbolFromVariable = resolveSymbol(symbolFromVariable, dontResolveAlias); + var symbolFromModule = getExportOfModule(targetSymbol, name.escapedText, dontResolveAlias); + // If the export member we're looking for is default, and there is no real default but allowSyntheticDefaultImports is on, return the entire module as the default + if (!symbolFromModule && allowSyntheticDefaultImports && name.escapedText === "default" /* Default */) { + symbolFromModule = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias); + } + var symbol = symbolFromModule && symbolFromVariable && symbolFromModule !== symbolFromVariable ? + combineValueAndTypeSymbols(symbolFromVariable, symbolFromModule) : + symbolFromModule || symbolFromVariable; + if (!symbol) { + var moduleName = getFullyQualifiedName(moduleSymbol, node); + var declarationName = ts.declarationNameToString(name); + var suggestion = getSuggestedSymbolForNonexistentModule(name, targetSymbol); + if (suggestion !== undefined) { + var suggestionName = symbolToString(suggestion); + var diagnostic = error(name, ts.Diagnostics.Module_0_has_no_exported_member_1_Did_you_mean_2, moduleName, declarationName, suggestionName); + if (suggestion.valueDeclaration) { + addRelatedInfo(diagnostic, ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestionName)); + } + } + else { + error(name, ts.Diagnostics.Module_0_has_no_exported_member_1, moduleName, declarationName); + } + } + return symbol; + } + } + } + function getTargetOfImportSpecifier(node, dontResolveAlias) { + return getExternalModuleMember(node.parent.parent.parent, node, dontResolveAlias); + } + function getTargetOfNamespaceExportDeclaration(node, dontResolveAlias) { + return resolveExternalModuleSymbol(node.parent.symbol, dontResolveAlias); + } + function getTargetOfExportSpecifier(node, meaning, dontResolveAlias) { + return node.parent.parent.moduleSpecifier ? + getExternalModuleMember(node.parent.parent, node, dontResolveAlias) : + resolveEntityName(node.propertyName || node.name, meaning, /*ignoreErrors*/ false, dontResolveAlias); + } + function getTargetOfExportAssignment(node, dontResolveAlias) { + var expression = (ts.isExportAssignment(node) ? node.expression : node.right); + if (ts.isClassExpression(expression)) { + return checkExpression(expression).symbol; + } + var aliasLike = resolveEntityName(expression, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ true, dontResolveAlias); + if (aliasLike) { + return aliasLike; + } + checkExpression(expression); + return getNodeLinks(expression).resolvedSymbol; + } + function getTargetOfAliasDeclaration(node, dontRecursivelyResolve) { + if (dontRecursivelyResolve === void 0) { dontRecursivelyResolve = false; } + switch (node.kind) { + case 248 /* ImportEqualsDeclaration */: + return getTargetOfImportEqualsDeclaration(node, dontRecursivelyResolve); + case 250 /* ImportClause */: + return getTargetOfImportClause(node, dontRecursivelyResolve); + case 251 /* NamespaceImport */: + return getTargetOfNamespaceImport(node, dontRecursivelyResolve); + case 253 /* ImportSpecifier */: + return getTargetOfImportSpecifier(node, dontRecursivelyResolve); + case 257 /* ExportSpecifier */: + return getTargetOfExportSpecifier(node, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */, dontRecursivelyResolve); + case 254 /* ExportAssignment */: + case 204 /* BinaryExpression */: + return getTargetOfExportAssignment(node, dontRecursivelyResolve); + case 247 /* NamespaceExportDeclaration */: + return getTargetOfNamespaceExportDeclaration(node, dontRecursivelyResolve); + default: + return ts.Debug.fail(); + } + } + /** + * Indicates that a symbol is an alias that does not merge with a local declaration. + * OR Is a JSContainer which may merge an alias with a local declaration + */ + function isNonLocalAlias(symbol, excludes) { + if (excludes === void 0) { excludes = 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */; } + if (!symbol) + return false; + return (symbol.flags & (2097152 /* Alias */ | excludes)) === 2097152 /* Alias */ || !!(symbol.flags & 2097152 /* Alias */ && symbol.flags & 67108864 /* Assignment */); + } + function resolveSymbol(symbol, dontResolveAlias) { + return !dontResolveAlias && isNonLocalAlias(symbol) ? resolveAlias(symbol) : symbol; + } + function resolveAlias(symbol) { + ts.Debug.assert((symbol.flags & 2097152 /* Alias */) !== 0, "Should only get Alias here."); + var links = getSymbolLinks(symbol); + if (!links.target) { + links.target = resolvingSymbol; + var node = getDeclarationOfAliasSymbol(symbol); + if (!node) + return ts.Debug.fail(); + var target = getTargetOfAliasDeclaration(node); + if (links.target === resolvingSymbol) { + links.target = target || unknownSymbol; + } + else { + error(node, ts.Diagnostics.Circular_definition_of_import_alias_0, symbolToString(symbol)); + } + } + else if (links.target === resolvingSymbol) { + links.target = unknownSymbol; + } + return links.target; + } + function markExportAsReferenced(node) { + var symbol = getSymbolOfNode(node); + var target = resolveAlias(symbol); + if (target) { + var markAlias = target === unknownSymbol || + ((target.flags & 67220415 /* Value */) && !isConstEnumOrConstEnumOnlyModule(target)); + if (markAlias) { + markAliasSymbolAsReferenced(symbol); + } + } + } + // When an alias symbol is referenced, we need to mark the entity it references as referenced and in turn repeat that until + // we reach a non-alias or an exported entity (which is always considered referenced). We do this by checking the target of + // the alias as an expression (which recursively takes us back here if the target references another alias). + function markAliasSymbolAsReferenced(symbol) { + var links = getSymbolLinks(symbol); + if (!links.referenced) { + links.referenced = true; + var node = getDeclarationOfAliasSymbol(symbol); + if (!node) + return ts.Debug.fail(); + if (node.kind === 254 /* ExportAssignment */) { + // export default + checkExpressionCached(node.expression); + } + else if (node.kind === 257 /* ExportSpecifier */) { + // export { } or export { as foo } + checkExpressionCached(node.propertyName || node.name); + } + else if (ts.isInternalModuleImportEqualsDeclaration(node)) { + // import foo = + checkExpressionCached(node.moduleReference); + } + } + } + // This function is only for imports with entity names + function getSymbolOfPartOfRightHandSideOfImportEquals(entityName, dontResolveAlias) { + // There are three things we might try to look for. In the following examples, + // the search term is enclosed in |...|: + // + // import a = |b|; // Namespace + // import a = |b.c|; // Value, type, namespace + // import a = |b.c|.d; // Namespace + if (entityName.kind === 72 /* Identifier */ && ts.isRightSideOfQualifiedNameOrPropertyAccess(entityName)) { + entityName = entityName.parent; + } + // Check for case 1 and 3 in the above example + if (entityName.kind === 72 /* Identifier */ || entityName.parent.kind === 148 /* QualifiedName */) { + return resolveEntityName(entityName, 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); + } + else { + // Case 2 in above example + // entityName.kind could be a QualifiedName or a Missing identifier + ts.Debug.assert(entityName.parent.kind === 248 /* ImportEqualsDeclaration */); + return resolveEntityName(entityName, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); + } + } + function getFullyQualifiedName(symbol, containingLocation) { + return symbol.parent ? getFullyQualifiedName(symbol.parent, containingLocation) + "." + symbolToString(symbol) : symbolToString(symbol, containingLocation, /*meaning*/ undefined, 16 /* DoNotIncludeSymbolChain */ | 4 /* AllowAnyNodeKind */); + } + /** + * Resolves a qualified name and any involved aliases. + */ + function resolveEntityName(name, meaning, ignoreErrors, dontResolveAlias, location) { + if (ts.nodeIsMissing(name)) { + return undefined; + } + var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJSFile(name) ? meaning & 67220415 /* Value */ : 0); + var symbol; + if (name.kind === 72 /* Identifier */) { + var message = meaning === namespaceMeaning ? ts.Diagnostics.Cannot_find_namespace_0 : getCannotFindNameDiagnosticForName(getFirstIdentifier(name).escapedText); + var symbolFromJSPrototype = ts.isInJSFile(name) ? resolveEntityNameFromAssignmentDeclaration(name, meaning) : undefined; + symbol = resolveName(location || name, name.escapedText, meaning, ignoreErrors || symbolFromJSPrototype ? undefined : message, name, /*isUse*/ true); + if (!symbol) { + return symbolFromJSPrototype; + } + } + else if (name.kind === 148 /* QualifiedName */ || name.kind === 189 /* PropertyAccessExpression */) { + var left = name.kind === 148 /* QualifiedName */ ? name.left : name.expression; + var right = name.kind === 148 /* QualifiedName */ ? name.right : name.name; + var namespace = resolveEntityName(left, namespaceMeaning, ignoreErrors, /*dontResolveAlias*/ false, location); + if (!namespace || ts.nodeIsMissing(right)) { + return undefined; + } + else if (namespace === unknownSymbol) { + return namespace; + } + if (ts.isInJSFile(name)) { + if (namespace.valueDeclaration && + ts.isVariableDeclaration(namespace.valueDeclaration) && + namespace.valueDeclaration.initializer && + isCommonJsRequire(namespace.valueDeclaration.initializer)) { + var moduleName = namespace.valueDeclaration.initializer.arguments[0]; + var moduleSym = resolveExternalModuleName(moduleName, moduleName); + if (moduleSym) { + var resolvedModuleSymbol = resolveExternalModuleSymbol(moduleSym); + if (resolvedModuleSymbol) { + namespace = resolvedModuleSymbol; + } + } + } + } + symbol = getSymbol(getExportsOfSymbol(namespace), right.escapedText, meaning); + if (!symbol) { + if (!ignoreErrors) { + error(right, ts.Diagnostics.Namespace_0_has_no_exported_member_1, getFullyQualifiedName(namespace), ts.declarationNameToString(right)); + } + return undefined; + } + } + else { + throw ts.Debug.assertNever(name, "Unknown entity name kind."); + } + ts.Debug.assert((ts.getCheckFlags(symbol) & 1 /* Instantiated */) === 0, "Should never get an instantiated symbol here."); + return (symbol.flags & meaning) || dontResolveAlias ? symbol : resolveAlias(symbol); + } + /** + * 1. For prototype-property methods like `A.prototype.m = function () ...`, try to resolve names in the scope of `A` too. + * Note that prototype-property assignment to locations outside the current file (eg globals) doesn't work, so + * name resolution won't work either. + * 2. For property assignments like `{ x: function f () { } }`, try to resolve names in the scope of `f` too. + */ + function resolveEntityNameFromAssignmentDeclaration(name, meaning) { + if (isJSDocTypeReference(name.parent)) { + var secondaryLocation = getAssignmentDeclarationLocation(name.parent); + if (secondaryLocation) { + return resolveName(secondaryLocation, name.escapedText, meaning, /*nameNotFoundMessage*/ undefined, name, /*isUse*/ true); + } + } + } + function getAssignmentDeclarationLocation(node) { + var typeAlias = ts.findAncestor(node, function (node) { return !(ts.isJSDocNode(node) || node.flags & 2097152 /* JSDoc */) ? "quit" : ts.isJSDocTypeAlias(node); }); + if (typeAlias) { + return; + } + var host = ts.getJSDocHost(node); + if (ts.isExpressionStatement(host) && + ts.isBinaryExpression(host.expression) && + ts.getAssignmentDeclarationKind(host.expression) === 3 /* PrototypeProperty */) { + // X.prototype.m = /** @param {K} p */ function () { } <-- look for K on X's declaration + var symbol = getSymbolOfNode(host.expression.left); + if (symbol) { + return getDeclarationOfJSPrototypeContainer(symbol); + } + } + if ((ts.isObjectLiteralMethod(host) || ts.isPropertyAssignment(host)) && + ts.isBinaryExpression(host.parent.parent) && + ts.getAssignmentDeclarationKind(host.parent.parent) === 6 /* Prototype */) { + // X.prototype = { /** @param {K} p */m() { } } <-- look for K on X's declaration + var symbol = getSymbolOfNode(host.parent.parent.left); + if (symbol) { + return getDeclarationOfJSPrototypeContainer(symbol); + } + } + var sig = ts.getHostSignatureFromJSDocHost(host); + if (sig) { + var symbol = getSymbolOfNode(sig); + return symbol && symbol.valueDeclaration; + } + } + function getDeclarationOfJSPrototypeContainer(symbol) { + var decl = symbol.parent.valueDeclaration; + if (!decl) { + return undefined; + } + var initializer = ts.isAssignmentDeclaration(decl) ? ts.getAssignedExpandoInitializer(decl) : + ts.hasOnlyExpressionInitializer(decl) ? ts.getDeclaredExpandoInitializer(decl) : + undefined; + return initializer || decl; + } + function resolveExternalModuleName(location, moduleReferenceExpression, ignoreErrors) { + return resolveExternalModuleNameWorker(location, moduleReferenceExpression, ignoreErrors ? undefined : ts.Diagnostics.Cannot_find_module_0); + } + function resolveExternalModuleNameWorker(location, moduleReferenceExpression, moduleNotFoundError, isForAugmentation) { + if (isForAugmentation === void 0) { isForAugmentation = false; } + return ts.isStringLiteralLike(moduleReferenceExpression) + ? resolveExternalModule(location, moduleReferenceExpression.text, moduleNotFoundError, moduleReferenceExpression, isForAugmentation) + : undefined; + } + function resolveExternalModule(location, moduleReference, moduleNotFoundError, errorNode, isForAugmentation) { + if (isForAugmentation === void 0) { isForAugmentation = false; } + if (moduleReference === undefined) { + return; + } + if (ts.startsWith(moduleReference, "@types/")) { + var diag = ts.Diagnostics.Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1; + var withoutAtTypePrefix = ts.removePrefix(moduleReference, "@types/"); + error(errorNode, diag, withoutAtTypePrefix, moduleReference); + } + var ambientModule = tryFindAmbientModule(moduleReference, /*withAugmentations*/ true); + if (ambientModule) { + return ambientModule; + } + var currentSourceFile = ts.getSourceFileOfNode(location); + var resolvedModule = ts.getResolvedModule(currentSourceFile, moduleReference); // TODO: GH#18217 + var resolutionDiagnostic = resolvedModule && ts.getResolutionDiagnostic(compilerOptions, resolvedModule); + var sourceFile = resolvedModule && !resolutionDiagnostic && host.getSourceFile(resolvedModule.resolvedFileName); + if (sourceFile) { + if (sourceFile.symbol) { + if (resolvedModule.isExternalLibraryImport && !ts.resolutionExtensionIsTSOrJson(resolvedModule.extension)) { + errorOnImplicitAnyModule(/*isError*/ false, errorNode, resolvedModule, moduleReference); + } + // merged symbol is module declaration symbol combined with all augmentations + return getMergedSymbol(sourceFile.symbol); + } + if (moduleNotFoundError) { + // report errors only if it was requested + error(errorNode, ts.Diagnostics.File_0_is_not_a_module, sourceFile.fileName); + } + return undefined; + } + if (patternAmbientModules) { + var pattern = ts.findBestPatternMatch(patternAmbientModules, function (_) { return _.pattern; }, moduleReference); + if (pattern) { + return getMergedSymbol(pattern.symbol); + } + } + // May be an untyped module. If so, ignore resolutionDiagnostic. + if (resolvedModule && !ts.resolutionExtensionIsTSOrJson(resolvedModule.extension) && resolutionDiagnostic === undefined || resolutionDiagnostic === ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type) { + if (isForAugmentation) { + var diag = ts.Diagnostics.Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented; + error(errorNode, diag, moduleReference, resolvedModule.resolvedFileName); + } + else { + errorOnImplicitAnyModule(/*isError*/ noImplicitAny && !!moduleNotFoundError, errorNode, resolvedModule, moduleReference); + } + // Failed imports and untyped modules are both treated in an untyped manner; only difference is whether we give a diagnostic first. + return undefined; + } + if (moduleNotFoundError) { + // For relative paths, see if this was possibly a projectReference redirect + if (ts.pathIsRelative(moduleReference)) { + var sourceFile_1 = ts.getSourceFileOfNode(location); + var redirects = sourceFile_1.redirectedReferences; + if (redirects) { + var normalizedTargetPath = ts.getNormalizedAbsolutePath(moduleReference, ts.getDirectoryPath(sourceFile_1.fileName)); + for (var _i = 0, _a = [".ts" /* Ts */, ".tsx" /* Tsx */]; _i < _a.length; _i++) { + var ext = _a[_i]; + var probePath = normalizedTargetPath + ext; + if (redirects.indexOf(probePath) >= 0) { + error(errorNode, ts.Diagnostics.Output_file_0_has_not_been_built_from_source_file_1, moduleReference, probePath); + return undefined; + } + } + } + } + if (resolutionDiagnostic) { + error(errorNode, resolutionDiagnostic, moduleReference, resolvedModule.resolvedFileName); + } + else { + var tsExtension = ts.tryExtractTSExtension(moduleReference); + if (tsExtension) { + var diag = ts.Diagnostics.An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead; + error(errorNode, diag, tsExtension, ts.removeExtension(moduleReference, tsExtension)); + } + else if (!compilerOptions.resolveJsonModule && + ts.fileExtensionIs(moduleReference, ".json" /* Json */) && + ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs && + ts.hasJsonModuleEmitEnabled(compilerOptions)) { + error(errorNode, ts.Diagnostics.Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension, moduleReference); + } + else { + error(errorNode, moduleNotFoundError, moduleReference); + } + } + } + return undefined; + } + function errorOnImplicitAnyModule(isError, errorNode, _a, moduleReference) { + var packageId = _a.packageId, resolvedFileName = _a.resolvedFileName; + var errorInfo = !ts.isExternalModuleNameRelative(moduleReference) && packageId + ? typesPackageExists(packageId.name) + ? ts.chainDiagnosticMessages( + /*details*/ undefined, ts.Diagnostics.If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1, packageId.name, ts.mangleScopedPackageName(packageId.name)) + : ts.chainDiagnosticMessages( + /*details*/ undefined, ts.Diagnostics.Try_npm_install_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, moduleReference, ts.mangleScopedPackageName(packageId.name)) + : undefined; + errorOrSuggestion(isError, errorNode, ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type, moduleReference, resolvedFileName)); + } + function typesPackageExists(packageName) { + return getPackagesSet().has(ts.getTypesPackageName(packageName)); + } + function resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) { + if (moduleSymbol) { + var exportEquals = resolveSymbol(moduleSymbol.exports.get("export=" /* ExportEquals */), dontResolveAlias); + var exported = getCommonJsExportEquals(exportEquals, moduleSymbol); + return getMergedSymbol(exported) || moduleSymbol; + } + return undefined; + } + function getCommonJsExportEquals(exported, moduleSymbol) { + if (!exported || exported === unknownSymbol || exported === moduleSymbol || moduleSymbol.exports.size === 1 || exported.flags & 2097152 /* Alias */) { + return exported; + } + var merged = cloneSymbol(exported); + if (merged.exports === undefined) { + merged.flags = merged.flags | 512 /* ValueModule */; + merged.exports = ts.createSymbolTable(); + } + moduleSymbol.exports.forEach(function (s, name) { + if (name === "export=" /* ExportEquals */) + return; + merged.exports.set(name, merged.exports.has(name) ? mergeSymbol(merged.exports.get(name), s) : s); + }); + return merged; + } + // An external module with an 'export =' declaration may be referenced as an ES6 module provided the 'export =' + // references a symbol that is at least declared as a module or a variable. The target of the 'export =' may + // combine other declarations with the module or variable (e.g. a class/module, function/module, interface/variable). + function resolveESModuleSymbol(moduleSymbol, referencingLocation, dontResolveAlias) { + var symbol = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias); + if (!dontResolveAlias && symbol) { + if (!(symbol.flags & (1536 /* Module */ | 3 /* Variable */)) && !ts.getDeclarationOfKind(symbol, 279 /* SourceFile */)) { + error(referencingLocation, ts.Diagnostics.Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct, symbolToString(moduleSymbol)); + return symbol; + } + if (compilerOptions.esModuleInterop) { + var referenceParent = referencingLocation.parent; + if ((ts.isImportDeclaration(referenceParent) && ts.getNamespaceDeclarationNode(referenceParent)) || + ts.isImportCall(referenceParent)) { + var type = getTypeOfSymbol(symbol); + var sigs = getSignaturesOfStructuredType(type, 0 /* Call */); + if (!sigs || !sigs.length) { + sigs = getSignaturesOfStructuredType(type, 1 /* Construct */); + } + if (sigs && sigs.length) { + var moduleType = getTypeWithSyntheticDefaultImportType(type, symbol, moduleSymbol); + // Create a new symbol which has the module's type less the call and construct signatures + var result = createSymbol(symbol.flags, symbol.escapedName); + result.declarations = symbol.declarations ? symbol.declarations.slice() : []; + result.parent = symbol.parent; + result.target = symbol; + result.originatingImport = referenceParent; + if (symbol.valueDeclaration) + result.valueDeclaration = symbol.valueDeclaration; + if (symbol.constEnumOnlyModule) + result.constEnumOnlyModule = true; + if (symbol.members) + result.members = ts.cloneMap(symbol.members); + if (symbol.exports) + result.exports = ts.cloneMap(symbol.exports); + var resolvedModuleType = resolveStructuredTypeMembers(moduleType); // Should already be resolved from the signature checks above + result.type = createAnonymousType(result, resolvedModuleType.members, ts.emptyArray, ts.emptyArray, resolvedModuleType.stringIndexInfo, resolvedModuleType.numberIndexInfo); + return result; + } + } + } + } + return symbol; + } + function hasExportAssignmentSymbol(moduleSymbol) { + return moduleSymbol.exports.get("export=" /* ExportEquals */) !== undefined; + } + function getExportsOfModuleAsArray(moduleSymbol) { + return symbolsToArray(getExportsOfModule(moduleSymbol)); + } + function getExportsAndPropertiesOfModule(moduleSymbol) { + var exports = getExportsOfModuleAsArray(moduleSymbol); + var exportEquals = resolveExternalModuleSymbol(moduleSymbol); + if (exportEquals !== moduleSymbol) { + ts.addRange(exports, getPropertiesOfType(getTypeOfSymbol(exportEquals))); + } + return exports; + } + function tryGetMemberInModuleExports(memberName, moduleSymbol) { + var symbolTable = getExportsOfModule(moduleSymbol); + if (symbolTable) { + return symbolTable.get(memberName); + } + } + function tryGetMemberInModuleExportsAndProperties(memberName, moduleSymbol) { + var symbol = tryGetMemberInModuleExports(memberName, moduleSymbol); + if (symbol) { + return symbol; + } + var exportEquals = resolveExternalModuleSymbol(moduleSymbol); + if (exportEquals === moduleSymbol) { + return undefined; + } + var type = getTypeOfSymbol(exportEquals); + return type.flags & 131068 /* Primitive */ ? undefined : getPropertyOfType(type, memberName); + } + function getExportsOfSymbol(symbol) { + return symbol.flags & 32 /* Class */ ? getResolvedMembersOrExportsOfSymbol(symbol, "resolvedExports" /* resolvedExports */) : + symbol.flags & 1536 /* Module */ ? getExportsOfModule(symbol) : + symbol.exports || emptySymbols; + } + function getExportsOfModule(moduleSymbol) { + var links = getSymbolLinks(moduleSymbol); + return links.resolvedExports || (links.resolvedExports = getExportsOfModuleWorker(moduleSymbol)); + } + /** + * Extends one symbol table with another while collecting information on name collisions for error message generation into the `lookupTable` argument + * Not passing `lookupTable` and `exportNode` disables this collection, and just extends the tables + */ + function extendExportSymbols(target, source, lookupTable, exportNode) { + if (!source) + return; + source.forEach(function (sourceSymbol, id) { + if (id === "default" /* Default */) + return; + var targetSymbol = target.get(id); + if (!targetSymbol) { + target.set(id, sourceSymbol); + if (lookupTable && exportNode) { + lookupTable.set(id, { + specifierText: ts.getTextOfNode(exportNode.moduleSpecifier) + }); + } + } + else if (lookupTable && exportNode && targetSymbol && resolveSymbol(targetSymbol) !== resolveSymbol(sourceSymbol)) { + var collisionTracker = lookupTable.get(id); + if (!collisionTracker.exportsWithDuplicate) { + collisionTracker.exportsWithDuplicate = [exportNode]; + } + else { + collisionTracker.exportsWithDuplicate.push(exportNode); + } + } + }); + } + function getExportsOfModuleWorker(moduleSymbol) { + var visitedSymbols = []; + // A module defined by an 'export=' consists of one export that needs to be resolved + moduleSymbol = resolveExternalModuleSymbol(moduleSymbol); + return visit(moduleSymbol) || emptySymbols; + // The ES6 spec permits export * declarations in a module to circularly reference the module itself. For example, + // module 'a' can 'export * from "b"' and 'b' can 'export * from "a"' without error. + function visit(symbol) { + if (!(symbol && symbol.exports && ts.pushIfUnique(visitedSymbols, symbol))) { + return; + } + var symbols = ts.cloneMap(symbol.exports); + // All export * declarations are collected in an __export symbol by the binder + var exportStars = symbol.exports.get("__export" /* ExportStar */); + if (exportStars) { + var nestedSymbols = ts.createSymbolTable(); + var lookupTable_1 = ts.createMap(); + for (var _i = 0, _a = exportStars.declarations; _i < _a.length; _i++) { + var node = _a[_i]; + var resolvedModule = resolveExternalModuleName(node, node.moduleSpecifier); + var exportedSymbols = visit(resolvedModule); + extendExportSymbols(nestedSymbols, exportedSymbols, lookupTable_1, node); + } + lookupTable_1.forEach(function (_a, id) { + var exportsWithDuplicate = _a.exportsWithDuplicate; + // It's not an error if the file with multiple `export *`s with duplicate names exports a member with that name itself + if (id === "export=" || !(exportsWithDuplicate && exportsWithDuplicate.length) || symbols.has(id)) { + return; + } + for (var _i = 0, exportsWithDuplicate_1 = exportsWithDuplicate; _i < exportsWithDuplicate_1.length; _i++) { + var node = exportsWithDuplicate_1[_i]; + diagnostics.add(ts.createDiagnosticForNode(node, ts.Diagnostics.Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambiguity, lookupTable_1.get(id).specifierText, ts.unescapeLeadingUnderscores(id))); + } + }); + extendExportSymbols(symbols, nestedSymbols); + } + return symbols; + } + } + function getMergedSymbol(symbol) { + var merged; + return symbol && symbol.mergeId && (merged = mergedSymbols[symbol.mergeId]) ? merged : symbol; + } + function getSymbolOfNode(node) { + return getMergedSymbol(node.symbol && getLateBoundSymbol(node.symbol)); + } + function getParentOfSymbol(symbol) { + return getMergedSymbol(symbol.parent && getLateBoundSymbol(symbol.parent)); + } + function getAlternativeContainingModules(symbol, enclosingDeclaration) { + var containingFile = ts.getSourceFileOfNode(enclosingDeclaration); + var id = "" + getNodeId(containingFile); + var links = getSymbolLinks(symbol); + var results; + if (links.extendedContainersByFile && (results = links.extendedContainersByFile.get(id))) { + return results; + } + if (containingFile && containingFile.imports) { + // Try to make an import using an import already in the enclosing file, if possible + for (var _i = 0, _a = containingFile.imports; _i < _a.length; _i++) { + var importRef = _a[_i]; + if (ts.nodeIsSynthesized(importRef)) + continue; // Synthetic names can't be resolved by `resolveExternalModuleName` - they'll cause a debug assert if they error + var resolvedModule = resolveExternalModuleName(enclosingDeclaration, importRef, /*ignoreErrors*/ true); + if (!resolvedModule) + continue; + var ref = getAliasForSymbolInContainer(resolvedModule, symbol); + if (!ref) + continue; + results = ts.append(results, resolvedModule); + } + if (ts.length(results)) { + (links.extendedContainersByFile || (links.extendedContainersByFile = ts.createMap())).set(id, results); + return results; + } + } + if (links.extendedContainers) { + return links.extendedContainers; + } + // No results from files already being imported by this file - expand search (expensive, but not location-specific, so cached) + var otherFiles = host.getSourceFiles(); + for (var _b = 0, otherFiles_1 = otherFiles; _b < otherFiles_1.length; _b++) { + var file = otherFiles_1[_b]; + if (!ts.isExternalModule(file)) + continue; + var sym = getSymbolOfNode(file); + var ref = getAliasForSymbolInContainer(sym, symbol); + if (!ref) + continue; + results = ts.append(results, sym); + } + return links.extendedContainers = results || ts.emptyArray; + } + /** + * Attempts to find the symbol corresponding to the container a symbol is in - usually this + * is just its' `.parent`, but for locals, this value is `undefined` + */ + function getContainersOfSymbol(symbol, enclosingDeclaration) { + var container = getParentOfSymbol(symbol); + if (container) { + var additionalContainers = ts.mapDefined(container.declarations, fileSymbolIfFileSymbolExportEqualsContainer); + var reexportContainers = enclosingDeclaration && getAlternativeContainingModules(symbol, enclosingDeclaration); + if (enclosingDeclaration && getAccessibleSymbolChain(container, enclosingDeclaration, 1920 /* Namespace */, /*externalOnly*/ false)) { + return ts.concatenate(ts.concatenate([container], additionalContainers), reexportContainers); // This order expresses a preference for the real container if it is in scope + } + var res = ts.append(additionalContainers, container); + return ts.concatenate(res, reexportContainers); + } + var candidates = ts.mapDefined(symbol.declarations, function (d) { return !ts.isAmbientModule(d) && d.parent && hasNonGlobalAugmentationExternalModuleSymbol(d.parent) ? getSymbolOfNode(d.parent) : undefined; }); + if (!ts.length(candidates)) { + return undefined; + } + return ts.mapDefined(candidates, function (candidate) { return getAliasForSymbolInContainer(candidate, symbol) ? candidate : undefined; }); + function fileSymbolIfFileSymbolExportEqualsContainer(d) { + var fileSymbol = getExternalModuleContainer(d); + var exported = fileSymbol && fileSymbol.exports && fileSymbol.exports.get("export=" /* ExportEquals */); + return resolveSymbol(exported) === resolveSymbol(container) ? fileSymbol : undefined; + } + } + function getAliasForSymbolInContainer(container, symbol) { + if (container === getParentOfSymbol(symbol)) { + // fast path, `symbol` is either already the alias or isn't aliased + return symbol; + } + var exports = getExportsOfSymbol(container); + var quick = exports.get(symbol.escapedName); + if (quick && symbolRefersToTarget(quick)) { + return quick; + } + return ts.forEachEntry(exports, function (exported) { + if (symbolRefersToTarget(exported)) { + return exported; + } + }); + function symbolRefersToTarget(s) { + if (s === symbol || resolveSymbol(s) === symbol || resolveSymbol(s) === resolveSymbol(symbol)) { + return s; + } + } + } + function getExportSymbolOfValueSymbolIfExported(symbol) { + return getMergedSymbol(symbol && (symbol.flags & 1048576 /* ExportValue */) !== 0 ? symbol.exportSymbol : symbol); + } + function symbolIsValue(symbol) { + return !!(symbol.flags & 67220415 /* Value */ || symbol.flags & 2097152 /* Alias */ && resolveAlias(symbol).flags & 67220415 /* Value */); + } + function findConstructorDeclaration(node) { + var members = node.members; + for (var _i = 0, members_2 = members; _i < members_2.length; _i++) { + var member = members_2[_i]; + if (member.kind === 157 /* Constructor */ && ts.nodeIsPresent(member.body)) { + return member; + } + } + } + function createType(flags) { + var result = new Type(checker, flags); + typeCount++; + result.id = typeCount; + return result; + } + function createIntrinsicType(kind, intrinsicName) { + var type = createType(kind); + type.intrinsicName = intrinsicName; + return type; + } + function createBooleanType(trueFalseTypes) { + var type = getUnionType(trueFalseTypes); + type.flags |= 16 /* Boolean */; + type.intrinsicName = "boolean"; + return type; + } + function createObjectType(objectFlags, symbol) { + var type = createType(524288 /* Object */); + type.objectFlags = objectFlags; + type.symbol = symbol; + type.members = undefined; + type.properties = undefined; + type.callSignatures = undefined; + type.constructSignatures = undefined; + type.stringIndexInfo = undefined; + type.numberIndexInfo = undefined; + return type; + } + function createTypeofType() { + return getUnionType(ts.arrayFrom(typeofEQFacts.keys(), getLiteralType)); + } + // A reserved member name starts with two underscores, but the third character cannot be an underscore + // or the @ symbol. A third underscore indicates an escaped form of an identifer that started + // with at least two underscores. The @ character indicates that the name is denoted by a well known ES + // Symbol instance. + function isReservedMemberName(name) { + return name.charCodeAt(0) === 95 /* _ */ && + name.charCodeAt(1) === 95 /* _ */ && + name.charCodeAt(2) !== 95 /* _ */ && + name.charCodeAt(2) !== 64 /* at */; + } + function getNamedMembers(members) { + var result; + members.forEach(function (symbol, id) { + if (!isReservedMemberName(id) && symbolIsValue(symbol)) { + (result || (result = [])).push(symbol); + } + }); + return result || ts.emptyArray; + } + function setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo) { + type.members = members; + type.properties = members === emptySymbols ? ts.emptyArray : getNamedMembers(members); + type.callSignatures = callSignatures; + type.constructSignatures = constructSignatures; + type.stringIndexInfo = stringIndexInfo; + type.numberIndexInfo = numberIndexInfo; + return type; + } + function createAnonymousType(symbol, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo) { + return setStructuredTypeMembers(createObjectType(16 /* Anonymous */, symbol), members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + } + function forEachSymbolTableInScope(enclosingDeclaration, callback) { + var result; + for (var location = enclosingDeclaration; location; location = location.parent) { + // Locals of a source file are not in scope (because they get merged into the global symbol table) + if (location.locals && !isGlobalSourceFile(location)) { + if (result = callback(location.locals)) { + return result; + } + } + switch (location.kind) { + case 279 /* SourceFile */: + if (!ts.isExternalOrCommonJsModule(location)) { + break; + } + // falls through + case 244 /* ModuleDeclaration */: + if (result = callback(getSymbolOfNode(location).exports)) { + return result; + } + break; + } + } + return callback(globals); + } + function getQualifiedLeftMeaning(rightMeaning) { + // If we are looking in value space, the parent meaning is value, other wise it is namespace + return rightMeaning === 67220415 /* Value */ ? 67220415 /* Value */ : 1920 /* Namespace */; + } + function getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, useOnlyExternalAliasing, visitedSymbolTablesMap) { + if (visitedSymbolTablesMap === void 0) { visitedSymbolTablesMap = ts.createMap(); } + if (!(symbol && !isPropertyOrMethodDeclarationSymbol(symbol))) { + return undefined; + } + var id = "" + getSymbolId(symbol); + var visitedSymbolTables = visitedSymbolTablesMap.get(id); + if (!visitedSymbolTables) { + visitedSymbolTablesMap.set(id, visitedSymbolTables = []); + } + return forEachSymbolTableInScope(enclosingDeclaration, getAccessibleSymbolChainFromSymbolTable); + /** + * @param {ignoreQualification} boolean Set when a symbol is being looked for through the exports of another symbol (meaning we have a route to qualify it already) + */ + function getAccessibleSymbolChainFromSymbolTable(symbols, ignoreQualification) { + if (!ts.pushIfUnique(visitedSymbolTables, symbols)) { + return undefined; + } + var result = trySymbolTable(symbols, ignoreQualification); + visitedSymbolTables.pop(); + return result; + } + function canQualifySymbol(symbolFromSymbolTable, meaning) { + // If the symbol is equivalent and doesn't need further qualification, this symbol is accessible + return !needsQualification(symbolFromSymbolTable, enclosingDeclaration, meaning) || + // If symbol needs qualification, make sure that parent is accessible, if it is then this symbol is accessible too + !!getAccessibleSymbolChain(symbolFromSymbolTable.parent, enclosingDeclaration, getQualifiedLeftMeaning(meaning), useOnlyExternalAliasing, visitedSymbolTablesMap); + } + function isAccessible(symbolFromSymbolTable, resolvedAliasSymbol, ignoreQualification) { + return symbol === (resolvedAliasSymbol || symbolFromSymbolTable) && + // if the symbolFromSymbolTable is not external module (it could be if it was determined as ambient external module and would be in globals table) + // and if symbolFromSymbolTable or alias resolution matches the symbol, + // check the symbol can be qualified, it is only then this symbol is accessible + !ts.some(symbolFromSymbolTable.declarations, hasNonGlobalAugmentationExternalModuleSymbol) && + (ignoreQualification || canQualifySymbol(symbolFromSymbolTable, meaning)); + } + function trySymbolTable(symbols, ignoreQualification) { + // If symbol is directly available by its name in the symbol table + if (isAccessible(symbols.get(symbol.escapedName), /*resolvedAliasSymbol*/ undefined, ignoreQualification)) { + return [symbol]; + } + // Check if symbol is any of the alias + return ts.forEachEntry(symbols, function (symbolFromSymbolTable) { + if (symbolFromSymbolTable.flags & 2097152 /* Alias */ + && symbolFromSymbolTable.escapedName !== "export=" /* ExportEquals */ + && symbolFromSymbolTable.escapedName !== "default" /* Default */ + && !(ts.isUMDExportSymbol(symbolFromSymbolTable) && enclosingDeclaration && ts.isExternalModule(ts.getSourceFileOfNode(enclosingDeclaration))) + // If `!useOnlyExternalAliasing`, we can use any type of alias to get the name + && (!useOnlyExternalAliasing || ts.some(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration)) + // While exports are generally considered to be in scope, export-specifier declared symbols are _not_ + // See similar comment in `resolveName` for details + && (ignoreQualification || !ts.getDeclarationOfKind(symbolFromSymbolTable, 257 /* ExportSpecifier */))) { + var resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable); + if (isAccessible(symbolFromSymbolTable, resolvedImportedSymbol, ignoreQualification)) { + return [symbolFromSymbolTable]; + } + // Look in the exported members, if we can find accessibleSymbolChain, symbol is accessible using this chain + // but only if the symbolFromSymbolTable can be qualified + var candidateTable = getExportsOfSymbol(resolvedImportedSymbol); + var accessibleSymbolsFromExports = candidateTable && getAccessibleSymbolChainFromSymbolTable(candidateTable, /*ignoreQualification*/ true); + if (accessibleSymbolsFromExports && canQualifySymbol(symbolFromSymbolTable, getQualifiedLeftMeaning(meaning))) { + return [symbolFromSymbolTable].concat(accessibleSymbolsFromExports); + } + } + if (symbolFromSymbolTable.escapedName === symbol.escapedName && symbolFromSymbolTable.exportSymbol) { + if (isAccessible(getMergedSymbol(symbolFromSymbolTable.exportSymbol), /*aliasSymbol*/ undefined, ignoreQualification)) { + return [symbol]; + } + } + }); + } + } + function needsQualification(symbol, enclosingDeclaration, meaning) { + var qualify = false; + forEachSymbolTableInScope(enclosingDeclaration, function (symbolTable) { + // If symbol of this name is not available in the symbol table we are ok + var symbolFromSymbolTable = getMergedSymbol(symbolTable.get(symbol.escapedName)); + if (!symbolFromSymbolTable) { + // Continue to the next symbol table + return false; + } + // If the symbol with this name is present it should refer to the symbol + if (symbolFromSymbolTable === symbol) { + // No need to qualify + return true; + } + // Qualify if the symbol from symbol table has same meaning as expected + symbolFromSymbolTable = (symbolFromSymbolTable.flags & 2097152 /* Alias */ && !ts.getDeclarationOfKind(symbolFromSymbolTable, 257 /* ExportSpecifier */)) ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable; + if (symbolFromSymbolTable.flags & meaning) { + qualify = true; + return true; + } + // Continue to the next symbol table + return false; + }); + return qualify; + } + function isPropertyOrMethodDeclarationSymbol(symbol) { + if (symbol.declarations && symbol.declarations.length) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + switch (declaration.kind) { + case 154 /* PropertyDeclaration */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + continue; + default: + return false; + } + } + return true; + } + return false; + } + function isTypeSymbolAccessible(typeSymbol, enclosingDeclaration) { + var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67897832 /* Type */, /*shouldComputeAliasesToMakeVisible*/ false); + return access.accessibility === 0 /* Accessible */; + } + function isValueSymbolAccessible(typeSymbol, enclosingDeclaration) { + var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67220415 /* Value */, /*shouldComputeAliasesToMakeVisible*/ false); + return access.accessibility === 0 /* Accessible */; + } + function isAnySymbolAccessible(symbols, enclosingDeclaration, initialSymbol, meaning, shouldComputeAliasesToMakeVisible) { + if (!ts.length(symbols)) + return; + var hadAccessibleChain; + for (var _i = 0, _a = symbols; _i < _a.length; _i++) { + var symbol = _a[_i]; + // Symbol is accessible if it by itself is accessible + var accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, /*useOnlyExternalAliasing*/ false); + if (accessibleSymbolChain) { + hadAccessibleChain = symbol; + var hasAccessibleDeclarations = hasVisibleDeclarations(accessibleSymbolChain[0], shouldComputeAliasesToMakeVisible); + if (hasAccessibleDeclarations) { + return hasAccessibleDeclarations; + } + } + else { + if (ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { + // Any meaning of a module symbol is always accessible via an `import` type + return { + accessibility: 0 /* Accessible */ + }; + } + } + // If we haven't got the accessible symbol, it doesn't mean the symbol is actually inaccessible. + // It could be a qualified symbol and hence verify the path + // e.g.: + // module m { + // export class c { + // } + // } + // const x: typeof m.c + // In the above example when we start with checking if typeof m.c symbol is accessible, + // we are going to see if c can be accessed in scope directly. + // But it can't, hence the accessible is going to be undefined, but that doesn't mean m.c is inaccessible + // It is accessible if the parent m is accessible because then m.c can be accessed through qualification + var containers = getContainersOfSymbol(symbol, enclosingDeclaration); + // If we're trying to reference some object literal in, eg `var a = { x: 1 }`, the symbol for the literal, `__object`, is distinct + // from the symbol of the declaration it is being assigned to. Since we can use the declaration to refer to the literal, however, + // we'd like to make that connection here - potentially causing us to paint the declararation's visibiility, and therefore the literal. + var firstDecl = ts.first(symbol.declarations); + if (!ts.length(containers) && meaning & 67220415 /* Value */ && firstDecl && ts.isObjectLiteralExpression(firstDecl)) { + if (firstDecl.parent && ts.isVariableDeclaration(firstDecl.parent) && firstDecl === firstDecl.parent.initializer) { + containers = [getSymbolOfNode(firstDecl.parent)]; + } + } + var parentResult = isAnySymbolAccessible(containers, enclosingDeclaration, initialSymbol, initialSymbol === symbol ? getQualifiedLeftMeaning(meaning) : meaning, shouldComputeAliasesToMakeVisible); + if (parentResult) { + return parentResult; + } + } + if (hadAccessibleChain) { + return { + accessibility: 1 /* NotAccessible */, + errorSymbolName: symbolToString(initialSymbol, enclosingDeclaration, meaning), + errorModuleName: hadAccessibleChain !== initialSymbol ? symbolToString(hadAccessibleChain, enclosingDeclaration, 1920 /* Namespace */) : undefined, + }; + } + } + /** + * Check if the given symbol in given enclosing declaration is accessible and mark all associated alias to be visible if requested + * + * @param symbol a Symbol to check if accessible + * @param enclosingDeclaration a Node containing reference to the symbol + * @param meaning a SymbolFlags to check if such meaning of the symbol is accessible + * @param shouldComputeAliasToMakeVisible a boolean value to indicate whether to return aliases to be mark visible in case the symbol is accessible + */ + function isSymbolAccessible(symbol, enclosingDeclaration, meaning, shouldComputeAliasesToMakeVisible) { + if (symbol && enclosingDeclaration) { + var result = isAnySymbolAccessible([symbol], enclosingDeclaration, symbol, meaning, shouldComputeAliasesToMakeVisible); + if (result) { + return result; + } + // This could be a symbol that is not exported in the external module + // or it could be a symbol from different external module that is not aliased and hence cannot be named + var symbolExternalModule = ts.forEach(symbol.declarations, getExternalModuleContainer); + if (symbolExternalModule) { + var enclosingExternalModule = getExternalModuleContainer(enclosingDeclaration); + if (symbolExternalModule !== enclosingExternalModule) { + // name from different external module that is not visible + return { + accessibility: 2 /* CannotBeNamed */, + errorSymbolName: symbolToString(symbol, enclosingDeclaration, meaning), + errorModuleName: symbolToString(symbolExternalModule) + }; + } + } + // Just a local name that is not accessible + return { + accessibility: 1 /* NotAccessible */, + errorSymbolName: symbolToString(symbol, enclosingDeclaration, meaning), + }; + } + return { accessibility: 0 /* Accessible */ }; + } + function getExternalModuleContainer(declaration) { + var node = ts.findAncestor(declaration, hasExternalModuleSymbol); + return node && getSymbolOfNode(node); + } + function hasExternalModuleSymbol(declaration) { + return ts.isAmbientModule(declaration) || (declaration.kind === 279 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration)); + } + function hasNonGlobalAugmentationExternalModuleSymbol(declaration) { + return ts.isModuleWithStringLiteralName(declaration) || (declaration.kind === 279 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration)); + } + function hasVisibleDeclarations(symbol, shouldComputeAliasToMakeVisible) { + var aliasesToMakeVisible; + if (!ts.every(symbol.declarations, getIsDeclarationVisible)) { + return undefined; + } + return { accessibility: 0 /* Accessible */, aliasesToMakeVisible: aliasesToMakeVisible }; + function getIsDeclarationVisible(declaration) { + if (!isDeclarationVisible(declaration)) { + // Mark the unexported alias as visible if its parent is visible + // because these kind of aliases can be used to name types in declaration file + var anyImportSyntax = getAnyImportSyntax(declaration); + if (anyImportSyntax && + !ts.hasModifier(anyImportSyntax, 1 /* Export */) && // import clause without export + isDeclarationVisible(anyImportSyntax.parent)) { + return addVisibleAlias(declaration, anyImportSyntax); + } + else if (ts.isVariableDeclaration(declaration) && ts.isVariableStatement(declaration.parent.parent) && + !ts.hasModifier(declaration.parent.parent, 1 /* Export */) && // unexported variable statement + isDeclarationVisible(declaration.parent.parent.parent)) { + return addVisibleAlias(declaration, declaration.parent.parent); + } + else if (ts.isLateVisibilityPaintedStatement(declaration) // unexported top-level statement + && !ts.hasModifier(declaration, 1 /* Export */) + && isDeclarationVisible(declaration.parent)) { + return addVisibleAlias(declaration, declaration); + } + // Declaration is not visible + return false; + } + return true; + } + function addVisibleAlias(declaration, aliasingStatement) { + // In function "buildTypeDisplay" where we decide whether to write type-alias or serialize types, + // we want to just check if type- alias is accessible or not but we don't care about emitting those alias at that time + // since we will do the emitting later in trackSymbol. + if (shouldComputeAliasToMakeVisible) { + getNodeLinks(declaration).isVisible = true; + aliasesToMakeVisible = ts.appendIfUnique(aliasesToMakeVisible, aliasingStatement); + } + return true; + } + } + function isEntityNameVisible(entityName, enclosingDeclaration) { + // get symbol of the first identifier of the entityName + var meaning; + if (entityName.parent.kind === 167 /* TypeQuery */ || + ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent) || + entityName.parent.kind === 149 /* ComputedPropertyName */) { + // Typeof value + meaning = 67220415 /* Value */ | 1048576 /* ExportValue */; + } + else if (entityName.kind === 148 /* QualifiedName */ || entityName.kind === 189 /* PropertyAccessExpression */ || + entityName.parent.kind === 248 /* ImportEqualsDeclaration */) { + // Left identifier from type reference or TypeAlias + // Entity name of the import declaration + meaning = 1920 /* Namespace */; + } + else { + // Type Reference or TypeAlias entity = Identifier + meaning = 67897832 /* Type */; + } + var firstIdentifier = getFirstIdentifier(entityName); + var symbol = resolveName(enclosingDeclaration, firstIdentifier.escapedText, meaning, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); + // Verify if the symbol is accessible + return (symbol && hasVisibleDeclarations(symbol, /*shouldComputeAliasToMakeVisible*/ true)) || { + accessibility: 1 /* NotAccessible */, + errorSymbolName: ts.getTextOfNode(firstIdentifier), + errorNode: firstIdentifier + }; + } + function symbolToString(symbol, enclosingDeclaration, meaning, flags, writer) { + if (flags === void 0) { flags = 4 /* AllowAnyNodeKind */; } + var nodeFlags = 70221824 /* IgnoreErrors */; + if (flags & 2 /* UseOnlyExternalAliasing */) { + nodeFlags |= 128 /* UseOnlyExternalAliasing */; + } + if (flags & 1 /* WriteTypeParametersOrArguments */) { + nodeFlags |= 512 /* WriteTypeParametersInQualifiedName */; + } + if (flags & 8 /* UseAliasDefinedOutsideCurrentScope */) { + nodeFlags |= 16384 /* UseAliasDefinedOutsideCurrentScope */; + } + if (flags & 16 /* DoNotIncludeSymbolChain */) { + nodeFlags |= 134217728 /* DoNotIncludeSymbolChain */; + } + var builder = flags & 4 /* AllowAnyNodeKind */ ? nodeBuilder.symbolToExpression : nodeBuilder.symbolToEntityName; + return writer ? symbolToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(symbolToStringWorker); + function symbolToStringWorker(writer) { + var entity = builder(symbol, meaning, enclosingDeclaration, nodeFlags); // TODO: GH#18217 + var printer = ts.createPrinter({ removeComments: true }); + var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); + printer.writeNode(4 /* Unspecified */, entity, /*sourceFile*/ sourceFile, writer); + return writer; + } + } + function signatureToString(signature, enclosingDeclaration, flags, kind, writer) { + if (flags === void 0) { flags = 0 /* None */; } + return writer ? signatureToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(signatureToStringWorker); + function signatureToStringWorker(writer) { + var sigOutput; + if (flags & 262144 /* WriteArrowStyleSignature */) { + sigOutput = kind === 1 /* Construct */ ? 166 /* ConstructorType */ : 165 /* FunctionType */; + } + else { + sigOutput = kind === 1 /* Construct */ ? 161 /* ConstructSignature */ : 160 /* CallSignature */; + } + var sig = nodeBuilder.signatureToSignatureDeclaration(signature, sigOutput, enclosingDeclaration, toNodeBuilderFlags(flags) | 70221824 /* IgnoreErrors */ | 512 /* WriteTypeParametersInQualifiedName */); + var printer = ts.createPrinter({ removeComments: true, omitTrailingSemicolon: true }); + var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); + printer.writeNode(4 /* Unspecified */, sig, /*sourceFile*/ sourceFile, ts.getTrailingSemicolonOmittingWriter(writer)); // TODO: GH#18217 + return writer; + } + } + function typeToString(type, enclosingDeclaration, flags, writer) { + if (flags === void 0) { flags = 1048576 /* AllowUniqueESSymbolType */ | 16384 /* UseAliasDefinedOutsideCurrentScope */; } + if (writer === void 0) { writer = ts.createTextWriter(""); } + var noTruncation = compilerOptions.noErrorTruncation || flags & 1 /* NoTruncation */; + var typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, toNodeBuilderFlags(flags) | 70221824 /* IgnoreErrors */ | (noTruncation ? 1 /* NoTruncation */ : 0), writer); + if (typeNode === undefined) + return ts.Debug.fail("should always get typenode"); + var options = { removeComments: true }; + var printer = ts.createPrinter(options); + var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); + printer.writeNode(4 /* Unspecified */, typeNode, /*sourceFile*/ sourceFile, writer); + var result = writer.getText(); + var maxLength = noTruncation ? undefined : ts.defaultMaximumTruncationLength * 2; + if (maxLength && result && result.length >= maxLength) { + return result.substr(0, maxLength - "...".length) + "..."; + } + return result; + } + function toNodeBuilderFlags(flags) { + if (flags === void 0) { flags = 0 /* None */; } + return flags & 9469291 /* NodeBuilderFlagsMask */; + } + function createNodeBuilder() { + return { + typeToTypeNode: function (type, enclosingDeclaration, flags, tracker) { + return withContext(enclosingDeclaration, flags, tracker, function (context) { return typeToTypeNodeHelper(type, context); }); + }, + indexInfoToIndexSignatureDeclaration: function (indexInfo, kind, enclosingDeclaration, flags, tracker) { + return withContext(enclosingDeclaration, flags, tracker, function (context) { return indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind, context); }); + }, + signatureToSignatureDeclaration: function (signature, kind, enclosingDeclaration, flags, tracker) { + return withContext(enclosingDeclaration, flags, tracker, function (context) { return signatureToSignatureDeclarationHelper(signature, kind, context); }); + }, + symbolToEntityName: function (symbol, meaning, enclosingDeclaration, flags, tracker) { + return withContext(enclosingDeclaration, flags, tracker, function (context) { return symbolToName(symbol, context, meaning, /*expectsIdentifier*/ false); }); + }, + symbolToExpression: function (symbol, meaning, enclosingDeclaration, flags, tracker) { + return withContext(enclosingDeclaration, flags, tracker, function (context) { return symbolToExpression(symbol, context, meaning); }); + }, + symbolToTypeParameterDeclarations: function (symbol, enclosingDeclaration, flags, tracker) { + return withContext(enclosingDeclaration, flags, tracker, function (context) { return typeParametersToTypeParameterDeclarations(symbol, context); }); + }, + symbolToParameterDeclaration: function (symbol, enclosingDeclaration, flags, tracker) { + return withContext(enclosingDeclaration, flags, tracker, function (context) { return symbolToParameterDeclaration(symbol, context); }); + }, + typeParameterToDeclaration: function (parameter, enclosingDeclaration, flags, tracker) { + return withContext(enclosingDeclaration, flags, tracker, function (context) { return typeParameterToDeclaration(parameter, context); }); + }, + }; + function withContext(enclosingDeclaration, flags, tracker, cb) { + ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8 /* Synthesized */) === 0); + var context = { + enclosingDeclaration: enclosingDeclaration, + flags: flags || 0 /* None */, + // If no full tracker is provided, fake up a dummy one with a basic limited-functionality moduleResolverHost + tracker: tracker && tracker.trackSymbol ? tracker : { trackSymbol: ts.noop, moduleResolverHost: flags & 134217728 /* DoNotIncludeSymbolChain */ ? { + getCommonSourceDirectory: host.getCommonSourceDirectory ? function () { return host.getCommonSourceDirectory(); } : function () { return ""; }, + getSourceFiles: function () { return host.getSourceFiles(); }, + getCurrentDirectory: host.getCurrentDirectory && (function () { return host.getCurrentDirectory(); }) + } : undefined }, + encounteredError: false, + visitedTypes: undefined, + symbolDepth: undefined, + inferTypeParameters: undefined, + approximateLength: 0 + }; + var resultingNode = cb(context); + return context.encounteredError ? undefined : resultingNode; + } + function checkTruncationLength(context) { + if (context.truncating) + return context.truncating; + return context.truncating = !(context.flags & 1 /* NoTruncation */) && context.approximateLength > ts.defaultMaximumTruncationLength; + } + function typeToTypeNodeHelper(type, context) { + if (cancellationToken && cancellationToken.throwIfCancellationRequested) { + cancellationToken.throwIfCancellationRequested(); + } + var inTypeAlias = context.flags & 8388608 /* InTypeAlias */; + context.flags &= ~8388608 /* InTypeAlias */; + if (!type) { + context.encounteredError = true; + return undefined; // TODO: GH#18217 + } + if (type.flags & 1 /* Any */) { + context.approximateLength += 3; + return ts.createKeywordTypeNode(120 /* AnyKeyword */); + } + if (type.flags & 2 /* Unknown */) { + return ts.createKeywordTypeNode(143 /* UnknownKeyword */); + } + if (type.flags & 4 /* String */) { + context.approximateLength += 6; + return ts.createKeywordTypeNode(138 /* StringKeyword */); + } + if (type.flags & 8 /* Number */) { + context.approximateLength += 6; + return ts.createKeywordTypeNode(135 /* NumberKeyword */); + } + if (type.flags & 64 /* BigInt */) { + context.approximateLength += 6; + return ts.createKeywordTypeNode(146 /* BigIntKeyword */); + } + if (type.flags & 16 /* Boolean */) { + context.approximateLength += 7; + return ts.createKeywordTypeNode(123 /* BooleanKeyword */); + } + if (type.flags & 1024 /* EnumLiteral */ && !(type.flags & 1048576 /* Union */)) { + var parentSymbol = getParentOfSymbol(type.symbol); + var parentName = symbolToTypeNode(parentSymbol, context, 67897832 /* Type */); + var enumLiteralName = getDeclaredTypeOfSymbol(parentSymbol) === type + ? parentName + : appendReferenceToType(parentName, ts.createTypeReferenceNode(ts.symbolName(type.symbol), /*typeArguments*/ undefined)); + return enumLiteralName; + } + if (type.flags & 1056 /* EnumLike */) { + return symbolToTypeNode(type.symbol, context, 67897832 /* Type */); + } + if (type.flags & 128 /* StringLiteral */) { + context.approximateLength += (type.value.length + 2); + return ts.createLiteralTypeNode(ts.setEmitFlags(ts.createLiteral(type.value), 16777216 /* NoAsciiEscaping */)); + } + if (type.flags & 256 /* NumberLiteral */) { + context.approximateLength += (("" + type.value).length); + return ts.createLiteralTypeNode((ts.createLiteral(type.value))); + } + if (type.flags & 2048 /* BigIntLiteral */) { + context.approximateLength += (ts.pseudoBigIntToString(type.value).length) + 1; + return ts.createLiteralTypeNode((ts.createLiteral(type.value))); + } + if (type.flags & 512 /* BooleanLiteral */) { + context.approximateLength += type.intrinsicName.length; + return type.intrinsicName === "true" ? ts.createTrue() : ts.createFalse(); + } + if (type.flags & 8192 /* UniqueESSymbol */) { + if (!(context.flags & 1048576 /* AllowUniqueESSymbolType */)) { + if (isValueSymbolAccessible(type.symbol, context.enclosingDeclaration)) { + context.approximateLength += 6; + return symbolToTypeNode(type.symbol, context, 67220415 /* Value */); + } + if (context.tracker.reportInaccessibleUniqueSymbolError) { + context.tracker.reportInaccessibleUniqueSymbolError(); + } + } + context.approximateLength += 13; + return ts.createTypeOperatorNode(142 /* UniqueKeyword */, ts.createKeywordTypeNode(139 /* SymbolKeyword */)); + } + if (type.flags & 16384 /* Void */) { + context.approximateLength += 4; + return ts.createKeywordTypeNode(106 /* VoidKeyword */); + } + if (type.flags & 32768 /* Undefined */) { + context.approximateLength += 9; + return ts.createKeywordTypeNode(141 /* UndefinedKeyword */); + } + if (type.flags & 65536 /* Null */) { + context.approximateLength += 4; + return ts.createKeywordTypeNode(96 /* NullKeyword */); + } + if (type.flags & 131072 /* Never */) { + context.approximateLength += 5; + return ts.createKeywordTypeNode(132 /* NeverKeyword */); + } + if (type.flags & 4096 /* ESSymbol */) { + context.approximateLength += 6; + return ts.createKeywordTypeNode(139 /* SymbolKeyword */); + } + if (type.flags & 67108864 /* NonPrimitive */) { + context.approximateLength += 6; + return ts.createKeywordTypeNode(136 /* ObjectKeyword */); + } + if (type.flags & 262144 /* TypeParameter */ && type.isThisType) { + if (context.flags & 4194304 /* InObjectTypeLiteral */) { + if (!context.encounteredError && !(context.flags & 32768 /* AllowThisInObjectLiteral */)) { + context.encounteredError = true; + } + if (context.tracker.reportInaccessibleThisError) { + context.tracker.reportInaccessibleThisError(); + } + } + context.approximateLength += 4; + return ts.createThis(); + } + var objectFlags = ts.getObjectFlags(type); + if (objectFlags & 4 /* Reference */) { + ts.Debug.assert(!!(type.flags & 524288 /* Object */)); + return typeReferenceToTypeNode(type); + } + if (type.flags & 262144 /* TypeParameter */ || objectFlags & 3 /* ClassOrInterface */) { + if (type.flags & 262144 /* TypeParameter */ && ts.contains(context.inferTypeParameters, type)) { + context.approximateLength += (ts.symbolName(type.symbol).length + 6); + return ts.createInferTypeNode(typeParameterToDeclarationWithConstraint(type, context, /*constraintNode*/ undefined)); + } + if (context.flags & 4 /* GenerateNamesForShadowedTypeParams */ && + type.flags & 262144 /* TypeParameter */ && + ts.length(type.symbol.declarations) && + ts.isTypeParameterDeclaration(type.symbol.declarations[0]) && + typeParameterShadowsNameInScope(type, context) && + !isTypeSymbolAccessible(type.symbol, context.enclosingDeclaration)) { + var name = type.symbol.declarations[0].name; + context.approximateLength += ts.idText(name).length; + return ts.createTypeReferenceNode(ts.getGeneratedNameForNode(name, 16 /* Optimistic */ | 8 /* ReservedInNestedScopes */), /*typeArguments*/ undefined); + } + // Ignore constraint/default when creating a usage (as opposed to declaration) of a type parameter. + return type.symbol + ? symbolToTypeNode(type.symbol, context, 67897832 /* Type */) + : ts.createTypeReferenceNode(ts.createIdentifier("?"), /*typeArguments*/ undefined); + } + if (!inTypeAlias && type.aliasSymbol && (context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */ || isTypeSymbolAccessible(type.aliasSymbol, context.enclosingDeclaration))) { + var typeArgumentNodes = mapToTypeNodes(type.aliasTypeArguments, context); + if (isReservedMemberName(type.aliasSymbol.escapedName) && !(type.aliasSymbol.flags & 32 /* Class */)) + return ts.createTypeReferenceNode(ts.createIdentifier(""), typeArgumentNodes); + return symbolToTypeNode(type.aliasSymbol, context, 67897832 /* Type */, typeArgumentNodes); + } + if (type.flags & (1048576 /* Union */ | 2097152 /* Intersection */)) { + var types = type.flags & 1048576 /* Union */ ? formatUnionTypes(type.types) : type.types; + if (ts.length(types) === 1) { + return typeToTypeNodeHelper(types[0], context); + } + var typeNodes = mapToTypeNodes(types, context, /*isBareList*/ true); + if (typeNodes && typeNodes.length > 0) { + var unionOrIntersectionTypeNode = ts.createUnionOrIntersectionTypeNode(type.flags & 1048576 /* Union */ ? 173 /* UnionType */ : 174 /* IntersectionType */, typeNodes); + return unionOrIntersectionTypeNode; + } + else { + if (!context.encounteredError && !(context.flags & 262144 /* AllowEmptyUnionOrIntersection */)) { + context.encounteredError = true; + } + return undefined; // TODO: GH#18217 + } + } + if (objectFlags & (16 /* Anonymous */ | 32 /* Mapped */)) { + ts.Debug.assert(!!(type.flags & 524288 /* Object */)); + // The type is an object literal type. + return createAnonymousTypeNode(type); + } + if (type.flags & 4194304 /* Index */) { + var indexedType = type.type; + context.approximateLength += 6; + var indexTypeNode = typeToTypeNodeHelper(indexedType, context); + return ts.createTypeOperatorNode(indexTypeNode); + } + if (type.flags & 8388608 /* IndexedAccess */) { + var objectTypeNode = typeToTypeNodeHelper(type.objectType, context); + var indexTypeNode = typeToTypeNodeHelper(type.indexType, context); + context.approximateLength += 2; + return ts.createIndexedAccessTypeNode(objectTypeNode, indexTypeNode); + } + if (type.flags & 16777216 /* Conditional */) { + var checkTypeNode = typeToTypeNodeHelper(type.checkType, context); + var saveInferTypeParameters = context.inferTypeParameters; + context.inferTypeParameters = type.root.inferTypeParameters; + var extendsTypeNode = typeToTypeNodeHelper(type.extendsType, context); + context.inferTypeParameters = saveInferTypeParameters; + var trueTypeNode = typeToTypeNodeHelper(getTrueTypeFromConditionalType(type), context); + var falseTypeNode = typeToTypeNodeHelper(getFalseTypeFromConditionalType(type), context); + context.approximateLength += 15; + return ts.createConditionalTypeNode(checkTypeNode, extendsTypeNode, trueTypeNode, falseTypeNode); + } + if (type.flags & 33554432 /* Substitution */) { + return typeToTypeNodeHelper(type.typeVariable, context); + } + return ts.Debug.fail("Should be unreachable."); + function createMappedTypeNodeFromType(type) { + ts.Debug.assert(!!(type.flags & 524288 /* Object */)); + var readonlyToken = type.declaration.readonlyToken ? ts.createToken(type.declaration.readonlyToken.kind) : undefined; + var questionToken = type.declaration.questionToken ? ts.createToken(type.declaration.questionToken.kind) : undefined; + var appropriateConstraintTypeNode; + if (isMappedTypeWithKeyofConstraintDeclaration(type)) { + // We have a { [P in keyof T]: X } + // We do this to ensure we retain the toplevel keyof-ness of the type which may be lost due to keyof distribution during `getConstraintTypeFromMappedType` + appropriateConstraintTypeNode = ts.createTypeOperatorNode(typeToTypeNodeHelper(getModifiersTypeFromMappedType(type), context)); + } + else { + appropriateConstraintTypeNode = typeToTypeNodeHelper(getConstraintTypeFromMappedType(type), context); + } + var typeParameterNode = typeParameterToDeclarationWithConstraint(getTypeParameterFromMappedType(type), context, appropriateConstraintTypeNode); + var templateTypeNode = typeToTypeNodeHelper(getTemplateTypeFromMappedType(type), context); + var mappedTypeNode = ts.createMappedTypeNode(readonlyToken, typeParameterNode, questionToken, templateTypeNode); + context.approximateLength += 10; + return ts.setEmitFlags(mappedTypeNode, 1 /* SingleLine */); + } + function createAnonymousTypeNode(type) { + var typeId = "" + type.id; + var symbol = type.symbol; + var id; + if (symbol) { + var isConstructorObject = ts.getObjectFlags(type) & 16 /* Anonymous */ && type.symbol && type.symbol.flags & 32 /* Class */; + id = (isConstructorObject ? "+" : "") + getSymbolId(symbol); + if (isJSConstructor(symbol.valueDeclaration)) { + // Instance and static types share the same symbol; only add 'typeof' for the static side. + var isInstanceType = type === getInferredClassType(symbol) ? 67897832 /* Type */ : 67220415 /* Value */; + return symbolToTypeNode(symbol, context, isInstanceType); + } + // Always use 'typeof T' for type of class, enum, and module objects + else if (symbol.flags & 32 /* Class */ && !getBaseTypeVariableOfClass(symbol) && !(symbol.valueDeclaration.kind === 209 /* ClassExpression */ && context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */) || + symbol.flags & (384 /* Enum */ | 512 /* ValueModule */) || + shouldWriteTypeOfFunctionSymbol()) { + return symbolToTypeNode(symbol, context, 67220415 /* Value */); + } + else if (context.visitedTypes && context.visitedTypes.has(typeId)) { + // If type is an anonymous type literal in a type alias declaration, use type alias name + var typeAlias = getTypeAliasForTypeLiteral(type); + if (typeAlias) { + // The specified symbol flags need to be reinterpreted as type flags + return symbolToTypeNode(typeAlias, context, 67897832 /* Type */); + } + else { + return createElidedInformationPlaceholder(context); + } + } + else { + // Since instantiations of the same anonymous type have the same symbol, tracking symbols instead + // of types allows us to catch circular references to instantiations of the same anonymous type + if (!context.visitedTypes) { + context.visitedTypes = ts.createMap(); + } + if (!context.symbolDepth) { + context.symbolDepth = ts.createMap(); + } + var depth = context.symbolDepth.get(id) || 0; + if (depth > 10) { + return createElidedInformationPlaceholder(context); + } + context.symbolDepth.set(id, depth + 1); + context.visitedTypes.set(typeId, true); + var result = createTypeNodeFromObjectType(type); + context.visitedTypes.delete(typeId); + context.symbolDepth.set(id, depth); + return result; + } + } + else { + // Anonymous types without a symbol are never circular. + return createTypeNodeFromObjectType(type); + } + function shouldWriteTypeOfFunctionSymbol() { + var isStaticMethodSymbol = !!(symbol.flags & 8192 /* Method */) && // typeof static method + ts.some(symbol.declarations, function (declaration) { return ts.hasModifier(declaration, 32 /* Static */); }); + var isNonLocalFunctionSymbol = !!(symbol.flags & 16 /* Function */) && + (symbol.parent || // is exported function symbol + ts.forEach(symbol.declarations, function (declaration) { + return declaration.parent.kind === 279 /* SourceFile */ || declaration.parent.kind === 245 /* ModuleBlock */; + })); + if (isStaticMethodSymbol || isNonLocalFunctionSymbol) { + // typeof is allowed only for static/non local functions + return (!!(context.flags & 4096 /* UseTypeOfFunction */) || (context.visitedTypes && context.visitedTypes.has(typeId))) && // it is type of the symbol uses itself recursively + (!(context.flags & 8 /* UseStructuralFallback */) || isValueSymbolAccessible(symbol, context.enclosingDeclaration)); // TODO: GH#18217 // And the build is going to succeed without visibility error or there is no structural fallback allowed + } + } + } + function createTypeNodeFromObjectType(type) { + if (isGenericMappedType(type)) { + return createMappedTypeNodeFromType(type); + } + var resolved = resolveStructuredTypeMembers(type); + if (!resolved.properties.length && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { + if (!resolved.callSignatures.length && !resolved.constructSignatures.length) { + context.approximateLength += 2; + return ts.setEmitFlags(ts.createTypeLiteralNode(/*members*/ undefined), 1 /* SingleLine */); + } + if (resolved.callSignatures.length === 1 && !resolved.constructSignatures.length) { + var signature = resolved.callSignatures[0]; + var signatureNode = signatureToSignatureDeclarationHelper(signature, 165 /* FunctionType */, context); + return signatureNode; + } + if (resolved.constructSignatures.length === 1 && !resolved.callSignatures.length) { + var signature = resolved.constructSignatures[0]; + var signatureNode = signatureToSignatureDeclarationHelper(signature, 166 /* ConstructorType */, context); + return signatureNode; + } + } + var savedFlags = context.flags; + context.flags |= 4194304 /* InObjectTypeLiteral */; + var members = createTypeNodesFromResolvedType(resolved); + context.flags = savedFlags; + var typeLiteralNode = ts.createTypeLiteralNode(members); + context.approximateLength += 2; + return ts.setEmitFlags(typeLiteralNode, (context.flags & 1024 /* MultilineObjectLiterals */) ? 0 : 1 /* SingleLine */); + } + function typeReferenceToTypeNode(type) { + var typeArguments = type.typeArguments || ts.emptyArray; + if (type.target === globalArrayType) { + if (context.flags & 2 /* WriteArrayAsGenericType */) { + var typeArgumentNode = typeToTypeNodeHelper(typeArguments[0], context); + return ts.createTypeReferenceNode("Array", [typeArgumentNode]); + } + var elementType = typeToTypeNodeHelper(typeArguments[0], context); + return ts.createArrayTypeNode(elementType); + } + else if (type.target.objectFlags & 8 /* Tuple */) { + if (typeArguments.length > 0) { + var arity = getTypeReferenceArity(type); + var tupleConstituentNodes = mapToTypeNodes(typeArguments.slice(0, arity), context); + var hasRestElement = type.target.hasRestElement; + if (tupleConstituentNodes) { + for (var i = type.target.minLength; i < Math.min(arity, tupleConstituentNodes.length); i++) { + tupleConstituentNodes[i] = hasRestElement && i === arity - 1 ? + ts.createRestTypeNode(ts.createArrayTypeNode(tupleConstituentNodes[i])) : + ts.createOptionalTypeNode(tupleConstituentNodes[i]); + } + return ts.createTupleTypeNode(tupleConstituentNodes); + } + } + if (context.encounteredError || (context.flags & 524288 /* AllowEmptyTuple */)) { + return ts.createTupleTypeNode([]); + } + context.encounteredError = true; + return undefined; // TODO: GH#18217 + } + else if (context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */ && + type.symbol.valueDeclaration && + ts.isClassLike(type.symbol.valueDeclaration) && + !isValueSymbolAccessible(type.symbol, context.enclosingDeclaration)) { + return createAnonymousTypeNode(type); + } + else { + var outerTypeParameters = type.target.outerTypeParameters; + var i = 0; + var resultType = void 0; + if (outerTypeParameters) { + var length_1 = outerTypeParameters.length; + while (i < length_1) { + // Find group of type arguments for type parameters with the same declaring container. + var start = i; + var parent = getParentSymbolOfTypeParameter(outerTypeParameters[i]); + do { + i++; + } while (i < length_1 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent); + // When type parameters are their own type arguments for the whole group (i.e. we have + // the default outer type arguments), we don't show the group. + if (!ts.rangeEquals(outerTypeParameters, typeArguments, start, i)) { + var typeArgumentSlice = mapToTypeNodes(typeArguments.slice(start, i), context); + var flags_2 = context.flags; + context.flags |= 16 /* ForbidIndexedAccessSymbolReferences */; + var ref = symbolToTypeNode(parent, context, 67897832 /* Type */, typeArgumentSlice); + context.flags = flags_2; + resultType = !resultType ? ref : appendReferenceToType(resultType, ref); + } + } + } + var typeArgumentNodes = void 0; + if (typeArguments.length > 0) { + var typeParameterCount = (type.target.typeParameters || ts.emptyArray).length; + typeArgumentNodes = mapToTypeNodes(typeArguments.slice(i, typeParameterCount), context); + } + var flags = context.flags; + context.flags |= 16 /* ForbidIndexedAccessSymbolReferences */; + var finalRef = symbolToTypeNode(type.symbol, context, 67897832 /* Type */, typeArgumentNodes); + context.flags = flags; + return !resultType ? finalRef : appendReferenceToType(resultType, finalRef); + } + } + function appendReferenceToType(root, ref) { + if (ts.isImportTypeNode(root)) { + // first shift type arguments + var innerParams = root.typeArguments; + if (root.qualifier) { + (ts.isIdentifier(root.qualifier) ? root.qualifier : root.qualifier.right).typeArguments = innerParams; + } + root.typeArguments = ref.typeArguments; + // then move qualifiers + var ids = getAccessStack(ref); + for (var _i = 0, ids_1 = ids; _i < ids_1.length; _i++) { + var id = ids_1[_i]; + root.qualifier = root.qualifier ? ts.createQualifiedName(root.qualifier, id) : id; + } + return root; + } + else { + // first shift type arguments + var innerParams = root.typeArguments; + (ts.isIdentifier(root.typeName) ? root.typeName : root.typeName.right).typeArguments = innerParams; + root.typeArguments = ref.typeArguments; + // then move qualifiers + var ids = getAccessStack(ref); + for (var _a = 0, ids_2 = ids; _a < ids_2.length; _a++) { + var id = ids_2[_a]; + root.typeName = ts.createQualifiedName(root.typeName, id); + } + return root; + } + } + function getAccessStack(ref) { + var state = ref.typeName; + var ids = []; + while (!ts.isIdentifier(state)) { + ids.unshift(state.right); + state = state.left; + } + ids.unshift(state); + return ids; + } + function createTypeNodesFromResolvedType(resolvedType) { + if (checkTruncationLength(context)) { + return [ts.createPropertySignature(/*modifiers*/ undefined, "...", /*questionToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined)]; + } + var typeElements = []; + for (var _i = 0, _a = resolvedType.callSignatures; _i < _a.length; _i++) { + var signature = _a[_i]; + typeElements.push(signatureToSignatureDeclarationHelper(signature, 160 /* CallSignature */, context)); + } + for (var _b = 0, _c = resolvedType.constructSignatures; _b < _c.length; _b++) { + var signature = _c[_b]; + typeElements.push(signatureToSignatureDeclarationHelper(signature, 161 /* ConstructSignature */, context)); + } + if (resolvedType.stringIndexInfo) { + var indexSignature = void 0; + if (resolvedType.objectFlags & 2048 /* ReverseMapped */) { + indexSignature = indexInfoToIndexSignatureDeclarationHelper(createIndexInfo(anyType, resolvedType.stringIndexInfo.isReadonly, resolvedType.stringIndexInfo.declaration), 0 /* String */, context); + indexSignature.type = createElidedInformationPlaceholder(context); + } + else { + indexSignature = indexInfoToIndexSignatureDeclarationHelper(resolvedType.stringIndexInfo, 0 /* String */, context); + } + typeElements.push(indexSignature); + } + if (resolvedType.numberIndexInfo) { + typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.numberIndexInfo, 1 /* Number */, context)); + } + var properties = resolvedType.properties; + if (!properties) { + return typeElements; + } + var i = 0; + for (var _d = 0, properties_1 = properties; _d < properties_1.length; _d++) { + var propertySymbol = properties_1[_d]; + i++; + if (context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */) { + if (propertySymbol.flags & 4194304 /* Prototype */) { + continue; + } + if (ts.getDeclarationModifierFlagsFromSymbol(propertySymbol) & (8 /* Private */ | 16 /* Protected */) && context.tracker.reportPrivateInBaseOfClassExpression) { + context.tracker.reportPrivateInBaseOfClassExpression(ts.unescapeLeadingUnderscores(propertySymbol.escapedName)); + } + } + if (checkTruncationLength(context) && (i + 2 < properties.length - 1)) { + typeElements.push(ts.createPropertySignature(/*modifiers*/ undefined, "... " + (properties.length - i) + " more ...", /*questionToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined)); + addPropertyToElementList(properties[properties.length - 1], context, typeElements); + break; + } + addPropertyToElementList(propertySymbol, context, typeElements); + } + return typeElements.length ? typeElements : undefined; + } + } + function createElidedInformationPlaceholder(context) { + context.approximateLength += 3; + if (!(context.flags & 1 /* NoTruncation */)) { + return ts.createTypeReferenceNode(ts.createIdentifier("..."), /*typeArguments*/ undefined); + } + return ts.createKeywordTypeNode(120 /* AnyKeyword */); + } + function addPropertyToElementList(propertySymbol, context, typeElements) { + var propertyIsReverseMapped = !!(ts.getCheckFlags(propertySymbol) & 2048 /* ReverseMapped */); + var propertyType = propertyIsReverseMapped && context.flags & 33554432 /* InReverseMappedType */ ? + anyType : getTypeOfSymbol(propertySymbol); + var saveEnclosingDeclaration = context.enclosingDeclaration; + context.enclosingDeclaration = undefined; + if (context.tracker.trackSymbol && ts.getCheckFlags(propertySymbol) & 1024 /* Late */) { + var decl = ts.first(propertySymbol.declarations); + if (hasLateBindableName(decl)) { + trackComputedName(decl.name, saveEnclosingDeclaration, context); + } + } + var propertyName = symbolToName(propertySymbol, context, 67220415 /* Value */, /*expectsIdentifier*/ true); + context.approximateLength += (ts.symbolName(propertySymbol).length + 1); + context.enclosingDeclaration = saveEnclosingDeclaration; + var optionalToken = propertySymbol.flags & 16777216 /* Optional */ ? ts.createToken(56 /* QuestionToken */) : undefined; + if (propertySymbol.flags & (16 /* Function */ | 8192 /* Method */) && !getPropertiesOfObjectType(propertyType).length) { + var signatures = getSignaturesOfType(propertyType, 0 /* Call */); + for (var _i = 0, signatures_1 = signatures; _i < signatures_1.length; _i++) { + var signature = signatures_1[_i]; + var methodDeclaration = signatureToSignatureDeclarationHelper(signature, 155 /* MethodSignature */, context); + methodDeclaration.name = propertyName; + methodDeclaration.questionToken = optionalToken; + if (propertySymbol.valueDeclaration) { + // Copy comments to node for declaration emit + ts.setCommentRange(methodDeclaration, propertySymbol.valueDeclaration); + } + typeElements.push(methodDeclaration); + } + } + else { + var savedFlags = context.flags; + context.flags |= propertyIsReverseMapped ? 33554432 /* InReverseMappedType */ : 0; + var propertyTypeNode = void 0; + if (propertyIsReverseMapped && !!(savedFlags & 33554432 /* InReverseMappedType */)) { + propertyTypeNode = createElidedInformationPlaceholder(context); + } + else { + propertyTypeNode = propertyType ? typeToTypeNodeHelper(propertyType, context) : ts.createKeywordTypeNode(120 /* AnyKeyword */); + } + context.flags = savedFlags; + var modifiers = isReadonlySymbol(propertySymbol) ? [ts.createToken(133 /* ReadonlyKeyword */)] : undefined; + if (modifiers) { + context.approximateLength += 9; + } + var propertySignature = ts.createPropertySignature(modifiers, propertyName, optionalToken, propertyTypeNode, + /*initializer*/ undefined); + if (propertySymbol.valueDeclaration) { + // Copy comments to node for declaration emit + ts.setCommentRange(propertySignature, propertySymbol.valueDeclaration); + } + typeElements.push(propertySignature); + } + } + function mapToTypeNodes(types, context, isBareList) { + if (ts.some(types)) { + if (checkTruncationLength(context)) { + if (!isBareList) { + return [ts.createTypeReferenceNode("...", /*typeArguments*/ undefined)]; + } + else if (types.length > 2) { + return [ + typeToTypeNodeHelper(types[0], context), + ts.createTypeReferenceNode("... " + (types.length - 2) + " more ...", /*typeArguments*/ undefined), + typeToTypeNodeHelper(types[types.length - 1], context) + ]; + } + } + var result = []; + var i = 0; + for (var _i = 0, types_1 = types; _i < types_1.length; _i++) { + var type = types_1[_i]; + i++; + if (checkTruncationLength(context) && (i + 2 < types.length - 1)) { + result.push(ts.createTypeReferenceNode("... " + (types.length - i) + " more ...", /*typeArguments*/ undefined)); + var typeNode_1 = typeToTypeNodeHelper(types[types.length - 1], context); + if (typeNode_1) { + result.push(typeNode_1); + } + break; + } + context.approximateLength += 2; // Account for whitespace + separator + var typeNode = typeToTypeNodeHelper(type, context); + if (typeNode) { + result.push(typeNode); + } + } + return result; + } + } + function indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind, context) { + var name = ts.getNameFromIndexInfo(indexInfo) || "x"; + var indexerTypeNode = ts.createKeywordTypeNode(kind === 0 /* String */ ? 138 /* StringKeyword */ : 135 /* NumberKeyword */); + var indexingParameter = ts.createParameter( + /*decorators*/ undefined, + /*modifiers*/ undefined, + /*dotDotDotToken*/ undefined, name, + /*questionToken*/ undefined, indexerTypeNode, + /*initializer*/ undefined); + var typeNode = typeToTypeNodeHelper(indexInfo.type || anyType, context); + if (!indexInfo.type && !(context.flags & 2097152 /* AllowEmptyIndexInfoType */)) { + context.encounteredError = true; + } + context.approximateLength += (name.length + 4); + return ts.createIndexSignature( + /*decorators*/ undefined, indexInfo.isReadonly ? [ts.createToken(133 /* ReadonlyKeyword */)] : undefined, [indexingParameter], typeNode); + } + function signatureToSignatureDeclarationHelper(signature, kind, context) { + var typeParameters; + var typeArguments; + if (context.flags & 32 /* WriteTypeArgumentsOfSignature */ && signature.target && signature.mapper && signature.target.typeParameters) { + typeArguments = signature.target.typeParameters.map(function (parameter) { return typeToTypeNodeHelper(instantiateType(parameter, signature.mapper), context); }); + } + else { + typeParameters = signature.typeParameters && signature.typeParameters.map(function (parameter) { return typeParameterToDeclaration(parameter, context); }); + } + var parameters = getExpandedParameters(signature).map(function (parameter) { return symbolToParameterDeclaration(parameter, context, kind === 157 /* Constructor */); }); + if (signature.thisParameter) { + var thisParameter = symbolToParameterDeclaration(signature.thisParameter, context); + parameters.unshift(thisParameter); + } + var returnTypeNode; + var typePredicate = getTypePredicateOfSignature(signature); + if (typePredicate) { + var parameterName = typePredicate.kind === 1 /* Identifier */ ? + ts.setEmitFlags(ts.createIdentifier(typePredicate.parameterName), 16777216 /* NoAsciiEscaping */) : + ts.createThisTypeNode(); + var typeNode = typeToTypeNodeHelper(typePredicate.type, context); + returnTypeNode = ts.createTypePredicateNode(parameterName, typeNode); + } + else { + var returnType = getReturnTypeOfSignature(signature); + returnTypeNode = returnType && typeToTypeNodeHelper(returnType, context); + } + if (context.flags & 256 /* SuppressAnyReturnType */) { + if (returnTypeNode && returnTypeNode.kind === 120 /* AnyKeyword */) { + returnTypeNode = undefined; + } + } + else if (!returnTypeNode) { + returnTypeNode = ts.createKeywordTypeNode(120 /* AnyKeyword */); + } + context.approximateLength += 3; // Usually a signature contributes a few more characters than this, but 3 is the minimum + return ts.createSignatureDeclaration(kind, typeParameters, parameters, returnTypeNode, typeArguments); + } + function typeParameterShadowsNameInScope(type, context) { + return !!resolveName(context.enclosingDeclaration, type.symbol.escapedName, 67897832 /* Type */, /*nameNotFoundArg*/ undefined, type.symbol.escapedName, /*isUse*/ false); + } + function typeParameterToDeclarationWithConstraint(type, context, constraintNode) { + var savedContextFlags = context.flags; + context.flags &= ~512 /* WriteTypeParametersInQualifiedName */; // Avoids potential infinite loop when building for a claimspace with a generic + var shouldUseGeneratedName = context.flags & 4 /* GenerateNamesForShadowedTypeParams */ && + type.symbol.declarations[0] && + ts.isTypeParameterDeclaration(type.symbol.declarations[0]) && + typeParameterShadowsNameInScope(type, context); + var name = shouldUseGeneratedName + ? ts.getGeneratedNameForNode(type.symbol.declarations[0].name, 16 /* Optimistic */ | 8 /* ReservedInNestedScopes */) + : symbolToName(type.symbol, context, 67897832 /* Type */, /*expectsIdentifier*/ true); + var defaultParameter = getDefaultFromTypeParameter(type); + var defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter, context); + context.flags = savedContextFlags; + return ts.createTypeParameterDeclaration(name, constraintNode, defaultParameterNode); + } + function typeParameterToDeclaration(type, context, constraint) { + if (constraint === void 0) { constraint = getConstraintOfTypeParameter(type); } + var constraintNode = constraint && typeToTypeNodeHelper(constraint, context); + return typeParameterToDeclarationWithConstraint(type, context, constraintNode); + } + function symbolToParameterDeclaration(parameterSymbol, context, preserveModifierFlags) { + var parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 151 /* Parameter */); + if (!parameterDeclaration && !isTransientSymbol(parameterSymbol)) { + parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 299 /* JSDocParameterTag */); + } + var parameterType = getTypeOfSymbol(parameterSymbol); + if (parameterDeclaration && isRequiredInitializedParameter(parameterDeclaration)) { + parameterType = getOptionalType(parameterType); + } + var parameterTypeNode = typeToTypeNodeHelper(parameterType, context); + var modifiers = !(context.flags & 8192 /* OmitParameterModifiers */) && preserveModifierFlags && parameterDeclaration && parameterDeclaration.modifiers ? parameterDeclaration.modifiers.map(ts.getSynthesizedClone) : undefined; + var isRest = parameterDeclaration && ts.isRestParameter(parameterDeclaration) || ts.getCheckFlags(parameterSymbol) & 8192 /* RestParameter */; + var dotDotDotToken = isRest ? ts.createToken(25 /* DotDotDotToken */) : undefined; + var name = parameterDeclaration + ? parameterDeclaration.name ? + parameterDeclaration.name.kind === 72 /* Identifier */ ? ts.setEmitFlags(ts.getSynthesizedClone(parameterDeclaration.name), 16777216 /* NoAsciiEscaping */) : + parameterDeclaration.name.kind === 148 /* QualifiedName */ ? ts.setEmitFlags(ts.getSynthesizedClone(parameterDeclaration.name.right), 16777216 /* NoAsciiEscaping */) : + cloneBindingName(parameterDeclaration.name) : + ts.symbolName(parameterSymbol) + : ts.symbolName(parameterSymbol); + var isOptional = parameterDeclaration && isOptionalParameter(parameterDeclaration) || ts.getCheckFlags(parameterSymbol) & 4096 /* OptionalParameter */; + var questionToken = isOptional ? ts.createToken(56 /* QuestionToken */) : undefined; + var parameterNode = ts.createParameter( + /*decorators*/ undefined, modifiers, dotDotDotToken, name, questionToken, parameterTypeNode, + /*initializer*/ undefined); + context.approximateLength += ts.symbolName(parameterSymbol).length + 3; + return parameterNode; + function cloneBindingName(node) { + return elideInitializerAndSetEmitFlags(node); + function elideInitializerAndSetEmitFlags(node) { + if (context.tracker.trackSymbol && ts.isComputedPropertyName(node) && isLateBindableName(node)) { + trackComputedName(node, context.enclosingDeclaration, context); + } + var visited = ts.visitEachChild(node, elideInitializerAndSetEmitFlags, ts.nullTransformationContext, /*nodesVisitor*/ undefined, elideInitializerAndSetEmitFlags); + var clone = ts.nodeIsSynthesized(visited) ? visited : ts.getSynthesizedClone(visited); + if (clone.kind === 186 /* BindingElement */) { + clone.initializer = undefined; + } + return ts.setEmitFlags(clone, 1 /* SingleLine */ | 16777216 /* NoAsciiEscaping */); + } + } + } + function trackComputedName(node, enclosingDeclaration, context) { + if (!context.tracker.trackSymbol) + return; + // get symbol of the first identifier of the entityName + var firstIdentifier = getFirstIdentifier(node.expression); + var name = resolveName(firstIdentifier, firstIdentifier.escapedText, 67220415 /* Value */ | 1048576 /* ExportValue */, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); + if (name) { + context.tracker.trackSymbol(name, enclosingDeclaration, 67220415 /* Value */); + } + } + function lookupSymbolChain(symbol, context, meaning, yieldModuleSymbol) { + context.tracker.trackSymbol(symbol, context.enclosingDeclaration, meaning); // TODO: GH#18217 + // Try to get qualified name if the symbol is not a type parameter and there is an enclosing declaration. + var chain; + var isTypeParameter = symbol.flags & 262144 /* TypeParameter */; + if (!isTypeParameter && (context.enclosingDeclaration || context.flags & 64 /* UseFullyQualifiedType */) && !(context.flags & 134217728 /* DoNotIncludeSymbolChain */)) { + chain = ts.Debug.assertDefined(getSymbolChain(symbol, meaning, /*endOfChain*/ true)); + ts.Debug.assert(chain && chain.length > 0); + } + else { + chain = [symbol]; + } + return chain; + /** @param endOfChain Set to false for recursive calls; non-recursive calls should always output something. */ + function getSymbolChain(symbol, meaning, endOfChain) { + var accessibleSymbolChain = getAccessibleSymbolChain(symbol, context.enclosingDeclaration, meaning, !!(context.flags & 128 /* UseOnlyExternalAliasing */)); + var parentSpecifiers; + if (!accessibleSymbolChain || + needsQualification(accessibleSymbolChain[0], context.enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) { + // Go up and add our parent. + var parents_1 = getContainersOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol, context.enclosingDeclaration); + if (ts.length(parents_1)) { + parentSpecifiers = parents_1.map(function (symbol) { + return ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol) + ? getSpecifierForModuleSymbol(symbol, context) + : undefined; + }); + var indices = parents_1.map(function (_, i) { return i; }); + indices.sort(sortByBestName); + var sortedParents = indices.map(function (i) { return parents_1[i]; }); + for (var _i = 0, sortedParents_1 = sortedParents; _i < sortedParents_1.length; _i++) { + var parent = sortedParents_1[_i]; + var parentChain = getSymbolChain(parent, getQualifiedLeftMeaning(meaning), /*endOfChain*/ false); + if (parentChain) { + accessibleSymbolChain = parentChain.concat(accessibleSymbolChain || [getAliasForSymbolInContainer(parent, symbol) || symbol]); + break; + } + } + } + } + if (accessibleSymbolChain) { + return accessibleSymbolChain; + } + if ( + // If this is the last part of outputting the symbol, always output. The cases apply only to parent symbols. + endOfChain || + // If a parent symbol is an anonymous type, don't write it. + !(symbol.flags & (2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */))) { + // If a parent symbol is an external module, don't write it. (We prefer just `x` vs `"foo/bar".x`.) + if (!endOfChain && !yieldModuleSymbol && !!ts.forEach(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { + return; + } + return [symbol]; + } + function sortByBestName(a, b) { + var specifierA = parentSpecifiers[a]; + var specifierB = parentSpecifiers[b]; + if (specifierA && specifierB) { + var isBRelative = ts.pathIsRelative(specifierB); + if (ts.pathIsRelative(specifierA) === isBRelative) { + // Both relative or both non-relative, sort by number of parts + return ts.moduleSpecifiers.countPathComponents(specifierA) - ts.moduleSpecifiers.countPathComponents(specifierB); + } + if (isBRelative) { + // A is non-relative, B is relative: prefer A + return -1; + } + // A is relative, B is non-relative: prefer B + return 1; + } + return 0; + } + } + } + function typeParametersToTypeParameterDeclarations(symbol, context) { + var typeParameterNodes; + var targetSymbol = getTargetSymbol(symbol); + if (targetSymbol.flags & (32 /* Class */ | 64 /* Interface */ | 524288 /* TypeAlias */)) { + typeParameterNodes = ts.createNodeArray(ts.map(getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol), function (tp) { return typeParameterToDeclaration(tp, context); })); + } + return typeParameterNodes; + } + function lookupTypeParameterNodes(chain, index, context) { + ts.Debug.assert(chain && 0 <= index && index < chain.length); + var symbol = chain[index]; + var typeParameterNodes; + if (context.flags & 512 /* WriteTypeParametersInQualifiedName */ && index < (chain.length - 1)) { + var parentSymbol = symbol; + var nextSymbol = chain[index + 1]; + if (ts.getCheckFlags(nextSymbol) & 1 /* Instantiated */) { + var params = getTypeParametersOfClassOrInterface(parentSymbol.flags & 2097152 /* Alias */ ? resolveAlias(parentSymbol) : parentSymbol); + typeParameterNodes = mapToTypeNodes(ts.map(params, nextSymbol.mapper), context); + } + else { + typeParameterNodes = typeParametersToTypeParameterDeclarations(symbol, context); + } + } + return typeParameterNodes; + } + /** + * Given A[B][C][D], finds A[B] + */ + function getTopmostIndexedAccessType(top) { + if (ts.isIndexedAccessTypeNode(top.objectType)) { + return getTopmostIndexedAccessType(top.objectType); + } + return top; + } + function getSpecifierForModuleSymbol(symbol, context) { + var file = ts.getDeclarationOfKind(symbol, 279 /* SourceFile */); + if (file && file.moduleName !== undefined) { + // Use the amd name if it is available + return file.moduleName; + } + if (!file) { + if (context.tracker.trackReferencedAmbientModule) { + var ambientDecls = ts.filter(symbol.declarations, ts.isAmbientModule); + if (ts.length(ambientDecls)) { + for (var _i = 0, ambientDecls_1 = ambientDecls; _i < ambientDecls_1.length; _i++) { + var decl = ambientDecls_1[_i]; + context.tracker.trackReferencedAmbientModule(decl, symbol); + } + } + } + if (ambientModuleSymbolRegex.test(symbol.escapedName)) { + return symbol.escapedName.substring(1, symbol.escapedName.length - 1); + } + } + if (!context.enclosingDeclaration || !context.tracker.moduleResolverHost) { + // If there's no context declaration, we can't lookup a non-ambient specifier, so we just use the symbol name + if (ambientModuleSymbolRegex.test(symbol.escapedName)) { + return symbol.escapedName.substring(1, symbol.escapedName.length - 1); + } + return ts.getSourceFileOfNode(ts.getNonAugmentationDeclaration(symbol)).fileName; // A resolver may not be provided for baselines and errors - in those cases we use the fileName in full + } + var contextFile = ts.getSourceFileOfNode(ts.getOriginalNode(context.enclosingDeclaration)); + var links = getSymbolLinks(symbol); + var specifier = links.specifierCache && links.specifierCache.get(contextFile.path); + if (!specifier) { + var isBundle_1 = (compilerOptions.out || compilerOptions.outFile); + // For declaration bundles, we need to generate absolute paths relative to the common source dir for imports, + // just like how the declaration emitter does for the ambient module declarations - we can easily accomplish this + // using the `baseUrl` compiler option (which we would otherwise never use in declaration emit) and a non-relative + // specifier preference + var moduleResolverHost = context.tracker.moduleResolverHost; + var specifierCompilerOptions = isBundle_1 ? __assign({}, compilerOptions, { baseUrl: moduleResolverHost.getCommonSourceDirectory() }) : compilerOptions; + specifier = ts.first(ts.moduleSpecifiers.getModuleSpecifiers(symbol, specifierCompilerOptions, contextFile, moduleResolverHost, host.getSourceFiles(), { importModuleSpecifierPreference: isBundle_1 ? "non-relative" : "relative" }, host.redirectTargetsMap)); + links.specifierCache = links.specifierCache || ts.createMap(); + links.specifierCache.set(contextFile.path, specifier); + } + return specifier; + } + function symbolToTypeNode(symbol, context, meaning, overrideTypeArguments) { + var chain = lookupSymbolChain(symbol, context, meaning, !(context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */)); // If we're using aliases outside the current scope, dont bother with the module + var isTypeOf = meaning === 67220415 /* Value */; + if (ts.some(chain[0].declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { + // module is root, must use `ImportTypeNode` + var nonRootParts = chain.length > 1 ? createAccessFromSymbolChain(chain, chain.length - 1, 1) : undefined; + var typeParameterNodes = overrideTypeArguments || lookupTypeParameterNodes(chain, 0, context); + var specifier = getSpecifierForModuleSymbol(chain[0], context); + if (!(context.flags & 67108864 /* AllowNodeModulesRelativePaths */) && ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs && specifier.indexOf("/node_modules/") >= 0) { + // If ultimately we can only name the symbol with a reference that dives into a `node_modules` folder, we should error + // since declaration files with these kinds of references are liable to fail when published :( + context.encounteredError = true; + if (context.tracker.reportLikelyUnsafeImportRequiredError) { + context.tracker.reportLikelyUnsafeImportRequiredError(specifier); + } + } + var lit = ts.createLiteralTypeNode(ts.createLiteral(specifier)); + if (context.tracker.trackExternalModuleSymbolOfImportTypeNode) + context.tracker.trackExternalModuleSymbolOfImportTypeNode(chain[0]); + context.approximateLength += specifier.length + 10; // specifier + import("") + if (!nonRootParts || ts.isEntityName(nonRootParts)) { + if (nonRootParts) { + var lastId = ts.isIdentifier(nonRootParts) ? nonRootParts : nonRootParts.right; + lastId.typeArguments = undefined; + } + return ts.createImportTypeNode(lit, nonRootParts, typeParameterNodes, isTypeOf); + } + else { + var splitNode = getTopmostIndexedAccessType(nonRootParts); + var qualifier = splitNode.objectType.typeName; + return ts.createIndexedAccessTypeNode(ts.createImportTypeNode(lit, qualifier, typeParameterNodes, isTypeOf), splitNode.indexType); + } + } + var entityName = createAccessFromSymbolChain(chain, chain.length - 1, 0); + if (ts.isIndexedAccessTypeNode(entityName)) { + return entityName; // Indexed accesses can never be `typeof` + } + if (isTypeOf) { + return ts.createTypeQueryNode(entityName); + } + else { + var lastId = ts.isIdentifier(entityName) ? entityName : entityName.right; + var lastTypeArgs = lastId.typeArguments; + lastId.typeArguments = undefined; + return ts.createTypeReferenceNode(entityName, lastTypeArgs); + } + function createAccessFromSymbolChain(chain, index, stopper) { + var typeParameterNodes = index === (chain.length - 1) ? overrideTypeArguments : lookupTypeParameterNodes(chain, index, context); + var symbol = chain[index]; + if (index === 0) { + context.flags |= 16777216 /* InInitialEntityName */; + } + var symbolName = getNameOfSymbolAsWritten(symbol, context); + context.approximateLength += symbolName.length + 1; + if (index === 0) { + context.flags ^= 16777216 /* InInitialEntityName */; + } + var parent = chain[index - 1]; + if (!(context.flags & 16 /* ForbidIndexedAccessSymbolReferences */) && parent && getMembersOfSymbol(parent) && getMembersOfSymbol(parent).get(symbol.escapedName) === symbol) { + // Should use an indexed access + var LHS = createAccessFromSymbolChain(chain, index - 1, stopper); + if (ts.isIndexedAccessTypeNode(LHS)) { + return ts.createIndexedAccessTypeNode(LHS, ts.createLiteralTypeNode(ts.createLiteral(symbolName))); + } + else { + return ts.createIndexedAccessTypeNode(ts.createTypeReferenceNode(LHS, typeParameterNodes), ts.createLiteralTypeNode(ts.createLiteral(symbolName))); + } + } + var identifier = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216 /* NoAsciiEscaping */); + identifier.symbol = symbol; + if (index > stopper) { + var LHS = createAccessFromSymbolChain(chain, index - 1, stopper); + if (!ts.isEntityName(LHS)) { + return ts.Debug.fail("Impossible construct - an export of an indexed access cannot be reachable"); + } + return ts.createQualifiedName(LHS, identifier); + } + return identifier; + } + } + function symbolToName(symbol, context, meaning, expectsIdentifier) { + var chain = lookupSymbolChain(symbol, context, meaning); + if (expectsIdentifier && chain.length !== 1 + && !context.encounteredError + && !(context.flags & 65536 /* AllowQualifedNameInPlaceOfIdentifier */)) { + context.encounteredError = true; + } + return createEntityNameFromSymbolChain(chain, chain.length - 1); + function createEntityNameFromSymbolChain(chain, index) { + var typeParameterNodes = lookupTypeParameterNodes(chain, index, context); + var symbol = chain[index]; + if (index === 0) { + context.flags |= 16777216 /* InInitialEntityName */; + } + var symbolName = getNameOfSymbolAsWritten(symbol, context); + if (index === 0) { + context.flags ^= 16777216 /* InInitialEntityName */; + } + var identifier = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216 /* NoAsciiEscaping */); + identifier.symbol = symbol; + return index > 0 ? ts.createQualifiedName(createEntityNameFromSymbolChain(chain, index - 1), identifier) : identifier; + } + } + function symbolToExpression(symbol, context, meaning) { + var chain = lookupSymbolChain(symbol, context, meaning); + return createExpressionFromSymbolChain(chain, chain.length - 1); + function createExpressionFromSymbolChain(chain, index) { + var typeParameterNodes = lookupTypeParameterNodes(chain, index, context); + var symbol = chain[index]; + if (ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { + return ts.createLiteral(getSpecifierForModuleSymbol(symbol, context)); + } + if (index === 0) { + context.flags |= 16777216 /* InInitialEntityName */; + } + var symbolName = getNameOfSymbolAsWritten(symbol, context); + if (index === 0) { + context.flags ^= 16777216 /* InInitialEntityName */; + } + var firstChar = symbolName.charCodeAt(0); + var canUsePropertyAccess = ts.isIdentifierStart(firstChar, languageVersion); + if (index === 0 || canUsePropertyAccess) { + var identifier = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216 /* NoAsciiEscaping */); + identifier.symbol = symbol; + return index > 0 ? ts.createPropertyAccess(createExpressionFromSymbolChain(chain, index - 1), identifier) : identifier; + } + else { + if (firstChar === 91 /* openBracket */) { + symbolName = symbolName.substring(1, symbolName.length - 1); + firstChar = symbolName.charCodeAt(0); + } + var expression = void 0; + if (ts.isSingleOrDoubleQuote(firstChar)) { + expression = ts.createLiteral(symbolName.substring(1, symbolName.length - 1).replace(/\\./g, function (s) { return s.substring(1); })); + expression.singleQuote = firstChar === 39 /* singleQuote */; + } + else if (("" + +symbolName) === symbolName) { + expression = ts.createLiteral(+symbolName); + } + if (!expression) { + expression = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216 /* NoAsciiEscaping */); + expression.symbol = symbol; + } + return ts.createElementAccess(createExpressionFromSymbolChain(chain, index - 1), expression); + } + } + } + } + function typePredicateToString(typePredicate, enclosingDeclaration, flags, writer) { + if (flags === void 0) { flags = 16384 /* UseAliasDefinedOutsideCurrentScope */; } + return writer ? typePredicateToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(typePredicateToStringWorker); + function typePredicateToStringWorker(writer) { + var predicate = ts.createTypePredicateNode(typePredicate.kind === 1 /* Identifier */ ? ts.createIdentifier(typePredicate.parameterName) : ts.createThisTypeNode(), nodeBuilder.typeToTypeNode(typePredicate.type, enclosingDeclaration, toNodeBuilderFlags(flags) | 70221824 /* IgnoreErrors */ | 512 /* WriteTypeParametersInQualifiedName */)); + var printer = ts.createPrinter({ removeComments: true }); + var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); + printer.writeNode(4 /* Unspecified */, predicate, /*sourceFile*/ sourceFile, writer); + return writer; + } + } + function formatUnionTypes(types) { + var result = []; + var flags = 0; + for (var i = 0; i < types.length; i++) { + var t = types[i]; + flags |= t.flags; + if (!(t.flags & 98304 /* Nullable */)) { + if (t.flags & (512 /* BooleanLiteral */ | 1024 /* EnumLiteral */)) { + var baseType = t.flags & 512 /* BooleanLiteral */ ? booleanType : getBaseTypeOfEnumLiteralType(t); + if (baseType.flags & 1048576 /* Union */) { + var count = baseType.types.length; + if (i + count <= types.length && getRegularTypeOfLiteralType(types[i + count - 1]) === getRegularTypeOfLiteralType(baseType.types[count - 1])) { + result.push(baseType); + i += count - 1; + continue; + } + } + } + result.push(t); + } + } + if (flags & 65536 /* Null */) + result.push(nullType); + if (flags & 32768 /* Undefined */) + result.push(undefinedType); + return result || types; + } + function visibilityToString(flags) { + if (flags === 8 /* Private */) { + return "private"; + } + if (flags === 16 /* Protected */) { + return "protected"; + } + return "public"; + } + function getTypeAliasForTypeLiteral(type) { + if (type.symbol && type.symbol.flags & 2048 /* TypeLiteral */) { + var node = ts.findAncestor(type.symbol.declarations[0].parent, function (n) { return n.kind !== 177 /* ParenthesizedType */; }); + if (node.kind === 242 /* TypeAliasDeclaration */) { + return getSymbolOfNode(node); + } + } + return undefined; + } + function isTopLevelInExternalModuleAugmentation(node) { + return node && node.parent && + node.parent.kind === 245 /* ModuleBlock */ && + ts.isExternalModuleAugmentation(node.parent.parent); + } + function isDefaultBindingContext(location) { + return location.kind === 279 /* SourceFile */ || ts.isAmbientModule(location); + } + /** + * Gets a human-readable name for a symbol. + * Should *not* be used for the right-hand side of a `.` -- use `symbolName(symbol)` for that instead. + * + * Unlike `symbolName(symbol)`, this will include quotes if the name is from a string literal. + * It will also use a representation of a number as written instead of a decimal form, e.g. `0o11` instead of `9`. + */ + function getNameOfSymbolAsWritten(symbol, context) { + if (context && symbol.escapedName === "default" /* Default */ && !(context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */) && + // If it's not the first part of an entity name, it must print as `default` + (!(context.flags & 16777216 /* InInitialEntityName */) || + // if the symbol is synthesized, it will only be referenced externally it must print as `default` + !symbol.declarations || + // if not in the same binding context (source file, module declaration), it must print as `default` + (context.enclosingDeclaration && ts.findAncestor(symbol.declarations[0], isDefaultBindingContext) !== ts.findAncestor(context.enclosingDeclaration, isDefaultBindingContext)))) { + return "default"; + } + if (symbol.declarations && symbol.declarations.length) { + var declaration = symbol.declarations[0]; + var name = ts.getNameOfDeclaration(declaration); + if (name) { + if (ts.isCallExpression(declaration) && ts.isBindableObjectDefinePropertyCall(declaration)) { + return ts.symbolName(symbol); + } + return ts.declarationNameToString(name); + } + if (declaration.parent && declaration.parent.kind === 237 /* VariableDeclaration */) { + return ts.declarationNameToString(declaration.parent.name); + } + switch (declaration.kind) { + case 209 /* ClassExpression */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + if (context && !context.encounteredError && !(context.flags & 131072 /* AllowAnonymousIdentifier */)) { + context.encounteredError = true; + } + return declaration.kind === 209 /* ClassExpression */ ? "(Anonymous class)" : "(Anonymous function)"; + } + } + var nameType = symbol.nameType; + if (nameType) { + if (nameType.flags & 128 /* StringLiteral */ && !ts.isIdentifierText(nameType.value, compilerOptions.target)) { + return "\"" + ts.escapeString(nameType.value, 34 /* doubleQuote */) + "\""; + } + if (nameType && nameType.flags & 8192 /* UniqueESSymbol */) { + return "[" + getNameOfSymbolAsWritten(nameType.symbol, context) + "]"; + } + } + return ts.symbolName(symbol); + } + function isDeclarationVisible(node) { + if (node) { + var links = getNodeLinks(node); + if (links.isVisible === undefined) { + links.isVisible = !!determineIfDeclarationIsVisible(); + } + return links.isVisible; + } + return false; + function determineIfDeclarationIsVisible() { + switch (node.kind) { + case 297 /* JSDocCallbackTag */: + case 304 /* JSDocTypedefTag */: + // Top-level jsdoc type aliases are considered exported + // First parent is comment node, second is hosting declaration or token; we only care about those tokens or declarations whose parent is a source file + return !!(node.parent && node.parent.parent && node.parent.parent.parent && ts.isSourceFile(node.parent.parent.parent)); + case 186 /* BindingElement */: + return isDeclarationVisible(node.parent.parent); + case 237 /* VariableDeclaration */: + if (ts.isBindingPattern(node.name) && + !node.name.elements.length) { + // If the binding pattern is empty, this variable declaration is not visible + return false; + } + // falls through + case 244 /* ModuleDeclaration */: + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 239 /* FunctionDeclaration */: + case 243 /* EnumDeclaration */: + case 248 /* ImportEqualsDeclaration */: + // external module augmentation is always visible + if (ts.isExternalModuleAugmentation(node)) { + return true; + } + var parent = getDeclarationContainer(node); + // If the node is not exported or it is not ambient module element (except import declaration) + if (!(ts.getCombinedModifierFlags(node) & 1 /* Export */) && + !(node.kind !== 248 /* ImportEqualsDeclaration */ && parent.kind !== 279 /* SourceFile */ && parent.flags & 4194304 /* Ambient */)) { + return isGlobalSourceFile(parent); + } + // Exported members/ambient module elements (exception import declaration) are visible if parent is visible + return isDeclarationVisible(parent); + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + if (ts.hasModifier(node, 8 /* Private */ | 16 /* Protected */)) { + // Private/protected properties/methods are not visible + return false; + } + // Public properties/methods are visible if its parents are visible, so: + // falls through + case 157 /* Constructor */: + case 161 /* ConstructSignature */: + case 160 /* CallSignature */: + case 162 /* IndexSignature */: + case 151 /* Parameter */: + case 245 /* ModuleBlock */: + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + case 168 /* TypeLiteral */: + case 164 /* TypeReference */: + case 169 /* ArrayType */: + case 170 /* TupleType */: + case 173 /* UnionType */: + case 174 /* IntersectionType */: + case 177 /* ParenthesizedType */: + return isDeclarationVisible(node.parent); + // Default binding, import specifier and namespace import is visible + // only on demand so by default it is not visible + case 250 /* ImportClause */: + case 251 /* NamespaceImport */: + case 253 /* ImportSpecifier */: + return false; + // Type parameters are always visible + case 150 /* TypeParameter */: + // Source file and namespace export are always visible + case 279 /* SourceFile */: + case 247 /* NamespaceExportDeclaration */: + return true; + // Export assignments do not create name bindings outside the module + case 254 /* ExportAssignment */: + return false; + default: + return false; + } + } + } + function collectLinkedAliases(node, setVisibility) { + var exportSymbol; + if (node.parent && node.parent.kind === 254 /* ExportAssignment */) { + exportSymbol = resolveName(node, node.escapedText, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, node, /*isUse*/ false); + } + else if (node.parent.kind === 257 /* ExportSpecifier */) { + exportSymbol = getTargetOfExportSpecifier(node.parent, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); + } + var result; + if (exportSymbol) { + buildVisibleNodeList(exportSymbol.declarations); + } + return result; + function buildVisibleNodeList(declarations) { + ts.forEach(declarations, function (declaration) { + var resultNode = getAnyImportSyntax(declaration) || declaration; + if (setVisibility) { + getNodeLinks(declaration).isVisible = true; + } + else { + result = result || []; + ts.pushIfUnique(result, resultNode); + } + if (ts.isInternalModuleImportEqualsDeclaration(declaration)) { + // Add the referenced top container visible + var internalModuleReference = declaration.moduleReference; + var firstIdentifier = getFirstIdentifier(internalModuleReference); + var importSymbol = resolveName(declaration, firstIdentifier.escapedText, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */, undefined, undefined, /*isUse*/ false); + if (importSymbol) { + buildVisibleNodeList(importSymbol.declarations); + } + } + }); + } + } + /** + * Push an entry on the type resolution stack. If an entry with the given target and the given property name + * is already on the stack, and no entries in between already have a type, then a circularity has occurred. + * In this case, the result values of the existing entry and all entries pushed after it are changed to false, + * and the value false is returned. Otherwise, the new entry is just pushed onto the stack, and true is returned. + * In order to see if the same query has already been done before, the target object and the propertyName both + * must match the one passed in. + * + * @param target The symbol, type, or signature whose type is being queried + * @param propertyName The property name that should be used to query the target for its type + */ + function pushTypeResolution(target, propertyName) { + var resolutionCycleStartIndex = findResolutionCycleStartIndex(target, propertyName); + if (resolutionCycleStartIndex >= 0) { + // A cycle was found + var length_2 = resolutionTargets.length; + for (var i = resolutionCycleStartIndex; i < length_2; i++) { + resolutionResults[i] = false; + } + return false; + } + resolutionTargets.push(target); + resolutionResults.push(/*items*/ true); + resolutionPropertyNames.push(propertyName); + return true; + } + function findResolutionCycleStartIndex(target, propertyName) { + for (var i = resolutionTargets.length - 1; i >= 0; i--) { + if (hasType(resolutionTargets[i], resolutionPropertyNames[i])) { + return -1; + } + if (resolutionTargets[i] === target && resolutionPropertyNames[i] === propertyName) { + return i; + } + } + return -1; + } + function hasType(target, propertyName) { + switch (propertyName) { + case 0 /* Type */: + return !!getSymbolLinks(target).type; + case 5 /* EnumTagType */: + return !!(getNodeLinks(target).resolvedEnumType); + case 2 /* DeclaredType */: + return !!getSymbolLinks(target).declaredType; + case 1 /* ResolvedBaseConstructorType */: + return !!target.resolvedBaseConstructorType; + case 3 /* ResolvedReturnType */: + return !!target.resolvedReturnType; + case 4 /* ImmediateBaseConstraint */: + return !!target.immediateBaseConstraint; + case 6 /* JSDocTypeReference */: + return !!getSymbolLinks(target).resolvedJSDocType; + } + return ts.Debug.assertNever(propertyName); + } + // Pop an entry from the type resolution stack and return its associated result value. The result value will + // be true if no circularities were detected, or false if a circularity was found. + function popTypeResolution() { + resolutionTargets.pop(); + resolutionPropertyNames.pop(); + return resolutionResults.pop(); + } + function getDeclarationContainer(node) { + return ts.findAncestor(ts.getRootDeclaration(node), function (node) { + switch (node.kind) { + case 237 /* VariableDeclaration */: + case 238 /* VariableDeclarationList */: + case 253 /* ImportSpecifier */: + case 252 /* NamedImports */: + case 251 /* NamespaceImport */: + case 250 /* ImportClause */: + return false; + default: + return true; + } + }).parent; + } + function getTypeOfPrototypeProperty(prototype) { + // TypeScript 1.0 spec (April 2014): 8.4 + // Every class automatically contains a static property member named 'prototype', + // the type of which is an instantiation of the class type with type Any supplied as a type argument for each type parameter. + // It is an error to explicitly declare a static property member with the name 'prototype'. + var classType = getDeclaredTypeOfSymbol(getParentOfSymbol(prototype)); + return classType.typeParameters ? createTypeReference(classType, ts.map(classType.typeParameters, function (_) { return anyType; })) : classType; + } + // Return the type of the given property in the given type, or undefined if no such property exists + function getTypeOfPropertyOfType(type, name) { + var prop = getPropertyOfType(type, name); + return prop ? getTypeOfSymbol(prop) : undefined; + } + function isTypeAny(type) { + return type && (type.flags & 1 /* Any */) !== 0; + } + // Return the type of a binding element parent. We check SymbolLinks first to see if a type has been + // assigned by contextual typing. + function getTypeForBindingElementParent(node) { + var symbol = getSymbolOfNode(node); + return symbol && getSymbolLinks(symbol).type || getTypeForVariableLikeDeclaration(node, /*includeOptionality*/ false); + } + function isComputedNonLiteralName(name) { + return name.kind === 149 /* ComputedPropertyName */ && !ts.isStringOrNumericLiteralLike(name.expression); + } + function getRestType(source, properties, symbol) { + source = filterType(source, function (t) { return !(t.flags & 98304 /* Nullable */); }); + if (source.flags & 131072 /* Never */) { + return emptyObjectType; + } + if (source.flags & 1048576 /* Union */) { + return mapType(source, function (t) { return getRestType(t, properties, symbol); }); + } + var omitKeyType = getUnionType(ts.map(properties, getLiteralTypeFromPropertyName)); + if (isGenericObjectType(source) || isGenericIndexType(omitKeyType)) { + if (omitKeyType.flags & 131072 /* Never */) { + return source; + } + var pickTypeAlias = getGlobalPickSymbol(); + var excludeTypeAlias = getGlobalExcludeSymbol(); + if (!pickTypeAlias || !excludeTypeAlias) { + return errorType; + } + var pickKeys = getTypeAliasInstantiation(excludeTypeAlias, [getIndexType(source), omitKeyType]); + return getTypeAliasInstantiation(pickTypeAlias, [source, pickKeys]); + } + var members = ts.createSymbolTable(); + for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) { + var prop = _a[_i]; + if (!isTypeAssignableTo(getLiteralTypeFromProperty(prop, 8576 /* StringOrNumberLiteralOrUnique */), omitKeyType) + && !(ts.getDeclarationModifierFlagsFromSymbol(prop) & (8 /* Private */ | 16 /* Protected */)) + && isSpreadableProperty(prop)) { + members.set(prop.escapedName, getSpreadSymbol(prop)); + } + } + var stringIndexInfo = getIndexInfoOfType(source, 0 /* String */); + var numberIndexInfo = getIndexInfoOfType(source, 1 /* Number */); + return createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); + } + /** Return the inferred type for a binding element */ + function getTypeForBindingElement(declaration) { + var pattern = declaration.parent; + var parentType = getTypeForBindingElementParent(pattern.parent); + // If parent has the unknown (error) type, then so does this binding element + if (parentType === errorType) { + return errorType; + } + // If no type was specified or inferred for parent, + // infer from the initializer of the binding element if one is present. + // Otherwise, go with the undefined type of the parent. + if (!parentType) { + return declaration.initializer ? checkDeclarationInitializer(declaration) : parentType; + } + if (isTypeAny(parentType)) { + return parentType; + } + // Relax null check on ambient destructuring parameters, since the parameters have no implementation and are just documentation + if (strictNullChecks && declaration.flags & 4194304 /* Ambient */ && ts.isParameterDeclaration(declaration)) { + parentType = getNonNullableType(parentType); + } + var type; + if (pattern.kind === 184 /* ObjectBindingPattern */) { + if (declaration.dotDotDotToken) { + if (parentType.flags & 2 /* Unknown */ || !isValidSpreadType(parentType)) { + error(declaration, ts.Diagnostics.Rest_types_may_only_be_created_from_object_types); + return errorType; + } + var literalMembers = []; + for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (!element.dotDotDotToken) { + literalMembers.push(element.propertyName || element.name); + } + } + type = getRestType(parentType, literalMembers, declaration.symbol); + } + else { + // Use explicitly specified property name ({ p: xxx } form), or otherwise the implied name ({ p } form) + var name = declaration.propertyName || declaration.name; + var exprType = getLiteralTypeFromPropertyName(name); + var declaredType = checkIndexedAccessIndexType(getIndexedAccessType(parentType, exprType, name), name); + type = getFlowTypeOfReference(declaration, getConstraintForLocation(declaredType, declaration.name)); + } + } + else { + // This elementType will be used if the specific property corresponding to this index is not + // present (aka the tuple element property). This call also checks that the parentType is in + // fact an iterable or array (depending on target language). + var elementType = checkIteratedTypeOrElementType(parentType, pattern, /*allowStringInput*/ false, /*allowAsyncIterables*/ false); + var index_1 = pattern.elements.indexOf(declaration); + if (declaration.dotDotDotToken) { + // If the parent is a tuple type, the rest element has a tuple type of the + // remaining tuple element types. Otherwise, the rest element has an array type with same + // element type as the parent type. + type = everyType(parentType, isTupleType) ? + mapType(parentType, function (t) { return sliceTupleType(t, index_1); }) : + createArrayType(elementType); + } + else { + // Use specific property type when parent is a tuple or numeric index type when parent is an array + var index_2 = pattern.elements.indexOf(declaration); + type = everyType(parentType, isTupleLikeType) ? + getTupleElementType(parentType, index_2) || declaration.initializer && checkDeclarationInitializer(declaration) : + elementType; + if (!type) { + if (isTupleType(parentType)) { + error(declaration, ts.Diagnostics.Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2, typeToString(parentType), getTypeReferenceArity(parentType), pattern.elements.length); + } + else { + error(declaration, ts.Diagnostics.Type_0_has_no_property_1, typeToString(parentType), "" + index_2); + } + return errorType; + } + } + } + // In strict null checking mode, if a default value of a non-undefined type is specified, remove + // undefined from the final type. + if (strictNullChecks && declaration.initializer && !(getFalsyFlags(checkDeclarationInitializer(declaration)) & 32768 /* Undefined */)) { + type = getTypeWithFacts(type, 524288 /* NEUndefined */); + } + return declaration.initializer && !ts.getEffectiveTypeAnnotationNode(ts.walkUpBindingElementsAndPatterns(declaration)) ? + getUnionType([type, checkDeclarationInitializer(declaration)], 2 /* Subtype */) : + type; + } + function getTypeForDeclarationFromJSDocComment(declaration) { + var jsdocType = ts.getJSDocType(declaration); + if (jsdocType) { + return getTypeFromTypeNode(jsdocType); + } + return undefined; + } + function isNullOrUndefined(node) { + var expr = ts.skipParentheses(node); + return expr.kind === 96 /* NullKeyword */ || expr.kind === 72 /* Identifier */ && getResolvedSymbol(expr) === undefinedSymbol; + } + function isEmptyArrayLiteral(node) { + var expr = ts.skipParentheses(node); + return expr.kind === 187 /* ArrayLiteralExpression */ && expr.elements.length === 0; + } + function addOptionality(type, optional) { + if (optional === void 0) { optional = true; } + return strictNullChecks && optional ? getOptionalType(type) : type; + } + // Return the inferred type for a variable, parameter, or property declaration + function getTypeForVariableLikeDeclaration(declaration, includeOptionality) { + // A variable declared in a for..in statement is of type string, or of type keyof T when the + // right hand expression is of a type parameter type. + if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 226 /* ForInStatement */) { + var indexType = getIndexType(getNonNullableTypeIfNeeded(checkExpression(declaration.parent.parent.expression))); + return indexType.flags & (262144 /* TypeParameter */ | 4194304 /* Index */) ? getExtractStringType(indexType) : stringType; + } + if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 227 /* ForOfStatement */) { + // checkRightHandSideOfForOf will return undefined if the for-of expression type was + // missing properties/signatures required to get its iteratedType (like + // [Symbol.iterator] or next). This may be because we accessed properties from anyType, + // or it may have led to an error inside getElementTypeOfIterable. + var forOfStatement = declaration.parent.parent; + return checkRightHandSideOfForOf(forOfStatement.expression, forOfStatement.awaitModifier) || anyType; + } + if (ts.isBindingPattern(declaration.parent)) { + return getTypeForBindingElement(declaration); + } + var isOptional = includeOptionality && (ts.isParameter(declaration) && isJSDocOptionalParameter(declaration) + || !ts.isBindingElement(declaration) && !ts.isVariableDeclaration(declaration) && !!declaration.questionToken); + // Use type from type annotation if one is present + var declaredType = tryGetTypeFromEffectiveTypeNode(declaration); + if (declaredType) { + return addOptionality(declaredType, isOptional); + } + if ((noImplicitAny || ts.isInJSFile(declaration)) && + declaration.kind === 237 /* VariableDeclaration */ && !ts.isBindingPattern(declaration.name) && + !(ts.getCombinedModifierFlags(declaration) & 1 /* Export */) && !(declaration.flags & 4194304 /* Ambient */)) { + // If --noImplicitAny is on or the declaration is in a Javascript file, + // use control flow tracked 'any' type for non-ambient, non-exported var or let variables with no + // initializer or a 'null' or 'undefined' initializer. + if (!(ts.getCombinedNodeFlags(declaration) & 2 /* Const */) && (!declaration.initializer || isNullOrUndefined(declaration.initializer))) { + return autoType; + } + // Use control flow tracked 'any[]' type for non-ambient, non-exported variables with an empty array + // literal initializer. + if (declaration.initializer && isEmptyArrayLiteral(declaration.initializer)) { + return autoArrayType; + } + } + if (declaration.kind === 151 /* Parameter */) { + var func = declaration.parent; + // For a parameter of a set accessor, use the type of the get accessor if one is present + if (func.kind === 159 /* SetAccessor */ && !hasNonBindableDynamicName(func)) { + var getter = ts.getDeclarationOfKind(getSymbolOfNode(declaration.parent), 158 /* GetAccessor */); + if (getter) { + var getterSignature = getSignatureFromDeclaration(getter); + var thisParameter = getAccessorThisParameter(func); + if (thisParameter && declaration === thisParameter) { + // Use the type from the *getter* + ts.Debug.assert(!thisParameter.type); + return getTypeOfSymbol(getterSignature.thisParameter); + } + return getReturnTypeOfSignature(getterSignature); + } + } + if (ts.isInJSFile(declaration)) { + var typeTag = ts.getJSDocType(func); + if (typeTag && ts.isFunctionTypeNode(typeTag)) { + return getTypeAtPosition(getSignatureFromDeclaration(typeTag), func.parameters.indexOf(declaration)); + } + } + // Use contextual parameter type if one is available + var type = declaration.symbol.escapedName === "this" /* This */ ? getContextualThisParameterType(func) : getContextuallyTypedParameterType(declaration); + if (type) { + return addOptionality(type, isOptional); + } + } + else if (ts.isInJSFile(declaration)) { + var containerObjectType = getJSContainerObjectType(declaration, getSymbolOfNode(declaration), ts.getDeclaredExpandoInitializer(declaration)); + if (containerObjectType) { + return containerObjectType; + } + } + // Use the type of the initializer expression if one is present + if (declaration.initializer) { + var type = checkDeclarationInitializer(declaration); + return addOptionality(type, isOptional); + } + if (ts.isJsxAttribute(declaration)) { + // if JSX attribute doesn't have initializer, by default the attribute will have boolean value of true. + // I.e is sugar for + return trueType; + } + // If the declaration specifies a binding pattern, use the type implied by the binding pattern + if (ts.isBindingPattern(declaration.name)) { + return getTypeFromBindingPattern(declaration.name, /*includePatternInType*/ false, /*reportErrors*/ true); + } + // No type specified and nothing can be inferred + return undefined; + } + function getWidenedTypeFromAssignmentDeclaration(symbol, resolvedSymbol) { + // function/class/{} initializers are themselves containers, so they won't merge in the same way as other initializers + var container = ts.getAssignedExpandoInitializer(symbol.valueDeclaration); + if (container) { + var tag = ts.getJSDocTypeTag(container); + if (tag && tag.typeExpression) { + return getTypeFromTypeNode(tag.typeExpression); + } + var containerObjectType = getJSContainerObjectType(symbol.valueDeclaration, symbol, container); + return containerObjectType || getWidenedLiteralType(checkExpressionCached(container)); + } + var definedInConstructor = false; + var definedInMethod = false; + var jsdocType; + var types; + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + var expression = (ts.isBinaryExpression(declaration) || ts.isCallExpression(declaration)) ? declaration : + ts.isPropertyAccessExpression(declaration) ? ts.isBinaryExpression(declaration.parent) ? declaration.parent : declaration : + undefined; + if (!expression) { + return errorType; + } + var kind = ts.isPropertyAccessExpression(expression) ? ts.getAssignmentDeclarationPropertyAccessKind(expression) : ts.getAssignmentDeclarationKind(expression); + if (kind === 4 /* ThisProperty */) { + if (isDeclarationInConstructor(expression)) { + definedInConstructor = true; + } + else { + definedInMethod = true; + } + } + if (!ts.isCallExpression(expression)) { + jsdocType = getJSDocTypeFromAssignmentDeclaration(jsdocType, expression, symbol, declaration); + } + if (!jsdocType) { + (types || (types = [])).push((ts.isBinaryExpression(expression) || ts.isCallExpression(expression)) ? getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) : neverType); + } + } + var type = jsdocType; + if (!type) { + var constructorTypes = definedInConstructor ? getConstructorDefinedThisAssignmentTypes(types, symbol.declarations) : undefined; + // use only the constructor types unless they were only assigned null | undefined (including widening variants) + if (definedInMethod) { + var propType = getTypeOfAssignmentDeclarationPropertyOfBaseType(symbol); + if (propType) { + (constructorTypes || (constructorTypes = [])).push(propType); + definedInConstructor = true; + } + } + var sourceTypes = ts.some(constructorTypes, function (t) { return !!(t.flags & ~(98304 /* Nullable */ | 134217728 /* ContainsWideningType */)); }) ? constructorTypes : types; // TODO: GH#18217 + type = getUnionType(sourceTypes, 2 /* Subtype */); + } + var widened = getWidenedType(addOptionality(type, definedInMethod && !definedInConstructor)); + if (filterType(widened, function (t) { return !!(t.flags & ~98304 /* Nullable */); }) === neverType) { + reportImplicitAny(symbol.valueDeclaration, anyType); + return anyType; + } + return widened; + } + function getJSContainerObjectType(decl, symbol, init) { + if (!ts.isInJSFile(decl) || !init || !ts.isObjectLiteralExpression(init) || init.properties.length) { + return undefined; + } + var exports = ts.createSymbolTable(); + while (ts.isBinaryExpression(decl) || ts.isPropertyAccessExpression(decl)) { + var s_1 = getSymbolOfNode(decl); + if (s_1 && ts.hasEntries(s_1.exports)) { + mergeSymbolTable(exports, s_1.exports); + } + decl = ts.isBinaryExpression(decl) ? decl.parent : decl.parent.parent; + } + var s = getSymbolOfNode(decl); + if (s && ts.hasEntries(s.exports)) { + mergeSymbolTable(exports, s.exports); + } + var type = createAnonymousType(symbol, exports, ts.emptyArray, ts.emptyArray, undefined, undefined); + type.objectFlags |= 16384 /* JSLiteral */; + return type; + } + function getJSDocTypeFromAssignmentDeclaration(declaredType, expression, _symbol, declaration) { + var typeNode = ts.getJSDocType(expression.parent); + if (typeNode) { + var type = getWidenedType(getTypeFromTypeNode(typeNode)); + if (!declaredType) { + return type; + } + else if (declaredType !== errorType && type !== errorType && !isTypeIdenticalTo(declaredType, type)) { + errorNextVariableOrPropertyDeclarationMustHaveSameType(declaredType, declaration, type); + } + } + return declaredType; + } + /** If we don't have an explicit JSDoc type, get the type from the initializer. */ + function getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) { + if (ts.isCallExpression(expression)) { + if (resolvedSymbol) { + return getTypeOfSymbol(resolvedSymbol); // This shouldn't happen except under some hopefully forbidden merges of export assignments and object define assignments + } + var objectLitType = checkExpressionCached(expression.arguments[2]); + var valueType = getTypeOfPropertyOfType(objectLitType, "value"); + if (valueType) { + return valueType; + } + var getFunc = getTypeOfPropertyOfType(objectLitType, "get"); + if (getFunc) { + var getSig = getSingleCallSignature(getFunc); + if (getSig) { + return getReturnTypeOfSignature(getSig); + } + } + var setFunc = getTypeOfPropertyOfType(objectLitType, "set"); + if (setFunc) { + var setSig = getSingleCallSignature(setFunc); + if (setSig) { + return getTypeOfFirstParameterOfSignature(setSig); + } + } + return anyType; + } + var type = resolvedSymbol ? getTypeOfSymbol(resolvedSymbol) : getWidenedLiteralType(checkExpressionCached(expression.right)); + if (type.flags & 524288 /* Object */ && + kind === 2 /* ModuleExports */ && + symbol.escapedName === "export=" /* ExportEquals */) { + var exportedType_1 = resolveStructuredTypeMembers(type); + var members_3 = ts.createSymbolTable(); + ts.copyEntries(exportedType_1.members, members_3); + if (resolvedSymbol && !resolvedSymbol.exports) { + resolvedSymbol.exports = ts.createSymbolTable(); + } + (resolvedSymbol || symbol).exports.forEach(function (s, name) { + if (members_3.has(name)) { + var exportedMember = exportedType_1.members.get(name); + var union = createSymbol(s.flags | exportedMember.flags, name); + union.type = getUnionType([getTypeOfSymbol(s), getTypeOfSymbol(exportedMember)]); + members_3.set(name, union); + } + else { + members_3.set(name, s); + } + }); + var result = createAnonymousType(exportedType_1.symbol, members_3, exportedType_1.callSignatures, exportedType_1.constructSignatures, exportedType_1.stringIndexInfo, exportedType_1.numberIndexInfo); + result.objectFlags |= (ts.getObjectFlags(type) & 16384 /* JSLiteral */); // Propagate JSLiteral flag + return result; + } + if (isEmptyArrayLiteralType(type)) { + reportImplicitAny(expression, anyArrayType); + return anyArrayType; + } + return type; + } + function isDeclarationInConstructor(expression) { + var thisContainer = ts.getThisContainer(expression, /*includeArrowFunctions*/ false); + // Properties defined in a constructor (or base constructor, or javascript constructor function) don't get undefined added. + // Function expressions that are assigned to the prototype count as methods. + return thisContainer.kind === 157 /* Constructor */ || + thisContainer.kind === 239 /* FunctionDeclaration */ || + (thisContainer.kind === 196 /* FunctionExpression */ && !ts.isPrototypePropertyAssignment(thisContainer.parent)); + } + function getConstructorDefinedThisAssignmentTypes(types, declarations) { + ts.Debug.assert(types.length === declarations.length); + return types.filter(function (_, i) { + var declaration = declarations[i]; + var expression = ts.isBinaryExpression(declaration) ? declaration : + ts.isBinaryExpression(declaration.parent) ? declaration.parent : undefined; + return expression && isDeclarationInConstructor(expression); + }); + } + /** check for definition in base class if any declaration is in a class */ + function getTypeOfAssignmentDeclarationPropertyOfBaseType(property) { + var parentDeclaration = ts.forEach(property.declarations, function (d) { + var parent = ts.getThisContainer(d, /*includeArrowFunctions*/ false).parent; + return ts.isClassLike(parent) && parent; + }); + if (parentDeclaration) { + var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(parentDeclaration)); + var baseClassType = classType && getBaseTypes(classType)[0]; + if (baseClassType) { + return getTypeOfPropertyOfType(baseClassType, property.escapedName); + } + } + } + // Return the type implied by a binding pattern element. This is the type of the initializer of the element if + // one is present. Otherwise, if the element is itself a binding pattern, it is the type implied by the binding + // pattern. Otherwise, it is the type any. + function getTypeFromBindingElement(element, includePatternInType, reportErrors) { + if (element.initializer) { + return addOptionality(checkDeclarationInitializer(element)); + } + if (ts.isBindingPattern(element.name)) { + return getTypeFromBindingPattern(element.name, includePatternInType, reportErrors); + } + if (reportErrors && !declarationBelongsToPrivateAmbientMember(element)) { + reportImplicitAny(element, anyType); + } + return anyType; + } + // Return the type implied by an object binding pattern + function getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) { + var members = ts.createSymbolTable(); + var stringIndexInfo; + var objectFlags = 128 /* ObjectLiteral */; + ts.forEach(pattern.elements, function (e) { + var name = e.propertyName || e.name; + if (isComputedNonLiteralName(name)) { + // do not include computed properties in the implied type + objectFlags |= 512 /* ObjectLiteralPatternWithComputedProperties */; + return; + } + if (e.dotDotDotToken) { + stringIndexInfo = createIndexInfo(anyType, /*isReadonly*/ false); + return; + } + var text = ts.getTextOfPropertyName(name); + var flags = 4 /* Property */ | (e.initializer ? 16777216 /* Optional */ : 0); + var symbol = createSymbol(flags, text); + symbol.type = getTypeFromBindingElement(e, includePatternInType, reportErrors); + symbol.bindingElement = e; + members.set(symbol.escapedName, symbol); + }); + var result = createAnonymousType(undefined, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, undefined); + result.flags |= 268435456 /* ContainsObjectLiteral */; + result.objectFlags |= objectFlags; + if (includePatternInType) { + result.pattern = pattern; + } + return result; + } + // Return the type implied by an array binding pattern + function getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors) { + var elements = pattern.elements; + var lastElement = ts.lastOrUndefined(elements); + var hasRestElement = !!(lastElement && lastElement.kind === 186 /* BindingElement */ && lastElement.dotDotDotToken); + if (elements.length === 0 || elements.length === 1 && hasRestElement) { + return languageVersion >= 2 /* ES2015 */ ? createIterableType(anyType) : anyArrayType; + } + var elementTypes = ts.map(elements, function (e) { return ts.isOmittedExpression(e) ? anyType : getTypeFromBindingElement(e, includePatternInType, reportErrors); }); + var minLength = ts.findLastIndex(elements, function (e) { return !ts.isOmittedExpression(e) && !hasDefaultValue(e); }, elements.length - (hasRestElement ? 2 : 1)) + 1; + var result = createTupleType(elementTypes, minLength, hasRestElement); + if (includePatternInType) { + result = cloneTypeReference(result); + result.pattern = pattern; + } + return result; + } + // Return the type implied by a binding pattern. This is the type implied purely by the binding pattern itself + // and without regard to its context (i.e. without regard any type annotation or initializer associated with the + // declaration in which the binding pattern is contained). For example, the implied type of [x, y] is [any, any] + // and the implied type of { x, y: z = 1 } is { x: any; y: number; }. The type implied by a binding pattern is + // used as the contextual type of an initializer associated with the binding pattern. Also, for a destructuring + // parameter with no type annotation or initializer, the type implied by the binding pattern becomes the type of + // the parameter. + function getTypeFromBindingPattern(pattern, includePatternInType, reportErrors) { + if (includePatternInType === void 0) { includePatternInType = false; } + if (reportErrors === void 0) { reportErrors = false; } + return pattern.kind === 184 /* ObjectBindingPattern */ + ? getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) + : getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors); + } + // Return the type associated with a variable, parameter, or property declaration. In the simple case this is the type + // specified in a type annotation or inferred from an initializer. However, in the case of a destructuring declaration it + // is a bit more involved. For example: + // + // var [x, s = ""] = [1, "one"]; + // + // Here, the array literal [1, "one"] is contextually typed by the type [any, string], which is the implied type of the + // binding pattern [x, s = ""]. Because the contextual type is a tuple type, the resulting type of [1, "one"] is the + // tuple type [number, string]. Thus, the type inferred for 'x' is number and the type inferred for 's' is string. + function getWidenedTypeForVariableLikeDeclaration(declaration, reportErrors) { + return widenTypeForVariableLikeDeclaration(getTypeForVariableLikeDeclaration(declaration, /*includeOptionality*/ true), declaration, reportErrors); + } + function widenTypeForVariableLikeDeclaration(type, declaration, reportErrors) { + if (type) { + if (reportErrors) { + reportErrorsFromWidening(declaration, type); + } + // always widen a 'unique symbol' type if the type was created for a different declaration. + if (type.flags & 8192 /* UniqueESSymbol */ && (ts.isBindingElement(declaration) || !declaration.type) && type.symbol !== getSymbolOfNode(declaration)) { + type = esSymbolType; + } + return getWidenedType(type); + } + // Rest parameters default to type any[], other parameters default to type any + type = ts.isParameter(declaration) && declaration.dotDotDotToken ? anyArrayType : anyType; + // Report implicit any errors unless this is a private property within an ambient declaration + if (reportErrors) { + if (!declarationBelongsToPrivateAmbientMember(declaration)) { + reportImplicitAny(declaration, type); + } + } + return type; + } + function declarationBelongsToPrivateAmbientMember(declaration) { + var root = ts.getRootDeclaration(declaration); + var memberDeclaration = root.kind === 151 /* Parameter */ ? root.parent : root; + return isPrivateWithinAmbient(memberDeclaration); + } + function tryGetTypeFromEffectiveTypeNode(declaration) { + var typeNode = ts.getEffectiveTypeAnnotationNode(declaration); + if (typeNode) { + return getTypeFromTypeNode(typeNode); + } + } + function getTypeOfVariableOrParameterOrProperty(symbol) { + var links = getSymbolLinks(symbol); + return links.type || (links.type = getTypeOfVariableOrParameterOrPropertyWorker(symbol)); + } + function getTypeOfVariableOrParameterOrPropertyWorker(symbol) { + // Handle prototype property + if (symbol.flags & 4194304 /* Prototype */) { + return getTypeOfPrototypeProperty(symbol); + } + // CommonsJS require and module both have type any. + if (symbol === requireSymbol) { + return anyType; + } + if (symbol.flags & 134217728 /* ModuleExports */) { + var fileSymbol = getSymbolOfNode(ts.getSourceFileOfNode(symbol.valueDeclaration)); + var members = ts.createSymbolTable(); + members.set("exports", fileSymbol); + return createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, undefined, undefined); + } + // Handle catch clause variables + var declaration = symbol.valueDeclaration; + if (ts.isCatchClauseVariableDeclarationOrBindingElement(declaration)) { + return anyType; + } + // Handle export default expressions + if (ts.isSourceFile(declaration)) { + var jsonSourceFile = ts.cast(declaration, ts.isJsonSourceFile); + if (!jsonSourceFile.statements.length) { + return emptyObjectType; + } + var type_1 = getWidenedLiteralType(checkExpression(jsonSourceFile.statements[0].expression)); + if (type_1.flags & 524288 /* Object */) { + return getRegularTypeOfObjectLiteral(type_1); + } + return type_1; + } + if (declaration.kind === 254 /* ExportAssignment */) { + return widenTypeForVariableLikeDeclaration(checkExpressionCached(declaration.expression), declaration); + } + // Handle variable, parameter or property + if (!pushTypeResolution(symbol, 0 /* Type */)) { + return errorType; + } + var type; + if (ts.isInJSFile(declaration) && + (ts.isCallExpression(declaration) || ts.isBinaryExpression(declaration) || ts.isPropertyAccessExpression(declaration) && ts.isBinaryExpression(declaration.parent))) { + type = getWidenedTypeFromAssignmentDeclaration(symbol); + } + else if (ts.isJSDocPropertyLikeTag(declaration) + || ts.isPropertyAccessExpression(declaration) + || ts.isIdentifier(declaration) + || ts.isClassDeclaration(declaration) + || ts.isFunctionDeclaration(declaration) + || (ts.isMethodDeclaration(declaration) && !ts.isObjectLiteralMethod(declaration)) + || ts.isMethodSignature(declaration)) { + // Symbol is property of some kind that is merged with something - should use `getTypeOfFuncClassEnumModule` and not `getTypeOfVariableOrParameterOrProperty` + if (symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 384 /* Enum */ | 512 /* ValueModule */)) { + return getTypeOfFuncClassEnumModule(symbol); + } + type = ts.isBinaryExpression(declaration.parent) ? + getWidenedTypeFromAssignmentDeclaration(symbol) : + tryGetTypeFromEffectiveTypeNode(declaration) || anyType; + } + else if (ts.isPropertyAssignment(declaration)) { + type = tryGetTypeFromEffectiveTypeNode(declaration) || checkPropertyAssignment(declaration); + } + else if (ts.isJsxAttribute(declaration)) { + type = tryGetTypeFromEffectiveTypeNode(declaration) || checkJsxAttribute(declaration); + } + else if (ts.isShorthandPropertyAssignment(declaration)) { + type = tryGetTypeFromEffectiveTypeNode(declaration) || checkExpressionForMutableLocation(declaration.name, 0 /* Normal */); + } + else if (ts.isObjectLiteralMethod(declaration)) { + type = tryGetTypeFromEffectiveTypeNode(declaration) || checkObjectLiteralMethod(declaration, 0 /* Normal */); + } + else if (ts.isParameter(declaration) + || ts.isPropertyDeclaration(declaration) + || ts.isPropertySignature(declaration) + || ts.isVariableDeclaration(declaration) + || ts.isBindingElement(declaration)) { + type = getWidenedTypeForVariableLikeDeclaration(declaration, /*includeOptionality*/ true); + } + // getTypeOfSymbol dispatches some JS merges incorrectly because their symbol flags are not mutually exclusive. + // Re-dispatch based on valueDeclaration.kind instead. + else if (ts.isEnumDeclaration(declaration)) { + type = getTypeOfFuncClassEnumModule(symbol); + } + else if (ts.isEnumMember(declaration)) { + type = getTypeOfEnumMember(symbol); + } + else { + return ts.Debug.fail("Unhandled declaration kind! " + ts.Debug.showSyntaxKind(declaration) + " for " + ts.Debug.showSymbol(symbol)); + } + if (!popTypeResolution()) { + type = reportCircularityError(symbol); + } + return type; + } + function getAnnotatedAccessorTypeNode(accessor) { + if (accessor) { + if (accessor.kind === 158 /* GetAccessor */) { + var getterTypeAnnotation = ts.getEffectiveReturnTypeNode(accessor); + return getterTypeAnnotation; + } + else { + var setterTypeAnnotation = ts.getEffectiveSetAccessorTypeAnnotationNode(accessor); + return setterTypeAnnotation; + } + } + return undefined; + } + function getAnnotatedAccessorType(accessor) { + var node = getAnnotatedAccessorTypeNode(accessor); + return node && getTypeFromTypeNode(node); + } + function getAnnotatedAccessorThisParameter(accessor) { + var parameter = getAccessorThisParameter(accessor); + return parameter && parameter.symbol; + } + function getThisTypeOfDeclaration(declaration) { + return getThisTypeOfSignature(getSignatureFromDeclaration(declaration)); + } + function getTypeOfAccessors(symbol) { + var links = getSymbolLinks(symbol); + return links.type || (links.type = getTypeOfAccessorsWorker(symbol)); + } + function getTypeOfAccessorsWorker(symbol) { + var getter = ts.getDeclarationOfKind(symbol, 158 /* GetAccessor */); + var setter = ts.getDeclarationOfKind(symbol, 159 /* SetAccessor */); + if (getter && ts.isInJSFile(getter)) { + var jsDocType = getTypeForDeclarationFromJSDocComment(getter); + if (jsDocType) { + return jsDocType; + } + } + if (!pushTypeResolution(symbol, 0 /* Type */)) { + return errorType; + } + var type; + // First try to see if the user specified a return type on the get-accessor. + var getterReturnType = getAnnotatedAccessorType(getter); + if (getterReturnType) { + type = getterReturnType; + } + else { + // If the user didn't specify a return type, try to use the set-accessor's parameter type. + var setterParameterType = getAnnotatedAccessorType(setter); + if (setterParameterType) { + type = setterParameterType; + } + else { + // If there are no specified types, try to infer it from the body of the get accessor if it exists. + if (getter && getter.body) { + type = getReturnTypeFromBody(getter); + } + // Otherwise, fall back to 'any'. + else { + if (setter) { + errorOrSuggestion(noImplicitAny, setter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation, symbolToString(symbol)); + } + else { + ts.Debug.assert(!!getter, "there must existed getter as we are current checking either setter or getter in this function"); + errorOrSuggestion(noImplicitAny, getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); + } + type = anyType; + } + } + } + if (!popTypeResolution()) { + type = anyType; + if (noImplicitAny) { + var getter_1 = ts.getDeclarationOfKind(symbol, 158 /* GetAccessor */); + error(getter_1, ts.Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, symbolToString(symbol)); + } + } + return type; + } + function getBaseTypeVariableOfClass(symbol) { + var baseConstructorType = getBaseConstructorTypeOfClass(getDeclaredTypeOfClassOrInterface(symbol)); + return baseConstructorType.flags & 8650752 /* TypeVariable */ ? baseConstructorType : undefined; + } + function getTypeOfFuncClassEnumModule(symbol) { + var links = getSymbolLinks(symbol); + var originalLinks = links; + if (!links.type) { + var jsDeclaration = ts.getDeclarationOfExpando(symbol.valueDeclaration); + if (jsDeclaration) { + var jsSymbol = getSymbolOfNode(jsDeclaration); + if (jsSymbol && (ts.hasEntries(jsSymbol.exports) || ts.hasEntries(jsSymbol.members))) { + symbol = cloneSymbol(symbol); + // note:we overwrite links because we just cloned the symbol + links = symbol; + if (ts.hasEntries(jsSymbol.exports)) { + symbol.exports = symbol.exports || ts.createSymbolTable(); + mergeSymbolTable(symbol.exports, jsSymbol.exports); + } + if (ts.hasEntries(jsSymbol.members)) { + symbol.members = symbol.members || ts.createSymbolTable(); + mergeSymbolTable(symbol.members, jsSymbol.members); + } + } + } + originalLinks.type = links.type = getTypeOfFuncClassEnumModuleWorker(symbol); + } + return links.type; + } + function getTypeOfFuncClassEnumModuleWorker(symbol) { + var declaration = symbol.valueDeclaration; + if (symbol.flags & 1536 /* Module */ && ts.isShorthandAmbientModuleSymbol(symbol)) { + return anyType; + } + else if (declaration.kind === 204 /* BinaryExpression */ || + declaration.kind === 189 /* PropertyAccessExpression */ && declaration.parent.kind === 204 /* BinaryExpression */) { + return getWidenedTypeFromAssignmentDeclaration(symbol); + } + else if (symbol.flags & 512 /* ValueModule */ && declaration && ts.isSourceFile(declaration) && declaration.commonJsModuleIndicator) { + var resolvedModule = resolveExternalModuleSymbol(symbol); + if (resolvedModule !== symbol) { + if (!pushTypeResolution(symbol, 0 /* Type */)) { + return errorType; + } + var exportEquals = getMergedSymbol(symbol.exports.get("export=" /* ExportEquals */)); + var type_2 = getWidenedTypeFromAssignmentDeclaration(exportEquals, exportEquals === resolvedModule ? undefined : resolvedModule); + if (!popTypeResolution()) { + return reportCircularityError(symbol); + } + return type_2; + } + } + var type = createObjectType(16 /* Anonymous */, symbol); + if (symbol.flags & 32 /* Class */) { + var baseTypeVariable = getBaseTypeVariableOfClass(symbol); + return baseTypeVariable ? getIntersectionType([type, baseTypeVariable]) : type; + } + else { + return strictNullChecks && symbol.flags & 16777216 /* Optional */ ? getOptionalType(type) : type; + } + } + function getTypeOfEnumMember(symbol) { + var links = getSymbolLinks(symbol); + return links.type || (links.type = getDeclaredTypeOfEnumMember(symbol)); + } + function getTypeOfAlias(symbol) { + var links = getSymbolLinks(symbol); + if (!links.type) { + var targetSymbol = resolveAlias(symbol); + // It only makes sense to get the type of a value symbol. If the result of resolving + // the alias is not a value, then it has no type. To get the type associated with a + // type symbol, call getDeclaredTypeOfSymbol. + // This check is important because without it, a call to getTypeOfSymbol could end + // up recursively calling getTypeOfAlias, causing a stack overflow. + links.type = targetSymbol.flags & 67220415 /* Value */ + ? getTypeOfSymbol(targetSymbol) + : errorType; + } + return links.type; + } + function getTypeOfInstantiatedSymbol(symbol) { + var links = getSymbolLinks(symbol); + if (!links.type) { + if (!pushTypeResolution(symbol, 0 /* Type */)) { + return links.type = errorType; + } + var type = instantiateType(getTypeOfSymbol(links.target), links.mapper); + if (!popTypeResolution()) { + type = reportCircularityError(symbol); + } + links.type = type; + } + return links.type; + } + function reportCircularityError(symbol) { + // Check if variable has type annotation that circularly references the variable itself + if (ts.getEffectiveTypeAnnotationNode(symbol.valueDeclaration)) { + error(symbol.valueDeclaration, ts.Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_type_annotation, symbolToString(symbol)); + return errorType; + } + // Otherwise variable has initializer that circularly references the variable itself + if (noImplicitAny) { + error(symbol.valueDeclaration, ts.Diagnostics._0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer, symbolToString(symbol)); + } + return anyType; + } + function getTypeOfSymbol(symbol) { + if (ts.getCheckFlags(symbol) & 1 /* Instantiated */) { + return getTypeOfInstantiatedSymbol(symbol); + } + if (ts.getCheckFlags(symbol) & 2048 /* ReverseMapped */) { + return getTypeOfReverseMappedSymbol(symbol); + } + if (symbol.flags & (3 /* Variable */ | 4 /* Property */)) { + return getTypeOfVariableOrParameterOrProperty(symbol); + } + if (symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 384 /* Enum */ | 512 /* ValueModule */)) { + return getTypeOfFuncClassEnumModule(symbol); + } + if (symbol.flags & 8 /* EnumMember */) { + return getTypeOfEnumMember(symbol); + } + if (symbol.flags & 98304 /* Accessor */) { + return getTypeOfAccessors(symbol); + } + if (symbol.flags & 2097152 /* Alias */) { + return getTypeOfAlias(symbol); + } + return errorType; + } + function isReferenceToType(type, target) { + return type !== undefined + && target !== undefined + && (ts.getObjectFlags(type) & 4 /* Reference */) !== 0 + && type.target === target; + } + function getTargetType(type) { + return ts.getObjectFlags(type) & 4 /* Reference */ ? type.target : type; + } + // TODO: GH#18217 If `checkBase` is undefined, we should not call this because this will always return false. + function hasBaseType(type, checkBase) { + return check(type); + function check(type) { + if (ts.getObjectFlags(type) & (3 /* ClassOrInterface */ | 4 /* Reference */)) { + var target = getTargetType(type); + return target === checkBase || ts.some(getBaseTypes(target), check); + } + else if (type.flags & 2097152 /* Intersection */) { + return ts.some(type.types, check); + } + return false; + } + } + // Appends the type parameters given by a list of declarations to a set of type parameters and returns the resulting set. + // The function allocates a new array if the input type parameter set is undefined, but otherwise it modifies the set + // in-place and returns the same array. + function appendTypeParameters(typeParameters, declarations) { + for (var _i = 0, declarations_2 = declarations; _i < declarations_2.length; _i++) { + var declaration = declarations_2[_i]; + typeParameters = ts.appendIfUnique(typeParameters, getDeclaredTypeOfTypeParameter(getSymbolOfNode(declaration))); + } + return typeParameters; + } + // Return the outer type parameters of a node or undefined if the node has no outer type parameters. + function getOuterTypeParameters(node, includeThisTypes) { + while (true) { + node = node.parent; // TODO: GH#18217 Use SourceFile kind check instead + if (!node) { + return undefined; + } + switch (node.kind) { + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 241 /* InterfaceDeclaration */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 155 /* MethodSignature */: + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + case 289 /* JSDocFunctionType */: + case 239 /* FunctionDeclaration */: + case 156 /* MethodDeclaration */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 242 /* TypeAliasDeclaration */: + case 303 /* JSDocTemplateTag */: + case 304 /* JSDocTypedefTag */: + case 297 /* JSDocCallbackTag */: + case 181 /* MappedType */: + case 175 /* ConditionalType */: + var outerTypeParameters = getOuterTypeParameters(node, includeThisTypes); + if (node.kind === 181 /* MappedType */) { + return ts.append(outerTypeParameters, getDeclaredTypeOfTypeParameter(getSymbolOfNode(node.typeParameter))); + } + else if (node.kind === 175 /* ConditionalType */) { + return ts.concatenate(outerTypeParameters, getInferTypeParameters(node)); + } + var outerAndOwnTypeParameters = appendTypeParameters(outerTypeParameters, ts.getEffectiveTypeParameterDeclarations(node)); + var thisType = includeThisTypes && + (node.kind === 240 /* ClassDeclaration */ || node.kind === 209 /* ClassExpression */ || node.kind === 241 /* InterfaceDeclaration */) && + getDeclaredTypeOfClassOrInterface(getSymbolOfNode(node)).thisType; + return thisType ? ts.append(outerAndOwnTypeParameters, thisType) : outerAndOwnTypeParameters; + } + } + } + // The outer type parameters are those defined by enclosing generic classes, methods, or functions. + function getOuterTypeParametersOfClassOrInterface(symbol) { + var declaration = symbol.flags & 32 /* Class */ ? symbol.valueDeclaration : ts.getDeclarationOfKind(symbol, 241 /* InterfaceDeclaration */); + return getOuterTypeParameters(declaration); + } + // The local type parameters are the combined set of type parameters from all declarations of the class, + // interface, or type alias. + function getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) { + var result; + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var node = _a[_i]; + if (node.kind === 241 /* InterfaceDeclaration */ || + node.kind === 240 /* ClassDeclaration */ || + node.kind === 209 /* ClassExpression */ || + ts.isTypeAlias(node)) { + var declaration = node; + result = appendTypeParameters(result, ts.getEffectiveTypeParameterDeclarations(declaration)); + } + } + return result; + } + // The full set of type parameters for a generic class or interface type consists of its outer type parameters plus + // its locally declared type parameters. + function getTypeParametersOfClassOrInterface(symbol) { + return ts.concatenate(getOuterTypeParametersOfClassOrInterface(symbol), getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol)); + } + // A type is a mixin constructor if it has a single construct signature taking no type parameters and a single + // rest parameter of type any[]. + function isMixinConstructorType(type) { + var signatures = getSignaturesOfType(type, 1 /* Construct */); + if (signatures.length === 1) { + var s = signatures[0]; + return !s.typeParameters && s.parameters.length === 1 && s.hasRestParameter && getTypeOfParameter(s.parameters[0]) === anyArrayType; + } + return false; + } + function isConstructorType(type) { + if (isValidBaseType(type) && getSignaturesOfType(type, 1 /* Construct */).length > 0) { + return true; + } + if (type.flags & 8650752 /* TypeVariable */) { + var constraint = getBaseConstraintOfType(type); + return !!constraint && isValidBaseType(constraint) && isMixinConstructorType(constraint); + } + return isJSConstructorType(type); + } + function getBaseTypeNodeOfClass(type) { + return ts.getEffectiveBaseTypeNode(type.symbol.valueDeclaration); + } + function getConstructorsForTypeArguments(type, typeArgumentNodes, location) { + var typeArgCount = ts.length(typeArgumentNodes); + var isJavascript = ts.isInJSFile(location); + return ts.filter(getSignaturesOfType(type, 1 /* Construct */), function (sig) { return (isJavascript || typeArgCount >= getMinTypeArgumentCount(sig.typeParameters)) && typeArgCount <= ts.length(sig.typeParameters); }); + } + function getInstantiatedConstructorsForTypeArguments(type, typeArgumentNodes, location) { + var signatures = getConstructorsForTypeArguments(type, typeArgumentNodes, location); + var typeArguments = ts.map(typeArgumentNodes, getTypeFromTypeNode); + return ts.sameMap(signatures, function (sig) { return ts.some(sig.typeParameters) ? getSignatureInstantiation(sig, typeArguments, ts.isInJSFile(location)) : sig; }); + } + /** + * The base constructor of a class can resolve to + * * undefinedType if the class has no extends clause, + * * unknownType if an error occurred during resolution of the extends expression, + * * nullType if the extends expression is the null value, + * * anyType if the extends expression has type any, or + * * an object type with at least one construct signature. + */ + function getBaseConstructorTypeOfClass(type) { + if (!type.resolvedBaseConstructorType) { + var decl = type.symbol.valueDeclaration; + var extended = ts.getEffectiveBaseTypeNode(decl); + var baseTypeNode = getBaseTypeNodeOfClass(type); + if (!baseTypeNode) { + return type.resolvedBaseConstructorType = undefinedType; + } + if (!pushTypeResolution(type, 1 /* ResolvedBaseConstructorType */)) { + return errorType; + } + var baseConstructorType = checkExpression(baseTypeNode.expression); + if (extended && baseTypeNode !== extended) { + ts.Debug.assert(!extended.typeArguments); // Because this is in a JS file, and baseTypeNode is in an @extends tag + checkExpression(extended.expression); + } + if (baseConstructorType.flags & (524288 /* Object */ | 2097152 /* Intersection */)) { + // Resolving the members of a class requires us to resolve the base class of that class. + // We force resolution here such that we catch circularities now. + resolveStructuredTypeMembers(baseConstructorType); + } + if (!popTypeResolution()) { + error(type.symbol.valueDeclaration, ts.Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_base_expression, symbolToString(type.symbol)); + return type.resolvedBaseConstructorType = errorType; + } + if (!(baseConstructorType.flags & 1 /* Any */) && baseConstructorType !== nullWideningType && !isConstructorType(baseConstructorType)) { + var err = error(baseTypeNode.expression, ts.Diagnostics.Type_0_is_not_a_constructor_function_type, typeToString(baseConstructorType)); + if (baseConstructorType.flags & 262144 /* TypeParameter */) { + var constraint = getConstraintFromTypeParameter(baseConstructorType); + var ctorReturn = unknownType; + if (constraint) { + var ctorSig = getSignaturesOfType(constraint, 1 /* Construct */); + if (ctorSig[0]) { + ctorReturn = getReturnTypeOfSignature(ctorSig[0]); + } + } + addRelatedInfo(err, ts.createDiagnosticForNode(baseConstructorType.symbol.declarations[0], ts.Diagnostics.Did_you_mean_for_0_to_be_constrained_to_type_new_args_Colon_any_1, symbolToString(baseConstructorType.symbol), typeToString(ctorReturn))); + } + return type.resolvedBaseConstructorType = errorType; + } + type.resolvedBaseConstructorType = baseConstructorType; + } + return type.resolvedBaseConstructorType; + } + function getBaseTypes(type) { + if (!type.resolvedBaseTypes) { + if (type.objectFlags & 8 /* Tuple */) { + type.resolvedBaseTypes = [createArrayType(getUnionType(type.typeParameters || ts.emptyArray))]; + } + else if (type.symbol.flags & (32 /* Class */ | 64 /* Interface */)) { + if (type.symbol.flags & 32 /* Class */) { + resolveBaseTypesOfClass(type); + } + if (type.symbol.flags & 64 /* Interface */) { + resolveBaseTypesOfInterface(type); + } + } + else { + ts.Debug.fail("type must be class or interface"); + } + } + return type.resolvedBaseTypes; + } + function resolveBaseTypesOfClass(type) { + type.resolvedBaseTypes = ts.resolvingEmptyArray; + var baseConstructorType = getApparentType(getBaseConstructorTypeOfClass(type)); + if (!(baseConstructorType.flags & (524288 /* Object */ | 2097152 /* Intersection */ | 1 /* Any */))) { + return type.resolvedBaseTypes = ts.emptyArray; + } + var baseTypeNode = getBaseTypeNodeOfClass(type); + var typeArgs = typeArgumentsFromTypeReferenceNode(baseTypeNode); + var baseType; + var originalBaseType = isJSConstructorType(baseConstructorType) ? baseConstructorType : + baseConstructorType.symbol ? getDeclaredTypeOfSymbol(baseConstructorType.symbol) : + undefined; + if (baseConstructorType.symbol && baseConstructorType.symbol.flags & 32 /* Class */ && + areAllOuterTypeParametersApplied(originalBaseType)) { + // When base constructor type is a class with no captured type arguments we know that the constructors all have the same type parameters as the + // class and all return the instance type of the class. There is no need for further checks and we can apply the + // type arguments in the same manner as a type reference to get the same error reporting experience. + baseType = getTypeFromClassOrInterfaceReference(baseTypeNode, baseConstructorType.symbol, typeArgs); + } + else if (baseConstructorType.flags & 1 /* Any */) { + baseType = baseConstructorType; + } + else if (isJSConstructorType(baseConstructorType)) { + baseType = !baseTypeNode.typeArguments && getJSClassType(baseConstructorType.symbol) || anyType; + } + else { + // The class derives from a "class-like" constructor function, check that we have at least one construct signature + // with a matching number of type parameters and use the return type of the first instantiated signature. Elsewhere + // we check that all instantiated signatures return the same type. + var constructors = getInstantiatedConstructorsForTypeArguments(baseConstructorType, baseTypeNode.typeArguments, baseTypeNode); + if (!constructors.length) { + error(baseTypeNode.expression, ts.Diagnostics.No_base_constructor_has_the_specified_number_of_type_arguments); + return type.resolvedBaseTypes = ts.emptyArray; + } + baseType = getReturnTypeOfSignature(constructors[0]); + } + if (baseType === errorType) { + return type.resolvedBaseTypes = ts.emptyArray; + } + if (!isValidBaseType(baseType)) { + error(baseTypeNode.expression, ts.Diagnostics.Base_constructor_return_type_0_is_not_an_object_type_or_intersection_of_object_types_with_statically_known_members, typeToString(baseType)); + return type.resolvedBaseTypes = ts.emptyArray; + } + if (type === baseType || hasBaseType(baseType, type)) { + error(type.symbol.valueDeclaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, /*enclosingDeclaration*/ undefined, 2 /* WriteArrayAsGenericType */)); + return type.resolvedBaseTypes = ts.emptyArray; + } + if (type.resolvedBaseTypes === ts.resolvingEmptyArray) { + // Circular reference, likely through instantiation of default parameters + // (otherwise there'd be an error from hasBaseType) - this is fine, but `.members` should be reset + // as `getIndexedAccessType` via `instantiateType` via `getTypeFromClassOrInterfaceReference` forces a + // partial instantiation of the members without the base types fully resolved + type.members = undefined; + } + return type.resolvedBaseTypes = [baseType]; + } + function areAllOuterTypeParametersApplied(type) { + // An unapplied type parameter has its symbol still the same as the matching argument symbol. + // Since parameters are applied outer-to-inner, only the last outer parameter needs to be checked. + var outerTypeParameters = type.outerTypeParameters; + if (outerTypeParameters) { + var last_1 = outerTypeParameters.length - 1; + var typeArguments = type.typeArguments; + return outerTypeParameters[last_1].symbol !== typeArguments[last_1].symbol; + } + return true; + } + // A valid base type is `any`, any non-generic object type or intersection of non-generic + // object types. + function isValidBaseType(type) { + return !!(type.flags & (524288 /* Object */ | 67108864 /* NonPrimitive */ | 1 /* Any */)) && !isGenericMappedType(type) || + !!(type.flags & 2097152 /* Intersection */) && ts.every(type.types, isValidBaseType); + } + function resolveBaseTypesOfInterface(type) { + type.resolvedBaseTypes = type.resolvedBaseTypes || ts.emptyArray; + for (var _i = 0, _a = type.symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (declaration.kind === 241 /* InterfaceDeclaration */ && ts.getInterfaceBaseTypeNodes(declaration)) { + for (var _b = 0, _c = ts.getInterfaceBaseTypeNodes(declaration); _b < _c.length; _b++) { + var node = _c[_b]; + var baseType = getTypeFromTypeNode(node); + if (baseType !== errorType) { + if (isValidBaseType(baseType)) { + if (type !== baseType && !hasBaseType(baseType, type)) { + if (type.resolvedBaseTypes === ts.emptyArray) { + type.resolvedBaseTypes = [baseType]; + } + else { + type.resolvedBaseTypes.push(baseType); + } + } + else { + error(declaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, /*enclosingDeclaration*/ undefined, 2 /* WriteArrayAsGenericType */)); + } + } + else { + error(node, ts.Diagnostics.An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_members); + } + } + } + } + } + } + /** + * Returns true if the interface given by the symbol is free of "this" references. + * + * Specifically, the result is true if the interface itself contains no references + * to "this" in its body, if all base types are interfaces, + * and if none of the base interfaces have a "this" type. + */ + function isThislessInterface(symbol) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (declaration.kind === 241 /* InterfaceDeclaration */) { + if (declaration.flags & 64 /* ContainsThis */) { + return false; + } + var baseTypeNodes = ts.getInterfaceBaseTypeNodes(declaration); + if (baseTypeNodes) { + for (var _b = 0, baseTypeNodes_1 = baseTypeNodes; _b < baseTypeNodes_1.length; _b++) { + var node = baseTypeNodes_1[_b]; + if (ts.isEntityNameExpression(node.expression)) { + var baseSymbol = resolveEntityName(node.expression, 67897832 /* Type */, /*ignoreErrors*/ true); + if (!baseSymbol || !(baseSymbol.flags & 64 /* Interface */) || getDeclaredTypeOfClassOrInterface(baseSymbol).thisType) { + return false; + } + } + } + } + } + } + return true; + } + function getDeclaredTypeOfClassOrInterface(symbol) { + var links = getSymbolLinks(symbol); + if (!links.declaredType) { + var kind = symbol.flags & 32 /* Class */ ? 1 /* Class */ : 2 /* Interface */; + var type = links.declaredType = createObjectType(kind, symbol); + var outerTypeParameters = getOuterTypeParametersOfClassOrInterface(symbol); + var localTypeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); + // A class or interface is generic if it has type parameters or a "this" type. We always give classes a "this" type + // because it is not feasible to analyze all members to determine if the "this" type escapes the class (in particular, + // property types inferred from initializers and method return types inferred from return statements are very hard + // to exhaustively analyze). We give interfaces a "this" type if we can't definitely determine that they are free of + // "this" references. + if (outerTypeParameters || localTypeParameters || kind === 1 /* Class */ || !isThislessInterface(symbol)) { + type.objectFlags |= 4 /* Reference */; + type.typeParameters = ts.concatenate(outerTypeParameters, localTypeParameters); + type.outerTypeParameters = outerTypeParameters; + type.localTypeParameters = localTypeParameters; + type.instantiations = ts.createMap(); + type.instantiations.set(getTypeListId(type.typeParameters), type); + type.target = type; + type.typeArguments = type.typeParameters; + type.thisType = createType(262144 /* TypeParameter */); + type.thisType.isThisType = true; + type.thisType.symbol = symbol; + type.thisType.constraint = type; + } + } + return links.declaredType; + } + function getDeclaredTypeOfTypeAlias(symbol) { + var links = getSymbolLinks(symbol); + if (!links.declaredType) { + // Note that we use the links object as the target here because the symbol object is used as the unique + // identity for resolution of the 'type' property in SymbolLinks. + if (!pushTypeResolution(symbol, 2 /* DeclaredType */)) { + return errorType; + } + var declaration = ts.find(symbol.declarations, function (d) { + return ts.isJSDocTypeAlias(d) || d.kind === 242 /* TypeAliasDeclaration */; + }); + var typeNode = ts.isJSDocTypeAlias(declaration) ? declaration.typeExpression : declaration.type; + // If typeNode is missing, we will error in checkJSDocTypedefTag. + var type = typeNode ? getTypeFromTypeNode(typeNode) : errorType; + if (popTypeResolution()) { + var typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); + if (typeParameters) { + // Initialize the instantiation cache for generic type aliases. The declared type corresponds to + // an instantiation of the type alias with the type parameters supplied as type arguments. + links.typeParameters = typeParameters; + links.instantiations = ts.createMap(); + links.instantiations.set(getTypeListId(typeParameters), type); + } + } + else { + type = errorType; + error(declaration.name, ts.Diagnostics.Type_alias_0_circularly_references_itself, symbolToString(symbol)); + } + links.declaredType = type; + } + return links.declaredType; + } + function isStringConcatExpression(expr) { + if (expr.kind === 10 /* StringLiteral */) { + return true; + } + else if (expr.kind === 204 /* BinaryExpression */) { + return isStringConcatExpression(expr.left) && isStringConcatExpression(expr.right); + } + return false; + } + function isLiteralEnumMember(member) { + var expr = member.initializer; + if (!expr) { + return !(member.flags & 4194304 /* Ambient */); + } + switch (expr.kind) { + case 10 /* StringLiteral */: + case 8 /* NumericLiteral */: + return true; + case 202 /* PrefixUnaryExpression */: + return expr.operator === 39 /* MinusToken */ && + expr.operand.kind === 8 /* NumericLiteral */; + case 72 /* Identifier */: + return ts.nodeIsMissing(expr) || !!getSymbolOfNode(member.parent).exports.get(expr.escapedText); + case 204 /* BinaryExpression */: + return isStringConcatExpression(expr); + default: + return false; + } + } + function getEnumKind(symbol) { + var links = getSymbolLinks(symbol); + if (links.enumKind !== undefined) { + return links.enumKind; + } + var hasNonLiteralMember = false; + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (declaration.kind === 243 /* EnumDeclaration */) { + for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { + var member = _c[_b]; + if (member.initializer && member.initializer.kind === 10 /* StringLiteral */) { + return links.enumKind = 1 /* Literal */; + } + if (!isLiteralEnumMember(member)) { + hasNonLiteralMember = true; + } + } + } + } + return links.enumKind = hasNonLiteralMember ? 0 /* Numeric */ : 1 /* Literal */; + } + function getBaseTypeOfEnumLiteralType(type) { + return type.flags & 1024 /* EnumLiteral */ && !(type.flags & 1048576 /* Union */) ? getDeclaredTypeOfSymbol(getParentOfSymbol(type.symbol)) : type; + } + function getDeclaredTypeOfEnum(symbol) { + var links = getSymbolLinks(symbol); + if (links.declaredType) { + return links.declaredType; + } + if (getEnumKind(symbol) === 1 /* Literal */) { + enumCount++; + var memberTypeList = []; + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (declaration.kind === 243 /* EnumDeclaration */) { + for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { + var member = _c[_b]; + var memberType = getFreshTypeOfLiteralType(getLiteralType(getEnumMemberValue(member), enumCount, getSymbolOfNode(member))); // TODO: GH#18217 + getSymbolLinks(getSymbolOfNode(member)).declaredType = memberType; + memberTypeList.push(getRegularTypeOfLiteralType(memberType)); + } + } + } + if (memberTypeList.length) { + var enumType_1 = getUnionType(memberTypeList, 1 /* Literal */, symbol, /*aliasTypeArguments*/ undefined); + if (enumType_1.flags & 1048576 /* Union */) { + enumType_1.flags |= 1024 /* EnumLiteral */; + enumType_1.symbol = symbol; + } + return links.declaredType = enumType_1; + } + } + var enumType = createType(32 /* Enum */); + enumType.symbol = symbol; + return links.declaredType = enumType; + } + function getDeclaredTypeOfEnumMember(symbol) { + var links = getSymbolLinks(symbol); + if (!links.declaredType) { + var enumType = getDeclaredTypeOfEnum(getParentOfSymbol(symbol)); + if (!links.declaredType) { + links.declaredType = enumType; + } + } + return links.declaredType; + } + function getDeclaredTypeOfTypeParameter(symbol) { + var links = getSymbolLinks(symbol); + if (!links.declaredType) { + var type = createType(262144 /* TypeParameter */); + type.symbol = symbol; + links.declaredType = type; + } + return links.declaredType; + } + function getDeclaredTypeOfAlias(symbol) { + var links = getSymbolLinks(symbol); + if (!links.declaredType) { + links.declaredType = getDeclaredTypeOfSymbol(resolveAlias(symbol)); + } + return links.declaredType; + } + function getDeclaredTypeOfSymbol(symbol) { + return tryGetDeclaredTypeOfSymbol(symbol) || errorType; + } + function tryGetDeclaredTypeOfSymbol(symbol) { + if (symbol.flags & (32 /* Class */ | 64 /* Interface */)) { + return getDeclaredTypeOfClassOrInterface(symbol); + } + if (symbol.flags & 524288 /* TypeAlias */) { + return getDeclaredTypeOfTypeAlias(symbol); + } + if (symbol.flags & 262144 /* TypeParameter */) { + return getDeclaredTypeOfTypeParameter(symbol); + } + if (symbol.flags & 384 /* Enum */) { + return getDeclaredTypeOfEnum(symbol); + } + if (symbol.flags & 8 /* EnumMember */) { + return getDeclaredTypeOfEnumMember(symbol); + } + if (symbol.flags & 2097152 /* Alias */) { + return getDeclaredTypeOfAlias(symbol); + } + return undefined; + } + /** + * A type is free of this references if it's the any, string, number, boolean, symbol, or void keyword, a string + * literal type, an array with an element type that is free of this references, or a type reference that is + * free of this references. + */ + function isThislessType(node) { + switch (node.kind) { + case 120 /* AnyKeyword */: + case 143 /* UnknownKeyword */: + case 138 /* StringKeyword */: + case 135 /* NumberKeyword */: + case 146 /* BigIntKeyword */: + case 123 /* BooleanKeyword */: + case 139 /* SymbolKeyword */: + case 136 /* ObjectKeyword */: + case 106 /* VoidKeyword */: + case 141 /* UndefinedKeyword */: + case 96 /* NullKeyword */: + case 132 /* NeverKeyword */: + case 182 /* LiteralType */: + return true; + case 169 /* ArrayType */: + return isThislessType(node.elementType); + case 164 /* TypeReference */: + return !node.typeArguments || node.typeArguments.every(isThislessType); + } + return false; + } + /** A type parameter is thisless if its contraint is thisless, or if it has no constraint. */ + function isThislessTypeParameter(node) { + var constraint = ts.getEffectiveConstraintOfTypeParameter(node); + return !constraint || isThislessType(constraint); + } + /** + * A variable-like declaration is free of this references if it has a type annotation + * that is thisless, or if it has no type annotation and no initializer (and is thus of type any). + */ + function isThislessVariableLikeDeclaration(node) { + var typeNode = ts.getEffectiveTypeAnnotationNode(node); + return typeNode ? isThislessType(typeNode) : !ts.hasInitializer(node); + } + /** + * A function-like declaration is considered free of `this` references if it has a return type + * annotation that is free of this references and if each parameter is thisless and if + * each type parameter (if present) is thisless. + */ + function isThislessFunctionLikeDeclaration(node) { + var returnType = ts.getEffectiveReturnTypeNode(node); + var typeParameters = ts.getEffectiveTypeParameterDeclarations(node); + return (node.kind === 157 /* Constructor */ || (!!returnType && isThislessType(returnType))) && + node.parameters.every(isThislessVariableLikeDeclaration) && + typeParameters.every(isThislessTypeParameter); + } + /** + * Returns true if the class or interface member given by the symbol is free of "this" references. The + * function may return false for symbols that are actually free of "this" references because it is not + * feasible to perform a complete analysis in all cases. In particular, property members with types + * inferred from their initializers and function members with inferred return types are conservatively + * assumed not to be free of "this" references. + */ + function isThisless(symbol) { + if (symbol.declarations && symbol.declarations.length === 1) { + var declaration = symbol.declarations[0]; + if (declaration) { + switch (declaration.kind) { + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + return isThislessVariableLikeDeclaration(declaration); + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 157 /* Constructor */: + return isThislessFunctionLikeDeclaration(declaration); + } + } + } + return false; + } + // The mappingThisOnly flag indicates that the only type parameter being mapped is "this". When the flag is true, + // we check symbols to see if we can quickly conclude they are free of "this" references, thus needing no instantiation. + function createInstantiatedSymbolTable(symbols, mapper, mappingThisOnly) { + var result = ts.createSymbolTable(); + for (var _i = 0, symbols_2 = symbols; _i < symbols_2.length; _i++) { + var symbol = symbols_2[_i]; + result.set(symbol.escapedName, mappingThisOnly && isThisless(symbol) ? symbol : instantiateSymbol(symbol, mapper)); + } + return result; + } + function addInheritedMembers(symbols, baseSymbols) { + for (var _i = 0, baseSymbols_1 = baseSymbols; _i < baseSymbols_1.length; _i++) { + var s = baseSymbols_1[_i]; + if (!symbols.has(s.escapedName)) { + symbols.set(s.escapedName, s); + } + } + } + function resolveDeclaredMembers(type) { + if (!type.declaredProperties) { + var symbol = type.symbol; + var members = getMembersOfSymbol(symbol); + type.declaredProperties = getNamedMembers(members); + // Start with signatures at empty array in case of recursive types + type.declaredCallSignatures = ts.emptyArray; + type.declaredConstructSignatures = ts.emptyArray; + type.declaredCallSignatures = getSignaturesOfSymbol(members.get("__call" /* Call */)); + type.declaredConstructSignatures = getSignaturesOfSymbol(members.get("__new" /* New */)); + type.declaredStringIndexInfo = getIndexInfoOfSymbol(symbol, 0 /* String */); + type.declaredNumberIndexInfo = getIndexInfoOfSymbol(symbol, 1 /* Number */); + } + return type; + } + /** + * Indicates whether a type can be used as a late-bound name. + */ + function isTypeUsableAsLateBoundName(type) { + return !!(type.flags & 8576 /* StringOrNumberLiteralOrUnique */); + } + /** + * Indicates whether a declaration name is definitely late-bindable. + * A declaration name is only late-bindable if: + * - It is a `ComputedPropertyName`. + * - Its expression is an `Identifier` or either a `PropertyAccessExpression` an + * `ElementAccessExpression` consisting only of these same three types of nodes. + * - The type of its expression is a string or numeric literal type, or is a `unique symbol` type. + */ + function isLateBindableName(node) { + return ts.isComputedPropertyName(node) + && ts.isEntityNameExpression(node.expression) + && isTypeUsableAsLateBoundName(checkComputedPropertyName(node)); + } + function isLateBoundName(name) { + return name.charCodeAt(0) === 95 /* _ */ && + name.charCodeAt(1) === 95 /* _ */ && + name.charCodeAt(2) === 64 /* at */; + } + /** + * Indicates whether a declaration has a late-bindable dynamic name. + */ + function hasLateBindableName(node) { + var name = ts.getNameOfDeclaration(node); + return !!name && isLateBindableName(name); + } + /** + * Indicates whether a declaration has a dynamic name that cannot be late-bound. + */ + function hasNonBindableDynamicName(node) { + return ts.hasDynamicName(node) && !hasLateBindableName(node); + } + /** + * Indicates whether a declaration name is a dynamic name that cannot be late-bound. + */ + function isNonBindableDynamicName(node) { + return ts.isDynamicName(node) && !isLateBindableName(node); + } + /** + * Gets the symbolic name for a late-bound member from its type. + */ + function getLateBoundNameFromType(type) { + if (type.flags & 8192 /* UniqueESSymbol */) { + return "__@" + type.symbol.escapedName + "@" + getSymbolId(type.symbol); + } + if (type.flags & (128 /* StringLiteral */ | 256 /* NumberLiteral */)) { + return ts.escapeLeadingUnderscores("" + type.value); + } + return ts.Debug.fail(); + } + /** + * Adds a declaration to a late-bound dynamic member. This performs the same function for + * late-bound members that `addDeclarationToSymbol` in binder.ts performs for early-bound + * members. + */ + function addDeclarationToLateBoundSymbol(symbol, member, symbolFlags) { + ts.Debug.assert(!!(ts.getCheckFlags(symbol) & 1024 /* Late */), "Expected a late-bound symbol."); + symbol.flags |= symbolFlags; + getSymbolLinks(member.symbol).lateSymbol = symbol; + if (!symbol.declarations) { + symbol.declarations = [member]; + } + else { + symbol.declarations.push(member); + } + if (symbolFlags & 67220415 /* Value */) { + if (!symbol.valueDeclaration || symbol.valueDeclaration.kind !== member.kind) { + symbol.valueDeclaration = member; + } + } + } + /** + * Performs late-binding of a dynamic member. This performs the same function for + * late-bound members that `declareSymbol` in binder.ts performs for early-bound + * members. + * + * If a symbol is a dynamic name from a computed property, we perform an additional "late" + * binding phase to attempt to resolve the name for the symbol from the type of the computed + * property's expression. If the type of the expression is a string-literal, numeric-literal, + * or unique symbol type, we can use that type as the name of the symbol. + * + * For example, given: + * + * const x = Symbol(); + * + * interface I { + * [x]: number; + * } + * + * The binder gives the property `[x]: number` a special symbol with the name "__computed". + * In the late-binding phase we can type-check the expression `x` and see that it has a + * unique symbol type which we can then use as the name of the member. This allows users + * to define custom symbols that can be used in the members of an object type. + * + * @param parent The containing symbol for the member. + * @param earlySymbols The early-bound symbols of the parent. + * @param lateSymbols The late-bound symbols of the parent. + * @param decl The member to bind. + */ + function lateBindMember(parent, earlySymbols, lateSymbols, decl) { + ts.Debug.assert(!!decl.symbol, "The member is expected to have a symbol."); + var links = getNodeLinks(decl); + if (!links.resolvedSymbol) { + // In the event we attempt to resolve the late-bound name of this member recursively, + // fall back to the early-bound name of this member. + links.resolvedSymbol = decl.symbol; + var type = checkComputedPropertyName(decl.name); + if (isTypeUsableAsLateBoundName(type)) { + var memberName = getLateBoundNameFromType(type); + var symbolFlags = decl.symbol.flags; + // Get or add a late-bound symbol for the member. This allows us to merge late-bound accessor declarations. + var lateSymbol = lateSymbols.get(memberName); + if (!lateSymbol) + lateSymbols.set(memberName, lateSymbol = createSymbol(0 /* None */, memberName, 1024 /* Late */)); + // Report an error if a late-bound member has the same name as an early-bound member, + // or if we have another early-bound symbol declaration with the same name and + // conflicting flags. + var earlySymbol = earlySymbols && earlySymbols.get(memberName); + if (lateSymbol.flags & getExcludedSymbolFlags(symbolFlags) || earlySymbol) { + // If we have an existing early-bound member, combine its declarations so that we can + // report an error at each declaration. + var declarations = earlySymbol ? ts.concatenate(earlySymbol.declarations, lateSymbol.declarations) : lateSymbol.declarations; + var name_2 = ts.declarationNameToString(decl.name); + ts.forEach(declarations, function (declaration) { return error(ts.getNameOfDeclaration(declaration) || declaration, ts.Diagnostics.Duplicate_declaration_0, name_2); }); + error(decl.name || decl, ts.Diagnostics.Duplicate_declaration_0, name_2); + lateSymbol = createSymbol(0 /* None */, memberName, 1024 /* Late */); + } + lateSymbol.nameType = type; + addDeclarationToLateBoundSymbol(lateSymbol, decl, symbolFlags); + if (lateSymbol.parent) { + ts.Debug.assert(lateSymbol.parent === parent, "Existing symbol parent should match new one"); + } + else { + lateSymbol.parent = parent; + } + return links.resolvedSymbol = lateSymbol; + } + } + return links.resolvedSymbol; + } + function getResolvedMembersOrExportsOfSymbol(symbol, resolutionKind) { + var links = getSymbolLinks(symbol); + if (!links[resolutionKind]) { + var isStatic = resolutionKind === "resolvedExports" /* resolvedExports */; + var earlySymbols = !isStatic ? symbol.members : + symbol.flags & 1536 /* Module */ ? getExportsOfModuleWorker(symbol) : + symbol.exports; + // In the event we recursively resolve the members/exports of the symbol, we + // set the initial value of resolvedMembers/resolvedExports to the early-bound + // members/exports of the symbol. + links[resolutionKind] = earlySymbols || emptySymbols; + // fill in any as-yet-unresolved late-bound members. + var lateSymbols = ts.createSymbolTable(); + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + var members = ts.getMembersOfDeclaration(decl); + if (members) { + for (var _b = 0, members_4 = members; _b < members_4.length; _b++) { + var member = members_4[_b]; + if (isStatic === ts.hasStaticModifier(member) && hasLateBindableName(member)) { + lateBindMember(symbol, earlySymbols, lateSymbols, member); + } + } + } + } + links[resolutionKind] = combineSymbolTables(earlySymbols, lateSymbols) || emptySymbols; + } + return links[resolutionKind]; + } + /** + * Gets a SymbolTable containing both the early- and late-bound members of a symbol. + * + * For a description of late-binding, see `lateBindMember`. + */ + function getMembersOfSymbol(symbol) { + return symbol.flags & 6240 /* LateBindingContainer */ + ? getResolvedMembersOrExportsOfSymbol(symbol, "resolvedMembers" /* resolvedMembers */) + : symbol.members || emptySymbols; + } + /** + * If a symbol is the dynamic name of the member of an object type, get the late-bound + * symbol of the member. + * + * For a description of late-binding, see `lateBindMember`. + */ + function getLateBoundSymbol(symbol) { + if (symbol.flags & 106500 /* ClassMember */ && symbol.escapedName === "__computed" /* Computed */) { + var links = getSymbolLinks(symbol); + if (!links.lateSymbol && ts.some(symbol.declarations, hasLateBindableName)) { + // force late binding of members/exports. This will set the late-bound symbol + if (ts.some(symbol.declarations, ts.hasStaticModifier)) { + getExportsOfSymbol(symbol.parent); + } + else { + getMembersOfSymbol(symbol.parent); + } + } + return links.lateSymbol || (links.lateSymbol = symbol); + } + return symbol; + } + function getTypeWithThisArgument(type, thisArgument, needApparentType) { + if (ts.getObjectFlags(type) & 4 /* Reference */) { + var target = type.target; + var typeArguments = type.typeArguments; + if (ts.length(target.typeParameters) === ts.length(typeArguments)) { + var ref = createTypeReference(target, ts.concatenate(typeArguments, [thisArgument || target.thisType])); + return needApparentType ? getApparentType(ref) : ref; + } + } + else if (type.flags & 2097152 /* Intersection */) { + return getIntersectionType(ts.map(type.types, function (t) { return getTypeWithThisArgument(t, thisArgument, needApparentType); })); + } + return needApparentType ? getApparentType(type) : type; + } + function resolveObjectTypeMembers(type, source, typeParameters, typeArguments) { + var mapper; + var members; + var callSignatures; + var constructSignatures; + var stringIndexInfo; + var numberIndexInfo; + if (ts.rangeEquals(typeParameters, typeArguments, 0, typeParameters.length)) { + mapper = identityMapper; + members = source.symbol ? getMembersOfSymbol(source.symbol) : ts.createSymbolTable(source.declaredProperties); + callSignatures = source.declaredCallSignatures; + constructSignatures = source.declaredConstructSignatures; + stringIndexInfo = source.declaredStringIndexInfo; + numberIndexInfo = source.declaredNumberIndexInfo; + } + else { + mapper = createTypeMapper(typeParameters, typeArguments); + members = createInstantiatedSymbolTable(source.declaredProperties, mapper, /*mappingThisOnly*/ typeParameters.length === 1); + callSignatures = instantiateSignatures(source.declaredCallSignatures, mapper); + constructSignatures = instantiateSignatures(source.declaredConstructSignatures, mapper); + stringIndexInfo = instantiateIndexInfo(source.declaredStringIndexInfo, mapper); + numberIndexInfo = instantiateIndexInfo(source.declaredNumberIndexInfo, mapper); + } + var baseTypes = getBaseTypes(source); + if (baseTypes.length) { + if (source.symbol && members === getMembersOfSymbol(source.symbol)) { + members = ts.createSymbolTable(source.declaredProperties); + } + setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + var thisArgument = ts.lastOrUndefined(typeArguments); + for (var _i = 0, baseTypes_1 = baseTypes; _i < baseTypes_1.length; _i++) { + var baseType = baseTypes_1[_i]; + var instantiatedBaseType = thisArgument ? getTypeWithThisArgument(instantiateType(baseType, mapper), thisArgument) : baseType; + addInheritedMembers(members, getPropertiesOfType(instantiatedBaseType)); + callSignatures = ts.concatenate(callSignatures, getSignaturesOfType(instantiatedBaseType, 0 /* Call */)); + constructSignatures = ts.concatenate(constructSignatures, getSignaturesOfType(instantiatedBaseType, 1 /* Construct */)); + if (!stringIndexInfo) { + stringIndexInfo = instantiatedBaseType === anyType ? + createIndexInfo(anyType, /*isReadonly*/ false) : + getIndexInfoOfType(instantiatedBaseType, 0 /* String */); + } + numberIndexInfo = numberIndexInfo || getIndexInfoOfType(instantiatedBaseType, 1 /* Number */); + } + } + setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + } + function resolveClassOrInterfaceMembers(type) { + resolveObjectTypeMembers(type, resolveDeclaredMembers(type), ts.emptyArray, ts.emptyArray); + } + function resolveTypeReferenceMembers(type) { + var source = resolveDeclaredMembers(type.target); + var typeParameters = ts.concatenate(source.typeParameters, [source.thisType]); + var typeArguments = type.typeArguments && type.typeArguments.length === typeParameters.length ? + type.typeArguments : ts.concatenate(type.typeArguments, [type]); + resolveObjectTypeMembers(type, source, typeParameters, typeArguments); + } + function createSignature(declaration, typeParameters, thisParameter, parameters, resolvedReturnType, resolvedTypePredicate, minArgumentCount, hasRestParameter, hasLiteralTypes) { + var sig = new Signature(checker); + sig.declaration = declaration; + sig.typeParameters = typeParameters; + sig.parameters = parameters; + sig.thisParameter = thisParameter; + sig.resolvedReturnType = resolvedReturnType; + sig.resolvedTypePredicate = resolvedTypePredicate; + sig.minArgumentCount = minArgumentCount; + sig.hasRestParameter = hasRestParameter; + sig.hasLiteralTypes = hasLiteralTypes; + sig.target = undefined; + sig.mapper = undefined; + return sig; + } + function cloneSignature(sig) { + return createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, /*resolvedReturnType*/ undefined, + /*resolvedTypePredicate*/ undefined, sig.minArgumentCount, sig.hasRestParameter, sig.hasLiteralTypes); + } + function getExpandedParameters(sig) { + if (sig.hasRestParameter) { + var restIndex_1 = sig.parameters.length - 1; + var restParameter = sig.parameters[restIndex_1]; + var restType = getTypeOfSymbol(restParameter); + if (isTupleType(restType)) { + var elementTypes = restType.typeArguments || ts.emptyArray; + var minLength_1 = restType.target.minLength; + var tupleRestIndex_1 = restType.target.hasRestElement ? elementTypes.length - 1 : -1; + var restParams = ts.map(elementTypes, function (t, i) { + var name = getParameterNameAtPosition(sig, restIndex_1 + i); + var checkFlags = i === tupleRestIndex_1 ? 8192 /* RestParameter */ : + i >= minLength_1 ? 4096 /* OptionalParameter */ : 0; + var symbol = createSymbol(1 /* FunctionScopedVariable */, name, checkFlags); + symbol.type = i === tupleRestIndex_1 ? createArrayType(t) : t; + return symbol; + }); + return ts.concatenate(sig.parameters.slice(0, restIndex_1), restParams); + } + } + return sig.parameters; + } + function getDefaultConstructSignatures(classType) { + var baseConstructorType = getBaseConstructorTypeOfClass(classType); + var baseSignatures = getSignaturesOfType(baseConstructorType, 1 /* Construct */); + if (baseSignatures.length === 0) { + return [createSignature(undefined, classType.localTypeParameters, undefined, ts.emptyArray, classType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false)]; // TODO: GH#18217 + } + var baseTypeNode = getBaseTypeNodeOfClass(classType); + var isJavaScript = ts.isInJSFile(baseTypeNode); + var typeArguments = typeArgumentsFromTypeReferenceNode(baseTypeNode); + var typeArgCount = ts.length(typeArguments); + var result = []; + for (var _i = 0, baseSignatures_1 = baseSignatures; _i < baseSignatures_1.length; _i++) { + var baseSig = baseSignatures_1[_i]; + var minTypeArgumentCount = getMinTypeArgumentCount(baseSig.typeParameters); + var typeParamCount = ts.length(baseSig.typeParameters); + if (isJavaScript || typeArgCount >= minTypeArgumentCount && typeArgCount <= typeParamCount) { + var sig = typeParamCount ? createSignatureInstantiation(baseSig, fillMissingTypeArguments(typeArguments, baseSig.typeParameters, minTypeArgumentCount, isJavaScript)) : cloneSignature(baseSig); + sig.typeParameters = classType.localTypeParameters; + sig.resolvedReturnType = classType; + result.push(sig); + } + } + return result; + } + function findMatchingSignature(signatureList, signature, partialMatch, ignoreThisTypes, ignoreReturnTypes) { + for (var _i = 0, signatureList_1 = signatureList; _i < signatureList_1.length; _i++) { + var s = signatureList_1[_i]; + if (compareSignaturesIdentical(s, signature, partialMatch, ignoreThisTypes, ignoreReturnTypes, partialMatch ? compareTypesSubtypeOf : compareTypesIdentical)) { + return s; + } + } + } + function findMatchingSignatures(signatureLists, signature, listIndex) { + if (signature.typeParameters) { + // We require an exact match for generic signatures, so we only return signatures from the first + // signature list and only if they have exact matches in the other signature lists. + if (listIndex > 0) { + return undefined; + } + for (var i = 1; i < signatureLists.length; i++) { + if (!findMatchingSignature(signatureLists[i], signature, /*partialMatch*/ false, /*ignoreThisTypes*/ false, /*ignoreReturnTypes*/ false)) { + return undefined; + } + } + return [signature]; + } + var result; + for (var i = 0; i < signatureLists.length; i++) { + // Allow matching non-generic signatures to have excess parameters and different return types + var match = i === listIndex ? signature : findMatchingSignature(signatureLists[i], signature, /*partialMatch*/ true, /*ignoreThisTypes*/ true, /*ignoreReturnTypes*/ true); + if (!match) { + return undefined; + } + result = ts.appendIfUnique(result, match); + } + return result; + } + // The signatures of a union type are those signatures that are present in each of the constituent types. + // Generic signatures must match exactly, but non-generic signatures are allowed to have extra optional + // parameters and may differ in return types. When signatures differ in return types, the resulting return + // type is the union of the constituent return types. + function getUnionSignatures(signatureLists) { + var result; + for (var i = 0; i < signatureLists.length; i++) { + for (var _i = 0, _a = signatureLists[i]; _i < _a.length; _i++) { + var signature = _a[_i]; + // Only process signatures with parameter lists that aren't already in the result list + if (!result || !findMatchingSignature(result, signature, /*partialMatch*/ false, /*ignoreThisTypes*/ true, /*ignoreReturnTypes*/ true)) { + var unionSignatures = findMatchingSignatures(signatureLists, signature, i); + if (unionSignatures) { + var s = signature; + // Union the result types when more than one signature matches + if (unionSignatures.length > 1) { + var thisParameter = signature.thisParameter; + if (ts.forEach(unionSignatures, function (sig) { return sig.thisParameter; })) { + // TODO: GH#18217 We tested that *some* has thisParameter and now act as if *all* do + var thisType = getUnionType(ts.map(unionSignatures, function (sig) { return sig.thisParameter ? getTypeOfSymbol(sig.thisParameter) : anyType; }), 2 /* Subtype */); + thisParameter = createSymbolWithType(signature.thisParameter, thisType); + } + s = cloneSignature(signature); + s.thisParameter = thisParameter; + s.unionSignatures = unionSignatures; + } + (result || (result = [])).push(s); + } + } + } + } + return result || ts.emptyArray; + } + function getUnionIndexInfo(types, kind) { + var indexTypes = []; + var isAnyReadonly = false; + for (var _i = 0, types_2 = types; _i < types_2.length; _i++) { + var type = types_2[_i]; + var indexInfo = getIndexInfoOfType(type, kind); + if (!indexInfo) { + return undefined; + } + indexTypes.push(indexInfo.type); + isAnyReadonly = isAnyReadonly || indexInfo.isReadonly; + } + return createIndexInfo(getUnionType(indexTypes, 2 /* Subtype */), isAnyReadonly); + } + function resolveUnionTypeMembers(type) { + // The members and properties collections are empty for union types. To get all properties of a union + // type use getPropertiesOfType (only the language service uses this). + var callSignatures = getUnionSignatures(ts.map(type.types, function (t) { return getSignaturesOfType(t, 0 /* Call */); })); + var constructSignatures = getUnionSignatures(ts.map(type.types, function (t) { return getSignaturesOfType(t, 1 /* Construct */); })); + var stringIndexInfo = getUnionIndexInfo(type.types, 0 /* String */); + var numberIndexInfo = getUnionIndexInfo(type.types, 1 /* Number */); + setStructuredTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + } + function intersectTypes(type1, type2) { + return !type1 ? type2 : !type2 ? type1 : getIntersectionType([type1, type2]); + } + function intersectIndexInfos(info1, info2) { + return !info1 ? info2 : !info2 ? info1 : createIndexInfo(getIntersectionType([info1.type, info2.type]), info1.isReadonly && info2.isReadonly); + } + function unionSpreadIndexInfos(info1, info2) { + return info1 && info2 && createIndexInfo(getUnionType([info1.type, info2.type]), info1.isReadonly || info2.isReadonly); + } + function includeMixinType(type, types, index) { + var mixedTypes = []; + for (var i = 0; i < types.length; i++) { + if (i === index) { + mixedTypes.push(type); + } + else if (isMixinConstructorType(types[i])) { + mixedTypes.push(getReturnTypeOfSignature(getSignaturesOfType(types[i], 1 /* Construct */)[0])); + } + } + return getIntersectionType(mixedTypes); + } + function resolveIntersectionTypeMembers(type) { + // The members and properties collections are empty for intersection types. To get all properties of an + // intersection type use getPropertiesOfType (only the language service uses this). + var callSignatures = ts.emptyArray; + var constructSignatures = ts.emptyArray; + var stringIndexInfo; + var numberIndexInfo; + var types = type.types; + var mixinCount = ts.countWhere(types, isMixinConstructorType); + var _loop_5 = function (i) { + var t = type.types[i]; + // When an intersection type contains mixin constructor types, the construct signatures from + // those types are discarded and their return types are mixed into the return types of all + // other construct signatures in the intersection type. For example, the intersection type + // '{ new(...args: any[]) => A } & { new(s: string) => B }' has a single construct signature + // 'new(s: string) => A & B'. + if (mixinCount === 0 || mixinCount === types.length && i === 0 || !isMixinConstructorType(t)) { + var signatures = getSignaturesOfType(t, 1 /* Construct */); + if (signatures.length && mixinCount > 0) { + signatures = ts.map(signatures, function (s) { + var clone = cloneSignature(s); + clone.resolvedReturnType = includeMixinType(getReturnTypeOfSignature(s), types, i); + return clone; + }); + } + constructSignatures = ts.concatenate(constructSignatures, signatures); + } + callSignatures = ts.concatenate(callSignatures, getSignaturesOfType(t, 0 /* Call */)); + stringIndexInfo = intersectIndexInfos(stringIndexInfo, getIndexInfoOfType(t, 0 /* String */)); + numberIndexInfo = intersectIndexInfos(numberIndexInfo, getIndexInfoOfType(t, 1 /* Number */)); + }; + for (var i = 0; i < types.length; i++) { + _loop_5(i); + } + setStructuredTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + } + /** + * Converts an AnonymousType to a ResolvedType. + */ + function resolveAnonymousTypeMembers(type) { + var symbol = type.symbol; + if (type.target) { + setStructuredTypeMembers(type, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + var members = createInstantiatedSymbolTable(getPropertiesOfObjectType(type.target), type.mapper, /*mappingThisOnly*/ false); + var callSignatures = instantiateSignatures(getSignaturesOfType(type.target, 0 /* Call */), type.mapper); + var constructSignatures = instantiateSignatures(getSignaturesOfType(type.target, 1 /* Construct */), type.mapper); + var stringIndexInfo = instantiateIndexInfo(getIndexInfoOfType(type.target, 0 /* String */), type.mapper); + var numberIndexInfo = instantiateIndexInfo(getIndexInfoOfType(type.target, 1 /* Number */), type.mapper); + setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + } + else if (symbol.flags & 2048 /* TypeLiteral */) { + setStructuredTypeMembers(type, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + var members = getMembersOfSymbol(symbol); + var callSignatures = getSignaturesOfSymbol(members.get("__call" /* Call */)); + var constructSignatures = getSignaturesOfSymbol(members.get("__new" /* New */)); + var stringIndexInfo = getIndexInfoOfSymbol(symbol, 0 /* String */); + var numberIndexInfo = getIndexInfoOfSymbol(symbol, 1 /* Number */); + setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + } + else { + // Combinations of function, class, enum and module + var members = emptySymbols; + var stringIndexInfo = void 0; + if (symbol.exports) { + members = getExportsOfSymbol(symbol); + } + setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, undefined, undefined); + if (symbol.flags & 32 /* Class */) { + var classType = getDeclaredTypeOfClassOrInterface(symbol); + var baseConstructorType = getBaseConstructorTypeOfClass(classType); + if (baseConstructorType.flags & (524288 /* Object */ | 2097152 /* Intersection */ | 8650752 /* TypeVariable */)) { + members = ts.createSymbolTable(getNamedMembers(members)); + addInheritedMembers(members, getPropertiesOfType(baseConstructorType)); + } + else if (baseConstructorType === anyType) { + stringIndexInfo = createIndexInfo(anyType, /*isReadonly*/ false); + } + } + var numberIndexInfo = symbol.flags & 384 /* Enum */ ? enumNumberIndexInfo : undefined; + setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); + // We resolve the members before computing the signatures because a signature may use + // typeof with a qualified name expression that circularly references the type we are + // in the process of resolving (see issue #6072). The temporarily empty signature list + // will never be observed because a qualified name can't reference signatures. + if (symbol.flags & (16 /* Function */ | 8192 /* Method */)) { + type.callSignatures = getSignaturesOfSymbol(symbol); + type.constructSignatures = ts.filter(type.callSignatures, function (sig) { return isJSConstructor(sig.declaration); }); + } + // And likewise for construct signatures for classes + if (symbol.flags & 32 /* Class */) { + var classType = getDeclaredTypeOfClassOrInterface(symbol); + var constructSignatures = getSignaturesOfSymbol(symbol.members.get("__constructor" /* Constructor */)); + if (!constructSignatures.length) { + constructSignatures = getDefaultConstructSignatures(classType); + } + type.constructSignatures = constructSignatures; + } + } + } + function resolveReverseMappedTypeMembers(type) { + var indexInfo = getIndexInfoOfType(type.source, 0 /* String */); + var modifiers = getMappedTypeModifiers(type.mappedType); + var readonlyMask = modifiers & 1 /* IncludeReadonly */ ? false : true; + var optionalMask = modifiers & 4 /* IncludeOptional */ ? 0 : 16777216 /* Optional */; + var stringIndexInfo = indexInfo && createIndexInfo(inferReverseMappedType(indexInfo.type, type.mappedType, type.constraintType), readonlyMask && indexInfo.isReadonly); + var members = ts.createSymbolTable(); + for (var _i = 0, _a = getPropertiesOfType(type.source); _i < _a.length; _i++) { + var prop = _a[_i]; + var checkFlags = 2048 /* ReverseMapped */ | (readonlyMask && isReadonlySymbol(prop) ? 8 /* Readonly */ : 0); + var inferredProp = createSymbol(4 /* Property */ | prop.flags & optionalMask, prop.escapedName, checkFlags); + inferredProp.declarations = prop.declarations; + inferredProp.nameType = prop.nameType; + inferredProp.propertyType = getTypeOfSymbol(prop); + inferredProp.mappedType = type.mappedType; + inferredProp.constraintType = type.constraintType; + members.set(prop.escapedName, inferredProp); + } + setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, undefined); + } + /** Resolve the members of a mapped type { [P in K]: T } */ + function resolveMappedTypeMembers(type) { + var members = ts.createSymbolTable(); + var stringIndexInfo; + var numberIndexInfo; + // Resolve upfront such that recursive references see an empty object type. + setStructuredTypeMembers(type, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + // In { [P in K]: T }, we refer to P as the type parameter type, K as the constraint type, + // and T as the template type. + var typeParameter = getTypeParameterFromMappedType(type); + var constraintType = getConstraintTypeFromMappedType(type); + var templateType = getTemplateTypeFromMappedType(type.target || type); + var modifiersType = getApparentType(getModifiersTypeFromMappedType(type)); // The 'T' in 'keyof T' + var templateModifiers = getMappedTypeModifiers(type); + var include = keyofStringsOnly ? 128 /* StringLiteral */ : 8576 /* StringOrNumberLiteralOrUnique */; + if (isMappedTypeWithKeyofConstraintDeclaration(type)) { + // We have a { [P in keyof T]: X } + for (var _i = 0, _a = getPropertiesOfType(modifiersType); _i < _a.length; _i++) { + var prop = _a[_i]; + addMemberForKeyType(getLiteralTypeFromProperty(prop, include)); + } + if (modifiersType.flags & 1 /* Any */ || getIndexInfoOfType(modifiersType, 0 /* String */)) { + addMemberForKeyType(stringType); + } + if (!keyofStringsOnly && getIndexInfoOfType(modifiersType, 1 /* Number */)) { + addMemberForKeyType(numberType); + } + } + else { + // If the key type is a 'keyof X', obtain 'keyof C' where C is the base constraint of X. + // Then iterate over the constituents of the key type. + var iterationType = constraintType.flags & 4194304 /* Index */ ? getIndexType(getApparentType(constraintType.type)) : constraintType; + forEachType(iterationType, addMemberForKeyType); + } + setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); + function addMemberForKeyType(t) { + // Create a mapper from T to the current iteration type constituent. Then, if the + // mapped type is itself an instantiated type, combine the iteration mapper with the + // instantiation mapper. + var templateMapper = combineTypeMappers(type.mapper, createTypeMapper([typeParameter], [t])); + var propType = instantiateType(templateType, templateMapper); + // If the current iteration type constituent is a string literal type, create a property. + // Otherwise, for type string create a string index signature. + if (t.flags & 8576 /* StringOrNumberLiteralOrUnique */) { + var propName = getLateBoundNameFromType(t); + var modifiersProp = getPropertyOfType(modifiersType, propName); + var isOptional = !!(templateModifiers & 4 /* IncludeOptional */ || + !(templateModifiers & 8 /* ExcludeOptional */) && modifiersProp && modifiersProp.flags & 16777216 /* Optional */); + var isReadonly = !!(templateModifiers & 1 /* IncludeReadonly */ || + !(templateModifiers & 2 /* ExcludeReadonly */) && modifiersProp && isReadonlySymbol(modifiersProp)); + var prop = createSymbol(4 /* Property */ | (isOptional ? 16777216 /* Optional */ : 0), propName, isReadonly ? 8 /* Readonly */ : 0); + // When creating an optional property in strictNullChecks mode, if 'undefined' isn't assignable to the + // type, we include 'undefined' in the type. Similarly, when creating a non-optional property in strictNullChecks + // mode, if the underlying property is optional we remove 'undefined' from the type. + prop.type = strictNullChecks && isOptional && !isTypeAssignableTo(undefinedType, propType) ? getOptionalType(propType) : + strictNullChecks && !isOptional && modifiersProp && modifiersProp.flags & 16777216 /* Optional */ ? getTypeWithFacts(propType, 524288 /* NEUndefined */) : + propType; + if (modifiersProp) { + prop.syntheticOrigin = modifiersProp; + prop.declarations = modifiersProp.declarations; + } + prop.nameType = t; + members.set(propName, prop); + } + else if (t.flags & (1 /* Any */ | 4 /* String */)) { + stringIndexInfo = createIndexInfo(propType, !!(templateModifiers & 1 /* IncludeReadonly */)); + } + else if (t.flags & 8 /* Number */) { + numberIndexInfo = createIndexInfo(propType, !!(templateModifiers & 1 /* IncludeReadonly */)); + } + } + } + function getTypeParameterFromMappedType(type) { + return type.typeParameter || + (type.typeParameter = getDeclaredTypeOfTypeParameter(getSymbolOfNode(type.declaration.typeParameter))); + } + function getConstraintTypeFromMappedType(type) { + return type.constraintType || + (type.constraintType = getConstraintOfTypeParameter(getTypeParameterFromMappedType(type)) || errorType); + } + function getTemplateTypeFromMappedType(type) { + return type.templateType || + (type.templateType = type.declaration.type ? + instantiateType(addOptionality(getTypeFromTypeNode(type.declaration.type), !!(getMappedTypeModifiers(type) & 4 /* IncludeOptional */)), type.mapper || identityMapper) : + errorType); + } + function getConstraintDeclarationForMappedType(type) { + return ts.getEffectiveConstraintOfTypeParameter(type.declaration.typeParameter); + } + function isMappedTypeWithKeyofConstraintDeclaration(type) { + var constraintDeclaration = getConstraintDeclarationForMappedType(type); // TODO: GH#18217 + return constraintDeclaration.kind === 179 /* TypeOperator */ && + constraintDeclaration.operator === 129 /* KeyOfKeyword */; + } + function getModifiersTypeFromMappedType(type) { + if (!type.modifiersType) { + if (isMappedTypeWithKeyofConstraintDeclaration(type)) { + // If the constraint declaration is a 'keyof T' node, the modifiers type is T. We check + // AST nodes here because, when T is a non-generic type, the logic below eagerly resolves + // 'keyof T' to a literal union type and we can't recover T from that type. + type.modifiersType = instantiateType(getTypeFromTypeNode(getConstraintDeclarationForMappedType(type).type), type.mapper || identityMapper); + } + else { + // Otherwise, get the declared constraint type, and if the constraint type is a type parameter, + // get the constraint of that type parameter. If the resulting type is an indexed type 'keyof T', + // the modifiers type is T. Otherwise, the modifiers type is {}. + var declaredType = getTypeFromMappedTypeNode(type.declaration); + var constraint = getConstraintTypeFromMappedType(declaredType); + var extendedConstraint = constraint && constraint.flags & 262144 /* TypeParameter */ ? getConstraintOfTypeParameter(constraint) : constraint; + type.modifiersType = extendedConstraint && extendedConstraint.flags & 4194304 /* Index */ ? instantiateType(extendedConstraint.type, type.mapper || identityMapper) : emptyObjectType; + } + } + return type.modifiersType; + } + function getMappedTypeModifiers(type) { + var declaration = type.declaration; + return (declaration.readonlyToken ? declaration.readonlyToken.kind === 39 /* MinusToken */ ? 2 /* ExcludeReadonly */ : 1 /* IncludeReadonly */ : 0) | + (declaration.questionToken ? declaration.questionToken.kind === 39 /* MinusToken */ ? 8 /* ExcludeOptional */ : 4 /* IncludeOptional */ : 0); + } + function getMappedTypeOptionality(type) { + var modifiers = getMappedTypeModifiers(type); + return modifiers & 8 /* ExcludeOptional */ ? -1 : modifiers & 4 /* IncludeOptional */ ? 1 : 0; + } + function getCombinedMappedTypeOptionality(type) { + var optionality = getMappedTypeOptionality(type); + var modifiersType = getModifiersTypeFromMappedType(type); + return optionality || (isGenericMappedType(modifiersType) ? getMappedTypeOptionality(modifiersType) : 0); + } + function isPartialMappedType(type) { + return !!(ts.getObjectFlags(type) & 32 /* Mapped */ && getMappedTypeModifiers(type) & 4 /* IncludeOptional */); + } + function isGenericMappedType(type) { + return !!(ts.getObjectFlags(type) & 32 /* Mapped */) && isGenericIndexType(getConstraintTypeFromMappedType(type)); + } + function resolveStructuredTypeMembers(type) { + if (!type.members) { + if (type.flags & 524288 /* Object */) { + if (type.objectFlags & 4 /* Reference */) { + resolveTypeReferenceMembers(type); + } + else if (type.objectFlags & 3 /* ClassOrInterface */) { + resolveClassOrInterfaceMembers(type); + } + else if (type.objectFlags & 2048 /* ReverseMapped */) { + resolveReverseMappedTypeMembers(type); + } + else if (type.objectFlags & 16 /* Anonymous */) { + resolveAnonymousTypeMembers(type); + } + else if (type.objectFlags & 32 /* Mapped */) { + resolveMappedTypeMembers(type); + } + } + else if (type.flags & 1048576 /* Union */) { + resolveUnionTypeMembers(type); + } + else if (type.flags & 2097152 /* Intersection */) { + resolveIntersectionTypeMembers(type); + } + } + return type; + } + /** Return properties of an object type or an empty array for other types */ + function getPropertiesOfObjectType(type) { + if (type.flags & 524288 /* Object */) { + return resolveStructuredTypeMembers(type).properties; + } + return ts.emptyArray; + } + /** If the given type is an object type and that type has a property by the given name, + * return the symbol for that property. Otherwise return undefined. + */ + function getPropertyOfObjectType(type, name) { + if (type.flags & 524288 /* Object */) { + var resolved = resolveStructuredTypeMembers(type); + var symbol = resolved.members.get(name); + if (symbol && symbolIsValue(symbol)) { + return symbol; + } + } + } + function getPropertiesOfUnionOrIntersectionType(type) { + if (!type.resolvedProperties) { + var members = ts.createSymbolTable(); + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var current = _a[_i]; + for (var _b = 0, _c = getPropertiesOfType(current); _b < _c.length; _b++) { + var prop = _c[_b]; + if (!members.has(prop.escapedName)) { + var combinedProp = getPropertyOfUnionOrIntersectionType(type, prop.escapedName); + if (combinedProp) { + members.set(prop.escapedName, combinedProp); + } + } + } + // The properties of a union type are those that are present in all constituent types, so + // we only need to check the properties of the first type + if (type.flags & 1048576 /* Union */) { + break; + } + } + type.resolvedProperties = getNamedMembers(members); + } + return type.resolvedProperties; + } + function getPropertiesOfType(type) { + type = getApparentType(type); + return type.flags & 3145728 /* UnionOrIntersection */ ? + getPropertiesOfUnionOrIntersectionType(type) : + getPropertiesOfObjectType(type); + } + function isTypeInvalidDueToUnionDiscriminant(contextualType, obj) { + var list = obj.properties; + return list.some(function (property) { + var name = property.name && ts.getTextOfPropertyName(property.name); + var expected = name === undefined ? undefined : getTypeOfPropertyOfType(contextualType, name); + return !!expected && typeIsLiteralType(expected) && !isTypeIdenticalTo(getTypeOfNode(property), expected); + }); + } + function getAllPossiblePropertiesOfTypes(types) { + var unionType = getUnionType(types); + if (!(unionType.flags & 1048576 /* Union */)) { + return getAugmentedPropertiesOfType(unionType); + } + var props = ts.createSymbolTable(); + for (var _i = 0, types_3 = types; _i < types_3.length; _i++) { + var memberType = types_3[_i]; + for (var _a = 0, _b = getAugmentedPropertiesOfType(memberType); _a < _b.length; _a++) { + var escapedName = _b[_a].escapedName; + if (!props.has(escapedName)) { + var prop = createUnionOrIntersectionProperty(unionType, escapedName); + // May be undefined if the property is private + if (prop) + props.set(escapedName, prop); + } + } + } + return ts.arrayFrom(props.values()); + } + function getConstraintOfType(type) { + return type.flags & 262144 /* TypeParameter */ ? getConstraintOfTypeParameter(type) : + type.flags & 8388608 /* IndexedAccess */ ? getConstraintOfIndexedAccess(type) : + type.flags & 16777216 /* Conditional */ ? getConstraintOfConditionalType(type) : + getBaseConstraintOfType(type); + } + function getConstraintOfTypeParameter(typeParameter) { + return hasNonCircularBaseConstraint(typeParameter) ? getConstraintFromTypeParameter(typeParameter) : undefined; + } + function getConstraintOfIndexedAccess(type) { + var objectType = getConstraintOfType(type.objectType) || type.objectType; + if (objectType !== type.objectType) { + var constraint = getIndexedAccessType(objectType, type.indexType, /*accessNode*/ undefined, errorType); + if (constraint && constraint !== errorType) { + return constraint; + } + } + var baseConstraint = getBaseConstraintOfType(type); + return baseConstraint && baseConstraint !== type ? baseConstraint : undefined; + } + function getDefaultConstraintOfConditionalType(type) { + if (!type.resolvedDefaultConstraint) { + var rootTrueType = type.root.trueType; + var rootTrueConstraint = !(rootTrueType.flags & 33554432 /* Substitution */) + ? rootTrueType + : (rootTrueType.substitute).flags & 3 /* AnyOrUnknown */ + ? rootTrueType.typeVariable + : getIntersectionType([rootTrueType.substitute, rootTrueType.typeVariable]); + type.resolvedDefaultConstraint = getUnionType([instantiateType(rootTrueConstraint, type.combinedMapper || type.mapper), getFalseTypeFromConditionalType(type)]); + } + return type.resolvedDefaultConstraint; + } + function getConstraintOfDistributiveConditionalType(type) { + // Check if we have a conditional type of the form 'T extends U ? X : Y', where T is a constrained + // type parameter. If so, create an instantiation of the conditional type where T is replaced + // with its constraint. We do this because if the constraint is a union type it will be distributed + // over the conditional type and possibly reduced. For example, 'T extends undefined ? never : T' + // removes 'undefined' from T. + if (type.root.isDistributive) { + var simplified = getSimplifiedType(type.checkType); + var constraint = simplified === type.checkType ? getConstraintOfType(simplified) : simplified; + if (constraint) { + var mapper = makeUnaryTypeMapper(type.root.checkType, constraint); + var instantiated = getConditionalTypeInstantiation(type, combineTypeMappers(mapper, type.mapper)); + if (!(instantiated.flags & 131072 /* Never */)) { + return instantiated; + } + } + } + return undefined; + } + function getConstraintOfConditionalType(type) { + return getConstraintOfDistributiveConditionalType(type) || getDefaultConstraintOfConditionalType(type); + } + function getUnionConstraintOfIntersection(type, targetIsUnion) { + var constraints; + var hasDisjointDomainType = false; + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (t.flags & 63176704 /* Instantiable */) { + // We keep following constraints as long as we have an instantiable type that is known + // not to be circular or infinite (hence we stop on index access types). + var constraint = getConstraintOfType(t); + while (constraint && constraint.flags & (262144 /* TypeParameter */ | 4194304 /* Index */ | 16777216 /* Conditional */)) { + constraint = getConstraintOfType(constraint); + } + if (constraint) { + // A constraint that isn't a union type implies that the final type would be a non-union + // type as well. Since non-union constraints are of no interest, we can exit here. + if (!(constraint.flags & 1048576 /* Union */)) { + return undefined; + } + constraints = ts.append(constraints, constraint); + } + } + else if (t.flags & 67238908 /* DisjointDomains */) { + hasDisjointDomainType = true; + } + } + // If the target is a union type or if we are intersecting with types belonging to one of the + // disjoint domans, we may end up producing a constraint that hasn't been examined before. + if (constraints && (targetIsUnion || hasDisjointDomainType)) { + if (hasDisjointDomainType) { + // We add any types belong to one of the disjoint domans because they might cause the final + // intersection operation to reduce the union constraints. + for (var _b = 0, _c = type.types; _b < _c.length; _b++) { + var t = _c[_b]; + if (t.flags & 67238908 /* DisjointDomains */) { + constraints = ts.append(constraints, t); + } + } + } + return getIntersectionType(constraints); + } + return undefined; + } + function getBaseConstraintOfType(type) { + if (type.flags & (58982400 /* InstantiableNonPrimitive */ | 3145728 /* UnionOrIntersection */)) { + var constraint = getResolvedBaseConstraint(type); + return constraint !== noConstraintType && constraint !== circularConstraintType ? constraint : undefined; + } + return type.flags & 4194304 /* Index */ ? keyofConstraintType : undefined; + } + /** + * This is similar to `getBaseConstraintOfType` except it returns the input type if there's no base constraint, instead of `undefined` + * It also doesn't map indexes to `string`, as where this is used this would be unneeded (and likely undesirable) + */ + function getBaseConstraintOrType(type) { + return getBaseConstraintOfType(type) || type; + } + function hasNonCircularBaseConstraint(type) { + return getResolvedBaseConstraint(type) !== circularConstraintType; + } + /** + * Return the resolved base constraint of a type variable. The noConstraintType singleton is returned if the + * type variable has no constraint, and the circularConstraintType singleton is returned if the constraint + * circularly references the type variable. + */ + function getResolvedBaseConstraint(type) { + var nonTerminating = false; + return type.resolvedBaseConstraint || + (type.resolvedBaseConstraint = getTypeWithThisArgument(getImmediateBaseConstraint(type), type)); + function getImmediateBaseConstraint(t) { + if (!t.immediateBaseConstraint) { + if (!pushTypeResolution(t, 4 /* ImmediateBaseConstraint */)) { + return circularConstraintType; + } + if (constraintDepth === 50) { + // We have reached 50 recursive invocations of getImmediateBaseConstraint and there is a + // very high likelyhood we're dealing with an infinite generic type that perpetually generates + // new type identities as we descend into it. We stop the recursion here and mark this type + // and the outer types as having circular constraints. + nonTerminating = true; + return t.immediateBaseConstraint = noConstraintType; + } + constraintDepth++; + var result = computeBaseConstraint(getSimplifiedType(t)); + constraintDepth--; + if (!popTypeResolution() || nonTerminating) { + result = circularConstraintType; + } + t.immediateBaseConstraint = result || noConstraintType; + } + return t.immediateBaseConstraint; + } + function getBaseConstraint(t) { + var c = getImmediateBaseConstraint(t); + return c !== noConstraintType && c !== circularConstraintType ? c : undefined; + } + function computeBaseConstraint(t) { + if (t.flags & 262144 /* TypeParameter */) { + var constraint = getConstraintFromTypeParameter(t); + return t.isThisType || !constraint ? + constraint : + getBaseConstraint(constraint); + } + if (t.flags & 3145728 /* UnionOrIntersection */) { + var types = t.types; + var baseTypes = []; + for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { + var type_3 = types_4[_i]; + var baseType = getBaseConstraint(type_3); + if (baseType) { + baseTypes.push(baseType); + } + } + return t.flags & 1048576 /* Union */ && baseTypes.length === types.length ? getUnionType(baseTypes) : + t.flags & 2097152 /* Intersection */ && baseTypes.length ? getIntersectionType(baseTypes) : + undefined; + } + if (t.flags & 4194304 /* Index */) { + return keyofConstraintType; + } + if (t.flags & 8388608 /* IndexedAccess */) { + var baseObjectType = getBaseConstraint(t.objectType); + var baseIndexType = getBaseConstraint(t.indexType); + var baseIndexedAccess = baseObjectType && baseIndexType ? getIndexedAccessType(baseObjectType, baseIndexType, /*accessNode*/ undefined, errorType) : undefined; + return baseIndexedAccess && baseIndexedAccess !== errorType ? getBaseConstraint(baseIndexedAccess) : undefined; + } + if (t.flags & 16777216 /* Conditional */) { + var constraint = getConstraintOfConditionalType(t); + return constraint && getBaseConstraint(constraint); + } + if (t.flags & 33554432 /* Substitution */) { + return getBaseConstraint(t.substitute); + } + return t; + } + } + function getApparentTypeOfIntersectionType(type) { + return type.resolvedApparentType || (type.resolvedApparentType = getTypeWithThisArgument(type, type, /*apparentType*/ true)); + } + function getResolvedTypeParameterDefault(typeParameter) { + if (!typeParameter.default) { + if (typeParameter.target) { + var targetDefault = getResolvedTypeParameterDefault(typeParameter.target); + typeParameter.default = targetDefault ? instantiateType(targetDefault, typeParameter.mapper) : noConstraintType; + } + else { + // To block recursion, set the initial value to the resolvingDefaultType. + typeParameter.default = resolvingDefaultType; + var defaultDeclaration = typeParameter.symbol && ts.forEach(typeParameter.symbol.declarations, function (decl) { return ts.isTypeParameterDeclaration(decl) && decl.default; }); + var defaultType = defaultDeclaration ? getTypeFromTypeNode(defaultDeclaration) : noConstraintType; + if (typeParameter.default === resolvingDefaultType) { + // If we have not been called recursively, set the correct default type. + typeParameter.default = defaultType; + } + } + } + else if (typeParameter.default === resolvingDefaultType) { + // If we are called recursively for this type parameter, mark the default as circular. + typeParameter.default = circularConstraintType; + } + return typeParameter.default; + } + /** + * Gets the default type for a type parameter. + * + * If the type parameter is the result of an instantiation, this gets the instantiated + * default type of its target. If the type parameter has no default type or the default is + * circular, `undefined` is returned. + */ + function getDefaultFromTypeParameter(typeParameter) { + var defaultType = getResolvedTypeParameterDefault(typeParameter); + return defaultType !== noConstraintType && defaultType !== circularConstraintType ? defaultType : undefined; + } + function hasNonCircularTypeParameterDefault(typeParameter) { + return getResolvedTypeParameterDefault(typeParameter) !== circularConstraintType; + } + /** + * Indicates whether the declaration of a typeParameter has a default type. + */ + function hasTypeParameterDefault(typeParameter) { + return !!(typeParameter.symbol && ts.forEach(typeParameter.symbol.declarations, function (decl) { return ts.isTypeParameterDeclaration(decl) && decl.default; })); + } + function getApparentTypeOfMappedType(type) { + return type.resolvedApparentType || (type.resolvedApparentType = getResolvedApparentTypeOfMappedType(type)); + } + function getResolvedApparentTypeOfMappedType(type) { + var typeVariable = getHomomorphicTypeVariable(type); + if (typeVariable) { + var constraint = getConstraintOfTypeParameter(typeVariable); + if (constraint && (isArrayType(constraint) || isReadonlyArrayType(constraint) || isTupleType(constraint))) { + var mapper = makeUnaryTypeMapper(typeVariable, constraint); + return instantiateType(type, combineTypeMappers(mapper, type.mapper)); + } + } + return type; + } + /** + * For a type parameter, return the base constraint of the type parameter. For the string, number, + * boolean, and symbol primitive types, return the corresponding object types. Otherwise return the + * type itself. Note that the apparent type of a union type is the union type itself. + */ + function getApparentType(type) { + var t = type.flags & 63176704 /* Instantiable */ ? getBaseConstraintOfType(type) || emptyObjectType : type; + return ts.getObjectFlags(t) & 32 /* Mapped */ ? getApparentTypeOfMappedType(t) : + t.flags & 2097152 /* Intersection */ ? getApparentTypeOfIntersectionType(t) : + t.flags & 132 /* StringLike */ ? globalStringType : + t.flags & 296 /* NumberLike */ ? globalNumberType : + t.flags & 2112 /* BigIntLike */ ? getGlobalBigIntType(/*reportErrors*/ languageVersion >= 6 /* ESNext */) : + t.flags & 528 /* BooleanLike */ ? globalBooleanType : + t.flags & 12288 /* ESSymbolLike */ ? getGlobalESSymbolType(/*reportErrors*/ languageVersion >= 2 /* ES2015 */) : + t.flags & 67108864 /* NonPrimitive */ ? emptyObjectType : + t.flags & 4194304 /* Index */ ? keyofConstraintType : + t; + } + function createUnionOrIntersectionProperty(containingType, name) { + var props; + var indexTypes; + var isUnion = containingType.flags & 1048576 /* Union */; + var excludeModifiers = isUnion ? 24 /* NonPublicAccessibilityModifier */ : 0; + // Flags we want to propagate to the result if they exist in all source symbols + var commonFlags = isUnion ? 0 /* None */ : 16777216 /* Optional */; + var syntheticFlag = 4 /* SyntheticMethod */; + var checkFlags = 0; + for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) { + var current = _a[_i]; + var type = getApparentType(current); + if (type !== errorType) { + var prop = getPropertyOfType(type, name); + var modifiers = prop ? ts.getDeclarationModifierFlagsFromSymbol(prop) : 0; + if (prop && !(modifiers & excludeModifiers)) { + commonFlags &= prop.flags; + props = ts.appendIfUnique(props, prop); + checkFlags |= (isReadonlySymbol(prop) ? 8 /* Readonly */ : 0) | + (!(modifiers & 24 /* NonPublicAccessibilityModifier */) ? 64 /* ContainsPublic */ : 0) | + (modifiers & 16 /* Protected */ ? 128 /* ContainsProtected */ : 0) | + (modifiers & 8 /* Private */ ? 256 /* ContainsPrivate */ : 0) | + (modifiers & 32 /* Static */ ? 512 /* ContainsStatic */ : 0); + if (!isPrototypeProperty(prop)) { + syntheticFlag = 2 /* SyntheticProperty */; + } + } + else if (isUnion) { + var indexInfo = !isLateBoundName(name) && (isNumericLiteralName(name) && getIndexInfoOfType(type, 1 /* Number */) || getIndexInfoOfType(type, 0 /* String */)); + if (indexInfo) { + checkFlags |= indexInfo.isReadonly ? 8 /* Readonly */ : 0; + indexTypes = ts.append(indexTypes, isTupleType(type) ? getRestTypeOfTupleType(type) || undefinedType : indexInfo.type); + } + else { + checkFlags |= 16 /* Partial */; + } + } + } + } + if (!props) { + return undefined; + } + if (props.length === 1 && !(checkFlags & 16 /* Partial */) && !indexTypes) { + return props[0]; + } + var declarations; + var commonType; + var nameType; + var propTypes = []; + var first = true; + var commonValueDeclaration; + var hasNonUniformValueDeclaration = false; + for (var _b = 0, props_1 = props; _b < props_1.length; _b++) { + var prop = props_1[_b]; + if (!commonValueDeclaration) { + commonValueDeclaration = prop.valueDeclaration; + } + else if (prop.valueDeclaration !== commonValueDeclaration) { + hasNonUniformValueDeclaration = true; + } + declarations = ts.addRange(declarations, prop.declarations); + var type = getTypeOfSymbol(prop); + if (first) { + commonType = type; + nameType = prop.nameType; + first = false; + } + else { + if (type !== commonType) { + checkFlags |= 32 /* HasNonUniformType */; + } + } + propTypes.push(type); + } + ts.addRange(propTypes, indexTypes); + var result = createSymbol(4 /* Property */ | commonFlags, name, syntheticFlag | checkFlags); + result.containingType = containingType; + if (!hasNonUniformValueDeclaration && commonValueDeclaration) { + result.valueDeclaration = commonValueDeclaration; + } + result.declarations = declarations; + result.nameType = nameType; + result.type = isUnion ? getUnionType(propTypes) : getIntersectionType(propTypes); + return result; + } + // Return the symbol for a given property in a union or intersection type, or undefined if the property + // does not exist in any constituent type. Note that the returned property may only be present in some + // constituents, in which case the isPartial flag is set when the containing type is union type. We need + // these partial properties when identifying discriminant properties, but otherwise they are filtered out + // and do not appear to be present in the union type. + function getUnionOrIntersectionProperty(type, name) { + var properties = type.propertyCache || (type.propertyCache = ts.createSymbolTable()); + var property = properties.get(name); + if (!property) { + property = createUnionOrIntersectionProperty(type, name); + if (property) { + properties.set(name, property); + } + } + return property; + } + function getPropertyOfUnionOrIntersectionType(type, name) { + var property = getUnionOrIntersectionProperty(type, name); + // We need to filter out partial properties in union types + return property && !(ts.getCheckFlags(property) & 16 /* Partial */) ? property : undefined; + } + /** + * Return the symbol for the property with the given name in the given type. Creates synthetic union properties when + * necessary, maps primitive types and type parameters are to their apparent types, and augments with properties from + * Object and Function as appropriate. + * + * @param type a type to look up property from + * @param name a name of property to look up in a given type + */ + function getPropertyOfType(type, name) { + type = getApparentType(type); + if (type.flags & 524288 /* Object */) { + var resolved = resolveStructuredTypeMembers(type); + var symbol = resolved.members.get(name); + if (symbol && symbolIsValue(symbol)) { + return symbol; + } + var functionType = resolved === anyFunctionType ? globalFunctionType : + resolved.callSignatures.length ? globalCallableFunctionType : + resolved.constructSignatures.length ? globalNewableFunctionType : + undefined; + if (functionType) { + var symbol_1 = getPropertyOfObjectType(functionType, name); + if (symbol_1) { + return symbol_1; + } + } + return getPropertyOfObjectType(globalObjectType, name); + } + if (type.flags & 3145728 /* UnionOrIntersection */) { + return getPropertyOfUnionOrIntersectionType(type, name); + } + return undefined; + } + function getSignaturesOfStructuredType(type, kind) { + if (type.flags & 3670016 /* StructuredType */) { + var resolved = resolveStructuredTypeMembers(type); + return kind === 0 /* Call */ ? resolved.callSignatures : resolved.constructSignatures; + } + return ts.emptyArray; + } + /** + * Return the signatures of the given kind in the given type. Creates synthetic union signatures when necessary and + * maps primitive types and type parameters are to their apparent types. + */ + function getSignaturesOfType(type, kind) { + return getSignaturesOfStructuredType(getApparentType(type), kind); + } + function getIndexInfoOfStructuredType(type, kind) { + if (type.flags & 3670016 /* StructuredType */) { + var resolved = resolveStructuredTypeMembers(type); + return kind === 0 /* String */ ? resolved.stringIndexInfo : resolved.numberIndexInfo; + } + } + function getIndexTypeOfStructuredType(type, kind) { + var info = getIndexInfoOfStructuredType(type, kind); + return info && info.type; + } + // Return the indexing info of the given kind in the given type. Creates synthetic union index types when necessary and + // maps primitive types and type parameters are to their apparent types. + function getIndexInfoOfType(type, kind) { + return getIndexInfoOfStructuredType(getApparentType(type), kind); + } + // Return the index type of the given kind in the given type. Creates synthetic union index types when necessary and + // maps primitive types and type parameters are to their apparent types. + function getIndexTypeOfType(type, kind) { + return getIndexTypeOfStructuredType(getApparentType(type), kind); + } + function getImplicitIndexTypeOfType(type, kind) { + if (isObjectTypeWithInferableIndex(type)) { + var propTypes = []; + for (var _i = 0, _a = getPropertiesOfType(type); _i < _a.length; _i++) { + var prop = _a[_i]; + if (kind === 0 /* String */ || isNumericLiteralName(prop.escapedName)) { + propTypes.push(getTypeOfSymbol(prop)); + } + } + if (propTypes.length) { + return getUnionType(propTypes, 2 /* Subtype */); + } + } + return undefined; + } + // Return list of type parameters with duplicates removed (duplicate identifier errors are generated in the actual + // type checking functions). + function getTypeParametersFromDeclaration(declaration) { + var result; + for (var _i = 0, _a = ts.getEffectiveTypeParameterDeclarations(declaration); _i < _a.length; _i++) { + var node = _a[_i]; + result = ts.appendIfUnique(result, getDeclaredTypeOfTypeParameter(node.symbol)); + } + return result; + } + function symbolsToArray(symbols) { + var result = []; + symbols.forEach(function (symbol, id) { + if (!isReservedMemberName(id)) { + result.push(symbol); + } + }); + return result; + } + function isJSDocOptionalParameter(node) { + return ts.isInJSFile(node) && ( + // node.type should only be a JSDocOptionalType when node is a parameter of a JSDocFunctionType + node.type && node.type.kind === 288 /* JSDocOptionalType */ + || ts.getJSDocParameterTags(node).some(function (_a) { + var isBracketed = _a.isBracketed, typeExpression = _a.typeExpression; + return isBracketed || !!typeExpression && typeExpression.type.kind === 288 /* JSDocOptionalType */; + })); + } + function tryFindAmbientModule(moduleName, withAugmentations) { + if (ts.isExternalModuleNameRelative(moduleName)) { + return undefined; + } + var symbol = getSymbol(globals, '"' + moduleName + '"', 512 /* ValueModule */); + // merged symbol is module declaration symbol combined with all augmentations + return symbol && withAugmentations ? getMergedSymbol(symbol) : symbol; + } + function isOptionalParameter(node) { + if (ts.hasQuestionToken(node) || isOptionalJSDocParameterTag(node) || isJSDocOptionalParameter(node)) { + return true; + } + if (node.initializer) { + var signature = getSignatureFromDeclaration(node.parent); + var parameterIndex = node.parent.parameters.indexOf(node); + ts.Debug.assert(parameterIndex >= 0); + return parameterIndex >= getMinArgumentCount(signature); + } + var iife = ts.getImmediatelyInvokedFunctionExpression(node.parent); + if (iife) { + return !node.type && + !node.dotDotDotToken && + node.parent.parameters.indexOf(node) >= iife.arguments.length; + } + return false; + } + function isOptionalJSDocParameterTag(node) { + if (!ts.isJSDocParameterTag(node)) { + return false; + } + var isBracketed = node.isBracketed, typeExpression = node.typeExpression; + return isBracketed || !!typeExpression && typeExpression.type.kind === 288 /* JSDocOptionalType */; + } + function createIdentifierTypePredicate(parameterName, parameterIndex, type) { + return { kind: 1 /* Identifier */, parameterName: parameterName, parameterIndex: parameterIndex, type: type }; + } + function createThisTypePredicate(type) { + return { kind: 0 /* This */, type: type }; + } + /** + * Gets the minimum number of type arguments needed to satisfy all non-optional type + * parameters. + */ + function getMinTypeArgumentCount(typeParameters) { + var minTypeArgumentCount = 0; + if (typeParameters) { + for (var i = 0; i < typeParameters.length; i++) { + if (!hasTypeParameterDefault(typeParameters[i])) { + minTypeArgumentCount = i + 1; + } + } + } + return minTypeArgumentCount; + } + function fillMissingTypeArguments(typeArguments, typeParameters, minTypeArgumentCount, isJavaScriptImplicitAny) { + var numTypeParameters = ts.length(typeParameters); + if (!numTypeParameters) { + return []; + } + var numTypeArguments = ts.length(typeArguments); + if (isJavaScriptImplicitAny || (numTypeArguments >= minTypeArgumentCount && numTypeArguments <= numTypeParameters)) { + var result = typeArguments ? typeArguments.slice() : []; + // Map an unsatisfied type parameter with a default type. + // If a type parameter does not have a default type, or if the default type + // is a forward reference, the empty object type is used. + var baseDefaultType_1 = getDefaultTypeArgumentType(isJavaScriptImplicitAny); + var circularityMapper = createTypeMapper(typeParameters, ts.map(typeParameters, function () { return baseDefaultType_1; })); + for (var i = numTypeArguments; i < numTypeParameters; i++) { + result[i] = instantiateType(getConstraintFromTypeParameter(typeParameters[i]) || baseDefaultType_1, circularityMapper); + } + for (var i = numTypeArguments; i < numTypeParameters; i++) { + var mapper = createTypeMapper(typeParameters, result); + var defaultType = getDefaultFromTypeParameter(typeParameters[i]); + if (isJavaScriptImplicitAny && defaultType && isTypeIdenticalTo(defaultType, emptyObjectType)) { + defaultType = anyType; + } + result[i] = defaultType ? instantiateType(defaultType, mapper) : baseDefaultType_1; + } + result.length = typeParameters.length; + return result; + } + return typeArguments && typeArguments.slice(); + } + function getSignatureFromDeclaration(declaration) { + var links = getNodeLinks(declaration); + if (!links.resolvedSignature) { + var parameters = []; + var hasLiteralTypes = false; + var minArgumentCount = 0; + var thisParameter = void 0; + var hasThisParameter = false; + var iife = ts.getImmediatelyInvokedFunctionExpression(declaration); + var isJSConstructSignature = ts.isJSDocConstructSignature(declaration); + var isUntypedSignatureInJSFile = !iife && + ts.isInJSFile(declaration) && + ts.isValueSignatureDeclaration(declaration) && + !ts.hasJSDocParameterTags(declaration) && + !ts.getJSDocType(declaration); + // If this is a JSDoc construct signature, then skip the first parameter in the + // parameter list. The first parameter represents the return type of the construct + // signature. + for (var i = isJSConstructSignature ? 1 : 0; i < declaration.parameters.length; i++) { + var param = declaration.parameters[i]; + var paramSymbol = param.symbol; + var type = ts.isJSDocParameterTag(param) ? (param.typeExpression && param.typeExpression.type) : param.type; + // Include parameter symbol instead of property symbol in the signature + if (paramSymbol && !!(paramSymbol.flags & 4 /* Property */) && !ts.isBindingPattern(param.name)) { + var resolvedSymbol = resolveName(param, paramSymbol.escapedName, 67220415 /* Value */, undefined, undefined, /*isUse*/ false); + paramSymbol = resolvedSymbol; + } + if (i === 0 && paramSymbol.escapedName === "this" /* This */) { + hasThisParameter = true; + thisParameter = param.symbol; + } + else { + parameters.push(paramSymbol); + } + if (type && type.kind === 182 /* LiteralType */) { + hasLiteralTypes = true; + } + // Record a new minimum argument count if this is not an optional parameter + var isOptionalParameter_1 = isOptionalJSDocParameterTag(param) || + param.initializer || param.questionToken || param.dotDotDotToken || + iife && parameters.length > iife.arguments.length && !type || + isUntypedSignatureInJSFile || + isJSDocOptionalParameter(param); + if (!isOptionalParameter_1) { + minArgumentCount = parameters.length; + } + } + // If only one accessor includes a this-type annotation, the other behaves as if it had the same type annotation + if ((declaration.kind === 158 /* GetAccessor */ || declaration.kind === 159 /* SetAccessor */) && + !hasNonBindableDynamicName(declaration) && + (!hasThisParameter || !thisParameter)) { + var otherKind = declaration.kind === 158 /* GetAccessor */ ? 159 /* SetAccessor */ : 158 /* GetAccessor */; + var other = ts.getDeclarationOfKind(getSymbolOfNode(declaration), otherKind); + if (other) { + thisParameter = getAnnotatedAccessorThisParameter(other); + } + } + var classType = declaration.kind === 157 /* Constructor */ ? + getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)) + : undefined; + var typeParameters = classType ? classType.localTypeParameters : getTypeParametersFromDeclaration(declaration); + var hasRestLikeParameter = ts.hasRestParameter(declaration) || ts.isInJSFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters); + links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, + /*resolvedReturnType*/ undefined, /*resolvedTypePredicate*/ undefined, minArgumentCount, hasRestLikeParameter, hasLiteralTypes); + } + return links.resolvedSignature; + } + /** + * A JS function gets a synthetic rest parameter if it references `arguments` AND: + * 1. It has no parameters but at least one `@param` with a type that starts with `...` + * OR + * 2. It has at least one parameter, and the last parameter has a matching `@param` with a type that starts with `...` + */ + function maybeAddJsSyntheticRestParameter(declaration, parameters) { + if (ts.isJSDocSignature(declaration) || !containsArgumentsReference(declaration)) { + return false; + } + var lastParam = ts.lastOrUndefined(declaration.parameters); + var lastParamTags = lastParam ? ts.getJSDocParameterTags(lastParam) : ts.getJSDocTags(declaration).filter(ts.isJSDocParameterTag); + var lastParamVariadicType = ts.firstDefined(lastParamTags, function (p) { + return p.typeExpression && ts.isJSDocVariadicType(p.typeExpression.type) ? p.typeExpression.type : undefined; + }); + var syntheticArgsSymbol = createSymbol(3 /* Variable */, "args", 8192 /* RestParameter */); + syntheticArgsSymbol.type = lastParamVariadicType ? createArrayType(getTypeFromTypeNode(lastParamVariadicType.type)) : anyArrayType; + if (lastParamVariadicType) { + // Replace the last parameter with a rest parameter. + parameters.pop(); + } + parameters.push(syntheticArgsSymbol); + return true; + } + function getSignatureOfTypeTag(node) { + var typeTag = ts.isInJSFile(node) ? ts.getJSDocTypeTag(node) : undefined; + var signature = typeTag && typeTag.typeExpression && getSingleCallSignature(getTypeFromTypeNode(typeTag.typeExpression)); + return signature && getErasedSignature(signature); + } + function getReturnTypeOfTypeTag(node) { + var signature = getSignatureOfTypeTag(node); + return signature && getReturnTypeOfSignature(signature); + } + function containsArgumentsReference(declaration) { + var links = getNodeLinks(declaration); + if (links.containsArgumentsReference === undefined) { + if (links.flags & 8192 /* CaptureArguments */) { + links.containsArgumentsReference = true; + } + else { + links.containsArgumentsReference = traverse(declaration.body); + } + } + return links.containsArgumentsReference; + function traverse(node) { + if (!node) + return false; + switch (node.kind) { + case 72 /* Identifier */: + return node.escapedText === "arguments" && ts.isExpressionNode(node); + case 154 /* PropertyDeclaration */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + return node.name.kind === 149 /* ComputedPropertyName */ + && traverse(node.name); + default: + return !ts.nodeStartsNewLexicalEnvironment(node) && !ts.isPartOfTypeNode(node) && !!ts.forEachChild(node, traverse); + } + } + } + function getSignaturesOfSymbol(symbol) { + if (!symbol) + return ts.emptyArray; + var result = []; + for (var i = 0; i < symbol.declarations.length; i++) { + var decl = symbol.declarations[i]; + if (!ts.isFunctionLike(decl)) + continue; + // Don't include signature if node is the implementation of an overloaded function. A node is considered + // an implementation node if it has a body and the previous node is of the same kind and immediately + // precedes the implementation node (i.e. has the same parent and ends where the implementation starts). + if (i > 0 && decl.body) { + var previous = symbol.declarations[i - 1]; + if (decl.parent === previous.parent && decl.kind === previous.kind && decl.pos === previous.end) { + continue; + } + } + result.push(getSignatureFromDeclaration(decl)); + } + return result; + } + function resolveExternalModuleTypeByLiteral(name) { + var moduleSym = resolveExternalModuleName(name, name); + if (moduleSym) { + var resolvedModuleSymbol = resolveExternalModuleSymbol(moduleSym); + if (resolvedModuleSymbol) { + return getTypeOfSymbol(resolvedModuleSymbol); + } + } + return anyType; + } + function getThisTypeOfSignature(signature) { + if (signature.thisParameter) { + return getTypeOfSymbol(signature.thisParameter); + } + } + function signatureHasTypePredicate(signature) { + return getTypePredicateOfSignature(signature) !== undefined; + } + function getTypePredicateOfSignature(signature) { + if (!signature.resolvedTypePredicate) { + if (signature.target) { + var targetTypePredicate = getTypePredicateOfSignature(signature.target); + signature.resolvedTypePredicate = targetTypePredicate ? instantiateTypePredicate(targetTypePredicate, signature.mapper) : noTypePredicate; + } + else if (signature.unionSignatures) { + signature.resolvedTypePredicate = getUnionTypePredicate(signature.unionSignatures) || noTypePredicate; + } + else { + var type = signature.declaration && ts.getEffectiveReturnTypeNode(signature.declaration); + var jsdocPredicate = void 0; + if (!type && ts.isInJSFile(signature.declaration)) { + var jsdocSignature = getSignatureOfTypeTag(signature.declaration); + if (jsdocSignature && signature !== jsdocSignature) { + jsdocPredicate = getTypePredicateOfSignature(jsdocSignature); + } + } + signature.resolvedTypePredicate = type && ts.isTypePredicateNode(type) ? + createTypePredicateFromTypePredicateNode(type, signature.declaration) : + jsdocPredicate || noTypePredicate; + } + ts.Debug.assert(!!signature.resolvedTypePredicate); + } + return signature.resolvedTypePredicate === noTypePredicate ? undefined : signature.resolvedTypePredicate; + } + function createTypePredicateFromTypePredicateNode(node, func) { + var parameterName = node.parameterName; + var type = getTypeFromTypeNode(node.type); + if (parameterName.kind === 72 /* Identifier */) { + return createIdentifierTypePredicate(parameterName.escapedText, getTypePredicateParameterIndex(func.parameters, parameterName), type); + } + else { + return createThisTypePredicate(type); + } + } + function getTypePredicateParameterIndex(parameterList, parameter) { + for (var i = 0; i < parameterList.length; i++) { + var param = parameterList[i]; + if (param.name.kind === 72 /* Identifier */ && param.name.escapedText === parameter.escapedText) { + return i; + } + } + return -1; + } + function getReturnTypeOfSignature(signature) { + if (!signature.resolvedReturnType) { + if (!pushTypeResolution(signature, 3 /* ResolvedReturnType */)) { + return errorType; + } + var type = signature.target ? instantiateType(getReturnTypeOfSignature(signature.target), signature.mapper) : + signature.unionSignatures ? getUnionType(ts.map(signature.unionSignatures, getReturnTypeOfSignature), 2 /* Subtype */) : + getReturnTypeFromAnnotation(signature.declaration) || + isJSConstructor(signature.declaration) && getJSClassType(getSymbolOfNode(signature.declaration)) || + (ts.nodeIsMissing(signature.declaration.body) ? anyType : getReturnTypeFromBody(signature.declaration)); + if (!popTypeResolution()) { + if (signature.declaration) { + var typeNode = ts.getEffectiveReturnTypeNode(signature.declaration); + if (typeNode) { + error(typeNode, ts.Diagnostics.Return_type_annotation_circularly_references_itself); + } + else if (noImplicitAny) { + var declaration = signature.declaration; + var name = ts.getNameOfDeclaration(declaration); + if (name) { + error(name, ts.Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, ts.declarationNameToString(name)); + } + else { + error(declaration, ts.Diagnostics.Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions); + } + } + } + type = anyType; + } + signature.resolvedReturnType = type; + } + return signature.resolvedReturnType; + } + function getReturnTypeFromAnnotation(declaration) { + if (declaration.kind === 157 /* Constructor */) { + return getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)); + } + if (ts.isJSDocConstructSignature(declaration)) { + return getTypeFromTypeNode(declaration.parameters[0].type); // TODO: GH#18217 + } + var typeNode = ts.getEffectiveReturnTypeNode(declaration); + if (typeNode) { + return getTypeFromTypeNode(typeNode); + } + if (declaration.kind === 158 /* GetAccessor */ && !hasNonBindableDynamicName(declaration)) { + var jsDocType = ts.isInJSFile(declaration) && getTypeForDeclarationFromJSDocComment(declaration); + if (jsDocType) { + return jsDocType; + } + var setter = ts.getDeclarationOfKind(getSymbolOfNode(declaration), 159 /* SetAccessor */); + var setterType = getAnnotatedAccessorType(setter); + if (setterType) { + return setterType; + } + } + return getReturnTypeOfTypeTag(declaration); + } + function isResolvingReturnTypeOfSignature(signature) { + return !signature.resolvedReturnType && findResolutionCycleStartIndex(signature, 3 /* ResolvedReturnType */) >= 0; + } + function getRestTypeOfSignature(signature) { + return tryGetRestTypeOfSignature(signature) || anyType; + } + function tryGetRestTypeOfSignature(signature) { + if (signature.hasRestParameter) { + var sigRestType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); + var restType = isTupleType(sigRestType) ? getRestTypeOfTupleType(sigRestType) : sigRestType; + return restType && getIndexTypeOfType(restType, 1 /* Number */); + } + return undefined; + } + function getSignatureInstantiation(signature, typeArguments, isJavascript) { + return getSignatureInstantiationWithoutFillingInTypeArguments(signature, fillMissingTypeArguments(typeArguments, signature.typeParameters, getMinTypeArgumentCount(signature.typeParameters), isJavascript)); + } + function getSignatureInstantiationWithoutFillingInTypeArguments(signature, typeArguments) { + var instantiations = signature.instantiations || (signature.instantiations = ts.createMap()); + var id = getTypeListId(typeArguments); + var instantiation = instantiations.get(id); + if (!instantiation) { + instantiations.set(id, instantiation = createSignatureInstantiation(signature, typeArguments)); + } + return instantiation; + } + function createSignatureInstantiation(signature, typeArguments) { + return instantiateSignature(signature, createSignatureTypeMapper(signature, typeArguments), /*eraseTypeParameters*/ true); + } + function createSignatureTypeMapper(signature, typeArguments) { + return createTypeMapper(signature.typeParameters, typeArguments); + } + function getErasedSignature(signature) { + return signature.typeParameters ? + signature.erasedSignatureCache || (signature.erasedSignatureCache = createErasedSignature(signature)) : + signature; + } + function createErasedSignature(signature) { + // Create an instantiation of the signature where all type arguments are the any type. + return instantiateSignature(signature, createTypeEraser(signature.typeParameters), /*eraseTypeParameters*/ true); + } + function getCanonicalSignature(signature) { + return signature.typeParameters ? + signature.canonicalSignatureCache || (signature.canonicalSignatureCache = createCanonicalSignature(signature)) : + signature; + } + function createCanonicalSignature(signature) { + // Create an instantiation of the signature where each unconstrained type parameter is replaced with + // its original. When a generic class or interface is instantiated, each generic method in the class or + // interface is instantiated with a fresh set of cloned type parameters (which we need to handle scenarios + // where different generations of the same type parameter are in scope). This leads to a lot of new type + // identities, and potentially a lot of work comparing those identities, so here we create an instantiation + // that uses the original type identities for all unconstrained type parameters. + return getSignatureInstantiation(signature, ts.map(signature.typeParameters, function (tp) { return tp.target && !getConstraintOfTypeParameter(tp.target) ? tp.target : tp; }), ts.isInJSFile(signature.declaration)); + } + function getBaseSignature(signature) { + var typeParameters = signature.typeParameters; + if (typeParameters) { + var typeEraser_1 = createTypeEraser(typeParameters); + var baseConstraints = ts.map(typeParameters, function (tp) { return instantiateType(getBaseConstraintOfType(tp), typeEraser_1) || emptyObjectType; }); + return instantiateSignature(signature, createTypeMapper(typeParameters, baseConstraints), /*eraseTypeParameters*/ true); + } + return signature; + } + function getOrCreateTypeFromSignature(signature) { + // There are two ways to declare a construct signature, one is by declaring a class constructor + // using the constructor keyword, and the other is declaring a bare construct signature in an + // object type literal or interface (using the new keyword). Each way of declaring a constructor + // will result in a different declaration kind. + if (!signature.isolatedSignatureType) { + var isConstructor = signature.declaration.kind === 157 /* Constructor */ || signature.declaration.kind === 161 /* ConstructSignature */; // TODO: GH#18217 + var type = createObjectType(16 /* Anonymous */); + type.members = emptySymbols; + type.properties = ts.emptyArray; + type.callSignatures = !isConstructor ? [signature] : ts.emptyArray; + type.constructSignatures = isConstructor ? [signature] : ts.emptyArray; + signature.isolatedSignatureType = type; + } + return signature.isolatedSignatureType; + } + function getIndexSymbol(symbol) { + return symbol.members.get("__index" /* Index */); + } + function getIndexDeclarationOfSymbol(symbol, kind) { + var syntaxKind = kind === 1 /* Number */ ? 135 /* NumberKeyword */ : 138 /* StringKeyword */; + var indexSymbol = getIndexSymbol(symbol); + if (indexSymbol) { + for (var _i = 0, _a = indexSymbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + var node = ts.cast(decl, ts.isIndexSignatureDeclaration); + if (node.parameters.length === 1) { + var parameter = node.parameters[0]; + if (parameter.type && parameter.type.kind === syntaxKind) { + return node; + } + } + } + } + return undefined; + } + function createIndexInfo(type, isReadonly, declaration) { + return { type: type, isReadonly: isReadonly, declaration: declaration }; + } + function getIndexInfoOfSymbol(symbol, kind) { + var declaration = getIndexDeclarationOfSymbol(symbol, kind); + if (declaration) { + return createIndexInfo(declaration.type ? getTypeFromTypeNode(declaration.type) : anyType, ts.hasModifier(declaration, 64 /* Readonly */), declaration); + } + return undefined; + } + function getConstraintDeclaration(type) { + var decl = type.symbol && ts.getDeclarationOfKind(type.symbol, 150 /* TypeParameter */); + return decl && ts.getEffectiveConstraintOfTypeParameter(decl); + } + function getInferredTypeParameterConstraint(typeParameter) { + var inferences; + if (typeParameter.symbol) { + for (var _i = 0, _a = typeParameter.symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (declaration.parent.kind === 176 /* InferType */) { + // When an 'infer T' declaration is immediately contained in a type reference node + // (such as 'Foo'), T's constraint is inferred from the constraint of the + // corresponding type parameter in 'Foo'. When multiple 'infer T' declarations are + // present, we form an intersection of the inferred constraint types. + var grandParent = declaration.parent.parent; + if (grandParent.kind === 164 /* TypeReference */) { + var typeReference = grandParent; + var typeParameters = getTypeParametersForTypeReference(typeReference); + if (typeParameters) { + var index = typeReference.typeArguments.indexOf(declaration.parent); + if (index < typeParameters.length) { + var declaredConstraint = getConstraintOfTypeParameter(typeParameters[index]); + if (declaredConstraint) { + // Type parameter constraints can reference other type parameters so + // constraints need to be instantiated. If instantiation produces the + // type parameter itself, we discard that inference. For example, in + // type Foo = [T, U]; + // type Bar = T extends Foo ? Foo : T; + // the instantiated constraint for U is X, so we discard that inference. + var mapper = createTypeMapper(typeParameters, getEffectiveTypeArguments(typeReference, typeParameters)); + var constraint = instantiateType(declaredConstraint, mapper); + if (constraint !== typeParameter) { + inferences = ts.append(inferences, constraint); + } + } + } + } + } + // When an 'infer T' declaration is immediately contained in a rest parameter + // declaration, we infer an 'unknown[]' constraint. + else if (grandParent.kind === 151 /* Parameter */ && grandParent.dotDotDotToken) { + inferences = ts.append(inferences, createArrayType(unknownType)); + } + } + } + } + return inferences && getIntersectionType(inferences); + } + /** This is a worker function. Use getConstraintOfTypeParameter which guards against circular constraints. */ + function getConstraintFromTypeParameter(typeParameter) { + if (!typeParameter.constraint) { + if (typeParameter.target) { + var targetConstraint = getConstraintOfTypeParameter(typeParameter.target); + typeParameter.constraint = targetConstraint ? instantiateType(targetConstraint, typeParameter.mapper) : noConstraintType; + } + else { + var constraintDeclaration = getConstraintDeclaration(typeParameter); + typeParameter.constraint = constraintDeclaration ? getTypeFromTypeNode(constraintDeclaration) : + getInferredTypeParameterConstraint(typeParameter) || noConstraintType; + } + } + return typeParameter.constraint === noConstraintType ? undefined : typeParameter.constraint; + } + function getParentSymbolOfTypeParameter(typeParameter) { + var tp = ts.getDeclarationOfKind(typeParameter.symbol, 150 /* TypeParameter */); + var host = ts.isJSDocTemplateTag(tp.parent) ? ts.getHostSignatureFromJSDoc(tp.parent) : tp.parent; + return host && getSymbolOfNode(host); + } + function getTypeListId(types) { + var result = ""; + if (types) { + var length_3 = types.length; + var i = 0; + while (i < length_3) { + var startId = types[i].id; + var count = 1; + while (i + count < length_3 && types[i + count].id === startId + count) { + count++; + } + if (result.length) { + result += ","; + } + result += startId; + if (count > 1) { + result += ":" + count; + } + i += count; + } + } + return result; + } + // This function is used to propagate certain flags when creating new object type references and union types. + // It is only necessary to do so if a constituent type might be the undefined type, the null type, the type + // of an object literal or the anyFunctionType. This is because there are operations in the type checker + // that care about the presence of such types at arbitrary depth in a containing type. + function getPropagatingFlagsOfTypes(types, excludeKinds) { + var result = 0; + for (var _i = 0, types_5 = types; _i < types_5.length; _i++) { + var type = types_5[_i]; + if (!(type.flags & excludeKinds)) { + result |= type.flags; + } + } + return result & 939524096 /* PropagatingFlags */; + } + function createTypeReference(target, typeArguments) { + var id = getTypeListId(typeArguments); + var type = target.instantiations.get(id); + if (!type) { + type = createObjectType(4 /* Reference */, target.symbol); + target.instantiations.set(id, type); + type.flags |= typeArguments ? getPropagatingFlagsOfTypes(typeArguments, /*excludeKinds*/ 0) : 0; + type.target = target; + type.typeArguments = typeArguments; + } + return type; + } + function cloneTypeReference(source) { + var type = createType(source.flags); + type.symbol = source.symbol; + type.objectFlags = source.objectFlags; + type.target = source.target; + type.typeArguments = source.typeArguments; + return type; + } + function getTypeReferenceArity(type) { + return ts.length(type.target.typeParameters); + } + /** + * Get type from type-reference that reference to class or interface + */ + function getTypeFromClassOrInterfaceReference(node, symbol, typeArgs) { + var type = getDeclaredTypeOfSymbol(getMergedSymbol(symbol)); + var typeParameters = type.localTypeParameters; + if (typeParameters) { + var numTypeArguments = ts.length(node.typeArguments); + var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters); + var isJs = ts.isInJSFile(node); + var isJsImplicitAny = !noImplicitAny && isJs; + if (!isJsImplicitAny && (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length)) { + var missingAugmentsTag = isJs && ts.isExpressionWithTypeArguments(node) && !ts.isJSDocAugmentsTag(node.parent); + var diag = minTypeArgumentCount === typeParameters.length + ? missingAugmentsTag + ? ts.Diagnostics.Expected_0_type_arguments_provide_these_with_an_extends_tag + : ts.Diagnostics.Generic_type_0_requires_1_type_argument_s + : missingAugmentsTag + ? ts.Diagnostics.Expected_0_1_type_arguments_provide_these_with_an_extends_tag + : ts.Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments; + var typeStr = typeToString(type, /*enclosingDeclaration*/ undefined, 2 /* WriteArrayAsGenericType */); + error(node, diag, typeStr, minTypeArgumentCount, typeParameters.length); + if (!isJs) { + // TODO: Adopt same permissive behavior in TS as in JS to reduce follow-on editing experience failures (requires editing fillMissingTypeArguments) + return errorType; + } + } + // In a type reference, the outer type parameters of the referenced class or interface are automatically + // supplied as type arguments and the type reference only specifies arguments for the local type parameters + // of the class or interface. + var typeArguments = ts.concatenate(type.outerTypeParameters, fillMissingTypeArguments(typeArgs, typeParameters, minTypeArgumentCount, isJs)); + return createTypeReference(type, typeArguments); + } + return checkNoTypeArguments(node, symbol) ? type : errorType; + } + function getTypeAliasInstantiation(symbol, typeArguments) { + var type = getDeclaredTypeOfSymbol(symbol); + var links = getSymbolLinks(symbol); + var typeParameters = links.typeParameters; + var id = getTypeListId(typeArguments); + var instantiation = links.instantiations.get(id); + if (!instantiation) { + links.instantiations.set(id, instantiation = instantiateType(type, createTypeMapper(typeParameters, fillMissingTypeArguments(typeArguments, typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJSFile(symbol.valueDeclaration))))); + } + return instantiation; + } + /** + * Get type from reference to type alias. When a type alias is generic, the declared type of the type alias may include + * references to the type parameters of the alias. We replace those with the actual type arguments by instantiating the + * declared type. Instantiations are cached using the type identities of the type arguments as the key. + */ + function getTypeFromTypeAliasReference(node, symbol, typeArguments) { + var type = getDeclaredTypeOfSymbol(symbol); + var typeParameters = getSymbolLinks(symbol).typeParameters; + if (typeParameters) { + var numTypeArguments = ts.length(node.typeArguments); + var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters); + if (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length) { + error(node, minTypeArgumentCount === typeParameters.length + ? ts.Diagnostics.Generic_type_0_requires_1_type_argument_s + : ts.Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments, symbolToString(symbol), minTypeArgumentCount, typeParameters.length); + return errorType; + } + return getTypeAliasInstantiation(symbol, typeArguments); + } + return checkNoTypeArguments(node, symbol) ? type : errorType; + } + function getTypeReferenceName(node) { + switch (node.kind) { + case 164 /* TypeReference */: + return node.typeName; + case 211 /* ExpressionWithTypeArguments */: + // We only support expressions that are simple qualified names. For other + // expressions this produces undefined. + var expr = node.expression; + if (ts.isEntityNameExpression(expr)) { + return expr; + } + // fall through; + } + return undefined; + } + function resolveTypeReferenceName(typeReferenceName, meaning) { + if (!typeReferenceName) { + return unknownSymbol; + } + return resolveEntityName(typeReferenceName, meaning) || unknownSymbol; + } + function getTypeReferenceType(node, symbol) { + var typeArguments = typeArgumentsFromTypeReferenceNode(node); // Do unconditionally so we mark type arguments as referenced. + if (symbol === unknownSymbol) { + return errorType; + } + var type = getTypeReferenceTypeWorker(node, symbol, typeArguments); + if (type) { + return type; + } + // JS enums are 'string' or 'number', not an enum type. + var enumTag = ts.isInJSFile(node) && symbol.valueDeclaration && ts.getJSDocEnumTag(symbol.valueDeclaration); + if (enumTag) { + var links = getNodeLinks(enumTag); + if (!pushTypeResolution(enumTag, 5 /* EnumTagType */)) { + return errorType; + } + var type_4 = enumTag.typeExpression ? getTypeFromTypeNode(enumTag.typeExpression) : errorType; + if (!popTypeResolution()) { + type_4 = errorType; + error(node, ts.Diagnostics.Enum_type_0_circularly_references_itself, symbolToString(symbol)); + } + return (links.resolvedEnumType = type_4); + } + // Get type from reference to named type that cannot be generic (enum or type parameter) + var res = tryGetDeclaredTypeOfSymbol(symbol); + if (res) { + return checkNoTypeArguments(node, symbol) ? + res.flags & 262144 /* TypeParameter */ ? getConstrainedTypeVariable(res, node) : getRegularTypeOfLiteralType(res) : + errorType; + } + if (!(symbol.flags & 67220415 /* Value */ && isJSDocTypeReference(node))) { + return errorType; + } + var jsdocType = getJSDocTypeReference(node, symbol, typeArguments); + if (jsdocType) { + return jsdocType; + } + // Resolve the type reference as a Type for the purpose of reporting errors. + resolveTypeReferenceName(getTypeReferenceName(node), 67897832 /* Type */); + return getTypeOfSymbol(symbol); + } + /** + * A jsdoc TypeReference may have resolved to a value (as opposed to a type). If + * the symbol is a constructor function, return the inferred class type; otherwise, + * the type of this reference is just the type of the value we resolved to. + */ + function getJSDocTypeReference(node, symbol, typeArguments) { + if (!pushTypeResolution(symbol, 6 /* JSDocTypeReference */)) { + return errorType; + } + var assignedType = getAssignedClassType(symbol); + var valueType = getTypeOfSymbol(symbol); + var referenceType = valueType.symbol && valueType.symbol !== symbol && !isInferredClassType(valueType) && getTypeReferenceTypeWorker(node, valueType.symbol, typeArguments); + if (!popTypeResolution()) { + getSymbolLinks(symbol).resolvedJSDocType = errorType; + error(node, ts.Diagnostics.JSDoc_type_0_circularly_references_itself, symbolToString(symbol)); + return errorType; + } + if (referenceType || assignedType) { + // TODO: GH#18217 (should the `|| assignedType` be at a lower precedence?) + var type = (referenceType && assignedType ? getIntersectionType([assignedType, referenceType]) : referenceType || assignedType); + return getSymbolLinks(symbol).resolvedJSDocType = type; + } + } + function getTypeReferenceTypeWorker(node, symbol, typeArguments) { + if (symbol.flags & (32 /* Class */ | 64 /* Interface */)) { + if (symbol.valueDeclaration && ts.isBinaryExpression(symbol.valueDeclaration.parent)) { + var jsdocType = getJSDocTypeReference(node, symbol, typeArguments); + if (jsdocType) { + return jsdocType; + } + } + return getTypeFromClassOrInterfaceReference(node, symbol, typeArguments); + } + if (symbol.flags & 524288 /* TypeAlias */) { + return getTypeFromTypeAliasReference(node, symbol, typeArguments); + } + if (symbol.flags & 16 /* Function */ && + isJSDocTypeReference(node) && + (symbol.members || ts.getJSDocClassTag(symbol.valueDeclaration))) { + return getInferredClassType(symbol); + } + } + function getSubstitutionType(typeVariable, substitute) { + var result = createType(33554432 /* Substitution */); + result.typeVariable = typeVariable; + result.substitute = substitute; + return result; + } + function isUnaryTupleTypeNode(node) { + return node.kind === 170 /* TupleType */ && node.elementTypes.length === 1; + } + function getImpliedConstraint(typeVariable, checkNode, extendsNode) { + return isUnaryTupleTypeNode(checkNode) && isUnaryTupleTypeNode(extendsNode) ? getImpliedConstraint(typeVariable, checkNode.elementTypes[0], extendsNode.elementTypes[0]) : + getActualTypeVariable(getTypeFromTypeNode(checkNode)) === typeVariable ? getTypeFromTypeNode(extendsNode) : + undefined; + } + function getConstrainedTypeVariable(typeVariable, node) { + var constraints; + while (node && !ts.isStatement(node) && node.kind !== 291 /* JSDocComment */) { + var parent = node.parent; + if (parent.kind === 175 /* ConditionalType */ && node === parent.trueType) { + var constraint = getImpliedConstraint(typeVariable, parent.checkType, parent.extendsType); + if (constraint) { + constraints = ts.append(constraints, constraint); + } + } + node = parent; + } + return constraints ? getSubstitutionType(typeVariable, getIntersectionType(ts.append(constraints, typeVariable))) : typeVariable; + } + function isJSDocTypeReference(node) { + return !!(node.flags & 2097152 /* JSDoc */) && (node.kind === 164 /* TypeReference */ || node.kind === 183 /* ImportType */); + } + function checkNoTypeArguments(node, symbol) { + if (node.typeArguments) { + error(node, ts.Diagnostics.Type_0_is_not_generic, symbol ? symbolToString(symbol) : node.typeName ? ts.declarationNameToString(node.typeName) : "(anonymous)"); + return false; + } + return true; + } + function getIntendedTypeFromJSDocTypeReference(node) { + if (ts.isIdentifier(node.typeName)) { + var typeArgs = node.typeArguments; + switch (node.typeName.escapedText) { + case "String": + checkNoTypeArguments(node); + return stringType; + case "Number": + checkNoTypeArguments(node); + return numberType; + case "Boolean": + checkNoTypeArguments(node); + return booleanType; + case "Void": + checkNoTypeArguments(node); + return voidType; + case "Undefined": + checkNoTypeArguments(node); + return undefinedType; + case "Null": + checkNoTypeArguments(node); + return nullType; + case "Function": + case "function": + checkNoTypeArguments(node); + return globalFunctionType; + case "Array": + case "array": + return !typeArgs || !typeArgs.length ? anyArrayType : undefined; + case "Promise": + case "promise": + return !typeArgs || !typeArgs.length ? createPromiseType(anyType) : undefined; + case "Object": + if (typeArgs && typeArgs.length === 2) { + if (ts.isJSDocIndexSignature(node)) { + var indexed = getTypeFromTypeNode(typeArgs[0]); + var target = getTypeFromTypeNode(typeArgs[1]); + var index = createIndexInfo(target, /*isReadonly*/ false); + return createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, indexed === stringType ? index : undefined, indexed === numberType ? index : undefined); + } + return anyType; + } + checkNoTypeArguments(node); + return anyType; + } + } + } + function getTypeFromJSDocNullableTypeNode(node) { + var type = getTypeFromTypeNode(node.type); + return strictNullChecks ? getNullableType(type, 65536 /* Null */) : type; + } + function getTypeFromTypeReference(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + var symbol = void 0; + var type = void 0; + var meaning = 67897832 /* Type */; + if (isJSDocTypeReference(node)) { + type = getIntendedTypeFromJSDocTypeReference(node); + meaning |= 67220415 /* Value */; + } + if (!type) { + symbol = resolveTypeReferenceName(getTypeReferenceName(node), meaning); + type = getTypeReferenceType(node, symbol); + } + // Cache both the resolved symbol and the resolved type. The resolved symbol is needed when we check the + // type reference in checkTypeReferenceNode. + links.resolvedSymbol = symbol; + links.resolvedType = type; + } + return links.resolvedType; + } + function typeArgumentsFromTypeReferenceNode(node) { + return ts.map(node.typeArguments, getTypeFromTypeNode); + } + function getTypeFromTypeQueryNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + // TypeScript 1.0 spec (April 2014): 3.6.3 + // The expression is processed as an identifier expression (section 4.3) + // or property access expression(section 4.10), + // the widened type(section 3.9) of which becomes the result. + links.resolvedType = getRegularTypeOfLiteralType(getWidenedType(checkExpression(node.exprName))); + } + return links.resolvedType; + } + function getTypeOfGlobalSymbol(symbol, arity) { + function getTypeDeclaration(symbol) { + var declarations = symbol.declarations; + for (var _i = 0, declarations_3 = declarations; _i < declarations_3.length; _i++) { + var declaration = declarations_3[_i]; + switch (declaration.kind) { + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + case 243 /* EnumDeclaration */: + return declaration; + } + } + } + if (!symbol) { + return arity ? emptyGenericType : emptyObjectType; + } + var type = getDeclaredTypeOfSymbol(symbol); + if (!(type.flags & 524288 /* Object */)) { + error(getTypeDeclaration(symbol), ts.Diagnostics.Global_type_0_must_be_a_class_or_interface_type, ts.symbolName(symbol)); + return arity ? emptyGenericType : emptyObjectType; + } + if (ts.length(type.typeParameters) !== arity) { + error(getTypeDeclaration(symbol), ts.Diagnostics.Global_type_0_must_have_1_type_parameter_s, ts.symbolName(symbol), arity); + return arity ? emptyGenericType : emptyObjectType; + } + return type; + } + function getGlobalValueSymbol(name, reportErrors) { + return getGlobalSymbol(name, 67220415 /* Value */, reportErrors ? ts.Diagnostics.Cannot_find_global_value_0 : undefined); + } + function getGlobalTypeSymbol(name, reportErrors) { + return getGlobalSymbol(name, 67897832 /* Type */, reportErrors ? ts.Diagnostics.Cannot_find_global_type_0 : undefined); + } + function getGlobalSymbol(name, meaning, diagnostic) { + // Don't track references for global symbols anyway, so value if `isReference` is arbitrary + return resolveName(undefined, name, meaning, diagnostic, name, /*isUse*/ false); + } + function getGlobalType(name, arity, reportErrors) { + var symbol = getGlobalTypeSymbol(name, reportErrors); + return symbol || reportErrors ? getTypeOfGlobalSymbol(symbol, arity) : undefined; + } + function getGlobalTypedPropertyDescriptorType() { + return deferredGlobalTypedPropertyDescriptorType || (deferredGlobalTypedPropertyDescriptorType = getGlobalType("TypedPropertyDescriptor", /*arity*/ 1, /*reportErrors*/ true)) || emptyGenericType; + } + function getGlobalTemplateStringsArrayType() { + return deferredGlobalTemplateStringsArrayType || (deferredGlobalTemplateStringsArrayType = getGlobalType("TemplateStringsArray", /*arity*/ 0, /*reportErrors*/ true)) || emptyObjectType; + } + function getGlobalImportMetaType() { + return deferredGlobalImportMetaType || (deferredGlobalImportMetaType = getGlobalType("ImportMeta", /*arity*/ 0, /*reportErrors*/ true)) || emptyObjectType; + } + function getGlobalESSymbolConstructorSymbol(reportErrors) { + return deferredGlobalESSymbolConstructorSymbol || (deferredGlobalESSymbolConstructorSymbol = getGlobalValueSymbol("Symbol", reportErrors)); + } + function getGlobalESSymbolType(reportErrors) { + return deferredGlobalESSymbolType || (deferredGlobalESSymbolType = getGlobalType("Symbol", /*arity*/ 0, reportErrors)) || emptyObjectType; + } + function getGlobalPromiseType(reportErrors) { + return deferredGlobalPromiseType || (deferredGlobalPromiseType = getGlobalType("Promise", /*arity*/ 1, reportErrors)) || emptyGenericType; + } + function getGlobalPromiseLikeType(reportErrors) { + return deferredGlobalPromiseLikeType || (deferredGlobalPromiseLikeType = getGlobalType("PromiseLike", /*arity*/ 1, reportErrors)) || emptyGenericType; + } + function getGlobalPromiseConstructorSymbol(reportErrors) { + return deferredGlobalPromiseConstructorSymbol || (deferredGlobalPromiseConstructorSymbol = getGlobalValueSymbol("Promise", reportErrors)); + } + function getGlobalPromiseConstructorLikeType(reportErrors) { + return deferredGlobalPromiseConstructorLikeType || (deferredGlobalPromiseConstructorLikeType = getGlobalType("PromiseConstructorLike", /*arity*/ 0, reportErrors)) || emptyObjectType; + } + function getGlobalAsyncIterableType(reportErrors) { + return deferredGlobalAsyncIterableType || (deferredGlobalAsyncIterableType = getGlobalType("AsyncIterable", /*arity*/ 1, reportErrors)) || emptyGenericType; + } + function getGlobalAsyncIteratorType(reportErrors) { + return deferredGlobalAsyncIteratorType || (deferredGlobalAsyncIteratorType = getGlobalType("AsyncIterator", /*arity*/ 1, reportErrors)) || emptyGenericType; + } + function getGlobalAsyncIterableIteratorType(reportErrors) { + return deferredGlobalAsyncIterableIteratorType || (deferredGlobalAsyncIterableIteratorType = getGlobalType("AsyncIterableIterator", /*arity*/ 1, reportErrors)) || emptyGenericType; + } + function getGlobalIterableType(reportErrors) { + return deferredGlobalIterableType || (deferredGlobalIterableType = getGlobalType("Iterable", /*arity*/ 1, reportErrors)) || emptyGenericType; + } + function getGlobalIteratorType(reportErrors) { + return deferredGlobalIteratorType || (deferredGlobalIteratorType = getGlobalType("Iterator", /*arity*/ 1, reportErrors)) || emptyGenericType; + } + function getGlobalIterableIteratorType(reportErrors) { + return deferredGlobalIterableIteratorType || (deferredGlobalIterableIteratorType = getGlobalType("IterableIterator", /*arity*/ 1, reportErrors)) || emptyGenericType; + } + function getGlobalTypeOrUndefined(name, arity) { + if (arity === void 0) { arity = 0; } + var symbol = getGlobalSymbol(name, 67897832 /* Type */, /*diagnostic*/ undefined); + return symbol && getTypeOfGlobalSymbol(symbol, arity); + } + function getGlobalExtractSymbol() { + return deferredGlobalExtractSymbol || (deferredGlobalExtractSymbol = getGlobalSymbol("Extract", 524288 /* TypeAlias */, ts.Diagnostics.Cannot_find_global_type_0)); // TODO: GH#18217 + } + function getGlobalExcludeSymbol() { + return deferredGlobalExcludeSymbol || (deferredGlobalExcludeSymbol = getGlobalSymbol("Exclude", 524288 /* TypeAlias */, ts.Diagnostics.Cannot_find_global_type_0)); // TODO: GH#18217 + } + function getGlobalPickSymbol() { + return deferredGlobalPickSymbol || (deferredGlobalPickSymbol = getGlobalSymbol("Pick", 524288 /* TypeAlias */, ts.Diagnostics.Cannot_find_global_type_0)); // TODO: GH#18217 + } + function getGlobalBigIntType(reportErrors) { + return deferredGlobalBigIntType || (deferredGlobalBigIntType = getGlobalType("BigInt", /*arity*/ 0, reportErrors)) || emptyObjectType; + } + /** + * Instantiates a global type that is generic with some element type, and returns that instantiation. + */ + function createTypeFromGenericGlobalType(genericGlobalType, typeArguments) { + return genericGlobalType !== emptyGenericType ? createTypeReference(genericGlobalType, typeArguments) : emptyObjectType; + } + function createTypedPropertyDescriptorType(propertyType) { + return createTypeFromGenericGlobalType(getGlobalTypedPropertyDescriptorType(), [propertyType]); + } + function createAsyncIterableType(iteratedType) { + return createTypeFromGenericGlobalType(getGlobalAsyncIterableType(/*reportErrors*/ true), [iteratedType]); + } + function createAsyncIterableIteratorType(iteratedType) { + return createTypeFromGenericGlobalType(getGlobalAsyncIterableIteratorType(/*reportErrors*/ true), [iteratedType]); + } + function createIterableType(iteratedType) { + return createTypeFromGenericGlobalType(getGlobalIterableType(/*reportErrors*/ true), [iteratedType]); + } + function createIterableIteratorType(iteratedType) { + return createTypeFromGenericGlobalType(getGlobalIterableIteratorType(/*reportErrors*/ true), [iteratedType]); + } + function createArrayType(elementType) { + return createTypeFromGenericGlobalType(globalArrayType, [elementType]); + } + function createReadonlyArrayType(elementType) { + return createTypeFromGenericGlobalType(globalReadonlyArrayType, [elementType]); + } + function getTypeFromArrayTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + links.resolvedType = createArrayType(getTypeFromTypeNode(node.elementType)); + } + return links.resolvedType; + } + // We represent tuple types as type references to synthesized generic interface types created by + // this function. The types are of the form: + // + // interface Tuple extends Array { 0: T0, 1: T1, 2: T2, ... } + // + // Note that the generic type created by this function has no symbol associated with it. The same + // is true for each of the synthesized type parameters. + function createTupleTypeOfArity(arity, minLength, hasRestElement, associatedNames) { + var typeParameters; + var properties = []; + var maxLength = hasRestElement ? arity - 1 : arity; + if (arity) { + typeParameters = new Array(arity); + for (var i = 0; i < arity; i++) { + var typeParameter = typeParameters[i] = createType(262144 /* TypeParameter */); + if (i < maxLength) { + var property = createSymbol(4 /* Property */ | (i >= minLength ? 16777216 /* Optional */ : 0), "" + i); + property.type = typeParameter; + properties.push(property); + } + } + } + var literalTypes = []; + for (var i = minLength; i <= maxLength; i++) + literalTypes.push(getLiteralType(i)); + var lengthSymbol = createSymbol(4 /* Property */, "length"); + lengthSymbol.type = hasRestElement ? numberType : getUnionType(literalTypes); + properties.push(lengthSymbol); + var type = createObjectType(8 /* Tuple */ | 4 /* Reference */); + type.typeParameters = typeParameters; + type.outerTypeParameters = undefined; + type.localTypeParameters = typeParameters; + type.instantiations = ts.createMap(); + type.instantiations.set(getTypeListId(type.typeParameters), type); + type.target = type; + type.typeArguments = type.typeParameters; + type.thisType = createType(262144 /* TypeParameter */); + type.thisType.isThisType = true; + type.thisType.constraint = type; + type.declaredProperties = properties; + type.declaredCallSignatures = ts.emptyArray; + type.declaredConstructSignatures = ts.emptyArray; + type.declaredStringIndexInfo = undefined; + type.declaredNumberIndexInfo = undefined; + type.minLength = minLength; + type.hasRestElement = hasRestElement; + type.associatedNames = associatedNames; + return type; + } + function getTupleTypeOfArity(arity, minLength, hasRestElement, associatedNames) { + var key = arity + (hasRestElement ? "+" : ",") + minLength + (associatedNames && associatedNames.length ? "," + associatedNames.join(",") : ""); + var type = tupleTypes.get(key); + if (!type) { + tupleTypes.set(key, type = createTupleTypeOfArity(arity, minLength, hasRestElement, associatedNames)); + } + return type; + } + function createTupleType(elementTypes, minLength, hasRestElement, associatedNames) { + if (minLength === void 0) { minLength = elementTypes.length; } + if (hasRestElement === void 0) { hasRestElement = false; } + var arity = elementTypes.length; + if (arity === 1 && hasRestElement) { + return createArrayType(elementTypes[0]); + } + var tupleType = getTupleTypeOfArity(arity, minLength, arity > 0 && hasRestElement, associatedNames); + return elementTypes.length ? createTypeReference(tupleType, elementTypes) : tupleType; + } + function getTypeFromTupleTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + var lastElement = ts.lastOrUndefined(node.elementTypes); + var restElement_1 = lastElement && lastElement.kind === 172 /* RestType */ ? lastElement : undefined; + var minLength = ts.findLastIndex(node.elementTypes, function (n) { return n.kind !== 171 /* OptionalType */ && n !== restElement_1; }) + 1; + var elementTypes = ts.map(node.elementTypes, function (n) { + var type = getTypeFromTypeNode(n); + return n === restElement_1 && getIndexTypeOfType(type, 1 /* Number */) || type; + }); + links.resolvedType = createTupleType(elementTypes, minLength, !!restElement_1); + } + return links.resolvedType; + } + function sliceTupleType(type, index) { + var tuple = type.target; + if (tuple.hasRestElement) { + // don't slice off rest element + index = Math.min(index, getTypeReferenceArity(type) - 1); + } + return createTupleType((type.typeArguments || ts.emptyArray).slice(index), Math.max(0, tuple.minLength - index), tuple.hasRestElement, tuple.associatedNames && tuple.associatedNames.slice(index)); + } + function getTypeFromOptionalTypeNode(node) { + var type = getTypeFromTypeNode(node.type); + return strictNullChecks ? getOptionalType(type) : type; + } + function getTypeId(type) { + return type.id; + } + function containsType(types, type) { + return ts.binarySearch(types, type, getTypeId, ts.compareValues) >= 0; + } + function insertType(types, type) { + var index = ts.binarySearch(types, type, getTypeId, ts.compareValues); + if (index < 0) { + types.splice(~index, 0, type); + return true; + } + return false; + } + // Return true if the given intersection type contains + // more than one unit type or, + // an object type and a nullable type (null or undefined), or + // a string-like type and a type known to be non-string-like, or + // a number-like type and a type known to be non-number-like, or + // a symbol-like type and a type known to be non-symbol-like, or + // a void-like type and a type known to be non-void-like, or + // a non-primitive type and a type known to be primitive. + function isEmptyIntersectionType(type) { + var combined = 0; + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (t.flags & 109440 /* Unit */ && combined & 109440 /* Unit */) { + return true; + } + combined |= t.flags; + if (combined & 98304 /* Nullable */ && combined & (524288 /* Object */ | 67108864 /* NonPrimitive */) || + combined & 67108864 /* NonPrimitive */ && combined & (67238908 /* DisjointDomains */ & ~67108864 /* NonPrimitive */) || + combined & 132 /* StringLike */ && combined & (67238908 /* DisjointDomains */ & ~132 /* StringLike */) || + combined & 296 /* NumberLike */ && combined & (67238908 /* DisjointDomains */ & ~296 /* NumberLike */) || + combined & 2112 /* BigIntLike */ && combined & (67238908 /* DisjointDomains */ & ~2112 /* BigIntLike */) || + combined & 12288 /* ESSymbolLike */ && combined & (67238908 /* DisjointDomains */ & ~12288 /* ESSymbolLike */) || + combined & 49152 /* VoidLike */ && combined & (67238908 /* DisjointDomains */ & ~49152 /* VoidLike */)) { + return true; + } + } + return false; + } + function addTypeToUnion(typeSet, includes, type) { + var flags = type.flags; + if (flags & 1048576 /* Union */) { + return addTypesToUnion(typeSet, includes, type.types); + } + // We ignore 'never' types in unions. Likewise, we ignore intersections of unit types as they are + // another form of 'never' (in that they have an empty value domain). We could in theory turn + // intersections of unit types into 'never' upon construction, but deferring the reduction makes it + // easier to reason about their origin. + if (!(flags & 131072 /* Never */ || flags & 2097152 /* Intersection */ && isEmptyIntersectionType(type))) { + includes |= flags & ~939524096 /* ConstructionFlags */; + if (type === wildcardType) + includes |= 268435456 /* Wildcard */; + if (!strictNullChecks && flags & 98304 /* Nullable */) { + if (!(flags & 134217728 /* ContainsWideningType */)) + includes |= 134217728 /* NonWideningType */; + } + else { + var len = typeSet.length; + var index = len && type.id > typeSet[len - 1].id ? ~len : ts.binarySearch(typeSet, type, getTypeId, ts.compareValues); + if (index < 0) { + typeSet.splice(~index, 0, type); + } + } + } + return includes; + } + // Add the given types to the given type set. Order is preserved, duplicates are removed, + // and nested types of the given kind are flattened into the set. + function addTypesToUnion(typeSet, includes, types) { + for (var _i = 0, types_6 = types; _i < types_6.length; _i++) { + var type = types_6[_i]; + includes = addTypeToUnion(typeSet, includes, type); + } + return includes; + } + function isSubtypeOfAny(source, targets) { + for (var _i = 0, targets_1 = targets; _i < targets_1.length; _i++) { + var target = targets_1[_i]; + if (source !== target && isTypeSubtypeOf(source, target) && (!(ts.getObjectFlags(getTargetType(source)) & 1 /* Class */) || + !(ts.getObjectFlags(getTargetType(target)) & 1 /* Class */) || + isTypeDerivedFrom(source, target))) { + return true; + } + } + return false; + } + function isSetOfLiteralsFromSameEnum(types) { + var first = types[0]; + if (first.flags & 1024 /* EnumLiteral */) { + var firstEnum = getParentOfSymbol(first.symbol); + for (var i = 1; i < types.length; i++) { + var other = types[i]; + if (!(other.flags & 1024 /* EnumLiteral */) || (firstEnum !== getParentOfSymbol(other.symbol))) { + return false; + } + } + return true; + } + return false; + } + function removeSubtypes(types) { + if (types.length === 0 || isSetOfLiteralsFromSameEnum(types)) { + return; + } + var i = types.length; + while (i > 0) { + i--; + if (isSubtypeOfAny(types[i], types)) { + ts.orderedRemoveItemAt(types, i); + } + } + } + function removeRedundantLiteralTypes(types, includes) { + var i = types.length; + while (i > 0) { + i--; + var t = types[i]; + var remove = t.flags & 128 /* StringLiteral */ && includes & 4 /* String */ || + t.flags & 256 /* NumberLiteral */ && includes & 8 /* Number */ || + t.flags & 2048 /* BigIntLiteral */ && includes & 64 /* BigInt */ || + t.flags & 8192 /* UniqueESSymbol */ && includes & 4096 /* ESSymbol */ || + isFreshLiteralType(t) && containsType(types, t.regularType); + if (remove) { + ts.orderedRemoveItemAt(types, i); + } + } + } + // We sort and deduplicate the constituent types based on object identity. If the subtypeReduction + // flag is specified we also reduce the constituent type set to only include types that aren't subtypes + // of other types. Subtype reduction is expensive for large union types and is possible only when union + // types are known not to circularly reference themselves (as is the case with union types created by + // expression constructs such as array literals and the || and ?: operators). Named types can + // circularly reference themselves and therefore cannot be subtype reduced during their declaration. + // For example, "type Item = string | (() => Item" is a named type that circularly references itself. + function getUnionType(types, unionReduction, aliasSymbol, aliasTypeArguments) { + if (unionReduction === void 0) { unionReduction = 1 /* Literal */; } + if (types.length === 0) { + return neverType; + } + if (types.length === 1) { + return types[0]; + } + var typeSet = []; + var includes = addTypesToUnion(typeSet, 0, types); + if (unionReduction !== 0 /* None */) { + if (includes & 3 /* AnyOrUnknown */) { + return includes & 1 /* Any */ ? includes & 268435456 /* Wildcard */ ? wildcardType : anyType : unknownType; + } + switch (unionReduction) { + case 1 /* Literal */: + if (includes & 8576 /* StringOrNumberLiteralOrUnique */ | 512 /* BooleanLiteral */) { + removeRedundantLiteralTypes(typeSet, includes); + } + break; + case 2 /* Subtype */: + removeSubtypes(typeSet); + break; + } + if (typeSet.length === 0) { + return includes & 65536 /* Null */ ? includes & 134217728 /* NonWideningType */ ? nullType : nullWideningType : + includes & 32768 /* Undefined */ ? includes & 134217728 /* NonWideningType */ ? undefinedType : undefinedWideningType : + neverType; + } + } + return getUnionTypeFromSortedList(typeSet, !(includes & 66994211 /* NotPrimitiveUnion */), aliasSymbol, aliasTypeArguments); + } + function getUnionTypePredicate(signatures) { + var first; + var types = []; + for (var _i = 0, signatures_2 = signatures; _i < signatures_2.length; _i++) { + var sig = signatures_2[_i]; + var pred = getTypePredicateOfSignature(sig); + if (!pred) { + continue; + } + if (first) { + if (!typePredicateKindsMatch(first, pred)) { + // No common type predicate. + return undefined; + } + } + else { + first = pred; + } + types.push(pred.type); + } + if (!first) { + // No union signatures had a type predicate. + return undefined; + } + var unionType = getUnionType(types); + return ts.isIdentifierTypePredicate(first) + ? createIdentifierTypePredicate(first.parameterName, first.parameterIndex, unionType) + : createThisTypePredicate(unionType); + } + function typePredicateKindsMatch(a, b) { + return ts.isIdentifierTypePredicate(a) + ? ts.isIdentifierTypePredicate(b) && a.parameterIndex === b.parameterIndex + : !ts.isIdentifierTypePredicate(b); + } + // This function assumes the constituent type list is sorted and deduplicated. + function getUnionTypeFromSortedList(types, primitiveTypesOnly, aliasSymbol, aliasTypeArguments) { + if (types.length === 0) { + return neverType; + } + if (types.length === 1) { + return types[0]; + } + var id = getTypeListId(types); + var type = unionTypes.get(id); + if (!type) { + var propagatedFlags = getPropagatingFlagsOfTypes(types, /*excludeKinds*/ 98304 /* Nullable */); + type = createType(1048576 /* Union */ | propagatedFlags); + unionTypes.set(id, type); + type.types = types; + type.primitiveTypesOnly = primitiveTypesOnly; + /* + Note: This is the alias symbol (or lack thereof) that we see when we first encounter this union type. + For aliases of identical unions, eg `type T = A | B; type U = A | B`, the symbol of the first alias encountered is the aliasSymbol. + (In the language service, the order may depend on the order in which a user takes actions, such as hovering over symbols.) + It's important that we create equivalent union types only once, so that's an unfortunate side effect. + */ + type.aliasSymbol = aliasSymbol; + type.aliasTypeArguments = aliasTypeArguments; + } + return type; + } + function getTypeFromUnionTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + var aliasSymbol = getAliasSymbolForTypeNode(node); + links.resolvedType = getUnionType(ts.map(node.types, getTypeFromTypeNode), 1 /* Literal */, aliasSymbol, getTypeArgumentsForAliasSymbol(aliasSymbol)); + } + return links.resolvedType; + } + function addTypeToIntersection(typeSet, includes, type) { + var flags = type.flags; + if (flags & 2097152 /* Intersection */) { + return addTypesToIntersection(typeSet, includes, type.types); + } + if (isEmptyAnonymousObjectType(type)) { + if (!(includes & 536870912 /* EmptyObject */)) { + includes |= 536870912 /* EmptyObject */; + typeSet.push(type); + } + } + else { + includes |= flags & ~939524096 /* ConstructionFlags */; + if (flags & 3 /* AnyOrUnknown */) { + if (type === wildcardType) + includes |= 268435456 /* Wildcard */; + } + else if ((strictNullChecks || !(flags & 98304 /* Nullable */)) && !ts.contains(typeSet, type)) { + typeSet.push(type); + } + } + return includes; + } + // Add the given types to the given type set. Order is preserved, freshness is removed from literal + // types, duplicates are removed, and nested types of the given kind are flattened into the set. + function addTypesToIntersection(typeSet, includes, types) { + for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { + var type = types_7[_i]; + includes = addTypeToIntersection(typeSet, includes, getRegularTypeOfLiteralType(type)); + } + return includes; + } + function removeRedundantPrimitiveTypes(types, includes) { + var i = types.length; + while (i > 0) { + i--; + var t = types[i]; + var remove = t.flags & 4 /* String */ && includes & 128 /* StringLiteral */ || + t.flags & 8 /* Number */ && includes & 256 /* NumberLiteral */ || + t.flags & 64 /* BigInt */ && includes & 2048 /* BigIntLiteral */ || + t.flags & 4096 /* ESSymbol */ && includes & 8192 /* UniqueESSymbol */; + if (remove) { + ts.orderedRemoveItemAt(types, i); + } + } + } + // Check that the given type has a match in every union. A given type is matched by + // an identical type, and a literal type is additionally matched by its corresponding + // primitive type. + function eachUnionContains(unionTypes, type) { + for (var _i = 0, unionTypes_1 = unionTypes; _i < unionTypes_1.length; _i++) { + var u = unionTypes_1[_i]; + if (!containsType(u.types, type)) { + var primitive = type.flags & 128 /* StringLiteral */ ? stringType : + type.flags & 256 /* NumberLiteral */ ? numberType : + type.flags & 2048 /* BigIntLiteral */ ? bigintType : + type.flags & 8192 /* UniqueESSymbol */ ? esSymbolType : + undefined; + if (!primitive || !containsType(u.types, primitive)) { + return false; + } + } + } + return true; + } + // If the given list of types contains more than one union of primitive types, replace the + // first with a union containing an intersection of those primitive types, then remove the + // other unions and return true. Otherwise, do nothing and return false. + function intersectUnionsOfPrimitiveTypes(types) { + var unionTypes; + var index = ts.findIndex(types, function (t) { return !!(t.flags & 1048576 /* Union */) && t.primitiveTypesOnly; }); + if (index < 0) { + return false; + } + var i = index + 1; + // Remove all but the first union of primitive types and collect them in + // the unionTypes array. + while (i < types.length) { + var t = types[i]; + if (t.flags & 1048576 /* Union */ && t.primitiveTypesOnly) { + (unionTypes || (unionTypes = [types[index]])).push(t); + ts.orderedRemoveItemAt(types, i); + } + else { + i++; + } + } + // Return false if there was only one union of primitive types + if (!unionTypes) { + return false; + } + // We have more than one union of primitive types, now intersect them. For each + // type in each union we check if the type is matched in every union and if so + // we include it in the result. + var checked = []; + var result = []; + for (var _i = 0, unionTypes_2 = unionTypes; _i < unionTypes_2.length; _i++) { + var u = unionTypes_2[_i]; + for (var _a = 0, _b = u.types; _a < _b.length; _a++) { + var t = _b[_a]; + if (insertType(checked, t)) { + if (eachUnionContains(unionTypes, t)) { + insertType(result, t); + } + } + } + } + // Finally replace the first union with the result + types[index] = getUnionTypeFromSortedList(result, /*primitiveTypesOnly*/ true); + return true; + } + // We normalize combinations of intersection and union types based on the distributive property of the '&' + // operator. Specifically, because X & (A | B) is equivalent to X & A | X & B, we can transform intersection + // types with union type constituents into equivalent union types with intersection type constituents and + // effectively ensure that union types are always at the top level in type representations. + // + // We do not perform structural deduplication on intersection types. Intersection types are created only by the & + // type operator and we can't reduce those because we want to support recursive intersection types. For example, + // a type alias of the form "type List = T & { next: List }" cannot be reduced during its declaration. + // Also, unlike union types, the order of the constituent types is preserved in order that overload resolution + // for intersections of types with signatures can be deterministic. + function getIntersectionType(types, aliasSymbol, aliasTypeArguments) { + var typeSet = []; + var includes = addTypesToIntersection(typeSet, 0, types); + if (includes & 131072 /* Never */) { + return neverType; + } + if (includes & 1 /* Any */) { + return includes & 268435456 /* Wildcard */ ? wildcardType : anyType; + } + if (!strictNullChecks && includes & 98304 /* Nullable */) { + return includes & 32768 /* Undefined */ ? undefinedType : nullType; + } + if (includes & 4 /* String */ && includes & 128 /* StringLiteral */ || + includes & 8 /* Number */ && includes & 256 /* NumberLiteral */ || + includes & 64 /* BigInt */ && includes & 2048 /* BigIntLiteral */ || + includes & 4096 /* ESSymbol */ && includes & 8192 /* UniqueESSymbol */) { + removeRedundantPrimitiveTypes(typeSet, includes); + } + if (includes & 536870912 /* EmptyObject */ && includes & 524288 /* Object */) { + ts.orderedRemoveItemAt(typeSet, ts.findIndex(typeSet, isEmptyAnonymousObjectType)); + } + if (typeSet.length === 0) { + return unknownType; + } + if (typeSet.length === 1) { + return typeSet[0]; + } + if (includes & 1048576 /* Union */) { + if (intersectUnionsOfPrimitiveTypes(typeSet)) { + // When the intersection creates a reduced set (which might mean that *all* union types have + // disappeared), we restart the operation to get a new set of combined flags. Once we have + // reduced we'll never reduce again, so this occurs at most once. + return getIntersectionType(typeSet, aliasSymbol, aliasTypeArguments); + } + // We are attempting to construct a type of the form X & (A | B) & Y. Transform this into a type of + // the form X & A & Y | X & B & Y and recursively reduce until no union type constituents remain. + var unionIndex_1 = ts.findIndex(typeSet, function (t) { return (t.flags & 1048576 /* Union */) !== 0; }); + var unionType = typeSet[unionIndex_1]; + return getUnionType(ts.map(unionType.types, function (t) { return getIntersectionType(ts.replaceElement(typeSet, unionIndex_1, t)); }), 1 /* Literal */, aliasSymbol, aliasTypeArguments); + } + var id = getTypeListId(typeSet); + var type = intersectionTypes.get(id); + if (!type) { + var propagatedFlags = getPropagatingFlagsOfTypes(typeSet, /*excludeKinds*/ 98304 /* Nullable */); + type = createType(2097152 /* Intersection */ | propagatedFlags); + intersectionTypes.set(id, type); + type.types = typeSet; + type.aliasSymbol = aliasSymbol; // See comment in `getUnionTypeFromSortedList`. + type.aliasTypeArguments = aliasTypeArguments; + } + return type; + } + function getTypeFromIntersectionTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + var aliasSymbol = getAliasSymbolForTypeNode(node); + links.resolvedType = getIntersectionType(ts.map(node.types, getTypeFromTypeNode), aliasSymbol, getTypeArgumentsForAliasSymbol(aliasSymbol)); + } + return links.resolvedType; + } + function createIndexType(type, stringsOnly) { + var result = createType(4194304 /* Index */); + result.type = type; + result.stringsOnly = stringsOnly; + return result; + } + function getIndexTypeForGenericType(type, stringsOnly) { + return stringsOnly ? + type.resolvedStringIndexType || (type.resolvedStringIndexType = createIndexType(type, /*stringsOnly*/ true)) : + type.resolvedIndexType || (type.resolvedIndexType = createIndexType(type, /*stringsOnly*/ false)); + } + function getLiteralTypeFromPropertyName(name) { + return ts.isIdentifier(name) ? getLiteralType(ts.unescapeLeadingUnderscores(name.escapedText)) : + getRegularTypeOfLiteralType(ts.isComputedPropertyName(name) ? checkComputedPropertyName(name) : checkExpression(name)); + } + function getBigIntLiteralType(node) { + return getLiteralType({ + negative: false, + base10Value: ts.parsePseudoBigInt(node.text) + }); + } + function getLiteralTypeFromProperty(prop, include) { + if (!(ts.getDeclarationModifierFlagsFromSymbol(prop) & 24 /* NonPublicAccessibilityModifier */)) { + var type = getLateBoundSymbol(prop).nameType; + if (!type && !ts.isKnownSymbol(prop)) { + if (prop.escapedName === "default" /* Default */) { + type = getLiteralType("default"); + } + else { + var name = prop.valueDeclaration && ts.getNameOfDeclaration(prop.valueDeclaration); + type = name && getLiteralTypeFromPropertyName(name) || getLiteralType(ts.symbolName(prop)); + } + } + if (type && type.flags & include) { + return type; + } + } + return neverType; + } + function getLiteralTypeFromProperties(type, include) { + return getUnionType(ts.map(getPropertiesOfType(type), function (t) { return getLiteralTypeFromProperty(t, include); })); + } + function getNonEnumNumberIndexInfo(type) { + var numberIndexInfo = getIndexInfoOfType(type, 1 /* Number */); + return numberIndexInfo !== enumNumberIndexInfo ? numberIndexInfo : undefined; + } + function getIndexType(type, stringsOnly) { + if (stringsOnly === void 0) { stringsOnly = keyofStringsOnly; } + return type.flags & 1048576 /* Union */ ? getIntersectionType(ts.map(type.types, function (t) { return getIndexType(t, stringsOnly); })) : + type.flags & 2097152 /* Intersection */ ? getUnionType(ts.map(type.types, function (t) { return getIndexType(t, stringsOnly); })) : + maybeTypeOfKind(type, 58982400 /* InstantiableNonPrimitive */) ? getIndexTypeForGenericType(type, stringsOnly) : + ts.getObjectFlags(type) & 32 /* Mapped */ ? getConstraintTypeFromMappedType(type) : + type === wildcardType ? wildcardType : + type.flags & 1 /* Any */ ? keyofConstraintType : + stringsOnly ? getIndexInfoOfType(type, 0 /* String */) ? stringType : getLiteralTypeFromProperties(type, 128 /* StringLiteral */) : + getIndexInfoOfType(type, 0 /* String */) ? getUnionType([stringType, numberType, getLiteralTypeFromProperties(type, 8192 /* UniqueESSymbol */)]) : + getNonEnumNumberIndexInfo(type) ? getUnionType([numberType, getLiteralTypeFromProperties(type, 128 /* StringLiteral */ | 8192 /* UniqueESSymbol */)]) : + getLiteralTypeFromProperties(type, 8576 /* StringOrNumberLiteralOrUnique */); + } + function getExtractStringType(type) { + if (keyofStringsOnly) { + return type; + } + var extractTypeAlias = getGlobalExtractSymbol(); + return extractTypeAlias ? getTypeAliasInstantiation(extractTypeAlias, [type, stringType]) : stringType; + } + function getIndexTypeOrString(type) { + var indexType = getExtractStringType(getIndexType(type)); + return indexType.flags & 131072 /* Never */ ? stringType : indexType; + } + function getTypeFromTypeOperatorNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + switch (node.operator) { + case 129 /* KeyOfKeyword */: + links.resolvedType = getIndexType(getTypeFromTypeNode(node.type)); + break; + case 142 /* UniqueKeyword */: + links.resolvedType = node.type.kind === 139 /* SymbolKeyword */ + ? getESSymbolLikeTypeForNode(ts.walkUpParenthesizedTypes(node.parent)) + : errorType; + break; + } + } + return links.resolvedType; // TODO: GH#18217 + } + function createIndexedAccessType(objectType, indexType) { + var type = createType(8388608 /* IndexedAccess */); + type.objectType = objectType; + type.indexType = indexType; + return type; + } + /** + * Returns if a type is or consists of a JSLiteral object type + * In addition to objects which are directly literals, + * * unions where every element is a jsliteral + * * intersections where at least one element is a jsliteral + * * and instantiable types constrained to a jsliteral + * Should all count as literals and not print errors on access or assignment of possibly existing properties. + * This mirrors the behavior of the index signature propagation, to which this behaves similarly (but doesn't affect assignability or inference). + */ + function isJSLiteralType(type) { + if (noImplicitAny) { + return false; // Flag is meaningless under `noImplicitAny` mode + } + if (ts.getObjectFlags(type) & 16384 /* JSLiteral */) { + return true; + } + if (type.flags & 1048576 /* Union */) { + return ts.every(type.types, isJSLiteralType); + } + if (type.flags & 2097152 /* Intersection */) { + return ts.some(type.types, isJSLiteralType); + } + if (type.flags & 63176704 /* Instantiable */) { + return isJSLiteralType(getResolvedBaseConstraint(type)); + } + return false; + } + function getPropertyTypeForIndexType(objectType, indexType, accessNode, cacheSymbol, missingType) { + var accessExpression = accessNode && accessNode.kind === 190 /* ElementAccessExpression */ ? accessNode : undefined; + var propName = isTypeUsableAsLateBoundName(indexType) + ? getLateBoundNameFromType(indexType) + : accessExpression && checkThatExpressionIsProperSymbolReference(accessExpression.argumentExpression, indexType, /*reportError*/ false) + ? ts.getPropertyNameForKnownSymbolName(ts.idText(accessExpression.argumentExpression.name)) + : accessNode && ts.isPropertyName(accessNode) + // late bound names are handled in the first branch, so here we only need to handle normal names + ? ts.getPropertyNameForPropertyNameNode(accessNode) + : undefined; + if (propName !== undefined) { + var prop = getPropertyOfType(objectType, propName); + if (prop) { + if (accessExpression) { + markPropertyAsReferenced(prop, accessExpression, /*isThisAccess*/ accessExpression.expression.kind === 100 /* ThisKeyword */); + if (ts.isAssignmentTarget(accessExpression) && (isReferenceToReadonlyEntity(accessExpression, prop) || isReferenceThroughNamespaceImport(accessExpression))) { + error(accessExpression.argumentExpression, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, symbolToString(prop)); + return missingType; + } + if (cacheSymbol) { + getNodeLinks(accessNode).resolvedSymbol = prop; + } + } + var propType = getTypeOfSymbol(prop); + return accessExpression && ts.getAssignmentTargetKind(accessExpression) !== 1 /* Definite */ ? + getFlowTypeOfReference(accessExpression, propType) : + propType; + } + if (everyType(objectType, isTupleType) && isNumericLiteralName(propName) && +propName >= 0) { + if (accessNode && everyType(objectType, function (t) { return !t.target.hasRestElement; })) { + var indexNode = getIndexNodeForAccessExpression(accessNode); + error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(propName), typeToString(objectType)); + } + return mapType(objectType, function (t) { return getRestTypeOfTupleType(t) || undefinedType; }); + } + } + if (!(indexType.flags & 98304 /* Nullable */) && isTypeAssignableToKind(indexType, 132 /* StringLike */ | 296 /* NumberLike */ | 12288 /* ESSymbolLike */)) { + if (objectType.flags & (1 /* Any */ | 131072 /* Never */)) { + return objectType; + } + var indexInfo = isTypeAssignableToKind(indexType, 296 /* NumberLike */) && getIndexInfoOfType(objectType, 1 /* Number */) || + getIndexInfoOfType(objectType, 0 /* String */) || + undefined; + if (indexInfo) { + if (accessNode && !isTypeAssignableToKind(indexType, 4 /* String */ | 8 /* Number */)) { + var indexNode = getIndexNodeForAccessExpression(accessNode); + error(indexNode, ts.Diagnostics.Type_0_cannot_be_used_as_an_index_type, typeToString(indexType)); + } + else if (accessExpression && indexInfo.isReadonly && (ts.isAssignmentTarget(accessExpression) || ts.isDeleteTarget(accessExpression))) { + error(accessExpression, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(objectType)); + } + return indexInfo.type; + } + if (indexType.flags & 131072 /* Never */) { + return neverType; + } + if (isJSLiteralType(objectType)) { + return anyType; + } + if (accessExpression && !isConstEnumObjectType(objectType)) { + if (noImplicitAny && !compilerOptions.suppressImplicitAnyIndexErrors) { + if (propName !== undefined && typeHasStaticProperty(propName, objectType)) { + error(accessExpression, ts.Diagnostics.Property_0_is_a_static_member_of_type_1, propName, typeToString(objectType)); + } + else if (getIndexTypeOfType(objectType, 1 /* Number */)) { + error(accessExpression.argumentExpression, ts.Diagnostics.Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number); + } + else { + var suggestion = void 0; + if (propName !== undefined && (suggestion = getSuggestionForNonexistentProperty(propName, objectType))) { + if (suggestion !== undefined) { + error(accessExpression.argumentExpression, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2, propName, typeToString(objectType), suggestion); + } + } + else { + error(accessExpression, ts.Diagnostics.Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature, typeToString(objectType)); + } + } + } + return missingType; + } + } + if (isJSLiteralType(objectType)) { + return anyType; + } + if (accessNode) { + var indexNode = getIndexNodeForAccessExpression(accessNode); + if (indexType.flags & (128 /* StringLiteral */ | 256 /* NumberLiteral */)) { + error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, "" + indexType.value, typeToString(objectType)); + } + else if (indexType.flags & (4 /* String */ | 8 /* Number */)) { + error(indexNode, ts.Diagnostics.Type_0_has_no_matching_index_signature_for_type_1, typeToString(objectType), typeToString(indexType)); + } + else { + error(indexNode, ts.Diagnostics.Type_0_cannot_be_used_as_an_index_type, typeToString(indexType)); + } + } + if (isTypeAny(indexType)) { + return indexType; + } + return missingType; + } + function getIndexNodeForAccessExpression(accessNode) { + return accessNode.kind === 190 /* ElementAccessExpression */ + ? accessNode.argumentExpression + : accessNode.kind === 180 /* IndexedAccessType */ + ? accessNode.indexType + : accessNode.kind === 149 /* ComputedPropertyName */ + ? accessNode.expression + : accessNode; + } + function isGenericObjectType(type) { + return maybeTypeOfKind(type, 58982400 /* InstantiableNonPrimitive */ | 134217728 /* GenericMappedType */); + } + function isGenericIndexType(type) { + return maybeTypeOfKind(type, 58982400 /* InstantiableNonPrimitive */ | 4194304 /* Index */); + } + function getSimplifiedType(type) { + return type.flags & 8388608 /* IndexedAccess */ ? getSimplifiedIndexedAccessType(type) : type; + } + function distributeIndexOverObjectType(objectType, indexType) { + // (T | U)[K] -> T[K] | U[K] + if (objectType.flags & 1048576 /* Union */) { + return mapType(objectType, function (t) { return getSimplifiedType(getIndexedAccessType(t, indexType)); }); + } + // (T & U)[K] -> T[K] & U[K] + if (objectType.flags & 2097152 /* Intersection */) { + return getIntersectionType(ts.map(objectType.types, function (t) { return getSimplifiedType(getIndexedAccessType(t, indexType)); })); + } + } + // Transform an indexed access to a simpler form, if possible. Return the simpler form, or return + // the type itself if no transformation is possible. + function getSimplifiedIndexedAccessType(type) { + if (type.simplified) { + return type.simplified === circularConstraintType ? type : type.simplified; + } + type.simplified = circularConstraintType; + // We recursively simplify the object type as it may in turn be an indexed access type. For example, with + // '{ [P in T]: { [Q in U]: number } }[T][U]' we want to first simplify the inner indexed access type. + var objectType = getSimplifiedType(type.objectType); + var indexType = getSimplifiedType(type.indexType); + // T[A | B] -> T[A] | T[B] + if (indexType.flags & 1048576 /* Union */) { + return type.simplified = mapType(indexType, function (t) { return getSimplifiedType(getIndexedAccessType(objectType, t)); }); + } + // Only do the inner distributions if the index can no longer be instantiated to cause index distribution again + if (!(indexType.flags & 63176704 /* Instantiable */)) { + var simplified = distributeIndexOverObjectType(objectType, indexType); + if (simplified) { + return type.simplified = simplified; + } + } + // So ultimately: + // ((A & B) | C)[K1 | K2] -> ((A & B) | C)[K1] | ((A & B) | C)[K2] -> (A & B)[K1] | C[K1] | (A & B)[K2] | C[K2] -> (A[K1] & B[K1]) | C[K1] | (A[K2] & B[K2]) | C[K2] + // If the object type is a mapped type { [P in K]: E }, where K is generic, instantiate E using a mapper + // that substitutes the index type for P. For example, for an index access { [P in K]: Box }[X], we + // construct the type Box. We do not further simplify the result because mapped types can be recursive + // and we might never terminate. + if (isGenericMappedType(objectType)) { + return type.simplified = substituteIndexedMappedType(objectType, type); + } + if (objectType.flags & 262144 /* TypeParameter */) { + var constraint = getConstraintOfTypeParameter(objectType); + if (constraint && isGenericMappedType(constraint)) { + return type.simplified = substituteIndexedMappedType(constraint, type); + } + } + return type.simplified = type; + } + function substituteIndexedMappedType(objectType, type) { + var mapper = createTypeMapper([getTypeParameterFromMappedType(objectType)], [type.indexType]); + var templateMapper = combineTypeMappers(objectType.mapper, mapper); + return instantiateType(getTemplateTypeFromMappedType(objectType), templateMapper); + } + function getIndexedAccessType(objectType, indexType, accessNode, missingType) { + if (missingType === void 0) { missingType = accessNode ? errorType : unknownType; } + if (objectType === wildcardType || indexType === wildcardType) { + return wildcardType; + } + // If the index type is generic, or if the object type is generic and doesn't originate in an expression, + // we are performing a higher-order index access where we cannot meaningfully access the properties of the + // object type. Note that for a generic T and a non-generic K, we eagerly resolve T[K] if it originates in + // an expression. This is to preserve backwards compatibility. For example, an element access 'this["foo"]' + // has always been resolved eagerly using the constraint type of 'this' at the given location. + if (isGenericIndexType(indexType) || !(accessNode && accessNode.kind !== 180 /* IndexedAccessType */) && isGenericObjectType(objectType)) { + if (objectType.flags & 3 /* AnyOrUnknown */) { + return objectType; + } + // Defer the operation by creating an indexed access type. + var id = objectType.id + "," + indexType.id; + var type = indexedAccessTypes.get(id); + if (!type) { + indexedAccessTypes.set(id, type = createIndexedAccessType(objectType, indexType)); + } + return type; + } + // In the following we resolve T[K] to the type of the property in T selected by K. + // We treat boolean as different from other unions to improve errors; + // skipping straight to getPropertyTypeForIndexType gives errors with 'boolean' instead of 'true'. + var apparentObjectType = getApparentType(objectType); + if (indexType.flags & 1048576 /* Union */ && !(indexType.flags & 16 /* Boolean */)) { + var propTypes = []; + var wasMissingProp = false; + for (var _i = 0, _a = indexType.types; _i < _a.length; _i++) { + var t = _a[_i]; + var propType = getPropertyTypeForIndexType(apparentObjectType, t, accessNode, /*cacheSymbol*/ false, missingType); + if (propType === missingType) { + if (!accessNode) { + // If there's no error node, we can immeditely stop, since error reporting is off + return missingType; + } + else { + // Otherwise we set a flag and return at the end of the loop so we still mark all errors + wasMissingProp = true; + } + } + propTypes.push(propType); + } + if (wasMissingProp) { + return missingType; + } + return getUnionType(propTypes); + } + return getPropertyTypeForIndexType(apparentObjectType, indexType, accessNode, /*cacheSymbol*/ true, missingType); + } + function getTypeFromIndexedAccessTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + var objectType = getTypeFromTypeNode(node.objectType); + var indexType = getTypeFromTypeNode(node.indexType); + var resolved = getIndexedAccessType(objectType, indexType, node); + links.resolvedType = resolved.flags & 8388608 /* IndexedAccess */ && + resolved.objectType === objectType && + resolved.indexType === indexType ? + getConstrainedTypeVariable(resolved, node) : resolved; + } + return links.resolvedType; + } + function getTypeFromMappedTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + var type = createObjectType(32 /* Mapped */, node.symbol); + type.declaration = node; + type.aliasSymbol = getAliasSymbolForTypeNode(node); + type.aliasTypeArguments = getTypeArgumentsForAliasSymbol(type.aliasSymbol); + links.resolvedType = type; + // Eagerly resolve the constraint type which forces an error if the constraint type circularly + // references itself through one or more type aliases. + getConstraintTypeFromMappedType(type); + } + return links.resolvedType; + } + function getActualTypeVariable(type) { + return type.flags & 33554432 /* Substitution */ ? type.typeVariable : type; + } + function getConditionalType(root, mapper) { + var checkType = instantiateType(root.checkType, mapper); + var extendsType = instantiateType(root.extendsType, mapper); + if (checkType === wildcardType || extendsType === wildcardType) { + return wildcardType; + } + // If this is a distributive conditional type and the check type is generic we need to defer + // resolution of the conditional type such that a later instantiation will properly distribute + // over union types. + var isDeferred = root.isDistributive && maybeTypeOfKind(checkType, 63176704 /* Instantiable */); + var combinedMapper; + if (root.inferTypeParameters) { + var context = createInferenceContext(root.inferTypeParameters, /*signature*/ undefined, 0 /* None */); + if (!isDeferred) { + // We don't want inferences from constraints as they may cause us to eagerly resolve the + // conditional type instead of deferring resolution. Also, we always want strict function + // types rules (i.e. proper contravariance) for inferences. + inferTypes(context.inferences, checkType, extendsType, 32 /* NoConstraints */ | 64 /* AlwaysStrict */); + } + combinedMapper = combineTypeMappers(mapper, context); + } + if (!isDeferred) { + if (extendsType.flags & 3 /* AnyOrUnknown */) { + return instantiateType(root.trueType, mapper); + } + // Return union of trueType and falseType for 'any' since it matches anything + if (checkType.flags & 1 /* Any */) { + return getUnionType([instantiateType(root.trueType, combinedMapper || mapper), instantiateType(root.falseType, mapper)]); + } + // Instantiate the extends type including inferences for 'infer T' type parameters + var inferredExtendsType = combinedMapper ? instantiateType(root.extendsType, combinedMapper) : extendsType; + // Return falseType for a definitely false extends check. We check an instantations of the two + // types with type parameters mapped to the wildcard type, the most permissive instantiations + // possible (the wildcard type is assignable to and from all types). If those are not related, + // then no instatiations will be and we can just return the false branch type. + if (!isTypeAssignableTo(getWildcardInstantiation(checkType), getWildcardInstantiation(inferredExtendsType))) { + return instantiateType(root.falseType, mapper); + } + // Return trueType for a definitely true extends check. The definitely assignable relation excludes + // type variable constraints from consideration. Without the definitely assignable relation, the type + // type Foo = T extends { x: string } ? string : number + // would immediately resolve to 'string' instead of being deferred. + if (checkTypeRelatedTo(checkType, inferredExtendsType, definitelyAssignableRelation, /*errorNode*/ undefined)) { + return instantiateType(root.trueType, combinedMapper || mapper); + } + } + // Return a deferred type for a check that is neither definitely true nor definitely false + var erasedCheckType = getActualTypeVariable(checkType); + var result = createType(16777216 /* Conditional */); + result.root = root; + result.checkType = erasedCheckType; + result.extendsType = extendsType; + result.mapper = mapper; + result.combinedMapper = combinedMapper; + result.aliasSymbol = root.aliasSymbol; + result.aliasTypeArguments = instantiateTypes(root.aliasTypeArguments, mapper); // TODO: GH#18217 + return result; + } + function getTrueTypeFromConditionalType(type) { + return type.resolvedTrueType || (type.resolvedTrueType = instantiateType(type.root.trueType, type.mapper)); + } + function getFalseTypeFromConditionalType(type) { + return type.resolvedFalseType || (type.resolvedFalseType = instantiateType(type.root.falseType, type.mapper)); + } + function getInferTypeParameters(node) { + var result; + if (node.locals) { + node.locals.forEach(function (symbol) { + if (symbol.flags & 262144 /* TypeParameter */) { + result = ts.append(result, getDeclaredTypeOfSymbol(symbol)); + } + }); + } + return result; + } + function isPossiblyReferencedInConditionalType(tp, node) { + if (isTypeParameterPossiblyReferenced(tp, node)) { + return true; + } + while (node) { + if (node.kind === 175 /* ConditionalType */) { + if (isTypeParameterPossiblyReferenced(tp, node.extendsType)) { + return true; + } + } + node = node.parent; + } + return false; + } + function getTypeFromConditionalTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + var checkType = getTypeFromTypeNode(node.checkType); + var aliasSymbol = getAliasSymbolForTypeNode(node); + var aliasTypeArguments = getTypeArgumentsForAliasSymbol(aliasSymbol); + var allOuterTypeParameters = getOuterTypeParameters(node, /*includeThisTypes*/ true); + var outerTypeParameters = aliasTypeArguments ? allOuterTypeParameters : ts.filter(allOuterTypeParameters, function (tp) { return isPossiblyReferencedInConditionalType(tp, node); }); + var root = { + node: node, + checkType: checkType, + extendsType: getTypeFromTypeNode(node.extendsType), + trueType: getTypeFromTypeNode(node.trueType), + falseType: getTypeFromTypeNode(node.falseType), + isDistributive: !!(checkType.flags & 262144 /* TypeParameter */), + inferTypeParameters: getInferTypeParameters(node), + outerTypeParameters: outerTypeParameters, + instantiations: undefined, + aliasSymbol: aliasSymbol, + aliasTypeArguments: aliasTypeArguments + }; + links.resolvedType = getConditionalType(root, /*mapper*/ undefined); + if (outerTypeParameters) { + root.instantiations = ts.createMap(); + root.instantiations.set(getTypeListId(outerTypeParameters), links.resolvedType); + } + } + return links.resolvedType; + } + function getTypeFromInferTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + links.resolvedType = getDeclaredTypeOfTypeParameter(getSymbolOfNode(node.typeParameter)); + } + return links.resolvedType; + } + function getIdentifierChain(node) { + if (ts.isIdentifier(node)) { + return [node]; + } + else { + return ts.append(getIdentifierChain(node.left), node.right); + } + } + function getTypeFromImportTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + if (node.isTypeOf && node.typeArguments) { // Only the non-typeof form can make use of type arguments + error(node, ts.Diagnostics.Type_arguments_cannot_be_used_here); + links.resolvedSymbol = unknownSymbol; + return links.resolvedType = errorType; + } + if (!ts.isLiteralImportTypeNode(node)) { + error(node.argument, ts.Diagnostics.String_literal_expected); + links.resolvedSymbol = unknownSymbol; + return links.resolvedType = errorType; + } + var targetMeaning = node.isTypeOf ? 67220415 /* Value */ : node.flags & 2097152 /* JSDoc */ ? 67220415 /* Value */ | 67897832 /* Type */ : 67897832 /* Type */; + // TODO: Future work: support unions/generics/whatever via a deferred import-type + var innerModuleSymbol = resolveExternalModuleName(node, node.argument.literal); + if (!innerModuleSymbol) { + links.resolvedSymbol = unknownSymbol; + return links.resolvedType = errorType; + } + var moduleSymbol = resolveExternalModuleSymbol(innerModuleSymbol, /*dontResolveAlias*/ false); + if (!ts.nodeIsMissing(node.qualifier)) { + var nameStack = getIdentifierChain(node.qualifier); + var currentNamespace = moduleSymbol; + var current = void 0; + while (current = nameStack.shift()) { + var meaning = nameStack.length ? 1920 /* Namespace */ : targetMeaning; + var next = getSymbol(getExportsOfSymbol(getMergedSymbol(resolveSymbol(currentNamespace))), current.escapedText, meaning); + if (!next) { + error(current, ts.Diagnostics.Namespace_0_has_no_exported_member_1, getFullyQualifiedName(currentNamespace), ts.declarationNameToString(current)); + return links.resolvedType = errorType; + } + getNodeLinks(current).resolvedSymbol = next; + getNodeLinks(current.parent).resolvedSymbol = next; + currentNamespace = next; + } + resolveImportSymbolType(node, links, currentNamespace, targetMeaning); + } + else { + if (moduleSymbol.flags & targetMeaning) { + resolveImportSymbolType(node, links, moduleSymbol, targetMeaning); + } + else { + var errorMessage = targetMeaning === 67220415 /* Value */ + ? ts.Diagnostics.Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here + : ts.Diagnostics.Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0; + error(node, errorMessage, node.argument.literal.text); + links.resolvedSymbol = unknownSymbol; + links.resolvedType = errorType; + } + } + } + return links.resolvedType; // TODO: GH#18217 + } + function resolveImportSymbolType(node, links, symbol, meaning) { + var resolvedSymbol = resolveSymbol(symbol); + links.resolvedSymbol = resolvedSymbol; + if (meaning === 67220415 /* Value */) { + return links.resolvedType = getTypeOfSymbol(symbol); // intentionally doesn't use resolved symbol so type is cached as expected on the alias + } + else { + return links.resolvedType = getTypeReferenceType(node, resolvedSymbol); // getTypeReferenceType doesn't handle aliases - it must get the resolved symbol + } + } + function getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + // Deferred resolution of members is handled by resolveObjectTypeMembers + var aliasSymbol = getAliasSymbolForTypeNode(node); + if (getMembersOfSymbol(node.symbol).size === 0 && !aliasSymbol) { + links.resolvedType = emptyTypeLiteralType; + } + else { + var type = createObjectType(16 /* Anonymous */, node.symbol); + type.aliasSymbol = aliasSymbol; + type.aliasTypeArguments = getTypeArgumentsForAliasSymbol(aliasSymbol); + if (ts.isJSDocTypeLiteral(node) && node.isArrayType) { + type = createArrayType(type); + } + links.resolvedType = type; + } + } + return links.resolvedType; + } + function getAliasSymbolForTypeNode(node) { + return ts.isTypeAlias(node.parent) ? getSymbolOfNode(node.parent) : undefined; + } + function getTypeArgumentsForAliasSymbol(symbol) { + return symbol ? getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) : undefined; + } + function isNonGenericObjectType(type) { + return !!(type.flags & 524288 /* Object */) && !isGenericMappedType(type); + } + /** + * Since the source of spread types are object literals, which are not binary, + * this function should be called in a left folding style, with left = previous result of getSpreadType + * and right = the new element to be spread. + */ + function getSpreadType(left, right, symbol, typeFlags, objectFlags) { + if (left.flags & 1 /* Any */ || right.flags & 1 /* Any */) { + return anyType; + } + if (left.flags & 2 /* Unknown */ || right.flags & 2 /* Unknown */) { + return unknownType; + } + if (left.flags & 131072 /* Never */) { + return right; + } + if (right.flags & 131072 /* Never */) { + return left; + } + if (left.flags & 1048576 /* Union */) { + return mapType(left, function (t) { return getSpreadType(t, right, symbol, typeFlags, objectFlags); }); + } + if (right.flags & 1048576 /* Union */) { + return mapType(right, function (t) { return getSpreadType(left, t, symbol, typeFlags, objectFlags); }); + } + if (right.flags & (528 /* BooleanLike */ | 296 /* NumberLike */ | 2112 /* BigIntLike */ | 132 /* StringLike */ | 1056 /* EnumLike */ | 67108864 /* NonPrimitive */ | 4194304 /* Index */)) { + return left; + } + if (isGenericObjectType(left) || isGenericObjectType(right)) { + if (isEmptyObjectType(left)) { + return right; + } + // When the left type is an intersection, we may need to merge the last constituent of the + // intersection with the right type. For example when the left type is 'T & { a: string }' + // and the right type is '{ b: string }' we produce 'T & { a: string, b: string }'. + if (left.flags & 2097152 /* Intersection */) { + var types = left.types; + var lastLeft = types[types.length - 1]; + if (isNonGenericObjectType(lastLeft) && isNonGenericObjectType(right)) { + return getIntersectionType(ts.concatenate(types.slice(0, types.length - 1), [getSpreadType(lastLeft, right, symbol, typeFlags, objectFlags)])); + } + } + return getIntersectionType([left, right]); + } + var members = ts.createSymbolTable(); + var skippedPrivateMembers = ts.createUnderscoreEscapedMap(); + var stringIndexInfo; + var numberIndexInfo; + if (left === emptyObjectType) { + // for the first spread element, left === emptyObjectType, so take the right's string indexer + stringIndexInfo = getIndexInfoOfType(right, 0 /* String */); + numberIndexInfo = getIndexInfoOfType(right, 1 /* Number */); + } + else { + stringIndexInfo = unionSpreadIndexInfos(getIndexInfoOfType(left, 0 /* String */), getIndexInfoOfType(right, 0 /* String */)); + numberIndexInfo = unionSpreadIndexInfos(getIndexInfoOfType(left, 1 /* Number */), getIndexInfoOfType(right, 1 /* Number */)); + } + for (var _i = 0, _a = getPropertiesOfType(right); _i < _a.length; _i++) { + var rightProp = _a[_i]; + if (ts.getDeclarationModifierFlagsFromSymbol(rightProp) & (8 /* Private */ | 16 /* Protected */)) { + skippedPrivateMembers.set(rightProp.escapedName, true); + } + else if (isSpreadableProperty(rightProp)) { + members.set(rightProp.escapedName, getSpreadSymbol(rightProp)); + } + } + for (var _b = 0, _c = getPropertiesOfType(left); _b < _c.length; _b++) { + var leftProp = _c[_b]; + if (skippedPrivateMembers.has(leftProp.escapedName) || !isSpreadableProperty(leftProp)) { + continue; + } + if (members.has(leftProp.escapedName)) { + var rightProp = members.get(leftProp.escapedName); + var rightType = getTypeOfSymbol(rightProp); + if (rightProp.flags & 16777216 /* Optional */) { + var declarations = ts.concatenate(leftProp.declarations, rightProp.declarations); + var flags = 4 /* Property */ | (leftProp.flags & 16777216 /* Optional */); + var result = createSymbol(flags, leftProp.escapedName); + result.type = getUnionType([getTypeOfSymbol(leftProp), getTypeWithFacts(rightType, 524288 /* NEUndefined */)]); + result.leftSpread = leftProp; + result.rightSpread = rightProp; + result.declarations = declarations; + result.nameType = leftProp.nameType; + members.set(leftProp.escapedName, result); + } + } + else { + members.set(leftProp.escapedName, getSpreadSymbol(leftProp)); + } + } + var spread = createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, getNonReadonlyIndexSignature(stringIndexInfo), getNonReadonlyIndexSignature(numberIndexInfo)); + spread.flags |= 268435456 /* ContainsObjectLiteral */ | typeFlags; + spread.objectFlags |= 128 /* ObjectLiteral */ | 1024 /* ContainsSpread */ | objectFlags; + return spread; + } + /** We approximate own properties as non-methods plus methods that are inside the object literal */ + function isSpreadableProperty(prop) { + return !(prop.flags & (8192 /* Method */ | 32768 /* GetAccessor */ | 65536 /* SetAccessor */)) || + !prop.declarations.some(function (decl) { return ts.isClassLike(decl.parent); }); + } + function getSpreadSymbol(prop) { + var isReadonly = isReadonlySymbol(prop); + var isSetonlyAccessor = prop.flags & 65536 /* SetAccessor */ && !(prop.flags & 32768 /* GetAccessor */); + if (!isReadonly && !isSetonlyAccessor) { + return prop; + } + var flags = 4 /* Property */ | (prop.flags & 16777216 /* Optional */); + var result = createSymbol(flags, prop.escapedName); + result.type = isSetonlyAccessor ? undefinedType : getTypeOfSymbol(prop); + result.declarations = prop.declarations; + result.nameType = prop.nameType; + result.syntheticOrigin = prop; + return result; + } + function getNonReadonlyIndexSignature(index) { + if (index && index.isReadonly) { + return createIndexInfo(index.type, /*isReadonly*/ false, index.declaration); + } + return index; + } + function createLiteralType(flags, value, symbol) { + var type = createType(flags); + type.symbol = symbol; + type.value = value; + return type; + } + function getFreshTypeOfLiteralType(type) { + if (type.flags & 2944 /* Literal */) { + if (!type.freshType) { + var freshType = createLiteralType(type.flags, type.value, type.symbol); + freshType.regularType = type; + freshType.freshType = freshType; + type.freshType = freshType; + } + return type.freshType; + } + return type; + } + function getRegularTypeOfLiteralType(type) { + return type.flags & 2944 /* Literal */ ? type.regularType : + type.flags & 1048576 /* Union */ ? getUnionType(ts.sameMap(type.types, getRegularTypeOfLiteralType)) : + type; + } + function isFreshLiteralType(type) { + return !!(type.flags & 2944 /* Literal */) && type.freshType === type; + } + function getLiteralType(value, enumId, symbol) { + // We store all literal types in a single map with keys of the form '#NNN' and '@SSS', + // where NNN is the text representation of a numeric literal and SSS are the characters + // of a string literal. For literal enum members we use 'EEE#NNN' and 'EEE@SSS', where + // EEE is a unique id for the containing enum type. + var qualifier = typeof value === "number" ? "#" : typeof value === "string" ? "@" : "n"; + var key = (enumId ? enumId : "") + qualifier + (typeof value === "object" ? ts.pseudoBigIntToString(value) : value); + var type = literalTypes.get(key); + if (!type) { + var flags = (typeof value === "number" ? 256 /* NumberLiteral */ : + typeof value === "string" ? 128 /* StringLiteral */ : 2048 /* BigIntLiteral */) | + (enumId ? 1024 /* EnumLiteral */ : 0); + literalTypes.set(key, type = createLiteralType(flags, value, symbol)); + type.regularType = type; + } + return type; + } + function getTypeFromLiteralTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + links.resolvedType = getRegularTypeOfLiteralType(checkExpression(node.literal)); + } + return links.resolvedType; + } + function createUniqueESSymbolType(symbol) { + var type = createType(8192 /* UniqueESSymbol */); + type.symbol = symbol; + return type; + } + function getESSymbolLikeTypeForNode(node) { + if (ts.isValidESSymbolDeclaration(node)) { + var symbol = getSymbolOfNode(node); + var links = getSymbolLinks(symbol); + return links.uniqueESSymbolType || (links.uniqueESSymbolType = createUniqueESSymbolType(symbol)); + } + return esSymbolType; + } + function getThisType(node) { + var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); + var parent = container && container.parent; + if (parent && (ts.isClassLike(parent) || parent.kind === 241 /* InterfaceDeclaration */)) { + if (!ts.hasModifier(container, 32 /* Static */) && + (container.kind !== 157 /* Constructor */ || ts.isNodeDescendantOf(node, container.body))) { + return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(parent)).thisType; + } + } + error(node, ts.Diagnostics.A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface); + return errorType; + } + function getTypeFromThisTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + links.resolvedType = getThisType(node); + } + return links.resolvedType; + } + function getTypeFromTypeNode(node) { + switch (node.kind) { + case 120 /* AnyKeyword */: + case 284 /* JSDocAllType */: + case 285 /* JSDocUnknownType */: + return anyType; + case 143 /* UnknownKeyword */: + return unknownType; + case 138 /* StringKeyword */: + return stringType; + case 135 /* NumberKeyword */: + return numberType; + case 146 /* BigIntKeyword */: + return bigintType; + case 123 /* BooleanKeyword */: + return booleanType; + case 139 /* SymbolKeyword */: + return esSymbolType; + case 106 /* VoidKeyword */: + return voidType; + case 141 /* UndefinedKeyword */: + return undefinedType; + case 96 /* NullKeyword */: + return nullType; + case 132 /* NeverKeyword */: + return neverType; + case 136 /* ObjectKeyword */: + return node.flags & 65536 /* JavaScriptFile */ ? anyType : nonPrimitiveType; + case 178 /* ThisType */: + case 100 /* ThisKeyword */: + return getTypeFromThisTypeNode(node); + case 182 /* LiteralType */: + return getTypeFromLiteralTypeNode(node); + case 164 /* TypeReference */: + return getTypeFromTypeReference(node); + case 163 /* TypePredicate */: + return booleanType; + case 211 /* ExpressionWithTypeArguments */: + return getTypeFromTypeReference(node); + case 167 /* TypeQuery */: + return getTypeFromTypeQueryNode(node); + case 169 /* ArrayType */: + return getTypeFromArrayTypeNode(node); + case 170 /* TupleType */: + return getTypeFromTupleTypeNode(node); + case 171 /* OptionalType */: + return getTypeFromOptionalTypeNode(node); + case 173 /* UnionType */: + return getTypeFromUnionTypeNode(node); + case 174 /* IntersectionType */: + return getTypeFromIntersectionTypeNode(node); + case 286 /* JSDocNullableType */: + return getTypeFromJSDocNullableTypeNode(node); + case 288 /* JSDocOptionalType */: + return addOptionality(getTypeFromTypeNode(node.type)); + case 177 /* ParenthesizedType */: + case 172 /* RestType */: + case 287 /* JSDocNonNullableType */: + case 283 /* JSDocTypeExpression */: + return getTypeFromTypeNode(node.type); + case 290 /* JSDocVariadicType */: + return getTypeFromJSDocVariadicType(node); + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + case 168 /* TypeLiteral */: + case 292 /* JSDocTypeLiteral */: + case 289 /* JSDocFunctionType */: + case 293 /* JSDocSignature */: + return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node); + case 179 /* TypeOperator */: + return getTypeFromTypeOperatorNode(node); + case 180 /* IndexedAccessType */: + return getTypeFromIndexedAccessTypeNode(node); + case 181 /* MappedType */: + return getTypeFromMappedTypeNode(node); + case 175 /* ConditionalType */: + return getTypeFromConditionalTypeNode(node); + case 176 /* InferType */: + return getTypeFromInferTypeNode(node); + case 183 /* ImportType */: + return getTypeFromImportTypeNode(node); + // This function assumes that an identifier or qualified name is a type expression + // Callers should first ensure this by calling isTypeNode + case 72 /* Identifier */: + case 148 /* QualifiedName */: + var symbol = getSymbolAtLocation(node); + return symbol ? getDeclaredTypeOfSymbol(symbol) : errorType; + default: + return errorType; + } + } + function instantiateList(items, mapper, instantiator) { + if (items && items.length) { + for (var i = 0; i < items.length; i++) { + var item = items[i]; + var mapped = instantiator(item, mapper); + if (item !== mapped) { + var result = i === 0 ? [] : items.slice(0, i); + result.push(mapped); + for (i++; i < items.length; i++) { + result.push(instantiator(items[i], mapper)); + } + return result; + } + } + } + return items; + } + function instantiateTypes(types, mapper) { + return instantiateList(types, mapper, instantiateType); + } + function instantiateSignatures(signatures, mapper) { + return instantiateList(signatures, mapper, instantiateSignature); + } + function makeUnaryTypeMapper(source, target) { + return function (t) { return t === source ? target : t; }; + } + function makeBinaryTypeMapper(source1, target1, source2, target2) { + return function (t) { return t === source1 ? target1 : t === source2 ? target2 : t; }; + } + function makeArrayTypeMapper(sources, targets) { + return function (t) { + for (var i = 0; i < sources.length; i++) { + if (t === sources[i]) { + return targets ? targets[i] : anyType; + } + } + return t; + }; + } + function createTypeMapper(sources, targets) { + ts.Debug.assert(targets === undefined || sources.length === targets.length); + return sources.length === 1 ? makeUnaryTypeMapper(sources[0], targets ? targets[0] : anyType) : + sources.length === 2 ? makeBinaryTypeMapper(sources[0], targets ? targets[0] : anyType, sources[1], targets ? targets[1] : anyType) : + makeArrayTypeMapper(sources, targets); + } + function createTypeEraser(sources) { + return createTypeMapper(sources, /*targets*/ undefined); + } + /** + * Maps forward-references to later types parameters to the empty object type. + * This is used during inference when instantiating type parameter defaults. + */ + function createBackreferenceMapper(typeParameters, index) { + return function (t) { return typeParameters.indexOf(t) >= index ? emptyObjectType : t; }; + } + function isInferenceContext(mapper) { + return !!mapper.typeParameters; + } + function cloneTypeMapper(mapper) { + return mapper && isInferenceContext(mapper) ? + createInferenceContext(mapper.typeParameters, mapper.signature, mapper.flags | 1 /* NoDefault */, mapper.compareTypes, mapper.inferences) : + mapper; + } + function combineTypeMappers(mapper1, mapper2) { + if (!mapper1) + return mapper2; + if (!mapper2) + return mapper1; + return function (t) { return instantiateType(mapper1(t), mapper2); }; + } + function createReplacementMapper(source, target, baseMapper) { + return function (t) { return t === source ? target : baseMapper(t); }; + } + function wildcardMapper(type) { + return type.flags & 262144 /* TypeParameter */ ? wildcardType : type; + } + function cloneTypeParameter(typeParameter) { + var result = createType(262144 /* TypeParameter */); + result.symbol = typeParameter.symbol; + result.target = typeParameter; + return result; + } + function instantiateTypePredicate(predicate, mapper) { + if (ts.isIdentifierTypePredicate(predicate)) { + return { + kind: 1 /* Identifier */, + parameterName: predicate.parameterName, + parameterIndex: predicate.parameterIndex, + type: instantiateType(predicate.type, mapper) + }; + } + else { + return { + kind: 0 /* This */, + type: instantiateType(predicate.type, mapper) + }; + } + } + function instantiateSignature(signature, mapper, eraseTypeParameters) { + var freshTypeParameters; + if (signature.typeParameters && !eraseTypeParameters) { + // First create a fresh set of type parameters, then include a mapping from the old to the + // new type parameters in the mapper function. Finally store this mapper in the new type + // parameters such that we can use it when instantiating constraints. + freshTypeParameters = ts.map(signature.typeParameters, cloneTypeParameter); + mapper = combineTypeMappers(createTypeMapper(signature.typeParameters, freshTypeParameters), mapper); + for (var _i = 0, freshTypeParameters_1 = freshTypeParameters; _i < freshTypeParameters_1.length; _i++) { + var tp = freshTypeParameters_1[_i]; + tp.mapper = mapper; + } + } + // Don't compute resolvedReturnType and resolvedTypePredicate now, + // because using `mapper` now could trigger inferences to become fixed. (See `createInferenceContext`.) + // See GH#17600. + var result = createSignature(signature.declaration, freshTypeParameters, signature.thisParameter && instantiateSymbol(signature.thisParameter, mapper), instantiateList(signature.parameters, mapper, instantiateSymbol), + /*resolvedReturnType*/ undefined, + /*resolvedTypePredicate*/ undefined, signature.minArgumentCount, signature.hasRestParameter, signature.hasLiteralTypes); + result.target = signature; + result.mapper = mapper; + return result; + } + function instantiateSymbol(symbol, mapper) { + var links = getSymbolLinks(symbol); + if (links.type && !maybeTypeOfKind(links.type, 524288 /* Object */ | 63176704 /* Instantiable */)) { + // If the type of the symbol is already resolved, and if that type could not possibly + // be affected by instantiation, simply return the symbol itself. + return symbol; + } + if (ts.getCheckFlags(symbol) & 1 /* Instantiated */) { + // If symbol being instantiated is itself a instantiation, fetch the original target and combine the + // type mappers. This ensures that original type identities are properly preserved and that aliases + // always reference a non-aliases. + symbol = links.target; + mapper = combineTypeMappers(links.mapper, mapper); + } + // Keep the flags from the symbol we're instantiating. Mark that is instantiated, and + // also transient so that we can just store data on it directly. + var result = createSymbol(symbol.flags, symbol.escapedName, 1 /* Instantiated */ | ts.getCheckFlags(symbol) & (1024 /* Late */ | 4096 /* OptionalParameter */ | 8192 /* RestParameter */)); + result.declarations = symbol.declarations; + result.parent = symbol.parent; + result.target = symbol; + result.mapper = mapper; + if (symbol.valueDeclaration) { + result.valueDeclaration = symbol.valueDeclaration; + } + if (symbol.nameType) { + result.nameType = symbol.nameType; + } + return result; + } + function getAnonymousTypeInstantiation(type, mapper) { + var target = type.objectFlags & 64 /* Instantiated */ ? type.target : type; + var symbol = target.symbol; + var links = getSymbolLinks(symbol); + var typeParameters = links.outerTypeParameters; + if (!typeParameters) { + // The first time an anonymous type is instantiated we compute and store a list of the type + // parameters that are in scope (and therefore potentially referenced). For type literals that + // aren't the right hand side of a generic type alias declaration we optimize by reducing the + // set of type parameters to those that are possibly referenced in the literal. + var declaration_1 = symbol.declarations[0]; + if (ts.isInJSFile(declaration_1)) { + var paramTag = ts.findAncestor(declaration_1, ts.isJSDocParameterTag); + if (paramTag) { + var paramSymbol = ts.getParameterSymbolFromJSDoc(paramTag); + if (paramSymbol) { + declaration_1 = paramSymbol.valueDeclaration; + } + } + } + var outerTypeParameters = getOuterTypeParameters(declaration_1, /*includeThisTypes*/ true); + if (isJSConstructor(declaration_1)) { + var templateTagParameters = getTypeParametersFromDeclaration(declaration_1); + outerTypeParameters = ts.addRange(outerTypeParameters, templateTagParameters); + } + typeParameters = outerTypeParameters || ts.emptyArray; + typeParameters = symbol.flags & 2048 /* TypeLiteral */ && !target.aliasTypeArguments ? + ts.filter(typeParameters, function (tp) { return isTypeParameterPossiblyReferenced(tp, declaration_1); }) : + typeParameters; + links.outerTypeParameters = typeParameters; + if (typeParameters.length) { + links.instantiations = ts.createMap(); + links.instantiations.set(getTypeListId(typeParameters), target); + } + } + if (typeParameters.length) { + // We are instantiating an anonymous type that has one or more type parameters in scope. Apply the + // mapper to the type parameters to produce the effective list of type arguments, and compute the + // instantiation cache key from the type IDs of the type arguments. + var combinedMapper = type.objectFlags & 64 /* Instantiated */ ? combineTypeMappers(type.mapper, mapper) : mapper; + var typeArguments = ts.map(typeParameters, combinedMapper); + var id = getTypeListId(typeArguments); + var result = links.instantiations.get(id); + if (!result) { + var newMapper = createTypeMapper(typeParameters, typeArguments); + result = target.objectFlags & 32 /* Mapped */ ? instantiateMappedType(target, newMapper) : instantiateAnonymousType(target, newMapper); + links.instantiations.set(id, result); + } + return result; + } + return type; + } + function maybeTypeParameterReference(node) { + return !(node.kind === 148 /* QualifiedName */ || + node.parent.kind === 164 /* TypeReference */ && node.parent.typeArguments && node === node.parent.typeName); + } + function isTypeParameterPossiblyReferenced(tp, node) { + // If the type parameter doesn't have exactly one declaration, if there are invening statement blocks + // between the node and the type parameter declaration, if the node contains actual references to the + // type parameter, or if the node contains type queries, we consider the type parameter possibly referenced. + if (tp.symbol && tp.symbol.declarations && tp.symbol.declarations.length === 1) { + var container_3 = tp.symbol.declarations[0].parent; + if (ts.findAncestor(node, function (n) { return n.kind === 218 /* Block */ ? "quit" : n === container_3; })) { + return !!ts.forEachChild(node, containsReference); + } + } + return true; + function containsReference(node) { + switch (node.kind) { + case 178 /* ThisType */: + return !!tp.isThisType; + case 72 /* Identifier */: + return !tp.isThisType && ts.isPartOfTypeNode(node) && maybeTypeParameterReference(node) && + getTypeFromTypeNode(node) === tp; + case 167 /* TypeQuery */: + return true; + } + return !!ts.forEachChild(node, containsReference); + } + } + function getHomomorphicTypeVariable(type) { + var constraintType = getConstraintTypeFromMappedType(type); + if (constraintType.flags & 4194304 /* Index */) { + var typeVariable = constraintType.type; + if (typeVariable.flags & 262144 /* TypeParameter */) { + return typeVariable; + } + } + return undefined; + } + function instantiateMappedType(type, mapper) { + // For a homomorphic mapped type { [P in keyof T]: X }, where T is some type variable, the mapping + // operation depends on T as follows: + // * If T is a primitive type no mapping is performed and the result is simply T. + // * If T is a union type we distribute the mapped type over the union. + // * If T is an array we map to an array where the element type has been transformed. + // * If T is a tuple we map to a tuple where the element types have been transformed. + // * Otherwise we map to an object type where the type of each property has been transformed. + // For example, when T is instantiated to a union type A | B, we produce { [P in keyof A]: X } | + // { [P in keyof B]: X }, and when when T is instantiated to a union type A | undefined, we produce + // { [P in keyof A]: X } | undefined. + var typeVariable = getHomomorphicTypeVariable(type); + if (typeVariable) { + var mappedTypeVariable = instantiateType(typeVariable, mapper); + if (typeVariable !== mappedTypeVariable) { + // If we are already in the process of creating an instantiation of this mapped type, + // return the error type. This situation only arises if we are instantiating the mapped + // type for an array or tuple type, as we then need to eagerly resolve the (possibly + // circular) element type(s). + if (type.instantiating) { + return errorType; + } + type.instantiating = true; + var result = mapType(mappedTypeVariable, function (t) { + if (t.flags & (3 /* AnyOrUnknown */ | 58982400 /* InstantiableNonPrimitive */ | 524288 /* Object */ | 2097152 /* Intersection */) && t !== wildcardType) { + var replacementMapper = createReplacementMapper(typeVariable, t, mapper); + return isArrayType(t) ? createArrayType(instantiateMappedTypeTemplate(type, numberType, /*isOptional*/ true, replacementMapper)) : + isReadonlyArrayType(t) ? createReadonlyArrayType(instantiateMappedTypeTemplate(type, numberType, /*isOptional*/ true, replacementMapper)) : + isTupleType(t) ? instantiateMappedTupleType(t, type, replacementMapper) : + instantiateAnonymousType(type, replacementMapper); + } + return t; + }); + type.instantiating = false; + return result; + } + } + return instantiateAnonymousType(type, mapper); + } + function instantiateMappedTupleType(tupleType, mappedType, mapper) { + var minLength = tupleType.target.minLength; + var elementTypes = ts.map(tupleType.typeArguments || ts.emptyArray, function (_, i) { + return instantiateMappedTypeTemplate(mappedType, getLiteralType("" + i), i >= minLength, mapper); + }); + var modifiers = getMappedTypeModifiers(mappedType); + var newMinLength = modifiers & 4 /* IncludeOptional */ ? 0 : + modifiers & 8 /* ExcludeOptional */ ? getTypeReferenceArity(tupleType) - (tupleType.target.hasRestElement ? 1 : 0) : + minLength; + return createTupleType(elementTypes, newMinLength, tupleType.target.hasRestElement, tupleType.target.associatedNames); + } + function instantiateMappedTypeTemplate(type, key, isOptional, mapper) { + var templateMapper = combineTypeMappers(mapper, createTypeMapper([getTypeParameterFromMappedType(type)], [key])); + var propType = instantiateType(getTemplateTypeFromMappedType(type.target || type), templateMapper); + var modifiers = getMappedTypeModifiers(type); + return strictNullChecks && modifiers & 4 /* IncludeOptional */ && !isTypeAssignableTo(undefinedType, propType) ? getOptionalType(propType) : + strictNullChecks && modifiers & 8 /* ExcludeOptional */ && isOptional ? getTypeWithFacts(propType, 524288 /* NEUndefined */) : + propType; + } + function instantiateAnonymousType(type, mapper) { + var result = createObjectType(type.objectFlags | 64 /* Instantiated */, type.symbol); + if (type.objectFlags & 32 /* Mapped */) { + result.declaration = type.declaration; + // C.f. instantiateSignature + var origTypeParameter = getTypeParameterFromMappedType(type); + var freshTypeParameter = cloneTypeParameter(origTypeParameter); + result.typeParameter = freshTypeParameter; + mapper = combineTypeMappers(makeUnaryTypeMapper(origTypeParameter, freshTypeParameter), mapper); + freshTypeParameter.mapper = mapper; + } + result.target = type; + result.mapper = mapper; + result.aliasSymbol = type.aliasSymbol; + result.aliasTypeArguments = instantiateTypes(type.aliasTypeArguments, mapper); + return result; + } + function getConditionalTypeInstantiation(type, mapper) { + var root = type.root; + if (root.outerTypeParameters) { + // We are instantiating a conditional type that has one or more type parameters in scope. Apply the + // mapper to the type parameters to produce the effective list of type arguments, and compute the + // instantiation cache key from the type IDs of the type arguments. + var typeArguments = ts.map(root.outerTypeParameters, mapper); + var id = getTypeListId(typeArguments); + var result = root.instantiations.get(id); + if (!result) { + var newMapper = createTypeMapper(root.outerTypeParameters, typeArguments); + result = instantiateConditionalType(root, newMapper); + root.instantiations.set(id, result); + } + return result; + } + return type; + } + function instantiateConditionalType(root, mapper) { + // Check if we have a conditional type where the check type is a naked type parameter. If so, + // the conditional type is distributive over union types and when T is instantiated to a union + // type A | B, we produce (A extends U ? X : Y) | (B extends U ? X : Y). + if (root.isDistributive) { + var checkType_1 = root.checkType; + var instantiatedType = mapper(checkType_1); + if (checkType_1 !== instantiatedType && instantiatedType.flags & (1048576 /* Union */ | 131072 /* Never */)) { + return mapType(instantiatedType, function (t) { return getConditionalType(root, createReplacementMapper(checkType_1, t, mapper)); }); + } + } + return getConditionalType(root, mapper); + } + function instantiateType(type, mapper) { + if (!type || !mapper || mapper === identityMapper) { + return type; + } + if (instantiationDepth === 50) { + // We have reached 50 recursive type instantiations and there is a very high likelyhood we're dealing + // with a combination of infinite generic types that perpetually generate new type identities. We stop + // the recursion here by yielding the error type. + return errorType; + } + instantiationDepth++; + var result = instantiateTypeWorker(type, mapper); + instantiationDepth--; + return result; + } + function instantiateTypeWorker(type, mapper) { + var flags = type.flags; + if (flags & 262144 /* TypeParameter */) { + return mapper(type); + } + if (flags & 524288 /* Object */) { + var objectFlags = type.objectFlags; + if (objectFlags & 16 /* Anonymous */) { + // If the anonymous type originates in a declaration of a function, method, class, or + // interface, in an object type literal, or in an object literal expression, we may need + // to instantiate the type because it might reference a type parameter. + return type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && type.symbol.declarations ? + getAnonymousTypeInstantiation(type, mapper) : type; + } + if (objectFlags & 32 /* Mapped */) { + return getAnonymousTypeInstantiation(type, mapper); + } + if (objectFlags & 4 /* Reference */) { + var typeArguments = type.typeArguments; + var newTypeArguments = instantiateTypes(typeArguments, mapper); + return newTypeArguments !== typeArguments ? createTypeReference(type.target, newTypeArguments) : type; + } + return type; + } + if (flags & 1048576 /* Union */ && !(flags & 131068 /* Primitive */)) { + var types = type.types; + var newTypes = instantiateTypes(types, mapper); + return newTypes !== types ? getUnionType(newTypes, 1 /* Literal */, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type; + } + if (flags & 2097152 /* Intersection */) { + var types = type.types; + var newTypes = instantiateTypes(types, mapper); + return newTypes !== types ? getIntersectionType(newTypes, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type; + } + if (flags & 4194304 /* Index */) { + return getIndexType(instantiateType(type.type, mapper)); + } + if (flags & 8388608 /* IndexedAccess */) { + return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper)); + } + if (flags & 16777216 /* Conditional */) { + return getConditionalTypeInstantiation(type, combineTypeMappers(type.mapper, mapper)); + } + if (flags & 33554432 /* Substitution */) { + return instantiateType(type.typeVariable, mapper); + } + return type; + } + function getWildcardInstantiation(type) { + return type.flags & (131068 /* Primitive */ | 3 /* AnyOrUnknown */ | 131072 /* Never */) ? type : + type.wildcardInstantiation || (type.wildcardInstantiation = instantiateType(type, wildcardMapper)); + } + function instantiateIndexInfo(info, mapper) { + return info && createIndexInfo(instantiateType(info.type, mapper), info.isReadonly, info.declaration); + } + // Returns true if the given expression contains (at any level of nesting) a function or arrow expression + // that is subject to contextual typing. + function isContextSensitive(node) { + ts.Debug.assert(node.kind !== 156 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + switch (node.kind) { + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 156 /* MethodDeclaration */: + return isContextSensitiveFunctionLikeDeclaration(node); + case 188 /* ObjectLiteralExpression */: + return ts.some(node.properties, isContextSensitive); + case 187 /* ArrayLiteralExpression */: + return ts.some(node.elements, isContextSensitive); + case 205 /* ConditionalExpression */: + return isContextSensitive(node.whenTrue) || + isContextSensitive(node.whenFalse); + case 204 /* BinaryExpression */: + return node.operatorToken.kind === 55 /* BarBarToken */ && + (isContextSensitive(node.left) || isContextSensitive(node.right)); + case 275 /* PropertyAssignment */: + return isContextSensitive(node.initializer); + case 195 /* ParenthesizedExpression */: + return isContextSensitive(node.expression); + case 268 /* JsxAttributes */: + return ts.some(node.properties, isContextSensitive) || ts.isJsxOpeningElement(node.parent) && ts.some(node.parent.parent.children, isContextSensitive); + case 267 /* JsxAttribute */: { + // If there is no initializer, JSX attribute has a boolean value of true which is not context sensitive. + var initializer = node.initializer; + return !!initializer && isContextSensitive(initializer); + } + case 270 /* JsxExpression */: { + // It is possible to that node.expression is undefined (e.g
      ) + var expression = node.expression; + return !!expression && isContextSensitive(expression); + } + } + return false; + } + function isContextSensitiveFunctionLikeDeclaration(node) { + // Functions with type parameters are not context sensitive. + if (node.typeParameters) { + return false; + } + // Functions with any parameters that lack type annotations are context sensitive. + if (ts.some(node.parameters, function (p) { return !ts.getEffectiveTypeAnnotationNode(p); })) { + return true; + } + if (node.kind !== 197 /* ArrowFunction */) { + // If the first parameter is not an explicit 'this' parameter, then the function has + // an implicit 'this' parameter which is subject to contextual typing. + var parameter = ts.firstOrUndefined(node.parameters); + if (!(parameter && ts.parameterIsThisKeyword(parameter))) { + return true; + } + } + return hasContextSensitiveReturnExpression(node); + } + function hasContextSensitiveReturnExpression(node) { + // TODO(anhans): A block should be context-sensitive if it has a context-sensitive return value. + var body = node.body; + return body.kind === 218 /* Block */ ? false : isContextSensitive(body); + } + function isContextSensitiveFunctionOrObjectLiteralMethod(func) { + return (ts.isInJSFile(func) && ts.isFunctionDeclaration(func) || isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && + isContextSensitiveFunctionLikeDeclaration(func); + } + function getTypeWithoutSignatures(type) { + if (type.flags & 524288 /* Object */) { + var resolved = resolveStructuredTypeMembers(type); + if (resolved.constructSignatures.length || resolved.callSignatures.length) { + var result = createObjectType(16 /* Anonymous */, type.symbol); + result.members = resolved.members; + result.properties = resolved.properties; + result.callSignatures = ts.emptyArray; + result.constructSignatures = ts.emptyArray; + return result; + } + } + else if (type.flags & 2097152 /* Intersection */) { + return getIntersectionType(ts.map(type.types, getTypeWithoutSignatures)); + } + return type; + } + // TYPE CHECKING + function isTypeIdenticalTo(source, target) { + return isTypeRelatedTo(source, target, identityRelation); + } + function compareTypesIdentical(source, target) { + return isTypeRelatedTo(source, target, identityRelation) ? -1 /* True */ : 0 /* False */; + } + function compareTypesAssignable(source, target) { + return isTypeRelatedTo(source, target, assignableRelation) ? -1 /* True */ : 0 /* False */; + } + function compareTypesSubtypeOf(source, target) { + return isTypeRelatedTo(source, target, subtypeRelation) ? -1 /* True */ : 0 /* False */; + } + function isTypeSubtypeOf(source, target) { + return isTypeRelatedTo(source, target, subtypeRelation); + } + function isTypeAssignableTo(source, target) { + return isTypeRelatedTo(source, target, assignableRelation); + } + // An object type S is considered to be derived from an object type T if + // S is a union type and every constituent of S is derived from T, + // T is a union type and S is derived from at least one constituent of T, or + // S is a type variable with a base constraint that is derived from T, + // T is one of the global types Object and Function and S is a subtype of T, or + // T occurs directly or indirectly in an 'extends' clause of S. + // Note that this check ignores type parameters and only considers the + // inheritance hierarchy. + function isTypeDerivedFrom(source, target) { + return source.flags & 1048576 /* Union */ ? ts.every(source.types, function (t) { return isTypeDerivedFrom(t, target); }) : + target.flags & 1048576 /* Union */ ? ts.some(target.types, function (t) { return isTypeDerivedFrom(source, t); }) : + source.flags & 58982400 /* InstantiableNonPrimitive */ ? isTypeDerivedFrom(getBaseConstraintOfType(source) || emptyObjectType, target) : + target === globalObjectType ? !!(source.flags & (524288 /* Object */ | 67108864 /* NonPrimitive */)) : + target === globalFunctionType ? !!(source.flags & 524288 /* Object */) && isFunctionObjectType(source) : + hasBaseType(source, getTargetType(target)); + } + /** + * This is *not* a bi-directional relationship. + * If one needs to check both directions for comparability, use a second call to this function or 'checkTypeComparableTo'. + * + * A type S is comparable to a type T if some (but not necessarily all) of the possible values of S are also possible values of T. + * It is used to check following cases: + * - the types of the left and right sides of equality/inequality operators (`===`, `!==`, `==`, `!=`). + * - the types of `case` clause expressions and their respective `switch` expressions. + * - the type of an expression in a type assertion with the type being asserted. + */ + function isTypeComparableTo(source, target) { + return isTypeRelatedTo(source, target, comparableRelation); + } + function areTypesComparable(type1, type2) { + return isTypeComparableTo(type1, type2) || isTypeComparableTo(type2, type1); + } + function checkTypeAssignableTo(source, target, errorNode, headMessage, containingMessageChain, errorOutputObject) { + return checkTypeRelatedTo(source, target, assignableRelation, errorNode, headMessage, containingMessageChain, errorOutputObject); + } + /** + * Like `checkTypeAssignableTo`, but if it would issue an error, instead performs structural comparisons of the types using the given expression node to + * attempt to issue more specific errors on, for example, specific object literal properties or tuple members. + */ + function checkTypeAssignableToAndOptionallyElaborate(source, target, errorNode, expr, headMessage, containingMessageChain) { + return checkTypeRelatedToAndOptionallyElaborate(source, target, assignableRelation, errorNode, expr, headMessage, containingMessageChain); + } + function checkTypeRelatedToAndOptionallyElaborate(source, target, relation, errorNode, expr, headMessage, containingMessageChain) { + if (isTypeRelatedTo(source, target, relation)) + return true; + if (!errorNode || !elaborateError(expr, source, target, relation, headMessage)) { + return checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain); + } + return false; + } + function isOrHasGenericConditional(type) { + return !!(type.flags & 16777216 /* Conditional */ || (type.flags & 2097152 /* Intersection */ && ts.some(type.types, isOrHasGenericConditional))); + } + function elaborateError(node, source, target, relation, headMessage) { + if (!node || isOrHasGenericConditional(target)) + return false; + if (!checkTypeRelatedTo(source, target, relation, /*errorNode*/ undefined) && elaborateDidYouMeanToCallOrConstruct(node, source, target, relation, headMessage)) { + return true; + } + switch (node.kind) { + case 270 /* JsxExpression */: + case 195 /* ParenthesizedExpression */: + return elaborateError(node.expression, source, target, relation, headMessage); + case 204 /* BinaryExpression */: + switch (node.operatorToken.kind) { + case 59 /* EqualsToken */: + case 27 /* CommaToken */: + return elaborateError(node.right, source, target, relation, headMessage); + } + break; + case 188 /* ObjectLiteralExpression */: + return elaborateObjectLiteral(node, source, target, relation); + case 187 /* ArrayLiteralExpression */: + return elaborateArrayLiteral(node, source, target, relation); + case 268 /* JsxAttributes */: + return elaborateJsxAttributes(node, source, target, relation); + case 197 /* ArrowFunction */: + return elaborateArrowFunction(node, source, target, relation); + } + return false; + } + function elaborateDidYouMeanToCallOrConstruct(node, source, target, relation, headMessage) { + var callSignatures = getSignaturesOfType(source, 0 /* Call */); + var constructSignatures = getSignaturesOfType(source, 1 /* Construct */); + for (var _i = 0, _a = [constructSignatures, callSignatures]; _i < _a.length; _i++) { + var signatures = _a[_i]; + if (ts.some(signatures, function (s) { + var returnType = getReturnTypeOfSignature(s); + return !(returnType.flags & (1 /* Any */ | 131072 /* Never */)) && checkTypeRelatedTo(returnType, target, relation, /*errorNode*/ undefined); + })) { + var resultObj = {}; + checkTypeAssignableTo(source, target, node, headMessage, /*containingChain*/ undefined, resultObj); + var diagnostic = resultObj.error; + addRelatedInfo(diagnostic, ts.createDiagnosticForNode(node, signatures === constructSignatures ? ts.Diagnostics.Did_you_mean_to_use_new_with_this_expression : ts.Diagnostics.Did_you_mean_to_call_this_expression)); + return true; + } + } + return false; + } + function elaborateArrowFunction(node, source, target, relation) { + // Don't elaborate blocks + if (ts.isBlock(node.body)) { + return false; + } + // Or functions with annotated parameter types + if (ts.some(node.parameters, ts.hasType)) { + return false; + } + var sourceSig = getSingleCallSignature(source); + if (!sourceSig) { + return false; + } + var targetSignatures = getSignaturesOfType(target, 0 /* Call */); + if (!ts.length(targetSignatures)) { + return false; + } + var returnExpression = node.body; + var sourceReturn = getReturnTypeOfSignature(sourceSig); + var targetReturn = getUnionType(ts.map(targetSignatures, getReturnTypeOfSignature)); + if (!checkTypeRelatedTo(sourceReturn, targetReturn, relation, /*errorNode*/ undefined)) { + var elaborated = returnExpression && elaborateError(returnExpression, sourceReturn, targetReturn, relation, /*headMessage*/ undefined); + if (elaborated) { + return elaborated; + } + var resultObj = {}; + checkTypeRelatedTo(sourceReturn, targetReturn, relation, returnExpression, /*message*/ undefined, /*chain*/ undefined, resultObj); + if (resultObj.error) { + if (target.symbol && ts.length(target.symbol.declarations)) { + addRelatedInfo(resultObj.error, ts.createDiagnosticForNode(target.symbol.declarations[0], ts.Diagnostics.The_expected_type_comes_from_the_return_type_of_this_signature)); + } + return true; + } + } + return false; + } + /** + * For every element returned from the iterator, checks that element to issue an error on a property of that element's type + * If that element would issue an error, we first attempt to dive into that element's inner expression and issue a more specific error by recuring into `elaborateError` + * Otherwise, we issue an error on _every_ element which fail the assignability check + */ + function elaborateElementwise(iterator, source, target, relation) { + // Assignability failure - check each prop individually, and if that fails, fall back on the bad error span + var reportedError = false; + for (var status = iterator.next(); !status.done; status = iterator.next()) { + var _a = status.value, prop = _a.errorNode, next = _a.innerExpression, nameType = _a.nameType, errorMessage = _a.errorMessage; + var targetPropType = getIndexedAccessType(target, nameType, /*accessNode*/ undefined, errorType); + if (targetPropType === errorType || targetPropType.flags & 8388608 /* IndexedAccess */) + continue; // Don't elaborate on indexes on generic variables + var sourcePropType = getIndexedAccessType(source, nameType, /*accessNode*/ undefined, errorType); + if (sourcePropType !== errorType && targetPropType !== errorType && !checkTypeRelatedTo(sourcePropType, targetPropType, relation, /*errorNode*/ undefined)) { + var elaborated = next && elaborateError(next, sourcePropType, targetPropType, relation, /*headMessage*/ undefined); + if (elaborated) { + reportedError = true; + } + else { + // Issue error on the prop itself, since the prop couldn't elaborate the error + var resultObj = {}; + // Use the expression type, if available + var specificSource = next ? checkExpressionForMutableLocation(next, 0 /* Normal */, sourcePropType) : sourcePropType; + var result = checkTypeRelatedTo(specificSource, targetPropType, relation, prop, errorMessage, /*containingChain*/ undefined, resultObj); + if (result && specificSource !== sourcePropType) { + // If for whatever reason the expression type doesn't yield an error, make sure we still issue an error on the sourcePropType + checkTypeRelatedTo(sourcePropType, targetPropType, relation, prop, errorMessage, /*containingChain*/ undefined, resultObj); + } + if (resultObj.error) { + var reportedDiag = resultObj.error; + var propertyName = isTypeUsableAsLateBoundName(nameType) ? getLateBoundNameFromType(nameType) : undefined; + var targetProp = propertyName !== undefined ? getPropertyOfType(target, propertyName) : undefined; + var issuedElaboration = false; + if (!targetProp) { + var indexInfo = isTypeAssignableToKind(nameType, 296 /* NumberLike */) && getIndexInfoOfType(target, 1 /* Number */) || + getIndexInfoOfType(target, 0 /* String */) || + undefined; + if (indexInfo && indexInfo.declaration && !ts.getSourceFileOfNode(indexInfo.declaration).hasNoDefaultLib) { + issuedElaboration = true; + addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(indexInfo.declaration, ts.Diagnostics.The_expected_type_comes_from_this_index_signature)); + } + } + if (!issuedElaboration && (targetProp && ts.length(targetProp.declarations) || target.symbol && ts.length(target.symbol.declarations))) { + var targetNode = targetProp && ts.length(targetProp.declarations) ? targetProp.declarations[0] : target.symbol.declarations[0]; + if (!ts.getSourceFileOfNode(targetNode).hasNoDefaultLib) { + addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(targetNode, ts.Diagnostics.The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1, propertyName && !(nameType.flags & 8192 /* UniqueESSymbol */) ? ts.unescapeLeadingUnderscores(propertyName) : typeToString(nameType), typeToString(target))); + } + } + } + reportedError = true; + } + } + } + return reportedError; + } + function generateJsxAttributes(node) { + var _i, _a, prop; + return __generator(this, function (_b) { + switch (_b.label) { + case 0: + if (!ts.length(node.properties)) + return [2 /*return*/]; + _i = 0, _a = node.properties; + _b.label = 1; + case 1: + if (!(_i < _a.length)) return [3 /*break*/, 4]; + prop = _a[_i]; + if (ts.isJsxSpreadAttribute(prop)) + return [3 /*break*/, 3]; + return [4 /*yield*/, { errorNode: prop.name, innerExpression: prop.initializer, nameType: getLiteralType(ts.idText(prop.name)) }]; + case 2: + _b.sent(); + _b.label = 3; + case 3: + _i++; + return [3 /*break*/, 1]; + case 4: return [2 /*return*/]; + } + }); + } + function elaborateJsxAttributes(node, source, target, relation) { + return elaborateElementwise(generateJsxAttributes(node), source, target, relation); + } + function generateLimitedTupleElements(node, target) { + var len, i, elem, nameType; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + len = ts.length(node.elements); + if (!len) + return [2 /*return*/]; + i = 0; + _a.label = 1; + case 1: + if (!(i < len)) return [3 /*break*/, 4]; + // Skip elements which do not exist in the target - a length error on the tuple overall is likely better than an error on a mismatched index signature + if (isTupleLikeType(target) && !getPropertyOfType(target, ("" + i))) + return [3 /*break*/, 3]; + elem = node.elements[i]; + if (ts.isOmittedExpression(elem)) + return [3 /*break*/, 3]; + nameType = getLiteralType(i); + return [4 /*yield*/, { errorNode: elem, innerExpression: elem, nameType: nameType }]; + case 2: + _a.sent(); + _a.label = 3; + case 3: + i++; + return [3 /*break*/, 1]; + case 4: return [2 /*return*/]; + } + }); + } + function elaborateArrayLiteral(node, source, target, relation) { + if (isTupleLikeType(source)) { + return elaborateElementwise(generateLimitedTupleElements(node, target), source, target, relation); + } + // recreate a tuple from the elements, if possible + var tupleizedType = checkArrayLiteral(node, 3 /* Contextual */, /*forceTuple*/ true); + if (isTupleLikeType(tupleizedType)) { + return elaborateElementwise(generateLimitedTupleElements(node, target), tupleizedType, target, relation); + } + return false; + } + function generateObjectLiteralElements(node) { + var _i, _a, prop, type, _b; + return __generator(this, function (_c) { + switch (_c.label) { + case 0: + if (!ts.length(node.properties)) + return [2 /*return*/]; + _i = 0, _a = node.properties; + _c.label = 1; + case 1: + if (!(_i < _a.length)) return [3 /*break*/, 8]; + prop = _a[_i]; + if (ts.isSpreadAssignment(prop)) + return [3 /*break*/, 7]; + type = getLiteralTypeFromProperty(getSymbolOfNode(prop), 8576 /* StringOrNumberLiteralOrUnique */); + if (!type || (type.flags & 131072 /* Never */)) { + return [3 /*break*/, 7]; + } + _b = prop.kind; + switch (_b) { + case 159 /* SetAccessor */: return [3 /*break*/, 2]; + case 158 /* GetAccessor */: return [3 /*break*/, 2]; + case 156 /* MethodDeclaration */: return [3 /*break*/, 2]; + case 276 /* ShorthandPropertyAssignment */: return [3 /*break*/, 2]; + case 275 /* PropertyAssignment */: return [3 /*break*/, 4]; + } + return [3 /*break*/, 6]; + case 2: return [4 /*yield*/, { errorNode: prop.name, innerExpression: undefined, nameType: type }]; + case 3: + _c.sent(); + return [3 /*break*/, 7]; + case 4: return [4 /*yield*/, { errorNode: prop.name, innerExpression: prop.initializer, nameType: type, errorMessage: isComputedNonLiteralName(prop.name) ? ts.Diagnostics.Type_of_computed_property_s_value_is_0_which_is_not_assignable_to_type_1 : undefined }]; + case 5: + _c.sent(); + return [3 /*break*/, 7]; + case 6: + ts.Debug.assertNever(prop); + _c.label = 7; + case 7: + _i++; + return [3 /*break*/, 1]; + case 8: return [2 /*return*/]; + } + }); + } + function elaborateObjectLiteral(node, source, target, relation) { + return elaborateElementwise(generateObjectLiteralElements(node), source, target, relation); + } + /** + * This is *not* a bi-directional relationship. + * If one needs to check both directions for comparability, use a second call to this function or 'isTypeComparableTo'. + */ + function checkTypeComparableTo(source, target, errorNode, headMessage, containingMessageChain) { + return checkTypeRelatedTo(source, target, comparableRelation, errorNode, headMessage, containingMessageChain); + } + function isSignatureAssignableTo(source, target, ignoreReturnTypes) { + return compareSignaturesRelated(source, target, 0 /* None */, ignoreReturnTypes, /*reportErrors*/ false, + /*errorReporter*/ undefined, compareTypesAssignable) !== 0 /* False */; + } + /** + * See signatureRelatedTo, compareSignaturesIdentical + */ + function compareSignaturesRelated(source, target, callbackCheck, ignoreReturnTypes, reportErrors, errorReporter, compareTypes) { + // TODO (drosen): De-duplicate code between related functions. + if (source === target) { + return -1 /* True */; + } + var targetCount = getParameterCount(target); + if (!hasEffectiveRestParameter(target) && getMinArgumentCount(source) > targetCount) { + return 0 /* False */; + } + if (source.typeParameters && source.typeParameters !== target.typeParameters) { + target = getCanonicalSignature(target); + source = instantiateSignatureInContextOf(source, target, /*contextualMapper*/ undefined, compareTypes); + } + var sourceCount = getParameterCount(source); + var sourceRestType = getNonArrayRestType(source); + var targetRestType = getNonArrayRestType(target); + if (sourceRestType && targetRestType && sourceCount !== targetCount) { + // We're not able to relate misaligned complex rest parameters + return 0 /* False */; + } + var kind = target.declaration ? target.declaration.kind : 0 /* Unknown */; + var strictVariance = !callbackCheck && strictFunctionTypes && kind !== 156 /* MethodDeclaration */ && + kind !== 155 /* MethodSignature */ && kind !== 157 /* Constructor */; + var result = -1 /* True */; + var sourceThisType = getThisTypeOfSignature(source); + if (sourceThisType && sourceThisType !== voidType) { + var targetThisType = getThisTypeOfSignature(target); + if (targetThisType) { + // void sources are assignable to anything. + var related = !strictVariance && compareTypes(sourceThisType, targetThisType, /*reportErrors*/ false) + || compareTypes(targetThisType, sourceThisType, reportErrors); + if (!related) { + if (reportErrors) { + errorReporter(ts.Diagnostics.The_this_types_of_each_signature_are_incompatible); + } + return 0 /* False */; + } + result &= related; + } + } + var paramCount = sourceRestType || targetRestType ? Math.min(sourceCount, targetCount) : Math.max(sourceCount, targetCount); + var restIndex = sourceRestType || targetRestType ? paramCount - 1 : -1; + for (var i = 0; i < paramCount; i++) { + var sourceType = i === restIndex ? getRestTypeAtPosition(source, i) : getTypeAtPosition(source, i); + var targetType = i === restIndex ? getRestTypeAtPosition(target, i) : getTypeAtPosition(target, i); + // In order to ensure that any generic type Foo is at least co-variant with respect to T no matter + // how Foo uses T, we need to relate parameters bi-variantly (given that parameters are input positions, + // they naturally relate only contra-variantly). However, if the source and target parameters both have + // function types with a single call signature, we know we are relating two callback parameters. In + // that case it is sufficient to only relate the parameters of the signatures co-variantly because, + // similar to return values, callback parameters are output positions. This means that a Promise, + // where T is used only in callback parameter positions, will be co-variant (as opposed to bi-variant) + // with respect to T. + var sourceSig = callbackCheck ? undefined : getSingleCallSignature(getNonNullableType(sourceType)); + var targetSig = callbackCheck ? undefined : getSingleCallSignature(getNonNullableType(targetType)); + var callbacks = sourceSig && targetSig && !signatureHasTypePredicate(sourceSig) && !signatureHasTypePredicate(targetSig) && + (getFalsyFlags(sourceType) & 98304 /* Nullable */) === (getFalsyFlags(targetType) & 98304 /* Nullable */); + var related = callbacks ? + // TODO: GH#18217 It will work if they're both `undefined`, but not if only one is + compareSignaturesRelated(targetSig, sourceSig, strictVariance ? 2 /* Strict */ : 1 /* Bivariant */, /*ignoreReturnTypes*/ false, reportErrors, errorReporter, compareTypes) : + !callbackCheck && !strictVariance && compareTypes(sourceType, targetType, /*reportErrors*/ false) || compareTypes(targetType, sourceType, reportErrors); + if (!related) { + if (reportErrors) { + errorReporter(ts.Diagnostics.Types_of_parameters_0_and_1_are_incompatible, ts.unescapeLeadingUnderscores(getParameterNameAtPosition(source, i)), ts.unescapeLeadingUnderscores(getParameterNameAtPosition(target, i))); + } + return 0 /* False */; + } + result &= related; + } + if (!ignoreReturnTypes) { + var targetReturnType = (target.declaration && isJSConstructor(target.declaration)) ? + getJSClassType(target.declaration.symbol) : getReturnTypeOfSignature(target); + if (targetReturnType === voidType) { + return result; + } + var sourceReturnType = (source.declaration && isJSConstructor(source.declaration)) ? + getJSClassType(source.declaration.symbol) : getReturnTypeOfSignature(source); + // The following block preserves behavior forbidding boolean returning functions from being assignable to type guard returning functions + var targetTypePredicate = getTypePredicateOfSignature(target); + if (targetTypePredicate) { + var sourceTypePredicate = getTypePredicateOfSignature(source); + if (sourceTypePredicate) { + result &= compareTypePredicateRelatedTo(sourceTypePredicate, targetTypePredicate, source.declaration, target.declaration, reportErrors, errorReporter, compareTypes); // TODO: GH#18217 + } + else if (ts.isIdentifierTypePredicate(targetTypePredicate)) { + if (reportErrors) { + errorReporter(ts.Diagnostics.Signature_0_must_be_a_type_predicate, signatureToString(source)); + } + return 0 /* False */; + } + } + else { + // When relating callback signatures, we still need to relate return types bi-variantly as otherwise + // the containing type wouldn't be co-variant. For example, interface Foo { add(cb: () => T): void } + // wouldn't be co-variant for T without this rule. + result &= callbackCheck === 1 /* Bivariant */ && compareTypes(targetReturnType, sourceReturnType, /*reportErrors*/ false) || + compareTypes(sourceReturnType, targetReturnType, reportErrors); + } + } + return result; + } + function compareTypePredicateRelatedTo(source, target, sourceDeclaration, targetDeclaration, reportErrors, errorReporter, compareTypes) { + if (source.kind !== target.kind) { + if (reportErrors) { + errorReporter(ts.Diagnostics.A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard); + errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target)); + } + return 0 /* False */; + } + if (source.kind === 1 /* Identifier */) { + var targetPredicate = target; + var sourceIndex = source.parameterIndex - (ts.getThisParameter(sourceDeclaration) ? 1 : 0); + var targetIndex = targetPredicate.parameterIndex - (ts.getThisParameter(targetDeclaration) ? 1 : 0); + if (sourceIndex !== targetIndex) { + if (reportErrors) { + errorReporter(ts.Diagnostics.Parameter_0_is_not_in_the_same_position_as_parameter_1, source.parameterName, targetPredicate.parameterName); + errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target)); + } + return 0 /* False */; + } + } + var related = compareTypes(source.type, target.type, reportErrors); + if (related === 0 /* False */ && reportErrors) { + errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target)); + } + return related; + } + function isImplementationCompatibleWithOverload(implementation, overload) { + var erasedSource = getErasedSignature(implementation); + var erasedTarget = getErasedSignature(overload); + // First see if the return types are compatible in either direction. + var sourceReturnType = getReturnTypeOfSignature(erasedSource); + var targetReturnType = getReturnTypeOfSignature(erasedTarget); + if (targetReturnType === voidType + || isTypeRelatedTo(targetReturnType, sourceReturnType, assignableRelation) + || isTypeRelatedTo(sourceReturnType, targetReturnType, assignableRelation)) { + return isSignatureAssignableTo(erasedSource, erasedTarget, /*ignoreReturnTypes*/ true); + } + return false; + } + function isEmptyResolvedType(t) { + return t.properties.length === 0 && + t.callSignatures.length === 0 && + t.constructSignatures.length === 0 && + !t.stringIndexInfo && + !t.numberIndexInfo; + } + function isEmptyObjectType(type) { + return type.flags & 524288 /* Object */ ? isEmptyResolvedType(resolveStructuredTypeMembers(type)) : + type.flags & 67108864 /* NonPrimitive */ ? true : + type.flags & 1048576 /* Union */ ? ts.some(type.types, isEmptyObjectType) : + type.flags & 2097152 /* Intersection */ ? ts.every(type.types, isEmptyObjectType) : + false; + } + function isEmptyAnonymousObjectType(type) { + return !!(ts.getObjectFlags(type) & 16 /* Anonymous */) && isEmptyObjectType(type); + } + function isEnumTypeRelatedTo(sourceSymbol, targetSymbol, errorReporter) { + if (sourceSymbol === targetSymbol) { + return true; + } + var id = getSymbolId(sourceSymbol) + "," + getSymbolId(targetSymbol); + var relation = enumRelation.get(id); + if (relation !== undefined && !(relation === 2 /* Failed */ && errorReporter)) { + return relation === 1 /* Succeeded */; + } + if (sourceSymbol.escapedName !== targetSymbol.escapedName || !(sourceSymbol.flags & 256 /* RegularEnum */) || !(targetSymbol.flags & 256 /* RegularEnum */)) { + enumRelation.set(id, 3 /* FailedAndReported */); + return false; + } + var targetEnumType = getTypeOfSymbol(targetSymbol); + for (var _i = 0, _a = getPropertiesOfType(getTypeOfSymbol(sourceSymbol)); _i < _a.length; _i++) { + var property = _a[_i]; + if (property.flags & 8 /* EnumMember */) { + var targetProperty = getPropertyOfType(targetEnumType, property.escapedName); + if (!targetProperty || !(targetProperty.flags & 8 /* EnumMember */)) { + if (errorReporter) { + errorReporter(ts.Diagnostics.Property_0_is_missing_in_type_1, ts.symbolName(property), typeToString(getDeclaredTypeOfSymbol(targetSymbol), /*enclosingDeclaration*/ undefined, 64 /* UseFullyQualifiedType */)); + enumRelation.set(id, 3 /* FailedAndReported */); + } + else { + enumRelation.set(id, 2 /* Failed */); + } + return false; + } + } + } + enumRelation.set(id, 1 /* Succeeded */); + return true; + } + function isSimpleTypeRelatedTo(source, target, relation, errorReporter) { + var s = source.flags; + var t = target.flags; + if (t & 3 /* AnyOrUnknown */ || s & 131072 /* Never */ || source === wildcardType) + return true; + if (t & 131072 /* Never */) + return false; + if (s & 132 /* StringLike */ && t & 4 /* String */) + return true; + if (s & 128 /* StringLiteral */ && s & 1024 /* EnumLiteral */ && + t & 128 /* StringLiteral */ && !(t & 1024 /* EnumLiteral */) && + source.value === target.value) + return true; + if (s & 296 /* NumberLike */ && t & 8 /* Number */) + return true; + if (s & 256 /* NumberLiteral */ && s & 1024 /* EnumLiteral */ && + t & 256 /* NumberLiteral */ && !(t & 1024 /* EnumLiteral */) && + source.value === target.value) + return true; + if (s & 2112 /* BigIntLike */ && t & 64 /* BigInt */) + return true; + if (s & 528 /* BooleanLike */ && t & 16 /* Boolean */) + return true; + if (s & 12288 /* ESSymbolLike */ && t & 4096 /* ESSymbol */) + return true; + if (s & 32 /* Enum */ && t & 32 /* Enum */ && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) + return true; + if (s & 1024 /* EnumLiteral */ && t & 1024 /* EnumLiteral */) { + if (s & 1048576 /* Union */ && t & 1048576 /* Union */ && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) + return true; + if (s & 2944 /* Literal */ && t & 2944 /* Literal */ && + source.value === target.value && + isEnumTypeRelatedTo(getParentOfSymbol(source.symbol), getParentOfSymbol(target.symbol), errorReporter)) + return true; + } + if (s & 32768 /* Undefined */ && (!strictNullChecks || t & (32768 /* Undefined */ | 16384 /* Void */))) + return true; + if (s & 65536 /* Null */ && (!strictNullChecks || t & 65536 /* Null */)) + return true; + if (s & 524288 /* Object */ && t & 67108864 /* NonPrimitive */) + return true; + if (s & 8192 /* UniqueESSymbol */ || t & 8192 /* UniqueESSymbol */) + return false; + if (relation === assignableRelation || relation === definitelyAssignableRelation || relation === comparableRelation) { + if (s & 1 /* Any */) + return true; + // Type number or any numeric literal type is assignable to any numeric enum type or any + // numeric enum literal type. This rule exists for backwards compatibility reasons because + // bit-flag enum types sometimes look like literal enum types with numeric literal values. + if (s & (8 /* Number */ | 256 /* NumberLiteral */) && !(s & 1024 /* EnumLiteral */) && (t & 32 /* Enum */ || t & 256 /* NumberLiteral */ && t & 1024 /* EnumLiteral */)) + return true; + } + return false; + } + function isTypeRelatedTo(source, target, relation) { + if (isFreshLiteralType(source)) { + source = source.regularType; + } + if (isFreshLiteralType(target)) { + target = target.regularType; + } + if (source === target || + relation === comparableRelation && !(target.flags & 131072 /* Never */) && isSimpleTypeRelatedTo(target, source, relation) || + relation !== identityRelation && isSimpleTypeRelatedTo(source, target, relation)) { + return true; + } + if (source.flags & 524288 /* Object */ && target.flags & 524288 /* Object */) { + var related = relation.get(getRelationKey(source, target, relation)); + if (related !== undefined) { + return related === 1 /* Succeeded */; + } + } + if (source.flags & 66846720 /* StructuredOrInstantiable */ || target.flags & 66846720 /* StructuredOrInstantiable */) { + return checkTypeRelatedTo(source, target, relation, /*errorNode*/ undefined); + } + return false; + } + function isIgnoredJsxProperty(source, sourceProp, targetMemberType) { + return ts.getObjectFlags(source) & 4096 /* JsxAttributes */ && !(isUnhyphenatedJsxName(sourceProp.escapedName) || targetMemberType); + } + /** + * Checks if 'source' is related to 'target' (e.g.: is a assignable to). + * @param source The left-hand-side of the relation. + * @param target The right-hand-side of the relation. + * @param relation The relation considered. One of 'identityRelation', 'subtypeRelation', 'assignableRelation', or 'comparableRelation'. + * Used as both to determine which checks are performed and as a cache of previously computed results. + * @param errorNode The suggested node upon which all errors will be reported, if defined. This may or may not be the actual node used. + * @param headMessage If the error chain should be prepended by a head message, then headMessage will be used. + * @param containingMessageChain A chain of errors to prepend any new errors found. + */ + function checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain, errorOutputContainer) { + var errorInfo; + var relatedInfo; + var maybeKeys; + var sourceStack; + var targetStack; + var maybeCount = 0; + var depth = 0; + var expandingFlags = 0 /* None */; + var overflow = false; + var suppressNextError = false; + ts.Debug.assert(relation !== identityRelation || !errorNode, "no error reporting in identity checking"); + var result = isRelatedTo(source, target, /*reportErrors*/ !!errorNode, headMessage); + if (overflow) { + error(errorNode, ts.Diagnostics.Excessive_stack_depth_comparing_types_0_and_1, typeToString(source), typeToString(target)); + } + else if (errorInfo) { + if (containingMessageChain) { + var chain_1 = containingMessageChain(); + if (chain_1) { + errorInfo = ts.concatenateDiagnosticMessageChains(chain_1, errorInfo); + } + } + var relatedInformation = void 0; + // Check if we should issue an extra diagnostic to produce a quickfix for a slightly incorrect import statement + if (headMessage && errorNode && !result && source.symbol) { + var links = getSymbolLinks(source.symbol); + if (links.originatingImport && !ts.isImportCall(links.originatingImport)) { + var helpfulRetry = checkTypeRelatedTo(getTypeOfSymbol(links.target), target, relation, /*errorNode*/ undefined); + if (helpfulRetry) { + // Likely an incorrect import. Issue a helpful diagnostic to produce a quickfix to change the import + var diag_1 = ts.createDiagnosticForNode(links.originatingImport, ts.Diagnostics.Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_Consider_using_a_default_import_or_import_require_here_instead); + relatedInformation = ts.append(relatedInformation, diag_1); // Cause the error to appear with the error that triggered it + } + } + } + var diag = ts.createDiagnosticForNodeFromMessageChain(errorNode, errorInfo, relatedInformation); + if (relatedInfo) { + addRelatedInfo.apply(void 0, [diag].concat(relatedInfo)); + } + if (errorOutputContainer) { + errorOutputContainer.error = diag; + } + diagnostics.add(diag); // TODO: GH#18217 + } + return result !== 0 /* False */; + function reportError(message, arg0, arg1, arg2, arg3) { + ts.Debug.assert(!!errorNode); + errorInfo = ts.chainDiagnosticMessages(errorInfo, message, arg0, arg1, arg2, arg3); + } + function associateRelatedInfo(info) { + ts.Debug.assert(!!errorInfo); + if (!relatedInfo) { + relatedInfo = [info]; + } + else { + relatedInfo.push(info); + } + } + function reportRelationError(message, source, target) { + var sourceType = typeToString(source); + var targetType = typeToString(target); + if (sourceType === targetType) { + sourceType = typeToString(source, /*enclosingDeclaration*/ undefined, 64 /* UseFullyQualifiedType */); + targetType = typeToString(target, /*enclosingDeclaration*/ undefined, 64 /* UseFullyQualifiedType */); + } + if (!message) { + if (relation === comparableRelation) { + message = ts.Diagnostics.Type_0_is_not_comparable_to_type_1; + } + else if (sourceType === targetType) { + message = ts.Diagnostics.Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated; + } + else { + message = ts.Diagnostics.Type_0_is_not_assignable_to_type_1; + } + } + reportError(message, sourceType, targetType); + } + function tryElaborateErrorsForPrimitivesAndObjects(source, target) { + var sourceType = typeToString(source); + var targetType = typeToString(target); + if ((globalStringType === source && stringType === target) || + (globalNumberType === source && numberType === target) || + (globalBooleanType === source && booleanType === target) || + (getGlobalESSymbolType(/*reportErrors*/ false) === source && esSymbolType === target)) { + reportError(ts.Diagnostics._0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible, targetType, sourceType); + } + } + function isUnionOrIntersectionTypeWithoutNullableConstituents(type) { + if (!(type.flags & 3145728 /* UnionOrIntersection */)) { + return false; + } + // at this point we know that this is union or intersection type possibly with nullable constituents. + // check if we still will have compound type if we ignore nullable components. + var seenNonNullable = false; + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (t.flags & 98304 /* Nullable */) { + continue; + } + if (seenNonNullable) { + return true; + } + seenNonNullable = true; + } + return false; + } + /** + * Compare two types and return + * * Ternary.True if they are related with no assumptions, + * * Ternary.Maybe if they are related with assumptions of other relationships, or + * * Ternary.False if they are not related. + */ + function isRelatedTo(source, target, reportErrors, headMessage, isApparentIntersectionConstituent) { + if (reportErrors === void 0) { reportErrors = false; } + if (isFreshLiteralType(source)) { + source = source.regularType; + } + if (isFreshLiteralType(target)) { + target = target.regularType; + } + if (source.flags & 33554432 /* Substitution */) { + source = relation === definitelyAssignableRelation ? source.typeVariable : source.substitute; + } + if (target.flags & 33554432 /* Substitution */) { + target = target.typeVariable; + } + if (source.flags & 8388608 /* IndexedAccess */) { + source = getSimplifiedType(source); + } + if (target.flags & 8388608 /* IndexedAccess */) { + target = getSimplifiedType(target); + } + // Try to see if we're relating something like `Foo` -> `Bar | null | undefined`. + // If so, reporting the `null` and `undefined` in the type is hardly useful. + // First, see if we're even relating an object type to a union. + // Then see if the target is stripped down to a single non-union type. + // Note + // * We actually want to remove null and undefined naively here (rather than using getNonNullableType), + // since we don't want to end up with a worse error like "`Foo` is not assignable to `NonNullable`" + // when dealing with generics. + // * We also don't deal with primitive source types, since we already halt elaboration below. + if (target.flags & 1048576 /* Union */ && source.flags & 524288 /* Object */ && + target.types.length <= 3 && maybeTypeOfKind(target, 98304 /* Nullable */)) { + var nullStrippedTarget = extractTypesOfKind(target, ~98304 /* Nullable */); + if (!(nullStrippedTarget.flags & (1048576 /* Union */ | 131072 /* Never */))) { + target = nullStrippedTarget; + } + } + // both types are the same - covers 'they are the same primitive type or both are Any' or the same type parameter cases + if (source === target) + return -1 /* True */; + if (relation === identityRelation) { + return isIdenticalTo(source, target); + } + if (relation === comparableRelation && !(target.flags & 131072 /* Never */) && isSimpleTypeRelatedTo(target, source, relation) || + isSimpleTypeRelatedTo(source, target, relation, reportErrors ? reportError : undefined)) + return -1 /* True */; + var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096 /* JsxAttributes */); + if (isObjectLiteralType(source) && ts.getObjectFlags(source) & 32768 /* FreshLiteral */) { + var discriminantType = target.flags & 1048576 /* Union */ ? findMatchingDiscriminantType(source, target) : undefined; + if (hasExcessProperties(source, target, discriminantType, reportErrors)) { + if (reportErrors) { + reportRelationError(headMessage, source, target); + } + return 0 /* False */; + } + // Above we check for excess properties with respect to the entire target type. When union + // and intersection types are further deconstructed on the target side, we don't want to + // make the check again (as it might fail for a partial target type). Therefore we obtain + // the regular source type and proceed with that. + if (isUnionOrIntersectionTypeWithoutNullableConstituents(target) && !discriminantType) { + source = getRegularTypeOfObjectLiteral(source); + } + } + if (relation !== comparableRelation && !isApparentIntersectionConstituent && + source.flags & (131068 /* Primitive */ | 524288 /* Object */ | 2097152 /* Intersection */) && source !== globalObjectType && + target.flags & (524288 /* Object */ | 2097152 /* Intersection */) && isWeakType(target) && + (getPropertiesOfType(source).length > 0 || typeHasCallOrConstructSignatures(source)) && + !hasCommonProperties(source, target, isComparingJsxAttributes)) { + if (reportErrors) { + var calls = getSignaturesOfType(source, 0 /* Call */); + var constructs = getSignaturesOfType(source, 1 /* Construct */); + if (calls.length > 0 && isRelatedTo(getReturnTypeOfSignature(calls[0]), target, /*reportErrors*/ false) || + constructs.length > 0 && isRelatedTo(getReturnTypeOfSignature(constructs[0]), target, /*reportErrors*/ false)) { + reportError(ts.Diagnostics.Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it, typeToString(source), typeToString(target)); + } + else { + reportError(ts.Diagnostics.Type_0_has_no_properties_in_common_with_type_1, typeToString(source), typeToString(target)); + } + } + return 0 /* False */; + } + var result = 0 /* False */; + var saveErrorInfo = errorInfo; + var isIntersectionConstituent = !!isApparentIntersectionConstituent; + // Note that these checks are specifically ordered to produce correct results. In particular, + // we need to deconstruct unions before intersections (because unions are always at the top), + // and we need to handle "each" relations before "some" relations for the same kind of type. + if (source.flags & 1048576 /* Union */) { + result = relation === comparableRelation ? + someTypeRelatedToType(source, target, reportErrors && !(source.flags & 131068 /* Primitive */)) : + eachTypeRelatedToType(source, target, reportErrors && !(source.flags & 131068 /* Primitive */)); + } + else { + if (target.flags & 1048576 /* Union */) { + result = typeRelatedToSomeType(source, target, reportErrors && !(source.flags & 131068 /* Primitive */) && !(target.flags & 131068 /* Primitive */)); + } + else if (target.flags & 2097152 /* Intersection */) { + isIntersectionConstituent = true; // set here to affect the following trio of checks + result = typeRelatedToEachType(source, target, reportErrors); + } + else if (source.flags & 2097152 /* Intersection */) { + // Check to see if any constituents of the intersection are immediately related to the target. + // + // Don't report errors though. Checking whether a constituent is related to the source is not actually + // useful and leads to some confusing error messages. Instead it is better to let the below checks + // take care of this, or to not elaborate at all. For instance, + // + // - For an object type (such as 'C = A & B'), users are usually more interested in structural errors. + // + // - For a union type (such as '(A | B) = (C & D)'), it's better to hold onto the whole intersection + // than to report that 'D' is not assignable to 'A' or 'B'. + // + // - For a primitive type or type parameter (such as 'number = A & B') there is no point in + // breaking the intersection apart. + result = someTypeRelatedToType(source, target, /*reportErrors*/ false); + } + if (!result && (source.flags & 66846720 /* StructuredOrInstantiable */ || target.flags & 66846720 /* StructuredOrInstantiable */)) { + if (result = recursiveTypeRelatedTo(source, target, reportErrors, isIntersectionConstituent)) { + errorInfo = saveErrorInfo; + } + } + } + if (!result && source.flags & 2097152 /* Intersection */) { + // The combined constraint of an intersection type is the intersection of the constraints of + // the constituents. When an intersection type contains instantiable types with union type + // constraints, there are situations where we need to examine the combined constraint. One is + // when the target is a union type. Another is when the intersection contains types belonging + // to one of the disjoint domains. For example, given type variables T and U, each with the + // constraint 'string | number', the combined constraint of 'T & U' is 'string | number' and + // we need to check this constraint against a union on the target side. Also, given a type + // variable V constrained to 'string | number', 'V & number' has a combined constraint of + // 'string & number | number & number' which reduces to just 'number'. + var constraint = getUnionConstraintOfIntersection(source, !!(target.flags & 1048576 /* Union */)); + if (constraint) { + if (result = isRelatedTo(constraint, target, reportErrors, /*headMessage*/ undefined, isIntersectionConstituent)) { + errorInfo = saveErrorInfo; + } + } + } + if (!result && reportErrors) { + var maybeSuppress = suppressNextError; + suppressNextError = false; + if (source.flags & 524288 /* Object */ && target.flags & 131068 /* Primitive */) { + tryElaborateErrorsForPrimitivesAndObjects(source, target); + } + else if (source.symbol && source.flags & 524288 /* Object */ && globalObjectType === source) { + reportError(ts.Diagnostics.The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead); + } + else if (isComparingJsxAttributes && target.flags & 2097152 /* Intersection */) { + var targetTypes = target.types; + var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes, errorNode); + var intrinsicClassAttributes = getJsxType(JsxNames.IntrinsicClassAttributes, errorNode); + if (intrinsicAttributes !== errorType && intrinsicClassAttributes !== errorType && + (ts.contains(targetTypes, intrinsicAttributes) || ts.contains(targetTypes, intrinsicClassAttributes))) { + // do not report top error + return result; + } + } + if (!headMessage && maybeSuppress) { + // Used by, eg, missing property checking to replace the top-level message with a more informative one + return result; + } + reportRelationError(headMessage, source, target); + } + return result; + } + function isIdenticalTo(source, target) { + var result; + var flags = source.flags & target.flags; + if (flags & 524288 /* Object */ || flags & 8388608 /* IndexedAccess */ || flags & 16777216 /* Conditional */ || flags & 4194304 /* Index */ || flags & 33554432 /* Substitution */) { + return recursiveTypeRelatedTo(source, target, /*reportErrors*/ false, /*isIntersectionConstituent*/ false); + } + if (flags & (1048576 /* Union */ | 2097152 /* Intersection */)) { + if (result = eachTypeRelatedToSomeType(source, target)) { + if (result &= eachTypeRelatedToSomeType(target, source)) { + return result; + } + } + } + return 0 /* False */; + } + function hasExcessProperties(source, target, discriminant, reportErrors) { + if (!noImplicitAny && ts.getObjectFlags(target) & 16384 /* JSLiteral */) { + return false; // Disable excess property checks on JS literals to simulate having an implicit "index signature" - but only outside of noImplicitAny + } + if (maybeTypeOfKind(target, 524288 /* Object */) && !(ts.getObjectFlags(target) & 512 /* ObjectLiteralPatternWithComputedProperties */)) { + var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096 /* JsxAttributes */); + if ((relation === assignableRelation || relation === definitelyAssignableRelation || relation === comparableRelation) && + (isTypeSubsetOf(globalObjectType, target) || (!isComparingJsxAttributes && isEmptyObjectType(target)))) { + return false; + } + if (discriminant) { + // check excess properties against discriminant type only, not the entire union + return hasExcessProperties(source, discriminant, /*discriminant*/ undefined, reportErrors); + } + var _loop_6 = function (prop) { + if (shouldCheckAsExcessProperty(prop, source.symbol) && !isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { + if (reportErrors) { + // We know *exactly* where things went wrong when comparing the types. + // Use this property as the error node as this will be more helpful in + // reasoning about what went wrong. + if (!errorNode) + return { value: ts.Debug.fail() }; + if (ts.isJsxAttributes(errorNode) || ts.isJsxOpeningLikeElement(errorNode) || ts.isJsxOpeningLikeElement(errorNode.parent)) { + // JsxAttributes has an object-literal flag and undergo same type-assignablity check as normal object-literal. + // However, using an object-literal error message will be very confusing to the users so we give different a message. + // TODO: Spelling suggestions for excess jsx attributes (needs new diagnostic messages) + reportError(ts.Diagnostics.Property_0_does_not_exist_on_type_1, symbolToString(prop), typeToString(target)); + } + else { + // use the property's value declaration if the property is assigned inside the literal itself + var objectLiteralDeclaration_1 = source.symbol && ts.firstOrUndefined(source.symbol.declarations); + var suggestion = void 0; + if (prop.valueDeclaration && ts.findAncestor(prop.valueDeclaration, function (d) { return d === objectLiteralDeclaration_1; })) { + var propDeclaration = prop.valueDeclaration; + ts.Debug.assertNode(propDeclaration, ts.isObjectLiteralElementLike); + errorNode = propDeclaration; + var name = propDeclaration.name; + if (ts.isIdentifier(name)) { + suggestion = getSuggestionForNonexistentProperty(name, target); + } + } + if (suggestion !== undefined) { + reportError(ts.Diagnostics.Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_write_2, symbolToString(prop), typeToString(target), suggestion); + } + else { + reportError(ts.Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(prop), typeToString(target)); + } + } + } + return { value: true }; + } + }; + for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) { + var prop = _a[_i]; + var state_2 = _loop_6(prop); + if (typeof state_2 === "object") + return state_2.value; + } + } + return false; + } + function shouldCheckAsExcessProperty(prop, container) { + return prop.valueDeclaration && container.valueDeclaration && prop.valueDeclaration.parent === container.valueDeclaration; + } + function eachTypeRelatedToSomeType(source, target) { + var result = -1 /* True */; + var sourceTypes = source.types; + for (var _i = 0, sourceTypes_1 = sourceTypes; _i < sourceTypes_1.length; _i++) { + var sourceType = sourceTypes_1[_i]; + var related = typeRelatedToSomeType(sourceType, target, /*reportErrors*/ false); + if (!related) { + return 0 /* False */; + } + result &= related; + } + return result; + } + function typeRelatedToSomeType(source, target, reportErrors) { + var targetTypes = target.types; + if (target.flags & 1048576 /* Union */ && containsType(targetTypes, source)) { + return -1 /* True */; + } + for (var _i = 0, targetTypes_1 = targetTypes; _i < targetTypes_1.length; _i++) { + var type = targetTypes_1[_i]; + var related = isRelatedTo(source, type, /*reportErrors*/ false); + if (related) { + return related; + } + } + if (reportErrors) { + var bestMatchingType = findMatchingDiscriminantType(source, target) || + findMatchingTypeReferenceOrTypeAliasReference(source, target) || + findBestTypeForObjectLiteral(source, target) || + findBestTypeForInvokable(source, target) || + findMostOverlappyType(source, target); + isRelatedTo(source, bestMatchingType || targetTypes[targetTypes.length - 1], /*reportErrors*/ true); + } + return 0 /* False */; + } + function findMatchingTypeReferenceOrTypeAliasReference(source, unionTarget) { + var sourceObjectFlags = ts.getObjectFlags(source); + if (sourceObjectFlags & (4 /* Reference */ | 16 /* Anonymous */) && unionTarget.flags & 1048576 /* Union */) { + return ts.find(unionTarget.types, function (target) { + if (target.flags & 524288 /* Object */) { + var overlapObjFlags = sourceObjectFlags & ts.getObjectFlags(target); + if (overlapObjFlags & 4 /* Reference */) { + return source.target === target.target; + } + if (overlapObjFlags & 16 /* Anonymous */) { + return !!source.aliasSymbol && source.aliasSymbol === target.aliasSymbol; + } + } + return false; + }); + } + } + function findBestTypeForObjectLiteral(source, unionTarget) { + if (ts.getObjectFlags(source) & 128 /* ObjectLiteral */ && forEachType(unionTarget, isArrayLikeType)) { + return ts.find(unionTarget.types, function (t) { return !isArrayLikeType(t); }); + } + } + function findBestTypeForInvokable(source, unionTarget) { + var signatureKind = 0 /* Call */; + var hasSignatures = getSignaturesOfType(source, signatureKind).length > 0 || + (signatureKind = 1 /* Construct */, getSignaturesOfType(source, signatureKind).length > 0); + if (hasSignatures) { + return ts.find(unionTarget.types, function (t) { return getSignaturesOfType(t, signatureKind).length > 0; }); + } + } + function findMostOverlappyType(source, unionTarget) { + var bestMatch; + var matchingCount = 0; + for (var _i = 0, _a = unionTarget.types; _i < _a.length; _i++) { + var target_1 = _a[_i]; + var overlap = getIntersectionType([getIndexType(source), getIndexType(target_1)]); + if (overlap.flags & 4194304 /* Index */) { + // perfect overlap of keys + bestMatch = target_1; + matchingCount = Infinity; + } + else if (overlap.flags & 1048576 /* Union */) { + // Some subset overlap if we have only string literals. + // If we have a union of index types, it seems likely that we + // needed to elaborate between two generic mapped types anyway. + var len = ts.length(overlap.types); + if (len >= matchingCount) { + bestMatch = target_1; + matchingCount = len; + } + } + else if (!(overlap.flags & 131072 /* Never */) && 1 >= matchingCount) { + bestMatch = target_1; + matchingCount = 1; + } + } + return bestMatch; + } + // Keep this up-to-date with the same logic within `getApparentTypeOfContextualType`, since they should behave similarly + function findMatchingDiscriminantType(source, target) { + if (target.flags & 1048576 /* Union */) { + var sourceProperties = getPropertiesOfObjectType(source); + if (sourceProperties) { + var sourcePropertiesFiltered = findDiscriminantProperties(sourceProperties, target); + if (sourcePropertiesFiltered) { + return discriminateTypeByDiscriminableItems(target, ts.map(sourcePropertiesFiltered, function (p) { return [function () { return getTypeOfSymbol(p); }, p.escapedName]; }), isRelatedTo); + } + } + } + return undefined; + } + function typeRelatedToEachType(source, target, reportErrors) { + var result = -1 /* True */; + var targetTypes = target.types; + for (var _i = 0, targetTypes_2 = targetTypes; _i < targetTypes_2.length; _i++) { + var targetType = targetTypes_2[_i]; + var related = isRelatedTo(source, targetType, reportErrors, /*headMessage*/ undefined, /*isIntersectionConstituent*/ true); + if (!related) { + return 0 /* False */; + } + result &= related; + } + return result; + } + function someTypeRelatedToType(source, target, reportErrors) { + var sourceTypes = source.types; + if (source.flags & 1048576 /* Union */ && containsType(sourceTypes, target)) { + return -1 /* True */; + } + var len = sourceTypes.length; + for (var i = 0; i < len; i++) { + var related = isRelatedTo(sourceTypes[i], target, reportErrors && i === len - 1); + if (related) { + return related; + } + } + return 0 /* False */; + } + function eachTypeRelatedToType(source, target, reportErrors) { + var result = -1 /* True */; + var sourceTypes = source.types; + for (var _i = 0, sourceTypes_2 = sourceTypes; _i < sourceTypes_2.length; _i++) { + var sourceType = sourceTypes_2[_i]; + var related = isRelatedTo(sourceType, target, reportErrors); + if (!related) { + return 0 /* False */; + } + result &= related; + } + return result; + } + function typeArgumentsRelatedTo(sources, targets, variances, reportErrors) { + if (sources === void 0) { sources = ts.emptyArray; } + if (targets === void 0) { targets = ts.emptyArray; } + if (variances === void 0) { variances = ts.emptyArray; } + if (sources.length !== targets.length && relation === identityRelation) { + return 0 /* False */; + } + var length = sources.length <= targets.length ? sources.length : targets.length; + var result = -1 /* True */; + for (var i = 0; i < length; i++) { + // When variance information isn't available we default to covariance. This happens + // in the process of computing variance information for recursive types and when + // comparing 'this' type arguments. + var variance = i < variances.length ? variances[i] : 1 /* Covariant */; + // We ignore arguments for independent type parameters (because they're never witnessed). + if (variance !== 4 /* Independent */) { + var s = sources[i]; + var t = targets[i]; + var related = -1 /* True */; + if (variance === 1 /* Covariant */) { + related = isRelatedTo(s, t, reportErrors); + } + else if (variance === 2 /* Contravariant */) { + related = isRelatedTo(t, s, reportErrors); + } + else if (variance === 3 /* Bivariant */) { + // In the bivariant case we first compare contravariantly without reporting + // errors. Then, if that doesn't succeed, we compare covariantly with error + // reporting. Thus, error elaboration will be based on the the covariant check, + // which is generally easier to reason about. + related = isRelatedTo(t, s, /*reportErrors*/ false); + if (!related) { + related = isRelatedTo(s, t, reportErrors); + } + } + else { + // In the invariant case we first compare covariantly, and only when that + // succeeds do we proceed to compare contravariantly. Thus, error elaboration + // will typically be based on the covariant check. + related = isRelatedTo(s, t, reportErrors); + if (related) { + related &= isRelatedTo(t, s, reportErrors); + } + } + if (!related) { + return 0 /* False */; + } + result &= related; + } + } + return result; + } + // Determine if possibly recursive types are related. First, check if the result is already available in the global cache. + // Second, check if we have already started a comparison of the given two types in which case we assume the result to be true. + // Third, check if both types are part of deeply nested chains of generic type instantiations and if so assume the types are + // equal and infinitely expanding. Fourth, if we have reached a depth of 100 nested comparisons, assume we have runaway recursion + // and issue an error. Otherwise, actually compare the structure of the two types. + function recursiveTypeRelatedTo(source, target, reportErrors, isIntersectionConstituent) { + if (overflow) { + return 0 /* False */; + } + var id = getRelationKey(source, target, relation); + var related = relation.get(id); + if (related !== undefined) { + if (reportErrors && related === 2 /* Failed */) { + // We are elaborating errors and the cached result is an unreported failure. The result will be reported + // as a failure, and should be updated as a reported failure by the bottom of this function. + } + else { + return related === 1 /* Succeeded */ ? -1 /* True */ : 0 /* False */; + } + } + if (!maybeKeys) { + maybeKeys = []; + sourceStack = []; + targetStack = []; + } + else { + for (var i = 0; i < maybeCount; i++) { + // If source and target are already being compared, consider them related with assumptions + if (id === maybeKeys[i]) { + return 1 /* Maybe */; + } + } + if (depth === 100) { + overflow = true; + return 0 /* False */; + } + } + var maybeStart = maybeCount; + maybeKeys[maybeCount] = id; + maybeCount++; + sourceStack[depth] = source; + targetStack[depth] = target; + depth++; + var saveExpandingFlags = expandingFlags; + if (!(expandingFlags & 1 /* Source */) && isDeeplyNestedType(source, sourceStack, depth)) + expandingFlags |= 1 /* Source */; + if (!(expandingFlags & 2 /* Target */) && isDeeplyNestedType(target, targetStack, depth)) + expandingFlags |= 2 /* Target */; + var result = expandingFlags !== 3 /* Both */ ? structuredTypeRelatedTo(source, target, reportErrors, isIntersectionConstituent) : 1 /* Maybe */; + expandingFlags = saveExpandingFlags; + depth--; + if (result) { + if (result === -1 /* True */ || depth === 0) { + // If result is definitely true, record all maybe keys as having succeeded + for (var i = maybeStart; i < maybeCount; i++) { + relation.set(maybeKeys[i], 1 /* Succeeded */); + } + maybeCount = maybeStart; + } + } + else { + // A false result goes straight into global cache (when something is false under + // assumptions it will also be false without assumptions) + relation.set(id, reportErrors ? 3 /* FailedAndReported */ : 2 /* Failed */); + maybeCount = maybeStart; + } + return result; + } + function getConstraintForRelation(type) { + return relation === definitelyAssignableRelation ? undefined : getConstraintOfType(type); + } + function structuredTypeRelatedTo(source, target, reportErrors, isIntersectionConstituent) { + var flags = source.flags & target.flags; + if (relation === identityRelation && !(flags & 524288 /* Object */)) { + if (flags & 4194304 /* Index */) { + return isRelatedTo(source.type, target.type, /*reportErrors*/ false); + } + var result_2 = 0 /* False */; + if (flags & 8388608 /* IndexedAccess */) { + if (result_2 = isRelatedTo(source.objectType, target.objectType, /*reportErrors*/ false)) { + if (result_2 &= isRelatedTo(source.indexType, target.indexType, /*reportErrors*/ false)) { + return result_2; + } + } + } + if (flags & 16777216 /* Conditional */) { + if (source.root.isDistributive === target.root.isDistributive) { + if (result_2 = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) { + if (result_2 &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) { + if (result_2 &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), /*reportErrors*/ false)) { + if (result_2 &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), /*reportErrors*/ false)) { + return result_2; + } + } + } + } + } + } + if (flags & 33554432 /* Substitution */) { + return isRelatedTo(source.substitute, target.substitute, /*reportErrors*/ false); + } + return 0 /* False */; + } + var result; + var originalErrorInfo; + var saveErrorInfo = errorInfo; + // We limit alias variance probing to only object and conditional types since their alias behavior + // is more predictable than other, interned types, which may or may not have an alias depending on + // the order in which things were checked. + if (source.flags & (524288 /* Object */ | 16777216 /* Conditional */) && source.aliasSymbol && + source.aliasTypeArguments && source.aliasSymbol === target.aliasSymbol && + !(source.aliasTypeArgumentsContainsMarker || target.aliasTypeArgumentsContainsMarker)) { + var variances = getAliasVariances(source.aliasSymbol); + if (result = typeArgumentsRelatedTo(source.aliasTypeArguments, target.aliasTypeArguments, variances, reportErrors)) { + return result; + } + originalErrorInfo = errorInfo; + errorInfo = saveErrorInfo; + } + if (target.flags & 262144 /* TypeParameter */) { + // A source type { [P in Q]: X } is related to a target type T if keyof T is related to Q and X is related to T[Q]. + if (ts.getObjectFlags(source) & 32 /* Mapped */ && isRelatedTo(getIndexType(target), getConstraintTypeFromMappedType(source))) { + if (!(getMappedTypeModifiers(source) & 4 /* IncludeOptional */)) { + var templateType = getTemplateTypeFromMappedType(source); + var indexedAccessType = getIndexedAccessType(target, getTypeParameterFromMappedType(source)); + if (result = isRelatedTo(templateType, indexedAccessType, reportErrors)) { + return result; + } + } + } + } + else if (target.flags & 4194304 /* Index */) { + // A keyof S is related to a keyof T if T is related to S. + if (source.flags & 4194304 /* Index */) { + if (result = isRelatedTo(target.type, source.type, /*reportErrors*/ false)) { + return result; + } + } + // A type S is assignable to keyof T if S is assignable to keyof C, where C is the + // simplified form of T or, if T doesn't simplify, the constraint of T. + if (relation !== definitelyAssignableRelation) { + var simplified = getSimplifiedType(target.type); + var constraint = simplified !== target.type ? simplified : getConstraintOfType(target.type); + if (constraint) { + // We require Ternary.True here such that circular constraints don't cause + // false positives. For example, given 'T extends { [K in keyof T]: string }', + // 'keyof T' has itself as its constraint and produces a Ternary.Maybe when + // related to other types. + if (isRelatedTo(source, getIndexType(constraint, target.stringsOnly), reportErrors) === -1 /* True */) { + return -1 /* True */; + } + } + } + } + else if (target.flags & 8388608 /* IndexedAccess */) { + // A type S is related to a type T[K], where T and K aren't both type variables, if S is related to C, + // where C is the base constraint of T[K] + if (relation !== identityRelation && !(isGenericObjectType(target.objectType) && isGenericIndexType(target.indexType))) { + var constraint = getBaseConstraintOfType(target); + if (constraint && constraint !== target) { + if (result = isRelatedTo(source, constraint, reportErrors)) { + return result; + } + } + } + } + else if (isGenericMappedType(target)) { + // A source type T is related to a target type { [P in X]: T[P] } + var template = getTemplateTypeFromMappedType(target); + var modifiers = getMappedTypeModifiers(target); + if (!(modifiers & 8 /* ExcludeOptional */)) { + if (template.flags & 8388608 /* IndexedAccess */ && template.objectType === source && + template.indexType === getTypeParameterFromMappedType(target)) { + return -1 /* True */; + } + // A source type T is related to a target type { [P in Q]: X } if Q is related to keyof T and T[Q] is related to X. + if (!isGenericMappedType(source) && isRelatedTo(getConstraintTypeFromMappedType(target), getIndexType(source))) { + var indexedAccessType = getIndexedAccessType(source, getTypeParameterFromMappedType(target)); + var templateType = getTemplateTypeFromMappedType(target); + if (result = isRelatedTo(indexedAccessType, templateType, reportErrors)) { + return result; + } + } + originalErrorInfo = errorInfo; + errorInfo = saveErrorInfo; + } + } + if (source.flags & 8650752 /* TypeVariable */) { + if (source.flags & 8388608 /* IndexedAccess */ && target.flags & 8388608 /* IndexedAccess */) { + // A type S[K] is related to a type T[J] if S is related to T and K is related to J. + if (result = isRelatedTo(source.objectType, target.objectType, reportErrors)) { + result &= isRelatedTo(source.indexType, target.indexType, reportErrors); + } + if (result) { + errorInfo = saveErrorInfo; + return result; + } + } + var constraint = getConstraintForRelation(source); + if (!constraint || (source.flags & 262144 /* TypeParameter */ && constraint.flags & 3 /* AnyOrUnknown */)) { + // A type variable with no constraint is not related to the non-primitive object type. + if (result = isRelatedTo(emptyObjectType, extractTypesOfKind(target, ~67108864 /* NonPrimitive */))) { + errorInfo = saveErrorInfo; + return result; + } + } + // hi-speed no-this-instantiation check (less accurate, but avoids costly `this`-instantiation when the constraint will suffice), see #28231 for report on why this is needed + else if (result = isRelatedTo(constraint, target, /*reportErrors*/ false, /*headMessage*/ undefined, isIntersectionConstituent)) { + errorInfo = saveErrorInfo; + return result; + } + // slower, fuller, this-instantiated check (necessary when comparing raw `this` types from base classes), see `subclassWithPolymorphicThisIsAssignable.ts` test for example + else if (result = isRelatedTo(getTypeWithThisArgument(constraint, source), target, reportErrors, /*headMessage*/ undefined, isIntersectionConstituent)) { + errorInfo = saveErrorInfo; + return result; + } + } + else if (source.flags & 4194304 /* Index */) { + if (result = isRelatedTo(keyofConstraintType, target, reportErrors)) { + errorInfo = saveErrorInfo; + return result; + } + } + else if (source.flags & 16777216 /* Conditional */) { + if (target.flags & 16777216 /* Conditional */) { + // Two conditional types 'T1 extends U1 ? X1 : Y1' and 'T2 extends U2 ? X2 : Y2' are related if + // one of T1 and T2 is related to the other, U1 and U2 are identical types, X1 is related to X2, + // and Y1 is related to Y2. + if (isTypeIdenticalTo(source.extendsType, target.extendsType) && + (isRelatedTo(source.checkType, target.checkType) || isRelatedTo(target.checkType, source.checkType))) { + if (result = isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), reportErrors)) { + result &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), reportErrors); + } + if (result) { + errorInfo = saveErrorInfo; + return result; + } + } + } + else if (relation !== definitelyAssignableRelation) { + var distributiveConstraint = getConstraintOfDistributiveConditionalType(source); + if (distributiveConstraint) { + if (result = isRelatedTo(distributiveConstraint, target, reportErrors)) { + errorInfo = saveErrorInfo; + return result; + } + } + var defaultConstraint = getDefaultConstraintOfConditionalType(source); + if (defaultConstraint) { + if (result = isRelatedTo(defaultConstraint, target, reportErrors)) { + errorInfo = saveErrorInfo; + return result; + } + } + } + } + else { + // An empty object type is related to any mapped type that includes a '?' modifier. + if (isPartialMappedType(target) && !isGenericMappedType(source) && isEmptyObjectType(source)) { + return -1 /* True */; + } + if (isGenericMappedType(target)) { + if (isGenericMappedType(source)) { + if (result = mappedTypeRelatedTo(source, target, reportErrors)) { + errorInfo = saveErrorInfo; + return result; + } + } + return 0 /* False */; + } + if (relation === definitelyAssignableRelation && isGenericMappedType(source)) { + return 0 /* False */; + } + var sourceIsPrimitive = !!(source.flags & 131068 /* Primitive */); + if (relation !== identityRelation) { + source = getApparentType(source); + } + if (ts.getObjectFlags(source) & 4 /* Reference */ && ts.getObjectFlags(target) & 4 /* Reference */ && source.target === target.target && + !(ts.getObjectFlags(source) & 8192 /* MarkerType */ || ts.getObjectFlags(target) & 8192 /* MarkerType */)) { + // We have type references to the same generic type, and the type references are not marker + // type references (which are intended by be compared structurally). Obtain the variance + // information for the type parameters and relate the type arguments accordingly. + var variances = getVariances(source.target); + if (result = typeArgumentsRelatedTo(source.typeArguments, target.typeArguments, variances, reportErrors)) { + return result; + } + // The type arguments did not relate appropriately, but it may be because we have no variance + // information (in which case typeArgumentsRelatedTo defaulted to covariance for all type + // arguments). It might also be the case that the target type has a 'void' type argument for + // a covariant type parameter that is only used in return positions within the generic type + // (in which case any type argument is permitted on the source side). In those cases we proceed + // with a structural comparison. Otherwise, we know for certain the instantiations aren't + // related and we can return here. + if (variances !== ts.emptyArray && !hasCovariantVoidArgument(target, variances)) { + // In some cases generic types that are covariant in regular type checking mode become + // invariant in --strictFunctionTypes mode because one or more type parameters are used in + // both co- and contravariant positions. In order to make it easier to diagnose *why* such + // types are invariant, if any of the type parameters are invariant we reset the reported + // errors and instead force a structural comparison (which will include elaborations that + // reveal the reason). + if (!(reportErrors && ts.some(variances, function (v) { return v === 0 /* Invariant */; }))) { + return 0 /* False */; + } + // We remember the original error information so we can restore it in case the structural + // comparison unexpectedly succeeds. This can happen when the structural comparison result + // is a Ternary.Maybe for example caused by the recursion depth limiter. + originalErrorInfo = errorInfo; + errorInfo = saveErrorInfo; + } + } + else if (isTupleType(source) && (isArrayType(target) || isReadonlyArrayType(target)) || isArrayType(source) && isReadonlyArrayType(target)) { + return isRelatedTo(getIndexTypeOfType(source, 1 /* Number */) || anyType, getIndexTypeOfType(target, 1 /* Number */) || anyType, reportErrors); + } + // Even if relationship doesn't hold for unions, intersections, or generic type references, + // it may hold in a structural comparison. + // In a check of the form X = A & B, we will have previously checked if A relates to X or B relates + // to X. Failing both of those we want to check if the aggregation of A and B's members structurally + // relates to X. Thus, we include intersection types on the source side here. + if (source.flags & (524288 /* Object */ | 2097152 /* Intersection */) && target.flags & 524288 /* Object */) { + // Report structural errors only if we haven't reported any errors yet + var reportStructuralErrors = reportErrors && errorInfo === saveErrorInfo && !sourceIsPrimitive; + result = propertiesRelatedTo(source, target, reportStructuralErrors); + if (result) { + result &= signaturesRelatedTo(source, target, 0 /* Call */, reportStructuralErrors); + if (result) { + result &= signaturesRelatedTo(source, target, 1 /* Construct */, reportStructuralErrors); + if (result) { + result &= indexTypesRelatedTo(source, target, 0 /* String */, sourceIsPrimitive, reportStructuralErrors); + if (result) { + result &= indexTypesRelatedTo(source, target, 1 /* Number */, sourceIsPrimitive, reportStructuralErrors); + } + } + } + } + if (result) { + if (!originalErrorInfo) { + errorInfo = saveErrorInfo; + return result; + } + errorInfo = originalErrorInfo; + } + } + } + return 0 /* False */; + } + // A type [P in S]: X is related to a type [Q in T]: Y if T is related to S and X' is + // related to Y, where X' is an instantiation of X in which P is replaced with Q. Notice + // that S and T are contra-variant whereas X and Y are co-variant. + function mappedTypeRelatedTo(source, target, reportErrors) { + var modifiersRelated = relation === comparableRelation || (relation === identityRelation ? getMappedTypeModifiers(source) === getMappedTypeModifiers(target) : + getCombinedMappedTypeOptionality(source) <= getCombinedMappedTypeOptionality(target)); + if (modifiersRelated) { + var result_3; + if (result_3 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) { + var mapper = createTypeMapper([getTypeParameterFromMappedType(source)], [getTypeParameterFromMappedType(target)]); + return result_3 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); + } + } + return 0 /* False */; + } + function propertiesRelatedTo(source, target, reportErrors) { + if (relation === identityRelation) { + return propertiesIdenticalTo(source, target); + } + var requireOptionalProperties = relation === subtypeRelation && !isObjectLiteralType(source) && !isEmptyArrayLiteralType(source) && !isTupleType(source); + var unmatchedProperty = getUnmatchedProperty(source, target, requireOptionalProperties); + if (unmatchedProperty) { + if (reportErrors) { + var props = ts.arrayFrom(getUnmatchedProperties(source, target, requireOptionalProperties)); + if (!headMessage || (headMessage.code !== ts.Diagnostics.Class_0_incorrectly_implements_interface_1.code && + headMessage.code !== ts.Diagnostics.Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass.code)) { + suppressNextError = true; // Retain top-level error for interface implementing issues, otherwise omit it + } + if (props.length === 1) { + var propName = symbolToString(unmatchedProperty); + reportError(ts.Diagnostics.Property_0_is_missing_in_type_1_but_required_in_type_2, propName, typeToString(source), typeToString(target)); + if (ts.length(unmatchedProperty.declarations)) { + associateRelatedInfo(ts.createDiagnosticForNode(unmatchedProperty.declarations[0], ts.Diagnostics._0_is_declared_here, propName)); + } + } + else if (props.length > 5) { // arbitrary cutoff for too-long list form + reportError(ts.Diagnostics.Type_0_is_missing_the_following_properties_from_type_1_Colon_2_and_3_more, typeToString(source), typeToString(target), ts.map(props.slice(0, 4), function (p) { return symbolToString(p); }).join(", "), props.length - 4); + } + else { + reportError(ts.Diagnostics.Type_0_is_missing_the_following_properties_from_type_1_Colon_2, typeToString(source), typeToString(target), ts.map(props, function (p) { return symbolToString(p); }).join(", ")); + } + } + return 0 /* False */; + } + if (isObjectLiteralType(target)) { + for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) { + var sourceProp = _a[_i]; + if (!getPropertyOfObjectType(target, sourceProp.escapedName)) { + var sourceType = getTypeOfSymbol(sourceProp); + if (!(sourceType === undefinedType || sourceType === undefinedWideningType)) { + if (reportErrors) { + reportError(ts.Diagnostics.Property_0_does_not_exist_on_type_1, symbolToString(sourceProp), typeToString(target)); + } + return 0 /* False */; + } + } + } + } + var result = -1 /* True */; + if (isTupleType(target)) { + var targetRestType = getRestTypeOfTupleType(target); + if (targetRestType) { + if (!isTupleType(source)) { + return 0 /* False */; + } + var sourceRestType = getRestTypeOfTupleType(source); + if (sourceRestType && !isRelatedTo(sourceRestType, targetRestType, reportErrors)) { + if (reportErrors) { + reportError(ts.Diagnostics.Rest_signatures_are_incompatible); + } + return 0 /* False */; + } + var targetCount = getTypeReferenceArity(target) - 1; + var sourceCount = getTypeReferenceArity(source) - (sourceRestType ? 1 : 0); + for (var i = targetCount; i < sourceCount; i++) { + var related = isRelatedTo(source.typeArguments[i], targetRestType, reportErrors); + if (!related) { + if (reportErrors) { + reportError(ts.Diagnostics.Property_0_is_incompatible_with_rest_element_type, "" + i); + } + return 0 /* False */; + } + result &= related; + } + } + } + var properties = getPropertiesOfObjectType(target); + for (var _b = 0, properties_2 = properties; _b < properties_2.length; _b++) { + var targetProp = properties_2[_b]; + if (!(targetProp.flags & 4194304 /* Prototype */)) { + var sourceProp = getPropertyOfType(source, targetProp.escapedName); + if (sourceProp && sourceProp !== targetProp) { + if (isIgnoredJsxProperty(source, sourceProp, getTypeOfSymbol(targetProp))) { + continue; + } + var sourcePropFlags = ts.getDeclarationModifierFlagsFromSymbol(sourceProp); + var targetPropFlags = ts.getDeclarationModifierFlagsFromSymbol(targetProp); + if (sourcePropFlags & 8 /* Private */ || targetPropFlags & 8 /* Private */) { + var hasDifferingDeclarations = sourceProp.valueDeclaration !== targetProp.valueDeclaration; + if (ts.getCheckFlags(sourceProp) & 256 /* ContainsPrivate */ && hasDifferingDeclarations) { + if (reportErrors) { + reportError(ts.Diagnostics.Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1, symbolToString(sourceProp), typeToString(source)); + } + return 0 /* False */; + } + if (hasDifferingDeclarations) { + if (reportErrors) { + if (sourcePropFlags & 8 /* Private */ && targetPropFlags & 8 /* Private */) { + reportError(ts.Diagnostics.Types_have_separate_declarations_of_a_private_property_0, symbolToString(targetProp)); + } + else { + reportError(ts.Diagnostics.Property_0_is_private_in_type_1_but_not_in_type_2, symbolToString(targetProp), typeToString(sourcePropFlags & 8 /* Private */ ? source : target), typeToString(sourcePropFlags & 8 /* Private */ ? target : source)); + } + } + return 0 /* False */; + } + } + else if (targetPropFlags & 16 /* Protected */) { + if (!isValidOverrideOf(sourceProp, targetProp)) { + if (reportErrors) { + reportError(ts.Diagnostics.Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2, symbolToString(targetProp), typeToString(getDeclaringClass(sourceProp) || source), typeToString(getDeclaringClass(targetProp) || target)); + } + return 0 /* False */; + } + } + else if (sourcePropFlags & 16 /* Protected */) { + if (reportErrors) { + reportError(ts.Diagnostics.Property_0_is_protected_in_type_1_but_public_in_type_2, symbolToString(targetProp), typeToString(source), typeToString(target)); + } + return 0 /* False */; + } + var related = isRelatedTo(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp), reportErrors); + if (!related) { + if (reportErrors) { + reportError(ts.Diagnostics.Types_of_property_0_are_incompatible, symbolToString(targetProp)); + } + return 0 /* False */; + } + result &= related; + // When checking for comparability, be more lenient with optional properties. + if (relation !== comparableRelation && sourceProp.flags & 16777216 /* Optional */ && !(targetProp.flags & 16777216 /* Optional */)) { + // TypeScript 1.0 spec (April 2014): 3.8.3 + // S is a subtype of a type T, and T is a supertype of S if ... + // S' and T are object types and, for each member M in T.. + // M is a property and S' contains a property N where + // if M is a required property, N is also a required property + // (M - property in T) + // (N - property in S) + if (reportErrors) { + reportError(ts.Diagnostics.Property_0_is_optional_in_type_1_but_required_in_type_2, symbolToString(targetProp), typeToString(source), typeToString(target)); + } + return 0 /* False */; + } + } + } + } + return result; + } + function propertiesIdenticalTo(source, target) { + if (!(source.flags & 524288 /* Object */ && target.flags & 524288 /* Object */)) { + return 0 /* False */; + } + var sourceProperties = getPropertiesOfObjectType(source); + var targetProperties = getPropertiesOfObjectType(target); + if (sourceProperties.length !== targetProperties.length) { + return 0 /* False */; + } + var result = -1 /* True */; + for (var _i = 0, sourceProperties_1 = sourceProperties; _i < sourceProperties_1.length; _i++) { + var sourceProp = sourceProperties_1[_i]; + var targetProp = getPropertyOfObjectType(target, sourceProp.escapedName); + if (!targetProp) { + return 0 /* False */; + } + var related = compareProperties(sourceProp, targetProp, isRelatedTo); + if (!related) { + return 0 /* False */; + } + result &= related; + } + return result; + } + function signaturesRelatedTo(source, target, kind, reportErrors) { + if (relation === identityRelation) { + return signaturesIdenticalTo(source, target, kind); + } + if (target === anyFunctionType || source === anyFunctionType) { + return -1 /* True */; + } + var sourceIsJSConstructor = source.symbol && isJSConstructor(source.symbol.valueDeclaration); + var targetIsJSConstructor = target.symbol && isJSConstructor(target.symbol.valueDeclaration); + var sourceSignatures = getSignaturesOfType(source, (sourceIsJSConstructor && kind === 1 /* Construct */) ? + 0 /* Call */ : kind); + var targetSignatures = getSignaturesOfType(target, (targetIsJSConstructor && kind === 1 /* Construct */) ? + 0 /* Call */ : kind); + if (kind === 1 /* Construct */ && sourceSignatures.length && targetSignatures.length) { + if (ts.isAbstractConstructorType(source) && !ts.isAbstractConstructorType(target)) { + // An abstract constructor type is not assignable to a non-abstract constructor type + // as it would otherwise be possible to new an abstract class. Note that the assignability + // check we perform for an extends clause excludes construct signatures from the target, + // so this check never proceeds. + if (reportErrors) { + reportError(ts.Diagnostics.Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type); + } + return 0 /* False */; + } + if (!constructorVisibilitiesAreCompatible(sourceSignatures[0], targetSignatures[0], reportErrors)) { + return 0 /* False */; + } + } + var result = -1 /* True */; + var saveErrorInfo = errorInfo; + if (ts.getObjectFlags(source) & 64 /* Instantiated */ && ts.getObjectFlags(target) & 64 /* Instantiated */ && source.symbol === target.symbol) { + // We have instantiations of the same anonymous type (which typically will be the type of a + // method). Simply do a pairwise comparison of the signatures in the two signature lists instead + // of the much more expensive N * M comparison matrix we explore below. We erase type parameters + // as they are known to always be the same. + for (var i = 0; i < targetSignatures.length; i++) { + var related = signatureRelatedTo(sourceSignatures[i], targetSignatures[i], /*erase*/ true, reportErrors); + if (!related) { + return 0 /* False */; + } + result &= related; + } + } + else if (sourceSignatures.length === 1 && targetSignatures.length === 1) { + // For simple functions (functions with a single signature) we only erase type parameters for + // the comparable relation. Otherwise, if the source signature is generic, we instantiate it + // in the context of the target signature before checking the relationship. Ideally we'd do + // this regardless of the number of signatures, but the potential costs are prohibitive due + // to the quadratic nature of the logic below. + var eraseGenerics = relation === comparableRelation || !!compilerOptions.noStrictGenericChecks; + result = signatureRelatedTo(sourceSignatures[0], targetSignatures[0], eraseGenerics, reportErrors); + } + else { + outer: for (var _i = 0, targetSignatures_1 = targetSignatures; _i < targetSignatures_1.length; _i++) { + var t = targetSignatures_1[_i]; + // Only elaborate errors from the first failure + var shouldElaborateErrors = reportErrors; + for (var _a = 0, sourceSignatures_1 = sourceSignatures; _a < sourceSignatures_1.length; _a++) { + var s = sourceSignatures_1[_a]; + var related = signatureRelatedTo(s, t, /*erase*/ true, shouldElaborateErrors); + if (related) { + result &= related; + errorInfo = saveErrorInfo; + continue outer; + } + shouldElaborateErrors = false; + } + if (shouldElaborateErrors) { + reportError(ts.Diagnostics.Type_0_provides_no_match_for_the_signature_1, typeToString(source), signatureToString(t, /*enclosingDeclaration*/ undefined, /*flags*/ undefined, kind)); + } + return 0 /* False */; + } + } + return result; + } + /** + * See signatureAssignableTo, compareSignaturesIdentical + */ + function signatureRelatedTo(source, target, erase, reportErrors) { + return compareSignaturesRelated(erase ? getErasedSignature(source) : source, erase ? getErasedSignature(target) : target, 0 /* None */, /*ignoreReturnTypes*/ false, reportErrors, reportError, isRelatedTo); + } + function signaturesIdenticalTo(source, target, kind) { + var sourceSignatures = getSignaturesOfType(source, kind); + var targetSignatures = getSignaturesOfType(target, kind); + if (sourceSignatures.length !== targetSignatures.length) { + return 0 /* False */; + } + var result = -1 /* True */; + for (var i = 0; i < sourceSignatures.length; i++) { + var related = compareSignaturesIdentical(sourceSignatures[i], targetSignatures[i], /*partialMatch*/ false, /*ignoreThisTypes*/ false, /*ignoreReturnTypes*/ false, isRelatedTo); + if (!related) { + return 0 /* False */; + } + result &= related; + } + return result; + } + function eachPropertyRelatedTo(source, target, kind, reportErrors) { + var result = -1 /* True */; + for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) { + var prop = _a[_i]; + if (isIgnoredJsxProperty(source, prop, /*targetMemberType*/ undefined)) { + continue; + } + // Skip over symbol-named members + if (prop.nameType && prop.nameType.flags & 8192 /* UniqueESSymbol */) { + continue; + } + if (kind === 0 /* String */ || isNumericLiteralName(prop.escapedName)) { + var related = isRelatedTo(getTypeOfSymbol(prop), target, reportErrors); + if (!related) { + if (reportErrors) { + reportError(ts.Diagnostics.Property_0_is_incompatible_with_index_signature, symbolToString(prop)); + } + return 0 /* False */; + } + result &= related; + } + } + return result; + } + function indexInfoRelatedTo(sourceInfo, targetInfo, reportErrors) { + var related = isRelatedTo(sourceInfo.type, targetInfo.type, reportErrors); + if (!related && reportErrors) { + reportError(ts.Diagnostics.Index_signatures_are_incompatible); + } + return related; + } + function indexTypesRelatedTo(source, target, kind, sourceIsPrimitive, reportErrors) { + if (relation === identityRelation) { + return indexTypesIdenticalTo(source, target, kind); + } + var targetInfo = getIndexInfoOfType(target, kind); + if (!targetInfo || targetInfo.type.flags & 3 /* AnyOrUnknown */ && !sourceIsPrimitive) { + // Index signature of type any permits assignment from everything but primitives + return -1 /* True */; + } + var sourceInfo = getIndexInfoOfType(source, kind) || + kind === 1 /* Number */ && getIndexInfoOfType(source, 0 /* String */); + if (sourceInfo) { + return indexInfoRelatedTo(sourceInfo, targetInfo, reportErrors); + } + if (isGenericMappedType(source)) { + // A generic mapped type { [P in K]: T } is related to an index signature { [x: string]: U } + // if T is related to U. + return (kind === 0 /* String */ && isRelatedTo(getTemplateTypeFromMappedType(source), targetInfo.type, reportErrors)); // TODO: GH#18217 + } + if (isObjectTypeWithInferableIndex(source)) { + var related = -1 /* True */; + if (kind === 0 /* String */) { + var sourceNumberInfo = getIndexInfoOfType(source, 1 /* Number */); + if (sourceNumberInfo) { + related = indexInfoRelatedTo(sourceNumberInfo, targetInfo, reportErrors); + } + } + if (related) { + related &= eachPropertyRelatedTo(source, targetInfo.type, kind, reportErrors); + } + return related; + } + if (reportErrors) { + reportError(ts.Diagnostics.Index_signature_is_missing_in_type_0, typeToString(source)); + } + return 0 /* False */; + } + function indexTypesIdenticalTo(source, target, indexKind) { + var targetInfo = getIndexInfoOfType(target, indexKind); + var sourceInfo = getIndexInfoOfType(source, indexKind); + if (!sourceInfo && !targetInfo) { + return -1 /* True */; + } + if (sourceInfo && targetInfo && sourceInfo.isReadonly === targetInfo.isReadonly) { + return isRelatedTo(sourceInfo.type, targetInfo.type); + } + return 0 /* False */; + } + function constructorVisibilitiesAreCompatible(sourceSignature, targetSignature, reportErrors) { + if (!sourceSignature.declaration || !targetSignature.declaration) { + return true; + } + var sourceAccessibility = ts.getSelectedModifierFlags(sourceSignature.declaration, 24 /* NonPublicAccessibilityModifier */); + var targetAccessibility = ts.getSelectedModifierFlags(targetSignature.declaration, 24 /* NonPublicAccessibilityModifier */); + // A public, protected and private signature is assignable to a private signature. + if (targetAccessibility === 8 /* Private */) { + return true; + } + // A public and protected signature is assignable to a protected signature. + if (targetAccessibility === 16 /* Protected */ && sourceAccessibility !== 8 /* Private */) { + return true; + } + // Only a public signature is assignable to public signature. + if (targetAccessibility !== 16 /* Protected */ && !sourceAccessibility) { + return true; + } + if (reportErrors) { + reportError(ts.Diagnostics.Cannot_assign_a_0_constructor_type_to_a_1_constructor_type, visibilityToString(sourceAccessibility), visibilityToString(targetAccessibility)); + } + return false; + } + } + function discriminateTypeByDiscriminableItems(target, discriminators, related, defaultValue) { + var match; + for (var _i = 0, discriminators_1 = discriminators; _i < discriminators_1.length; _i++) { + var _a = discriminators_1[_i], getDiscriminatingType = _a[0], propertyName = _a[1]; + for (var _b = 0, _c = target.types; _b < _c.length; _b++) { + var type = _c[_b]; + var targetType = getTypeOfPropertyOfType(type, propertyName); + if (targetType && related(getDiscriminatingType(), targetType)) { + if (match) { + if (type === match) + continue; // Finding multiple fields which discriminate to the same type is fine + return defaultValue; + } + match = type; + } + } + } + return match || defaultValue; + } + /** + * A type is 'weak' if it is an object type with at least one optional property + * and no required properties, call/construct signatures or index signatures + */ + function isWeakType(type) { + if (type.flags & 524288 /* Object */) { + var resolved = resolveStructuredTypeMembers(type); + return resolved.callSignatures.length === 0 && resolved.constructSignatures.length === 0 && + !resolved.stringIndexInfo && !resolved.numberIndexInfo && + resolved.properties.length > 0 && + ts.every(resolved.properties, function (p) { return !!(p.flags & 16777216 /* Optional */); }); + } + if (type.flags & 2097152 /* Intersection */) { + return ts.every(type.types, isWeakType); + } + return false; + } + function hasCommonProperties(source, target, isComparingJsxAttributes) { + for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) { + var prop = _a[_i]; + if (isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { + return true; + } + } + return false; + } + // Return a type reference where the source type parameter is replaced with the target marker + // type, and flag the result as a marker type reference. + function getMarkerTypeReference(type, source, target) { + var result = createTypeReference(type, ts.map(type.typeParameters, function (t) { return t === source ? target : t; })); + result.objectFlags |= 8192 /* MarkerType */; + return result; + } + function getAliasVariances(symbol) { + var links = getSymbolLinks(symbol); + return getVariancesWorker(links.typeParameters, links, function (_links, param, marker) { + var type = getTypeAliasInstantiation(symbol, instantiateTypes(links.typeParameters, makeUnaryTypeMapper(param, marker))); + type.aliasTypeArgumentsContainsMarker = true; + return type; + }); + } + // Return an array containing the variance of each type parameter. The variance is effectively + // a digest of the type comparisons that occur for each type argument when instantiations of the + // generic type are structurally compared. We infer the variance information by comparing + // instantiations of the generic type for type arguments with known relations. The function + // returns the emptyArray singleton if we're not in strictFunctionTypes mode or if the function + // has been invoked recursively for the given generic type. + function getVariancesWorker(typeParameters, cache, createMarkerType) { + if (typeParameters === void 0) { typeParameters = ts.emptyArray; } + var variances = cache.variances; + if (!variances) { + // The emptyArray singleton is used to signal a recursive invocation. + cache.variances = ts.emptyArray; + variances = []; + for (var _i = 0, typeParameters_1 = typeParameters; _i < typeParameters_1.length; _i++) { + var tp = typeParameters_1[_i]; + // We first compare instantiations where the type parameter is replaced with + // marker types that have a known subtype relationship. From this we can infer + // invariance, covariance, contravariance or bivariance. + var typeWithSuper = createMarkerType(cache, tp, markerSuperType); + var typeWithSub = createMarkerType(cache, tp, markerSubType); + var variance = (isTypeAssignableTo(typeWithSub, typeWithSuper) ? 1 /* Covariant */ : 0) | + (isTypeAssignableTo(typeWithSuper, typeWithSub) ? 2 /* Contravariant */ : 0); + // If the instantiations appear to be related bivariantly it may be because the + // type parameter is independent (i.e. it isn't witnessed anywhere in the generic + // type). To determine this we compare instantiations where the type parameter is + // replaced with marker types that are known to be unrelated. + if (variance === 3 /* Bivariant */ && isTypeAssignableTo(createMarkerType(cache, tp, markerOtherType), typeWithSuper)) { + variance = 4 /* Independent */; + } + variances.push(variance); + } + cache.variances = variances; + } + return variances; + } + function getVariances(type) { + if (!strictFunctionTypes) { + return ts.emptyArray; + } + if (type === globalArrayType || type === globalReadonlyArrayType) { + // Arrays are known to be covariant, no need to spend time computing this (emptyArray implies covariance for all parameters) + return ts.emptyArray; + } + return getVariancesWorker(type.typeParameters, type, getMarkerTypeReference); + } + // Return true if the given type reference has a 'void' type argument for a covariant type parameter. + // See comment at call in recursiveTypeRelatedTo for when this case matters. + function hasCovariantVoidArgument(type, variances) { + for (var i = 0; i < variances.length; i++) { + if (variances[i] === 1 /* Covariant */ && type.typeArguments[i].flags & 16384 /* Void */) { + return true; + } + } + return false; + } + function isUnconstrainedTypeParameter(type) { + return type.flags & 262144 /* TypeParameter */ && !getConstraintOfTypeParameter(type); + } + function isTypeReferenceWithGenericArguments(type) { + return !!(ts.getObjectFlags(type) & 4 /* Reference */) && ts.some(type.typeArguments, function (t) { return isUnconstrainedTypeParameter(t) || isTypeReferenceWithGenericArguments(t); }); + } + /** + * getTypeReferenceId(A) returns "111=0-12=1" + * where A.id=111 and number.id=12 + */ + function getTypeReferenceId(type, typeParameters, depth) { + if (depth === void 0) { depth = 0; } + var result = "" + type.target.id; + for (var _i = 0, _a = type.typeArguments; _i < _a.length; _i++) { + var t = _a[_i]; + if (isUnconstrainedTypeParameter(t)) { + var index = typeParameters.indexOf(t); + if (index < 0) { + index = typeParameters.length; + typeParameters.push(t); + } + result += "=" + index; + } + else if (depth < 4 && isTypeReferenceWithGenericArguments(t)) { + result += "<" + getTypeReferenceId(t, typeParameters, depth + 1) + ">"; + } + else { + result += "-" + t.id; + } + } + return result; + } + /** + * To improve caching, the relation key for two generic types uses the target's id plus ids of the type parameters. + * For other cases, the types ids are used. + */ + function getRelationKey(source, target, relation) { + if (relation === identityRelation && source.id > target.id) { + var temp = source; + source = target; + target = temp; + } + if (isTypeReferenceWithGenericArguments(source) && isTypeReferenceWithGenericArguments(target)) { + var typeParameters = []; + return getTypeReferenceId(source, typeParameters) + "," + getTypeReferenceId(target, typeParameters); + } + return source.id + "," + target.id; + } + // Invoke the callback for each underlying property symbol of the given symbol and return the first + // value that isn't undefined. + function forEachProperty(prop, callback) { + if (ts.getCheckFlags(prop) & 6 /* Synthetic */) { + for (var _i = 0, _a = prop.containingType.types; _i < _a.length; _i++) { + var t = _a[_i]; + var p = getPropertyOfType(t, prop.escapedName); + var result = p && forEachProperty(p, callback); + if (result) { + return result; + } + } + return undefined; + } + return callback(prop); + } + // Return the declaring class type of a property or undefined if property not declared in class + function getDeclaringClass(prop) { + return prop.parent && prop.parent.flags & 32 /* Class */ ? getDeclaredTypeOfSymbol(getParentOfSymbol(prop)) : undefined; + } + // Return true if some underlying source property is declared in a class that derives + // from the given base class. + function isPropertyInClassDerivedFrom(prop, baseClass) { + return forEachProperty(prop, function (sp) { + var sourceClass = getDeclaringClass(sp); + return sourceClass ? hasBaseType(sourceClass, baseClass) : false; + }); + } + // Return true if source property is a valid override of protected parts of target property. + function isValidOverrideOf(sourceProp, targetProp) { + return !forEachProperty(targetProp, function (tp) { return ts.getDeclarationModifierFlagsFromSymbol(tp) & 16 /* Protected */ ? + !isPropertyInClassDerivedFrom(sourceProp, getDeclaringClass(tp)) : false; }); + } + // Return true if the given class derives from each of the declaring classes of the protected + // constituents of the given property. + function isClassDerivedFromDeclaringClasses(checkClass, prop) { + return forEachProperty(prop, function (p) { return ts.getDeclarationModifierFlagsFromSymbol(p) & 16 /* Protected */ ? + !hasBaseType(checkClass, getDeclaringClass(p)) : false; }) ? undefined : checkClass; + } + // Return true if the given type is deeply nested. We consider this to be the case when structural type comparisons + // for 5 or more occurrences or instantiations of the type have been recorded on the given stack. It is possible, + // though highly unlikely, for this test to be true in a situation where a chain of instantiations is not infinitely + // expanding. Effectively, we will generate a false positive when two types are structurally equal to at least 5 + // levels, but unequal at some level beyond that. + function isDeeplyNestedType(type, stack, depth) { + // We track all object types that have an associated symbol (representing the origin of the type) + if (depth >= 5 && type.flags & 524288 /* Object */) { + var symbol = type.symbol; + if (symbol) { + var count = 0; + for (var i = 0; i < depth; i++) { + var t = stack[i]; + if (t.flags & 524288 /* Object */ && t.symbol === symbol) { + count++; + if (count >= 5) + return true; + } + } + } + } + return false; + } + function isPropertyIdenticalTo(sourceProp, targetProp) { + return compareProperties(sourceProp, targetProp, compareTypesIdentical) !== 0 /* False */; + } + function compareProperties(sourceProp, targetProp, compareTypes) { + // Two members are considered identical when + // - they are public properties with identical names, optionality, and types, + // - they are private or protected properties originating in the same declaration and having identical types + if (sourceProp === targetProp) { + return -1 /* True */; + } + var sourcePropAccessibility = ts.getDeclarationModifierFlagsFromSymbol(sourceProp) & 24 /* NonPublicAccessibilityModifier */; + var targetPropAccessibility = ts.getDeclarationModifierFlagsFromSymbol(targetProp) & 24 /* NonPublicAccessibilityModifier */; + if (sourcePropAccessibility !== targetPropAccessibility) { + return 0 /* False */; + } + if (sourcePropAccessibility) { + if (getTargetSymbol(sourceProp) !== getTargetSymbol(targetProp)) { + return 0 /* False */; + } + } + else { + if ((sourceProp.flags & 16777216 /* Optional */) !== (targetProp.flags & 16777216 /* Optional */)) { + return 0 /* False */; + } + } + if (isReadonlySymbol(sourceProp) !== isReadonlySymbol(targetProp)) { + return 0 /* False */; + } + return compareTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); + } + function isMatchingSignature(source, target, partialMatch) { + var sourceParameterCount = getParameterCount(source); + var targetParameterCount = getParameterCount(target); + var sourceMinArgumentCount = getMinArgumentCount(source); + var targetMinArgumentCount = getMinArgumentCount(target); + var sourceHasRestParameter = hasEffectiveRestParameter(source); + var targetHasRestParameter = hasEffectiveRestParameter(target); + // A source signature matches a target signature if the two signatures have the same number of required, + // optional, and rest parameters. + if (sourceParameterCount === targetParameterCount && + sourceMinArgumentCount === targetMinArgumentCount && + sourceHasRestParameter === targetHasRestParameter) { + return true; + } + // A source signature partially matches a target signature if the target signature has no fewer required + // parameters + if (partialMatch && sourceMinArgumentCount <= targetMinArgumentCount) { + return true; + } + return false; + } + /** + * See signatureRelatedTo, compareSignaturesIdentical + */ + function compareSignaturesIdentical(source, target, partialMatch, ignoreThisTypes, ignoreReturnTypes, compareTypes) { + // TODO (drosen): De-duplicate code between related functions. + if (source === target) { + return -1 /* True */; + } + if (!(isMatchingSignature(source, target, partialMatch))) { + return 0 /* False */; + } + // Check that the two signatures have the same number of type parameters. We might consider + // also checking that any type parameter constraints match, but that would require instantiating + // the constraints with a common set of type arguments to get relatable entities in places where + // type parameters occur in the constraints. The complexity of doing that doesn't seem worthwhile, + // particularly as we're comparing erased versions of the signatures below. + if (ts.length(source.typeParameters) !== ts.length(target.typeParameters)) { + return 0 /* False */; + } + // Spec 1.0 Section 3.8.3 & 3.8.4: + // M and N (the signatures) are instantiated using type Any as the type argument for all type parameters declared by M and N + source = getErasedSignature(source); + target = getErasedSignature(target); + var result = -1 /* True */; + if (!ignoreThisTypes) { + var sourceThisType = getThisTypeOfSignature(source); + if (sourceThisType) { + var targetThisType = getThisTypeOfSignature(target); + if (targetThisType) { + var related = compareTypes(sourceThisType, targetThisType); + if (!related) { + return 0 /* False */; + } + result &= related; + } + } + } + var targetLen = getParameterCount(target); + for (var i = 0; i < targetLen; i++) { + var s = getTypeAtPosition(source, i); + var t = getTypeAtPosition(target, i); + var related = compareTypes(t, s); + if (!related) { + return 0 /* False */; + } + result &= related; + } + if (!ignoreReturnTypes) { + var sourceTypePredicate = getTypePredicateOfSignature(source); + var targetTypePredicate = getTypePredicateOfSignature(target); + result &= sourceTypePredicate !== undefined || targetTypePredicate !== undefined + ? compareTypePredicatesIdentical(sourceTypePredicate, targetTypePredicate, compareTypes) + // If they're both type predicates their return types will both be `boolean`, so no need to compare those. + : compareTypes(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target)); + } + return result; + } + function compareTypePredicatesIdentical(source, target, compareTypes) { + return source === undefined || target === undefined || !typePredicateKindsMatch(source, target) ? 0 /* False */ : compareTypes(source.type, target.type); + } + function literalTypesWithSameBaseType(types) { + var commonBaseType; + for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { + var t = types_8[_i]; + var baseType = getBaseTypeOfLiteralType(t); + if (!commonBaseType) { + commonBaseType = baseType; + } + if (baseType === t || baseType !== commonBaseType) { + return false; + } + } + return true; + } + // When the candidate types are all literal types with the same base type, return a union + // of those literal types. Otherwise, return the leftmost type for which no type to the + // right is a supertype. + function getSupertypeOrUnion(types) { + return literalTypesWithSameBaseType(types) ? + getUnionType(types) : + ts.reduceLeft(types, function (s, t) { return isTypeSubtypeOf(s, t) ? t : s; }); + } + function getCommonSupertype(types) { + if (!strictNullChecks) { + return getSupertypeOrUnion(types); + } + var primaryTypes = ts.filter(types, function (t) { return !(t.flags & 98304 /* Nullable */); }); + return primaryTypes.length ? + getNullableType(getSupertypeOrUnion(primaryTypes), getFalsyFlagsOfTypes(types) & 98304 /* Nullable */) : + getUnionType(types, 2 /* Subtype */); + } + // Return the leftmost type for which no type to the right is a subtype. + function getCommonSubtype(types) { + return ts.reduceLeft(types, function (s, t) { return isTypeSubtypeOf(t, s) ? t : s; }); + } + function isArrayType(type) { + return !!(ts.getObjectFlags(type) & 4 /* Reference */) && type.target === globalArrayType; + } + function isReadonlyArrayType(type) { + return !!(ts.getObjectFlags(type) & 4 /* Reference */) && type.target === globalReadonlyArrayType; + } + function getElementTypeOfArrayType(type) { + return isArrayType(type) && type.typeArguments ? type.typeArguments[0] : undefined; + } + function isArrayLikeType(type) { + // A type is array-like if it is a reference to the global Array or global ReadonlyArray type, + // or if it is not the undefined or null type and if it is assignable to ReadonlyArray + return ts.getObjectFlags(type) & 4 /* Reference */ && (type.target === globalArrayType || type.target === globalReadonlyArrayType) || + !(type.flags & 98304 /* Nullable */) && isTypeAssignableTo(type, anyReadonlyArrayType); + } + function isEmptyArrayLiteralType(type) { + var elementType = isArrayType(type) ? type.typeArguments[0] : undefined; + return elementType === undefinedWideningType || elementType === implicitNeverType; + } + function isTupleLikeType(type) { + return isTupleType(type) || !!getPropertyOfType(type, "0"); + } + function getTupleElementType(type, index) { + var propType = getTypeOfPropertyOfType(type, "" + index); + if (propType) { + return propType; + } + if (everyType(type, isTupleType) && !everyType(type, function (t) { return !t.target.hasRestElement; })) { + return mapType(type, function (t) { return getRestTypeOfTupleType(t) || undefinedType; }); + } + return undefined; + } + function isNeitherUnitTypeNorNever(type) { + return !(type.flags & (109440 /* Unit */ | 131072 /* Never */)); + } + function isUnitType(type) { + return !!(type.flags & 109440 /* Unit */); + } + function isLiteralType(type) { + return type.flags & 16 /* Boolean */ ? true : + type.flags & 1048576 /* Union */ ? type.flags & 1024 /* EnumLiteral */ ? true : ts.every(type.types, isUnitType) : + isUnitType(type); + } + function getBaseTypeOfLiteralType(type) { + return type.flags & 1024 /* EnumLiteral */ ? getBaseTypeOfEnumLiteralType(type) : + type.flags & 128 /* StringLiteral */ ? stringType : + type.flags & 256 /* NumberLiteral */ ? numberType : + type.flags & 2048 /* BigIntLiteral */ ? bigintType : + type.flags & 512 /* BooleanLiteral */ ? booleanType : + type.flags & 1048576 /* Union */ ? getUnionType(ts.sameMap(type.types, getBaseTypeOfLiteralType)) : + type; + } + function getWidenedLiteralType(type) { + return type.flags & 1024 /* EnumLiteral */ && isFreshLiteralType(type) ? getBaseTypeOfEnumLiteralType(type) : + type.flags & 128 /* StringLiteral */ && isFreshLiteralType(type) ? stringType : + type.flags & 256 /* NumberLiteral */ && isFreshLiteralType(type) ? numberType : + type.flags & 2048 /* BigIntLiteral */ && isFreshLiteralType(type) ? bigintType : + type.flags & 512 /* BooleanLiteral */ && isFreshLiteralType(type) ? booleanType : + type.flags & 1048576 /* Union */ ? getUnionType(ts.sameMap(type.types, getWidenedLiteralType)) : + type; + } + function getWidenedUniqueESSymbolType(type) { + return type.flags & 8192 /* UniqueESSymbol */ ? esSymbolType : + type.flags & 1048576 /* Union */ ? getUnionType(ts.sameMap(type.types, getWidenedUniqueESSymbolType)) : + type; + } + function getWidenedLiteralLikeTypeForContextualType(type, contextualType) { + if (!isLiteralOfContextualType(type, contextualType)) { + type = getWidenedUniqueESSymbolType(getWidenedLiteralType(type)); + } + return type; + } + /** + * Check if a Type was written as a tuple type literal. + * Prefer using isTupleLikeType() unless the use of `elementTypes` is required. + */ + function isTupleType(type) { + return !!(ts.getObjectFlags(type) & 4 /* Reference */ && type.target.objectFlags & 8 /* Tuple */); + } + function getRestTypeOfTupleType(type) { + return type.target.hasRestElement ? type.typeArguments[type.target.typeParameters.length - 1] : undefined; + } + function getRestArrayTypeOfTupleType(type) { + var restType = getRestTypeOfTupleType(type); + return restType && createArrayType(restType); + } + function getLengthOfTupleType(type) { + return getTypeReferenceArity(type) - (type.target.hasRestElement ? 1 : 0); + } + function isZeroBigInt(_a) { + var value = _a.value; + return value.base10Value === "0"; + } + function getFalsyFlagsOfTypes(types) { + var result = 0; + for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { + var t = types_9[_i]; + result |= getFalsyFlags(t); + } + return result; + } + // Returns the String, Number, Boolean, StringLiteral, NumberLiteral, BooleanLiteral, Void, Undefined, or Null + // flags for the string, number, boolean, "", 0, false, void, undefined, or null types respectively. Returns + // no flags for all other types (including non-falsy literal types). + function getFalsyFlags(type) { + return type.flags & 1048576 /* Union */ ? getFalsyFlagsOfTypes(type.types) : + type.flags & 128 /* StringLiteral */ ? type.value === "" ? 128 /* StringLiteral */ : 0 : + type.flags & 256 /* NumberLiteral */ ? type.value === 0 ? 256 /* NumberLiteral */ : 0 : + type.flags & 2048 /* BigIntLiteral */ ? isZeroBigInt(type) ? 2048 /* BigIntLiteral */ : 0 : + type.flags & 512 /* BooleanLiteral */ ? (type === falseType || type === regularFalseType) ? 512 /* BooleanLiteral */ : 0 : + type.flags & 117724 /* PossiblyFalsy */; + } + function removeDefinitelyFalsyTypes(type) { + return getFalsyFlags(type) & 117632 /* DefinitelyFalsy */ ? + filterType(type, function (t) { return !(getFalsyFlags(t) & 117632 /* DefinitelyFalsy */); }) : + type; + } + function extractDefinitelyFalsyTypes(type) { + return mapType(type, getDefinitelyFalsyPartOfType); + } + function getDefinitelyFalsyPartOfType(type) { + return type.flags & 4 /* String */ ? emptyStringType : + type.flags & 8 /* Number */ ? zeroType : + type.flags & 64 /* BigInt */ ? zeroBigIntType : + type === regularFalseType || + type === falseType || + type.flags & (16384 /* Void */ | 32768 /* Undefined */ | 65536 /* Null */) || + type.flags & 128 /* StringLiteral */ && type.value === "" || + type.flags & 256 /* NumberLiteral */ && type.value === 0 || + type.flags & 2048 /* BigIntLiteral */ && isZeroBigInt(type) ? type : + neverType; + } + /** + * Add undefined or null or both to a type if they are missing. + * @param type - type to add undefined and/or null to if not present + * @param flags - Either TypeFlags.Undefined or TypeFlags.Null, or both + */ + function getNullableType(type, flags) { + var missing = (flags & ~type.flags) & (32768 /* Undefined */ | 65536 /* Null */); + return missing === 0 ? type : + missing === 32768 /* Undefined */ ? getUnionType([type, undefinedType]) : + missing === 65536 /* Null */ ? getUnionType([type, nullType]) : + getUnionType([type, undefinedType, nullType]); + } + function getOptionalType(type) { + ts.Debug.assert(strictNullChecks); + return type.flags & 32768 /* Undefined */ ? type : getUnionType([type, undefinedType]); + } + function getGlobalNonNullableTypeInstantiation(type) { + if (!deferredGlobalNonNullableTypeAlias) { + deferredGlobalNonNullableTypeAlias = getGlobalSymbol("NonNullable", 524288 /* TypeAlias */, /*diagnostic*/ undefined) || unknownSymbol; + } + // Use NonNullable global type alias if available to improve quick info/declaration emit + if (deferredGlobalNonNullableTypeAlias !== unknownSymbol) { + return getTypeAliasInstantiation(deferredGlobalNonNullableTypeAlias, [type]); + } + return getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */); // Type alias unavailable, fall back to non-higher-order behavior + } + function getNonNullableType(type) { + return strictNullChecks ? getGlobalNonNullableTypeInstantiation(type) : type; + } + /** + * Return true if type was inferred from an object literal, written as an object type literal, or is the shape of a module + * with no call or construct signatures. + */ + function isObjectTypeWithInferableIndex(type) { + return type.symbol && (type.symbol.flags & (4096 /* ObjectLiteral */ | 2048 /* TypeLiteral */ | 512 /* ValueModule */)) !== 0 && + !typeHasCallOrConstructSignatures(type); + } + function createSymbolWithType(source, type) { + var symbol = createSymbol(source.flags, source.escapedName); + symbol.declarations = source.declarations; + symbol.parent = source.parent; + symbol.type = type; + symbol.target = source; + if (source.valueDeclaration) { + symbol.valueDeclaration = source.valueDeclaration; + } + if (source.nameType) { + symbol.nameType = source.nameType; + } + return symbol; + } + function transformTypeOfMembers(type, f) { + var members = ts.createSymbolTable(); + for (var _i = 0, _a = getPropertiesOfObjectType(type); _i < _a.length; _i++) { + var property = _a[_i]; + var original = getTypeOfSymbol(property); + var updated = f(original); + members.set(property.escapedName, updated === original ? property : createSymbolWithType(property, updated)); + } + return members; + } + /** + * If the the provided object literal is subject to the excess properties check, + * create a new that is exempt. Recursively mark object literal members as exempt. + * Leave signatures alone since they are not subject to the check. + */ + function getRegularTypeOfObjectLiteral(type) { + if (!(isObjectLiteralType(type) && ts.getObjectFlags(type) & 32768 /* FreshLiteral */)) { + return type; + } + var regularType = type.regularType; + if (regularType) { + return regularType; + } + var resolved = type; + var members = transformTypeOfMembers(type, getRegularTypeOfObjectLiteral); + var regularNew = createAnonymousType(resolved.symbol, members, resolved.callSignatures, resolved.constructSignatures, resolved.stringIndexInfo, resolved.numberIndexInfo); + regularNew.flags = resolved.flags; + regularNew.objectFlags |= 128 /* ObjectLiteral */ | (ts.getObjectFlags(resolved) & 16384 /* JSLiteral */); + type.regularType = regularNew; + return regularNew; + } + function createWideningContext(parent, propertyName, siblings) { + return { parent: parent, propertyName: propertyName, siblings: siblings, resolvedProperties: undefined }; + } + function getSiblingsOfContext(context) { + if (!context.siblings) { + var siblings_1 = []; + for (var _i = 0, _a = getSiblingsOfContext(context.parent); _i < _a.length; _i++) { + var type = _a[_i]; + if (isObjectLiteralType(type)) { + var prop = getPropertyOfObjectType(type, context.propertyName); + if (prop) { + forEachType(getTypeOfSymbol(prop), function (t) { + siblings_1.push(t); + }); + } + } + } + context.siblings = siblings_1; + } + return context.siblings; + } + function getPropertiesOfContext(context) { + if (!context.resolvedProperties) { + var names = ts.createMap(); + for (var _i = 0, _a = getSiblingsOfContext(context); _i < _a.length; _i++) { + var t = _a[_i]; + if (isObjectLiteralType(t) && !(ts.getObjectFlags(t) & 1024 /* ContainsSpread */)) { + for (var _b = 0, _c = getPropertiesOfType(t); _b < _c.length; _b++) { + var prop = _c[_b]; + names.set(prop.escapedName, prop); + } + } + } + context.resolvedProperties = ts.arrayFrom(names.values()); + } + return context.resolvedProperties; + } + function getWidenedProperty(prop, context) { + if (!(prop.flags & 4 /* Property */)) { + // Since get accessors already widen their return value there is no need to + // widen accessor based properties here. + return prop; + } + var original = getTypeOfSymbol(prop); + var propContext = context && createWideningContext(context, prop.escapedName, /*siblings*/ undefined); + var widened = getWidenedTypeWithContext(original, propContext); + return widened === original ? prop : createSymbolWithType(prop, widened); + } + function getUndefinedProperty(prop) { + var cached = undefinedProperties.get(prop.escapedName); + if (cached) { + return cached; + } + var result = createSymbolWithType(prop, undefinedType); + result.flags |= 16777216 /* Optional */; + undefinedProperties.set(prop.escapedName, result); + return result; + } + function getWidenedTypeOfObjectLiteral(type, context) { + var members = ts.createSymbolTable(); + for (var _i = 0, _a = getPropertiesOfObjectType(type); _i < _a.length; _i++) { + var prop = _a[_i]; + members.set(prop.escapedName, getWidenedProperty(prop, context)); + } + if (context) { + for (var _b = 0, _c = getPropertiesOfContext(context); _b < _c.length; _b++) { + var prop = _c[_b]; + if (!members.has(prop.escapedName)) { + members.set(prop.escapedName, getUndefinedProperty(prop)); + } + } + } + var stringIndexInfo = getIndexInfoOfType(type, 0 /* String */); + var numberIndexInfo = getIndexInfoOfType(type, 1 /* Number */); + var result = createAnonymousType(type.symbol, members, ts.emptyArray, ts.emptyArray, stringIndexInfo && createIndexInfo(getWidenedType(stringIndexInfo.type), stringIndexInfo.isReadonly), numberIndexInfo && createIndexInfo(getWidenedType(numberIndexInfo.type), numberIndexInfo.isReadonly)); + result.objectFlags |= (ts.getObjectFlags(type) & 16384 /* JSLiteral */); // Retain js literal flag through widening + return result; + } + function getWidenedType(type) { + return getWidenedTypeWithContext(type, /*context*/ undefined); + } + function getWidenedTypeWithContext(type, context) { + if (type.flags & 402653184 /* RequiresWidening */) { + if (type.flags & 98304 /* Nullable */) { + return anyType; + } + if (isObjectLiteralType(type)) { + return getWidenedTypeOfObjectLiteral(type, context); + } + if (type.flags & 1048576 /* Union */) { + var unionContext_1 = context || createWideningContext(/*parent*/ undefined, /*propertyName*/ undefined, type.types); + var widenedTypes = ts.sameMap(type.types, function (t) { return t.flags & 98304 /* Nullable */ ? t : getWidenedTypeWithContext(t, unionContext_1); }); + // Widening an empty object literal transitions from a highly restrictive type to + // a highly inclusive one. For that reason we perform subtype reduction here if the + // union includes empty object types (e.g. reducing {} | string to just {}). + return getUnionType(widenedTypes, ts.some(widenedTypes, isEmptyObjectType) ? 2 /* Subtype */ : 1 /* Literal */); + } + if (isArrayType(type) || isTupleType(type)) { + return createTypeReference(type.target, ts.sameMap(type.typeArguments, getWidenedType)); + } + } + return type; + } + /** + * Reports implicit any errors that occur as a result of widening 'null' and 'undefined' + * to 'any'. A call to reportWideningErrorsInType is normally accompanied by a call to + * getWidenedType. But in some cases getWidenedType is called without reporting errors + * (type argument inference is an example). + * + * The return value indicates whether an error was in fact reported. The particular circumstances + * are on a best effort basis. Currently, if the null or undefined that causes widening is inside + * an object literal property (arbitrarily deeply), this function reports an error. If no error is + * reported, reportImplicitAnyError is a suitable fallback to report a general error. + */ + function reportWideningErrorsInType(type) { + var errorReported = false; + if (type.flags & 134217728 /* ContainsWideningType */) { + if (type.flags & 1048576 /* Union */) { + if (ts.some(type.types, isEmptyObjectType)) { + errorReported = true; + } + else { + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (reportWideningErrorsInType(t)) { + errorReported = true; + } + } + } + } + if (isArrayType(type) || isTupleType(type)) { + for (var _b = 0, _c = type.typeArguments; _b < _c.length; _b++) { + var t = _c[_b]; + if (reportWideningErrorsInType(t)) { + errorReported = true; + } + } + } + if (isObjectLiteralType(type)) { + for (var _d = 0, _e = getPropertiesOfObjectType(type); _d < _e.length; _d++) { + var p = _e[_d]; + var t = getTypeOfSymbol(p); + if (t.flags & 134217728 /* ContainsWideningType */) { + if (!reportWideningErrorsInType(t)) { + error(p.valueDeclaration, ts.Diagnostics.Object_literal_s_property_0_implicitly_has_an_1_type, symbolToString(p), typeToString(getWidenedType(t))); + } + errorReported = true; + } + } + } + } + return errorReported; + } + function reportImplicitAny(declaration, type) { + var typeAsString = typeToString(getWidenedType(type)); + if (ts.isInJSFile(declaration) && !ts.isCheckJsEnabledForFile(ts.getSourceFileOfNode(declaration), compilerOptions)) { + // Only report implicit any errors/suggestions in TS and ts-check JS files + return; + } + var diagnostic; + switch (declaration.kind) { + case 204 /* BinaryExpression */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + diagnostic = noImplicitAny ? ts.Diagnostics.Member_0_implicitly_has_an_1_type : ts.Diagnostics.Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage; + break; + case 151 /* Parameter */: + var param = declaration; + if (ts.isIdentifier(param.name) && + (ts.isCallSignatureDeclaration(param.parent) || ts.isMethodSignature(param.parent) || ts.isFunctionTypeNode(param.parent)) && + param.parent.parameters.indexOf(param) > -1 && + (resolveName(param, param.name.escapedText, 67897832 /* Type */, undefined, param.name.escapedText, /*isUse*/ true) || + param.name.originalKeywordKind && ts.isTypeNodeKind(param.name.originalKeywordKind))) { + var newName = "arg" + param.parent.parameters.indexOf(param); + errorOrSuggestion(noImplicitAny, declaration, ts.Diagnostics.Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1, newName, ts.declarationNameToString(param.name)); + return; + } + diagnostic = declaration.dotDotDotToken ? + noImplicitAny ? ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type : ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage : + noImplicitAny ? ts.Diagnostics.Parameter_0_implicitly_has_an_1_type : ts.Diagnostics.Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage; + break; + case 186 /* BindingElement */: + diagnostic = ts.Diagnostics.Binding_element_0_implicitly_has_an_1_type; + break; + case 289 /* JSDocFunctionType */: + error(declaration, ts.Diagnostics.Function_type_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString); + return; + case 239 /* FunctionDeclaration */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + if (noImplicitAny && !declaration.name) { + error(declaration, ts.Diagnostics.Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString); + return; + } + diagnostic = noImplicitAny ? ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type : ts.Diagnostics._0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage; + break; + case 181 /* MappedType */: + if (noImplicitAny) { + error(declaration, ts.Diagnostics.Mapped_object_type_implicitly_has_an_any_template_type); + } + return; + default: + diagnostic = noImplicitAny ? ts.Diagnostics.Variable_0_implicitly_has_an_1_type : ts.Diagnostics.Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage; + } + errorOrSuggestion(noImplicitAny, declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString); + } + function reportErrorsFromWidening(declaration, type) { + if (produceDiagnostics && noImplicitAny && type.flags & 134217728 /* ContainsWideningType */) { + // Report implicit any error within type if possible, otherwise report error on declaration + if (!reportWideningErrorsInType(type)) { + reportImplicitAny(declaration, type); + } + } + } + function forEachMatchingParameterType(source, target, callback) { + var sourceCount = getParameterCount(source); + var targetCount = getParameterCount(target); + var sourceRestType = getEffectiveRestType(source); + var targetRestType = getEffectiveRestType(target); + var targetNonRestCount = targetRestType ? targetCount - 1 : targetCount; + var paramCount = sourceRestType ? targetNonRestCount : Math.min(sourceCount, targetNonRestCount); + var sourceThisType = getThisTypeOfSignature(source); + if (sourceThisType) { + var targetThisType = getThisTypeOfSignature(target); + if (targetThisType) { + callback(sourceThisType, targetThisType); + } + } + for (var i = 0; i < paramCount; i++) { + callback(getTypeAtPosition(source, i), getTypeAtPosition(target, i)); + } + if (targetRestType) { + callback(getRestTypeAtPosition(source, paramCount), targetRestType); + } + } + function createInferenceContext(typeParameters, signature, flags, compareTypes, baseInferences) { + var inferences = baseInferences ? baseInferences.map(cloneInferenceInfo) : typeParameters.map(createInferenceInfo); + var context = mapper; + context.typeParameters = typeParameters; + context.signature = signature; + context.inferences = inferences; + context.flags = flags; + context.compareTypes = compareTypes || compareTypesAssignable; + return context; + function mapper(t) { + for (var i = 0; i < inferences.length; i++) { + if (t === inferences[i].typeParameter) { + inferences[i].isFixed = true; + return getInferredType(context, i); + } + } + return t; + } + } + function createInferenceInfo(typeParameter) { + return { + typeParameter: typeParameter, + candidates: undefined, + contraCandidates: undefined, + inferredType: undefined, + priority: undefined, + topLevel: true, + isFixed: false + }; + } + function cloneInferenceInfo(inference) { + return { + typeParameter: inference.typeParameter, + candidates: inference.candidates && inference.candidates.slice(), + contraCandidates: inference.contraCandidates && inference.contraCandidates.slice(), + inferredType: inference.inferredType, + priority: inference.priority, + topLevel: inference.topLevel, + isFixed: inference.isFixed + }; + } + // Return true if the given type could possibly reference a type parameter for which + // we perform type inference (i.e. a type parameter of a generic function). We cache + // results for union and intersection types for performance reasons. + function couldContainTypeVariables(type) { + var objectFlags = ts.getObjectFlags(type); + return !!(type.flags & 63176704 /* Instantiable */ || + objectFlags & 4 /* Reference */ && ts.forEach(type.typeArguments, couldContainTypeVariables) || + objectFlags & 16 /* Anonymous */ && type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 2048 /* TypeLiteral */ | 32 /* Class */) || + objectFlags & 32 /* Mapped */ || + type.flags & 3145728 /* UnionOrIntersection */ && couldUnionOrIntersectionContainTypeVariables(type)); + } + function couldUnionOrIntersectionContainTypeVariables(type) { + if (type.couldContainTypeVariables === undefined) { + type.couldContainTypeVariables = ts.some(type.types, couldContainTypeVariables); + } + return type.couldContainTypeVariables; + } + function isTypeParameterAtTopLevel(type, typeParameter) { + return type === typeParameter || !!(type.flags & 3145728 /* UnionOrIntersection */) && ts.some(type.types, function (t) { return isTypeParameterAtTopLevel(t, typeParameter); }); + } + /** Create an object with properties named in the string literal type. Every property has type `any` */ + function createEmptyObjectTypeFromStringLiteral(type) { + var members = ts.createSymbolTable(); + forEachType(type, function (t) { + if (!(t.flags & 128 /* StringLiteral */)) { + return; + } + var name = ts.escapeLeadingUnderscores(t.value); + var literalProp = createSymbol(4 /* Property */, name); + literalProp.type = anyType; + if (t.symbol) { + literalProp.declarations = t.symbol.declarations; + literalProp.valueDeclaration = t.symbol.valueDeclaration; + } + members.set(name, literalProp); + }); + var indexInfo = type.flags & 4 /* String */ ? createIndexInfo(emptyObjectType, /*isReadonly*/ false) : undefined; + return createAnonymousType(undefined, members, ts.emptyArray, ts.emptyArray, indexInfo, undefined); + } + /** + * Infer a suitable input type for a homomorphic mapped type { [P in keyof T]: X }. We construct + * an object type with the same set of properties as the source type, where the type of each + * property is computed by inferring from the source property type to X for the type + * variable T[P] (i.e. we treat the type T[P] as the type variable we're inferring for). + */ + function inferTypeForHomomorphicMappedType(source, target, constraint) { + var key = source.id + "," + target.id + "," + constraint.id; + if (reverseMappedCache.has(key)) { + return reverseMappedCache.get(key); + } + reverseMappedCache.set(key, undefined); + var type = createReverseMappedType(source, target, constraint); + reverseMappedCache.set(key, type); + return type; + } + function createReverseMappedType(source, target, constraint) { + var properties = getPropertiesOfType(source); + if (properties.length === 0 && !getIndexInfoOfType(source, 0 /* String */)) { + return undefined; + } + // If any property contains context sensitive functions that have been skipped, the source type + // is incomplete and we can't infer a meaningful input type. + for (var _i = 0, properties_3 = properties; _i < properties_3.length; _i++) { + var prop = properties_3[_i]; + if (getTypeOfSymbol(prop).flags & 536870912 /* ContainsAnyFunctionType */) { + return undefined; + } + } + // For arrays and tuples we infer new arrays and tuples where the reverse mapping has been + // applied to the element type(s). + if (isArrayType(source)) { + return createArrayType(inferReverseMappedType(source.typeArguments[0], target, constraint)); + } + if (isReadonlyArrayType(source)) { + return createReadonlyArrayType(inferReverseMappedType(source.typeArguments[0], target, constraint)); + } + if (isTupleType(source)) { + var elementTypes = ts.map(source.typeArguments || ts.emptyArray, function (t) { return inferReverseMappedType(t, target, constraint); }); + var minLength = getMappedTypeModifiers(target) & 4 /* IncludeOptional */ ? + getTypeReferenceArity(source) - (source.target.hasRestElement ? 1 : 0) : source.target.minLength; + return createTupleType(elementTypes, minLength, source.target.hasRestElement, source.target.associatedNames); + } + // For all other object types we infer a new object type where the reverse mapping has been + // applied to the type of each property. + var reversed = createObjectType(2048 /* ReverseMapped */ | 16 /* Anonymous */, /*symbol*/ undefined); + reversed.source = source; + reversed.mappedType = target; + reversed.constraintType = constraint; + return reversed; + } + function getTypeOfReverseMappedSymbol(symbol) { + return inferReverseMappedType(symbol.propertyType, symbol.mappedType, symbol.constraintType); + } + function inferReverseMappedType(sourceType, target, constraint) { + var typeParameter = getIndexedAccessType(constraint.type, getTypeParameterFromMappedType(target)); + var templateType = getTemplateTypeFromMappedType(target); + var inference = createInferenceInfo(typeParameter); + inferTypes([inference], sourceType, templateType); + return getTypeFromInference(inference); + } + function getUnmatchedProperties(source, target, requireOptionalProperties) { + var properties, _i, properties_4, targetProp, sourceProp; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + properties = target.flags & 2097152 /* Intersection */ ? getPropertiesOfUnionOrIntersectionType(target) : getPropertiesOfObjectType(target); + _i = 0, properties_4 = properties; + _a.label = 1; + case 1: + if (!(_i < properties_4.length)) return [3 /*break*/, 4]; + targetProp = properties_4[_i]; + if (!(requireOptionalProperties || !(targetProp.flags & 16777216 /* Optional */))) return [3 /*break*/, 3]; + sourceProp = getPropertyOfType(source, targetProp.escapedName); + if (!!sourceProp) return [3 /*break*/, 3]; + return [4 /*yield*/, targetProp]; + case 2: + _a.sent(); + _a.label = 3; + case 3: + _i++; + return [3 /*break*/, 1]; + case 4: return [2 /*return*/]; + } + }); + } + function getUnmatchedProperty(source, target, requireOptionalProperties) { + return getUnmatchedProperties(source, target, requireOptionalProperties).next().value; + } + function tupleTypesDefinitelyUnrelated(source, target) { + return target.target.minLength > source.target.minLength || + !getRestTypeOfTupleType(target) && (!!getRestTypeOfTupleType(source) || getLengthOfTupleType(target) < getLengthOfTupleType(source)); + } + function typesDefinitelyUnrelated(source, target) { + // Two tuple types with incompatible arities are definitely unrelated. + // Two object types that each have a property that is unmatched in the other are definitely unrelated. + return isTupleType(source) && isTupleType(target) && tupleTypesDefinitelyUnrelated(source, target) || + !!getUnmatchedProperty(source, target, /*requireOptionalProperties*/ false) && !!getUnmatchedProperty(target, source, /*requireOptionalProperties*/ false); + } + function getTypeFromInference(inference) { + return inference.candidates ? getUnionType(inference.candidates, 2 /* Subtype */) : + inference.contraCandidates ? getIntersectionType(inference.contraCandidates) : + emptyObjectType; + } + function inferTypes(inferences, originalSource, originalTarget, priority) { + if (priority === void 0) { priority = 0; } + var symbolStack; + var visited; + var contravariant = false; + var bivariant = false; + var propagationType; + var allowComplexConstraintInference = true; + inferFromTypes(originalSource, originalTarget); + function inferFromTypes(source, target) { + if (!couldContainTypeVariables(target)) { + return; + } + if (source === wildcardType) { + // We are inferring from an 'any' type. We want to infer this type for every type parameter + // referenced in the target type, so we record it as the propagation type and infer from the + // target to itself. Then, as we find candidates we substitute the propagation type. + var savePropagationType = propagationType; + propagationType = source; + inferFromTypes(target, target); + propagationType = savePropagationType; + return; + } + if (source.aliasSymbol && source.aliasTypeArguments && source.aliasSymbol === target.aliasSymbol) { + // Source and target are types originating in the same generic type alias declaration. + // Simply infer from source type arguments to target type arguments. + var sourceTypes = source.aliasTypeArguments; + var targetTypes = target.aliasTypeArguments; + for (var i = 0; i < sourceTypes.length; i++) { + inferFromTypes(sourceTypes[i], targetTypes[i]); + } + return; + } + if (source.flags & 1048576 /* Union */ && target.flags & 1048576 /* Union */ && !(source.flags & 1024 /* EnumLiteral */ && target.flags & 1024 /* EnumLiteral */) || + source.flags & 2097152 /* Intersection */ && target.flags & 2097152 /* Intersection */) { + // Source and target are both unions or both intersections. If source and target + // are the same type, just relate each constituent type to itself. + if (source === target) { + for (var _i = 0, _a = source.types; _i < _a.length; _i++) { + var t = _a[_i]; + inferFromTypes(t, t); + } + return; + } + // Find each source constituent type that has an identically matching target constituent + // type, and for each such type infer from the type to itself. When inferring from a + // type to itself we effectively find all type parameter occurrences within that type + // and infer themselves as their type arguments. We have special handling for numeric + // and string literals because the number and string types are not represented as unions + // of all their possible values. + var matchingTypes = void 0; + for (var _b = 0, _c = source.types; _b < _c.length; _b++) { + var t = _c[_b]; + if (typeIdenticalToSomeType(t, target.types)) { + (matchingTypes || (matchingTypes = [])).push(t); + inferFromTypes(t, t); + } + else if (t.flags & (256 /* NumberLiteral */ | 128 /* StringLiteral */)) { + var b = getBaseTypeOfLiteralType(t); + if (typeIdenticalToSomeType(b, target.types)) { + (matchingTypes || (matchingTypes = [])).push(t, b); + } + } + } + // Next, to improve the quality of inferences, reduce the source and target types by + // removing the identically matched constituents. For example, when inferring from + // 'string | string[]' to 'string | T' we reduce the types to 'string[]' and 'T'. + if (matchingTypes) { + source = removeTypesFromUnionOrIntersection(source, matchingTypes); + target = removeTypesFromUnionOrIntersection(target, matchingTypes); + } + } + if (target.flags & 8650752 /* TypeVariable */) { + // If target is a type parameter, make an inference, unless the source type contains + // the anyFunctionType (the wildcard type that's used to avoid contextually typing functions). + // Because the anyFunctionType is internal, it should not be exposed to the user by adding + // it as an inference candidate. Hopefully, a better candidate will come along that does + // not contain anyFunctionType when we come back to this argument for its second round + // of inference. Also, we exclude inferences for silentNeverType (which is used as a wildcard + // when constructing types from type parameters that had no inference candidates). + if (source.flags & 536870912 /* ContainsAnyFunctionType */ || source === silentNeverType || (priority & 8 /* ReturnType */ && (source === autoType || source === autoArrayType))) { + return; + } + var inference = getInferenceInfoForType(target); + if (inference) { + if (!inference.isFixed) { + if (inference.priority === undefined || priority < inference.priority) { + inference.candidates = undefined; + inference.contraCandidates = undefined; + inference.priority = priority; + } + if (priority === inference.priority) { + var candidate = propagationType || source; + // We make contravariant inferences only if we are in a pure contravariant position, + // i.e. only if we have not descended into a bivariant position. + if (contravariant && !bivariant) { + inference.contraCandidates = ts.appendIfUnique(inference.contraCandidates, candidate); + } + else { + inference.candidates = ts.appendIfUnique(inference.candidates, candidate); + } + } + if (!(priority & 8 /* ReturnType */) && target.flags & 262144 /* TypeParameter */ && !isTypeParameterAtTopLevel(originalTarget, target)) { + inference.topLevel = false; + } + } + return; + } + else { + // Infer to the simplified version of an indexed access, if possible, to (hopefully) expose more bare type parameters to the inference engine + var simplified = getSimplifiedType(target); + if (simplified !== target) { + inferFromTypesOnce(source, simplified); + } + else if (target.flags & 8388608 /* IndexedAccess */) { + var indexType = getSimplifiedType(target.indexType); + // Generally simplifications of instantiable indexes are avoided to keep relationship checking correct, however if our target is an access, we can consider + // that key of that access to be "instantiated", since we're looking to find the infernce goal in any way we can. + if (indexType.flags & 63176704 /* Instantiable */) { + var simplified_1 = distributeIndexOverObjectType(getSimplifiedType(target.objectType), indexType); + if (simplified_1 && simplified_1 !== target) { + inferFromTypesOnce(source, simplified_1); + } + } + } + } + } + if (ts.getObjectFlags(source) & 4 /* Reference */ && ts.getObjectFlags(target) & 4 /* Reference */ && source.target === target.target) { + // If source and target are references to the same generic type, infer from type arguments + var sourceTypes = source.typeArguments || ts.emptyArray; + var targetTypes = target.typeArguments || ts.emptyArray; + var count = sourceTypes.length < targetTypes.length ? sourceTypes.length : targetTypes.length; + var variances = getVariances(source.target); + for (var i = 0; i < count; i++) { + if (i < variances.length && variances[i] === 2 /* Contravariant */) { + inferFromContravariantTypes(sourceTypes[i], targetTypes[i]); + } + else { + inferFromTypes(sourceTypes[i], targetTypes[i]); + } + } + } + else if (source.flags & 4194304 /* Index */ && target.flags & 4194304 /* Index */) { + contravariant = !contravariant; + inferFromTypes(source.type, target.type); + contravariant = !contravariant; + } + else if ((isLiteralType(source) || source.flags & 4 /* String */) && target.flags & 4194304 /* Index */) { + var empty = createEmptyObjectTypeFromStringLiteral(source); + contravariant = !contravariant; + var savePriority = priority; + priority |= 16 /* LiteralKeyof */; + inferFromTypes(empty, target.type); + priority = savePriority; + contravariant = !contravariant; + } + else if (source.flags & 8388608 /* IndexedAccess */ && target.flags & 8388608 /* IndexedAccess */) { + inferFromTypes(source.objectType, target.objectType); + inferFromTypes(source.indexType, target.indexType); + } + else if (source.flags & 16777216 /* Conditional */ && target.flags & 16777216 /* Conditional */) { + inferFromTypes(source.checkType, target.checkType); + inferFromTypes(source.extendsType, target.extendsType); + inferFromTypes(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target)); + inferFromTypes(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target)); + } + else if (target.flags & 16777216 /* Conditional */) { + inferFromTypes(source, getUnionType([getTrueTypeFromConditionalType(target), getFalseTypeFromConditionalType(target)])); + } + else if (target.flags & 3145728 /* UnionOrIntersection */) { + var targetTypes = target.types; + var typeVariableCount = 0; + var typeVariable = void 0; + // First infer to each type in union or intersection that isn't a type variable + for (var _d = 0, targetTypes_3 = targetTypes; _d < targetTypes_3.length; _d++) { + var t = targetTypes_3[_d]; + if (getInferenceInfoForType(t)) { + typeVariable = t; + typeVariableCount++; + } + else { + inferFromTypes(source, t); + } + } + // Next, if target containings a single naked type variable, make a secondary inference to that type + // variable. This gives meaningful results for union types in co-variant positions and intersection + // types in contra-variant positions (such as callback parameters). + if (typeVariableCount === 1) { + var savePriority = priority; + priority |= 1 /* NakedTypeVariable */; + inferFromTypes(source, typeVariable); + priority = savePriority; + } + } + else if (source.flags & 1048576 /* Union */) { + // Source is a union or intersection type, infer from each constituent type + var sourceTypes = source.types; + for (var _e = 0, sourceTypes_3 = sourceTypes; _e < sourceTypes_3.length; _e++) { + var sourceType = sourceTypes_3[_e]; + inferFromTypes(sourceType, target); + } + } + else { + if (!(priority & 32 /* NoConstraints */ && source.flags & (2097152 /* Intersection */ | 63176704 /* Instantiable */))) { + var apparentSource = getApparentType(source); + // getApparentType can return _any_ type, since an indexed access or conditional may simplify to any other type. + // If that occurs and it doesn't simplify to an object or intersection, we'll need to restart `inferFromTypes` + // with the simplified source. + if (apparentSource !== source && allowComplexConstraintInference && !(apparentSource.flags & (524288 /* Object */ | 2097152 /* Intersection */))) { + // TODO: The `allowComplexConstraintInference` flag is a hack! This forbids inference from complex constraints within constraints! + // This isn't required algorithmically, but rather is used to lower the memory burden caused by performing inference + // that is _too good_ in projects with complicated constraints (eg, fp-ts). In such cases, if we did not limit ourselves + // here, we might produce more valid inferences for types, causing us to do more checks and perform more instantiations + // (in addition to the extra stack depth here) which, in turn, can push the already close process over its limit. + // TL;DR: If we ever become generally more memory efficienct (or our resource budget ever increases), we should just + // remove this `allowComplexConstraintInference` flag. + allowComplexConstraintInference = false; + return inferFromTypes(apparentSource, target); + } + source = apparentSource; + } + if (source.flags & (524288 /* Object */ | 2097152 /* Intersection */)) { + var key = source.id + "," + target.id; + if (visited && visited.get(key)) { + return; + } + (visited || (visited = ts.createMap())).set(key, true); + // If we are already processing another target type with the same associated symbol (such as + // an instantiation of the same generic type), we do not explore this target as it would yield + // no further inferences. We exclude the static side of classes from this check since it shares + // its symbol with the instance side which would lead to false positives. + var isNonConstructorObject = target.flags & 524288 /* Object */ && + !(ts.getObjectFlags(target) & 16 /* Anonymous */ && target.symbol && target.symbol.flags & 32 /* Class */); + var symbol = isNonConstructorObject ? target.symbol : undefined; + if (symbol) { + if (ts.contains(symbolStack, symbol)) { + return; + } + (symbolStack || (symbolStack = [])).push(symbol); + inferFromObjectTypes(source, target); + symbolStack.pop(); + } + else { + inferFromObjectTypes(source, target); + } + } + } + function inferFromTypesOnce(source, target) { + var key = source.id + "," + target.id; + if (!visited || !visited.get(key)) { + (visited || (visited = ts.createMap())).set(key, true); + inferFromTypes(source, target); + } + } + } + function inferFromContravariantTypes(source, target) { + if (strictFunctionTypes || priority & 64 /* AlwaysStrict */) { + contravariant = !contravariant; + inferFromTypes(source, target); + contravariant = !contravariant; + } + else { + inferFromTypes(source, target); + } + } + function getInferenceInfoForType(type) { + if (type.flags & 8650752 /* TypeVariable */) { + for (var _i = 0, inferences_1 = inferences; _i < inferences_1.length; _i++) { + var inference = inferences_1[_i]; + if (type === inference.typeParameter) { + return inference; + } + } + } + return undefined; + } + function inferFromMappedTypeConstraint(source, target, constraintType) { + if (constraintType.flags & 1048576 /* Union */) { + var result = false; + for (var _i = 0, _a = constraintType.types; _i < _a.length; _i++) { + var type = _a[_i]; + result = inferFromMappedTypeConstraint(source, target, type) || result; + } + return result; + } + if (constraintType.flags & 4194304 /* Index */) { + // We're inferring from some source type S to a homomorphic mapped type { [P in keyof T]: X }, + // where T is a type variable. Use inferTypeForHomomorphicMappedType to infer a suitable source + // type and then make a secondary inference from that type to T. We make a secondary inference + // such that direct inferences to T get priority over inferences to Partial, for example. + var inference = getInferenceInfoForType(constraintType.type); + if (inference && !inference.isFixed) { + var inferredType = inferTypeForHomomorphicMappedType(source, target, constraintType); + if (inferredType) { + var savePriority = priority; + priority |= 2 /* HomomorphicMappedType */; + inferFromTypes(inferredType, inference.typeParameter); + priority = savePriority; + } + } + return true; + } + if (constraintType.flags & 262144 /* TypeParameter */) { + // We're inferring from some source type S to a mapped type { [P in T]: X }, where T is a type + // parameter. Infer from 'keyof S' to T and infer from a union of each property type in S to X. + var savePriority = priority; + priority |= 4 /* MappedTypeConstraint */; + inferFromTypes(getIndexType(source), constraintType); + priority = savePriority; + inferFromTypes(getUnionType(ts.map(getPropertiesOfType(source), getTypeOfSymbol)), getTemplateTypeFromMappedType(target)); + return true; + } + return false; + } + function inferFromObjectTypes(source, target) { + if (isGenericMappedType(source) && isGenericMappedType(target)) { + // The source and target types are generic types { [P in S]: X } and { [P in T]: Y }, so we infer + // from S to T and from X to Y. + inferFromTypes(getConstraintTypeFromMappedType(source), getConstraintTypeFromMappedType(target)); + inferFromTypes(getTemplateTypeFromMappedType(source), getTemplateTypeFromMappedType(target)); + } + if (ts.getObjectFlags(target) & 32 /* Mapped */) { + var constraintType = getConstraintTypeFromMappedType(target); + if (inferFromMappedTypeConstraint(source, target, constraintType)) { + return; + } + } + // Infer from the members of source and target only if the two types are possibly related + if (!typesDefinitelyUnrelated(source, target)) { + inferFromProperties(source, target); + inferFromSignatures(source, target, 0 /* Call */); + inferFromSignatures(source, target, 1 /* Construct */); + inferFromIndexTypes(source, target); + } + } + function inferFromProperties(source, target) { + if (isTupleType(source)) { + if (isTupleType(target)) { + var sourceLength = getLengthOfTupleType(source); + var targetLength = getLengthOfTupleType(target); + var sourceRestType = getRestTypeOfTupleType(source); + var targetRestType = getRestTypeOfTupleType(target); + var fixedLength = targetLength < sourceLength || sourceRestType ? targetLength : sourceLength; + for (var i = 0; i < fixedLength; i++) { + inferFromTypes(i < sourceLength ? source.typeArguments[i] : sourceRestType, target.typeArguments[i]); + } + if (targetRestType) { + var types = fixedLength < sourceLength ? source.typeArguments.slice(fixedLength, sourceLength) : []; + if (sourceRestType) { + types.push(sourceRestType); + } + if (types.length) { + inferFromTypes(getUnionType(types), targetRestType); + } + } + return; + } + if (isArrayType(target)) { + inferFromIndexTypes(source, target); + return; + } + } + var properties = getPropertiesOfObjectType(target); + for (var _i = 0, properties_5 = properties; _i < properties_5.length; _i++) { + var targetProp = properties_5[_i]; + var sourceProp = getPropertyOfType(source, targetProp.escapedName); + if (sourceProp) { + inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); + } + } + } + function inferFromSignatures(source, target, kind) { + var sourceSignatures = getSignaturesOfType(source, kind); + var targetSignatures = getSignaturesOfType(target, kind); + var sourceLen = sourceSignatures.length; + var targetLen = targetSignatures.length; + var len = sourceLen < targetLen ? sourceLen : targetLen; + var skipParameters = !!(source.flags & 536870912 /* ContainsAnyFunctionType */); + for (var i = 0; i < len; i++) { + inferFromSignature(getBaseSignature(sourceSignatures[sourceLen - len + i]), getBaseSignature(targetSignatures[targetLen - len + i]), skipParameters); + } + } + function inferFromSignature(source, target, skipParameters) { + if (!skipParameters) { + var saveBivariant = bivariant; + var kind = target.declaration ? target.declaration.kind : 0 /* Unknown */; + // Once we descend into a bivariant signature we remain bivariant for all nested inferences + bivariant = bivariant || kind === 156 /* MethodDeclaration */ || kind === 155 /* MethodSignature */ || kind === 157 /* Constructor */; + forEachMatchingParameterType(source, target, inferFromContravariantTypes); + bivariant = saveBivariant; + } + var sourceTypePredicate = getTypePredicateOfSignature(source); + var targetTypePredicate = getTypePredicateOfSignature(target); + if (sourceTypePredicate && targetTypePredicate && sourceTypePredicate.kind === targetTypePredicate.kind) { + inferFromTypes(sourceTypePredicate.type, targetTypePredicate.type); + } + else { + inferFromTypes(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target)); + } + } + function inferFromIndexTypes(source, target) { + var targetStringIndexType = getIndexTypeOfType(target, 0 /* String */); + if (targetStringIndexType) { + var sourceIndexType = getIndexTypeOfType(source, 0 /* String */) || + getImplicitIndexTypeOfType(source, 0 /* String */); + if (sourceIndexType) { + inferFromTypes(sourceIndexType, targetStringIndexType); + } + } + var targetNumberIndexType = getIndexTypeOfType(target, 1 /* Number */); + if (targetNumberIndexType) { + var sourceIndexType = getIndexTypeOfType(source, 1 /* Number */) || + getIndexTypeOfType(source, 0 /* String */) || + getImplicitIndexTypeOfType(source, 1 /* Number */); + if (sourceIndexType) { + inferFromTypes(sourceIndexType, targetNumberIndexType); + } + } + } + } + function typeIdenticalToSomeType(type, types) { + for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { + var t = types_10[_i]; + if (isTypeIdenticalTo(t, type)) { + return true; + } + } + return false; + } + /** + * Return a new union or intersection type computed by removing a given set of types + * from a given union or intersection type. + */ + function removeTypesFromUnionOrIntersection(type, typesToRemove) { + var reducedTypes = []; + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (!typeIdenticalToSomeType(t, typesToRemove)) { + reducedTypes.push(t); + } + } + return type.flags & 1048576 /* Union */ ? getUnionType(reducedTypes) : getIntersectionType(reducedTypes); + } + function hasPrimitiveConstraint(type) { + var constraint = getConstraintOfTypeParameter(type); + return !!constraint && maybeTypeOfKind(constraint.flags & 16777216 /* Conditional */ ? getDefaultConstraintOfConditionalType(constraint) : constraint, 131068 /* Primitive */ | 4194304 /* Index */); + } + function isObjectLiteralType(type) { + return !!(ts.getObjectFlags(type) & 128 /* ObjectLiteral */); + } + function widenObjectLiteralCandidates(candidates) { + if (candidates.length > 1) { + var objectLiterals = ts.filter(candidates, isObjectLiteralType); + if (objectLiterals.length) { + var objectLiteralsType = getWidenedType(getUnionType(objectLiterals, 2 /* Subtype */)); + return ts.concatenate(ts.filter(candidates, function (t) { return !isObjectLiteralType(t); }), [objectLiteralsType]); + } + } + return candidates; + } + function getContravariantInference(inference) { + return inference.priority & 28 /* PriorityImpliesCombination */ ? getIntersectionType(inference.contraCandidates) : getCommonSubtype(inference.contraCandidates); + } + function getCovariantInference(inference, signature) { + // Extract all object literal types and replace them with a single widened and normalized type. + var candidates = widenObjectLiteralCandidates(inference.candidates); + // We widen inferred literal types if + // all inferences were made to top-level occurrences of the type parameter, and + // the type parameter has no constraint or its constraint includes no primitive or literal types, and + // the type parameter was fixed during inference or does not occur at top-level in the return type. + var primitiveConstraint = hasPrimitiveConstraint(inference.typeParameter); + var widenLiteralTypes = !primitiveConstraint && inference.topLevel && + (inference.isFixed || !isTypeParameterAtTopLevel(getReturnTypeOfSignature(signature), inference.typeParameter)); + var baseCandidates = primitiveConstraint ? ts.sameMap(candidates, getRegularTypeOfLiteralType) : + widenLiteralTypes ? ts.sameMap(candidates, getWidenedLiteralType) : + candidates; + // If all inferences were made from a position that implies a combined result, infer a union type. + // Otherwise, infer a common supertype. + var unwidenedType = inference.priority & 28 /* PriorityImpliesCombination */ ? + getUnionType(baseCandidates, 2 /* Subtype */) : + getCommonSupertype(baseCandidates); + return getWidenedType(unwidenedType); + } + function getInferredType(context, index) { + var inference = context.inferences[index]; + var inferredType = inference.inferredType; + if (!inferredType) { + var signature = context.signature; + if (signature) { + var inferredCovariantType = inference.candidates ? getCovariantInference(inference, signature) : undefined; + if (inference.contraCandidates) { + var inferredContravariantType = getContravariantInference(inference); + // If we have both co- and contra-variant inferences, we prefer the contra-variant inference + // unless the co-variant inference is a subtype and not 'never'. + inferredType = inferredCovariantType && !(inferredCovariantType.flags & 131072 /* Never */) && + isTypeSubtypeOf(inferredCovariantType, inferredContravariantType) ? + inferredCovariantType : inferredContravariantType; + } + else if (inferredCovariantType) { + inferredType = inferredCovariantType; + } + else if (context.flags & 1 /* NoDefault */) { + // We use silentNeverType as the wildcard that signals no inferences. + inferredType = silentNeverType; + } + else { + // Infer either the default or the empty object type when no inferences were + // made. It is important to remember that in this case, inference still + // succeeds, meaning there is no error for not having inference candidates. An + // inference error only occurs when there are *conflicting* candidates, i.e. + // candidates with no common supertype. + var defaultType = getDefaultFromTypeParameter(inference.typeParameter); + if (defaultType) { + // Instantiate the default type. Any forward reference to a type + // parameter should be instantiated to the empty object type. + inferredType = instantiateType(defaultType, combineTypeMappers(createBackreferenceMapper(context.signature.typeParameters, index), context)); + } + else { + inferredType = getDefaultTypeArgumentType(!!(context.flags & 2 /* AnyDefault */)); + } + } + } + else { + inferredType = getTypeFromInference(inference); + } + inference.inferredType = inferredType; + var constraint = getConstraintOfTypeParameter(inference.typeParameter); + if (constraint) { + var instantiatedConstraint = instantiateType(constraint, context); + if (!context.compareTypes(inferredType, getTypeWithThisArgument(instantiatedConstraint, inferredType))) { + inference.inferredType = inferredType = instantiatedConstraint; + } + } + } + return inferredType; + } + function getDefaultTypeArgumentType(isInJavaScriptFile) { + return isInJavaScriptFile ? anyType : emptyObjectType; + } + function getInferredTypes(context) { + var result = []; + for (var i = 0; i < context.inferences.length; i++) { + result.push(getInferredType(context, i)); + } + return result; + } + // EXPRESSION TYPE CHECKING + function getCannotFindNameDiagnosticForName(name) { + switch (name) { + case "document": + case "console": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom; + case "$": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_and_then_add_jquery_to_the_types_field_in_your_tsconfig; + case "describe": + case "suite": + case "it": + case "test": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha_and_then_add_jest_or_mocha_to_the_types_field_in_your_tsconfig; + case "process": + case "require": + case "Buffer": + case "module": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_and_then_add_node_to_the_types_field_in_your_tsconfig; + case "Map": + case "Set": + case "Promise": + case "Symbol": + case "WeakMap": + case "WeakSet": + case "Iterator": + case "AsyncIterator": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later; + default: return ts.Diagnostics.Cannot_find_name_0; + } + } + function getResolvedSymbol(node) { + var links = getNodeLinks(node); + if (!links.resolvedSymbol) { + links.resolvedSymbol = !ts.nodeIsMissing(node) && + resolveName(node, node.escapedText, 67220415 /* Value */ | 1048576 /* ExportValue */, getCannotFindNameDiagnosticForName(node.escapedText), node, !ts.isWriteOnlyAccess(node), + /*excludeGlobals*/ false, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1) || unknownSymbol; + } + return links.resolvedSymbol; + } + function isInTypeQuery(node) { + // TypeScript 1.0 spec (April 2014): 3.6.3 + // A type query consists of the keyword typeof followed by an expression. + // The expression is restricted to a single identifier or a sequence of identifiers separated by periods + return !!ts.findAncestor(node, function (n) { return n.kind === 167 /* TypeQuery */ ? true : n.kind === 72 /* Identifier */ || n.kind === 148 /* QualifiedName */ ? false : "quit"; }); + } + // Return the flow cache key for a "dotted name" (i.e. a sequence of identifiers + // separated by dots). The key consists of the id of the symbol referenced by the + // leftmost identifier followed by zero or more property names separated by dots. + // The result is undefined if the reference isn't a dotted name. We prefix nodes + // occurring in an apparent type position with '@' because the control flow type + // of such nodes may be based on the apparent type instead of the declared type. + function getFlowCacheKey(node) { + if (node.kind === 72 /* Identifier */) { + var symbol = getResolvedSymbol(node); + return symbol !== unknownSymbol ? (isConstraintPosition(node) ? "@" : "") + getSymbolId(symbol) : undefined; + } + if (node.kind === 100 /* ThisKeyword */) { + return "0"; + } + if (node.kind === 189 /* PropertyAccessExpression */) { + var key = getFlowCacheKey(node.expression); + return key && key + "." + ts.idText(node.name); + } + if (node.kind === 186 /* BindingElement */) { + var container = node.parent.parent; + var key = container.kind === 186 /* BindingElement */ ? getFlowCacheKey(container) : (container.initializer && getFlowCacheKey(container.initializer)); + var text = getBindingElementNameText(node); + var result = key && text && (key + "." + text); + return result; + } + return undefined; + } + function getBindingElementNameText(element) { + var parent = element.parent; + if (parent.kind === 184 /* ObjectBindingPattern */) { + var name = element.propertyName || element.name; + switch (name.kind) { + case 72 /* Identifier */: + return ts.idText(name); + case 149 /* ComputedPropertyName */: + return ts.isStringOrNumericLiteralLike(name.expression) ? name.expression.text : undefined; + case 10 /* StringLiteral */: + case 8 /* NumericLiteral */: + return name.text; + default: + // Per types, array and object binding patterns remain, however they should never be present if propertyName is not defined + ts.Debug.fail("Unexpected name kind for binding element name"); + } + } + else { + return "" + parent.elements.indexOf(element); + } + } + function isMatchingReference(source, target) { + switch (source.kind) { + case 72 /* Identifier */: + return target.kind === 72 /* Identifier */ && getResolvedSymbol(source) === getResolvedSymbol(target) || + (target.kind === 237 /* VariableDeclaration */ || target.kind === 186 /* BindingElement */) && + getExportSymbolOfValueSymbolIfExported(getResolvedSymbol(source)) === getSymbolOfNode(target); + case 100 /* ThisKeyword */: + return target.kind === 100 /* ThisKeyword */; + case 98 /* SuperKeyword */: + return target.kind === 98 /* SuperKeyword */; + case 189 /* PropertyAccessExpression */: + case 190 /* ElementAccessExpression */: + return (ts.isPropertyAccessExpression(target) || ts.isElementAccessExpression(target)) && + getAccessedPropertyName(source) === getAccessedPropertyName(target) && + isMatchingReference(source.expression, target.expression); + case 186 /* BindingElement */: + if (target.kind !== 189 /* PropertyAccessExpression */) + return false; + var t = target; + if (t.name.escapedText !== getBindingElementNameText(source)) + return false; + if (source.parent.parent.kind === 186 /* BindingElement */ && isMatchingReference(source.parent.parent, t.expression)) { + return true; + } + if (source.parent.parent.kind === 237 /* VariableDeclaration */) { + var maybeId = source.parent.parent.initializer; + return !!maybeId && isMatchingReference(maybeId, t.expression); + } + } + return false; + } + function getAccessedPropertyName(access) { + return ts.isPropertyAccessExpression(access) ? access.name.escapedText : + ts.isStringLiteral(access.argumentExpression) || ts.isNumericLiteral(access.argumentExpression) ? ts.escapeLeadingUnderscores(access.argumentExpression.text) : + undefined; + } + function containsMatchingReference(source, target) { + while (source.kind === 189 /* PropertyAccessExpression */) { + source = source.expression; + if (isMatchingReference(source, target)) { + return true; + } + } + return false; + } + // Return true if target is a property access xxx.yyy, source is a property access xxx.zzz, the declared + // type of xxx is a union type, and yyy is a property that is possibly a discriminant. We consider a property + // a possible discriminant if its type differs in the constituents of containing union type, and if every + // choice is a unit type or a union of unit types. + function containsMatchingReferenceDiscriminant(source, target) { + return target.kind === 189 /* PropertyAccessExpression */ && + containsMatchingReference(source, target.expression) && + isDiscriminantProperty(getDeclaredTypeOfReference(target.expression), target.name.escapedText); + } + function getDeclaredTypeOfReference(expr) { + if (expr.kind === 72 /* Identifier */) { + return getTypeOfSymbol(getResolvedSymbol(expr)); + } + if (expr.kind === 189 /* PropertyAccessExpression */) { + var type = getDeclaredTypeOfReference(expr.expression); + return type && getTypeOfPropertyOfType(type, expr.name.escapedText); + } + return undefined; + } + function isDiscriminantType(type) { + if (type.flags & 1048576 /* Union */) { + if (type.flags & (16 /* Boolean */ | 1024 /* EnumLiteral */)) { + return true; + } + var combined = 0; + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var t = _a[_i]; + combined |= t.flags; + } + if (combined & 109440 /* Unit */ && !(combined & 63176704 /* Instantiable */)) { + return true; + } + } + return false; + } + function isDiscriminantProperty(type, name) { + if (type && type.flags & 1048576 /* Union */) { + var prop = getUnionOrIntersectionProperty(type, name); + if (prop && ts.getCheckFlags(prop) & 2 /* SyntheticProperty */) { + if (prop.isDiscriminantProperty === undefined) { + prop.isDiscriminantProperty = !!(prop.checkFlags & 32 /* HasNonUniformType */) && isDiscriminantType(getTypeOfSymbol(prop)); + } + return !!prop.isDiscriminantProperty; + } + } + return false; + } + function hasNarrowableDeclaredType(expr) { + var type = getDeclaredTypeOfReference(expr); + return !!(type && type.flags & 1048576 /* Union */); + } + function findDiscriminantProperties(sourceProperties, target) { + var result; + for (var _i = 0, sourceProperties_2 = sourceProperties; _i < sourceProperties_2.length; _i++) { + var sourceProperty = sourceProperties_2[_i]; + if (isDiscriminantProperty(target, sourceProperty.escapedName)) { + if (result) { + result.push(sourceProperty); + continue; + } + result = [sourceProperty]; + } + } + return result; + } + function isOrContainsMatchingReference(source, target) { + return isMatchingReference(source, target) || containsMatchingReference(source, target); + } + function hasMatchingArgument(callExpression, reference) { + if (callExpression.arguments) { + for (var _i = 0, _a = callExpression.arguments; _i < _a.length; _i++) { + var argument = _a[_i]; + if (isOrContainsMatchingReference(reference, argument)) { + return true; + } + } + } + if (callExpression.expression.kind === 189 /* PropertyAccessExpression */ && + isOrContainsMatchingReference(reference, callExpression.expression.expression)) { + return true; + } + return false; + } + function getFlowNodeId(flow) { + if (!flow.id) { + flow.id = nextFlowId; + nextFlowId++; + } + return flow.id; + } + function typeMaybeAssignableTo(source, target) { + if (!(source.flags & 1048576 /* Union */)) { + return isTypeAssignableTo(source, target); + } + for (var _i = 0, _a = source.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (isTypeAssignableTo(t, target)) { + return true; + } + } + return false; + } + // Remove those constituent types of declaredType to which no constituent type of assignedType is assignable. + // For example, when a variable of type number | string | boolean is assigned a value of type number | boolean, + // we remove type string. + function getAssignmentReducedType(declaredType, assignedType) { + if (declaredType !== assignedType) { + if (assignedType.flags & 131072 /* Never */) { + return assignedType; + } + var reducedType = filterType(declaredType, function (t) { return typeMaybeAssignableTo(assignedType, t); }); + if (assignedType.flags & 512 /* BooleanLiteral */ && isFreshLiteralType(assignedType)) { + reducedType = mapType(reducedType, getFreshTypeOfLiteralType); // Ensure that if the assignment is a fresh type, that we narrow to fresh types + } + // Our crude heuristic produces an invalid result in some cases: see GH#26130. + // For now, when that happens, we give up and don't narrow at all. (This also + // means we'll never narrow for erroneous assignments where the assigned type + // is not assignable to the declared type.) + if (isTypeAssignableTo(assignedType, reducedType)) { + return reducedType; + } + } + return declaredType; + } + function getTypeFactsOfTypes(types) { + var result = 0 /* None */; + for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { + var t = types_11[_i]; + result |= getTypeFacts(t); + } + return result; + } + function isFunctionObjectType(type) { + // We do a quick check for a "bind" property before performing the more expensive subtype + // check. This gives us a quicker out in the common case where an object type is not a function. + var resolved = resolveStructuredTypeMembers(type); + return !!(resolved.callSignatures.length || resolved.constructSignatures.length || + resolved.members.get("bind") && isTypeSubtypeOf(type, globalFunctionType)); + } + function getTypeFacts(type) { + var flags = type.flags; + if (flags & 4 /* String */) { + return strictNullChecks ? 16317953 /* StringStrictFacts */ : 16776705 /* StringFacts */; + } + if (flags & 128 /* StringLiteral */) { + var isEmpty = type.value === ""; + return strictNullChecks ? + isEmpty ? 12123649 /* EmptyStringStrictFacts */ : 7929345 /* NonEmptyStringStrictFacts */ : + isEmpty ? 12582401 /* EmptyStringFacts */ : 16776705 /* NonEmptyStringFacts */; + } + if (flags & (8 /* Number */ | 32 /* Enum */)) { + return strictNullChecks ? 16317698 /* NumberStrictFacts */ : 16776450 /* NumberFacts */; + } + if (flags & 256 /* NumberLiteral */) { + var isZero = type.value === 0; + return strictNullChecks ? + isZero ? 12123394 /* ZeroNumberStrictFacts */ : 7929090 /* NonZeroNumberStrictFacts */ : + isZero ? 12582146 /* ZeroNumberFacts */ : 16776450 /* NonZeroNumberFacts */; + } + if (flags & 64 /* BigInt */) { + return strictNullChecks ? 16317188 /* BigIntStrictFacts */ : 16775940 /* BigIntFacts */; + } + if (flags & 2048 /* BigIntLiteral */) { + var isZero = isZeroBigInt(type); + return strictNullChecks ? + isZero ? 12122884 /* ZeroBigIntStrictFacts */ : 7928580 /* NonZeroBigIntStrictFacts */ : + isZero ? 12581636 /* ZeroBigIntFacts */ : 16775940 /* NonZeroBigIntFacts */; + } + if (flags & 16 /* Boolean */) { + return strictNullChecks ? 16316168 /* BooleanStrictFacts */ : 16774920 /* BooleanFacts */; + } + if (flags & 528 /* BooleanLike */) { + return strictNullChecks ? + (type === falseType || type === regularFalseType) ? 12121864 /* FalseStrictFacts */ : 7927560 /* TrueStrictFacts */ : + (type === falseType || type === regularFalseType) ? 12580616 /* FalseFacts */ : 16774920 /* TrueFacts */; + } + if (flags & 524288 /* Object */) { + return ts.getObjectFlags(type) & 16 /* Anonymous */ && isEmptyObjectType(type) ? + strictNullChecks ? 16318463 /* EmptyObjectStrictFacts */ : 16777215 /* EmptyObjectFacts */ : + isFunctionObjectType(type) ? + strictNullChecks ? 7880640 /* FunctionStrictFacts */ : 16728000 /* FunctionFacts */ : + strictNullChecks ? 7888800 /* ObjectStrictFacts */ : 16736160 /* ObjectFacts */; + } + if (flags & (16384 /* Void */ | 32768 /* Undefined */)) { + return 9830144 /* UndefinedFacts */; + } + if (flags & 65536 /* Null */) { + return 9363232 /* NullFacts */; + } + if (flags & 12288 /* ESSymbolLike */) { + return strictNullChecks ? 7925520 /* SymbolStrictFacts */ : 16772880 /* SymbolFacts */; + } + if (flags & 67108864 /* NonPrimitive */) { + return strictNullChecks ? 7888800 /* ObjectStrictFacts */ : 16736160 /* ObjectFacts */; + } + if (flags & 63176704 /* Instantiable */) { + return getTypeFacts(getBaseConstraintOfType(type) || emptyObjectType); + } + if (flags & 3145728 /* UnionOrIntersection */) { + return getTypeFactsOfTypes(type.types); + } + return 16777215 /* All */; + } + function getTypeWithFacts(type, include) { + return filterType(type, function (t) { return (getTypeFacts(t) & include) !== 0; }); + } + function getTypeWithDefault(type, defaultExpression) { + if (defaultExpression) { + var defaultType = getTypeOfExpression(defaultExpression); + return getUnionType([getTypeWithFacts(type, 524288 /* NEUndefined */), defaultType]); + } + return type; + } + function getTypeOfDestructuredProperty(type, name) { + var text = ts.getTextOfPropertyName(name); + return getConstraintForLocation(getTypeOfPropertyOfType(type, text), name) || + isNumericLiteralName(text) && getIndexTypeOfType(type, 1 /* Number */) || + getIndexTypeOfType(type, 0 /* String */) || + errorType; + } + function getTypeOfDestructuredArrayElement(type, index) { + return everyType(type, isTupleLikeType) && getTupleElementType(type, index) || + checkIteratedTypeOrElementType(type, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterables*/ false) || + errorType; + } + function getTypeOfDestructuredSpreadExpression(type) { + return createArrayType(checkIteratedTypeOrElementType(type, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterables*/ false) || errorType); + } + function getAssignedTypeOfBinaryExpression(node) { + var isDestructuringDefaultAssignment = node.parent.kind === 187 /* ArrayLiteralExpression */ && isDestructuringAssignmentTarget(node.parent) || + node.parent.kind === 275 /* PropertyAssignment */ && isDestructuringAssignmentTarget(node.parent.parent); + return isDestructuringDefaultAssignment ? + getTypeWithDefault(getAssignedType(node), node.right) : + getTypeOfExpression(node.right); + } + function isDestructuringAssignmentTarget(parent) { + return parent.parent.kind === 204 /* BinaryExpression */ && parent.parent.left === parent || + parent.parent.kind === 227 /* ForOfStatement */ && parent.parent.initializer === parent; + } + function getAssignedTypeOfArrayLiteralElement(node, element) { + return getTypeOfDestructuredArrayElement(getAssignedType(node), node.elements.indexOf(element)); + } + function getAssignedTypeOfSpreadExpression(node) { + return getTypeOfDestructuredSpreadExpression(getAssignedType(node.parent)); + } + function getAssignedTypeOfPropertyAssignment(node) { + return getTypeOfDestructuredProperty(getAssignedType(node.parent), node.name); + } + function getAssignedTypeOfShorthandPropertyAssignment(node) { + return getTypeWithDefault(getAssignedTypeOfPropertyAssignment(node), node.objectAssignmentInitializer); + } + function getAssignedType(node) { + var parent = node.parent; + switch (parent.kind) { + case 226 /* ForInStatement */: + return stringType; + case 227 /* ForOfStatement */: + return checkRightHandSideOfForOf(parent.expression, parent.awaitModifier) || errorType; + case 204 /* BinaryExpression */: + return getAssignedTypeOfBinaryExpression(parent); + case 198 /* DeleteExpression */: + return undefinedType; + case 187 /* ArrayLiteralExpression */: + return getAssignedTypeOfArrayLiteralElement(parent, node); + case 208 /* SpreadElement */: + return getAssignedTypeOfSpreadExpression(parent); + case 275 /* PropertyAssignment */: + return getAssignedTypeOfPropertyAssignment(parent); + case 276 /* ShorthandPropertyAssignment */: + return getAssignedTypeOfShorthandPropertyAssignment(parent); + } + return errorType; + } + function getInitialTypeOfBindingElement(node) { + var pattern = node.parent; + var parentType = getInitialType(pattern.parent); + var type = pattern.kind === 184 /* ObjectBindingPattern */ ? + getTypeOfDestructuredProperty(parentType, node.propertyName || node.name) : + !node.dotDotDotToken ? + getTypeOfDestructuredArrayElement(parentType, pattern.elements.indexOf(node)) : + getTypeOfDestructuredSpreadExpression(parentType); + return getTypeWithDefault(type, node.initializer); + } + function getTypeOfInitializer(node) { + // Return the cached type if one is available. If the type of the variable was inferred + // from its initializer, we'll already have cached the type. Otherwise we compute it now + // without caching such that transient types are reflected. + var links = getNodeLinks(node); + return links.resolvedType || getTypeOfExpression(node); + } + function getInitialTypeOfVariableDeclaration(node) { + if (node.initializer) { + return getTypeOfInitializer(node.initializer); + } + if (node.parent.parent.kind === 226 /* ForInStatement */) { + return stringType; + } + if (node.parent.parent.kind === 227 /* ForOfStatement */) { + return checkRightHandSideOfForOf(node.parent.parent.expression, node.parent.parent.awaitModifier) || errorType; + } + return errorType; + } + function getInitialType(node) { + return node.kind === 237 /* VariableDeclaration */ ? + getInitialTypeOfVariableDeclaration(node) : + getInitialTypeOfBindingElement(node); + } + function getInitialOrAssignedType(node, reference) { + return getConstraintForLocation(node.kind === 237 /* VariableDeclaration */ || node.kind === 186 /* BindingElement */ ? + getInitialType(node) : + getAssignedType(node), reference); + } + function isEmptyArrayAssignment(node) { + return node.kind === 237 /* VariableDeclaration */ && node.initializer && + isEmptyArrayLiteral(node.initializer) || + node.kind !== 186 /* BindingElement */ && node.parent.kind === 204 /* BinaryExpression */ && + isEmptyArrayLiteral(node.parent.right); + } + function getReferenceCandidate(node) { + switch (node.kind) { + case 195 /* ParenthesizedExpression */: + return getReferenceCandidate(node.expression); + case 204 /* BinaryExpression */: + switch (node.operatorToken.kind) { + case 59 /* EqualsToken */: + return getReferenceCandidate(node.left); + case 27 /* CommaToken */: + return getReferenceCandidate(node.right); + } + } + return node; + } + function getReferenceRoot(node) { + var parent = node.parent; + return parent.kind === 195 /* ParenthesizedExpression */ || + parent.kind === 204 /* BinaryExpression */ && parent.operatorToken.kind === 59 /* EqualsToken */ && parent.left === node || + parent.kind === 204 /* BinaryExpression */ && parent.operatorToken.kind === 27 /* CommaToken */ && parent.right === node ? + getReferenceRoot(parent) : node; + } + function getTypeOfSwitchClause(clause) { + if (clause.kind === 271 /* CaseClause */) { + return getRegularTypeOfLiteralType(getTypeOfExpression(clause.expression)); + } + return neverType; + } + function getSwitchClauseTypes(switchStatement) { + var links = getNodeLinks(switchStatement); + if (!links.switchTypes) { + links.switchTypes = []; + for (var _i = 0, _a = switchStatement.caseBlock.clauses; _i < _a.length; _i++) { + var clause = _a[_i]; + links.switchTypes.push(getTypeOfSwitchClause(clause)); + } + } + return links.switchTypes; + } + // Get the types from all cases in a switch on `typeof`. An + // `undefined` element denotes an explicit `default` clause. + function getSwitchClauseTypeOfWitnesses(switchStatement) { + var witnesses = []; + for (var _i = 0, _a = switchStatement.caseBlock.clauses; _i < _a.length; _i++) { + var clause = _a[_i]; + if (clause.kind === 271 /* CaseClause */) { + if (clause.expression.kind === 10 /* StringLiteral */) { + witnesses.push(clause.expression.text); + continue; + } + return ts.emptyArray; + } + witnesses.push(/*explicitDefaultStatement*/ undefined); + } + return witnesses; + } + function eachTypeContainedIn(source, types) { + return source.flags & 1048576 /* Union */ ? !ts.forEach(source.types, function (t) { return !ts.contains(types, t); }) : ts.contains(types, source); + } + function isTypeSubsetOf(source, target) { + return source === target || target.flags & 1048576 /* Union */ && isTypeSubsetOfUnion(source, target); + } + function isTypeSubsetOfUnion(source, target) { + if (source.flags & 1048576 /* Union */) { + for (var _i = 0, _a = source.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (!containsType(target.types, t)) { + return false; + } + } + return true; + } + if (source.flags & 1024 /* EnumLiteral */ && getBaseTypeOfEnumLiteralType(source) === target) { + return true; + } + return containsType(target.types, source); + } + function forEachType(type, f) { + return type.flags & 1048576 /* Union */ ? ts.forEach(type.types, f) : f(type); + } + function everyType(type, f) { + return type.flags & 1048576 /* Union */ ? ts.every(type.types, f) : f(type); + } + function filterType(type, f) { + if (type.flags & 1048576 /* Union */) { + var types = type.types; + var filtered = ts.filter(types, f); + return filtered === types ? type : getUnionTypeFromSortedList(filtered, type.primitiveTypesOnly); + } + return f(type) ? type : neverType; + } + function mapType(type, mapper, noReductions) { + if (type.flags & 131072 /* Never */) { + return type; + } + if (!(type.flags & 1048576 /* Union */)) { + return mapper(type); + } + var types = type.types; + var mappedType; + var mappedTypes; + for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { + var current = types_12[_i]; + var t = mapper(current); + if (t) { + if (!mappedType) { + mappedType = t; + } + else if (!mappedTypes) { + mappedTypes = [mappedType, t]; + } + else { + mappedTypes.push(t); + } + } + } + return mappedTypes ? getUnionType(mappedTypes, noReductions ? 0 /* None */ : 1 /* Literal */) : mappedType; + } + function extractTypesOfKind(type, kind) { + return filterType(type, function (t) { return (t.flags & kind) !== 0; }); + } + // Return a new type in which occurrences of the string and number primitive types in + // typeWithPrimitives have been replaced with occurrences of string literals and numeric + // literals in typeWithLiterals, respectively. + function replacePrimitivesWithLiterals(typeWithPrimitives, typeWithLiterals) { + if (isTypeSubsetOf(stringType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 128 /* StringLiteral */) || + isTypeSubsetOf(numberType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 256 /* NumberLiteral */) || + isTypeSubsetOf(bigintType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 2048 /* BigIntLiteral */)) { + return mapType(typeWithPrimitives, function (t) { + return t.flags & 4 /* String */ ? extractTypesOfKind(typeWithLiterals, 4 /* String */ | 128 /* StringLiteral */) : + t.flags & 8 /* Number */ ? extractTypesOfKind(typeWithLiterals, 8 /* Number */ | 256 /* NumberLiteral */) : + t.flags & 64 /* BigInt */ ? extractTypesOfKind(typeWithLiterals, 64 /* BigInt */ | 2048 /* BigIntLiteral */) : + t; + }); + } + return typeWithPrimitives; + } + function isIncomplete(flowType) { + return flowType.flags === 0; + } + function getTypeFromFlowType(flowType) { + return flowType.flags === 0 ? flowType.type : flowType; + } + function createFlowType(type, incomplete) { + return incomplete ? { flags: 0, type: type } : type; + } + // An evolving array type tracks the element types that have so far been seen in an + // 'x.push(value)' or 'x[n] = value' operation along the control flow graph. Evolving + // array types are ultimately converted into manifest array types (using getFinalArrayType) + // and never escape the getFlowTypeOfReference function. + function createEvolvingArrayType(elementType) { + var result = createObjectType(256 /* EvolvingArray */); + result.elementType = elementType; + return result; + } + function getEvolvingArrayType(elementType) { + return evolvingArrayTypes[elementType.id] || (evolvingArrayTypes[elementType.id] = createEvolvingArrayType(elementType)); + } + // When adding evolving array element types we do not perform subtype reduction. Instead, + // we defer subtype reduction until the evolving array type is finalized into a manifest + // array type. + function addEvolvingArrayElementType(evolvingArrayType, node) { + var elementType = getBaseTypeOfLiteralType(getContextFreeTypeOfExpression(node)); + return isTypeSubsetOf(elementType, evolvingArrayType.elementType) ? evolvingArrayType : getEvolvingArrayType(getUnionType([evolvingArrayType.elementType, elementType])); + } + function createFinalArrayType(elementType) { + return elementType.flags & 131072 /* Never */ ? + autoArrayType : + createArrayType(elementType.flags & 1048576 /* Union */ ? + getUnionType(elementType.types, 2 /* Subtype */) : + elementType); + } + // We perform subtype reduction upon obtaining the final array type from an evolving array type. + function getFinalArrayType(evolvingArrayType) { + return evolvingArrayType.finalArrayType || (evolvingArrayType.finalArrayType = createFinalArrayType(evolvingArrayType.elementType)); + } + function finalizeEvolvingArrayType(type) { + return ts.getObjectFlags(type) & 256 /* EvolvingArray */ ? getFinalArrayType(type) : type; + } + function getElementTypeOfEvolvingArrayType(type) { + return ts.getObjectFlags(type) & 256 /* EvolvingArray */ ? type.elementType : neverType; + } + function isEvolvingArrayTypeList(types) { + var hasEvolvingArrayType = false; + for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { + var t = types_13[_i]; + if (!(t.flags & 131072 /* Never */)) { + if (!(ts.getObjectFlags(t) & 256 /* EvolvingArray */)) { + return false; + } + hasEvolvingArrayType = true; + } + } + return hasEvolvingArrayType; + } + // At flow control branch or loop junctions, if the type along every antecedent code path + // is an evolving array type, we construct a combined evolving array type. Otherwise we + // finalize all evolving array types. + function getUnionOrEvolvingArrayType(types, subtypeReduction) { + return isEvolvingArrayTypeList(types) ? + getEvolvingArrayType(getUnionType(ts.map(types, getElementTypeOfEvolvingArrayType))) : + getUnionType(ts.sameMap(types, finalizeEvolvingArrayType), subtypeReduction); + } + // Return true if the given node is 'x' in an 'x.length', x.push(value)', 'x.unshift(value)' or + // 'x[n] = value' operation, where 'n' is an expression of type any, undefined, or a number-like type. + function isEvolvingArrayOperationTarget(node) { + var root = getReferenceRoot(node); + var parent = root.parent; + var isLengthPushOrUnshift = parent.kind === 189 /* PropertyAccessExpression */ && (parent.name.escapedText === "length" || + parent.parent.kind === 191 /* CallExpression */ && ts.isPushOrUnshiftIdentifier(parent.name)); + var isElementAssignment = parent.kind === 190 /* ElementAccessExpression */ && + parent.expression === root && + parent.parent.kind === 204 /* BinaryExpression */ && + parent.parent.operatorToken.kind === 59 /* EqualsToken */ && + parent.parent.left === parent && + !ts.isAssignmentTarget(parent.parent) && + isTypeAssignableToKind(getTypeOfExpression(parent.argumentExpression), 296 /* NumberLike */); + return isLengthPushOrUnshift || isElementAssignment; + } + function maybeTypePredicateCall(node) { + var links = getNodeLinks(node); + if (links.maybeTypePredicate === undefined) { + links.maybeTypePredicate = getMaybeTypePredicate(node); + } + return links.maybeTypePredicate; + } + function getMaybeTypePredicate(node) { + if (node.expression.kind !== 98 /* SuperKeyword */) { + var funcType = checkNonNullExpression(node.expression); + if (funcType !== silentNeverType) { + var apparentType = getApparentType(funcType); + return apparentType !== errorType && ts.some(getSignaturesOfType(apparentType, 0 /* Call */), signatureHasTypePredicate); + } + } + return false; + } + function reportFlowControlError(node) { + var block = ts.findAncestor(node, ts.isFunctionOrModuleBlock); + var sourceFile = ts.getSourceFileOfNode(node); + var span = ts.getSpanOfTokenAtPosition(sourceFile, block.statements.pos); + diagnostics.add(ts.createFileDiagnostic(sourceFile, span.start, span.length, ts.Diagnostics.The_containing_function_or_module_body_is_too_large_for_control_flow_analysis)); + } + function getFlowTypeOfReference(reference, declaredType, initialType, flowContainer, couldBeUninitialized) { + if (initialType === void 0) { initialType = declaredType; } + var key; + var flowDepth = 0; + if (flowAnalysisDisabled) { + return errorType; + } + if (!reference.flowNode || !couldBeUninitialized && !(declaredType.flags & 133970943 /* Narrowable */)) { + return declaredType; + } + var sharedFlowStart = sharedFlowCount; + var evolvedType = getTypeFromFlowType(getTypeAtFlowNode(reference.flowNode)); + sharedFlowCount = sharedFlowStart; + // When the reference is 'x' in an 'x.length', 'x.push(value)', 'x.unshift(value)' or x[n] = value' operation, + // we give type 'any[]' to 'x' instead of using the type determined by control flow analysis such that operations + // on empty arrays are possible without implicit any errors and new element types can be inferred without + // type mismatch errors. + var resultType = ts.getObjectFlags(evolvedType) & 256 /* EvolvingArray */ && isEvolvingArrayOperationTarget(reference) ? autoArrayType : finalizeEvolvingArrayType(evolvedType); + if (reference.parent && reference.parent.kind === 213 /* NonNullExpression */ && getTypeWithFacts(resultType, 2097152 /* NEUndefinedOrNull */).flags & 131072 /* Never */) { + return declaredType; + } + return resultType; + function getTypeAtFlowNode(flow) { + if (flowDepth === 2000) { + // We have made 2000 recursive invocations. To avoid overflowing the call stack we report an error + // and disable further control flow analysis in the containing function or module body. + flowAnalysisDisabled = true; + reportFlowControlError(reference); + return errorType; + } + flowDepth++; + while (true) { + var flags = flow.flags; + if (flags & 1024 /* Shared */) { + // We cache results of flow type resolution for shared nodes that were previously visited in + // the same getFlowTypeOfReference invocation. A node is considered shared when it is the + // antecedent of more than one node. + for (var i = sharedFlowStart; i < sharedFlowCount; i++) { + if (sharedFlowNodes[i] === flow) { + flowDepth--; + return sharedFlowTypes[i]; + } + } + } + var type = void 0; + if (flags & 4096 /* AfterFinally */) { + // block flow edge: finally -> pre-try (for larger explanation check comment in binder.ts - bindTryStatement + flow.locked = true; + type = getTypeAtFlowNode(flow.antecedent); + flow.locked = false; + } + else if (flags & 2048 /* PreFinally */) { + // locked pre-finally flows are filtered out in getTypeAtFlowBranchLabel + // so here just redirect to antecedent + flow = flow.antecedent; + continue; + } + else if (flags & 16 /* Assignment */) { + type = getTypeAtFlowAssignment(flow); + if (!type) { + flow = flow.antecedent; + continue; + } + } + else if (flags & 96 /* Condition */) { + type = getTypeAtFlowCondition(flow); + } + else if (flags & 128 /* SwitchClause */) { + type = getTypeAtSwitchClause(flow); + } + else if (flags & 12 /* Label */) { + if (flow.antecedents.length === 1) { + flow = flow.antecedents[0]; + continue; + } + type = flags & 4 /* BranchLabel */ ? + getTypeAtFlowBranchLabel(flow) : + getTypeAtFlowLoopLabel(flow); + } + else if (flags & 256 /* ArrayMutation */) { + type = getTypeAtFlowArrayMutation(flow); + if (!type) { + flow = flow.antecedent; + continue; + } + } + else if (flags & 2 /* Start */) { + // Check if we should continue with the control flow of the containing function. + var container = flow.container; + if (container && container !== flowContainer && + reference.kind !== 189 /* PropertyAccessExpression */ && + reference.kind !== 190 /* ElementAccessExpression */ && + reference.kind !== 100 /* ThisKeyword */) { + flow = container.flowNode; + continue; + } + // At the top of the flow we have the initial type. + type = initialType; + } + else { + // Unreachable code errors are reported in the binding phase. Here we + // simply return the non-auto declared type to reduce follow-on errors. + type = convertAutoToAny(declaredType); + } + if (flags & 1024 /* Shared */) { + // Record visited node and the associated type in the cache. + sharedFlowNodes[sharedFlowCount] = flow; + sharedFlowTypes[sharedFlowCount] = type; + sharedFlowCount++; + } + flowDepth--; + return type; + } + } + function getTypeAtFlowAssignment(flow) { + var node = flow.node; + // Assignments only narrow the computed type if the declared type is a union type. Thus, we + // only need to evaluate the assigned type if the declared type is a union type. + if (isMatchingReference(reference, node)) { + if (ts.getAssignmentTargetKind(node) === 2 /* Compound */) { + var flowType = getTypeAtFlowNode(flow.antecedent); + return createFlowType(getBaseTypeOfLiteralType(getTypeFromFlowType(flowType)), isIncomplete(flowType)); + } + if (declaredType === autoType || declaredType === autoArrayType) { + if (isEmptyArrayAssignment(node)) { + return getEvolvingArrayType(neverType); + } + var assignedType = getBaseTypeOfLiteralType(getInitialOrAssignedType(node, reference)); + return isTypeAssignableTo(assignedType, declaredType) ? assignedType : anyArrayType; + } + if (declaredType.flags & 1048576 /* Union */) { + return getAssignmentReducedType(declaredType, getInitialOrAssignedType(node, reference)); + } + return declaredType; + } + // We didn't have a direct match. However, if the reference is a dotted name, this + // may be an assignment to a left hand part of the reference. For example, for a + // reference 'x.y.z', we may be at an assignment to 'x.y' or 'x'. In that case, + // return the declared type. + if (containsMatchingReference(reference, node)) { + // A matching dotted name might also be an expando property on a function *expression*, + // in which case we continue control flow analysis back to the function's declaration + if (ts.isVariableDeclaration(node) && (ts.isInJSFile(node) || ts.isVarConst(node))) { + var init = ts.getDeclaredExpandoInitializer(node); + if (init && (init.kind === 196 /* FunctionExpression */ || init.kind === 197 /* ArrowFunction */)) { + return getTypeAtFlowNode(flow.antecedent); + } + } + return declaredType; + } + // for (const _ in ref) acts as a nonnull on ref + if (ts.isVariableDeclaration(node) && node.parent.parent.kind === 226 /* ForInStatement */ && isMatchingReference(reference, node.parent.parent.expression)) { + return getNonNullableTypeIfNeeded(getTypeFromFlowType(getTypeAtFlowNode(flow.antecedent))); + } + // Assignment doesn't affect reference + return undefined; + } + function getTypeAtFlowArrayMutation(flow) { + if (declaredType === autoType || declaredType === autoArrayType) { + var node = flow.node; + var expr = node.kind === 191 /* CallExpression */ ? + node.expression.expression : + node.left.expression; + if (isMatchingReference(reference, getReferenceCandidate(expr))) { + var flowType = getTypeAtFlowNode(flow.antecedent); + var type = getTypeFromFlowType(flowType); + if (ts.getObjectFlags(type) & 256 /* EvolvingArray */) { + var evolvedType_1 = type; + if (node.kind === 191 /* CallExpression */) { + for (var _i = 0, _a = node.arguments; _i < _a.length; _i++) { + var arg = _a[_i]; + evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, arg); + } + } + else { + // We must get the context free expression type so as to not recur in an uncached fashion on the LHS (which causes exponential blowup in compile time) + var indexType = getContextFreeTypeOfExpression(node.left.argumentExpression); + if (isTypeAssignableToKind(indexType, 296 /* NumberLike */)) { + evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, node.right); + } + } + return evolvedType_1 === type ? flowType : createFlowType(evolvedType_1, isIncomplete(flowType)); + } + return flowType; + } + } + return undefined; + } + function getTypeAtFlowCondition(flow) { + var flowType = getTypeAtFlowNode(flow.antecedent); + var type = getTypeFromFlowType(flowType); + if (type.flags & 131072 /* Never */) { + return flowType; + } + // If we have an antecedent type (meaning we're reachable in some way), we first + // attempt to narrow the antecedent type. If that produces the never type, and if + // the antecedent type is incomplete (i.e. a transient type in a loop), then we + // take the type guard as an indication that control *could* reach here once we + // have the complete type. We proceed by switching to the silent never type which + // doesn't report errors when operators are applied to it. Note that this is the + // *only* place a silent never type is ever generated. + var assumeTrue = (flow.flags & 32 /* TrueCondition */) !== 0; + var nonEvolvingType = finalizeEvolvingArrayType(type); + var narrowedType = narrowType(nonEvolvingType, flow.expression, assumeTrue); + if (narrowedType === nonEvolvingType) { + return flowType; + } + var incomplete = isIncomplete(flowType); + var resultType = incomplete && narrowedType.flags & 131072 /* Never */ ? silentNeverType : narrowedType; + return createFlowType(resultType, incomplete); + } + function getTypeAtSwitchClause(flow) { + var expr = flow.switchStatement.expression; + if (containsMatchingReferenceDiscriminant(reference, expr)) { + return declaredType; + } + var flowType = getTypeAtFlowNode(flow.antecedent); + var type = getTypeFromFlowType(flowType); + if (isMatchingReference(reference, expr)) { + type = narrowTypeBySwitchOnDiscriminant(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); + } + else if (isMatchingReferenceDiscriminant(expr, type)) { + type = narrowTypeByDiscriminant(type, expr, function (t) { return narrowTypeBySwitchOnDiscriminant(t, flow.switchStatement, flow.clauseStart, flow.clauseEnd); }); + } + else if (expr.kind === 199 /* TypeOfExpression */ && isMatchingReference(reference, expr.expression)) { + type = narrowBySwitchOnTypeOf(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); + } + return createFlowType(type, isIncomplete(flowType)); + } + function getTypeAtFlowBranchLabel(flow) { + var antecedentTypes = []; + var subtypeReduction = false; + var seenIncomplete = false; + for (var _i = 0, _a = flow.antecedents; _i < _a.length; _i++) { + var antecedent = _a[_i]; + if (antecedent.flags & 2048 /* PreFinally */ && antecedent.lock.locked) { + // if flow correspond to branch from pre-try to finally and this branch is locked - this means that + // we initially have started following the flow outside the finally block. + // in this case we should ignore this branch. + continue; + } + var flowType = getTypeAtFlowNode(antecedent); + var type = getTypeFromFlowType(flowType); + // If the type at a particular antecedent path is the declared type and the + // reference is known to always be assigned (i.e. when declared and initial types + // are the same), there is no reason to process more antecedents since the only + // possible outcome is subtypes that will be removed in the final union type anyway. + if (type === declaredType && declaredType === initialType) { + return type; + } + ts.pushIfUnique(antecedentTypes, type); + // If an antecedent type is not a subset of the declared type, we need to perform + // subtype reduction. This happens when a "foreign" type is injected into the control + // flow using the instanceof operator or a user defined type predicate. + if (!isTypeSubsetOf(type, declaredType)) { + subtypeReduction = true; + } + if (isIncomplete(flowType)) { + seenIncomplete = true; + } + } + return createFlowType(getUnionOrEvolvingArrayType(antecedentTypes, subtypeReduction ? 2 /* Subtype */ : 1 /* Literal */), seenIncomplete); + } + function getTypeAtFlowLoopLabel(flow) { + // If we have previously computed the control flow type for the reference at + // this flow loop junction, return the cached type. + var id = getFlowNodeId(flow); + var cache = flowLoopCaches[id] || (flowLoopCaches[id] = ts.createMap()); + if (!key) { + key = getFlowCacheKey(reference); + // No cache key is generated when binding patterns are in unnarrowable situations + if (!key) { + return declaredType; + } + } + var cached = cache.get(key); + if (cached) { + return cached; + } + // If this flow loop junction and reference are already being processed, return + // the union of the types computed for each branch so far, marked as incomplete. + // It is possible to see an empty array in cases where loops are nested and the + // back edge of the outer loop reaches an inner loop that is already being analyzed. + // In such cases we restart the analysis of the inner loop, which will then see + // a non-empty in-process array for the outer loop and eventually terminate because + // the first antecedent of a loop junction is always the non-looping control flow + // path that leads to the top. + for (var i = flowLoopStart; i < flowLoopCount; i++) { + if (flowLoopNodes[i] === flow && flowLoopKeys[i] === key && flowLoopTypes[i].length) { + return createFlowType(getUnionOrEvolvingArrayType(flowLoopTypes[i], 1 /* Literal */), /*incomplete*/ true); + } + } + // Add the flow loop junction and reference to the in-process stack and analyze + // each antecedent code path. + var antecedentTypes = []; + var subtypeReduction = false; + var firstAntecedentType; + flowLoopNodes[flowLoopCount] = flow; + flowLoopKeys[flowLoopCount] = key; + flowLoopTypes[flowLoopCount] = antecedentTypes; + for (var _i = 0, _a = flow.antecedents; _i < _a.length; _i++) { + var antecedent = _a[_i]; + flowLoopCount++; + var flowType = getTypeAtFlowNode(antecedent); + flowLoopCount--; + if (!firstAntecedentType) { + firstAntecedentType = flowType; + } + var type = getTypeFromFlowType(flowType); + // If we see a value appear in the cache it is a sign that control flow analysis + // was restarted and completed by checkExpressionCached. We can simply pick up + // the resulting type and bail out. + var cached_1 = cache.get(key); + if (cached_1) { + return cached_1; + } + ts.pushIfUnique(antecedentTypes, type); + // If an antecedent type is not a subset of the declared type, we need to perform + // subtype reduction. This happens when a "foreign" type is injected into the control + // flow using the instanceof operator or a user defined type predicate. + if (!isTypeSubsetOf(type, declaredType)) { + subtypeReduction = true; + } + // If the type at a particular antecedent path is the declared type there is no + // reason to process more antecedents since the only possible outcome is subtypes + // that will be removed in the final union type anyway. + if (type === declaredType) { + break; + } + } + // The result is incomplete if the first antecedent (the non-looping control flow path) + // is incomplete. + var result = getUnionOrEvolvingArrayType(antecedentTypes, subtypeReduction ? 2 /* Subtype */ : 1 /* Literal */); + if (isIncomplete(firstAntecedentType)) { + return createFlowType(result, /*incomplete*/ true); + } + cache.set(key, result); + return result; + } + function isMatchingReferenceDiscriminant(expr, computedType) { + if (!(computedType.flags & 1048576 /* Union */) || + expr.kind !== 189 /* PropertyAccessExpression */ && expr.kind !== 190 /* ElementAccessExpression */) { + return false; + } + var access = expr; + var name = getAccessedPropertyName(access); + if (!name) { + return false; + } + return isMatchingReference(reference, access.expression) && isDiscriminantProperty(computedType, name); + } + function narrowTypeByDiscriminant(type, access, narrowType) { + var propName = getAccessedPropertyName(access); + if (!propName) { + return type; + } + var propType = getTypeOfPropertyOfType(type, propName); + var narrowedPropType = propType && narrowType(propType); + return propType === narrowedPropType ? type : filterType(type, function (t) { return isTypeComparableTo(getTypeOfPropertyOfType(t, propName), narrowedPropType); }); + } + function narrowTypeByTruthiness(type, expr, assumeTrue) { + if (isMatchingReference(reference, expr)) { + return getTypeWithFacts(type, assumeTrue ? 4194304 /* Truthy */ : 8388608 /* Falsy */); + } + if (isMatchingReferenceDiscriminant(expr, declaredType)) { + return narrowTypeByDiscriminant(type, expr, function (t) { return getTypeWithFacts(t, assumeTrue ? 4194304 /* Truthy */ : 8388608 /* Falsy */); }); + } + if (containsMatchingReferenceDiscriminant(reference, expr)) { + return declaredType; + } + return type; + } + function isTypePresencePossible(type, propName, assumeTrue) { + if (getIndexInfoOfType(type, 0 /* String */)) { + return true; + } + var prop = getPropertyOfType(type, propName); + if (prop) { + return prop.flags & 16777216 /* Optional */ ? true : assumeTrue; + } + return !assumeTrue; + } + function narrowByInKeyword(type, literal, assumeTrue) { + if ((type.flags & (1048576 /* Union */ | 524288 /* Object */)) || (type.flags & 262144 /* TypeParameter */ && type.isThisType)) { + var propName_1 = ts.escapeLeadingUnderscores(literal.text); + return filterType(type, function (t) { return isTypePresencePossible(t, propName_1, assumeTrue); }); + } + return type; + } + function narrowTypeByBinaryExpression(type, expr, assumeTrue) { + switch (expr.operatorToken.kind) { + case 59 /* EqualsToken */: + return narrowTypeByTruthiness(type, expr.left, assumeTrue); + case 33 /* EqualsEqualsToken */: + case 34 /* ExclamationEqualsToken */: + case 35 /* EqualsEqualsEqualsToken */: + case 36 /* ExclamationEqualsEqualsToken */: + var operator_1 = expr.operatorToken.kind; + var left_1 = getReferenceCandidate(expr.left); + var right_1 = getReferenceCandidate(expr.right); + if (left_1.kind === 199 /* TypeOfExpression */ && ts.isStringLiteralLike(right_1)) { + return narrowTypeByTypeof(type, left_1, operator_1, right_1, assumeTrue); + } + if (right_1.kind === 199 /* TypeOfExpression */ && ts.isStringLiteralLike(left_1)) { + return narrowTypeByTypeof(type, right_1, operator_1, left_1, assumeTrue); + } + if (isMatchingReference(reference, left_1)) { + return narrowTypeByEquality(type, operator_1, right_1, assumeTrue); + } + if (isMatchingReference(reference, right_1)) { + return narrowTypeByEquality(type, operator_1, left_1, assumeTrue); + } + if (isMatchingReferenceDiscriminant(left_1, declaredType)) { + return narrowTypeByDiscriminant(type, left_1, function (t) { return narrowTypeByEquality(t, operator_1, right_1, assumeTrue); }); + } + if (isMatchingReferenceDiscriminant(right_1, declaredType)) { + return narrowTypeByDiscriminant(type, right_1, function (t) { return narrowTypeByEquality(t, operator_1, left_1, assumeTrue); }); + } + if (containsMatchingReferenceDiscriminant(reference, left_1) || containsMatchingReferenceDiscriminant(reference, right_1)) { + return declaredType; + } + break; + case 94 /* InstanceOfKeyword */: + return narrowTypeByInstanceof(type, expr, assumeTrue); + case 93 /* InKeyword */: + var target = getReferenceCandidate(expr.right); + if (ts.isStringLiteralLike(expr.left) && isMatchingReference(reference, target)) { + return narrowByInKeyword(type, expr.left, assumeTrue); + } + break; + case 27 /* CommaToken */: + return narrowType(type, expr.right, assumeTrue); + } + return type; + } + function narrowTypeByEquality(type, operator, value, assumeTrue) { + if (type.flags & 1 /* Any */) { + return type; + } + if (operator === 34 /* ExclamationEqualsToken */ || operator === 36 /* ExclamationEqualsEqualsToken */) { + assumeTrue = !assumeTrue; + } + var valueType = getTypeOfExpression(value); + if (valueType.flags & 98304 /* Nullable */) { + if (!strictNullChecks) { + return type; + } + var doubleEquals = operator === 33 /* EqualsEqualsToken */ || operator === 34 /* ExclamationEqualsToken */; + var facts = doubleEquals ? + assumeTrue ? 262144 /* EQUndefinedOrNull */ : 2097152 /* NEUndefinedOrNull */ : + valueType.flags & 65536 /* Null */ ? + assumeTrue ? 131072 /* EQNull */ : 1048576 /* NENull */ : + assumeTrue ? 65536 /* EQUndefined */ : 524288 /* NEUndefined */; + return getTypeWithFacts(type, facts); + } + if (type.flags & 67637251 /* NotUnionOrUnit */) { + return type; + } + if (assumeTrue) { + var narrowedType = filterType(type, function (t) { return areTypesComparable(t, valueType); }); + return narrowedType.flags & 131072 /* Never */ ? type : replacePrimitivesWithLiterals(narrowedType, valueType); + } + if (isUnitType(valueType)) { + var regularType_1 = getRegularTypeOfLiteralType(valueType); + return filterType(type, function (t) { return getRegularTypeOfLiteralType(t) !== regularType_1; }); + } + return type; + } + function narrowTypeByTypeof(type, typeOfExpr, operator, literal, assumeTrue) { + // We have '==', '!=', '====', or !==' operator with 'typeof xxx' and string literal operands + var target = getReferenceCandidate(typeOfExpr.expression); + if (!isMatchingReference(reference, target)) { + // For a reference of the form 'x.y', where 'x' has a narrowable declared type, a + // 'typeof x === ...' type guard resets the narrowed type of 'y' to its declared type. + if (containsMatchingReference(reference, target) && hasNarrowableDeclaredType(target)) { + return declaredType; + } + return type; + } + if (operator === 34 /* ExclamationEqualsToken */ || operator === 36 /* ExclamationEqualsEqualsToken */) { + assumeTrue = !assumeTrue; + } + if (type.flags & 1 /* Any */ && literal.text === "function") { + return type; + } + var facts = assumeTrue ? + typeofEQFacts.get(literal.text) || 128 /* TypeofEQHostObject */ : + typeofNEFacts.get(literal.text) || 32768 /* TypeofNEHostObject */; + return getTypeWithFacts(assumeTrue ? mapType(type, narrowTypeForTypeof) : type, facts); + function narrowTypeForTypeof(type) { + if (type.flags & 2 /* Unknown */ && literal.text === "object") { + return getUnionType([nonPrimitiveType, nullType]); + } + // We narrow a non-union type to an exact primitive type if the non-union type + // is a supertype of that primitive type. For example, type 'any' can be narrowed + // to one of the primitive types. + var targetType = literal.text === "function" ? globalFunctionType : typeofTypesByName.get(literal.text); + if (targetType) { + if (isTypeSubtypeOf(type, targetType)) { + return type; + } + if (isTypeSubtypeOf(targetType, type)) { + return targetType; + } + if (type.flags & 63176704 /* Instantiable */) { + var constraint = getBaseConstraintOfType(type) || anyType; + if (isTypeSubtypeOf(targetType, constraint)) { + return getIntersectionType([type, targetType]); + } + } + } + return type; + } + } + function narrowTypeBySwitchOnDiscriminant(type, switchStatement, clauseStart, clauseEnd) { + // We only narrow if all case expressions specify values with unit types + var switchTypes = getSwitchClauseTypes(switchStatement); + if (!switchTypes.length) { + return type; + } + var clauseTypes = switchTypes.slice(clauseStart, clauseEnd); + var hasDefaultClause = clauseStart === clauseEnd || ts.contains(clauseTypes, neverType); + var discriminantType = getUnionType(clauseTypes); + var caseType = discriminantType.flags & 131072 /* Never */ ? neverType : + replacePrimitivesWithLiterals(filterType(type, function (t) { return areTypesComparable(discriminantType, t); }), discriminantType); + if (!hasDefaultClause) { + return caseType; + } + var defaultType = filterType(type, function (t) { return !(isUnitType(t) && ts.contains(switchTypes, getRegularTypeOfLiteralType(t))); }); + return caseType.flags & 131072 /* Never */ ? defaultType : getUnionType([caseType, defaultType]); + } + function getImpliedTypeFromTypeofCase(type, text) { + switch (text) { + case "function": + return type.flags & 1 /* Any */ ? type : globalFunctionType; + case "object": + return type.flags & 2 /* Unknown */ ? getUnionType([nonPrimitiveType, nullType]) : type; + default: + return typeofTypesByName.get(text) || type; + } + } + function narrowTypeForTypeofSwitch(candidate) { + return function (type) { + if (isTypeSubtypeOf(candidate, type)) { + return candidate; + } + if (type.flags & 63176704 /* Instantiable */) { + var constraint = getBaseConstraintOfType(type) || anyType; + if (isTypeSubtypeOf(candidate, constraint)) { + return getIntersectionType([type, candidate]); + } + } + return type; + }; + } + function narrowBySwitchOnTypeOf(type, switchStatement, clauseStart, clauseEnd) { + var switchWitnesses = getSwitchClauseTypeOfWitnesses(switchStatement); + if (!switchWitnesses.length) { + return type; + } + // Equal start and end denotes implicit fallthrough; undefined marks explicit default clause + var defaultCaseLocation = ts.findIndex(switchWitnesses, function (elem) { return elem === undefined; }); + var hasDefaultClause = clauseStart === clauseEnd || (defaultCaseLocation >= clauseStart && defaultCaseLocation < clauseEnd); + var clauseWitnesses; + var switchFacts; + if (defaultCaseLocation > -1) { + // We no longer need the undefined denoting an + // explicit default case. Remove the undefined and + // fix-up clauseStart and clauseEnd. This means + // that we don't have to worry about undefined + // in the witness array. + var witnesses = switchWitnesses.filter(function (witness) { return witness !== undefined; }); + // The adjusted clause start and end after removing the `default` statement. + var fixedClauseStart = defaultCaseLocation < clauseStart ? clauseStart - 1 : clauseStart; + var fixedClauseEnd = defaultCaseLocation < clauseEnd ? clauseEnd - 1 : clauseEnd; + clauseWitnesses = witnesses.slice(fixedClauseStart, fixedClauseEnd); + switchFacts = getFactsFromTypeofSwitch(fixedClauseStart, fixedClauseEnd, witnesses, hasDefaultClause); + } + else { + clauseWitnesses = switchWitnesses.slice(clauseStart, clauseEnd); + switchFacts = getFactsFromTypeofSwitch(clauseStart, clauseEnd, switchWitnesses, hasDefaultClause); + } + if (hasDefaultClause) { + return filterType(type, function (t) { return (getTypeFacts(t) & switchFacts) === switchFacts; }); + } + /* + The implied type is the raw type suggested by a + value being caught in this clause. + + When the clause contains a default case we ignore + the implied type and try to narrow using any facts + we can learn: see `switchFacts`. + + Example: + switch (typeof x) { + case 'number': + case 'string': break; + default: break; + case 'number': + case 'boolean': break + } + + In the first clause (case `number` and `string`) the + implied type is number | string. + + In the default clause we de not compute an implied type. + + In the third clause (case `number` and `boolean`) + the naive implied type is number | boolean, however + we use the type facts to narrow the implied type to + boolean. We know that number cannot be selected + because it is caught in the first clause. + */ + var impliedType = getTypeWithFacts(getUnionType(clauseWitnesses.map(function (text) { return getImpliedTypeFromTypeofCase(type, text); })), switchFacts); + if (impliedType.flags & 1048576 /* Union */) { + impliedType = getAssignmentReducedType(impliedType, getBaseConstraintOrType(type)); + } + return getTypeWithFacts(mapType(type, narrowTypeForTypeofSwitch(impliedType)), switchFacts); + } + function narrowTypeByInstanceof(type, expr, assumeTrue) { + var left = getReferenceCandidate(expr.left); + if (!isMatchingReference(reference, left)) { + // For a reference of the form 'x.y', where 'x' has a narrowable declared type, an + // 'x instanceof T' type guard resets the narrowed type of 'y' to its declared type. + if (containsMatchingReference(reference, left) && hasNarrowableDeclaredType(left)) { + return declaredType; + } + return type; + } + // Check that right operand is a function type with a prototype property + var rightType = getTypeOfExpression(expr.right); + if (!isTypeDerivedFrom(rightType, globalFunctionType)) { + return type; + } + var targetType; + var prototypeProperty = getPropertyOfType(rightType, "prototype"); + if (prototypeProperty) { + // Target type is type of the prototype property + var prototypePropertyType = getTypeOfSymbol(prototypeProperty); + if (!isTypeAny(prototypePropertyType)) { + targetType = prototypePropertyType; + } + } + // Don't narrow from 'any' if the target type is exactly 'Object' or 'Function' + if (isTypeAny(type) && (targetType === globalObjectType || targetType === globalFunctionType)) { + return type; + } + if (!targetType) { + var constructSignatures = getSignaturesOfType(rightType, 1 /* Construct */); + targetType = constructSignatures.length ? + getUnionType(ts.map(constructSignatures, function (signature) { return getReturnTypeOfSignature(getErasedSignature(signature)); })) : + emptyObjectType; + } + return getNarrowedType(type, targetType, assumeTrue, isTypeDerivedFrom); + } + function getNarrowedType(type, candidate, assumeTrue, isRelated) { + if (!assumeTrue) { + return filterType(type, function (t) { return !isRelated(t, candidate); }); + } + // If the current type is a union type, remove all constituents that couldn't be instances of + // the candidate type. If one or more constituents remain, return a union of those. + if (type.flags & 1048576 /* Union */) { + var assignableType = filterType(type, function (t) { return isRelated(t, candidate); }); + if (!(assignableType.flags & 131072 /* Never */)) { + return assignableType; + } + } + // If the candidate type is a subtype of the target type, narrow to the candidate type. + // Otherwise, if the target type is assignable to the candidate type, keep the target type. + // Otherwise, if the candidate type is assignable to the target type, narrow to the candidate + // type. Otherwise, the types are completely unrelated, so narrow to an intersection of the + // two types. + return isTypeSubtypeOf(candidate, type) ? candidate : + isTypeAssignableTo(type, candidate) ? type : + isTypeAssignableTo(candidate, type) ? candidate : + getIntersectionType([type, candidate]); + } + function narrowTypeByTypePredicate(type, callExpression, assumeTrue) { + if (!hasMatchingArgument(callExpression, reference) || !maybeTypePredicateCall(callExpression)) { + return type; + } + var signature = getResolvedSignature(callExpression); + var predicate = getTypePredicateOfSignature(signature); + if (!predicate) { + return type; + } + // Don't narrow from 'any' if the predicate type is exactly 'Object' or 'Function' + if (isTypeAny(type) && (predicate.type === globalObjectType || predicate.type === globalFunctionType)) { + return type; + } + if (ts.isIdentifierTypePredicate(predicate)) { + var predicateArgument = callExpression.arguments[predicate.parameterIndex - (signature.thisParameter ? 1 : 0)]; + if (predicateArgument) { + if (isMatchingReference(reference, predicateArgument)) { + return getNarrowedType(type, predicate.type, assumeTrue, isTypeSubtypeOf); + } + if (containsMatchingReference(reference, predicateArgument)) { + return declaredType; + } + } + } + else { + var invokedExpression = ts.skipParentheses(callExpression.expression); + if (invokedExpression.kind === 190 /* ElementAccessExpression */ || invokedExpression.kind === 189 /* PropertyAccessExpression */) { + var accessExpression = invokedExpression; + var possibleReference = ts.skipParentheses(accessExpression.expression); + if (isMatchingReference(reference, possibleReference)) { + return getNarrowedType(type, predicate.type, assumeTrue, isTypeSubtypeOf); + } + if (containsMatchingReference(reference, possibleReference)) { + return declaredType; + } + } + } + return type; + } + // Narrow the given type based on the given expression having the assumed boolean value. The returned type + // will be a subtype or the same type as the argument. + function narrowType(type, expr, assumeTrue) { + switch (expr.kind) { + case 72 /* Identifier */: + case 100 /* ThisKeyword */: + case 98 /* SuperKeyword */: + case 189 /* PropertyAccessExpression */: + case 190 /* ElementAccessExpression */: + return narrowTypeByTruthiness(type, expr, assumeTrue); + case 191 /* CallExpression */: + return narrowTypeByTypePredicate(type, expr, assumeTrue); + case 195 /* ParenthesizedExpression */: + return narrowType(type, expr.expression, assumeTrue); + case 204 /* BinaryExpression */: + return narrowTypeByBinaryExpression(type, expr, assumeTrue); + case 202 /* PrefixUnaryExpression */: + if (expr.operator === 52 /* ExclamationToken */) { + return narrowType(type, expr.operand, !assumeTrue); + } + break; + } + return type; + } + } + function getTypeOfSymbolAtLocation(symbol, location) { + symbol = symbol.exportSymbol || symbol; + // If we have an identifier or a property access at the given location, if the location is + // an dotted name expression, and if the location is not an assignment target, obtain the type + // of the expression (which will reflect control flow analysis). If the expression indeed + // resolved to the given symbol, return the narrowed type. + if (location.kind === 72 /* Identifier */) { + if (ts.isRightSideOfQualifiedNameOrPropertyAccess(location)) { + location = location.parent; + } + if (ts.isExpressionNode(location) && !ts.isAssignmentTarget(location)) { + var type = getTypeOfExpression(location); + if (getExportSymbolOfValueSymbolIfExported(getNodeLinks(location).resolvedSymbol) === symbol) { + return type; + } + } + } + // The location isn't a reference to the given symbol, meaning we're being asked + // a hypothetical question of what type the symbol would have if there was a reference + // to it at the given location. Since we have no control flow information for the + // hypothetical reference (control flow information is created and attached by the + // binder), we simply return the declared type of the symbol. + return getTypeOfSymbol(symbol); + } + function getControlFlowContainer(node) { + return ts.findAncestor(node.parent, function (node) { + return ts.isFunctionLike(node) && !ts.getImmediatelyInvokedFunctionExpression(node) || + node.kind === 245 /* ModuleBlock */ || + node.kind === 279 /* SourceFile */ || + node.kind === 154 /* PropertyDeclaration */; + }); + } + // Check if a parameter is assigned anywhere within its declaring function. + function isParameterAssigned(symbol) { + var func = ts.getRootDeclaration(symbol.valueDeclaration).parent; + var links = getNodeLinks(func); + if (!(links.flags & 8388608 /* AssignmentsMarked */)) { + links.flags |= 8388608 /* AssignmentsMarked */; + if (!hasParentWithAssignmentsMarked(func)) { + markParameterAssignments(func); + } + } + return symbol.isAssigned || false; + } + function hasParentWithAssignmentsMarked(node) { + return !!ts.findAncestor(node.parent, function (node) { return ts.isFunctionLike(node) && !!(getNodeLinks(node).flags & 8388608 /* AssignmentsMarked */); }); + } + function markParameterAssignments(node) { + if (node.kind === 72 /* Identifier */) { + if (ts.isAssignmentTarget(node)) { + var symbol = getResolvedSymbol(node); + if (symbol.valueDeclaration && ts.getRootDeclaration(symbol.valueDeclaration).kind === 151 /* Parameter */) { + symbol.isAssigned = true; + } + } + } + else { + ts.forEachChild(node, markParameterAssignments); + } + } + function isConstVariable(symbol) { + return symbol.flags & 3 /* Variable */ && (getDeclarationNodeFlagsFromSymbol(symbol) & 2 /* Const */) !== 0 && getTypeOfSymbol(symbol) !== autoArrayType; + } + /** remove undefined from the annotated type of a parameter when there is an initializer (that doesn't include undefined) */ + function removeOptionalityFromDeclaredType(declaredType, declaration) { + var annotationIncludesUndefined = strictNullChecks && + declaration.kind === 151 /* Parameter */ && + declaration.initializer && + getFalsyFlags(declaredType) & 32768 /* Undefined */ && + !(getFalsyFlags(checkExpression(declaration.initializer)) & 32768 /* Undefined */); + return annotationIncludesUndefined ? getTypeWithFacts(declaredType, 524288 /* NEUndefined */) : declaredType; + } + function isConstraintPosition(node) { + var parent = node.parent; + return parent.kind === 189 /* PropertyAccessExpression */ || + parent.kind === 191 /* CallExpression */ && parent.expression === node || + parent.kind === 190 /* ElementAccessExpression */ && parent.expression === node || + parent.kind === 186 /* BindingElement */ && parent.name === node && !!parent.initializer; + } + function typeHasNullableConstraint(type) { + return type.flags & 58982400 /* InstantiableNonPrimitive */ && maybeTypeOfKind(getBaseConstraintOfType(type) || emptyObjectType, 98304 /* Nullable */); + } + function getConstraintForLocation(type, node) { + // When a node is the left hand expression of a property access, element access, or call expression, + // and the type of the node includes type variables with constraints that are nullable, we fetch the + // apparent type of the node *before* performing control flow analysis such that narrowings apply to + // the constraint type. + if (type && isConstraintPosition(node) && forEachType(type, typeHasNullableConstraint)) { + return mapType(getWidenedType(type), getBaseConstraintOrType); + } + return type; + } + function markAliasReferenced(symbol, location) { + if (isNonLocalAlias(symbol, /*excludes*/ 67220415 /* Value */) && !isInTypeQuery(location) && !isConstEnumOrConstEnumOnlyModule(resolveAlias(symbol))) { + markAliasSymbolAsReferenced(symbol); + } + } + function checkIdentifier(node) { + var symbol = getResolvedSymbol(node); + if (symbol === unknownSymbol) { + return errorType; + } + // As noted in ECMAScript 6 language spec, arrow functions never have an arguments objects. + // Although in down-level emit of arrow function, we emit it using function expression which means that + // arguments objects will be bound to the inner object; emitting arrow function natively in ES6, arguments objects + // will be bound to non-arrow function that contain this arrow function. This results in inconsistent behavior. + // To avoid that we will give an error to users if they use arguments objects in arrow function so that they + // can explicitly bound arguments objects + if (symbol === argumentsSymbol) { + var container = ts.getContainingFunction(node); + if (languageVersion < 2 /* ES2015 */) { + if (container.kind === 197 /* ArrowFunction */) { + error(node, ts.Diagnostics.The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_standard_function_expression); + } + else if (ts.hasModifier(container, 256 /* Async */)) { + error(node, ts.Diagnostics.The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_using_a_standard_function_or_method); + } + } + getNodeLinks(container).flags |= 8192 /* CaptureArguments */; + return getTypeOfSymbol(symbol); + } + // We should only mark aliases as referenced if there isn't a local value declaration + // for the symbol. Also, don't mark any property access expression LHS - checkPropertyAccessExpression will handle that + if (!(node.parent && ts.isPropertyAccessExpression(node.parent) && node.parent.expression === node)) { + markAliasReferenced(symbol, node); + } + var localOrExportSymbol = getExportSymbolOfValueSymbolIfExported(symbol); + var declaration = localOrExportSymbol.valueDeclaration; + if (localOrExportSymbol.flags & 32 /* Class */) { + // Due to the emit for class decorators, any reference to the class from inside of the class body + // must instead be rewritten to point to a temporary variable to avoid issues with the double-bind + // behavior of class names in ES6. + if (declaration.kind === 240 /* ClassDeclaration */ + && ts.nodeIsDecorated(declaration)) { + var container = ts.getContainingClass(node); + while (container !== undefined) { + if (container === declaration && container.name !== node) { + getNodeLinks(declaration).flags |= 16777216 /* ClassWithConstructorReference */; + getNodeLinks(node).flags |= 33554432 /* ConstructorReferenceInClass */; + break; + } + container = ts.getContainingClass(container); + } + } + else if (declaration.kind === 209 /* ClassExpression */) { + // When we emit a class expression with static members that contain a reference + // to the constructor in the initializer, we will need to substitute that + // binding with an alias as the class name is not in scope. + var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); + while (container.kind !== 279 /* SourceFile */) { + if (container.parent === declaration) { + if (container.kind === 154 /* PropertyDeclaration */ && ts.hasModifier(container, 32 /* Static */)) { + getNodeLinks(declaration).flags |= 16777216 /* ClassWithConstructorReference */; + getNodeLinks(node).flags |= 33554432 /* ConstructorReferenceInClass */; + } + break; + } + container = ts.getThisContainer(container, /*includeArrowFunctions*/ false); + } + } + } + checkNestedBlockScopedBinding(node, symbol); + var type = getConstraintForLocation(getTypeOfSymbol(localOrExportSymbol), node); + var assignmentKind = ts.getAssignmentTargetKind(node); + if (assignmentKind) { + if (!(localOrExportSymbol.flags & 3 /* Variable */) && + !(ts.isInJSFile(node) && localOrExportSymbol.flags & 512 /* ValueModule */)) { + error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_not_a_variable, symbolToString(symbol)); + return errorType; + } + if (isReadonlySymbol(localOrExportSymbol)) { + if (localOrExportSymbol.flags & 3 /* Variable */) { + error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant, symbolToString(symbol)); + } + else { + error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, symbolToString(symbol)); + } + return errorType; + } + } + var isAlias = localOrExportSymbol.flags & 2097152 /* Alias */; + // We only narrow variables and parameters occurring in a non-assignment position. For all other + // entities we simply return the declared type. + if (localOrExportSymbol.flags & 3 /* Variable */) { + if (assignmentKind === 1 /* Definite */) { + return type; + } + } + else if (isAlias) { + declaration = ts.find(symbol.declarations, isSomeImportDeclaration); + } + else { + return type; + } + if (!declaration) { + return type; + } + // The declaration container is the innermost function that encloses the declaration of the variable + // or parameter. The flow container is the innermost function starting with which we analyze the control + // flow graph to determine the control flow based type. + var isParameter = ts.getRootDeclaration(declaration).kind === 151 /* Parameter */; + var declarationContainer = getControlFlowContainer(declaration); + var flowContainer = getControlFlowContainer(node); + var isOuterVariable = flowContainer !== declarationContainer; + var isSpreadDestructuringAssignmentTarget = node.parent && node.parent.parent && ts.isSpreadAssignment(node.parent) && isDestructuringAssignmentTarget(node.parent.parent); + var isModuleExports = symbol.flags & 134217728 /* ModuleExports */; + // When the control flow originates in a function expression or arrow function and we are referencing + // a const variable or parameter from an outer function, we extend the origin of the control flow + // analysis to include the immediately enclosing function. + while (flowContainer !== declarationContainer && (flowContainer.kind === 196 /* FunctionExpression */ || + flowContainer.kind === 197 /* ArrowFunction */ || ts.isObjectLiteralOrClassExpressionMethod(flowContainer)) && + (isConstVariable(localOrExportSymbol) || isParameter && !isParameterAssigned(localOrExportSymbol))) { + flowContainer = getControlFlowContainer(flowContainer); + } + // We only look for uninitialized variables in strict null checking mode, and only when we can analyze + // the entire control flow graph from the variable's declaration (i.e. when the flow container and + // declaration container are the same). + var assumeInitialized = isParameter || isAlias || isOuterVariable || isSpreadDestructuringAssignmentTarget || isModuleExports || + type !== autoType && type !== autoArrayType && (!strictNullChecks || (type.flags & 3 /* AnyOrUnknown */) !== 0 || + isInTypeQuery(node) || node.parent.kind === 257 /* ExportSpecifier */) || + node.parent.kind === 213 /* NonNullExpression */ || + declaration.kind === 237 /* VariableDeclaration */ && declaration.exclamationToken || + declaration.flags & 4194304 /* Ambient */; + var initialType = assumeInitialized ? (isParameter ? removeOptionalityFromDeclaredType(type, declaration) : type) : + type === autoType || type === autoArrayType ? undefinedType : + getOptionalType(type); + var flowType = getFlowTypeOfReference(node, type, initialType, flowContainer, !assumeInitialized); + // A variable is considered uninitialized when it is possible to analyze the entire control flow graph + // from declaration to use, and when the variable's declared type doesn't include undefined but the + // control flow based type does include undefined. + if (!isEvolvingArrayOperationTarget(node) && (type === autoType || type === autoArrayType)) { + if (flowType === autoType || flowType === autoArrayType) { + if (noImplicitAny) { + error(ts.getNameOfDeclaration(declaration), ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined, symbolToString(symbol), typeToString(flowType)); + error(node, ts.Diagnostics.Variable_0_implicitly_has_an_1_type, symbolToString(symbol), typeToString(flowType)); + } + return convertAutoToAny(flowType); + } + } + else if (!assumeInitialized && !(getFalsyFlags(type) & 32768 /* Undefined */) && getFalsyFlags(flowType) & 32768 /* Undefined */) { + error(node, ts.Diagnostics.Variable_0_is_used_before_being_assigned, symbolToString(symbol)); + // Return the declared type to reduce follow-on errors + return type; + } + return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType; + } + function isInsideFunction(node, threshold) { + return !!ts.findAncestor(node, function (n) { return n === threshold ? "quit" : ts.isFunctionLike(n); }); + } + function getPartOfForStatementContainingNode(node, container) { + return ts.findAncestor(node, function (n) { return n === container ? "quit" : n === container.initializer || n === container.condition || n === container.incrementor || n === container.statement; }); + } + function checkNestedBlockScopedBinding(node, symbol) { + if (languageVersion >= 2 /* ES2015 */ || + (symbol.flags & (2 /* BlockScopedVariable */ | 32 /* Class */)) === 0 || + symbol.valueDeclaration.parent.kind === 274 /* CatchClause */) { + return; + } + // 1. walk from the use site up to the declaration and check + // if there is anything function like between declaration and use-site (is binding/class is captured in function). + // 2. walk from the declaration up to the boundary of lexical environment and check + // if there is an iteration statement in between declaration and boundary (is binding/class declared inside iteration statement) + var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); + var usedInFunction = isInsideFunction(node.parent, container); + var current = container; + var containedInIterationStatement = false; + while (current && !ts.nodeStartsNewLexicalEnvironment(current)) { + if (ts.isIterationStatement(current, /*lookInLabeledStatements*/ false)) { + containedInIterationStatement = true; + break; + } + current = current.parent; + } + if (containedInIterationStatement) { + if (usedInFunction) { + // mark iteration statement as containing block-scoped binding captured in some function + var capturesBlockScopeBindingInLoopBody = true; + if (ts.isForStatement(container) && + ts.getAncestor(symbol.valueDeclaration, 238 /* VariableDeclarationList */).parent === container) { + var part = getPartOfForStatementContainingNode(node.parent, container); + if (part) { + var links = getNodeLinks(part); + links.flags |= 131072 /* ContainsCapturedBlockScopeBinding */; + var capturedBindings = links.capturedBlockScopeBindings || (links.capturedBlockScopeBindings = []); + ts.pushIfUnique(capturedBindings, symbol); + if (part === container.initializer) { + capturesBlockScopeBindingInLoopBody = false; // Initializer is outside of loop body + } + } + } + if (capturesBlockScopeBindingInLoopBody) { + getNodeLinks(current).flags |= 65536 /* LoopWithCapturedBlockScopedBinding */; + } + } + // mark variables that are declared in loop initializer and reassigned inside the body of ForStatement. + // if body of ForStatement will be converted to function then we'll need a extra machinery to propagate reassigned values back. + if (container.kind === 225 /* ForStatement */ && + ts.getAncestor(symbol.valueDeclaration, 238 /* VariableDeclarationList */).parent === container && + isAssignedInBodyOfForStatement(node, container)) { + getNodeLinks(symbol.valueDeclaration).flags |= 4194304 /* NeedsLoopOutParameter */; + } + // set 'declared inside loop' bit on the block-scoped binding + getNodeLinks(symbol.valueDeclaration).flags |= 524288 /* BlockScopedBindingInLoop */; + } + if (usedInFunction) { + getNodeLinks(symbol.valueDeclaration).flags |= 262144 /* CapturedBlockScopedBinding */; + } + } + function isBindingCapturedByNode(node, decl) { + var links = getNodeLinks(node); + return !!links && ts.contains(links.capturedBlockScopeBindings, getSymbolOfNode(decl)); + } + function isAssignedInBodyOfForStatement(node, container) { + // skip parenthesized nodes + var current = node; + while (current.parent.kind === 195 /* ParenthesizedExpression */) { + current = current.parent; + } + // check if node is used as LHS in some assignment expression + var isAssigned = false; + if (ts.isAssignmentTarget(current)) { + isAssigned = true; + } + else if ((current.parent.kind === 202 /* PrefixUnaryExpression */ || current.parent.kind === 203 /* PostfixUnaryExpression */)) { + var expr = current.parent; + isAssigned = expr.operator === 44 /* PlusPlusToken */ || expr.operator === 45 /* MinusMinusToken */; + } + if (!isAssigned) { + return false; + } + // at this point we know that node is the target of assignment + // now check that modification happens inside the statement part of the ForStatement + return !!ts.findAncestor(current, function (n) { return n === container ? "quit" : n === container.statement; }); + } + function captureLexicalThis(node, container) { + getNodeLinks(node).flags |= 2 /* LexicalThis */; + if (container.kind === 154 /* PropertyDeclaration */ || container.kind === 157 /* Constructor */) { + var classNode = container.parent; + getNodeLinks(classNode).flags |= 4 /* CaptureThis */; + } + else { + getNodeLinks(container).flags |= 4 /* CaptureThis */; + } + } + function findFirstSuperCall(n) { + if (ts.isSuperCall(n)) { + return n; + } + else if (ts.isFunctionLike(n)) { + return undefined; + } + return ts.forEachChild(n, findFirstSuperCall); + } + /** + * Return a cached result if super-statement is already found. + * Otherwise, find a super statement in a given constructor function and cache the result in the node-links of the constructor + * + * @param constructor constructor-function to look for super statement + */ + function getSuperCallInConstructor(constructor) { + var links = getNodeLinks(constructor); + // Only trying to find super-call if we haven't yet tried to find one. Once we try, we will record the result + if (links.hasSuperCall === undefined) { + links.superCall = findFirstSuperCall(constructor.body); + links.hasSuperCall = links.superCall ? true : false; + } + return links.superCall; + } + /** + * Check if the given class-declaration extends null then return true. + * Otherwise, return false + * @param classDecl a class declaration to check if it extends null + */ + function classDeclarationExtendsNull(classDecl) { + var classSymbol = getSymbolOfNode(classDecl); + var classInstanceType = getDeclaredTypeOfSymbol(classSymbol); + var baseConstructorType = getBaseConstructorTypeOfClass(classInstanceType); + return baseConstructorType === nullWideningType; + } + function checkThisBeforeSuper(node, container, diagnosticMessage) { + var containingClassDecl = container.parent; + var baseTypeNode = ts.getEffectiveBaseTypeNode(containingClassDecl); + // If a containing class does not have extends clause or the class extends null + // skip checking whether super statement is called before "this" accessing. + if (baseTypeNode && !classDeclarationExtendsNull(containingClassDecl)) { + var superCall = getSuperCallInConstructor(container); + // We should give an error in the following cases: + // - No super-call + // - "this" is accessing before super-call. + // i.e super(this) + // this.x; super(); + // We want to make sure that super-call is done before accessing "this" so that + // "this" is not accessed as a parameter of the super-call. + if (!superCall || superCall.end > node.pos) { + // In ES6, super inside constructor of class-declaration has to precede "this" accessing + error(node, diagnosticMessage); + } + } + } + function checkThisExpression(node) { + // Stop at the first arrow function so that we can + // tell whether 'this' needs to be captured. + var container = ts.getThisContainer(node, /* includeArrowFunctions */ true); + var capturedByArrowFunction = false; + if (container.kind === 157 /* Constructor */) { + checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class); + } + // Now skip arrow functions to get the "real" owner of 'this'. + if (container.kind === 197 /* ArrowFunction */) { + container = ts.getThisContainer(container, /* includeArrowFunctions */ false); + capturedByArrowFunction = true; + } + switch (container.kind) { + case 244 /* ModuleDeclaration */: + error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_module_or_namespace_body); + // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks + break; + case 243 /* EnumDeclaration */: + error(node, ts.Diagnostics.this_cannot_be_referenced_in_current_location); + // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks + break; + case 157 /* Constructor */: + if (isInConstructorArgumentInitializer(node, container)) { + error(node, ts.Diagnostics.this_cannot_be_referenced_in_constructor_arguments); + // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks + } + break; + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + if (ts.hasModifier(container, 32 /* Static */)) { + error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_static_property_initializer); + // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks + } + break; + case 149 /* ComputedPropertyName */: + error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_computed_property_name); + break; + } + // When targeting es6, mark that we'll need to capture `this` in its lexically bound scope. + if (capturedByArrowFunction && languageVersion < 2 /* ES2015 */) { + captureLexicalThis(node, container); + } + var type = tryGetThisTypeAt(node, container); + if (!type && noImplicitThis) { + // With noImplicitThis, functions may not reference 'this' if it has type 'any' + var diag = error(node, capturedByArrowFunction && container.kind === 279 /* SourceFile */ ? + ts.Diagnostics.The_containing_arrow_function_captures_the_global_value_of_this_which_implicitly_has_type_any : + ts.Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation); + if (!ts.isSourceFile(container)) { + var outsideThis = tryGetThisTypeAt(container); + if (outsideThis) { + addRelatedInfo(diag, ts.createDiagnosticForNode(container, ts.Diagnostics.An_outer_value_of_this_is_shadowed_by_this_container)); + } + } + } + return type || anyType; + } + function tryGetThisTypeAt(node, container) { + if (container === void 0) { container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); } + var isInJS = ts.isInJSFile(node); + if (ts.isFunctionLike(container) && + (!isInParameterInitializerBeforeContainingFunction(node) || ts.getThisParameter(container))) { + // Note: a parameter initializer should refer to class-this unless function-this is explicitly annotated. + // If this is a function in a JS file, it might be a class method. + var className = getClassNameFromPrototypeMethod(container); + if (isInJS && className) { + var classSymbol = checkExpression(className).symbol; + if (classSymbol && classSymbol.members && (classSymbol.flags & 16 /* Function */)) { + var classType = getJSClassType(classSymbol); + if (classType) { + return getFlowTypeOfReference(node, classType); + } + } + } + // Check if it's a constructor definition, can be either a variable decl or function decl + // i.e. + // * /** @constructor */ function [name]() { ... } + // * /** @constructor */ var x = function() { ... } + else if (isInJS && + (container.kind === 196 /* FunctionExpression */ || container.kind === 239 /* FunctionDeclaration */) && + ts.getJSDocClassTag(container)) { + var classType = getJSClassType(container.symbol); + if (classType) { + return getFlowTypeOfReference(node, classType); + } + } + var thisType = getThisTypeOfDeclaration(container) || getContextualThisParameterType(container); + if (thisType) { + return getFlowTypeOfReference(node, thisType); + } + } + if (ts.isClassLike(container.parent)) { + var symbol = getSymbolOfNode(container.parent); + var type = ts.hasModifier(container, 32 /* Static */) ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol).thisType; + return getFlowTypeOfReference(node, type); + } + if (isInJS) { + var type = getTypeForThisExpressionFromJSDoc(container); + if (type && type !== errorType) { + return getFlowTypeOfReference(node, type); + } + } + } + function getClassNameFromPrototypeMethod(container) { + // Check if it's the RHS of a x.prototype.y = function [name]() { .... } + if (container.kind === 196 /* FunctionExpression */ && + ts.isBinaryExpression(container.parent) && + ts.getAssignmentDeclarationKind(container.parent) === 3 /* PrototypeProperty */) { + // Get the 'x' of 'x.prototype.y = container' + return container.parent // x.prototype.y = container + .left // x.prototype.y + .expression // x.prototype + .expression; // x + } + // x.prototype = { method() { } } + else if (container.kind === 156 /* MethodDeclaration */ && + container.parent.kind === 188 /* ObjectLiteralExpression */ && + ts.isBinaryExpression(container.parent.parent) && + ts.getAssignmentDeclarationKind(container.parent.parent) === 6 /* Prototype */) { + return container.parent.parent.left.expression; + } + // x.prototype = { method: function() { } } + else if (container.kind === 196 /* FunctionExpression */ && + container.parent.kind === 275 /* PropertyAssignment */ && + container.parent.parent.kind === 188 /* ObjectLiteralExpression */ && + ts.isBinaryExpression(container.parent.parent.parent) && + ts.getAssignmentDeclarationKind(container.parent.parent.parent) === 6 /* Prototype */) { + return container.parent.parent.parent.left.expression; + } + // Object.defineProperty(x, "method", { value: function() { } }); + // Object.defineProperty(x, "method", { set: (x: () => void) => void }); + // Object.defineProperty(x, "method", { get: () => function() { }) }); + else if (container.kind === 196 /* FunctionExpression */ && + ts.isPropertyAssignment(container.parent) && + ts.isIdentifier(container.parent.name) && + (container.parent.name.escapedText === "value" || container.parent.name.escapedText === "get" || container.parent.name.escapedText === "set") && + ts.isObjectLiteralExpression(container.parent.parent) && + ts.isCallExpression(container.parent.parent.parent) && + container.parent.parent.parent.arguments[2] === container.parent.parent && + ts.getAssignmentDeclarationKind(container.parent.parent.parent) === 9 /* ObjectDefinePrototypeProperty */) { + return container.parent.parent.parent.arguments[0].expression; + } + // Object.defineProperty(x, "method", { value() { } }); + // Object.defineProperty(x, "method", { set(x: () => void) {} }); + // Object.defineProperty(x, "method", { get() { return () => {} } }); + else if (ts.isMethodDeclaration(container) && + ts.isIdentifier(container.name) && + (container.name.escapedText === "value" || container.name.escapedText === "get" || container.name.escapedText === "set") && + ts.isObjectLiteralExpression(container.parent) && + ts.isCallExpression(container.parent.parent) && + container.parent.parent.arguments[2] === container.parent && + ts.getAssignmentDeclarationKind(container.parent.parent) === 9 /* ObjectDefinePrototypeProperty */) { + return container.parent.parent.arguments[0].expression; + } + } + function getTypeForThisExpressionFromJSDoc(node) { + var jsdocType = ts.getJSDocType(node); + if (jsdocType && jsdocType.kind === 289 /* JSDocFunctionType */) { + var jsDocFunctionType = jsdocType; + if (jsDocFunctionType.parameters.length > 0 && + jsDocFunctionType.parameters[0].name && + jsDocFunctionType.parameters[0].name.escapedText === "this" /* This */) { + return getTypeFromTypeNode(jsDocFunctionType.parameters[0].type); + } + } + var thisTag = ts.getJSDocThisTag(node); + if (thisTag && thisTag.typeExpression) { + return getTypeFromTypeNode(thisTag.typeExpression); + } + } + function isInConstructorArgumentInitializer(node, constructorDecl) { + return !!ts.findAncestor(node, function (n) { return n === constructorDecl ? "quit" : n.kind === 151 /* Parameter */; }); + } + function checkSuperExpression(node) { + var isCallExpression = node.parent.kind === 191 /* CallExpression */ && node.parent.expression === node; + var container = ts.getSuperContainer(node, /*stopOnFunctions*/ true); + var needToCaptureLexicalThis = false; + // adjust the container reference in case if super is used inside arrow functions with arbitrarily deep nesting + if (!isCallExpression) { + while (container && container.kind === 197 /* ArrowFunction */) { + container = ts.getSuperContainer(container, /*stopOnFunctions*/ true); + needToCaptureLexicalThis = languageVersion < 2 /* ES2015 */; + } + } + var canUseSuperExpression = isLegalUsageOfSuperExpression(container); + var nodeCheckFlag = 0; + if (!canUseSuperExpression) { + // issue more specific error if super is used in computed property name + // class A { foo() { return "1" }} + // class B { + // [super.foo()]() {} + // } + var current = ts.findAncestor(node, function (n) { return n === container ? "quit" : n.kind === 149 /* ComputedPropertyName */; }); + if (current && current.kind === 149 /* ComputedPropertyName */) { + error(node, ts.Diagnostics.super_cannot_be_referenced_in_a_computed_property_name); + } + else if (isCallExpression) { + error(node, ts.Diagnostics.Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors); + } + else if (!container || !container.parent || !(ts.isClassLike(container.parent) || container.parent.kind === 188 /* ObjectLiteralExpression */)) { + error(node, ts.Diagnostics.super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions); + } + else { + error(node, ts.Diagnostics.super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_derived_class); + } + return errorType; + } + if (!isCallExpression && container.kind === 157 /* Constructor */) { + checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class); + } + if (ts.hasModifier(container, 32 /* Static */) || isCallExpression) { + nodeCheckFlag = 512 /* SuperStatic */; + } + else { + nodeCheckFlag = 256 /* SuperInstance */; + } + getNodeLinks(node).flags |= nodeCheckFlag; + // Due to how we emit async functions, we need to specialize the emit for an async method that contains a `super` reference. + // This is due to the fact that we emit the body of an async function inside of a generator function. As generator + // functions cannot reference `super`, we emit a helper inside of the method body, but outside of the generator. This helper + // uses an arrow function, which is permitted to reference `super`. + // + // There are two primary ways we can access `super` from within an async method. The first is getting the value of a property + // or indexed access on super, either as part of a right-hand-side expression or call expression. The second is when setting the value + // of a property or indexed access, either as part of an assignment expression or destructuring assignment. + // + // The simplest case is reading a value, in which case we will emit something like the following: + // + // // ts + // ... + // async asyncMethod() { + // let x = await super.asyncMethod(); + // return x; + // } + // ... + // + // // js + // ... + // asyncMethod() { + // const _super = Object.create(null, { + // asyncMethod: { get: () => super.asyncMethod }, + // }); + // return __awaiter(this, arguments, Promise, function *() { + // let x = yield _super.asyncMethod.call(this); + // return x; + // }); + // } + // ... + // + // The more complex case is when we wish to assign a value, especially as part of a destructuring assignment. As both cases + // are legal in ES6, but also likely less frequent, we only emit setters if there is an assignment: + // + // // ts + // ... + // async asyncMethod(ar: Promise) { + // [super.a, super.b] = await ar; + // } + // ... + // + // // js + // ... + // asyncMethod(ar) { + // const _super = Object.create(null, { + // a: { get: () => super.a, set: (v) => super.a = v }, + // b: { get: () => super.b, set: (v) => super.b = v } + // }; + // return __awaiter(this, arguments, Promise, function *() { + // [_super.a, _super.b] = yield ar; + // }); + // } + // ... + // + // Creating an object that has getter and setters instead of just an accessor function is required for destructuring assignments + // as a call expression cannot be used as the target of a destructuring assignment while a property access can. + // + // For element access expressions (`super[x]`), we emit a generic helper that forwards the element access in both situations. + if (container.kind === 156 /* MethodDeclaration */ && ts.hasModifier(container, 256 /* Async */)) { + if (ts.isSuperProperty(node.parent) && ts.isAssignmentTarget(node.parent)) { + getNodeLinks(container).flags |= 4096 /* AsyncMethodWithSuperBinding */; + } + else { + getNodeLinks(container).flags |= 2048 /* AsyncMethodWithSuper */; + } + } + if (needToCaptureLexicalThis) { + // call expressions are allowed only in constructors so they should always capture correct 'this' + // super property access expressions can also appear in arrow functions - + // in this case they should also use correct lexical this + captureLexicalThis(node.parent, container); + } + if (container.parent.kind === 188 /* ObjectLiteralExpression */) { + if (languageVersion < 2 /* ES2015 */) { + error(node, ts.Diagnostics.super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_higher); + return errorType; + } + else { + // for object literal assume that type of 'super' is 'any' + return anyType; + } + } + // at this point the only legal case for parent is ClassLikeDeclaration + var classLikeDeclaration = container.parent; + if (!ts.getEffectiveBaseTypeNode(classLikeDeclaration)) { + error(node, ts.Diagnostics.super_can_only_be_referenced_in_a_derived_class); + return errorType; + } + var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(classLikeDeclaration)); + var baseClassType = classType && getBaseTypes(classType)[0]; + if (!baseClassType) { + return errorType; + } + if (container.kind === 157 /* Constructor */ && isInConstructorArgumentInitializer(node, container)) { + // issue custom error message for super property access in constructor arguments (to be aligned with old compiler) + error(node, ts.Diagnostics.super_cannot_be_referenced_in_constructor_arguments); + return errorType; + } + return nodeCheckFlag === 512 /* SuperStatic */ + ? getBaseConstructorTypeOfClass(classType) + : getTypeWithThisArgument(baseClassType, classType.thisType); + function isLegalUsageOfSuperExpression(container) { + if (!container) { + return false; + } + if (isCallExpression) { + // TS 1.0 SPEC (April 2014): 4.8.1 + // Super calls are only permitted in constructors of derived classes + return container.kind === 157 /* Constructor */; + } + else { + // TS 1.0 SPEC (April 2014) + // 'super' property access is allowed + // - In a constructor, instance member function, instance member accessor, or instance member variable initializer where this references a derived class instance + // - In a static member function or static member accessor + // topmost container must be something that is directly nested in the class declaration\object literal expression + if (ts.isClassLike(container.parent) || container.parent.kind === 188 /* ObjectLiteralExpression */) { + if (ts.hasModifier(container, 32 /* Static */)) { + return container.kind === 156 /* MethodDeclaration */ || + container.kind === 155 /* MethodSignature */ || + container.kind === 158 /* GetAccessor */ || + container.kind === 159 /* SetAccessor */; + } + else { + return container.kind === 156 /* MethodDeclaration */ || + container.kind === 155 /* MethodSignature */ || + container.kind === 158 /* GetAccessor */ || + container.kind === 159 /* SetAccessor */ || + container.kind === 154 /* PropertyDeclaration */ || + container.kind === 153 /* PropertySignature */ || + container.kind === 157 /* Constructor */; + } + } + } + return false; + } + } + function getContainingObjectLiteral(func) { + return (func.kind === 156 /* MethodDeclaration */ || + func.kind === 158 /* GetAccessor */ || + func.kind === 159 /* SetAccessor */) && func.parent.kind === 188 /* ObjectLiteralExpression */ ? func.parent : + func.kind === 196 /* FunctionExpression */ && func.parent.kind === 275 /* PropertyAssignment */ ? func.parent.parent : + undefined; + } + function getThisTypeArgument(type) { + return ts.getObjectFlags(type) & 4 /* Reference */ && type.target === globalThisType ? type.typeArguments[0] : undefined; + } + function getThisTypeFromContextualType(type) { + return mapType(type, function (t) { + return t.flags & 2097152 /* Intersection */ ? ts.forEach(t.types, getThisTypeArgument) : getThisTypeArgument(t); + }); + } + function getContextualThisParameterType(func) { + if (func.kind === 197 /* ArrowFunction */) { + return undefined; + } + if (isContextSensitiveFunctionOrObjectLiteralMethod(func)) { + var contextualSignature = getContextualSignature(func); + if (contextualSignature) { + var thisParameter = contextualSignature.thisParameter; + if (thisParameter) { + return getTypeOfSymbol(thisParameter); + } + } + } + var inJs = ts.isInJSFile(func); + if (noImplicitThis || inJs) { + var containingLiteral = getContainingObjectLiteral(func); + if (containingLiteral) { + // We have an object literal method. Check if the containing object literal has a contextual type + // that includes a ThisType. If so, T is the contextual type for 'this'. We continue looking in + // any directly enclosing object literals. + var contextualType = getApparentTypeOfContextualType(containingLiteral); + var literal = containingLiteral; + var type = contextualType; + while (type) { + var thisType = getThisTypeFromContextualType(type); + if (thisType) { + return instantiateType(thisType, getContextualMapper(containingLiteral)); + } + if (literal.parent.kind !== 275 /* PropertyAssignment */) { + break; + } + literal = literal.parent.parent; + type = getApparentTypeOfContextualType(literal); + } + // There was no contextual ThisType for the containing object literal, so the contextual type + // for 'this' is the non-null form of the contextual type for the containing object literal or + // the type of the object literal itself. + return contextualType ? getNonNullableType(contextualType) : checkExpressionCached(containingLiteral); + } + // In an assignment of the form 'obj.xxx = function(...)' or 'obj[xxx] = function(...)', the + // contextual type for 'this' is 'obj'. + var parent = func.parent; + if (parent.kind === 204 /* BinaryExpression */ && parent.operatorToken.kind === 59 /* EqualsToken */) { + var target = parent.left; + if (target.kind === 189 /* PropertyAccessExpression */ || target.kind === 190 /* ElementAccessExpression */) { + var expression = target.expression; + // Don't contextually type `this` as `exports` in `exports.Point = function(x, y) { this.x = x; this.y = y; }` + if (inJs && ts.isIdentifier(expression)) { + var sourceFile = ts.getSourceFileOfNode(parent); + if (sourceFile.commonJsModuleIndicator && getResolvedSymbol(expression) === sourceFile.symbol) { + return undefined; + } + } + return checkExpressionCached(expression); + } + } + } + return undefined; + } + // Return contextual type of parameter or undefined if no contextual type is available + function getContextuallyTypedParameterType(parameter) { + var func = parameter.parent; + if (!isContextSensitiveFunctionOrObjectLiteralMethod(func)) { + return undefined; + } + var iife = ts.getImmediatelyInvokedFunctionExpression(func); + if (iife && iife.arguments) { + var args = getEffectiveCallArguments(iife); + var indexOfParameter = func.parameters.indexOf(parameter); + if (parameter.dotDotDotToken) { + return getSpreadArgumentType(args, indexOfParameter, args.length, anyType, /*context*/ undefined); + } + var links = getNodeLinks(iife); + var cached = links.resolvedSignature; + links.resolvedSignature = anySignature; + var type = indexOfParameter < args.length ? + getWidenedLiteralType(checkExpression(args[indexOfParameter])) : + parameter.initializer ? undefined : undefinedWideningType; + links.resolvedSignature = cached; + return type; + } + var contextualSignature = getContextualSignature(func); + if (contextualSignature) { + var index = func.parameters.indexOf(parameter) - (ts.getThisParameter(func) ? 1 : 0); + return parameter.dotDotDotToken && ts.lastOrUndefined(func.parameters) === parameter ? + getRestTypeAtPosition(contextualSignature, index) : + tryGetTypeAtPosition(contextualSignature, index); + } + } + // In a variable, parameter or property declaration with a type annotation, + // the contextual type of an initializer expression is the type of the variable, parameter or property. + // Otherwise, in a parameter declaration of a contextually typed function expression, + // the contextual type of an initializer expression is the contextual type of the parameter. + // Otherwise, in a variable or parameter declaration with a binding pattern name, + // the contextual type of an initializer expression is the type implied by the binding pattern. + // Otherwise, in a binding pattern inside a variable or parameter declaration, + // the contextual type of an initializer expression is the type annotation of the containing declaration, if present. + function getContextualTypeForInitializerExpression(node) { + var declaration = node.parent; + if (ts.hasInitializer(declaration) && node === declaration.initializer) { + var typeNode = ts.getEffectiveTypeAnnotationNode(declaration); + if (typeNode) { + return getTypeFromTypeNode(typeNode); + } + if (declaration.kind === 151 /* Parameter */) { + var type = getContextuallyTypedParameterType(declaration); + if (type) { + return type; + } + } + if (ts.isBindingPattern(declaration.name)) { + return getTypeFromBindingPattern(declaration.name, /*includePatternInType*/ true, /*reportErrors*/ false); + } + if (ts.isBindingPattern(declaration.parent)) { + var parentDeclaration = declaration.parent.parent; + var name = declaration.propertyName || declaration.name; + if (parentDeclaration.kind !== 186 /* BindingElement */) { + var parentTypeNode = ts.getEffectiveTypeAnnotationNode(parentDeclaration); + if (parentTypeNode && !ts.isBindingPattern(name)) { + var text = ts.getTextOfPropertyName(name); + if (text) { + return getTypeOfPropertyOfType(getTypeFromTypeNode(parentTypeNode), text); + } + } + } + } + } + return undefined; + } + function getContextualTypeForReturnExpression(node) { + var func = ts.getContainingFunction(node); + if (func) { + var functionFlags = ts.getFunctionFlags(func); + if (functionFlags & 1 /* Generator */) { // AsyncGenerator function or Generator function + return undefined; + } + var contextualReturnType = getContextualReturnType(func); + if (contextualReturnType) { + if (functionFlags & 2 /* Async */) { // Async function + var contextualAwaitedType = getAwaitedTypeOfPromise(contextualReturnType); + return contextualAwaitedType && getUnionType([contextualAwaitedType, createPromiseLikeType(contextualAwaitedType)]); + } + return contextualReturnType; // Regular function + } + } + return undefined; + } + function getContextualTypeForAwaitOperand(node) { + var contextualType = getContextualType(node); + if (contextualType) { + var contextualAwaitedType = getAwaitedType(contextualType); + return contextualAwaitedType && getUnionType([contextualAwaitedType, createPromiseLikeType(contextualAwaitedType)]); + } + return undefined; + } + function getContextualTypeForYieldOperand(node) { + var func = ts.getContainingFunction(node); + if (func) { + var functionFlags = ts.getFunctionFlags(func); + var contextualReturnType = getContextualReturnType(func); + if (contextualReturnType) { + return node.asteriskToken + ? contextualReturnType + : getIteratedTypeOfGenerator(contextualReturnType, (functionFlags & 2 /* Async */) !== 0); + } + } + return undefined; + } + function isInParameterInitializerBeforeContainingFunction(node) { + var inBindingInitializer = false; + while (node.parent && !ts.isFunctionLike(node.parent)) { + if (ts.isParameter(node.parent) && (inBindingInitializer || node.parent.initializer === node)) { + return true; + } + if (ts.isBindingElement(node.parent) && node.parent.initializer === node) { + inBindingInitializer = true; + } + node = node.parent; + } + return false; + } + function getContextualReturnType(functionDecl) { + // If the containing function has a return type annotation, is a constructor, or is a get accessor whose + // corresponding set accessor has a type annotation, return statements in the function are contextually typed + var returnType = getReturnTypeFromAnnotation(functionDecl); + if (returnType) { + return returnType; + } + // Otherwise, if the containing function is contextually typed by a function type with exactly one call signature + // and that call signature is non-generic, return statements are contextually typed by the return type of the signature + var signature = getContextualSignatureForFunctionLikeDeclaration(functionDecl); + if (signature && !isResolvingReturnTypeOfSignature(signature)) { + return getReturnTypeOfSignature(signature); + } + return undefined; + } + // In a typed function call, an argument or substitution expression is contextually typed by the type of the corresponding parameter. + function getContextualTypeForArgument(callTarget, arg) { + var args = getEffectiveCallArguments(callTarget); + var argIndex = args.indexOf(arg); // -1 for e.g. the expression of a CallExpression, or the tag of a TaggedTemplateExpression + return argIndex === -1 ? undefined : getContextualTypeForArgumentAtIndex(callTarget, argIndex); + } + function getContextualTypeForArgumentAtIndex(callTarget, argIndex) { + // If we're already in the process of resolving the given signature, don't resolve again as + // that could cause infinite recursion. Instead, return anySignature. + var signature = getNodeLinks(callTarget).resolvedSignature === resolvingSignature ? resolvingSignature : getResolvedSignature(callTarget); + if (ts.isJsxOpeningLikeElement(callTarget) && argIndex === 0) { + return getEffectiveFirstArgumentForJsxSignature(signature, callTarget); + } + return getTypeAtPosition(signature, argIndex); + } + function getContextualTypeForSubstitutionExpression(template, substitutionExpression) { + if (template.parent.kind === 193 /* TaggedTemplateExpression */) { + return getContextualTypeForArgument(template.parent, substitutionExpression); + } + return undefined; + } + function getContextualTypeForBinaryOperand(node) { + var binaryExpression = node.parent; + var left = binaryExpression.left, operatorToken = binaryExpression.operatorToken, right = binaryExpression.right; + switch (operatorToken.kind) { + case 59 /* EqualsToken */: + if (node !== right) { + return undefined; + } + var contextSensitive = getIsContextSensitiveAssignmentOrContextType(binaryExpression); + if (!contextSensitive) { + return undefined; + } + return contextSensitive === true ? getTypeOfExpression(left) : contextSensitive; + case 55 /* BarBarToken */: + // When an || expression has a contextual type, the operands are contextually typed by that type. When an || + // expression has no contextual type, the right operand is contextually typed by the type of the left operand, + // except for the special case of Javascript declarations of the form `namespace.prop = namespace.prop || {}` + var type = getContextualType(binaryExpression); + return !type && node === right && !ts.isDefaultedExpandoInitializer(binaryExpression) ? + getTypeOfExpression(left) : type; + case 54 /* AmpersandAmpersandToken */: + case 27 /* CommaToken */: + return node === right ? getContextualType(binaryExpression) : undefined; + default: + return undefined; + } + } + // In an assignment expression, the right operand is contextually typed by the type of the left operand. + // Don't do this for assignment declarations unless there is a type tag on the assignment, to avoid circularity from checking the right operand. + function getIsContextSensitiveAssignmentOrContextType(binaryExpression) { + var kind = ts.getAssignmentDeclarationKind(binaryExpression); + switch (kind) { + case 0 /* None */: + return true; + case 5 /* Property */: + case 1 /* ExportsProperty */: + case 6 /* Prototype */: + case 3 /* PrototypeProperty */: + // If `binaryExpression.left` was assigned a symbol, then this is a new declaration; otherwise it is an assignment to an existing declaration. + // See `bindStaticPropertyAssignment` in `binder.ts`. + if (!binaryExpression.left.symbol) { + return true; + } + else { + var decl = binaryExpression.left.symbol.valueDeclaration; + if (!decl) { + return false; + } + var lhs = binaryExpression.left; + var overallAnnotation = ts.getEffectiveTypeAnnotationNode(decl); + if (overallAnnotation) { + return getTypeFromTypeNode(overallAnnotation); + } + else if (ts.isIdentifier(lhs.expression)) { + var id = lhs.expression; + var parentSymbol = resolveName(id, id.escapedText, 67220415 /* Value */, undefined, id.escapedText, /*isUse*/ true); + if (parentSymbol) { + var annotated = ts.getEffectiveTypeAnnotationNode(parentSymbol.valueDeclaration); + if (annotated) { + var type = getTypeOfPropertyOfContextualType(getTypeFromTypeNode(annotated), lhs.name.escapedText); + return type || false; + } + return false; + } + } + return !ts.isInJSFile(decl); + } + case 2 /* ModuleExports */: + case 4 /* ThisProperty */: + if (!binaryExpression.symbol) + return true; + if (binaryExpression.symbol.valueDeclaration) { + var annotated = ts.getEffectiveTypeAnnotationNode(binaryExpression.symbol.valueDeclaration); + if (annotated) { + var type = getTypeFromTypeNode(annotated); + if (type) { + return type; + } + } + } + if (kind === 2 /* ModuleExports */) + return false; + var thisAccess = binaryExpression.left; + if (!ts.isObjectLiteralMethod(ts.getThisContainer(thisAccess.expression, /*includeArrowFunctions*/ false))) { + return false; + } + var thisType = checkThisExpression(thisAccess.expression); + return thisType && getTypeOfPropertyOfContextualType(thisType, thisAccess.name.escapedText) || false; + case 7 /* ObjectDefinePropertyValue */: + case 8 /* ObjectDefinePropertyExports */: + case 9 /* ObjectDefinePrototypeProperty */: + return ts.Debug.fail("Does not apply"); + default: + return ts.Debug.assertNever(kind); + } + } + function getTypeOfPropertyOfContextualType(type, name) { + return mapType(type, function (t) { + if (t.flags & 3670016 /* StructuredType */) { + var prop = getPropertyOfType(t, name); + if (prop) { + return getTypeOfSymbol(prop); + } + if (isTupleType(t)) { + var restType = getRestTypeOfTupleType(t); + if (restType && isNumericLiteralName(name) && +name >= 0) { + return restType; + } + } + return isNumericLiteralName(name) && getIndexTypeOfContextualType(t, 1 /* Number */) || + getIndexTypeOfContextualType(t, 0 /* String */); + } + return undefined; + }, /*noReductions*/ true); + } + function getIndexTypeOfContextualType(type, kind) { + return mapType(type, function (t) { return getIndexTypeOfStructuredType(t, kind); }, /*noReductions*/ true); + } + // In an object literal contextually typed by a type T, the contextual type of a property assignment is the type of + // the matching property in T, if one exists. Otherwise, it is the type of the numeric index signature in T, if one + // exists. Otherwise, it is the type of the string index signature in T, if one exists. + function getContextualTypeForObjectLiteralMethod(node) { + ts.Debug.assert(ts.isObjectLiteralMethod(node)); + if (node.flags & 8388608 /* InWithStatement */) { + // We cannot answer semantic questions within a with block, do not proceed any further + return undefined; + } + return getContextualTypeForObjectLiteralElement(node); + } + function getContextualTypeForObjectLiteralElement(element) { + var objectLiteral = element.parent; + var type = getApparentTypeOfContextualType(objectLiteral); + if (type) { + if (!hasNonBindableDynamicName(element)) { + // For a (non-symbol) computed property, there is no reason to look up the name + // in the type. It will just be "__computed", which does not appear in any + // SymbolTable. + var symbolName_2 = getSymbolOfNode(element).escapedName; + var propertyType = getTypeOfPropertyOfContextualType(type, symbolName_2); + if (propertyType) { + return propertyType; + } + } + return isNumericName(element.name) && getIndexTypeOfContextualType(type, 1 /* Number */) || + getIndexTypeOfContextualType(type, 0 /* String */); + } + return undefined; + } + // In an array literal contextually typed by a type T, the contextual type of an element expression at index N is + // the type of the property with the numeric name N in T, if one exists. Otherwise, if T has a numeric index signature, + // it is the type of the numeric index signature in T. Otherwise, in ES6 and higher, the contextual type is the iterated + // type of T. + function getContextualTypeForElementExpression(arrayContextualType, index) { + return arrayContextualType && (getTypeOfPropertyOfContextualType(arrayContextualType, "" + index) + || getIteratedTypeOrElementType(arrayContextualType, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterables*/ false, /*checkAssignability*/ false)); + } + // In a contextually typed conditional expression, the true/false expressions are contextually typed by the same type. + function getContextualTypeForConditionalOperand(node) { + var conditional = node.parent; + return node === conditional.whenTrue || node === conditional.whenFalse ? getContextualType(conditional) : undefined; + } + function getContextualTypeForChildJsxExpression(node) { + var attributesType = getApparentTypeOfContextualType(node.openingElement.tagName); + // JSX expression is in children of JSX Element, we will look for an "children" atttribute (we get the name from JSX.ElementAttributesProperty) + var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(node)); + return attributesType && !isTypeAny(attributesType) && jsxChildrenPropertyName && jsxChildrenPropertyName !== "" ? getTypeOfPropertyOfContextualType(attributesType, jsxChildrenPropertyName) : undefined; + } + function getContextualTypeForJsxExpression(node) { + var exprParent = node.parent; + return ts.isJsxAttributeLike(exprParent) + ? getContextualType(node) + : ts.isJsxElement(exprParent) + ? getContextualTypeForChildJsxExpression(exprParent) + : undefined; + } + function getContextualTypeForJsxAttribute(attribute) { + // When we trying to resolve JsxOpeningLikeElement as a stateless function element, we will already give its attributes a contextual type + // which is a type of the parameter of the signature we are trying out. + // If there is no contextual type (e.g. we are trying to resolve stateful component), get attributes type from resolving element's tagName + if (ts.isJsxAttribute(attribute)) { + var attributesType = getApparentTypeOfContextualType(attribute.parent); + if (!attributesType || isTypeAny(attributesType)) { + return undefined; + } + return getTypeOfPropertyOfContextualType(attributesType, attribute.name.escapedText); + } + else { + return getContextualType(attribute.parent); + } + } + // Return true if the given expression is possibly a discriminant value. We limit the kinds of + // expressions we check to those that don't depend on their contextual type in order not to cause + // recursive (and possibly infinite) invocations of getContextualType. + function isPossiblyDiscriminantValue(node) { + switch (node.kind) { + case 10 /* StringLiteral */: + case 8 /* NumericLiteral */: + case 9 /* BigIntLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: + case 102 /* TrueKeyword */: + case 87 /* FalseKeyword */: + case 96 /* NullKeyword */: + case 72 /* Identifier */: + case 141 /* UndefinedKeyword */: + return true; + case 189 /* PropertyAccessExpression */: + case 195 /* ParenthesizedExpression */: + return isPossiblyDiscriminantValue(node.expression); + case 270 /* JsxExpression */: + return !node.expression || isPossiblyDiscriminantValue(node.expression); + } + return false; + } + function discriminateContextualTypeByObjectMembers(node, contextualType) { + return discriminateTypeByDiscriminableItems(contextualType, ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 275 /* PropertyAssignment */ && isPossiblyDiscriminantValue(p.initializer) && isDiscriminantProperty(contextualType, p.symbol.escapedName); }), function (prop) { return [function () { return checkExpression(prop.initializer); }, prop.symbol.escapedName]; }), isTypeAssignableTo, contextualType); + } + function discriminateContextualTypeByJSXAttributes(node, contextualType) { + return discriminateTypeByDiscriminableItems(contextualType, ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 267 /* JsxAttribute */ && isDiscriminantProperty(contextualType, p.symbol.escapedName) && (!p.initializer || isPossiblyDiscriminantValue(p.initializer)); }), function (prop) { return [!prop.initializer ? (function () { return trueType; }) : (function () { return checkExpression(prop.initializer); }), prop.symbol.escapedName]; }), isTypeAssignableTo, contextualType); + } + // Return the contextual type for a given expression node. During overload resolution, a contextual type may temporarily + // be "pushed" onto a node using the contextualType property. + function getApparentTypeOfContextualType(node) { + var contextualType = getContextualType(node); + contextualType = contextualType && mapType(contextualType, getApparentType); + if (contextualType && contextualType.flags & 1048576 /* Union */) { + if (ts.isObjectLiteralExpression(node)) { + return discriminateContextualTypeByObjectMembers(node, contextualType); + } + else if (ts.isJsxAttributes(node)) { + return discriminateContextualTypeByJSXAttributes(node, contextualType); + } + } + return contextualType; + } + /** + * Woah! Do you really want to use this function? + * + * Unless you're trying to get the *non-apparent* type for a + * value-literal type or you're authoring relevant portions of this algorithm, + * you probably meant to use 'getApparentTypeOfContextualType'. + * Otherwise this may not be very useful. + * + * In cases where you *are* working on this function, you should understand + * when it is appropriate to use 'getContextualType' and 'getApparentTypeOfContextualType'. + * + * - Use 'getContextualType' when you are simply going to propagate the result to the expression. + * - Use 'getApparentTypeOfContextualType' when you're going to need the members of the type. + * + * @param node the expression whose contextual type will be returned. + * @returns the contextual type of an expression. + */ + function getContextualType(node) { + if (node.flags & 8388608 /* InWithStatement */) { + // We cannot answer semantic questions within a with block, do not proceed any further + return undefined; + } + if (node.contextualType) { + return node.contextualType; + } + var parent = node.parent; + switch (parent.kind) { + case 237 /* VariableDeclaration */: + case 151 /* Parameter */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 186 /* BindingElement */: + return getContextualTypeForInitializerExpression(node); + case 197 /* ArrowFunction */: + case 230 /* ReturnStatement */: + return getContextualTypeForReturnExpression(node); + case 207 /* YieldExpression */: + return getContextualTypeForYieldOperand(parent); + case 201 /* AwaitExpression */: + return getContextualTypeForAwaitOperand(parent); + case 191 /* CallExpression */: + case 192 /* NewExpression */: + return getContextualTypeForArgument(parent, node); + case 194 /* TypeAssertionExpression */: + case 212 /* AsExpression */: + return getTypeFromTypeNode(parent.type); + case 204 /* BinaryExpression */: + return getContextualTypeForBinaryOperand(node); + case 275 /* PropertyAssignment */: + case 276 /* ShorthandPropertyAssignment */: + return getContextualTypeForObjectLiteralElement(parent); + case 277 /* SpreadAssignment */: + return getApparentTypeOfContextualType(parent.parent); + case 187 /* ArrayLiteralExpression */: { + var arrayLiteral = parent; + var type = getApparentTypeOfContextualType(arrayLiteral); + return getContextualTypeForElementExpression(type, ts.indexOfNode(arrayLiteral.elements, node)); + } + case 205 /* ConditionalExpression */: + return getContextualTypeForConditionalOperand(node); + case 216 /* TemplateSpan */: + ts.Debug.assert(parent.parent.kind === 206 /* TemplateExpression */); + return getContextualTypeForSubstitutionExpression(parent.parent, node); + case 195 /* ParenthesizedExpression */: { + // Like in `checkParenthesizedExpression`, an `/** @type {xyz} */` comment before a parenthesized expression acts as a type cast. + var tag = ts.isInJSFile(parent) ? ts.getJSDocTypeTag(parent) : undefined; + return tag ? getTypeFromTypeNode(tag.typeExpression.type) : getContextualType(parent); + } + case 270 /* JsxExpression */: + return getContextualTypeForJsxExpression(parent); + case 267 /* JsxAttribute */: + case 269 /* JsxSpreadAttribute */: + return getContextualTypeForJsxAttribute(parent); + case 262 /* JsxOpeningElement */: + case 261 /* JsxSelfClosingElement */: + return getContextualJsxElementAttributesType(parent); + } + return undefined; + } + function getContextualMapper(node) { + var ancestor = ts.findAncestor(node, function (n) { return !!n.contextualMapper; }); + return ancestor ? ancestor.contextualMapper : identityMapper; + } + function getContextualJsxElementAttributesType(node) { + if (ts.isJsxOpeningElement(node) && node.parent.contextualType) { + // Contextually applied type is moved from attributes up to the outer jsx attributes so when walking up from the children they get hit + // _However_ to hit them from the _attributes_ we must look for them here; otherwise we'll used the declared type + // (as below) instead! + return node.parent.contextualType; + } + return getContextualTypeForArgumentAtIndex(node, 0); + } + function getEffectiveFirstArgumentForJsxSignature(signature, node) { + return getJsxReferenceKind(node) !== 0 /* Component */ ? getJsxPropsTypeFromCallSignature(signature, node) : getJsxPropsTypeFromClassType(signature, node); + } + function getJsxPropsTypeFromCallSignature(sig, context) { + var propsType = getTypeOfFirstParameterOfSignatureWithFallback(sig, emptyObjectType); + propsType = getJsxManagedAttributesFromLocatedAttributes(context, getJsxNamespaceAt(context), propsType); + var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes, context); + if (intrinsicAttribs !== errorType) { + propsType = intersectTypes(intrinsicAttribs, propsType); + } + return propsType; + } + function getJsxPropsTypeForSignatureFromMember(sig, forcedLookupLocation) { + var instanceType = getReturnTypeOfSignature(sig); + return isTypeAny(instanceType) ? instanceType : getTypeOfPropertyOfType(instanceType, forcedLookupLocation); + } + function getStaticTypeOfReferencedJsxConstructor(context) { + if (isJsxIntrinsicIdentifier(context.tagName)) { + var result = getIntrinsicAttributesTypeFromJsxOpeningLikeElement(context); + var fakeSignature = createSignatureForJSXIntrinsic(context, result); + return getOrCreateTypeFromSignature(fakeSignature); + } + var tagType = checkExpressionCached(context.tagName); + if (tagType.flags & 128 /* StringLiteral */) { + var result = getIntrinsicAttributesTypeFromStringLiteralType(tagType, context); + if (!result) { + return errorType; + } + var fakeSignature = createSignatureForJSXIntrinsic(context, result); + return getOrCreateTypeFromSignature(fakeSignature); + } + return tagType; + } + function getJsxManagedAttributesFromLocatedAttributes(context, ns, attributesType) { + var managedSym = getJsxLibraryManagedAttributes(ns); + if (managedSym) { + var declaredManagedType = getDeclaredTypeOfSymbol(managedSym); + var ctorType = getStaticTypeOfReferencedJsxConstructor(context); + if (ts.length(declaredManagedType.typeParameters) >= 2) { + var args = fillMissingTypeArguments([ctorType, attributesType], declaredManagedType.typeParameters, 2, ts.isInJSFile(context)); + return createTypeReference(declaredManagedType, args); + } + else if (ts.length(declaredManagedType.aliasTypeArguments) >= 2) { + var args = fillMissingTypeArguments([ctorType, attributesType], declaredManagedType.aliasTypeArguments, 2, ts.isInJSFile(context)); + return getTypeAliasInstantiation(declaredManagedType.aliasSymbol, args); + } + } + return attributesType; + } + function getJsxPropsTypeFromClassType(sig, context) { + var ns = getJsxNamespaceAt(context); + var forcedLookupLocation = getJsxElementPropertiesName(ns); + var attributesType = forcedLookupLocation === undefined + // If there is no type ElementAttributesProperty, return the type of the first parameter of the signature, which should be the props type + ? getTypeOfFirstParameterOfSignatureWithFallback(sig, emptyObjectType) + : forcedLookupLocation === "" + // If there is no e.g. 'props' member in ElementAttributesProperty, use the element class type instead + ? getReturnTypeOfSignature(sig) + // Otherwise get the type of the property on the signature return type + : getJsxPropsTypeForSignatureFromMember(sig, forcedLookupLocation); + if (!attributesType) { + // There is no property named 'props' on this instance type + if (!!forcedLookupLocation && !!ts.length(context.attributes.properties)) { + error(context, ts.Diagnostics.JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property, ts.unescapeLeadingUnderscores(forcedLookupLocation)); + } + return emptyObjectType; + } + attributesType = getJsxManagedAttributesFromLocatedAttributes(context, ns, attributesType); + if (isTypeAny(attributesType)) { + // Props is of type 'any' or unknown + return attributesType; + } + else { + // Normal case -- add in IntrinsicClassElements and IntrinsicElements + var apparentAttributesType = attributesType; + var intrinsicClassAttribs = getJsxType(JsxNames.IntrinsicClassAttributes, context); + if (intrinsicClassAttribs !== errorType) { + var typeParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(intrinsicClassAttribs.symbol); + var hostClassType = getReturnTypeOfSignature(sig); + apparentAttributesType = intersectTypes(typeParams + ? createTypeReference(intrinsicClassAttribs, fillMissingTypeArguments([hostClassType], typeParams, getMinTypeArgumentCount(typeParams), ts.isInJSFile(context))) + : intrinsicClassAttribs, apparentAttributesType); + } + var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes, context); + if (intrinsicAttribs !== errorType) { + apparentAttributesType = intersectTypes(intrinsicAttribs, apparentAttributesType); + } + return apparentAttributesType; + } + } + // If the given type is an object or union type with a single signature, and if that signature has at + // least as many parameters as the given function, return the signature. Otherwise return undefined. + function getContextualCallSignature(type, node) { + var signatures = getSignaturesOfType(type, 0 /* Call */); + if (signatures.length === 1) { + var signature = signatures[0]; + if (!isAritySmaller(signature, node)) { + return signature; + } + } + } + /** If the contextual signature has fewer parameters than the function expression, do not use it */ + function isAritySmaller(signature, target) { + var targetParameterCount = 0; + for (; targetParameterCount < target.parameters.length; targetParameterCount++) { + var param = target.parameters[targetParameterCount]; + if (param.initializer || param.questionToken || param.dotDotDotToken || isJSDocOptionalParameter(param)) { + break; + } + } + if (target.parameters.length && ts.parameterIsThisKeyword(target.parameters[0])) { + targetParameterCount--; + } + return !hasEffectiveRestParameter(signature) && getParameterCount(signature) < targetParameterCount; + } + function isFunctionExpressionOrArrowFunction(node) { + return node.kind === 196 /* FunctionExpression */ || node.kind === 197 /* ArrowFunction */; + } + function getContextualSignatureForFunctionLikeDeclaration(node) { + // Only function expressions, arrow functions, and object literal methods are contextually typed. + return isFunctionExpressionOrArrowFunction(node) || ts.isObjectLiteralMethod(node) + ? getContextualSignature(node) + : undefined; + } + function getContextualTypeForFunctionLikeDeclaration(node) { + return ts.isObjectLiteralMethod(node) ? + getContextualTypeForObjectLiteralMethod(node) : + getApparentTypeOfContextualType(node); + } + // Return the contextual signature for a given expression node. A contextual type provides a + // contextual signature if it has a single call signature and if that call signature is non-generic. + // If the contextual type is a union type, get the signature from each type possible and if they are + // all identical ignoring their return type, the result is same signature but with return type as + // union type of return types from these signatures + function getContextualSignature(node) { + ts.Debug.assert(node.kind !== 156 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + var typeTagSignature = getSignatureOfTypeTag(node); + if (typeTagSignature) { + return typeTagSignature; + } + var type = getContextualTypeForFunctionLikeDeclaration(node); + if (!type) { + return undefined; + } + if (!(type.flags & 1048576 /* Union */)) { + return getContextualCallSignature(type, node); + } + var signatureList; + var types = type.types; + for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { + var current = types_14[_i]; + var signature = getContextualCallSignature(current, node); + if (signature) { + if (!signatureList) { + // This signature will contribute to contextual union signature + signatureList = [signature]; + } + else if (!compareSignaturesIdentical(signatureList[0], signature, /*partialMatch*/ false, /*ignoreThisTypes*/ true, /*ignoreReturnTypes*/ true, compareTypesIdentical)) { + // Signatures aren't identical, do not use + return undefined; + } + else { + // Use this signature for contextual union signature + signatureList.push(signature); + } + } + } + // Result is union of signatures collected (return type is union of return types of this signature set) + var result; + if (signatureList) { + result = cloneSignature(signatureList[0]); + result.unionSignatures = signatureList; + } + return result; + } + function checkSpreadExpression(node, checkMode) { + if (languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) { + checkExternalEmitHelpers(node, 1536 /* SpreadIncludes */); + } + var arrayOrIterableType = checkExpression(node.expression, checkMode); + return checkIteratedTypeOrElementType(arrayOrIterableType, node.expression, /*allowStringInput*/ false, /*allowAsyncIterables*/ false); + } + function hasDefaultValue(node) { + return (node.kind === 186 /* BindingElement */ && !!node.initializer) || + (node.kind === 204 /* BinaryExpression */ && node.operatorToken.kind === 59 /* EqualsToken */); + } + function checkArrayLiteral(node, checkMode, forceTuple) { + var elements = node.elements; + var elementCount = elements.length; + var hasNonEndingSpreadElement = false; + var elementTypes = []; + var inDestructuringPattern = ts.isAssignmentTarget(node); + var contextualType = getApparentTypeOfContextualType(node); + for (var index = 0; index < elementCount; index++) { + var e = elements[index]; + if (inDestructuringPattern && e.kind === 208 /* SpreadElement */) { + // Given the following situation: + // var c: {}; + // [...c] = ["", 0]; + // + // c is represented in the tree as a spread element in an array literal. + // But c really functions as a rest element, and its purpose is to provide + // a contextual type for the right hand side of the assignment. Therefore, + // instead of calling checkExpression on "...c", which will give an error + // if c is not iterable/array-like, we need to act as if we are trying to + // get the contextual element type from it. So we do something similar to + // getContextualTypeForElementExpression, which will crucially not error + // if there is no index type / iterated type. + var restArrayType = checkExpression(e.expression, checkMode, forceTuple); + var restElementType = getIndexTypeOfType(restArrayType, 1 /* Number */) || + getIteratedTypeOrElementType(restArrayType, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterables*/ false, /*checkAssignability*/ false); + if (restElementType) { + elementTypes.push(restElementType); + } + } + else { + var elementContextualType = getContextualTypeForElementExpression(contextualType, index); + var type = checkExpressionForMutableLocation(e, checkMode, elementContextualType, forceTuple); + elementTypes.push(type); + } + if (index < elementCount - 1 && e.kind === 208 /* SpreadElement */) { + hasNonEndingSpreadElement = true; + } + } + if (!hasNonEndingSpreadElement) { + var hasRestElement = elementCount > 0 && elements[elementCount - 1].kind === 208 /* SpreadElement */; + var minLength = elementCount - (hasRestElement ? 1 : 0); + // If array literal is actually a destructuring pattern, mark it as an implied type. We do this such + // that we get the same behavior for "var [x, y] = []" and "[x, y] = []". + var tupleResult = void 0; + if (inDestructuringPattern && minLength > 0) { + var type = cloneTypeReference(createTupleType(elementTypes, minLength, hasRestElement)); + type.pattern = node; + return type; + } + else if (tupleResult = getArrayLiteralTupleTypeIfApplicable(elementTypes, contextualType, hasRestElement, elementCount)) { + return tupleResult; + } + else if (forceTuple) { + return createTupleType(elementTypes, minLength, hasRestElement); + } + } + return getArrayLiteralType(elementTypes, 2 /* Subtype */); + } + function getArrayLiteralTupleTypeIfApplicable(elementTypes, contextualType, hasRestElement, elementCount) { + if (elementCount === void 0) { elementCount = elementTypes.length; } + // Infer a tuple type when the contextual type is or contains a tuple-like type + if (contextualType && forEachType(contextualType, isTupleLikeType)) { + var minLength = elementCount - (hasRestElement ? 1 : 0); + var pattern = contextualType.pattern; + // If array literal is contextually typed by a binding pattern or an assignment pattern, pad the resulting + // tuple type with the corresponding binding or assignment element types to make the lengths equal. + if (!hasRestElement && pattern && (pattern.kind === 185 /* ArrayBindingPattern */ || pattern.kind === 187 /* ArrayLiteralExpression */)) { + var patternElements = pattern.elements; + for (var i = elementCount; i < patternElements.length; i++) { + var e = patternElements[i]; + if (hasDefaultValue(e)) { + elementTypes.push(contextualType.typeArguments[i]); + } + else if (i < patternElements.length - 1 || !(e.kind === 186 /* BindingElement */ && e.dotDotDotToken || e.kind === 208 /* SpreadElement */)) { + if (e.kind !== 210 /* OmittedExpression */) { + error(e, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); + } + elementTypes.push(strictNullChecks ? implicitNeverType : undefinedWideningType); + } + } + } + return createTupleType(elementTypes, minLength, hasRestElement); + } + } + function getArrayLiteralType(elementTypes, unionReduction) { + if (unionReduction === void 0) { unionReduction = 1 /* Literal */; } + return createArrayType(elementTypes.length ? + getUnionType(elementTypes, unionReduction) : + strictNullChecks ? implicitNeverType : undefinedWideningType); + } + function isNumericName(name) { + switch (name.kind) { + case 149 /* ComputedPropertyName */: + return isNumericComputedName(name); + case 72 /* Identifier */: + return isNumericLiteralName(name.escapedText); + case 8 /* NumericLiteral */: + case 10 /* StringLiteral */: + return isNumericLiteralName(name.text); + default: + return false; + } + } + function isNumericComputedName(name) { + // It seems odd to consider an expression of type Any to result in a numeric name, + // but this behavior is consistent with checkIndexedAccess + return isTypeAssignableToKind(checkComputedPropertyName(name), 296 /* NumberLike */); + } + function isInfinityOrNaNString(name) { + return name === "Infinity" || name === "-Infinity" || name === "NaN"; + } + function isNumericLiteralName(name) { + // The intent of numeric names is that + // - they are names with text in a numeric form, and that + // - setting properties/indexing with them is always equivalent to doing so with the numeric literal 'numLit', + // acquired by applying the abstract 'ToNumber' operation on the name's text. + // + // The subtlety is in the latter portion, as we cannot reliably say that anything that looks like a numeric literal is a numeric name. + // In fact, it is the case that the text of the name must be equal to 'ToString(numLit)' for this to hold. + // + // Consider the property name '"0xF00D"'. When one indexes with '0xF00D', they are actually indexing with the value of 'ToString(0xF00D)' + // according to the ECMAScript specification, so it is actually as if the user indexed with the string '"61453"'. + // Thus, the text of all numeric literals equivalent to '61543' such as '0xF00D', '0xf00D', '0170015', etc. are not valid numeric names + // because their 'ToString' representation is not equal to their original text. + // This is motivated by ECMA-262 sections 9.3.1, 9.8.1, 11.1.5, and 11.2.1. + // + // Here, we test whether 'ToString(ToNumber(name))' is exactly equal to 'name'. + // The '+' prefix operator is equivalent here to applying the abstract ToNumber operation. + // Applying the 'toString()' method on a number gives us the abstract ToString operation on a number. + // + // Note that this accepts the values 'Infinity', '-Infinity', and 'NaN', and that this is intentional. + // This is desired behavior, because when indexing with them as numeric entities, you are indexing + // with the strings '"Infinity"', '"-Infinity"', and '"NaN"' respectively. + return (+name).toString() === name; + } + function checkComputedPropertyName(node) { + var links = getNodeLinks(node.expression); + if (!links.resolvedType) { + links.resolvedType = checkExpression(node.expression); + // This will allow types number, string, symbol or any. It will also allow enums, the unknown + // type, and any union of these types (like string | number). + if (links.resolvedType.flags & 98304 /* Nullable */ || + !isTypeAssignableToKind(links.resolvedType, 132 /* StringLike */ | 296 /* NumberLike */ | 12288 /* ESSymbolLike */) && + !isTypeAssignableTo(links.resolvedType, stringNumberSymbolType)) { + error(node, ts.Diagnostics.A_computed_property_name_must_be_of_type_string_number_symbol_or_any); + } + else { + checkThatExpressionIsProperSymbolReference(node.expression, links.resolvedType, /*reportError*/ true); + } + } + return links.resolvedType; + } + function getObjectLiteralIndexInfo(propertyNodes, offset, properties, kind) { + var propTypes = []; + for (var i = 0; i < properties.length; i++) { + if (kind === 0 /* String */ || isNumericName(propertyNodes[i + offset].name)) { + propTypes.push(getTypeOfSymbol(properties[i])); + } + } + var unionType = propTypes.length ? getUnionType(propTypes, 2 /* Subtype */) : undefinedType; + return createIndexInfo(unionType, /*isReadonly*/ false); + } + function getImmediateAliasedSymbol(symbol) { + ts.Debug.assert((symbol.flags & 2097152 /* Alias */) !== 0, "Should only get Alias here."); + var links = getSymbolLinks(symbol); + if (!links.immediateTarget) { + var node = getDeclarationOfAliasSymbol(symbol); + if (!node) + return ts.Debug.fail(); + links.immediateTarget = getTargetOfAliasDeclaration(node, /*dontRecursivelyResolve*/ true); + } + return links.immediateTarget; + } + function checkObjectLiteral(node, checkMode) { + var inDestructuringPattern = ts.isAssignmentTarget(node); + // Grammar checking + checkGrammarObjectLiteralExpression(node, inDestructuringPattern); + var propertiesTable; + var propertiesArray = []; + var spread = emptyObjectType; + var propagatedFlags = 0; + var contextualType = getApparentTypeOfContextualType(node); + var contextualTypeHasPattern = contextualType && contextualType.pattern && + (contextualType.pattern.kind === 184 /* ObjectBindingPattern */ || contextualType.pattern.kind === 188 /* ObjectLiteralExpression */); + var isInJavascript = ts.isInJSFile(node) && !ts.isInJsonFile(node); + var enumTag = ts.getJSDocEnumTag(node); + var isJSObjectLiteral = !contextualType && isInJavascript && !enumTag; + var typeFlags = 0; + var patternWithComputedProperties = false; + var hasComputedStringProperty = false; + var hasComputedNumberProperty = false; + propertiesTable = ts.createSymbolTable(); + var offset = 0; + for (var i = 0; i < node.properties.length; i++) { + var memberDecl = node.properties[i]; + var member = getSymbolOfNode(memberDecl); + var computedNameType = memberDecl.name && memberDecl.name.kind === 149 /* ComputedPropertyName */ && !ts.isWellKnownSymbolSyntactically(memberDecl.name.expression) ? + checkComputedPropertyName(memberDecl.name) : undefined; + if (memberDecl.kind === 275 /* PropertyAssignment */ || + memberDecl.kind === 276 /* ShorthandPropertyAssignment */ || + ts.isObjectLiteralMethod(memberDecl)) { + var type = memberDecl.kind === 275 /* PropertyAssignment */ ? checkPropertyAssignment(memberDecl, checkMode) : + memberDecl.kind === 276 /* ShorthandPropertyAssignment */ ? checkExpressionForMutableLocation(memberDecl.name, checkMode) : + checkObjectLiteralMethod(memberDecl, checkMode); + if (isInJavascript) { + var jsDocType = getTypeForDeclarationFromJSDocComment(memberDecl); + if (jsDocType) { + checkTypeAssignableTo(type, jsDocType, memberDecl); + type = jsDocType; + } + else if (enumTag && enumTag.typeExpression) { + checkTypeAssignableTo(type, getTypeFromTypeNode(enumTag.typeExpression), memberDecl); + } + } + typeFlags |= type.flags; + var nameType = computedNameType && computedNameType.flags & 8576 /* StringOrNumberLiteralOrUnique */ ? + computedNameType : undefined; + var prop = nameType ? + createSymbol(4 /* Property */ | member.flags, getLateBoundNameFromType(nameType), 1024 /* Late */) : + createSymbol(4 /* Property */ | member.flags, member.escapedName); + if (nameType) { + prop.nameType = nameType; + } + if (inDestructuringPattern) { + // If object literal is an assignment pattern and if the assignment pattern specifies a default value + // for the property, make the property optional. + var isOptional = (memberDecl.kind === 275 /* PropertyAssignment */ && hasDefaultValue(memberDecl.initializer)) || + (memberDecl.kind === 276 /* ShorthandPropertyAssignment */ && memberDecl.objectAssignmentInitializer); + if (isOptional) { + prop.flags |= 16777216 /* Optional */; + } + } + else if (contextualTypeHasPattern && !(ts.getObjectFlags(contextualType) & 512 /* ObjectLiteralPatternWithComputedProperties */)) { + // If object literal is contextually typed by the implied type of a binding pattern, and if the + // binding pattern specifies a default value for the property, make the property optional. + var impliedProp = getPropertyOfType(contextualType, member.escapedName); + if (impliedProp) { + prop.flags |= impliedProp.flags & 16777216 /* Optional */; + } + else if (!compilerOptions.suppressExcessPropertyErrors && !getIndexInfoOfType(contextualType, 0 /* String */)) { + error(memberDecl.name, ts.Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(member), typeToString(contextualType)); + } + } + prop.declarations = member.declarations; + prop.parent = member.parent; + if (member.valueDeclaration) { + prop.valueDeclaration = member.valueDeclaration; + } + prop.type = type; + prop.target = member; + member = prop; + } + else if (memberDecl.kind === 277 /* SpreadAssignment */) { + if (languageVersion < 2 /* ES2015 */) { + checkExternalEmitHelpers(memberDecl, 2 /* Assign */); + } + if (propertiesArray.length > 0) { + spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, propagatedFlags, 32768 /* FreshLiteral */); + propertiesArray = []; + propertiesTable = ts.createSymbolTable(); + hasComputedStringProperty = false; + hasComputedNumberProperty = false; + typeFlags = 0; + } + var type = checkExpression(memberDecl.expression); + if (!isValidSpreadType(type)) { + error(memberDecl, ts.Diagnostics.Spread_types_may_only_be_created_from_object_types); + return errorType; + } + spread = getSpreadType(spread, type, node.symbol, propagatedFlags, 32768 /* FreshLiteral */); + offset = i + 1; + continue; + } + else { + // TypeScript 1.0 spec (April 2014) + // A get accessor declaration is processed in the same manner as + // an ordinary function declaration(section 6.1) with no parameters. + // A set accessor declaration is processed in the same manner + // as an ordinary function declaration with a single parameter and a Void return type. + ts.Debug.assert(memberDecl.kind === 158 /* GetAccessor */ || memberDecl.kind === 159 /* SetAccessor */); + checkNodeDeferred(memberDecl); + } + if (computedNameType && !(computedNameType.flags & 8576 /* StringOrNumberLiteralOrUnique */)) { + if (isTypeAssignableTo(computedNameType, stringNumberSymbolType)) { + if (isTypeAssignableTo(computedNameType, numberType)) { + hasComputedNumberProperty = true; + } + else { + hasComputedStringProperty = true; + } + if (inDestructuringPattern) { + patternWithComputedProperties = true; + } + } + } + else { + propertiesTable.set(member.escapedName, member); + } + propertiesArray.push(member); + } + // If object literal is contextually typed by the implied type of a binding pattern, augment the result + // type with those properties for which the binding pattern specifies a default value. + if (contextualTypeHasPattern) { + for (var _i = 0, _a = getPropertiesOfType(contextualType); _i < _a.length; _i++) { + var prop = _a[_i]; + if (!propertiesTable.get(prop.escapedName) && !(spread && getPropertyOfType(spread, prop.escapedName))) { + if (!(prop.flags & 16777216 /* Optional */)) { + error(prop.valueDeclaration || prop.bindingElement, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); + } + propertiesTable.set(prop.escapedName, prop); + propertiesArray.push(prop); + } + } + } + if (spread !== emptyObjectType) { + if (propertiesArray.length > 0) { + spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, propagatedFlags, 32768 /* FreshLiteral */); + } + return spread; + } + return createObjectLiteralType(); + function createObjectLiteralType() { + var stringIndexInfo = hasComputedStringProperty ? getObjectLiteralIndexInfo(node.properties, offset, propertiesArray, 0 /* String */) : undefined; + var numberIndexInfo = hasComputedNumberProperty ? getObjectLiteralIndexInfo(node.properties, offset, propertiesArray, 1 /* Number */) : undefined; + var result = createAnonymousType(node.symbol, propertiesTable, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); + result.flags |= 268435456 /* ContainsObjectLiteral */ | typeFlags & 939524096 /* PropagatingFlags */; + result.objectFlags |= 128 /* ObjectLiteral */ | freshObjectLiteralFlag; + if (isJSObjectLiteral) { + result.objectFlags |= 16384 /* JSLiteral */; + } + if (patternWithComputedProperties) { + result.objectFlags |= 512 /* ObjectLiteralPatternWithComputedProperties */; + } + if (inDestructuringPattern) { + result.pattern = node; + } + propagatedFlags |= result.flags & 939524096 /* PropagatingFlags */; + return result; + } + } + function isValidSpreadType(type) { + return !!(type.flags & (3 /* AnyOrUnknown */ | 67108864 /* NonPrimitive */ | 524288 /* Object */ | 58982400 /* InstantiableNonPrimitive */) || + getFalsyFlags(type) & 117632 /* DefinitelyFalsy */ && isValidSpreadType(removeDefinitelyFalsyTypes(type)) || + type.flags & 3145728 /* UnionOrIntersection */ && ts.every(type.types, isValidSpreadType)); + } + function checkJsxSelfClosingElementDeferred(node) { + checkJsxOpeningLikeElementOrOpeningFragment(node); + } + function checkJsxSelfClosingElement(node, _checkMode) { + checkNodeDeferred(node); + return getJsxElementTypeAt(node) || anyType; + } + function checkJsxElementDeferred(node) { + // Check attributes + checkJsxOpeningLikeElementOrOpeningFragment(node.openingElement); + // Perform resolution on the closing tag so that rename/go to definition/etc work + if (isJsxIntrinsicIdentifier(node.closingElement.tagName)) { + getIntrinsicTagSymbol(node.closingElement); + } + else { + checkExpression(node.closingElement.tagName); + } + checkJsxChildren(node); + } + function checkJsxElement(node, _checkMode) { + checkNodeDeferred(node); + return getJsxElementTypeAt(node) || anyType; + } + function checkJsxFragment(node) { + checkJsxOpeningLikeElementOrOpeningFragment(node.openingFragment); + if (compilerOptions.jsx === 2 /* React */ && (compilerOptions.jsxFactory || ts.getSourceFileOfNode(node).pragmas.has("jsx"))) { + error(node, compilerOptions.jsxFactory + ? ts.Diagnostics.JSX_fragment_is_not_supported_when_using_jsxFactory + : ts.Diagnostics.JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma); + } + checkJsxChildren(node); + return getJsxElementTypeAt(node) || anyType; + } + /** + * Returns true iff the JSX element name would be a valid JS identifier, ignoring restrictions about keywords not being identifiers + */ + function isUnhyphenatedJsxName(name) { + // - is the only character supported in JSX attribute names that isn't valid in JavaScript identifiers + return !ts.stringContains(name, "-"); + } + /** + * Returns true iff React would emit this tag name as a string rather than an identifier or qualified name + */ + function isJsxIntrinsicIdentifier(tagName) { + return tagName.kind === 72 /* Identifier */ && ts.isIntrinsicJsxName(tagName.escapedText); + } + function checkJsxAttribute(node, checkMode) { + return node.initializer + ? checkExpressionForMutableLocation(node.initializer, checkMode) + : trueType; // is sugar for + } + /** + * Get attributes type of the JSX opening-like element. The result is from resolving "attributes" property of the opening-like element. + * + * @param openingLikeElement a JSX opening-like element + * @param filter a function to remove attributes that will not participate in checking whether attributes are assignable + * @return an anonymous type (similar to the one returned by checkObjectLiteral) in which its properties are attributes property. + * @remarks Because this function calls getSpreadType, it needs to use the same checks as checkObjectLiteral, + * which also calls getSpreadType. + */ + function createJsxAttributesTypeFromAttributesProperty(openingLikeElement, checkMode) { + var attributes = openingLikeElement.attributes; + var attributesTable = ts.createSymbolTable(); + var spread = emptyJsxObjectType; + var hasSpreadAnyType = false; + var typeToIntersect; + var explicitlySpecifyChildrenAttribute = false; + var typeFlags = 0; + var objectFlags = 4096 /* JsxAttributes */; + var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(openingLikeElement)); + for (var _i = 0, _a = attributes.properties; _i < _a.length; _i++) { + var attributeDecl = _a[_i]; + var member = attributeDecl.symbol; + if (ts.isJsxAttribute(attributeDecl)) { + var exprType = checkJsxAttribute(attributeDecl, checkMode); + typeFlags |= exprType.flags & 939524096 /* PropagatingFlags */; + var attributeSymbol = createSymbol(4 /* Property */ | 33554432 /* Transient */ | member.flags, member.escapedName); + attributeSymbol.declarations = member.declarations; + attributeSymbol.parent = member.parent; + if (member.valueDeclaration) { + attributeSymbol.valueDeclaration = member.valueDeclaration; + } + attributeSymbol.type = exprType; + attributeSymbol.target = member; + attributesTable.set(attributeSymbol.escapedName, attributeSymbol); + if (attributeDecl.name.escapedText === jsxChildrenPropertyName) { + explicitlySpecifyChildrenAttribute = true; + } + } + else { + ts.Debug.assert(attributeDecl.kind === 269 /* JsxSpreadAttribute */); + if (attributesTable.size > 0) { + spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, typeFlags, objectFlags); + attributesTable = ts.createSymbolTable(); + } + var exprType = checkExpressionCached(attributeDecl.expression, checkMode); + if (isTypeAny(exprType)) { + hasSpreadAnyType = true; + } + if (isValidSpreadType(exprType)) { + spread = getSpreadType(spread, exprType, attributes.symbol, typeFlags, objectFlags); + } + else { + typeToIntersect = typeToIntersect ? getIntersectionType([typeToIntersect, exprType]) : exprType; + } + } + } + if (!hasSpreadAnyType) { + if (attributesTable.size > 0) { + spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, typeFlags, objectFlags); + } + } + // Handle children attribute + var parent = openingLikeElement.parent.kind === 260 /* JsxElement */ ? openingLikeElement.parent : undefined; + // We have to check that openingElement of the parent is the one we are visiting as this may not be true for selfClosingElement + if (parent && parent.openingElement === openingLikeElement && parent.children.length > 0) { + var childrenTypes = checkJsxChildren(parent, checkMode); + if (!hasSpreadAnyType && jsxChildrenPropertyName && jsxChildrenPropertyName !== "") { + // Error if there is a attribute named "children" explicitly specified and children element. + // This is because children element will overwrite the value from attributes. + // Note: we will not warn "children" attribute overwritten if "children" attribute is specified in object spread. + if (explicitlySpecifyChildrenAttribute) { + error(attributes, ts.Diagnostics._0_are_specified_twice_The_attribute_named_0_will_be_overwritten, ts.unescapeLeadingUnderscores(jsxChildrenPropertyName)); + } + var contextualType = getApparentTypeOfContextualType(openingLikeElement.attributes); + var childrenContextualType = contextualType && getTypeOfPropertyOfContextualType(contextualType, jsxChildrenPropertyName); + // If there are children in the body of JSX element, create dummy attribute "children" with the union of children types so that it will pass the attribute checking process + var childrenPropSymbol = createSymbol(4 /* Property */ | 33554432 /* Transient */, jsxChildrenPropertyName); + childrenPropSymbol.type = childrenTypes.length === 1 ? + childrenTypes[0] : + (getArrayLiteralTupleTypeIfApplicable(childrenTypes, childrenContextualType, /*hasRestElement*/ false) || createArrayType(getUnionType(childrenTypes))); + var childPropMap = ts.createSymbolTable(); + childPropMap.set(jsxChildrenPropertyName, childrenPropSymbol); + spread = getSpreadType(spread, createAnonymousType(attributes.symbol, childPropMap, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined), attributes.symbol, typeFlags, objectFlags); + } + } + if (hasSpreadAnyType) { + return anyType; + } + if (typeToIntersect && spread !== emptyJsxObjectType) { + return getIntersectionType([typeToIntersect, spread]); + } + return typeToIntersect || (spread === emptyJsxObjectType ? createJsxAttributesType() : spread); + /** + * Create anonymous type from given attributes symbol table. + * @param symbol a symbol of JsxAttributes containing attributes corresponding to attributesTable + * @param attributesTable a symbol table of attributes property + */ + function createJsxAttributesType() { + objectFlags |= freshObjectLiteralFlag; + var result = createAnonymousType(attributes.symbol, attributesTable, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined); + result.flags |= 268435456 /* ContainsObjectLiteral */ | typeFlags; + result.objectFlags |= 128 /* ObjectLiteral */ | objectFlags; + return result; + } + } + function checkJsxChildren(node, checkMode) { + var childrenTypes = []; + for (var _i = 0, _a = node.children; _i < _a.length; _i++) { + var child = _a[_i]; + // In React, JSX text that contains only whitespaces will be ignored so we don't want to type-check that + // because then type of children property will have constituent of string type. + if (child.kind === 11 /* JsxText */) { + if (!child.containsOnlyWhiteSpaces) { + childrenTypes.push(stringType); + } + } + else { + childrenTypes.push(checkExpressionForMutableLocation(child, checkMode)); + } + } + return childrenTypes; + } + /** + * Check attributes property of opening-like element. This function is called during chooseOverload to get call signature of a JSX opening-like element. + * (See "checkApplicableSignatureForJsxOpeningLikeElement" for how the function is used) + * @param node a JSXAttributes to be resolved of its type + */ + function checkJsxAttributes(node, checkMode) { + return createJsxAttributesTypeFromAttributesProperty(node.parent, checkMode); + } + function getJsxType(name, location) { + var namespace = getJsxNamespaceAt(location); + var exports = namespace && getExportsOfSymbol(namespace); + var typeSymbol = exports && getSymbol(exports, name, 67897832 /* Type */); + return typeSymbol ? getDeclaredTypeOfSymbol(typeSymbol) : errorType; + } + /** + * Looks up an intrinsic tag name and returns a symbol that either points to an intrinsic + * property (in which case nodeLinks.jsxFlags will be IntrinsicNamedElement) or an intrinsic + * string index signature (in which case nodeLinks.jsxFlags will be IntrinsicIndexedElement). + * May also return unknownSymbol if both of these lookups fail. + */ + function getIntrinsicTagSymbol(node) { + var links = getNodeLinks(node); + if (!links.resolvedSymbol) { + var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements, node); + if (intrinsicElementsType !== errorType) { + // Property case + if (!ts.isIdentifier(node.tagName)) + return ts.Debug.fail(); + var intrinsicProp = getPropertyOfType(intrinsicElementsType, node.tagName.escapedText); + if (intrinsicProp) { + links.jsxFlags |= 1 /* IntrinsicNamedElement */; + return links.resolvedSymbol = intrinsicProp; + } + // Intrinsic string indexer case + var indexSignatureType = getIndexTypeOfType(intrinsicElementsType, 0 /* String */); + if (indexSignatureType) { + links.jsxFlags |= 2 /* IntrinsicIndexedElement */; + return links.resolvedSymbol = intrinsicElementsType.symbol; + } + // Wasn't found + error(node, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.idText(node.tagName), "JSX." + JsxNames.IntrinsicElements); + return links.resolvedSymbol = unknownSymbol; + } + else { + if (noImplicitAny) { + error(node, ts.Diagnostics.JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists, ts.unescapeLeadingUnderscores(JsxNames.IntrinsicElements)); + } + return links.resolvedSymbol = unknownSymbol; + } + } + return links.resolvedSymbol; + } + function getJsxNamespaceAt(location) { + var links = location && getNodeLinks(location); + if (links && links.jsxNamespace) { + return links.jsxNamespace; + } + if (!links || links.jsxNamespace !== false) { + var namespaceName = getJsxNamespace(location); + var resolvedNamespace = resolveName(location, namespaceName, 1920 /* Namespace */, /*diagnosticMessage*/ undefined, namespaceName, /*isUse*/ false); + if (resolvedNamespace) { + var candidate = getSymbol(getExportsOfSymbol(resolveSymbol(resolvedNamespace)), JsxNames.JSX, 1920 /* Namespace */); + if (candidate) { + if (links) { + links.jsxNamespace = candidate; + } + return candidate; + } + if (links) { + links.jsxNamespace = false; + } + } + } + // JSX global fallback + return getGlobalSymbol(JsxNames.JSX, 1920 /* Namespace */, /*diagnosticMessage*/ undefined); // TODO: GH#18217 + } + /** + * Look into JSX namespace and then look for container with matching name as nameOfAttribPropContainer. + * Get a single property from that container if existed. Report an error if there are more than one property. + * + * @param nameOfAttribPropContainer a string of value JsxNames.ElementAttributesPropertyNameContainer or JsxNames.ElementChildrenAttributeNameContainer + * if other string is given or the container doesn't exist, return undefined. + */ + function getNameFromJsxElementAttributesContainer(nameOfAttribPropContainer, jsxNamespace) { + // JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute [symbol] + var jsxElementAttribPropInterfaceSym = jsxNamespace && getSymbol(jsxNamespace.exports, nameOfAttribPropContainer, 67897832 /* Type */); + // JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute [type] + var jsxElementAttribPropInterfaceType = jsxElementAttribPropInterfaceSym && getDeclaredTypeOfSymbol(jsxElementAttribPropInterfaceSym); + // The properties of JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute + var propertiesOfJsxElementAttribPropInterface = jsxElementAttribPropInterfaceType && getPropertiesOfType(jsxElementAttribPropInterfaceType); + if (propertiesOfJsxElementAttribPropInterface) { + // Element Attributes has zero properties, so the element attributes type will be the class instance type + if (propertiesOfJsxElementAttribPropInterface.length === 0) { + return ""; + } + // Element Attributes has one property, so the element attributes type will be the type of the corresponding + // property of the class instance type + else if (propertiesOfJsxElementAttribPropInterface.length === 1) { + return propertiesOfJsxElementAttribPropInterface[0].escapedName; + } + else if (propertiesOfJsxElementAttribPropInterface.length > 1) { + // More than one property on ElementAttributesProperty is an error + error(jsxElementAttribPropInterfaceSym.declarations[0], ts.Diagnostics.The_global_type_JSX_0_may_not_have_more_than_one_property, ts.unescapeLeadingUnderscores(nameOfAttribPropContainer)); + } + } + return undefined; + } + function getJsxLibraryManagedAttributes(jsxNamespace) { + // JSX.LibraryManagedAttributes [symbol] + return jsxNamespace && getSymbol(jsxNamespace.exports, JsxNames.LibraryManagedAttributes, 67897832 /* Type */); + } + /// e.g. "props" for React.d.ts, + /// or 'undefined' if ElementAttributesProperty doesn't exist (which means all + /// non-intrinsic elements' attributes type is 'any'), + /// or '' if it has 0 properties (which means every + /// non-intrinsic elements' attributes type is the element instance type) + function getJsxElementPropertiesName(jsxNamespace) { + return getNameFromJsxElementAttributesContainer(JsxNames.ElementAttributesPropertyNameContainer, jsxNamespace); + } + function getJsxElementChildrenPropertyName(jsxNamespace) { + return getNameFromJsxElementAttributesContainer(JsxNames.ElementChildrenAttributeNameContainer, jsxNamespace); + } + function getUninstantiatedJsxSignaturesOfType(elementType, caller) { + if (elementType.flags & 4 /* String */) { + return [anySignature]; + } + else if (elementType.flags & 128 /* StringLiteral */) { + var intrinsicType = getIntrinsicAttributesTypeFromStringLiteralType(elementType, caller); + if (!intrinsicType) { + error(caller, ts.Diagnostics.Property_0_does_not_exist_on_type_1, elementType.value, "JSX." + JsxNames.IntrinsicElements); + return ts.emptyArray; + } + else { + var fakeSignature = createSignatureForJSXIntrinsic(caller, intrinsicType); + return [fakeSignature]; + } + } + var apparentElemType = getApparentType(elementType); + // Resolve the signatures, preferring constructor + var signatures = getSignaturesOfType(apparentElemType, 1 /* Construct */); + if (signatures.length === 0) { + // No construct signatures, try call signatures + signatures = getSignaturesOfType(apparentElemType, 0 /* Call */); + } + if (signatures.length === 0 && apparentElemType.flags & 1048576 /* Union */) { + // If each member has some combination of new/call signatures; make a union signature list for those + signatures = getUnionSignatures(ts.map(apparentElemType.types, function (t) { return getUninstantiatedJsxSignaturesOfType(t, caller); })); + } + return signatures; + } + function getIntrinsicAttributesTypeFromStringLiteralType(type, location) { + // If the elemType is a stringLiteral type, we can then provide a check to make sure that the string literal type is one of the Jsx intrinsic element type + // For example: + // var CustomTag: "h1" = "h1"; + // Hello World + var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements, location); + if (intrinsicElementsType !== errorType) { + var stringLiteralTypeName = type.value; + var intrinsicProp = getPropertyOfType(intrinsicElementsType, ts.escapeLeadingUnderscores(stringLiteralTypeName)); + if (intrinsicProp) { + return getTypeOfSymbol(intrinsicProp); + } + var indexSignatureType = getIndexTypeOfType(intrinsicElementsType, 0 /* String */); + if (indexSignatureType) { + return indexSignatureType; + } + return undefined; + } + // If we need to report an error, we already done so here. So just return any to prevent any more error downstream + return anyType; + } + function checkJsxReturnAssignableToAppropriateBound(refKind, elemInstanceType, openingLikeElement) { + if (refKind === 1 /* Function */) { + var sfcReturnConstraint = getJsxStatelessElementTypeAt(openingLikeElement); + if (sfcReturnConstraint) { + checkTypeRelatedTo(elemInstanceType, sfcReturnConstraint, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); + } + } + else if (refKind === 0 /* Component */) { + var classConstraint = getJsxElementClassTypeAt(openingLikeElement); + if (classConstraint) { + // Issue an error if this return type isn't assignable to JSX.ElementClass or JSX.Element, failing that + checkTypeRelatedTo(elemInstanceType, classConstraint, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); + } + } + else { // Mixed + var sfcReturnConstraint = getJsxStatelessElementTypeAt(openingLikeElement); + var classConstraint = getJsxElementClassTypeAt(openingLikeElement); + if (!sfcReturnConstraint || !classConstraint) { + return; + } + var combined = getUnionType([sfcReturnConstraint, classConstraint]); + checkTypeRelatedTo(elemInstanceType, combined, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); + } + } + /** + * Get attributes type of the given intrinsic opening-like Jsx element by resolving the tag name. + * The function is intended to be called from a function which has checked that the opening element is an intrinsic element. + * @param node an intrinsic JSX opening-like element + */ + function getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node) { + ts.Debug.assert(isJsxIntrinsicIdentifier(node.tagName)); + var links = getNodeLinks(node); + if (!links.resolvedJsxElementAttributesType) { + var symbol = getIntrinsicTagSymbol(node); + if (links.jsxFlags & 1 /* IntrinsicNamedElement */) { + return links.resolvedJsxElementAttributesType = getTypeOfSymbol(symbol); + } + else if (links.jsxFlags & 2 /* IntrinsicIndexedElement */) { + return links.resolvedJsxElementAttributesType = getIndexInfoOfSymbol(symbol, 0 /* String */).type; + } + else { + return links.resolvedJsxElementAttributesType = errorType; + } + } + return links.resolvedJsxElementAttributesType; + } + function getJsxElementClassTypeAt(location) { + var type = getJsxType(JsxNames.ElementClass, location); + if (type === errorType) + return undefined; + return type; + } + function getJsxElementTypeAt(location) { + return getJsxType(JsxNames.Element, location); + } + function getJsxStatelessElementTypeAt(location) { + var jsxElementType = getJsxElementTypeAt(location); + if (jsxElementType) { + return getUnionType([jsxElementType, nullType]); + } + } + /** + * Returns all the properties of the Jsx.IntrinsicElements interface + */ + function getJsxIntrinsicTagNamesAt(location) { + var intrinsics = getJsxType(JsxNames.IntrinsicElements, location); + return intrinsics ? getPropertiesOfType(intrinsics) : ts.emptyArray; + } + function checkJsxPreconditions(errorNode) { + // Preconditions for using JSX + if ((compilerOptions.jsx || 0 /* None */) === 0 /* None */) { + error(errorNode, ts.Diagnostics.Cannot_use_JSX_unless_the_jsx_flag_is_provided); + } + if (getJsxElementTypeAt(errorNode) === undefined) { + if (noImplicitAny) { + error(errorNode, ts.Diagnostics.JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist); + } + } + } + function checkJsxOpeningLikeElementOrOpeningFragment(node) { + var isNodeOpeningLikeElement = ts.isJsxOpeningLikeElement(node); + if (isNodeOpeningLikeElement) { + checkGrammarJsxElement(node); + } + checkJsxPreconditions(node); + // The reactNamespace/jsxFactory's root symbol should be marked as 'used' so we don't incorrectly elide its import. + // And if there is no reactNamespace/jsxFactory's symbol in scope when targeting React emit, we should issue an error. + var reactRefErr = diagnostics && compilerOptions.jsx === 2 /* React */ ? ts.Diagnostics.Cannot_find_name_0 : undefined; + var reactNamespace = getJsxNamespace(node); + var reactLocation = isNodeOpeningLikeElement ? node.tagName : node; + var reactSym = resolveName(reactLocation, reactNamespace, 67220415 /* Value */, reactRefErr, reactNamespace, /*isUse*/ true); + if (reactSym) { + // Mark local symbol as referenced here because it might not have been marked + // if jsx emit was not react as there wont be error being emitted + reactSym.isReferenced = 67108863 /* All */; + // If react symbol is alias, mark it as refereced + if (reactSym.flags & 2097152 /* Alias */ && !isConstEnumOrConstEnumOnlyModule(resolveAlias(reactSym))) { + markAliasSymbolAsReferenced(reactSym); + } + } + if (isNodeOpeningLikeElement) { + var sig = getResolvedSignature(node); + checkJsxReturnAssignableToAppropriateBound(getJsxReferenceKind(node), getReturnTypeOfSignature(sig), node); + } + } + /** + * Check if a property with the given name is known anywhere in the given type. In an object type, a property + * is considered known if + * 1. the object type is empty and the check is for assignability, or + * 2. if the object type has index signatures, or + * 3. if the property is actually declared in the object type + * (this means that 'toString', for example, is not usually a known property). + * 4. In a union or intersection type, + * a property is considered known if it is known in any constituent type. + * @param targetType a type to search a given name in + * @param name a property name to search + * @param isComparingJsxAttributes a boolean flag indicating whether we are searching in JsxAttributesType + */ + function isKnownProperty(targetType, name, isComparingJsxAttributes) { + if (targetType.flags & 524288 /* Object */) { + var resolved = resolveStructuredTypeMembers(targetType); + if (resolved.stringIndexInfo || + resolved.numberIndexInfo && isNumericLiteralName(name) || + getPropertyOfObjectType(targetType, name) || + isComparingJsxAttributes && !isUnhyphenatedJsxName(name)) { + // For JSXAttributes, if the attribute has a hyphenated name, consider that the attribute to be known. + return true; + } + } + else if (targetType.flags & 3145728 /* UnionOrIntersection */) { + for (var _i = 0, _a = targetType.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (isKnownProperty(t, name, isComparingJsxAttributes)) { + return true; + } + } + } + else if (targetType.flags & 16777216 /* Conditional */) { + return isKnownProperty(targetType.root.trueType, name, isComparingJsxAttributes) || + isKnownProperty(targetType.root.falseType, name, isComparingJsxAttributes); + } + return false; + } + function checkJsxExpression(node, checkMode) { + if (node.expression) { + var type = checkExpression(node.expression, checkMode); + if (node.dotDotDotToken && type !== anyType && !isArrayType(type)) { + error(node, ts.Diagnostics.JSX_spread_child_must_be_an_array_type); + } + return type; + } + else { + return errorType; + } + } + function getDeclarationNodeFlagsFromSymbol(s) { + return s.valueDeclaration ? ts.getCombinedNodeFlags(s.valueDeclaration) : 0; + } + /** + * Return whether this symbol is a member of a prototype somewhere + * Note that this is not tracked well within the compiler, so the answer may be incorrect. + */ + function isPrototypeProperty(symbol) { + if (symbol.flags & 8192 /* Method */ || ts.getCheckFlags(symbol) & 4 /* SyntheticMethod */) { + return true; + } + if (ts.isInJSFile(symbol.valueDeclaration)) { + var parent = symbol.valueDeclaration.parent; + return parent && ts.isBinaryExpression(parent) && + ts.getAssignmentDeclarationKind(parent) === 3 /* PrototypeProperty */; + } + } + /** + * Check whether the requested property access is valid. + * Returns true if node is a valid property access, and false otherwise. + * @param node The node to be checked. + * @param isSuper True if the access is from `super.`. + * @param type The type of the object whose property is being accessed. (Not the type of the property.) + * @param prop The symbol for the property being accessed. + */ + function checkPropertyAccessibility(node, isSuper, type, prop) { + var flags = ts.getDeclarationModifierFlagsFromSymbol(prop); + var errorNode = node.kind === 148 /* QualifiedName */ ? node.right : node.kind === 183 /* ImportType */ ? node : node.name; + if (ts.getCheckFlags(prop) & 256 /* ContainsPrivate */) { + // Synthetic property with private constituent property + error(errorNode, ts.Diagnostics.Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1, symbolToString(prop), typeToString(type)); + return false; + } + if (isSuper) { + // TS 1.0 spec (April 2014): 4.8.2 + // - In a constructor, instance member function, instance member accessor, or + // instance member variable initializer where this references a derived class instance, + // a super property access is permitted and must specify a public instance member function of the base class. + // - In a static member function or static member accessor + // where this references the constructor function object of a derived class, + // a super property access is permitted and must specify a public static member function of the base class. + if (languageVersion < 2 /* ES2015 */) { + if (symbolHasNonMethodDeclaration(prop)) { + error(errorNode, ts.Diagnostics.Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword); + return false; + } + } + if (flags & 128 /* Abstract */) { + // A method cannot be accessed in a super property access if the method is abstract. + // This error could mask a private property access error. But, a member + // cannot simultaneously be private and abstract, so this will trigger an + // additional error elsewhere. + error(errorNode, ts.Diagnostics.Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression, symbolToString(prop), typeToString(getDeclaringClass(prop))); + return false; + } + } + // Referencing abstract properties within their own constructors is not allowed + if ((flags & 128 /* Abstract */) && ts.isThisProperty(node) && symbolHasNonMethodDeclaration(prop)) { + var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop)); + if (declaringClassDeclaration && isNodeUsedDuringClassInitialization(node)) { + error(errorNode, ts.Diagnostics.Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor, symbolToString(prop), ts.getTextOfIdentifierOrLiteral(declaringClassDeclaration.name)); // TODO: GH#18217 + return false; + } + } + // Public properties are otherwise accessible. + if (!(flags & 24 /* NonPublicAccessibilityModifier */)) { + return true; + } + // Property is known to be private or protected at this point + // Private property is accessible if the property is within the declaring class + if (flags & 8 /* Private */) { + var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop)); + if (!isNodeWithinClass(node, declaringClassDeclaration)) { + error(errorNode, ts.Diagnostics.Property_0_is_private_and_only_accessible_within_class_1, symbolToString(prop), typeToString(getDeclaringClass(prop))); + return false; + } + return true; + } + // Property is known to be protected at this point + // All protected properties of a supertype are accessible in a super access + if (isSuper) { + return true; + } + // Find the first enclosing class that has the declaring classes of the protected constituents + // of the property as base classes + var enclosingClass = forEachEnclosingClass(node, function (enclosingDeclaration) { + var enclosingClass = getDeclaredTypeOfSymbol(getSymbolOfNode(enclosingDeclaration)); + return isClassDerivedFromDeclaringClasses(enclosingClass, prop) ? enclosingClass : undefined; + }); + // A protected property is accessible if the property is within the declaring class or classes derived from it + if (!enclosingClass) { + // allow PropertyAccessibility if context is in function with this parameter + // static member access is disallow + var thisParameter = void 0; + if (flags & 32 /* Static */ || !(thisParameter = getThisParameterFromNodeContext(node)) || !thisParameter.type) { + error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses, symbolToString(prop), typeToString(getDeclaringClass(prop) || type)); + return false; + } + var thisType = getTypeFromTypeNode(thisParameter.type); + enclosingClass = ((thisType.flags & 262144 /* TypeParameter */) ? getConstraintOfTypeParameter(thisType) : thisType); + } + // No further restrictions for static properties + if (flags & 32 /* Static */) { + return true; + } + if (type.flags & 262144 /* TypeParameter */) { + // get the original type -- represented as the type constraint of the 'this' type + type = type.isThisType ? getConstraintOfTypeParameter(type) : getBaseConstraintOfType(type); // TODO: GH#18217 Use a different variable that's allowed to be undefined + } + if (!type || !hasBaseType(type, enclosingClass)) { + error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1, symbolToString(prop), typeToString(enclosingClass)); + return false; + } + return true; + } + function getThisParameterFromNodeContext(node) { + var thisContainer = ts.getThisContainer(node, /* includeArrowFunctions */ false); + return thisContainer && ts.isFunctionLike(thisContainer) ? ts.getThisParameter(thisContainer) : undefined; + } + function symbolHasNonMethodDeclaration(symbol) { + return !!forEachProperty(symbol, function (prop) { return !(prop.flags & 8192 /* Method */); }); + } + function checkNonNullExpression(node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic) { + return checkNonNullType(checkExpression(node), node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic); + } + function getNonNullableTypeIfNeeded(type) { + var kind = (strictNullChecks ? getFalsyFlags(type) : type.flags) & 98304 /* Nullable */; + if (kind) { + return getNonNullableType(type); + } + return type; + } + function checkNonNullType(type, node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic) { + if (type.flags & 2 /* Unknown */) { + error(node, ts.Diagnostics.Object_is_of_type_unknown); + return errorType; + } + var kind = (strictNullChecks ? getFalsyFlags(type) : type.flags) & 98304 /* Nullable */; + if (kind) { + error(node, kind & 32768 /* Undefined */ ? kind & 65536 /* Null */ ? + (nullOrUndefinedDiagnostic || ts.Diagnostics.Object_is_possibly_null_or_undefined) : + (undefinedDiagnostic || ts.Diagnostics.Object_is_possibly_undefined) : + (nullDiagnostic || ts.Diagnostics.Object_is_possibly_null)); + var t = getNonNullableType(type); + return t.flags & (98304 /* Nullable */ | 131072 /* Never */) ? errorType : t; + } + return type; + } + function checkPropertyAccessExpression(node) { + return checkPropertyAccessExpressionOrQualifiedName(node, node.expression, node.name); + } + function checkQualifiedName(node) { + return checkPropertyAccessExpressionOrQualifiedName(node, node.left, node.right); + } + function checkPropertyAccessExpressionOrQualifiedName(node, left, right) { + var propType; + var leftType = checkNonNullExpression(left); + var parentSymbol = getNodeLinks(left).resolvedSymbol; + var apparentType = getApparentType(getWidenedType(leftType)); + if (isTypeAny(apparentType) || apparentType === silentNeverType) { + if (ts.isIdentifier(left) && parentSymbol) { + markAliasReferenced(parentSymbol, node); + } + return apparentType; + } + var assignmentKind = ts.getAssignmentTargetKind(node); + var prop = getPropertyOfType(apparentType, right.escapedText); + if (ts.isIdentifier(left) && parentSymbol && !(prop && isConstEnumOrConstEnumOnlyModule(prop))) { + markAliasReferenced(parentSymbol, node); + } + if (!prop) { + var indexInfo = getIndexInfoOfType(apparentType, 0 /* String */); + if (!(indexInfo && indexInfo.type)) { + if (isJSLiteralType(leftType)) { + return anyType; + } + if (right.escapedText && !checkAndReportErrorForExtendingInterface(node)) { + reportNonexistentProperty(right, leftType.flags & 262144 /* TypeParameter */ && leftType.isThisType ? apparentType : leftType); + } + return errorType; + } + if (indexInfo.isReadonly && (ts.isAssignmentTarget(node) || ts.isDeleteTarget(node))) { + error(node, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(apparentType)); + } + propType = indexInfo.type; + } + else { + checkPropertyNotUsedBeforeDeclaration(prop, node, right); + markPropertyAsReferenced(prop, node, left.kind === 100 /* ThisKeyword */); + getNodeLinks(node).resolvedSymbol = prop; + checkPropertyAccessibility(node, left.kind === 98 /* SuperKeyword */, apparentType, prop); + if (assignmentKind) { + if (isReferenceToReadonlyEntity(node, prop) || isReferenceThroughNamespaceImport(node)) { + error(right, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, ts.idText(right)); + return errorType; + } + } + propType = getConstraintForLocation(getTypeOfSymbol(prop), node); + } + // Only compute control flow type if this is a property access expression that isn't an + // assignment target, and the referenced property was declared as a variable, property, + // accessor, or optional method. + if (node.kind !== 189 /* PropertyAccessExpression */ || + assignmentKind === 1 /* Definite */ || + prop && !(prop.flags & (3 /* Variable */ | 4 /* Property */ | 98304 /* Accessor */)) && !(prop.flags & 8192 /* Method */ && propType.flags & 1048576 /* Union */)) { + return propType; + } + // If strict null checks and strict property initialization checks are enabled, if we have + // a this.xxx property access, if the property is an instance property without an initializer, + // and if we are in a constructor of the same class as the property declaration, assume that + // the property is uninitialized at the top of the control flow. + var assumeUninitialized = false; + if (strictNullChecks && strictPropertyInitialization && left.kind === 100 /* ThisKeyword */) { + var declaration = prop && prop.valueDeclaration; + if (declaration && isInstancePropertyWithoutInitializer(declaration)) { + var flowContainer = getControlFlowContainer(node); + if (flowContainer.kind === 157 /* Constructor */ && flowContainer.parent === declaration.parent) { + assumeUninitialized = true; + } + } + } + else if (strictNullChecks && prop && prop.valueDeclaration && + ts.isPropertyAccessExpression(prop.valueDeclaration) && + ts.getAssignmentDeclarationPropertyAccessKind(prop.valueDeclaration) && + getControlFlowContainer(node) === getControlFlowContainer(prop.valueDeclaration)) { + assumeUninitialized = true; + } + var flowType = getFlowTypeOfReference(node, propType, assumeUninitialized ? getOptionalType(propType) : propType); + if (assumeUninitialized && !(getFalsyFlags(propType) & 32768 /* Undefined */) && getFalsyFlags(flowType) & 32768 /* Undefined */) { + error(right, ts.Diagnostics.Property_0_is_used_before_being_assigned, symbolToString(prop)); // TODO: GH#18217 + // Return the declared type to reduce follow-on errors + return propType; + } + return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType; + } + function checkPropertyNotUsedBeforeDeclaration(prop, node, right) { + var valueDeclaration = prop.valueDeclaration; + if (!valueDeclaration) { + return; + } + var diagnosticMessage; + var declarationName = ts.idText(right); + if (isInPropertyInitializer(node) && + !isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right) + && !isPropertyDeclaredInAncestorClass(prop)) { + diagnosticMessage = error(right, ts.Diagnostics.Property_0_is_used_before_its_initialization, declarationName); + } + else if (valueDeclaration.kind === 240 /* ClassDeclaration */ && + node.parent.kind !== 164 /* TypeReference */ && + !(valueDeclaration.flags & 4194304 /* Ambient */) && + !isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right)) { + diagnosticMessage = error(right, ts.Diagnostics.Class_0_used_before_its_declaration, declarationName); + } + if (diagnosticMessage) { + addRelatedInfo(diagnosticMessage, ts.createDiagnosticForNode(valueDeclaration, ts.Diagnostics._0_is_declared_here, declarationName)); + } + } + function isInPropertyInitializer(node) { + return !!ts.findAncestor(node, function (node) { + switch (node.kind) { + case 154 /* PropertyDeclaration */: + return true; + case 275 /* PropertyAssignment */: + // We might be in `a = { b: this.b }`, so keep looking. See `tests/cases/compiler/useBeforeDeclaration_propertyAssignment.ts`. + return false; + default: + return ts.isExpressionNode(node) ? false : "quit"; + } + }); + } + /** + * It's possible that "prop.valueDeclaration" is a local declaration, but the property was also declared in a superclass. + * In that case we won't consider it used before its declaration, because it gets its value from the superclass' declaration. + */ + function isPropertyDeclaredInAncestorClass(prop) { + if (!(prop.parent.flags & 32 /* Class */)) { + return false; + } + var classType = getTypeOfSymbol(prop.parent); + while (true) { + classType = classType.symbol && getSuperClass(classType); + if (!classType) { + return false; + } + var superProperty = getPropertyOfType(classType, prop.escapedName); + if (superProperty && superProperty.valueDeclaration) { + return true; + } + } + } + function getSuperClass(classType) { + var x = getBaseTypes(classType); + if (x.length === 0) { + return undefined; + } + return getIntersectionType(x); + } + function reportNonexistentProperty(propNode, containingType) { + var errorInfo; + var relatedInfo; + if (containingType.flags & 1048576 /* Union */ && !(containingType.flags & 131068 /* Primitive */)) { + for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) { + var subtype = _a[_i]; + if (!getPropertyOfType(subtype, propNode.escapedText)) { + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(subtype)); + break; + } + } + } + if (typeHasStaticProperty(propNode.escapedText, containingType)) { + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_is_a_static_member_of_type_1, ts.declarationNameToString(propNode), typeToString(containingType)); + } + else { + var promisedType = getPromisedTypeOfPromise(containingType); + if (promisedType && getPropertyOfType(promisedType, propNode.escapedText)) { + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_forget_to_use_await, ts.declarationNameToString(propNode), typeToString(containingType)); + } + else { + var suggestion = getSuggestedSymbolForNonexistentProperty(propNode, containingType); + if (suggestion !== undefined) { + var suggestedName = ts.symbolName(suggestion); + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2, ts.declarationNameToString(propNode), typeToString(containingType), suggestedName); + relatedInfo = suggestion.valueDeclaration && ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestedName); + } + else { + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(containingType)); + } + } + } + var resultDiagnostic = ts.createDiagnosticForNodeFromMessageChain(propNode, errorInfo); + if (relatedInfo) { + addRelatedInfo(resultDiagnostic, relatedInfo); + } + diagnostics.add(resultDiagnostic); + } + function typeHasStaticProperty(propName, containingType) { + var prop = containingType.symbol && getPropertyOfType(getTypeOfSymbol(containingType.symbol), propName); + return prop !== undefined && prop.valueDeclaration && ts.hasModifier(prop.valueDeclaration, 32 /* Static */); + } + function getSuggestedSymbolForNonexistentProperty(name, containingType) { + return getSpellingSuggestionForName(ts.isString(name) ? name : ts.idText(name), getPropertiesOfType(containingType), 67220415 /* Value */); + } + function getSuggestionForNonexistentProperty(name, containingType) { + var suggestion = getSuggestedSymbolForNonexistentProperty(name, containingType); + return suggestion && ts.symbolName(suggestion); + } + function getSuggestedSymbolForNonexistentSymbol(location, outerName, meaning) { + ts.Debug.assert(outerName !== undefined, "outername should always be defined"); + var result = resolveNameHelper(location, outerName, meaning, /*nameNotFoundMessage*/ undefined, outerName, /*isUse*/ false, /*excludeGlobals*/ false, function (symbols, name, meaning) { + ts.Debug.assertEqual(outerName, name, "name should equal outerName"); + var symbol = getSymbol(symbols, name, meaning); + // Sometimes the symbol is found when location is a return type of a function: `typeof x` and `x` is declared in the body of the function + // So the table *contains* `x` but `x` isn't actually in scope. + // However, resolveNameHelper will continue and call this callback again, so we'll eventually get a correct suggestion. + return symbol || getSpellingSuggestionForName(ts.unescapeLeadingUnderscores(name), ts.arrayFrom(symbols.values()), meaning); + }); + return result; + } + function getSuggestionForNonexistentSymbol(location, outerName, meaning) { + var symbolResult = getSuggestedSymbolForNonexistentSymbol(location, outerName, meaning); + return symbolResult && ts.symbolName(symbolResult); + } + function getSuggestedSymbolForNonexistentModule(name, targetModule) { + return targetModule.exports && getSpellingSuggestionForName(ts.idText(name), getExportsOfModuleAsArray(targetModule), 2623475 /* ModuleMember */); + } + function getSuggestionForNonexistentExport(name, targetModule) { + var suggestion = getSuggestedSymbolForNonexistentModule(name, targetModule); + return suggestion && ts.symbolName(suggestion); + } + /** + * Given a name and a list of symbols whose names are *not* equal to the name, return a spelling suggestion if there is one that is close enough. + * Names less than length 3 only check for case-insensitive equality, not levenshtein distance. + * + * If there is a candidate that's the same except for case, return that. + * If there is a candidate that's within one edit of the name, return that. + * Otherwise, return the candidate with the smallest Levenshtein distance, + * except for candidates: + * * With no name + * * Whose meaning doesn't match the `meaning` parameter. + * * Whose length differs from the target name by more than 0.34 of the length of the name. + * * Whose levenshtein distance is more than 0.4 of the length of the name + * (0.4 allows 1 substitution/transposition for every 5 characters, + * and 1 insertion/deletion at 3 characters) + */ + function getSpellingSuggestionForName(name, symbols, meaning) { + return ts.getSpellingSuggestion(name, symbols, getCandidateName); + function getCandidateName(candidate) { + var candidateName = ts.symbolName(candidate); + return !ts.startsWith(candidateName, "\"") && candidate.flags & meaning ? candidateName : undefined; + } + } + function markPropertyAsReferenced(prop, nodeForCheckWriteOnly, isThisAccess) { + if (!prop || !(prop.flags & 106500 /* ClassMember */) || !prop.valueDeclaration || !ts.hasModifier(prop.valueDeclaration, 8 /* Private */)) { + return; + } + if (nodeForCheckWriteOnly && ts.isWriteOnlyAccess(nodeForCheckWriteOnly) && !(prop.flags & 65536 /* SetAccessor */ && !(prop.flags & 32768 /* GetAccessor */))) { + return; + } + if (isThisAccess) { + // Find any FunctionLikeDeclaration because those create a new 'this' binding. But this should only matter for methods (or getters/setters). + var containingMethod = ts.findAncestor(nodeForCheckWriteOnly, ts.isFunctionLikeDeclaration); + if (containingMethod && containingMethod.symbol === prop) { + return; + } + } + (ts.getCheckFlags(prop) & 1 /* Instantiated */ ? getSymbolLinks(prop).target : prop).isReferenced = 67108863 /* All */; + } + function isValidPropertyAccess(node, propertyName) { + switch (node.kind) { + case 189 /* PropertyAccessExpression */: + return isValidPropertyAccessWithType(node, node.expression.kind === 98 /* SuperKeyword */, propertyName, getWidenedType(checkExpression(node.expression))); + case 148 /* QualifiedName */: + return isValidPropertyAccessWithType(node, /*isSuper*/ false, propertyName, getWidenedType(checkExpression(node.left))); + case 183 /* ImportType */: + return isValidPropertyAccessWithType(node, /*isSuper*/ false, propertyName, getTypeFromTypeNode(node)); + } + } + function isValidPropertyAccessForCompletions(node, type, property) { + return isValidPropertyAccessWithType(node, node.kind !== 183 /* ImportType */ && node.expression.kind === 98 /* SuperKeyword */, property.escapedName, type) + && (!(property.flags & 8192 /* Method */) || isValidMethodAccess(property, type)); + } + function isValidMethodAccess(method, actualThisType) { + var propType = getTypeOfPropertyOfType(actualThisType, method.escapedName); + var signatures = getSignaturesOfType(getNonNullableType(propType), 0 /* Call */); + ts.Debug.assert(signatures.length !== 0); + return signatures.some(function (sig) { + var signatureThisType = getThisTypeOfSignature(sig); + return !signatureThisType || isTypeAssignableTo(actualThisType, getInstantiatedSignatureThisType(sig, signatureThisType, actualThisType)); + }); + } + function getInstantiatedSignatureThisType(sig, signatureThisType, actualThisType) { + if (!sig.typeParameters) { + return signatureThisType; + } + var context = createInferenceContext(sig.typeParameters, sig, 0 /* None */); + inferTypes(context.inferences, actualThisType, signatureThisType); + return instantiateType(signatureThisType, createSignatureTypeMapper(sig, getInferredTypes(context))); + } + function isValidPropertyAccessWithType(node, isSuper, propertyName, type) { + if (type === errorType || isTypeAny(type)) { + return true; + } + var prop = getPropertyOfType(type, propertyName); + return prop ? checkPropertyAccessibility(node, isSuper, type, prop) + // In js files properties of unions are allowed in completion + : ts.isInJSFile(node) && (type.flags & 1048576 /* Union */) !== 0 && type.types.some(function (elementType) { return isValidPropertyAccessWithType(node, isSuper, propertyName, elementType); }); + } + /** + * Return the symbol of the for-in variable declared or referenced by the given for-in statement. + */ + function getForInVariableSymbol(node) { + var initializer = node.initializer; + if (initializer.kind === 238 /* VariableDeclarationList */) { + var variable = initializer.declarations[0]; + if (variable && !ts.isBindingPattern(variable.name)) { + return getSymbolOfNode(variable); + } + } + else if (initializer.kind === 72 /* Identifier */) { + return getResolvedSymbol(initializer); + } + return undefined; + } + /** + * Return true if the given type is considered to have numeric property names. + */ + function hasNumericPropertyNames(type) { + return getIndexTypeOfType(type, 1 /* Number */) && !getIndexTypeOfType(type, 0 /* String */); + } + /** + * Return true if given node is an expression consisting of an identifier (possibly parenthesized) + * that references a for-in variable for an object with numeric property names. + */ + function isForInVariableForNumericPropertyNames(expr) { + var e = ts.skipParentheses(expr); + if (e.kind === 72 /* Identifier */) { + var symbol = getResolvedSymbol(e); + if (symbol.flags & 3 /* Variable */) { + var child = expr; + var node = expr.parent; + while (node) { + if (node.kind === 226 /* ForInStatement */ && + child === node.statement && + getForInVariableSymbol(node) === symbol && + hasNumericPropertyNames(getTypeOfExpression(node.expression))) { + return true; + } + child = node; + node = node.parent; + } + } + } + return false; + } + function checkIndexedAccess(node) { + var objectType = checkNonNullExpression(node.expression); + var indexExpression = node.argumentExpression; + if (!indexExpression) { + var sourceFile = ts.getSourceFileOfNode(node); + if (node.parent.kind === 192 /* NewExpression */ && node.parent.expression === node) { + var start = ts.skipTrivia(sourceFile.text, node.expression.end); + var end = node.end; + grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead); + } + else { + var start = node.end - "]".length; + var end = node.end; + grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.Expression_expected); + } + return errorType; + } + var indexType = checkExpression(indexExpression); + if (objectType === errorType || objectType === silentNeverType) { + return objectType; + } + if (isConstEnumObjectType(objectType) && indexExpression.kind !== 10 /* StringLiteral */) { + error(indexExpression, ts.Diagnostics.A_const_enum_member_can_only_be_accessed_using_a_string_literal); + return errorType; + } + return checkIndexedAccessIndexType(getIndexedAccessType(objectType, isForInVariableForNumericPropertyNames(indexExpression) ? numberType : indexType, node), node); + } + function checkThatExpressionIsProperSymbolReference(expression, expressionType, reportError) { + if (expressionType === errorType) { + // There is already an error, so no need to report one. + return false; + } + if (!ts.isWellKnownSymbolSyntactically(expression)) { + return false; + } + // Make sure the property type is the primitive symbol type + if ((expressionType.flags & 12288 /* ESSymbolLike */) === 0) { + if (reportError) { + error(expression, ts.Diagnostics.A_computed_property_name_of_the_form_0_must_be_of_type_symbol, ts.getTextOfNode(expression)); + } + return false; + } + // The name is Symbol., so make sure Symbol actually resolves to the + // global Symbol object + var leftHandSide = expression.expression; + var leftHandSideSymbol = getResolvedSymbol(leftHandSide); + if (!leftHandSideSymbol) { + return false; + } + var globalESSymbol = getGlobalESSymbolConstructorSymbol(/*reportErrors*/ true); + if (!globalESSymbol) { + // Already errored when we tried to look up the symbol + return false; + } + if (leftHandSideSymbol !== globalESSymbol) { + if (reportError) { + error(leftHandSide, ts.Diagnostics.Symbol_reference_does_not_refer_to_the_global_Symbol_constructor_object); + } + return false; + } + return true; + } + function callLikeExpressionMayHaveTypeArguments(node) { + return ts.isCallOrNewExpression(node) || ts.isTaggedTemplateExpression(node) || ts.isJsxOpeningLikeElement(node); + } + function resolveUntypedCall(node) { + if (callLikeExpressionMayHaveTypeArguments(node)) { + // Check type arguments even though we will give an error that untyped calls may not accept type arguments. + // This gets us diagnostics for the type arguments and marks them as referenced. + ts.forEach(node.typeArguments, checkSourceElement); + } + if (node.kind === 193 /* TaggedTemplateExpression */) { + checkExpression(node.template); + } + else if (ts.isJsxOpeningLikeElement(node)) { + checkExpression(node.attributes); + } + else if (node.kind !== 152 /* Decorator */) { + ts.forEach(node.arguments, function (argument) { + checkExpression(argument); + }); + } + return anySignature; + } + function resolveErrorCall(node) { + resolveUntypedCall(node); + return unknownSignature; + } + // Re-order candidate signatures into the result array. Assumes the result array to be empty. + // The candidate list orders groups in reverse, but within a group signatures are kept in declaration order + // A nit here is that we reorder only signatures that belong to the same symbol, + // so order how inherited signatures are processed is still preserved. + // interface A { (x: string): void } + // interface B extends A { (x: 'foo'): string } + // const b: B; + // b('foo') // <- here overloads should be processed as [(x:'foo'): string, (x: string): void] + function reorderCandidates(signatures, result) { + var lastParent; + var lastSymbol; + var cutoffIndex = 0; + var index; + var specializedIndex = -1; + var spliceIndex; + ts.Debug.assert(!result.length); + for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { + var signature = signatures_3[_i]; + var symbol = signature.declaration && getSymbolOfNode(signature.declaration); + var parent = signature.declaration && signature.declaration.parent; + if (!lastSymbol || symbol === lastSymbol) { + if (lastParent && parent === lastParent) { + index = index + 1; + } + else { + lastParent = parent; + index = cutoffIndex; + } + } + else { + // current declaration belongs to a different symbol + // set cutoffIndex so re-orderings in the future won't change result set from 0 to cutoffIndex + index = cutoffIndex = result.length; + lastParent = parent; + } + lastSymbol = symbol; + // specialized signatures always need to be placed before non-specialized signatures regardless + // of the cutoff position; see GH#1133 + if (signature.hasLiteralTypes) { + specializedIndex++; + spliceIndex = specializedIndex; + // The cutoff index always needs to be greater than or equal to the specialized signature index + // in order to prevent non-specialized signatures from being added before a specialized + // signature. + cutoffIndex++; + } + else { + spliceIndex = index; + } + result.splice(spliceIndex, 0, signature); + } + } + function isSpreadArgument(arg) { + return !!arg && (arg.kind === 208 /* SpreadElement */ || arg.kind === 215 /* SyntheticExpression */ && arg.isSpread); + } + function getSpreadArgumentIndex(args) { + return ts.findIndex(args, isSpreadArgument); + } + function acceptsVoid(t) { + return !!(t.flags & 16384 /* Void */); + } + function hasCorrectArity(node, args, signature, signatureHelpTrailingComma) { + if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; } + var argCount; + var callIsIncomplete = false; // In incomplete call we want to be lenient when we have too few arguments + var effectiveParameterCount = getParameterCount(signature); + var effectiveMinimumArguments = getMinArgumentCount(signature); + if (node.kind === 193 /* TaggedTemplateExpression */) { + argCount = args.length; + if (node.template.kind === 206 /* TemplateExpression */) { + // If a tagged template expression lacks a tail literal, the call is incomplete. + // Specifically, a template only can end in a TemplateTail or a Missing literal. + var lastSpan = ts.last(node.template.templateSpans); // we should always have at least one span. + callIsIncomplete = ts.nodeIsMissing(lastSpan.literal) || !!lastSpan.literal.isUnterminated; + } + else { + // If the template didn't end in a backtick, or its beginning occurred right prior to EOF, + // then this might actually turn out to be a TemplateHead in the future; + // so we consider the call to be incomplete. + var templateLiteral = node.template; + ts.Debug.assert(templateLiteral.kind === 14 /* NoSubstitutionTemplateLiteral */); + callIsIncomplete = !!templateLiteral.isUnterminated; + } + } + else if (node.kind === 152 /* Decorator */) { + argCount = getDecoratorArgumentCount(node, signature); + } + else if (ts.isJsxOpeningLikeElement(node)) { + callIsIncomplete = node.attributes.end === node.end; + if (callIsIncomplete) { + return true; + } + argCount = effectiveMinimumArguments === 0 ? args.length : 1; + effectiveParameterCount = args.length === 0 ? effectiveParameterCount : 1; // class may have argumentless ctor functions - still resolve ctor and compare vs props member type + effectiveMinimumArguments = Math.min(effectiveMinimumArguments, 1); // sfc may specify context argument - handled by framework and not typechecked + } + else { + if (!node.arguments) { + // This only happens when we have something of the form: 'new C' + ts.Debug.assert(node.kind === 192 /* NewExpression */); + return getMinArgumentCount(signature) === 0; + } + argCount = signatureHelpTrailingComma ? args.length + 1 : args.length; + // If we are missing the close parenthesis, the call is incomplete. + callIsIncomplete = node.arguments.end === node.end; + // If a spread argument is present, check that it corresponds to a rest parameter or at least that it's in the valid range. + var spreadArgIndex = getSpreadArgumentIndex(args); + if (spreadArgIndex >= 0) { + return spreadArgIndex >= getMinArgumentCount(signature) && (hasEffectiveRestParameter(signature) || spreadArgIndex < getParameterCount(signature)); + } + } + // Too many arguments implies incorrect arity. + if (!hasEffectiveRestParameter(signature) && argCount > effectiveParameterCount) { + return false; + } + // If the call is incomplete, we should skip the lower bound check. + // JSX signatures can have extra parameters provided by the library which we don't check + if (callIsIncomplete || argCount >= effectiveMinimumArguments) { + return true; + } + for (var i = argCount; i < effectiveMinimumArguments; i++) { + var type = getTypeAtPosition(signature, i); + if (filterType(type, acceptsVoid).flags & 131072 /* Never */) { + return false; + } + } + return true; + } + function hasCorrectTypeArgumentArity(signature, typeArguments) { + // If the user supplied type arguments, but the number of type arguments does not match + // the declared number of type parameters, the call has an incorrect arity. + var numTypeParameters = ts.length(signature.typeParameters); + var minTypeArgumentCount = getMinTypeArgumentCount(signature.typeParameters); + return !typeArguments || + (typeArguments.length >= minTypeArgumentCount && typeArguments.length <= numTypeParameters); + } + // If type has a single call signature and no other members, return that signature. Otherwise, return undefined. + function getSingleCallSignature(type) { + if (type.flags & 524288 /* Object */) { + var resolved = resolveStructuredTypeMembers(type); + if (resolved.callSignatures.length === 1 && resolved.constructSignatures.length === 0 && + resolved.properties.length === 0 && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { + return resolved.callSignatures[0]; + } + } + return undefined; + } + // Instantiate a generic signature in the context of a non-generic signature (section 3.8.5 in TypeScript spec) + function instantiateSignatureInContextOf(signature, contextualSignature, contextualMapper, compareTypes) { + var context = createInferenceContext(signature.typeParameters, signature, 0 /* None */, compareTypes); + var sourceSignature = contextualMapper ? instantiateSignature(contextualSignature, contextualMapper) : contextualSignature; + forEachMatchingParameterType(sourceSignature, signature, function (source, target) { + // Type parameters from outer context referenced by source type are fixed by instantiation of the source type + inferTypes(context.inferences, source, target); + }); + if (!contextualMapper) { + inferTypes(context.inferences, getReturnTypeOfSignature(contextualSignature), getReturnTypeOfSignature(signature), 8 /* ReturnType */); + } + return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJSFile(contextualSignature.declaration)); + } + function inferJsxTypeArguments(node, signature, excludeArgument, context) { + var paramType = getEffectiveFirstArgumentForJsxSignature(signature, node); + var checkAttrType = checkExpressionWithContextualType(node.attributes, paramType, excludeArgument && excludeArgument[0] !== undefined ? identityMapper : context); + inferTypes(context.inferences, checkAttrType, paramType); + return getInferredTypes(context); + } + function inferTypeArguments(node, signature, args, excludeArgument, context) { + // Clear out all the inference results from the last time inferTypeArguments was called on this context + for (var _i = 0, _a = context.inferences; _i < _a.length; _i++) { + var inference = _a[_i]; + // As an optimization, we don't have to clear (and later recompute) inferred types + // for type parameters that have already been fixed on the previous call to inferTypeArguments. + // It would be just as correct to reset all of them. But then we'd be repeating the same work + // for the type parameters that were fixed, namely the work done by getInferredType. + if (!inference.isFixed) { + inference.inferredType = undefined; + } + } + if (ts.isJsxOpeningLikeElement(node)) { + return inferJsxTypeArguments(node, signature, excludeArgument, context); + } + // If a contextual type is available, infer from that type to the return type of the call expression. For + // example, given a 'function wrap(cb: (x: T) => U): (x: T) => U' and a call expression + // 'let f: (x: string) => number = wrap(s => s.length)', we infer from the declared type of 'f' to the + // return type of 'wrap'. + if (node.kind !== 152 /* Decorator */) { + var contextualType = getContextualType(node); + if (contextualType) { + // We clone the contextual mapper to avoid disturbing a resolution in progress for an + // outer call expression. Effectively we just want a snapshot of whatever has been + // inferred for any outer call expression so far. + var instantiatedType = instantiateType(contextualType, cloneTypeMapper(getContextualMapper(node))); + // If the contextual type is a generic function type with a single call signature, we + // instantiate the type with its own type parameters and type arguments. This ensures that + // the type parameters are not erased to type any during type inference such that they can + // be inferred as actual types from the contextual type. For example: + // declare function arrayMap(f: (x: T) => U): (a: T[]) => U[]; + // const boxElements: (a: A[]) => { value: A }[] = arrayMap(value => ({ value })); + // Above, the type of the 'value' parameter is inferred to be 'A'. + var contextualSignature = getSingleCallSignature(instantiatedType); + var inferenceSourceType = contextualSignature && contextualSignature.typeParameters ? + getOrCreateTypeFromSignature(getSignatureInstantiationWithoutFillingInTypeArguments(contextualSignature, contextualSignature.typeParameters)) : + instantiatedType; + var inferenceTargetType = getReturnTypeOfSignature(signature); + // Inferences made from return types have lower priority than all other inferences. + inferTypes(context.inferences, inferenceSourceType, inferenceTargetType, 8 /* ReturnType */); + } + } + var thisType = getThisTypeOfSignature(signature); + if (thisType) { + var thisArgumentNode = getThisArgumentOfCall(node); + var thisArgumentType = thisArgumentNode ? checkExpression(thisArgumentNode) : voidType; + inferTypes(context.inferences, thisArgumentType, thisType); + } + var restType = getNonArrayRestType(signature); + var argCount = restType ? Math.min(getParameterCount(signature) - 1, args.length) : args.length; + for (var i = 0; i < argCount; i++) { + var arg = args[i]; + if (arg.kind !== 210 /* OmittedExpression */) { + var paramType = getTypeAtPosition(signature, i); + // For context sensitive arguments we pass the identityMapper, which is a signal to treat all + // context sensitive function expressions as wildcards + var mapper = excludeArgument && excludeArgument[i] !== undefined ? identityMapper : context; + var argType = checkExpressionWithContextualType(arg, paramType, mapper); + inferTypes(context.inferences, argType, paramType); + } + } + if (restType) { + var spreadType = getSpreadArgumentType(args, argCount, args.length, restType, context); + inferTypes(context.inferences, spreadType, restType); + } + return getInferredTypes(context); + } + function getArrayifiedType(type) { + if (forEachType(type, function (t) { return !(t.flags & (1 /* Any */ | 63176704 /* Instantiable */) || isArrayType(t) || isTupleType(t)); })) { + return createArrayType(getIndexTypeOfType(type, 1 /* Number */) || errorType); + } + return type; + } + function getSpreadArgumentType(args, index, argCount, restType, context) { + if (index >= argCount - 1) { + var arg = args[argCount - 1]; + if (isSpreadArgument(arg)) { + // We are inferring from a spread expression in the last argument position, i.e. both the parameter + // and the argument are ...x forms. + return arg.kind === 215 /* SyntheticExpression */ ? + createArrayType(arg.type) : + getArrayifiedType(checkExpressionWithContextualType(arg.expression, restType, context)); + } + } + var contextualType = getIndexTypeOfType(restType, 1 /* Number */) || anyType; + var hasPrimitiveContextualType = maybeTypeOfKind(contextualType, 131068 /* Primitive */ | 4194304 /* Index */); + var types = []; + var spreadIndex = -1; + for (var i = index; i < argCount; i++) { + var argType = checkExpressionWithContextualType(args[i], contextualType, context); + if (spreadIndex < 0 && isSpreadArgument(args[i])) { + spreadIndex = i - index; + } + types.push(hasPrimitiveContextualType ? getRegularTypeOfLiteralType(argType) : getWidenedLiteralType(argType)); + } + return spreadIndex < 0 ? + createTupleType(types) : + createTupleType(ts.append(types.slice(0, spreadIndex), getUnionType(types.slice(spreadIndex))), spreadIndex, /*hasRestElement*/ true); + } + function checkTypeArguments(signature, typeArgumentNodes, reportErrors, headMessage) { + var isJavascript = ts.isInJSFile(signature.declaration); + var typeParameters = signature.typeParameters; + var typeArgumentTypes = fillMissingTypeArguments(ts.map(typeArgumentNodes, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), isJavascript); + var mapper; + for (var i = 0; i < typeArgumentNodes.length; i++) { + ts.Debug.assert(typeParameters[i] !== undefined, "Should not call checkTypeArguments with too many type arguments"); + var constraint = getConstraintOfTypeParameter(typeParameters[i]); + if (constraint) { + var errorInfo = reportErrors && headMessage ? (function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); }) : undefined; + var typeArgumentHeadMessage = headMessage || ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1; + if (!mapper) { + mapper = createTypeMapper(typeParameters, typeArgumentTypes); + } + var typeArgument = typeArgumentTypes[i]; + if (!checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), reportErrors ? typeArgumentNodes[i] : undefined, typeArgumentHeadMessage, errorInfo)) { + return undefined; + } + } + } + return typeArgumentTypes; + } + function getJsxReferenceKind(node) { + if (isJsxIntrinsicIdentifier(node.tagName)) { + return 2 /* Mixed */; + } + var tagType = getApparentType(checkExpression(node.tagName)); + if (ts.length(getSignaturesOfType(tagType, 1 /* Construct */))) { + return 0 /* Component */; + } + if (ts.length(getSignaturesOfType(tagType, 0 /* Call */))) { + return 1 /* Function */; + } + return 2 /* Mixed */; + } + /** + * Check if the given signature can possibly be a signature called by the JSX opening-like element. + * @param node a JSX opening-like element we are trying to figure its call signature + * @param signature a candidate signature we are trying whether it is a call signature + * @param relation a relationship to check parameter and argument type + * @param excludeArgument + */ + function checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation, excludeArgument, reportErrors) { + // Stateless function components can have maximum of three arguments: "props", "context", and "updater". + // However "context" and "updater" are implicit and can't be specify by users. Only the first parameter, props, + // can be specified by users through attributes property. + var paramType = getEffectiveFirstArgumentForJsxSignature(signature, node); + var attributesType = checkExpressionWithContextualType(node.attributes, paramType, excludeArgument && excludeArgument[0] ? identityMapper : undefined); + return checkTypeRelatedToAndOptionallyElaborate(attributesType, paramType, relation, reportErrors ? node.tagName : undefined, node.attributes); + } + function checkApplicableSignature(node, args, signature, relation, excludeArgument, reportErrors) { + if (ts.isJsxOpeningLikeElement(node)) { + return checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation, excludeArgument, reportErrors); + } + var thisType = getThisTypeOfSignature(signature); + if (thisType && thisType !== voidType && node.kind !== 192 /* NewExpression */) { + // If the called expression is not of the form `x.f` or `x["f"]`, then sourceType = voidType + // If the signature's 'this' type is voidType, then the check is skipped -- anything is compatible. + // If the expression is a new expression, then the check is skipped. + var thisArgumentNode = getThisArgumentOfCall(node); + var thisArgumentType = thisArgumentNode ? checkExpression(thisArgumentNode) : voidType; + var errorNode = reportErrors ? (thisArgumentNode || node) : undefined; + var headMessage_1 = ts.Diagnostics.The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1; + if (!checkTypeRelatedTo(thisArgumentType, thisType, relation, errorNode, headMessage_1)) { + return false; + } + } + var headMessage = ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1; + var restType = getNonArrayRestType(signature); + var argCount = restType ? Math.min(getParameterCount(signature) - 1, args.length) : args.length; + for (var i = 0; i < argCount; i++) { + var arg = args[i]; + if (arg.kind !== 210 /* OmittedExpression */) { + var paramType = getTypeAtPosition(signature, i); + var argType = checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); + // If one or more arguments are still excluded (as indicated by a non-null excludeArgument parameter), + // we obtain the regular type of any object literal arguments because we may not have inferred complete + // parameter types yet and therefore excess property checks may yield false positives (see #17041). + var checkArgType = excludeArgument ? getRegularTypeOfObjectLiteral(argType) : argType; + if (!checkTypeRelatedToAndOptionallyElaborate(checkArgType, paramType, relation, reportErrors ? arg : undefined, arg, headMessage)) { + return false; + } + } + } + if (restType) { + var spreadType = getSpreadArgumentType(args, argCount, args.length, restType, /*context*/ undefined); + var errorNode = reportErrors ? argCount < args.length ? args[argCount] : node : undefined; + return checkTypeRelatedTo(spreadType, restType, relation, errorNode, headMessage); + } + return true; + } + /** + * Returns the this argument in calls like x.f(...) and x[f](...). Undefined otherwise. + */ + function getThisArgumentOfCall(node) { + if (node.kind === 191 /* CallExpression */) { + var callee = ts.skipOuterExpressions(node.expression); + if (callee.kind === 189 /* PropertyAccessExpression */ || callee.kind === 190 /* ElementAccessExpression */) { + return callee.expression; + } + } + } + function createSyntheticExpression(parent, type, isSpread) { + var result = ts.createNode(215 /* SyntheticExpression */, parent.pos, parent.end); + result.parent = parent; + result.type = type; + result.isSpread = isSpread || false; + return result; + } + /** + * Returns the effective arguments for an expression that works like a function invocation. + */ + function getEffectiveCallArguments(node) { + if (node.kind === 193 /* TaggedTemplateExpression */) { + var template = node.template; + var args_4 = [createSyntheticExpression(template, getGlobalTemplateStringsArrayType())]; + if (template.kind === 206 /* TemplateExpression */) { + ts.forEach(template.templateSpans, function (span) { + args_4.push(span.expression); + }); + } + return args_4; + } + if (node.kind === 152 /* Decorator */) { + return getEffectiveDecoratorArguments(node); + } + if (ts.isJsxOpeningLikeElement(node)) { + return node.attributes.properties.length > 0 || (ts.isJsxOpeningElement(node) && node.parent.children.length > 0) ? [node.attributes] : ts.emptyArray; + } + var args = node.arguments || ts.emptyArray; + var length = args.length; + if (length && isSpreadArgument(args[length - 1]) && getSpreadArgumentIndex(args) === length - 1) { + // We have a spread argument in the last position and no other spread arguments. If the type + // of the argument is a tuple type, spread the tuple elements into the argument list. We can + // call checkExpressionCached because spread expressions never have a contextual type. + var spreadArgument_1 = args[length - 1]; + var type = checkExpressionCached(spreadArgument_1.expression); + if (isTupleType(type)) { + var typeArguments = type.typeArguments || ts.emptyArray; + var restIndex_2 = type.target.hasRestElement ? typeArguments.length - 1 : -1; + var syntheticArgs = ts.map(typeArguments, function (t, i) { return createSyntheticExpression(spreadArgument_1, t, /*isSpread*/ i === restIndex_2); }); + return ts.concatenate(args.slice(0, length - 1), syntheticArgs); + } + } + return args; + } + /** + * Returns the synthetic argument list for a decorator invocation. + */ + function getEffectiveDecoratorArguments(node) { + var parent = node.parent; + var expr = node.expression; + switch (parent.kind) { + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + // For a class decorator, the `target` is the type of the class (e.g. the + // "static" or "constructor" side of the class). + return [ + createSyntheticExpression(expr, getTypeOfSymbol(getSymbolOfNode(parent))) + ]; + case 151 /* Parameter */: + // A parameter declaration decorator will have three arguments (see + // `ParameterDecorator` in core.d.ts). + var func = parent.parent; + return [ + createSyntheticExpression(expr, parent.parent.kind === 157 /* Constructor */ ? getTypeOfSymbol(getSymbolOfNode(func)) : errorType), + createSyntheticExpression(expr, anyType), + createSyntheticExpression(expr, numberType) + ]; + case 154 /* PropertyDeclaration */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + // A method or accessor declaration decorator will have two or three arguments (see + // `PropertyDecorator` and `MethodDecorator` in core.d.ts). If we are emitting decorators + // for ES3, we will only pass two arguments. + var hasPropDesc = parent.kind !== 154 /* PropertyDeclaration */ && languageVersion !== 0 /* ES3 */; + return [ + createSyntheticExpression(expr, getParentTypeOfClassElement(parent)), + createSyntheticExpression(expr, getClassElementPropertyKeyType(parent)), + createSyntheticExpression(expr, hasPropDesc ? createTypedPropertyDescriptorType(getTypeOfNode(parent)) : anyType) + ]; + } + return ts.Debug.fail(); + } + /** + * Returns the argument count for a decorator node that works like a function invocation. + */ + function getDecoratorArgumentCount(node, signature) { + switch (node.parent.kind) { + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + return 1; + case 154 /* PropertyDeclaration */: + return 2; + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + // For ES3 or decorators with only two parameters we supply only two arguments + return languageVersion === 0 /* ES3 */ || signature.parameters.length <= 2 ? 2 : 3; + case 151 /* Parameter */: + return 3; + default: + return ts.Debug.fail(); + } + } + function getArgumentArityError(node, signatures, args) { + var min = Number.POSITIVE_INFINITY; + var max = Number.NEGATIVE_INFINITY; + var belowArgCount = Number.NEGATIVE_INFINITY; + var aboveArgCount = Number.POSITIVE_INFINITY; + var argCount = args.length; + var closestSignature; + for (var _i = 0, signatures_4 = signatures; _i < signatures_4.length; _i++) { + var sig = signatures_4[_i]; + var minCount = getMinArgumentCount(sig); + var maxCount = getParameterCount(sig); + if (minCount < argCount && minCount > belowArgCount) + belowArgCount = minCount; + if (argCount < maxCount && maxCount < aboveArgCount) + aboveArgCount = maxCount; + if (minCount < min) { + min = minCount; + closestSignature = sig; + } + max = Math.max(max, maxCount); + } + var hasRestParameter = ts.some(signatures, hasEffectiveRestParameter); + var paramRange = hasRestParameter ? min : + min < max ? min + "-" + max : + min; + var hasSpreadArgument = getSpreadArgumentIndex(args) > -1; + if (argCount <= max && hasSpreadArgument) { + argCount--; + } + var related; + if (closestSignature && getMinArgumentCount(closestSignature) > argCount && closestSignature.declaration) { + var paramDecl = closestSignature.declaration.parameters[closestSignature.thisParameter ? argCount + 1 : argCount]; + if (paramDecl) { + related = ts.createDiagnosticForNode(paramDecl, ts.isBindingPattern(paramDecl.name) ? ts.Diagnostics.An_argument_matching_this_binding_pattern_was_not_provided : ts.Diagnostics.An_argument_for_0_was_not_provided, !paramDecl.name ? argCount : !ts.isBindingPattern(paramDecl.name) ? ts.idText(getFirstIdentifier(paramDecl.name)) : undefined); + } + } + if (hasRestParameter || hasSpreadArgument) { + var error_1 = hasRestParameter && hasSpreadArgument ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1_or_more : + hasRestParameter ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1 : + ts.Diagnostics.Expected_0_arguments_but_got_1_or_more; + var diagnostic_1 = ts.createDiagnosticForNode(node, error_1, paramRange, argCount); + return related ? addRelatedInfo(diagnostic_1, related) : diagnostic_1; + } + if (min < argCount && argCount < max) { + return ts.createDiagnosticForNode(node, ts.Diagnostics.No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments, argCount, belowArgCount, aboveArgCount); + } + var diagnostic = ts.createDiagnosticForNode(node, ts.Diagnostics.Expected_0_arguments_but_got_1, paramRange, argCount); + return related ? addRelatedInfo(diagnostic, related) : diagnostic; + } + function getTypeArgumentArityError(node, signatures, typeArguments) { + var min = Infinity; + var max = -Infinity; + for (var _i = 0, signatures_5 = signatures; _i < signatures_5.length; _i++) { + var sig = signatures_5[_i]; + min = Math.min(min, getMinTypeArgumentCount(sig.typeParameters)); + max = Math.max(max, ts.length(sig.typeParameters)); + } + var paramCount = min === max ? min : min + "-" + max; + return ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), typeArguments, ts.Diagnostics.Expected_0_type_arguments_but_got_1, paramCount, typeArguments.length); + } + function resolveCall(node, signatures, candidatesOutArray, isForSignatureHelp, fallbackError) { + var isTaggedTemplate = node.kind === 193 /* TaggedTemplateExpression */; + var isDecorator = node.kind === 152 /* Decorator */; + var isJsxOpeningOrSelfClosingElement = ts.isJsxOpeningLikeElement(node); + var reportErrors = !candidatesOutArray; + var typeArguments; + if (!isDecorator) { + typeArguments = node.typeArguments; + // We already perform checking on the type arguments on the class declaration itself. + if (isTaggedTemplate || isJsxOpeningOrSelfClosingElement || node.expression.kind !== 98 /* SuperKeyword */) { + ts.forEach(typeArguments, checkSourceElement); + } + } + var candidates = candidatesOutArray || []; + // reorderCandidates fills up the candidates array directly + reorderCandidates(signatures, candidates); + if (!candidates.length) { + if (reportErrors) { + diagnostics.add(ts.createDiagnosticForNode(node, ts.Diagnostics.Call_target_does_not_contain_any_signatures)); + } + return resolveErrorCall(node); + } + var args = getEffectiveCallArguments(node); + // The excludeArgument array contains true for each context sensitive argument (an argument + // is context sensitive it is susceptible to a one-time permanent contextual typing). + // + // The idea is that we will perform type argument inference & assignability checking once + // without using the susceptible parameters that are functions, and once more for those + // parameters, contextually typing each as we go along. + // + // For a tagged template, then the first argument be 'undefined' if necessary because it + // represents a TemplateStringsArray. + // + // For a decorator, no arguments are susceptible to contextual typing due to the fact + // decorators are applied to a declaration by the emitter, and not to an expression. + var isSingleNonGenericCandidate = candidates.length === 1 && !candidates[0].typeParameters; + var excludeArgument = !isDecorator && !isSingleNonGenericCandidate ? getExcludeArgument(args) : undefined; + // The following variables are captured and modified by calls to chooseOverload. + // If overload resolution or type argument inference fails, we want to report the + // best error possible. The best error is one which says that an argument was not + // assignable to a parameter. This implies that everything else about the overload + // was fine. So if there is any overload that is only incorrect because of an + // argument, we will report an error on that one. + // + // function foo(s: string): void; + // function foo(n: number): void; // Report argument error on this overload + // function foo(): void; + // foo(true); + // + // If none of the overloads even made it that far, there are two possibilities. + // There was a problem with type arguments for some overload, in which case + // report an error on that. Or none of the overloads even had correct arity, + // in which case give an arity error. + // + // function foo(x: T): void; // Report type argument error + // function foo(): void; + // foo(0); + // + var candidateForArgumentError; + var candidateForArgumentArityError; + var candidateForTypeArgumentError; + var result; + // If we are in signature help, a trailing comma indicates that we intend to provide another argument, + // so we will only accept overloads with arity at least 1 higher than the current number of provided arguments. + var signatureHelpTrailingComma = isForSignatureHelp && node.kind === 191 /* CallExpression */ && node.arguments.hasTrailingComma; + // Section 4.12.1: + // if the candidate list contains one or more signatures for which the type of each argument + // expression is a subtype of each corresponding parameter type, the return type of the first + // of those signatures becomes the return type of the function call. + // Otherwise, the return type of the first signature in the candidate list becomes the return + // type of the function call. + // + // Whether the call is an error is determined by assignability of the arguments. The subtype pass + // is just important for choosing the best signature. So in the case where there is only one + // signature, the subtype pass is useless. So skipping it is an optimization. + if (candidates.length > 1) { + result = chooseOverload(candidates, subtypeRelation, signatureHelpTrailingComma); + } + if (!result) { + result = chooseOverload(candidates, assignableRelation, signatureHelpTrailingComma); + } + if (result) { + return result; + } + // No signatures were applicable. Now report errors based on the last applicable signature with + // no arguments excluded from assignability checks. + // If candidate is undefined, it means that no candidates had a suitable arity. In that case, + // skip the checkApplicableSignature check. + if (reportErrors) { + if (candidateForArgumentError) { + // excludeArgument is undefined, in this case also equivalent to [undefined, undefined, ...] + // The importance of excludeArgument is to prevent us from typing function expression parameters + // in arguments too early. If possible, we'd like to only type them once we know the correct + // overload. However, this matters for the case where the call is correct. When the call is + // an error, we don't need to exclude any arguments, although it would cause no harm to do so. + checkApplicableSignature(node, args, candidateForArgumentError, assignableRelation, /*excludeArgument*/ undefined, /*reportErrors*/ true); + } + else if (candidateForArgumentArityError) { + diagnostics.add(getArgumentArityError(node, [candidateForArgumentArityError], args)); + } + else if (candidateForTypeArgumentError) { + checkTypeArguments(candidateForTypeArgumentError, node.typeArguments, /*reportErrors*/ true, fallbackError); + } + else { + var signaturesWithCorrectTypeArgumentArity = ts.filter(signatures, function (s) { return hasCorrectTypeArgumentArity(s, typeArguments); }); + if (signaturesWithCorrectTypeArgumentArity.length === 0) { + diagnostics.add(getTypeArgumentArityError(node, signatures, typeArguments)); + } + else if (!isDecorator) { + diagnostics.add(getArgumentArityError(node, signaturesWithCorrectTypeArgumentArity, args)); + } + else if (fallbackError) { + diagnostics.add(ts.createDiagnosticForNode(node, fallbackError)); + } + } + } + return produceDiagnostics || !args ? resolveErrorCall(node) : getCandidateForOverloadFailure(node, candidates, args, !!candidatesOutArray); + function chooseOverload(candidates, relation, signatureHelpTrailingComma) { + if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; } + candidateForArgumentError = undefined; + candidateForArgumentArityError = undefined; + candidateForTypeArgumentError = undefined; + if (isSingleNonGenericCandidate) { + var candidate = candidates[0]; + if (typeArguments || !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) { + return undefined; + } + if (!checkApplicableSignature(node, args, candidate, relation, excludeArgument, /*reportErrors*/ false)) { + candidateForArgumentError = candidate; + return undefined; + } + return candidate; + } + for (var candidateIndex = 0; candidateIndex < candidates.length; candidateIndex++) { + var candidate = candidates[candidateIndex]; + if (!hasCorrectTypeArgumentArity(candidate, typeArguments) || !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) { + continue; + } + var checkCandidate = void 0; + var inferenceContext = void 0; + if (candidate.typeParameters) { + var typeArgumentTypes = void 0; + if (typeArguments) { + typeArgumentTypes = checkTypeArguments(candidate, typeArguments, /*reportErrors*/ false); + if (!typeArgumentTypes) { + candidateForTypeArgumentError = candidate; + continue; + } + } + else { + inferenceContext = createInferenceContext(candidate.typeParameters, candidate, /*flags*/ ts.isInJSFile(node) ? 2 /* AnyDefault */ : 0 /* None */); + typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); + } + checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration)); + // If the original signature has a generic rest type, instantiation may produce a + // signature with different arity and we need to perform another arity check. + if (getNonArrayRestType(candidate) && !hasCorrectArity(node, args, checkCandidate, signatureHelpTrailingComma)) { + candidateForArgumentArityError = checkCandidate; + continue; + } + } + else { + checkCandidate = candidate; + } + if (!checkApplicableSignature(node, args, checkCandidate, relation, excludeArgument, /*reportErrors*/ false)) { + // Give preference to error candidates that have no rest parameters (as they are more specific) + if (!candidateForArgumentError || getEffectiveRestType(candidateForArgumentError) || !getEffectiveRestType(checkCandidate)) { + candidateForArgumentError = checkCandidate; + } + continue; + } + if (excludeArgument) { + // If one or more context sensitive arguments were excluded, we start including + // them now (and keeping do so for any subsequent candidates) and perform a second + // round of type inference and applicability checking for this particular candidate. + excludeArgument = undefined; + if (inferenceContext) { + var typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); + checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration)); + } + if (!checkApplicableSignature(node, args, checkCandidate, relation, excludeArgument, /*reportErrors*/ false)) { + // Give preference to error candidates that have no rest parameters (as they are more specific) + if (!candidateForArgumentError || getEffectiveRestType(candidateForArgumentError) || !getEffectiveRestType(checkCandidate)) { + candidateForArgumentError = checkCandidate; + } + continue; + } + } + candidates[candidateIndex] = checkCandidate; + return checkCandidate; + } + return undefined; + } + } + function getExcludeArgument(args) { + var excludeArgument; + // We do not need to call `getEffectiveArgumentCount` here as it only + // applies when calculating the number of arguments for a decorator. + for (var i = 0; i < args.length; i++) { + if (isContextSensitive(args[i])) { + if (!excludeArgument) { + excludeArgument = new Array(args.length); + } + excludeArgument[i] = true; + } + } + return excludeArgument; + } + // No signature was applicable. We have already reported the errors for the invalid signature. + // If this is a type resolution session, e.g. Language Service, try to get better information than anySignature. + function getCandidateForOverloadFailure(node, candidates, args, hasCandidatesOutArray) { + ts.Debug.assert(candidates.length > 0); // Else should not have called this. + // Normally we will combine overloads. Skip this if they have type parameters since that's hard to combine. + // Don't do this if there is a `candidatesOutArray`, + // because then we want the chosen best candidate to be one of the overloads, not a combination. + return hasCandidatesOutArray || candidates.length === 1 || candidates.some(function (c) { return !!c.typeParameters; }) + ? pickLongestCandidateSignature(node, candidates, args) + : createUnionOfSignaturesForOverloadFailure(candidates); + } + function createUnionOfSignaturesForOverloadFailure(candidates) { + var thisParameters = ts.mapDefined(candidates, function (c) { return c.thisParameter; }); + var thisParameter; + if (thisParameters.length) { + thisParameter = createCombinedSymbolFromTypes(thisParameters, thisParameters.map(getTypeOfParameter)); + } + var _a = ts.minAndMax(candidates, getNumNonRestParameters), minArgumentCount = _a.min, maxNonRestParam = _a.max; + var parameters = []; + var _loop_7 = function (i) { + var symbols = ts.mapDefined(candidates, function (_a) { + var parameters = _a.parameters, hasRestParameter = _a.hasRestParameter; + return hasRestParameter ? + i < parameters.length - 1 ? parameters[i] : ts.last(parameters) : + i < parameters.length ? parameters[i] : undefined; + }); + ts.Debug.assert(symbols.length !== 0); + parameters.push(createCombinedSymbolFromTypes(symbols, ts.mapDefined(candidates, function (candidate) { return tryGetTypeAtPosition(candidate, i); }))); + }; + for (var i = 0; i < maxNonRestParam; i++) { + _loop_7(i); + } + var restParameterSymbols = ts.mapDefined(candidates, function (c) { return c.hasRestParameter ? ts.last(c.parameters) : undefined; }); + var hasRestParameter = restParameterSymbols.length !== 0; + if (hasRestParameter) { + var type = createArrayType(getUnionType(ts.mapDefined(candidates, tryGetRestTypeOfSignature), 2 /* Subtype */)); + parameters.push(createCombinedSymbolForOverloadFailure(restParameterSymbols, type)); + } + return createSignature(candidates[0].declaration, + /*typeParameters*/ undefined, // Before calling this we tested for `!candidates.some(c => !!c.typeParameters)`. + thisParameter, parameters, + /*resolvedReturnType*/ getIntersectionType(candidates.map(getReturnTypeOfSignature)), + /*typePredicate*/ undefined, minArgumentCount, hasRestParameter, + /*hasLiteralTypes*/ candidates.some(function (c) { return c.hasLiteralTypes; })); + } + function getNumNonRestParameters(signature) { + var numParams = signature.parameters.length; + return signature.hasRestParameter ? numParams - 1 : numParams; + } + function createCombinedSymbolFromTypes(sources, types) { + return createCombinedSymbolForOverloadFailure(sources, getUnionType(types, 2 /* Subtype */)); + } + function createCombinedSymbolForOverloadFailure(sources, type) { + // This function is currently only used for erroneous overloads, so it's good enough to just use the first source. + return createSymbolWithType(ts.first(sources), type); + } + function pickLongestCandidateSignature(node, candidates, args) { + // Pick the longest signature. This way we can get a contextual type for cases like: + // declare function f(a: { xa: number; xb: number; }, b: number); + // f({ | + // Also, use explicitly-supplied type arguments if they are provided, so we can get a contextual signature in cases like: + // declare function f(k: keyof T); + // f(" + var bestIndex = getLongestCandidateIndex(candidates, apparentArgumentCount === undefined ? args.length : apparentArgumentCount); + var candidate = candidates[bestIndex]; + var typeParameters = candidate.typeParameters; + if (!typeParameters) { + return candidate; + } + var typeArgumentNodes = callLikeExpressionMayHaveTypeArguments(node) ? node.typeArguments : undefined; + var instantiated = typeArgumentNodes + ? createSignatureInstantiation(candidate, getTypeArgumentsFromNodes(typeArgumentNodes, typeParameters, ts.isInJSFile(node))) + : inferSignatureInstantiationForOverloadFailure(node, typeParameters, candidate, args); + candidates[bestIndex] = instantiated; + return instantiated; + } + function getTypeArgumentsFromNodes(typeArgumentNodes, typeParameters, isJs) { + var typeArguments = typeArgumentNodes.map(getTypeOfNode); + while (typeArguments.length > typeParameters.length) { + typeArguments.pop(); + } + while (typeArguments.length < typeParameters.length) { + typeArguments.push(getConstraintOfTypeParameter(typeParameters[typeArguments.length]) || getDefaultTypeArgumentType(isJs)); + } + return typeArguments; + } + function inferSignatureInstantiationForOverloadFailure(node, typeParameters, candidate, args) { + var inferenceContext = createInferenceContext(typeParameters, candidate, /*flags*/ ts.isInJSFile(node) ? 2 /* AnyDefault */ : 0 /* None */); + var typeArgumentTypes = inferTypeArguments(node, candidate, args, getExcludeArgument(args), inferenceContext); + return createSignatureInstantiation(candidate, typeArgumentTypes); + } + function getLongestCandidateIndex(candidates, argsCount) { + var maxParamsIndex = -1; + var maxParams = -1; + for (var i = 0; i < candidates.length; i++) { + var candidate = candidates[i]; + var paramCount = getParameterCount(candidate); + if (hasEffectiveRestParameter(candidate) || paramCount >= argsCount) { + return i; + } + if (paramCount > maxParams) { + maxParams = paramCount; + maxParamsIndex = i; + } + } + return maxParamsIndex; + } + function resolveCallExpression(node, candidatesOutArray, isForSignatureHelp) { + if (node.expression.kind === 98 /* SuperKeyword */) { + var superType = checkSuperExpression(node.expression); + if (isTypeAny(superType)) { + for (var _i = 0, _a = node.arguments; _i < _a.length; _i++) { + var arg = _a[_i]; + checkExpression(arg); // Still visit arguments so they get marked for visibility, etc + } + return anySignature; + } + if (superType !== errorType) { + // In super call, the candidate signatures are the matching arity signatures of the base constructor function instantiated + // with the type arguments specified in the extends clause. + var baseTypeNode = ts.getEffectiveBaseTypeNode(ts.getContainingClass(node)); + if (baseTypeNode) { + var baseConstructors = getInstantiatedConstructorsForTypeArguments(superType, baseTypeNode.typeArguments, baseTypeNode); + return resolveCall(node, baseConstructors, candidatesOutArray, isForSignatureHelp); + } + } + return resolveUntypedCall(node); + } + var funcType = checkNonNullExpression(node.expression, ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_null, ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_undefined, ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_null_or_undefined); + if (funcType === silentNeverType) { + return silentNeverSignature; + } + var apparentType = getApparentType(funcType); + if (apparentType === errorType) { + // Another error has already been reported + return resolveErrorCall(node); + } + // Technically, this signatures list may be incomplete. We are taking the apparent type, + // but we are not including call signatures that may have been added to the Object or + // Function interface, since they have none by default. This is a bit of a leap of faith + // that the user will not add any. + var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */); + var numConstructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */).length; + // TS 1.0 Spec: 4.12 + // In an untyped function call no TypeArgs are permitted, Args can be any argument list, no contextual + // types are provided for the argument expressions, and the result is always of type Any. + if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, numConstructSignatures)) { + // The unknownType indicates that an error already occurred (and was reported). No + // need to report another error in this case. + if (funcType !== errorType && node.typeArguments) { + error(node, ts.Diagnostics.Untyped_function_calls_may_not_accept_type_arguments); + } + return resolveUntypedCall(node); + } + // If FuncExpr's apparent type(section 3.8.1) is a function type, the call is a typed function call. + // TypeScript employs overload resolution in typed function calls in order to support functions + // with multiple call signatures. + if (!callSignatures.length) { + if (numConstructSignatures) { + error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType)); + } + else { + var relatedInformation = void 0; + if (node.arguments.length === 1) { + var text = ts.getSourceFileOfNode(node).text; + if (ts.isLineBreak(text.charCodeAt(ts.skipTrivia(text, node.expression.end, /* stopAfterLineBreak */ true) - 1))) { + relatedInformation = ts.createDiagnosticForNode(node.expression, ts.Diagnostics.It_is_highly_likely_that_you_are_missing_a_semicolon); + } + } + invocationError(node, apparentType, 0 /* Call */, relatedInformation); + } + return resolveErrorCall(node); + } + // If the function is explicitly marked with `@class`, then it must be constructed. + if (callSignatures.some(function (sig) { return ts.isInJSFile(sig.declaration) && !!ts.getJSDocClassTag(sig.declaration); })) { + error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType)); + return resolveErrorCall(node); + } + return resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp); + } + /** + * TS 1.0 spec: 4.12 + * If FuncExpr is of type Any, or of an object type that has no call or construct signatures + * but is a subtype of the Function interface, the call is an untyped function call. + */ + function isUntypedFunctionCall(funcType, apparentFuncType, numCallSignatures, numConstructSignatures) { + // We exclude union types because we may have a union of function types that happen to have no common signatures. + return isTypeAny(funcType) || isTypeAny(apparentFuncType) && funcType.flags & 262144 /* TypeParameter */ || + !numCallSignatures && !numConstructSignatures && !(apparentFuncType.flags & (1048576 /* Union */ | 131072 /* Never */)) && isTypeAssignableTo(funcType, globalFunctionType); + } + function resolveNewExpression(node, candidatesOutArray, isForSignatureHelp) { + if (node.arguments && languageVersion < 1 /* ES5 */) { + var spreadIndex = getSpreadArgumentIndex(node.arguments); + if (spreadIndex >= 0) { + error(node.arguments[spreadIndex], ts.Diagnostics.Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher); + } + } + var expressionType = checkNonNullExpression(node.expression); + if (expressionType === silentNeverType) { + return silentNeverSignature; + } + // If expressionType's apparent type(section 3.8.1) is an object type with one or + // more construct signatures, the expression is processed in the same manner as a + // function call, but using the construct signatures as the initial set of candidate + // signatures for overload resolution. The result type of the function call becomes + // the result type of the operation. + expressionType = getApparentType(expressionType); + if (expressionType === errorType) { + // Another error has already been reported + return resolveErrorCall(node); + } + // TS 1.0 spec: 4.11 + // If expressionType is of type Any, Args can be any argument + // list and the result of the operation is of type Any. + if (isTypeAny(expressionType)) { + if (node.typeArguments) { + error(node, ts.Diagnostics.Untyped_function_calls_may_not_accept_type_arguments); + } + return resolveUntypedCall(node); + } + // Technically, this signatures list may be incomplete. We are taking the apparent type, + // but we are not including construct signatures that may have been added to the Object or + // Function interface, since they have none by default. This is a bit of a leap of faith + // that the user will not add any. + var constructSignatures = getSignaturesOfType(expressionType, 1 /* Construct */); + if (constructSignatures.length) { + if (!isConstructorAccessible(node, constructSignatures[0])) { + return resolveErrorCall(node); + } + // If the expression is a class of abstract type, then it cannot be instantiated. + // Note, only class declarations can be declared abstract. + // In the case of a merged class-module or class-interface declaration, + // only the class declaration node will have the Abstract flag set. + var valueDecl = expressionType.symbol && ts.getClassLikeDeclarationOfSymbol(expressionType.symbol); + if (valueDecl && ts.hasModifier(valueDecl, 128 /* Abstract */)) { + error(node, ts.Diagnostics.Cannot_create_an_instance_of_an_abstract_class); + return resolveErrorCall(node); + } + return resolveCall(node, constructSignatures, candidatesOutArray, isForSignatureHelp); + } + // If expressionType's apparent type is an object type with no construct signatures but + // one or more call signatures, the expression is processed as a function call. A compile-time + // error occurs if the result of the function call is not Void. The type of the result of the + // operation is Any. It is an error to have a Void this type. + var callSignatures = getSignaturesOfType(expressionType, 0 /* Call */); + if (callSignatures.length) { + var signature = resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp); + if (!noImplicitAny) { + if (signature.declaration && !isJSConstructor(signature.declaration) && getReturnTypeOfSignature(signature) !== voidType) { + error(node, ts.Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword); + } + if (getThisTypeOfSignature(signature) === voidType) { + error(node, ts.Diagnostics.A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void); + } + } + return signature; + } + invocationError(node, expressionType, 1 /* Construct */); + return resolveErrorCall(node); + } + function typeHasProtectedAccessibleBase(target, type) { + var baseTypes = getBaseTypes(type); + if (!ts.length(baseTypes)) { + return false; + } + var firstBase = baseTypes[0]; + if (firstBase.flags & 2097152 /* Intersection */) { + var types = firstBase.types; + var mixinCount = ts.countWhere(types, isMixinConstructorType); + var i = 0; + for (var _i = 0, _a = firstBase.types; _i < _a.length; _i++) { + var intersectionMember = _a[_i]; + i++; + // We want to ignore mixin ctors + if (mixinCount === 0 || mixinCount === types.length && i === 0 || !isMixinConstructorType(intersectionMember)) { + if (ts.getObjectFlags(intersectionMember) & (1 /* Class */ | 2 /* Interface */)) { + if (intersectionMember.symbol === target) { + return true; + } + if (typeHasProtectedAccessibleBase(target, intersectionMember)) { + return true; + } + } + } + } + return false; + } + if (firstBase.symbol === target) { + return true; + } + return typeHasProtectedAccessibleBase(target, firstBase); + } + function isConstructorAccessible(node, signature) { + if (!signature || !signature.declaration) { + return true; + } + var declaration = signature.declaration; + var modifiers = ts.getSelectedModifierFlags(declaration, 24 /* NonPublicAccessibilityModifier */); + // Public constructor is accessible. + if (!modifiers) { + return true; + } + var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(declaration.parent.symbol); + var declaringClass = getDeclaredTypeOfSymbol(declaration.parent.symbol); + // A private or protected constructor can only be instantiated within its own class (or a subclass, for protected) + if (!isNodeWithinClass(node, declaringClassDeclaration)) { + var containingClass = ts.getContainingClass(node); + if (containingClass && modifiers & 16 /* Protected */) { + var containingType = getTypeOfNode(containingClass); + if (typeHasProtectedAccessibleBase(declaration.parent.symbol, containingType)) { + return true; + } + } + if (modifiers & 8 /* Private */) { + error(node, ts.Diagnostics.Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration, typeToString(declaringClass)); + } + if (modifiers & 16 /* Protected */) { + error(node, ts.Diagnostics.Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration, typeToString(declaringClass)); + } + return false; + } + return true; + } + function invocationError(node, apparentType, kind, relatedInformation) { + var diagnostic = error(node, (kind === 0 /* Call */ ? + ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures : + ts.Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature), typeToString(apparentType)); + invocationErrorRecovery(apparentType, kind, relatedInformation ? addRelatedInfo(diagnostic, relatedInformation) : diagnostic); + } + function invocationErrorRecovery(apparentType, kind, diagnostic) { + if (!apparentType.symbol) { + return; + } + var importNode = getSymbolLinks(apparentType.symbol).originatingImport; + // Create a diagnostic on the originating import if possible onto which we can attach a quickfix + // An import call expression cannot be rewritten into another form to correct the error - the only solution is to use `.default` at the use-site + if (importNode && !ts.isImportCall(importNode)) { + var sigs = getSignaturesOfType(getTypeOfSymbol(getSymbolLinks(apparentType.symbol).target), kind); + if (!sigs || !sigs.length) + return; + addRelatedInfo(diagnostic, ts.createDiagnosticForNode(importNode, ts.Diagnostics.Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_Consider_using_a_default_import_or_import_require_here_instead)); + } + } + function resolveTaggedTemplateExpression(node, candidatesOutArray, isForSignatureHelp) { + var tagType = checkExpression(node.tag); + var apparentType = getApparentType(tagType); + if (apparentType === errorType) { + // Another error has already been reported + return resolveErrorCall(node); + } + var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */); + var numConstructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */).length; + if (isUntypedFunctionCall(tagType, apparentType, callSignatures.length, numConstructSignatures)) { + return resolveUntypedCall(node); + } + if (!callSignatures.length) { + invocationError(node, apparentType, 0 /* Call */); + return resolveErrorCall(node); + } + return resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp); + } + /** + * Gets the localized diagnostic head message to use for errors when resolving a decorator as a call expression. + */ + function getDiagnosticHeadMessageForDecoratorResolution(node) { + switch (node.parent.kind) { + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + return ts.Diagnostics.Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression; + case 151 /* Parameter */: + return ts.Diagnostics.Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression; + case 154 /* PropertyDeclaration */: + return ts.Diagnostics.Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression; + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + return ts.Diagnostics.Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression; + default: + return ts.Debug.fail(); + } + } + /** + * Resolves a decorator as if it were a call expression. + */ + function resolveDecorator(node, candidatesOutArray, isForSignatureHelp) { + var funcType = checkExpression(node.expression); + var apparentType = getApparentType(funcType); + if (apparentType === errorType) { + return resolveErrorCall(node); + } + var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */); + var numConstructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */).length; + if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, numConstructSignatures)) { + return resolveUntypedCall(node); + } + if (isPotentiallyUncalledDecorator(node, callSignatures)) { + var nodeStr = ts.getTextOfNode(node.expression, /*includeTrivia*/ false); + error(node, ts.Diagnostics._0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write_0, nodeStr); + return resolveErrorCall(node); + } + var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); + if (!callSignatures.length) { + var errorInfo = ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures, typeToString(apparentType)); + errorInfo = ts.chainDiagnosticMessages(errorInfo, headMessage); + var diag = ts.createDiagnosticForNodeFromMessageChain(node, errorInfo); + diagnostics.add(diag); + invocationErrorRecovery(apparentType, 0 /* Call */, diag); + return resolveErrorCall(node); + } + return resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp, headMessage); + } + function createSignatureForJSXIntrinsic(node, result) { + var namespace = getJsxNamespaceAt(node); + var exports = namespace && getExportsOfSymbol(namespace); + // We fake up a SFC signature for each intrinsic, however a more specific per-element signature drawn from the JSX declaration + // file would probably be preferable. + var typeSymbol = exports && getSymbol(exports, JsxNames.Element, 67897832 /* Type */); + var returnNode = typeSymbol && nodeBuilder.symbolToEntityName(typeSymbol, 67897832 /* Type */, node); + var declaration = ts.createFunctionTypeNode(/*typeParameters*/ undefined, [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotdotdot*/ undefined, "props", /*questionMark*/ undefined, nodeBuilder.typeToTypeNode(result, node))], returnNode ? ts.createTypeReferenceNode(returnNode, /*typeArguments*/ undefined) : ts.createKeywordTypeNode(120 /* AnyKeyword */)); + var parameterSymbol = createSymbol(1 /* FunctionScopedVariable */, "props"); + parameterSymbol.type = result; + return createSignature(declaration, + /*typeParameters*/ undefined, + /*thisParameter*/ undefined, [parameterSymbol], typeSymbol ? getDeclaredTypeOfSymbol(typeSymbol) : errorType, + /*returnTypePredicate*/ undefined, 1, + /*hasRestparameter*/ false, + /*hasLiteralTypes*/ false); + } + function resolveJsxOpeningLikeElement(node, candidatesOutArray, isForSignatureHelp) { + if (isJsxIntrinsicIdentifier(node.tagName)) { + var result = getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node); + var fakeSignature = createSignatureForJSXIntrinsic(node, result); + checkTypeAssignableToAndOptionallyElaborate(checkExpressionWithContextualType(node.attributes, getEffectiveFirstArgumentForJsxSignature(fakeSignature, node), /*mapper*/ undefined), result, node.tagName, node.attributes); + return fakeSignature; + } + var exprTypes = checkExpression(node.tagName); + var apparentType = getApparentType(exprTypes); + if (apparentType === errorType) { + return resolveErrorCall(node); + } + var signatures = getUninstantiatedJsxSignaturesOfType(exprTypes, node); + if (isUntypedFunctionCall(exprTypes, apparentType, signatures.length, /*constructSignatures*/ 0)) { + return resolveUntypedCall(node); + } + if (signatures.length === 0) { + // We found no signatures at all, which is an error + error(node.tagName, ts.Diagnostics.JSX_element_type_0_does_not_have_any_construct_or_call_signatures, ts.getTextOfNode(node.tagName)); + return resolveErrorCall(node); + } + return resolveCall(node, signatures, candidatesOutArray, isForSignatureHelp); + } + /** + * Sometimes, we have a decorator that could accept zero arguments, + * but is receiving too many arguments as part of the decorator invocation. + * In those cases, a user may have meant to *call* the expression before using it as a decorator. + */ + function isPotentiallyUncalledDecorator(decorator, signatures) { + return signatures.length && ts.every(signatures, function (signature) { + return signature.minArgumentCount === 0 && + !signature.hasRestParameter && + signature.parameters.length < getDecoratorArgumentCount(decorator, signature); + }); + } + function resolveSignature(node, candidatesOutArray, isForSignatureHelp) { + switch (node.kind) { + case 191 /* CallExpression */: + return resolveCallExpression(node, candidatesOutArray, isForSignatureHelp); + case 192 /* NewExpression */: + return resolveNewExpression(node, candidatesOutArray, isForSignatureHelp); + case 193 /* TaggedTemplateExpression */: + return resolveTaggedTemplateExpression(node, candidatesOutArray, isForSignatureHelp); + case 152 /* Decorator */: + return resolveDecorator(node, candidatesOutArray, isForSignatureHelp); + case 262 /* JsxOpeningElement */: + case 261 /* JsxSelfClosingElement */: + return resolveJsxOpeningLikeElement(node, candidatesOutArray, isForSignatureHelp); + } + throw ts.Debug.assertNever(node, "Branch in 'resolveSignature' should be unreachable."); + } + /** + * Resolve a signature of a given call-like expression. + * @param node a call-like expression to try resolve a signature for + * @param candidatesOutArray an array of signature to be filled in by the function. It is passed by signature help in the language service; + * the function will fill it up with appropriate candidate signatures + * @return a signature of the call-like expression or undefined if one can't be found + */ + function getResolvedSignature(node, candidatesOutArray, isForSignatureHelp) { + if (isForSignatureHelp === void 0) { isForSignatureHelp = false; } + var links = getNodeLinks(node); + // If getResolvedSignature has already been called, we will have cached the resolvedSignature. + // However, it is possible that either candidatesOutArray was not passed in the first time, + // or that a different candidatesOutArray was passed in. Therefore, we need to redo the work + // to correctly fill the candidatesOutArray. + var cached = links.resolvedSignature; + if (cached && cached !== resolvingSignature && !candidatesOutArray) { + return cached; + } + links.resolvedSignature = resolvingSignature; + var result = resolveSignature(node, candidatesOutArray, isForSignatureHelp); + // If signature resolution originated in control flow type analysis (for example to compute the + // assigned type in a flow assignment) we don't cache the result as it may be based on temporary + // types from the control flow analysis. + links.resolvedSignature = flowLoopStart === flowLoopCount ? result : cached; + return result; + } + /** + * Indicates whether a declaration can be treated as a constructor in a JavaScript + * file. + */ + function isJSConstructor(node) { + if (!node || !ts.isInJSFile(node)) { + return false; + } + var func = ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node) ? node : + ts.isVariableDeclaration(node) && node.initializer && ts.isFunctionExpression(node.initializer) ? node.initializer : + undefined; + if (func) { + // If the node has a @class tag, treat it like a constructor. + if (ts.getJSDocClassTag(node)) + return true; + // If the symbol of the node has members, treat it like a constructor. + var symbol = getSymbolOfNode(func); + return !!symbol && symbol.members !== undefined; + } + return false; + } + function isJSConstructorType(type) { + if (type.flags & 524288 /* Object */) { + var resolved = resolveStructuredTypeMembers(type); + return resolved.callSignatures.length === 1 && isJSConstructor(resolved.callSignatures[0].declaration); + } + return false; + } + function getJSClassType(symbol) { + var inferred; + if (isJSConstructor(symbol.valueDeclaration)) { + inferred = getInferredClassType(symbol); + } + var assigned = getAssignedClassType(symbol); + var valueType = getTypeOfSymbol(symbol); + if (valueType.symbol && !isInferredClassType(valueType) && isJSConstructor(valueType.symbol.valueDeclaration)) { + inferred = getInferredClassType(valueType.symbol); + } + return assigned && inferred ? + getIntersectionType([inferred, assigned]) : + assigned || inferred; + } + function getAssignedClassType(symbol) { + var decl = symbol.valueDeclaration; + var assignmentSymbol = decl && decl.parent && + (ts.isFunctionDeclaration(decl) && getSymbolOfNode(decl) || + ts.isBinaryExpression(decl.parent) && getSymbolOfNode(decl.parent.left) || + ts.isVariableDeclaration(decl.parent) && getSymbolOfNode(decl.parent)); + var prototype = assignmentSymbol && assignmentSymbol.exports && assignmentSymbol.exports.get("prototype"); + var init = prototype && prototype.valueDeclaration && getAssignedJSPrototype(prototype.valueDeclaration); + return init ? checkExpression(init) : undefined; + } + function getAssignedJSPrototype(node) { + if (!node.parent) { + return false; + } + var parent = node.parent; + while (parent && parent.kind === 189 /* PropertyAccessExpression */) { + parent = parent.parent; + } + if (parent && ts.isBinaryExpression(parent) && ts.isPrototypeAccess(parent.left) && parent.operatorToken.kind === 59 /* EqualsToken */) { + var right = ts.getInitializerOfBinaryExpression(parent); + return ts.isObjectLiteralExpression(right) && right; + } + } + function getInferredClassType(symbol) { + var links = getSymbolLinks(symbol); + if (!links.inferredClassType) { + links.inferredClassType = createAnonymousType(symbol, getMembersOfSymbol(symbol) || emptySymbols, ts.emptyArray, ts.emptyArray, /*stringIndexType*/ undefined, /*numberIndexType*/ undefined); + } + return links.inferredClassType; + } + function isInferredClassType(type) { + return type.symbol + && ts.getObjectFlags(type) & 16 /* Anonymous */ + && getSymbolLinks(type.symbol).inferredClassType === type; + } + /** + * Syntactically and semantically checks a call or new expression. + * @param node The call/new expression to be checked. + * @returns On success, the expression's signature's return type. On failure, anyType. + */ + function checkCallExpression(node) { + if (!checkGrammarTypeArguments(node, node.typeArguments)) + checkGrammarArguments(node.arguments); + var signature = getResolvedSignature(node); + if (node.expression.kind === 98 /* SuperKeyword */) { + return voidType; + } + if (node.kind === 192 /* NewExpression */) { + var declaration = signature.declaration; + if (declaration && + declaration.kind !== 157 /* Constructor */ && + declaration.kind !== 161 /* ConstructSignature */ && + declaration.kind !== 166 /* ConstructorType */ && + !ts.isJSDocConstructSignature(declaration)) { + // When resolved signature is a call signature (and not a construct signature) the result type is any, unless + // the declaring function had members created through 'x.prototype.y = expr' or 'this.y = expr' psuedodeclarations + // in a JS file + // Note:JS inferred classes might come from a variable declaration instead of a function declaration. + // In this case, using getResolvedSymbol directly is required to avoid losing the members from the declaration. + var funcSymbol = checkExpression(node.expression).symbol; + if (!funcSymbol && node.expression.kind === 72 /* Identifier */) { + funcSymbol = getResolvedSymbol(node.expression); + } + var type = funcSymbol && getJSClassType(funcSymbol); + if (type) { + return signature.target ? instantiateType(type, signature.mapper) : type; + } + if (noImplicitAny) { + error(node, ts.Diagnostics.new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type); + } + return anyType; + } + } + // In JavaScript files, calls to any identifier 'require' are treated as external module imports + if (ts.isInJSFile(node) && isCommonJsRequire(node)) { + return resolveExternalModuleTypeByLiteral(node.arguments[0]); + } + var returnType = getReturnTypeOfSignature(signature); + // Treat any call to the global 'Symbol' function that is part of a const variable or readonly property + // as a fresh unique symbol literal type. + if (returnType.flags & 12288 /* ESSymbolLike */ && isSymbolOrSymbolForCall(node)) { + return getESSymbolLikeTypeForNode(ts.walkUpParenthesizedExpressions(node.parent)); + } + var jsAssignmentType; + if (ts.isInJSFile(node)) { + var decl = ts.getDeclarationOfExpando(node); + if (decl) { + var jsSymbol = getSymbolOfNode(decl); + if (jsSymbol && ts.hasEntries(jsSymbol.exports)) { + jsAssignmentType = createAnonymousType(jsSymbol, jsSymbol.exports, ts.emptyArray, ts.emptyArray, undefined, undefined); + jsAssignmentType.objectFlags |= 16384 /* JSLiteral */; + } + } + } + return jsAssignmentType ? getIntersectionType([returnType, jsAssignmentType]) : returnType; + } + function isSymbolOrSymbolForCall(node) { + if (!ts.isCallExpression(node)) + return false; + var left = node.expression; + if (ts.isPropertyAccessExpression(left) && left.name.escapedText === "for") { + left = left.expression; + } + if (!ts.isIdentifier(left) || left.escapedText !== "Symbol") { + return false; + } + // make sure `Symbol` is the global symbol + var globalESSymbol = getGlobalESSymbolConstructorSymbol(/*reportErrors*/ false); + if (!globalESSymbol) { + return false; + } + return globalESSymbol === resolveName(left, "Symbol", 67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); + } + function checkImportCallExpression(node) { + // Check grammar of dynamic import + if (!checkGrammarArguments(node.arguments)) + checkGrammarImportCallExpression(node); + if (node.arguments.length === 0) { + return createPromiseReturnType(node, anyType); + } + var specifier = node.arguments[0]; + var specifierType = checkExpressionCached(specifier); + // Even though multiple arguments is grammatically incorrect, type-check extra arguments for completion + for (var i = 1; i < node.arguments.length; ++i) { + checkExpressionCached(node.arguments[i]); + } + if (specifierType.flags & 32768 /* Undefined */ || specifierType.flags & 65536 /* Null */ || !isTypeAssignableTo(specifierType, stringType)) { + error(specifier, ts.Diagnostics.Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0, typeToString(specifierType)); + } + // resolveExternalModuleName will return undefined if the moduleReferenceExpression is not a string literal + var moduleSymbol = resolveExternalModuleName(node, specifier); + if (moduleSymbol) { + var esModuleSymbol = resolveESModuleSymbol(moduleSymbol, specifier, /*dontRecursivelyResolve*/ true); + if (esModuleSymbol) { + return createPromiseReturnType(node, getTypeWithSyntheticDefaultImportType(getTypeOfSymbol(esModuleSymbol), esModuleSymbol, moduleSymbol)); + } + } + return createPromiseReturnType(node, anyType); + } + function getTypeWithSyntheticDefaultImportType(type, symbol, originalSymbol) { + if (allowSyntheticDefaultImports && type && type !== errorType) { + var synthType = type; + if (!synthType.syntheticType) { + var file = ts.find(originalSymbol.declarations, ts.isSourceFile); + var hasSyntheticDefault = canHaveSyntheticDefault(file, originalSymbol, /*dontResolveAlias*/ false); + if (hasSyntheticDefault) { + var memberTable = ts.createSymbolTable(); + var newSymbol = createSymbol(2097152 /* Alias */, "default" /* Default */); + newSymbol.nameType = getLiteralType("default"); + newSymbol.target = resolveSymbol(symbol); + memberTable.set("default" /* Default */, newSymbol); + var anonymousSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */); + var defaultContainingObject = createAnonymousType(anonymousSymbol, memberTable, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined); + anonymousSymbol.type = defaultContainingObject; + synthType.syntheticType = isValidSpreadType(type) ? getSpreadType(type, defaultContainingObject, anonymousSymbol, /*typeFLags*/ 0, /*objectFlags*/ 0) : defaultContainingObject; + } + else { + synthType.syntheticType = type; + } + } + return synthType.syntheticType; + } + return type; + } + function isCommonJsRequire(node) { + if (!ts.isRequireCall(node, /*checkArgumentIsStringLiteralLike*/ true)) { + return false; + } + // Make sure require is not a local function + if (!ts.isIdentifier(node.expression)) + return ts.Debug.fail(); + var resolvedRequire = resolveName(node.expression, node.expression.escapedText, 67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); // TODO: GH#18217 + if (resolvedRequire === requireSymbol) { + return true; + } + // project includes symbol named 'require' - make sure that it is ambient and local non-alias + if (resolvedRequire.flags & 2097152 /* Alias */) { + return false; + } + var targetDeclarationKind = resolvedRequire.flags & 16 /* Function */ + ? 239 /* FunctionDeclaration */ + : resolvedRequire.flags & 3 /* Variable */ + ? 237 /* VariableDeclaration */ + : 0 /* Unknown */; + if (targetDeclarationKind !== 0 /* Unknown */) { + var decl = ts.getDeclarationOfKind(resolvedRequire, targetDeclarationKind); + // function/variable declaration should be ambient + return !!decl && !!(decl.flags & 4194304 /* Ambient */); + } + return false; + } + function checkTaggedTemplateExpression(node) { + checkGrammarTypeArguments(node, node.typeArguments); + if (languageVersion < 2 /* ES2015 */) { + checkExternalEmitHelpers(node, 65536 /* MakeTemplateObject */); + } + return getReturnTypeOfSignature(getResolvedSignature(node)); + } + function checkAssertion(node) { + return checkAssertionWorker(node, node.type, node.expression); + } + function checkAssertionWorker(errNode, type, expression, checkMode) { + var exprType = getRegularTypeOfObjectLiteral(getBaseTypeOfLiteralType(checkExpression(expression, checkMode))); + checkSourceElement(type); + var targetType = getTypeFromTypeNode(type); + if (produceDiagnostics && targetType !== errorType) { + var widenedType = getWidenedType(exprType); + if (!isTypeComparableTo(targetType, widenedType)) { + checkTypeComparableTo(exprType, targetType, errNode, ts.Diagnostics.Conversion_of_type_0_to_type_1_may_be_a_mistake_because_neither_type_sufficiently_overlaps_with_the_other_If_this_was_intentional_convert_the_expression_to_unknown_first); + } + } + return targetType; + } + function checkNonNullAssertion(node) { + return getNonNullableType(checkExpression(node.expression)); + } + function checkMetaProperty(node) { + checkGrammarMetaProperty(node); + if (node.keywordToken === 95 /* NewKeyword */) { + return checkNewTargetMetaProperty(node); + } + if (node.keywordToken === 92 /* ImportKeyword */) { + return checkImportMetaProperty(node); + } + return ts.Debug.assertNever(node.keywordToken); + } + function checkNewTargetMetaProperty(node) { + var container = ts.getNewTargetContainer(node); + if (!container) { + error(node, ts.Diagnostics.Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constructor, "new.target"); + return errorType; + } + else if (container.kind === 157 /* Constructor */) { + var symbol = getSymbolOfNode(container.parent); + return getTypeOfSymbol(symbol); + } + else { + var symbol = getSymbolOfNode(container); + return getTypeOfSymbol(symbol); + } + } + function checkImportMetaProperty(node) { + if (languageVersion < 6 /* ESNext */ || moduleKind < ts.ModuleKind.ESNext) { + error(node, ts.Diagnostics.The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_options); + } + var file = ts.getSourceFileOfNode(node); + ts.Debug.assert(!!(file.flags & 1048576 /* PossiblyContainsImportMeta */), "Containing file is missing import meta node flag."); + ts.Debug.assert(!!file.externalModuleIndicator, "Containing file should be a module."); + return node.name.escapedText === "meta" ? getGlobalImportMetaType() : errorType; + } + function getTypeOfParameter(symbol) { + var type = getTypeOfSymbol(symbol); + if (strictNullChecks) { + var declaration = symbol.valueDeclaration; + if (declaration && ts.hasInitializer(declaration)) { + return getOptionalType(type); + } + } + return type; + } + function getParameterNameAtPosition(signature, pos) { + var paramCount = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); + if (pos < paramCount) { + return signature.parameters[pos].escapedName; + } + var restParameter = signature.parameters[paramCount] || unknownSymbol; + var restType = getTypeOfSymbol(restParameter); + if (isTupleType(restType)) { + var associatedNames = restType.target.associatedNames; + var index = pos - paramCount; + return associatedNames ? associatedNames[index] : restParameter.escapedName + "_" + index; + } + return restParameter.escapedName; + } + function getTypeAtPosition(signature, pos) { + return tryGetTypeAtPosition(signature, pos) || anyType; + } + function tryGetTypeAtPosition(signature, pos) { + var paramCount = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); + if (pos < paramCount) { + return getTypeOfParameter(signature.parameters[pos]); + } + if (signature.hasRestParameter) { + var restType = getTypeOfSymbol(signature.parameters[paramCount]); + if (isTupleType(restType)) { + if (pos - paramCount < getLengthOfTupleType(restType)) { + return restType.typeArguments[pos - paramCount]; + } + return getRestTypeOfTupleType(restType); + } + return getIndexTypeOfType(restType, 1 /* Number */); + } + return undefined; + } + function getRestTypeAtPosition(source, pos) { + var paramCount = getParameterCount(source); + var restType = getEffectiveRestType(source); + if (restType && pos === paramCount - 1) { + return restType; + } + var start = restType ? Math.min(pos, paramCount - 1) : pos; + var types = []; + var names = []; + for (var i = start; i < paramCount; i++) { + types.push(getTypeAtPosition(source, i)); + names.push(getParameterNameAtPosition(source, i)); + } + var minArgumentCount = getMinArgumentCount(source); + var minLength = minArgumentCount < start ? 0 : minArgumentCount - start; + return createTupleType(types, minLength, !!restType, names); + } + function getParameterCount(signature) { + var length = signature.parameters.length; + if (signature.hasRestParameter) { + var restType = getTypeOfSymbol(signature.parameters[length - 1]); + if (isTupleType(restType)) { + return length + (restType.typeArguments || ts.emptyArray).length - 1; + } + } + return length; + } + function getMinArgumentCount(signature) { + if (signature.hasRestParameter) { + var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); + if (isTupleType(restType)) { + var minLength = restType.target.minLength; + if (minLength > 0) { + return signature.parameters.length - 1 + minLength; + } + } + } + return signature.minArgumentCount; + } + function hasEffectiveRestParameter(signature) { + if (signature.hasRestParameter) { + var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); + return !isTupleType(restType) || restType.target.hasRestElement; + } + return false; + } + function getEffectiveRestType(signature) { + if (signature.hasRestParameter) { + var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); + return isTupleType(restType) ? getRestArrayTypeOfTupleType(restType) : restType; + } + return undefined; + } + function getNonArrayRestType(signature) { + var restType = getEffectiveRestType(signature); + return restType && !isArrayType(restType) && !isTypeAny(restType) ? restType : undefined; + } + function getTypeOfFirstParameterOfSignature(signature) { + return getTypeOfFirstParameterOfSignatureWithFallback(signature, neverType); + } + function getTypeOfFirstParameterOfSignatureWithFallback(signature, fallbackType) { + return signature.parameters.length > 0 ? getTypeAtPosition(signature, 0) : fallbackType; + } + function inferFromAnnotatedParameters(signature, context, mapper) { + var len = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); + for (var i = 0; i < len; i++) { + var declaration = signature.parameters[i].valueDeclaration; + if (declaration.type) { + var typeNode = ts.getEffectiveTypeAnnotationNode(declaration); + if (typeNode) { + inferTypes(mapper.inferences, getTypeFromTypeNode(typeNode), getTypeAtPosition(context, i)); + } + } + } + } + function assignContextualParameterTypes(signature, context) { + signature.typeParameters = context.typeParameters; + if (context.thisParameter) { + var parameter = signature.thisParameter; + if (!parameter || parameter.valueDeclaration && !parameter.valueDeclaration.type) { + if (!parameter) { + signature.thisParameter = createSymbolWithType(context.thisParameter, /*type*/ undefined); + } + assignTypeToParameterAndFixTypeParameters(signature.thisParameter, getTypeOfSymbol(context.thisParameter)); + } + } + var len = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); + for (var i = 0; i < len; i++) { + var parameter = signature.parameters[i]; + if (!ts.getEffectiveTypeAnnotationNode(parameter.valueDeclaration)) { + var contextualParameterType = getTypeAtPosition(context, i); + assignTypeToParameterAndFixTypeParameters(parameter, contextualParameterType); + } + } + if (signature.hasRestParameter) { + // parameter might be a transient symbol generated by use of `arguments` in the function body. + var parameter = ts.last(signature.parameters); + if (isTransientSymbol(parameter) || !ts.getEffectiveTypeAnnotationNode(parameter.valueDeclaration)) { + var contextualParameterType = getRestTypeAtPosition(context, len); + assignTypeToParameterAndFixTypeParameters(parameter, contextualParameterType); + } + } + } + // When contextual typing assigns a type to a parameter that contains a binding pattern, we also need to push + // the destructured type into the contained binding elements. + function assignBindingElementTypes(pattern) { + for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (!ts.isOmittedExpression(element)) { + if (element.name.kind === 72 /* Identifier */) { + getSymbolLinks(getSymbolOfNode(element)).type = getTypeForBindingElement(element); + } + else { + assignBindingElementTypes(element.name); + } + } + } + } + function assignTypeToParameterAndFixTypeParameters(parameter, contextualType) { + var links = getSymbolLinks(parameter); + if (!links.type) { + links.type = contextualType; + var decl = parameter.valueDeclaration; + if (decl.name.kind !== 72 /* Identifier */) { + // if inference didn't come up with anything but {}, fall back to the binding pattern if present. + if (links.type === emptyObjectType) { + links.type = getTypeFromBindingPattern(decl.name); + } + assignBindingElementTypes(decl.name); + } + } + } + function createPromiseType(promisedType) { + // creates a `Promise` type where `T` is the promisedType argument + var globalPromiseType = getGlobalPromiseType(/*reportErrors*/ true); + if (globalPromiseType !== emptyGenericType) { + // if the promised type is itself a promise, get the underlying type; otherwise, fallback to the promised type + promisedType = getAwaitedType(promisedType) || emptyObjectType; + return createTypeReference(globalPromiseType, [promisedType]); + } + return emptyObjectType; + } + function createPromiseLikeType(promisedType) { + // creates a `PromiseLike` type where `T` is the promisedType argument + var globalPromiseLikeType = getGlobalPromiseLikeType(/*reportErrors*/ true); + if (globalPromiseLikeType !== emptyGenericType) { + // if the promised type is itself a promise, get the underlying type; otherwise, fallback to the promised type + promisedType = getAwaitedType(promisedType) || emptyObjectType; + return createTypeReference(globalPromiseLikeType, [promisedType]); + } + return emptyObjectType; + } + function createPromiseReturnType(func, promisedType) { + var promiseType = createPromiseType(promisedType); + if (promiseType === emptyObjectType) { + error(func, ts.isImportCall(func) ? + ts.Diagnostics.A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option : + ts.Diagnostics.An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option); + return errorType; + } + else if (!getGlobalPromiseConstructorSymbol(/*reportErrors*/ true)) { + error(func, ts.isImportCall(func) ? + ts.Diagnostics.A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option : + ts.Diagnostics.An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option); + } + return promiseType; + } + function getReturnTypeFromBody(func, checkMode) { + if (!func.body) { + return errorType; + } + var functionFlags = ts.getFunctionFlags(func); + var type; + if (func.body.kind !== 218 /* Block */) { + type = checkExpressionCached(func.body, checkMode); + if (functionFlags & 2 /* Async */) { + // From within an async function you can return either a non-promise value or a promise. Any + // Promise/A+ compatible implementation will always assimilate any foreign promise, so the + // return type of the body should be unwrapped to its awaited type, which we will wrap in + // the native Promise type later in this function. + type = checkAwaitedType(type, /*errorNode*/ func, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); + } + } + else { + var types = checkAndAggregateReturnExpressionTypes(func, checkMode); + if (functionFlags & 1 /* Generator */) { // Generator or AsyncGenerator function + types = ts.concatenate(checkAndAggregateYieldOperandTypes(func, checkMode), types); + if (!types || types.length === 0) { + var iterableIteratorAny = functionFlags & 2 /* Async */ + ? createAsyncIterableIteratorType(anyType) // AsyncGenerator function + : createIterableIteratorType(anyType); // Generator function + if (noImplicitAny) { + error(func.asteriskToken, ts.Diagnostics.Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_type, typeToString(iterableIteratorAny)); + } + return iterableIteratorAny; + } + } + else { + if (!types) { + // For an async function, the return type will not be never, but rather a Promise for never. + return functionFlags & 2 /* Async */ + ? createPromiseReturnType(func, neverType) // Async function + : neverType; // Normal function + } + if (types.length === 0) { + // For an async function, the return type will not be void, but rather a Promise for void. + return functionFlags & 2 /* Async */ + ? createPromiseReturnType(func, voidType) // Async function + : voidType; // Normal function + } + } + // Return a union of the return expression types. + type = getUnionType(types, 2 /* Subtype */); + } + var contextualSignature = getContextualSignatureForFunctionLikeDeclaration(func); + if (!contextualSignature) { + reportErrorsFromWidening(func, type); + } + if (isUnitType(type)) { + var contextualType = !contextualSignature ? undefined : + contextualSignature === getSignatureFromDeclaration(func) ? type : + getReturnTypeOfSignature(contextualSignature); + if (contextualType) { + switch (functionFlags & 3 /* AsyncGenerator */) { + case 3 /* AsyncGenerator */: + contextualType = getIteratedTypeOfGenerator(contextualType, /*isAsyncGenerator*/ true); + break; + case 1 /* Generator */: + contextualType = getIteratedTypeOfGenerator(contextualType, /*isAsyncGenerator*/ false); + break; + case 2 /* Async */: + contextualType = getPromisedTypeOfPromise(contextualType); + break; + } + } + type = getWidenedLiteralLikeTypeForContextualType(type, contextualType); + } + var widenedType = getWidenedType(type); + switch (functionFlags & 3 /* AsyncGenerator */) { + case 3 /* AsyncGenerator */: + return createAsyncIterableIteratorType(widenedType); + case 1 /* Generator */: + return createIterableIteratorType(widenedType); + case 2 /* Async */: + // From within an async function you can return either a non-promise value or a promise. Any + // Promise/A+ compatible implementation will always assimilate any foreign promise, so the + // return type of the body is awaited type of the body, wrapped in a native Promise type. + return createPromiseType(widenedType); + default: + return widenedType; + } + } + function checkAndAggregateYieldOperandTypes(func, checkMode) { + var aggregatedTypes = []; + var isAsync = (ts.getFunctionFlags(func) & 2 /* Async */) !== 0; + ts.forEachYieldExpression(func.body, function (yieldExpression) { + ts.pushIfUnique(aggregatedTypes, getYieldedTypeOfYieldExpression(yieldExpression, isAsync, checkMode)); + }); + return aggregatedTypes; + } + function getYieldedTypeOfYieldExpression(node, isAsync, checkMode) { + var errorNode = node.expression || node; + var expressionType = node.expression ? checkExpression(node.expression, checkMode) : undefinedWideningType; + // A `yield*` expression effectively yields everything that its operand yields + var yieldedType = node.asteriskToken ? checkIteratedTypeOrElementType(expressionType, errorNode, /*allowStringInput*/ false, isAsync) : expressionType; + return !isAsync ? yieldedType : getAwaitedType(yieldedType, errorNode, node.asteriskToken + ? ts.Diagnostics.Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member + : ts.Diagnostics.Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); + } + /** + * Collect the TypeFacts learned from a typeof switch with + * total clauses `witnesses`, and the active clause ranging + * from `start` to `end`. Parameter `hasDefault` denotes + * whether the active clause contains a default clause. + */ + function getFactsFromTypeofSwitch(start, end, witnesses, hasDefault) { + var facts = 0 /* None */; + // When in the default we only collect inequality facts + // because default is 'in theory' a set of infinite + // equalities. + if (hasDefault) { + // Value is not equal to any types after the active clause. + for (var i = end; i < witnesses.length; i++) { + facts |= typeofNEFacts.get(witnesses[i]) || 32768 /* TypeofNEHostObject */; + } + // Remove inequalities for types that appear in the + // active clause because they appear before other + // types collected so far. + for (var i = start; i < end; i++) { + facts &= ~(typeofNEFacts.get(witnesses[i]) || 0); + } + // Add inequalities for types before the active clause unconditionally. + for (var i = 0; i < start; i++) { + facts |= typeofNEFacts.get(witnesses[i]) || 32768 /* TypeofNEHostObject */; + } + } + // When in an active clause without default the set of + // equalities is finite. + else { + // Add equalities for all types in the active clause. + for (var i = start; i < end; i++) { + facts |= typeofEQFacts.get(witnesses[i]) || 128 /* TypeofEQHostObject */; + } + // Remove equalities for types that appear before the + // active clause. + for (var i = 0; i < start; i++) { + facts &= ~(typeofEQFacts.get(witnesses[i]) || 0); + } + } + return facts; + } + function isExhaustiveSwitchStatement(node) { + if (!node.possiblyExhaustive) { + return false; + } + if (node.expression.kind === 199 /* TypeOfExpression */) { + var operandType = getTypeOfExpression(node.expression.expression); + // This cast is safe because the switch is possibly exhaustive and does not contain a default case, so there can be no undefined. + var witnesses = getSwitchClauseTypeOfWitnesses(node); + // notEqualFacts states that the type of the switched value is not equal to every type in the switch. + var notEqualFacts_1 = getFactsFromTypeofSwitch(0, 0, witnesses, /*hasDefault*/ true); + var type_5 = getBaseConstraintOfType(operandType) || operandType; + return !!(filterType(type_5, function (t) { return (getTypeFacts(t) & notEqualFacts_1) === notEqualFacts_1; }).flags & 131072 /* Never */); + } + var type = getTypeOfExpression(node.expression); + if (!isLiteralType(type)) { + return false; + } + var switchTypes = getSwitchClauseTypes(node); + if (!switchTypes.length || ts.some(switchTypes, isNeitherUnitTypeNorNever)) { + return false; + } + return eachTypeContainedIn(mapType(type, getRegularTypeOfLiteralType), switchTypes); + } + function functionHasImplicitReturn(func) { + if (!(func.flags & 128 /* HasImplicitReturn */)) { + return false; + } + if (ts.some(func.body.statements, function (statement) { return statement.kind === 232 /* SwitchStatement */ && isExhaustiveSwitchStatement(statement); })) { + return false; + } + return true; + } + /** NOTE: Return value of `[]` means a different thing than `undefined`. `[]` means func returns `void`, `undefined` means it returns `never`. */ + function checkAndAggregateReturnExpressionTypes(func, checkMode) { + var functionFlags = ts.getFunctionFlags(func); + var aggregatedTypes = []; + var hasReturnWithNoExpression = functionHasImplicitReturn(func); + var hasReturnOfTypeNever = false; + ts.forEachReturnStatement(func.body, function (returnStatement) { + var expr = returnStatement.expression; + if (expr) { + var type = checkExpressionCached(expr, checkMode); + if (functionFlags & 2 /* Async */) { + // From within an async function you can return either a non-promise value or a promise. Any + // Promise/A+ compatible implementation will always assimilate any foreign promise, so the + // return type of the body should be unwrapped to its awaited type, which should be wrapped in + // the native Promise type by the caller. + type = checkAwaitedType(type, func, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); + } + if (type.flags & 131072 /* Never */) { + hasReturnOfTypeNever = true; + } + ts.pushIfUnique(aggregatedTypes, type); + } + else { + hasReturnWithNoExpression = true; + } + }); + if (aggregatedTypes.length === 0 && !hasReturnWithNoExpression && (hasReturnOfTypeNever || mayReturnNever(func))) { + return undefined; + } + if (strictNullChecks && aggregatedTypes.length && hasReturnWithNoExpression && + !(isJSConstructor(func) && aggregatedTypes.some(function (t) { return t.symbol === func.symbol; }))) { + // Javascript "callable constructors", containing eg `if (!(this instanceof A)) return new A()` should not add undefined + ts.pushIfUnique(aggregatedTypes, undefinedType); + } + return aggregatedTypes; + } + function mayReturnNever(func) { + switch (func.kind) { + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + return true; + case 156 /* MethodDeclaration */: + return func.parent.kind === 188 /* ObjectLiteralExpression */; + default: + return false; + } + } + /** + * TypeScript Specification 1.0 (6.3) - July 2014 + * An explicitly typed function whose return type isn't the Void type, + * the Any type, or a union type containing the Void or Any type as a constituent + * must have at least one return statement somewhere in its body. + * An exception to this rule is if the function implementation consists of a single 'throw' statement. + * + * @param returnType - return type of the function, can be undefined if return type is not explicitly specified + */ + function checkAllCodePathsInNonVoidFunctionReturnOrThrow(func, returnType) { + if (!produceDiagnostics) { + return; + } + // Functions with with an explicitly specified 'void' or 'any' return type don't need any return expressions. + if (returnType && maybeTypeOfKind(returnType, 1 /* Any */ | 16384 /* Void */)) { + return; + } + // If all we have is a function signature, or an arrow function with an expression body, then there is nothing to check. + // also if HasImplicitReturn flag is not set this means that all codepaths in function body end with return or throw + if (func.kind === 155 /* MethodSignature */ || ts.nodeIsMissing(func.body) || func.body.kind !== 218 /* Block */ || !functionHasImplicitReturn(func)) { + return; + } + var hasExplicitReturn = func.flags & 256 /* HasExplicitReturn */; + if (returnType && returnType.flags & 131072 /* Never */) { + error(ts.getEffectiveReturnTypeNode(func), ts.Diagnostics.A_function_returning_never_cannot_have_a_reachable_end_point); + } + else if (returnType && !hasExplicitReturn) { + // minimal check: function has syntactic return type annotation and no explicit return statements in the body + // this function does not conform to the specification. + // NOTE: having returnType !== undefined is a precondition for entering this branch so func.type will always be present + error(ts.getEffectiveReturnTypeNode(func), ts.Diagnostics.A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value); + } + else if (returnType && strictNullChecks && !isTypeAssignableTo(undefinedType, returnType)) { + error(ts.getEffectiveReturnTypeNode(func), ts.Diagnostics.Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined); + } + else if (compilerOptions.noImplicitReturns) { + if (!returnType) { + // If return type annotation is omitted check if function has any explicit return statements. + // If it does not have any - its inferred return type is void - don't do any checks. + // Otherwise get inferred return type from function body and report error only if it is not void / anytype + if (!hasExplicitReturn) { + return; + } + var inferredReturnType = getReturnTypeOfSignature(getSignatureFromDeclaration(func)); + if (isUnwrappedReturnTypeVoidOrAny(func, inferredReturnType)) { + return; + } + } + error(ts.getEffectiveReturnTypeNode(func) || func, ts.Diagnostics.Not_all_code_paths_return_a_value); + } + } + function checkFunctionExpressionOrObjectLiteralMethod(node, checkMode) { + ts.Debug.assert(node.kind !== 156 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + checkNodeDeferred(node); + // The identityMapper object is used to indicate that function expressions are wildcards + if (checkMode === 1 /* SkipContextSensitive */ && isContextSensitive(node)) { + // Skip parameters, return signature with return type that retains noncontextual parts so inferences can still be drawn in an early stage + if (!ts.getEffectiveReturnTypeNode(node) && hasContextSensitiveReturnExpression(node)) { + var links_1 = getNodeLinks(node); + if (links_1.contextFreeType) { + return links_1.contextFreeType; + } + var returnType = getReturnTypeFromBody(node, checkMode); + var returnOnlySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, returnType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + var returnOnlyType = createAnonymousType(node.symbol, emptySymbols, [returnOnlySignature], ts.emptyArray, undefined, undefined); + returnOnlyType.flags |= 536870912 /* ContainsAnyFunctionType */; + return links_1.contextFreeType = returnOnlyType; + } + return anyFunctionType; + } + // Grammar checking + var hasGrammarError = checkGrammarFunctionLikeDeclaration(node); + if (!hasGrammarError && node.kind === 196 /* FunctionExpression */) { + checkGrammarForGenerator(node); + } + var links = getNodeLinks(node); + var type = getTypeOfSymbol(getMergedSymbol(node.symbol)); + if (isTypeAny(type)) { + return type; + } + // Check if function expression is contextually typed and assign parameter types if so. + if (!(links.flags & 1024 /* ContextChecked */)) { + var contextualSignature = getContextualSignature(node); + // If a type check is started at a function expression that is an argument of a function call, obtaining the + // contextual type may recursively get back to here during overload resolution of the call. If so, we will have + // already assigned contextual types. + if (!(links.flags & 1024 /* ContextChecked */)) { + links.flags |= 1024 /* ContextChecked */; + if (contextualSignature) { + var signature = getSignaturesOfType(type, 0 /* Call */)[0]; + if (isContextSensitive(node)) { + var contextualMapper = getContextualMapper(node); + if (checkMode === 2 /* Inferential */) { + inferFromAnnotatedParameters(signature, contextualSignature, contextualMapper); + } + var instantiatedContextualSignature = contextualMapper === identityMapper ? + contextualSignature : instantiateSignature(contextualSignature, contextualMapper); + assignContextualParameterTypes(signature, instantiatedContextualSignature); + } + if (!getReturnTypeFromAnnotation(node) && !signature.resolvedReturnType) { + var returnType = getReturnTypeFromBody(node, checkMode); + if (!signature.resolvedReturnType) { + signature.resolvedReturnType = returnType; + } + } + } + checkSignatureDeclaration(node); + } + } + return type; + } + function getReturnOrPromisedType(node, functionFlags) { + var type = getReturnTypeFromAnnotation(node); + return type && ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */) ? + getAwaitedType(type) || errorType : type; + } + function checkFunctionExpressionOrObjectLiteralMethodDeferred(node) { + ts.Debug.assert(node.kind !== 156 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + var functionFlags = ts.getFunctionFlags(node); + var returnOrPromisedType = getReturnOrPromisedType(node, functionFlags); + if ((functionFlags & 1 /* Generator */) === 0) { // Async function or normal function + // return is not necessary in the body of generators + checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnOrPromisedType); + } + if (node.body) { + if (!ts.getEffectiveReturnTypeNode(node)) { + // There are some checks that are only performed in getReturnTypeFromBody, that may produce errors + // we need. An example is the noImplicitAny errors resulting from widening the return expression + // of a function. Because checking of function expression bodies is deferred, there was never an + // appropriate time to do this during the main walk of the file (see the comment at the top of + // checkFunctionExpressionBodies). So it must be done now. + getReturnTypeOfSignature(getSignatureFromDeclaration(node)); + } + if (node.body.kind === 218 /* Block */) { + checkSourceElement(node.body); + } + else { + // From within an async function you can return either a non-promise value or a promise. Any + // Promise/A+ compatible implementation will always assimilate any foreign promise, so we + // should not be checking assignability of a promise to the return type. Instead, we need to + // check assignability of the awaited type of the expression body against the promised type of + // its return type annotation. + var exprType = checkExpression(node.body); + if (returnOrPromisedType) { + if ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */) { // Async function + var awaitedType = checkAwaitedType(exprType, node.body, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); + checkTypeAssignableToAndOptionallyElaborate(awaitedType, returnOrPromisedType, node.body, node.body); + } + else { // Normal function + checkTypeAssignableToAndOptionallyElaborate(exprType, returnOrPromisedType, node.body, node.body); + } + } + } + } + } + function checkArithmeticOperandType(operand, type, diagnostic) { + if (!isTypeAssignableTo(type, numberOrBigIntType)) { + error(operand, diagnostic); + return false; + } + return true; + } + function isReadonlyAssignmentDeclaration(d) { + if (!ts.isCallExpression(d)) { + return false; + } + if (!ts.isBindableObjectDefinePropertyCall(d)) { + return false; + } + var objectLitType = checkExpressionCached(d.arguments[2]); + var valueType = getTypeOfPropertyOfType(objectLitType, "value"); + if (valueType) { + var writableProp = getPropertyOfType(objectLitType, "writable"); + var writableType = writableProp && getTypeOfSymbol(writableProp); + if (!writableType || writableType === falseType || writableType === regularFalseType) { + return true; + } + // We include this definition whereupon we walk back and check the type at the declaration because + // The usual definition of `Object.defineProperty` will _not_ cause literal types to be preserved in the + // argument types, should the type be contextualized by the call itself. + if (writableProp && writableProp.valueDeclaration && ts.isPropertyAssignment(writableProp.valueDeclaration)) { + var initializer = writableProp.valueDeclaration.initializer; + var rawOriginalType = checkExpression(initializer); + if (rawOriginalType === falseType || rawOriginalType === regularFalseType) { + return true; + } + } + return false; + } + var setProp = getPropertyOfType(objectLitType, "set"); + return !setProp; + } + function isReadonlySymbol(symbol) { + // The following symbols are considered read-only: + // Properties with a 'readonly' modifier + // Variables declared with 'const' + // Get accessors without matching set accessors + // Enum members + // Object.defineProperty assignments with writable false or no setter + // Unions and intersections of the above (unions and intersections eagerly set isReadonly on creation) + return !!(ts.getCheckFlags(symbol) & 8 /* Readonly */ || + symbol.flags & 4 /* Property */ && ts.getDeclarationModifierFlagsFromSymbol(symbol) & 64 /* Readonly */ || + symbol.flags & 3 /* Variable */ && getDeclarationNodeFlagsFromSymbol(symbol) & 2 /* Const */ || + symbol.flags & 98304 /* Accessor */ && !(symbol.flags & 65536 /* SetAccessor */) || + symbol.flags & 8 /* EnumMember */ || + ts.some(symbol.declarations, isReadonlyAssignmentDeclaration)); + } + function isReferenceToReadonlyEntity(expr, symbol) { + if (isReadonlySymbol(symbol)) { + // Allow assignments to readonly properties within constructors of the same class declaration. + if (symbol.flags & 4 /* Property */ && + (expr.kind === 189 /* PropertyAccessExpression */ || expr.kind === 190 /* ElementAccessExpression */) && + expr.expression.kind === 100 /* ThisKeyword */) { + // Look for if this is the constructor for the class that `symbol` is a property of. + var func = ts.getContainingFunction(expr); + if (!(func && func.kind === 157 /* Constructor */)) { + return true; + } + // If func.parent is a class and symbol is a (readonly) property of that class, or + // if func is a constructor and symbol is a (readonly) parameter property declared in it, + // then symbol is writeable here. + return !symbol.valueDeclaration || !(func.parent === symbol.valueDeclaration.parent || func === symbol.valueDeclaration.parent); + } + return true; + } + return false; + } + function isReferenceThroughNamespaceImport(expr) { + if (expr.kind === 189 /* PropertyAccessExpression */ || expr.kind === 190 /* ElementAccessExpression */) { + var node = ts.skipParentheses(expr.expression); + if (node.kind === 72 /* Identifier */) { + var symbol = getNodeLinks(node).resolvedSymbol; + if (symbol.flags & 2097152 /* Alias */) { + var declaration = getDeclarationOfAliasSymbol(symbol); + return !!declaration && declaration.kind === 251 /* NamespaceImport */; + } + } + } + return false; + } + function checkReferenceExpression(expr, invalidReferenceMessage) { + // References are combinations of identifiers, parentheses, and property accesses. + var node = ts.skipOuterExpressions(expr, 2 /* Assertions */ | 1 /* Parentheses */); + if (node.kind !== 72 /* Identifier */ && node.kind !== 189 /* PropertyAccessExpression */ && node.kind !== 190 /* ElementAccessExpression */) { + error(expr, invalidReferenceMessage); + return false; + } + return true; + } + function checkDeleteExpression(node) { + checkExpression(node.expression); + var expr = ts.skipParentheses(node.expression); + if (expr.kind !== 189 /* PropertyAccessExpression */ && expr.kind !== 190 /* ElementAccessExpression */) { + error(expr, ts.Diagnostics.The_operand_of_a_delete_operator_must_be_a_property_reference); + return booleanType; + } + var links = getNodeLinks(expr); + var symbol = getExportSymbolOfValueSymbolIfExported(links.resolvedSymbol); + if (symbol && isReadonlySymbol(symbol)) { + error(expr, ts.Diagnostics.The_operand_of_a_delete_operator_cannot_be_a_read_only_property); + } + return booleanType; + } + function checkTypeOfExpression(node) { + checkExpression(node.expression); + return typeofType; + } + function checkVoidExpression(node) { + checkExpression(node.expression); + return undefinedWideningType; + } + function checkAwaitExpression(node) { + // Grammar checking + if (produceDiagnostics) { + if (!(node.flags & 16384 /* AwaitContext */)) { + grammarErrorOnFirstToken(node, ts.Diagnostics.await_expression_is_only_allowed_within_an_async_function); + } + if (isInParameterInitializerBeforeContainingFunction(node)) { + error(node, ts.Diagnostics.await_expressions_cannot_be_used_in_a_parameter_initializer); + } + } + var operandType = checkExpression(node.expression); + return checkAwaitedType(operandType, node, ts.Diagnostics.Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); + } + function checkPrefixUnaryExpression(node) { + var operandType = checkExpression(node.operand); + if (operandType === silentNeverType) { + return silentNeverType; + } + switch (node.operand.kind) { + case 8 /* NumericLiteral */: + switch (node.operator) { + case 39 /* MinusToken */: + return getFreshTypeOfLiteralType(getLiteralType(-node.operand.text)); + case 38 /* PlusToken */: + return getFreshTypeOfLiteralType(getLiteralType(+node.operand.text)); + } + break; + case 9 /* BigIntLiteral */: + if (node.operator === 39 /* MinusToken */) { + return getFreshTypeOfLiteralType(getLiteralType({ + negative: true, + base10Value: ts.parsePseudoBigInt(node.operand.text) + })); + } + } + switch (node.operator) { + case 38 /* PlusToken */: + case 39 /* MinusToken */: + case 53 /* TildeToken */: + checkNonNullType(operandType, node.operand); + if (maybeTypeOfKind(operandType, 12288 /* ESSymbolLike */)) { + error(node.operand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(node.operator)); + } + if (node.operator === 38 /* PlusToken */) { + if (maybeTypeOfKind(operandType, 2112 /* BigIntLike */)) { + error(node.operand, ts.Diagnostics.Operator_0_cannot_be_applied_to_type_1, ts.tokenToString(node.operator), typeToString(operandType)); + } + return numberType; + } + return getUnaryResultType(operandType); + case 52 /* ExclamationToken */: + checkTruthinessExpression(node.operand); + var facts = getTypeFacts(operandType) & (4194304 /* Truthy */ | 8388608 /* Falsy */); + return facts === 4194304 /* Truthy */ ? falseType : + facts === 8388608 /* Falsy */ ? trueType : + booleanType; + case 44 /* PlusPlusToken */: + case 45 /* MinusMinusToken */: + var ok = checkArithmeticOperandType(node.operand, checkNonNullType(operandType, node.operand), ts.Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_bigint_or_an_enum_type); + if (ok) { + // run check only if former checks succeeded to avoid reporting cascading errors + checkReferenceExpression(node.operand, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access); + } + return getUnaryResultType(operandType); + } + return errorType; + } + function checkPostfixUnaryExpression(node) { + var operandType = checkExpression(node.operand); + if (operandType === silentNeverType) { + return silentNeverType; + } + var ok = checkArithmeticOperandType(node.operand, checkNonNullType(operandType, node.operand), ts.Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_bigint_or_an_enum_type); + if (ok) { + // run check only if former checks succeeded to avoid reporting cascading errors + checkReferenceExpression(node.operand, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access); + } + return getUnaryResultType(operandType); + } + function getUnaryResultType(operandType) { + if (maybeTypeOfKind(operandType, 2112 /* BigIntLike */)) { + return isTypeAssignableToKind(operandType, 3 /* AnyOrUnknown */) || maybeTypeOfKind(operandType, 296 /* NumberLike */) + ? numberOrBigIntType + : bigintType; + } + // If it's not a bigint type, implicit coercion will result in a number + return numberType; + } + // Return true if type might be of the given kind. A union or intersection type might be of a given + // kind if at least one constituent type is of the given kind. + function maybeTypeOfKind(type, kind) { + if (type.flags & kind & ~134217728 /* GenericMappedType */ || kind & 134217728 /* GenericMappedType */ && isGenericMappedType(type)) { + return true; + } + if (type.flags & 3145728 /* UnionOrIntersection */) { + var types = type.types; + for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { + var t = types_15[_i]; + if (maybeTypeOfKind(t, kind)) { + return true; + } + } + } + return false; + } + function isTypeAssignableToKind(source, kind, strict) { + if (source.flags & kind) { + return true; + } + if (strict && source.flags & (3 /* AnyOrUnknown */ | 16384 /* Void */ | 32768 /* Undefined */ | 65536 /* Null */)) { + return false; + } + return !!(kind & 296 /* NumberLike */) && isTypeAssignableTo(source, numberType) || + !!(kind & 2112 /* BigIntLike */) && isTypeAssignableTo(source, bigintType) || + !!(kind & 132 /* StringLike */) && isTypeAssignableTo(source, stringType) || + !!(kind & 528 /* BooleanLike */) && isTypeAssignableTo(source, booleanType) || + !!(kind & 16384 /* Void */) && isTypeAssignableTo(source, voidType) || + !!(kind & 131072 /* Never */) && isTypeAssignableTo(source, neverType) || + !!(kind & 65536 /* Null */) && isTypeAssignableTo(source, nullType) || + !!(kind & 32768 /* Undefined */) && isTypeAssignableTo(source, undefinedType) || + !!(kind & 4096 /* ESSymbol */) && isTypeAssignableTo(source, esSymbolType) || + !!(kind & 67108864 /* NonPrimitive */) && isTypeAssignableTo(source, nonPrimitiveType); + } + function allTypesAssignableToKind(source, kind, strict) { + return source.flags & 1048576 /* Union */ ? + ts.every(source.types, function (subType) { return allTypesAssignableToKind(subType, kind, strict); }) : + isTypeAssignableToKind(source, kind, strict); + } + function isConstEnumObjectType(type) { + return !!(ts.getObjectFlags(type) & 16 /* Anonymous */) && !!type.symbol && isConstEnumSymbol(type.symbol); + } + function isConstEnumSymbol(symbol) { + return (symbol.flags & 128 /* ConstEnum */) !== 0; + } + function checkInstanceOfExpression(left, right, leftType, rightType) { + if (leftType === silentNeverType || rightType === silentNeverType) { + return silentNeverType; + } + // TypeScript 1.0 spec (April 2014): 4.15.4 + // The instanceof operator requires the left operand to be of type Any, an object type, or a type parameter type, + // and the right operand to be of type Any, a subtype of the 'Function' interface type, or have a call or construct signature. + // The result is always of the Boolean primitive type. + // NOTE: do not raise error if leftType is unknown as related error was already reported + if (!isTypeAny(leftType) && + allTypesAssignableToKind(leftType, 131068 /* Primitive */)) { + error(left, ts.Diagnostics.The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter); + } + // NOTE: do not raise error if right is unknown as related error was already reported + if (!(isTypeAny(rightType) || typeHasCallOrConstructSignatures(rightType) || isTypeSubtypeOf(rightType, globalFunctionType))) { + error(right, ts.Diagnostics.The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_Function_interface_type); + } + return booleanType; + } + function checkInExpression(left, right, leftType, rightType) { + if (leftType === silentNeverType || rightType === silentNeverType) { + return silentNeverType; + } + leftType = checkNonNullType(leftType, left); + rightType = checkNonNullType(rightType, right); + // TypeScript 1.0 spec (April 2014): 4.15.5 + // The in operator requires the left operand to be of type Any, the String primitive type, or the Number primitive type, + // and the right operand to be of type Any, an object type, or a type parameter type. + // The result is always of the Boolean primitive type. + if (!(isTypeComparableTo(leftType, stringType) || isTypeAssignableToKind(leftType, 296 /* NumberLike */ | 12288 /* ESSymbolLike */))) { + error(left, ts.Diagnostics.The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol); + } + if (!isTypeAssignableToKind(rightType, 67108864 /* NonPrimitive */ | 58982400 /* InstantiableNonPrimitive */)) { + error(right, ts.Diagnostics.The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter); + } + return booleanType; + } + function checkObjectLiteralAssignment(node, sourceType, rightIsThis) { + var properties = node.properties; + if (strictNullChecks && properties.length === 0) { + return checkNonNullType(sourceType, node); + } + for (var _i = 0, properties_6 = properties; _i < properties_6.length; _i++) { + var p = properties_6[_i]; + checkObjectLiteralDestructuringPropertyAssignment(sourceType, p, properties, rightIsThis); + } + return sourceType; + } + /** Note: If property cannot be a SpreadAssignment, then allProperties does not need to be provided */ + function checkObjectLiteralDestructuringPropertyAssignment(objectLiteralType, property, allProperties, rightIsThis) { + if (rightIsThis === void 0) { rightIsThis = false; } + if (property.kind === 275 /* PropertyAssignment */ || property.kind === 276 /* ShorthandPropertyAssignment */) { + var name = property.name; + if (name.kind === 149 /* ComputedPropertyName */) { + checkComputedPropertyName(name); + } + if (isComputedNonLiteralName(name)) { + return undefined; + } + var type = getTypeOfObjectLiteralDestructuringProperty(objectLiteralType, name, property, rightIsThis); + if (type) { + // non-shorthand property assignments should always have initializers + return checkDestructuringAssignment(property.kind === 276 /* ShorthandPropertyAssignment */ ? property : property.initializer, type); + } + else { + error(name, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(objectLiteralType), ts.declarationNameToString(name)); + } + } + else if (property.kind === 277 /* SpreadAssignment */) { + if (languageVersion < 6 /* ESNext */) { + checkExternalEmitHelpers(property, 4 /* Rest */); + } + var nonRestNames = []; + if (allProperties) { + for (var i = 0; i < allProperties.length - 1; i++) { + nonRestNames.push(allProperties[i].name); + } + } + var type = getRestType(objectLiteralType, nonRestNames, objectLiteralType.symbol); + checkGrammarForDisallowedTrailingComma(allProperties, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma); + return checkDestructuringAssignment(property.expression, type); + } + else { + error(property, ts.Diagnostics.Property_assignment_expected); + } + } + function getTypeOfObjectLiteralDestructuringProperty(objectLiteralType, name, property, rightIsThis) { + if (isTypeAny(objectLiteralType)) { + return objectLiteralType; + } + var type; + var text = ts.getTextOfPropertyName(name); + if (text) { // TODO: GH#26379 + var prop = getPropertyOfType(objectLiteralType, text); + if (prop) { + markPropertyAsReferenced(prop, property, rightIsThis); + checkPropertyAccessibility(property, /*isSuper*/ false, objectLiteralType, prop); + type = getTypeOfSymbol(prop); + } + type = type || (isNumericLiteralName(text) ? getIndexTypeOfType(objectLiteralType, 1 /* Number */) : undefined); + } + return type || getIndexTypeOfType(objectLiteralType, 0 /* String */); + } + function checkArrayLiteralAssignment(node, sourceType, checkMode) { + var elements = node.elements; + if (languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) { + checkExternalEmitHelpers(node, 512 /* Read */); + } + // This elementType will be used if the specific property corresponding to this index is not + // present (aka the tuple element property). This call also checks that the parentType is in + // fact an iterable or array (depending on target language). + var elementType = checkIteratedTypeOrElementType(sourceType, node, /*allowStringInput*/ false, /*allowAsyncIterables*/ false) || errorType; + for (var i = 0; i < elements.length; i++) { + checkArrayLiteralDestructuringElementAssignment(node, sourceType, i, elementType, checkMode); + } + return sourceType; + } + function checkArrayLiteralDestructuringElementAssignment(node, sourceType, elementIndex, elementType, checkMode) { + var elements = node.elements; + var element = elements[elementIndex]; + if (element.kind !== 210 /* OmittedExpression */) { + if (element.kind !== 208 /* SpreadElement */) { + var propName = "" + elementIndex; + var type = isTypeAny(sourceType) ? sourceType : + everyType(sourceType, isTupleLikeType) ? getTupleElementType(sourceType, elementIndex) : + elementType; + if (type) { + return checkDestructuringAssignment(element, type, checkMode); + } + // We still need to check element expression here because we may need to set appropriate flag on the expression + // such as NodeCheckFlags.LexicalThis on "this"expression. + checkExpression(element); + if (isTupleType(sourceType)) { + error(element, ts.Diagnostics.Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2, typeToString(sourceType), getTypeReferenceArity(sourceType), elements.length); + } + else { + error(element, ts.Diagnostics.Type_0_has_no_property_1, typeToString(sourceType), propName); + } + } + else { + if (elementIndex < elements.length - 1) { + error(element, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern); + } + else { + var restExpression = element.expression; + if (restExpression.kind === 204 /* BinaryExpression */ && restExpression.operatorToken.kind === 59 /* EqualsToken */) { + error(restExpression.operatorToken, ts.Diagnostics.A_rest_element_cannot_have_an_initializer); + } + else { + checkGrammarForDisallowedTrailingComma(node.elements, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma); + var type = everyType(sourceType, isTupleType) ? + mapType(sourceType, function (t) { return sliceTupleType(t, elementIndex); }) : + createArrayType(elementType); + return checkDestructuringAssignment(restExpression, type, checkMode); + } + } + } + } + return undefined; + } + function checkDestructuringAssignment(exprOrAssignment, sourceType, checkMode, rightIsThis) { + var target; + if (exprOrAssignment.kind === 276 /* ShorthandPropertyAssignment */) { + var prop = exprOrAssignment; + if (prop.objectAssignmentInitializer) { + // In strict null checking mode, if a default value of a non-undefined type is specified, remove + // undefined from the final type. + if (strictNullChecks && + !(getFalsyFlags(checkExpression(prop.objectAssignmentInitializer)) & 32768 /* Undefined */)) { + sourceType = getTypeWithFacts(sourceType, 524288 /* NEUndefined */); + } + checkBinaryLikeExpression(prop.name, prop.equalsToken, prop.objectAssignmentInitializer, checkMode); + } + target = exprOrAssignment.name; + } + else { + target = exprOrAssignment; + } + if (target.kind === 204 /* BinaryExpression */ && target.operatorToken.kind === 59 /* EqualsToken */) { + checkBinaryExpression(target, checkMode); + target = target.left; + } + if (target.kind === 188 /* ObjectLiteralExpression */) { + return checkObjectLiteralAssignment(target, sourceType, rightIsThis); + } + if (target.kind === 187 /* ArrayLiteralExpression */) { + return checkArrayLiteralAssignment(target, sourceType, checkMode); + } + return checkReferenceAssignment(target, sourceType, checkMode); + } + function checkReferenceAssignment(target, sourceType, checkMode) { + var targetType = checkExpression(target, checkMode); + var error = target.parent.kind === 277 /* SpreadAssignment */ ? + ts.Diagnostics.The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access : + ts.Diagnostics.The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access; + if (checkReferenceExpression(target, error)) { + checkTypeAssignableToAndOptionallyElaborate(sourceType, targetType, target, target); + } + return sourceType; + } + /** + * This is a *shallow* check: An expression is side-effect-free if the + * evaluation of the expression *itself* cannot produce side effects. + * For example, x++ / 3 is side-effect free because the / operator + * does not have side effects. + * The intent is to "smell test" an expression for correctness in positions where + * its value is discarded (e.g. the left side of the comma operator). + */ + function isSideEffectFree(node) { + node = ts.skipParentheses(node); + switch (node.kind) { + case 72 /* Identifier */: + case 10 /* StringLiteral */: + case 13 /* RegularExpressionLiteral */: + case 193 /* TaggedTemplateExpression */: + case 206 /* TemplateExpression */: + case 14 /* NoSubstitutionTemplateLiteral */: + case 8 /* NumericLiteral */: + case 9 /* BigIntLiteral */: + case 102 /* TrueKeyword */: + case 87 /* FalseKeyword */: + case 96 /* NullKeyword */: + case 141 /* UndefinedKeyword */: + case 196 /* FunctionExpression */: + case 209 /* ClassExpression */: + case 197 /* ArrowFunction */: + case 187 /* ArrayLiteralExpression */: + case 188 /* ObjectLiteralExpression */: + case 199 /* TypeOfExpression */: + case 213 /* NonNullExpression */: + case 261 /* JsxSelfClosingElement */: + case 260 /* JsxElement */: + return true; + case 205 /* ConditionalExpression */: + return isSideEffectFree(node.whenTrue) && + isSideEffectFree(node.whenFalse); + case 204 /* BinaryExpression */: + if (ts.isAssignmentOperator(node.operatorToken.kind)) { + return false; + } + return isSideEffectFree(node.left) && + isSideEffectFree(node.right); + case 202 /* PrefixUnaryExpression */: + case 203 /* PostfixUnaryExpression */: + // Unary operators ~, !, +, and - have no side effects. + // The rest do. + switch (node.operator) { + case 52 /* ExclamationToken */: + case 38 /* PlusToken */: + case 39 /* MinusToken */: + case 53 /* TildeToken */: + return true; + } + return false; + // Some forms listed here for clarity + case 200 /* VoidExpression */: // Explicit opt-out + case 194 /* TypeAssertionExpression */: // Not SEF, but can produce useful type warnings + case 212 /* AsExpression */: // Not SEF, but can produce useful type warnings + default: + return false; + } + } + function isTypeEqualityComparableTo(source, target) { + return (target.flags & 98304 /* Nullable */) !== 0 || isTypeComparableTo(source, target); + } + function checkBinaryExpression(node, checkMode) { + if (ts.isInJSFile(node) && ts.getAssignedExpandoInitializer(node)) { + return checkExpression(node.right, checkMode); + } + return checkBinaryLikeExpression(node.left, node.operatorToken, node.right, checkMode, node); + } + function checkBinaryLikeExpression(left, operatorToken, right, checkMode, errorNode) { + var operator = operatorToken.kind; + if (operator === 59 /* EqualsToken */ && (left.kind === 188 /* ObjectLiteralExpression */ || left.kind === 187 /* ArrayLiteralExpression */)) { + return checkDestructuringAssignment(left, checkExpression(right, checkMode), checkMode, right.kind === 100 /* ThisKeyword */); + } + var leftType; + if (operator === 54 /* AmpersandAmpersandToken */ || operator === 55 /* BarBarToken */) { + leftType = checkTruthinessExpression(left, checkMode); + } + else { + leftType = checkExpression(left, checkMode); + } + var rightType = checkExpression(right, checkMode); + switch (operator) { + case 40 /* AsteriskToken */: + case 41 /* AsteriskAsteriskToken */: + case 62 /* AsteriskEqualsToken */: + case 63 /* AsteriskAsteriskEqualsToken */: + case 42 /* SlashToken */: + case 64 /* SlashEqualsToken */: + case 43 /* PercentToken */: + case 65 /* PercentEqualsToken */: + case 39 /* MinusToken */: + case 61 /* MinusEqualsToken */: + case 46 /* LessThanLessThanToken */: + case 66 /* LessThanLessThanEqualsToken */: + case 47 /* GreaterThanGreaterThanToken */: + case 67 /* GreaterThanGreaterThanEqualsToken */: + case 48 /* GreaterThanGreaterThanGreaterThanToken */: + case 68 /* GreaterThanGreaterThanGreaterThanEqualsToken */: + case 50 /* BarToken */: + case 70 /* BarEqualsToken */: + case 51 /* CaretToken */: + case 71 /* CaretEqualsToken */: + case 49 /* AmpersandToken */: + case 69 /* AmpersandEqualsToken */: + if (leftType === silentNeverType || rightType === silentNeverType) { + return silentNeverType; + } + leftType = checkNonNullType(leftType, left); + rightType = checkNonNullType(rightType, right); + var suggestedOperator = void 0; + // if a user tries to apply a bitwise operator to 2 boolean operands + // try and return them a helpful suggestion + if ((leftType.flags & 528 /* BooleanLike */) && + (rightType.flags & 528 /* BooleanLike */) && + (suggestedOperator = getSuggestedBooleanOperator(operatorToken.kind)) !== undefined) { + error(errorNode || operatorToken, ts.Diagnostics.The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead, ts.tokenToString(operatorToken.kind), ts.tokenToString(suggestedOperator)); + return numberType; + } + else { + // otherwise just check each operand separately and report errors as normal + var leftOk = checkArithmeticOperandType(left, leftType, ts.Diagnostics.The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type); + var rightOk = checkArithmeticOperandType(right, rightType, ts.Diagnostics.The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type); + var resultType_1; + // If both are any or unknown, allow operation; assume it will resolve to number + if ((isTypeAssignableToKind(leftType, 3 /* AnyOrUnknown */) && isTypeAssignableToKind(rightType, 3 /* AnyOrUnknown */)) || + // Or, if neither could be bigint, implicit coercion results in a number result + !(maybeTypeOfKind(leftType, 2112 /* BigIntLike */) || maybeTypeOfKind(rightType, 2112 /* BigIntLike */))) { + resultType_1 = numberType; + } + // At least one is assignable to bigint, so both should be only assignable to bigint + else if (isTypeAssignableToKind(leftType, 2112 /* BigIntLike */) && isTypeAssignableToKind(rightType, 2112 /* BigIntLike */)) { + switch (operator) { + case 48 /* GreaterThanGreaterThanGreaterThanToken */: + case 68 /* GreaterThanGreaterThanGreaterThanEqualsToken */: + reportOperatorError(); + } + resultType_1 = bigintType; + } + else { + reportOperatorError(); + resultType_1 = errorType; + } + if (leftOk && rightOk) { + checkAssignmentOperator(resultType_1); + } + return resultType_1; + } + case 38 /* PlusToken */: + case 60 /* PlusEqualsToken */: + if (leftType === silentNeverType || rightType === silentNeverType) { + return silentNeverType; + } + if (!isTypeAssignableToKind(leftType, 132 /* StringLike */) && !isTypeAssignableToKind(rightType, 132 /* StringLike */)) { + leftType = checkNonNullType(leftType, left); + rightType = checkNonNullType(rightType, right); + } + var resultType = void 0; + if (isTypeAssignableToKind(leftType, 296 /* NumberLike */, /*strict*/ true) && isTypeAssignableToKind(rightType, 296 /* NumberLike */, /*strict*/ true)) { + // Operands of an enum type are treated as having the primitive type Number. + // If both operands are of the Number primitive type, the result is of the Number primitive type. + resultType = numberType; + } + else if (isTypeAssignableToKind(leftType, 2112 /* BigIntLike */, /*strict*/ true) && isTypeAssignableToKind(rightType, 2112 /* BigIntLike */, /*strict*/ true)) { + // If both operands are of the BigInt primitive type, the result is of the BigInt primitive type. + resultType = bigintType; + } + else if (isTypeAssignableToKind(leftType, 132 /* StringLike */, /*strict*/ true) || isTypeAssignableToKind(rightType, 132 /* StringLike */, /*strict*/ true)) { + // If one or both operands are of the String primitive type, the result is of the String primitive type. + resultType = stringType; + } + else if (isTypeAny(leftType) || isTypeAny(rightType)) { + // Otherwise, the result is of type Any. + // NOTE: unknown type here denotes error type. Old compiler treated this case as any type so do we. + resultType = leftType === errorType || rightType === errorType ? errorType : anyType; + } + // Symbols are not allowed at all in arithmetic expressions + if (resultType && !checkForDisallowedESSymbolOperand(operator)) { + return resultType; + } + if (!resultType) { + reportOperatorError(); + return anyType; + } + if (operator === 60 /* PlusEqualsToken */) { + checkAssignmentOperator(resultType); + } + return resultType; + case 28 /* LessThanToken */: + case 30 /* GreaterThanToken */: + case 31 /* LessThanEqualsToken */: + case 32 /* GreaterThanEqualsToken */: + if (checkForDisallowedESSymbolOperand(operator)) { + leftType = getBaseTypeOfLiteralType(checkNonNullType(leftType, left)); + rightType = getBaseTypeOfLiteralType(checkNonNullType(rightType, right)); + if (!(isTypeComparableTo(leftType, rightType) || isTypeComparableTo(rightType, leftType) || + (isTypeAssignableTo(leftType, numberOrBigIntType) && isTypeAssignableTo(rightType, numberOrBigIntType)))) { + reportOperatorError(); + } + } + return booleanType; + case 33 /* EqualsEqualsToken */: + case 34 /* ExclamationEqualsToken */: + case 35 /* EqualsEqualsEqualsToken */: + case 36 /* ExclamationEqualsEqualsToken */: + var leftIsLiteral = isLiteralType(leftType); + var rightIsLiteral = isLiteralType(rightType); + if (!leftIsLiteral || !rightIsLiteral) { + leftType = leftIsLiteral ? getBaseTypeOfLiteralType(leftType) : leftType; + rightType = rightIsLiteral ? getBaseTypeOfLiteralType(rightType) : rightType; + } + if (!isTypeEqualityComparableTo(leftType, rightType) && !isTypeEqualityComparableTo(rightType, leftType)) { + reportOperatorError(); + } + return booleanType; + case 94 /* InstanceOfKeyword */: + return checkInstanceOfExpression(left, right, leftType, rightType); + case 93 /* InKeyword */: + return checkInExpression(left, right, leftType, rightType); + case 54 /* AmpersandAmpersandToken */: + return getTypeFacts(leftType) & 4194304 /* Truthy */ ? + getUnionType([extractDefinitelyFalsyTypes(strictNullChecks ? leftType : getBaseTypeOfLiteralType(rightType)), rightType]) : + leftType; + case 55 /* BarBarToken */: + return getTypeFacts(leftType) & 8388608 /* Falsy */ ? + getUnionType([removeDefinitelyFalsyTypes(leftType), rightType], 2 /* Subtype */) : + leftType; + case 59 /* EqualsToken */: + var declKind = ts.isBinaryExpression(left.parent) ? ts.getAssignmentDeclarationKind(left.parent) : 0 /* None */; + checkAssignmentDeclaration(declKind, rightType); + if (isAssignmentDeclaration(declKind)) { + if (!(rightType.flags & 524288 /* Object */) || + declKind !== 2 /* ModuleExports */ && + declKind !== 6 /* Prototype */ && + !isEmptyObjectType(rightType) && + !isFunctionObjectType(rightType) && + !(ts.getObjectFlags(rightType) & 1 /* Class */)) { + // don't check assignability of module.exports=, C.prototype=, or expando types because they will necessarily be incomplete + checkAssignmentOperator(rightType); + } + return leftType; + } + else { + checkAssignmentOperator(rightType); + return getRegularTypeOfObjectLiteral(rightType); + } + case 27 /* CommaToken */: + if (!compilerOptions.allowUnreachableCode && isSideEffectFree(left) && !isEvalNode(right)) { + error(left, ts.Diagnostics.Left_side_of_comma_operator_is_unused_and_has_no_side_effects); + } + return rightType; + default: + return ts.Debug.fail(); + } + function checkAssignmentDeclaration(kind, rightType) { + if (kind === 2 /* ModuleExports */) { + for (var _i = 0, _a = getPropertiesOfObjectType(rightType); _i < _a.length; _i++) { + var prop = _a[_i]; + var propType = getTypeOfSymbol(prop); + if (propType.symbol && propType.symbol.flags & 32 /* Class */) { + var name = prop.escapedName; + var symbol = resolveName(prop.valueDeclaration, name, 67897832 /* Type */, undefined, name, /*isUse*/ false); + if (symbol && symbol.declarations.some(ts.isJSDocTypedefTag)) { + grammarErrorOnNode(symbol.declarations[0], ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name)); + return grammarErrorOnNode(prop.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name)); + } + } + } + } + } + function isEvalNode(node) { + return node.kind === 72 /* Identifier */ && node.escapedText === "eval"; + } + // Return true if there was no error, false if there was an error. + function checkForDisallowedESSymbolOperand(operator) { + var offendingSymbolOperand = maybeTypeOfKind(leftType, 12288 /* ESSymbolLike */) ? left : + maybeTypeOfKind(rightType, 12288 /* ESSymbolLike */) ? right : + undefined; + if (offendingSymbolOperand) { + error(offendingSymbolOperand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(operator)); + return false; + } + return true; + } + function getSuggestedBooleanOperator(operator) { + switch (operator) { + case 50 /* BarToken */: + case 70 /* BarEqualsToken */: + return 55 /* BarBarToken */; + case 51 /* CaretToken */: + case 71 /* CaretEqualsToken */: + return 36 /* ExclamationEqualsEqualsToken */; + case 49 /* AmpersandToken */: + case 69 /* AmpersandEqualsToken */: + return 54 /* AmpersandAmpersandToken */; + default: + return undefined; + } + } + function checkAssignmentOperator(valueType) { + if (produceDiagnostics && ts.isAssignmentOperator(operator)) { + // TypeScript 1.0 spec (April 2014): 4.17 + // An assignment of the form + // VarExpr = ValueExpr + // requires VarExpr to be classified as a reference + // A compound assignment furthermore requires VarExpr to be classified as a reference (section 4.1) + // and the type of the non-compound operation to be assignable to the type of VarExpr. + if (checkReferenceExpression(left, ts.Diagnostics.The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access) + && (!ts.isIdentifier(left) || ts.unescapeLeadingUnderscores(left.escapedText) !== "exports")) { + // to avoid cascading errors check assignability only if 'isReference' check succeeded and no errors were reported + checkTypeAssignableToAndOptionallyElaborate(valueType, leftType, left, right); + } + } + } + function isAssignmentDeclaration(kind) { + switch (kind) { + case 2 /* ModuleExports */: + return true; + case 1 /* ExportsProperty */: + case 5 /* Property */: + case 6 /* Prototype */: + case 3 /* PrototypeProperty */: + case 4 /* ThisProperty */: + var symbol = getSymbolOfNode(left); + var init = ts.getAssignedExpandoInitializer(right); + return init && ts.isObjectLiteralExpression(init) && + symbol && ts.hasEntries(symbol.exports); + default: + return false; + } + } + function reportOperatorError() { + var leftStr = typeToString(leftType); + var rightStr = typeToString(rightType); + var errNode = errorNode || operatorToken; + if (!tryGiveBetterPrimaryError(errNode, leftStr, rightStr)) { + error(errNode, ts.Diagnostics.Operator_0_cannot_be_applied_to_types_1_and_2, ts.tokenToString(operatorToken.kind), leftStr, rightStr); + } + } + function tryGiveBetterPrimaryError(errNode, leftStr, rightStr) { + switch (operatorToken.kind) { + case 35 /* EqualsEqualsEqualsToken */: + case 33 /* EqualsEqualsToken */: + return error(errNode, ts.Diagnostics.This_condition_will_always_return_0_since_the_types_1_and_2_have_no_overlap, "false", leftStr, rightStr); + case 36 /* ExclamationEqualsEqualsToken */: + case 34 /* ExclamationEqualsToken */: + return error(errNode, ts.Diagnostics.This_condition_will_always_return_0_since_the_types_1_and_2_have_no_overlap, "true", leftStr, rightStr); + } + return undefined; + } + } + function isYieldExpressionInClass(node) { + var current = node; + var parent = node.parent; + while (parent) { + if (ts.isFunctionLike(parent) && current === parent.body) { + return false; + } + else if (ts.isClassLike(current)) { + return true; + } + current = parent; + parent = parent.parent; + } + return false; + } + function checkYieldExpression(node) { + // Grammar checking + if (produceDiagnostics) { + if (!(node.flags & 4096 /* YieldContext */) || isYieldExpressionInClass(node)) { + grammarErrorOnFirstToken(node, ts.Diagnostics.A_yield_expression_is_only_allowed_in_a_generator_body); + } + if (isInParameterInitializerBeforeContainingFunction(node)) { + error(node, ts.Diagnostics.yield_expressions_cannot_be_used_in_a_parameter_initializer); + } + } + var func = ts.getContainingFunction(node); + if (!func) + return anyType; + var functionFlags = ts.getFunctionFlags(func); + if (!(functionFlags & 1 /* Generator */)) { + // If the user's code is syntactically correct, the func should always have a star. After all, we are in a yield context. + return anyType; + } + if (node.asteriskToken) { + // Async generator functions prior to ESNext require the __await, __asyncDelegator, + // and __asyncValues helpers + if ((functionFlags & 3 /* AsyncGenerator */) === 3 /* AsyncGenerator */ && + languageVersion < 6 /* ESNext */) { + checkExternalEmitHelpers(node, 26624 /* AsyncDelegatorIncludes */); + } + // Generator functions prior to ES2015 require the __values helper + if ((functionFlags & 3 /* AsyncGenerator */) === 1 /* Generator */ && + languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) { + checkExternalEmitHelpers(node, 256 /* Values */); + } + } + var isAsync = (functionFlags & 2 /* Async */) !== 0; + var yieldedType = getYieldedTypeOfYieldExpression(node, isAsync); // TODO: GH#18217 + // There is no point in doing an assignability check if the function + // has no explicit return type because the return type is directly computed + // from the yield expressions. + var returnType = getReturnTypeFromAnnotation(func); + if (returnType) { + var signatureElementType = getIteratedTypeOfGenerator(returnType, isAsync) || anyType; + checkTypeAssignableToAndOptionallyElaborate(yieldedType, signatureElementType, node.expression || node, node.expression); + } + // Both yield and yield* expressions have type 'any' + return anyType; + } + function checkConditionalExpression(node, checkMode) { + checkTruthinessExpression(node.condition); + var type1 = checkExpression(node.whenTrue, checkMode); + var type2 = checkExpression(node.whenFalse, checkMode); + return getUnionType([type1, type2], 2 /* Subtype */); + } + function checkTemplateExpression(node) { + // We just want to check each expressions, but we are unconcerned with + // the type of each expression, as any value may be coerced into a string. + // It is worth asking whether this is what we really want though. + // A place where we actually *are* concerned with the expressions' types are + // in tagged templates. + ts.forEach(node.templateSpans, function (templateSpan) { + if (maybeTypeOfKind(checkExpression(templateSpan.expression), 12288 /* ESSymbolLike */)) { + error(templateSpan.expression, ts.Diagnostics.Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_in_String); + } + }); + return stringType; + } + function getContextNode(node) { + if (node.kind === 268 /* JsxAttributes */ && !ts.isJsxSelfClosingElement(node.parent)) { + return node.parent.parent; // Needs to be the root JsxElement, so it encompasses the attributes _and_ the children (which are essentially part of the attributes) + } + return node; + } + function checkExpressionWithContextualType(node, contextualType, contextualMapper) { + var context = getContextNode(node); + var saveContextualType = context.contextualType; + var saveContextualMapper = context.contextualMapper; + context.contextualType = contextualType; + context.contextualMapper = contextualMapper; + var checkMode = contextualMapper === identityMapper ? 1 /* SkipContextSensitive */ : + contextualMapper ? 2 /* Inferential */ : 3 /* Contextual */; + var result = checkExpression(node, checkMode); + context.contextualType = saveContextualType; + context.contextualMapper = saveContextualMapper; + return result; + } + function checkExpressionCached(node, checkMode) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + if (checkMode) { + return checkExpression(node, checkMode); + } + // When computing a type that we're going to cache, we need to ignore any ongoing control flow + // analysis because variables may have transient types in indeterminable states. Moving flowLoopStart + // to the top of the stack ensures all transient types are computed from a known point. + var saveFlowLoopStart = flowLoopStart; + flowLoopStart = flowLoopCount; + links.resolvedType = checkExpression(node, checkMode); + flowLoopStart = saveFlowLoopStart; + } + return links.resolvedType; + } + function isTypeAssertion(node) { + node = ts.skipParentheses(node); + return node.kind === 194 /* TypeAssertionExpression */ || node.kind === 212 /* AsExpression */; + } + function checkDeclarationInitializer(declaration) { + var initializer = ts.getEffectiveInitializer(declaration); + var type = getTypeOfExpression(initializer, /*cache*/ true); + var widened = ts.getCombinedNodeFlags(declaration) & 2 /* Const */ || + ts.isDeclarationReadonly(declaration) || + isTypeAssertion(initializer) ? type : getWidenedLiteralType(type); + if (ts.isInJSFile(declaration)) { + if (widened.flags & 98304 /* Nullable */) { + reportImplicitAny(declaration, anyType); + return anyType; + } + else if (isEmptyArrayLiteralType(widened)) { + reportImplicitAny(declaration, anyArrayType); + return anyArrayType; + } + } + return widened; + } + function isLiteralOfContextualType(candidateType, contextualType) { + if (contextualType) { + if (contextualType.flags & 3145728 /* UnionOrIntersection */) { + var types = contextualType.types; + return ts.some(types, function (t) { return isLiteralOfContextualType(candidateType, t); }); + } + if (contextualType.flags & 58982400 /* InstantiableNonPrimitive */) { + // If the contextual type is a type variable constrained to a primitive type, consider + // this a literal context for literals of that primitive type. For example, given a + // type parameter 'T extends string', infer string literal types for T. + var constraint = getBaseConstraintOfType(contextualType) || emptyObjectType; + return maybeTypeOfKind(constraint, 4 /* String */) && maybeTypeOfKind(candidateType, 128 /* StringLiteral */) || + maybeTypeOfKind(constraint, 8 /* Number */) && maybeTypeOfKind(candidateType, 256 /* NumberLiteral */) || + maybeTypeOfKind(constraint, 64 /* BigInt */) && maybeTypeOfKind(candidateType, 2048 /* BigIntLiteral */) || + maybeTypeOfKind(constraint, 4096 /* ESSymbol */) && maybeTypeOfKind(candidateType, 8192 /* UniqueESSymbol */) || + isLiteralOfContextualType(candidateType, constraint); + } + // If the contextual type is a literal of a particular primitive type, we consider this a + // literal context for all literals of that primitive type. + return !!(contextualType.flags & (128 /* StringLiteral */ | 4194304 /* Index */) && maybeTypeOfKind(candidateType, 128 /* StringLiteral */) || + contextualType.flags & 256 /* NumberLiteral */ && maybeTypeOfKind(candidateType, 256 /* NumberLiteral */) || + contextualType.flags & 2048 /* BigIntLiteral */ && maybeTypeOfKind(candidateType, 2048 /* BigIntLiteral */) || + contextualType.flags & 512 /* BooleanLiteral */ && maybeTypeOfKind(candidateType, 512 /* BooleanLiteral */) || + contextualType.flags & 8192 /* UniqueESSymbol */ && maybeTypeOfKind(candidateType, 8192 /* UniqueESSymbol */)); + } + return false; + } + function checkExpressionForMutableLocation(node, checkMode, contextualType, forceTuple) { + if (arguments.length === 2) { + contextualType = getContextualType(node); + } + var type = checkExpression(node, checkMode, forceTuple); + return isTypeAssertion(node) ? type : + getWidenedLiteralLikeTypeForContextualType(type, contextualType); + } + function checkPropertyAssignment(node, checkMode) { + // Do not use hasDynamicName here, because that returns false for well known symbols. + // We want to perform checkComputedPropertyName for all computed properties, including + // well known symbols. + if (node.name.kind === 149 /* ComputedPropertyName */) { + checkComputedPropertyName(node.name); + } + return checkExpressionForMutableLocation(node.initializer, checkMode); + } + function checkObjectLiteralMethod(node, checkMode) { + // Grammar checking + checkGrammarMethod(node); + // Do not use hasDynamicName here, because that returns false for well known symbols. + // We want to perform checkComputedPropertyName for all computed properties, including + // well known symbols. + if (node.name.kind === 149 /* ComputedPropertyName */) { + checkComputedPropertyName(node.name); + } + var uninstantiatedType = checkFunctionExpressionOrObjectLiteralMethod(node, checkMode); + return instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode); + } + function instantiateTypeWithSingleGenericCallSignature(node, type, checkMode) { + if (checkMode === 2 /* Inferential */) { + var signature = getSingleCallSignature(type); + if (signature && signature.typeParameters) { + var contextualType = getApparentTypeOfContextualType(node); + if (contextualType) { + var contextualSignature = getSingleCallSignature(getNonNullableType(contextualType)); + if (contextualSignature && !contextualSignature.typeParameters) { + return getOrCreateTypeFromSignature(instantiateSignatureInContextOf(signature, contextualSignature, getContextualMapper(node))); + } + } + } + } + return type; + } + /** + * Returns the type of an expression. Unlike checkExpression, this function is simply concerned + * with computing the type and may not fully check all contained sub-expressions for errors. + * A cache argument of true indicates that if the function performs a full type check, it is ok + * to cache the result. + */ + function getTypeOfExpression(node, cache) { + var expr = ts.skipParentheses(node); + // Optimize for the common case of a call to a function with a single non-generic call + // signature where we can just fetch the return type without checking the arguments. + if (expr.kind === 191 /* CallExpression */ && expr.expression.kind !== 98 /* SuperKeyword */ && !ts.isRequireCall(expr, /*checkArgumentIsStringLiteralLike*/ true) && !isSymbolOrSymbolForCall(expr)) { + var funcType = checkNonNullExpression(expr.expression); + var signature = getSingleCallSignature(funcType); + if (signature && !signature.typeParameters) { + return getReturnTypeOfSignature(signature); + } + } + else if (expr.kind === 194 /* TypeAssertionExpression */ || expr.kind === 212 /* AsExpression */) { + return getTypeFromTypeNode(expr.type); + } + // Otherwise simply call checkExpression. Ideally, the entire family of checkXXX functions + // should have a parameter that indicates whether full error checking is required such that + // we can perform the optimizations locally. + return cache ? checkExpressionCached(node) : checkExpression(node); + } + /** + * Returns the type of an expression. Unlike checkExpression, this function is simply concerned + * with computing the type and may not fully check all contained sub-expressions for errors. + * It is intended for uses where you know there is no contextual type, + * and requesting the contextual type might cause a circularity or other bad behaviour. + * It sets the contextual type of the node to any before calling getTypeOfExpression. + */ + function getContextFreeTypeOfExpression(node) { + var links = getNodeLinks(node); + if (links.contextFreeType) { + return links.contextFreeType; + } + var saveContextualType = node.contextualType; + node.contextualType = anyType; + var type = links.contextFreeType = checkExpression(node, 1 /* SkipContextSensitive */); + node.contextualType = saveContextualType; + return type; + } + // Checks an expression and returns its type. The contextualMapper parameter serves two purposes: When + // contextualMapper is not undefined and not equal to the identityMapper function object it indicates that the + // expression is being inferentially typed (section 4.15.2 in spec) and provides the type mapper to use in + // conjunction with the generic contextual type. When contextualMapper is equal to the identityMapper function + // object, it serves as an indicator that all contained function and arrow expressions should be considered to + // have the wildcard function type; this form of type check is used during overload resolution to exclude + // contextually typed function and arrow expressions in the initial phase. + function checkExpression(node, checkMode, forceTuple) { + var type; + if (node.kind === 148 /* QualifiedName */) { + type = checkQualifiedName(node); + } + else { + var uninstantiatedType = checkExpressionWorker(node, checkMode, forceTuple); + type = instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode); + } + if (isConstEnumObjectType(type)) { + // enum object type for const enums are only permitted in: + // - 'left' in property access + // - 'object' in indexed access + // - target in rhs of import statement + var ok = (node.parent.kind === 189 /* PropertyAccessExpression */ && node.parent.expression === node) || + (node.parent.kind === 190 /* ElementAccessExpression */ && node.parent.expression === node) || + ((node.kind === 72 /* Identifier */ || node.kind === 148 /* QualifiedName */) && isInRightSideOfImportOrExportAssignment(node) || + (node.parent.kind === 167 /* TypeQuery */ && node.parent.exprName === node)); + if (!ok) { + error(node, ts.Diagnostics.const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment_or_type_query); + } + } + return type; + } + function checkParenthesizedExpression(node, checkMode) { + var tag = ts.isInJSFile(node) ? ts.getJSDocTypeTag(node) : undefined; + if (tag) { + return checkAssertionWorker(tag, tag.typeExpression.type, node.expression, checkMode); + } + return checkExpression(node.expression, checkMode); + } + function checkExpressionWorker(node, checkMode, forceTuple) { + switch (node.kind) { + case 72 /* Identifier */: + return checkIdentifier(node); + case 100 /* ThisKeyword */: + return checkThisExpression(node); + case 98 /* SuperKeyword */: + return checkSuperExpression(node); + case 96 /* NullKeyword */: + return nullWideningType; + case 14 /* NoSubstitutionTemplateLiteral */: + case 10 /* StringLiteral */: + return getFreshTypeOfLiteralType(getLiteralType(node.text)); + case 8 /* NumericLiteral */: + checkGrammarNumericLiteral(node); + return getFreshTypeOfLiteralType(getLiteralType(+node.text)); + case 9 /* BigIntLiteral */: + checkGrammarBigIntLiteral(node); + return getFreshTypeOfLiteralType(getBigIntLiteralType(node)); + case 102 /* TrueKeyword */: + return trueType; + case 87 /* FalseKeyword */: + return falseType; + case 206 /* TemplateExpression */: + return checkTemplateExpression(node); + case 13 /* RegularExpressionLiteral */: + return globalRegExpType; + case 187 /* ArrayLiteralExpression */: + return checkArrayLiteral(node, checkMode, forceTuple); + case 188 /* ObjectLiteralExpression */: + return checkObjectLiteral(node, checkMode); + case 189 /* PropertyAccessExpression */: + return checkPropertyAccessExpression(node); + case 190 /* ElementAccessExpression */: + return checkIndexedAccess(node); + case 191 /* CallExpression */: + if (node.expression.kind === 92 /* ImportKeyword */) { + return checkImportCallExpression(node); + } + /* falls through */ + case 192 /* NewExpression */: + return checkCallExpression(node); + case 193 /* TaggedTemplateExpression */: + return checkTaggedTemplateExpression(node); + case 195 /* ParenthesizedExpression */: + return checkParenthesizedExpression(node, checkMode); + case 209 /* ClassExpression */: + return checkClassExpression(node); + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + return checkFunctionExpressionOrObjectLiteralMethod(node, checkMode); + case 199 /* TypeOfExpression */: + return checkTypeOfExpression(node); + case 194 /* TypeAssertionExpression */: + case 212 /* AsExpression */: + return checkAssertion(node); + case 213 /* NonNullExpression */: + return checkNonNullAssertion(node); + case 214 /* MetaProperty */: + return checkMetaProperty(node); + case 198 /* DeleteExpression */: + return checkDeleteExpression(node); + case 200 /* VoidExpression */: + return checkVoidExpression(node); + case 201 /* AwaitExpression */: + return checkAwaitExpression(node); + case 202 /* PrefixUnaryExpression */: + return checkPrefixUnaryExpression(node); + case 203 /* PostfixUnaryExpression */: + return checkPostfixUnaryExpression(node); + case 204 /* BinaryExpression */: + return checkBinaryExpression(node, checkMode); + case 205 /* ConditionalExpression */: + return checkConditionalExpression(node, checkMode); + case 208 /* SpreadElement */: + return checkSpreadExpression(node, checkMode); + case 210 /* OmittedExpression */: + return undefinedWideningType; + case 207 /* YieldExpression */: + return checkYieldExpression(node); + case 215 /* SyntheticExpression */: + return node.type; + case 270 /* JsxExpression */: + return checkJsxExpression(node, checkMode); + case 260 /* JsxElement */: + return checkJsxElement(node, checkMode); + case 261 /* JsxSelfClosingElement */: + return checkJsxSelfClosingElement(node, checkMode); + case 264 /* JsxFragment */: + return checkJsxFragment(node); + case 268 /* JsxAttributes */: + return checkJsxAttributes(node, checkMode); + case 262 /* JsxOpeningElement */: + ts.Debug.fail("Shouldn't ever directly check a JsxOpeningElement"); + } + return errorType; + } + // DECLARATION AND STATEMENT TYPE CHECKING + function checkTypeParameter(node) { + // Grammar Checking + if (node.expression) { + grammarErrorOnFirstToken(node.expression, ts.Diagnostics.Type_expected); + } + checkSourceElement(node.constraint); + checkSourceElement(node.default); + var typeParameter = getDeclaredTypeOfTypeParameter(getSymbolOfNode(node)); + if (!hasNonCircularBaseConstraint(typeParameter)) { + error(ts.getEffectiveConstraintOfTypeParameter(node), ts.Diagnostics.Type_parameter_0_has_a_circular_constraint, typeToString(typeParameter)); + } + if (!hasNonCircularTypeParameterDefault(typeParameter)) { + error(node.default, ts.Diagnostics.Type_parameter_0_has_a_circular_default, typeToString(typeParameter)); + } + var constraintType = getConstraintOfTypeParameter(typeParameter); + var defaultType = getDefaultFromTypeParameter(typeParameter); + if (constraintType && defaultType) { + checkTypeAssignableTo(defaultType, getTypeWithThisArgument(constraintType, defaultType), node.default, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); + } + if (produceDiagnostics) { + checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_parameter_name_cannot_be_0); + } + } + function checkParameter(node) { + // Grammar checking + // It is a SyntaxError if the Identifier "eval" or the Identifier "arguments" occurs as the + // Identifier in a PropertySetParameterList of a PropertyAssignment that is contained in strict code + // or if its FunctionBody is strict code(11.1.5). + checkGrammarDecoratorsAndModifiers(node); + checkVariableLikeDeclaration(node); + var func = ts.getContainingFunction(node); + if (ts.hasModifier(node, 92 /* ParameterPropertyModifier */)) { + if (!(func.kind === 157 /* Constructor */ && ts.nodeIsPresent(func.body))) { + error(node, ts.Diagnostics.A_parameter_property_is_only_allowed_in_a_constructor_implementation); + } + } + if (node.questionToken && ts.isBindingPattern(node.name) && func.body) { + error(node, ts.Diagnostics.A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature); + } + if (node.name && ts.isIdentifier(node.name) && (node.name.escapedText === "this" || node.name.escapedText === "new")) { + if (func.parameters.indexOf(node) !== 0) { + error(node, ts.Diagnostics.A_0_parameter_must_be_the_first_parameter, node.name.escapedText); + } + if (func.kind === 157 /* Constructor */ || func.kind === 161 /* ConstructSignature */ || func.kind === 166 /* ConstructorType */) { + error(node, ts.Diagnostics.A_constructor_cannot_have_a_this_parameter); + } + if (func.kind === 197 /* ArrowFunction */) { + error(node, ts.Diagnostics.An_arrow_function_cannot_have_a_this_parameter); + } + } + // Only check rest parameter type if it's not a binding pattern. Since binding patterns are + // not allowed in a rest parameter, we already have an error from checkGrammarParameterList. + if (node.dotDotDotToken && !ts.isBindingPattern(node.name) && !isTypeAssignableTo(getTypeOfSymbol(node.symbol), anyArrayType)) { + error(node, ts.Diagnostics.A_rest_parameter_must_be_of_an_array_type); + } + } + function checkTypePredicate(node) { + var parent = getTypePredicateParent(node); + if (!parent) { + // The parent must not be valid. + error(node, ts.Diagnostics.A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods); + return; + } + var typePredicate = getTypePredicateOfSignature(getSignatureFromDeclaration(parent)); + if (!typePredicate) { + return; + } + checkSourceElement(node.type); + var parameterName = node.parameterName; + if (ts.isThisTypePredicate(typePredicate)) { + getTypeFromThisTypeNode(parameterName); + } + else { + if (typePredicate.parameterIndex >= 0) { + if (parent.parameters[typePredicate.parameterIndex].dotDotDotToken) { + error(parameterName, ts.Diagnostics.A_type_predicate_cannot_reference_a_rest_parameter); + } + else { + var leadingError = function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type); }; + checkTypeAssignableTo(typePredicate.type, getTypeOfNode(parent.parameters[typePredicate.parameterIndex]), node.type, + /*headMessage*/ undefined, leadingError); + } + } + else if (parameterName) { + var hasReportedError = false; + for (var _i = 0, _a = parent.parameters; _i < _a.length; _i++) { + var name = _a[_i].name; + if (ts.isBindingPattern(name) && + checkIfTypePredicateVariableIsDeclaredInBindingPattern(name, parameterName, typePredicate.parameterName)) { + hasReportedError = true; + break; + } + } + if (!hasReportedError) { + error(node.parameterName, ts.Diagnostics.Cannot_find_parameter_0, typePredicate.parameterName); + } + } + } + } + function getTypePredicateParent(node) { + switch (node.parent.kind) { + case 197 /* ArrowFunction */: + case 160 /* CallSignature */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 165 /* FunctionType */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + var parent = node.parent; + if (node === parent.type) { + return parent; + } + } + } + function checkIfTypePredicateVariableIsDeclaredInBindingPattern(pattern, predicateVariableNode, predicateVariableName) { + for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (ts.isOmittedExpression(element)) { + continue; + } + var name = element.name; + if (name.kind === 72 /* Identifier */ && name.escapedText === predicateVariableName) { + error(predicateVariableNode, ts.Diagnostics.A_type_predicate_cannot_reference_element_0_in_a_binding_pattern, predicateVariableName); + return true; + } + else if (name.kind === 185 /* ArrayBindingPattern */ || name.kind === 184 /* ObjectBindingPattern */) { + if (checkIfTypePredicateVariableIsDeclaredInBindingPattern(name, predicateVariableNode, predicateVariableName)) { + return true; + } + } + } + } + function checkSignatureDeclaration(node) { + // Grammar checking + if (node.kind === 162 /* IndexSignature */) { + checkGrammarIndexSignature(node); + } + // TODO (yuisu): Remove this check in else-if when SyntaxKind.Construct is moved and ambient context is handled + else if (node.kind === 165 /* FunctionType */ || node.kind === 239 /* FunctionDeclaration */ || node.kind === 166 /* ConstructorType */ || + node.kind === 160 /* CallSignature */ || node.kind === 157 /* Constructor */ || + node.kind === 161 /* ConstructSignature */) { + checkGrammarFunctionLikeDeclaration(node); + } + var functionFlags = ts.getFunctionFlags(node); + if (!(functionFlags & 4 /* Invalid */)) { + // Async generators prior to ESNext require the __await and __asyncGenerator helpers + if ((functionFlags & 3 /* AsyncGenerator */) === 3 /* AsyncGenerator */ && languageVersion < 6 /* ESNext */) { + checkExternalEmitHelpers(node, 6144 /* AsyncGeneratorIncludes */); + } + // Async functions prior to ES2017 require the __awaiter helper + if ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */ && languageVersion < 4 /* ES2017 */) { + checkExternalEmitHelpers(node, 64 /* Awaiter */); + } + // Generator functions, Async functions, and Async Generator functions prior to + // ES2015 require the __generator helper + if ((functionFlags & 3 /* AsyncGenerator */) !== 0 /* Normal */ && languageVersion < 2 /* ES2015 */) { + checkExternalEmitHelpers(node, 128 /* Generator */); + } + } + checkTypeParameters(node.typeParameters); + ts.forEach(node.parameters, checkParameter); + // TODO(rbuckton): Should we start checking JSDoc types? + if (node.type) { + checkSourceElement(node.type); + } + if (produceDiagnostics) { + checkCollisionWithArgumentsInGeneratedCode(node); + var returnTypeNode = ts.getEffectiveReturnTypeNode(node); + if (noImplicitAny && !returnTypeNode) { + switch (node.kind) { + case 161 /* ConstructSignature */: + error(node, ts.Diagnostics.Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type); + break; + case 160 /* CallSignature */: + error(node, ts.Diagnostics.Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type); + break; + } + } + if (returnTypeNode) { + var functionFlags_1 = ts.getFunctionFlags(node); + if ((functionFlags_1 & (4 /* Invalid */ | 1 /* Generator */)) === 1 /* Generator */) { + var returnType = getTypeFromTypeNode(returnTypeNode); + if (returnType === voidType) { + error(returnTypeNode, ts.Diagnostics.A_generator_cannot_have_a_void_type_annotation); + } + else { + var generatorElementType = getIteratedTypeOfGenerator(returnType, (functionFlags_1 & 2 /* Async */) !== 0) || anyType; + var iterableIteratorInstantiation = functionFlags_1 & 2 /* Async */ + ? createAsyncIterableIteratorType(generatorElementType) // AsyncGenerator function + : createIterableIteratorType(generatorElementType); // Generator function + // Naively, one could check that IterableIterator is assignable to the return type annotation. + // However, that would not catch the error in the following case. + // + // interface BadGenerator extends Iterable, Iterator { } + // function* g(): BadGenerator { } // Iterable and Iterator have different types! + // + checkTypeAssignableTo(iterableIteratorInstantiation, returnType, returnTypeNode); + } + } + else if ((functionFlags_1 & 3 /* AsyncGenerator */) === 2 /* Async */) { + checkAsyncFunctionReturnType(node, returnTypeNode); + } + } + if (node.kind !== 162 /* IndexSignature */ && node.kind !== 289 /* JSDocFunctionType */) { + registerForUnusedIdentifiersCheck(node); + } + } + } + function checkClassForDuplicateDeclarations(node) { + var Declaration; + (function (Declaration) { + Declaration[Declaration["Getter"] = 1] = "Getter"; + Declaration[Declaration["Setter"] = 2] = "Setter"; + Declaration[Declaration["Method"] = 4] = "Method"; + Declaration[Declaration["Property"] = 3] = "Property"; + })(Declaration || (Declaration = {})); + var instanceNames = ts.createUnderscoreEscapedMap(); + var staticNames = ts.createUnderscoreEscapedMap(); + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + if (member.kind === 157 /* Constructor */) { + for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { + var param = _c[_b]; + if (ts.isParameterPropertyDeclaration(param) && !ts.isBindingPattern(param.name)) { + addName(instanceNames, param.name, param.name.escapedText, 3 /* Property */); + } + } + } + else { + var isStatic = ts.hasModifier(member, 32 /* Static */); + var names = isStatic ? staticNames : instanceNames; + var name = member.name; + var memberName = name && ts.getPropertyNameForPropertyNameNode(name); + if (name && memberName) { + switch (member.kind) { + case 158 /* GetAccessor */: + addName(names, name, memberName, 1 /* Getter */); + break; + case 159 /* SetAccessor */: + addName(names, name, memberName, 2 /* Setter */); + break; + case 154 /* PropertyDeclaration */: + addName(names, name, memberName, 3 /* Property */); + break; + case 156 /* MethodDeclaration */: + addName(names, name, memberName, 4 /* Method */); + break; + } + } + } + } + function addName(names, location, name, meaning) { + var prev = names.get(name); + if (prev) { + if (prev & 4 /* Method */) { + if (meaning !== 4 /* Method */) { + error(location, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(location)); + } + } + else if (prev & meaning) { + error(location, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(location)); + } + else { + names.set(name, prev | meaning); + } + } + else { + names.set(name, meaning); + } + } + } + /** + * Static members being set on a constructor function may conflict with built-in properties + * of Function. Esp. in ECMAScript 5 there are non-configurable and non-writable + * built-in properties. This check issues a transpile error when a class has a static + * member with the same name as a non-writable built-in property. + * + * @see http://www.ecma-international.org/ecma-262/5.1/#sec-15.3.3 + * @see http://www.ecma-international.org/ecma-262/5.1/#sec-15.3.5 + * @see http://www.ecma-international.org/ecma-262/6.0/#sec-properties-of-the-function-constructor + * @see http://www.ecma-international.org/ecma-262/6.0/#sec-function-instances + */ + function checkClassForStaticPropertyNameConflicts(node) { + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + var memberNameNode = member.name; + var isStatic = ts.hasModifier(member, 32 /* Static */); + if (isStatic && memberNameNode) { + var memberName = ts.getPropertyNameForPropertyNameNode(memberNameNode); + switch (memberName) { + case "name": + case "length": + case "caller": + case "arguments": + case "prototype": + var message = ts.Diagnostics.Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1; + var className = getNameOfSymbolAsWritten(getSymbolOfNode(node)); + error(memberNameNode, message, memberName, className); + break; + } + } + } + } + function checkObjectTypeForDuplicateDeclarations(node) { + var names = ts.createMap(); + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + if (member.kind === 153 /* PropertySignature */) { + var memberName = void 0; + var name = member.name; + switch (name.kind) { + case 10 /* StringLiteral */: + case 8 /* NumericLiteral */: + memberName = name.text; + break; + case 72 /* Identifier */: + memberName = ts.idText(name); + break; + default: + continue; + } + if (names.get(memberName)) { + error(ts.getNameOfDeclaration(member.symbol.valueDeclaration), ts.Diagnostics.Duplicate_identifier_0, memberName); + error(member.name, ts.Diagnostics.Duplicate_identifier_0, memberName); + } + else { + names.set(memberName, true); + } + } + } + } + function checkTypeForDuplicateIndexSignatures(node) { + if (node.kind === 241 /* InterfaceDeclaration */) { + var nodeSymbol = getSymbolOfNode(node); + // in case of merging interface declaration it is possible that we'll enter this check procedure several times for every declaration + // to prevent this run check only for the first declaration of a given kind + if (nodeSymbol.declarations.length > 0 && nodeSymbol.declarations[0] !== node) { + return; + } + } + // TypeScript 1.0 spec (April 2014) + // 3.7.4: An object type can contain at most one string index signature and one numeric index signature. + // 8.5: A class declaration can have at most one string index member declaration and one numeric index member declaration + var indexSymbol = getIndexSymbol(getSymbolOfNode(node)); + if (indexSymbol) { + var seenNumericIndexer = false; + var seenStringIndexer = false; + for (var _i = 0, _a = indexSymbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + var declaration = decl; + if (declaration.parameters.length === 1 && declaration.parameters[0].type) { + switch (declaration.parameters[0].type.kind) { + case 138 /* StringKeyword */: + if (!seenStringIndexer) { + seenStringIndexer = true; + } + else { + error(declaration, ts.Diagnostics.Duplicate_string_index_signature); + } + break; + case 135 /* NumberKeyword */: + if (!seenNumericIndexer) { + seenNumericIndexer = true; + } + else { + error(declaration, ts.Diagnostics.Duplicate_number_index_signature); + } + break; + } + } + } + } + } + function checkPropertyDeclaration(node) { + // Grammar checking + if (!checkGrammarDecoratorsAndModifiers(node) && !checkGrammarProperty(node)) + checkGrammarComputedPropertyName(node.name); + checkVariableLikeDeclaration(node); + } + function checkMethodDeclaration(node) { + // Grammar checking + if (!checkGrammarMethod(node)) + checkGrammarComputedPropertyName(node.name); + // Grammar checking for modifiers is done inside the function checkGrammarFunctionLikeDeclaration + checkFunctionOrMethodDeclaration(node); + // Abstract methods cannot have an implementation. + // Extra checks are to avoid reporting multiple errors relating to the "abstractness" of the node. + if (ts.hasModifier(node, 128 /* Abstract */) && node.kind === 156 /* MethodDeclaration */ && node.body) { + error(node, ts.Diagnostics.Method_0_cannot_have_an_implementation_because_it_is_marked_abstract, ts.declarationNameToString(node.name)); + } + } + function checkConstructorDeclaration(node) { + // Grammar check on signature of constructor and modifier of the constructor is done in checkSignatureDeclaration function. + checkSignatureDeclaration(node); + // Grammar check for checking only related to constructorDeclaration + if (!checkGrammarConstructorTypeParameters(node)) + checkGrammarConstructorTypeAnnotation(node); + checkSourceElement(node.body); + var symbol = getSymbolOfNode(node); + var firstDeclaration = ts.getDeclarationOfKind(symbol, node.kind); + // Only type check the symbol once + if (node === firstDeclaration) { + checkFunctionOrConstructorSymbol(symbol); + } + // exit early in the case of signature - super checks are not relevant to them + if (ts.nodeIsMissing(node.body)) { + return; + } + if (!produceDiagnostics) { + return; + } + function isInstancePropertyWithInitializer(n) { + return n.kind === 154 /* PropertyDeclaration */ && + !ts.hasModifier(n, 32 /* Static */) && + !!n.initializer; + } + // TS 1.0 spec (April 2014): 8.3.2 + // Constructors of classes with no extends clause may not contain super calls, whereas + // constructors of derived classes must contain at least one super call somewhere in their function body. + var containingClassDecl = node.parent; + if (ts.getEffectiveBaseTypeNode(containingClassDecl)) { + captureLexicalThis(node.parent, containingClassDecl); + var classExtendsNull = classDeclarationExtendsNull(containingClassDecl); + var superCall = getSuperCallInConstructor(node); + if (superCall) { + if (classExtendsNull) { + error(superCall, ts.Diagnostics.A_constructor_cannot_contain_a_super_call_when_its_class_extends_null); + } + // The first statement in the body of a constructor (excluding prologue directives) must be a super call + // if both of the following are true: + // - The containing class is a derived class. + // - The constructor declares parameter properties + // or the containing class declares instance member variables with initializers. + var superCallShouldBeFirst = ts.some(node.parent.members, isInstancePropertyWithInitializer) || + ts.some(node.parameters, function (p) { return ts.hasModifier(p, 92 /* ParameterPropertyModifier */); }); + // Skip past any prologue directives to find the first statement + // to ensure that it was a super call. + if (superCallShouldBeFirst) { + var statements = node.body.statements; + var superCallStatement = void 0; + for (var _i = 0, statements_2 = statements; _i < statements_2.length; _i++) { + var statement = statements_2[_i]; + if (statement.kind === 221 /* ExpressionStatement */ && ts.isSuperCall(statement.expression)) { + superCallStatement = statement; + break; + } + if (!ts.isPrologueDirective(statement)) { + break; + } + } + if (!superCallStatement) { + error(node, ts.Diagnostics.A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_properties_or_has_parameter_properties); + } + } + } + else if (!classExtendsNull) { + error(node, ts.Diagnostics.Constructors_for_derived_classes_must_contain_a_super_call); + } + } + } + function checkAccessorDeclaration(node) { + if (produceDiagnostics) { + // Grammar checking accessors + if (!checkGrammarFunctionLikeDeclaration(node) && !checkGrammarAccessor(node)) + checkGrammarComputedPropertyName(node.name); + checkDecorators(node); + checkSignatureDeclaration(node); + if (node.kind === 158 /* GetAccessor */) { + if (!(node.flags & 4194304 /* Ambient */) && ts.nodeIsPresent(node.body) && (node.flags & 128 /* HasImplicitReturn */)) { + if (!(node.flags & 256 /* HasExplicitReturn */)) { + error(node.name, ts.Diagnostics.A_get_accessor_must_return_a_value); + } + } + } + // Do not use hasDynamicName here, because that returns false for well known symbols. + // We want to perform checkComputedPropertyName for all computed properties, including + // well known symbols. + if (node.name.kind === 149 /* ComputedPropertyName */) { + checkComputedPropertyName(node.name); + } + if (!hasNonBindableDynamicName(node)) { + // TypeScript 1.0 spec (April 2014): 8.4.3 + // Accessors for the same member name must specify the same accessibility. + var otherKind = node.kind === 158 /* GetAccessor */ ? 159 /* SetAccessor */ : 158 /* GetAccessor */; + var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(node), otherKind); + if (otherAccessor) { + var nodeFlags = ts.getModifierFlags(node); + var otherFlags = ts.getModifierFlags(otherAccessor); + if ((nodeFlags & 28 /* AccessibilityModifier */) !== (otherFlags & 28 /* AccessibilityModifier */)) { + error(node.name, ts.Diagnostics.Getter_and_setter_accessors_do_not_agree_in_visibility); + } + if ((nodeFlags & 128 /* Abstract */) !== (otherFlags & 128 /* Abstract */)) { + error(node.name, ts.Diagnostics.Accessors_must_both_be_abstract_or_non_abstract); + } + // TypeScript 1.0 spec (April 2014): 4.5 + // If both accessors include type annotations, the specified types must be identical. + checkAccessorDeclarationTypesIdentical(node, otherAccessor, getAnnotatedAccessorType, ts.Diagnostics.get_and_set_accessor_must_have_the_same_type); + checkAccessorDeclarationTypesIdentical(node, otherAccessor, getThisTypeOfDeclaration, ts.Diagnostics.get_and_set_accessor_must_have_the_same_this_type); + } + } + var returnType = getTypeOfAccessors(getSymbolOfNode(node)); + if (node.kind === 158 /* GetAccessor */) { + checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnType); + } + } + checkSourceElement(node.body); + } + function checkAccessorDeclarationTypesIdentical(first, second, getAnnotatedType, message) { + var firstType = getAnnotatedType(first); + var secondType = getAnnotatedType(second); + if (firstType && secondType && !isTypeIdenticalTo(firstType, secondType)) { + error(first, message); + } + } + function checkMissingDeclaration(node) { + checkDecorators(node); + } + function getEffectiveTypeArguments(node, typeParameters) { + return fillMissingTypeArguments(ts.map(node.typeArguments, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJSFile(node)); + } + function checkTypeArgumentConstraints(node, typeParameters) { + var typeArguments; + var mapper; + var result = true; + for (var i = 0; i < typeParameters.length; i++) { + var constraint = getConstraintOfTypeParameter(typeParameters[i]); + if (constraint) { + if (!typeArguments) { + typeArguments = getEffectiveTypeArguments(node, typeParameters); + mapper = createTypeMapper(typeParameters, typeArguments); + } + result = result && checkTypeAssignableTo(typeArguments[i], instantiateType(constraint, mapper), node.typeArguments[i], ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); + } + } + return result; + } + function getTypeParametersForTypeReference(node) { + var type = getTypeFromTypeReference(node); + if (type !== errorType) { + var symbol = getNodeLinks(node).resolvedSymbol; + if (symbol) { + return symbol.flags & 524288 /* TypeAlias */ && getSymbolLinks(symbol).typeParameters || + (ts.getObjectFlags(type) & 4 /* Reference */ ? type.target.localTypeParameters : undefined); + } + } + return undefined; + } + function checkTypeReferenceNode(node) { + checkGrammarTypeArguments(node, node.typeArguments); + if (node.kind === 164 /* TypeReference */ && node.typeName.jsdocDotPos !== undefined && !ts.isInJSFile(node) && !ts.isInJSDoc(node)) { + grammarErrorAtPos(node, node.typeName.jsdocDotPos, 1, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments); + } + var type = getTypeFromTypeReference(node); + if (type !== errorType) { + if (node.typeArguments) { + // Do type argument local checks only if referenced type is successfully resolved + ts.forEach(node.typeArguments, checkSourceElement); + if (produceDiagnostics) { + var typeParameters = getTypeParametersForTypeReference(node); + if (typeParameters) { + checkTypeArgumentConstraints(node, typeParameters); + } + } + } + if (type.flags & 32 /* Enum */ && getNodeLinks(node).resolvedSymbol.flags & 8 /* EnumMember */) { + error(node, ts.Diagnostics.Enum_type_0_has_members_with_initializers_that_are_not_literals, typeToString(type)); + } + } + } + function getTypeArgumentConstraint(node) { + var typeReferenceNode = ts.tryCast(node.parent, ts.isTypeReferenceType); + if (!typeReferenceNode) + return undefined; + var typeParameters = getTypeParametersForTypeReference(typeReferenceNode); // TODO: GH#18217 + var constraint = getConstraintOfTypeParameter(typeParameters[typeReferenceNode.typeArguments.indexOf(node)]); + return constraint && instantiateType(constraint, createTypeMapper(typeParameters, getEffectiveTypeArguments(typeReferenceNode, typeParameters))); + } + function checkTypeQuery(node) { + getTypeFromTypeQueryNode(node); + } + function checkTypeLiteral(node) { + ts.forEach(node.members, checkSourceElement); + if (produceDiagnostics) { + var type = getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node); + checkIndexConstraints(type); + checkTypeForDuplicateIndexSignatures(node); + checkObjectTypeForDuplicateDeclarations(node); + } + } + function checkArrayType(node) { + checkSourceElement(node.elementType); + } + function checkTupleType(node) { + var elementTypes = node.elementTypes; + var seenOptionalElement = false; + for (var i = 0; i < elementTypes.length; i++) { + var e = elementTypes[i]; + if (e.kind === 172 /* RestType */) { + if (i !== elementTypes.length - 1) { + grammarErrorOnNode(e, ts.Diagnostics.A_rest_element_must_be_last_in_a_tuple_type); + break; + } + if (!isArrayType(getTypeFromTypeNode(e))) { + error(e, ts.Diagnostics.A_rest_element_type_must_be_an_array_type); + } + } + else if (e.kind === 171 /* OptionalType */) { + seenOptionalElement = true; + } + else if (seenOptionalElement) { + grammarErrorOnNode(e, ts.Diagnostics.A_required_element_cannot_follow_an_optional_element); + break; + } + } + checkGrammarForDisallowedTrailingComma(node.elementTypes); + ts.forEach(node.elementTypes, checkSourceElement); + } + function checkUnionOrIntersectionType(node) { + ts.forEach(node.types, checkSourceElement); + } + function checkIndexedAccessIndexType(type, accessNode) { + if (!(type.flags & 8388608 /* IndexedAccess */)) { + return type; + } + // Check if the index type is assignable to 'keyof T' for the object type. + var objectType = type.objectType; + var indexType = type.indexType; + if (isTypeAssignableTo(indexType, getIndexType(objectType, /*stringsOnly*/ false))) { + if (accessNode.kind === 190 /* ElementAccessExpression */ && ts.isAssignmentTarget(accessNode) && + ts.getObjectFlags(objectType) & 32 /* Mapped */ && getMappedTypeModifiers(objectType) & 1 /* IncludeReadonly */) { + error(accessNode, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(objectType)); + } + return type; + } + // Check if we're indexing with a numeric type and if either object or index types + // is a generic type with a constraint that has a numeric index signature. + if (getIndexInfoOfType(getApparentType(objectType), 1 /* Number */) && isTypeAssignableToKind(indexType, 296 /* NumberLike */)) { + return type; + } + error(accessNode, ts.Diagnostics.Type_0_cannot_be_used_to_index_type_1, typeToString(indexType), typeToString(objectType)); + return type; + } + function checkIndexedAccessType(node) { + checkSourceElement(node.objectType); + checkSourceElement(node.indexType); + checkIndexedAccessIndexType(getTypeFromIndexedAccessTypeNode(node), node); + } + function checkMappedType(node) { + checkSourceElement(node.typeParameter); + checkSourceElement(node.type); + if (!node.type) { + reportImplicitAny(node, anyType); + } + var type = getTypeFromMappedTypeNode(node); + var constraintType = getConstraintTypeFromMappedType(type); + checkTypeAssignableTo(constraintType, keyofConstraintType, ts.getEffectiveConstraintOfTypeParameter(node.typeParameter)); + } + function checkThisType(node) { + getTypeFromThisTypeNode(node); + } + function checkTypeOperator(node) { + checkGrammarTypeOperatorNode(node); + checkSourceElement(node.type); + } + function checkConditionalType(node) { + ts.forEachChild(node, checkSourceElement); + } + function checkInferType(node) { + if (!ts.findAncestor(node, function (n) { return n.parent && n.parent.kind === 175 /* ConditionalType */ && n.parent.extendsType === n; })) { + grammarErrorOnNode(node, ts.Diagnostics.infer_declarations_are_only_permitted_in_the_extends_clause_of_a_conditional_type); + } + checkSourceElement(node.typeParameter); + registerForUnusedIdentifiersCheck(node); + } + function checkImportType(node) { + checkSourceElement(node.argument); + getTypeFromTypeNode(node); + } + function isPrivateWithinAmbient(node) { + return ts.hasModifier(node, 8 /* Private */) && !!(node.flags & 4194304 /* Ambient */); + } + function getEffectiveDeclarationFlags(n, flagsToCheck) { + var flags = ts.getCombinedModifierFlags(n); + // children of classes (even ambient classes) should not be marked as ambient or export + // because those flags have no useful semantics there. + if (n.parent.kind !== 241 /* InterfaceDeclaration */ && + n.parent.kind !== 240 /* ClassDeclaration */ && + n.parent.kind !== 209 /* ClassExpression */ && + n.flags & 4194304 /* Ambient */) { + if (!(flags & 2 /* Ambient */) && !(ts.isModuleBlock(n.parent) && ts.isModuleDeclaration(n.parent.parent) && ts.isGlobalScopeAugmentation(n.parent.parent))) { + // It is nested in an ambient context, which means it is automatically exported + flags |= 1 /* Export */; + } + flags |= 2 /* Ambient */; + } + return flags & flagsToCheck; + } + function checkFunctionOrConstructorSymbol(symbol) { + if (!produceDiagnostics) { + return; + } + function getCanonicalOverload(overloads, implementation) { + // Consider the canonical set of flags to be the flags of the bodyDeclaration or the first declaration + // Error on all deviations from this canonical set of flags + // The caveat is that if some overloads are defined in lib.d.ts, we don't want to + // report the errors on those. To achieve this, we will say that the implementation is + // the canonical signature only if it is in the same container as the first overload + var implementationSharesContainerWithFirstOverload = implementation !== undefined && implementation.parent === overloads[0].parent; + return implementationSharesContainerWithFirstOverload ? implementation : overloads[0]; + } + function checkFlagAgreementBetweenOverloads(overloads, implementation, flagsToCheck, someOverloadFlags, allOverloadFlags) { + // Error if some overloads have a flag that is not shared by all overloads. To find the + // deviations, we XOR someOverloadFlags with allOverloadFlags + var someButNotAllOverloadFlags = someOverloadFlags ^ allOverloadFlags; + if (someButNotAllOverloadFlags !== 0) { + var canonicalFlags_1 = getEffectiveDeclarationFlags(getCanonicalOverload(overloads, implementation), flagsToCheck); + ts.forEach(overloads, function (o) { + var deviation = getEffectiveDeclarationFlags(o, flagsToCheck) ^ canonicalFlags_1; + if (deviation & 1 /* Export */) { + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_exported_or_non_exported); + } + else if (deviation & 2 /* Ambient */) { + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_ambient_or_non_ambient); + } + else if (deviation & (8 /* Private */ | 16 /* Protected */)) { + error(ts.getNameOfDeclaration(o) || o, ts.Diagnostics.Overload_signatures_must_all_be_public_private_or_protected); + } + else if (deviation & 128 /* Abstract */) { + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_abstract_or_non_abstract); + } + }); + } + } + function checkQuestionTokenAgreementBetweenOverloads(overloads, implementation, someHaveQuestionToken, allHaveQuestionToken) { + if (someHaveQuestionToken !== allHaveQuestionToken) { + var canonicalHasQuestionToken_1 = ts.hasQuestionToken(getCanonicalOverload(overloads, implementation)); + ts.forEach(overloads, function (o) { + var deviation = ts.hasQuestionToken(o) !== canonicalHasQuestionToken_1; + if (deviation) { + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_optional_or_required); + } + }); + } + } + var flagsToCheck = 1 /* Export */ | 2 /* Ambient */ | 8 /* Private */ | 16 /* Protected */ | 128 /* Abstract */; + var someNodeFlags = 0 /* None */; + var allNodeFlags = flagsToCheck; + var someHaveQuestionToken = false; + var allHaveQuestionToken = true; + var hasOverloads = false; + var bodyDeclaration; + var lastSeenNonAmbientDeclaration; + var previousDeclaration; + var declarations = symbol.declarations; + var isConstructor = (symbol.flags & 16384 /* Constructor */) !== 0; + function reportImplementationExpectedError(node) { + if (node.name && ts.nodeIsMissing(node.name)) { + return; + } + var seen = false; + var subsequentNode = ts.forEachChild(node.parent, function (c) { + if (seen) { + return c; + } + else { + seen = c === node; + } + }); + // We may be here because of some extra nodes between overloads that could not be parsed into a valid node. + // In this case the subsequent node is not really consecutive (.pos !== node.end), and we must ignore it here. + if (subsequentNode && subsequentNode.pos === node.end) { + if (subsequentNode.kind === node.kind) { + var errorNode_1 = subsequentNode.name || subsequentNode; + // TODO: GH#17345: These are methods, so handle computed name case. (`Always allowing computed property names is *not* the correct behavior!) + var subsequentName = subsequentNode.name; + if (node.name && subsequentName && + (ts.isComputedPropertyName(node.name) && ts.isComputedPropertyName(subsequentName) || + !ts.isComputedPropertyName(node.name) && !ts.isComputedPropertyName(subsequentName) && ts.getEscapedTextOfIdentifierOrLiteral(node.name) === ts.getEscapedTextOfIdentifierOrLiteral(subsequentName))) { + var reportError = (node.kind === 156 /* MethodDeclaration */ || node.kind === 155 /* MethodSignature */) && + ts.hasModifier(node, 32 /* Static */) !== ts.hasModifier(subsequentNode, 32 /* Static */); + // we can get here in two cases + // 1. mixed static and instance class members + // 2. something with the same name was defined before the set of overloads that prevents them from merging + // here we'll report error only for the first case since for second we should already report error in binder + if (reportError) { + var diagnostic = ts.hasModifier(node, 32 /* Static */) ? ts.Diagnostics.Function_overload_must_be_static : ts.Diagnostics.Function_overload_must_not_be_static; + error(errorNode_1, diagnostic); + } + return; + } + else if (ts.nodeIsPresent(subsequentNode.body)) { + error(errorNode_1, ts.Diagnostics.Function_implementation_name_must_be_0, ts.declarationNameToString(node.name)); + return; + } + } + } + var errorNode = node.name || node; + if (isConstructor) { + error(errorNode, ts.Diagnostics.Constructor_implementation_is_missing); + } + else { + // Report different errors regarding non-consecutive blocks of declarations depending on whether + // the node in question is abstract. + if (ts.hasModifier(node, 128 /* Abstract */)) { + error(errorNode, ts.Diagnostics.All_declarations_of_an_abstract_method_must_be_consecutive); + } + else { + error(errorNode, ts.Diagnostics.Function_implementation_is_missing_or_not_immediately_following_the_declaration); + } + } + } + var duplicateFunctionDeclaration = false; + var multipleConstructorImplementation = false; + for (var _i = 0, declarations_4 = declarations; _i < declarations_4.length; _i++) { + var current = declarations_4[_i]; + var node = current; + var inAmbientContext = node.flags & 4194304 /* Ambient */; + var inAmbientContextOrInterface = node.parent.kind === 241 /* InterfaceDeclaration */ || node.parent.kind === 168 /* TypeLiteral */ || inAmbientContext; + if (inAmbientContextOrInterface) { + // check if declarations are consecutive only if they are non-ambient + // 1. ambient declarations can be interleaved + // i.e. this is legal + // declare function foo(); + // declare function bar(); + // declare function foo(); + // 2. mixing ambient and non-ambient declarations is a separate error that will be reported - do not want to report an extra one + previousDeclaration = undefined; + } + if (node.kind === 239 /* FunctionDeclaration */ || node.kind === 156 /* MethodDeclaration */ || node.kind === 155 /* MethodSignature */ || node.kind === 157 /* Constructor */) { + var currentNodeFlags = getEffectiveDeclarationFlags(node, flagsToCheck); + someNodeFlags |= currentNodeFlags; + allNodeFlags &= currentNodeFlags; + someHaveQuestionToken = someHaveQuestionToken || ts.hasQuestionToken(node); + allHaveQuestionToken = allHaveQuestionToken && ts.hasQuestionToken(node); + if (ts.nodeIsPresent(node.body) && bodyDeclaration) { + if (isConstructor) { + multipleConstructorImplementation = true; + } + else { + duplicateFunctionDeclaration = true; + } + } + else if (previousDeclaration && previousDeclaration.parent === node.parent && previousDeclaration.end !== node.pos) { + reportImplementationExpectedError(previousDeclaration); + } + if (ts.nodeIsPresent(node.body)) { + if (!bodyDeclaration) { + bodyDeclaration = node; + } + } + else { + hasOverloads = true; + } + previousDeclaration = node; + if (!inAmbientContextOrInterface) { + lastSeenNonAmbientDeclaration = node; + } + } + } + if (multipleConstructorImplementation) { + ts.forEach(declarations, function (declaration) { + error(declaration, ts.Diagnostics.Multiple_constructor_implementations_are_not_allowed); + }); + } + if (duplicateFunctionDeclaration) { + ts.forEach(declarations, function (declaration) { + error(ts.getNameOfDeclaration(declaration), ts.Diagnostics.Duplicate_function_implementation); + }); + } + // Abstract methods can't have an implementation -- in particular, they don't need one. + if (lastSeenNonAmbientDeclaration && !lastSeenNonAmbientDeclaration.body && + !ts.hasModifier(lastSeenNonAmbientDeclaration, 128 /* Abstract */) && !lastSeenNonAmbientDeclaration.questionToken) { + reportImplementationExpectedError(lastSeenNonAmbientDeclaration); + } + if (hasOverloads) { + checkFlagAgreementBetweenOverloads(declarations, bodyDeclaration, flagsToCheck, someNodeFlags, allNodeFlags); + checkQuestionTokenAgreementBetweenOverloads(declarations, bodyDeclaration, someHaveQuestionToken, allHaveQuestionToken); + if (bodyDeclaration) { + var signatures = getSignaturesOfSymbol(symbol); + var bodySignature = getSignatureFromDeclaration(bodyDeclaration); + for (var _a = 0, signatures_6 = signatures; _a < signatures_6.length; _a++) { + var signature = signatures_6[_a]; + if (!isImplementationCompatibleWithOverload(bodySignature, signature)) { + error(signature.declaration, ts.Diagnostics.Overload_signature_is_not_compatible_with_function_implementation); + break; + } + } + } + } + } + var DeclarationSpaces; + (function (DeclarationSpaces) { + DeclarationSpaces[DeclarationSpaces["None"] = 0] = "None"; + DeclarationSpaces[DeclarationSpaces["ExportValue"] = 1] = "ExportValue"; + DeclarationSpaces[DeclarationSpaces["ExportType"] = 2] = "ExportType"; + DeclarationSpaces[DeclarationSpaces["ExportNamespace"] = 4] = "ExportNamespace"; + })(DeclarationSpaces || (DeclarationSpaces = {})); + function checkExportsOnMergedDeclarations(node) { + if (!produceDiagnostics) { + return; + } + // if localSymbol is defined on node then node itself is exported - check is required + var symbol = node.localSymbol; + if (!symbol) { + // local symbol is undefined => this declaration is non-exported. + // however symbol might contain other declarations that are exported + symbol = getSymbolOfNode(node); + if (!symbol.exportSymbol) { + // this is a pure local symbol (all declarations are non-exported) - no need to check anything + return; + } + } + // run the check only for the first declaration in the list + if (ts.getDeclarationOfKind(symbol, node.kind) !== node) { + return; + } + var exportedDeclarationSpaces = 0 /* None */; + var nonExportedDeclarationSpaces = 0 /* None */; + var defaultExportedDeclarationSpaces = 0 /* None */; + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var d = _a[_i]; + var declarationSpaces = getDeclarationSpaces(d); + var effectiveDeclarationFlags = getEffectiveDeclarationFlags(d, 1 /* Export */ | 512 /* Default */); + if (effectiveDeclarationFlags & 1 /* Export */) { + if (effectiveDeclarationFlags & 512 /* Default */) { + defaultExportedDeclarationSpaces |= declarationSpaces; + } + else { + exportedDeclarationSpaces |= declarationSpaces; + } + } + else { + nonExportedDeclarationSpaces |= declarationSpaces; + } + } + // Spaces for anything not declared a 'default export'. + var nonDefaultExportedDeclarationSpaces = exportedDeclarationSpaces | nonExportedDeclarationSpaces; + var commonDeclarationSpacesForExportsAndLocals = exportedDeclarationSpaces & nonExportedDeclarationSpaces; + var commonDeclarationSpacesForDefaultAndNonDefault = defaultExportedDeclarationSpaces & nonDefaultExportedDeclarationSpaces; + if (commonDeclarationSpacesForExportsAndLocals || commonDeclarationSpacesForDefaultAndNonDefault) { + // declaration spaces for exported and non-exported declarations intersect + for (var _b = 0, _c = symbol.declarations; _b < _c.length; _b++) { + var d = _c[_b]; + var declarationSpaces = getDeclarationSpaces(d); + var name = ts.getNameOfDeclaration(d); + // Only error on the declarations that contributed to the intersecting spaces. + if (declarationSpaces & commonDeclarationSpacesForDefaultAndNonDefault) { + error(name, ts.Diagnostics.Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead, ts.declarationNameToString(name)); + } + else if (declarationSpaces & commonDeclarationSpacesForExportsAndLocals) { + error(name, ts.Diagnostics.Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local, ts.declarationNameToString(name)); + } + } + } + function getDeclarationSpaces(decl) { + var d = decl; + switch (d.kind) { + case 241 /* InterfaceDeclaration */: + case 242 /* TypeAliasDeclaration */: + // A jsdoc typedef and callback are, by definition, type aliases + case 304 /* JSDocTypedefTag */: + case 297 /* JSDocCallbackTag */: + return 2 /* ExportType */; + case 244 /* ModuleDeclaration */: + return ts.isAmbientModule(d) || ts.getModuleInstanceState(d) !== 0 /* NonInstantiated */ + ? 4 /* ExportNamespace */ | 1 /* ExportValue */ + : 4 /* ExportNamespace */; + case 240 /* ClassDeclaration */: + case 243 /* EnumDeclaration */: + return 2 /* ExportType */ | 1 /* ExportValue */; + case 279 /* SourceFile */: + return 2 /* ExportType */ | 1 /* ExportValue */ | 4 /* ExportNamespace */; + case 254 /* ExportAssignment */: + // Export assigned entity name expressions act as aliases and should fall through, otherwise they export values + if (!ts.isEntityNameExpression(d.expression)) { + return 1 /* ExportValue */; + } + d = d.expression; + /* falls through */ + // The below options all declare an Alias, which is allowed to merge with other values within the importing module + case 248 /* ImportEqualsDeclaration */: + case 251 /* NamespaceImport */: + case 250 /* ImportClause */: + var result_4 = 0 /* None */; + var target = resolveAlias(getSymbolOfNode(d)); + ts.forEach(target.declarations, function (d) { result_4 |= getDeclarationSpaces(d); }); + return result_4; + case 237 /* VariableDeclaration */: + case 186 /* BindingElement */: + case 239 /* FunctionDeclaration */: + case 253 /* ImportSpecifier */: // https://github.com/Microsoft/TypeScript/pull/7591 + return 1 /* ExportValue */; + default: + return ts.Debug.fail(ts.Debug.showSyntaxKind(d)); + } + } + } + function getAwaitedTypeOfPromise(type, errorNode, diagnosticMessage) { + var promisedType = getPromisedTypeOfPromise(type, errorNode); + return promisedType && getAwaitedType(promisedType, errorNode, diagnosticMessage); + } + /** + * Gets the "promised type" of a promise. + * @param type The type of the promise. + * @remarks The "promised type" of a type is the type of the "value" parameter of the "onfulfilled" callback. + */ + function getPromisedTypeOfPromise(promise, errorNode) { + // + // { // promise + // then( // thenFunction + // onfulfilled: ( // onfulfilledParameterType + // value: T // valueParameterType + // ) => any + // ): any; + // } + // + if (isTypeAny(promise)) { + return undefined; + } + var typeAsPromise = promise; + if (typeAsPromise.promisedTypeOfPromise) { + return typeAsPromise.promisedTypeOfPromise; + } + if (isReferenceToType(promise, getGlobalPromiseType(/*reportErrors*/ false))) { + return typeAsPromise.promisedTypeOfPromise = promise.typeArguments[0]; + } + var thenFunction = getTypeOfPropertyOfType(promise, "then"); // TODO: GH#18217 + if (isTypeAny(thenFunction)) { + return undefined; + } + var thenSignatures = thenFunction ? getSignaturesOfType(thenFunction, 0 /* Call */) : ts.emptyArray; + if (thenSignatures.length === 0) { + if (errorNode) { + error(errorNode, ts.Diagnostics.A_promise_must_have_a_then_method); + } + return undefined; + } + var onfulfilledParameterType = getTypeWithFacts(getUnionType(ts.map(thenSignatures, getTypeOfFirstParameterOfSignature)), 2097152 /* NEUndefinedOrNull */); + if (isTypeAny(onfulfilledParameterType)) { + return undefined; + } + var onfulfilledParameterSignatures = getSignaturesOfType(onfulfilledParameterType, 0 /* Call */); + if (onfulfilledParameterSignatures.length === 0) { + if (errorNode) { + error(errorNode, ts.Diagnostics.The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback); + } + return undefined; + } + return typeAsPromise.promisedTypeOfPromise = getUnionType(ts.map(onfulfilledParameterSignatures, getTypeOfFirstParameterOfSignature), 2 /* Subtype */); + } + /** + * Gets the "awaited type" of a type. + * @param type The type to await. + * @remarks The "awaited type" of an expression is its "promised type" if the expression is a + * Promise-like type; otherwise, it is the type of the expression. This is used to reflect + * The runtime behavior of the `await` keyword. + */ + function checkAwaitedType(type, errorNode, diagnosticMessage) { + return getAwaitedType(type, errorNode, diagnosticMessage) || errorType; + } + function getAwaitedType(type, errorNode, diagnosticMessage) { + var typeAsAwaitable = type; + if (typeAsAwaitable.awaitedTypeOfType) { + return typeAsAwaitable.awaitedTypeOfType; + } + if (isTypeAny(type)) { + return typeAsAwaitable.awaitedTypeOfType = type; + } + if (type.flags & 1048576 /* Union */) { + var types = void 0; + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var constituentType = _a[_i]; + types = ts.append(types, getAwaitedType(constituentType, errorNode, diagnosticMessage)); + } + if (!types) { + return undefined; + } + return typeAsAwaitable.awaitedTypeOfType = getUnionType(types); + } + var promisedType = getPromisedTypeOfPromise(type); + if (promisedType) { + if (type.id === promisedType.id || awaitedTypeStack.indexOf(promisedType.id) >= 0) { + // Verify that we don't have a bad actor in the form of a promise whose + // promised type is the same as the promise type, or a mutually recursive + // promise. If so, we return undefined as we cannot guess the shape. If this + // were the actual case in the JavaScript, this Promise would never resolve. + // + // An example of a bad actor with a singly-recursive promise type might + // be: + // + // interface BadPromise { + // then( + // onfulfilled: (value: BadPromise) => any, + // onrejected: (error: any) => any): BadPromise; + // } + // The above interface will pass the PromiseLike check, and return a + // promised type of `BadPromise`. Since this is a self reference, we + // don't want to keep recursing ad infinitum. + // + // An example of a bad actor in the form of a mutually-recursive + // promise type might be: + // + // interface BadPromiseA { + // then( + // onfulfilled: (value: BadPromiseB) => any, + // onrejected: (error: any) => any): BadPromiseB; + // } + // + // interface BadPromiseB { + // then( + // onfulfilled: (value: BadPromiseA) => any, + // onrejected: (error: any) => any): BadPromiseA; + // } + // + if (errorNode) { + error(errorNode, ts.Diagnostics.Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method); + } + return undefined; + } + // Keep track of the type we're about to unwrap to avoid bad recursive promise types. + // See the comments above for more information. + awaitedTypeStack.push(type.id); + var awaitedType = getAwaitedType(promisedType, errorNode, diagnosticMessage); + awaitedTypeStack.pop(); + if (!awaitedType) { + return undefined; + } + return typeAsAwaitable.awaitedTypeOfType = awaitedType; + } + // The type was not a promise, so it could not be unwrapped any further. + // As long as the type does not have a callable "then" property, it is + // safe to return the type; otherwise, an error will be reported in + // the call to getNonThenableType and we will return undefined. + // + // An example of a non-promise "thenable" might be: + // + // await { then(): void {} } + // + // The "thenable" does not match the minimal definition for a promise. When + // a Promise/A+-compatible or ES6 promise tries to adopt this value, the promise + // will never settle. We treat this as an error to help flag an early indicator + // of a runtime problem. If the user wants to return this value from an async + // function, they would need to wrap it in some other value. If they want it to + // be treated as a promise, they can cast to . + var thenFunction = getTypeOfPropertyOfType(type, "then"); + if (thenFunction && getSignaturesOfType(thenFunction, 0 /* Call */).length > 0) { + if (errorNode) { + if (!diagnosticMessage) + return ts.Debug.fail(); + error(errorNode, diagnosticMessage); + } + return undefined; + } + return typeAsAwaitable.awaitedTypeOfType = type; + } + /** + * Checks the return type of an async function to ensure it is a compatible + * Promise implementation. + * + * This checks that an async function has a valid Promise-compatible return type. + * An async function has a valid Promise-compatible return type if the resolved value + * of the return type has a construct signature that takes in an `initializer` function + * that in turn supplies a `resolve` function as one of its arguments and results in an + * object with a callable `then` signature. + * + * @param node The signature to check + */ + function checkAsyncFunctionReturnType(node, returnTypeNode) { + // As part of our emit for an async function, we will need to emit the entity name of + // the return type annotation as an expression. To meet the necessary runtime semantics + // for __awaiter, we must also check that the type of the declaration (e.g. the static + // side or "constructor" of the promise type) is compatible `PromiseConstructorLike`. + // + // An example might be (from lib.es6.d.ts): + // + // interface Promise { ... } + // interface PromiseConstructor { + // new (...): Promise; + // } + // declare var Promise: PromiseConstructor; + // + // When an async function declares a return type annotation of `Promise`, we + // need to get the type of the `Promise` variable declaration above, which would + // be `PromiseConstructor`. + // + // The same case applies to a class: + // + // declare class Promise { + // constructor(...); + // then(...): Promise; + // } + // + var returnType = getTypeFromTypeNode(returnTypeNode); + if (languageVersion >= 2 /* ES2015 */) { + if (returnType === errorType) { + return; + } + var globalPromiseType = getGlobalPromiseType(/*reportErrors*/ true); + if (globalPromiseType !== emptyGenericType && !isReferenceToType(returnType, globalPromiseType)) { + // The promise type was not a valid type reference to the global promise type, so we + // report an error and return the unknown type. + error(returnTypeNode, ts.Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type); + return; + } + } + else { + // Always mark the type node as referenced if it points to a value + markTypeNodeAsReferenced(returnTypeNode); + if (returnType === errorType) { + return; + } + var promiseConstructorName = ts.getEntityNameFromTypeNode(returnTypeNode); + if (promiseConstructorName === undefined) { + error(returnTypeNode, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, typeToString(returnType)); + return; + } + var promiseConstructorSymbol = resolveEntityName(promiseConstructorName, 67220415 /* Value */, /*ignoreErrors*/ true); + var promiseConstructorType = promiseConstructorSymbol ? getTypeOfSymbol(promiseConstructorSymbol) : errorType; + if (promiseConstructorType === errorType) { + if (promiseConstructorName.kind === 72 /* Identifier */ && promiseConstructorName.escapedText === "Promise" && getTargetType(returnType) === getGlobalPromiseType(/*reportErrors*/ false)) { + error(returnTypeNode, ts.Diagnostics.An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option); + } + else { + error(returnTypeNode, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, ts.entityNameToString(promiseConstructorName)); + } + return; + } + var globalPromiseConstructorLikeType = getGlobalPromiseConstructorLikeType(/*reportErrors*/ true); + if (globalPromiseConstructorLikeType === emptyObjectType) { + // If we couldn't resolve the global PromiseConstructorLike type we cannot verify + // compatibility with __awaiter. + error(returnTypeNode, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, ts.entityNameToString(promiseConstructorName)); + return; + } + if (!checkTypeAssignableTo(promiseConstructorType, globalPromiseConstructorLikeType, returnTypeNode, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value)) { + return; + } + // Verify there is no local declaration that could collide with the promise constructor. + var rootName = promiseConstructorName && getFirstIdentifier(promiseConstructorName); + var collidingSymbol = getSymbol(node.locals, rootName.escapedText, 67220415 /* Value */); + if (collidingSymbol) { + error(collidingSymbol.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, ts.idText(rootName), ts.entityNameToString(promiseConstructorName)); + return; + } + } + checkAwaitedType(returnType, node, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); + } + /** Check a decorator */ + function checkDecorator(node) { + var signature = getResolvedSignature(node); + var returnType = getReturnTypeOfSignature(signature); + if (returnType.flags & 1 /* Any */) { + return; + } + var expectedReturnType; + var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); + var errorInfo; + switch (node.parent.kind) { + case 240 /* ClassDeclaration */: + var classSymbol = getSymbolOfNode(node.parent); + var classConstructorType = getTypeOfSymbol(classSymbol); + expectedReturnType = getUnionType([classConstructorType, voidType]); + break; + case 151 /* Parameter */: + expectedReturnType = voidType; + errorInfo = ts.chainDiagnosticMessages( + /*details*/ undefined, ts.Diagnostics.The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any); + break; + case 154 /* PropertyDeclaration */: + expectedReturnType = voidType; + errorInfo = ts.chainDiagnosticMessages( + /*details*/ undefined, ts.Diagnostics.The_return_type_of_a_property_decorator_function_must_be_either_void_or_any); + break; + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + var methodType = getTypeOfNode(node.parent); + var descriptorType = createTypedPropertyDescriptorType(methodType); + expectedReturnType = getUnionType([descriptorType, voidType]); + break; + default: + return ts.Debug.fail(); + } + checkTypeAssignableTo(returnType, expectedReturnType, node, headMessage, function () { return errorInfo; }); + } + /** + * If a TypeNode can be resolved to a value symbol imported from an external module, it is + * marked as referenced to prevent import elision. + */ + function markTypeNodeAsReferenced(node) { + markEntityNameOrEntityExpressionAsReference(node && ts.getEntityNameFromTypeNode(node)); + } + function markEntityNameOrEntityExpressionAsReference(typeName) { + if (!typeName) + return; + var rootName = getFirstIdentifier(typeName); + var meaning = (typeName.kind === 72 /* Identifier */ ? 67897832 /* Type */ : 1920 /* Namespace */) | 2097152 /* Alias */; + var rootSymbol = resolveName(rootName, rootName.escapedText, meaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isRefernce*/ true); + if (rootSymbol + && rootSymbol.flags & 2097152 /* Alias */ + && symbolIsValue(rootSymbol) + && !isConstEnumOrConstEnumOnlyModule(resolveAlias(rootSymbol))) { + markAliasSymbolAsReferenced(rootSymbol); + } + } + /** + * This function marks the type used for metadata decorator as referenced if it is import + * from external module. + * This is different from markTypeNodeAsReferenced because it tries to simplify type nodes in + * union and intersection type + * @param node + */ + function markDecoratorMedataDataTypeNodeAsReferenced(node) { + var entityName = getEntityNameForDecoratorMetadata(node); + if (entityName && ts.isEntityName(entityName)) { + markEntityNameOrEntityExpressionAsReference(entityName); + } + } + function getEntityNameForDecoratorMetadata(node) { + if (node) { + switch (node.kind) { + case 174 /* IntersectionType */: + case 173 /* UnionType */: + return getEntityNameForDecoratorMetadataFromTypeList(node.types); + case 175 /* ConditionalType */: + return getEntityNameForDecoratorMetadataFromTypeList([node.trueType, node.falseType]); + case 177 /* ParenthesizedType */: + return getEntityNameForDecoratorMetadata(node.type); + case 164 /* TypeReference */: + return node.typeName; + } + } + } + function getEntityNameForDecoratorMetadataFromTypeList(types) { + var commonEntityName; + for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { + var typeNode = types_16[_i]; + while (typeNode.kind === 177 /* ParenthesizedType */) { + typeNode = typeNode.type; // Skip parens if need be + } + if (typeNode.kind === 132 /* NeverKeyword */) { + continue; // Always elide `never` from the union/intersection if possible + } + if (!strictNullChecks && (typeNode.kind === 96 /* NullKeyword */ || typeNode.kind === 141 /* UndefinedKeyword */)) { + continue; // Elide null and undefined from unions for metadata, just like what we did prior to the implementation of strict null checks + } + var individualEntityName = getEntityNameForDecoratorMetadata(typeNode); + if (!individualEntityName) { + // Individual is something like string number + // So it would be serialized to either that type or object + // Safe to return here + return undefined; + } + if (commonEntityName) { + // Note this is in sync with the transformation that happens for type node. + // Keep this in sync with serializeUnionOrIntersectionType + // Verify if they refer to same entity and is identifier + // return undefined if they dont match because we would emit object + if (!ts.isIdentifier(commonEntityName) || + !ts.isIdentifier(individualEntityName) || + commonEntityName.escapedText !== individualEntityName.escapedText) { + return undefined; + } + } + else { + commonEntityName = individualEntityName; + } + } + return commonEntityName; + } + function getParameterTypeNodeForDecoratorCheck(node) { + var typeNode = ts.getEffectiveTypeAnnotationNode(node); + return ts.isRestParameter(node) ? ts.getRestParameterElementType(typeNode) : typeNode; + } + /** Check the decorators of a node */ + function checkDecorators(node) { + if (!node.decorators) { + return; + } + // skip this check for nodes that cannot have decorators. These should have already had an error reported by + // checkGrammarDecorators. + if (!ts.nodeCanBeDecorated(node, node.parent, node.parent.parent)) { + return; + } + if (!compilerOptions.experimentalDecorators) { + error(node, ts.Diagnostics.Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_to_remove_this_warning); + } + var firstDecorator = node.decorators[0]; + checkExternalEmitHelpers(firstDecorator, 8 /* Decorate */); + if (node.kind === 151 /* Parameter */) { + checkExternalEmitHelpers(firstDecorator, 32 /* Param */); + } + if (compilerOptions.emitDecoratorMetadata) { + checkExternalEmitHelpers(firstDecorator, 16 /* Metadata */); + // we only need to perform these checks if we are emitting serialized type metadata for the target of a decorator. + switch (node.kind) { + case 240 /* ClassDeclaration */: + var constructor = ts.getFirstConstructorWithBody(node); + if (constructor) { + for (var _i = 0, _a = constructor.parameters; _i < _a.length; _i++) { + var parameter = _a[_i]; + markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); + } + } + break; + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + var otherKind = node.kind === 158 /* GetAccessor */ ? 159 /* SetAccessor */ : 158 /* GetAccessor */; + var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(node), otherKind); + markDecoratorMedataDataTypeNodeAsReferenced(getAnnotatedAccessorTypeNode(node) || otherAccessor && getAnnotatedAccessorTypeNode(otherAccessor)); + break; + case 156 /* MethodDeclaration */: + for (var _b = 0, _c = node.parameters; _b < _c.length; _b++) { + var parameter = _c[_b]; + markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); + } + markDecoratorMedataDataTypeNodeAsReferenced(ts.getEffectiveReturnTypeNode(node)); + break; + case 154 /* PropertyDeclaration */: + markDecoratorMedataDataTypeNodeAsReferenced(ts.getEffectiveTypeAnnotationNode(node)); + break; + case 151 /* Parameter */: + markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(node)); + var containingSignature = node.parent; + for (var _d = 0, _e = containingSignature.parameters; _d < _e.length; _d++) { + var parameter = _e[_d]; + markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); + } + break; + } + } + ts.forEach(node.decorators, checkDecorator); + } + function checkFunctionDeclaration(node) { + if (produceDiagnostics) { + checkFunctionOrMethodDeclaration(node); + checkGrammarForGenerator(node); + checkCollisionWithRequireExportsInGeneratedCode(node, node.name); + checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); + } + } + function checkJSDocTypeAliasTag(node) { + if (!node.typeExpression) { + // If the node had `@property` tags, `typeExpression` would have been set to the first property tag. + error(node.name, ts.Diagnostics.JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags); + } + if (node.name) { + checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_alias_name_cannot_be_0); + } + checkSourceElement(node.typeExpression); + } + function checkJSDocTemplateTag(node) { + checkSourceElement(node.constraint); + for (var _i = 0, _a = node.typeParameters; _i < _a.length; _i++) { + var tp = _a[_i]; + checkSourceElement(tp); + } + } + function checkJSDocTypeTag(node) { + checkSourceElement(node.typeExpression); + } + function checkJSDocParameterTag(node) { + checkSourceElement(node.typeExpression); + if (!ts.getParameterSymbolFromJSDoc(node)) { + var decl = ts.getHostSignatureFromJSDoc(node); + // don't issue an error for invalid hosts -- just functions -- + // and give a better error message when the host function mentions `arguments` + // but the tag doesn't have an array type + if (decl) { + var i = ts.getJSDocTags(decl).filter(ts.isJSDocParameterTag).indexOf(node); + if (i > -1 && i < decl.parameters.length && ts.isBindingPattern(decl.parameters[i].name)) { + return; + } + if (!containsArgumentsReference(decl)) { + error(node.name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name, ts.idText(node.name.kind === 148 /* QualifiedName */ ? node.name.right : node.name)); + } + else if (ts.findLast(ts.getJSDocTags(decl), ts.isJSDocParameterTag) === node && + node.typeExpression && node.typeExpression.type && + !isArrayType(getTypeFromTypeNode(node.typeExpression.type))) { + error(node.name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_had_an_array_type, ts.idText(node.name.kind === 148 /* QualifiedName */ ? node.name.right : node.name)); + } + } + } + } + function checkJSDocFunctionType(node) { + if (produceDiagnostics && !node.type && !ts.isJSDocConstructSignature(node)) { + reportImplicitAny(node, anyType); + } + checkSignatureDeclaration(node); + } + function checkJSDocAugmentsTag(node) { + var classLike = ts.getJSDocHost(node); + if (!ts.isClassDeclaration(classLike) && !ts.isClassExpression(classLike)) { + error(classLike, ts.Diagnostics.JSDoc_0_is_not_attached_to_a_class, ts.idText(node.tagName)); + return; + } + var augmentsTags = ts.getJSDocTags(classLike).filter(ts.isJSDocAugmentsTag); + ts.Debug.assert(augmentsTags.length > 0); + if (augmentsTags.length > 1) { + error(augmentsTags[1], ts.Diagnostics.Class_declarations_cannot_have_more_than_one_augments_or_extends_tag); + } + var name = getIdentifierFromEntityNameExpression(node.class.expression); + var extend = ts.getClassExtendsHeritageElement(classLike); + if (extend) { + var className = getIdentifierFromEntityNameExpression(extend.expression); + if (className && name.escapedText !== className.escapedText) { + error(name, ts.Diagnostics.JSDoc_0_1_does_not_match_the_extends_2_clause, ts.idText(node.tagName), ts.idText(name), ts.idText(className)); + } + } + } + function getIdentifierFromEntityNameExpression(node) { + switch (node.kind) { + case 72 /* Identifier */: + return node; + case 189 /* PropertyAccessExpression */: + return node.name; + default: + return undefined; + } + } + function checkFunctionOrMethodDeclaration(node) { + checkDecorators(node); + checkSignatureDeclaration(node); + var functionFlags = ts.getFunctionFlags(node); + // Do not use hasDynamicName here, because that returns false for well known symbols. + // We want to perform checkComputedPropertyName for all computed properties, including + // well known symbols. + if (node.name && node.name.kind === 149 /* ComputedPropertyName */) { + // This check will account for methods in class/interface declarations, + // as well as accessors in classes/object literals + checkComputedPropertyName(node.name); + } + if (!hasNonBindableDynamicName(node)) { + // first we want to check the local symbol that contain this declaration + // - if node.localSymbol !== undefined - this is current declaration is exported and localSymbol points to the local symbol + // - if node.localSymbol === undefined - this node is non-exported so we can just pick the result of getSymbolOfNode + var symbol = getSymbolOfNode(node); + var localSymbol = node.localSymbol || symbol; + // Since the javascript won't do semantic analysis like typescript, + // if the javascript file comes before the typescript file and both contain same name functions, + // checkFunctionOrConstructorSymbol wouldn't be called if we didnt ignore javascript function. + var firstDeclaration = ts.find(localSymbol.declarations, + // Get first non javascript function declaration + function (declaration) { return declaration.kind === node.kind && !(declaration.flags & 65536 /* JavaScriptFile */); }); + // Only type check the symbol once + if (node === firstDeclaration) { + checkFunctionOrConstructorSymbol(localSymbol); + } + if (symbol.parent) { + // run check once for the first declaration + if (ts.getDeclarationOfKind(symbol, node.kind) === node) { + // run check on export symbol to check that modifiers agree across all exported declarations + checkFunctionOrConstructorSymbol(symbol); + } + } + } + var body = node.kind === 155 /* MethodSignature */ ? undefined : node.body; + checkSourceElement(body); + if ((functionFlags & 1 /* Generator */) === 0) { // Async function or normal function + var returnOrPromisedType = getReturnOrPromisedType(node, functionFlags); + checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnOrPromisedType); + } + if (produceDiagnostics && !ts.getEffectiveReturnTypeNode(node)) { + // Report an implicit any error if there is no body, no explicit return type, and node is not a private method + // in an ambient context + if (ts.nodeIsMissing(body) && !isPrivateWithinAmbient(node)) { + reportImplicitAny(node, anyType); + } + if (functionFlags & 1 /* Generator */ && ts.nodeIsPresent(body)) { + // A generator with a body and no type annotation can still cause errors. It can error if the + // yielded values have no common supertype, or it can give an implicit any error if it has no + // yielded values. The only way to trigger these errors is to try checking its return type. + getReturnTypeOfSignature(getSignatureFromDeclaration(node)); + } + } + // A js function declaration can have a @type tag instead of a return type node, but that type must have a call signature + if (ts.isInJSFile(node)) { + var typeTag = ts.getJSDocTypeTag(node); + if (typeTag && typeTag.typeExpression && !getContextualCallSignature(getTypeFromTypeNode(typeTag.typeExpression), node)) { + error(typeTag, ts.Diagnostics.The_type_of_a_function_declaration_must_match_the_function_s_signature); + } + } + } + function registerForUnusedIdentifiersCheck(node) { + // May be in a call such as getTypeOfNode that happened to call this. But potentiallyUnusedIdentifiers is only defined in the scope of `checkSourceFile`. + if (produceDiagnostics && !(node.flags & 4194304 /* Ambient */)) { + var sourceFile = ts.getSourceFileOfNode(node); + var potentiallyUnusedIdentifiers = allPotentiallyUnusedIdentifiers.get(sourceFile.path); + if (!potentiallyUnusedIdentifiers) { + potentiallyUnusedIdentifiers = []; + allPotentiallyUnusedIdentifiers.set(sourceFile.path, potentiallyUnusedIdentifiers); + } + // TODO: GH#22580 + // Debug.assert(addToSeen(seenPotentiallyUnusedIdentifiers, getNodeId(node)), "Adding potentially-unused identifier twice"); + potentiallyUnusedIdentifiers.push(node); + } + } + function checkUnusedIdentifiers(potentiallyUnusedIdentifiers, addDiagnostic) { + for (var _i = 0, potentiallyUnusedIdentifiers_1 = potentiallyUnusedIdentifiers; _i < potentiallyUnusedIdentifiers_1.length; _i++) { + var node = potentiallyUnusedIdentifiers_1[_i]; + switch (node.kind) { + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + checkUnusedClassMembers(node, addDiagnostic); + checkUnusedTypeParameters(node, addDiagnostic); + break; + case 279 /* SourceFile */: + case 244 /* ModuleDeclaration */: + case 218 /* Block */: + case 246 /* CaseBlock */: + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + checkUnusedLocalsAndParameters(node, addDiagnostic); + break; + case 157 /* Constructor */: + case 196 /* FunctionExpression */: + case 239 /* FunctionDeclaration */: + case 197 /* ArrowFunction */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + if (node.body) { // Don't report unused parameters in overloads + checkUnusedLocalsAndParameters(node, addDiagnostic); + } + checkUnusedTypeParameters(node, addDiagnostic); + break; + case 155 /* MethodSignature */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + case 242 /* TypeAliasDeclaration */: + case 241 /* InterfaceDeclaration */: + checkUnusedTypeParameters(node, addDiagnostic); + break; + case 176 /* InferType */: + checkUnusedInferTypeParameter(node, addDiagnostic); + break; + default: + ts.Debug.assertNever(node, "Node should not have been registered for unused identifiers check"); + } + } + } + function errorUnusedLocal(declaration, name, addDiagnostic) { + var node = ts.getNameOfDeclaration(declaration) || declaration; + var message = isTypeDeclaration(declaration) ? ts.Diagnostics._0_is_declared_but_never_used : ts.Diagnostics._0_is_declared_but_its_value_is_never_read; + addDiagnostic(declaration, 0 /* Local */, ts.createDiagnosticForNode(node, message, name)); + } + function isIdentifierThatStartsWithUnderscore(node) { + return ts.isIdentifier(node) && ts.idText(node).charCodeAt(0) === 95 /* _ */; + } + function checkUnusedClassMembers(node, addDiagnostic) { + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + switch (member.kind) { + case 156 /* MethodDeclaration */: + case 154 /* PropertyDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + if (member.kind === 159 /* SetAccessor */ && member.symbol.flags & 32768 /* GetAccessor */) { + // Already would have reported an error on the getter. + break; + } + var symbol = getSymbolOfNode(member); + if (!symbol.isReferenced && ts.hasModifier(member, 8 /* Private */)) { + addDiagnostic(member, 0 /* Local */, ts.createDiagnosticForNode(member.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, symbolToString(symbol))); + } + break; + case 157 /* Constructor */: + for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { + var parameter = _c[_b]; + if (!parameter.symbol.isReferenced && ts.hasModifier(parameter, 8 /* Private */)) { + addDiagnostic(parameter, 0 /* Local */, ts.createDiagnosticForNode(parameter.name, ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read, ts.symbolName(parameter.symbol))); + } + } + break; + case 162 /* IndexSignature */: + case 217 /* SemicolonClassElement */: + // Can't be private + break; + default: + ts.Debug.fail(); + } + } + } + function checkUnusedInferTypeParameter(node, addDiagnostic) { + var typeParameter = node.typeParameter; + if (isTypeParameterUnused(typeParameter)) { + addDiagnostic(node, 1 /* Parameter */, ts.createDiagnosticForNode(node, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(typeParameter.name))); + } + } + function checkUnusedTypeParameters(node, addDiagnostic) { + // Only report errors on the last declaration for the type parameter container; + // this ensures that all uses have been accounted for. + if (ts.last(getSymbolOfNode(node).declarations) !== node) + return; + var typeParameters = ts.getEffectiveTypeParameterDeclarations(node); + var seenParentsWithEveryUnused = new ts.NodeSet(); + for (var _i = 0, typeParameters_2 = typeParameters; _i < typeParameters_2.length; _i++) { + var typeParameter = typeParameters_2[_i]; + if (!isTypeParameterUnused(typeParameter)) + continue; + var name = ts.idText(typeParameter.name); + var parent = typeParameter.parent; + if (parent.kind !== 176 /* InferType */ && parent.typeParameters.every(isTypeParameterUnused)) { + if (seenParentsWithEveryUnused.tryAdd(parent)) { + var range = ts.isJSDocTemplateTag(parent) + // Whole @template tag + ? ts.rangeOfNode(parent) + // Include the `<>` in the error message + : ts.rangeOfTypeParameters(parent.typeParameters); + var only = typeParameters.length === 1; + var message = only ? ts.Diagnostics._0_is_declared_but_its_value_is_never_read : ts.Diagnostics.All_type_parameters_are_unused; + var arg0 = only ? name : undefined; + addDiagnostic(typeParameter, 1 /* Parameter */, ts.createFileDiagnostic(ts.getSourceFileOfNode(parent), range.pos, range.end - range.pos, message, arg0)); + } + } + else { + addDiagnostic(typeParameter, 1 /* Parameter */, ts.createDiagnosticForNode(typeParameter, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, name)); + } + } + } + function isTypeParameterUnused(typeParameter) { + return !(getMergedSymbol(typeParameter.symbol).isReferenced & 262144 /* TypeParameter */) && !isIdentifierThatStartsWithUnderscore(typeParameter.name); + } + function addToGroup(map, key, value, getKey) { + var keyString = String(getKey(key)); + var group = map.get(keyString); + if (group) { + group[1].push(value); + } + else { + map.set(keyString, [key, [value]]); + } + } + function tryGetRootParameterDeclaration(node) { + return ts.tryCast(ts.getRootDeclaration(node), ts.isParameter); + } + function checkUnusedLocalsAndParameters(nodeWithLocals, addDiagnostic) { + if (nodeWithLocals.flags & 4194304 /* Ambient */) + return; + // Ideally we could use the ImportClause directly as a key, but must wait until we have full ES6 maps. So must store key along with value. + var unusedImports = ts.createMap(); + var unusedDestructures = ts.createMap(); + var unusedVariables = ts.createMap(); + nodeWithLocals.locals.forEach(function (local) { + // If it's purely a type parameter, ignore, will be checked in `checkUnusedTypeParameters`. + // If it's a type parameter merged with a parameter, check if the parameter-side is used. + if (local.flags & 262144 /* TypeParameter */ ? !(local.flags & 3 /* Variable */ && !(local.isReferenced & 3 /* Variable */)) : local.isReferenced || local.exportSymbol) { + return; + } + for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (ts.isAmbientModule(declaration) || + (ts.isVariableDeclaration(declaration) && ts.isForInOrOfStatement(declaration.parent.parent) || isImportedDeclaration(declaration)) && isIdentifierThatStartsWithUnderscore(declaration.name)) { + continue; + } + if (isImportedDeclaration(declaration)) { + addToGroup(unusedImports, importClauseFromImported(declaration), declaration, getNodeId); + } + else if (ts.isBindingElement(declaration) && ts.isObjectBindingPattern(declaration.parent)) { + // In `{ a, ...b }, `a` is considered used since it removes a property from `b`. `b` may still be unused though. + var lastElement = ts.last(declaration.parent.elements); + if (declaration === lastElement || !ts.last(declaration.parent.elements).dotDotDotToken) { + addToGroup(unusedDestructures, declaration.parent, declaration, getNodeId); + } + } + else if (ts.isVariableDeclaration(declaration)) { + addToGroup(unusedVariables, declaration.parent, declaration, getNodeId); + } + else { + var parameter = local.valueDeclaration && tryGetRootParameterDeclaration(local.valueDeclaration); + var name = local.valueDeclaration && ts.getNameOfDeclaration(local.valueDeclaration); + if (parameter && name) { + if (!ts.isParameterPropertyDeclaration(parameter) && !ts.parameterIsThisKeyword(parameter) && !isIdentifierThatStartsWithUnderscore(name)) { + addDiagnostic(parameter, 1 /* Parameter */, ts.createDiagnosticForNode(name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.symbolName(local))); + } + } + else { + errorUnusedLocal(declaration, ts.symbolName(local), addDiagnostic); + } + } + } + }); + unusedImports.forEach(function (_a) { + var importClause = _a[0], unuseds = _a[1]; + var importDecl = importClause.parent; + var nDeclarations = (importClause.name ? 1 : 0) + + (importClause.namedBindings ? + (importClause.namedBindings.kind === 251 /* NamespaceImport */ ? 1 : importClause.namedBindings.elements.length) + : 0); + if (nDeclarations === unuseds.length) { + addDiagnostic(importDecl, 0 /* Local */, unuseds.length === 1 + ? ts.createDiagnosticForNode(importDecl, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(ts.first(unuseds).name)) + : ts.createDiagnosticForNode(importDecl, ts.Diagnostics.All_imports_in_import_declaration_are_unused)); + } + else { + for (var _i = 0, unuseds_1 = unuseds; _i < unuseds_1.length; _i++) { + var unused = unuseds_1[_i]; + errorUnusedLocal(unused, ts.idText(unused.name), addDiagnostic); + } + } + }); + unusedDestructures.forEach(function (_a) { + var bindingPattern = _a[0], bindingElements = _a[1]; + var kind = tryGetRootParameterDeclaration(bindingPattern.parent) ? 1 /* Parameter */ : 0 /* Local */; + if (bindingPattern.elements.length === bindingElements.length) { + if (bindingElements.length === 1 && bindingPattern.parent.kind === 237 /* VariableDeclaration */ && bindingPattern.parent.parent.kind === 238 /* VariableDeclarationList */) { + addToGroup(unusedVariables, bindingPattern.parent.parent, bindingPattern.parent, getNodeId); + } + else { + addDiagnostic(bindingPattern, kind, bindingElements.length === 1 + ? ts.createDiagnosticForNode(bindingPattern, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(ts.first(bindingElements).name)) + : ts.createDiagnosticForNode(bindingPattern, ts.Diagnostics.All_destructured_elements_are_unused)); + } + } + else { + for (var _i = 0, bindingElements_1 = bindingElements; _i < bindingElements_1.length; _i++) { + var e = bindingElements_1[_i]; + addDiagnostic(e, kind, ts.createDiagnosticForNode(e, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(e.name))); + } + } + }); + unusedVariables.forEach(function (_a) { + var declarationList = _a[0], declarations = _a[1]; + if (declarationList.declarations.length === declarations.length) { + addDiagnostic(declarationList, 0 /* Local */, declarations.length === 1 + ? ts.createDiagnosticForNode(ts.first(declarations).name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(ts.first(declarations).name)) + : ts.createDiagnosticForNode(declarationList.parent.kind === 219 /* VariableStatement */ ? declarationList.parent : declarationList, ts.Diagnostics.All_variables_are_unused)); + } + else { + for (var _i = 0, declarations_5 = declarations; _i < declarations_5.length; _i++) { + var decl = declarations_5[_i]; + addDiagnostic(decl, 0 /* Local */, ts.createDiagnosticForNode(decl, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(decl.name))); + } + } + }); + } + function bindingNameText(name) { + switch (name.kind) { + case 72 /* Identifier */: + return ts.idText(name); + case 185 /* ArrayBindingPattern */: + case 184 /* ObjectBindingPattern */: + return bindingNameText(ts.cast(ts.first(name.elements), ts.isBindingElement).name); + default: + return ts.Debug.assertNever(name); + } + } + function isImportedDeclaration(node) { + return node.kind === 250 /* ImportClause */ || node.kind === 253 /* ImportSpecifier */ || node.kind === 251 /* NamespaceImport */; + } + function importClauseFromImported(decl) { + return decl.kind === 250 /* ImportClause */ ? decl : decl.kind === 251 /* NamespaceImport */ ? decl.parent : decl.parent.parent; + } + function checkBlock(node) { + // Grammar checking for SyntaxKind.Block + if (node.kind === 218 /* Block */) { + checkGrammarStatementInAmbientContext(node); + } + if (ts.isFunctionOrModuleBlock(node)) { + var saveFlowAnalysisDisabled = flowAnalysisDisabled; + ts.forEach(node.statements, checkSourceElement); + flowAnalysisDisabled = saveFlowAnalysisDisabled; + } + else { + ts.forEach(node.statements, checkSourceElement); + } + if (node.locals) { + registerForUnusedIdentifiersCheck(node); + } + } + function checkCollisionWithArgumentsInGeneratedCode(node) { + // no rest parameters \ declaration context \ overload - no codegen impact + if (languageVersion >= 2 /* ES2015 */ || compilerOptions.noEmit || !ts.hasRestParameter(node) || node.flags & 4194304 /* Ambient */ || ts.nodeIsMissing(node.body)) { + return; + } + ts.forEach(node.parameters, function (p) { + if (p.name && !ts.isBindingPattern(p.name) && p.name.escapedText === argumentsSymbol.escapedName) { + error(p, ts.Diagnostics.Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters); + } + }); + } + function needCollisionCheckForIdentifier(node, identifier, name) { + if (!(identifier && identifier.escapedText === name)) { + return false; + } + if (node.kind === 154 /* PropertyDeclaration */ || + node.kind === 153 /* PropertySignature */ || + node.kind === 156 /* MethodDeclaration */ || + node.kind === 155 /* MethodSignature */ || + node.kind === 158 /* GetAccessor */ || + node.kind === 159 /* SetAccessor */) { + // it is ok to have member named '_super' or '_this' - member access is always qualified + return false; + } + if (node.flags & 4194304 /* Ambient */) { + // ambient context - no codegen impact + return false; + } + var root = ts.getRootDeclaration(node); + if (root.kind === 151 /* Parameter */ && ts.nodeIsMissing(root.parent.body)) { + // just an overload - no codegen impact + return false; + } + return true; + } + // this function will run after checking the source file so 'CaptureThis' is correct for all nodes + function checkIfThisIsCapturedInEnclosingScope(node) { + ts.findAncestor(node, function (current) { + if (getNodeCheckFlags(current) & 4 /* CaptureThis */) { + var isDeclaration_1 = node.kind !== 72 /* Identifier */; + if (isDeclaration_1) { + error(ts.getNameOfDeclaration(node), ts.Diagnostics.Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference); + } + else { + error(node, ts.Diagnostics.Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference); + } + return true; + } + return false; + }); + } + function checkIfNewTargetIsCapturedInEnclosingScope(node) { + ts.findAncestor(node, function (current) { + if (getNodeCheckFlags(current) & 8 /* CaptureNewTarget */) { + var isDeclaration_2 = node.kind !== 72 /* Identifier */; + if (isDeclaration_2) { + error(ts.getNameOfDeclaration(node), ts.Diagnostics.Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference); + } + else { + error(node, ts.Diagnostics.Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta_property_reference); + } + return true; + } + return false; + }); + } + function checkCollisionWithRequireExportsInGeneratedCode(node, name) { + // No need to check for require or exports for ES6 modules and later + if (moduleKind >= ts.ModuleKind.ES2015 || compilerOptions.noEmit) { + return; + } + if (!needCollisionCheckForIdentifier(node, name, "require") && !needCollisionCheckForIdentifier(node, name, "exports")) { + return; + } + // Uninstantiated modules shouldnt do this check + if (ts.isModuleDeclaration(node) && ts.getModuleInstanceState(node) !== 1 /* Instantiated */) { + return; + } + // In case of variable declaration, node.parent is variable statement so look at the variable statement's parent + var parent = getDeclarationContainer(node); + if (parent.kind === 279 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent)) { + // If the declaration happens to be in external module, report error that require and exports are reserved keywords + error(name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module, ts.declarationNameToString(name), ts.declarationNameToString(name)); + } + } + function checkCollisionWithGlobalPromiseInGeneratedCode(node, name) { + if (languageVersion >= 4 /* ES2017 */ || compilerOptions.noEmit || !needCollisionCheckForIdentifier(node, name, "Promise")) { + return; + } + // Uninstantiated modules shouldnt do this check + if (ts.isModuleDeclaration(node) && ts.getModuleInstanceState(node) !== 1 /* Instantiated */) { + return; + } + // In case of variable declaration, node.parent is variable statement so look at the variable statement's parent + var parent = getDeclarationContainer(node); + if (parent.kind === 279 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent) && parent.flags & 1024 /* HasAsyncFunctions */) { + // If the declaration happens to be in external module, report error that Promise is a reserved identifier. + error(name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_functions, ts.declarationNameToString(name), ts.declarationNameToString(name)); + } + } + function checkVarDeclaredNamesNotShadowed(node) { + // - ScriptBody : StatementList + // It is a Syntax Error if any element of the LexicallyDeclaredNames of StatementList + // also occurs in the VarDeclaredNames of StatementList. + // - Block : { StatementList } + // It is a Syntax Error if any element of the LexicallyDeclaredNames of StatementList + // also occurs in the VarDeclaredNames of StatementList. + // Variable declarations are hoisted to the top of their function scope. They can shadow + // block scoped declarations, which bind tighter. this will not be flagged as duplicate definition + // by the binder as the declaration scope is different. + // A non-initialized declaration is a no-op as the block declaration will resolve before the var + // declaration. the problem is if the declaration has an initializer. this will act as a write to the + // block declared value. this is fine for let, but not const. + // Only consider declarations with initializers, uninitialized const declarations will not + // step on a let/const variable. + // Do not consider const and const declarations, as duplicate block-scoped declarations + // are handled by the binder. + // We are only looking for const declarations that step on let\const declarations from a + // different scope. e.g.: + // { + // const x = 0; // localDeclarationSymbol obtained after name resolution will correspond to this declaration + // const x = 0; // symbol for this declaration will be 'symbol' + // } + // skip block-scoped variables and parameters + if ((ts.getCombinedNodeFlags(node) & 3 /* BlockScoped */) !== 0 || ts.isParameterDeclaration(node)) { + return; + } + // skip variable declarations that don't have initializers + // NOTE: in ES6 spec initializer is required in variable declarations where name is binding pattern + // so we'll always treat binding elements as initialized + if (node.kind === 237 /* VariableDeclaration */ && !node.initializer) { + return; + } + var symbol = getSymbolOfNode(node); + if (symbol.flags & 1 /* FunctionScopedVariable */) { + if (!ts.isIdentifier(node.name)) + return ts.Debug.fail(); + var localDeclarationSymbol = resolveName(node, node.name.escapedText, 3 /* Variable */, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); + if (localDeclarationSymbol && + localDeclarationSymbol !== symbol && + localDeclarationSymbol.flags & 2 /* BlockScopedVariable */) { + if (getDeclarationNodeFlagsFromSymbol(localDeclarationSymbol) & 3 /* BlockScoped */) { + var varDeclList = ts.getAncestor(localDeclarationSymbol.valueDeclaration, 238 /* VariableDeclarationList */); + var container = varDeclList.parent.kind === 219 /* VariableStatement */ && varDeclList.parent.parent + ? varDeclList.parent.parent + : undefined; + // names of block-scoped and function scoped variables can collide only + // if block scoped variable is defined in the function\module\source file scope (because of variable hoisting) + var namesShareScope = container && + (container.kind === 218 /* Block */ && ts.isFunctionLike(container.parent) || + container.kind === 245 /* ModuleBlock */ || + container.kind === 244 /* ModuleDeclaration */ || + container.kind === 279 /* SourceFile */); + // here we know that function scoped variable is shadowed by block scoped one + // if they are defined in the same scope - binder has already reported redeclaration error + // otherwise if variable has an initializer - show error that initialization will fail + // since LHS will be block scoped name instead of function scoped + if (!namesShareScope) { + var name = symbolToString(localDeclarationSymbol); + error(node, ts.Diagnostics.Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1, name, name); + } + } + } + } + } + // Check that a parameter initializer contains no references to parameters declared to the right of itself + function checkParameterInitializer(node) { + if (ts.getRootDeclaration(node).kind !== 151 /* Parameter */) { + return; + } + var func = ts.getContainingFunction(node); + visit(node.initializer); + function visit(n) { + if (ts.isTypeNode(n) || ts.isDeclarationName(n)) { + // do not dive in types + // skip declaration names (i.e. in object literal expressions) + return; + } + if (n.kind === 189 /* PropertyAccessExpression */) { + // skip property names in property access expression + return visit(n.expression); + } + else if (n.kind === 72 /* Identifier */) { + // check FunctionLikeDeclaration.locals (stores parameters\function local variable) + // if it contains entry with a specified name + var symbol = resolveName(n, n.escapedText, 67220415 /* Value */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); + if (!symbol || symbol === unknownSymbol || !symbol.valueDeclaration) { + return; + } + if (symbol.valueDeclaration === node) { + error(n, ts.Diagnostics.Parameter_0_cannot_be_referenced_in_its_initializer, ts.declarationNameToString(node.name)); + return; + } + // locals map for function contain both parameters and function locals + // so we need to do a bit of extra work to check if reference is legal + var enclosingContainer = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); + if (enclosingContainer === func) { + if (symbol.valueDeclaration.kind === 151 /* Parameter */ || + symbol.valueDeclaration.kind === 186 /* BindingElement */) { + // it is ok to reference parameter in initializer if either + // - parameter is located strictly on the left of current parameter declaration + if (symbol.valueDeclaration.pos < node.pos) { + return; + } + // - parameter is wrapped in function-like entity + if (ts.findAncestor(n, function (current) { + if (current === node.initializer) { + return "quit"; + } + return ts.isFunctionLike(current.parent) || + // computed property names/initializers in instance property declaration of class like entities + // are executed in constructor and thus deferred + (current.parent.kind === 154 /* PropertyDeclaration */ && + !(ts.hasModifier(current.parent, 32 /* Static */)) && + ts.isClassLike(current.parent.parent)); + })) { + return; + } + // fall through to report error + } + error(n, ts.Diagnostics.Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it, ts.declarationNameToString(node.name), ts.declarationNameToString(n)); + } + } + else { + return ts.forEachChild(n, visit); + } + } + } + function convertAutoToAny(type) { + return type === autoType ? anyType : type === autoArrayType ? anyArrayType : type; + } + // Check variable, parameter, or property declaration + function checkVariableLikeDeclaration(node) { + checkDecorators(node); + if (!ts.isBindingElement(node)) { + checkSourceElement(node.type); + } + // JSDoc `function(string, string): string` syntax results in parameters with no name + if (!node.name) { + return; + } + // For a computed property, just check the initializer and exit + // Do not use hasDynamicName here, because that returns false for well known symbols. + // We want to perform checkComputedPropertyName for all computed properties, including + // well known symbols. + if (node.name.kind === 149 /* ComputedPropertyName */) { + checkComputedPropertyName(node.name); + if (node.initializer) { + checkExpressionCached(node.initializer); + } + } + if (node.kind === 186 /* BindingElement */) { + if (node.parent.kind === 184 /* ObjectBindingPattern */ && languageVersion < 6 /* ESNext */) { + checkExternalEmitHelpers(node, 4 /* Rest */); + } + // check computed properties inside property names of binding elements + if (node.propertyName && node.propertyName.kind === 149 /* ComputedPropertyName */) { + checkComputedPropertyName(node.propertyName); + } + // check private/protected variable access + var parent = node.parent.parent; + var parentType = getTypeForBindingElementParent(parent); + var name = node.propertyName || node.name; + if (!ts.isBindingPattern(name)) { + var nameText = ts.getTextOfPropertyName(name); + if (nameText) { + var property = getPropertyOfType(parentType, nameText); // TODO: GH#18217 + if (property) { + markPropertyAsReferenced(property, /*nodeForCheckWriteOnly*/ undefined, /*isThisAccess*/ false); // A destructuring is never a write-only reference. + checkPropertyAccessibility(parent, !!parent.initializer && parent.initializer.kind === 98 /* SuperKeyword */, parentType, property); + } + } + } + } + // For a binding pattern, check contained binding elements + if (ts.isBindingPattern(node.name)) { + if (node.name.kind === 185 /* ArrayBindingPattern */ && languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) { + checkExternalEmitHelpers(node, 512 /* Read */); + } + ts.forEach(node.name.elements, checkSourceElement); + } + // For a parameter declaration with an initializer, error and exit if the containing function doesn't have a body + if (node.initializer && ts.getRootDeclaration(node).kind === 151 /* Parameter */ && ts.nodeIsMissing(ts.getContainingFunction(node).body)) { + error(node, ts.Diagnostics.A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation); + return; + } + // For a binding pattern, validate the initializer and exit + if (ts.isBindingPattern(node.name)) { + // Don't validate for-in initializer as it is already an error + if (node.initializer && node.parent.parent.kind !== 226 /* ForInStatement */) { + var initializerType = checkExpressionCached(node.initializer); + if (strictNullChecks && node.name.elements.length === 0) { + checkNonNullType(initializerType, node); + } + else { + checkTypeAssignableToAndOptionallyElaborate(initializerType, getWidenedTypeForVariableLikeDeclaration(node), node, node.initializer); + } + checkParameterInitializer(node); + } + return; + } + var symbol = getSymbolOfNode(node); + var type = convertAutoToAny(getTypeOfSymbol(symbol)); + if (node === symbol.valueDeclaration) { + // Node is the primary declaration of the symbol, just validate the initializer + // Don't validate for-in initializer as it is already an error + var initializer = ts.getEffectiveInitializer(node); + if (initializer) { + var isJSObjectLiteralInitializer = ts.isInJSFile(node) && + ts.isObjectLiteralExpression(initializer) && + (initializer.properties.length === 0 || ts.isPrototypeAccess(node.name)) && + ts.hasEntries(symbol.exports); + if (!isJSObjectLiteralInitializer && node.parent.parent.kind !== 226 /* ForInStatement */) { + checkTypeAssignableToAndOptionallyElaborate(checkExpressionCached(initializer), type, node, initializer, /*headMessage*/ undefined); + checkParameterInitializer(node); + } + } + if (symbol.declarations.length > 1) { + if (ts.some(symbol.declarations, function (d) { return d !== node && ts.isVariableLike(d) && !areDeclarationFlagsIdentical(d, node); })) { + error(node.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); + } + } + } + else { + // Node is a secondary declaration, check that type is identical to primary declaration and check that + // initializer is consistent with type associated with the node + var declarationType = convertAutoToAny(getWidenedTypeForVariableLikeDeclaration(node)); + if (type !== errorType && declarationType !== errorType && + !isTypeIdenticalTo(type, declarationType) && + !(symbol.flags & 67108864 /* Assignment */)) { + errorNextVariableOrPropertyDeclarationMustHaveSameType(type, node, declarationType); + } + if (node.initializer) { + checkTypeAssignableToAndOptionallyElaborate(checkExpressionCached(node.initializer), declarationType, node, node.initializer, /*headMessage*/ undefined); + } + if (!areDeclarationFlagsIdentical(node, symbol.valueDeclaration)) { + error(node.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); + } + } + if (node.kind !== 154 /* PropertyDeclaration */ && node.kind !== 153 /* PropertySignature */) { + // We know we don't have a binding pattern or computed name here + checkExportsOnMergedDeclarations(node); + if (node.kind === 237 /* VariableDeclaration */ || node.kind === 186 /* BindingElement */) { + checkVarDeclaredNamesNotShadowed(node); + } + checkCollisionWithRequireExportsInGeneratedCode(node, node.name); + checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); + } + } + function errorNextVariableOrPropertyDeclarationMustHaveSameType(firstType, nextDeclaration, nextType) { + var nextDeclarationName = ts.getNameOfDeclaration(nextDeclaration); + var message = nextDeclaration.kind === 154 /* PropertyDeclaration */ || nextDeclaration.kind === 153 /* PropertySignature */ + ? ts.Diagnostics.Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_type_2 + : ts.Diagnostics.Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2; + error(nextDeclarationName, message, ts.declarationNameToString(nextDeclarationName), typeToString(firstType), typeToString(nextType)); + } + function areDeclarationFlagsIdentical(left, right) { + if ((left.kind === 151 /* Parameter */ && right.kind === 237 /* VariableDeclaration */) || + (left.kind === 237 /* VariableDeclaration */ && right.kind === 151 /* Parameter */)) { + // Differences in optionality between parameters and variables are allowed. + return true; + } + if (ts.hasQuestionToken(left) !== ts.hasQuestionToken(right)) { + return false; + } + var interestingFlags = 8 /* Private */ | + 16 /* Protected */ | + 256 /* Async */ | + 128 /* Abstract */ | + 64 /* Readonly */ | + 32 /* Static */; + return ts.getSelectedModifierFlags(left, interestingFlags) === ts.getSelectedModifierFlags(right, interestingFlags); + } + function checkVariableDeclaration(node) { + checkGrammarVariableDeclaration(node); + return checkVariableLikeDeclaration(node); + } + function checkBindingElement(node) { + checkGrammarBindingElement(node); + return checkVariableLikeDeclaration(node); + } + function checkVariableStatement(node) { + // Grammar checking + if (!checkGrammarDecoratorsAndModifiers(node) && !checkGrammarVariableDeclarationList(node.declarationList)) + checkGrammarForDisallowedLetOrConstStatement(node); + ts.forEach(node.declarationList.declarations, checkSourceElement); + } + function checkExpressionStatement(node) { + // Grammar checking + checkGrammarStatementInAmbientContext(node); + checkExpression(node.expression); + } + function checkIfStatement(node) { + // Grammar checking + checkGrammarStatementInAmbientContext(node); + checkTruthinessExpression(node.expression); + checkSourceElement(node.thenStatement); + if (node.thenStatement.kind === 220 /* EmptyStatement */) { + error(node.thenStatement, ts.Diagnostics.The_body_of_an_if_statement_cannot_be_the_empty_statement); + } + checkSourceElement(node.elseStatement); + } + function checkDoStatement(node) { + // Grammar checking + checkGrammarStatementInAmbientContext(node); + checkSourceElement(node.statement); + checkTruthinessExpression(node.expression); + } + function checkWhileStatement(node) { + // Grammar checking + checkGrammarStatementInAmbientContext(node); + checkTruthinessExpression(node.expression); + checkSourceElement(node.statement); + } + function checkTruthinessExpression(node, checkMode) { + var type = checkExpression(node, checkMode); + if (type.flags & 16384 /* Void */) { + error(node, ts.Diagnostics.An_expression_of_type_void_cannot_be_tested_for_truthiness); + } + return type; + } + function checkForStatement(node) { + // Grammar checking + if (!checkGrammarStatementInAmbientContext(node)) { + if (node.initializer && node.initializer.kind === 238 /* VariableDeclarationList */) { + checkGrammarVariableDeclarationList(node.initializer); + } + } + if (node.initializer) { + if (node.initializer.kind === 238 /* VariableDeclarationList */) { + ts.forEach(node.initializer.declarations, checkVariableDeclaration); + } + else { + checkExpression(node.initializer); + } + } + if (node.condition) + checkTruthinessExpression(node.condition); + if (node.incrementor) + checkExpression(node.incrementor); + checkSourceElement(node.statement); + if (node.locals) { + registerForUnusedIdentifiersCheck(node); + } + } + function checkForOfStatement(node) { + checkGrammarForInOrForOfStatement(node); + if (node.awaitModifier) { + var functionFlags = ts.getFunctionFlags(ts.getContainingFunction(node)); + if ((functionFlags & (4 /* Invalid */ | 2 /* Async */)) === 2 /* Async */ && languageVersion < 6 /* ESNext */) { + // for..await..of in an async function or async generator function prior to ESNext requires the __asyncValues helper + checkExternalEmitHelpers(node, 16384 /* ForAwaitOfIncludes */); + } + } + else if (compilerOptions.downlevelIteration && languageVersion < 2 /* ES2015 */) { + // for..of prior to ES2015 requires the __values helper when downlevelIteration is enabled + checkExternalEmitHelpers(node, 256 /* ForOfIncludes */); + } + // Check the LHS and RHS + // If the LHS is a declaration, just check it as a variable declaration, which will in turn check the RHS + // via checkRightHandSideOfForOf. + // If the LHS is an expression, check the LHS, as a destructuring assignment or as a reference. + // Then check that the RHS is assignable to it. + if (node.initializer.kind === 238 /* VariableDeclarationList */) { + checkForInOrForOfVariableDeclaration(node); + } + else { + var varExpr = node.initializer; + var iteratedType = checkRightHandSideOfForOf(node.expression, node.awaitModifier); + // There may be a destructuring assignment on the left side + if (varExpr.kind === 187 /* ArrayLiteralExpression */ || varExpr.kind === 188 /* ObjectLiteralExpression */) { + // iteratedType may be undefined. In this case, we still want to check the structure of + // varExpr, in particular making sure it's a valid LeftHandSideExpression. But we'd like + // to short circuit the type relation checking as much as possible, so we pass the unknownType. + checkDestructuringAssignment(varExpr, iteratedType || errorType); + } + else { + var leftType = checkExpression(varExpr); + checkReferenceExpression(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access); + // iteratedType will be undefined if the rightType was missing properties/signatures + // required to get its iteratedType (like [Symbol.iterator] or next). This may be + // because we accessed properties from anyType, or it may have led to an error inside + // getElementTypeOfIterable. + if (iteratedType) { + checkTypeAssignableToAndOptionallyElaborate(iteratedType, leftType, varExpr, node.expression); + } + } + } + checkSourceElement(node.statement); + if (node.locals) { + registerForUnusedIdentifiersCheck(node); + } + } + function checkForInStatement(node) { + // Grammar checking + checkGrammarForInOrForOfStatement(node); + var rightType = getNonNullableTypeIfNeeded(checkExpression(node.expression)); + // TypeScript 1.0 spec (April 2014): 5.4 + // In a 'for-in' statement of the form + // for (let VarDecl in Expr) Statement + // VarDecl must be a variable declaration without a type annotation that declares a variable of type Any, + // and Expr must be an expression of type Any, an object type, or a type parameter type. + if (node.initializer.kind === 238 /* VariableDeclarationList */) { + var variable = node.initializer.declarations[0]; + if (variable && ts.isBindingPattern(variable.name)) { + error(variable.name, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern); + } + checkForInOrForOfVariableDeclaration(node); + } + else { + // In a 'for-in' statement of the form + // for (Var in Expr) Statement + // Var must be an expression classified as a reference of type Any or the String primitive type, + // and Expr must be an expression of type Any, an object type, or a type parameter type. + var varExpr = node.initializer; + var leftType = checkExpression(varExpr); + if (varExpr.kind === 187 /* ArrayLiteralExpression */ || varExpr.kind === 188 /* ObjectLiteralExpression */) { + error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern); + } + else if (!isTypeAssignableTo(getIndexTypeOrString(rightType), leftType)) { + error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any); + } + else { + // run check only former check succeeded to avoid cascading errors + checkReferenceExpression(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access); + } + } + // unknownType is returned i.e. if node.expression is identifier whose name cannot be resolved + // in this case error about missing name is already reported - do not report extra one + if (rightType === neverType || !isTypeAssignableToKind(rightType, 67108864 /* NonPrimitive */ | 58982400 /* InstantiableNonPrimitive */)) { + error(node.expression, ts.Diagnostics.The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_but_here_has_type_0, typeToString(rightType)); + } + checkSourceElement(node.statement); + if (node.locals) { + registerForUnusedIdentifiersCheck(node); + } + } + function checkForInOrForOfVariableDeclaration(iterationStatement) { + var variableDeclarationList = iterationStatement.initializer; + // checkGrammarForInOrForOfStatement will check that there is exactly one declaration. + if (variableDeclarationList.declarations.length >= 1) { + var decl = variableDeclarationList.declarations[0]; + checkVariableDeclaration(decl); + } + } + function checkRightHandSideOfForOf(rhsExpression, awaitModifier) { + var expressionType = checkNonNullExpression(rhsExpression); + return checkIteratedTypeOrElementType(expressionType, rhsExpression, /*allowStringInput*/ true, awaitModifier !== undefined); + } + function checkIteratedTypeOrElementType(inputType, errorNode, allowStringInput, allowAsyncIterables) { + if (isTypeAny(inputType)) { + return inputType; + } + return getIteratedTypeOrElementType(inputType, errorNode, allowStringInput, allowAsyncIterables, /*checkAssignability*/ true) || anyType; + } + /** + * When consuming an iterable type in a for..of, spread, or iterator destructuring assignment + * we want to get the iterated type of an iterable for ES2015 or later, or the iterated type + * of a iterable (if defined globally) or element type of an array like for ES2015 or earlier. + */ + function getIteratedTypeOrElementType(inputType, errorNode, allowStringInput, allowAsyncIterables, checkAssignability) { + if (inputType === neverType) { + reportTypeNotIterableError(errorNode, inputType, allowAsyncIterables); // TODO: GH#18217 + return undefined; + } + var uplevelIteration = languageVersion >= 2 /* ES2015 */; + var downlevelIteration = !uplevelIteration && compilerOptions.downlevelIteration; + // Get the iterated type of an `Iterable` or `IterableIterator` only in ES2015 + // or higher, when inside of an async generator or for-await-if, or when + // downlevelIteration is requested. + if (uplevelIteration || downlevelIteration || allowAsyncIterables) { + // We only report errors for an invalid iterable type in ES2015 or higher. + var iteratedType = getIteratedTypeOfIterable(inputType, uplevelIteration ? errorNode : undefined, allowAsyncIterables, /*allowSyncIterables*/ true, checkAssignability); + if (iteratedType || uplevelIteration) { + return iteratedType; + } + } + var arrayType = inputType; + var reportedError = false; + var hasStringConstituent = false; + // If strings are permitted, remove any string-like constituents from the array type. + // This allows us to find other non-string element types from an array unioned with + // a string. + if (allowStringInput) { + if (arrayType.flags & 1048576 /* Union */) { + // After we remove all types that are StringLike, we will know if there was a string constituent + // based on whether the result of filter is a new array. + var arrayTypes = inputType.types; + var filteredTypes = ts.filter(arrayTypes, function (t) { return !(t.flags & 132 /* StringLike */); }); + if (filteredTypes !== arrayTypes) { + arrayType = getUnionType(filteredTypes, 2 /* Subtype */); + } + } + else if (arrayType.flags & 132 /* StringLike */) { + arrayType = neverType; + } + hasStringConstituent = arrayType !== inputType; + if (hasStringConstituent) { + if (languageVersion < 1 /* ES5 */) { + if (errorNode) { + error(errorNode, ts.Diagnostics.Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher); + reportedError = true; + } + } + // Now that we've removed all the StringLike types, if no constituents remain, then the entire + // arrayOrStringType was a string. + if (arrayType.flags & 131072 /* Never */) { + return stringType; + } + } + } + if (!isArrayLikeType(arrayType)) { + if (errorNode && !reportedError) { + // Which error we report depends on whether we allow strings or if there was a + // string constituent. For example, if the input type is number | string, we + // want to say that number is not an array type. But if the input was just + // number and string input is allowed, we want to say that number is not an + // array type or a string type. + var isIterable = !!getIteratedTypeOfIterable(inputType, /* errorNode */ undefined, allowAsyncIterables, /*allowSyncIterables*/ true, checkAssignability); + var diagnostic = !allowStringInput || hasStringConstituent + ? downlevelIteration + ? ts.Diagnostics.Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator + : isIterable + ? ts.Diagnostics.Type_0_is_not_an_array_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators + : ts.Diagnostics.Type_0_is_not_an_array_type + : downlevelIteration + ? ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator + : isIterable + ? ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators + : ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type; + error(errorNode, diagnostic, typeToString(arrayType)); + } + return hasStringConstituent ? stringType : undefined; + } + var arrayElementType = getIndexTypeOfType(arrayType, 1 /* Number */); + if (hasStringConstituent && arrayElementType) { + // This is just an optimization for the case where arrayOrStringType is string | string[] + if (arrayElementType.flags & 132 /* StringLike */) { + return stringType; + } + return getUnionType([arrayElementType, stringType], 2 /* Subtype */); + } + return arrayElementType; + } + /** + * We want to treat type as an iterable, and get the type it is an iterable of. The iterable + * must have the following structure (annotated with the names of the variables below): + * + * { // iterable + * [Symbol.iterator]: { // iteratorMethod + * (): Iterator + * } + * } + * + * For an async iterable, we expect the following structure: + * + * { // iterable + * [Symbol.asyncIterator]: { // iteratorMethod + * (): AsyncIterator + * } + * } + * + * T is the type we are after. At every level that involves analyzing return types + * of signatures, we union the return types of all the signatures. + * + * Another thing to note is that at any step of this process, we could run into a dead end, + * meaning either the property is missing, or we run into the anyType. If either of these things + * happens, we return undefined to signal that we could not find the iterated type. If a property + * is missing, and the previous step did not result in 'any', then we also give an error if the + * caller requested it. Then the caller can decide what to do in the case where there is no iterated + * type. This is different from returning anyType, because that would signify that we have matched the + * whole pattern and that T (above) is 'any'. + * + * For a **for-of** statement, `yield*` (in a normal generator), spread, array + * destructuring, or normal generator we will only ever look for a `[Symbol.iterator]()` + * method. + * + * For an async generator we will only ever look at the `[Symbol.asyncIterator]()` method. + * + * For a **for-await-of** statement or a `yield*` in an async generator we will look for + * the `[Symbol.asyncIterator]()` method first, and then the `[Symbol.iterator]()` method. + */ + function getIteratedTypeOfIterable(type, errorNode, allowAsyncIterables, allowSyncIterables, checkAssignability) { + if (isTypeAny(type)) { + return undefined; + } + return mapType(type, getIteratedType); + function getIteratedType(type) { + var typeAsIterable = type; + if (allowAsyncIterables) { + if (typeAsIterable.iteratedTypeOfAsyncIterable) { + return typeAsIterable.iteratedTypeOfAsyncIterable; + } + // As an optimization, if the type is an instantiation of the global `AsyncIterable` + // or the global `AsyncIterableIterator` then just grab its type argument. + if (isReferenceToType(type, getGlobalAsyncIterableType(/*reportErrors*/ false)) || + isReferenceToType(type, getGlobalAsyncIterableIteratorType(/*reportErrors*/ false))) { + return typeAsIterable.iteratedTypeOfAsyncIterable = type.typeArguments[0]; + } + } + if (allowSyncIterables) { + if (typeAsIterable.iteratedTypeOfIterable) { + return allowAsyncIterables + ? typeAsIterable.iteratedTypeOfAsyncIterable = getAwaitedType(typeAsIterable.iteratedTypeOfIterable) + : typeAsIterable.iteratedTypeOfIterable; + } + // As an optimization, if the type is an instantiation of the global `Iterable` or + // `IterableIterator` then just grab its type argument. + if (isReferenceToType(type, getGlobalIterableType(/*reportErrors*/ false)) || + isReferenceToType(type, getGlobalIterableIteratorType(/*reportErrors*/ false))) { + return allowAsyncIterables + ? typeAsIterable.iteratedTypeOfAsyncIterable = getAwaitedType(type.typeArguments[0]) + : typeAsIterable.iteratedTypeOfIterable = type.typeArguments[0]; + } + } + var asyncMethodType = allowAsyncIterables && getTypeOfPropertyOfType(type, ts.getPropertyNameForKnownSymbolName("asyncIterator")); + var methodType = asyncMethodType || (allowSyncIterables ? getTypeOfPropertyOfType(type, ts.getPropertyNameForKnownSymbolName("iterator")) : undefined); + if (isTypeAny(methodType)) { + return undefined; + } + var signatures = methodType ? getSignaturesOfType(methodType, 0 /* Call */) : undefined; + if (!ts.some(signatures)) { + if (errorNode) { + // only report on the first error + reportTypeNotIterableError(errorNode, type, allowAsyncIterables); + errorNode = undefined; + } + return undefined; + } + var returnType = getUnionType(ts.map(signatures, getReturnTypeOfSignature), 2 /* Subtype */); + var iteratedType = getIteratedTypeOfIterator(returnType, errorNode, /*isAsyncIterator*/ !!asyncMethodType); + if (checkAssignability && errorNode && iteratedType) { + // If `checkAssignability` was specified, we were called from + // `checkIteratedTypeOrElementType`. As such, we need to validate that + // the type passed in is actually an Iterable. + checkTypeAssignableTo(type, asyncMethodType + ? createAsyncIterableType(iteratedType) + : createIterableType(iteratedType), errorNode); + } + if (iteratedType) { + return allowAsyncIterables + ? typeAsIterable.iteratedTypeOfAsyncIterable = asyncMethodType ? iteratedType : getAwaitedType(iteratedType) + : typeAsIterable.iteratedTypeOfIterable = iteratedType; + } + } + } + function reportTypeNotIterableError(errorNode, type, allowAsyncIterables) { + error(errorNode, allowAsyncIterables + ? ts.Diagnostics.Type_0_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator + : ts.Diagnostics.Type_0_must_have_a_Symbol_iterator_method_that_returns_an_iterator, typeToString(type)); + } + /** + * This function has very similar logic as getIteratedTypeOfIterable, except that it operates on + * Iterators instead of Iterables. Here is the structure: + * + * { // iterator + * next: { // nextMethod + * (): { // nextResult + * value: T // nextValue + * } + * } + * } + * + * For an async iterator, we expect the following structure: + * + * { // iterator + * next: { // nextMethod + * (): PromiseLike<{ // nextResult + * value: T // nextValue + * }> + * } + * } + */ + function getIteratedTypeOfIterator(type, errorNode, isAsyncIterator) { + if (isTypeAny(type)) { + return undefined; + } + var typeAsIterator = type; + if (isAsyncIterator ? typeAsIterator.iteratedTypeOfAsyncIterator : typeAsIterator.iteratedTypeOfIterator) { + return isAsyncIterator ? typeAsIterator.iteratedTypeOfAsyncIterator : typeAsIterator.iteratedTypeOfIterator; + } + // As an optimization, if the type is an instantiation of the global `Iterator` (for + // a non-async iterator) or the global `AsyncIterator` (for an async-iterator) then + // just grab its type argument. + var getIteratorType = isAsyncIterator ? getGlobalAsyncIteratorType : getGlobalIteratorType; + if (isReferenceToType(type, getIteratorType(/*reportErrors*/ false))) { + return isAsyncIterator + ? typeAsIterator.iteratedTypeOfAsyncIterator = type.typeArguments[0] + : typeAsIterator.iteratedTypeOfIterator = type.typeArguments[0]; + } + // Both async and non-async iterators must have a `next` method. + var nextMethod = getTypeOfPropertyOfType(type, "next"); + if (isTypeAny(nextMethod)) { + return undefined; + } + var nextMethodSignatures = nextMethod ? getSignaturesOfType(nextMethod, 0 /* Call */) : ts.emptyArray; + if (nextMethodSignatures.length === 0) { + if (errorNode) { + error(errorNode, isAsyncIterator + ? ts.Diagnostics.An_async_iterator_must_have_a_next_method + : ts.Diagnostics.An_iterator_must_have_a_next_method); + } + return undefined; + } + var nextResult = getUnionType(ts.map(nextMethodSignatures, getReturnTypeOfSignature), 2 /* Subtype */); + if (isTypeAny(nextResult)) { + return undefined; + } + // For an async iterator, we must get the awaited type of the return type. + if (isAsyncIterator) { + nextResult = getAwaitedTypeOfPromise(nextResult, errorNode, ts.Diagnostics.The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property); + if (isTypeAny(nextResult)) { + return undefined; + } + } + var nextValue = nextResult && getTypeOfPropertyOfType(nextResult, "value"); + if (!nextValue) { + if (errorNode) { + error(errorNode, isAsyncIterator + ? ts.Diagnostics.The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property + : ts.Diagnostics.The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property); + } + return undefined; + } + return isAsyncIterator + ? typeAsIterator.iteratedTypeOfAsyncIterator = nextValue + : typeAsIterator.iteratedTypeOfIterator = nextValue; + } + /** + * A generator may have a return type of `Iterator`, `Iterable`, or + * `IterableIterator`. An async generator may have a return type of `AsyncIterator`, + * `AsyncIterable`, or `AsyncIterableIterator`. This function can be used to extract + * the iterated type from this return type for contextual typing and verifying signatures. + */ + function getIteratedTypeOfGenerator(returnType, isAsyncGenerator) { + if (isTypeAny(returnType)) { + return undefined; + } + return getIteratedTypeOfIterable(returnType, /*errorNode*/ undefined, /*allowAsyncIterables*/ isAsyncGenerator, /*allowSyncIterables*/ !isAsyncGenerator, /*checkAssignability*/ false) + || getIteratedTypeOfIterator(returnType, /*errorNode*/ undefined, isAsyncGenerator); + } + function checkBreakOrContinueStatement(node) { + // Grammar checking + if (!checkGrammarStatementInAmbientContext(node)) + checkGrammarBreakOrContinueStatement(node); + // TODO: Check that target label is valid + } + function isUnwrappedReturnTypeVoidOrAny(func, returnType) { + var unwrappedReturnType = (ts.getFunctionFlags(func) & 3 /* AsyncGenerator */) === 2 /* Async */ + ? getPromisedTypeOfPromise(returnType) // Async function + : returnType; // AsyncGenerator function, Generator function, or normal function + return !!unwrappedReturnType && maybeTypeOfKind(unwrappedReturnType, 16384 /* Void */ | 3 /* AnyOrUnknown */); + } + function checkReturnStatement(node) { + // Grammar checking + if (checkGrammarStatementInAmbientContext(node)) { + return; + } + var func = ts.getContainingFunction(node); + if (!func) { + grammarErrorOnFirstToken(node, ts.Diagnostics.A_return_statement_can_only_be_used_within_a_function_body); + return; + } + var signature = getSignatureFromDeclaration(func); + var returnType = getReturnTypeOfSignature(signature); + var functionFlags = ts.getFunctionFlags(func); + var isGenerator = functionFlags & 1 /* Generator */; + if (strictNullChecks || node.expression || returnType.flags & 131072 /* Never */) { + var exprType = node.expression ? checkExpressionCached(node.expression) : undefinedType; + if (isGenerator) { // AsyncGenerator function or Generator function + // A generator does not need its return expressions checked against its return type. + // Instead, the yield expressions are checked against the element type. + // TODO: Check return types of generators when return type tracking is added + // for generators. + return; + } + else if (func.kind === 159 /* SetAccessor */) { + if (node.expression) { + error(node, ts.Diagnostics.Setters_cannot_return_a_value); + } + } + else if (func.kind === 157 /* Constructor */) { + if (node.expression && !checkTypeAssignableToAndOptionallyElaborate(exprType, returnType, node, node.expression)) { + error(node, ts.Diagnostics.Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class); + } + } + else if (getReturnTypeFromAnnotation(func)) { + if (functionFlags & 2 /* Async */) { // Async function + var promisedType = getPromisedTypeOfPromise(returnType); + var awaitedType = checkAwaitedType(exprType, node, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); + if (promisedType) { + // If the function has a return type, but promisedType is + // undefined, an error will be reported in checkAsyncFunctionReturnType + // so we don't need to report one here. + checkTypeAssignableTo(awaitedType, promisedType, node); + } + } + else { + checkTypeAssignableToAndOptionallyElaborate(exprType, returnType, node, node.expression); + } + } + } + else if (func.kind !== 157 /* Constructor */ && compilerOptions.noImplicitReturns && !isUnwrappedReturnTypeVoidOrAny(func, returnType) && !isGenerator) { + // The function has a return type, but the return statement doesn't have an expression. + error(node, ts.Diagnostics.Not_all_code_paths_return_a_value); + } + } + function checkWithStatement(node) { + // Grammar checking for withStatement + if (!checkGrammarStatementInAmbientContext(node)) { + if (node.flags & 16384 /* AwaitContext */) { + grammarErrorOnFirstToken(node, ts.Diagnostics.with_statements_are_not_allowed_in_an_async_function_block); + } + } + checkExpression(node.expression); + var sourceFile = ts.getSourceFileOfNode(node); + if (!hasParseDiagnostics(sourceFile)) { + var start = ts.getSpanOfTokenAtPosition(sourceFile, node.pos).start; + var end = node.statement.pos; + grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any); + } + } + function checkSwitchStatement(node) { + // Grammar checking + checkGrammarStatementInAmbientContext(node); + var firstDefaultClause; + var hasDuplicateDefaultClause = false; + var expressionType = checkExpression(node.expression); + var expressionIsLiteral = isLiteralType(expressionType); + ts.forEach(node.caseBlock.clauses, function (clause) { + // Grammar check for duplicate default clauses, skip if we already report duplicate default clause + if (clause.kind === 272 /* DefaultClause */ && !hasDuplicateDefaultClause) { + if (firstDefaultClause === undefined) { + firstDefaultClause = clause; + } + else { + var sourceFile = ts.getSourceFileOfNode(node); + var start = ts.skipTrivia(sourceFile.text, clause.pos); + var end = clause.statements.length > 0 ? clause.statements[0].pos : clause.end; + grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.A_default_clause_cannot_appear_more_than_once_in_a_switch_statement); + hasDuplicateDefaultClause = true; + } + } + if (produceDiagnostics && clause.kind === 271 /* CaseClause */) { + // TypeScript 1.0 spec (April 2014): 5.9 + // In a 'switch' statement, each 'case' expression must be of a type that is comparable + // to or from the type of the 'switch' expression. + var caseType = checkExpression(clause.expression); + var caseIsLiteral = isLiteralType(caseType); + var comparedExpressionType = expressionType; + if (!caseIsLiteral || !expressionIsLiteral) { + caseType = caseIsLiteral ? getBaseTypeOfLiteralType(caseType) : caseType; + comparedExpressionType = getBaseTypeOfLiteralType(expressionType); + } + if (!isTypeEqualityComparableTo(comparedExpressionType, caseType)) { + // expressionType is not comparable to caseType, try the reversed check and report errors if it fails + checkTypeComparableTo(caseType, comparedExpressionType, clause.expression, /*headMessage*/ undefined); + } + } + ts.forEach(clause.statements, checkSourceElement); + }); + if (node.caseBlock.locals) { + registerForUnusedIdentifiersCheck(node.caseBlock); + } + } + function checkLabeledStatement(node) { + // Grammar checking + if (!checkGrammarStatementInAmbientContext(node)) { + ts.findAncestor(node.parent, function (current) { + if (ts.isFunctionLike(current)) { + return "quit"; + } + if (current.kind === 233 /* LabeledStatement */ && current.label.escapedText === node.label.escapedText) { + grammarErrorOnNode(node.label, ts.Diagnostics.Duplicate_label_0, ts.getTextOfNode(node.label)); + return true; + } + return false; + }); + } + // ensure that label is unique + checkSourceElement(node.statement); + } + function checkThrowStatement(node) { + // Grammar checking + if (!checkGrammarStatementInAmbientContext(node)) { + if (node.expression === undefined) { + grammarErrorAfterFirstToken(node, ts.Diagnostics.Line_break_not_permitted_here); + } + } + if (node.expression) { + checkExpression(node.expression); + } + } + function checkTryStatement(node) { + // Grammar checking + checkGrammarStatementInAmbientContext(node); + checkBlock(node.tryBlock); + var catchClause = node.catchClause; + if (catchClause) { + // Grammar checking + if (catchClause.variableDeclaration) { + if (catchClause.variableDeclaration.type) { + grammarErrorOnFirstToken(catchClause.variableDeclaration.type, ts.Diagnostics.Catch_clause_variable_cannot_have_a_type_annotation); + } + else if (catchClause.variableDeclaration.initializer) { + grammarErrorOnFirstToken(catchClause.variableDeclaration.initializer, ts.Diagnostics.Catch_clause_variable_cannot_have_an_initializer); + } + else { + var blockLocals_1 = catchClause.block.locals; + if (blockLocals_1) { + ts.forEachKey(catchClause.locals, function (caughtName) { + var blockLocal = blockLocals_1.get(caughtName); + if (blockLocal && (blockLocal.flags & 2 /* BlockScopedVariable */) !== 0) { + grammarErrorOnNode(blockLocal.valueDeclaration, ts.Diagnostics.Cannot_redeclare_identifier_0_in_catch_clause, caughtName); + } + }); + } + } + } + checkBlock(catchClause.block); + } + if (node.finallyBlock) { + checkBlock(node.finallyBlock); + } + } + function checkIndexConstraints(type) { + var declaredNumberIndexer = getIndexDeclarationOfSymbol(type.symbol, 1 /* Number */); + var declaredStringIndexer = getIndexDeclarationOfSymbol(type.symbol, 0 /* String */); + var stringIndexType = getIndexTypeOfType(type, 0 /* String */); + var numberIndexType = getIndexTypeOfType(type, 1 /* Number */); + if (stringIndexType || numberIndexType) { + ts.forEach(getPropertiesOfObjectType(type), function (prop) { + var propType = getTypeOfSymbol(prop); + checkIndexConstraintForProperty(prop, propType, type, declaredStringIndexer, stringIndexType, 0 /* String */); + checkIndexConstraintForProperty(prop, propType, type, declaredNumberIndexer, numberIndexType, 1 /* Number */); + }); + var classDeclaration = type.symbol.valueDeclaration; + if (ts.getObjectFlags(type) & 1 /* Class */ && ts.isClassLike(classDeclaration)) { + for (var _i = 0, _a = classDeclaration.members; _i < _a.length; _i++) { + var member = _a[_i]; + // Only process instance properties with computed names here. + // Static properties cannot be in conflict with indexers, + // and properties with literal names were already checked. + if (!ts.hasModifier(member, 32 /* Static */) && hasNonBindableDynamicName(member)) { + var symbol = getSymbolOfNode(member); + var propType = getTypeOfSymbol(symbol); + checkIndexConstraintForProperty(symbol, propType, type, declaredStringIndexer, stringIndexType, 0 /* String */); + checkIndexConstraintForProperty(symbol, propType, type, declaredNumberIndexer, numberIndexType, 1 /* Number */); + } + } + } + } + var errorNode; + if (stringIndexType && numberIndexType) { + errorNode = declaredNumberIndexer || declaredStringIndexer; + // condition 'errorNode === undefined' may appear if types does not declare nor string neither number indexer + if (!errorNode && (ts.getObjectFlags(type) & 2 /* Interface */)) { + var someBaseTypeHasBothIndexers = ts.forEach(getBaseTypes(type), function (base) { return getIndexTypeOfType(base, 0 /* String */) && getIndexTypeOfType(base, 1 /* Number */); }); + errorNode = someBaseTypeHasBothIndexers ? undefined : type.symbol.declarations[0]; + } + } + if (errorNode && !isTypeAssignableTo(numberIndexType, stringIndexType)) { // TODO: GH#18217 + error(errorNode, ts.Diagnostics.Numeric_index_type_0_is_not_assignable_to_string_index_type_1, typeToString(numberIndexType), typeToString(stringIndexType)); + } + function checkIndexConstraintForProperty(prop, propertyType, containingType, indexDeclaration, indexType, indexKind) { + // ESSymbol properties apply to neither string nor numeric indexers. + if (!indexType || ts.isKnownSymbol(prop)) { + return; + } + var propDeclaration = prop.valueDeclaration; + var name = propDeclaration && ts.getNameOfDeclaration(propDeclaration); + // index is numeric and property name is not valid numeric literal + if (indexKind === 1 /* Number */ && !(name ? isNumericName(name) : isNumericLiteralName(prop.escapedName))) { + return; + } + // perform property check if property or indexer is declared in 'type' + // this allows us to rule out cases when both property and indexer are inherited from the base class + var errorNode; + if (propDeclaration && name && + (propDeclaration.kind === 204 /* BinaryExpression */ || + name.kind === 149 /* ComputedPropertyName */ || + prop.parent === containingType.symbol)) { + errorNode = propDeclaration; + } + else if (indexDeclaration) { + errorNode = indexDeclaration; + } + else if (ts.getObjectFlags(containingType) & 2 /* Interface */) { + // for interfaces property and indexer might be inherited from different bases + // check if any base class already has both property and indexer. + // check should be performed only if 'type' is the first type that brings property\indexer together + var someBaseClassHasBothPropertyAndIndexer = ts.forEach(getBaseTypes(containingType), function (base) { return getPropertyOfObjectType(base, prop.escapedName) && getIndexTypeOfType(base, indexKind); }); + errorNode = someBaseClassHasBothPropertyAndIndexer ? undefined : containingType.symbol.declarations[0]; + } + if (errorNode && !isTypeAssignableTo(propertyType, indexType)) { + var errorMessage = indexKind === 0 /* String */ + ? ts.Diagnostics.Property_0_of_type_1_is_not_assignable_to_string_index_type_2 + : ts.Diagnostics.Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2; + error(errorNode, errorMessage, symbolToString(prop), typeToString(propertyType), typeToString(indexType)); + } + } + } + function checkTypeNameIsReserved(name, message) { + // TS 1.0 spec (April 2014): 3.6.1 + // The predefined type keywords are reserved and cannot be used as names of user defined types. + switch (name.escapedText) { + case "any": + case "unknown": + case "number": + case "bigint": + case "boolean": + case "string": + case "symbol": + case "void": + case "object": + error(name, message, name.escapedText); + } + } + /** + * The name cannot be used as 'Object' of user defined types with special target. + */ + function checkClassNameCollisionWithObject(name) { + if (languageVersion === 1 /* ES5 */ && name.escapedText === "Object" + && moduleKind !== ts.ModuleKind.ES2015 && moduleKind !== ts.ModuleKind.ESNext) { + error(name, ts.Diagnostics.Class_name_cannot_be_Object_when_targeting_ES5_with_module_0, ts.ModuleKind[moduleKind]); // https://github.com/Microsoft/TypeScript/issues/17494 + } + } + /** + * Check each type parameter and check that type parameters have no duplicate type parameter declarations + */ + function checkTypeParameters(typeParameterDeclarations) { + if (typeParameterDeclarations) { + var seenDefault = false; + for (var i = 0; i < typeParameterDeclarations.length; i++) { + var node = typeParameterDeclarations[i]; + checkTypeParameter(node); + if (produceDiagnostics) { + if (node.default) { + seenDefault = true; + } + else if (seenDefault) { + error(node, ts.Diagnostics.Required_type_parameters_may_not_follow_optional_type_parameters); + } + for (var j = 0; j < i; j++) { + if (typeParameterDeclarations[j].symbol === node.symbol) { + error(node.name, ts.Diagnostics.Duplicate_identifier_0, ts.declarationNameToString(node.name)); + } + } + } + } + } + } + /** Check that type parameter lists are identical across multiple declarations */ + function checkTypeParameterListsIdentical(symbol) { + if (symbol.declarations.length === 1) { + return; + } + var links = getSymbolLinks(symbol); + if (!links.typeParametersChecked) { + links.typeParametersChecked = true; + var declarations = getClassOrInterfaceDeclarationsOfSymbol(symbol); + if (declarations.length <= 1) { + return; + } + var type = getDeclaredTypeOfSymbol(symbol); + if (!areTypeParametersIdentical(declarations, type.localTypeParameters)) { + // Report an error on every conflicting declaration. + var name = symbolToString(symbol); + for (var _i = 0, declarations_6 = declarations; _i < declarations_6.length; _i++) { + var declaration = declarations_6[_i]; + error(declaration.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_type_parameters, name); + } + } + } + } + function areTypeParametersIdentical(declarations, targetParameters) { + var maxTypeArgumentCount = ts.length(targetParameters); + var minTypeArgumentCount = getMinTypeArgumentCount(targetParameters); + for (var _i = 0, declarations_7 = declarations; _i < declarations_7.length; _i++) { + var declaration = declarations_7[_i]; + // If this declaration has too few or too many type parameters, we report an error + var sourceParameters = ts.getEffectiveTypeParameterDeclarations(declaration); + var numTypeParameters = sourceParameters.length; + if (numTypeParameters < minTypeArgumentCount || numTypeParameters > maxTypeArgumentCount) { + return false; + } + for (var i = 0; i < numTypeParameters; i++) { + var source = sourceParameters[i]; + var target = targetParameters[i]; + // If the type parameter node does not have the same as the resolved type + // parameter at this position, we report an error. + if (source.name.escapedText !== target.symbol.escapedName) { + return false; + } + // If the type parameter node does not have an identical constraint as the resolved + // type parameter at this position, we report an error. + var constraint = ts.getEffectiveConstraintOfTypeParameter(source); + var sourceConstraint = constraint && getTypeFromTypeNode(constraint); + var targetConstraint = getConstraintOfTypeParameter(target); + if (sourceConstraint) { + // relax check if later interface augmentation has no constraint + if (!targetConstraint || !isTypeIdenticalTo(sourceConstraint, targetConstraint)) { + return false; + } + } + // If the type parameter node has a default and it is not identical to the default + // for the type parameter at this position, we report an error. + var sourceDefault = source.default && getTypeFromTypeNode(source.default); + var targetDefault = getDefaultFromTypeParameter(target); + if (sourceDefault && targetDefault && !isTypeIdenticalTo(sourceDefault, targetDefault)) { + return false; + } + } + } + return true; + } + function checkClassExpression(node) { + checkClassLikeDeclaration(node); + checkNodeDeferred(node); + return getTypeOfSymbol(getSymbolOfNode(node)); + } + function checkClassExpressionDeferred(node) { + ts.forEach(node.members, checkSourceElement); + registerForUnusedIdentifiersCheck(node); + } + function checkClassDeclaration(node) { + if (!node.name && !ts.hasModifier(node, 512 /* Default */)) { + grammarErrorOnFirstToken(node, ts.Diagnostics.A_class_declaration_without_the_default_modifier_must_have_a_name); + } + checkClassLikeDeclaration(node); + ts.forEach(node.members, checkSourceElement); + registerForUnusedIdentifiersCheck(node); + } + function checkClassLikeDeclaration(node) { + checkGrammarClassLikeDeclaration(node); + checkDecorators(node); + if (node.name) { + checkTypeNameIsReserved(node.name, ts.Diagnostics.Class_name_cannot_be_0); + checkCollisionWithRequireExportsInGeneratedCode(node, node.name); + checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); + if (!(node.flags & 4194304 /* Ambient */)) { + checkClassNameCollisionWithObject(node.name); + } + } + checkTypeParameters(ts.getEffectiveTypeParameterDeclarations(node)); + checkExportsOnMergedDeclarations(node); + var symbol = getSymbolOfNode(node); + var type = getDeclaredTypeOfSymbol(symbol); + var typeWithThis = getTypeWithThisArgument(type); + var staticType = getTypeOfSymbol(symbol); + checkTypeParameterListsIdentical(symbol); + checkClassForDuplicateDeclarations(node); + // Only check for reserved static identifiers on non-ambient context. + if (!(node.flags & 4194304 /* Ambient */)) { + checkClassForStaticPropertyNameConflicts(node); + } + var baseTypeNode = ts.getEffectiveBaseTypeNode(node); + if (baseTypeNode) { + if (languageVersion < 2 /* ES2015 */) { + checkExternalEmitHelpers(baseTypeNode.parent, 1 /* Extends */); + } + var baseTypes = getBaseTypes(type); + if (baseTypes.length && produceDiagnostics) { + var baseType_1 = baseTypes[0]; + var baseConstructorType = getBaseConstructorTypeOfClass(type); + var staticBaseType = getApparentType(baseConstructorType); + checkBaseTypeAccessibility(staticBaseType, baseTypeNode); + checkSourceElement(baseTypeNode.expression); + var extendsNode = ts.getClassExtendsHeritageElement(node); + if (extendsNode && extendsNode !== baseTypeNode) { + checkExpression(extendsNode.expression); + } + if (ts.some(baseTypeNode.typeArguments)) { + ts.forEach(baseTypeNode.typeArguments, checkSourceElement); + for (var _i = 0, _a = getConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments, baseTypeNode); _i < _a.length; _i++) { + var constructor = _a[_i]; + if (!checkTypeArgumentConstraints(baseTypeNode, constructor.typeParameters)) { + break; + } + } + } + var baseWithThis = getTypeWithThisArgument(baseType_1, type.thisType); + if (!checkTypeAssignableTo(typeWithThis, baseWithThis, /*errorNode*/ undefined)) { + issueMemberSpecificError(node, typeWithThis, baseWithThis, ts.Diagnostics.Class_0_incorrectly_extends_base_class_1); + } + else { + // Report static side error only when instance type is assignable + checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, ts.Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1); + } + if (baseConstructorType.flags & 8650752 /* TypeVariable */ && !isMixinConstructorType(staticType)) { + error(node.name || node, ts.Diagnostics.A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any); + } + if (!(staticBaseType.symbol && staticBaseType.symbol.flags & 32 /* Class */) && !(baseConstructorType.flags & 8650752 /* TypeVariable */)) { + // When the static base type is a "class-like" constructor function (but not actually a class), we verify + // that all instantiated base constructor signatures return the same type. We can simply compare the type + // references (as opposed to checking the structure of the types) because elsewhere we have already checked + // that the base type is a class or interface type (and not, for example, an anonymous object type). + // (Javascript constructor functions have this property trivially true since their return type is ignored.) + var constructors = getInstantiatedConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments, baseTypeNode); + if (ts.forEach(constructors, function (sig) { return !isJSConstructor(sig.declaration) && getReturnTypeOfSignature(sig) !== baseType_1; })) { + error(baseTypeNode.expression, ts.Diagnostics.Base_constructors_must_all_have_the_same_return_type); + } + } + checkKindsOfPropertyMemberOverrides(type, baseType_1); + } + } + var implementedTypeNodes = ts.getClassImplementsHeritageClauseElements(node); + if (implementedTypeNodes) { + for (var _b = 0, implementedTypeNodes_1 = implementedTypeNodes; _b < implementedTypeNodes_1.length; _b++) { + var typeRefNode = implementedTypeNodes_1[_b]; + if (!ts.isEntityNameExpression(typeRefNode.expression)) { + error(typeRefNode.expression, ts.Diagnostics.A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments); + } + checkTypeReferenceNode(typeRefNode); + if (produceDiagnostics) { + var t = getTypeFromTypeNode(typeRefNode); + if (t !== errorType) { + if (isValidBaseType(t)) { + var genericDiag = t.symbol && t.symbol.flags & 32 /* Class */ ? + ts.Diagnostics.Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass : + ts.Diagnostics.Class_0_incorrectly_implements_interface_1; + var baseWithThis = getTypeWithThisArgument(t, type.thisType); + if (!checkTypeAssignableTo(typeWithThis, baseWithThis, /*errorNode*/ undefined)) { + issueMemberSpecificError(node, typeWithThis, baseWithThis, genericDiag); + } + } + else { + error(typeRefNode, ts.Diagnostics.A_class_can_only_implement_an_object_type_or_intersection_of_object_types_with_statically_known_members); + } + } + } + } + } + if (produceDiagnostics) { + checkIndexConstraints(type); + checkTypeForDuplicateIndexSignatures(node); + checkPropertyInitialization(node); + } + } + function issueMemberSpecificError(node, typeWithThis, baseWithThis, broadDiag) { + // iterate over all implemented properties and issue errors on each one which isn't compatible, rather than the class as a whole, if possible + var issuedMemberError = false; + var _loop_8 = function (member) { + if (ts.hasStaticModifier(member)) { + return "continue"; + } + var declaredProp = member.name && getSymbolAtLocation(member.name) || getSymbolAtLocation(member); + if (declaredProp) { + var prop = getPropertyOfType(typeWithThis, declaredProp.escapedName); + var baseProp = getPropertyOfType(baseWithThis, declaredProp.escapedName); + if (prop && baseProp) { + var rootChain = function () { return ts.chainDiagnosticMessages( + /*details*/ undefined, ts.Diagnostics.Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2, symbolToString(declaredProp), typeToString(typeWithThis), typeToString(baseWithThis)); }; + if (!checkTypeAssignableTo(getTypeOfSymbol(prop), getTypeOfSymbol(baseProp), member.name || member, /*message*/ undefined, rootChain)) { + issuedMemberError = true; + } + } + } + }; + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + _loop_8(member); + } + if (!issuedMemberError) { + // check again with diagnostics to generate a less-specific error + checkTypeAssignableTo(typeWithThis, baseWithThis, node.name || node, broadDiag); + } + } + function checkBaseTypeAccessibility(type, node) { + var signatures = getSignaturesOfType(type, 1 /* Construct */); + if (signatures.length) { + var declaration = signatures[0].declaration; + if (declaration && ts.hasModifier(declaration, 8 /* Private */)) { + var typeClassDeclaration = ts.getClassLikeDeclarationOfSymbol(type.symbol); + if (!isNodeWithinClass(node, typeClassDeclaration)) { + error(node, ts.Diagnostics.Cannot_extend_a_class_0_Class_constructor_is_marked_as_private, getFullyQualifiedName(type.symbol)); + } + } + } + } + function getTargetSymbol(s) { + // if symbol is instantiated its flags are not copied from the 'target' + // so we'll need to get back original 'target' symbol to work with correct set of flags + return ts.getCheckFlags(s) & 1 /* Instantiated */ ? s.target : s; + } + function getClassOrInterfaceDeclarationsOfSymbol(symbol) { + return ts.filter(symbol.declarations, function (d) { + return d.kind === 240 /* ClassDeclaration */ || d.kind === 241 /* InterfaceDeclaration */; + }); + } + function checkKindsOfPropertyMemberOverrides(type, baseType) { + // TypeScript 1.0 spec (April 2014): 8.2.3 + // A derived class inherits all members from its base class it doesn't override. + // Inheritance means that a derived class implicitly contains all non - overridden members of the base class. + // Both public and private property members are inherited, but only public property members can be overridden. + // A property member in a derived class is said to override a property member in a base class + // when the derived class property member has the same name and kind(instance or static) + // as the base class property member. + // The type of an overriding property member must be assignable(section 3.8.4) + // to the type of the overridden property member, or otherwise a compile - time error occurs. + // Base class instance member functions can be overridden by derived class instance member functions, + // but not by other kinds of members. + // Base class instance member variables and accessors can be overridden by + // derived class instance member variables and accessors, but not by other kinds of members. + // NOTE: assignability is checked in checkClassDeclaration + var baseProperties = getPropertiesOfType(baseType); + for (var _i = 0, baseProperties_1 = baseProperties; _i < baseProperties_1.length; _i++) { + var baseProperty = baseProperties_1[_i]; + var base = getTargetSymbol(baseProperty); + if (base.flags & 4194304 /* Prototype */) { + continue; + } + var derived = getTargetSymbol(getPropertyOfObjectType(type, base.escapedName)); // TODO: GH#18217 + var baseDeclarationFlags = ts.getDeclarationModifierFlagsFromSymbol(base); + ts.Debug.assert(!!derived, "derived should point to something, even if it is the base class' declaration."); + if (derived) { + // In order to resolve whether the inherited method was overridden in the base class or not, + // we compare the Symbols obtained. Since getTargetSymbol returns the symbol on the *uninstantiated* + // type declaration, derived and base resolve to the same symbol even in the case of generic classes. + if (derived === base) { + // derived class inherits base without override/redeclaration + var derivedClassDecl = ts.getClassLikeDeclarationOfSymbol(type.symbol); + // It is an error to inherit an abstract member without implementing it or being declared abstract. + // If there is no declaration for the derived class (as in the case of class expressions), + // then the class cannot be declared abstract. + if (baseDeclarationFlags & 128 /* Abstract */ && (!derivedClassDecl || !ts.hasModifier(derivedClassDecl, 128 /* Abstract */))) { + if (derivedClassDecl.kind === 209 /* ClassExpression */) { + error(derivedClassDecl, ts.Diagnostics.Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1, symbolToString(baseProperty), typeToString(baseType)); + } + else { + error(derivedClassDecl, ts.Diagnostics.Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2, typeToString(type), symbolToString(baseProperty), typeToString(baseType)); + } + } + } + else { + // derived overrides base. + var derivedDeclarationFlags = ts.getDeclarationModifierFlagsFromSymbol(derived); + if (baseDeclarationFlags & 8 /* Private */ || derivedDeclarationFlags & 8 /* Private */) { + // either base or derived property is private - not override, skip it + continue; + } + if (isPrototypeProperty(base) || base.flags & 98308 /* PropertyOrAccessor */ && derived.flags & 98308 /* PropertyOrAccessor */) { + // method is overridden with method or property/accessor is overridden with property/accessor - correct case + continue; + } + var errorMessage = void 0; + if (isPrototypeProperty(base)) { + if (derived.flags & 98304 /* Accessor */) { + errorMessage = ts.Diagnostics.Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor; + } + else { + errorMessage = ts.Diagnostics.Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_property; + } + } + else if (base.flags & 98304 /* Accessor */) { + errorMessage = ts.Diagnostics.Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function; + } + else { + errorMessage = ts.Diagnostics.Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_function; + } + error(ts.getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage, typeToString(baseType), symbolToString(base), typeToString(type)); + } + } + } + } + function checkInheritedPropertiesAreIdentical(type, typeNode) { + var baseTypes = getBaseTypes(type); + if (baseTypes.length < 2) { + return true; + } + var seen = ts.createUnderscoreEscapedMap(); + ts.forEach(resolveDeclaredMembers(type).declaredProperties, function (p) { seen.set(p.escapedName, { prop: p, containingType: type }); }); + var ok = true; + for (var _i = 0, baseTypes_2 = baseTypes; _i < baseTypes_2.length; _i++) { + var base = baseTypes_2[_i]; + var properties = getPropertiesOfType(getTypeWithThisArgument(base, type.thisType)); + for (var _a = 0, properties_7 = properties; _a < properties_7.length; _a++) { + var prop = properties_7[_a]; + var existing = seen.get(prop.escapedName); + if (!existing) { + seen.set(prop.escapedName, { prop: prop, containingType: base }); + } + else { + var isInheritedProperty = existing.containingType !== type; + if (isInheritedProperty && !isPropertyIdenticalTo(existing.prop, prop)) { + ok = false; + var typeName1 = typeToString(existing.containingType); + var typeName2 = typeToString(base); + var errorInfo = ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Named_property_0_of_types_1_and_2_are_not_identical, symbolToString(prop), typeName1, typeName2); + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Interface_0_cannot_simultaneously_extend_types_1_and_2, typeToString(type), typeName1, typeName2); + diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(typeNode, errorInfo)); + } + } + } + } + return ok; + } + function checkPropertyInitialization(node) { + if (!strictNullChecks || !strictPropertyInitialization || node.flags & 4194304 /* Ambient */) { + return; + } + var constructor = findConstructorDeclaration(node); + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + if (isInstancePropertyWithoutInitializer(member)) { + var propName = member.name; + if (ts.isIdentifier(propName)) { + var type = getTypeOfSymbol(getSymbolOfNode(member)); + if (!(type.flags & 3 /* AnyOrUnknown */ || getFalsyFlags(type) & 32768 /* Undefined */)) { + if (!constructor || !isPropertyInitializedInConstructor(propName, type, constructor)) { + error(member.name, ts.Diagnostics.Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor, ts.declarationNameToString(propName)); + } + } + } + } + } + } + function isInstancePropertyWithoutInitializer(node) { + return node.kind === 154 /* PropertyDeclaration */ && + !ts.hasModifier(node, 32 /* Static */ | 128 /* Abstract */) && + !node.exclamationToken && + !node.initializer; + } + function isPropertyInitializedInConstructor(propName, propType, constructor) { + var reference = ts.createPropertyAccess(ts.createThis(), propName); + reference.expression.parent = reference; + reference.parent = constructor; + reference.flowNode = constructor.returnFlowNode; + var flowType = getFlowTypeOfReference(reference, propType, getOptionalType(propType)); + return !(getFalsyFlags(flowType) & 32768 /* Undefined */); + } + function checkInterfaceDeclaration(node) { + // Grammar checking + if (!checkGrammarDecoratorsAndModifiers(node)) + checkGrammarInterfaceDeclaration(node); + checkTypeParameters(node.typeParameters); + if (produceDiagnostics) { + checkTypeNameIsReserved(node.name, ts.Diagnostics.Interface_name_cannot_be_0); + checkExportsOnMergedDeclarations(node); + var symbol = getSymbolOfNode(node); + checkTypeParameterListsIdentical(symbol); + // Only check this symbol once + var firstInterfaceDecl = ts.getDeclarationOfKind(symbol, 241 /* InterfaceDeclaration */); + if (node === firstInterfaceDecl) { + var type = getDeclaredTypeOfSymbol(symbol); + var typeWithThis = getTypeWithThisArgument(type); + // run subsequent checks only if first set succeeded + if (checkInheritedPropertiesAreIdentical(type, node.name)) { + for (var _i = 0, _a = getBaseTypes(type); _i < _a.length; _i++) { + var baseType = _a[_i]; + checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(baseType, type.thisType), node.name, ts.Diagnostics.Interface_0_incorrectly_extends_interface_1); + } + checkIndexConstraints(type); + } + } + checkObjectTypeForDuplicateDeclarations(node); + } + ts.forEach(ts.getInterfaceBaseTypeNodes(node), function (heritageElement) { + if (!ts.isEntityNameExpression(heritageElement.expression)) { + error(heritageElement.expression, ts.Diagnostics.An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments); + } + checkTypeReferenceNode(heritageElement); + }); + ts.forEach(node.members, checkSourceElement); + if (produceDiagnostics) { + checkTypeForDuplicateIndexSignatures(node); + registerForUnusedIdentifiersCheck(node); + } + } + function checkTypeAliasDeclaration(node) { + // Grammar checking + checkGrammarDecoratorsAndModifiers(node); + checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_alias_name_cannot_be_0); + checkTypeParameters(node.typeParameters); + checkSourceElement(node.type); + registerForUnusedIdentifiersCheck(node); + } + function computeEnumMemberValues(node) { + var nodeLinks = getNodeLinks(node); + if (!(nodeLinks.flags & 16384 /* EnumValuesComputed */)) { + nodeLinks.flags |= 16384 /* EnumValuesComputed */; + var autoValue = 0; + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + var value = computeMemberValue(member, autoValue); + getNodeLinks(member).enumMemberValue = value; + autoValue = typeof value === "number" ? value + 1 : undefined; + } + } + } + function computeMemberValue(member, autoValue) { + if (isComputedNonLiteralName(member.name)) { + error(member.name, ts.Diagnostics.Computed_property_names_are_not_allowed_in_enums); + } + else { + var text = ts.getTextOfPropertyName(member.name); + if (isNumericLiteralName(text) && !isInfinityOrNaNString(text)) { + error(member.name, ts.Diagnostics.An_enum_member_cannot_have_a_numeric_name); + } + } + if (member.initializer) { + return computeConstantValue(member); + } + // In ambient enum declarations that specify no const modifier, enum member declarations that omit + // a value are considered computed members (as opposed to having auto-incremented values). + if (member.parent.flags & 4194304 /* Ambient */ && !ts.isEnumConst(member.parent)) { + return undefined; + } + // If the member declaration specifies no value, the member is considered a constant enum member. + // If the member is the first member in the enum declaration, it is assigned the value zero. + // Otherwise, it is assigned the value of the immediately preceding member plus one, and an error + // occurs if the immediately preceding member is not a constant enum member. + if (autoValue !== undefined) { + return autoValue; + } + error(member.name, ts.Diagnostics.Enum_member_must_have_initializer); + return undefined; + } + function computeConstantValue(member) { + var enumKind = getEnumKind(getSymbolOfNode(member.parent)); + var isConstEnum = ts.isEnumConst(member.parent); + var initializer = member.initializer; + var value = enumKind === 1 /* Literal */ && !isLiteralEnumMember(member) ? undefined : evaluate(initializer); + if (value !== undefined) { + if (isConstEnum && typeof value === "number" && !isFinite(value)) { + error(initializer, isNaN(value) ? + ts.Diagnostics.const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN : + ts.Diagnostics.const_enum_member_initializer_was_evaluated_to_a_non_finite_value); + } + } + else if (enumKind === 1 /* Literal */) { + error(initializer, ts.Diagnostics.Computed_values_are_not_permitted_in_an_enum_with_string_valued_members); + return 0; + } + else if (isConstEnum) { + error(initializer, ts.Diagnostics.In_const_enum_declarations_member_initializer_must_be_constant_expression); + } + else if (member.parent.flags & 4194304 /* Ambient */) { + error(initializer, ts.Diagnostics.In_ambient_enum_declarations_member_initializer_must_be_constant_expression); + } + else { + // Only here do we need to check that the initializer is assignable to the enum type. + checkTypeAssignableTo(checkExpression(initializer), getDeclaredTypeOfSymbol(getSymbolOfNode(member.parent)), initializer, /*headMessage*/ undefined); + } + return value; + function evaluate(expr) { + switch (expr.kind) { + case 202 /* PrefixUnaryExpression */: + var value_2 = evaluate(expr.operand); + if (typeof value_2 === "number") { + switch (expr.operator) { + case 38 /* PlusToken */: return value_2; + case 39 /* MinusToken */: return -value_2; + case 53 /* TildeToken */: return ~value_2; + } + } + break; + case 204 /* BinaryExpression */: + var left = evaluate(expr.left); + var right = evaluate(expr.right); + if (typeof left === "number" && typeof right === "number") { + switch (expr.operatorToken.kind) { + case 50 /* BarToken */: return left | right; + case 49 /* AmpersandToken */: return left & right; + case 47 /* GreaterThanGreaterThanToken */: return left >> right; + case 48 /* GreaterThanGreaterThanGreaterThanToken */: return left >>> right; + case 46 /* LessThanLessThanToken */: return left << right; + case 51 /* CaretToken */: return left ^ right; + case 40 /* AsteriskToken */: return left * right; + case 42 /* SlashToken */: return left / right; + case 38 /* PlusToken */: return left + right; + case 39 /* MinusToken */: return left - right; + case 43 /* PercentToken */: return left % right; + case 41 /* AsteriskAsteriskToken */: return Math.pow(left, right); + } + } + else if (typeof left === "string" && typeof right === "string" && expr.operatorToken.kind === 38 /* PlusToken */) { + return left + right; + } + break; + case 10 /* StringLiteral */: + return expr.text; + case 8 /* NumericLiteral */: + checkGrammarNumericLiteral(expr); + return +expr.text; + case 195 /* ParenthesizedExpression */: + return evaluate(expr.expression); + case 72 /* Identifier */: + var identifier = expr; + if (isInfinityOrNaNString(identifier.escapedText)) { + return +(identifier.escapedText); + } + return ts.nodeIsMissing(expr) ? 0 : evaluateEnumMember(expr, getSymbolOfNode(member.parent), identifier.escapedText); + case 190 /* ElementAccessExpression */: + case 189 /* PropertyAccessExpression */: + var ex = expr; + if (isConstantMemberAccess(ex)) { + var type = getTypeOfExpression(ex.expression); + if (type.symbol && type.symbol.flags & 384 /* Enum */) { + var name = void 0; + if (ex.kind === 189 /* PropertyAccessExpression */) { + name = ex.name.escapedText; + } + else { + var argument = ex.argumentExpression; + ts.Debug.assert(ts.isLiteralExpression(argument)); + name = ts.escapeLeadingUnderscores(argument.text); + } + return evaluateEnumMember(expr, type.symbol, name); + } + } + break; + } + return undefined; + } + function evaluateEnumMember(expr, enumSymbol, name) { + var memberSymbol = enumSymbol.exports.get(name); + if (memberSymbol) { + var declaration = memberSymbol.valueDeclaration; + if (declaration !== member) { + if (isBlockScopedNameDeclaredBeforeUse(declaration, member)) { + return getEnumMemberValue(declaration); + } + error(expr, ts.Diagnostics.A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums); + return 0; + } + } + return undefined; + } + } + function isConstantMemberAccess(node) { + return node.kind === 72 /* Identifier */ || + node.kind === 189 /* PropertyAccessExpression */ && isConstantMemberAccess(node.expression) || + node.kind === 190 /* ElementAccessExpression */ && isConstantMemberAccess(node.expression) && + node.argumentExpression.kind === 10 /* StringLiteral */; + } + function checkEnumDeclaration(node) { + if (!produceDiagnostics) { + return; + } + // Grammar checking + checkGrammarDecoratorsAndModifiers(node); + checkTypeNameIsReserved(node.name, ts.Diagnostics.Enum_name_cannot_be_0); + checkCollisionWithRequireExportsInGeneratedCode(node, node.name); + checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); + checkExportsOnMergedDeclarations(node); + computeEnumMemberValues(node); + var enumIsConst = ts.isEnumConst(node); + if (compilerOptions.isolatedModules && enumIsConst && node.flags & 4194304 /* Ambient */) { + error(node.name, ts.Diagnostics.Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided); + } + // Spec 2014 - Section 9.3: + // It isn't possible for one enum declaration to continue the automatic numbering sequence of another, + // and when an enum type has multiple declarations, only one declaration is permitted to omit a value + // for the first member. + // + // Only perform this check once per symbol + var enumSymbol = getSymbolOfNode(node); + var firstDeclaration = ts.getDeclarationOfKind(enumSymbol, node.kind); + if (node === firstDeclaration) { + if (enumSymbol.declarations.length > 1) { + // check that const is placed\omitted on all enum declarations + ts.forEach(enumSymbol.declarations, function (decl) { + if (ts.isEnumDeclaration(decl) && ts.isEnumConst(decl) !== enumIsConst) { + error(ts.getNameOfDeclaration(decl), ts.Diagnostics.Enum_declarations_must_all_be_const_or_non_const); + } + }); + } + var seenEnumMissingInitialInitializer_1 = false; + ts.forEach(enumSymbol.declarations, function (declaration) { + // return true if we hit a violation of the rule, false otherwise + if (declaration.kind !== 243 /* EnumDeclaration */) { + return false; + } + var enumDeclaration = declaration; + if (!enumDeclaration.members.length) { + return false; + } + var firstEnumMember = enumDeclaration.members[0]; + if (!firstEnumMember.initializer) { + if (seenEnumMissingInitialInitializer_1) { + error(firstEnumMember.name, ts.Diagnostics.In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enum_element); + } + else { + seenEnumMissingInitialInitializer_1 = true; + } + } + }); + } + } + function getFirstNonAmbientClassOrFunctionDeclaration(symbol) { + var declarations = symbol.declarations; + for (var _i = 0, declarations_8 = declarations; _i < declarations_8.length; _i++) { + var declaration = declarations_8[_i]; + if ((declaration.kind === 240 /* ClassDeclaration */ || + (declaration.kind === 239 /* FunctionDeclaration */ && ts.nodeIsPresent(declaration.body))) && + !(declaration.flags & 4194304 /* Ambient */)) { + return declaration; + } + } + return undefined; + } + function inSameLexicalScope(node1, node2) { + var container1 = ts.getEnclosingBlockScopeContainer(node1); + var container2 = ts.getEnclosingBlockScopeContainer(node2); + if (isGlobalSourceFile(container1)) { + return isGlobalSourceFile(container2); + } + else if (isGlobalSourceFile(container2)) { + return false; + } + else { + return container1 === container2; + } + } + function checkModuleDeclaration(node) { + if (produceDiagnostics) { + // Grammar checking + var isGlobalAugmentation = ts.isGlobalScopeAugmentation(node); + var inAmbientContext = node.flags & 4194304 /* Ambient */; + if (isGlobalAugmentation && !inAmbientContext) { + error(node.name, ts.Diagnostics.Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambient_context); + } + var isAmbientExternalModule = ts.isAmbientModule(node); + var contextErrorMessage = isAmbientExternalModule + ? ts.Diagnostics.An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file + : ts.Diagnostics.A_namespace_declaration_is_only_allowed_in_a_namespace_or_module; + if (checkGrammarModuleElementContext(node, contextErrorMessage)) { + // If we hit a module declaration in an illegal context, just bail out to avoid cascading errors. + return; + } + if (!checkGrammarDecoratorsAndModifiers(node)) { + if (!inAmbientContext && node.name.kind === 10 /* StringLiteral */) { + grammarErrorOnNode(node.name, ts.Diagnostics.Only_ambient_modules_can_use_quoted_names); + } + } + if (ts.isIdentifier(node.name)) { + checkCollisionWithRequireExportsInGeneratedCode(node, node.name); + checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); + } + checkExportsOnMergedDeclarations(node); + var symbol = getSymbolOfNode(node); + // The following checks only apply on a non-ambient instantiated module declaration. + if (symbol.flags & 512 /* ValueModule */ + && symbol.declarations.length > 1 + && !inAmbientContext + && isInstantiatedModule(node, !!compilerOptions.preserveConstEnums || !!compilerOptions.isolatedModules)) { + var firstNonAmbientClassOrFunc = getFirstNonAmbientClassOrFunctionDeclaration(symbol); + if (firstNonAmbientClassOrFunc) { + if (ts.getSourceFileOfNode(node) !== ts.getSourceFileOfNode(firstNonAmbientClassOrFunc)) { + error(node.name, ts.Diagnostics.A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merged); + } + else if (node.pos < firstNonAmbientClassOrFunc.pos) { + error(node.name, ts.Diagnostics.A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged); + } + } + // if the module merges with a class declaration in the same lexical scope, + // we need to track this to ensure the correct emit. + var mergedClass = ts.getDeclarationOfKind(symbol, 240 /* ClassDeclaration */); + if (mergedClass && + inSameLexicalScope(node, mergedClass)) { + getNodeLinks(node).flags |= 32768 /* LexicalModuleMergesWithClass */; + } + } + if (isAmbientExternalModule) { + if (ts.isExternalModuleAugmentation(node)) { + // body of the augmentation should be checked for consistency only if augmentation was applied to its target (either global scope or module) + // otherwise we'll be swamped in cascading errors. + // We can detect if augmentation was applied using following rules: + // - augmentation for a global scope is always applied + // - augmentation for some external module is applied if symbol for augmentation is merged (it was combined with target module). + var checkBody = isGlobalAugmentation || (getSymbolOfNode(node).flags & 33554432 /* Transient */); + if (checkBody && node.body) { + for (var _i = 0, _a = node.body.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + checkModuleAugmentationElement(statement, isGlobalAugmentation); + } + } + } + else if (isGlobalSourceFile(node.parent)) { + if (isGlobalAugmentation) { + error(node.name, ts.Diagnostics.Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_declarations); + } + else if (ts.isExternalModuleNameRelative(ts.getTextOfIdentifierOrLiteral(node.name))) { + error(node.name, ts.Diagnostics.Ambient_module_declaration_cannot_specify_relative_module_name); + } + } + else { + if (isGlobalAugmentation) { + error(node.name, ts.Diagnostics.Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_declarations); + } + else { + // Node is not an augmentation and is not located on the script level. + // This means that this is declaration of ambient module that is located in other module or namespace which is prohibited. + error(node.name, ts.Diagnostics.Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces); + } + } + } + } + if (node.body) { + checkSourceElement(node.body); + if (!ts.isGlobalScopeAugmentation(node)) { + registerForUnusedIdentifiersCheck(node); + } + } + } + function checkModuleAugmentationElement(node, isGlobalAugmentation) { + switch (node.kind) { + case 219 /* VariableStatement */: + // error each individual name in variable statement instead of marking the entire variable statement + for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + checkModuleAugmentationElement(decl, isGlobalAugmentation); + } + break; + case 254 /* ExportAssignment */: + case 255 /* ExportDeclaration */: + grammarErrorOnFirstToken(node, ts.Diagnostics.Exports_and_export_assignments_are_not_permitted_in_module_augmentations); + break; + case 248 /* ImportEqualsDeclaration */: + case 249 /* ImportDeclaration */: + grammarErrorOnFirstToken(node, ts.Diagnostics.Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_module); + break; + case 186 /* BindingElement */: + case 237 /* VariableDeclaration */: + var name = node.name; + if (ts.isBindingPattern(name)) { + for (var _b = 0, _c = name.elements; _b < _c.length; _b++) { + var el = _c[_b]; + // mark individual names in binding pattern + checkModuleAugmentationElement(el, isGlobalAugmentation); + } + break; + } + // falls through + case 240 /* ClassDeclaration */: + case 243 /* EnumDeclaration */: + case 239 /* FunctionDeclaration */: + case 241 /* InterfaceDeclaration */: + case 244 /* ModuleDeclaration */: + case 242 /* TypeAliasDeclaration */: + if (isGlobalAugmentation) { + return; + } + var symbol = getSymbolOfNode(node); + if (symbol) { + // module augmentations cannot introduce new names on the top level scope of the module + // this is done it two steps + // 1. quick check - if symbol for node is not merged - this is local symbol to this augmentation - report error + // 2. main check - report error if value declaration of the parent symbol is module augmentation) + var reportError = !(symbol.flags & 33554432 /* Transient */); + if (!reportError) { + // symbol should not originate in augmentation + reportError = !!symbol.parent && ts.isExternalModuleAugmentation(symbol.parent.declarations[0]); + } + } + break; + } + } + function getFirstIdentifier(node) { + switch (node.kind) { + case 72 /* Identifier */: + return node; + case 148 /* QualifiedName */: + do { + node = node.left; + } while (node.kind !== 72 /* Identifier */); + return node; + case 189 /* PropertyAccessExpression */: + do { + node = node.expression; + } while (node.kind !== 72 /* Identifier */); + return node; + } + } + function checkExternalImportOrExportDeclaration(node) { + var moduleName = ts.getExternalModuleName(node); + if (!moduleName || ts.nodeIsMissing(moduleName)) { + // Should be a parse error. + return false; + } + if (!ts.isStringLiteral(moduleName)) { + error(moduleName, ts.Diagnostics.String_literal_expected); + return false; + } + var inAmbientExternalModule = node.parent.kind === 245 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent); + if (node.parent.kind !== 279 /* SourceFile */ && !inAmbientExternalModule) { + error(moduleName, node.kind === 255 /* ExportDeclaration */ ? + ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace : + ts.Diagnostics.Import_declarations_in_a_namespace_cannot_reference_a_module); + return false; + } + if (inAmbientExternalModule && ts.isExternalModuleNameRelative(moduleName.text)) { + // we have already reported errors on top level imports\exports in external module augmentations in checkModuleDeclaration + // no need to do this again. + if (!isTopLevelInExternalModuleAugmentation(node)) { + // TypeScript 1.0 spec (April 2013): 12.1.6 + // An ExternalImportDeclaration in an AmbientExternalModuleDeclaration may reference + // other external modules only through top - level external module names. + // Relative external module names are not permitted. + error(node, ts.Diagnostics.Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relative_module_name); + return false; + } + } + return true; + } + function checkAliasSymbol(node) { + var symbol = getSymbolOfNode(node); + var target = resolveAlias(symbol); + if (target !== unknownSymbol) { + // For external modules symbol represent local symbol for an alias. + // This local symbol will merge any other local declarations (excluding other aliases) + // and symbol.flags will contains combined representation for all merged declaration. + // Based on symbol.flags we can compute a set of excluded meanings (meaning that resolved alias should not have, + // otherwise it will conflict with some local declaration). Note that in addition to normal flags we include matching SymbolFlags.Export* + // in order to prevent collisions with declarations that were exported from the current module (they still contribute to local names). + var excludedMeanings = (symbol.flags & (67220415 /* Value */ | 1048576 /* ExportValue */) ? 67220415 /* Value */ : 0) | + (symbol.flags & 67897832 /* Type */ ? 67897832 /* Type */ : 0) | + (symbol.flags & 1920 /* Namespace */ ? 1920 /* Namespace */ : 0); + if (target.flags & excludedMeanings) { + var message = node.kind === 257 /* ExportSpecifier */ ? + ts.Diagnostics.Export_declaration_conflicts_with_exported_declaration_of_0 : + ts.Diagnostics.Import_declaration_conflicts_with_local_declaration_of_0; + error(node, message, symbolToString(symbol)); + } + // Don't allow to re-export something with no value side when `--isolatedModules` is set. + if (compilerOptions.isolatedModules + && node.kind === 257 /* ExportSpecifier */ + && !(target.flags & 67220415 /* Value */) + && !(node.flags & 4194304 /* Ambient */)) { + error(node, ts.Diagnostics.Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided); + } + } + } + function checkImportBinding(node) { + checkCollisionWithRequireExportsInGeneratedCode(node, node.name); + checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); + checkAliasSymbol(node); + } + function checkImportDeclaration(node) { + if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_import_declaration_can_only_be_used_in_a_namespace_or_module)) { + // If we hit an import declaration in an illegal context, just bail out to avoid cascading errors. + return; + } + if (!checkGrammarDecoratorsAndModifiers(node) && ts.hasModifiers(node)) { + grammarErrorOnFirstToken(node, ts.Diagnostics.An_import_declaration_cannot_have_modifiers); + } + if (checkExternalImportOrExportDeclaration(node)) { + var importClause = node.importClause; + if (importClause) { + if (importClause.name) { + checkImportBinding(importClause); + } + if (importClause.namedBindings) { + if (importClause.namedBindings.kind === 251 /* NamespaceImport */) { + checkImportBinding(importClause.namedBindings); + } + else { + var moduleExisted = resolveExternalModuleName(node, node.moduleSpecifier); + if (moduleExisted) { + ts.forEach(importClause.namedBindings.elements, checkImportBinding); + } + } + } + } + } + } + function checkImportEqualsDeclaration(node) { + if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_import_declaration_can_only_be_used_in_a_namespace_or_module)) { + // If we hit an import declaration in an illegal context, just bail out to avoid cascading errors. + return; + } + checkGrammarDecoratorsAndModifiers(node); + if (ts.isInternalModuleImportEqualsDeclaration(node) || checkExternalImportOrExportDeclaration(node)) { + checkImportBinding(node); + if (ts.hasModifier(node, 1 /* Export */)) { + markExportAsReferenced(node); + } + if (node.moduleReference.kind !== 259 /* ExternalModuleReference */) { + var target = resolveAlias(getSymbolOfNode(node)); + if (target !== unknownSymbol) { + if (target.flags & 67220415 /* Value */) { + // Target is a value symbol, check that it is not hidden by a local declaration with the same name + var moduleName = getFirstIdentifier(node.moduleReference); + if (!(resolveEntityName(moduleName, 67220415 /* Value */ | 1920 /* Namespace */).flags & 1920 /* Namespace */)) { + error(moduleName, ts.Diagnostics.Module_0_is_hidden_by_a_local_declaration_with_the_same_name, ts.declarationNameToString(moduleName)); + } + } + if (target.flags & 67897832 /* Type */) { + checkTypeNameIsReserved(node.name, ts.Diagnostics.Import_name_cannot_be_0); + } + } + } + else { + if (moduleKind >= ts.ModuleKind.ES2015 && !(node.flags & 4194304 /* Ambient */)) { + // Import equals declaration is deprecated in es6 or above + grammarErrorOnNode(node, ts.Diagnostics.Import_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_import_Asterisk_as_ns_from_mod_import_a_from_mod_import_d_from_mod_or_another_module_format_instead); + } + } + } + } + function checkExportDeclaration(node) { + if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_export_declaration_can_only_be_used_in_a_module)) { + // If we hit an export in an illegal context, just bail out to avoid cascading errors. + return; + } + if (!checkGrammarDecoratorsAndModifiers(node) && ts.hasModifiers(node)) { + grammarErrorOnFirstToken(node, ts.Diagnostics.An_export_declaration_cannot_have_modifiers); + } + if (!node.moduleSpecifier || checkExternalImportOrExportDeclaration(node)) { + if (node.exportClause) { + // export { x, y } + // export { x, y } from "foo" + ts.forEach(node.exportClause.elements, checkExportSpecifier); + var inAmbientExternalModule = node.parent.kind === 245 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent); + var inAmbientNamespaceDeclaration = !inAmbientExternalModule && node.parent.kind === 245 /* ModuleBlock */ && + !node.moduleSpecifier && node.flags & 4194304 /* Ambient */; + if (node.parent.kind !== 279 /* SourceFile */ && !inAmbientExternalModule && !inAmbientNamespaceDeclaration) { + error(node, ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace); + } + } + else { + // export * from "foo" + var moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier); + if (moduleSymbol && hasExportAssignmentSymbol(moduleSymbol)) { + error(node.moduleSpecifier, ts.Diagnostics.Module_0_uses_export_and_cannot_be_used_with_export_Asterisk, symbolToString(moduleSymbol)); + } + if (moduleKind !== ts.ModuleKind.System && moduleKind !== ts.ModuleKind.ES2015 && moduleKind !== ts.ModuleKind.ESNext) { + checkExternalEmitHelpers(node, 32768 /* ExportStar */); + } + } + } + } + function checkGrammarModuleElementContext(node, errorMessage) { + var isInAppropriateContext = node.parent.kind === 279 /* SourceFile */ || node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 244 /* ModuleDeclaration */; + if (!isInAppropriateContext) { + grammarErrorOnFirstToken(node, errorMessage); + } + return !isInAppropriateContext; + } + function checkExportSpecifier(node) { + checkAliasSymbol(node); + if (ts.getEmitDeclarations(compilerOptions)) { + collectLinkedAliases(node.propertyName || node.name, /*setVisibility*/ true); + } + if (!node.parent.parent.moduleSpecifier) { + var exportedName = node.propertyName || node.name; + // find immediate value referenced by exported name (SymbolFlags.Alias is set so we don't chase down aliases) + var symbol = resolveName(exportedName, exportedName.escapedText, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, + /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); + if (symbol && (symbol === undefinedSymbol || isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { + error(exportedName, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, ts.idText(exportedName)); + } + else { + markExportAsReferenced(node); + } + } + } + function checkExportAssignment(node) { + if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_export_assignment_can_only_be_used_in_a_module)) { + // If we hit an export assignment in an illegal context, just bail out to avoid cascading errors. + return; + } + var container = node.parent.kind === 279 /* SourceFile */ ? node.parent : node.parent.parent; + if (container.kind === 244 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) { + if (node.isExportEquals) { + error(node, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_namespace); + } + else { + error(node, ts.Diagnostics.A_default_export_can_only_be_used_in_an_ECMAScript_style_module); + } + return; + } + // Grammar checking + if (!checkGrammarDecoratorsAndModifiers(node) && ts.hasModifiers(node)) { + grammarErrorOnFirstToken(node, ts.Diagnostics.An_export_assignment_cannot_have_modifiers); + } + if (node.expression.kind === 72 /* Identifier */) { + markExportAsReferenced(node); + if (ts.getEmitDeclarations(compilerOptions)) { + collectLinkedAliases(node.expression, /*setVisibility*/ true); + } + } + else { + checkExpressionCached(node.expression); + } + checkExternalModuleExports(container); + if ((node.flags & 4194304 /* Ambient */) && !ts.isEntityNameExpression(node.expression)) { + grammarErrorOnNode(node.expression, ts.Diagnostics.The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context); + } + if (node.isExportEquals && !(node.flags & 4194304 /* Ambient */)) { + if (moduleKind >= ts.ModuleKind.ES2015) { + // export assignment is not supported in es6 modules + grammarErrorOnNode(node, ts.Diagnostics.Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or_another_module_format_instead); + } + else if (moduleKind === ts.ModuleKind.System) { + // system modules does not support export assignment + grammarErrorOnNode(node, ts.Diagnostics.Export_assignment_is_not_supported_when_module_flag_is_system); + } + } + } + function hasExportedMembers(moduleSymbol) { + return ts.forEachEntry(moduleSymbol.exports, function (_, id) { return id !== "export="; }); + } + function checkExternalModuleExports(node) { + var moduleSymbol = getSymbolOfNode(node); + var links = getSymbolLinks(moduleSymbol); + if (!links.exportsChecked) { + var exportEqualsSymbol = moduleSymbol.exports.get("export="); + if (exportEqualsSymbol && hasExportedMembers(moduleSymbol)) { + var declaration = getDeclarationOfAliasSymbol(exportEqualsSymbol) || exportEqualsSymbol.valueDeclaration; + if (!isTopLevelInExternalModuleAugmentation(declaration) && !ts.isInJSFile(declaration)) { + error(declaration, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements); + } + } + // Checks for export * conflicts + var exports_1 = getExportsOfModule(moduleSymbol); + if (exports_1) { + exports_1.forEach(function (_a, id) { + var declarations = _a.declarations, flags = _a.flags; + if (id === "__export") { + return; + } + // ECMA262: 15.2.1.1 It is a Syntax Error if the ExportedNames of ModuleItemList contains any duplicate entries. + // (TS Exceptions: namespaces, function overloads, enums, and interfaces) + if (flags & (1920 /* Namespace */ | 64 /* Interface */ | 384 /* Enum */)) { + return; + } + var exportedDeclarationsCount = ts.countWhere(declarations, isNotOverloadAndNotAccessor); + if (flags & 524288 /* TypeAlias */ && exportedDeclarationsCount <= 2) { + // it is legal to merge type alias with other values + // so count should be either 1 (just type alias) or 2 (type alias + merged value) + return; + } + if (exportedDeclarationsCount > 1) { + for (var _i = 0, declarations_9 = declarations; _i < declarations_9.length; _i++) { + var declaration = declarations_9[_i]; + if (isNotOverload(declaration)) { + diagnostics.add(ts.createDiagnosticForNode(declaration, ts.Diagnostics.Cannot_redeclare_exported_variable_0, ts.unescapeLeadingUnderscores(id))); + } + } + } + }); + } + links.exportsChecked = true; + } + } + function isNotAccessor(declaration) { + // Accessors check for their own matching duplicates, and in contexts where they are valid, there are already duplicate identifier checks + return !ts.isAccessor(declaration); + } + function isNotOverload(declaration) { + return (declaration.kind !== 239 /* FunctionDeclaration */ && declaration.kind !== 156 /* MethodDeclaration */) || + !!declaration.body; + } + function checkSourceElement(node) { + if (!node) { + return; + } + if (ts.isInJSFile(node)) { + ts.forEach(node.jsDoc, function (_a) { + var tags = _a.tags; + return ts.forEach(tags, checkSourceElement); + }); + } + var kind = node.kind; + if (cancellationToken) { + // Only bother checking on a few construct kinds. We don't want to be excessively + // hitting the cancellation token on every node we check. + switch (kind) { + case 244 /* ModuleDeclaration */: + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + case 239 /* FunctionDeclaration */: + cancellationToken.throwIfCancellationRequested(); + } + } + switch (kind) { + case 150 /* TypeParameter */: + return checkTypeParameter(node); + case 151 /* Parameter */: + return checkParameter(node); + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + return checkPropertyDeclaration(node); + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 162 /* IndexSignature */: + return checkSignatureDeclaration(node); + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + return checkMethodDeclaration(node); + case 157 /* Constructor */: + return checkConstructorDeclaration(node); + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + return checkAccessorDeclaration(node); + case 164 /* TypeReference */: + return checkTypeReferenceNode(node); + case 163 /* TypePredicate */: + return checkTypePredicate(node); + case 167 /* TypeQuery */: + return checkTypeQuery(node); + case 168 /* TypeLiteral */: + return checkTypeLiteral(node); + case 169 /* ArrayType */: + return checkArrayType(node); + case 170 /* TupleType */: + return checkTupleType(node); + case 173 /* UnionType */: + case 174 /* IntersectionType */: + return checkUnionOrIntersectionType(node); + case 177 /* ParenthesizedType */: + case 171 /* OptionalType */: + case 172 /* RestType */: + return checkSourceElement(node.type); + case 178 /* ThisType */: + return checkThisType(node); + case 179 /* TypeOperator */: + return checkTypeOperator(node); + case 175 /* ConditionalType */: + return checkConditionalType(node); + case 176 /* InferType */: + return checkInferType(node); + case 183 /* ImportType */: + return checkImportType(node); + case 295 /* JSDocAugmentsTag */: + return checkJSDocAugmentsTag(node); + case 304 /* JSDocTypedefTag */: + case 297 /* JSDocCallbackTag */: + return checkJSDocTypeAliasTag(node); + case 303 /* JSDocTemplateTag */: + return checkJSDocTemplateTag(node); + case 302 /* JSDocTypeTag */: + return checkJSDocTypeTag(node); + case 299 /* JSDocParameterTag */: + return checkJSDocParameterTag(node); + case 289 /* JSDocFunctionType */: + checkJSDocFunctionType(node); + // falls through + case 287 /* JSDocNonNullableType */: + case 286 /* JSDocNullableType */: + case 284 /* JSDocAllType */: + case 285 /* JSDocUnknownType */: + case 292 /* JSDocTypeLiteral */: + checkJSDocTypeIsInJsFile(node); + ts.forEachChild(node, checkSourceElement); + return; + case 290 /* JSDocVariadicType */: + checkJSDocVariadicType(node); + return; + case 283 /* JSDocTypeExpression */: + return checkSourceElement(node.type); + case 180 /* IndexedAccessType */: + return checkIndexedAccessType(node); + case 181 /* MappedType */: + return checkMappedType(node); + case 239 /* FunctionDeclaration */: + return checkFunctionDeclaration(node); + case 218 /* Block */: + case 245 /* ModuleBlock */: + return checkBlock(node); + case 219 /* VariableStatement */: + return checkVariableStatement(node); + case 221 /* ExpressionStatement */: + return checkExpressionStatement(node); + case 222 /* IfStatement */: + return checkIfStatement(node); + case 223 /* DoStatement */: + return checkDoStatement(node); + case 224 /* WhileStatement */: + return checkWhileStatement(node); + case 225 /* ForStatement */: + return checkForStatement(node); + case 226 /* ForInStatement */: + return checkForInStatement(node); + case 227 /* ForOfStatement */: + return checkForOfStatement(node); + case 228 /* ContinueStatement */: + case 229 /* BreakStatement */: + return checkBreakOrContinueStatement(node); + case 230 /* ReturnStatement */: + return checkReturnStatement(node); + case 231 /* WithStatement */: + return checkWithStatement(node); + case 232 /* SwitchStatement */: + return checkSwitchStatement(node); + case 233 /* LabeledStatement */: + return checkLabeledStatement(node); + case 234 /* ThrowStatement */: + return checkThrowStatement(node); + case 235 /* TryStatement */: + return checkTryStatement(node); + case 237 /* VariableDeclaration */: + return checkVariableDeclaration(node); + case 186 /* BindingElement */: + return checkBindingElement(node); + case 240 /* ClassDeclaration */: + return checkClassDeclaration(node); + case 241 /* InterfaceDeclaration */: + return checkInterfaceDeclaration(node); + case 242 /* TypeAliasDeclaration */: + return checkTypeAliasDeclaration(node); + case 243 /* EnumDeclaration */: + return checkEnumDeclaration(node); + case 244 /* ModuleDeclaration */: + return checkModuleDeclaration(node); + case 249 /* ImportDeclaration */: + return checkImportDeclaration(node); + case 248 /* ImportEqualsDeclaration */: + return checkImportEqualsDeclaration(node); + case 255 /* ExportDeclaration */: + return checkExportDeclaration(node); + case 254 /* ExportAssignment */: + return checkExportAssignment(node); + case 220 /* EmptyStatement */: + case 236 /* DebuggerStatement */: + checkGrammarStatementInAmbientContext(node); + return; + case 258 /* MissingDeclaration */: + return checkMissingDeclaration(node); + } + } + function checkJSDocTypeIsInJsFile(node) { + if (!ts.isInJSFile(node)) { + grammarErrorOnNode(node, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments); + } + } + function checkJSDocVariadicType(node) { + checkJSDocTypeIsInJsFile(node); + checkSourceElement(node.type); + // Only legal location is in the *last* parameter tag or last parameter of a JSDoc function. + var parent = node.parent; + if (ts.isParameter(parent) && ts.isJSDocFunctionType(parent.parent)) { + if (ts.last(parent.parent.parameters) !== parent) { + error(node, ts.Diagnostics.A_rest_parameter_must_be_last_in_a_parameter_list); + } + return; + } + if (!ts.isJSDocTypeExpression(parent)) { + error(node, ts.Diagnostics.JSDoc_may_only_appear_in_the_last_parameter_of_a_signature); + } + var paramTag = node.parent.parent; + if (!ts.isJSDocParameterTag(paramTag)) { + error(node, ts.Diagnostics.JSDoc_may_only_appear_in_the_last_parameter_of_a_signature); + return; + } + var param = ts.getParameterSymbolFromJSDoc(paramTag); + if (!param) { + // We will error in `checkJSDocParameterTag`. + return; + } + var host = ts.getHostSignatureFromJSDoc(paramTag); + if (!host || ts.last(host.parameters).symbol !== param) { + error(node, ts.Diagnostics.A_rest_parameter_must_be_last_in_a_parameter_list); + } + } + function getTypeFromJSDocVariadicType(node) { + var type = getTypeFromTypeNode(node.type); + var parent = node.parent; + var paramTag = node.parent.parent; + if (ts.isJSDocTypeExpression(node.parent) && ts.isJSDocParameterTag(paramTag)) { + // Else we will add a diagnostic, see `checkJSDocVariadicType`. + var host_1 = ts.getHostSignatureFromJSDoc(paramTag); + if (host_1) { + /* + Only return an array type if the corresponding parameter is marked as a rest parameter, or if there are no parameters. + So in the following situation we will not create an array type: + /** @param {...number} a * / + function f(a) {} + Because `a` will just be of type `number | undefined`. A synthetic `...args` will also be added, which *will* get an array type. + */ + var lastParamDeclaration = ts.lastOrUndefined(host_1.parameters); + var symbol = ts.getParameterSymbolFromJSDoc(paramTag); + if (!lastParamDeclaration || + symbol && lastParamDeclaration.symbol === symbol && ts.isRestParameter(lastParamDeclaration)) { + return createArrayType(type); + } + } + } + if (ts.isParameter(parent) && ts.isJSDocFunctionType(parent.parent)) { + return createArrayType(type); + } + return addOptionality(type); + } + // Function and class expression bodies are checked after all statements in the enclosing body. This is + // to ensure constructs like the following are permitted: + // const foo = function () { + // const s = foo(); + // return "hello"; + // } + // Here, performing a full type check of the body of the function expression whilst in the process of + // determining the type of foo would cause foo to be given type any because of the recursive reference. + // Delaying the type check of the body ensures foo has been assigned a type. + function checkNodeDeferred(node) { + var enclosingFile = ts.getSourceFileOfNode(node); + var links = getNodeLinks(enclosingFile); + if (!(links.flags & 1 /* TypeChecked */)) { + links.deferredNodes = links.deferredNodes || ts.createMap(); + var id = "" + getNodeId(node); + links.deferredNodes.set(id, node); + } + } + function checkDeferredNodes(context) { + var links = getNodeLinks(context); + if (!links.deferredNodes) { + return; + } + links.deferredNodes.forEach(function (node) { + switch (node.kind) { + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + checkFunctionExpressionOrObjectLiteralMethodDeferred(node); + break; + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + checkAccessorDeclaration(node); + break; + case 209 /* ClassExpression */: + checkClassExpressionDeferred(node); + break; + case 261 /* JsxSelfClosingElement */: + checkJsxSelfClosingElementDeferred(node); + break; + case 260 /* JsxElement */: + checkJsxElementDeferred(node); + break; + } + }); + } + function checkSourceFile(node) { + ts.performance.mark("beforeCheck"); + checkSourceFileWorker(node); + ts.performance.mark("afterCheck"); + ts.performance.measure("Check", "beforeCheck", "afterCheck"); + } + function unusedIsError(kind) { + switch (kind) { + case 0 /* Local */: + return !!compilerOptions.noUnusedLocals; + case 1 /* Parameter */: + return !!compilerOptions.noUnusedParameters; + default: + return ts.Debug.assertNever(kind); + } + } + function getPotentiallyUnusedIdentifiers(sourceFile) { + return allPotentiallyUnusedIdentifiers.get(sourceFile.path) || ts.emptyArray; + } + // Fully type check a source file and collect the relevant diagnostics. + function checkSourceFileWorker(node) { + var links = getNodeLinks(node); + if (!(links.flags & 1 /* TypeChecked */)) { + if (ts.skipTypeChecking(node, compilerOptions)) { + return; + } + // Grammar checking + checkGrammarSourceFile(node); + ts.clear(potentialThisCollisions); + ts.clear(potentialNewTargetCollisions); + ts.forEach(node.statements, checkSourceElement); + checkSourceElement(node.endOfFileToken); + checkDeferredNodes(node); + if (ts.isExternalOrCommonJsModule(node)) { + registerForUnusedIdentifiersCheck(node); + } + if (!node.isDeclarationFile && (compilerOptions.noUnusedLocals || compilerOptions.noUnusedParameters)) { + checkUnusedIdentifiers(getPotentiallyUnusedIdentifiers(node), function (containingNode, kind, diag) { + if (!ts.containsParseError(containingNode) && unusedIsError(kind)) { + diagnostics.add(diag); + } + }); + } + if (ts.isExternalOrCommonJsModule(node)) { + checkExternalModuleExports(node); + } + if (potentialThisCollisions.length) { + ts.forEach(potentialThisCollisions, checkIfThisIsCapturedInEnclosingScope); + ts.clear(potentialThisCollisions); + } + if (potentialNewTargetCollisions.length) { + ts.forEach(potentialNewTargetCollisions, checkIfNewTargetIsCapturedInEnclosingScope); + ts.clear(potentialNewTargetCollisions); + } + links.flags |= 1 /* TypeChecked */; + } + } + function getDiagnostics(sourceFile, ct) { + try { + // Record the cancellation token so it can be checked later on during checkSourceElement. + // Do this in a finally block so we can ensure that it gets reset back to nothing after + // this call is done. + cancellationToken = ct; + return getDiagnosticsWorker(sourceFile); + } + finally { + cancellationToken = undefined; + } + } + function getDiagnosticsWorker(sourceFile) { + throwIfNonDiagnosticsProducing(); + if (sourceFile) { + // Some global diagnostics are deferred until they are needed and + // may not be reported in the firt call to getGlobalDiagnostics. + // We should catch these changes and report them. + var previousGlobalDiagnostics = diagnostics.getGlobalDiagnostics(); + var previousGlobalDiagnosticsSize = previousGlobalDiagnostics.length; + checkSourceFile(sourceFile); + var semanticDiagnostics = diagnostics.getDiagnostics(sourceFile.fileName); + var currentGlobalDiagnostics = diagnostics.getGlobalDiagnostics(); + if (currentGlobalDiagnostics !== previousGlobalDiagnostics) { + // If the arrays are not the same reference, new diagnostics were added. + var deferredGlobalDiagnostics = ts.relativeComplement(previousGlobalDiagnostics, currentGlobalDiagnostics, ts.compareDiagnostics); + return ts.concatenate(deferredGlobalDiagnostics, semanticDiagnostics); + } + else if (previousGlobalDiagnosticsSize === 0 && currentGlobalDiagnostics.length > 0) { + // If the arrays are the same reference, but the length has changed, a single + // new diagnostic was added as DiagnosticCollection attempts to reuse the + // same array. + return ts.concatenate(currentGlobalDiagnostics, semanticDiagnostics); + } + return semanticDiagnostics; + } + // Global diagnostics are always added when a file is not provided to + // getDiagnostics + ts.forEach(host.getSourceFiles(), checkSourceFile); + return diagnostics.getDiagnostics(); + } + function getGlobalDiagnostics() { + throwIfNonDiagnosticsProducing(); + return diagnostics.getGlobalDiagnostics(); + } + function throwIfNonDiagnosticsProducing() { + if (!produceDiagnostics) { + throw new Error("Trying to get diagnostics from a type checker that does not produce them."); + } + } + // Language service support + function getSymbolsInScope(location, meaning) { + if (location.flags & 8388608 /* InWithStatement */) { + // We cannot answer semantic questions within a with block, do not proceed any further + return []; + } + var symbols = ts.createSymbolTable(); + var isStatic = false; + populateSymbols(); + symbols.delete("this" /* This */); // Not a symbol, a keyword + return symbolsToArray(symbols); + function populateSymbols() { + while (location) { + if (location.locals && !isGlobalSourceFile(location)) { + copySymbols(location.locals, meaning); + } + switch (location.kind) { + case 279 /* SourceFile */: + if (!ts.isExternalOrCommonJsModule(location)) + break; + // falls through + case 244 /* ModuleDeclaration */: + copySymbols(getSymbolOfNode(location).exports, meaning & 2623475 /* ModuleMember */); + break; + case 243 /* EnumDeclaration */: + copySymbols(getSymbolOfNode(location).exports, meaning & 8 /* EnumMember */); + break; + case 209 /* ClassExpression */: + var className = location.name; + if (className) { + copySymbol(location.symbol, meaning); + } + // falls through + // this fall-through is necessary because we would like to handle + // type parameter inside class expression similar to how we handle it in classDeclaration and interface Declaration + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + // If we didn't come from static member of class or interface, + // add the type parameters into the symbol table + // (type parameters of classDeclaration/classExpression and interface are in member property of the symbol. + // Note: that the memberFlags come from previous iteration. + if (!isStatic) { + copySymbols(getMembersOfSymbol(getSymbolOfNode(location)), meaning & 67897832 /* Type */); + } + break; + case 196 /* FunctionExpression */: + var funcName = location.name; + if (funcName) { + copySymbol(location.symbol, meaning); + } + break; + } + if (ts.introducesArgumentsExoticObject(location)) { + copySymbol(argumentsSymbol, meaning); + } + isStatic = ts.hasModifier(location, 32 /* Static */); + location = location.parent; + } + copySymbols(globals, meaning); + } + /** + * Copy the given symbol into symbol tables if the symbol has the given meaning + * and it doesn't already existed in the symbol table + * @param key a key for storing in symbol table; if undefined, use symbol.name + * @param symbol the symbol to be added into symbol table + * @param meaning meaning of symbol to filter by before adding to symbol table + */ + function copySymbol(symbol, meaning) { + if (ts.getCombinedLocalAndExportSymbolFlags(symbol) & meaning) { + var id = symbol.escapedName; + // We will copy all symbol regardless of its reserved name because + // symbolsToArray will check whether the key is a reserved name and + // it will not copy symbol with reserved name to the array + if (!symbols.has(id)) { + symbols.set(id, symbol); + } + } + } + function copySymbols(source, meaning) { + if (meaning) { + source.forEach(function (symbol) { + copySymbol(symbol, meaning); + }); + } + } + } + function isTypeDeclarationName(name) { + return name.kind === 72 /* Identifier */ && + isTypeDeclaration(name.parent) && + name.parent.name === name; + } + function isTypeDeclaration(node) { + switch (node.kind) { + case 150 /* TypeParameter */: + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 243 /* EnumDeclaration */: + return true; + default: + return false; + } + } + // True if the given identifier is part of a type reference + function isTypeReferenceIdentifier(node) { + while (node.parent.kind === 148 /* QualifiedName */) { + node = node.parent; + } + return node.parent.kind === 164 /* TypeReference */; + } + function isHeritageClauseElementIdentifier(node) { + while (node.parent.kind === 189 /* PropertyAccessExpression */) { + node = node.parent; + } + return node.parent.kind === 211 /* ExpressionWithTypeArguments */; + } + function forEachEnclosingClass(node, callback) { + var result; + while (true) { + node = ts.getContainingClass(node); + if (!node) + break; + if (result = callback(node)) + break; + } + return result; + } + function isNodeUsedDuringClassInitialization(node) { + return !!ts.findAncestor(node, function (element) { + if (ts.isConstructorDeclaration(element) && ts.nodeIsPresent(element.body) || ts.isPropertyDeclaration(element)) { + return true; + } + else if (ts.isClassLike(element) || ts.isFunctionLikeDeclaration(element)) { + return "quit"; + } + return false; + }); + } + function isNodeWithinClass(node, classDeclaration) { + return !!forEachEnclosingClass(node, function (n) { return n === classDeclaration; }); + } + function getLeftSideOfImportEqualsOrExportAssignment(nodeOnRightSide) { + while (nodeOnRightSide.parent.kind === 148 /* QualifiedName */) { + nodeOnRightSide = nodeOnRightSide.parent; + } + if (nodeOnRightSide.parent.kind === 248 /* ImportEqualsDeclaration */) { + return nodeOnRightSide.parent.moduleReference === nodeOnRightSide ? nodeOnRightSide.parent : undefined; + } + if (nodeOnRightSide.parent.kind === 254 /* ExportAssignment */) { + return nodeOnRightSide.parent.expression === nodeOnRightSide ? nodeOnRightSide.parent : undefined; + } + return undefined; + } + function isInRightSideOfImportOrExportAssignment(node) { + return getLeftSideOfImportEqualsOrExportAssignment(node) !== undefined; + } + function getSpecialPropertyAssignmentSymbolFromEntityName(entityName) { + var specialPropertyAssignmentKind = ts.getAssignmentDeclarationKind(entityName.parent.parent); + switch (specialPropertyAssignmentKind) { + case 1 /* ExportsProperty */: + case 3 /* PrototypeProperty */: + return getSymbolOfNode(entityName.parent); + case 4 /* ThisProperty */: + case 2 /* ModuleExports */: + case 5 /* Property */: + return getSymbolOfNode(entityName.parent.parent); + } + } + function isImportTypeQualifierPart(node) { + var parent = node.parent; + while (ts.isQualifiedName(parent)) { + node = parent; + parent = parent.parent; + } + if (parent && parent.kind === 183 /* ImportType */ && parent.qualifier === node) { + return parent; + } + return undefined; + } + function getSymbolOfEntityNameOrPropertyAccessExpression(entityName) { + if (ts.isDeclarationName(entityName)) { + return getSymbolOfNode(entityName.parent); + } + if (ts.isInJSFile(entityName) && + entityName.parent.kind === 189 /* PropertyAccessExpression */ && + entityName.parent === entityName.parent.parent.left) { + // Check if this is a special property assignment + var specialPropertyAssignmentSymbol = getSpecialPropertyAssignmentSymbolFromEntityName(entityName); + if (specialPropertyAssignmentSymbol) { + return specialPropertyAssignmentSymbol; + } + } + if (entityName.parent.kind === 254 /* ExportAssignment */ && ts.isEntityNameExpression(entityName)) { + // Even an entity name expression that doesn't resolve as an entityname may still typecheck as a property access expression + var success = resolveEntityName(entityName, + /*all meanings*/ 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*ignoreErrors*/ true); + if (success && success !== unknownSymbol) { + return success; + } + } + else if (!ts.isPropertyAccessExpression(entityName) && isInRightSideOfImportOrExportAssignment(entityName)) { + // Since we already checked for ExportAssignment, this really could only be an Import + var importEqualsDeclaration = ts.getAncestor(entityName, 248 /* ImportEqualsDeclaration */); + ts.Debug.assert(importEqualsDeclaration !== undefined); + return getSymbolOfPartOfRightHandSideOfImportEquals(entityName, /*dontResolveAlias*/ true); + } + if (!ts.isPropertyAccessExpression(entityName)) { + var possibleImportNode = isImportTypeQualifierPart(entityName); + if (possibleImportNode) { + getTypeFromTypeNode(possibleImportNode); + var sym = getNodeLinks(entityName).resolvedSymbol; + return sym === unknownSymbol ? undefined : sym; + } + } + while (ts.isRightSideOfQualifiedNameOrPropertyAccess(entityName)) { + entityName = entityName.parent; + } + if (isHeritageClauseElementIdentifier(entityName)) { + var meaning = 0 /* None */; + // In an interface or class, we're definitely interested in a type. + if (entityName.parent.kind === 211 /* ExpressionWithTypeArguments */) { + meaning = 67897832 /* Type */; + // In a class 'extends' clause we are also looking for a value. + if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent)) { + meaning |= 67220415 /* Value */; + } + } + else { + meaning = 1920 /* Namespace */; + } + meaning |= 2097152 /* Alias */; + var entityNameSymbol = ts.isEntityNameExpression(entityName) ? resolveEntityName(entityName, meaning) : undefined; + if (entityNameSymbol) { + return entityNameSymbol; + } + } + if (entityName.parent.kind === 299 /* JSDocParameterTag */) { + return ts.getParameterSymbolFromJSDoc(entityName.parent); + } + if (entityName.parent.kind === 150 /* TypeParameter */ && entityName.parent.parent.kind === 303 /* JSDocTemplateTag */) { + ts.Debug.assert(!ts.isInJSFile(entityName)); // Otherwise `isDeclarationName` would have been true. + var typeParameter = ts.getTypeParameterFromJsDoc(entityName.parent); + return typeParameter && typeParameter.symbol; + } + if (ts.isExpressionNode(entityName)) { + if (ts.nodeIsMissing(entityName)) { + // Missing entity name. + return undefined; + } + if (entityName.kind === 72 /* Identifier */) { + if (ts.isJSXTagName(entityName) && isJsxIntrinsicIdentifier(entityName)) { + var symbol = getIntrinsicTagSymbol(entityName.parent); + return symbol === unknownSymbol ? undefined : symbol; + } + return resolveEntityName(entityName, 67220415 /* Value */, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); + } + else if (entityName.kind === 189 /* PropertyAccessExpression */ || entityName.kind === 148 /* QualifiedName */) { + var links = getNodeLinks(entityName); + if (links.resolvedSymbol) { + return links.resolvedSymbol; + } + if (entityName.kind === 189 /* PropertyAccessExpression */) { + checkPropertyAccessExpression(entityName); + } + else { + checkQualifiedName(entityName); + } + return links.resolvedSymbol; + } + } + else if (isTypeReferenceIdentifier(entityName)) { + var meaning = entityName.parent.kind === 164 /* TypeReference */ ? 67897832 /* Type */ : 1920 /* Namespace */; + return resolveEntityName(entityName, meaning, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); + } + if (entityName.parent.kind === 163 /* TypePredicate */) { + return resolveEntityName(entityName, /*meaning*/ 1 /* FunctionScopedVariable */); + } + // Do we want to return undefined here? + return undefined; + } + function getSymbolAtLocation(node) { + if (node.kind === 279 /* SourceFile */) { + return ts.isExternalModule(node) ? getMergedSymbol(node.symbol) : undefined; + } + var parent = node.parent; + var grandParent = parent.parent; + if (node.flags & 8388608 /* InWithStatement */) { + // We cannot answer semantic questions within a with block, do not proceed any further + return undefined; + } + if (isDeclarationNameOrImportPropertyName(node)) { + // This is a declaration, call getSymbolOfNode + var parentSymbol = getSymbolOfNode(parent); + return ts.isImportOrExportSpecifier(node.parent) && node.parent.propertyName === node + ? getImmediateAliasedSymbol(parentSymbol) + : parentSymbol; + } + else if (ts.isLiteralComputedPropertyDeclarationName(node)) { + return getSymbolOfNode(parent.parent); + } + if (node.kind === 72 /* Identifier */) { + if (isInRightSideOfImportOrExportAssignment(node)) { + return getSymbolOfEntityNameOrPropertyAccessExpression(node); + } + else if (parent.kind === 186 /* BindingElement */ && + grandParent.kind === 184 /* ObjectBindingPattern */ && + node === parent.propertyName) { + var typeOfPattern = getTypeOfNode(grandParent); + var propertyDeclaration = getPropertyOfType(typeOfPattern, node.escapedText); + if (propertyDeclaration) { + return propertyDeclaration; + } + } + } + switch (node.kind) { + case 72 /* Identifier */: + case 189 /* PropertyAccessExpression */: + case 148 /* QualifiedName */: + return getSymbolOfEntityNameOrPropertyAccessExpression(node); + case 100 /* ThisKeyword */: + var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); + if (ts.isFunctionLike(container)) { + var sig = getSignatureFromDeclaration(container); + if (sig.thisParameter) { + return sig.thisParameter; + } + } + if (ts.isInExpressionContext(node)) { + return checkExpression(node).symbol; + } + // falls through + case 178 /* ThisType */: + return getTypeFromThisTypeNode(node).symbol; + case 98 /* SuperKeyword */: + return checkExpression(node).symbol; + case 124 /* ConstructorKeyword */: + // constructor keyword for an overload, should take us to the definition if it exist + var constructorDeclaration = node.parent; + if (constructorDeclaration && constructorDeclaration.kind === 157 /* Constructor */) { + return constructorDeclaration.parent.symbol; + } + return undefined; + case 10 /* StringLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: + // 1). import x = require("./mo/*gotToDefinitionHere*/d") + // 2). External module name in an import declaration + // 3). Dynamic import call or require in javascript + // 4). type A = import("./f/*gotToDefinitionHere*/oo") + if ((ts.isExternalModuleImportEqualsDeclaration(node.parent.parent) && ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node) || + ((node.parent.kind === 249 /* ImportDeclaration */ || node.parent.kind === 255 /* ExportDeclaration */) && node.parent.moduleSpecifier === node) || + ((ts.isInJSFile(node) && ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteralLike*/ false)) || ts.isImportCall(node.parent)) || + (ts.isLiteralTypeNode(node.parent) && ts.isLiteralImportTypeNode(node.parent.parent) && node.parent.parent.argument === node.parent)) { + return resolveExternalModuleName(node, node); + } + if (ts.isCallExpression(parent) && ts.isBindableObjectDefinePropertyCall(parent) && parent.arguments[1] === node) { + return getSymbolOfNode(parent); + } + // falls through + case 8 /* NumericLiteral */: + // index access + var objectType = ts.isElementAccessExpression(parent) + ? parent.argumentExpression === node ? getTypeOfExpression(parent.expression) : undefined + : ts.isLiteralTypeNode(parent) && ts.isIndexedAccessTypeNode(grandParent) + ? getTypeFromTypeNode(grandParent.objectType) + : undefined; + return objectType && getPropertyOfType(objectType, ts.escapeLeadingUnderscores(node.text)); + case 80 /* DefaultKeyword */: + case 90 /* FunctionKeyword */: + case 37 /* EqualsGreaterThanToken */: + case 76 /* ClassKeyword */: + return getSymbolOfNode(node.parent); + case 183 /* ImportType */: + return ts.isLiteralImportTypeNode(node) ? getSymbolAtLocation(node.argument.literal) : undefined; + case 85 /* ExportKeyword */: + return ts.isExportAssignment(node.parent) ? ts.Debug.assertDefined(node.parent.symbol) : undefined; + default: + return undefined; + } + } + function getShorthandAssignmentValueSymbol(location) { + if (location && location.kind === 276 /* ShorthandPropertyAssignment */) { + return resolveEntityName(location.name, 67220415 /* Value */ | 2097152 /* Alias */); + } + return undefined; + } + /** Returns the target of an export specifier without following aliases */ + function getExportSpecifierLocalTargetSymbol(node) { + return node.parent.parent.moduleSpecifier ? + getExternalModuleMember(node.parent.parent, node) : + resolveEntityName(node.propertyName || node.name, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); + } + function getTypeOfNode(node) { + if (node.flags & 8388608 /* InWithStatement */) { + // We cannot answer semantic questions within a with block, do not proceed any further + return errorType; + } + var classDecl = ts.tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node); + var classType = classDecl && getDeclaredTypeOfClassOrInterface(getSymbolOfNode(classDecl.class)); + if (ts.isPartOfTypeNode(node)) { + var typeFromTypeNode = getTypeFromTypeNode(node); + return classType ? getTypeWithThisArgument(typeFromTypeNode, classType.thisType) : typeFromTypeNode; + } + if (ts.isExpressionNode(node)) { + return getRegularTypeOfExpression(node); + } + if (classType && !classDecl.isImplements) { + // A SyntaxKind.ExpressionWithTypeArguments is considered a type node, except when it occurs in the + // extends clause of a class. We handle that case here. + var baseType = ts.firstOrUndefined(getBaseTypes(classType)); + return baseType ? getTypeWithThisArgument(baseType, classType.thisType) : errorType; + } + if (isTypeDeclaration(node)) { + // In this case, we call getSymbolOfNode instead of getSymbolAtLocation because it is a declaration + var symbol = getSymbolOfNode(node); + return getDeclaredTypeOfSymbol(symbol); + } + if (isTypeDeclarationName(node)) { + var symbol = getSymbolAtLocation(node); + return symbol ? getDeclaredTypeOfSymbol(symbol) : errorType; + } + if (ts.isDeclaration(node)) { + // In this case, we call getSymbolOfNode instead of getSymbolAtLocation because it is a declaration + var symbol = getSymbolOfNode(node); + return getTypeOfSymbol(symbol); + } + if (isDeclarationNameOrImportPropertyName(node)) { + var symbol = getSymbolAtLocation(node); + return symbol ? getTypeOfSymbol(symbol) : errorType; + } + if (ts.isBindingPattern(node)) { + return getTypeForVariableLikeDeclaration(node.parent, /*includeOptionality*/ true) || errorType; + } + if (isInRightSideOfImportOrExportAssignment(node)) { + var symbol = getSymbolAtLocation(node); + if (symbol) { + var declaredType = getDeclaredTypeOfSymbol(symbol); + return declaredType !== errorType ? declaredType : getTypeOfSymbol(symbol); + } + } + return errorType; + } + // Gets the type of object literal or array literal of destructuring assignment. + // { a } from + // for ( { a } of elems) { + // } + // [ a ] from + // [a] = [ some array ...] + function getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr) { + ts.Debug.assert(expr.kind === 188 /* ObjectLiteralExpression */ || expr.kind === 187 /* ArrayLiteralExpression */); + // If this is from "for of" + // for ( { a } of elems) { + // } + if (expr.parent.kind === 227 /* ForOfStatement */) { + var iteratedType = checkRightHandSideOfForOf(expr.parent.expression, expr.parent.awaitModifier); + return checkDestructuringAssignment(expr, iteratedType || errorType); + } + // If this is from "for" initializer + // for ({a } = elems[0];.....) { } + if (expr.parent.kind === 204 /* BinaryExpression */) { + var iteratedType = getTypeOfExpression(expr.parent.right); + return checkDestructuringAssignment(expr, iteratedType || errorType); + } + // If this is from nested object binding pattern + // for ({ skills: { primary, secondary } } = multiRobot, i = 0; i < 1; i++) { + if (expr.parent.kind === 275 /* PropertyAssignment */) { + var typeOfParentObjectLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr.parent.parent); + return checkObjectLiteralDestructuringPropertyAssignment(typeOfParentObjectLiteral || errorType, expr.parent); // TODO: GH#18217 + } + // Array literal assignment - array destructuring pattern + ts.Debug.assert(expr.parent.kind === 187 /* ArrayLiteralExpression */); + // [{ property1: p1, property2 }] = elems; + var typeOfArrayLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr.parent); + var elementType = checkIteratedTypeOrElementType(typeOfArrayLiteral || errorType, expr.parent, /*allowStringInput*/ false, /*allowAsyncIterables*/ false) || errorType; + return checkArrayLiteralDestructuringElementAssignment(expr.parent, typeOfArrayLiteral, expr.parent.elements.indexOf(expr), elementType || errorType); // TODO: GH#18217 + } + // Gets the property symbol corresponding to the property in destructuring assignment + // 'property1' from + // for ( { property1: a } of elems) { + // } + // 'property1' at location 'a' from: + // [a] = [ property1, property2 ] + function getPropertySymbolOfDestructuringAssignment(location) { + // Get the type of the object or array literal and then look for property of given name in the type + var typeOfObjectLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(location.parent.parent); + return typeOfObjectLiteral && getPropertyOfType(typeOfObjectLiteral, location.escapedText); + } + function getRegularTypeOfExpression(expr) { + if (ts.isRightSideOfQualifiedNameOrPropertyAccess(expr)) { + expr = expr.parent; + } + return getRegularTypeOfLiteralType(getTypeOfExpression(expr)); + } + /** + * Gets either the static or instance type of a class element, based on + * whether the element is declared as "static". + */ + function getParentTypeOfClassElement(node) { + var classSymbol = getSymbolOfNode(node.parent); + return ts.hasModifier(node, 32 /* Static */) + ? getTypeOfSymbol(classSymbol) + : getDeclaredTypeOfSymbol(classSymbol); + } + function getClassElementPropertyKeyType(element) { + var name = element.name; + switch (name.kind) { + case 72 /* Identifier */: + return getLiteralType(ts.idText(name)); + case 8 /* NumericLiteral */: + case 10 /* StringLiteral */: + return getLiteralType(name.text); + case 149 /* ComputedPropertyName */: + var nameType = checkComputedPropertyName(name); + return isTypeAssignableToKind(nameType, 12288 /* ESSymbolLike */) ? nameType : stringType; + default: + ts.Debug.fail("Unsupported property name."); + return errorType; + } + } + // Return the list of properties of the given type, augmented with properties from Function + // if the type has call or construct signatures + function getAugmentedPropertiesOfType(type) { + type = getApparentType(type); + var propsByName = ts.createSymbolTable(getPropertiesOfType(type)); + var functionType = getSignaturesOfType(type, 0 /* Call */).length ? globalCallableFunctionType : + getSignaturesOfType(type, 1 /* Construct */).length ? globalNewableFunctionType : + undefined; + if (functionType) { + ts.forEach(getPropertiesOfType(functionType), function (p) { + if (!propsByName.has(p.escapedName)) { + propsByName.set(p.escapedName, p); + } + }); + } + return getNamedMembers(propsByName); + } + function typeHasCallOrConstructSignatures(type) { + return ts.typeHasCallOrConstructSignatures(type, checker); + } + function getRootSymbols(symbol) { + var roots = getImmediateRootSymbols(symbol); + return roots ? ts.flatMap(roots, getRootSymbols) : [symbol]; + } + function getImmediateRootSymbols(symbol) { + if (ts.getCheckFlags(symbol) & 6 /* Synthetic */) { + return ts.mapDefined(getSymbolLinks(symbol).containingType.types, function (type) { return getPropertyOfType(type, symbol.escapedName); }); + } + else if (symbol.flags & 33554432 /* Transient */) { + var _a = symbol, leftSpread = _a.leftSpread, rightSpread = _a.rightSpread, syntheticOrigin = _a.syntheticOrigin; + return leftSpread ? [leftSpread, rightSpread] + : syntheticOrigin ? [syntheticOrigin] + : ts.singleElementArray(tryGetAliasTarget(symbol)); + } + return undefined; + } + function tryGetAliasTarget(symbol) { + var target; + var next = symbol; + while (next = getSymbolLinks(next).target) { + target = next; + } + return target; + } + // Emitter support + function isArgumentsLocalBinding(nodeIn) { + if (!ts.isGeneratedIdentifier(nodeIn)) { + var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier); + if (node) { + var isPropertyName_1 = node.parent.kind === 189 /* PropertyAccessExpression */ && node.parent.name === node; + return !isPropertyName_1 && getReferencedValueSymbol(node) === argumentsSymbol; + } + } + return false; + } + function moduleExportsSomeValue(moduleReferenceExpression) { + var moduleSymbol = resolveExternalModuleName(moduleReferenceExpression.parent, moduleReferenceExpression); + if (!moduleSymbol || ts.isShorthandAmbientModuleSymbol(moduleSymbol)) { + // If the module is not found or is shorthand, assume that it may export a value. + return true; + } + var hasExportAssignment = hasExportAssignmentSymbol(moduleSymbol); + // if module has export assignment then 'resolveExternalModuleSymbol' will return resolved symbol for export assignment + // otherwise it will return moduleSymbol itself + moduleSymbol = resolveExternalModuleSymbol(moduleSymbol); + var symbolLinks = getSymbolLinks(moduleSymbol); + if (symbolLinks.exportsSomeValue === undefined) { + // for export assignments - check if resolved symbol for RHS is itself a value + // otherwise - check if at least one export is value + symbolLinks.exportsSomeValue = hasExportAssignment + ? !!(moduleSymbol.flags & 67220415 /* Value */) + : ts.forEachEntry(getExportsOfModule(moduleSymbol), isValue); + } + return symbolLinks.exportsSomeValue; + function isValue(s) { + s = resolveSymbol(s); + return s && !!(s.flags & 67220415 /* Value */); + } + } + function isNameOfModuleOrEnumDeclaration(node) { + return ts.isModuleOrEnumDeclaration(node.parent) && node === node.parent.name; + } + // When resolved as an expression identifier, if the given node references an exported entity, return the declaration + // node of the exported entity's container. Otherwise, return undefined. + function getReferencedExportContainer(nodeIn, prefixLocals) { + var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier); + if (node) { + // When resolving the export container for the name of a module or enum + // declaration, we need to start resolution at the declaration's container. + // Otherwise, we could incorrectly resolve the export container as the + // declaration if it contains an exported member with the same name. + var symbol = getReferencedValueSymbol(node, /*startInDeclarationContainer*/ isNameOfModuleOrEnumDeclaration(node)); + if (symbol) { + if (symbol.flags & 1048576 /* ExportValue */) { + // If we reference an exported entity within the same module declaration, then whether + // we prefix depends on the kind of entity. SymbolFlags.ExportHasLocal encompasses all the + // kinds that we do NOT prefix. + var exportSymbol = getMergedSymbol(symbol.exportSymbol); + if (!prefixLocals && exportSymbol.flags & 944 /* ExportHasLocal */ && !(exportSymbol.flags & 3 /* Variable */)) { + return undefined; + } + symbol = exportSymbol; + } + var parentSymbol_1 = getParentOfSymbol(symbol); + if (parentSymbol_1) { + if (parentSymbol_1.flags & 512 /* ValueModule */ && parentSymbol_1.valueDeclaration.kind === 279 /* SourceFile */) { + var symbolFile = parentSymbol_1.valueDeclaration; + var referenceFile = ts.getSourceFileOfNode(node); + // If `node` accesses an export and that export isn't in the same file, then symbol is a namespace export, so return undefined. + var symbolIsUmdExport = symbolFile !== referenceFile; + return symbolIsUmdExport ? undefined : symbolFile; + } + return ts.findAncestor(node.parent, function (n) { return ts.isModuleOrEnumDeclaration(n) && getSymbolOfNode(n) === parentSymbol_1; }); + } + } + } + } + // When resolved as an expression identifier, if the given node references an import, return the declaration of + // that import. Otherwise, return undefined. + function getReferencedImportDeclaration(nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier); + if (node) { + var symbol = getReferencedValueSymbol(node); + // We should only get the declaration of an alias if there isn't a local value + // declaration for the symbol + if (isNonLocalAlias(symbol, /*excludes*/ 67220415 /* Value */)) { + return getDeclarationOfAliasSymbol(symbol); + } + } + return undefined; + } + function isSymbolOfDeclarationWithCollidingName(symbol) { + if (symbol.flags & 418 /* BlockScoped */) { + var links = getSymbolLinks(symbol); + if (links.isDeclarationWithCollidingName === undefined) { + var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); + if (ts.isStatementWithLocals(container)) { + var nodeLinks_1 = getNodeLinks(symbol.valueDeclaration); + if (resolveName(container.parent, symbol.escapedName, 67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)) { + // redeclaration - always should be renamed + links.isDeclarationWithCollidingName = true; + } + else if (nodeLinks_1.flags & 262144 /* CapturedBlockScopedBinding */) { + // binding is captured in the function + // should be renamed if: + // - binding is not top level - top level bindings never collide with anything + // AND + // - binding is not declared in loop, should be renamed to avoid name reuse across siblings + // let a, b + // { let x = 1; a = () => x; } + // { let x = 100; b = () => x; } + // console.log(a()); // should print '1' + // console.log(b()); // should print '100' + // OR + // - binding is declared inside loop but not in inside initializer of iteration statement or directly inside loop body + // * variables from initializer are passed to rewritten loop body as parameters so they are not captured directly + // * variables that are declared immediately in loop body will become top level variable after loop is rewritten and thus + // they will not collide with anything + var isDeclaredInLoop = nodeLinks_1.flags & 524288 /* BlockScopedBindingInLoop */; + var inLoopInitializer = ts.isIterationStatement(container, /*lookInLabeledStatements*/ false); + var inLoopBodyBlock = container.kind === 218 /* Block */ && ts.isIterationStatement(container.parent, /*lookInLabeledStatements*/ false); + links.isDeclarationWithCollidingName = !ts.isBlockScopedContainerTopLevel(container) && (!isDeclaredInLoop || (!inLoopInitializer && !inLoopBodyBlock)); + } + else { + links.isDeclarationWithCollidingName = false; + } + } + } + return links.isDeclarationWithCollidingName; + } + return false; + } + // When resolved as an expression identifier, if the given node references a nested block scoped entity with + // a name that either hides an existing name or might hide it when compiled downlevel, + // return the declaration of that entity. Otherwise, return undefined. + function getReferencedDeclarationWithCollidingName(nodeIn) { + if (!ts.isGeneratedIdentifier(nodeIn)) { + var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier); + if (node) { + var symbol = getReferencedValueSymbol(node); + if (symbol && isSymbolOfDeclarationWithCollidingName(symbol)) { + return symbol.valueDeclaration; + } + } + } + return undefined; + } + // Return true if the given node is a declaration of a nested block scoped entity with a name that either hides an + // existing name or might hide a name when compiled downlevel + function isDeclarationWithCollidingName(nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isDeclaration); + if (node) { + var symbol = getSymbolOfNode(node); + if (symbol) { + return isSymbolOfDeclarationWithCollidingName(symbol); + } + } + return false; + } + function isValueAliasDeclaration(node) { + switch (node.kind) { + case 248 /* ImportEqualsDeclaration */: + case 250 /* ImportClause */: + case 251 /* NamespaceImport */: + case 253 /* ImportSpecifier */: + case 257 /* ExportSpecifier */: + return isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol); + case 255 /* ExportDeclaration */: + var exportClause = node.exportClause; + return !!exportClause && ts.some(exportClause.elements, isValueAliasDeclaration); + case 254 /* ExportAssignment */: + return node.expression + && node.expression.kind === 72 /* Identifier */ + ? isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol) + : true; + } + return false; + } + function isTopLevelValueImportEqualsWithEntityName(nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isImportEqualsDeclaration); + if (node === undefined || node.parent.kind !== 279 /* SourceFile */ || !ts.isInternalModuleImportEqualsDeclaration(node)) { + // parent is not source file or it is not reference to internal module + return false; + } + var isValue = isAliasResolvedToValue(getSymbolOfNode(node)); + return isValue && node.moduleReference && !ts.nodeIsMissing(node.moduleReference); + } + function isAliasResolvedToValue(symbol) { + var target = resolveAlias(symbol); + if (target === unknownSymbol) { + return true; + } + // const enums and modules that contain only const enums are not considered values from the emit perspective + // unless 'preserveConstEnums' option is set to true + return !!(target.flags & 67220415 /* Value */) && + (compilerOptions.preserveConstEnums || !isConstEnumOrConstEnumOnlyModule(target)); + } + function isConstEnumOrConstEnumOnlyModule(s) { + return isConstEnumSymbol(s) || !!s.constEnumOnlyModule; + } + function isReferencedAliasDeclaration(node, checkChildren) { + if (ts.isAliasSymbolDeclaration(node)) { + var symbol = getSymbolOfNode(node); + if (symbol && getSymbolLinks(symbol).referenced) { + return true; + } + var target = getSymbolLinks(symbol).target; // TODO: GH#18217 + if (target && ts.getModifierFlags(node) & 1 /* Export */ && + target.flags & 67220415 /* Value */ && (compilerOptions.preserveConstEnums || !isConstEnumOrConstEnumOnlyModule(target))) { + // An `export import ... =` of a value symbol is always considered referenced + return true; + } + } + if (checkChildren) { + return !!ts.forEachChild(node, function (node) { return isReferencedAliasDeclaration(node, checkChildren); }); + } + return false; + } + function isImplementationOfOverload(node) { + if (ts.nodeIsPresent(node.body)) { + if (ts.isGetAccessor(node) || ts.isSetAccessor(node)) + return false; // Get or set accessors can never be overload implementations, but can have up to 2 signatures + var symbol = getSymbolOfNode(node); + var signaturesOfSymbol = getSignaturesOfSymbol(symbol); + // If this function body corresponds to function with multiple signature, it is implementation of overload + // e.g.: function foo(a: string): string; + // function foo(a: number): number; + // function foo(a: any) { // This is implementation of the overloads + // return a; + // } + return signaturesOfSymbol.length > 1 || + // If there is single signature for the symbol, it is overload if that signature isn't coming from the node + // e.g.: function foo(a: string): string; + // function foo(a: any) { // This is implementation of the overloads + // return a; + // } + (signaturesOfSymbol.length === 1 && signaturesOfSymbol[0].declaration !== node); + } + return false; + } + function isRequiredInitializedParameter(parameter) { + return !!strictNullChecks && + !isOptionalParameter(parameter) && + !ts.isJSDocParameterTag(parameter) && + !!parameter.initializer && + !ts.hasModifier(parameter, 92 /* ParameterPropertyModifier */); + } + function isOptionalUninitializedParameterProperty(parameter) { + return strictNullChecks && + isOptionalParameter(parameter) && + !parameter.initializer && + ts.hasModifier(parameter, 92 /* ParameterPropertyModifier */); + } + function isExpandoFunctionDeclaration(node) { + var declaration = ts.getParseTreeNode(node, ts.isFunctionDeclaration); + if (!declaration) { + return false; + } + var symbol = getSymbolOfNode(declaration); + if (!symbol || !(symbol.flags & 16 /* Function */)) { + return false; + } + return !!ts.forEachEntry(getExportsOfSymbol(symbol), function (p) { return p.flags & 67220415 /* Value */ && ts.isPropertyAccessExpression(p.valueDeclaration); }); + } + function getPropertiesOfContainerFunction(node) { + var declaration = ts.getParseTreeNode(node, ts.isFunctionDeclaration); + if (!declaration) { + return ts.emptyArray; + } + var symbol = getSymbolOfNode(declaration); + return symbol && getPropertiesOfType(getTypeOfSymbol(symbol)) || ts.emptyArray; + } + function getNodeCheckFlags(node) { + return getNodeLinks(node).flags || 0; + } + function getEnumMemberValue(node) { + computeEnumMemberValues(node.parent); + return getNodeLinks(node).enumMemberValue; + } + function canHaveConstantValue(node) { + switch (node.kind) { + case 278 /* EnumMember */: + case 189 /* PropertyAccessExpression */: + case 190 /* ElementAccessExpression */: + return true; + } + return false; + } + function getConstantValue(node) { + if (node.kind === 278 /* EnumMember */) { + return getEnumMemberValue(node); + } + var symbol = getNodeLinks(node).resolvedSymbol; + if (symbol && (symbol.flags & 8 /* EnumMember */)) { + // inline property\index accesses only for const enums + var member = symbol.valueDeclaration; + if (ts.isEnumConst(member.parent)) { + return getEnumMemberValue(member); + } + } + return undefined; + } + function isFunctionType(type) { + return !!(type.flags & 524288 /* Object */) && getSignaturesOfType(type, 0 /* Call */).length > 0; + } + function getTypeReferenceSerializationKind(typeNameIn, location) { + // ensure both `typeName` and `location` are parse tree nodes. + var typeName = ts.getParseTreeNode(typeNameIn, ts.isEntityName); + if (!typeName) + return ts.TypeReferenceSerializationKind.Unknown; + if (location) { + location = ts.getParseTreeNode(location); + if (!location) + return ts.TypeReferenceSerializationKind.Unknown; + } + // Resolve the symbol as a value to ensure the type can be reached at runtime during emit. + var valueSymbol = resolveEntityName(typeName, 67220415 /* Value */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location); + // Resolve the symbol as a type so that we can provide a more useful hint for the type serializer. + var typeSymbol = resolveEntityName(typeName, 67897832 /* Type */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location); + if (valueSymbol && valueSymbol === typeSymbol) { + var globalPromiseSymbol = getGlobalPromiseConstructorSymbol(/*reportErrors*/ false); + if (globalPromiseSymbol && valueSymbol === globalPromiseSymbol) { + return ts.TypeReferenceSerializationKind.Promise; + } + var constructorType = getTypeOfSymbol(valueSymbol); + if (constructorType && isConstructorType(constructorType)) { + return ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue; + } + } + // We might not be able to resolve type symbol so use unknown type in that case (eg error case) + if (!typeSymbol) { + return ts.TypeReferenceSerializationKind.Unknown; + } + var type = getDeclaredTypeOfSymbol(typeSymbol); + if (type === errorType) { + return ts.TypeReferenceSerializationKind.Unknown; + } + else if (type.flags & 3 /* AnyOrUnknown */) { + return ts.TypeReferenceSerializationKind.ObjectType; + } + else if (isTypeAssignableToKind(type, 16384 /* Void */ | 98304 /* Nullable */ | 131072 /* Never */)) { + return ts.TypeReferenceSerializationKind.VoidNullableOrNeverType; + } + else if (isTypeAssignableToKind(type, 528 /* BooleanLike */)) { + return ts.TypeReferenceSerializationKind.BooleanType; + } + else if (isTypeAssignableToKind(type, 296 /* NumberLike */)) { + return ts.TypeReferenceSerializationKind.NumberLikeType; + } + else if (isTypeAssignableToKind(type, 2112 /* BigIntLike */)) { + return ts.TypeReferenceSerializationKind.BigIntLikeType; + } + else if (isTypeAssignableToKind(type, 132 /* StringLike */)) { + return ts.TypeReferenceSerializationKind.StringLikeType; + } + else if (isTupleType(type)) { + return ts.TypeReferenceSerializationKind.ArrayLikeType; + } + else if (isTypeAssignableToKind(type, 12288 /* ESSymbolLike */)) { + return ts.TypeReferenceSerializationKind.ESSymbolType; + } + else if (isFunctionType(type)) { + return ts.TypeReferenceSerializationKind.TypeWithCallSignature; + } + else if (isArrayType(type)) { + return ts.TypeReferenceSerializationKind.ArrayLikeType; + } + else { + return ts.TypeReferenceSerializationKind.ObjectType; + } + } + function createTypeOfDeclaration(declarationIn, enclosingDeclaration, flags, tracker, addUndefined) { + var declaration = ts.getParseTreeNode(declarationIn, ts.isVariableLikeOrAccessor); + if (!declaration) { + return ts.createToken(120 /* AnyKeyword */); + } + // Get type of the symbol if this is the valid symbol otherwise get type at location + var symbol = getSymbolOfNode(declaration); + var type = symbol && !(symbol.flags & (2048 /* TypeLiteral */ | 131072 /* Signature */)) + ? getWidenedLiteralType(getTypeOfSymbol(symbol)) + : errorType; + if (type.flags & 8192 /* UniqueESSymbol */ && + type.symbol === symbol) { + flags |= 1048576 /* AllowUniqueESSymbolType */; + } + if (addUndefined) { + type = getOptionalType(type); + } + return nodeBuilder.typeToTypeNode(type, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, tracker); + } + function createReturnTypeOfSignatureDeclaration(signatureDeclarationIn, enclosingDeclaration, flags, tracker) { + var signatureDeclaration = ts.getParseTreeNode(signatureDeclarationIn, ts.isFunctionLike); + if (!signatureDeclaration) { + return ts.createToken(120 /* AnyKeyword */); + } + var signature = getSignatureFromDeclaration(signatureDeclaration); + return nodeBuilder.typeToTypeNode(getReturnTypeOfSignature(signature), enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, tracker); + } + function createTypeOfExpression(exprIn, enclosingDeclaration, flags, tracker) { + var expr = ts.getParseTreeNode(exprIn, ts.isExpression); + if (!expr) { + return ts.createToken(120 /* AnyKeyword */); + } + var type = getWidenedType(getRegularTypeOfExpression(expr)); + return nodeBuilder.typeToTypeNode(type, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, tracker); + } + function hasGlobalName(name) { + return globals.has(ts.escapeLeadingUnderscores(name)); + } + function getReferencedValueSymbol(reference, startInDeclarationContainer) { + var resolvedSymbol = getNodeLinks(reference).resolvedSymbol; + if (resolvedSymbol) { + return resolvedSymbol; + } + var location = reference; + if (startInDeclarationContainer) { + // When resolving the name of a declaration as a value, we need to start resolution + // at a point outside of the declaration. + var parent = reference.parent; + if (ts.isDeclaration(parent) && reference === parent.name) { + location = getDeclarationContainer(parent); + } + } + return resolveName(location, reference.escapedText, 67220415 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */, /*nodeNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); + } + function getReferencedValueDeclaration(referenceIn) { + if (!ts.isGeneratedIdentifier(referenceIn)) { + var reference = ts.getParseTreeNode(referenceIn, ts.isIdentifier); + if (reference) { + var symbol = getReferencedValueSymbol(reference); + if (symbol) { + return getExportSymbolOfValueSymbolIfExported(symbol).valueDeclaration; + } + } + } + return undefined; + } + function isLiteralConstDeclaration(node) { + if (ts.isDeclarationReadonly(node) || ts.isVariableDeclaration(node) && ts.isVarConst(node)) { + return isFreshLiteralType(getTypeOfSymbol(getSymbolOfNode(node))); + } + return false; + } + function literalTypeToNode(type, enclosing, tracker) { + var enumResult = type.flags & 1024 /* EnumLiteral */ ? nodeBuilder.symbolToExpression(type.symbol, 67220415 /* Value */, enclosing, /*flags*/ undefined, tracker) + : type === trueType ? ts.createTrue() : type === falseType && ts.createFalse(); + return enumResult || ts.createLiteral(type.value); + } + function createLiteralConstValue(node, tracker) { + var type = getTypeOfSymbol(getSymbolOfNode(node)); + return literalTypeToNode(type, node, tracker); + } + function createResolver() { + // this variable and functions that use it are deliberately moved here from the outer scope + // to avoid scope pollution + var resolvedTypeReferenceDirectives = host.getResolvedTypeReferenceDirectives(); + var fileToDirective; + if (resolvedTypeReferenceDirectives) { + // populate reverse mapping: file path -> type reference directive that was resolved to this file + fileToDirective = ts.createMap(); + resolvedTypeReferenceDirectives.forEach(function (resolvedDirective, key) { + if (!resolvedDirective || !resolvedDirective.resolvedFileName) { + return; + } + var file = host.getSourceFile(resolvedDirective.resolvedFileName); + fileToDirective.set(file.path, key); + }); + } + return { + getReferencedExportContainer: getReferencedExportContainer, + getReferencedImportDeclaration: getReferencedImportDeclaration, + getReferencedDeclarationWithCollidingName: getReferencedDeclarationWithCollidingName, + isDeclarationWithCollidingName: isDeclarationWithCollidingName, + isValueAliasDeclaration: function (node) { + node = ts.getParseTreeNode(node); + // Synthesized nodes are always treated like values. + return node ? isValueAliasDeclaration(node) : true; + }, + hasGlobalName: hasGlobalName, + isReferencedAliasDeclaration: function (node, checkChildren) { + node = ts.getParseTreeNode(node); + // Synthesized nodes are always treated as referenced. + return node ? isReferencedAliasDeclaration(node, checkChildren) : true; + }, + getNodeCheckFlags: function (node) { + node = ts.getParseTreeNode(node); + return node ? getNodeCheckFlags(node) : 0; + }, + isTopLevelValueImportEqualsWithEntityName: isTopLevelValueImportEqualsWithEntityName, + isDeclarationVisible: isDeclarationVisible, + isImplementationOfOverload: isImplementationOfOverload, + isRequiredInitializedParameter: isRequiredInitializedParameter, + isOptionalUninitializedParameterProperty: isOptionalUninitializedParameterProperty, + isExpandoFunctionDeclaration: isExpandoFunctionDeclaration, + getPropertiesOfContainerFunction: getPropertiesOfContainerFunction, + createTypeOfDeclaration: createTypeOfDeclaration, + createReturnTypeOfSignatureDeclaration: createReturnTypeOfSignatureDeclaration, + createTypeOfExpression: createTypeOfExpression, + createLiteralConstValue: createLiteralConstValue, + isSymbolAccessible: isSymbolAccessible, + isEntityNameVisible: isEntityNameVisible, + getConstantValue: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, canHaveConstantValue); + return node ? getConstantValue(node) : undefined; + }, + collectLinkedAliases: collectLinkedAliases, + getReferencedValueDeclaration: getReferencedValueDeclaration, + getTypeReferenceSerializationKind: getTypeReferenceSerializationKind, + isOptionalParameter: isOptionalParameter, + moduleExportsSomeValue: moduleExportsSomeValue, + isArgumentsLocalBinding: isArgumentsLocalBinding, + getExternalModuleFileFromDeclaration: getExternalModuleFileFromDeclaration, + getTypeReferenceDirectivesForEntityName: getTypeReferenceDirectivesForEntityName, + getTypeReferenceDirectivesForSymbol: getTypeReferenceDirectivesForSymbol, + isLiteralConstDeclaration: isLiteralConstDeclaration, + isLateBound: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isDeclaration); + var symbol = node && getSymbolOfNode(node); + return !!(symbol && ts.getCheckFlags(symbol) & 1024 /* Late */); + }, + getJsxFactoryEntity: function (location) { return location ? (getJsxNamespace(location), (ts.getSourceFileOfNode(location).localJsxFactory || _jsxFactoryEntity)) : _jsxFactoryEntity; }, + getAllAccessorDeclarations: function (accessor) { + accessor = ts.getParseTreeNode(accessor, ts.isGetOrSetAccessorDeclaration); // TODO: GH#18217 + var otherKind = accessor.kind === 159 /* SetAccessor */ ? 158 /* GetAccessor */ : 159 /* SetAccessor */; + var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(accessor), otherKind); + var firstAccessor = otherAccessor && (otherAccessor.pos < accessor.pos) ? otherAccessor : accessor; + var secondAccessor = otherAccessor && (otherAccessor.pos < accessor.pos) ? accessor : otherAccessor; + var setAccessor = accessor.kind === 159 /* SetAccessor */ ? accessor : otherAccessor; + var getAccessor = accessor.kind === 158 /* GetAccessor */ ? accessor : otherAccessor; + return { + firstAccessor: firstAccessor, + secondAccessor: secondAccessor, + setAccessor: setAccessor, + getAccessor: getAccessor + }; + }, + getSymbolOfExternalModuleSpecifier: function (moduleName) { return resolveExternalModuleNameWorker(moduleName, moduleName, /*moduleNotFoundError*/ undefined); }, + isBindingCapturedByNode: function (node, decl) { + var parseNode = ts.getParseTreeNode(node); + var parseDecl = ts.getParseTreeNode(decl); + return !!parseNode && !!parseDecl && (ts.isVariableDeclaration(parseDecl) || ts.isBindingElement(parseDecl)) && isBindingCapturedByNode(parseNode, parseDecl); + } + }; + function isInHeritageClause(node) { + return node.parent && node.parent.kind === 211 /* ExpressionWithTypeArguments */ && node.parent.parent && node.parent.parent.kind === 273 /* HeritageClause */; + } + // defined here to avoid outer scope pollution + function getTypeReferenceDirectivesForEntityName(node) { + // program does not have any files with type reference directives - bail out + if (!fileToDirective) { + return undefined; + } + // property access can only be used as values, or types when within an expression with type arguments inside a heritage clause + // qualified names can only be used as types\namespaces + // identifiers are treated as values only if they appear in type queries + var meaning = 67897832 /* Type */ | 1920 /* Namespace */; + if ((node.kind === 72 /* Identifier */ && isInTypeQuery(node)) || (node.kind === 189 /* PropertyAccessExpression */ && !isInHeritageClause(node))) { + meaning = 67220415 /* Value */ | 1048576 /* ExportValue */; + } + var symbol = resolveEntityName(node, meaning, /*ignoreErrors*/ true); + return symbol && symbol !== unknownSymbol ? getTypeReferenceDirectivesForSymbol(symbol, meaning) : undefined; + } + // defined here to avoid outer scope pollution + function getTypeReferenceDirectivesForSymbol(symbol, meaning) { + // program does not have any files with type reference directives - bail out + if (!fileToDirective) { + return undefined; + } + if (!isSymbolFromTypeDeclarationFile(symbol)) { + return undefined; + } + // check what declarations in the symbol can contribute to the target meaning + var typeReferenceDirectives; + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + // check meaning of the local symbol to see if declaration needs to be analyzed further + if (decl.symbol && decl.symbol.flags & meaning) { + var file = ts.getSourceFileOfNode(decl); + var typeReferenceDirective = fileToDirective.get(file.path); + if (typeReferenceDirective) { + (typeReferenceDirectives || (typeReferenceDirectives = [])).push(typeReferenceDirective); + } + else { + // found at least one entry that does not originate from type reference directive + return undefined; + } + } + } + return typeReferenceDirectives; + } + function isSymbolFromTypeDeclarationFile(symbol) { + // bail out if symbol does not have associated declarations (i.e. this is transient symbol created for property in binding pattern) + if (!symbol.declarations) { + return false; + } + // walk the parent chain for symbols to make sure that top level parent symbol is in the global scope + // external modules cannot define or contribute to type declaration files + var current = symbol; + while (true) { + var parent = getParentOfSymbol(current); + if (parent) { + current = parent; + } + else { + break; + } + } + if (current.valueDeclaration && current.valueDeclaration.kind === 279 /* SourceFile */ && current.flags & 512 /* ValueModule */) { + return false; + } + // check that at least one declaration of top level symbol originates from type declaration file + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + var file = ts.getSourceFileOfNode(decl); + if (fileToDirective.has(file.path)) { + return true; + } + } + return false; + } + } + function getExternalModuleFileFromDeclaration(declaration) { + var specifier = declaration.kind === 244 /* ModuleDeclaration */ ? ts.tryCast(declaration.name, ts.isStringLiteral) : ts.getExternalModuleName(declaration); + var moduleSymbol = resolveExternalModuleNameWorker(specifier, specifier, /*moduleNotFoundError*/ undefined); // TODO: GH#18217 + if (!moduleSymbol) { + return undefined; + } + return ts.getDeclarationOfKind(moduleSymbol, 279 /* SourceFile */); + } + function initializeTypeChecker() { + // Bind all source files and propagate errors + for (var _i = 0, _a = host.getSourceFiles(); _i < _a.length; _i++) { + var file = _a[_i]; + ts.bindSourceFile(file, compilerOptions); + } + amalgamatedDuplicates = ts.createMap(); + // Initialize global symbol table + var augmentations; + for (var _b = 0, _c = host.getSourceFiles(); _b < _c.length; _b++) { + var file = _c[_b]; + if (file.redirectInfo) { + continue; + } + if (!ts.isExternalOrCommonJsModule(file)) { + mergeSymbolTable(globals, file.locals); + } + if (file.jsGlobalAugmentations) { + mergeSymbolTable(globals, file.jsGlobalAugmentations); + } + if (file.patternAmbientModules && file.patternAmbientModules.length) { + patternAmbientModules = ts.concatenate(patternAmbientModules, file.patternAmbientModules); + } + if (file.moduleAugmentations.length) { + (augmentations || (augmentations = [])).push(file.moduleAugmentations); + } + if (file.symbol && file.symbol.globalExports) { + // Merge in UMD exports with first-in-wins semantics (see #9771) + var source = file.symbol.globalExports; + source.forEach(function (sourceSymbol, id) { + if (!globals.has(id)) { + globals.set(id, sourceSymbol); + } + }); + } + } + // We do global augmentations separately from module augmentations (and before creating global types) because they + // 1. Affect global types. We won't have the correct global types until global augmentations are merged. Also, + // 2. Module augmentation instantiation requires creating the type of a module, which, in turn, can require + // checking for an export or property on the module (if export=) which, in turn, can fall back to the + // apparent type of the module - either globalObjectType or globalFunctionType - which wouldn't exist if we + // did module augmentations prior to finalizing the global types. + if (augmentations) { + // merge _global_ module augmentations. + // this needs to be done after global symbol table is initialized to make sure that all ambient modules are indexed + for (var _d = 0, augmentations_1 = augmentations; _d < augmentations_1.length; _d++) { + var list = augmentations_1[_d]; + for (var _e = 0, list_1 = list; _e < list_1.length; _e++) { + var augmentation = list_1[_e]; + if (!ts.isGlobalScopeAugmentation(augmentation.parent)) + continue; + mergeModuleAugmentation(augmentation); + } + } + } + // Setup global builtins + addToSymbolTable(globals, builtinGlobals, ts.Diagnostics.Declaration_name_conflicts_with_built_in_global_identifier_0); + getSymbolLinks(undefinedSymbol).type = undefinedWideningType; + getSymbolLinks(argumentsSymbol).type = getGlobalType("IArguments", /*arity*/ 0, /*reportErrors*/ true); + getSymbolLinks(unknownSymbol).type = errorType; + // Initialize special types + globalArrayType = getGlobalType("Array", /*arity*/ 1, /*reportErrors*/ true); + globalObjectType = getGlobalType("Object", /*arity*/ 0, /*reportErrors*/ true); + globalFunctionType = getGlobalType("Function", /*arity*/ 0, /*reportErrors*/ true); + globalCallableFunctionType = strictBindCallApply && getGlobalType("CallableFunction", /*arity*/ 0, /*reportErrors*/ true) || globalFunctionType; + globalNewableFunctionType = strictBindCallApply && getGlobalType("NewableFunction", /*arity*/ 0, /*reportErrors*/ true) || globalFunctionType; + globalStringType = getGlobalType("String", /*arity*/ 0, /*reportErrors*/ true); + globalNumberType = getGlobalType("Number", /*arity*/ 0, /*reportErrors*/ true); + globalBooleanType = getGlobalType("Boolean", /*arity*/ 0, /*reportErrors*/ true); + globalRegExpType = getGlobalType("RegExp", /*arity*/ 0, /*reportErrors*/ true); + anyArrayType = createArrayType(anyType); + autoArrayType = createArrayType(autoType); + if (autoArrayType === emptyObjectType) { + // autoArrayType is used as a marker, so even if global Array type is not defined, it needs to be a unique type + autoArrayType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + } + globalReadonlyArrayType = getGlobalTypeOrUndefined("ReadonlyArray", /*arity*/ 1); + anyReadonlyArrayType = globalReadonlyArrayType ? createTypeFromGenericGlobalType(globalReadonlyArrayType, [anyType]) : anyArrayType; + globalThisType = getGlobalTypeOrUndefined("ThisType", /*arity*/ 1); + if (augmentations) { + // merge _nonglobal_ module augmentations. + // this needs to be done after global symbol table is initialized to make sure that all ambient modules are indexed + for (var _f = 0, augmentations_2 = augmentations; _f < augmentations_2.length; _f++) { + var list = augmentations_2[_f]; + for (var _g = 0, list_2 = list; _g < list_2.length; _g++) { + var augmentation = list_2[_g]; + if (ts.isGlobalScopeAugmentation(augmentation.parent)) + continue; + mergeModuleAugmentation(augmentation); + } + } + } + amalgamatedDuplicates.forEach(function (_a) { + var firstFile = _a.firstFile, secondFile = _a.secondFile, conflictingSymbols = _a.conflictingSymbols; + // If not many things conflict, issue individual errors + if (conflictingSymbols.size < 8) { + conflictingSymbols.forEach(function (_a, symbolName) { + var isBlockScoped = _a.isBlockScoped, firstFileLocations = _a.firstFileLocations, secondFileLocations = _a.secondFileLocations; + var message = isBlockScoped ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 : ts.Diagnostics.Duplicate_identifier_0; + for (var _i = 0, firstFileLocations_1 = firstFileLocations; _i < firstFileLocations_1.length; _i++) { + var node = firstFileLocations_1[_i]; + addDuplicateDeclarationError(node, message, symbolName, secondFileLocations); + } + for (var _b = 0, secondFileLocations_1 = secondFileLocations; _b < secondFileLocations_1.length; _b++) { + var node = secondFileLocations_1[_b]; + addDuplicateDeclarationError(node, message, symbolName, firstFileLocations); + } + }); + } + else { + // Otherwise issue top-level error since the files appear very identical in terms of what they contain + var list = ts.arrayFrom(conflictingSymbols.keys()).join(", "); + diagnostics.add(addRelatedInfo(ts.createDiagnosticForNode(firstFile, ts.Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list), ts.createDiagnosticForNode(secondFile, ts.Diagnostics.Conflicts_are_in_this_file))); + diagnostics.add(addRelatedInfo(ts.createDiagnosticForNode(secondFile, ts.Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list), ts.createDiagnosticForNode(firstFile, ts.Diagnostics.Conflicts_are_in_this_file))); + } + }); + amalgamatedDuplicates = undefined; + } + function checkExternalEmitHelpers(location, helpers) { + if ((requestedExternalEmitHelpers & helpers) !== helpers && compilerOptions.importHelpers) { + var sourceFile = ts.getSourceFileOfNode(location); + if (ts.isEffectiveExternalModule(sourceFile, compilerOptions) && !(location.flags & 4194304 /* Ambient */)) { + var helpersModule = resolveHelpersModule(sourceFile, location); + if (helpersModule !== unknownSymbol) { + var uncheckedHelpers = helpers & ~requestedExternalEmitHelpers; + for (var helper = 1 /* FirstEmitHelper */; helper <= 65536 /* LastEmitHelper */; helper <<= 1) { + if (uncheckedHelpers & helper) { + var name = getHelperName(helper); + var symbol = getSymbol(helpersModule.exports, ts.escapeLeadingUnderscores(name), 67220415 /* Value */); + if (!symbol) { + error(location, ts.Diagnostics.This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1, ts.externalHelpersModuleNameText, name); + } + } + } + } + requestedExternalEmitHelpers |= helpers; + } + } + } + function getHelperName(helper) { + switch (helper) { + case 1 /* Extends */: return "__extends"; + case 2 /* Assign */: return "__assign"; + case 4 /* Rest */: return "__rest"; + case 8 /* Decorate */: return "__decorate"; + case 16 /* Metadata */: return "__metadata"; + case 32 /* Param */: return "__param"; + case 64 /* Awaiter */: return "__awaiter"; + case 128 /* Generator */: return "__generator"; + case 256 /* Values */: return "__values"; + case 512 /* Read */: return "__read"; + case 1024 /* Spread */: return "__spread"; + case 2048 /* Await */: return "__await"; + case 4096 /* AsyncGenerator */: return "__asyncGenerator"; + case 8192 /* AsyncDelegator */: return "__asyncDelegator"; + case 16384 /* AsyncValues */: return "__asyncValues"; + case 32768 /* ExportStar */: return "__exportStar"; + case 65536 /* MakeTemplateObject */: return "__makeTemplateObject"; + default: return ts.Debug.fail("Unrecognized helper"); + } + } + function resolveHelpersModule(node, errorNode) { + if (!externalHelpersModule) { + externalHelpersModule = resolveExternalModule(node, ts.externalHelpersModuleNameText, ts.Diagnostics.This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found, errorNode) || unknownSymbol; + } + return externalHelpersModule; + } + // GRAMMAR CHECKING + function checkGrammarDecoratorsAndModifiers(node) { + return checkGrammarDecorators(node) || checkGrammarModifiers(node); + } + function checkGrammarDecorators(node) { + if (!node.decorators) { + return false; + } + if (!ts.nodeCanBeDecorated(node, node.parent, node.parent.parent)) { + if (node.kind === 156 /* MethodDeclaration */ && !ts.nodeIsPresent(node.body)) { + return grammarErrorOnFirstToken(node, ts.Diagnostics.A_decorator_can_only_decorate_a_method_implementation_not_an_overload); + } + else { + return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_are_not_valid_here); + } + } + else if (node.kind === 158 /* GetAccessor */ || node.kind === 159 /* SetAccessor */) { + var accessors = ts.getAllAccessorDeclarations(node.parent.members, node); + if (accessors.firstAccessor.decorators && node === accessors.secondAccessor) { + return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name); + } + } + return false; + } + function checkGrammarModifiers(node) { + var quickResult = reportObviousModifierErrors(node); + if (quickResult !== undefined) { + return quickResult; + } + var lastStatic, lastDeclare, lastAsync, lastReadonly; + var flags = 0 /* None */; + for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) { + var modifier = _a[_i]; + if (modifier.kind !== 133 /* ReadonlyKeyword */) { + if (node.kind === 153 /* PropertySignature */ || node.kind === 155 /* MethodSignature */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_type_member, ts.tokenToString(modifier.kind)); + } + if (node.kind === 162 /* IndexSignature */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_an_index_signature, ts.tokenToString(modifier.kind)); + } + } + switch (modifier.kind) { + case 77 /* ConstKeyword */: + if (node.kind !== 243 /* EnumDeclaration */) { + return grammarErrorOnNode(node, ts.Diagnostics.A_class_member_cannot_have_the_0_keyword, ts.tokenToString(77 /* ConstKeyword */)); + } + break; + case 115 /* PublicKeyword */: + case 114 /* ProtectedKeyword */: + case 113 /* PrivateKeyword */: + var text = visibilityToString(ts.modifierToFlag(modifier.kind)); + if (flags & 28 /* AccessibilityModifier */) { + return grammarErrorOnNode(modifier, ts.Diagnostics.Accessibility_modifier_already_seen); + } + else if (flags & 32 /* Static */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "static"); + } + else if (flags & 64 /* Readonly */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "readonly"); + } + else if (flags & 256 /* Async */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "async"); + } + else if (node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 279 /* SourceFile */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, text); + } + else if (flags & 128 /* Abstract */) { + if (modifier.kind === 113 /* PrivateKeyword */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, text, "abstract"); + } + else { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "abstract"); + } + } + flags |= ts.modifierToFlag(modifier.kind); + break; + case 116 /* StaticKeyword */: + if (flags & 32 /* Static */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "static"); + } + else if (flags & 64 /* Readonly */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "readonly"); + } + else if (flags & 256 /* Async */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "async"); + } + else if (node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 279 /* SourceFile */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, "static"); + } + else if (node.kind === 151 /* Parameter */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "static"); + } + else if (flags & 128 /* Abstract */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "abstract"); + } + flags |= 32 /* Static */; + lastStatic = modifier; + break; + case 133 /* ReadonlyKeyword */: + if (flags & 64 /* Readonly */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "readonly"); + } + else if (node.kind !== 154 /* PropertyDeclaration */ && node.kind !== 153 /* PropertySignature */ && node.kind !== 162 /* IndexSignature */ && node.kind !== 151 /* Parameter */) { + // If node.kind === SyntaxKind.Parameter, checkParameter report an error if it's not a parameter property. + return grammarErrorOnNode(modifier, ts.Diagnostics.readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature); + } + flags |= 64 /* Readonly */; + lastReadonly = modifier; + break; + case 85 /* ExportKeyword */: + if (flags & 1 /* Export */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "export"); + } + else if (flags & 2 /* Ambient */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "declare"); + } + else if (flags & 128 /* Abstract */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "abstract"); + } + else if (flags & 256 /* Async */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "async"); + } + else if (node.parent.kind === 240 /* ClassDeclaration */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_class_element, "export"); + } + else if (node.kind === 151 /* Parameter */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "export"); + } + flags |= 1 /* Export */; + break; + case 80 /* DefaultKeyword */: + var container = node.parent.kind === 279 /* SourceFile */ ? node.parent : node.parent.parent; + if (container.kind === 244 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) { + return grammarErrorOnNode(modifier, ts.Diagnostics.A_default_export_can_only_be_used_in_an_ECMAScript_style_module); + } + flags |= 512 /* Default */; + break; + case 125 /* DeclareKeyword */: + if (flags & 2 /* Ambient */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "declare"); + } + else if (flags & 256 /* Async */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async"); + } + else if (node.parent.kind === 240 /* ClassDeclaration */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_class_element, "declare"); + } + else if (node.kind === 151 /* Parameter */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "declare"); + } + else if ((node.parent.flags & 4194304 /* Ambient */) && node.parent.kind === 245 /* ModuleBlock */) { + return grammarErrorOnNode(modifier, ts.Diagnostics.A_declare_modifier_cannot_be_used_in_an_already_ambient_context); + } + flags |= 2 /* Ambient */; + lastDeclare = modifier; + break; + case 118 /* AbstractKeyword */: + if (flags & 128 /* Abstract */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "abstract"); + } + if (node.kind !== 240 /* ClassDeclaration */) { + if (node.kind !== 156 /* MethodDeclaration */ && + node.kind !== 154 /* PropertyDeclaration */ && + node.kind !== 158 /* GetAccessor */ && + node.kind !== 159 /* SetAccessor */) { + return grammarErrorOnNode(modifier, ts.Diagnostics.abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration); + } + if (!(node.parent.kind === 240 /* ClassDeclaration */ && ts.hasModifier(node.parent, 128 /* Abstract */))) { + return grammarErrorOnNode(modifier, ts.Diagnostics.Abstract_methods_can_only_appear_within_an_abstract_class); + } + if (flags & 32 /* Static */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "abstract"); + } + if (flags & 8 /* Private */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "private", "abstract"); + } + } + flags |= 128 /* Abstract */; + break; + case 121 /* AsyncKeyword */: + if (flags & 256 /* Async */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "async"); + } + else if (flags & 2 /* Ambient */ || node.parent.flags & 4194304 /* Ambient */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async"); + } + else if (node.kind === 151 /* Parameter */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "async"); + } + flags |= 256 /* Async */; + lastAsync = modifier; + break; + } + } + if (node.kind === 157 /* Constructor */) { + if (flags & 32 /* Static */) { + return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "static"); + } + if (flags & 128 /* Abstract */) { + return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "abstract"); // TODO: GH#18217 + } + else if (flags & 256 /* Async */) { + return grammarErrorOnNode(lastAsync, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "async"); + } + else if (flags & 64 /* Readonly */) { + return grammarErrorOnNode(lastReadonly, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "readonly"); + } + return false; + } + else if ((node.kind === 249 /* ImportDeclaration */ || node.kind === 248 /* ImportEqualsDeclaration */) && flags & 2 /* Ambient */) { + return grammarErrorOnNode(lastDeclare, ts.Diagnostics.A_0_modifier_cannot_be_used_with_an_import_declaration, "declare"); + } + else if (node.kind === 151 /* Parameter */ && (flags & 92 /* ParameterPropertyModifier */) && ts.isBindingPattern(node.name)) { + return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_may_not_be_declared_using_a_binding_pattern); + } + else if (node.kind === 151 /* Parameter */ && (flags & 92 /* ParameterPropertyModifier */) && node.dotDotDotToken) { + return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_cannot_be_declared_using_a_rest_parameter); + } + if (flags & 256 /* Async */) { + return checkGrammarAsyncModifier(node, lastAsync); + } + return false; + } + /** + * true | false: Early return this value from checkGrammarModifiers. + * undefined: Need to do full checking on the modifiers. + */ + function reportObviousModifierErrors(node) { + return !node.modifiers + ? false + : shouldReportBadModifier(node) + ? grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here) + : undefined; + } + function shouldReportBadModifier(node) { + switch (node.kind) { + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 157 /* Constructor */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 162 /* IndexSignature */: + case 244 /* ModuleDeclaration */: + case 249 /* ImportDeclaration */: + case 248 /* ImportEqualsDeclaration */: + case 255 /* ExportDeclaration */: + case 254 /* ExportAssignment */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 151 /* Parameter */: + return false; + default: + if (node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 279 /* SourceFile */) { + return false; + } + switch (node.kind) { + case 239 /* FunctionDeclaration */: + return nodeHasAnyModifiersExcept(node, 121 /* AsyncKeyword */); + case 240 /* ClassDeclaration */: + return nodeHasAnyModifiersExcept(node, 118 /* AbstractKeyword */); + case 241 /* InterfaceDeclaration */: + case 219 /* VariableStatement */: + case 242 /* TypeAliasDeclaration */: + return true; + case 243 /* EnumDeclaration */: + return nodeHasAnyModifiersExcept(node, 77 /* ConstKeyword */); + default: + ts.Debug.fail(); + return false; + } + } + } + function nodeHasAnyModifiersExcept(node, allowedModifier) { + return node.modifiers.length > 1 || node.modifiers[0].kind !== allowedModifier; + } + function checkGrammarAsyncModifier(node, asyncModifier) { + switch (node.kind) { + case 156 /* MethodDeclaration */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + return false; + } + return grammarErrorOnNode(asyncModifier, ts.Diagnostics._0_modifier_cannot_be_used_here, "async"); + } + function checkGrammarForDisallowedTrailingComma(list, diag) { + if (diag === void 0) { diag = ts.Diagnostics.Trailing_comma_not_allowed; } + if (list && list.hasTrailingComma) { + return grammarErrorAtPos(list[0], list.end - ",".length, ",".length, diag); + } + return false; + } + function checkGrammarTypeParameterList(typeParameters, file) { + if (typeParameters && typeParameters.length === 0) { + var start = typeParameters.pos - "<".length; + var end = ts.skipTrivia(file.text, typeParameters.end) + ">".length; + return grammarErrorAtPos(file, start, end - start, ts.Diagnostics.Type_parameter_list_cannot_be_empty); + } + return false; + } + function checkGrammarParameterList(parameters) { + var seenOptionalParameter = false; + var parameterCount = parameters.length; + for (var i = 0; i < parameterCount; i++) { + var parameter = parameters[i]; + if (parameter.dotDotDotToken) { + if (i !== (parameterCount - 1)) { + return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.A_rest_parameter_must_be_last_in_a_parameter_list); + } + if (!(parameter.flags & 4194304 /* Ambient */)) { // Allow `...foo,` in ambient declarations; see GH#23070 + checkGrammarForDisallowedTrailingComma(parameters, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma); + } + if (ts.isBindingPattern(parameter.name)) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.A_rest_element_cannot_contain_a_binding_pattern); + } + if (parameter.questionToken) { + return grammarErrorOnNode(parameter.questionToken, ts.Diagnostics.A_rest_parameter_cannot_be_optional); + } + if (parameter.initializer) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.A_rest_parameter_cannot_have_an_initializer); + } + } + else if (parameter.questionToken) { + seenOptionalParameter = true; + if (parameter.initializer) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.Parameter_cannot_have_question_mark_and_initializer); + } + } + else if (seenOptionalParameter && !parameter.initializer) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.A_required_parameter_cannot_follow_an_optional_parameter); + } + } + } + function getNonSimpleParameters(parameters) { + return ts.filter(parameters, function (parameter) { return !!parameter.initializer || ts.isBindingPattern(parameter.name) || ts.isRestParameter(parameter); }); + } + function checkGrammarForUseStrictSimpleParameterList(node) { + if (languageVersion >= 3 /* ES2016 */) { + var useStrictDirective_1 = node.body && ts.isBlock(node.body) && ts.findUseStrictPrologue(node.body.statements); + if (useStrictDirective_1) { + var nonSimpleParameters = getNonSimpleParameters(node.parameters); + if (ts.length(nonSimpleParameters)) { + ts.forEach(nonSimpleParameters, function (parameter) { + addRelatedInfo(error(parameter, ts.Diagnostics.This_parameter_is_not_allowed_with_use_strict_directive), ts.createDiagnosticForNode(useStrictDirective_1, ts.Diagnostics.use_strict_directive_used_here)); + }); + var diagnostics_1 = nonSimpleParameters.map(function (parameter, index) { return (index === 0 ? ts.createDiagnosticForNode(parameter, ts.Diagnostics.Non_simple_parameter_declared_here) : ts.createDiagnosticForNode(parameter, ts.Diagnostics.and_here)); }); + addRelatedInfo.apply(void 0, [error(useStrictDirective_1, ts.Diagnostics.use_strict_directive_cannot_be_used_with_non_simple_parameter_list)].concat(diagnostics_1)); + return true; + } + } + } + return false; + } + function checkGrammarFunctionLikeDeclaration(node) { + // Prevent cascading error by short-circuit + var file = ts.getSourceFileOfNode(node); + return checkGrammarDecoratorsAndModifiers(node) || checkGrammarTypeParameterList(node.typeParameters, file) || + checkGrammarParameterList(node.parameters) || checkGrammarArrowFunction(node, file) || + (ts.isFunctionLikeDeclaration(node) && checkGrammarForUseStrictSimpleParameterList(node)); + } + function checkGrammarClassLikeDeclaration(node) { + var file = ts.getSourceFileOfNode(node); + return checkGrammarClassDeclarationHeritageClauses(node) || checkGrammarTypeParameterList(node.typeParameters, file); + } + function checkGrammarArrowFunction(node, file) { + if (!ts.isArrowFunction(node)) { + return false; + } + var equalsGreaterThanToken = node.equalsGreaterThanToken; + var startLine = ts.getLineAndCharacterOfPosition(file, equalsGreaterThanToken.pos).line; + var endLine = ts.getLineAndCharacterOfPosition(file, equalsGreaterThanToken.end).line; + return startLine !== endLine && grammarErrorOnNode(equalsGreaterThanToken, ts.Diagnostics.Line_terminator_not_permitted_before_arrow); + } + function checkGrammarIndexSignatureParameters(node) { + var parameter = node.parameters[0]; + if (node.parameters.length !== 1) { + if (parameter) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_must_have_exactly_one_parameter); + } + else { + return grammarErrorOnNode(node, ts.Diagnostics.An_index_signature_must_have_exactly_one_parameter); + } + } + if (parameter.dotDotDotToken) { + return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.An_index_signature_cannot_have_a_rest_parameter); + } + if (ts.hasModifiers(parameter)) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_cannot_have_an_accessibility_modifier); + } + if (parameter.questionToken) { + return grammarErrorOnNode(parameter.questionToken, ts.Diagnostics.An_index_signature_parameter_cannot_have_a_question_mark); + } + if (parameter.initializer) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_cannot_have_an_initializer); + } + if (!parameter.type) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_must_have_a_type_annotation); + } + if (parameter.type.kind !== 138 /* StringKeyword */ && parameter.type.kind !== 135 /* NumberKeyword */) { + var type = getTypeFromTypeNode(parameter.type); + if (type.flags & 4 /* String */ || type.flags & 8 /* Number */) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead, ts.getTextOfNode(parameter.name), typeToString(type), typeToString(getTypeFromTypeNode(node.type))); + } + if (type.flags & 1048576 /* Union */ && allTypesAssignableToKind(type, 128 /* StringLiteral */, /*strict*/ true)) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead); + } + return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_must_be_string_or_number); + } + if (!node.type) { + return grammarErrorOnNode(node, ts.Diagnostics.An_index_signature_must_have_a_type_annotation); + } + return false; + } + function checkGrammarIndexSignature(node) { + // Prevent cascading error by short-circuit + return checkGrammarDecoratorsAndModifiers(node) || checkGrammarIndexSignatureParameters(node); + } + function checkGrammarForAtLeastOneTypeArgument(node, typeArguments) { + if (typeArguments && typeArguments.length === 0) { + var sourceFile = ts.getSourceFileOfNode(node); + var start = typeArguments.pos - "<".length; + var end = ts.skipTrivia(sourceFile.text, typeArguments.end) + ">".length; + return grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.Type_argument_list_cannot_be_empty); + } + return false; + } + function checkGrammarTypeArguments(node, typeArguments) { + return checkGrammarForDisallowedTrailingComma(typeArguments) || + checkGrammarForAtLeastOneTypeArgument(node, typeArguments); + } + function checkGrammarForOmittedArgument(args) { + if (args) { + for (var _i = 0, args_5 = args; _i < args_5.length; _i++) { + var arg = args_5[_i]; + if (arg.kind === 210 /* OmittedExpression */) { + return grammarErrorAtPos(arg, arg.pos, 0, ts.Diagnostics.Argument_expression_expected); + } + } + } + return false; + } + function checkGrammarArguments(args) { + return checkGrammarForOmittedArgument(args); + } + function checkGrammarHeritageClause(node) { + var types = node.types; + if (checkGrammarForDisallowedTrailingComma(types)) { + return true; + } + if (types && types.length === 0) { + var listType = ts.tokenToString(node.token); + return grammarErrorAtPos(node, types.pos, 0, ts.Diagnostics._0_list_cannot_be_empty, listType); + } + return ts.some(types, checkGrammarExpressionWithTypeArguments); + } + function checkGrammarExpressionWithTypeArguments(node) { + return checkGrammarTypeArguments(node, node.typeArguments); + } + function checkGrammarClassDeclarationHeritageClauses(node) { + var seenExtendsClause = false; + var seenImplementsClause = false; + if (!checkGrammarDecoratorsAndModifiers(node) && node.heritageClauses) { + for (var _i = 0, _a = node.heritageClauses; _i < _a.length; _i++) { + var heritageClause = _a[_i]; + if (heritageClause.token === 86 /* ExtendsKeyword */) { + if (seenExtendsClause) { + return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.extends_clause_already_seen); + } + if (seenImplementsClause) { + return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.extends_clause_must_precede_implements_clause); + } + if (heritageClause.types.length > 1) { + return grammarErrorOnFirstToken(heritageClause.types[1], ts.Diagnostics.Classes_can_only_extend_a_single_class); + } + seenExtendsClause = true; + } + else { + ts.Debug.assert(heritageClause.token === 109 /* ImplementsKeyword */); + if (seenImplementsClause) { + return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.implements_clause_already_seen); + } + seenImplementsClause = true; + } + // Grammar checking heritageClause inside class declaration + checkGrammarHeritageClause(heritageClause); + } + } + } + function checkGrammarInterfaceDeclaration(node) { + var seenExtendsClause = false; + if (node.heritageClauses) { + for (var _i = 0, _a = node.heritageClauses; _i < _a.length; _i++) { + var heritageClause = _a[_i]; + if (heritageClause.token === 86 /* ExtendsKeyword */) { + if (seenExtendsClause) { + return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.extends_clause_already_seen); + } + seenExtendsClause = true; + } + else { + ts.Debug.assert(heritageClause.token === 109 /* ImplementsKeyword */); + return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.Interface_declaration_cannot_have_implements_clause); + } + // Grammar checking heritageClause inside class declaration + checkGrammarHeritageClause(heritageClause); + } + } + return false; + } + function checkGrammarComputedPropertyName(node) { + // If node is not a computedPropertyName, just skip the grammar checking + if (node.kind !== 149 /* ComputedPropertyName */) { + return false; + } + var computedPropertyName = node; + if (computedPropertyName.expression.kind === 204 /* BinaryExpression */ && computedPropertyName.expression.operatorToken.kind === 27 /* CommaToken */) { + return grammarErrorOnNode(computedPropertyName.expression, ts.Diagnostics.A_comma_expression_is_not_allowed_in_a_computed_property_name); + } + return false; + } + function checkGrammarForGenerator(node) { + if (node.asteriskToken) { + ts.Debug.assert(node.kind === 239 /* FunctionDeclaration */ || + node.kind === 196 /* FunctionExpression */ || + node.kind === 156 /* MethodDeclaration */); + if (node.flags & 4194304 /* Ambient */) { + return grammarErrorOnNode(node.asteriskToken, ts.Diagnostics.Generators_are_not_allowed_in_an_ambient_context); + } + if (!node.body) { + return grammarErrorOnNode(node.asteriskToken, ts.Diagnostics.An_overload_signature_cannot_be_declared_as_a_generator); + } + } + } + function checkGrammarForInvalidQuestionMark(questionToken, message) { + return !!questionToken && grammarErrorOnNode(questionToken, message); + } + function checkGrammarForInvalidExclamationToken(exclamationToken, message) { + return !!exclamationToken && grammarErrorOnNode(exclamationToken, message); + } + function checkGrammarObjectLiteralExpression(node, inDestructuring) { + var Flags; + (function (Flags) { + Flags[Flags["Property"] = 1] = "Property"; + Flags[Flags["GetAccessor"] = 2] = "GetAccessor"; + Flags[Flags["SetAccessor"] = 4] = "SetAccessor"; + Flags[Flags["GetOrSetAccessor"] = 6] = "GetOrSetAccessor"; + })(Flags || (Flags = {})); + var seen = ts.createUnderscoreEscapedMap(); + for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { + var prop = _a[_i]; + if (prop.kind === 277 /* SpreadAssignment */) { + continue; + } + var name = prop.name; + if (name.kind === 149 /* ComputedPropertyName */) { + // If the name is not a ComputedPropertyName, the grammar checking will skip it + checkGrammarComputedPropertyName(name); + } + if (prop.kind === 276 /* ShorthandPropertyAssignment */ && !inDestructuring && prop.objectAssignmentInitializer) { + // having objectAssignmentInitializer is only valid in ObjectAssignmentPattern + // outside of destructuring it is a syntax error + return grammarErrorOnNode(prop.equalsToken, ts.Diagnostics.can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment); + } + // Modifiers are never allowed on properties except for 'async' on a method declaration + if (prop.modifiers) { + for (var _b = 0, _c = prop.modifiers; _b < _c.length; _b++) { // TODO: GH#19955 + var mod = _c[_b]; + if (mod.kind !== 121 /* AsyncKeyword */ || prop.kind !== 156 /* MethodDeclaration */) { + grammarErrorOnNode(mod, ts.Diagnostics._0_modifier_cannot_be_used_here, ts.getTextOfNode(mod)); + } + } + } + // ECMA-262 11.1.5 Object Initializer + // If previous is not undefined then throw a SyntaxError exception if any of the following conditions are true + // a.This production is contained in strict code and IsDataDescriptor(previous) is true and + // IsDataDescriptor(propId.descriptor) is true. + // b.IsDataDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true. + // c.IsAccessorDescriptor(previous) is true and IsDataDescriptor(propId.descriptor) is true. + // d.IsAccessorDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true + // and either both previous and propId.descriptor have[[Get]] fields or both previous and propId.descriptor have[[Set]] fields + var currentKind = void 0; + switch (prop.kind) { + case 276 /* ShorthandPropertyAssignment */: + checkGrammarForInvalidExclamationToken(prop.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context); + /* tslint:disable:no-switch-case-fall-through */ + case 275 /* PropertyAssignment */: + // Grammar checking for computedPropertyName and shorthandPropertyAssignment + checkGrammarForInvalidQuestionMark(prop.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional); + if (name.kind === 8 /* NumericLiteral */) { + checkGrammarNumericLiteral(name); + } + // falls through + case 156 /* MethodDeclaration */: + currentKind = 1 /* Property */; + break; + case 158 /* GetAccessor */: + currentKind = 2 /* GetAccessor */; + break; + case 159 /* SetAccessor */: + currentKind = 4 /* SetAccessor */; + break; + default: + throw ts.Debug.assertNever(prop, "Unexpected syntax kind:" + prop.kind); + } + var effectiveName = ts.getPropertyNameForPropertyNameNode(name); + if (effectiveName === undefined) { + continue; + } + var existingKind = seen.get(effectiveName); + if (!existingKind) { + seen.set(effectiveName, currentKind); + } + else { + if (currentKind === 1 /* Property */ && existingKind === 1 /* Property */) { + grammarErrorOnNode(name, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(name)); + } + else if ((currentKind & 6 /* GetOrSetAccessor */) && (existingKind & 6 /* GetOrSetAccessor */)) { + if (existingKind !== 6 /* GetOrSetAccessor */ && currentKind !== existingKind) { + seen.set(effectiveName, currentKind | existingKind); + } + else { + return grammarErrorOnNode(name, ts.Diagnostics.An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name); + } + } + else { + return grammarErrorOnNode(name, ts.Diagnostics.An_object_literal_cannot_have_property_and_accessor_with_the_same_name); + } + } + } + } + function checkGrammarJsxElement(node) { + checkGrammarTypeArguments(node, node.typeArguments); + var seen = ts.createUnderscoreEscapedMap(); + for (var _i = 0, _a = node.attributes.properties; _i < _a.length; _i++) { + var attr = _a[_i]; + if (attr.kind === 269 /* JsxSpreadAttribute */) { + continue; + } + var name = attr.name, initializer = attr.initializer; + if (!seen.get(name.escapedText)) { + seen.set(name.escapedText, true); + } + else { + return grammarErrorOnNode(name, ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name); + } + if (initializer && initializer.kind === 270 /* JsxExpression */ && !initializer.expression) { + return grammarErrorOnNode(initializer, ts.Diagnostics.JSX_attributes_must_only_be_assigned_a_non_empty_expression); + } + } + } + function checkGrammarForInOrForOfStatement(forInOrOfStatement) { + if (checkGrammarStatementInAmbientContext(forInOrOfStatement)) { + return true; + } + if (forInOrOfStatement.kind === 227 /* ForOfStatement */ && forInOrOfStatement.awaitModifier) { + if ((forInOrOfStatement.flags & 16384 /* AwaitContext */) === 0 /* None */) { + return grammarErrorOnNode(forInOrOfStatement.awaitModifier, ts.Diagnostics.A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator); + } + } + if (forInOrOfStatement.initializer.kind === 238 /* VariableDeclarationList */) { + var variableList = forInOrOfStatement.initializer; + if (!checkGrammarVariableDeclarationList(variableList)) { + var declarations = variableList.declarations; + // declarations.length can be zero if there is an error in variable declaration in for-of or for-in + // See http://www.ecma-international.org/ecma-262/6.0/#sec-for-in-and-for-of-statements for details + // For example: + // var let = 10; + // for (let of [1,2,3]) {} // this is invalid ES6 syntax + // for (let in [1,2,3]) {} // this is invalid ES6 syntax + // We will then want to skip on grammar checking on variableList declaration + if (!declarations.length) { + return false; + } + if (declarations.length > 1) { + var diagnostic = forInOrOfStatement.kind === 226 /* ForInStatement */ + ? ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement + : ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement; + return grammarErrorOnFirstToken(variableList.declarations[1], diagnostic); + } + var firstDeclaration = declarations[0]; + if (firstDeclaration.initializer) { + var diagnostic = forInOrOfStatement.kind === 226 /* ForInStatement */ + ? ts.Diagnostics.The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer + : ts.Diagnostics.The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer; + return grammarErrorOnNode(firstDeclaration.name, diagnostic); + } + if (firstDeclaration.type) { + var diagnostic = forInOrOfStatement.kind === 226 /* ForInStatement */ + ? ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation + : ts.Diagnostics.The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation; + return grammarErrorOnNode(firstDeclaration, diagnostic); + } + } + } + return false; + } + function checkGrammarAccessor(accessor) { + var kind = accessor.kind; + if (languageVersion < 1 /* ES5 */) { + return grammarErrorOnNode(accessor.name, ts.Diagnostics.Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher); + } + else if (accessor.flags & 4194304 /* Ambient */) { + return grammarErrorOnNode(accessor.name, ts.Diagnostics.An_accessor_cannot_be_declared_in_an_ambient_context); + } + else if (accessor.body === undefined && !ts.hasModifier(accessor, 128 /* Abstract */)) { + return grammarErrorAtPos(accessor, accessor.end - 1, ";".length, ts.Diagnostics._0_expected, "{"); + } + else if (accessor.body && ts.hasModifier(accessor, 128 /* Abstract */)) { + return grammarErrorOnNode(accessor, ts.Diagnostics.An_abstract_accessor_cannot_have_an_implementation); + } + else if (accessor.typeParameters) { + return grammarErrorOnNode(accessor.name, ts.Diagnostics.An_accessor_cannot_have_type_parameters); + } + else if (!doesAccessorHaveCorrectParameterCount(accessor)) { + return grammarErrorOnNode(accessor.name, kind === 158 /* GetAccessor */ ? + ts.Diagnostics.A_get_accessor_cannot_have_parameters : + ts.Diagnostics.A_set_accessor_must_have_exactly_one_parameter); + } + else if (kind === 159 /* SetAccessor */) { + if (accessor.type) { + return grammarErrorOnNode(accessor.name, ts.Diagnostics.A_set_accessor_cannot_have_a_return_type_annotation); + } + else { + var parameter = accessor.parameters[0]; + if (parameter.dotDotDotToken) { + return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.A_set_accessor_cannot_have_rest_parameter); + } + else if (parameter.questionToken) { + return grammarErrorOnNode(parameter.questionToken, ts.Diagnostics.A_set_accessor_cannot_have_an_optional_parameter); + } + else if (parameter.initializer) { + return grammarErrorOnNode(accessor.name, ts.Diagnostics.A_set_accessor_parameter_cannot_have_an_initializer); + } + } + } + return false; + } + /** Does the accessor have the right number of parameters? + * A get accessor has no parameters or a single `this` parameter. + * A set accessor has one parameter or a `this` parameter and one more parameter. + */ + function doesAccessorHaveCorrectParameterCount(accessor) { + return getAccessorThisParameter(accessor) || accessor.parameters.length === (accessor.kind === 158 /* GetAccessor */ ? 0 : 1); + } + function getAccessorThisParameter(accessor) { + if (accessor.parameters.length === (accessor.kind === 158 /* GetAccessor */ ? 1 : 2)) { + return ts.getThisParameter(accessor); + } + } + function checkGrammarTypeOperatorNode(node) { + if (node.operator === 142 /* UniqueKeyword */) { + if (node.type.kind !== 139 /* SymbolKeyword */) { + return grammarErrorOnNode(node.type, ts.Diagnostics._0_expected, ts.tokenToString(139 /* SymbolKeyword */)); + } + var parent = ts.walkUpParenthesizedTypes(node.parent); + switch (parent.kind) { + case 237 /* VariableDeclaration */: + var decl = parent; + if (decl.name.kind !== 72 /* Identifier */) { + return grammarErrorOnNode(node, ts.Diagnostics.unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name); + } + if (!ts.isVariableDeclarationInVariableStatement(decl)) { + return grammarErrorOnNode(node, ts.Diagnostics.unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement); + } + if (!(decl.parent.flags & 2 /* Const */)) { + return grammarErrorOnNode(parent.name, ts.Diagnostics.A_variable_whose_type_is_a_unique_symbol_type_must_be_const); + } + break; + case 154 /* PropertyDeclaration */: + if (!ts.hasModifier(parent, 32 /* Static */) || + !ts.hasModifier(parent, 64 /* Readonly */)) { + return grammarErrorOnNode(parent.name, ts.Diagnostics.A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly); + } + break; + case 153 /* PropertySignature */: + if (!ts.hasModifier(parent, 64 /* Readonly */)) { + return grammarErrorOnNode(parent.name, ts.Diagnostics.A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly); + } + break; + default: + return grammarErrorOnNode(node, ts.Diagnostics.unique_symbol_types_are_not_allowed_here); + } + } + } + function checkGrammarForInvalidDynamicName(node, message) { + if (isNonBindableDynamicName(node)) { + return grammarErrorOnNode(node, message); + } + } + function checkGrammarMethod(node) { + if (checkGrammarFunctionLikeDeclaration(node)) { + return true; + } + if (node.kind === 156 /* MethodDeclaration */) { + if (node.parent.kind === 188 /* ObjectLiteralExpression */) { + // We only disallow modifier on a method declaration if it is a property of object-literal-expression + if (node.modifiers && !(node.modifiers.length === 1 && ts.first(node.modifiers).kind === 121 /* AsyncKeyword */)) { + return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); + } + else if (checkGrammarForInvalidQuestionMark(node.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional)) { + return true; + } + else if (checkGrammarForInvalidExclamationToken(node.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context)) { + return true; + } + else if (node.body === undefined) { + return grammarErrorAtPos(node, node.end - 1, ";".length, ts.Diagnostics._0_expected, "{"); + } + } + if (checkGrammarForGenerator(node)) { + return true; + } + } + if (ts.isClassLike(node.parent)) { + // Technically, computed properties in ambient contexts is disallowed + // for property declarations and accessors too, not just methods. + // However, property declarations disallow computed names in general, + // and accessors are not allowed in ambient contexts in general, + // so this error only really matters for methods. + if (node.flags & 4194304 /* Ambient */) { + return checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type); + } + else if (node.kind === 156 /* MethodDeclaration */ && !node.body) { + return checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type); + } + } + else if (node.parent.kind === 241 /* InterfaceDeclaration */) { + return checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type); + } + else if (node.parent.kind === 168 /* TypeLiteral */) { + return checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type); + } + } + function checkGrammarBreakOrContinueStatement(node) { + var current = node; + while (current) { + if (ts.isFunctionLike(current)) { + return grammarErrorOnNode(node, ts.Diagnostics.Jump_target_cannot_cross_function_boundary); + } + switch (current.kind) { + case 233 /* LabeledStatement */: + if (node.label && current.label.escapedText === node.label.escapedText) { + // found matching label - verify that label usage is correct + // continue can only target labels that are on iteration statements + var isMisplacedContinueLabel = node.kind === 228 /* ContinueStatement */ + && !ts.isIterationStatement(current.statement, /*lookInLabeledStatement*/ true); + if (isMisplacedContinueLabel) { + return grammarErrorOnNode(node, ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement); + } + return false; + } + break; + case 232 /* SwitchStatement */: + if (node.kind === 229 /* BreakStatement */ && !node.label) { + // unlabeled break within switch statement - ok + return false; + } + break; + default: + if (ts.isIterationStatement(current, /*lookInLabeledStatement*/ false) && !node.label) { + // unlabeled break or continue within iteration statement - ok + return false; + } + break; + } + current = current.parent; + } + if (node.label) { + var message = node.kind === 229 /* BreakStatement */ + ? ts.Diagnostics.A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement + : ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement; + return grammarErrorOnNode(node, message); + } + else { + var message = node.kind === 229 /* BreakStatement */ + ? ts.Diagnostics.A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement + : ts.Diagnostics.A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement; + return grammarErrorOnNode(node, message); + } + } + function checkGrammarBindingElement(node) { + if (node.dotDotDotToken) { + var elements = node.parent.elements; + if (node !== ts.last(elements)) { + return grammarErrorOnNode(node, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern); + } + checkGrammarForDisallowedTrailingComma(elements, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma); + if (node.propertyName) { + return grammarErrorOnNode(node.name, ts.Diagnostics.A_rest_element_cannot_have_a_property_name); + } + if (node.initializer) { + // Error on equals token which immediately precedes the initializer + return grammarErrorAtPos(node, node.initializer.pos - 1, 1, ts.Diagnostics.A_rest_element_cannot_have_an_initializer); + } + } + } + function isStringOrNumberLiteralExpression(expr) { + return expr.kind === 10 /* StringLiteral */ || expr.kind === 8 /* NumericLiteral */ || + expr.kind === 202 /* PrefixUnaryExpression */ && expr.operator === 39 /* MinusToken */ && + expr.operand.kind === 8 /* NumericLiteral */; + } + function isBigIntLiteralExpression(expr) { + return expr.kind === 9 /* BigIntLiteral */ || + expr.kind === 202 /* PrefixUnaryExpression */ && expr.operator === 39 /* MinusToken */ && + expr.operand.kind === 9 /* BigIntLiteral */; + } + function isSimpleLiteralEnumReference(expr) { + if ((ts.isPropertyAccessExpression(expr) || (ts.isElementAccessExpression(expr) && isStringOrNumberLiteralExpression(expr.argumentExpression))) && + ts.isEntityNameExpression(expr.expression)) + return !!(checkExpressionCached(expr).flags & 1024 /* EnumLiteral */); + } + function checkAmbientInitializer(node) { + var initializer = node.initializer; + if (initializer) { + var isInvalidInitializer = !(isStringOrNumberLiteralExpression(initializer) || + isSimpleLiteralEnumReference(initializer) || + initializer.kind === 102 /* TrueKeyword */ || initializer.kind === 87 /* FalseKeyword */ || + isBigIntLiteralExpression(initializer)); + var isConstOrReadonly = ts.isDeclarationReadonly(node) || ts.isVariableDeclaration(node) && ts.isVarConst(node); + if (isConstOrReadonly && !node.type) { + if (isInvalidInitializer) { + return grammarErrorOnNode(initializer, ts.Diagnostics.A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_reference); + } + } + else { + return grammarErrorOnNode(initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); + } + if (!isConstOrReadonly || isInvalidInitializer) { + return grammarErrorOnNode(initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); + } + } + } + function checkGrammarVariableDeclaration(node) { + if (node.parent.parent.kind !== 226 /* ForInStatement */ && node.parent.parent.kind !== 227 /* ForOfStatement */) { + if (node.flags & 4194304 /* Ambient */) { + checkAmbientInitializer(node); + } + else if (!node.initializer) { + if (ts.isBindingPattern(node.name) && !ts.isBindingPattern(node.parent)) { + return grammarErrorOnNode(node, ts.Diagnostics.A_destructuring_declaration_must_have_an_initializer); + } + if (ts.isVarConst(node)) { + return grammarErrorOnNode(node, ts.Diagnostics.const_declarations_must_be_initialized); + } + } + } + if (node.exclamationToken && (node.parent.parent.kind !== 219 /* VariableStatement */ || !node.type || node.initializer || node.flags & 4194304 /* Ambient */)) { + return grammarErrorOnNode(node.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context); + } + if (compilerOptions.module !== ts.ModuleKind.ES2015 && compilerOptions.module !== ts.ModuleKind.ESNext && compilerOptions.module !== ts.ModuleKind.System && !compilerOptions.noEmit && + !(node.parent.parent.flags & 4194304 /* Ambient */) && ts.hasModifier(node.parent.parent, 1 /* Export */)) { + checkESModuleMarker(node.name); + } + var checkLetConstNames = (ts.isLet(node) || ts.isVarConst(node)); + // 1. LexicalDeclaration : LetOrConst BindingList ; + // It is a Syntax Error if the BoundNames of BindingList contains "let". + // 2. ForDeclaration: ForDeclaration : LetOrConst ForBinding + // It is a Syntax Error if the BoundNames of ForDeclaration contains "let". + // It is a SyntaxError if a VariableDeclaration or VariableDeclarationNoIn occurs within strict code + // and its Identifier is eval or arguments + return checkLetConstNames && checkGrammarNameInLetOrConstDeclarations(node.name); + } + function checkESModuleMarker(name) { + if (name.kind === 72 /* Identifier */) { + if (ts.idText(name) === "__esModule") { + return grammarErrorOnNode(name, ts.Diagnostics.Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules); + } + } + else { + var elements = name.elements; + for (var _i = 0, elements_1 = elements; _i < elements_1.length; _i++) { + var element = elements_1[_i]; + if (!ts.isOmittedExpression(element)) { + return checkESModuleMarker(element.name); + } + } + } + return false; + } + function checkGrammarNameInLetOrConstDeclarations(name) { + if (name.kind === 72 /* Identifier */) { + if (name.originalKeywordKind === 111 /* LetKeyword */) { + return grammarErrorOnNode(name, ts.Diagnostics.let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations); + } + } + else { + var elements = name.elements; + for (var _i = 0, elements_2 = elements; _i < elements_2.length; _i++) { + var element = elements_2[_i]; + if (!ts.isOmittedExpression(element)) { + checkGrammarNameInLetOrConstDeclarations(element.name); + } + } + } + return false; + } + function checkGrammarVariableDeclarationList(declarationList) { + var declarations = declarationList.declarations; + if (checkGrammarForDisallowedTrailingComma(declarationList.declarations)) { + return true; + } + if (!declarationList.declarations.length) { + return grammarErrorAtPos(declarationList, declarations.pos, declarations.end - declarations.pos, ts.Diagnostics.Variable_declaration_list_cannot_be_empty); + } + return false; + } + function allowLetAndConstDeclarations(parent) { + switch (parent.kind) { + case 222 /* IfStatement */: + case 223 /* DoStatement */: + case 224 /* WhileStatement */: + case 231 /* WithStatement */: + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + return false; + case 233 /* LabeledStatement */: + return allowLetAndConstDeclarations(parent.parent); + } + return true; + } + function checkGrammarForDisallowedLetOrConstStatement(node) { + if (!allowLetAndConstDeclarations(node.parent)) { + if (ts.isLet(node.declarationList)) { + return grammarErrorOnNode(node, ts.Diagnostics.let_declarations_can_only_be_declared_inside_a_block); + } + else if (ts.isVarConst(node.declarationList)) { + return grammarErrorOnNode(node, ts.Diagnostics.const_declarations_can_only_be_declared_inside_a_block); + } + } + } + function checkGrammarMetaProperty(node) { + var escapedText = node.name.escapedText; + switch (node.keywordToken) { + case 95 /* NewKeyword */: + if (escapedText !== "target") { + return grammarErrorOnNode(node.name, ts.Diagnostics._0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2, node.name.escapedText, ts.tokenToString(node.keywordToken), "target"); + } + break; + case 92 /* ImportKeyword */: + if (escapedText !== "meta") { + return grammarErrorOnNode(node.name, ts.Diagnostics._0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2, node.name.escapedText, ts.tokenToString(node.keywordToken), "meta"); + } + break; + } + } + function hasParseDiagnostics(sourceFile) { + return sourceFile.parseDiagnostics.length > 0; + } + function grammarErrorOnFirstToken(node, message, arg0, arg1, arg2) { + var sourceFile = ts.getSourceFileOfNode(node); + if (!hasParseDiagnostics(sourceFile)) { + var span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos); + diagnostics.add(ts.createFileDiagnostic(sourceFile, span.start, span.length, message, arg0, arg1, arg2)); + return true; + } + return false; + } + function grammarErrorAtPos(nodeForSourceFile, start, length, message, arg0, arg1, arg2) { + var sourceFile = ts.getSourceFileOfNode(nodeForSourceFile); + if (!hasParseDiagnostics(sourceFile)) { + diagnostics.add(ts.createFileDiagnostic(sourceFile, start, length, message, arg0, arg1, arg2)); + return true; + } + return false; + } + function grammarErrorOnNode(node, message, arg0, arg1, arg2) { + var sourceFile = ts.getSourceFileOfNode(node); + if (!hasParseDiagnostics(sourceFile)) { + diagnostics.add(ts.createDiagnosticForNode(node, message, arg0, arg1, arg2)); + return true; + } + return false; + } + function checkGrammarConstructorTypeParameters(node) { + var jsdocTypeParameters = ts.isInJSFile(node) ? ts.getJSDocTypeParameterDeclarations(node) : undefined; + var range = node.typeParameters || jsdocTypeParameters && ts.firstOrUndefined(jsdocTypeParameters); + if (range) { + var pos = range.pos === range.end ? range.pos : ts.skipTrivia(ts.getSourceFileOfNode(node).text, range.pos); + return grammarErrorAtPos(node, pos, range.end - pos, ts.Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration); + } + } + function checkGrammarConstructorTypeAnnotation(node) { + var type = ts.getEffectiveReturnTypeNode(node); + if (type) { + return grammarErrorOnNode(type, ts.Diagnostics.Type_annotation_cannot_appear_on_a_constructor_declaration); + } + } + function checkGrammarProperty(node) { + if (ts.isClassLike(node.parent)) { + if (checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_class_property_declaration_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type)) { + return true; + } + } + else if (node.parent.kind === 241 /* InterfaceDeclaration */) { + if (checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type)) { + return true; + } + if (node.initializer) { + return grammarErrorOnNode(node.initializer, ts.Diagnostics.An_interface_property_cannot_have_an_initializer); + } + } + else if (node.parent.kind === 168 /* TypeLiteral */) { + if (checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type)) { + return true; + } + if (node.initializer) { + return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_type_literal_property_cannot_have_an_initializer); + } + } + if (node.flags & 4194304 /* Ambient */) { + checkAmbientInitializer(node); + } + if (ts.isPropertyDeclaration(node) && node.exclamationToken && (!ts.isClassLike(node.parent) || !node.type || node.initializer || + node.flags & 4194304 /* Ambient */ || ts.hasModifier(node, 32 /* Static */ | 128 /* Abstract */))) { + return grammarErrorOnNode(node.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context); + } + } + function checkGrammarTopLevelElementForRequiredDeclareModifier(node) { + // A declare modifier is required for any top level .d.ts declaration except export=, export default, export as namespace + // interfaces and imports categories: + // + // DeclarationElement: + // ExportAssignment + // export_opt InterfaceDeclaration + // export_opt TypeAliasDeclaration + // export_opt ImportDeclaration + // export_opt ExternalImportDeclaration + // export_opt AmbientDeclaration + // + // TODO: The spec needs to be amended to reflect this grammar. + if (node.kind === 241 /* InterfaceDeclaration */ || + node.kind === 242 /* TypeAliasDeclaration */ || + node.kind === 249 /* ImportDeclaration */ || + node.kind === 248 /* ImportEqualsDeclaration */ || + node.kind === 255 /* ExportDeclaration */ || + node.kind === 254 /* ExportAssignment */ || + node.kind === 247 /* NamespaceExportDeclaration */ || + ts.hasModifier(node, 2 /* Ambient */ | 1 /* Export */ | 512 /* Default */)) { + return false; + } + return grammarErrorOnFirstToken(node, ts.Diagnostics.A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file); + } + function checkGrammarTopLevelElementsForRequiredDeclareModifier(file) { + for (var _i = 0, _a = file.statements; _i < _a.length; _i++) { + var decl = _a[_i]; + if (ts.isDeclaration(decl) || decl.kind === 219 /* VariableStatement */) { + if (checkGrammarTopLevelElementForRequiredDeclareModifier(decl)) { + return true; + } + } + } + return false; + } + function checkGrammarSourceFile(node) { + return !!(node.flags & 4194304 /* Ambient */) && checkGrammarTopLevelElementsForRequiredDeclareModifier(node); + } + function checkGrammarStatementInAmbientContext(node) { + if (node.flags & 4194304 /* Ambient */) { + // An accessors is already reported about the ambient context + if (ts.isAccessor(node.parent)) { + return getNodeLinks(node).hasReportedStatementInAmbientContext = true; + } + // Find containing block which is either Block, ModuleBlock, SourceFile + var links = getNodeLinks(node); + if (!links.hasReportedStatementInAmbientContext && ts.isFunctionLike(node.parent)) { + return getNodeLinks(node).hasReportedStatementInAmbientContext = grammarErrorOnFirstToken(node, ts.Diagnostics.An_implementation_cannot_be_declared_in_ambient_contexts); + } + // We are either parented by another statement, or some sort of block. + // If we're in a block, we only want to really report an error once + // to prevent noisiness. So use a bit on the block to indicate if + // this has already been reported, and don't report if it has. + // + if (node.parent.kind === 218 /* Block */ || node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 279 /* SourceFile */) { + var links_2 = getNodeLinks(node.parent); + // Check if the containing block ever report this error + if (!links_2.hasReportedStatementInAmbientContext) { + return links_2.hasReportedStatementInAmbientContext = grammarErrorOnFirstToken(node, ts.Diagnostics.Statements_are_not_allowed_in_ambient_contexts); + } + } + else { + // We must be parented by a statement. If so, there's no need + // to report the error as our parent will have already done it. + // Debug.assert(isStatement(node.parent)); + } + } + return false; + } + function checkGrammarNumericLiteral(node) { + // Grammar checking + if (node.numericLiteralFlags & 32 /* Octal */) { + var diagnosticMessage = void 0; + if (languageVersion >= 1 /* ES5 */) { + diagnosticMessage = ts.Diagnostics.Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0; + } + else if (ts.isChildOfNodeWithKind(node, 182 /* LiteralType */)) { + diagnosticMessage = ts.Diagnostics.Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0; + } + else if (ts.isChildOfNodeWithKind(node, 278 /* EnumMember */)) { + diagnosticMessage = ts.Diagnostics.Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0; + } + if (diagnosticMessage) { + var withMinus = ts.isPrefixUnaryExpression(node.parent) && node.parent.operator === 39 /* MinusToken */; + var literal = (withMinus ? "-" : "") + "0o" + node.text; + return grammarErrorOnNode(withMinus ? node.parent : node, diagnosticMessage, literal); + } + } + return false; + } + function checkGrammarBigIntLiteral(node) { + var literalType = ts.isLiteralTypeNode(node.parent) || + ts.isPrefixUnaryExpression(node.parent) && ts.isLiteralTypeNode(node.parent.parent); + if (!literalType) { + if (languageVersion < 6 /* ESNext */) { + if (grammarErrorOnNode(node, ts.Diagnostics.BigInt_literals_are_not_available_when_targeting_lower_than_ESNext)) { + return true; + } + } + } + return false; + } + function grammarErrorAfterFirstToken(node, message, arg0, arg1, arg2) { + var sourceFile = ts.getSourceFileOfNode(node); + if (!hasParseDiagnostics(sourceFile)) { + var span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos); + diagnostics.add(ts.createFileDiagnostic(sourceFile, ts.textSpanEnd(span), /*length*/ 0, message, arg0, arg1, arg2)); + return true; + } + return false; + } + function getAmbientModules() { + if (!ambientModulesCache) { + ambientModulesCache = []; + globals.forEach(function (global, sym) { + // No need to `unescapeLeadingUnderscores`, an escaped symbol is never an ambient module. + if (ambientModuleSymbolRegex.test(sym)) { + ambientModulesCache.push(global); + } + }); + } + return ambientModulesCache; + } + function checkGrammarImportCallExpression(node) { + if (moduleKind === ts.ModuleKind.ES2015) { + return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext); + } + if (node.typeArguments) { + return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_import_cannot_have_type_arguments); + } + var nodeArguments = node.arguments; + if (nodeArguments.length !== 1) { + return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_import_must_have_one_specifier_as_an_argument); + } + // see: parseArgumentOrArrayLiteralElement...we use this function which parse arguments of callExpression to parse specifier for dynamic import. + // parseArgumentOrArrayLiteralElement allows spread element to be in an argument list which is not allowed as specifier in dynamic import. + if (ts.isSpreadElement(nodeArguments[0])) { + return grammarErrorOnNode(nodeArguments[0], ts.Diagnostics.Specifier_of_dynamic_import_cannot_be_spread_element); + } + return false; + } + } + ts.createTypeChecker = createTypeChecker; + /** Like 'isDeclarationName', but returns true for LHS of `import { x as y }` or `export { x as y }`. */ + function isDeclarationNameOrImportPropertyName(name) { + switch (name.parent.kind) { + case 253 /* ImportSpecifier */: + case 257 /* ExportSpecifier */: + return ts.isIdentifier(name); + default: + return ts.isDeclarationName(name); + } + } + function isSomeImportDeclaration(decl) { + switch (decl.kind) { + case 250 /* ImportClause */: // For default import + case 248 /* ImportEqualsDeclaration */: + case 251 /* NamespaceImport */: + case 253 /* ImportSpecifier */: // For rename import `x as y` + return true; + case 72 /* Identifier */: + // For regular import, `decl` is an Identifier under the ImportSpecifier. + return decl.parent.kind === 253 /* ImportSpecifier */; + default: + return false; + } + } + var JsxNames; + (function (JsxNames) { + // tslint:disable variable-name + JsxNames.JSX = "JSX"; + JsxNames.IntrinsicElements = "IntrinsicElements"; + JsxNames.ElementClass = "ElementClass"; + JsxNames.ElementAttributesPropertyNameContainer = "ElementAttributesProperty"; // TODO: Deprecate and remove support + JsxNames.ElementChildrenAttributeNameContainer = "ElementChildrenAttribute"; + JsxNames.Element = "Element"; + JsxNames.IntrinsicAttributes = "IntrinsicAttributes"; + JsxNames.IntrinsicClassAttributes = "IntrinsicClassAttributes"; + JsxNames.LibraryManagedAttributes = "LibraryManagedAttributes"; + // tslint:enable variable-name + })(JsxNames || (JsxNames = {})); + function typeIsLiteralType(type) { + return !!(type.flags & 2944 /* Literal */); + } +})(ts || (ts = {})); +var ts; +(function (ts) { + function createSynthesizedNode(kind) { + var node = ts.createNode(kind, -1, -1); + node.flags |= 8 /* Synthesized */; + return node; + } + /* @internal */ + function updateNode(updated, original) { + if (updated !== original) { + setOriginalNode(updated, original); + setTextRange(updated, original); + ts.aggregateTransformFlags(updated); + } + return updated; + } + ts.updateNode = updateNode; + /** + * Make `elements` into a `NodeArray`. If `elements` is `undefined`, returns an empty `NodeArray`. + */ + function createNodeArray(elements, hasTrailingComma) { + if (!elements || elements === ts.emptyArray) { + elements = []; + } + else if (ts.isNodeArray(elements)) { + return elements; + } + var array = elements; + array.pos = -1; + array.end = -1; + array.hasTrailingComma = hasTrailingComma; + return array; + } + ts.createNodeArray = createNodeArray; + /** + * Creates a shallow, memberwise clone of a node with no source map location. + */ + /* @internal */ + function getSynthesizedClone(node) { + // We don't use "clone" from core.ts here, as we need to preserve the prototype chain of + // the original node. We also need to exclude specific properties and only include own- + // properties (to skip members already defined on the shared prototype). + if (node === undefined) { + return node; + } + var clone = createSynthesizedNode(node.kind); + clone.flags |= node.flags; + setOriginalNode(clone, node); + for (var key in node) { + if (clone.hasOwnProperty(key) || !node.hasOwnProperty(key)) { + continue; + } + clone[key] = node[key]; + } + return clone; + } + ts.getSynthesizedClone = getSynthesizedClone; + function createLiteral(value, isSingleQuote) { + if (typeof value === "number") { + return createNumericLiteral(value + ""); + } + if (typeof value === "object" && "base10Value" in value) { // PseudoBigInt + return createBigIntLiteral(ts.pseudoBigIntToString(value) + "n"); + } + if (typeof value === "boolean") { + return value ? createTrue() : createFalse(); + } + if (ts.isString(value)) { + var res = createStringLiteral(value); + if (isSingleQuote) + res.singleQuote = true; + return res; + } + return createLiteralFromNode(value); + } + ts.createLiteral = createLiteral; + function createNumericLiteral(value) { + var node = createSynthesizedNode(8 /* NumericLiteral */); + node.text = value; + node.numericLiteralFlags = 0; + return node; + } + ts.createNumericLiteral = createNumericLiteral; + function createBigIntLiteral(value) { + var node = createSynthesizedNode(9 /* BigIntLiteral */); + node.text = value; + return node; + } + ts.createBigIntLiteral = createBigIntLiteral; + function createStringLiteral(text) { + var node = createSynthesizedNode(10 /* StringLiteral */); + node.text = text; + return node; + } + ts.createStringLiteral = createStringLiteral; + function createRegularExpressionLiteral(text) { + var node = createSynthesizedNode(13 /* RegularExpressionLiteral */); + node.text = text; + return node; + } + ts.createRegularExpressionLiteral = createRegularExpressionLiteral; + function createLiteralFromNode(sourceNode) { + var node = createStringLiteral(ts.getTextOfIdentifierOrLiteral(sourceNode)); + node.textSourceNode = sourceNode; + return node; + } + function createIdentifier(text, typeArguments) { + var node = createSynthesizedNode(72 /* Identifier */); + node.escapedText = ts.escapeLeadingUnderscores(text); + node.originalKeywordKind = text ? ts.stringToToken(text) : 0 /* Unknown */; + node.autoGenerateFlags = 0 /* None */; + node.autoGenerateId = 0; + if (typeArguments) { + node.typeArguments = createNodeArray(typeArguments); + } + return node; + } + ts.createIdentifier = createIdentifier; + function updateIdentifier(node, typeArguments) { + return node.typeArguments !== typeArguments + ? updateNode(createIdentifier(ts.idText(node), typeArguments), node) + : node; + } + ts.updateIdentifier = updateIdentifier; + var nextAutoGenerateId = 0; + function createTempVariable(recordTempVariable, reservedInNestedScopes) { + var name = createIdentifier(""); + name.autoGenerateFlags = 1 /* Auto */; + name.autoGenerateId = nextAutoGenerateId; + nextAutoGenerateId++; + if (recordTempVariable) { + recordTempVariable(name); + } + if (reservedInNestedScopes) { + name.autoGenerateFlags |= 8 /* ReservedInNestedScopes */; + } + return name; + } + ts.createTempVariable = createTempVariable; + /** Create a unique temporary variable for use in a loop. */ + function createLoopVariable() { + var name = createIdentifier(""); + name.autoGenerateFlags = 2 /* Loop */; + name.autoGenerateId = nextAutoGenerateId; + nextAutoGenerateId++; + return name; + } + ts.createLoopVariable = createLoopVariable; + /** Create a unique name based on the supplied text. */ + function createUniqueName(text) { + var name = createIdentifier(text); + name.autoGenerateFlags = 3 /* Unique */; + name.autoGenerateId = nextAutoGenerateId; + nextAutoGenerateId++; + return name; + } + ts.createUniqueName = createUniqueName; + function createOptimisticUniqueName(text) { + var name = createIdentifier(text); + name.autoGenerateFlags = 3 /* Unique */ | 16 /* Optimistic */; + name.autoGenerateId = nextAutoGenerateId; + nextAutoGenerateId++; + return name; + } + ts.createOptimisticUniqueName = createOptimisticUniqueName; + /** Create a unique name based on the supplied text. This does not consider names injected by the transformer. */ + function createFileLevelUniqueName(text) { + var name = createOptimisticUniqueName(text); + name.autoGenerateFlags |= 32 /* FileLevel */; + return name; + } + ts.createFileLevelUniqueName = createFileLevelUniqueName; + function getGeneratedNameForNode(node, flags) { + var name = createIdentifier(node && ts.isIdentifier(node) ? ts.idText(node) : ""); + name.autoGenerateFlags = 4 /* Node */ | flags; + name.autoGenerateId = nextAutoGenerateId; + name.original = node; + nextAutoGenerateId++; + return name; + } + ts.getGeneratedNameForNode = getGeneratedNameForNode; + // Punctuation + function createToken(token) { + return createSynthesizedNode(token); + } + ts.createToken = createToken; + // Reserved words + function createSuper() { + return createSynthesizedNode(98 /* SuperKeyword */); + } + ts.createSuper = createSuper; + function createThis() { + return createSynthesizedNode(100 /* ThisKeyword */); + } + ts.createThis = createThis; + function createNull() { + return createSynthesizedNode(96 /* NullKeyword */); + } + ts.createNull = createNull; + function createTrue() { + return createSynthesizedNode(102 /* TrueKeyword */); + } + ts.createTrue = createTrue; + function createFalse() { + return createSynthesizedNode(87 /* FalseKeyword */); + } + ts.createFalse = createFalse; + // Modifiers + function createModifier(kind) { + return createToken(kind); + } + ts.createModifier = createModifier; + function createModifiersFromModifierFlags(flags) { + var result = []; + if (flags & 1 /* Export */) { + result.push(createModifier(85 /* ExportKeyword */)); + } + if (flags & 2 /* Ambient */) { + result.push(createModifier(125 /* DeclareKeyword */)); + } + if (flags & 512 /* Default */) { + result.push(createModifier(80 /* DefaultKeyword */)); + } + if (flags & 2048 /* Const */) { + result.push(createModifier(77 /* ConstKeyword */)); + } + if (flags & 4 /* Public */) { + result.push(createModifier(115 /* PublicKeyword */)); + } + if (flags & 8 /* Private */) { + result.push(createModifier(113 /* PrivateKeyword */)); + } + if (flags & 16 /* Protected */) { + result.push(createModifier(114 /* ProtectedKeyword */)); + } + if (flags & 128 /* Abstract */) { + result.push(createModifier(118 /* AbstractKeyword */)); + } + if (flags & 32 /* Static */) { + result.push(createModifier(116 /* StaticKeyword */)); + } + if (flags & 64 /* Readonly */) { + result.push(createModifier(133 /* ReadonlyKeyword */)); + } + if (flags & 256 /* Async */) { + result.push(createModifier(121 /* AsyncKeyword */)); + } + return result; + } + ts.createModifiersFromModifierFlags = createModifiersFromModifierFlags; + // Names + function createQualifiedName(left, right) { + var node = createSynthesizedNode(148 /* QualifiedName */); + node.left = left; + node.right = asName(right); + return node; + } + ts.createQualifiedName = createQualifiedName; + function updateQualifiedName(node, left, right) { + return node.left !== left + || node.right !== right + ? updateNode(createQualifiedName(left, right), node) + : node; + } + ts.updateQualifiedName = updateQualifiedName; + function parenthesizeForComputedName(expression) { + return ts.isCommaSequence(expression) + ? createParen(expression) + : expression; + } + function createComputedPropertyName(expression) { + var node = createSynthesizedNode(149 /* ComputedPropertyName */); + node.expression = parenthesizeForComputedName(expression); + return node; + } + ts.createComputedPropertyName = createComputedPropertyName; + function updateComputedPropertyName(node, expression) { + return node.expression !== expression + ? updateNode(createComputedPropertyName(expression), node) + : node; + } + ts.updateComputedPropertyName = updateComputedPropertyName; + // Signature elements + function createTypeParameterDeclaration(name, constraint, defaultType) { + var node = createSynthesizedNode(150 /* TypeParameter */); + node.name = asName(name); + node.constraint = constraint; + node.default = defaultType; + return node; + } + ts.createTypeParameterDeclaration = createTypeParameterDeclaration; + function updateTypeParameterDeclaration(node, name, constraint, defaultType) { + return node.name !== name + || node.constraint !== constraint + || node.default !== defaultType + ? updateNode(createTypeParameterDeclaration(name, constraint, defaultType), node) + : node; + } + ts.updateTypeParameterDeclaration = updateTypeParameterDeclaration; + function createParameter(decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer) { + var node = createSynthesizedNode(151 /* Parameter */); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.dotDotDotToken = dotDotDotToken; + node.name = asName(name); + node.questionToken = questionToken; + node.type = type; + node.initializer = initializer ? ts.parenthesizeExpressionForList(initializer) : undefined; + return node; + } + ts.createParameter = createParameter; + function updateParameter(node, decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.dotDotDotToken !== dotDotDotToken + || node.name !== name + || node.questionToken !== questionToken + || node.type !== type + || node.initializer !== initializer + ? updateNode(createParameter(decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer), node) + : node; + } + ts.updateParameter = updateParameter; + function createDecorator(expression) { + var node = createSynthesizedNode(152 /* Decorator */); + node.expression = ts.parenthesizeForAccess(expression); + return node; + } + ts.createDecorator = createDecorator; + function updateDecorator(node, expression) { + return node.expression !== expression + ? updateNode(createDecorator(expression), node) + : node; + } + ts.updateDecorator = updateDecorator; + // Type Elements + function createPropertySignature(modifiers, name, questionToken, type, initializer) { + var node = createSynthesizedNode(153 /* PropertySignature */); + node.modifiers = asNodeArray(modifiers); + node.name = asName(name); + node.questionToken = questionToken; + node.type = type; + node.initializer = initializer; + return node; + } + ts.createPropertySignature = createPropertySignature; + function updatePropertySignature(node, modifiers, name, questionToken, type, initializer) { + return node.modifiers !== modifiers + || node.name !== name + || node.questionToken !== questionToken + || node.type !== type + || node.initializer !== initializer + ? updateNode(createPropertySignature(modifiers, name, questionToken, type, initializer), node) + : node; + } + ts.updatePropertySignature = updatePropertySignature; + function createProperty(decorators, modifiers, name, questionOrExclamationToken, type, initializer) { + var node = createSynthesizedNode(154 /* PropertyDeclaration */); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.name = asName(name); + node.questionToken = questionOrExclamationToken !== undefined && questionOrExclamationToken.kind === 56 /* QuestionToken */ ? questionOrExclamationToken : undefined; + node.exclamationToken = questionOrExclamationToken !== undefined && questionOrExclamationToken.kind === 52 /* ExclamationToken */ ? questionOrExclamationToken : undefined; + node.type = type; + node.initializer = initializer; + return node; + } + ts.createProperty = createProperty; + function updateProperty(node, decorators, modifiers, name, questionOrExclamationToken, type, initializer) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.name !== name + || node.questionToken !== (questionOrExclamationToken !== undefined && questionOrExclamationToken.kind === 56 /* QuestionToken */ ? questionOrExclamationToken : undefined) + || node.exclamationToken !== (questionOrExclamationToken !== undefined && questionOrExclamationToken.kind === 52 /* ExclamationToken */ ? questionOrExclamationToken : undefined) + || node.type !== type + || node.initializer !== initializer + ? updateNode(createProperty(decorators, modifiers, name, questionOrExclamationToken, type, initializer), node) + : node; + } + ts.updateProperty = updateProperty; + function createMethodSignature(typeParameters, parameters, type, name, questionToken) { + var node = createSignatureDeclaration(155 /* MethodSignature */, typeParameters, parameters, type); + node.name = asName(name); + node.questionToken = questionToken; + return node; + } + ts.createMethodSignature = createMethodSignature; + function updateMethodSignature(node, typeParameters, parameters, type, name, questionToken) { + return node.typeParameters !== typeParameters + || node.parameters !== parameters + || node.type !== type + || node.name !== name + || node.questionToken !== questionToken + ? updateNode(createMethodSignature(typeParameters, parameters, type, name, questionToken), node) + : node; + } + ts.updateMethodSignature = updateMethodSignature; + function createMethod(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { + var node = createSynthesizedNode(156 /* MethodDeclaration */); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.asteriskToken = asteriskToken; + node.name = asName(name); + node.questionToken = questionToken; + node.typeParameters = asNodeArray(typeParameters); + node.parameters = createNodeArray(parameters); + node.type = type; + node.body = body; + return node; + } + ts.createMethod = createMethod; + function updateMethod(node, decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.asteriskToken !== asteriskToken + || node.name !== name + || node.questionToken !== questionToken + || node.typeParameters !== typeParameters + || node.parameters !== parameters + || node.type !== type + || node.body !== body + ? updateNode(createMethod(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body), node) + : node; + } + ts.updateMethod = updateMethod; + function createConstructor(decorators, modifiers, parameters, body) { + var node = createSynthesizedNode(157 /* Constructor */); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.typeParameters = undefined; + node.parameters = createNodeArray(parameters); + node.type = undefined; + node.body = body; + return node; + } + ts.createConstructor = createConstructor; + function updateConstructor(node, decorators, modifiers, parameters, body) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.parameters !== parameters + || node.body !== body + ? updateNode(createConstructor(decorators, modifiers, parameters, body), node) + : node; + } + ts.updateConstructor = updateConstructor; + function createGetAccessor(decorators, modifiers, name, parameters, type, body) { + var node = createSynthesizedNode(158 /* GetAccessor */); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.name = asName(name); + node.typeParameters = undefined; + node.parameters = createNodeArray(parameters); + node.type = type; + node.body = body; + return node; + } + ts.createGetAccessor = createGetAccessor; + function updateGetAccessor(node, decorators, modifiers, name, parameters, type, body) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.name !== name + || node.parameters !== parameters + || node.type !== type + || node.body !== body + ? updateNode(createGetAccessor(decorators, modifiers, name, parameters, type, body), node) + : node; + } + ts.updateGetAccessor = updateGetAccessor; + function createSetAccessor(decorators, modifiers, name, parameters, body) { + var node = createSynthesizedNode(159 /* SetAccessor */); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.name = asName(name); + node.typeParameters = undefined; + node.parameters = createNodeArray(parameters); + node.body = body; + return node; + } + ts.createSetAccessor = createSetAccessor; + function updateSetAccessor(node, decorators, modifiers, name, parameters, body) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.name !== name + || node.parameters !== parameters + || node.body !== body + ? updateNode(createSetAccessor(decorators, modifiers, name, parameters, body), node) + : node; + } + ts.updateSetAccessor = updateSetAccessor; + function createCallSignature(typeParameters, parameters, type) { + return createSignatureDeclaration(160 /* CallSignature */, typeParameters, parameters, type); + } + ts.createCallSignature = createCallSignature; + function updateCallSignature(node, typeParameters, parameters, type) { + return updateSignatureDeclaration(node, typeParameters, parameters, type); + } + ts.updateCallSignature = updateCallSignature; + function createConstructSignature(typeParameters, parameters, type) { + return createSignatureDeclaration(161 /* ConstructSignature */, typeParameters, parameters, type); + } + ts.createConstructSignature = createConstructSignature; + function updateConstructSignature(node, typeParameters, parameters, type) { + return updateSignatureDeclaration(node, typeParameters, parameters, type); + } + ts.updateConstructSignature = updateConstructSignature; + function createIndexSignature(decorators, modifiers, parameters, type) { + var node = createSynthesizedNode(162 /* IndexSignature */); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.parameters = createNodeArray(parameters); + node.type = type; + return node; + } + ts.createIndexSignature = createIndexSignature; + function updateIndexSignature(node, decorators, modifiers, parameters, type) { + return node.parameters !== parameters + || node.type !== type + || node.decorators !== decorators + || node.modifiers !== modifiers + ? updateNode(createIndexSignature(decorators, modifiers, parameters, type), node) + : node; + } + ts.updateIndexSignature = updateIndexSignature; + /* @internal */ + function createSignatureDeclaration(kind, typeParameters, parameters, type, typeArguments) { + var node = createSynthesizedNode(kind); + node.typeParameters = asNodeArray(typeParameters); + node.parameters = asNodeArray(parameters); + node.type = type; + node.typeArguments = asNodeArray(typeArguments); + return node; + } + ts.createSignatureDeclaration = createSignatureDeclaration; + function updateSignatureDeclaration(node, typeParameters, parameters, type) { + return node.typeParameters !== typeParameters + || node.parameters !== parameters + || node.type !== type + ? updateNode(createSignatureDeclaration(node.kind, typeParameters, parameters, type), node) + : node; + } + // Types + function createKeywordTypeNode(kind) { + return createSynthesizedNode(kind); + } + ts.createKeywordTypeNode = createKeywordTypeNode; + function createTypePredicateNode(parameterName, type) { + var node = createSynthesizedNode(163 /* TypePredicate */); + node.parameterName = asName(parameterName); + node.type = type; + return node; + } + ts.createTypePredicateNode = createTypePredicateNode; + function updateTypePredicateNode(node, parameterName, type) { + return node.parameterName !== parameterName + || node.type !== type + ? updateNode(createTypePredicateNode(parameterName, type), node) + : node; + } + ts.updateTypePredicateNode = updateTypePredicateNode; + function createTypeReferenceNode(typeName, typeArguments) { + var node = createSynthesizedNode(164 /* TypeReference */); + node.typeName = asName(typeName); + node.typeArguments = typeArguments && ts.parenthesizeTypeParameters(typeArguments); + return node; + } + ts.createTypeReferenceNode = createTypeReferenceNode; + function updateTypeReferenceNode(node, typeName, typeArguments) { + return node.typeName !== typeName + || node.typeArguments !== typeArguments + ? updateNode(createTypeReferenceNode(typeName, typeArguments), node) + : node; + } + ts.updateTypeReferenceNode = updateTypeReferenceNode; + function createFunctionTypeNode(typeParameters, parameters, type) { + return createSignatureDeclaration(165 /* FunctionType */, typeParameters, parameters, type); + } + ts.createFunctionTypeNode = createFunctionTypeNode; + function updateFunctionTypeNode(node, typeParameters, parameters, type) { + return updateSignatureDeclaration(node, typeParameters, parameters, type); + } + ts.updateFunctionTypeNode = updateFunctionTypeNode; + function createConstructorTypeNode(typeParameters, parameters, type) { + return createSignatureDeclaration(166 /* ConstructorType */, typeParameters, parameters, type); + } + ts.createConstructorTypeNode = createConstructorTypeNode; + function updateConstructorTypeNode(node, typeParameters, parameters, type) { + return updateSignatureDeclaration(node, typeParameters, parameters, type); + } + ts.updateConstructorTypeNode = updateConstructorTypeNode; + function createTypeQueryNode(exprName) { + var node = createSynthesizedNode(167 /* TypeQuery */); + node.exprName = exprName; + return node; + } + ts.createTypeQueryNode = createTypeQueryNode; + function updateTypeQueryNode(node, exprName) { + return node.exprName !== exprName + ? updateNode(createTypeQueryNode(exprName), node) + : node; + } + ts.updateTypeQueryNode = updateTypeQueryNode; + function createTypeLiteralNode(members) { + var node = createSynthesizedNode(168 /* TypeLiteral */); + node.members = createNodeArray(members); + return node; + } + ts.createTypeLiteralNode = createTypeLiteralNode; + function updateTypeLiteralNode(node, members) { + return node.members !== members + ? updateNode(createTypeLiteralNode(members), node) + : node; + } + ts.updateTypeLiteralNode = updateTypeLiteralNode; + function createArrayTypeNode(elementType) { + var node = createSynthesizedNode(169 /* ArrayType */); + node.elementType = ts.parenthesizeArrayTypeMember(elementType); + return node; + } + ts.createArrayTypeNode = createArrayTypeNode; + function updateArrayTypeNode(node, elementType) { + return node.elementType !== elementType + ? updateNode(createArrayTypeNode(elementType), node) + : node; + } + ts.updateArrayTypeNode = updateArrayTypeNode; + function createTupleTypeNode(elementTypes) { + var node = createSynthesizedNode(170 /* TupleType */); + node.elementTypes = createNodeArray(elementTypes); + return node; + } + ts.createTupleTypeNode = createTupleTypeNode; + function updateTupleTypeNode(node, elementTypes) { + return node.elementTypes !== elementTypes + ? updateNode(createTupleTypeNode(elementTypes), node) + : node; + } + ts.updateTupleTypeNode = updateTupleTypeNode; + function createOptionalTypeNode(type) { + var node = createSynthesizedNode(171 /* OptionalType */); + node.type = ts.parenthesizeArrayTypeMember(type); + return node; + } + ts.createOptionalTypeNode = createOptionalTypeNode; + function updateOptionalTypeNode(node, type) { + return node.type !== type + ? updateNode(createOptionalTypeNode(type), node) + : node; + } + ts.updateOptionalTypeNode = updateOptionalTypeNode; + function createRestTypeNode(type) { + var node = createSynthesizedNode(172 /* RestType */); + node.type = type; + return node; + } + ts.createRestTypeNode = createRestTypeNode; + function updateRestTypeNode(node, type) { + return node.type !== type + ? updateNode(createRestTypeNode(type), node) + : node; + } + ts.updateRestTypeNode = updateRestTypeNode; + function createUnionTypeNode(types) { + return createUnionOrIntersectionTypeNode(173 /* UnionType */, types); + } + ts.createUnionTypeNode = createUnionTypeNode; + function updateUnionTypeNode(node, types) { + return updateUnionOrIntersectionTypeNode(node, types); + } + ts.updateUnionTypeNode = updateUnionTypeNode; + function createIntersectionTypeNode(types) { + return createUnionOrIntersectionTypeNode(174 /* IntersectionType */, types); + } + ts.createIntersectionTypeNode = createIntersectionTypeNode; + function updateIntersectionTypeNode(node, types) { + return updateUnionOrIntersectionTypeNode(node, types); + } + ts.updateIntersectionTypeNode = updateIntersectionTypeNode; + function createUnionOrIntersectionTypeNode(kind, types) { + var node = createSynthesizedNode(kind); + node.types = ts.parenthesizeElementTypeMembers(types); + return node; + } + ts.createUnionOrIntersectionTypeNode = createUnionOrIntersectionTypeNode; + function updateUnionOrIntersectionTypeNode(node, types) { + return node.types !== types + ? updateNode(createUnionOrIntersectionTypeNode(node.kind, types), node) + : node; + } + function createConditionalTypeNode(checkType, extendsType, trueType, falseType) { + var node = createSynthesizedNode(175 /* ConditionalType */); + node.checkType = ts.parenthesizeConditionalTypeMember(checkType); + node.extendsType = ts.parenthesizeConditionalTypeMember(extendsType); + node.trueType = trueType; + node.falseType = falseType; + return node; + } + ts.createConditionalTypeNode = createConditionalTypeNode; + function updateConditionalTypeNode(node, checkType, extendsType, trueType, falseType) { + return node.checkType !== checkType + || node.extendsType !== extendsType + || node.trueType !== trueType + || node.falseType !== falseType + ? updateNode(createConditionalTypeNode(checkType, extendsType, trueType, falseType), node) + : node; + } + ts.updateConditionalTypeNode = updateConditionalTypeNode; + function createInferTypeNode(typeParameter) { + var node = createSynthesizedNode(176 /* InferType */); + node.typeParameter = typeParameter; + return node; + } + ts.createInferTypeNode = createInferTypeNode; + function updateInferTypeNode(node, typeParameter) { + return node.typeParameter !== typeParameter + ? updateNode(createInferTypeNode(typeParameter), node) + : node; + } + ts.updateInferTypeNode = updateInferTypeNode; + function createImportTypeNode(argument, qualifier, typeArguments, isTypeOf) { + var node = createSynthesizedNode(183 /* ImportType */); + node.argument = argument; + node.qualifier = qualifier; + node.typeArguments = asNodeArray(typeArguments); + node.isTypeOf = isTypeOf; + return node; + } + ts.createImportTypeNode = createImportTypeNode; + function updateImportTypeNode(node, argument, qualifier, typeArguments, isTypeOf) { + return node.argument !== argument + || node.qualifier !== qualifier + || node.typeArguments !== typeArguments + || node.isTypeOf !== isTypeOf + ? updateNode(createImportTypeNode(argument, qualifier, typeArguments, isTypeOf), node) + : node; + } + ts.updateImportTypeNode = updateImportTypeNode; + function createParenthesizedType(type) { + var node = createSynthesizedNode(177 /* ParenthesizedType */); + node.type = type; + return node; + } + ts.createParenthesizedType = createParenthesizedType; + function updateParenthesizedType(node, type) { + return node.type !== type + ? updateNode(createParenthesizedType(type), node) + : node; + } + ts.updateParenthesizedType = updateParenthesizedType; + function createThisTypeNode() { + return createSynthesizedNode(178 /* ThisType */); + } + ts.createThisTypeNode = createThisTypeNode; + function createTypeOperatorNode(operatorOrType, type) { + var node = createSynthesizedNode(179 /* TypeOperator */); + node.operator = typeof operatorOrType === "number" ? operatorOrType : 129 /* KeyOfKeyword */; + node.type = ts.parenthesizeElementTypeMember(typeof operatorOrType === "number" ? type : operatorOrType); + return node; + } + ts.createTypeOperatorNode = createTypeOperatorNode; + function updateTypeOperatorNode(node, type) { + return node.type !== type ? updateNode(createTypeOperatorNode(node.operator, type), node) : node; + } + ts.updateTypeOperatorNode = updateTypeOperatorNode; + function createIndexedAccessTypeNode(objectType, indexType) { + var node = createSynthesizedNode(180 /* IndexedAccessType */); + node.objectType = ts.parenthesizeElementTypeMember(objectType); + node.indexType = indexType; + return node; + } + ts.createIndexedAccessTypeNode = createIndexedAccessTypeNode; + function updateIndexedAccessTypeNode(node, objectType, indexType) { + return node.objectType !== objectType + || node.indexType !== indexType + ? updateNode(createIndexedAccessTypeNode(objectType, indexType), node) + : node; + } + ts.updateIndexedAccessTypeNode = updateIndexedAccessTypeNode; + function createMappedTypeNode(readonlyToken, typeParameter, questionToken, type) { + var node = createSynthesizedNode(181 /* MappedType */); + node.readonlyToken = readonlyToken; + node.typeParameter = typeParameter; + node.questionToken = questionToken; + node.type = type; + return node; + } + ts.createMappedTypeNode = createMappedTypeNode; + function updateMappedTypeNode(node, readonlyToken, typeParameter, questionToken, type) { + return node.readonlyToken !== readonlyToken + || node.typeParameter !== typeParameter + || node.questionToken !== questionToken + || node.type !== type + ? updateNode(createMappedTypeNode(readonlyToken, typeParameter, questionToken, type), node) + : node; + } + ts.updateMappedTypeNode = updateMappedTypeNode; + function createLiteralTypeNode(literal) { + var node = createSynthesizedNode(182 /* LiteralType */); + node.literal = literal; + return node; + } + ts.createLiteralTypeNode = createLiteralTypeNode; + function updateLiteralTypeNode(node, literal) { + return node.literal !== literal + ? updateNode(createLiteralTypeNode(literal), node) + : node; + } + ts.updateLiteralTypeNode = updateLiteralTypeNode; + // Binding Patterns + function createObjectBindingPattern(elements) { + var node = createSynthesizedNode(184 /* ObjectBindingPattern */); + node.elements = createNodeArray(elements); + return node; + } + ts.createObjectBindingPattern = createObjectBindingPattern; + function updateObjectBindingPattern(node, elements) { + return node.elements !== elements + ? updateNode(createObjectBindingPattern(elements), node) + : node; + } + ts.updateObjectBindingPattern = updateObjectBindingPattern; + function createArrayBindingPattern(elements) { + var node = createSynthesizedNode(185 /* ArrayBindingPattern */); + node.elements = createNodeArray(elements); + return node; + } + ts.createArrayBindingPattern = createArrayBindingPattern; + function updateArrayBindingPattern(node, elements) { + return node.elements !== elements + ? updateNode(createArrayBindingPattern(elements), node) + : node; + } + ts.updateArrayBindingPattern = updateArrayBindingPattern; + function createBindingElement(dotDotDotToken, propertyName, name, initializer) { + var node = createSynthesizedNode(186 /* BindingElement */); + node.dotDotDotToken = dotDotDotToken; + node.propertyName = asName(propertyName); + node.name = asName(name); + node.initializer = initializer; + return node; + } + ts.createBindingElement = createBindingElement; + function updateBindingElement(node, dotDotDotToken, propertyName, name, initializer) { + return node.propertyName !== propertyName + || node.dotDotDotToken !== dotDotDotToken + || node.name !== name + || node.initializer !== initializer + ? updateNode(createBindingElement(dotDotDotToken, propertyName, name, initializer), node) + : node; + } + ts.updateBindingElement = updateBindingElement; + // Expression + function createArrayLiteral(elements, multiLine) { + var node = createSynthesizedNode(187 /* ArrayLiteralExpression */); + node.elements = ts.parenthesizeListElements(createNodeArray(elements)); + if (multiLine) + node.multiLine = true; + return node; + } + ts.createArrayLiteral = createArrayLiteral; + function updateArrayLiteral(node, elements) { + return node.elements !== elements + ? updateNode(createArrayLiteral(elements, node.multiLine), node) + : node; + } + ts.updateArrayLiteral = updateArrayLiteral; + function createObjectLiteral(properties, multiLine) { + var node = createSynthesizedNode(188 /* ObjectLiteralExpression */); + node.properties = createNodeArray(properties); + if (multiLine) + node.multiLine = true; + return node; + } + ts.createObjectLiteral = createObjectLiteral; + function updateObjectLiteral(node, properties) { + return node.properties !== properties + ? updateNode(createObjectLiteral(properties, node.multiLine), node) + : node; + } + ts.updateObjectLiteral = updateObjectLiteral; + function createPropertyAccess(expression, name) { + var node = createSynthesizedNode(189 /* PropertyAccessExpression */); + node.expression = ts.parenthesizeForAccess(expression); + node.name = asName(name); // TODO: GH#18217 + setEmitFlags(node, 131072 /* NoIndentation */); + return node; + } + ts.createPropertyAccess = createPropertyAccess; + function updatePropertyAccess(node, expression, name) { + // Because we are updating existed propertyAccess we want to inherit its emitFlags + // instead of using the default from createPropertyAccess + return node.expression !== expression + || node.name !== name + ? updateNode(setEmitFlags(createPropertyAccess(expression, name), ts.getEmitFlags(node)), node) + : node; + } + ts.updatePropertyAccess = updatePropertyAccess; + function createElementAccess(expression, index) { + var node = createSynthesizedNode(190 /* ElementAccessExpression */); + node.expression = ts.parenthesizeForAccess(expression); + node.argumentExpression = asExpression(index); + return node; + } + ts.createElementAccess = createElementAccess; + function updateElementAccess(node, expression, argumentExpression) { + return node.expression !== expression + || node.argumentExpression !== argumentExpression + ? updateNode(createElementAccess(expression, argumentExpression), node) + : node; + } + ts.updateElementAccess = updateElementAccess; + function createCall(expression, typeArguments, argumentsArray) { + var node = createSynthesizedNode(191 /* CallExpression */); + node.expression = ts.parenthesizeForAccess(expression); + node.typeArguments = asNodeArray(typeArguments); + node.arguments = ts.parenthesizeListElements(createNodeArray(argumentsArray)); + return node; + } + ts.createCall = createCall; + function updateCall(node, expression, typeArguments, argumentsArray) { + return node.expression !== expression + || node.typeArguments !== typeArguments + || node.arguments !== argumentsArray + ? updateNode(createCall(expression, typeArguments, argumentsArray), node) + : node; + } + ts.updateCall = updateCall; + function createNew(expression, typeArguments, argumentsArray) { + var node = createSynthesizedNode(192 /* NewExpression */); + node.expression = ts.parenthesizeForNew(expression); + node.typeArguments = asNodeArray(typeArguments); + node.arguments = argumentsArray ? ts.parenthesizeListElements(createNodeArray(argumentsArray)) : undefined; + return node; + } + ts.createNew = createNew; + function updateNew(node, expression, typeArguments, argumentsArray) { + return node.expression !== expression + || node.typeArguments !== typeArguments + || node.arguments !== argumentsArray + ? updateNode(createNew(expression, typeArguments, argumentsArray), node) + : node; + } + ts.updateNew = updateNew; + function createTaggedTemplate(tag, typeArgumentsOrTemplate, template) { + var node = createSynthesizedNode(193 /* TaggedTemplateExpression */); + node.tag = ts.parenthesizeForAccess(tag); + if (template) { + node.typeArguments = asNodeArray(typeArgumentsOrTemplate); + node.template = template; + } + else { + node.typeArguments = undefined; + node.template = typeArgumentsOrTemplate; + } + return node; + } + ts.createTaggedTemplate = createTaggedTemplate; + function updateTaggedTemplate(node, tag, typeArgumentsOrTemplate, template) { + return node.tag !== tag + || (template + ? node.typeArguments !== typeArgumentsOrTemplate || node.template !== template + : node.typeArguments !== undefined || node.template !== typeArgumentsOrTemplate) + ? updateNode(createTaggedTemplate(tag, typeArgumentsOrTemplate, template), node) + : node; + } + ts.updateTaggedTemplate = updateTaggedTemplate; + function createTypeAssertion(type, expression) { + var node = createSynthesizedNode(194 /* TypeAssertionExpression */); + node.type = type; + node.expression = ts.parenthesizePrefixOperand(expression); + return node; + } + ts.createTypeAssertion = createTypeAssertion; + function updateTypeAssertion(node, type, expression) { + return node.type !== type + || node.expression !== expression + ? updateNode(createTypeAssertion(type, expression), node) + : node; + } + ts.updateTypeAssertion = updateTypeAssertion; + function createParen(expression) { + var node = createSynthesizedNode(195 /* ParenthesizedExpression */); + node.expression = expression; + return node; + } + ts.createParen = createParen; + function updateParen(node, expression) { + return node.expression !== expression + ? updateNode(createParen(expression), node) + : node; + } + ts.updateParen = updateParen; + function createFunctionExpression(modifiers, asteriskToken, name, typeParameters, parameters, type, body) { + var node = createSynthesizedNode(196 /* FunctionExpression */); + node.modifiers = asNodeArray(modifiers); + node.asteriskToken = asteriskToken; + node.name = asName(name); + node.typeParameters = asNodeArray(typeParameters); + node.parameters = createNodeArray(parameters); + node.type = type; + node.body = body; + return node; + } + ts.createFunctionExpression = createFunctionExpression; + function updateFunctionExpression(node, modifiers, asteriskToken, name, typeParameters, parameters, type, body) { + return node.name !== name + || node.modifiers !== modifiers + || node.asteriskToken !== asteriskToken + || node.typeParameters !== typeParameters + || node.parameters !== parameters + || node.type !== type + || node.body !== body + ? updateNode(createFunctionExpression(modifiers, asteriskToken, name, typeParameters, parameters, type, body), node) + : node; + } + ts.updateFunctionExpression = updateFunctionExpression; + function createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body) { + var node = createSynthesizedNode(197 /* ArrowFunction */); + node.modifiers = asNodeArray(modifiers); + node.typeParameters = asNodeArray(typeParameters); + node.parameters = createNodeArray(parameters); + node.type = type; + node.equalsGreaterThanToken = equalsGreaterThanToken || createToken(37 /* EqualsGreaterThanToken */); + node.body = ts.parenthesizeConciseBody(body); + return node; + } + ts.createArrowFunction = createArrowFunction; + function updateArrowFunction(node, modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body) { + return node.modifiers !== modifiers + || node.typeParameters !== typeParameters + || node.parameters !== parameters + || node.type !== type + || node.equalsGreaterThanToken !== equalsGreaterThanToken + || node.body !== body + ? updateNode(createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body), node) + : node; + } + ts.updateArrowFunction = updateArrowFunction; + function createDelete(expression) { + var node = createSynthesizedNode(198 /* DeleteExpression */); + node.expression = ts.parenthesizePrefixOperand(expression); + return node; + } + ts.createDelete = createDelete; + function updateDelete(node, expression) { + return node.expression !== expression + ? updateNode(createDelete(expression), node) + : node; + } + ts.updateDelete = updateDelete; + function createTypeOf(expression) { + var node = createSynthesizedNode(199 /* TypeOfExpression */); + node.expression = ts.parenthesizePrefixOperand(expression); + return node; + } + ts.createTypeOf = createTypeOf; + function updateTypeOf(node, expression) { + return node.expression !== expression + ? updateNode(createTypeOf(expression), node) + : node; + } + ts.updateTypeOf = updateTypeOf; + function createVoid(expression) { + var node = createSynthesizedNode(200 /* VoidExpression */); + node.expression = ts.parenthesizePrefixOperand(expression); + return node; + } + ts.createVoid = createVoid; + function updateVoid(node, expression) { + return node.expression !== expression + ? updateNode(createVoid(expression), node) + : node; + } + ts.updateVoid = updateVoid; + function createAwait(expression) { + var node = createSynthesizedNode(201 /* AwaitExpression */); + node.expression = ts.parenthesizePrefixOperand(expression); + return node; + } + ts.createAwait = createAwait; + function updateAwait(node, expression) { + return node.expression !== expression + ? updateNode(createAwait(expression), node) + : node; + } + ts.updateAwait = updateAwait; + function createPrefix(operator, operand) { + var node = createSynthesizedNode(202 /* PrefixUnaryExpression */); + node.operator = operator; + node.operand = ts.parenthesizePrefixOperand(operand); + return node; + } + ts.createPrefix = createPrefix; + function updatePrefix(node, operand) { + return node.operand !== operand + ? updateNode(createPrefix(node.operator, operand), node) + : node; + } + ts.updatePrefix = updatePrefix; + function createPostfix(operand, operator) { + var node = createSynthesizedNode(203 /* PostfixUnaryExpression */); + node.operand = ts.parenthesizePostfixOperand(operand); + node.operator = operator; + return node; + } + ts.createPostfix = createPostfix; + function updatePostfix(node, operand) { + return node.operand !== operand + ? updateNode(createPostfix(operand, node.operator), node) + : node; + } + ts.updatePostfix = updatePostfix; + function createBinary(left, operator, right) { + var node = createSynthesizedNode(204 /* BinaryExpression */); + var operatorToken = asToken(operator); + var operatorKind = operatorToken.kind; + node.left = ts.parenthesizeBinaryOperand(operatorKind, left, /*isLeftSideOfBinary*/ true, /*leftOperand*/ undefined); + node.operatorToken = operatorToken; + node.right = ts.parenthesizeBinaryOperand(operatorKind, right, /*isLeftSideOfBinary*/ false, node.left); + return node; + } + ts.createBinary = createBinary; + function updateBinary(node, left, right, operator) { + return node.left !== left + || node.right !== right + ? updateNode(createBinary(left, operator || node.operatorToken, right), node) + : node; + } + ts.updateBinary = updateBinary; + function createConditional(condition, questionTokenOrWhenTrue, whenTrueOrWhenFalse, colonToken, whenFalse) { + var node = createSynthesizedNode(205 /* ConditionalExpression */); + node.condition = ts.parenthesizeForConditionalHead(condition); + node.questionToken = whenFalse ? questionTokenOrWhenTrue : createToken(56 /* QuestionToken */); + node.whenTrue = ts.parenthesizeSubexpressionOfConditionalExpression(whenFalse ? whenTrueOrWhenFalse : questionTokenOrWhenTrue); + node.colonToken = whenFalse ? colonToken : createToken(57 /* ColonToken */); + node.whenFalse = ts.parenthesizeSubexpressionOfConditionalExpression(whenFalse ? whenFalse : whenTrueOrWhenFalse); + return node; + } + ts.createConditional = createConditional; + function updateConditional(node, condition, questionToken, whenTrue, colonToken, whenFalse) { + return node.condition !== condition + || node.questionToken !== questionToken + || node.whenTrue !== whenTrue + || node.colonToken !== colonToken + || node.whenFalse !== whenFalse + ? updateNode(createConditional(condition, questionToken, whenTrue, colonToken, whenFalse), node) + : node; + } + ts.updateConditional = updateConditional; + function createTemplateExpression(head, templateSpans) { + var node = createSynthesizedNode(206 /* TemplateExpression */); + node.head = head; + node.templateSpans = createNodeArray(templateSpans); + return node; + } + ts.createTemplateExpression = createTemplateExpression; + function updateTemplateExpression(node, head, templateSpans) { + return node.head !== head + || node.templateSpans !== templateSpans + ? updateNode(createTemplateExpression(head, templateSpans), node) + : node; + } + ts.updateTemplateExpression = updateTemplateExpression; + function createTemplateHead(text) { + var node = createSynthesizedNode(15 /* TemplateHead */); + node.text = text; + return node; + } + ts.createTemplateHead = createTemplateHead; + function createTemplateMiddle(text) { + var node = createSynthesizedNode(16 /* TemplateMiddle */); + node.text = text; + return node; + } + ts.createTemplateMiddle = createTemplateMiddle; + function createTemplateTail(text) { + var node = createSynthesizedNode(17 /* TemplateTail */); + node.text = text; + return node; + } + ts.createTemplateTail = createTemplateTail; + function createNoSubstitutionTemplateLiteral(text) { + var node = createSynthesizedNode(14 /* NoSubstitutionTemplateLiteral */); + node.text = text; + return node; + } + ts.createNoSubstitutionTemplateLiteral = createNoSubstitutionTemplateLiteral; + function createYield(asteriskTokenOrExpression, expression) { + var node = createSynthesizedNode(207 /* YieldExpression */); + node.asteriskToken = asteriskTokenOrExpression && asteriskTokenOrExpression.kind === 40 /* AsteriskToken */ ? asteriskTokenOrExpression : undefined; + node.expression = asteriskTokenOrExpression && asteriskTokenOrExpression.kind !== 40 /* AsteriskToken */ ? asteriskTokenOrExpression : expression; + return node; + } + ts.createYield = createYield; + function updateYield(node, asteriskToken, expression) { + return node.expression !== expression + || node.asteriskToken !== asteriskToken + ? updateNode(createYield(asteriskToken, expression), node) + : node; + } + ts.updateYield = updateYield; + function createSpread(expression) { + var node = createSynthesizedNode(208 /* SpreadElement */); + node.expression = ts.parenthesizeExpressionForList(expression); + return node; + } + ts.createSpread = createSpread; + function updateSpread(node, expression) { + return node.expression !== expression + ? updateNode(createSpread(expression), node) + : node; + } + ts.updateSpread = updateSpread; + function createClassExpression(modifiers, name, typeParameters, heritageClauses, members) { + var node = createSynthesizedNode(209 /* ClassExpression */); + node.decorators = undefined; + node.modifiers = asNodeArray(modifiers); + node.name = asName(name); + node.typeParameters = asNodeArray(typeParameters); + node.heritageClauses = asNodeArray(heritageClauses); + node.members = createNodeArray(members); + return node; + } + ts.createClassExpression = createClassExpression; + function updateClassExpression(node, modifiers, name, typeParameters, heritageClauses, members) { + return node.modifiers !== modifiers + || node.name !== name + || node.typeParameters !== typeParameters + || node.heritageClauses !== heritageClauses + || node.members !== members + ? updateNode(createClassExpression(modifiers, name, typeParameters, heritageClauses, members), node) + : node; + } + ts.updateClassExpression = updateClassExpression; + function createOmittedExpression() { + return createSynthesizedNode(210 /* OmittedExpression */); + } + ts.createOmittedExpression = createOmittedExpression; + function createExpressionWithTypeArguments(typeArguments, expression) { + var node = createSynthesizedNode(211 /* ExpressionWithTypeArguments */); + node.expression = ts.parenthesizeForAccess(expression); + node.typeArguments = asNodeArray(typeArguments); + return node; + } + ts.createExpressionWithTypeArguments = createExpressionWithTypeArguments; + function updateExpressionWithTypeArguments(node, typeArguments, expression) { + return node.typeArguments !== typeArguments + || node.expression !== expression + ? updateNode(createExpressionWithTypeArguments(typeArguments, expression), node) + : node; + } + ts.updateExpressionWithTypeArguments = updateExpressionWithTypeArguments; + function createAsExpression(expression, type) { + var node = createSynthesizedNode(212 /* AsExpression */); + node.expression = expression; + node.type = type; + return node; + } + ts.createAsExpression = createAsExpression; + function updateAsExpression(node, expression, type) { + return node.expression !== expression + || node.type !== type + ? updateNode(createAsExpression(expression, type), node) + : node; + } + ts.updateAsExpression = updateAsExpression; + function createNonNullExpression(expression) { + var node = createSynthesizedNode(213 /* NonNullExpression */); + node.expression = ts.parenthesizeForAccess(expression); + return node; + } + ts.createNonNullExpression = createNonNullExpression; + function updateNonNullExpression(node, expression) { + return node.expression !== expression + ? updateNode(createNonNullExpression(expression), node) + : node; + } + ts.updateNonNullExpression = updateNonNullExpression; + function createMetaProperty(keywordToken, name) { + var node = createSynthesizedNode(214 /* MetaProperty */); + node.keywordToken = keywordToken; + node.name = name; + return node; + } + ts.createMetaProperty = createMetaProperty; + function updateMetaProperty(node, name) { + return node.name !== name + ? updateNode(createMetaProperty(node.keywordToken, name), node) + : node; + } + ts.updateMetaProperty = updateMetaProperty; + // Misc + function createTemplateSpan(expression, literal) { + var node = createSynthesizedNode(216 /* TemplateSpan */); + node.expression = expression; + node.literal = literal; + return node; + } + ts.createTemplateSpan = createTemplateSpan; + function updateTemplateSpan(node, expression, literal) { + return node.expression !== expression + || node.literal !== literal + ? updateNode(createTemplateSpan(expression, literal), node) + : node; + } + ts.updateTemplateSpan = updateTemplateSpan; + function createSemicolonClassElement() { + return createSynthesizedNode(217 /* SemicolonClassElement */); + } + ts.createSemicolonClassElement = createSemicolonClassElement; + // Element + function createBlock(statements, multiLine) { + var block = createSynthesizedNode(218 /* Block */); + block.statements = createNodeArray(statements); + if (multiLine) + block.multiLine = multiLine; + return block; + } + ts.createBlock = createBlock; + function updateBlock(node, statements) { + return node.statements !== statements + ? updateNode(createBlock(statements, node.multiLine), node) + : node; + } + ts.updateBlock = updateBlock; + function createVariableStatement(modifiers, declarationList) { + var node = createSynthesizedNode(219 /* VariableStatement */); + node.decorators = undefined; + node.modifiers = asNodeArray(modifiers); + node.declarationList = ts.isArray(declarationList) ? createVariableDeclarationList(declarationList) : declarationList; + return node; + } + ts.createVariableStatement = createVariableStatement; + function updateVariableStatement(node, modifiers, declarationList) { + return node.modifiers !== modifiers + || node.declarationList !== declarationList + ? updateNode(createVariableStatement(modifiers, declarationList), node) + : node; + } + ts.updateVariableStatement = updateVariableStatement; + function createEmptyStatement() { + return createSynthesizedNode(220 /* EmptyStatement */); + } + ts.createEmptyStatement = createEmptyStatement; + function createExpressionStatement(expression) { + var node = createSynthesizedNode(221 /* ExpressionStatement */); + node.expression = ts.parenthesizeExpressionForExpressionStatement(expression); + return node; + } + ts.createExpressionStatement = createExpressionStatement; + function updateExpressionStatement(node, expression) { + return node.expression !== expression + ? updateNode(createExpressionStatement(expression), node) + : node; + } + ts.updateExpressionStatement = updateExpressionStatement; + /** @deprecated Use `createExpressionStatement` instead. */ + ts.createStatement = createExpressionStatement; + /** @deprecated Use `updateExpressionStatement` instead. */ + ts.updateStatement = updateExpressionStatement; + function createIf(expression, thenStatement, elseStatement) { + var node = createSynthesizedNode(222 /* IfStatement */); + node.expression = expression; + node.thenStatement = thenStatement; + node.elseStatement = elseStatement; + return node; + } + ts.createIf = createIf; + function updateIf(node, expression, thenStatement, elseStatement) { + return node.expression !== expression + || node.thenStatement !== thenStatement + || node.elseStatement !== elseStatement + ? updateNode(createIf(expression, thenStatement, elseStatement), node) + : node; + } + ts.updateIf = updateIf; + function createDo(statement, expression) { + var node = createSynthesizedNode(223 /* DoStatement */); + node.statement = statement; + node.expression = expression; + return node; + } + ts.createDo = createDo; + function updateDo(node, statement, expression) { + return node.statement !== statement + || node.expression !== expression + ? updateNode(createDo(statement, expression), node) + : node; + } + ts.updateDo = updateDo; + function createWhile(expression, statement) { + var node = createSynthesizedNode(224 /* WhileStatement */); + node.expression = expression; + node.statement = statement; + return node; + } + ts.createWhile = createWhile; + function updateWhile(node, expression, statement) { + return node.expression !== expression + || node.statement !== statement + ? updateNode(createWhile(expression, statement), node) + : node; + } + ts.updateWhile = updateWhile; + function createFor(initializer, condition, incrementor, statement) { + var node = createSynthesizedNode(225 /* ForStatement */); + node.initializer = initializer; + node.condition = condition; + node.incrementor = incrementor; + node.statement = statement; + return node; + } + ts.createFor = createFor; + function updateFor(node, initializer, condition, incrementor, statement) { + return node.initializer !== initializer + || node.condition !== condition + || node.incrementor !== incrementor + || node.statement !== statement + ? updateNode(createFor(initializer, condition, incrementor, statement), node) + : node; + } + ts.updateFor = updateFor; + function createForIn(initializer, expression, statement) { + var node = createSynthesizedNode(226 /* ForInStatement */); + node.initializer = initializer; + node.expression = expression; + node.statement = statement; + return node; + } + ts.createForIn = createForIn; + function updateForIn(node, initializer, expression, statement) { + return node.initializer !== initializer + || node.expression !== expression + || node.statement !== statement + ? updateNode(createForIn(initializer, expression, statement), node) + : node; + } + ts.updateForIn = updateForIn; + function createForOf(awaitModifier, initializer, expression, statement) { + var node = createSynthesizedNode(227 /* ForOfStatement */); + node.awaitModifier = awaitModifier; + node.initializer = initializer; + node.expression = expression; + node.statement = statement; + return node; + } + ts.createForOf = createForOf; + function updateForOf(node, awaitModifier, initializer, expression, statement) { + return node.awaitModifier !== awaitModifier + || node.initializer !== initializer + || node.expression !== expression + || node.statement !== statement + ? updateNode(createForOf(awaitModifier, initializer, expression, statement), node) + : node; + } + ts.updateForOf = updateForOf; + function createContinue(label) { + var node = createSynthesizedNode(228 /* ContinueStatement */); + node.label = asName(label); + return node; + } + ts.createContinue = createContinue; + function updateContinue(node, label) { + return node.label !== label + ? updateNode(createContinue(label), node) + : node; + } + ts.updateContinue = updateContinue; + function createBreak(label) { + var node = createSynthesizedNode(229 /* BreakStatement */); + node.label = asName(label); + return node; + } + ts.createBreak = createBreak; + function updateBreak(node, label) { + return node.label !== label + ? updateNode(createBreak(label), node) + : node; + } + ts.updateBreak = updateBreak; + function createReturn(expression) { + var node = createSynthesizedNode(230 /* ReturnStatement */); + node.expression = expression; + return node; + } + ts.createReturn = createReturn; + function updateReturn(node, expression) { + return node.expression !== expression + ? updateNode(createReturn(expression), node) + : node; + } + ts.updateReturn = updateReturn; + function createWith(expression, statement) { + var node = createSynthesizedNode(231 /* WithStatement */); + node.expression = expression; + node.statement = statement; + return node; + } + ts.createWith = createWith; + function updateWith(node, expression, statement) { + return node.expression !== expression + || node.statement !== statement + ? updateNode(createWith(expression, statement), node) + : node; + } + ts.updateWith = updateWith; + function createSwitch(expression, caseBlock) { + var node = createSynthesizedNode(232 /* SwitchStatement */); + node.expression = ts.parenthesizeExpressionForList(expression); + node.caseBlock = caseBlock; + return node; + } + ts.createSwitch = createSwitch; + function updateSwitch(node, expression, caseBlock) { + return node.expression !== expression + || node.caseBlock !== caseBlock + ? updateNode(createSwitch(expression, caseBlock), node) + : node; + } + ts.updateSwitch = updateSwitch; + function createLabel(label, statement) { + var node = createSynthesizedNode(233 /* LabeledStatement */); + node.label = asName(label); + node.statement = statement; + return node; + } + ts.createLabel = createLabel; + function updateLabel(node, label, statement) { + return node.label !== label + || node.statement !== statement + ? updateNode(createLabel(label, statement), node) + : node; + } + ts.updateLabel = updateLabel; + function createThrow(expression) { + var node = createSynthesizedNode(234 /* ThrowStatement */); + node.expression = expression; + return node; + } + ts.createThrow = createThrow; + function updateThrow(node, expression) { + return node.expression !== expression + ? updateNode(createThrow(expression), node) + : node; + } + ts.updateThrow = updateThrow; + function createTry(tryBlock, catchClause, finallyBlock) { + var node = createSynthesizedNode(235 /* TryStatement */); + node.tryBlock = tryBlock; + node.catchClause = catchClause; + node.finallyBlock = finallyBlock; + return node; + } + ts.createTry = createTry; + function updateTry(node, tryBlock, catchClause, finallyBlock) { + return node.tryBlock !== tryBlock + || node.catchClause !== catchClause + || node.finallyBlock !== finallyBlock + ? updateNode(createTry(tryBlock, catchClause, finallyBlock), node) + : node; + } + ts.updateTry = updateTry; + function createDebuggerStatement() { + return createSynthesizedNode(236 /* DebuggerStatement */); + } + ts.createDebuggerStatement = createDebuggerStatement; + function createVariableDeclaration(name, type, initializer) { + var node = createSynthesizedNode(237 /* VariableDeclaration */); + node.name = asName(name); + node.type = type; + node.initializer = initializer !== undefined ? ts.parenthesizeExpressionForList(initializer) : undefined; + return node; + } + ts.createVariableDeclaration = createVariableDeclaration; + function updateVariableDeclaration(node, name, type, initializer) { + return node.name !== name + || node.type !== type + || node.initializer !== initializer + ? updateNode(createVariableDeclaration(name, type, initializer), node) + : node; + } + ts.updateVariableDeclaration = updateVariableDeclaration; + function createVariableDeclarationList(declarations, flags) { + if (flags === void 0) { flags = 0 /* None */; } + var node = createSynthesizedNode(238 /* VariableDeclarationList */); + node.flags |= flags & 3 /* BlockScoped */; + node.declarations = createNodeArray(declarations); + return node; + } + ts.createVariableDeclarationList = createVariableDeclarationList; + function updateVariableDeclarationList(node, declarations) { + return node.declarations !== declarations + ? updateNode(createVariableDeclarationList(declarations, node.flags), node) + : node; + } + ts.updateVariableDeclarationList = updateVariableDeclarationList; + function createFunctionDeclaration(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body) { + var node = createSynthesizedNode(239 /* FunctionDeclaration */); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.asteriskToken = asteriskToken; + node.name = asName(name); + node.typeParameters = asNodeArray(typeParameters); + node.parameters = createNodeArray(parameters); + node.type = type; + node.body = body; + return node; + } + ts.createFunctionDeclaration = createFunctionDeclaration; + function updateFunctionDeclaration(node, decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.asteriskToken !== asteriskToken + || node.name !== name + || node.typeParameters !== typeParameters + || node.parameters !== parameters + || node.type !== type + || node.body !== body + ? updateNode(createFunctionDeclaration(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body), node) + : node; + } + ts.updateFunctionDeclaration = updateFunctionDeclaration; + function createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) { + var node = createSynthesizedNode(240 /* ClassDeclaration */); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.name = asName(name); + node.typeParameters = asNodeArray(typeParameters); + node.heritageClauses = asNodeArray(heritageClauses); + node.members = createNodeArray(members); + return node; + } + ts.createClassDeclaration = createClassDeclaration; + function updateClassDeclaration(node, decorators, modifiers, name, typeParameters, heritageClauses, members) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.name !== name + || node.typeParameters !== typeParameters + || node.heritageClauses !== heritageClauses + || node.members !== members + ? updateNode(createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members), node) + : node; + } + ts.updateClassDeclaration = updateClassDeclaration; + function createInterfaceDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) { + var node = createSynthesizedNode(241 /* InterfaceDeclaration */); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.name = asName(name); + node.typeParameters = asNodeArray(typeParameters); + node.heritageClauses = asNodeArray(heritageClauses); + node.members = createNodeArray(members); + return node; + } + ts.createInterfaceDeclaration = createInterfaceDeclaration; + function updateInterfaceDeclaration(node, decorators, modifiers, name, typeParameters, heritageClauses, members) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.name !== name + || node.typeParameters !== typeParameters + || node.heritageClauses !== heritageClauses + || node.members !== members + ? updateNode(createInterfaceDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members), node) + : node; + } + ts.updateInterfaceDeclaration = updateInterfaceDeclaration; + function createTypeAliasDeclaration(decorators, modifiers, name, typeParameters, type) { + var node = createSynthesizedNode(242 /* TypeAliasDeclaration */); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.name = asName(name); + node.typeParameters = asNodeArray(typeParameters); + node.type = type; + return node; + } + ts.createTypeAliasDeclaration = createTypeAliasDeclaration; + function updateTypeAliasDeclaration(node, decorators, modifiers, name, typeParameters, type) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.name !== name + || node.typeParameters !== typeParameters + || node.type !== type + ? updateNode(createTypeAliasDeclaration(decorators, modifiers, name, typeParameters, type), node) + : node; + } + ts.updateTypeAliasDeclaration = updateTypeAliasDeclaration; + function createEnumDeclaration(decorators, modifiers, name, members) { + var node = createSynthesizedNode(243 /* EnumDeclaration */); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.name = asName(name); + node.members = createNodeArray(members); + return node; + } + ts.createEnumDeclaration = createEnumDeclaration; + function updateEnumDeclaration(node, decorators, modifiers, name, members) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.name !== name + || node.members !== members + ? updateNode(createEnumDeclaration(decorators, modifiers, name, members), node) + : node; + } + ts.updateEnumDeclaration = updateEnumDeclaration; + function createModuleDeclaration(decorators, modifiers, name, body, flags) { + if (flags === void 0) { flags = 0 /* None */; } + var node = createSynthesizedNode(244 /* ModuleDeclaration */); + node.flags |= flags & (16 /* Namespace */ | 4 /* NestedNamespace */ | 512 /* GlobalAugmentation */); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.name = name; + node.body = body; + return node; + } + ts.createModuleDeclaration = createModuleDeclaration; + function updateModuleDeclaration(node, decorators, modifiers, name, body) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.name !== name + || node.body !== body + ? updateNode(createModuleDeclaration(decorators, modifiers, name, body, node.flags), node) + : node; + } + ts.updateModuleDeclaration = updateModuleDeclaration; + function createModuleBlock(statements) { + var node = createSynthesizedNode(245 /* ModuleBlock */); + node.statements = createNodeArray(statements); + return node; + } + ts.createModuleBlock = createModuleBlock; + function updateModuleBlock(node, statements) { + return node.statements !== statements + ? updateNode(createModuleBlock(statements), node) + : node; + } + ts.updateModuleBlock = updateModuleBlock; + function createCaseBlock(clauses) { + var node = createSynthesizedNode(246 /* CaseBlock */); + node.clauses = createNodeArray(clauses); + return node; + } + ts.createCaseBlock = createCaseBlock; + function updateCaseBlock(node, clauses) { + return node.clauses !== clauses + ? updateNode(createCaseBlock(clauses), node) + : node; + } + ts.updateCaseBlock = updateCaseBlock; + function createNamespaceExportDeclaration(name) { + var node = createSynthesizedNode(247 /* NamespaceExportDeclaration */); + node.name = asName(name); + return node; + } + ts.createNamespaceExportDeclaration = createNamespaceExportDeclaration; + function updateNamespaceExportDeclaration(node, name) { + return node.name !== name + ? updateNode(createNamespaceExportDeclaration(name), node) + : node; + } + ts.updateNamespaceExportDeclaration = updateNamespaceExportDeclaration; + function createImportEqualsDeclaration(decorators, modifiers, name, moduleReference) { + var node = createSynthesizedNode(248 /* ImportEqualsDeclaration */); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.name = asName(name); + node.moduleReference = moduleReference; + return node; + } + ts.createImportEqualsDeclaration = createImportEqualsDeclaration; + function updateImportEqualsDeclaration(node, decorators, modifiers, name, moduleReference) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.name !== name + || node.moduleReference !== moduleReference + ? updateNode(createImportEqualsDeclaration(decorators, modifiers, name, moduleReference), node) + : node; + } + ts.updateImportEqualsDeclaration = updateImportEqualsDeclaration; + function createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier) { + var node = createSynthesizedNode(249 /* ImportDeclaration */); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.importClause = importClause; + node.moduleSpecifier = moduleSpecifier; + return node; + } + ts.createImportDeclaration = createImportDeclaration; + function updateImportDeclaration(node, decorators, modifiers, importClause, moduleSpecifier) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.importClause !== importClause + || node.moduleSpecifier !== moduleSpecifier + ? updateNode(createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier), node) + : node; + } + ts.updateImportDeclaration = updateImportDeclaration; + function createImportClause(name, namedBindings) { + var node = createSynthesizedNode(250 /* ImportClause */); + node.name = name; + node.namedBindings = namedBindings; + return node; + } + ts.createImportClause = createImportClause; + function updateImportClause(node, name, namedBindings) { + return node.name !== name + || node.namedBindings !== namedBindings + ? updateNode(createImportClause(name, namedBindings), node) + : node; + } + ts.updateImportClause = updateImportClause; + function createNamespaceImport(name) { + var node = createSynthesizedNode(251 /* NamespaceImport */); + node.name = name; + return node; + } + ts.createNamespaceImport = createNamespaceImport; + function updateNamespaceImport(node, name) { + return node.name !== name + ? updateNode(createNamespaceImport(name), node) + : node; + } + ts.updateNamespaceImport = updateNamespaceImport; + function createNamedImports(elements) { + var node = createSynthesizedNode(252 /* NamedImports */); + node.elements = createNodeArray(elements); + return node; + } + ts.createNamedImports = createNamedImports; + function updateNamedImports(node, elements) { + return node.elements !== elements + ? updateNode(createNamedImports(elements), node) + : node; + } + ts.updateNamedImports = updateNamedImports; + function createImportSpecifier(propertyName, name) { + var node = createSynthesizedNode(253 /* ImportSpecifier */); + node.propertyName = propertyName; + node.name = name; + return node; + } + ts.createImportSpecifier = createImportSpecifier; + function updateImportSpecifier(node, propertyName, name) { + return node.propertyName !== propertyName + || node.name !== name + ? updateNode(createImportSpecifier(propertyName, name), node) + : node; + } + ts.updateImportSpecifier = updateImportSpecifier; + function createExportAssignment(decorators, modifiers, isExportEquals, expression) { + var node = createSynthesizedNode(254 /* ExportAssignment */); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.isExportEquals = isExportEquals; + node.expression = isExportEquals ? ts.parenthesizeBinaryOperand(59 /* EqualsToken */, expression, /*isLeftSideOfBinary*/ false, /*leftOperand*/ undefined) : ts.parenthesizeDefaultExpression(expression); + return node; + } + ts.createExportAssignment = createExportAssignment; + function updateExportAssignment(node, decorators, modifiers, expression) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.expression !== expression + ? updateNode(createExportAssignment(decorators, modifiers, node.isExportEquals, expression), node) + : node; + } + ts.updateExportAssignment = updateExportAssignment; + function createExportDeclaration(decorators, modifiers, exportClause, moduleSpecifier) { + var node = createSynthesizedNode(255 /* ExportDeclaration */); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.exportClause = exportClause; + node.moduleSpecifier = moduleSpecifier; + return node; + } + ts.createExportDeclaration = createExportDeclaration; + function updateExportDeclaration(node, decorators, modifiers, exportClause, moduleSpecifier) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.exportClause !== exportClause + || node.moduleSpecifier !== moduleSpecifier + ? updateNode(createExportDeclaration(decorators, modifiers, exportClause, moduleSpecifier), node) + : node; + } + ts.updateExportDeclaration = updateExportDeclaration; + function createNamedExports(elements) { + var node = createSynthesizedNode(256 /* NamedExports */); + node.elements = createNodeArray(elements); + return node; + } + ts.createNamedExports = createNamedExports; + function updateNamedExports(node, elements) { + return node.elements !== elements + ? updateNode(createNamedExports(elements), node) + : node; + } + ts.updateNamedExports = updateNamedExports; + function createExportSpecifier(propertyName, name) { + var node = createSynthesizedNode(257 /* ExportSpecifier */); + node.propertyName = asName(propertyName); + node.name = asName(name); + return node; + } + ts.createExportSpecifier = createExportSpecifier; + function updateExportSpecifier(node, propertyName, name) { + return node.propertyName !== propertyName + || node.name !== name + ? updateNode(createExportSpecifier(propertyName, name), node) + : node; + } + ts.updateExportSpecifier = updateExportSpecifier; + // Module references + function createExternalModuleReference(expression) { + var node = createSynthesizedNode(259 /* ExternalModuleReference */); + node.expression = expression; + return node; + } + ts.createExternalModuleReference = createExternalModuleReference; + function updateExternalModuleReference(node, expression) { + return node.expression !== expression + ? updateNode(createExternalModuleReference(expression), node) + : node; + } + ts.updateExternalModuleReference = updateExternalModuleReference; + // JSDoc + /* @internal */ + function createJSDocTypeExpression(type) { + var node = createSynthesizedNode(283 /* JSDocTypeExpression */); + node.type = type; + return node; + } + ts.createJSDocTypeExpression = createJSDocTypeExpression; + /* @internal */ + function createJSDocTypeTag(typeExpression, comment) { + var tag = createJSDocTag(302 /* JSDocTypeTag */, "type"); + tag.typeExpression = typeExpression; + tag.comment = comment; + return tag; + } + ts.createJSDocTypeTag = createJSDocTypeTag; + /* @internal */ + function createJSDocReturnTag(typeExpression, comment) { + var tag = createJSDocTag(300 /* JSDocReturnTag */, "returns"); + tag.typeExpression = typeExpression; + tag.comment = comment; + return tag; + } + ts.createJSDocReturnTag = createJSDocReturnTag; + /* @internal */ + function createJSDocParamTag(name, isBracketed, typeExpression, comment) { + var tag = createJSDocTag(299 /* JSDocParameterTag */, "param"); + tag.typeExpression = typeExpression; + tag.name = name; + tag.isBracketed = isBracketed; + tag.comment = comment; + return tag; + } + ts.createJSDocParamTag = createJSDocParamTag; + /* @internal */ + function createJSDocComment(comment, tags) { + var node = createSynthesizedNode(291 /* JSDocComment */); + node.comment = comment; + node.tags = tags; + return node; + } + ts.createJSDocComment = createJSDocComment; + /* @internal */ + function createJSDocTag(kind, tagName) { + var node = createSynthesizedNode(kind); + node.tagName = createIdentifier(tagName); + return node; + } + // JSX + function createJsxElement(openingElement, children, closingElement) { + var node = createSynthesizedNode(260 /* JsxElement */); + node.openingElement = openingElement; + node.children = createNodeArray(children); + node.closingElement = closingElement; + return node; + } + ts.createJsxElement = createJsxElement; + function updateJsxElement(node, openingElement, children, closingElement) { + return node.openingElement !== openingElement + || node.children !== children + || node.closingElement !== closingElement + ? updateNode(createJsxElement(openingElement, children, closingElement), node) + : node; + } + ts.updateJsxElement = updateJsxElement; + function createJsxSelfClosingElement(tagName, typeArguments, attributes) { + var node = createSynthesizedNode(261 /* JsxSelfClosingElement */); + node.tagName = tagName; + node.typeArguments = asNodeArray(typeArguments); + node.attributes = attributes; + return node; + } + ts.createJsxSelfClosingElement = createJsxSelfClosingElement; + function updateJsxSelfClosingElement(node, tagName, typeArguments, attributes) { + return node.tagName !== tagName + || node.typeArguments !== typeArguments + || node.attributes !== attributes + ? updateNode(createJsxSelfClosingElement(tagName, typeArguments, attributes), node) + : node; + } + ts.updateJsxSelfClosingElement = updateJsxSelfClosingElement; + function createJsxOpeningElement(tagName, typeArguments, attributes) { + var node = createSynthesizedNode(262 /* JsxOpeningElement */); + node.tagName = tagName; + node.typeArguments = asNodeArray(typeArguments); + node.attributes = attributes; + return node; + } + ts.createJsxOpeningElement = createJsxOpeningElement; + function updateJsxOpeningElement(node, tagName, typeArguments, attributes) { + return node.tagName !== tagName + || node.typeArguments !== typeArguments + || node.attributes !== attributes + ? updateNode(createJsxOpeningElement(tagName, typeArguments, attributes), node) + : node; + } + ts.updateJsxOpeningElement = updateJsxOpeningElement; + function createJsxClosingElement(tagName) { + var node = createSynthesizedNode(263 /* JsxClosingElement */); + node.tagName = tagName; + return node; + } + ts.createJsxClosingElement = createJsxClosingElement; + function updateJsxClosingElement(node, tagName) { + return node.tagName !== tagName + ? updateNode(createJsxClosingElement(tagName), node) + : node; + } + ts.updateJsxClosingElement = updateJsxClosingElement; + function createJsxFragment(openingFragment, children, closingFragment) { + var node = createSynthesizedNode(264 /* JsxFragment */); + node.openingFragment = openingFragment; + node.children = createNodeArray(children); + node.closingFragment = closingFragment; + return node; + } + ts.createJsxFragment = createJsxFragment; + function updateJsxFragment(node, openingFragment, children, closingFragment) { + return node.openingFragment !== openingFragment + || node.children !== children + || node.closingFragment !== closingFragment + ? updateNode(createJsxFragment(openingFragment, children, closingFragment), node) + : node; + } + ts.updateJsxFragment = updateJsxFragment; + function createJsxAttribute(name, initializer) { + var node = createSynthesizedNode(267 /* JsxAttribute */); + node.name = name; + node.initializer = initializer; + return node; + } + ts.createJsxAttribute = createJsxAttribute; + function updateJsxAttribute(node, name, initializer) { + return node.name !== name + || node.initializer !== initializer + ? updateNode(createJsxAttribute(name, initializer), node) + : node; + } + ts.updateJsxAttribute = updateJsxAttribute; + function createJsxAttributes(properties) { + var node = createSynthesizedNode(268 /* JsxAttributes */); + node.properties = createNodeArray(properties); + return node; + } + ts.createJsxAttributes = createJsxAttributes; + function updateJsxAttributes(node, properties) { + return node.properties !== properties + ? updateNode(createJsxAttributes(properties), node) + : node; + } + ts.updateJsxAttributes = updateJsxAttributes; + function createJsxSpreadAttribute(expression) { + var node = createSynthesizedNode(269 /* JsxSpreadAttribute */); + node.expression = expression; + return node; + } + ts.createJsxSpreadAttribute = createJsxSpreadAttribute; + function updateJsxSpreadAttribute(node, expression) { + return node.expression !== expression + ? updateNode(createJsxSpreadAttribute(expression), node) + : node; + } + ts.updateJsxSpreadAttribute = updateJsxSpreadAttribute; + function createJsxExpression(dotDotDotToken, expression) { + var node = createSynthesizedNode(270 /* JsxExpression */); + node.dotDotDotToken = dotDotDotToken; + node.expression = expression; + return node; + } + ts.createJsxExpression = createJsxExpression; + function updateJsxExpression(node, expression) { + return node.expression !== expression + ? updateNode(createJsxExpression(node.dotDotDotToken, expression), node) + : node; + } + ts.updateJsxExpression = updateJsxExpression; + // Clauses + function createCaseClause(expression, statements) { + var node = createSynthesizedNode(271 /* CaseClause */); + node.expression = ts.parenthesizeExpressionForList(expression); + node.statements = createNodeArray(statements); + return node; + } + ts.createCaseClause = createCaseClause; + function updateCaseClause(node, expression, statements) { + return node.expression !== expression + || node.statements !== statements + ? updateNode(createCaseClause(expression, statements), node) + : node; + } + ts.updateCaseClause = updateCaseClause; + function createDefaultClause(statements) { + var node = createSynthesizedNode(272 /* DefaultClause */); + node.statements = createNodeArray(statements); + return node; + } + ts.createDefaultClause = createDefaultClause; + function updateDefaultClause(node, statements) { + return node.statements !== statements + ? updateNode(createDefaultClause(statements), node) + : node; + } + ts.updateDefaultClause = updateDefaultClause; + function createHeritageClause(token, types) { + var node = createSynthesizedNode(273 /* HeritageClause */); + node.token = token; + node.types = createNodeArray(types); + return node; + } + ts.createHeritageClause = createHeritageClause; + function updateHeritageClause(node, types) { + return node.types !== types + ? updateNode(createHeritageClause(node.token, types), node) + : node; + } + ts.updateHeritageClause = updateHeritageClause; + function createCatchClause(variableDeclaration, block) { + var node = createSynthesizedNode(274 /* CatchClause */); + node.variableDeclaration = ts.isString(variableDeclaration) ? createVariableDeclaration(variableDeclaration) : variableDeclaration; + node.block = block; + return node; + } + ts.createCatchClause = createCatchClause; + function updateCatchClause(node, variableDeclaration, block) { + return node.variableDeclaration !== variableDeclaration + || node.block !== block + ? updateNode(createCatchClause(variableDeclaration, block), node) + : node; + } + ts.updateCatchClause = updateCatchClause; + // Property assignments + function createPropertyAssignment(name, initializer) { + var node = createSynthesizedNode(275 /* PropertyAssignment */); + node.name = asName(name); + node.questionToken = undefined; + node.initializer = ts.parenthesizeExpressionForList(initializer); + return node; + } + ts.createPropertyAssignment = createPropertyAssignment; + function updatePropertyAssignment(node, name, initializer) { + return node.name !== name + || node.initializer !== initializer + ? updateNode(createPropertyAssignment(name, initializer), node) + : node; + } + ts.updatePropertyAssignment = updatePropertyAssignment; + function createShorthandPropertyAssignment(name, objectAssignmentInitializer) { + var node = createSynthesizedNode(276 /* ShorthandPropertyAssignment */); + node.name = asName(name); + node.objectAssignmentInitializer = objectAssignmentInitializer !== undefined ? ts.parenthesizeExpressionForList(objectAssignmentInitializer) : undefined; + return node; + } + ts.createShorthandPropertyAssignment = createShorthandPropertyAssignment; + function updateShorthandPropertyAssignment(node, name, objectAssignmentInitializer) { + return node.name !== name + || node.objectAssignmentInitializer !== objectAssignmentInitializer + ? updateNode(createShorthandPropertyAssignment(name, objectAssignmentInitializer), node) + : node; + } + ts.updateShorthandPropertyAssignment = updateShorthandPropertyAssignment; + function createSpreadAssignment(expression) { + var node = createSynthesizedNode(277 /* SpreadAssignment */); + node.expression = expression !== undefined ? ts.parenthesizeExpressionForList(expression) : undefined; // TODO: GH#18217 + return node; + } + ts.createSpreadAssignment = createSpreadAssignment; + function updateSpreadAssignment(node, expression) { + return node.expression !== expression + ? updateNode(createSpreadAssignment(expression), node) + : node; + } + ts.updateSpreadAssignment = updateSpreadAssignment; + // Enum + function createEnumMember(name, initializer) { + var node = createSynthesizedNode(278 /* EnumMember */); + node.name = asName(name); + node.initializer = initializer && ts.parenthesizeExpressionForList(initializer); + return node; + } + ts.createEnumMember = createEnumMember; + function updateEnumMember(node, name, initializer) { + return node.name !== name + || node.initializer !== initializer + ? updateNode(createEnumMember(name, initializer), node) + : node; + } + ts.updateEnumMember = updateEnumMember; + // Top-level nodes + function updateSourceFileNode(node, statements, isDeclarationFile, referencedFiles, typeReferences, hasNoDefaultLib, libReferences) { + if (node.statements !== statements || + (isDeclarationFile !== undefined && node.isDeclarationFile !== isDeclarationFile) || + (referencedFiles !== undefined && node.referencedFiles !== referencedFiles) || + (typeReferences !== undefined && node.typeReferenceDirectives !== typeReferences) || + (libReferences !== undefined && node.libReferenceDirectives !== libReferences) || + (hasNoDefaultLib !== undefined && node.hasNoDefaultLib !== hasNoDefaultLib)) { + var updated = createSynthesizedNode(279 /* SourceFile */); + updated.flags |= node.flags; + updated.statements = createNodeArray(statements); + updated.endOfFileToken = node.endOfFileToken; + updated.fileName = node.fileName; + updated.path = node.path; + updated.text = node.text; + updated.isDeclarationFile = isDeclarationFile === undefined ? node.isDeclarationFile : isDeclarationFile; + updated.referencedFiles = referencedFiles === undefined ? node.referencedFiles : referencedFiles; + updated.typeReferenceDirectives = typeReferences === undefined ? node.typeReferenceDirectives : typeReferences; + updated.hasNoDefaultLib = hasNoDefaultLib === undefined ? node.hasNoDefaultLib : hasNoDefaultLib; + updated.libReferenceDirectives = libReferences === undefined ? node.libReferenceDirectives : libReferences; + if (node.amdDependencies !== undefined) + updated.amdDependencies = node.amdDependencies; + if (node.moduleName !== undefined) + updated.moduleName = node.moduleName; + if (node.languageVariant !== undefined) + updated.languageVariant = node.languageVariant; + if (node.renamedDependencies !== undefined) + updated.renamedDependencies = node.renamedDependencies; + if (node.languageVersion !== undefined) + updated.languageVersion = node.languageVersion; + if (node.scriptKind !== undefined) + updated.scriptKind = node.scriptKind; + if (node.externalModuleIndicator !== undefined) + updated.externalModuleIndicator = node.externalModuleIndicator; + if (node.commonJsModuleIndicator !== undefined) + updated.commonJsModuleIndicator = node.commonJsModuleIndicator; + if (node.identifiers !== undefined) + updated.identifiers = node.identifiers; + if (node.nodeCount !== undefined) + updated.nodeCount = node.nodeCount; + if (node.identifierCount !== undefined) + updated.identifierCount = node.identifierCount; + if (node.symbolCount !== undefined) + updated.symbolCount = node.symbolCount; + if (node.parseDiagnostics !== undefined) + updated.parseDiagnostics = node.parseDiagnostics; + if (node.bindDiagnostics !== undefined) + updated.bindDiagnostics = node.bindDiagnostics; + if (node.bindSuggestionDiagnostics !== undefined) + updated.bindSuggestionDiagnostics = node.bindSuggestionDiagnostics; + if (node.lineMap !== undefined) + updated.lineMap = node.lineMap; + if (node.classifiableNames !== undefined) + updated.classifiableNames = node.classifiableNames; + if (node.resolvedModules !== undefined) + updated.resolvedModules = node.resolvedModules; + if (node.resolvedTypeReferenceDirectiveNames !== undefined) + updated.resolvedTypeReferenceDirectiveNames = node.resolvedTypeReferenceDirectiveNames; + if (node.imports !== undefined) + updated.imports = node.imports; + if (node.moduleAugmentations !== undefined) + updated.moduleAugmentations = node.moduleAugmentations; + if (node.pragmas !== undefined) + updated.pragmas = node.pragmas; + if (node.localJsxFactory !== undefined) + updated.localJsxFactory = node.localJsxFactory; + if (node.localJsxNamespace !== undefined) + updated.localJsxNamespace = node.localJsxNamespace; + return updateNode(updated, node); + } + return node; + } + ts.updateSourceFileNode = updateSourceFileNode; + /** + * Creates a shallow, memberwise clone of a node for mutation. + */ + function getMutableClone(node) { + var clone = getSynthesizedClone(node); + clone.pos = node.pos; + clone.end = node.end; + clone.parent = node.parent; + return clone; + } + ts.getMutableClone = getMutableClone; + // Transformation nodes + /** + * Creates a synthetic statement to act as a placeholder for a not-emitted statement in + * order to preserve comments. + * + * @param original The original statement. + */ + function createNotEmittedStatement(original) { + var node = createSynthesizedNode(307 /* NotEmittedStatement */); + node.original = original; + setTextRange(node, original); + return node; + } + ts.createNotEmittedStatement = createNotEmittedStatement; + /** + * Creates a synthetic element to act as a placeholder for the end of an emitted declaration in + * order to properly emit exports. + */ + /* @internal */ + function createEndOfDeclarationMarker(original) { + var node = createSynthesizedNode(311 /* EndOfDeclarationMarker */); + node.emitNode = {}; + node.original = original; + return node; + } + ts.createEndOfDeclarationMarker = createEndOfDeclarationMarker; + /** + * Creates a synthetic element to act as a placeholder for the beginning of a merged declaration in + * order to properly emit exports. + */ + /* @internal */ + function createMergeDeclarationMarker(original) { + var node = createSynthesizedNode(310 /* MergeDeclarationMarker */); + node.emitNode = {}; + node.original = original; + return node; + } + ts.createMergeDeclarationMarker = createMergeDeclarationMarker; + /** + * Creates a synthetic expression to act as a placeholder for a not-emitted expression in + * order to preserve comments or sourcemap positions. + * + * @param expression The inner expression to emit. + * @param original The original outer expression. + * @param location The location for the expression. Defaults to the positions from "original" if provided. + */ + function createPartiallyEmittedExpression(expression, original) { + var node = createSynthesizedNode(308 /* PartiallyEmittedExpression */); + node.expression = expression; + node.original = original; + setTextRange(node, original); + return node; + } + ts.createPartiallyEmittedExpression = createPartiallyEmittedExpression; + function updatePartiallyEmittedExpression(node, expression) { + if (node.expression !== expression) { + return updateNode(createPartiallyEmittedExpression(expression, node.original), node); + } + return node; + } + ts.updatePartiallyEmittedExpression = updatePartiallyEmittedExpression; + function flattenCommaElements(node) { + if (ts.nodeIsSynthesized(node) && !ts.isParseTreeNode(node) && !node.original && !node.emitNode && !node.id) { + if (node.kind === 309 /* CommaListExpression */) { + return node.elements; + } + if (ts.isBinaryExpression(node) && node.operatorToken.kind === 27 /* CommaToken */) { + return [node.left, node.right]; + } + } + return node; + } + function createCommaList(elements) { + var node = createSynthesizedNode(309 /* CommaListExpression */); + node.elements = createNodeArray(ts.sameFlatMap(elements, flattenCommaElements)); + return node; + } + ts.createCommaList = createCommaList; + function updateCommaList(node, elements) { + return node.elements !== elements + ? updateNode(createCommaList(elements), node) + : node; + } + ts.updateCommaList = updateCommaList; + function createBundle(sourceFiles, prepends) { + if (prepends === void 0) { prepends = ts.emptyArray; } + var node = ts.createNode(280 /* Bundle */); + node.prepends = prepends; + node.sourceFiles = sourceFiles; + return node; + } + ts.createBundle = createBundle; + function createUnparsedSourceFile(text, mapPath, map) { + var node = ts.createNode(281 /* UnparsedSource */); + node.text = text; + node.sourceMapPath = mapPath; + node.sourceMapText = map; + return node; + } + ts.createUnparsedSourceFile = createUnparsedSourceFile; + function createInputFiles(javascript, declaration, javascriptMapPath, javascriptMapText, declarationMapPath, declarationMapText) { + var node = ts.createNode(282 /* InputFiles */); + node.javascriptText = javascript; + node.javascriptMapPath = javascriptMapPath; + node.javascriptMapText = javascriptMapText; + node.declarationText = declaration; + node.declarationMapPath = declarationMapPath; + node.declarationMapText = declarationMapText; + return node; + } + ts.createInputFiles = createInputFiles; + function updateBundle(node, sourceFiles, prepends) { + if (prepends === void 0) { prepends = ts.emptyArray; } + if (node.sourceFiles !== sourceFiles || node.prepends !== prepends) { + return createBundle(sourceFiles, prepends); + } + return node; + } + ts.updateBundle = updateBundle; + function createImmediatelyInvokedFunctionExpression(statements, param, paramValue) { + return createCall(createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, + /*parameters*/ param ? [param] : [], + /*type*/ undefined, createBlock(statements, /*multiLine*/ true)), + /*typeArguments*/ undefined, + /*argumentsArray*/ paramValue ? [paramValue] : []); + } + ts.createImmediatelyInvokedFunctionExpression = createImmediatelyInvokedFunctionExpression; + function createImmediatelyInvokedArrowFunction(statements, param, paramValue) { + return createCall(createArrowFunction( + /*modifiers*/ undefined, + /*typeParameters*/ undefined, + /*parameters*/ param ? [param] : [], + /*type*/ undefined, + /*equalsGreaterThanToken*/ undefined, createBlock(statements, /*multiLine*/ true)), + /*typeArguments*/ undefined, + /*argumentsArray*/ paramValue ? [paramValue] : []); + } + ts.createImmediatelyInvokedArrowFunction = createImmediatelyInvokedArrowFunction; + function createComma(left, right) { + return createBinary(left, 27 /* CommaToken */, right); + } + ts.createComma = createComma; + function createLessThan(left, right) { + return createBinary(left, 28 /* LessThanToken */, right); + } + ts.createLessThan = createLessThan; + function createAssignment(left, right) { + return createBinary(left, 59 /* EqualsToken */, right); + } + ts.createAssignment = createAssignment; + function createStrictEquality(left, right) { + return createBinary(left, 35 /* EqualsEqualsEqualsToken */, right); + } + ts.createStrictEquality = createStrictEquality; + function createStrictInequality(left, right) { + return createBinary(left, 36 /* ExclamationEqualsEqualsToken */, right); + } + ts.createStrictInequality = createStrictInequality; + function createAdd(left, right) { + return createBinary(left, 38 /* PlusToken */, right); + } + ts.createAdd = createAdd; + function createSubtract(left, right) { + return createBinary(left, 39 /* MinusToken */, right); + } + ts.createSubtract = createSubtract; + function createPostfixIncrement(operand) { + return createPostfix(operand, 44 /* PlusPlusToken */); + } + ts.createPostfixIncrement = createPostfixIncrement; + function createLogicalAnd(left, right) { + return createBinary(left, 54 /* AmpersandAmpersandToken */, right); + } + ts.createLogicalAnd = createLogicalAnd; + function createLogicalOr(left, right) { + return createBinary(left, 55 /* BarBarToken */, right); + } + ts.createLogicalOr = createLogicalOr; + function createLogicalNot(operand) { + return createPrefix(52 /* ExclamationToken */, operand); + } + ts.createLogicalNot = createLogicalNot; + function createVoidZero() { + return createVoid(createLiteral(0)); + } + ts.createVoidZero = createVoidZero; + function createExportDefault(expression) { + return createExportAssignment(/*decorators*/ undefined, /*modifiers*/ undefined, /*isExportEquals*/ false, expression); + } + ts.createExportDefault = createExportDefault; + function createExternalModuleExport(exportName) { + return createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, createNamedExports([createExportSpecifier(/*propertyName*/ undefined, exportName)])); + } + ts.createExternalModuleExport = createExternalModuleExport; + // Utilities + function asName(name) { + return ts.isString(name) ? createIdentifier(name) : name; + } + function asExpression(value) { + return ts.isString(value) || typeof value === "number" ? createLiteral(value) : value; + } + function asNodeArray(array) { + return array ? createNodeArray(array) : undefined; + } + function asToken(value) { + return typeof value === "number" ? createToken(value) : value; + } + /** + * Clears any EmitNode entries from parse-tree nodes. + * @param sourceFile A source file. + */ + function disposeEmitNodes(sourceFile) { + // During transformation we may need to annotate a parse tree node with transient + // transformation properties. As parse tree nodes live longer than transformation + // nodes, we need to make sure we reclaim any memory allocated for custom ranges + // from these nodes to ensure we do not hold onto entire subtrees just for position + // information. We also need to reset these nodes to a pre-transformation state + // for incremental parsing scenarios so that we do not impact later emit. + sourceFile = ts.getSourceFileOfNode(ts.getParseTreeNode(sourceFile)); + var emitNode = sourceFile && sourceFile.emitNode; + var annotatedNodes = emitNode && emitNode.annotatedNodes; + if (annotatedNodes) { + for (var _i = 0, annotatedNodes_1 = annotatedNodes; _i < annotatedNodes_1.length; _i++) { + var node = annotatedNodes_1[_i]; + node.emitNode = undefined; + } + } + } + ts.disposeEmitNodes = disposeEmitNodes; + /** + * Associates a node with the current transformation, initializing + * various transient transformation properties. + */ + /* @internal */ + function getOrCreateEmitNode(node) { + if (!node.emitNode) { + if (ts.isParseTreeNode(node)) { + // To avoid holding onto transformation artifacts, we keep track of any + // parse tree node we are annotating. This allows us to clean them up after + // all transformations have completed. + if (node.kind === 279 /* SourceFile */) { + return node.emitNode = { annotatedNodes: [node] }; + } + var sourceFile = ts.getSourceFileOfNode(node); + getOrCreateEmitNode(sourceFile).annotatedNodes.push(node); + } + node.emitNode = {}; + } + return node.emitNode; + } + ts.getOrCreateEmitNode = getOrCreateEmitNode; + function setTextRange(range, location) { + if (location) { + range.pos = location.pos; + range.end = location.end; + } + return range; + } + ts.setTextRange = setTextRange; + /** + * Sets flags that control emit behavior of a node. + */ + function setEmitFlags(node, emitFlags) { + getOrCreateEmitNode(node).flags = emitFlags; + return node; + } + ts.setEmitFlags = setEmitFlags; + /** + * Sets flags that control emit behavior of a node. + */ + /* @internal */ + function addEmitFlags(node, emitFlags) { + var emitNode = getOrCreateEmitNode(node); + emitNode.flags = emitNode.flags | emitFlags; + return node; + } + ts.addEmitFlags = addEmitFlags; + /** + * Gets a custom text range to use when emitting source maps. + */ + function getSourceMapRange(node) { + var emitNode = node.emitNode; + return (emitNode && emitNode.sourceMapRange) || node; + } + ts.getSourceMapRange = getSourceMapRange; + /** + * Sets a custom text range to use when emitting source maps. + */ + function setSourceMapRange(node, range) { + getOrCreateEmitNode(node).sourceMapRange = range; + return node; + } + ts.setSourceMapRange = setSourceMapRange; + // tslint:disable-next-line variable-name + var SourceMapSource; + /** + * Create an external source map source file reference + */ + function createSourceMapSource(fileName, text, skipTrivia) { + return new (SourceMapSource || (SourceMapSource = ts.objectAllocator.getSourceMapSourceConstructor()))(fileName, text, skipTrivia); + } + ts.createSourceMapSource = createSourceMapSource; + /** + * Gets the TextRange to use for source maps for a token of a node. + */ + function getTokenSourceMapRange(node, token) { + var emitNode = node.emitNode; + var tokenSourceMapRanges = emitNode && emitNode.tokenSourceMapRanges; + return tokenSourceMapRanges && tokenSourceMapRanges[token]; + } + ts.getTokenSourceMapRange = getTokenSourceMapRange; + /** + * Sets the TextRange to use for source maps for a token of a node. + */ + function setTokenSourceMapRange(node, token, range) { + var emitNode = getOrCreateEmitNode(node); + var tokenSourceMapRanges = emitNode.tokenSourceMapRanges || (emitNode.tokenSourceMapRanges = []); + tokenSourceMapRanges[token] = range; + return node; + } + ts.setTokenSourceMapRange = setTokenSourceMapRange; + /** + * Gets a custom text range to use when emitting comments. + */ + /*@internal*/ + function getStartsOnNewLine(node) { + var emitNode = node.emitNode; + return emitNode && emitNode.startsOnNewLine; + } + ts.getStartsOnNewLine = getStartsOnNewLine; + /** + * Sets a custom text range to use when emitting comments. + */ + /*@internal*/ + function setStartsOnNewLine(node, newLine) { + getOrCreateEmitNode(node).startsOnNewLine = newLine; + return node; + } + ts.setStartsOnNewLine = setStartsOnNewLine; + /** + * Gets a custom text range to use when emitting comments. + */ + function getCommentRange(node) { + var emitNode = node.emitNode; + return (emitNode && emitNode.commentRange) || node; + } + ts.getCommentRange = getCommentRange; + /** + * Sets a custom text range to use when emitting comments. + */ + function setCommentRange(node, range) { + getOrCreateEmitNode(node).commentRange = range; + return node; + } + ts.setCommentRange = setCommentRange; + function getSyntheticLeadingComments(node) { + var emitNode = node.emitNode; + return emitNode && emitNode.leadingComments; + } + ts.getSyntheticLeadingComments = getSyntheticLeadingComments; + function setSyntheticLeadingComments(node, comments) { + getOrCreateEmitNode(node).leadingComments = comments; + return node; + } + ts.setSyntheticLeadingComments = setSyntheticLeadingComments; + function addSyntheticLeadingComment(node, kind, text, hasTrailingNewLine) { + return setSyntheticLeadingComments(node, ts.append(getSyntheticLeadingComments(node), { kind: kind, pos: -1, end: -1, hasTrailingNewLine: hasTrailingNewLine, text: text })); + } + ts.addSyntheticLeadingComment = addSyntheticLeadingComment; + function getSyntheticTrailingComments(node) { + var emitNode = node.emitNode; + return emitNode && emitNode.trailingComments; + } + ts.getSyntheticTrailingComments = getSyntheticTrailingComments; + function setSyntheticTrailingComments(node, comments) { + getOrCreateEmitNode(node).trailingComments = comments; + return node; + } + ts.setSyntheticTrailingComments = setSyntheticTrailingComments; + function addSyntheticTrailingComment(node, kind, text, hasTrailingNewLine) { + return setSyntheticTrailingComments(node, ts.append(getSyntheticTrailingComments(node), { kind: kind, pos: -1, end: -1, hasTrailingNewLine: hasTrailingNewLine, text: text })); + } + ts.addSyntheticTrailingComment = addSyntheticTrailingComment; + function moveSyntheticComments(node, original) { + setSyntheticLeadingComments(node, getSyntheticLeadingComments(original)); + setSyntheticTrailingComments(node, getSyntheticTrailingComments(original)); + var emit = getOrCreateEmitNode(original); + emit.leadingComments = undefined; + emit.trailingComments = undefined; + return node; + } + ts.moveSyntheticComments = moveSyntheticComments; + /** + * Gets the constant value to emit for an expression. + */ + function getConstantValue(node) { + var emitNode = node.emitNode; + return emitNode && emitNode.constantValue; + } + ts.getConstantValue = getConstantValue; + /** + * Sets the constant value to emit for an expression. + */ + function setConstantValue(node, value) { + var emitNode = getOrCreateEmitNode(node); + emitNode.constantValue = value; + return node; + } + ts.setConstantValue = setConstantValue; + /** + * Adds an EmitHelper to a node. + */ + function addEmitHelper(node, helper) { + var emitNode = getOrCreateEmitNode(node); + emitNode.helpers = ts.append(emitNode.helpers, helper); + return node; + } + ts.addEmitHelper = addEmitHelper; + /** + * Add EmitHelpers to a node. + */ + function addEmitHelpers(node, helpers) { + if (ts.some(helpers)) { + var emitNode = getOrCreateEmitNode(node); + for (var _i = 0, helpers_1 = helpers; _i < helpers_1.length; _i++) { + var helper = helpers_1[_i]; + emitNode.helpers = ts.appendIfUnique(emitNode.helpers, helper); + } + } + return node; + } + ts.addEmitHelpers = addEmitHelpers; + /** + * Removes an EmitHelper from a node. + */ + function removeEmitHelper(node, helper) { + var emitNode = node.emitNode; + if (emitNode) { + var helpers = emitNode.helpers; + if (helpers) { + return ts.orderedRemoveItem(helpers, helper); + } + } + return false; + } + ts.removeEmitHelper = removeEmitHelper; + /** + * Gets the EmitHelpers of a node. + */ + function getEmitHelpers(node) { + var emitNode = node.emitNode; + return emitNode && emitNode.helpers; + } + ts.getEmitHelpers = getEmitHelpers; + /** + * Moves matching emit helpers from a source node to a target node. + */ + function moveEmitHelpers(source, target, predicate) { + var sourceEmitNode = source.emitNode; + var sourceEmitHelpers = sourceEmitNode && sourceEmitNode.helpers; + if (!ts.some(sourceEmitHelpers)) + return; + var targetEmitNode = getOrCreateEmitNode(target); + var helpersRemoved = 0; + for (var i = 0; i < sourceEmitHelpers.length; i++) { + var helper = sourceEmitHelpers[i]; + if (predicate(helper)) { + helpersRemoved++; + targetEmitNode.helpers = ts.appendIfUnique(targetEmitNode.helpers, helper); + } + else if (helpersRemoved > 0) { + sourceEmitHelpers[i - helpersRemoved] = helper; + } + } + if (helpersRemoved > 0) { + sourceEmitHelpers.length -= helpersRemoved; + } + } + ts.moveEmitHelpers = moveEmitHelpers; + /* @internal */ + function compareEmitHelpers(x, y) { + if (x === y) + return 0 /* EqualTo */; + if (x.priority === y.priority) + return 0 /* EqualTo */; + if (x.priority === undefined) + return 1 /* GreaterThan */; + if (y.priority === undefined) + return -1 /* LessThan */; + return ts.compareValues(x.priority, y.priority); + } + ts.compareEmitHelpers = compareEmitHelpers; + function setOriginalNode(node, original) { + node.original = original; + if (original) { + var emitNode = original.emitNode; + if (emitNode) + node.emitNode = mergeEmitNode(emitNode, node.emitNode); + } + return node; + } + ts.setOriginalNode = setOriginalNode; + function mergeEmitNode(sourceEmitNode, destEmitNode) { + var flags = sourceEmitNode.flags, leadingComments = sourceEmitNode.leadingComments, trailingComments = sourceEmitNode.trailingComments, commentRange = sourceEmitNode.commentRange, sourceMapRange = sourceEmitNode.sourceMapRange, tokenSourceMapRanges = sourceEmitNode.tokenSourceMapRanges, constantValue = sourceEmitNode.constantValue, helpers = sourceEmitNode.helpers, startsOnNewLine = sourceEmitNode.startsOnNewLine; + if (!destEmitNode) + destEmitNode = {}; + // We are using `.slice()` here in case `destEmitNode.leadingComments` is pushed to later. + if (leadingComments) + destEmitNode.leadingComments = ts.addRange(leadingComments.slice(), destEmitNode.leadingComments); + if (trailingComments) + destEmitNode.trailingComments = ts.addRange(trailingComments.slice(), destEmitNode.trailingComments); + if (flags) + destEmitNode.flags = flags; + if (commentRange) + destEmitNode.commentRange = commentRange; + if (sourceMapRange) + destEmitNode.sourceMapRange = sourceMapRange; + if (tokenSourceMapRanges) + destEmitNode.tokenSourceMapRanges = mergeTokenSourceMapRanges(tokenSourceMapRanges, destEmitNode.tokenSourceMapRanges); + if (constantValue !== undefined) + destEmitNode.constantValue = constantValue; + if (helpers) + destEmitNode.helpers = ts.addRange(destEmitNode.helpers, helpers); + if (startsOnNewLine !== undefined) + destEmitNode.startsOnNewLine = startsOnNewLine; + return destEmitNode; + } + function mergeTokenSourceMapRanges(sourceRanges, destRanges) { + if (!destRanges) + destRanges = []; + for (var key in sourceRanges) { + destRanges[key] = sourceRanges[key]; + } + return destRanges; + } +})(ts || (ts = {})); +/* @internal */ +(function (ts) { + ts.nullTransformationContext = { + enableEmitNotification: ts.noop, + enableSubstitution: ts.noop, + endLexicalEnvironment: function () { return undefined; }, + getCompilerOptions: ts.notImplemented, + getEmitHost: ts.notImplemented, + getEmitResolver: ts.notImplemented, + hoistFunctionDeclaration: ts.noop, + hoistVariableDeclaration: ts.noop, + isEmitNotificationEnabled: ts.notImplemented, + isSubstitutionEnabled: ts.notImplemented, + onEmitNode: ts.noop, + onSubstituteNode: ts.notImplemented, + readEmitHelpers: ts.notImplemented, + requestEmitHelper: ts.noop, + resumeLexicalEnvironment: ts.noop, + startLexicalEnvironment: ts.noop, + suspendLexicalEnvironment: ts.noop, + addDiagnostic: ts.noop, + }; + function createTypeCheck(value, tag) { + return tag === "undefined" + ? ts.createStrictEquality(value, ts.createVoidZero()) + : ts.createStrictEquality(ts.createTypeOf(value), ts.createLiteral(tag)); + } + ts.createTypeCheck = createTypeCheck; + function createMemberAccessForPropertyName(target, memberName, location) { + if (ts.isComputedPropertyName(memberName)) { + return ts.setTextRange(ts.createElementAccess(target, memberName.expression), location); + } + else { + var expression = ts.setTextRange(ts.isIdentifier(memberName) + ? ts.createPropertyAccess(target, memberName) + : ts.createElementAccess(target, memberName), memberName); + ts.getOrCreateEmitNode(expression).flags |= 64 /* NoNestedSourceMaps */; + return expression; + } + } + ts.createMemberAccessForPropertyName = createMemberAccessForPropertyName; + function createFunctionCall(func, thisArg, argumentsList, location) { + return ts.setTextRange(ts.createCall(ts.createPropertyAccess(func, "call"), + /*typeArguments*/ undefined, [ + thisArg + ].concat(argumentsList)), location); + } + ts.createFunctionCall = createFunctionCall; + function createFunctionApply(func, thisArg, argumentsExpression, location) { + return ts.setTextRange(ts.createCall(ts.createPropertyAccess(func, "apply"), + /*typeArguments*/ undefined, [ + thisArg, + argumentsExpression + ]), location); + } + ts.createFunctionApply = createFunctionApply; + function createArraySlice(array, start) { + var argumentsList = []; + if (start !== undefined) { + argumentsList.push(typeof start === "number" ? ts.createLiteral(start) : start); + } + return ts.createCall(ts.createPropertyAccess(array, "slice"), /*typeArguments*/ undefined, argumentsList); + } + ts.createArraySlice = createArraySlice; + function createArrayConcat(array, values) { + return ts.createCall(ts.createPropertyAccess(array, "concat"), + /*typeArguments*/ undefined, values); + } + ts.createArrayConcat = createArrayConcat; + function createMathPow(left, right, location) { + return ts.setTextRange(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Math"), "pow"), + /*typeArguments*/ undefined, [left, right]), location); + } + ts.createMathPow = createMathPow; + function createReactNamespace(reactNamespace, parent) { + // To ensure the emit resolver can properly resolve the namespace, we need to + // treat this identifier as if it were a source tree node by clearing the `Synthesized` + // flag and setting a parent node. + var react = ts.createIdentifier(reactNamespace || "React"); + react.flags &= ~8 /* Synthesized */; + // Set the parent that is in parse tree + // this makes sure that parent chain is intact for checker to traverse complete scope tree + react.parent = ts.getParseTreeNode(parent); + return react; + } + function createJsxFactoryExpressionFromEntityName(jsxFactory, parent) { + if (ts.isQualifiedName(jsxFactory)) { + var left = createJsxFactoryExpressionFromEntityName(jsxFactory.left, parent); + var right = ts.createIdentifier(ts.idText(jsxFactory.right)); + right.escapedText = jsxFactory.right.escapedText; + return ts.createPropertyAccess(left, right); + } + else { + return createReactNamespace(ts.idText(jsxFactory), parent); + } + } + function createJsxFactoryExpression(jsxFactoryEntity, reactNamespace, parent) { + return jsxFactoryEntity ? + createJsxFactoryExpressionFromEntityName(jsxFactoryEntity, parent) : + ts.createPropertyAccess(createReactNamespace(reactNamespace, parent), "createElement"); + } + function createExpressionForJsxElement(jsxFactoryEntity, reactNamespace, tagName, props, children, parentElement, location) { + var argumentsList = [tagName]; + if (props) { + argumentsList.push(props); + } + if (children && children.length > 0) { + if (!props) { + argumentsList.push(ts.createNull()); + } + if (children.length > 1) { + for (var _i = 0, children_1 = children; _i < children_1.length; _i++) { + var child = children_1[_i]; + startOnNewLine(child); + argumentsList.push(child); + } + } + else { + argumentsList.push(children[0]); + } + } + return ts.setTextRange(ts.createCall(createJsxFactoryExpression(jsxFactoryEntity, reactNamespace, parentElement), + /*typeArguments*/ undefined, argumentsList), location); + } + ts.createExpressionForJsxElement = createExpressionForJsxElement; + function createExpressionForJsxFragment(jsxFactoryEntity, reactNamespace, children, parentElement, location) { + var tagName = ts.createPropertyAccess(createReactNamespace(reactNamespace, parentElement), "Fragment"); + var argumentsList = [tagName]; + argumentsList.push(ts.createNull()); + if (children && children.length > 0) { + if (children.length > 1) { + for (var _i = 0, children_2 = children; _i < children_2.length; _i++) { + var child = children_2[_i]; + startOnNewLine(child); + argumentsList.push(child); + } + } + else { + argumentsList.push(children[0]); + } + } + return ts.setTextRange(ts.createCall(createJsxFactoryExpression(jsxFactoryEntity, reactNamespace, parentElement), + /*typeArguments*/ undefined, argumentsList), location); + } + ts.createExpressionForJsxFragment = createExpressionForJsxFragment; + // Helpers + function getHelperName(name) { + return ts.setEmitFlags(ts.createIdentifier(name), 4096 /* HelperName */ | 2 /* AdviseOnEmitNode */); + } + ts.getHelperName = getHelperName; + var valuesHelper = { + name: "typescript:values", + scoped: false, + text: "\n var __values = (this && this.__values) || function (o) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator], i = 0;\n if (m) return m.call(o);\n return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n };" + }; + function createValuesHelper(context, expression, location) { + context.requestEmitHelper(valuesHelper); + return ts.setTextRange(ts.createCall(getHelperName("__values"), + /*typeArguments*/ undefined, [expression]), location); + } + ts.createValuesHelper = createValuesHelper; + var readHelper = { + name: "typescript:read", + scoped: false, + text: "\n var __read = (this && this.__read) || function (o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m) return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n }\n catch (error) { e = { error: error }; }\n finally {\n try {\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\n }\n finally { if (e) throw e.error; }\n }\n return ar;\n };" + }; + function createReadHelper(context, iteratorRecord, count, location) { + context.requestEmitHelper(readHelper); + return ts.setTextRange(ts.createCall(getHelperName("__read"), + /*typeArguments*/ undefined, count !== undefined + ? [iteratorRecord, ts.createLiteral(count)] + : [iteratorRecord]), location); + } + ts.createReadHelper = createReadHelper; + var spreadHelper = { + name: "typescript:spread", + scoped: false, + text: "\n var __spread = (this && this.__spread) || function () {\n for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i]));\n return ar;\n };" + }; + function createSpreadHelper(context, argumentList, location) { + context.requestEmitHelper(readHelper); + context.requestEmitHelper(spreadHelper); + return ts.setTextRange(ts.createCall(getHelperName("__spread"), + /*typeArguments*/ undefined, argumentList), location); + } + ts.createSpreadHelper = createSpreadHelper; + // Utilities + function createForOfBindingStatement(node, boundValue) { + if (ts.isVariableDeclarationList(node)) { + var firstDeclaration = ts.first(node.declarations); + var updatedDeclaration = ts.updateVariableDeclaration(firstDeclaration, firstDeclaration.name, + /*typeNode*/ undefined, boundValue); + return ts.setTextRange(ts.createVariableStatement( + /*modifiers*/ undefined, ts.updateVariableDeclarationList(node, [updatedDeclaration])), + /*location*/ node); + } + else { + var updatedExpression = ts.setTextRange(ts.createAssignment(node, boundValue), /*location*/ node); + return ts.setTextRange(ts.createStatement(updatedExpression), /*location*/ node); + } + } + ts.createForOfBindingStatement = createForOfBindingStatement; + function insertLeadingStatement(dest, source) { + if (ts.isBlock(dest)) { + return ts.updateBlock(dest, ts.setTextRange(ts.createNodeArray([source].concat(dest.statements)), dest.statements)); + } + else { + return ts.createBlock(ts.createNodeArray([dest, source]), /*multiLine*/ true); + } + } + ts.insertLeadingStatement = insertLeadingStatement; + function restoreEnclosingLabel(node, outermostLabeledStatement, afterRestoreLabelCallback) { + if (!outermostLabeledStatement) { + return node; + } + var updated = ts.updateLabel(outermostLabeledStatement, outermostLabeledStatement.label, outermostLabeledStatement.statement.kind === 233 /* LabeledStatement */ + ? restoreEnclosingLabel(node, outermostLabeledStatement.statement) + : node); + if (afterRestoreLabelCallback) { + afterRestoreLabelCallback(outermostLabeledStatement); + } + return updated; + } + ts.restoreEnclosingLabel = restoreEnclosingLabel; + function shouldBeCapturedInTempVariable(node, cacheIdentifiers) { + var target = ts.skipParentheses(node); + switch (target.kind) { + case 72 /* Identifier */: + return cacheIdentifiers; + case 100 /* ThisKeyword */: + case 8 /* NumericLiteral */: + case 9 /* BigIntLiteral */: + case 10 /* StringLiteral */: + return false; + case 187 /* ArrayLiteralExpression */: + var elements = target.elements; + if (elements.length === 0) { + return false; + } + return true; + case 188 /* ObjectLiteralExpression */: + return target.properties.length > 0; + default: + return true; + } + } + function createCallBinding(expression, recordTempVariable, languageVersion, cacheIdentifiers) { + if (cacheIdentifiers === void 0) { cacheIdentifiers = false; } + var callee = skipOuterExpressions(expression, 7 /* All */); + var thisArg; + var target; + if (ts.isSuperProperty(callee)) { + thisArg = ts.createThis(); + target = callee; + } + else if (callee.kind === 98 /* SuperKeyword */) { + thisArg = ts.createThis(); + target = languageVersion < 2 /* ES2015 */ + ? ts.setTextRange(ts.createIdentifier("_super"), callee) + : callee; + } + else if (ts.getEmitFlags(callee) & 4096 /* HelperName */) { + thisArg = ts.createVoidZero(); + target = parenthesizeForAccess(callee); + } + else { + switch (callee.kind) { + case 189 /* PropertyAccessExpression */: { + if (shouldBeCapturedInTempVariable(callee.expression, cacheIdentifiers)) { + // for `a.b()` target is `(_a = a).b` and thisArg is `_a` + thisArg = ts.createTempVariable(recordTempVariable); + target = ts.createPropertyAccess(ts.setTextRange(ts.createAssignment(thisArg, callee.expression), callee.expression), callee.name); + ts.setTextRange(target, callee); + } + else { + thisArg = callee.expression; + target = callee; + } + break; + } + case 190 /* ElementAccessExpression */: { + if (shouldBeCapturedInTempVariable(callee.expression, cacheIdentifiers)) { + // for `a[b]()` target is `(_a = a)[b]` and thisArg is `_a` + thisArg = ts.createTempVariable(recordTempVariable); + target = ts.createElementAccess(ts.setTextRange(ts.createAssignment(thisArg, callee.expression), callee.expression), callee.argumentExpression); + ts.setTextRange(target, callee); + } + else { + thisArg = callee.expression; + target = callee; + } + break; + } + default: { + // for `a()` target is `a` and thisArg is `void 0` + thisArg = ts.createVoidZero(); + target = parenthesizeForAccess(expression); + break; + } + } + } + return { target: target, thisArg: thisArg }; + } + ts.createCallBinding = createCallBinding; + function inlineExpressions(expressions) { + // Avoid deeply nested comma expressions as traversing them during emit can result in "Maximum call + // stack size exceeded" errors. + return expressions.length > 10 + ? ts.createCommaList(expressions) + : ts.reduceLeft(expressions, ts.createComma); + } + ts.inlineExpressions = inlineExpressions; + function createExpressionFromEntityName(node) { + if (ts.isQualifiedName(node)) { + var left = createExpressionFromEntityName(node.left); + var right = ts.getMutableClone(node.right); + return ts.setTextRange(ts.createPropertyAccess(left, right), node); + } + else { + return ts.getMutableClone(node); + } + } + ts.createExpressionFromEntityName = createExpressionFromEntityName; + function createExpressionForPropertyName(memberName) { + if (ts.isIdentifier(memberName)) { + return ts.createLiteral(memberName); + } + else if (ts.isComputedPropertyName(memberName)) { + return ts.getMutableClone(memberName.expression); + } + else { + return ts.getMutableClone(memberName); + } + } + ts.createExpressionForPropertyName = createExpressionForPropertyName; + function createExpressionForObjectLiteralElementLike(node, property, receiver) { + switch (property.kind) { + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + return createExpressionForAccessorDeclaration(node.properties, property, receiver, !!node.multiLine); + case 275 /* PropertyAssignment */: + return createExpressionForPropertyAssignment(property, receiver); + case 276 /* ShorthandPropertyAssignment */: + return createExpressionForShorthandPropertyAssignment(property, receiver); + case 156 /* MethodDeclaration */: + return createExpressionForMethodDeclaration(property, receiver); + } + } + ts.createExpressionForObjectLiteralElementLike = createExpressionForObjectLiteralElementLike; + function createExpressionForAccessorDeclaration(properties, property, receiver, multiLine) { + var _a = ts.getAllAccessorDeclarations(properties, property), firstAccessor = _a.firstAccessor, getAccessor = _a.getAccessor, setAccessor = _a.setAccessor; + if (property === firstAccessor) { + var properties_8 = []; + if (getAccessor) { + var getterFunction = ts.createFunctionExpression(getAccessor.modifiers, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, getAccessor.parameters, + /*type*/ undefined, getAccessor.body // TODO: GH#18217 + ); + ts.setTextRange(getterFunction, getAccessor); + ts.setOriginalNode(getterFunction, getAccessor); + var getter = ts.createPropertyAssignment("get", getterFunction); + properties_8.push(getter); + } + if (setAccessor) { + var setterFunction = ts.createFunctionExpression(setAccessor.modifiers, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, setAccessor.parameters, + /*type*/ undefined, setAccessor.body // TODO: GH#18217 + ); + ts.setTextRange(setterFunction, setAccessor); + ts.setOriginalNode(setterFunction, setAccessor); + var setter = ts.createPropertyAssignment("set", setterFunction); + properties_8.push(setter); + } + properties_8.push(ts.createPropertyAssignment("enumerable", ts.createTrue())); + properties_8.push(ts.createPropertyAssignment("configurable", ts.createTrue())); + var expression = ts.setTextRange(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"), + /*typeArguments*/ undefined, [ + receiver, + createExpressionForPropertyName(property.name), + ts.createObjectLiteral(properties_8, multiLine) + ]), + /*location*/ firstAccessor); + return ts.aggregateTransformFlags(expression); + } + return undefined; + } + function createExpressionForPropertyAssignment(property, receiver) { + return ts.aggregateTransformFlags(ts.setOriginalNode(ts.setTextRange(ts.createAssignment(createMemberAccessForPropertyName(receiver, property.name, /*location*/ property.name), property.initializer), property), property)); + } + function createExpressionForShorthandPropertyAssignment(property, receiver) { + return ts.aggregateTransformFlags(ts.setOriginalNode(ts.setTextRange(ts.createAssignment(createMemberAccessForPropertyName(receiver, property.name, /*location*/ property.name), ts.getSynthesizedClone(property.name)), + /*location*/ property), + /*original*/ property)); + } + function createExpressionForMethodDeclaration(method, receiver) { + return ts.aggregateTransformFlags(ts.setOriginalNode(ts.setTextRange(ts.createAssignment(createMemberAccessForPropertyName(receiver, method.name, /*location*/ method.name), ts.setOriginalNode(ts.setTextRange(ts.createFunctionExpression(method.modifiers, method.asteriskToken, + /*name*/ undefined, + /*typeParameters*/ undefined, method.parameters, + /*type*/ undefined, method.body // TODO: GH#18217 + ), + /*location*/ method), + /*original*/ method)), + /*location*/ method), + /*original*/ method)); + } + /** + * Gets the internal name of a declaration. This is primarily used for declarations that can be + * referred to by name in the body of an ES5 class function body. An internal name will *never* + * be prefixed with an module or namespace export modifier like "exports." when emitted as an + * expression. An internal name will also *never* be renamed due to a collision with a block + * scoped variable. + * + * @param node The declaration. + * @param allowComments A value indicating whether comments may be emitted for the name. + * @param allowSourceMaps A value indicating whether source maps may be emitted for the name. + */ + function getInternalName(node, allowComments, allowSourceMaps) { + return getName(node, allowComments, allowSourceMaps, 16384 /* LocalName */ | 32768 /* InternalName */); + } + ts.getInternalName = getInternalName; + /** + * Gets whether an identifier should only be referred to by its internal name. + */ + function isInternalName(node) { + return (ts.getEmitFlags(node) & 32768 /* InternalName */) !== 0; + } + ts.isInternalName = isInternalName; + /** + * Gets the local name of a declaration. This is primarily used for declarations that can be + * referred to by name in the declaration's immediate scope (classes, enums, namespaces). A + * local name will *never* be prefixed with an module or namespace export modifier like + * "exports." when emitted as an expression. + * + * @param node The declaration. + * @param allowComments A value indicating whether comments may be emitted for the name. + * @param allowSourceMaps A value indicating whether source maps may be emitted for the name. + */ + function getLocalName(node, allowComments, allowSourceMaps) { + return getName(node, allowComments, allowSourceMaps, 16384 /* LocalName */); + } + ts.getLocalName = getLocalName; + /** + * Gets whether an identifier should only be referred to by its local name. + */ + function isLocalName(node) { + return (ts.getEmitFlags(node) & 16384 /* LocalName */) !== 0; + } + ts.isLocalName = isLocalName; + /** + * Gets the export name of a declaration. This is primarily used for declarations that can be + * referred to by name in the declaration's immediate scope (classes, enums, namespaces). An + * export name will *always* be prefixed with an module or namespace export modifier like + * `"exports."` when emitted as an expression if the name points to an exported symbol. + * + * @param node The declaration. + * @param allowComments A value indicating whether comments may be emitted for the name. + * @param allowSourceMaps A value indicating whether source maps may be emitted for the name. + */ + function getExportName(node, allowComments, allowSourceMaps) { + return getName(node, allowComments, allowSourceMaps, 8192 /* ExportName */); + } + ts.getExportName = getExportName; + /** + * Gets whether an identifier should only be referred to by its export representation if the + * name points to an exported symbol. + */ + function isExportName(node) { + return (ts.getEmitFlags(node) & 8192 /* ExportName */) !== 0; + } + ts.isExportName = isExportName; + /** + * Gets the name of a declaration for use in declarations. + * + * @param node The declaration. + * @param allowComments A value indicating whether comments may be emitted for the name. + * @param allowSourceMaps A value indicating whether source maps may be emitted for the name. + */ + function getDeclarationName(node, allowComments, allowSourceMaps) { + return getName(node, allowComments, allowSourceMaps); + } + ts.getDeclarationName = getDeclarationName; + function getName(node, allowComments, allowSourceMaps, emitFlags) { + if (emitFlags === void 0) { emitFlags = 0; } + var nodeName = ts.getNameOfDeclaration(node); + if (nodeName && ts.isIdentifier(nodeName) && !ts.isGeneratedIdentifier(nodeName)) { + var name = ts.getMutableClone(nodeName); + emitFlags |= ts.getEmitFlags(nodeName); + if (!allowSourceMaps) + emitFlags |= 48 /* NoSourceMap */; + if (!allowComments) + emitFlags |= 1536 /* NoComments */; + if (emitFlags) + ts.setEmitFlags(name, emitFlags); + return name; + } + return ts.getGeneratedNameForNode(node); + } + /** + * Gets the exported name of a declaration for use in expressions. + * + * An exported name will *always* be prefixed with an module or namespace export modifier like + * "exports." if the name points to an exported symbol. + * + * @param ns The namespace identifier. + * @param node The declaration. + * @param allowComments A value indicating whether comments may be emitted for the name. + * @param allowSourceMaps A value indicating whether source maps may be emitted for the name. + */ + function getExternalModuleOrNamespaceExportName(ns, node, allowComments, allowSourceMaps) { + if (ns && ts.hasModifier(node, 1 /* Export */)) { + return getNamespaceMemberName(ns, getName(node), allowComments, allowSourceMaps); + } + return getExportName(node, allowComments, allowSourceMaps); + } + ts.getExternalModuleOrNamespaceExportName = getExternalModuleOrNamespaceExportName; + /** + * Gets a namespace-qualified name for use in expressions. + * + * @param ns The namespace identifier. + * @param name The name. + * @param allowComments A value indicating whether comments may be emitted for the name. + * @param allowSourceMaps A value indicating whether source maps may be emitted for the name. + */ + function getNamespaceMemberName(ns, name, allowComments, allowSourceMaps) { + var qualifiedName = ts.createPropertyAccess(ns, ts.nodeIsSynthesized(name) ? name : ts.getSynthesizedClone(name)); + ts.setTextRange(qualifiedName, name); + var emitFlags = 0; + if (!allowSourceMaps) + emitFlags |= 48 /* NoSourceMap */; + if (!allowComments) + emitFlags |= 1536 /* NoComments */; + if (emitFlags) + ts.setEmitFlags(qualifiedName, emitFlags); + return qualifiedName; + } + ts.getNamespaceMemberName = getNamespaceMemberName; + function convertToFunctionBody(node, multiLine) { + return ts.isBlock(node) ? node : ts.setTextRange(ts.createBlock([ts.setTextRange(ts.createReturn(node), node)], multiLine), node); + } + ts.convertToFunctionBody = convertToFunctionBody; + function convertFunctionDeclarationToExpression(node) { + if (!node.body) + return ts.Debug.fail(); + var updated = ts.createFunctionExpression(node.modifiers, node.asteriskToken, node.name, node.typeParameters, node.parameters, node.type, node.body); + ts.setOriginalNode(updated, node); + ts.setTextRange(updated, node); + if (ts.getStartsOnNewLine(node)) { + ts.setStartsOnNewLine(updated, /*newLine*/ true); + } + ts.aggregateTransformFlags(updated); + return updated; + } + ts.convertFunctionDeclarationToExpression = convertFunctionDeclarationToExpression; + function isUseStrictPrologue(node) { + return ts.isStringLiteral(node.expression) && node.expression.text === "use strict"; + } + /** + * Add any necessary prologue-directives into target statement-array. + * The function needs to be called during each transformation step. + * This function needs to be called whenever we transform the statement + * list of a source file, namespace, or function-like body. + * + * @param target: result statements array + * @param source: origin statements array + * @param ensureUseStrict: boolean determining whether the function need to add prologue-directives + * @param visitor: Optional callback used to visit any custom prologue directives. + */ + function addPrologue(target, source, ensureUseStrict, visitor) { + var offset = addStandardPrologue(target, source, ensureUseStrict); + return addCustomPrologue(target, source, offset, visitor); + } + ts.addPrologue = addPrologue; + /** + * Add just the standard (string-expression) prologue-directives into target statement-array. + * The function needs to be called during each transformation step. + * This function needs to be called whenever we transform the statement + * list of a source file, namespace, or function-like body. + */ + function addStandardPrologue(target, source, ensureUseStrict) { + ts.Debug.assert(target.length === 0, "Prologue directives should be at the first statement in the target statements array"); + var foundUseStrict = false; + var statementOffset = 0; + var numStatements = source.length; + while (statementOffset < numStatements) { + var statement = source[statementOffset]; + if (ts.isPrologueDirective(statement)) { + if (isUseStrictPrologue(statement)) { + foundUseStrict = true; + } + target.push(statement); + } + else { + break; + } + statementOffset++; + } + if (ensureUseStrict && !foundUseStrict) { + target.push(startOnNewLine(ts.createStatement(ts.createLiteral("use strict")))); + } + return statementOffset; + } + ts.addStandardPrologue = addStandardPrologue; + function addCustomPrologue(target, source, statementOffset, visitor) { + var numStatements = source.length; + while (statementOffset !== undefined && statementOffset < numStatements) { + var statement = source[statementOffset]; + if (ts.getEmitFlags(statement) & 1048576 /* CustomPrologue */) { + ts.append(target, visitor ? ts.visitNode(statement, visitor, ts.isStatement) : statement); + } + else { + break; + } + statementOffset++; + } + return statementOffset; + } + ts.addCustomPrologue = addCustomPrologue; + function findUseStrictPrologue(statements) { + for (var _i = 0, statements_3 = statements; _i < statements_3.length; _i++) { + var statement = statements_3[_i]; + if (ts.isPrologueDirective(statement)) { + if (isUseStrictPrologue(statement)) { + return statement; + } + } + else { + break; + } + } + return undefined; + } + ts.findUseStrictPrologue = findUseStrictPrologue; + function startsWithUseStrict(statements) { + var firstStatement = ts.firstOrUndefined(statements); + return firstStatement !== undefined + && ts.isPrologueDirective(firstStatement) + && isUseStrictPrologue(firstStatement); + } + ts.startsWithUseStrict = startsWithUseStrict; + /** + * Ensures "use strict" directive is added + * + * @param statements An array of statements + */ + function ensureUseStrict(statements) { + var foundUseStrict = findUseStrictPrologue(statements); + if (!foundUseStrict) { + return ts.setTextRange(ts.createNodeArray([ + startOnNewLine(ts.createStatement(ts.createLiteral("use strict"))) + ].concat(statements)), statements); + } + return statements; + } + ts.ensureUseStrict = ensureUseStrict; + /** + * Wraps the operand to a BinaryExpression in parentheses if they are needed to preserve the intended + * order of operations. + * + * @param binaryOperator The operator for the BinaryExpression. + * @param operand The operand for the BinaryExpression. + * @param isLeftSideOfBinary A value indicating whether the operand is the left side of the + * BinaryExpression. + */ + function parenthesizeBinaryOperand(binaryOperator, operand, isLeftSideOfBinary, leftOperand) { + var skipped = ts.skipPartiallyEmittedExpressions(operand); + // If the resulting expression is already parenthesized, we do not need to do any further processing. + if (skipped.kind === 195 /* ParenthesizedExpression */) { + return operand; + } + return binaryOperandNeedsParentheses(binaryOperator, operand, isLeftSideOfBinary, leftOperand) + ? ts.createParen(operand) + : operand; + } + ts.parenthesizeBinaryOperand = parenthesizeBinaryOperand; + /** + * Determines whether the operand to a BinaryExpression needs to be parenthesized. + * + * @param binaryOperator The operator for the BinaryExpression. + * @param operand The operand for the BinaryExpression. + * @param isLeftSideOfBinary A value indicating whether the operand is the left side of the + * BinaryExpression. + */ + function binaryOperandNeedsParentheses(binaryOperator, operand, isLeftSideOfBinary, leftOperand) { + // If the operand has lower precedence, then it needs to be parenthesized to preserve the + // intent of the expression. For example, if the operand is `a + b` and the operator is + // `*`, then we need to parenthesize the operand to preserve the intended order of + // operations: `(a + b) * x`. + // + // If the operand has higher precedence, then it does not need to be parenthesized. For + // example, if the operand is `a * b` and the operator is `+`, then we do not need to + // parenthesize to preserve the intended order of operations: `a * b + x`. + // + // If the operand has the same precedence, then we need to check the associativity of + // the operator based on whether this is the left or right operand of the expression. + // + // For example, if `a / d` is on the right of operator `*`, we need to parenthesize + // to preserve the intended order of operations: `x * (a / d)` + // + // If `a ** d` is on the left of operator `**`, we need to parenthesize to preserve + // the intended order of operations: `(a ** b) ** c` + var binaryOperatorPrecedence = ts.getOperatorPrecedence(204 /* BinaryExpression */, binaryOperator); + var binaryOperatorAssociativity = ts.getOperatorAssociativity(204 /* BinaryExpression */, binaryOperator); + var emittedOperand = ts.skipPartiallyEmittedExpressions(operand); + if (!isLeftSideOfBinary && operand.kind === 197 /* ArrowFunction */ && binaryOperatorPrecedence > 4) { + // We need to parenthesize arrow functions on the right side to avoid it being + // parsed as parenthesized expression: `a && (() => {})` + return true; + } + var operandPrecedence = ts.getExpressionPrecedence(emittedOperand); + switch (ts.compareValues(operandPrecedence, binaryOperatorPrecedence)) { + case -1 /* LessThan */: + // If the operand is the right side of a right-associative binary operation + // and is a yield expression, then we do not need parentheses. + if (!isLeftSideOfBinary + && binaryOperatorAssociativity === 1 /* Right */ + && operand.kind === 207 /* YieldExpression */) { + return false; + } + return true; + case 1 /* GreaterThan */: + return false; + case 0 /* EqualTo */: + if (isLeftSideOfBinary) { + // No need to parenthesize the left operand when the binary operator is + // left associative: + // (a*b)/x -> a*b/x + // (a**b)/x -> a**b/x + // + // Parentheses are needed for the left operand when the binary operator is + // right associative: + // (a/b)**x -> (a/b)**x + // (a**b)**x -> (a**b)**x + return binaryOperatorAssociativity === 1 /* Right */; + } + else { + if (ts.isBinaryExpression(emittedOperand) + && emittedOperand.operatorToken.kind === binaryOperator) { + // No need to parenthesize the right operand when the binary operator and + // operand are the same and one of the following: + // x*(a*b) => x*a*b + // x|(a|b) => x|a|b + // x&(a&b) => x&a&b + // x^(a^b) => x^a^b + if (operatorHasAssociativeProperty(binaryOperator)) { + return false; + } + // No need to parenthesize the right operand when the binary operator + // is plus (+) if both the left and right operands consist solely of either + // literals of the same kind or binary plus (+) expressions for literals of + // the same kind (recursively). + // "a"+(1+2) => "a"+(1+2) + // "a"+("b"+"c") => "a"+"b"+"c" + if (binaryOperator === 38 /* PlusToken */) { + var leftKind = leftOperand ? getLiteralKindOfBinaryPlusOperand(leftOperand) : 0 /* Unknown */; + if (ts.isLiteralKind(leftKind) && leftKind === getLiteralKindOfBinaryPlusOperand(emittedOperand)) { + return false; + } + } + } + // No need to parenthesize the right operand when the operand is right + // associative: + // x/(a**b) -> x/a**b + // x**(a**b) -> x**a**b + // + // Parentheses are needed for the right operand when the operand is left + // associative: + // x/(a*b) -> x/(a*b) + // x**(a/b) -> x**(a/b) + var operandAssociativity = ts.getExpressionAssociativity(emittedOperand); + return operandAssociativity === 0 /* Left */; + } + } + } + /** + * Determines whether a binary operator is mathematically associative. + * + * @param binaryOperator The binary operator. + */ + function operatorHasAssociativeProperty(binaryOperator) { + // The following operators are associative in JavaScript: + // (a*b)*c -> a*(b*c) -> a*b*c + // (a|b)|c -> a|(b|c) -> a|b|c + // (a&b)&c -> a&(b&c) -> a&b&c + // (a^b)^c -> a^(b^c) -> a^b^c + // + // While addition is associative in mathematics, JavaScript's `+` is not + // guaranteed to be associative as it is overloaded with string concatenation. + return binaryOperator === 40 /* AsteriskToken */ + || binaryOperator === 50 /* BarToken */ + || binaryOperator === 49 /* AmpersandToken */ + || binaryOperator === 51 /* CaretToken */; + } + /** + * This function determines whether an expression consists of a homogeneous set of + * literal expressions or binary plus expressions that all share the same literal kind. + * It is used to determine whether the right-hand operand of a binary plus expression can be + * emitted without parentheses. + */ + function getLiteralKindOfBinaryPlusOperand(node) { + node = ts.skipPartiallyEmittedExpressions(node); + if (ts.isLiteralKind(node.kind)) { + return node.kind; + } + if (node.kind === 204 /* BinaryExpression */ && node.operatorToken.kind === 38 /* PlusToken */) { + if (node.cachedLiteralKind !== undefined) { + return node.cachedLiteralKind; + } + var leftKind = getLiteralKindOfBinaryPlusOperand(node.left); + var literalKind = ts.isLiteralKind(leftKind) + && leftKind === getLiteralKindOfBinaryPlusOperand(node.right) + ? leftKind + : 0 /* Unknown */; + node.cachedLiteralKind = literalKind; + return literalKind; + } + return 0 /* Unknown */; + } + function parenthesizeForConditionalHead(condition) { + var conditionalPrecedence = ts.getOperatorPrecedence(205 /* ConditionalExpression */, 56 /* QuestionToken */); + var emittedCondition = ts.skipPartiallyEmittedExpressions(condition); + var conditionPrecedence = ts.getExpressionPrecedence(emittedCondition); + if (ts.compareValues(conditionPrecedence, conditionalPrecedence) === -1 /* LessThan */) { + return ts.createParen(condition); + } + return condition; + } + ts.parenthesizeForConditionalHead = parenthesizeForConditionalHead; + function parenthesizeSubexpressionOfConditionalExpression(e) { + // per ES grammar both 'whenTrue' and 'whenFalse' parts of conditional expression are assignment expressions + // so in case when comma expression is introduced as a part of previous transformations + // if should be wrapped in parens since comma operator has the lowest precedence + var emittedExpression = ts.skipPartiallyEmittedExpressions(e); + return isCommaSequence(emittedExpression) + ? ts.createParen(e) + : e; + } + ts.parenthesizeSubexpressionOfConditionalExpression = parenthesizeSubexpressionOfConditionalExpression; + /** + * [Per the spec](https://tc39.github.io/ecma262/#prod-ExportDeclaration), `export default` accepts _AssigmentExpression_ but + * has a lookahead restriction for `function`, `async function`, and `class`. + * + * Basically, that means we need to parenthesize in the following cases: + * + * - BinaryExpression of CommaToken + * - CommaList (synthetic list of multiple comma expressions) + * - FunctionExpression + * - ClassExpression + */ + function parenthesizeDefaultExpression(e) { + var check = ts.skipPartiallyEmittedExpressions(e); + var needsParens = isCommaSequence(check); + if (!needsParens) { + switch (getLeftmostExpression(check, /*stopAtCallExpression*/ false).kind) { + case 209 /* ClassExpression */: + case 196 /* FunctionExpression */: + needsParens = true; + } + } + return needsParens ? ts.createParen(e) : e; + } + ts.parenthesizeDefaultExpression = parenthesizeDefaultExpression; + /** + * Wraps an expression in parentheses if it is needed in order to use the expression + * as the expression of a NewExpression node. + * + * @param expression The Expression node. + */ + function parenthesizeForNew(expression) { + var leftmostExpr = getLeftmostExpression(expression, /*stopAtCallExpressions*/ true); + switch (leftmostExpr.kind) { + case 191 /* CallExpression */: + return ts.createParen(expression); + case 192 /* NewExpression */: + return !leftmostExpr.arguments + ? ts.createParen(expression) + : expression; + } + return parenthesizeForAccess(expression); + } + ts.parenthesizeForNew = parenthesizeForNew; + /** + * Wraps an expression in parentheses if it is needed in order to use the expression for + * property or element access. + * + * @param expr The expression node. + */ + function parenthesizeForAccess(expression) { + // isLeftHandSideExpression is almost the correct criterion for when it is not necessary + // to parenthesize the expression before a dot. The known exception is: + // + // NewExpression: + // new C.x -> not the same as (new C).x + // + var emittedExpression = ts.skipPartiallyEmittedExpressions(expression); + if (ts.isLeftHandSideExpression(emittedExpression) + && (emittedExpression.kind !== 192 /* NewExpression */ || emittedExpression.arguments)) { + return expression; + } + return ts.setTextRange(ts.createParen(expression), expression); + } + ts.parenthesizeForAccess = parenthesizeForAccess; + function parenthesizePostfixOperand(operand) { + return ts.isLeftHandSideExpression(operand) + ? operand + : ts.setTextRange(ts.createParen(operand), operand); + } + ts.parenthesizePostfixOperand = parenthesizePostfixOperand; + function parenthesizePrefixOperand(operand) { + return ts.isUnaryExpression(operand) + ? operand + : ts.setTextRange(ts.createParen(operand), operand); + } + ts.parenthesizePrefixOperand = parenthesizePrefixOperand; + function parenthesizeListElements(elements) { + var result; + for (var i = 0; i < elements.length; i++) { + var element = parenthesizeExpressionForList(elements[i]); + if (result !== undefined || element !== elements[i]) { + if (result === undefined) { + result = elements.slice(0, i); + } + result.push(element); + } + } + if (result !== undefined) { + return ts.setTextRange(ts.createNodeArray(result, elements.hasTrailingComma), elements); + } + return elements; + } + ts.parenthesizeListElements = parenthesizeListElements; + function parenthesizeExpressionForList(expression) { + var emittedExpression = ts.skipPartiallyEmittedExpressions(expression); + var expressionPrecedence = ts.getExpressionPrecedence(emittedExpression); + var commaPrecedence = ts.getOperatorPrecedence(204 /* BinaryExpression */, 27 /* CommaToken */); + return expressionPrecedence > commaPrecedence + ? expression + : ts.setTextRange(ts.createParen(expression), expression); + } + ts.parenthesizeExpressionForList = parenthesizeExpressionForList; + function parenthesizeExpressionForExpressionStatement(expression) { + var emittedExpression = ts.skipPartiallyEmittedExpressions(expression); + if (ts.isCallExpression(emittedExpression)) { + var callee = emittedExpression.expression; + var kind = ts.skipPartiallyEmittedExpressions(callee).kind; + if (kind === 196 /* FunctionExpression */ || kind === 197 /* ArrowFunction */) { + var mutableCall = ts.getMutableClone(emittedExpression); + mutableCall.expression = ts.setTextRange(ts.createParen(callee), callee); + return recreateOuterExpressions(expression, mutableCall, 4 /* PartiallyEmittedExpressions */); + } + } + var leftmostExpressionKind = getLeftmostExpression(emittedExpression, /*stopAtCallExpressions*/ false).kind; + if (leftmostExpressionKind === 188 /* ObjectLiteralExpression */ || leftmostExpressionKind === 196 /* FunctionExpression */) { + return ts.setTextRange(ts.createParen(expression), expression); + } + return expression; + } + ts.parenthesizeExpressionForExpressionStatement = parenthesizeExpressionForExpressionStatement; + function parenthesizeConditionalTypeMember(member) { + return member.kind === 175 /* ConditionalType */ ? ts.createParenthesizedType(member) : member; + } + ts.parenthesizeConditionalTypeMember = parenthesizeConditionalTypeMember; + function parenthesizeElementTypeMember(member) { + switch (member.kind) { + case 173 /* UnionType */: + case 174 /* IntersectionType */: + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + return ts.createParenthesizedType(member); + } + return parenthesizeConditionalTypeMember(member); + } + ts.parenthesizeElementTypeMember = parenthesizeElementTypeMember; + function parenthesizeArrayTypeMember(member) { + switch (member.kind) { + case 167 /* TypeQuery */: + case 179 /* TypeOperator */: + case 176 /* InferType */: + return ts.createParenthesizedType(member); + } + return parenthesizeElementTypeMember(member); + } + ts.parenthesizeArrayTypeMember = parenthesizeArrayTypeMember; + function parenthesizeElementTypeMembers(members) { + return ts.createNodeArray(ts.sameMap(members, parenthesizeElementTypeMember)); + } + ts.parenthesizeElementTypeMembers = parenthesizeElementTypeMembers; + function parenthesizeTypeParameters(typeParameters) { + if (ts.some(typeParameters)) { + var params = []; + for (var i = 0; i < typeParameters.length; ++i) { + var entry = typeParameters[i]; + params.push(i === 0 && ts.isFunctionOrConstructorTypeNode(entry) && entry.typeParameters ? + ts.createParenthesizedType(entry) : + entry); + } + return ts.createNodeArray(params); + } + } + ts.parenthesizeTypeParameters = parenthesizeTypeParameters; + function getLeftmostExpression(node, stopAtCallExpressions) { + while (true) { + switch (node.kind) { + case 203 /* PostfixUnaryExpression */: + node = node.operand; + continue; + case 204 /* BinaryExpression */: + node = node.left; + continue; + case 205 /* ConditionalExpression */: + node = node.condition; + continue; + case 193 /* TaggedTemplateExpression */: + node = node.tag; + continue; + case 191 /* CallExpression */: + if (stopAtCallExpressions) { + return node; + } + // falls through + case 212 /* AsExpression */: + case 190 /* ElementAccessExpression */: + case 189 /* PropertyAccessExpression */: + case 213 /* NonNullExpression */: + case 308 /* PartiallyEmittedExpression */: + node = node.expression; + continue; + } + return node; + } + } + function parenthesizeConciseBody(body) { + if (!ts.isBlock(body) && (isCommaSequence(body) || getLeftmostExpression(body, /*stopAtCallExpressions*/ false).kind === 188 /* ObjectLiteralExpression */)) { + return ts.setTextRange(ts.createParen(body), body); + } + return body; + } + ts.parenthesizeConciseBody = parenthesizeConciseBody; + function isCommaSequence(node) { + return node.kind === 204 /* BinaryExpression */ && node.operatorToken.kind === 27 /* CommaToken */ || + node.kind === 309 /* CommaListExpression */; + } + ts.isCommaSequence = isCommaSequence; + var OuterExpressionKinds; + (function (OuterExpressionKinds) { + OuterExpressionKinds[OuterExpressionKinds["Parentheses"] = 1] = "Parentheses"; + OuterExpressionKinds[OuterExpressionKinds["Assertions"] = 2] = "Assertions"; + OuterExpressionKinds[OuterExpressionKinds["PartiallyEmittedExpressions"] = 4] = "PartiallyEmittedExpressions"; + OuterExpressionKinds[OuterExpressionKinds["All"] = 7] = "All"; + })(OuterExpressionKinds = ts.OuterExpressionKinds || (ts.OuterExpressionKinds = {})); + function isOuterExpression(node, kinds) { + if (kinds === void 0) { kinds = 7 /* All */; } + switch (node.kind) { + case 195 /* ParenthesizedExpression */: + return (kinds & 1 /* Parentheses */) !== 0; + case 194 /* TypeAssertionExpression */: + case 212 /* AsExpression */: + case 213 /* NonNullExpression */: + return (kinds & 2 /* Assertions */) !== 0; + case 308 /* PartiallyEmittedExpression */: + return (kinds & 4 /* PartiallyEmittedExpressions */) !== 0; + } + return false; + } + ts.isOuterExpression = isOuterExpression; + function skipOuterExpressions(node, kinds) { + if (kinds === void 0) { kinds = 7 /* All */; } + var previousNode; + do { + previousNode = node; + if (kinds & 1 /* Parentheses */) { + node = ts.skipParentheses(node); + } + if (kinds & 2 /* Assertions */) { + node = skipAssertions(node); + } + if (kinds & 4 /* PartiallyEmittedExpressions */) { + node = ts.skipPartiallyEmittedExpressions(node); + } + } while (previousNode !== node); + return node; + } + ts.skipOuterExpressions = skipOuterExpressions; + function skipAssertions(node) { + while (ts.isAssertionExpression(node) || node.kind === 213 /* NonNullExpression */) { + node = node.expression; + } + return node; + } + ts.skipAssertions = skipAssertions; + function updateOuterExpression(outerExpression, expression) { + switch (outerExpression.kind) { + case 195 /* ParenthesizedExpression */: return ts.updateParen(outerExpression, expression); + case 194 /* TypeAssertionExpression */: return ts.updateTypeAssertion(outerExpression, outerExpression.type, expression); + case 212 /* AsExpression */: return ts.updateAsExpression(outerExpression, expression, outerExpression.type); + case 213 /* NonNullExpression */: return ts.updateNonNullExpression(outerExpression, expression); + case 308 /* PartiallyEmittedExpression */: return ts.updatePartiallyEmittedExpression(outerExpression, expression); + } + } + /** + * Determines whether a node is a parenthesized expression that can be ignored when recreating outer expressions. + * + * A parenthesized expression can be ignored when all of the following are true: + * + * - It's `pos` and `end` are not -1 + * - It does not have a custom source map range + * - It does not have a custom comment range + * - It does not have synthetic leading or trailing comments + * + * If an outermost parenthesized expression is ignored, but the containing expression requires a parentheses around + * the expression to maintain precedence, a new parenthesized expression should be created automatically when + * the containing expression is created/updated. + */ + function isIgnorableParen(node) { + return node.kind === 195 /* ParenthesizedExpression */ + && ts.nodeIsSynthesized(node) + && ts.nodeIsSynthesized(ts.getSourceMapRange(node)) + && ts.nodeIsSynthesized(ts.getCommentRange(node)) + && !ts.some(ts.getSyntheticLeadingComments(node)) + && !ts.some(ts.getSyntheticTrailingComments(node)); + } + function recreateOuterExpressions(outerExpression, innerExpression, kinds) { + if (kinds === void 0) { kinds = 7 /* All */; } + if (outerExpression && isOuterExpression(outerExpression, kinds) && !isIgnorableParen(outerExpression)) { + return updateOuterExpression(outerExpression, recreateOuterExpressions(outerExpression.expression, innerExpression)); + } + return innerExpression; + } + ts.recreateOuterExpressions = recreateOuterExpressions; + function startOnNewLine(node) { + return ts.setStartsOnNewLine(node, /*newLine*/ true); + } + ts.startOnNewLine = startOnNewLine; + function getExternalHelpersModuleName(node) { + var parseNode = ts.getOriginalNode(node, ts.isSourceFile); + var emitNode = parseNode && parseNode.emitNode; + return emitNode && emitNode.externalHelpersModuleName; + } + ts.getExternalHelpersModuleName = getExternalHelpersModuleName; + function getOrCreateExternalHelpersModuleNameIfNeeded(node, compilerOptions, hasExportStarsToExportValues, hasImportStarOrImportDefault) { + if (compilerOptions.importHelpers && ts.isEffectiveExternalModule(node, compilerOptions)) { + var externalHelpersModuleName = getExternalHelpersModuleName(node); + if (externalHelpersModuleName) { + return externalHelpersModuleName; + } + var moduleKind = ts.getEmitModuleKind(compilerOptions); + var create = (hasExportStarsToExportValues || (compilerOptions.esModuleInterop && hasImportStarOrImportDefault)) + && moduleKind !== ts.ModuleKind.System + && moduleKind !== ts.ModuleKind.ES2015 + && moduleKind !== ts.ModuleKind.ESNext; + if (!create) { + var helpers = ts.getEmitHelpers(node); + if (helpers) { + for (var _i = 0, helpers_2 = helpers; _i < helpers_2.length; _i++) { + var helper = helpers_2[_i]; + if (!helper.scoped) { + create = true; + break; + } + } + } + } + if (create) { + var parseNode = ts.getOriginalNode(node, ts.isSourceFile); + var emitNode = ts.getOrCreateEmitNode(parseNode); + return emitNode.externalHelpersModuleName || (emitNode.externalHelpersModuleName = ts.createUniqueName(ts.externalHelpersModuleNameText)); + } + } + } + ts.getOrCreateExternalHelpersModuleNameIfNeeded = getOrCreateExternalHelpersModuleNameIfNeeded; + /** + * Get the name of that target module from an import or export declaration + */ + function getLocalNameForExternalImport(node, sourceFile) { + var namespaceDeclaration = ts.getNamespaceDeclarationNode(node); + if (namespaceDeclaration && !ts.isDefaultImport(node)) { + var name = namespaceDeclaration.name; + return ts.isGeneratedIdentifier(name) ? name : ts.createIdentifier(ts.getSourceTextOfNodeFromSourceFile(sourceFile, name) || ts.idText(name)); + } + if (node.kind === 249 /* ImportDeclaration */ && node.importClause) { + return ts.getGeneratedNameForNode(node); + } + if (node.kind === 255 /* ExportDeclaration */ && node.moduleSpecifier) { + return ts.getGeneratedNameForNode(node); + } + return undefined; + } + ts.getLocalNameForExternalImport = getLocalNameForExternalImport; + /** + * Get the name of a target module from an import/export declaration as should be written in the emitted output. + * The emitted output name can be different from the input if: + * 1. The module has a /// + * 2. --out or --outFile is used, making the name relative to the rootDir + * 3- The containing SourceFile has an entry in renamedDependencies for the import as requested by some module loaders (e.g. System). + * Otherwise, a new StringLiteral node representing the module name will be returned. + */ + function getExternalModuleNameLiteral(importNode, sourceFile, host, resolver, compilerOptions) { + var moduleName = ts.getExternalModuleName(importNode); // TODO: GH#18217 + if (moduleName.kind === 10 /* StringLiteral */) { + return tryGetModuleNameFromDeclaration(importNode, host, resolver, compilerOptions) + || tryRenameExternalModule(moduleName, sourceFile) + || ts.getSynthesizedClone(moduleName); + } + return undefined; + } + ts.getExternalModuleNameLiteral = getExternalModuleNameLiteral; + /** + * Some bundlers (SystemJS builder) sometimes want to rename dependencies. + * Here we check if alternative name was provided for a given moduleName and return it if possible. + */ + function tryRenameExternalModule(moduleName, sourceFile) { + var rename = sourceFile.renamedDependencies && sourceFile.renamedDependencies.get(moduleName.text); + return rename && ts.createLiteral(rename); + } + /** + * Get the name of a module as should be written in the emitted output. + * The emitted output name can be different from the input if: + * 1. The module has a /// + * 2. --out or --outFile is used, making the name relative to the rootDir + * Otherwise, a new StringLiteral node representing the module name will be returned. + */ + function tryGetModuleNameFromFile(file, host, options) { + if (!file) { + return undefined; + } + if (file.moduleName) { + return ts.createLiteral(file.moduleName); + } + if (!file.isDeclarationFile && (options.out || options.outFile)) { + return ts.createLiteral(ts.getExternalModuleNameFromPath(host, file.fileName)); + } + return undefined; + } + ts.tryGetModuleNameFromFile = tryGetModuleNameFromFile; + function tryGetModuleNameFromDeclaration(declaration, host, resolver, compilerOptions) { + return tryGetModuleNameFromFile(resolver.getExternalModuleFileFromDeclaration(declaration), host, compilerOptions); + } + /** + * Gets the initializer of an BindingOrAssignmentElement. + */ + function getInitializerOfBindingOrAssignmentElement(bindingElement) { + if (ts.isDeclarationBindingElement(bindingElement)) { + // `1` in `let { a = 1 } = ...` + // `1` in `let { a: b = 1 } = ...` + // `1` in `let { a: {b} = 1 } = ...` + // `1` in `let { a: [b] = 1 } = ...` + // `1` in `let [a = 1] = ...` + // `1` in `let [{a} = 1] = ...` + // `1` in `let [[a] = 1] = ...` + return bindingElement.initializer; + } + if (ts.isPropertyAssignment(bindingElement)) { + // `1` in `({ a: b = 1 } = ...)` + // `1` in `({ a: {b} = 1 } = ...)` + // `1` in `({ a: [b] = 1 } = ...)` + var initializer = bindingElement.initializer; + return ts.isAssignmentExpression(initializer, /*excludeCompoundAssignment*/ true) + ? initializer.right + : undefined; + } + if (ts.isShorthandPropertyAssignment(bindingElement)) { + // `1` in `({ a = 1 } = ...)` + return bindingElement.objectAssignmentInitializer; + } + if (ts.isAssignmentExpression(bindingElement, /*excludeCompoundAssignment*/ true)) { + // `1` in `[a = 1] = ...` + // `1` in `[{a} = 1] = ...` + // `1` in `[[a] = 1] = ...` + return bindingElement.right; + } + if (ts.isSpreadElement(bindingElement)) { + // Recovery consistent with existing emit. + return getInitializerOfBindingOrAssignmentElement(bindingElement.expression); + } + } + ts.getInitializerOfBindingOrAssignmentElement = getInitializerOfBindingOrAssignmentElement; + /** + * Gets the name of an BindingOrAssignmentElement. + */ + function getTargetOfBindingOrAssignmentElement(bindingElement) { + if (ts.isDeclarationBindingElement(bindingElement)) { + // `a` in `let { a } = ...` + // `a` in `let { a = 1 } = ...` + // `b` in `let { a: b } = ...` + // `b` in `let { a: b = 1 } = ...` + // `a` in `let { ...a } = ...` + // `{b}` in `let { a: {b} } = ...` + // `{b}` in `let { a: {b} = 1 } = ...` + // `[b]` in `let { a: [b] } = ...` + // `[b]` in `let { a: [b] = 1 } = ...` + // `a` in `let [a] = ...` + // `a` in `let [a = 1] = ...` + // `a` in `let [...a] = ...` + // `{a}` in `let [{a}] = ...` + // `{a}` in `let [{a} = 1] = ...` + // `[a]` in `let [[a]] = ...` + // `[a]` in `let [[a] = 1] = ...` + return bindingElement.name; + } + if (ts.isObjectLiteralElementLike(bindingElement)) { + switch (bindingElement.kind) { + case 275 /* PropertyAssignment */: + // `b` in `({ a: b } = ...)` + // `b` in `({ a: b = 1 } = ...)` + // `{b}` in `({ a: {b} } = ...)` + // `{b}` in `({ a: {b} = 1 } = ...)` + // `[b]` in `({ a: [b] } = ...)` + // `[b]` in `({ a: [b] = 1 } = ...)` + // `b.c` in `({ a: b.c } = ...)` + // `b.c` in `({ a: b.c = 1 } = ...)` + // `b[0]` in `({ a: b[0] } = ...)` + // `b[0]` in `({ a: b[0] = 1 } = ...)` + return getTargetOfBindingOrAssignmentElement(bindingElement.initializer); + case 276 /* ShorthandPropertyAssignment */: + // `a` in `({ a } = ...)` + // `a` in `({ a = 1 } = ...)` + return bindingElement.name; + case 277 /* SpreadAssignment */: + // `a` in `({ ...a } = ...)` + return getTargetOfBindingOrAssignmentElement(bindingElement.expression); + } + // no target + return undefined; + } + if (ts.isAssignmentExpression(bindingElement, /*excludeCompoundAssignment*/ true)) { + // `a` in `[a = 1] = ...` + // `{a}` in `[{a} = 1] = ...` + // `[a]` in `[[a] = 1] = ...` + // `a.b` in `[a.b = 1] = ...` + // `a[0]` in `[a[0] = 1] = ...` + return getTargetOfBindingOrAssignmentElement(bindingElement.left); + } + if (ts.isSpreadElement(bindingElement)) { + // `a` in `[...a] = ...` + return getTargetOfBindingOrAssignmentElement(bindingElement.expression); + } + // `a` in `[a] = ...` + // `{a}` in `[{a}] = ...` + // `[a]` in `[[a]] = ...` + // `a.b` in `[a.b] = ...` + // `a[0]` in `[a[0]] = ...` + return bindingElement; + } + ts.getTargetOfBindingOrAssignmentElement = getTargetOfBindingOrAssignmentElement; + /** + * Determines whether an BindingOrAssignmentElement is a rest element. + */ + function getRestIndicatorOfBindingOrAssignmentElement(bindingElement) { + switch (bindingElement.kind) { + case 151 /* Parameter */: + case 186 /* BindingElement */: + // `...` in `let [...a] = ...` + return bindingElement.dotDotDotToken; + case 208 /* SpreadElement */: + case 277 /* SpreadAssignment */: + // `...` in `[...a] = ...` + return bindingElement; + } + return undefined; + } + ts.getRestIndicatorOfBindingOrAssignmentElement = getRestIndicatorOfBindingOrAssignmentElement; + /** + * Gets the property name of a BindingOrAssignmentElement + */ + function getPropertyNameOfBindingOrAssignmentElement(bindingElement) { + switch (bindingElement.kind) { + case 186 /* BindingElement */: + // `a` in `let { a: b } = ...` + // `[a]` in `let { [a]: b } = ...` + // `"a"` in `let { "a": b } = ...` + // `1` in `let { 1: b } = ...` + if (bindingElement.propertyName) { + var propertyName = bindingElement.propertyName; + return ts.isComputedPropertyName(propertyName) && isStringOrNumericLiteral(propertyName.expression) + ? propertyName.expression + : propertyName; + } + break; + case 275 /* PropertyAssignment */: + // `a` in `({ a: b } = ...)` + // `[a]` in `({ [a]: b } = ...)` + // `"a"` in `({ "a": b } = ...)` + // `1` in `({ 1: b } = ...)` + if (bindingElement.name) { + var propertyName = bindingElement.name; + return ts.isComputedPropertyName(propertyName) && isStringOrNumericLiteral(propertyName.expression) + ? propertyName.expression + : propertyName; + } + break; + case 277 /* SpreadAssignment */: + // `a` in `({ ...a } = ...)` + return bindingElement.name; + } + var target = getTargetOfBindingOrAssignmentElement(bindingElement); + if (target && ts.isPropertyName(target)) { + return ts.isComputedPropertyName(target) && isStringOrNumericLiteral(target.expression) + ? target.expression + : target; + } + ts.Debug.fail("Invalid property name for binding element."); + } + ts.getPropertyNameOfBindingOrAssignmentElement = getPropertyNameOfBindingOrAssignmentElement; + function isStringOrNumericLiteral(node) { + var kind = node.kind; + return kind === 10 /* StringLiteral */ + || kind === 8 /* NumericLiteral */; + } + /** + * Gets the elements of a BindingOrAssignmentPattern + */ + function getElementsOfBindingOrAssignmentPattern(name) { + switch (name.kind) { + case 184 /* ObjectBindingPattern */: + case 185 /* ArrayBindingPattern */: + case 187 /* ArrayLiteralExpression */: + // `a` in `{a}` + // `a` in `[a]` + return name.elements; + case 188 /* ObjectLiteralExpression */: + // `a` in `{a}` + return name.properties; + } + } + ts.getElementsOfBindingOrAssignmentPattern = getElementsOfBindingOrAssignmentPattern; + function convertToArrayAssignmentElement(element) { + if (ts.isBindingElement(element)) { + if (element.dotDotDotToken) { + ts.Debug.assertNode(element.name, ts.isIdentifier); + return ts.setOriginalNode(ts.setTextRange(ts.createSpread(element.name), element), element); + } + var expression = convertToAssignmentElementTarget(element.name); + return element.initializer + ? ts.setOriginalNode(ts.setTextRange(ts.createAssignment(expression, element.initializer), element), element) + : expression; + } + ts.Debug.assertNode(element, ts.isExpression); + return element; + } + ts.convertToArrayAssignmentElement = convertToArrayAssignmentElement; + function convertToObjectAssignmentElement(element) { + if (ts.isBindingElement(element)) { + if (element.dotDotDotToken) { + ts.Debug.assertNode(element.name, ts.isIdentifier); + return ts.setOriginalNode(ts.setTextRange(ts.createSpreadAssignment(element.name), element), element); + } + if (element.propertyName) { + var expression = convertToAssignmentElementTarget(element.name); + return ts.setOriginalNode(ts.setTextRange(ts.createPropertyAssignment(element.propertyName, element.initializer ? ts.createAssignment(expression, element.initializer) : expression), element), element); + } + ts.Debug.assertNode(element.name, ts.isIdentifier); + return ts.setOriginalNode(ts.setTextRange(ts.createShorthandPropertyAssignment(element.name, element.initializer), element), element); + } + ts.Debug.assertNode(element, ts.isObjectLiteralElementLike); + return element; + } + ts.convertToObjectAssignmentElement = convertToObjectAssignmentElement; + function convertToAssignmentPattern(node) { + switch (node.kind) { + case 185 /* ArrayBindingPattern */: + case 187 /* ArrayLiteralExpression */: + return convertToArrayAssignmentPattern(node); + case 184 /* ObjectBindingPattern */: + case 188 /* ObjectLiteralExpression */: + return convertToObjectAssignmentPattern(node); + } + } + ts.convertToAssignmentPattern = convertToAssignmentPattern; + function convertToObjectAssignmentPattern(node) { + if (ts.isObjectBindingPattern(node)) { + return ts.setOriginalNode(ts.setTextRange(ts.createObjectLiteral(ts.map(node.elements, convertToObjectAssignmentElement)), node), node); + } + ts.Debug.assertNode(node, ts.isObjectLiteralExpression); + return node; + } + ts.convertToObjectAssignmentPattern = convertToObjectAssignmentPattern; + function convertToArrayAssignmentPattern(node) { + if (ts.isArrayBindingPattern(node)) { + return ts.setOriginalNode(ts.setTextRange(ts.createArrayLiteral(ts.map(node.elements, convertToArrayAssignmentElement)), node), node); + } + ts.Debug.assertNode(node, ts.isArrayLiteralExpression); + return node; + } + ts.convertToArrayAssignmentPattern = convertToArrayAssignmentPattern; + function convertToAssignmentElementTarget(node) { + if (ts.isBindingPattern(node)) { + return convertToAssignmentPattern(node); + } + ts.Debug.assertNode(node, ts.isExpression); + return node; + } + ts.convertToAssignmentElementTarget = convertToAssignmentElementTarget; +})(ts || (ts = {})); +var ts; +(function (ts) { + var isTypeNodeOrTypeParameterDeclaration = ts.or(ts.isTypeNode, ts.isTypeParameterDeclaration); + function visitNode(node, visitor, test, lift) { + if (node === undefined || visitor === undefined) { + return node; + } + ts.aggregateTransformFlags(node); + var visited = visitor(node); + if (visited === node) { + return node; + } + var visitedNode; + if (visited === undefined) { + return undefined; + } + else if (ts.isArray(visited)) { + visitedNode = (lift || extractSingleNode)(visited); + } + else { + visitedNode = visited; + } + ts.Debug.assertNode(visitedNode, test); + ts.aggregateTransformFlags(visitedNode); + return visitedNode; + } + ts.visitNode = visitNode; + /** + * Visits a NodeArray using the supplied visitor, possibly returning a new NodeArray in its place. + * + * @param nodes The NodeArray to visit. + * @param visitor The callback used to visit a Node. + * @param test A node test to execute for each node. + * @param start An optional value indicating the starting offset at which to start visiting. + * @param count An optional value indicating the maximum number of nodes to visit. + */ + function visitNodes(nodes, visitor, test, start, count) { + if (nodes === undefined || visitor === undefined) { + return nodes; + } + var updated; + // Ensure start and count have valid values + var length = nodes.length; + if (start === undefined || start < 0) { + start = 0; + } + if (count === undefined || count > length - start) { + count = length - start; + } + if (start > 0 || count < length) { + // If we are not visiting all of the original nodes, we must always create a new array. + // Since this is a fragment of a node array, we do not copy over the previous location + // and will only copy over `hasTrailingComma` if we are including the last element. + updated = ts.createNodeArray([], /*hasTrailingComma*/ nodes.hasTrailingComma && start + count === length); + } + // Visit each original node. + for (var i = 0; i < count; i++) { + var node = nodes[i + start]; + ts.aggregateTransformFlags(node); + var visited = node !== undefined ? visitor(node) : undefined; + if (updated !== undefined || visited === undefined || visited !== node) { + if (updated === undefined) { + // Ensure we have a copy of `nodes`, up to the current index. + updated = ts.createNodeArray(nodes.slice(0, i), nodes.hasTrailingComma); + ts.setTextRange(updated, nodes); + } + if (visited) { + if (ts.isArray(visited)) { + for (var _i = 0, visited_1 = visited; _i < visited_1.length; _i++) { + var visitedNode = visited_1[_i]; + ts.Debug.assertNode(visitedNode, test); + ts.aggregateTransformFlags(visitedNode); + updated.push(visitedNode); + } + } + else { + ts.Debug.assertNode(visited, test); + ts.aggregateTransformFlags(visited); + updated.push(visited); + } + } + } + } + return updated || nodes; + } + ts.visitNodes = visitNodes; + /** + * Starts a new lexical environment and visits a statement list, ending the lexical environment + * and merging hoisted declarations upon completion. + */ + function visitLexicalEnvironment(statements, visitor, context, start, ensureUseStrict) { + context.startLexicalEnvironment(); + statements = visitNodes(statements, visitor, ts.isStatement, start); + if (ensureUseStrict && !ts.startsWithUseStrict(statements)) { + statements = ts.setTextRange(ts.createNodeArray([ts.createExpressionStatement(ts.createLiteral("use strict"))].concat(statements)), statements); + } + var declarations = context.endLexicalEnvironment(); + return ts.setTextRange(ts.createNodeArray(ts.concatenate(declarations, statements)), statements); + } + ts.visitLexicalEnvironment = visitLexicalEnvironment; + /** + * Starts a new lexical environment and visits a parameter list, suspending the lexical + * environment upon completion. + */ + function visitParameterList(nodes, visitor, context, nodesVisitor) { + if (nodesVisitor === void 0) { nodesVisitor = visitNodes; } + context.startLexicalEnvironment(); + var updated = nodesVisitor(nodes, visitor, ts.isParameterDeclaration); + context.suspendLexicalEnvironment(); + return updated; + } + ts.visitParameterList = visitParameterList; + function visitFunctionBody(node, visitor, context) { + context.resumeLexicalEnvironment(); + var updated = visitNode(node, visitor, ts.isConciseBody); + var declarations = context.endLexicalEnvironment(); + if (ts.some(declarations)) { + var block = ts.convertToFunctionBody(updated); + var statements = ts.mergeLexicalEnvironment(block.statements, declarations); + return ts.updateBlock(block, statements); + } + return updated; + } + ts.visitFunctionBody = visitFunctionBody; + function visitEachChild(node, visitor, context, nodesVisitor, tokenVisitor) { + if (nodesVisitor === void 0) { nodesVisitor = visitNodes; } + if (node === undefined) { + return undefined; + } + var kind = node.kind; + // No need to visit nodes with no children. + if ((kind > 0 /* FirstToken */ && kind <= 147 /* LastToken */) || kind === 178 /* ThisType */) { + return node; + } + switch (kind) { + // Names + case 72 /* Identifier */: + return ts.updateIdentifier(node, nodesVisitor(node.typeArguments, visitor, isTypeNodeOrTypeParameterDeclaration)); + case 148 /* QualifiedName */: + return ts.updateQualifiedName(node, visitNode(node.left, visitor, ts.isEntityName), visitNode(node.right, visitor, ts.isIdentifier)); + case 149 /* ComputedPropertyName */: + return ts.updateComputedPropertyName(node, visitNode(node.expression, visitor, ts.isExpression)); + // Signature elements + case 150 /* TypeParameter */: + return ts.updateTypeParameterDeclaration(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.constraint, visitor, ts.isTypeNode), visitNode(node.default, visitor, ts.isTypeNode)); + case 151 /* Parameter */: + return ts.updateParameter(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.dotDotDotToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isBindingName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); + case 152 /* Decorator */: + return ts.updateDecorator(node, visitNode(node.expression, visitor, ts.isExpression)); + // Type elements + case 153 /* PropertySignature */: + return ts.updatePropertySignature(node, nodesVisitor(node.modifiers, visitor, ts.isToken), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); + case 154 /* PropertyDeclaration */: + return ts.updateProperty(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); + case 155 /* MethodSignature */: + return ts.updateMethodSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken)); + case 156 /* MethodDeclaration */: + return ts.updateMethod(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); + case 157 /* Constructor */: + return ts.updateConstructor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context)); + case 158 /* GetAccessor */: + return ts.updateGetAccessor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); + case 159 /* SetAccessor */: + return ts.updateSetAccessor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context)); + case 160 /* CallSignature */: + return ts.updateCallSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); + case 161 /* ConstructSignature */: + return ts.updateConstructSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); + case 162 /* IndexSignature */: + return ts.updateIndexSignature(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); + // Types + case 163 /* TypePredicate */: + return ts.updateTypePredicateNode(node, visitNode(node.parameterName, visitor), visitNode(node.type, visitor, ts.isTypeNode)); + case 164 /* TypeReference */: + return ts.updateTypeReferenceNode(node, visitNode(node.typeName, visitor, ts.isEntityName), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode)); + case 165 /* FunctionType */: + return ts.updateFunctionTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); + case 166 /* ConstructorType */: + return ts.updateConstructorTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); + case 167 /* TypeQuery */: + return ts.updateTypeQueryNode(node, visitNode(node.exprName, visitor, ts.isEntityName)); + case 168 /* TypeLiteral */: + return ts.updateTypeLiteralNode(node, nodesVisitor(node.members, visitor, ts.isTypeElement)); + case 169 /* ArrayType */: + return ts.updateArrayTypeNode(node, visitNode(node.elementType, visitor, ts.isTypeNode)); + case 170 /* TupleType */: + return ts.updateTupleTypeNode(node, nodesVisitor(node.elementTypes, visitor, ts.isTypeNode)); + case 171 /* OptionalType */: + return ts.updateOptionalTypeNode(node, visitNode(node.type, visitor, ts.isTypeNode)); + case 172 /* RestType */: + return ts.updateRestTypeNode(node, visitNode(node.type, visitor, ts.isTypeNode)); + case 173 /* UnionType */: + return ts.updateUnionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode)); + case 174 /* IntersectionType */: + return ts.updateIntersectionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode)); + case 175 /* ConditionalType */: + return ts.updateConditionalTypeNode(node, visitNode(node.checkType, visitor, ts.isTypeNode), visitNode(node.extendsType, visitor, ts.isTypeNode), visitNode(node.trueType, visitor, ts.isTypeNode), visitNode(node.falseType, visitor, ts.isTypeNode)); + case 176 /* InferType */: + return ts.updateInferTypeNode(node, visitNode(node.typeParameter, visitor, ts.isTypeParameterDeclaration)); + case 183 /* ImportType */: + return ts.updateImportTypeNode(node, visitNode(node.argument, visitor, ts.isTypeNode), visitNode(node.qualifier, visitor, ts.isEntityName), visitNodes(node.typeArguments, visitor, ts.isTypeNode), node.isTypeOf); + case 177 /* ParenthesizedType */: + return ts.updateParenthesizedType(node, visitNode(node.type, visitor, ts.isTypeNode)); + case 179 /* TypeOperator */: + return ts.updateTypeOperatorNode(node, visitNode(node.type, visitor, ts.isTypeNode)); + case 180 /* IndexedAccessType */: + return ts.updateIndexedAccessTypeNode(node, visitNode(node.objectType, visitor, ts.isTypeNode), visitNode(node.indexType, visitor, ts.isTypeNode)); + case 181 /* MappedType */: + return ts.updateMappedTypeNode(node, visitNode(node.readonlyToken, tokenVisitor, ts.isToken), visitNode(node.typeParameter, visitor, ts.isTypeParameterDeclaration), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode)); + case 182 /* LiteralType */: + return ts.updateLiteralTypeNode(node, visitNode(node.literal, visitor, ts.isExpression)); + // Binding patterns + case 184 /* ObjectBindingPattern */: + return ts.updateObjectBindingPattern(node, nodesVisitor(node.elements, visitor, ts.isBindingElement)); + case 185 /* ArrayBindingPattern */: + return ts.updateArrayBindingPattern(node, nodesVisitor(node.elements, visitor, ts.isArrayBindingElement)); + case 186 /* BindingElement */: + return ts.updateBindingElement(node, visitNode(node.dotDotDotToken, tokenVisitor, ts.isToken), visitNode(node.propertyName, visitor, ts.isPropertyName), visitNode(node.name, visitor, ts.isBindingName), visitNode(node.initializer, visitor, ts.isExpression)); + // Expression + case 187 /* ArrayLiteralExpression */: + return ts.updateArrayLiteral(node, nodesVisitor(node.elements, visitor, ts.isExpression)); + case 188 /* ObjectLiteralExpression */: + return ts.updateObjectLiteral(node, nodesVisitor(node.properties, visitor, ts.isObjectLiteralElementLike)); + case 189 /* PropertyAccessExpression */: + return ts.updatePropertyAccess(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.name, visitor, ts.isIdentifier)); + case 190 /* ElementAccessExpression */: + return ts.updateElementAccess(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.argumentExpression, visitor, ts.isExpression)); + case 191 /* CallExpression */: + return ts.updateCall(node, visitNode(node.expression, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression)); + case 192 /* NewExpression */: + return ts.updateNew(node, visitNode(node.expression, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression)); + case 193 /* TaggedTemplateExpression */: + return ts.updateTaggedTemplate(node, visitNode(node.tag, visitor, ts.isExpression), visitNodes(node.typeArguments, visitor, ts.isExpression), visitNode(node.template, visitor, ts.isTemplateLiteral)); + case 194 /* TypeAssertionExpression */: + return ts.updateTypeAssertion(node, visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.expression, visitor, ts.isExpression)); + case 195 /* ParenthesizedExpression */: + return ts.updateParen(node, visitNode(node.expression, visitor, ts.isExpression)); + case 196 /* FunctionExpression */: + return ts.updateFunctionExpression(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); + case 197 /* ArrowFunction */: + return ts.updateArrowFunction(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.equalsGreaterThanToken, visitor, ts.isToken), visitFunctionBody(node.body, visitor, context)); + case 198 /* DeleteExpression */: + return ts.updateDelete(node, visitNode(node.expression, visitor, ts.isExpression)); + case 199 /* TypeOfExpression */: + return ts.updateTypeOf(node, visitNode(node.expression, visitor, ts.isExpression)); + case 200 /* VoidExpression */: + return ts.updateVoid(node, visitNode(node.expression, visitor, ts.isExpression)); + case 201 /* AwaitExpression */: + return ts.updateAwait(node, visitNode(node.expression, visitor, ts.isExpression)); + case 202 /* PrefixUnaryExpression */: + return ts.updatePrefix(node, visitNode(node.operand, visitor, ts.isExpression)); + case 203 /* PostfixUnaryExpression */: + return ts.updatePostfix(node, visitNode(node.operand, visitor, ts.isExpression)); + case 204 /* BinaryExpression */: + return ts.updateBinary(node, visitNode(node.left, visitor, ts.isExpression), visitNode(node.right, visitor, ts.isExpression), visitNode(node.operatorToken, visitor, ts.isToken)); + case 205 /* ConditionalExpression */: + return ts.updateConditional(node, visitNode(node.condition, visitor, ts.isExpression), visitNode(node.questionToken, visitor, ts.isToken), visitNode(node.whenTrue, visitor, ts.isExpression), visitNode(node.colonToken, visitor, ts.isToken), visitNode(node.whenFalse, visitor, ts.isExpression)); + case 206 /* TemplateExpression */: + return ts.updateTemplateExpression(node, visitNode(node.head, visitor, ts.isTemplateHead), nodesVisitor(node.templateSpans, visitor, ts.isTemplateSpan)); + case 207 /* YieldExpression */: + return ts.updateYield(node, visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.expression, visitor, ts.isExpression)); + case 208 /* SpreadElement */: + return ts.updateSpread(node, visitNode(node.expression, visitor, ts.isExpression)); + case 209 /* ClassExpression */: + return ts.updateClassExpression(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement)); + case 211 /* ExpressionWithTypeArguments */: + return ts.updateExpressionWithTypeArguments(node, nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), visitNode(node.expression, visitor, ts.isExpression)); + case 212 /* AsExpression */: + return ts.updateAsExpression(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.type, visitor, ts.isTypeNode)); + case 213 /* NonNullExpression */: + return ts.updateNonNullExpression(node, visitNode(node.expression, visitor, ts.isExpression)); + case 214 /* MetaProperty */: + return ts.updateMetaProperty(node, visitNode(node.name, visitor, ts.isIdentifier)); + // Misc + case 216 /* TemplateSpan */: + return ts.updateTemplateSpan(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.literal, visitor, ts.isTemplateMiddleOrTemplateTail)); + // Element + case 218 /* Block */: + return ts.updateBlock(node, nodesVisitor(node.statements, visitor, ts.isStatement)); + case 219 /* VariableStatement */: + return ts.updateVariableStatement(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.declarationList, visitor, ts.isVariableDeclarationList)); + case 221 /* ExpressionStatement */: + return ts.updateExpressionStatement(node, visitNode(node.expression, visitor, ts.isExpression)); + case 222 /* IfStatement */: + return ts.updateIf(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.thenStatement, visitor, ts.isStatement, ts.liftToBlock), visitNode(node.elseStatement, visitor, ts.isStatement, ts.liftToBlock)); + case 223 /* DoStatement */: + return ts.updateDo(node, visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock), visitNode(node.expression, visitor, ts.isExpression)); + case 224 /* WhileStatement */: + return ts.updateWhile(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); + case 225 /* ForStatement */: + return ts.updateFor(node, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.condition, visitor, ts.isExpression), visitNode(node.incrementor, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); + case 226 /* ForInStatement */: + return ts.updateForIn(node, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); + case 227 /* ForOfStatement */: + return ts.updateForOf(node, visitNode(node.awaitModifier, visitor, ts.isToken), visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); + case 228 /* ContinueStatement */: + return ts.updateContinue(node, visitNode(node.label, visitor, ts.isIdentifier)); + case 229 /* BreakStatement */: + return ts.updateBreak(node, visitNode(node.label, visitor, ts.isIdentifier)); + case 230 /* ReturnStatement */: + return ts.updateReturn(node, visitNode(node.expression, visitor, ts.isExpression)); + case 231 /* WithStatement */: + return ts.updateWith(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); + case 232 /* SwitchStatement */: + return ts.updateSwitch(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.caseBlock, visitor, ts.isCaseBlock)); + case 233 /* LabeledStatement */: + return ts.updateLabel(node, visitNode(node.label, visitor, ts.isIdentifier), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); + case 234 /* ThrowStatement */: + return ts.updateThrow(node, visitNode(node.expression, visitor, ts.isExpression)); + case 235 /* TryStatement */: + return ts.updateTry(node, visitNode(node.tryBlock, visitor, ts.isBlock), visitNode(node.catchClause, visitor, ts.isCatchClause), visitNode(node.finallyBlock, visitor, ts.isBlock)); + case 237 /* VariableDeclaration */: + return ts.updateVariableDeclaration(node, visitNode(node.name, visitor, ts.isBindingName), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); + case 238 /* VariableDeclarationList */: + return ts.updateVariableDeclarationList(node, nodesVisitor(node.declarations, visitor, ts.isVariableDeclaration)); + case 239 /* FunctionDeclaration */: + return ts.updateFunctionDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); + case 240 /* ClassDeclaration */: + return ts.updateClassDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement)); + case 241 /* InterfaceDeclaration */: + return ts.updateInterfaceDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isTypeElement)); + case 242 /* TypeAliasDeclaration */: + return ts.updateTypeAliasDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); + case 243 /* EnumDeclaration */: + return ts.updateEnumDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.members, visitor, ts.isEnumMember)); + case 244 /* ModuleDeclaration */: + return ts.updateModuleDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.body, visitor, ts.isModuleBody)); + case 245 /* ModuleBlock */: + return ts.updateModuleBlock(node, nodesVisitor(node.statements, visitor, ts.isStatement)); + case 246 /* CaseBlock */: + return ts.updateCaseBlock(node, nodesVisitor(node.clauses, visitor, ts.isCaseOrDefaultClause)); + case 247 /* NamespaceExportDeclaration */: + return ts.updateNamespaceExportDeclaration(node, visitNode(node.name, visitor, ts.isIdentifier)); + case 248 /* ImportEqualsDeclaration */: + return ts.updateImportEqualsDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.moduleReference, visitor, ts.isModuleReference)); + case 249 /* ImportDeclaration */: + return ts.updateImportDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.importClause, visitor, ts.isImportClause), visitNode(node.moduleSpecifier, visitor, ts.isExpression)); + case 250 /* ImportClause */: + return ts.updateImportClause(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.namedBindings, visitor, ts.isNamedImportBindings)); + case 251 /* NamespaceImport */: + return ts.updateNamespaceImport(node, visitNode(node.name, visitor, ts.isIdentifier)); + case 252 /* NamedImports */: + return ts.updateNamedImports(node, nodesVisitor(node.elements, visitor, ts.isImportSpecifier)); + case 253 /* ImportSpecifier */: + return ts.updateImportSpecifier(node, visitNode(node.propertyName, visitor, ts.isIdentifier), visitNode(node.name, visitor, ts.isIdentifier)); + case 254 /* ExportAssignment */: + return ts.updateExportAssignment(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.expression, visitor, ts.isExpression)); + case 255 /* ExportDeclaration */: + return ts.updateExportDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.exportClause, visitor, ts.isNamedExports), visitNode(node.moduleSpecifier, visitor, ts.isExpression)); + case 256 /* NamedExports */: + return ts.updateNamedExports(node, nodesVisitor(node.elements, visitor, ts.isExportSpecifier)); + case 257 /* ExportSpecifier */: + return ts.updateExportSpecifier(node, visitNode(node.propertyName, visitor, ts.isIdentifier), visitNode(node.name, visitor, ts.isIdentifier)); + // Module references + case 259 /* ExternalModuleReference */: + return ts.updateExternalModuleReference(node, visitNode(node.expression, visitor, ts.isExpression)); + // JSX + case 260 /* JsxElement */: + return ts.updateJsxElement(node, visitNode(node.openingElement, visitor, ts.isJsxOpeningElement), nodesVisitor(node.children, visitor, ts.isJsxChild), visitNode(node.closingElement, visitor, ts.isJsxClosingElement)); + case 261 /* JsxSelfClosingElement */: + return ts.updateJsxSelfClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), visitNode(node.attributes, visitor, ts.isJsxAttributes)); + case 262 /* JsxOpeningElement */: + return ts.updateJsxOpeningElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), visitNode(node.attributes, visitor, ts.isJsxAttributes)); + case 263 /* JsxClosingElement */: + return ts.updateJsxClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression)); + case 264 /* JsxFragment */: + return ts.updateJsxFragment(node, visitNode(node.openingFragment, visitor, ts.isJsxOpeningFragment), nodesVisitor(node.children, visitor, ts.isJsxChild), visitNode(node.closingFragment, visitor, ts.isJsxClosingFragment)); + case 267 /* JsxAttribute */: + return ts.updateJsxAttribute(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.initializer, visitor, ts.isStringLiteralOrJsxExpression)); + case 268 /* JsxAttributes */: + return ts.updateJsxAttributes(node, nodesVisitor(node.properties, visitor, ts.isJsxAttributeLike)); + case 269 /* JsxSpreadAttribute */: + return ts.updateJsxSpreadAttribute(node, visitNode(node.expression, visitor, ts.isExpression)); + case 270 /* JsxExpression */: + return ts.updateJsxExpression(node, visitNode(node.expression, visitor, ts.isExpression)); + // Clauses + case 271 /* CaseClause */: + return ts.updateCaseClause(node, visitNode(node.expression, visitor, ts.isExpression), nodesVisitor(node.statements, visitor, ts.isStatement)); + case 272 /* DefaultClause */: + return ts.updateDefaultClause(node, nodesVisitor(node.statements, visitor, ts.isStatement)); + case 273 /* HeritageClause */: + return ts.updateHeritageClause(node, nodesVisitor(node.types, visitor, ts.isExpressionWithTypeArguments)); + case 274 /* CatchClause */: + return ts.updateCatchClause(node, visitNode(node.variableDeclaration, visitor, ts.isVariableDeclaration), visitNode(node.block, visitor, ts.isBlock)); + // Property assignments + case 275 /* PropertyAssignment */: + return ts.updatePropertyAssignment(node, visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.initializer, visitor, ts.isExpression)); + case 276 /* ShorthandPropertyAssignment */: + return ts.updateShorthandPropertyAssignment(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.objectAssignmentInitializer, visitor, ts.isExpression)); + case 277 /* SpreadAssignment */: + return ts.updateSpreadAssignment(node, visitNode(node.expression, visitor, ts.isExpression)); + // Enum + case 278 /* EnumMember */: + return ts.updateEnumMember(node, visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.initializer, visitor, ts.isExpression)); + // Top-level nodes + case 279 /* SourceFile */: + return ts.updateSourceFileNode(node, visitLexicalEnvironment(node.statements, visitor, context)); + // Transformation nodes + case 308 /* PartiallyEmittedExpression */: + return ts.updatePartiallyEmittedExpression(node, visitNode(node.expression, visitor, ts.isExpression)); + case 309 /* CommaListExpression */: + return ts.updateCommaList(node, nodesVisitor(node.elements, visitor, ts.isExpression)); + default: + // No need to visit nodes with no children. + return node; + } + } + ts.visitEachChild = visitEachChild; + /** + * Extracts the single node from a NodeArray. + * + * @param nodes The NodeArray. + */ + function extractSingleNode(nodes) { + ts.Debug.assert(nodes.length <= 1, "Too many nodes written to output."); + return ts.singleOrUndefined(nodes); + } +})(ts || (ts = {})); +/* @internal */ +(function (ts) { + function reduceNode(node, f, initial) { + return node ? f(initial, node) : initial; + } + function reduceNodeArray(nodes, f, initial) { + return nodes ? f(initial, nodes) : initial; + } + /** + * Similar to `reduceLeft`, performs a reduction against each child of a node. + * NOTE: Unlike `forEachChild`, this does *not* visit every node. + * + * @param node The node containing the children to reduce. + * @param initial The initial value to supply to the reduction. + * @param f The callback function + */ + function reduceEachChild(node, initial, cbNode, cbNodeArray) { + if (node === undefined) { + return initial; + } + var reduceNodes = cbNodeArray ? reduceNodeArray : ts.reduceLeft; + var cbNodes = cbNodeArray || cbNode; + var kind = node.kind; + // No need to visit nodes with no children. + if ((kind > 0 /* FirstToken */ && kind <= 147 /* LastToken */)) { + return initial; + } + // We do not yet support types. + if ((kind >= 163 /* TypePredicate */ && kind <= 182 /* LiteralType */)) { + return initial; + } + var result = initial; + switch (node.kind) { + // Leaf nodes + case 217 /* SemicolonClassElement */: + case 220 /* EmptyStatement */: + case 210 /* OmittedExpression */: + case 236 /* DebuggerStatement */: + case 307 /* NotEmittedStatement */: + // No need to visit nodes with no children. + break; + // Names + case 148 /* QualifiedName */: + result = reduceNode(node.left, cbNode, result); + result = reduceNode(node.right, cbNode, result); + break; + case 149 /* ComputedPropertyName */: + result = reduceNode(node.expression, cbNode, result); + break; + // Signature elements + case 151 /* Parameter */: + result = reduceNodes(node.decorators, cbNodes, result); + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.type, cbNode, result); + result = reduceNode(node.initializer, cbNode, result); + break; + case 152 /* Decorator */: + result = reduceNode(node.expression, cbNode, result); + break; + // Type member + case 153 /* PropertySignature */: + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.questionToken, cbNode, result); + result = reduceNode(node.type, cbNode, result); + result = reduceNode(node.initializer, cbNode, result); + break; + case 154 /* PropertyDeclaration */: + result = reduceNodes(node.decorators, cbNodes, result); + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.type, cbNode, result); + result = reduceNode(node.initializer, cbNode, result); + break; + case 156 /* MethodDeclaration */: + result = reduceNodes(node.decorators, cbNodes, result); + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNodes(node.typeParameters, cbNodes, result); + result = reduceNodes(node.parameters, cbNodes, result); + result = reduceNode(node.type, cbNode, result); + result = reduceNode(node.body, cbNode, result); + break; + case 157 /* Constructor */: + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNodes(node.parameters, cbNodes, result); + result = reduceNode(node.body, cbNode, result); + break; + case 158 /* GetAccessor */: + result = reduceNodes(node.decorators, cbNodes, result); + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNodes(node.parameters, cbNodes, result); + result = reduceNode(node.type, cbNode, result); + result = reduceNode(node.body, cbNode, result); + break; + case 159 /* SetAccessor */: + result = reduceNodes(node.decorators, cbNodes, result); + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNodes(node.parameters, cbNodes, result); + result = reduceNode(node.body, cbNode, result); + break; + // Binding patterns + case 184 /* ObjectBindingPattern */: + case 185 /* ArrayBindingPattern */: + result = reduceNodes(node.elements, cbNodes, result); + break; + case 186 /* BindingElement */: + result = reduceNode(node.propertyName, cbNode, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.initializer, cbNode, result); + break; + // Expression + case 187 /* ArrayLiteralExpression */: + result = reduceNodes(node.elements, cbNodes, result); + break; + case 188 /* ObjectLiteralExpression */: + result = reduceNodes(node.properties, cbNodes, result); + break; + case 189 /* PropertyAccessExpression */: + result = reduceNode(node.expression, cbNode, result); + result = reduceNode(node.name, cbNode, result); + break; + case 190 /* ElementAccessExpression */: + result = reduceNode(node.expression, cbNode, result); + result = reduceNode(node.argumentExpression, cbNode, result); + break; + case 191 /* CallExpression */: + result = reduceNode(node.expression, cbNode, result); + result = reduceNodes(node.typeArguments, cbNodes, result); + result = reduceNodes(node.arguments, cbNodes, result); + break; + case 192 /* NewExpression */: + result = reduceNode(node.expression, cbNode, result); + result = reduceNodes(node.typeArguments, cbNodes, result); + result = reduceNodes(node.arguments, cbNodes, result); + break; + case 193 /* TaggedTemplateExpression */: + result = reduceNode(node.tag, cbNode, result); + result = reduceNodes(node.typeArguments, cbNodes, result); + result = reduceNode(node.template, cbNode, result); + break; + case 194 /* TypeAssertionExpression */: + result = reduceNode(node.type, cbNode, result); + result = reduceNode(node.expression, cbNode, result); + break; + case 196 /* FunctionExpression */: + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNodes(node.typeParameters, cbNodes, result); + result = reduceNodes(node.parameters, cbNodes, result); + result = reduceNode(node.type, cbNode, result); + result = reduceNode(node.body, cbNode, result); + break; + case 197 /* ArrowFunction */: + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNodes(node.typeParameters, cbNodes, result); + result = reduceNodes(node.parameters, cbNodes, result); + result = reduceNode(node.type, cbNode, result); + result = reduceNode(node.body, cbNode, result); + break; + case 195 /* ParenthesizedExpression */: + case 198 /* DeleteExpression */: + case 199 /* TypeOfExpression */: + case 200 /* VoidExpression */: + case 201 /* AwaitExpression */: + case 207 /* YieldExpression */: + case 208 /* SpreadElement */: + case 213 /* NonNullExpression */: + result = reduceNode(node.expression, cbNode, result); + break; + case 202 /* PrefixUnaryExpression */: + case 203 /* PostfixUnaryExpression */: + result = reduceNode(node.operand, cbNode, result); + break; + case 204 /* BinaryExpression */: + result = reduceNode(node.left, cbNode, result); + result = reduceNode(node.right, cbNode, result); + break; + case 205 /* ConditionalExpression */: + result = reduceNode(node.condition, cbNode, result); + result = reduceNode(node.whenTrue, cbNode, result); + result = reduceNode(node.whenFalse, cbNode, result); + break; + case 206 /* TemplateExpression */: + result = reduceNode(node.head, cbNode, result); + result = reduceNodes(node.templateSpans, cbNodes, result); + break; + case 209 /* ClassExpression */: + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNodes(node.typeParameters, cbNodes, result); + result = reduceNodes(node.heritageClauses, cbNodes, result); + result = reduceNodes(node.members, cbNodes, result); + break; + case 211 /* ExpressionWithTypeArguments */: + result = reduceNode(node.expression, cbNode, result); + result = reduceNodes(node.typeArguments, cbNodes, result); + break; + case 212 /* AsExpression */: + result = reduceNode(node.expression, cbNode, result); + result = reduceNode(node.type, cbNode, result); + break; + // Misc + case 216 /* TemplateSpan */: + result = reduceNode(node.expression, cbNode, result); + result = reduceNode(node.literal, cbNode, result); + break; + // Element + case 218 /* Block */: + result = reduceNodes(node.statements, cbNodes, result); + break; + case 219 /* VariableStatement */: + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.declarationList, cbNode, result); + break; + case 221 /* ExpressionStatement */: + result = reduceNode(node.expression, cbNode, result); + break; + case 222 /* IfStatement */: + result = reduceNode(node.expression, cbNode, result); + result = reduceNode(node.thenStatement, cbNode, result); + result = reduceNode(node.elseStatement, cbNode, result); + break; + case 223 /* DoStatement */: + result = reduceNode(node.statement, cbNode, result); + result = reduceNode(node.expression, cbNode, result); + break; + case 224 /* WhileStatement */: + case 231 /* WithStatement */: + result = reduceNode(node.expression, cbNode, result); + result = reduceNode(node.statement, cbNode, result); + break; + case 225 /* ForStatement */: + result = reduceNode(node.initializer, cbNode, result); + result = reduceNode(node.condition, cbNode, result); + result = reduceNode(node.incrementor, cbNode, result); + result = reduceNode(node.statement, cbNode, result); + break; + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + result = reduceNode(node.initializer, cbNode, result); + result = reduceNode(node.expression, cbNode, result); + result = reduceNode(node.statement, cbNode, result); + break; + case 230 /* ReturnStatement */: + case 234 /* ThrowStatement */: + result = reduceNode(node.expression, cbNode, result); + break; + case 232 /* SwitchStatement */: + result = reduceNode(node.expression, cbNode, result); + result = reduceNode(node.caseBlock, cbNode, result); + break; + case 233 /* LabeledStatement */: + result = reduceNode(node.label, cbNode, result); + result = reduceNode(node.statement, cbNode, result); + break; + case 235 /* TryStatement */: + result = reduceNode(node.tryBlock, cbNode, result); + result = reduceNode(node.catchClause, cbNode, result); + result = reduceNode(node.finallyBlock, cbNode, result); + break; + case 237 /* VariableDeclaration */: + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.type, cbNode, result); + result = reduceNode(node.initializer, cbNode, result); + break; + case 238 /* VariableDeclarationList */: + result = reduceNodes(node.declarations, cbNodes, result); + break; + case 239 /* FunctionDeclaration */: + result = reduceNodes(node.decorators, cbNodes, result); + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNodes(node.typeParameters, cbNodes, result); + result = reduceNodes(node.parameters, cbNodes, result); + result = reduceNode(node.type, cbNode, result); + result = reduceNode(node.body, cbNode, result); + break; + case 240 /* ClassDeclaration */: + result = reduceNodes(node.decorators, cbNodes, result); + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNodes(node.typeParameters, cbNodes, result); + result = reduceNodes(node.heritageClauses, cbNodes, result); + result = reduceNodes(node.members, cbNodes, result); + break; + case 243 /* EnumDeclaration */: + result = reduceNodes(node.decorators, cbNodes, result); + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNodes(node.members, cbNodes, result); + break; + case 244 /* ModuleDeclaration */: + result = reduceNodes(node.decorators, cbNodes, result); + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.body, cbNode, result); + break; + case 245 /* ModuleBlock */: + result = reduceNodes(node.statements, cbNodes, result); + break; + case 246 /* CaseBlock */: + result = reduceNodes(node.clauses, cbNodes, result); + break; + case 248 /* ImportEqualsDeclaration */: + result = reduceNodes(node.decorators, cbNodes, result); + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.moduleReference, cbNode, result); + break; + case 249 /* ImportDeclaration */: + result = reduceNodes(node.decorators, cbNodes, result); + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.importClause, cbNode, result); + result = reduceNode(node.moduleSpecifier, cbNode, result); + break; + case 250 /* ImportClause */: + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.namedBindings, cbNode, result); + break; + case 251 /* NamespaceImport */: + result = reduceNode(node.name, cbNode, result); + break; + case 252 /* NamedImports */: + case 256 /* NamedExports */: + result = reduceNodes(node.elements, cbNodes, result); + break; + case 253 /* ImportSpecifier */: + case 257 /* ExportSpecifier */: + result = reduceNode(node.propertyName, cbNode, result); + result = reduceNode(node.name, cbNode, result); + break; + case 254 /* ExportAssignment */: + result = ts.reduceLeft(node.decorators, cbNode, result); + result = ts.reduceLeft(node.modifiers, cbNode, result); + result = reduceNode(node.expression, cbNode, result); + break; + case 255 /* ExportDeclaration */: + result = ts.reduceLeft(node.decorators, cbNode, result); + result = ts.reduceLeft(node.modifiers, cbNode, result); + result = reduceNode(node.exportClause, cbNode, result); + result = reduceNode(node.moduleSpecifier, cbNode, result); + break; + // Module references + case 259 /* ExternalModuleReference */: + result = reduceNode(node.expression, cbNode, result); + break; + // JSX + case 260 /* JsxElement */: + result = reduceNode(node.openingElement, cbNode, result); + result = ts.reduceLeft(node.children, cbNode, result); + result = reduceNode(node.closingElement, cbNode, result); + break; + case 264 /* JsxFragment */: + result = reduceNode(node.openingFragment, cbNode, result); + result = ts.reduceLeft(node.children, cbNode, result); + result = reduceNode(node.closingFragment, cbNode, result); + break; + case 261 /* JsxSelfClosingElement */: + case 262 /* JsxOpeningElement */: + result = reduceNode(node.tagName, cbNode, result); + result = reduceNodes(node.typeArguments, cbNode, result); + result = reduceNode(node.attributes, cbNode, result); + break; + case 268 /* JsxAttributes */: + result = reduceNodes(node.properties, cbNodes, result); + break; + case 263 /* JsxClosingElement */: + result = reduceNode(node.tagName, cbNode, result); + break; + case 267 /* JsxAttribute */: + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.initializer, cbNode, result); + break; + case 269 /* JsxSpreadAttribute */: + result = reduceNode(node.expression, cbNode, result); + break; + case 270 /* JsxExpression */: + result = reduceNode(node.expression, cbNode, result); + break; + // Clauses + case 271 /* CaseClause */: + result = reduceNode(node.expression, cbNode, result); + // falls through + case 272 /* DefaultClause */: + result = reduceNodes(node.statements, cbNodes, result); + break; + case 273 /* HeritageClause */: + result = reduceNodes(node.types, cbNodes, result); + break; + case 274 /* CatchClause */: + result = reduceNode(node.variableDeclaration, cbNode, result); + result = reduceNode(node.block, cbNode, result); + break; + // Property assignments + case 275 /* PropertyAssignment */: + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.initializer, cbNode, result); + break; + case 276 /* ShorthandPropertyAssignment */: + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.objectAssignmentInitializer, cbNode, result); + break; + case 277 /* SpreadAssignment */: + result = reduceNode(node.expression, cbNode, result); + break; + // Enum + case 278 /* EnumMember */: + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.initializer, cbNode, result); + break; + // Top-level nodes + case 279 /* SourceFile */: + result = reduceNodes(node.statements, cbNodes, result); + break; + // Transformation nodes + case 308 /* PartiallyEmittedExpression */: + result = reduceNode(node.expression, cbNode, result); + break; + case 309 /* CommaListExpression */: + result = reduceNodes(node.elements, cbNodes, result); + break; + default: + break; + } + return result; + } + ts.reduceEachChild = reduceEachChild; + function mergeLexicalEnvironment(statements, declarations) { + if (!ts.some(declarations)) { + return statements; + } + return ts.isNodeArray(statements) + ? ts.setTextRange(ts.createNodeArray(ts.addStatementsAfterPrologue(statements.slice(), declarations)), statements) + : ts.addStatementsAfterPrologue(statements, declarations); + } + ts.mergeLexicalEnvironment = mergeLexicalEnvironment; + /** + * Lifts a NodeArray containing only Statement nodes to a block. + * + * @param nodes The NodeArray. + */ + function liftToBlock(nodes) { + Debug.assert(ts.every(nodes, ts.isStatement), "Cannot lift nodes to a Block."); + return ts.singleOrUndefined(nodes) || ts.createBlock(nodes); + } + ts.liftToBlock = liftToBlock; + /** + * Aggregates the TransformFlags for a Node and its subtree. + */ + function aggregateTransformFlags(node) { + aggregateTransformFlagsForNode(node); + return node; + } + ts.aggregateTransformFlags = aggregateTransformFlags; + /** + * Aggregates the TransformFlags for a Node and its subtree. The flags for the subtree are + * computed first, then the transform flags for the current node are computed from the subtree + * flags and the state of the current node. Finally, the transform flags of the node are + * returned, excluding any flags that should not be included in its parent node's subtree + * flags. + */ + function aggregateTransformFlagsForNode(node) { + if (node === undefined) { + return 0 /* None */; + } + if (node.transformFlags & 536870912 /* HasComputedFlags */) { + return node.transformFlags & ~ts.getTransformFlagsSubtreeExclusions(node.kind); + } + var subtreeFlags = aggregateTransformFlagsForSubtree(node); + return ts.computeTransformFlagsForNode(node, subtreeFlags); + } + function aggregateTransformFlagsForNodeArray(nodes) { + if (nodes === undefined) { + return 0 /* None */; + } + var subtreeFlags = 0 /* None */; + var nodeArrayFlags = 0 /* None */; + for (var _i = 0, nodes_3 = nodes; _i < nodes_3.length; _i++) { + var node = nodes_3[_i]; + subtreeFlags |= aggregateTransformFlagsForNode(node); + nodeArrayFlags |= node.transformFlags & ~536870912 /* HasComputedFlags */; + } + nodes.transformFlags = nodeArrayFlags | 536870912 /* HasComputedFlags */; + return subtreeFlags; + } + /** + * Aggregates the transform flags for the subtree of a node. + */ + function aggregateTransformFlagsForSubtree(node) { + // We do not transform ambient declarations or types, so there is no need to + // recursively aggregate transform flags. + if (ts.hasModifier(node, 2 /* Ambient */) || (ts.isTypeNode(node) && node.kind !== 211 /* ExpressionWithTypeArguments */)) { + return 0 /* None */; + } + // Aggregate the transform flags of each child. + return reduceEachChild(node, 0 /* None */, aggregateTransformFlagsForChildNode, aggregateTransformFlagsForChildNodes); + } + /** + * Aggregates the TransformFlags of a child node with the TransformFlags of its + * siblings. + */ + function aggregateTransformFlagsForChildNode(transformFlags, node) { + return transformFlags | aggregateTransformFlagsForNode(node); + } + function aggregateTransformFlagsForChildNodes(transformFlags, nodes) { + return transformFlags | aggregateTransformFlagsForNodeArray(nodes); + } + var Debug; + (function (Debug) { + var isDebugInfoEnabled = false; + function failBadSyntaxKind(node, message) { + return Debug.fail((message || "Unexpected node.") + "\r\nNode " + ts.formatSyntaxKind(node.kind) + " was unexpected.", failBadSyntaxKind); + } + Debug.failBadSyntaxKind = failBadSyntaxKind; + Debug.assertEachNode = Debug.shouldAssert(1 /* Normal */) + ? function (nodes, test, message) { return Debug.assert(test === undefined || ts.every(nodes, test), message || "Unexpected node.", function () { return "Node array did not pass test '" + Debug.getFunctionName(test) + "'."; }, Debug.assertEachNode); } + : ts.noop; + Debug.assertNode = Debug.shouldAssert(1 /* Normal */) + ? function (node, test, message) { return Debug.assert(test === undefined || test(node), message || "Unexpected node.", function () { return "Node " + ts.formatSyntaxKind(node.kind) + " did not pass test '" + Debug.getFunctionName(test) + "'."; }, Debug.assertNode); } + : ts.noop; + Debug.assertOptionalNode = Debug.shouldAssert(1 /* Normal */) + ? function (node, test, message) { return Debug.assert(test === undefined || node === undefined || test(node), message || "Unexpected node.", function () { return "Node " + ts.formatSyntaxKind(node.kind) + " did not pass test '" + Debug.getFunctionName(test) + "'."; }, Debug.assertOptionalNode); } + : ts.noop; + Debug.assertOptionalToken = Debug.shouldAssert(1 /* Normal */) + ? function (node, kind, message) { return Debug.assert(kind === undefined || node === undefined || node.kind === kind, message || "Unexpected node.", function () { return "Node " + ts.formatSyntaxKind(node.kind) + " was not a '" + ts.formatSyntaxKind(kind) + "' token."; }, Debug.assertOptionalToken); } + : ts.noop; + Debug.assertMissingNode = Debug.shouldAssert(1 /* Normal */) + ? function (node, message) { return Debug.assert(node === undefined, message || "Unexpected node.", function () { return "Node " + ts.formatSyntaxKind(node.kind) + " was unexpected'."; }, Debug.assertMissingNode); } + : ts.noop; + /** + * Injects debug information into frequently used types. + */ + function enableDebugInfo() { + if (isDebugInfoEnabled) + return; + // Add additional properties in debug mode to assist with debugging. + Object.defineProperties(ts.objectAllocator.getSymbolConstructor().prototype, { + __debugFlags: { get: function () { return ts.formatSymbolFlags(this.flags); } } + }); + Object.defineProperties(ts.objectAllocator.getTypeConstructor().prototype, { + __debugFlags: { get: function () { return ts.formatTypeFlags(this.flags); } }, + __debugObjectFlags: { get: function () { return this.flags & 524288 /* Object */ ? ts.formatObjectFlags(this.objectFlags) : ""; } }, + __debugTypeToString: { value: function () { return this.checker.typeToString(this); } }, + }); + var nodeConstructors = [ + ts.objectAllocator.getNodeConstructor(), + ts.objectAllocator.getIdentifierConstructor(), + ts.objectAllocator.getTokenConstructor(), + ts.objectAllocator.getSourceFileConstructor() + ]; + for (var _i = 0, nodeConstructors_1 = nodeConstructors; _i < nodeConstructors_1.length; _i++) { + var ctor = nodeConstructors_1[_i]; + if (!ctor.prototype.hasOwnProperty("__debugKind")) { + Object.defineProperties(ctor.prototype, { + __debugKind: { get: function () { return ts.formatSyntaxKind(this.kind); } }, + __debugModifierFlags: { get: function () { return ts.formatModifierFlags(ts.getModifierFlagsNoCache(this)); } }, + __debugTransformFlags: { get: function () { return ts.formatTransformFlags(this.transformFlags); } }, + __debugEmitFlags: { get: function () { return ts.formatEmitFlags(ts.getEmitFlags(this)); } }, + __debugGetText: { + value: function (includeTrivia) { + if (ts.nodeIsSynthesized(this)) + return ""; + var parseNode = ts.getParseTreeNode(this); + var sourceFile = parseNode && ts.getSourceFileOfNode(parseNode); + return sourceFile ? ts.getSourceTextOfNodeFromSourceFile(sourceFile, parseNode, includeTrivia) : ""; + } + } + }); + } + } + isDebugInfoEnabled = true; + } + Debug.enableDebugInfo = enableDebugInfo; + })(Debug = ts.Debug || (ts.Debug = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + function createSourceMapGenerator(host, file, sourceRoot, sourcesDirectoryPath, generatorOptions) { + var _a = generatorOptions.extendedDiagnostics + ? ts.performance.createTimer("Source Map", "beforeSourcemap", "afterSourcemap") + : ts.performance.nullTimer, enter = _a.enter, exit = _a.exit; + // Current source map file and its index in the sources list + var rawSources = []; + var sources = []; + var sourceToSourceIndexMap = ts.createMap(); + var sourcesContent; + var names = []; + var nameToNameIndexMap; + var mappings = ""; + // Last recorded and encoded mappings + var lastGeneratedLine = 0; + var lastGeneratedCharacter = 0; + var lastSourceIndex = 0; + var lastSourceLine = 0; + var lastSourceCharacter = 0; + var lastNameIndex = 0; + var hasLast = false; + var pendingGeneratedLine = 0; + var pendingGeneratedCharacter = 0; + var pendingSourceIndex = 0; + var pendingSourceLine = 0; + var pendingSourceCharacter = 0; + var pendingNameIndex = 0; + var hasPending = false; + var hasPendingSource = false; + var hasPendingName = false; + return { + getSources: function () { return rawSources; }, + addSource: addSource, + setSourceContent: setSourceContent, + addName: addName, + addMapping: addMapping, + appendSourceMap: appendSourceMap, + toJSON: toJSON, + toString: function () { return JSON.stringify(toJSON()); } + }; + function addSource(fileName) { + enter(); + var source = ts.getRelativePathToDirectoryOrUrl(sourcesDirectoryPath, fileName, host.getCurrentDirectory(), host.getCanonicalFileName, + /*isAbsolutePathAnUrl*/ true); + var sourceIndex = sourceToSourceIndexMap.get(source); + if (sourceIndex === undefined) { + sourceIndex = sources.length; + sources.push(source); + rawSources.push(fileName); + sourceToSourceIndexMap.set(source, sourceIndex); + } + exit(); + return sourceIndex; + } + function setSourceContent(sourceIndex, content) { + enter(); + if (content !== null) { + if (!sourcesContent) + sourcesContent = []; + while (sourcesContent.length < sourceIndex) { + // tslint:disable-next-line:no-null-keyword boolean-trivia + sourcesContent.push(null); + } + sourcesContent[sourceIndex] = content; + } + exit(); + } + function addName(name) { + enter(); + if (!nameToNameIndexMap) + nameToNameIndexMap = ts.createMap(); + var nameIndex = nameToNameIndexMap.get(name); + if (nameIndex === undefined) { + nameIndex = names.length; + names.push(name); + nameToNameIndexMap.set(name, nameIndex); + } + exit(); + return nameIndex; + } + function isNewGeneratedPosition(generatedLine, generatedCharacter) { + return !hasPending + || pendingGeneratedLine !== generatedLine + || pendingGeneratedCharacter !== generatedCharacter; + } + function isBacktrackingSourcePosition(sourceIndex, sourceLine, sourceCharacter) { + return sourceIndex !== undefined + && sourceLine !== undefined + && sourceCharacter !== undefined + && pendingSourceIndex === sourceIndex + && (pendingSourceLine > sourceLine + || pendingSourceLine === sourceLine && pendingSourceCharacter > sourceCharacter); + } + function addMapping(generatedLine, generatedCharacter, sourceIndex, sourceLine, sourceCharacter, nameIndex) { + ts.Debug.assert(generatedLine >= pendingGeneratedLine, "generatedLine cannot backtrack"); + ts.Debug.assert(generatedCharacter >= 0, "generatedCharacter cannot be negative"); + ts.Debug.assert(sourceIndex === undefined || sourceIndex >= 0, "sourceIndex cannot be negative"); + ts.Debug.assert(sourceLine === undefined || sourceLine >= 0, "sourceLine cannot be negative"); + ts.Debug.assert(sourceCharacter === undefined || sourceCharacter >= 0, "sourceCharacter cannot be negative"); + enter(); + // If this location wasn't recorded or the location in source is going backwards, record the mapping + if (isNewGeneratedPosition(generatedLine, generatedCharacter) || + isBacktrackingSourcePosition(sourceIndex, sourceLine, sourceCharacter)) { + commitPendingMapping(); + pendingGeneratedLine = generatedLine; + pendingGeneratedCharacter = generatedCharacter; + hasPendingSource = false; + hasPendingName = false; + hasPending = true; + } + if (sourceIndex !== undefined && sourceLine !== undefined && sourceCharacter !== undefined) { + pendingSourceIndex = sourceIndex; + pendingSourceLine = sourceLine; + pendingSourceCharacter = sourceCharacter; + hasPendingSource = true; + if (nameIndex !== undefined) { + pendingNameIndex = nameIndex; + hasPendingName = true; + } + } + exit(); + } + function appendSourceMap(generatedLine, generatedCharacter, map, sourceMapPath) { + var _a; + ts.Debug.assert(generatedLine >= pendingGeneratedLine, "generatedLine cannot backtrack"); + ts.Debug.assert(generatedCharacter >= 0, "generatedCharacter cannot be negative"); + enter(); + // First, decode the old component sourcemap + var sourceIndexToNewSourceIndexMap = []; + var nameIndexToNewNameIndexMap; + var mappingIterator = decodeMappings(map.mappings); + for (var _b = mappingIterator.next(), raw = _b.value, done = _b.done; !done; _a = mappingIterator.next(), raw = _a.value, done = _a.done, _a) { + // Then reencode all the updated mappings into the overall map + var newSourceIndex = void 0; + var newSourceLine = void 0; + var newSourceCharacter = void 0; + var newNameIndex = void 0; + if (raw.sourceIndex !== undefined) { + newSourceIndex = sourceIndexToNewSourceIndexMap[raw.sourceIndex]; + if (newSourceIndex === undefined) { + // Apply offsets to each position and fixup source entries + var rawPath = map.sources[raw.sourceIndex]; + var relativePath = map.sourceRoot ? ts.combinePaths(map.sourceRoot, rawPath) : rawPath; + var combinedPath = ts.combinePaths(ts.getDirectoryPath(sourceMapPath), relativePath); + sourceIndexToNewSourceIndexMap[raw.sourceIndex] = newSourceIndex = addSource(combinedPath); + if (map.sourcesContent && typeof map.sourcesContent[raw.sourceIndex] === "string") { + setSourceContent(newSourceIndex, map.sourcesContent[raw.sourceIndex]); + } + } + newSourceLine = raw.sourceLine; + newSourceCharacter = raw.sourceCharacter; + if (map.names && raw.nameIndex !== undefined) { + if (!nameIndexToNewNameIndexMap) + nameIndexToNewNameIndexMap = []; + newNameIndex = nameIndexToNewNameIndexMap[raw.nameIndex]; + if (newNameIndex === undefined) { + nameIndexToNewNameIndexMap[raw.nameIndex] = newNameIndex = addName(map.names[raw.nameIndex]); + } + } + } + var newGeneratedLine = raw.generatedLine + generatedLine; + var newGeneratedCharacter = raw.generatedLine === 0 ? raw.generatedCharacter + generatedCharacter : raw.generatedCharacter; + addMapping(newGeneratedLine, newGeneratedCharacter, newSourceIndex, newSourceLine, newSourceCharacter, newNameIndex); + } + exit(); + } + function shouldCommitMapping() { + return !hasLast + || lastGeneratedLine !== pendingGeneratedLine + || lastGeneratedCharacter !== pendingGeneratedCharacter + || lastSourceIndex !== pendingSourceIndex + || lastSourceLine !== pendingSourceLine + || lastSourceCharacter !== pendingSourceCharacter + || lastNameIndex !== pendingNameIndex; + } + function commitPendingMapping() { + if (!hasPending || !shouldCommitMapping()) { + return; + } + enter(); + // Line/Comma delimiters + if (lastGeneratedLine < pendingGeneratedLine) { + // Emit line delimiters + do { + mappings += ";"; + lastGeneratedLine++; + lastGeneratedCharacter = 0; + } while (lastGeneratedLine < pendingGeneratedLine); + } + else { + ts.Debug.assertEqual(lastGeneratedLine, pendingGeneratedLine, "generatedLine cannot backtrack"); + // Emit comma to separate the entry + if (hasLast) { + mappings += ","; + } + } + // 1. Relative generated character + mappings += base64VLQFormatEncode(pendingGeneratedCharacter - lastGeneratedCharacter); + lastGeneratedCharacter = pendingGeneratedCharacter; + if (hasPendingSource) { + // 2. Relative sourceIndex + mappings += base64VLQFormatEncode(pendingSourceIndex - lastSourceIndex); + lastSourceIndex = pendingSourceIndex; + // 3. Relative source line + mappings += base64VLQFormatEncode(pendingSourceLine - lastSourceLine); + lastSourceLine = pendingSourceLine; + // 4. Relative source character + mappings += base64VLQFormatEncode(pendingSourceCharacter - lastSourceCharacter); + lastSourceCharacter = pendingSourceCharacter; + if (hasPendingName) { + // 5. Relative nameIndex + mappings += base64VLQFormatEncode(pendingNameIndex - lastNameIndex); + lastNameIndex = pendingNameIndex; + } + } + hasLast = true; + exit(); + } + function toJSON() { + commitPendingMapping(); + return { + version: 3, + file: file, + sourceRoot: sourceRoot, + sources: sources, + names: names, + mappings: mappings, + sourcesContent: sourcesContent, + }; + } + } + ts.createSourceMapGenerator = createSourceMapGenerator; + // Sometimes tools can see the following line as a source mapping url comment, so we mangle it a bit (the [M]) + var sourceMapCommentRegExp = /^\/\/[@#] source[M]appingURL=(.+)\s*$/; + var whitespaceOrMapCommentRegExp = /^\s*(\/\/[@#] .*)?$/; + /** + * Tries to find the sourceMappingURL comment at the end of a file. + * @param text The source text of the file. + * @param lineStarts The line starts of the file. + */ + function tryGetSourceMappingURL(text, lineStarts) { + if (lineStarts === void 0) { lineStarts = ts.computeLineStarts(text); } + for (var index = lineStarts.length - 1; index >= 0; index--) { + var line = text.substring(lineStarts[index], lineStarts[index + 1]); + var comment = sourceMapCommentRegExp.exec(line); + if (comment) { + return comment[1]; + } + // If we see a non-whitespace/map comment-like line, break, to avoid scanning up the entire file + else if (!line.match(whitespaceOrMapCommentRegExp)) { + break; + } + } + } + ts.tryGetSourceMappingURL = tryGetSourceMappingURL; + function isStringOrNull(x) { + // tslint:disable-next-line:no-null-keyword + return typeof x === "string" || x === null; + } + function isRawSourceMap(x) { + // tslint:disable-next-line:no-null-keyword + return x !== null + && typeof x === "object" + && x.version === 3 + && typeof x.file === "string" + && typeof x.mappings === "string" + && ts.isArray(x.sources) && ts.every(x.sources, ts.isString) + && (x.sourceRoot === undefined || x.sourceRoot === null || typeof x.sourceRoot === "string") + && (x.sourcesContent === undefined || x.sourcesContent === null || ts.isArray(x.sourcesContent) && ts.every(x.sourcesContent, isStringOrNull)) + && (x.names === undefined || x.names === null || ts.isArray(x.names) && ts.every(x.names, ts.isString)); + } + ts.isRawSourceMap = isRawSourceMap; + function tryParseRawSourceMap(text) { + try { + var parsed = JSON.parse(text); + if (isRawSourceMap(parsed)) { + return parsed; + } + } + catch (_a) { + // empty + } + return undefined; + } + ts.tryParseRawSourceMap = tryParseRawSourceMap; + function decodeMappings(mappings) { + var done = false; + var pos = 0; + var generatedLine = 0; + var generatedCharacter = 0; + var sourceIndex = 0; + var sourceLine = 0; + var sourceCharacter = 0; + var nameIndex = 0; + var error; + return { + get pos() { return pos; }, + get error() { return error; }, + get state() { return captureMapping(/*hasSource*/ true, /*hasName*/ true); }, + next: function () { + while (!done && pos < mappings.length) { + var ch = mappings.charCodeAt(pos); + if (ch === 59 /* semicolon */) { + // new line + generatedLine++; + generatedCharacter = 0; + pos++; + continue; + } + if (ch === 44 /* comma */) { + // Next entry is on same line - no action needed + pos++; + continue; + } + var hasSource = false; + var hasName = false; + generatedCharacter += base64VLQFormatDecode(); + if (hasReportedError()) + return stopIterating(); + if (generatedCharacter < 0) + return setErrorAndStopIterating("Invalid generatedCharacter found"); + if (!isSourceMappingSegmentEnd()) { + hasSource = true; + sourceIndex += base64VLQFormatDecode(); + if (hasReportedError()) + return stopIterating(); + if (sourceIndex < 0) + return setErrorAndStopIterating("Invalid sourceIndex found"); + if (isSourceMappingSegmentEnd()) + return setErrorAndStopIterating("Unsupported Format: No entries after sourceIndex"); + sourceLine += base64VLQFormatDecode(); + if (hasReportedError()) + return stopIterating(); + if (sourceLine < 0) + return setErrorAndStopIterating("Invalid sourceLine found"); + if (isSourceMappingSegmentEnd()) + return setErrorAndStopIterating("Unsupported Format: No entries after sourceLine"); + sourceCharacter += base64VLQFormatDecode(); + if (hasReportedError()) + return stopIterating(); + if (sourceCharacter < 0) + return setErrorAndStopIterating("Invalid sourceCharacter found"); + if (!isSourceMappingSegmentEnd()) { + hasName = true; + nameIndex += base64VLQFormatDecode(); + if (hasReportedError()) + return stopIterating(); + if (nameIndex < 0) + return setErrorAndStopIterating("Invalid nameIndex found"); + if (!isSourceMappingSegmentEnd()) + return setErrorAndStopIterating("Unsupported Error Format: Entries after nameIndex"); + } + } + return { value: captureMapping(hasSource, hasName), done: done }; + } + return stopIterating(); + } + }; + function captureMapping(hasSource, hasName) { + return { + generatedLine: generatedLine, + generatedCharacter: generatedCharacter, + sourceIndex: hasSource ? sourceIndex : undefined, + sourceLine: hasSource ? sourceLine : undefined, + sourceCharacter: hasSource ? sourceCharacter : undefined, + nameIndex: hasName ? nameIndex : undefined + }; + } + function stopIterating() { + done = true; + return { value: undefined, done: true }; + } + function setError(message) { + if (error === undefined) { + error = message; + } + } + function setErrorAndStopIterating(message) { + setError(message); + return stopIterating(); + } + function hasReportedError() { + return error !== undefined; + } + function isSourceMappingSegmentEnd() { + return (pos === mappings.length || + mappings.charCodeAt(pos) === 44 /* comma */ || + mappings.charCodeAt(pos) === 59 /* semicolon */); + } + function base64VLQFormatDecode() { + var moreDigits = true; + var shiftCount = 0; + var value = 0; + for (; moreDigits; pos++) { + if (pos >= mappings.length) + return setError("Error in decoding base64VLQFormatDecode, past the mapping string"), -1; + // 6 digit number + var currentByte = base64FormatDecode(mappings.charCodeAt(pos)); + if (currentByte === -1) + return setError("Invalid character in VLQ"), -1; + // If msb is set, we still have more bits to continue + moreDigits = (currentByte & 32) !== 0; + // least significant 5 bits are the next msbs in the final value. + value = value | ((currentByte & 31) << shiftCount); + shiftCount += 5; + } + // Least significant bit if 1 represents negative and rest of the msb is actual absolute value + if ((value & 1) === 0) { + // + number + value = value >> 1; + } + else { + // - number + value = value >> 1; + value = -value; + } + return value; + } + } + ts.decodeMappings = decodeMappings; + function sameMapping(left, right) { + return left === right + || left.generatedLine === right.generatedLine + && left.generatedCharacter === right.generatedCharacter + && left.sourceIndex === right.sourceIndex + && left.sourceLine === right.sourceLine + && left.sourceCharacter === right.sourceCharacter + && left.nameIndex === right.nameIndex; + } + ts.sameMapping = sameMapping; + function isSourceMapping(mapping) { + return mapping.sourceIndex !== undefined + && mapping.sourceLine !== undefined + && mapping.sourceCharacter !== undefined; + } + ts.isSourceMapping = isSourceMapping; + function base64FormatEncode(value) { + return value >= 0 && value < 26 ? 65 /* A */ + value : + value >= 26 && value < 52 ? 97 /* a */ + value - 26 : + value >= 52 && value < 62 ? 48 /* _0 */ + value - 52 : + value === 62 ? 43 /* plus */ : + value === 63 ? 47 /* slash */ : + ts.Debug.fail(value + ": not a base64 value"); + } + function base64FormatDecode(ch) { + return ch >= 65 /* A */ && ch <= 90 /* Z */ ? ch - 65 /* A */ : + ch >= 97 /* a */ && ch <= 122 /* z */ ? ch - 97 /* a */ + 26 : + ch >= 48 /* _0 */ && ch <= 57 /* _9 */ ? ch - 48 /* _0 */ + 52 : + ch === 43 /* plus */ ? 62 : + ch === 47 /* slash */ ? 63 : + -1; + } + function base64VLQFormatEncode(inValue) { + // Add a new least significant bit that has the sign of the value. + // if negative number the least significant bit that gets added to the number has value 1 + // else least significant bit value that gets added is 0 + // eg. -1 changes to binary : 01 [1] => 3 + // +1 changes to binary : 01 [0] => 2 + if (inValue < 0) { + inValue = ((-inValue) << 1) + 1; + } + else { + inValue = inValue << 1; + } + // Encode 5 bits at a time starting from least significant bits + var encodedStr = ""; + do { + var currentDigit = inValue & 31; // 11111 + inValue = inValue >> 5; + if (inValue > 0) { + // There are still more digits to decode, set the msb (6th bit) + currentDigit = currentDigit | 32; + } + encodedStr = encodedStr + String.fromCharCode(base64FormatEncode(currentDigit)); + } while (inValue > 0); + return encodedStr; + } + function isSourceMappedPosition(value) { + return value.sourceIndex !== undefined + && value.sourcePosition !== undefined; + } + function sameMappedPosition(left, right) { + return left.generatedPosition === right.generatedPosition + && left.sourceIndex === right.sourceIndex + && left.sourcePosition === right.sourcePosition; + } + function compareSourcePositions(left, right) { + return ts.compareValues(left.sourceIndex, right.sourceIndex); + } + function compareGeneratedPositions(left, right) { + return ts.compareValues(left.generatedPosition, right.generatedPosition); + } + function getSourcePositionOfMapping(value) { + return value.sourcePosition; + } + function getGeneratedPositionOfMapping(value) { + return value.generatedPosition; + } + function createDocumentPositionMapper(host, map, mapPath) { + var mapDirectory = ts.getDirectoryPath(mapPath); + var sourceRoot = map.sourceRoot ? ts.getNormalizedAbsolutePath(map.sourceRoot, mapDirectory) : mapDirectory; + var generatedAbsoluteFilePath = ts.getNormalizedAbsolutePath(map.file, mapDirectory); + var generatedCanonicalFilePath = host.getCanonicalFileName(generatedAbsoluteFilePath); + var generatedFile = host.getSourceFileLike(generatedCanonicalFilePath); + var sourceFileAbsolutePaths = map.sources.map(function (source) { return ts.getNormalizedAbsolutePath(source, sourceRoot); }); + var sourceFileCanonicalPaths = sourceFileAbsolutePaths.map(function (source) { return host.getCanonicalFileName(source); }); + var sourceToSourceIndexMap = ts.createMapFromEntries(sourceFileCanonicalPaths.map(function (source, i) { return [source, i]; })); + var decodedMappings; + var generatedMappings; + var sourceMappings; + return { + getSourcePosition: getSourcePosition, + getGeneratedPosition: getGeneratedPosition + }; + function processMapping(mapping) { + var generatedPosition = generatedFile !== undefined + ? ts.getPositionOfLineAndCharacterWithEdits(generatedFile, mapping.generatedLine, mapping.generatedCharacter) + : -1; + var source; + var sourcePosition; + if (isSourceMapping(mapping)) { + var sourceFilePath = sourceFileCanonicalPaths[mapping.sourceIndex]; + var sourceFile = host.getSourceFileLike(sourceFilePath); + source = map.sources[mapping.sourceIndex]; + sourcePosition = sourceFile !== undefined + ? ts.getPositionOfLineAndCharacterWithEdits(sourceFile, mapping.sourceLine, mapping.sourceCharacter) + : -1; + } + return { + generatedPosition: generatedPosition, + source: source, + sourceIndex: mapping.sourceIndex, + sourcePosition: sourcePosition, + nameIndex: mapping.nameIndex + }; + } + function getDecodedMappings() { + if (decodedMappings === undefined) { + var decoder = decodeMappings(map.mappings); + var mappings = ts.arrayFrom(decoder, processMapping); + if (decoder.error !== undefined) { + if (host.log) { + host.log("Encountered error while decoding sourcemap: " + decoder.error); + } + decodedMappings = ts.emptyArray; + } + else { + decodedMappings = mappings; + } + } + return decodedMappings; + } + function getSourceMappings(sourceIndex) { + if (sourceMappings === undefined) { + var lists = []; + for (var _i = 0, _a = getDecodedMappings(); _i < _a.length; _i++) { + var mapping = _a[_i]; + if (!isSourceMappedPosition(mapping)) + continue; + var list = lists[mapping.sourceIndex]; + if (!list) + lists[mapping.sourceIndex] = list = []; + list.push(mapping); + } + sourceMappings = lists.map(function (list) { return ts.sortAndDeduplicate(list, compareSourcePositions, sameMappedPosition); }); + } + return sourceMappings[sourceIndex]; + } + function getGeneratedMappings() { + if (generatedMappings === undefined) { + var list = []; + for (var _i = 0, _a = getDecodedMappings(); _i < _a.length; _i++) { + var mapping = _a[_i]; + list.push(mapping); + } + generatedMappings = ts.sortAndDeduplicate(list, compareGeneratedPositions, sameMappedPosition); + } + return generatedMappings; + } + function getGeneratedPosition(loc) { + var sourceIndex = sourceToSourceIndexMap.get(host.getCanonicalFileName(loc.fileName)); + if (sourceIndex === undefined) + return loc; + var sourceMappings = getSourceMappings(sourceIndex); + if (!ts.some(sourceMappings)) + return loc; + var targetIndex = ts.binarySearchKey(sourceMappings, loc.pos, getSourcePositionOfMapping, ts.compareValues); + if (targetIndex < 0) { + // if no exact match, closest is 2's complement of result + targetIndex = ~targetIndex; + } + var mapping = sourceMappings[targetIndex]; + if (mapping === undefined || mapping.sourceIndex !== sourceIndex) { + return loc; + } + return { fileName: generatedAbsoluteFilePath, pos: mapping.generatedPosition }; // Closest pos + } + function getSourcePosition(loc) { + var generatedMappings = getGeneratedMappings(); + if (!ts.some(generatedMappings)) + return loc; + var targetIndex = ts.binarySearchKey(generatedMappings, loc.pos, getGeneratedPositionOfMapping, ts.compareValues); + if (targetIndex < 0) { + // if no exact match, closest is 2's complement of result + targetIndex = ~targetIndex; + } + var mapping = generatedMappings[targetIndex]; + if (mapping === undefined || !isSourceMappedPosition(mapping)) { + return loc; + } + return { fileName: sourceFileAbsolutePaths[mapping.sourceIndex], pos: mapping.sourcePosition }; // Closest pos + } + } + ts.createDocumentPositionMapper = createDocumentPositionMapper; + ts.identitySourceMapConsumer = { + getSourcePosition: ts.identity, + getGeneratedPosition: ts.identity + }; +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + function getOriginalNodeId(node) { + node = ts.getOriginalNode(node); + return node ? ts.getNodeId(node) : 0; + } + ts.getOriginalNodeId = getOriginalNodeId; + function containsDefaultReference(node) { + if (!node) + return false; + if (!ts.isNamedImports(node)) + return false; + return ts.some(node.elements, isNamedDefaultReference); + } + function isNamedDefaultReference(e) { + return e.propertyName !== undefined && e.propertyName.escapedText === "default" /* Default */; + } + function chainBundle(transformSourceFile) { + return transformSourceFileOrBundle; + function transformSourceFileOrBundle(node) { + return node.kind === 279 /* SourceFile */ ? transformSourceFile(node) : transformBundle(node); + } + function transformBundle(node) { + return ts.createBundle(ts.map(node.sourceFiles, transformSourceFile), node.prepends); + } + } + ts.chainBundle = chainBundle; + function getImportNeedsImportStarHelper(node) { + if (!!ts.getNamespaceDeclarationNode(node)) { + return true; + } + var bindings = node.importClause && node.importClause.namedBindings; + if (!bindings) { + return false; + } + if (!ts.isNamedImports(bindings)) + return false; + var defaultRefCount = 0; + for (var _i = 0, _a = bindings.elements; _i < _a.length; _i++) { + var binding = _a[_i]; + if (isNamedDefaultReference(binding)) { + defaultRefCount++; + } + } + // Import star is required if there's default named refs mixed with non-default refs, or if theres non-default refs and it has a default import + return (defaultRefCount > 0 && defaultRefCount !== bindings.elements.length) || (!!(bindings.elements.length - defaultRefCount) && ts.isDefaultImport(node)); + } + ts.getImportNeedsImportStarHelper = getImportNeedsImportStarHelper; + function getImportNeedsImportDefaultHelper(node) { + // Import default is needed if there's a default import or a default ref and no other refs (meaning an import star helper wasn't requested) + return !getImportNeedsImportStarHelper(node) && (ts.isDefaultImport(node) || (!!node.importClause && ts.isNamedImports(node.importClause.namedBindings) && containsDefaultReference(node.importClause.namedBindings))); // TODO: GH#18217 + } + ts.getImportNeedsImportDefaultHelper = getImportNeedsImportDefaultHelper; + function collectExternalModuleInfo(sourceFile, resolver, compilerOptions) { + var externalImports = []; + var exportSpecifiers = ts.createMultiMap(); + var exportedBindings = []; + var uniqueExports = ts.createMap(); + var exportedNames; + var hasExportDefault = false; + var exportEquals; + var hasExportStarsToExportValues = false; + var hasImportStarOrImportDefault = false; + for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { + var node = _a[_i]; + switch (node.kind) { + case 249 /* ImportDeclaration */: + // import "mod" + // import x from "mod" + // import * as x from "mod" + // import { x, y } from "mod" + externalImports.push(node); + hasImportStarOrImportDefault = hasImportStarOrImportDefault || getImportNeedsImportStarHelper(node) || getImportNeedsImportDefaultHelper(node); + break; + case 248 /* ImportEqualsDeclaration */: + if (node.moduleReference.kind === 259 /* ExternalModuleReference */) { + // import x = require("mod") + externalImports.push(node); + } + break; + case 255 /* ExportDeclaration */: + if (node.moduleSpecifier) { + if (!node.exportClause) { + // export * from "mod" + externalImports.push(node); + hasExportStarsToExportValues = true; + } + else { + // export { x, y } from "mod" + externalImports.push(node); + } + } + else { + // export { x, y } + for (var _b = 0, _c = node.exportClause.elements; _b < _c.length; _b++) { + var specifier = _c[_b]; + if (!uniqueExports.get(ts.idText(specifier.name))) { + var name = specifier.propertyName || specifier.name; + exportSpecifiers.add(ts.idText(name), specifier); + var decl = resolver.getReferencedImportDeclaration(name) + || resolver.getReferencedValueDeclaration(name); + if (decl) { + multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(decl), specifier.name); + } + uniqueExports.set(ts.idText(specifier.name), true); + exportedNames = ts.append(exportedNames, specifier.name); + } + } + } + break; + case 254 /* ExportAssignment */: + if (node.isExportEquals && !exportEquals) { + // export = x + exportEquals = node; + } + break; + case 219 /* VariableStatement */: + if (ts.hasModifier(node, 1 /* Export */)) { + for (var _d = 0, _e = node.declarationList.declarations; _d < _e.length; _d++) { + var decl = _e[_d]; + exportedNames = collectExportedVariableInfo(decl, uniqueExports, exportedNames); + } + } + break; + case 239 /* FunctionDeclaration */: + if (ts.hasModifier(node, 1 /* Export */)) { + if (ts.hasModifier(node, 512 /* Default */)) { + // export default function() { } + if (!hasExportDefault) { + multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), ts.getDeclarationName(node)); + hasExportDefault = true; + } + } + else { + // export function x() { } + var name = node.name; + if (!uniqueExports.get(ts.idText(name))) { + multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), name); + uniqueExports.set(ts.idText(name), true); + exportedNames = ts.append(exportedNames, name); + } + } + } + break; + case 240 /* ClassDeclaration */: + if (ts.hasModifier(node, 1 /* Export */)) { + if (ts.hasModifier(node, 512 /* Default */)) { + // export default class { } + if (!hasExportDefault) { + multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), ts.getDeclarationName(node)); + hasExportDefault = true; + } + } + else { + // export class x { } + var name = node.name; + if (name && !uniqueExports.get(ts.idText(name))) { + multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), name); + uniqueExports.set(ts.idText(name), true); + exportedNames = ts.append(exportedNames, name); + } + } + } + break; + } + } + var externalHelpersModuleName = ts.getOrCreateExternalHelpersModuleNameIfNeeded(sourceFile, compilerOptions, hasExportStarsToExportValues, hasImportStarOrImportDefault); + var externalHelpersImportDeclaration = externalHelpersModuleName && ts.createImportDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(externalHelpersModuleName)), ts.createLiteral(ts.externalHelpersModuleNameText)); + if (externalHelpersImportDeclaration) { + ts.addEmitFlags(externalHelpersImportDeclaration, 67108864 /* NeverApplyImportHelper */); + externalImports.unshift(externalHelpersImportDeclaration); + } + return { externalImports: externalImports, exportSpecifiers: exportSpecifiers, exportEquals: exportEquals, hasExportStarsToExportValues: hasExportStarsToExportValues, exportedBindings: exportedBindings, exportedNames: exportedNames, externalHelpersImportDeclaration: externalHelpersImportDeclaration }; + } + ts.collectExternalModuleInfo = collectExternalModuleInfo; + function collectExportedVariableInfo(decl, uniqueExports, exportedNames) { + if (ts.isBindingPattern(decl.name)) { + for (var _i = 0, _a = decl.name.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (!ts.isOmittedExpression(element)) { + exportedNames = collectExportedVariableInfo(element, uniqueExports, exportedNames); + } + } + } + else if (!ts.isGeneratedIdentifier(decl.name)) { + var text = ts.idText(decl.name); + if (!uniqueExports.get(text)) { + uniqueExports.set(text, true); + exportedNames = ts.append(exportedNames, decl.name); + } + } + return exportedNames; + } + /** Use a sparse array as a multi-map. */ + function multiMapSparseArrayAdd(map, key, value) { + var values = map[key]; + if (values) { + values.push(value); + } + else { + map[key] = values = [value]; + } + return values; + } + /** + * Used in the module transformer to check if an expression is reasonably without sideeffect, + * and thus better to copy into multiple places rather than to cache in a temporary variable + * - this is mostly subjective beyond the requirement that the expression not be sideeffecting + */ + function isSimpleCopiableExpression(expression) { + return ts.isStringLiteralLike(expression) || + expression.kind === 8 /* NumericLiteral */ || + ts.isKeyword(expression.kind) || + ts.isIdentifier(expression); + } + ts.isSimpleCopiableExpression = isSimpleCopiableExpression; + /** + * @param input Template string input strings + * @param args Names which need to be made file-level unique + */ + function helperString(input) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + return function (uniqueName) { + var result = ""; + for (var i = 0; i < args.length; i++) { + result += input[i]; + result += uniqueName(args[i]); + } + result += input[input.length - 1]; + return result; + }; + } + ts.helperString = helperString; +})(ts || (ts = {})); +/*@internal*/ +var ts; +(function (ts) { + var FlattenLevel; + (function (FlattenLevel) { + FlattenLevel[FlattenLevel["All"] = 0] = "All"; + FlattenLevel[FlattenLevel["ObjectRest"] = 1] = "ObjectRest"; + })(FlattenLevel = ts.FlattenLevel || (ts.FlattenLevel = {})); + /** + * Flattens a DestructuringAssignment or a VariableDeclaration to an expression. + * + * @param node The node to flatten. + * @param visitor An optional visitor used to visit initializers. + * @param context The transformation context. + * @param level Indicates the extent to which flattening should occur. + * @param needsValue An optional value indicating whether the value from the right-hand-side of + * the destructuring assignment is needed as part of a larger expression. + * @param createAssignmentCallback An optional callback used to create the assignment expression. + */ + function flattenDestructuringAssignment(node, visitor, context, level, needsValue, createAssignmentCallback) { + var location = node; + var value; + if (ts.isDestructuringAssignment(node)) { + value = node.right; + while (ts.isEmptyArrayLiteral(node.left) || ts.isEmptyObjectLiteral(node.left)) { + if (ts.isDestructuringAssignment(value)) { + location = node = value; + value = node.right; + } + else { + return ts.visitNode(value, visitor, ts.isExpression); + } + } + } + var expressions; + var flattenContext = { + context: context, + level: level, + downlevelIteration: !!context.getCompilerOptions().downlevelIteration, + hoistTempVariables: true, + emitExpression: emitExpression, + emitBindingOrAssignment: emitBindingOrAssignment, + createArrayBindingOrAssignmentPattern: makeArrayAssignmentPattern, + createObjectBindingOrAssignmentPattern: makeObjectAssignmentPattern, + createArrayBindingOrAssignmentElement: makeAssignmentElement, + visitor: visitor + }; + if (value) { + value = ts.visitNode(value, visitor, ts.isExpression); + if (ts.isIdentifier(value) && bindingOrAssignmentElementAssignsToName(node, value.escapedText)) { + // If the right-hand value of the assignment is also an assignment target then + // we need to cache the right-hand value. + value = ensureIdentifier(flattenContext, value, /*reuseIdentifierExpressions*/ false, location); + } + else if (needsValue) { + // If the right-hand value of the destructuring assignment needs to be preserved (as + // is the case when the destructuring assignment is part of a larger expression), + // then we need to cache the right-hand value. + // + // The source map location for the assignment should point to the entire binary + // expression. + value = ensureIdentifier(flattenContext, value, /*reuseIdentifierExpressions*/ true, location); + } + else if (ts.nodeIsSynthesized(node)) { + // Generally, the source map location for a destructuring assignment is the root + // expression. + // + // However, if the root expression is synthesized (as in the case + // of the initializer when transforming a ForOfStatement), then the source map + // location should point to the right-hand value of the expression. + location = value; + } + } + flattenBindingOrAssignmentElement(flattenContext, node, value, location, /*skipInitializer*/ ts.isDestructuringAssignment(node)); + if (value && needsValue) { + if (!ts.some(expressions)) { + return value; + } + expressions.push(value); + } + return ts.aggregateTransformFlags(ts.inlineExpressions(expressions)) || ts.createOmittedExpression(); + function emitExpression(expression) { + // NOTE: this completely disables source maps, but aligns with the behavior of + // `emitAssignment` in the old emitter. + ts.setEmitFlags(expression, 64 /* NoNestedSourceMaps */); + ts.aggregateTransformFlags(expression); + expressions = ts.append(expressions, expression); + } + function emitBindingOrAssignment(target, value, location, original) { + ts.Debug.assertNode(target, createAssignmentCallback ? ts.isIdentifier : ts.isExpression); + var expression = createAssignmentCallback + ? createAssignmentCallback(target, value, location) + : ts.setTextRange(ts.createAssignment(ts.visitNode(target, visitor, ts.isExpression), value), location); + expression.original = original; + emitExpression(expression); + } + } + ts.flattenDestructuringAssignment = flattenDestructuringAssignment; + function bindingOrAssignmentElementAssignsToName(element, escapedName) { + var target = ts.getTargetOfBindingOrAssignmentElement(element); // TODO: GH#18217 + if (ts.isBindingOrAssignmentPattern(target)) { + return bindingOrAssignmentPatternAssignsToName(target, escapedName); + } + else if (ts.isIdentifier(target)) { + return target.escapedText === escapedName; + } + return false; + } + function bindingOrAssignmentPatternAssignsToName(pattern, escapedName) { + var elements = ts.getElementsOfBindingOrAssignmentPattern(pattern); + for (var _i = 0, elements_3 = elements; _i < elements_3.length; _i++) { + var element = elements_3[_i]; + if (bindingOrAssignmentElementAssignsToName(element, escapedName)) { + return true; + } + } + return false; + } + /** + * Flattens a VariableDeclaration or ParameterDeclaration to one or more variable declarations. + * + * @param node The node to flatten. + * @param visitor An optional visitor used to visit initializers. + * @param context The transformation context. + * @param boundValue The value bound to the declaration. + * @param skipInitializer A value indicating whether to ignore the initializer of `node`. + * @param hoistTempVariables Indicates whether temporary variables should not be recorded in-line. + * @param level Indicates the extent to which flattening should occur. + */ + function flattenDestructuringBinding(node, visitor, context, level, rval, hoistTempVariables, skipInitializer) { + if (hoistTempVariables === void 0) { hoistTempVariables = false; } + var pendingExpressions; + var pendingDeclarations = []; + var declarations = []; + var flattenContext = { + context: context, + level: level, + downlevelIteration: !!context.getCompilerOptions().downlevelIteration, + hoistTempVariables: hoistTempVariables, + emitExpression: emitExpression, + emitBindingOrAssignment: emitBindingOrAssignment, + createArrayBindingOrAssignmentPattern: makeArrayBindingPattern, + createObjectBindingOrAssignmentPattern: makeObjectBindingPattern, + createArrayBindingOrAssignmentElement: makeBindingElement, + visitor: visitor + }; + if (ts.isVariableDeclaration(node)) { + var initializer = ts.getInitializerOfBindingOrAssignmentElement(node); + if (initializer && ts.isIdentifier(initializer) && bindingOrAssignmentElementAssignsToName(node, initializer.escapedText)) { + // If the right-hand value of the assignment is also an assignment target then + // we need to cache the right-hand value. + initializer = ensureIdentifier(flattenContext, initializer, /*reuseIdentifierExpressions*/ false, initializer); + node = ts.updateVariableDeclaration(node, node.name, node.type, initializer); + } + } + flattenBindingOrAssignmentElement(flattenContext, node, rval, node, skipInitializer); + if (pendingExpressions) { + var temp = ts.createTempVariable(/*recordTempVariable*/ undefined); + if (hoistTempVariables) { + var value = ts.inlineExpressions(pendingExpressions); + pendingExpressions = undefined; + emitBindingOrAssignment(temp, value, /*location*/ undefined, /*original*/ undefined); + } + else { + context.hoistVariableDeclaration(temp); + var pendingDeclaration = ts.last(pendingDeclarations); + pendingDeclaration.pendingExpressions = ts.append(pendingDeclaration.pendingExpressions, ts.createAssignment(temp, pendingDeclaration.value)); + ts.addRange(pendingDeclaration.pendingExpressions, pendingExpressions); + pendingDeclaration.value = temp; + } + } + for (var _i = 0, pendingDeclarations_1 = pendingDeclarations; _i < pendingDeclarations_1.length; _i++) { + var _a = pendingDeclarations_1[_i], pendingExpressions_1 = _a.pendingExpressions, name = _a.name, value = _a.value, location = _a.location, original = _a.original; + var variable = ts.createVariableDeclaration(name, + /*type*/ undefined, pendingExpressions_1 ? ts.inlineExpressions(ts.append(pendingExpressions_1, value)) : value); + variable.original = original; + ts.setTextRange(variable, location); + if (ts.isIdentifier(name)) { + ts.setEmitFlags(variable, 64 /* NoNestedSourceMaps */); + } + ts.aggregateTransformFlags(variable); + declarations.push(variable); + } + return declarations; + function emitExpression(value) { + pendingExpressions = ts.append(pendingExpressions, value); + } + function emitBindingOrAssignment(target, value, location, original) { + ts.Debug.assertNode(target, ts.isBindingName); + if (pendingExpressions) { + value = ts.inlineExpressions(ts.append(pendingExpressions, value)); + pendingExpressions = undefined; + } + pendingDeclarations.push({ pendingExpressions: pendingExpressions, name: target, value: value, location: location, original: original }); + } + } + ts.flattenDestructuringBinding = flattenDestructuringBinding; + /** + * Flattens a BindingOrAssignmentElement into zero or more bindings or assignments. + * + * @param flattenContext Options used to control flattening. + * @param element The element to flatten. + * @param value The current RHS value to assign to the element. + * @param location The location to use for source maps and comments. + * @param skipInitializer An optional value indicating whether to include the initializer + * for the element. + */ + function flattenBindingOrAssignmentElement(flattenContext, element, value, location, skipInitializer) { + if (!skipInitializer) { + var initializer = ts.visitNode(ts.getInitializerOfBindingOrAssignmentElement(element), flattenContext.visitor, ts.isExpression); + if (initializer) { + // Combine value and initializer + value = value ? createDefaultValueCheck(flattenContext, value, initializer, location) : initializer; + } + else if (!value) { + // Use 'void 0' in absence of value and initializer + value = ts.createVoidZero(); + } + } + var bindingTarget = ts.getTargetOfBindingOrAssignmentElement(element); // TODO: GH#18217 + if (ts.isObjectBindingOrAssignmentPattern(bindingTarget)) { + flattenObjectBindingOrAssignmentPattern(flattenContext, element, bindingTarget, value, location); + } + else if (ts.isArrayBindingOrAssignmentPattern(bindingTarget)) { + flattenArrayBindingOrAssignmentPattern(flattenContext, element, bindingTarget, value, location); + } + else { + flattenContext.emitBindingOrAssignment(bindingTarget, value, location, /*original*/ element); // TODO: GH#18217 + } + } + /** + * Flattens an ObjectBindingOrAssignmentPattern into zero or more bindings or assignments. + * + * @param flattenContext Options used to control flattening. + * @param parent The parent element of the pattern. + * @param pattern The ObjectBindingOrAssignmentPattern to flatten. + * @param value The current RHS value to assign to the element. + * @param location The location to use for source maps and comments. + */ + function flattenObjectBindingOrAssignmentPattern(flattenContext, parent, pattern, value, location) { + var elements = ts.getElementsOfBindingOrAssignmentPattern(pattern); + var numElements = elements.length; + if (numElements !== 1) { + // For anything other than a single-element destructuring we need to generate a temporary + // to ensure value is evaluated exactly once. Additionally, if we have zero elements + // we need to emit *something* to ensure that in case a 'var' keyword was already emitted, + // so in that case, we'll intentionally create that temporary. + var reuseIdentifierExpressions = !ts.isDeclarationBindingElement(parent) || numElements !== 0; + value = ensureIdentifier(flattenContext, value, reuseIdentifierExpressions, location); + } + var bindingElements; + var computedTempVariables; + for (var i = 0; i < numElements; i++) { + var element = elements[i]; + if (!ts.getRestIndicatorOfBindingOrAssignmentElement(element)) { + var propertyName = ts.getPropertyNameOfBindingOrAssignmentElement(element); + if (flattenContext.level >= 1 /* ObjectRest */ + && !(element.transformFlags & (131072 /* ContainsRestOrSpread */ | 262144 /* ContainsObjectRestOrSpread */)) + && !(ts.getTargetOfBindingOrAssignmentElement(element).transformFlags & (131072 /* ContainsRestOrSpread */ | 262144 /* ContainsObjectRestOrSpread */)) + && !ts.isComputedPropertyName(propertyName)) { + bindingElements = ts.append(bindingElements, element); + } + else { + if (bindingElements) { + flattenContext.emitBindingOrAssignment(flattenContext.createObjectBindingOrAssignmentPattern(bindingElements), value, location, pattern); + bindingElements = undefined; + } + var rhsValue = createDestructuringPropertyAccess(flattenContext, value, propertyName); + if (ts.isComputedPropertyName(propertyName)) { + computedTempVariables = ts.append(computedTempVariables, rhsValue.argumentExpression); + } + flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, /*location*/ element); + } + } + else if (i === numElements - 1) { + if (bindingElements) { + flattenContext.emitBindingOrAssignment(flattenContext.createObjectBindingOrAssignmentPattern(bindingElements), value, location, pattern); + bindingElements = undefined; + } + var rhsValue = createRestCall(flattenContext.context, value, elements, computedTempVariables, pattern); // TODO: GH#18217 + flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, element); + } + } + if (bindingElements) { + flattenContext.emitBindingOrAssignment(flattenContext.createObjectBindingOrAssignmentPattern(bindingElements), value, location, pattern); + } + } + /** + * Flattens an ArrayBindingOrAssignmentPattern into zero or more bindings or assignments. + * + * @param flattenContext Options used to control flattening. + * @param parent The parent element of the pattern. + * @param pattern The ArrayBindingOrAssignmentPattern to flatten. + * @param value The current RHS value to assign to the element. + * @param location The location to use for source maps and comments. + */ + function flattenArrayBindingOrAssignmentPattern(flattenContext, parent, pattern, value, location) { + var elements = ts.getElementsOfBindingOrAssignmentPattern(pattern); + var numElements = elements.length; + if (flattenContext.level < 1 /* ObjectRest */ && flattenContext.downlevelIteration) { + // Read the elements of the iterable into an array + value = ensureIdentifier(flattenContext, ts.createReadHelper(flattenContext.context, value, numElements > 0 && ts.getRestIndicatorOfBindingOrAssignmentElement(elements[numElements - 1]) + ? undefined + : numElements, location), + /*reuseIdentifierExpressions*/ false, location); + } + else if (numElements !== 1 && (flattenContext.level < 1 /* ObjectRest */ || numElements === 0) + || ts.every(elements, ts.isOmittedExpression)) { + // For anything other than a single-element destructuring we need to generate a temporary + // to ensure value is evaluated exactly once. Additionally, if we have zero elements + // we need to emit *something* to ensure that in case a 'var' keyword was already emitted, + // so in that case, we'll intentionally create that temporary. + // Or all the elements of the binding pattern are omitted expression such as "var [,] = [1,2]", + // then we will create temporary variable. + var reuseIdentifierExpressions = !ts.isDeclarationBindingElement(parent) || numElements !== 0; + value = ensureIdentifier(flattenContext, value, reuseIdentifierExpressions, location); + } + var bindingElements; + var restContainingElements; + for (var i = 0; i < numElements; i++) { + var element = elements[i]; + if (flattenContext.level >= 1 /* ObjectRest */) { + // If an array pattern contains an ObjectRest, we must cache the result so that we + // can perform the ObjectRest destructuring in a different declaration + if (element.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { + var temp = ts.createTempVariable(/*recordTempVariable*/ undefined); + if (flattenContext.hoistTempVariables) { + flattenContext.context.hoistVariableDeclaration(temp); + } + restContainingElements = ts.append(restContainingElements, [temp, element]); + bindingElements = ts.append(bindingElements, flattenContext.createArrayBindingOrAssignmentElement(temp)); + } + else { + bindingElements = ts.append(bindingElements, element); + } + } + else if (ts.isOmittedExpression(element)) { + continue; + } + else if (!ts.getRestIndicatorOfBindingOrAssignmentElement(element)) { + var rhsValue = ts.createElementAccess(value, i); + flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, /*location*/ element); + } + else if (i === numElements - 1) { + var rhsValue = ts.createArraySlice(value, i); + flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, /*location*/ element); + } + } + if (bindingElements) { + flattenContext.emitBindingOrAssignment(flattenContext.createArrayBindingOrAssignmentPattern(bindingElements), value, location, pattern); + } + if (restContainingElements) { + for (var _i = 0, restContainingElements_1 = restContainingElements; _i < restContainingElements_1.length; _i++) { + var _a = restContainingElements_1[_i], id = _a[0], element = _a[1]; + flattenBindingOrAssignmentElement(flattenContext, element, id, element); + } + } + } + /** + * Creates an expression used to provide a default value if a value is `undefined` at runtime. + * + * @param flattenContext Options used to control flattening. + * @param value The RHS value to test. + * @param defaultValue The default value to use if `value` is `undefined` at runtime. + * @param location The location to use for source maps and comments. + */ + function createDefaultValueCheck(flattenContext, value, defaultValue, location) { + value = ensureIdentifier(flattenContext, value, /*reuseIdentifierExpressions*/ true, location); + return ts.createConditional(ts.createTypeCheck(value, "undefined"), defaultValue, value); + } + /** + * Creates either a PropertyAccessExpression or an ElementAccessExpression for the + * right-hand side of a transformed destructuring assignment. + * + * @link https://tc39.github.io/ecma262/#sec-runtime-semantics-keyeddestructuringassignmentevaluation + * + * @param flattenContext Options used to control flattening. + * @param value The RHS value that is the source of the property. + * @param propertyName The destructuring property name. + */ + function createDestructuringPropertyAccess(flattenContext, value, propertyName) { + if (ts.isComputedPropertyName(propertyName)) { + var argumentExpression = ensureIdentifier(flattenContext, ts.visitNode(propertyName.expression, flattenContext.visitor), /*reuseIdentifierExpressions*/ false, /*location*/ propertyName); + return ts.createElementAccess(value, argumentExpression); + } + else if (ts.isStringOrNumericLiteralLike(propertyName)) { + var argumentExpression = ts.getSynthesizedClone(propertyName); + argumentExpression.text = argumentExpression.text; + return ts.createElementAccess(value, argumentExpression); + } + else { + var name = ts.createIdentifier(ts.idText(propertyName)); + return ts.createPropertyAccess(value, name); + } + } + /** + * Ensures that there exists a declared identifier whose value holds the given expression. + * This function is useful to ensure that the expression's value can be read from in subsequent expressions. + * Unless 'reuseIdentifierExpressions' is false, 'value' will be returned if it is just an identifier. + * + * @param flattenContext Options used to control flattening. + * @param value the expression whose value needs to be bound. + * @param reuseIdentifierExpressions true if identifier expressions can simply be returned; + * false if it is necessary to always emit an identifier. + * @param location The location to use for source maps and comments. + */ + function ensureIdentifier(flattenContext, value, reuseIdentifierExpressions, location) { + if (ts.isIdentifier(value) && reuseIdentifierExpressions) { + return value; + } + else { + var temp = ts.createTempVariable(/*recordTempVariable*/ undefined); + if (flattenContext.hoistTempVariables) { + flattenContext.context.hoistVariableDeclaration(temp); + flattenContext.emitExpression(ts.setTextRange(ts.createAssignment(temp, value), location)); + } + else { + flattenContext.emitBindingOrAssignment(temp, value, location, /*original*/ undefined); + } + return temp; + } + } + function makeArrayBindingPattern(elements) { + ts.Debug.assertEachNode(elements, ts.isArrayBindingElement); + return ts.createArrayBindingPattern(elements); + } + function makeArrayAssignmentPattern(elements) { + return ts.createArrayLiteral(ts.map(elements, ts.convertToArrayAssignmentElement)); + } + function makeObjectBindingPattern(elements) { + ts.Debug.assertEachNode(elements, ts.isBindingElement); + return ts.createObjectBindingPattern(elements); + } + function makeObjectAssignmentPattern(elements) { + return ts.createObjectLiteral(ts.map(elements, ts.convertToObjectAssignmentElement)); + } + function makeBindingElement(name) { + return ts.createBindingElement(/*dotDotDotToken*/ undefined, /*propertyName*/ undefined, name); + } + function makeAssignmentElement(name) { + return name; + } + var restHelper = { + name: "typescript:rest", + scoped: false, + text: "\n var __rest = (this && this.__rest) || function (s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) if (e.indexOf(p[i]) < 0)\n t[p[i]] = s[p[i]];\n return t;\n };" + }; + /** Given value: o, propName: p, pattern: { a, b, ...p } from the original statement + * `{ a, b, ...p } = o`, create `p = __rest(o, ["a", "b"]);` + */ + function createRestCall(context, value, elements, computedTempVariables, location) { + context.requestEmitHelper(restHelper); + var propertyNames = []; + var computedTempVariableOffset = 0; + for (var i = 0; i < elements.length - 1; i++) { + var propertyName = ts.getPropertyNameOfBindingOrAssignmentElement(elements[i]); + if (propertyName) { + if (ts.isComputedPropertyName(propertyName)) { + var temp = computedTempVariables[computedTempVariableOffset]; + computedTempVariableOffset++; + // typeof _tmp === "symbol" ? _tmp : _tmp + "" + propertyNames.push(ts.createConditional(ts.createTypeCheck(temp, "symbol"), temp, ts.createAdd(temp, ts.createLiteral("")))); + } + else { + propertyNames.push(ts.createLiteral(propertyName)); + } + } + } + return ts.createCall(ts.getHelperName("__rest"), + /*typeArguments*/ undefined, [ + value, + ts.setTextRange(ts.createArrayLiteral(propertyNames), location) + ]); + } +})(ts || (ts = {})); +/*@internal*/ +var ts; +(function (ts) { + /** + * Indicates whether to emit type metadata in the new format. + */ + var USE_NEW_TYPE_METADATA_FORMAT = false; + var TypeScriptSubstitutionFlags; + (function (TypeScriptSubstitutionFlags) { + /** Enables substitutions for decorated classes. */ + TypeScriptSubstitutionFlags[TypeScriptSubstitutionFlags["ClassAliases"] = 1] = "ClassAliases"; + /** Enables substitutions for namespace exports. */ + TypeScriptSubstitutionFlags[TypeScriptSubstitutionFlags["NamespaceExports"] = 2] = "NamespaceExports"; + /* Enables substitutions for unqualified enum members */ + TypeScriptSubstitutionFlags[TypeScriptSubstitutionFlags["NonQualifiedEnumMembers"] = 8] = "NonQualifiedEnumMembers"; + })(TypeScriptSubstitutionFlags || (TypeScriptSubstitutionFlags = {})); + var ClassFacts; + (function (ClassFacts) { + ClassFacts[ClassFacts["None"] = 0] = "None"; + ClassFacts[ClassFacts["HasStaticInitializedProperties"] = 1] = "HasStaticInitializedProperties"; + ClassFacts[ClassFacts["HasConstructorDecorators"] = 2] = "HasConstructorDecorators"; + ClassFacts[ClassFacts["HasMemberDecorators"] = 4] = "HasMemberDecorators"; + ClassFacts[ClassFacts["IsExportOfNamespace"] = 8] = "IsExportOfNamespace"; + ClassFacts[ClassFacts["IsNamedExternalExport"] = 16] = "IsNamedExternalExport"; + ClassFacts[ClassFacts["IsDefaultExternalExport"] = 32] = "IsDefaultExternalExport"; + ClassFacts[ClassFacts["IsDerivedClass"] = 64] = "IsDerivedClass"; + ClassFacts[ClassFacts["UseImmediatelyInvokedFunctionExpression"] = 128] = "UseImmediatelyInvokedFunctionExpression"; + ClassFacts[ClassFacts["HasAnyDecorators"] = 6] = "HasAnyDecorators"; + ClassFacts[ClassFacts["NeedsName"] = 5] = "NeedsName"; + ClassFacts[ClassFacts["MayNeedImmediatelyInvokedFunctionExpression"] = 7] = "MayNeedImmediatelyInvokedFunctionExpression"; + ClassFacts[ClassFacts["IsExported"] = 56] = "IsExported"; + })(ClassFacts || (ClassFacts = {})); + function transformTypeScript(context) { + var startLexicalEnvironment = context.startLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; + var resolver = context.getEmitResolver(); + var compilerOptions = context.getCompilerOptions(); + var strictNullChecks = ts.getStrictOptionValue(compilerOptions, "strictNullChecks"); + var languageVersion = ts.getEmitScriptTarget(compilerOptions); + var moduleKind = ts.getEmitModuleKind(compilerOptions); + // Save the previous transformation hooks. + var previousOnEmitNode = context.onEmitNode; + var previousOnSubstituteNode = context.onSubstituteNode; + // Set new transformation hooks. + context.onEmitNode = onEmitNode; + context.onSubstituteNode = onSubstituteNode; + // Enable substitution for property/element access to emit const enum values. + context.enableSubstitution(189 /* PropertyAccessExpression */); + context.enableSubstitution(190 /* ElementAccessExpression */); + // These variables contain state that changes as we descend into the tree. + var currentSourceFile; + var currentNamespace; + var currentNamespaceContainerName; + var currentLexicalScope; + var currentNameScope; + var currentScopeFirstDeclarationsOfName; + /** + * Keeps track of whether expression substitution has been enabled for specific edge cases. + * They are persisted between each SourceFile transformation and should not be reset. + */ + var enabledSubstitutions; + /** + * A map that keeps track of aliases created for classes with decorators to avoid issues + * with the double-binding behavior of classes. + */ + var classAliases; + /** + * Keeps track of whether we are within any containing namespaces when performing + * just-in-time substitution while printing an expression identifier. + */ + var applicableSubstitutions; + /** + * Tracks what computed name expressions originating from elided names must be inlined + * at the next execution site, in document order + */ + var pendingExpressions; + return transformSourceFileOrBundle; + function transformSourceFileOrBundle(node) { + if (node.kind === 280 /* Bundle */) { + return transformBundle(node); + } + return transformSourceFile(node); + } + function transformBundle(node) { + return ts.createBundle(node.sourceFiles.map(transformSourceFile), ts.mapDefined(node.prepends, function (prepend) { + if (prepend.kind === 282 /* InputFiles */) { + return ts.createUnparsedSourceFile(prepend.javascriptText, prepend.javascriptMapPath, prepend.javascriptMapText); + } + return prepend; + })); + } + /** + * Transform TypeScript-specific syntax in a SourceFile. + * + * @param node A SourceFile node. + */ + function transformSourceFile(node) { + if (node.isDeclarationFile) { + return node; + } + currentSourceFile = node; + var visited = saveStateAndInvoke(node, visitSourceFile); + ts.addEmitHelpers(visited, context.readEmitHelpers()); + currentSourceFile = undefined; + return visited; + } + /** + * Visits a node, saving and restoring state variables on the stack. + * + * @param node The node to visit. + */ + function saveStateAndInvoke(node, f) { + // Save state + var savedCurrentScope = currentLexicalScope; + var savedCurrentNameScope = currentNameScope; + var savedCurrentScopeFirstDeclarationsOfName = currentScopeFirstDeclarationsOfName; + // Handle state changes before visiting a node. + onBeforeVisitNode(node); + var visited = f(node); + // Restore state + if (currentLexicalScope !== savedCurrentScope) { + currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName; + } + currentLexicalScope = savedCurrentScope; + currentNameScope = savedCurrentNameScope; + return visited; + } + /** + * Performs actions that should always occur immediately before visiting a node. + * + * @param node The node to visit. + */ + function onBeforeVisitNode(node) { + switch (node.kind) { + case 279 /* SourceFile */: + case 246 /* CaseBlock */: + case 245 /* ModuleBlock */: + case 218 /* Block */: + currentLexicalScope = node; + currentNameScope = undefined; + currentScopeFirstDeclarationsOfName = undefined; + break; + case 240 /* ClassDeclaration */: + case 239 /* FunctionDeclaration */: + if (ts.hasModifier(node, 2 /* Ambient */)) { + break; + } + // Record these declarations provided that they have a name. + if (node.name) { + recordEmittedDeclarationInScope(node); + } + else { + // These nodes should always have names unless they are default-exports; + // however, class declaration parsing allows for undefined names, so syntactically invalid + // programs may also have an undefined name. + ts.Debug.assert(node.kind === 240 /* ClassDeclaration */ || ts.hasModifier(node, 512 /* Default */)); + } + if (ts.isClassDeclaration(node)) { + // XXX: should probably also cover interfaces and type aliases that can have type variables? + currentNameScope = node; + } + break; + } + } + /** + * General-purpose node visitor. + * + * @param node The node to visit. + */ + function visitor(node) { + return saveStateAndInvoke(node, visitorWorker); + } + /** + * Visits and possibly transforms any node. + * + * @param node The node to visit. + */ + function visitorWorker(node) { + if (node.transformFlags & 1 /* TypeScript */) { + // This node is explicitly marked as TypeScript, so we should transform the node. + return visitTypeScript(node); + } + else if (node.transformFlags & 2 /* ContainsTypeScript */) { + // This node contains TypeScript, so we should visit its children. + return ts.visitEachChild(node, visitor, context); + } + return node; + } + /** + * Specialized visitor that visits the immediate children of a SourceFile. + * + * @param node The node to visit. + */ + function sourceElementVisitor(node) { + return saveStateAndInvoke(node, sourceElementVisitorWorker); + } + /** + * Specialized visitor that visits the immediate children of a SourceFile. + * + * @param node The node to visit. + */ + function sourceElementVisitorWorker(node) { + switch (node.kind) { + case 249 /* ImportDeclaration */: + case 248 /* ImportEqualsDeclaration */: + case 254 /* ExportAssignment */: + case 255 /* ExportDeclaration */: + return visitEllidableStatement(node); + default: + return visitorWorker(node); + } + } + function visitEllidableStatement(node) { + var parsed = ts.getParseTreeNode(node); + if (parsed !== node) { + // If the node has been transformed by a `before` transformer, perform no ellision on it + // As the type information we would attempt to lookup to perform ellision is potentially unavailable for the synthesized nodes + // We do not reuse `visitorWorker`, as the ellidable statement syntax kinds are technically unrecognized by the switch-case in `visitTypeScript`, + // and will trigger debug failures when debug verbosity is turned up + if (node.transformFlags & 2 /* ContainsTypeScript */) { + // This node contains TypeScript, so we should visit its children. + return ts.visitEachChild(node, visitor, context); + } + // Otherwise, we can just return the node + return node; + } + switch (node.kind) { + case 249 /* ImportDeclaration */: + return visitImportDeclaration(node); + case 248 /* ImportEqualsDeclaration */: + return visitImportEqualsDeclaration(node); + case 254 /* ExportAssignment */: + return visitExportAssignment(node); + case 255 /* ExportDeclaration */: + return visitExportDeclaration(node); + default: + ts.Debug.fail("Unhandled ellided statement"); + } + } + /** + * Specialized visitor that visits the immediate children of a namespace. + * + * @param node The node to visit. + */ + function namespaceElementVisitor(node) { + return saveStateAndInvoke(node, namespaceElementVisitorWorker); + } + /** + * Specialized visitor that visits the immediate children of a namespace. + * + * @param node The node to visit. + */ + function namespaceElementVisitorWorker(node) { + if (node.kind === 255 /* ExportDeclaration */ || + node.kind === 249 /* ImportDeclaration */ || + node.kind === 250 /* ImportClause */ || + (node.kind === 248 /* ImportEqualsDeclaration */ && + node.moduleReference.kind === 259 /* ExternalModuleReference */)) { + // do not emit ES6 imports and exports since they are illegal inside a namespace + return undefined; + } + else if (node.transformFlags & 1 /* TypeScript */ || ts.hasModifier(node, 1 /* Export */)) { + // This node is explicitly marked as TypeScript, or is exported at the namespace + // level, so we should transform the node. + return visitTypeScript(node); + } + else if (node.transformFlags & 2 /* ContainsTypeScript */) { + // This node contains TypeScript, so we should visit its children. + return ts.visitEachChild(node, visitor, context); + } + return node; + } + /** + * Specialized visitor that visits the immediate children of a class with TypeScript syntax. + * + * @param node The node to visit. + */ + function classElementVisitor(node) { + return saveStateAndInvoke(node, classElementVisitorWorker); + } + /** + * Specialized visitor that visits the immediate children of a class with TypeScript syntax. + * + * @param node The node to visit. + */ + function classElementVisitorWorker(node) { + switch (node.kind) { + case 157 /* Constructor */: + // TypeScript constructors are transformed in `visitClassDeclaration`. + // We elide them here as `visitorWorker` checks transform flags, which could + // erronously include an ES6 constructor without TypeScript syntax. + return undefined; + case 154 /* PropertyDeclaration */: + case 162 /* IndexSignature */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 156 /* MethodDeclaration */: + // Fallback to the default visit behavior. + return visitorWorker(node); + case 217 /* SemicolonClassElement */: + return node; + default: + return ts.Debug.failBadSyntaxKind(node); + } + } + function modifierVisitor(node) { + if (ts.modifierToFlag(node.kind) & 2270 /* TypeScriptModifier */) { + return undefined; + } + else if (currentNamespace && node.kind === 85 /* ExportKeyword */) { + return undefined; + } + return node; + } + /** + * Branching visitor, visits a TypeScript syntax node. + * + * @param node The node to visit. + */ + function visitTypeScript(node) { + if (ts.hasModifier(node, 2 /* Ambient */) && ts.isStatement(node)) { + // TypeScript ambient declarations are elided, but some comments may be preserved. + // See the implementation of `getLeadingComments` in comments.ts for more details. + return ts.createNotEmittedStatement(node); + } + switch (node.kind) { + case 85 /* ExportKeyword */: + case 80 /* DefaultKeyword */: + // ES6 export and default modifiers are elided when inside a namespace. + return currentNamespace ? undefined : node; + case 115 /* PublicKeyword */: + case 113 /* PrivateKeyword */: + case 114 /* ProtectedKeyword */: + case 118 /* AbstractKeyword */: + case 77 /* ConstKeyword */: + case 125 /* DeclareKeyword */: + case 133 /* ReadonlyKeyword */: + // TypeScript accessibility and readonly modifiers are elided. + case 169 /* ArrayType */: + case 170 /* TupleType */: + case 171 /* OptionalType */: + case 172 /* RestType */: + case 168 /* TypeLiteral */: + case 163 /* TypePredicate */: + case 150 /* TypeParameter */: + case 120 /* AnyKeyword */: + case 143 /* UnknownKeyword */: + case 123 /* BooleanKeyword */: + case 138 /* StringKeyword */: + case 135 /* NumberKeyword */: + case 132 /* NeverKeyword */: + case 106 /* VoidKeyword */: + case 139 /* SymbolKeyword */: + case 166 /* ConstructorType */: + case 165 /* FunctionType */: + case 167 /* TypeQuery */: + case 164 /* TypeReference */: + case 173 /* UnionType */: + case 174 /* IntersectionType */: + case 175 /* ConditionalType */: + case 177 /* ParenthesizedType */: + case 178 /* ThisType */: + case 179 /* TypeOperator */: + case 180 /* IndexedAccessType */: + case 181 /* MappedType */: + case 182 /* LiteralType */: + // TypeScript type nodes are elided. + case 162 /* IndexSignature */: + // TypeScript index signatures are elided. + case 152 /* Decorator */: + // TypeScript decorators are elided. They will be emitted as part of visitClassDeclaration. + case 242 /* TypeAliasDeclaration */: + // TypeScript type-only declarations are elided. + return undefined; + case 154 /* PropertyDeclaration */: + // TypeScript property declarations are elided. However their names are still visited, and can potentially be retained if they could have sideeffects + return visitPropertyDeclaration(node); + case 247 /* NamespaceExportDeclaration */: + // TypeScript namespace export declarations are elided. + return undefined; + case 157 /* Constructor */: + return visitConstructor(node); + case 241 /* InterfaceDeclaration */: + // TypeScript interfaces are elided, but some comments may be preserved. + // See the implementation of `getLeadingComments` in comments.ts for more details. + return ts.createNotEmittedStatement(node); + case 240 /* ClassDeclaration */: + // This is a class declaration with TypeScript syntax extensions. + // + // TypeScript class syntax extensions include: + // - decorators + // - optional `implements` heritage clause + // - parameter property assignments in the constructor + // - property declarations + // - index signatures + // - method overload signatures + return visitClassDeclaration(node); + case 209 /* ClassExpression */: + // This is a class expression with TypeScript syntax extensions. + // + // TypeScript class syntax extensions include: + // - decorators + // - optional `implements` heritage clause + // - parameter property assignments in the constructor + // - property declarations + // - index signatures + // - method overload signatures + return visitClassExpression(node); + case 273 /* HeritageClause */: + // This is a heritage clause with TypeScript syntax extensions. + // + // TypeScript heritage clause extensions include: + // - `implements` clause + return visitHeritageClause(node); + case 211 /* ExpressionWithTypeArguments */: + // TypeScript supports type arguments on an expression in an `extends` heritage clause. + return visitExpressionWithTypeArguments(node); + case 156 /* MethodDeclaration */: + // TypeScript method declarations may have decorators, modifiers + // or type annotations. + return visitMethodDeclaration(node); + case 158 /* GetAccessor */: + // Get Accessors can have TypeScript modifiers, decorators, and type annotations. + return visitGetAccessor(node); + case 159 /* SetAccessor */: + // Set Accessors can have TypeScript modifiers and type annotations. + return visitSetAccessor(node); + case 239 /* FunctionDeclaration */: + // Typescript function declarations can have modifiers, decorators, and type annotations. + return visitFunctionDeclaration(node); + case 196 /* FunctionExpression */: + // TypeScript function expressions can have modifiers and type annotations. + return visitFunctionExpression(node); + case 197 /* ArrowFunction */: + // TypeScript arrow functions can have modifiers and type annotations. + return visitArrowFunction(node); + case 151 /* Parameter */: + // This is a parameter declaration with TypeScript syntax extensions. + // + // TypeScript parameter declaration syntax extensions include: + // - decorators + // - accessibility modifiers + // - the question mark (?) token for optional parameters + // - type annotations + // - this parameters + return visitParameter(node); + case 195 /* ParenthesizedExpression */: + // ParenthesizedExpressions are TypeScript if their expression is a + // TypeAssertion or AsExpression + return visitParenthesizedExpression(node); + case 194 /* TypeAssertionExpression */: + case 212 /* AsExpression */: + // TypeScript type assertions are removed, but their subtrees are preserved. + return visitAssertionExpression(node); + case 191 /* CallExpression */: + return visitCallExpression(node); + case 192 /* NewExpression */: + return visitNewExpression(node); + case 193 /* TaggedTemplateExpression */: + return visitTaggedTemplateExpression(node); + case 213 /* NonNullExpression */: + // TypeScript non-null expressions are removed, but their subtrees are preserved. + return visitNonNullExpression(node); + case 243 /* EnumDeclaration */: + // TypeScript enum declarations do not exist in ES6 and must be rewritten. + return visitEnumDeclaration(node); + case 219 /* VariableStatement */: + // TypeScript namespace exports for variable statements must be transformed. + return visitVariableStatement(node); + case 237 /* VariableDeclaration */: + return visitVariableDeclaration(node); + case 244 /* ModuleDeclaration */: + // TypeScript namespace declarations must be transformed. + return visitModuleDeclaration(node); + case 248 /* ImportEqualsDeclaration */: + // TypeScript namespace or external module import. + return visitImportEqualsDeclaration(node); + default: + return ts.Debug.failBadSyntaxKind(node); + } + } + function visitSourceFile(node) { + var alwaysStrict = ts.getStrictOptionValue(compilerOptions, "alwaysStrict") && + !(ts.isExternalModule(node) && moduleKind >= ts.ModuleKind.ES2015) && + !ts.isJsonSourceFile(node); + return ts.updateSourceFileNode(node, ts.visitLexicalEnvironment(node.statements, sourceElementVisitor, context, /*start*/ 0, alwaysStrict)); + } + /** + * Tests whether we should emit a __decorate call for a class declaration. + */ + function shouldEmitDecorateCallForClass(node) { + if (node.decorators && node.decorators.length > 0) { + return true; + } + var constructor = ts.getFirstConstructorWithBody(node); + if (constructor) { + return ts.forEach(constructor.parameters, shouldEmitDecorateCallForParameter); + } + return false; + } + /** + * Tests whether we should emit a __decorate call for a parameter declaration. + */ + function shouldEmitDecorateCallForParameter(parameter) { + return parameter.decorators !== undefined && parameter.decorators.length > 0; + } + function getClassFacts(node, staticProperties) { + var facts = 0 /* None */; + if (ts.some(staticProperties)) + facts |= 1 /* HasStaticInitializedProperties */; + var extendsClauseElement = ts.getEffectiveBaseTypeNode(node); + if (extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 96 /* NullKeyword */) + facts |= 64 /* IsDerivedClass */; + if (shouldEmitDecorateCallForClass(node)) + facts |= 2 /* HasConstructorDecorators */; + if (ts.childIsDecorated(node)) + facts |= 4 /* HasMemberDecorators */; + if (isExportOfNamespace(node)) + facts |= 8 /* IsExportOfNamespace */; + else if (isDefaultExternalModuleExport(node)) + facts |= 32 /* IsDefaultExternalExport */; + else if (isNamedExternalModuleExport(node)) + facts |= 16 /* IsNamedExternalExport */; + if (languageVersion <= 1 /* ES5 */ && (facts & 7 /* MayNeedImmediatelyInvokedFunctionExpression */)) + facts |= 128 /* UseImmediatelyInvokedFunctionExpression */; + return facts; + } + /** + * Transforms a class declaration with TypeScript syntax into compatible ES6. + * + * This function will only be called when one of the following conditions are met: + * - The class has decorators. + * - The class has property declarations with initializers. + * - The class contains a constructor that contains parameters with accessibility modifiers. + * - The class is an export in a TypeScript namespace. + * + * @param node The node to transform. + */ + function visitClassDeclaration(node) { + var savedPendingExpressions = pendingExpressions; + pendingExpressions = undefined; + var staticProperties = getInitializedProperties(node, /*isStatic*/ true); + var facts = getClassFacts(node, staticProperties); + if (facts & 128 /* UseImmediatelyInvokedFunctionExpression */) { + context.startLexicalEnvironment(); + } + var name = node.name || (facts & 5 /* NeedsName */ ? ts.getGeneratedNameForNode(node) : undefined); + var classStatement = facts & 2 /* HasConstructorDecorators */ + ? createClassDeclarationHeadWithDecorators(node, name, facts) + : createClassDeclarationHeadWithoutDecorators(node, name, facts); + var statements = [classStatement]; + // Write any pending expressions from elided or moved computed property names + if (ts.some(pendingExpressions)) { + statements.push(ts.createExpressionStatement(ts.inlineExpressions(pendingExpressions))); + } + pendingExpressions = savedPendingExpressions; + // Emit static property assignment. Because classDeclaration is lexically evaluated, + // it is safe to emit static property assignment after classDeclaration + // From ES6 specification: + // HasLexicalDeclaration (N) : Determines if the argument identifier has a binding in this environment record that was created using + // a lexical declaration such as a LexicalDeclaration or a ClassDeclaration. + if (facts & 1 /* HasStaticInitializedProperties */) { + addInitializedPropertyStatements(statements, staticProperties, facts & 128 /* UseImmediatelyInvokedFunctionExpression */ ? ts.getInternalName(node) : ts.getLocalName(node)); + } + // Write any decorators of the node. + addClassElementDecorationStatements(statements, node, /*isStatic*/ false); + addClassElementDecorationStatements(statements, node, /*isStatic*/ true); + addConstructorDecorationStatement(statements, node); + if (facts & 128 /* UseImmediatelyInvokedFunctionExpression */) { + // When we emit a TypeScript class down to ES5, we must wrap it in an IIFE so that the + // 'es2015' transformer can properly nest static initializers and decorators. The result + // looks something like: + // + // var C = function () { + // class C { + // } + // C.static_prop = 1; + // return C; + // }(); + // + var closingBraceLocation = ts.createTokenRange(ts.skipTrivia(currentSourceFile.text, node.members.end), 19 /* CloseBraceToken */); + var localName = ts.getInternalName(node); + // The following partially-emitted expression exists purely to align our sourcemap + // emit with the original emitter. + var outer = ts.createPartiallyEmittedExpression(localName); + outer.end = closingBraceLocation.end; + ts.setEmitFlags(outer, 1536 /* NoComments */); + var statement = ts.createReturn(outer); + statement.pos = closingBraceLocation.pos; + ts.setEmitFlags(statement, 1536 /* NoComments */ | 384 /* NoTokenSourceMaps */); + statements.push(statement); + ts.addStatementsAfterPrologue(statements, context.endLexicalEnvironment()); + var iife = ts.createImmediatelyInvokedArrowFunction(statements); + ts.setEmitFlags(iife, 33554432 /* TypeScriptClassWrapper */); + var varStatement = ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ false), + /*type*/ undefined, iife) + ])); + ts.setOriginalNode(varStatement, node); + ts.setCommentRange(varStatement, node); + ts.setSourceMapRange(varStatement, ts.moveRangePastDecorators(node)); + ts.startOnNewLine(varStatement); + statements = [varStatement]; + } + // If the class is exported as part of a TypeScript namespace, emit the namespace export. + // Otherwise, if the class was exported at the top level and was decorated, emit an export + // declaration or export default for the class. + if (facts & 8 /* IsExportOfNamespace */) { + addExportMemberAssignment(statements, node); + } + else if (facts & 128 /* UseImmediatelyInvokedFunctionExpression */ || facts & 2 /* HasConstructorDecorators */) { + if (facts & 32 /* IsDefaultExternalExport */) { + statements.push(ts.createExportDefault(ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true))); + } + else if (facts & 16 /* IsNamedExternalExport */) { + statements.push(ts.createExternalModuleExport(ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true))); + } + } + if (statements.length > 1) { + // Add a DeclarationMarker as a marker for the end of the declaration + statements.push(ts.createEndOfDeclarationMarker(node)); + ts.setEmitFlags(classStatement, ts.getEmitFlags(classStatement) | 4194304 /* HasEndOfDeclarationMarker */); + } + return ts.singleOrMany(statements); + } + /** + * Transforms a non-decorated class declaration and appends the resulting statements. + * + * @param node A ClassDeclaration node. + * @param name The name of the class. + * @param facts Precomputed facts about the class. + */ + function createClassDeclarationHeadWithoutDecorators(node, name, facts) { + // ${modifiers} class ${name} ${heritageClauses} { + // ${members} + // } + // we do not emit modifiers on the declaration if we are emitting an IIFE + var modifiers = !(facts & 128 /* UseImmediatelyInvokedFunctionExpression */) + ? ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier) + : undefined; + var classDeclaration = ts.createClassDeclaration( + /*decorators*/ undefined, modifiers, name, + /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node, (facts & 64 /* IsDerivedClass */) !== 0)); + // To better align with the old emitter, we should not emit a trailing source map + // entry if the class has static properties. + var emitFlags = ts.getEmitFlags(node); + if (facts & 1 /* HasStaticInitializedProperties */) { + emitFlags |= 32 /* NoTrailingSourceMap */; + } + ts.setTextRange(classDeclaration, node); + ts.setOriginalNode(classDeclaration, node); + ts.setEmitFlags(classDeclaration, emitFlags); + return classDeclaration; + } + /** + * Transforms a decorated class declaration and appends the resulting statements. If + * the class requires an alias to avoid issues with double-binding, the alias is returned. + */ + function createClassDeclarationHeadWithDecorators(node, name, facts) { + // When we emit an ES6 class that has a class decorator, we must tailor the + // emit to certain specific cases. + // + // In the simplest case, we emit the class declaration as a let declaration, and + // evaluate decorators after the close of the class body: + // + // [Example 1] + // --------------------------------------------------------------------- + // TypeScript | Javascript + // --------------------------------------------------------------------- + // @dec | let C = class C { + // class C { | } + // } | C = __decorate([dec], C); + // --------------------------------------------------------------------- + // @dec | let C = class C { + // export class C { | } + // } | C = __decorate([dec], C); + // | export { C }; + // --------------------------------------------------------------------- + // + // If a class declaration contains a reference to itself *inside* of the class body, + // this introduces two bindings to the class: One outside of the class body, and one + // inside of the class body. If we apply decorators as in [Example 1] above, there + // is the possibility that the decorator `dec` will return a new value for the + // constructor, which would result in the binding inside of the class no longer + // pointing to the same reference as the binding outside of the class. + // + // As a result, we must instead rewrite all references to the class *inside* of the + // class body to instead point to a local temporary alias for the class: + // + // [Example 2] + // --------------------------------------------------------------------- + // TypeScript | Javascript + // --------------------------------------------------------------------- + // @dec | let C = C_1 = class C { + // class C { | static x() { return C_1.y; } + // static x() { return C.y; } | } + // static y = 1; | C.y = 1; + // } | C = C_1 = __decorate([dec], C); + // | var C_1; + // --------------------------------------------------------------------- + // @dec | let C = class C { + // export class C { | static x() { return C_1.y; } + // static x() { return C.y; } | } + // static y = 1; | C.y = 1; + // } | C = C_1 = __decorate([dec], C); + // | export { C }; + // | var C_1; + // --------------------------------------------------------------------- + // + // If a class declaration is the default export of a module, we instead emit + // the export after the decorated declaration: + // + // [Example 3] + // --------------------------------------------------------------------- + // TypeScript | Javascript + // --------------------------------------------------------------------- + // @dec | let default_1 = class { + // export default class { | } + // } | default_1 = __decorate([dec], default_1); + // | export default default_1; + // --------------------------------------------------------------------- + // @dec | let C = class C { + // export default class C { | } + // } | C = __decorate([dec], C); + // | export default C; + // --------------------------------------------------------------------- + // + // If the class declaration is the default export and a reference to itself + // inside of the class body, we must emit both an alias for the class *and* + // move the export after the declaration: + // + // [Example 4] + // --------------------------------------------------------------------- + // TypeScript | Javascript + // --------------------------------------------------------------------- + // @dec | let C = class C { + // export default class C { | static x() { return C_1.y; } + // static x() { return C.y; } | } + // static y = 1; | C.y = 1; + // } | C = C_1 = __decorate([dec], C); + // | export default C; + // | var C_1; + // --------------------------------------------------------------------- + // + var location = ts.moveRangePastDecorators(node); + var classAlias = getClassAliasIfNeeded(node); + var declName = ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true); + // ... = class ${name} ${heritageClauses} { + // ${members} + // } + var heritageClauses = ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause); + var members = transformClassMembers(node, (facts & 64 /* IsDerivedClass */) !== 0); + var classExpression = ts.createClassExpression(/*modifiers*/ undefined, name, /*typeParameters*/ undefined, heritageClauses, members); + ts.setOriginalNode(classExpression, node); + ts.setTextRange(classExpression, location); + // let ${name} = ${classExpression} where name is either declaredName if the class doesn't contain self-reference + // or decoratedClassAlias if the class contain self-reference. + var statement = ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(declName, + /*type*/ undefined, classAlias ? ts.createAssignment(classAlias, classExpression) : classExpression) + ], 1 /* Let */)); + ts.setOriginalNode(statement, node); + ts.setTextRange(statement, location); + ts.setCommentRange(statement, node); + return statement; + } + /** + * Transforms a class expression with TypeScript syntax into compatible ES6. + * + * This function will only be called when one of the following conditions are met: + * - The class has property declarations with initializers. + * - The class contains a constructor that contains parameters with accessibility modifiers. + * + * @param node The node to transform. + */ + function visitClassExpression(node) { + var savedPendingExpressions = pendingExpressions; + pendingExpressions = undefined; + var staticProperties = getInitializedProperties(node, /*isStatic*/ true); + var heritageClauses = ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause); + var members = transformClassMembers(node, ts.some(heritageClauses, function (c) { return c.token === 86 /* ExtendsKeyword */; })); + var classExpression = ts.createClassExpression( + /*modifiers*/ undefined, node.name, + /*typeParameters*/ undefined, heritageClauses, members); + ts.setOriginalNode(classExpression, node); + ts.setTextRange(classExpression, node); + if (ts.some(staticProperties) || ts.some(pendingExpressions)) { + var expressions = []; + var isClassWithConstructorReference = resolver.getNodeCheckFlags(node) & 16777216 /* ClassWithConstructorReference */; + var temp = ts.createTempVariable(hoistVariableDeclaration, !!isClassWithConstructorReference); + if (isClassWithConstructorReference) { + // record an alias as the class name is not in scope for statics. + enableSubstitutionForClassAliases(); + var alias = ts.getSynthesizedClone(temp); + alias.autoGenerateFlags &= ~8 /* ReservedInNestedScopes */; + classAliases[ts.getOriginalNodeId(node)] = alias; + } + // To preserve the behavior of the old emitter, we explicitly indent + // the body of a class with static initializers. + ts.setEmitFlags(classExpression, 65536 /* Indented */ | ts.getEmitFlags(classExpression)); + expressions.push(ts.startOnNewLine(ts.createAssignment(temp, classExpression))); + // Add any pending expressions leftover from elided or relocated computed property names + ts.addRange(expressions, ts.map(pendingExpressions, ts.startOnNewLine)); + pendingExpressions = savedPendingExpressions; + ts.addRange(expressions, generateInitializedPropertyExpressions(staticProperties, temp)); + expressions.push(ts.startOnNewLine(temp)); + return ts.inlineExpressions(expressions); + } + pendingExpressions = savedPendingExpressions; + return classExpression; + } + /** + * Transforms the members of a class. + * + * @param node The current class. + * @param isDerivedClass A value indicating whether the class has an extends clause that does not extend 'null'. + */ + function transformClassMembers(node, isDerivedClass) { + var members = []; + var constructor = transformConstructor(node, isDerivedClass); + if (constructor) { + members.push(constructor); + } + ts.addRange(members, ts.visitNodes(node.members, classElementVisitor, ts.isClassElement)); + return ts.setTextRange(ts.createNodeArray(members), /*location*/ node.members); + } + /** + * Transforms (or creates) a constructor for a class. + * + * @param node The current class. + * @param isDerivedClass A value indicating whether the class has an extends clause that does not extend 'null'. + */ + function transformConstructor(node, isDerivedClass) { + // Check if we have property assignment inside class declaration. + // If there is a property assignment, we need to emit constructor whether users define it or not + // If there is no property assignment, we can omit constructor if users do not define it + var constructor = ts.getFirstConstructorWithBody(node); + var hasInstancePropertyWithInitializer = ts.forEach(node.members, isInstanceInitializedProperty); + var hasParameterPropertyAssignments = constructor && + constructor.transformFlags & 4096 /* ContainsTypeScriptClassSyntax */ && + ts.forEach(constructor.parameters, isParameterWithPropertyAssignment); + // If the class does not contain nodes that require a synthesized constructor, + // accept the current constructor if it exists. + if (!hasInstancePropertyWithInitializer && !hasParameterPropertyAssignments) { + return ts.visitEachChild(constructor, visitor, context); + } + var parameters = transformConstructorParameters(constructor); + var body = transformConstructorBody(node, constructor, isDerivedClass); + // constructor(${parameters}) { + // ${body} + // } + return ts.startOnNewLine(ts.setOriginalNode(ts.setTextRange(ts.createConstructor( + /*decorators*/ undefined, + /*modifiers*/ undefined, parameters, body), constructor || node), constructor)); + } + /** + * Transforms (or creates) the parameters for the constructor of a class with + * parameter property assignments or instance property initializers. + * + * @param constructor The constructor declaration. + */ + function transformConstructorParameters(constructor) { + // The ES2015 spec specifies in 14.5.14. Runtime Semantics: ClassDefinitionEvaluation: + // If constructor is empty, then + // If ClassHeritag_eopt is present and protoParent is not null, then + // Let constructor be the result of parsing the source text + // constructor(...args) { super (...args);} + // using the syntactic grammar with the goal symbol MethodDefinition[~Yield]. + // Else, + // Let constructor be the result of parsing the source text + // constructor( ){ } + // using the syntactic grammar with the goal symbol MethodDefinition[~Yield]. + // + // While we could emit the '...args' rest parameter, certain later tools in the pipeline might + // downlevel the '...args' portion less efficiently by naively copying the contents of 'arguments' to an array. + // Instead, we'll avoid using a rest parameter and spread into the super call as + // 'super(...arguments)' instead of 'super(...args)', as you can see in "transformConstructorBody". + return ts.visitParameterList(constructor && constructor.parameters, visitor, context) + || []; + } + /** + * Transforms (or creates) a constructor body for a class with parameter property + * assignments or instance property initializers. + * + * @param node The current class. + * @param constructor The current class constructor. + * @param isDerivedClass A value indicating whether the class has an extends clause that does not extend 'null'. + */ + function transformConstructorBody(node, constructor, isDerivedClass) { + var statements = []; + var indexOfFirstStatement = 0; + resumeLexicalEnvironment(); + if (constructor) { + indexOfFirstStatement = addPrologueDirectivesAndInitialSuperCall(constructor, statements); + // Add parameters with property assignments. Transforms this: + // + // constructor (public x, public y) { + // } + // + // Into this: + // + // constructor (x, y) { + // this.x = x; + // this.y = y; + // } + // + var propertyAssignments = getParametersWithPropertyAssignments(constructor); + ts.addRange(statements, ts.map(propertyAssignments, transformParameterWithPropertyAssignment)); + } + else if (isDerivedClass) { + // Add a synthetic `super` call: + // + // super(...arguments); + // + statements.push(ts.createExpressionStatement(ts.createCall(ts.createSuper(), + /*typeArguments*/ undefined, [ts.createSpread(ts.createIdentifier("arguments"))]))); + } + // Add the property initializers. Transforms this: + // + // public x = 1; + // + // Into this: + // + // constructor() { + // this.x = 1; + // } + // + var properties = getInitializedProperties(node, /*isStatic*/ false); + addInitializedPropertyStatements(statements, properties, ts.createThis()); + if (constructor) { + // The class already had a constructor, so we should add the existing statements, skipping the initial super call. + ts.addRange(statements, ts.visitNodes(constructor.body.statements, visitor, ts.isStatement, indexOfFirstStatement)); + } + // End the lexical environment. + statements = ts.mergeLexicalEnvironment(statements, endLexicalEnvironment()); + return ts.setTextRange(ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), + /*location*/ constructor ? constructor.body.statements : node.members), + /*multiLine*/ true), + /*location*/ constructor ? constructor.body : undefined); + } + /** + * Adds super call and preceding prologue directives into the list of statements. + * + * @param ctor The constructor node. + * @returns index of the statement that follows super call + */ + function addPrologueDirectivesAndInitialSuperCall(ctor, result) { + if (ctor.body) { + var statements = ctor.body.statements; + // add prologue directives to the list (if any) + var index = ts.addPrologue(result, statements, /*ensureUseStrict*/ false, visitor); + if (index === statements.length) { + // list contains nothing but prologue directives (or empty) - exit + return index; + } + var statement = statements[index]; + if (statement.kind === 221 /* ExpressionStatement */ && ts.isSuperCall(statement.expression)) { + result.push(ts.visitNode(statement, visitor, ts.isStatement)); + return index + 1; + } + return index; + } + return 0; + } + /** + * Gets all parameters of a constructor that should be transformed into property assignments. + * + * @param node The constructor node. + */ + function getParametersWithPropertyAssignments(node) { + return ts.filter(node.parameters, isParameterWithPropertyAssignment); + } + /** + * Determines whether a parameter should be transformed into a property assignment. + * + * @param parameter The parameter node. + */ + function isParameterWithPropertyAssignment(parameter) { + return ts.hasModifier(parameter, 92 /* ParameterPropertyModifier */) + && ts.isIdentifier(parameter.name); + } + /** + * Transforms a parameter into a property assignment statement. + * + * @param node The parameter declaration. + */ + function transformParameterWithPropertyAssignment(node) { + ts.Debug.assert(ts.isIdentifier(node.name)); + var name = node.name; + var propertyName = ts.getMutableClone(name); + ts.setEmitFlags(propertyName, 1536 /* NoComments */ | 48 /* NoSourceMap */); + var localName = ts.getMutableClone(name); + ts.setEmitFlags(localName, 1536 /* NoComments */); + return ts.startOnNewLine(ts.setEmitFlags(ts.setTextRange(ts.createExpressionStatement(ts.createAssignment(ts.setTextRange(ts.createPropertyAccess(ts.createThis(), propertyName), node.name), localName)), ts.moveRangePos(node, -1)), 1536 /* NoComments */)); + } + /** + * Gets all property declarations with initializers on either the static or instance side of a class. + * + * @param node The class node. + * @param isStatic A value indicating whether to get properties from the static or instance side of the class. + */ + function getInitializedProperties(node, isStatic) { + return ts.filter(node.members, isStatic ? isStaticInitializedProperty : isInstanceInitializedProperty); + } + /** + * Gets a value indicating whether a class element is a static property declaration with an initializer. + * + * @param member The class element node. + */ + function isStaticInitializedProperty(member) { + return isInitializedProperty(member, /*isStatic*/ true); + } + /** + * Gets a value indicating whether a class element is an instance property declaration with an initializer. + * + * @param member The class element node. + */ + function isInstanceInitializedProperty(member) { + return isInitializedProperty(member, /*isStatic*/ false); + } + /** + * Gets a value indicating whether a class element is either a static or an instance property declaration with an initializer. + * + * @param member The class element node. + * @param isStatic A value indicating whether the member should be a static or instance member. + */ + function isInitializedProperty(member, isStatic) { + return member.kind === 154 /* PropertyDeclaration */ + && isStatic === ts.hasModifier(member, 32 /* Static */) + && member.initializer !== undefined; + } + /** + * Generates assignment statements for property initializers. + * + * @param properties An array of property declarations to transform. + * @param receiver The receiver on which each property should be assigned. + */ + function addInitializedPropertyStatements(statements, properties, receiver) { + for (var _i = 0, properties_9 = properties; _i < properties_9.length; _i++) { + var property = properties_9[_i]; + var statement = ts.createExpressionStatement(transformInitializedProperty(property, receiver)); + ts.setSourceMapRange(statement, ts.moveRangePastModifiers(property)); + ts.setCommentRange(statement, property); + ts.setOriginalNode(statement, property); + statements.push(statement); + } + } + /** + * Generates assignment expressions for property initializers. + * + * @param properties An array of property declarations to transform. + * @param receiver The receiver on which each property should be assigned. + */ + function generateInitializedPropertyExpressions(properties, receiver) { + var expressions = []; + for (var _i = 0, properties_10 = properties; _i < properties_10.length; _i++) { + var property = properties_10[_i]; + var expression = transformInitializedProperty(property, receiver); + ts.startOnNewLine(expression); + ts.setSourceMapRange(expression, ts.moveRangePastModifiers(property)); + ts.setCommentRange(expression, property); + ts.setOriginalNode(expression, property); + expressions.push(expression); + } + return expressions; + } + /** + * Transforms a property initializer into an assignment statement. + * + * @param property The property declaration. + * @param receiver The object receiving the property assignment. + */ + function transformInitializedProperty(property, receiver) { + // We generate a name here in order to reuse the value cached by the relocated computed name expression (which uses the same generated name) + var propertyName = ts.isComputedPropertyName(property.name) && !isSimpleInlineableExpression(property.name.expression) + ? ts.updateComputedPropertyName(property.name, ts.getGeneratedNameForNode(property.name)) + : property.name; + var initializer = ts.visitNode(property.initializer, visitor, ts.isExpression); + var memberAccess = ts.createMemberAccessForPropertyName(receiver, propertyName, /*location*/ propertyName); + return ts.createAssignment(memberAccess, initializer); + } + /** + * Gets either the static or instance members of a class that are decorated, or have + * parameters that are decorated. + * + * @param node The class containing the member. + * @param isStatic A value indicating whether to retrieve static or instance members of + * the class. + */ + function getDecoratedClassElements(node, isStatic) { + return ts.filter(node.members, isStatic ? function (m) { return isStaticDecoratedClassElement(m, node); } : function (m) { return isInstanceDecoratedClassElement(m, node); }); + } + /** + * Determines whether a class member is a static member of a class that is decorated, or + * has parameters that are decorated. + * + * @param member The class member. + */ + function isStaticDecoratedClassElement(member, parent) { + return isDecoratedClassElement(member, /*isStatic*/ true, parent); + } + /** + * Determines whether a class member is an instance member of a class that is decorated, + * or has parameters that are decorated. + * + * @param member The class member. + */ + function isInstanceDecoratedClassElement(member, parent) { + return isDecoratedClassElement(member, /*isStatic*/ false, parent); + } + /** + * Determines whether a class member is either a static or an instance member of a class + * that is decorated, or has parameters that are decorated. + * + * @param member The class member. + */ + function isDecoratedClassElement(member, isStatic, parent) { + return ts.nodeOrChildIsDecorated(member, parent) + && isStatic === ts.hasModifier(member, 32 /* Static */); + } + /** + * Gets an array of arrays of decorators for the parameters of a function-like node. + * The offset into the result array should correspond to the offset of the parameter. + * + * @param node The function-like node. + */ + function getDecoratorsOfParameters(node) { + var decorators; + if (node) { + var parameters = node.parameters; + for (var i = 0; i < parameters.length; i++) { + var parameter = parameters[i]; + if (decorators || parameter.decorators) { + if (!decorators) { + decorators = new Array(parameters.length); + } + decorators[i] = parameter.decorators; + } + } + } + return decorators; + } + /** + * Gets an AllDecorators object containing the decorators for the class and the decorators for the + * parameters of the constructor of the class. + * + * @param node The class node. + */ + function getAllDecoratorsOfConstructor(node) { + var decorators = node.decorators; + var parameters = getDecoratorsOfParameters(ts.getFirstConstructorWithBody(node)); + if (!decorators && !parameters) { + return undefined; + } + return { + decorators: decorators, + parameters: parameters + }; + } + /** + * Gets an AllDecorators object containing the decorators for the member and its parameters. + * + * @param node The class node that contains the member. + * @param member The class member. + */ + function getAllDecoratorsOfClassElement(node, member) { + switch (member.kind) { + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + return getAllDecoratorsOfAccessors(node, member); + case 156 /* MethodDeclaration */: + return getAllDecoratorsOfMethod(member); + case 154 /* PropertyDeclaration */: + return getAllDecoratorsOfProperty(member); + default: + return undefined; + } + } + /** + * Gets an AllDecorators object containing the decorators for the accessor and its parameters. + * + * @param node The class node that contains the accessor. + * @param accessor The class accessor member. + */ + function getAllDecoratorsOfAccessors(node, accessor) { + if (!accessor.body) { + return undefined; + } + var _a = ts.getAllAccessorDeclarations(node.members, accessor), firstAccessor = _a.firstAccessor, secondAccessor = _a.secondAccessor, setAccessor = _a.setAccessor; + var firstAccessorWithDecorators = firstAccessor.decorators ? firstAccessor : secondAccessor && secondAccessor.decorators ? secondAccessor : undefined; + if (!firstAccessorWithDecorators || accessor !== firstAccessorWithDecorators) { + return undefined; + } + var decorators = firstAccessorWithDecorators.decorators; + var parameters = getDecoratorsOfParameters(setAccessor); + if (!decorators && !parameters) { + return undefined; + } + return { decorators: decorators, parameters: parameters }; + } + /** + * Gets an AllDecorators object containing the decorators for the method and its parameters. + * + * @param method The class method member. + */ + function getAllDecoratorsOfMethod(method) { + if (!method.body) { + return undefined; + } + var decorators = method.decorators; + var parameters = getDecoratorsOfParameters(method); + if (!decorators && !parameters) { + return undefined; + } + return { decorators: decorators, parameters: parameters }; + } + /** + * Gets an AllDecorators object containing the decorators for the property. + * + * @param property The class property member. + */ + function getAllDecoratorsOfProperty(property) { + var decorators = property.decorators; + if (!decorators) { + return undefined; + } + return { decorators: decorators }; + } + /** + * Transforms all of the decorators for a declaration into an array of expressions. + * + * @param node The declaration node. + * @param allDecorators An object containing all of the decorators for the declaration. + */ + function transformAllDecoratorsOfDeclaration(node, container, allDecorators) { + if (!allDecorators) { + return undefined; + } + var decoratorExpressions = []; + ts.addRange(decoratorExpressions, ts.map(allDecorators.decorators, transformDecorator)); + ts.addRange(decoratorExpressions, ts.flatMap(allDecorators.parameters, transformDecoratorsOfParameter)); + addTypeMetadata(node, container, decoratorExpressions); + return decoratorExpressions; + } + /** + * Generates statements used to apply decorators to either the static or instance members + * of a class. + * + * @param node The class node. + * @param isStatic A value indicating whether to generate statements for static or + * instance members. + */ + function addClassElementDecorationStatements(statements, node, isStatic) { + ts.addRange(statements, ts.map(generateClassElementDecorationExpressions(node, isStatic), expressionToStatement)); + } + /** + * Generates expressions used to apply decorators to either the static or instance members + * of a class. + * + * @param node The class node. + * @param isStatic A value indicating whether to generate expressions for static or + * instance members. + */ + function generateClassElementDecorationExpressions(node, isStatic) { + var members = getDecoratedClassElements(node, isStatic); + var expressions; + for (var _i = 0, members_5 = members; _i < members_5.length; _i++) { + var member = members_5[_i]; + var expression = generateClassElementDecorationExpression(node, member); + if (expression) { + if (!expressions) { + expressions = [expression]; + } + else { + expressions.push(expression); + } + } + } + return expressions; + } + /** + * Generates an expression used to evaluate class element decorators at runtime. + * + * @param node The class node that contains the member. + * @param member The class member. + */ + function generateClassElementDecorationExpression(node, member) { + var allDecorators = getAllDecoratorsOfClassElement(node, member); + var decoratorExpressions = transformAllDecoratorsOfDeclaration(member, node, allDecorators); + if (!decoratorExpressions) { + return undefined; + } + // Emit the call to __decorate. Given the following: + // + // class C { + // @dec method(@dec2 x) {} + // @dec get accessor() {} + // @dec prop; + // } + // + // The emit for a method is: + // + // __decorate([ + // dec, + // __param(0, dec2), + // __metadata("design:type", Function), + // __metadata("design:paramtypes", [Object]), + // __metadata("design:returntype", void 0) + // ], C.prototype, "method", null); + // + // The emit for an accessor is: + // + // __decorate([ + // dec + // ], C.prototype, "accessor", null); + // + // The emit for a property is: + // + // __decorate([ + // dec + // ], C.prototype, "prop"); + // + var prefix = getClassMemberPrefix(node, member); + var memberName = getExpressionForPropertyName(member, /*generateNameForComputedPropertyName*/ true); + var descriptor = languageVersion > 0 /* ES3 */ + ? member.kind === 154 /* PropertyDeclaration */ + // We emit `void 0` here to indicate to `__decorate` that it can invoke `Object.defineProperty` directly, but that it + // should not invoke `Object.getOwnPropertyDescriptor`. + ? ts.createVoidZero() + // We emit `null` here to indicate to `__decorate` that it can invoke `Object.getOwnPropertyDescriptor` directly. + // We have this extra argument here so that we can inject an explicit property descriptor at a later date. + : ts.createNull() + : undefined; + var helper = createDecorateHelper(context, decoratorExpressions, prefix, memberName, descriptor, ts.moveRangePastDecorators(member)); + ts.setEmitFlags(helper, 1536 /* NoComments */); + return helper; + } + /** + * Generates a __decorate helper call for a class constructor. + * + * @param node The class node. + */ + function addConstructorDecorationStatement(statements, node) { + var expression = generateConstructorDecorationExpression(node); + if (expression) { + statements.push(ts.setOriginalNode(ts.createExpressionStatement(expression), node)); + } + } + /** + * Generates a __decorate helper call for a class constructor. + * + * @param node The class node. + */ + function generateConstructorDecorationExpression(node) { + var allDecorators = getAllDecoratorsOfConstructor(node); + var decoratorExpressions = transformAllDecoratorsOfDeclaration(node, node, allDecorators); + if (!decoratorExpressions) { + return undefined; + } + var classAlias = classAliases && classAliases[ts.getOriginalNodeId(node)]; + var localName = ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true); + var decorate = createDecorateHelper(context, decoratorExpressions, localName); + var expression = ts.createAssignment(localName, classAlias ? ts.createAssignment(classAlias, decorate) : decorate); + ts.setEmitFlags(expression, 1536 /* NoComments */); + ts.setSourceMapRange(expression, ts.moveRangePastDecorators(node)); + return expression; + } + /** + * Transforms a decorator into an expression. + * + * @param decorator The decorator node. + */ + function transformDecorator(decorator) { + return ts.visitNode(decorator.expression, visitor, ts.isExpression); + } + /** + * Transforms the decorators of a parameter. + * + * @param decorators The decorators for the parameter at the provided offset. + * @param parameterOffset The offset of the parameter. + */ + function transformDecoratorsOfParameter(decorators, parameterOffset) { + var expressions; + if (decorators) { + expressions = []; + for (var _i = 0, decorators_1 = decorators; _i < decorators_1.length; _i++) { + var decorator = decorators_1[_i]; + var helper = createParamHelper(context, transformDecorator(decorator), parameterOffset, + /*location*/ decorator.expression); + ts.setEmitFlags(helper, 1536 /* NoComments */); + expressions.push(helper); + } + } + return expressions; + } + /** + * Adds optional type metadata for a declaration. + * + * @param node The declaration node. + * @param decoratorExpressions The destination array to which to add new decorator expressions. + */ + function addTypeMetadata(node, container, decoratorExpressions) { + if (USE_NEW_TYPE_METADATA_FORMAT) { + addNewTypeMetadata(node, container, decoratorExpressions); + } + else { + addOldTypeMetadata(node, container, decoratorExpressions); + } + } + function addOldTypeMetadata(node, container, decoratorExpressions) { + if (compilerOptions.emitDecoratorMetadata) { + if (shouldAddTypeMetadata(node)) { + decoratorExpressions.push(createMetadataHelper(context, "design:type", serializeTypeOfNode(node))); + } + if (shouldAddParamTypesMetadata(node)) { + decoratorExpressions.push(createMetadataHelper(context, "design:paramtypes", serializeParameterTypesOfNode(node, container))); + } + if (shouldAddReturnTypeMetadata(node)) { + decoratorExpressions.push(createMetadataHelper(context, "design:returntype", serializeReturnTypeOfNode(node))); + } + } + } + function addNewTypeMetadata(node, container, decoratorExpressions) { + if (compilerOptions.emitDecoratorMetadata) { + var properties = void 0; + if (shouldAddTypeMetadata(node)) { + (properties || (properties = [])).push(ts.createPropertyAssignment("type", ts.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, ts.createToken(37 /* EqualsGreaterThanToken */), serializeTypeOfNode(node)))); + } + if (shouldAddParamTypesMetadata(node)) { + (properties || (properties = [])).push(ts.createPropertyAssignment("paramTypes", ts.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, ts.createToken(37 /* EqualsGreaterThanToken */), serializeParameterTypesOfNode(node, container)))); + } + if (shouldAddReturnTypeMetadata(node)) { + (properties || (properties = [])).push(ts.createPropertyAssignment("returnType", ts.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, ts.createToken(37 /* EqualsGreaterThanToken */), serializeReturnTypeOfNode(node)))); + } + if (properties) { + decoratorExpressions.push(createMetadataHelper(context, "design:typeinfo", ts.createObjectLiteral(properties, /*multiLine*/ true))); + } + } + } + /** + * Determines whether to emit the "design:type" metadata based on the node's kind. + * The caller should have already tested whether the node has decorators and whether the + * emitDecoratorMetadata compiler option is set. + * + * @param node The node to test. + */ + function shouldAddTypeMetadata(node) { + var kind = node.kind; + return kind === 156 /* MethodDeclaration */ + || kind === 158 /* GetAccessor */ + || kind === 159 /* SetAccessor */ + || kind === 154 /* PropertyDeclaration */; + } + /** + * Determines whether to emit the "design:returntype" metadata based on the node's kind. + * The caller should have already tested whether the node has decorators and whether the + * emitDecoratorMetadata compiler option is set. + * + * @param node The node to test. + */ + function shouldAddReturnTypeMetadata(node) { + return node.kind === 156 /* MethodDeclaration */; + } + /** + * Determines whether to emit the "design:paramtypes" metadata based on the node's kind. + * The caller should have already tested whether the node has decorators and whether the + * emitDecoratorMetadata compiler option is set. + * + * @param node The node to test. + */ + function shouldAddParamTypesMetadata(node) { + switch (node.kind) { + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + return ts.getFirstConstructorWithBody(node) !== undefined; + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + return true; + } + return false; + } + function getAccessorTypeNode(node) { + var accessors = resolver.getAllAccessorDeclarations(node); + return accessors.setAccessor && ts.getSetAccessorTypeAnnotationNode(accessors.setAccessor) + || accessors.getAccessor && ts.getEffectiveReturnTypeNode(accessors.getAccessor); + } + /** + * Serializes the type of a node for use with decorator type metadata. + * + * @param node The node that should have its type serialized. + */ + function serializeTypeOfNode(node) { + switch (node.kind) { + case 154 /* PropertyDeclaration */: + case 151 /* Parameter */: + return serializeTypeNode(node.type); + case 159 /* SetAccessor */: + case 158 /* GetAccessor */: + return serializeTypeNode(getAccessorTypeNode(node)); + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 156 /* MethodDeclaration */: + return ts.createIdentifier("Function"); + default: + return ts.createVoidZero(); + } + } + /** + * Serializes the types of the parameters of a node for use with decorator type metadata. + * + * @param node The node that should have its parameter types serialized. + */ + function serializeParameterTypesOfNode(node, container) { + var valueDeclaration = ts.isClassLike(node) + ? ts.getFirstConstructorWithBody(node) + : ts.isFunctionLike(node) && ts.nodeIsPresent(node.body) + ? node + : undefined; + var expressions = []; + if (valueDeclaration) { + var parameters = getParametersOfDecoratedDeclaration(valueDeclaration, container); + var numParameters = parameters.length; + for (var i = 0; i < numParameters; i++) { + var parameter = parameters[i]; + if (i === 0 && ts.isIdentifier(parameter.name) && parameter.name.escapedText === "this") { + continue; + } + if (parameter.dotDotDotToken) { + expressions.push(serializeTypeNode(ts.getRestParameterElementType(parameter.type))); + } + else { + expressions.push(serializeTypeOfNode(parameter)); + } + } + } + return ts.createArrayLiteral(expressions); + } + function getParametersOfDecoratedDeclaration(node, container) { + if (container && node.kind === 158 /* GetAccessor */) { + var setAccessor = ts.getAllAccessorDeclarations(container.members, node).setAccessor; + if (setAccessor) { + return setAccessor.parameters; + } + } + return node.parameters; + } + /** + * Serializes the return type of a node for use with decorator type metadata. + * + * @param node The node that should have its return type serialized. + */ + function serializeReturnTypeOfNode(node) { + if (ts.isFunctionLike(node) && node.type) { + return serializeTypeNode(node.type); + } + else if (ts.isAsyncFunction(node)) { + return ts.createIdentifier("Promise"); + } + return ts.createVoidZero(); + } + /** + * Serializes a type node for use with decorator type metadata. + * + * Types are serialized in the following fashion: + * - Void types point to "undefined" (e.g. "void 0") + * - Function and Constructor types point to the global "Function" constructor. + * - Interface types with a call or construct signature types point to the global + * "Function" constructor. + * - Array and Tuple types point to the global "Array" constructor. + * - Type predicates and booleans point to the global "Boolean" constructor. + * - String literal types and strings point to the global "String" constructor. + * - Enum and number types point to the global "Number" constructor. + * - Symbol types point to the global "Symbol" constructor. + * - Type references to classes (or class-like variables) point to the constructor for the class. + * - Anything else points to the global "Object" constructor. + * + * @param node The type node to serialize. + */ + function serializeTypeNode(node) { + if (node === undefined) { + return ts.createIdentifier("Object"); + } + switch (node.kind) { + case 106 /* VoidKeyword */: + case 141 /* UndefinedKeyword */: + case 96 /* NullKeyword */: + case 132 /* NeverKeyword */: + return ts.createVoidZero(); + case 177 /* ParenthesizedType */: + return serializeTypeNode(node.type); + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + return ts.createIdentifier("Function"); + case 169 /* ArrayType */: + case 170 /* TupleType */: + return ts.createIdentifier("Array"); + case 163 /* TypePredicate */: + case 123 /* BooleanKeyword */: + return ts.createIdentifier("Boolean"); + case 138 /* StringKeyword */: + return ts.createIdentifier("String"); + case 136 /* ObjectKeyword */: + return ts.createIdentifier("Object"); + case 182 /* LiteralType */: + switch (node.literal.kind) { + case 10 /* StringLiteral */: + return ts.createIdentifier("String"); + case 8 /* NumericLiteral */: + return ts.createIdentifier("Number"); + case 9 /* BigIntLiteral */: + return getGlobalBigIntNameWithFallback(); + case 102 /* TrueKeyword */: + case 87 /* FalseKeyword */: + return ts.createIdentifier("Boolean"); + default: + return ts.Debug.failBadSyntaxKind(node.literal); + } + case 135 /* NumberKeyword */: + return ts.createIdentifier("Number"); + case 146 /* BigIntKeyword */: + return getGlobalBigIntNameWithFallback(); + case 139 /* SymbolKeyword */: + return languageVersion < 2 /* ES2015 */ + ? getGlobalSymbolNameWithFallback() + : ts.createIdentifier("Symbol"); + case 164 /* TypeReference */: + return serializeTypeReferenceNode(node); + case 174 /* IntersectionType */: + case 173 /* UnionType */: + return serializeTypeList(node.types); + case 175 /* ConditionalType */: + return serializeTypeList([node.trueType, node.falseType]); + case 167 /* TypeQuery */: + case 179 /* TypeOperator */: + case 180 /* IndexedAccessType */: + case 181 /* MappedType */: + case 168 /* TypeLiteral */: + case 120 /* AnyKeyword */: + case 143 /* UnknownKeyword */: + case 178 /* ThisType */: + case 183 /* ImportType */: + break; + default: + return ts.Debug.failBadSyntaxKind(node); + } + return ts.createIdentifier("Object"); + } + function serializeTypeList(types) { + // Note when updating logic here also update getEntityNameForDecoratorMetadata + // so that aliases can be marked as referenced + var serializedUnion; + for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { + var typeNode = types_17[_i]; + while (typeNode.kind === 177 /* ParenthesizedType */) { + typeNode = typeNode.type; // Skip parens if need be + } + if (typeNode.kind === 132 /* NeverKeyword */) { + continue; // Always elide `never` from the union/intersection if possible + } + if (!strictNullChecks && (typeNode.kind === 96 /* NullKeyword */ || typeNode.kind === 141 /* UndefinedKeyword */)) { + continue; // Elide null and undefined from unions for metadata, just like what we did prior to the implementation of strict null checks + } + var serializedIndividual = serializeTypeNode(typeNode); + if (ts.isIdentifier(serializedIndividual) && serializedIndividual.escapedText === "Object") { + // One of the individual is global object, return immediately + return serializedIndividual; + } + // If there exists union that is not void 0 expression, check if the the common type is identifier. + // anything more complex and we will just default to Object + else if (serializedUnion) { + // Different types + if (!ts.isIdentifier(serializedUnion) || + !ts.isIdentifier(serializedIndividual) || + serializedUnion.escapedText !== serializedIndividual.escapedText) { + return ts.createIdentifier("Object"); + } + } + else { + // Initialize the union type + serializedUnion = serializedIndividual; + } + } + // If we were able to find common type, use it + return serializedUnion || ts.createVoidZero(); // Fallback is only hit if all union constituients are null/undefined/never + } + /** + * Serializes a TypeReferenceNode to an appropriate JS constructor value for use with + * decorator type metadata. + * + * @param node The type reference node. + */ + function serializeTypeReferenceNode(node) { + var kind = resolver.getTypeReferenceSerializationKind(node.typeName, currentNameScope || currentLexicalScope); + switch (kind) { + case ts.TypeReferenceSerializationKind.Unknown: + // From conditional type type reference that cannot be resolved is Similar to any or unknown + if (ts.findAncestor(node, function (n) { return n.parent && ts.isConditionalTypeNode(n.parent) && (n.parent.trueType === n || n.parent.falseType === n); })) { + return ts.createIdentifier("Object"); + } + var serialized = serializeEntityNameAsExpressionFallback(node.typeName); + var temp = ts.createTempVariable(hoistVariableDeclaration); + return ts.createConditional(ts.createTypeCheck(ts.createAssignment(temp, serialized), "function"), temp, ts.createIdentifier("Object")); + case ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue: + return serializeEntityNameAsExpression(node.typeName); + case ts.TypeReferenceSerializationKind.VoidNullableOrNeverType: + return ts.createVoidZero(); + case ts.TypeReferenceSerializationKind.BigIntLikeType: + return getGlobalBigIntNameWithFallback(); + case ts.TypeReferenceSerializationKind.BooleanType: + return ts.createIdentifier("Boolean"); + case ts.TypeReferenceSerializationKind.NumberLikeType: + return ts.createIdentifier("Number"); + case ts.TypeReferenceSerializationKind.StringLikeType: + return ts.createIdentifier("String"); + case ts.TypeReferenceSerializationKind.ArrayLikeType: + return ts.createIdentifier("Array"); + case ts.TypeReferenceSerializationKind.ESSymbolType: + return languageVersion < 2 /* ES2015 */ + ? getGlobalSymbolNameWithFallback() + : ts.createIdentifier("Symbol"); + case ts.TypeReferenceSerializationKind.TypeWithCallSignature: + return ts.createIdentifier("Function"); + case ts.TypeReferenceSerializationKind.Promise: + return ts.createIdentifier("Promise"); + case ts.TypeReferenceSerializationKind.ObjectType: + return ts.createIdentifier("Object"); + default: + return ts.Debug.assertNever(kind); + } + } + function createCheckedValue(left, right) { + return ts.createLogicalAnd(ts.createStrictInequality(ts.createTypeOf(left), ts.createLiteral("undefined")), right); + } + /** + * Serializes an entity name which may not exist at runtime, but whose access shouldn't throw + * + * @param node The entity name to serialize. + */ + function serializeEntityNameAsExpressionFallback(node) { + if (node.kind === 72 /* Identifier */) { + // A -> typeof A !== undefined && A + var copied = serializeEntityNameAsExpression(node); + return createCheckedValue(copied, copied); + } + if (node.left.kind === 72 /* Identifier */) { + // A.B -> typeof A !== undefined && A.B + return createCheckedValue(serializeEntityNameAsExpression(node.left), serializeEntityNameAsExpression(node)); + } + // A.B.C -> typeof A !== undefined && (_a = A.B) !== void 0 && _a.C + var left = serializeEntityNameAsExpressionFallback(node.left); + var temp = ts.createTempVariable(hoistVariableDeclaration); + return ts.createLogicalAnd(ts.createLogicalAnd(left.left, ts.createStrictInequality(ts.createAssignment(temp, left.right), ts.createVoidZero())), ts.createPropertyAccess(temp, node.right)); + } + /** + * Serializes an entity name as an expression for decorator type metadata. + * + * @param node The entity name to serialize. + */ + function serializeEntityNameAsExpression(node) { + switch (node.kind) { + case 72 /* Identifier */: + // Create a clone of the name with a new parent, and treat it as if it were + // a source tree node for the purposes of the checker. + var name = ts.getMutableClone(node); + name.flags &= ~8 /* Synthesized */; + name.original = undefined; + name.parent = ts.getParseTreeNode(currentLexicalScope); // ensure the parent is set to a parse tree node. + return name; + case 148 /* QualifiedName */: + return serializeQualifiedNameAsExpression(node); + } + } + /** + * Serializes an qualified name as an expression for decorator type metadata. + * + * @param node The qualified name to serialize. + * @param useFallback A value indicating whether to use logical operators to test for the + * qualified name at runtime. + */ + function serializeQualifiedNameAsExpression(node) { + return ts.createPropertyAccess(serializeEntityNameAsExpression(node.left), node.right); + } + /** + * Gets an expression that points to the global "Symbol" constructor at runtime if it is + * available. + */ + function getGlobalSymbolNameWithFallback() { + return ts.createConditional(ts.createTypeCheck(ts.createIdentifier("Symbol"), "function"), ts.createIdentifier("Symbol"), ts.createIdentifier("Object")); + } + /** + * Gets an expression that points to the global "BigInt" constructor at runtime if it is + * available. + */ + function getGlobalBigIntNameWithFallback() { + return languageVersion < 6 /* ESNext */ + ? ts.createConditional(ts.createTypeCheck(ts.createIdentifier("BigInt"), "function"), ts.createIdentifier("BigInt"), ts.createIdentifier("Object")) + : ts.createIdentifier("BigInt"); + } + /** + * A simple inlinable expression is an expression which can be copied into multiple locations + * without risk of repeating any sideeffects and whose value could not possibly change between + * any such locations + */ + function isSimpleInlineableExpression(expression) { + return !ts.isIdentifier(expression) && ts.isSimpleCopiableExpression(expression) || + ts.isWellKnownSymbolSyntactically(expression); + } + /** + * Gets an expression that represents a property name. For a computed property, a + * name is generated for the node. + * + * @param member The member whose name should be converted into an expression. + */ + function getExpressionForPropertyName(member, generateNameForComputedPropertyName) { + var name = member.name; + if (ts.isComputedPropertyName(name)) { + return generateNameForComputedPropertyName && !isSimpleInlineableExpression(name.expression) + ? ts.getGeneratedNameForNode(name) + : name.expression; + } + else if (ts.isIdentifier(name)) { + return ts.createLiteral(ts.idText(name)); + } + else { + return ts.getSynthesizedClone(name); + } + } + /** + * If the name is a computed property, this function transforms it, then either returns an expression which caches the + * value of the result or the expression itself if the value is either unused or safe to inline into multiple locations + * @param shouldHoist Does the expression need to be reused? (ie, for an initializer or a decorator) + * @param omitSimple Should expressions with no observable side-effects be elided? (ie, the expression is not hoisted for a decorator or initializer and is a literal) + */ + function getPropertyNameExpressionIfNeeded(name, shouldHoist, omitSimple) { + if (ts.isComputedPropertyName(name)) { + var expression = ts.visitNode(name.expression, visitor, ts.isExpression); + var innerExpression = ts.skipPartiallyEmittedExpressions(expression); + var inlinable = isSimpleInlineableExpression(innerExpression); + if (!inlinable && shouldHoist) { + var generatedName = ts.getGeneratedNameForNode(name); + hoistVariableDeclaration(generatedName); + return ts.createAssignment(generatedName, expression); + } + return (omitSimple && (inlinable || ts.isIdentifier(innerExpression))) ? undefined : expression; + } + } + /** + * Visits the property name of a class element, for use when emitting property + * initializers. For a computed property on a node with decorators, a temporary + * value is stored for later use. + * + * @param member The member whose name should be visited. + */ + function visitPropertyNameOfClassElement(member) { + var name = member.name; + var expr = getPropertyNameExpressionIfNeeded(name, ts.some(member.decorators), /*omitSimple*/ false); + if (expr) { // expr only exists if `name` is a computed property name + // Inline any pending expressions from previous elided or relocated computed property name expressions in order to preserve execution order + if (ts.some(pendingExpressions)) { + expr = ts.inlineExpressions(pendingExpressions.concat([expr])); + pendingExpressions.length = 0; + } + return ts.updateComputedPropertyName(name, expr); + } + else { + return name; + } + } + /** + * Transforms a HeritageClause with TypeScript syntax. + * + * This function will only be called when one of the following conditions are met: + * - The node is a non-`extends` heritage clause that should be elided. + * - The node is an `extends` heritage clause that should be visited, but only allow a single type. + * + * @param node The HeritageClause to transform. + */ + function visitHeritageClause(node) { + if (node.token === 86 /* ExtendsKeyword */) { + var types = ts.visitNodes(node.types, visitor, ts.isExpressionWithTypeArguments, 0, 1); + return ts.setTextRange(ts.createHeritageClause(86 /* ExtendsKeyword */, types), node); + } + return undefined; + } + /** + * Transforms an ExpressionWithTypeArguments with TypeScript syntax. + * + * This function will only be called when one of the following conditions are met: + * - The node contains type arguments that should be elided. + * + * @param node The ExpressionWithTypeArguments to transform. + */ + function visitExpressionWithTypeArguments(node) { + return ts.updateExpressionWithTypeArguments(node, + /*typeArguments*/ undefined, ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression)); + } + /** + * Determines whether to emit a function-like declaration. We should not emit the + * declaration if it does not have a body. + * + * @param node The declaration node. + */ + function shouldEmitFunctionLikeDeclaration(node) { + return !ts.nodeIsMissing(node.body); + } + function visitPropertyDeclaration(node) { + var expr = getPropertyNameExpressionIfNeeded(node.name, ts.some(node.decorators) || !!node.initializer, /*omitSimple*/ true); + if (expr && !isSimpleInlineableExpression(expr)) { + (pendingExpressions || (pendingExpressions = [])).push(expr); + } + return undefined; + } + function visitConstructor(node) { + if (!shouldEmitFunctionLikeDeclaration(node)) { + return undefined; + } + return ts.updateConstructor(node, ts.visitNodes(node.decorators, visitor, ts.isDecorator), ts.visitNodes(node.modifiers, visitor, ts.isModifier), ts.visitParameterList(node.parameters, visitor, context), ts.visitFunctionBody(node.body, visitor, context)); + } + /** + * Visits a method declaration of a class. + * + * This function will be called when one of the following conditions are met: + * - The node is an overload + * - The node is marked as abstract, public, private, protected, or readonly + * - The node has a computed property name + * + * @param node The method node. + */ + function visitMethodDeclaration(node) { + if (!shouldEmitFunctionLikeDeclaration(node)) { + return undefined; + } + var updated = ts.updateMethod(node, + /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, visitPropertyNameOfClassElement(node), + /*questionToken*/ undefined, + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context)); + if (updated !== node) { + // While we emit the source map for the node after skipping decorators and modifiers, + // we need to emit the comments for the original range. + ts.setCommentRange(updated, node); + ts.setSourceMapRange(updated, ts.moveRangePastDecorators(node)); + } + return updated; + } + /** + * Determines whether to emit an accessor declaration. We should not emit the + * declaration if it does not have a body and is abstract. + * + * @param node The declaration node. + */ + function shouldEmitAccessorDeclaration(node) { + return !(ts.nodeIsMissing(node.body) && ts.hasModifier(node, 128 /* Abstract */)); + } + /** + * Visits a get accessor declaration of a class. + * + * This function will be called when one of the following conditions are met: + * - The node is marked as abstract, public, private, or protected + * - The node has a computed property name + * + * @param node The get accessor node. + */ + function visitGetAccessor(node) { + if (!shouldEmitAccessorDeclaration(node)) { + return undefined; + } + var updated = ts.updateGetAccessor(node, + /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), visitPropertyNameOfClassElement(node), ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context) || ts.createBlock([])); + if (updated !== node) { + // While we emit the source map for the node after skipping decorators and modifiers, + // we need to emit the comments for the original range. + ts.setCommentRange(updated, node); + ts.setSourceMapRange(updated, ts.moveRangePastDecorators(node)); + } + return updated; + } + /** + * Visits a set accessor declaration of a class. + * + * This function will be called when one of the following conditions are met: + * - The node is marked as abstract, public, private, or protected + * - The node has a computed property name + * + * @param node The set accessor node. + */ + function visitSetAccessor(node) { + if (!shouldEmitAccessorDeclaration(node)) { + return undefined; + } + var updated = ts.updateSetAccessor(node, + /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), visitPropertyNameOfClassElement(node), ts.visitParameterList(node.parameters, visitor, context), ts.visitFunctionBody(node.body, visitor, context) || ts.createBlock([])); + if (updated !== node) { + // While we emit the source map for the node after skipping decorators and modifiers, + // we need to emit the comments for the original range. + ts.setCommentRange(updated, node); + ts.setSourceMapRange(updated, ts.moveRangePastDecorators(node)); + } + return updated; + } + /** + * Visits a function declaration. + * + * This function will be called when one of the following conditions are met: + * - The node is an overload + * - The node is exported from a TypeScript namespace + * - The node has decorators + * + * @param node The function node. + */ + function visitFunctionDeclaration(node) { + if (!shouldEmitFunctionLikeDeclaration(node)) { + return ts.createNotEmittedStatement(node); + } + var updated = ts.updateFunctionDeclaration(node, + /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, node.name, + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context) || ts.createBlock([])); + if (isExportOfNamespace(node)) { + var statements = [updated]; + addExportMemberAssignment(statements, node); + return statements; + } + return updated; + } + /** + * Visits a function expression node. + * + * This function will be called when one of the following conditions are met: + * - The node has type annotations + * + * @param node The function expression node. + */ + function visitFunctionExpression(node) { + if (!shouldEmitFunctionLikeDeclaration(node)) { + return ts.createOmittedExpression(); + } + var updated = ts.updateFunctionExpression(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, node.name, + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context) || ts.createBlock([])); + return updated; + } + /** + * @remarks + * This function will be called when one of the following conditions are met: + * - The node has type annotations + */ + function visitArrowFunction(node) { + var updated = ts.updateArrowFunction(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, node.equalsGreaterThanToken, ts.visitFunctionBody(node.body, visitor, context)); + return updated; + } + /** + * Visits a parameter declaration node. + * + * This function will be called when one of the following conditions are met: + * - The node has an accessibility modifier. + * - The node has a questionToken. + * - The node's kind is ThisKeyword. + * + * @param node The parameter declaration node. + */ + function visitParameter(node) { + if (ts.parameterIsThisKeyword(node)) { + return undefined; + } + var parameter = ts.createParameter( + /*decorators*/ undefined, + /*modifiers*/ undefined, node.dotDotDotToken, ts.visitNode(node.name, visitor, ts.isBindingName), + /*questionToken*/ undefined, + /*type*/ undefined, ts.visitNode(node.initializer, visitor, ts.isExpression)); + // While we emit the source map for the node after skipping decorators and modifiers, + // we need to emit the comments for the original range. + ts.setOriginalNode(parameter, node); + ts.setTextRange(parameter, ts.moveRangePastModifiers(node)); + ts.setCommentRange(parameter, node); + ts.setSourceMapRange(parameter, ts.moveRangePastModifiers(node)); + ts.setEmitFlags(parameter.name, 32 /* NoTrailingSourceMap */); + return parameter; + } + /** + * Visits a variable statement in a namespace. + * + * This function will be called when one of the following conditions are met: + * - The node is exported from a TypeScript namespace. + */ + function visitVariableStatement(node) { + if (isExportOfNamespace(node)) { + var variables = ts.getInitializedVariables(node.declarationList); + if (variables.length === 0) { + // elide statement if there are no initialized variables. + return undefined; + } + return ts.setTextRange(ts.createExpressionStatement(ts.inlineExpressions(ts.map(variables, transformInitializedVariable))), node); + } + else { + return ts.visitEachChild(node, visitor, context); + } + } + function transformInitializedVariable(node) { + var name = node.name; + if (ts.isBindingPattern(name)) { + return ts.flattenDestructuringAssignment(node, visitor, context, 0 /* All */, + /*needsValue*/ false, createNamespaceExportExpression); + } + else { + return ts.setTextRange(ts.createAssignment(getNamespaceMemberNameWithSourceMapsAndWithoutComments(name), ts.visitNode(node.initializer, visitor, ts.isExpression)), + /*location*/ node); + } + } + function visitVariableDeclaration(node) { + return ts.updateVariableDeclaration(node, ts.visitNode(node.name, visitor, ts.isBindingName), + /*type*/ undefined, ts.visitNode(node.initializer, visitor, ts.isExpression)); + } + /** + * Visits a parenthesized expression that contains either a type assertion or an `as` + * expression. + * + * @param node The parenthesized expression node. + */ + function visitParenthesizedExpression(node) { + var innerExpression = ts.skipOuterExpressions(node.expression, ~2 /* Assertions */); + if (ts.isAssertionExpression(innerExpression)) { + // Make sure we consider all nested cast expressions, e.g.: + // (-A).x; + var expression = ts.visitNode(node.expression, visitor, ts.isExpression); + // We have an expression of the form: (SubExpr). Emitting this as (SubExpr) + // is really not desirable. We would like to emit the subexpression as-is. Omitting + // the parentheses, however, could cause change in the semantics of the generated + // code if the casted expression has a lower precedence than the rest of the + // expression. + // + // To preserve comments, we return a "PartiallyEmittedExpression" here which will + // preserve the position information of the original expression. + // + // Due to the auto-parenthesization rules used by the visitor and factory functions + // we can safely elide the parentheses here, as a new synthetic + // ParenthesizedExpression will be inserted if we remove parentheses too + // aggressively. + // HOWEVER - if there are leading comments on the expression itself, to handle ASI + // correctly for return and throw, we must keep the parenthesis + if (ts.length(ts.getLeadingCommentRangesOfNode(expression, currentSourceFile))) { + return ts.updateParen(node, expression); + } + return ts.createPartiallyEmittedExpression(expression, node); + } + return ts.visitEachChild(node, visitor, context); + } + function visitAssertionExpression(node) { + var expression = ts.visitNode(node.expression, visitor, ts.isExpression); + return ts.createPartiallyEmittedExpression(expression, node); + } + function visitNonNullExpression(node) { + var expression = ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression); + return ts.createPartiallyEmittedExpression(expression, node); + } + function visitCallExpression(node) { + return ts.updateCall(node, ts.visitNode(node.expression, visitor, ts.isExpression), + /*typeArguments*/ undefined, ts.visitNodes(node.arguments, visitor, ts.isExpression)); + } + function visitNewExpression(node) { + return ts.updateNew(node, ts.visitNode(node.expression, visitor, ts.isExpression), + /*typeArguments*/ undefined, ts.visitNodes(node.arguments, visitor, ts.isExpression)); + } + function visitTaggedTemplateExpression(node) { + return ts.updateTaggedTemplate(node, ts.visitNode(node.tag, visitor, ts.isExpression), + /*typeArguments*/ undefined, ts.visitNode(node.template, visitor, ts.isExpression)); + } + /** + * Determines whether to emit an enum declaration. + * + * @param node The enum declaration node. + */ + function shouldEmitEnumDeclaration(node) { + return !ts.isEnumConst(node) + || compilerOptions.preserveConstEnums + || compilerOptions.isolatedModules; + } + /** + * Visits an enum declaration. + * + * This function will be called any time a TypeScript enum is encountered. + * + * @param node The enum declaration node. + */ + function visitEnumDeclaration(node) { + if (!shouldEmitEnumDeclaration(node)) { + return undefined; + } + var statements = []; + // We request to be advised when the printer is about to print this node. This allows + // us to set up the correct state for later substitutions. + var emitFlags = 2 /* AdviseOnEmitNode */; + // If needed, we should emit a variable declaration for the enum. If we emit + // a leading variable declaration, we should not emit leading comments for the + // enum body. + var varAdded = addVarForEnumOrModuleDeclaration(statements, node); + if (varAdded) { + // We should still emit the comments if we are emitting a system module. + if (moduleKind !== ts.ModuleKind.System || currentLexicalScope !== currentSourceFile) { + emitFlags |= 512 /* NoLeadingComments */; + } + } + // `parameterName` is the declaration name used inside of the enum. + var parameterName = getNamespaceParameterName(node); + // `containerName` is the expression used inside of the enum for assignments. + var containerName = getNamespaceContainerName(node); + // `exportName` is the expression used within this node's container for any exported references. + var exportName = ts.hasModifier(node, 1 /* Export */) + ? ts.getExternalModuleOrNamespaceExportName(currentNamespaceContainerName, node, /*allowComments*/ false, /*allowSourceMaps*/ true) + : ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true); + // x || (x = {}) + // exports.x || (exports.x = {}) + var moduleArg = ts.createLogicalOr(exportName, ts.createAssignment(exportName, ts.createObjectLiteral())); + if (hasNamespaceQualifiedExportName(node)) { + // `localName` is the expression used within this node's containing scope for any local references. + var localName = ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true); + // x = (exports.x || (exports.x = {})) + moduleArg = ts.createAssignment(localName, moduleArg); + } + // (function (x) { + // x[x["y"] = 0] = "y"; + // ... + // })(x || (x = {})); + var enumStatement = ts.createExpressionStatement(ts.createCall(ts.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, parameterName)], + /*type*/ undefined, transformEnumBody(node, containerName)), + /*typeArguments*/ undefined, [moduleArg])); + ts.setOriginalNode(enumStatement, node); + if (varAdded) { + // If a variable was added, synthetic comments are emitted on it, not on the moduleStatement. + ts.setSyntheticLeadingComments(enumStatement, undefined); + ts.setSyntheticTrailingComments(enumStatement, undefined); + } + ts.setTextRange(enumStatement, node); + ts.addEmitFlags(enumStatement, emitFlags); + statements.push(enumStatement); + // Add a DeclarationMarker for the enum to preserve trailing comments and mark + // the end of the declaration. + statements.push(ts.createEndOfDeclarationMarker(node)); + return statements; + } + /** + * Transforms the body of an enum declaration. + * + * @param node The enum declaration node. + */ + function transformEnumBody(node, localName) { + var savedCurrentNamespaceLocalName = currentNamespaceContainerName; + currentNamespaceContainerName = localName; + var statements = []; + startLexicalEnvironment(); + var members = ts.map(node.members, transformEnumMember); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + ts.addRange(statements, members); + currentNamespaceContainerName = savedCurrentNamespaceLocalName; + return ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), /*location*/ node.members), + /*multiLine*/ true); + } + /** + * Transforms an enum member into a statement. + * + * @param member The enum member node. + */ + function transformEnumMember(member) { + // enums don't support computed properties + // we pass false as 'generateNameForComputedPropertyName' for a backward compatibility purposes + // old emitter always generate 'expression' part of the name as-is. + var name = getExpressionForPropertyName(member, /*generateNameForComputedPropertyName*/ false); + var valueExpression = transformEnumMemberDeclarationValue(member); + var innerAssignment = ts.createAssignment(ts.createElementAccess(currentNamespaceContainerName, name), valueExpression); + var outerAssignment = valueExpression.kind === 10 /* StringLiteral */ ? + innerAssignment : + ts.createAssignment(ts.createElementAccess(currentNamespaceContainerName, innerAssignment), name); + return ts.setTextRange(ts.createExpressionStatement(ts.setTextRange(outerAssignment, member)), member); + } + /** + * Transforms the value of an enum member. + * + * @param member The enum member node. + */ + function transformEnumMemberDeclarationValue(member) { + var value = resolver.getConstantValue(member); + if (value !== undefined) { + return ts.createLiteral(value); + } + else { + enableSubstitutionForNonQualifiedEnumMembers(); + if (member.initializer) { + return ts.visitNode(member.initializer, visitor, ts.isExpression); + } + else { + return ts.createVoidZero(); + } + } + } + /** + * Determines whether to elide a module declaration. + * + * @param node The module declaration node. + */ + function shouldEmitModuleDeclaration(node) { + return ts.isInstantiatedModule(node, !!compilerOptions.preserveConstEnums || !!compilerOptions.isolatedModules); + } + /** + * Determines whether an exported declaration will have a qualified export name (e.g. `f.x` + * or `exports.x`). + */ + function hasNamespaceQualifiedExportName(node) { + return isExportOfNamespace(node) + || (isExternalModuleExport(node) + && moduleKind !== ts.ModuleKind.ES2015 + && moduleKind !== ts.ModuleKind.ESNext + && moduleKind !== ts.ModuleKind.System); + } + /** + * Records that a declaration was emitted in the current scope, if it was the first + * declaration for the provided symbol. + */ + function recordEmittedDeclarationInScope(node) { + if (!currentScopeFirstDeclarationsOfName) { + currentScopeFirstDeclarationsOfName = ts.createUnderscoreEscapedMap(); + } + var name = declaredNameInScope(node); + if (!currentScopeFirstDeclarationsOfName.has(name)) { + currentScopeFirstDeclarationsOfName.set(name, node); + } + } + /** + * Determines whether a declaration is the first declaration with + * the same name emitted in the current scope. + */ + function isFirstEmittedDeclarationInScope(node) { + if (currentScopeFirstDeclarationsOfName) { + var name = declaredNameInScope(node); + return currentScopeFirstDeclarationsOfName.get(name) === node; + } + return true; + } + function declaredNameInScope(node) { + ts.Debug.assertNode(node.name, ts.isIdentifier); + return node.name.escapedText; + } + /** + * Adds a leading VariableStatement for a enum or module declaration. + */ + function addVarForEnumOrModuleDeclaration(statements, node) { + // Emit a variable statement for the module. We emit top-level enums as a `var` + // declaration to avoid static errors in global scripts scripts due to redeclaration. + // enums in any other scope are emitted as a `let` declaration. + var statement = ts.createVariableStatement(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.createVariableDeclarationList([ + ts.createVariableDeclaration(ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true)) + ], currentLexicalScope.kind === 279 /* SourceFile */ ? 0 /* None */ : 1 /* Let */)); + ts.setOriginalNode(statement, node); + recordEmittedDeclarationInScope(node); + if (isFirstEmittedDeclarationInScope(node)) { + // Adjust the source map emit to match the old emitter. + if (node.kind === 243 /* EnumDeclaration */) { + ts.setSourceMapRange(statement.declarationList, node); + } + else { + ts.setSourceMapRange(statement, node); + } + // Trailing comments for module declaration should be emitted after the function closure + // instead of the variable statement: + // + // /** Module comment*/ + // module m1 { + // function foo4Export() { + // } + // } // trailing comment module + // + // Should emit: + // + // /** Module comment*/ + // var m1; + // (function (m1) { + // function foo4Export() { + // } + // })(m1 || (m1 = {})); // trailing comment module + // + ts.setCommentRange(statement, node); + ts.addEmitFlags(statement, 1024 /* NoTrailingComments */ | 4194304 /* HasEndOfDeclarationMarker */); + statements.push(statement); + return true; + } + else { + // For an EnumDeclaration or ModuleDeclaration that merges with a preceeding + // declaration we do not emit a leading variable declaration. To preserve the + // begin/end semantics of the declararation and to properly handle exports + // we wrap the leading variable declaration in a `MergeDeclarationMarker`. + var mergeMarker = ts.createMergeDeclarationMarker(statement); + ts.setEmitFlags(mergeMarker, 1536 /* NoComments */ | 4194304 /* HasEndOfDeclarationMarker */); + statements.push(mergeMarker); + return false; + } + } + /** + * Visits a module declaration node. + * + * This function will be called any time a TypeScript namespace (ModuleDeclaration) is encountered. + * + * @param node The module declaration node. + */ + function visitModuleDeclaration(node) { + if (!shouldEmitModuleDeclaration(node)) { + return ts.createNotEmittedStatement(node); + } + ts.Debug.assertNode(node.name, ts.isIdentifier, "A TypeScript namespace should have an Identifier name."); + enableSubstitutionForNamespaceExports(); + var statements = []; + // We request to be advised when the printer is about to print this node. This allows + // us to set up the correct state for later substitutions. + var emitFlags = 2 /* AdviseOnEmitNode */; + // If needed, we should emit a variable declaration for the module. If we emit + // a leading variable declaration, we should not emit leading comments for the + // module body. + var varAdded = addVarForEnumOrModuleDeclaration(statements, node); + if (varAdded) { + // We should still emit the comments if we are emitting a system module. + if (moduleKind !== ts.ModuleKind.System || currentLexicalScope !== currentSourceFile) { + emitFlags |= 512 /* NoLeadingComments */; + } + } + // `parameterName` is the declaration name used inside of the namespace. + var parameterName = getNamespaceParameterName(node); + // `containerName` is the expression used inside of the namespace for exports. + var containerName = getNamespaceContainerName(node); + // `exportName` is the expression used within this node's container for any exported references. + var exportName = ts.hasModifier(node, 1 /* Export */) + ? ts.getExternalModuleOrNamespaceExportName(currentNamespaceContainerName, node, /*allowComments*/ false, /*allowSourceMaps*/ true) + : ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true); + // x || (x = {}) + // exports.x || (exports.x = {}) + var moduleArg = ts.createLogicalOr(exportName, ts.createAssignment(exportName, ts.createObjectLiteral())); + if (hasNamespaceQualifiedExportName(node)) { + // `localName` is the expression used within this node's containing scope for any local references. + var localName = ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true); + // x = (exports.x || (exports.x = {})) + moduleArg = ts.createAssignment(localName, moduleArg); + } + // (function (x_1) { + // x_1.y = ...; + // })(x || (x = {})); + var moduleStatement = ts.createExpressionStatement(ts.createCall(ts.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, parameterName)], + /*type*/ undefined, transformModuleBody(node, containerName)), + /*typeArguments*/ undefined, [moduleArg])); + ts.setOriginalNode(moduleStatement, node); + if (varAdded) { + // If a variable was added, synthetic comments are emitted on it, not on the moduleStatement. + ts.setSyntheticLeadingComments(moduleStatement, undefined); + ts.setSyntheticTrailingComments(moduleStatement, undefined); + } + ts.setTextRange(moduleStatement, node); + ts.addEmitFlags(moduleStatement, emitFlags); + statements.push(moduleStatement); + // Add a DeclarationMarker for the namespace to preserve trailing comments and mark + // the end of the declaration. + statements.push(ts.createEndOfDeclarationMarker(node)); + return statements; + } + /** + * Transforms the body of a module declaration. + * + * @param node The module declaration node. + */ + function transformModuleBody(node, namespaceLocalName) { + var savedCurrentNamespaceContainerName = currentNamespaceContainerName; + var savedCurrentNamespace = currentNamespace; + var savedCurrentScopeFirstDeclarationsOfName = currentScopeFirstDeclarationsOfName; + currentNamespaceContainerName = namespaceLocalName; + currentNamespace = node; + currentScopeFirstDeclarationsOfName = undefined; + var statements = []; + startLexicalEnvironment(); + var statementsLocation; + var blockLocation; + var body = node.body; + if (body.kind === 245 /* ModuleBlock */) { + saveStateAndInvoke(body, function (body) { return ts.addRange(statements, ts.visitNodes(body.statements, namespaceElementVisitor, ts.isStatement)); }); + statementsLocation = body.statements; + blockLocation = body; + } + else { + var result = visitModuleDeclaration(body); + if (result) { + if (ts.isArray(result)) { + ts.addRange(statements, result); + } + else { + statements.push(result); + } + } + var moduleBlock = getInnerMostModuleDeclarationFromDottedModule(node).body; + statementsLocation = ts.moveRangePos(moduleBlock.statements, -1); + } + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + currentNamespaceContainerName = savedCurrentNamespaceContainerName; + currentNamespace = savedCurrentNamespace; + currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName; + var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), + /*location*/ statementsLocation), + /*multiLine*/ true); + ts.setTextRange(block, blockLocation); + // namespace hello.hi.world { + // function foo() {} + // + // // TODO, blah + // } + // + // should be emitted as + // + // var hello; + // (function (hello) { + // var hi; + // (function (hi) { + // var world; + // (function (world) { + // function foo() { } + // // TODO, blah + // })(world = hi.world || (hi.world = {})); + // })(hi = hello.hi || (hello.hi = {})); + // })(hello || (hello = {})); + // We only want to emit comment on the namespace which contains block body itself, not the containing namespaces. + if (body.kind !== 245 /* ModuleBlock */) { + ts.setEmitFlags(block, ts.getEmitFlags(block) | 1536 /* NoComments */); + } + return block; + } + function getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration) { + if (moduleDeclaration.body.kind === 244 /* ModuleDeclaration */) { + var recursiveInnerModule = getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration.body); + return recursiveInnerModule || moduleDeclaration.body; + } + } + /** + * Visits an import declaration, eliding it if it is not referenced. + * + * @param node The import declaration node. + */ + function visitImportDeclaration(node) { + if (!node.importClause) { + // Do not elide a side-effect only import declaration. + // import "foo"; + return node; + } + // Elide the declaration if the import clause was elided. + var importClause = ts.visitNode(node.importClause, visitImportClause, ts.isImportClause); + return importClause + ? ts.updateImportDeclaration(node, + /*decorators*/ undefined, + /*modifiers*/ undefined, importClause, node.moduleSpecifier) + : undefined; + } + /** + * Visits an import clause, eliding it if it is not referenced. + * + * @param node The import clause node. + */ + function visitImportClause(node) { + // Elide the import clause if we elide both its name and its named bindings. + var name = resolver.isReferencedAliasDeclaration(node) ? node.name : undefined; + var namedBindings = ts.visitNode(node.namedBindings, visitNamedImportBindings, ts.isNamedImportBindings); + return (name || namedBindings) ? ts.updateImportClause(node, name, namedBindings) : undefined; + } + /** + * Visits named import bindings, eliding it if it is not referenced. + * + * @param node The named import bindings node. + */ + function visitNamedImportBindings(node) { + if (node.kind === 251 /* NamespaceImport */) { + // Elide a namespace import if it is not referenced. + return resolver.isReferencedAliasDeclaration(node) ? node : undefined; + } + else { + // Elide named imports if all of its import specifiers are elided. + var elements = ts.visitNodes(node.elements, visitImportSpecifier, ts.isImportSpecifier); + return ts.some(elements) ? ts.updateNamedImports(node, elements) : undefined; + } + } + /** + * Visits an import specifier, eliding it if it is not referenced. + * + * @param node The import specifier node. + */ + function visitImportSpecifier(node) { + // Elide an import specifier if it is not referenced. + return resolver.isReferencedAliasDeclaration(node) ? node : undefined; + } + /** + * Visits an export assignment, eliding it if it does not contain a clause that resolves + * to a value. + * + * @param node The export assignment node. + */ + function visitExportAssignment(node) { + // Elide the export assignment if it does not reference a value. + return resolver.isValueAliasDeclaration(node) + ? ts.visitEachChild(node, visitor, context) + : undefined; + } + /** + * Visits an export declaration, eliding it if it does not contain a clause that resolves + * to a value. + * + * @param node The export declaration node. + */ + function visitExportDeclaration(node) { + if (!node.exportClause) { + // Elide a star export if the module it references does not export a value. + return compilerOptions.isolatedModules || resolver.moduleExportsSomeValue(node.moduleSpecifier) ? node : undefined; + } + if (!resolver.isValueAliasDeclaration(node)) { + // Elide the export declaration if it does not export a value. + return undefined; + } + // Elide the export declaration if all of its named exports are elided. + var exportClause = ts.visitNode(node.exportClause, visitNamedExports, ts.isNamedExports); + return exportClause + ? ts.updateExportDeclaration(node, + /*decorators*/ undefined, + /*modifiers*/ undefined, exportClause, node.moduleSpecifier) + : undefined; + } + /** + * Visits named exports, eliding it if it does not contain an export specifier that + * resolves to a value. + * + * @param node The named exports node. + */ + function visitNamedExports(node) { + // Elide the named exports if all of its export specifiers were elided. + var elements = ts.visitNodes(node.elements, visitExportSpecifier, ts.isExportSpecifier); + return ts.some(elements) ? ts.updateNamedExports(node, elements) : undefined; + } + /** + * Visits an export specifier, eliding it if it does not resolve to a value. + * + * @param node The export specifier node. + */ + function visitExportSpecifier(node) { + // Elide an export specifier if it does not reference a value. + return resolver.isValueAliasDeclaration(node) ? node : undefined; + } + /** + * Determines whether to emit an import equals declaration. + * + * @param node The import equals declaration node. + */ + function shouldEmitImportEqualsDeclaration(node) { + // preserve old compiler's behavior: emit 'var' for import declaration (even if we do not consider them referenced) when + // - current file is not external module + // - import declaration is top level and target is value imported by entity name + return resolver.isReferencedAliasDeclaration(node) + || (!ts.isExternalModule(currentSourceFile) + && resolver.isTopLevelValueImportEqualsWithEntityName(node)); + } + /** + * Visits an import equals declaration. + * + * @param node The import equals declaration node. + */ + function visitImportEqualsDeclaration(node) { + if (ts.isExternalModuleImportEqualsDeclaration(node)) { + // Elide external module `import=` if it is not referenced. + return resolver.isReferencedAliasDeclaration(node) + ? ts.visitEachChild(node, visitor, context) + : undefined; + } + if (!shouldEmitImportEqualsDeclaration(node)) { + return undefined; + } + var moduleReference = ts.createExpressionFromEntityName(node.moduleReference); + ts.setEmitFlags(moduleReference, 1536 /* NoComments */ | 2048 /* NoNestedComments */); + if (isNamedExternalModuleExport(node) || !isExportOfNamespace(node)) { + // export var ${name} = ${moduleReference}; + // var ${name} = ${moduleReference}; + return ts.setOriginalNode(ts.setTextRange(ts.createVariableStatement(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.createVariableDeclarationList([ + ts.setOriginalNode(ts.createVariableDeclaration(node.name, + /*type*/ undefined, moduleReference), node) + ])), node), node); + } + else { + // exports.${name} = ${moduleReference}; + return ts.setOriginalNode(createNamespaceExport(node.name, moduleReference, node), node); + } + } + /** + * Gets a value indicating whether the node is exported from a namespace. + * + * @param node The node to test. + */ + function isExportOfNamespace(node) { + return currentNamespace !== undefined && ts.hasModifier(node, 1 /* Export */); + } + /** + * Gets a value indicating whether the node is exported from an external module. + * + * @param node The node to test. + */ + function isExternalModuleExport(node) { + return currentNamespace === undefined && ts.hasModifier(node, 1 /* Export */); + } + /** + * Gets a value indicating whether the node is a named export from an external module. + * + * @param node The node to test. + */ + function isNamedExternalModuleExport(node) { + return isExternalModuleExport(node) + && !ts.hasModifier(node, 512 /* Default */); + } + /** + * Gets a value indicating whether the node is the default export of an external module. + * + * @param node The node to test. + */ + function isDefaultExternalModuleExport(node) { + return isExternalModuleExport(node) + && ts.hasModifier(node, 512 /* Default */); + } + /** + * Creates a statement for the provided expression. This is used in calls to `map`. + */ + function expressionToStatement(expression) { + return ts.createExpressionStatement(expression); + } + function addExportMemberAssignment(statements, node) { + var expression = ts.createAssignment(ts.getExternalModuleOrNamespaceExportName(currentNamespaceContainerName, node, /*allowComments*/ false, /*allowSourceMaps*/ true), ts.getLocalName(node)); + ts.setSourceMapRange(expression, ts.createRange(node.name ? node.name.pos : node.pos, node.end)); + var statement = ts.createExpressionStatement(expression); + ts.setSourceMapRange(statement, ts.createRange(-1, node.end)); + statements.push(statement); + } + function createNamespaceExport(exportName, exportValue, location) { + return ts.setTextRange(ts.createExpressionStatement(ts.createAssignment(ts.getNamespaceMemberName(currentNamespaceContainerName, exportName, /*allowComments*/ false, /*allowSourceMaps*/ true), exportValue)), location); + } + function createNamespaceExportExpression(exportName, exportValue, location) { + return ts.setTextRange(ts.createAssignment(getNamespaceMemberNameWithSourceMapsAndWithoutComments(exportName), exportValue), location); + } + function getNamespaceMemberNameWithSourceMapsAndWithoutComments(name) { + return ts.getNamespaceMemberName(currentNamespaceContainerName, name, /*allowComments*/ false, /*allowSourceMaps*/ true); + } + /** + * Gets the declaration name used inside of a namespace or enum. + */ + function getNamespaceParameterName(node) { + var name = ts.getGeneratedNameForNode(node); + ts.setSourceMapRange(name, node.name); + return name; + } + /** + * Gets the expression used to refer to a namespace or enum within the body + * of its declaration. + */ + function getNamespaceContainerName(node) { + return ts.getGeneratedNameForNode(node); + } + /** + * Gets a local alias for a class declaration if it is a decorated class with an internal + * reference to the static side of the class. This is necessary to avoid issues with + * double-binding semantics for the class name. + */ + function getClassAliasIfNeeded(node) { + if (resolver.getNodeCheckFlags(node) & 16777216 /* ClassWithConstructorReference */) { + enableSubstitutionForClassAliases(); + var classAlias = ts.createUniqueName(node.name && !ts.isGeneratedIdentifier(node.name) ? ts.idText(node.name) : "default"); + classAliases[ts.getOriginalNodeId(node)] = classAlias; + hoistVariableDeclaration(classAlias); + return classAlias; + } + } + function getClassPrototype(node) { + return ts.createPropertyAccess(ts.getDeclarationName(node), "prototype"); + } + function getClassMemberPrefix(node, member) { + return ts.hasModifier(member, 32 /* Static */) + ? ts.getDeclarationName(node) + : getClassPrototype(node); + } + function enableSubstitutionForNonQualifiedEnumMembers() { + if ((enabledSubstitutions & 8 /* NonQualifiedEnumMembers */) === 0) { + enabledSubstitutions |= 8 /* NonQualifiedEnumMembers */; + context.enableSubstitution(72 /* Identifier */); + } + } + function enableSubstitutionForClassAliases() { + if ((enabledSubstitutions & 1 /* ClassAliases */) === 0) { + enabledSubstitutions |= 1 /* ClassAliases */; + // We need to enable substitutions for identifiers. This allows us to + // substitute class names inside of a class declaration. + context.enableSubstitution(72 /* Identifier */); + // Keep track of class aliases. + classAliases = []; + } + } + function enableSubstitutionForNamespaceExports() { + if ((enabledSubstitutions & 2 /* NamespaceExports */) === 0) { + enabledSubstitutions |= 2 /* NamespaceExports */; + // We need to enable substitutions for identifiers and shorthand property assignments. This allows us to + // substitute the names of exported members of a namespace. + context.enableSubstitution(72 /* Identifier */); + context.enableSubstitution(276 /* ShorthandPropertyAssignment */); + // We need to be notified when entering and exiting namespaces. + context.enableEmitNotification(244 /* ModuleDeclaration */); + } + } + function isTransformedModuleDeclaration(node) { + return ts.getOriginalNode(node).kind === 244 /* ModuleDeclaration */; + } + function isTransformedEnumDeclaration(node) { + return ts.getOriginalNode(node).kind === 243 /* EnumDeclaration */; + } + /** + * Hook for node emit. + * + * @param hint A hint as to the intended usage of the node. + * @param node The node to emit. + * @param emit A callback used to emit the node in the printer. + */ + function onEmitNode(hint, node, emitCallback) { + var savedApplicableSubstitutions = applicableSubstitutions; + var savedCurrentSourceFile = currentSourceFile; + if (ts.isSourceFile(node)) { + currentSourceFile = node; + } + if (enabledSubstitutions & 2 /* NamespaceExports */ && isTransformedModuleDeclaration(node)) { + applicableSubstitutions |= 2 /* NamespaceExports */; + } + if (enabledSubstitutions & 8 /* NonQualifiedEnumMembers */ && isTransformedEnumDeclaration(node)) { + applicableSubstitutions |= 8 /* NonQualifiedEnumMembers */; + } + previousOnEmitNode(hint, node, emitCallback); + applicableSubstitutions = savedApplicableSubstitutions; + currentSourceFile = savedCurrentSourceFile; + } + /** + * Hooks node substitutions. + * + * @param hint A hint as to the intended usage of the node. + * @param node The node to substitute. + */ + function onSubstituteNode(hint, node) { + node = previousOnSubstituteNode(hint, node); + if (hint === 1 /* Expression */) { + return substituteExpression(node); + } + else if (ts.isShorthandPropertyAssignment(node)) { + return substituteShorthandPropertyAssignment(node); + } + return node; + } + function substituteShorthandPropertyAssignment(node) { + if (enabledSubstitutions & 2 /* NamespaceExports */) { + var name = node.name; + var exportedName = trySubstituteNamespaceExportedName(name); + if (exportedName) { + // A shorthand property with an assignment initializer is probably part of a + // destructuring assignment + if (node.objectAssignmentInitializer) { + var initializer = ts.createAssignment(exportedName, node.objectAssignmentInitializer); + return ts.setTextRange(ts.createPropertyAssignment(name, initializer), node); + } + return ts.setTextRange(ts.createPropertyAssignment(name, exportedName), node); + } + } + return node; + } + function substituteExpression(node) { + switch (node.kind) { + case 72 /* Identifier */: + return substituteExpressionIdentifier(node); + case 189 /* PropertyAccessExpression */: + return substitutePropertyAccessExpression(node); + case 190 /* ElementAccessExpression */: + return substituteElementAccessExpression(node); + } + return node; + } + function substituteExpressionIdentifier(node) { + return trySubstituteClassAlias(node) + || trySubstituteNamespaceExportedName(node) + || node; + } + function trySubstituteClassAlias(node) { + if (enabledSubstitutions & 1 /* ClassAliases */) { + if (resolver.getNodeCheckFlags(node) & 33554432 /* ConstructorReferenceInClass */) { + // Due to the emit for class decorators, any reference to the class from inside of the class body + // must instead be rewritten to point to a temporary variable to avoid issues with the double-bind + // behavior of class names in ES6. + // Also, when emitting statics for class expressions, we must substitute a class alias for + // constructor references in static property initializers. + var declaration = resolver.getReferencedValueDeclaration(node); + if (declaration) { + var classAlias = classAliases[declaration.id]; // TODO: GH#18217 + if (classAlias) { + var clone_1 = ts.getSynthesizedClone(classAlias); + ts.setSourceMapRange(clone_1, node); + ts.setCommentRange(clone_1, node); + return clone_1; + } + } + } + } + return undefined; + } + function trySubstituteNamespaceExportedName(node) { + // If this is explicitly a local name, do not substitute. + if (enabledSubstitutions & applicableSubstitutions && !ts.isGeneratedIdentifier(node) && !ts.isLocalName(node)) { + // If we are nested within a namespace declaration, we may need to qualifiy + // an identifier that is exported from a merged namespace. + var container = resolver.getReferencedExportContainer(node, /*prefixLocals*/ false); + if (container && container.kind !== 279 /* SourceFile */) { + var substitute = (applicableSubstitutions & 2 /* NamespaceExports */ && container.kind === 244 /* ModuleDeclaration */) || + (applicableSubstitutions & 8 /* NonQualifiedEnumMembers */ && container.kind === 243 /* EnumDeclaration */); + if (substitute) { + return ts.setTextRange(ts.createPropertyAccess(ts.getGeneratedNameForNode(container), node), + /*location*/ node); + } + } + } + return undefined; + } + function substitutePropertyAccessExpression(node) { + return substituteConstantValue(node); + } + function substituteElementAccessExpression(node) { + return substituteConstantValue(node); + } + function substituteConstantValue(node) { + var constantValue = tryGetConstEnumValue(node); + if (constantValue !== undefined) { + // track the constant value on the node for the printer in needsDotDotForPropertyAccess + ts.setConstantValue(node, constantValue); + var substitute = ts.createLiteral(constantValue); + if (!compilerOptions.removeComments) { + var propertyName = ts.isPropertyAccessExpression(node) + ? ts.declarationNameToString(node.name) + : ts.getTextOfNode(node.argumentExpression); + ts.addSyntheticTrailingComment(substitute, 3 /* MultiLineCommentTrivia */, " " + propertyName + " "); + } + return substitute; + } + return node; + } + function tryGetConstEnumValue(node) { + if (compilerOptions.isolatedModules) { + return undefined; + } + return ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node) ? resolver.getConstantValue(node) : undefined; + } + } + ts.transformTypeScript = transformTypeScript; + function createDecorateHelper(context, decoratorExpressions, target, memberName, descriptor, location) { + var argumentsArray = []; + argumentsArray.push(ts.createArrayLiteral(decoratorExpressions, /*multiLine*/ true)); + argumentsArray.push(target); + if (memberName) { + argumentsArray.push(memberName); + if (descriptor) { + argumentsArray.push(descriptor); + } + } + context.requestEmitHelper(decorateHelper); + return ts.setTextRange(ts.createCall(ts.getHelperName("__decorate"), + /*typeArguments*/ undefined, argumentsArray), location); + } + var decorateHelper = { + name: "typescript:decorate", + scoped: false, + priority: 2, + text: "\n var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n };" + }; + function createMetadataHelper(context, metadataKey, metadataValue) { + context.requestEmitHelper(metadataHelper); + return ts.createCall(ts.getHelperName("__metadata"), + /*typeArguments*/ undefined, [ + ts.createLiteral(metadataKey), + metadataValue + ]); + } + var metadataHelper = { + name: "typescript:metadata", + scoped: false, + priority: 3, + text: "\n var __metadata = (this && this.__metadata) || function (k, v) {\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(k, v);\n };" + }; + function createParamHelper(context, expression, parameterOffset, location) { + context.requestEmitHelper(paramHelper); + return ts.setTextRange(ts.createCall(ts.getHelperName("__param"), + /*typeArguments*/ undefined, [ + ts.createLiteral(parameterOffset), + expression + ]), location); + } + var paramHelper = { + name: "typescript:param", + scoped: false, + priority: 4, + text: "\n var __param = (this && this.__param) || function (paramIndex, decorator) {\n return function (target, key) { decorator(target, key, paramIndex); }\n };" + }; +})(ts || (ts = {})); +/*@internal*/ +var ts; +(function (ts) { + var ES2017SubstitutionFlags; + (function (ES2017SubstitutionFlags) { + /** Enables substitutions for async methods with `super` calls. */ + ES2017SubstitutionFlags[ES2017SubstitutionFlags["AsyncMethodsWithSuper"] = 1] = "AsyncMethodsWithSuper"; + })(ES2017SubstitutionFlags || (ES2017SubstitutionFlags = {})); + function transformES2017(context) { + var resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; + var resolver = context.getEmitResolver(); + var compilerOptions = context.getCompilerOptions(); + var languageVersion = ts.getEmitScriptTarget(compilerOptions); + /** + * Keeps track of whether expression substitution has been enabled for specific edge cases. + * They are persisted between each SourceFile transformation and should not be reset. + */ + var enabledSubstitutions; + /** + * This keeps track of containers where `super` is valid, for use with + * just-in-time substitution for `super` expressions inside of async methods. + */ + var enclosingSuperContainerFlags = 0; + var enclosingFunctionParameterNames; + /** + * Keeps track of property names accessed on super (`super.x`) within async functions. + */ + var capturedSuperProperties; + /** Whether the async function contains an element access on super (`super[x]`). */ + var hasSuperElementAccess; + /** A set of node IDs for generated super accessors (variable statements). */ + var substitutedSuperAccessors = []; + // Save the previous transformation hooks. + var previousOnEmitNode = context.onEmitNode; + var previousOnSubstituteNode = context.onSubstituteNode; + // Set new transformation hooks. + context.onEmitNode = onEmitNode; + context.onSubstituteNode = onSubstituteNode; + return ts.chainBundle(transformSourceFile); + function transformSourceFile(node) { + if (node.isDeclarationFile) { + return node; + } + var visited = ts.visitEachChild(node, visitor, context); + ts.addEmitHelpers(visited, context.readEmitHelpers()); + return visited; + } + function visitor(node) { + if ((node.transformFlags & 16 /* ContainsES2017 */) === 0) { + return node; + } + switch (node.kind) { + case 121 /* AsyncKeyword */: + // ES2017 async modifier should be elided for targets < ES2017 + return undefined; + case 201 /* AwaitExpression */: + return visitAwaitExpression(node); + case 156 /* MethodDeclaration */: + return visitMethodDeclaration(node); + case 239 /* FunctionDeclaration */: + return visitFunctionDeclaration(node); + case 196 /* FunctionExpression */: + return visitFunctionExpression(node); + case 197 /* ArrowFunction */: + return visitArrowFunction(node); + case 189 /* PropertyAccessExpression */: + if (capturedSuperProperties && ts.isPropertyAccessExpression(node) && node.expression.kind === 98 /* SuperKeyword */) { + capturedSuperProperties.set(node.name.escapedText, true); + } + return ts.visitEachChild(node, visitor, context); + case 190 /* ElementAccessExpression */: + if (capturedSuperProperties && node.expression.kind === 98 /* SuperKeyword */) { + hasSuperElementAccess = true; + } + return ts.visitEachChild(node, visitor, context); + default: + return ts.visitEachChild(node, visitor, context); + } + } + function asyncBodyVisitor(node) { + if (ts.isNodeWithPossibleHoistedDeclaration(node)) { + switch (node.kind) { + case 219 /* VariableStatement */: + return visitVariableStatementInAsyncBody(node); + case 225 /* ForStatement */: + return visitForStatementInAsyncBody(node); + case 226 /* ForInStatement */: + return visitForInStatementInAsyncBody(node); + case 227 /* ForOfStatement */: + return visitForOfStatementInAsyncBody(node); + case 274 /* CatchClause */: + return visitCatchClauseInAsyncBody(node); + case 218 /* Block */: + case 232 /* SwitchStatement */: + case 246 /* CaseBlock */: + case 271 /* CaseClause */: + case 272 /* DefaultClause */: + case 235 /* TryStatement */: + case 223 /* DoStatement */: + case 224 /* WhileStatement */: + case 222 /* IfStatement */: + case 231 /* WithStatement */: + case 233 /* LabeledStatement */: + return ts.visitEachChild(node, asyncBodyVisitor, context); + default: + return ts.Debug.assertNever(node, "Unhandled node."); + } + } + return visitor(node); + } + function visitCatchClauseInAsyncBody(node) { + var catchClauseNames = ts.createUnderscoreEscapedMap(); + recordDeclarationName(node.variableDeclaration, catchClauseNames); // TODO: GH#18217 + // names declared in a catch variable are block scoped + var catchClauseUnshadowedNames; + catchClauseNames.forEach(function (_, escapedName) { + if (enclosingFunctionParameterNames.has(escapedName)) { + if (!catchClauseUnshadowedNames) { + catchClauseUnshadowedNames = ts.cloneMap(enclosingFunctionParameterNames); + } + catchClauseUnshadowedNames.delete(escapedName); + } + }); + if (catchClauseUnshadowedNames) { + var savedEnclosingFunctionParameterNames = enclosingFunctionParameterNames; + enclosingFunctionParameterNames = catchClauseUnshadowedNames; + var result = ts.visitEachChild(node, asyncBodyVisitor, context); + enclosingFunctionParameterNames = savedEnclosingFunctionParameterNames; + return result; + } + else { + return ts.visitEachChild(node, asyncBodyVisitor, context); + } + } + function visitVariableStatementInAsyncBody(node) { + if (isVariableDeclarationListWithCollidingName(node.declarationList)) { + var expression = visitVariableDeclarationListWithCollidingNames(node.declarationList, /*hasReceiver*/ false); + return expression ? ts.createExpressionStatement(expression) : undefined; + } + return ts.visitEachChild(node, visitor, context); + } + function visitForInStatementInAsyncBody(node) { + return ts.updateForIn(node, isVariableDeclarationListWithCollidingName(node.initializer) + ? visitVariableDeclarationListWithCollidingNames(node.initializer, /*hasReceiver*/ true) + : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitNode(node.statement, asyncBodyVisitor, ts.isStatement, ts.liftToBlock)); + } + function visitForOfStatementInAsyncBody(node) { + return ts.updateForOf(node, ts.visitNode(node.awaitModifier, visitor, ts.isToken), isVariableDeclarationListWithCollidingName(node.initializer) + ? visitVariableDeclarationListWithCollidingNames(node.initializer, /*hasReceiver*/ true) + : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitNode(node.statement, asyncBodyVisitor, ts.isStatement, ts.liftToBlock)); + } + function visitForStatementInAsyncBody(node) { + var initializer = node.initializer; // TODO: GH#18217 + return ts.updateFor(node, isVariableDeclarationListWithCollidingName(initializer) + ? visitVariableDeclarationListWithCollidingNames(initializer, /*hasReceiver*/ false) + : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.condition, visitor, ts.isExpression), ts.visitNode(node.incrementor, visitor, ts.isExpression), ts.visitNode(node.statement, asyncBodyVisitor, ts.isStatement, ts.liftToBlock)); + } + /** + * Visits an AwaitExpression node. + * + * This function will be called any time a ES2017 await expression is encountered. + * + * @param node The node to visit. + */ + function visitAwaitExpression(node) { + return ts.setOriginalNode(ts.setTextRange(ts.createYield( + /*asteriskToken*/ undefined, ts.visitNode(node.expression, visitor, ts.isExpression)), node), node); + } + /** + * Visits a MethodDeclaration node. + * + * This function will be called when one of the following conditions are met: + * - The node is marked as async + * + * @param node The node to visit. + */ + function visitMethodDeclaration(node) { + return ts.updateMethod(node, + /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, node.name, + /*questionToken*/ undefined, + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, ts.getFunctionFlags(node) & 2 /* Async */ + ? transformAsyncFunctionBody(node) + : ts.visitFunctionBody(node.body, visitor, context)); + } + /** + * Visits a FunctionDeclaration node. + * + * This function will be called when one of the following conditions are met: + * - The node is marked async + * + * @param node The node to visit. + */ + function visitFunctionDeclaration(node) { + return ts.updateFunctionDeclaration(node, + /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, node.name, + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, ts.getFunctionFlags(node) & 2 /* Async */ + ? transformAsyncFunctionBody(node) + : ts.visitFunctionBody(node.body, visitor, context)); + } + /** + * Visits a FunctionExpression node. + * + * This function will be called when one of the following conditions are met: + * - The node is marked async + * + * @param node The node to visit. + */ + function visitFunctionExpression(node) { + return ts.updateFunctionExpression(node, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, node.name, + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, ts.getFunctionFlags(node) & 2 /* Async */ + ? transformAsyncFunctionBody(node) + : ts.visitFunctionBody(node.body, visitor, context)); + } + /** + * Visits an ArrowFunction. + * + * This function will be called when one of the following conditions are met: + * - The node is marked async + * + * @param node The node to visit. + */ + function visitArrowFunction(node) { + return ts.updateArrowFunction(node, ts.visitNodes(node.modifiers, visitor, ts.isModifier), + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, node.equalsGreaterThanToken, ts.getFunctionFlags(node) & 2 /* Async */ + ? transformAsyncFunctionBody(node) + : ts.visitFunctionBody(node.body, visitor, context)); + } + function recordDeclarationName(_a, names) { + var name = _a.name; + if (ts.isIdentifier(name)) { + names.set(name.escapedText, true); + } + else { + for (var _i = 0, _b = name.elements; _i < _b.length; _i++) { + var element = _b[_i]; + if (!ts.isOmittedExpression(element)) { + recordDeclarationName(element, names); + } + } + } + } + function isVariableDeclarationListWithCollidingName(node) { + return !!node + && ts.isVariableDeclarationList(node) + && !(node.flags & 3 /* BlockScoped */) + && node.declarations.some(collidesWithParameterName); + } + function visitVariableDeclarationListWithCollidingNames(node, hasReceiver) { + hoistVariableDeclarationList(node); + var variables = ts.getInitializedVariables(node); + if (variables.length === 0) { + if (hasReceiver) { + return ts.visitNode(ts.convertToAssignmentElementTarget(node.declarations[0].name), visitor, ts.isExpression); + } + return undefined; + } + return ts.inlineExpressions(ts.map(variables, transformInitializedVariable)); + } + function hoistVariableDeclarationList(node) { + ts.forEach(node.declarations, hoistVariable); + } + function hoistVariable(_a) { + var name = _a.name; + if (ts.isIdentifier(name)) { + hoistVariableDeclaration(name); + } + else { + for (var _i = 0, _b = name.elements; _i < _b.length; _i++) { + var element = _b[_i]; + if (!ts.isOmittedExpression(element)) { + hoistVariable(element); + } + } + } + } + function transformInitializedVariable(node) { + var converted = ts.setSourceMapRange(ts.createAssignment(ts.convertToAssignmentElementTarget(node.name), node.initializer), node); + return ts.visitNode(converted, visitor, ts.isExpression); + } + function collidesWithParameterName(_a) { + var name = _a.name; + if (ts.isIdentifier(name)) { + return enclosingFunctionParameterNames.has(name.escapedText); + } + else { + for (var _i = 0, _b = name.elements; _i < _b.length; _i++) { + var element = _b[_i]; + if (!ts.isOmittedExpression(element) && collidesWithParameterName(element)) { + return true; + } + } + } + return false; + } + function transformAsyncFunctionBody(node) { + resumeLexicalEnvironment(); + var original = ts.getOriginalNode(node, ts.isFunctionLike); + var nodeType = original.type; + var promiseConstructor = languageVersion < 2 /* ES2015 */ ? getPromiseConstructor(nodeType) : undefined; + var isArrowFunction = node.kind === 197 /* ArrowFunction */; + var hasLexicalArguments = (resolver.getNodeCheckFlags(node) & 8192 /* CaptureArguments */) !== 0; + // An async function is emit as an outer function that calls an inner + // generator function. To preserve lexical bindings, we pass the current + // `this` and `arguments` objects to `__awaiter`. The generator function + // passed to `__awaiter` is executed inside of the callback to the + // promise constructor. + var savedEnclosingFunctionParameterNames = enclosingFunctionParameterNames; + enclosingFunctionParameterNames = ts.createUnderscoreEscapedMap(); + for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { + var parameter = _a[_i]; + recordDeclarationName(parameter, enclosingFunctionParameterNames); + } + var savedCapturedSuperProperties = capturedSuperProperties; + var savedHasSuperElementAccess = hasSuperElementAccess; + capturedSuperProperties = ts.createUnderscoreEscapedMap(); + hasSuperElementAccess = false; + var result; + if (!isArrowFunction) { + var statements = []; + var statementOffset = ts.addPrologue(statements, node.body.statements, /*ensureUseStrict*/ false, visitor); + statements.push(ts.createReturn(createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, transformAsyncFunctionBodyWorker(node.body, statementOffset)))); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + // Minor optimization, emit `_super` helper to capture `super` access in an arrow. + // This step isn't needed if we eventually transform this to ES5. + var emitSuperHelpers = languageVersion >= 2 /* ES2015 */ && resolver.getNodeCheckFlags(node) & (4096 /* AsyncMethodWithSuperBinding */ | 2048 /* AsyncMethodWithSuper */); + if (emitSuperHelpers) { + enableSubstitutionForAsyncMethodsWithSuper(); + var variableStatement = createSuperAccessVariableStatement(resolver, node, capturedSuperProperties); + substitutedSuperAccessors[ts.getNodeId(variableStatement)] = true; + ts.addStatementsAfterPrologue(statements, [variableStatement]); + } + var block = ts.createBlock(statements, /*multiLine*/ true); + ts.setTextRange(block, node.body); + if (emitSuperHelpers && hasSuperElementAccess) { + // Emit helpers for super element access expressions (`super[x]`). + if (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) { + ts.addEmitHelper(block, ts.advancedAsyncSuperHelper); + } + else if (resolver.getNodeCheckFlags(node) & 2048 /* AsyncMethodWithSuper */) { + ts.addEmitHelper(block, ts.asyncSuperHelper); + } + } + result = block; + } + else { + var expression = createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, transformAsyncFunctionBodyWorker(node.body)); + var declarations = endLexicalEnvironment(); + if (ts.some(declarations)) { + var block = ts.convertToFunctionBody(expression); + result = ts.updateBlock(block, ts.setTextRange(ts.createNodeArray(ts.concatenate(declarations, block.statements)), block.statements)); + } + else { + result = expression; + } + } + enclosingFunctionParameterNames = savedEnclosingFunctionParameterNames; + capturedSuperProperties = savedCapturedSuperProperties; + hasSuperElementAccess = savedHasSuperElementAccess; + return result; + } + function transformAsyncFunctionBodyWorker(body, start) { + if (ts.isBlock(body)) { + return ts.updateBlock(body, ts.visitNodes(body.statements, asyncBodyVisitor, ts.isStatement, start)); + } + else { + return ts.convertToFunctionBody(ts.visitNode(body, asyncBodyVisitor, ts.isConciseBody)); + } + } + function getPromiseConstructor(type) { + var typeName = type && ts.getEntityNameFromTypeNode(type); + if (typeName && ts.isEntityName(typeName)) { + var serializationKind = resolver.getTypeReferenceSerializationKind(typeName); + if (serializationKind === ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue + || serializationKind === ts.TypeReferenceSerializationKind.Unknown) { + return typeName; + } + } + return undefined; + } + function enableSubstitutionForAsyncMethodsWithSuper() { + if ((enabledSubstitutions & 1 /* AsyncMethodsWithSuper */) === 0) { + enabledSubstitutions |= 1 /* AsyncMethodsWithSuper */; + // We need to enable substitutions for call, property access, and element access + // if we need to rewrite super calls. + context.enableSubstitution(191 /* CallExpression */); + context.enableSubstitution(189 /* PropertyAccessExpression */); + context.enableSubstitution(190 /* ElementAccessExpression */); + // We need to be notified when entering and exiting declarations that bind super. + context.enableEmitNotification(240 /* ClassDeclaration */); + context.enableEmitNotification(156 /* MethodDeclaration */); + context.enableEmitNotification(158 /* GetAccessor */); + context.enableEmitNotification(159 /* SetAccessor */); + context.enableEmitNotification(157 /* Constructor */); + // We need to be notified when entering the generated accessor arrow functions. + context.enableEmitNotification(219 /* VariableStatement */); + } + } + /** + * Hook for node emit. + * + * @param hint A hint as to the intended usage of the node. + * @param node The node to emit. + * @param emit A callback used to emit the node in the printer. + */ + function onEmitNode(hint, node, emitCallback) { + // If we need to support substitutions for `super` in an async method, + // we should track it here. + if (enabledSubstitutions & 1 /* AsyncMethodsWithSuper */ && isSuperContainer(node)) { + var superContainerFlags = resolver.getNodeCheckFlags(node) & (2048 /* AsyncMethodWithSuper */ | 4096 /* AsyncMethodWithSuperBinding */); + if (superContainerFlags !== enclosingSuperContainerFlags) { + var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags; + enclosingSuperContainerFlags = superContainerFlags; + previousOnEmitNode(hint, node, emitCallback); + enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags; + return; + } + } + // Disable substitution in the generated super accessor itself. + else if (enabledSubstitutions && substitutedSuperAccessors[ts.getNodeId(node)]) { + var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags; + enclosingSuperContainerFlags = 0; + previousOnEmitNode(hint, node, emitCallback); + enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags; + return; + } + previousOnEmitNode(hint, node, emitCallback); + } + /** + * Hooks node substitutions. + * + * @param hint A hint as to the intended usage of the node. + * @param node The node to substitute. + */ + function onSubstituteNode(hint, node) { + node = previousOnSubstituteNode(hint, node); + if (hint === 1 /* Expression */ && enclosingSuperContainerFlags) { + return substituteExpression(node); + } + return node; + } + function substituteExpression(node) { + switch (node.kind) { + case 189 /* PropertyAccessExpression */: + return substitutePropertyAccessExpression(node); + case 190 /* ElementAccessExpression */: + return substituteElementAccessExpression(node); + case 191 /* CallExpression */: + return substituteCallExpression(node); + } + return node; + } + function substitutePropertyAccessExpression(node) { + if (node.expression.kind === 98 /* SuperKeyword */) { + return ts.setTextRange(ts.createPropertyAccess(ts.createFileLevelUniqueName("_super"), node.name), node); + } + return node; + } + function substituteElementAccessExpression(node) { + if (node.expression.kind === 98 /* SuperKeyword */) { + return createSuperElementAccessInAsyncMethod(node.argumentExpression, node); + } + return node; + } + function substituteCallExpression(node) { + var expression = node.expression; + if (ts.isSuperProperty(expression)) { + var argumentExpression = ts.isPropertyAccessExpression(expression) + ? substitutePropertyAccessExpression(expression) + : substituteElementAccessExpression(expression); + return ts.createCall(ts.createPropertyAccess(argumentExpression, "call"), + /*typeArguments*/ undefined, [ + ts.createThis() + ].concat(node.arguments)); + } + return node; + } + function isSuperContainer(node) { + var kind = node.kind; + return kind === 240 /* ClassDeclaration */ + || kind === 157 /* Constructor */ + || kind === 156 /* MethodDeclaration */ + || kind === 158 /* GetAccessor */ + || kind === 159 /* SetAccessor */; + } + function createSuperElementAccessInAsyncMethod(argumentExpression, location) { + if (enclosingSuperContainerFlags & 4096 /* AsyncMethodWithSuperBinding */) { + return ts.setTextRange(ts.createPropertyAccess(ts.createCall(ts.createFileLevelUniqueName("_superIndex"), + /*typeArguments*/ undefined, [argumentExpression]), "value"), location); + } + else { + return ts.setTextRange(ts.createCall(ts.createFileLevelUniqueName("_superIndex"), + /*typeArguments*/ undefined, [argumentExpression]), location); + } + } + } + ts.transformES2017 = transformES2017; + /** Creates a variable named `_super` with accessor properties for the given property names. */ + function createSuperAccessVariableStatement(resolver, node, names) { + // Create a variable declaration with a getter/setter (if binding) definition for each name: + // const _super = Object.create(null, { x: { get: () => super.x, set: (v) => super.x = v }, ... }); + var hasBinding = (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) !== 0; + var accessors = []; + names.forEach(function (_, key) { + var name = ts.unescapeLeadingUnderscores(key); + var getterAndSetter = []; + getterAndSetter.push(ts.createPropertyAssignment("get", ts.createArrowFunction( + /* modifiers */ undefined, + /* typeParameters */ undefined, + /* parameters */ [], + /* type */ undefined, + /* equalsGreaterThanToken */ undefined, ts.createPropertyAccess(ts.createSuper(), name)))); + if (hasBinding) { + getterAndSetter.push(ts.createPropertyAssignment("set", ts.createArrowFunction( + /* modifiers */ undefined, + /* typeParameters */ undefined, + /* parameters */ [ + ts.createParameter( + /* decorators */ undefined, + /* modifiers */ undefined, + /* dotDotDotToken */ undefined, "v", + /* questionToken */ undefined, + /* type */ undefined, + /* initializer */ undefined) + ], + /* type */ undefined, + /* equalsGreaterThanToken */ undefined, ts.createAssignment(ts.createPropertyAccess(ts.createSuper(), name), ts.createIdentifier("v"))))); + } + accessors.push(ts.createPropertyAssignment(name, ts.createObjectLiteral(getterAndSetter))); + }); + return ts.createVariableStatement( + /* modifiers */ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(ts.createFileLevelUniqueName("_super"), + /* type */ undefined, ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "create"), + /* typeArguments */ undefined, [ + ts.createNull(), + ts.createObjectLiteral(accessors, /* multiline */ true) + ])) + ], 2 /* Const */)); + } + ts.createSuperAccessVariableStatement = createSuperAccessVariableStatement; + var awaiterHelper = { + name: "typescript:awaiter", + scoped: false, + priority: 5, + text: "\n var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n };" + }; + function createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, body) { + context.requestEmitHelper(awaiterHelper); + var generatorFunc = ts.createFunctionExpression( + /*modifiers*/ undefined, ts.createToken(40 /* AsteriskToken */), + /*name*/ undefined, + /*typeParameters*/ undefined, + /*parameters*/ [], + /*type*/ undefined, body); + // Mark this node as originally an async function + (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 262144 /* AsyncFunctionBody */ | 524288 /* ReuseTempVariableScope */; + return ts.createCall(ts.getHelperName("__awaiter"), + /*typeArguments*/ undefined, [ + ts.createThis(), + hasLexicalArguments ? ts.createIdentifier("arguments") : ts.createVoidZero(), + promiseConstructor ? ts.createExpressionFromEntityName(promiseConstructor) : ts.createVoidZero(), + generatorFunc + ]); + } + ts.asyncSuperHelper = { + name: "typescript:async-super", + scoped: true, + text: ts.helperString(__makeTemplateObject(["\n const ", " = name => super[name];"], ["\n const ", " = name => super[name];"]), "_superIndex") + }; + ts.advancedAsyncSuperHelper = { + name: "typescript:advanced-async-super", + scoped: true, + text: ts.helperString(__makeTemplateObject(["\n const ", " = (function (geti, seti) {\n const cache = Object.create(null);\n return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } });\n })(name => super[name], (name, value) => super[name] = value);"], ["\n const ", " = (function (geti, seti) {\n const cache = Object.create(null);\n return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } });\n })(name => super[name], (name, value) => super[name] = value);"]), "_superIndex") + }; +})(ts || (ts = {})); +/*@internal*/ +var ts; +(function (ts) { + var ESNextSubstitutionFlags; + (function (ESNextSubstitutionFlags) { + /** Enables substitutions for async methods with `super` calls. */ + ESNextSubstitutionFlags[ESNextSubstitutionFlags["AsyncMethodsWithSuper"] = 1] = "AsyncMethodsWithSuper"; + })(ESNextSubstitutionFlags || (ESNextSubstitutionFlags = {})); + function transformESNext(context) { + var resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; + var resolver = context.getEmitResolver(); + var compilerOptions = context.getCompilerOptions(); + var languageVersion = ts.getEmitScriptTarget(compilerOptions); + var previousOnEmitNode = context.onEmitNode; + context.onEmitNode = onEmitNode; + var previousOnSubstituteNode = context.onSubstituteNode; + context.onSubstituteNode = onSubstituteNode; + var enabledSubstitutions; + var enclosingFunctionFlags; + var enclosingSuperContainerFlags = 0; + /** Keeps track of property names accessed on super (`super.x`) within async functions. */ + var capturedSuperProperties; + /** Whether the async function contains an element access on super (`super[x]`). */ + var hasSuperElementAccess; + /** A set of node IDs for generated super accessors. */ + var substitutedSuperAccessors = []; + return ts.chainBundle(transformSourceFile); + function transformSourceFile(node) { + if (node.isDeclarationFile) { + return node; + } + var visited = ts.visitEachChild(node, visitor, context); + ts.addEmitHelpers(visited, context.readEmitHelpers()); + return visited; + } + function visitor(node) { + return visitorWorker(node, /*noDestructuringValue*/ false); + } + function visitorNoDestructuringValue(node) { + return visitorWorker(node, /*noDestructuringValue*/ true); + } + function visitorNoAsyncModifier(node) { + if (node.kind === 121 /* AsyncKeyword */) { + return undefined; + } + return node; + } + function visitorWorker(node, noDestructuringValue) { + if ((node.transformFlags & 8 /* ContainsESNext */) === 0) { + return node; + } + switch (node.kind) { + case 201 /* AwaitExpression */: + return visitAwaitExpression(node); + case 207 /* YieldExpression */: + return visitYieldExpression(node); + case 230 /* ReturnStatement */: + return visitReturnStatement(node); + case 233 /* LabeledStatement */: + return visitLabeledStatement(node); + case 188 /* ObjectLiteralExpression */: + return visitObjectLiteralExpression(node); + case 204 /* BinaryExpression */: + return visitBinaryExpression(node, noDestructuringValue); + case 237 /* VariableDeclaration */: + return visitVariableDeclaration(node); + case 227 /* ForOfStatement */: + return visitForOfStatement(node, /*outermostLabeledStatement*/ undefined); + case 225 /* ForStatement */: + return visitForStatement(node); + case 200 /* VoidExpression */: + return visitVoidExpression(node); + case 157 /* Constructor */: + return visitConstructorDeclaration(node); + case 156 /* MethodDeclaration */: + return visitMethodDeclaration(node); + case 158 /* GetAccessor */: + return visitGetAccessorDeclaration(node); + case 159 /* SetAccessor */: + return visitSetAccessorDeclaration(node); + case 239 /* FunctionDeclaration */: + return visitFunctionDeclaration(node); + case 196 /* FunctionExpression */: + return visitFunctionExpression(node); + case 197 /* ArrowFunction */: + return visitArrowFunction(node); + case 151 /* Parameter */: + return visitParameter(node); + case 221 /* ExpressionStatement */: + return visitExpressionStatement(node); + case 195 /* ParenthesizedExpression */: + return visitParenthesizedExpression(node, noDestructuringValue); + case 274 /* CatchClause */: + return visitCatchClause(node); + case 189 /* PropertyAccessExpression */: + if (capturedSuperProperties && ts.isPropertyAccessExpression(node) && node.expression.kind === 98 /* SuperKeyword */) { + capturedSuperProperties.set(node.name.escapedText, true); + } + return ts.visitEachChild(node, visitor, context); + case 190 /* ElementAccessExpression */: + if (capturedSuperProperties && node.expression.kind === 98 /* SuperKeyword */) { + hasSuperElementAccess = true; + } + return ts.visitEachChild(node, visitor, context); + default: + return ts.visitEachChild(node, visitor, context); + } + } + function visitAwaitExpression(node) { + if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */) { + return ts.setOriginalNode(ts.setTextRange(ts.createYield(createAwaitHelper(context, ts.visitNode(node.expression, visitor, ts.isExpression))), + /*location*/ node), node); + } + return ts.visitEachChild(node, visitor, context); + } + function visitYieldExpression(node) { + if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */) { + if (node.asteriskToken) { + var expression = ts.visitNode(node.expression, visitor, ts.isExpression); + return ts.setOriginalNode(ts.setTextRange(ts.createYield(createAwaitHelper(context, ts.updateYield(node, node.asteriskToken, createAsyncDelegatorHelper(context, createAsyncValuesHelper(context, expression, expression), expression)))), node), node); + } + return ts.setOriginalNode(ts.setTextRange(ts.createYield(createDownlevelAwait(node.expression + ? ts.visitNode(node.expression, visitor, ts.isExpression) + : ts.createVoidZero())), node), node); + } + return ts.visitEachChild(node, visitor, context); + } + function visitReturnStatement(node) { + if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */) { + return ts.updateReturn(node, createDownlevelAwait(node.expression ? ts.visitNode(node.expression, visitor, ts.isExpression) : ts.createVoidZero())); + } + return ts.visitEachChild(node, visitor, context); + } + function visitLabeledStatement(node) { + if (enclosingFunctionFlags & 2 /* Async */) { + var statement = ts.unwrapInnermostStatementOfLabel(node); + if (statement.kind === 227 /* ForOfStatement */ && statement.awaitModifier) { + return visitForOfStatement(statement, node); + } + return ts.restoreEnclosingLabel(ts.visitEachChild(statement, visitor, context), node); + } + return ts.visitEachChild(node, visitor, context); + } + function chunkObjectLiteralElements(elements) { + var chunkObject; + var objects = []; + for (var _i = 0, elements_4 = elements; _i < elements_4.length; _i++) { + var e = elements_4[_i]; + if (e.kind === 277 /* SpreadAssignment */) { + if (chunkObject) { + objects.push(ts.createObjectLiteral(chunkObject)); + chunkObject = undefined; + } + var target = e.expression; + objects.push(ts.visitNode(target, visitor, ts.isExpression)); + } + else { + chunkObject = ts.append(chunkObject, e.kind === 275 /* PropertyAssignment */ + ? ts.createPropertyAssignment(e.name, ts.visitNode(e.initializer, visitor, ts.isExpression)) + : ts.visitNode(e, visitor, ts.isObjectLiteralElementLike)); + } + } + if (chunkObject) { + objects.push(ts.createObjectLiteral(chunkObject)); + } + return objects; + } + function visitObjectLiteralExpression(node) { + if (node.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { + // spread elements emit like so: + // non-spread elements are chunked together into object literals, and then all are passed to __assign: + // { a, ...o, b } => __assign({a}, o, {b}); + // If the first element is a spread element, then the first argument to __assign is {}: + // { ...o, a, b, ...o2 } => __assign({}, o, {a, b}, o2) + var objects = chunkObjectLiteralElements(node.properties); + if (objects.length && objects[0].kind !== 188 /* ObjectLiteralExpression */) { + objects.unshift(ts.createObjectLiteral()); + } + return createAssignHelper(context, objects); + } + return ts.visitEachChild(node, visitor, context); + } + function visitExpressionStatement(node) { + return ts.visitEachChild(node, visitorNoDestructuringValue, context); + } + function visitParenthesizedExpression(node, noDestructuringValue) { + return ts.visitEachChild(node, noDestructuringValue ? visitorNoDestructuringValue : visitor, context); + } + function visitCatchClause(node) { + if (!node.variableDeclaration) { + return ts.updateCatchClause(node, ts.createVariableDeclaration(ts.createTempVariable(/*recordTempVariable*/ undefined)), ts.visitNode(node.block, visitor, ts.isBlock)); + } + return ts.visitEachChild(node, visitor, context); + } + /** + * Visits a BinaryExpression that contains a destructuring assignment. + * + * @param node A BinaryExpression node. + */ + function visitBinaryExpression(node, noDestructuringValue) { + if (ts.isDestructuringAssignment(node) && node.left.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { + return ts.flattenDestructuringAssignment(node, visitor, context, 1 /* ObjectRest */, !noDestructuringValue); + } + else if (node.operatorToken.kind === 27 /* CommaToken */) { + return ts.updateBinary(node, ts.visitNode(node.left, visitorNoDestructuringValue, ts.isExpression), ts.visitNode(node.right, noDestructuringValue ? visitorNoDestructuringValue : visitor, ts.isExpression)); + } + return ts.visitEachChild(node, visitor, context); + } + /** + * Visits a VariableDeclaration node with a binding pattern. + * + * @param node A VariableDeclaration node. + */ + function visitVariableDeclaration(node) { + // If we are here it is because the name contains a binding pattern with a rest somewhere in it. + if (ts.isBindingPattern(node.name) && node.name.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { + return ts.flattenDestructuringBinding(node, visitor, context, 1 /* ObjectRest */); + } + return ts.visitEachChild(node, visitor, context); + } + function visitForStatement(node) { + return ts.updateFor(node, ts.visitNode(node.initializer, visitorNoDestructuringValue, ts.isForInitializer), ts.visitNode(node.condition, visitor, ts.isExpression), ts.visitNode(node.incrementor, visitor, ts.isExpression), ts.visitNode(node.statement, visitor, ts.isStatement)); + } + function visitVoidExpression(node) { + return ts.visitEachChild(node, visitorNoDestructuringValue, context); + } + /** + * Visits a ForOfStatement and converts it into a ES2015-compatible ForOfStatement. + * + * @param node A ForOfStatement. + */ + function visitForOfStatement(node, outermostLabeledStatement) { + if (node.initializer.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { + node = transformForOfStatementWithObjectRest(node); + } + if (node.awaitModifier) { + return transformForAwaitOfStatement(node, outermostLabeledStatement); + } + else { + return ts.restoreEnclosingLabel(ts.visitEachChild(node, visitor, context), outermostLabeledStatement); + } + } + function transformForOfStatementWithObjectRest(node) { + var initializerWithoutParens = ts.skipParentheses(node.initializer); + if (ts.isVariableDeclarationList(initializerWithoutParens) || ts.isAssignmentPattern(initializerWithoutParens)) { + var bodyLocation = void 0; + var statementsLocation = void 0; + var temp = ts.createTempVariable(/*recordTempVariable*/ undefined); + var statements = [ts.createForOfBindingStatement(initializerWithoutParens, temp)]; + if (ts.isBlock(node.statement)) { + ts.addRange(statements, node.statement.statements); + bodyLocation = node.statement; + statementsLocation = node.statement.statements; + } + else if (node.statement) { + ts.append(statements, node.statement); + bodyLocation = node.statement; + statementsLocation = node.statement; + } + return ts.updateForOf(node, node.awaitModifier, ts.setTextRange(ts.createVariableDeclarationList([ + ts.setTextRange(ts.createVariableDeclaration(temp), node.initializer) + ], 1 /* Let */), node.initializer), node.expression, ts.setTextRange(ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), statementsLocation), + /*multiLine*/ true), bodyLocation)); + } + return node; + } + function convertForOfStatementHead(node, boundValue) { + var binding = ts.createForOfBindingStatement(node.initializer, boundValue); + var bodyLocation; + var statementsLocation; + var statements = [ts.visitNode(binding, visitor, ts.isStatement)]; + var statement = ts.visitNode(node.statement, visitor, ts.isStatement); + if (ts.isBlock(statement)) { + ts.addRange(statements, statement.statements); + bodyLocation = statement; + statementsLocation = statement.statements; + } + else { + statements.push(statement); + } + return ts.setEmitFlags(ts.setTextRange(ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), statementsLocation), + /*multiLine*/ true), bodyLocation), 48 /* NoSourceMap */ | 384 /* NoTokenSourceMaps */); + } + function createDownlevelAwait(expression) { + return enclosingFunctionFlags & 1 /* Generator */ + ? ts.createYield(/*asteriskToken*/ undefined, createAwaitHelper(context, expression)) + : ts.createAwait(expression); + } + function transformForAwaitOfStatement(node, outermostLabeledStatement) { + var expression = ts.visitNode(node.expression, visitor, ts.isExpression); + var iterator = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(expression) : ts.createTempVariable(/*recordTempVariable*/ undefined); + var result = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(iterator) : ts.createTempVariable(/*recordTempVariable*/ undefined); + var errorRecord = ts.createUniqueName("e"); + var catchVariable = ts.getGeneratedNameForNode(errorRecord); + var returnMethod = ts.createTempVariable(/*recordTempVariable*/ undefined); + var callValues = createAsyncValuesHelper(context, expression, /*location*/ node.expression); + var callNext = ts.createCall(ts.createPropertyAccess(iterator, "next"), /*typeArguments*/ undefined, []); + var getDone = ts.createPropertyAccess(result, "done"); + var getValue = ts.createPropertyAccess(result, "value"); + var callReturn = ts.createFunctionCall(returnMethod, iterator, []); + hoistVariableDeclaration(errorRecord); + hoistVariableDeclaration(returnMethod); + var forStatement = ts.setEmitFlags(ts.setTextRange(ts.createFor( + /*initializer*/ ts.setEmitFlags(ts.setTextRange(ts.createVariableDeclarationList([ + ts.setTextRange(ts.createVariableDeclaration(iterator, /*type*/ undefined, callValues), node.expression), + ts.createVariableDeclaration(result) + ]), node.expression), 2097152 /* NoHoisting */), + /*condition*/ ts.createComma(ts.createAssignment(result, createDownlevelAwait(callNext)), ts.createLogicalNot(getDone)), + /*incrementor*/ undefined, + /*statement*/ convertForOfStatementHead(node, getValue)), + /*location*/ node), 256 /* NoTokenTrailingSourceMaps */); + return ts.createTry(ts.createBlock([ + ts.restoreEnclosingLabel(forStatement, outermostLabeledStatement) + ]), ts.createCatchClause(ts.createVariableDeclaration(catchVariable), ts.setEmitFlags(ts.createBlock([ + ts.createExpressionStatement(ts.createAssignment(errorRecord, ts.createObjectLiteral([ + ts.createPropertyAssignment("error", catchVariable) + ]))) + ]), 1 /* SingleLine */)), ts.createBlock([ + ts.createTry( + /*tryBlock*/ ts.createBlock([ + ts.setEmitFlags(ts.createIf(ts.createLogicalAnd(ts.createLogicalAnd(result, ts.createLogicalNot(getDone)), ts.createAssignment(returnMethod, ts.createPropertyAccess(iterator, "return"))), ts.createExpressionStatement(createDownlevelAwait(callReturn))), 1 /* SingleLine */) + ]), + /*catchClause*/ undefined, + /*finallyBlock*/ ts.setEmitFlags(ts.createBlock([ + ts.setEmitFlags(ts.createIf(errorRecord, ts.createThrow(ts.createPropertyAccess(errorRecord, "error"))), 1 /* SingleLine */) + ]), 1 /* SingleLine */)) + ])); + } + function visitParameter(node) { + if (node.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { + // Binding patterns are converted into a generated name and are + // evaluated inside the function body. + return ts.updateParameter(node, + /*decorators*/ undefined, + /*modifiers*/ undefined, node.dotDotDotToken, ts.getGeneratedNameForNode(node), + /*questionToken*/ undefined, + /*type*/ undefined, ts.visitNode(node.initializer, visitor, ts.isExpression)); + } + return ts.visitEachChild(node, visitor, context); + } + function visitConstructorDeclaration(node) { + var savedEnclosingFunctionFlags = enclosingFunctionFlags; + enclosingFunctionFlags = 0 /* Normal */; + var updated = ts.updateConstructor(node, + /*decorators*/ undefined, node.modifiers, ts.visitParameterList(node.parameters, visitor, context), transformFunctionBody(node)); + enclosingFunctionFlags = savedEnclosingFunctionFlags; + return updated; + } + function visitGetAccessorDeclaration(node) { + var savedEnclosingFunctionFlags = enclosingFunctionFlags; + enclosingFunctionFlags = 0 /* Normal */; + var updated = ts.updateGetAccessor(node, + /*decorators*/ undefined, node.modifiers, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, transformFunctionBody(node)); + enclosingFunctionFlags = savedEnclosingFunctionFlags; + return updated; + } + function visitSetAccessorDeclaration(node) { + var savedEnclosingFunctionFlags = enclosingFunctionFlags; + enclosingFunctionFlags = 0 /* Normal */; + var updated = ts.updateSetAccessor(node, + /*decorators*/ undefined, node.modifiers, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitParameterList(node.parameters, visitor, context), transformFunctionBody(node)); + enclosingFunctionFlags = savedEnclosingFunctionFlags; + return updated; + } + function visitMethodDeclaration(node) { + var savedEnclosingFunctionFlags = enclosingFunctionFlags; + enclosingFunctionFlags = ts.getFunctionFlags(node); + var updated = ts.updateMethod(node, + /*decorators*/ undefined, enclosingFunctionFlags & 1 /* Generator */ + ? ts.visitNodes(node.modifiers, visitorNoAsyncModifier, ts.isModifier) + : node.modifiers, enclosingFunctionFlags & 2 /* Async */ + ? undefined + : node.asteriskToken, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitNode(/*questionToken*/ undefined, visitor, ts.isToken), + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */ + ? transformAsyncGeneratorFunctionBody(node) + : transformFunctionBody(node)); + enclosingFunctionFlags = savedEnclosingFunctionFlags; + return updated; + } + function visitFunctionDeclaration(node) { + var savedEnclosingFunctionFlags = enclosingFunctionFlags; + enclosingFunctionFlags = ts.getFunctionFlags(node); + var updated = ts.updateFunctionDeclaration(node, + /*decorators*/ undefined, enclosingFunctionFlags & 1 /* Generator */ + ? ts.visitNodes(node.modifiers, visitorNoAsyncModifier, ts.isModifier) + : node.modifiers, enclosingFunctionFlags & 2 /* Async */ + ? undefined + : node.asteriskToken, node.name, + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */ + ? transformAsyncGeneratorFunctionBody(node) + : transformFunctionBody(node)); + enclosingFunctionFlags = savedEnclosingFunctionFlags; + return updated; + } + function visitArrowFunction(node) { + var savedEnclosingFunctionFlags = enclosingFunctionFlags; + enclosingFunctionFlags = ts.getFunctionFlags(node); + var updated = ts.updateArrowFunction(node, node.modifiers, + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, node.equalsGreaterThanToken, transformFunctionBody(node)); + enclosingFunctionFlags = savedEnclosingFunctionFlags; + return updated; + } + function visitFunctionExpression(node) { + var savedEnclosingFunctionFlags = enclosingFunctionFlags; + enclosingFunctionFlags = ts.getFunctionFlags(node); + var updated = ts.updateFunctionExpression(node, enclosingFunctionFlags & 1 /* Generator */ + ? ts.visitNodes(node.modifiers, visitorNoAsyncModifier, ts.isModifier) + : node.modifiers, enclosingFunctionFlags & 2 /* Async */ + ? undefined + : node.asteriskToken, node.name, + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */ + ? transformAsyncGeneratorFunctionBody(node) + : transformFunctionBody(node)); + enclosingFunctionFlags = savedEnclosingFunctionFlags; + return updated; + } + function transformAsyncGeneratorFunctionBody(node) { + resumeLexicalEnvironment(); + var statements = []; + var statementOffset = ts.addPrologue(statements, node.body.statements, /*ensureUseStrict*/ false, visitor); + appendObjectRestAssignmentsIfNeeded(statements, node); + var savedCapturedSuperProperties = capturedSuperProperties; + var savedHasSuperElementAccess = hasSuperElementAccess; + capturedSuperProperties = ts.createUnderscoreEscapedMap(); + hasSuperElementAccess = false; + var returnStatement = ts.createReturn(createAsyncGeneratorHelper(context, ts.createFunctionExpression( + /*modifiers*/ undefined, ts.createToken(40 /* AsteriskToken */), node.name && ts.getGeneratedNameForNode(node.name), + /*typeParameters*/ undefined, + /*parameters*/ [], + /*type*/ undefined, ts.updateBlock(node.body, ts.visitLexicalEnvironment(node.body.statements, visitor, context, statementOffset))))); + // Minor optimization, emit `_super` helper to capture `super` access in an arrow. + // This step isn't needed if we eventually transform this to ES5. + var emitSuperHelpers = languageVersion >= 2 /* ES2015 */ && resolver.getNodeCheckFlags(node) & (4096 /* AsyncMethodWithSuperBinding */ | 2048 /* AsyncMethodWithSuper */); + if (emitSuperHelpers) { + enableSubstitutionForAsyncMethodsWithSuper(); + var variableStatement = ts.createSuperAccessVariableStatement(resolver, node, capturedSuperProperties); + substitutedSuperAccessors[ts.getNodeId(variableStatement)] = true; + ts.addStatementsAfterPrologue(statements, [variableStatement]); + } + statements.push(returnStatement); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + var block = ts.updateBlock(node.body, statements); + if (emitSuperHelpers && hasSuperElementAccess) { + if (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) { + ts.addEmitHelper(block, ts.advancedAsyncSuperHelper); + } + else if (resolver.getNodeCheckFlags(node) & 2048 /* AsyncMethodWithSuper */) { + ts.addEmitHelper(block, ts.asyncSuperHelper); + } + } + capturedSuperProperties = savedCapturedSuperProperties; + hasSuperElementAccess = savedHasSuperElementAccess; + return block; + } + function transformFunctionBody(node) { + resumeLexicalEnvironment(); + var statementOffset = 0; + var statements = []; + var body = ts.visitNode(node.body, visitor, ts.isConciseBody); + if (ts.isBlock(body)) { + statementOffset = ts.addPrologue(statements, body.statements, /*ensureUseStrict*/ false, visitor); + } + ts.addRange(statements, appendObjectRestAssignmentsIfNeeded(/*statements*/ undefined, node)); + var leadingStatements = endLexicalEnvironment(); + if (statementOffset > 0 || ts.some(statements) || ts.some(leadingStatements)) { + var block = ts.convertToFunctionBody(body, /*multiLine*/ true); + ts.addStatementsAfterPrologue(statements, leadingStatements); + ts.addRange(statements, block.statements.slice(statementOffset)); + return ts.updateBlock(block, ts.setTextRange(ts.createNodeArray(statements), block.statements)); + } + return body; + } + function appendObjectRestAssignmentsIfNeeded(statements, node) { + for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { + var parameter = _a[_i]; + if (parameter.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { + var temp = ts.getGeneratedNameForNode(parameter); + var declarations = ts.flattenDestructuringBinding(parameter, visitor, context, 1 /* ObjectRest */, temp, + /*doNotRecordTempVariablesInLine*/ false, + /*skipInitializer*/ true); + if (ts.some(declarations)) { + var statement = ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList(declarations)); + ts.setEmitFlags(statement, 1048576 /* CustomPrologue */); + statements = ts.append(statements, statement); + } + } + } + return statements; + } + function enableSubstitutionForAsyncMethodsWithSuper() { + if ((enabledSubstitutions & 1 /* AsyncMethodsWithSuper */) === 0) { + enabledSubstitutions |= 1 /* AsyncMethodsWithSuper */; + // We need to enable substitutions for call, property access, and element access + // if we need to rewrite super calls. + context.enableSubstitution(191 /* CallExpression */); + context.enableSubstitution(189 /* PropertyAccessExpression */); + context.enableSubstitution(190 /* ElementAccessExpression */); + // We need to be notified when entering and exiting declarations that bind super. + context.enableEmitNotification(240 /* ClassDeclaration */); + context.enableEmitNotification(156 /* MethodDeclaration */); + context.enableEmitNotification(158 /* GetAccessor */); + context.enableEmitNotification(159 /* SetAccessor */); + context.enableEmitNotification(157 /* Constructor */); + // We need to be notified when entering the generated accessor arrow functions. + context.enableEmitNotification(219 /* VariableStatement */); + } + } + /** + * Called by the printer just before a node is printed. + * + * @param hint A hint as to the intended usage of the node. + * @param node The node to be printed. + * @param emitCallback The callback used to emit the node. + */ + function onEmitNode(hint, node, emitCallback) { + // If we need to support substitutions for `super` in an async method, + // we should track it here. + if (enabledSubstitutions & 1 /* AsyncMethodsWithSuper */ && isSuperContainer(node)) { + var superContainerFlags = resolver.getNodeCheckFlags(node) & (2048 /* AsyncMethodWithSuper */ | 4096 /* AsyncMethodWithSuperBinding */); + if (superContainerFlags !== enclosingSuperContainerFlags) { + var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags; + enclosingSuperContainerFlags = superContainerFlags; + previousOnEmitNode(hint, node, emitCallback); + enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags; + return; + } + } + // Disable substitution in the generated super accessor itself. + else if (enabledSubstitutions && substitutedSuperAccessors[ts.getNodeId(node)]) { + var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags; + enclosingSuperContainerFlags = 0; + previousOnEmitNode(hint, node, emitCallback); + enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags; + return; + } + previousOnEmitNode(hint, node, emitCallback); + } + /** + * Hooks node substitutions. + * + * @param hint The context for the emitter. + * @param node The node to substitute. + */ + function onSubstituteNode(hint, node) { + node = previousOnSubstituteNode(hint, node); + if (hint === 1 /* Expression */ && enclosingSuperContainerFlags) { + return substituteExpression(node); + } + return node; + } + function substituteExpression(node) { + switch (node.kind) { + case 189 /* PropertyAccessExpression */: + return substitutePropertyAccessExpression(node); + case 190 /* ElementAccessExpression */: + return substituteElementAccessExpression(node); + case 191 /* CallExpression */: + return substituteCallExpression(node); + } + return node; + } + function substitutePropertyAccessExpression(node) { + if (node.expression.kind === 98 /* SuperKeyword */) { + return ts.setTextRange(ts.createPropertyAccess(ts.createFileLevelUniqueName("_super"), node.name), node); + } + return node; + } + function substituteElementAccessExpression(node) { + if (node.expression.kind === 98 /* SuperKeyword */) { + return createSuperElementAccessInAsyncMethod(node.argumentExpression, node); + } + return node; + } + function substituteCallExpression(node) { + var expression = node.expression; + if (ts.isSuperProperty(expression)) { + var argumentExpression = ts.isPropertyAccessExpression(expression) + ? substitutePropertyAccessExpression(expression) + : substituteElementAccessExpression(expression); + return ts.createCall(ts.createPropertyAccess(argumentExpression, "call"), + /*typeArguments*/ undefined, [ + ts.createThis() + ].concat(node.arguments)); + } + return node; + } + function isSuperContainer(node) { + var kind = node.kind; + return kind === 240 /* ClassDeclaration */ + || kind === 157 /* Constructor */ + || kind === 156 /* MethodDeclaration */ + || kind === 158 /* GetAccessor */ + || kind === 159 /* SetAccessor */; + } + function createSuperElementAccessInAsyncMethod(argumentExpression, location) { + if (enclosingSuperContainerFlags & 4096 /* AsyncMethodWithSuperBinding */) { + return ts.setTextRange(ts.createPropertyAccess(ts.createCall(ts.createIdentifier("_superIndex"), + /*typeArguments*/ undefined, [argumentExpression]), "value"), location); + } + else { + return ts.setTextRange(ts.createCall(ts.createIdentifier("_superIndex"), + /*typeArguments*/ undefined, [argumentExpression]), location); + } + } + } + ts.transformESNext = transformESNext; + var assignHelper = { + name: "typescript:assign", + scoped: false, + priority: 1, + text: "\n var __assign = (this && this.__assign) || function () {\n __assign = Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n };\n return __assign.apply(this, arguments);\n };" + }; + function createAssignHelper(context, attributesSegments) { + if (context.getCompilerOptions().target >= 2 /* ES2015 */) { + return ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "assign"), + /*typeArguments*/ undefined, attributesSegments); + } + context.requestEmitHelper(assignHelper); + return ts.createCall(ts.getHelperName("__assign"), + /*typeArguments*/ undefined, attributesSegments); + } + ts.createAssignHelper = createAssignHelper; + var awaitHelper = { + name: "typescript:await", + scoped: false, + text: "\n var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }" + }; + function createAwaitHelper(context, expression) { + context.requestEmitHelper(awaitHelper); + return ts.createCall(ts.getHelperName("__await"), /*typeArguments*/ undefined, [expression]); + } + var asyncGeneratorHelper = { + name: "typescript:asyncGenerator", + scoped: false, + text: "\n var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\n function fulfill(value) { resume(\"next\", value); }\n function reject(value) { resume(\"throw\", value); }\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\n };" + }; + function createAsyncGeneratorHelper(context, generatorFunc) { + context.requestEmitHelper(awaitHelper); + context.requestEmitHelper(asyncGeneratorHelper); + // Mark this node as originally an async function + (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 262144 /* AsyncFunctionBody */; + return ts.createCall(ts.getHelperName("__asyncGenerator"), + /*typeArguments*/ undefined, [ + ts.createThis(), + ts.createIdentifier("arguments"), + generatorFunc + ]); + } + var asyncDelegator = { + name: "typescript:asyncDelegator", + scoped: false, + text: "\n var __asyncDelegator = (this && this.__asyncDelegator) || function (o) {\n var i, p;\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; } : f; }\n };" + }; + function createAsyncDelegatorHelper(context, expression, location) { + context.requestEmitHelper(awaitHelper); + context.requestEmitHelper(asyncDelegator); + return ts.setTextRange(ts.createCall(ts.getHelperName("__asyncDelegator"), + /*typeArguments*/ undefined, [expression]), location); + } + var asyncValues = { + name: "typescript:asyncValues", + scoped: false, + text: "\n var __asyncValues = (this && this.__asyncValues) || function (o) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var m = o[Symbol.asyncIterator], i;\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\n };" + }; + function createAsyncValuesHelper(context, expression, location) { + context.requestEmitHelper(asyncValues); + return ts.setTextRange(ts.createCall(ts.getHelperName("__asyncValues"), + /*typeArguments*/ undefined, [expression]), location); + } +})(ts || (ts = {})); +/*@internal*/ +var ts; +(function (ts) { + function transformJsx(context) { + var compilerOptions = context.getCompilerOptions(); + var currentSourceFile; + return ts.chainBundle(transformSourceFile); + /** + * Transform JSX-specific syntax in a SourceFile. + * + * @param node A SourceFile node. + */ + function transformSourceFile(node) { + if (node.isDeclarationFile) { + return node; + } + currentSourceFile = node; + var visited = ts.visitEachChild(node, visitor, context); + ts.addEmitHelpers(visited, context.readEmitHelpers()); + return visited; + } + function visitor(node) { + if (node.transformFlags & 4 /* ContainsJsx */) { + return visitorWorker(node); + } + else { + return node; + } + } + function visitorWorker(node) { + switch (node.kind) { + case 260 /* JsxElement */: + return visitJsxElement(node, /*isChild*/ false); + case 261 /* JsxSelfClosingElement */: + return visitJsxSelfClosingElement(node, /*isChild*/ false); + case 264 /* JsxFragment */: + return visitJsxFragment(node, /*isChild*/ false); + case 270 /* JsxExpression */: + return visitJsxExpression(node); + default: + return ts.visitEachChild(node, visitor, context); + } + } + function transformJsxChildToExpression(node) { + switch (node.kind) { + case 11 /* JsxText */: + return visitJsxText(node); + case 270 /* JsxExpression */: + return visitJsxExpression(node); + case 260 /* JsxElement */: + return visitJsxElement(node, /*isChild*/ true); + case 261 /* JsxSelfClosingElement */: + return visitJsxSelfClosingElement(node, /*isChild*/ true); + case 264 /* JsxFragment */: + return visitJsxFragment(node, /*isChild*/ true); + default: + return ts.Debug.failBadSyntaxKind(node); + } + } + function visitJsxElement(node, isChild) { + return visitJsxOpeningLikeElement(node.openingElement, node.children, isChild, /*location*/ node); + } + function visitJsxSelfClosingElement(node, isChild) { + return visitJsxOpeningLikeElement(node, /*children*/ undefined, isChild, /*location*/ node); + } + function visitJsxFragment(node, isChild) { + return visitJsxOpeningFragment(node.openingFragment, node.children, isChild, /*location*/ node); + } + function visitJsxOpeningLikeElement(node, children, isChild, location) { + var tagName = getTagName(node); + var objectProperties; + var attrs = node.attributes.properties; + if (attrs.length === 0) { + // When there are no attributes, React wants "null" + objectProperties = ts.createNull(); + } + else { + // Map spans of JsxAttribute nodes into object literals and spans + // of JsxSpreadAttribute nodes into expressions. + var segments = ts.flatten(ts.spanMap(attrs, ts.isJsxSpreadAttribute, function (attrs, isSpread) { return isSpread + ? ts.map(attrs, transformJsxSpreadAttributeToExpression) + : ts.createObjectLiteral(ts.map(attrs, transformJsxAttributeToObjectLiteralElement)); })); + if (ts.isJsxSpreadAttribute(attrs[0])) { + // We must always emit at least one object literal before a spread + // argument. + segments.unshift(ts.createObjectLiteral()); + } + // Either emit one big object literal (no spread attribs), or + // a call to the __assign helper. + objectProperties = ts.singleOrUndefined(segments); + if (!objectProperties) { + objectProperties = ts.createAssignHelper(context, segments); + } + } + var element = ts.createExpressionForJsxElement(context.getEmitResolver().getJsxFactoryEntity(currentSourceFile), compilerOptions.reactNamespace, // TODO: GH#18217 + tagName, objectProperties, ts.mapDefined(children, transformJsxChildToExpression), node, location); + if (isChild) { + ts.startOnNewLine(element); + } + return element; + } + function visitJsxOpeningFragment(node, children, isChild, location) { + var element = ts.createExpressionForJsxFragment(context.getEmitResolver().getJsxFactoryEntity(currentSourceFile), compilerOptions.reactNamespace, // TODO: GH#18217 + ts.mapDefined(children, transformJsxChildToExpression), node, location); + if (isChild) { + ts.startOnNewLine(element); + } + return element; + } + function transformJsxSpreadAttributeToExpression(node) { + return ts.visitNode(node.expression, visitor, ts.isExpression); + } + function transformJsxAttributeToObjectLiteralElement(node) { + var name = getAttributeName(node); + var expression = transformJsxAttributeInitializer(node.initializer); + return ts.createPropertyAssignment(name, expression); + } + function transformJsxAttributeInitializer(node) { + if (node === undefined) { + return ts.createTrue(); + } + else if (node.kind === 10 /* StringLiteral */) { + // Always recreate the literal to escape any escape sequences or newlines which may be in the original jsx string and which + // Need to be escaped to be handled correctly in a normal string + var literal = ts.createLiteral(tryDecodeEntities(node.text) || node.text); + literal.singleQuote = node.singleQuote !== undefined ? node.singleQuote : !ts.isStringDoubleQuoted(node, currentSourceFile); + return ts.setTextRange(literal, node); + } + else if (node.kind === 270 /* JsxExpression */) { + if (node.expression === undefined) { + return ts.createTrue(); + } + return visitJsxExpression(node); + } + else { + return ts.Debug.failBadSyntaxKind(node); + } + } + function visitJsxText(node) { + var fixed = fixupWhitespaceAndDecodeEntities(ts.getTextOfNode(node, /*includeTrivia*/ true)); + return fixed === undefined ? undefined : ts.createLiteral(fixed); + } + /** + * JSX trims whitespace at the end and beginning of lines, except that the + * start/end of a tag is considered a start/end of a line only if that line is + * on the same line as the closing tag. See examples in + * tests/cases/conformance/jsx/tsxReactEmitWhitespace.tsx + * See also https://www.w3.org/TR/html4/struct/text.html#h-9.1 and https://www.w3.org/TR/CSS2/text.html#white-space-model + * + * An equivalent algorithm would be: + * - If there is only one line, return it. + * - If there is only whitespace (but multiple lines), return `undefined`. + * - Split the text into lines. + * - 'trimRight' the first line, 'trimLeft' the last line, 'trim' middle lines. + * - Decode entities on each line (individually). + * - Remove empty lines and join the rest with " ". + */ + function fixupWhitespaceAndDecodeEntities(text) { + var acc; + // First non-whitespace character on this line. + var firstNonWhitespace = 0; + // Last non-whitespace character on this line. + var lastNonWhitespace = -1; + // These initial values are special because the first line is: + // firstNonWhitespace = 0 to indicate that we want leading whitsepace, + // but lastNonWhitespace = -1 as a special flag to indicate that we *don't* include the line if it's all whitespace. + for (var i = 0; i < text.length; i++) { + var c = text.charCodeAt(i); + if (ts.isLineBreak(c)) { + // If we've seen any non-whitespace characters on this line, add the 'trim' of the line. + // (lastNonWhitespace === -1 is a special flag to detect whether the first line is all whitespace.) + if (firstNonWhitespace !== -1 && lastNonWhitespace !== -1) { + acc = addLineOfJsxText(acc, text.substr(firstNonWhitespace, lastNonWhitespace - firstNonWhitespace + 1)); + } + // Reset firstNonWhitespace for the next line. + // Don't bother to reset lastNonWhitespace because we ignore it if firstNonWhitespace = -1. + firstNonWhitespace = -1; + } + else if (!ts.isWhiteSpaceSingleLine(c)) { + lastNonWhitespace = i; + if (firstNonWhitespace === -1) { + firstNonWhitespace = i; + } + } + } + return firstNonWhitespace !== -1 + // Last line had a non-whitespace character. Emit the 'trimLeft', meaning keep trailing whitespace. + ? addLineOfJsxText(acc, text.substr(firstNonWhitespace)) + // Last line was all whitespace, so ignore it + : acc; + } + function addLineOfJsxText(acc, trimmedLine) { + // We do not escape the string here as that is handled by the printer + // when it emits the literal. We do, however, need to decode JSX entities. + var decoded = decodeEntities(trimmedLine); + return acc === undefined ? decoded : acc + " " + decoded; + } + /** + * Replace entities like " ", "{", and "�" with the characters they encode. + * See https://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references + */ + function decodeEntities(text) { + return text.replace(/&((#((\d+)|x([\da-fA-F]+)))|(\w+));/g, function (match, _all, _number, _digits, decimal, hex, word) { + if (decimal) { + return String.fromCharCode(parseInt(decimal, 10)); + } + else if (hex) { + return String.fromCharCode(parseInt(hex, 16)); + } + else { + var ch = entities.get(word); + // If this is not a valid entity, then just use `match` (replace it with itself, i.e. don't replace) + return ch ? String.fromCharCode(ch) : match; + } + }); + } + /** Like `decodeEntities` but returns `undefined` if there were no entities to decode. */ + function tryDecodeEntities(text) { + var decoded = decodeEntities(text); + return decoded === text ? undefined : decoded; + } + function getTagName(node) { + if (node.kind === 260 /* JsxElement */) { + return getTagName(node.openingElement); + } + else { + var name = node.tagName; + if (ts.isIdentifier(name) && ts.isIntrinsicJsxName(name.escapedText)) { + return ts.createLiteral(ts.idText(name)); + } + else { + return ts.createExpressionFromEntityName(name); + } + } + } + /** + * Emit an attribute name, which is quoted if it needs to be quoted. Because + * these emit into an object literal property name, we don't need to be worried + * about keywords, just non-identifier characters + */ + function getAttributeName(node) { + var name = node.name; + var text = ts.idText(name); + if (/^[A-Za-z_]\w*$/.test(text)) { + return name; + } + else { + return ts.createLiteral(text); + } + } + function visitJsxExpression(node) { + return ts.visitNode(node.expression, visitor, ts.isExpression); + } + } + ts.transformJsx = transformJsx; + var entities = ts.createMapFromTemplate({ + quot: 0x0022, + amp: 0x0026, + apos: 0x0027, + lt: 0x003C, + gt: 0x003E, + nbsp: 0x00A0, + iexcl: 0x00A1, + cent: 0x00A2, + pound: 0x00A3, + curren: 0x00A4, + yen: 0x00A5, + brvbar: 0x00A6, + sect: 0x00A7, + uml: 0x00A8, + copy: 0x00A9, + ordf: 0x00AA, + laquo: 0x00AB, + not: 0x00AC, + shy: 0x00AD, + reg: 0x00AE, + macr: 0x00AF, + deg: 0x00B0, + plusmn: 0x00B1, + sup2: 0x00B2, + sup3: 0x00B3, + acute: 0x00B4, + micro: 0x00B5, + para: 0x00B6, + middot: 0x00B7, + cedil: 0x00B8, + sup1: 0x00B9, + ordm: 0x00BA, + raquo: 0x00BB, + frac14: 0x00BC, + frac12: 0x00BD, + frac34: 0x00BE, + iquest: 0x00BF, + Agrave: 0x00C0, + Aacute: 0x00C1, + Acirc: 0x00C2, + Atilde: 0x00C3, + Auml: 0x00C4, + Aring: 0x00C5, + AElig: 0x00C6, + Ccedil: 0x00C7, + Egrave: 0x00C8, + Eacute: 0x00C9, + Ecirc: 0x00CA, + Euml: 0x00CB, + Igrave: 0x00CC, + Iacute: 0x00CD, + Icirc: 0x00CE, + Iuml: 0x00CF, + ETH: 0x00D0, + Ntilde: 0x00D1, + Ograve: 0x00D2, + Oacute: 0x00D3, + Ocirc: 0x00D4, + Otilde: 0x00D5, + Ouml: 0x00D6, + times: 0x00D7, + Oslash: 0x00D8, + Ugrave: 0x00D9, + Uacute: 0x00DA, + Ucirc: 0x00DB, + Uuml: 0x00DC, + Yacute: 0x00DD, + THORN: 0x00DE, + szlig: 0x00DF, + agrave: 0x00E0, + aacute: 0x00E1, + acirc: 0x00E2, + atilde: 0x00E3, + auml: 0x00E4, + aring: 0x00E5, + aelig: 0x00E6, + ccedil: 0x00E7, + egrave: 0x00E8, + eacute: 0x00E9, + ecirc: 0x00EA, + euml: 0x00EB, + igrave: 0x00EC, + iacute: 0x00ED, + icirc: 0x00EE, + iuml: 0x00EF, + eth: 0x00F0, + ntilde: 0x00F1, + ograve: 0x00F2, + oacute: 0x00F3, + ocirc: 0x00F4, + otilde: 0x00F5, + ouml: 0x00F6, + divide: 0x00F7, + oslash: 0x00F8, + ugrave: 0x00F9, + uacute: 0x00FA, + ucirc: 0x00FB, + uuml: 0x00FC, + yacute: 0x00FD, + thorn: 0x00FE, + yuml: 0x00FF, + OElig: 0x0152, + oelig: 0x0153, + Scaron: 0x0160, + scaron: 0x0161, + Yuml: 0x0178, + fnof: 0x0192, + circ: 0x02C6, + tilde: 0x02DC, + Alpha: 0x0391, + Beta: 0x0392, + Gamma: 0x0393, + Delta: 0x0394, + Epsilon: 0x0395, + Zeta: 0x0396, + Eta: 0x0397, + Theta: 0x0398, + Iota: 0x0399, + Kappa: 0x039A, + Lambda: 0x039B, + Mu: 0x039C, + Nu: 0x039D, + Xi: 0x039E, + Omicron: 0x039F, + Pi: 0x03A0, + Rho: 0x03A1, + Sigma: 0x03A3, + Tau: 0x03A4, + Upsilon: 0x03A5, + Phi: 0x03A6, + Chi: 0x03A7, + Psi: 0x03A8, + Omega: 0x03A9, + alpha: 0x03B1, + beta: 0x03B2, + gamma: 0x03B3, + delta: 0x03B4, + epsilon: 0x03B5, + zeta: 0x03B6, + eta: 0x03B7, + theta: 0x03B8, + iota: 0x03B9, + kappa: 0x03BA, + lambda: 0x03BB, + mu: 0x03BC, + nu: 0x03BD, + xi: 0x03BE, + omicron: 0x03BF, + pi: 0x03C0, + rho: 0x03C1, + sigmaf: 0x03C2, + sigma: 0x03C3, + tau: 0x03C4, + upsilon: 0x03C5, + phi: 0x03C6, + chi: 0x03C7, + psi: 0x03C8, + omega: 0x03C9, + thetasym: 0x03D1, + upsih: 0x03D2, + piv: 0x03D6, + ensp: 0x2002, + emsp: 0x2003, + thinsp: 0x2009, + zwnj: 0x200C, + zwj: 0x200D, + lrm: 0x200E, + rlm: 0x200F, + ndash: 0x2013, + mdash: 0x2014, + lsquo: 0x2018, + rsquo: 0x2019, + sbquo: 0x201A, + ldquo: 0x201C, + rdquo: 0x201D, + bdquo: 0x201E, + dagger: 0x2020, + Dagger: 0x2021, + bull: 0x2022, + hellip: 0x2026, + permil: 0x2030, + prime: 0x2032, + Prime: 0x2033, + lsaquo: 0x2039, + rsaquo: 0x203A, + oline: 0x203E, + frasl: 0x2044, + euro: 0x20AC, + image: 0x2111, + weierp: 0x2118, + real: 0x211C, + trade: 0x2122, + alefsym: 0x2135, + larr: 0x2190, + uarr: 0x2191, + rarr: 0x2192, + darr: 0x2193, + harr: 0x2194, + crarr: 0x21B5, + lArr: 0x21D0, + uArr: 0x21D1, + rArr: 0x21D2, + dArr: 0x21D3, + hArr: 0x21D4, + forall: 0x2200, + part: 0x2202, + exist: 0x2203, + empty: 0x2205, + nabla: 0x2207, + isin: 0x2208, + notin: 0x2209, + ni: 0x220B, + prod: 0x220F, + sum: 0x2211, + minus: 0x2212, + lowast: 0x2217, + radic: 0x221A, + prop: 0x221D, + infin: 0x221E, + ang: 0x2220, + and: 0x2227, + or: 0x2228, + cap: 0x2229, + cup: 0x222A, + int: 0x222B, + there4: 0x2234, + sim: 0x223C, + cong: 0x2245, + asymp: 0x2248, + ne: 0x2260, + equiv: 0x2261, + le: 0x2264, + ge: 0x2265, + sub: 0x2282, + sup: 0x2283, + nsub: 0x2284, + sube: 0x2286, + supe: 0x2287, + oplus: 0x2295, + otimes: 0x2297, + perp: 0x22A5, + sdot: 0x22C5, + lceil: 0x2308, + rceil: 0x2309, + lfloor: 0x230A, + rfloor: 0x230B, + lang: 0x2329, + rang: 0x232A, + loz: 0x25CA, + spades: 0x2660, + clubs: 0x2663, + hearts: 0x2665, + diams: 0x2666 + }); +})(ts || (ts = {})); +/*@internal*/ +var ts; +(function (ts) { + function transformES2016(context) { + var hoistVariableDeclaration = context.hoistVariableDeclaration; + return ts.chainBundle(transformSourceFile); + function transformSourceFile(node) { + if (node.isDeclarationFile) { + return node; + } + return ts.visitEachChild(node, visitor, context); + } + function visitor(node) { + if ((node.transformFlags & 32 /* ContainsES2016 */) === 0) { + return node; + } + switch (node.kind) { + case 204 /* BinaryExpression */: + return visitBinaryExpression(node); + default: + return ts.visitEachChild(node, visitor, context); + } + } + function visitBinaryExpression(node) { + switch (node.operatorToken.kind) { + case 63 /* AsteriskAsteriskEqualsToken */: + return visitExponentiationAssignmentExpression(node); + case 41 /* AsteriskAsteriskToken */: + return visitExponentiationExpression(node); + default: + return ts.visitEachChild(node, visitor, context); + } + } + function visitExponentiationAssignmentExpression(node) { + var target; + var value; + var left = ts.visitNode(node.left, visitor, ts.isExpression); + var right = ts.visitNode(node.right, visitor, ts.isExpression); + if (ts.isElementAccessExpression(left)) { + // Transforms `a[x] **= b` into `(_a = a)[_x = x] = Math.pow(_a[_x], b)` + var expressionTemp = ts.createTempVariable(hoistVariableDeclaration); + var argumentExpressionTemp = ts.createTempVariable(hoistVariableDeclaration); + target = ts.setTextRange(ts.createElementAccess(ts.setTextRange(ts.createAssignment(expressionTemp, left.expression), left.expression), ts.setTextRange(ts.createAssignment(argumentExpressionTemp, left.argumentExpression), left.argumentExpression)), left); + value = ts.setTextRange(ts.createElementAccess(expressionTemp, argumentExpressionTemp), left); + } + else if (ts.isPropertyAccessExpression(left)) { + // Transforms `a.x **= b` into `(_a = a).x = Math.pow(_a.x, b)` + var expressionTemp = ts.createTempVariable(hoistVariableDeclaration); + target = ts.setTextRange(ts.createPropertyAccess(ts.setTextRange(ts.createAssignment(expressionTemp, left.expression), left.expression), left.name), left); + value = ts.setTextRange(ts.createPropertyAccess(expressionTemp, left.name), left); + } + else { + // Transforms `a **= b` into `a = Math.pow(a, b)` + target = left; + value = left; + } + return ts.setTextRange(ts.createAssignment(target, ts.createMathPow(value, right, /*location*/ node)), node); + } + function visitExponentiationExpression(node) { + // Transforms `a ** b` into `Math.pow(a, b)` + var left = ts.visitNode(node.left, visitor, ts.isExpression); + var right = ts.visitNode(node.right, visitor, ts.isExpression); + return ts.createMathPow(left, right, /*location*/ node); + } + } + ts.transformES2016 = transformES2016; +})(ts || (ts = {})); +/*@internal*/ +var ts; +(function (ts) { + var ES2015SubstitutionFlags; + (function (ES2015SubstitutionFlags) { + /** Enables substitutions for captured `this` */ + ES2015SubstitutionFlags[ES2015SubstitutionFlags["CapturedThis"] = 1] = "CapturedThis"; + /** Enables substitutions for block-scoped bindings. */ + ES2015SubstitutionFlags[ES2015SubstitutionFlags["BlockScopedBindings"] = 2] = "BlockScopedBindings"; + })(ES2015SubstitutionFlags || (ES2015SubstitutionFlags = {})); + var LoopOutParameterFlags; + (function (LoopOutParameterFlags) { + LoopOutParameterFlags[LoopOutParameterFlags["Body"] = 1] = "Body"; + LoopOutParameterFlags[LoopOutParameterFlags["Initializer"] = 2] = "Initializer"; + })(LoopOutParameterFlags || (LoopOutParameterFlags = {})); + var CopyDirection; + (function (CopyDirection) { + CopyDirection[CopyDirection["ToOriginal"] = 0] = "ToOriginal"; + CopyDirection[CopyDirection["ToOutParameter"] = 1] = "ToOutParameter"; + })(CopyDirection || (CopyDirection = {})); + var Jump; + (function (Jump) { + Jump[Jump["Break"] = 2] = "Break"; + Jump[Jump["Continue"] = 4] = "Continue"; + Jump[Jump["Return"] = 8] = "Return"; + })(Jump || (Jump = {})); + var SuperCaptureResult; + (function (SuperCaptureResult) { + /** + * A capture may have been added for calls to 'super', but + * the caller should emit subsequent statements normally. + */ + SuperCaptureResult[SuperCaptureResult["NoReplacement"] = 0] = "NoReplacement"; + /** + * A call to 'super()' got replaced with a capturing statement like: + * + * var _this = _super.call(...) || this; + * + * Callers should skip the current statement. + */ + SuperCaptureResult[SuperCaptureResult["ReplaceSuperCapture"] = 1] = "ReplaceSuperCapture"; + /** + * A call to 'super()' got replaced with a capturing statement like: + * + * return _super.call(...) || this; + * + * Callers should skip the current statement and avoid any returns of '_this'. + */ + SuperCaptureResult[SuperCaptureResult["ReplaceWithReturn"] = 2] = "ReplaceWithReturn"; + })(SuperCaptureResult || (SuperCaptureResult = {})); + // Facts we track as we traverse the tree + var HierarchyFacts; + (function (HierarchyFacts) { + HierarchyFacts[HierarchyFacts["None"] = 0] = "None"; + // + // Ancestor facts + // + HierarchyFacts[HierarchyFacts["Function"] = 1] = "Function"; + HierarchyFacts[HierarchyFacts["ArrowFunction"] = 2] = "ArrowFunction"; + HierarchyFacts[HierarchyFacts["AsyncFunctionBody"] = 4] = "AsyncFunctionBody"; + HierarchyFacts[HierarchyFacts["NonStaticClassElement"] = 8] = "NonStaticClassElement"; + HierarchyFacts[HierarchyFacts["CapturesThis"] = 16] = "CapturesThis"; + HierarchyFacts[HierarchyFacts["ExportedVariableStatement"] = 32] = "ExportedVariableStatement"; + HierarchyFacts[HierarchyFacts["TopLevel"] = 64] = "TopLevel"; + HierarchyFacts[HierarchyFacts["Block"] = 128] = "Block"; + HierarchyFacts[HierarchyFacts["IterationStatement"] = 256] = "IterationStatement"; + HierarchyFacts[HierarchyFacts["IterationStatementBlock"] = 512] = "IterationStatementBlock"; + HierarchyFacts[HierarchyFacts["ForStatement"] = 1024] = "ForStatement"; + HierarchyFacts[HierarchyFacts["ForInOrForOfStatement"] = 2048] = "ForInOrForOfStatement"; + HierarchyFacts[HierarchyFacts["ConstructorWithCapturedSuper"] = 4096] = "ConstructorWithCapturedSuper"; + HierarchyFacts[HierarchyFacts["ComputedPropertyName"] = 8192] = "ComputedPropertyName"; + // NOTE: do not add more ancestor flags without also updating AncestorFactsMask below. + // + // Ancestor masks + // + HierarchyFacts[HierarchyFacts["AncestorFactsMask"] = 16383] = "AncestorFactsMask"; + // We are always in *some* kind of block scope, but only specific block-scope containers are + // top-level or Blocks. + HierarchyFacts[HierarchyFacts["BlockScopeIncludes"] = 0] = "BlockScopeIncludes"; + HierarchyFacts[HierarchyFacts["BlockScopeExcludes"] = 4032] = "BlockScopeExcludes"; + // A source file is a top-level block scope. + HierarchyFacts[HierarchyFacts["SourceFileIncludes"] = 64] = "SourceFileIncludes"; + HierarchyFacts[HierarchyFacts["SourceFileExcludes"] = 3968] = "SourceFileExcludes"; + // Functions, methods, and accessors are both new lexical scopes and new block scopes. + HierarchyFacts[HierarchyFacts["FunctionIncludes"] = 65] = "FunctionIncludes"; + HierarchyFacts[HierarchyFacts["FunctionExcludes"] = 16286] = "FunctionExcludes"; + HierarchyFacts[HierarchyFacts["AsyncFunctionBodyIncludes"] = 69] = "AsyncFunctionBodyIncludes"; + HierarchyFacts[HierarchyFacts["AsyncFunctionBodyExcludes"] = 16278] = "AsyncFunctionBodyExcludes"; + // Arrow functions are lexically scoped to their container, but are new block scopes. + HierarchyFacts[HierarchyFacts["ArrowFunctionIncludes"] = 66] = "ArrowFunctionIncludes"; + HierarchyFacts[HierarchyFacts["ArrowFunctionExcludes"] = 16256] = "ArrowFunctionExcludes"; + // Constructors are both new lexical scopes and new block scopes. Constructors are also + // always considered non-static members of a class. + HierarchyFacts[HierarchyFacts["ConstructorIncludes"] = 73] = "ConstructorIncludes"; + HierarchyFacts[HierarchyFacts["ConstructorExcludes"] = 16278] = "ConstructorExcludes"; + // 'do' and 'while' statements are not block scopes. We track that the subtree is contained + // within an IterationStatement to indicate whether the embedded statement is an + // IterationStatementBlock. + HierarchyFacts[HierarchyFacts["DoOrWhileStatementIncludes"] = 256] = "DoOrWhileStatementIncludes"; + HierarchyFacts[HierarchyFacts["DoOrWhileStatementExcludes"] = 0] = "DoOrWhileStatementExcludes"; + // 'for' statements are new block scopes and have special handling for 'let' declarations. + HierarchyFacts[HierarchyFacts["ForStatementIncludes"] = 1280] = "ForStatementIncludes"; + HierarchyFacts[HierarchyFacts["ForStatementExcludes"] = 3008] = "ForStatementExcludes"; + // 'for-in' and 'for-of' statements are new block scopes and have special handling for + // 'let' declarations. + HierarchyFacts[HierarchyFacts["ForInOrForOfStatementIncludes"] = 2304] = "ForInOrForOfStatementIncludes"; + HierarchyFacts[HierarchyFacts["ForInOrForOfStatementExcludes"] = 1984] = "ForInOrForOfStatementExcludes"; + // Blocks (other than function bodies) are new block scopes. + HierarchyFacts[HierarchyFacts["BlockIncludes"] = 128] = "BlockIncludes"; + HierarchyFacts[HierarchyFacts["BlockExcludes"] = 3904] = "BlockExcludes"; + HierarchyFacts[HierarchyFacts["IterationStatementBlockIncludes"] = 512] = "IterationStatementBlockIncludes"; + HierarchyFacts[HierarchyFacts["IterationStatementBlockExcludes"] = 4032] = "IterationStatementBlockExcludes"; + // Computed property names track subtree flags differently than their containing members. + HierarchyFacts[HierarchyFacts["ComputedPropertyNameIncludes"] = 8192] = "ComputedPropertyNameIncludes"; + HierarchyFacts[HierarchyFacts["ComputedPropertyNameExcludes"] = 0] = "ComputedPropertyNameExcludes"; + // + // Subtree facts + // + HierarchyFacts[HierarchyFacts["NewTarget"] = 16384] = "NewTarget"; + HierarchyFacts[HierarchyFacts["NewTargetInComputedPropertyName"] = 32768] = "NewTargetInComputedPropertyName"; + // + // Subtree masks + // + HierarchyFacts[HierarchyFacts["SubtreeFactsMask"] = -16384] = "SubtreeFactsMask"; + HierarchyFacts[HierarchyFacts["PropagateNewTargetMask"] = 49152] = "PropagateNewTargetMask"; + })(HierarchyFacts || (HierarchyFacts = {})); + function transformES2015(context) { + var startLexicalEnvironment = context.startLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; + var compilerOptions = context.getCompilerOptions(); + var resolver = context.getEmitResolver(); + var previousOnSubstituteNode = context.onSubstituteNode; + var previousOnEmitNode = context.onEmitNode; + context.onEmitNode = onEmitNode; + context.onSubstituteNode = onSubstituteNode; + var currentSourceFile; + var currentText; + var hierarchyFacts; + var taggedTemplateStringDeclarations; + function recordTaggedTemplateString(temp) { + taggedTemplateStringDeclarations = ts.append(taggedTemplateStringDeclarations, ts.createVariableDeclaration(temp)); + } + /** + * Used to track if we are emitting body of the converted loop + */ + var convertedLoopState; + /** + * Keeps track of whether substitutions have been enabled for specific cases. + * They are persisted between each SourceFile transformation and should not + * be reset. + */ + var enabledSubstitutions; + return ts.chainBundle(transformSourceFile); + function transformSourceFile(node) { + if (node.isDeclarationFile) { + return node; + } + currentSourceFile = node; + currentText = node.text; + var visited = visitSourceFile(node); + ts.addEmitHelpers(visited, context.readEmitHelpers()); + currentSourceFile = undefined; + currentText = undefined; + taggedTemplateStringDeclarations = undefined; + hierarchyFacts = 0 /* None */; + return visited; + } + /** + * Sets the `HierarchyFacts` for this node prior to visiting this node's subtree, returning the facts set prior to modification. + * @param excludeFacts The existing `HierarchyFacts` to reset before visiting the subtree. + * @param includeFacts The new `HierarchyFacts` to set before visiting the subtree. + */ + function enterSubtree(excludeFacts, includeFacts) { + var ancestorFacts = hierarchyFacts; + hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & 16383 /* AncestorFactsMask */; + return ancestorFacts; + } + /** + * Restores the `HierarchyFacts` for this node's ancestor after visiting this node's + * subtree, propagating specific facts from the subtree. + * @param ancestorFacts The `HierarchyFacts` of the ancestor to restore after visiting the subtree. + * @param excludeFacts The existing `HierarchyFacts` of the subtree that should not be propagated. + * @param includeFacts The new `HierarchyFacts` of the subtree that should be propagated. + */ + function exitSubtree(ancestorFacts, excludeFacts, includeFacts) { + hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & -16384 /* SubtreeFactsMask */ | ancestorFacts; + } + function isReturnVoidStatementInConstructorWithCapturedSuper(node) { + return (hierarchyFacts & 4096 /* ConstructorWithCapturedSuper */) !== 0 + && node.kind === 230 /* ReturnStatement */ + && !node.expression; + } + function shouldVisitNode(node) { + return (node.transformFlags & 128 /* ContainsES2015 */) !== 0 + || convertedLoopState !== undefined + || (hierarchyFacts & 4096 /* ConstructorWithCapturedSuper */ && (ts.isStatement(node) || (node.kind === 218 /* Block */))) + || (ts.isIterationStatement(node, /*lookInLabeledStatements*/ false) && shouldConvertIterationStatement(node)) + || (ts.getEmitFlags(node) & 33554432 /* TypeScriptClassWrapper */) !== 0; + } + function visitor(node) { + if (shouldVisitNode(node)) { + return visitJavaScript(node); + } + else { + return node; + } + } + function functionBodyVisitor(node) { + if (shouldVisitNode(node)) { + return visitBlock(node, /*isFunctionBody*/ true); + } + return node; + } + function callExpressionVisitor(node) { + if (node.kind === 98 /* SuperKeyword */) { + return visitSuperKeyword(/*isExpressionOfCall*/ true); + } + return visitor(node); + } + function visitJavaScript(node) { + switch (node.kind) { + case 116 /* StaticKeyword */: + return undefined; // elide static keyword + case 240 /* ClassDeclaration */: + return visitClassDeclaration(node); + case 209 /* ClassExpression */: + return visitClassExpression(node); + case 151 /* Parameter */: + return visitParameter(node); + case 239 /* FunctionDeclaration */: + return visitFunctionDeclaration(node); + case 197 /* ArrowFunction */: + return visitArrowFunction(node); + case 196 /* FunctionExpression */: + return visitFunctionExpression(node); + case 237 /* VariableDeclaration */: + return visitVariableDeclaration(node); + case 72 /* Identifier */: + return visitIdentifier(node); + case 238 /* VariableDeclarationList */: + return visitVariableDeclarationList(node); + case 232 /* SwitchStatement */: + return visitSwitchStatement(node); + case 246 /* CaseBlock */: + return visitCaseBlock(node); + case 218 /* Block */: + return visitBlock(node, /*isFunctionBody*/ false); + case 229 /* BreakStatement */: + case 228 /* ContinueStatement */: + return visitBreakOrContinueStatement(node); + case 233 /* LabeledStatement */: + return visitLabeledStatement(node); + case 223 /* DoStatement */: + case 224 /* WhileStatement */: + return visitDoOrWhileStatement(node, /*outermostLabeledStatement*/ undefined); + case 225 /* ForStatement */: + return visitForStatement(node, /*outermostLabeledStatement*/ undefined); + case 226 /* ForInStatement */: + return visitForInStatement(node, /*outermostLabeledStatement*/ undefined); + case 227 /* ForOfStatement */: + return visitForOfStatement(node, /*outermostLabeledStatement*/ undefined); + case 221 /* ExpressionStatement */: + return visitExpressionStatement(node); + case 188 /* ObjectLiteralExpression */: + return visitObjectLiteralExpression(node); + case 274 /* CatchClause */: + return visitCatchClause(node); + case 276 /* ShorthandPropertyAssignment */: + return visitShorthandPropertyAssignment(node); + case 149 /* ComputedPropertyName */: + return visitComputedPropertyName(node); + case 187 /* ArrayLiteralExpression */: + return visitArrayLiteralExpression(node); + case 191 /* CallExpression */: + return visitCallExpression(node); + case 192 /* NewExpression */: + return visitNewExpression(node); + case 195 /* ParenthesizedExpression */: + return visitParenthesizedExpression(node, /*needsDestructuringValue*/ true); + case 204 /* BinaryExpression */: + return visitBinaryExpression(node, /*needsDestructuringValue*/ true); + case 14 /* NoSubstitutionTemplateLiteral */: + case 15 /* TemplateHead */: + case 16 /* TemplateMiddle */: + case 17 /* TemplateTail */: + return visitTemplateLiteral(node); + case 10 /* StringLiteral */: + return visitStringLiteral(node); + case 8 /* NumericLiteral */: + return visitNumericLiteral(node); + case 193 /* TaggedTemplateExpression */: + return visitTaggedTemplateExpression(node); + case 206 /* TemplateExpression */: + return visitTemplateExpression(node); + case 207 /* YieldExpression */: + return visitYieldExpression(node); + case 208 /* SpreadElement */: + return visitSpreadElement(node); + case 98 /* SuperKeyword */: + return visitSuperKeyword(/*isExpressionOfCall*/ false); + case 100 /* ThisKeyword */: + return visitThisKeyword(node); + case 214 /* MetaProperty */: + return visitMetaProperty(node); + case 156 /* MethodDeclaration */: + return visitMethodDeclaration(node); + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + return visitAccessorDeclaration(node); + case 219 /* VariableStatement */: + return visitVariableStatement(node); + case 230 /* ReturnStatement */: + return visitReturnStatement(node); + default: + return ts.visitEachChild(node, visitor, context); + } + } + function visitSourceFile(node) { + var ancestorFacts = enterSubtree(3968 /* SourceFileExcludes */, 64 /* SourceFileIncludes */); + var statements = []; + startLexicalEnvironment(); + var statementOffset = ts.addStandardPrologue(statements, node.statements, /*ensureUseStrict*/ false); + addCaptureThisForNodeIfNeeded(statements, node); + statementOffset = ts.addCustomPrologue(statements, node.statements, statementOffset, visitor); + ts.addRange(statements, ts.visitNodes(node.statements, visitor, ts.isStatement, statementOffset)); + if (taggedTemplateStringDeclarations) { + statements.push(ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList(taggedTemplateStringDeclarations))); + } + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */); + return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements)); + } + function visitSwitchStatement(node) { + if (convertedLoopState !== undefined) { + var savedAllowedNonLabeledJumps = convertedLoopState.allowedNonLabeledJumps; + // for switch statement allow only non-labeled break + convertedLoopState.allowedNonLabeledJumps |= 2 /* Break */; + var result = ts.visitEachChild(node, visitor, context); + convertedLoopState.allowedNonLabeledJumps = savedAllowedNonLabeledJumps; + return result; + } + return ts.visitEachChild(node, visitor, context); + } + function visitCaseBlock(node) { + var ancestorFacts = enterSubtree(4032 /* BlockScopeExcludes */, 0 /* BlockScopeIncludes */); + var updated = ts.visitEachChild(node, visitor, context); + exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */); + return updated; + } + function returnCapturedThis(node) { + return ts.setOriginalNode(ts.createReturn(ts.createFileLevelUniqueName("_this")), node); + } + function visitReturnStatement(node) { + if (convertedLoopState) { + convertedLoopState.nonLocalJumps |= 8 /* Return */; + if (isReturnVoidStatementInConstructorWithCapturedSuper(node)) { + node = returnCapturedThis(node); + } + return ts.createReturn(ts.createObjectLiteral([ + ts.createPropertyAssignment(ts.createIdentifier("value"), node.expression + ? ts.visitNode(node.expression, visitor, ts.isExpression) + : ts.createVoidZero()) + ])); + } + else if (isReturnVoidStatementInConstructorWithCapturedSuper(node)) { + return returnCapturedThis(node); + } + return ts.visitEachChild(node, visitor, context); + } + function visitThisKeyword(node) { + if (convertedLoopState) { + if (hierarchyFacts & 2 /* ArrowFunction */) { + // if the enclosing function is an ArrowFunction then we use the captured 'this' keyword. + convertedLoopState.containsLexicalThis = true; + return node; + } + return convertedLoopState.thisName || (convertedLoopState.thisName = ts.createUniqueName("this")); + } + return node; + } + function visitIdentifier(node) { + if (!convertedLoopState) { + return node; + } + if (ts.isGeneratedIdentifier(node)) { + return node; + } + if (node.escapedText !== "arguments" || !resolver.isArgumentsLocalBinding(node)) { + return node; + } + return convertedLoopState.argumentsName || (convertedLoopState.argumentsName = ts.createUniqueName("arguments")); + } + function visitBreakOrContinueStatement(node) { + if (convertedLoopState) { + // check if we can emit break/continue as is + // it is possible if either + // - break/continue is labeled and label is located inside the converted loop + // - break/continue is non-labeled and located in non-converted loop/switch statement + var jump = node.kind === 229 /* BreakStatement */ ? 2 /* Break */ : 4 /* Continue */; + var canUseBreakOrContinue = (node.label && convertedLoopState.labels && convertedLoopState.labels.get(ts.idText(node.label))) || + (!node.label && (convertedLoopState.allowedNonLabeledJumps & jump)); + if (!canUseBreakOrContinue) { + var labelMarker = void 0; + var label = node.label; + if (!label) { + if (node.kind === 229 /* BreakStatement */) { + convertedLoopState.nonLocalJumps |= 2 /* Break */; + labelMarker = "break"; + } + else { + convertedLoopState.nonLocalJumps |= 4 /* Continue */; + // note: return value is emitted only to simplify debugging, call to converted loop body does not do any dispatching on it. + labelMarker = "continue"; + } + } + else { + if (node.kind === 229 /* BreakStatement */) { + labelMarker = "break-" + label.escapedText; + setLabeledJump(convertedLoopState, /*isBreak*/ true, ts.idText(label), labelMarker); + } + else { + labelMarker = "continue-" + label.escapedText; + setLabeledJump(convertedLoopState, /*isBreak*/ false, ts.idText(label), labelMarker); + } + } + var returnExpression = ts.createLiteral(labelMarker); + if (convertedLoopState.loopOutParameters.length) { + var outParams = convertedLoopState.loopOutParameters; + var expr = void 0; + for (var i = 0; i < outParams.length; i++) { + var copyExpr = copyOutParameter(outParams[i], 1 /* ToOutParameter */); + if (i === 0) { + expr = copyExpr; + } + else { + expr = ts.createBinary(expr, 27 /* CommaToken */, copyExpr); + } + } + returnExpression = ts.createBinary(expr, 27 /* CommaToken */, returnExpression); + } + return ts.createReturn(returnExpression); + } + } + return ts.visitEachChild(node, visitor, context); + } + /** + * Visits a ClassDeclaration and transforms it into a variable statement. + * + * @param node A ClassDeclaration node. + */ + function visitClassDeclaration(node) { + // [source] + // class C { } + // + // [output] + // var C = (function () { + // function C() { + // } + // return C; + // }()); + var variable = ts.createVariableDeclaration(ts.getLocalName(node, /*allowComments*/ true), + /*type*/ undefined, transformClassLikeDeclarationToExpression(node)); + ts.setOriginalNode(variable, node); + var statements = []; + var statement = ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([variable])); + ts.setOriginalNode(statement, node); + ts.setTextRange(statement, node); + ts.startOnNewLine(statement); + statements.push(statement); + // Add an `export default` statement for default exports (for `--target es5 --module es6`) + if (ts.hasModifier(node, 1 /* Export */)) { + var exportStatement = ts.hasModifier(node, 512 /* Default */) + ? ts.createExportDefault(ts.getLocalName(node)) + : ts.createExternalModuleExport(ts.getLocalName(node)); + ts.setOriginalNode(exportStatement, statement); + statements.push(exportStatement); + } + var emitFlags = ts.getEmitFlags(node); + if ((emitFlags & 4194304 /* HasEndOfDeclarationMarker */) === 0) { + // Add a DeclarationMarker as a marker for the end of the declaration + statements.push(ts.createEndOfDeclarationMarker(node)); + ts.setEmitFlags(statement, emitFlags | 4194304 /* HasEndOfDeclarationMarker */); + } + return ts.singleOrMany(statements); + } + /** + * Visits a ClassExpression and transforms it into an expression. + * + * @param node A ClassExpression node. + */ + function visitClassExpression(node) { + // [source] + // C = class { } + // + // [output] + // C = (function () { + // function class_1() { + // } + // return class_1; + // }()) + return transformClassLikeDeclarationToExpression(node); + } + /** + * Transforms a ClassExpression or ClassDeclaration into an expression. + * + * @param node A ClassExpression or ClassDeclaration node. + */ + function transformClassLikeDeclarationToExpression(node) { + // [source] + // class C extends D { + // constructor() {} + // method() {} + // get prop() {} + // set prop(v) {} + // } + // + // [output] + // (function (_super) { + // __extends(C, _super); + // function C() { + // } + // C.prototype.method = function () {} + // Object.defineProperty(C.prototype, "prop", { + // get: function() {}, + // set: function() {}, + // enumerable: true, + // configurable: true + // }); + // return C; + // }(D)) + if (node.name) { + enableSubstitutionsForBlockScopedBindings(); + } + var extendsClauseElement = ts.getEffectiveBaseTypeNode(node); + var classFunction = ts.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, extendsClauseElement ? [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, ts.createFileLevelUniqueName("_super"))] : [], + /*type*/ undefined, transformClassBody(node, extendsClauseElement)); + // To preserve the behavior of the old emitter, we explicitly indent + // the body of the function here if it was requested in an earlier + // transformation. + ts.setEmitFlags(classFunction, (ts.getEmitFlags(node) & 65536 /* Indented */) | 524288 /* ReuseTempVariableScope */); + // "inner" and "outer" below are added purely to preserve source map locations from + // the old emitter + var inner = ts.createPartiallyEmittedExpression(classFunction); + inner.end = node.end; + ts.setEmitFlags(inner, 1536 /* NoComments */); + var outer = ts.createPartiallyEmittedExpression(inner); + outer.end = ts.skipTrivia(currentText, node.pos); + ts.setEmitFlags(outer, 1536 /* NoComments */); + var result = ts.createParen(ts.createCall(outer, + /*typeArguments*/ undefined, extendsClauseElement + ? [ts.visitNode(extendsClauseElement.expression, visitor, ts.isExpression)] + : [])); + ts.addSyntheticLeadingComment(result, 3 /* MultiLineCommentTrivia */, "* @class "); + return result; + } + /** + * Transforms a ClassExpression or ClassDeclaration into a function body. + * + * @param node A ClassExpression or ClassDeclaration node. + * @param extendsClauseElement The expression for the class `extends` clause. + */ + function transformClassBody(node, extendsClauseElement) { + var statements = []; + startLexicalEnvironment(); + addExtendsHelperIfNeeded(statements, node, extendsClauseElement); + addConstructor(statements, node, extendsClauseElement); + addClassMembers(statements, node); + // Create a synthetic text range for the return statement. + var closingBraceLocation = ts.createTokenRange(ts.skipTrivia(currentText, node.members.end), 19 /* CloseBraceToken */); + var localName = ts.getInternalName(node); + // The following partially-emitted expression exists purely to align our sourcemap + // emit with the original emitter. + var outer = ts.createPartiallyEmittedExpression(localName); + outer.end = closingBraceLocation.end; + ts.setEmitFlags(outer, 1536 /* NoComments */); + var statement = ts.createReturn(outer); + statement.pos = closingBraceLocation.pos; + ts.setEmitFlags(statement, 1536 /* NoComments */ | 384 /* NoTokenSourceMaps */); + statements.push(statement); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), /*location*/ node.members), /*multiLine*/ true); + ts.setEmitFlags(block, 1536 /* NoComments */); + return block; + } + /** + * Adds a call to the `__extends` helper if needed for a class. + * + * @param statements The statements of the class body function. + * @param node The ClassExpression or ClassDeclaration node. + * @param extendsClauseElement The expression for the class `extends` clause. + */ + function addExtendsHelperIfNeeded(statements, node, extendsClauseElement) { + if (extendsClauseElement) { + statements.push(ts.setTextRange(ts.createExpressionStatement(createExtendsHelper(context, ts.getInternalName(node))), + /*location*/ extendsClauseElement)); + } + } + /** + * Adds the constructor of the class to a class body function. + * + * @param statements The statements of the class body function. + * @param node The ClassExpression or ClassDeclaration node. + * @param extendsClauseElement The expression for the class `extends` clause. + */ + function addConstructor(statements, node, extendsClauseElement) { + var savedConvertedLoopState = convertedLoopState; + convertedLoopState = undefined; + var ancestorFacts = enterSubtree(16278 /* ConstructorExcludes */, 73 /* ConstructorIncludes */); + var constructor = ts.getFirstConstructorWithBody(node); + var hasSynthesizedSuper = hasSynthesizedDefaultSuperCall(constructor, extendsClauseElement !== undefined); + var constructorFunction = ts.createFunctionDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, ts.getInternalName(node), + /*typeParameters*/ undefined, transformConstructorParameters(constructor, hasSynthesizedSuper), + /*type*/ undefined, transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper)); + ts.setTextRange(constructorFunction, constructor || node); + if (extendsClauseElement) { + ts.setEmitFlags(constructorFunction, 8 /* CapturesThis */); + } + statements.push(constructorFunction); + exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, 0 /* None */); + convertedLoopState = savedConvertedLoopState; + } + /** + * Transforms the parameters of the constructor declaration of a class. + * + * @param constructor The constructor for the class. + * @param hasSynthesizedSuper A value indicating whether the constructor starts with a + * synthesized `super` call. + */ + function transformConstructorParameters(constructor, hasSynthesizedSuper) { + // If the TypeScript transformer needed to synthesize a constructor for property + // initializers, it would have also added a synthetic `...args` parameter and + // `super` call. + // If this is the case, we do not include the synthetic `...args` parameter and + // will instead use the `arguments` object in ES5/3. + return ts.visitParameterList(constructor && !hasSynthesizedSuper ? constructor.parameters : undefined, visitor, context) + || []; + } + /** + * Transforms the body of a constructor declaration of a class. + * + * @param constructor The constructor for the class. + * @param node The node which contains the constructor. + * @param extendsClauseElement The expression for the class `extends` clause. + * @param hasSynthesizedSuper A value indicating whether the constructor starts with a + * synthesized `super` call. + */ + function transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper) { + var statements = []; + resumeLexicalEnvironment(); + var statementOffset = -1; + if (hasSynthesizedSuper) { + // If a super call has already been synthesized, + // we're going to assume that we should just transform everything after that. + // The assumption is that no prior step in the pipeline has added any prologue directives. + statementOffset = 0; + } + else if (constructor) { + statementOffset = ts.addStandardPrologue(statements, constructor.body.statements, /*ensureUseStrict*/ false); + } + if (constructor) { + addDefaultValueAssignmentsIfNeeded(statements, constructor); + addRestParameterIfNeeded(statements, constructor, hasSynthesizedSuper); + if (!hasSynthesizedSuper) { + // If no super call has been synthesized, emit custom prologue directives. + statementOffset = ts.addCustomPrologue(statements, constructor.body.statements, statementOffset, visitor); + } + ts.Debug.assert(statementOffset >= 0, "statementOffset not initialized correctly!"); + } + // determine whether the class is known syntactically to be a derived class (e.g. a + // class that extends a value that is not syntactically known to be `null`). + var isDerivedClass = !!extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 96 /* NullKeyword */; + var superCaptureStatus = declareOrCaptureOrReturnThisForConstructorIfNeeded(statements, constructor, isDerivedClass, hasSynthesizedSuper, statementOffset); + // The last statement expression was replaced. Skip it. + if (superCaptureStatus === 1 /* ReplaceSuperCapture */ || superCaptureStatus === 2 /* ReplaceWithReturn */) { + statementOffset++; + } + if (constructor) { + if (superCaptureStatus === 1 /* ReplaceSuperCapture */) { + hierarchyFacts |= 4096 /* ConstructorWithCapturedSuper */; + } + ts.addRange(statements, ts.visitNodes(constructor.body.statements, visitor, ts.isStatement, /*start*/ statementOffset)); + } + // Return `_this` unless we're sure enough that it would be pointless to add a return statement. + // If there's a constructor that we can tell returns in enough places, then we *do not* want to add a return. + if (isDerivedClass + && superCaptureStatus !== 2 /* ReplaceWithReturn */ + && !(constructor && isSufficientlyCoveredByReturnStatements(constructor.body))) { + statements.push(ts.createReturn(ts.createFileLevelUniqueName("_this"))); + } + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + if (constructor) { + prependCaptureNewTargetIfNeeded(statements, constructor, /*copyOnWrite*/ false); + } + var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), + /*location*/ constructor ? constructor.body.statements : node.members), + /*multiLine*/ true); + ts.setTextRange(block, constructor ? constructor.body : node); + if (!constructor) { + ts.setEmitFlags(block, 1536 /* NoComments */); + } + return block; + } + /** + * We want to try to avoid emitting a return statement in certain cases if a user already returned something. + * It would generate obviously dead code, so we'll try to make things a little bit prettier + * by doing a minimal check on whether some common patterns always explicitly return. + */ + function isSufficientlyCoveredByReturnStatements(statement) { + // A return statement is considered covered. + if (statement.kind === 230 /* ReturnStatement */) { + return true; + } + // An if-statement with two covered branches is covered. + else if (statement.kind === 222 /* IfStatement */) { + var ifStatement = statement; + if (ifStatement.elseStatement) { + return isSufficientlyCoveredByReturnStatements(ifStatement.thenStatement) && + isSufficientlyCoveredByReturnStatements(ifStatement.elseStatement); + } + } + // A block is covered if it has a last statement which is covered. + else if (statement.kind === 218 /* Block */) { + var lastStatement = ts.lastOrUndefined(statement.statements); + if (lastStatement && isSufficientlyCoveredByReturnStatements(lastStatement)) { + return true; + } + } + return false; + } + /** + * Declares a `_this` variable for derived classes and for when arrow functions capture `this`. + * + * @returns The new statement offset into the `statements` array. + */ + function declareOrCaptureOrReturnThisForConstructorIfNeeded(statements, ctor, isDerivedClass, hasSynthesizedSuper, statementOffset) { + // If this isn't a derived class, just capture 'this' for arrow functions if necessary. + if (!isDerivedClass) { + if (ctor) { + addCaptureThisForNodeIfNeeded(statements, ctor); + } + return 0 /* NoReplacement */; + } + // We must be here because the user didn't write a constructor + // but we needed to call 'super(...args)' anyway as per 14.5.14 of the ES2016 spec. + // If that's the case we can just immediately return the result of a 'super()' call. + if (!ctor) { + statements.push(ts.createReturn(createDefaultSuperCallOrThis())); + return 2 /* ReplaceWithReturn */; + } + // The constructor exists, but it and the 'super()' call it contains were generated + // for something like property initializers. + // Create a captured '_this' variable and assume it will subsequently be used. + if (hasSynthesizedSuper) { + captureThisForNode(statements, ctor, createDefaultSuperCallOrThis()); + enableSubstitutionsForCapturedThis(); + return 1 /* ReplaceSuperCapture */; + } + // Most of the time, a 'super' call will be the first real statement in a constructor body. + // In these cases, we'd like to transform these into a *single* statement instead of a declaration + // followed by an assignment statement for '_this'. For instance, if we emitted without an initializer, + // we'd get: + // + // var _this; + // _this = _super.call(...) || this; + // + // instead of + // + // var _this = _super.call(...) || this; + // + // Additionally, if the 'super()' call is the last statement, we should just avoid capturing + // entirely and immediately return the result like so: + // + // return _super.call(...) || this; + // + var firstStatement; + var superCallExpression; + var ctorStatements = ctor.body.statements; + if (statementOffset < ctorStatements.length) { + firstStatement = ctorStatements[statementOffset]; + if (firstStatement.kind === 221 /* ExpressionStatement */ && ts.isSuperCall(firstStatement.expression)) { + superCallExpression = visitImmediateSuperCallInBody(firstStatement.expression); + } + } + // Return the result if we have an immediate super() call on the last statement, + // but only if the constructor itself doesn't use 'this' elsewhere. + if (superCallExpression + && statementOffset === ctorStatements.length - 1 + && !(ctor.transformFlags & (8192 /* ContainsLexicalThis */ | 16384 /* ContainsCapturedLexicalThis */))) { + var returnStatement = ts.createReturn(superCallExpression); + if (superCallExpression.kind !== 204 /* BinaryExpression */ + || superCallExpression.left.kind !== 191 /* CallExpression */) { + ts.Debug.fail("Assumed generated super call would have form 'super.call(...) || this'."); + } + // Shift comments from the original super call to the return statement. + ts.setCommentRange(returnStatement, ts.getCommentRange(ts.setEmitFlags(superCallExpression.left, 1536 /* NoComments */))); + statements.push(returnStatement); + return 2 /* ReplaceWithReturn */; + } + // Perform the capture. + captureThisForNode(statements, ctor, superCallExpression || createActualThis()); + // If we're actually replacing the original statement, we need to signal this to the caller. + if (superCallExpression) { + return 1 /* ReplaceSuperCapture */; + } + return 0 /* NoReplacement */; + } + function createActualThis() { + return ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */); + } + function createDefaultSuperCallOrThis() { + return ts.createLogicalOr(ts.createLogicalAnd(ts.createStrictInequality(ts.createFileLevelUniqueName("_super"), ts.createNull()), ts.createFunctionApply(ts.createFileLevelUniqueName("_super"), createActualThis(), ts.createIdentifier("arguments"))), createActualThis()); + } + /** + * Visits a parameter declaration. + * + * @param node A ParameterDeclaration node. + */ + function visitParameter(node) { + if (node.dotDotDotToken) { + // rest parameters are elided + return undefined; + } + else if (ts.isBindingPattern(node.name)) { + // Binding patterns are converted into a generated name and are + // evaluated inside the function body. + return ts.setOriginalNode(ts.setTextRange(ts.createParameter( + /*decorators*/ undefined, + /*modifiers*/ undefined, + /*dotDotDotToken*/ undefined, ts.getGeneratedNameForNode(node), + /*questionToken*/ undefined, + /*type*/ undefined, + /*initializer*/ undefined), + /*location*/ node), + /*original*/ node); + } + else if (node.initializer) { + // Initializers are elided + return ts.setOriginalNode(ts.setTextRange(ts.createParameter( + /*decorators*/ undefined, + /*modifiers*/ undefined, + /*dotDotDotToken*/ undefined, node.name, + /*questionToken*/ undefined, + /*type*/ undefined, + /*initializer*/ undefined), + /*location*/ node), + /*original*/ node); + } + else { + return node; + } + } + /** + * Gets a value indicating whether we need to add default value assignments for a + * function-like node. + * + * @param node A function-like node. + */ + function shouldAddDefaultValueAssignments(node) { + return (node.transformFlags & 65536 /* ContainsDefaultValueAssignments */) !== 0; + } + /** + * Adds statements to the body of a function-like node if it contains parameters with + * binding patterns or initializers. + * + * @param statements The statements for the new function body. + * @param node A function-like node. + */ + function addDefaultValueAssignmentsIfNeeded(statements, node) { + if (!shouldAddDefaultValueAssignments(node)) { + return; + } + for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { + var parameter = _a[_i]; + var name = parameter.name, initializer = parameter.initializer, dotDotDotToken = parameter.dotDotDotToken; + // A rest parameter cannot have a binding pattern or an initializer, + // so let's just ignore it. + if (dotDotDotToken) { + continue; + } + if (ts.isBindingPattern(name)) { + addDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer); + } + else if (initializer) { + addDefaultValueAssignmentForInitializer(statements, parameter, name, initializer); + } + } + } + /** + * Adds statements to the body of a function-like node for parameters with binding patterns + * + * @param statements The statements for the new function body. + * @param parameter The parameter for the function. + * @param name The name of the parameter. + * @param initializer The initializer for the parameter. + */ + function addDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer) { + var temp = ts.getGeneratedNameForNode(parameter); + // In cases where a binding pattern is simply '[]' or '{}', + // we usually don't want to emit a var declaration; however, in the presence + // of an initializer, we must emit that expression to preserve side effects. + if (name.elements.length > 0) { + statements.push(ts.setEmitFlags(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList(ts.flattenDestructuringBinding(parameter, visitor, context, 0 /* All */, temp))), 1048576 /* CustomPrologue */)); + } + else if (initializer) { + statements.push(ts.setEmitFlags(ts.createExpressionStatement(ts.createAssignment(temp, ts.visitNode(initializer, visitor, ts.isExpression))), 1048576 /* CustomPrologue */)); + } + } + /** + * Adds statements to the body of a function-like node for parameters with initializers. + * + * @param statements The statements for the new function body. + * @param parameter The parameter for the function. + * @param name The name of the parameter. + * @param initializer The initializer for the parameter. + */ + function addDefaultValueAssignmentForInitializer(statements, parameter, name, initializer) { + initializer = ts.visitNode(initializer, visitor, ts.isExpression); + var statement = ts.createIf(ts.createTypeCheck(ts.getSynthesizedClone(name), "undefined"), ts.setEmitFlags(ts.setTextRange(ts.createBlock([ + ts.createExpressionStatement(ts.setEmitFlags(ts.setTextRange(ts.createAssignment(ts.setEmitFlags(ts.getMutableClone(name), 48 /* NoSourceMap */), ts.setEmitFlags(initializer, 48 /* NoSourceMap */ | ts.getEmitFlags(initializer) | 1536 /* NoComments */)), parameter), 1536 /* NoComments */)) + ]), parameter), 1 /* SingleLine */ | 32 /* NoTrailingSourceMap */ | 384 /* NoTokenSourceMaps */ | 1536 /* NoComments */)); + ts.startOnNewLine(statement); + ts.setTextRange(statement, parameter); + ts.setEmitFlags(statement, 384 /* NoTokenSourceMaps */ | 32 /* NoTrailingSourceMap */ | 1048576 /* CustomPrologue */ | 1536 /* NoComments */); + statements.push(statement); + } + /** + * Gets a value indicating whether we need to add statements to handle a rest parameter. + * + * @param node A ParameterDeclaration node. + * @param inConstructorWithSynthesizedSuper A value indicating whether the parameter is + * part of a constructor declaration with a + * synthesized call to `super` + */ + function shouldAddRestParameter(node, inConstructorWithSynthesizedSuper) { + return node && node.dotDotDotToken && node.name.kind === 72 /* Identifier */ && !inConstructorWithSynthesizedSuper; + } + /** + * Adds statements to the body of a function-like node if it contains a rest parameter. + * + * @param statements The statements for the new function body. + * @param node A function-like node. + * @param inConstructorWithSynthesizedSuper A value indicating whether the parameter is + * part of a constructor declaration with a + * synthesized call to `super` + */ + function addRestParameterIfNeeded(statements, node, inConstructorWithSynthesizedSuper) { + var parameter = ts.lastOrUndefined(node.parameters); + if (!shouldAddRestParameter(parameter, inConstructorWithSynthesizedSuper)) { + return; + } + // `declarationName` is the name of the local declaration for the parameter. + var declarationName = ts.getMutableClone(parameter.name); + ts.setEmitFlags(declarationName, 48 /* NoSourceMap */); + // `expressionName` is the name of the parameter used in expressions. + var expressionName = ts.getSynthesizedClone(parameter.name); + var restIndex = node.parameters.length - 1; + var temp = ts.createLoopVariable(); + // var param = []; + statements.push(ts.setEmitFlags(ts.setTextRange(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(declarationName, + /*type*/ undefined, ts.createArrayLiteral([])) + ])), + /*location*/ parameter), 1048576 /* CustomPrologue */)); + // for (var _i = restIndex; _i < arguments.length; _i++) { + // param[_i - restIndex] = arguments[_i]; + // } + var forStatement = ts.createFor(ts.setTextRange(ts.createVariableDeclarationList([ + ts.createVariableDeclaration(temp, /*type*/ undefined, ts.createLiteral(restIndex)) + ]), parameter), ts.setTextRange(ts.createLessThan(temp, ts.createPropertyAccess(ts.createIdentifier("arguments"), "length")), parameter), ts.setTextRange(ts.createPostfixIncrement(temp), parameter), ts.createBlock([ + ts.startOnNewLine(ts.setTextRange(ts.createExpressionStatement(ts.createAssignment(ts.createElementAccess(expressionName, restIndex === 0 + ? temp + : ts.createSubtract(temp, ts.createLiteral(restIndex))), ts.createElementAccess(ts.createIdentifier("arguments"), temp))), + /*location*/ parameter)) + ])); + ts.setEmitFlags(forStatement, 1048576 /* CustomPrologue */); + ts.startOnNewLine(forStatement); + statements.push(forStatement); + } + /** + * Adds a statement to capture the `this` of a function declaration if it is needed. + * + * @param statements The statements for the new function body. + * @param node A node. + */ + function addCaptureThisForNodeIfNeeded(statements, node) { + if (node.transformFlags & 16384 /* ContainsCapturedLexicalThis */ && node.kind !== 197 /* ArrowFunction */) { + captureThisForNode(statements, node, ts.createThis()); + } + } + function captureThisForNode(statements, node, initializer) { + enableSubstitutionsForCapturedThis(); + var captureThisStatement = ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(ts.createFileLevelUniqueName("_this"), + /*type*/ undefined, initializer) + ])); + ts.setEmitFlags(captureThisStatement, 1536 /* NoComments */ | 1048576 /* CustomPrologue */); + ts.setSourceMapRange(captureThisStatement, node); + statements.push(captureThisStatement); + } + function prependCaptureNewTargetIfNeeded(statements, node, copyOnWrite) { + if (hierarchyFacts & 16384 /* NewTarget */) { + var newTarget = void 0; + switch (node.kind) { + case 197 /* ArrowFunction */: + return statements; + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + // Methods and accessors cannot be constructors, so 'new.target' will + // always return 'undefined'. + newTarget = ts.createVoidZero(); + break; + case 157 /* Constructor */: + // Class constructors can only be called with `new`, so `this.constructor` + // should be relatively safe to use. + newTarget = ts.createPropertyAccess(ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */), "constructor"); + break; + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + // Functions can be called or constructed, and may have a `this` due to + // being a member or when calling an imported function via `other_1.f()`. + newTarget = ts.createConditional(ts.createLogicalAnd(ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */), ts.createBinary(ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */), 94 /* InstanceOfKeyword */, ts.getLocalName(node))), ts.createPropertyAccess(ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */), "constructor"), ts.createVoidZero()); + break; + default: + return ts.Debug.failBadSyntaxKind(node); + } + var captureNewTargetStatement = ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(ts.createFileLevelUniqueName("_newTarget"), + /*type*/ undefined, newTarget) + ])); + if (copyOnWrite) { + return [captureNewTargetStatement].concat(statements); + } + statements.unshift(captureNewTargetStatement); + } + return statements; + } + /** + * Adds statements to the class body function for a class to define the members of the + * class. + * + * @param statements The statements for the class body function. + * @param node The ClassExpression or ClassDeclaration node. + */ + function addClassMembers(statements, node) { + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + switch (member.kind) { + case 217 /* SemicolonClassElement */: + statements.push(transformSemicolonClassElementToStatement(member)); + break; + case 156 /* MethodDeclaration */: + statements.push(transformClassMethodDeclarationToStatement(getClassMemberPrefix(node, member), member, node)); + break; + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + var accessors = ts.getAllAccessorDeclarations(node.members, member); + if (member === accessors.firstAccessor) { + statements.push(transformAccessorsToStatement(getClassMemberPrefix(node, member), accessors, node)); + } + break; + case 157 /* Constructor */: + // Constructors are handled in visitClassExpression/visitClassDeclaration + break; + default: + ts.Debug.failBadSyntaxKind(node); + break; + } + } + } + /** + * Transforms a SemicolonClassElement into a statement for a class body function. + * + * @param member The SemicolonClassElement node. + */ + function transformSemicolonClassElementToStatement(member) { + return ts.setTextRange(ts.createEmptyStatement(), member); + } + /** + * Transforms a MethodDeclaration into a statement for a class body function. + * + * @param receiver The receiver for the member. + * @param member The MethodDeclaration node. + */ + function transformClassMethodDeclarationToStatement(receiver, member, container) { + var ancestorFacts = enterSubtree(0 /* None */, 0 /* None */); + var commentRange = ts.getCommentRange(member); + var sourceMapRange = ts.getSourceMapRange(member); + var memberName = ts.createMemberAccessForPropertyName(receiver, ts.visitNode(member.name, visitor, ts.isPropertyName), /*location*/ member.name); + var memberFunction = transformFunctionLikeToExpression(member, /*location*/ member, /*name*/ undefined, container); + ts.setEmitFlags(memberFunction, 1536 /* NoComments */); + ts.setSourceMapRange(memberFunction, sourceMapRange); + var statement = ts.setTextRange(ts.createExpressionStatement(ts.createAssignment(memberName, memberFunction)), + /*location*/ member); + ts.setOriginalNode(statement, member); + ts.setCommentRange(statement, commentRange); + // The location for the statement is used to emit comments only. + // No source map should be emitted for this statement to align with the + // old emitter. + ts.setEmitFlags(statement, 48 /* NoSourceMap */); + exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, hierarchyFacts & 49152 /* PropagateNewTargetMask */ ? 16384 /* NewTarget */ : 0 /* None */); + return statement; + } + /** + * Transforms a set of related of get/set accessors into a statement for a class body function. + * + * @param receiver The receiver for the member. + * @param accessors The set of related get/set accessors. + */ + function transformAccessorsToStatement(receiver, accessors, container) { + var statement = ts.createExpressionStatement(transformAccessorsToExpression(receiver, accessors, container, /*startsOnNewLine*/ false)); + // The location for the statement is used to emit source maps only. + // No comments should be emitted for this statement to align with the + // old emitter. + ts.setEmitFlags(statement, 1536 /* NoComments */); + ts.setSourceMapRange(statement, ts.getSourceMapRange(accessors.firstAccessor)); + return statement; + } + /** + * Transforms a set of related get/set accessors into an expression for either a class + * body function or an ObjectLiteralExpression with computed properties. + * + * @param receiver The receiver for the member. + */ + function transformAccessorsToExpression(receiver, _a, container, startsOnNewLine) { + var firstAccessor = _a.firstAccessor, getAccessor = _a.getAccessor, setAccessor = _a.setAccessor; + var ancestorFacts = enterSubtree(0 /* None */, 0 /* None */); + // To align with source maps in the old emitter, the receiver and property name + // arguments are both mapped contiguously to the accessor name. + var target = ts.getMutableClone(receiver); + ts.setEmitFlags(target, 1536 /* NoComments */ | 32 /* NoTrailingSourceMap */); + ts.setSourceMapRange(target, firstAccessor.name); // TODO: GH#18217 + var propertyName = ts.createExpressionForPropertyName(ts.visitNode(firstAccessor.name, visitor, ts.isPropertyName)); + ts.setEmitFlags(propertyName, 1536 /* NoComments */ | 16 /* NoLeadingSourceMap */); + ts.setSourceMapRange(propertyName, firstAccessor.name); + var properties = []; + if (getAccessor) { + var getterFunction = transformFunctionLikeToExpression(getAccessor, /*location*/ undefined, /*name*/ undefined, container); + ts.setSourceMapRange(getterFunction, ts.getSourceMapRange(getAccessor)); + ts.setEmitFlags(getterFunction, 512 /* NoLeadingComments */); + var getter = ts.createPropertyAssignment("get", getterFunction); + ts.setCommentRange(getter, ts.getCommentRange(getAccessor)); + properties.push(getter); + } + if (setAccessor) { + var setterFunction = transformFunctionLikeToExpression(setAccessor, /*location*/ undefined, /*name*/ undefined, container); + ts.setSourceMapRange(setterFunction, ts.getSourceMapRange(setAccessor)); + ts.setEmitFlags(setterFunction, 512 /* NoLeadingComments */); + var setter = ts.createPropertyAssignment("set", setterFunction); + ts.setCommentRange(setter, ts.getCommentRange(setAccessor)); + properties.push(setter); + } + properties.push(ts.createPropertyAssignment("enumerable", ts.createTrue()), ts.createPropertyAssignment("configurable", ts.createTrue())); + var call = ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"), + /*typeArguments*/ undefined, [ + target, + propertyName, + ts.createObjectLiteral(properties, /*multiLine*/ true) + ]); + if (startsOnNewLine) { + ts.startOnNewLine(call); + } + exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, hierarchyFacts & 49152 /* PropagateNewTargetMask */ ? 16384 /* NewTarget */ : 0 /* None */); + return call; + } + /** + * Visits an ArrowFunction and transforms it into a FunctionExpression. + * + * @param node An ArrowFunction node. + */ + function visitArrowFunction(node) { + if (node.transformFlags & 8192 /* ContainsLexicalThis */) { + enableSubstitutionsForCapturedThis(); + } + var savedConvertedLoopState = convertedLoopState; + convertedLoopState = undefined; + var ancestorFacts = enterSubtree(16256 /* ArrowFunctionExcludes */, 66 /* ArrowFunctionIncludes */); + var func = ts.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, transformFunctionBody(node)); + ts.setTextRange(func, node); + ts.setOriginalNode(func, node); + ts.setEmitFlags(func, 8 /* CapturesThis */); + exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */); + convertedLoopState = savedConvertedLoopState; + return func; + } + /** + * Visits a FunctionExpression node. + * + * @param node a FunctionExpression node. + */ + function visitFunctionExpression(node) { + var ancestorFacts = ts.getEmitFlags(node) & 262144 /* AsyncFunctionBody */ + ? enterSubtree(16278 /* AsyncFunctionBodyExcludes */, 69 /* AsyncFunctionBodyIncludes */) + : enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */); + var savedConvertedLoopState = convertedLoopState; + convertedLoopState = undefined; + var parameters = ts.visitParameterList(node.parameters, visitor, context); + var body = node.transformFlags & 64 /* ES2015 */ + ? transformFunctionBody(node) + : visitFunctionBodyDownLevel(node); + var name = hierarchyFacts & 16384 /* NewTarget */ + ? ts.getLocalName(node) + : node.name; + exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, 0 /* None */); + convertedLoopState = savedConvertedLoopState; + return ts.updateFunctionExpression(node, + /*modifiers*/ undefined, node.asteriskToken, name, + /*typeParameters*/ undefined, parameters, + /*type*/ undefined, body); + } + /** + * Visits a FunctionDeclaration node. + * + * @param node a FunctionDeclaration node. + */ + function visitFunctionDeclaration(node) { + var savedConvertedLoopState = convertedLoopState; + convertedLoopState = undefined; + var ancestorFacts = enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */); + var parameters = ts.visitParameterList(node.parameters, visitor, context); + var body = node.transformFlags & 64 /* ES2015 */ + ? transformFunctionBody(node) + : visitFunctionBodyDownLevel(node); + var name = hierarchyFacts & 16384 /* NewTarget */ + ? ts.getLocalName(node) + : node.name; + exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, 0 /* None */); + convertedLoopState = savedConvertedLoopState; + return ts.updateFunctionDeclaration(node, + /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, name, + /*typeParameters*/ undefined, parameters, + /*type*/ undefined, body); + } + /** + * Transforms a function-like node into a FunctionExpression. + * + * @param node The function-like node to transform. + * @param location The source-map location for the new FunctionExpression. + * @param name The name of the new FunctionExpression. + */ + function transformFunctionLikeToExpression(node, location, name, container) { + var savedConvertedLoopState = convertedLoopState; + convertedLoopState = undefined; + var ancestorFacts = container && ts.isClassLike(container) && !ts.hasModifier(node, 32 /* Static */) + ? enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */ | 8 /* NonStaticClassElement */) + : enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */); + var parameters = ts.visitParameterList(node.parameters, visitor, context); + var body = transformFunctionBody(node); + if (hierarchyFacts & 16384 /* NewTarget */ && !name && (node.kind === 239 /* FunctionDeclaration */ || node.kind === 196 /* FunctionExpression */)) { + name = ts.getGeneratedNameForNode(node); + } + exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, 0 /* None */); + convertedLoopState = savedConvertedLoopState; + return ts.setOriginalNode(ts.setTextRange(ts.createFunctionExpression( + /*modifiers*/ undefined, node.asteriskToken, name, + /*typeParameters*/ undefined, parameters, + /*type*/ undefined, body), location), + /*original*/ node); + } + /** + * Transforms the body of a function-like node. + * + * @param node A function-like node. + */ + function transformFunctionBody(node) { + var multiLine = false; // indicates whether the block *must* be emitted as multiple lines + var singleLine = false; // indicates whether the block *may* be emitted as a single line + var statementsLocation; + var closeBraceLocation; + var leadingStatements = []; + var statements = []; + var body = node.body; + var statementOffset; + resumeLexicalEnvironment(); + if (ts.isBlock(body)) { + // ensureUseStrict is false because no new prologue-directive should be added. + // addStandardPrologue will put already-existing directives at the beginning of the target statement-array + statementOffset = ts.addStandardPrologue(leadingStatements, body.statements, /*ensureUseStrict*/ false); + } + addCaptureThisForNodeIfNeeded(leadingStatements, node); + addDefaultValueAssignmentsIfNeeded(leadingStatements, node); + addRestParameterIfNeeded(leadingStatements, node, /*inConstructorWithSynthesizedSuper*/ false); + if (ts.isBlock(body)) { + // addCustomPrologue puts already-existing directives at the beginning of the target statement-array + statementOffset = ts.addCustomPrologue(leadingStatements, body.statements, statementOffset, visitor); + statementsLocation = body.statements; + ts.addRange(statements, ts.visitNodes(body.statements, visitor, ts.isStatement, statementOffset)); + // If the original body was a multi-line block, this must be a multi-line block. + if (!multiLine && body.multiLine) { + multiLine = true; + } + } + else { + ts.Debug.assert(node.kind === 197 /* ArrowFunction */); + // To align with the old emitter, we use a synthetic end position on the location + // for the statement list we synthesize when we down-level an arrow function with + // an expression function body. This prevents both comments and source maps from + // being emitted for the end position only. + statementsLocation = ts.moveRangeEnd(body, -1); + var equalsGreaterThanToken = node.equalsGreaterThanToken; + if (!ts.nodeIsSynthesized(equalsGreaterThanToken) && !ts.nodeIsSynthesized(body)) { + if (ts.rangeEndIsOnSameLineAsRangeStart(equalsGreaterThanToken, body, currentSourceFile)) { + singleLine = true; + } + else { + multiLine = true; + } + } + var expression = ts.visitNode(body, visitor, ts.isExpression); + var returnStatement = ts.createReturn(expression); + ts.setTextRange(returnStatement, body); + ts.moveSyntheticComments(returnStatement, body); + ts.setEmitFlags(returnStatement, 384 /* NoTokenSourceMaps */ | 32 /* NoTrailingSourceMap */ | 1024 /* NoTrailingComments */); + statements.push(returnStatement); + // To align with the source map emit for the old emitter, we set a custom + // source map location for the close brace. + closeBraceLocation = body; + } + var lexicalEnvironment = context.endLexicalEnvironment(); + ts.addStatementsAfterPrologue(statements, lexicalEnvironment); + prependCaptureNewTargetIfNeeded(statements, node, /*copyOnWrite*/ false); + // If we added any final generated statements, this must be a multi-line block + if (ts.some(leadingStatements) || ts.some(lexicalEnvironment)) { + multiLine = true; + } + var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(leadingStatements.concat(statements)), statementsLocation), multiLine); + ts.setTextRange(block, node.body); + if (!multiLine && singleLine) { + ts.setEmitFlags(block, 1 /* SingleLine */); + } + if (closeBraceLocation) { + ts.setTokenSourceMapRange(block, 19 /* CloseBraceToken */, closeBraceLocation); + } + ts.setOriginalNode(block, node.body); + return block; + } + function visitFunctionBodyDownLevel(node) { + var updated = ts.visitFunctionBody(node.body, functionBodyVisitor, context); + return ts.updateBlock(updated, ts.setTextRange(ts.createNodeArray(prependCaptureNewTargetIfNeeded(updated.statements, node, /*copyOnWrite*/ true)), + /*location*/ updated.statements)); + } + function visitBlock(node, isFunctionBody) { + if (isFunctionBody) { + // A function body is not a block scope. + return ts.visitEachChild(node, visitor, context); + } + var ancestorFacts = hierarchyFacts & 256 /* IterationStatement */ + ? enterSubtree(4032 /* IterationStatementBlockExcludes */, 512 /* IterationStatementBlockIncludes */) + : enterSubtree(3904 /* BlockExcludes */, 128 /* BlockIncludes */); + var updated = ts.visitEachChild(node, visitor, context); + exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */); + return updated; + } + /** + * Visits an ExpressionStatement that contains a destructuring assignment. + * + * @param node An ExpressionStatement node. + */ + function visitExpressionStatement(node) { + // If we are here it is most likely because our expression is a destructuring assignment. + switch (node.expression.kind) { + case 195 /* ParenthesizedExpression */: + return ts.updateExpressionStatement(node, visitParenthesizedExpression(node.expression, /*needsDestructuringValue*/ false)); + case 204 /* BinaryExpression */: + return ts.updateExpressionStatement(node, visitBinaryExpression(node.expression, /*needsDestructuringValue*/ false)); + } + return ts.visitEachChild(node, visitor, context); + } + /** + * Visits a ParenthesizedExpression that may contain a destructuring assignment. + * + * @param node A ParenthesizedExpression node. + * @param needsDestructuringValue A value indicating whether we need to hold onto the rhs + * of a destructuring assignment. + */ + function visitParenthesizedExpression(node, needsDestructuringValue) { + // If we are here it is most likely because our expression is a destructuring assignment. + if (!needsDestructuringValue) { + // By default we always emit the RHS at the end of a flattened destructuring + // expression. If we are in a state where we do not need the destructuring value, + // we pass that information along to the children that care about it. + switch (node.expression.kind) { + case 195 /* ParenthesizedExpression */: + return ts.updateParen(node, visitParenthesizedExpression(node.expression, /*needsDestructuringValue*/ false)); + case 204 /* BinaryExpression */: + return ts.updateParen(node, visitBinaryExpression(node.expression, /*needsDestructuringValue*/ false)); + } + } + return ts.visitEachChild(node, visitor, context); + } + /** + * Visits a BinaryExpression that contains a destructuring assignment. + * + * @param node A BinaryExpression node. + * @param needsDestructuringValue A value indicating whether we need to hold onto the rhs + * of a destructuring assignment. + */ + function visitBinaryExpression(node, needsDestructuringValue) { + // If we are here it is because this is a destructuring assignment. + if (ts.isDestructuringAssignment(node)) { + return ts.flattenDestructuringAssignment(node, visitor, context, 0 /* All */, needsDestructuringValue); + } + return ts.visitEachChild(node, visitor, context); + } + function visitVariableStatement(node) { + var ancestorFacts = enterSubtree(0 /* None */, ts.hasModifier(node, 1 /* Export */) ? 32 /* ExportedVariableStatement */ : 0 /* None */); + var updated; + if (convertedLoopState && (node.declarationList.flags & 3 /* BlockScoped */) === 0) { + // we are inside a converted loop - hoist variable declarations + var assignments = void 0; + for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + hoistVariableDeclarationDeclaredInConvertedLoop(convertedLoopState, decl); + if (decl.initializer) { + var assignment = void 0; + if (ts.isBindingPattern(decl.name)) { + assignment = ts.flattenDestructuringAssignment(decl, visitor, context, 0 /* All */); + } + else { + assignment = ts.createBinary(decl.name, 59 /* EqualsToken */, ts.visitNode(decl.initializer, visitor, ts.isExpression)); + ts.setTextRange(assignment, decl); + } + assignments = ts.append(assignments, assignment); + } + } + if (assignments) { + updated = ts.setTextRange(ts.createExpressionStatement(ts.inlineExpressions(assignments)), node); + } + else { + // none of declarations has initializer - the entire variable statement can be deleted + updated = undefined; + } + } + else { + updated = ts.visitEachChild(node, visitor, context); + } + exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */); + return updated; + } + /** + * Visits a VariableDeclarationList that is block scoped (e.g. `let` or `const`). + * + * @param node A VariableDeclarationList node. + */ + function visitVariableDeclarationList(node) { + if (node.transformFlags & 64 /* ES2015 */) { + if (node.flags & 3 /* BlockScoped */) { + enableSubstitutionsForBlockScopedBindings(); + } + var declarations = ts.flatMap(node.declarations, node.flags & 1 /* Let */ + ? visitVariableDeclarationInLetDeclarationList + : visitVariableDeclaration); + var declarationList = ts.createVariableDeclarationList(declarations); + ts.setOriginalNode(declarationList, node); + ts.setTextRange(declarationList, node); + ts.setCommentRange(declarationList, node); + // If the first or last declaration is a binding pattern, we need to modify + // the source map range for the declaration list. + if (node.transformFlags & 2097152 /* ContainsBindingPattern */ + && (ts.isBindingPattern(node.declarations[0].name) || ts.isBindingPattern(ts.last(node.declarations).name))) { + ts.setSourceMapRange(declarationList, getRangeUnion(declarations)); + } + return declarationList; + } + return ts.visitEachChild(node, visitor, context); + } + function getRangeUnion(declarations) { + // declarations may not be sorted by position. + // pos should be the minimum* position over all nodes (that's not -1), end should be the maximum end over all nodes. + var pos = -1, end = -1; + for (var _i = 0, declarations_10 = declarations; _i < declarations_10.length; _i++) { + var node = declarations_10[_i]; + pos = pos === -1 ? node.pos : node.pos === -1 ? pos : Math.min(pos, node.pos); + end = Math.max(end, node.end); + } + return ts.createRange(pos, end); + } + /** + * Gets a value indicating whether we should emit an explicit initializer for a variable + * declaration in a `let` declaration list. + * + * @param node A VariableDeclaration node. + */ + function shouldEmitExplicitInitializerForLetDeclaration(node) { + // Nested let bindings might need to be initialized explicitly to preserve + // ES6 semantic: + // + // { let x = 1; } + // { let x; } // x here should be undefined. not 1 + // + // Top level bindings never collide with anything and thus don't require + // explicit initialization. As for nested let bindings there are two cases: + // + // - Nested let bindings that were not renamed definitely should be + // initialized explicitly: + // + // { let x = 1; } + // { let x; if (some-condition) { x = 1}; if (x) { /*1*/ } } + // + // Without explicit initialization code in /*1*/ can be executed even if + // some-condition is evaluated to false. + // + // - Renaming introduces fresh name that should not collide with any + // existing names, however renamed bindings sometimes also should be + // explicitly initialized. One particular case: non-captured binding + // declared inside loop body (but not in loop initializer): + // + // let x; + // for (;;) { + // let x; + // } + // + // In downlevel codegen inner 'x' will be renamed so it won't collide + // with outer 'x' however it will should be reset on every iteration as + // if it was declared anew. + // + // * Why non-captured binding? + // - Because if loop contains block scoped binding captured in some + // function then loop body will be rewritten to have a fresh scope + // on every iteration so everything will just work. + // + // * Why loop initializer is excluded? + // - Since we've introduced a fresh name it already will be undefined. + var flags = resolver.getNodeCheckFlags(node); + var isCapturedInFunction = flags & 262144 /* CapturedBlockScopedBinding */; + var isDeclaredInLoop = flags & 524288 /* BlockScopedBindingInLoop */; + var emittedAsTopLevel = (hierarchyFacts & 64 /* TopLevel */) !== 0 + || (isCapturedInFunction + && isDeclaredInLoop + && (hierarchyFacts & 512 /* IterationStatementBlock */) !== 0); + var emitExplicitInitializer = !emittedAsTopLevel + && (hierarchyFacts & 2048 /* ForInOrForOfStatement */) === 0 + && (!resolver.isDeclarationWithCollidingName(node) + || (isDeclaredInLoop + && !isCapturedInFunction + && (hierarchyFacts & (1024 /* ForStatement */ | 2048 /* ForInOrForOfStatement */)) === 0)); + return emitExplicitInitializer; + } + /** + * Visits a VariableDeclaration in a `let` declaration list. + * + * @param node A VariableDeclaration node. + */ + function visitVariableDeclarationInLetDeclarationList(node) { + // For binding pattern names that lack initializers there is no point to emit + // explicit initializer since downlevel codegen for destructuring will fail + // in the absence of initializer so all binding elements will say uninitialized + var name = node.name; + if (ts.isBindingPattern(name)) { + return visitVariableDeclaration(node); + } + if (!node.initializer && shouldEmitExplicitInitializerForLetDeclaration(node)) { + var clone_2 = ts.getMutableClone(node); + clone_2.initializer = ts.createVoidZero(); + return clone_2; + } + return ts.visitEachChild(node, visitor, context); + } + /** + * Visits a VariableDeclaration node with a binding pattern. + * + * @param node A VariableDeclaration node. + */ + function visitVariableDeclaration(node) { + var ancestorFacts = enterSubtree(32 /* ExportedVariableStatement */, 0 /* None */); + var updated; + if (ts.isBindingPattern(node.name)) { + updated = ts.flattenDestructuringBinding(node, visitor, context, 0 /* All */, + /*value*/ undefined, (ancestorFacts & 32 /* ExportedVariableStatement */) !== 0); + } + else { + updated = ts.visitEachChild(node, visitor, context); + } + exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */); + return updated; + } + function recordLabel(node) { + convertedLoopState.labels.set(ts.idText(node.label), true); + } + function resetLabel(node) { + convertedLoopState.labels.set(ts.idText(node.label), false); + } + function visitLabeledStatement(node) { + if (convertedLoopState && !convertedLoopState.labels) { + convertedLoopState.labels = ts.createMap(); + } + var statement = ts.unwrapInnermostStatementOfLabel(node, convertedLoopState && recordLabel); + return ts.isIterationStatement(statement, /*lookInLabeledStatements*/ false) + ? visitIterationStatement(statement, /*outermostLabeledStatement*/ node) + : ts.restoreEnclosingLabel(ts.visitNode(statement, visitor, ts.isStatement, ts.liftToBlock), node, convertedLoopState && resetLabel); + } + function visitIterationStatement(node, outermostLabeledStatement) { + switch (node.kind) { + case 223 /* DoStatement */: + case 224 /* WhileStatement */: + return visitDoOrWhileStatement(node, outermostLabeledStatement); + case 225 /* ForStatement */: + return visitForStatement(node, outermostLabeledStatement); + case 226 /* ForInStatement */: + return visitForInStatement(node, outermostLabeledStatement); + case 227 /* ForOfStatement */: + return visitForOfStatement(node, outermostLabeledStatement); + } + } + function visitIterationStatementWithFacts(excludeFacts, includeFacts, node, outermostLabeledStatement, convert) { + var ancestorFacts = enterSubtree(excludeFacts, includeFacts); + var updated = convertIterationStatementBodyIfNecessary(node, outermostLabeledStatement, convert); + exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */); + return updated; + } + function visitDoOrWhileStatement(node, outermostLabeledStatement) { + return visitIterationStatementWithFacts(0 /* DoOrWhileStatementExcludes */, 256 /* DoOrWhileStatementIncludes */, node, outermostLabeledStatement); + } + function visitForStatement(node, outermostLabeledStatement) { + return visitIterationStatementWithFacts(3008 /* ForStatementExcludes */, 1280 /* ForStatementIncludes */, node, outermostLabeledStatement); + } + function visitForInStatement(node, outermostLabeledStatement) { + return visitIterationStatementWithFacts(1984 /* ForInOrForOfStatementExcludes */, 2304 /* ForInOrForOfStatementIncludes */, node, outermostLabeledStatement); + } + function visitForOfStatement(node, outermostLabeledStatement) { + return visitIterationStatementWithFacts(1984 /* ForInOrForOfStatementExcludes */, 2304 /* ForInOrForOfStatementIncludes */, node, outermostLabeledStatement, compilerOptions.downlevelIteration ? convertForOfStatementForIterable : convertForOfStatementForArray); + } + function convertForOfStatementHead(node, boundValue, convertedLoopBodyStatements) { + var statements = []; + var initializer = node.initializer; + if (ts.isVariableDeclarationList(initializer)) { + if (node.initializer.flags & 3 /* BlockScoped */) { + enableSubstitutionsForBlockScopedBindings(); + } + var firstOriginalDeclaration = ts.firstOrUndefined(initializer.declarations); + if (firstOriginalDeclaration && ts.isBindingPattern(firstOriginalDeclaration.name)) { + // This works whether the declaration is a var, let, or const. + // It will use rhsIterationValue _a[_i] as the initializer. + var declarations = ts.flattenDestructuringBinding(firstOriginalDeclaration, visitor, context, 0 /* All */, boundValue); + var declarationList = ts.setTextRange(ts.createVariableDeclarationList(declarations), node.initializer); + ts.setOriginalNode(declarationList, node.initializer); + // Adjust the source map range for the first declaration to align with the old + // emitter. + ts.setSourceMapRange(declarationList, ts.createRange(declarations[0].pos, ts.last(declarations).end)); + statements.push(ts.createVariableStatement( + /*modifiers*/ undefined, declarationList)); + } + else { + // The following call does not include the initializer, so we have + // to emit it separately. + statements.push(ts.setTextRange(ts.createVariableStatement( + /*modifiers*/ undefined, ts.setOriginalNode(ts.setTextRange(ts.createVariableDeclarationList([ + ts.createVariableDeclaration(firstOriginalDeclaration ? firstOriginalDeclaration.name : ts.createTempVariable(/*recordTempVariable*/ undefined), + /*type*/ undefined, boundValue) + ]), ts.moveRangePos(initializer, -1)), initializer)), ts.moveRangeEnd(initializer, -1))); + } + } + else { + // Initializer is an expression. Emit the expression in the body, so that it's + // evaluated on every iteration. + var assignment = ts.createAssignment(initializer, boundValue); + if (ts.isDestructuringAssignment(assignment)) { + ts.aggregateTransformFlags(assignment); + statements.push(ts.createExpressionStatement(visitBinaryExpression(assignment, /*needsDestructuringValue*/ false))); + } + else { + assignment.end = initializer.end; + statements.push(ts.setTextRange(ts.createExpressionStatement(ts.visitNode(assignment, visitor, ts.isExpression)), ts.moveRangeEnd(initializer, -1))); + } + } + if (convertedLoopBodyStatements) { + return createSyntheticBlockForConvertedStatements(ts.addRange(statements, convertedLoopBodyStatements)); + } + else { + var statement = ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock); + if (ts.isBlock(statement)) { + return ts.updateBlock(statement, ts.setTextRange(ts.createNodeArray(ts.concatenate(statements, statement.statements)), statement.statements)); + } + else { + statements.push(statement); + return createSyntheticBlockForConvertedStatements(statements); + } + } + } + function createSyntheticBlockForConvertedStatements(statements) { + return ts.setEmitFlags(ts.createBlock(ts.createNodeArray(statements), + /*multiLine*/ true), 48 /* NoSourceMap */ | 384 /* NoTokenSourceMaps */); + } + function convertForOfStatementForArray(node, outermostLabeledStatement, convertedLoopBodyStatements) { + // The following ES6 code: + // + // for (let v of expr) { } + // + // should be emitted as + // + // for (var _i = 0, _a = expr; _i < _a.length; _i++) { + // var v = _a[_i]; + // } + // + // where _a and _i are temps emitted to capture the RHS and the counter, + // respectively. + // When the left hand side is an expression instead of a let declaration, + // the "let v" is not emitted. + // When the left hand side is a let/const, the v is renamed if there is + // another v in scope. + // Note that all assignments to the LHS are emitted in the body, including + // all destructuring. + // Note also that because an extra statement is needed to assign to the LHS, + // for-of bodies are always emitted as blocks. + var expression = ts.visitNode(node.expression, visitor, ts.isExpression); + // In the case where the user wrote an identifier as the RHS, like this: + // + // for (let v of arr) { } + // + // we don't want to emit a temporary variable for the RHS, just use it directly. + var counter = ts.createLoopVariable(); + var rhsReference = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(expression) : ts.createTempVariable(/*recordTempVariable*/ undefined); + // The old emitter does not emit source maps for the expression + ts.setEmitFlags(expression, 48 /* NoSourceMap */ | ts.getEmitFlags(expression)); + var forStatement = ts.setTextRange(ts.createFor( + /*initializer*/ ts.setEmitFlags(ts.setTextRange(ts.createVariableDeclarationList([ + ts.setTextRange(ts.createVariableDeclaration(counter, /*type*/ undefined, ts.createLiteral(0)), ts.moveRangePos(node.expression, -1)), + ts.setTextRange(ts.createVariableDeclaration(rhsReference, /*type*/ undefined, expression), node.expression) + ]), node.expression), 2097152 /* NoHoisting */), + /*condition*/ ts.setTextRange(ts.createLessThan(counter, ts.createPropertyAccess(rhsReference, "length")), node.expression), + /*incrementor*/ ts.setTextRange(ts.createPostfixIncrement(counter), node.expression), + /*statement*/ convertForOfStatementHead(node, ts.createElementAccess(rhsReference, counter), convertedLoopBodyStatements)), + /*location*/ node); + // Disable trailing source maps for the OpenParenToken to align source map emit with the old emitter. + ts.setEmitFlags(forStatement, 256 /* NoTokenTrailingSourceMaps */); + ts.setTextRange(forStatement, node); + return ts.restoreEnclosingLabel(forStatement, outermostLabeledStatement, convertedLoopState && resetLabel); + } + function convertForOfStatementForIterable(node, outermostLabeledStatement, convertedLoopBodyStatements) { + var expression = ts.visitNode(node.expression, visitor, ts.isExpression); + var iterator = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(expression) : ts.createTempVariable(/*recordTempVariable*/ undefined); + var result = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(iterator) : ts.createTempVariable(/*recordTempVariable*/ undefined); + var errorRecord = ts.createUniqueName("e"); + var catchVariable = ts.getGeneratedNameForNode(errorRecord); + var returnMethod = ts.createTempVariable(/*recordTempVariable*/ undefined); + var values = ts.createValuesHelper(context, expression, node.expression); + var next = ts.createCall(ts.createPropertyAccess(iterator, "next"), /*typeArguments*/ undefined, []); + hoistVariableDeclaration(errorRecord); + hoistVariableDeclaration(returnMethod); + var forStatement = ts.setEmitFlags(ts.setTextRange(ts.createFor( + /*initializer*/ ts.setEmitFlags(ts.setTextRange(ts.createVariableDeclarationList([ + ts.setTextRange(ts.createVariableDeclaration(iterator, /*type*/ undefined, values), node.expression), + ts.createVariableDeclaration(result, /*type*/ undefined, next) + ]), node.expression), 2097152 /* NoHoisting */), + /*condition*/ ts.createLogicalNot(ts.createPropertyAccess(result, "done")), + /*incrementor*/ ts.createAssignment(result, next), + /*statement*/ convertForOfStatementHead(node, ts.createPropertyAccess(result, "value"), convertedLoopBodyStatements)), + /*location*/ node), 256 /* NoTokenTrailingSourceMaps */); + return ts.createTry(ts.createBlock([ + ts.restoreEnclosingLabel(forStatement, outermostLabeledStatement, convertedLoopState && resetLabel) + ]), ts.createCatchClause(ts.createVariableDeclaration(catchVariable), ts.setEmitFlags(ts.createBlock([ + ts.createExpressionStatement(ts.createAssignment(errorRecord, ts.createObjectLiteral([ + ts.createPropertyAssignment("error", catchVariable) + ]))) + ]), 1 /* SingleLine */)), ts.createBlock([ + ts.createTry( + /*tryBlock*/ ts.createBlock([ + ts.setEmitFlags(ts.createIf(ts.createLogicalAnd(ts.createLogicalAnd(result, ts.createLogicalNot(ts.createPropertyAccess(result, "done"))), ts.createAssignment(returnMethod, ts.createPropertyAccess(iterator, "return"))), ts.createExpressionStatement(ts.createFunctionCall(returnMethod, iterator, []))), 1 /* SingleLine */), + ]), + /*catchClause*/ undefined, + /*finallyBlock*/ ts.setEmitFlags(ts.createBlock([ + ts.setEmitFlags(ts.createIf(errorRecord, ts.createThrow(ts.createPropertyAccess(errorRecord, "error"))), 1 /* SingleLine */) + ]), 1 /* SingleLine */)) + ])); + } + /** + * Visits an ObjectLiteralExpression with computed property names. + * + * @param node An ObjectLiteralExpression node. + */ + function visitObjectLiteralExpression(node) { + // We are here because a ComputedPropertyName was used somewhere in the expression. + var properties = node.properties; + var numProperties = properties.length; + // Find the first computed property. + // Everything until that point can be emitted as part of the initial object literal. + var numInitialProperties = numProperties; + var numInitialPropertiesWithoutYield = numProperties; + for (var i = 0; i < numProperties; i++) { + var property = properties[i]; + if ((property.transformFlags & 4194304 /* ContainsYield */ && hierarchyFacts & 4 /* AsyncFunctionBody */) + && i < numInitialPropertiesWithoutYield) { + numInitialPropertiesWithoutYield = i; + } + if (property.name.kind === 149 /* ComputedPropertyName */) { + numInitialProperties = i; + break; + } + } + if (numInitialProperties !== numProperties) { + if (numInitialPropertiesWithoutYield < numInitialProperties) { + numInitialProperties = numInitialPropertiesWithoutYield; + } + // For computed properties, we need to create a unique handle to the object + // literal so we can modify it without risking internal assignments tainting the object. + var temp = ts.createTempVariable(hoistVariableDeclaration); + // Write out the first non-computed properties, then emit the rest through indexing on the temp variable. + var expressions = []; + var assignment = ts.createAssignment(temp, ts.setEmitFlags(ts.createObjectLiteral(ts.visitNodes(properties, visitor, ts.isObjectLiteralElementLike, 0, numInitialProperties), node.multiLine), 65536 /* Indented */)); + if (node.multiLine) { + ts.startOnNewLine(assignment); + } + expressions.push(assignment); + addObjectLiteralMembers(expressions, node, temp, numInitialProperties); + // We need to clone the temporary identifier so that we can write it on a + // new line + expressions.push(node.multiLine ? ts.startOnNewLine(ts.getMutableClone(temp)) : temp); + return ts.inlineExpressions(expressions); + } + return ts.visitEachChild(node, visitor, context); + } + function shouldConvertPartOfIterationStatement(node) { + return (resolver.getNodeCheckFlags(node) & 131072 /* ContainsCapturedBlockScopeBinding */) !== 0; + } + function shouldConvertInitializerOfForStatement(node) { + return ts.isForStatement(node) && !!node.initializer && shouldConvertPartOfIterationStatement(node.initializer); + } + function shouldConvertConditionOfForStatement(node) { + return ts.isForStatement(node) && !!node.condition && shouldConvertPartOfIterationStatement(node.condition); + } + function shouldConvertIncrementorOfForStatement(node) { + return ts.isForStatement(node) && !!node.incrementor && shouldConvertPartOfIterationStatement(node.incrementor); + } + function shouldConvertIterationStatement(node) { + return shouldConvertBodyOfIterationStatement(node) + || shouldConvertInitializerOfForStatement(node); + } + function shouldConvertBodyOfIterationStatement(node) { + return (resolver.getNodeCheckFlags(node) & 65536 /* LoopWithCapturedBlockScopedBinding */) !== 0; + } + /** + * Records constituents of name for the given variable to be hoisted in the outer scope. + */ + function hoistVariableDeclarationDeclaredInConvertedLoop(state, node) { + if (!state.hoistedLocalVariables) { + state.hoistedLocalVariables = []; + } + visit(node.name); + function visit(node) { + if (node.kind === 72 /* Identifier */) { + state.hoistedLocalVariables.push(node); + } + else { + for (var _i = 0, _a = node.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (!ts.isOmittedExpression(element)) { + visit(element.name); + } + } + } + } + } + function convertIterationStatementBodyIfNecessary(node, outermostLabeledStatement, convert) { + if (!shouldConvertIterationStatement(node)) { + var saveAllowedNonLabeledJumps = void 0; + if (convertedLoopState) { + // we get here if we are trying to emit normal loop loop inside converted loop + // set allowedNonLabeledJumps to Break | Continue to mark that break\continue inside the loop should be emitted as is + saveAllowedNonLabeledJumps = convertedLoopState.allowedNonLabeledJumps; + convertedLoopState.allowedNonLabeledJumps = 2 /* Break */ | 4 /* Continue */; + } + var result = convert + ? convert(node, outermostLabeledStatement, /*convertedLoopBodyStatements*/ undefined) + : ts.restoreEnclosingLabel(ts.visitEachChild(node, visitor, context), outermostLabeledStatement, convertedLoopState && resetLabel); + if (convertedLoopState) { + convertedLoopState.allowedNonLabeledJumps = saveAllowedNonLabeledJumps; + } + return result; + } + var currentState = createConvertedLoopState(node); + var statements = []; + var outerConvertedLoopState = convertedLoopState; + convertedLoopState = currentState; + var initializerFunction = shouldConvertInitializerOfForStatement(node) ? createFunctionForInitializerOfForStatement(node, currentState) : undefined; + var bodyFunction = shouldConvertBodyOfIterationStatement(node) ? createFunctionForBodyOfIterationStatement(node, currentState, outerConvertedLoopState) : undefined; + convertedLoopState = outerConvertedLoopState; + if (initializerFunction) + statements.push(initializerFunction.functionDeclaration); + if (bodyFunction) + statements.push(bodyFunction.functionDeclaration); + addExtraDeclarationsForConvertedLoop(statements, currentState, outerConvertedLoopState); + if (initializerFunction) { + statements.push(generateCallToConvertedLoopInitializer(initializerFunction.functionName, initializerFunction.containsYield)); + } + var loop; + if (bodyFunction) { + if (convert) { + loop = convert(node, outermostLabeledStatement, bodyFunction.part); + } + else { + var clone_3 = convertIterationStatementCore(node, initializerFunction, ts.createBlock(bodyFunction.part, /*multiLine*/ true)); + ts.aggregateTransformFlags(clone_3); + loop = ts.restoreEnclosingLabel(clone_3, outermostLabeledStatement, convertedLoopState && resetLabel); + } + } + else { + var clone_4 = convertIterationStatementCore(node, initializerFunction, ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); + ts.aggregateTransformFlags(clone_4); + loop = ts.restoreEnclosingLabel(clone_4, outermostLabeledStatement, convertedLoopState && resetLabel); + } + statements.push(loop); + return statements; + } + function convertIterationStatementCore(node, initializerFunction, convertedLoopBody) { + switch (node.kind) { + case 225 /* ForStatement */: return convertForStatement(node, initializerFunction, convertedLoopBody); + case 226 /* ForInStatement */: return convertForInStatement(node, convertedLoopBody); + case 227 /* ForOfStatement */: return convertForOfStatement(node, convertedLoopBody); + case 223 /* DoStatement */: return convertDoStatement(node, convertedLoopBody); + case 224 /* WhileStatement */: return convertWhileStatement(node, convertedLoopBody); + default: return ts.Debug.failBadSyntaxKind(node, "IterationStatement expected"); + } + } + function convertForStatement(node, initializerFunction, convertedLoopBody) { + var shouldConvertCondition = node.condition && shouldConvertPartOfIterationStatement(node.condition); + var shouldConvertIncrementor = shouldConvertCondition || node.incrementor && shouldConvertPartOfIterationStatement(node.incrementor); + return ts.updateFor(node, ts.visitNode(initializerFunction ? initializerFunction.part : node.initializer, visitor, ts.isForInitializer), ts.visitNode(shouldConvertCondition ? undefined : node.condition, visitor, ts.isExpression), ts.visitNode(shouldConvertIncrementor ? undefined : node.incrementor, visitor, ts.isExpression), convertedLoopBody); + } + function convertForOfStatement(node, convertedLoopBody) { + return ts.updateForOf(node, + /*awaitModifier*/ undefined, ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), convertedLoopBody); + } + function convertForInStatement(node, convertedLoopBody) { + return ts.updateForIn(node, ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), convertedLoopBody); + } + function convertDoStatement(node, convertedLoopBody) { + return ts.updateDo(node, convertedLoopBody, ts.visitNode(node.expression, visitor, ts.isExpression)); + } + function convertWhileStatement(node, convertedLoopBody) { + return ts.updateWhile(node, ts.visitNode(node.expression, visitor, ts.isExpression), convertedLoopBody); + } + function createConvertedLoopState(node) { + var loopInitializer; + switch (node.kind) { + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + var initializer = node.initializer; + if (initializer && initializer.kind === 238 /* VariableDeclarationList */) { + loopInitializer = initializer; + } + break; + } + // variables that will be passed to the loop as parameters + var loopParameters = []; + // variables declared in the loop initializer that will be changed inside the loop + var loopOutParameters = []; + if (loopInitializer && (ts.getCombinedNodeFlags(loopInitializer) & 3 /* BlockScoped */)) { + var hasCapturedBindingsInForInitializer = shouldConvertInitializerOfForStatement(node); + for (var _i = 0, _a = loopInitializer.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + processLoopVariableDeclaration(node, decl, loopParameters, loopOutParameters, hasCapturedBindingsInForInitializer); + } + } + var currentState = { loopParameters: loopParameters, loopOutParameters: loopOutParameters }; + if (convertedLoopState) { + // convertedOuterLoopState !== undefined means that this converted loop is nested in another converted loop. + // if outer converted loop has already accumulated some state - pass it through + if (convertedLoopState.argumentsName) { + // outer loop has already used 'arguments' so we've already have some name to alias it + // use the same name in all nested loops + currentState.argumentsName = convertedLoopState.argumentsName; + } + if (convertedLoopState.thisName) { + // outer loop has already used 'this' so we've already have some name to alias it + // use the same name in all nested loops + currentState.thisName = convertedLoopState.thisName; + } + if (convertedLoopState.hoistedLocalVariables) { + // we've already collected some non-block scoped variable declarations in enclosing loop + // use the same storage in nested loop + currentState.hoistedLocalVariables = convertedLoopState.hoistedLocalVariables; + } + } + return currentState; + } + function addExtraDeclarationsForConvertedLoop(statements, state, outerState) { + var extraVariableDeclarations; + // propagate state from the inner loop to the outer loop if necessary + if (state.argumentsName) { + // if alias for arguments is set + if (outerState) { + // pass it to outer converted loop + outerState.argumentsName = state.argumentsName; + } + else { + // this is top level converted loop and we need to create an alias for 'arguments' object + (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(state.argumentsName, + /*type*/ undefined, ts.createIdentifier("arguments"))); + } + } + if (state.thisName) { + // if alias for this is set + if (outerState) { + // pass it to outer converted loop + outerState.thisName = state.thisName; + } + else { + // this is top level converted loop so we need to create an alias for 'this' here + // NOTE: + // if converted loops were all nested in arrow function then we'll always emit '_this' so convertedLoopState.thisName will not be set. + // If it is set this means that all nested loops are not nested in arrow function and it is safe to capture 'this'. + (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(state.thisName, + /*type*/ undefined, ts.createIdentifier("this"))); + } + } + if (state.hoistedLocalVariables) { + // if hoistedLocalVariables !== undefined this means that we've possibly collected some variable declarations to be hoisted later + if (outerState) { + // pass them to outer converted loop + outerState.hoistedLocalVariables = state.hoistedLocalVariables; + } + else { + if (!extraVariableDeclarations) { + extraVariableDeclarations = []; + } + // hoist collected variable declarations + for (var _i = 0, _a = state.hoistedLocalVariables; _i < _a.length; _i++) { + var identifier = _a[_i]; + extraVariableDeclarations.push(ts.createVariableDeclaration(identifier)); + } + } + } + // add extra variables to hold out parameters if necessary + if (state.loopOutParameters.length) { + if (!extraVariableDeclarations) { + extraVariableDeclarations = []; + } + for (var _b = 0, _c = state.loopOutParameters; _b < _c.length; _b++) { + var outParam = _c[_b]; + extraVariableDeclarations.push(ts.createVariableDeclaration(outParam.outParamName)); + } + } + if (state.conditionVariable) { + if (!extraVariableDeclarations) { + extraVariableDeclarations = []; + } + extraVariableDeclarations.push(ts.createVariableDeclaration(state.conditionVariable, /*type*/ undefined, ts.createFalse())); + } + // create variable statement to hold all introduced variable declarations + if (extraVariableDeclarations) { + statements.push(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList(extraVariableDeclarations))); + } + } + function createOutVariable(p) { + return ts.createVariableDeclaration(p.originalName, /*type*/ undefined, p.outParamName); + } + /** + * Creates a `_loop_init` function for a `ForStatement` with a block-scoped initializer + * that is captured in a closure inside of the initializer. The `_loop_init` function is + * used to preserve the per-iteration environment semantics of + * [13.7.4.8 RS: ForBodyEvaluation](https://tc39.github.io/ecma262/#sec-forbodyevaluation). + */ + function createFunctionForInitializerOfForStatement(node, currentState) { + var functionName = ts.createUniqueName("_loop_init"); + var containsYield = (node.initializer.transformFlags & 4194304 /* ContainsYield */) !== 0; + var emitFlags = 0 /* None */; + if (currentState.containsLexicalThis) + emitFlags |= 8 /* CapturesThis */; + if (containsYield && hierarchyFacts & 4 /* AsyncFunctionBody */) + emitFlags |= 262144 /* AsyncFunctionBody */; + var statements = []; + statements.push(ts.createVariableStatement(/*modifiers*/ undefined, node.initializer)); + copyOutParameters(currentState.loopOutParameters, 2 /* Initializer */, 1 /* ToOutParameter */, statements); + // This transforms the following ES2015 syntax: + // + // for (let i = (setImmediate(() => console.log(i)), 0); i < 2; i++) { + // // loop body + // } + // + // Into the following ES5 syntax: + // + // var _loop_init_1 = function () { + // var i = (setImmediate(() => console.log(i)), 0); + // out_i_1 = i; + // }; + // var out_i_1; + // _loop_init_1(); + // for (var i = out_i_1; i < 2; i++) { + // // loop body + // } + // + // Which prevents mutations to `i` in the per-iteration environment of the body + // from affecting the initial value for `i` outside of the per-iteration environment. + var functionDeclaration = ts.createVariableStatement( + /*modifiers*/ undefined, ts.setEmitFlags(ts.createVariableDeclarationList([ + ts.createVariableDeclaration(functionName, + /*type*/ undefined, ts.setEmitFlags(ts.createFunctionExpression( + /*modifiers*/ undefined, containsYield ? ts.createToken(40 /* AsteriskToken */) : undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, + /*parameters*/ undefined, + /*type*/ undefined, ts.visitNode(ts.createBlock(statements, /*multiLine*/ true), visitor, ts.isBlock)), emitFlags)) + ]), 2097152 /* NoHoisting */)); + var part = ts.createVariableDeclarationList(ts.map(currentState.loopOutParameters, createOutVariable)); + return { functionName: functionName, containsYield: containsYield, functionDeclaration: functionDeclaration, part: part }; + } + /** + * Creates a `_loop` function for an `IterationStatement` with a block-scoped initializer + * that is captured in a closure inside of the loop body. The `_loop` function is used to + * preserve the per-iteration environment semantics of + * [13.7.4.8 RS: ForBodyEvaluation](https://tc39.github.io/ecma262/#sec-forbodyevaluation). + */ + function createFunctionForBodyOfIterationStatement(node, currentState, outerState) { + var functionName = ts.createUniqueName("_loop"); + startLexicalEnvironment(); + var statement = ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock); + var lexicalEnvironment = endLexicalEnvironment(); + var statements = []; + if (shouldConvertConditionOfForStatement(node) || shouldConvertIncrementorOfForStatement(node)) { + // If a block-scoped variable declared in the initializer of `node` is captured in + // the condition or incrementor, we must move the condition and incrementor into + // the body of the for loop. + // + // This transforms the following ES2015 syntax: + // + // for (let i = 0; setImmediate(() => console.log(i)), i < 2; setImmediate(() => console.log(i)), i++) { + // // loop body + // } + // + // Into the following ES5 syntax: + // + // var _loop_1 = function (i) { + // if (inc_1) + // setImmediate(() => console.log(i)), i++; + // else + // inc_1 = true; + // if (!(setImmediate(() => console.log(i)), i < 2)) + // return out_i_1 = i, "break"; + // // loop body + // out_i_1 = i; + // } + // var out_i_1, inc_1 = false; + // for (var i = 0;;) { + // var state_1 = _loop_1(i); + // i = out_i_1; + // if (state_1 === "break") + // break; + // } + // + // Which prevents mutations to `i` in the per-iteration environment of the body + // from affecting the value of `i` in the previous per-iteration environment. + // + // Note that the incrementor of a `for` loop is evaluated in a *new* per-iteration + // environment that is carried over to the next iteration of the loop. As a result, + // we must indicate whether this is the first evaluation of the loop body so that + // we only evaluate the incrementor on subsequent evaluations. + currentState.conditionVariable = ts.createUniqueName("inc"); + statements.push(ts.createIf(currentState.conditionVariable, ts.createStatement(ts.visitNode(node.incrementor, visitor, ts.isExpression)), ts.createStatement(ts.createAssignment(currentState.conditionVariable, ts.createTrue())))); + if (shouldConvertConditionOfForStatement(node)) { + statements.push(ts.createIf(ts.createPrefix(52 /* ExclamationToken */, ts.visitNode(node.condition, visitor, ts.isExpression)), ts.visitNode(ts.createBreak(), visitor, ts.isStatement))); + } + } + if (ts.isBlock(statement)) { + ts.addRange(statements, statement.statements); + } + else { + statements.push(statement); + } + copyOutParameters(currentState.loopOutParameters, 1 /* Body */, 1 /* ToOutParameter */, statements); + ts.addStatementsAfterPrologue(statements, lexicalEnvironment); + var loopBody = ts.createBlock(statements, /*multiLine*/ true); + if (ts.isBlock(statement)) + ts.setOriginalNode(loopBody, statement); + var containsYield = (node.statement.transformFlags & 4194304 /* ContainsYield */) !== 0; + var emitFlags = 0; + if (currentState.containsLexicalThis) + emitFlags |= 8 /* CapturesThis */; + if (containsYield && (hierarchyFacts & 4 /* AsyncFunctionBody */) !== 0) + emitFlags |= 262144 /* AsyncFunctionBody */; + // This transforms the following ES2015 syntax (in addition to other variations): + // + // for (let i = 0; i < 2; i++) { + // setImmediate(() => console.log(i)); + // } + // + // Into the following ES5 syntax: + // + // var _loop_1 = function (i) { + // setImmediate(() => console.log(i)); + // }; + // for (var i = 0; i < 2; i++) { + // _loop_1(i); + // } + var functionDeclaration = ts.createVariableStatement( + /*modifiers*/ undefined, ts.setEmitFlags(ts.createVariableDeclarationList([ + ts.createVariableDeclaration(functionName, + /*type*/ undefined, ts.setEmitFlags(ts.createFunctionExpression( + /*modifiers*/ undefined, containsYield ? ts.createToken(40 /* AsteriskToken */) : undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, currentState.loopParameters, + /*type*/ undefined, loopBody), emitFlags)) + ]), 2097152 /* NoHoisting */)); + var part = generateCallToConvertedLoop(functionName, currentState, outerState, containsYield); + return { functionName: functionName, containsYield: containsYield, functionDeclaration: functionDeclaration, part: part }; + } + function copyOutParameter(outParam, copyDirection) { + var source = copyDirection === 0 /* ToOriginal */ ? outParam.outParamName : outParam.originalName; + var target = copyDirection === 0 /* ToOriginal */ ? outParam.originalName : outParam.outParamName; + return ts.createBinary(target, 59 /* EqualsToken */, source); + } + function copyOutParameters(outParams, partFlags, copyDirection, statements) { + for (var _i = 0, outParams_1 = outParams; _i < outParams_1.length; _i++) { + var outParam = outParams_1[_i]; + if (outParam.flags & partFlags) { + statements.push(ts.createExpressionStatement(copyOutParameter(outParam, copyDirection))); + } + } + } + function generateCallToConvertedLoopInitializer(initFunctionExpressionName, containsYield) { + var call = ts.createCall(initFunctionExpressionName, /*typeArguments*/ undefined, []); + var callResult = containsYield + ? ts.createYield(ts.createToken(40 /* AsteriskToken */), ts.setEmitFlags(call, 8388608 /* Iterator */)) + : call; + return ts.createStatement(callResult); + } + function generateCallToConvertedLoop(loopFunctionExpressionName, state, outerState, containsYield) { + var statements = []; + // loop is considered simple if it does not have any return statements or break\continue that transfer control outside of the loop + // simple loops are emitted as just 'loop()'; + // NOTE: if loop uses only 'continue' it still will be emitted as simple loop + var isSimpleLoop = !(state.nonLocalJumps & ~4 /* Continue */) && + !state.labeledNonLocalBreaks && + !state.labeledNonLocalContinues; + var call = ts.createCall(loopFunctionExpressionName, /*typeArguments*/ undefined, ts.map(state.loopParameters, function (p) { return p.name; })); + var callResult = containsYield + ? ts.createYield(ts.createToken(40 /* AsteriskToken */), ts.setEmitFlags(call, 8388608 /* Iterator */)) + : call; + if (isSimpleLoop) { + statements.push(ts.createExpressionStatement(callResult)); + copyOutParameters(state.loopOutParameters, 1 /* Body */, 0 /* ToOriginal */, statements); + } + else { + var loopResultName = ts.createUniqueName("state"); + var stateVariable = ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(loopResultName, /*type*/ undefined, callResult)])); + statements.push(stateVariable); + copyOutParameters(state.loopOutParameters, 1 /* Body */, 0 /* ToOriginal */, statements); + if (state.nonLocalJumps & 8 /* Return */) { + var returnStatement = void 0; + if (outerState) { + outerState.nonLocalJumps |= 8 /* Return */; + returnStatement = ts.createReturn(loopResultName); + } + else { + returnStatement = ts.createReturn(ts.createPropertyAccess(loopResultName, "value")); + } + statements.push(ts.createIf(ts.createBinary(ts.createTypeOf(loopResultName), 35 /* EqualsEqualsEqualsToken */, ts.createLiteral("object")), returnStatement)); + } + if (state.nonLocalJumps & 2 /* Break */) { + statements.push(ts.createIf(ts.createBinary(loopResultName, 35 /* EqualsEqualsEqualsToken */, ts.createLiteral("break")), ts.createBreak())); + } + if (state.labeledNonLocalBreaks || state.labeledNonLocalContinues) { + var caseClauses = []; + processLabeledJumps(state.labeledNonLocalBreaks, /*isBreak*/ true, loopResultName, outerState, caseClauses); + processLabeledJumps(state.labeledNonLocalContinues, /*isBreak*/ false, loopResultName, outerState, caseClauses); + statements.push(ts.createSwitch(loopResultName, ts.createCaseBlock(caseClauses))); + } + } + return statements; + } + function setLabeledJump(state, isBreak, labelText, labelMarker) { + if (isBreak) { + if (!state.labeledNonLocalBreaks) { + state.labeledNonLocalBreaks = ts.createMap(); + } + state.labeledNonLocalBreaks.set(labelText, labelMarker); + } + else { + if (!state.labeledNonLocalContinues) { + state.labeledNonLocalContinues = ts.createMap(); + } + state.labeledNonLocalContinues.set(labelText, labelMarker); + } + } + function processLabeledJumps(table, isBreak, loopResultName, outerLoop, caseClauses) { + if (!table) { + return; + } + table.forEach(function (labelMarker, labelText) { + var statements = []; + // if there are no outer converted loop or outer label in question is located inside outer converted loop + // then emit labeled break\continue + // otherwise propagate pair 'label -> marker' to outer converted loop and emit 'return labelMarker' so outer loop can later decide what to do + if (!outerLoop || (outerLoop.labels && outerLoop.labels.get(labelText))) { + var label = ts.createIdentifier(labelText); + statements.push(isBreak ? ts.createBreak(label) : ts.createContinue(label)); + } + else { + setLabeledJump(outerLoop, isBreak, labelText, labelMarker); + statements.push(ts.createReturn(loopResultName)); + } + caseClauses.push(ts.createCaseClause(ts.createLiteral(labelMarker), statements)); + }); + } + function processLoopVariableDeclaration(container, decl, loopParameters, loopOutParameters, hasCapturedBindingsInForInitializer) { + var name = decl.name; + if (ts.isBindingPattern(name)) { + for (var _i = 0, _a = name.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (!ts.isOmittedExpression(element)) { + processLoopVariableDeclaration(container, element, loopParameters, loopOutParameters, hasCapturedBindingsInForInitializer); + } + } + } + else { + loopParameters.push(ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, name)); + var checkFlags = resolver.getNodeCheckFlags(decl); + if (checkFlags & 4194304 /* NeedsLoopOutParameter */ || hasCapturedBindingsInForInitializer) { + var outParamName = ts.createUniqueName("out_" + ts.idText(name)); + var flags = 0; + if (checkFlags & 4194304 /* NeedsLoopOutParameter */) { + flags |= 1 /* Body */; + } + if (ts.isForStatement(container) && container.initializer && resolver.isBindingCapturedByNode(container.initializer, decl)) { + flags |= 2 /* Initializer */; + } + loopOutParameters.push({ flags: flags, originalName: name, outParamName: outParamName }); + } + } + } + /** + * Adds the members of an object literal to an array of expressions. + * + * @param expressions An array of expressions. + * @param node An ObjectLiteralExpression node. + * @param receiver The receiver for members of the ObjectLiteralExpression. + * @param numInitialNonComputedProperties The number of initial properties without + * computed property names. + */ + function addObjectLiteralMembers(expressions, node, receiver, start) { + var properties = node.properties; + var numProperties = properties.length; + for (var i = start; i < numProperties; i++) { + var property = properties[i]; + switch (property.kind) { + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + var accessors = ts.getAllAccessorDeclarations(node.properties, property); + if (property === accessors.firstAccessor) { + expressions.push(transformAccessorsToExpression(receiver, accessors, node, !!node.multiLine)); + } + break; + case 156 /* MethodDeclaration */: + expressions.push(transformObjectLiteralMethodDeclarationToExpression(property, receiver, node, node.multiLine)); + break; + case 275 /* PropertyAssignment */: + expressions.push(transformPropertyAssignmentToExpression(property, receiver, node.multiLine)); + break; + case 276 /* ShorthandPropertyAssignment */: + expressions.push(transformShorthandPropertyAssignmentToExpression(property, receiver, node.multiLine)); + break; + default: + ts.Debug.failBadSyntaxKind(node); + break; + } + } + } + /** + * Transforms a PropertyAssignment node into an expression. + * + * @param node The ObjectLiteralExpression that contains the PropertyAssignment. + * @param property The PropertyAssignment node. + * @param receiver The receiver for the assignment. + */ + function transformPropertyAssignmentToExpression(property, receiver, startsOnNewLine) { + var expression = ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(property.name, visitor, ts.isPropertyName)), ts.visitNode(property.initializer, visitor, ts.isExpression)); + ts.setTextRange(expression, property); + if (startsOnNewLine) { + ts.startOnNewLine(expression); + } + return expression; + } + /** + * Transforms a ShorthandPropertyAssignment node into an expression. + * + * @param node The ObjectLiteralExpression that contains the ShorthandPropertyAssignment. + * @param property The ShorthandPropertyAssignment node. + * @param receiver The receiver for the assignment. + */ + function transformShorthandPropertyAssignmentToExpression(property, receiver, startsOnNewLine) { + var expression = ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(property.name, visitor, ts.isPropertyName)), ts.getSynthesizedClone(property.name)); + ts.setTextRange(expression, property); + if (startsOnNewLine) { + ts.startOnNewLine(expression); + } + return expression; + } + /** + * Transforms a MethodDeclaration of an ObjectLiteralExpression into an expression. + * + * @param node The ObjectLiteralExpression that contains the MethodDeclaration. + * @param method The MethodDeclaration node. + * @param receiver The receiver for the assignment. + */ + function transformObjectLiteralMethodDeclarationToExpression(method, receiver, container, startsOnNewLine) { + var ancestorFacts = enterSubtree(0 /* None */, 0 /* None */); + var expression = ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(method.name, visitor, ts.isPropertyName)), transformFunctionLikeToExpression(method, /*location*/ method, /*name*/ undefined, container)); + ts.setTextRange(expression, method); + if (startsOnNewLine) { + ts.startOnNewLine(expression); + } + exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, hierarchyFacts & 49152 /* PropagateNewTargetMask */ ? 16384 /* NewTarget */ : 0 /* None */); + return expression; + } + function visitCatchClause(node) { + var ancestorFacts = enterSubtree(4032 /* BlockScopeExcludes */, 0 /* BlockScopeIncludes */); + var updated; + ts.Debug.assert(!!node.variableDeclaration, "Catch clause variable should always be present when downleveling ES2015."); + if (ts.isBindingPattern(node.variableDeclaration.name)) { + var temp = ts.createTempVariable(/*recordTempVariable*/ undefined); + var newVariableDeclaration = ts.createVariableDeclaration(temp); + ts.setTextRange(newVariableDeclaration, node.variableDeclaration); + var vars = ts.flattenDestructuringBinding(node.variableDeclaration, visitor, context, 0 /* All */, temp); + var list = ts.createVariableDeclarationList(vars); + ts.setTextRange(list, node.variableDeclaration); + var destructure = ts.createVariableStatement(/*modifiers*/ undefined, list); + updated = ts.updateCatchClause(node, newVariableDeclaration, addStatementToStartOfBlock(node.block, destructure)); + } + else { + updated = ts.visitEachChild(node, visitor, context); + } + exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */); + return updated; + } + function addStatementToStartOfBlock(block, statement) { + var transformedStatements = ts.visitNodes(block.statements, visitor, ts.isStatement); + return ts.updateBlock(block, [statement].concat(transformedStatements)); + } + /** + * Visits a MethodDeclaration of an ObjectLiteralExpression and transforms it into a + * PropertyAssignment. + * + * @param node A MethodDeclaration node. + */ + function visitMethodDeclaration(node) { + // We should only get here for methods on an object literal with regular identifier names. + // Methods on classes are handled in visitClassDeclaration/visitClassExpression. + // Methods with computed property names are handled in visitObjectLiteralExpression. + ts.Debug.assert(!ts.isComputedPropertyName(node.name)); + var functionExpression = transformFunctionLikeToExpression(node, /*location*/ ts.moveRangePos(node, -1), /*name*/ undefined, /*container*/ undefined); + ts.setEmitFlags(functionExpression, 512 /* NoLeadingComments */ | ts.getEmitFlags(functionExpression)); + return ts.setTextRange(ts.createPropertyAssignment(node.name, functionExpression), + /*location*/ node); + } + /** + * Visits an AccessorDeclaration of an ObjectLiteralExpression. + * + * @param node An AccessorDeclaration node. + */ + function visitAccessorDeclaration(node) { + ts.Debug.assert(!ts.isComputedPropertyName(node.name)); + var savedConvertedLoopState = convertedLoopState; + convertedLoopState = undefined; + var ancestorFacts = enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */); + var updated; + var parameters = ts.visitParameterList(node.parameters, visitor, context); + var body = node.transformFlags & (16384 /* ContainsCapturedLexicalThis */ | 128 /* ContainsES2015 */) + ? transformFunctionBody(node) + : visitFunctionBodyDownLevel(node); + if (node.kind === 158 /* GetAccessor */) { + updated = ts.updateGetAccessor(node, node.decorators, node.modifiers, node.name, parameters, node.type, body); + } + else { + updated = ts.updateSetAccessor(node, node.decorators, node.modifiers, node.name, parameters, body); + } + exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, 0 /* None */); + convertedLoopState = savedConvertedLoopState; + return updated; + } + /** + * Visits a ShorthandPropertyAssignment and transforms it into a PropertyAssignment. + * + * @param node A ShorthandPropertyAssignment node. + */ + function visitShorthandPropertyAssignment(node) { + return ts.setTextRange(ts.createPropertyAssignment(node.name, ts.getSynthesizedClone(node.name)), + /*location*/ node); + } + function visitComputedPropertyName(node) { + var ancestorFacts = enterSubtree(0 /* ComputedPropertyNameExcludes */, 8192 /* ComputedPropertyNameIncludes */); + var updated = ts.visitEachChild(node, visitor, context); + exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, hierarchyFacts & 49152 /* PropagateNewTargetMask */ ? 32768 /* NewTargetInComputedPropertyName */ : 0 /* None */); + return updated; + } + /** + * Visits a YieldExpression node. + * + * @param node A YieldExpression node. + */ + function visitYieldExpression(node) { + // `yield` expressions are transformed using the generators transformer. + return ts.visitEachChild(node, visitor, context); + } + /** + * Visits an ArrayLiteralExpression that contains a spread element. + * + * @param node An ArrayLiteralExpression node. + */ + function visitArrayLiteralExpression(node) { + if (node.transformFlags & 64 /* ES2015 */) { + // We are here because we contain a SpreadElementExpression. + return transformAndSpreadElements(node.elements, /*needsUniqueCopy*/ true, !!node.multiLine, /*hasTrailingComma*/ !!node.elements.hasTrailingComma); + } + return ts.visitEachChild(node, visitor, context); + } + /** + * Visits a CallExpression that contains either a spread element or `super`. + * + * @param node a CallExpression. + */ + function visitCallExpression(node) { + if (ts.getEmitFlags(node) & 33554432 /* TypeScriptClassWrapper */) { + return visitTypeScriptClassWrapper(node); + } + if (node.transformFlags & 64 /* ES2015 */) { + return visitCallExpressionWithPotentialCapturedThisAssignment(node, /*assignToCapturedThis*/ true); + } + return ts.updateCall(node, ts.visitNode(node.expression, callExpressionVisitor, ts.isExpression), + /*typeArguments*/ undefined, ts.visitNodes(node.arguments, visitor, ts.isExpression)); + } + function visitTypeScriptClassWrapper(node) { + // This is a call to a class wrapper function (an IIFE) created by the 'ts' transformer. + // The wrapper has a form similar to: + // + // (function() { + // class C { // 1 + // } + // C.x = 1; // 2 + // return C; + // }()) + // + // When we transform the class, we end up with something like this: + // + // (function () { + // var C = (function () { // 3 + // function C() { + // } + // return C; // 4 + // }()); + // C.x = 1; + // return C; + // }()) + // + // We want to simplify the two nested IIFEs to end up with something like this: + // + // (function () { + // function C() { + // } + // C.x = 1; + // return C; + // }()) + // We skip any outer expressions in a number of places to get to the innermost + // expression, but we will restore them later to preserve comments and source maps. + var body = ts.cast(ts.cast(ts.skipOuterExpressions(node.expression), ts.isArrowFunction).body, ts.isBlock); + // The class statements are the statements generated by visiting the first statement with initializer of the + // body (1), while all other statements are added to remainingStatements (2) + var isVariableStatementWithInitializer = function (stmt) { return ts.isVariableStatement(stmt) && !!ts.first(stmt.declarationList.declarations).initializer; }; + var bodyStatements = ts.visitNodes(body.statements, visitor, ts.isStatement); + var classStatements = ts.filter(bodyStatements, isVariableStatementWithInitializer); + var remainingStatements = ts.filter(bodyStatements, function (stmt) { return !isVariableStatementWithInitializer(stmt); }); + var varStatement = ts.cast(ts.first(classStatements), ts.isVariableStatement); + // We know there is only one variable declaration here as we verified this in an + // earlier call to isTypeScriptClassWrapper + var variable = varStatement.declarationList.declarations[0]; + var initializer = ts.skipOuterExpressions(variable.initializer); + // Under certain conditions, the 'ts' transformer may introduce a class alias, which + // we see as an assignment, for example: + // + // (function () { + // var C_1; + // var C = C_1 = (function () { + // function C() { + // } + // C.x = function () { return C_1; } + // return C; + // }()); + // C = C_1 = __decorate([dec], C); + // return C; + // }()) + // + var aliasAssignment = ts.tryCast(initializer, ts.isAssignmentExpression); + // The underlying call (3) is another IIFE that may contain a '_super' argument. + var call = ts.cast(aliasAssignment ? ts.skipOuterExpressions(aliasAssignment.right) : initializer, ts.isCallExpression); + var func = ts.cast(ts.skipOuterExpressions(call.expression), ts.isFunctionExpression); + var funcStatements = func.body.statements; + var classBodyStart = 0; + var classBodyEnd = -1; + var statements = []; + if (aliasAssignment) { + // If we have a class alias assignment, we need to move it to the down-level constructor + // function we generated for the class. + var extendsCall = ts.tryCast(funcStatements[classBodyStart], ts.isExpressionStatement); + if (extendsCall) { + statements.push(extendsCall); + classBodyStart++; + } + // The next statement is the function declaration. + statements.push(funcStatements[classBodyStart]); + classBodyStart++; + // Add the class alias following the declaration. + statements.push(ts.createExpressionStatement(ts.createAssignment(aliasAssignment.left, ts.cast(variable.name, ts.isIdentifier)))); + } + // Find the trailing 'return' statement (4) + while (!ts.isReturnStatement(ts.elementAt(funcStatements, classBodyEnd))) { + classBodyEnd--; + } + // When we extract the statements of the inner IIFE, we exclude the 'return' statement (4) + // as we already have one that has been introduced by the 'ts' transformer. + ts.addRange(statements, funcStatements, classBodyStart, classBodyEnd); + if (classBodyEnd < -1) { + // If there were any hoisted declarations following the return statement, we should + // append them. + ts.addRange(statements, funcStatements, classBodyEnd + 1); + } + // Add the remaining statements of the outer wrapper. + ts.addRange(statements, remainingStatements); + // The 'es2015' class transform may add an end-of-declaration marker. If so we will add it + // after the remaining statements from the 'ts' transformer. + ts.addRange(statements, classStatements, /*start*/ 1); + // Recreate any outer parentheses or partially-emitted expressions to preserve source map + // and comment locations. + return ts.recreateOuterExpressions(node.expression, ts.recreateOuterExpressions(variable.initializer, ts.recreateOuterExpressions(aliasAssignment && aliasAssignment.right, ts.updateCall(call, ts.recreateOuterExpressions(call.expression, ts.updateFunctionExpression(func, + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, func.parameters, + /*type*/ undefined, ts.updateBlock(func.body, statements))), + /*typeArguments*/ undefined, call.arguments)))); + } + function visitImmediateSuperCallInBody(node) { + return visitCallExpressionWithPotentialCapturedThisAssignment(node, /*assignToCapturedThis*/ false); + } + function visitCallExpressionWithPotentialCapturedThisAssignment(node, assignToCapturedThis) { + // We are here either because SuperKeyword was used somewhere in the expression, or + // because we contain a SpreadElementExpression. + if (node.transformFlags & 131072 /* ContainsRestOrSpread */ || + node.expression.kind === 98 /* SuperKeyword */ || + ts.isSuperProperty(ts.skipOuterExpressions(node.expression))) { + var _a = ts.createCallBinding(node.expression, hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg; + if (node.expression.kind === 98 /* SuperKeyword */) { + ts.setEmitFlags(thisArg, 4 /* NoSubstitution */); + } + var resultingCall = void 0; + if (node.transformFlags & 131072 /* ContainsRestOrSpread */) { + // [source] + // f(...a, b) + // x.m(...a, b) + // super(...a, b) + // super.m(...a, b) // in static + // super.m(...a, b) // in instance + // + // [output] + // f.apply(void 0, a.concat([b])) + // (_a = x).m.apply(_a, a.concat([b])) + // _super.apply(this, a.concat([b])) + // _super.m.apply(this, a.concat([b])) + // _super.prototype.m.apply(this, a.concat([b])) + resultingCall = ts.createFunctionApply(ts.visitNode(target, callExpressionVisitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), transformAndSpreadElements(node.arguments, /*needsUniqueCopy*/ false, /*multiLine*/ false, /*hasTrailingComma*/ false)); + } + else { + // [source] + // super(a) + // super.m(a) // in static + // super.m(a) // in instance + // + // [output] + // _super.call(this, a) + // _super.m.call(this, a) + // _super.prototype.m.call(this, a) + resultingCall = ts.createFunctionCall(ts.visitNode(target, callExpressionVisitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), ts.visitNodes(node.arguments, visitor, ts.isExpression), + /*location*/ node); + } + if (node.expression.kind === 98 /* SuperKeyword */) { + var actualThis = ts.createThis(); + ts.setEmitFlags(actualThis, 4 /* NoSubstitution */); + var initializer = ts.createLogicalOr(resultingCall, actualThis); + resultingCall = assignToCapturedThis + ? ts.createAssignment(ts.createFileLevelUniqueName("_this"), initializer) + : initializer; + } + return ts.setOriginalNode(resultingCall, node); + } + return ts.visitEachChild(node, visitor, context); + } + /** + * Visits a NewExpression that contains a spread element. + * + * @param node A NewExpression node. + */ + function visitNewExpression(node) { + if (node.transformFlags & 131072 /* ContainsRestOrSpread */) { + // We are here because we contain a SpreadElementExpression. + // [source] + // new C(...a) + // + // [output] + // new ((_a = C).bind.apply(_a, [void 0].concat(a)))() + var _a = ts.createCallBinding(ts.createPropertyAccess(node.expression, "bind"), hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg; + return ts.createNew(ts.createFunctionApply(ts.visitNode(target, visitor, ts.isExpression), thisArg, transformAndSpreadElements(ts.createNodeArray([ts.createVoidZero()].concat(node.arguments)), /*needsUniqueCopy*/ false, /*multiLine*/ false, /*hasTrailingComma*/ false)), + /*typeArguments*/ undefined, []); + } + return ts.visitEachChild(node, visitor, context); + } + /** + * Transforms an array of Expression nodes that contains a SpreadExpression. + * + * @param elements The array of Expression nodes. + * @param needsUniqueCopy A value indicating whether to ensure that the result is a fresh array. + * @param multiLine A value indicating whether the result should be emitted on multiple lines. + */ + function transformAndSpreadElements(elements, needsUniqueCopy, multiLine, hasTrailingComma) { + // [source] + // [a, ...b, c] + // + // [output] + // [a].concat(b, [c]) + // Map spans of spread expressions into their expressions and spans of other + // expressions into an array literal. + var numElements = elements.length; + var segments = ts.flatten(ts.spanMap(elements, partitionSpread, function (partition, visitPartition, _start, end) { + return visitPartition(partition, multiLine, hasTrailingComma && end === numElements); + })); + if (compilerOptions.downlevelIteration) { + if (segments.length === 1) { + var firstSegment = segments[0]; + if (ts.isCallExpression(firstSegment) + && ts.isIdentifier(firstSegment.expression) + && (ts.getEmitFlags(firstSegment.expression) & 4096 /* HelperName */) + && firstSegment.expression.escapedText === "___spread") { + return segments[0]; + } + } + return ts.createSpreadHelper(context, segments); + } + else { + if (segments.length === 1) { + var firstElement = elements[0]; + return needsUniqueCopy && ts.isSpreadElement(firstElement) && firstElement.expression.kind !== 187 /* ArrayLiteralExpression */ + ? ts.createArraySlice(segments[0]) + : segments[0]; + } + // Rewrite using the pattern .concat(, , ...) + return ts.createArrayConcat(segments.shift(), segments); + } + } + function partitionSpread(node) { + return ts.isSpreadElement(node) + ? visitSpanOfSpreads + : visitSpanOfNonSpreads; + } + function visitSpanOfSpreads(chunk) { + return ts.map(chunk, visitExpressionOfSpread); + } + function visitSpanOfNonSpreads(chunk, multiLine, hasTrailingComma) { + return ts.createArrayLiteral(ts.visitNodes(ts.createNodeArray(chunk, hasTrailingComma), visitor, ts.isExpression), multiLine); + } + function visitSpreadElement(node) { + return ts.visitNode(node.expression, visitor, ts.isExpression); + } + /** + * Transforms the expression of a SpreadExpression node. + * + * @param node A SpreadExpression node. + */ + function visitExpressionOfSpread(node) { + return ts.visitNode(node.expression, visitor, ts.isExpression); + } + /** + * Visits a template literal. + * + * @param node A template literal. + */ + function visitTemplateLiteral(node) { + return ts.setTextRange(ts.createLiteral(node.text), node); + } + /** + * Visits a string literal with an extended unicode escape. + * + * @param node A string literal. + */ + function visitStringLiteral(node) { + if (node.hasExtendedUnicodeEscape) { + return ts.setTextRange(ts.createLiteral(node.text), node); + } + return node; + } + /** + * Visits a binary or octal (ES6) numeric literal. + * + * @param node A string literal. + */ + function visitNumericLiteral(node) { + if (node.numericLiteralFlags & 384 /* BinaryOrOctalSpecifier */) { + return ts.setTextRange(ts.createNumericLiteral(node.text), node); + } + return node; + } + /** + * Visits a TaggedTemplateExpression node. + * + * @param node A TaggedTemplateExpression node. + */ + function visitTaggedTemplateExpression(node) { + // Visit the tag expression + var tag = ts.visitNode(node.tag, visitor, ts.isExpression); + // Build up the template arguments and the raw and cooked strings for the template. + // We start out with 'undefined' for the first argument and revisit later + // to avoid walking over the template string twice and shifting all our arguments over after the fact. + var templateArguments = [undefined]; + var cookedStrings = []; + var rawStrings = []; + var template = node.template; + if (ts.isNoSubstitutionTemplateLiteral(template)) { + cookedStrings.push(ts.createLiteral(template.text)); + rawStrings.push(getRawLiteral(template)); + } + else { + cookedStrings.push(ts.createLiteral(template.head.text)); + rawStrings.push(getRawLiteral(template.head)); + for (var _i = 0, _a = template.templateSpans; _i < _a.length; _i++) { + var templateSpan = _a[_i]; + cookedStrings.push(ts.createLiteral(templateSpan.literal.text)); + rawStrings.push(getRawLiteral(templateSpan.literal)); + templateArguments.push(ts.visitNode(templateSpan.expression, visitor, ts.isExpression)); + } + } + var helperCall = createTemplateObjectHelper(context, ts.createArrayLiteral(cookedStrings), ts.createArrayLiteral(rawStrings)); + // Create a variable to cache the template object if we're in a module. + // Do not do this in the global scope, as any variable we currently generate could conflict with + // variables from outside of the current compilation. In the future, we can revisit this behavior. + if (ts.isExternalModule(currentSourceFile)) { + var tempVar = ts.createUniqueName("templateObject"); + recordTaggedTemplateString(tempVar); + templateArguments[0] = ts.createLogicalOr(tempVar, ts.createAssignment(tempVar, helperCall)); + } + else { + templateArguments[0] = helperCall; + } + return ts.createCall(tag, /*typeArguments*/ undefined, templateArguments); + } + /** + * Creates an ES5 compatible literal from an ES6 template literal. + * + * @param node The ES6 template literal. + */ + function getRawLiteral(node) { + // Find original source text, since we need to emit the raw strings of the tagged template. + // The raw strings contain the (escaped) strings of what the user wrote. + // Examples: `\n` is converted to "\\n", a template string with a newline to "\n". + var text = ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node); + // text contains the original source, it will also contain quotes ("`"), dolar signs and braces ("${" and "}"), + // thus we need to remove those characters. + // First template piece starts with "`", others with "}" + // Last template piece ends with "`", others with "${" + var isLast = node.kind === 14 /* NoSubstitutionTemplateLiteral */ || node.kind === 17 /* TemplateTail */; + text = text.substring(1, text.length - (isLast ? 1 : 2)); + // Newline normalization: + // ES6 Spec 11.8.6.1 - Static Semantics of TV's and TRV's + // and LineTerminatorSequences are normalized to for both TV and TRV. + text = text.replace(/\r\n?/g, "\n"); + return ts.setTextRange(ts.createLiteral(text), node); + } + /** + * Visits a TemplateExpression node. + * + * @param node A TemplateExpression node. + */ + function visitTemplateExpression(node) { + var expressions = []; + addTemplateHead(expressions, node); + addTemplateSpans(expressions, node); + // createAdd will check if each expression binds less closely than binary '+'. + // If it does, it wraps the expression in parentheses. Otherwise, something like + // `abc${ 1 << 2 }` + // becomes + // "abc" + 1 << 2 + "" + // which is really + // ("abc" + 1) << (2 + "") + // rather than + // "abc" + (1 << 2) + "" + var expression = ts.reduceLeft(expressions, ts.createAdd); + if (ts.nodeIsSynthesized(expression)) { + expression.pos = node.pos; + expression.end = node.end; + } + return expression; + } + /** + * Gets a value indicating whether we need to include the head of a TemplateExpression. + * + * @param node A TemplateExpression node. + */ + function shouldAddTemplateHead(node) { + // If this expression has an empty head literal and the first template span has a non-empty + // literal, then emitting the empty head literal is not necessary. + // `${ foo } and ${ bar }` + // can be emitted as + // foo + " and " + bar + // This is because it is only required that one of the first two operands in the emit + // output must be a string literal, so that the other operand and all following operands + // are forced into strings. + // + // If the first template span has an empty literal, then the head must still be emitted. + // `${ foo }${ bar }` + // must still be emitted as + // "" + foo + bar + // There is always atleast one templateSpan in this code path, since + // NoSubstitutionTemplateLiterals are directly emitted via emitLiteral() + ts.Debug.assert(node.templateSpans.length !== 0); + return node.head.text.length !== 0 || node.templateSpans[0].literal.text.length === 0; + } + /** + * Adds the head of a TemplateExpression to an array of expressions. + * + * @param expressions An array of expressions. + * @param node A TemplateExpression node. + */ + function addTemplateHead(expressions, node) { + if (!shouldAddTemplateHead(node)) { + return; + } + expressions.push(ts.createLiteral(node.head.text)); + } + /** + * Visits and adds the template spans of a TemplateExpression to an array of expressions. + * + * @param expressions An array of expressions. + * @param node A TemplateExpression node. + */ + function addTemplateSpans(expressions, node) { + for (var _i = 0, _a = node.templateSpans; _i < _a.length; _i++) { + var span = _a[_i]; + expressions.push(ts.visitNode(span.expression, visitor, ts.isExpression)); + // Only emit if the literal is non-empty. + // The binary '+' operator is left-associative, so the first string concatenation + // with the head will force the result up to this point to be a string. + // Emitting a '+ ""' has no semantic effect for middles and tails. + if (span.literal.text.length !== 0) { + expressions.push(ts.createLiteral(span.literal.text)); + } + } + } + /** + * Visits the `super` keyword + */ + function visitSuperKeyword(isExpressionOfCall) { + return hierarchyFacts & 8 /* NonStaticClassElement */ + && !isExpressionOfCall + ? ts.createPropertyAccess(ts.createFileLevelUniqueName("_super"), "prototype") + : ts.createFileLevelUniqueName("_super"); + } + function visitMetaProperty(node) { + if (node.keywordToken === 95 /* NewKeyword */ && node.name.escapedText === "target") { + if (hierarchyFacts & 8192 /* ComputedPropertyName */) { + hierarchyFacts |= 32768 /* NewTargetInComputedPropertyName */; + } + else { + hierarchyFacts |= 16384 /* NewTarget */; + } + return ts.createFileLevelUniqueName("_newTarget"); + } + return node; + } + /** + * Called by the printer just before a node is printed. + * + * @param hint A hint as to the intended usage of the node. + * @param node The node to be printed. + * @param emitCallback The callback used to emit the node. + */ + function onEmitNode(hint, node, emitCallback) { + if (enabledSubstitutions & 1 /* CapturedThis */ && ts.isFunctionLike(node)) { + // If we are tracking a captured `this`, keep track of the enclosing function. + var ancestorFacts = enterSubtree(16286 /* FunctionExcludes */, ts.getEmitFlags(node) & 8 /* CapturesThis */ + ? 65 /* FunctionIncludes */ | 16 /* CapturesThis */ + : 65 /* FunctionIncludes */); + previousOnEmitNode(hint, node, emitCallback); + exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */); + return; + } + previousOnEmitNode(hint, node, emitCallback); + } + /** + * Enables a more costly code path for substitutions when we determine a source file + * contains block-scoped bindings (e.g. `let` or `const`). + */ + function enableSubstitutionsForBlockScopedBindings() { + if ((enabledSubstitutions & 2 /* BlockScopedBindings */) === 0) { + enabledSubstitutions |= 2 /* BlockScopedBindings */; + context.enableSubstitution(72 /* Identifier */); + } + } + /** + * Enables a more costly code path for substitutions when we determine a source file + * contains a captured `this`. + */ + function enableSubstitutionsForCapturedThis() { + if ((enabledSubstitutions & 1 /* CapturedThis */) === 0) { + enabledSubstitutions |= 1 /* CapturedThis */; + context.enableSubstitution(100 /* ThisKeyword */); + context.enableEmitNotification(157 /* Constructor */); + context.enableEmitNotification(156 /* MethodDeclaration */); + context.enableEmitNotification(158 /* GetAccessor */); + context.enableEmitNotification(159 /* SetAccessor */); + context.enableEmitNotification(197 /* ArrowFunction */); + context.enableEmitNotification(196 /* FunctionExpression */); + context.enableEmitNotification(239 /* FunctionDeclaration */); + } + } + /** + * Hooks node substitutions. + * + * @param hint The context for the emitter. + * @param node The node to substitute. + */ + function onSubstituteNode(hint, node) { + node = previousOnSubstituteNode(hint, node); + if (hint === 1 /* Expression */) { + return substituteExpression(node); + } + if (ts.isIdentifier(node)) { + return substituteIdentifier(node); + } + return node; + } + /** + * Hooks substitutions for non-expression identifiers. + */ + function substituteIdentifier(node) { + // Only substitute the identifier if we have enabled substitutions for block-scoped + // bindings. + if (enabledSubstitutions & 2 /* BlockScopedBindings */ && !ts.isInternalName(node)) { + var original = ts.getParseTreeNode(node, ts.isIdentifier); + if (original && isNameOfDeclarationWithCollidingName(original)) { + return ts.setTextRange(ts.getGeneratedNameForNode(original), node); + } + } + return node; + } + /** + * Determines whether a name is the name of a declaration with a colliding name. + * NOTE: This function expects to be called with an original source tree node. + * + * @param node An original source tree node. + */ + function isNameOfDeclarationWithCollidingName(node) { + switch (node.parent.kind) { + case 186 /* BindingElement */: + case 240 /* ClassDeclaration */: + case 243 /* EnumDeclaration */: + case 237 /* VariableDeclaration */: + return node.parent.name === node + && resolver.isDeclarationWithCollidingName(node.parent); + } + return false; + } + /** + * Substitutes an expression. + * + * @param node An Expression node. + */ + function substituteExpression(node) { + switch (node.kind) { + case 72 /* Identifier */: + return substituteExpressionIdentifier(node); + case 100 /* ThisKeyword */: + return substituteThisKeyword(node); + } + return node; + } + /** + * Substitutes an expression identifier. + * + * @param node An Identifier node. + */ + function substituteExpressionIdentifier(node) { + if (enabledSubstitutions & 2 /* BlockScopedBindings */ && !ts.isInternalName(node)) { + var declaration = resolver.getReferencedDeclarationWithCollidingName(node); + if (declaration && !(ts.isClassLike(declaration) && isPartOfClassBody(declaration, node))) { + return ts.setTextRange(ts.getGeneratedNameForNode(ts.getNameOfDeclaration(declaration)), node); + } + } + return node; + } + function isPartOfClassBody(declaration, node) { + var currentNode = ts.getParseTreeNode(node); + if (!currentNode || currentNode === declaration || currentNode.end <= declaration.pos || currentNode.pos >= declaration.end) { + // if the node has no correlation to a parse tree node, its definitely not + // part of the body. + // if the node is outside of the document range of the declaration, its + // definitely not part of the body. + return false; + } + var blockScope = ts.getEnclosingBlockScopeContainer(declaration); + while (currentNode) { + if (currentNode === blockScope || currentNode === declaration) { + // if we are in the enclosing block scope of the declaration, we are definitely + // not inside the class body. + return false; + } + if (ts.isClassElement(currentNode) && currentNode.parent === declaration) { + return true; + } + currentNode = currentNode.parent; + } + return false; + } + /** + * Substitutes `this` when contained within an arrow function. + * + * @param node The ThisKeyword node. + */ + function substituteThisKeyword(node) { + if (enabledSubstitutions & 1 /* CapturedThis */ + && hierarchyFacts & 16 /* CapturesThis */) { + return ts.setTextRange(ts.createFileLevelUniqueName("_this"), node); + } + return node; + } + function getClassMemberPrefix(node, member) { + return ts.hasModifier(member, 32 /* Static */) + ? ts.getInternalName(node) + : ts.createPropertyAccess(ts.getInternalName(node), "prototype"); + } + function hasSynthesizedDefaultSuperCall(constructor, hasExtendsClause) { + if (!constructor || !hasExtendsClause) { + return false; + } + if (ts.some(constructor.parameters)) { + return false; + } + var statement = ts.firstOrUndefined(constructor.body.statements); + if (!statement || !ts.nodeIsSynthesized(statement) || statement.kind !== 221 /* ExpressionStatement */) { + return false; + } + var statementExpression = statement.expression; + if (!ts.nodeIsSynthesized(statementExpression) || statementExpression.kind !== 191 /* CallExpression */) { + return false; + } + var callTarget = statementExpression.expression; + if (!ts.nodeIsSynthesized(callTarget) || callTarget.kind !== 98 /* SuperKeyword */) { + return false; + } + var callArgument = ts.singleOrUndefined(statementExpression.arguments); + if (!callArgument || !ts.nodeIsSynthesized(callArgument) || callArgument.kind !== 208 /* SpreadElement */) { + return false; + } + var expression = callArgument.expression; + return ts.isIdentifier(expression) && expression.escapedText === "arguments"; + } + } + ts.transformES2015 = transformES2015; + function createExtendsHelper(context, name) { + context.requestEmitHelper(extendsHelper); + return ts.createCall(ts.getHelperName("__extends"), + /*typeArguments*/ undefined, [ + name, + ts.createFileLevelUniqueName("_super") + ]); + } + function createTemplateObjectHelper(context, cooked, raw) { + context.requestEmitHelper(templateObjectHelper); + return ts.createCall(ts.getHelperName("__makeTemplateObject"), + /*typeArguments*/ undefined, [ + cooked, + raw + ]); + } + var extendsHelper = { + name: "typescript:extends", + scoped: false, + priority: 0, + text: "\n var __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return extendStatics(d, b);\n };\n\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n })();" + }; + var templateObjectHelper = { + name: "typescript:makeTemplateObject", + scoped: false, + priority: 0, + text: "\n var __makeTemplateObject = (this && this.__makeTemplateObject) || function (cooked, raw) {\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\n return cooked;\n };" + }; +})(ts || (ts = {})); +/*@internal*/ +var ts; +(function (ts) { + /** + * Transforms ES5 syntax into ES3 syntax. + * + * @param context Context and state information for the transformation. + */ + function transformES5(context) { + var compilerOptions = context.getCompilerOptions(); + // enable emit notification only if using --jsx preserve or react-native + var previousOnEmitNode; + var noSubstitution; + if (compilerOptions.jsx === 1 /* Preserve */ || compilerOptions.jsx === 3 /* ReactNative */) { + previousOnEmitNode = context.onEmitNode; + context.onEmitNode = onEmitNode; + context.enableEmitNotification(262 /* JsxOpeningElement */); + context.enableEmitNotification(263 /* JsxClosingElement */); + context.enableEmitNotification(261 /* JsxSelfClosingElement */); + noSubstitution = []; + } + var previousOnSubstituteNode = context.onSubstituteNode; + context.onSubstituteNode = onSubstituteNode; + context.enableSubstitution(189 /* PropertyAccessExpression */); + context.enableSubstitution(275 /* PropertyAssignment */); + return ts.chainBundle(transformSourceFile); + /** + * Transforms an ES5 source file to ES3. + * + * @param node A SourceFile + */ + function transformSourceFile(node) { + return node; + } + /** + * Called by the printer just before a node is printed. + * + * @param hint A hint as to the intended usage of the node. + * @param node The node to emit. + * @param emitCallback A callback used to emit the node. + */ + function onEmitNode(hint, node, emitCallback) { + switch (node.kind) { + case 262 /* JsxOpeningElement */: + case 263 /* JsxClosingElement */: + case 261 /* JsxSelfClosingElement */: + var tagName = node.tagName; + noSubstitution[ts.getOriginalNodeId(tagName)] = true; + break; + } + previousOnEmitNode(hint, node, emitCallback); + } + /** + * Hooks node substitutions. + * + * @param hint A hint as to the intended usage of the node. + * @param node The node to substitute. + */ + function onSubstituteNode(hint, node) { + if (node.id && noSubstitution && noSubstitution[node.id]) { + return previousOnSubstituteNode(hint, node); + } + node = previousOnSubstituteNode(hint, node); + if (ts.isPropertyAccessExpression(node)) { + return substitutePropertyAccessExpression(node); + } + else if (ts.isPropertyAssignment(node)) { + return substitutePropertyAssignment(node); + } + return node; + } + /** + * Substitutes a PropertyAccessExpression whose name is a reserved word. + * + * @param node A PropertyAccessExpression + */ + function substitutePropertyAccessExpression(node) { + var literalName = trySubstituteReservedName(node.name); + if (literalName) { + return ts.setTextRange(ts.createElementAccess(node.expression, literalName), node); + } + return node; + } + /** + * Substitutes a PropertyAssignment whose name is a reserved word. + * + * @param node A PropertyAssignment + */ + function substitutePropertyAssignment(node) { + var literalName = ts.isIdentifier(node.name) && trySubstituteReservedName(node.name); + if (literalName) { + return ts.updatePropertyAssignment(node, literalName, node.initializer); + } + return node; + } + /** + * If an identifier name is a reserved word, returns a string literal for the name. + * + * @param name An Identifier + */ + function trySubstituteReservedName(name) { + var token = name.originalKeywordKind || (ts.nodeIsSynthesized(name) ? ts.stringToToken(ts.idText(name)) : undefined); + if (token !== undefined && token >= 73 /* FirstReservedWord */ && token <= 108 /* LastReservedWord */) { + return ts.setTextRange(ts.createLiteral(name), name); + } + return undefined; + } + } + ts.transformES5 = transformES5; +})(ts || (ts = {})); +// Transforms generator functions into a compatible ES5 representation with similar runtime +// semantics. This is accomplished by first transforming the body of each generator +// function into an intermediate representation that is the compiled into a JavaScript +// switch statement. +// +// Many functions in this transformer will contain comments indicating the expected +// intermediate representation. For illustrative purposes, the following intermediate +// language is used to define this intermediate representation: +// +// .nop - Performs no operation. +// .local NAME, ... - Define local variable declarations. +// .mark LABEL - Mark the location of a label. +// .br LABEL - Jump to a label. If jumping out of a protected +// region, all .finally blocks are executed. +// .brtrue LABEL, (x) - Jump to a label IIF the expression `x` is truthy. +// If jumping out of a protected region, all .finally +// blocks are executed. +// .brfalse LABEL, (x) - Jump to a label IIF the expression `x` is falsey. +// If jumping out of a protected region, all .finally +// blocks are executed. +// .yield (x) - Yield the value of the optional expression `x`. +// Resume at the next label. +// .yieldstar (x) - Delegate yield to the value of the optional +// expression `x`. Resume at the next label. +// NOTE: `x` must be an Iterator, not an Iterable. +// .loop CONTINUE, BREAK - Marks the beginning of a loop. Any "continue" or +// "break" abrupt completions jump to the CONTINUE or +// BREAK labels, respectively. +// .endloop - Marks the end of a loop. +// .with (x) - Marks the beginning of a WithStatement block, using +// the supplied expression. +// .endwith - Marks the end of a WithStatement. +// .switch - Marks the beginning of a SwitchStatement. +// .endswitch - Marks the end of a SwitchStatement. +// .labeled NAME - Marks the beginning of a LabeledStatement with the +// supplied name. +// .endlabeled - Marks the end of a LabeledStatement. +// .try TRY, CATCH, FINALLY, END - Marks the beginning of a protected region, and the +// labels for each block. +// .catch (x) - Marks the beginning of a catch block. +// .finally - Marks the beginning of a finally block. +// .endfinally - Marks the end of a finally block. +// .endtry - Marks the end of a protected region. +// .throw (x) - Throws the value of the expression `x`. +// .return (x) - Returns the value of the expression `x`. +// +// In addition, the illustrative intermediate representation introduces some special +// variables: +// +// %sent% - Either returns the next value sent to the generator, +// returns the result of a delegated yield, or throws +// the exception sent to the generator. +// %error% - Returns the value of the current exception in a +// catch block. +// +// This intermediate representation is then compiled into JavaScript syntax. The resulting +// compilation output looks something like the following: +// +// function f() { +// var /*locals*/; +// /*functions*/ +// return __generator(function (state) { +// switch (state.label) { +// /*cases per label*/ +// } +// }); +// } +// +// Each of the above instructions corresponds to JavaScript emit similar to the following: +// +// .local NAME | var NAME; +// -------------------------------|---------------------------------------------- +// .mark LABEL | case LABEL: +// -------------------------------|---------------------------------------------- +// .br LABEL | return [3 /*break*/, LABEL]; +// -------------------------------|---------------------------------------------- +// .brtrue LABEL, (x) | if (x) return [3 /*break*/, LABEL]; +// -------------------------------|---------------------------------------------- +// .brfalse LABEL, (x) | if (!(x)) return [3, /*break*/, LABEL]; +// -------------------------------|---------------------------------------------- +// .yield (x) | return [4 /*yield*/, x]; +// .mark RESUME | case RESUME: +// a = %sent%; | a = state.sent(); +// -------------------------------|---------------------------------------------- +// .yieldstar (x) | return [5 /*yield**/, x]; +// .mark RESUME | case RESUME: +// a = %sent%; | a = state.sent(); +// -------------------------------|---------------------------------------------- +// .with (_a) | with (_a) { +// a(); | a(); +// | } +// | state.label = LABEL; +// .mark LABEL | case LABEL: +// | with (_a) { +// b(); | b(); +// | } +// .endwith | +// -------------------------------|---------------------------------------------- +// | case 0: +// | state.trys = []; +// | ... +// .try TRY, CATCH, FINALLY, END | +// .mark TRY | case TRY: +// | state.trys.push([TRY, CATCH, FINALLY, END]); +// .nop | +// a(); | a(); +// .br END | return [3 /*break*/, END]; +// .catch (e) | +// .mark CATCH | case CATCH: +// | e = state.sent(); +// b(); | b(); +// .br END | return [3 /*break*/, END]; +// .finally | +// .mark FINALLY | case FINALLY: +// c(); | c(); +// .endfinally | return [7 /*endfinally*/]; +// .endtry | +// .mark END | case END: +/*@internal*/ +var ts; +(function (ts) { + var OpCode; + (function (OpCode) { + OpCode[OpCode["Nop"] = 0] = "Nop"; + OpCode[OpCode["Statement"] = 1] = "Statement"; + OpCode[OpCode["Assign"] = 2] = "Assign"; + OpCode[OpCode["Break"] = 3] = "Break"; + OpCode[OpCode["BreakWhenTrue"] = 4] = "BreakWhenTrue"; + OpCode[OpCode["BreakWhenFalse"] = 5] = "BreakWhenFalse"; + OpCode[OpCode["Yield"] = 6] = "Yield"; + OpCode[OpCode["YieldStar"] = 7] = "YieldStar"; + OpCode[OpCode["Return"] = 8] = "Return"; + OpCode[OpCode["Throw"] = 9] = "Throw"; + OpCode[OpCode["Endfinally"] = 10] = "Endfinally"; // Marks the end of a `finally` block + })(OpCode || (OpCode = {})); + // whether a generated code block is opening or closing at the current operation for a FunctionBuilder + var BlockAction; + (function (BlockAction) { + BlockAction[BlockAction["Open"] = 0] = "Open"; + BlockAction[BlockAction["Close"] = 1] = "Close"; + })(BlockAction || (BlockAction = {})); + // the kind for a generated code block in a FunctionBuilder + var CodeBlockKind; + (function (CodeBlockKind) { + CodeBlockKind[CodeBlockKind["Exception"] = 0] = "Exception"; + CodeBlockKind[CodeBlockKind["With"] = 1] = "With"; + CodeBlockKind[CodeBlockKind["Switch"] = 2] = "Switch"; + CodeBlockKind[CodeBlockKind["Loop"] = 3] = "Loop"; + CodeBlockKind[CodeBlockKind["Labeled"] = 4] = "Labeled"; + })(CodeBlockKind || (CodeBlockKind = {})); + // the state for a generated code exception block + var ExceptionBlockState; + (function (ExceptionBlockState) { + ExceptionBlockState[ExceptionBlockState["Try"] = 0] = "Try"; + ExceptionBlockState[ExceptionBlockState["Catch"] = 1] = "Catch"; + ExceptionBlockState[ExceptionBlockState["Finally"] = 2] = "Finally"; + ExceptionBlockState[ExceptionBlockState["Done"] = 3] = "Done"; + })(ExceptionBlockState || (ExceptionBlockState = {})); + // NOTE: changes to this enum should be reflected in the __generator helper. + var Instruction; + (function (Instruction) { + Instruction[Instruction["Next"] = 0] = "Next"; + Instruction[Instruction["Throw"] = 1] = "Throw"; + Instruction[Instruction["Return"] = 2] = "Return"; + Instruction[Instruction["Break"] = 3] = "Break"; + Instruction[Instruction["Yield"] = 4] = "Yield"; + Instruction[Instruction["YieldStar"] = 5] = "YieldStar"; + Instruction[Instruction["Catch"] = 6] = "Catch"; + Instruction[Instruction["Endfinally"] = 7] = "Endfinally"; + })(Instruction || (Instruction = {})); + function getInstructionName(instruction) { + switch (instruction) { + case 2 /* Return */: return "return"; + case 3 /* Break */: return "break"; + case 4 /* Yield */: return "yield"; + case 5 /* YieldStar */: return "yield*"; + case 7 /* Endfinally */: return "endfinally"; + default: return undefined; // TODO: GH#18217 + } + } + function transformGenerators(context) { + var resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistFunctionDeclaration = context.hoistFunctionDeclaration, hoistVariableDeclaration = context.hoistVariableDeclaration; + var compilerOptions = context.getCompilerOptions(); + var languageVersion = ts.getEmitScriptTarget(compilerOptions); + var resolver = context.getEmitResolver(); + var previousOnSubstituteNode = context.onSubstituteNode; + context.onSubstituteNode = onSubstituteNode; + var renamedCatchVariables; + var renamedCatchVariableDeclarations; + var inGeneratorFunctionBody; + var inStatementContainingYield; + // The following three arrays store information about generated code blocks. + // All three arrays are correlated by their index. This approach is used over allocating + // objects to store the same information to avoid GC overhead. + // + var blocks; // Information about the code block + var blockOffsets; // The operation offset at which a code block begins or ends + var blockActions; // Whether the code block is opened or closed + var blockStack; // A stack of currently open code blocks + // Labels are used to mark locations in the code that can be the target of a Break (jump) + // operation. These are translated into case clauses in a switch statement. + // The following two arrays are correlated by their index. This approach is used over + // allocating objects to store the same information to avoid GC overhead. + // + var labelOffsets; // The operation offset at which the label is defined. + var labelExpressions; // The NumericLiteral nodes bound to each label. + var nextLabelId = 1; // The next label id to use. + // Operations store information about generated code for the function body. This + // Includes things like statements, assignments, breaks (jumps), and yields. + // The following three arrays are correlated by their index. This approach is used over + // allocating objects to store the same information to avoid GC overhead. + // + var operations; // The operation to perform. + var operationArguments; // The arguments to the operation. + var operationLocations; // The source map location for the operation. + var state; // The name of the state object used by the generator at runtime. + // The following variables store information used by the `build` function: + // + var blockIndex = 0; // The index of the current block. + var labelNumber = 0; // The current label number. + var labelNumbers; + var lastOperationWasAbrupt; // Indicates whether the last operation was abrupt (break/continue). + var lastOperationWasCompletion; // Indicates whether the last operation was a completion (return/throw). + var clauses; // The case clauses generated for labels. + var statements; // The statements for the current label. + var exceptionBlockStack; // A stack of containing exception blocks. + var currentExceptionBlock; // The current exception block. + var withBlockStack; // A stack containing `with` blocks. + return ts.chainBundle(transformSourceFile); + function transformSourceFile(node) { + if (node.isDeclarationFile || (node.transformFlags & 512 /* ContainsGenerator */) === 0) { + return node; + } + var visited = ts.visitEachChild(node, visitor, context); + ts.addEmitHelpers(visited, context.readEmitHelpers()); + return visited; + } + /** + * Visits a node. + * + * @param node The node to visit. + */ + function visitor(node) { + var transformFlags = node.transformFlags; + if (inStatementContainingYield) { + return visitJavaScriptInStatementContainingYield(node); + } + else if (inGeneratorFunctionBody) { + return visitJavaScriptInGeneratorFunctionBody(node); + } + else if (transformFlags & 256 /* Generator */) { + return visitGenerator(node); + } + else if (transformFlags & 512 /* ContainsGenerator */) { + return ts.visitEachChild(node, visitor, context); + } + else { + return node; + } + } + /** + * Visits a node that is contained within a statement that contains yield. + * + * @param node The node to visit. + */ + function visitJavaScriptInStatementContainingYield(node) { + switch (node.kind) { + case 223 /* DoStatement */: + return visitDoStatement(node); + case 224 /* WhileStatement */: + return visitWhileStatement(node); + case 232 /* SwitchStatement */: + return visitSwitchStatement(node); + case 233 /* LabeledStatement */: + return visitLabeledStatement(node); + default: + return visitJavaScriptInGeneratorFunctionBody(node); + } + } + /** + * Visits a node that is contained within a generator function. + * + * @param node The node to visit. + */ + function visitJavaScriptInGeneratorFunctionBody(node) { + switch (node.kind) { + case 239 /* FunctionDeclaration */: + return visitFunctionDeclaration(node); + case 196 /* FunctionExpression */: + return visitFunctionExpression(node); + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + return visitAccessorDeclaration(node); + case 219 /* VariableStatement */: + return visitVariableStatement(node); + case 225 /* ForStatement */: + return visitForStatement(node); + case 226 /* ForInStatement */: + return visitForInStatement(node); + case 229 /* BreakStatement */: + return visitBreakStatement(node); + case 228 /* ContinueStatement */: + return visitContinueStatement(node); + case 230 /* ReturnStatement */: + return visitReturnStatement(node); + default: + if (node.transformFlags & 4194304 /* ContainsYield */) { + return visitJavaScriptContainingYield(node); + } + else if (node.transformFlags & (512 /* ContainsGenerator */ | 8388608 /* ContainsHoistedDeclarationOrCompletion */)) { + return ts.visitEachChild(node, visitor, context); + } + else { + return node; + } + } + } + /** + * Visits a node that contains a YieldExpression. + * + * @param node The node to visit. + */ + function visitJavaScriptContainingYield(node) { + switch (node.kind) { + case 204 /* BinaryExpression */: + return visitBinaryExpression(node); + case 205 /* ConditionalExpression */: + return visitConditionalExpression(node); + case 207 /* YieldExpression */: + return visitYieldExpression(node); + case 187 /* ArrayLiteralExpression */: + return visitArrayLiteralExpression(node); + case 188 /* ObjectLiteralExpression */: + return visitObjectLiteralExpression(node); + case 190 /* ElementAccessExpression */: + return visitElementAccessExpression(node); + case 191 /* CallExpression */: + return visitCallExpression(node); + case 192 /* NewExpression */: + return visitNewExpression(node); + default: + return ts.visitEachChild(node, visitor, context); + } + } + /** + * Visits a generator function. + * + * @param node The node to visit. + */ + function visitGenerator(node) { + switch (node.kind) { + case 239 /* FunctionDeclaration */: + return visitFunctionDeclaration(node); + case 196 /* FunctionExpression */: + return visitFunctionExpression(node); + default: + return ts.Debug.failBadSyntaxKind(node); + } + } + /** + * Visits a function declaration. + * + * This will be called when one of the following conditions are met: + * - The function declaration is a generator function. + * - The function declaration is contained within the body of a generator function. + * + * @param node The node to visit. + */ + function visitFunctionDeclaration(node) { + // Currently, we only support generators that were originally async functions. + if (node.asteriskToken) { + node = ts.setOriginalNode(ts.setTextRange(ts.createFunctionDeclaration( + /*decorators*/ undefined, node.modifiers, + /*asteriskToken*/ undefined, node.name, + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, transformGeneratorFunctionBody(node.body)), + /*location*/ node), node); + } + else { + var savedInGeneratorFunctionBody = inGeneratorFunctionBody; + var savedInStatementContainingYield = inStatementContainingYield; + inGeneratorFunctionBody = false; + inStatementContainingYield = false; + node = ts.visitEachChild(node, visitor, context); + inGeneratorFunctionBody = savedInGeneratorFunctionBody; + inStatementContainingYield = savedInStatementContainingYield; + } + if (inGeneratorFunctionBody) { + // Function declarations in a generator function body are hoisted + // to the top of the lexical scope and elided from the current statement. + hoistFunctionDeclaration(node); + return undefined; + } + else { + return node; + } + } + /** + * Visits a function expression. + * + * This will be called when one of the following conditions are met: + * - The function expression is a generator function. + * - The function expression is contained within the body of a generator function. + * + * @param node The node to visit. + */ + function visitFunctionExpression(node) { + // Currently, we only support generators that were originally async functions. + if (node.asteriskToken) { + node = ts.setOriginalNode(ts.setTextRange(ts.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, node.name, + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, transformGeneratorFunctionBody(node.body)), + /*location*/ node), node); + } + else { + var savedInGeneratorFunctionBody = inGeneratorFunctionBody; + var savedInStatementContainingYield = inStatementContainingYield; + inGeneratorFunctionBody = false; + inStatementContainingYield = false; + node = ts.visitEachChild(node, visitor, context); + inGeneratorFunctionBody = savedInGeneratorFunctionBody; + inStatementContainingYield = savedInStatementContainingYield; + } + return node; + } + /** + * Visits a get or set accessor declaration. + * + * This will be called when one of the following conditions are met: + * - The accessor is contained within the body of a generator function. + * + * @param node The node to visit. + */ + function visitAccessorDeclaration(node) { + var savedInGeneratorFunctionBody = inGeneratorFunctionBody; + var savedInStatementContainingYield = inStatementContainingYield; + inGeneratorFunctionBody = false; + inStatementContainingYield = false; + node = ts.visitEachChild(node, visitor, context); + inGeneratorFunctionBody = savedInGeneratorFunctionBody; + inStatementContainingYield = savedInStatementContainingYield; + return node; + } + /** + * Transforms the body of a generator function declaration. + * + * @param node The function body to transform. + */ + function transformGeneratorFunctionBody(body) { + // Save existing generator state + var statements = []; + var savedInGeneratorFunctionBody = inGeneratorFunctionBody; + var savedInStatementContainingYield = inStatementContainingYield; + var savedBlocks = blocks; + var savedBlockOffsets = blockOffsets; + var savedBlockActions = blockActions; + var savedBlockStack = blockStack; + var savedLabelOffsets = labelOffsets; + var savedLabelExpressions = labelExpressions; + var savedNextLabelId = nextLabelId; + var savedOperations = operations; + var savedOperationArguments = operationArguments; + var savedOperationLocations = operationLocations; + var savedState = state; + // Initialize generator state + inGeneratorFunctionBody = true; + inStatementContainingYield = false; + blocks = undefined; + blockOffsets = undefined; + blockActions = undefined; + blockStack = undefined; + labelOffsets = undefined; + labelExpressions = undefined; + nextLabelId = 1; + operations = undefined; + operationArguments = undefined; + operationLocations = undefined; + state = ts.createTempVariable(/*recordTempVariable*/ undefined); + // Build the generator + resumeLexicalEnvironment(); + var statementOffset = ts.addPrologue(statements, body.statements, /*ensureUseStrict*/ false, visitor); + transformAndEmitStatements(body.statements, statementOffset); + var buildResult = build(); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + statements.push(ts.createReturn(buildResult)); + // Restore previous generator state + inGeneratorFunctionBody = savedInGeneratorFunctionBody; + inStatementContainingYield = savedInStatementContainingYield; + blocks = savedBlocks; + blockOffsets = savedBlockOffsets; + blockActions = savedBlockActions; + blockStack = savedBlockStack; + labelOffsets = savedLabelOffsets; + labelExpressions = savedLabelExpressions; + nextLabelId = savedNextLabelId; + operations = savedOperations; + operationArguments = savedOperationArguments; + operationLocations = savedOperationLocations; + state = savedState; + return ts.setTextRange(ts.createBlock(statements, body.multiLine), body); + } + /** + * Visits a variable statement. + * + * This will be called when one of the following conditions are met: + * - The variable statement is contained within the body of a generator function. + * + * @param node The node to visit. + */ + function visitVariableStatement(node) { + if (node.transformFlags & 4194304 /* ContainsYield */) { + transformAndEmitVariableDeclarationList(node.declarationList); + return undefined; + } + else { + // Do not hoist custom prologues. + if (ts.getEmitFlags(node) & 1048576 /* CustomPrologue */) { + return node; + } + for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { + var variable = _a[_i]; + hoistVariableDeclaration(variable.name); + } + var variables = ts.getInitializedVariables(node.declarationList); + if (variables.length === 0) { + return undefined; + } + return ts.setSourceMapRange(ts.createExpressionStatement(ts.inlineExpressions(ts.map(variables, transformInitializedVariable))), node); + } + } + /** + * Visits a binary expression. + * + * This will be called when one of the following conditions are met: + * - The node contains a YieldExpression. + * + * @param node The node to visit. + */ + function visitBinaryExpression(node) { + var assoc = ts.getExpressionAssociativity(node); + switch (assoc) { + case 0 /* Left */: + return visitLeftAssociativeBinaryExpression(node); + case 1 /* Right */: + return visitRightAssociativeBinaryExpression(node); + default: + return ts.Debug.assertNever(assoc); + } + } + function isCompoundAssignment(kind) { + return kind >= 60 /* FirstCompoundAssignment */ + && kind <= 71 /* LastCompoundAssignment */; + } + function getOperatorForCompoundAssignment(kind) { + switch (kind) { + case 60 /* PlusEqualsToken */: return 38 /* PlusToken */; + case 61 /* MinusEqualsToken */: return 39 /* MinusToken */; + case 62 /* AsteriskEqualsToken */: return 40 /* AsteriskToken */; + case 63 /* AsteriskAsteriskEqualsToken */: return 41 /* AsteriskAsteriskToken */; + case 64 /* SlashEqualsToken */: return 42 /* SlashToken */; + case 65 /* PercentEqualsToken */: return 43 /* PercentToken */; + case 66 /* LessThanLessThanEqualsToken */: return 46 /* LessThanLessThanToken */; + case 67 /* GreaterThanGreaterThanEqualsToken */: return 47 /* GreaterThanGreaterThanToken */; + case 68 /* GreaterThanGreaterThanGreaterThanEqualsToken */: return 48 /* GreaterThanGreaterThanGreaterThanToken */; + case 69 /* AmpersandEqualsToken */: return 49 /* AmpersandToken */; + case 70 /* BarEqualsToken */: return 50 /* BarToken */; + case 71 /* CaretEqualsToken */: return 51 /* CaretToken */; + } + } + /** + * Visits a right-associative binary expression containing `yield`. + * + * @param node The node to visit. + */ + function visitRightAssociativeBinaryExpression(node) { + var left = node.left, right = node.right; + if (containsYield(right)) { + var target = void 0; + switch (left.kind) { + case 189 /* PropertyAccessExpression */: + // [source] + // a.b = yield; + // + // [intermediate] + // .local _a + // _a = a; + // .yield resumeLabel + // .mark resumeLabel + // _a.b = %sent%; + target = ts.updatePropertyAccess(left, cacheExpression(ts.visitNode(left.expression, visitor, ts.isLeftHandSideExpression)), left.name); + break; + case 190 /* ElementAccessExpression */: + // [source] + // a[b] = yield; + // + // [intermediate] + // .local _a, _b + // _a = a; + // _b = b; + // .yield resumeLabel + // .mark resumeLabel + // _a[_b] = %sent%; + target = ts.updateElementAccess(left, cacheExpression(ts.visitNode(left.expression, visitor, ts.isLeftHandSideExpression)), cacheExpression(ts.visitNode(left.argumentExpression, visitor, ts.isExpression))); + break; + default: + target = ts.visitNode(left, visitor, ts.isExpression); + break; + } + var operator = node.operatorToken.kind; + if (isCompoundAssignment(operator)) { + return ts.setTextRange(ts.createAssignment(target, ts.setTextRange(ts.createBinary(cacheExpression(target), getOperatorForCompoundAssignment(operator), ts.visitNode(right, visitor, ts.isExpression)), node)), node); + } + else { + return ts.updateBinary(node, target, ts.visitNode(right, visitor, ts.isExpression)); + } + } + return ts.visitEachChild(node, visitor, context); + } + function visitLeftAssociativeBinaryExpression(node) { + if (containsYield(node.right)) { + if (ts.isLogicalOperator(node.operatorToken.kind)) { + return visitLogicalBinaryExpression(node); + } + else if (node.operatorToken.kind === 27 /* CommaToken */) { + return visitCommaExpression(node); + } + // [source] + // a() + (yield) + c() + // + // [intermediate] + // .local _a + // _a = a(); + // .yield resumeLabel + // _a + %sent% + c() + var clone_5 = ts.getMutableClone(node); + clone_5.left = cacheExpression(ts.visitNode(node.left, visitor, ts.isExpression)); + clone_5.right = ts.visitNode(node.right, visitor, ts.isExpression); + return clone_5; + } + return ts.visitEachChild(node, visitor, context); + } + /** + * Visits a logical binary expression containing `yield`. + * + * @param node A node to visit. + */ + function visitLogicalBinaryExpression(node) { + // Logical binary expressions (`&&` and `||`) are shortcutting expressions and need + // to be transformed as such: + // + // [source] + // x = a() && yield; + // + // [intermediate] + // .local _a + // _a = a(); + // .brfalse resultLabel, (_a) + // .yield resumeLabel + // .mark resumeLabel + // _a = %sent%; + // .mark resultLabel + // x = _a; + // + // [source] + // x = a() || yield; + // + // [intermediate] + // .local _a + // _a = a(); + // .brtrue resultLabel, (_a) + // .yield resumeLabel + // .mark resumeLabel + // _a = %sent%; + // .mark resultLabel + // x = _a; + var resultLabel = defineLabel(); + var resultLocal = declareLocal(); + emitAssignment(resultLocal, ts.visitNode(node.left, visitor, ts.isExpression), /*location*/ node.left); + if (node.operatorToken.kind === 54 /* AmpersandAmpersandToken */) { + // Logical `&&` shortcuts when the left-hand operand is falsey. + emitBreakWhenFalse(resultLabel, resultLocal, /*location*/ node.left); + } + else { + // Logical `||` shortcuts when the left-hand operand is truthy. + emitBreakWhenTrue(resultLabel, resultLocal, /*location*/ node.left); + } + emitAssignment(resultLocal, ts.visitNode(node.right, visitor, ts.isExpression), /*location*/ node.right); + markLabel(resultLabel); + return resultLocal; + } + /** + * Visits a comma expression containing `yield`. + * + * @param node The node to visit. + */ + function visitCommaExpression(node) { + // [source] + // x = a(), yield, b(); + // + // [intermediate] + // a(); + // .yield resumeLabel + // .mark resumeLabel + // x = %sent%, b(); + var pendingExpressions = []; + visit(node.left); + visit(node.right); + return ts.inlineExpressions(pendingExpressions); + function visit(node) { + if (ts.isBinaryExpression(node) && node.operatorToken.kind === 27 /* CommaToken */) { + visit(node.left); + visit(node.right); + } + else { + if (containsYield(node) && pendingExpressions.length > 0) { + emitWorker(1 /* Statement */, [ts.createExpressionStatement(ts.inlineExpressions(pendingExpressions))]); + pendingExpressions = []; + } + pendingExpressions.push(ts.visitNode(node, visitor, ts.isExpression)); + } + } + } + /** + * Visits a conditional expression containing `yield`. + * + * @param node The node to visit. + */ + function visitConditionalExpression(node) { + // [source] + // x = a() ? yield : b(); + // + // [intermediate] + // .local _a + // .brfalse whenFalseLabel, (a()) + // .yield resumeLabel + // .mark resumeLabel + // _a = %sent%; + // .br resultLabel + // .mark whenFalseLabel + // _a = b(); + // .mark resultLabel + // x = _a; + // We only need to perform a specific transformation if a `yield` expression exists + // in either the `whenTrue` or `whenFalse` branches. + // A `yield` in the condition will be handled by the normal visitor. + if (containsYield(node.whenTrue) || containsYield(node.whenFalse)) { + var whenFalseLabel = defineLabel(); + var resultLabel = defineLabel(); + var resultLocal = declareLocal(); + emitBreakWhenFalse(whenFalseLabel, ts.visitNode(node.condition, visitor, ts.isExpression), /*location*/ node.condition); + emitAssignment(resultLocal, ts.visitNode(node.whenTrue, visitor, ts.isExpression), /*location*/ node.whenTrue); + emitBreak(resultLabel); + markLabel(whenFalseLabel); + emitAssignment(resultLocal, ts.visitNode(node.whenFalse, visitor, ts.isExpression), /*location*/ node.whenFalse); + markLabel(resultLabel); + return resultLocal; + } + return ts.visitEachChild(node, visitor, context); + } + /** + * Visits a `yield` expression. + * + * @param node The node to visit. + */ + function visitYieldExpression(node) { + // [source] + // x = yield a(); + // + // [intermediate] + // .yield resumeLabel, (a()) + // .mark resumeLabel + // x = %sent%; + var resumeLabel = defineLabel(); + var expression = ts.visitNode(node.expression, visitor, ts.isExpression); + if (node.asteriskToken) { + var iterator = (ts.getEmitFlags(node.expression) & 8388608 /* Iterator */) === 0 + ? ts.createValuesHelper(context, expression, /*location*/ node) + : expression; + emitYieldStar(iterator, /*location*/ node); + } + else { + emitYield(expression, /*location*/ node); + } + markLabel(resumeLabel); + return createGeneratorResume(/*location*/ node); + } + /** + * Visits an ArrayLiteralExpression that contains a YieldExpression. + * + * @param node The node to visit. + */ + function visitArrayLiteralExpression(node) { + return visitElements(node.elements, /*leadingElement*/ undefined, /*location*/ undefined, node.multiLine); + } + /** + * Visits an array of expressions containing one or more YieldExpression nodes + * and returns an expression for the resulting value. + * + * @param elements The elements to visit. + * @param multiLine Whether array literals created should be emitted on multiple lines. + */ + function visitElements(elements, leadingElement, location, multiLine) { + // [source] + // ar = [1, yield, 2]; + // + // [intermediate] + // .local _a + // _a = [1]; + // .yield resumeLabel + // .mark resumeLabel + // ar = _a.concat([%sent%, 2]); + var numInitialElements = countInitialNodesWithoutYield(elements); + var temp; + if (numInitialElements > 0) { + temp = declareLocal(); + var initialElements = ts.visitNodes(elements, visitor, ts.isExpression, 0, numInitialElements); + emitAssignment(temp, ts.createArrayLiteral(leadingElement + ? [leadingElement].concat(initialElements) : initialElements)); + leadingElement = undefined; + } + var expressions = ts.reduceLeft(elements, reduceElement, [], numInitialElements); + return temp + ? ts.createArrayConcat(temp, [ts.createArrayLiteral(expressions, multiLine)]) + : ts.setTextRange(ts.createArrayLiteral(leadingElement ? [leadingElement].concat(expressions) : expressions, multiLine), location); + function reduceElement(expressions, element) { + if (containsYield(element) && expressions.length > 0) { + var hasAssignedTemp = temp !== undefined; + if (!temp) { + temp = declareLocal(); + } + emitAssignment(temp, hasAssignedTemp + ? ts.createArrayConcat(temp, [ts.createArrayLiteral(expressions, multiLine)]) + : ts.createArrayLiteral(leadingElement ? [leadingElement].concat(expressions) : expressions, multiLine)); + leadingElement = undefined; + expressions = []; + } + expressions.push(ts.visitNode(element, visitor, ts.isExpression)); + return expressions; + } + } + function visitObjectLiteralExpression(node) { + // [source] + // o = { + // a: 1, + // b: yield, + // c: 2 + // }; + // + // [intermediate] + // .local _a + // _a = { + // a: 1 + // }; + // .yield resumeLabel + // .mark resumeLabel + // o = (_a.b = %sent%, + // _a.c = 2, + // _a); + var properties = node.properties; + var multiLine = node.multiLine; + var numInitialProperties = countInitialNodesWithoutYield(properties); + var temp = declareLocal(); + emitAssignment(temp, ts.createObjectLiteral(ts.visitNodes(properties, visitor, ts.isObjectLiteralElementLike, 0, numInitialProperties), multiLine)); + var expressions = ts.reduceLeft(properties, reduceProperty, [], numInitialProperties); + expressions.push(multiLine ? ts.startOnNewLine(ts.getMutableClone(temp)) : temp); + return ts.inlineExpressions(expressions); + function reduceProperty(expressions, property) { + if (containsYield(property) && expressions.length > 0) { + emitStatement(ts.createExpressionStatement(ts.inlineExpressions(expressions))); + expressions = []; + } + var expression = ts.createExpressionForObjectLiteralElementLike(node, property, temp); + var visited = ts.visitNode(expression, visitor, ts.isExpression); + if (visited) { + if (multiLine) { + ts.startOnNewLine(visited); + } + expressions.push(visited); + } + return expressions; + } + } + /** + * Visits an ElementAccessExpression that contains a YieldExpression. + * + * @param node The node to visit. + */ + function visitElementAccessExpression(node) { + if (containsYield(node.argumentExpression)) { + // [source] + // a = x[yield]; + // + // [intermediate] + // .local _a + // _a = x; + // .yield resumeLabel + // .mark resumeLabel + // a = _a[%sent%] + var clone_6 = ts.getMutableClone(node); + clone_6.expression = cacheExpression(ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression)); + clone_6.argumentExpression = ts.visitNode(node.argumentExpression, visitor, ts.isExpression); + return clone_6; + } + return ts.visitEachChild(node, visitor, context); + } + function visitCallExpression(node) { + if (!ts.isImportCall(node) && ts.forEach(node.arguments, containsYield)) { + // [source] + // a.b(1, yield, 2); + // + // [intermediate] + // .local _a, _b, _c + // _b = (_a = a).b; + // _c = [1]; + // .yield resumeLabel + // .mark resumeLabel + // _b.apply(_a, _c.concat([%sent%, 2])); + var _a = ts.createCallBinding(node.expression, hoistVariableDeclaration, languageVersion, /*cacheIdentifiers*/ true), target = _a.target, thisArg = _a.thisArg; + return ts.setOriginalNode(ts.createFunctionApply(cacheExpression(ts.visitNode(target, visitor, ts.isLeftHandSideExpression)), thisArg, visitElements(node.arguments), + /*location*/ node), node); + } + return ts.visitEachChild(node, visitor, context); + } + function visitNewExpression(node) { + if (ts.forEach(node.arguments, containsYield)) { + // [source] + // new a.b(1, yield, 2); + // + // [intermediate] + // .local _a, _b, _c + // _b = (_a = a.b).bind; + // _c = [1]; + // .yield resumeLabel + // .mark resumeLabel + // new (_b.apply(_a, _c.concat([%sent%, 2]))); + var _a = ts.createCallBinding(ts.createPropertyAccess(node.expression, "bind"), hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg; + return ts.setOriginalNode(ts.setTextRange(ts.createNew(ts.createFunctionApply(cacheExpression(ts.visitNode(target, visitor, ts.isExpression)), thisArg, visitElements(node.arguments, + /*leadingElement*/ ts.createVoidZero())), + /*typeArguments*/ undefined, []), node), node); + } + return ts.visitEachChild(node, visitor, context); + } + function transformAndEmitStatements(statements, start) { + if (start === void 0) { start = 0; } + var numStatements = statements.length; + for (var i = start; i < numStatements; i++) { + transformAndEmitStatement(statements[i]); + } + } + function transformAndEmitEmbeddedStatement(node) { + if (ts.isBlock(node)) { + transformAndEmitStatements(node.statements); + } + else { + transformAndEmitStatement(node); + } + } + function transformAndEmitStatement(node) { + var savedInStatementContainingYield = inStatementContainingYield; + if (!inStatementContainingYield) { + inStatementContainingYield = containsYield(node); + } + transformAndEmitStatementWorker(node); + inStatementContainingYield = savedInStatementContainingYield; + } + function transformAndEmitStatementWorker(node) { + switch (node.kind) { + case 218 /* Block */: + return transformAndEmitBlock(node); + case 221 /* ExpressionStatement */: + return transformAndEmitExpressionStatement(node); + case 222 /* IfStatement */: + return transformAndEmitIfStatement(node); + case 223 /* DoStatement */: + return transformAndEmitDoStatement(node); + case 224 /* WhileStatement */: + return transformAndEmitWhileStatement(node); + case 225 /* ForStatement */: + return transformAndEmitForStatement(node); + case 226 /* ForInStatement */: + return transformAndEmitForInStatement(node); + case 228 /* ContinueStatement */: + return transformAndEmitContinueStatement(node); + case 229 /* BreakStatement */: + return transformAndEmitBreakStatement(node); + case 230 /* ReturnStatement */: + return transformAndEmitReturnStatement(node); + case 231 /* WithStatement */: + return transformAndEmitWithStatement(node); + case 232 /* SwitchStatement */: + return transformAndEmitSwitchStatement(node); + case 233 /* LabeledStatement */: + return transformAndEmitLabeledStatement(node); + case 234 /* ThrowStatement */: + return transformAndEmitThrowStatement(node); + case 235 /* TryStatement */: + return transformAndEmitTryStatement(node); + default: + return emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + } + function transformAndEmitBlock(node) { + if (containsYield(node)) { + transformAndEmitStatements(node.statements); + } + else { + emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + } + function transformAndEmitExpressionStatement(node) { + emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + function transformAndEmitVariableDeclarationList(node) { + for (var _i = 0, _a = node.declarations; _i < _a.length; _i++) { + var variable = _a[_i]; + var name = ts.getSynthesizedClone(variable.name); + ts.setCommentRange(name, variable.name); + hoistVariableDeclaration(name); + } + var variables = ts.getInitializedVariables(node); + var numVariables = variables.length; + var variablesWritten = 0; + var pendingExpressions = []; + while (variablesWritten < numVariables) { + for (var i = variablesWritten; i < numVariables; i++) { + var variable = variables[i]; + if (containsYield(variable.initializer) && pendingExpressions.length > 0) { + break; + } + pendingExpressions.push(transformInitializedVariable(variable)); + } + if (pendingExpressions.length) { + emitStatement(ts.createExpressionStatement(ts.inlineExpressions(pendingExpressions))); + variablesWritten += pendingExpressions.length; + pendingExpressions = []; + } + } + return undefined; + } + function transformInitializedVariable(node) { + return ts.setSourceMapRange(ts.createAssignment(ts.setSourceMapRange(ts.getSynthesizedClone(node.name), node.name), ts.visitNode(node.initializer, visitor, ts.isExpression)), node); + } + function transformAndEmitIfStatement(node) { + if (containsYield(node)) { + // [source] + // if (x) + // /*thenStatement*/ + // else + // /*elseStatement*/ + // + // [intermediate] + // .brfalse elseLabel, (x) + // /*thenStatement*/ + // .br endLabel + // .mark elseLabel + // /*elseStatement*/ + // .mark endLabel + if (containsYield(node.thenStatement) || containsYield(node.elseStatement)) { + var endLabel = defineLabel(); + var elseLabel = node.elseStatement ? defineLabel() : undefined; + emitBreakWhenFalse(node.elseStatement ? elseLabel : endLabel, ts.visitNode(node.expression, visitor, ts.isExpression), /*location*/ node.expression); + transformAndEmitEmbeddedStatement(node.thenStatement); + if (node.elseStatement) { + emitBreak(endLabel); + markLabel(elseLabel); + transformAndEmitEmbeddedStatement(node.elseStatement); + } + markLabel(endLabel); + } + else { + emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + } + else { + emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + } + function transformAndEmitDoStatement(node) { + if (containsYield(node)) { + // [source] + // do { + // /*body*/ + // } + // while (i < 10); + // + // [intermediate] + // .loop conditionLabel, endLabel + // .mark loopLabel + // /*body*/ + // .mark conditionLabel + // .brtrue loopLabel, (i < 10) + // .endloop + // .mark endLabel + var conditionLabel = defineLabel(); + var loopLabel = defineLabel(); + beginLoopBlock(/*continueLabel*/ conditionLabel); + markLabel(loopLabel); + transformAndEmitEmbeddedStatement(node.statement); + markLabel(conditionLabel); + emitBreakWhenTrue(loopLabel, ts.visitNode(node.expression, visitor, ts.isExpression)); + endLoopBlock(); + } + else { + emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + } + function visitDoStatement(node) { + if (inStatementContainingYield) { + beginScriptLoopBlock(); + node = ts.visitEachChild(node, visitor, context); + endLoopBlock(); + return node; + } + else { + return ts.visitEachChild(node, visitor, context); + } + } + function transformAndEmitWhileStatement(node) { + if (containsYield(node)) { + // [source] + // while (i < 10) { + // /*body*/ + // } + // + // [intermediate] + // .loop loopLabel, endLabel + // .mark loopLabel + // .brfalse endLabel, (i < 10) + // /*body*/ + // .br loopLabel + // .endloop + // .mark endLabel + var loopLabel = defineLabel(); + var endLabel = beginLoopBlock(loopLabel); + markLabel(loopLabel); + emitBreakWhenFalse(endLabel, ts.visitNode(node.expression, visitor, ts.isExpression)); + transformAndEmitEmbeddedStatement(node.statement); + emitBreak(loopLabel); + endLoopBlock(); + } + else { + emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + } + function visitWhileStatement(node) { + if (inStatementContainingYield) { + beginScriptLoopBlock(); + node = ts.visitEachChild(node, visitor, context); + endLoopBlock(); + return node; + } + else { + return ts.visitEachChild(node, visitor, context); + } + } + function transformAndEmitForStatement(node) { + if (containsYield(node)) { + // [source] + // for (var i = 0; i < 10; i++) { + // /*body*/ + // } + // + // [intermediate] + // .local i + // i = 0; + // .loop incrementLabel, endLoopLabel + // .mark conditionLabel + // .brfalse endLoopLabel, (i < 10) + // /*body*/ + // .mark incrementLabel + // i++; + // .br conditionLabel + // .endloop + // .mark endLoopLabel + var conditionLabel = defineLabel(); + var incrementLabel = defineLabel(); + var endLabel = beginLoopBlock(incrementLabel); + if (node.initializer) { + var initializer = node.initializer; + if (ts.isVariableDeclarationList(initializer)) { + transformAndEmitVariableDeclarationList(initializer); + } + else { + emitStatement(ts.setTextRange(ts.createExpressionStatement(ts.visitNode(initializer, visitor, ts.isExpression)), initializer)); + } + } + markLabel(conditionLabel); + if (node.condition) { + emitBreakWhenFalse(endLabel, ts.visitNode(node.condition, visitor, ts.isExpression)); + } + transformAndEmitEmbeddedStatement(node.statement); + markLabel(incrementLabel); + if (node.incrementor) { + emitStatement(ts.setTextRange(ts.createExpressionStatement(ts.visitNode(node.incrementor, visitor, ts.isExpression)), node.incrementor)); + } + emitBreak(conditionLabel); + endLoopBlock(); + } + else { + emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + } + function visitForStatement(node) { + if (inStatementContainingYield) { + beginScriptLoopBlock(); + } + var initializer = node.initializer; + if (initializer && ts.isVariableDeclarationList(initializer)) { + for (var _i = 0, _a = initializer.declarations; _i < _a.length; _i++) { + var variable = _a[_i]; + hoistVariableDeclaration(variable.name); + } + var variables = ts.getInitializedVariables(initializer); + node = ts.updateFor(node, variables.length > 0 + ? ts.inlineExpressions(ts.map(variables, transformInitializedVariable)) + : undefined, ts.visitNode(node.condition, visitor, ts.isExpression), ts.visitNode(node.incrementor, visitor, ts.isExpression), ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); + } + else { + node = ts.visitEachChild(node, visitor, context); + } + if (inStatementContainingYield) { + endLoopBlock(); + } + return node; + } + function transformAndEmitForInStatement(node) { + // TODO(rbuckton): Source map locations + if (containsYield(node)) { + // [source] + // for (var p in o) { + // /*body*/ + // } + // + // [intermediate] + // .local _a, _b, _i + // _a = []; + // for (_b in o) _a.push(_b); + // _i = 0; + // .loop incrementLabel, endLoopLabel + // .mark conditionLabel + // .brfalse endLoopLabel, (_i < _a.length) + // p = _a[_i]; + // /*body*/ + // .mark incrementLabel + // _b++; + // .br conditionLabel + // .endloop + // .mark endLoopLabel + var keysArray = declareLocal(); // _a + var key = declareLocal(); // _b + var keysIndex = ts.createLoopVariable(); // _i + var initializer = node.initializer; + hoistVariableDeclaration(keysIndex); + emitAssignment(keysArray, ts.createArrayLiteral()); + emitStatement(ts.createForIn(key, ts.visitNode(node.expression, visitor, ts.isExpression), ts.createExpressionStatement(ts.createCall(ts.createPropertyAccess(keysArray, "push"), + /*typeArguments*/ undefined, [key])))); + emitAssignment(keysIndex, ts.createLiteral(0)); + var conditionLabel = defineLabel(); + var incrementLabel = defineLabel(); + var endLabel = beginLoopBlock(incrementLabel); + markLabel(conditionLabel); + emitBreakWhenFalse(endLabel, ts.createLessThan(keysIndex, ts.createPropertyAccess(keysArray, "length"))); + var variable = void 0; + if (ts.isVariableDeclarationList(initializer)) { + for (var _i = 0, _a = initializer.declarations; _i < _a.length; _i++) { + var variable_1 = _a[_i]; + hoistVariableDeclaration(variable_1.name); + } + variable = ts.getSynthesizedClone(initializer.declarations[0].name); + } + else { + variable = ts.visitNode(initializer, visitor, ts.isExpression); + ts.Debug.assert(ts.isLeftHandSideExpression(variable)); + } + emitAssignment(variable, ts.createElementAccess(keysArray, keysIndex)); + transformAndEmitEmbeddedStatement(node.statement); + markLabel(incrementLabel); + emitStatement(ts.createExpressionStatement(ts.createPostfixIncrement(keysIndex))); + emitBreak(conditionLabel); + endLoopBlock(); + } + else { + emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + } + function visitForInStatement(node) { + // [source] + // for (var x in a) { + // /*body*/ + // } + // + // [intermediate] + // .local x + // .loop + // for (x in a) { + // /*body*/ + // } + // .endloop + if (inStatementContainingYield) { + beginScriptLoopBlock(); + } + var initializer = node.initializer; + if (ts.isVariableDeclarationList(initializer)) { + for (var _i = 0, _a = initializer.declarations; _i < _a.length; _i++) { + var variable = _a[_i]; + hoistVariableDeclaration(variable.name); + } + node = ts.updateForIn(node, initializer.declarations[0].name, ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); + } + else { + node = ts.visitEachChild(node, visitor, context); + } + if (inStatementContainingYield) { + endLoopBlock(); + } + return node; + } + function transformAndEmitContinueStatement(node) { + var label = findContinueTarget(node.label ? ts.idText(node.label) : undefined); + if (label > 0) { + emitBreak(label, /*location*/ node); + } + else { + // invalid continue without a containing loop. Leave the node as is, per #17875. + emitStatement(node); + } + } + function visitContinueStatement(node) { + if (inStatementContainingYield) { + var label = findContinueTarget(node.label && ts.idText(node.label)); + if (label > 0) { + return createInlineBreak(label, /*location*/ node); + } + } + return ts.visitEachChild(node, visitor, context); + } + function transformAndEmitBreakStatement(node) { + var label = findBreakTarget(node.label ? ts.idText(node.label) : undefined); + if (label > 0) { + emitBreak(label, /*location*/ node); + } + else { + // invalid break without a containing loop, switch, or labeled statement. Leave the node as is, per #17875. + emitStatement(node); + } + } + function visitBreakStatement(node) { + if (inStatementContainingYield) { + var label = findBreakTarget(node.label && ts.idText(node.label)); + if (label > 0) { + return createInlineBreak(label, /*location*/ node); + } + } + return ts.visitEachChild(node, visitor, context); + } + function transformAndEmitReturnStatement(node) { + emitReturn(ts.visitNode(node.expression, visitor, ts.isExpression), + /*location*/ node); + } + function visitReturnStatement(node) { + return createInlineReturn(ts.visitNode(node.expression, visitor, ts.isExpression), + /*location*/ node); + } + function transformAndEmitWithStatement(node) { + if (containsYield(node)) { + // [source] + // with (x) { + // /*body*/ + // } + // + // [intermediate] + // .with (x) + // /*body*/ + // .endwith + beginWithBlock(cacheExpression(ts.visitNode(node.expression, visitor, ts.isExpression))); + transformAndEmitEmbeddedStatement(node.statement); + endWithBlock(); + } + else { + emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + } + function transformAndEmitSwitchStatement(node) { + if (containsYield(node.caseBlock)) { + // [source] + // switch (x) { + // case a: + // /*caseStatements*/ + // case b: + // /*caseStatements*/ + // default: + // /*defaultStatements*/ + // } + // + // [intermediate] + // .local _a + // .switch endLabel + // _a = x; + // switch (_a) { + // case a: + // .br clauseLabels[0] + // } + // switch (_a) { + // case b: + // .br clauseLabels[1] + // } + // .br clauseLabels[2] + // .mark clauseLabels[0] + // /*caseStatements*/ + // .mark clauseLabels[1] + // /*caseStatements*/ + // .mark clauseLabels[2] + // /*caseStatements*/ + // .endswitch + // .mark endLabel + var caseBlock = node.caseBlock; + var numClauses = caseBlock.clauses.length; + var endLabel = beginSwitchBlock(); + var expression = cacheExpression(ts.visitNode(node.expression, visitor, ts.isExpression)); + // Create labels for each clause and find the index of the first default clause. + var clauseLabels = []; + var defaultClauseIndex = -1; + for (var i = 0; i < numClauses; i++) { + var clause = caseBlock.clauses[i]; + clauseLabels.push(defineLabel()); + if (clause.kind === 272 /* DefaultClause */ && defaultClauseIndex === -1) { + defaultClauseIndex = i; + } + } + // Emit switch statements for each run of case clauses either from the first case + // clause or the next case clause with a `yield` in its expression, up to the next + // case clause with a `yield` in its expression. + var clausesWritten = 0; + var pendingClauses = []; + while (clausesWritten < numClauses) { + var defaultClausesSkipped = 0; + for (var i = clausesWritten; i < numClauses; i++) { + var clause = caseBlock.clauses[i]; + if (clause.kind === 271 /* CaseClause */) { + if (containsYield(clause.expression) && pendingClauses.length > 0) { + break; + } + pendingClauses.push(ts.createCaseClause(ts.visitNode(clause.expression, visitor, ts.isExpression), [ + createInlineBreak(clauseLabels[i], /*location*/ clause.expression) + ])); + } + else { + defaultClausesSkipped++; + } + } + if (pendingClauses.length) { + emitStatement(ts.createSwitch(expression, ts.createCaseBlock(pendingClauses))); + clausesWritten += pendingClauses.length; + pendingClauses = []; + } + if (defaultClausesSkipped > 0) { + clausesWritten += defaultClausesSkipped; + defaultClausesSkipped = 0; + } + } + if (defaultClauseIndex >= 0) { + emitBreak(clauseLabels[defaultClauseIndex]); + } + else { + emitBreak(endLabel); + } + for (var i = 0; i < numClauses; i++) { + markLabel(clauseLabels[i]); + transformAndEmitStatements(caseBlock.clauses[i].statements); + } + endSwitchBlock(); + } + else { + emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + } + function visitSwitchStatement(node) { + if (inStatementContainingYield) { + beginScriptSwitchBlock(); + } + node = ts.visitEachChild(node, visitor, context); + if (inStatementContainingYield) { + endSwitchBlock(); + } + return node; + } + function transformAndEmitLabeledStatement(node) { + if (containsYield(node)) { + // [source] + // x: { + // /*body*/ + // } + // + // [intermediate] + // .labeled "x", endLabel + // /*body*/ + // .endlabeled + // .mark endLabel + beginLabeledBlock(ts.idText(node.label)); + transformAndEmitEmbeddedStatement(node.statement); + endLabeledBlock(); + } + else { + emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + } + function visitLabeledStatement(node) { + if (inStatementContainingYield) { + beginScriptLabeledBlock(ts.idText(node.label)); + } + node = ts.visitEachChild(node, visitor, context); + if (inStatementContainingYield) { + endLabeledBlock(); + } + return node; + } + function transformAndEmitThrowStatement(node) { + emitThrow(ts.visitNode(node.expression, visitor, ts.isExpression), + /*location*/ node); + } + function transformAndEmitTryStatement(node) { + if (containsYield(node)) { + // [source] + // try { + // /*tryBlock*/ + // } + // catch (e) { + // /*catchBlock*/ + // } + // finally { + // /*finallyBlock*/ + // } + // + // [intermediate] + // .local _a + // .try tryLabel, catchLabel, finallyLabel, endLabel + // .mark tryLabel + // .nop + // /*tryBlock*/ + // .br endLabel + // .catch + // .mark catchLabel + // _a = %error%; + // /*catchBlock*/ + // .br endLabel + // .finally + // .mark finallyLabel + // /*finallyBlock*/ + // .endfinally + // .endtry + // .mark endLabel + beginExceptionBlock(); + transformAndEmitEmbeddedStatement(node.tryBlock); + if (node.catchClause) { + beginCatchBlock(node.catchClause.variableDeclaration); // TODO: GH#18217 + transformAndEmitEmbeddedStatement(node.catchClause.block); + } + if (node.finallyBlock) { + beginFinallyBlock(); + transformAndEmitEmbeddedStatement(node.finallyBlock); + } + endExceptionBlock(); + } + else { + emitStatement(ts.visitEachChild(node, visitor, context)); + } + } + function containsYield(node) { + return !!node && (node.transformFlags & 4194304 /* ContainsYield */) !== 0; + } + function countInitialNodesWithoutYield(nodes) { + var numNodes = nodes.length; + for (var i = 0; i < numNodes; i++) { + if (containsYield(nodes[i])) { + return i; + } + } + return -1; + } + function onSubstituteNode(hint, node) { + node = previousOnSubstituteNode(hint, node); + if (hint === 1 /* Expression */) { + return substituteExpression(node); + } + return node; + } + function substituteExpression(node) { + if (ts.isIdentifier(node)) { + return substituteExpressionIdentifier(node); + } + return node; + } + function substituteExpressionIdentifier(node) { + if (!ts.isGeneratedIdentifier(node) && renamedCatchVariables && renamedCatchVariables.has(ts.idText(node))) { + var original = ts.getOriginalNode(node); + if (ts.isIdentifier(original) && original.parent) { + var declaration = resolver.getReferencedValueDeclaration(original); + if (declaration) { + var name = renamedCatchVariableDeclarations[ts.getOriginalNodeId(declaration)]; + if (name) { + var clone_7 = ts.getMutableClone(name); + ts.setSourceMapRange(clone_7, node); + ts.setCommentRange(clone_7, node); + return clone_7; + } + } + } + } + return node; + } + function cacheExpression(node) { + var temp; + if (ts.isGeneratedIdentifier(node) || ts.getEmitFlags(node) & 4096 /* HelperName */) { + return node; + } + temp = ts.createTempVariable(hoistVariableDeclaration); + emitAssignment(temp, node, /*location*/ node); + return temp; + } + function declareLocal(name) { + var temp = name + ? ts.createUniqueName(name) + : ts.createTempVariable(/*recordTempVariable*/ undefined); + hoistVariableDeclaration(temp); + return temp; + } + /** + * Defines a label, uses as the target of a Break operation. + */ + function defineLabel() { + if (!labelOffsets) { + labelOffsets = []; + } + var label = nextLabelId; + nextLabelId++; + labelOffsets[label] = -1; + return label; + } + /** + * Marks the current operation with the specified label. + */ + function markLabel(label) { + ts.Debug.assert(labelOffsets !== undefined, "No labels were defined."); + labelOffsets[label] = operations ? operations.length : 0; + } + /** + * Begins a block operation (With, Break/Continue, Try/Catch/Finally) + * + * @param block Information about the block. + */ + function beginBlock(block) { + if (!blocks) { + blocks = []; + blockActions = []; + blockOffsets = []; + blockStack = []; + } + var index = blockActions.length; + blockActions[index] = 0 /* Open */; + blockOffsets[index] = operations ? operations.length : 0; + blocks[index] = block; + blockStack.push(block); + return index; + } + /** + * Ends the current block operation. + */ + function endBlock() { + var block = peekBlock(); + if (block === undefined) + return ts.Debug.fail("beginBlock was never called."); + var index = blockActions.length; + blockActions[index] = 1 /* Close */; + blockOffsets[index] = operations ? operations.length : 0; + blocks[index] = block; + blockStack.pop(); + return block; + } + /** + * Gets the current open block. + */ + function peekBlock() { + return ts.lastOrUndefined(blockStack); + } + /** + * Gets the kind of the current open block. + */ + function peekBlockKind() { + var block = peekBlock(); + return block && block.kind; + } + /** + * Begins a code block for a generated `with` statement. + * + * @param expression An identifier representing expression for the `with` block. + */ + function beginWithBlock(expression) { + var startLabel = defineLabel(); + var endLabel = defineLabel(); + markLabel(startLabel); + beginBlock({ + kind: 1 /* With */, + expression: expression, + startLabel: startLabel, + endLabel: endLabel + }); + } + /** + * Ends a code block for a generated `with` statement. + */ + function endWithBlock() { + ts.Debug.assert(peekBlockKind() === 1 /* With */); + var block = endBlock(); + markLabel(block.endLabel); + } + /** + * Begins a code block for a generated `try` statement. + */ + function beginExceptionBlock() { + var startLabel = defineLabel(); + var endLabel = defineLabel(); + markLabel(startLabel); + beginBlock({ + kind: 0 /* Exception */, + state: 0 /* Try */, + startLabel: startLabel, + endLabel: endLabel + }); + emitNop(); + return endLabel; + } + /** + * Enters the `catch` clause of a generated `try` statement. + * + * @param variable The catch variable. + */ + function beginCatchBlock(variable) { + ts.Debug.assert(peekBlockKind() === 0 /* Exception */); + // generated identifiers should already be unique within a file + var name; + if (ts.isGeneratedIdentifier(variable.name)) { + name = variable.name; + hoistVariableDeclaration(variable.name); + } + else { + var text = ts.idText(variable.name); + name = declareLocal(text); + if (!renamedCatchVariables) { + renamedCatchVariables = ts.createMap(); + renamedCatchVariableDeclarations = []; + context.enableSubstitution(72 /* Identifier */); + } + renamedCatchVariables.set(text, true); + renamedCatchVariableDeclarations[ts.getOriginalNodeId(variable)] = name; + } + var exception = peekBlock(); + ts.Debug.assert(exception.state < 1 /* Catch */); + var endLabel = exception.endLabel; + emitBreak(endLabel); + var catchLabel = defineLabel(); + markLabel(catchLabel); + exception.state = 1 /* Catch */; + exception.catchVariable = name; + exception.catchLabel = catchLabel; + emitAssignment(name, ts.createCall(ts.createPropertyAccess(state, "sent"), /*typeArguments*/ undefined, [])); + emitNop(); + } + /** + * Enters the `finally` block of a generated `try` statement. + */ + function beginFinallyBlock() { + ts.Debug.assert(peekBlockKind() === 0 /* Exception */); + var exception = peekBlock(); + ts.Debug.assert(exception.state < 2 /* Finally */); + var endLabel = exception.endLabel; + emitBreak(endLabel); + var finallyLabel = defineLabel(); + markLabel(finallyLabel); + exception.state = 2 /* Finally */; + exception.finallyLabel = finallyLabel; + } + /** + * Ends the code block for a generated `try` statement. + */ + function endExceptionBlock() { + ts.Debug.assert(peekBlockKind() === 0 /* Exception */); + var exception = endBlock(); + var state = exception.state; + if (state < 2 /* Finally */) { + emitBreak(exception.endLabel); + } + else { + emitEndfinally(); + } + markLabel(exception.endLabel); + emitNop(); + exception.state = 3 /* Done */; + } + /** + * Begins a code block that supports `break` or `continue` statements that are defined in + * the source tree and not from generated code. + * + * @param labelText Names from containing labeled statements. + */ + function beginScriptLoopBlock() { + beginBlock({ + kind: 3 /* Loop */, + isScript: true, + breakLabel: -1, + continueLabel: -1 + }); + } + /** + * Begins a code block that supports `break` or `continue` statements that are defined in + * generated code. Returns a label used to mark the operation to which to jump when a + * `break` statement targets this block. + * + * @param continueLabel A Label used to mark the operation to which to jump when a + * `continue` statement targets this block. + */ + function beginLoopBlock(continueLabel) { + var breakLabel = defineLabel(); + beginBlock({ + kind: 3 /* Loop */, + isScript: false, + breakLabel: breakLabel, + continueLabel: continueLabel, + }); + return breakLabel; + } + /** + * Ends a code block that supports `break` or `continue` statements that are defined in + * generated code or in the source tree. + */ + function endLoopBlock() { + ts.Debug.assert(peekBlockKind() === 3 /* Loop */); + var block = endBlock(); + var breakLabel = block.breakLabel; + if (!block.isScript) { + markLabel(breakLabel); + } + } + /** + * Begins a code block that supports `break` statements that are defined in the source + * tree and not from generated code. + * + */ + function beginScriptSwitchBlock() { + beginBlock({ + kind: 2 /* Switch */, + isScript: true, + breakLabel: -1 + }); + } + /** + * Begins a code block that supports `break` statements that are defined in generated code. + * Returns a label used to mark the operation to which to jump when a `break` statement + * targets this block. + */ + function beginSwitchBlock() { + var breakLabel = defineLabel(); + beginBlock({ + kind: 2 /* Switch */, + isScript: false, + breakLabel: breakLabel, + }); + return breakLabel; + } + /** + * Ends a code block that supports `break` statements that are defined in generated code. + */ + function endSwitchBlock() { + ts.Debug.assert(peekBlockKind() === 2 /* Switch */); + var block = endBlock(); + var breakLabel = block.breakLabel; + if (!block.isScript) { + markLabel(breakLabel); + } + } + function beginScriptLabeledBlock(labelText) { + beginBlock({ + kind: 4 /* Labeled */, + isScript: true, + labelText: labelText, + breakLabel: -1 + }); + } + function beginLabeledBlock(labelText) { + var breakLabel = defineLabel(); + beginBlock({ + kind: 4 /* Labeled */, + isScript: false, + labelText: labelText, + breakLabel: breakLabel + }); + } + function endLabeledBlock() { + ts.Debug.assert(peekBlockKind() === 4 /* Labeled */); + var block = endBlock(); + if (!block.isScript) { + markLabel(block.breakLabel); + } + } + /** + * Indicates whether the provided block supports `break` statements. + * + * @param block A code block. + */ + function supportsUnlabeledBreak(block) { + return block.kind === 2 /* Switch */ + || block.kind === 3 /* Loop */; + } + /** + * Indicates whether the provided block supports `break` statements with labels. + * + * @param block A code block. + */ + function supportsLabeledBreakOrContinue(block) { + return block.kind === 4 /* Labeled */; + } + /** + * Indicates whether the provided block supports `continue` statements. + * + * @param block A code block. + */ + function supportsUnlabeledContinue(block) { + return block.kind === 3 /* Loop */; + } + function hasImmediateContainingLabeledBlock(labelText, start) { + for (var j = start; j >= 0; j--) { + var containingBlock = blockStack[j]; + if (supportsLabeledBreakOrContinue(containingBlock)) { + if (containingBlock.labelText === labelText) { + return true; + } + } + else { + break; + } + } + return false; + } + /** + * Finds the label that is the target for a `break` statement. + * + * @param labelText An optional name of a containing labeled statement. + */ + function findBreakTarget(labelText) { + if (blockStack) { + if (labelText) { + for (var i = blockStack.length - 1; i >= 0; i--) { + var block = blockStack[i]; + if (supportsLabeledBreakOrContinue(block) && block.labelText === labelText) { + return block.breakLabel; + } + else if (supportsUnlabeledBreak(block) && hasImmediateContainingLabeledBlock(labelText, i - 1)) { + return block.breakLabel; + } + } + } + else { + for (var i = blockStack.length - 1; i >= 0; i--) { + var block = blockStack[i]; + if (supportsUnlabeledBreak(block)) { + return block.breakLabel; + } + } + } + } + return 0; + } + /** + * Finds the label that is the target for a `continue` statement. + * + * @param labelText An optional name of a containing labeled statement. + */ + function findContinueTarget(labelText) { + if (blockStack) { + if (labelText) { + for (var i = blockStack.length - 1; i >= 0; i--) { + var block = blockStack[i]; + if (supportsUnlabeledContinue(block) && hasImmediateContainingLabeledBlock(labelText, i - 1)) { + return block.continueLabel; + } + } + } + else { + for (var i = blockStack.length - 1; i >= 0; i--) { + var block = blockStack[i]; + if (supportsUnlabeledContinue(block)) { + return block.continueLabel; + } + } + } + } + return 0; + } + /** + * Creates an expression that can be used to indicate the value for a label. + * + * @param label A label. + */ + function createLabel(label) { + if (label !== undefined && label > 0) { + if (labelExpressions === undefined) { + labelExpressions = []; + } + var expression = ts.createLiteral(-1); + if (labelExpressions[label] === undefined) { + labelExpressions[label] = [expression]; + } + else { + labelExpressions[label].push(expression); + } + return expression; + } + return ts.createOmittedExpression(); + } + /** + * Creates a numeric literal for the provided instruction. + */ + function createInstruction(instruction) { + var literal = ts.createLiteral(instruction); + ts.addSyntheticTrailingComment(literal, 3 /* MultiLineCommentTrivia */, getInstructionName(instruction)); + return literal; + } + /** + * Creates a statement that can be used indicate a Break operation to the provided label. + * + * @param label A label. + * @param location An optional source map location for the statement. + */ + function createInlineBreak(label, location) { + ts.Debug.assertLessThan(0, label, "Invalid label"); + return ts.setTextRange(ts.createReturn(ts.createArrayLiteral([ + createInstruction(3 /* Break */), + createLabel(label) + ])), location); + } + /** + * Creates a statement that can be used indicate a Return operation. + * + * @param expression The expression for the return statement. + * @param location An optional source map location for the statement. + */ + function createInlineReturn(expression, location) { + return ts.setTextRange(ts.createReturn(ts.createArrayLiteral(expression + ? [createInstruction(2 /* Return */), expression] + : [createInstruction(2 /* Return */)])), location); + } + /** + * Creates an expression that can be used to resume from a Yield operation. + */ + function createGeneratorResume(location) { + return ts.setTextRange(ts.createCall(ts.createPropertyAccess(state, "sent"), + /*typeArguments*/ undefined, []), location); + } + /** + * Emits an empty instruction. + */ + function emitNop() { + emitWorker(0 /* Nop */); + } + /** + * Emits a Statement. + * + * @param node A statement. + */ + function emitStatement(node) { + if (node) { + emitWorker(1 /* Statement */, [node]); + } + else { + emitNop(); + } + } + /** + * Emits an Assignment operation. + * + * @param left The left-hand side of the assignment. + * @param right The right-hand side of the assignment. + * @param location An optional source map location for the assignment. + */ + function emitAssignment(left, right, location) { + emitWorker(2 /* Assign */, [left, right], location); + } + /** + * Emits a Break operation to the specified label. + * + * @param label A label. + * @param location An optional source map location for the assignment. + */ + function emitBreak(label, location) { + emitWorker(3 /* Break */, [label], location); + } + /** + * Emits a Break operation to the specified label when a condition evaluates to a truthy + * value at runtime. + * + * @param label A label. + * @param condition The condition. + * @param location An optional source map location for the assignment. + */ + function emitBreakWhenTrue(label, condition, location) { + emitWorker(4 /* BreakWhenTrue */, [label, condition], location); + } + /** + * Emits a Break to the specified label when a condition evaluates to a falsey value at + * runtime. + * + * @param label A label. + * @param condition The condition. + * @param location An optional source map location for the assignment. + */ + function emitBreakWhenFalse(label, condition, location) { + emitWorker(5 /* BreakWhenFalse */, [label, condition], location); + } + /** + * Emits a YieldStar operation for the provided expression. + * + * @param expression An optional value for the yield operation. + * @param location An optional source map location for the assignment. + */ + function emitYieldStar(expression, location) { + emitWorker(7 /* YieldStar */, [expression], location); + } + /** + * Emits a Yield operation for the provided expression. + * + * @param expression An optional value for the yield operation. + * @param location An optional source map location for the assignment. + */ + function emitYield(expression, location) { + emitWorker(6 /* Yield */, [expression], location); + } + /** + * Emits a Return operation for the provided expression. + * + * @param expression An optional value for the operation. + * @param location An optional source map location for the assignment. + */ + function emitReturn(expression, location) { + emitWorker(8 /* Return */, [expression], location); + } + /** + * Emits a Throw operation for the provided expression. + * + * @param expression A value for the operation. + * @param location An optional source map location for the assignment. + */ + function emitThrow(expression, location) { + emitWorker(9 /* Throw */, [expression], location); + } + /** + * Emits an Endfinally operation. This is used to handle `finally` block semantics. + */ + function emitEndfinally() { + emitWorker(10 /* Endfinally */); + } + /** + * Emits an operation. + * + * @param code The OpCode for the operation. + * @param args The optional arguments for the operation. + */ + function emitWorker(code, args, location) { + if (operations === undefined) { + operations = []; + operationArguments = []; + operationLocations = []; + } + if (labelOffsets === undefined) { + // mark entry point + markLabel(defineLabel()); + } + var operationIndex = operations.length; + operations[operationIndex] = code; + operationArguments[operationIndex] = args; + operationLocations[operationIndex] = location; + } + /** + * Builds the generator function body. + */ + function build() { + blockIndex = 0; + labelNumber = 0; + labelNumbers = undefined; + lastOperationWasAbrupt = false; + lastOperationWasCompletion = false; + clauses = undefined; + statements = undefined; + exceptionBlockStack = undefined; + currentExceptionBlock = undefined; + withBlockStack = undefined; + var buildResult = buildStatements(); + return createGeneratorHelper(context, ts.setEmitFlags(ts.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, state)], + /*type*/ undefined, ts.createBlock(buildResult, + /*multiLine*/ buildResult.length > 0)), 524288 /* ReuseTempVariableScope */)); + } + /** + * Builds the statements for the generator function body. + */ + function buildStatements() { + if (operations) { + for (var operationIndex = 0; operationIndex < operations.length; operationIndex++) { + writeOperation(operationIndex); + } + flushFinalLabel(operations.length); + } + else { + flushFinalLabel(0); + } + if (clauses) { + var labelExpression = ts.createPropertyAccess(state, "label"); + var switchStatement = ts.createSwitch(labelExpression, ts.createCaseBlock(clauses)); + return [ts.startOnNewLine(switchStatement)]; + } + if (statements) { + return statements; + } + return []; + } + /** + * Flush the current label and advance to a new label. + */ + function flushLabel() { + if (!statements) { + return; + } + appendLabel(/*markLabelEnd*/ !lastOperationWasAbrupt); + lastOperationWasAbrupt = false; + lastOperationWasCompletion = false; + labelNumber++; + } + /** + * Flush the final label of the generator function body. + */ + function flushFinalLabel(operationIndex) { + if (isFinalLabelReachable(operationIndex)) { + tryEnterLabel(operationIndex); + withBlockStack = undefined; + writeReturn(/*expression*/ undefined, /*operationLocation*/ undefined); + } + if (statements && clauses) { + appendLabel(/*markLabelEnd*/ false); + } + updateLabelExpressions(); + } + /** + * Tests whether the final label of the generator function body + * is reachable by user code. + */ + function isFinalLabelReachable(operationIndex) { + // if the last operation was *not* a completion (return/throw) then + // the final label is reachable. + if (!lastOperationWasCompletion) { + return true; + } + // if there are no labels defined or referenced, then the final label is + // not reachable. + if (!labelOffsets || !labelExpressions) { + return false; + } + // if the label for this offset is referenced, then the final label + // is reachable. + for (var label = 0; label < labelOffsets.length; label++) { + if (labelOffsets[label] === operationIndex && labelExpressions[label]) { + return true; + } + } + return false; + } + /** + * Appends a case clause for the last label and sets the new label. + * + * @param markLabelEnd Indicates that the transition between labels was a fall-through + * from a previous case clause and the change in labels should be + * reflected on the `state` object. + */ + function appendLabel(markLabelEnd) { + if (!clauses) { + clauses = []; + } + if (statements) { + if (withBlockStack) { + // The previous label was nested inside one or more `with` blocks, so we + // surround the statements in generated `with` blocks to create the same environment. + for (var i = withBlockStack.length - 1; i >= 0; i--) { + var withBlock = withBlockStack[i]; + statements = [ts.createWith(withBlock.expression, ts.createBlock(statements))]; + } + } + if (currentExceptionBlock) { + // The previous label was nested inside of an exception block, so we must + // indicate entry into a protected region by pushing the label numbers + // for each block in the protected region. + var startLabel = currentExceptionBlock.startLabel, catchLabel = currentExceptionBlock.catchLabel, finallyLabel = currentExceptionBlock.finallyLabel, endLabel = currentExceptionBlock.endLabel; + statements.unshift(ts.createExpressionStatement(ts.createCall(ts.createPropertyAccess(ts.createPropertyAccess(state, "trys"), "push"), + /*typeArguments*/ undefined, [ + ts.createArrayLiteral([ + createLabel(startLabel), + createLabel(catchLabel), + createLabel(finallyLabel), + createLabel(endLabel) + ]) + ]))); + currentExceptionBlock = undefined; + } + if (markLabelEnd) { + // The case clause for the last label falls through to this label, so we + // add an assignment statement to reflect the change in labels. + statements.push(ts.createExpressionStatement(ts.createAssignment(ts.createPropertyAccess(state, "label"), ts.createLiteral(labelNumber + 1)))); + } + } + clauses.push(ts.createCaseClause(ts.createLiteral(labelNumber), statements || [])); + statements = undefined; + } + /** + * Tries to enter into a new label at the current operation index. + */ + function tryEnterLabel(operationIndex) { + if (!labelOffsets) { + return; + } + for (var label = 0; label < labelOffsets.length; label++) { + if (labelOffsets[label] === operationIndex) { + flushLabel(); + if (labelNumbers === undefined) { + labelNumbers = []; + } + if (labelNumbers[labelNumber] === undefined) { + labelNumbers[labelNumber] = [label]; + } + else { + labelNumbers[labelNumber].push(label); + } + } + } + } + /** + * Updates literal expressions for labels with actual label numbers. + */ + function updateLabelExpressions() { + if (labelExpressions !== undefined && labelNumbers !== undefined) { + for (var labelNumber_1 = 0; labelNumber_1 < labelNumbers.length; labelNumber_1++) { + var labels = labelNumbers[labelNumber_1]; + if (labels !== undefined) { + for (var _i = 0, labels_1 = labels; _i < labels_1.length; _i++) { + var label = labels_1[_i]; + var expressions = labelExpressions[label]; + if (expressions !== undefined) { + for (var _a = 0, expressions_1 = expressions; _a < expressions_1.length; _a++) { + var expression = expressions_1[_a]; + expression.text = String(labelNumber_1); + } + } + } + } + } + } + } + /** + * Tries to enter or leave a code block. + */ + function tryEnterOrLeaveBlock(operationIndex) { + if (blocks) { + for (; blockIndex < blockActions.length && blockOffsets[blockIndex] <= operationIndex; blockIndex++) { + var block = blocks[blockIndex]; + var blockAction = blockActions[blockIndex]; + switch (block.kind) { + case 0 /* Exception */: + if (blockAction === 0 /* Open */) { + if (!exceptionBlockStack) { + exceptionBlockStack = []; + } + if (!statements) { + statements = []; + } + exceptionBlockStack.push(currentExceptionBlock); + currentExceptionBlock = block; + } + else if (blockAction === 1 /* Close */) { + currentExceptionBlock = exceptionBlockStack.pop(); + } + break; + case 1 /* With */: + if (blockAction === 0 /* Open */) { + if (!withBlockStack) { + withBlockStack = []; + } + withBlockStack.push(block); + } + else if (blockAction === 1 /* Close */) { + withBlockStack.pop(); + } + break; + // default: do nothing + } + } + } + } + /** + * Writes an operation as a statement to the current label's statement list. + * + * @param operation The OpCode of the operation + */ + function writeOperation(operationIndex) { + tryEnterLabel(operationIndex); + tryEnterOrLeaveBlock(operationIndex); + // early termination, nothing else to process in this label + if (lastOperationWasAbrupt) { + return; + } + lastOperationWasAbrupt = false; + lastOperationWasCompletion = false; + var opcode = operations[operationIndex]; + if (opcode === 0 /* Nop */) { + return; + } + else if (opcode === 10 /* Endfinally */) { + return writeEndfinally(); + } + var args = operationArguments[operationIndex]; + if (opcode === 1 /* Statement */) { + return writeStatement(args[0]); + } + var location = operationLocations[operationIndex]; + switch (opcode) { + case 2 /* Assign */: + return writeAssign(args[0], args[1], location); + case 3 /* Break */: + return writeBreak(args[0], location); + case 4 /* BreakWhenTrue */: + return writeBreakWhenTrue(args[0], args[1], location); + case 5 /* BreakWhenFalse */: + return writeBreakWhenFalse(args[0], args[1], location); + case 6 /* Yield */: + return writeYield(args[0], location); + case 7 /* YieldStar */: + return writeYieldStar(args[0], location); + case 8 /* Return */: + return writeReturn(args[0], location); + case 9 /* Throw */: + return writeThrow(args[0], location); + } + } + /** + * Writes a statement to the current label's statement list. + * + * @param statement A statement to write. + */ + function writeStatement(statement) { + if (statement) { + if (!statements) { + statements = [statement]; + } + else { + statements.push(statement); + } + } + } + /** + * Writes an Assign operation to the current label's statement list. + * + * @param left The left-hand side of the assignment. + * @param right The right-hand side of the assignment. + * @param operationLocation The source map location for the operation. + */ + function writeAssign(left, right, operationLocation) { + writeStatement(ts.setTextRange(ts.createExpressionStatement(ts.createAssignment(left, right)), operationLocation)); + } + /** + * Writes a Throw operation to the current label's statement list. + * + * @param expression The value to throw. + * @param operationLocation The source map location for the operation. + */ + function writeThrow(expression, operationLocation) { + lastOperationWasAbrupt = true; + lastOperationWasCompletion = true; + writeStatement(ts.setTextRange(ts.createThrow(expression), operationLocation)); + } + /** + * Writes a Return operation to the current label's statement list. + * + * @param expression The value to return. + * @param operationLocation The source map location for the operation. + */ + function writeReturn(expression, operationLocation) { + lastOperationWasAbrupt = true; + lastOperationWasCompletion = true; + writeStatement(ts.setEmitFlags(ts.setTextRange(ts.createReturn(ts.createArrayLiteral(expression + ? [createInstruction(2 /* Return */), expression] + : [createInstruction(2 /* Return */)])), operationLocation), 384 /* NoTokenSourceMaps */)); + } + /** + * Writes a Break operation to the current label's statement list. + * + * @param label The label for the Break. + * @param operationLocation The source map location for the operation. + */ + function writeBreak(label, operationLocation) { + lastOperationWasAbrupt = true; + writeStatement(ts.setEmitFlags(ts.setTextRange(ts.createReturn(ts.createArrayLiteral([ + createInstruction(3 /* Break */), + createLabel(label) + ])), operationLocation), 384 /* NoTokenSourceMaps */)); + } + /** + * Writes a BreakWhenTrue operation to the current label's statement list. + * + * @param label The label for the Break. + * @param condition The condition for the Break. + * @param operationLocation The source map location for the operation. + */ + function writeBreakWhenTrue(label, condition, operationLocation) { + writeStatement(ts.setEmitFlags(ts.createIf(condition, ts.setEmitFlags(ts.setTextRange(ts.createReturn(ts.createArrayLiteral([ + createInstruction(3 /* Break */), + createLabel(label) + ])), operationLocation), 384 /* NoTokenSourceMaps */)), 1 /* SingleLine */)); + } + /** + * Writes a BreakWhenFalse operation to the current label's statement list. + * + * @param label The label for the Break. + * @param condition The condition for the Break. + * @param operationLocation The source map location for the operation. + */ + function writeBreakWhenFalse(label, condition, operationLocation) { + writeStatement(ts.setEmitFlags(ts.createIf(ts.createLogicalNot(condition), ts.setEmitFlags(ts.setTextRange(ts.createReturn(ts.createArrayLiteral([ + createInstruction(3 /* Break */), + createLabel(label) + ])), operationLocation), 384 /* NoTokenSourceMaps */)), 1 /* SingleLine */)); + } + /** + * Writes a Yield operation to the current label's statement list. + * + * @param expression The expression to yield. + * @param operationLocation The source map location for the operation. + */ + function writeYield(expression, operationLocation) { + lastOperationWasAbrupt = true; + writeStatement(ts.setEmitFlags(ts.setTextRange(ts.createReturn(ts.createArrayLiteral(expression + ? [createInstruction(4 /* Yield */), expression] + : [createInstruction(4 /* Yield */)])), operationLocation), 384 /* NoTokenSourceMaps */)); + } + /** + * Writes a YieldStar instruction to the current label's statement list. + * + * @param expression The expression to yield. + * @param operationLocation The source map location for the operation. + */ + function writeYieldStar(expression, operationLocation) { + lastOperationWasAbrupt = true; + writeStatement(ts.setEmitFlags(ts.setTextRange(ts.createReturn(ts.createArrayLiteral([ + createInstruction(5 /* YieldStar */), + expression + ])), operationLocation), 384 /* NoTokenSourceMaps */)); + } + /** + * Writes an Endfinally instruction to the current label's statement list. + */ + function writeEndfinally() { + lastOperationWasAbrupt = true; + writeStatement(ts.createReturn(ts.createArrayLiteral([ + createInstruction(7 /* Endfinally */) + ]))); + } + } + ts.transformGenerators = transformGenerators; + function createGeneratorHelper(context, body) { + context.requestEmitHelper(generatorHelper); + return ts.createCall(ts.getHelperName("__generator"), + /*typeArguments*/ undefined, [ts.createThis(), body]); + } + // The __generator helper is used by down-level transformations to emulate the runtime + // semantics of an ES2015 generator function. When called, this helper returns an + // object that implements the Iterator protocol, in that it has `next`, `return`, and + // `throw` methods that step through the generator when invoked. + // + // parameters: + // @param thisArg The value to use as the `this` binding for the transformed generator body. + // @param body A function that acts as the transformed generator body. + // + // variables: + // _ Persistent state for the generator that is shared between the helper and the + // generator body. The state object has the following members: + // sent() - A method that returns or throws the current completion value. + // label - The next point at which to resume evaluation of the generator body. + // trys - A stack of protected regions (try/catch/finally blocks). + // ops - A stack of pending instructions when inside of a finally block. + // f A value indicating whether the generator is executing. + // y An iterator to delegate for a yield*. + // t A temporary variable that holds one of the following values (note that these + // cases do not overlap): + // - The completion value when resuming from a `yield` or `yield*`. + // - The error value for a catch block. + // - The current protected region (array of try/catch/finally/end labels). + // - The verb (`next`, `throw`, or `return` method) to delegate to the expression + // of a `yield*`. + // - The result of evaluating the verb delegated to the expression of a `yield*`. + // + // functions: + // verb(n) Creates a bound callback to the `step` function for opcode `n`. + // step(op) Evaluates opcodes in a generator body until execution is suspended or + // completed. + // + // The __generator helper understands a limited set of instructions: + // 0: next(value?) - Start or resume the generator with the specified value. + // 1: throw(error) - Resume the generator with an exception. If the generator is + // suspended inside of one or more protected regions, evaluates + // any intervening finally blocks between the current label and + // the nearest catch block or function boundary. If uncaught, the + // exception is thrown to the caller. + // 2: return(value?) - Resume the generator as if with a return. If the generator is + // suspended inside of one or more protected regions, evaluates any + // intervening finally blocks. + // 3: break(label) - Jump to the specified label. If the label is outside of the + // current protected region, evaluates any intervening finally + // blocks. + // 4: yield(value?) - Yield execution to the caller with an optional value. When + // resumed, the generator will continue at the next label. + // 5: yield*(value) - Delegates evaluation to the supplied iterator. When + // delegation completes, the generator will continue at the next + // label. + // 6: catch(error) - Handles an exception thrown from within the generator body. If + // the current label is inside of one or more protected regions, + // evaluates any intervening finally blocks between the current + // label and the nearest catch block or function boundary. If + // uncaught, the exception is thrown to the caller. + // 7: endfinally - Ends a finally block, resuming the last instruction prior to + // entering a finally block. + // + // For examples of how these are used, see the comments in ./transformers/generators.ts + var generatorHelper = { + name: "typescript:generator", + scoped: false, + priority: 6, + text: "\n var __generator = (this && this.__generator) || function (thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (_) try {\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [op[0] & 2, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n };" + }; +})(ts || (ts = {})); +/*@internal*/ +var ts; +(function (ts) { + function transformModule(context) { + function getTransformModuleDelegate(moduleKind) { + switch (moduleKind) { + case ts.ModuleKind.AMD: return transformAMDModule; + case ts.ModuleKind.UMD: return transformUMDModule; + default: return transformCommonJSModule; + } + } + var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; + var compilerOptions = context.getCompilerOptions(); + var resolver = context.getEmitResolver(); + var host = context.getEmitHost(); + var languageVersion = ts.getEmitScriptTarget(compilerOptions); + var moduleKind = ts.getEmitModuleKind(compilerOptions); + var previousOnSubstituteNode = context.onSubstituteNode; + var previousOnEmitNode = context.onEmitNode; + context.onSubstituteNode = onSubstituteNode; + context.onEmitNode = onEmitNode; + context.enableSubstitution(72 /* Identifier */); // Substitutes expression identifiers with imported/exported symbols. + context.enableSubstitution(204 /* BinaryExpression */); // Substitutes assignments to exported symbols. + context.enableSubstitution(202 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols. + context.enableSubstitution(203 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols. + context.enableSubstitution(276 /* ShorthandPropertyAssignment */); // Substitutes shorthand property assignments for imported/exported symbols. + context.enableEmitNotification(279 /* SourceFile */); // Restore state when substituting nodes in a file. + var moduleInfoMap = []; // The ExternalModuleInfo for each file. + var deferredExports = []; // Exports to defer until an EndOfDeclarationMarker is found. + var currentSourceFile; // The current file. + var currentModuleInfo; // The ExternalModuleInfo for the current file. + var noSubstitution; // Set of nodes for which substitution rules should be ignored. + var needUMDDynamicImportHelper; + return ts.chainBundle(transformSourceFile); + /** + * Transforms the module aspects of a SourceFile. + * + * @param node The SourceFile node. + */ + function transformSourceFile(node) { + if (node.isDeclarationFile || + !(ts.isEffectiveExternalModule(node, compilerOptions) || + node.transformFlags & 16777216 /* ContainsDynamicImport */ || + (ts.isJsonSourceFile(node) && ts.hasJsonModuleEmitEnabled(compilerOptions) && (compilerOptions.out || compilerOptions.outFile)))) { + return node; + } + currentSourceFile = node; + currentModuleInfo = ts.collectExternalModuleInfo(node, resolver, compilerOptions); + moduleInfoMap[ts.getOriginalNodeId(node)] = currentModuleInfo; + // Perform the transformation. + var transformModule = getTransformModuleDelegate(moduleKind); + var updated = transformModule(node); + currentSourceFile = undefined; + currentModuleInfo = undefined; + needUMDDynamicImportHelper = false; + return ts.aggregateTransformFlags(updated); + } + function shouldEmitUnderscoreUnderscoreESModule() { + if (!currentModuleInfo.exportEquals && ts.isExternalModule(currentSourceFile)) { + return true; + } + return false; + } + /** + * Transforms a SourceFile into a CommonJS module. + * + * @param node The SourceFile node. + */ + function transformCommonJSModule(node) { + startLexicalEnvironment(); + var statements = []; + var ensureUseStrict = ts.getStrictOptionValue(compilerOptions, "alwaysStrict") || (!compilerOptions.noImplicitUseStrict && ts.isExternalModule(currentSourceFile)); + var statementOffset = ts.addPrologue(statements, node.statements, ensureUseStrict, sourceElementVisitor); + if (shouldEmitUnderscoreUnderscoreESModule()) { + ts.append(statements, createUnderscoreUnderscoreESModule()); + } + ts.append(statements, ts.visitNode(currentModuleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement)); + ts.addRange(statements, ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset)); + addExportEqualsIfNeeded(statements, /*emitAsReturn*/ false); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + var updated = ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements)); + if (currentModuleInfo.hasExportStarsToExportValues && !compilerOptions.importHelpers) { + // If we have any `export * from ...` declarations + // we need to inform the emitter to add the __export helper. + ts.addEmitHelper(updated, exportStarHelper); + } + ts.addEmitHelpers(updated, context.readEmitHelpers()); + return updated; + } + /** + * Transforms a SourceFile into an AMD module. + * + * @param node The SourceFile node. + */ + function transformAMDModule(node) { + var define = ts.createIdentifier("define"); + var moduleName = ts.tryGetModuleNameFromFile(node, host, compilerOptions); + var jsonSourceFile = ts.isJsonSourceFile(node) && node; + // An AMD define function has the following shape: + // + // define(id?, dependencies?, factory); + // + // This has the shape of the following: + // + // define(name, ["module1", "module2"], function (module1Alias) { ... } + // + // The location of the alias in the parameter list in the factory function needs to + // match the position of the module name in the dependency list. + // + // To ensure this is true in cases of modules with no aliases, e.g.: + // + // import "module" + // + // or + // + // /// + // + // we need to add modules without alias names to the end of the dependencies list + var _a = collectAsynchronousDependencies(node, /*includeNonAmdDependencies*/ true), aliasedModuleNames = _a.aliasedModuleNames, unaliasedModuleNames = _a.unaliasedModuleNames, importAliasNames = _a.importAliasNames; + // Create an updated SourceFile: + // + // define(moduleName?, ["module1", "module2"], function ... + var updated = ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray([ + ts.createExpressionStatement(ts.createCall(define, + /*typeArguments*/ undefined, (moduleName ? [moduleName] : []).concat([ + // Add the dependency array argument: + // + // ["require", "exports", module1", "module2", ...] + ts.createArrayLiteral(jsonSourceFile ? ts.emptyArray : [ + ts.createLiteral("require"), + ts.createLiteral("exports") + ].concat(aliasedModuleNames, unaliasedModuleNames)), + // Add the module body function argument: + // + // function (require, exports, module1, module2) ... + jsonSourceFile ? + jsonSourceFile.statements.length ? jsonSourceFile.statements[0].expression : ts.createObjectLiteral() : + ts.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, [ + ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "require"), + ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "exports") + ].concat(importAliasNames), + /*type*/ undefined, transformAsynchronousModuleBody(node)) + ]))) + ]), + /*location*/ node.statements)); + ts.addEmitHelpers(updated, context.readEmitHelpers()); + return updated; + } + /** + * Transforms a SourceFile into a UMD module. + * + * @param node The SourceFile node. + */ + function transformUMDModule(node) { + var _a = collectAsynchronousDependencies(node, /*includeNonAmdDependencies*/ false), aliasedModuleNames = _a.aliasedModuleNames, unaliasedModuleNames = _a.unaliasedModuleNames, importAliasNames = _a.importAliasNames; + var moduleName = ts.tryGetModuleNameFromFile(node, host, compilerOptions); + var umdHeader = ts.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "factory")], + /*type*/ undefined, ts.setTextRange(ts.createBlock([ + ts.createIf(ts.createLogicalAnd(ts.createTypeCheck(ts.createIdentifier("module"), "object"), ts.createTypeCheck(ts.createPropertyAccess(ts.createIdentifier("module"), "exports"), "object")), ts.createBlock([ + ts.createVariableStatement( + /*modifiers*/ undefined, [ + ts.createVariableDeclaration("v", + /*type*/ undefined, ts.createCall(ts.createIdentifier("factory"), + /*typeArguments*/ undefined, [ + ts.createIdentifier("require"), + ts.createIdentifier("exports") + ])) + ]), + ts.setEmitFlags(ts.createIf(ts.createStrictInequality(ts.createIdentifier("v"), ts.createIdentifier("undefined")), ts.createExpressionStatement(ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier("module"), "exports"), ts.createIdentifier("v")))), 1 /* SingleLine */) + ]), ts.createIf(ts.createLogicalAnd(ts.createTypeCheck(ts.createIdentifier("define"), "function"), ts.createPropertyAccess(ts.createIdentifier("define"), "amd")), ts.createBlock([ + ts.createExpressionStatement(ts.createCall(ts.createIdentifier("define"), + /*typeArguments*/ undefined, (moduleName ? [moduleName] : []).concat([ + ts.createArrayLiteral([ + ts.createLiteral("require"), + ts.createLiteral("exports") + ].concat(aliasedModuleNames, unaliasedModuleNames)), + ts.createIdentifier("factory") + ]))) + ]))) + ], + /*multiLine*/ true), + /*location*/ undefined)); + // Create an updated SourceFile: + // + // (function (factory) { + // if (typeof module === "object" && typeof module.exports === "object") { + // var v = factory(require, exports); + // if (v !== undefined) module.exports = v; + // } + // else if (typeof define === 'function' && define.amd) { + // define(["require", "exports"], factory); + // } + // })(function ...) + var updated = ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray([ + ts.createExpressionStatement(ts.createCall(umdHeader, + /*typeArguments*/ undefined, [ + // Add the module body function argument: + // + // function (require, exports) ... + ts.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, [ + ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "require"), + ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "exports") + ].concat(importAliasNames), + /*type*/ undefined, transformAsynchronousModuleBody(node)) + ])) + ]), + /*location*/ node.statements)); + ts.addEmitHelpers(updated, context.readEmitHelpers()); + return updated; + } + /** + * Collect the additional asynchronous dependencies for the module. + * + * @param node The source file. + * @param includeNonAmdDependencies A value indicating whether to include non-AMD dependencies. + */ + function collectAsynchronousDependencies(node, includeNonAmdDependencies) { + // names of modules with corresponding parameter in the factory function + var aliasedModuleNames = []; + // names of modules with no corresponding parameters in factory function + var unaliasedModuleNames = []; + // names of the parameters in the factory function; these + // parameters need to match the indexes of the corresponding + // module names in aliasedModuleNames. + var importAliasNames = []; + // Fill in amd-dependency tags + for (var _i = 0, _a = node.amdDependencies; _i < _a.length; _i++) { + var amdDependency = _a[_i]; + if (amdDependency.name) { + aliasedModuleNames.push(ts.createLiteral(amdDependency.path)); + importAliasNames.push(ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, amdDependency.name)); + } + else { + unaliasedModuleNames.push(ts.createLiteral(amdDependency.path)); + } + } + for (var _b = 0, _c = currentModuleInfo.externalImports; _b < _c.length; _b++) { + var importNode = _c[_b]; + // Find the name of the external module + var externalModuleName = ts.getExternalModuleNameLiteral(importNode, currentSourceFile, host, resolver, compilerOptions); + // Find the name of the module alias, if there is one + var importAliasName = ts.getLocalNameForExternalImport(importNode, currentSourceFile); + // It is possible that externalModuleName is undefined if it is not string literal. + // This can happen in the invalid import syntax. + // E.g : "import * from alias from 'someLib';" + if (externalModuleName) { + if (includeNonAmdDependencies && importAliasName) { + // Set emitFlags on the name of the classDeclaration + // This is so that when printer will not substitute the identifier + ts.setEmitFlags(importAliasName, 4 /* NoSubstitution */); + aliasedModuleNames.push(externalModuleName); + importAliasNames.push(ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, importAliasName)); + } + else { + unaliasedModuleNames.push(externalModuleName); + } + } + } + return { aliasedModuleNames: aliasedModuleNames, unaliasedModuleNames: unaliasedModuleNames, importAliasNames: importAliasNames }; + } + function getAMDImportExpressionForImport(node) { + if (ts.isImportEqualsDeclaration(node) || ts.isExportDeclaration(node) || !ts.getExternalModuleNameLiteral(node, currentSourceFile, host, resolver, compilerOptions)) { + return undefined; + } + var name = ts.getLocalNameForExternalImport(node, currentSourceFile); // TODO: GH#18217 + var expr = getHelperExpressionForImport(node, name); + if (expr === name) { + return undefined; + } + return ts.createExpressionStatement(ts.createAssignment(name, expr)); + } + /** + * Transforms a SourceFile into an AMD or UMD module body. + * + * @param node The SourceFile node. + */ + function transformAsynchronousModuleBody(node) { + startLexicalEnvironment(); + var statements = []; + var statementOffset = ts.addPrologue(statements, node.statements, /*ensureUseStrict*/ !compilerOptions.noImplicitUseStrict, sourceElementVisitor); + if (shouldEmitUnderscoreUnderscoreESModule()) { + ts.append(statements, createUnderscoreUnderscoreESModule()); + } + // Visit each statement of the module body. + ts.append(statements, ts.visitNode(currentModuleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement)); + if (moduleKind === ts.ModuleKind.AMD) { + ts.addRange(statements, ts.mapDefined(currentModuleInfo.externalImports, getAMDImportExpressionForImport)); + } + ts.addRange(statements, ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset)); + // Append the 'export =' statement if provided. + addExportEqualsIfNeeded(statements, /*emitAsReturn*/ true); + // End the lexical environment for the module body + // and merge any new lexical declarations. + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + var body = ts.createBlock(statements, /*multiLine*/ true); + if (currentModuleInfo.hasExportStarsToExportValues && !compilerOptions.importHelpers) { + // If we have any `export * from ...` declarations + // we need to inform the emitter to add the __export helper. + ts.addEmitHelper(body, exportStarHelper); + } + if (needUMDDynamicImportHelper) { + ts.addEmitHelper(body, dynamicImportUMDHelper); + } + return body; + } + /** + * Adds the down-level representation of `export=` to the statement list if one exists + * in the source file. + * + * @param statements The Statement list to modify. + * @param emitAsReturn A value indicating whether to emit the `export=` statement as a + * return statement. + */ + function addExportEqualsIfNeeded(statements, emitAsReturn) { + if (currentModuleInfo.exportEquals) { + var expressionResult = ts.visitNode(currentModuleInfo.exportEquals.expression, moduleExpressionElementVisitor); + if (expressionResult) { + if (emitAsReturn) { + var statement = ts.createReturn(expressionResult); + ts.setTextRange(statement, currentModuleInfo.exportEquals); + ts.setEmitFlags(statement, 384 /* NoTokenSourceMaps */ | 1536 /* NoComments */); + statements.push(statement); + } + else { + var statement = ts.createExpressionStatement(ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier("module"), "exports"), expressionResult)); + ts.setTextRange(statement, currentModuleInfo.exportEquals); + ts.setEmitFlags(statement, 1536 /* NoComments */); + statements.push(statement); + } + } + } + } + // + // Top-Level Source Element Visitors + // + /** + * Visits a node at the top level of the source file. + * + * @param node The node to visit. + */ + function sourceElementVisitor(node) { + switch (node.kind) { + case 249 /* ImportDeclaration */: + return visitImportDeclaration(node); + case 248 /* ImportEqualsDeclaration */: + return visitImportEqualsDeclaration(node); + case 255 /* ExportDeclaration */: + return visitExportDeclaration(node); + case 254 /* ExportAssignment */: + return visitExportAssignment(node); + case 219 /* VariableStatement */: + return visitVariableStatement(node); + case 239 /* FunctionDeclaration */: + return visitFunctionDeclaration(node); + case 240 /* ClassDeclaration */: + return visitClassDeclaration(node); + case 310 /* MergeDeclarationMarker */: + return visitMergeDeclarationMarker(node); + case 311 /* EndOfDeclarationMarker */: + return visitEndOfDeclarationMarker(node); + default: + return ts.visitEachChild(node, moduleExpressionElementVisitor, context); + } + } + function moduleExpressionElementVisitor(node) { + // This visitor does not need to descend into the tree if there is no dynamic import or destructuring assignment, + // as export/import statements are only transformed at the top level of a file. + if (!(node.transformFlags & 16777216 /* ContainsDynamicImport */) && !(node.transformFlags & 2048 /* ContainsDestructuringAssignment */)) { + return node; + } + if (ts.isImportCall(node)) { + return visitImportCallExpression(node); + } + else if (node.transformFlags & 1024 /* DestructuringAssignment */ && ts.isBinaryExpression(node)) { + return visitDestructuringAssignment(node); + } + else { + return ts.visitEachChild(node, moduleExpressionElementVisitor, context); + } + } + function destructuringNeedsFlattening(node) { + if (ts.isObjectLiteralExpression(node)) { + for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { + var elem = _a[_i]; + switch (elem.kind) { + case 275 /* PropertyAssignment */: + if (destructuringNeedsFlattening(elem.initializer)) { + return true; + } + break; + case 276 /* ShorthandPropertyAssignment */: + if (destructuringNeedsFlattening(elem.name)) { + return true; + } + break; + case 277 /* SpreadAssignment */: + if (destructuringNeedsFlattening(elem.expression)) { + return true; + } + break; + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + return false; + default: ts.Debug.assertNever(elem, "Unhandled object member kind"); + } + } + } + else if (ts.isArrayLiteralExpression(node)) { + for (var _b = 0, _c = node.elements; _b < _c.length; _b++) { + var elem = _c[_b]; + if (ts.isSpreadElement(elem)) { + if (destructuringNeedsFlattening(elem.expression)) { + return true; + } + } + else if (destructuringNeedsFlattening(elem)) { + return true; + } + } + } + else if (ts.isIdentifier(node)) { + return ts.length(getExports(node)) > (ts.isExportName(node) ? 1 : 0); + } + return false; + } + function visitDestructuringAssignment(node) { + if (destructuringNeedsFlattening(node.left)) { + return ts.flattenDestructuringAssignment(node, moduleExpressionElementVisitor, context, 0 /* All */, /*needsValue*/ false, createAllExportExpressions); + } + return ts.visitEachChild(node, moduleExpressionElementVisitor, context); + } + function visitImportCallExpression(node) { + var argument = ts.visitNode(ts.firstOrUndefined(node.arguments), moduleExpressionElementVisitor); + var containsLexicalThis = !!(node.transformFlags & 8192 /* ContainsLexicalThis */); + switch (compilerOptions.module) { + case ts.ModuleKind.AMD: + return createImportCallExpressionAMD(argument, containsLexicalThis); + case ts.ModuleKind.UMD: + return createImportCallExpressionUMD(argument, containsLexicalThis); + case ts.ModuleKind.CommonJS: + default: + return createImportCallExpressionCommonJS(argument, containsLexicalThis); + } + } + function createImportCallExpressionUMD(arg, containsLexicalThis) { + // (function (factory) { + // ... (regular UMD) + // } + // })(function (require, exports, useSyncRequire) { + // "use strict"; + // Object.defineProperty(exports, "__esModule", { value: true }); + // var __syncRequire = typeof module === "object" && typeof module.exports === "object"; + // var __resolved = new Promise(function (resolve) { resolve(); }); + // ..... + // __syncRequire + // ? __resolved.then(function () { return require(x); }) /*CommonJs Require*/ + // : new Promise(function (_a, _b) { require([x], _a, _b); }); /*Amd Require*/ + // }); + needUMDDynamicImportHelper = true; + if (ts.isSimpleCopiableExpression(arg)) { + var argClone = ts.isGeneratedIdentifier(arg) ? arg : ts.isStringLiteral(arg) ? ts.createLiteral(arg) : ts.setEmitFlags(ts.setTextRange(ts.getSynthesizedClone(arg), arg), 1536 /* NoComments */); + return ts.createConditional( + /*condition*/ ts.createIdentifier("__syncRequire"), + /*whenTrue*/ createImportCallExpressionCommonJS(arg, containsLexicalThis), + /*whenFalse*/ createImportCallExpressionAMD(argClone, containsLexicalThis)); + } + else { + var temp = ts.createTempVariable(hoistVariableDeclaration); + return ts.createComma(ts.createAssignment(temp, arg), ts.createConditional( + /*condition*/ ts.createIdentifier("__syncRequire"), + /*whenTrue*/ createImportCallExpressionCommonJS(temp, containsLexicalThis), + /*whenFalse*/ createImportCallExpressionAMD(temp, containsLexicalThis))); + } + } + function createImportCallExpressionAMD(arg, containsLexicalThis) { + // improt("./blah") + // emit as + // define(["require", "exports", "blah"], function (require, exports) { + // ... + // new Promise(function (_a, _b) { require([x], _a, _b); }); /*Amd Require*/ + // }); + var resolve = ts.createUniqueName("resolve"); + var reject = ts.createUniqueName("reject"); + var parameters = [ + ts.createParameter(/*decorator*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, /*name*/ resolve), + ts.createParameter(/*decorator*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, /*name*/ reject) + ]; + var body = ts.createBlock([ + ts.createExpressionStatement(ts.createCall(ts.createIdentifier("require"), + /*typeArguments*/ undefined, [ts.createArrayLiteral([arg || ts.createOmittedExpression()]), resolve, reject])) + ]); + var func; + if (languageVersion >= 2 /* ES2015 */) { + func = ts.createArrowFunction( + /*modifiers*/ undefined, + /*typeParameters*/ undefined, parameters, + /*type*/ undefined, + /*equalsGreaterThanToken*/ undefined, body); + } + else { + func = ts.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, parameters, + /*type*/ undefined, body); + // if there is a lexical 'this' in the import call arguments, ensure we indicate + // that this new function expression indicates it captures 'this' so that the + // es2015 transformer will properly substitute 'this' with '_this'. + if (containsLexicalThis) { + ts.setEmitFlags(func, 8 /* CapturesThis */); + } + } + var promise = ts.createNew(ts.createIdentifier("Promise"), /*typeArguments*/ undefined, [func]); + if (compilerOptions.esModuleInterop) { + context.requestEmitHelper(importStarHelper); + return ts.createCall(ts.createPropertyAccess(promise, ts.createIdentifier("then")), /*typeArguments*/ undefined, [ts.getHelperName("__importStar")]); + } + return promise; + } + function createImportCallExpressionCommonJS(arg, containsLexicalThis) { + // import("./blah") + // emit as + // Promise.resolve().then(function () { return require(x); }) /*CommonJs Require*/ + // We have to wrap require in then callback so that require is done in asynchronously + // if we simply do require in resolve callback in Promise constructor. We will execute the loading immediately + var promiseResolveCall = ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Promise"), "resolve"), /*typeArguments*/ undefined, /*argumentsArray*/ []); + var requireCall = ts.createCall(ts.createIdentifier("require"), /*typeArguments*/ undefined, arg ? [arg] : []); + if (compilerOptions.esModuleInterop) { + context.requestEmitHelper(importStarHelper); + requireCall = ts.createCall(ts.getHelperName("__importStar"), /*typeArguments*/ undefined, [requireCall]); + } + var func; + if (languageVersion >= 2 /* ES2015 */) { + func = ts.createArrowFunction( + /*modifiers*/ undefined, + /*typeParameters*/ undefined, + /*parameters*/ [], + /*type*/ undefined, + /*equalsGreaterThanToken*/ undefined, requireCall); + } + else { + func = ts.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, + /*parameters*/ [], + /*type*/ undefined, ts.createBlock([ts.createReturn(requireCall)])); + // if there is a lexical 'this' in the import call arguments, ensure we indicate + // that this new function expression indicates it captures 'this' so that the + // es2015 transformer will properly substitute 'this' with '_this'. + if (containsLexicalThis) { + ts.setEmitFlags(func, 8 /* CapturesThis */); + } + } + return ts.createCall(ts.createPropertyAccess(promiseResolveCall, "then"), /*typeArguments*/ undefined, [func]); + } + function getHelperExpressionForImport(node, innerExpr) { + if (!compilerOptions.esModuleInterop || ts.getEmitFlags(node) & 67108864 /* NeverApplyImportHelper */) { + return innerExpr; + } + if (ts.getImportNeedsImportStarHelper(node)) { + context.requestEmitHelper(importStarHelper); + return ts.createCall(ts.getHelperName("__importStar"), /*typeArguments*/ undefined, [innerExpr]); + } + if (ts.getImportNeedsImportDefaultHelper(node)) { + context.requestEmitHelper(importDefaultHelper); + return ts.createCall(ts.getHelperName("__importDefault"), /*typeArguments*/ undefined, [innerExpr]); + } + return innerExpr; + } + /** + * Visits an ImportDeclaration node. + * + * @param node The node to visit. + */ + function visitImportDeclaration(node) { + var statements; + var namespaceDeclaration = ts.getNamespaceDeclarationNode(node); + if (moduleKind !== ts.ModuleKind.AMD) { + if (!node.importClause) { + // import "mod"; + return ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(createRequireCall(node)), node), node); + } + else { + var variables = []; + if (namespaceDeclaration && !ts.isDefaultImport(node)) { + // import * as n from "mod"; + variables.push(ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name), + /*type*/ undefined, getHelperExpressionForImport(node, createRequireCall(node)))); + } + else { + // import d from "mod"; + // import { x, y } from "mod"; + // import d, { x, y } from "mod"; + // import d, * as n from "mod"; + variables.push(ts.createVariableDeclaration(ts.getGeneratedNameForNode(node), + /*type*/ undefined, getHelperExpressionForImport(node, createRequireCall(node)))); + if (namespaceDeclaration && ts.isDefaultImport(node)) { + variables.push(ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name), + /*type*/ undefined, ts.getGeneratedNameForNode(node))); + } + } + statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList(variables, languageVersion >= 2 /* ES2015 */ ? 2 /* Const */ : 0 /* None */)), + /*location*/ node), + /*original*/ node)); + } + } + else if (namespaceDeclaration && ts.isDefaultImport(node)) { + // import d, * as n from "mod"; + statements = ts.append(statements, ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ + ts.setOriginalNode(ts.setTextRange(ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name), + /*type*/ undefined, ts.getGeneratedNameForNode(node)), + /*location*/ node), + /*original*/ node) + ], languageVersion >= 2 /* ES2015 */ ? 2 /* Const */ : 0 /* None */))); + } + if (hasAssociatedEndOfDeclarationMarker(node)) { + // Defer exports until we encounter an EndOfDeclarationMarker node + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportsOfImportDeclaration(deferredExports[id], node); + } + else { + statements = appendExportsOfImportDeclaration(statements, node); + } + return ts.singleOrMany(statements); + } + /** + * Creates a `require()` call to import an external module. + * + * @param importNode The declararation to import. + */ + function createRequireCall(importNode) { + var moduleName = ts.getExternalModuleNameLiteral(importNode, currentSourceFile, host, resolver, compilerOptions); + var args = []; + if (moduleName) { + args.push(moduleName); + } + return ts.createCall(ts.createIdentifier("require"), /*typeArguments*/ undefined, args); + } + /** + * Visits an ImportEqualsDeclaration node. + * + * @param node The node to visit. + */ + function visitImportEqualsDeclaration(node) { + ts.Debug.assert(ts.isExternalModuleImportEqualsDeclaration(node), "import= for internal module references should be handled in an earlier transformer."); + var statements; + if (moduleKind !== ts.ModuleKind.AMD) { + if (ts.hasModifier(node, 1 /* Export */)) { + statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(createExportExpression(node.name, createRequireCall(node))), node), node)); + } + else { + statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(ts.getSynthesizedClone(node.name), + /*type*/ undefined, createRequireCall(node)) + ], + /*flags*/ languageVersion >= 2 /* ES2015 */ ? 2 /* Const */ : 0 /* None */)), node), node)); + } + } + else { + if (ts.hasModifier(node, 1 /* Export */)) { + statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(createExportExpression(ts.getExportName(node), ts.getLocalName(node))), node), node)); + } + } + if (hasAssociatedEndOfDeclarationMarker(node)) { + // Defer exports until we encounter an EndOfDeclarationMarker node + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportsOfImportEqualsDeclaration(deferredExports[id], node); + } + else { + statements = appendExportsOfImportEqualsDeclaration(statements, node); + } + return ts.singleOrMany(statements); + } + /** + * Visits an ExportDeclaration node. + * + * @param The node to visit. + */ + function visitExportDeclaration(node) { + if (!node.moduleSpecifier) { + // Elide export declarations with no module specifier as they are handled + // elsewhere. + return undefined; + } + var generatedName = ts.getGeneratedNameForNode(node); + if (node.exportClause) { + var statements = []; + // export { x, y } from "mod"; + if (moduleKind !== ts.ModuleKind.AMD) { + statements.push(ts.setOriginalNode(ts.setTextRange(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(generatedName, + /*type*/ undefined, createRequireCall(node)) + ])), + /*location*/ node), + /* original */ node)); + } + for (var _i = 0, _a = node.exportClause.elements; _i < _a.length; _i++) { + var specifier = _a[_i]; + var exportedValue = ts.createPropertyAccess(generatedName, specifier.propertyName || specifier.name); + statements.push(ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(createExportExpression(ts.getExportName(specifier), exportedValue)), specifier), specifier)); + } + return ts.singleOrMany(statements); + } + else { + // export * from "mod"; + return ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(createExportStarHelper(context, moduleKind !== ts.ModuleKind.AMD ? createRequireCall(node) : generatedName)), node), node); + } + } + /** + * Visits an ExportAssignment node. + * + * @param node The node to visit. + */ + function visitExportAssignment(node) { + if (node.isExportEquals) { + return undefined; + } + var statements; + var original = node.original; + if (original && hasAssociatedEndOfDeclarationMarker(original)) { + // Defer exports until we encounter an EndOfDeclarationMarker node + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportStatement(deferredExports[id], ts.createIdentifier("default"), ts.visitNode(node.expression, moduleExpressionElementVisitor), /*location*/ node, /*allowComments*/ true); + } + else { + statements = appendExportStatement(statements, ts.createIdentifier("default"), ts.visitNode(node.expression, moduleExpressionElementVisitor), /*location*/ node, /*allowComments*/ true); + } + return ts.singleOrMany(statements); + } + /** + * Visits a FunctionDeclaration node. + * + * @param node The node to visit. + */ + function visitFunctionDeclaration(node) { + var statements; + if (ts.hasModifier(node, 1 /* Export */)) { + statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createFunctionDeclaration( + /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, ts.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true), + /*typeParameters*/ undefined, ts.visitNodes(node.parameters, moduleExpressionElementVisitor), + /*type*/ undefined, ts.visitEachChild(node.body, moduleExpressionElementVisitor, context)), + /*location*/ node), + /*original*/ node)); + } + else { + statements = ts.append(statements, ts.visitEachChild(node, moduleExpressionElementVisitor, context)); + } + if (hasAssociatedEndOfDeclarationMarker(node)) { + // Defer exports until we encounter an EndOfDeclarationMarker node + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node); + } + else { + statements = appendExportsOfHoistedDeclaration(statements, node); + } + return ts.singleOrMany(statements); + } + /** + * Visits a ClassDeclaration node. + * + * @param node The node to visit. + */ + function visitClassDeclaration(node) { + var statements; + if (ts.hasModifier(node, 1 /* Export */)) { + statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createClassDeclaration( + /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true), + /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, moduleExpressionElementVisitor), ts.visitNodes(node.members, moduleExpressionElementVisitor)), node), node)); + } + else { + statements = ts.append(statements, ts.visitEachChild(node, moduleExpressionElementVisitor, context)); + } + if (hasAssociatedEndOfDeclarationMarker(node)) { + // Defer exports until we encounter an EndOfDeclarationMarker node + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node); + } + else { + statements = appendExportsOfHoistedDeclaration(statements, node); + } + return ts.singleOrMany(statements); + } + /** + * Visits a VariableStatement node. + * + * @param node The node to visit. + */ + function visitVariableStatement(node) { + var statements; + var variables; + var expressions; + if (ts.hasModifier(node, 1 /* Export */)) { + var modifiers = void 0; + // If we're exporting these variables, then these just become assignments to 'exports.x'. + // We only want to emit assignments for variables with initializers. + for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { + var variable = _a[_i]; + if (ts.isIdentifier(variable.name) && ts.isLocalName(variable.name)) { + if (!modifiers) { + modifiers = ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier); + } + variables = ts.append(variables, variable); + } + else if (variable.initializer) { + expressions = ts.append(expressions, transformInitializedVariable(variable)); + } + } + if (variables) { + statements = ts.append(statements, ts.updateVariableStatement(node, modifiers, ts.updateVariableDeclarationList(node.declarationList, variables))); + } + if (expressions) { + statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(ts.inlineExpressions(expressions)), node), node)); + } + } + else { + statements = ts.append(statements, ts.visitEachChild(node, moduleExpressionElementVisitor, context)); + } + if (hasAssociatedEndOfDeclarationMarker(node)) { + // Defer exports until we encounter an EndOfDeclarationMarker node + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node); + } + else { + statements = appendExportsOfVariableStatement(statements, node); + } + return ts.singleOrMany(statements); + } + function createAllExportExpressions(name, value, location) { + var exportedNames = getExports(name); + if (exportedNames) { + // For each additional export of the declaration, apply an export assignment. + var expression = ts.isExportName(name) ? value : ts.createAssignment(name, value); + for (var _i = 0, exportedNames_1 = exportedNames; _i < exportedNames_1.length; _i++) { + var exportName = exportedNames_1[_i]; + // Mark the node to prevent triggering substitution. + ts.setEmitFlags(expression, 4 /* NoSubstitution */); + expression = createExportExpression(exportName, expression, /*location*/ location); + } + return expression; + } + return ts.createAssignment(name, value); + } + /** + * Transforms an exported variable with an initializer into an expression. + * + * @param node The node to transform. + */ + function transformInitializedVariable(node) { + if (ts.isBindingPattern(node.name)) { + return ts.flattenDestructuringAssignment(ts.visitNode(node, moduleExpressionElementVisitor), + /*visitor*/ undefined, context, 0 /* All */, + /*needsValue*/ false, createAllExportExpressions); + } + else { + return ts.createAssignment(ts.setTextRange(ts.createPropertyAccess(ts.createIdentifier("exports"), node.name), + /*location*/ node.name), ts.visitNode(node.initializer, moduleExpressionElementVisitor)); + } + } + /** + * Visits a MergeDeclarationMarker used as a placeholder for the beginning of a merged + * and transformed declaration. + * + * @param node The node to visit. + */ + function visitMergeDeclarationMarker(node) { + // For an EnumDeclaration or ModuleDeclaration that merges with a preceeding + // declaration we do not emit a leading variable declaration. To preserve the + // begin/end semantics of the declararation and to properly handle exports + // we wrapped the leading variable declaration in a `MergeDeclarationMarker`. + // + // To balance the declaration, add the exports of the elided variable + // statement. + if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 219 /* VariableStatement */) { + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node.original); + } + return node; + } + /** + * Determines whether a node has an associated EndOfDeclarationMarker. + * + * @param node The node to test. + */ + function hasAssociatedEndOfDeclarationMarker(node) { + return (ts.getEmitFlags(node) & 4194304 /* HasEndOfDeclarationMarker */) !== 0; + } + /** + * Visits a DeclarationMarker used as a placeholder for the end of a transformed + * declaration. + * + * @param node The node to visit. + */ + function visitEndOfDeclarationMarker(node) { + // For some transformations we emit an `EndOfDeclarationMarker` to mark the actual + // end of the transformed declaration. We use this marker to emit any deferred exports + // of the declaration. + var id = ts.getOriginalNodeId(node); + var statements = deferredExports[id]; + if (statements) { + delete deferredExports[id]; + return ts.append(statements, node); + } + return node; + } + /** + * Appends the exports of an ImportDeclaration to a statement list, returning the + * statement list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param decl The declaration whose exports are to be recorded. + */ + function appendExportsOfImportDeclaration(statements, decl) { + if (currentModuleInfo.exportEquals) { + return statements; + } + var importClause = decl.importClause; + if (!importClause) { + return statements; + } + if (importClause.name) { + statements = appendExportsOfDeclaration(statements, importClause); + } + var namedBindings = importClause.namedBindings; + if (namedBindings) { + switch (namedBindings.kind) { + case 251 /* NamespaceImport */: + statements = appendExportsOfDeclaration(statements, namedBindings); + break; + case 252 /* NamedImports */: + for (var _i = 0, _a = namedBindings.elements; _i < _a.length; _i++) { + var importBinding = _a[_i]; + statements = appendExportsOfDeclaration(statements, importBinding); + } + break; + } + } + return statements; + } + /** + * Appends the exports of an ImportEqualsDeclaration to a statement list, returning the + * statement list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param decl The declaration whose exports are to be recorded. + */ + function appendExportsOfImportEqualsDeclaration(statements, decl) { + if (currentModuleInfo.exportEquals) { + return statements; + } + return appendExportsOfDeclaration(statements, decl); + } + /** + * Appends the exports of a VariableStatement to a statement list, returning the statement + * list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param node The VariableStatement whose exports are to be recorded. + */ + function appendExportsOfVariableStatement(statements, node) { + if (currentModuleInfo.exportEquals) { + return statements; + } + for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + statements = appendExportsOfBindingElement(statements, decl); + } + return statements; + } + /** + * Appends the exports of a VariableDeclaration or BindingElement to a statement list, + * returning the statement list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param decl The declaration whose exports are to be recorded. + */ + function appendExportsOfBindingElement(statements, decl) { + if (currentModuleInfo.exportEquals) { + return statements; + } + if (ts.isBindingPattern(decl.name)) { + for (var _i = 0, _a = decl.name.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (!ts.isOmittedExpression(element)) { + statements = appendExportsOfBindingElement(statements, element); + } + } + } + else if (!ts.isGeneratedIdentifier(decl.name)) { + statements = appendExportsOfDeclaration(statements, decl); + } + return statements; + } + /** + * Appends the exports of a ClassDeclaration or FunctionDeclaration to a statement list, + * returning the statement list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param decl The declaration whose exports are to be recorded. + */ + function appendExportsOfHoistedDeclaration(statements, decl) { + if (currentModuleInfo.exportEquals) { + return statements; + } + if (ts.hasModifier(decl, 1 /* Export */)) { + var exportName = ts.hasModifier(decl, 512 /* Default */) ? ts.createIdentifier("default") : ts.getDeclarationName(decl); + statements = appendExportStatement(statements, exportName, ts.getLocalName(decl), /*location*/ decl); + } + if (decl.name) { + statements = appendExportsOfDeclaration(statements, decl); + } + return statements; + } + /** + * Appends the exports of a declaration to a statement list, returning the statement list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param decl The declaration to export. + */ + function appendExportsOfDeclaration(statements, decl) { + var name = ts.getDeclarationName(decl); + var exportSpecifiers = currentModuleInfo.exportSpecifiers.get(ts.idText(name)); + if (exportSpecifiers) { + for (var _i = 0, exportSpecifiers_1 = exportSpecifiers; _i < exportSpecifiers_1.length; _i++) { + var exportSpecifier = exportSpecifiers_1[_i]; + statements = appendExportStatement(statements, exportSpecifier.name, name, /*location*/ exportSpecifier.name); + } + } + return statements; + } + /** + * Appends the down-level representation of an export to a statement list, returning the + * statement list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param exportName The name of the export. + * @param expression The expression to export. + * @param location The location to use for source maps and comments for the export. + * @param allowComments Whether to allow comments on the export. + */ + function appendExportStatement(statements, exportName, expression, location, allowComments) { + statements = ts.append(statements, createExportStatement(exportName, expression, location, allowComments)); + return statements; + } + function createUnderscoreUnderscoreESModule() { + var statement; + if (languageVersion === 0 /* ES3 */) { + statement = ts.createExpressionStatement(createExportExpression(ts.createIdentifier("__esModule"), ts.createLiteral(/*value*/ true))); + } + else { + statement = ts.createExpressionStatement(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"), + /*typeArguments*/ undefined, [ + ts.createIdentifier("exports"), + ts.createLiteral("__esModule"), + ts.createObjectLiteral([ + ts.createPropertyAssignment("value", ts.createLiteral(/*value*/ true)) + ]) + ])); + } + ts.setEmitFlags(statement, 1048576 /* CustomPrologue */); + return statement; + } + /** + * Creates a call to the current file's export function to export a value. + * + * @param name The bound name of the export. + * @param value The exported value. + * @param location The location to use for source maps and comments for the export. + * @param allowComments An optional value indicating whether to emit comments for the statement. + */ + function createExportStatement(name, value, location, allowComments) { + var statement = ts.setTextRange(ts.createExpressionStatement(createExportExpression(name, value)), location); + ts.startOnNewLine(statement); + if (!allowComments) { + ts.setEmitFlags(statement, 1536 /* NoComments */); + } + return statement; + } + /** + * Creates a call to the current file's export function to export a value. + * + * @param name The bound name of the export. + * @param value The exported value. + * @param location The location to use for source maps and comments for the export. + */ + function createExportExpression(name, value, location) { + return ts.setTextRange(ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier("exports"), ts.getSynthesizedClone(name)), value), location); + } + // + // Modifier Visitors + // + /** + * Visit nodes to elide module-specific modifiers. + * + * @param node The node to visit. + */ + function modifierVisitor(node) { + // Elide module-specific modifiers. + switch (node.kind) { + case 85 /* ExportKeyword */: + case 80 /* DefaultKeyword */: + return undefined; + } + return node; + } + // + // Emit Notification + // + /** + * Hook for node emit notifications. + * + * @param hint A hint as to the intended usage of the node. + * @param node The node to emit. + * @param emit A callback used to emit the node in the printer. + */ + function onEmitNode(hint, node, emitCallback) { + if (node.kind === 279 /* SourceFile */) { + currentSourceFile = node; + currentModuleInfo = moduleInfoMap[ts.getOriginalNodeId(currentSourceFile)]; + noSubstitution = []; + previousOnEmitNode(hint, node, emitCallback); + currentSourceFile = undefined; + currentModuleInfo = undefined; + noSubstitution = undefined; + } + else { + previousOnEmitNode(hint, node, emitCallback); + } + } + // + // Substitutions + // + /** + * Hooks node substitutions. + * + * @param hint A hint as to the intended usage of the node. + * @param node The node to substitute. + */ + function onSubstituteNode(hint, node) { + node = previousOnSubstituteNode(hint, node); + if (node.id && noSubstitution[node.id]) { + return node; + } + if (hint === 1 /* Expression */) { + return substituteExpression(node); + } + else if (ts.isShorthandPropertyAssignment(node)) { + return substituteShorthandPropertyAssignment(node); + } + return node; + } + /** + * Substitution for a ShorthandPropertyAssignment whose declaration name is an imported + * or exported symbol. + * + * @param node The node to substitute. + */ + function substituteShorthandPropertyAssignment(node) { + var name = node.name; + var exportedOrImportedName = substituteExpressionIdentifier(name); + if (exportedOrImportedName !== name) { + // A shorthand property with an assignment initializer is probably part of a + // destructuring assignment + if (node.objectAssignmentInitializer) { + var initializer = ts.createAssignment(exportedOrImportedName, node.objectAssignmentInitializer); + return ts.setTextRange(ts.createPropertyAssignment(name, initializer), node); + } + return ts.setTextRange(ts.createPropertyAssignment(name, exportedOrImportedName), node); + } + return node; + } + /** + * Substitution for an Expression that may contain an imported or exported symbol. + * + * @param node The node to substitute. + */ + function substituteExpression(node) { + switch (node.kind) { + case 72 /* Identifier */: + return substituteExpressionIdentifier(node); + case 204 /* BinaryExpression */: + return substituteBinaryExpression(node); + case 203 /* PostfixUnaryExpression */: + case 202 /* PrefixUnaryExpression */: + return substituteUnaryExpression(node); + } + return node; + } + /** + * Substitution for an Identifier expression that may contain an imported or exported + * symbol. + * + * @param node The node to substitute. + */ + function substituteExpressionIdentifier(node) { + if (ts.getEmitFlags(node) & 4096 /* HelperName */) { + var externalHelpersModuleName = ts.getExternalHelpersModuleName(currentSourceFile); + if (externalHelpersModuleName) { + return ts.createPropertyAccess(externalHelpersModuleName, node); + } + return node; + } + if (!ts.isGeneratedIdentifier(node) && !ts.isLocalName(node)) { + var exportContainer = resolver.getReferencedExportContainer(node, ts.isExportName(node)); + if (exportContainer && exportContainer.kind === 279 /* SourceFile */) { + return ts.setTextRange(ts.createPropertyAccess(ts.createIdentifier("exports"), ts.getSynthesizedClone(node)), + /*location*/ node); + } + var importDeclaration = resolver.getReferencedImportDeclaration(node); + if (importDeclaration) { + if (ts.isImportClause(importDeclaration)) { + return ts.setTextRange(ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent), ts.createIdentifier("default")), + /*location*/ node); + } + else if (ts.isImportSpecifier(importDeclaration)) { + var name = importDeclaration.propertyName || importDeclaration.name; + return ts.setTextRange(ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent.parent.parent), ts.getSynthesizedClone(name)), + /*location*/ node); + } + } + } + return node; + } + /** + * Substitution for a BinaryExpression that may contain an imported or exported symbol. + * + * @param node The node to substitute. + */ + function substituteBinaryExpression(node) { + // When we see an assignment expression whose left-hand side is an exported symbol, + // we should ensure all exports of that symbol are updated with the correct value. + // + // - We do not substitute generated identifiers for any reason. + // - We do not substitute identifiers tagged with the LocalName flag. + // - We do not substitute identifiers that were originally the name of an enum or + // namespace due to how they are transformed in TypeScript. + // - We only substitute identifiers that are exported at the top level. + if (ts.isAssignmentOperator(node.operatorToken.kind) + && ts.isIdentifier(node.left) + && !ts.isGeneratedIdentifier(node.left) + && !ts.isLocalName(node.left) + && !ts.isDeclarationNameOfEnumOrNamespace(node.left)) { + var exportedNames = getExports(node.left); + if (exportedNames) { + // For each additional export of the declaration, apply an export assignment. + var expression = node; + for (var _i = 0, exportedNames_2 = exportedNames; _i < exportedNames_2.length; _i++) { + var exportName = exportedNames_2[_i]; + // Mark the node to prevent triggering this rule again. + noSubstitution[ts.getNodeId(expression)] = true; + expression = createExportExpression(exportName, expression, /*location*/ node); + } + return expression; + } + } + return node; + } + /** + * Substitution for a UnaryExpression that may contain an imported or exported symbol. + * + * @param node The node to substitute. + */ + function substituteUnaryExpression(node) { + // When we see a prefix or postfix increment expression whose operand is an exported + // symbol, we should ensure all exports of that symbol are updated with the correct + // value. + // + // - We do not substitute generated identifiers for any reason. + // - We do not substitute identifiers tagged with the LocalName flag. + // - We do not substitute identifiers that were originally the name of an enum or + // namespace due to how they are transformed in TypeScript. + // - We only substitute identifiers that are exported at the top level. + if ((node.operator === 44 /* PlusPlusToken */ || node.operator === 45 /* MinusMinusToken */) + && ts.isIdentifier(node.operand) + && !ts.isGeneratedIdentifier(node.operand) + && !ts.isLocalName(node.operand) + && !ts.isDeclarationNameOfEnumOrNamespace(node.operand)) { + var exportedNames = getExports(node.operand); + if (exportedNames) { + var expression = node.kind === 203 /* PostfixUnaryExpression */ + ? ts.setTextRange(ts.createBinary(node.operand, ts.createToken(node.operator === 44 /* PlusPlusToken */ ? 60 /* PlusEqualsToken */ : 61 /* MinusEqualsToken */), ts.createLiteral(1)), + /*location*/ node) + : node; + for (var _i = 0, exportedNames_3 = exportedNames; _i < exportedNames_3.length; _i++) { + var exportName = exportedNames_3[_i]; + // Mark the node to prevent triggering this rule again. + noSubstitution[ts.getNodeId(expression)] = true; + expression = createExportExpression(exportName, expression); + } + return expression; + } + } + return node; + } + /** + * Gets the additional exports of a name. + * + * @param name The name. + */ + function getExports(name) { + if (!ts.isGeneratedIdentifier(name)) { + var valueDeclaration = resolver.getReferencedImportDeclaration(name) + || resolver.getReferencedValueDeclaration(name); + if (valueDeclaration) { + return currentModuleInfo + && currentModuleInfo.exportedBindings[ts.getOriginalNodeId(valueDeclaration)]; + } + } + } + } + ts.transformModule = transformModule; + // emit output for the __export helper function + var exportStarHelper = { + name: "typescript:export-star", + scoped: true, + text: "\n function __export(m) {\n for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\n }" + }; + function createExportStarHelper(context, module) { + var compilerOptions = context.getCompilerOptions(); + return compilerOptions.importHelpers + ? ts.createCall(ts.getHelperName("__exportStar"), /*typeArguments*/ undefined, [module, ts.createIdentifier("exports")]) + : ts.createCall(ts.createIdentifier("__export"), /*typeArguments*/ undefined, [module]); + } + // emit helper for dynamic import + var dynamicImportUMDHelper = { + name: "typescript:dynamicimport-sync-require", + scoped: true, + text: "\n var __syncRequire = typeof module === \"object\" && typeof module.exports === \"object\";" + }; + // emit helper for `import * as Name from "foo"` + var importStarHelper = { + name: "typescript:commonjsimportstar", + scoped: false, + text: "\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];\n result[\"default\"] = mod;\n return result;\n};" + }; + // emit helper for `import Name from "foo"` + var importDefaultHelper = { + name: "typescript:commonjsimportdefault", + scoped: false, + text: "\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};" + }; +})(ts || (ts = {})); +/*@internal*/ +var ts; +(function (ts) { + function transformSystemModule(context) { + var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; + var compilerOptions = context.getCompilerOptions(); + var resolver = context.getEmitResolver(); + var host = context.getEmitHost(); + var previousOnSubstituteNode = context.onSubstituteNode; + var previousOnEmitNode = context.onEmitNode; + context.onSubstituteNode = onSubstituteNode; + context.onEmitNode = onEmitNode; + context.enableSubstitution(72 /* Identifier */); // Substitutes expression identifiers for imported symbols. + context.enableSubstitution(276 /* ShorthandPropertyAssignment */); // Substitutes expression identifiers for imported symbols + context.enableSubstitution(204 /* BinaryExpression */); // Substitutes assignments to exported symbols. + context.enableSubstitution(202 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols. + context.enableSubstitution(203 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols. + context.enableEmitNotification(279 /* SourceFile */); // Restore state when substituting nodes in a file. + var moduleInfoMap = []; // The ExternalModuleInfo for each file. + var deferredExports = []; // Exports to defer until an EndOfDeclarationMarker is found. + var exportFunctionsMap = []; // The export function associated with a source file. + var noSubstitutionMap = []; // Set of nodes for which substitution rules should be ignored for each file. + var currentSourceFile; // The current file. + var moduleInfo; // ExternalModuleInfo for the current file. + var exportFunction; // The export function for the current file. + var contextObject; // The context object for the current file. + var hoistedStatements; + var enclosingBlockScopedContainer; + var noSubstitution; // Set of nodes for which substitution rules should be ignored. + return ts.chainBundle(transformSourceFile); + /** + * Transforms the module aspects of a SourceFile. + * + * @param node The SourceFile node. + */ + function transformSourceFile(node) { + if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 16777216 /* ContainsDynamicImport */)) { + return node; + } + var id = ts.getOriginalNodeId(node); + currentSourceFile = node; + enclosingBlockScopedContainer = node; + // System modules have the following shape: + // + // System.register(['dep-1', ... 'dep-n'], function(exports) {/* module body function */}) + // + // The parameter 'exports' here is a callback '(name: string, value: T) => T' that + // is used to publish exported values. 'exports' returns its 'value' argument so in + // most cases expressions that mutate exported values can be rewritten as: + // + // expr -> exports('name', expr) + // + // The only exception in this rule is postfix unary operators, + // see comment to 'substitutePostfixUnaryExpression' for more details + // Collect information about the external module and dependency groups. + moduleInfo = moduleInfoMap[id] = ts.collectExternalModuleInfo(node, resolver, compilerOptions); + // Make sure that the name of the 'exports' function does not conflict with + // existing identifiers. + exportFunction = ts.createUniqueName("exports"); + exportFunctionsMap[id] = exportFunction; + contextObject = ts.createUniqueName("context"); + // Add the body of the module. + var dependencyGroups = collectDependencyGroups(moduleInfo.externalImports); + var moduleBodyBlock = createSystemModuleBody(node, dependencyGroups); + var moduleBodyFunction = ts.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, [ + ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, exportFunction), + ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, contextObject) + ], + /*type*/ undefined, moduleBodyBlock); + // Write the call to `System.register` + // Clear the emit-helpers flag for later passes since we'll have already used it in the module body + // So the helper will be emit at the correct position instead of at the top of the source-file + var moduleName = ts.tryGetModuleNameFromFile(node, host, compilerOptions); + var dependencies = ts.createArrayLiteral(ts.map(dependencyGroups, function (dependencyGroup) { return dependencyGroup.name; })); + var updated = ts.setEmitFlags(ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray([ + ts.createExpressionStatement(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("System"), "register"), + /*typeArguments*/ undefined, moduleName + ? [moduleName, dependencies, moduleBodyFunction] + : [dependencies, moduleBodyFunction])) + ]), node.statements)), 1024 /* NoTrailingComments */); + if (!(compilerOptions.outFile || compilerOptions.out)) { + ts.moveEmitHelpers(updated, moduleBodyBlock, function (helper) { return !helper.scoped; }); + } + if (noSubstitution) { + noSubstitutionMap[id] = noSubstitution; + noSubstitution = undefined; + } + currentSourceFile = undefined; + moduleInfo = undefined; + exportFunction = undefined; + contextObject = undefined; + hoistedStatements = undefined; + enclosingBlockScopedContainer = undefined; + return ts.aggregateTransformFlags(updated); + } + /** + * Collects the dependency groups for this files imports. + * + * @param externalImports The imports for the file. + */ + function collectDependencyGroups(externalImports) { + var groupIndices = ts.createMap(); + var dependencyGroups = []; + for (var _i = 0, externalImports_1 = externalImports; _i < externalImports_1.length; _i++) { + var externalImport = externalImports_1[_i]; + var externalModuleName = ts.getExternalModuleNameLiteral(externalImport, currentSourceFile, host, resolver, compilerOptions); + if (externalModuleName) { + var text = externalModuleName.text; + var groupIndex = groupIndices.get(text); + if (groupIndex !== undefined) { + // deduplicate/group entries in dependency list by the dependency name + dependencyGroups[groupIndex].externalImports.push(externalImport); + } + else { + groupIndices.set(text, dependencyGroups.length); + dependencyGroups.push({ + name: externalModuleName, + externalImports: [externalImport] + }); + } + } + } + return dependencyGroups; + } + /** + * Adds the statements for the module body function for the source file. + * + * @param node The source file for the module. + * @param dependencyGroups The grouped dependencies of the module. + */ + function createSystemModuleBody(node, dependencyGroups) { + // Shape of the body in system modules: + // + // function (exports) { + // + // + // + // return { + // setters: [ + // + // ], + // execute: function() { + // + // } + // } + // + // } + // + // i.e: + // + // import {x} from 'file1' + // var y = 1; + // export function foo() { return y + x(); } + // console.log(y); + // + // Will be transformed to: + // + // function(exports) { + // function foo() { return y + file_1.x(); } + // exports("foo", foo); + // var file_1, y; + // return { + // setters: [ + // function(v) { file_1 = v } + // ], + // execute(): function() { + // y = 1; + // console.log(y); + // } + // }; + // } + var statements = []; + // We start a new lexical environment in this function body, but *not* in the + // body of the execute function. This allows us to emit temporary declarations + // only in the outer module body and not in the inner one. + startLexicalEnvironment(); + // Add any prologue directives. + var ensureUseStrict = ts.getStrictOptionValue(compilerOptions, "alwaysStrict") || (!compilerOptions.noImplicitUseStrict && ts.isExternalModule(currentSourceFile)); + var statementOffset = ts.addPrologue(statements, node.statements, ensureUseStrict, sourceElementVisitor); + // var __moduleName = context_1 && context_1.id; + statements.push(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration("__moduleName", + /*type*/ undefined, ts.createLogicalAnd(contextObject, ts.createPropertyAccess(contextObject, "id"))) + ]))); + // Visit the synthetic external helpers import declaration if present + ts.visitNode(moduleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement); + // Visit the statements of the source file, emitting any transformations into + // the `executeStatements` array. We do this *before* we fill the `setters` array + // as we both emit transformations as well as aggregate some data used when creating + // setters. This allows us to reduce the number of times we need to loop through the + // statements of the source file. + var executeStatements = ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset); + // Emit early exports for function declarations. + ts.addRange(statements, hoistedStatements); + // We emit hoisted variables early to align roughly with our previous emit output. + // Two key differences in this approach are: + // - Temporary variables will appear at the top rather than at the bottom of the file + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + var exportStarFunction = addExportStarIfNeeded(statements); // TODO: GH#18217 + var moduleObject = ts.createObjectLiteral([ + ts.createPropertyAssignment("setters", createSettersArray(exportStarFunction, dependencyGroups)), + ts.createPropertyAssignment("execute", ts.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, + /*parameters*/ [], + /*type*/ undefined, ts.createBlock(executeStatements, /*multiLine*/ true))) + ]); + moduleObject.multiLine = true; + statements.push(ts.createReturn(moduleObject)); + return ts.createBlock(statements, /*multiLine*/ true); + } + /** + * Adds an exportStar function to a statement list if it is needed for the file. + * + * @param statements A statement list. + */ + function addExportStarIfNeeded(statements) { + if (!moduleInfo.hasExportStarsToExportValues) { + return; + } + // when resolving exports local exported entries/indirect exported entries in the module + // should always win over entries with similar names that were added via star exports + // to support this we store names of local/indirect exported entries in a set. + // this set is used to filter names brought by star expors. + // local names set should only be added if we have anything exported + if (!moduleInfo.exportedNames && moduleInfo.exportSpecifiers.size === 0) { + // no exported declarations (export var ...) or export specifiers (export {x}) + // check if we have any non star export declarations. + var hasExportDeclarationWithExportClause = false; + for (var _i = 0, _a = moduleInfo.externalImports; _i < _a.length; _i++) { + var externalImport = _a[_i]; + if (externalImport.kind === 255 /* ExportDeclaration */ && externalImport.exportClause) { + hasExportDeclarationWithExportClause = true; + break; + } + } + if (!hasExportDeclarationWithExportClause) { + // we still need to emit exportStar helper + var exportStarFunction_1 = createExportStarFunction(/*localNames*/ undefined); + statements.push(exportStarFunction_1); + return exportStarFunction_1.name; + } + } + var exportedNames = []; + if (moduleInfo.exportedNames) { + for (var _b = 0, _c = moduleInfo.exportedNames; _b < _c.length; _b++) { + var exportedLocalName = _c[_b]; + if (exportedLocalName.escapedText === "default") { + continue; + } + // write name of exported declaration, i.e 'export var x...' + exportedNames.push(ts.createPropertyAssignment(ts.createLiteral(exportedLocalName), ts.createTrue())); + } + } + for (var _d = 0, _e = moduleInfo.externalImports; _d < _e.length; _d++) { + var externalImport = _e[_d]; + if (externalImport.kind !== 255 /* ExportDeclaration */) { + continue; + } + if (!externalImport.exportClause) { + // export * from ... + continue; + } + for (var _f = 0, _g = externalImport.exportClause.elements; _f < _g.length; _f++) { + var element = _g[_f]; + // write name of indirectly exported entry, i.e. 'export {x} from ...' + exportedNames.push(ts.createPropertyAssignment(ts.createLiteral(ts.idText(element.name || element.propertyName)), ts.createTrue())); + } + } + var exportedNamesStorageRef = ts.createUniqueName("exportedNames"); + statements.push(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(exportedNamesStorageRef, + /*type*/ undefined, ts.createObjectLiteral(exportedNames, /*multiline*/ true)) + ]))); + var exportStarFunction = createExportStarFunction(exportedNamesStorageRef); + statements.push(exportStarFunction); + return exportStarFunction.name; + } + /** + * Creates an exportStar function for the file, with an optional set of excluded local + * names. + * + * @param localNames An optional reference to an object containing a set of excluded local + * names. + */ + function createExportStarFunction(localNames) { + var exportStarFunction = ts.createUniqueName("exportStar"); + var m = ts.createIdentifier("m"); + var n = ts.createIdentifier("n"); + var exports = ts.createIdentifier("exports"); + var condition = ts.createStrictInequality(n, ts.createLiteral("default")); + if (localNames) { + condition = ts.createLogicalAnd(condition, ts.createLogicalNot(ts.createCall(ts.createPropertyAccess(localNames, "hasOwnProperty"), + /*typeArguments*/ undefined, [n]))); + } + return ts.createFunctionDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, exportStarFunction, + /*typeParameters*/ undefined, [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, m)], + /*type*/ undefined, ts.createBlock([ + ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(exports, + /*type*/ undefined, ts.createObjectLiteral([])) + ])), + ts.createForIn(ts.createVariableDeclarationList([ + ts.createVariableDeclaration(n, /*type*/ undefined) + ]), m, ts.createBlock([ + ts.setEmitFlags(ts.createIf(condition, ts.createExpressionStatement(ts.createAssignment(ts.createElementAccess(exports, n), ts.createElementAccess(m, n)))), 1 /* SingleLine */) + ])), + ts.createExpressionStatement(ts.createCall(exportFunction, + /*typeArguments*/ undefined, [exports])) + ], /*multiline*/ true)); + } + /** + * Creates an array setter callbacks for each dependency group. + * + * @param exportStarFunction A reference to an exportStarFunction for the file. + * @param dependencyGroups An array of grouped dependencies. + */ + function createSettersArray(exportStarFunction, dependencyGroups) { + var setters = []; + for (var _i = 0, dependencyGroups_1 = dependencyGroups; _i < dependencyGroups_1.length; _i++) { + var group_1 = dependencyGroups_1[_i]; + // derive a unique name for parameter from the first named entry in the group + var localName = ts.forEach(group_1.externalImports, function (i) { return ts.getLocalNameForExternalImport(i, currentSourceFile); }); + var parameterName = localName ? ts.getGeneratedNameForNode(localName) : ts.createUniqueName(""); + var statements = []; + for (var _a = 0, _b = group_1.externalImports; _a < _b.length; _a++) { + var entry = _b[_a]; + var importVariableName = ts.getLocalNameForExternalImport(entry, currentSourceFile); // TODO: GH#18217 + switch (entry.kind) { + case 249 /* ImportDeclaration */: + if (!entry.importClause) { + // 'import "..."' case + // module is imported only for side-effects, no emit required + break; + } + // falls through + case 248 /* ImportEqualsDeclaration */: + ts.Debug.assert(importVariableName !== undefined); + // save import into the local + statements.push(ts.createExpressionStatement(ts.createAssignment(importVariableName, parameterName))); + break; + case 255 /* ExportDeclaration */: + ts.Debug.assert(importVariableName !== undefined); + if (entry.exportClause) { + // export {a, b as c} from 'foo' + // + // emit as: + // + // exports_({ + // "a": _["a"], + // "c": _["b"] + // }); + var properties = []; + for (var _c = 0, _d = entry.exportClause.elements; _c < _d.length; _c++) { + var e = _d[_c]; + properties.push(ts.createPropertyAssignment(ts.createLiteral(ts.idText(e.name)), ts.createElementAccess(parameterName, ts.createLiteral(ts.idText(e.propertyName || e.name))))); + } + statements.push(ts.createExpressionStatement(ts.createCall(exportFunction, + /*typeArguments*/ undefined, [ts.createObjectLiteral(properties, /*multiline*/ true)]))); + } + else { + // export * from 'foo' + // + // emit as: + // + // exportStar(foo_1_1); + statements.push(ts.createExpressionStatement(ts.createCall(exportStarFunction, + /*typeArguments*/ undefined, [parameterName]))); + } + break; + } + } + setters.push(ts.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, parameterName)], + /*type*/ undefined, ts.createBlock(statements, /*multiLine*/ true))); + } + return ts.createArrayLiteral(setters, /*multiLine*/ true); + } + // + // Top-level Source Element Visitors + // + /** + * Visit source elements at the top-level of a module. + * + * @param node The node to visit. + */ + function sourceElementVisitor(node) { + switch (node.kind) { + case 249 /* ImportDeclaration */: + return visitImportDeclaration(node); + case 248 /* ImportEqualsDeclaration */: + return visitImportEqualsDeclaration(node); + case 255 /* ExportDeclaration */: + // ExportDeclarations are elided as they are handled via + // `appendExportsOfDeclaration`. + return undefined; + case 254 /* ExportAssignment */: + return visitExportAssignment(node); + default: + return nestedElementVisitor(node); + } + } + /** + * Visits an ImportDeclaration node. + * + * @param node The node to visit. + */ + function visitImportDeclaration(node) { + var statements; + if (node.importClause) { + hoistVariableDeclaration(ts.getLocalNameForExternalImport(node, currentSourceFile)); // TODO: GH#18217 + } + if (hasAssociatedEndOfDeclarationMarker(node)) { + // Defer exports until we encounter an EndOfDeclarationMarker node + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportsOfImportDeclaration(deferredExports[id], node); + } + else { + statements = appendExportsOfImportDeclaration(statements, node); + } + return ts.singleOrMany(statements); + } + /** + * Visits an ImportEqualsDeclaration node. + * + * @param node The node to visit. + */ + function visitImportEqualsDeclaration(node) { + ts.Debug.assert(ts.isExternalModuleImportEqualsDeclaration(node), "import= for internal module references should be handled in an earlier transformer."); + var statements; + hoistVariableDeclaration(ts.getLocalNameForExternalImport(node, currentSourceFile)); // TODO: GH#18217 + if (hasAssociatedEndOfDeclarationMarker(node)) { + // Defer exports until we encounter an EndOfDeclarationMarker node + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportsOfImportEqualsDeclaration(deferredExports[id], node); + } + else { + statements = appendExportsOfImportEqualsDeclaration(statements, node); + } + return ts.singleOrMany(statements); + } + /** + * Visits an ExportAssignment node. + * + * @param node The node to visit. + */ + function visitExportAssignment(node) { + if (node.isExportEquals) { + // Elide `export=` as it is illegal in a SystemJS module. + return undefined; + } + var expression = ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression); + var original = node.original; + if (original && hasAssociatedEndOfDeclarationMarker(original)) { + // Defer exports until we encounter an EndOfDeclarationMarker node + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportStatement(deferredExports[id], ts.createIdentifier("default"), expression, /*allowComments*/ true); + } + else { + return createExportStatement(ts.createIdentifier("default"), expression, /*allowComments*/ true); + } + } + /** + * Visits a FunctionDeclaration, hoisting it to the outer module body function. + * + * @param node The node to visit. + */ + function visitFunctionDeclaration(node) { + if (ts.hasModifier(node, 1 /* Export */)) { + hoistedStatements = ts.append(hoistedStatements, ts.updateFunctionDeclaration(node, node.decorators, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, ts.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true), + /*typeParameters*/ undefined, ts.visitNodes(node.parameters, destructuringAndImportCallVisitor, ts.isParameterDeclaration), + /*type*/ undefined, ts.visitNode(node.body, destructuringAndImportCallVisitor, ts.isBlock))); + } + else { + hoistedStatements = ts.append(hoistedStatements, ts.visitEachChild(node, destructuringAndImportCallVisitor, context)); + } + if (hasAssociatedEndOfDeclarationMarker(node)) { + // Defer exports until we encounter an EndOfDeclarationMarker node + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node); + } + else { + hoistedStatements = appendExportsOfHoistedDeclaration(hoistedStatements, node); + } + return undefined; + } + /** + * Visits a ClassDeclaration, hoisting its name to the outer module body function. + * + * @param node The node to visit. + */ + function visitClassDeclaration(node) { + var statements; + // Hoist the name of the class declaration to the outer module body function. + var name = ts.getLocalName(node); + hoistVariableDeclaration(name); + // Rewrite the class declaration into an assignment of a class expression. + statements = ts.append(statements, ts.setTextRange(ts.createExpressionStatement(ts.createAssignment(name, ts.setTextRange(ts.createClassExpression( + /*modifiers*/ undefined, node.name, + /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, destructuringAndImportCallVisitor, ts.isHeritageClause), ts.visitNodes(node.members, destructuringAndImportCallVisitor, ts.isClassElement)), node))), node)); + if (hasAssociatedEndOfDeclarationMarker(node)) { + // Defer exports until we encounter an EndOfDeclarationMarker node + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node); + } + else { + statements = appendExportsOfHoistedDeclaration(statements, node); + } + return ts.singleOrMany(statements); + } + /** + * Visits a variable statement, hoisting declared names to the top-level module body. + * Each declaration is rewritten into an assignment expression. + * + * @param node The node to visit. + */ + function visitVariableStatement(node) { + if (!shouldHoistVariableDeclarationList(node.declarationList)) { + return ts.visitNode(node, destructuringAndImportCallVisitor, ts.isStatement); + } + var expressions; + var isExportedDeclaration = ts.hasModifier(node, 1 /* Export */); + var isMarkedDeclaration = hasAssociatedEndOfDeclarationMarker(node); + for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { + var variable = _a[_i]; + if (variable.initializer) { + expressions = ts.append(expressions, transformInitializedVariable(variable, isExportedDeclaration && !isMarkedDeclaration)); + } + else { + hoistBindingElement(variable); + } + } + var statements; + if (expressions) { + statements = ts.append(statements, ts.setTextRange(ts.createExpressionStatement(ts.inlineExpressions(expressions)), node)); + } + if (isMarkedDeclaration) { + // Defer exports until we encounter an EndOfDeclarationMarker node + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node, isExportedDeclaration); + } + else { + statements = appendExportsOfVariableStatement(statements, node, /*exportSelf*/ false); + } + return ts.singleOrMany(statements); + } + /** + * Hoists the declared names of a VariableDeclaration or BindingElement. + * + * @param node The declaration to hoist. + */ + function hoistBindingElement(node) { + if (ts.isBindingPattern(node.name)) { + for (var _i = 0, _a = node.name.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (!ts.isOmittedExpression(element)) { + hoistBindingElement(element); + } + } + } + else { + hoistVariableDeclaration(ts.getSynthesizedClone(node.name)); + } + } + /** + * Determines whether a VariableDeclarationList should be hoisted. + * + * @param node The node to test. + */ + function shouldHoistVariableDeclarationList(node) { + // hoist only non-block scoped declarations or block scoped declarations parented by source file + return (ts.getEmitFlags(node) & 2097152 /* NoHoisting */) === 0 + && (enclosingBlockScopedContainer.kind === 279 /* SourceFile */ + || (ts.getOriginalNode(node).flags & 3 /* BlockScoped */) === 0); + } + /** + * Transform an initialized variable declaration into an expression. + * + * @param node The node to transform. + * @param isExportedDeclaration A value indicating whether the variable is exported. + */ + function transformInitializedVariable(node, isExportedDeclaration) { + var createAssignment = isExportedDeclaration ? createExportedVariableAssignment : createNonExportedVariableAssignment; + return ts.isBindingPattern(node.name) + ? ts.flattenDestructuringAssignment(node, destructuringAndImportCallVisitor, context, 0 /* All */, + /*needsValue*/ false, createAssignment) + : node.initializer ? createAssignment(node.name, ts.visitNode(node.initializer, destructuringAndImportCallVisitor, ts.isExpression)) : node.name; + } + /** + * Creates an assignment expression for an exported variable declaration. + * + * @param name The name of the variable. + * @param value The value of the variable's initializer. + * @param location The source map location for the assignment. + */ + function createExportedVariableAssignment(name, value, location) { + return createVariableAssignment(name, value, location, /*isExportedDeclaration*/ true); + } + /** + * Creates an assignment expression for a non-exported variable declaration. + * + * @param name The name of the variable. + * @param value The value of the variable's initializer. + * @param location The source map location for the assignment. + */ + function createNonExportedVariableAssignment(name, value, location) { + return createVariableAssignment(name, value, location, /*isExportedDeclaration*/ false); + } + /** + * Creates an assignment expression for a variable declaration. + * + * @param name The name of the variable. + * @param value The value of the variable's initializer. + * @param location The source map location for the assignment. + * @param isExportedDeclaration A value indicating whether the variable is exported. + */ + function createVariableAssignment(name, value, location, isExportedDeclaration) { + hoistVariableDeclaration(ts.getSynthesizedClone(name)); + return isExportedDeclaration + ? createExportExpression(name, preventSubstitution(ts.setTextRange(ts.createAssignment(name, value), location))) + : preventSubstitution(ts.setTextRange(ts.createAssignment(name, value), location)); + } + /** + * Visits a MergeDeclarationMarker used as a placeholder for the beginning of a merged + * and transformed declaration. + * + * @param node The node to visit. + */ + function visitMergeDeclarationMarker(node) { + // For an EnumDeclaration or ModuleDeclaration that merges with a preceeding + // declaration we do not emit a leading variable declaration. To preserve the + // begin/end semantics of the declararation and to properly handle exports + // we wrapped the leading variable declaration in a `MergeDeclarationMarker`. + // + // To balance the declaration, we defer the exports of the elided variable + // statement until we visit this declaration's `EndOfDeclarationMarker`. + if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 219 /* VariableStatement */) { + var id = ts.getOriginalNodeId(node); + var isExportedDeclaration = ts.hasModifier(node.original, 1 /* Export */); + deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node.original, isExportedDeclaration); + } + return node; + } + /** + * Determines whether a node has an associated EndOfDeclarationMarker. + * + * @param node The node to test. + */ + function hasAssociatedEndOfDeclarationMarker(node) { + return (ts.getEmitFlags(node) & 4194304 /* HasEndOfDeclarationMarker */) !== 0; + } + /** + * Visits a DeclarationMarker used as a placeholder for the end of a transformed + * declaration. + * + * @param node The node to visit. + */ + function visitEndOfDeclarationMarker(node) { + // For some transformations we emit an `EndOfDeclarationMarker` to mark the actual + // end of the transformed declaration. We use this marker to emit any deferred exports + // of the declaration. + var id = ts.getOriginalNodeId(node); + var statements = deferredExports[id]; + if (statements) { + delete deferredExports[id]; + return ts.append(statements, node); + } + else { + var original = ts.getOriginalNode(node); + if (ts.isModuleOrEnumDeclaration(original)) { + return ts.append(appendExportsOfDeclaration(statements, original), node); + } + } + return node; + } + /** + * Appends the exports of an ImportDeclaration to a statement list, returning the + * statement list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param decl The declaration whose exports are to be recorded. + */ + function appendExportsOfImportDeclaration(statements, decl) { + if (moduleInfo.exportEquals) { + return statements; + } + var importClause = decl.importClause; + if (!importClause) { + return statements; + } + if (importClause.name) { + statements = appendExportsOfDeclaration(statements, importClause); + } + var namedBindings = importClause.namedBindings; + if (namedBindings) { + switch (namedBindings.kind) { + case 251 /* NamespaceImport */: + statements = appendExportsOfDeclaration(statements, namedBindings); + break; + case 252 /* NamedImports */: + for (var _i = 0, _a = namedBindings.elements; _i < _a.length; _i++) { + var importBinding = _a[_i]; + statements = appendExportsOfDeclaration(statements, importBinding); + } + break; + } + } + return statements; + } + /** + * Appends the export of an ImportEqualsDeclaration to a statement list, returning the + * statement list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param decl The declaration whose exports are to be recorded. + */ + function appendExportsOfImportEqualsDeclaration(statements, decl) { + if (moduleInfo.exportEquals) { + return statements; + } + return appendExportsOfDeclaration(statements, decl); + } + /** + * Appends the exports of a VariableStatement to a statement list, returning the statement + * list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param node The VariableStatement whose exports are to be recorded. + * @param exportSelf A value indicating whether to also export each VariableDeclaration of + * `nodes` declaration list. + */ + function appendExportsOfVariableStatement(statements, node, exportSelf) { + if (moduleInfo.exportEquals) { + return statements; + } + for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + if (decl.initializer || exportSelf) { + statements = appendExportsOfBindingElement(statements, decl, exportSelf); + } + } + return statements; + } + /** + * Appends the exports of a VariableDeclaration or BindingElement to a statement list, + * returning the statement list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param decl The declaration whose exports are to be recorded. + * @param exportSelf A value indicating whether to also export the declaration itself. + */ + function appendExportsOfBindingElement(statements, decl, exportSelf) { + if (moduleInfo.exportEquals) { + return statements; + } + if (ts.isBindingPattern(decl.name)) { + for (var _i = 0, _a = decl.name.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (!ts.isOmittedExpression(element)) { + statements = appendExportsOfBindingElement(statements, element, exportSelf); + } + } + } + else if (!ts.isGeneratedIdentifier(decl.name)) { + var excludeName = void 0; + if (exportSelf) { + statements = appendExportStatement(statements, decl.name, ts.getLocalName(decl)); + excludeName = ts.idText(decl.name); + } + statements = appendExportsOfDeclaration(statements, decl, excludeName); + } + return statements; + } + /** + * Appends the exports of a ClassDeclaration or FunctionDeclaration to a statement list, + * returning the statement list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param decl The declaration whose exports are to be recorded. + */ + function appendExportsOfHoistedDeclaration(statements, decl) { + if (moduleInfo.exportEquals) { + return statements; + } + var excludeName; + if (ts.hasModifier(decl, 1 /* Export */)) { + var exportName = ts.hasModifier(decl, 512 /* Default */) ? ts.createLiteral("default") : decl.name; + statements = appendExportStatement(statements, exportName, ts.getLocalName(decl)); + excludeName = ts.getTextOfIdentifierOrLiteral(exportName); + } + if (decl.name) { + statements = appendExportsOfDeclaration(statements, decl, excludeName); + } + return statements; + } + /** + * Appends the exports of a declaration to a statement list, returning the statement list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param decl The declaration to export. + * @param excludeName An optional name to exclude from exports. + */ + function appendExportsOfDeclaration(statements, decl, excludeName) { + if (moduleInfo.exportEquals) { + return statements; + } + var name = ts.getDeclarationName(decl); + var exportSpecifiers = moduleInfo.exportSpecifiers.get(ts.idText(name)); + if (exportSpecifiers) { + for (var _i = 0, exportSpecifiers_2 = exportSpecifiers; _i < exportSpecifiers_2.length; _i++) { + var exportSpecifier = exportSpecifiers_2[_i]; + if (exportSpecifier.name.escapedText !== excludeName) { + statements = appendExportStatement(statements, exportSpecifier.name, name); + } + } + } + return statements; + } + /** + * Appends the down-level representation of an export to a statement list, returning the + * statement list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param exportName The name of the export. + * @param expression The expression to export. + * @param allowComments Whether to allow comments on the export. + */ + function appendExportStatement(statements, exportName, expression, allowComments) { + statements = ts.append(statements, createExportStatement(exportName, expression, allowComments)); + return statements; + } + /** + * Creates a call to the current file's export function to export a value. + * + * @param name The bound name of the export. + * @param value The exported value. + * @param allowComments An optional value indicating whether to emit comments for the statement. + */ + function createExportStatement(name, value, allowComments) { + var statement = ts.createExpressionStatement(createExportExpression(name, value)); + ts.startOnNewLine(statement); + if (!allowComments) { + ts.setEmitFlags(statement, 1536 /* NoComments */); + } + return statement; + } + /** + * Creates a call to the current file's export function to export a value. + * + * @param name The bound name of the export. + * @param value The exported value. + */ + function createExportExpression(name, value) { + var exportName = ts.isIdentifier(name) ? ts.createLiteral(name) : name; + ts.setEmitFlags(value, ts.getEmitFlags(value) | 1536 /* NoComments */); + return ts.setCommentRange(ts.createCall(exportFunction, /*typeArguments*/ undefined, [exportName, value]), value); + } + // + // Top-Level or Nested Source Element Visitors + // + /** + * Visit nested elements at the top-level of a module. + * + * @param node The node to visit. + */ + function nestedElementVisitor(node) { + switch (node.kind) { + case 219 /* VariableStatement */: + return visitVariableStatement(node); + case 239 /* FunctionDeclaration */: + return visitFunctionDeclaration(node); + case 240 /* ClassDeclaration */: + return visitClassDeclaration(node); + case 225 /* ForStatement */: + return visitForStatement(node); + case 226 /* ForInStatement */: + return visitForInStatement(node); + case 227 /* ForOfStatement */: + return visitForOfStatement(node); + case 223 /* DoStatement */: + return visitDoStatement(node); + case 224 /* WhileStatement */: + return visitWhileStatement(node); + case 233 /* LabeledStatement */: + return visitLabeledStatement(node); + case 231 /* WithStatement */: + return visitWithStatement(node); + case 232 /* SwitchStatement */: + return visitSwitchStatement(node); + case 246 /* CaseBlock */: + return visitCaseBlock(node); + case 271 /* CaseClause */: + return visitCaseClause(node); + case 272 /* DefaultClause */: + return visitDefaultClause(node); + case 235 /* TryStatement */: + return visitTryStatement(node); + case 274 /* CatchClause */: + return visitCatchClause(node); + case 218 /* Block */: + return visitBlock(node); + case 310 /* MergeDeclarationMarker */: + return visitMergeDeclarationMarker(node); + case 311 /* EndOfDeclarationMarker */: + return visitEndOfDeclarationMarker(node); + default: + return destructuringAndImportCallVisitor(node); + } + } + /** + * Visits the body of a ForStatement to hoist declarations. + * + * @param node The node to visit. + */ + function visitForStatement(node) { + var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; + enclosingBlockScopedContainer = node; + node = ts.updateFor(node, node.initializer && visitForInitializer(node.initializer), ts.visitNode(node.condition, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.incrementor, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement)); + enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; + return node; + } + /** + * Visits the body of a ForInStatement to hoist declarations. + * + * @param node The node to visit. + */ + function visitForInStatement(node) { + var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; + enclosingBlockScopedContainer = node; + node = ts.updateForIn(node, visitForInitializer(node.initializer), ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock)); + enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; + return node; + } + /** + * Visits the body of a ForOfStatement to hoist declarations. + * + * @param node The node to visit. + */ + function visitForOfStatement(node) { + var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; + enclosingBlockScopedContainer = node; + node = ts.updateForOf(node, node.awaitModifier, visitForInitializer(node.initializer), ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock)); + enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; + return node; + } + /** + * Determines whether to hoist the initializer of a ForStatement, ForInStatement, or + * ForOfStatement. + * + * @param node The node to test. + */ + function shouldHoistForInitializer(node) { + return ts.isVariableDeclarationList(node) + && shouldHoistVariableDeclarationList(node); + } + /** + * Visits the initializer of a ForStatement, ForInStatement, or ForOfStatement + * + * @param node The node to visit. + */ + function visitForInitializer(node) { + if (shouldHoistForInitializer(node)) { + var expressions = void 0; + for (var _i = 0, _a = node.declarations; _i < _a.length; _i++) { + var variable = _a[_i]; + expressions = ts.append(expressions, transformInitializedVariable(variable, /*isExportedDeclaration*/ false)); + if (!variable.initializer) { + hoistBindingElement(variable); + } + } + return expressions ? ts.inlineExpressions(expressions) : ts.createOmittedExpression(); + } + else { + return ts.visitEachChild(node, nestedElementVisitor, context); + } + } + /** + * Visits the body of a DoStatement to hoist declarations. + * + * @param node The node to visit. + */ + function visitDoStatement(node) { + return ts.updateDo(node, ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock), ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression)); + } + /** + * Visits the body of a WhileStatement to hoist declarations. + * + * @param node The node to visit. + */ + function visitWhileStatement(node) { + return ts.updateWhile(node, ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock)); + } + /** + * Visits the body of a LabeledStatement to hoist declarations. + * + * @param node The node to visit. + */ + function visitLabeledStatement(node) { + return ts.updateLabel(node, node.label, ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock)); + } + /** + * Visits the body of a WithStatement to hoist declarations. + * + * @param node The node to visit. + */ + function visitWithStatement(node) { + return ts.updateWith(node, ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock)); + } + /** + * Visits the body of a SwitchStatement to hoist declarations. + * + * @param node The node to visit. + */ + function visitSwitchStatement(node) { + return ts.updateSwitch(node, ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.caseBlock, nestedElementVisitor, ts.isCaseBlock)); + } + /** + * Visits the body of a CaseBlock to hoist declarations. + * + * @param node The node to visit. + */ + function visitCaseBlock(node) { + var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; + enclosingBlockScopedContainer = node; + node = ts.updateCaseBlock(node, ts.visitNodes(node.clauses, nestedElementVisitor, ts.isCaseOrDefaultClause)); + enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; + return node; + } + /** + * Visits the body of a CaseClause to hoist declarations. + * + * @param node The node to visit. + */ + function visitCaseClause(node) { + return ts.updateCaseClause(node, ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNodes(node.statements, nestedElementVisitor, ts.isStatement)); + } + /** + * Visits the body of a DefaultClause to hoist declarations. + * + * @param node The node to visit. + */ + function visitDefaultClause(node) { + return ts.visitEachChild(node, nestedElementVisitor, context); + } + /** + * Visits the body of a TryStatement to hoist declarations. + * + * @param node The node to visit. + */ + function visitTryStatement(node) { + return ts.visitEachChild(node, nestedElementVisitor, context); + } + /** + * Visits the body of a CatchClause to hoist declarations. + * + * @param node The node to visit. + */ + function visitCatchClause(node) { + var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; + enclosingBlockScopedContainer = node; + node = ts.updateCatchClause(node, node.variableDeclaration, ts.visitNode(node.block, nestedElementVisitor, ts.isBlock)); + enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; + return node; + } + /** + * Visits the body of a Block to hoist declarations. + * + * @param node The node to visit. + */ + function visitBlock(node) { + var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; + enclosingBlockScopedContainer = node; + node = ts.visitEachChild(node, nestedElementVisitor, context); + enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; + return node; + } + // + // Destructuring Assignment Visitors + // + /** + * Visit nodes to flatten destructuring assignments to exported symbols. + * + * @param node The node to visit. + */ + function destructuringAndImportCallVisitor(node) { + if (node.transformFlags & 1024 /* DestructuringAssignment */ + && node.kind === 204 /* BinaryExpression */) { + return visitDestructuringAssignment(node); + } + else if (ts.isImportCall(node)) { + return visitImportCallExpression(node); + } + else if ((node.transformFlags & 2048 /* ContainsDestructuringAssignment */) || (node.transformFlags & 16777216 /* ContainsDynamicImport */)) { + return ts.visitEachChild(node, destructuringAndImportCallVisitor, context); + } + else { + return node; + } + } + function visitImportCallExpression(node) { + // import("./blah") + // emit as + // System.register([], function (_export, _context) { + // return { + // setters: [], + // execute: () => { + // _context.import('./blah'); + // } + // }; + // }); + return ts.createCall(ts.createPropertyAccess(contextObject, ts.createIdentifier("import")), + /*typeArguments*/ undefined, ts.some(node.arguments) ? [ts.visitNode(node.arguments[0], destructuringAndImportCallVisitor)] : []); + } + /** + * Visits a DestructuringAssignment to flatten destructuring to exported symbols. + * + * @param node The node to visit. + */ + function visitDestructuringAssignment(node) { + if (hasExportedReferenceInDestructuringTarget(node.left)) { + return ts.flattenDestructuringAssignment(node, destructuringAndImportCallVisitor, context, 0 /* All */, + /*needsValue*/ true); + } + return ts.visitEachChild(node, destructuringAndImportCallVisitor, context); + } + /** + * Determines whether the target of a destructuring assigment refers to an exported symbol. + * + * @param node The destructuring target. + */ + function hasExportedReferenceInDestructuringTarget(node) { + if (ts.isAssignmentExpression(node, /*excludeCompoundAssignment*/ true)) { + return hasExportedReferenceInDestructuringTarget(node.left); + } + else if (ts.isSpreadElement(node)) { + return hasExportedReferenceInDestructuringTarget(node.expression); + } + else if (ts.isObjectLiteralExpression(node)) { + return ts.some(node.properties, hasExportedReferenceInDestructuringTarget); + } + else if (ts.isArrayLiteralExpression(node)) { + return ts.some(node.elements, hasExportedReferenceInDestructuringTarget); + } + else if (ts.isShorthandPropertyAssignment(node)) { + return hasExportedReferenceInDestructuringTarget(node.name); + } + else if (ts.isPropertyAssignment(node)) { + return hasExportedReferenceInDestructuringTarget(node.initializer); + } + else if (ts.isIdentifier(node)) { + var container = resolver.getReferencedExportContainer(node); + return container !== undefined && container.kind === 279 /* SourceFile */; + } + else { + return false; + } + } + // + // Modifier Visitors + // + /** + * Visit nodes to elide module-specific modifiers. + * + * @param node The node to visit. + */ + function modifierVisitor(node) { + switch (node.kind) { + case 85 /* ExportKeyword */: + case 80 /* DefaultKeyword */: + return undefined; + } + return node; + } + // + // Emit Notification + // + /** + * Hook for node emit notifications. + * + * @param hint A hint as to the intended usage of the node. + * @param node The node to emit. + * @param emitCallback A callback used to emit the node in the printer. + */ + function onEmitNode(hint, node, emitCallback) { + if (node.kind === 279 /* SourceFile */) { + var id = ts.getOriginalNodeId(node); + currentSourceFile = node; + moduleInfo = moduleInfoMap[id]; + exportFunction = exportFunctionsMap[id]; + noSubstitution = noSubstitutionMap[id]; + if (noSubstitution) { + delete noSubstitutionMap[id]; + } + previousOnEmitNode(hint, node, emitCallback); + currentSourceFile = undefined; + moduleInfo = undefined; + exportFunction = undefined; + noSubstitution = undefined; + } + else { + previousOnEmitNode(hint, node, emitCallback); + } + } + // + // Substitutions + // + /** + * Hooks node substitutions. + * + * @param hint A hint as to the intended usage of the node. + * @param node The node to substitute. + */ + function onSubstituteNode(hint, node) { + node = previousOnSubstituteNode(hint, node); + if (isSubstitutionPrevented(node)) { + return node; + } + if (hint === 1 /* Expression */) { + return substituteExpression(node); + } + else if (hint === 4 /* Unspecified */) { + return substituteUnspecified(node); + } + return node; + } + /** + * Substitute the node, if necessary. + * + * @param node The node to substitute. + */ + function substituteUnspecified(node) { + switch (node.kind) { + case 276 /* ShorthandPropertyAssignment */: + return substituteShorthandPropertyAssignment(node); + } + return node; + } + /** + * Substitution for a ShorthandPropertyAssignment whose name that may contain an imported or exported symbol. + * + * @param node The node to substitute. + */ + function substituteShorthandPropertyAssignment(node) { + var name = node.name; + if (!ts.isGeneratedIdentifier(name) && !ts.isLocalName(name)) { + var importDeclaration = resolver.getReferencedImportDeclaration(name); + if (importDeclaration) { + if (ts.isImportClause(importDeclaration)) { + return ts.setTextRange(ts.createPropertyAssignment(ts.getSynthesizedClone(name), ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent), ts.createIdentifier("default"))), + /*location*/ node); + } + else if (ts.isImportSpecifier(importDeclaration)) { + return ts.setTextRange(ts.createPropertyAssignment(ts.getSynthesizedClone(name), ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent.parent.parent), ts.getSynthesizedClone(importDeclaration.propertyName || importDeclaration.name))), + /*location*/ node); + } + } + } + return node; + } + /** + * Substitute the expression, if necessary. + * + * @param node The node to substitute. + */ + function substituteExpression(node) { + switch (node.kind) { + case 72 /* Identifier */: + return substituteExpressionIdentifier(node); + case 204 /* BinaryExpression */: + return substituteBinaryExpression(node); + case 202 /* PrefixUnaryExpression */: + case 203 /* PostfixUnaryExpression */: + return substituteUnaryExpression(node); + } + return node; + } + /** + * Substitution for an Identifier expression that may contain an imported or exported symbol. + * + * @param node The node to substitute. + */ + function substituteExpressionIdentifier(node) { + if (ts.getEmitFlags(node) & 4096 /* HelperName */) { + var externalHelpersModuleName = ts.getExternalHelpersModuleName(currentSourceFile); + if (externalHelpersModuleName) { + return ts.createPropertyAccess(externalHelpersModuleName, node); + } + return node; + } + // When we see an identifier in an expression position that + // points to an imported symbol, we should substitute a qualified + // reference to the imported symbol if one is needed. + // + // - We do not substitute generated identifiers for any reason. + // - We do not substitute identifiers tagged with the LocalName flag. + if (!ts.isGeneratedIdentifier(node) && !ts.isLocalName(node)) { + var importDeclaration = resolver.getReferencedImportDeclaration(node); + if (importDeclaration) { + if (ts.isImportClause(importDeclaration)) { + return ts.setTextRange(ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent), ts.createIdentifier("default")), + /*location*/ node); + } + else if (ts.isImportSpecifier(importDeclaration)) { + return ts.setTextRange(ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent.parent.parent), ts.getSynthesizedClone(importDeclaration.propertyName || importDeclaration.name)), + /*location*/ node); + } + } + } + return node; + } + /** + * Substitution for a BinaryExpression that may contain an imported or exported symbol. + * + * @param node The node to substitute. + */ + function substituteBinaryExpression(node) { + // When we see an assignment expression whose left-hand side is an exported symbol, + // we should ensure all exports of that symbol are updated with the correct value. + // + // - We do not substitute generated identifiers for any reason. + // - We do not substitute identifiers tagged with the LocalName flag. + // - We do not substitute identifiers that were originally the name of an enum or + // namespace due to how they are transformed in TypeScript. + // - We only substitute identifiers that are exported at the top level. + if (ts.isAssignmentOperator(node.operatorToken.kind) + && ts.isIdentifier(node.left) + && !ts.isGeneratedIdentifier(node.left) + && !ts.isLocalName(node.left) + && !ts.isDeclarationNameOfEnumOrNamespace(node.left)) { + var exportedNames = getExports(node.left); + if (exportedNames) { + // For each additional export of the declaration, apply an export assignment. + var expression = node; + for (var _i = 0, exportedNames_4 = exportedNames; _i < exportedNames_4.length; _i++) { + var exportName = exportedNames_4[_i]; + expression = createExportExpression(exportName, preventSubstitution(expression)); + } + return expression; + } + } + return node; + } + /** + * Substitution for a UnaryExpression that may contain an imported or exported symbol. + * + * @param node The node to substitute. + */ + function substituteUnaryExpression(node) { + // When we see a prefix or postfix increment expression whose operand is an exported + // symbol, we should ensure all exports of that symbol are updated with the correct + // value. + // + // - We do not substitute generated identifiers for any reason. + // - We do not substitute identifiers tagged with the LocalName flag. + // - We do not substitute identifiers that were originally the name of an enum or + // namespace due to how they are transformed in TypeScript. + // - We only substitute identifiers that are exported at the top level. + if ((node.operator === 44 /* PlusPlusToken */ || node.operator === 45 /* MinusMinusToken */) + && ts.isIdentifier(node.operand) + && !ts.isGeneratedIdentifier(node.operand) + && !ts.isLocalName(node.operand) + && !ts.isDeclarationNameOfEnumOrNamespace(node.operand)) { + var exportedNames = getExports(node.operand); + if (exportedNames) { + var expression = node.kind === 203 /* PostfixUnaryExpression */ + ? ts.setTextRange(ts.createPrefix(node.operator, node.operand), node) + : node; + for (var _i = 0, exportedNames_5 = exportedNames; _i < exportedNames_5.length; _i++) { + var exportName = exportedNames_5[_i]; + expression = createExportExpression(exportName, preventSubstitution(expression)); + } + if (node.kind === 203 /* PostfixUnaryExpression */) { + expression = node.operator === 44 /* PlusPlusToken */ + ? ts.createSubtract(preventSubstitution(expression), ts.createLiteral(1)) + : ts.createAdd(preventSubstitution(expression), ts.createLiteral(1)); + } + return expression; + } + } + return node; + } + /** + * Gets the exports of a name. + * + * @param name The name. + */ + function getExports(name) { + var exportedNames; + if (!ts.isGeneratedIdentifier(name)) { + var valueDeclaration = resolver.getReferencedImportDeclaration(name) + || resolver.getReferencedValueDeclaration(name); + if (valueDeclaration) { + var exportContainer = resolver.getReferencedExportContainer(name, /*prefixLocals*/ false); + if (exportContainer && exportContainer.kind === 279 /* SourceFile */) { + exportedNames = ts.append(exportedNames, ts.getDeclarationName(valueDeclaration)); + } + exportedNames = ts.addRange(exportedNames, moduleInfo && moduleInfo.exportedBindings[ts.getOriginalNodeId(valueDeclaration)]); + } + } + return exportedNames; + } + /** + * Prevent substitution of a node for this transformer. + * + * @param node The node which should not be substituted. + */ + function preventSubstitution(node) { + if (noSubstitution === undefined) + noSubstitution = []; + noSubstitution[ts.getNodeId(node)] = true; + return node; + } + /** + * Determines whether a node should not be substituted. + * + * @param node The node to test. + */ + function isSubstitutionPrevented(node) { + return noSubstitution && node.id && noSubstitution[node.id]; + } + } + ts.transformSystemModule = transformSystemModule; +})(ts || (ts = {})); +/*@internal*/ +var ts; +(function (ts) { + function transformES2015Module(context) { + var compilerOptions = context.getCompilerOptions(); + var previousOnEmitNode = context.onEmitNode; + var previousOnSubstituteNode = context.onSubstituteNode; + context.onEmitNode = onEmitNode; + context.onSubstituteNode = onSubstituteNode; + context.enableEmitNotification(279 /* SourceFile */); + context.enableSubstitution(72 /* Identifier */); + var currentSourceFile; + return ts.chainBundle(transformSourceFile); + function transformSourceFile(node) { + if (node.isDeclarationFile) { + return node; + } + if (ts.isExternalModule(node) || compilerOptions.isolatedModules) { + var externalHelpersModuleName = ts.getOrCreateExternalHelpersModuleNameIfNeeded(node, compilerOptions); + if (externalHelpersModuleName) { + var statements = []; + var statementOffset = ts.addPrologue(statements, node.statements); + var tslibImport = ts.createImportDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(externalHelpersModuleName)), ts.createLiteral(ts.externalHelpersModuleNameText)); + ts.addEmitFlags(tslibImport, 67108864 /* NeverApplyImportHelper */); + ts.append(statements, tslibImport); + ts.addRange(statements, ts.visitNodes(node.statements, visitor, ts.isStatement, statementOffset)); + return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements)); + } + else { + return ts.visitEachChild(node, visitor, context); + } + } + return node; + } + function visitor(node) { + switch (node.kind) { + case 248 /* ImportEqualsDeclaration */: + // Elide `import=` as it is not legal with --module ES6 + return undefined; + case 254 /* ExportAssignment */: + return visitExportAssignment(node); + } + return node; + } + function visitExportAssignment(node) { + // Elide `export=` as it is not legal with --module ES6 + return node.isExportEquals ? undefined : node; + } + // + // Emit Notification + // + /** + * Hook for node emit. + * + * @param hint A hint as to the intended usage of the node. + * @param node The node to emit. + * @param emit A callback used to emit the node in the printer. + */ + function onEmitNode(hint, node, emitCallback) { + if (ts.isSourceFile(node)) { + currentSourceFile = node; + previousOnEmitNode(hint, node, emitCallback); + currentSourceFile = undefined; + } + else { + previousOnEmitNode(hint, node, emitCallback); + } + } + // + // Substitutions + // + /** + * Hooks node substitutions. + * + * @param hint A hint as to the intended usage of the node. + * @param node The node to substitute. + */ + function onSubstituteNode(hint, node) { + node = previousOnSubstituteNode(hint, node); + if (ts.isIdentifier(node) && hint === 1 /* Expression */) { + return substituteExpressionIdentifier(node); + } + return node; + } + function substituteExpressionIdentifier(node) { + if (ts.getEmitFlags(node) & 4096 /* HelperName */) { + var externalHelpersModuleName = ts.getExternalHelpersModuleName(currentSourceFile); + if (externalHelpersModuleName) { + return ts.createPropertyAccess(externalHelpersModuleName, node); + } + } + return node; + } + } + ts.transformES2015Module = transformES2015Module; +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + function canProduceDiagnostics(node) { + return ts.isVariableDeclaration(node) || + ts.isPropertyDeclaration(node) || + ts.isPropertySignature(node) || + ts.isBindingElement(node) || + ts.isSetAccessor(node) || + ts.isGetAccessor(node) || + ts.isConstructSignatureDeclaration(node) || + ts.isCallSignatureDeclaration(node) || + ts.isMethodDeclaration(node) || + ts.isMethodSignature(node) || + ts.isFunctionDeclaration(node) || + ts.isParameter(node) || + ts.isTypeParameterDeclaration(node) || + ts.isExpressionWithTypeArguments(node) || + ts.isImportEqualsDeclaration(node) || + ts.isTypeAliasDeclaration(node) || + ts.isConstructorDeclaration(node) || + ts.isIndexSignatureDeclaration(node); + } + ts.canProduceDiagnostics = canProduceDiagnostics; + function createGetSymbolAccessibilityDiagnosticForNodeName(node) { + if (ts.isSetAccessor(node) || ts.isGetAccessor(node)) { + return getAccessorNameVisibilityError; + } + else if (ts.isMethodSignature(node) || ts.isMethodDeclaration(node)) { + return getMethodNameVisibilityError; + } + else { + return createGetSymbolAccessibilityDiagnosticForNode(node); + } + function getAccessorNameVisibilityError(symbolAccessibilityResult) { + var diagnosticMessage = getAccessorNameVisibilityDiagnosticMessage(symbolAccessibilityResult); + return diagnosticMessage !== undefined ? { + diagnosticMessage: diagnosticMessage, + errorNode: node, + typeName: node.name + } : undefined; + } + function getAccessorNameVisibilityDiagnosticMessage(symbolAccessibilityResult) { + if (ts.hasModifier(node, 32 /* Static */)) { + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1; + } + else if (node.parent.kind === 240 /* ClassDeclaration */) { + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_private_name_1; + } + else { + return symbolAccessibilityResult.errorModuleName ? + ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_private_name_1; + } + } + function getMethodNameVisibilityError(symbolAccessibilityResult) { + var diagnosticMessage = getMethodNameVisibilityDiagnosticMessage(symbolAccessibilityResult); + return diagnosticMessage !== undefined ? { + diagnosticMessage: diagnosticMessage, + errorNode: node, + typeName: node.name + } : undefined; + } + function getMethodNameVisibilityDiagnosticMessage(symbolAccessibilityResult) { + if (ts.hasModifier(node, 32 /* Static */)) { + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_private_name_1; + } + else if (node.parent.kind === 240 /* ClassDeclaration */) { + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Public_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Public_method_0_of_exported_class_has_or_is_using_private_name_1; + } + else { + return symbolAccessibilityResult.errorModuleName ? + ts.Diagnostics.Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Method_0_of_exported_interface_has_or_is_using_private_name_1; + } + } + } + ts.createGetSymbolAccessibilityDiagnosticForNodeName = createGetSymbolAccessibilityDiagnosticForNodeName; + function createGetSymbolAccessibilityDiagnosticForNode(node) { + if (ts.isVariableDeclaration(node) || ts.isPropertyDeclaration(node) || ts.isPropertySignature(node) || ts.isBindingElement(node) || ts.isConstructorDeclaration(node)) { + return getVariableDeclarationTypeVisibilityError; + } + else if (ts.isSetAccessor(node) || ts.isGetAccessor(node)) { + return getAccessorDeclarationTypeVisibilityError; + } + else if (ts.isConstructSignatureDeclaration(node) || ts.isCallSignatureDeclaration(node) || ts.isMethodDeclaration(node) || ts.isMethodSignature(node) || ts.isFunctionDeclaration(node) || ts.isIndexSignatureDeclaration(node)) { + return getReturnTypeVisibilityError; + } + else if (ts.isParameter(node)) { + if (ts.isParameterPropertyDeclaration(node) && ts.hasModifier(node.parent, 8 /* Private */)) { + return getVariableDeclarationTypeVisibilityError; + } + return getParameterDeclarationTypeVisibilityError; + } + else if (ts.isTypeParameterDeclaration(node)) { + return getTypeParameterConstraintVisibilityError; + } + else if (ts.isExpressionWithTypeArguments(node)) { + return getHeritageClauseVisibilityError; + } + else if (ts.isImportEqualsDeclaration(node)) { + return getImportEntityNameVisibilityError; + } + else if (ts.isTypeAliasDeclaration(node)) { + return getTypeAliasDeclarationVisibilityError; + } + else { + return ts.Debug.assertNever(node, "Attempted to set a declaration diagnostic context for unhandled node kind: " + ts.SyntaxKind[node.kind]); + } + function getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) { + if (node.kind === 237 /* VariableDeclaration */ || node.kind === 186 /* BindingElement */) { + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Exported_variable_0_has_or_is_using_private_name_1; + } + // This check is to ensure we don't report error on constructor parameter property as that error would be reported during parameter emit + // The only exception here is if the constructor was marked as private. we are not emitting the constructor parameters at all. + else if (node.kind === 154 /* PropertyDeclaration */ || node.kind === 153 /* PropertySignature */ || + (node.kind === 151 /* Parameter */ && ts.hasModifier(node.parent, 8 /* Private */))) { + // TODO(jfreeman): Deal with computed properties in error reporting. + if (ts.hasModifier(node, 32 /* Static */)) { + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1; + } + else if (node.parent.kind === 240 /* ClassDeclaration */ || node.kind === 151 /* Parameter */) { + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_private_name_1; + } + else { + // Interfaces cannot have types that cannot be named + return symbolAccessibilityResult.errorModuleName ? + ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_private_name_1; + } + } + } + function getVariableDeclarationTypeVisibilityError(symbolAccessibilityResult) { + var diagnosticMessage = getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult); + return diagnosticMessage !== undefined ? { + diagnosticMessage: diagnosticMessage, + errorNode: node, + typeName: node.name + } : undefined; + } + function getAccessorDeclarationTypeVisibilityError(symbolAccessibilityResult) { + var diagnosticMessage; + if (node.kind === 159 /* SetAccessor */) { + // Getters can infer the return type from the returned expression, but setters cannot, so the + // "_from_external_module_1_but_cannot_be_named" case cannot occur. + if (ts.hasModifier(node, 32 /* Static */)) { + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + ts.Diagnostics.Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1; + } + else { + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + ts.Diagnostics.Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_private_name_1; + } + } + else { + if (ts.hasModifier(node, 32 /* Static */)) { + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_private_name_1; + } + else { + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Return_type_of_public_getter_0_from_exported_class_has_or_is_using_private_name_1; + } + } + return { + diagnosticMessage: diagnosticMessage, + errorNode: node.name, + typeName: node.name + }; + } + function getReturnTypeVisibilityError(symbolAccessibilityResult) { + var diagnosticMessage; + switch (node.kind) { + case 161 /* ConstructSignature */: + // Interfaces cannot have return types that cannot be named + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + ts.Diagnostics.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : + ts.Diagnostics.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0; + break; + case 160 /* CallSignature */: + // Interfaces cannot have return types that cannot be named + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + ts.Diagnostics.Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : + ts.Diagnostics.Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0; + break; + case 162 /* IndexSignature */: + // Interfaces cannot have return types that cannot be named + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + ts.Diagnostics.Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : + ts.Diagnostics.Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0; + break; + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + if (ts.hasModifier(node, 32 /* Static */)) { + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : + ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1 : + ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0; + } + else if (node.parent.kind === 240 /* ClassDeclaration */) { + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : + ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1 : + ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0; + } + else { + // Interfaces cannot have return types that cannot be named + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + ts.Diagnostics.Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : + ts.Diagnostics.Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0; + } + break; + case 239 /* FunctionDeclaration */: + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : + ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1 : + ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_private_name_0; + break; + default: + return ts.Debug.fail("This is unknown kind for signature: " + node.kind); + } + return { + diagnosticMessage: diagnosticMessage, + errorNode: node.name || node + }; + } + function getParameterDeclarationTypeVisibilityError(symbolAccessibilityResult) { + var diagnosticMessage = getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult); + return diagnosticMessage !== undefined ? { + diagnosticMessage: diagnosticMessage, + errorNode: node, + typeName: node.name + } : undefined; + } + function getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) { + switch (node.parent.kind) { + case 157 /* Constructor */: + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1; + case 161 /* ConstructSignature */: + case 166 /* ConstructorType */: + // Interfaces cannot have parameter types that cannot be named + return symbolAccessibilityResult.errorModuleName ? + ts.Diagnostics.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1; + case 160 /* CallSignature */: + // Interfaces cannot have parameter types that cannot be named + return symbolAccessibilityResult.errorModuleName ? + ts.Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1; + case 162 /* IndexSignature */: + // Interfaces cannot have parameter types that cannot be named + return symbolAccessibilityResult.errorModuleName ? + ts.Diagnostics.Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1; + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + if (ts.hasModifier(node.parent, 32 /* Static */)) { + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1; + } + else if (node.parent.parent.kind === 240 /* ClassDeclaration */) { + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1; + } + else { + // Interfaces cannot have parameter types that cannot be named + return symbolAccessibilityResult.errorModuleName ? + ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1; + } + case 239 /* FunctionDeclaration */: + case 165 /* FunctionType */: + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_private_name_1; + default: + return ts.Debug.fail("Unknown parent for parameter: " + ts.SyntaxKind[node.parent.kind]); + } + } + function getTypeParameterConstraintVisibilityError() { + // Type parameter constraints are named by user so we should always be able to name it + var diagnosticMessage; + switch (node.parent.kind) { + case 240 /* ClassDeclaration */: + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_class_has_or_is_using_private_name_1; + break; + case 241 /* InterfaceDeclaration */: + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1; + break; + case 161 /* ConstructSignature */: + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1; + break; + case 160 /* CallSignature */: + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1; + break; + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + if (ts.hasModifier(node.parent, 32 /* Static */)) { + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1; + } + else if (node.parent.parent.kind === 240 /* ClassDeclaration */) { + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1; + } + else { + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1; + } + break; + case 239 /* FunctionDeclaration */: + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_function_has_or_is_using_private_name_1; + break; + case 242 /* TypeAliasDeclaration */: + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1; + break; + default: + return ts.Debug.fail("This is unknown parent for type parameter: " + node.parent.kind); + } + return { + diagnosticMessage: diagnosticMessage, + errorNode: node, + typeName: node.name + }; + } + function getHeritageClauseVisibilityError() { + var diagnosticMessage; + // Heritage clause is written by user so it can always be named + if (node.parent.parent.kind === 240 /* ClassDeclaration */) { + // Class or Interface implemented/extended is inaccessible + diagnosticMessage = ts.isHeritageClause(node.parent) && node.parent.token === 109 /* ImplementsKeyword */ ? + ts.Diagnostics.Implements_clause_of_exported_class_0_has_or_is_using_private_name_1 : + ts.Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1; + } + else { + // interface is inaccessible + diagnosticMessage = ts.Diagnostics.extends_clause_of_exported_interface_0_has_or_is_using_private_name_1; + } + return { + diagnosticMessage: diagnosticMessage, + errorNode: node, + typeName: ts.getNameOfDeclaration(node.parent.parent) + }; + } + function getImportEntityNameVisibilityError() { + return { + diagnosticMessage: ts.Diagnostics.Import_declaration_0_is_using_private_name_1, + errorNode: node, + typeName: node.name + }; + } + function getTypeAliasDeclarationVisibilityError() { + return { + diagnosticMessage: ts.Diagnostics.Exported_type_alias_0_has_or_is_using_private_name_1, + errorNode: node.type, + typeName: node.name + }; + } + } + ts.createGetSymbolAccessibilityDiagnosticForNode = createGetSymbolAccessibilityDiagnosticForNode; +})(ts || (ts = {})); +/*@internal*/ +var ts; +(function (ts) { + function getDeclarationDiagnostics(host, resolver, file) { + if (file && ts.isSourceFileJS(file)) { + return []; // No declaration diagnostics for js for now + } + var compilerOptions = host.getCompilerOptions(); + var result = ts.transformNodes(resolver, host, compilerOptions, file ? [file] : ts.filter(host.getSourceFiles(), ts.isSourceFileNotJS), [transformDeclarations], /*allowDtsFiles*/ false); + return result.diagnostics; + } + ts.getDeclarationDiagnostics = getDeclarationDiagnostics; + var declarationEmitNodeBuilderFlags = 1024 /* MultilineObjectLiterals */ | + 2048 /* WriteClassExpressionAsTypeLiteral */ | + 4096 /* UseTypeOfFunction */ | + 8 /* UseStructuralFallback */ | + 524288 /* AllowEmptyTuple */ | + 4 /* GenerateNamesForShadowedTypeParams */ | + 1 /* NoTruncation */; + /** + * Transforms a ts file into a .d.ts file + * This process requires type information, which is retrieved through the emit resolver. Because of this, + * in many places this transformer assumes it will be operating on parse tree nodes directly. + * This means that _no transforms should be allowed to occur before this one_. + */ + function transformDeclarations(context) { + var throwDiagnostic = function () { return ts.Debug.fail("Diagnostic emitted without context"); }; + var getSymbolAccessibilityDiagnostic = throwDiagnostic; + var needsDeclare = true; + var isBundledEmit = false; + var resultHasExternalModuleIndicator = false; + var needsScopeFixMarker = false; + var resultHasScopeMarker = false; + var enclosingDeclaration; + var necessaryTypeReferences; + var lateMarkedStatements; + var lateStatementReplacementMap; + var suppressNewDiagnosticContexts; + var exportedModulesFromDeclarationEmit; + var host = context.getEmitHost(); + var symbolTracker = { + trackSymbol: trackSymbol, + reportInaccessibleThisError: reportInaccessibleThisError, + reportInaccessibleUniqueSymbolError: reportInaccessibleUniqueSymbolError, + reportPrivateInBaseOfClassExpression: reportPrivateInBaseOfClassExpression, + reportLikelyUnsafeImportRequiredError: reportLikelyUnsafeImportRequiredError, + moduleResolverHost: host, + trackReferencedAmbientModule: trackReferencedAmbientModule, + trackExternalModuleSymbolOfImportTypeNode: trackExternalModuleSymbolOfImportTypeNode + }; + var errorNameNode; + var currentSourceFile; + var refs; + var libs; + var resolver = context.getEmitResolver(); + var options = context.getCompilerOptions(); + var newLine = ts.getNewLineCharacter(options); + var noResolve = options.noResolve, stripInternal = options.stripInternal; + return transformRoot; + function recordTypeReferenceDirectivesIfNecessary(typeReferenceDirectives) { + if (!typeReferenceDirectives) { + return; + } + necessaryTypeReferences = necessaryTypeReferences || ts.createMap(); + for (var _i = 0, typeReferenceDirectives_2 = typeReferenceDirectives; _i < typeReferenceDirectives_2.length; _i++) { + var ref = typeReferenceDirectives_2[_i]; + necessaryTypeReferences.set(ref, true); + } + } + function trackReferencedAmbientModule(node, symbol) { + // If it is visible via `// `, then we should just use that + var directives = resolver.getTypeReferenceDirectivesForSymbol(symbol, 67108863 /* All */); + if (ts.length(directives)) { + return recordTypeReferenceDirectivesIfNecessary(directives); + } + // Otherwise we should emit a path-based reference + var container = ts.getSourceFileOfNode(node); + refs.set("" + ts.getOriginalNodeId(container), container); + } + function handleSymbolAccessibilityError(symbolAccessibilityResult) { + if (symbolAccessibilityResult.accessibility === 0 /* Accessible */) { + // Add aliases back onto the possible imports list if they're not there so we can try them again with updated visibility info + if (symbolAccessibilityResult && symbolAccessibilityResult.aliasesToMakeVisible) { + if (!lateMarkedStatements) { + lateMarkedStatements = symbolAccessibilityResult.aliasesToMakeVisible; + } + else { + for (var _i = 0, _a = symbolAccessibilityResult.aliasesToMakeVisible; _i < _a.length; _i++) { + var ref = _a[_i]; + ts.pushIfUnique(lateMarkedStatements, ref); + } + } + } + // TODO: Do all these accessibility checks inside/after the first pass in the checker when declarations are enabled, if possible + } + else { + // Report error + var errorInfo = getSymbolAccessibilityDiagnostic(symbolAccessibilityResult); + if (errorInfo) { + if (errorInfo.typeName) { + context.addDiagnostic(ts.createDiagnosticForNode(symbolAccessibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, ts.getTextOfNode(errorInfo.typeName), symbolAccessibilityResult.errorSymbolName, symbolAccessibilityResult.errorModuleName)); + } + else { + context.addDiagnostic(ts.createDiagnosticForNode(symbolAccessibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, symbolAccessibilityResult.errorSymbolName, symbolAccessibilityResult.errorModuleName)); + } + } + } + } + function trackExternalModuleSymbolOfImportTypeNode(symbol) { + if (!isBundledEmit) { + (exportedModulesFromDeclarationEmit || (exportedModulesFromDeclarationEmit = [])).push(symbol); + } + } + function trackSymbol(symbol, enclosingDeclaration, meaning) { + if (symbol.flags & 262144 /* TypeParameter */) + return; + handleSymbolAccessibilityError(resolver.isSymbolAccessible(symbol, enclosingDeclaration, meaning, /*shouldComputeAliasesToMakeVisible*/ true)); + recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForSymbol(symbol, meaning)); + } + function reportPrivateInBaseOfClassExpression(propertyName) { + if (errorNameNode) { + context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.Property_0_of_exported_class_expression_may_not_be_private_or_protected, propertyName)); + } + } + function reportInaccessibleUniqueSymbolError() { + if (errorNameNode) { + context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary, ts.declarationNameToString(errorNameNode), "unique symbol")); + } + } + function reportInaccessibleThisError() { + if (errorNameNode) { + context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary, ts.declarationNameToString(errorNameNode), "this")); + } + } + function reportLikelyUnsafeImportRequiredError(specifier) { + if (errorNameNode) { + context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_annotation_is_necessary, ts.declarationNameToString(errorNameNode), specifier)); + } + } + function transformRoot(node) { + if (node.kind === 279 /* SourceFile */ && (node.isDeclarationFile || ts.isSourceFileJS(node))) { + return node; + } + if (node.kind === 280 /* Bundle */) { + isBundledEmit = true; + refs = ts.createMap(); + libs = ts.createMap(); + var hasNoDefaultLib_1 = false; + var bundle = ts.createBundle(ts.map(node.sourceFiles, function (sourceFile) { + if (sourceFile.isDeclarationFile || ts.isSourceFileJS(sourceFile)) + return undefined; // Omit declaration files from bundle results, too // TODO: GH#18217 + hasNoDefaultLib_1 = hasNoDefaultLib_1 || sourceFile.hasNoDefaultLib; + currentSourceFile = sourceFile; + enclosingDeclaration = sourceFile; + lateMarkedStatements = undefined; + suppressNewDiagnosticContexts = false; + lateStatementReplacementMap = ts.createMap(); + getSymbolAccessibilityDiagnostic = throwDiagnostic; + needsScopeFixMarker = false; + resultHasScopeMarker = false; + collectReferences(sourceFile, refs); + collectLibs(sourceFile, libs); + if (ts.isExternalModule(sourceFile)) { + resultHasExternalModuleIndicator = false; // unused in external module bundle emit (all external modules are within module blocks, therefore are known to be modules) + needsDeclare = false; + var statements_4 = ts.visitNodes(sourceFile.statements, visitDeclarationStatements); + var newFile = ts.updateSourceFileNode(sourceFile, [ts.createModuleDeclaration([], [ts.createModifier(125 /* DeclareKeyword */)], ts.createLiteral(ts.getResolvedExternalModuleName(context.getEmitHost(), sourceFile)), ts.createModuleBlock(ts.setTextRange(ts.createNodeArray(transformAndReplaceLatePaintedStatements(statements_4)), sourceFile.statements)))], /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false, /*libReferences*/ []); + return newFile; + } + needsDeclare = true; + var updated = ts.visitNodes(sourceFile.statements, visitDeclarationStatements); + return ts.updateSourceFileNode(sourceFile, transformAndReplaceLatePaintedStatements(updated), /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false, /*libReferences*/ []); + }), ts.mapDefined(node.prepends, function (prepend) { + if (prepend.kind === 282 /* InputFiles */) { + return ts.createUnparsedSourceFile(prepend.declarationText, prepend.declarationMapPath, prepend.declarationMapText); + } + })); + bundle.syntheticFileReferences = []; + bundle.syntheticTypeReferences = getFileReferencesForUsedTypeReferences(); + bundle.syntheticLibReferences = getLibReferences(); + bundle.hasNoDefaultLib = hasNoDefaultLib_1; + var outputFilePath_1 = ts.getDirectoryPath(ts.normalizeSlashes(ts.getOutputPathsFor(node, host, /*forceDtsPaths*/ true).declarationFilePath)); + var referenceVisitor_1 = mapReferencesIntoArray(bundle.syntheticFileReferences, outputFilePath_1); + refs.forEach(referenceVisitor_1); + return bundle; + } + // Single source file + needsDeclare = true; + needsScopeFixMarker = false; + resultHasScopeMarker = false; + enclosingDeclaration = node; + currentSourceFile = node; + getSymbolAccessibilityDiagnostic = throwDiagnostic; + isBundledEmit = false; + resultHasExternalModuleIndicator = false; + suppressNewDiagnosticContexts = false; + lateMarkedStatements = undefined; + lateStatementReplacementMap = ts.createMap(); + necessaryTypeReferences = undefined; + refs = collectReferences(currentSourceFile, ts.createMap()); + libs = collectLibs(currentSourceFile, ts.createMap()); + var references = []; + var outputFilePath = ts.getDirectoryPath(ts.normalizeSlashes(ts.getOutputPathsFor(node, host, /*forceDtsPaths*/ true).declarationFilePath)); + var referenceVisitor = mapReferencesIntoArray(references, outputFilePath); + var statements = ts.visitNodes(node.statements, visitDeclarationStatements); + var combinedStatements = ts.setTextRange(ts.createNodeArray(transformAndReplaceLatePaintedStatements(statements)), node.statements); + refs.forEach(referenceVisitor); + var emittedImports = ts.filter(combinedStatements, ts.isAnyImportSyntax); + if (ts.isExternalModule(node) && (!resultHasExternalModuleIndicator || (needsScopeFixMarker && !resultHasScopeMarker))) { + combinedStatements = ts.setTextRange(ts.createNodeArray(combinedStatements.concat([ts.createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createNamedExports([]), /*moduleSpecifier*/ undefined)])), combinedStatements); + } + var updated = ts.updateSourceFileNode(node, combinedStatements, /*isDeclarationFile*/ true, references, getFileReferencesForUsedTypeReferences(), node.hasNoDefaultLib, getLibReferences()); + updated.exportedModulesFromDeclarationEmit = exportedModulesFromDeclarationEmit; + return updated; + function getLibReferences() { + return ts.map(ts.arrayFrom(libs.keys()), function (lib) { return ({ fileName: lib, pos: -1, end: -1 }); }); + } + function getFileReferencesForUsedTypeReferences() { + return necessaryTypeReferences ? ts.mapDefined(ts.arrayFrom(necessaryTypeReferences.keys()), getFileReferenceForTypeName) : []; + } + function getFileReferenceForTypeName(typeName) { + // Elide type references for which we have imports + if (emittedImports) { + for (var _i = 0, emittedImports_1 = emittedImports; _i < emittedImports_1.length; _i++) { + var importStatement = emittedImports_1[_i]; + if (ts.isImportEqualsDeclaration(importStatement) && ts.isExternalModuleReference(importStatement.moduleReference)) { + var expr = importStatement.moduleReference.expression; + if (ts.isStringLiteralLike(expr) && expr.text === typeName) { + return undefined; + } + } + else if (ts.isImportDeclaration(importStatement) && ts.isStringLiteral(importStatement.moduleSpecifier) && importStatement.moduleSpecifier.text === typeName) { + return undefined; + } + } + } + return { fileName: typeName, pos: -1, end: -1 }; + } + function mapReferencesIntoArray(references, outputFilePath) { + return function (file) { + var declFileName; + if (file.isDeclarationFile) { // Neither decl files or js should have their refs changed + declFileName = file.fileName; + } + else { + if (isBundledEmit && ts.contains(node.sourceFiles, file)) + return; // Omit references to files which are being merged + var paths = ts.getOutputPathsFor(file, host, /*forceDtsPaths*/ true); + declFileName = paths.declarationFilePath || paths.jsFilePath || file.fileName; + } + if (declFileName) { + var fileName = ts.getRelativePathToDirectoryOrUrl(outputFilePath, declFileName, host.getCurrentDirectory(), host.getCanonicalFileName, + /*isAbsolutePathAnUrl*/ false); + if (ts.startsWith(fileName, "./") && ts.hasExtension(fileName)) { + fileName = fileName.substring(2); + } + // omit references to files from node_modules (npm may disambiguate module + // references when installing this package, making the path is unreliable). + if (ts.startsWith(fileName, "node_modules/") || fileName.indexOf("/node_modules/") !== -1) { + return; + } + references.push({ pos: -1, end: -1, fileName: fileName }); + } + }; + } + } + function collectReferences(sourceFile, ret) { + if (noResolve || ts.isSourceFileJS(sourceFile)) + return ret; + ts.forEach(sourceFile.referencedFiles, function (f) { + var elem = ts.tryResolveScriptReference(host, sourceFile, f); + if (elem) { + ret.set("" + ts.getOriginalNodeId(elem), elem); + } + }); + return ret; + } + function collectLibs(sourceFile, ret) { + ts.forEach(sourceFile.libReferenceDirectives, function (ref) { + var lib = host.getLibFileFromReference(ref); + if (lib) { + ret.set(ref.fileName.toLocaleLowerCase(), true); + } + }); + return ret; + } + function filterBindingPatternInitializers(name) { + if (name.kind === 72 /* Identifier */) { + return name; + } + else { + if (name.kind === 185 /* ArrayBindingPattern */) { + return ts.updateArrayBindingPattern(name, ts.visitNodes(name.elements, visitBindingElement)); + } + else { + return ts.updateObjectBindingPattern(name, ts.visitNodes(name.elements, visitBindingElement)); + } + } + function visitBindingElement(elem) { + if (elem.kind === 210 /* OmittedExpression */) { + return elem; + } + return ts.updateBindingElement(elem, elem.dotDotDotToken, elem.propertyName, filterBindingPatternInitializers(elem.name), shouldPrintWithInitializer(elem) ? elem.initializer : undefined); + } + } + function ensureParameter(p, modifierMask) { + var oldDiag; + if (!suppressNewDiagnosticContexts) { + oldDiag = getSymbolAccessibilityDiagnostic; + getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(p); + } + var newParam = ts.updateParameter(p, + /*decorators*/ undefined, maskModifiers(p, modifierMask), p.dotDotDotToken, filterBindingPatternInitializers(p.name), resolver.isOptionalParameter(p) ? (p.questionToken || ts.createToken(56 /* QuestionToken */)) : undefined, ensureType(p, p.type, /*ignorePrivate*/ true), // Ignore private param props, since this type is going straight back into a param + ensureNoInitializer(p)); + if (!suppressNewDiagnosticContexts) { + getSymbolAccessibilityDiagnostic = oldDiag; + } + return newParam; + } + function shouldPrintWithInitializer(node) { + return canHaveLiteralInitializer(node) && resolver.isLiteralConstDeclaration(ts.getParseTreeNode(node)); // TODO: Make safe + } + function ensureNoInitializer(node) { + if (shouldPrintWithInitializer(node)) { + return resolver.createLiteralConstValue(ts.getParseTreeNode(node), symbolTracker); // TODO: Make safe + } + return undefined; + } + function ensureType(node, type, ignorePrivate) { + if (!ignorePrivate && ts.hasModifier(node, 8 /* Private */)) { + // Private nodes emit no types (except private parameter properties, whose parameter types are actually visible) + return; + } + if (shouldPrintWithInitializer(node)) { + // Literal const declarations will have an initializer ensured rather than a type + return; + } + var shouldUseResolverType = node.kind === 151 /* Parameter */ && + (resolver.isRequiredInitializedParameter(node) || + resolver.isOptionalUninitializedParameterProperty(node)); + if (type && !shouldUseResolverType) { + return ts.visitNode(type, visitDeclarationSubtree); + } + if (!ts.getParseTreeNode(node)) { + return type ? ts.visitNode(type, visitDeclarationSubtree) : ts.createKeywordTypeNode(120 /* AnyKeyword */); + } + if (node.kind === 159 /* SetAccessor */) { + // Set accessors with no associated type node (from it's param or get accessor return) are `any` since they are never contextually typed right now + // (The inferred type here will be void, but the old declaration emitter printed `any`, so this replicates that) + return ts.createKeywordTypeNode(120 /* AnyKeyword */); + } + errorNameNode = node.name; + var oldDiag; + if (!suppressNewDiagnosticContexts) { + oldDiag = getSymbolAccessibilityDiagnostic; + getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(node); + } + if (node.kind === 237 /* VariableDeclaration */ || node.kind === 186 /* BindingElement */) { + return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker)); + } + if (node.kind === 151 /* Parameter */ + || node.kind === 154 /* PropertyDeclaration */ + || node.kind === 153 /* PropertySignature */) { + if (!node.initializer) + return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker, shouldUseResolverType)); + return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker, shouldUseResolverType) || resolver.createTypeOfExpression(node.initializer, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker)); + } + return cleanup(resolver.createReturnTypeOfSignatureDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker)); + function cleanup(returnValue) { + errorNameNode = undefined; + if (!suppressNewDiagnosticContexts) { + getSymbolAccessibilityDiagnostic = oldDiag; + } + return returnValue || ts.createKeywordTypeNode(120 /* AnyKeyword */); + } + } + function isDeclarationAndNotVisible(node) { + node = ts.getParseTreeNode(node); + switch (node.kind) { + case 239 /* FunctionDeclaration */: + case 244 /* ModuleDeclaration */: + case 241 /* InterfaceDeclaration */: + case 240 /* ClassDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 243 /* EnumDeclaration */: + return !resolver.isDeclarationVisible(node); + // The following should be doing their own visibility checks based on filtering their members + case 237 /* VariableDeclaration */: + return !getBindingNameVisible(node); + case 248 /* ImportEqualsDeclaration */: + case 249 /* ImportDeclaration */: + case 255 /* ExportDeclaration */: + case 254 /* ExportAssignment */: + return false; + } + return false; + } + function getBindingNameVisible(elem) { + if (ts.isOmittedExpression(elem)) { + return false; + } + if (ts.isBindingPattern(elem.name)) { + // If any child binding pattern element has been marked visible (usually by collect linked aliases), then this is visible + return ts.some(elem.name.elements, getBindingNameVisible); + } + else { + return resolver.isDeclarationVisible(elem); + } + } + function updateParamsList(node, params, modifierMask) { + if (ts.hasModifier(node, 8 /* Private */)) { + return undefined; // TODO: GH#18217 + } + var newParams = ts.map(params, function (p) { return ensureParameter(p, modifierMask); }); + if (!newParams) { + return undefined; // TODO: GH#18217 + } + return ts.createNodeArray(newParams, params.hasTrailingComma); + } + function ensureTypeParams(node, params) { + return ts.hasModifier(node, 8 /* Private */) ? undefined : ts.visitNodes(params, visitDeclarationSubtree); + } + function isEnclosingDeclaration(node) { + return ts.isSourceFile(node) + || ts.isTypeAliasDeclaration(node) + || ts.isModuleDeclaration(node) + || ts.isClassDeclaration(node) + || ts.isInterfaceDeclaration(node) + || ts.isFunctionLike(node) + || ts.isIndexSignatureDeclaration(node) + || ts.isMappedTypeNode(node); + } + function checkEntityNameVisibility(entityName, enclosingDeclaration) { + var visibilityResult = resolver.isEntityNameVisible(entityName, enclosingDeclaration); + handleSymbolAccessibilityError(visibilityResult); + recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForEntityName(entityName)); + } + function preserveJsDoc(updated, original) { + if (ts.hasJSDocNodes(updated) && ts.hasJSDocNodes(original)) { + updated.jsDoc = original.jsDoc; + } + return ts.setCommentRange(updated, ts.getCommentRange(original)); + } + function rewriteModuleSpecifier(parent, input) { + if (!input) + return undefined; // TODO: GH#18217 + resultHasExternalModuleIndicator = resultHasExternalModuleIndicator || (parent.kind !== 244 /* ModuleDeclaration */ && parent.kind !== 183 /* ImportType */); + if (ts.isStringLiteralLike(input)) { + if (isBundledEmit) { + var newName = ts.getExternalModuleNameFromDeclaration(context.getEmitHost(), resolver, parent); + if (newName) { + return ts.createLiteral(newName); + } + } + else { + var symbol = resolver.getSymbolOfExternalModuleSpecifier(input); + if (symbol) { + (exportedModulesFromDeclarationEmit || (exportedModulesFromDeclarationEmit = [])).push(symbol); + } + } + } + return input; + } + function transformImportEqualsDeclaration(decl) { + if (!resolver.isDeclarationVisible(decl)) + return; + if (decl.moduleReference.kind === 259 /* ExternalModuleReference */) { + // Rewrite external module names if necessary + var specifier = ts.getExternalModuleImportEqualsDeclarationExpression(decl); + return ts.updateImportEqualsDeclaration(decl, + /*decorators*/ undefined, decl.modifiers, decl.name, ts.updateExternalModuleReference(decl.moduleReference, rewriteModuleSpecifier(decl, specifier))); + } + else { + var oldDiag = getSymbolAccessibilityDiagnostic; + getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(decl); + checkEntityNameVisibility(decl.moduleReference, enclosingDeclaration); + getSymbolAccessibilityDiagnostic = oldDiag; + return decl; + } + } + function transformImportDeclaration(decl) { + if (!decl.importClause) { + // import "mod" - possibly needed for side effects? (global interface patches, module augmentations, etc) + return ts.updateImportDeclaration(decl, + /*decorators*/ undefined, decl.modifiers, decl.importClause, rewriteModuleSpecifier(decl, decl.moduleSpecifier)); + } + // The `importClause` visibility corresponds to the default's visibility. + var visibleDefaultBinding = decl.importClause && decl.importClause.name && resolver.isDeclarationVisible(decl.importClause) ? decl.importClause.name : undefined; + if (!decl.importClause.namedBindings) { + // No named bindings (either namespace or list), meaning the import is just default or should be elided + return visibleDefaultBinding && ts.updateImportDeclaration(decl, /*decorators*/ undefined, decl.modifiers, ts.updateImportClause(decl.importClause, visibleDefaultBinding, + /*namedBindings*/ undefined), rewriteModuleSpecifier(decl, decl.moduleSpecifier)); + } + if (decl.importClause.namedBindings.kind === 251 /* NamespaceImport */) { + // Namespace import (optionally with visible default) + var namedBindings = resolver.isDeclarationVisible(decl.importClause.namedBindings) ? decl.importClause.namedBindings : /*namedBindings*/ undefined; + return visibleDefaultBinding || namedBindings ? ts.updateImportDeclaration(decl, /*decorators*/ undefined, decl.modifiers, ts.updateImportClause(decl.importClause, visibleDefaultBinding, namedBindings), rewriteModuleSpecifier(decl, decl.moduleSpecifier)) : undefined; + } + // Named imports (optionally with visible default) + var bindingList = ts.mapDefined(decl.importClause.namedBindings.elements, function (b) { return resolver.isDeclarationVisible(b) ? b : undefined; }); + if ((bindingList && bindingList.length) || visibleDefaultBinding) { + return ts.updateImportDeclaration(decl, + /*decorators*/ undefined, decl.modifiers, ts.updateImportClause(decl.importClause, visibleDefaultBinding, bindingList && bindingList.length ? ts.updateNamedImports(decl.importClause.namedBindings, bindingList) : undefined), rewriteModuleSpecifier(decl, decl.moduleSpecifier)); + } + // Nothing visible + } + function transformAndReplaceLatePaintedStatements(statements) { + // This is a `while` loop because `handleSymbolAccessibilityError` can see additional import aliases marked as visible during + // error handling which must now be included in the output and themselves checked for errors. + // For example: + // ``` + // module A { + // export module Q {} + // import B = Q; + // import C = B; + // export import D = C; + // } + // ``` + // In such a scenario, only Q and D are initially visible, but we don't consider imports as private names - instead we say they if they are referenced they must + // be recorded. So while checking D's visibility we mark C as visible, then we must check C which in turn marks B, completing the chain of + // dependent imports and allowing a valid declaration file output. Today, this dependent alias marking only happens for internal import aliases. + while (ts.length(lateMarkedStatements)) { + var i = lateMarkedStatements.shift(); + if (!ts.isLateVisibilityPaintedStatement(i)) { + return ts.Debug.fail("Late replaced statement was found which is not handled by the declaration transformer!: " + (ts.SyntaxKind ? ts.SyntaxKind[i.kind] : i.kind)); + } + var result = transformTopLevelDeclaration(i, /*privateDeclaration*/ true); + lateStatementReplacementMap.set("" + ts.getOriginalNodeId(i), result); + } + // And lastly, we need to get the final form of all those indetermine import declarations from before and add them to the output list + // (and remove them from the set to examine for outter declarations) + return ts.visitNodes(statements, visitLateVisibilityMarkedStatements); + function visitLateVisibilityMarkedStatements(statement) { + if (ts.isLateVisibilityPaintedStatement(statement)) { + var key = "" + ts.getOriginalNodeId(statement); + if (lateStatementReplacementMap.has(key)) { + var result = lateStatementReplacementMap.get(key); + lateStatementReplacementMap.delete(key); + if (result && ts.isSourceFile(statement.parent)) { + if (ts.isArray(result) ? ts.some(result, needsScopeMarker) : needsScopeMarker(result)) { + // Top-level declarations in .d.ts files are always considered exported even without a modifier unless there's an export assignment or specifier + needsScopeFixMarker = true; + } + if (ts.isArray(result) ? ts.some(result, isExternalModuleIndicator) : isExternalModuleIndicator(result)) { + resultHasExternalModuleIndicator = true; + } + } + return result; + } + } + return statement; + } + } + function isExternalModuleIndicator(result) { + // Exported top-level member indicates moduleness + return ts.isAnyImportOrReExport(result) || ts.isExportAssignment(result) || ts.hasModifier(result, 1 /* Export */); + } + function needsScopeMarker(result) { + return !ts.isAnyImportOrReExport(result) && !ts.isExportAssignment(result) && !ts.hasModifier(result, 1 /* Export */) && !ts.isAmbientModule(result); + } + function visitDeclarationSubtree(input) { + if (shouldStripInternal(input)) + return; + if (ts.isDeclaration(input)) { + if (isDeclarationAndNotVisible(input)) + return; + if (ts.hasDynamicName(input) && !resolver.isLateBound(ts.getParseTreeNode(input))) { + return; + } + } + // Elide implementation signatures from overload sets + if (ts.isFunctionLike(input) && resolver.isImplementationOfOverload(input)) + return; + // Elide semicolon class statements + if (ts.isSemicolonClassElement(input)) + return; + var previousEnclosingDeclaration; + if (isEnclosingDeclaration(input)) { + previousEnclosingDeclaration = enclosingDeclaration; + enclosingDeclaration = input; + } + var oldDiag = getSymbolAccessibilityDiagnostic; + // Emit methods which are private as properties with no type information + if (ts.isMethodDeclaration(input) || ts.isMethodSignature(input)) { + if (ts.hasModifier(input, 8 /* Private */)) { + if (input.symbol && input.symbol.declarations && input.symbol.declarations[0] !== input) + return; // Elide all but the first overload + return cleanup(ts.createProperty(/*decorators*/ undefined, ensureModifiers(input), input.name, /*questionToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined)); + } + } + var canProdiceDiagnostic = ts.canProduceDiagnostics(input); + if (canProdiceDiagnostic && !suppressNewDiagnosticContexts) { + getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(input); + } + if (ts.isTypeQueryNode(input)) { + checkEntityNameVisibility(input.exprName, enclosingDeclaration); + } + var oldWithinObjectLiteralType = suppressNewDiagnosticContexts; + var shouldEnterSuppressNewDiagnosticsContextContext = ((input.kind === 168 /* TypeLiteral */ || input.kind === 181 /* MappedType */) && input.parent.kind !== 242 /* TypeAliasDeclaration */); + if (shouldEnterSuppressNewDiagnosticsContextContext) { + // We stop making new diagnostic contexts within object literal types. Unless it's an object type on the RHS of a type alias declaration. Then we do. + suppressNewDiagnosticContexts = true; + } + if (isProcessedComponent(input)) { + switch (input.kind) { + case 211 /* ExpressionWithTypeArguments */: { + if ((ts.isEntityName(input.expression) || ts.isEntityNameExpression(input.expression))) { + checkEntityNameVisibility(input.expression, enclosingDeclaration); + } + var node = ts.visitEachChild(input, visitDeclarationSubtree, context); + return cleanup(ts.updateExpressionWithTypeArguments(node, ts.parenthesizeTypeParameters(node.typeArguments), node.expression)); + } + case 164 /* TypeReference */: { + checkEntityNameVisibility(input.typeName, enclosingDeclaration); + var node = ts.visitEachChild(input, visitDeclarationSubtree, context); + return cleanup(ts.updateTypeReferenceNode(node, node.typeName, ts.parenthesizeTypeParameters(node.typeArguments))); + } + case 161 /* ConstructSignature */: + return cleanup(ts.updateConstructSignature(input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type))); + case 157 /* Constructor */: { + var isPrivate = ts.hasModifier(input, 8 /* Private */); + // A constructor declaration may not have a type annotation + var ctor = ts.createSignatureDeclaration(157 /* Constructor */, isPrivate ? undefined : ensureTypeParams(input, input.typeParameters), + // TODO: GH#18217 + isPrivate ? undefined : updateParamsList(input, input.parameters, 0 /* None */), + /*type*/ undefined); + ctor.modifiers = ts.createNodeArray(ensureModifiers(input)); + return cleanup(ctor); + } + case 156 /* MethodDeclaration */: { + var sig = ts.createSignatureDeclaration(155 /* MethodSignature */, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type)); + sig.name = input.name; + sig.modifiers = ts.createNodeArray(ensureModifiers(input)); + sig.questionToken = input.questionToken; + return cleanup(sig); + } + case 158 /* GetAccessor */: { + var newNode = ensureAccessor(input); + return cleanup(newNode); + } + case 159 /* SetAccessor */: { + var newNode = ensureAccessor(input); + return cleanup(newNode); + } + case 154 /* PropertyDeclaration */: + return cleanup(ts.updateProperty(input, + /*decorators*/ undefined, ensureModifiers(input), input.name, input.questionToken, !ts.hasModifier(input, 8 /* Private */) ? ensureType(input, input.type) : undefined, ensureNoInitializer(input))); + case 153 /* PropertySignature */: + return cleanup(ts.updatePropertySignature(input, ensureModifiers(input), input.name, input.questionToken, !ts.hasModifier(input, 8 /* Private */) ? ensureType(input, input.type) : undefined, ensureNoInitializer(input))); + case 155 /* MethodSignature */: { + return cleanup(ts.updateMethodSignature(input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type), input.name, input.questionToken)); + } + case 160 /* CallSignature */: { + return cleanup(ts.updateCallSignature(input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type))); + } + case 162 /* IndexSignature */: { + return cleanup(ts.updateIndexSignature(input, + /*decorators*/ undefined, ensureModifiers(input), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree) || ts.createKeywordTypeNode(120 /* AnyKeyword */))); + } + case 237 /* VariableDeclaration */: { + if (ts.isBindingPattern(input.name)) { + return recreateBindingPattern(input.name); + } + shouldEnterSuppressNewDiagnosticsContextContext = true; + suppressNewDiagnosticContexts = true; // Variable declaration types also suppress new diagnostic contexts, provided the contexts wouldn't be made for binding pattern types + return cleanup(ts.updateVariableDeclaration(input, input.name, ensureType(input, input.type), ensureNoInitializer(input))); + } + case 150 /* TypeParameter */: { + if (isPrivateMethodTypeParameter(input) && (input.default || input.constraint)) { + return cleanup(ts.updateTypeParameterDeclaration(input, input.name, /*constraint*/ undefined, /*defaultType*/ undefined)); + } + return cleanup(ts.visitEachChild(input, visitDeclarationSubtree, context)); + } + case 175 /* ConditionalType */: { + // We have to process conditional types in a special way because for visibility purposes we need to push a new enclosingDeclaration + // just for the `infer` types in the true branch. It's an implicit declaration scope that only applies to _part_ of the type. + var checkType = ts.visitNode(input.checkType, visitDeclarationSubtree); + var extendsType = ts.visitNode(input.extendsType, visitDeclarationSubtree); + var oldEnclosingDecl = enclosingDeclaration; + enclosingDeclaration = input.trueType; + var trueType = ts.visitNode(input.trueType, visitDeclarationSubtree); + enclosingDeclaration = oldEnclosingDecl; + var falseType = ts.visitNode(input.falseType, visitDeclarationSubtree); + return cleanup(ts.updateConditionalTypeNode(input, checkType, extendsType, trueType, falseType)); + } + case 165 /* FunctionType */: { + return cleanup(ts.updateFunctionTypeNode(input, ts.visitNodes(input.typeParameters, visitDeclarationSubtree), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree))); + } + case 166 /* ConstructorType */: { + return cleanup(ts.updateConstructorTypeNode(input, ts.visitNodes(input.typeParameters, visitDeclarationSubtree), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree))); + } + case 183 /* ImportType */: { + if (!ts.isLiteralImportTypeNode(input)) + return cleanup(input); + return cleanup(ts.updateImportTypeNode(input, ts.updateLiteralTypeNode(input.argument, rewriteModuleSpecifier(input, input.argument.literal)), input.qualifier, ts.visitNodes(input.typeArguments, visitDeclarationSubtree, ts.isTypeNode), input.isTypeOf)); + } + default: ts.Debug.assertNever(input, "Attempted to process unhandled node kind: " + ts.SyntaxKind[input.kind]); + } + } + return cleanup(ts.visitEachChild(input, visitDeclarationSubtree, context)); + function cleanup(returnValue) { + if (returnValue && canProdiceDiagnostic && ts.hasDynamicName(input)) { + checkName(input); + } + if (isEnclosingDeclaration(input)) { + enclosingDeclaration = previousEnclosingDeclaration; + } + if (canProdiceDiagnostic && !suppressNewDiagnosticContexts) { + getSymbolAccessibilityDiagnostic = oldDiag; + } + if (shouldEnterSuppressNewDiagnosticsContextContext) { + suppressNewDiagnosticContexts = oldWithinObjectLiteralType; + } + if (returnValue === input) { + return returnValue; + } + return returnValue && ts.setOriginalNode(preserveJsDoc(returnValue, input), input); + } + } + function isPrivateMethodTypeParameter(node) { + return node.parent.kind === 156 /* MethodDeclaration */ && ts.hasModifier(node.parent, 8 /* Private */); + } + function visitDeclarationStatements(input) { + if (!isPreservedDeclarationStatement(input)) { + // return undefined for unmatched kinds to omit them from the tree + return; + } + if (shouldStripInternal(input)) + return; + switch (input.kind) { + case 255 /* ExportDeclaration */: { + if (ts.isSourceFile(input.parent)) { + resultHasExternalModuleIndicator = true; + resultHasScopeMarker = true; + } + // Always visible if the parent node isn't dropped for being not visible + // Rewrite external module names if necessary + return ts.updateExportDeclaration(input, /*decorators*/ undefined, input.modifiers, input.exportClause, rewriteModuleSpecifier(input, input.moduleSpecifier)); + } + case 254 /* ExportAssignment */: { + // Always visible if the parent node isn't dropped for being not visible + if (ts.isSourceFile(input.parent)) { + resultHasExternalModuleIndicator = true; + resultHasScopeMarker = true; + } + if (input.expression.kind === 72 /* Identifier */) { + return input; + } + else { + var newId = ts.createOptimisticUniqueName("_default"); + getSymbolAccessibilityDiagnostic = function () { return ({ + diagnosticMessage: ts.Diagnostics.Default_export_of_the_module_has_or_is_using_private_name_0, + errorNode: input + }); }; + var varDecl = ts.createVariableDeclaration(newId, resolver.createTypeOfExpression(input.expression, input, declarationEmitNodeBuilderFlags, symbolTracker), /*initializer*/ undefined); + var statement = ts.createVariableStatement(needsDeclare ? [ts.createModifier(125 /* DeclareKeyword */)] : [], ts.createVariableDeclarationList([varDecl], 2 /* Const */)); + return [statement, ts.updateExportAssignment(input, input.decorators, input.modifiers, newId)]; + } + } + } + var result = transformTopLevelDeclaration(input); + // Don't actually transform yet; just leave as original node - will be elided/swapped by late pass + lateStatementReplacementMap.set("" + ts.getOriginalNodeId(input), result); + return input; + } + function transformTopLevelDeclaration(input, isPrivate) { + if (shouldStripInternal(input)) + return; + switch (input.kind) { + case 248 /* ImportEqualsDeclaration */: { + return transformImportEqualsDeclaration(input); + } + case 249 /* ImportDeclaration */: { + return transformImportDeclaration(input); + } + } + if (ts.isDeclaration(input) && isDeclarationAndNotVisible(input)) + return; + // Elide implementation signatures from overload sets + if (ts.isFunctionLike(input) && resolver.isImplementationOfOverload(input)) + return; + var previousEnclosingDeclaration; + if (isEnclosingDeclaration(input)) { + previousEnclosingDeclaration = enclosingDeclaration; + enclosingDeclaration = input; + } + var canProdiceDiagnostic = ts.canProduceDiagnostics(input); + var oldDiag = getSymbolAccessibilityDiagnostic; + if (canProdiceDiagnostic) { + getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(input); + } + var previousNeedsDeclare = needsDeclare; + switch (input.kind) { + case 242 /* TypeAliasDeclaration */: // Type aliases get `declare`d if need be (for legacy support), but that's all + return cleanup(ts.updateTypeAliasDeclaration(input, + /*decorators*/ undefined, ensureModifiers(input, isPrivate), input.name, ts.visitNodes(input.typeParameters, visitDeclarationSubtree, ts.isTypeParameterDeclaration), ts.visitNode(input.type, visitDeclarationSubtree, ts.isTypeNode))); + case 241 /* InterfaceDeclaration */: { + return cleanup(ts.updateInterfaceDeclaration(input, + /*decorators*/ undefined, ensureModifiers(input, isPrivate), input.name, ensureTypeParams(input, input.typeParameters), transformHeritageClauses(input.heritageClauses), ts.visitNodes(input.members, visitDeclarationSubtree))); + } + case 239 /* FunctionDeclaration */: { + // Generators lose their generator-ness, excepting their return type + var clean = cleanup(ts.updateFunctionDeclaration(input, + /*decorators*/ undefined, ensureModifiers(input, isPrivate), + /*asteriskToken*/ undefined, input.name, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type), + /*body*/ undefined)); + if (clean && resolver.isExpandoFunctionDeclaration(input)) { + var declarations = ts.mapDefined(resolver.getPropertiesOfContainerFunction(input), function (p) { + if (!ts.isPropertyAccessExpression(p.valueDeclaration)) { + return undefined; + } + var type = resolver.createTypeOfDeclaration(p.valueDeclaration, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker); + var varDecl = ts.createVariableDeclaration(ts.unescapeLeadingUnderscores(p.escapedName), type, /*initializer*/ undefined); + return ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([varDecl])); + }); + var namespaceDecl = ts.createModuleDeclaration(/*decorators*/ undefined, ensureModifiers(input, isPrivate), input.name, ts.createModuleBlock(declarations), 16 /* Namespace */); + return [clean, namespaceDecl]; + } + else { + return clean; + } + } + case 244 /* ModuleDeclaration */: { + needsDeclare = false; + var inner = input.body; + if (inner && inner.kind === 245 /* ModuleBlock */) { + var statements = ts.visitNodes(inner.statements, visitDeclarationStatements); + var body = ts.updateModuleBlock(inner, transformAndReplaceLatePaintedStatements(statements)); + needsDeclare = previousNeedsDeclare; + var mods = ensureModifiers(input, isPrivate); + return cleanup(ts.updateModuleDeclaration(input, + /*decorators*/ undefined, mods, ts.isExternalModuleAugmentation(input) ? rewriteModuleSpecifier(input, input.name) : input.name, body)); + } + else { + needsDeclare = previousNeedsDeclare; + var mods = ensureModifiers(input, isPrivate); + needsDeclare = false; + ts.visitNode(inner, visitDeclarationStatements); + // eagerly transform nested namespaces (the nesting doesn't need any elision or painting done) + var id = "" + ts.getOriginalNodeId(inner); // TODO: GH#18217 + var body = lateStatementReplacementMap.get(id); + lateStatementReplacementMap.delete(id); + return cleanup(ts.updateModuleDeclaration(input, + /*decorators*/ undefined, mods, input.name, body)); + } + } + case 240 /* ClassDeclaration */: { + var modifiers = ts.createNodeArray(ensureModifiers(input, isPrivate)); + var typeParameters = ensureTypeParams(input, input.typeParameters); + var ctor = ts.getFirstConstructorWithBody(input); + var parameterProperties = void 0; + if (ctor) { + var oldDiag_1 = getSymbolAccessibilityDiagnostic; + parameterProperties = ts.compact(ts.flatMap(ctor.parameters, function (param) { + if (!ts.hasModifier(param, 92 /* ParameterPropertyModifier */)) + return; + getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(param); + if (param.name.kind === 72 /* Identifier */) { + return preserveJsDoc(ts.createProperty( + /*decorators*/ undefined, ensureModifiers(param), param.name, param.questionToken, ensureType(param, param.type), ensureNoInitializer(param)), param); + } + else { + // Pattern - this is currently an error, but we emit declarations for it somewhat correctly + return walkBindingPattern(param.name); + } + function walkBindingPattern(pattern) { + var elems; + for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) { + var elem = _a[_i]; + if (ts.isOmittedExpression(elem)) + continue; + if (ts.isBindingPattern(elem.name)) { + elems = ts.concatenate(elems, walkBindingPattern(elem.name)); + } + elems = elems || []; + elems.push(ts.createProperty( + /*decorators*/ undefined, ensureModifiers(param), elem.name, + /*questionToken*/ undefined, ensureType(elem, /*type*/ undefined), + /*initializer*/ undefined)); + } + return elems; + } + })); + getSymbolAccessibilityDiagnostic = oldDiag_1; + } + var members = ts.createNodeArray(ts.concatenate(parameterProperties, ts.visitNodes(input.members, visitDeclarationSubtree))); + var extendsClause_1 = ts.getEffectiveBaseTypeNode(input); + if (extendsClause_1 && !ts.isEntityNameExpression(extendsClause_1.expression) && extendsClause_1.expression.kind !== 96 /* NullKeyword */) { + // We must add a temporary declaration for the extends clause expression + var newId_1 = ts.createOptimisticUniqueName(ts.unescapeLeadingUnderscores(input.name.escapedText) + "_base"); // TODO: GH#18217 + getSymbolAccessibilityDiagnostic = function () { return ({ + diagnosticMessage: ts.Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1, + errorNode: extendsClause_1, + typeName: input.name + }); }; + var varDecl = ts.createVariableDeclaration(newId_1, resolver.createTypeOfExpression(extendsClause_1.expression, input, declarationEmitNodeBuilderFlags, symbolTracker), /*initializer*/ undefined); + var statement = ts.createVariableStatement(needsDeclare ? [ts.createModifier(125 /* DeclareKeyword */)] : [], ts.createVariableDeclarationList([varDecl], 2 /* Const */)); + var heritageClauses = ts.createNodeArray(ts.map(input.heritageClauses, function (clause) { + if (clause.token === 86 /* ExtendsKeyword */) { + var oldDiag_2 = getSymbolAccessibilityDiagnostic; + getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(clause.types[0]); + var newClause = ts.updateHeritageClause(clause, ts.map(clause.types, function (t) { return ts.updateExpressionWithTypeArguments(t, ts.visitNodes(t.typeArguments, visitDeclarationSubtree), newId_1); })); + getSymbolAccessibilityDiagnostic = oldDiag_2; + return newClause; + } + return ts.updateHeritageClause(clause, ts.visitNodes(ts.createNodeArray(ts.filter(clause.types, function (t) { return ts.isEntityNameExpression(t.expression) || t.expression.kind === 96 /* NullKeyword */; })), visitDeclarationSubtree)); + })); + return [statement, cleanup(ts.updateClassDeclaration(input, + /*decorators*/ undefined, modifiers, input.name, typeParameters, heritageClauses, members))]; // TODO: GH#18217 + } + else { + var heritageClauses = transformHeritageClauses(input.heritageClauses); + return cleanup(ts.updateClassDeclaration(input, + /*decorators*/ undefined, modifiers, input.name, typeParameters, heritageClauses, members)); + } + } + case 219 /* VariableStatement */: { + return cleanup(transformVariableStatement(input, isPrivate)); + } + case 243 /* EnumDeclaration */: { + return cleanup(ts.updateEnumDeclaration(input, /*decorators*/ undefined, ts.createNodeArray(ensureModifiers(input, isPrivate)), input.name, ts.createNodeArray(ts.mapDefined(input.members, function (m) { + if (shouldStripInternal(m)) + return; + // Rewrite enum values to their constants, if available + var constValue = resolver.getConstantValue(m); + return preserveJsDoc(ts.updateEnumMember(m, m.name, constValue !== undefined ? ts.createLiteral(constValue) : undefined), m); + })))); + } + } + // Anything left unhandled is an error, so this should be unreachable + return ts.Debug.assertNever(input, "Unhandled top-level node in declaration emit: " + ts.SyntaxKind[input.kind]); + function cleanup(node) { + if (isEnclosingDeclaration(input)) { + enclosingDeclaration = previousEnclosingDeclaration; + } + if (canProdiceDiagnostic) { + getSymbolAccessibilityDiagnostic = oldDiag; + } + if (input.kind === 244 /* ModuleDeclaration */) { + needsDeclare = previousNeedsDeclare; + } + if (node === input) { + return node; + } + return node && ts.setOriginalNode(preserveJsDoc(node, input), input); + } + } + function transformVariableStatement(input, privateDeclaration) { + if (!ts.forEach(input.declarationList.declarations, getBindingNameVisible)) + return; + var nodes = ts.visitNodes(input.declarationList.declarations, visitDeclarationSubtree); + if (!ts.length(nodes)) + return; + return ts.updateVariableStatement(input, ts.createNodeArray(ensureModifiers(input, privateDeclaration)), ts.updateVariableDeclarationList(input.declarationList, nodes)); + } + function recreateBindingPattern(d) { + return ts.flatten(ts.mapDefined(d.elements, function (e) { return recreateBindingElement(e); })); + } + function recreateBindingElement(e) { + if (e.kind === 210 /* OmittedExpression */) { + return; + } + if (e.name) { + if (!getBindingNameVisible(e)) + return; + if (ts.isBindingPattern(e.name)) { + return recreateBindingPattern(e.name); + } + else { + return ts.createVariableDeclaration(e.name, ensureType(e, /*type*/ undefined), /*initializer*/ undefined); + } + } + } + function checkName(node) { + var oldDiag; + if (!suppressNewDiagnosticContexts) { + oldDiag = getSymbolAccessibilityDiagnostic; + getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNodeName(node); + } + errorNameNode = node.name; + ts.Debug.assert(resolver.isLateBound(ts.getParseTreeNode(node))); // Should only be called with dynamic names + var decl = node; + var entityName = decl.name.expression; + checkEntityNameVisibility(entityName, enclosingDeclaration); + if (!suppressNewDiagnosticContexts) { + getSymbolAccessibilityDiagnostic = oldDiag; + } + errorNameNode = undefined; + } + function hasInternalAnnotation(range) { + var comment = currentSourceFile.text.substring(range.pos, range.end); + return ts.stringContains(comment, "@internal"); + } + function shouldStripInternal(node) { + if (stripInternal && node) { + var leadingCommentRanges = ts.getLeadingCommentRangesOfNode(ts.getParseTreeNode(node), currentSourceFile); + if (ts.forEach(leadingCommentRanges, hasInternalAnnotation)) { + return true; + } + } + return false; + } + function isScopeMarker(node) { + return ts.isExportAssignment(node) || ts.isExportDeclaration(node); + } + function hasScopeMarker(node) { + if (ts.isModuleBlock(node)) { + return ts.some(node.statements, isScopeMarker); + } + return false; + } + function ensureModifiers(node, privateDeclaration) { + var currentFlags = ts.getModifierFlags(node); + var newFlags = ensureModifierFlags(node, privateDeclaration); + if (currentFlags === newFlags) { + return node.modifiers; + } + return ts.createModifiersFromModifierFlags(newFlags); + } + function ensureModifierFlags(node, privateDeclaration) { + var mask = 3071 /* All */ ^ (4 /* Public */ | 256 /* Async */); // No async modifiers in declaration files + var additions = (needsDeclare && !isAlwaysType(node)) ? 2 /* Ambient */ : 0 /* None */; + var parentIsFile = node.parent.kind === 279 /* SourceFile */; + if (!parentIsFile || (isBundledEmit && parentIsFile && ts.isExternalModule(node.parent))) { + mask ^= ((privateDeclaration || (isBundledEmit && parentIsFile) || hasScopeMarker(node.parent) ? 0 : 1 /* Export */) | 2 /* Ambient */); + additions = 0 /* None */; + } + return maskModifierFlags(node, mask, additions); + } + function ensureAccessor(node) { + var accessors = resolver.getAllAccessorDeclarations(node); + if (node.kind !== accessors.firstAccessor.kind) { + return; + } + var accessorType = getTypeAnnotationFromAccessor(node); + if (!accessorType && accessors.secondAccessor) { + accessorType = getTypeAnnotationFromAccessor(accessors.secondAccessor); + // If we end up pulling the type from the second accessor, we also need to change the diagnostic context to get the expected error message + getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(accessors.secondAccessor); + } + var prop = ts.createProperty(/*decorators*/ undefined, maskModifiers(node, /*mask*/ undefined, (!accessors.setAccessor) ? 64 /* Readonly */ : 0 /* None */), node.name, node.questionToken, ensureType(node, accessorType), /*initializer*/ undefined); + var leadingsSyntheticCommentRanges = accessors.secondAccessor && ts.getLeadingCommentRangesOfNode(accessors.secondAccessor, currentSourceFile); + if (leadingsSyntheticCommentRanges) { + var _loop_9 = function (range) { + if (range.kind === 3 /* MultiLineCommentTrivia */) { + var text = currentSourceFile.text.slice(range.pos + 2, range.end - 2); + var lines = text.split(/\r\n?|\n/g); + if (lines.length > 1) { + var lastLines = lines.slice(1); + var indentation_1 = ts.guessIndentation(lastLines); + text = [lines[0]].concat(ts.map(lastLines, function (l) { return l.slice(indentation_1); })).join(newLine); + } + ts.addSyntheticLeadingComment(prop, range.kind, text, range.hasTrailingNewLine); + } + }; + for (var _i = 0, leadingsSyntheticCommentRanges_1 = leadingsSyntheticCommentRanges; _i < leadingsSyntheticCommentRanges_1.length; _i++) { + var range = leadingsSyntheticCommentRanges_1[_i]; + _loop_9(range); + } + } + return prop; + } + function transformHeritageClauses(nodes) { + return ts.createNodeArray(ts.filter(ts.map(nodes, function (clause) { return ts.updateHeritageClause(clause, ts.visitNodes(ts.createNodeArray(ts.filter(clause.types, function (t) { + return ts.isEntityNameExpression(t.expression) || (clause.token === 86 /* ExtendsKeyword */ && t.expression.kind === 96 /* NullKeyword */); + })), visitDeclarationSubtree)); }), function (clause) { return clause.types && !!clause.types.length; })); + } + } + ts.transformDeclarations = transformDeclarations; + function isAlwaysType(node) { + if (node.kind === 241 /* InterfaceDeclaration */) { + return true; + } + return false; + } + // Elide "public" modifier, as it is the default + function maskModifiers(node, modifierMask, modifierAdditions) { + return ts.createModifiersFromModifierFlags(maskModifierFlags(node, modifierMask, modifierAdditions)); + } + function maskModifierFlags(node, modifierMask, modifierAdditions) { + if (modifierMask === void 0) { modifierMask = 3071 /* All */ ^ 4 /* Public */; } + if (modifierAdditions === void 0) { modifierAdditions = 0 /* None */; } + var flags = (ts.getModifierFlags(node) & modifierMask) | modifierAdditions; + if (flags & 512 /* Default */ && !(flags & 1 /* Export */)) { + // A non-exported default is a nonsequitor - we usually try to remove all export modifiers + // from statements in ambient declarations; but a default export must retain its export modifier to be syntactically valid + flags ^= 1 /* Export */; + } + if (flags & 512 /* Default */ && flags & 2 /* Ambient */) { + flags ^= 2 /* Ambient */; // `declare` is never required alongside `default` (and would be an error if printed) + } + return flags; + } + function getTypeAnnotationFromAccessor(accessor) { + if (accessor) { + return accessor.kind === 158 /* GetAccessor */ + ? accessor.type // Getter - return type + : accessor.parameters.length > 0 + ? accessor.parameters[0].type // Setter parameter type + : undefined; + } + } + function canHaveLiteralInitializer(node) { + switch (node.kind) { + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + return !ts.hasModifier(node, 8 /* Private */); + case 151 /* Parameter */: + case 237 /* VariableDeclaration */: + return true; + } + return false; + } + function isPreservedDeclarationStatement(node) { + switch (node.kind) { + case 239 /* FunctionDeclaration */: + case 244 /* ModuleDeclaration */: + case 248 /* ImportEqualsDeclaration */: + case 241 /* InterfaceDeclaration */: + case 240 /* ClassDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 243 /* EnumDeclaration */: + case 219 /* VariableStatement */: + case 249 /* ImportDeclaration */: + case 255 /* ExportDeclaration */: + case 254 /* ExportAssignment */: + return true; + } + return false; + } + function isProcessedComponent(node) { + switch (node.kind) { + case 161 /* ConstructSignature */: + case 157 /* Constructor */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 155 /* MethodSignature */: + case 160 /* CallSignature */: + case 162 /* IndexSignature */: + case 237 /* VariableDeclaration */: + case 150 /* TypeParameter */: + case 211 /* ExpressionWithTypeArguments */: + case 164 /* TypeReference */: + case 175 /* ConditionalType */: + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + case 183 /* ImportType */: + return true; + } + return false; + } +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + function getModuleTransformer(moduleKind) { + switch (moduleKind) { + case ts.ModuleKind.ESNext: + case ts.ModuleKind.ES2015: + return ts.transformES2015Module; + case ts.ModuleKind.System: + return ts.transformSystemModule; + default: + return ts.transformModule; + } + } + var TransformationState; + (function (TransformationState) { + TransformationState[TransformationState["Uninitialized"] = 0] = "Uninitialized"; + TransformationState[TransformationState["Initialized"] = 1] = "Initialized"; + TransformationState[TransformationState["Completed"] = 2] = "Completed"; + TransformationState[TransformationState["Disposed"] = 3] = "Disposed"; + })(TransformationState || (TransformationState = {})); + var SyntaxKindFeatureFlags; + (function (SyntaxKindFeatureFlags) { + SyntaxKindFeatureFlags[SyntaxKindFeatureFlags["Substitution"] = 1] = "Substitution"; + SyntaxKindFeatureFlags[SyntaxKindFeatureFlags["EmitNotifications"] = 2] = "EmitNotifications"; + })(SyntaxKindFeatureFlags || (SyntaxKindFeatureFlags = {})); + function getTransformers(compilerOptions, customTransformers) { + var jsx = compilerOptions.jsx; + var languageVersion = ts.getEmitScriptTarget(compilerOptions); + var moduleKind = ts.getEmitModuleKind(compilerOptions); + var transformers = []; + ts.addRange(transformers, customTransformers && customTransformers.before); + transformers.push(ts.transformTypeScript); + if (jsx === 2 /* React */) { + transformers.push(ts.transformJsx); + } + if (languageVersion < 6 /* ESNext */) { + transformers.push(ts.transformESNext); + } + if (languageVersion < 4 /* ES2017 */) { + transformers.push(ts.transformES2017); + } + if (languageVersion < 3 /* ES2016 */) { + transformers.push(ts.transformES2016); + } + if (languageVersion < 2 /* ES2015 */) { + transformers.push(ts.transformES2015); + transformers.push(ts.transformGenerators); + } + transformers.push(getModuleTransformer(moduleKind)); + // The ES5 transformer is last so that it can substitute expressions like `exports.default` + // for ES3. + if (languageVersion < 1 /* ES5 */) { + transformers.push(ts.transformES5); + } + ts.addRange(transformers, customTransformers && customTransformers.after); + return transformers; + } + ts.getTransformers = getTransformers; + function noEmitSubstitution(_hint, node) { + return node; + } + ts.noEmitSubstitution = noEmitSubstitution; + function noEmitNotification(hint, node, callback) { + callback(hint, node); + } + ts.noEmitNotification = noEmitNotification; + /** + * Transforms an array of SourceFiles by passing them through each transformer. + * + * @param resolver The emit resolver provided by the checker. + * @param host The emit host object used to interact with the file system. + * @param options Compiler options to surface in the `TransformationContext`. + * @param nodes An array of nodes to transform. + * @param transforms An array of `TransformerFactory` callbacks. + * @param allowDtsFiles A value indicating whether to allow the transformation of .d.ts files. + */ + function transformNodes(resolver, host, options, nodes, transformers, allowDtsFiles) { + var enabledSyntaxKindFeatures = new Array(312 /* Count */); + var lexicalEnvironmentVariableDeclarations; + var lexicalEnvironmentFunctionDeclarations; + var lexicalEnvironmentVariableDeclarationsStack = []; + var lexicalEnvironmentFunctionDeclarationsStack = []; + var lexicalEnvironmentStackOffset = 0; + var lexicalEnvironmentSuspended = false; + var emitHelpers; + var onSubstituteNode = noEmitSubstitution; + var onEmitNode = noEmitNotification; + var state = 0 /* Uninitialized */; + var diagnostics = []; + // The transformation context is provided to each transformer as part of transformer + // initialization. + var context = { + getCompilerOptions: function () { return options; }, + getEmitResolver: function () { return resolver; }, + getEmitHost: function () { return host; }, + startLexicalEnvironment: startLexicalEnvironment, + suspendLexicalEnvironment: suspendLexicalEnvironment, + resumeLexicalEnvironment: resumeLexicalEnvironment, + endLexicalEnvironment: endLexicalEnvironment, + hoistVariableDeclaration: hoistVariableDeclaration, + hoistFunctionDeclaration: hoistFunctionDeclaration, + requestEmitHelper: requestEmitHelper, + readEmitHelpers: readEmitHelpers, + enableSubstitution: enableSubstitution, + enableEmitNotification: enableEmitNotification, + isSubstitutionEnabled: isSubstitutionEnabled, + isEmitNotificationEnabled: isEmitNotificationEnabled, + get onSubstituteNode() { return onSubstituteNode; }, + set onSubstituteNode(value) { + ts.Debug.assert(state < 1 /* Initialized */, "Cannot modify transformation hooks after initialization has completed."); + ts.Debug.assert(value !== undefined, "Value must not be 'undefined'"); + onSubstituteNode = value; + }, + get onEmitNode() { return onEmitNode; }, + set onEmitNode(value) { + ts.Debug.assert(state < 1 /* Initialized */, "Cannot modify transformation hooks after initialization has completed."); + ts.Debug.assert(value !== undefined, "Value must not be 'undefined'"); + onEmitNode = value; + }, + addDiagnostic: function (diag) { + diagnostics.push(diag); + } + }; + // Ensure the parse tree is clean before applying transformations + for (var _i = 0, nodes_4 = nodes; _i < nodes_4.length; _i++) { + var node = nodes_4[_i]; + ts.disposeEmitNodes(ts.getSourceFileOfNode(ts.getParseTreeNode(node))); + } + ts.performance.mark("beforeTransform"); + // Chain together and initialize each transformer. + var transformation = ts.chain.apply(void 0, transformers)(context); + // prevent modification of transformation hooks. + state = 1 /* Initialized */; + // Transform each node. + var transformed = ts.map(nodes, allowDtsFiles ? transformation : transformRoot); + // prevent modification of the lexical environment. + state = 2 /* Completed */; + ts.performance.mark("afterTransform"); + ts.performance.measure("transformTime", "beforeTransform", "afterTransform"); + return { + transformed: transformed, + substituteNode: substituteNode, + emitNodeWithNotification: emitNodeWithNotification, + dispose: dispose, + diagnostics: diagnostics + }; + function transformRoot(node) { + return node && (!ts.isSourceFile(node) || !node.isDeclarationFile) ? transformation(node) : node; + } + /** + * Enables expression substitutions in the pretty printer for the provided SyntaxKind. + */ + function enableSubstitution(kind) { + ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the transformation context after transformation has completed."); + enabledSyntaxKindFeatures[kind] |= 1 /* Substitution */; + } + /** + * Determines whether expression substitutions are enabled for the provided node. + */ + function isSubstitutionEnabled(node) { + return (enabledSyntaxKindFeatures[node.kind] & 1 /* Substitution */) !== 0 + && (ts.getEmitFlags(node) & 4 /* NoSubstitution */) === 0; + } + /** + * Emits a node with possible substitution. + * + * @param hint A hint as to the intended usage of the node. + * @param node The node to emit. + * @param emitCallback The callback used to emit the node or its substitute. + */ + function substituteNode(hint, node) { + ts.Debug.assert(state < 3 /* Disposed */, "Cannot substitute a node after the result is disposed."); + return node && isSubstitutionEnabled(node) && onSubstituteNode(hint, node) || node; + } + /** + * Enables before/after emit notifications in the pretty printer for the provided SyntaxKind. + */ + function enableEmitNotification(kind) { + ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the transformation context after transformation has completed."); + enabledSyntaxKindFeatures[kind] |= 2 /* EmitNotifications */; + } + /** + * Determines whether before/after emit notifications should be raised in the pretty + * printer when it emits a node. + */ + function isEmitNotificationEnabled(node) { + return (enabledSyntaxKindFeatures[node.kind] & 2 /* EmitNotifications */) !== 0 + || (ts.getEmitFlags(node) & 2 /* AdviseOnEmitNode */) !== 0; + } + /** + * Emits a node with possible emit notification. + * + * @param hint A hint as to the intended usage of the node. + * @param node The node to emit. + * @param emitCallback The callback used to emit the node. + */ + function emitNodeWithNotification(hint, node, emitCallback) { + ts.Debug.assert(state < 3 /* Disposed */, "Cannot invoke TransformationResult callbacks after the result is disposed."); + if (node) { + if (isEmitNotificationEnabled(node)) { + onEmitNode(hint, node, emitCallback); + } + else { + emitCallback(hint, node); + } + } + } + /** + * Records a hoisted variable declaration for the provided name within a lexical environment. + */ + function hoistVariableDeclaration(name) { + ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization."); + ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed."); + var decl = ts.setEmitFlags(ts.createVariableDeclaration(name), 64 /* NoNestedSourceMaps */); + if (!lexicalEnvironmentVariableDeclarations) { + lexicalEnvironmentVariableDeclarations = [decl]; + } + else { + lexicalEnvironmentVariableDeclarations.push(decl); + } + } + /** + * Records a hoisted function declaration within a lexical environment. + */ + function hoistFunctionDeclaration(func) { + ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization."); + ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed."); + if (!lexicalEnvironmentFunctionDeclarations) { + lexicalEnvironmentFunctionDeclarations = [func]; + } + else { + lexicalEnvironmentFunctionDeclarations.push(func); + } + } + /** + * Starts a new lexical environment. Any existing hoisted variable or function declarations + * are pushed onto a stack, and the related storage variables are reset. + */ + function startLexicalEnvironment() { + ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization."); + ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed."); + ts.Debug.assert(!lexicalEnvironmentSuspended, "Lexical environment is suspended."); + // Save the current lexical environment. Rather than resizing the array we adjust the + // stack size variable. This allows us to reuse existing array slots we've + // already allocated between transformations to avoid allocation and GC overhead during + // transformation. + lexicalEnvironmentVariableDeclarationsStack[lexicalEnvironmentStackOffset] = lexicalEnvironmentVariableDeclarations; + lexicalEnvironmentFunctionDeclarationsStack[lexicalEnvironmentStackOffset] = lexicalEnvironmentFunctionDeclarations; + lexicalEnvironmentStackOffset++; + lexicalEnvironmentVariableDeclarations = undefined; + lexicalEnvironmentFunctionDeclarations = undefined; + } + /** Suspends the current lexical environment, usually after visiting a parameter list. */ + function suspendLexicalEnvironment() { + ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization."); + ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed."); + ts.Debug.assert(!lexicalEnvironmentSuspended, "Lexical environment is already suspended."); + lexicalEnvironmentSuspended = true; + } + /** Resumes a suspended lexical environment, usually before visiting a function body. */ + function resumeLexicalEnvironment() { + ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization."); + ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed."); + ts.Debug.assert(lexicalEnvironmentSuspended, "Lexical environment is not suspended."); + lexicalEnvironmentSuspended = false; + } + /** + * Ends a lexical environment. The previous set of hoisted declarations are restored and + * any hoisted declarations added in this environment are returned. + */ + function endLexicalEnvironment() { + ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization."); + ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed."); + ts.Debug.assert(!lexicalEnvironmentSuspended, "Lexical environment is suspended."); + var statements; + if (lexicalEnvironmentVariableDeclarations || lexicalEnvironmentFunctionDeclarations) { + if (lexicalEnvironmentFunctionDeclarations) { + statements = lexicalEnvironmentFunctionDeclarations.slice(); + } + if (lexicalEnvironmentVariableDeclarations) { + var statement = ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList(lexicalEnvironmentVariableDeclarations)); + if (!statements) { + statements = [statement]; + } + else { + statements.push(statement); + } + } + } + // Restore the previous lexical environment. + lexicalEnvironmentStackOffset--; + lexicalEnvironmentVariableDeclarations = lexicalEnvironmentVariableDeclarationsStack[lexicalEnvironmentStackOffset]; + lexicalEnvironmentFunctionDeclarations = lexicalEnvironmentFunctionDeclarationsStack[lexicalEnvironmentStackOffset]; + if (lexicalEnvironmentStackOffset === 0) { + lexicalEnvironmentVariableDeclarationsStack = []; + lexicalEnvironmentFunctionDeclarationsStack = []; + } + return statements; + } + function requestEmitHelper(helper) { + ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the transformation context during initialization."); + ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the transformation context after transformation has completed."); + ts.Debug.assert(!helper.scoped, "Cannot request a scoped emit helper."); + emitHelpers = ts.append(emitHelpers, helper); + } + function readEmitHelpers() { + ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the transformation context during initialization."); + ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the transformation context after transformation has completed."); + var helpers = emitHelpers; + emitHelpers = undefined; + return helpers; + } + function dispose() { + if (state < 3 /* Disposed */) { + // Clean up emit nodes on parse tree + for (var _i = 0, nodes_5 = nodes; _i < nodes_5.length; _i++) { + var node = nodes_5[_i]; + ts.disposeEmitNodes(ts.getSourceFileOfNode(ts.getParseTreeNode(node))); + } + // Release references to external entries for GC purposes. + lexicalEnvironmentVariableDeclarations = undefined; + lexicalEnvironmentVariableDeclarationsStack = undefined; + lexicalEnvironmentFunctionDeclarations = undefined; + lexicalEnvironmentFunctionDeclarationsStack = undefined; + onSubstituteNode = undefined; + onEmitNode = undefined; + emitHelpers = undefined; + // Prevent further use of the transformation result. + state = 3 /* Disposed */; + } + } + } + ts.transformNodes = transformNodes; +})(ts || (ts = {})); +var ts; +(function (ts) { + var infoExtension = ".tsbundleinfo"; + var brackets = createBracketsMap(); + var syntheticParent = { pos: -1, end: -1 }; + /*@internal*/ + /** + * Iterates over the source files that are expected to have an emit output. + * + * @param host An EmitHost. + * @param action The action to execute. + * @param sourceFilesOrTargetSourceFile + * If an array, the full list of source files to emit. + * Else, calls `getSourceFilesToEmit` with the (optional) target source file to determine the list of source files to emit. + */ + function forEachEmittedFile(host, action, sourceFilesOrTargetSourceFile, emitOnlyDtsFiles) { + if (emitOnlyDtsFiles === void 0) { emitOnlyDtsFiles = false; } + var sourceFiles = ts.isArray(sourceFilesOrTargetSourceFile) ? sourceFilesOrTargetSourceFile : ts.getSourceFilesToEmit(host, sourceFilesOrTargetSourceFile); + var options = host.getCompilerOptions(); + if (options.outFile || options.out) { + if (sourceFiles.length) { + var bundle = ts.createBundle(sourceFiles, host.getPrependNodes()); + var result = action(getOutputPathsFor(bundle, host, emitOnlyDtsFiles), bundle); + if (result) { + return result; + } + } + } + else { + for (var _a = 0, sourceFiles_1 = sourceFiles; _a < sourceFiles_1.length; _a++) { + var sourceFile = sourceFiles_1[_a]; + var result = action(getOutputPathsFor(sourceFile, host, emitOnlyDtsFiles), sourceFile); + if (result) { + return result; + } + } + } + } + ts.forEachEmittedFile = forEachEmittedFile; + /*@internal*/ + function getOutputPathsFor(sourceFile, host, forceDtsPaths) { + var options = host.getCompilerOptions(); + if (sourceFile.kind === 280 /* Bundle */) { + var outPath = options.outFile || options.out; + var jsFilePath = options.emitDeclarationOnly ? undefined : outPath; + var sourceMapFilePath = jsFilePath && getSourceMapFilePath(jsFilePath, options); + var declarationFilePath = (forceDtsPaths || ts.getEmitDeclarations(options)) ? ts.removeFileExtension(outPath) + ".d.ts" /* Dts */ : undefined; + var declarationMapPath = declarationFilePath && ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; + var bundleInfoPath = options.references && jsFilePath ? (ts.removeFileExtension(jsFilePath) + infoExtension) : undefined; + return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, bundleInfoPath: bundleInfoPath }; + } + else { + var ownOutputFilePath = ts.getOwnEmitOutputFilePath(sourceFile.fileName, host, getOutputExtension(sourceFile, options)); + // If json file emits to the same location skip writing it, if emitDeclarationOnly skip writing it + var isJsonEmittedToSameLocation = ts.isJsonSourceFile(sourceFile) && + ts.comparePaths(sourceFile.fileName, ownOutputFilePath, host.getCurrentDirectory(), !host.useCaseSensitiveFileNames()) === 0 /* EqualTo */; + var jsFilePath = options.emitDeclarationOnly || isJsonEmittedToSameLocation ? undefined : ownOutputFilePath; + var sourceMapFilePath = !jsFilePath || ts.isJsonSourceFile(sourceFile) ? undefined : getSourceMapFilePath(jsFilePath, options); + // For legacy reasons (ie, we have baselines capturing the behavior), js files don't report a .d.ts output path - this would only matter if `declaration` and `allowJs` were both on, which is currently an error + var isJs = ts.isSourceFileJS(sourceFile); + var declarationFilePath = ((forceDtsPaths || ts.getEmitDeclarations(options)) && !isJs) ? ts.getDeclarationEmitOutputFilePath(sourceFile.fileName, host) : undefined; + var declarationMapPath = declarationFilePath && ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; + return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, bundleInfoPath: undefined }; + } + } + ts.getOutputPathsFor = getOutputPathsFor; + function getSourceMapFilePath(jsFilePath, options) { + return (options.sourceMap && !options.inlineSourceMap) ? jsFilePath + ".map" : undefined; + } + function createDefaultBundleInfo() { + return { + originalOffset: -1, + totalLength: -1 + }; + } + // JavaScript files are always LanguageVariant.JSX, as JSX syntax is allowed in .js files also. + // So for JavaScript files, '.jsx' is only emitted if the input was '.jsx', and JsxEmit.Preserve. + // For TypeScript, the only time to emit with a '.jsx' extension, is on JSX input, and JsxEmit.Preserve + /* @internal */ + function getOutputExtension(sourceFile, options) { + if (ts.isJsonSourceFile(sourceFile)) { + return ".json" /* Json */; + } + if (options.jsx === 1 /* Preserve */) { + if (ts.isSourceFileJS(sourceFile)) { + if (ts.fileExtensionIs(sourceFile.fileName, ".jsx" /* Jsx */)) { + return ".jsx" /* Jsx */; + } + } + else if (sourceFile.languageVariant === 1 /* JSX */) { + // TypeScript source file preserving JSX syntax + return ".jsx" /* Jsx */; + } + } + return ".js" /* Js */; + } + ts.getOutputExtension = getOutputExtension; + /*@internal*/ + // targetSourceFile is when users only want one file in entire project to be emitted. This is used in compileOnSave feature + function emitFiles(resolver, host, targetSourceFile, emitOnlyDtsFiles, transformers, declarationTransformers) { + var compilerOptions = host.getCompilerOptions(); + var sourceMapDataList = (compilerOptions.sourceMap || compilerOptions.inlineSourceMap || ts.getAreDeclarationMapsEnabled(compilerOptions)) ? [] : undefined; + var emittedFilesList = compilerOptions.listEmittedFiles ? [] : undefined; + var emitterDiagnostics = ts.createDiagnosticCollection(); + var newLine = ts.getNewLineCharacter(compilerOptions, function () { return host.getNewLine(); }); + var writer = ts.createTextWriter(newLine); + var _a = ts.performance.createTimer("printTime", "beforePrint", "afterPrint"), enter = _a.enter, exit = _a.exit; + var bundleInfo = createDefaultBundleInfo(); + var emitSkipped = false; + var exportedModulesFromDeclarationEmit; + // Emit each output file + enter(); + forEachEmittedFile(host, emitSourceFileOrBundle, ts.getSourceFilesToEmit(host, targetSourceFile), emitOnlyDtsFiles); + exit(); + return { + emitSkipped: emitSkipped, + diagnostics: emitterDiagnostics.getDiagnostics(), + emittedFiles: emittedFilesList, + sourceMaps: sourceMapDataList, + exportedModulesFromDeclarationEmit: exportedModulesFromDeclarationEmit + }; + function emitSourceFileOrBundle(_a, sourceFileOrBundle) { + var jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, bundleInfoPath = _a.bundleInfoPath; + emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, bundleInfoPath); + emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath); + if (!emitSkipped && emittedFilesList) { + if (!emitOnlyDtsFiles) { + if (jsFilePath) { + emittedFilesList.push(jsFilePath); + } + if (sourceMapFilePath) { + emittedFilesList.push(sourceMapFilePath); + } + if (bundleInfoPath) { + emittedFilesList.push(bundleInfoPath); + } + } + if (declarationFilePath) { + emittedFilesList.push(declarationFilePath); + } + if (declarationMapPath) { + emittedFilesList.push(declarationMapPath); + } + } + } + function emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, bundleInfoPath) { + if (emitOnlyDtsFiles || !jsFilePath) { + return; + } + // Make sure not to write js file and source map file if any of them cannot be written + if ((jsFilePath && host.isEmitBlocked(jsFilePath)) || compilerOptions.noEmit) { + emitSkipped = true; + return; + } + // Transform the source files + var transform = ts.transformNodes(resolver, host, compilerOptions, [sourceFileOrBundle], transformers, /*allowDtsFiles*/ false); + var printerOptions = { + removeComments: compilerOptions.removeComments, + newLine: compilerOptions.newLine, + noEmitHelpers: compilerOptions.noEmitHelpers, + module: compilerOptions.module, + target: compilerOptions.target, + sourceMap: compilerOptions.sourceMap, + inlineSourceMap: compilerOptions.inlineSourceMap, + inlineSources: compilerOptions.inlineSources, + extendedDiagnostics: compilerOptions.extendedDiagnostics, + }; + // Create a printer to print the nodes + var printer = createPrinter(printerOptions, { + // resolver hooks + hasGlobalName: resolver.hasGlobalName, + // transform hooks + onEmitNode: transform.emitNodeWithNotification, + substituteNode: transform.substituteNode, + }); + ts.Debug.assert(transform.transformed.length === 1, "Should only see one output from the transform"); + printSourceFileOrBundle(jsFilePath, sourceMapFilePath, transform.transformed[0], bundleInfoPath, printer, compilerOptions); + // Clean up emit nodes on parse tree + transform.dispose(); + } + function emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath) { + if (!(declarationFilePath && !ts.isInJSFile(sourceFileOrBundle))) { + return; + } + var sourceFiles = ts.isSourceFile(sourceFileOrBundle) ? [sourceFileOrBundle] : sourceFileOrBundle.sourceFiles; + // Setup and perform the transformation to retrieve declarations from the input files + var nonJsFiles = ts.filter(sourceFiles, ts.isSourceFileNotJS); + var inputListOrBundle = (compilerOptions.outFile || compilerOptions.out) ? [ts.createBundle(nonJsFiles, !ts.isSourceFile(sourceFileOrBundle) ? sourceFileOrBundle.prepends : undefined)] : nonJsFiles; + if (emitOnlyDtsFiles && !ts.getEmitDeclarations(compilerOptions)) { + // Checker wont collect the linked aliases since thats only done when declaration is enabled. + // Do that here when emitting only dts files + nonJsFiles.forEach(collectLinkedAliases); + } + var declarationTransform = ts.transformNodes(resolver, host, compilerOptions, inputListOrBundle, ts.concatenate([ts.transformDeclarations], declarationTransformers), /*allowDtsFiles*/ false); + if (ts.length(declarationTransform.diagnostics)) { + for (var _a = 0, _b = declarationTransform.diagnostics; _a < _b.length; _a++) { + var diagnostic = _b[_a]; + emitterDiagnostics.add(diagnostic); + } + } + var printerOptions = { + removeComments: compilerOptions.removeComments, + newLine: compilerOptions.newLine, + noEmitHelpers: true, + module: compilerOptions.module, + target: compilerOptions.target, + sourceMap: compilerOptions.sourceMap, + inlineSourceMap: compilerOptions.inlineSourceMap, + extendedDiagnostics: compilerOptions.extendedDiagnostics, + onlyPrintJsDocStyle: true, + }; + var declarationPrinter = createPrinter(printerOptions, { + // resolver hooks + hasGlobalName: resolver.hasGlobalName, + // transform hooks + onEmitNode: declarationTransform.emitNodeWithNotification, + substituteNode: declarationTransform.substituteNode, + }); + var declBlocked = (!!declarationTransform.diagnostics && !!declarationTransform.diagnostics.length) || !!host.isEmitBlocked(declarationFilePath) || !!compilerOptions.noEmit; + emitSkipped = emitSkipped || declBlocked; + if (!declBlocked || emitOnlyDtsFiles) { + ts.Debug.assert(declarationTransform.transformed.length === 1, "Should only see one output from the decl transform"); + printSourceFileOrBundle(declarationFilePath, declarationMapPath, declarationTransform.transformed[0], /* bundleInfopath*/ undefined, declarationPrinter, { + sourceMap: compilerOptions.declarationMap, + sourceRoot: compilerOptions.sourceRoot, + mapRoot: compilerOptions.mapRoot, + extendedDiagnostics: compilerOptions.extendedDiagnostics, + }); + if (emitOnlyDtsFiles && declarationTransform.transformed[0].kind === 279 /* SourceFile */) { + var sourceFile = declarationTransform.transformed[0]; + exportedModulesFromDeclarationEmit = sourceFile.exportedModulesFromDeclarationEmit; + } + } + declarationTransform.dispose(); + } + function collectLinkedAliases(node) { + if (ts.isExportAssignment(node)) { + if (node.expression.kind === 72 /* Identifier */) { + resolver.collectLinkedAliases(node.expression, /*setVisibility*/ true); + } + return; + } + else if (ts.isExportSpecifier(node)) { + resolver.collectLinkedAliases(node.propertyName || node.name, /*setVisibility*/ true); + return; + } + ts.forEachChild(node, collectLinkedAliases); + } + function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle, bundleInfoPath, printer, mapOptions) { + var bundle = sourceFileOrBundle.kind === 280 /* Bundle */ ? sourceFileOrBundle : undefined; + var sourceFile = sourceFileOrBundle.kind === 279 /* SourceFile */ ? sourceFileOrBundle : undefined; + var sourceFiles = bundle ? bundle.sourceFiles : [sourceFile]; + var sourceMapGenerator; + if (shouldEmitSourceMaps(mapOptions, sourceFileOrBundle)) { + sourceMapGenerator = ts.createSourceMapGenerator(host, ts.getBaseFileName(ts.normalizeSlashes(jsFilePath)), getSourceRoot(mapOptions), getSourceMapDirectory(mapOptions, jsFilePath, sourceFile), mapOptions); + } + if (bundle) { + printer.writeBundle(bundle, bundleInfo, writer, sourceMapGenerator); + } + else { + printer.writeFile(sourceFile, writer, sourceMapGenerator); + } + if (sourceMapGenerator) { + if (sourceMapDataList) { + sourceMapDataList.push({ + inputSourceFileNames: sourceMapGenerator.getSources(), + sourceMap: sourceMapGenerator.toJSON() + }); + } + var sourceMappingURL = getSourceMappingURL(mapOptions, sourceMapGenerator, jsFilePath, sourceMapFilePath, sourceFile); + if (sourceMappingURL) { + if (!writer.isAtStartOfLine()) + writer.rawWrite(newLine); + writer.writeComment("//# " + "sourceMappingURL" + "=" + sourceMappingURL); // Tools can sometimes see this line as a source mapping url comment + } + // Write the source map + if (sourceMapFilePath) { + var sourceMap = sourceMapGenerator.toString(); + ts.writeFile(host, emitterDiagnostics, sourceMapFilePath, sourceMap, /*writeByteOrderMark*/ false, sourceFiles); + } + } + else { + writer.writeLine(); + } + // Write the output file + ts.writeFile(host, emitterDiagnostics, jsFilePath, writer.getText(), !!compilerOptions.emitBOM, sourceFiles); + // Write bundled offset information if applicable + if (bundleInfoPath) { + bundleInfo.totalLength = writer.getTextPos(); + ts.writeFile(host, emitterDiagnostics, bundleInfoPath, JSON.stringify(bundleInfo, undefined, 2), /*writeByteOrderMark*/ false); + } + // Reset state + writer.clear(); + bundleInfo = createDefaultBundleInfo(); + } + function shouldEmitSourceMaps(mapOptions, sourceFileOrBundle) { + return (mapOptions.sourceMap || mapOptions.inlineSourceMap) + && (sourceFileOrBundle.kind !== 279 /* SourceFile */ || !ts.fileExtensionIs(sourceFileOrBundle.fileName, ".json" /* Json */)); + } + function getSourceRoot(mapOptions) { + // Normalize source root and make sure it has trailing "/" so that it can be used to combine paths with the + // relative paths of the sources list in the sourcemap + var sourceRoot = ts.normalizeSlashes(mapOptions.sourceRoot || ""); + return sourceRoot ? ts.ensureTrailingDirectorySeparator(sourceRoot) : sourceRoot; + } + function getSourceMapDirectory(mapOptions, filePath, sourceFile) { + if (mapOptions.sourceRoot) + return host.getCommonSourceDirectory(); + if (mapOptions.mapRoot) { + var sourceMapDir = ts.normalizeSlashes(mapOptions.mapRoot); + if (sourceFile) { + // For modules or multiple emit files the mapRoot will have directory structure like the sources + // So if src\a.ts and src\lib\b.ts are compiled together user would be moving the maps into mapRoot\a.js.map and mapRoot\lib\b.js.map + sourceMapDir = ts.getDirectoryPath(ts.getSourceFilePathInNewDir(sourceFile.fileName, host, sourceMapDir)); + } + if (ts.getRootLength(sourceMapDir) === 0) { + // The relative paths are relative to the common directory + sourceMapDir = ts.combinePaths(host.getCommonSourceDirectory(), sourceMapDir); + } + return sourceMapDir; + } + return ts.getDirectoryPath(ts.normalizePath(filePath)); + } + function getSourceMappingURL(mapOptions, sourceMapGenerator, filePath, sourceMapFilePath, sourceFile) { + if (mapOptions.inlineSourceMap) { + // Encode the sourceMap into the sourceMap url + var sourceMapText = sourceMapGenerator.toString(); + var base64SourceMapText = ts.base64encode(ts.sys, sourceMapText); + return "data:application/json;base64," + base64SourceMapText; + } + var sourceMapFile = ts.getBaseFileName(ts.normalizeSlashes(ts.Debug.assertDefined(sourceMapFilePath))); + if (mapOptions.mapRoot) { + var sourceMapDir = ts.normalizeSlashes(mapOptions.mapRoot); + if (sourceFile) { + // For modules or multiple emit files the mapRoot will have directory structure like the sources + // So if src\a.ts and src\lib\b.ts are compiled together user would be moving the maps into mapRoot\a.js.map and mapRoot\lib\b.js.map + sourceMapDir = ts.getDirectoryPath(ts.getSourceFilePathInNewDir(sourceFile.fileName, host, sourceMapDir)); + } + if (ts.getRootLength(sourceMapDir) === 0) { + // The relative paths are relative to the common directory + sourceMapDir = ts.combinePaths(host.getCommonSourceDirectory(), sourceMapDir); + return ts.getRelativePathToDirectoryOrUrl(ts.getDirectoryPath(ts.normalizePath(filePath)), // get the relative sourceMapDir path based on jsFilePath + ts.combinePaths(sourceMapDir, sourceMapFile), // this is where user expects to see sourceMap + host.getCurrentDirectory(), host.getCanonicalFileName, + /*isAbsolutePathAnUrl*/ true); + } + else { + return ts.combinePaths(sourceMapDir, sourceMapFile); + } + } + return sourceMapFile; + } + } + ts.emitFiles = emitFiles; + var PipelinePhase; + (function (PipelinePhase) { + PipelinePhase[PipelinePhase["Notification"] = 0] = "Notification"; + PipelinePhase[PipelinePhase["Substitution"] = 1] = "Substitution"; + PipelinePhase[PipelinePhase["Comments"] = 2] = "Comments"; + PipelinePhase[PipelinePhase["SourceMaps"] = 3] = "SourceMaps"; + PipelinePhase[PipelinePhase["Emit"] = 4] = "Emit"; + })(PipelinePhase || (PipelinePhase = {})); + function createPrinter(printerOptions, handlers) { + if (printerOptions === void 0) { printerOptions = {}; } + if (handlers === void 0) { handlers = {}; } + var hasGlobalName = handlers.hasGlobalName, _a = handlers.onEmitNode, onEmitNode = _a === void 0 ? ts.noEmitNotification : _a, _b = handlers.substituteNode, substituteNode = _b === void 0 ? ts.noEmitSubstitution : _b, onBeforeEmitNodeArray = handlers.onBeforeEmitNodeArray, onAfterEmitNodeArray = handlers.onAfterEmitNodeArray, onBeforeEmitToken = handlers.onBeforeEmitToken, onAfterEmitToken = handlers.onAfterEmitToken; + var extendedDiagnostics = !!printerOptions.extendedDiagnostics; + var newLine = ts.getNewLineCharacter(printerOptions); + var moduleKind = ts.getEmitModuleKind(printerOptions); + var bundledHelpers = ts.createMap(); + var currentSourceFile; + var nodeIdToGeneratedName; // Map of generated names for specific nodes. + var autoGeneratedIdToGeneratedName; // Map of generated names for temp and loop variables. + var generatedNames; // Set of names generated by the NameGenerator. + var tempFlagsStack; // Stack of enclosing name generation scopes. + var tempFlags; // TempFlags for the current name generation scope. + var reservedNamesStack; // Stack of TempFlags reserved in enclosing name generation scopes. + var reservedNames; // TempFlags to reserve in nested name generation scopes. + var writer; + var ownWriter; // Reusable `EmitTextWriter` for basic printing. + var write = writeBase; + var isOwnFileEmit; + // Source Maps + var sourceMapsDisabled = true; + var sourceMapGenerator; + var sourceMapSource; + var sourceMapSourceIndex = -1; + // Comments + var containerPos = -1; + var containerEnd = -1; + var declarationListContainerEnd = -1; + var currentLineMap; + var detachedCommentsInfo; + var hasWrittenComment = false; + var commentsDisabled = !!printerOptions.removeComments; + var _c = ts.performance.createTimerIf(extendedDiagnostics, "commentTime", "beforeComment", "afterComment"), enterComment = _c.enter, exitComment = _c.exit; + reset(); + return { + // public API + printNode: printNode, + printList: printList, + printFile: printFile, + printBundle: printBundle, + // internal API + writeNode: writeNode, + writeList: writeList, + writeFile: writeFile, + writeBundle: writeBundle + }; + function printNode(hint, node, sourceFile) { + switch (hint) { + case 0 /* SourceFile */: + ts.Debug.assert(ts.isSourceFile(node), "Expected a SourceFile node."); + break; + case 2 /* IdentifierName */: + ts.Debug.assert(ts.isIdentifier(node), "Expected an Identifier node."); + break; + case 1 /* Expression */: + ts.Debug.assert(ts.isExpression(node), "Expected an Expression node."); + break; + } + switch (node.kind) { + case 279 /* SourceFile */: return printFile(node); + case 280 /* Bundle */: return printBundle(node); + case 281 /* UnparsedSource */: return printUnparsedSource(node); + } + writeNode(hint, node, sourceFile, beginPrint()); + return endPrint(); + } + function printList(format, nodes, sourceFile) { + writeList(format, nodes, sourceFile, beginPrint()); + return endPrint(); + } + function printBundle(bundle) { + writeBundle(bundle, /*bundleInfo*/ undefined, beginPrint(), /*sourceMapEmitter*/ undefined); + return endPrint(); + } + function printFile(sourceFile) { + writeFile(sourceFile, beginPrint(), /*sourceMapEmitter*/ undefined); + return endPrint(); + } + function printUnparsedSource(unparsed) { + writeUnparsedSource(unparsed, beginPrint()); + return endPrint(); + } + function writeNode(hint, node, sourceFile, output) { + var previousWriter = writer; + setWriter(output, /*_sourceMapGenerator*/ undefined); + print(hint, node, sourceFile); + reset(); + writer = previousWriter; + } + function writeList(format, nodes, sourceFile, output) { + var previousWriter = writer; + setWriter(output, /*_sourceMapGenerator*/ undefined); + if (sourceFile) { + setSourceFile(sourceFile); + } + emitList(syntheticParent, nodes, format); + reset(); + writer = previousWriter; + } + function writeBundle(bundle, bundleInfo, output, sourceMapGenerator) { + isOwnFileEmit = false; + var previousWriter = writer; + setWriter(output, sourceMapGenerator); + emitShebangIfNeeded(bundle); + emitPrologueDirectivesIfNeeded(bundle); + emitHelpers(bundle); + emitSyntheticTripleSlashReferencesIfNeeded(bundle); + for (var _a = 0, _b = bundle.prepends; _a < _b.length; _a++) { + var prepend = _b[_a]; + writeLine(); + print(4 /* Unspecified */, prepend, /*sourceFile*/ undefined); + } + if (bundleInfo) { + bundleInfo.originalOffset = writer.getTextPos(); + } + for (var _c = 0, _d = bundle.sourceFiles; _c < _d.length; _c++) { + var sourceFile = _d[_c]; + print(0 /* SourceFile */, sourceFile, sourceFile); + } + reset(); + writer = previousWriter; + } + function writeUnparsedSource(unparsed, output) { + var previousWriter = writer; + setWriter(output, /*_sourceMapGenerator*/ undefined); + print(4 /* Unspecified */, unparsed, /*sourceFile*/ undefined); + reset(); + writer = previousWriter; + } + function writeFile(sourceFile, output, sourceMapGenerator) { + isOwnFileEmit = true; + var previousWriter = writer; + setWriter(output, sourceMapGenerator); + emitShebangIfNeeded(sourceFile); + emitPrologueDirectivesIfNeeded(sourceFile); + print(0 /* SourceFile */, sourceFile, sourceFile); + reset(); + writer = previousWriter; + } + function beginPrint() { + return ownWriter || (ownWriter = ts.createTextWriter(newLine)); + } + function endPrint() { + var text = ownWriter.getText(); + ownWriter.clear(); + return text; + } + function print(hint, node, sourceFile) { + if (sourceFile) { + setSourceFile(sourceFile); + } + var pipelinePhase = getPipelinePhase(0 /* Notification */, node); + pipelinePhase(hint, node); + } + function setSourceFile(sourceFile) { + currentSourceFile = sourceFile; + currentLineMap = undefined; + detachedCommentsInfo = undefined; + if (sourceFile) { + setSourceMapSource(sourceFile); + } + } + function setWriter(_writer, _sourceMapGenerator) { + if (_writer && printerOptions.omitTrailingSemicolon) { + _writer = ts.getTrailingSemicolonOmittingWriter(_writer); + } + writer = _writer; // TODO: GH#18217 + sourceMapGenerator = _sourceMapGenerator; + sourceMapsDisabled = !writer || !sourceMapGenerator; + } + function reset() { + nodeIdToGeneratedName = []; + autoGeneratedIdToGeneratedName = []; + generatedNames = ts.createMap(); + tempFlagsStack = []; + tempFlags = 0 /* Auto */; + reservedNamesStack = []; + currentSourceFile = undefined; + currentLineMap = undefined; + detachedCommentsInfo = undefined; + setWriter(/*output*/ undefined, /*_sourceMapGenerator*/ undefined); + } + function getCurrentLineMap() { + return currentLineMap || (currentLineMap = ts.getLineStarts(currentSourceFile)); + } + function emit(node) { + if (node === undefined) + return; + var pipelinePhase = getPipelinePhase(0 /* Notification */, node); + pipelinePhase(4 /* Unspecified */, node); + } + function emitIdentifierName(node) { + if (node === undefined) + return; + var pipelinePhase = getPipelinePhase(0 /* Notification */, node); + pipelinePhase(2 /* IdentifierName */, node); + } + function emitExpression(node) { + if (node === undefined) + return; + var pipelinePhase = getPipelinePhase(0 /* Notification */, node); + pipelinePhase(1 /* Expression */, node); + } + function getPipelinePhase(phase, node) { + switch (phase) { + case 0 /* Notification */: + if (onEmitNode !== ts.noEmitNotification) { + return pipelineEmitWithNotification; + } + // falls through + case 1 /* Substitution */: + if (substituteNode !== ts.noEmitSubstitution) { + return pipelineEmitWithSubstitution; + } + // falls through + case 2 /* Comments */: + if (!commentsDisabled && node.kind !== 279 /* SourceFile */) { + return pipelineEmitWithComments; + } + // falls through + case 3 /* SourceMaps */: + if (!sourceMapsDisabled && node.kind !== 279 /* SourceFile */ && !ts.isInJsonFile(node)) { + return pipelineEmitWithSourceMap; + } + // falls through + case 4 /* Emit */: + return pipelineEmitWithHint; + default: + return ts.Debug.assertNever(phase); + } + } + function getNextPipelinePhase(currentPhase, node) { + return getPipelinePhase(currentPhase + 1, node); + } + function pipelineEmitWithNotification(hint, node) { + var pipelinePhase = getNextPipelinePhase(0 /* Notification */, node); + onEmitNode(hint, node, pipelinePhase); + } + function pipelineEmitWithHint(hint, node) { + if (hint === 0 /* SourceFile */) + return emitSourceFile(ts.cast(node, ts.isSourceFile)); + if (hint === 2 /* IdentifierName */) + return emitIdentifier(ts.cast(node, ts.isIdentifier)); + if (hint === 3 /* MappedTypeParameter */) + return emitMappedTypeParameter(ts.cast(node, ts.isTypeParameterDeclaration)); + if (hint === 5 /* EmbeddedStatement */) { + ts.Debug.assertNode(node, ts.isEmptyStatement); + return emitEmptyStatement(/*isEmbeddedStatement*/ true); + } + if (hint === 4 /* Unspecified */) { + if (ts.isKeyword(node.kind)) + return writeTokenNode(node, writeKeyword); + switch (node.kind) { + // Pseudo-literals + case 15 /* TemplateHead */: + case 16 /* TemplateMiddle */: + case 17 /* TemplateTail */: + return emitLiteral(node); + case 281 /* UnparsedSource */: + return emitUnparsedSource(node); + // Identifiers + case 72 /* Identifier */: + return emitIdentifier(node); + // Parse tree nodes + // Names + case 148 /* QualifiedName */: + return emitQualifiedName(node); + case 149 /* ComputedPropertyName */: + return emitComputedPropertyName(node); + // Signature elements + case 150 /* TypeParameter */: + return emitTypeParameter(node); + case 151 /* Parameter */: + return emitParameter(node); + case 152 /* Decorator */: + return emitDecorator(node); + // Type members + case 153 /* PropertySignature */: + return emitPropertySignature(node); + case 154 /* PropertyDeclaration */: + return emitPropertyDeclaration(node); + case 155 /* MethodSignature */: + return emitMethodSignature(node); + case 156 /* MethodDeclaration */: + return emitMethodDeclaration(node); + case 157 /* Constructor */: + return emitConstructor(node); + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + return emitAccessorDeclaration(node); + case 160 /* CallSignature */: + return emitCallSignature(node); + case 161 /* ConstructSignature */: + return emitConstructSignature(node); + case 162 /* IndexSignature */: + return emitIndexSignature(node); + // Types + case 163 /* TypePredicate */: + return emitTypePredicate(node); + case 164 /* TypeReference */: + return emitTypeReference(node); + case 165 /* FunctionType */: + return emitFunctionType(node); + case 289 /* JSDocFunctionType */: + return emitJSDocFunctionType(node); + case 166 /* ConstructorType */: + return emitConstructorType(node); + case 167 /* TypeQuery */: + return emitTypeQuery(node); + case 168 /* TypeLiteral */: + return emitTypeLiteral(node); + case 169 /* ArrayType */: + return emitArrayType(node); + case 170 /* TupleType */: + return emitTupleType(node); + case 171 /* OptionalType */: + return emitOptionalType(node); + case 173 /* UnionType */: + return emitUnionType(node); + case 174 /* IntersectionType */: + return emitIntersectionType(node); + case 175 /* ConditionalType */: + return emitConditionalType(node); + case 176 /* InferType */: + return emitInferType(node); + case 177 /* ParenthesizedType */: + return emitParenthesizedType(node); + case 211 /* ExpressionWithTypeArguments */: + return emitExpressionWithTypeArguments(node); + case 178 /* ThisType */: + return emitThisType(); + case 179 /* TypeOperator */: + return emitTypeOperator(node); + case 180 /* IndexedAccessType */: + return emitIndexedAccessType(node); + case 181 /* MappedType */: + return emitMappedType(node); + case 182 /* LiteralType */: + return emitLiteralType(node); + case 183 /* ImportType */: + return emitImportTypeNode(node); + case 284 /* JSDocAllType */: + writePunctuation("*"); + return; + case 285 /* JSDocUnknownType */: + writePunctuation("?"); + return; + case 286 /* JSDocNullableType */: + return emitJSDocNullableType(node); + case 287 /* JSDocNonNullableType */: + return emitJSDocNonNullableType(node); + case 288 /* JSDocOptionalType */: + return emitJSDocOptionalType(node); + case 172 /* RestType */: + case 290 /* JSDocVariadicType */: + return emitRestOrJSDocVariadicType(node); + // Binding patterns + case 184 /* ObjectBindingPattern */: + return emitObjectBindingPattern(node); + case 185 /* ArrayBindingPattern */: + return emitArrayBindingPattern(node); + case 186 /* BindingElement */: + return emitBindingElement(node); + // Misc + case 216 /* TemplateSpan */: + return emitTemplateSpan(node); + case 217 /* SemicolonClassElement */: + return emitSemicolonClassElement(); + // Statements + case 218 /* Block */: + return emitBlock(node); + case 219 /* VariableStatement */: + return emitVariableStatement(node); + case 220 /* EmptyStatement */: + return emitEmptyStatement(/*isEmbeddedStatement*/ false); + case 221 /* ExpressionStatement */: + return emitExpressionStatement(node); + case 222 /* IfStatement */: + return emitIfStatement(node); + case 223 /* DoStatement */: + return emitDoStatement(node); + case 224 /* WhileStatement */: + return emitWhileStatement(node); + case 225 /* ForStatement */: + return emitForStatement(node); + case 226 /* ForInStatement */: + return emitForInStatement(node); + case 227 /* ForOfStatement */: + return emitForOfStatement(node); + case 228 /* ContinueStatement */: + return emitContinueStatement(node); + case 229 /* BreakStatement */: + return emitBreakStatement(node); + case 230 /* ReturnStatement */: + return emitReturnStatement(node); + case 231 /* WithStatement */: + return emitWithStatement(node); + case 232 /* SwitchStatement */: + return emitSwitchStatement(node); + case 233 /* LabeledStatement */: + return emitLabeledStatement(node); + case 234 /* ThrowStatement */: + return emitThrowStatement(node); + case 235 /* TryStatement */: + return emitTryStatement(node); + case 236 /* DebuggerStatement */: + return emitDebuggerStatement(node); + // Declarations + case 237 /* VariableDeclaration */: + return emitVariableDeclaration(node); + case 238 /* VariableDeclarationList */: + return emitVariableDeclarationList(node); + case 239 /* FunctionDeclaration */: + return emitFunctionDeclaration(node); + case 240 /* ClassDeclaration */: + return emitClassDeclaration(node); + case 241 /* InterfaceDeclaration */: + return emitInterfaceDeclaration(node); + case 242 /* TypeAliasDeclaration */: + return emitTypeAliasDeclaration(node); + case 243 /* EnumDeclaration */: + return emitEnumDeclaration(node); + case 244 /* ModuleDeclaration */: + return emitModuleDeclaration(node); + case 245 /* ModuleBlock */: + return emitModuleBlock(node); + case 246 /* CaseBlock */: + return emitCaseBlock(node); + case 247 /* NamespaceExportDeclaration */: + return emitNamespaceExportDeclaration(node); + case 248 /* ImportEqualsDeclaration */: + return emitImportEqualsDeclaration(node); + case 249 /* ImportDeclaration */: + return emitImportDeclaration(node); + case 250 /* ImportClause */: + return emitImportClause(node); + case 251 /* NamespaceImport */: + return emitNamespaceImport(node); + case 252 /* NamedImports */: + return emitNamedImports(node); + case 253 /* ImportSpecifier */: + return emitImportSpecifier(node); + case 254 /* ExportAssignment */: + return emitExportAssignment(node); + case 255 /* ExportDeclaration */: + return emitExportDeclaration(node); + case 256 /* NamedExports */: + return emitNamedExports(node); + case 257 /* ExportSpecifier */: + return emitExportSpecifier(node); + case 258 /* MissingDeclaration */: + return; + // Module references + case 259 /* ExternalModuleReference */: + return emitExternalModuleReference(node); + // JSX (non-expression) + case 11 /* JsxText */: + return emitJsxText(node); + case 262 /* JsxOpeningElement */: + case 265 /* JsxOpeningFragment */: + return emitJsxOpeningElementOrFragment(node); + case 263 /* JsxClosingElement */: + case 266 /* JsxClosingFragment */: + return emitJsxClosingElementOrFragment(node); + case 267 /* JsxAttribute */: + return emitJsxAttribute(node); + case 268 /* JsxAttributes */: + return emitJsxAttributes(node); + case 269 /* JsxSpreadAttribute */: + return emitJsxSpreadAttribute(node); + case 270 /* JsxExpression */: + return emitJsxExpression(node); + // Clauses + case 271 /* CaseClause */: + return emitCaseClause(node); + case 272 /* DefaultClause */: + return emitDefaultClause(node); + case 273 /* HeritageClause */: + return emitHeritageClause(node); + case 274 /* CatchClause */: + return emitCatchClause(node); + // Property assignments + case 275 /* PropertyAssignment */: + return emitPropertyAssignment(node); + case 276 /* ShorthandPropertyAssignment */: + return emitShorthandPropertyAssignment(node); + case 277 /* SpreadAssignment */: + return emitSpreadAssignment(node); + // Enum + case 278 /* EnumMember */: + return emitEnumMember(node); + // JSDoc nodes (only used in codefixes currently) + case 299 /* JSDocParameterTag */: + case 305 /* JSDocPropertyTag */: + return emitJSDocPropertyLikeTag(node); + case 300 /* JSDocReturnTag */: + case 302 /* JSDocTypeTag */: + case 301 /* JSDocThisTag */: + case 298 /* JSDocEnumTag */: + return emitJSDocSimpleTypedTag(node); + case 295 /* JSDocAugmentsTag */: + return emitJSDocAugmentsTag(node); + case 303 /* JSDocTemplateTag */: + return emitJSDocTemplateTag(node); + case 304 /* JSDocTypedefTag */: + return emitJSDocTypedefTag(node); + case 297 /* JSDocCallbackTag */: + return emitJSDocCallbackTag(node); + case 293 /* JSDocSignature */: + return emitJSDocSignature(node); + case 292 /* JSDocTypeLiteral */: + return emitJSDocTypeLiteral(node); + case 296 /* JSDocClassTag */: + case 294 /* JSDocTag */: + return emitJSDocSimpleTag(node); + case 291 /* JSDocComment */: + return emitJSDoc(node); + // Transformation nodes (ignored) + } + if (ts.isExpression(node)) { + hint = 1 /* Expression */; + if (substituteNode !== ts.noEmitSubstitution) { + node = substituteNode(hint, node); + } + } + else if (ts.isToken(node)) { + return writeTokenNode(node, writePunctuation); + } + } + if (hint === 1 /* Expression */) { + switch (node.kind) { + // Literals + case 8 /* NumericLiteral */: + case 9 /* BigIntLiteral */: + return emitNumericOrBigIntLiteral(node); + case 10 /* StringLiteral */: + case 13 /* RegularExpressionLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: + return emitLiteral(node); + // Identifiers + case 72 /* Identifier */: + return emitIdentifier(node); + // Reserved words + case 87 /* FalseKeyword */: + case 96 /* NullKeyword */: + case 98 /* SuperKeyword */: + case 102 /* TrueKeyword */: + case 100 /* ThisKeyword */: + case 92 /* ImportKeyword */: + writeTokenNode(node, writeKeyword); + return; + // Expressions + case 187 /* ArrayLiteralExpression */: + return emitArrayLiteralExpression(node); + case 188 /* ObjectLiteralExpression */: + return emitObjectLiteralExpression(node); + case 189 /* PropertyAccessExpression */: + return emitPropertyAccessExpression(node); + case 190 /* ElementAccessExpression */: + return emitElementAccessExpression(node); + case 191 /* CallExpression */: + return emitCallExpression(node); + case 192 /* NewExpression */: + return emitNewExpression(node); + case 193 /* TaggedTemplateExpression */: + return emitTaggedTemplateExpression(node); + case 194 /* TypeAssertionExpression */: + return emitTypeAssertionExpression(node); + case 195 /* ParenthesizedExpression */: + return emitParenthesizedExpression(node); + case 196 /* FunctionExpression */: + return emitFunctionExpression(node); + case 197 /* ArrowFunction */: + return emitArrowFunction(node); + case 198 /* DeleteExpression */: + return emitDeleteExpression(node); + case 199 /* TypeOfExpression */: + return emitTypeOfExpression(node); + case 200 /* VoidExpression */: + return emitVoidExpression(node); + case 201 /* AwaitExpression */: + return emitAwaitExpression(node); + case 202 /* PrefixUnaryExpression */: + return emitPrefixUnaryExpression(node); + case 203 /* PostfixUnaryExpression */: + return emitPostfixUnaryExpression(node); + case 204 /* BinaryExpression */: + return emitBinaryExpression(node); + case 205 /* ConditionalExpression */: + return emitConditionalExpression(node); + case 206 /* TemplateExpression */: + return emitTemplateExpression(node); + case 207 /* YieldExpression */: + return emitYieldExpression(node); + case 208 /* SpreadElement */: + return emitSpreadExpression(node); + case 209 /* ClassExpression */: + return emitClassExpression(node); + case 210 /* OmittedExpression */: + return; + case 212 /* AsExpression */: + return emitAsExpression(node); + case 213 /* NonNullExpression */: + return emitNonNullExpression(node); + case 214 /* MetaProperty */: + return emitMetaProperty(node); + // JSX + case 260 /* JsxElement */: + return emitJsxElement(node); + case 261 /* JsxSelfClosingElement */: + return emitJsxSelfClosingElement(node); + case 264 /* JsxFragment */: + return emitJsxFragment(node); + // Transformation nodes + case 308 /* PartiallyEmittedExpression */: + return emitPartiallyEmittedExpression(node); + case 309 /* CommaListExpression */: + return emitCommaList(node); + } + } + } + function emitMappedTypeParameter(node) { + emit(node.name); + writeSpace(); + writeKeyword("in"); + writeSpace(); + emit(node.constraint); + } + function pipelineEmitWithSubstitution(hint, node) { + var pipelinePhase = getNextPipelinePhase(1 /* Substitution */, node); + pipelinePhase(hint, substituteNode(hint, node)); + } + function emitHelpers(node) { + var helpersEmitted = false; + var bundle = node.kind === 280 /* Bundle */ ? node : undefined; + if (bundle && moduleKind === ts.ModuleKind.None) { + return; + } + var numNodes = bundle ? bundle.sourceFiles.length : 1; + for (var i = 0; i < numNodes; i++) { + var currentNode = bundle ? bundle.sourceFiles[i] : node; + var sourceFile = ts.isSourceFile(currentNode) ? currentNode : currentSourceFile; + var shouldSkip = printerOptions.noEmitHelpers || ts.getExternalHelpersModuleName(sourceFile) !== undefined; + var shouldBundle = ts.isSourceFile(currentNode) && !isOwnFileEmit; + var helpers = ts.getEmitHelpers(currentNode); + if (helpers) { + for (var _a = 0, _b = ts.stableSort(helpers, ts.compareEmitHelpers); _a < _b.length; _a++) { + var helper = _b[_a]; + if (!helper.scoped) { + // Skip the helper if it can be skipped and the noEmitHelpers compiler + // option is set, or if it can be imported and the importHelpers compiler + // option is set. + if (shouldSkip) + continue; + // Skip the helper if it can be bundled but hasn't already been emitted and we + // are emitting a bundled module. + if (shouldBundle) { + if (bundledHelpers.get(helper.name)) { + continue; + } + bundledHelpers.set(helper.name, true); + } + } + else if (bundle) { + // Skip the helper if it is scoped and we are emitting bundled helpers + continue; + } + if (typeof helper.text === "string") { + writeLines(helper.text); + } + else { + writeLines(helper.text(makeFileLevelOptimisticUniqueName)); + } + helpersEmitted = true; + } + } + } + return helpersEmitted; + } + // + // Literals/Pseudo-literals + // + // SyntaxKind.NumericLiteral + // SyntaxKind.BigIntLiteral + function emitNumericOrBigIntLiteral(node) { + emitLiteral(node); + } + // SyntaxKind.StringLiteral + // SyntaxKind.RegularExpressionLiteral + // SyntaxKind.NoSubstitutionTemplateLiteral + // SyntaxKind.TemplateHead + // SyntaxKind.TemplateMiddle + // SyntaxKind.TemplateTail + function emitLiteral(node) { + var text = getLiteralTextOfNode(node, printerOptions.neverAsciiEscape); + if ((printerOptions.sourceMap || printerOptions.inlineSourceMap) + && (node.kind === 10 /* StringLiteral */ || ts.isTemplateLiteralKind(node.kind))) { + writeLiteral(text); + } + else { + // Quick info expects all literals to be called with writeStringLiteral, as there's no specific type for numberLiterals + writeStringLiteral(text); + } + } + // SyntaxKind.UnparsedSource + function emitUnparsedSource(unparsed) { + writer.rawWrite(unparsed.text); + } + // + // Identifiers + // + function emitIdentifier(node) { + var writeText = node.symbol ? writeSymbol : write; + writeText(getTextOfNode(node, /*includeTrivia*/ false), node.symbol); + emitList(node, node.typeArguments, 53776 /* TypeParameters */); // Call emitList directly since it could be an array of TypeParameterDeclarations _or_ type arguments + } + // + // Names + // + function emitQualifiedName(node) { + emitEntityName(node.left); + writePunctuation("."); + emit(node.right); + } + function emitEntityName(node) { + if (node.kind === 72 /* Identifier */) { + emitExpression(node); + } + else { + emit(node); + } + } + function emitComputedPropertyName(node) { + writePunctuation("["); + emitExpression(node.expression); + writePunctuation("]"); + } + // + // Signature elements + // + function emitTypeParameter(node) { + emit(node.name); + if (node.constraint) { + writeSpace(); + writeKeyword("extends"); + writeSpace(); + emit(node.constraint); + } + if (node.default) { + writeSpace(); + writeOperator("="); + writeSpace(); + emit(node.default); + } + } + function emitParameter(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + emit(node.dotDotDotToken); + emitNodeWithWriter(node.name, writeParameter); + emit(node.questionToken); + if (node.parent && node.parent.kind === 289 /* JSDocFunctionType */ && !node.name) { + emit(node.type); + } + else { + emitTypeAnnotation(node.type); + } + // The comment position has to fallback to any present node within the parameterdeclaration because as it turns out, the parser can make parameter declarations with _just_ an initializer. + emitInitializer(node.initializer, node.type ? node.type.end : node.questionToken ? node.questionToken.end : node.name ? node.name.end : node.modifiers ? node.modifiers.end : node.decorators ? node.decorators.end : node.pos, node); + } + function emitDecorator(decorator) { + writePunctuation("@"); + emitExpression(decorator.expression); + } + // + // Type members + // + function emitPropertySignature(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + emitNodeWithWriter(node.name, writeProperty); + emit(node.questionToken); + emitTypeAnnotation(node.type); + writeTrailingSemicolon(); + } + function emitPropertyDeclaration(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + emit(node.name); + emit(node.questionToken); + emit(node.exclamationToken); + emitTypeAnnotation(node.type); + emitInitializer(node.initializer, node.type ? node.type.end : node.questionToken ? node.questionToken.end : node.name.end, node); + writeTrailingSemicolon(); + } + function emitMethodSignature(node) { + pushNameGenerationScope(node); + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + emit(node.name); + emit(node.questionToken); + emitTypeParameters(node, node.typeParameters); + emitParameters(node, node.parameters); + emitTypeAnnotation(node.type); + writeTrailingSemicolon(); + popNameGenerationScope(node); + } + function emitMethodDeclaration(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + emit(node.asteriskToken); + emit(node.name); + emit(node.questionToken); + emitSignatureAndBody(node, emitSignatureHead); + } + function emitConstructor(node) { + emitModifiers(node, node.modifiers); + writeKeyword("constructor"); + emitSignatureAndBody(node, emitSignatureHead); + } + function emitAccessorDeclaration(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + writeKeyword(node.kind === 158 /* GetAccessor */ ? "get" : "set"); + writeSpace(); + emit(node.name); + emitSignatureAndBody(node, emitSignatureHead); + } + function emitCallSignature(node) { + pushNameGenerationScope(node); + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + emitTypeParameters(node, node.typeParameters); + emitParameters(node, node.parameters); + emitTypeAnnotation(node.type); + writeTrailingSemicolon(); + popNameGenerationScope(node); + } + function emitConstructSignature(node) { + pushNameGenerationScope(node); + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + writeKeyword("new"); + writeSpace(); + emitTypeParameters(node, node.typeParameters); + emitParameters(node, node.parameters); + emitTypeAnnotation(node.type); + writeTrailingSemicolon(); + popNameGenerationScope(node); + } + function emitIndexSignature(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + emitParametersForIndexSignature(node, node.parameters); + emitTypeAnnotation(node.type); + writeTrailingSemicolon(); + } + function emitSemicolonClassElement() { + writeTrailingSemicolon(); + } + // + // Types + // + function emitTypePredicate(node) { + emit(node.parameterName); + writeSpace(); + writeKeyword("is"); + writeSpace(); + emit(node.type); + } + function emitTypeReference(node) { + emit(node.typeName); + emitTypeArguments(node, node.typeArguments); + } + function emitFunctionType(node) { + pushNameGenerationScope(node); + emitTypeParameters(node, node.typeParameters); + emitParametersForArrow(node, node.parameters); + writeSpace(); + writePunctuation("=>"); + writeSpace(); + emit(node.type); + popNameGenerationScope(node); + } + function emitJSDocFunctionType(node) { + writeKeyword("function"); + emitParameters(node, node.parameters); + writePunctuation(":"); + emit(node.type); + } + function emitJSDocNullableType(node) { + writePunctuation("?"); + emit(node.type); + } + function emitJSDocNonNullableType(node) { + writePunctuation("!"); + emit(node.type); + } + function emitJSDocOptionalType(node) { + emit(node.type); + writePunctuation("="); + } + function emitConstructorType(node) { + pushNameGenerationScope(node); + writeKeyword("new"); + writeSpace(); + emitTypeParameters(node, node.typeParameters); + emitParameters(node, node.parameters); + writeSpace(); + writePunctuation("=>"); + writeSpace(); + emit(node.type); + popNameGenerationScope(node); + } + function emitTypeQuery(node) { + writeKeyword("typeof"); + writeSpace(); + emit(node.exprName); + } + function emitTypeLiteral(node) { + writePunctuation("{"); + var flags = ts.getEmitFlags(node) & 1 /* SingleLine */ ? 768 /* SingleLineTypeLiteralMembers */ : 32897 /* MultiLineTypeLiteralMembers */; + emitList(node, node.members, flags | 524288 /* NoSpaceIfEmpty */); + writePunctuation("}"); + } + function emitArrayType(node) { + emit(node.elementType); + writePunctuation("["); + writePunctuation("]"); + } + function emitRestOrJSDocVariadicType(node) { + writePunctuation("..."); + emit(node.type); + } + function emitTupleType(node) { + writePunctuation("["); + emitList(node, node.elementTypes, 528 /* TupleTypeElements */); + writePunctuation("]"); + } + function emitOptionalType(node) { + emit(node.type); + writePunctuation("?"); + } + function emitUnionType(node) { + emitList(node, node.types, 516 /* UnionTypeConstituents */); + } + function emitIntersectionType(node) { + emitList(node, node.types, 520 /* IntersectionTypeConstituents */); + } + function emitConditionalType(node) { + emit(node.checkType); + writeSpace(); + writeKeyword("extends"); + writeSpace(); + emit(node.extendsType); + writeSpace(); + writePunctuation("?"); + writeSpace(); + emit(node.trueType); + writeSpace(); + writePunctuation(":"); + writeSpace(); + emit(node.falseType); + } + function emitInferType(node) { + writeKeyword("infer"); + writeSpace(); + emit(node.typeParameter); + } + function emitParenthesizedType(node) { + writePunctuation("("); + emit(node.type); + writePunctuation(")"); + } + function emitThisType() { + writeKeyword("this"); + } + function emitTypeOperator(node) { + writeTokenText(node.operator, writeKeyword); + writeSpace(); + emit(node.type); + } + function emitIndexedAccessType(node) { + emit(node.objectType); + writePunctuation("["); + emit(node.indexType); + writePunctuation("]"); + } + function emitMappedType(node) { + var emitFlags = ts.getEmitFlags(node); + writePunctuation("{"); + if (emitFlags & 1 /* SingleLine */) { + writeSpace(); + } + else { + writeLine(); + increaseIndent(); + } + if (node.readonlyToken) { + emit(node.readonlyToken); + if (node.readonlyToken.kind !== 133 /* ReadonlyKeyword */) { + writeKeyword("readonly"); + } + writeSpace(); + } + writePunctuation("["); + var pipelinePhase = getPipelinePhase(0 /* Notification */, node.typeParameter); + pipelinePhase(3 /* MappedTypeParameter */, node.typeParameter); + writePunctuation("]"); + if (node.questionToken) { + emit(node.questionToken); + if (node.questionToken.kind !== 56 /* QuestionToken */) { + writePunctuation("?"); + } + } + writePunctuation(":"); + writeSpace(); + emit(node.type); + writeTrailingSemicolon(); + if (emitFlags & 1 /* SingleLine */) { + writeSpace(); + } + else { + writeLine(); + decreaseIndent(); + } + writePunctuation("}"); + } + function emitLiteralType(node) { + emitExpression(node.literal); + } + function emitImportTypeNode(node) { + if (node.isTypeOf) { + writeKeyword("typeof"); + writeSpace(); + } + writeKeyword("import"); + writePunctuation("("); + emit(node.argument); + writePunctuation(")"); + if (node.qualifier) { + writePunctuation("."); + emit(node.qualifier); + } + emitTypeArguments(node, node.typeArguments); + } + // + // Binding patterns + // + function emitObjectBindingPattern(node) { + writePunctuation("{"); + emitList(node, node.elements, 525136 /* ObjectBindingPatternElements */); + writePunctuation("}"); + } + function emitArrayBindingPattern(node) { + writePunctuation("["); + emitList(node, node.elements, 524880 /* ArrayBindingPatternElements */); + writePunctuation("]"); + } + function emitBindingElement(node) { + emit(node.dotDotDotToken); + if (node.propertyName) { + emit(node.propertyName); + writePunctuation(":"); + writeSpace(); + } + emit(node.name); + emitInitializer(node.initializer, node.name.end, node); + } + // + // Expressions + // + function emitArrayLiteralExpression(node) { + var elements = node.elements; + var preferNewLine = node.multiLine ? 65536 /* PreferNewLine */ : 0 /* None */; + emitExpressionList(node, elements, 8914 /* ArrayLiteralExpressionElements */ | preferNewLine); + } + function emitObjectLiteralExpression(node) { + ts.forEach(node.properties, generateMemberNames); + var indentedFlag = ts.getEmitFlags(node) & 65536 /* Indented */; + if (indentedFlag) { + increaseIndent(); + } + var preferNewLine = node.multiLine ? 65536 /* PreferNewLine */ : 0 /* None */; + var allowTrailingComma = currentSourceFile.languageVersion >= 1 /* ES5 */ && !ts.isJsonSourceFile(currentSourceFile) ? 64 /* AllowTrailingComma */ : 0 /* None */; + emitList(node, node.properties, 526226 /* ObjectLiteralExpressionProperties */ | allowTrailingComma | preferNewLine); + if (indentedFlag) { + decreaseIndent(); + } + } + function emitPropertyAccessExpression(node) { + var indentBeforeDot = false; + var indentAfterDot = false; + if (!(ts.getEmitFlags(node) & 131072 /* NoIndentation */)) { + var dotRangeStart = node.expression.end; + var dotRangeEnd = ts.skipTrivia(currentSourceFile.text, node.expression.end) + 1; + var dotToken = ts.createToken(24 /* DotToken */); + dotToken.pos = dotRangeStart; + dotToken.end = dotRangeEnd; + indentBeforeDot = needsIndentation(node, node.expression, dotToken); + indentAfterDot = needsIndentation(node, dotToken, node.name); + } + emitExpression(node.expression); + increaseIndentIf(indentBeforeDot, /*writeSpaceIfNotIndenting*/ false); + var shouldEmitDotDot = !indentBeforeDot && needsDotDotForPropertyAccess(node.expression); + if (shouldEmitDotDot) { + writePunctuation("."); + } + emitTokenWithComment(24 /* DotToken */, node.expression.end, writePunctuation, node); + increaseIndentIf(indentAfterDot, /*writeSpaceIfNotIndenting*/ false); + emit(node.name); + decreaseIndentIf(indentBeforeDot, indentAfterDot); + } + // 1..toString is a valid property access, emit a dot after the literal + // Also emit a dot if expression is a integer const enum value - it will appear in generated code as numeric literal + function needsDotDotForPropertyAccess(expression) { + expression = ts.skipPartiallyEmittedExpressions(expression); + if (ts.isNumericLiteral(expression)) { + // check if numeric literal is a decimal literal that was originally written with a dot + var text = getLiteralTextOfNode(expression, /*neverAsciiEscape*/ true); + return !expression.numericLiteralFlags + && !ts.stringContains(text, ts.tokenToString(24 /* DotToken */)); + } + else if (ts.isPropertyAccessExpression(expression) || ts.isElementAccessExpression(expression)) { + // check if constant enum value is integer + var constantValue = ts.getConstantValue(expression); + // isFinite handles cases when constantValue is undefined + return typeof constantValue === "number" && isFinite(constantValue) + && Math.floor(constantValue) === constantValue + && printerOptions.removeComments; + } + } + function emitElementAccessExpression(node) { + emitExpression(node.expression); + emitTokenWithComment(22 /* OpenBracketToken */, node.expression.end, writePunctuation, node); + emitExpression(node.argumentExpression); + emitTokenWithComment(23 /* CloseBracketToken */, node.argumentExpression.end, writePunctuation, node); + } + function emitCallExpression(node) { + emitExpression(node.expression); + emitTypeArguments(node, node.typeArguments); + emitExpressionList(node, node.arguments, 2576 /* CallExpressionArguments */); + } + function emitNewExpression(node) { + emitTokenWithComment(95 /* NewKeyword */, node.pos, writeKeyword, node); + writeSpace(); + emitExpression(node.expression); + emitTypeArguments(node, node.typeArguments); + emitExpressionList(node, node.arguments, 18960 /* NewExpressionArguments */); + } + function emitTaggedTemplateExpression(node) { + emitExpression(node.tag); + emitTypeArguments(node, node.typeArguments); + writeSpace(); + emitExpression(node.template); + } + function emitTypeAssertionExpression(node) { + writePunctuation("<"); + emit(node.type); + writePunctuation(">"); + emitExpression(node.expression); + } + function emitParenthesizedExpression(node) { + var openParenPos = emitTokenWithComment(20 /* OpenParenToken */, node.pos, writePunctuation, node); + emitExpression(node.expression); + emitTokenWithComment(21 /* CloseParenToken */, node.expression ? node.expression.end : openParenPos, writePunctuation, node); + } + function emitFunctionExpression(node) { + generateNameIfNeeded(node.name); + emitFunctionDeclarationOrExpression(node); + } + function emitArrowFunction(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + emitSignatureAndBody(node, emitArrowFunctionHead); + } + function emitArrowFunctionHead(node) { + emitTypeParameters(node, node.typeParameters); + emitParametersForArrow(node, node.parameters); + emitTypeAnnotation(node.type); + writeSpace(); + emit(node.equalsGreaterThanToken); + } + function emitDeleteExpression(node) { + emitTokenWithComment(81 /* DeleteKeyword */, node.pos, writeKeyword, node); + writeSpace(); + emitExpression(node.expression); + } + function emitTypeOfExpression(node) { + emitTokenWithComment(104 /* TypeOfKeyword */, node.pos, writeKeyword, node); + writeSpace(); + emitExpression(node.expression); + } + function emitVoidExpression(node) { + emitTokenWithComment(106 /* VoidKeyword */, node.pos, writeKeyword, node); + writeSpace(); + emitExpression(node.expression); + } + function emitAwaitExpression(node) { + emitTokenWithComment(122 /* AwaitKeyword */, node.pos, writeKeyword, node); + writeSpace(); + emitExpression(node.expression); + } + function emitPrefixUnaryExpression(node) { + writeTokenText(node.operator, writeOperator); + if (shouldEmitWhitespaceBeforeOperand(node)) { + writeSpace(); + } + emitExpression(node.operand); + } + function shouldEmitWhitespaceBeforeOperand(node) { + // In some cases, we need to emit a space between the operator and the operand. One obvious case + // is when the operator is an identifier, like delete or typeof. We also need to do this for plus + // and minus expressions in certain cases. Specifically, consider the following two cases (parens + // are just for clarity of exposition, and not part of the source code): + // + // (+(+1)) + // (+(++1)) + // + // We need to emit a space in both cases. In the first case, the absence of a space will make + // the resulting expression a prefix increment operation. And in the second, it will make the resulting + // expression a prefix increment whose operand is a plus expression - (++(+x)) + // The same is true of minus of course. + var operand = node.operand; + return operand.kind === 202 /* PrefixUnaryExpression */ + && ((node.operator === 38 /* PlusToken */ && (operand.operator === 38 /* PlusToken */ || operand.operator === 44 /* PlusPlusToken */)) + || (node.operator === 39 /* MinusToken */ && (operand.operator === 39 /* MinusToken */ || operand.operator === 45 /* MinusMinusToken */))); + } + function emitPostfixUnaryExpression(node) { + emitExpression(node.operand); + writeTokenText(node.operator, writeOperator); + } + function emitBinaryExpression(node) { + var isCommaOperator = node.operatorToken.kind !== 27 /* CommaToken */; + var indentBeforeOperator = needsIndentation(node, node.left, node.operatorToken); + var indentAfterOperator = needsIndentation(node, node.operatorToken, node.right); + emitExpression(node.left); + increaseIndentIf(indentBeforeOperator, isCommaOperator); + emitLeadingCommentsOfPosition(node.operatorToken.pos); + writeTokenNode(node.operatorToken, node.operatorToken.kind === 93 /* InKeyword */ ? writeKeyword : writeOperator); + emitTrailingCommentsOfPosition(node.operatorToken.end, /*prefixSpace*/ true); // Binary operators should have a space before the comment starts + increaseIndentIf(indentAfterOperator, /*writeSpaceIfNotIndenting*/ true); + emitExpression(node.right); + decreaseIndentIf(indentBeforeOperator, indentAfterOperator); + } + function emitConditionalExpression(node) { + var indentBeforeQuestion = needsIndentation(node, node.condition, node.questionToken); + var indentAfterQuestion = needsIndentation(node, node.questionToken, node.whenTrue); + var indentBeforeColon = needsIndentation(node, node.whenTrue, node.colonToken); + var indentAfterColon = needsIndentation(node, node.colonToken, node.whenFalse); + emitExpression(node.condition); + increaseIndentIf(indentBeforeQuestion, /*writeSpaceIfNotIndenting*/ true); + emit(node.questionToken); + increaseIndentIf(indentAfterQuestion, /*writeSpaceIfNotIndenting*/ true); + emitExpression(node.whenTrue); + decreaseIndentIf(indentBeforeQuestion, indentAfterQuestion); + increaseIndentIf(indentBeforeColon, /*writeSpaceIfNotIndenting*/ true); + emit(node.colonToken); + increaseIndentIf(indentAfterColon, /*writeSpaceIfNotIndenting*/ true); + emitExpression(node.whenFalse); + decreaseIndentIf(indentBeforeColon, indentAfterColon); + } + function emitTemplateExpression(node) { + emit(node.head); + emitList(node, node.templateSpans, 262144 /* TemplateExpressionSpans */); + } + function emitYieldExpression(node) { + emitTokenWithComment(117 /* YieldKeyword */, node.pos, writeKeyword, node); + emit(node.asteriskToken); + emitExpressionWithLeadingSpace(node.expression); + } + function emitSpreadExpression(node) { + emitTokenWithComment(25 /* DotDotDotToken */, node.pos, writePunctuation, node); + emitExpression(node.expression); + } + function emitClassExpression(node) { + generateNameIfNeeded(node.name); + emitClassDeclarationOrExpression(node); + } + function emitExpressionWithTypeArguments(node) { + emitExpression(node.expression); + emitTypeArguments(node, node.typeArguments); + } + function emitAsExpression(node) { + emitExpression(node.expression); + if (node.type) { + writeSpace(); + writeKeyword("as"); + writeSpace(); + emit(node.type); + } + } + function emitNonNullExpression(node) { + emitExpression(node.expression); + writeOperator("!"); + } + function emitMetaProperty(node) { + writeToken(node.keywordToken, node.pos, writePunctuation); + writePunctuation("."); + emit(node.name); + } + // + // Misc + // + function emitTemplateSpan(node) { + emitExpression(node.expression); + emit(node.literal); + } + // + // Statements + // + function emitBlock(node) { + emitBlockStatements(node, /*forceSingleLine*/ !node.multiLine && isEmptyBlock(node)); + } + function emitBlockStatements(node, forceSingleLine) { + emitTokenWithComment(18 /* OpenBraceToken */, node.pos, writePunctuation, /*contextNode*/ node); + var format = forceSingleLine || ts.getEmitFlags(node) & 1 /* SingleLine */ ? 768 /* SingleLineBlockStatements */ : 129 /* MultiLineBlockStatements */; + emitList(node, node.statements, format); + emitTokenWithComment(19 /* CloseBraceToken */, node.statements.end, writePunctuation, /*contextNode*/ node, /*indentLeading*/ !!(format & 1 /* MultiLine */)); + } + function emitVariableStatement(node) { + emitModifiers(node, node.modifiers); + emit(node.declarationList); + writeTrailingSemicolon(); + } + function emitEmptyStatement(isEmbeddedStatement) { + // While most trailing semicolons are possibly insignificant, an embedded "empty" + // statement is significant and cannot be elided by a trailing-semicolon-omitting writer. + if (isEmbeddedStatement) { + writePunctuation(";"); + } + else { + writeTrailingSemicolon(); + } + } + function emitExpressionStatement(node) { + emitExpression(node.expression); + // Emit semicolon in non json files + // or if json file that created synthesized expression(eg.define expression statement when --out and amd code generation) + if (!ts.isJsonSourceFile(currentSourceFile) || ts.nodeIsSynthesized(node.expression)) { + writeTrailingSemicolon(); + } + } + function emitIfStatement(node) { + var openParenPos = emitTokenWithComment(91 /* IfKeyword */, node.pos, writeKeyword, node); + writeSpace(); + emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node); + emitExpression(node.expression); + emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node); + emitEmbeddedStatement(node, node.thenStatement); + if (node.elseStatement) { + writeLineOrSpace(node); + emitTokenWithComment(83 /* ElseKeyword */, node.thenStatement.end, writeKeyword, node); + if (node.elseStatement.kind === 222 /* IfStatement */) { + writeSpace(); + emit(node.elseStatement); + } + else { + emitEmbeddedStatement(node, node.elseStatement); + } + } + } + function emitWhileClause(node, startPos) { + var openParenPos = emitTokenWithComment(107 /* WhileKeyword */, startPos, writeKeyword, node); + writeSpace(); + emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node); + emitExpression(node.expression); + emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node); + } + function emitDoStatement(node) { + emitTokenWithComment(82 /* DoKeyword */, node.pos, writeKeyword, node); + emitEmbeddedStatement(node, node.statement); + if (ts.isBlock(node.statement)) { + writeSpace(); + } + else { + writeLineOrSpace(node); + } + emitWhileClause(node, node.statement.end); + writePunctuation(";"); + } + function emitWhileStatement(node) { + emitWhileClause(node, node.pos); + emitEmbeddedStatement(node, node.statement); + } + function emitForStatement(node) { + var openParenPos = emitTokenWithComment(89 /* ForKeyword */, node.pos, writeKeyword, node); + writeSpace(); + var pos = emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, /*contextNode*/ node); + emitForBinding(node.initializer); + pos = emitTokenWithComment(26 /* SemicolonToken */, node.initializer ? node.initializer.end : pos, writePunctuation, node); + emitExpressionWithLeadingSpace(node.condition); + pos = emitTokenWithComment(26 /* SemicolonToken */, node.condition ? node.condition.end : pos, writePunctuation, node); + emitExpressionWithLeadingSpace(node.incrementor); + emitTokenWithComment(21 /* CloseParenToken */, node.incrementor ? node.incrementor.end : pos, writePunctuation, node); + emitEmbeddedStatement(node, node.statement); + } + function emitForInStatement(node) { + var openParenPos = emitTokenWithComment(89 /* ForKeyword */, node.pos, writeKeyword, node); + writeSpace(); + emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node); + emitForBinding(node.initializer); + writeSpace(); + emitTokenWithComment(93 /* InKeyword */, node.initializer.end, writeKeyword, node); + writeSpace(); + emitExpression(node.expression); + emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node); + emitEmbeddedStatement(node, node.statement); + } + function emitForOfStatement(node) { + var openParenPos = emitTokenWithComment(89 /* ForKeyword */, node.pos, writeKeyword, node); + writeSpace(); + emitWithTrailingSpace(node.awaitModifier); + emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node); + emitForBinding(node.initializer); + writeSpace(); + emitTokenWithComment(147 /* OfKeyword */, node.initializer.end, writeKeyword, node); + writeSpace(); + emitExpression(node.expression); + emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node); + emitEmbeddedStatement(node, node.statement); + } + function emitForBinding(node) { + if (node !== undefined) { + if (node.kind === 238 /* VariableDeclarationList */) { + emit(node); + } + else { + emitExpression(node); + } + } + } + function emitContinueStatement(node) { + emitTokenWithComment(78 /* ContinueKeyword */, node.pos, writeKeyword, node); + emitWithLeadingSpace(node.label); + writeTrailingSemicolon(); + } + function emitBreakStatement(node) { + emitTokenWithComment(73 /* BreakKeyword */, node.pos, writeKeyword, node); + emitWithLeadingSpace(node.label); + writeTrailingSemicolon(); + } + function emitTokenWithComment(token, pos, writer, contextNode, indentLeading) { + var node = ts.getParseTreeNode(contextNode); + var isSimilarNode = node && node.kind === contextNode.kind; + var startPos = pos; + if (isSimilarNode) { + pos = ts.skipTrivia(currentSourceFile.text, pos); + } + if (emitLeadingCommentsOfPosition && isSimilarNode && contextNode.pos !== startPos) { + var needsIndent = indentLeading && !ts.positionsAreOnSameLine(startPos, pos, currentSourceFile); + if (needsIndent) { + increaseIndent(); + } + emitLeadingCommentsOfPosition(startPos); + if (needsIndent) { + decreaseIndent(); + } + } + pos = writeTokenText(token, writer, pos); + if (emitTrailingCommentsOfPosition && isSimilarNode && contextNode.end !== pos) { + emitTrailingCommentsOfPosition(pos, /*prefixSpace*/ true); + } + return pos; + } + function emitReturnStatement(node) { + emitTokenWithComment(97 /* ReturnKeyword */, node.pos, writeKeyword, /*contextNode*/ node); + emitExpressionWithLeadingSpace(node.expression); + writeTrailingSemicolon(); + } + function emitWithStatement(node) { + var openParenPos = emitTokenWithComment(108 /* WithKeyword */, node.pos, writeKeyword, node); + writeSpace(); + emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node); + emitExpression(node.expression); + emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node); + emitEmbeddedStatement(node, node.statement); + } + function emitSwitchStatement(node) { + var openParenPos = emitTokenWithComment(99 /* SwitchKeyword */, node.pos, writeKeyword, node); + writeSpace(); + emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node); + emitExpression(node.expression); + emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node); + writeSpace(); + emit(node.caseBlock); + } + function emitLabeledStatement(node) { + emit(node.label); + emitTokenWithComment(57 /* ColonToken */, node.label.end, writePunctuation, node); + writeSpace(); + emit(node.statement); + } + function emitThrowStatement(node) { + emitTokenWithComment(101 /* ThrowKeyword */, node.pos, writeKeyword, node); + emitExpressionWithLeadingSpace(node.expression); + writeTrailingSemicolon(); + } + function emitTryStatement(node) { + emitTokenWithComment(103 /* TryKeyword */, node.pos, writeKeyword, node); + writeSpace(); + emit(node.tryBlock); + if (node.catchClause) { + writeLineOrSpace(node); + emit(node.catchClause); + } + if (node.finallyBlock) { + writeLineOrSpace(node); + emitTokenWithComment(88 /* FinallyKeyword */, (node.catchClause || node.tryBlock).end, writeKeyword, node); + writeSpace(); + emit(node.finallyBlock); + } + } + function emitDebuggerStatement(node) { + writeToken(79 /* DebuggerKeyword */, node.pos, writeKeyword); + writeTrailingSemicolon(); + } + // + // Declarations + // + function emitVariableDeclaration(node) { + emit(node.name); + emitTypeAnnotation(node.type); + emitInitializer(node.initializer, node.type ? node.type.end : node.name.end, node); + } + function emitVariableDeclarationList(node) { + writeKeyword(ts.isLet(node) ? "let" : ts.isVarConst(node) ? "const" : "var"); + writeSpace(); + emitList(node, node.declarations, 528 /* VariableDeclarationList */); + } + function emitFunctionDeclaration(node) { + emitFunctionDeclarationOrExpression(node); + } + function emitFunctionDeclarationOrExpression(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + writeKeyword("function"); + emit(node.asteriskToken); + writeSpace(); + emitIdentifierName(node.name); // TODO: GH#18217 + emitSignatureAndBody(node, emitSignatureHead); + } + function emitBlockCallback(_hint, body) { + emitBlockFunctionBody(body); + } + function emitSignatureAndBody(node, emitSignatureHead) { + var body = node.body; + if (body) { + if (ts.isBlock(body)) { + var indentedFlag = ts.getEmitFlags(node) & 65536 /* Indented */; + if (indentedFlag) { + increaseIndent(); + } + pushNameGenerationScope(node); + ts.forEach(node.parameters, generateNames); + generateNames(node.body); + emitSignatureHead(node); + if (onEmitNode) { + onEmitNode(4 /* Unspecified */, body, emitBlockCallback); + } + else { + emitBlockFunctionBody(body); + } + popNameGenerationScope(node); + if (indentedFlag) { + decreaseIndent(); + } + } + else { + emitSignatureHead(node); + writeSpace(); + emitExpression(body); + } + } + else { + emitSignatureHead(node); + writeTrailingSemicolon(); + } + } + function emitSignatureHead(node) { + emitTypeParameters(node, node.typeParameters); + emitParameters(node, node.parameters); + emitTypeAnnotation(node.type); + } + function shouldEmitBlockFunctionBodyOnSingleLine(body) { + // We must emit a function body as a single-line body in the following case: + // * The body has NodeEmitFlags.SingleLine specified. + // We must emit a function body as a multi-line body in the following cases: + // * The body is explicitly marked as multi-line. + // * A non-synthesized body's start and end position are on different lines. + // * Any statement in the body starts on a new line. + if (ts.getEmitFlags(body) & 1 /* SingleLine */) { + return true; + } + if (body.multiLine) { + return false; + } + if (!ts.nodeIsSynthesized(body) && !ts.rangeIsOnSingleLine(body, currentSourceFile)) { + return false; + } + if (shouldWriteLeadingLineTerminator(body, body.statements, 2 /* PreserveLines */) + || shouldWriteClosingLineTerminator(body, body.statements, 2 /* PreserveLines */)) { + return false; + } + var previousStatement; + for (var _a = 0, _b = body.statements; _a < _b.length; _a++) { + var statement = _b[_a]; + if (shouldWriteSeparatingLineTerminator(previousStatement, statement, 2 /* PreserveLines */)) { + return false; + } + previousStatement = statement; + } + return true; + } + function emitBlockFunctionBody(body) { + writeSpace(); + writePunctuation("{"); + increaseIndent(); + var emitBlockFunctionBody = shouldEmitBlockFunctionBodyOnSingleLine(body) + ? emitBlockFunctionBodyOnSingleLine + : emitBlockFunctionBodyWorker; + if (emitBodyWithDetachedComments) { + emitBodyWithDetachedComments(body, body.statements, emitBlockFunctionBody); + } + else { + emitBlockFunctionBody(body); + } + decreaseIndent(); + writeToken(19 /* CloseBraceToken */, body.statements.end, writePunctuation, body); + } + function emitBlockFunctionBodyOnSingleLine(body) { + emitBlockFunctionBodyWorker(body, /*emitBlockFunctionBodyOnSingleLine*/ true); + } + function emitBlockFunctionBodyWorker(body, emitBlockFunctionBodyOnSingleLine) { + // Emit all the prologue directives (like "use strict"). + var statementOffset = emitPrologueDirectives(body.statements, /*startWithNewLine*/ true); + var pos = writer.getTextPos(); + emitHelpers(body); + if (statementOffset === 0 && pos === writer.getTextPos() && emitBlockFunctionBodyOnSingleLine) { + decreaseIndent(); + emitList(body, body.statements, 768 /* SingleLineFunctionBodyStatements */); + increaseIndent(); + } + else { + emitList(body, body.statements, 1 /* MultiLineFunctionBodyStatements */, statementOffset); + } + } + function emitClassDeclaration(node) { + emitClassDeclarationOrExpression(node); + } + function emitClassDeclarationOrExpression(node) { + ts.forEach(node.members, generateMemberNames); + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + writeKeyword("class"); + if (node.name) { + writeSpace(); + emitIdentifierName(node.name); + } + var indentedFlag = ts.getEmitFlags(node) & 65536 /* Indented */; + if (indentedFlag) { + increaseIndent(); + } + emitTypeParameters(node, node.typeParameters); + emitList(node, node.heritageClauses, 0 /* ClassHeritageClauses */); + writeSpace(); + writePunctuation("{"); + emitList(node, node.members, 129 /* ClassMembers */); + writePunctuation("}"); + if (indentedFlag) { + decreaseIndent(); + } + } + function emitInterfaceDeclaration(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + writeKeyword("interface"); + writeSpace(); + emit(node.name); + emitTypeParameters(node, node.typeParameters); + emitList(node, node.heritageClauses, 512 /* HeritageClauses */); + writeSpace(); + writePunctuation("{"); + emitList(node, node.members, 129 /* InterfaceMembers */); + writePunctuation("}"); + } + function emitTypeAliasDeclaration(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + writeKeyword("type"); + writeSpace(); + emit(node.name); + emitTypeParameters(node, node.typeParameters); + writeSpace(); + writePunctuation("="); + writeSpace(); + emit(node.type); + writeTrailingSemicolon(); + } + function emitEnumDeclaration(node) { + emitModifiers(node, node.modifiers); + writeKeyword("enum"); + writeSpace(); + emit(node.name); + writeSpace(); + writePunctuation("{"); + emitList(node, node.members, 145 /* EnumMembers */); + writePunctuation("}"); + } + function emitModuleDeclaration(node) { + emitModifiers(node, node.modifiers); + if (~node.flags & 512 /* GlobalAugmentation */) { + writeKeyword(node.flags & 16 /* Namespace */ ? "namespace" : "module"); + writeSpace(); + } + emit(node.name); + var body = node.body; + if (!body) + return writeTrailingSemicolon(); + while (body.kind === 244 /* ModuleDeclaration */) { + writePunctuation("."); + emit(body.name); + body = body.body; + } + writeSpace(); + emit(body); + } + function emitModuleBlock(node) { + pushNameGenerationScope(node); + ts.forEach(node.statements, generateNames); + emitBlockStatements(node, /*forceSingleLine*/ isEmptyBlock(node)); + popNameGenerationScope(node); + } + function emitCaseBlock(node) { + emitTokenWithComment(18 /* OpenBraceToken */, node.pos, writePunctuation, node); + emitList(node, node.clauses, 129 /* CaseBlockClauses */); + emitTokenWithComment(19 /* CloseBraceToken */, node.clauses.end, writePunctuation, node, /*indentLeading*/ true); + } + function emitImportEqualsDeclaration(node) { + emitModifiers(node, node.modifiers); + emitTokenWithComment(92 /* ImportKeyword */, node.modifiers ? node.modifiers.end : node.pos, writeKeyword, node); + writeSpace(); + emit(node.name); + writeSpace(); + emitTokenWithComment(59 /* EqualsToken */, node.name.end, writePunctuation, node); + writeSpace(); + emitModuleReference(node.moduleReference); + writeTrailingSemicolon(); + } + function emitModuleReference(node) { + if (node.kind === 72 /* Identifier */) { + emitExpression(node); + } + else { + emit(node); + } + } + function emitImportDeclaration(node) { + emitModifiers(node, node.modifiers); + emitTokenWithComment(92 /* ImportKeyword */, node.modifiers ? node.modifiers.end : node.pos, writeKeyword, node); + writeSpace(); + if (node.importClause) { + emit(node.importClause); + writeSpace(); + emitTokenWithComment(144 /* FromKeyword */, node.importClause.end, writeKeyword, node); + writeSpace(); + } + emitExpression(node.moduleSpecifier); + writeTrailingSemicolon(); + } + function emitImportClause(node) { + emit(node.name); + if (node.name && node.namedBindings) { + emitTokenWithComment(27 /* CommaToken */, node.name.end, writePunctuation, node); + writeSpace(); + } + emit(node.namedBindings); + } + function emitNamespaceImport(node) { + var asPos = emitTokenWithComment(40 /* AsteriskToken */, node.pos, writePunctuation, node); + writeSpace(); + emitTokenWithComment(119 /* AsKeyword */, asPos, writeKeyword, node); + writeSpace(); + emit(node.name); + } + function emitNamedImports(node) { + emitNamedImportsOrExports(node); + } + function emitImportSpecifier(node) { + emitImportOrExportSpecifier(node); + } + function emitExportAssignment(node) { + var nextPos = emitTokenWithComment(85 /* ExportKeyword */, node.pos, writeKeyword, node); + writeSpace(); + if (node.isExportEquals) { + emitTokenWithComment(59 /* EqualsToken */, nextPos, writeOperator, node); + } + else { + emitTokenWithComment(80 /* DefaultKeyword */, nextPos, writeKeyword, node); + } + writeSpace(); + emitExpression(node.expression); + writeTrailingSemicolon(); + } + function emitExportDeclaration(node) { + var nextPos = emitTokenWithComment(85 /* ExportKeyword */, node.pos, writeKeyword, node); + writeSpace(); + if (node.exportClause) { + emit(node.exportClause); + } + else { + nextPos = emitTokenWithComment(40 /* AsteriskToken */, nextPos, writePunctuation, node); + } + if (node.moduleSpecifier) { + writeSpace(); + var fromPos = node.exportClause ? node.exportClause.end : nextPos; + emitTokenWithComment(144 /* FromKeyword */, fromPos, writeKeyword, node); + writeSpace(); + emitExpression(node.moduleSpecifier); + } + writeTrailingSemicolon(); + } + function emitNamespaceExportDeclaration(node) { + var nextPos = emitTokenWithComment(85 /* ExportKeyword */, node.pos, writeKeyword, node); + writeSpace(); + nextPos = emitTokenWithComment(119 /* AsKeyword */, nextPos, writeKeyword, node); + writeSpace(); + nextPos = emitTokenWithComment(131 /* NamespaceKeyword */, nextPos, writeKeyword, node); + writeSpace(); + emit(node.name); + writeTrailingSemicolon(); + } + function emitNamedExports(node) { + emitNamedImportsOrExports(node); + } + function emitExportSpecifier(node) { + emitImportOrExportSpecifier(node); + } + function emitNamedImportsOrExports(node) { + writePunctuation("{"); + emitList(node, node.elements, 525136 /* NamedImportsOrExportsElements */); + writePunctuation("}"); + } + function emitImportOrExportSpecifier(node) { + if (node.propertyName) { + emit(node.propertyName); + writeSpace(); + emitTokenWithComment(119 /* AsKeyword */, node.propertyName.end, writeKeyword, node); + writeSpace(); + } + emit(node.name); + } + // + // Module references + // + function emitExternalModuleReference(node) { + writeKeyword("require"); + writePunctuation("("); + emitExpression(node.expression); + writePunctuation(")"); + } + // + // JSX + // + function emitJsxElement(node) { + emit(node.openingElement); + emitList(node, node.children, 262144 /* JsxElementOrFragmentChildren */); + emit(node.closingElement); + } + function emitJsxSelfClosingElement(node) { + writePunctuation("<"); + emitJsxTagName(node.tagName); + writeSpace(); + emit(node.attributes); + writePunctuation("/>"); + } + function emitJsxFragment(node) { + emit(node.openingFragment); + emitList(node, node.children, 262144 /* JsxElementOrFragmentChildren */); + emit(node.closingFragment); + } + function emitJsxOpeningElementOrFragment(node) { + writePunctuation("<"); + if (ts.isJsxOpeningElement(node)) { + emitJsxTagName(node.tagName); + if (node.attributes.properties && node.attributes.properties.length > 0) { + writeSpace(); + } + emit(node.attributes); + } + writePunctuation(">"); + } + function emitJsxText(node) { + writer.writeLiteral(getTextOfNode(node, /*includeTrivia*/ true)); + } + function emitJsxClosingElementOrFragment(node) { + writePunctuation(""); + } + function emitJsxAttributes(node) { + emitList(node, node.properties, 262656 /* JsxElementAttributes */); + } + function emitJsxAttribute(node) { + emit(node.name); + emitNodeWithPrefix("=", writePunctuation, node.initializer, emit); // TODO: GH#18217 + } + function emitJsxSpreadAttribute(node) { + writePunctuation("{..."); + emitExpression(node.expression); + writePunctuation("}"); + } + function emitJsxExpression(node) { + if (node.expression) { + writePunctuation("{"); + emit(node.dotDotDotToken); + emitExpression(node.expression); + writePunctuation("}"); + } + } + function emitJsxTagName(node) { + if (node.kind === 72 /* Identifier */) { + emitExpression(node); + } + else { + emit(node); + } + } + // + // Clauses + // + function emitCaseClause(node) { + emitTokenWithComment(74 /* CaseKeyword */, node.pos, writeKeyword, node); + writeSpace(); + emitExpression(node.expression); + emitCaseOrDefaultClauseRest(node, node.statements, node.expression.end); + } + function emitDefaultClause(node) { + var pos = emitTokenWithComment(80 /* DefaultKeyword */, node.pos, writeKeyword, node); + emitCaseOrDefaultClauseRest(node, node.statements, pos); + } + function emitCaseOrDefaultClauseRest(parentNode, statements, colonPos) { + var emitAsSingleStatement = statements.length === 1 && + ( + // treat synthesized nodes as located on the same line for emit purposes + ts.nodeIsSynthesized(parentNode) || + ts.nodeIsSynthesized(statements[0]) || + ts.rangeStartPositionsAreOnSameLine(parentNode, statements[0], currentSourceFile)); + var format = 163969 /* CaseOrDefaultClauseStatements */; + if (emitAsSingleStatement) { + writeToken(57 /* ColonToken */, colonPos, writePunctuation, parentNode); + writeSpace(); + format &= ~(1 /* MultiLine */ | 128 /* Indented */); + } + else { + emitTokenWithComment(57 /* ColonToken */, colonPos, writePunctuation, parentNode); + } + emitList(parentNode, statements, format); + } + function emitHeritageClause(node) { + writeSpace(); + writeTokenText(node.token, writeKeyword); + writeSpace(); + emitList(node, node.types, 528 /* HeritageClauseTypes */); + } + function emitCatchClause(node) { + var openParenPos = emitTokenWithComment(75 /* CatchKeyword */, node.pos, writeKeyword, node); + writeSpace(); + if (node.variableDeclaration) { + emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node); + emit(node.variableDeclaration); + emitTokenWithComment(21 /* CloseParenToken */, node.variableDeclaration.end, writePunctuation, node); + writeSpace(); + } + emit(node.block); + } + // + // Property assignments + // + function emitPropertyAssignment(node) { + emit(node.name); + writePunctuation(":"); + writeSpace(); + // This is to ensure that we emit comment in the following case: + // For example: + // obj = { + // id: /*comment1*/ ()=>void + // } + // "comment1" is not considered to be leading comment for node.initializer + // but rather a trailing comment on the previous node. + var initializer = node.initializer; + if (emitTrailingCommentsOfPosition && (ts.getEmitFlags(initializer) & 512 /* NoLeadingComments */) === 0) { + var commentRange = ts.getCommentRange(initializer); + emitTrailingCommentsOfPosition(commentRange.pos); + } + emitExpression(initializer); + } + function emitShorthandPropertyAssignment(node) { + emit(node.name); + if (node.objectAssignmentInitializer) { + writeSpace(); + writePunctuation("="); + writeSpace(); + emitExpression(node.objectAssignmentInitializer); + } + } + function emitSpreadAssignment(node) { + if (node.expression) { + emitTokenWithComment(25 /* DotDotDotToken */, node.pos, writePunctuation, node); + emitExpression(node.expression); + } + } + // + // Enum + // + function emitEnumMember(node) { + emit(node.name); + emitInitializer(node.initializer, node.name.end, node); + } + // + // JSDoc + // + function emitJSDoc(node) { + write("/**"); + if (node.comment) { + var lines = node.comment.split(/\r\n?|\n/g); + for (var _a = 0, lines_2 = lines; _a < lines_2.length; _a++) { + var line = lines_2[_a]; + writeLine(); + writeSpace(); + writePunctuation("*"); + writeSpace(); + write(line); + } + } + if (node.tags) { + if (node.tags.length === 1 && node.tags[0].kind === 302 /* JSDocTypeTag */ && !node.comment) { + writeSpace(); + emit(node.tags[0]); + } + else { + emitList(node, node.tags, 33 /* JSDocComment */); + } + } + writeSpace(); + write("*/"); + } + function emitJSDocSimpleTypedTag(tag) { + emitJSDocTagName(tag.tagName); + emitJSDocTypeExpression(tag.typeExpression); + emitJSDocComment(tag.comment); + } + function emitJSDocAugmentsTag(tag) { + emitJSDocTagName(tag.tagName); + writeSpace(); + writePunctuation("{"); + emit(tag.class); + writePunctuation("}"); + emitJSDocComment(tag.comment); + } + function emitJSDocTemplateTag(tag) { + emitJSDocTagName(tag.tagName); + emitJSDocTypeExpression(tag.constraint); + writeSpace(); + emitList(tag, tag.typeParameters, 528 /* CommaListElements */); + emitJSDocComment(tag.comment); + } + function emitJSDocTypedefTag(tag) { + emitJSDocTagName(tag.tagName); + if (tag.typeExpression) { + if (tag.typeExpression.kind === 283 /* JSDocTypeExpression */) { + emitJSDocTypeExpression(tag.typeExpression); + } + else { + writeSpace(); + writePunctuation("{"); + write("Object"); + if (tag.typeExpression.isArrayType) { + writePunctuation("["); + writePunctuation("]"); + } + writePunctuation("}"); + } + } + if (tag.fullName) { + writeSpace(); + emit(tag.fullName); + } + emitJSDocComment(tag.comment); + if (tag.typeExpression && tag.typeExpression.kind === 292 /* JSDocTypeLiteral */) { + emitJSDocTypeLiteral(tag.typeExpression); + } + } + function emitJSDocCallbackTag(tag) { + emitJSDocTagName(tag.tagName); + if (tag.name) { + writeSpace(); + emit(tag.name); + } + emitJSDocComment(tag.comment); + emitJSDocSignature(tag.typeExpression); + } + function emitJSDocSimpleTag(tag) { + emitJSDocTagName(tag.tagName); + emitJSDocComment(tag.comment); + } + function emitJSDocTypeLiteral(lit) { + emitList(lit, ts.createNodeArray(lit.jsDocPropertyTags), 33 /* JSDocComment */); + } + function emitJSDocSignature(sig) { + if (sig.typeParameters) { + emitList(sig, ts.createNodeArray(sig.typeParameters), 33 /* JSDocComment */); + } + if (sig.parameters) { + emitList(sig, ts.createNodeArray(sig.parameters), 33 /* JSDocComment */); + } + if (sig.type) { + writeLine(); + writeSpace(); + writePunctuation("*"); + writeSpace(); + emit(sig.type); + } + } + function emitJSDocPropertyLikeTag(param) { + emitJSDocTagName(param.tagName); + emitJSDocTypeExpression(param.typeExpression); + writeSpace(); + if (param.isBracketed) { + writePunctuation("["); + } + emit(param.name); + if (param.isBracketed) { + writePunctuation("]"); + } + emitJSDocComment(param.comment); + } + function emitJSDocTagName(tagName) { + writePunctuation("@"); + emit(tagName); + } + function emitJSDocComment(comment) { + if (comment) { + writeSpace(); + write(comment); + } + } + function emitJSDocTypeExpression(typeExpression) { + if (typeExpression) { + writeSpace(); + writePunctuation("{"); + emit(typeExpression.type); + writePunctuation("}"); + } + } + // + // Top-level nodes + // + function emitSourceFile(node) { + writeLine(); + var statements = node.statements; + if (emitBodyWithDetachedComments) { + // Emit detached comment if there are no prologue directives or if the first node is synthesized. + // The synthesized node will have no leading comment so some comments may be missed. + var shouldEmitDetachedComment = statements.length === 0 || + !ts.isPrologueDirective(statements[0]) || + ts.nodeIsSynthesized(statements[0]); + if (shouldEmitDetachedComment) { + emitBodyWithDetachedComments(node, statements, emitSourceFileWorker); + return; + } + } + emitSourceFileWorker(node); + } + function emitSyntheticTripleSlashReferencesIfNeeded(node) { + emitTripleSlashDirectives(!!node.hasNoDefaultLib, node.syntheticFileReferences || [], node.syntheticTypeReferences || [], node.syntheticLibReferences || []); + } + function emitTripleSlashDirectivesIfNeeded(node) { + if (node.isDeclarationFile) + emitTripleSlashDirectives(node.hasNoDefaultLib, node.referencedFiles, node.typeReferenceDirectives, node.libReferenceDirectives); + } + function emitTripleSlashDirectives(hasNoDefaultLib, files, types, libs) { + if (hasNoDefaultLib) { + writeComment("/// "); + writeLine(); + } + if (currentSourceFile && currentSourceFile.moduleName) { + writeComment("/// "); + writeLine(); + } + if (currentSourceFile && currentSourceFile.amdDependencies) { + for (var _a = 0, _b = currentSourceFile.amdDependencies; _a < _b.length; _a++) { + var dep = _b[_a]; + if (dep.name) { + writeComment("/// "); + } + else { + writeComment("/// "); + } + writeLine(); + } + } + for (var _c = 0, files_1 = files; _c < files_1.length; _c++) { + var directive = files_1[_c]; + writeComment("/// "); + writeLine(); + } + for (var _d = 0, types_18 = types; _d < types_18.length; _d++) { + var directive = types_18[_d]; + writeComment("/// "); + writeLine(); + } + for (var _e = 0, libs_1 = libs; _e < libs_1.length; _e++) { + var directive = libs_1[_e]; + writeComment("/// "); + writeLine(); + } + } + function emitSourceFileWorker(node) { + var statements = node.statements; + pushNameGenerationScope(node); + ts.forEach(node.statements, generateNames); + emitHelpers(node); + var index = ts.findIndex(statements, function (statement) { return !ts.isPrologueDirective(statement); }); + emitTripleSlashDirectivesIfNeeded(node); + emitList(node, statements, 1 /* MultiLine */, index === -1 ? statements.length : index); + popNameGenerationScope(node); + } + // Transformation nodes + function emitPartiallyEmittedExpression(node) { + emitExpression(node.expression); + } + function emitCommaList(node) { + emitExpressionList(node, node.elements, 528 /* CommaListElements */); + } + /** + * Emits any prologue directives at the start of a Statement list, returning the + * number of prologue directives written to the output. + */ + function emitPrologueDirectives(statements, startWithNewLine, seenPrologueDirectives) { + for (var i = 0; i < statements.length; i++) { + var statement = statements[i]; + if (ts.isPrologueDirective(statement)) { + var shouldEmitPrologueDirective = seenPrologueDirectives ? !seenPrologueDirectives.has(statement.expression.text) : true; + if (shouldEmitPrologueDirective) { + if (startWithNewLine || i > 0) { + writeLine(); + } + emit(statement); + if (seenPrologueDirectives) { + seenPrologueDirectives.set(statement.expression.text, true); + } + } + } + else { + // return index of the first non prologue directive + return i; + } + } + return statements.length; + } + function emitPrologueDirectivesIfNeeded(sourceFileOrBundle) { + if (ts.isSourceFile(sourceFileOrBundle)) { + setSourceFile(sourceFileOrBundle); + emitPrologueDirectives(sourceFileOrBundle.statements); + } + else { + var seenPrologueDirectives = ts.createMap(); + for (var _a = 0, _b = sourceFileOrBundle.sourceFiles; _a < _b.length; _a++) { + var sourceFile = _b[_a]; + setSourceFile(sourceFile); + emitPrologueDirectives(sourceFile.statements, /*startWithNewLine*/ true, seenPrologueDirectives); + } + setSourceFile(undefined); + } + } + function emitShebangIfNeeded(sourceFileOrBundle) { + if (ts.isSourceFile(sourceFileOrBundle)) { + var shebang = ts.getShebang(sourceFileOrBundle.text); + if (shebang) { + writeComment(shebang); + writeLine(); + return true; + } + } + else { + for (var _a = 0, _b = sourceFileOrBundle.sourceFiles; _a < _b.length; _a++) { + var sourceFile = _b[_a]; + // Emit only the first encountered shebang + if (emitShebangIfNeeded(sourceFile)) { + break; + } + } + } + } + // + // Helpers + // + function emitNodeWithWriter(node, writer) { + if (!node) + return; + var savedWrite = write; + write = writer; + emit(node); + write = savedWrite; + } + function emitModifiers(node, modifiers) { + if (modifiers && modifiers.length) { + emitList(node, modifiers, 262656 /* Modifiers */); + writeSpace(); + } + } + function emitTypeAnnotation(node) { + if (node) { + writePunctuation(":"); + writeSpace(); + emit(node); + } + } + function emitInitializer(node, equalCommentStartPos, container) { + if (node) { + writeSpace(); + emitTokenWithComment(59 /* EqualsToken */, equalCommentStartPos, writeOperator, container); + writeSpace(); + emitExpression(node); + } + } + function emitNodeWithPrefix(prefix, prefixWriter, node, emit) { + if (node) { + prefixWriter(prefix); + emit(node); + } + } + function emitWithLeadingSpace(node) { + if (node) { + writeSpace(); + emit(node); + } + } + function emitExpressionWithLeadingSpace(node) { + if (node) { + writeSpace(); + emitExpression(node); + } + } + function emitWithTrailingSpace(node) { + if (node) { + emit(node); + writeSpace(); + } + } + function emitEmbeddedStatement(parent, node) { + if (ts.isBlock(node) || ts.getEmitFlags(parent) & 1 /* SingleLine */) { + writeSpace(); + emit(node); + } + else { + writeLine(); + increaseIndent(); + if (ts.isEmptyStatement(node)) { + var pipelinePhase = getPipelinePhase(0 /* Notification */, node); + pipelinePhase(5 /* EmbeddedStatement */, node); + } + else { + emit(node); + } + decreaseIndent(); + } + } + function emitDecorators(parentNode, decorators) { + emitList(parentNode, decorators, 49153 /* Decorators */); + } + function emitTypeArguments(parentNode, typeArguments) { + emitList(parentNode, typeArguments, 53776 /* TypeArguments */); + } + function emitTypeParameters(parentNode, typeParameters) { + if (ts.isFunctionLike(parentNode) && parentNode.typeArguments) { // Quick info uses type arguments in place of type parameters on instantiated signatures + return emitTypeArguments(parentNode, parentNode.typeArguments); + } + emitList(parentNode, typeParameters, 53776 /* TypeParameters */); + } + function emitParameters(parentNode, parameters) { + emitList(parentNode, parameters, 2576 /* Parameters */); + } + function canEmitSimpleArrowHead(parentNode, parameters) { + var parameter = ts.singleOrUndefined(parameters); + return parameter + && parameter.pos === parentNode.pos // may not have parsed tokens between parent and parameter + && ts.isArrowFunction(parentNode) // only arrow functions may have simple arrow head + && !parentNode.type // arrow function may not have return type annotation + && !ts.some(parentNode.decorators) // parent may not have decorators + && !ts.some(parentNode.modifiers) // parent may not have modifiers + && !ts.some(parentNode.typeParameters) // parent may not have type parameters + && !ts.some(parameter.decorators) // parameter may not have decorators + && !ts.some(parameter.modifiers) // parameter may not have modifiers + && !parameter.dotDotDotToken // parameter may not be rest + && !parameter.questionToken // parameter may not be optional + && !parameter.type // parameter may not have a type annotation + && !parameter.initializer // parameter may not have an initializer + && ts.isIdentifier(parameter.name); // parameter name must be identifier + } + function emitParametersForArrow(parentNode, parameters) { + if (canEmitSimpleArrowHead(parentNode, parameters)) { + emitList(parentNode, parameters, 2576 /* Parameters */ & ~2048 /* Parenthesis */); + } + else { + emitParameters(parentNode, parameters); + } + } + function emitParametersForIndexSignature(parentNode, parameters) { + emitList(parentNode, parameters, 8848 /* IndexSignatureParameters */); + } + function emitList(parentNode, children, format, start, count) { + emitNodeList(emit, parentNode, children, format, start, count); + } + function emitExpressionList(parentNode, children, format, start, count) { + emitNodeList(emitExpression, parentNode, children, format, start, count); // TODO: GH#18217 + } + function writeDelimiter(format) { + switch (format & 60 /* DelimitersMask */) { + case 0 /* None */: + break; + case 16 /* CommaDelimited */: + writePunctuation(","); + break; + case 4 /* BarDelimited */: + writeSpace(); + writePunctuation("|"); + break; + case 32 /* AsteriskDelimited */: + writeSpace(); + writePunctuation("*"); + writeSpace(); + break; + case 8 /* AmpersandDelimited */: + writeSpace(); + writePunctuation("&"); + break; + } + } + function emitNodeList(emit, parentNode, children, format, start, count) { + if (start === void 0) { start = 0; } + if (count === void 0) { count = children ? children.length - start : 0; } + var isUndefined = children === undefined; + if (isUndefined && format & 16384 /* OptionalIfUndefined */) { + return; + } + var isEmpty = children === undefined || start >= children.length || count === 0; + if (isEmpty && format & 32768 /* OptionalIfEmpty */) { + if (onBeforeEmitNodeArray) { + onBeforeEmitNodeArray(children); + } + if (onAfterEmitNodeArray) { + onAfterEmitNodeArray(children); + } + return; + } + if (format & 15360 /* BracketsMask */) { + writePunctuation(getOpeningBracket(format)); + if (isEmpty && !isUndefined) { + // TODO: GH#18217 + emitTrailingCommentsOfPosition(children.pos, /*prefixSpace*/ true); // Emit comments within empty bracketed lists + } + } + if (onBeforeEmitNodeArray) { + onBeforeEmitNodeArray(children); + } + if (isEmpty) { + // Write a line terminator if the parent node was multi-line + if (format & 1 /* MultiLine */) { + writeLine(); + } + else if (format & 256 /* SpaceBetweenBraces */ && !(format & 524288 /* NoSpaceIfEmpty */)) { + writeSpace(); + } + } + else { + // Write the opening line terminator or leading whitespace. + var mayEmitInterveningComments = (format & 262144 /* NoInterveningComments */) === 0; + var shouldEmitInterveningComments = mayEmitInterveningComments; + if (shouldWriteLeadingLineTerminator(parentNode, children, format)) { // TODO: GH#18217 + writeLine(); + shouldEmitInterveningComments = false; + } + else if (format & 256 /* SpaceBetweenBraces */) { + writeSpace(); + } + // Increase the indent, if requested. + if (format & 128 /* Indented */) { + increaseIndent(); + } + // Emit each child. + var previousSibling = void 0; + var shouldDecreaseIndentAfterEmit = false; + for (var i = 0; i < count; i++) { + var child = children[start + i]; + // Write the delimiter if this is not the first node. + if (format & 32 /* AsteriskDelimited */) { + // always write JSDoc in the format "\n *" + writeLine(); + writeDelimiter(format); + } + else if (previousSibling) { + // i.e + // function commentedParameters( + // /* Parameter a */ + // a + // /* End of parameter a */ -> this comment isn't considered to be trailing comment of parameter "a" due to newline + // , + if (format & 60 /* DelimitersMask */ && previousSibling.end !== parentNode.end) { + emitLeadingCommentsOfPosition(previousSibling.end); + } + writeDelimiter(format); + // Write either a line terminator or whitespace to separate the elements. + if (shouldWriteSeparatingLineTerminator(previousSibling, child, format)) { + // If a synthesized node in a single-line list starts on a new + // line, we should increase the indent. + if ((format & (3 /* LinesMask */ | 128 /* Indented */)) === 0 /* SingleLine */) { + increaseIndent(); + shouldDecreaseIndentAfterEmit = true; + } + writeLine(); + shouldEmitInterveningComments = false; + } + else if (previousSibling && format & 512 /* SpaceBetweenSiblings */) { + writeSpace(); + } + } + // Emit this child. + if (shouldEmitInterveningComments) { + if (emitTrailingCommentsOfPosition) { + var commentRange = ts.getCommentRange(child); + emitTrailingCommentsOfPosition(commentRange.pos); + } + } + else { + shouldEmitInterveningComments = mayEmitInterveningComments; + } + emit(child); + if (shouldDecreaseIndentAfterEmit) { + decreaseIndent(); + shouldDecreaseIndentAfterEmit = false; + } + previousSibling = child; + } + // Write a trailing comma, if requested. + var hasTrailingComma = (format & 64 /* AllowTrailingComma */) && children.hasTrailingComma; + if (format & 16 /* CommaDelimited */ && hasTrailingComma) { + writePunctuation(","); + } + // Emit any trailing comment of the last element in the list + // i.e + // var array = [... + // 2 + // /* end of element 2 */ + // ]; + if (previousSibling && format & 60 /* DelimitersMask */ && previousSibling.end !== parentNode.end && !(ts.getEmitFlags(previousSibling) & 1024 /* NoTrailingComments */)) { + emitLeadingCommentsOfPosition(previousSibling.end); + } + // Decrease the indent, if requested. + if (format & 128 /* Indented */) { + decreaseIndent(); + } + // Write the closing line terminator or closing whitespace. + if (shouldWriteClosingLineTerminator(parentNode, children, format)) { + writeLine(); + } + else if (format & 256 /* SpaceBetweenBraces */) { + writeSpace(); + } + } + if (onAfterEmitNodeArray) { + onAfterEmitNodeArray(children); + } + if (format & 15360 /* BracketsMask */) { + if (isEmpty && !isUndefined) { + // TODO: GH#18217 + emitLeadingCommentsOfPosition(children.end); // Emit leading comments within empty lists + } + writePunctuation(getClosingBracket(format)); + } + } + // Writers + function writeLiteral(s) { + writer.writeLiteral(s); + } + function writeStringLiteral(s) { + writer.writeStringLiteral(s); + } + function writeBase(s) { + writer.write(s); + } + function writeSymbol(s, sym) { + writer.writeSymbol(s, sym); + } + function writePunctuation(s) { + writer.writePunctuation(s); + } + function writeTrailingSemicolon() { + writer.writeTrailingSemicolon(";"); + } + function writeKeyword(s) { + writer.writeKeyword(s); + } + function writeOperator(s) { + writer.writeOperator(s); + } + function writeParameter(s) { + writer.writeParameter(s); + } + function writeComment(s) { + writer.writeComment(s); + } + function writeSpace() { + writer.writeSpace(" "); + } + function writeProperty(s) { + writer.writeProperty(s); + } + function writeLine() { + writer.writeLine(); + } + function increaseIndent() { + writer.increaseIndent(); + } + function decreaseIndent() { + writer.decreaseIndent(); + } + function writeToken(token, pos, writer, contextNode) { + return !sourceMapsDisabled + ? emitTokenWithSourceMap(contextNode, token, writer, pos, writeTokenText) + : writeTokenText(token, writer, pos); + } + function writeTokenNode(node, writer) { + if (onBeforeEmitToken) { + onBeforeEmitToken(node); + } + writer(ts.tokenToString(node.kind)); + if (onAfterEmitToken) { + onAfterEmitToken(node); + } + } + function writeTokenText(token, writer, pos) { + var tokenString = ts.tokenToString(token); + writer(tokenString); + return pos < 0 ? pos : pos + tokenString.length; + } + function writeLineOrSpace(node) { + if (ts.getEmitFlags(node) & 1 /* SingleLine */) { + writeSpace(); + } + else { + writeLine(); + } + } + function writeLines(text) { + var lines = text.split(/\r\n?|\n/g); + var indentation = ts.guessIndentation(lines); + for (var _a = 0, lines_3 = lines; _a < lines_3.length; _a++) { + var lineText = lines_3[_a]; + var line = indentation ? lineText.slice(indentation) : lineText; + if (line.length) { + writeLine(); + write(line); + writer.rawWrite(newLine); + } + } + } + function increaseIndentIf(value, writeSpaceIfNotIndenting) { + if (value) { + increaseIndent(); + writeLine(); + } + else if (writeSpaceIfNotIndenting) { + writeSpace(); + } + } + // Helper function to decrease the indent if we previously indented. Allows multiple + // previous indent values to be considered at a time. This also allows caller to just + // call this once, passing in all their appropriate indent values, instead of needing + // to call this helper function multiple times. + function decreaseIndentIf(value1, value2) { + if (value1) { + decreaseIndent(); + } + if (value2) { + decreaseIndent(); + } + } + function shouldWriteLeadingLineTerminator(parentNode, children, format) { + if (format & 1 /* MultiLine */) { + return true; + } + if (format & 2 /* PreserveLines */) { + if (format & 65536 /* PreferNewLine */) { + return true; + } + var firstChild = children[0]; + if (firstChild === undefined) { + return !ts.rangeIsOnSingleLine(parentNode, currentSourceFile); + } + else if (ts.positionIsSynthesized(parentNode.pos) || ts.nodeIsSynthesized(firstChild)) { + return synthesizedNodeStartsOnNewLine(firstChild, format); + } + else { + return !ts.rangeStartPositionsAreOnSameLine(parentNode, firstChild, currentSourceFile); + } + } + else { + return false; + } + } + function shouldWriteSeparatingLineTerminator(previousNode, nextNode, format) { + if (format & 1 /* MultiLine */) { + return true; + } + else if (format & 2 /* PreserveLines */) { + if (previousNode === undefined || nextNode === undefined) { + return false; + } + else if (ts.nodeIsSynthesized(previousNode) || ts.nodeIsSynthesized(nextNode)) { + return synthesizedNodeStartsOnNewLine(previousNode, format) || synthesizedNodeStartsOnNewLine(nextNode, format); + } + else { + return !ts.rangeEndIsOnSameLineAsRangeStart(previousNode, nextNode, currentSourceFile); + } + } + else { + return ts.getStartsOnNewLine(nextNode); + } + } + function shouldWriteClosingLineTerminator(parentNode, children, format) { + if (format & 1 /* MultiLine */) { + return (format & 131072 /* NoTrailingNewLine */) === 0; + } + else if (format & 2 /* PreserveLines */) { + if (format & 65536 /* PreferNewLine */) { + return true; + } + var lastChild = ts.lastOrUndefined(children); + if (lastChild === undefined) { + return !ts.rangeIsOnSingleLine(parentNode, currentSourceFile); + } + else if (ts.positionIsSynthesized(parentNode.pos) || ts.nodeIsSynthesized(lastChild)) { + return synthesizedNodeStartsOnNewLine(lastChild, format); + } + else { + return !ts.rangeEndPositionsAreOnSameLine(parentNode, lastChild, currentSourceFile); + } + } + else { + return false; + } + } + function synthesizedNodeStartsOnNewLine(node, format) { + if (ts.nodeIsSynthesized(node)) { + var startsOnNewLine = ts.getStartsOnNewLine(node); + if (startsOnNewLine === undefined) { + return (format & 65536 /* PreferNewLine */) !== 0; + } + return startsOnNewLine; + } + return (format & 65536 /* PreferNewLine */) !== 0; + } + function needsIndentation(parent, node1, node2) { + parent = skipSynthesizedParentheses(parent); + node1 = skipSynthesizedParentheses(node1); + node2 = skipSynthesizedParentheses(node2); + // Always use a newline for synthesized code if the synthesizer desires it. + if (ts.getStartsOnNewLine(node2)) { + return true; + } + return !ts.nodeIsSynthesized(parent) + && !ts.nodeIsSynthesized(node1) + && !ts.nodeIsSynthesized(node2) + && !ts.rangeEndIsOnSameLineAsRangeStart(node1, node2, currentSourceFile); + } + function isEmptyBlock(block) { + return block.statements.length === 0 + && ts.rangeEndIsOnSameLineAsRangeStart(block, block, currentSourceFile); + } + function skipSynthesizedParentheses(node) { + while (node.kind === 195 /* ParenthesizedExpression */ && ts.nodeIsSynthesized(node)) { + node = node.expression; + } + return node; + } + function getTextOfNode(node, includeTrivia) { + if (ts.isGeneratedIdentifier(node)) { + return generateName(node); + } + else if (ts.isIdentifier(node) && (ts.nodeIsSynthesized(node) || !node.parent || !currentSourceFile || (node.parent && currentSourceFile && ts.getSourceFileOfNode(node) !== ts.getOriginalNode(currentSourceFile)))) { + return ts.idText(node); + } + else if (node.kind === 10 /* StringLiteral */ && node.textSourceNode) { + return getTextOfNode(node.textSourceNode, includeTrivia); + } + else if (ts.isLiteralExpression(node) && (ts.nodeIsSynthesized(node) || !node.parent)) { + return node.text; + } + return ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node, includeTrivia); + } + function getLiteralTextOfNode(node, neverAsciiEscape) { + if (node.kind === 10 /* StringLiteral */ && node.textSourceNode) { + var textSourceNode = node.textSourceNode; + if (ts.isIdentifier(textSourceNode)) { + return neverAsciiEscape || (ts.getEmitFlags(node) & 16777216 /* NoAsciiEscaping */) ? + "\"" + ts.escapeString(getTextOfNode(textSourceNode)) + "\"" : + "\"" + ts.escapeNonAsciiString(getTextOfNode(textSourceNode)) + "\""; + } + else { + return getLiteralTextOfNode(textSourceNode, neverAsciiEscape); + } + } + return ts.getLiteralText(node, currentSourceFile, neverAsciiEscape); + } + /** + * Push a new name generation scope. + */ + function pushNameGenerationScope(node) { + if (node && ts.getEmitFlags(node) & 524288 /* ReuseTempVariableScope */) { + return; + } + tempFlagsStack.push(tempFlags); + tempFlags = 0; + reservedNamesStack.push(reservedNames); + } + /** + * Pop the current name generation scope. + */ + function popNameGenerationScope(node) { + if (node && ts.getEmitFlags(node) & 524288 /* ReuseTempVariableScope */) { + return; + } + tempFlags = tempFlagsStack.pop(); + reservedNames = reservedNamesStack.pop(); + } + function reserveNameInNestedScopes(name) { + if (!reservedNames || reservedNames === ts.lastOrUndefined(reservedNamesStack)) { + reservedNames = ts.createMap(); + } + reservedNames.set(name, true); + } + function generateNames(node) { + if (!node) + return; + switch (node.kind) { + case 218 /* Block */: + ts.forEach(node.statements, generateNames); + break; + case 233 /* LabeledStatement */: + case 231 /* WithStatement */: + case 223 /* DoStatement */: + case 224 /* WhileStatement */: + generateNames(node.statement); + break; + case 222 /* IfStatement */: + generateNames(node.thenStatement); + generateNames(node.elseStatement); + break; + case 225 /* ForStatement */: + case 227 /* ForOfStatement */: + case 226 /* ForInStatement */: + generateNames(node.initializer); + generateNames(node.statement); + break; + case 232 /* SwitchStatement */: + generateNames(node.caseBlock); + break; + case 246 /* CaseBlock */: + ts.forEach(node.clauses, generateNames); + break; + case 271 /* CaseClause */: + case 272 /* DefaultClause */: + ts.forEach(node.statements, generateNames); + break; + case 235 /* TryStatement */: + generateNames(node.tryBlock); + generateNames(node.catchClause); + generateNames(node.finallyBlock); + break; + case 274 /* CatchClause */: + generateNames(node.variableDeclaration); + generateNames(node.block); + break; + case 219 /* VariableStatement */: + generateNames(node.declarationList); + break; + case 238 /* VariableDeclarationList */: + ts.forEach(node.declarations, generateNames); + break; + case 237 /* VariableDeclaration */: + case 151 /* Parameter */: + case 186 /* BindingElement */: + case 240 /* ClassDeclaration */: + generateNameIfNeeded(node.name); + break; + case 239 /* FunctionDeclaration */: + generateNameIfNeeded(node.name); + if (ts.getEmitFlags(node) & 524288 /* ReuseTempVariableScope */) { + ts.forEach(node.parameters, generateNames); + generateNames(node.body); + } + break; + case 184 /* ObjectBindingPattern */: + case 185 /* ArrayBindingPattern */: + ts.forEach(node.elements, generateNames); + break; + case 249 /* ImportDeclaration */: + generateNames(node.importClause); + break; + case 250 /* ImportClause */: + generateNameIfNeeded(node.name); + generateNames(node.namedBindings); + break; + case 251 /* NamespaceImport */: + generateNameIfNeeded(node.name); + break; + case 252 /* NamedImports */: + ts.forEach(node.elements, generateNames); + break; + case 253 /* ImportSpecifier */: + generateNameIfNeeded(node.propertyName || node.name); + break; + } + } + function generateMemberNames(node) { + if (!node) + return; + switch (node.kind) { + case 275 /* PropertyAssignment */: + case 276 /* ShorthandPropertyAssignment */: + case 154 /* PropertyDeclaration */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + generateNameIfNeeded(node.name); + break; + } + } + function generateNameIfNeeded(name) { + if (name) { + if (ts.isGeneratedIdentifier(name)) { + generateName(name); + } + else if (ts.isBindingPattern(name)) { + generateNames(name); + } + } + } + /** + * Generate the text for a generated identifier. + */ + function generateName(name) { + if ((name.autoGenerateFlags & 7 /* KindMask */) === 4 /* Node */) { + // Node names generate unique names based on their original node + // and are cached based on that node's id. + return generateNameCached(getNodeForGeneratedName(name), name.autoGenerateFlags); + } + else { + // Auto, Loop, and Unique names are cached based on their unique + // autoGenerateId. + var autoGenerateId = name.autoGenerateId; + return autoGeneratedIdToGeneratedName[autoGenerateId] || (autoGeneratedIdToGeneratedName[autoGenerateId] = makeName(name)); + } + } + function generateNameCached(node, flags) { + var nodeId = ts.getNodeId(node); + return nodeIdToGeneratedName[nodeId] || (nodeIdToGeneratedName[nodeId] = generateNameForNode(node, flags)); + } + /** + * Returns a value indicating whether a name is unique globally, within the current file, + * or within the NameGenerator. + */ + function isUniqueName(name) { + return isFileLevelUniqueName(name) + && !generatedNames.has(name) + && !(reservedNames && reservedNames.has(name)); + } + /** + * Returns a value indicating whether a name is unique globally or within the current file. + */ + function isFileLevelUniqueName(name) { + return currentSourceFile ? ts.isFileLevelUniqueName(currentSourceFile, name, hasGlobalName) : true; + } + /** + * Returns a value indicating whether a name is unique within a container. + */ + function isUniqueLocalName(name, container) { + for (var node = container; ts.isNodeDescendantOf(node, container); node = node.nextContainer) { + if (node.locals) { + var local = node.locals.get(ts.escapeLeadingUnderscores(name)); + // We conservatively include alias symbols to cover cases where they're emitted as locals + if (local && local.flags & (67220415 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */)) { + return false; + } + } + } + return true; + } + /** + * Return the next available name in the pattern _a ... _z, _0, _1, ... + * TempFlags._i or TempFlags._n may be used to express a preference for that dedicated name. + * Note that names generated by makeTempVariableName and makeUniqueName will never conflict. + */ + function makeTempVariableName(flags, reservedInNestedScopes) { + if (flags && !(tempFlags & flags)) { + var name = flags === 268435456 /* _i */ ? "_i" : "_n"; + if (isUniqueName(name)) { + tempFlags |= flags; + if (reservedInNestedScopes) { + reserveNameInNestedScopes(name); + } + return name; + } + } + while (true) { + var count = tempFlags & 268435455 /* CountMask */; + tempFlags++; + // Skip over 'i' and 'n' + if (count !== 8 && count !== 13) { + var name = count < 26 + ? "_" + String.fromCharCode(97 /* a */ + count) + : "_" + (count - 26); + if (isUniqueName(name)) { + if (reservedInNestedScopes) { + reserveNameInNestedScopes(name); + } + return name; + } + } + } + } + /** + * Generate a name that is unique within the current file and doesn't conflict with any names + * in global scope. The name is formed by adding an '_n' suffix to the specified base name, + * where n is a positive integer. Note that names generated by makeTempVariableName and + * makeUniqueName are guaranteed to never conflict. + * If `optimistic` is set, the first instance will use 'baseName' verbatim instead of 'baseName_1' + */ + function makeUniqueName(baseName, checkFn, optimistic, scoped) { + if (checkFn === void 0) { checkFn = isUniqueName; } + if (optimistic) { + if (checkFn(baseName)) { + if (scoped) { + reserveNameInNestedScopes(baseName); + } + else { + generatedNames.set(baseName, true); + } + return baseName; + } + } + // Find the first unique 'name_n', where n is a positive number + if (baseName.charCodeAt(baseName.length - 1) !== 95 /* _ */) { + baseName += "_"; + } + var i = 1; + while (true) { + var generatedName = baseName + i; + if (checkFn(generatedName)) { + if (scoped) { + reserveNameInNestedScopes(generatedName); + } + else { + generatedNames.set(generatedName, true); + } + return generatedName; + } + i++; + } + } + function makeFileLevelOptimisticUniqueName(name) { + return makeUniqueName(name, isFileLevelUniqueName, /*optimistic*/ true); + } + /** + * Generates a unique name for a ModuleDeclaration or EnumDeclaration. + */ + function generateNameForModuleOrEnum(node) { + var name = getTextOfNode(node.name); + // Use module/enum name itself if it is unique, otherwise make a unique variation + return isUniqueLocalName(name, node) ? name : makeUniqueName(name); + } + /** + * Generates a unique name for an ImportDeclaration or ExportDeclaration. + */ + function generateNameForImportOrExportDeclaration(node) { + var expr = ts.getExternalModuleName(node); // TODO: GH#18217 + var baseName = ts.isStringLiteral(expr) ? + ts.makeIdentifierFromModuleName(expr.text) : "module"; + return makeUniqueName(baseName); + } + /** + * Generates a unique name for a default export. + */ + function generateNameForExportDefault() { + return makeUniqueName("default"); + } + /** + * Generates a unique name for a class expression. + */ + function generateNameForClassExpression() { + return makeUniqueName("class"); + } + function generateNameForMethodOrAccessor(node) { + if (ts.isIdentifier(node.name)) { + return generateNameCached(node.name); + } + return makeTempVariableName(0 /* Auto */); + } + /** + * Generates a unique name from a node. + */ + function generateNameForNode(node, flags) { + switch (node.kind) { + case 72 /* Identifier */: + return makeUniqueName(getTextOfNode(node), isUniqueName, !!(flags & 16 /* Optimistic */), !!(flags & 8 /* ReservedInNestedScopes */)); + case 244 /* ModuleDeclaration */: + case 243 /* EnumDeclaration */: + return generateNameForModuleOrEnum(node); + case 249 /* ImportDeclaration */: + case 255 /* ExportDeclaration */: + return generateNameForImportOrExportDeclaration(node); + case 239 /* FunctionDeclaration */: + case 240 /* ClassDeclaration */: + case 254 /* ExportAssignment */: + return generateNameForExportDefault(); + case 209 /* ClassExpression */: + return generateNameForClassExpression(); + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + return generateNameForMethodOrAccessor(node); + default: + return makeTempVariableName(0 /* Auto */); + } + } + /** + * Generates a unique identifier for a node. + */ + function makeName(name) { + switch (name.autoGenerateFlags & 7 /* KindMask */) { + case 1 /* Auto */: + return makeTempVariableName(0 /* Auto */, !!(name.autoGenerateFlags & 8 /* ReservedInNestedScopes */)); + case 2 /* Loop */: + return makeTempVariableName(268435456 /* _i */, !!(name.autoGenerateFlags & 8 /* ReservedInNestedScopes */)); + case 3 /* Unique */: + return makeUniqueName(ts.idText(name), (name.autoGenerateFlags & 32 /* FileLevel */) ? isFileLevelUniqueName : isUniqueName, !!(name.autoGenerateFlags & 16 /* Optimistic */), !!(name.autoGenerateFlags & 8 /* ReservedInNestedScopes */)); + } + return ts.Debug.fail("Unsupported GeneratedIdentifierKind."); + } + /** + * Gets the node from which a name should be generated. + */ + function getNodeForGeneratedName(name) { + var autoGenerateId = name.autoGenerateId; + var node = name; + var original = node.original; + while (original) { + node = original; + // if "node" is a different generated name (having a different + // "autoGenerateId"), use it and stop traversing. + if (ts.isIdentifier(node) + && !!(node.autoGenerateFlags & 4 /* Node */) + && node.autoGenerateId !== autoGenerateId) { + break; + } + original = node.original; + } + // otherwise, return the original node for the source; + return node; + } + // Comments + function pipelineEmitWithComments(hint, node) { + enterComment(); + hasWrittenComment = false; + var emitFlags = ts.getEmitFlags(node); + var _a = ts.getCommentRange(node), pos = _a.pos, end = _a.end; + var isEmittedNode = node.kind !== 307 /* NotEmittedStatement */; + // We have to explicitly check that the node is JsxText because if the compilerOptions.jsx is "preserve" we will not do any transformation. + // It is expensive to walk entire tree just to set one kind of node to have no comments. + var skipLeadingComments = pos < 0 || (emitFlags & 512 /* NoLeadingComments */) !== 0 || node.kind === 11 /* JsxText */; + var skipTrailingComments = end < 0 || (emitFlags & 1024 /* NoTrailingComments */) !== 0 || node.kind === 11 /* JsxText */; + // Save current container state on the stack. + var savedContainerPos = containerPos; + var savedContainerEnd = containerEnd; + var savedDeclarationListContainerEnd = declarationListContainerEnd; + if ((pos > 0 || end > 0) && pos !== end) { + // Emit leading comments if the position is not synthesized and the node + // has not opted out from emitting leading comments. + if (!skipLeadingComments) { + emitLeadingComments(pos, isEmittedNode); + } + if (!skipLeadingComments || (pos >= 0 && (emitFlags & 512 /* NoLeadingComments */) !== 0)) { + // Advance the container position if comments get emitted or if they've been disabled explicitly using NoLeadingComments. + containerPos = pos; + } + if (!skipTrailingComments || (end >= 0 && (emitFlags & 1024 /* NoTrailingComments */) !== 0)) { + // As above. + containerEnd = end; + // To avoid invalid comment emit in a down-level binding pattern, we + // keep track of the last declaration list container's end + if (node.kind === 238 /* VariableDeclarationList */) { + declarationListContainerEnd = end; + } + } + } + ts.forEach(ts.getSyntheticLeadingComments(node), emitLeadingSynthesizedComment); + exitComment(); + var pipelinePhase = getNextPipelinePhase(2 /* Comments */, node); + if (emitFlags & 2048 /* NoNestedComments */) { + commentsDisabled = true; + pipelinePhase(hint, node); + commentsDisabled = false; + } + else { + pipelinePhase(hint, node); + } + enterComment(); + ts.forEach(ts.getSyntheticTrailingComments(node), emitTrailingSynthesizedComment); + if ((pos > 0 || end > 0) && pos !== end) { + // Restore previous container state. + containerPos = savedContainerPos; + containerEnd = savedContainerEnd; + declarationListContainerEnd = savedDeclarationListContainerEnd; + // Emit trailing comments if the position is not synthesized and the node + // has not opted out from emitting leading comments and is an emitted node. + if (!skipTrailingComments && isEmittedNode) { + emitTrailingComments(end); + } + } + exitComment(); + } + function emitLeadingSynthesizedComment(comment) { + if (comment.kind === 2 /* SingleLineCommentTrivia */) { + writer.writeLine(); + } + writeSynthesizedComment(comment); + if (comment.hasTrailingNewLine || comment.kind === 2 /* SingleLineCommentTrivia */) { + writer.writeLine(); + } + else { + writer.writeSpace(" "); + } + } + function emitTrailingSynthesizedComment(comment) { + if (!writer.isAtStartOfLine()) { + writer.writeSpace(" "); + } + writeSynthesizedComment(comment); + if (comment.hasTrailingNewLine) { + writer.writeLine(); + } + } + function writeSynthesizedComment(comment) { + var text = formatSynthesizedComment(comment); + var lineMap = comment.kind === 3 /* MultiLineCommentTrivia */ ? ts.computeLineStarts(text) : undefined; + ts.writeCommentRange(text, lineMap, writer, 0, text.length, newLine); + } + function formatSynthesizedComment(comment) { + return comment.kind === 3 /* MultiLineCommentTrivia */ + ? "/*" + comment.text + "*/" + : "//" + comment.text; + } + function emitBodyWithDetachedComments(node, detachedRange, emitCallback) { + enterComment(); + var pos = detachedRange.pos, end = detachedRange.end; + var emitFlags = ts.getEmitFlags(node); + var skipLeadingComments = pos < 0 || (emitFlags & 512 /* NoLeadingComments */) !== 0; + var skipTrailingComments = commentsDisabled || end < 0 || (emitFlags & 1024 /* NoTrailingComments */) !== 0; + if (!skipLeadingComments) { + emitDetachedCommentsAndUpdateCommentsInfo(detachedRange); + } + exitComment(); + if (emitFlags & 2048 /* NoNestedComments */ && !commentsDisabled) { + commentsDisabled = true; + emitCallback(node); + commentsDisabled = false; + } + else { + emitCallback(node); + } + enterComment(); + if (!skipTrailingComments) { + emitLeadingComments(detachedRange.end, /*isEmittedNode*/ true); + if (hasWrittenComment && !writer.isAtStartOfLine()) { + writer.writeLine(); + } + } + exitComment(); + } + function emitLeadingComments(pos, isEmittedNode) { + hasWrittenComment = false; + if (isEmittedNode) { + forEachLeadingCommentToEmit(pos, emitLeadingComment); + } + else if (pos === 0) { + // If the node will not be emitted in JS, remove all the comments(normal, pinned and ///) associated with the node, + // unless it is a triple slash comment at the top of the file. + // For Example: + // /// + // declare var x; + // /// + // interface F {} + // The first /// will NOT be removed while the second one will be removed even though both node will not be emitted + forEachLeadingCommentToEmit(pos, emitTripleSlashLeadingComment); + } + } + function emitTripleSlashLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos) { + if (isTripleSlashComment(commentPos, commentEnd)) { + emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos); + } + } + function shouldWriteComment(text, pos) { + if (printerOptions.onlyPrintJsDocStyle) { + return (ts.isJSDocLikeText(text, pos) || ts.isPinnedComment(text, pos)); + } + return true; + } + function emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos) { + if (!shouldWriteComment(currentSourceFile.text, commentPos)) + return; + if (!hasWrittenComment) { + ts.emitNewLineBeforeLeadingCommentOfPosition(getCurrentLineMap(), writer, rangePos, commentPos); + hasWrittenComment = true; + } + // Leading comments are emitted at /*leading comment1 */space/*leading comment*/space + emitPos(commentPos); + ts.writeCommentRange(currentSourceFile.text, getCurrentLineMap(), writer, commentPos, commentEnd, newLine); + emitPos(commentEnd); + if (hasTrailingNewLine) { + writer.writeLine(); + } + else if (kind === 3 /* MultiLineCommentTrivia */) { + writer.writeSpace(" "); + } + } + function emitLeadingCommentsOfPosition(pos) { + if (commentsDisabled || pos === -1) { + return; + } + emitLeadingComments(pos, /*isEmittedNode*/ true); + } + function emitTrailingComments(pos) { + forEachTrailingCommentToEmit(pos, emitTrailingComment); + } + function emitTrailingComment(commentPos, commentEnd, _kind, hasTrailingNewLine) { + if (!shouldWriteComment(currentSourceFile.text, commentPos)) + return; + // trailing comments are emitted at space/*trailing comment1 */space/*trailing comment2*/ + if (!writer.isAtStartOfLine()) { + writer.writeSpace(" "); + } + emitPos(commentPos); + ts.writeCommentRange(currentSourceFile.text, getCurrentLineMap(), writer, commentPos, commentEnd, newLine); + emitPos(commentEnd); + if (hasTrailingNewLine) { + writer.writeLine(); + } + } + function emitTrailingCommentsOfPosition(pos, prefixSpace) { + if (commentsDisabled) { + return; + } + enterComment(); + forEachTrailingCommentToEmit(pos, prefixSpace ? emitTrailingComment : emitTrailingCommentOfPosition); + exitComment(); + } + function emitTrailingCommentOfPosition(commentPos, commentEnd, _kind, hasTrailingNewLine) { + // trailing comments of a position are emitted at /*trailing comment1 */space/*trailing comment*/space + emitPos(commentPos); + ts.writeCommentRange(currentSourceFile.text, getCurrentLineMap(), writer, commentPos, commentEnd, newLine); + emitPos(commentEnd); + if (hasTrailingNewLine) { + writer.writeLine(); + } + else { + writer.writeSpace(" "); + } + } + function forEachLeadingCommentToEmit(pos, cb) { + // Emit the leading comments only if the container's pos doesn't match because the container should take care of emitting these comments + if (currentSourceFile && (containerPos === -1 || pos !== containerPos)) { + if (hasDetachedComments(pos)) { + forEachLeadingCommentWithoutDetachedComments(cb); + } + else { + ts.forEachLeadingCommentRange(currentSourceFile.text, pos, cb, /*state*/ pos); + } + } + } + function forEachTrailingCommentToEmit(end, cb) { + // Emit the trailing comments only if the container's end doesn't match because the container should take care of emitting these comments + if (currentSourceFile && (containerEnd === -1 || (end !== containerEnd && end !== declarationListContainerEnd))) { + ts.forEachTrailingCommentRange(currentSourceFile.text, end, cb); + } + } + function hasDetachedComments(pos) { + return detachedCommentsInfo !== undefined && ts.last(detachedCommentsInfo).nodePos === pos; + } + function forEachLeadingCommentWithoutDetachedComments(cb) { + // get the leading comments from detachedPos + var pos = ts.last(detachedCommentsInfo).detachedCommentEndPos; + if (detachedCommentsInfo.length - 1) { + detachedCommentsInfo.pop(); + } + else { + detachedCommentsInfo = undefined; + } + ts.forEachLeadingCommentRange(currentSourceFile.text, pos, cb, /*state*/ pos); + } + function emitDetachedCommentsAndUpdateCommentsInfo(range) { + var currentDetachedCommentInfo = ts.emitDetachedComments(currentSourceFile.text, getCurrentLineMap(), writer, emitComment, range, newLine, commentsDisabled); + if (currentDetachedCommentInfo) { + if (detachedCommentsInfo) { + detachedCommentsInfo.push(currentDetachedCommentInfo); + } + else { + detachedCommentsInfo = [currentDetachedCommentInfo]; + } + } + } + function emitComment(text, lineMap, writer, commentPos, commentEnd, newLine) { + if (!shouldWriteComment(currentSourceFile.text, commentPos)) + return; + emitPos(commentPos); + ts.writeCommentRange(text, lineMap, writer, commentPos, commentEnd, newLine); + emitPos(commentEnd); + } + /** + * Determine if the given comment is a triple-slash + * + * @return true if the comment is a triple-slash comment else false + */ + function isTripleSlashComment(commentPos, commentEnd) { + return ts.isRecognizedTripleSlashComment(currentSourceFile.text, commentPos, commentEnd); + } + // Source Maps + function pipelineEmitWithSourceMap(hint, node) { + var pipelinePhase = getNextPipelinePhase(3 /* SourceMaps */, node); + if (ts.isUnparsedSource(node) && node.sourceMapText !== undefined) { + var parsed = ts.tryParseRawSourceMap(node.sourceMapText); + if (parsed) { + sourceMapGenerator.appendSourceMap(writer.getLine(), writer.getColumn(), parsed, node.sourceMapPath); + } + pipelinePhase(hint, node); + } + else { + var _a = ts.getSourceMapRange(node), pos = _a.pos, end = _a.end, _b = _a.source, source = _b === void 0 ? sourceMapSource : _b; + var emitFlags = ts.getEmitFlags(node); + if (node.kind !== 307 /* NotEmittedStatement */ + && (emitFlags & 16 /* NoLeadingSourceMap */) === 0 + && pos >= 0) { + emitSourcePos(source, skipSourceTrivia(source, pos)); + } + if (emitFlags & 64 /* NoNestedSourceMaps */) { + sourceMapsDisabled = true; + pipelinePhase(hint, node); + sourceMapsDisabled = false; + } + else { + pipelinePhase(hint, node); + } + if (node.kind !== 307 /* NotEmittedStatement */ + && (emitFlags & 32 /* NoTrailingSourceMap */) === 0 + && end >= 0) { + emitSourcePos(source, end); + } + } + } + /** + * Skips trivia such as comments and white-space that can optionally overriden by the source map source + */ + function skipSourceTrivia(source, pos) { + return source.skipTrivia ? source.skipTrivia(pos) : ts.skipTrivia(sourceMapSource.text, pos); + } + /** + * Emits a mapping. + * + * If the position is synthetic (undefined or a negative value), no mapping will be + * created. + * + * @param pos The position. + */ + function emitPos(pos) { + if (sourceMapsDisabled || ts.positionIsSynthesized(pos) || isJsonSourceMapSource(sourceMapSource)) { + return; + } + var _a = ts.getLineAndCharacterOfPosition(currentSourceFile, pos), sourceLine = _a.line, sourceCharacter = _a.character; + sourceMapGenerator.addMapping(writer.getLine(), writer.getColumn(), sourceMapSourceIndex, sourceLine, sourceCharacter, + /*nameIndex*/ undefined); + } + function emitSourcePos(source, pos) { + if (source !== sourceMapSource) { + var savedSourceMapSource = sourceMapSource; + setSourceMapSource(source); + emitPos(pos); + setSourceMapSource(savedSourceMapSource); + } + else { + emitPos(pos); + } + } + /** + * Emits a token of a node with possible leading and trailing source maps. + * + * @param node The node containing the token. + * @param token The token to emit. + * @param tokenStartPos The start pos of the token. + * @param emitCallback The callback used to emit the token. + */ + function emitTokenWithSourceMap(node, token, writer, tokenPos, emitCallback) { + if (sourceMapsDisabled || node && ts.isInJsonFile(node)) { + return emitCallback(token, writer, tokenPos); + } + var emitNode = node && node.emitNode; + var emitFlags = emitNode && emitNode.flags || 0 /* None */; + var range = emitNode && emitNode.tokenSourceMapRanges && emitNode.tokenSourceMapRanges[token]; + var source = range && range.source || sourceMapSource; + tokenPos = skipSourceTrivia(source, range ? range.pos : tokenPos); + if ((emitFlags & 128 /* NoTokenLeadingSourceMaps */) === 0 && tokenPos >= 0) { + emitSourcePos(source, tokenPos); + } + tokenPos = emitCallback(token, writer, tokenPos); + if (range) + tokenPos = range.end; + if ((emitFlags & 256 /* NoTokenTrailingSourceMaps */) === 0 && tokenPos >= 0) { + emitSourcePos(source, tokenPos); + } + return tokenPos; + } + function setSourceMapSource(source) { + if (sourceMapsDisabled) { + return; + } + sourceMapSource = source; + if (isJsonSourceMapSource(source)) { + return; + } + sourceMapSourceIndex = sourceMapGenerator.addSource(source.fileName); + if (printerOptions.inlineSources) { + sourceMapGenerator.setSourceContent(sourceMapSourceIndex, source.text); + } + } + function isJsonSourceMapSource(sourceFile) { + return ts.fileExtensionIs(sourceFile.fileName, ".json" /* Json */); + } + } + ts.createPrinter = createPrinter; + function createBracketsMap() { + var brackets = []; + brackets[1024 /* Braces */] = ["{", "}"]; + brackets[2048 /* Parenthesis */] = ["(", ")"]; + brackets[4096 /* AngleBrackets */] = ["<", ">"]; + brackets[8192 /* SquareBrackets */] = ["[", "]"]; + return brackets; + } + function getOpeningBracket(format) { + return brackets[format & 15360 /* BracketsMask */][0]; + } + function getClosingBracket(format) { + return brackets[format & 15360 /* BracketsMask */][1]; + } + // Flags enum to track count of temp variables and a few dedicated names + var TempFlags; + (function (TempFlags) { + TempFlags[TempFlags["Auto"] = 0] = "Auto"; + TempFlags[TempFlags["CountMask"] = 268435455] = "CountMask"; + TempFlags[TempFlags["_i"] = 268435456] = "_i"; + })(TempFlags || (TempFlags = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + function createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensitiveFileNames) { + if (!host.getDirectories || !host.readDirectory) { + return undefined; + } + var cachedReadDirectoryResult = ts.createMap(); + var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); + return { + useCaseSensitiveFileNames: useCaseSensitiveFileNames, + fileExists: fileExists, + readFile: function (path, encoding) { return host.readFile(path, encoding); }, + directoryExists: host.directoryExists && directoryExists, + getDirectories: getDirectories, + readDirectory: readDirectory, + createDirectory: host.createDirectory && createDirectory, + writeFile: host.writeFile && writeFile, + addOrDeleteFileOrDirectory: addOrDeleteFileOrDirectory, + addOrDeleteFile: addOrDeleteFile, + clearCache: clearCache + }; + function toPath(fileName) { + return ts.toPath(fileName, currentDirectory, getCanonicalFileName); + } + function getCachedFileSystemEntries(rootDirPath) { + return cachedReadDirectoryResult.get(ts.ensureTrailingDirectorySeparator(rootDirPath)); + } + function getCachedFileSystemEntriesForBaseDir(path) { + return getCachedFileSystemEntries(ts.getDirectoryPath(path)); + } + function getBaseNameOfFileName(fileName) { + return ts.getBaseFileName(ts.normalizePath(fileName)); + } + function createCachedFileSystemEntries(rootDir, rootDirPath) { + var resultFromHost = { + files: ts.map(host.readDirectory(rootDir, /*extensions*/ undefined, /*exclude*/ undefined, /*include*/ ["*.*"]), getBaseNameOfFileName) || [], + directories: host.getDirectories(rootDir) || [] + }; + cachedReadDirectoryResult.set(ts.ensureTrailingDirectorySeparator(rootDirPath), resultFromHost); + return resultFromHost; + } + /** + * If the readDirectory result was already cached, it returns that + * Otherwise gets result from host and caches it. + * The host request is done under try catch block to avoid caching incorrect result + */ + function tryReadDirectory(rootDir, rootDirPath) { + rootDirPath = ts.ensureTrailingDirectorySeparator(rootDirPath); + var cachedResult = getCachedFileSystemEntries(rootDirPath); + if (cachedResult) { + return cachedResult; + } + try { + return createCachedFileSystemEntries(rootDir, rootDirPath); + } + catch (_e) { + // If there is exception to read directories, dont cache the result and direct the calls to host + ts.Debug.assert(!cachedReadDirectoryResult.has(ts.ensureTrailingDirectorySeparator(rootDirPath))); + return undefined; + } + } + function fileNameEqual(name1, name2) { + return getCanonicalFileName(name1) === getCanonicalFileName(name2); + } + function hasEntry(entries, name) { + return ts.some(entries, function (file) { return fileNameEqual(file, name); }); + } + function updateFileSystemEntry(entries, baseName, isValid) { + if (hasEntry(entries, baseName)) { + if (!isValid) { + return ts.filterMutate(entries, function (entry) { return !fileNameEqual(entry, baseName); }); + } + } + else if (isValid) { + return entries.push(baseName); + } + } + function writeFile(fileName, data, writeByteOrderMark) { + var path = toPath(fileName); + var result = getCachedFileSystemEntriesForBaseDir(path); + if (result) { + updateFilesOfFileSystemEntry(result, getBaseNameOfFileName(fileName), /*fileExists*/ true); + } + return host.writeFile(fileName, data, writeByteOrderMark); + } + function fileExists(fileName) { + var path = toPath(fileName); + var result = getCachedFileSystemEntriesForBaseDir(path); + return result && hasEntry(result.files, getBaseNameOfFileName(fileName)) || + host.fileExists(fileName); + } + function directoryExists(dirPath) { + var path = toPath(dirPath); + return cachedReadDirectoryResult.has(ts.ensureTrailingDirectorySeparator(path)) || host.directoryExists(dirPath); + } + function createDirectory(dirPath) { + var path = toPath(dirPath); + var result = getCachedFileSystemEntriesForBaseDir(path); + var baseFileName = getBaseNameOfFileName(dirPath); + if (result) { + updateFileSystemEntry(result.directories, baseFileName, /*isValid*/ true); + } + host.createDirectory(dirPath); + } + function getDirectories(rootDir) { + var rootDirPath = toPath(rootDir); + var result = tryReadDirectory(rootDir, rootDirPath); + if (result) { + return result.directories.slice(); + } + return host.getDirectories(rootDir); + } + function readDirectory(rootDir, extensions, excludes, includes, depth) { + var rootDirPath = toPath(rootDir); + var result = tryReadDirectory(rootDir, rootDirPath); + if (result) { + return ts.matchFiles(rootDir, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries); + } + return host.readDirectory(rootDir, extensions, excludes, includes, depth); + function getFileSystemEntries(dir) { + var path = toPath(dir); + if (path === rootDirPath) { + return result; + } + return tryReadDirectory(dir, path) || ts.emptyFileSystemEntries; + } + } + function addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath) { + var existingResult = getCachedFileSystemEntries(fileOrDirectoryPath); + if (existingResult) { + // Just clear the cache for now + // For now just clear the cache, since this could mean that multiple level entries might need to be re-evaluated + clearCache(); + return undefined; + } + var parentResult = getCachedFileSystemEntriesForBaseDir(fileOrDirectoryPath); + if (!parentResult) { + return undefined; + } + // This was earlier a file (hence not in cached directory contents) + // or we never cached the directory containing it + if (!host.directoryExists) { + // Since host doesnt support directory exists, clear the cache as otherwise it might not be same + clearCache(); + return undefined; + } + var baseName = getBaseNameOfFileName(fileOrDirectory); + var fsQueryResult = { + fileExists: host.fileExists(fileOrDirectoryPath), + directoryExists: host.directoryExists(fileOrDirectoryPath) + }; + if (fsQueryResult.directoryExists || hasEntry(parentResult.directories, baseName)) { + // Folder added or removed, clear the cache instead of updating the folder and its structure + clearCache(); + } + else { + // No need to update the directory structure, just files + updateFilesOfFileSystemEntry(parentResult, baseName, fsQueryResult.fileExists); + } + return fsQueryResult; + } + function addOrDeleteFile(fileName, filePath, eventKind) { + if (eventKind === ts.FileWatcherEventKind.Changed) { + return; + } + var parentResult = getCachedFileSystemEntriesForBaseDir(filePath); + if (parentResult) { + updateFilesOfFileSystemEntry(parentResult, getBaseNameOfFileName(fileName), eventKind === ts.FileWatcherEventKind.Created); + } + } + function updateFilesOfFileSystemEntry(parentResult, baseName, fileExists) { + updateFileSystemEntry(parentResult.files, baseName, fileExists); + } + function clearCache() { + cachedReadDirectoryResult.clear(); + } + } + ts.createCachedDirectoryStructureHost = createCachedDirectoryStructureHost; + var ConfigFileProgramReloadLevel; + (function (ConfigFileProgramReloadLevel) { + ConfigFileProgramReloadLevel[ConfigFileProgramReloadLevel["None"] = 0] = "None"; + /** Update the file name list from the disk */ + ConfigFileProgramReloadLevel[ConfigFileProgramReloadLevel["Partial"] = 1] = "Partial"; + /** Reload completely by re-reading contents of config file from disk and updating program */ + ConfigFileProgramReloadLevel[ConfigFileProgramReloadLevel["Full"] = 2] = "Full"; + })(ConfigFileProgramReloadLevel = ts.ConfigFileProgramReloadLevel || (ts.ConfigFileProgramReloadLevel = {})); + /** + * Updates the existing missing file watches with the new set of missing files after new program is created + */ + function updateMissingFilePathsWatch(program, missingFileWatches, createMissingFileWatch) { + var missingFilePaths = program.getMissingFilePaths(); + var newMissingFilePathMap = ts.arrayToSet(missingFilePaths); + // Update the missing file paths watcher + ts.mutateMap(missingFileWatches, newMissingFilePathMap, { + // Watch the missing files + createNewValue: createMissingFileWatch, + // Files that are no longer missing (e.g. because they are no longer required) + // should no longer be watched. + onDeleteValue: ts.closeFileWatcher + }); + } + ts.updateMissingFilePathsWatch = updateMissingFilePathsWatch; + /** + * Updates the existing wild card directory watches with the new set of wild card directories from the config file + * after new program is created because the config file was reloaded or program was created first time from the config file + * Note that there is no need to call this function when the program is updated with additional files without reloading config files, + * as wildcard directories wont change unless reloading config file + */ + function updateWatchingWildcardDirectories(existingWatchedForWildcards, wildcardDirectories, watchDirectory) { + ts.mutateMap(existingWatchedForWildcards, wildcardDirectories, { + // Create new watch and recursive info + createNewValue: createWildcardDirectoryWatcher, + // Close existing watch thats not needed any more + onDeleteValue: closeFileWatcherOf, + // Close existing watch that doesnt match in the flags + onExistingValue: updateWildcardDirectoryWatcher + }); + function createWildcardDirectoryWatcher(directory, flags) { + // Create new watch and recursive info + return { + watcher: watchDirectory(directory, flags), + flags: flags + }; + } + function updateWildcardDirectoryWatcher(existingWatcher, flags, directory) { + // Watcher needs to be updated if the recursive flags dont match + if (existingWatcher.flags === flags) { + return; + } + existingWatcher.watcher.close(); + existingWatchedForWildcards.set(directory, createWildcardDirectoryWatcher(directory, flags)); + } + } + ts.updateWatchingWildcardDirectories = updateWatchingWildcardDirectories; + function isEmittedFileOfProgram(program, file) { + if (!program) { + return false; + } + return program.isEmittedFile(file); + } + ts.isEmittedFileOfProgram = isEmittedFileOfProgram; + var WatchLogLevel; + (function (WatchLogLevel) { + WatchLogLevel[WatchLogLevel["None"] = 0] = "None"; + WatchLogLevel[WatchLogLevel["TriggerOnly"] = 1] = "TriggerOnly"; + WatchLogLevel[WatchLogLevel["Verbose"] = 2] = "Verbose"; + })(WatchLogLevel = ts.WatchLogLevel || (ts.WatchLogLevel = {})); + function getWatchFactory(watchLogLevel, log, getDetailWatchInfo) { + return getWatchFactoryWith(watchLogLevel, log, getDetailWatchInfo, watchFile, watchDirectory); + } + ts.getWatchFactory = getWatchFactory; + function getWatchFactoryWith(watchLogLevel, log, getDetailWatchInfo, watchFile, watchDirectory) { + var createFileWatcher = getCreateFileWatcher(watchLogLevel, watchFile); + var createFilePathWatcher = watchLogLevel === WatchLogLevel.None ? watchFilePath : createFileWatcher; + var createDirectoryWatcher = getCreateFileWatcher(watchLogLevel, watchDirectory); + return { + watchFile: function (host, file, callback, pollingInterval, detailInfo1, detailInfo2) { + return createFileWatcher(host, file, callback, pollingInterval, /*passThrough*/ undefined, detailInfo1, detailInfo2, watchFile, log, "FileWatcher", getDetailWatchInfo); + }, + watchFilePath: function (host, file, callback, pollingInterval, path, detailInfo1, detailInfo2) { + return createFilePathWatcher(host, file, callback, pollingInterval, path, detailInfo1, detailInfo2, watchFile, log, "FileWatcher", getDetailWatchInfo); + }, + watchDirectory: function (host, directory, callback, flags, detailInfo1, detailInfo2) { + return createDirectoryWatcher(host, directory, callback, flags, /*passThrough*/ undefined, detailInfo1, detailInfo2, watchDirectory, log, "DirectoryWatcher", getDetailWatchInfo); + } + }; + function watchFilePath(host, file, callback, pollingInterval, path) { + return watchFile(host, file, function (fileName, eventKind) { return callback(fileName, eventKind, path); }, pollingInterval); + } + } + function watchFile(host, file, callback, pollingInterval) { + return host.watchFile(file, callback, pollingInterval); + } + function watchDirectory(host, directory, callback, flags) { + return host.watchDirectory(directory, callback, (flags & 1 /* Recursive */) !== 0); + } + function getCreateFileWatcher(watchLogLevel, addWatch) { + switch (watchLogLevel) { + case WatchLogLevel.None: + return addWatch; + case WatchLogLevel.TriggerOnly: + return createFileWatcherWithTriggerLogging; + case WatchLogLevel.Verbose: + return addWatch === watchDirectory ? createDirectoryWatcherWithLogging : createFileWatcherWithLogging; + } + } + function createFileWatcherWithLogging(host, file, cb, flags, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo) { + log(watchCaption + ":: Added:: " + getWatchInfo(file, flags, detailInfo1, detailInfo2, getDetailWatchInfo)); + var watcher = createFileWatcherWithTriggerLogging(host, file, cb, flags, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo); + return { + close: function () { + log(watchCaption + ":: Close:: " + getWatchInfo(file, flags, detailInfo1, detailInfo2, getDetailWatchInfo)); + watcher.close(); + } + }; + } + function createDirectoryWatcherWithLogging(host, file, cb, flags, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo) { + var watchInfo = watchCaption + ":: Added:: " + getWatchInfo(file, flags, detailInfo1, detailInfo2, getDetailWatchInfo); + log(watchInfo); + var start = ts.timestamp(); + var watcher = createFileWatcherWithTriggerLogging(host, file, cb, flags, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo); + var elapsed = ts.timestamp() - start; + log("Elapsed:: " + elapsed + "ms " + watchInfo); + return { + close: function () { + var watchInfo = watchCaption + ":: Close:: " + getWatchInfo(file, flags, detailInfo1, detailInfo2, getDetailWatchInfo); + log(watchInfo); + var start = ts.timestamp(); + watcher.close(); + var elapsed = ts.timestamp() - start; + log("Elapsed:: " + elapsed + "ms " + watchInfo); + } + }; + } + function createFileWatcherWithTriggerLogging(host, file, cb, flags, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo) { + return addWatch(host, file, function (fileName, cbOptional) { + var triggerredInfo = watchCaption + ":: Triggered with " + fileName + " " + (cbOptional !== undefined ? cbOptional : "") + ":: " + getWatchInfo(file, flags, detailInfo1, detailInfo2, getDetailWatchInfo); + log(triggerredInfo); + var start = ts.timestamp(); + cb(fileName, cbOptional, passThrough); + var elapsed = ts.timestamp() - start; + log("Elapsed:: " + elapsed + "ms " + triggerredInfo); + }, flags); + } + function getWatchInfo(file, flags, detailInfo1, detailInfo2, getDetailWatchInfo) { + return "WatchInfo: " + file + " " + flags + " " + (getDetailWatchInfo ? getDetailWatchInfo(detailInfo1, detailInfo2) : detailInfo1); + } + function closeFileWatcherOf(objWithWatcher) { + objWithWatcher.watcher.close(); + } + ts.closeFileWatcherOf = closeFileWatcherOf; +})(ts || (ts = {})); +var ts; +(function (ts) { + var ignoreDiagnosticCommentRegEx = /(^\s*$)|(^\s*\/\/\/?\s*(@ts-ignore)?)/; + function findConfigFile(searchPath, fileExists, configName) { + if (configName === void 0) { configName = "tsconfig.json"; } + return ts.forEachAncestorDirectory(searchPath, function (ancestor) { + var fileName = ts.combinePaths(ancestor, configName); + return fileExists(fileName) ? fileName : undefined; + }); + } + ts.findConfigFile = findConfigFile; + function resolveTripleslashReference(moduleName, containingFile) { + var basePath = ts.getDirectoryPath(containingFile); + var referencedFileName = ts.isRootedDiskPath(moduleName) ? moduleName : ts.combinePaths(basePath, moduleName); + return ts.normalizePath(referencedFileName); + } + ts.resolveTripleslashReference = resolveTripleslashReference; + /* @internal */ + function computeCommonSourceDirectoryOfFilenames(fileNames, currentDirectory, getCanonicalFileName) { + var commonPathComponents; + var failed = ts.forEach(fileNames, function (sourceFile) { + // Each file contributes into common source file path + var sourcePathComponents = ts.getNormalizedPathComponents(sourceFile, currentDirectory); + sourcePathComponents.pop(); // The base file name is not part of the common directory path + if (!commonPathComponents) { + // first file + commonPathComponents = sourcePathComponents; + return; + } + var n = Math.min(commonPathComponents.length, sourcePathComponents.length); + for (var i = 0; i < n; i++) { + if (getCanonicalFileName(commonPathComponents[i]) !== getCanonicalFileName(sourcePathComponents[i])) { + if (i === 0) { + // Failed to find any common path component + return true; + } + // New common path found that is 0 -> i-1 + commonPathComponents.length = i; + break; + } + } + // If the sourcePathComponents was shorter than the commonPathComponents, truncate to the sourcePathComponents + if (sourcePathComponents.length < commonPathComponents.length) { + commonPathComponents.length = sourcePathComponents.length; + } + }); + // A common path can not be found when paths span multiple drives on windows, for example + if (failed) { + return ""; + } + if (!commonPathComponents) { // Can happen when all input files are .d.ts files + return currentDirectory; + } + return ts.getPathFromPathComponents(commonPathComponents); + } + ts.computeCommonSourceDirectoryOfFilenames = computeCommonSourceDirectoryOfFilenames; + function createCompilerHost(options, setParentNodes) { + return createCompilerHostWorker(options, setParentNodes); + } + ts.createCompilerHost = createCompilerHost; + /*@internal*/ + // TODO(shkamat): update this after reworking ts build API + function createCompilerHostWorker(options, setParentNodes, system) { + if (system === void 0) { system = ts.sys; } + var existingDirectories = ts.createMap(); + function getCanonicalFileName(fileName) { + // if underlying system can distinguish between two files whose names differs only in cases then file name already in canonical form. + // otherwise use toLowerCase as a canonical form. + return system.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); + } + function getSourceFile(fileName, languageVersion, onError) { + var text; + try { + ts.performance.mark("beforeIORead"); + text = compilerHost.readFile(fileName); + ts.performance.mark("afterIORead"); + ts.performance.measure("I/O Read", "beforeIORead", "afterIORead"); + } + catch (e) { + if (onError) { + onError(e.message); + } + text = ""; + } + return text !== undefined ? ts.createSourceFile(fileName, text, languageVersion, setParentNodes) : undefined; + } + function directoryExists(directoryPath) { + if (existingDirectories.has(directoryPath)) { + return true; + } + if (system.directoryExists(directoryPath)) { + existingDirectories.set(directoryPath, true); + return true; + } + return false; + } + function ensureDirectoriesExist(directoryPath) { + if (directoryPath.length > ts.getRootLength(directoryPath) && !directoryExists(directoryPath)) { + var parentDirectory = ts.getDirectoryPath(directoryPath); + ensureDirectoriesExist(parentDirectory); + if (compilerHost.createDirectory) { + compilerHost.createDirectory(directoryPath); + } + else { + system.createDirectory(directoryPath); + } + } + } + var outputFingerprints; + function writeFileIfUpdated(fileName, data, writeByteOrderMark) { + if (!outputFingerprints) { + outputFingerprints = ts.createMap(); + } + var hash = system.createHash(data); // TODO: GH#18217 + var mtimeBefore = system.getModifiedTime(fileName); // TODO: GH#18217 + if (mtimeBefore) { + var fingerprint = outputFingerprints.get(fileName); + // If output has not been changed, and the file has no external modification + if (fingerprint && + fingerprint.byteOrderMark === writeByteOrderMark && + fingerprint.hash === hash && + fingerprint.mtime.getTime() === mtimeBefore.getTime()) { + return; + } + } + system.writeFile(fileName, data, writeByteOrderMark); + var mtimeAfter = system.getModifiedTime(fileName) || ts.missingFileModifiedTime; // TODO: GH#18217 + outputFingerprints.set(fileName, { + hash: hash, + byteOrderMark: writeByteOrderMark, + mtime: mtimeAfter + }); + } + function writeFile(fileName, data, writeByteOrderMark, onError) { + try { + ts.performance.mark("beforeIOWrite"); + ensureDirectoriesExist(ts.getDirectoryPath(ts.normalizePath(fileName))); + if (ts.isWatchSet(options) && system.createHash && system.getModifiedTime) { + writeFileIfUpdated(fileName, data, writeByteOrderMark); + } + else { + system.writeFile(fileName, data, writeByteOrderMark); + } + ts.performance.mark("afterIOWrite"); + ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite"); + } + catch (e) { + if (onError) { + onError(e.message); + } + } + } + function getDefaultLibLocation() { + return ts.getDirectoryPath(ts.normalizePath(system.getExecutingFilePath())); + } + var newLine = ts.getNewLineCharacter(options, function () { return system.newLine; }); + var realpath = system.realpath && (function (path) { return system.realpath(path); }); + var compilerHost = { + getSourceFile: getSourceFile, + getDefaultLibLocation: getDefaultLibLocation, + getDefaultLibFileName: function (options) { return ts.combinePaths(getDefaultLibLocation(), ts.getDefaultLibFileName(options)); }, + writeFile: writeFile, + getCurrentDirectory: ts.memoize(function () { return system.getCurrentDirectory(); }), + useCaseSensitiveFileNames: function () { return system.useCaseSensitiveFileNames; }, + getCanonicalFileName: getCanonicalFileName, + getNewLine: function () { return newLine; }, + fileExists: function (fileName) { return system.fileExists(fileName); }, + readFile: function (fileName) { return system.readFile(fileName); }, + trace: function (s) { return system.write(s + newLine); }, + directoryExists: function (directoryName) { return system.directoryExists(directoryName); }, + getEnvironmentVariable: function (name) { return system.getEnvironmentVariable ? system.getEnvironmentVariable(name) : ""; }, + getDirectories: function (path) { return system.getDirectories(path); }, + realpath: realpath, + readDirectory: function (path, extensions, include, exclude, depth) { return system.readDirectory(path, extensions, include, exclude, depth); }, + createDirectory: function (d) { return system.createDirectory(d); } + }; + return compilerHost; + } + ts.createCompilerHostWorker = createCompilerHostWorker; + /*@internal*/ + function changeCompilerHostToUseCache(host, toPath, useCacheForSourceFile) { + var originalReadFile = host.readFile; + var originalFileExists = host.fileExists; + var originalDirectoryExists = host.directoryExists; + var originalCreateDirectory = host.createDirectory; + var originalWriteFile = host.writeFile; + var originalGetSourceFile = host.getSourceFile; + var readFileCache = ts.createMap(); + var fileExistsCache = ts.createMap(); + var directoryExistsCache = ts.createMap(); + var sourceFileCache = ts.createMap(); + var readFileWithCache = function (fileName) { + var key = toPath(fileName); + var value = readFileCache.get(key); + if (value !== undefined) + return value || undefined; + return setReadFileCache(key, fileName); + }; + var setReadFileCache = function (key, fileName) { + var newValue = originalReadFile.call(host, fileName); + readFileCache.set(key, newValue || false); + return newValue; + }; + host.readFile = function (fileName) { + var key = toPath(fileName); + var value = readFileCache.get(key); + if (value !== undefined) + return value; // could be .d.ts from output + if (!ts.fileExtensionIs(fileName, ".json" /* Json */)) { + return originalReadFile.call(host, fileName); + } + return setReadFileCache(key, fileName); + }; + if (useCacheForSourceFile) { + host.getSourceFile = function (fileName, languageVersion, onError, shouldCreateNewSourceFile) { + var key = toPath(fileName); + var value = sourceFileCache.get(key); + if (value) + return value; + var sourceFile = originalGetSourceFile.call(host, fileName, languageVersion, onError, shouldCreateNewSourceFile); + if (sourceFile && (ts.isDeclarationFileName(fileName) || ts.fileExtensionIs(fileName, ".json" /* Json */))) { + sourceFileCache.set(key, sourceFile); + } + return sourceFile; + }; + } + // fileExists for any kind of extension + host.fileExists = function (fileName) { + var key = toPath(fileName); + var value = fileExistsCache.get(key); + if (value !== undefined) + return value; + var newValue = originalFileExists.call(host, fileName); + fileExistsCache.set(key, !!newValue); + return newValue; + }; + host.writeFile = function (fileName, data, writeByteOrderMark, onError, sourceFiles) { + var key = toPath(fileName); + fileExistsCache.delete(key); + var value = readFileCache.get(key); + if (value && value !== data) { + readFileCache.delete(key); + sourceFileCache.delete(key); + } + else if (useCacheForSourceFile) { + var sourceFile = sourceFileCache.get(key); + if (sourceFile && sourceFile.text !== data) { + sourceFileCache.delete(key); + } + } + originalWriteFile.call(host, fileName, data, writeByteOrderMark, onError, sourceFiles); + }; + // directoryExists + if (originalDirectoryExists && originalCreateDirectory) { + host.directoryExists = function (directory) { + var key = toPath(directory); + var value = directoryExistsCache.get(key); + if (value !== undefined) + return value; + var newValue = originalDirectoryExists.call(host, directory); + directoryExistsCache.set(key, !!newValue); + return newValue; + }; + host.createDirectory = function (directory) { + var key = toPath(directory); + directoryExistsCache.delete(key); + originalCreateDirectory.call(host, directory); + }; + } + return { + originalReadFile: originalReadFile, + originalFileExists: originalFileExists, + originalDirectoryExists: originalDirectoryExists, + originalCreateDirectory: originalCreateDirectory, + originalWriteFile: originalWriteFile, + originalGetSourceFile: originalGetSourceFile, + readFileWithCache: readFileWithCache + }; + } + ts.changeCompilerHostToUseCache = changeCompilerHostToUseCache; + function getPreEmitDiagnostics(program, sourceFile, cancellationToken) { + var diagnostics = program.getConfigFileParsingDiagnostics().concat(program.getOptionsDiagnostics(cancellationToken), program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken)); + if (ts.getEmitDeclarations(program.getCompilerOptions())) { + ts.addRange(diagnostics, program.getDeclarationDiagnostics(sourceFile, cancellationToken)); + } + return ts.sortAndDeduplicateDiagnostics(diagnostics); + } + ts.getPreEmitDiagnostics = getPreEmitDiagnostics; + function formatDiagnostics(diagnostics, host) { + var output = ""; + for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { + var diagnostic = diagnostics_2[_i]; + output += formatDiagnostic(diagnostic, host); + } + return output; + } + ts.formatDiagnostics = formatDiagnostics; + function formatDiagnostic(diagnostic, host) { + var errorMessage = ts.diagnosticCategoryName(diagnostic) + " TS" + diagnostic.code + ": " + flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine()) + host.getNewLine(); + if (diagnostic.file) { + var _a = ts.getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start), line = _a.line, character = _a.character; // TODO: GH#18217 + var fileName = diagnostic.file.fileName; + var relativeFileName = ts.convertToRelativePath(fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); }); + return relativeFileName + "(" + (line + 1) + "," + (character + 1) + "): " + errorMessage; + } + return errorMessage; + } + ts.formatDiagnostic = formatDiagnostic; + /** @internal */ + var ForegroundColorEscapeSequences; + (function (ForegroundColorEscapeSequences) { + ForegroundColorEscapeSequences["Grey"] = "\u001B[90m"; + ForegroundColorEscapeSequences["Red"] = "\u001B[91m"; + ForegroundColorEscapeSequences["Yellow"] = "\u001B[93m"; + ForegroundColorEscapeSequences["Blue"] = "\u001B[94m"; + ForegroundColorEscapeSequences["Cyan"] = "\u001B[96m"; + })(ForegroundColorEscapeSequences = ts.ForegroundColorEscapeSequences || (ts.ForegroundColorEscapeSequences = {})); + var gutterStyleSequence = "\u001b[7m"; + var gutterSeparator = " "; + var resetEscapeSequence = "\u001b[0m"; + var ellipsis = "..."; + var halfIndent = " "; + var indent = " "; + function getCategoryFormat(category) { + switch (category) { + case ts.DiagnosticCategory.Error: return ForegroundColorEscapeSequences.Red; + case ts.DiagnosticCategory.Warning: return ForegroundColorEscapeSequences.Yellow; + case ts.DiagnosticCategory.Suggestion: return ts.Debug.fail("Should never get an Info diagnostic on the command line."); + case ts.DiagnosticCategory.Message: return ForegroundColorEscapeSequences.Blue; + } + } + /** @internal */ + function formatColorAndReset(text, formatStyle) { + return formatStyle + text + resetEscapeSequence; + } + ts.formatColorAndReset = formatColorAndReset; + function padLeft(s, length) { + while (s.length < length) { + s = " " + s; + } + return s; + } + function formatCodeSpan(file, start, length, indent, squiggleColor, host) { + var _a = ts.getLineAndCharacterOfPosition(file, start), firstLine = _a.line, firstLineChar = _a.character; + var _b = ts.getLineAndCharacterOfPosition(file, start + length), lastLine = _b.line, lastLineChar = _b.character; + var lastLineInFile = ts.getLineAndCharacterOfPosition(file, file.text.length).line; + var hasMoreThanFiveLines = (lastLine - firstLine) >= 4; + var gutterWidth = (lastLine + 1 + "").length; + if (hasMoreThanFiveLines) { + gutterWidth = Math.max(ellipsis.length, gutterWidth); + } + var context = ""; + for (var i = firstLine; i <= lastLine; i++) { + context += host.getNewLine(); + // If the error spans over 5 lines, we'll only show the first 2 and last 2 lines, + // so we'll skip ahead to the second-to-last line. + if (hasMoreThanFiveLines && firstLine + 1 < i && i < lastLine - 1) { + context += indent + formatColorAndReset(padLeft(ellipsis, gutterWidth), gutterStyleSequence) + gutterSeparator + host.getNewLine(); + i = lastLine - 1; + } + var lineStart = ts.getPositionOfLineAndCharacter(file, i, 0); + var lineEnd = i < lastLineInFile ? ts.getPositionOfLineAndCharacter(file, i + 1, 0) : file.text.length; + var lineContent = file.text.slice(lineStart, lineEnd); + lineContent = lineContent.replace(/\s+$/g, ""); // trim from end + lineContent = lineContent.replace("\t", " "); // convert tabs to single spaces + // Output the gutter and the actual contents of the line. + context += indent + formatColorAndReset(padLeft(i + 1 + "", gutterWidth), gutterStyleSequence) + gutterSeparator; + context += lineContent + host.getNewLine(); + // Output the gutter and the error span for the line using tildes. + context += indent + formatColorAndReset(padLeft("", gutterWidth), gutterStyleSequence) + gutterSeparator; + context += squiggleColor; + if (i === firstLine) { + // If we're on the last line, then limit it to the last character of the last line. + // Otherwise, we'll just squiggle the rest of the line, giving 'slice' no end position. + var lastCharForLine = i === lastLine ? lastLineChar : undefined; + context += lineContent.slice(0, firstLineChar).replace(/\S/g, " "); + context += lineContent.slice(firstLineChar, lastCharForLine).replace(/./g, "~"); + } + else if (i === lastLine) { + context += lineContent.slice(0, lastLineChar).replace(/./g, "~"); + } + else { + // Squiggle the entire line. + context += lineContent.replace(/./g, "~"); + } + context += resetEscapeSequence; + } + return context; + } + /* @internal */ + function formatLocation(file, start, host, color) { + if (color === void 0) { color = formatColorAndReset; } + var _a = ts.getLineAndCharacterOfPosition(file, start), firstLine = _a.line, firstLineChar = _a.character; // TODO: GH#18217 + var relativeFileName = host ? ts.convertToRelativePath(file.fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); }) : file.fileName; + var output = ""; + output += color(relativeFileName, ForegroundColorEscapeSequences.Cyan); + output += ":"; + output += color("" + (firstLine + 1), ForegroundColorEscapeSequences.Yellow); + output += ":"; + output += color("" + (firstLineChar + 1), ForegroundColorEscapeSequences.Yellow); + return output; + } + ts.formatLocation = formatLocation; + function formatDiagnosticsWithColorAndContext(diagnostics, host) { + var output = ""; + for (var _i = 0, diagnostics_3 = diagnostics; _i < diagnostics_3.length; _i++) { + var diagnostic = diagnostics_3[_i]; + if (diagnostic.file) { + var file = diagnostic.file, start = diagnostic.start; + output += formatLocation(file, start, host); // TODO: GH#18217 + output += " - "; + } + output += formatColorAndReset(ts.diagnosticCategoryName(diagnostic), getCategoryFormat(diagnostic.category)); + output += formatColorAndReset(" TS" + diagnostic.code + ": ", ForegroundColorEscapeSequences.Grey); + output += flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine()); + if (diagnostic.file) { + output += host.getNewLine(); + output += formatCodeSpan(diagnostic.file, diagnostic.start, diagnostic.length, "", getCategoryFormat(diagnostic.category), host); // TODO: GH#18217 + if (diagnostic.relatedInformation) { + output += host.getNewLine(); + for (var _a = 0, _b = diagnostic.relatedInformation; _a < _b.length; _a++) { + var _c = _b[_a], file = _c.file, start = _c.start, length_4 = _c.length, messageText = _c.messageText; + if (file) { + output += host.getNewLine(); + output += halfIndent + formatLocation(file, start, host); // TODO: GH#18217 + output += formatCodeSpan(file, start, length_4, indent, ForegroundColorEscapeSequences.Cyan, host); // TODO: GH#18217 + } + output += host.getNewLine(); + output += indent + flattenDiagnosticMessageText(messageText, host.getNewLine()); + } + } + } + output += host.getNewLine(); + } + return output; + } + ts.formatDiagnosticsWithColorAndContext = formatDiagnosticsWithColorAndContext; + function flattenDiagnosticMessageText(messageText, newLine) { + if (ts.isString(messageText)) { + return messageText; + } + else { + var diagnosticChain = messageText; + var result = ""; + var indent_1 = 0; + while (diagnosticChain) { + if (indent_1) { + result += newLine; + for (var i = 0; i < indent_1; i++) { + result += " "; + } + } + result += diagnosticChain.messageText; + indent_1++; + diagnosticChain = diagnosticChain.next; + } + return result; + } + } + ts.flattenDiagnosticMessageText = flattenDiagnosticMessageText; + function loadWithLocalCache(names, containingFile, redirectedReference, loader) { + if (names.length === 0) { + return []; + } + var resolutions = []; + var cache = ts.createMap(); + for (var _i = 0, names_1 = names; _i < names_1.length; _i++) { + var name = names_1[_i]; + var result = void 0; + if (cache.has(name)) { + result = cache.get(name); + } + else { + cache.set(name, result = loader(name, containingFile, redirectedReference)); + } + resolutions.push(result); + } + return resolutions; + } + /** + * Determines if program structure is upto date or needs to be recreated + */ + /* @internal */ + function isProgramUptoDate(program, rootFileNames, newOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, projectReferences) { + // If we haven't created a program yet or have changed automatic type directives, then it is not up-to-date + if (!program || hasChangedAutomaticTypeDirectiveNames) { + return false; + } + // If number of files in the program do not match, it is not up-to-date + if (program.getRootFileNames().length !== rootFileNames.length) { + return false; + } + var seenResolvedRefs; + // If project references dont match + if (!ts.arrayIsEqualTo(program.getProjectReferences(), projectReferences, projectReferenceUptoDate)) { + return false; + } + // If any file is not up-to-date, then the whole program is not up-to-date + if (program.getSourceFiles().some(sourceFileNotUptoDate)) { + return false; + } + // If any of the missing file paths are now created + if (program.getMissingFilePaths().some(fileExists)) { + return false; + } + var currentOptions = program.getCompilerOptions(); + // If the compilation settings do no match, then the program is not up-to-date + if (!ts.compareDataObjects(currentOptions, newOptions)) { + return false; + } + // If everything matches but the text of config file is changed, + // error locations can change for program options, so update the program + if (currentOptions.configFile && newOptions.configFile) { + return currentOptions.configFile.text === newOptions.configFile.text; + } + return true; + function sourceFileNotUptoDate(sourceFile) { + return !sourceFileVersionUptoDate(sourceFile) || + hasInvalidatedResolution(sourceFile.path); + } + function sourceFileVersionUptoDate(sourceFile) { + return sourceFile.version === getSourceVersion(sourceFile.resolvedPath); + } + function projectReferenceUptoDate(oldRef, newRef, index) { + if (!ts.projectReferenceIsEqualTo(oldRef, newRef)) { + return false; + } + return resolvedProjectReferenceUptoDate(program.getResolvedProjectReferences()[index], oldRef); + } + function resolvedProjectReferenceUptoDate(oldResolvedRef, oldRef) { + if (oldResolvedRef) { + if (ts.contains(seenResolvedRefs, oldResolvedRef)) { + // Assume true + return true; + } + // If sourceFile for the oldResolvedRef existed, check the version for uptodate + if (!sourceFileVersionUptoDate(oldResolvedRef.sourceFile)) { + return false; + } + // Add to seen before checking the referenced paths of this config file + (seenResolvedRefs || (seenResolvedRefs = [])).push(oldResolvedRef); + // If child project references are upto date, this project reference is uptodate + return !ts.forEach(oldResolvedRef.references, function (childResolvedRef, index) { + return !resolvedProjectReferenceUptoDate(childResolvedRef, oldResolvedRef.commandLine.projectReferences[index]); + }); + } + // In old program, not able to resolve project reference path, + // so if config file doesnt exist, it is uptodate. + return !fileExists(resolveProjectReferencePath(oldRef)); + } + } + ts.isProgramUptoDate = isProgramUptoDate; + function getConfigFileParsingDiagnostics(configFileParseResult) { + return configFileParseResult.options.configFile ? configFileParseResult.options.configFile.parseDiagnostics.concat(configFileParseResult.errors) : + configFileParseResult.errors; + } + ts.getConfigFileParsingDiagnostics = getConfigFileParsingDiagnostics; + /** + * Determine if source file needs to be re-created even if its text hasn't changed + */ + function shouldProgramCreateNewSourceFiles(program, newOptions) { + if (!program) + return false; + // If any compiler options change, we can't reuse old source file even if version match + // The change in options like these could result in change in syntax tree or `sourceFile.bindDiagnostics`. + var oldOptions = program.getCompilerOptions(); + return !!ts.sourceFileAffectingCompilerOptions.some(function (option) { + return !ts.isJsonEqual(ts.getCompilerOptionValue(oldOptions, option), ts.getCompilerOptionValue(newOptions, option)); + }); + } + function createCreateProgramOptions(rootNames, options, host, oldProgram, configFileParsingDiagnostics) { + return { + rootNames: rootNames, + options: options, + host: host, + oldProgram: oldProgram, + configFileParsingDiagnostics: configFileParsingDiagnostics + }; + } + function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _configFileParsingDiagnostics) { + var createProgramOptions = ts.isArray(rootNamesOrOptions) ? createCreateProgramOptions(rootNamesOrOptions, _options, _host, _oldProgram, _configFileParsingDiagnostics) : rootNamesOrOptions; // TODO: GH#18217 + var rootNames = createProgramOptions.rootNames, options = createProgramOptions.options, configFileParsingDiagnostics = createProgramOptions.configFileParsingDiagnostics, projectReferences = createProgramOptions.projectReferences; + var oldProgram = createProgramOptions.oldProgram; + var program; + var processingDefaultLibFiles; + var processingOtherFiles; + var files; + var commonSourceDirectory; + var diagnosticsProducingTypeChecker; + var noDiagnosticsTypeChecker; + var classifiableNames; + var ambientModuleNameToUnmodifiedFileName = ts.createMap(); + var cachedSemanticDiagnosticsForFile = {}; + var cachedDeclarationDiagnosticsForFile = {}; + var resolvedTypeReferenceDirectives = ts.createMap(); + var fileProcessingDiagnostics = ts.createDiagnosticCollection(); + // The below settings are to track if a .js file should be add to the program if loaded via searching under node_modules. + // This works as imported modules are discovered recursively in a depth first manner, specifically: + // - For each root file, findSourceFile is called. + // - This calls processImportedModules for each module imported in the source file. + // - This calls resolveModuleNames, and then calls findSourceFile for each resolved module. + // As all these operations happen - and are nested - within the createProgram call, they close over the below variables. + // The current resolution depth is tracked by incrementing/decrementing as the depth first search progresses. + var maxNodeModuleJsDepth = typeof options.maxNodeModuleJsDepth === "number" ? options.maxNodeModuleJsDepth : 0; + var currentNodeModulesDepth = 0; + // If a module has some of its imports skipped due to being at the depth limit under node_modules, then track + // this, as it may be imported at a shallower depth later, and then it will need its skipped imports processed. + var modulesWithElidedImports = ts.createMap(); + // Track source files that are source files found by searching under node_modules, as these shouldn't be compiled. + var sourceFilesFoundSearchingNodeModules = ts.createMap(); + ts.performance.mark("beforeProgram"); + var host = createProgramOptions.host || createCompilerHost(options); + var configParsingHost = parseConfigHostFromCompilerHost(host); + var skipDefaultLib = options.noLib; + var getDefaultLibraryFileName = ts.memoize(function () { return host.getDefaultLibFileName(options); }); + var defaultLibraryPath = host.getDefaultLibLocation ? host.getDefaultLibLocation() : ts.getDirectoryPath(getDefaultLibraryFileName()); + var programDiagnostics = ts.createDiagnosticCollection(); + var currentDirectory = host.getCurrentDirectory(); + var supportedExtensions = ts.getSupportedExtensions(options); + var supportedExtensionsWithJsonIfResolveJsonModule = ts.getSuppoertedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions); + // Map storing if there is emit blocking diagnostics for given input + var hasEmitBlockingDiagnostics = ts.createMap(); + var _compilerOptionsObjectLiteralSyntax; + var moduleResolutionCache; + var resolveModuleNamesWorker; + var hasInvalidatedResolution = host.hasInvalidatedResolution || ts.returnFalse; + if (host.resolveModuleNames) { + resolveModuleNamesWorker = function (moduleNames, containingFile, reusedNames, redirectedReference) { return host.resolveModuleNames(ts.Debug.assertEachDefined(moduleNames), containingFile, reusedNames, redirectedReference).map(function (resolved) { + // An older host may have omitted extension, in which case we should infer it from the file extension of resolvedFileName. + if (!resolved || resolved.extension !== undefined) { + return resolved; + } + var withExtension = ts.clone(resolved); + withExtension.extension = ts.extensionFromPath(resolved.resolvedFileName); + return withExtension; + }); }; + } + else { + moduleResolutionCache = ts.createModuleResolutionCache(currentDirectory, function (x) { return host.getCanonicalFileName(x); }); + var loader_1 = function (moduleName, containingFile, redirectedReference) { return ts.resolveModuleName(moduleName, containingFile, options, host, moduleResolutionCache, redirectedReference).resolvedModule; }; // TODO: GH#18217 + resolveModuleNamesWorker = function (moduleNames, containingFile, _reusedNames, redirectedReference) { return loadWithLocalCache(ts.Debug.assertEachDefined(moduleNames), containingFile, redirectedReference, loader_1); }; + } + var resolveTypeReferenceDirectiveNamesWorker; + if (host.resolveTypeReferenceDirectives) { + resolveTypeReferenceDirectiveNamesWorker = function (typeDirectiveNames, containingFile, redirectedReference) { return host.resolveTypeReferenceDirectives(ts.Debug.assertEachDefined(typeDirectiveNames), containingFile, redirectedReference); }; + } + else { + var loader_2 = function (typesRef, containingFile, redirectedReference) { return ts.resolveTypeReferenceDirective(typesRef, containingFile, options, host, redirectedReference).resolvedTypeReferenceDirective; }; // TODO: GH#18217 + resolveTypeReferenceDirectiveNamesWorker = function (typeReferenceDirectiveNames, containingFile, redirectedReference) { return loadWithLocalCache(ts.Debug.assertEachDefined(typeReferenceDirectiveNames), containingFile, redirectedReference, loader_2); }; + } + // Map from a stringified PackageId to the source file with that id. + // Only one source file may have a given packageId. Others become redirects (see createRedirectSourceFile). + // `packageIdToSourceFile` is only used while building the program, while `sourceFileToPackageName` and `isSourceFileTargetOfRedirect` are kept around. + var packageIdToSourceFile = ts.createMap(); + // Maps from a SourceFile's `.path` to the name of the package it was imported with. + var sourceFileToPackageName = ts.createMap(); + // Key is a file name. Value is the (non-empty, or undefined) list of files that redirect to it. + var redirectTargetsMap = ts.createMultiMap(); + var filesByName = ts.createMap(); + var missingFilePaths; + // stores 'filename -> file association' ignoring case + // used to track cases when two file names differ only in casing + var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createMap() : undefined; + // A parallel array to projectReferences storing the results of reading in the referenced tsconfig files + var resolvedProjectReferences; + var projectReferenceRedirects; + var mapFromFileToProjectReferenceRedirects; + var shouldCreateNewSourceFile = shouldProgramCreateNewSourceFiles(oldProgram, options); + var structuralIsReused = tryReuseStructureFromOldProgram(); + if (structuralIsReused !== 2 /* Completely */) { + processingDefaultLibFiles = []; + processingOtherFiles = []; + if (projectReferences) { + if (!resolvedProjectReferences) { + resolvedProjectReferences = projectReferences.map(parseProjectReferenceConfigFile); + } + if (rootNames.length) { + for (var _i = 0, resolvedProjectReferences_1 = resolvedProjectReferences; _i < resolvedProjectReferences_1.length; _i++) { + var parsedRef = resolvedProjectReferences_1[_i]; + if (parsedRef) { + var out = parsedRef.commandLine.options.outFile || parsedRef.commandLine.options.out; + if (out) { + var dtsOutfile = ts.changeExtension(out, ".d.ts"); + processSourceFile(dtsOutfile, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined); + } + } + } + } + } + ts.forEach(rootNames, function (name) { return processRootFile(name, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false); }); + // load type declarations specified via 'types' argument or implicitly from types/ and node_modules/@types folders + var typeReferences = rootNames.length ? ts.getAutomaticTypeDirectiveNames(options, host) : ts.emptyArray; + if (typeReferences.length) { + // This containingFilename needs to match with the one used in managed-side + var containingDirectory = options.configFilePath ? ts.getDirectoryPath(options.configFilePath) : host.getCurrentDirectory(); + var containingFilename = ts.combinePaths(containingDirectory, "__inferred type names__.ts"); + var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeReferences, containingFilename); + for (var i = 0; i < typeReferences.length; i++) { + processTypeReferenceDirective(typeReferences[i], resolutions[i]); + } + } + // Do not process the default library if: + // - The '--noLib' flag is used. + // - A 'no-default-lib' reference comment is encountered in + // processing the root files. + if (rootNames.length && !skipDefaultLib) { + // If '--lib' is not specified, include default library file according to '--target' + // otherwise, using options specified in '--lib' instead of '--target' default library file + var defaultLibraryFileName = getDefaultLibraryFileName(); + if (!options.lib && defaultLibraryFileName) { + processRootFile(defaultLibraryFileName, /*isDefaultLib*/ true, /*ignoreNoDefaultLib*/ false); + } + else { + ts.forEach(options.lib, function (libFileName) { + processRootFile(ts.combinePaths(defaultLibraryPath, libFileName), /*isDefaultLib*/ true, /*ignoreNoDefaultLib*/ false); + }); + } + } + missingFilePaths = ts.arrayFrom(filesByName.keys(), function (p) { return p; }).filter(function (p) { return !filesByName.get(p); }); + files = ts.stableSort(processingDefaultLibFiles, compareDefaultLibFiles).concat(processingOtherFiles); + processingDefaultLibFiles = undefined; + processingOtherFiles = undefined; + } + ts.Debug.assert(!!missingFilePaths); + // Release any files we have acquired in the old program but are + // not part of the new program. + if (oldProgram && host.onReleaseOldSourceFile) { + var oldSourceFiles = oldProgram.getSourceFiles(); + for (var _a = 0, oldSourceFiles_1 = oldSourceFiles; _a < oldSourceFiles_1.length; _a++) { + var oldSourceFile = oldSourceFiles_1[_a]; + var newFile = getSourceFileByPath(oldSourceFile.resolvedPath); + if (shouldCreateNewSourceFile || !newFile || + // old file wasnt redirect but new file is + (oldSourceFile.resolvedPath === oldSourceFile.path && newFile.resolvedPath !== oldSourceFile.path)) { + host.onReleaseOldSourceFile(oldSourceFile, oldProgram.getCompilerOptions(), !!getSourceFileByPath(oldSourceFile.path)); + } + } + oldProgram.forEachResolvedProjectReference(function (resolvedProjectReference, resolvedProjectReferencePath) { + if (resolvedProjectReference && !getResolvedProjectReferenceByPath(resolvedProjectReferencePath)) { + host.onReleaseOldSourceFile(resolvedProjectReference.sourceFile, oldProgram.getCompilerOptions(), /*hasSourceFileByPath*/ false); + } + }); + } + // unconditionally set oldProgram to undefined to prevent it from being captured in closure + oldProgram = undefined; + program = { + getRootFileNames: function () { return rootNames; }, + getSourceFile: getSourceFile, + getSourceFileByPath: getSourceFileByPath, + getSourceFiles: function () { return files; }, + getMissingFilePaths: function () { return missingFilePaths; }, + getCompilerOptions: function () { return options; }, + getSyntacticDiagnostics: getSyntacticDiagnostics, + getOptionsDiagnostics: getOptionsDiagnostics, + getGlobalDiagnostics: getGlobalDiagnostics, + getSemanticDiagnostics: getSemanticDiagnostics, + getSuggestionDiagnostics: getSuggestionDiagnostics, + getDeclarationDiagnostics: getDeclarationDiagnostics, + getTypeChecker: getTypeChecker, + getClassifiableNames: getClassifiableNames, + getDiagnosticsProducingTypeChecker: getDiagnosticsProducingTypeChecker, + getCommonSourceDirectory: getCommonSourceDirectory, + emit: emit, + getCurrentDirectory: function () { return currentDirectory; }, + getNodeCount: function () { return getDiagnosticsProducingTypeChecker().getNodeCount(); }, + getIdentifierCount: function () { return getDiagnosticsProducingTypeChecker().getIdentifierCount(); }, + getSymbolCount: function () { return getDiagnosticsProducingTypeChecker().getSymbolCount(); }, + getTypeCount: function () { return getDiagnosticsProducingTypeChecker().getTypeCount(); }, + getFileProcessingDiagnostics: function () { return fileProcessingDiagnostics; }, + getResolvedTypeReferenceDirectives: function () { return resolvedTypeReferenceDirectives; }, + isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary, + isSourceFileDefaultLibrary: isSourceFileDefaultLibrary, + dropDiagnosticsProducingTypeChecker: dropDiagnosticsProducingTypeChecker, + getSourceFileFromReference: getSourceFileFromReference, + getLibFileFromReference: getLibFileFromReference, + sourceFileToPackageName: sourceFileToPackageName, + redirectTargetsMap: redirectTargetsMap, + isEmittedFile: isEmittedFile, + getConfigFileParsingDiagnostics: getConfigFileParsingDiagnostics, + getResolvedModuleWithFailedLookupLocationsFromCache: getResolvedModuleWithFailedLookupLocationsFromCache, + getProjectReferences: getProjectReferences, + getResolvedProjectReferences: getResolvedProjectReferences, + getProjectReferenceRedirect: getProjectReferenceRedirect, + getResolvedProjectReferenceToRedirect: getResolvedProjectReferenceToRedirect, + getResolvedProjectReferenceByPath: getResolvedProjectReferenceByPath, + forEachResolvedProjectReference: forEachResolvedProjectReference + }; + verifyCompilerOptions(); + ts.performance.mark("afterProgram"); + ts.performance.measure("Program", "beforeProgram", "afterProgram"); + return program; + function compareDefaultLibFiles(a, b) { + return ts.compareValues(getDefaultLibFilePriority(a), getDefaultLibFilePriority(b)); + } + function getDefaultLibFilePriority(a) { + if (ts.containsPath(defaultLibraryPath, a.fileName, /*ignoreCase*/ false)) { + var basename = ts.getBaseFileName(a.fileName); + if (basename === "lib.d.ts" || basename === "lib.es6.d.ts") + return 0; + var name = ts.removeSuffix(ts.removePrefix(basename, "lib."), ".d.ts"); + var index = ts.libs.indexOf(name); + if (index !== -1) + return index + 1; + } + return ts.libs.length + 2; + } + function getResolvedModuleWithFailedLookupLocationsFromCache(moduleName, containingFile) { + return moduleResolutionCache && ts.resolveModuleNameFromCache(moduleName, containingFile, moduleResolutionCache); + } + function toPath(fileName) { + return ts.toPath(fileName, currentDirectory, getCanonicalFileName); + } + function getCommonSourceDirectory() { + if (commonSourceDirectory === undefined) { + var emittedFiles = ts.filter(files, function (file) { return ts.sourceFileMayBeEmitted(file, options, isSourceFileFromExternalLibrary); }); + if (options.rootDir && checkSourceFilesBelongToPath(emittedFiles, options.rootDir)) { + // If a rootDir is specified use it as the commonSourceDirectory + commonSourceDirectory = ts.getNormalizedAbsolutePath(options.rootDir, currentDirectory); + } + else if (options.composite && options.configFilePath) { + // Project compilations never infer their root from the input source paths + commonSourceDirectory = ts.getDirectoryPath(ts.normalizeSlashes(options.configFilePath)); + checkSourceFilesBelongToPath(emittedFiles, commonSourceDirectory); + } + else { + commonSourceDirectory = computeCommonSourceDirectory(emittedFiles); + } + if (commonSourceDirectory && commonSourceDirectory[commonSourceDirectory.length - 1] !== ts.directorySeparator) { + // Make sure directory path ends with directory separator so this string can directly + // used to replace with "" to get the relative path of the source file and the relative path doesn't + // start with / making it rooted path + commonSourceDirectory += ts.directorySeparator; + } + } + return commonSourceDirectory; + } + function getClassifiableNames() { + if (!classifiableNames) { + // Initialize a checker so that all our files are bound. + getTypeChecker(); + classifiableNames = ts.createUnderscoreEscapedMap(); + for (var _i = 0, files_2 = files; _i < files_2.length; _i++) { + var sourceFile = files_2[_i]; + ts.copyEntries(sourceFile.classifiableNames, classifiableNames); + } + } + return classifiableNames; + } + function resolveModuleNamesReusingOldState(moduleNames, containingFile, file) { + if (structuralIsReused === 0 /* Not */ && !file.ambientModuleNames.length) { + // If the old program state does not permit reusing resolutions and `file` does not contain locally defined ambient modules, + // the best we can do is fallback to the default logic. + return resolveModuleNamesWorker(moduleNames, containingFile, /*reusedNames*/ undefined, getResolvedProjectReferenceToRedirect(file.originalFileName)); + } + var oldSourceFile = oldProgram && oldProgram.getSourceFile(containingFile); + if (oldSourceFile !== file && file.resolvedModules) { + // `file` was created for the new program. + // + // We only set `file.resolvedModules` via work from the current function, + // so it is defined iff we already called the current function on `file`. + // That call happened no later than the creation of the `file` object, + // which per above occurred during the current program creation. + // Since we assume the filesystem does not change during program creation, + // it is safe to reuse resolutions from the earlier call. + var result_5 = []; + for (var _i = 0, moduleNames_1 = moduleNames; _i < moduleNames_1.length; _i++) { + var moduleName = moduleNames_1[_i]; + var resolvedModule = file.resolvedModules.get(moduleName); + result_5.push(resolvedModule); + } + return result_5; + } + // At this point, we know at least one of the following hold: + // - file has local declarations for ambient modules + // - old program state is available + // With this information, we can infer some module resolutions without performing resolution. + /** An ordered list of module names for which we cannot recover the resolution. */ + var unknownModuleNames; + /** + * The indexing of elements in this list matches that of `moduleNames`. + * + * Before combining results, result[i] is in one of the following states: + * * undefined: needs to be recomputed, + * * predictedToResolveToAmbientModuleMarker: known to be an ambient module. + * Needs to be reset to undefined before returning, + * * ResolvedModuleFull instance: can be reused. + */ + var result; + var reusedNames; + /** A transient placeholder used to mark predicted resolution in the result list. */ + var predictedToResolveToAmbientModuleMarker = {}; + for (var i = 0; i < moduleNames.length; i++) { + var moduleName = moduleNames[i]; + // If the source file is unchanged and doesnt have invalidated resolution, reuse the module resolutions + if (file === oldSourceFile && !hasInvalidatedResolution(oldSourceFile.path)) { + var oldResolvedModule = oldSourceFile && oldSourceFile.resolvedModules.get(moduleName); + if (oldResolvedModule) { + if (ts.isTraceEnabled(options, host)) { + ts.trace(host, ts.Diagnostics.Reusing_resolution_of_module_0_to_file_1_from_old_program, moduleName, containingFile); + } + (result || (result = new Array(moduleNames.length)))[i] = oldResolvedModule; + (reusedNames || (reusedNames = [])).push(moduleName); + continue; + } + } + // We know moduleName resolves to an ambient module provided that moduleName: + // - is in the list of ambient modules locally declared in the current source file. + // - resolved to an ambient module in the old program whose declaration is in an unmodified file + // (so the same module declaration will land in the new program) + var resolvesToAmbientModuleInNonModifiedFile = false; + if (ts.contains(file.ambientModuleNames, moduleName)) { + resolvesToAmbientModuleInNonModifiedFile = true; + if (ts.isTraceEnabled(options, host)) { + ts.trace(host, ts.Diagnostics.Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1, moduleName, containingFile); + } + } + else { + resolvesToAmbientModuleInNonModifiedFile = moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName); + } + if (resolvesToAmbientModuleInNonModifiedFile) { + (result || (result = new Array(moduleNames.length)))[i] = predictedToResolveToAmbientModuleMarker; + } + else { + // Resolution failed in the old program, or resolved to an ambient module for which we can't reuse the result. + (unknownModuleNames || (unknownModuleNames = [])).push(moduleName); + } + } + var resolutions = unknownModuleNames && unknownModuleNames.length + ? resolveModuleNamesWorker(unknownModuleNames, containingFile, reusedNames, getResolvedProjectReferenceToRedirect(file.originalFileName)) + : ts.emptyArray; + // Combine results of resolutions and predicted results + if (!result) { + // There were no unresolved/ambient resolutions. + ts.Debug.assert(resolutions.length === moduleNames.length); + return resolutions; + } + var j = 0; + for (var i = 0; i < result.length; i++) { + if (result[i]) { + // `result[i]` is either a `ResolvedModuleFull` or a marker. + // If it is the former, we can leave it as is. + if (result[i] === predictedToResolveToAmbientModuleMarker) { + result[i] = undefined; // TODO: GH#18217 + } + } + else { + result[i] = resolutions[j]; + j++; + } + } + ts.Debug.assert(j === resolutions.length); + return result; + // If we change our policy of rechecking failed lookups on each program create, + // we should adjust the value returned here. + function moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName) { + var resolutionToFile = ts.getResolvedModule(oldSourceFile, moduleName); + var resolvedFile = resolutionToFile && oldProgram.getSourceFile(resolutionToFile.resolvedFileName); + if (resolutionToFile && resolvedFile && !resolvedFile.externalModuleIndicator) { + // In the old program, we resolved to an ambient module that was in the same + // place as we expected to find an actual module file. + // We actually need to return 'false' here even though this seems like a 'true' case + // because the normal module resolution algorithm will find this anyway. + return false; + } + // at least one of declarations should come from non-modified source file + var unmodifiedFile = ambientModuleNameToUnmodifiedFileName.get(moduleName); + if (!unmodifiedFile) { + return false; + } + if (ts.isTraceEnabled(options, host)) { + ts.trace(host, ts.Diagnostics.Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified, moduleName, unmodifiedFile); + } + return true; + } + } + function canReuseProjectReferences() { + return !forEachProjectReference(oldProgram.getProjectReferences(), oldProgram.getResolvedProjectReferences(), function (oldResolvedRef, index, parent) { + var newRef = (parent ? parent.commandLine.projectReferences : projectReferences)[index]; + var newResolvedRef = parseProjectReferenceConfigFile(newRef); + if (oldResolvedRef) { + // Resolved project reference has gone missing or changed + return !newResolvedRef || newResolvedRef.sourceFile !== oldResolvedRef.sourceFile; + } + else { + // A previously-unresolved reference may be resolved now + return newResolvedRef !== undefined; + } + }, function (oldProjectReferences, parent) { + // If array of references is changed, we cant resue old program + var newReferences = parent ? getResolvedProjectReferenceByPath(parent.sourceFile.path).commandLine.projectReferences : projectReferences; + return !ts.arrayIsEqualTo(oldProjectReferences, newReferences, ts.projectReferenceIsEqualTo); + }); + } + function tryReuseStructureFromOldProgram() { + if (!oldProgram) { + return 0 /* Not */; + } + // check properties that can affect structure of the program or module resolution strategy + // if any of these properties has changed - structure cannot be reused + var oldOptions = oldProgram.getCompilerOptions(); + if (ts.changesAffectModuleResolution(oldOptions, options)) { + return oldProgram.structureIsReused = 0 /* Not */; + } + ts.Debug.assert(!(oldProgram.structureIsReused & (2 /* Completely */ | 1 /* SafeModules */))); + // there is an old program, check if we can reuse its structure + var oldRootNames = oldProgram.getRootFileNames(); + if (!ts.arrayIsEqualTo(oldRootNames, rootNames)) { + return oldProgram.structureIsReused = 0 /* Not */; + } + if (!ts.arrayIsEqualTo(options.types, oldOptions.types)) { + return oldProgram.structureIsReused = 0 /* Not */; + } + // Check if any referenced project tsconfig files are different + if (!canReuseProjectReferences()) { + return oldProgram.structureIsReused = 0 /* Not */; + } + if (projectReferences) { + resolvedProjectReferences = projectReferences.map(parseProjectReferenceConfigFile); + } + // check if program source files has changed in the way that can affect structure of the program + var newSourceFiles = []; + var modifiedSourceFiles = []; + oldProgram.structureIsReused = 2 /* Completely */; + // If the missing file paths are now present, it can change the progam structure, + // and hence cant reuse the structure. + // This is same as how we dont reuse the structure if one of the file from old program is now missing + if (oldProgram.getMissingFilePaths().some(function (missingFilePath) { return host.fileExists(missingFilePath); })) { + return oldProgram.structureIsReused = 0 /* Not */; + } + var oldSourceFiles = oldProgram.getSourceFiles(); + var SeenPackageName; + (function (SeenPackageName) { + SeenPackageName[SeenPackageName["Exists"] = 0] = "Exists"; + SeenPackageName[SeenPackageName["Modified"] = 1] = "Modified"; + })(SeenPackageName || (SeenPackageName = {})); + var seenPackageNames = ts.createMap(); + for (var _i = 0, oldSourceFiles_2 = oldSourceFiles; _i < oldSourceFiles_2.length; _i++) { + var oldSourceFile = oldSourceFiles_2[_i]; + var newSourceFile = host.getSourceFileByPath + ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.resolvedPath, options.target, /*onError*/ undefined, shouldCreateNewSourceFile) + : host.getSourceFile(oldSourceFile.fileName, options.target, /*onError*/ undefined, shouldCreateNewSourceFile); // TODO: GH#18217 + if (!newSourceFile) { + return oldProgram.structureIsReused = 0 /* Not */; + } + ts.Debug.assert(!newSourceFile.redirectInfo, "Host should not return a redirect source file from `getSourceFile`"); + var fileChanged = void 0; + if (oldSourceFile.redirectInfo) { + // We got `newSourceFile` by path, so it is actually for the unredirected file. + // This lets us know if the unredirected file has changed. If it has we should break the redirect. + if (newSourceFile !== oldSourceFile.redirectInfo.unredirected) { + // Underlying file has changed. Might not redirect anymore. Must rebuild program. + return oldProgram.structureIsReused = 0 /* Not */; + } + fileChanged = false; + newSourceFile = oldSourceFile; // Use the redirect. + } + else if (oldProgram.redirectTargetsMap.has(oldSourceFile.path)) { + // If a redirected-to source file changes, the redirect may be broken. + if (newSourceFile !== oldSourceFile) { + return oldProgram.structureIsReused = 0 /* Not */; + } + fileChanged = false; + } + else { + fileChanged = newSourceFile !== oldSourceFile; + } + // Since the project references havent changed, its right to set originalFileName and resolvedPath here + newSourceFile.path = oldSourceFile.path; + newSourceFile.originalFileName = oldSourceFile.originalFileName; + newSourceFile.resolvedPath = oldSourceFile.resolvedPath; + newSourceFile.fileName = oldSourceFile.fileName; + var packageName = oldProgram.sourceFileToPackageName.get(oldSourceFile.path); + if (packageName !== undefined) { + // If there are 2 different source files for the same package name and at least one of them changes, + // they might become redirects. So we must rebuild the program. + var prevKind = seenPackageNames.get(packageName); + var newKind = fileChanged ? 1 /* Modified */ : 0 /* Exists */; + if ((prevKind !== undefined && newKind === 1 /* Modified */) || prevKind === 1 /* Modified */) { + return oldProgram.structureIsReused = 0 /* Not */; + } + seenPackageNames.set(packageName, newKind); + } + if (fileChanged) { + // The `newSourceFile` object was created for the new program. + if (!ts.arrayIsEqualTo(oldSourceFile.libReferenceDirectives, newSourceFile.libReferenceDirectives, fileReferenceIsEqualTo)) { + // 'lib' references has changed. Matches behavior in changesAffectModuleResolution + return oldProgram.structureIsReused = 0 /* Not */; + } + if (oldSourceFile.hasNoDefaultLib !== newSourceFile.hasNoDefaultLib) { + // value of no-default-lib has changed + // this will affect if default library is injected into the list of files + oldProgram.structureIsReused = 1 /* SafeModules */; + } + // check tripleslash references + if (!ts.arrayIsEqualTo(oldSourceFile.referencedFiles, newSourceFile.referencedFiles, fileReferenceIsEqualTo)) { + // tripleslash references has changed + oldProgram.structureIsReused = 1 /* SafeModules */; + } + // check imports and module augmentations + collectExternalModuleReferences(newSourceFile); + if (!ts.arrayIsEqualTo(oldSourceFile.imports, newSourceFile.imports, moduleNameIsEqualTo)) { + // imports has changed + oldProgram.structureIsReused = 1 /* SafeModules */; + } + if (!ts.arrayIsEqualTo(oldSourceFile.moduleAugmentations, newSourceFile.moduleAugmentations, moduleNameIsEqualTo)) { + // moduleAugmentations has changed + oldProgram.structureIsReused = 1 /* SafeModules */; + } + if ((oldSourceFile.flags & 1572864 /* PermanentlySetIncrementalFlags */) !== (newSourceFile.flags & 1572864 /* PermanentlySetIncrementalFlags */)) { + // dynamicImport has changed + oldProgram.structureIsReused = 1 /* SafeModules */; + } + if (!ts.arrayIsEqualTo(oldSourceFile.typeReferenceDirectives, newSourceFile.typeReferenceDirectives, fileReferenceIsEqualTo)) { + // 'types' references has changed + oldProgram.structureIsReused = 1 /* SafeModules */; + } + // tentatively approve the file + modifiedSourceFiles.push({ oldFile: oldSourceFile, newFile: newSourceFile }); + } + else if (hasInvalidatedResolution(oldSourceFile.path)) { + // 'module/types' references could have changed + oldProgram.structureIsReused = 1 /* SafeModules */; + // add file to the modified list so that we will resolve it later + modifiedSourceFiles.push({ oldFile: oldSourceFile, newFile: newSourceFile }); + } + // if file has passed all checks it should be safe to reuse it + newSourceFiles.push(newSourceFile); + } + if (oldProgram.structureIsReused !== 2 /* Completely */) { + return oldProgram.structureIsReused; + } + var modifiedFiles = modifiedSourceFiles.map(function (f) { return f.oldFile; }); + for (var _a = 0, oldSourceFiles_3 = oldSourceFiles; _a < oldSourceFiles_3.length; _a++) { + var oldFile = oldSourceFiles_3[_a]; + if (!ts.contains(modifiedFiles, oldFile)) { + for (var _b = 0, _c = oldFile.ambientModuleNames; _b < _c.length; _b++) { + var moduleName = _c[_b]; + ambientModuleNameToUnmodifiedFileName.set(moduleName, oldFile.fileName); + } + } + } + // try to verify results of module resolution + for (var _d = 0, modifiedSourceFiles_1 = modifiedSourceFiles; _d < modifiedSourceFiles_1.length; _d++) { + var _e = modifiedSourceFiles_1[_d], oldSourceFile = _e.oldFile, newSourceFile = _e.newFile; + var newSourceFilePath = ts.getNormalizedAbsolutePath(newSourceFile.originalFileName, currentDirectory); + if (resolveModuleNamesWorker) { + var moduleNames = getModuleNames(newSourceFile); + var resolutions = resolveModuleNamesReusingOldState(moduleNames, newSourceFilePath, newSourceFile); + // ensure that module resolution results are still correct + var resolutionsChanged = ts.hasChangesInResolutions(moduleNames, resolutions, oldSourceFile.resolvedModules, ts.moduleResolutionIsEqualTo); + if (resolutionsChanged) { + oldProgram.structureIsReused = 1 /* SafeModules */; + newSourceFile.resolvedModules = ts.zipToMap(moduleNames, resolutions); + } + else { + newSourceFile.resolvedModules = oldSourceFile.resolvedModules; + } + } + if (resolveTypeReferenceDirectiveNamesWorker) { + // We lower-case all type references because npm automatically lowercases all packages. See GH#9824. + var typesReferenceDirectives = ts.map(newSourceFile.typeReferenceDirectives, function (ref) { return ref.fileName.toLocaleLowerCase(); }); + var resolutions = resolveTypeReferenceDirectiveNamesWorker(typesReferenceDirectives, newSourceFilePath, getResolvedProjectReferenceToRedirect(newSourceFile.originalFileName)); + // ensure that types resolutions are still correct + var resolutionsChanged = ts.hasChangesInResolutions(typesReferenceDirectives, resolutions, oldSourceFile.resolvedTypeReferenceDirectiveNames, ts.typeDirectiveIsEqualTo); + if (resolutionsChanged) { + oldProgram.structureIsReused = 1 /* SafeModules */; + newSourceFile.resolvedTypeReferenceDirectiveNames = ts.zipToMap(typesReferenceDirectives, resolutions); + } + else { + newSourceFile.resolvedTypeReferenceDirectiveNames = oldSourceFile.resolvedTypeReferenceDirectiveNames; + } + } + } + if (oldProgram.structureIsReused !== 2 /* Completely */) { + return oldProgram.structureIsReused; + } + if (host.hasChangedAutomaticTypeDirectiveNames) { + return oldProgram.structureIsReused = 1 /* SafeModules */; + } + missingFilePaths = oldProgram.getMissingFilePaths(); + // update fileName -> file mapping + for (var _f = 0, newSourceFiles_1 = newSourceFiles; _f < newSourceFiles_1.length; _f++) { + var newSourceFile = newSourceFiles_1[_f]; + var filePath = newSourceFile.path; + addFileToFilesByName(newSourceFile, filePath, newSourceFile.resolvedPath); + // Set the file as found during node modules search if it was found that way in old progra, + if (oldProgram.isSourceFileFromExternalLibrary(oldProgram.getSourceFileByPath(filePath))) { + sourceFilesFoundSearchingNodeModules.set(filePath, true); + } + } + files = newSourceFiles; + fileProcessingDiagnostics = oldProgram.getFileProcessingDiagnostics(); + for (var _g = 0, modifiedSourceFiles_2 = modifiedSourceFiles; _g < modifiedSourceFiles_2.length; _g++) { + var modifiedFile = modifiedSourceFiles_2[_g]; + fileProcessingDiagnostics.reattachFileDiagnostics(modifiedFile.newFile); + } + resolvedTypeReferenceDirectives = oldProgram.getResolvedTypeReferenceDirectives(); + sourceFileToPackageName = oldProgram.sourceFileToPackageName; + redirectTargetsMap = oldProgram.redirectTargetsMap; + return oldProgram.structureIsReused = 2 /* Completely */; + } + function getEmitHost(writeFileCallback) { + return __assign({ getPrependNodes: getPrependNodes, + getCanonicalFileName: getCanonicalFileName, getCommonSourceDirectory: program.getCommonSourceDirectory, getCompilerOptions: program.getCompilerOptions, getCurrentDirectory: function () { return currentDirectory; }, getNewLine: function () { return host.getNewLine(); }, getSourceFile: program.getSourceFile, getSourceFileByPath: program.getSourceFileByPath, getSourceFiles: program.getSourceFiles, getLibFileFromReference: program.getLibFileFromReference, isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary, writeFile: writeFileCallback || (function (fileName, data, writeByteOrderMark, onError, sourceFiles) { return host.writeFile(fileName, data, writeByteOrderMark, onError, sourceFiles); }), isEmitBlocked: isEmitBlocked, readFile: function (f) { return host.readFile(f); }, fileExists: function (f) { + // Use local caches + var path = toPath(f); + if (getSourceFileByPath(path)) + return true; + if (ts.contains(missingFilePaths, path)) + return false; + // Before falling back to the host + return host.fileExists(f); + } }, (host.directoryExists ? { directoryExists: function (f) { return host.directoryExists(f); } } : {}), { useCaseSensitiveFileNames: function () { return host.useCaseSensitiveFileNames(); } }); + } + function getResolvedProjectReferences() { + return resolvedProjectReferences; + } + function getProjectReferences() { + return projectReferences; + } + function getPrependNodes() { + if (!projectReferences) { + return ts.emptyArray; + } + var nodes = []; + for (var i = 0; i < projectReferences.length; i++) { + var ref = projectReferences[i]; + var resolvedRefOpts = resolvedProjectReferences[i].commandLine; + if (ref.prepend && resolvedRefOpts && resolvedRefOpts.options) { + var out = resolvedRefOpts.options.outFile || resolvedRefOpts.options.out; + // Upstream project didn't have outFile set -- skip (error will have been issued earlier) + if (!out) + continue; + var dtsFilename = ts.changeExtension(out, ".d.ts"); + var js = host.readFile(out) || "/* Input file " + out + " was missing */\r\n"; + var jsMapPath = out + ".map"; // TODO: try to read sourceMappingUrl comment from the file + var jsMap = host.readFile(jsMapPath); + var dts = host.readFile(dtsFilename) || "/* Input file " + dtsFilename + " was missing */\r\n"; + var dtsMapPath = dtsFilename + ".map"; + var dtsMap = host.readFile(dtsMapPath); + var node = ts.createInputFiles(js, dts, jsMap && jsMapPath, jsMap, dtsMap && dtsMapPath, dtsMap); + nodes.push(node); + } + } + return nodes; + } + function isSourceFileFromExternalLibrary(file) { + return !!sourceFilesFoundSearchingNodeModules.get(file.path); + } + function isSourceFileDefaultLibrary(file) { + if (file.hasNoDefaultLib) { + return true; + } + if (!options.noLib) { + return false; + } + // If '--lib' is not specified, include default library file according to '--target' + // otherwise, using options specified in '--lib' instead of '--target' default library file + var equalityComparer = host.useCaseSensitiveFileNames() ? ts.equateStringsCaseSensitive : ts.equateStringsCaseInsensitive; + if (!options.lib) { + return equalityComparer(file.fileName, getDefaultLibraryFileName()); + } + else { + return ts.some(options.lib, function (libFileName) { return equalityComparer(file.fileName, ts.combinePaths(defaultLibraryPath, libFileName)); }); + } + } + function getDiagnosticsProducingTypeChecker() { + return diagnosticsProducingTypeChecker || (diagnosticsProducingTypeChecker = ts.createTypeChecker(program, /*produceDiagnostics:*/ true)); + } + function dropDiagnosticsProducingTypeChecker() { + diagnosticsProducingTypeChecker = undefined; + } + function getTypeChecker() { + return noDiagnosticsTypeChecker || (noDiagnosticsTypeChecker = ts.createTypeChecker(program, /*produceDiagnostics:*/ false)); + } + function emit(sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles, transformers) { + return runWithCancellationToken(function () { return emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles, transformers); }); + } + function isEmitBlocked(emitFileName) { + return hasEmitBlockingDiagnostics.has(toPath(emitFileName)); + } + function emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles, customTransformers) { + var declarationDiagnostics = []; + if (!emitOnlyDtsFiles) { + if (options.noEmit) { + return { diagnostics: declarationDiagnostics, sourceMaps: undefined, emittedFiles: undefined, emitSkipped: true }; + } + // If the noEmitOnError flag is set, then check if we have any errors so far. If so, + // immediately bail out. Note that we pass 'undefined' for 'sourceFile' so that we + // get any preEmit diagnostics, not just the ones + if (options.noEmitOnError) { + var diagnostics = program.getOptionsDiagnostics(cancellationToken).concat(program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken)); + if (diagnostics.length === 0 && ts.getEmitDeclarations(program.getCompilerOptions())) { + declarationDiagnostics = program.getDeclarationDiagnostics(/*sourceFile*/ undefined, cancellationToken); + } + if (diagnostics.length > 0 || declarationDiagnostics.length > 0) { + return { + diagnostics: ts.concatenate(diagnostics, declarationDiagnostics), + sourceMaps: undefined, + emittedFiles: undefined, + emitSkipped: true + }; + } + } + } + // Create the emit resolver outside of the "emitTime" tracking code below. That way + // any cost associated with it (like type checking) are appropriate associated with + // the type-checking counter. + // + // If the -out option is specified, we should not pass the source file to getEmitResolver. + // This is because in the -out scenario all files need to be emitted, and therefore all + // files need to be type checked. And the way to specify that all files need to be type + // checked is to not pass the file to getEmitResolver. + var emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile, cancellationToken); + ts.performance.mark("beforeEmit"); + var transformers = emitOnlyDtsFiles ? [] : ts.getTransformers(options, customTransformers); + var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile, // TODO: GH#18217 + emitOnlyDtsFiles, transformers, customTransformers && customTransformers.afterDeclarations); + ts.performance.mark("afterEmit"); + ts.performance.measure("Emit", "beforeEmit", "afterEmit"); + return emitResult; + } + function getSourceFile(fileName) { + return getSourceFileByPath(toPath(fileName)); + } + function getSourceFileByPath(path) { + return filesByName.get(path); + } + function getDiagnosticsHelper(sourceFile, getDiagnostics, cancellationToken) { + if (sourceFile) { + return getDiagnostics(sourceFile, cancellationToken); + } + return ts.sortAndDeduplicateDiagnostics(ts.flatMap(program.getSourceFiles(), function (sourceFile) { + if (cancellationToken) { + cancellationToken.throwIfCancellationRequested(); + } + return getDiagnostics(sourceFile, cancellationToken); + })); + } + function getSyntacticDiagnostics(sourceFile, cancellationToken) { + return getDiagnosticsHelper(sourceFile, getSyntacticDiagnosticsForFile, cancellationToken); + } + function getSemanticDiagnostics(sourceFile, cancellationToken) { + return getDiagnosticsHelper(sourceFile, getSemanticDiagnosticsForFile, cancellationToken); + } + function getDeclarationDiagnostics(sourceFile, cancellationToken) { + var options = program.getCompilerOptions(); + // collect diagnostics from the program only once if either no source file was specified or out/outFile is set (bundled emit) + if (!sourceFile || options.out || options.outFile) { + return getDeclarationDiagnosticsWorker(sourceFile, cancellationToken); + } + else { + return getDiagnosticsHelper(sourceFile, getDeclarationDiagnosticsForFile, cancellationToken); + } + } + function getSyntacticDiagnosticsForFile(sourceFile) { + // For JavaScript files, we report semantic errors for using TypeScript-only + // constructs from within a JavaScript file as syntactic errors. + if (ts.isSourceFileJS(sourceFile)) { + if (!sourceFile.additionalSyntacticDiagnostics) { + sourceFile.additionalSyntacticDiagnostics = getJSSyntacticDiagnosticsForFile(sourceFile); + } + return ts.concatenate(sourceFile.additionalSyntacticDiagnostics, sourceFile.parseDiagnostics); + } + return sourceFile.parseDiagnostics; + } + function runWithCancellationToken(func) { + try { + return func(); + } + catch (e) { + if (e instanceof ts.OperationCanceledException) { + // We were canceled while performing the operation. Because our type checker + // might be a bad state, we need to throw it away. + // + // Note: we are overly aggressive here. We do not actually *have* to throw away + // the "noDiagnosticsTypeChecker". However, for simplicity, i'd like to keep + // the lifetimes of these two TypeCheckers the same. Also, we generally only + // cancel when the user has made a change anyways. And, in that case, we (the + // program instance) will get thrown away anyways. So trying to keep one of + // these type checkers alive doesn't serve much purpose. + noDiagnosticsTypeChecker = undefined; + diagnosticsProducingTypeChecker = undefined; + } + throw e; + } + } + function getSemanticDiagnosticsForFile(sourceFile, cancellationToken) { + return getAndCacheDiagnostics(sourceFile, cancellationToken, cachedSemanticDiagnosticsForFile, getSemanticDiagnosticsForFileNoCache); + } + function getSemanticDiagnosticsForFileNoCache(sourceFile, cancellationToken) { + return runWithCancellationToken(function () { + if (ts.skipTypeChecking(sourceFile, options)) { + return ts.emptyArray; + } + var typeChecker = getDiagnosticsProducingTypeChecker(); + ts.Debug.assert(!!sourceFile.bindDiagnostics); + var isCheckJs = ts.isCheckJsEnabledForFile(sourceFile, options); + // By default, only type-check .ts, .tsx, 'Deferred' and 'External' files (external files are added by plugins) + var includeBindAndCheckDiagnostics = sourceFile.scriptKind === 3 /* TS */ || sourceFile.scriptKind === 4 /* TSX */ || + sourceFile.scriptKind === 5 /* External */ || isCheckJs || sourceFile.scriptKind === 7 /* Deferred */; + var bindDiagnostics = includeBindAndCheckDiagnostics ? sourceFile.bindDiagnostics : ts.emptyArray; + var checkDiagnostics = includeBindAndCheckDiagnostics ? typeChecker.getDiagnostics(sourceFile, cancellationToken) : ts.emptyArray; + var fileProcessingDiagnosticsInFile = fileProcessingDiagnostics.getDiagnostics(sourceFile.fileName); + var programDiagnosticsInFile = programDiagnostics.getDiagnostics(sourceFile.fileName); + var diagnostics; + for (var _i = 0, _a = [bindDiagnostics, checkDiagnostics, fileProcessingDiagnosticsInFile, programDiagnosticsInFile, isCheckJs ? sourceFile.jsDocDiagnostics : undefined]; _i < _a.length; _i++) { + var diags = _a[_i]; + if (diags) { + for (var _b = 0, diags_1 = diags; _b < diags_1.length; _b++) { + var diag = diags_1[_b]; + if (shouldReportDiagnostic(diag)) { + diagnostics = ts.append(diagnostics, diag); + } + } + } + } + return diagnostics; + }); + } + function getSuggestionDiagnostics(sourceFile, cancellationToken) { + return runWithCancellationToken(function () { + return getDiagnosticsProducingTypeChecker().getSuggestionDiagnostics(sourceFile, cancellationToken); + }); + } + /** + * Skip errors if previous line start with '// @ts-ignore' comment, not counting non-empty non-comment lines + */ + function shouldReportDiagnostic(diagnostic) { + var file = diagnostic.file, start = diagnostic.start; + if (file) { + var lineStarts = ts.getLineStarts(file); + var line = ts.computeLineAndCharacterOfPosition(lineStarts, start).line; // TODO: GH#18217 + while (line > 0) { + var previousLineText = file.text.slice(lineStarts[line - 1], lineStarts[line]); + var result = ignoreDiagnosticCommentRegEx.exec(previousLineText); + if (!result) { + // non-empty line + return true; + } + if (result[3]) { + // @ts-ignore + return false; + } + line--; + } + } + return true; + } + function getJSSyntacticDiagnosticsForFile(sourceFile) { + return runWithCancellationToken(function () { + var diagnostics = []; + var parent = sourceFile; + walk(sourceFile); + return diagnostics; + function walk(node) { + // Return directly from the case if the given node doesnt want to visit each child + // Otherwise break to visit each child + switch (parent.kind) { + case 151 /* Parameter */: + case 154 /* PropertyDeclaration */: + if (parent.questionToken === node) { + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, "?")); + return; + } + // falls through + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 196 /* FunctionExpression */: + case 239 /* FunctionDeclaration */: + case 197 /* ArrowFunction */: + case 237 /* VariableDeclaration */: + // type annotation + if (parent.type === node) { + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.types_can_only_be_used_in_a_ts_file)); + return; + } + } + switch (node.kind) { + case 248 /* ImportEqualsDeclaration */: + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.import_can_only_be_used_in_a_ts_file)); + return; + case 254 /* ExportAssignment */: + if (node.isExportEquals) { + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.export_can_only_be_used_in_a_ts_file)); + return; + } + break; + case 273 /* HeritageClause */: + var heritageClause = node; + if (heritageClause.token === 109 /* ImplementsKeyword */) { + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.implements_clauses_can_only_be_used_in_a_ts_file)); + return; + } + break; + case 241 /* InterfaceDeclaration */: + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.interface_declarations_can_only_be_used_in_a_ts_file)); + return; + case 244 /* ModuleDeclaration */: + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.module_declarations_can_only_be_used_in_a_ts_file)); + return; + case 242 /* TypeAliasDeclaration */: + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.type_aliases_can_only_be_used_in_a_ts_file)); + return; + case 243 /* EnumDeclaration */: + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.enum_declarations_can_only_be_used_in_a_ts_file)); + return; + case 213 /* NonNullExpression */: + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.non_null_assertions_can_only_be_used_in_a_ts_file)); + return; + case 212 /* AsExpression */: + diagnostics.push(createDiagnosticForNode(node.type, ts.Diagnostics.type_assertion_expressions_can_only_be_used_in_a_ts_file)); + return; + case 194 /* TypeAssertionExpression */: + ts.Debug.fail(); // Won't parse these in a JS file anyway, as they are interpreted as JSX. + } + var prevParent = parent; + parent = node; + ts.forEachChild(node, walk, walkArray); + parent = prevParent; + } + function walkArray(nodes) { + if (parent.decorators === nodes && !options.experimentalDecorators) { + diagnostics.push(createDiagnosticForNode(parent, ts.Diagnostics.Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_to_remove_this_warning)); + } + switch (parent.kind) { + case 240 /* ClassDeclaration */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 196 /* FunctionExpression */: + case 239 /* FunctionDeclaration */: + case 197 /* ArrowFunction */: + // Check type parameters + if (nodes === parent.typeParameters) { + diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.type_parameter_declarations_can_only_be_used_in_a_ts_file)); + return; + } + // falls through + case 219 /* VariableStatement */: + // Check modifiers + if (nodes === parent.modifiers) { + return checkModifiers(nodes, parent.kind === 219 /* VariableStatement */); + } + break; + case 154 /* PropertyDeclaration */: + // Check modifiers of property declaration + if (nodes === parent.modifiers) { + for (var _i = 0, _a = nodes; _i < _a.length; _i++) { + var modifier = _a[_i]; + if (modifier.kind !== 116 /* StaticKeyword */) { + diagnostics.push(createDiagnosticForNode(modifier, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, ts.tokenToString(modifier.kind))); + } + } + return; + } + break; + case 151 /* Parameter */: + // Check modifiers of parameter declaration + if (nodes === parent.modifiers) { + diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.parameter_modifiers_can_only_be_used_in_a_ts_file)); + return; + } + break; + case 191 /* CallExpression */: + case 192 /* NewExpression */: + case 211 /* ExpressionWithTypeArguments */: + case 261 /* JsxSelfClosingElement */: + case 262 /* JsxOpeningElement */: + // Check type arguments + if (nodes === parent.typeArguments) { + diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.type_arguments_can_only_be_used_in_a_ts_file)); + return; + } + break; + } + for (var _b = 0, nodes_6 = nodes; _b < nodes_6.length; _b++) { + var node = nodes_6[_b]; + walk(node); + } + } + function checkModifiers(modifiers, isConstValid) { + for (var _i = 0, modifiers_1 = modifiers; _i < modifiers_1.length; _i++) { + var modifier = modifiers_1[_i]; + switch (modifier.kind) { + case 77 /* ConstKeyword */: + if (isConstValid) { + continue; + } + // to report error, + // falls through + case 115 /* PublicKeyword */: + case 113 /* PrivateKeyword */: + case 114 /* ProtectedKeyword */: + case 133 /* ReadonlyKeyword */: + case 125 /* DeclareKeyword */: + case 118 /* AbstractKeyword */: + diagnostics.push(createDiagnosticForNode(modifier, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, ts.tokenToString(modifier.kind))); + break; + // These are all legal modifiers. + case 116 /* StaticKeyword */: + case 85 /* ExportKeyword */: + case 80 /* DefaultKeyword */: + } + } + } + function createDiagnosticForNodeArray(nodes, message, arg0, arg1, arg2) { + var start = nodes.pos; + return ts.createFileDiagnostic(sourceFile, start, nodes.end - start, message, arg0, arg1, arg2); + } + // Since these are syntactic diagnostics, parent might not have been set + // this means the sourceFile cannot be infered from the node + function createDiagnosticForNode(node, message, arg0, arg1, arg2) { + return ts.createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2); + } + }); + } + function getDeclarationDiagnosticsWorker(sourceFile, cancellationToken) { + return getAndCacheDiagnostics(sourceFile, cancellationToken, cachedDeclarationDiagnosticsForFile, getDeclarationDiagnosticsForFileNoCache); + } + function getDeclarationDiagnosticsForFileNoCache(sourceFile, cancellationToken) { + return runWithCancellationToken(function () { + var resolver = getDiagnosticsProducingTypeChecker().getEmitResolver(sourceFile, cancellationToken); + // Don't actually write any files since we're just getting diagnostics. + return ts.getDeclarationDiagnostics(getEmitHost(ts.noop), resolver, sourceFile); + }); + } + function getAndCacheDiagnostics(sourceFile, cancellationToken, cache, getDiagnostics) { + var cachedResult = sourceFile + ? cache.perFile && cache.perFile.get(sourceFile.path) + : cache.allDiagnostics; + if (cachedResult) { + return cachedResult; + } + var result = getDiagnostics(sourceFile, cancellationToken) || ts.emptyArray; // TODO: GH#18217 + if (sourceFile) { + if (!cache.perFile) { + cache.perFile = ts.createMap(); + } + cache.perFile.set(sourceFile.path, result); + } + else { + cache.allDiagnostics = result; + } + return result; + } + function getDeclarationDiagnosticsForFile(sourceFile, cancellationToken) { + return sourceFile.isDeclarationFile ? [] : getDeclarationDiagnosticsWorker(sourceFile, cancellationToken); + } + function getOptionsDiagnostics() { + return ts.sortAndDeduplicateDiagnostics(ts.concatenate(fileProcessingDiagnostics.getGlobalDiagnostics(), ts.concatenate(programDiagnostics.getGlobalDiagnostics(), getOptionsDiagnosticsOfConfigFile()))); + } + function getOptionsDiagnosticsOfConfigFile() { + if (!options.configFile) { + return ts.emptyArray; + } + var diagnostics = programDiagnostics.getDiagnostics(options.configFile.fileName); + forEachResolvedProjectReference(function (resolvedRef) { + if (resolvedRef) { + diagnostics = ts.concatenate(diagnostics, programDiagnostics.getDiagnostics(resolvedRef.sourceFile.fileName)); + } + }); + return diagnostics; + } + function getGlobalDiagnostics() { + return rootNames.length ? ts.sortAndDeduplicateDiagnostics(getDiagnosticsProducingTypeChecker().getGlobalDiagnostics().slice()) : ts.emptyArray; + } + function getConfigFileParsingDiagnostics() { + return configFileParsingDiagnostics || ts.emptyArray; + } + function processRootFile(fileName, isDefaultLib, ignoreNoDefaultLib) { + processSourceFile(ts.normalizePath(fileName), isDefaultLib, ignoreNoDefaultLib, /*packageId*/ undefined); + } + function fileReferenceIsEqualTo(a, b) { + return a.fileName === b.fileName; + } + function moduleNameIsEqualTo(a, b) { + return a.kind === 72 /* Identifier */ + ? b.kind === 72 /* Identifier */ && a.escapedText === b.escapedText + : b.kind === 10 /* StringLiteral */ && a.text === b.text; + } + function collectExternalModuleReferences(file) { + if (file.imports) { + return; + } + var isJavaScriptFile = ts.isSourceFileJS(file); + var isExternalModuleFile = ts.isExternalModule(file); + // file.imports may not be undefined if there exists dynamic import + var imports; + var moduleAugmentations; + var ambientModules; + // If we are importing helpers, we need to add a synthetic reference to resolve the + // helpers library. + if (options.importHelpers + && (options.isolatedModules || isExternalModuleFile) + && !file.isDeclarationFile) { + // synthesize 'import "tslib"' declaration + var externalHelpersModuleReference = ts.createLiteral(ts.externalHelpersModuleNameText); + var importDecl = ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*importClause*/ undefined, externalHelpersModuleReference); + ts.addEmitFlags(importDecl, 67108864 /* NeverApplyImportHelper */); + externalHelpersModuleReference.parent = importDecl; + importDecl.parent = file; + imports = [externalHelpersModuleReference]; + } + for (var _i = 0, _a = file.statements; _i < _a.length; _i++) { + var node = _a[_i]; + collectModuleReferences(node, /*inAmbientModule*/ false); + } + if ((file.flags & 524288 /* PossiblyContainsDynamicImport */) || isJavaScriptFile) { + collectDynamicImportOrRequireCalls(file); + } + file.imports = imports || ts.emptyArray; + file.moduleAugmentations = moduleAugmentations || ts.emptyArray; + file.ambientModuleNames = ambientModules || ts.emptyArray; + return; + function collectModuleReferences(node, inAmbientModule) { + if (ts.isAnyImportOrReExport(node)) { + var moduleNameExpr = ts.getExternalModuleName(node); + // TypeScript 1.0 spec (April 2014): 12.1.6 + // An ExternalImportDeclaration in an AmbientExternalModuleDeclaration may reference other external modules + // only through top - level external module names. Relative external module names are not permitted. + if (moduleNameExpr && ts.isStringLiteral(moduleNameExpr) && moduleNameExpr.text && (!inAmbientModule || !ts.isExternalModuleNameRelative(moduleNameExpr.text))) { + imports = ts.append(imports, moduleNameExpr); + } + } + else if (ts.isModuleDeclaration(node)) { + if (ts.isAmbientModule(node) && (inAmbientModule || ts.hasModifier(node, 2 /* Ambient */) || file.isDeclarationFile)) { + var nameText = ts.getTextOfIdentifierOrLiteral(node.name); + // Ambient module declarations can be interpreted as augmentations for some existing external modules. + // This will happen in two cases: + // - if current file is external module then module augmentation is a ambient module declaration defined in the top level scope + // - if current file is not external module then module augmentation is an ambient module declaration with non-relative module name + // immediately nested in top level ambient module declaration . + if (isExternalModuleFile || (inAmbientModule && !ts.isExternalModuleNameRelative(nameText))) { + (moduleAugmentations || (moduleAugmentations = [])).push(node.name); + } + else if (!inAmbientModule) { + if (file.isDeclarationFile) { + // for global .d.ts files record name of ambient module + (ambientModules || (ambientModules = [])).push(nameText); + } + // An AmbientExternalModuleDeclaration declares an external module. + // This type of declaration is permitted only in the global module. + // The StringLiteral must specify a top - level external module name. + // Relative external module names are not permitted + // NOTE: body of ambient module is always a module block, if it exists + var body = node.body; + if (body) { + for (var _i = 0, _a = body.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + collectModuleReferences(statement, /*inAmbientModule*/ true); + } + } + } + } + } + } + function collectDynamicImportOrRequireCalls(file) { + var r = /import|require/g; + while (r.exec(file.text) !== null) { + var node = getNodeAtPosition(file, r.lastIndex); + if (ts.isRequireCall(node, /*checkArgumentIsStringLiteralLike*/ true)) { + imports = ts.append(imports, node.arguments[0]); + } + // we have to check the argument list has length of 1. We will still have to process these even though we have parsing error. + else if (ts.isImportCall(node) && node.arguments.length === 1 && ts.isStringLiteralLike(node.arguments[0])) { + imports = ts.append(imports, node.arguments[0]); + } + else if (ts.isLiteralImportTypeNode(node)) { + imports = ts.append(imports, node.argument.literal); + } + } + } + /** Returns a token if position is in [start-of-leading-trivia, end), includes JSDoc only in JS files */ + function getNodeAtPosition(sourceFile, position) { + var current = sourceFile; + var getContainingChild = function (child) { + if (child.pos <= position && (position < child.end || (position === child.end && (child.kind === 1 /* EndOfFileToken */)))) { + return child; + } + }; + while (true) { + var child = isJavaScriptFile && ts.hasJSDocNodes(current) && ts.forEach(current.jsDoc, getContainingChild) || ts.forEachChild(current, getContainingChild); + if (!child) { + return current; + } + current = child; + } + } + } + function getLibFileFromReference(ref) { + var libName = ref.fileName.toLocaleLowerCase(); + var libFileName = ts.libMap.get(libName); + if (libFileName) { + return getSourceFile(ts.combinePaths(defaultLibraryPath, libFileName)); + } + } + /** This should have similar behavior to 'processSourceFile' without diagnostics or mutation. */ + function getSourceFileFromReference(referencingFile, ref) { + return getSourceFileFromReferenceWorker(resolveTripleslashReference(ref.fileName, referencingFile.fileName), function (fileName) { return filesByName.get(toPath(fileName)); }); + } + function getSourceFileFromReferenceWorker(fileName, getSourceFile, fail, refFile) { + if (ts.hasExtension(fileName)) { + if (!options.allowNonTsExtensions && !ts.forEach(supportedExtensionsWithJsonIfResolveJsonModule, function (extension) { return ts.fileExtensionIs(host.getCanonicalFileName(fileName), extension); })) { + if (fail) + fail(ts.Diagnostics.File_0_has_unsupported_extension_The_only_supported_extensions_are_1, fileName, "'" + supportedExtensions.join("', '") + "'"); + return undefined; + } + var sourceFile = getSourceFile(fileName); + if (fail) { + if (!sourceFile) { + var redirect = getProjectReferenceRedirect(fileName); + if (redirect) { + fail(ts.Diagnostics.Output_file_0_has_not_been_built_from_source_file_1, redirect, fileName); + } + else { + fail(ts.Diagnostics.File_0_not_found, fileName); + } + } + else if (refFile && host.getCanonicalFileName(fileName) === host.getCanonicalFileName(refFile.fileName)) { + fail(ts.Diagnostics.A_file_cannot_have_a_reference_to_itself); + } + } + return sourceFile; + } + else { + var sourceFileNoExtension = options.allowNonTsExtensions && getSourceFile(fileName); + if (sourceFileNoExtension) + return sourceFileNoExtension; + if (fail && options.allowNonTsExtensions) { + fail(ts.Diagnostics.File_0_not_found, fileName); + return undefined; + } + var sourceFileWithAddedExtension = ts.forEach(supportedExtensions, function (extension) { return getSourceFile(fileName + extension); }); + if (fail && !sourceFileWithAddedExtension) + fail(ts.Diagnostics.File_0_not_found, fileName + ".ts" /* Ts */); + return sourceFileWithAddedExtension; + } + } + /** This has side effects through `findSourceFile`. */ + function processSourceFile(fileName, isDefaultLib, ignoreNoDefaultLib, packageId, refFile, refPos, refEnd) { + getSourceFileFromReferenceWorker(fileName, function (fileName) { return findSourceFile(fileName, toPath(fileName), isDefaultLib, ignoreNoDefaultLib, refFile, refPos, refEnd, packageId); }, // TODO: GH#18217 + function (diagnostic) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + fileProcessingDiagnostics.add(refFile !== undefined && refEnd !== undefined && refPos !== undefined + ? ts.createFileDiagnostic.apply(void 0, [refFile, refPos, refEnd - refPos, diagnostic].concat(args)) : ts.createCompilerDiagnostic.apply(void 0, [diagnostic].concat(args))); + }, refFile); + } + function reportFileNamesDifferOnlyInCasingError(fileName, existingFileName, refFile, refPos, refEnd) { + if (refFile !== undefined && refPos !== undefined && refEnd !== undefined) { + fileProcessingDiagnostics.add(ts.createFileDiagnostic(refFile, refPos, refEnd - refPos, ts.Diagnostics.File_name_0_differs_from_already_included_file_name_1_only_in_casing, fileName, existingFileName)); + } + else { + fileProcessingDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_name_0_differs_from_already_included_file_name_1_only_in_casing, fileName, existingFileName)); + } + } + function createRedirectSourceFile(redirectTarget, unredirected, fileName, path, resolvedPath, originalFileName) { + var redirect = Object.create(redirectTarget); + redirect.fileName = fileName; + redirect.path = path; + redirect.resolvedPath = resolvedPath; + redirect.originalFileName = originalFileName; + redirect.redirectInfo = { redirectTarget: redirectTarget, unredirected: unredirected }; + sourceFilesFoundSearchingNodeModules.set(path, currentNodeModulesDepth > 0); + Object.defineProperties(redirect, { + id: { + get: function () { return this.redirectInfo.redirectTarget.id; }, + set: function (value) { this.redirectInfo.redirectTarget.id = value; }, + }, + symbol: { + get: function () { return this.redirectInfo.redirectTarget.symbol; }, + set: function (value) { this.redirectInfo.redirectTarget.symbol = value; }, + }, + }); + return redirect; + } + // Get source file from normalized fileName + function findSourceFile(fileName, path, isDefaultLib, ignoreNoDefaultLib, refFile, refPos, refEnd, packageId) { + var originalFileName = fileName; + if (filesByName.has(path)) { + var file_1 = filesByName.get(path); + // try to check if we've already seen this file but with a different casing in path + // NOTE: this only makes sense for case-insensitive file systems, and only on files which are not redirected + if (file_1 && options.forceConsistentCasingInFileNames) { + var inputName = fileName; + var checkedName = file_1.fileName; + var isRedirect = toPath(checkedName) !== toPath(inputName); + if (isRedirect) { + inputName = getProjectReferenceRedirect(fileName) || fileName; + } + if (ts.getNormalizedAbsolutePath(checkedName, currentDirectory) !== ts.getNormalizedAbsolutePath(inputName, currentDirectory)) { + reportFileNamesDifferOnlyInCasingError(inputName, checkedName, refFile, refPos, refEnd); + } + } + // If the file was previously found via a node_modules search, but is now being processed as a root file, + // then everything it sucks in may also be marked incorrectly, and needs to be checked again. + if (file_1 && sourceFilesFoundSearchingNodeModules.get(file_1.path) && currentNodeModulesDepth === 0) { + sourceFilesFoundSearchingNodeModules.set(file_1.path, false); + if (!options.noResolve) { + processReferencedFiles(file_1, isDefaultLib); + processTypeReferenceDirectives(file_1); + } + processLibReferenceDirectives(file_1); + modulesWithElidedImports.set(file_1.path, false); + processImportedModules(file_1); + } + // See if we need to reprocess the imports due to prior skipped imports + else if (file_1 && modulesWithElidedImports.get(file_1.path)) { + if (currentNodeModulesDepth < maxNodeModuleJsDepth) { + modulesWithElidedImports.set(file_1.path, false); + processImportedModules(file_1); + } + } + return file_1; + } + var redirectedPath; + if (refFile) { + var redirect = getProjectReferenceRedirect(fileName); + if (redirect) { + (refFile.redirectedReferences || (refFile.redirectedReferences = [])).push(fileName); + fileName = redirect; + // Once we start redirecting to a file, we can potentially come back to it + // via a back-reference from another file in the .d.ts folder. If that happens we'll + // end up trying to add it to the program *again* because we were tracking it via its + // original (un-redirected) name. So we have to map both the original path and the redirected path + // to the source file we're about to find/create + redirectedPath = toPath(redirect); + } + } + // We haven't looked for this file, do so now and cache result + var file = host.getSourceFile(fileName, options.target, function (hostErrorMessage) { + if (refFile !== undefined && refPos !== undefined && refEnd !== undefined) { + fileProcessingDiagnostics.add(ts.createFileDiagnostic(refFile, refPos, refEnd - refPos, ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, hostErrorMessage)); + } + else { + fileProcessingDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, hostErrorMessage)); + } + }, shouldCreateNewSourceFile); + if (packageId) { + var packageIdKey = ts.packageIdToString(packageId); + var fileFromPackageId = packageIdToSourceFile.get(packageIdKey); + if (fileFromPackageId) { + // Some other SourceFile already exists with this package name and version. + // Instead of creating a duplicate, just redirect to the existing one. + var dupFile = createRedirectSourceFile(fileFromPackageId, file, fileName, path, toPath(fileName), originalFileName); // TODO: GH#18217 + redirectTargetsMap.add(fileFromPackageId.path, fileName); + addFileToFilesByName(dupFile, path, redirectedPath); + sourceFileToPackageName.set(path, packageId.name); + processingOtherFiles.push(dupFile); + return dupFile; + } + else if (file) { + // This is the first source file to have this packageId. + packageIdToSourceFile.set(packageIdKey, file); + sourceFileToPackageName.set(path, packageId.name); + } + } + addFileToFilesByName(file, path, redirectedPath); + if (file) { + sourceFilesFoundSearchingNodeModules.set(path, currentNodeModulesDepth > 0); + file.path = path; + file.resolvedPath = toPath(fileName); + file.originalFileName = originalFileName; + if (host.useCaseSensitiveFileNames()) { + var pathLowerCase = path.toLowerCase(); + // for case-sensitive file systems check if we've already seen some file with similar filename ignoring case + var existingFile = filesByNameIgnoreCase.get(pathLowerCase); + if (existingFile) { + reportFileNamesDifferOnlyInCasingError(fileName, existingFile.fileName, refFile, refPos, refEnd); + } + else { + filesByNameIgnoreCase.set(pathLowerCase, file); + } + } + skipDefaultLib = skipDefaultLib || (file.hasNoDefaultLib && !ignoreNoDefaultLib); + if (!options.noResolve) { + processReferencedFiles(file, isDefaultLib); + processTypeReferenceDirectives(file); + } + processLibReferenceDirectives(file); + // always process imported modules to record module name resolutions + processImportedModules(file); + if (isDefaultLib) { + processingDefaultLibFiles.push(file); + } + else { + processingOtherFiles.push(file); + } + } + return file; + } + function addFileToFilesByName(file, path, redirectedPath) { + filesByName.set(path, file); + if (redirectedPath) { + filesByName.set(redirectedPath, file); + } + } + function getProjectReferenceRedirect(fileName) { + // Ignore dts or any of the non ts files + if (!resolvedProjectReferences || !resolvedProjectReferences.length || ts.fileExtensionIs(fileName, ".d.ts" /* Dts */) || !ts.fileExtensionIsOneOf(fileName, ts.supportedTSExtensions)) { + return undefined; + } + // If this file is produced by a referenced project, we need to rewrite it to + // look in the output folder of the referenced project rather than the input + var referencedProject = getResolvedProjectReferenceToRedirect(fileName); + if (!referencedProject) { + return undefined; + } + var out = referencedProject.commandLine.options.outFile || referencedProject.commandLine.options.out; + return out ? + ts.changeExtension(out, ".d.ts" /* Dts */) : + ts.getOutputDeclarationFileName(fileName, referencedProject.commandLine); + } + /** + * Get the referenced project if the file is input file from that reference project + */ + function getResolvedProjectReferenceToRedirect(fileName) { + if (mapFromFileToProjectReferenceRedirects === undefined) { + mapFromFileToProjectReferenceRedirects = ts.createMap(); + forEachResolvedProjectReference(function (referencedProject, referenceProjectPath) { + // not input file from the referenced project, ignore + if (referencedProject && + toPath(options.configFilePath) !== referenceProjectPath) { + referencedProject.commandLine.fileNames.forEach(function (f) { + return mapFromFileToProjectReferenceRedirects.set(toPath(f), referenceProjectPath); + }); + } + }); + } + var referencedProjectPath = mapFromFileToProjectReferenceRedirects.get(toPath(fileName)); + return referencedProjectPath && getResolvedProjectReferenceByPath(referencedProjectPath); + } + function forEachResolvedProjectReference(cb) { + return forEachProjectReference(projectReferences, resolvedProjectReferences, function (resolvedRef, index, parent) { + var ref = (parent ? parent.commandLine.projectReferences : projectReferences)[index]; + var resolvedRefPath = toPath(resolveProjectReferencePath(ref)); + return cb(resolvedRef, resolvedRefPath); + }); + } + function forEachProjectReference(projectReferences, resolvedProjectReferences, cbResolvedRef, cbRef) { + var seenResolvedRefs; + return worker(projectReferences, resolvedProjectReferences, /*parent*/ undefined, cbResolvedRef, cbRef); + function worker(projectReferences, resolvedProjectReferences, parent, cbResolvedRef, cbRef) { + // Visit project references first + if (cbRef) { + var result = cbRef(projectReferences, parent); + if (result) { + return result; + } + } + return ts.forEach(resolvedProjectReferences, function (resolvedRef, index) { + if (ts.contains(seenResolvedRefs, resolvedRef)) { + // ignore recursives + return undefined; + } + var result = cbResolvedRef(resolvedRef, index, parent); + if (result) { + return result; + } + if (!resolvedRef) + return undefined; + (seenResolvedRefs || (seenResolvedRefs = [])).push(resolvedRef); + return worker(resolvedRef.commandLine.projectReferences, resolvedRef.references, resolvedRef, cbResolvedRef, cbRef); + }); + } + } + function getResolvedProjectReferenceByPath(projectReferencePath) { + if (!projectReferenceRedirects) { + return undefined; + } + return projectReferenceRedirects.get(projectReferencePath) || undefined; + } + function processReferencedFiles(file, isDefaultLib) { + ts.forEach(file.referencedFiles, function (ref) { + var referencedFileName = resolveTripleslashReference(ref.fileName, file.originalFileName); + processSourceFile(referencedFileName, isDefaultLib, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined, file, ref.pos, ref.end); + }); + } + function processTypeReferenceDirectives(file) { + // We lower-case all type references because npm automatically lowercases all packages. See GH#9824. + var typeDirectives = ts.map(file.typeReferenceDirectives, function (ref) { return ref.fileName.toLocaleLowerCase(); }); + if (!typeDirectives) { + return; + } + var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeDirectives, file.originalFileName, getResolvedProjectReferenceToRedirect(file.originalFileName)); + for (var i = 0; i < typeDirectives.length; i++) { + var ref = file.typeReferenceDirectives[i]; + var resolvedTypeReferenceDirective = resolutions[i]; + // store resolved type directive on the file + var fileName = ref.fileName.toLocaleLowerCase(); + ts.setResolvedTypeReferenceDirective(file, fileName, resolvedTypeReferenceDirective); + processTypeReferenceDirective(fileName, resolvedTypeReferenceDirective, file, ref.pos, ref.end); + } + } + function processTypeReferenceDirective(typeReferenceDirective, resolvedTypeReferenceDirective, refFile, refPos, refEnd) { + // If we already found this library as a primary reference - nothing to do + var previousResolution = resolvedTypeReferenceDirectives.get(typeReferenceDirective); + if (previousResolution && previousResolution.primary) { + return; + } + var saveResolution = true; + if (resolvedTypeReferenceDirective) { + if (resolvedTypeReferenceDirective.isExternalLibraryImport) + currentNodeModulesDepth++; + if (resolvedTypeReferenceDirective.primary) { + // resolved from the primary path + processSourceFile(resolvedTypeReferenceDirective.resolvedFileName, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, resolvedTypeReferenceDirective.packageId, refFile, refPos, refEnd); // TODO: GH#18217 + } + else { + // If we already resolved to this file, it must have been a secondary reference. Check file contents + // for sameness and possibly issue an error + if (previousResolution) { + // Don't bother reading the file again if it's the same file. + if (resolvedTypeReferenceDirective.resolvedFileName !== previousResolution.resolvedFileName) { + var otherFileText = host.readFile(resolvedTypeReferenceDirective.resolvedFileName); + if (otherFileText !== getSourceFile(previousResolution.resolvedFileName).text) { + fileProcessingDiagnostics.add(createDiagnostic(refFile, refPos, refEnd, // TODO: GH#18217 + ts.Diagnostics.Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict, typeReferenceDirective, resolvedTypeReferenceDirective.resolvedFileName, previousResolution.resolvedFileName)); + } + } + // don't overwrite previous resolution result + saveResolution = false; + } + else { + // First resolution of this library + processSourceFile(resolvedTypeReferenceDirective.resolvedFileName, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, resolvedTypeReferenceDirective.packageId, refFile, refPos, refEnd); + } + } + if (resolvedTypeReferenceDirective.isExternalLibraryImport) + currentNodeModulesDepth--; + } + else { + fileProcessingDiagnostics.add(createDiagnostic(refFile, refPos, refEnd, ts.Diagnostics.Cannot_find_type_definition_file_for_0, typeReferenceDirective)); // TODO: GH#18217 + } + if (saveResolution) { + resolvedTypeReferenceDirectives.set(typeReferenceDirective, resolvedTypeReferenceDirective); + } + } + function processLibReferenceDirectives(file) { + ts.forEach(file.libReferenceDirectives, function (libReference) { + var libName = libReference.fileName.toLocaleLowerCase(); + var libFileName = ts.libMap.get(libName); + if (libFileName) { + // we ignore any 'no-default-lib' reference set on this file. + processRootFile(ts.combinePaths(defaultLibraryPath, libFileName), /*isDefaultLib*/ true, /*ignoreNoDefaultLib*/ true); + } + else { + var unqualifiedLibName = ts.removeSuffix(ts.removePrefix(libName, "lib."), ".d.ts"); + var suggestion = ts.getSpellingSuggestion(unqualifiedLibName, ts.libs, ts.identity); + var message = suggestion ? ts.Diagnostics.Cannot_find_lib_definition_for_0_Did_you_mean_1 : ts.Diagnostics.Cannot_find_lib_definition_for_0; + fileProcessingDiagnostics.add(createDiagnostic(file, libReference.pos, libReference.end, message, libName, suggestion)); + } + }); + } + function createDiagnostic(refFile, refPos, refEnd, message) { + var args = []; + for (var _i = 4; _i < arguments.length; _i++) { + args[_i - 4] = arguments[_i]; + } + if (refFile === undefined || refPos === undefined || refEnd === undefined) { + return ts.createCompilerDiagnostic.apply(void 0, [message].concat(args)); + } + else { + return ts.createFileDiagnostic.apply(void 0, [refFile, refPos, refEnd - refPos, message].concat(args)); + } + } + function getCanonicalFileName(fileName) { + return host.getCanonicalFileName(fileName); + } + function processImportedModules(file) { + collectExternalModuleReferences(file); + if (file.imports.length || file.moduleAugmentations.length) { + // Because global augmentation doesn't have string literal name, we can check for global augmentation as such. + var moduleNames = getModuleNames(file); + var resolutions = resolveModuleNamesReusingOldState(moduleNames, ts.getNormalizedAbsolutePath(file.originalFileName, currentDirectory), file); + ts.Debug.assert(resolutions.length === moduleNames.length); + for (var i = 0; i < moduleNames.length; i++) { + var resolution = resolutions[i]; + ts.setResolvedModule(file, moduleNames[i], resolution); + if (!resolution) { + continue; + } + var isFromNodeModulesSearch = resolution.isExternalLibraryImport; + var isJsFile = !ts.resolutionExtensionIsTSOrJson(resolution.extension); + var isJsFileFromNodeModules = isFromNodeModulesSearch && isJsFile; + var resolvedFileName = resolution.resolvedFileName; + if (isFromNodeModulesSearch) { + currentNodeModulesDepth++; + } + // add file to program only if: + // - resolution was successful + // - noResolve is falsy + // - module name comes from the list of imports + // - it's not a top level JavaScript module that exceeded the search max + var elideImport = isJsFileFromNodeModules && currentNodeModulesDepth > maxNodeModuleJsDepth; + // Don't add the file if it has a bad extension (e.g. 'tsx' if we don't have '--allowJs') + // This may still end up being an untyped module -- the file won't be included but imports will be allowed. + var shouldAddFile = resolvedFileName + && !getResolutionDiagnostic(options, resolution) + && !options.noResolve + && i < file.imports.length + && !elideImport + && !(isJsFile && !options.allowJs) + && (ts.isInJSFile(file.imports[i]) || !(file.imports[i].flags & 2097152 /* JSDoc */)); + if (elideImport) { + modulesWithElidedImports.set(file.path, true); + } + else if (shouldAddFile) { + var path = toPath(resolvedFileName); + var pos = ts.skipTrivia(file.text, file.imports[i].pos); + findSourceFile(resolvedFileName, path, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, file, pos, file.imports[i].end, resolution.packageId); + } + if (isFromNodeModulesSearch) { + currentNodeModulesDepth--; + } + } + } + else { + // no imports - drop cached module resolutions + file.resolvedModules = undefined; + } + } + function computeCommonSourceDirectory(sourceFiles) { + var fileNames = ts.mapDefined(sourceFiles, function (file) { return file.isDeclarationFile ? undefined : file.fileName; }); + return computeCommonSourceDirectoryOfFilenames(fileNames, currentDirectory, getCanonicalFileName); + } + function checkSourceFilesBelongToPath(sourceFiles, rootDirectory) { + var allFilesBelongToPath = true; + var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory)); + for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) { + var sourceFile = sourceFiles_2[_i]; + if (!sourceFile.isDeclarationFile) { + var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); + if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, sourceFile.fileName, rootDirectory)); + allFilesBelongToPath = false; + } + } + } + return allFilesBelongToPath; + } + function parseProjectReferenceConfigFile(ref) { + if (!projectReferenceRedirects) { + projectReferenceRedirects = ts.createMap(); + } + // The actual filename (i.e. add "/tsconfig.json" if necessary) + var refPath = resolveProjectReferencePath(ref); + var sourceFilePath = toPath(refPath); + var fromCache = projectReferenceRedirects.get(sourceFilePath); + if (fromCache !== undefined) { + return fromCache || undefined; + } + // An absolute path pointing to the containing directory of the config file + var basePath = ts.getNormalizedAbsolutePath(ts.getDirectoryPath(refPath), host.getCurrentDirectory()); + var sourceFile = host.getSourceFile(refPath, 100 /* JSON */); + addFileToFilesByName(sourceFile, sourceFilePath, /*redirectedPath*/ undefined); + if (sourceFile === undefined) { + projectReferenceRedirects.set(sourceFilePath, false); + return undefined; + } + sourceFile.path = sourceFilePath; + sourceFile.resolvedPath = sourceFilePath; + sourceFile.originalFileName = refPath; + var commandLine = ts.parseJsonSourceFileConfigFileContent(sourceFile, configParsingHost, basePath, /*existingOptions*/ undefined, refPath); + var resolvedRef = { commandLine: commandLine, sourceFile: sourceFile }; + projectReferenceRedirects.set(sourceFilePath, resolvedRef); + if (commandLine.projectReferences) { + resolvedRef.references = commandLine.projectReferences.map(parseProjectReferenceConfigFile); + } + return resolvedRef; + } + function verifyCompilerOptions() { + if (options.strictPropertyInitialization && !ts.getStrictOptionValue(options, "strictNullChecks")) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "strictPropertyInitialization", "strictNullChecks"); + } + if (options.isolatedModules) { + if (ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, getEmitDeclarationOptionName(options), "isolatedModules"); + } + if (options.noEmitOnError) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmitOnError", "isolatedModules"); + } + if (options.out) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "out", "isolatedModules"); + } + if (options.outFile) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "outFile", "isolatedModules"); + } + } + if (options.inlineSourceMap) { + if (options.sourceMap) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "sourceMap", "inlineSourceMap"); + } + if (options.mapRoot) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "mapRoot", "inlineSourceMap"); + } + } + if (options.paths && options.baseUrl === undefined) { + createDiagnosticForOptionName(ts.Diagnostics.Option_paths_cannot_be_used_without_specifying_baseUrl_option, "paths"); + } + if (options.composite) { + if (options.declaration === false) { + createDiagnosticForOptionName(ts.Diagnostics.Composite_projects_may_not_disable_declaration_emit, "declaration"); + } + } + verifyProjectReferences(); + // List of collected files is complete; validate exhautiveness if this is a project with a file list + if (options.composite) { + var sourceFiles = files.filter(function (f) { return !f.isDeclarationFile; }); + if (rootNames.length < sourceFiles.length) { + var normalizedRootNames = rootNames.map(function (r) { return ts.normalizePath(r).toLowerCase(); }); + for (var _i = 0, _a = sourceFiles.map(function (f) { return ts.normalizePath(f.path).toLowerCase(); }); _i < _a.length; _i++) { + var file = _a[_i]; + if (normalizedRootNames.indexOf(file) === -1) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern, file)); + } + } + } + } + if (options.paths) { + for (var key in options.paths) { + if (!ts.hasProperty(options.paths, key)) { + continue; + } + if (!ts.hasZeroOrOneAsteriskCharacter(key)) { + createDiagnosticForOptionPaths(/*onKey*/ true, key, ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, key); + } + if (ts.isArray(options.paths[key])) { + var len = options.paths[key].length; + if (len === 0) { + createDiagnosticForOptionPaths(/*onKey*/ false, key, ts.Diagnostics.Substitutions_for_pattern_0_shouldn_t_be_an_empty_array, key); + } + for (var i = 0; i < len; i++) { + var subst = options.paths[key][i]; + var typeOfSubst = typeof subst; + if (typeOfSubst === "string") { + if (!ts.hasZeroOrOneAsteriskCharacter(subst)) { + createDiagnosticForOptionPathKeyValue(key, i, ts.Diagnostics.Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character, subst, key); + } + } + else { + createDiagnosticForOptionPathKeyValue(key, i, ts.Diagnostics.Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2, subst, key, typeOfSubst); + } + } + } + else { + createDiagnosticForOptionPaths(/*onKey*/ false, key, ts.Diagnostics.Substitutions_for_pattern_0_should_be_an_array, key); + } + } + } + if (!options.sourceMap && !options.inlineSourceMap) { + if (options.inlineSources) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided, "inlineSources"); + } + if (options.sourceRoot) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided, "sourceRoot"); + } + } + if (options.out && options.outFile) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "out", "outFile"); + } + if (options.mapRoot && !(options.sourceMap || options.declarationMap)) { + // Error to specify --mapRoot without --sourcemap + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "mapRoot", "sourceMap", "declarationMap"); + } + if (options.declarationDir) { + if (!ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "declarationDir", "declaration", "composite"); + } + if (options.out || options.outFile) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "declarationDir", options.out ? "out" : "outFile"); + } + } + if (options.declarationMap && !ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "declarationMap", "declaration", "composite"); + } + if (options.lib && options.noLib) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "lib", "noLib"); + } + if (options.noImplicitUseStrict && ts.getStrictOptionValue(options, "alwaysStrict")) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noImplicitUseStrict", "alwaysStrict"); + } + var languageVersion = options.target || 0 /* ES3 */; + var outFile = options.outFile || options.out; + var firstNonAmbientExternalModuleSourceFile = ts.find(files, function (f) { return ts.isExternalModule(f) && !f.isDeclarationFile; }); + if (options.isolatedModules) { + if (options.module === ts.ModuleKind.None && languageVersion < 2 /* ES2015 */) { + createDiagnosticForOptionName(ts.Diagnostics.Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher, "isolatedModules", "target"); + } + var firstNonExternalModuleSourceFile = ts.find(files, function (f) { return !ts.isExternalModule(f) && !f.isDeclarationFile && f.scriptKind !== 6 /* JSON */; }); + if (firstNonExternalModuleSourceFile) { + var span = ts.getErrorSpanForNode(firstNonExternalModuleSourceFile, firstNonExternalModuleSourceFile); + programDiagnostics.add(ts.createFileDiagnostic(firstNonExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided)); + } + } + else if (firstNonAmbientExternalModuleSourceFile && languageVersion < 2 /* ES2015 */ && options.module === ts.ModuleKind.None) { + // We cannot use createDiagnosticFromNode because nodes do not have parents yet + var span = ts.getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, firstNonAmbientExternalModuleSourceFile.externalModuleIndicator); + programDiagnostics.add(ts.createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_use_imports_exports_or_module_augmentations_when_module_is_none)); + } + // Cannot specify module gen that isn't amd or system with --out + if (outFile && !options.emitDeclarationOnly) { + if (options.module && !(options.module === ts.ModuleKind.AMD || options.module === ts.ModuleKind.System)) { + createDiagnosticForOptionName(ts.Diagnostics.Only_amd_and_system_modules_are_supported_alongside_0, options.out ? "out" : "outFile", "module"); + } + else if (options.module === undefined && firstNonAmbientExternalModuleSourceFile) { + var span = ts.getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, firstNonAmbientExternalModuleSourceFile.externalModuleIndicator); + programDiagnostics.add(ts.createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system, options.out ? "out" : "outFile")); + } + } + if (options.resolveJsonModule) { + if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { + createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy, "resolveJsonModule"); + } + // Any emit other than common js, amd, es2015 or esnext is error + else if (!ts.hasJsonModuleEmitEnabled(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_esNext, "resolveJsonModule", "module"); + } + } + // there has to be common source directory if user specified --outdir || --sourceRoot + // if user specified --mapRoot, there needs to be common source directory if there would be multiple files being emitted + if (options.outDir || // there is --outDir specified + options.sourceRoot || // there is --sourceRoot specified + options.mapRoot) { // there is --mapRoot specified + // Precalculate and cache the common source directory + var dir = getCommonSourceDirectory(); + // If we failed to find a good common directory, but outDir is specified and at least one of our files is on a windows drive/URL/other resource, add a failure + if (options.outDir && dir === "" && files.some(function (file) { return ts.getRootLength(file.fileName) > 1; })) { + createDiagnosticForOptionName(ts.Diagnostics.Cannot_find_the_common_subdirectory_path_for_the_input_files, "outDir"); + } + } + if (!options.noEmit && options.allowJs && ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "allowJs", getEmitDeclarationOptionName(options)); + } + if (options.checkJs && !options.allowJs) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "checkJs", "allowJs")); + } + if (options.emitDeclarationOnly) { + if (!ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "emitDeclarationOnly", "declaration", "composite"); + } + if (options.noEmit) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "emitDeclarationOnly", "noEmit"); + } + } + if (options.emitDecoratorMetadata && + !options.experimentalDecorators) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDecoratorMetadata", "experimentalDecorators"); + } + if (options.jsxFactory) { + if (options.reactNamespace) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "reactNamespace", "jsxFactory"); + } + if (!ts.parseIsolatedEntityName(options.jsxFactory, languageVersion)) { + createOptionValueDiagnostic("jsxFactory", ts.Diagnostics.Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name, options.jsxFactory); + } + } + else if (options.reactNamespace && !ts.isIdentifierText(options.reactNamespace, languageVersion)) { + createOptionValueDiagnostic("reactNamespace", ts.Diagnostics.Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier, options.reactNamespace); + } + // If the emit is enabled make sure that every output file is unique and not overwriting any of the input files + if (!options.noEmit && !options.suppressOutputPathCheck) { + var emitHost = getEmitHost(); + var emitFilesSeen_1 = ts.createMap(); + ts.forEachEmittedFile(emitHost, function (emitFileNames) { + if (!options.emitDeclarationOnly) { + verifyEmitFilePath(emitFileNames.jsFilePath, emitFilesSeen_1); + } + verifyEmitFilePath(emitFileNames.declarationFilePath, emitFilesSeen_1); + }); + } + // Verify that all the emit files are unique and don't overwrite input files + function verifyEmitFilePath(emitFileName, emitFilesSeen) { + if (emitFileName) { + var emitFilePath = toPath(emitFileName); + // Report error if the output overwrites input file + if (filesByName.has(emitFilePath)) { + var chain_2; + if (!options.configFilePath) { + // The program is from either an inferred project or an external project + chain_2 = ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig); + } + chain_2 = ts.chainDiagnosticMessages(chain_2, ts.Diagnostics.Cannot_write_file_0_because_it_would_overwrite_input_file, emitFileName); + blockEmittingOfFile(emitFileName, ts.createCompilerDiagnosticFromMessageChain(chain_2)); + } + var emitFileKey = !host.useCaseSensitiveFileNames() ? emitFilePath.toLocaleLowerCase() : emitFilePath; + // Report error if multiple files write into same file + if (emitFilesSeen.has(emitFileKey)) { + // Already seen the same emit file - report error + blockEmittingOfFile(emitFileName, ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files, emitFileName)); + } + else { + emitFilesSeen.set(emitFileKey, true); + } + } + } + } + function verifyProjectReferences() { + forEachProjectReference(projectReferences, resolvedProjectReferences, function (resolvedRef, index, parent) { + var ref = (parent ? parent.commandLine.projectReferences : projectReferences)[index]; + var parentFile = parent && parent.sourceFile; + if (!resolvedRef) { + createDiagnosticForReference(parentFile, index, ts.Diagnostics.File_0_not_found, ref.path); + return; + } + var options = resolvedRef.commandLine.options; + if (!options.composite) { + // ok to not have composite if the current program is container only + var inputs = parent ? parent.commandLine.fileNames : rootNames; + if (inputs.length) { + createDiagnosticForReference(parentFile, index, ts.Diagnostics.Referenced_project_0_must_have_setting_composite_Colon_true, ref.path); + } + } + if (ref.prepend) { + var out = options.outFile || options.out; + if (out) { + if (!host.fileExists(out)) { + createDiagnosticForReference(parentFile, index, ts.Diagnostics.Output_file_0_from_project_1_does_not_exist, out, ref.path); + } + } + else { + createDiagnosticForReference(parentFile, index, ts.Diagnostics.Cannot_prepend_project_0_because_it_does_not_have_outFile_set, ref.path); + } + } + }); + } + function createDiagnosticForOptionPathKeyValue(key, valueIndex, message, arg0, arg1, arg2) { + var needCompilerDiagnostic = true; + var pathsSyntax = getOptionPathsSyntax(); + for (var _i = 0, pathsSyntax_1 = pathsSyntax; _i < pathsSyntax_1.length; _i++) { + var pathProp = pathsSyntax_1[_i]; + if (ts.isObjectLiteralExpression(pathProp.initializer)) { + for (var _a = 0, _b = ts.getPropertyAssignment(pathProp.initializer, key); _a < _b.length; _a++) { + var keyProps = _b[_a]; + var initializer = keyProps.initializer; + if (ts.isArrayLiteralExpression(initializer) && initializer.elements.length > valueIndex) { + programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(options.configFile, initializer.elements[valueIndex], message, arg0, arg1, arg2)); + needCompilerDiagnostic = false; + } + } + } + } + if (needCompilerDiagnostic) { + programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1, arg2)); + } + } + function createDiagnosticForOptionPaths(onKey, key, message, arg0) { + var needCompilerDiagnostic = true; + var pathsSyntax = getOptionPathsSyntax(); + for (var _i = 0, pathsSyntax_2 = pathsSyntax; _i < pathsSyntax_2.length; _i++) { + var pathProp = pathsSyntax_2[_i]; + if (ts.isObjectLiteralExpression(pathProp.initializer) && + createOptionDiagnosticInObjectLiteralSyntax(pathProp.initializer, onKey, key, /*key2*/ undefined, message, arg0)) { + needCompilerDiagnostic = false; + } + } + if (needCompilerDiagnostic) { + programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0)); + } + } + function getOptionsSyntaxByName(name) { + var compilerOptionsObjectLiteralSyntax = getCompilerOptionsObjectLiteralSyntax(); + if (compilerOptionsObjectLiteralSyntax) { + return ts.getPropertyAssignment(compilerOptionsObjectLiteralSyntax, name); + } + return undefined; + } + function getOptionPathsSyntax() { + return getOptionsSyntaxByName("paths") || ts.emptyArray; + } + function createDiagnosticForOptionName(message, option1, option2, option3) { + createDiagnosticForOption(/*onKey*/ true, option1, option2, message, option1, option2, option3); + } + function createOptionValueDiagnostic(option1, message, arg0) { + createDiagnosticForOption(/*onKey*/ false, option1, /*option2*/ undefined, message, arg0); + } + function createDiagnosticForReference(sourceFile, index, message, arg0, arg1) { + var referencesSyntax = ts.firstDefined(ts.getTsConfigPropArray(sourceFile || options.configFile, "references"), function (property) { return ts.isArrayLiteralExpression(property.initializer) ? property.initializer : undefined; }); + if (referencesSyntax && referencesSyntax.elements.length > index) { + programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(sourceFile || options.configFile, referencesSyntax.elements[index], message, arg0, arg1)); + } + else { + programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1)); + } + } + function createDiagnosticForOption(onKey, option1, option2, message, arg0, arg1, arg2) { + var compilerOptionsObjectLiteralSyntax = getCompilerOptionsObjectLiteralSyntax(); + var needCompilerDiagnostic = !compilerOptionsObjectLiteralSyntax || + !createOptionDiagnosticInObjectLiteralSyntax(compilerOptionsObjectLiteralSyntax, onKey, option1, option2, message, arg0, arg1, arg2); + if (needCompilerDiagnostic) { + programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1, arg2)); + } + } + function getCompilerOptionsObjectLiteralSyntax() { + if (_compilerOptionsObjectLiteralSyntax === undefined) { + _compilerOptionsObjectLiteralSyntax = null; // tslint:disable-line:no-null-keyword + var jsonObjectLiteral = ts.getTsConfigObjectLiteralExpression(options.configFile); + if (jsonObjectLiteral) { + for (var _i = 0, _a = ts.getPropertyAssignment(jsonObjectLiteral, "compilerOptions"); _i < _a.length; _i++) { + var prop = _a[_i]; + if (ts.isObjectLiteralExpression(prop.initializer)) { + _compilerOptionsObjectLiteralSyntax = prop.initializer; + break; + } + } + } + } + return _compilerOptionsObjectLiteralSyntax; + } + function createOptionDiagnosticInObjectLiteralSyntax(objectLiteral, onKey, key1, key2, message, arg0, arg1, arg2) { + var props = ts.getPropertyAssignment(objectLiteral, key1, key2); + for (var _i = 0, props_2 = props; _i < props_2.length; _i++) { + var prop = props_2[_i]; + programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(options.configFile, onKey ? prop.name : prop.initializer, message, arg0, arg1, arg2)); + } + return !!props.length; + } + function blockEmittingOfFile(emitFileName, diag) { + hasEmitBlockingDiagnostics.set(toPath(emitFileName), true); + programDiagnostics.add(diag); + } + function isEmittedFile(file) { + if (options.noEmit) { + return false; + } + // If this is source file, its not emitted file + var filePath = toPath(file); + if (getSourceFileByPath(filePath)) { + return false; + } + // If options have --outFile or --out just check that + var out = options.outFile || options.out; + if (out) { + return isSameFile(filePath, out) || isSameFile(filePath, ts.removeFileExtension(out) + ".d.ts" /* Dts */); + } + // If declarationDir is specified, return if its a file in that directory + if (options.declarationDir && ts.containsPath(options.declarationDir, filePath, currentDirectory, !host.useCaseSensitiveFileNames())) { + return true; + } + // If --outDir, check if file is in that directory + if (options.outDir) { + return ts.containsPath(options.outDir, filePath, currentDirectory, !host.useCaseSensitiveFileNames()); + } + if (ts.fileExtensionIsOneOf(filePath, ts.supportedJSExtensions) || ts.fileExtensionIs(filePath, ".d.ts" /* Dts */)) { + // Otherwise just check if sourceFile with the name exists + var filePathWithoutExtension = ts.removeFileExtension(filePath); + return !!getSourceFileByPath((filePathWithoutExtension + ".ts" /* Ts */)) || + !!getSourceFileByPath((filePathWithoutExtension + ".tsx" /* Tsx */)); + } + return false; + } + function isSameFile(file1, file2) { + return ts.comparePaths(file1, file2, currentDirectory, !host.useCaseSensitiveFileNames()) === 0 /* EqualTo */; + } + } + ts.createProgram = createProgram; + /* @internal */ + function parseConfigHostFromCompilerHost(host) { + return { + fileExists: function (f) { return host.fileExists(f); }, + readDirectory: function (root, extensions, excludes, includes, depth) { + ts.Debug.assertDefined(host.readDirectory, "'CompilerHost.readDirectory' must be implemented to correctly process 'projectReferences'"); + return host.readDirectory(root, extensions, excludes, includes, depth); + }, + readFile: function (f) { return host.readFile(f); }, + useCaseSensitiveFileNames: host.useCaseSensitiveFileNames(), + getCurrentDirectory: function () { return host.getCurrentDirectory(); }, + onUnRecoverableConfigFileDiagnostic: function () { return undefined; }, + trace: host.trace ? function (s) { return host.trace(s); } : undefined + }; + } + ts.parseConfigHostFromCompilerHost = parseConfigHostFromCompilerHost; + function resolveProjectReferencePath(hostOrRef, ref) { + var passedInRef = ref ? ref : hostOrRef; + return ts.resolveConfigFileProjectName(passedInRef.path); + } + ts.resolveProjectReferencePath = resolveProjectReferencePath; + function getEmitDeclarationOptionName(options) { + return options.declaration ? "declaration" : "composite"; + } + /* @internal */ + /** + * Returns a DiagnosticMessage if we won't include a resolved module due to its extension. + * The DiagnosticMessage's parameters are the imported module name, and the filename it resolved to. + * This returns a diagnostic even if the module will be an untyped module. + */ + function getResolutionDiagnostic(options, _a) { + var extension = _a.extension; + switch (extension) { + case ".ts" /* Ts */: + case ".d.ts" /* Dts */: + // These are always allowed. + return undefined; + case ".tsx" /* Tsx */: + return needJsx(); + case ".jsx" /* Jsx */: + return needJsx() || needAllowJs(); + case ".js" /* Js */: + return needAllowJs(); + case ".json" /* Json */: + return needResolveJsonModule(); + } + function needJsx() { + return options.jsx ? undefined : ts.Diagnostics.Module_0_was_resolved_to_1_but_jsx_is_not_set; + } + function needAllowJs() { + return options.allowJs || !ts.getStrictOptionValue(options, "noImplicitAny") ? undefined : ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type; + } + function needResolveJsonModule() { + return options.resolveJsonModule ? undefined : ts.Diagnostics.Module_0_was_resolved_to_1_but_resolveJsonModule_is_not_used; + } + } + ts.getResolutionDiagnostic = getResolutionDiagnostic; + function getModuleNames(_a) { + var imports = _a.imports, moduleAugmentations = _a.moduleAugmentations; + var res = imports.map(function (i) { return i.text; }); + for (var _i = 0, moduleAugmentations_1 = moduleAugmentations; _i < moduleAugmentations_1.length; _i++) { + var aug = moduleAugmentations_1[_i]; + if (aug.kind === 10 /* StringLiteral */) { + res.push(aug.text); + } + // Do nothing if it's an Identifier; we don't need to do module resolution for `declare global`. + } + return res; + } +})(ts || (ts = {})); +/*@internal*/ +var ts; +(function (ts) { + function getFileEmitOutput(program, sourceFile, emitOnlyDtsFiles, cancellationToken, customTransformers) { + var outputFiles = []; + var emitResult = program.emit(sourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); + return { outputFiles: outputFiles, emitSkipped: emitResult.emitSkipped, exportedModulesFromDeclarationEmit: emitResult.exportedModulesFromDeclarationEmit }; + function writeFile(fileName, text, writeByteOrderMark) { + outputFiles.push({ name: fileName, writeByteOrderMark: writeByteOrderMark, text: text }); + } + } + ts.getFileEmitOutput = getFileEmitOutput; +})(ts || (ts = {})); +/*@internal*/ +(function (ts) { + var BuilderState; + (function (BuilderState) { + /** + * Get the referencedFile from the imported module symbol + */ + function getReferencedFileFromImportedModuleSymbol(symbol) { + if (symbol.declarations && symbol.declarations[0]) { + var declarationSourceFile = ts.getSourceFileOfNode(symbol.declarations[0]); + return declarationSourceFile && declarationSourceFile.resolvedPath; + } + } + /** + * Get the referencedFile from the import name node from file + */ + function getReferencedFileFromImportLiteral(checker, importName) { + var symbol = checker.getSymbolAtLocation(importName); + return symbol && getReferencedFileFromImportedModuleSymbol(symbol); + } + /** + * Gets the path to reference file from file name, it could be resolvedPath if present otherwise path + */ + function getReferencedFileFromFileName(program, fileName, sourceFileDirectory, getCanonicalFileName) { + return ts.toPath(program.getProjectReferenceRedirect(fileName) || fileName, sourceFileDirectory, getCanonicalFileName); + } + /** + * Gets the referenced files for a file from the program with values for the keys as referenced file's path to be true + */ + function getReferencedFiles(program, sourceFile, getCanonicalFileName) { + var referencedFiles; + // We need to use a set here since the code can contain the same import twice, + // but that will only be one dependency. + // To avoid invernal conversion, the key of the referencedFiles map must be of type Path + if (sourceFile.imports && sourceFile.imports.length > 0) { + var checker = program.getTypeChecker(); + for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { + var importName = _a[_i]; + var declarationSourceFilePath = getReferencedFileFromImportLiteral(checker, importName); + if (declarationSourceFilePath) { + addReferencedFile(declarationSourceFilePath); + } + } + } + var sourceFileDirectory = ts.getDirectoryPath(sourceFile.path); + // Handle triple slash references + if (sourceFile.referencedFiles && sourceFile.referencedFiles.length > 0) { + for (var _b = 0, _c = sourceFile.referencedFiles; _b < _c.length; _b++) { + var referencedFile = _c[_b]; + var referencedPath = getReferencedFileFromFileName(program, referencedFile.fileName, sourceFileDirectory, getCanonicalFileName); + addReferencedFile(referencedPath); + } + } + // Handle type reference directives + if (sourceFile.resolvedTypeReferenceDirectiveNames) { + sourceFile.resolvedTypeReferenceDirectiveNames.forEach(function (resolvedTypeReferenceDirective) { + if (!resolvedTypeReferenceDirective) { + return; + } + var fileName = resolvedTypeReferenceDirective.resolvedFileName; // TODO: GH#18217 + var typeFilePath = getReferencedFileFromFileName(program, fileName, sourceFileDirectory, getCanonicalFileName); + addReferencedFile(typeFilePath); + }); + } + // Add module augmentation as references + if (sourceFile.moduleAugmentations.length) { + var checker = program.getTypeChecker(); + for (var _d = 0, _e = sourceFile.moduleAugmentations; _d < _e.length; _d++) { + var moduleName = _e[_d]; + if (!ts.isStringLiteral(moduleName)) { + continue; + } + var symbol = checker.getSymbolAtLocation(moduleName); + if (!symbol) { + continue; + } + // Add any file other than our own as reference + addReferenceFromAmbientModule(symbol); + } + } + // From ambient modules + for (var _f = 0, _g = program.getTypeChecker().getAmbientModules(); _f < _g.length; _f++) { + var ambientModule = _g[_f]; + if (ambientModule.declarations.length > 1) { + addReferenceFromAmbientModule(ambientModule); + } + } + return referencedFiles; + function addReferenceFromAmbientModule(symbol) { + // Add any file other than our own as reference + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + var declarationSourceFile = ts.getSourceFileOfNode(declaration); + if (declarationSourceFile && + declarationSourceFile !== sourceFile) { + addReferencedFile(declarationSourceFile.resolvedPath); + } + } + } + function addReferencedFile(referencedPath) { + if (!referencedFiles) { + referencedFiles = ts.createMap(); + } + referencedFiles.set(referencedPath, true); + } + } + /** + * Returns true if oldState is reusable, that is the emitKind = module/non module has not changed + */ + function canReuseOldState(newReferencedMap, oldState) { + return oldState && !oldState.referencedMap === !newReferencedMap; + } + BuilderState.canReuseOldState = canReuseOldState; + /** + * Creates the state of file references and signature for the new program from oldState if it is safe + */ + function create(newProgram, getCanonicalFileName, oldState) { + var fileInfos = ts.createMap(); + var referencedMap = newProgram.getCompilerOptions().module !== ts.ModuleKind.None ? ts.createMap() : undefined; + var exportedModulesMap = referencedMap ? ts.createMap() : undefined; + var hasCalledUpdateShapeSignature = ts.createMap(); + var useOldState = canReuseOldState(referencedMap, oldState); + // Create the reference map, and set the file infos + for (var _i = 0, _a = newProgram.getSourceFiles(); _i < _a.length; _i++) { + var sourceFile = _a[_i]; + var version_1 = sourceFile.version; + var oldInfo = useOldState ? oldState.fileInfos.get(sourceFile.path) : undefined; + if (referencedMap) { + var newReferences = getReferencedFiles(newProgram, sourceFile, getCanonicalFileName); + if (newReferences) { + referencedMap.set(sourceFile.path, newReferences); + } + // Copy old visible to outside files map + if (useOldState) { + var exportedModules = oldState.exportedModulesMap.get(sourceFile.path); + if (exportedModules) { + exportedModulesMap.set(sourceFile.path, exportedModules); + } + } + } + fileInfos.set(sourceFile.path, { version: version_1, signature: oldInfo && oldInfo.signature }); + } + return { + fileInfos: fileInfos, + referencedMap: referencedMap, + exportedModulesMap: exportedModulesMap, + hasCalledUpdateShapeSignature: hasCalledUpdateShapeSignature, + allFilesExcludingDefaultLibraryFile: undefined, + allFileNames: undefined + }; + } + BuilderState.create = create; + /** + * Gets the files affected by the path from the program + */ + function getFilesAffectedBy(state, programOfThisState, path, cancellationToken, computeHash, cacheToUpdateSignature, exportedModulesMapCache) { + // Since the operation could be cancelled, the signatures are always stored in the cache + // They will be commited once it is safe to use them + // eg when calling this api from tsserver, if there is no cancellation of the operation + // In the other cases the affected files signatures are commited only after the iteration through the result is complete + var signatureCache = cacheToUpdateSignature || ts.createMap(); + var sourceFile = programOfThisState.getSourceFileByPath(path); + if (!sourceFile) { + return ts.emptyArray; + } + if (!updateShapeSignature(state, programOfThisState, sourceFile, signatureCache, cancellationToken, computeHash, exportedModulesMapCache)) { + return [sourceFile]; + } + var result = (state.referencedMap ? getFilesAffectedByUpdatedShapeWhenModuleEmit : getFilesAffectedByUpdatedShapeWhenNonModuleEmit)(state, programOfThisState, sourceFile, signatureCache, cancellationToken, computeHash, exportedModulesMapCache); + if (!cacheToUpdateSignature) { + // Commit all the signatures in the signature cache + updateSignaturesFromCache(state, signatureCache); + } + return result; + } + BuilderState.getFilesAffectedBy = getFilesAffectedBy; + /** + * Updates the signatures from the cache into state's fileinfo signatures + * This should be called whenever it is safe to commit the state of the builder + */ + function updateSignaturesFromCache(state, signatureCache) { + signatureCache.forEach(function (signature, path) { + state.fileInfos.get(path).signature = signature; + state.hasCalledUpdateShapeSignature.set(path, true); + }); + } + BuilderState.updateSignaturesFromCache = updateSignaturesFromCache; + /** + * Returns if the shape of the signature has changed since last emit + */ + function updateShapeSignature(state, programOfThisState, sourceFile, cacheToUpdateSignature, cancellationToken, computeHash, exportedModulesMapCache) { + ts.Debug.assert(!!sourceFile); + ts.Debug.assert(!exportedModulesMapCache || !!state.exportedModulesMap, "Compute visible to outside map only if visibleToOutsideReferencedMap present in the state"); + // If we have cached the result for this file, that means hence forth we should assume file shape is uptodate + if (state.hasCalledUpdateShapeSignature.has(sourceFile.path) || cacheToUpdateSignature.has(sourceFile.path)) { + return false; + } + var info = state.fileInfos.get(sourceFile.path); + if (!info) + return ts.Debug.fail(); + var prevSignature = info.signature; + var latestSignature; + if (sourceFile.isDeclarationFile) { + latestSignature = sourceFile.version; + if (exportedModulesMapCache && latestSignature !== prevSignature) { + // All the references in this file are exported + var references = state.referencedMap ? state.referencedMap.get(sourceFile.path) : undefined; + exportedModulesMapCache.set(sourceFile.path, references || false); + } + } + else { + var emitOutput = ts.getFileEmitOutput(programOfThisState, sourceFile, /*emitOnlyDtsFiles*/ true, cancellationToken); + if (emitOutput.outputFiles && emitOutput.outputFiles.length > 0) { + latestSignature = computeHash(emitOutput.outputFiles[0].text); + if (exportedModulesMapCache && latestSignature !== prevSignature) { + updateExportedModules(sourceFile, emitOutput.exportedModulesFromDeclarationEmit, exportedModulesMapCache); + } + } + else { + latestSignature = prevSignature; // TODO: GH#18217 + } + } + cacheToUpdateSignature.set(sourceFile.path, latestSignature); + return !prevSignature || latestSignature !== prevSignature; + } + /** + * Coverts the declaration emit result into exported modules map + */ + function updateExportedModules(sourceFile, exportedModulesFromDeclarationEmit, exportedModulesMapCache) { + if (!exportedModulesFromDeclarationEmit) { + exportedModulesMapCache.set(sourceFile.path, false); + return; + } + var exportedModules; + exportedModulesFromDeclarationEmit.forEach(function (symbol) { return addExportedModule(getReferencedFileFromImportedModuleSymbol(symbol)); }); + exportedModulesMapCache.set(sourceFile.path, exportedModules || false); + function addExportedModule(exportedModulePath) { + if (exportedModulePath) { + if (!exportedModules) { + exportedModules = ts.createMap(); + } + exportedModules.set(exportedModulePath, true); + } + } + } + /** + * Updates the exported modules from cache into state's exported modules map + * This should be called whenever it is safe to commit the state of the builder + */ + function updateExportedFilesMapFromCache(state, exportedModulesMapCache) { + if (exportedModulesMapCache) { + ts.Debug.assert(!!state.exportedModulesMap); + exportedModulesMapCache.forEach(function (exportedModules, path) { + if (exportedModules) { + state.exportedModulesMap.set(path, exportedModules); + } + else { + state.exportedModulesMap.delete(path); + } + }); + } + } + BuilderState.updateExportedFilesMapFromCache = updateExportedFilesMapFromCache; + /** + * Get all the dependencies of the sourceFile + */ + function getAllDependencies(state, programOfThisState, sourceFile) { + var _a; + var compilerOptions = programOfThisState.getCompilerOptions(); + // With --out or --outFile all outputs go into single file, all files depend on each other + if (compilerOptions.outFile || compilerOptions.out) { + return getAllFileNames(state, programOfThisState); + } + // If this is non module emit, or its a global file, it depends on all the source files + if (!state.referencedMap || isFileAffectingGlobalScope(sourceFile)) { + return getAllFileNames(state, programOfThisState); + } + // Get the references, traversing deep from the referenceMap + var seenMap = ts.createMap(); + var queue = [sourceFile.path]; + while (queue.length) { + var path = queue.pop(); + if (!seenMap.has(path)) { + seenMap.set(path, true); + var references = state.referencedMap.get(path); + if (references) { + var iterator = references.keys(); + for (var _b = iterator.next(), value = _b.value, done = _b.done; !done; _a = iterator.next(), value = _a.value, done = _a.done, _a) { + queue.push(value); + } + } + } + } + return ts.arrayFrom(ts.mapDefinedIterator(seenMap.keys(), function (path) { + var file = programOfThisState.getSourceFileByPath(path); + return file ? file.fileName : path; + })); + } + BuilderState.getAllDependencies = getAllDependencies; + /** + * Gets the names of all files from the program + */ + function getAllFileNames(state, programOfThisState) { + if (!state.allFileNames) { + var sourceFiles = programOfThisState.getSourceFiles(); + state.allFileNames = sourceFiles === ts.emptyArray ? ts.emptyArray : sourceFiles.map(function (file) { return file.fileName; }); + } + return state.allFileNames; + } + /** + * Gets the files referenced by the the file path + */ + function getReferencedByPaths(state, referencedFilePath) { + return ts.arrayFrom(ts.mapDefinedIterator(state.referencedMap.entries(), function (_a) { + var filePath = _a[0], referencesInFile = _a[1]; + return referencesInFile.has(referencedFilePath) ? filePath : undefined; + })); + } + /** + * For script files that contains only ambient external modules, although they are not actually external module files, + * they can only be consumed via importing elements from them. Regular script files cannot consume them. Therefore, + * there are no point to rebuild all script files if these special files have changed. However, if any statement + * in the file is not ambient external module, we treat it as a regular script file. + */ + function containsOnlyAmbientModules(sourceFile) { + for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + if (!ts.isModuleWithStringLiteralName(statement)) { + return false; + } + } + return true; + } + /** + * Return true if file contains anything that augments to global scope we need to build them as if + * they are global files as well as module + */ + function containsGlobalScopeAugmentation(sourceFile) { + return ts.some(sourceFile.moduleAugmentations, function (augmentation) { return ts.isGlobalScopeAugmentation(augmentation.parent); }); + } + /** + * Return true if the file will invalidate all files because it affectes global scope + */ + function isFileAffectingGlobalScope(sourceFile) { + return containsGlobalScopeAugmentation(sourceFile) || + !ts.isExternalModule(sourceFile) && !containsOnlyAmbientModules(sourceFile); + } + /** + * Gets all files of the program excluding the default library file + */ + function getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, firstSourceFile) { + // Use cached result + if (state.allFilesExcludingDefaultLibraryFile) { + return state.allFilesExcludingDefaultLibraryFile; + } + var result; + addSourceFile(firstSourceFile); + for (var _i = 0, _a = programOfThisState.getSourceFiles(); _i < _a.length; _i++) { + var sourceFile = _a[_i]; + if (sourceFile !== firstSourceFile) { + addSourceFile(sourceFile); + } + } + state.allFilesExcludingDefaultLibraryFile = result || ts.emptyArray; + return state.allFilesExcludingDefaultLibraryFile; + function addSourceFile(sourceFile) { + if (!programOfThisState.isSourceFileDefaultLibrary(sourceFile)) { + (result || (result = [])).push(sourceFile); + } + } + } + /** + * When program emits non modular code, gets the files affected by the sourceFile whose shape has changed + */ + function getFilesAffectedByUpdatedShapeWhenNonModuleEmit(state, programOfThisState, sourceFileWithUpdatedShape) { + var compilerOptions = programOfThisState.getCompilerOptions(); + // If `--out` or `--outFile` is specified, any new emit will result in re-emitting the entire project, + // so returning the file itself is good enough. + if (compilerOptions && (compilerOptions.out || compilerOptions.outFile)) { + return [sourceFileWithUpdatedShape]; + } + return getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, sourceFileWithUpdatedShape); + } + /** + * When program emits modular code, gets the files affected by the sourceFile whose shape has changed + */ + function getFilesAffectedByUpdatedShapeWhenModuleEmit(state, programOfThisState, sourceFileWithUpdatedShape, cacheToUpdateSignature, cancellationToken, computeHash, exportedModulesMapCache) { + if (isFileAffectingGlobalScope(sourceFileWithUpdatedShape)) { + return getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, sourceFileWithUpdatedShape); + } + var compilerOptions = programOfThisState.getCompilerOptions(); + if (compilerOptions && (compilerOptions.isolatedModules || compilerOptions.out || compilerOptions.outFile)) { + return [sourceFileWithUpdatedShape]; + } + // Now we need to if each file in the referencedBy list has a shape change as well. + // Because if so, its own referencedBy files need to be saved as well to make the + // emitting result consistent with files on disk. + var seenFileNamesMap = ts.createMap(); + // Start with the paths this file was referenced by + seenFileNamesMap.set(sourceFileWithUpdatedShape.path, sourceFileWithUpdatedShape); + var queue = getReferencedByPaths(state, sourceFileWithUpdatedShape.path); + while (queue.length > 0) { + var currentPath = queue.pop(); + if (!seenFileNamesMap.has(currentPath)) { + var currentSourceFile = programOfThisState.getSourceFileByPath(currentPath); + seenFileNamesMap.set(currentPath, currentSourceFile); + if (currentSourceFile && updateShapeSignature(state, programOfThisState, currentSourceFile, cacheToUpdateSignature, cancellationToken, computeHash, exportedModulesMapCache)) { // TODO: GH#18217 + queue.push.apply(// TODO: GH#18217 + queue, getReferencedByPaths(state, currentPath)); + } + } + } + // Return array of values that needs emit + // Return array of values that needs emit + return ts.arrayFrom(ts.mapDefinedIterator(seenFileNamesMap.values(), function (value) { return value; })); + } + })(BuilderState = ts.BuilderState || (ts.BuilderState = {})); +})(ts || (ts = {})); +/*@internal*/ +var ts; +(function (ts) { + function hasSameKeys(map1, map2) { + // Has same size and every key is present in both maps + return map1 === map2 || map1 !== undefined && map2 !== undefined && map1.size === map2.size && !ts.forEachKey(map1, function (key) { return !map2.has(key); }); + } + /** + * Create the state so that we can iterate on changedFiles/affected files + */ + function createBuilderProgramState(newProgram, getCanonicalFileName, oldState) { + var state = ts.BuilderState.create(newProgram, getCanonicalFileName, oldState); + state.program = newProgram; + var compilerOptions = newProgram.getCompilerOptions(); + if (!compilerOptions.outFile && !compilerOptions.out) { + state.semanticDiagnosticsPerFile = ts.createMap(); + } + state.changedFilesSet = ts.createMap(); + var useOldState = ts.BuilderState.canReuseOldState(state.referencedMap, oldState); + var oldCompilerOptions = useOldState ? oldState.program.getCompilerOptions() : undefined; + var canCopySemanticDiagnostics = useOldState && oldState.semanticDiagnosticsPerFile && !!state.semanticDiagnosticsPerFile && + !ts.compilerOptionsAffectSemanticDiagnostics(compilerOptions, oldCompilerOptions); + if (useOldState) { + // Verify the sanity of old state + if (!oldState.currentChangedFilePath) { + ts.Debug.assert(!oldState.affectedFiles && (!oldState.currentAffectedFilesSignatures || !oldState.currentAffectedFilesSignatures.size), "Cannot reuse if only few affected files of currentChangedFile were iterated"); + } + if (canCopySemanticDiagnostics) { + ts.Debug.assert(!ts.forEachKey(oldState.changedFilesSet, function (path) { return oldState.semanticDiagnosticsPerFile.has(path); }), "Semantic diagnostics shouldnt be available for changed files"); + } + // Copy old state's changed files set + ts.copyEntries(oldState.changedFilesSet, state.changedFilesSet); + } + // Update changed files and copy semantic diagnostics if we can + var referencedMap = state.referencedMap; + var oldReferencedMap = useOldState ? oldState.referencedMap : undefined; + var copyDeclarationFileDiagnostics = canCopySemanticDiagnostics && !compilerOptions.skipLibCheck === !oldCompilerOptions.skipLibCheck; + var copyLibFileDiagnostics = copyDeclarationFileDiagnostics && !compilerOptions.skipDefaultLibCheck === !oldCompilerOptions.skipDefaultLibCheck; + state.fileInfos.forEach(function (info, sourceFilePath) { + var oldInfo; + var newReferences; + // if not using old state, every file is changed + if (!useOldState || + // File wasnt present in old state + !(oldInfo = oldState.fileInfos.get(sourceFilePath)) || + // versions dont match + oldInfo.version !== info.version || + // Referenced files changed + !hasSameKeys(newReferences = referencedMap && referencedMap.get(sourceFilePath), oldReferencedMap && oldReferencedMap.get(sourceFilePath)) || + // Referenced file was deleted in the new program + newReferences && ts.forEachKey(newReferences, function (path) { return !state.fileInfos.has(path) && oldState.fileInfos.has(path); })) { + // Register file as changed file and do not copy semantic diagnostics, since all changed files need to be re-evaluated + state.changedFilesSet.set(sourceFilePath, true); + } + else if (canCopySemanticDiagnostics) { + var sourceFile = state.program.getSourceFileByPath(sourceFilePath); + if (sourceFile.isDeclarationFile && !copyDeclarationFileDiagnostics) { + return; + } + if (sourceFile.hasNoDefaultLib && !copyLibFileDiagnostics) { + return; + } + // Unchanged file copy diagnostics + var diagnostics = oldState.semanticDiagnosticsPerFile.get(sourceFilePath); + if (diagnostics) { + state.semanticDiagnosticsPerFile.set(sourceFilePath, diagnostics); + if (!state.semanticDiagnosticsFromOldState) { + state.semanticDiagnosticsFromOldState = ts.createMap(); + } + state.semanticDiagnosticsFromOldState.set(sourceFilePath, true); + } + } + }); + return state; + } + /** + * Verifies that source file is ok to be used in calls that arent handled by next + */ + function assertSourceFileOkWithoutNextAffectedCall(state, sourceFile) { + ts.Debug.assert(!sourceFile || !state.affectedFiles || state.affectedFiles[state.affectedFilesIndex - 1] !== sourceFile || !state.semanticDiagnosticsPerFile.has(sourceFile.path)); + } + /** + * This function returns the next affected file to be processed. + * Note that until doneAffected is called it would keep reporting same result + * This is to allow the callers to be able to actually remove affected file only when the operation is complete + * eg. if during diagnostics check cancellation token ends up cancelling the request, the affected file should be retained + */ + function getNextAffectedFile(state, cancellationToken, computeHash) { + while (true) { + var affectedFiles = state.affectedFiles; + if (affectedFiles) { + var seenAffectedFiles = state.seenAffectedFiles; + var affectedFilesIndex = state.affectedFilesIndex; // TODO: GH#18217 + while (affectedFilesIndex < affectedFiles.length) { + var affectedFile = affectedFiles[affectedFilesIndex]; + if (!seenAffectedFiles.has(affectedFile.path)) { + // Set the next affected file as seen and remove the cached semantic diagnostics + state.affectedFilesIndex = affectedFilesIndex; + cleanSemanticDiagnosticsOfAffectedFile(state, affectedFile); + return affectedFile; + } + seenAffectedFiles.set(affectedFile.path, true); + affectedFilesIndex++; + } + // Remove the changed file from the change set + state.changedFilesSet.delete(state.currentChangedFilePath); + state.currentChangedFilePath = undefined; + // Commit the changes in file signature + ts.BuilderState.updateSignaturesFromCache(state, state.currentAffectedFilesSignatures); + state.currentAffectedFilesSignatures.clear(); + ts.BuilderState.updateExportedFilesMapFromCache(state, state.currentAffectedFilesExportedModulesMap); + state.affectedFiles = undefined; + } + // Get next changed file + var nextKey = state.changedFilesSet.keys().next(); + if (nextKey.done) { + // Done + return undefined; + } + // With --out or --outFile all outputs go into single file + // so operations are performed directly on program, return program + var compilerOptions = state.program.getCompilerOptions(); + if (compilerOptions.outFile || compilerOptions.out) { + ts.Debug.assert(!state.semanticDiagnosticsPerFile); + return state.program; + } + // Get next batch of affected files + state.currentAffectedFilesSignatures = state.currentAffectedFilesSignatures || ts.createMap(); + if (state.exportedModulesMap) { + state.currentAffectedFilesExportedModulesMap = state.currentAffectedFilesExportedModulesMap || ts.createMap(); + } + state.affectedFiles = ts.BuilderState.getFilesAffectedBy(state, state.program, nextKey.value, cancellationToken, computeHash, state.currentAffectedFilesSignatures, state.currentAffectedFilesExportedModulesMap); + state.currentChangedFilePath = nextKey.value; + state.affectedFilesIndex = 0; + state.seenAffectedFiles = state.seenAffectedFiles || ts.createMap(); + } + } + /** + * Remove the semantic diagnostics cached from old state for affected File and the files that are referencing modules that export entities from affected file + */ + function cleanSemanticDiagnosticsOfAffectedFile(state, affectedFile) { + if (removeSemanticDiagnosticsOf(state, affectedFile.path)) { + // If there are no more diagnostics from old cache, done + return; + } + // Clean lib file diagnostics if its all files excluding default files to emit + if (state.allFilesExcludingDefaultLibraryFile === state.affectedFiles && !state.cleanedDiagnosticsOfLibFiles) { + state.cleanedDiagnosticsOfLibFiles = true; + var options_2 = state.program.getCompilerOptions(); + if (ts.forEach(state.program.getSourceFiles(), function (f) { + return state.program.isSourceFileDefaultLibrary(f) && + !ts.skipTypeChecking(f, options_2) && + removeSemanticDiagnosticsOf(state, f.path); + })) { + return; + } + } + // If there was change in signature for the changed file, + // then delete the semantic diagnostics for files that are affected by using exports of this module + if (!state.exportedModulesMap || state.affectedFiles.length === 1 || !state.changedFilesSet.has(affectedFile.path)) { + return; + } + ts.Debug.assert(!!state.currentAffectedFilesExportedModulesMap); + var seenFileAndExportsOfFile = ts.createMap(); + // Go through exported modules from cache first + // If exported modules has path, all files referencing file exported from are affected + if (ts.forEachEntry(state.currentAffectedFilesExportedModulesMap, function (exportedModules, exportedFromPath) { + return exportedModules && + exportedModules.has(affectedFile.path) && + removeSemanticDiagnosticsOfFilesReferencingPath(state, exportedFromPath, seenFileAndExportsOfFile); + })) { + return; + } + // If exported from path is not from cache and exported modules has path, all files referencing file exported from are affected + ts.forEachEntry(state.exportedModulesMap, function (exportedModules, exportedFromPath) { + return !state.currentAffectedFilesExportedModulesMap.has(exportedFromPath) && // If we already iterated this through cache, ignore it + exportedModules.has(affectedFile.path) && + removeSemanticDiagnosticsOfFilesReferencingPath(state, exportedFromPath, seenFileAndExportsOfFile); + }); + } + /** + * removes the semantic diagnostics of files referencing referencedPath and + * returns true if there are no more semantic diagnostics from old state + */ + function removeSemanticDiagnosticsOfFilesReferencingPath(state, referencedPath, seenFileAndExportsOfFile) { + return ts.forEachEntry(state.referencedMap, function (referencesInFile, filePath) { + return referencesInFile.has(referencedPath) && removeSemanticDiagnosticsOfFileAndExportsOfFile(state, filePath, seenFileAndExportsOfFile); + }); + } + /** + * Removes semantic diagnostics of file and anything that exports this file + */ + function removeSemanticDiagnosticsOfFileAndExportsOfFile(state, filePath, seenFileAndExportsOfFile) { + if (!ts.addToSeen(seenFileAndExportsOfFile, filePath)) { + return false; + } + if (removeSemanticDiagnosticsOf(state, filePath)) { + // If there are no more diagnostics from old cache, done + return true; + } + ts.Debug.assert(!!state.currentAffectedFilesExportedModulesMap); + // Go through exported modules from cache first + // If exported modules has path, all files referencing file exported from are affected + if (ts.forEachEntry(state.currentAffectedFilesExportedModulesMap, function (exportedModules, exportedFromPath) { + return exportedModules && + exportedModules.has(filePath) && + removeSemanticDiagnosticsOfFileAndExportsOfFile(state, exportedFromPath, seenFileAndExportsOfFile); + })) { + return true; + } + // If exported from path is not from cache and exported modules has path, all files referencing file exported from are affected + return !!ts.forEachEntry(state.exportedModulesMap, function (exportedModules, exportedFromPath) { + return !state.currentAffectedFilesExportedModulesMap.has(exportedFromPath) && // If we already iterated this through cache, ignore it + exportedModules.has(filePath) && + removeSemanticDiagnosticsOfFileAndExportsOfFile(state, exportedFromPath, seenFileAndExportsOfFile); + }); + } + /** + * Removes semantic diagnostics for path and + * returns true if there are no more semantic diagnostics from the old state + */ + function removeSemanticDiagnosticsOf(state, path) { + if (!state.semanticDiagnosticsFromOldState) { + return true; + } + state.semanticDiagnosticsFromOldState.delete(path); + state.semanticDiagnosticsPerFile.delete(path); + return !state.semanticDiagnosticsFromOldState.size; + } + /** + * This is called after completing operation on the next affected file. + * The operations here are postponed to ensure that cancellation during the iteration is handled correctly + */ + function doneWithAffectedFile(state, affected) { + if (affected === state.program) { + state.changedFilesSet.clear(); + } + else { + state.seenAffectedFiles.set(affected.path, true); + state.affectedFilesIndex++; + } + } + /** + * Returns the result with affected file + */ + function toAffectedFileResult(state, result, affected) { + doneWithAffectedFile(state, affected); + return { result: result, affected: affected }; + } + /** + * Gets the semantic diagnostics either from cache if present, or otherwise from program and caches it + * Note that it is assumed that the when asked about semantic diagnostics, the file has been taken out of affected files/changed file set + */ + function getSemanticDiagnosticsOfFile(state, sourceFile, cancellationToken) { + var path = sourceFile.path; + var cachedDiagnostics = state.semanticDiagnosticsPerFile.get(path); + // Report the semantic diagnostics from the cache if we already have those diagnostics present + if (cachedDiagnostics) { + return cachedDiagnostics; + } + // Diagnostics werent cached, get them from program, and cache the result + var diagnostics = state.program.getSemanticDiagnostics(sourceFile, cancellationToken); + state.semanticDiagnosticsPerFile.set(path, diagnostics); + return diagnostics; + } + var BuilderProgramKind; + (function (BuilderProgramKind) { + BuilderProgramKind[BuilderProgramKind["SemanticDiagnosticsBuilderProgram"] = 0] = "SemanticDiagnosticsBuilderProgram"; + BuilderProgramKind[BuilderProgramKind["EmitAndSemanticDiagnosticsBuilderProgram"] = 1] = "EmitAndSemanticDiagnosticsBuilderProgram"; + })(BuilderProgramKind = ts.BuilderProgramKind || (ts.BuilderProgramKind = {})); + function getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { + var host; + var newProgram; + var oldProgram; + if (newProgramOrRootNames === undefined) { + ts.Debug.assert(hostOrOptions === undefined); + host = oldProgramOrHost; + oldProgram = configFileParsingDiagnosticsOrOldProgram; + ts.Debug.assert(!!oldProgram); + newProgram = oldProgram.getProgram(); + } + else if (ts.isArray(newProgramOrRootNames)) { + oldProgram = configFileParsingDiagnosticsOrOldProgram; + newProgram = ts.createProgram({ + rootNames: newProgramOrRootNames, + options: hostOrOptions, + host: oldProgramOrHost, + oldProgram: oldProgram && oldProgram.getProgram(), + configFileParsingDiagnostics: configFileParsingDiagnostics, + projectReferences: projectReferences + }); + host = oldProgramOrHost; + } + else { + newProgram = newProgramOrRootNames; + host = hostOrOptions; + oldProgram = oldProgramOrHost; + configFileParsingDiagnostics = configFileParsingDiagnosticsOrOldProgram; + } + return { host: host, newProgram: newProgram, oldProgram: oldProgram, configFileParsingDiagnostics: configFileParsingDiagnostics || ts.emptyArray }; + } + ts.getBuilderCreationParameters = getBuilderCreationParameters; + function createBuilderProgram(kind, _a) { + var newProgram = _a.newProgram, host = _a.host, oldProgram = _a.oldProgram, configFileParsingDiagnostics = _a.configFileParsingDiagnostics; + // Return same program if underlying program doesnt change + var oldState = oldProgram && oldProgram.getState(); + if (oldState && newProgram === oldState.program && configFileParsingDiagnostics === newProgram.getConfigFileParsingDiagnostics()) { + newProgram = undefined; // TODO: GH#18217 + oldState = undefined; + return oldProgram; + } + /** + * Create the canonical file name for identity + */ + var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames()); + /** + * Computing hash to for signature verification + */ + var computeHash = host.createHash || ts.identity; + var state = createBuilderProgramState(newProgram, getCanonicalFileName, oldState); + // To ensure that we arent storing any references to old program or new program without state + newProgram = undefined; // TODO: GH#18217 + oldProgram = undefined; + oldState = undefined; + var result = { + getState: function () { return state; }, + getProgram: function () { return state.program; }, + getCompilerOptions: function () { return state.program.getCompilerOptions(); }, + getSourceFile: function (fileName) { return state.program.getSourceFile(fileName); }, + getSourceFiles: function () { return state.program.getSourceFiles(); }, + getOptionsDiagnostics: function (cancellationToken) { return state.program.getOptionsDiagnostics(cancellationToken); }, + getGlobalDiagnostics: function (cancellationToken) { return state.program.getGlobalDiagnostics(cancellationToken); }, + getConfigFileParsingDiagnostics: function () { return configFileParsingDiagnostics || state.program.getConfigFileParsingDiagnostics(); }, + getSyntacticDiagnostics: function (sourceFile, cancellationToken) { return state.program.getSyntacticDiagnostics(sourceFile, cancellationToken); }, + getSemanticDiagnostics: getSemanticDiagnostics, + emit: emit, + getAllDependencies: function (sourceFile) { return ts.BuilderState.getAllDependencies(state, state.program, sourceFile); }, + getCurrentDirectory: function () { return state.program.getCurrentDirectory(); } + }; + if (kind === BuilderProgramKind.SemanticDiagnosticsBuilderProgram) { + result.getSemanticDiagnosticsOfNextAffectedFile = getSemanticDiagnosticsOfNextAffectedFile; + } + else if (kind === BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram) { + result.emitNextAffectedFile = emitNextAffectedFile; + } + else { + ts.notImplemented(); + } + return result; + /** + * Emits the next affected file's emit result (EmitResult and sourceFiles emitted) or returns undefined if iteration is complete + * The first of writeFile if provided, writeFile of BuilderProgramHost if provided, writeFile of compiler host + * in that order would be used to write the files + */ + function emitNextAffectedFile(writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) { + var affected = getNextAffectedFile(state, cancellationToken, computeHash); + if (!affected) { + // Done + return undefined; + } + return toAffectedFileResult(state, + // When whole program is affected, do emit only once (eg when --out or --outFile is specified) + // Otherwise just affected file + state.program.emit(affected === state.program ? undefined : affected, writeFile || host.writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers), affected); + } + /** + * Emits the JavaScript and declaration files. + * When targetSource file is specified, emits the files corresponding to that source file, + * otherwise for the whole program. + * In case of EmitAndSemanticDiagnosticsBuilderProgram, when targetSourceFile is specified, + * it is assumed that that file is handled from affected file list. If targetSourceFile is not specified, + * it will only emit all the affected files instead of whole program + * + * The first of writeFile if provided, writeFile of BuilderProgramHost if provided, writeFile of compiler host + * in that order would be used to write the files + */ + function emit(targetSourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) { + if (kind === BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram) { + assertSourceFileOkWithoutNextAffectedCall(state, targetSourceFile); + if (!targetSourceFile) { + // Emit and report any errors we ran into. + var sourceMaps = []; + var emitSkipped = false; + var diagnostics = void 0; + var emittedFiles = []; + var affectedEmitResult = void 0; + while (affectedEmitResult = emitNextAffectedFile(writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers)) { + emitSkipped = emitSkipped || affectedEmitResult.result.emitSkipped; + diagnostics = ts.addRange(diagnostics, affectedEmitResult.result.diagnostics); + emittedFiles = ts.addRange(emittedFiles, affectedEmitResult.result.emittedFiles); + sourceMaps = ts.addRange(sourceMaps, affectedEmitResult.result.sourceMaps); + } + return { + emitSkipped: emitSkipped, + diagnostics: diagnostics || ts.emptyArray, + emittedFiles: emittedFiles, + sourceMaps: sourceMaps + }; + } + } + return state.program.emit(targetSourceFile, writeFile || host.writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); + } + /** + * Return the semantic diagnostics for the next affected file or undefined if iteration is complete + * If provided ignoreSourceFile would be called before getting the diagnostics and would ignore the sourceFile if the returned value was true + */ + function getSemanticDiagnosticsOfNextAffectedFile(cancellationToken, ignoreSourceFile) { + while (true) { + var affected = getNextAffectedFile(state, cancellationToken, computeHash); + if (!affected) { + // Done + return undefined; + } + else if (affected === state.program) { + // When whole program is affected, get all semantic diagnostics (eg when --out or --outFile is specified) + return toAffectedFileResult(state, state.program.getSemanticDiagnostics(/*targetSourceFile*/ undefined, cancellationToken), affected); + } + // Get diagnostics for the affected file if its not ignored + if (ignoreSourceFile && ignoreSourceFile(affected)) { + // Get next affected file + doneWithAffectedFile(state, affected); + continue; + } + return toAffectedFileResult(state, getSemanticDiagnosticsOfFile(state, affected, cancellationToken), affected); + } + } + /** + * Gets the semantic diagnostics from the program corresponding to this state of file (if provided) or whole program + * The semantic diagnostics are cached and managed here + * Note that it is assumed that when asked about semantic diagnostics through this API, + * the file has been taken out of affected files so it is safe to use cache or get from program and cache the diagnostics + * In case of SemanticDiagnosticsBuilderProgram if the source file is not provided, + * it will iterate through all the affected files, to ensure that cache stays valid and yet provide a way to get all semantic diagnostics + */ + function getSemanticDiagnostics(sourceFile, cancellationToken) { + assertSourceFileOkWithoutNextAffectedCall(state, sourceFile); + var compilerOptions = state.program.getCompilerOptions(); + if (compilerOptions.outFile || compilerOptions.out) { + ts.Debug.assert(!state.semanticDiagnosticsPerFile); + // We dont need to cache the diagnostics just return them from program + return state.program.getSemanticDiagnostics(sourceFile, cancellationToken); + } + if (sourceFile) { + return getSemanticDiagnosticsOfFile(state, sourceFile, cancellationToken); + } + if (kind === BuilderProgramKind.SemanticDiagnosticsBuilderProgram) { + // When semantic builder asks for diagnostics of the whole program, + // ensure that all the affected files are handled + var affected = void 0; + while (affected = getNextAffectedFile(state, cancellationToken, computeHash)) { + doneWithAffectedFile(state, affected); + } + } + var diagnostics; + for (var _i = 0, _a = state.program.getSourceFiles(); _i < _a.length; _i++) { + var sourceFile_2 = _a[_i]; + diagnostics = ts.addRange(diagnostics, getSemanticDiagnosticsOfFile(state, sourceFile_2, cancellationToken)); + } + return diagnostics || ts.emptyArray; + } + } + ts.createBuilderProgram = createBuilderProgram; +})(ts || (ts = {})); +(function (ts) { + function createSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { + return ts.createBuilderProgram(ts.BuilderProgramKind.SemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences)); + } + ts.createSemanticDiagnosticsBuilderProgram = createSemanticDiagnosticsBuilderProgram; + function createEmitAndSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { + return ts.createBuilderProgram(ts.BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences)); + } + ts.createEmitAndSemanticDiagnosticsBuilderProgram = createEmitAndSemanticDiagnosticsBuilderProgram; + function createAbstractBuilder(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { + var program = ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences).newProgram; + return { + // Only return program, all other methods are not implemented + getProgram: function () { return program; }, + getState: ts.notImplemented, + getCompilerOptions: ts.notImplemented, + getSourceFile: ts.notImplemented, + getSourceFiles: ts.notImplemented, + getOptionsDiagnostics: ts.notImplemented, + getGlobalDiagnostics: ts.notImplemented, + getConfigFileParsingDiagnostics: ts.notImplemented, + getSyntacticDiagnostics: ts.notImplemented, + getSemanticDiagnostics: ts.notImplemented, + emit: ts.notImplemented, + getAllDependencies: ts.notImplemented, + getCurrentDirectory: ts.notImplemented + }; + } + ts.createAbstractBuilder = createAbstractBuilder; +})(ts || (ts = {})); +/*@internal*/ +var ts; +(function (ts) { + function isPathInNodeModulesStartingWithDot(path) { + return ts.stringContains(path, "/node_modules/."); + } + ts.isPathInNodeModulesStartingWithDot = isPathInNodeModulesStartingWithDot; + ts.maxNumberOfFilesToIterateForInvalidation = 256; + function createResolutionCache(resolutionHost, rootDirForResolution, logChangesWhenResolvingModule) { + var filesWithChangedSetOfUnresolvedImports; + var filesWithInvalidatedResolutions; + var filesWithInvalidatedNonRelativeUnresolvedImports; + var allFilesHaveInvalidatedResolution = false; + var nonRelativeExternalModuleResolutions = ts.createMultiMap(); + var getCurrentDirectory = ts.memoize(function () { return resolutionHost.getCurrentDirectory(); }); // TODO: GH#18217 + var cachedDirectoryStructureHost = resolutionHost.getCachedDirectoryStructureHost(); + // The resolvedModuleNames and resolvedTypeReferenceDirectives are the cache of resolutions per file. + // The key in the map is source file's path. + // The values are Map of resolutions with key being name lookedup. + var resolvedModuleNames = ts.createMap(); + var perDirectoryResolvedModuleNames = ts.createCacheWithRedirects(); + var nonRelativeModuleNameCache = ts.createCacheWithRedirects(); + var moduleResolutionCache = ts.createModuleResolutionCacheWithMaps(perDirectoryResolvedModuleNames, nonRelativeModuleNameCache, getCurrentDirectory(), resolutionHost.getCanonicalFileName); + var resolvedTypeReferenceDirectives = ts.createMap(); + var perDirectoryResolvedTypeReferenceDirectives = ts.createCacheWithRedirects(); + /** + * These are the extensions that failed lookup files will have by default, + * any other extension of failed lookup will be store that path in custom failed lookup path + * This helps in not having to comb through all resolutions when files are added/removed + * Note that .d.ts file also has .d.ts extension hence will be part of default extensions + */ + var failedLookupDefaultExtensions = [".ts" /* Ts */, ".tsx" /* Tsx */, ".js" /* Js */, ".jsx" /* Jsx */, ".json" /* Json */]; + var customFailedLookupPaths = ts.createMap(); + var directoryWatchesOfFailedLookups = ts.createMap(); + var rootDir = rootDirForResolution && ts.removeTrailingDirectorySeparator(ts.getNormalizedAbsolutePath(rootDirForResolution, getCurrentDirectory())); + var rootPath = (rootDir && resolutionHost.toPath(rootDir)); // TODO: GH#18217 + // TypeRoot watches for the types that get added as part of getAutomaticTypeDirectiveNames + var typeRootsWatches = ts.createMap(); + return { + startRecordingFilesWithChangedResolutions: startRecordingFilesWithChangedResolutions, + finishRecordingFilesWithChangedResolutions: finishRecordingFilesWithChangedResolutions, + // perDirectoryResolvedModuleNames and perDirectoryResolvedTypeReferenceDirectives could be non empty if there was exception during program update + // (between startCachingPerDirectoryResolution and finishCachingPerDirectoryResolution) + startCachingPerDirectoryResolution: clearPerDirectoryResolutions, + finishCachingPerDirectoryResolution: finishCachingPerDirectoryResolution, + resolveModuleNames: resolveModuleNames, + getResolvedModuleWithFailedLookupLocationsFromCache: getResolvedModuleWithFailedLookupLocationsFromCache, + resolveTypeReferenceDirectives: resolveTypeReferenceDirectives, + removeResolutionsFromProjectReferenceRedirects: removeResolutionsFromProjectReferenceRedirects, + removeResolutionsOfFile: removeResolutionsOfFile, + invalidateResolutionOfFile: invalidateResolutionOfFile, + setFilesWithInvalidatedNonRelativeUnresolvedImports: setFilesWithInvalidatedNonRelativeUnresolvedImports, + createHasInvalidatedResolution: createHasInvalidatedResolution, + updateTypeRootsWatch: updateTypeRootsWatch, + closeTypeRootsWatch: closeTypeRootsWatch, + clear: clear + }; + function getResolvedModule(resolution) { + return resolution.resolvedModule; + } + function getResolvedTypeReferenceDirective(resolution) { + return resolution.resolvedTypeReferenceDirective; + } + function isInDirectoryPath(dir, file) { + if (dir === undefined || file.length <= dir.length) { + return false; + } + return ts.startsWith(file, dir) && file[dir.length] === ts.directorySeparator; + } + function clear() { + ts.clearMap(directoryWatchesOfFailedLookups, ts.closeFileWatcherOf); + customFailedLookupPaths.clear(); + nonRelativeExternalModuleResolutions.clear(); + closeTypeRootsWatch(); + resolvedModuleNames.clear(); + resolvedTypeReferenceDirectives.clear(); + allFilesHaveInvalidatedResolution = false; + // perDirectoryResolvedModuleNames and perDirectoryResolvedTypeReferenceDirectives could be non empty if there was exception during program update + // (between startCachingPerDirectoryResolution and finishCachingPerDirectoryResolution) + clearPerDirectoryResolutions(); + } + function startRecordingFilesWithChangedResolutions() { + filesWithChangedSetOfUnresolvedImports = []; + } + function finishRecordingFilesWithChangedResolutions() { + var collected = filesWithChangedSetOfUnresolvedImports; + filesWithChangedSetOfUnresolvedImports = undefined; + return collected; + } + function isFileWithInvalidatedNonRelativeUnresolvedImports(path) { + if (!filesWithInvalidatedNonRelativeUnresolvedImports) { + return false; + } + // Invalidated if file has unresolved imports + var value = filesWithInvalidatedNonRelativeUnresolvedImports.get(path); + return !!value && !!value.length; + } + function createHasInvalidatedResolution(forceAllFilesAsInvalidated) { + if (allFilesHaveInvalidatedResolution || forceAllFilesAsInvalidated) { + // Any file asked would have invalidated resolution + filesWithInvalidatedResolutions = undefined; + return ts.returnTrue; + } + var collected = filesWithInvalidatedResolutions; + filesWithInvalidatedResolutions = undefined; + return function (path) { return (!!collected && collected.has(path)) || + isFileWithInvalidatedNonRelativeUnresolvedImports(path); }; + } + function clearPerDirectoryResolutions() { + perDirectoryResolvedModuleNames.clear(); + nonRelativeModuleNameCache.clear(); + perDirectoryResolvedTypeReferenceDirectives.clear(); + nonRelativeExternalModuleResolutions.forEach(watchFailedLookupLocationOfNonRelativeModuleResolutions); + nonRelativeExternalModuleResolutions.clear(); + } + function finishCachingPerDirectoryResolution() { + allFilesHaveInvalidatedResolution = false; + filesWithInvalidatedNonRelativeUnresolvedImports = undefined; + clearPerDirectoryResolutions(); + directoryWatchesOfFailedLookups.forEach(function (watcher, path) { + if (watcher.refCount === 0) { + directoryWatchesOfFailedLookups.delete(path); + watcher.watcher.close(); + } + }); + } + function resolveModuleName(moduleName, containingFile, compilerOptions, host, redirectedReference) { + var primaryResult = ts.resolveModuleName(moduleName, containingFile, compilerOptions, host, moduleResolutionCache, redirectedReference); + // return result immediately only if global cache support is not enabled or if it is .ts, .tsx or .d.ts + if (!resolutionHost.getGlobalCache) { + return primaryResult; + } + // otherwise try to load typings from @types + var globalCache = resolutionHost.getGlobalCache(); + if (globalCache !== undefined && !ts.isExternalModuleNameRelative(moduleName) && !(primaryResult.resolvedModule && ts.extensionIsTS(primaryResult.resolvedModule.extension))) { + // create different collection of failed lookup locations for second pass + // if it will fail and we've already found something during the first pass - we don't want to pollute its results + var _a = ts.loadModuleFromGlobalCache(moduleName, resolutionHost.projectName, compilerOptions, host, globalCache), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; + if (resolvedModule) { + return { resolvedModule: resolvedModule, failedLookupLocations: ts.addRange(primaryResult.failedLookupLocations, failedLookupLocations) }; + } + } + // Default return the result from the first pass + return primaryResult; + } + function resolveNamesWithLocalCache(names, containingFile, redirectedReference, cache, perDirectoryCacheWithRedirects, loader, getResolutionWithResolvedFileName, shouldRetryResolution, reusedNames, logChanges) { + var path = resolutionHost.toPath(containingFile); + var resolutionsInFile = cache.get(path) || cache.set(path, ts.createMap()).get(path); + var dirPath = ts.getDirectoryPath(path); + var perDirectoryCache = perDirectoryCacheWithRedirects.getOrCreateMapOfCacheRedirects(redirectedReference); + var perDirectoryResolution = perDirectoryCache.get(dirPath); + if (!perDirectoryResolution) { + perDirectoryResolution = ts.createMap(); + perDirectoryCache.set(dirPath, perDirectoryResolution); + } + var resolvedModules = []; + var compilerOptions = resolutionHost.getCompilationSettings(); + var hasInvalidatedNonRelativeUnresolvedImport = logChanges && isFileWithInvalidatedNonRelativeUnresolvedImports(path); + // All the resolutions in this file are invalidated if this file wasnt resolved using same redirect + var program = resolutionHost.getCurrentProgram(); + var oldRedirect = program && program.getResolvedProjectReferenceToRedirect(containingFile); + var unmatchedRedirects = oldRedirect ? + !redirectedReference || redirectedReference.sourceFile.path !== oldRedirect.sourceFile.path : + !!redirectedReference; + var seenNamesInFile = ts.createMap(); + for (var _i = 0, names_2 = names; _i < names_2.length; _i++) { + var name = names_2[_i]; + var resolution = resolutionsInFile.get(name); + // Resolution is valid if it is present and not invalidated + if (!seenNamesInFile.has(name) && + allFilesHaveInvalidatedResolution || unmatchedRedirects || !resolution || resolution.isInvalidated || + // If the name is unresolved import that was invalidated, recalculate + (hasInvalidatedNonRelativeUnresolvedImport && !ts.isExternalModuleNameRelative(name) && shouldRetryResolution(resolution))) { + var existingResolution = resolution; + var resolutionInDirectory = perDirectoryResolution.get(name); + if (resolutionInDirectory) { + resolution = resolutionInDirectory; + } + else { + resolution = loader(name, containingFile, compilerOptions, resolutionHost, redirectedReference); + perDirectoryResolution.set(name, resolution); + } + resolutionsInFile.set(name, resolution); + watchFailedLookupLocationsOfExternalModuleResolutions(name, resolution); + if (existingResolution) { + stopWatchFailedLookupLocationOfResolution(existingResolution); + } + if (logChanges && filesWithChangedSetOfUnresolvedImports && !resolutionIsEqualTo(existingResolution, resolution)) { + filesWithChangedSetOfUnresolvedImports.push(path); + // reset log changes to avoid recording the same file multiple times + logChanges = false; + } + } + ts.Debug.assert(resolution !== undefined && !resolution.isInvalidated); + seenNamesInFile.set(name, true); + resolvedModules.push(getResolutionWithResolvedFileName(resolution)); + } + // Stop watching and remove the unused name + resolutionsInFile.forEach(function (resolution, name) { + if (!seenNamesInFile.has(name) && !ts.contains(reusedNames, name)) { + stopWatchFailedLookupLocationOfResolution(resolution); + resolutionsInFile.delete(name); + } + }); + return resolvedModules; + function resolutionIsEqualTo(oldResolution, newResolution) { + if (oldResolution === newResolution) { + return true; + } + if (!oldResolution || !newResolution) { + return false; + } + var oldResult = getResolutionWithResolvedFileName(oldResolution); + var newResult = getResolutionWithResolvedFileName(newResolution); + if (oldResult === newResult) { + return true; + } + if (!oldResult || !newResult) { + return false; + } + return oldResult.resolvedFileName === newResult.resolvedFileName; + } + } + function resolveTypeReferenceDirectives(typeDirectiveNames, containingFile, redirectedReference) { + return resolveNamesWithLocalCache(typeDirectiveNames, containingFile, redirectedReference, resolvedTypeReferenceDirectives, perDirectoryResolvedTypeReferenceDirectives, ts.resolveTypeReferenceDirective, getResolvedTypeReferenceDirective, + /*shouldRetryResolution*/ function (resolution) { return resolution.resolvedTypeReferenceDirective === undefined; }, + /*reusedNames*/ undefined, /*logChanges*/ false); + } + function resolveModuleNames(moduleNames, containingFile, reusedNames, redirectedReference) { + return resolveNamesWithLocalCache(moduleNames, containingFile, redirectedReference, resolvedModuleNames, perDirectoryResolvedModuleNames, resolveModuleName, getResolvedModule, + /*shouldRetryResolution*/ function (resolution) { return !resolution.resolvedModule || !ts.resolutionExtensionIsTSOrJson(resolution.resolvedModule.extension); }, reusedNames, logChangesWhenResolvingModule); + } + function getResolvedModuleWithFailedLookupLocationsFromCache(moduleName, containingFile) { + var cache = resolvedModuleNames.get(resolutionHost.toPath(containingFile)); + return cache && cache.get(moduleName); + } + function isNodeModulesDirectory(dirPath) { + return ts.endsWith(dirPath, "/node_modules"); + } + function isNodeModulesAtTypesDirectory(dirPath) { + return ts.endsWith(dirPath, "/node_modules/@types"); + } + /** + * Filter out paths like + * "/", "/user", "/user/username", "/user/username/folderAtRoot", + * "c:/", "c:/users", "c:/users/username", "c:/users/username/folderAtRoot", "c:/folderAtRoot" + * @param dirPath + */ + function canWatchDirectory(dirPath) { + var rootLength = ts.getRootLength(dirPath); + if (dirPath.length === rootLength) { + // Ignore "/", "c:/" + return false; + } + var nextDirectorySeparator = dirPath.indexOf(ts.directorySeparator, rootLength); + if (nextDirectorySeparator === -1) { + // ignore "/user", "c:/users" or "c:/folderAtRoot" + return false; + } + if (dirPath.charCodeAt(0) !== 47 /* slash */ && + dirPath.substr(rootLength, nextDirectorySeparator).search(/users/i) === -1) { + // Paths like c:/folderAtRoot/subFolder are allowed + return true; + } + for (var searchIndex = nextDirectorySeparator + 1, searchLevels = 2; searchLevels > 0; searchLevels--) { + searchIndex = dirPath.indexOf(ts.directorySeparator, searchIndex) + 1; + if (searchIndex === 0) { + // Folder isnt at expected minimun levels + return false; + } + } + return true; + } + function getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath) { + if (isInDirectoryPath(rootPath, failedLookupLocationPath)) { + // Ensure failed look up is normalized path + failedLookupLocation = ts.isRootedDiskPath(failedLookupLocation) ? ts.normalizePath(failedLookupLocation) : ts.getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory()); + ts.Debug.assert(failedLookupLocation.length === failedLookupLocationPath.length, "FailedLookup: " + failedLookupLocation + " failedLookupLocationPath: " + failedLookupLocationPath); // tslint:disable-line + var subDirectoryInRoot = failedLookupLocationPath.indexOf(ts.directorySeparator, rootPath.length + 1); + if (subDirectoryInRoot !== -1) { + // Instead of watching root, watch directory in root to avoid watching excluded directories not needed for module resolution + return { dir: failedLookupLocation.substr(0, subDirectoryInRoot), dirPath: failedLookupLocationPath.substr(0, subDirectoryInRoot) }; + } + else { + // Always watch root directory non recursively + return { dir: rootDir, dirPath: rootPath, nonRecursive: false }; // TODO: GH#18217 + } + } + return getDirectoryToWatchFromFailedLookupLocationDirectory(ts.getDirectoryPath(ts.getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory())), ts.getDirectoryPath(failedLookupLocationPath)); + } + function getDirectoryToWatchFromFailedLookupLocationDirectory(dir, dirPath) { + // If directory path contains node module, get the most parent node_modules directory for watching + while (ts.pathContainsNodeModules(dirPath)) { + dir = ts.getDirectoryPath(dir); + dirPath = ts.getDirectoryPath(dirPath); + } + // If the directory is node_modules use it to watch, always watch it recursively + if (isNodeModulesDirectory(dirPath)) { + return canWatchDirectory(ts.getDirectoryPath(dirPath)) ? { dir: dir, dirPath: dirPath } : undefined; + } + var nonRecursive = true; + // Use some ancestor of the root directory + var subDirectoryPath, subDirectory; + if (rootPath !== undefined) { + while (!isInDirectoryPath(dirPath, rootPath)) { + var parentPath = ts.getDirectoryPath(dirPath); + if (parentPath === dirPath) { + break; + } + nonRecursive = false; + subDirectoryPath = dirPath; + subDirectory = dir; + dirPath = parentPath; + dir = ts.getDirectoryPath(dir); + } + } + return canWatchDirectory(dirPath) ? { dir: subDirectory || dir, dirPath: subDirectoryPath || dirPath, nonRecursive: nonRecursive } : undefined; + } + function isPathWithDefaultFailedLookupExtension(path) { + return ts.fileExtensionIsOneOf(path, failedLookupDefaultExtensions); + } + function watchFailedLookupLocationsOfExternalModuleResolutions(name, resolution) { + // No need to set the resolution refCount + if (resolution.failedLookupLocations && resolution.failedLookupLocations.length) { + if (resolution.refCount) { + resolution.refCount++; + } + else { + resolution.refCount = 1; + if (ts.isExternalModuleNameRelative(name)) { + watchFailedLookupLocationOfResolution(resolution); + } + else { + nonRelativeExternalModuleResolutions.add(name, resolution); + } + } + } + } + function watchFailedLookupLocationOfResolution(resolution) { + ts.Debug.assert(!!resolution.refCount); + var failedLookupLocations = resolution.failedLookupLocations; + var setAtRoot = false; + for (var _i = 0, failedLookupLocations_1 = failedLookupLocations; _i < failedLookupLocations_1.length; _i++) { + var failedLookupLocation = failedLookupLocations_1[_i]; + var failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation); + var toWatch = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath); + if (toWatch) { + var dir = toWatch.dir, dirPath = toWatch.dirPath, nonRecursive = toWatch.nonRecursive; + // If the failed lookup location path is not one of the supported extensions, + // store it in the custom path + if (!isPathWithDefaultFailedLookupExtension(failedLookupLocationPath)) { + var refCount = customFailedLookupPaths.get(failedLookupLocationPath) || 0; + customFailedLookupPaths.set(failedLookupLocationPath, refCount + 1); + } + if (dirPath === rootPath) { + ts.Debug.assert(!nonRecursive); + setAtRoot = true; + } + else { + setDirectoryWatcher(dir, dirPath, nonRecursive); + } + } + } + if (setAtRoot) { + // This is always non recursive + setDirectoryWatcher(rootDir, rootPath, /*nonRecursive*/ true); // TODO: GH#18217 + } + } + function setRefCountToUndefined(resolution) { + resolution.refCount = undefined; + } + function watchFailedLookupLocationOfNonRelativeModuleResolutions(resolutions, name) { + var program = resolutionHost.getCurrentProgram(); + var updateResolution = program && program.getTypeChecker().tryFindAmbientModuleWithoutAugmentations(name) ? + setRefCountToUndefined : watchFailedLookupLocationOfResolution; + resolutions.forEach(updateResolution); + } + function setDirectoryWatcher(dir, dirPath, nonRecursive) { + var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath); + if (dirWatcher) { + ts.Debug.assert(!!nonRecursive === !!dirWatcher.nonRecursive); + dirWatcher.refCount++; + } + else { + directoryWatchesOfFailedLookups.set(dirPath, { watcher: createDirectoryWatcher(dir, dirPath, nonRecursive), refCount: 1, nonRecursive: nonRecursive }); + } + } + function stopWatchFailedLookupLocationOfResolution(resolution) { + if (!resolution.refCount) { + return; + } + resolution.refCount--; + if (resolution.refCount) { + return; + } + var failedLookupLocations = resolution.failedLookupLocations; + var removeAtRoot = false; + for (var _i = 0, failedLookupLocations_2 = failedLookupLocations; _i < failedLookupLocations_2.length; _i++) { + var failedLookupLocation = failedLookupLocations_2[_i]; + var failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation); + var toWatch = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath); + if (toWatch) { + var dirPath = toWatch.dirPath; + var refCount = customFailedLookupPaths.get(failedLookupLocationPath); + if (refCount) { + if (refCount === 1) { + customFailedLookupPaths.delete(failedLookupLocationPath); + } + else { + ts.Debug.assert(refCount > 1); + customFailedLookupPaths.set(failedLookupLocationPath, refCount - 1); + } + } + if (dirPath === rootPath) { + removeAtRoot = true; + } + else { + removeDirectoryWatcher(dirPath); + } + } + } + if (removeAtRoot) { + removeDirectoryWatcher(rootPath); + } + } + function removeDirectoryWatcher(dirPath) { + var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath); + // Do not close the watcher yet since it might be needed by other failed lookup locations. + dirWatcher.refCount--; + } + function createDirectoryWatcher(directory, dirPath, nonRecursive) { + return resolutionHost.watchDirectoryOfFailedLookupLocation(directory, function (fileOrDirectory) { + var fileOrDirectoryPath = resolutionHost.toPath(fileOrDirectory); + if (cachedDirectoryStructureHost) { + // Since the file existence changed, update the sourceFiles cache + cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); + } + if (!allFilesHaveInvalidatedResolution && invalidateResolutionOfFailedLookupLocation(fileOrDirectoryPath, dirPath === fileOrDirectoryPath)) { + resolutionHost.onInvalidatedResolution(); + } + }, nonRecursive ? 0 /* None */ : 1 /* Recursive */); + } + function removeResolutionsOfFileFromCache(cache, filePath) { + // Deleted file, stop watching failed lookups for all the resolutions in the file + var resolutions = cache.get(filePath); + if (resolutions) { + resolutions.forEach(stopWatchFailedLookupLocationOfResolution); + cache.delete(filePath); + } + } + function removeResolutionsFromProjectReferenceRedirects(filePath) { + if (!ts.fileExtensionIs(filePath, ".json" /* Json */)) { + return; + } + var program = resolutionHost.getCurrentProgram(); + if (!program) { + return; + } + // If this file is input file for the referenced project, get it + var resolvedProjectReference = program.getResolvedProjectReferenceByPath(filePath); + if (!resolvedProjectReference) { + return; + } + // filePath is for the projectReference and the containing file is from this project reference, invalidate the resolution + resolvedProjectReference.commandLine.fileNames.forEach(function (f) { return removeResolutionsOfFile(resolutionHost.toPath(f)); }); + } + function removeResolutionsOfFile(filePath) { + removeResolutionsOfFileFromCache(resolvedModuleNames, filePath); + removeResolutionsOfFileFromCache(resolvedTypeReferenceDirectives, filePath); + } + function invalidateResolutionCache(cache, isInvalidatedResolution, getResolutionWithResolvedFileName) { + var seen = ts.createMap(); + cache.forEach(function (resolutions, containingFilePath) { + var dirPath = ts.getDirectoryPath(containingFilePath); + var seenInDir = seen.get(dirPath); + if (!seenInDir) { + seenInDir = ts.createMap(); + seen.set(dirPath, seenInDir); + } + resolutions.forEach(function (resolution, name) { + if (seenInDir.has(name)) { + return; + } + seenInDir.set(name, true); + if (!resolution.isInvalidated && isInvalidatedResolution(resolution, getResolutionWithResolvedFileName)) { + // Mark the file as needing re-evaluation of module resolution instead of using it blindly. + resolution.isInvalidated = true; + (filesWithInvalidatedResolutions || (filesWithInvalidatedResolutions = ts.createMap())).set(containingFilePath, true); + } + }); + }); + } + function hasReachedResolutionIterationLimit() { + var maxSize = resolutionHost.maxNumberOfFilesToIterateForInvalidation || ts.maxNumberOfFilesToIterateForInvalidation; + return resolvedModuleNames.size > maxSize || resolvedTypeReferenceDirectives.size > maxSize; + } + function invalidateResolutions(isInvalidatedResolution) { + // If more than maxNumberOfFilesToIterateForInvalidation present, + // just invalidated all files and recalculate the resolutions for files instead + if (hasReachedResolutionIterationLimit()) { + allFilesHaveInvalidatedResolution = true; + return; + } + invalidateResolutionCache(resolvedModuleNames, isInvalidatedResolution, getResolvedModule); + invalidateResolutionCache(resolvedTypeReferenceDirectives, isInvalidatedResolution, getResolvedTypeReferenceDirective); + } + function invalidateResolutionOfFile(filePath) { + removeResolutionsOfFile(filePath); + invalidateResolutions( + // Resolution is invalidated if the resulting file name is same as the deleted file path + function (resolution, getResolutionWithResolvedFileName) { + var result = getResolutionWithResolvedFileName(resolution); + return !!result && resolutionHost.toPath(result.resolvedFileName) === filePath; // TODO: GH#18217 + }); + } + function setFilesWithInvalidatedNonRelativeUnresolvedImports(filesMap) { + ts.Debug.assert(filesWithInvalidatedNonRelativeUnresolvedImports === filesMap || filesWithInvalidatedNonRelativeUnresolvedImports === undefined); + filesWithInvalidatedNonRelativeUnresolvedImports = filesMap; + } + function invalidateResolutionOfFailedLookupLocation(fileOrDirectoryPath, isCreatingWatchedDirectory) { + var isChangedFailedLookupLocation; + if (isCreatingWatchedDirectory) { + // Watching directory is created + // Invalidate any resolution has failed lookup in this directory + isChangedFailedLookupLocation = function (location) { return isInDirectoryPath(fileOrDirectoryPath, resolutionHost.toPath(location)); }; + } + else { + // If something to do with folder/file starting with "." in node_modules folder, skip it + if (isPathInNodeModulesStartingWithDot(fileOrDirectoryPath)) + return false; + // Some file or directory in the watching directory is created + // Return early if it does not have any of the watching extension or not the custom failed lookup path + var dirOfFileOrDirectory = ts.getDirectoryPath(fileOrDirectoryPath); + if (isNodeModulesAtTypesDirectory(fileOrDirectoryPath) || isNodeModulesDirectory(fileOrDirectoryPath) || + isNodeModulesAtTypesDirectory(dirOfFileOrDirectory) || isNodeModulesDirectory(dirOfFileOrDirectory)) { + // Invalidate any resolution from this directory + isChangedFailedLookupLocation = function (location) { + var locationPath = resolutionHost.toPath(location); + return locationPath === fileOrDirectoryPath || ts.startsWith(resolutionHost.toPath(location), fileOrDirectoryPath); + }; + } + else { + if (!isPathWithDefaultFailedLookupExtension(fileOrDirectoryPath) && !customFailedLookupPaths.has(fileOrDirectoryPath)) { + return false; + } + // Ignore emits from the program + if (ts.isEmittedFileOfProgram(resolutionHost.getCurrentProgram(), fileOrDirectoryPath)) { + return false; + } + // Resolution need to be invalidated if failed lookup location is same as the file or directory getting created + isChangedFailedLookupLocation = function (location) { return resolutionHost.toPath(location) === fileOrDirectoryPath; }; + } + } + var hasChangedFailedLookupLocation = function (resolution) { return ts.some(resolution.failedLookupLocations, isChangedFailedLookupLocation); }; + var invalidatedFilesCount = filesWithInvalidatedResolutions && filesWithInvalidatedResolutions.size; + invalidateResolutions( + // Resolution is invalidated if the resulting file name is same as the deleted file path + hasChangedFailedLookupLocation); + return allFilesHaveInvalidatedResolution || filesWithInvalidatedResolutions && filesWithInvalidatedResolutions.size !== invalidatedFilesCount; + } + function closeTypeRootsWatch() { + ts.clearMap(typeRootsWatches, ts.closeFileWatcher); + } + function getDirectoryToWatchFailedLookupLocationFromTypeRoot(typeRoot, typeRootPath) { + if (allFilesHaveInvalidatedResolution) { + return undefined; + } + if (isInDirectoryPath(rootPath, typeRootPath)) { + return rootPath; + } + var toWatch = getDirectoryToWatchFromFailedLookupLocationDirectory(typeRoot, typeRootPath); + return toWatch && directoryWatchesOfFailedLookups.has(toWatch.dirPath) ? toWatch.dirPath : undefined; + } + function createTypeRootsWatch(typeRootPath, typeRoot) { + // Create new watch and recursive info + return resolutionHost.watchTypeRootsDirectory(typeRoot, function (fileOrDirectory) { + var fileOrDirectoryPath = resolutionHost.toPath(fileOrDirectory); + if (cachedDirectoryStructureHost) { + // Since the file existence changed, update the sourceFiles cache + cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); + } + // For now just recompile + // We could potentially store more data here about whether it was/would be really be used or not + // and with that determine to trigger compilation but for now this is enough + resolutionHost.onChangedAutomaticTypeDirectiveNames(); + // Since directory watchers invoked are flaky, the failed lookup location events might not be triggered + // So handle to failed lookup locations here as well to ensure we are invalidating resolutions + var dirPath = getDirectoryToWatchFailedLookupLocationFromTypeRoot(typeRoot, typeRootPath); + if (dirPath && invalidateResolutionOfFailedLookupLocation(fileOrDirectoryPath, dirPath === fileOrDirectoryPath)) { + resolutionHost.onInvalidatedResolution(); + } + }, 1 /* Recursive */); + } + /** + * Watches the types that would get added as part of getAutomaticTypeDirectiveNames + * To be called when compiler options change + */ + function updateTypeRootsWatch() { + var options = resolutionHost.getCompilationSettings(); + if (options.types) { + // No need to do any watch since resolution cache is going to handle the failed lookups + // for the types added by this + closeTypeRootsWatch(); + return; + } + // we need to assume the directories exist to ensure that we can get all the type root directories that get included + // But filter directories that are at root level to say directory doesnt exist, so that we arent watching them + var typeRoots = ts.getEffectiveTypeRoots(options, { directoryExists: directoryExistsForTypeRootWatch, getCurrentDirectory: getCurrentDirectory }); + if (typeRoots) { + ts.mutateMap(typeRootsWatches, ts.arrayToMap(typeRoots, function (tr) { return resolutionHost.toPath(tr); }), { + createNewValue: createTypeRootsWatch, + onDeleteValue: ts.closeFileWatcher + }); + } + else { + closeTypeRootsWatch(); + } + } + /** + * Use this function to return if directory exists to get type roots to watch + * If we return directory exists then only the paths will be added to type roots + * Hence return true for all directories except root directories which are filtered from watching + */ + function directoryExistsForTypeRootWatch(nodeTypesDirectory) { + var dir = ts.getDirectoryPath(ts.getDirectoryPath(nodeTypesDirectory)); + var dirPath = resolutionHost.toPath(dir); + return dirPath === rootPath || canWatchDirectory(dirPath); + } + } + ts.createResolutionCache = createResolutionCache; +})(ts || (ts = {})); +// Used by importFixes, getEditsForFileRename, and declaration emit to synthesize import module specifiers. +/* @internal */ +var ts; +(function (ts) { + var moduleSpecifiers; + (function (moduleSpecifiers) { + var RelativePreference; + (function (RelativePreference) { + RelativePreference[RelativePreference["Relative"] = 0] = "Relative"; + RelativePreference[RelativePreference["NonRelative"] = 1] = "NonRelative"; + RelativePreference[RelativePreference["Auto"] = 2] = "Auto"; + })(RelativePreference || (RelativePreference = {})); + // See UserPreferences#importPathEnding + var Ending; + (function (Ending) { + Ending[Ending["Minimal"] = 0] = "Minimal"; + Ending[Ending["Index"] = 1] = "Index"; + Ending[Ending["JsExtension"] = 2] = "JsExtension"; + })(Ending || (Ending = {})); + function getPreferences(_a, compilerOptions, importingSourceFile) { + var importModuleSpecifierPreference = _a.importModuleSpecifierPreference, importModuleSpecifierEnding = _a.importModuleSpecifierEnding; + return { + relativePreference: importModuleSpecifierPreference === "relative" ? 0 /* Relative */ : importModuleSpecifierPreference === "non-relative" ? 1 /* NonRelative */ : 2 /* Auto */, + ending: getEnding(), + }; + function getEnding() { + switch (importModuleSpecifierEnding) { + case "minimal": return 0 /* Minimal */; + case "index": return 1 /* Index */; + case "js": return 2 /* JsExtension */; + default: return usesJsExtensionOnImports(importingSourceFile) ? 2 /* JsExtension */ + : ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.NodeJs ? 1 /* Index */ : 0 /* Minimal */; + } + } + } + function getPreferencesForUpdate(compilerOptions, oldImportSpecifier) { + return { + relativePreference: ts.isExternalModuleNameRelative(oldImportSpecifier) ? 0 /* Relative */ : 1 /* NonRelative */, + ending: ts.hasJSOrJsonFileExtension(oldImportSpecifier) ? 2 /* JsExtension */ + : ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.NodeJs || ts.endsWith(oldImportSpecifier, "index") ? 1 /* Index */ : 0 /* Minimal */, + }; + } + function updateModuleSpecifier(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, oldImportSpecifier) { + var res = getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, getPreferencesForUpdate(compilerOptions, oldImportSpecifier)); + if (res === oldImportSpecifier) + return undefined; + return res; + } + moduleSpecifiers.updateModuleSpecifier = updateModuleSpecifier; + // Note: importingSourceFile is just for usesJsExtensionOnImports + function getModuleSpecifier(compilerOptions, importingSourceFile, importingSourceFileName, toFileName, host, files, preferences, redirectTargetsMap) { + if (preferences === void 0) { preferences = {}; } + return getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, getPreferences(preferences, compilerOptions, importingSourceFile)); + } + moduleSpecifiers.getModuleSpecifier = getModuleSpecifier; + function getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, preferences) { + var info = getInfo(importingSourceFileName, host); + var modulePaths = getAllModulePaths(files, importingSourceFileName, toFileName, info.getCanonicalFileName, host, redirectTargetsMap); + return ts.firstDefined(modulePaths, function (moduleFileName) { return tryGetModuleNameAsNodeModule(moduleFileName, info, host, compilerOptions); }) || + getLocalModuleSpecifier(toFileName, info, compilerOptions, preferences); + } + // Returns an import for each symlink and for the realpath. + function getModuleSpecifiers(moduleSymbol, compilerOptions, importingSourceFile, host, files, userPreferences, redirectTargetsMap) { + var ambient = tryGetModuleNameFromAmbientModule(moduleSymbol); + if (ambient) + return [ambient]; + var info = getInfo(importingSourceFile.path, host); + var moduleSourceFile = ts.getSourceFileOfNode(moduleSymbol.valueDeclaration || ts.getNonAugmentationDeclaration(moduleSymbol)); + var modulePaths = getAllModulePaths(files, importingSourceFile.path, moduleSourceFile.fileName, info.getCanonicalFileName, host, redirectTargetsMap); + var preferences = getPreferences(userPreferences, compilerOptions, importingSourceFile); + var global = ts.mapDefined(modulePaths, function (moduleFileName) { return tryGetModuleNameAsNodeModule(moduleFileName, info, host, compilerOptions); }); + return global.length ? global : modulePaths.map(function (moduleFileName) { return getLocalModuleSpecifier(moduleFileName, info, compilerOptions, preferences); }); + } + moduleSpecifiers.getModuleSpecifiers = getModuleSpecifiers; + // importingSourceFileName is separate because getEditsForFileRename may need to specify an updated path + function getInfo(importingSourceFileName, host) { + var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames ? host.useCaseSensitiveFileNames() : true); + var sourceDirectory = ts.getDirectoryPath(importingSourceFileName); + return { getCanonicalFileName: getCanonicalFileName, sourceDirectory: sourceDirectory }; + } + function getLocalModuleSpecifier(moduleFileName, _a, compilerOptions, _b) { + var getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory; + var ending = _b.ending, relativePreference = _b.relativePreference; + var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths, rootDirs = compilerOptions.rootDirs; + var relativePath = rootDirs && tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName) || + removeExtensionAndIndexPostFix(ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, moduleFileName, getCanonicalFileName)), ending, compilerOptions); + if (!baseUrl || relativePreference === 0 /* Relative */) { + return relativePath; + } + var relativeToBaseUrl = getRelativePathIfInDirectory(moduleFileName, baseUrl, getCanonicalFileName); + if (!relativeToBaseUrl) { + return relativePath; + } + var importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, ending, compilerOptions); + var fromPaths = paths && tryGetModuleNameFromPaths(ts.removeFileExtension(relativeToBaseUrl), importRelativeToBaseUrl, paths); + var nonRelative = fromPaths === undefined ? importRelativeToBaseUrl : fromPaths; + if (relativePreference === 1 /* NonRelative */) { + return nonRelative; + } + if (relativePreference !== 2 /* Auto */) + ts.Debug.assertNever(relativePreference); + // Prefer a relative import over a baseUrl import if it has fewer components. + return isPathRelativeToParent(nonRelative) || countPathComponents(relativePath) < countPathComponents(nonRelative) ? relativePath : nonRelative; + } + function countPathComponents(path) { + var count = 0; + for (var i = ts.startsWith(path, "./") ? 2 : 0; i < path.length; i++) { + if (path.charCodeAt(i) === 47 /* slash */) + count++; + } + return count; + } + moduleSpecifiers.countPathComponents = countPathComponents; + function usesJsExtensionOnImports(_a) { + var imports = _a.imports; + return ts.firstDefined(imports, function (_a) { + var text = _a.text; + return ts.pathIsRelative(text) ? ts.hasJSOrJsonFileExtension(text) : undefined; + }) || false; + } + function stringsEqual(a, b, getCanonicalFileName) { + return getCanonicalFileName(a) === getCanonicalFileName(b); + } + // KLUDGE: Don't assume one 'node_modules' links to another. More likely a single directory inside the node_modules is the symlink. + // ALso, don't assume that an `@foo` directory is linked. More likely the contents of that are linked. + function isNodeModulesOrScopedPackageDirectory(s, getCanonicalFileName) { + return getCanonicalFileName(s) === "node_modules" || ts.startsWith(s, "@"); + } + function guessDirectorySymlink(a, b, cwd, getCanonicalFileName) { + var aParts = ts.getPathComponents(ts.toPath(a, cwd, getCanonicalFileName)); + var bParts = ts.getPathComponents(ts.toPath(b, cwd, getCanonicalFileName)); + while (!isNodeModulesOrScopedPackageDirectory(aParts[aParts.length - 2], getCanonicalFileName) && + !isNodeModulesOrScopedPackageDirectory(bParts[bParts.length - 2], getCanonicalFileName) && + stringsEqual(aParts[aParts.length - 1], bParts[bParts.length - 1], getCanonicalFileName)) { + aParts.pop(); + bParts.pop(); + } + return [ts.getPathFromPathComponents(aParts), ts.getPathFromPathComponents(bParts)]; + } + function discoverProbableSymlinks(files, getCanonicalFileName, cwd) { + var result = ts.createMap(); + var symlinks = ts.mapDefined(files, function (sf) { + return sf.resolvedModules && ts.firstDefinedIterator(sf.resolvedModules.values(), function (res) { + return res && res.originalPath && res.resolvedFileName !== res.originalPath ? [res.resolvedFileName, res.originalPath] : undefined; + }); + }); + for (var _i = 0, symlinks_1 = symlinks; _i < symlinks_1.length; _i++) { + var _a = symlinks_1[_i], resolvedPath = _a[0], originalPath = _a[1]; + var _b = guessDirectorySymlink(resolvedPath, originalPath, cwd, getCanonicalFileName), commonResolved = _b[0], commonOriginal = _b[1]; + result.set(commonOriginal, commonResolved); + } + return result; + } + /** + * Looks for existing imports that use symlinks to this module. + * Symlinks will be returned first so they are preferred over the real path. + */ + function getAllModulePaths(files, importingFileName, importedFileName, getCanonicalFileName, host, redirectTargetsMap) { + var redirects = redirectTargetsMap.get(importedFileName); + var importedFileNames = redirects ? redirects.concat([importedFileName]) : [importedFileName]; + var cwd = host.getCurrentDirectory ? host.getCurrentDirectory() : ""; + var targets = importedFileNames.map(function (f) { return ts.getNormalizedAbsolutePath(f, cwd); }); + var links = discoverProbableSymlinks(files, getCanonicalFileName, cwd); + var result = []; + var compareStrings = (!host.useCaseSensitiveFileNames || host.useCaseSensitiveFileNames()) ? ts.compareStringsCaseSensitive : ts.compareStringsCaseInsensitive; + links.forEach(function (resolved, path) { + if (ts.startsWithDirectory(importingFileName, resolved, getCanonicalFileName)) { + return; // Don't want to a package to globally import from itself + } + var target = targets.find(function (t) { return compareStrings(t.slice(0, resolved.length + 1), resolved + "/") === 0 /* EqualTo */; }); + if (target === undefined) + return; + var relative = ts.getRelativePathFromDirectory(resolved, target, getCanonicalFileName); + var option = ts.resolvePath(path, relative); + if (!host.fileExists || host.fileExists(option)) { + result.push(option); + } + }); + result.push.apply(result, targets); + return result; + } + function tryGetModuleNameFromAmbientModule(moduleSymbol) { + var decl = ts.find(moduleSymbol.declarations, function (d) { return ts.isNonGlobalAmbientModule(d) && (!ts.isExternalModuleAugmentation(d) || !ts.isExternalModuleNameRelative(ts.getTextOfIdentifierOrLiteral(d.name))); }); + if (decl) { + return decl.name.text; + } + } + function tryGetModuleNameFromPaths(relativeToBaseUrlWithIndex, relativeToBaseUrl, paths) { + for (var key in paths) { + for (var _i = 0, _a = paths[key]; _i < _a.length; _i++) { + var patternText_1 = _a[_i]; + var pattern = ts.removeFileExtension(ts.normalizePath(patternText_1)); + var indexOfStar = pattern.indexOf("*"); + if (indexOfStar !== -1) { + var prefix = pattern.substr(0, indexOfStar); + var suffix = pattern.substr(indexOfStar + 1); + if (relativeToBaseUrl.length >= prefix.length + suffix.length && + ts.startsWith(relativeToBaseUrl, prefix) && + ts.endsWith(relativeToBaseUrl, suffix) || + !suffix && relativeToBaseUrl === ts.removeTrailingDirectorySeparator(prefix)) { + var matchedStar = relativeToBaseUrl.substr(prefix.length, relativeToBaseUrl.length - suffix.length); + return key.replace("*", matchedStar); + } + } + else if (pattern === relativeToBaseUrl || pattern === relativeToBaseUrlWithIndex) { + return key; + } + } + } + } + function tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName) { + var normalizedTargetPath = getPathRelativeToRootDirs(moduleFileName, rootDirs, getCanonicalFileName); + if (normalizedTargetPath === undefined) { + return undefined; + } + var normalizedSourcePath = getPathRelativeToRootDirs(sourceDirectory, rootDirs, getCanonicalFileName); + var relativePath = normalizedSourcePath !== undefined ? ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(normalizedSourcePath, normalizedTargetPath, getCanonicalFileName)) : normalizedTargetPath; + return ts.removeFileExtension(relativePath); + } + function tryGetModuleNameAsNodeModule(moduleFileName, _a, host, options) { + var getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory; + if (!host.fileExists || !host.readFile) { + return undefined; + } + var parts = getNodeModulePathParts(moduleFileName); + if (!parts) { + return undefined; + } + var packageRootPath = moduleFileName.substring(0, parts.packageRootIndex); + var packageJsonPath = ts.combinePaths(packageRootPath, "package.json"); + var packageJsonContent = host.fileExists(packageJsonPath) + ? JSON.parse(host.readFile(packageJsonPath)) + : undefined; + var versionPaths = packageJsonContent && packageJsonContent.typesVersions + ? ts.getPackageJsonTypesVersionsPaths(packageJsonContent.typesVersions) + : undefined; + if (versionPaths) { + var subModuleName = moduleFileName.slice(parts.packageRootIndex + 1); + var fromPaths = tryGetModuleNameFromPaths(ts.removeFileExtension(subModuleName), removeExtensionAndIndexPostFix(subModuleName, 0 /* Minimal */, options), versionPaths.paths); + if (fromPaths !== undefined) { + moduleFileName = ts.combinePaths(moduleFileName.slice(0, parts.packageRootIndex), fromPaths); + } + } + // Simplify the full file path to something that can be resolved by Node. + // If the module could be imported by a directory name, use that directory's name + var moduleSpecifier = getDirectoryOrExtensionlessFileName(moduleFileName); + // Get a path that's relative to node_modules or the importing file's path + // if node_modules folder is in this folder or any of its parent folders, no need to keep it. + if (!ts.startsWith(sourceDirectory, getCanonicalFileName(moduleSpecifier.substring(0, parts.topLevelNodeModulesIndex)))) + return undefined; + // If the module was found in @types, get the actual Node package name + var nodeModulesDirectoryName = moduleSpecifier.substring(parts.topLevelPackageNameIndex + 1); + var packageName = ts.getPackageNameFromTypesPackageName(nodeModulesDirectoryName); + // For classic resolution, only allow importing from node_modules/@types, not other node_modules + return ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs && packageName === nodeModulesDirectoryName ? undefined : packageName; + function getDirectoryOrExtensionlessFileName(path) { + // If the file is the main module, it can be imported by the package name + if (packageJsonContent) { + var mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main; + if (mainFileRelative) { + var mainExportFile = ts.toPath(mainFileRelative, packageRootPath, getCanonicalFileName); + if (ts.removeFileExtension(mainExportFile) === ts.removeFileExtension(getCanonicalFileName(path))) { + return packageRootPath; + } + } + } + // We still have a file name - remove the extension + var fullModulePathWithoutExtension = ts.removeFileExtension(path); + // If the file is /index, it can be imported by its directory name + // IFF there is not _also_ a file by the same name + if (getCanonicalFileName(fullModulePathWithoutExtension.substring(parts.fileNameIndex)) === "/index" && !tryGetAnyFileFromPath(host, fullModulePathWithoutExtension.substring(0, parts.fileNameIndex))) { + return fullModulePathWithoutExtension.substring(0, parts.fileNameIndex); + } + return fullModulePathWithoutExtension; + } + } + function tryGetAnyFileFromPath(host, path) { + if (!host.fileExists) + return; + // We check all js, `node` and `json` extensions in addition to TS, since node module resolution would also choose those over the directory + var extensions = ts.getSupportedExtensions({ allowJs: true }, [{ extension: "node", isMixedContent: false }, { extension: "json", isMixedContent: false, scriptKind: 6 /* JSON */ }]); + for (var _i = 0, extensions_3 = extensions; _i < extensions_3.length; _i++) { + var e = extensions_3[_i]; + var fullPath = path + e; + if (host.fileExists(fullPath)) { + return fullPath; + } + } + } + function getNodeModulePathParts(fullPath) { + // If fullPath can't be valid module file within node_modules, returns undefined. + // Example of expected pattern: /base/path/node_modules/[@scope/otherpackage/@otherscope/node_modules/]package/[subdirectory/]file.js + // Returns indices: ^ ^ ^ ^ + var topLevelNodeModulesIndex = 0; + var topLevelPackageNameIndex = 0; + var packageRootIndex = 0; + var fileNameIndex = 0; + var States; + (function (States) { + States[States["BeforeNodeModules"] = 0] = "BeforeNodeModules"; + States[States["NodeModules"] = 1] = "NodeModules"; + States[States["Scope"] = 2] = "Scope"; + States[States["PackageContent"] = 3] = "PackageContent"; + })(States || (States = {})); + var partStart = 0; + var partEnd = 0; + var state = 0 /* BeforeNodeModules */; + while (partEnd >= 0) { + partStart = partEnd; + partEnd = fullPath.indexOf("/", partStart + 1); + switch (state) { + case 0 /* BeforeNodeModules */: + if (fullPath.indexOf(ts.nodeModulesPathPart, partStart) === partStart) { + topLevelNodeModulesIndex = partStart; + topLevelPackageNameIndex = partEnd; + state = 1 /* NodeModules */; + } + break; + case 1 /* NodeModules */: + case 2 /* Scope */: + if (state === 1 /* NodeModules */ && fullPath.charAt(partStart + 1) === "@") { + state = 2 /* Scope */; + } + else { + packageRootIndex = partEnd; + state = 3 /* PackageContent */; + } + break; + case 3 /* PackageContent */: + if (fullPath.indexOf(ts.nodeModulesPathPart, partStart) === partStart) { + state = 1 /* NodeModules */; + } + else { + state = 3 /* PackageContent */; + } + break; + } + } + fileNameIndex = partStart; + return state > 1 /* NodeModules */ ? { topLevelNodeModulesIndex: topLevelNodeModulesIndex, topLevelPackageNameIndex: topLevelPackageNameIndex, packageRootIndex: packageRootIndex, fileNameIndex: fileNameIndex } : undefined; + } + function getPathRelativeToRootDirs(path, rootDirs, getCanonicalFileName) { + return ts.firstDefined(rootDirs, function (rootDir) { + var relativePath = getRelativePathIfInDirectory(path, rootDir, getCanonicalFileName); // TODO: GH#18217 + return isPathRelativeToParent(relativePath) ? undefined : relativePath; + }); + } + function removeExtensionAndIndexPostFix(fileName, ending, options) { + if (ts.fileExtensionIs(fileName, ".json" /* Json */)) + return fileName; + var noExtension = ts.removeFileExtension(fileName); + switch (ending) { + case 0 /* Minimal */: + return ts.removeSuffix(noExtension, "/index"); + case 1 /* Index */: + return noExtension; + case 2 /* JsExtension */: + return noExtension + getJSExtensionForFile(fileName, options); + default: + return ts.Debug.assertNever(ending); + } + } + function getJSExtensionForFile(fileName, options) { + var ext = ts.extensionFromPath(fileName); + switch (ext) { + case ".ts" /* Ts */: + case ".d.ts" /* Dts */: + return ".js" /* Js */; + case ".tsx" /* Tsx */: + return options.jsx === 1 /* Preserve */ ? ".jsx" /* Jsx */ : ".js" /* Js */; + case ".js" /* Js */: + case ".jsx" /* Jsx */: + case ".json" /* Json */: + return ext; + default: + return ts.Debug.assertNever(ext); + } + } + function getRelativePathIfInDirectory(path, directoryPath, getCanonicalFileName) { + var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); + return ts.isRootedDiskPath(relativePath) ? undefined : relativePath; + } + function isPathRelativeToParent(path) { + return ts.startsWith(path, ".."); + } + })(moduleSpecifiers = ts.moduleSpecifiers || (ts.moduleSpecifiers = {})); +})(ts || (ts = {})); +/*@internal*/ +var ts; +(function (ts) { + var sysFormatDiagnosticsHost = ts.sys ? { + getCurrentDirectory: function () { return ts.sys.getCurrentDirectory(); }, + getNewLine: function () { return ts.sys.newLine; }, + getCanonicalFileName: ts.createGetCanonicalFileName(ts.sys.useCaseSensitiveFileNames) + } : undefined; // TODO: GH#18217 + /** + * Create a function that reports error by writing to the system and handles the formating of the diagnostic + */ + function createDiagnosticReporter(system, pretty) { + var host = system === ts.sys ? sysFormatDiagnosticsHost : { + getCurrentDirectory: function () { return system.getCurrentDirectory(); }, + getNewLine: function () { return system.newLine; }, + getCanonicalFileName: ts.createGetCanonicalFileName(system.useCaseSensitiveFileNames), + }; + if (!pretty) { + return function (diagnostic) { return system.write(ts.formatDiagnostic(diagnostic, host)); }; + } + var diagnostics = new Array(1); + return function (diagnostic) { + diagnostics[0] = diagnostic; + system.write(ts.formatDiagnosticsWithColorAndContext(diagnostics, host) + host.getNewLine()); + diagnostics[0] = undefined; // TODO: GH#18217 + }; + } + ts.createDiagnosticReporter = createDiagnosticReporter; + /** + * @returns Whether the screen was cleared. + */ + function clearScreenIfNotWatchingForFileChanges(system, diagnostic, options) { + if (system.clearScreen && + !options.preserveWatchOutput && + !options.extendedDiagnostics && + !options.diagnostics && + ts.contains(ts.screenStartingMessageCodes, diagnostic.code)) { + system.clearScreen(); + return true; + } + return false; + } + ts.screenStartingMessageCodes = [ + ts.Diagnostics.Starting_compilation_in_watch_mode.code, + ts.Diagnostics.File_change_detected_Starting_incremental_compilation.code, + ]; + function getPlainDiagnosticFollowingNewLines(diagnostic, newLine) { + return ts.contains(ts.screenStartingMessageCodes, diagnostic.code) + ? newLine + newLine + : newLine; + } + /** + * Create a function that reports watch status by writing to the system and handles the formating of the diagnostic + */ + function createWatchStatusReporter(system, pretty) { + return pretty ? + function (diagnostic, newLine, options) { + clearScreenIfNotWatchingForFileChanges(system, diagnostic, options); + var output = "[" + ts.formatColorAndReset(new Date().toLocaleTimeString(), ts.ForegroundColorEscapeSequences.Grey) + "] "; + output += "" + ts.flattenDiagnosticMessageText(diagnostic.messageText, system.newLine) + (newLine + newLine); + system.write(output); + } : + function (diagnostic, newLine, options) { + var output = ""; + if (!clearScreenIfNotWatchingForFileChanges(system, diagnostic, options)) { + output += newLine; + } + output += new Date().toLocaleTimeString() + " - "; + output += "" + ts.flattenDiagnosticMessageText(diagnostic.messageText, system.newLine) + getPlainDiagnosticFollowingNewLines(diagnostic, newLine); + system.write(output); + }; + } + ts.createWatchStatusReporter = createWatchStatusReporter; + /** Parses config file using System interface */ + function parseConfigFileWithSystem(configFileName, optionsToExtend, system, reportDiagnostic) { + var host = system; + host.onUnRecoverableConfigFileDiagnostic = function (diagnostic) { return reportUnrecoverableDiagnostic(ts.sys, reportDiagnostic, diagnostic); }; + var result = ts.getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host); + host.onUnRecoverableConfigFileDiagnostic = undefined; // TODO: GH#18217 + return result; + } + ts.parseConfigFileWithSystem = parseConfigFileWithSystem; + function getErrorCountForSummary(diagnostics) { + return ts.countWhere(diagnostics, function (diagnostic) { return diagnostic.category === ts.DiagnosticCategory.Error; }); + } + ts.getErrorCountForSummary = getErrorCountForSummary; + function getWatchErrorSummaryDiagnosticMessage(errorCount) { + return errorCount === 1 ? + ts.Diagnostics.Found_1_error_Watching_for_file_changes : + ts.Diagnostics.Found_0_errors_Watching_for_file_changes; + } + ts.getWatchErrorSummaryDiagnosticMessage = getWatchErrorSummaryDiagnosticMessage; + function getErrorSummaryText(errorCount, newLine) { + if (errorCount === 0) + return ""; + var d = ts.createCompilerDiagnostic(errorCount === 1 ? ts.Diagnostics.Found_1_error : ts.Diagnostics.Found_0_errors, errorCount); + return "" + newLine + ts.flattenDiagnosticMessageText(d.messageText, newLine) + newLine + newLine; + } + ts.getErrorSummaryText = getErrorSummaryText; + /** + * Helper that emit files, report diagnostics and lists emitted and/or source files depending on compiler options + */ + function emitFilesAndReportErrors(program, reportDiagnostic, writeFileName, reportSummary, writeFile) { + // First get and report any syntactic errors. + var diagnostics = program.getConfigFileParsingDiagnostics().slice(); + var configFileParsingDiagnosticsLength = diagnostics.length; + ts.addRange(diagnostics, program.getSyntacticDiagnostics()); + var reportSemanticDiagnostics = false; + // If we didn't have any syntactic errors, then also try getting the global and + // semantic errors. + if (diagnostics.length === configFileParsingDiagnosticsLength) { + ts.addRange(diagnostics, program.getOptionsDiagnostics()); + ts.addRange(diagnostics, program.getGlobalDiagnostics()); + if (diagnostics.length === configFileParsingDiagnosticsLength) { + reportSemanticDiagnostics = true; + } + } + // Emit and report any errors we ran into. + var _a = program.emit(/*targetSourceFile*/ undefined, writeFile), emittedFiles = _a.emittedFiles, emitSkipped = _a.emitSkipped, emitDiagnostics = _a.diagnostics; + ts.addRange(diagnostics, emitDiagnostics); + if (reportSemanticDiagnostics) { + ts.addRange(diagnostics, program.getSemanticDiagnostics()); + } + ts.sortAndDeduplicateDiagnostics(diagnostics).forEach(reportDiagnostic); + if (writeFileName) { + var currentDir_1 = program.getCurrentDirectory(); + ts.forEach(emittedFiles, function (file) { + var filepath = ts.getNormalizedAbsolutePath(file, currentDir_1); + writeFileName("TSFILE: " + filepath); + }); + if (program.getCompilerOptions().listFiles) { + ts.forEach(program.getSourceFiles(), function (file) { + writeFileName(file.fileName); + }); + } + } + if (reportSummary) { + reportSummary(getErrorCountForSummary(diagnostics)); + } + if (emitSkipped && diagnostics.length > 0) { + // If the emitter didn't emit anything, then pass that value along. + return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; + } + else if (diagnostics.length > 0) { + // The emitter emitted something, inform the caller if that happened in the presence + // of diagnostics or not. + return ts.ExitStatus.DiagnosticsPresent_OutputsGenerated; + } + return ts.ExitStatus.Success; + } + ts.emitFilesAndReportErrors = emitFilesAndReportErrors; + var noopFileWatcher = { close: ts.noop }; + function createWatchHost(system, reportWatchStatus) { + if (system === void 0) { system = ts.sys; } + var onWatchStatusChange = reportWatchStatus || createWatchStatusReporter(system); + return { + onWatchStatusChange: onWatchStatusChange, + watchFile: system.watchFile ? (function (path, callback, pollingInterval) { return system.watchFile(path, callback, pollingInterval); }) : function () { return noopFileWatcher; }, + watchDirectory: system.watchDirectory ? (function (path, callback, recursive) { return system.watchDirectory(path, callback, recursive); }) : function () { return noopFileWatcher; }, + setTimeout: system.setTimeout ? (function (callback, ms) { + var args = []; + for (var _i = 2; _i < arguments.length; _i++) { + args[_i - 2] = arguments[_i]; + } + var _a; + return (_a = system.setTimeout).call.apply(_a, [system, callback, ms].concat(args)); + }) : ts.noop, + clearTimeout: system.clearTimeout ? (function (timeoutId) { return system.clearTimeout(timeoutId); }) : ts.noop + }; + } + ts.createWatchHost = createWatchHost; + /** + * Creates the watch compiler host that can be extended with config file or root file names and options host + */ + function createWatchCompilerHost(system, createProgram, reportDiagnostic, reportWatchStatus) { + if (system === void 0) { system = ts.sys; } + if (!createProgram) { + createProgram = ts.createEmitAndSemanticDiagnosticsBuilderProgram; + } + var host = system; + host; // tslint:disable-line no-unused-expression (TODO: `host` is unused!) + var useCaseSensitiveFileNames = function () { return system.useCaseSensitiveFileNames; }; + var writeFileName = function (s) { return system.write(s + system.newLine); }; + var _a = createWatchHost(system, reportWatchStatus), onWatchStatusChange = _a.onWatchStatusChange, watchFile = _a.watchFile, watchDirectory = _a.watchDirectory, setTimeout = _a.setTimeout, clearTimeout = _a.clearTimeout; + return { + useCaseSensitiveFileNames: useCaseSensitiveFileNames, + getNewLine: function () { return system.newLine; }, + getCurrentDirectory: function () { return system.getCurrentDirectory(); }, + getDefaultLibLocation: getDefaultLibLocation, + getDefaultLibFileName: function (options) { return ts.combinePaths(getDefaultLibLocation(), ts.getDefaultLibFileName(options)); }, + fileExists: function (path) { return system.fileExists(path); }, + readFile: function (path, encoding) { return system.readFile(path, encoding); }, + directoryExists: function (path) { return system.directoryExists(path); }, + getDirectories: function (path) { return system.getDirectories(path); }, + readDirectory: function (path, extensions, exclude, include, depth) { return system.readDirectory(path, extensions, exclude, include, depth); }, + realpath: system.realpath && (function (path) { return system.realpath(path); }), + getEnvironmentVariable: system.getEnvironmentVariable && (function (name) { return system.getEnvironmentVariable(name); }), + watchFile: watchFile, + watchDirectory: watchDirectory, + setTimeout: setTimeout, + clearTimeout: clearTimeout, + trace: function (s) { return system.write(s); }, + onWatchStatusChange: onWatchStatusChange, + createDirectory: function (path) { return system.createDirectory(path); }, + writeFile: function (path, data, writeByteOrderMark) { return system.writeFile(path, data, writeByteOrderMark); }, + onCachedDirectoryStructureHostCreate: function (cacheHost) { return host = cacheHost || system; }, + createHash: system.createHash && (function (s) { return system.createHash(s); }), + createProgram: createProgram, + afterProgramCreate: emitFilesAndReportErrorUsingBuilder + }; + function getDefaultLibLocation() { + return ts.getDirectoryPath(ts.normalizePath(system.getExecutingFilePath())); + } + function emitFilesAndReportErrorUsingBuilder(builderProgram) { + var compilerOptions = builderProgram.getCompilerOptions(); + var newLine = ts.getNewLineCharacter(compilerOptions, function () { return system.newLine; }); + emitFilesAndReportErrors(builderProgram, reportDiagnostic, writeFileName, function (errorCount) { return onWatchStatusChange(ts.createCompilerDiagnostic(getWatchErrorSummaryDiagnosticMessage(errorCount), errorCount), newLine, compilerOptions); }); + } + } + /** + * Report error and exit + */ + function reportUnrecoverableDiagnostic(system, reportDiagnostic, diagnostic) { + reportDiagnostic(diagnostic); + system.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); + } + /** + * Creates the watch compiler host from system for config file in watch mode + */ + function createWatchCompilerHostOfConfigFile(configFileName, optionsToExtend, system, createProgram, reportDiagnostic, reportWatchStatus) { + var diagnosticReporter = reportDiagnostic || createDiagnosticReporter(system); + var host = createWatchCompilerHost(system, createProgram, diagnosticReporter, reportWatchStatus); + host.onUnRecoverableConfigFileDiagnostic = function (diagnostic) { return reportUnrecoverableDiagnostic(system, diagnosticReporter, diagnostic); }; + host.configFileName = configFileName; + host.optionsToExtend = optionsToExtend; + return host; + } + ts.createWatchCompilerHostOfConfigFile = createWatchCompilerHostOfConfigFile; + /** + * Creates the watch compiler host from system for compiling root files and options in watch mode + */ + function createWatchCompilerHostOfFilesAndCompilerOptions(rootFiles, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences) { + var host = createWatchCompilerHost(system, createProgram, reportDiagnostic || createDiagnosticReporter(system), reportWatchStatus); + host.rootFiles = rootFiles; + host.options = options; + host.projectReferences = projectReferences; + return host; + } + ts.createWatchCompilerHostOfFilesAndCompilerOptions = createWatchCompilerHostOfFilesAndCompilerOptions; +})(ts || (ts = {})); +(function (ts) { + function createWatchCompilerHost(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences) { + if (ts.isArray(rootFilesOrConfigFileName)) { + return ts.createWatchCompilerHostOfFilesAndCompilerOptions(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences); // TODO: GH#18217 + } + else { + return ts.createWatchCompilerHostOfConfigFile(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus); + } + } + ts.createWatchCompilerHost = createWatchCompilerHost; + var initialVersion = 1; + function createWatchProgram(host) { + var builderProgram; + var reloadLevel; // level to indicate if the program needs to be reloaded from config file/just filenames etc + var missingFilesMap; // Map of file watchers for the missing files + var watchedWildcardDirectories; // map of watchers for the wild card directories in the config file + var timerToUpdateProgram; // timer callback to recompile the program + var sourceFilesCache = ts.createMap(); // Cache that stores the source file and version info + var missingFilePathsRequestedForRelease; // These paths are held temparirly so that we can remove the entry from source file cache if the file is not tracked by missing files + var hasChangedCompilerOptions = false; // True if the compiler options have changed between compilations + var hasChangedAutomaticTypeDirectiveNames = false; // True if the automatic type directives have changed + var useCaseSensitiveFileNames = host.useCaseSensitiveFileNames(); + var currentDirectory = host.getCurrentDirectory(); + var getCurrentDirectory = function () { return currentDirectory; }; + var readFile = function (path, encoding) { return host.readFile(path, encoding); }; + var configFileName = host.configFileName, _a = host.optionsToExtend, optionsToExtendForConfigFile = _a === void 0 ? {} : _a, createProgram = host.createProgram; + var rootFileNames = host.rootFiles, compilerOptions = host.options, projectReferences = host.projectReferences; + var configFileSpecs; + var configFileParsingDiagnostics; + var canConfigFileJsonReportNoInputFiles = false; + var hasChangedConfigFileParsingErrors = false; + var cachedDirectoryStructureHost = configFileName === undefined ? undefined : ts.createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensitiveFileNames); + if (cachedDirectoryStructureHost && host.onCachedDirectoryStructureHostCreate) { + host.onCachedDirectoryStructureHostCreate(cachedDirectoryStructureHost); + } + var directoryStructureHost = cachedDirectoryStructureHost || host; + var parseConfigFileHost = { + useCaseSensitiveFileNames: useCaseSensitiveFileNames, + readDirectory: function (path, extensions, exclude, include, depth) { return directoryStructureHost.readDirectory(path, extensions, exclude, include, depth); }, + fileExists: function (path) { return host.fileExists(path); }, + readFile: readFile, + getCurrentDirectory: getCurrentDirectory, + onUnRecoverableConfigFileDiagnostic: host.onUnRecoverableConfigFileDiagnostic, + trace: host.trace ? function (s) { return host.trace(s); } : undefined + }; + // From tsc we want to get already parsed result and hence check for rootFileNames + var newLine = updateNewLine(); + if (configFileName && host.configFileParsingResult) { + setConfigFileParsingResult(host.configFileParsingResult); + newLine = updateNewLine(); + } + reportWatchDiagnostic(ts.Diagnostics.Starting_compilation_in_watch_mode); + if (configFileName && !host.configFileParsingResult) { + newLine = ts.getNewLineCharacter(optionsToExtendForConfigFile, function () { return host.getNewLine(); }); + ts.Debug.assert(!rootFileNames); + parseConfigFile(); + newLine = updateNewLine(); + } + var trace = host.trace && (function (s) { host.trace(s + newLine); }); + var watchLogLevel = trace ? compilerOptions.extendedDiagnostics ? ts.WatchLogLevel.Verbose : + compilerOptions.diagnostics ? ts.WatchLogLevel.TriggerOnly : ts.WatchLogLevel.None : ts.WatchLogLevel.None; + var writeLog = watchLogLevel !== ts.WatchLogLevel.None ? trace : ts.noop; // TODO: GH#18217 + var _b = ts.getWatchFactory(watchLogLevel, writeLog), watchFile = _b.watchFile, watchFilePath = _b.watchFilePath, watchDirectory = _b.watchDirectory; + var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); + writeLog("Current directory: " + currentDirectory + " CaseSensitiveFileNames: " + useCaseSensitiveFileNames); + if (configFileName) { + watchFile(host, configFileName, scheduleProgramReload, ts.PollingInterval.High, "Config file"); + } + var compilerHost = { + // Members for CompilerHost + getSourceFile: function (fileName, languageVersion, onError, shouldCreateNewSourceFile) { return getVersionedSourceFileByPath(fileName, toPath(fileName), languageVersion, onError, shouldCreateNewSourceFile); }, + getSourceFileByPath: getVersionedSourceFileByPath, + getDefaultLibLocation: host.getDefaultLibLocation && (function () { return host.getDefaultLibLocation(); }), + getDefaultLibFileName: function (options) { return host.getDefaultLibFileName(options); }, + writeFile: writeFile, + getCurrentDirectory: getCurrentDirectory, + useCaseSensitiveFileNames: function () { return useCaseSensitiveFileNames; }, + getCanonicalFileName: getCanonicalFileName, + getNewLine: function () { return newLine; }, + fileExists: fileExists, + readFile: readFile, + trace: trace, + directoryExists: directoryStructureHost.directoryExists && (function (path) { return directoryStructureHost.directoryExists(path); }), + getDirectories: (directoryStructureHost.getDirectories && (function (path) { return directoryStructureHost.getDirectories(path); })), + realpath: host.realpath && (function (s) { return host.realpath(s); }), + getEnvironmentVariable: host.getEnvironmentVariable ? (function (name) { return host.getEnvironmentVariable(name); }) : (function () { return ""; }), + onReleaseOldSourceFile: onReleaseOldSourceFile, + createHash: host.createHash && (function (data) { return host.createHash(data); }), + // Members for ResolutionCacheHost + toPath: toPath, + getCompilationSettings: function () { return compilerOptions; }, + watchDirectoryOfFailedLookupLocation: function (dir, cb, flags) { return watchDirectory(host, dir, cb, flags, "Failed Lookup Locations"); }, + watchTypeRootsDirectory: function (dir, cb, flags) { return watchDirectory(host, dir, cb, flags, "Type roots"); }, + getCachedDirectoryStructureHost: function () { return cachedDirectoryStructureHost; }, + onInvalidatedResolution: scheduleProgramUpdate, + onChangedAutomaticTypeDirectiveNames: function () { + hasChangedAutomaticTypeDirectiveNames = true; + scheduleProgramUpdate(); + }, + maxNumberOfFilesToIterateForInvalidation: host.maxNumberOfFilesToIterateForInvalidation, + getCurrentProgram: getCurrentProgram, + writeLog: writeLog, + readDirectory: function (path, extensions, exclude, include, depth) { return directoryStructureHost.readDirectory(path, extensions, exclude, include, depth); }, + }; + // Cache for the module resolution + var resolutionCache = ts.createResolutionCache(compilerHost, configFileName ? + ts.getDirectoryPath(ts.getNormalizedAbsolutePath(configFileName, currentDirectory)) : + currentDirectory, + /*logChangesWhenResolvingModule*/ false); + // Resolve module using host module resolution strategy if provided otherwise use resolution cache to resolve module names + compilerHost.resolveModuleNames = host.resolveModuleNames ? + (function (moduleNames, containingFile, reusedNames, redirectedReference) { return host.resolveModuleNames(moduleNames, containingFile, reusedNames, redirectedReference); }) : + (function (moduleNames, containingFile, reusedNames, redirectedReference) { return resolutionCache.resolveModuleNames(moduleNames, containingFile, reusedNames, redirectedReference); }); + compilerHost.resolveTypeReferenceDirectives = host.resolveTypeReferenceDirectives ? + (function (typeDirectiveNames, containingFile, redirectedReference) { return host.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile, redirectedReference); }) : + (function (typeDirectiveNames, containingFile, redirectedReference) { return resolutionCache.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile, redirectedReference); }); + var userProvidedResolution = !!host.resolveModuleNames || !!host.resolveTypeReferenceDirectives; + synchronizeProgram(); + // Update the wild card directory watch + watchConfigFileWildCardDirectories(); + return configFileName ? + { getCurrentProgram: getCurrentBuilderProgram, getProgram: synchronizeProgram } : + { getCurrentProgram: getCurrentBuilderProgram, getProgram: synchronizeProgram, updateRootFileNames: updateRootFileNames }; + function getCurrentBuilderProgram() { + return builderProgram; + } + function getCurrentProgram() { + return builderProgram && builderProgram.getProgram(); + } + function synchronizeProgram() { + writeLog("Synchronizing program"); + var program = getCurrentProgram(); + if (hasChangedCompilerOptions) { + newLine = updateNewLine(); + if (program && ts.changesAffectModuleResolution(program.getCompilerOptions(), compilerOptions)) { + resolutionCache.clear(); + } + } + // All resolutions are invalid if user provided resolutions + var hasInvalidatedResolution = resolutionCache.createHasInvalidatedResolution(userProvidedResolution); + if (ts.isProgramUptoDate(getCurrentProgram(), rootFileNames, compilerOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, projectReferences)) { + if (hasChangedConfigFileParsingErrors) { + builderProgram = createProgram(/*rootNames*/ undefined, /*options*/ undefined, compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences); + hasChangedConfigFileParsingErrors = false; + } + } + else { + createNewProgram(program, hasInvalidatedResolution); + } + if (host.afterProgramCreate) { + host.afterProgramCreate(builderProgram); + } + return builderProgram; + } + function createNewProgram(program, hasInvalidatedResolution) { + // Compile the program + if (watchLogLevel !== ts.WatchLogLevel.None) { + writeLog("CreatingProgramWith::"); + writeLog(" roots: " + JSON.stringify(rootFileNames)); + writeLog(" options: " + JSON.stringify(compilerOptions)); + } + var needsUpdateInTypeRootWatch = hasChangedCompilerOptions || !program; + hasChangedCompilerOptions = false; + hasChangedConfigFileParsingErrors = false; + resolutionCache.startCachingPerDirectoryResolution(); + compilerHost.hasInvalidatedResolution = hasInvalidatedResolution; + compilerHost.hasChangedAutomaticTypeDirectiveNames = hasChangedAutomaticTypeDirectiveNames; + builderProgram = createProgram(rootFileNames, compilerOptions, compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences); + resolutionCache.finishCachingPerDirectoryResolution(); + // Update watches + ts.updateMissingFilePathsWatch(builderProgram.getProgram(), missingFilesMap || (missingFilesMap = ts.createMap()), watchMissingFilePath); + if (needsUpdateInTypeRootWatch) { + resolutionCache.updateTypeRootsWatch(); + } + if (missingFilePathsRequestedForRelease) { + // These are the paths that program creater told us as not in use any more but were missing on the disk. + // We didnt remove the entry for them from sourceFiles cache so that we dont have to do File IO, + // if there is already watcher for it (for missing files) + // At this point our watches were updated, hence now we know that these paths are not tracked and need to be removed + // so that at later time we have correct result of their presence + for (var _i = 0, missingFilePathsRequestedForRelease_1 = missingFilePathsRequestedForRelease; _i < missingFilePathsRequestedForRelease_1.length; _i++) { + var missingFilePath = missingFilePathsRequestedForRelease_1[_i]; + if (!missingFilesMap.has(missingFilePath)) { + sourceFilesCache.delete(missingFilePath); + } + } + missingFilePathsRequestedForRelease = undefined; + } + } + function updateRootFileNames(files) { + ts.Debug.assert(!configFileName, "Cannot update root file names with config file watch mode"); + rootFileNames = files; + scheduleProgramUpdate(); + } + function updateNewLine() { + return ts.getNewLineCharacter(compilerOptions || optionsToExtendForConfigFile, function () { return host.getNewLine(); }); + } + function toPath(fileName) { + return ts.toPath(fileName, currentDirectory, getCanonicalFileName); + } + function isFileMissingOnHost(hostSourceFile) { + return typeof hostSourceFile === "number"; + } + function isFilePresentOnHost(hostSourceFile) { + return !!hostSourceFile.sourceFile; + } + function fileExists(fileName) { + var path = toPath(fileName); + // If file is missing on host from cache, we can definitely say file doesnt exist + // otherwise we need to ensure from the disk + if (isFileMissingOnHost(sourceFilesCache.get(path))) { + return true; + } + return directoryStructureHost.fileExists(fileName); + } + function getVersionedSourceFileByPath(fileName, path, languageVersion, onError, shouldCreateNewSourceFile) { + var hostSourceFile = sourceFilesCache.get(path); + // No source file on the host + if (isFileMissingOnHost(hostSourceFile)) { + return undefined; + } + // Create new source file if requested or the versions dont match + if (!hostSourceFile || shouldCreateNewSourceFile || !isFilePresentOnHost(hostSourceFile) || hostSourceFile.version.toString() !== hostSourceFile.sourceFile.version) { + var sourceFile = getNewSourceFile(); + if (hostSourceFile) { + if (shouldCreateNewSourceFile) { + hostSourceFile.version++; + } + if (sourceFile) { + // Set the source file and create file watcher now that file was present on the disk + hostSourceFile.sourceFile = sourceFile; + sourceFile.version = hostSourceFile.version.toString(); + if (!hostSourceFile.fileWatcher) { + hostSourceFile.fileWatcher = watchFilePath(host, fileName, onSourceFileChange, ts.PollingInterval.Low, path, "Source file"); + } + } + else { + // There is no source file on host any more, close the watch, missing file paths will track it + if (isFilePresentOnHost(hostSourceFile)) { + hostSourceFile.fileWatcher.close(); + } + sourceFilesCache.set(path, hostSourceFile.version); + } + } + else { + if (sourceFile) { + sourceFile.version = initialVersion.toString(); + var fileWatcher = watchFilePath(host, fileName, onSourceFileChange, ts.PollingInterval.Low, path, "Source file"); + sourceFilesCache.set(path, { sourceFile: sourceFile, version: initialVersion, fileWatcher: fileWatcher }); + } + else { + sourceFilesCache.set(path, initialVersion); + } + } + return sourceFile; + } + return hostSourceFile.sourceFile; + function getNewSourceFile() { + var text; + try { + ts.performance.mark("beforeIORead"); + text = host.readFile(fileName, compilerOptions.charset); + ts.performance.mark("afterIORead"); + ts.performance.measure("I/O Read", "beforeIORead", "afterIORead"); + } + catch (e) { + if (onError) { + onError(e.message); + } + } + return text !== undefined ? ts.createSourceFile(fileName, text, languageVersion) : undefined; + } + } + function nextSourceFileVersion(path) { + var hostSourceFile = sourceFilesCache.get(path); + if (hostSourceFile !== undefined) { + if (isFileMissingOnHost(hostSourceFile)) { + // The next version, lets set it as presence unknown file + sourceFilesCache.set(path, { version: Number(hostSourceFile) + 1 }); + } + else { + hostSourceFile.version++; + } + } + } + function getSourceVersion(path) { + var hostSourceFile = sourceFilesCache.get(path); + return !hostSourceFile || isFileMissingOnHost(hostSourceFile) ? undefined : hostSourceFile.version.toString(); + } + function onReleaseOldSourceFile(oldSourceFile, _oldOptions, hasSourceFileByPath) { + var hostSourceFileInfo = sourceFilesCache.get(oldSourceFile.resolvedPath); + // If this is the source file thats in the cache and new program doesnt need it, + // remove the cached entry. + // Note we arent deleting entry if file became missing in new program or + // there was version update and new source file was created. + if (hostSourceFileInfo) { + // record the missing file paths so they can be removed later if watchers arent tracking them + if (isFileMissingOnHost(hostSourceFileInfo)) { + (missingFilePathsRequestedForRelease || (missingFilePathsRequestedForRelease = [])).push(oldSourceFile.path); + } + else if (hostSourceFileInfo.sourceFile === oldSourceFile) { + if (hostSourceFileInfo.fileWatcher) { + hostSourceFileInfo.fileWatcher.close(); + } + sourceFilesCache.delete(oldSourceFile.resolvedPath); + if (!hasSourceFileByPath) { + resolutionCache.removeResolutionsOfFile(oldSourceFile.path); + } + } + } + } + function reportWatchDiagnostic(message) { + if (host.onWatchStatusChange) { + host.onWatchStatusChange(ts.createCompilerDiagnostic(message), newLine, compilerOptions || optionsToExtendForConfigFile); + } + } + // Upon detecting a file change, wait for 250ms and then perform a recompilation. This gives batch + // operations (such as saving all modified files in an editor) a chance to complete before we kick + // off a new compilation. + function scheduleProgramUpdate() { + if (!host.setTimeout || !host.clearTimeout) { + return; + } + if (timerToUpdateProgram) { + host.clearTimeout(timerToUpdateProgram); + } + writeLog("Scheduling update"); + timerToUpdateProgram = host.setTimeout(updateProgram, 250); + } + function scheduleProgramReload() { + ts.Debug.assert(!!configFileName); + reloadLevel = ts.ConfigFileProgramReloadLevel.Full; + scheduleProgramUpdate(); + } + function updateProgram() { + timerToUpdateProgram = undefined; + reportWatchDiagnostic(ts.Diagnostics.File_change_detected_Starting_incremental_compilation); + switch (reloadLevel) { + case ts.ConfigFileProgramReloadLevel.Partial: + return reloadFileNamesFromConfigFile(); + case ts.ConfigFileProgramReloadLevel.Full: + return reloadConfigFile(); + default: + synchronizeProgram(); + return; + } + } + function reloadFileNamesFromConfigFile() { + writeLog("Reloading new file names and options"); + var result = ts.getFileNamesFromConfigSpecs(configFileSpecs, ts.getDirectoryPath(configFileName), compilerOptions, parseConfigFileHost); + if (ts.updateErrorForNoInputFiles(result, configFileName, configFileSpecs, configFileParsingDiagnostics, canConfigFileJsonReportNoInputFiles)) { + hasChangedConfigFileParsingErrors = true; + } + rootFileNames = result.fileNames; + // Update the program + synchronizeProgram(); + } + function reloadConfigFile() { + writeLog("Reloading config file: " + configFileName); + reloadLevel = ts.ConfigFileProgramReloadLevel.None; + if (cachedDirectoryStructureHost) { + cachedDirectoryStructureHost.clearCache(); + } + parseConfigFile(); + hasChangedCompilerOptions = true; + synchronizeProgram(); + // Update the wild card directory watch + watchConfigFileWildCardDirectories(); + } + function parseConfigFile() { + setConfigFileParsingResult(ts.getParsedCommandLineOfConfigFile(configFileName, optionsToExtendForConfigFile, parseConfigFileHost)); // TODO: GH#18217 + } + function setConfigFileParsingResult(configFileParseResult) { + rootFileNames = configFileParseResult.fileNames; + compilerOptions = configFileParseResult.options; + configFileSpecs = configFileParseResult.configFileSpecs; // TODO: GH#18217 + projectReferences = configFileParseResult.projectReferences; + configFileParsingDiagnostics = ts.getConfigFileParsingDiagnostics(configFileParseResult).slice(); + canConfigFileJsonReportNoInputFiles = ts.canJsonReportNoInutFiles(configFileParseResult.raw); + hasChangedConfigFileParsingErrors = true; + } + function onSourceFileChange(fileName, eventKind, path) { + updateCachedSystemWithFile(fileName, path, eventKind); + // Update the source file cache + if (eventKind === ts.FileWatcherEventKind.Deleted && sourceFilesCache.get(path)) { + resolutionCache.invalidateResolutionOfFile(path); + } + resolutionCache.removeResolutionsFromProjectReferenceRedirects(path); + nextSourceFileVersion(path); + // Update the program + scheduleProgramUpdate(); + } + function updateCachedSystemWithFile(fileName, path, eventKind) { + if (cachedDirectoryStructureHost) { + cachedDirectoryStructureHost.addOrDeleteFile(fileName, path, eventKind); + } + } + function watchMissingFilePath(missingFilePath) { + return watchFilePath(host, missingFilePath, onMissingFileChange, ts.PollingInterval.Medium, missingFilePath, "Missing file"); + } + function onMissingFileChange(fileName, eventKind, missingFilePath) { + updateCachedSystemWithFile(fileName, missingFilePath, eventKind); + if (eventKind === ts.FileWatcherEventKind.Created && missingFilesMap.has(missingFilePath)) { + missingFilesMap.get(missingFilePath).close(); + missingFilesMap.delete(missingFilePath); + // Delete the entry in the source files cache so that new source file is created + nextSourceFileVersion(missingFilePath); + // When a missing file is created, we should update the graph. + scheduleProgramUpdate(); + } + } + function watchConfigFileWildCardDirectories() { + if (configFileSpecs) { + ts.updateWatchingWildcardDirectories(watchedWildcardDirectories || (watchedWildcardDirectories = ts.createMap()), ts.createMapFromTemplate(configFileSpecs.wildcardDirectories), watchWildcardDirectory); + } + else if (watchedWildcardDirectories) { + ts.clearMap(watchedWildcardDirectories, ts.closeFileWatcherOf); + } + } + function watchWildcardDirectory(directory, flags) { + return watchDirectory(host, directory, function (fileOrDirectory) { + ts.Debug.assert(!!configFileName); + var fileOrDirectoryPath = toPath(fileOrDirectory); + // Since the file existance changed, update the sourceFiles cache + if (cachedDirectoryStructureHost) { + cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); + } + nextSourceFileVersion(fileOrDirectoryPath); + if (ts.isPathInNodeModulesStartingWithDot(fileOrDirectoryPath)) + return; + // If the the added or created file or directory is not supported file name, ignore the file + // But when watched directory is added/removed, we need to reload the file list + if (fileOrDirectoryPath !== directory && ts.hasExtension(fileOrDirectoryPath) && !ts.isSupportedSourceFileName(fileOrDirectory, compilerOptions)) { + writeLog("Project: " + configFileName + " Detected file add/remove of non supported extension: " + fileOrDirectory); + return; + } + // Reload is pending, do the reload + if (reloadLevel !== ts.ConfigFileProgramReloadLevel.Full) { + reloadLevel = ts.ConfigFileProgramReloadLevel.Partial; + // Schedule Update the program + scheduleProgramUpdate(); + } + }, flags, "Wild card directories"); + } + function ensureDirectoriesExist(directoryPath) { + if (directoryPath.length > ts.getRootLength(directoryPath) && !host.directoryExists(directoryPath)) { + var parentDirectory = ts.getDirectoryPath(directoryPath); + ensureDirectoriesExist(parentDirectory); + host.createDirectory(directoryPath); + } + } + function writeFile(fileName, text, writeByteOrderMark, onError) { + try { + ts.performance.mark("beforeIOWrite"); + ensureDirectoriesExist(ts.getDirectoryPath(ts.normalizePath(fileName))); + host.writeFile(fileName, text, writeByteOrderMark); + ts.performance.mark("afterIOWrite"); + ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite"); + } + catch (e) { + if (onError) { + onError(e.message); + } + } + } + } + ts.createWatchProgram = createWatchProgram; +})(ts || (ts = {})); +// Currently we do not want to expose API for build, we should work out the API, and then expose it just like we did for builder/watch +/*@internal*/ +var ts; +(function (ts) { + var minimumDate = new Date(-8640000000000000); + var maximumDate = new Date(8640000000000000); + var BuildResultFlags; + (function (BuildResultFlags) { + BuildResultFlags[BuildResultFlags["None"] = 0] = "None"; + /** + * No errors of any kind occurred during build + */ + BuildResultFlags[BuildResultFlags["Success"] = 1] = "Success"; + /** + * None of the .d.ts files emitted by this build were + * different from the existing files on disk + */ + BuildResultFlags[BuildResultFlags["DeclarationOutputUnchanged"] = 2] = "DeclarationOutputUnchanged"; + BuildResultFlags[BuildResultFlags["ConfigFileErrors"] = 4] = "ConfigFileErrors"; + BuildResultFlags[BuildResultFlags["SyntaxErrors"] = 8] = "SyntaxErrors"; + BuildResultFlags[BuildResultFlags["TypeErrors"] = 16] = "TypeErrors"; + BuildResultFlags[BuildResultFlags["DeclarationEmitErrors"] = 32] = "DeclarationEmitErrors"; + BuildResultFlags[BuildResultFlags["EmitErrors"] = 64] = "EmitErrors"; + BuildResultFlags[BuildResultFlags["AnyErrors"] = 124] = "AnyErrors"; + })(BuildResultFlags || (BuildResultFlags = {})); + var UpToDateStatusType; + (function (UpToDateStatusType) { + UpToDateStatusType[UpToDateStatusType["Unbuildable"] = 0] = "Unbuildable"; + UpToDateStatusType[UpToDateStatusType["UpToDate"] = 1] = "UpToDate"; + /** + * The project appears out of date because its upstream inputs are newer than its outputs, + * but all of its outputs are actually newer than the previous identical outputs of its (.d.ts) inputs. + * This means we can Pseudo-build (just touch timestamps), as if we had actually built this project. + */ + UpToDateStatusType[UpToDateStatusType["UpToDateWithUpstreamTypes"] = 2] = "UpToDateWithUpstreamTypes"; + UpToDateStatusType[UpToDateStatusType["OutputMissing"] = 3] = "OutputMissing"; + UpToDateStatusType[UpToDateStatusType["OutOfDateWithSelf"] = 4] = "OutOfDateWithSelf"; + UpToDateStatusType[UpToDateStatusType["OutOfDateWithUpstream"] = 5] = "OutOfDateWithUpstream"; + UpToDateStatusType[UpToDateStatusType["UpstreamOutOfDate"] = 6] = "UpstreamOutOfDate"; + UpToDateStatusType[UpToDateStatusType["UpstreamBlocked"] = 7] = "UpstreamBlocked"; + UpToDateStatusType[UpToDateStatusType["ComputingUpstream"] = 8] = "ComputingUpstream"; + /** + * Projects with no outputs (i.e. "solution" files) + */ + UpToDateStatusType[UpToDateStatusType["ContainerOnly"] = 9] = "ContainerOnly"; + })(UpToDateStatusType = ts.UpToDateStatusType || (ts.UpToDateStatusType = {})); + function createFileMap(toPath) { + // tslint:disable-next-line:no-null-keyword + var lookup = ts.createMap(); + return { + setValue: setValue, + getValue: getValue, + removeKey: removeKey, + forEach: forEach, + hasKey: hasKey, + getSize: getSize, + clear: clear + }; + function forEach(action) { + lookup.forEach(action); + } + function hasKey(fileName) { + return lookup.has(toPath(fileName)); + } + function removeKey(fileName) { + lookup.delete(toPath(fileName)); + } + function setValue(fileName, value) { + lookup.set(toPath(fileName), value); + } + function getValue(fileName) { + return lookup.get(toPath(fileName)); + } + function getSize() { + return lookup.size; + } + function clear() { + lookup.clear(); + } + } + function getOrCreateValueFromConfigFileMap(configFileMap, resolved, createT) { + var existingValue = configFileMap.getValue(resolved); + var newValue; + if (!existingValue) { + newValue = createT(); + configFileMap.setValue(resolved, newValue); + } + return existingValue || newValue; + } + function getOrCreateValueMapFromConfigFileMap(configFileMap, resolved) { + return getOrCreateValueFromConfigFileMap(configFileMap, resolved, ts.createMap); + } + function getOutputDeclarationFileName(inputFileName, configFile) { + var relativePath = ts.getRelativePathFromDirectory(rootDirOfOptions(configFile.options, configFile.options.configFilePath), inputFileName, /*ignoreCase*/ true); + var outputPath = ts.resolvePath(configFile.options.declarationDir || configFile.options.outDir || ts.getDirectoryPath(configFile.options.configFilePath), relativePath); + return ts.changeExtension(outputPath, ".d.ts" /* Dts */); + } + ts.getOutputDeclarationFileName = getOutputDeclarationFileName; + function getOutputJSFileName(inputFileName, configFile) { + var relativePath = ts.getRelativePathFromDirectory(rootDirOfOptions(configFile.options, configFile.options.configFilePath), inputFileName, /*ignoreCase*/ true); + var outputPath = ts.resolvePath(configFile.options.outDir || ts.getDirectoryPath(configFile.options.configFilePath), relativePath); + var newExtension = ts.fileExtensionIs(inputFileName, ".json" /* Json */) ? ".json" /* Json */ : + ts.fileExtensionIs(inputFileName, ".tsx" /* Tsx */) && configFile.options.jsx === 1 /* Preserve */ ? ".jsx" /* Jsx */ : ".js" /* Js */; + return ts.changeExtension(outputPath, newExtension); + } + function getOutputFileNames(inputFileName, configFile) { + // outFile is handled elsewhere; .d.ts files don't generate outputs + if (configFile.options.outFile || configFile.options.out || ts.fileExtensionIs(inputFileName, ".d.ts" /* Dts */)) { + return ts.emptyArray; + } + var outputs = []; + var js = getOutputJSFileName(inputFileName, configFile); + outputs.push(js); + if (configFile.options.sourceMap) { + outputs.push(js + ".map"); + } + if (ts.getEmitDeclarations(configFile.options) && !ts.fileExtensionIs(inputFileName, ".json" /* Json */)) { + var dts = getOutputDeclarationFileName(inputFileName, configFile); + outputs.push(dts); + if (configFile.options.declarationMap) { + outputs.push(dts + ".map"); + } + } + return outputs; + } + function getOutFileOutputs(project) { + var out = project.options.outFile || project.options.out; + if (!out) { + return ts.Debug.fail("outFile must be set"); + } + var outputs = []; + outputs.push(out); + if (project.options.sourceMap) { + outputs.push(out + ".map"); + } + if (ts.getEmitDeclarations(project.options)) { + var dts = ts.changeExtension(out, ".d.ts" /* Dts */); + outputs.push(dts); + if (project.options.declarationMap) { + outputs.push(dts + ".map"); + } + } + return outputs; + } + function rootDirOfOptions(opts, configFileName) { + return opts.rootDir || ts.getDirectoryPath(configFileName); + } + function newer(date1, date2) { + return date2 > date1 ? date2 : date1; + } + function isDeclarationFile(fileName) { + return ts.fileExtensionIs(fileName, ".d.ts" /* Dts */); + } + /** + * Create a function that reports watch status by writing to the system and handles the formating of the diagnostic + */ + function createBuilderStatusReporter(system, pretty) { + return function (diagnostic) { + var output = pretty ? "[" + ts.formatColorAndReset(new Date().toLocaleTimeString(), ts.ForegroundColorEscapeSequences.Grey) + "] " : new Date().toLocaleTimeString() + " - "; + output += "" + ts.flattenDiagnosticMessageText(diagnostic.messageText, system.newLine) + (system.newLine + system.newLine); + system.write(output); + }; + } + ts.createBuilderStatusReporter = createBuilderStatusReporter; + function createSolutionBuilderHostBase(system, reportDiagnostic, reportSolutionBuilderStatus) { + if (system === void 0) { system = ts.sys; } + var host = ts.createCompilerHostWorker({}, /*setParentNodes*/ undefined, system); + host.getModifiedTime = system.getModifiedTime ? function (path) { return system.getModifiedTime(path); } : function () { return undefined; }; + host.setModifiedTime = system.setModifiedTime ? function (path, date) { return system.setModifiedTime(path, date); } : ts.noop; + host.deleteFile = system.deleteFile ? function (path) { return system.deleteFile(path); } : ts.noop; + host.reportDiagnostic = reportDiagnostic || ts.createDiagnosticReporter(system); + host.reportSolutionBuilderStatus = reportSolutionBuilderStatus || createBuilderStatusReporter(system); + return host; + } + function createSolutionBuilderHost(system, reportDiagnostic, reportSolutionBuilderStatus, reportErrorSummary) { + if (system === void 0) { system = ts.sys; } + var host = createSolutionBuilderHostBase(system, reportDiagnostic, reportSolutionBuilderStatus); + host.reportErrorSummary = reportErrorSummary; + return host; + } + ts.createSolutionBuilderHost = createSolutionBuilderHost; + function createSolutionBuilderWithWatchHost(system, reportDiagnostic, reportSolutionBuilderStatus, reportWatchStatus) { + var host = createSolutionBuilderHostBase(system, reportDiagnostic, reportSolutionBuilderStatus); + var watchHost = ts.createWatchHost(system, reportWatchStatus); + host.onWatchStatusChange = watchHost.onWatchStatusChange; + host.watchFile = watchHost.watchFile; + host.watchDirectory = watchHost.watchDirectory; + host.setTimeout = watchHost.setTimeout; + host.clearTimeout = watchHost.clearTimeout; + return host; + } + ts.createSolutionBuilderWithWatchHost = createSolutionBuilderWithWatchHost; + function getCompilerOptionsOfBuildOptions(buildOptions) { + var result = {}; + ts.commonOptionsWithBuild.forEach(function (option) { + result[option.name] = buildOptions[option.name]; + }); + return result; + } + function createSolutionBuilder(host, rootNames, defaultOptions) { + var hostWithWatch = host; + var currentDirectory = host.getCurrentDirectory(); + var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames()); + var parseConfigFileHost = ts.parseConfigHostFromCompilerHost(host); + // State of the solution + var options = defaultOptions; + var baseCompilerOptions = getCompilerOptionsOfBuildOptions(options); + var configFileCache = createFileMap(toPath); + /** Map from output file name to its pre-build timestamp */ + var unchangedOutputs = createFileMap(toPath); + /** Map from config file name to up-to-date status */ + var projectStatus = createFileMap(toPath); + var missingRoots = ts.createMap(); + var globalDependencyGraph; + var writeFileName = function (s) { return host.trace && host.trace(s); }; + var readFileWithCache = function (f) { return host.readFile(f); }; + // Watch state + var diagnostics = createFileMap(toPath); + var projectPendingBuild = createFileMap(toPath); + var projectErrorsReported = createFileMap(toPath); + var invalidatedProjectQueue = []; + var nextProjectToBuild = 0; + var timerToBuildInvalidatedProject; + var reportFileChangeDetected = false; + // Watches for the solution + var allWatchedWildcardDirectories = createFileMap(toPath); + var allWatchedInputFiles = createFileMap(toPath); + var allWatchedConfigFiles = createFileMap(toPath); + return { + buildAllProjects: buildAllProjects, + getUpToDateStatusOfFile: getUpToDateStatusOfFile, + cleanAllProjects: cleanAllProjects, + resetBuildContext: resetBuildContext, + getBuildGraph: getBuildGraph, + invalidateProject: invalidateProject, + buildInvalidatedProject: buildInvalidatedProject, + resolveProjectName: resolveProjectName, + startWatching: startWatching + }; + function toPath(fileName) { + return ts.toPath(fileName, currentDirectory, getCanonicalFileName); + } + function resetBuildContext(opts) { + if (opts === void 0) { opts = defaultOptions; } + options = opts; + baseCompilerOptions = getCompilerOptionsOfBuildOptions(options); + configFileCache.clear(); + unchangedOutputs.clear(); + projectStatus.clear(); + missingRoots.clear(); + globalDependencyGraph = undefined; + diagnostics.clear(); + projectPendingBuild.clear(); + projectErrorsReported.clear(); + invalidatedProjectQueue.length = 0; + nextProjectToBuild = 0; + if (timerToBuildInvalidatedProject) { + clearTimeout(timerToBuildInvalidatedProject); + timerToBuildInvalidatedProject = undefined; + } + reportFileChangeDetected = false; + ts.clearMap(allWatchedWildcardDirectories, function (wildCardWatches) { return ts.clearMap(wildCardWatches, ts.closeFileWatcherOf); }); + ts.clearMap(allWatchedInputFiles, function (inputFileWatches) { return ts.clearMap(inputFileWatches, ts.closeFileWatcher); }); + ts.clearMap(allWatchedConfigFiles, ts.closeFileWatcher); + } + function isParsedCommandLine(entry) { + return !!entry.options; + } + function parseConfigFile(configFilePath) { + var value = configFileCache.getValue(configFilePath); + if (value) { + return isParsedCommandLine(value) ? value : undefined; + } + var diagnostic; + parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = function (d) { return diagnostic = d; }; + var parsed = ts.getParsedCommandLineOfConfigFile(configFilePath, baseCompilerOptions, parseConfigFileHost); + parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = ts.noop; + configFileCache.setValue(configFilePath, parsed || diagnostic); + return parsed; + } + function reportStatus(message) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + host.reportSolutionBuilderStatus(ts.createCompilerDiagnostic.apply(void 0, [message].concat(args))); + } + function reportWatchStatus(message) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + if (hostWithWatch.onWatchStatusChange) { + hostWithWatch.onWatchStatusChange(ts.createCompilerDiagnostic.apply(void 0, [message].concat(args)), host.getNewLine(), baseCompilerOptions); + } + } + function startWatching() { + var graph = getGlobalDependencyGraph(); + for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { + var resolved = _a[_i]; + // Watch this file + watchConfigFile(resolved); + var cfg = parseConfigFile(resolved); + if (cfg) { + // Update watchers for wildcard directories + watchWildCardDirectories(resolved, cfg); + // Watch input files + watchInputFiles(resolved, cfg); + } + } + } + function watchConfigFile(resolved) { + if (options.watch && !allWatchedConfigFiles.hasKey(resolved)) { + allWatchedConfigFiles.setValue(resolved, hostWithWatch.watchFile(resolved, function () { + invalidateProjectAndScheduleBuilds(resolved, ts.ConfigFileProgramReloadLevel.Full); + })); + } + } + function watchWildCardDirectories(resolved, parsed) { + if (!options.watch) + return; + ts.updateWatchingWildcardDirectories(getOrCreateValueMapFromConfigFileMap(allWatchedWildcardDirectories, resolved), ts.createMapFromTemplate(parsed.configFileSpecs.wildcardDirectories), function (dir, flags) { + return hostWithWatch.watchDirectory(dir, function (fileOrDirectory) { + var fileOrDirectoryPath = toPath(fileOrDirectory); + if (fileOrDirectoryPath !== toPath(dir) && ts.hasExtension(fileOrDirectoryPath) && !ts.isSupportedSourceFileName(fileOrDirectory, parsed.options)) { + // writeLog(`Project: ${configFileName} Detected file add/remove of non supported extension: ${fileOrDirectory}`); + return; + } + if (isOutputFile(fileOrDirectory, parsed)) { + // writeLog(`${fileOrDirectory} is output file`); + return; + } + invalidateProjectAndScheduleBuilds(resolved, ts.ConfigFileProgramReloadLevel.Partial); + }, !!(flags & 1 /* Recursive */)); + }); + } + function watchInputFiles(resolved, parsed) { + if (!options.watch) + return; + ts.mutateMap(getOrCreateValueMapFromConfigFileMap(allWatchedInputFiles, resolved), ts.arrayToMap(parsed.fileNames, toPath), { + createNewValue: function (_key, input) { return hostWithWatch.watchFile(input, function () { + invalidateProjectAndScheduleBuilds(resolved, ts.ConfigFileProgramReloadLevel.None); + }); }, + onDeleteValue: ts.closeFileWatcher, + }); + } + function isOutputFile(fileName, configFile) { + if (configFile.options.noEmit) + return false; + // ts or tsx files are not output + if (!ts.fileExtensionIs(fileName, ".d.ts" /* Dts */) && + (ts.fileExtensionIs(fileName, ".ts" /* Ts */) || ts.fileExtensionIs(fileName, ".tsx" /* Tsx */))) { + return false; + } + // If options have --outFile or --out, check if its that + var out = configFile.options.outFile || configFile.options.out; + if (out && (isSameFile(fileName, out) || isSameFile(fileName, ts.removeFileExtension(out) + ".d.ts" /* Dts */))) { + return true; + } + // If declarationDir is specified, return if its a file in that directory + if (configFile.options.declarationDir && ts.containsPath(configFile.options.declarationDir, fileName, currentDirectory, !host.useCaseSensitiveFileNames())) { + return true; + } + // If --outDir, check if file is in that directory + if (configFile.options.outDir && ts.containsPath(configFile.options.outDir, fileName, currentDirectory, !host.useCaseSensitiveFileNames())) { + return true; + } + return !ts.forEach(configFile.fileNames, function (inputFile) { return isSameFile(fileName, inputFile); }); + } + function isSameFile(file1, file2) { + return ts.comparePaths(file1, file2, currentDirectory, !host.useCaseSensitiveFileNames()) === 0 /* EqualTo */; + } + function invalidateProjectAndScheduleBuilds(resolved, reloadLevel) { + reportFileChangeDetected = true; + invalidateResolvedProject(resolved, reloadLevel); + scheduleBuildInvalidatedProject(); + } + function getUpToDateStatusOfFile(configFileName) { + return getUpToDateStatus(parseConfigFile(configFileName)); + } + function getBuildGraph(configFileNames) { + return createDependencyGraph(resolveProjectNames(configFileNames)); + } + function getGlobalDependencyGraph() { + return globalDependencyGraph || (globalDependencyGraph = getBuildGraph(rootNames)); + } + function getUpToDateStatus(project) { + if (project === undefined) { + return { type: UpToDateStatusType.Unbuildable, reason: "File deleted mid-build" }; + } + var prior = projectStatus.getValue(project.options.configFilePath); + if (prior !== undefined) { + return prior; + } + var actual = getUpToDateStatusWorker(project); + projectStatus.setValue(project.options.configFilePath, actual); + return actual; + } + function getUpToDateStatusWorker(project) { + var newestInputFileName = undefined; + var newestInputFileTime = minimumDate; + // Get timestamps of input files + for (var _i = 0, _a = project.fileNames; _i < _a.length; _i++) { + var inputFile = _a[_i]; + if (!host.fileExists(inputFile)) { + return { + type: UpToDateStatusType.Unbuildable, + reason: inputFile + " does not exist" + }; + } + var inputTime = host.getModifiedTime(inputFile) || ts.missingFileModifiedTime; + if (inputTime > newestInputFileTime) { + newestInputFileName = inputFile; + newestInputFileTime = inputTime; + } + } + // Collect the expected outputs of this project + var outputs = getAllProjectOutputs(project); + if (outputs.length === 0) { + return { + type: UpToDateStatusType.ContainerOnly + }; + } + // Now see if all outputs are newer than the newest input + var oldestOutputFileName = "(none)"; + var oldestOutputFileTime = maximumDate; + var newestOutputFileName = "(none)"; + var newestOutputFileTime = minimumDate; + var missingOutputFileName; + var newestDeclarationFileContentChangedTime = minimumDate; + var isOutOfDateWithInputs = false; + for (var _b = 0, outputs_1 = outputs; _b < outputs_1.length; _b++) { + var output = outputs_1[_b]; + // Output is missing; can stop checking + // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status + if (!host.fileExists(output)) { + missingOutputFileName = output; + break; + } + var outputTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; + if (outputTime < oldestOutputFileTime) { + oldestOutputFileTime = outputTime; + oldestOutputFileName = output; + } + // If an output is older than the newest input, we can stop checking + // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status + if (outputTime < newestInputFileTime) { + isOutOfDateWithInputs = true; + break; + } + if (outputTime > newestOutputFileTime) { + newestOutputFileTime = outputTime; + newestOutputFileName = output; + } + // Keep track of when the most recent time a .d.ts file was changed. + // In addition to file timestamps, we also keep track of when a .d.ts file + // had its file touched but not had its contents changed - this allows us + // to skip a downstream typecheck + if (isDeclarationFile(output)) { + var unchangedTime = unchangedOutputs.getValue(output); + if (unchangedTime !== undefined) { + newestDeclarationFileContentChangedTime = newer(unchangedTime, newestDeclarationFileContentChangedTime); + } + else { + var outputModifiedTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; + newestDeclarationFileContentChangedTime = newer(newestDeclarationFileContentChangedTime, outputModifiedTime); + } + } + } + var pseudoUpToDate = false; + var usesPrepend = false; + var upstreamChangedProject; + if (project.projectReferences) { + projectStatus.setValue(project.options.configFilePath, { type: UpToDateStatusType.ComputingUpstream }); + for (var _c = 0, _d = project.projectReferences; _c < _d.length; _c++) { + var ref = _d[_c]; + usesPrepend = usesPrepend || !!(ref.prepend); + var resolvedRef = ts.resolveProjectReferencePath(ref); + var refStatus = getUpToDateStatus(parseConfigFile(resolvedRef)); + // Its a circular reference ignore the status of this project + if (refStatus.type === UpToDateStatusType.ComputingUpstream) { + continue; + } + // An upstream project is blocked + if (refStatus.type === UpToDateStatusType.Unbuildable) { + return { + type: UpToDateStatusType.UpstreamBlocked, + upstreamProjectName: ref.path + }; + } + // If the upstream project is out of date, then so are we (someone shouldn't have asked, though?) + if (refStatus.type !== UpToDateStatusType.UpToDate) { + return { + type: UpToDateStatusType.UpstreamOutOfDate, + upstreamProjectName: ref.path + }; + } + // If the upstream project's newest file is older than our oldest output, we + // can't be out of date because of it + if (refStatus.newestInputFileTime && refStatus.newestInputFileTime <= oldestOutputFileTime) { + continue; + } + // If the upstream project has only change .d.ts files, and we've built + // *after* those files, then we're "psuedo up to date" and eligible for a fast rebuild + if (refStatus.newestDeclarationFileContentChangedTime && refStatus.newestDeclarationFileContentChangedTime <= oldestOutputFileTime) { + pseudoUpToDate = true; + upstreamChangedProject = ref.path; + continue; + } + // We have an output older than an upstream output - we are out of date + ts.Debug.assert(oldestOutputFileName !== undefined, "Should have an oldest output filename here"); + return { + type: UpToDateStatusType.OutOfDateWithUpstream, + outOfDateOutputFileName: oldestOutputFileName, + newerProjectName: ref.path + }; + } + } + if (missingOutputFileName !== undefined) { + return { + type: UpToDateStatusType.OutputMissing, + missingOutputFileName: missingOutputFileName + }; + } + if (isOutOfDateWithInputs) { + return { + type: UpToDateStatusType.OutOfDateWithSelf, + outOfDateOutputFileName: oldestOutputFileName, + newerInputFileName: newestInputFileName + }; + } + if (usesPrepend && pseudoUpToDate) { + return { + type: UpToDateStatusType.OutOfDateWithUpstream, + outOfDateOutputFileName: oldestOutputFileName, + newerProjectName: upstreamChangedProject + }; + } + // Up to date + return { + type: pseudoUpToDate ? UpToDateStatusType.UpToDateWithUpstreamTypes : UpToDateStatusType.UpToDate, + newestDeclarationFileContentChangedTime: newestDeclarationFileContentChangedTime, + newestInputFileTime: newestInputFileTime, + newestOutputFileTime: newestOutputFileTime, + newestInputFileName: newestInputFileName, + newestOutputFileName: newestOutputFileName, + oldestOutputFileName: oldestOutputFileName + }; + } + function invalidateProject(configFileName, reloadLevel) { + invalidateResolvedProject(resolveProjectName(configFileName), reloadLevel); + } + function invalidateResolvedProject(resolved, reloadLevel) { + if (reloadLevel === ts.ConfigFileProgramReloadLevel.Full) { + configFileCache.removeKey(resolved); + globalDependencyGraph = undefined; + } + projectStatus.removeKey(resolved); + diagnostics.removeKey(resolved); + addProjToQueue(resolved, reloadLevel); + } + /** + * return true if new addition + */ + function addProjToQueue(proj, reloadLevel) { + var value = projectPendingBuild.getValue(proj); + if (value === undefined) { + projectPendingBuild.setValue(proj, reloadLevel || ts.ConfigFileProgramReloadLevel.None); + invalidatedProjectQueue.push(proj); + } + else if (value < (reloadLevel || ts.ConfigFileProgramReloadLevel.None)) { + projectPendingBuild.setValue(proj, reloadLevel || ts.ConfigFileProgramReloadLevel.None); + } + } + function getNextInvalidatedProject() { + if (nextProjectToBuild < invalidatedProjectQueue.length) { + var project = invalidatedProjectQueue[nextProjectToBuild]; + nextProjectToBuild++; + var reloadLevel = projectPendingBuild.getValue(project); + projectPendingBuild.removeKey(project); + if (!projectPendingBuild.getSize()) { + invalidatedProjectQueue.length = 0; + nextProjectToBuild = 0; + } + return { project: project, reloadLevel: reloadLevel }; + } + } + function hasPendingInvalidatedProjects() { + return !!projectPendingBuild.getSize(); + } + function scheduleBuildInvalidatedProject() { + if (!hostWithWatch.setTimeout || !hostWithWatch.clearTimeout) { + return; + } + if (timerToBuildInvalidatedProject) { + hostWithWatch.clearTimeout(timerToBuildInvalidatedProject); + } + timerToBuildInvalidatedProject = hostWithWatch.setTimeout(buildInvalidatedProject, 250); + } + function buildInvalidatedProject() { + timerToBuildInvalidatedProject = undefined; + if (reportFileChangeDetected) { + reportFileChangeDetected = false; + projectErrorsReported.clear(); + reportWatchStatus(ts.Diagnostics.File_change_detected_Starting_incremental_compilation); + } + var buildProject = getNextInvalidatedProject(); + if (buildProject) { + buildSingleInvalidatedProject(buildProject.project, buildProject.reloadLevel); + if (hasPendingInvalidatedProjects()) { + if (options.watch && !timerToBuildInvalidatedProject) { + scheduleBuildInvalidatedProject(); + } + } + else { + reportErrorSummary(); + } + } + } + function reportErrorSummary() { + if (options.watch || host.reportErrorSummary) { + // Report errors from the other projects + getGlobalDependencyGraph().buildQueue.forEach(function (project) { + if (!projectErrorsReported.hasKey(project)) { + reportErrors(diagnostics.getValue(project) || ts.emptyArray); + } + }); + var totalErrors_1 = 0; + diagnostics.forEach(function (singleProjectErrors) { return totalErrors_1 += ts.getErrorCountForSummary(singleProjectErrors); }); + if (options.watch) { + reportWatchStatus(ts.getWatchErrorSummaryDiagnosticMessage(totalErrors_1), totalErrors_1); + } + else { + host.reportErrorSummary(totalErrors_1); + } + } + } + function buildSingleInvalidatedProject(resolved, reloadLevel) { + var proj = parseConfigFile(resolved); + if (!proj) { + reportParseConfigFileDiagnostic(resolved); + return; + } + if (reloadLevel === ts.ConfigFileProgramReloadLevel.Full) { + watchConfigFile(resolved); + watchWildCardDirectories(resolved, proj); + watchInputFiles(resolved, proj); + } + else if (reloadLevel === ts.ConfigFileProgramReloadLevel.Partial) { + // Update file names + var result = ts.getFileNamesFromConfigSpecs(proj.configFileSpecs, ts.getDirectoryPath(resolved), proj.options, parseConfigFileHost); + ts.updateErrorForNoInputFiles(result, resolved, proj.configFileSpecs, proj.errors, ts.canJsonReportNoInutFiles(proj.raw)); + proj.fileNames = result.fileNames; + watchInputFiles(resolved, proj); + } + var status = getUpToDateStatus(proj); + verboseReportProjectStatus(resolved, status); + if (status.type === UpToDateStatusType.UpstreamBlocked) { + if (options.verbose) + reportStatus(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, resolved, status.upstreamProjectName); + return; + } + var buildResult = buildSingleProject(resolved); + var dependencyGraph = getGlobalDependencyGraph(); + var referencingProjects = dependencyGraph.referencingProjectsMap.getValue(resolved); + if (!referencingProjects) + return; + // Always use build order to queue projects + for (var _i = 0, _a = dependencyGraph.buildQueue; _i < _a.length; _i++) { + var project = _a[_i]; + var prepend = referencingProjects.getValue(project); + // If the project is referenced with prepend, always build downstream projectm, + // otherwise queue it only if declaration output changed + if (prepend || (prepend !== undefined && !(buildResult & BuildResultFlags.DeclarationOutputUnchanged))) { + addProjToQueue(project); + } + } + } + function createDependencyGraph(roots) { + var temporaryMarks = createFileMap(toPath); + var permanentMarks = createFileMap(toPath); + var circularityReportStack = []; + var buildOrder = []; + var referencingProjectsMap = createFileMap(toPath); + for (var _i = 0, roots_1 = roots; _i < roots_1.length; _i++) { + var root = roots_1[_i]; + visit(root); + } + return { + buildQueue: buildOrder, + referencingProjectsMap: referencingProjectsMap + }; + function visit(projPath, inCircularContext) { + // Already visited + if (permanentMarks.hasKey(projPath)) + return; + // Circular + if (temporaryMarks.hasKey(projPath)) { + if (!inCircularContext) { + // TODO:: Do we report this as error? + reportStatus(ts.Diagnostics.Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0, circularityReportStack.join("\r\n")); + } + return; + } + temporaryMarks.setValue(projPath, true); + circularityReportStack.push(projPath); + var parsed = parseConfigFile(projPath); + if (parsed && parsed.projectReferences) { + for (var _i = 0, _a = parsed.projectReferences; _i < _a.length; _i++) { + var ref = _a[_i]; + var resolvedRefPath = resolveProjectName(ref.path); + visit(resolvedRefPath, inCircularContext || ref.circular); + // Get projects referencing resolvedRefPath and add projPath to it + var referencingProjects = getOrCreateValueFromConfigFileMap(referencingProjectsMap, resolvedRefPath, function () { return createFileMap(toPath); }); + referencingProjects.setValue(projPath, !!ref.prepend); + } + } + circularityReportStack.pop(); + permanentMarks.setValue(projPath, true); + buildOrder.push(projPath); + } + } + function buildSingleProject(proj) { + if (options.dry) { + reportStatus(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj); + return BuildResultFlags.Success; + } + if (options.verbose) + reportStatus(ts.Diagnostics.Building_project_0, proj); + var resultFlags = BuildResultFlags.None; + resultFlags |= BuildResultFlags.DeclarationOutputUnchanged; + var configFile = parseConfigFile(proj); + if (!configFile) { + // Failed to read the config file + resultFlags |= BuildResultFlags.ConfigFileErrors; + reportParseConfigFileDiagnostic(proj); + projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Config file errors" }); + return resultFlags; + } + if (configFile.fileNames.length === 0) { + reportAndStoreErrors(proj, configFile.errors); + // Nothing to build - must be a solution file, basically + return BuildResultFlags.None; + } + var programOptions = { + projectReferences: configFile.projectReferences, + host: host, + rootNames: configFile.fileNames, + options: configFile.options, + configFileParsingDiagnostics: configFile.errors + }; + if (host.beforeCreateProgram) { + host.beforeCreateProgram(options); + } + var program = ts.createProgram(programOptions); + // Don't emit anything in the presence of syntactic errors or options diagnostics + var syntaxDiagnostics = program.getOptionsDiagnostics().concat(program.getConfigFileParsingDiagnostics(), program.getSyntacticDiagnostics()); + if (syntaxDiagnostics.length) { + return buildErrors(syntaxDiagnostics, BuildResultFlags.SyntaxErrors, "Syntactic"); + } + // Same as above but now for semantic diagnostics + var semanticDiagnostics = program.getSemanticDiagnostics(); + if (semanticDiagnostics.length) { + return buildErrors(semanticDiagnostics, BuildResultFlags.TypeErrors, "Semantic"); + } + var newestDeclarationFileContentChangedTime = minimumDate; + var anyDtsChanged = false; + var declDiagnostics; + var reportDeclarationDiagnostics = function (d) { return (declDiagnostics || (declDiagnostics = [])).push(d); }; + var outputFiles = []; + ts.emitFilesAndReportErrors(program, reportDeclarationDiagnostics, writeFileName, /*reportSummary*/ undefined, function (name, text, writeByteOrderMark) { return outputFiles.push({ name: name, text: text, writeByteOrderMark: writeByteOrderMark }); }); + // Don't emit .d.ts if there are decl file errors + if (declDiagnostics) { + return buildErrors(declDiagnostics, BuildResultFlags.DeclarationEmitErrors, "Declaration file"); + } + // Actual Emit + var emitterDiagnostics = ts.createDiagnosticCollection(); + outputFiles.forEach(function (_a) { + var name = _a.name, text = _a.text, writeByteOrderMark = _a.writeByteOrderMark; + var priorChangeTime; + if (!anyDtsChanged && isDeclarationFile(name)) { + // Check for unchanged .d.ts files + if (host.fileExists(name) && readFileWithCache(name) === text) { + priorChangeTime = host.getModifiedTime(name); + } + else { + resultFlags &= ~BuildResultFlags.DeclarationOutputUnchanged; + anyDtsChanged = true; + } + } + ts.writeFile(host, emitterDiagnostics, name, text, writeByteOrderMark); + if (priorChangeTime !== undefined) { + newestDeclarationFileContentChangedTime = newer(priorChangeTime, newestDeclarationFileContentChangedTime); + unchangedOutputs.setValue(name, priorChangeTime); + } + }); + var emitDiagnostics = emitterDiagnostics.getDiagnostics(); + if (emitDiagnostics.length) { + return buildErrors(emitDiagnostics, BuildResultFlags.EmitErrors, "Emit"); + } + var status = { + type: UpToDateStatusType.UpToDate, + newestDeclarationFileContentChangedTime: anyDtsChanged ? maximumDate : newestDeclarationFileContentChangedTime + }; + diagnostics.removeKey(proj); + projectStatus.setValue(proj, status); + if (host.afterProgramEmitAndDiagnostics) { + host.afterProgramEmitAndDiagnostics(program); + } + return resultFlags; + function buildErrors(diagnostics, errorFlags, errorType) { + resultFlags |= errorFlags; + reportAndStoreErrors(proj, diagnostics); + projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: errorType + " errors" }); + if (host.afterProgramEmitAndDiagnostics) { + host.afterProgramEmitAndDiagnostics(program); + } + return resultFlags; + } + } + function updateOutputTimestamps(proj) { + if (options.dry) { + return reportStatus(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj.options.configFilePath); + } + if (options.verbose) { + reportStatus(ts.Diagnostics.Updating_output_timestamps_of_project_0, proj.options.configFilePath); + } + var now = new Date(); + var outputs = getAllProjectOutputs(proj); + var priorNewestUpdateTime = minimumDate; + for (var _i = 0, outputs_2 = outputs; _i < outputs_2.length; _i++) { + var file = outputs_2[_i]; + if (isDeclarationFile(file)) { + priorNewestUpdateTime = newer(priorNewestUpdateTime, host.getModifiedTime(file) || ts.missingFileModifiedTime); + } + host.setModifiedTime(file, now); + } + projectStatus.setValue(proj.options.configFilePath, { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: priorNewestUpdateTime }); + } + function getFilesToClean() { + // Get the same graph for cleaning we'd use for building + var graph = getGlobalDependencyGraph(); + var filesToDelete = []; + for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { + var proj = _a[_i]; + var parsed = parseConfigFile(proj); + if (parsed === undefined) { + // File has gone missing; fine to ignore here + reportParseConfigFileDiagnostic(proj); + continue; + } + var outputs = getAllProjectOutputs(parsed); + for (var _b = 0, outputs_3 = outputs; _b < outputs_3.length; _b++) { + var output = outputs_3[_b]; + if (host.fileExists(output)) { + filesToDelete.push(output); + } + } + } + return filesToDelete; + } + function cleanAllProjects() { + var filesToDelete = getFilesToClean(); + if (options.dry) { + reportStatus(ts.Diagnostics.A_non_dry_build_would_delete_the_following_files_Colon_0, filesToDelete.map(function (f) { return "\r\n * " + f; }).join("")); + return ts.ExitStatus.Success; + } + for (var _i = 0, filesToDelete_1 = filesToDelete; _i < filesToDelete_1.length; _i++) { + var output = filesToDelete_1[_i]; + host.deleteFile(output); + } + return ts.ExitStatus.Success; + } + function resolveProjectName(name) { + return resolveConfigFileProjectName(ts.resolvePath(host.getCurrentDirectory(), name)); + } + function resolveProjectNames(configFileNames) { + return configFileNames.map(resolveProjectName); + } + function buildAllProjects() { + if (options.watch) { + reportWatchStatus(ts.Diagnostics.Starting_compilation_in_watch_mode); + } + // TODO:: In watch mode as well to use caches for incremental build once we can invalidate caches correctly and have right api + // Override readFile for json files and output .d.ts to cache the text + var _a = ts.changeCompilerHostToUseCache(host, toPath, /*useCacheForSourceFile*/ true), originalReadFile = _a.originalReadFile, originalFileExists = _a.originalFileExists, originalDirectoryExists = _a.originalDirectoryExists, originalCreateDirectory = _a.originalCreateDirectory, originalWriteFile = _a.originalWriteFile, originalGetSourceFile = _a.originalGetSourceFile, newReadFileWithCache = _a.readFileWithCache; + var savedReadFileWithCache = readFileWithCache; + readFileWithCache = newReadFileWithCache; + var graph = getGlobalDependencyGraph(); + reportBuildQueue(graph); + var anyFailed = false; + for (var _i = 0, _b = graph.buildQueue; _i < _b.length; _i++) { + var next = _b[_i]; + var proj = parseConfigFile(next); + if (proj === undefined) { + reportParseConfigFileDiagnostic(next); + anyFailed = true; + break; + } + // report errors early when using continue or break statements + var errors = proj.errors; + var status = getUpToDateStatus(proj); + verboseReportProjectStatus(next, status); + var projName = proj.options.configFilePath; + if (status.type === UpToDateStatusType.UpToDate && !options.force) { + reportAndStoreErrors(next, errors); + // Up to date, skip + if (defaultOptions.dry) { + // In a dry build, inform the user of this fact + reportStatus(ts.Diagnostics.Project_0_is_up_to_date, projName); + } + continue; + } + if (status.type === UpToDateStatusType.UpToDateWithUpstreamTypes && !options.force) { + reportAndStoreErrors(next, errors); + // Fake build + updateOutputTimestamps(proj); + continue; + } + if (status.type === UpToDateStatusType.UpstreamBlocked) { + reportAndStoreErrors(next, errors); + if (options.verbose) + reportStatus(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, projName, status.upstreamProjectName); + continue; + } + if (status.type === UpToDateStatusType.ContainerOnly) { + reportAndStoreErrors(next, errors); + // Do nothing + continue; + } + var buildResult = buildSingleProject(next); + anyFailed = anyFailed || !!(buildResult & BuildResultFlags.AnyErrors); + } + reportErrorSummary(); + host.readFile = originalReadFile; + host.fileExists = originalFileExists; + host.directoryExists = originalDirectoryExists; + host.createDirectory = originalCreateDirectory; + host.writeFile = originalWriteFile; + readFileWithCache = savedReadFileWithCache; + host.getSourceFile = originalGetSourceFile; + return anyFailed ? ts.ExitStatus.DiagnosticsPresent_OutputsSkipped : ts.ExitStatus.Success; + } + function reportParseConfigFileDiagnostic(proj) { + reportAndStoreErrors(proj, [configFileCache.getValue(proj)]); + } + function reportAndStoreErrors(proj, errors) { + reportErrors(errors); + projectErrorsReported.setValue(proj, true); + diagnostics.setValue(proj, errors); + } + function reportErrors(errors) { + errors.forEach(function (err) { return host.reportDiagnostic(err); }); + } + /** + * Report the build ordering inferred from the current project graph if we're in verbose mode + */ + function reportBuildQueue(graph) { + if (options.verbose) { + reportStatus(ts.Diagnostics.Projects_in_this_build_Colon_0, graph.buildQueue.map(function (s) { return "\r\n * " + relName(s); }).join("")); + } + } + function relName(path) { + return ts.convertToRelativePath(path, host.getCurrentDirectory(), function (f) { return host.getCanonicalFileName(f); }); + } + /** + * Report the up-to-date status of a project if we're in verbose mode + */ + function verboseReportProjectStatus(configFileName, status) { + if (!options.verbose) + return; + return formatUpToDateStatus(configFileName, status, relName, reportStatus); + } + } + ts.createSolutionBuilder = createSolutionBuilder; + function resolveConfigFileProjectName(project) { + if (ts.fileExtensionIs(project, ".json" /* Json */)) { + return project; + } + return ts.combinePaths(project, "tsconfig.json"); + } + ts.resolveConfigFileProjectName = resolveConfigFileProjectName; + function getAllProjectOutputs(project) { + if (project.options.outFile || project.options.out) { + return getOutFileOutputs(project); + } + else { + var outputs = []; + for (var _i = 0, _a = project.fileNames; _i < _a.length; _i++) { + var inputFile = _a[_i]; + outputs.push.apply(outputs, getOutputFileNames(inputFile, project)); + } + return outputs; + } + } + ts.getAllProjectOutputs = getAllProjectOutputs; + function formatUpToDateStatus(configFileName, status, relName, formatMessage) { + switch (status.type) { + case UpToDateStatusType.OutOfDateWithSelf: + return formatMessage(ts.Diagnostics.Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2, relName(configFileName), relName(status.outOfDateOutputFileName), relName(status.newerInputFileName)); + case UpToDateStatusType.OutOfDateWithUpstream: + return formatMessage(ts.Diagnostics.Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2, relName(configFileName), relName(status.outOfDateOutputFileName), relName(status.newerProjectName)); + case UpToDateStatusType.OutputMissing: + return formatMessage(ts.Diagnostics.Project_0_is_out_of_date_because_output_file_1_does_not_exist, relName(configFileName), relName(status.missingOutputFileName)); + case UpToDateStatusType.UpToDate: + if (status.newestInputFileTime !== undefined) { + return formatMessage(ts.Diagnostics.Project_0_is_up_to_date_because_newest_input_1_is_older_than_oldest_output_2, relName(configFileName), relName(status.newestInputFileName || ""), relName(status.oldestOutputFileName || "")); + } + // Don't report anything for "up to date because it was already built" -- too verbose + break; + case UpToDateStatusType.UpToDateWithUpstreamTypes: + return formatMessage(ts.Diagnostics.Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies, relName(configFileName)); + case UpToDateStatusType.UpstreamOutOfDate: + return formatMessage(ts.Diagnostics.Project_0_is_out_of_date_because_its_dependency_1_is_out_of_date, relName(configFileName), relName(status.upstreamProjectName)); + case UpToDateStatusType.UpstreamBlocked: + return formatMessage(ts.Diagnostics.Project_0_can_t_be_built_because_its_dependency_1_has_errors, relName(configFileName), relName(status.upstreamProjectName)); + case UpToDateStatusType.Unbuildable: + return formatMessage(ts.Diagnostics.Failed_to_parse_file_0_Colon_1, relName(configFileName), status.reason); + case UpToDateStatusType.ContainerOnly: + // Don't report status on "solution" projects + case UpToDateStatusType.ComputingUpstream: + // Should never leak from getUptoDateStatusWorker + break; + default: + ts.assertType(status); + } + } + ts.formatUpToDateStatus = formatUpToDateStatus; +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var ValueKind; + (function (ValueKind) { + ValueKind[ValueKind["Const"] = 0] = "Const"; + ValueKind[ValueKind["Array"] = 1] = "Array"; + ValueKind[ValueKind["FunctionOrClass"] = 2] = "FunctionOrClass"; + ValueKind[ValueKind["Object"] = 3] = "Object"; + })(ValueKind = ts.ValueKind || (ts.ValueKind = {})); + function inspectModule(fileNameToRequire) { + return inspectValue(ts.removeFileExtension(ts.getBaseFileName(fileNameToRequire)), tryRequire(fileNameToRequire)); + } + ts.inspectModule = inspectModule; + function inspectValue(name, value) { + return getValueInfo(name, value, getRecurser()); + } + ts.inspectValue = inspectValue; + function getRecurser() { + var seen = new Set(); + var nameStack = []; + return function (obj, name, cbOk, cbFail) { + if (seen.has(obj) || nameStack.length > 4) { + return cbFail(seen.has(obj), nameStack); + } + seen.add(obj); + nameStack.push(name); + var res = cbOk(); + nameStack.pop(); + seen.delete(obj); + return res; + }; + } + function getValueInfo(name, value, recurser) { + return recurser(value, name, function () { + if (typeof value === "function") + return getFunctionOrClassInfo(value, name, recurser); + if (typeof value === "object") { + var builtin = getBuiltinType(name, value, recurser); + if (builtin !== undefined) + return builtin; + var entries = getEntriesOfObject(value); + var hasNontrivialPrototype = Object.getPrototypeOf(value) !== Object.prototype; + var members = ts.flatMap(entries, function (_a) { + var key = _a.key, value = _a.value; + return getValueInfo(key, value, recurser); + }); + return { kind: 3 /* Object */, name: name, hasNontrivialPrototype: hasNontrivialPrototype, members: members }; + } + return { kind: 0 /* Const */, name: name, typeName: isNullOrUndefined(value) ? "any" : typeof value }; + }, function (isCircularReference, keyStack) { return anyValue(name, " " + (isCircularReference ? "Circular reference" : "Too-deep object hierarchy") + " from " + keyStack.join(".")); }); + } + function getFunctionOrClassInfo(fn, name, recurser) { + var prototypeMembers = getPrototypeMembers(fn, recurser); + var namespaceMembers = ts.flatMap(getEntriesOfObject(fn), function (_a) { + var key = _a.key, value = _a.value; + return getValueInfo(key, value, recurser); + }); + var toString = ts.cast(Function.prototype.toString.call(fn), ts.isString); + var source = ts.stringContains(toString, "{ [native code] }") ? getFunctionLength(fn) : toString; + return { kind: 2 /* FunctionOrClass */, name: name, source: source, namespaceMembers: namespaceMembers, prototypeMembers: prototypeMembers }; + } + var builtins = ts.memoize(function () { + var map = ts.createMap(); + for (var _i = 0, _a = getEntriesOfObject(global); _i < _a.length; _i++) { + var _b = _a[_i], key = _b.key, value = _b.value; + if (typeof value === "function" && typeof value.prototype === "object" && value !== Object) { + map.set(key, value); + } + } + return map; + }); + function getBuiltinType(name, value, recurser) { + return ts.isArray(value) + ? { name: name, kind: 1 /* Array */, inner: value.length && getValueInfo("element", ts.first(value), recurser) || anyValue(name) } + : ts.forEachEntry(builtins(), function (builtin, builtinName) { + return value instanceof builtin ? { kind: 0 /* Const */, name: name, typeName: builtinName } : undefined; + }); + } + function getPrototypeMembers(fn, recurser) { + var prototype = fn.prototype; + // tslint:disable-next-line no-unnecessary-type-assertion (TODO: update LKG and it will really be unnecessary) + return typeof prototype !== "object" || prototype === null ? ts.emptyArray : ts.mapDefined(getEntriesOfObject(prototype), function (_a) { + var key = _a.key, value = _a.value; + return key === "constructor" ? undefined : getValueInfo(key, value, recurser); + }); + } + var ignoredProperties = new Set(["arguments", "caller", "constructor", "eval", "super_"]); + var reservedFunctionProperties = new Set(Object.getOwnPropertyNames(ts.noop)); + function getEntriesOfObject(obj) { + var seen = ts.createMap(); + var entries = []; + var chain = obj; + while (!isNullOrUndefined(chain) && chain !== Object.prototype && chain !== Function.prototype) { + for (var _i = 0, _a = Object.getOwnPropertyNames(chain); _i < _a.length; _i++) { + var key = _a[_i]; + if (!isJsPrivate(key) && + !ignoredProperties.has(key) && + (typeof obj !== "function" || !reservedFunctionProperties.has(key)) && + // Don't add property from a higher prototype if it already exists in a lower one + ts.addToSeen(seen, key)) { + var value = safeGetPropertyOfObject(chain, key); + // Don't repeat "toString" that matches signature from Object.prototype + if (!(key === "toString" && typeof value === "function" && value.length === 0)) { + entries.push({ key: key, value: value }); + } + } + } + chain = Object.getPrototypeOf(chain); + } + return entries.sort(function (e1, e2) { return ts.compareStringsCaseSensitive(e1.key, e2.key); }); + } + function getFunctionLength(fn) { + return ts.tryCast(safeGetPropertyOfObject(fn, "length"), ts.isNumber) || 0; + } + function safeGetPropertyOfObject(obj, key) { + var desc = Object.getOwnPropertyDescriptor(obj, key); + return desc && desc.value; + } + function isNullOrUndefined(value) { + return value == null; // tslint:disable-line + } + function anyValue(name, comment) { + return { kind: 0 /* Const */, name: name, typeName: "any", comment: comment }; + } + function isJsPrivate(name) { + return name.startsWith("_"); + } + ts.isJsPrivate = isJsPrivate; + function tryRequire(fileNameToRequire) { + try { + return require(fileNameToRequire); + } + catch (_a) { + return undefined; + } + } +})(ts || (ts = {})); +//# sourceMappingURL=compiler.js.map +"use strict"; +var __assign = (this && this.__assign) || function () { + __assign = Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; + }; + return __assign.apply(this, arguments); +}; +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +var ts; +(function (ts) { + var ScriptSnapshot; + (function (ScriptSnapshot) { + var StringScriptSnapshot = /** @class */ (function () { + function StringScriptSnapshot(text) { + this.text = text; + } + StringScriptSnapshot.prototype.getText = function (start, end) { + return start === 0 && end === this.text.length + ? this.text + : this.text.substring(start, end); + }; + StringScriptSnapshot.prototype.getLength = function () { + return this.text.length; + }; + StringScriptSnapshot.prototype.getChangeRange = function () { + // Text-based snapshots do not support incremental parsing. Return undefined + // to signal that to the caller. + return undefined; + }; + return StringScriptSnapshot; + }()); + function fromString(text) { + return new StringScriptSnapshot(text); + } + ScriptSnapshot.fromString = fromString; + })(ScriptSnapshot = ts.ScriptSnapshot || (ts.ScriptSnapshot = {})); + /* @internal */ + ts.emptyOptions = {}; + var HighlightSpanKind; + (function (HighlightSpanKind) { + HighlightSpanKind["none"] = "none"; + HighlightSpanKind["definition"] = "definition"; + HighlightSpanKind["reference"] = "reference"; + HighlightSpanKind["writtenReference"] = "writtenReference"; + })(HighlightSpanKind = ts.HighlightSpanKind || (ts.HighlightSpanKind = {})); + var IndentStyle; + (function (IndentStyle) { + IndentStyle[IndentStyle["None"] = 0] = "None"; + IndentStyle[IndentStyle["Block"] = 1] = "Block"; + IndentStyle[IndentStyle["Smart"] = 2] = "Smart"; + })(IndentStyle = ts.IndentStyle || (ts.IndentStyle = {})); + function getDefaultFormatCodeSettings(newLineCharacter) { + return { + indentSize: 4, + tabSize: 4, + newLineCharacter: newLineCharacter || "\n", + convertTabsToSpaces: true, + indentStyle: IndentStyle.Smart, + insertSpaceAfterConstructor: false, + insertSpaceAfterCommaDelimiter: true, + insertSpaceAfterSemicolonInForStatements: true, + insertSpaceBeforeAndAfterBinaryOperators: true, + insertSpaceAfterKeywordsInControlFlowStatements: true, + insertSpaceAfterFunctionKeywordForAnonymousFunctions: false, + insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: false, + insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: false, + insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces: true, + insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: false, + insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces: false, + insertSpaceBeforeFunctionParenthesis: false, + placeOpenBraceOnNewLineForFunctions: false, + placeOpenBraceOnNewLineForControlBlocks: false, + }; + } + ts.getDefaultFormatCodeSettings = getDefaultFormatCodeSettings; + /* @internal */ + ts.testFormatSettings = getDefaultFormatCodeSettings("\n"); + var SymbolDisplayPartKind; + (function (SymbolDisplayPartKind) { + SymbolDisplayPartKind[SymbolDisplayPartKind["aliasName"] = 0] = "aliasName"; + SymbolDisplayPartKind[SymbolDisplayPartKind["className"] = 1] = "className"; + SymbolDisplayPartKind[SymbolDisplayPartKind["enumName"] = 2] = "enumName"; + SymbolDisplayPartKind[SymbolDisplayPartKind["fieldName"] = 3] = "fieldName"; + SymbolDisplayPartKind[SymbolDisplayPartKind["interfaceName"] = 4] = "interfaceName"; + SymbolDisplayPartKind[SymbolDisplayPartKind["keyword"] = 5] = "keyword"; + SymbolDisplayPartKind[SymbolDisplayPartKind["lineBreak"] = 6] = "lineBreak"; + SymbolDisplayPartKind[SymbolDisplayPartKind["numericLiteral"] = 7] = "numericLiteral"; + SymbolDisplayPartKind[SymbolDisplayPartKind["stringLiteral"] = 8] = "stringLiteral"; + SymbolDisplayPartKind[SymbolDisplayPartKind["localName"] = 9] = "localName"; + SymbolDisplayPartKind[SymbolDisplayPartKind["methodName"] = 10] = "methodName"; + SymbolDisplayPartKind[SymbolDisplayPartKind["moduleName"] = 11] = "moduleName"; + SymbolDisplayPartKind[SymbolDisplayPartKind["operator"] = 12] = "operator"; + SymbolDisplayPartKind[SymbolDisplayPartKind["parameterName"] = 13] = "parameterName"; + SymbolDisplayPartKind[SymbolDisplayPartKind["propertyName"] = 14] = "propertyName"; + SymbolDisplayPartKind[SymbolDisplayPartKind["punctuation"] = 15] = "punctuation"; + SymbolDisplayPartKind[SymbolDisplayPartKind["space"] = 16] = "space"; + SymbolDisplayPartKind[SymbolDisplayPartKind["text"] = 17] = "text"; + SymbolDisplayPartKind[SymbolDisplayPartKind["typeParameterName"] = 18] = "typeParameterName"; + SymbolDisplayPartKind[SymbolDisplayPartKind["enumMemberName"] = 19] = "enumMemberName"; + SymbolDisplayPartKind[SymbolDisplayPartKind["functionName"] = 20] = "functionName"; + SymbolDisplayPartKind[SymbolDisplayPartKind["regularExpressionLiteral"] = 21] = "regularExpressionLiteral"; + })(SymbolDisplayPartKind = ts.SymbolDisplayPartKind || (ts.SymbolDisplayPartKind = {})); + var OutliningSpanKind; + (function (OutliningSpanKind) { + /** Single or multi-line comments */ + OutliningSpanKind["Comment"] = "comment"; + /** Sections marked by '// #region' and '// #endregion' comments */ + OutliningSpanKind["Region"] = "region"; + /** Declarations and expressions */ + OutliningSpanKind["Code"] = "code"; + /** Contiguous blocks of import declarations */ + OutliningSpanKind["Imports"] = "imports"; + })(OutliningSpanKind = ts.OutliningSpanKind || (ts.OutliningSpanKind = {})); + var OutputFileType; + (function (OutputFileType) { + OutputFileType[OutputFileType["JavaScript"] = 0] = "JavaScript"; + OutputFileType[OutputFileType["SourceMap"] = 1] = "SourceMap"; + OutputFileType[OutputFileType["Declaration"] = 2] = "Declaration"; + })(OutputFileType = ts.OutputFileType || (ts.OutputFileType = {})); + var EndOfLineState; + (function (EndOfLineState) { + EndOfLineState[EndOfLineState["None"] = 0] = "None"; + EndOfLineState[EndOfLineState["InMultiLineCommentTrivia"] = 1] = "InMultiLineCommentTrivia"; + EndOfLineState[EndOfLineState["InSingleQuoteStringLiteral"] = 2] = "InSingleQuoteStringLiteral"; + EndOfLineState[EndOfLineState["InDoubleQuoteStringLiteral"] = 3] = "InDoubleQuoteStringLiteral"; + EndOfLineState[EndOfLineState["InTemplateHeadOrNoSubstitutionTemplate"] = 4] = "InTemplateHeadOrNoSubstitutionTemplate"; + EndOfLineState[EndOfLineState["InTemplateMiddleOrTail"] = 5] = "InTemplateMiddleOrTail"; + EndOfLineState[EndOfLineState["InTemplateSubstitutionPosition"] = 6] = "InTemplateSubstitutionPosition"; + })(EndOfLineState = ts.EndOfLineState || (ts.EndOfLineState = {})); + var TokenClass; + (function (TokenClass) { + TokenClass[TokenClass["Punctuation"] = 0] = "Punctuation"; + TokenClass[TokenClass["Keyword"] = 1] = "Keyword"; + TokenClass[TokenClass["Operator"] = 2] = "Operator"; + TokenClass[TokenClass["Comment"] = 3] = "Comment"; + TokenClass[TokenClass["Whitespace"] = 4] = "Whitespace"; + TokenClass[TokenClass["Identifier"] = 5] = "Identifier"; + TokenClass[TokenClass["NumberLiteral"] = 6] = "NumberLiteral"; + TokenClass[TokenClass["BigIntLiteral"] = 7] = "BigIntLiteral"; + TokenClass[TokenClass["StringLiteral"] = 8] = "StringLiteral"; + TokenClass[TokenClass["RegExpLiteral"] = 9] = "RegExpLiteral"; + })(TokenClass = ts.TokenClass || (ts.TokenClass = {})); + var ScriptElementKind; + (function (ScriptElementKind) { + ScriptElementKind["unknown"] = ""; + ScriptElementKind["warning"] = "warning"; + /** predefined type (void) or keyword (class) */ + ScriptElementKind["keyword"] = "keyword"; + /** top level script node */ + ScriptElementKind["scriptElement"] = "script"; + /** module foo {} */ + ScriptElementKind["moduleElement"] = "module"; + /** class X {} */ + ScriptElementKind["classElement"] = "class"; + /** var x = class X {} */ + ScriptElementKind["localClassElement"] = "local class"; + /** interface Y {} */ + ScriptElementKind["interfaceElement"] = "interface"; + /** type T = ... */ + ScriptElementKind["typeElement"] = "type"; + /** enum E */ + ScriptElementKind["enumElement"] = "enum"; + ScriptElementKind["enumMemberElement"] = "enum member"; + /** + * Inside module and script only + * const v = .. + */ + ScriptElementKind["variableElement"] = "var"; + /** Inside function */ + ScriptElementKind["localVariableElement"] = "local var"; + /** + * Inside module and script only + * function f() { } + */ + ScriptElementKind["functionElement"] = "function"; + /** Inside function */ + ScriptElementKind["localFunctionElement"] = "local function"; + /** class X { [public|private]* foo() {} } */ + ScriptElementKind["memberFunctionElement"] = "method"; + /** class X { [public|private]* [get|set] foo:number; } */ + ScriptElementKind["memberGetAccessorElement"] = "getter"; + ScriptElementKind["memberSetAccessorElement"] = "setter"; + /** + * class X { [public|private]* foo:number; } + * interface Y { foo:number; } + */ + ScriptElementKind["memberVariableElement"] = "property"; + /** class X { constructor() { } } */ + ScriptElementKind["constructorImplementationElement"] = "constructor"; + /** interface Y { ():number; } */ + ScriptElementKind["callSignatureElement"] = "call"; + /** interface Y { []:number; } */ + ScriptElementKind["indexSignatureElement"] = "index"; + /** interface Y { new():Y; } */ + ScriptElementKind["constructSignatureElement"] = "construct"; + /** function foo(*Y*: string) */ + ScriptElementKind["parameterElement"] = "parameter"; + ScriptElementKind["typeParameterElement"] = "type parameter"; + ScriptElementKind["primitiveType"] = "primitive type"; + ScriptElementKind["label"] = "label"; + ScriptElementKind["alias"] = "alias"; + ScriptElementKind["constElement"] = "const"; + ScriptElementKind["letElement"] = "let"; + ScriptElementKind["directory"] = "directory"; + ScriptElementKind["externalModuleName"] = "external module name"; + /** + * + */ + ScriptElementKind["jsxAttribute"] = "JSX attribute"; + /** String literal */ + ScriptElementKind["string"] = "string"; + })(ScriptElementKind = ts.ScriptElementKind || (ts.ScriptElementKind = {})); + var ScriptElementKindModifier; + (function (ScriptElementKindModifier) { + ScriptElementKindModifier["none"] = ""; + ScriptElementKindModifier["publicMemberModifier"] = "public"; + ScriptElementKindModifier["privateMemberModifier"] = "private"; + ScriptElementKindModifier["protectedMemberModifier"] = "protected"; + ScriptElementKindModifier["exportedModifier"] = "export"; + ScriptElementKindModifier["ambientModifier"] = "declare"; + ScriptElementKindModifier["staticModifier"] = "static"; + ScriptElementKindModifier["abstractModifier"] = "abstract"; + ScriptElementKindModifier["optionalModifier"] = "optional"; + ScriptElementKindModifier["dtsModifier"] = ".d.ts"; + ScriptElementKindModifier["tsModifier"] = ".ts"; + ScriptElementKindModifier["tsxModifier"] = ".tsx"; + ScriptElementKindModifier["jsModifier"] = ".js"; + ScriptElementKindModifier["jsxModifier"] = ".jsx"; + ScriptElementKindModifier["jsonModifier"] = ".json"; + })(ScriptElementKindModifier = ts.ScriptElementKindModifier || (ts.ScriptElementKindModifier = {})); + var ClassificationTypeNames; + (function (ClassificationTypeNames) { + ClassificationTypeNames["comment"] = "comment"; + ClassificationTypeNames["identifier"] = "identifier"; + ClassificationTypeNames["keyword"] = "keyword"; + ClassificationTypeNames["numericLiteral"] = "number"; + ClassificationTypeNames["bigintLiteral"] = "bigint"; + ClassificationTypeNames["operator"] = "operator"; + ClassificationTypeNames["stringLiteral"] = "string"; + ClassificationTypeNames["whiteSpace"] = "whitespace"; + ClassificationTypeNames["text"] = "text"; + ClassificationTypeNames["punctuation"] = "punctuation"; + ClassificationTypeNames["className"] = "class name"; + ClassificationTypeNames["enumName"] = "enum name"; + ClassificationTypeNames["interfaceName"] = "interface name"; + ClassificationTypeNames["moduleName"] = "module name"; + ClassificationTypeNames["typeParameterName"] = "type parameter name"; + ClassificationTypeNames["typeAliasName"] = "type alias name"; + ClassificationTypeNames["parameterName"] = "parameter name"; + ClassificationTypeNames["docCommentTagName"] = "doc comment tag name"; + ClassificationTypeNames["jsxOpenTagName"] = "jsx open tag name"; + ClassificationTypeNames["jsxCloseTagName"] = "jsx close tag name"; + ClassificationTypeNames["jsxSelfClosingTagName"] = "jsx self closing tag name"; + ClassificationTypeNames["jsxAttribute"] = "jsx attribute"; + ClassificationTypeNames["jsxText"] = "jsx text"; + ClassificationTypeNames["jsxAttributeStringLiteralValue"] = "jsx attribute string literal value"; + })(ClassificationTypeNames = ts.ClassificationTypeNames || (ts.ClassificationTypeNames = {})); + var ClassificationType; + (function (ClassificationType) { + ClassificationType[ClassificationType["comment"] = 1] = "comment"; + ClassificationType[ClassificationType["identifier"] = 2] = "identifier"; + ClassificationType[ClassificationType["keyword"] = 3] = "keyword"; + ClassificationType[ClassificationType["numericLiteral"] = 4] = "numericLiteral"; + ClassificationType[ClassificationType["operator"] = 5] = "operator"; + ClassificationType[ClassificationType["stringLiteral"] = 6] = "stringLiteral"; + ClassificationType[ClassificationType["regularExpressionLiteral"] = 7] = "regularExpressionLiteral"; + ClassificationType[ClassificationType["whiteSpace"] = 8] = "whiteSpace"; + ClassificationType[ClassificationType["text"] = 9] = "text"; + ClassificationType[ClassificationType["punctuation"] = 10] = "punctuation"; + ClassificationType[ClassificationType["className"] = 11] = "className"; + ClassificationType[ClassificationType["enumName"] = 12] = "enumName"; + ClassificationType[ClassificationType["interfaceName"] = 13] = "interfaceName"; + ClassificationType[ClassificationType["moduleName"] = 14] = "moduleName"; + ClassificationType[ClassificationType["typeParameterName"] = 15] = "typeParameterName"; + ClassificationType[ClassificationType["typeAliasName"] = 16] = "typeAliasName"; + ClassificationType[ClassificationType["parameterName"] = 17] = "parameterName"; + ClassificationType[ClassificationType["docCommentTagName"] = 18] = "docCommentTagName"; + ClassificationType[ClassificationType["jsxOpenTagName"] = 19] = "jsxOpenTagName"; + ClassificationType[ClassificationType["jsxCloseTagName"] = 20] = "jsxCloseTagName"; + ClassificationType[ClassificationType["jsxSelfClosingTagName"] = 21] = "jsxSelfClosingTagName"; + ClassificationType[ClassificationType["jsxAttribute"] = 22] = "jsxAttribute"; + ClassificationType[ClassificationType["jsxText"] = 23] = "jsxText"; + ClassificationType[ClassificationType["jsxAttributeStringLiteralValue"] = 24] = "jsxAttributeStringLiteralValue"; + ClassificationType[ClassificationType["bigintLiteral"] = 25] = "bigintLiteral"; + })(ClassificationType = ts.ClassificationType || (ts.ClassificationType = {})); +})(ts || (ts = {})); +// These utilities are common to multiple language service features. +/* @internal */ +var ts; +(function (ts) { + ts.scanner = ts.createScanner(6 /* Latest */, /*skipTrivia*/ true); + var SemanticMeaning; + (function (SemanticMeaning) { + SemanticMeaning[SemanticMeaning["None"] = 0] = "None"; + SemanticMeaning[SemanticMeaning["Value"] = 1] = "Value"; + SemanticMeaning[SemanticMeaning["Type"] = 2] = "Type"; + SemanticMeaning[SemanticMeaning["Namespace"] = 4] = "Namespace"; + SemanticMeaning[SemanticMeaning["All"] = 7] = "All"; + })(SemanticMeaning = ts.SemanticMeaning || (ts.SemanticMeaning = {})); + function getMeaningFromDeclaration(node) { + switch (node.kind) { + case 237 /* VariableDeclaration */: + return ts.isInJSFile(node) && ts.getJSDocEnumTag(node) ? 7 /* All */ : 1 /* Value */; + case 151 /* Parameter */: + case 186 /* BindingElement */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 275 /* PropertyAssignment */: + case 276 /* ShorthandPropertyAssignment */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 274 /* CatchClause */: + case 267 /* JsxAttribute */: + return 1 /* Value */; + case 150 /* TypeParameter */: + case 241 /* InterfaceDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 168 /* TypeLiteral */: + return 2 /* Type */; + case 304 /* JSDocTypedefTag */: + // If it has no name node, it shares the name with the value declaration below it. + return node.name === undefined ? 1 /* Value */ | 2 /* Type */ : 2 /* Type */; + case 278 /* EnumMember */: + case 240 /* ClassDeclaration */: + return 1 /* Value */ | 2 /* Type */; + case 244 /* ModuleDeclaration */: + if (ts.isAmbientModule(node)) { + return 4 /* Namespace */ | 1 /* Value */; + } + else if (ts.getModuleInstanceState(node) === 1 /* Instantiated */) { + return 4 /* Namespace */ | 1 /* Value */; + } + else { + return 4 /* Namespace */; + } + case 243 /* EnumDeclaration */: + case 252 /* NamedImports */: + case 253 /* ImportSpecifier */: + case 248 /* ImportEqualsDeclaration */: + case 249 /* ImportDeclaration */: + case 254 /* ExportAssignment */: + case 255 /* ExportDeclaration */: + return 7 /* All */; + // An external module can be a Value + case 279 /* SourceFile */: + return 4 /* Namespace */ | 1 /* Value */; + } + return 7 /* All */; + } + ts.getMeaningFromDeclaration = getMeaningFromDeclaration; + function getMeaningFromLocation(node) { + if (node.kind === 279 /* SourceFile */) { + return 1 /* Value */; + } + else if (node.parent.kind === 254 /* ExportAssignment */ || node.parent.kind === 259 /* ExternalModuleReference */) { + return 7 /* All */; + } + else if (isInRightSideOfInternalImportEqualsDeclaration(node)) { + return getMeaningFromRightHandSideOfImportEquals(node); + } + else if (ts.isDeclarationName(node)) { + return getMeaningFromDeclaration(node.parent); + } + else if (isTypeReference(node)) { + return 2 /* Type */; + } + else if (isNamespaceReference(node)) { + return 4 /* Namespace */; + } + else if (ts.isTypeParameterDeclaration(node.parent)) { + ts.Debug.assert(ts.isJSDocTemplateTag(node.parent.parent)); // Else would be handled by isDeclarationName + return 2 /* Type */; + } + else if (ts.isLiteralTypeNode(node.parent)) { + // This might be T["name"], which is actually referencing a property and not a type. So allow both meanings. + return 2 /* Type */ | 1 /* Value */; + } + else { + return 1 /* Value */; + } + } + ts.getMeaningFromLocation = getMeaningFromLocation; + function getMeaningFromRightHandSideOfImportEquals(node) { + // import a = |b|; // Namespace + // import a = |b.c|; // Value, type, namespace + // import a = |b.c|.d; // Namespace + var name = node.kind === 148 /* QualifiedName */ ? node : ts.isQualifiedName(node.parent) && node.parent.right === node ? node.parent : undefined; + return name && name.parent.kind === 248 /* ImportEqualsDeclaration */ ? 7 /* All */ : 4 /* Namespace */; + } + function isInRightSideOfInternalImportEqualsDeclaration(node) { + while (node.parent.kind === 148 /* QualifiedName */) { + node = node.parent; + } + return ts.isInternalModuleImportEqualsDeclaration(node.parent) && node.parent.moduleReference === node; + } + ts.isInRightSideOfInternalImportEqualsDeclaration = isInRightSideOfInternalImportEqualsDeclaration; + function isNamespaceReference(node) { + return isQualifiedNameNamespaceReference(node) || isPropertyAccessNamespaceReference(node); + } + function isQualifiedNameNamespaceReference(node) { + var root = node; + var isLastClause = true; + if (root.parent.kind === 148 /* QualifiedName */) { + while (root.parent && root.parent.kind === 148 /* QualifiedName */) { + root = root.parent; + } + isLastClause = root.right === node; + } + return root.parent.kind === 164 /* TypeReference */ && !isLastClause; + } + function isPropertyAccessNamespaceReference(node) { + var root = node; + var isLastClause = true; + if (root.parent.kind === 189 /* PropertyAccessExpression */) { + while (root.parent && root.parent.kind === 189 /* PropertyAccessExpression */) { + root = root.parent; + } + isLastClause = root.name === node; + } + if (!isLastClause && root.parent.kind === 211 /* ExpressionWithTypeArguments */ && root.parent.parent.kind === 273 /* HeritageClause */) { + var decl = root.parent.parent.parent; + return (decl.kind === 240 /* ClassDeclaration */ && root.parent.parent.token === 109 /* ImplementsKeyword */) || + (decl.kind === 241 /* InterfaceDeclaration */ && root.parent.parent.token === 86 /* ExtendsKeyword */); + } + return false; + } + function isTypeReference(node) { + if (ts.isRightSideOfQualifiedNameOrPropertyAccess(node)) { + node = node.parent; + } + switch (node.kind) { + case 100 /* ThisKeyword */: + return !ts.isExpressionNode(node); + case 178 /* ThisType */: + return true; + } + switch (node.parent.kind) { + case 164 /* TypeReference */: + return true; + case 183 /* ImportType */: + return !node.parent.isTypeOf; + case 211 /* ExpressionWithTypeArguments */: + return !ts.isExpressionWithTypeArgumentsInClassExtendsClause(node.parent); + } + return false; + } + function isCallExpressionTarget(node) { + return isCallOrNewExpressionTargetWorker(node, ts.isCallExpression); + } + ts.isCallExpressionTarget = isCallExpressionTarget; + function isNewExpressionTarget(node) { + return isCallOrNewExpressionTargetWorker(node, ts.isNewExpression); + } + ts.isNewExpressionTarget = isNewExpressionTarget; + function isCallOrNewExpressionTarget(node) { + return isCallOrNewExpressionTargetWorker(node, ts.isCallOrNewExpression); + } + ts.isCallOrNewExpressionTarget = isCallOrNewExpressionTarget; + function isCallOrNewExpressionTargetWorker(node, pred) { + var target = climbPastPropertyAccess(node); + return !!target && !!target.parent && pred(target.parent) && target.parent.expression === target; + } + function climbPastPropertyAccess(node) { + return isRightSideOfPropertyAccess(node) ? node.parent : node; + } + ts.climbPastPropertyAccess = climbPastPropertyAccess; + function getTargetLabel(referenceNode, labelName) { + while (referenceNode) { + if (referenceNode.kind === 233 /* LabeledStatement */ && referenceNode.label.escapedText === labelName) { + return referenceNode.label; + } + referenceNode = referenceNode.parent; + } + return undefined; + } + ts.getTargetLabel = getTargetLabel; + function hasPropertyAccessExpressionWithName(node, funcName) { + if (!ts.isPropertyAccessExpression(node.expression)) { + return false; + } + return node.expression.name.text === funcName; + } + ts.hasPropertyAccessExpressionWithName = hasPropertyAccessExpressionWithName; + function isJumpStatementTarget(node) { + return node.kind === 72 /* Identifier */ && ts.isBreakOrContinueStatement(node.parent) && node.parent.label === node; + } + ts.isJumpStatementTarget = isJumpStatementTarget; + function isLabelOfLabeledStatement(node) { + return node.kind === 72 /* Identifier */ && ts.isLabeledStatement(node.parent) && node.parent.label === node; + } + ts.isLabelOfLabeledStatement = isLabelOfLabeledStatement; + function isLabelName(node) { + return isLabelOfLabeledStatement(node) || isJumpStatementTarget(node); + } + ts.isLabelName = isLabelName; + function isTagName(node) { + return ts.isJSDocTag(node.parent) && node.parent.tagName === node; + } + ts.isTagName = isTagName; + function isRightSideOfQualifiedName(node) { + return node.parent.kind === 148 /* QualifiedName */ && node.parent.right === node; + } + ts.isRightSideOfQualifiedName = isRightSideOfQualifiedName; + function isRightSideOfPropertyAccess(node) { + return node && node.parent && node.parent.kind === 189 /* PropertyAccessExpression */ && node.parent.name === node; + } + ts.isRightSideOfPropertyAccess = isRightSideOfPropertyAccess; + function isNameOfModuleDeclaration(node) { + return node.parent.kind === 244 /* ModuleDeclaration */ && node.parent.name === node; + } + ts.isNameOfModuleDeclaration = isNameOfModuleDeclaration; + function isNameOfFunctionDeclaration(node) { + return node.kind === 72 /* Identifier */ && + ts.isFunctionLike(node.parent) && node.parent.name === node; + } + ts.isNameOfFunctionDeclaration = isNameOfFunctionDeclaration; + function isLiteralNameOfPropertyDeclarationOrIndexAccess(node) { + switch (node.parent.kind) { + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 275 /* PropertyAssignment */: + case 278 /* EnumMember */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 244 /* ModuleDeclaration */: + return ts.getNameOfDeclaration(node.parent) === node; + case 190 /* ElementAccessExpression */: + return node.parent.argumentExpression === node; + case 149 /* ComputedPropertyName */: + return true; + case 182 /* LiteralType */: + return node.parent.parent.kind === 180 /* IndexedAccessType */; + default: + return false; + } + } + ts.isLiteralNameOfPropertyDeclarationOrIndexAccess = isLiteralNameOfPropertyDeclarationOrIndexAccess; + function isExpressionOfExternalModuleImportEqualsDeclaration(node) { + return ts.isExternalModuleImportEqualsDeclaration(node.parent.parent) && + ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node; + } + ts.isExpressionOfExternalModuleImportEqualsDeclaration = isExpressionOfExternalModuleImportEqualsDeclaration; + function getContainerNode(node) { + if (ts.isJSDocTypeAlias(node)) { + // This doesn't just apply to the node immediately under the comment, but to everything in its parent's scope. + // node.parent = the JSDoc comment, node.parent.parent = the node having the comment. + // Then we get parent again in the loop. + node = node.parent.parent; + } + while (true) { + node = node.parent; + if (!node) { + return undefined; + } + switch (node.kind) { + case 279 /* SourceFile */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + case 243 /* EnumDeclaration */: + case 244 /* ModuleDeclaration */: + return node; + } + } + } + ts.getContainerNode = getContainerNode; + function getNodeKind(node) { + switch (node.kind) { + case 279 /* SourceFile */: + return ts.isExternalModule(node) ? "module" /* moduleElement */ : "script" /* scriptElement */; + case 244 /* ModuleDeclaration */: + return "module" /* moduleElement */; + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + return "class" /* classElement */; + case 241 /* InterfaceDeclaration */: return "interface" /* interfaceElement */; + case 242 /* TypeAliasDeclaration */: + case 297 /* JSDocCallbackTag */: + case 304 /* JSDocTypedefTag */: + return "type" /* typeElement */; + case 243 /* EnumDeclaration */: return "enum" /* enumElement */; + case 237 /* VariableDeclaration */: + return getKindOfVariableDeclaration(node); + case 186 /* BindingElement */: + return getKindOfVariableDeclaration(ts.getRootDeclaration(node)); + case 197 /* ArrowFunction */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + return "function" /* functionElement */; + case 158 /* GetAccessor */: return "getter" /* memberGetAccessorElement */; + case 159 /* SetAccessor */: return "setter" /* memberSetAccessorElement */; + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + return "method" /* memberFunctionElement */; + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + return "property" /* memberVariableElement */; + case 162 /* IndexSignature */: return "index" /* indexSignatureElement */; + case 161 /* ConstructSignature */: return "construct" /* constructSignatureElement */; + case 160 /* CallSignature */: return "call" /* callSignatureElement */; + case 157 /* Constructor */: return "constructor" /* constructorImplementationElement */; + case 150 /* TypeParameter */: return "type parameter" /* typeParameterElement */; + case 278 /* EnumMember */: return "enum member" /* enumMemberElement */; + case 151 /* Parameter */: return ts.hasModifier(node, 92 /* ParameterPropertyModifier */) ? "property" /* memberVariableElement */ : "parameter" /* parameterElement */; + case 248 /* ImportEqualsDeclaration */: + case 253 /* ImportSpecifier */: + case 257 /* ExportSpecifier */: + case 251 /* NamespaceImport */: + return "alias" /* alias */; + case 204 /* BinaryExpression */: + var kind = ts.getAssignmentDeclarationKind(node); + var right = node.right; + switch (kind) { + case 7 /* ObjectDefinePropertyValue */: + case 8 /* ObjectDefinePropertyExports */: + case 9 /* ObjectDefinePrototypeProperty */: + case 0 /* None */: + return "" /* unknown */; + case 1 /* ExportsProperty */: + case 2 /* ModuleExports */: + var rightKind = getNodeKind(right); + return rightKind === "" /* unknown */ ? "const" /* constElement */ : rightKind; + case 3 /* PrototypeProperty */: + return ts.isFunctionExpression(right) ? "method" /* memberFunctionElement */ : "property" /* memberVariableElement */; + case 4 /* ThisProperty */: + return "property" /* memberVariableElement */; // property + case 5 /* Property */: + // static method / property + return ts.isFunctionExpression(right) ? "method" /* memberFunctionElement */ : "property" /* memberVariableElement */; + case 6 /* Prototype */: + return "local class" /* localClassElement */; + default: { + ts.assertType(kind); + return "" /* unknown */; + } + } + case 72 /* Identifier */: + return ts.isImportClause(node.parent) ? "alias" /* alias */ : "" /* unknown */; + default: + return "" /* unknown */; + } + function getKindOfVariableDeclaration(v) { + return ts.isVarConst(v) + ? "const" /* constElement */ + : ts.isLet(v) + ? "let" /* letElement */ + : "var" /* variableElement */; + } + } + ts.getNodeKind = getNodeKind; + function isThis(node) { + switch (node.kind) { + case 100 /* ThisKeyword */: + // case SyntaxKind.ThisType: TODO: GH#9267 + return true; + case 72 /* Identifier */: + // 'this' as a parameter + return ts.identifierIsThisKeyword(node) && node.parent.kind === 151 /* Parameter */; + default: + return false; + } + } + ts.isThis = isThis; + // Matches the beginning of a triple slash directive + var tripleSlashDirectivePrefixRegex = /^\/\/\/\s*= range.end; + } + ts.startEndContainsRange = startEndContainsRange; + function rangeContainsStartEnd(range, start, end) { + return range.pos <= start && range.end >= end; + } + ts.rangeContainsStartEnd = rangeContainsStartEnd; + function rangeOverlapsWithStartEnd(r1, start, end) { + return startEndOverlapsWithStartEnd(r1.pos, r1.end, start, end); + } + ts.rangeOverlapsWithStartEnd = rangeOverlapsWithStartEnd; + function nodeOverlapsWithStartEnd(node, sourceFile, start, end) { + return startEndOverlapsWithStartEnd(node.getStart(sourceFile), node.end, start, end); + } + ts.nodeOverlapsWithStartEnd = nodeOverlapsWithStartEnd; + function startEndOverlapsWithStartEnd(start1, end1, start2, end2) { + var start = Math.max(start1, start2); + var end = Math.min(end1, end2); + return start < end; + } + ts.startEndOverlapsWithStartEnd = startEndOverlapsWithStartEnd; + /** + * Assumes `candidate.start <= position` holds. + */ + function positionBelongsToNode(candidate, position, sourceFile) { + ts.Debug.assert(candidate.pos <= position); + return position < candidate.end || !isCompletedNode(candidate, sourceFile); + } + ts.positionBelongsToNode = positionBelongsToNode; + function isCompletedNode(n, sourceFile) { + if (n === undefined || ts.nodeIsMissing(n)) { + return false; + } + switch (n.kind) { + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + case 243 /* EnumDeclaration */: + case 188 /* ObjectLiteralExpression */: + case 184 /* ObjectBindingPattern */: + case 168 /* TypeLiteral */: + case 218 /* Block */: + case 245 /* ModuleBlock */: + case 246 /* CaseBlock */: + case 252 /* NamedImports */: + case 256 /* NamedExports */: + return nodeEndsWith(n, 19 /* CloseBraceToken */, sourceFile); + case 274 /* CatchClause */: + return isCompletedNode(n.block, sourceFile); + case 192 /* NewExpression */: + if (!n.arguments) { + return true; + } + // falls through + case 191 /* CallExpression */: + case 195 /* ParenthesizedExpression */: + case 177 /* ParenthesizedType */: + return nodeEndsWith(n, 21 /* CloseParenToken */, sourceFile); + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + return isCompletedNode(n.type, sourceFile); + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 161 /* ConstructSignature */: + case 160 /* CallSignature */: + case 197 /* ArrowFunction */: + if (n.body) { + return isCompletedNode(n.body, sourceFile); + } + if (n.type) { + return isCompletedNode(n.type, sourceFile); + } + // Even though type parameters can be unclosed, we can get away with + // having at least a closing paren. + return hasChildOfKind(n, 21 /* CloseParenToken */, sourceFile); + case 244 /* ModuleDeclaration */: + return !!n.body && isCompletedNode(n.body, sourceFile); + case 222 /* IfStatement */: + if (n.elseStatement) { + return isCompletedNode(n.elseStatement, sourceFile); + } + return isCompletedNode(n.thenStatement, sourceFile); + case 221 /* ExpressionStatement */: + return isCompletedNode(n.expression, sourceFile) || + hasChildOfKind(n, 26 /* SemicolonToken */, sourceFile); + case 187 /* ArrayLiteralExpression */: + case 185 /* ArrayBindingPattern */: + case 190 /* ElementAccessExpression */: + case 149 /* ComputedPropertyName */: + case 170 /* TupleType */: + return nodeEndsWith(n, 23 /* CloseBracketToken */, sourceFile); + case 162 /* IndexSignature */: + if (n.type) { + return isCompletedNode(n.type, sourceFile); + } + return hasChildOfKind(n, 23 /* CloseBracketToken */, sourceFile); + case 271 /* CaseClause */: + case 272 /* DefaultClause */: + // there is no such thing as terminator token for CaseClause/DefaultClause so for simplicity always consider them non-completed + return false; + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + case 224 /* WhileStatement */: + return isCompletedNode(n.statement, sourceFile); + case 223 /* DoStatement */: + // rough approximation: if DoStatement has While keyword - then if node is completed is checking the presence of ')'; + return hasChildOfKind(n, 107 /* WhileKeyword */, sourceFile) + ? nodeEndsWith(n, 21 /* CloseParenToken */, sourceFile) + : isCompletedNode(n.statement, sourceFile); + case 167 /* TypeQuery */: + return isCompletedNode(n.exprName, sourceFile); + case 199 /* TypeOfExpression */: + case 198 /* DeleteExpression */: + case 200 /* VoidExpression */: + case 207 /* YieldExpression */: + case 208 /* SpreadElement */: + var unaryWordExpression = n; + return isCompletedNode(unaryWordExpression.expression, sourceFile); + case 193 /* TaggedTemplateExpression */: + return isCompletedNode(n.template, sourceFile); + case 206 /* TemplateExpression */: + var lastSpan = ts.lastOrUndefined(n.templateSpans); + return isCompletedNode(lastSpan, sourceFile); + case 216 /* TemplateSpan */: + return ts.nodeIsPresent(n.literal); + case 255 /* ExportDeclaration */: + case 249 /* ImportDeclaration */: + return ts.nodeIsPresent(n.moduleSpecifier); + case 202 /* PrefixUnaryExpression */: + return isCompletedNode(n.operand, sourceFile); + case 204 /* BinaryExpression */: + return isCompletedNode(n.right, sourceFile); + case 205 /* ConditionalExpression */: + return isCompletedNode(n.whenFalse, sourceFile); + default: + return true; + } + } + /* + * Checks if node ends with 'expectedLastToken'. + * If child at position 'length - 1' is 'SemicolonToken' it is skipped and 'expectedLastToken' is compared with child at position 'length - 2'. + */ + function nodeEndsWith(n, expectedLastToken, sourceFile) { + var children = n.getChildren(sourceFile); + if (children.length) { + var lastChild = ts.last(children); + if (lastChild.kind === expectedLastToken) { + return true; + } + else if (lastChild.kind === 26 /* SemicolonToken */ && children.length !== 1) { + return children[children.length - 2].kind === expectedLastToken; + } + } + return false; + } + function findListItemInfo(node) { + var list = findContainingList(node); + // It is possible at this point for syntaxList to be undefined, either if + // node.parent had no list child, or if none of its list children contained + // the span of node. If this happens, return undefined. The caller should + // handle this case. + if (!list) { + return undefined; + } + var children = list.getChildren(); + var listItemIndex = ts.indexOfNode(children, node); + return { + listItemIndex: listItemIndex, + list: list + }; + } + ts.findListItemInfo = findListItemInfo; + function hasChildOfKind(n, kind, sourceFile) { + return !!findChildOfKind(n, kind, sourceFile); + } + ts.hasChildOfKind = hasChildOfKind; + function findChildOfKind(n, kind, sourceFile) { + return ts.find(n.getChildren(sourceFile), function (c) { return c.kind === kind; }); + } + ts.findChildOfKind = findChildOfKind; + function findContainingList(node) { + // The node might be a list element (nonsynthetic) or a comma (synthetic). Either way, it will + // be parented by the container of the SyntaxList, not the SyntaxList itself. + // In order to find the list item index, we first need to locate SyntaxList itself and then search + // for the position of the relevant node (or comma). + var syntaxList = ts.find(node.parent.getChildren(), function (c) { return ts.isSyntaxList(c) && rangeContainsRange(c, node); }); + // Either we didn't find an appropriate list, or the list must contain us. + ts.Debug.assert(!syntaxList || ts.contains(syntaxList.getChildren(), node)); + return syntaxList; + } + ts.findContainingList = findContainingList; + /** + * Gets the token whose text has range [start, end) and + * position >= start and (position < end or (position === end && token is literal or keyword or identifier)) + */ + function getTouchingPropertyName(sourceFile, position) { + return getTouchingToken(sourceFile, position, function (n) { return ts.isPropertyNameLiteral(n) || ts.isKeyword(n.kind); }); + } + ts.getTouchingPropertyName = getTouchingPropertyName; + /** + * Returns the token if position is in [start, end). + * If position === end, returns the preceding token if includeItemAtEndPosition(previousToken) === true + */ + function getTouchingToken(sourceFile, position, includePrecedingTokenAtEndPosition) { + return getTokenAtPositionWorker(sourceFile, position, /*allowPositionInLeadingTrivia*/ false, includePrecedingTokenAtEndPosition, /*includeEndPosition*/ false); + } + ts.getTouchingToken = getTouchingToken; + /** Returns a token if position is in [start-of-leading-trivia, end) */ + function getTokenAtPosition(sourceFile, position) { + return getTokenAtPositionWorker(sourceFile, position, /*allowPositionInLeadingTrivia*/ true, /*includePrecedingTokenAtEndPosition*/ undefined, /*includeEndPosition*/ false); + } + ts.getTokenAtPosition = getTokenAtPosition; + /** Get the token whose text contains the position */ + function getTokenAtPositionWorker(sourceFile, position, allowPositionInLeadingTrivia, includePrecedingTokenAtEndPosition, includeEndPosition) { + var current = sourceFile; + outer: while (true) { + // find the child that contains 'position' + for (var _i = 0, _a = current.getChildren(sourceFile); _i < _a.length; _i++) { + var child = _a[_i]; + var start = allowPositionInLeadingTrivia ? child.getFullStart() : child.getStart(sourceFile, /*includeJsDoc*/ true); + if (start > position) { + // If this child begins after position, then all subsequent children will as well. + break; + } + var end = child.getEnd(); + if (position < end || (position === end && (child.kind === 1 /* EndOfFileToken */ || includeEndPosition))) { + current = child; + continue outer; + } + else if (includePrecedingTokenAtEndPosition && end === position) { + var previousToken = findPrecedingToken(position, sourceFile, child); + if (previousToken && includePrecedingTokenAtEndPosition(previousToken)) { + return previousToken; + } + } + } + return current; + } + } + /** + * The token on the left of the position is the token that strictly includes the position + * or sits to the left of the cursor if it is on a boundary. For example + * + * fo|o -> will return foo + * foo |bar -> will return foo + * + */ + function findTokenOnLeftOfPosition(file, position) { + // Ideally, getTokenAtPosition should return a token. However, it is currently + // broken, so we do a check to make sure the result was indeed a token. + var tokenAtPosition = getTokenAtPosition(file, position); + if (ts.isToken(tokenAtPosition) && position > tokenAtPosition.getStart(file) && position < tokenAtPosition.getEnd()) { + return tokenAtPosition; + } + return findPrecedingToken(position, file); + } + ts.findTokenOnLeftOfPosition = findTokenOnLeftOfPosition; + function findNextToken(previousToken, parent, sourceFile) { + return find(parent); + function find(n) { + if (ts.isToken(n) && n.pos === previousToken.end) { + // this is token that starts at the end of previous token - return it + return n; + } + return ts.firstDefined(n.getChildren(), function (child) { + var shouldDiveInChildNode = + // previous token is enclosed somewhere in the child + (child.pos <= previousToken.pos && child.end > previousToken.end) || + // previous token ends exactly at the beginning of child + (child.pos === previousToken.end); + return shouldDiveInChildNode && nodeHasTokens(child, sourceFile) ? find(child) : undefined; + }); + } + } + ts.findNextToken = findNextToken; + /** + * Finds the rightmost token satisfying `token.end <= position`, + * excluding `JsxText` tokens containing only whitespace. + */ + function findPrecedingToken(position, sourceFile, startNode, excludeJsdoc) { + var result = find(startNode || sourceFile); + ts.Debug.assert(!(result && isWhiteSpaceOnlyJsxText(result))); + return result; + function find(n) { + if (isNonWhitespaceToken(n) && n.kind !== 1 /* EndOfFileToken */) { + return n; + } + var children = n.getChildren(sourceFile); + for (var i = 0; i < children.length; i++) { + var child = children[i]; + // Note that the span of a node's tokens is [node.getStart(...), node.end). + // Given that `position < child.end` and child has constituent tokens, we distinguish these cases: + // 1) `position` precedes `child`'s tokens or `child` has no tokens (ie: in a comment or whitespace preceding `child`): + // we need to find the last token in a previous child. + // 2) `position` is within the same span: we recurse on `child`. + if (position < child.end) { + var start = child.getStart(sourceFile, /*includeJsDoc*/ !excludeJsdoc); + var lookInPreviousChild = (start >= position) || // cursor in the leading trivia + !nodeHasTokens(child, sourceFile) || + isWhiteSpaceOnlyJsxText(child); + if (lookInPreviousChild) { + // actual start of the node is past the position - previous token should be at the end of previous child + var candidate_1 = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ i, sourceFile); + return candidate_1 && findRightmostToken(candidate_1, sourceFile); + } + else { + // candidate should be in this node + return find(child); + } + } + } + ts.Debug.assert(startNode !== undefined || n.kind === 279 /* SourceFile */ || n.kind === 1 /* EndOfFileToken */ || ts.isJSDocCommentContainingNode(n)); + // Here we know that none of child token nodes embrace the position, + // the only known case is when position is at the end of the file. + // Try to find the rightmost token in the file without filtering. + // Namely we are skipping the check: 'position < node.end' + var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ children.length, sourceFile); + return candidate && findRightmostToken(candidate, sourceFile); + } + } + ts.findPrecedingToken = findPrecedingToken; + function isNonWhitespaceToken(n) { + return ts.isToken(n) && !isWhiteSpaceOnlyJsxText(n); + } + function findRightmostToken(n, sourceFile) { + if (isNonWhitespaceToken(n)) { + return n; + } + var children = n.getChildren(sourceFile); + var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ children.length, sourceFile); + return candidate && findRightmostToken(candidate, sourceFile); + } + /** + * Finds the rightmost child to the left of `children[exclusiveStartPosition]` which is a non-all-whitespace token or has constituent tokens. + */ + function findRightmostChildNodeWithTokens(children, exclusiveStartPosition, sourceFile) { + for (var i = exclusiveStartPosition - 1; i >= 0; i--) { + var child = children[i]; + if (isWhiteSpaceOnlyJsxText(child)) { + ts.Debug.assert(i > 0, "`JsxText` tokens should not be the first child of `JsxElement | JsxSelfClosingElement`"); + } + else if (nodeHasTokens(children[i], sourceFile)) { + return children[i]; + } + } + } + function isInString(sourceFile, position, previousToken) { + if (previousToken === void 0) { previousToken = findPrecedingToken(position, sourceFile); } + if (previousToken && ts.isStringTextContainingNode(previousToken)) { + var start = previousToken.getStart(sourceFile); + var end = previousToken.getEnd(); + // To be "in" one of these literals, the position has to be: + // 1. entirely within the token text. + // 2. at the end position of an unterminated token. + // 3. at the end of a regular expression (due to trailing flags like '/foo/g'). + if (start < position && position < end) { + return true; + } + if (position === end) { + return !!previousToken.isUnterminated; + } + } + return false; + } + ts.isInString = isInString; + /** + * returns true if the position is in between the open and close elements of an JSX expression. + */ + function isInsideJsxElementOrAttribute(sourceFile, position) { + var token = getTokenAtPosition(sourceFile, position); + if (!token) { + return false; + } + if (token.kind === 11 /* JsxText */) { + return true; + } + //
      Hello |
      + if (token.kind === 28 /* LessThanToken */ && token.parent.kind === 11 /* JsxText */) { + return true; + } + //
      { |
      or
      + if (token.kind === 28 /* LessThanToken */ && token.parent.kind === 270 /* JsxExpression */) { + return true; + } + //
      { + // | + // } < /div> + if (token && token.kind === 19 /* CloseBraceToken */ && token.parent.kind === 270 /* JsxExpression */) { + return true; + } + //
      |
      + if (token.kind === 28 /* LessThanToken */ && token.parent.kind === 263 /* JsxClosingElement */) { + return true; + } + return false; + } + ts.isInsideJsxElementOrAttribute = isInsideJsxElementOrAttribute; + function isWhiteSpaceOnlyJsxText(node) { + return ts.isJsxText(node) && node.containsOnlyWhiteSpaces; + } + function isInTemplateString(sourceFile, position) { + var token = getTokenAtPosition(sourceFile, position); + return ts.isTemplateLiteralKind(token.kind) && position > token.getStart(sourceFile); + } + ts.isInTemplateString = isInTemplateString; + function isInJSXText(sourceFile, position) { + var token = getTokenAtPosition(sourceFile, position); + if (ts.isJsxText(token)) { + return true; + } + if (token.kind === 18 /* OpenBraceToken */ && ts.isJsxExpression(token.parent) && ts.isJsxElement(token.parent.parent)) { + return true; + } + if (token.kind === 28 /* LessThanToken */ && ts.isJsxOpeningLikeElement(token.parent) && ts.isJsxElement(token.parent.parent)) { + return true; + } + return false; + } + ts.isInJSXText = isInJSXText; + function findPrecedingMatchingToken(token, matchingTokenKind, sourceFile) { + var tokenKind = token.kind; + var remainingMatchingTokens = 0; + while (true) { + var preceding = findPrecedingToken(token.getFullStart(), sourceFile); + if (!preceding) { + return undefined; + } + token = preceding; + if (token.kind === matchingTokenKind) { + if (remainingMatchingTokens === 0) { + return token; + } + remainingMatchingTokens--; + } + else if (token.kind === tokenKind) { + remainingMatchingTokens++; + } + } + } + ts.findPrecedingMatchingToken = findPrecedingMatchingToken; + function isPossiblyTypeArgumentPosition(token, sourceFile, checker) { + var info = getPossibleTypeArgumentsInfo(token, sourceFile); + return info !== undefined && (ts.isPartOfTypeNode(info.called) || + getPossibleGenericSignatures(info.called, info.nTypeArguments, checker).length !== 0 || + isPossiblyTypeArgumentPosition(info.called, sourceFile, checker)); + } + ts.isPossiblyTypeArgumentPosition = isPossiblyTypeArgumentPosition; + function getPossibleGenericSignatures(called, typeArgumentCount, checker) { + var type = checker.getTypeAtLocation(called); + var signatures = ts.isNewExpression(called.parent) ? type.getConstructSignatures() : type.getCallSignatures(); + return signatures.filter(function (candidate) { return !!candidate.typeParameters && candidate.typeParameters.length >= typeArgumentCount; }); + } + ts.getPossibleGenericSignatures = getPossibleGenericSignatures; + // Get info for an expression like `f <` that may be the start of type arguments. + function getPossibleTypeArgumentsInfo(tokenIn, sourceFile) { + var token = tokenIn; + // This function determines if the node could be type argument position + // Since during editing, when type argument list is not complete, + // the tree could be of any shape depending on the tokens parsed before current node, + // scanning of the previous identifier followed by "<" before current node would give us better result + // Note that we also balance out the already provided type arguments, arrays, object literals while doing so + var remainingLessThanTokens = 0; + var nTypeArguments = 0; + while (token) { + switch (token.kind) { + case 28 /* LessThanToken */: + // Found the beginning of the generic argument expression + token = findPrecedingToken(token.getFullStart(), sourceFile); + if (!token || !ts.isIdentifier(token)) + return undefined; + if (!remainingLessThanTokens) { + return ts.isDeclarationName(token) ? undefined : { called: token, nTypeArguments: nTypeArguments }; + } + remainingLessThanTokens--; + break; + case 48 /* GreaterThanGreaterThanGreaterThanToken */: + remainingLessThanTokens = +3; + break; + case 47 /* GreaterThanGreaterThanToken */: + remainingLessThanTokens = +2; + break; + case 30 /* GreaterThanToken */: + remainingLessThanTokens++; + break; + case 19 /* CloseBraceToken */: + // This can be object type, skip until we find the matching open brace token + // Skip until the matching open brace token + token = findPrecedingMatchingToken(token, 18 /* OpenBraceToken */, sourceFile); + if (!token) + return undefined; + break; + case 21 /* CloseParenToken */: + // This can be object type, skip until we find the matching open brace token + // Skip until the matching open brace token + token = findPrecedingMatchingToken(token, 20 /* OpenParenToken */, sourceFile); + if (!token) + return undefined; + break; + case 23 /* CloseBracketToken */: + // This can be object type, skip until we find the matching open brace token + // Skip until the matching open brace token + token = findPrecedingMatchingToken(token, 22 /* OpenBracketToken */, sourceFile); + if (!token) + return undefined; + break; + // Valid tokens in a type name. Skip. + case 27 /* CommaToken */: + nTypeArguments++; + break; + case 37 /* EqualsGreaterThanToken */: + case 72 /* Identifier */: + case 10 /* StringLiteral */: + case 8 /* NumericLiteral */: + case 9 /* BigIntLiteral */: + case 102 /* TrueKeyword */: + case 87 /* FalseKeyword */: + case 104 /* TypeOfKeyword */: + case 86 /* ExtendsKeyword */: + case 129 /* KeyOfKeyword */: + case 24 /* DotToken */: + case 50 /* BarToken */: + case 56 /* QuestionToken */: + case 57 /* ColonToken */: + break; + default: + if (ts.isTypeNode(token)) { + break; + } + // Invalid token in type + return undefined; + } + token = findPrecedingToken(token.getFullStart(), sourceFile); + } + return undefined; + } + ts.getPossibleTypeArgumentsInfo = getPossibleTypeArgumentsInfo; + /** + * Returns true if the cursor at position in sourceFile is within a comment. + * + * @param tokenAtPosition Must equal `getTokenAtPosition(sourceFile, position) + * @param predicate Additional predicate to test on the comment range. + */ + function isInComment(sourceFile, position, tokenAtPosition) { + return ts.formatting.getRangeOfEnclosingComment(sourceFile, position, /*precedingToken*/ undefined, tokenAtPosition); + } + ts.isInComment = isInComment; + function hasDocComment(sourceFile, position) { + var token = getTokenAtPosition(sourceFile, position); + return !!ts.findAncestor(token, ts.isJSDoc); + } + ts.hasDocComment = hasDocComment; + function nodeHasTokens(n, sourceFile) { + // If we have a token or node that has a non-zero width, it must have tokens. + // Note: getWidth() does not take trivia into account. + return n.kind === 1 /* EndOfFileToken */ ? !!n.jsDoc : n.getWidth(sourceFile) !== 0; + } + function getNodeModifiers(node) { + var flags = ts.isDeclaration(node) ? ts.getCombinedModifierFlags(node) : 0 /* None */; + var result = []; + if (flags & 8 /* Private */) + result.push("private" /* privateMemberModifier */); + if (flags & 16 /* Protected */) + result.push("protected" /* protectedMemberModifier */); + if (flags & 4 /* Public */) + result.push("public" /* publicMemberModifier */); + if (flags & 32 /* Static */) + result.push("static" /* staticModifier */); + if (flags & 128 /* Abstract */) + result.push("abstract" /* abstractModifier */); + if (flags & 1 /* Export */) + result.push("export" /* exportedModifier */); + if (node.flags & 4194304 /* Ambient */) + result.push("declare" /* ambientModifier */); + return result.length > 0 ? result.join(",") : "" /* none */; + } + ts.getNodeModifiers = getNodeModifiers; + function getTypeArgumentOrTypeParameterList(node) { + if (node.kind === 164 /* TypeReference */ || node.kind === 191 /* CallExpression */) { + return node.typeArguments; + } + if (ts.isFunctionLike(node) || node.kind === 240 /* ClassDeclaration */ || node.kind === 241 /* InterfaceDeclaration */) { + return node.typeParameters; + } + return undefined; + } + ts.getTypeArgumentOrTypeParameterList = getTypeArgumentOrTypeParameterList; + function isComment(kind) { + return kind === 2 /* SingleLineCommentTrivia */ || kind === 3 /* MultiLineCommentTrivia */; + } + ts.isComment = isComment; + function isStringOrRegularExpressionOrTemplateLiteral(kind) { + if (kind === 10 /* StringLiteral */ + || kind === 13 /* RegularExpressionLiteral */ + || ts.isTemplateLiteralKind(kind)) { + return true; + } + return false; + } + ts.isStringOrRegularExpressionOrTemplateLiteral = isStringOrRegularExpressionOrTemplateLiteral; + function isPunctuation(kind) { + return 18 /* FirstPunctuation */ <= kind && kind <= 71 /* LastPunctuation */; + } + ts.isPunctuation = isPunctuation; + function isInsideTemplateLiteral(node, position, sourceFile) { + return ts.isTemplateLiteralKind(node.kind) + && (node.getStart(sourceFile) < position && position < node.end) || (!!node.isUnterminated && position === node.end); + } + ts.isInsideTemplateLiteral = isInsideTemplateLiteral; + function isAccessibilityModifier(kind) { + switch (kind) { + case 115 /* PublicKeyword */: + case 113 /* PrivateKeyword */: + case 114 /* ProtectedKeyword */: + return true; + } + return false; + } + ts.isAccessibilityModifier = isAccessibilityModifier; + function cloneCompilerOptions(options) { + var result = ts.clone(options); + ts.setConfigFileInOptions(result, options && options.configFile); + return result; + } + ts.cloneCompilerOptions = cloneCompilerOptions; + function isArrayLiteralOrObjectLiteralDestructuringPattern(node) { + if (node.kind === 187 /* ArrayLiteralExpression */ || + node.kind === 188 /* ObjectLiteralExpression */) { + // [a,b,c] from: + // [a, b, c] = someExpression; + if (node.parent.kind === 204 /* BinaryExpression */ && + node.parent.left === node && + node.parent.operatorToken.kind === 59 /* EqualsToken */) { + return true; + } + // [a, b, c] from: + // for([a, b, c] of expression) + if (node.parent.kind === 227 /* ForOfStatement */ && + node.parent.initializer === node) { + return true; + } + // [a, b, c] of + // [x, [a, b, c] ] = someExpression + // or + // {x, a: {a, b, c} } = someExpression + if (isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent.kind === 275 /* PropertyAssignment */ ? node.parent.parent : node.parent)) { + return true; + } + } + return false; + } + ts.isArrayLiteralOrObjectLiteralDestructuringPattern = isArrayLiteralOrObjectLiteralDestructuringPattern; + function isInReferenceComment(sourceFile, position) { + return isInReferenceCommentWorker(sourceFile, position, /*shouldBeReference*/ true); + } + ts.isInReferenceComment = isInReferenceComment; + function isInNonReferenceComment(sourceFile, position) { + return isInReferenceCommentWorker(sourceFile, position, /*shouldBeReference*/ false); + } + ts.isInNonReferenceComment = isInNonReferenceComment; + function isInReferenceCommentWorker(sourceFile, position, shouldBeReference) { + var range = isInComment(sourceFile, position, /*tokenAtPosition*/ undefined); + return !!range && shouldBeReference === tripleSlashDirectivePrefixRegex.test(sourceFile.text.substring(range.pos, range.end)); + } + function createTextSpanFromNode(node, sourceFile) { + return ts.createTextSpanFromBounds(node.getStart(sourceFile), node.getEnd()); + } + ts.createTextSpanFromNode = createTextSpanFromNode; + function createTextRangeFromNode(node, sourceFile) { + return ts.createRange(node.getStart(sourceFile), node.end); + } + ts.createTextRangeFromNode = createTextRangeFromNode; + function createTextSpanFromRange(range) { + return ts.createTextSpanFromBounds(range.pos, range.end); + } + ts.createTextSpanFromRange = createTextSpanFromRange; + function createTextRangeFromSpan(span) { + return ts.createRange(span.start, span.start + span.length); + } + ts.createTextRangeFromSpan = createTextRangeFromSpan; + function createTextChangeFromStartLength(start, length, newText) { + return createTextChange(ts.createTextSpan(start, length), newText); + } + ts.createTextChangeFromStartLength = createTextChangeFromStartLength; + function createTextChange(span, newText) { + return { span: span, newText: newText }; + } + ts.createTextChange = createTextChange; + ts.typeKeywords = [ + 120 /* AnyKeyword */, + 146 /* BigIntKeyword */, + 123 /* BooleanKeyword */, + 87 /* FalseKeyword */, + 129 /* KeyOfKeyword */, + 132 /* NeverKeyword */, + 96 /* NullKeyword */, + 135 /* NumberKeyword */, + 136 /* ObjectKeyword */, + 138 /* StringKeyword */, + 139 /* SymbolKeyword */, + 102 /* TrueKeyword */, + 106 /* VoidKeyword */, + 141 /* UndefinedKeyword */, + 142 /* UniqueKeyword */, + 143 /* UnknownKeyword */, + ]; + function isTypeKeyword(kind) { + return ts.contains(ts.typeKeywords, kind); + } + ts.isTypeKeyword = isTypeKeyword; + /** True if the symbol is for an external module, as opposed to a namespace. */ + function isExternalModuleSymbol(moduleSymbol) { + return !!(moduleSymbol.flags & 1536 /* Module */) && moduleSymbol.name.charCodeAt(0) === 34 /* doubleQuote */; + } + ts.isExternalModuleSymbol = isExternalModuleSymbol; + function nodeSeenTracker() { + var seen = []; + return function (node) { + var id = ts.getNodeId(node); + return !seen[id] && (seen[id] = true); + }; + } + ts.nodeSeenTracker = nodeSeenTracker; + function getSnapshotText(snap) { + return snap.getText(0, snap.getLength()); + } + ts.getSnapshotText = getSnapshotText; + function repeatString(str, count) { + var result = ""; + for (var i = 0; i < count; i++) { + result += str; + } + return result; + } + ts.repeatString = repeatString; + function skipConstraint(type) { + return type.isTypeParameter() ? type.getConstraint() || type : type; + } + ts.skipConstraint = skipConstraint; + function getNameFromPropertyName(name) { + return name.kind === 149 /* ComputedPropertyName */ + // treat computed property names where expression is string/numeric literal as just string/numeric literal + ? ts.isStringOrNumericLiteralLike(name.expression) ? name.expression.text : undefined + : ts.getTextOfIdentifierOrLiteral(name); + } + ts.getNameFromPropertyName = getNameFromPropertyName; + function programContainsEs6Modules(program) { + return program.getSourceFiles().some(function (s) { return !s.isDeclarationFile && !program.isSourceFileFromExternalLibrary(s) && !!s.externalModuleIndicator; }); + } + ts.programContainsEs6Modules = programContainsEs6Modules; + function compilerOptionsIndicateEs6Modules(compilerOptions) { + return !!compilerOptions.module || compilerOptions.target >= 2 /* ES2015 */ || !!compilerOptions.noEmit; + } + ts.compilerOptionsIndicateEs6Modules = compilerOptionsIndicateEs6Modules; + function hostUsesCaseSensitiveFileNames(host) { + return host.useCaseSensitiveFileNames ? host.useCaseSensitiveFileNames() : false; + } + ts.hostUsesCaseSensitiveFileNames = hostUsesCaseSensitiveFileNames; + function hostGetCanonicalFileName(host) { + return ts.createGetCanonicalFileName(hostUsesCaseSensitiveFileNames(host)); + } + ts.hostGetCanonicalFileName = hostGetCanonicalFileName; + function makeImportIfNecessary(defaultImport, namedImports, moduleSpecifier, quotePreference) { + return defaultImport || namedImports && namedImports.length ? makeImport(defaultImport, namedImports, moduleSpecifier, quotePreference) : undefined; + } + ts.makeImportIfNecessary = makeImportIfNecessary; + function makeImport(defaultImport, namedImports, moduleSpecifier, quotePreference) { + return ts.createImportDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, defaultImport || namedImports + ? ts.createImportClause(defaultImport, namedImports && namedImports.length ? ts.createNamedImports(namedImports) : undefined) + : undefined, typeof moduleSpecifier === "string" ? makeStringLiteral(moduleSpecifier, quotePreference) : moduleSpecifier); + } + ts.makeImport = makeImport; + function makeStringLiteral(text, quotePreference) { + return ts.createLiteral(text, quotePreference === 0 /* Single */); + } + ts.makeStringLiteral = makeStringLiteral; + var QuotePreference; + (function (QuotePreference) { + QuotePreference[QuotePreference["Single"] = 0] = "Single"; + QuotePreference[QuotePreference["Double"] = 1] = "Double"; + })(QuotePreference = ts.QuotePreference || (ts.QuotePreference = {})); + function quotePreferenceFromString(str, sourceFile) { + return ts.isStringDoubleQuoted(str, sourceFile) ? 1 /* Double */ : 0 /* Single */; + } + ts.quotePreferenceFromString = quotePreferenceFromString; + function getQuotePreference(sourceFile, preferences) { + if (preferences.quotePreference) { + return preferences.quotePreference === "single" ? 0 /* Single */ : 1 /* Double */; + } + else { + var firstModuleSpecifier = sourceFile.imports && ts.find(sourceFile.imports, ts.isStringLiteral); + return firstModuleSpecifier ? quotePreferenceFromString(firstModuleSpecifier, sourceFile) : 1 /* Double */; + } + } + ts.getQuotePreference = getQuotePreference; + function getQuoteFromPreference(qp) { + switch (qp) { + case 0 /* Single */: return "'"; + case 1 /* Double */: return '"'; + default: return ts.Debug.assertNever(qp); + } + } + ts.getQuoteFromPreference = getQuoteFromPreference; + function symbolNameNoDefault(symbol) { + var escaped = symbolEscapedNameNoDefault(symbol); + return escaped === undefined ? undefined : ts.unescapeLeadingUnderscores(escaped); + } + ts.symbolNameNoDefault = symbolNameNoDefault; + function symbolEscapedNameNoDefault(symbol) { + if (symbol.escapedName !== "default" /* Default */) { + return symbol.escapedName; + } + return ts.firstDefined(symbol.declarations, function (decl) { + var name = ts.getNameOfDeclaration(decl); + return name && name.kind === 72 /* Identifier */ ? name.escapedText : undefined; + }); + } + ts.symbolEscapedNameNoDefault = symbolEscapedNameNoDefault; + function isObjectBindingElementWithoutPropertyName(bindingElement) { + return ts.isBindingElement(bindingElement) && + ts.isObjectBindingPattern(bindingElement.parent) && + ts.isIdentifier(bindingElement.name) && + !bindingElement.propertyName; + } + ts.isObjectBindingElementWithoutPropertyName = isObjectBindingElementWithoutPropertyName; + function getPropertySymbolFromBindingElement(checker, bindingElement) { + var typeOfPattern = checker.getTypeAtLocation(bindingElement.parent); + return typeOfPattern && checker.getPropertyOfType(typeOfPattern, bindingElement.name.text); + } + ts.getPropertySymbolFromBindingElement = getPropertySymbolFromBindingElement; + /** + * Find symbol of the given property-name and add the symbol to the given result array + * @param symbol a symbol to start searching for the given propertyName + * @param propertyName a name of property to search for + * @param result an array of symbol of found property symbols + * @param previousIterationSymbolsCache a cache of symbol from previous iterations of calling this function to prevent infinite revisiting of the same symbol. + * The value of previousIterationSymbol is undefined when the function is first called. + */ + function getPropertySymbolsFromBaseTypes(symbol, propertyName, checker, cb) { + var seen = ts.createMap(); + return recur(symbol); + function recur(symbol) { + // Use `addToSeen` to ensure we don't infinitely recurse in this situation: + // interface C extends C { + // /*findRef*/propName: string; + // } + if (!(symbol.flags & (32 /* Class */ | 64 /* Interface */)) || !ts.addToSeen(seen, ts.getSymbolId(symbol))) + return; + return ts.firstDefined(symbol.declarations, function (declaration) { return ts.firstDefined(ts.getAllSuperTypeNodes(declaration), function (typeReference) { + var type = checker.getTypeAtLocation(typeReference); + var propertySymbol = type && type.symbol && checker.getPropertyOfType(type, propertyName); + // Visit the typeReference as well to see if it directly or indirectly uses that property + return type && propertySymbol && (ts.firstDefined(checker.getRootSymbols(propertySymbol), cb) || recur(type.symbol)); + }); }); + } + } + ts.getPropertySymbolsFromBaseTypes = getPropertySymbolsFromBaseTypes; + function isMemberSymbolInBaseType(memberSymbol, checker) { + return getPropertySymbolsFromBaseTypes(memberSymbol.parent, memberSymbol.name, checker, function (_) { return true; }) || false; + } + ts.isMemberSymbolInBaseType = isMemberSymbolInBaseType; + function getParentNodeInSpan(node, file, span) { + if (!node) + return undefined; + while (node.parent) { + if (ts.isSourceFile(node.parent) || !spanContainsNode(span, node.parent, file)) { + return node; + } + node = node.parent; + } + } + ts.getParentNodeInSpan = getParentNodeInSpan; + function spanContainsNode(span, node, file) { + return ts.textSpanContainsPosition(span, node.getStart(file)) && + node.getEnd() <= ts.textSpanEnd(span); + } + function findModifier(node, kind) { + return node.modifiers && ts.find(node.modifiers, function (m) { return m.kind === kind; }); + } + ts.findModifier = findModifier; + function insertImport(changes, sourceFile, importDecl) { + var lastImportDeclaration = ts.findLast(sourceFile.statements, ts.isAnyImportSyntax); + if (lastImportDeclaration) { + changes.insertNodeAfter(sourceFile, lastImportDeclaration, importDecl); + } + else { + changes.insertNodeAtTopOfFile(sourceFile, importDecl, /*blankLineBetween*/ true); + } + } + ts.insertImport = insertImport; + function textSpansEqual(a, b) { + return !!a && !!b && a.start === b.start && a.length === b.length; + } + ts.textSpansEqual = textSpansEqual; + function documentSpansEqual(a, b) { + return a.fileName === b.fileName && textSpansEqual(a.textSpan, b.textSpan); + } + ts.documentSpansEqual = documentSpansEqual; +})(ts || (ts = {})); +// Display-part writer helpers +/* @internal */ +(function (ts) { + function isFirstDeclarationOfSymbolParameter(symbol) { + return symbol.declarations && symbol.declarations.length > 0 && symbol.declarations[0].kind === 151 /* Parameter */; + } + ts.isFirstDeclarationOfSymbolParameter = isFirstDeclarationOfSymbolParameter; + var displayPartWriter = getDisplayPartWriter(); + function getDisplayPartWriter() { + var absoluteMaximumLength = ts.defaultMaximumTruncationLength * 10; // A hard cutoff to avoid overloading the messaging channel in worst-case scenarios + var displayParts; + var lineStart; + var indent; + var length; + resetWriter(); + var unknownWrite = function (text) { return writeKind(text, ts.SymbolDisplayPartKind.text); }; + return { + displayParts: function () { + var finalText = displayParts.length && displayParts[displayParts.length - 1].text; + if (length > absoluteMaximumLength && finalText && finalText !== "...") { + if (!ts.isWhiteSpaceLike(finalText.charCodeAt(finalText.length - 1))) { + displayParts.push(displayPart(" ", ts.SymbolDisplayPartKind.space)); + } + displayParts.push(displayPart("...", ts.SymbolDisplayPartKind.punctuation)); + } + return displayParts; + }, + writeKeyword: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.keyword); }, + writeOperator: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.operator); }, + writePunctuation: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.punctuation); }, + writeTrailingSemicolon: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.punctuation); }, + writeSpace: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.space); }, + writeStringLiteral: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.stringLiteral); }, + writeParameter: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.parameterName); }, + writeProperty: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.propertyName); }, + writeLiteral: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.stringLiteral); }, + writeSymbol: writeSymbol, + writeLine: writeLine, + write: unknownWrite, + writeComment: unknownWrite, + getText: function () { return ""; }, + getTextPos: function () { return 0; }, + getColumn: function () { return 0; }, + getLine: function () { return 0; }, + isAtStartOfLine: function () { return false; }, + rawWrite: ts.notImplemented, + getIndent: function () { return indent; }, + increaseIndent: function () { indent++; }, + decreaseIndent: function () { indent--; }, + clear: resetWriter, + trackSymbol: ts.noop, + reportInaccessibleThisError: ts.noop, + reportInaccessibleUniqueSymbolError: ts.noop, + reportPrivateInBaseOfClassExpression: ts.noop, + }; + function writeIndent() { + if (length > absoluteMaximumLength) + return; + if (lineStart) { + var indentString = ts.getIndentString(indent); + if (indentString) { + length += indentString.length; + displayParts.push(displayPart(indentString, ts.SymbolDisplayPartKind.space)); + } + lineStart = false; + } + } + function writeKind(text, kind) { + if (length > absoluteMaximumLength) + return; + writeIndent(); + length += text.length; + displayParts.push(displayPart(text, kind)); + } + function writeSymbol(text, symbol) { + if (length > absoluteMaximumLength) + return; + writeIndent(); + length += text.length; + displayParts.push(symbolPart(text, symbol)); + } + function writeLine() { + if (length > absoluteMaximumLength) + return; + length += 1; + displayParts.push(lineBreakPart()); + lineStart = true; + } + function resetWriter() { + displayParts = []; + lineStart = true; + indent = 0; + length = 0; + } + } + function symbolPart(text, symbol) { + return displayPart(text, displayPartKind(symbol)); + function displayPartKind(symbol) { + var flags = symbol.flags; + if (flags & 3 /* Variable */) { + return isFirstDeclarationOfSymbolParameter(symbol) ? ts.SymbolDisplayPartKind.parameterName : ts.SymbolDisplayPartKind.localName; + } + else if (flags & 4 /* Property */) { + return ts.SymbolDisplayPartKind.propertyName; + } + else if (flags & 32768 /* GetAccessor */) { + return ts.SymbolDisplayPartKind.propertyName; + } + else if (flags & 65536 /* SetAccessor */) { + return ts.SymbolDisplayPartKind.propertyName; + } + else if (flags & 8 /* EnumMember */) { + return ts.SymbolDisplayPartKind.enumMemberName; + } + else if (flags & 16 /* Function */) { + return ts.SymbolDisplayPartKind.functionName; + } + else if (flags & 32 /* Class */) { + return ts.SymbolDisplayPartKind.className; + } + else if (flags & 64 /* Interface */) { + return ts.SymbolDisplayPartKind.interfaceName; + } + else if (flags & 384 /* Enum */) { + return ts.SymbolDisplayPartKind.enumName; + } + else if (flags & 1536 /* Module */) { + return ts.SymbolDisplayPartKind.moduleName; + } + else if (flags & 8192 /* Method */) { + return ts.SymbolDisplayPartKind.methodName; + } + else if (flags & 262144 /* TypeParameter */) { + return ts.SymbolDisplayPartKind.typeParameterName; + } + else if (flags & 524288 /* TypeAlias */) { + return ts.SymbolDisplayPartKind.aliasName; + } + else if (flags & 2097152 /* Alias */) { + return ts.SymbolDisplayPartKind.aliasName; + } + return ts.SymbolDisplayPartKind.text; + } + } + ts.symbolPart = symbolPart; + function displayPart(text, kind) { + return { text: text, kind: ts.SymbolDisplayPartKind[kind] }; + } + ts.displayPart = displayPart; + function spacePart() { + return displayPart(" ", ts.SymbolDisplayPartKind.space); + } + ts.spacePart = spacePart; + function keywordPart(kind) { + return displayPart(ts.tokenToString(kind), ts.SymbolDisplayPartKind.keyword); + } + ts.keywordPart = keywordPart; + function punctuationPart(kind) { + return displayPart(ts.tokenToString(kind), ts.SymbolDisplayPartKind.punctuation); + } + ts.punctuationPart = punctuationPart; + function operatorPart(kind) { + return displayPart(ts.tokenToString(kind), ts.SymbolDisplayPartKind.operator); + } + ts.operatorPart = operatorPart; + function textOrKeywordPart(text) { + var kind = ts.stringToToken(text); + return kind === undefined + ? textPart(text) + : keywordPart(kind); + } + ts.textOrKeywordPart = textOrKeywordPart; + function textPart(text) { + return displayPart(text, ts.SymbolDisplayPartKind.text); + } + ts.textPart = textPart; + var carriageReturnLineFeed = "\r\n"; + /** + * The default is CRLF. + */ + function getNewLineOrDefaultFromHost(host, formatSettings) { + return (formatSettings && formatSettings.newLineCharacter) || + (host.getNewLine && host.getNewLine()) || + carriageReturnLineFeed; + } + ts.getNewLineOrDefaultFromHost = getNewLineOrDefaultFromHost; + function lineBreakPart() { + return displayPart("\n", ts.SymbolDisplayPartKind.lineBreak); + } + ts.lineBreakPart = lineBreakPart; + function mapToDisplayParts(writeDisplayParts) { + try { + writeDisplayParts(displayPartWriter); + return displayPartWriter.displayParts(); + } + finally { + displayPartWriter.clear(); + } + } + ts.mapToDisplayParts = mapToDisplayParts; + function typeToDisplayParts(typechecker, type, enclosingDeclaration, flags) { + if (flags === void 0) { flags = 0 /* None */; } + return mapToDisplayParts(function (writer) { + typechecker.writeType(type, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */ | 16384 /* UseAliasDefinedOutsideCurrentScope */, writer); + }); + } + ts.typeToDisplayParts = typeToDisplayParts; + function symbolToDisplayParts(typeChecker, symbol, enclosingDeclaration, meaning, flags) { + if (flags === void 0) { flags = 0 /* None */; } + return mapToDisplayParts(function (writer) { + typeChecker.writeSymbol(symbol, enclosingDeclaration, meaning, flags | 8 /* UseAliasDefinedOutsideCurrentScope */, writer); + }); + } + ts.symbolToDisplayParts = symbolToDisplayParts; + function signatureToDisplayParts(typechecker, signature, enclosingDeclaration, flags) { + if (flags === void 0) { flags = 0 /* None */; } + flags |= 16384 /* UseAliasDefinedOutsideCurrentScope */ | 1024 /* MultilineObjectLiterals */ | 32 /* WriteTypeArgumentsOfSignature */ | 8192 /* OmitParameterModifiers */; + return mapToDisplayParts(function (writer) { + typechecker.writeSignature(signature, enclosingDeclaration, flags, /*signatureKind*/ undefined, writer); + }); + } + ts.signatureToDisplayParts = signatureToDisplayParts; + function isImportOrExportSpecifierName(location) { + return !!location.parent && ts.isImportOrExportSpecifier(location.parent) && location.parent.propertyName === location; + } + ts.isImportOrExportSpecifierName = isImportOrExportSpecifierName; + /** + * Strip off existed single quotes or double quotes from a given string + * + * @return non-quoted string + */ + function stripQuotes(name) { + var length = name.length; + if (length >= 2 && name.charCodeAt(0) === name.charCodeAt(length - 1) && startsWithQuote(name)) { + return name.substring(1, length - 1); + } + return name; + } + ts.stripQuotes = stripQuotes; + function startsWithQuote(name) { + return ts.isSingleOrDoubleQuote(name.charCodeAt(0)); + } + ts.startsWithQuote = startsWithQuote; + function scriptKindIs(fileName, host) { + var scriptKinds = []; + for (var _i = 2; _i < arguments.length; _i++) { + scriptKinds[_i - 2] = arguments[_i]; + } + var scriptKind = getScriptKind(fileName, host); + return ts.some(scriptKinds, function (k) { return k === scriptKind; }); + } + ts.scriptKindIs = scriptKindIs; + function getScriptKind(fileName, host) { + // First check to see if the script kind was specified by the host. Chances are the host + // may override the default script kind for the file extension. + return ts.ensureScriptKind(fileName, host && host.getScriptKind && host.getScriptKind(fileName)); + } + ts.getScriptKind = getScriptKind; + function getUniqueSymbolId(symbol, checker) { + return ts.getSymbolId(ts.skipAlias(symbol, checker)); + } + ts.getUniqueSymbolId = getUniqueSymbolId; + function getFirstNonSpaceCharacterPosition(text, position) { + while (ts.isWhiteSpaceLike(text.charCodeAt(position))) { + position += 1; + } + return position; + } + ts.getFirstNonSpaceCharacterPosition = getFirstNonSpaceCharacterPosition; + function getPrecedingNonSpaceCharacterPosition(text, position) { + while (position > -1 && ts.isWhiteSpaceSingleLine(text.charCodeAt(position))) { + position -= 1; + } + return position + 1; + } + ts.getPrecedingNonSpaceCharacterPosition = getPrecedingNonSpaceCharacterPosition; + /** + * Creates a deep, memberwise clone of a node with no source map location. + * + * WARNING: This is an expensive operation and is only intended to be used in refactorings + * and code fixes (because those are triggered by explicit user actions). + */ + function getSynthesizedDeepClone(node, includeTrivia) { + if (includeTrivia === void 0) { includeTrivia = true; } + var clone = node && getSynthesizedDeepCloneWorker(node); + if (clone && !includeTrivia) + suppressLeadingAndTrailingTrivia(clone); + return clone; + } + ts.getSynthesizedDeepClone = getSynthesizedDeepClone; + function getSynthesizedDeepCloneWithRenames(node, includeTrivia, renameMap, checker, callback) { + if (includeTrivia === void 0) { includeTrivia = true; } + var clone; + if (ts.isIdentifier(node) && renameMap && checker) { + var symbol = checker.getSymbolAtLocation(node); + var renameInfo = symbol && renameMap.get(String(ts.getSymbolId(symbol))); + if (renameInfo) { + clone = ts.createIdentifier(renameInfo.text); + } + } + if (!clone) { + clone = getSynthesizedDeepCloneWorker(node, renameMap, checker, callback); + } + if (clone && !includeTrivia) + suppressLeadingAndTrailingTrivia(clone); + if (callback && clone) + callback(node, clone); + return clone; + } + ts.getSynthesizedDeepCloneWithRenames = getSynthesizedDeepCloneWithRenames; + function getSynthesizedDeepCloneWorker(node, renameMap, checker, callback) { + var visited = (renameMap || checker || callback) ? + ts.visitEachChild(node, wrapper, ts.nullTransformationContext) : + ts.visitEachChild(node, getSynthesizedDeepClone, ts.nullTransformationContext); + if (visited === node) { + // This only happens for leaf nodes - internal nodes always see their children change. + var clone_1 = ts.getSynthesizedClone(node); + if (ts.isStringLiteral(clone_1)) { + clone_1.textSourceNode = node; + } + else if (ts.isNumericLiteral(clone_1)) { + clone_1.numericLiteralFlags = node.numericLiteralFlags; + } + return ts.setTextRange(clone_1, node); + } + // PERF: As an optimization, rather than calling getSynthesizedClone, we'll update + // the new node created by visitEachChild with the extra changes getSynthesizedClone + // would have made. + visited.parent = undefined; + return visited; + function wrapper(node) { + return getSynthesizedDeepCloneWithRenames(node, /*includeTrivia*/ true, renameMap, checker, callback); + } + } + function getSynthesizedDeepClones(nodes, includeTrivia) { + if (includeTrivia === void 0) { includeTrivia = true; } + return nodes && ts.createNodeArray(nodes.map(function (n) { return getSynthesizedDeepClone(n, includeTrivia); }), nodes.hasTrailingComma); + } + ts.getSynthesizedDeepClones = getSynthesizedDeepClones; + /** + * Sets EmitFlags to suppress leading and trailing trivia on the node. + */ + function suppressLeadingAndTrailingTrivia(node) { + suppressLeadingTrivia(node); + suppressTrailingTrivia(node); + } + ts.suppressLeadingAndTrailingTrivia = suppressLeadingAndTrailingTrivia; + /** + * Sets EmitFlags to suppress leading trivia on the node. + */ + function suppressLeadingTrivia(node) { + addEmitFlagsRecursively(node, 512 /* NoLeadingComments */, getFirstChild); + } + ts.suppressLeadingTrivia = suppressLeadingTrivia; + /** + * Sets EmitFlags to suppress trailing trivia on the node. + */ + function suppressTrailingTrivia(node) { + addEmitFlagsRecursively(node, 1024 /* NoTrailingComments */, ts.getLastChild); + } + ts.suppressTrailingTrivia = suppressTrailingTrivia; + function addEmitFlagsRecursively(node, flag, getChild) { + ts.addEmitFlags(node, flag); + var child = getChild(node); + if (child) + addEmitFlagsRecursively(child, flag, getChild); + } + function getFirstChild(node) { + return node.forEachChild(function (child) { return child; }); + } + function getUniqueName(baseName, sourceFile) { + var nameText = baseName; + for (var i = 1; !ts.isFileLevelUniqueName(sourceFile, nameText); i++) { + nameText = baseName + "_" + i; + } + return nameText; + } + ts.getUniqueName = getUniqueName; + /** + * @return The index of the (only) reference to the extracted symbol. We want the cursor + * to be on the reference, rather than the declaration, because it's closer to where the + * user was before extracting it. + */ + function getRenameLocation(edits, renameFilename, name, preferLastLocation) { + var delta = 0; + var lastPos = -1; + for (var _i = 0, edits_1 = edits; _i < edits_1.length; _i++) { + var _a = edits_1[_i], fileName = _a.fileName, textChanges_2 = _a.textChanges; + ts.Debug.assert(fileName === renameFilename); + for (var _b = 0, textChanges_1 = textChanges_2; _b < textChanges_1.length; _b++) { + var change = textChanges_1[_b]; + var span = change.span, newText = change.newText; + var index = indexInTextChange(newText, name); + if (index !== -1) { + lastPos = span.start + delta + index; + // If the reference comes first, return immediately. + if (!preferLastLocation) { + return lastPos; + } + } + delta += newText.length - span.length; + } + } + // If the declaration comes first, return the position of the last occurrence. + ts.Debug.assert(preferLastLocation); + ts.Debug.assert(lastPos >= 0); + return lastPos; + } + ts.getRenameLocation = getRenameLocation; + function copyComments(sourceNode, targetNode, sourceFile, commentKind, hasTrailingNewLine) { + ts.forEachLeadingCommentRange(sourceFile.text, sourceNode.pos, function (pos, end, kind, htnl) { + if (kind === 3 /* MultiLineCommentTrivia */) { + // Remove leading /* + pos += 2; + // Remove trailing */ + end -= 2; + } + else { + // Remove leading // + pos += 2; + } + ts.addSyntheticLeadingComment(targetNode, commentKind || kind, sourceFile.text.slice(pos, end), hasTrailingNewLine !== undefined ? hasTrailingNewLine : htnl); + }); + } + ts.copyComments = copyComments; + function indexInTextChange(change, name) { + if (ts.startsWith(change, name)) + return 0; + // Add a " " to avoid references inside words + var idx = change.indexOf(" " + name); + if (idx === -1) + idx = change.indexOf("." + name); + if (idx === -1) + idx = change.indexOf('"' + name); + return idx === -1 ? -1 : idx + 1; + } + function getContextualTypeFromParent(node, checker) { + var parent = node.parent; + switch (parent.kind) { + case 192 /* NewExpression */: + return checker.getContextualType(parent); + case 204 /* BinaryExpression */: { + var _a = parent, left = _a.left, operatorToken = _a.operatorToken, right = _a.right; + return isEqualityOperatorKind(operatorToken.kind) + ? checker.getTypeAtLocation(node === right ? left : right) + : checker.getContextualType(node); + } + case 271 /* CaseClause */: + return parent.expression === node ? getSwitchedType(parent, checker) : undefined; + default: + return checker.getContextualType(node); + } + } + ts.getContextualTypeFromParent = getContextualTypeFromParent; + function quote(text, preferences) { + if (/^\d+$/.test(text)) { + return text; + } + var quoted = JSON.stringify(text); + switch (preferences.quotePreference) { + case undefined: + case "double": + return quoted; + case "single": + return "'" + stripQuotes(quoted).replace("'", "\\'").replace('\\"', '"') + "'"; + default: + return ts.Debug.assertNever(preferences.quotePreference); + } + } + ts.quote = quote; + function isEqualityOperatorKind(kind) { + switch (kind) { + case 35 /* EqualsEqualsEqualsToken */: + case 33 /* EqualsEqualsToken */: + case 36 /* ExclamationEqualsEqualsToken */: + case 34 /* ExclamationEqualsToken */: + return true; + default: + return false; + } + } + ts.isEqualityOperatorKind = isEqualityOperatorKind; + function isStringLiteralOrTemplate(node) { + switch (node.kind) { + case 10 /* StringLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: + case 206 /* TemplateExpression */: + case 193 /* TaggedTemplateExpression */: + return true; + default: + return false; + } + } + ts.isStringLiteralOrTemplate = isStringLiteralOrTemplate; + function hasIndexSignature(type) { + return !!type.getStringIndexType() || !!type.getNumberIndexType(); + } + ts.hasIndexSignature = hasIndexSignature; + function getSwitchedType(caseClause, checker) { + return checker.getTypeAtLocation(caseClause.parent.parent.expression); + } + ts.getSwitchedType = getSwitchedType; +})(ts || (ts = {})); +var ts; +(function (ts) { + function createClassifier() { + var scanner = ts.createScanner(6 /* Latest */, /*skipTrivia*/ false); + function getClassificationsForLine(text, lexState, syntacticClassifierAbsent) { + return convertClassificationsToResult(getEncodedLexicalClassifications(text, lexState, syntacticClassifierAbsent), text); + } + // If there is a syntactic classifier ('syntacticClassifierAbsent' is false), + // we will be more conservative in order to avoid conflicting with the syntactic classifier. + function getEncodedLexicalClassifications(text, lexState, syntacticClassifierAbsent) { + var token = 0 /* Unknown */; + var lastNonTriviaToken = 0 /* Unknown */; + // Just a stack of TemplateHeads and OpenCurlyBraces, used to perform rudimentary (inexact) + // classification on template strings. Because of the context free nature of templates, + // the only precise way to classify a template portion would be by propagating the stack across + // lines, just as we do with the end-of-line state. However, this is a burden for implementers, + // and the behavior is entirely subsumed by the syntactic classifier anyway, so we instead + // flatten any nesting when the template stack is non-empty and encode it in the end-of-line state. + // Situations in which this fails are + // 1) When template strings are nested across different lines: + // `hello ${ `world + // ` }` + // + // Where on the second line, you will get the closing of a template, + // a closing curly, and a new template. + // + // 2) When substitution expressions have curly braces and the curly brace falls on the next line: + // `hello ${ () => { + // return "world" } } ` + // + // Where on the second line, you will get the 'return' keyword, + // a string literal, and a template end consisting of '} } `'. + var templateStack = []; + var _a = getPrefixFromLexState(lexState), prefix = _a.prefix, pushTemplate = _a.pushTemplate; + text = prefix + text; + var offset = prefix.length; + if (pushTemplate) { + templateStack.push(15 /* TemplateHead */); + } + scanner.setText(text); + var endOfLineState = 0 /* None */; + var spans = []; + // We can run into an unfortunate interaction between the lexical and syntactic classifier + // when the user is typing something generic. Consider the case where the user types: + // + // Foo tokens. It's a weak heuristic, but should + // work well enough in practice. + var angleBracketStack = 0; + do { + token = scanner.scan(); + if (!ts.isTrivia(token)) { + handleToken(); + lastNonTriviaToken = token; + } + var end = scanner.getTextPos(); + pushEncodedClassification(scanner.getTokenPos(), end, offset, classFromKind(token), spans); + if (end >= text.length) { + var end_1 = getNewEndOfLineState(scanner, token, ts.lastOrUndefined(templateStack)); + if (end_1 !== undefined) { + endOfLineState = end_1; + } + } + } while (token !== 1 /* EndOfFileToken */); + function handleToken() { + switch (token) { + case 42 /* SlashToken */: + case 64 /* SlashEqualsToken */: + if (!noRegexTable[lastNonTriviaToken] && scanner.reScanSlashToken() === 13 /* RegularExpressionLiteral */) { + token = 13 /* RegularExpressionLiteral */; + } + break; + case 28 /* LessThanToken */: + if (lastNonTriviaToken === 72 /* Identifier */) { + // Could be the start of something generic. Keep track of that by bumping + // up the current count of generic contexts we may be in. + angleBracketStack++; + } + break; + case 30 /* GreaterThanToken */: + if (angleBracketStack > 0) { + // If we think we're currently in something generic, then mark that that + // generic entity is complete. + angleBracketStack--; + } + break; + case 120 /* AnyKeyword */: + case 138 /* StringKeyword */: + case 135 /* NumberKeyword */: + case 123 /* BooleanKeyword */: + case 139 /* SymbolKeyword */: + if (angleBracketStack > 0 && !syntacticClassifierAbsent) { + // If it looks like we're could be in something generic, don't classify this + // as a keyword. We may just get overwritten by the syntactic classifier, + // causing a noisy experience for the user. + token = 72 /* Identifier */; + } + break; + case 15 /* TemplateHead */: + templateStack.push(token); + break; + case 18 /* OpenBraceToken */: + // If we don't have anything on the template stack, + // then we aren't trying to keep track of a previously scanned template head. + if (templateStack.length > 0) { + templateStack.push(token); + } + break; + case 19 /* CloseBraceToken */: + // If we don't have anything on the template stack, + // then we aren't trying to keep track of a previously scanned template head. + if (templateStack.length > 0) { + var lastTemplateStackToken = ts.lastOrUndefined(templateStack); + if (lastTemplateStackToken === 15 /* TemplateHead */) { + token = scanner.reScanTemplateToken(); + // Only pop on a TemplateTail; a TemplateMiddle indicates there is more for us. + if (token === 17 /* TemplateTail */) { + templateStack.pop(); + } + else { + ts.Debug.assertEqual(token, 16 /* TemplateMiddle */, "Should have been a template middle."); + } + } + else { + ts.Debug.assertEqual(lastTemplateStackToken, 18 /* OpenBraceToken */, "Should have been an open brace"); + templateStack.pop(); + } + } + break; + default: + if (!ts.isKeyword(token)) { + break; + } + if (lastNonTriviaToken === 24 /* DotToken */) { + token = 72 /* Identifier */; + } + else if (ts.isKeyword(lastNonTriviaToken) && ts.isKeyword(token) && !canFollow(lastNonTriviaToken, token)) { + // We have two keywords in a row. Only treat the second as a keyword if + // it's a sequence that could legally occur in the language. Otherwise + // treat it as an identifier. This way, if someone writes "private var" + // we recognize that 'var' is actually an identifier here. + token = 72 /* Identifier */; + } + } + } + return { endOfLineState: endOfLineState, spans: spans }; + } + return { getClassificationsForLine: getClassificationsForLine, getEncodedLexicalClassifications: getEncodedLexicalClassifications }; + } + ts.createClassifier = createClassifier; + /// We do not have a full parser support to know when we should parse a regex or not + /// If we consider every slash token to be a regex, we could be missing cases like "1/2/3", where + /// we have a series of divide operator. this list allows us to be more accurate by ruling out + /// locations where a regexp cannot exist. + var noRegexTable = ts.arrayToNumericMap([ + 72 /* Identifier */, + 10 /* StringLiteral */, + 8 /* NumericLiteral */, + 9 /* BigIntLiteral */, + 13 /* RegularExpressionLiteral */, + 100 /* ThisKeyword */, + 44 /* PlusPlusToken */, + 45 /* MinusMinusToken */, + 21 /* CloseParenToken */, + 23 /* CloseBracketToken */, + 19 /* CloseBraceToken */, + 102 /* TrueKeyword */, + 87 /* FalseKeyword */, + ], function (token) { return token; }, function () { return true; }); + function getNewEndOfLineState(scanner, token, lastOnTemplateStack) { + switch (token) { + case 10 /* StringLiteral */: { + // Check to see if we finished up on a multiline string literal. + if (!scanner.isUnterminated()) + return undefined; + var tokenText = scanner.getTokenText(); + var lastCharIndex = tokenText.length - 1; + var numBackslashes = 0; + while (tokenText.charCodeAt(lastCharIndex - numBackslashes) === 92 /* backslash */) { + numBackslashes++; + } + // If we have an odd number of backslashes, then the multiline string is unclosed + if ((numBackslashes & 1) === 0) + return undefined; + return tokenText.charCodeAt(0) === 34 /* doubleQuote */ ? 3 /* InDoubleQuoteStringLiteral */ : 2 /* InSingleQuoteStringLiteral */; + } + case 3 /* MultiLineCommentTrivia */: + // Check to see if the multiline comment was unclosed. + return scanner.isUnterminated() ? 1 /* InMultiLineCommentTrivia */ : undefined; + default: + if (ts.isTemplateLiteralKind(token)) { + if (!scanner.isUnterminated()) { + return undefined; + } + switch (token) { + case 17 /* TemplateTail */: + return 5 /* InTemplateMiddleOrTail */; + case 14 /* NoSubstitutionTemplateLiteral */: + return 4 /* InTemplateHeadOrNoSubstitutionTemplate */; + default: + return ts.Debug.fail("Only 'NoSubstitutionTemplateLiteral's and 'TemplateTail's can be unterminated; got SyntaxKind #" + token); + } + } + return lastOnTemplateStack === 15 /* TemplateHead */ ? 6 /* InTemplateSubstitutionPosition */ : undefined; + } + } + function pushEncodedClassification(start, end, offset, classification, result) { + if (classification === 8 /* whiteSpace */) { + // Don't bother with whitespace classifications. They're not needed. + return; + } + if (start === 0 && offset > 0) { + // We're classifying the first token, and this was a case where we prepended text. + // We should consider the start of this token to be at the start of the original text. + start += offset; + } + var length = end - start; + if (length > 0) { + // All our tokens are in relation to the augmented text. Move them back to be + // relative to the original text. + result.push(start - offset, length, classification); + } + } + function convertClassificationsToResult(classifications, text) { + var entries = []; + var dense = classifications.spans; + var lastEnd = 0; + for (var i = 0; i < dense.length; i += 3) { + var start = dense[i]; + var length_1 = dense[i + 1]; + var type = dense[i + 2]; + // Make a whitespace entry between the last item and this one. + if (lastEnd >= 0) { + var whitespaceLength_1 = start - lastEnd; + if (whitespaceLength_1 > 0) { + entries.push({ length: whitespaceLength_1, classification: ts.TokenClass.Whitespace }); + } + } + entries.push({ length: length_1, classification: convertClassification(type) }); + lastEnd = start + length_1; + } + var whitespaceLength = text.length - lastEnd; + if (whitespaceLength > 0) { + entries.push({ length: whitespaceLength, classification: ts.TokenClass.Whitespace }); + } + return { entries: entries, finalLexState: classifications.endOfLineState }; + } + function convertClassification(type) { + switch (type) { + case 1 /* comment */: return ts.TokenClass.Comment; + case 3 /* keyword */: return ts.TokenClass.Keyword; + case 4 /* numericLiteral */: return ts.TokenClass.NumberLiteral; + case 25 /* bigintLiteral */: return ts.TokenClass.BigIntLiteral; + case 5 /* operator */: return ts.TokenClass.Operator; + case 6 /* stringLiteral */: return ts.TokenClass.StringLiteral; + case 8 /* whiteSpace */: return ts.TokenClass.Whitespace; + case 10 /* punctuation */: return ts.TokenClass.Punctuation; + case 2 /* identifier */: + case 11 /* className */: + case 12 /* enumName */: + case 13 /* interfaceName */: + case 14 /* moduleName */: + case 15 /* typeParameterName */: + case 16 /* typeAliasName */: + case 9 /* text */: + case 17 /* parameterName */: + return ts.TokenClass.Identifier; + default: + return undefined; // TODO: GH#18217 Debug.assertNever(type); + } + } + /** Returns true if 'keyword2' can legally follow 'keyword1' in any language construct. */ + function canFollow(keyword1, keyword2) { + if (!ts.isAccessibilityModifier(keyword1)) { + // Assume any other keyword combination is legal. + // This can be refined in the future if there are more cases we want the classifier to be better at. + return true; + } + switch (keyword2) { + case 126 /* GetKeyword */: + case 137 /* SetKeyword */: + case 124 /* ConstructorKeyword */: + case 116 /* StaticKeyword */: + return true; // Allow things like "public get", "public constructor" and "public static". + default: + return false; // Any other keyword following "public" is actually an identifier, not a real keyword. + } + } + function getPrefixFromLexState(lexState) { + // If we're in a string literal, then prepend: "\ + // (and a newline). That way when we lex we'll think we're still in a string literal. + // + // If we're in a multiline comment, then prepend: /* + // (and a newline). That way when we lex we'll think we're still in a multiline comment. + switch (lexState) { + case 3 /* InDoubleQuoteStringLiteral */: + return { prefix: "\"\\\n" }; + case 2 /* InSingleQuoteStringLiteral */: + return { prefix: "'\\\n" }; + case 1 /* InMultiLineCommentTrivia */: + return { prefix: "/*\n" }; + case 4 /* InTemplateHeadOrNoSubstitutionTemplate */: + return { prefix: "`\n" }; + case 5 /* InTemplateMiddleOrTail */: + return { prefix: "}\n", pushTemplate: true }; + case 6 /* InTemplateSubstitutionPosition */: + return { prefix: "", pushTemplate: true }; + case 0 /* None */: + return { prefix: "" }; + default: + return ts.Debug.assertNever(lexState); + } + } + function isBinaryExpressionOperatorToken(token) { + switch (token) { + case 40 /* AsteriskToken */: + case 42 /* SlashToken */: + case 43 /* PercentToken */: + case 38 /* PlusToken */: + case 39 /* MinusToken */: + case 46 /* LessThanLessThanToken */: + case 47 /* GreaterThanGreaterThanToken */: + case 48 /* GreaterThanGreaterThanGreaterThanToken */: + case 28 /* LessThanToken */: + case 30 /* GreaterThanToken */: + case 31 /* LessThanEqualsToken */: + case 32 /* GreaterThanEqualsToken */: + case 94 /* InstanceOfKeyword */: + case 93 /* InKeyword */: + case 119 /* AsKeyword */: + case 33 /* EqualsEqualsToken */: + case 34 /* ExclamationEqualsToken */: + case 35 /* EqualsEqualsEqualsToken */: + case 36 /* ExclamationEqualsEqualsToken */: + case 49 /* AmpersandToken */: + case 51 /* CaretToken */: + case 50 /* BarToken */: + case 54 /* AmpersandAmpersandToken */: + case 55 /* BarBarToken */: + case 70 /* BarEqualsToken */: + case 69 /* AmpersandEqualsToken */: + case 71 /* CaretEqualsToken */: + case 66 /* LessThanLessThanEqualsToken */: + case 67 /* GreaterThanGreaterThanEqualsToken */: + case 68 /* GreaterThanGreaterThanGreaterThanEqualsToken */: + case 60 /* PlusEqualsToken */: + case 61 /* MinusEqualsToken */: + case 62 /* AsteriskEqualsToken */: + case 64 /* SlashEqualsToken */: + case 65 /* PercentEqualsToken */: + case 59 /* EqualsToken */: + case 27 /* CommaToken */: + return true; + default: + return false; + } + } + function isPrefixUnaryExpressionOperatorToken(token) { + switch (token) { + case 38 /* PlusToken */: + case 39 /* MinusToken */: + case 53 /* TildeToken */: + case 52 /* ExclamationToken */: + case 44 /* PlusPlusToken */: + case 45 /* MinusMinusToken */: + return true; + default: + return false; + } + } + function classFromKind(token) { + if (ts.isKeyword(token)) { + return 3 /* keyword */; + } + else if (isBinaryExpressionOperatorToken(token) || isPrefixUnaryExpressionOperatorToken(token)) { + return 5 /* operator */; + } + else if (token >= 18 /* FirstPunctuation */ && token <= 71 /* LastPunctuation */) { + return 10 /* punctuation */; + } + switch (token) { + case 8 /* NumericLiteral */: + return 4 /* numericLiteral */; + case 9 /* BigIntLiteral */: + return 25 /* bigintLiteral */; + case 10 /* StringLiteral */: + return 6 /* stringLiteral */; + case 13 /* RegularExpressionLiteral */: + return 7 /* regularExpressionLiteral */; + case 7 /* ConflictMarkerTrivia */: + case 3 /* MultiLineCommentTrivia */: + case 2 /* SingleLineCommentTrivia */: + return 1 /* comment */; + case 5 /* WhitespaceTrivia */: + case 4 /* NewLineTrivia */: + return 8 /* whiteSpace */; + case 72 /* Identifier */: + default: + if (ts.isTemplateLiteralKind(token)) { + return 6 /* stringLiteral */; + } + return 2 /* identifier */; + } + } + /* @internal */ + function getSemanticClassifications(typeChecker, cancellationToken, sourceFile, classifiableNames, span) { + return convertClassificationsToSpans(getEncodedSemanticClassifications(typeChecker, cancellationToken, sourceFile, classifiableNames, span)); + } + ts.getSemanticClassifications = getSemanticClassifications; + function checkForClassificationCancellation(cancellationToken, kind) { + // We don't want to actually call back into our host on every node to find out if we've + // been canceled. That would be an enormous amount of chattyness, along with the all + // the overhead of marshalling the data to/from the host. So instead we pick a few + // reasonable node kinds to bother checking on. These node kinds represent high level + // constructs that we would expect to see commonly, but just at a far less frequent + // interval. + // + // For example, in checker.ts (around 750k) we only have around 600 of these constructs. + // That means we're calling back into the host around every 1.2k of the file we process. + // Lib.d.ts has similar numbers. + switch (kind) { + case 244 /* ModuleDeclaration */: + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + case 239 /* FunctionDeclaration */: + cancellationToken.throwIfCancellationRequested(); + } + } + /* @internal */ + function getEncodedSemanticClassifications(typeChecker, cancellationToken, sourceFile, classifiableNames, span) { + var spans = []; + sourceFile.forEachChild(function cb(node) { + // Only walk into nodes that intersect the requested span. + if (!node || !ts.textSpanIntersectsWith(span, node.pos, node.getFullWidth())) { + return; + } + checkForClassificationCancellation(cancellationToken, node.kind); + // Only bother calling into the typechecker if this is an identifier that + // could possibly resolve to a type name. This makes classification run + // in a third of the time it would normally take. + if (ts.isIdentifier(node) && !ts.nodeIsMissing(node) && classifiableNames.has(node.escapedText)) { + var symbol = typeChecker.getSymbolAtLocation(node); + var type = symbol && classifySymbol(symbol, ts.getMeaningFromLocation(node), typeChecker); + if (type) { + pushClassification(node.getStart(sourceFile), node.getEnd(), type); + } + } + node.forEachChild(cb); + }); + return { spans: spans, endOfLineState: 0 /* None */ }; + function pushClassification(start, end, type) { + spans.push(start); + spans.push(end - start); + spans.push(type); + } + } + ts.getEncodedSemanticClassifications = getEncodedSemanticClassifications; + function classifySymbol(symbol, meaningAtPosition, checker) { + var flags = symbol.getFlags(); + if ((flags & 2885600 /* Classifiable */) === 0 /* None */) { + return undefined; + } + else if (flags & 32 /* Class */) { + return 11 /* className */; + } + else if (flags & 384 /* Enum */) { + return 12 /* enumName */; + } + else if (flags & 524288 /* TypeAlias */) { + return 16 /* typeAliasName */; + } + else if (flags & 1536 /* Module */) { + // Only classify a module as such if + // - It appears in a namespace context. + // - There exists a module declaration which actually impacts the value side. + return meaningAtPosition & 4 /* Namespace */ || meaningAtPosition & 1 /* Value */ && hasValueSideModule(symbol) ? 14 /* moduleName */ : undefined; + } + else if (flags & 2097152 /* Alias */) { + return classifySymbol(checker.getAliasedSymbol(symbol), meaningAtPosition, checker); + } + else if (meaningAtPosition & 2 /* Type */) { + return flags & 64 /* Interface */ ? 13 /* interfaceName */ : flags & 262144 /* TypeParameter */ ? 15 /* typeParameterName */ : undefined; + } + else { + return undefined; + } + } + /** Returns true if there exists a module that introduces entities on the value side. */ + function hasValueSideModule(symbol) { + return ts.some(symbol.declarations, function (declaration) { + return ts.isModuleDeclaration(declaration) && ts.getModuleInstanceState(declaration) === 1 /* Instantiated */; + }); + } + function getClassificationTypeName(type) { + switch (type) { + case 1 /* comment */: return "comment" /* comment */; + case 2 /* identifier */: return "identifier" /* identifier */; + case 3 /* keyword */: return "keyword" /* keyword */; + case 4 /* numericLiteral */: return "number" /* numericLiteral */; + case 25 /* bigintLiteral */: return "bigint" /* bigintLiteral */; + case 5 /* operator */: return "operator" /* operator */; + case 6 /* stringLiteral */: return "string" /* stringLiteral */; + case 8 /* whiteSpace */: return "whitespace" /* whiteSpace */; + case 9 /* text */: return "text" /* text */; + case 10 /* punctuation */: return "punctuation" /* punctuation */; + case 11 /* className */: return "class name" /* className */; + case 12 /* enumName */: return "enum name" /* enumName */; + case 13 /* interfaceName */: return "interface name" /* interfaceName */; + case 14 /* moduleName */: return "module name" /* moduleName */; + case 15 /* typeParameterName */: return "type parameter name" /* typeParameterName */; + case 16 /* typeAliasName */: return "type alias name" /* typeAliasName */; + case 17 /* parameterName */: return "parameter name" /* parameterName */; + case 18 /* docCommentTagName */: return "doc comment tag name" /* docCommentTagName */; + case 19 /* jsxOpenTagName */: return "jsx open tag name" /* jsxOpenTagName */; + case 20 /* jsxCloseTagName */: return "jsx close tag name" /* jsxCloseTagName */; + case 21 /* jsxSelfClosingTagName */: return "jsx self closing tag name" /* jsxSelfClosingTagName */; + case 22 /* jsxAttribute */: return "jsx attribute" /* jsxAttribute */; + case 23 /* jsxText */: return "jsx text" /* jsxText */; + case 24 /* jsxAttributeStringLiteralValue */: return "jsx attribute string literal value" /* jsxAttributeStringLiteralValue */; + default: return undefined; // TODO: GH#18217 throw Debug.assertNever(type); + } + } + function convertClassificationsToSpans(classifications) { + ts.Debug.assert(classifications.spans.length % 3 === 0); + var dense = classifications.spans; + var result = []; + for (var i = 0; i < dense.length; i += 3) { + result.push({ + textSpan: ts.createTextSpan(dense[i], dense[i + 1]), + classificationType: getClassificationTypeName(dense[i + 2]) + }); + } + return result; + } + /* @internal */ + function getSyntacticClassifications(cancellationToken, sourceFile, span) { + return convertClassificationsToSpans(getEncodedSyntacticClassifications(cancellationToken, sourceFile, span)); + } + ts.getSyntacticClassifications = getSyntacticClassifications; + /* @internal */ + function getEncodedSyntacticClassifications(cancellationToken, sourceFile, span) { + var spanStart = span.start; + var spanLength = span.length; + // Make a scanner we can get trivia from. + var triviaScanner = ts.createScanner(6 /* Latest */, /*skipTrivia*/ false, sourceFile.languageVariant, sourceFile.text); + var mergeConflictScanner = ts.createScanner(6 /* Latest */, /*skipTrivia*/ false, sourceFile.languageVariant, sourceFile.text); + var result = []; + processElement(sourceFile); + return { spans: result, endOfLineState: 0 /* None */ }; + function pushClassification(start, length, type) { + result.push(start); + result.push(length); + result.push(type); + } + function classifyLeadingTriviaAndGetTokenStart(token) { + triviaScanner.setTextPos(token.pos); + while (true) { + var start = triviaScanner.getTextPos(); + // only bother scanning if we have something that could be trivia. + if (!ts.couldStartTrivia(sourceFile.text, start)) { + return start; + } + var kind = triviaScanner.scan(); + var end = triviaScanner.getTextPos(); + var width = end - start; + // The moment we get something that isn't trivia, then stop processing. + if (!ts.isTrivia(kind)) { + return start; + } + switch (kind) { + case 4 /* NewLineTrivia */: + case 5 /* WhitespaceTrivia */: + // Don't bother with newlines/whitespace. + continue; + case 2 /* SingleLineCommentTrivia */: + case 3 /* MultiLineCommentTrivia */: + // Only bother with the trivia if it at least intersects the span of interest. + classifyComment(token, kind, start, width); + // Classifying a comment might cause us to reuse the trivia scanner + // (because of jsdoc comments). So after we classify the comment make + // sure we set the scanner position back to where it needs to be. + triviaScanner.setTextPos(end); + continue; + case 7 /* ConflictMarkerTrivia */: + var text = sourceFile.text; + var ch = text.charCodeAt(start); + // for the <<<<<<< and >>>>>>> markers, we just add them in as comments + // in the classification stream. + if (ch === 60 /* lessThan */ || ch === 62 /* greaterThan */) { + pushClassification(start, width, 1 /* comment */); + continue; + } + // for the ||||||| and ======== markers, add a comment for the first line, + // and then lex all subsequent lines up until the end of the conflict marker. + ts.Debug.assert(ch === 124 /* bar */ || ch === 61 /* equals */); + classifyDisabledMergeCode(text, start, end); + break; + case 6 /* ShebangTrivia */: + // TODO: Maybe we should classify these. + break; + default: + ts.Debug.assertNever(kind); + } + } + } + function classifyComment(token, kind, start, width) { + if (kind === 3 /* MultiLineCommentTrivia */) { + // See if this is a doc comment. If so, we'll classify certain portions of it + // specially. + var docCommentAndDiagnostics = ts.parseIsolatedJSDocComment(sourceFile.text, start, width); + if (docCommentAndDiagnostics && docCommentAndDiagnostics.jsDoc) { + // TODO: This should be predicated on `token["kind"]` being compatible with `HasJSDoc["kind"]` + docCommentAndDiagnostics.jsDoc.parent = token; + classifyJSDocComment(docCommentAndDiagnostics.jsDoc); + return; + } + } + // Simple comment. Just add as is. + pushCommentRange(start, width); + } + function pushCommentRange(start, width) { + pushClassification(start, width, 1 /* comment */); + } + function classifyJSDocComment(docComment) { + var pos = docComment.pos; + if (docComment.tags) { + for (var _i = 0, _a = docComment.tags; _i < _a.length; _i++) { + var tag = _a[_i]; + // As we walk through each tag, classify the portion of text from the end of + // the last tag (or the start of the entire doc comment) as 'comment'. + if (tag.pos !== pos) { + pushCommentRange(pos, tag.pos - pos); + } + pushClassification(tag.pos, 1, 10 /* punctuation */); // "@" + pushClassification(tag.tagName.pos, tag.tagName.end - tag.tagName.pos, 18 /* docCommentTagName */); // e.g. "param" + pos = tag.tagName.end; + switch (tag.kind) { + case 299 /* JSDocParameterTag */: + processJSDocParameterTag(tag); + break; + case 303 /* JSDocTemplateTag */: + processJSDocTemplateTag(tag); + pos = tag.end; + break; + case 302 /* JSDocTypeTag */: + processElement(tag.typeExpression); + pos = tag.end; + break; + case 300 /* JSDocReturnTag */: + processElement(tag.typeExpression); + pos = tag.end; + break; + } + } + } + if (pos !== docComment.end) { + pushCommentRange(pos, docComment.end - pos); + } + return; + function processJSDocParameterTag(tag) { + if (tag.isNameFirst) { + pushCommentRange(pos, tag.name.pos - pos); + pushClassification(tag.name.pos, tag.name.end - tag.name.pos, 17 /* parameterName */); + pos = tag.name.end; + } + if (tag.typeExpression) { + pushCommentRange(pos, tag.typeExpression.pos - pos); + processElement(tag.typeExpression); + pos = tag.typeExpression.end; + } + if (!tag.isNameFirst) { + pushCommentRange(pos, tag.name.pos - pos); + pushClassification(tag.name.pos, tag.name.end - tag.name.pos, 17 /* parameterName */); + pos = tag.name.end; + } + } + } + function processJSDocTemplateTag(tag) { + for (var _i = 0, _a = tag.getChildren(); _i < _a.length; _i++) { + var child = _a[_i]; + processElement(child); + } + } + function classifyDisabledMergeCode(text, start, end) { + // Classify the line that the ||||||| or ======= marker is on as a comment. + // Then just lex all further tokens and add them to the result. + var i; + for (i = start; i < end; i++) { + if (ts.isLineBreak(text.charCodeAt(i))) { + break; + } + } + pushClassification(start, i - start, 1 /* comment */); + mergeConflictScanner.setTextPos(i); + while (mergeConflictScanner.getTextPos() < end) { + classifyDisabledCodeToken(); + } + } + function classifyDisabledCodeToken() { + var start = mergeConflictScanner.getTextPos(); + var tokenKind = mergeConflictScanner.scan(); + var end = mergeConflictScanner.getTextPos(); + var type = classifyTokenType(tokenKind); + if (type) { + pushClassification(start, end - start, type); + } + } + /** + * Returns true if node should be treated as classified and no further processing is required. + * False will mean that node is not classified and traverse routine should recurse into node contents. + */ + function tryClassifyNode(node) { + if (ts.isJSDoc(node)) { + return true; + } + if (ts.nodeIsMissing(node)) { + return true; + } + var classifiedElementName = tryClassifyJsxElementName(node); + if (!ts.isToken(node) && node.kind !== 11 /* JsxText */ && classifiedElementName === undefined) { + return false; + } + var tokenStart = node.kind === 11 /* JsxText */ ? node.pos : classifyLeadingTriviaAndGetTokenStart(node); + var tokenWidth = node.end - tokenStart; + ts.Debug.assert(tokenWidth >= 0); + if (tokenWidth > 0) { + var type = classifiedElementName || classifyTokenType(node.kind, node); + if (type) { + pushClassification(tokenStart, tokenWidth, type); + } + } + return true; + } + function tryClassifyJsxElementName(token) { + switch (token.parent && token.parent.kind) { + case 262 /* JsxOpeningElement */: + if (token.parent.tagName === token) { + return 19 /* jsxOpenTagName */; + } + break; + case 263 /* JsxClosingElement */: + if (token.parent.tagName === token) { + return 20 /* jsxCloseTagName */; + } + break; + case 261 /* JsxSelfClosingElement */: + if (token.parent.tagName === token) { + return 21 /* jsxSelfClosingTagName */; + } + break; + case 267 /* JsxAttribute */: + if (token.parent.name === token) { + return 22 /* jsxAttribute */; + } + break; + } + return undefined; + } + // for accurate classification, the actual token should be passed in. however, for + // cases like 'disabled merge code' classification, we just get the token kind and + // classify based on that instead. + function classifyTokenType(tokenKind, token) { + if (ts.isKeyword(tokenKind)) { + return 3 /* keyword */; + } + // Special case `<` and `>`: If they appear in a generic context they are punctuation, + // not operators. + if (tokenKind === 28 /* LessThanToken */ || tokenKind === 30 /* GreaterThanToken */) { + // If the node owning the token has a type argument list or type parameter list, then + // we can effectively assume that a '<' and '>' belong to those lists. + if (token && ts.getTypeArgumentOrTypeParameterList(token.parent)) { + return 10 /* punctuation */; + } + } + if (ts.isPunctuation(tokenKind)) { + if (token) { + var parent = token.parent; + if (tokenKind === 59 /* EqualsToken */) { + // the '=' in a variable declaration is special cased here. + if (parent.kind === 237 /* VariableDeclaration */ || + parent.kind === 154 /* PropertyDeclaration */ || + parent.kind === 151 /* Parameter */ || + parent.kind === 267 /* JsxAttribute */) { + return 5 /* operator */; + } + } + if (parent.kind === 204 /* BinaryExpression */ || + parent.kind === 202 /* PrefixUnaryExpression */ || + parent.kind === 203 /* PostfixUnaryExpression */ || + parent.kind === 205 /* ConditionalExpression */) { + return 5 /* operator */; + } + } + return 10 /* punctuation */; + } + else if (tokenKind === 8 /* NumericLiteral */) { + return 4 /* numericLiteral */; + } + else if (tokenKind === 9 /* BigIntLiteral */) { + return 25 /* bigintLiteral */; + } + else if (tokenKind === 10 /* StringLiteral */) { + // TODO: GH#18217 + return token.parent.kind === 267 /* JsxAttribute */ ? 24 /* jsxAttributeStringLiteralValue */ : 6 /* stringLiteral */; + } + else if (tokenKind === 13 /* RegularExpressionLiteral */) { + // TODO: we should get another classification type for these literals. + return 6 /* stringLiteral */; + } + else if (ts.isTemplateLiteralKind(tokenKind)) { + // TODO (drosen): we should *also* get another classification type for these literals. + return 6 /* stringLiteral */; + } + else if (tokenKind === 11 /* JsxText */) { + return 23 /* jsxText */; + } + else if (tokenKind === 72 /* Identifier */) { + if (token) { + switch (token.parent.kind) { + case 240 /* ClassDeclaration */: + if (token.parent.name === token) { + return 11 /* className */; + } + return; + case 150 /* TypeParameter */: + if (token.parent.name === token) { + return 15 /* typeParameterName */; + } + return; + case 241 /* InterfaceDeclaration */: + if (token.parent.name === token) { + return 13 /* interfaceName */; + } + return; + case 243 /* EnumDeclaration */: + if (token.parent.name === token) { + return 12 /* enumName */; + } + return; + case 244 /* ModuleDeclaration */: + if (token.parent.name === token) { + return 14 /* moduleName */; + } + return; + case 151 /* Parameter */: + if (token.parent.name === token) { + return ts.isThisIdentifier(token) ? 3 /* keyword */ : 17 /* parameterName */; + } + return; + } + } + return 2 /* identifier */; + } + } + function processElement(element) { + if (!element) { + return; + } + // Ignore nodes that don't intersect the original span to classify. + if (ts.decodedTextSpanIntersectsWith(spanStart, spanLength, element.pos, element.getFullWidth())) { + checkForClassificationCancellation(cancellationToken, element.kind); + for (var _i = 0, _a = element.getChildren(sourceFile); _i < _a.length; _i++) { + var child = _a[_i]; + if (!tryClassifyNode(child)) { + // Recurse into our child nodes. + processElement(child); + } + } + } + } + } + ts.getEncodedSyntacticClassifications = getEncodedSyntacticClassifications; +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var Completions; + (function (Completions) { + var StringCompletions; + (function (StringCompletions) { + function getStringLiteralCompletions(sourceFile, position, contextToken, checker, options, host, log, preferences) { + if (ts.isInReferenceComment(sourceFile, position)) { + var entries = getTripleSlashReferenceCompletion(sourceFile, position, options, host); + return entries && convertPathCompletions(entries); + } + if (ts.isInString(sourceFile, position, contextToken)) { + return !contextToken || !ts.isStringLiteralLike(contextToken) + ? undefined + : convertStringLiteralCompletions(getStringLiteralCompletionEntries(sourceFile, contextToken, position, checker, options, host), sourceFile, checker, log, preferences); + } + } + StringCompletions.getStringLiteralCompletions = getStringLiteralCompletions; + function convertStringLiteralCompletions(completion, sourceFile, checker, log, preferences) { + if (completion === undefined) { + return undefined; + } + switch (completion.kind) { + case 0 /* Paths */: + return convertPathCompletions(completion.paths); + case 1 /* Properties */: { + var entries = []; + Completions.getCompletionEntriesFromSymbols(completion.symbols, entries, sourceFile, sourceFile, checker, 6 /* ESNext */, log, 4 /* String */, preferences); // Target will not be used, so arbitrary + return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: completion.hasIndexSignature, entries: entries }; + } + case 2 /* Types */: { + var entries = completion.types.map(function (type) { return ({ name: type.value, kindModifiers: "" /* none */, kind: "string" /* string */, sortText: "0" }); }); + return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: completion.isNewIdentifier, entries: entries }; + } + default: + return ts.Debug.assertNever(completion); + } + } + function getStringLiteralCompletionDetails(name, sourceFile, position, contextToken, checker, options, host, cancellationToken) { + if (!contextToken || !ts.isStringLiteralLike(contextToken)) + return undefined; + var completions = getStringLiteralCompletionEntries(sourceFile, contextToken, position, checker, options, host); + return completions && stringLiteralCompletionDetails(name, contextToken, completions, sourceFile, checker, cancellationToken); + } + StringCompletions.getStringLiteralCompletionDetails = getStringLiteralCompletionDetails; + function stringLiteralCompletionDetails(name, location, completion, sourceFile, checker, cancellationToken) { + switch (completion.kind) { + case 0 /* Paths */: { + var match = ts.find(completion.paths, function (p) { return p.name === name; }); + return match && Completions.createCompletionDetails(name, kindModifiersFromExtension(match.extension), match.kind, [ts.textPart(name)]); + } + case 1 /* Properties */: { + var match = ts.find(completion.symbols, function (s) { return s.name === name; }); + return match && Completions.createCompletionDetailsForSymbol(match, checker, sourceFile, location, cancellationToken); + } + case 2 /* Types */: + return ts.find(completion.types, function (t) { return t.value === name; }) ? Completions.createCompletionDetails(name, "" /* none */, "type" /* typeElement */, [ts.textPart(name)]) : undefined; + default: + return ts.Debug.assertNever(completion); + } + } + function convertPathCompletions(pathCompletions) { + var isGlobalCompletion = false; // We don't want the editor to offer any other completions, such as snippets, inside a comment. + var isNewIdentifierLocation = true; // The user may type in a path that doesn't yet exist, creating a "new identifier" with respect to the collection of identifiers the server is aware of. + var entries = pathCompletions.map(function (_a) { + var name = _a.name, kind = _a.kind, span = _a.span, extension = _a.extension; + return ({ name: name, kind: kind, kindModifiers: kindModifiersFromExtension(extension), sortText: "0", replacementSpan: span }); + }); + return { isGlobalCompletion: isGlobalCompletion, isMemberCompletion: false, isNewIdentifierLocation: isNewIdentifierLocation, entries: entries }; + } + function kindModifiersFromExtension(extension) { + switch (extension) { + case ".d.ts" /* Dts */: return ".d.ts" /* dtsModifier */; + case ".js" /* Js */: return ".js" /* jsModifier */; + case ".json" /* Json */: return ".json" /* jsonModifier */; + case ".jsx" /* Jsx */: return ".jsx" /* jsxModifier */; + case ".ts" /* Ts */: return ".ts" /* tsModifier */; + case ".tsx" /* Tsx */: return ".tsx" /* tsxModifier */; + case undefined: return "" /* none */; + default: + return ts.Debug.assertNever(extension); + } + } + var StringLiteralCompletionKind; + (function (StringLiteralCompletionKind) { + StringLiteralCompletionKind[StringLiteralCompletionKind["Paths"] = 0] = "Paths"; + StringLiteralCompletionKind[StringLiteralCompletionKind["Properties"] = 1] = "Properties"; + StringLiteralCompletionKind[StringLiteralCompletionKind["Types"] = 2] = "Types"; + })(StringLiteralCompletionKind || (StringLiteralCompletionKind = {})); + function getStringLiteralCompletionEntries(sourceFile, node, position, typeChecker, compilerOptions, host) { + var parent = node.parent; + switch (parent.kind) { + case 182 /* LiteralType */: + switch (parent.parent.kind) { + case 164 /* TypeReference */: + return { kind: 2 /* Types */, types: getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(parent)), isNewIdentifier: false }; + case 180 /* IndexedAccessType */: + // Get all apparent property names + // i.e. interface Foo { + // foo: string; + // bar: string; + // } + // let x: Foo["/*completion position*/"] + return stringLiteralCompletionsFromProperties(typeChecker.getTypeFromTypeNode(parent.parent.objectType)); + case 183 /* ImportType */: + return { kind: 0 /* Paths */, paths: getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker) }; + case 173 /* UnionType */: { + if (!ts.isTypeReferenceNode(parent.parent.parent)) + return undefined; + var alreadyUsedTypes_1 = getAlreadyUsedTypesInStringLiteralUnion(parent.parent, parent); + var types = getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(parent.parent)).filter(function (t) { return !ts.contains(alreadyUsedTypes_1, t.value); }); + return { kind: 2 /* Types */, types: types, isNewIdentifier: false }; + } + default: + return undefined; + } + case 275 /* PropertyAssignment */: + if (ts.isObjectLiteralExpression(parent.parent) && parent.name === node) { + // Get quoted name of properties of the object literal expression + // i.e. interface ConfigFiles { + // 'jspm:dev': string + // } + // let files: ConfigFiles = { + // '/*completion position*/' + // } + // + // function foo(c: ConfigFiles) {} + // foo({ + // '/*completion position*/' + // }); + return stringLiteralCompletionsFromProperties(typeChecker.getContextualType(parent.parent)); + } + return fromContextualType(); + case 190 /* ElementAccessExpression */: { + var _a = parent, expression = _a.expression, argumentExpression = _a.argumentExpression; + if (node === argumentExpression) { + // Get all names of properties on the expression + // i.e. interface A { + // 'prop1': string + // } + // let a: A; + // a['/*completion position*/'] + return stringLiteralCompletionsFromProperties(typeChecker.getTypeAtLocation(expression)); + } + return undefined; + } + case 191 /* CallExpression */: + case 192 /* NewExpression */: + if (!ts.isRequireCall(parent, /*checkArgumentIsStringLiteralLike*/ false) && !ts.isImportCall(parent)) { + var argumentInfo = ts.SignatureHelp.getArgumentInfoForCompletions(node, position, sourceFile); + // Get string literal completions from specialized signatures of the target + // i.e. declare function f(a: 'A'); + // f("/*completion position*/") + return argumentInfo ? getStringLiteralCompletionsFromSignature(argumentInfo, typeChecker) : fromContextualType(); + } + // falls through (is `require("")` or `import("")`) + case 249 /* ImportDeclaration */: + case 255 /* ExportDeclaration */: + case 259 /* ExternalModuleReference */: + // Get all known external module names or complete a path to a module + // i.e. import * as ns from "/*completion position*/"; + // var y = import("/*completion position*/"); + // import x = require("/*completion position*/"); + // var y = require("/*completion position*/"); + // export * from "/*completion position*/"; + return { kind: 0 /* Paths */, paths: getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker) }; + default: + return fromContextualType(); + } + function fromContextualType() { + // Get completion for string literal from string literal type + // i.e. var x: "hi" | "hello" = "/*completion position*/" + return { kind: 2 /* Types */, types: getStringLiteralTypes(ts.getContextualTypeFromParent(node, typeChecker)), isNewIdentifier: false }; + } + } + function getAlreadyUsedTypesInStringLiteralUnion(union, current) { + return ts.mapDefined(union.types, function (type) { + return type !== current && ts.isLiteralTypeNode(type) && ts.isStringLiteral(type.literal) ? type.literal.text : undefined; + }); + } + function getStringLiteralCompletionsFromSignature(argumentInfo, checker) { + var isNewIdentifier = false; + var uniques = ts.createMap(); + var candidates = []; + checker.getResolvedSignature(argumentInfo.invocation, candidates, argumentInfo.argumentCount); + var types = ts.flatMap(candidates, function (candidate) { + if (!candidate.hasRestParameter && argumentInfo.argumentCount > candidate.parameters.length) + return; + var type = checker.getParameterType(candidate, argumentInfo.argumentIndex); + isNewIdentifier = isNewIdentifier || !!(type.flags & 4 /* String */); + return getStringLiteralTypes(type, uniques); + }); + return { kind: 2 /* Types */, types: types, isNewIdentifier: isNewIdentifier }; + } + function stringLiteralCompletionsFromProperties(type) { + return type && { kind: 1 /* Properties */, symbols: type.getApparentProperties(), hasIndexSignature: ts.hasIndexSignature(type) }; + } + function getStringLiteralTypes(type, uniques) { + if (uniques === void 0) { uniques = ts.createMap(); } + if (!type) + return ts.emptyArray; + type = ts.skipConstraint(type); + return type.isUnion() + ? ts.flatMap(type.types, function (t) { return getStringLiteralTypes(t, uniques); }) + : type.isStringLiteral() && !(type.flags & 1024 /* EnumLiteral */) && ts.addToSeen(uniques, type.value) + ? [type] + : ts.emptyArray; + } + function nameAndKind(name, kind, extension) { + return { name: name, kind: kind, extension: extension }; + } + function directoryResult(name) { + return nameAndKind(name, "directory" /* directory */, /*extension*/ undefined); + } + function addReplacementSpans(text, textStart, names) { + var span = getDirectoryFragmentTextSpan(text, textStart); + return names.map(function (_a) { + var name = _a.name, kind = _a.kind, extension = _a.extension; + return ({ name: name, kind: kind, extension: extension, span: span }); + }); + } + function getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker) { + return addReplacementSpans(node.text, node.getStart(sourceFile) + 1, getStringLiteralCompletionsFromModuleNamesWorker(sourceFile, node, compilerOptions, host, typeChecker)); + } + function getStringLiteralCompletionsFromModuleNamesWorker(sourceFile, node, compilerOptions, host, typeChecker) { + var literalValue = ts.normalizeSlashes(node.text); + var scriptPath = sourceFile.path; + var scriptDirectory = ts.getDirectoryPath(scriptPath); + return isPathRelativeToScript(literalValue) || !compilerOptions.baseUrl && (ts.isRootedDiskPath(literalValue) || ts.isUrl(literalValue)) + ? getCompletionEntriesForRelativeModules(literalValue, scriptDirectory, compilerOptions, host, scriptPath) + : getCompletionEntriesForNonRelativeModules(literalValue, scriptDirectory, compilerOptions, host, typeChecker); + } + function getExtensionOptions(compilerOptions, includeExtensions) { + if (includeExtensions === void 0) { includeExtensions = false; } + return { extensions: getSupportedExtensionsForModuleResolution(compilerOptions), includeExtensions: includeExtensions }; + } + function getCompletionEntriesForRelativeModules(literalValue, scriptDirectory, compilerOptions, host, scriptPath) { + var extensionOptions = getExtensionOptions(compilerOptions); + if (compilerOptions.rootDirs) { + return getCompletionEntriesForDirectoryFragmentWithRootDirs(compilerOptions.rootDirs, literalValue, scriptDirectory, extensionOptions, compilerOptions, host, scriptPath); + } + else { + return getCompletionEntriesForDirectoryFragment(literalValue, scriptDirectory, extensionOptions, host, scriptPath); + } + } + function getSupportedExtensionsForModuleResolution(compilerOptions) { + var extensions = ts.getSupportedExtensions(compilerOptions); + return compilerOptions.resolveJsonModule && ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs ? + extensions.concat(".json" /* Json */) : + extensions; + } + /** + * Takes a script path and returns paths for all potential folders that could be merged with its + * containing folder via the "rootDirs" compiler option + */ + function getBaseDirectoriesFromRootDirs(rootDirs, basePath, scriptDirectory, ignoreCase) { + // Make all paths absolute/normalized if they are not already + rootDirs = rootDirs.map(function (rootDirectory) { return ts.normalizePath(ts.isRootedDiskPath(rootDirectory) ? rootDirectory : ts.combinePaths(basePath, rootDirectory)); }); + // Determine the path to the directory containing the script relative to the root directory it is contained within + var relativeDirectory = ts.firstDefined(rootDirs, function (rootDirectory) { + return ts.containsPath(rootDirectory, scriptDirectory, basePath, ignoreCase) ? scriptDirectory.substr(rootDirectory.length) : undefined; + }); // TODO: GH#18217 + // Now find a path for each potential directory that is to be merged with the one containing the script + return ts.deduplicate(rootDirs.map(function (rootDirectory) { return ts.combinePaths(rootDirectory, relativeDirectory); }).concat([scriptDirectory]), ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive); + } + function getCompletionEntriesForDirectoryFragmentWithRootDirs(rootDirs, fragment, scriptDirectory, extensionOptions, compilerOptions, host, exclude) { + var basePath = compilerOptions.project || host.getCurrentDirectory(); + var ignoreCase = !(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames()); + var baseDirectories = getBaseDirectoriesFromRootDirs(rootDirs, basePath, scriptDirectory, ignoreCase); + return ts.flatMap(baseDirectories, function (baseDirectory) { return getCompletionEntriesForDirectoryFragment(fragment, baseDirectory, extensionOptions, host, exclude); }); + } + /** + * Given a path ending at a directory, gets the completions for the path, and filters for those entries containing the basename. + */ + function getCompletionEntriesForDirectoryFragment(fragment, scriptPath, _a, host, exclude, result) { + var extensions = _a.extensions, includeExtensions = _a.includeExtensions; + if (result === void 0) { result = []; } + if (fragment === undefined) { + fragment = ""; + } + fragment = ts.normalizeSlashes(fragment); + /** + * Remove the basename from the path. Note that we don't use the basename to filter completions; + * the client is responsible for refining completions. + */ + if (!ts.hasTrailingDirectorySeparator(fragment)) { + fragment = ts.getDirectoryPath(fragment); + } + if (fragment === "") { + fragment = "." + ts.directorySeparator; + } + fragment = ts.ensureTrailingDirectorySeparator(fragment); + // const absolutePath = normalizeAndPreserveTrailingSlash(isRootedDiskPath(fragment) ? fragment : combinePaths(scriptPath, fragment)); // TODO(rbuckton): should use resolvePaths + var absolutePath = ts.resolvePath(scriptPath, fragment); + var baseDirectory = ts.hasTrailingDirectorySeparator(absolutePath) ? absolutePath : ts.getDirectoryPath(absolutePath); + var ignoreCase = !(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames()); + if (!tryDirectoryExists(host, baseDirectory)) + return result; + // Enumerate the available files if possible + var files = tryReadDirectory(host, baseDirectory, extensions, /*exclude*/ undefined, /*include*/ ["./*"]); + if (files) { + /** + * Multiple file entries might map to the same truncated name once we remove extensions + * (happens iff includeExtensions === false)so we use a set-like data structure. Eg: + * + * both foo.ts and foo.tsx become foo + */ + var foundFiles = ts.createMap(); // maps file to its extension + for (var _i = 0, files_1 = files; _i < files_1.length; _i++) { + var filePath = files_1[_i]; + filePath = ts.normalizePath(filePath); + if (exclude && ts.comparePaths(filePath, exclude, scriptPath, ignoreCase) === 0 /* EqualTo */) { + continue; + } + var foundFileName = includeExtensions || ts.fileExtensionIs(filePath, ".json" /* Json */) ? ts.getBaseFileName(filePath) : ts.removeFileExtension(ts.getBaseFileName(filePath)); + foundFiles.set(foundFileName, ts.tryGetExtensionFromPath(filePath)); + } + foundFiles.forEach(function (ext, foundFile) { + result.push(nameAndKind(foundFile, "script" /* scriptElement */, ext)); + }); + } + // If possible, get folder completion as well + var directories = tryGetDirectories(host, baseDirectory); + if (directories) { + for (var _b = 0, directories_1 = directories; _b < directories_1.length; _b++) { + var directory = directories_1[_b]; + var directoryName = ts.getBaseFileName(ts.normalizePath(directory)); + if (directoryName !== "@types") { + result.push(directoryResult(directoryName)); + } + } + } + // check for a version redirect + var packageJsonPath = findPackageJson(baseDirectory, host); + if (packageJsonPath) { + var packageJson = ts.readJson(packageJsonPath, host); + var typesVersions = packageJson.typesVersions; + if (typeof typesVersions === "object") { + var versionResult = ts.getPackageJsonTypesVersionsPaths(typesVersions); + var versionPaths = versionResult && versionResult.paths; + var rest = absolutePath.slice(ts.ensureTrailingDirectorySeparator(baseDirectory).length); + if (versionPaths) { + addCompletionEntriesFromPaths(result, rest, baseDirectory, extensions, versionPaths, host); + } + } + } + return result; + } + function addCompletionEntriesFromPaths(result, fragment, baseDirectory, fileExtensions, paths, host) { + for (var path in paths) { + if (!ts.hasProperty(paths, path)) + continue; + var patterns = paths[path]; + if (patterns) { + var _loop_1 = function (name, kind, extension) { + // Path mappings may provide a duplicate way to get to something we've already added, so don't add again. + if (!result.some(function (entry) { return entry.name === name; })) { + result.push(nameAndKind(name, kind, extension)); + } + }; + for (var _i = 0, _a = getCompletionsForPathMapping(path, patterns, fragment, baseDirectory, fileExtensions, host); _i < _a.length; _i++) { + var _b = _a[_i], name = _b.name, kind = _b.kind, extension = _b.extension; + _loop_1(name, kind, extension); + } + } + } + } + /** + * Check all of the declared modules and those in node modules. Possible sources of modules: + * Modules that are found by the type checker + * Modules found relative to "baseUrl" compliler options (including patterns from "paths" compiler option) + * Modules from node_modules (i.e. those listed in package.json) + * This includes all files that are found in node_modules/moduleName/ with acceptable file extensions + */ + function getCompletionEntriesForNonRelativeModules(fragment, scriptPath, compilerOptions, host, typeChecker) { + var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths; + var result = []; + var extensionOptions = getExtensionOptions(compilerOptions); + if (baseUrl) { + var projectDir = compilerOptions.project || host.getCurrentDirectory(); + var absolute = ts.normalizePath(ts.combinePaths(projectDir, baseUrl)); + getCompletionEntriesForDirectoryFragment(fragment, absolute, extensionOptions, host, /*exclude*/ undefined, result); + if (paths) { + addCompletionEntriesFromPaths(result, fragment, absolute, extensionOptions.extensions, paths, host); + } + } + var fragmentDirectory = getFragmentDirectory(fragment); + for (var _i = 0, _a = getAmbientModuleCompletions(fragment, fragmentDirectory, typeChecker); _i < _a.length; _i++) { + var ambientName = _a[_i]; + result.push(nameAndKind(ambientName, "external module name" /* externalModuleName */, /*extension*/ undefined)); + } + getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, fragmentDirectory, extensionOptions, result); + if (ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs) { + // If looking for a global package name, don't just include everything in `node_modules` because that includes dependencies' own dependencies. + // (But do if we didn't find anything, e.g. 'package.json' missing.) + var foundGlobal = false; + if (fragmentDirectory === undefined) { + var _loop_2 = function (moduleName) { + if (!result.some(function (entry) { return entry.name === moduleName; })) { + foundGlobal = true; + result.push(nameAndKind(moduleName, "external module name" /* externalModuleName */, /*extension*/ undefined)); + } + }; + for (var _b = 0, _c = enumerateNodeModulesVisibleToScript(host, scriptPath); _b < _c.length; _b++) { + var moduleName = _c[_b]; + _loop_2(moduleName); + } + } + if (!foundGlobal) { + ts.forEachAncestorDirectory(scriptPath, function (ancestor) { + var nodeModules = ts.combinePaths(ancestor, "node_modules"); + if (tryDirectoryExists(host, nodeModules)) { + getCompletionEntriesForDirectoryFragment(fragment, nodeModules, extensionOptions, host, /*exclude*/ undefined, result); + } + }); + } + } + return result; + } + function getFragmentDirectory(fragment) { + return containsSlash(fragment) ? ts.hasTrailingDirectorySeparator(fragment) ? fragment : ts.getDirectoryPath(fragment) : undefined; + } + function getCompletionsForPathMapping(path, patterns, fragment, baseUrl, fileExtensions, host) { + if (!ts.endsWith(path, "*")) { + // For a path mapping "foo": ["/x/y/z.ts"], add "foo" itself as a completion. + return !ts.stringContains(path, "*") ? justPathMappingName(path) : ts.emptyArray; + } + var pathPrefix = path.slice(0, path.length - 1); + var remainingFragment = ts.tryRemovePrefix(fragment, pathPrefix); + return remainingFragment === undefined ? justPathMappingName(pathPrefix) : ts.flatMap(patterns, function (pattern) { + return getModulesForPathsPattern(remainingFragment, baseUrl, pattern, fileExtensions, host); + }); + function justPathMappingName(name) { + return ts.startsWith(name, fragment) ? [directoryResult(name)] : ts.emptyArray; + } + } + function getModulesForPathsPattern(fragment, baseUrl, pattern, fileExtensions, host) { + if (!host.readDirectory) { + return undefined; + } + var parsed = ts.hasZeroOrOneAsteriskCharacter(pattern) ? ts.tryParsePattern(pattern) : undefined; + if (!parsed) { + return undefined; + } + // The prefix has two effective parts: the directory path and the base component after the filepath that is not a + // full directory component. For example: directory/path/of/prefix/base* + var normalizedPrefix = ts.resolvePath(parsed.prefix); + var normalizedPrefixDirectory = ts.hasTrailingDirectorySeparator(parsed.prefix) ? normalizedPrefix : ts.getDirectoryPath(normalizedPrefix); + var normalizedPrefixBase = ts.hasTrailingDirectorySeparator(parsed.prefix) ? "" : ts.getBaseFileName(normalizedPrefix); + var fragmentHasPath = containsSlash(fragment); + var fragmentDirectory = fragmentHasPath ? ts.hasTrailingDirectorySeparator(fragment) ? fragment : ts.getDirectoryPath(fragment) : undefined; + // Try and expand the prefix to include any path from the fragment so that we can limit the readDirectory call + var expandedPrefixDirectory = fragmentHasPath ? ts.combinePaths(normalizedPrefixDirectory, normalizedPrefixBase + fragmentDirectory) : normalizedPrefixDirectory; + var normalizedSuffix = ts.normalizePath(parsed.suffix); + // Need to normalize after combining: If we combinePaths("a", "../b"), we want "b" and not "a/../b". + var baseDirectory = ts.normalizePath(ts.combinePaths(baseUrl, expandedPrefixDirectory)); + var completePrefix = fragmentHasPath ? baseDirectory : ts.ensureTrailingDirectorySeparator(baseDirectory) + normalizedPrefixBase; + // If we have a suffix, then we need to read the directory all the way down. We could create a glob + // that encodes the suffix, but we would have to escape the character "?" which readDirectory + // doesn't support. For now, this is safer but slower + var includeGlob = normalizedSuffix ? "**/*" : "./*"; + var matches = ts.mapDefined(tryReadDirectory(host, baseDirectory, fileExtensions, /*exclude*/ undefined, [includeGlob]), function (match) { + var extension = ts.tryGetExtensionFromPath(match); + var name = trimPrefixAndSuffix(match); + return name === undefined ? undefined : nameAndKind(ts.removeFileExtension(name), "script" /* scriptElement */, extension); + }); + var directories = ts.mapDefined(tryGetDirectories(host, baseDirectory).map(function (d) { return ts.combinePaths(baseDirectory, d); }), function (dir) { + var name = trimPrefixAndSuffix(dir); + return name === undefined ? undefined : directoryResult(name); + }); + return matches.concat(directories); + function trimPrefixAndSuffix(path) { + var inner = withoutStartAndEnd(ts.normalizePath(path), completePrefix, normalizedSuffix); + return inner === undefined ? undefined : removeLeadingDirectorySeparator(inner); + } + } + function withoutStartAndEnd(s, start, end) { + return ts.startsWith(s, start) && ts.endsWith(s, end) ? s.slice(start.length, s.length - end.length) : undefined; + } + function removeLeadingDirectorySeparator(path) { + return path[0] === ts.directorySeparator ? path.slice(1) : path; + } + function getAmbientModuleCompletions(fragment, fragmentDirectory, checker) { + // Get modules that the type checker picked up + var ambientModules = checker.getAmbientModules().map(function (sym) { return ts.stripQuotes(sym.name); }); + var nonRelativeModuleNames = ambientModules.filter(function (moduleName) { return ts.startsWith(moduleName, fragment); }); + // Nested modules of the form "module-name/sub" need to be adjusted to only return the string + // after the last '/' that appears in the fragment because that's where the replacement span + // starts + if (fragmentDirectory !== undefined) { + var moduleNameWithSeparator_1 = ts.ensureTrailingDirectorySeparator(fragmentDirectory); + return nonRelativeModuleNames.map(function (nonRelativeModuleName) { return ts.removePrefix(nonRelativeModuleName, moduleNameWithSeparator_1); }); + } + return nonRelativeModuleNames; + } + function getTripleSlashReferenceCompletion(sourceFile, position, compilerOptions, host) { + var token = ts.getTokenAtPosition(sourceFile, position); + var commentRanges = ts.getLeadingCommentRanges(sourceFile.text, token.pos); + var range = commentRanges && ts.find(commentRanges, function (commentRange) { return position >= commentRange.pos && position <= commentRange.end; }); + if (!range) { + return undefined; + } + var text = sourceFile.text.slice(range.pos, position); + var match = tripleSlashDirectiveFragmentRegex.exec(text); + if (!match) { + return undefined; + } + var prefix = match[1], kind = match[2], toComplete = match[3]; + var scriptPath = ts.getDirectoryPath(sourceFile.path); + var names = kind === "path" ? getCompletionEntriesForDirectoryFragment(toComplete, scriptPath, getExtensionOptions(compilerOptions, /*includeExtensions*/ true), host, sourceFile.path) + : kind === "types" ? getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, getFragmentDirectory(toComplete), getExtensionOptions(compilerOptions)) + : ts.Debug.fail(); + return addReplacementSpans(toComplete, range.pos + prefix.length, names); + } + function getCompletionEntriesFromTypings(host, options, scriptPath, fragmentDirectory, extensionOptions, result) { + if (result === void 0) { result = []; } + // Check for typings specified in compiler options + var seen = ts.createMap(); + var typeRoots = tryAndIgnoreErrors(function () { return ts.getEffectiveTypeRoots(options, host); }) || ts.emptyArray; + for (var _i = 0, typeRoots_1 = typeRoots; _i < typeRoots_1.length; _i++) { + var root = typeRoots_1[_i]; + getCompletionEntriesFromDirectories(root); + } + // Also get all @types typings installed in visible node_modules directories + for (var _a = 0, _b = findPackageJsons(scriptPath, host); _a < _b.length; _a++) { + var packageJson = _b[_a]; + var typesDir = ts.combinePaths(ts.getDirectoryPath(packageJson), "node_modules/@types"); + getCompletionEntriesFromDirectories(typesDir); + } + return result; + function getCompletionEntriesFromDirectories(directory) { + if (!tryDirectoryExists(host, directory)) + return; + for (var _i = 0, _a = tryGetDirectories(host, directory); _i < _a.length; _i++) { + var typeDirectoryName = _a[_i]; + var packageName = ts.unmangleScopedPackageName(typeDirectoryName); + if (options.types && !ts.contains(options.types, packageName)) + continue; + if (fragmentDirectory === undefined) { + if (!seen.has(packageName)) { + result.push(nameAndKind(packageName, "external module name" /* externalModuleName */, /*extension*/ undefined)); + seen.set(packageName, true); + } + } + else { + var baseDirectory = ts.combinePaths(directory, typeDirectoryName); + var remainingFragment = ts.tryRemoveDirectoryPrefix(fragmentDirectory, packageName, ts.hostGetCanonicalFileName(host)); + if (remainingFragment !== undefined) { + getCompletionEntriesForDirectoryFragment(remainingFragment, baseDirectory, extensionOptions, host, /*exclude*/ undefined, result); + } + } + } + } + } + function findPackageJsons(directory, host) { + var paths = []; + ts.forEachAncestorDirectory(directory, function (ancestor) { + var currentConfigPath = ts.findConfigFile(ancestor, function (f) { return tryFileExists(host, f); }, "package.json"); + if (!currentConfigPath) { + return true; // break out + } + paths.push(currentConfigPath); + }); + return paths; + } + function findPackageJson(directory, host) { + var packageJson; + ts.forEachAncestorDirectory(directory, function (ancestor) { + if (ancestor === "node_modules") + return true; + packageJson = ts.findConfigFile(ancestor, function (f) { return tryFileExists(host, f); }, "package.json"); + if (packageJson) { + return true; // break out + } + }); + return packageJson; + } + function enumerateNodeModulesVisibleToScript(host, scriptPath) { + if (!host.readFile || !host.fileExists) + return ts.emptyArray; + var result = []; + for (var _i = 0, _a = findPackageJsons(scriptPath, host); _i < _a.length; _i++) { + var packageJson = _a[_i]; + var contents = ts.readJson(packageJson, host); // Cast to assert that readFile is defined + // Provide completions for all non @types dependencies + for (var _b = 0, nodeModulesDependencyKeys_1 = nodeModulesDependencyKeys; _b < nodeModulesDependencyKeys_1.length; _b++) { + var key = nodeModulesDependencyKeys_1[_b]; + var dependencies = contents[key]; + if (!dependencies) + continue; + for (var dep in dependencies) { + if (dependencies.hasOwnProperty(dep) && !ts.startsWith(dep, "@types/")) { + result.push(dep); + } + } + } + } + return result; + } + // Replace everything after the last directory separator that appears + function getDirectoryFragmentTextSpan(text, textStart) { + var index = Math.max(text.lastIndexOf(ts.directorySeparator), text.lastIndexOf("\\")); + var offset = index !== -1 ? index + 1 : 0; + // If the range is an identifier, span is unnecessary. + var length = text.length - offset; + return length === 0 || ts.isIdentifierText(text.substr(offset, length), 6 /* ESNext */) ? undefined : ts.createTextSpan(textStart + offset, length); + } + // Returns true if the path is explicitly relative to the script (i.e. relative to . or ..) + function isPathRelativeToScript(path) { + if (path && path.length >= 2 && path.charCodeAt(0) === 46 /* dot */) { + var slashIndex = path.length >= 3 && path.charCodeAt(1) === 46 /* dot */ ? 2 : 1; + var slashCharCode = path.charCodeAt(slashIndex); + return slashCharCode === 47 /* slash */ || slashCharCode === 92 /* backslash */; + } + return false; + } + /** + * Matches a triple slash reference directive with an incomplete string literal for its path. Used + * to determine if the caret is currently within the string literal and capture the literal fragment + * for completions. + * For example, this matches + * + * /// " with type any + // And at `
      ` (with a closing `>`), the completion list will contain "div". + var tagName = location.parent.parent.openingElement.tagName; + var hasClosingAngleBracket = !!ts.findChildOfKind(location.parent, 30 /* GreaterThanToken */, sourceFile); + var entry = { + name: tagName.getFullText(sourceFile) + (hasClosingAngleBracket ? "" : ">"), + kind: "class" /* classElement */, + kindModifiers: undefined, + sortText: "0", + }; + return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: false, entries: [entry] }; + } + var entries = []; + if (isUncheckedFile(sourceFile, compilerOptions)) { + var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, preferences, propertyAccessToConvert, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap); + getJSCompletionEntries(sourceFile, location.pos, uniqueNames, compilerOptions.target, entries); // TODO: GH#18217 + } + else { + if ((!symbols || symbols.length === 0) && keywordFilters === 0 /* None */) { + return undefined; + } + getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, preferences, propertyAccessToConvert, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap); + } + if (keywordFilters !== 0 /* None */) { + var entryNames = ts.arrayToSet(entries, function (e) { return e.name; }); + for (var _i = 0, _a = getKeywordCompletions(keywordFilters); _i < _a.length; _i++) { + var keywordEntry = _a[_i]; + if (!entryNames.has(keywordEntry.name)) { + entries.push(keywordEntry); + } + } + } + for (var _b = 0, literals_1 = literals; _b < literals_1.length; _b++) { + var literal = literals_1[_b]; + entries.push(createCompletionEntryForLiteral(literal)); + } + return { isGlobalCompletion: isInSnippetScope, isMemberCompletion: isMemberCompletionKind(completionKind), isNewIdentifierLocation: isNewIdentifierLocation, entries: entries }; + } + function isUncheckedFile(sourceFile, compilerOptions) { + return ts.isSourceFileJS(sourceFile) && !ts.isCheckJsEnabledForFile(sourceFile, compilerOptions); + } + function isMemberCompletionKind(kind) { + switch (kind) { + case 0 /* ObjectPropertyDeclaration */: + case 3 /* MemberLike */: + case 2 /* PropertyAccess */: + return true; + default: + return false; + } + } + function getJSCompletionEntries(sourceFile, position, uniqueNames, target, entries) { + ts.getNameTable(sourceFile).forEach(function (pos, name) { + // Skip identifiers produced only from the current location + if (pos === position) { + return; + } + var realName = ts.unescapeLeadingUnderscores(name); + if (ts.addToSeen(uniqueNames, realName) && ts.isIdentifierText(realName, target)) { + entries.push({ + name: realName, + kind: "warning" /* warning */, + kindModifiers: "", + sortText: "1" + }); + } + }); + } + var completionNameForLiteral = function (literal) { + return typeof literal === "object" ? ts.pseudoBigIntToString(literal) + "n" : JSON.stringify(literal); + }; + function createCompletionEntryForLiteral(literal) { + return { name: completionNameForLiteral(literal), kind: "string" /* string */, kindModifiers: "" /* none */, sortText: "0" }; + } + function createCompletionEntry(symbol, location, sourceFile, typeChecker, target, kind, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, preferences) { + var info = getCompletionEntryDisplayNameForSymbol(symbol, target, origin, kind); + if (!info) { + return undefined; + } + var name = info.name, needsConvertPropertyAccess = info.needsConvertPropertyAccess; + var insertText; + var replacementSpan; + if (origin && origin.kind === 0 /* ThisType */) { + insertText = needsConvertPropertyAccess ? "this[" + ts.quote(name, preferences) + "]" : "this." + name; + } + // We should only have needsConvertPropertyAccess if there's a property access to convert. But see #21790. + // Somehow there was a global with a non-identifier name. Hopefully someone will complain about getting a "foo bar" global completion and provide a repro. + else if ((origin && originIsSymbolMember(origin) || needsConvertPropertyAccess) && propertyAccessToConvert) { + insertText = needsConvertPropertyAccess ? "[" + ts.quote(name, preferences) + "]" : "[" + name + "]"; + var dot = ts.findChildOfKind(propertyAccessToConvert, 24 /* DotToken */, sourceFile); + // If the text after the '.' starts with this name, write over it. Else, add new text. + var end = ts.startsWith(name, propertyAccessToConvert.name.text) ? propertyAccessToConvert.name.end : dot.end; + replacementSpan = ts.createTextSpanFromBounds(dot.getStart(sourceFile), end); + } + if (isJsxInitializer) { + if (insertText === undefined) + insertText = name; + insertText = "{" + insertText + "}"; + if (typeof isJsxInitializer !== "boolean") { + replacementSpan = ts.createTextSpanFromNode(isJsxInitializer, sourceFile); + } + } + if (insertText !== undefined && !preferences.includeCompletionsWithInsertText) { + return undefined; + } + // TODO(drosen): Right now we just permit *all* semantic meanings when calling + // 'getSymbolKind' which is permissible given that it is backwards compatible; but + // really we should consider passing the meaning for the node so that we don't report + // that a suggestion for a value is an interface. We COULD also just do what + // 'getSymbolModifiers' does, which is to use the first declaration. + // Use a 'sortText' of 0' so that all symbol completion entries come before any other + // entries (like JavaScript identifier entries). + return { + name: name, + kind: ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, location), + kindModifiers: ts.SymbolDisplay.getSymbolModifiers(symbol), + sortText: "0", + source: getSourceFromOrigin(origin), + hasAction: trueOrUndefined(!!origin && originIsExport(origin)), + isRecommended: trueOrUndefined(isRecommendedCompletionMatch(symbol, recommendedCompletion, typeChecker)), + insertText: insertText, + replacementSpan: replacementSpan, + }; + } + function isRecommendedCompletionMatch(localSymbol, recommendedCompletion, checker) { + return localSymbol === recommendedCompletion || + !!(localSymbol.flags & 1048576 /* ExportValue */) && checker.getExportSymbolOfSymbol(localSymbol) === recommendedCompletion; + } + function trueOrUndefined(b) { + return b ? true : undefined; + } + function getSourceFromOrigin(origin) { + return origin && originIsExport(origin) ? ts.stripQuotes(origin.moduleSymbol.name) : undefined; + } + function getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, target, log, kind, preferences, propertyAccessToConvert, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap) { + var start = ts.timestamp(); + // Tracks unique names. + // We don't set this for global variables or completions from external module exports, because we can have multiple of those. + // Based on the order we add things we will always see locals first, then globals, then module exports. + // So adding a completion for a local will prevent us from adding completions for external module exports sharing the same name. + var uniques = ts.createMap(); + for (var _i = 0, symbols_1 = symbols; _i < symbols_1.length; _i++) { + var symbol = symbols_1[_i]; + var origin = symbolToOriginInfoMap ? symbolToOriginInfoMap[ts.getSymbolId(symbol)] : undefined; + var entry = createCompletionEntry(symbol, location, sourceFile, typeChecker, target, kind, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, preferences); + if (!entry) { + continue; + } + var name = entry.name; + if (uniques.has(name)) { + continue; + } + // Latter case tests whether this is a global variable. + if (!origin && !(symbol.parent === undefined && !ts.some(symbol.declarations, function (d) { return d.getSourceFile() === location.getSourceFile(); }))) { // TODO: GH#18217 + uniques.set(name, true); + } + entries.push(entry); + } + log("getCompletionsAtPosition: getCompletionEntriesFromSymbols: " + (ts.timestamp() - start)); + return uniques; + } + Completions.getCompletionEntriesFromSymbols = getCompletionEntriesFromSymbols; + function getLabelCompletionAtPosition(node) { + var entries = getLabelStatementCompletions(node); + if (entries.length) { + return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries }; + } + } + function getLabelStatementCompletions(node) { + var entries = []; + var uniques = ts.createMap(); + var current = node; + while (current) { + if (ts.isFunctionLike(current)) { + break; + } + if (ts.isLabeledStatement(current)) { + var name = current.label.text; + if (!uniques.has(name)) { + uniques.set(name, true); + entries.push({ + name: name, + kindModifiers: "" /* none */, + kind: "label" /* label */, + sortText: "0" + }); + } + } + current = current.parent; + } + return entries; + } + function getSymbolCompletionFromEntryId(program, log, sourceFile, position, entryId) { + var compilerOptions = program.getCompilerOptions(); + var completionData = getCompletionData(program, log, sourceFile, isUncheckedFile(sourceFile, compilerOptions), position, { includeCompletionsForModuleExports: true, includeCompletionsWithInsertText: true }, entryId); + if (!completionData) { + return { type: "none" }; + } + if (completionData.kind !== 0 /* Data */) { + return { type: "request", request: completionData }; + } + var symbols = completionData.symbols, literals = completionData.literals, location = completionData.location, completionKind = completionData.completionKind, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap, previousToken = completionData.previousToken, isJsxInitializer = completionData.isJsxInitializer; + var literal = ts.find(literals, function (l) { return completionNameForLiteral(l) === entryId.name; }); + if (literal !== undefined) + return { type: "literal", literal: literal }; + // Find the symbol with the matching entry name. + // We don't need to perform character checks here because we're only comparing the + // name against 'entryName' (which is known to be good), not building a new + // completion entry. + return ts.firstDefined(symbols, function (symbol) { + var origin = symbolToOriginInfoMap[ts.getSymbolId(symbol)]; + var info = getCompletionEntryDisplayNameForSymbol(symbol, compilerOptions.target, origin, completionKind); + return info && info.name === entryId.name && getSourceFromOrigin(origin) === entryId.source + ? { type: "symbol", symbol: symbol, location: location, symbolToOriginInfoMap: symbolToOriginInfoMap, previousToken: previousToken, isJsxInitializer: isJsxInitializer } + : undefined; + }) || { type: "none" }; + } + function getSymbolName(symbol, origin, target) { + return origin && originIsExport(origin) && origin.isDefaultExport && symbol.escapedName === "default" /* Default */ + // Name of "export default foo;" is "foo". Name of "export default 0" is the filename converted to camelCase. + ? ts.firstDefined(symbol.declarations, function (d) { return ts.isExportAssignment(d) && ts.isIdentifier(d.expression) ? d.expression.text : undefined; }) + || ts.codefix.moduleSymbolToValidIdentifier(origin.moduleSymbol, target) + : symbol.name; + } + function getCompletionEntryDetails(program, log, sourceFile, position, entryId, host, formatContext, preferences, cancellationToken) { + var typeChecker = program.getTypeChecker(); + var compilerOptions = program.getCompilerOptions(); + var name = entryId.name; + var contextToken = ts.findPrecedingToken(position, sourceFile); + if (ts.isInString(sourceFile, position, contextToken)) { + return Completions.StringCompletions.getStringLiteralCompletionDetails(name, sourceFile, position, contextToken, typeChecker, compilerOptions, host, cancellationToken); + } + // Compute all the completion symbols again. + var symbolCompletion = getSymbolCompletionFromEntryId(program, log, sourceFile, position, entryId); + switch (symbolCompletion.type) { + case "request": { + var request = symbolCompletion.request; + switch (request.kind) { + case 1 /* JsDocTagName */: + return ts.JsDoc.getJSDocTagNameCompletionDetails(name); + case 2 /* JsDocTag */: + return ts.JsDoc.getJSDocTagCompletionDetails(name); + case 3 /* JsDocParameterName */: + return ts.JsDoc.getJSDocParameterNameCompletionDetails(name); + default: + return ts.Debug.assertNever(request); + } + } + case "symbol": { + var symbol = symbolCompletion.symbol, location = symbolCompletion.location, symbolToOriginInfoMap = symbolCompletion.symbolToOriginInfoMap, previousToken = symbolCompletion.previousToken; + var _a = getCompletionEntryCodeActionsAndSourceDisplay(symbolToOriginInfoMap, symbol, program, typeChecker, host, compilerOptions, sourceFile, position, previousToken, formatContext, preferences), codeActions = _a.codeActions, sourceDisplay = _a.sourceDisplay; + return createCompletionDetailsForSymbol(symbol, typeChecker, sourceFile, location, cancellationToken, codeActions, sourceDisplay); // TODO: GH#18217 + } + case "literal": { + var literal = symbolCompletion.literal; + return createSimpleDetails(completionNameForLiteral(literal), "string" /* string */, typeof literal === "string" ? ts.SymbolDisplayPartKind.stringLiteral : ts.SymbolDisplayPartKind.numericLiteral); + } + case "none": + // Didn't find a symbol with this name. See if we can find a keyword instead. + return allKeywordsCompletions().some(function (c) { return c.name === name; }) ? createSimpleDetails(name, "keyword" /* keyword */, ts.SymbolDisplayPartKind.keyword) : undefined; + default: + ts.Debug.assertNever(symbolCompletion); + } + } + Completions.getCompletionEntryDetails = getCompletionEntryDetails; + function createSimpleDetails(name, kind, kind2) { + return createCompletionDetails(name, "" /* none */, kind, [ts.displayPart(name, kind2)]); + } + function createCompletionDetailsForSymbol(symbol, checker, sourceFile, location, cancellationToken, codeActions, sourceDisplay) { + var _a = checker.runWithCancellationToken(cancellationToken, function (checker) { + return ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, sourceFile, location, location, 7 /* All */); + }), displayParts = _a.displayParts, documentation = _a.documentation, symbolKind = _a.symbolKind, tags = _a.tags; + return createCompletionDetails(symbol.name, ts.SymbolDisplay.getSymbolModifiers(symbol), symbolKind, displayParts, documentation, tags, codeActions, sourceDisplay); + } + Completions.createCompletionDetailsForSymbol = createCompletionDetailsForSymbol; + function createCompletionDetails(name, kindModifiers, kind, displayParts, documentation, tags, codeActions, source) { + return { name: name, kindModifiers: kindModifiers, kind: kind, displayParts: displayParts, documentation: documentation, tags: tags, codeActions: codeActions, source: source }; + } + Completions.createCompletionDetails = createCompletionDetails; + function getCompletionEntryCodeActionsAndSourceDisplay(symbolToOriginInfoMap, symbol, program, checker, host, compilerOptions, sourceFile, position, previousToken, formatContext, preferences) { + var symbolOriginInfo = symbolToOriginInfoMap[ts.getSymbolId(symbol)]; + if (!symbolOriginInfo || !originIsExport(symbolOriginInfo)) { + return { codeActions: undefined, sourceDisplay: undefined }; + } + var moduleSymbol = symbolOriginInfo.moduleSymbol; + var exportedSymbol = checker.getMergedSymbol(ts.skipAlias(symbol.exportSymbol || symbol, checker)); + var _a = ts.codefix.getImportCompletionAction(exportedSymbol, moduleSymbol, sourceFile, getSymbolName(symbol, symbolOriginInfo, compilerOptions.target), host, program, formatContext, previousToken && ts.isIdentifier(previousToken) ? previousToken.getStart(sourceFile) : position, preferences), moduleSpecifier = _a.moduleSpecifier, codeAction = _a.codeAction; + return { sourceDisplay: [ts.textPart(moduleSpecifier)], codeActions: [codeAction] }; + } + function getCompletionEntrySymbol(program, log, sourceFile, position, entryId) { + var completion = getSymbolCompletionFromEntryId(program, log, sourceFile, position, entryId); + return completion.type === "symbol" ? completion.symbol : undefined; + } + Completions.getCompletionEntrySymbol = getCompletionEntrySymbol; + var CompletionDataKind; + (function (CompletionDataKind) { + CompletionDataKind[CompletionDataKind["Data"] = 0] = "Data"; + CompletionDataKind[CompletionDataKind["JsDocTagName"] = 1] = "JsDocTagName"; + CompletionDataKind[CompletionDataKind["JsDocTag"] = 2] = "JsDocTag"; + CompletionDataKind[CompletionDataKind["JsDocParameterName"] = 3] = "JsDocParameterName"; + })(CompletionDataKind || (CompletionDataKind = {})); + var CompletionKind; + (function (CompletionKind) { + CompletionKind[CompletionKind["ObjectPropertyDeclaration"] = 0] = "ObjectPropertyDeclaration"; + CompletionKind[CompletionKind["Global"] = 1] = "Global"; + CompletionKind[CompletionKind["PropertyAccess"] = 2] = "PropertyAccess"; + CompletionKind[CompletionKind["MemberLike"] = 3] = "MemberLike"; + CompletionKind[CompletionKind["String"] = 4] = "String"; + CompletionKind[CompletionKind["None"] = 5] = "None"; + })(CompletionKind = Completions.CompletionKind || (Completions.CompletionKind = {})); + function getRecommendedCompletion(previousToken, contextualType, checker) { + // For a union, return the first one with a recommended completion. + return ts.firstDefined(contextualType && (contextualType.isUnion() ? contextualType.types : [contextualType]), function (type) { + var symbol = type && type.symbol; + // Don't include make a recommended completion for an abstract class + return symbol && (symbol.flags & (8 /* EnumMember */ | 384 /* Enum */ | 32 /* Class */) && !ts.isAbstractConstructorSymbol(symbol)) + ? getFirstSymbolInChain(symbol, previousToken, checker) + : undefined; + }); + } + function getContextualType(previousToken, position, sourceFile, checker) { + var parent = previousToken.parent; + switch (previousToken.kind) { + case 72 /* Identifier */: + return ts.getContextualTypeFromParent(previousToken, checker); + case 59 /* EqualsToken */: + switch (parent.kind) { + case 237 /* VariableDeclaration */: + return checker.getContextualType(parent.initializer); // TODO: GH#18217 + case 204 /* BinaryExpression */: + return checker.getTypeAtLocation(parent.left); + case 267 /* JsxAttribute */: + return checker.getContextualTypeForJsxAttribute(parent); + default: + return undefined; + } + case 95 /* NewKeyword */: + return checker.getContextualType(parent); + case 74 /* CaseKeyword */: + return ts.getSwitchedType(ts.cast(parent, ts.isCaseClause), checker); + case 18 /* OpenBraceToken */: + return ts.isJsxExpression(parent) && parent.parent.kind !== 260 /* JsxElement */ ? checker.getContextualTypeForJsxAttribute(parent.parent) : undefined; + default: + var argInfo = ts.SignatureHelp.getArgumentInfoForCompletions(previousToken, position, sourceFile); + return argInfo + // At `,`, treat this as the next argument after the comma. + ? checker.getContextualTypeForArgumentAtIndex(argInfo.invocation, argInfo.argumentIndex + (previousToken.kind === 27 /* CommaToken */ ? 1 : 0)) + : ts.isEqualityOperatorKind(previousToken.kind) && ts.isBinaryExpression(parent) && ts.isEqualityOperatorKind(parent.operatorToken.kind) + // completion at `x ===/**/` should be for the right side + ? checker.getTypeAtLocation(parent.left) + : checker.getContextualType(previousToken); + } + } + function getFirstSymbolInChain(symbol, enclosingDeclaration, checker) { + var chain = checker.getAccessibleSymbolChain(symbol, enclosingDeclaration, /*meaning*/ 67108863 /* All */, /*useOnlyExternalAliasing*/ false); + if (chain) + return ts.first(chain); + return symbol.parent && (isModuleSymbol(symbol.parent) ? symbol : getFirstSymbolInChain(symbol.parent, enclosingDeclaration, checker)); + } + function isModuleSymbol(symbol) { + return symbol.declarations.some(function (d) { return d.kind === 279 /* SourceFile */; }); + } + function getCompletionData(program, log, sourceFile, isUncheckedFile, position, preferences, detailsEntryId) { + var typeChecker = program.getTypeChecker(); + var start = ts.timestamp(); + var currentToken = ts.getTokenAtPosition(sourceFile, position); // TODO: GH#15853 + // We will check for jsdoc comments with insideComment and getJsDocTagAtPosition. (TODO: that seems rather inefficient to check the same thing so many times.) + log("getCompletionData: Get current token: " + (ts.timestamp() - start)); + start = ts.timestamp(); + var insideComment = ts.isInComment(sourceFile, position, currentToken); + log("getCompletionData: Is inside comment: " + (ts.timestamp() - start)); + var insideJsDocTagTypeExpression = false; + var isInSnippetScope = false; + if (insideComment) { + if (ts.hasDocComment(sourceFile, position)) { + if (sourceFile.text.charCodeAt(position - 1) === 64 /* at */) { + // The current position is next to the '@' sign, when no tag name being provided yet. + // Provide a full list of tag names + return { kind: 1 /* JsDocTagName */ }; + } + else { + // When completion is requested without "@", we will have check to make sure that + // there are no comments prefix the request position. We will only allow "*" and space. + // e.g + // /** |c| /* + // + // /** + // |c| + // */ + // + // /** + // * |c| + // */ + // + // /** + // * |c| + // */ + var lineStart = ts.getLineStartPositionForPosition(position, sourceFile); + if (!(sourceFile.text.substring(lineStart, position).match(/[^\*|\s|(/\*\*)]/))) { + return { kind: 2 /* JsDocTag */ }; + } + } + } + // Completion should work inside certain JsDoc tags. For example: + // /** @type {number | string} */ + // Completion should work in the brackets + var tag = getJsDocTagAtPosition(currentToken, position); + if (tag) { + if (tag.tagName.pos <= position && position <= tag.tagName.end) { + return { kind: 1 /* JsDocTagName */ }; + } + if (isTagWithTypeExpression(tag) && tag.typeExpression && tag.typeExpression.kind === 283 /* JSDocTypeExpression */) { + currentToken = ts.getTokenAtPosition(sourceFile, position); + if (!currentToken || + (!ts.isDeclarationName(currentToken) && + (currentToken.parent.kind !== 305 /* JSDocPropertyTag */ || + currentToken.parent.name !== currentToken))) { + // Use as type location if inside tag's type expression + insideJsDocTagTypeExpression = isCurrentlyEditingNode(tag.typeExpression); + } + } + if (ts.isJSDocParameterTag(tag) && (ts.nodeIsMissing(tag.name) || tag.name.pos <= position && position <= tag.name.end)) { + return { kind: 3 /* JsDocParameterName */, tag: tag }; + } + } + if (!insideJsDocTagTypeExpression) { + // Proceed if the current position is in jsDoc tag expression; otherwise it is a normal + // comment or the plain text part of a jsDoc comment, so no completion should be available + log("Returning an empty list because completion was inside a regular comment or plain text part of a JsDoc comment."); + return undefined; + } + } + start = ts.timestamp(); + var previousToken = ts.findPrecedingToken(position, sourceFile, /*startNode*/ undefined); // TODO: GH#18217 + log("getCompletionData: Get previous token 1: " + (ts.timestamp() - start)); + // The decision to provide completion depends on the contextToken, which is determined through the previousToken. + // Note: 'previousToken' (and thus 'contextToken') can be undefined if we are the beginning of the file + var contextToken = previousToken; + // Check if the caret is at the end of an identifier; this is a partial identifier that we want to complete: e.g. a.toS| + // Skip this partial identifier and adjust the contextToken to the token that precedes it. + if (contextToken && position <= contextToken.end && (ts.isIdentifier(contextToken) || ts.isKeyword(contextToken.kind))) { + var start_1 = ts.timestamp(); + contextToken = ts.findPrecedingToken(contextToken.getFullStart(), sourceFile, /*startNode*/ undefined); // TODO: GH#18217 + log("getCompletionData: Get previous token 2: " + (ts.timestamp() - start_1)); + } + // Find the node where completion is requested on. + // Also determine whether we are trying to complete with members of that node + // or attributes of a JSX tag. + var node = currentToken; + var propertyAccessToConvert; + var isRightOfDot = false; + var isRightOfOpenTag = false; + var isStartingCloseTag = false; + var isJsxInitializer = false; + var location = ts.getTouchingPropertyName(sourceFile, position); + if (contextToken) { + // Bail out if this is a known invalid completion location + if (isCompletionListBlocker(contextToken)) { + log("Returning an empty list because completion was requested in an invalid position."); + return undefined; + } + var parent = contextToken.parent; + if (contextToken.kind === 24 /* DotToken */) { + isRightOfDot = true; + switch (parent.kind) { + case 189 /* PropertyAccessExpression */: + propertyAccessToConvert = parent; + node = propertyAccessToConvert.expression; + break; + case 148 /* QualifiedName */: + node = parent.left; + break; + case 244 /* ModuleDeclaration */: + node = parent.name; + break; + case 183 /* ImportType */: + case 214 /* MetaProperty */: + node = parent; + break; + default: + // There is nothing that precedes the dot, so this likely just a stray character + // or leading into a '...' token. Just bail out instead. + return undefined; + } + } + else if (sourceFile.languageVariant === 1 /* JSX */) { + // + // If the tagname is a property access expression, we will then walk up to the top most of property access expression. + // Then, try to get a JSX container and its associated attributes type. + if (parent && parent.kind === 189 /* PropertyAccessExpression */) { + contextToken = parent; + parent = parent.parent; + } + // Fix location + if (currentToken.parent === location) { + switch (currentToken.kind) { + case 30 /* GreaterThanToken */: + if (currentToken.parent.kind === 260 /* JsxElement */ || currentToken.parent.kind === 262 /* JsxOpeningElement */) { + location = currentToken; + } + break; + case 42 /* SlashToken */: + if (currentToken.parent.kind === 261 /* JsxSelfClosingElement */) { + location = currentToken; + } + break; + } + } + switch (parent.kind) { + case 263 /* JsxClosingElement */: + if (contextToken.kind === 42 /* SlashToken */) { + isStartingCloseTag = true; + location = contextToken; + } + break; + case 204 /* BinaryExpression */: + if (!binaryExpressionMayBeOpenTag(parent)) { + break; + } + // falls through + case 261 /* JsxSelfClosingElement */: + case 260 /* JsxElement */: + case 262 /* JsxOpeningElement */: + if (contextToken.kind === 28 /* LessThanToken */) { + isRightOfOpenTag = true; + location = contextToken; + } + break; + case 267 /* JsxAttribute */: + switch (previousToken.kind) { + case 59 /* EqualsToken */: + isJsxInitializer = true; + break; + case 72 /* Identifier */: + // For `
      ` we don't want to treat this as a jsx inializer, instead it's the attribute name. + if (parent !== previousToken.parent && + !parent.initializer && + ts.findChildOfKind(parent, 59 /* EqualsToken */, sourceFile)) { + isJsxInitializer = previousToken; + } + } + break; + } + } + } + var semanticStart = ts.timestamp(); + var completionKind = 5 /* None */; + var isNewIdentifierLocation = false; + var keywordFilters = 0 /* None */; + var symbols = []; + var symbolToOriginInfoMap = []; + if (isRightOfDot) { + getTypeScriptMemberSymbols(); + } + else if (isRightOfOpenTag) { + var tagSymbols = ts.Debug.assertEachDefined(typeChecker.getJsxIntrinsicTagNamesAt(location), "getJsxIntrinsicTagNames() should all be defined"); + tryGetGlobalSymbols(); + symbols = tagSymbols.concat(symbols); + completionKind = 3 /* MemberLike */; + keywordFilters = 0 /* None */; + } + else if (isStartingCloseTag) { + var tagName = contextToken.parent.parent.openingElement.tagName; + var tagSymbol = typeChecker.getSymbolAtLocation(tagName); + if (tagSymbol) { + symbols = [tagSymbol]; + } + completionKind = 3 /* MemberLike */; + keywordFilters = 0 /* None */; + } + else { + // For JavaScript or TypeScript, if we're not after a dot, then just try to get the + // global symbols in scope. These results should be valid for either language as + // the set of symbols that can be referenced from this location. + if (!tryGetGlobalSymbols()) { + return undefined; + } + } + log("getCompletionData: Semantic work: " + (ts.timestamp() - semanticStart)); + var contextualType = previousToken && getContextualType(previousToken, position, sourceFile, typeChecker); + var literals = ts.mapDefined(contextualType && (contextualType.isUnion() ? contextualType.types : [contextualType]), function (t) { return t.isLiteral() ? t.value : undefined; }); + var recommendedCompletion = previousToken && contextualType && getRecommendedCompletion(previousToken, contextualType, typeChecker); + return { kind: 0 /* Data */, symbols: symbols, completionKind: completionKind, isInSnippetScope: isInSnippetScope, propertyAccessToConvert: propertyAccessToConvert, isNewIdentifierLocation: isNewIdentifierLocation, location: location, keywordFilters: keywordFilters, literals: literals, symbolToOriginInfoMap: symbolToOriginInfoMap, recommendedCompletion: recommendedCompletion, previousToken: previousToken, isJsxInitializer: isJsxInitializer }; + function isTagWithTypeExpression(tag) { + switch (tag.kind) { + case 299 /* JSDocParameterTag */: + case 305 /* JSDocPropertyTag */: + case 300 /* JSDocReturnTag */: + case 302 /* JSDocTypeTag */: + case 304 /* JSDocTypedefTag */: + return true; + default: + return false; + } + } + function getTypeScriptMemberSymbols() { + // Right of dot member completion list + completionKind = 2 /* PropertyAccess */; + // Since this is qualified name check its a type node location + var isImportType = ts.isLiteralImportTypeNode(node); + var isTypeLocation = insideJsDocTagTypeExpression || (isImportType && !node.isTypeOf) || ts.isPartOfTypeNode(node.parent); + var isRhsOfImportDeclaration = ts.isInRightSideOfInternalImportEqualsDeclaration(node); + var allowTypeOrValue = isRhsOfImportDeclaration || (!isTypeLocation && ts.isPossiblyTypeArgumentPosition(contextToken, sourceFile, typeChecker)); + if (ts.isEntityName(node) || isImportType) { + var isNamespaceName = ts.isModuleDeclaration(node.parent); + if (isNamespaceName) + isNewIdentifierLocation = true; + var symbol = typeChecker.getSymbolAtLocation(node); + if (symbol) { + symbol = ts.skipAlias(symbol, typeChecker); + if (symbol.flags & (1536 /* Module */ | 384 /* Enum */)) { + // Extract module or enum members + var exportedSymbols = ts.Debug.assertEachDefined(typeChecker.getExportsOfModule(symbol), "getExportsOfModule() should all be defined"); + var isValidValueAccess_1 = function (symbol) { return typeChecker.isValidPropertyAccess(isImportType ? node : (node.parent), symbol.name); }; + var isValidTypeAccess_1 = function (symbol) { return symbolCanBeReferencedAtTypeLocation(symbol); }; + var isValidAccess = isNamespaceName + // At `namespace N.M/**/`, if this is the only declaration of `M`, don't include `M` as a completion. + ? function (symbol) { return !!(symbol.flags & 1920 /* Namespace */) && !symbol.declarations.every(function (d) { return d.parent === node.parent; }); } + : allowTypeOrValue ? + // Any kind is allowed when dotting off namespace in internal import equals declaration + function (symbol) { return isValidTypeAccess_1(symbol) || isValidValueAccess_1(symbol); } : + isTypeLocation ? isValidTypeAccess_1 : isValidValueAccess_1; + for (var _i = 0, exportedSymbols_1 = exportedSymbols; _i < exportedSymbols_1.length; _i++) { + var exportedSymbol = exportedSymbols_1[_i]; + if (isValidAccess(exportedSymbol)) { + symbols.push(exportedSymbol); + } + } + // If the module is merged with a value, we must get the type of the class and add its propertes (for inherited static methods). + if (!isTypeLocation && symbol.declarations.some(function (d) { return d.kind !== 279 /* SourceFile */ && d.kind !== 244 /* ModuleDeclaration */ && d.kind !== 243 /* EnumDeclaration */; })) { + addTypeProperties(typeChecker.getTypeOfSymbolAtLocation(symbol, node)); + } + return; + } + } + } + if (ts.isMetaProperty(node) && (node.keywordToken === 95 /* NewKeyword */ || node.keywordToken === 92 /* ImportKeyword */)) { + var completion = (node.keywordToken === 95 /* NewKeyword */) ? "target" : "meta"; + symbols.push(typeChecker.createSymbol(4 /* Property */, ts.escapeLeadingUnderscores(completion))); + return; + } + if (!isTypeLocation) { + addTypeProperties(typeChecker.getTypeAtLocation(node)); + } + } + function addTypeProperties(type) { + isNewIdentifierLocation = !!type.getStringIndexType(); + if (isUncheckedFile) { + // In javascript files, for union types, we don't just get the members that + // the individual types have in common, we also include all the members that + // each individual type has. This is because we're going to add all identifiers + // anyways. So we might as well elevate the members that were at least part + // of the individual types to a higher status since we know what they are. + symbols.push.apply(symbols, getPropertiesForCompletion(type, typeChecker)); + } + else { + for (var _i = 0, _a = type.getApparentProperties(); _i < _a.length; _i++) { + var symbol = _a[_i]; + if (typeChecker.isValidPropertyAccessForCompletions(node.kind === 183 /* ImportType */ ? node : node.parent, type, symbol)) { + addPropertySymbol(symbol); + } + } + } + } + function addPropertySymbol(symbol) { + // For a computed property with an accessible name like `Symbol.iterator`, + // we'll add a completion for the *name* `Symbol` instead of for the property. + // If this is e.g. [Symbol.iterator], add a completion for `Symbol`. + var computedPropertyName = ts.firstDefined(symbol.declarations, function (decl) { return ts.tryCast(ts.getNameOfDeclaration(decl), ts.isComputedPropertyName); }); + if (computedPropertyName) { + var leftMostName = getLeftMostName(computedPropertyName.expression); // The completion is for `Symbol`, not `iterator`. + var nameSymbol = leftMostName && typeChecker.getSymbolAtLocation(leftMostName); + // If this is nested like for `namespace N { export const sym = Symbol(); }`, we'll add the completion for `N`. + var firstAccessibleSymbol = nameSymbol && getFirstSymbolInChain(nameSymbol, contextToken, typeChecker); + if (firstAccessibleSymbol && !symbolToOriginInfoMap[ts.getSymbolId(firstAccessibleSymbol)]) { + symbols.push(firstAccessibleSymbol); + var moduleSymbol = firstAccessibleSymbol.parent; + symbolToOriginInfoMap[ts.getSymbolId(firstAccessibleSymbol)] = + !moduleSymbol || !ts.isExternalModuleSymbol(moduleSymbol) ? { kind: 1 /* SymbolMemberNoExport */ } : { kind: 2 /* SymbolMemberExport */, moduleSymbol: moduleSymbol, isDefaultExport: false }; + } + } + else { + symbols.push(symbol); + } + } + /** Given 'a.b.c', returns 'a'. */ + function getLeftMostName(e) { + return ts.isIdentifier(e) ? e : ts.isPropertyAccessExpression(e) ? getLeftMostName(e.expression) : undefined; + } + function tryGetGlobalSymbols() { + var result = tryGetObjectLikeCompletionSymbols() + || tryGetImportOrExportClauseCompletionSymbols() + || tryGetConstructorCompletion() + || tryGetClassLikeCompletionSymbols() + || tryGetJsxCompletionSymbols() + || (getGlobalCompletions(), 1 /* Success */); + return result === 1 /* Success */; + } + function tryGetConstructorCompletion() { + if (!tryGetConstructorLikeCompletionContainer(contextToken)) + return 0 /* Continue */; + // no members, only keywords + completionKind = 5 /* None */; + // Declaring new property/method/accessor + isNewIdentifierLocation = true; + // Has keywords for constructor parameter + keywordFilters = 4 /* ConstructorParameterKeywords */; + return 1 /* Success */; + } + function tryGetJsxCompletionSymbols() { + var jsxContainer = tryGetContainingJsxElement(contextToken); + // Cursor is inside a JSX self-closing element or opening element + var attrsType = jsxContainer && typeChecker.getContextualType(jsxContainer.attributes); + if (!attrsType) + return 0 /* Continue */; + symbols = filterJsxAttributes(getPropertiesForObjectExpression(attrsType, jsxContainer.attributes, typeChecker), jsxContainer.attributes.properties); + completionKind = 3 /* MemberLike */; + isNewIdentifierLocation = false; + return 1 /* Success */; + } + function getGlobalCompletions() { + keywordFilters = tryGetFunctionLikeBodyCompletionContainer(contextToken) ? 5 /* FunctionLikeBodyKeywords */ : 1 /* All */; + // Get all entities in the current scope. + completionKind = 1 /* Global */; + isNewIdentifierLocation = isNewIdentifierDefinitionLocation(contextToken); + if (previousToken !== contextToken) { + ts.Debug.assert(!!previousToken, "Expected 'contextToken' to be defined when different from 'previousToken'."); + } + // We need to find the node that will give us an appropriate scope to begin + // aggregating completion candidates. This is achieved in 'getScopeNode' + // by finding the first node that encompasses a position, accounting for whether a node + // is "complete" to decide whether a position belongs to the node. + // + // However, at the end of an identifier, we are interested in the scope of the identifier + // itself, but fall outside of the identifier. For instance: + // + // xyz => x$ + // + // the cursor is outside of both the 'x' and the arrow function 'xyz => x', + // so 'xyz' is not returned in our results. + // + // We define 'adjustedPosition' so that we may appropriately account for + // being at the end of an identifier. The intention is that if requesting completion + // at the end of an identifier, it should be effectively equivalent to requesting completion + // anywhere inside/at the beginning of the identifier. So in the previous case, the + // 'adjustedPosition' will work as if requesting completion in the following: + // + // xyz => $x + // + // If previousToken !== contextToken, then + // - 'contextToken' was adjusted to the token prior to 'previousToken' + // because we were at the end of an identifier. + // - 'previousToken' is defined. + var adjustedPosition = previousToken !== contextToken ? + previousToken.getStart() : + position; + var scopeNode = getScopeNode(contextToken, adjustedPosition, sourceFile) || sourceFile; + isInSnippetScope = isSnippetScope(scopeNode); + var isTypeOnly = isTypeOnlyCompletion(); + var symbolMeanings = (isTypeOnly ? 0 /* None */ : 67220415 /* Value */) | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */; + symbols = ts.Debug.assertEachDefined(typeChecker.getSymbolsInScope(scopeNode, symbolMeanings), "getSymbolsInScope() should all be defined"); + // Need to insert 'this.' before properties of `this` type, so only do that if `includeInsertTextCompletions` + if (preferences.includeCompletionsWithInsertText && scopeNode.kind !== 279 /* SourceFile */) { + var thisType = typeChecker.tryGetThisTypeAt(scopeNode); + if (thisType) { + for (var _i = 0, _a = getPropertiesForCompletion(thisType, typeChecker); _i < _a.length; _i++) { + var symbol = _a[_i]; + symbolToOriginInfoMap[ts.getSymbolId(symbol)] = { kind: 0 /* ThisType */ }; + symbols.push(symbol); + } + } + } + if (shouldOfferImportCompletions()) { + getSymbolsFromOtherSourceFileExports(symbols, previousToken && ts.isIdentifier(previousToken) ? previousToken.text : "", program.getCompilerOptions().target); + } + filterGlobalCompletion(symbols); + } + function shouldOfferImportCompletions() { + // If not already a module, must have modules enabled and not currently be in a commonjs module. (TODO: import completions for commonjs) + if (!preferences.includeCompletionsForModuleExports) + return false; + // If already using ES6 modules, OK to continue using them. + if (sourceFile.externalModuleIndicator) + return true; + // If already using commonjs, don't introduce ES6. + if (sourceFile.commonJsModuleIndicator) + return false; + // If module transpilation is enabled or we're targeting es6 or above, or not emitting, OK. + if (ts.compilerOptionsIndicateEs6Modules(program.getCompilerOptions())) + return true; + // If some file is using ES6 modules, assume that it's OK to add more. + return ts.programContainsEs6Modules(program); + } + function isSnippetScope(scopeNode) { + switch (scopeNode.kind) { + case 279 /* SourceFile */: + case 206 /* TemplateExpression */: + case 270 /* JsxExpression */: + case 218 /* Block */: + return true; + default: + return ts.isStatement(scopeNode); + } + } + function filterGlobalCompletion(symbols) { + var isTypeOnly = isTypeOnlyCompletion(); + var allowTypes = isTypeOnly || !isContextTokenValueLocation(contextToken) && ts.isPossiblyTypeArgumentPosition(contextToken, sourceFile, typeChecker); + if (isTypeOnly) + keywordFilters = 6 /* TypeKeywords */; + ts.filterMutate(symbols, function (symbol) { + if (!ts.isSourceFile(location)) { + // export = /**/ here we want to get all meanings, so any symbol is ok + if (ts.isExportAssignment(location.parent)) { + return true; + } + symbol = ts.skipAlias(symbol, typeChecker); + // import m = /**/ <-- It can only access namespace (if typing import = x. this would get member symbols and not namespace) + if (ts.isInRightSideOfInternalImportEqualsDeclaration(location)) { + return !!(symbol.flags & 1920 /* Namespace */); + } + if (allowTypes) { + // Its a type, but you can reach it by namespace.type as well + var symbolAllowedAsType = symbolCanBeReferencedAtTypeLocation(symbol); + if (symbolAllowedAsType || isTypeOnly) { + return symbolAllowedAsType; + } + } + } + // expressions are value space (which includes the value namespaces) + return !!(ts.getCombinedLocalAndExportSymbolFlags(symbol) & 67220415 /* Value */); + }); + } + function isTypeOnlyCompletion() { + return insideJsDocTagTypeExpression || !isContextTokenValueLocation(contextToken) && (ts.isPartOfTypeNode(location) || isContextTokenTypeLocation(contextToken)); + } + function isContextTokenValueLocation(contextToken) { + return contextToken && + contextToken.kind === 104 /* TypeOfKeyword */ && + (contextToken.parent.kind === 167 /* TypeQuery */ || ts.isTypeOfExpression(contextToken.parent)); + } + function isContextTokenTypeLocation(contextToken) { + if (contextToken) { + var parentKind = contextToken.parent.kind; + switch (contextToken.kind) { + case 57 /* ColonToken */: + return parentKind === 154 /* PropertyDeclaration */ || + parentKind === 153 /* PropertySignature */ || + parentKind === 151 /* Parameter */ || + parentKind === 237 /* VariableDeclaration */ || + ts.isFunctionLikeKind(parentKind); + case 59 /* EqualsToken */: + return parentKind === 242 /* TypeAliasDeclaration */; + case 119 /* AsKeyword */: + return parentKind === 212 /* AsExpression */; + } + } + return false; + } + /** True if symbol is a type or a module containing at least one type. */ + function symbolCanBeReferencedAtTypeLocation(symbol, seenModules) { + if (seenModules === void 0) { seenModules = ts.createMap(); } + var sym = ts.skipAlias(symbol.exportSymbol || symbol, typeChecker); + return !!(sym.flags & 67897832 /* Type */) || + !!(sym.flags & 1536 /* Module */) && + ts.addToSeen(seenModules, ts.getSymbolId(sym)) && + typeChecker.getExportsOfModule(sym).some(function (e) { return symbolCanBeReferencedAtTypeLocation(e, seenModules); }); + } + function getSymbolsFromOtherSourceFileExports(symbols, tokenText, target) { + var tokenTextLowerCase = tokenText.toLowerCase(); + var seenResolvedModules = ts.createMap(); + ts.codefix.forEachExternalModuleToImportFrom(typeChecker, sourceFile, program.getSourceFiles(), function (moduleSymbol) { + // Perf -- ignore other modules if this is a request for details + if (detailsEntryId && detailsEntryId.source && ts.stripQuotes(moduleSymbol.name) !== detailsEntryId.source) { + return; + } + var resolvedModuleSymbol = typeChecker.resolveExternalModuleSymbol(moduleSymbol); + // resolvedModuleSymbol may be a namespace. A namespace may be `export =` by multiple module declarations, but only keep the first one. + if (!ts.addToSeen(seenResolvedModules, ts.getSymbolId(resolvedModuleSymbol))) { + return; + } + if (resolvedModuleSymbol !== moduleSymbol && + // Don't add another completion for `export =` of a symbol that's already global. + // So in `declare namespace foo {} declare module "foo" { export = foo; }`, there will just be the global completion for `foo`. + ts.some(resolvedModuleSymbol.declarations, function (d) { return !!d.getSourceFile().externalModuleIndicator; })) { + symbols.push(resolvedModuleSymbol); + symbolToOriginInfoMap[ts.getSymbolId(resolvedModuleSymbol)] = { kind: 3 /* Export */, moduleSymbol: moduleSymbol, isDefaultExport: false }; + } + for (var _i = 0, _a = typeChecker.getExportsOfModule(moduleSymbol); _i < _a.length; _i++) { + var symbol = _a[_i]; + // Don't add a completion for a re-export, only for the original. + // The actual import fix might end up coming from a re-export -- we don't compute that until getting completion details. + // This is just to avoid adding duplicate completion entries. + // + // If `symbol.parent !== ...`, this is an `export * from "foo"` re-export. Those don't create new symbols. + if (typeChecker.getMergedSymbol(symbol.parent) !== resolvedModuleSymbol + || ts.some(symbol.declarations, function (d) { + // If `!!d.name.originalKeywordKind`, this is `export { _break as break };` -- skip this and prefer the keyword completion. + // If `!!d.parent.parent.moduleSpecifier`, this is `export { foo } from "foo"` re-export, which creates a new symbol (thus isn't caught by the first check). + return ts.isExportSpecifier(d) && (d.propertyName ? ts.isIdentifierANonContextualKeyword(d.name) : !!d.parent.parent.moduleSpecifier); + })) { + continue; + } + var isDefaultExport = symbol.escapedName === "default" /* Default */; + if (isDefaultExport) { + symbol = ts.getLocalSymbolForExportDefault(symbol) || symbol; + } + var origin = { kind: 3 /* Export */, moduleSymbol: moduleSymbol, isDefaultExport: isDefaultExport }; + if (detailsEntryId || stringContainsCharactersInOrder(getSymbolName(symbol, origin, target).toLowerCase(), tokenTextLowerCase)) { + symbols.push(symbol); + symbolToOriginInfoMap[ts.getSymbolId(symbol)] = origin; + } + } + }); + } + /** + * True if you could remove some characters in `a` to get `b`. + * E.g., true for "abcdef" and "bdf". + * But not true for "abcdef" and "dbf". + */ + function stringContainsCharactersInOrder(str, characters) { + if (characters.length === 0) { + return true; + } + var characterIndex = 0; + for (var strIndex = 0; strIndex < str.length; strIndex++) { + if (str.charCodeAt(strIndex) === characters.charCodeAt(characterIndex)) { + characterIndex++; + if (characterIndex === characters.length) { + return true; + } + } + } + // Did not find all characters + return false; + } + /** + * Finds the first node that "embraces" the position, so that one may + * accurately aggregate locals from the closest containing scope. + */ + function getScopeNode(initialToken, position, sourceFile) { + var scope = initialToken; + while (scope && !ts.positionBelongsToNode(scope, position, sourceFile)) { + scope = scope.parent; + } + return scope; + } + function isCompletionListBlocker(contextToken) { + var start = ts.timestamp(); + var result = isInStringOrRegularExpressionOrTemplateLiteral(contextToken) || + isSolelyIdentifierDefinitionLocation(contextToken) || + isDotOfNumericLiteral(contextToken) || + isInJsxText(contextToken); + log("getCompletionsAtPosition: isCompletionListBlocker: " + (ts.timestamp() - start)); + return result; + } + function isInJsxText(contextToken) { + if (contextToken.kind === 11 /* JsxText */) { + return true; + } + if (contextToken.kind === 30 /* GreaterThanToken */ && contextToken.parent) { + if (contextToken.parent.kind === 262 /* JsxOpeningElement */) { + return true; + } + if (contextToken.parent.kind === 263 /* JsxClosingElement */ || contextToken.parent.kind === 261 /* JsxSelfClosingElement */) { + return !!contextToken.parent.parent && contextToken.parent.parent.kind === 260 /* JsxElement */; + } + } + return false; + } + function isNewIdentifierDefinitionLocation(previousToken) { + if (previousToken) { + var containingNodeKind = previousToken.parent.kind; + // Previous token may have been a keyword that was converted to an identifier. + switch (keywordForNode(previousToken)) { + case 27 /* CommaToken */: + return containingNodeKind === 191 /* CallExpression */ // func( a, | + || containingNodeKind === 157 /* Constructor */ // constructor( a, | /* public, protected, private keywords are allowed here, so show completion */ + || containingNodeKind === 192 /* NewExpression */ // new C(a, | + || containingNodeKind === 187 /* ArrayLiteralExpression */ // [a, | + || containingNodeKind === 204 /* BinaryExpression */ // const x = (a, | + || containingNodeKind === 165 /* FunctionType */; // var x: (s: string, list| + case 20 /* OpenParenToken */: + return containingNodeKind === 191 /* CallExpression */ // func( | + || containingNodeKind === 157 /* Constructor */ // constructor( | + || containingNodeKind === 192 /* NewExpression */ // new C(a| + || containingNodeKind === 195 /* ParenthesizedExpression */ // const x = (a| + || containingNodeKind === 177 /* ParenthesizedType */; // function F(pred: (a| /* this can become an arrow function, where 'a' is the argument */ + case 22 /* OpenBracketToken */: + return containingNodeKind === 187 /* ArrayLiteralExpression */ // [ | + || containingNodeKind === 162 /* IndexSignature */ // [ | : string ] + || containingNodeKind === 149 /* ComputedPropertyName */; // [ | /* this can become an index signature */ + case 130 /* ModuleKeyword */: // module | + case 131 /* NamespaceKeyword */: // namespace | + return true; + case 24 /* DotToken */: + return containingNodeKind === 244 /* ModuleDeclaration */; // module A.| + case 18 /* OpenBraceToken */: + return containingNodeKind === 240 /* ClassDeclaration */; // class A{ | + case 59 /* EqualsToken */: + return containingNodeKind === 237 /* VariableDeclaration */ // const x = a| + || containingNodeKind === 204 /* BinaryExpression */; // x = a| + case 15 /* TemplateHead */: + return containingNodeKind === 206 /* TemplateExpression */; // `aa ${| + case 16 /* TemplateMiddle */: + return containingNodeKind === 216 /* TemplateSpan */; // `aa ${10} dd ${| + case 115 /* PublicKeyword */: + case 113 /* PrivateKeyword */: + case 114 /* ProtectedKeyword */: + return containingNodeKind === 154 /* PropertyDeclaration */; // class A{ public | + } + } + return false; + } + function isInStringOrRegularExpressionOrTemplateLiteral(contextToken) { + // To be "in" one of these literals, the position has to be: + // 1. entirely within the token text. + // 2. at the end position of an unterminated token. + // 3. at the end of a regular expression (due to trailing flags like '/foo/g'). + return (ts.isRegularExpressionLiteral(contextToken) || ts.isStringTextContainingNode(contextToken)) && (ts.rangeContainsPositionExclusive(ts.createTextRangeFromSpan(ts.createTextSpanFromNode(contextToken)), position) || + position === contextToken.end && (!!contextToken.isUnterminated || ts.isRegularExpressionLiteral(contextToken))); + } + /** + * Aggregates relevant symbols for completion in object literals and object binding patterns. + * Relevant symbols are stored in the captured 'symbols' variable. + * + * @returns true if 'symbols' was successfully populated; false otherwise. + */ + function tryGetObjectLikeCompletionSymbols() { + var objectLikeContainer = tryGetObjectLikeCompletionContainer(contextToken); + if (!objectLikeContainer) + return 0 /* Continue */; + // We're looking up possible property names from contextual/inferred/declared type. + completionKind = 0 /* ObjectPropertyDeclaration */; + var typeMembers; + var existingMembers; + if (objectLikeContainer.kind === 188 /* ObjectLiteralExpression */) { + var typeForObject = typeChecker.getContextualType(objectLikeContainer); + if (!typeForObject) + return 2 /* Fail */; + isNewIdentifierLocation = ts.hasIndexSignature(typeForObject); + typeMembers = getPropertiesForObjectExpression(typeForObject, objectLikeContainer, typeChecker); + existingMembers = objectLikeContainer.properties; + } + else { + ts.Debug.assert(objectLikeContainer.kind === 184 /* ObjectBindingPattern */); + // We are *only* completing on properties from the type being destructured. + isNewIdentifierLocation = false; + var rootDeclaration = ts.getRootDeclaration(objectLikeContainer.parent); + if (!ts.isVariableLike(rootDeclaration)) + return ts.Debug.fail("Root declaration is not variable-like."); + // We don't want to complete using the type acquired by the shape + // of the binding pattern; we are only interested in types acquired + // through type declaration or inference. + // Also proceed if rootDeclaration is a parameter and if its containing function expression/arrow function is contextually typed - + // type of parameter will flow in from the contextual type of the function + var canGetType = ts.hasInitializer(rootDeclaration) || ts.hasType(rootDeclaration) || rootDeclaration.parent.parent.kind === 227 /* ForOfStatement */; + if (!canGetType && rootDeclaration.kind === 151 /* Parameter */) { + if (ts.isExpression(rootDeclaration.parent)) { + canGetType = !!typeChecker.getContextualType(rootDeclaration.parent); + } + else if (rootDeclaration.parent.kind === 156 /* MethodDeclaration */ || rootDeclaration.parent.kind === 159 /* SetAccessor */) { + canGetType = ts.isExpression(rootDeclaration.parent.parent) && !!typeChecker.getContextualType(rootDeclaration.parent.parent); + } + } + if (canGetType) { + var typeForObject = typeChecker.getTypeAtLocation(objectLikeContainer); + if (!typeForObject) + return 2 /* Fail */; + // In a binding pattern, get only known properties. Everywhere else we will get all possible properties. + typeMembers = typeChecker.getPropertiesOfType(typeForObject).filter(function (symbol) { return !(ts.getDeclarationModifierFlagsFromSymbol(symbol) & 24 /* NonPublicAccessibilityModifier */); }); + existingMembers = objectLikeContainer.elements; + } + } + if (typeMembers && typeMembers.length > 0) { + // Add filtered items to the completion list + symbols = filterObjectMembersList(typeMembers, ts.Debug.assertDefined(existingMembers)); + } + return 1 /* Success */; + } + /** + * Aggregates relevant symbols for completion in import clauses and export clauses + * whose declarations have a module specifier; for instance, symbols will be aggregated for + * + * import { | } from "moduleName"; + * export { a as foo, | } from "moduleName"; + * + * but not for + * + * export { | }; + * + * Relevant symbols are stored in the captured 'symbols' variable. + * + * @returns true if 'symbols' was successfully populated; false otherwise. + */ + function tryGetImportOrExportClauseCompletionSymbols() { + // `import { |` or `import { a as 0, | }` + var namedImportsOrExports = contextToken && (contextToken.kind === 18 /* OpenBraceToken */ || contextToken.kind === 27 /* CommaToken */) + ? ts.tryCast(contextToken.parent, ts.isNamedImportsOrExports) : undefined; + if (!namedImportsOrExports) + return 0 /* Continue */; + // cursor is in an import clause + // try to show exported member for imported module + var moduleSpecifier = (namedImportsOrExports.kind === 252 /* NamedImports */ ? namedImportsOrExports.parent.parent : namedImportsOrExports.parent).moduleSpecifier; + var moduleSpecifierSymbol = typeChecker.getSymbolAtLocation(moduleSpecifier); // TODO: GH#18217 + if (!moduleSpecifierSymbol) + return 2 /* Fail */; + completionKind = 3 /* MemberLike */; + isNewIdentifierLocation = false; + var exports = typeChecker.getExportsAndPropertiesOfModule(moduleSpecifierSymbol); + var existing = ts.arrayToSet(namedImportsOrExports.elements, function (n) { return isCurrentlyEditingNode(n) ? undefined : (n.propertyName || n.name).escapedText; }); + symbols = exports.filter(function (e) { return e.escapedName !== "default" /* Default */ && !existing.get(e.escapedName); }); + return 1 /* Success */; + } + /** + * Aggregates relevant symbols for completion in class declaration + * Relevant symbols are stored in the captured 'symbols' variable. + */ + function tryGetClassLikeCompletionSymbols() { + var decl = tryGetObjectTypeDeclarationCompletionContainer(sourceFile, contextToken, location); + if (!decl) + return 0 /* Continue */; + // We're looking up possible property names from parent type. + completionKind = 3 /* MemberLike */; + // Declaring new property/method/accessor + isNewIdentifierLocation = true; + keywordFilters = contextToken.kind === 40 /* AsteriskToken */ ? 0 /* None */ : + ts.isClassLike(decl) ? 2 /* ClassElementKeywords */ : 3 /* InterfaceElementKeywords */; + // If you're in an interface you don't want to repeat things from super-interface. So just stop here. + if (!ts.isClassLike(decl)) + return 1 /* Success */; + var classElement = contextToken.parent; + var classElementModifierFlags = ts.isClassElement(classElement) ? ts.getModifierFlags(classElement) : 0 /* None */; + // If this is context token is not something we are editing now, consider if this would lead to be modifier + if (contextToken.kind === 72 /* Identifier */ && !isCurrentlyEditingNode(contextToken)) { + switch (contextToken.getText()) { + case "private": + classElementModifierFlags = classElementModifierFlags | 8 /* Private */; + break; + case "static": + classElementModifierFlags = classElementModifierFlags | 32 /* Static */; + break; + } + } + // No member list for private methods + if (!(classElementModifierFlags & 8 /* Private */)) { + // List of property symbols of base type that are not private and already implemented + var baseSymbols = ts.flatMap(ts.getAllSuperTypeNodes(decl), function (baseTypeNode) { + var type = typeChecker.getTypeAtLocation(baseTypeNode); + return type && typeChecker.getPropertiesOfType(classElementModifierFlags & 32 /* Static */ ? typeChecker.getTypeOfSymbolAtLocation(type.symbol, decl) : type); + }); + symbols = filterClassMembersList(baseSymbols, decl.members, classElementModifierFlags); + } + return 1 /* Success */; + } + /** + * Returns the immediate owning object literal or binding pattern of a context token, + * on the condition that one exists and that the context implies completion should be given. + */ + function tryGetObjectLikeCompletionContainer(contextToken) { + if (contextToken) { + var parent = contextToken.parent; + switch (contextToken.kind) { + case 18 /* OpenBraceToken */: // const x = { | + case 27 /* CommaToken */: // const x = { a: 0, | + if (ts.isObjectLiteralExpression(parent) || ts.isObjectBindingPattern(parent)) { + return parent; + } + break; + case 40 /* AsteriskToken */: + return ts.isMethodDeclaration(parent) ? ts.tryCast(parent.parent, ts.isObjectLiteralExpression) : undefined; + case 72 /* Identifier */: + return contextToken.text === "async" && ts.isShorthandPropertyAssignment(contextToken.parent) + ? contextToken.parent.parent : undefined; + } + } + return undefined; + } + function isConstructorParameterCompletion(node) { + return !!node.parent && ts.isParameter(node.parent) && ts.isConstructorDeclaration(node.parent.parent) + && (ts.isParameterPropertyModifier(node.kind) || ts.isDeclarationName(node)); + } + /** + * Returns the immediate owning class declaration of a context token, + * on the condition that one exists and that the context implies completion should be given. + */ + function tryGetConstructorLikeCompletionContainer(contextToken) { + if (contextToken) { + var parent = contextToken.parent; + switch (contextToken.kind) { + case 20 /* OpenParenToken */: + case 27 /* CommaToken */: + return ts.isConstructorDeclaration(contextToken.parent) ? contextToken.parent : undefined; + default: + if (isConstructorParameterCompletion(contextToken)) { + return parent.parent; + } + } + } + return undefined; + } + function tryGetFunctionLikeBodyCompletionContainer(contextToken) { + if (contextToken) { + var prev_1; + var container = ts.findAncestor(contextToken.parent, function (node) { + if (ts.isClassLike(node)) { + return "quit"; + } + if (ts.isFunctionLikeDeclaration(node) && prev_1 === node.body) { + return true; + } + prev_1 = node; + return false; + }); + return container && container; + } + } + function tryGetContainingJsxElement(contextToken) { + if (contextToken) { + var parent = contextToken.parent; + switch (contextToken.kind) { + case 30 /* GreaterThanToken */: // End of a type argument list + case 29 /* LessThanSlashToken */: + case 42 /* SlashToken */: + case 72 /* Identifier */: + case 189 /* PropertyAccessExpression */: + case 268 /* JsxAttributes */: + case 267 /* JsxAttribute */: + case 269 /* JsxSpreadAttribute */: + if (parent && (parent.kind === 261 /* JsxSelfClosingElement */ || parent.kind === 262 /* JsxOpeningElement */)) { + if (contextToken.kind === 30 /* GreaterThanToken */) { + var precedingToken = ts.findPrecedingToken(contextToken.pos, sourceFile, /*startNode*/ undefined); + if (!parent.typeArguments || (precedingToken && precedingToken.kind === 42 /* SlashToken */)) + break; + } + return parent; + } + else if (parent.kind === 267 /* JsxAttribute */) { + // Currently we parse JsxOpeningLikeElement as: + // JsxOpeningLikeElement + // attributes: JsxAttributes + // properties: NodeArray + return parent.parent.parent; + } + break; + // The context token is the closing } or " of an attribute, which means + // its parent is a JsxExpression, whose parent is a JsxAttribute, + // whose parent is a JsxOpeningLikeElement + case 10 /* StringLiteral */: + if (parent && ((parent.kind === 267 /* JsxAttribute */) || (parent.kind === 269 /* JsxSpreadAttribute */))) { + // Currently we parse JsxOpeningLikeElement as: + // JsxOpeningLikeElement + // attributes: JsxAttributes + // properties: NodeArray + return parent.parent.parent; + } + break; + case 19 /* CloseBraceToken */: + if (parent && + parent.kind === 270 /* JsxExpression */ && + parent.parent && parent.parent.kind === 267 /* JsxAttribute */) { + // Currently we parse JsxOpeningLikeElement as: + // JsxOpeningLikeElement + // attributes: JsxAttributes + // properties: NodeArray + // each JsxAttribute can have initializer as JsxExpression + return parent.parent.parent.parent; + } + if (parent && parent.kind === 269 /* JsxSpreadAttribute */) { + // Currently we parse JsxOpeningLikeElement as: + // JsxOpeningLikeElement + // attributes: JsxAttributes + // properties: NodeArray + return parent.parent.parent; + } + break; + } + } + return undefined; + } + /** + * @returns true if we are certain that the currently edited location must define a new location; false otherwise. + */ + function isSolelyIdentifierDefinitionLocation(contextToken) { + var parent = contextToken.parent; + var containingNodeKind = parent.kind; + switch (contextToken.kind) { + case 27 /* CommaToken */: + return containingNodeKind === 237 /* VariableDeclaration */ || + containingNodeKind === 238 /* VariableDeclarationList */ || + containingNodeKind === 219 /* VariableStatement */ || + containingNodeKind === 243 /* EnumDeclaration */ || // enum a { foo, | + isFunctionLikeButNotConstructor(containingNodeKind) || + containingNodeKind === 241 /* InterfaceDeclaration */ || // interface A= contextToken.pos); + case 24 /* DotToken */: + return containingNodeKind === 185 /* ArrayBindingPattern */; // var [.| + case 57 /* ColonToken */: + return containingNodeKind === 186 /* BindingElement */; // var {x :html| + case 22 /* OpenBracketToken */: + return containingNodeKind === 185 /* ArrayBindingPattern */; // var [x| + case 20 /* OpenParenToken */: + return containingNodeKind === 274 /* CatchClause */ || + isFunctionLikeButNotConstructor(containingNodeKind); + case 18 /* OpenBraceToken */: + return containingNodeKind === 243 /* EnumDeclaration */; // enum a { | + case 28 /* LessThanToken */: + return containingNodeKind === 240 /* ClassDeclaration */ || // class A< | + containingNodeKind === 209 /* ClassExpression */ || // var C = class D< | + containingNodeKind === 241 /* InterfaceDeclaration */ || // interface A< | + containingNodeKind === 242 /* TypeAliasDeclaration */ || // type List< | + ts.isFunctionLikeKind(containingNodeKind); + case 116 /* StaticKeyword */: + return containingNodeKind === 154 /* PropertyDeclaration */ && !ts.isClassLike(parent.parent); + case 25 /* DotDotDotToken */: + return containingNodeKind === 151 /* Parameter */ || + (!!parent.parent && parent.parent.kind === 185 /* ArrayBindingPattern */); // var [...z| + case 115 /* PublicKeyword */: + case 113 /* PrivateKeyword */: + case 114 /* ProtectedKeyword */: + return containingNodeKind === 151 /* Parameter */ && !ts.isConstructorDeclaration(parent.parent); + case 119 /* AsKeyword */: + return containingNodeKind === 253 /* ImportSpecifier */ || + containingNodeKind === 257 /* ExportSpecifier */ || + containingNodeKind === 251 /* NamespaceImport */; + case 126 /* GetKeyword */: + case 137 /* SetKeyword */: + return !isFromObjectTypeDeclaration(contextToken); + case 76 /* ClassKeyword */: + case 84 /* EnumKeyword */: + case 110 /* InterfaceKeyword */: + case 90 /* FunctionKeyword */: + case 105 /* VarKeyword */: + case 92 /* ImportKeyword */: + case 111 /* LetKeyword */: + case 77 /* ConstKeyword */: + case 117 /* YieldKeyword */: + case 140 /* TypeKeyword */: // type htm| + return true; + case 40 /* AsteriskToken */: + return ts.isFunctionLike(contextToken.parent) && !ts.isMethodDeclaration(contextToken.parent); + } + // If the previous token is keyword correspoding to class member completion keyword + // there will be completion available here + if (isClassMemberCompletionKeyword(keywordForNode(contextToken)) && isFromObjectTypeDeclaration(contextToken)) { + return false; + } + if (isConstructorParameterCompletion(contextToken)) { + // constructor parameter completion is available only if + // - its modifier of the constructor parameter or + // - its name of the parameter and not being edited + // eg. constructor(a |<- this shouldnt show completion + if (!ts.isIdentifier(contextToken) || + ts.isParameterPropertyModifier(keywordForNode(contextToken)) || + isCurrentlyEditingNode(contextToken)) { + return false; + } + } + // Previous token may have been a keyword that was converted to an identifier. + switch (keywordForNode(contextToken)) { + case 118 /* AbstractKeyword */: + case 76 /* ClassKeyword */: + case 77 /* ConstKeyword */: + case 125 /* DeclareKeyword */: + case 84 /* EnumKeyword */: + case 90 /* FunctionKeyword */: + case 110 /* InterfaceKeyword */: + case 111 /* LetKeyword */: + case 113 /* PrivateKeyword */: + case 114 /* ProtectedKeyword */: + case 115 /* PublicKeyword */: + case 116 /* StaticKeyword */: + case 105 /* VarKeyword */: + case 117 /* YieldKeyword */: + return true; + case 121 /* AsyncKeyword */: + return ts.isPropertyDeclaration(contextToken.parent); + } + return ts.isDeclarationName(contextToken) + && !ts.isJsxAttribute(contextToken.parent) + // Don't block completions if we're in `class C /**/`, because we're *past* the end of the identifier and might want to complete `extends`. + // If `contextToken !== previousToken`, this is `class C ex/**/`. + && !(ts.isClassLike(contextToken.parent) && (contextToken !== previousToken || position > previousToken.end)); + } + function isFunctionLikeButNotConstructor(kind) { + return ts.isFunctionLikeKind(kind) && kind !== 157 /* Constructor */; + } + function isDotOfNumericLiteral(contextToken) { + if (contextToken.kind === 8 /* NumericLiteral */) { + var text = contextToken.getFullText(); + return text.charAt(text.length - 1) === "."; + } + return false; + } + /** + * Filters out completion suggestions for named imports or exports. + * + * @returns Symbols to be suggested in an object binding pattern or object literal expression, barring those whose declarations + * do not occur at the current position and have not otherwise been typed. + */ + function filterObjectMembersList(contextualMemberSymbols, existingMembers) { + if (existingMembers.length === 0) { + return contextualMemberSymbols; + } + var existingMemberNames = ts.createUnderscoreEscapedMap(); + for (var _i = 0, existingMembers_1 = existingMembers; _i < existingMembers_1.length; _i++) { + var m = existingMembers_1[_i]; + // Ignore omitted expressions for missing members + if (m.kind !== 275 /* PropertyAssignment */ && + m.kind !== 276 /* ShorthandPropertyAssignment */ && + m.kind !== 186 /* BindingElement */ && + m.kind !== 156 /* MethodDeclaration */ && + m.kind !== 158 /* GetAccessor */ && + m.kind !== 159 /* SetAccessor */) { + continue; + } + // If this is the current item we are editing right now, do not filter it out + if (isCurrentlyEditingNode(m)) { + continue; + } + var existingName = void 0; + if (ts.isBindingElement(m) && m.propertyName) { + // include only identifiers in completion list + if (m.propertyName.kind === 72 /* Identifier */) { + existingName = m.propertyName.escapedText; + } + } + else { + // TODO: Account for computed property name + // NOTE: if one only performs this step when m.name is an identifier, + // things like '__proto__' are not filtered out. + var name = ts.getNameOfDeclaration(m); + existingName = name && ts.isPropertyNameLiteral(name) ? ts.getEscapedTextOfIdentifierOrLiteral(name) : undefined; + } + existingMemberNames.set(existingName, true); // TODO: GH#18217 + } + return contextualMemberSymbols.filter(function (m) { return !existingMemberNames.get(m.escapedName); }); + } + /** + * Filters out completion suggestions for class elements. + * + * @returns Symbols to be suggested in an class element depending on existing memebers and symbol flags + */ + function filterClassMembersList(baseSymbols, existingMembers, currentClassElementModifierFlags) { + var existingMemberNames = ts.createUnderscoreEscapedMap(); + for (var _i = 0, existingMembers_2 = existingMembers; _i < existingMembers_2.length; _i++) { + var m = existingMembers_2[_i]; + // Ignore omitted expressions for missing members + if (m.kind !== 154 /* PropertyDeclaration */ && + m.kind !== 156 /* MethodDeclaration */ && + m.kind !== 158 /* GetAccessor */ && + m.kind !== 159 /* SetAccessor */) { + continue; + } + // If this is the current item we are editing right now, do not filter it out + if (isCurrentlyEditingNode(m)) { + continue; + } + // Dont filter member even if the name matches if it is declared private in the list + if (ts.hasModifier(m, 8 /* Private */)) { + continue; + } + // do not filter it out if the static presence doesnt match + if (ts.hasModifier(m, 32 /* Static */) !== !!(currentClassElementModifierFlags & 32 /* Static */)) { + continue; + } + var existingName = ts.getPropertyNameForPropertyNameNode(m.name); + if (existingName) { + existingMemberNames.set(existingName, true); + } + } + return baseSymbols.filter(function (propertySymbol) { + return !existingMemberNames.has(propertySymbol.escapedName) && + !!propertySymbol.declarations && + !(ts.getDeclarationModifierFlagsFromSymbol(propertySymbol) & 8 /* Private */); + }); + } + /** + * Filters out completion suggestions from 'symbols' according to existing JSX attributes. + * + * @returns Symbols to be suggested in a JSX element, barring those whose attributes + * do not occur at the current position and have not otherwise been typed. + */ + function filterJsxAttributes(symbols, attributes) { + var seenNames = ts.createUnderscoreEscapedMap(); + for (var _i = 0, attributes_1 = attributes; _i < attributes_1.length; _i++) { + var attr = attributes_1[_i]; + // If this is the current item we are editing right now, do not filter it out + if (isCurrentlyEditingNode(attr)) { + continue; + } + if (attr.kind === 267 /* JsxAttribute */) { + seenNames.set(attr.name.escapedText, true); + } + } + return symbols.filter(function (a) { return !seenNames.get(a.escapedName); }); + } + function isCurrentlyEditingNode(node) { + return node.getStart(sourceFile) <= position && position <= node.getEnd(); + } + } + function getCompletionEntryDisplayNameForSymbol(symbol, target, origin, kind) { + var name = getSymbolName(symbol, origin, target); + if (name === undefined + // If the symbol is external module, don't show it in the completion list + // (i.e declare module "http" { const x; } | // <= request completion here, "http" should not be there) + || symbol.flags & 1536 /* Module */ && ts.startsWithQuote(name) + // If the symbol is the internal name of an ES symbol, it is not a valid entry. Internal names for ES symbols start with "__@" + || ts.isKnownSymbol(symbol)) { + return undefined; + } + var validIdentiferResult = { name: name, needsConvertPropertyAccess: false }; + if (ts.isIdentifierText(name, target)) + return validIdentiferResult; + switch (kind) { + case 3 /* MemberLike */: + return undefined; + case 0 /* ObjectPropertyDeclaration */: + // TODO: GH#18169 + return { name: JSON.stringify(name), needsConvertPropertyAccess: false }; + case 2 /* PropertyAccess */: + case 1 /* Global */: // For a 'this.' completion it will be in a global context, but may have a non-identifier name. + // Don't add a completion for a name starting with a space. See https://github.com/Microsoft/TypeScript/pull/20547 + return name.charCodeAt(0) === 32 /* space */ ? undefined : { name: name, needsConvertPropertyAccess: true }; + case 5 /* None */: + case 4 /* String */: + return validIdentiferResult; + default: + ts.Debug.assertNever(kind); + } + } + // A cache of completion entries for keywords, these do not change between sessions + var _keywordCompletions = []; + var allKeywordsCompletions = ts.memoize(function () { + var res = []; + for (var i = 73 /* FirstKeyword */; i <= 147 /* LastKeyword */; i++) { + res.push({ + name: ts.tokenToString(i), + kind: "keyword" /* keyword */, + kindModifiers: "" /* none */, + sortText: "0" + }); + } + return res; + }); + function getKeywordCompletions(keywordFilter) { + return _keywordCompletions[keywordFilter] || (_keywordCompletions[keywordFilter] = allKeywordsCompletions().filter(function (entry) { + var kind = ts.stringToToken(entry.name); + switch (keywordFilter) { + case 0 /* None */: + return false; + case 1 /* All */: + return kind === 121 /* AsyncKeyword */ || 122 /* AwaitKeyword */ || !ts.isContextualKeyword(kind) && !isClassMemberCompletionKeyword(kind) || kind === 125 /* DeclareKeyword */ || kind === 130 /* ModuleKeyword */ + || ts.isTypeKeyword(kind) && kind !== 141 /* UndefinedKeyword */; + case 2 /* ClassElementKeywords */: + return isClassMemberCompletionKeyword(kind); + case 3 /* InterfaceElementKeywords */: + return isInterfaceOrTypeLiteralCompletionKeyword(kind); + case 4 /* ConstructorParameterKeywords */: + return ts.isParameterPropertyModifier(kind); + case 5 /* FunctionLikeBodyKeywords */: + return isFunctionLikeBodyKeyword(kind); + case 6 /* TypeKeywords */: + return ts.isTypeKeyword(kind); + default: + return ts.Debug.assertNever(keywordFilter); + } + })); + } + function isInterfaceOrTypeLiteralCompletionKeyword(kind) { + return kind === 133 /* ReadonlyKeyword */; + } + function isClassMemberCompletionKeyword(kind) { + switch (kind) { + case 118 /* AbstractKeyword */: + case 124 /* ConstructorKeyword */: + case 126 /* GetKeyword */: + case 137 /* SetKeyword */: + case 121 /* AsyncKeyword */: + return true; + default: + return ts.isClassMemberModifier(kind); + } + } + function isFunctionLikeBodyKeyword(kind) { + return kind === 121 /* AsyncKeyword */ || kind === 122 /* AwaitKeyword */ || !ts.isContextualKeyword(kind) && !isClassMemberCompletionKeyword(kind); + } + function keywordForNode(node) { + return ts.isIdentifier(node) ? node.originalKeywordKind || 0 /* Unknown */ : node.kind; + } + /** Get the corresponding JSDocTag node if the position is in a jsDoc comment */ + function getJsDocTagAtPosition(node, position) { + var jsdoc = ts.findAncestor(node, ts.isJSDoc); + return jsdoc && jsdoc.tags && (ts.rangeContainsPosition(jsdoc, position) ? ts.findLast(jsdoc.tags, function (tag) { return tag.pos < position; }) : undefined); + } + function getPropertiesForObjectExpression(contextualType, obj, checker) { + return contextualType.isUnion() + ? checker.getAllPossiblePropertiesOfTypes(contextualType.types.filter(function (memberType) { + // If we're providing completions for an object literal, skip primitive, array-like, or callable types since those shouldn't be implemented by object literals. + return !(memberType.flags & 131068 /* Primitive */ || + checker.isArrayLikeType(memberType) || + ts.typeHasCallOrConstructSignatures(memberType, checker) || + checker.isTypeInvalidDueToUnionDiscriminant(memberType, obj)); + })) + : contextualType.getApparentProperties(); + } + /** + * Gets all properties on a type, but if that type is a union of several types, + * excludes array-like types or callable/constructable types. + */ + function getPropertiesForCompletion(type, checker) { + return type.isUnion() + ? ts.Debug.assertEachDefined(checker.getAllPossiblePropertiesOfTypes(type.types), "getAllPossiblePropertiesOfTypes() should all be defined") + : ts.Debug.assertEachDefined(type.getApparentProperties(), "getApparentProperties() should all be defined"); + } + /** + * Returns the immediate owning class declaration of a context token, + * on the condition that one exists and that the context implies completion should be given. + */ + function tryGetObjectTypeDeclarationCompletionContainer(sourceFile, contextToken, location) { + // class c { method() { } | method2() { } } + switch (location.kind) { + case 306 /* SyntaxList */: + return ts.tryCast(location.parent, ts.isObjectTypeDeclaration); + case 1 /* EndOfFileToken */: + var cls = ts.tryCast(ts.lastOrUndefined(ts.cast(location.parent, ts.isSourceFile).statements), ts.isObjectTypeDeclaration); + if (cls && !ts.findChildOfKind(cls, 19 /* CloseBraceToken */, sourceFile)) { + return cls; + } + } + if (!contextToken) + return undefined; + switch (contextToken.kind) { + case 26 /* SemicolonToken */: // class c {getValue(): number; | } + case 19 /* CloseBraceToken */: // class c { method() { } | } + // class c { method() { } b| } + return isFromObjectTypeDeclaration(location) && location.parent.name === location + ? location.parent.parent + : ts.tryCast(location, ts.isObjectTypeDeclaration); + case 18 /* OpenBraceToken */: // class c { | + case 27 /* CommaToken */: // class c {getValue(): number, | } + return ts.tryCast(contextToken.parent, ts.isObjectTypeDeclaration); + default: + if (!isFromObjectTypeDeclaration(contextToken)) + return undefined; + var isValidKeyword = ts.isClassLike(contextToken.parent.parent) ? isClassMemberCompletionKeyword : isInterfaceOrTypeLiteralCompletionKeyword; + return (isValidKeyword(contextToken.kind) || contextToken.kind === 40 /* AsteriskToken */ || ts.isIdentifier(contextToken) && isValidKeyword(ts.stringToToken(contextToken.text))) // TODO: GH#18217 + ? contextToken.parent.parent : undefined; + } + } + // TODO: GH#19856 Would like to return `node is Node & { parent: (ClassElement | TypeElement) & { parent: ObjectTypeDeclaration } }` but then compilation takes > 10 minutes + function isFromObjectTypeDeclaration(node) { + return node.parent && ts.isClassOrTypeElement(node.parent) && ts.isObjectTypeDeclaration(node.parent.parent); + } + function isValidTrigger(sourceFile, triggerCharacter, contextToken, position) { + switch (triggerCharacter) { + case ".": + case "@": + return true; + case '"': + case "'": + case "`": + // Only automatically bring up completions if this is an opening quote. + return !!contextToken && ts.isStringLiteralOrTemplate(contextToken) && position === contextToken.getStart(sourceFile) + 1; + case "<": + // Opening JSX tag + return !!contextToken && contextToken.kind === 28 /* LessThanToken */ && (!ts.isBinaryExpression(contextToken.parent) || binaryExpressionMayBeOpenTag(contextToken.parent)); + case "/": + return !!contextToken && (ts.isStringLiteralLike(contextToken) + ? !!ts.tryGetImportFromModuleSpecifier(contextToken) + : contextToken.kind === 42 /* SlashToken */ && ts.isJsxClosingElement(contextToken.parent)); + default: + return ts.Debug.assertNever(triggerCharacter); + } + } + function binaryExpressionMayBeOpenTag(_a) { + var left = _a.left; + return ts.nodeIsMissing(left); + } + })(Completions = ts.Completions || (ts.Completions = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var DocumentHighlights; + (function (DocumentHighlights) { + function getDocumentHighlights(program, cancellationToken, sourceFile, position, sourceFilesToSearch) { + var node = ts.getTouchingPropertyName(sourceFile, position); + if (node.parent && (ts.isJsxOpeningElement(node.parent) && node.parent.tagName === node || ts.isJsxClosingElement(node.parent))) { + // For a JSX element, just highlight the matching tag, not all references. + var _a = node.parent.parent, openingElement = _a.openingElement, closingElement = _a.closingElement; + var highlightSpans = [openingElement, closingElement].map(function (_a) { + var tagName = _a.tagName; + return getHighlightSpanForNode(tagName, sourceFile); + }); + return [{ fileName: sourceFile.fileName, highlightSpans: highlightSpans }]; + } + return getSemanticDocumentHighlights(position, node, program, cancellationToken, sourceFilesToSearch) || getSyntacticDocumentHighlights(node, sourceFile); + } + DocumentHighlights.getDocumentHighlights = getDocumentHighlights; + function getHighlightSpanForNode(node, sourceFile) { + return { + fileName: sourceFile.fileName, + textSpan: ts.createTextSpanFromNode(node, sourceFile), + kind: "none" /* none */ + }; + } + function getSemanticDocumentHighlights(position, node, program, cancellationToken, sourceFilesToSearch) { + var sourceFilesSet = ts.arrayToSet(sourceFilesToSearch, function (f) { return f.fileName; }); + var referenceEntries = ts.FindAllReferences.getReferenceEntriesForNode(position, node, program, sourceFilesToSearch, cancellationToken, /*options*/ undefined, sourceFilesSet); + if (!referenceEntries) + return undefined; + var map = ts.arrayToMultiMap(referenceEntries.map(ts.FindAllReferences.toHighlightSpan), function (e) { return e.fileName; }, function (e) { return e.span; }); + return ts.arrayFrom(map.entries(), function (_a) { + var fileName = _a[0], highlightSpans = _a[1]; + if (!sourceFilesSet.has(fileName)) { + ts.Debug.assert(program.redirectTargetsMap.has(fileName)); + var redirectTarget_1 = program.getSourceFile(fileName); + var redirect = ts.find(sourceFilesToSearch, function (f) { return !!f.redirectInfo && f.redirectInfo.redirectTarget === redirectTarget_1; }); + fileName = redirect.fileName; + ts.Debug.assert(sourceFilesSet.has(fileName)); + } + return { fileName: fileName, highlightSpans: highlightSpans }; + }); + } + function getSyntacticDocumentHighlights(node, sourceFile) { + var highlightSpans = getHighlightSpans(node, sourceFile); + return highlightSpans && [{ fileName: sourceFile.fileName, highlightSpans: highlightSpans }]; + } + function getHighlightSpans(node, sourceFile) { + switch (node.kind) { + case 91 /* IfKeyword */: + case 83 /* ElseKeyword */: + return ts.isIfStatement(node.parent) ? getIfElseOccurrences(node.parent, sourceFile) : undefined; + case 97 /* ReturnKeyword */: + return useParent(node.parent, ts.isReturnStatement, getReturnOccurrences); + case 101 /* ThrowKeyword */: + return useParent(node.parent, ts.isThrowStatement, getThrowOccurrences); + case 103 /* TryKeyword */: + case 75 /* CatchKeyword */: + case 88 /* FinallyKeyword */: + var tryStatement = node.kind === 75 /* CatchKeyword */ ? node.parent.parent : node.parent; + return useParent(tryStatement, ts.isTryStatement, getTryCatchFinallyOccurrences); + case 99 /* SwitchKeyword */: + return useParent(node.parent, ts.isSwitchStatement, getSwitchCaseDefaultOccurrences); + case 74 /* CaseKeyword */: + case 80 /* DefaultKeyword */: + return useParent(node.parent.parent.parent, ts.isSwitchStatement, getSwitchCaseDefaultOccurrences); + case 73 /* BreakKeyword */: + case 78 /* ContinueKeyword */: + return useParent(node.parent, ts.isBreakOrContinueStatement, getBreakOrContinueStatementOccurrences); + case 89 /* ForKeyword */: + case 107 /* WhileKeyword */: + case 82 /* DoKeyword */: + return useParent(node.parent, function (n) { return ts.isIterationStatement(n, /*lookInLabeledStatements*/ true); }, getLoopBreakContinueOccurrences); + case 124 /* ConstructorKeyword */: + return getFromAllDeclarations(ts.isConstructorDeclaration, [124 /* ConstructorKeyword */]); + case 126 /* GetKeyword */: + case 137 /* SetKeyword */: + return getFromAllDeclarations(ts.isAccessor, [126 /* GetKeyword */, 137 /* SetKeyword */]); + case 122 /* AwaitKeyword */: + return useParent(node.parent, ts.isAwaitExpression, getAsyncAndAwaitOccurrences); + case 121 /* AsyncKeyword */: + return highlightSpans(getAsyncAndAwaitOccurrences(node)); + case 117 /* YieldKeyword */: + return highlightSpans(getYieldOccurrences(node)); + default: + return ts.isModifierKind(node.kind) && (ts.isDeclaration(node.parent) || ts.isVariableStatement(node.parent)) + ? highlightSpans(getModifierOccurrences(node.kind, node.parent)) + : undefined; + } + function getFromAllDeclarations(nodeTest, keywords) { + return useParent(node.parent, nodeTest, function (decl) { return ts.mapDefined(decl.symbol.declarations, function (d) { + return nodeTest(d) ? ts.find(d.getChildren(sourceFile), function (c) { return ts.contains(keywords, c.kind); }) : undefined; + }); }); + } + function useParent(node, nodeTest, getNodes) { + return nodeTest(node) ? highlightSpans(getNodes(node, sourceFile)) : undefined; + } + function highlightSpans(nodes) { + return nodes && nodes.map(function (node) { return getHighlightSpanForNode(node, sourceFile); }); + } + } + /** + * Aggregates all throw-statements within this node *without* crossing + * into function boundaries and try-blocks with catch-clauses. + */ + function aggregateOwnedThrowStatements(node) { + if (ts.isThrowStatement(node)) { + return [node]; + } + else if (ts.isTryStatement(node)) { + // Exceptions thrown within a try block lacking a catch clause are "owned" in the current context. + return ts.concatenate(node.catchClause ? aggregateOwnedThrowStatements(node.catchClause) : node.tryBlock && aggregateOwnedThrowStatements(node.tryBlock), node.finallyBlock && aggregateOwnedThrowStatements(node.finallyBlock)); + } + // Do not cross function boundaries. + return ts.isFunctionLike(node) ? undefined : flatMapChildren(node, aggregateOwnedThrowStatements); + } + /** + * For lack of a better name, this function takes a throw statement and returns the + * nearest ancestor that is a try-block (whose try statement has a catch clause), + * function-block, or source file. + */ + function getThrowStatementOwner(throwStatement) { + var child = throwStatement; + while (child.parent) { + var parent = child.parent; + if (ts.isFunctionBlock(parent) || parent.kind === 279 /* SourceFile */) { + return parent; + } + // A throw-statement is only owned by a try-statement if the try-statement has + // a catch clause, and if the throw-statement occurs within the try block. + if (ts.isTryStatement(parent) && parent.tryBlock === child && parent.catchClause) { + return child; + } + child = parent; + } + return undefined; + } + function aggregateAllBreakAndContinueStatements(node) { + return ts.isBreakOrContinueStatement(node) ? [node] : ts.isFunctionLike(node) ? undefined : flatMapChildren(node, aggregateAllBreakAndContinueStatements); + } + function flatMapChildren(node, cb) { + var result = []; + node.forEachChild(function (child) { + var value = cb(child); + if (value !== undefined) { + result.push.apply(result, ts.toArray(value)); + } + }); + return result; + } + function ownsBreakOrContinueStatement(owner, statement) { + var actualOwner = getBreakOrContinueOwner(statement); + return !!actualOwner && actualOwner === owner; + } + function getBreakOrContinueOwner(statement) { + return ts.findAncestor(statement, function (node) { + switch (node.kind) { + case 232 /* SwitchStatement */: + if (statement.kind === 228 /* ContinueStatement */) { + return false; + } + // falls through + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + case 224 /* WhileStatement */: + case 223 /* DoStatement */: + return !statement.label || isLabeledBy(node, statement.label.escapedText); + default: + // Don't cross function boundaries. + // TODO: GH#20090 + return ts.isFunctionLike(node) && "quit"; + } + }); + } + function getModifierOccurrences(modifier, declaration) { + return ts.mapDefined(getNodesToSearchForModifier(declaration, ts.modifierToFlag(modifier)), function (node) { return ts.findModifier(node, modifier); }); + } + function getNodesToSearchForModifier(declaration, modifierFlag) { + // Types of node whose children might have modifiers. + var container = declaration.parent; + switch (container.kind) { + case 245 /* ModuleBlock */: + case 279 /* SourceFile */: + case 218 /* Block */: + case 271 /* CaseClause */: + case 272 /* DefaultClause */: + // Container is either a class declaration or the declaration is a classDeclaration + if (modifierFlag & 128 /* Abstract */ && ts.isClassDeclaration(declaration)) { + return declaration.members.concat([declaration]); + } + else { + return container.statements; + } + case 157 /* Constructor */: + case 156 /* MethodDeclaration */: + case 239 /* FunctionDeclaration */: + return container.parameters.concat((ts.isClassLike(container.parent) ? container.parent.members : [])); + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + var nodes = container.members; + // If we're an accessibility modifier, we're in an instance member and should search + // the constructor's parameter list for instance members as well. + if (modifierFlag & 28 /* AccessibilityModifier */) { + var constructor = ts.find(container.members, ts.isConstructorDeclaration); + if (constructor) { + return nodes.concat(constructor.parameters); + } + } + else if (modifierFlag & 128 /* Abstract */) { + return nodes.concat([container]); + } + return nodes; + default: + ts.Debug.assertNever(container, "Invalid container kind."); + } + } + function pushKeywordIf(keywordList, token) { + var expected = []; + for (var _i = 2; _i < arguments.length; _i++) { + expected[_i - 2] = arguments[_i]; + } + if (token && ts.contains(expected, token.kind)) { + keywordList.push(token); + return true; + } + return false; + } + function getLoopBreakContinueOccurrences(loopNode) { + var keywords = []; + if (pushKeywordIf(keywords, loopNode.getFirstToken(), 89 /* ForKeyword */, 107 /* WhileKeyword */, 82 /* DoKeyword */)) { + // If we succeeded and got a do-while loop, then start looking for a 'while' keyword. + if (loopNode.kind === 223 /* DoStatement */) { + var loopTokens = loopNode.getChildren(); + for (var i = loopTokens.length - 1; i >= 0; i--) { + if (pushKeywordIf(keywords, loopTokens[i], 107 /* WhileKeyword */)) { + break; + } + } + } + } + ts.forEach(aggregateAllBreakAndContinueStatements(loopNode.statement), function (statement) { + if (ownsBreakOrContinueStatement(loopNode, statement)) { + pushKeywordIf(keywords, statement.getFirstToken(), 73 /* BreakKeyword */, 78 /* ContinueKeyword */); + } + }); + return keywords; + } + function getBreakOrContinueStatementOccurrences(breakOrContinueStatement) { + var owner = getBreakOrContinueOwner(breakOrContinueStatement); + if (owner) { + switch (owner.kind) { + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + case 223 /* DoStatement */: + case 224 /* WhileStatement */: + return getLoopBreakContinueOccurrences(owner); + case 232 /* SwitchStatement */: + return getSwitchCaseDefaultOccurrences(owner); + } + } + return undefined; + } + function getSwitchCaseDefaultOccurrences(switchStatement) { + var keywords = []; + pushKeywordIf(keywords, switchStatement.getFirstToken(), 99 /* SwitchKeyword */); + // Go through each clause in the switch statement, collecting the 'case'/'default' keywords. + ts.forEach(switchStatement.caseBlock.clauses, function (clause) { + pushKeywordIf(keywords, clause.getFirstToken(), 74 /* CaseKeyword */, 80 /* DefaultKeyword */); + ts.forEach(aggregateAllBreakAndContinueStatements(clause), function (statement) { + if (ownsBreakOrContinueStatement(switchStatement, statement)) { + pushKeywordIf(keywords, statement.getFirstToken(), 73 /* BreakKeyword */); + } + }); + }); + return keywords; + } + function getTryCatchFinallyOccurrences(tryStatement, sourceFile) { + var keywords = []; + pushKeywordIf(keywords, tryStatement.getFirstToken(), 103 /* TryKeyword */); + if (tryStatement.catchClause) { + pushKeywordIf(keywords, tryStatement.catchClause.getFirstToken(), 75 /* CatchKeyword */); + } + if (tryStatement.finallyBlock) { + var finallyKeyword = ts.findChildOfKind(tryStatement, 88 /* FinallyKeyword */, sourceFile); + pushKeywordIf(keywords, finallyKeyword, 88 /* FinallyKeyword */); + } + return keywords; + } + function getThrowOccurrences(throwStatement, sourceFile) { + var owner = getThrowStatementOwner(throwStatement); + if (!owner) { + return undefined; + } + var keywords = []; + ts.forEach(aggregateOwnedThrowStatements(owner), function (throwStatement) { + keywords.push(ts.findChildOfKind(throwStatement, 101 /* ThrowKeyword */, sourceFile)); + }); + // If the "owner" is a function, then we equate 'return' and 'throw' statements in their + // ability to "jump out" of the function, and include occurrences for both. + if (ts.isFunctionBlock(owner)) { + ts.forEachReturnStatement(owner, function (returnStatement) { + keywords.push(ts.findChildOfKind(returnStatement, 97 /* ReturnKeyword */, sourceFile)); + }); + } + return keywords; + } + function getReturnOccurrences(returnStatement, sourceFile) { + var func = ts.getContainingFunction(returnStatement); + if (!func) { + return undefined; + } + var keywords = []; + ts.forEachReturnStatement(ts.cast(func.body, ts.isBlock), function (returnStatement) { + keywords.push(ts.findChildOfKind(returnStatement, 97 /* ReturnKeyword */, sourceFile)); + }); + // Include 'throw' statements that do not occur within a try block. + ts.forEach(aggregateOwnedThrowStatements(func.body), function (throwStatement) { + keywords.push(ts.findChildOfKind(throwStatement, 101 /* ThrowKeyword */, sourceFile)); + }); + return keywords; + } + function getAsyncAndAwaitOccurrences(node) { + var func = ts.getContainingFunction(node); + if (!func) { + return undefined; + } + var keywords = []; + if (func.modifiers) { + func.modifiers.forEach(function (modifier) { + pushKeywordIf(keywords, modifier, 121 /* AsyncKeyword */); + }); + } + ts.forEachChild(func, function (child) { + traverseWithoutCrossingFunction(child, function (node) { + if (ts.isAwaitExpression(node)) { + pushKeywordIf(keywords, node.getFirstToken(), 122 /* AwaitKeyword */); + } + }); + }); + return keywords; + } + function getYieldOccurrences(node) { + var func = ts.getContainingFunction(node); + if (!func) { + return undefined; + } + var keywords = []; + ts.forEachChild(func, function (child) { + traverseWithoutCrossingFunction(child, function (node) { + if (ts.isYieldExpression(node)) { + pushKeywordIf(keywords, node.getFirstToken(), 117 /* YieldKeyword */); + } + }); + }); + return keywords; + } + // Do not cross function/class/interface/module/type boundaries. + function traverseWithoutCrossingFunction(node, cb) { + cb(node); + if (!ts.isFunctionLike(node) && !ts.isClassLike(node) && !ts.isInterfaceDeclaration(node) && !ts.isModuleDeclaration(node) && !ts.isTypeAliasDeclaration(node) && !ts.isTypeNode(node)) { + ts.forEachChild(node, function (child) { return traverseWithoutCrossingFunction(child, cb); }); + } + } + function getIfElseOccurrences(ifStatement, sourceFile) { + var keywords = getIfElseKeywords(ifStatement, sourceFile); + var result = []; + // We'd like to highlight else/ifs together if they are only separated by whitespace + // (i.e. the keywords are separated by no comments, no newlines). + for (var i = 0; i < keywords.length; i++) { + if (keywords[i].kind === 83 /* ElseKeyword */ && i < keywords.length - 1) { + var elseKeyword = keywords[i]; + var ifKeyword = keywords[i + 1]; // this *should* always be an 'if' keyword. + var shouldCombineElseAndIf = true; + // Avoid recalculating getStart() by iterating backwards. + for (var j = ifKeyword.getStart(sourceFile) - 1; j >= elseKeyword.end; j--) { + if (!ts.isWhiteSpaceSingleLine(sourceFile.text.charCodeAt(j))) { + shouldCombineElseAndIf = false; + break; + } + } + if (shouldCombineElseAndIf) { + result.push({ + fileName: sourceFile.fileName, + textSpan: ts.createTextSpanFromBounds(elseKeyword.getStart(), ifKeyword.end), + kind: "reference" /* reference */ + }); + i++; // skip the next keyword + continue; + } + } + // Ordinary case: just highlight the keyword. + result.push(getHighlightSpanForNode(keywords[i], sourceFile)); + } + return result; + } + function getIfElseKeywords(ifStatement, sourceFile) { + var keywords = []; + // Traverse upwards through all parent if-statements linked by their else-branches. + while (ts.isIfStatement(ifStatement.parent) && ifStatement.parent.elseStatement === ifStatement) { + ifStatement = ifStatement.parent; + } + // Now traverse back down through the else branches, aggregating if/else keywords of if-statements. + while (true) { + var children = ifStatement.getChildren(sourceFile); + pushKeywordIf(keywords, children[0], 91 /* IfKeyword */); + // Generally the 'else' keyword is second-to-last, so we traverse backwards. + for (var i = children.length - 1; i >= 0; i--) { + if (pushKeywordIf(keywords, children[i], 83 /* ElseKeyword */)) { + break; + } + } + if (!ifStatement.elseStatement || !ts.isIfStatement(ifStatement.elseStatement)) { + break; + } + ifStatement = ifStatement.elseStatement; + } + return keywords; + } + /** + * Whether or not a 'node' is preceded by a label of the given string. + * Note: 'node' cannot be a SourceFile. + */ + function isLabeledBy(node, labelName) { + return !!ts.findAncestor(node.parent, function (owner) { return !ts.isLabeledStatement(owner) ? "quit" : owner.label.escapedText === labelName; }); + } + })(DocumentHighlights = ts.DocumentHighlights || (ts.DocumentHighlights = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + function createDocumentRegistry(useCaseSensitiveFileNames, currentDirectory) { + return createDocumentRegistryInternal(useCaseSensitiveFileNames, currentDirectory); + } + ts.createDocumentRegistry = createDocumentRegistry; + /*@internal*/ + function createDocumentRegistryInternal(useCaseSensitiveFileNames, currentDirectory, externalCache) { + if (currentDirectory === void 0) { currentDirectory = ""; } + // Maps from compiler setting target (ES3, ES5, etc.) to all the cached documents we have + // for those settings. + var buckets = ts.createMap(); + var getCanonicalFileName = ts.createGetCanonicalFileName(!!useCaseSensitiveFileNames); + function reportStats() { + var bucketInfoArray = ts.arrayFrom(buckets.keys()).filter(function (name) { return name && name.charAt(0) === "_"; }).map(function (name) { + var entries = buckets.get(name); + var sourceFiles = []; + entries.forEach(function (entry, name) { + sourceFiles.push({ + name: name, + refCount: entry.languageServiceRefCount + }); + }); + sourceFiles.sort(function (x, y) { return y.refCount - x.refCount; }); + return { + bucket: name, + sourceFiles: sourceFiles + }; + }); + return JSON.stringify(bucketInfoArray, undefined, 2); + } + function acquireDocument(fileName, compilationSettings, scriptSnapshot, version, scriptKind) { + var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); + var key = getKeyForCompilationSettings(compilationSettings); + return acquireDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind); + } + function acquireDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind) { + return acquireOrUpdateDocument(fileName, path, compilationSettings, key, scriptSnapshot, version, /*acquiring*/ true, scriptKind); + } + function updateDocument(fileName, compilationSettings, scriptSnapshot, version, scriptKind) { + var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); + var key = getKeyForCompilationSettings(compilationSettings); + return updateDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind); + } + function updateDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind) { + return acquireOrUpdateDocument(fileName, path, compilationSettings, key, scriptSnapshot, version, /*acquiring*/ false, scriptKind); + } + function acquireOrUpdateDocument(fileName, path, compilationSettings, key, scriptSnapshot, version, acquiring, scriptKind) { + var bucket = ts.getOrUpdate(buckets, key, ts.createMap); + var entry = bucket.get(path); + var scriptTarget = scriptKind === 6 /* JSON */ ? 100 /* JSON */ : compilationSettings.target || 1 /* ES5 */; + if (!entry && externalCache) { + var sourceFile = externalCache.getDocument(key, path); + if (sourceFile) { + ts.Debug.assert(acquiring); + entry = { + sourceFile: sourceFile, + languageServiceRefCount: 0 + }; + bucket.set(path, entry); + } + } + if (!entry) { + // Have never seen this file with these settings. Create a new source file for it. + var sourceFile = ts.createLanguageServiceSourceFile(fileName, scriptSnapshot, scriptTarget, version, /*setNodeParents*/ false, scriptKind); + if (externalCache) { + externalCache.setDocument(key, path, sourceFile); + } + entry = { + sourceFile: sourceFile, + languageServiceRefCount: 1, + }; + bucket.set(path, entry); + } + else { + // We have an entry for this file. However, it may be for a different version of + // the script snapshot. If so, update it appropriately. Otherwise, we can just + // return it as is. + if (entry.sourceFile.version !== version) { + entry.sourceFile = ts.updateLanguageServiceSourceFile(entry.sourceFile, scriptSnapshot, version, scriptSnapshot.getChangeRange(entry.sourceFile.scriptSnapshot)); // TODO: GH#18217 + if (externalCache) { + externalCache.setDocument(key, path, entry.sourceFile); + } + } + // If we're acquiring, then this is the first time this LS is asking for this document. + // Increase our ref count so we know there's another LS using the document. If we're + // not acquiring, then that means the LS is 'updating' the file instead, and that means + // it has already acquired the document previously. As such, we do not need to increase + // the ref count. + if (acquiring) { + entry.languageServiceRefCount++; + } + } + ts.Debug.assert(entry.languageServiceRefCount !== 0); + return entry.sourceFile; + } + function releaseDocument(fileName, compilationSettings) { + var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); + var key = getKeyForCompilationSettings(compilationSettings); + return releaseDocumentWithKey(path, key); + } + function releaseDocumentWithKey(path, key) { + var bucket = ts.Debug.assertDefined(buckets.get(key)); + var entry = bucket.get(path); + entry.languageServiceRefCount--; + ts.Debug.assert(entry.languageServiceRefCount >= 0); + if (entry.languageServiceRefCount === 0) { + bucket.delete(path); + } + } + function getLanguageServiceRefCounts(path) { + return ts.arrayFrom(buckets.entries(), function (_a) { + var key = _a[0], bucket = _a[1]; + var entry = bucket.get(path); + return [key, entry && entry.languageServiceRefCount]; + }); + } + return { + acquireDocument: acquireDocument, + acquireDocumentWithKey: acquireDocumentWithKey, + updateDocument: updateDocument, + updateDocumentWithKey: updateDocumentWithKey, + releaseDocument: releaseDocument, + releaseDocumentWithKey: releaseDocumentWithKey, + getLanguageServiceRefCounts: getLanguageServiceRefCounts, + reportStats: reportStats, + getKeyForCompilationSettings: getKeyForCompilationSettings + }; + } + ts.createDocumentRegistryInternal = createDocumentRegistryInternal; + function getKeyForCompilationSettings(settings) { + return ts.sourceFileAffectingCompilerOptions.map(function (option) { return ts.getCompilerOptionValue(settings, option); }).join("|"); + } +})(ts || (ts = {})); +/* Code for finding imports of an exported symbol. Used only by FindAllReferences. */ +/* @internal */ +var ts; +(function (ts) { + var FindAllReferences; + (function (FindAllReferences) { + /** Creates the imports map and returns an ImportTracker that uses it. Call this lazily to avoid calling `getDirectImportsMap` unnecessarily. */ + function createImportTracker(sourceFiles, sourceFilesSet, checker, cancellationToken) { + var allDirectImports = getDirectImportsMap(sourceFiles, checker, cancellationToken); + return function (exportSymbol, exportInfo, isForRename) { + var _a = getImportersForExport(sourceFiles, sourceFilesSet, allDirectImports, exportInfo, checker, cancellationToken), directImports = _a.directImports, indirectUsers = _a.indirectUsers; + return __assign({ indirectUsers: indirectUsers }, getSearchesFromDirectImports(directImports, exportSymbol, exportInfo.exportKind, checker, isForRename)); + }; + } + FindAllReferences.createImportTracker = createImportTracker; + var ExportKind; + (function (ExportKind) { + ExportKind[ExportKind["Named"] = 0] = "Named"; + ExportKind[ExportKind["Default"] = 1] = "Default"; + ExportKind[ExportKind["ExportEquals"] = 2] = "ExportEquals"; + })(ExportKind = FindAllReferences.ExportKind || (FindAllReferences.ExportKind = {})); + var ImportExport; + (function (ImportExport) { + ImportExport[ImportExport["Import"] = 0] = "Import"; + ImportExport[ImportExport["Export"] = 1] = "Export"; + })(ImportExport = FindAllReferences.ImportExport || (FindAllReferences.ImportExport = {})); + /** Returns import statements that directly reference the exporting module, and a list of files that may access the module through a namespace. */ + function getImportersForExport(sourceFiles, sourceFilesSet, allDirectImports, _a, checker, cancellationToken) { + var exportingModuleSymbol = _a.exportingModuleSymbol, exportKind = _a.exportKind; + var markSeenDirectImport = ts.nodeSeenTracker(); + var markSeenIndirectUser = ts.nodeSeenTracker(); + var directImports = []; + var isAvailableThroughGlobal = !!exportingModuleSymbol.globalExports; + var indirectUserDeclarations = isAvailableThroughGlobal ? undefined : []; + handleDirectImports(exportingModuleSymbol); + return { directImports: directImports, indirectUsers: getIndirectUsers() }; + function getIndirectUsers() { + if (isAvailableThroughGlobal) { + // It has `export as namespace`, so anything could potentially use it. + return sourceFiles; + } + // Module augmentations may use this module's exports without importing it. + for (var _i = 0, _a = exportingModuleSymbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + if (ts.isExternalModuleAugmentation(decl) && sourceFilesSet.has(decl.getSourceFile().fileName)) { + addIndirectUser(decl); + } + } + // This may return duplicates (if there are multiple module declarations in a single source file, all importing the same thing as a namespace), but `State.markSearchedSymbol` will handle that. + return indirectUserDeclarations.map(ts.getSourceFileOfNode); + } + function handleDirectImports(exportingModuleSymbol) { + var theseDirectImports = getDirectImports(exportingModuleSymbol); + if (theseDirectImports) { + for (var _i = 0, theseDirectImports_1 = theseDirectImports; _i < theseDirectImports_1.length; _i++) { + var direct = theseDirectImports_1[_i]; + if (!markSeenDirectImport(direct)) { + continue; + } + if (cancellationToken) + cancellationToken.throwIfCancellationRequested(); + switch (direct.kind) { + case 191 /* CallExpression */: + if (!isAvailableThroughGlobal) { + var parent = direct.parent; + if (exportKind === 2 /* ExportEquals */ && parent.kind === 237 /* VariableDeclaration */) { + var name = parent.name; + if (name.kind === 72 /* Identifier */) { + directImports.push(name); + break; + } + } + // Don't support re-exporting 'require()' calls, so just add a single indirect user. + addIndirectUser(direct.getSourceFile()); + } + break; + case 72 /* Identifier */: // for 'const x = require("y"); + break; // TODO: GH#23879 + case 248 /* ImportEqualsDeclaration */: + handleNamespaceImport(direct, direct.name, ts.hasModifier(direct, 1 /* Export */), /*alreadyAddedDirect*/ false); + break; + case 249 /* ImportDeclaration */: + directImports.push(direct); + var namedBindings = direct.importClause && direct.importClause.namedBindings; + if (namedBindings && namedBindings.kind === 251 /* NamespaceImport */) { + handleNamespaceImport(direct, namedBindings.name, /*isReExport*/ false, /*alreadyAddedDirect*/ true); + } + else if (!isAvailableThroughGlobal && ts.isDefaultImport(direct)) { + addIndirectUser(getSourceFileLikeForImportDeclaration(direct)); // Add a check for indirect uses to handle synthetic default imports + } + break; + case 255 /* ExportDeclaration */: + if (!direct.exportClause) { + // This is `export * from "foo"`, so imports of this module may import the export too. + handleDirectImports(getContainingModuleSymbol(direct, checker)); + } + else { + // This is `export { foo } from "foo"` and creates an alias symbol, so recursive search will get handle re-exports. + directImports.push(direct); + } + break; + case 183 /* ImportType */: + directImports.push(direct); + break; + default: + ts.Debug.assertNever(direct, "Unexpected import kind: " + ts.Debug.showSyntaxKind(direct)); + } + } + } + } + function handleNamespaceImport(importDeclaration, name, isReExport, alreadyAddedDirect) { + if (exportKind === 2 /* ExportEquals */) { + // This is a direct import, not import-as-namespace. + if (!alreadyAddedDirect) + directImports.push(importDeclaration); + } + else if (!isAvailableThroughGlobal) { + var sourceFileLike = getSourceFileLikeForImportDeclaration(importDeclaration); + ts.Debug.assert(sourceFileLike.kind === 279 /* SourceFile */ || sourceFileLike.kind === 244 /* ModuleDeclaration */); + if (isReExport || findNamespaceReExports(sourceFileLike, name, checker)) { + addIndirectUsers(sourceFileLike); + } + else { + addIndirectUser(sourceFileLike); + } + } + } + function addIndirectUser(sourceFileLike) { + ts.Debug.assert(!isAvailableThroughGlobal); + var isNew = markSeenIndirectUser(sourceFileLike); + if (isNew) { + indirectUserDeclarations.push(sourceFileLike); // TODO: GH#18217 + } + return isNew; + } + /** Adds a module and all of its transitive dependencies as possible indirect users. */ + function addIndirectUsers(sourceFileLike) { + if (!addIndirectUser(sourceFileLike)) { + return; + } + var moduleSymbol = checker.getMergedSymbol(sourceFileLike.symbol); + ts.Debug.assert(!!(moduleSymbol.flags & 1536 /* Module */)); + var directImports = getDirectImports(moduleSymbol); + if (directImports) { + for (var _i = 0, directImports_1 = directImports; _i < directImports_1.length; _i++) { + var directImport = directImports_1[_i]; + addIndirectUsers(getSourceFileLikeForImportDeclaration(directImport)); + } + } + } + function getDirectImports(moduleSymbol) { + return allDirectImports.get(ts.getSymbolId(moduleSymbol).toString()); + } + } + /** + * Given the set of direct imports of a module, we need to find which ones import the particular exported symbol. + * The returned `importSearches` will result in the entire source file being searched. + * But re-exports will be placed in 'singleReferences' since they cannot be locally referenced. + */ + function getSearchesFromDirectImports(directImports, exportSymbol, exportKind, checker, isForRename) { + var importSearches = []; + var singleReferences = []; + function addSearch(location, symbol) { + importSearches.push([location, symbol]); + } + if (directImports) { + for (var _i = 0, directImports_2 = directImports; _i < directImports_2.length; _i++) { + var decl = directImports_2[_i]; + handleImport(decl); + } + } + return { importSearches: importSearches, singleReferences: singleReferences }; + function handleImport(decl) { + if (decl.kind === 248 /* ImportEqualsDeclaration */) { + if (isExternalModuleImportEquals(decl)) { + handleNamespaceImportLike(decl.name); + } + return; + } + if (decl.kind === 72 /* Identifier */) { + handleNamespaceImportLike(decl); + return; + } + if (decl.kind === 183 /* ImportType */) { + if (decl.qualifier) { + if (ts.isIdentifier(decl.qualifier) && decl.qualifier.escapedText === ts.symbolName(exportSymbol)) { + singleReferences.push(decl.qualifier); + } + } + else if (exportKind === 2 /* ExportEquals */) { + singleReferences.push(decl.argument.literal); + } + return; + } + // Ignore if there's a grammar error + if (decl.moduleSpecifier.kind !== 10 /* StringLiteral */) { + return; + } + if (decl.kind === 255 /* ExportDeclaration */) { + searchForNamedImport(decl.exportClause); + return; + } + var _a = decl.importClause || { name: undefined, namedBindings: undefined }, name = _a.name, namedBindings = _a.namedBindings; + if (namedBindings) { + switch (namedBindings.kind) { + case 251 /* NamespaceImport */: + handleNamespaceImportLike(namedBindings.name); + break; + case 252 /* NamedImports */: + // 'default' might be accessed as a named import `{ default as foo }`. + if (exportKind === 0 /* Named */ || exportKind === 1 /* Default */) { + searchForNamedImport(namedBindings); + } + break; + default: + ts.Debug.assertNever(namedBindings); + } + } + // `export =` might be imported by a default import if `--allowSyntheticDefaultImports` is on, so this handles both ExportKind.Default and ExportKind.ExportEquals. + // If a default import has the same name as the default export, allow to rename it. + // Given `import f` and `export default function f`, we will rename both, but for `import g` we will rename just that. + if (name && (exportKind === 1 /* Default */ || exportKind === 2 /* ExportEquals */) && (!isForRename || name.escapedText === ts.symbolEscapedNameNoDefault(exportSymbol))) { + var defaultImportAlias = checker.getSymbolAtLocation(name); + addSearch(name, defaultImportAlias); + } + } + /** + * `import x = require("./x") or `import * as x from "./x"`. + * An `export =` may be imported by this syntax, so it may be a direct import. + * If it's not a direct import, it will be in `indirectUsers`, so we don't have to do anything here. + */ + function handleNamespaceImportLike(importName) { + // Don't rename an import that already has a different name than the export. + if (exportKind === 2 /* ExportEquals */ && (!isForRename || isNameMatch(importName.escapedText))) { + addSearch(importName, checker.getSymbolAtLocation(importName)); + } + } + function searchForNamedImport(namedBindings) { + if (!namedBindings) { + return; + } + for (var _i = 0, _a = namedBindings.elements; _i < _a.length; _i++) { + var element = _a[_i]; + var name = element.name, propertyName = element.propertyName; + if (!isNameMatch((propertyName || name).escapedText)) { + continue; + } + if (propertyName) { + // This is `import { foo as bar } from "./a"` or `export { foo as bar } from "./a"`. `foo` isn't a local in the file, so just add it as a single reference. + singleReferences.push(propertyName); + // If renaming `{ foo as bar }`, don't touch `bar`, just `foo`. + // But do rename `foo` in ` { default as foo }` if that's the original export name. + if (!isForRename || name.escapedText === exportSymbol.escapedName) { + // Search locally for `bar`. + addSearch(name, checker.getSymbolAtLocation(name)); + } + } + else { + var localSymbol = element.kind === 257 /* ExportSpecifier */ && element.propertyName + ? checker.getExportSpecifierLocalTargetSymbol(element) // For re-exporting under a different name, we want to get the re-exported symbol. + : checker.getSymbolAtLocation(name); + addSearch(name, localSymbol); + } + } + } + function isNameMatch(name) { + // Use name of "default" even in `export =` case because we may have allowSyntheticDefaultImports + return name === exportSymbol.escapedName || exportKind !== 0 /* Named */ && name === "default" /* Default */; + } + } + /** Returns 'true' is the namespace 'name' is re-exported from this module, and 'false' if it is only used locally. */ + function findNamespaceReExports(sourceFileLike, name, checker) { + var namespaceImportSymbol = checker.getSymbolAtLocation(name); + return !!forEachPossibleImportOrExportStatement(sourceFileLike, function (statement) { + if (!ts.isExportDeclaration(statement)) + return; + var exportClause = statement.exportClause, moduleSpecifier = statement.moduleSpecifier; + return !moduleSpecifier && exportClause && + exportClause.elements.some(function (element) { return checker.getExportSpecifierLocalTargetSymbol(element) === namespaceImportSymbol; }); + }); + } + function findModuleReferences(program, sourceFiles, searchModuleSymbol) { + var refs = []; + var checker = program.getTypeChecker(); + for (var _i = 0, sourceFiles_1 = sourceFiles; _i < sourceFiles_1.length; _i++) { + var referencingFile = sourceFiles_1[_i]; + var searchSourceFile = searchModuleSymbol.valueDeclaration; + if (searchSourceFile.kind === 279 /* SourceFile */) { + for (var _a = 0, _b = referencingFile.referencedFiles; _a < _b.length; _a++) { + var ref = _b[_a]; + if (program.getSourceFileFromReference(referencingFile, ref) === searchSourceFile) { + refs.push({ kind: "reference", referencingFile: referencingFile, ref: ref }); + } + } + for (var _c = 0, _d = referencingFile.typeReferenceDirectives; _c < _d.length; _c++) { + var ref = _d[_c]; + var referenced = program.getResolvedTypeReferenceDirectives().get(ref.fileName); + if (referenced !== undefined && referenced.resolvedFileName === searchSourceFile.fileName) { + refs.push({ kind: "reference", referencingFile: referencingFile, ref: ref }); + } + } + } + forEachImport(referencingFile, function (_importDecl, moduleSpecifier) { + var moduleSymbol = checker.getSymbolAtLocation(moduleSpecifier); + if (moduleSymbol === searchModuleSymbol) { + refs.push({ kind: "import", literal: moduleSpecifier }); + } + }); + } + return refs; + } + FindAllReferences.findModuleReferences = findModuleReferences; + /** Returns a map from a module symbol Id to all import statements that directly reference the module. */ + function getDirectImportsMap(sourceFiles, checker, cancellationToken) { + var map = ts.createMap(); + for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) { + var sourceFile = sourceFiles_2[_i]; + if (cancellationToken) + cancellationToken.throwIfCancellationRequested(); + forEachImport(sourceFile, function (importDecl, moduleSpecifier) { + var moduleSymbol = checker.getSymbolAtLocation(moduleSpecifier); + if (moduleSymbol) { + var id = ts.getSymbolId(moduleSymbol).toString(); + var imports = map.get(id); + if (!imports) { + map.set(id, imports = []); + } + imports.push(importDecl); + } + }); + } + return map; + } + /** Iterates over all statements at the top level or in module declarations. Returns the first truthy result. */ + function forEachPossibleImportOrExportStatement(sourceFileLike, action) { + return ts.forEach(sourceFileLike.kind === 279 /* SourceFile */ ? sourceFileLike.statements : sourceFileLike.body.statements, function (statement) { + return action(statement) || (isAmbientModuleDeclaration(statement) && ts.forEach(statement.body && statement.body.statements, action)); + }); + } + /** Calls `action` for each import, re-export, or require() in a file. */ + function forEachImport(sourceFile, action) { + if (sourceFile.externalModuleIndicator || sourceFile.imports !== undefined) { + for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { + var i = _a[_i]; + action(ts.importFromModuleSpecifier(i), i); + } + } + else { + forEachPossibleImportOrExportStatement(sourceFile, function (statement) { + switch (statement.kind) { + case 255 /* ExportDeclaration */: + case 249 /* ImportDeclaration */: { + var decl = statement; + if (decl.moduleSpecifier && ts.isStringLiteral(decl.moduleSpecifier)) { + action(decl, decl.moduleSpecifier); + } + break; + } + case 248 /* ImportEqualsDeclaration */: { + var decl = statement; + if (isExternalModuleImportEquals(decl)) { + action(decl, decl.moduleReference.expression); + } + break; + } + } + }); + } + } + /** + * Given a local reference, we might notice that it's an import/export and recursively search for references of that. + * If at an import, look locally for the symbol it imports. + * If an an export, look for all imports of it. + * This doesn't handle export specifiers; that is done in `getReferencesAtExportSpecifier`. + * @param comingFromExport If we are doing a search for all exports, don't bother looking backwards for the imported symbol, since that's the reason we're here. + */ + function getImportOrExportSymbol(node, symbol, checker, comingFromExport) { + return comingFromExport ? getExport() : getExport() || getImport(); + function getExport() { + var parent = node.parent; + var grandParent = parent.parent; + if (symbol.exportSymbol) { + if (parent.kind === 189 /* PropertyAccessExpression */) { + // When accessing an export of a JS module, there's no alias. The symbol will still be flagged as an export even though we're at the use. + // So check that we are at the declaration. + return symbol.declarations.some(function (d) { return d === parent; }) && ts.isBinaryExpression(grandParent) + ? getSpecialPropertyExport(grandParent, /*useLhsSymbol*/ false) + : undefined; + } + else { + return exportInfo(symbol.exportSymbol, getExportKindForDeclaration(parent)); + } + } + else { + var exportNode = getExportNode(parent, node); + if (exportNode && ts.hasModifier(exportNode, 1 /* Export */)) { + if (ts.isImportEqualsDeclaration(exportNode) && exportNode.moduleReference === node) { + // We're at `Y` in `export import X = Y`. This is not the exported symbol, the left-hand-side is. So treat this as an import statement. + if (comingFromExport) { + return undefined; + } + var lhsSymbol = checker.getSymbolAtLocation(exportNode.name); + return { kind: 0 /* Import */, symbol: lhsSymbol }; + } + else { + return exportInfo(symbol, getExportKindForDeclaration(exportNode)); + } + } + // If we are in `export = a;` or `export default a;`, `parent` is the export assignment. + else if (ts.isExportAssignment(parent)) { + return getExportAssignmentExport(parent); + } + // If we are in `export = class A {};` (or `export = class A {};`) at `A`, `parent.parent` is the export assignment. + else if (ts.isExportAssignment(grandParent)) { + return getExportAssignmentExport(grandParent); + } + // Similar for `module.exports =` and `exports.A =`. + else if (ts.isBinaryExpression(parent)) { + return getSpecialPropertyExport(parent, /*useLhsSymbol*/ true); + } + else if (ts.isBinaryExpression(grandParent)) { + return getSpecialPropertyExport(grandParent, /*useLhsSymbol*/ true); + } + else if (ts.isJSDocTypedefTag(parent)) { + return exportInfo(symbol, 0 /* Named */); + } + } + function getExportAssignmentExport(ex) { + // Get the symbol for the `export =` node; its parent is the module it's the export of. + var exportingModuleSymbol = ts.Debug.assertDefined(ex.symbol.parent, "Expected export symbol to have a parent"); + var exportKind = ex.isExportEquals ? 2 /* ExportEquals */ : 1 /* Default */; + return { kind: 1 /* Export */, symbol: symbol, exportInfo: { exportingModuleSymbol: exportingModuleSymbol, exportKind: exportKind } }; + } + function getSpecialPropertyExport(node, useLhsSymbol) { + var kind; + switch (ts.getAssignmentDeclarationKind(node)) { + case 1 /* ExportsProperty */: + kind = 0 /* Named */; + break; + case 2 /* ModuleExports */: + kind = 2 /* ExportEquals */; + break; + default: + return undefined; + } + var sym = useLhsSymbol ? checker.getSymbolAtLocation(ts.cast(node.left, ts.isPropertyAccessExpression).name) : symbol; + // Better detection for GH#20803 + if (sym && !(checker.getMergedSymbol(sym.parent).flags & 1536 /* Module */)) { + ts.Debug.fail("Special property assignment kind does not have a module as its parent. Assignment is " + ts.Debug.showSymbol(sym) + ", parent is " + ts.Debug.showSymbol(sym.parent)); + } + return sym && exportInfo(sym, kind); + } + } + function getImport() { + var isImport = isNodeImport(node); + if (!isImport) + return undefined; + // A symbol being imported is always an alias. So get what that aliases to find the local symbol. + var importedSymbol = checker.getImmediateAliasedSymbol(symbol); + if (!importedSymbol) + return undefined; + // Search on the local symbol in the exporting module, not the exported symbol. + importedSymbol = skipExportSpecifierSymbol(importedSymbol, checker); + // Similarly, skip past the symbol for 'export =' + if (importedSymbol.escapedName === "export=") { + importedSymbol = getExportEqualsLocalSymbol(importedSymbol, checker); + } + // If the import has a different name than the export, do not continue searching. + // If `importedName` is undefined, do continue searching as the export is anonymous. + // (All imports returned from this function will be ignored anyway if we are in rename and this is a not a named export.) + var importedName = ts.symbolEscapedNameNoDefault(importedSymbol); + if (importedName === undefined || importedName === "default" /* Default */ || importedName === symbol.escapedName) { + return { kind: 0 /* Import */, symbol: importedSymbol }; + } + } + function exportInfo(symbol, kind) { + var exportInfo = getExportInfo(symbol, kind, checker); + return exportInfo && { kind: 1 /* Export */, symbol: symbol, exportInfo: exportInfo }; + } + // Not meant for use with export specifiers or export assignment. + function getExportKindForDeclaration(node) { + return ts.hasModifier(node, 512 /* Default */) ? 1 /* Default */ : 0 /* Named */; + } + } + FindAllReferences.getImportOrExportSymbol = getImportOrExportSymbol; + function getExportEqualsLocalSymbol(importedSymbol, checker) { + if (importedSymbol.flags & 2097152 /* Alias */) { + return ts.Debug.assertDefined(checker.getImmediateAliasedSymbol(importedSymbol)); + } + var decl = importedSymbol.valueDeclaration; + if (ts.isExportAssignment(decl)) { // `export = class {}` + return ts.Debug.assertDefined(decl.expression.symbol); + } + else if (ts.isBinaryExpression(decl)) { // `module.exports = class {}` + return ts.Debug.assertDefined(decl.right.symbol); + } + else if (ts.isSourceFile(decl)) { // json module + return ts.Debug.assertDefined(decl.symbol); + } + return ts.Debug.fail(); + } + // If a reference is a class expression, the exported node would be its parent. + // If a reference is a variable declaration, the exported node would be the variable statement. + function getExportNode(parent, node) { + if (parent.kind === 237 /* VariableDeclaration */) { + var p = parent; + return p.name !== node ? undefined : + p.parent.kind === 274 /* CatchClause */ ? undefined : p.parent.parent.kind === 219 /* VariableStatement */ ? p.parent.parent : undefined; + } + else { + return parent; + } + } + function isNodeImport(node) { + var parent = node.parent; + switch (parent.kind) { + case 248 /* ImportEqualsDeclaration */: + return parent.name === node && isExternalModuleImportEquals(parent); + case 253 /* ImportSpecifier */: + // For a rename import `{ foo as bar }`, don't search for the imported symbol. Just find local uses of `bar`. + return !parent.propertyName; + case 250 /* ImportClause */: + case 251 /* NamespaceImport */: + ts.Debug.assert(parent.name === node); + return true; + default: + return false; + } + } + function getExportInfo(exportSymbol, exportKind, checker) { + var moduleSymbol = exportSymbol.parent; + if (!moduleSymbol) + return undefined; // This can happen if an `export` is not at the top-level (which is a compile error). + var exportingModuleSymbol = checker.getMergedSymbol(moduleSymbol); // Need to get merged symbol in case there's an augmentation. + // `export` may appear in a namespace. In that case, just rely on global search. + return ts.isExternalModuleSymbol(exportingModuleSymbol) ? { exportingModuleSymbol: exportingModuleSymbol, exportKind: exportKind } : undefined; + } + FindAllReferences.getExportInfo = getExportInfo; + /** If at an export specifier, go to the symbol it refers to. */ + function skipExportSpecifierSymbol(symbol, checker) { + // For `export { foo } from './bar", there's nothing to skip, because it does not create a new alias. But `export { foo } does. + if (symbol.declarations) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (ts.isExportSpecifier(declaration) && !declaration.propertyName && !declaration.parent.parent.moduleSpecifier) { + return checker.getExportSpecifierLocalTargetSymbol(declaration); + } + } + } + return symbol; + } + function getContainingModuleSymbol(importer, checker) { + return checker.getMergedSymbol(getSourceFileLikeForImportDeclaration(importer).symbol); + } + function getSourceFileLikeForImportDeclaration(node) { + if (node.kind === 191 /* CallExpression */) { + return node.getSourceFile(); + } + var parent = node.parent; + if (parent.kind === 279 /* SourceFile */) { + return parent; + } + ts.Debug.assert(parent.kind === 245 /* ModuleBlock */); + return ts.cast(parent.parent, isAmbientModuleDeclaration); + } + function isAmbientModuleDeclaration(node) { + return node.kind === 244 /* ModuleDeclaration */ && node.name.kind === 10 /* StringLiteral */; + } + function isExternalModuleImportEquals(eq) { + return eq.moduleReference.kind === 259 /* ExternalModuleReference */ && eq.moduleReference.expression.kind === 10 /* StringLiteral */; + } + })(FindAllReferences = ts.FindAllReferences || (ts.FindAllReferences = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var FindAllReferences; + (function (FindAllReferences) { + var DefinitionKind; + (function (DefinitionKind) { + DefinitionKind[DefinitionKind["Symbol"] = 0] = "Symbol"; + DefinitionKind[DefinitionKind["Label"] = 1] = "Label"; + DefinitionKind[DefinitionKind["Keyword"] = 2] = "Keyword"; + DefinitionKind[DefinitionKind["This"] = 3] = "This"; + DefinitionKind[DefinitionKind["String"] = 4] = "String"; + })(DefinitionKind = FindAllReferences.DefinitionKind || (FindAllReferences.DefinitionKind = {})); + var EntryKind; + (function (EntryKind) { + EntryKind[EntryKind["Span"] = 0] = "Span"; + EntryKind[EntryKind["Node"] = 1] = "Node"; + EntryKind[EntryKind["StringLiteral"] = 2] = "StringLiteral"; + EntryKind[EntryKind["SearchedLocalFoundProperty"] = 3] = "SearchedLocalFoundProperty"; + EntryKind[EntryKind["SearchedPropertyFoundLocal"] = 4] = "SearchedPropertyFoundLocal"; + })(EntryKind = FindAllReferences.EntryKind || (FindAllReferences.EntryKind = {})); + function nodeEntry(node, kind) { + if (kind === void 0) { kind = 1 /* Node */; } + return { kind: kind, node: node.name || node }; + } + FindAllReferences.nodeEntry = nodeEntry; + function findReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position) { + var node = ts.getTouchingPropertyName(sourceFile, position); + var referencedSymbols = FindAllReferences.Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken); + var checker = program.getTypeChecker(); + return !referencedSymbols || !referencedSymbols.length ? undefined : ts.mapDefined(referencedSymbols, function (_a) { + var definition = _a.definition, references = _a.references; + // Only include referenced symbols that have a valid definition. + return definition && { + definition: checker.runWithCancellationToken(cancellationToken, function (checker) { return definitionToReferencedSymbolDefinitionInfo(definition, checker, node); }), + references: references.map(toReferenceEntry) + }; + }); + } + FindAllReferences.findReferencedSymbols = findReferencedSymbols; + function getImplementationsAtPosition(program, cancellationToken, sourceFiles, sourceFile, position) { + var node = ts.getTouchingPropertyName(sourceFile, position); + var referenceEntries = getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node, position); + var checker = program.getTypeChecker(); + return ts.map(referenceEntries, function (entry) { return toImplementationLocation(entry, checker); }); + } + FindAllReferences.getImplementationsAtPosition = getImplementationsAtPosition; + function getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node, position) { + if (node.kind === 279 /* SourceFile */) { + return undefined; + } + var checker = program.getTypeChecker(); + // If invoked directly on a shorthand property assignment, then return + // the declaration of the symbol being assigned (not the symbol being assigned to). + if (node.parent.kind === 276 /* ShorthandPropertyAssignment */) { + var result_1 = []; + FindAllReferences.Core.getReferenceEntriesForShorthandPropertyAssignment(node, checker, function (node) { return result_1.push(nodeEntry(node)); }); + return result_1; + } + else if (node.kind === 98 /* SuperKeyword */ || ts.isSuperProperty(node.parent)) { + // References to and accesses on the super keyword only have one possible implementation, so no + // need to "Find all References" + var symbol = checker.getSymbolAtLocation(node); + return symbol.valueDeclaration && [nodeEntry(symbol.valueDeclaration)]; + } + else { + // Perform "Find all References" and retrieve only those that are implementations + return getReferenceEntriesForNode(position, node, program, sourceFiles, cancellationToken, { implementations: true }); + } + } + function findReferenceOrRenameEntries(program, cancellationToken, sourceFiles, node, position, options, convertEntry) { + return ts.map(flattenEntries(FindAllReferences.Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options)), function (entry) { return convertEntry(entry, node, program.getTypeChecker()); }); + } + FindAllReferences.findReferenceOrRenameEntries = findReferenceOrRenameEntries; + function getReferenceEntriesForNode(position, node, program, sourceFiles, cancellationToken, options, sourceFilesSet) { + if (options === void 0) { options = {}; } + if (sourceFilesSet === void 0) { sourceFilesSet = ts.arrayToSet(sourceFiles, function (f) { return f.fileName; }); } + return flattenEntries(FindAllReferences.Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options, sourceFilesSet)); + } + FindAllReferences.getReferenceEntriesForNode = getReferenceEntriesForNode; + function flattenEntries(referenceSymbols) { + return referenceSymbols && ts.flatMap(referenceSymbols, function (r) { return r.references; }); + } + function definitionToReferencedSymbolDefinitionInfo(def, checker, originalNode) { + var info = (function () { + switch (def.type) { + case 0 /* Symbol */: { + var symbol = def.symbol; + var _a = getDefinitionKindAndDisplayParts(symbol, checker, originalNode), displayParts_1 = _a.displayParts, kind_1 = _a.kind; + var name_1 = displayParts_1.map(function (p) { return p.text; }).join(""); + return { node: symbol.declarations ? ts.getNameOfDeclaration(ts.first(symbol.declarations)) || ts.first(symbol.declarations) : originalNode, name: name_1, kind: kind_1, displayParts: displayParts_1 }; + } + case 1 /* Label */: { + var node_1 = def.node; + return { node: node_1, name: node_1.text, kind: "label" /* label */, displayParts: [ts.displayPart(node_1.text, ts.SymbolDisplayPartKind.text)] }; + } + case 2 /* Keyword */: { + var node_2 = def.node; + var name_2 = ts.tokenToString(node_2.kind); + return { node: node_2, name: name_2, kind: "keyword" /* keyword */, displayParts: [{ text: name_2, kind: "keyword" /* keyword */ }] }; + } + case 3 /* This */: { + var node_3 = def.node; + var symbol = checker.getSymbolAtLocation(node_3); + var displayParts_2 = symbol && ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, node_3.getSourceFile(), ts.getContainerNode(node_3), node_3).displayParts || [ts.textPart("this")]; + return { node: node_3, name: "this", kind: "var" /* variableElement */, displayParts: displayParts_2 }; + } + case 4 /* String */: { + var node_4 = def.node; + return { node: node_4, name: node_4.text, kind: "var" /* variableElement */, displayParts: [ts.displayPart(ts.getTextOfNode(node_4), ts.SymbolDisplayPartKind.stringLiteral)] }; + } + default: + return ts.Debug.assertNever(def); + } + })(); + var node = info.node, name = info.name, kind = info.kind, displayParts = info.displayParts; + var sourceFile = node.getSourceFile(); + return { containerKind: "" /* unknown */, containerName: "", fileName: sourceFile.fileName, kind: kind, name: name, textSpan: getTextSpan(ts.isComputedPropertyName(node) ? node.expression : node, sourceFile), displayParts: displayParts }; + } + function getDefinitionKindAndDisplayParts(symbol, checker, node) { + var meaning = FindAllReferences.Core.getIntersectingMeaningFromDeclarations(node, symbol); + var enclosingDeclaration = symbol.declarations && ts.firstOrUndefined(symbol.declarations) || node; + var _a = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, enclosingDeclaration.getSourceFile(), enclosingDeclaration, enclosingDeclaration, meaning), displayParts = _a.displayParts, symbolKind = _a.symbolKind; + return { displayParts: displayParts, kind: symbolKind }; + } + function toRenameLocation(entry, originalNode, checker) { + return __assign({}, entryToDocumentSpan(entry), getPrefixAndSuffixText(entry, originalNode, checker)); + } + FindAllReferences.toRenameLocation = toRenameLocation; + function toReferenceEntry(entry) { + var _a = entryToDocumentSpan(entry), textSpan = _a.textSpan, fileName = _a.fileName; + if (entry.kind === 0 /* Span */) { + return { textSpan: textSpan, fileName: fileName, isWriteAccess: false, isDefinition: false }; + } + var kind = entry.kind, node = entry.node; + return { + textSpan: textSpan, + fileName: fileName, + isWriteAccess: isWriteAccessForReference(node), + isDefinition: node.kind === 80 /* DefaultKeyword */ + || !!ts.getDeclarationFromName(node) + || ts.isLiteralComputedPropertyDeclarationName(node), + isInString: kind === 2 /* StringLiteral */ ? true : undefined, + }; + } + FindAllReferences.toReferenceEntry = toReferenceEntry; + function entryToDocumentSpan(entry) { + if (entry.kind === 0 /* Span */) { + return { textSpan: entry.textSpan, fileName: entry.fileName }; + } + else { + var sourceFile = entry.node.getSourceFile(); + return { textSpan: getTextSpan(entry.node, sourceFile), fileName: sourceFile.fileName }; + } + } + function getPrefixAndSuffixText(entry, originalNode, checker) { + if (entry.kind !== 0 /* Span */ && ts.isIdentifier(originalNode)) { + var node = entry.node, kind = entry.kind; + var name = originalNode.text; + var isShorthandAssignment = ts.isShorthandPropertyAssignment(node.parent); + if (isShorthandAssignment || ts.isObjectBindingElementWithoutPropertyName(node.parent)) { + var prefixColon = { prefixText: name + ": " }; + var suffixColon = { suffixText: ": " + name }; + return kind === 3 /* SearchedLocalFoundProperty */ ? prefixColon + : kind === 4 /* SearchedPropertyFoundLocal */ ? suffixColon + // In `const o = { x }; o.x`, symbolAtLocation at `x` in `{ x }` is the property symbol. + // For a binding element `const { x } = o;`, symbolAtLocation at `x` is the property symbol. + : isShorthandAssignment ? suffixColon : prefixColon; + } + else if (ts.isImportSpecifier(entry.node.parent) && !entry.node.parent.propertyName) { + // If the original symbol was using this alias, just rename the alias. + var originalSymbol = ts.isExportSpecifier(originalNode.parent) ? checker.getExportSpecifierLocalTargetSymbol(originalNode.parent) : checker.getSymbolAtLocation(originalNode); + return ts.contains(originalSymbol.declarations, entry.node.parent) ? { prefixText: name + " as " } : ts.emptyOptions; + } + else if (ts.isExportSpecifier(entry.node.parent) && !entry.node.parent.propertyName) { + return originalNode === entry.node ? { prefixText: name + " as " } : { suffixText: " as " + name }; + } + } + return ts.emptyOptions; + } + function toImplementationLocation(entry, checker) { + if (entry.kind !== 0 /* Span */) { + var node = entry.node; + var sourceFile = node.getSourceFile(); + return __assign({ textSpan: getTextSpan(node, sourceFile), fileName: sourceFile.fileName }, implementationKindDisplayParts(node, checker)); + } + else { + var textSpan = entry.textSpan, fileName = entry.fileName; + return { textSpan: textSpan, fileName: fileName, kind: "" /* unknown */, displayParts: [] }; + } + } + function implementationKindDisplayParts(node, checker) { + var symbol = checker.getSymbolAtLocation(ts.isDeclaration(node) && node.name ? node.name : node); + if (symbol) { + return getDefinitionKindAndDisplayParts(symbol, checker, node); + } + else if (node.kind === 188 /* ObjectLiteralExpression */) { + return { + kind: "interface" /* interfaceElement */, + displayParts: [ts.punctuationPart(20 /* OpenParenToken */), ts.textPart("object literal"), ts.punctuationPart(21 /* CloseParenToken */)] + }; + } + else if (node.kind === 209 /* ClassExpression */) { + return { + kind: "local class" /* localClassElement */, + displayParts: [ts.punctuationPart(20 /* OpenParenToken */), ts.textPart("anonymous local class"), ts.punctuationPart(21 /* CloseParenToken */)] + }; + } + else { + return { kind: ts.getNodeKind(node), displayParts: [] }; + } + } + function toHighlightSpan(entry) { + if (entry.kind === 0 /* Span */) { + var fileName = entry.fileName, textSpan = entry.textSpan; + return { fileName: fileName, span: { textSpan: textSpan, kind: "reference" /* reference */ } }; + } + var node = entry.node, kind = entry.kind; + var sourceFile = node.getSourceFile(); + var writeAccess = isWriteAccessForReference(node); + var span = { + textSpan: getTextSpan(node, sourceFile), + kind: writeAccess ? "writtenReference" /* writtenReference */ : "reference" /* reference */, + isInString: kind === 2 /* StringLiteral */ ? true : undefined, + }; + return { fileName: sourceFile.fileName, span: span }; + } + FindAllReferences.toHighlightSpan = toHighlightSpan; + function getTextSpan(node, sourceFile) { + var start = node.getStart(sourceFile); + var end = node.getEnd(); + if (node.kind === 10 /* StringLiteral */) { + start += 1; + end -= 1; + } + return ts.createTextSpanFromBounds(start, end); + } + /** A node is considered a writeAccess iff it is a name of a declaration or a target of an assignment */ + function isWriteAccessForReference(node) { + var decl = ts.getDeclarationFromName(node); + return !!decl && declarationIsWriteAccess(decl) || node.kind === 80 /* DefaultKeyword */ || ts.isWriteAccess(node); + } + /** + * True if 'decl' provides a value, as in `function f() {}`; + * false if 'decl' is just a location for a future write, as in 'let x;' + */ + function declarationIsWriteAccess(decl) { + // Consider anything in an ambient declaration to be a write access since it may be coming from JS. + if (!!(decl.flags & 4194304 /* Ambient */)) + return true; + switch (decl.kind) { + case 204 /* BinaryExpression */: + case 186 /* BindingElement */: + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 80 /* DefaultKeyword */: + case 243 /* EnumDeclaration */: + case 278 /* EnumMember */: + case 257 /* ExportSpecifier */: + case 250 /* ImportClause */: // default import + case 248 /* ImportEqualsDeclaration */: + case 253 /* ImportSpecifier */: + case 241 /* InterfaceDeclaration */: + case 297 /* JSDocCallbackTag */: + case 304 /* JSDocTypedefTag */: + case 267 /* JsxAttribute */: + case 244 /* ModuleDeclaration */: + case 247 /* NamespaceExportDeclaration */: + case 251 /* NamespaceImport */: + case 151 /* Parameter */: + case 276 /* ShorthandPropertyAssignment */: + case 242 /* TypeAliasDeclaration */: + case 150 /* TypeParameter */: + return true; + case 275 /* PropertyAssignment */: + // In `({ x: y } = 0);`, `x` is not a write access. (Won't call this function for `y`.) + return !ts.isArrayLiteralOrObjectLiteralDestructuringPattern(decl.parent); + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 157 /* Constructor */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + return !!decl.body; + case 237 /* VariableDeclaration */: + case 154 /* PropertyDeclaration */: + return !!decl.initializer || ts.isCatchClause(decl.parent); + case 155 /* MethodSignature */: + case 153 /* PropertySignature */: + case 305 /* JSDocPropertyTag */: + case 299 /* JSDocParameterTag */: + return false; + default: + return ts.Debug.failBadSyntaxKind(decl); + } + } + })(FindAllReferences = ts.FindAllReferences || (ts.FindAllReferences = {})); +})(ts || (ts = {})); +/** Encapsulates the core find-all-references algorithm. */ +/* @internal */ +(function (ts) { + var FindAllReferences; + (function (FindAllReferences) { + var Core; + (function (Core) { + /** Core find-all-references algorithm. Handles special cases before delegating to `getReferencedSymbolsForSymbol`. */ + function getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options, sourceFilesSet) { + if (options === void 0) { options = {}; } + if (sourceFilesSet === void 0) { sourceFilesSet = ts.arrayToSet(sourceFiles, function (f) { return f.fileName; }); } + if (ts.isSourceFile(node)) { + var reference = ts.GoToDefinition.getReferenceAtPosition(node, position, program); + var moduleSymbol = reference && program.getTypeChecker().getMergedSymbol(reference.file.symbol); + return moduleSymbol && getReferencedSymbolsForModule(program, moduleSymbol, /*excludeImportTypeOfExportEquals*/ false, sourceFiles, sourceFilesSet); + } + if (!options.implementations) { + var special = getReferencedSymbolsSpecial(node, sourceFiles, cancellationToken); + if (special) { + return special; + } + } + var checker = program.getTypeChecker(); + var symbol = checker.getSymbolAtLocation(node); + // Could not find a symbol e.g. unknown identifier + if (!symbol) { + // String literal might be a property (and thus have a symbol), so do this here rather than in getReferencedSymbolsSpecial. + return !options.implementations && ts.isStringLiteral(node) ? getReferencesForStringLiteral(node, sourceFiles, cancellationToken) : undefined; + } + if (symbol.escapedName === "export=" /* ExportEquals */) { + return getReferencedSymbolsForModule(program, symbol.parent, /*excludeImportTypeOfExportEquals*/ false, sourceFiles, sourceFilesSet); + } + var moduleReferences = ts.emptyArray; + var moduleSourceFile = isModuleSymbol(symbol); + var referencedNode = node; + if (moduleSourceFile) { + var exportEquals = symbol.exports.get("export=" /* ExportEquals */); + // If !!exportEquals, we're about to add references to `import("mod")` anyway, so don't double-count them. + moduleReferences = getReferencedSymbolsForModule(program, symbol, !!exportEquals, sourceFiles, sourceFilesSet); + if (!exportEquals || !sourceFilesSet.has(moduleSourceFile.fileName)) + return moduleReferences; + // Continue to get references to 'export ='. + symbol = ts.skipAlias(exportEquals, checker); + referencedNode = undefined; + } + return ts.concatenate(moduleReferences, getReferencedSymbolsForSymbol(symbol, referencedNode, sourceFiles, sourceFilesSet, checker, cancellationToken, options)); + } + Core.getReferencedSymbolsForNode = getReferencedSymbolsForNode; + function isModuleSymbol(symbol) { + return symbol.flags & 1536 /* Module */ ? ts.find(symbol.declarations, ts.isSourceFile) : undefined; + } + function getReferencedSymbolsForModule(program, symbol, excludeImportTypeOfExportEquals, sourceFiles, sourceFilesSet) { + ts.Debug.assert(!!symbol.valueDeclaration); + var references = ts.mapDefined(FindAllReferences.findModuleReferences(program, sourceFiles, symbol), function (reference) { + if (reference.kind === "import") { + var parent = reference.literal.parent; + if (ts.isLiteralTypeNode(parent)) { + var importType = ts.cast(parent.parent, ts.isImportTypeNode); + if (excludeImportTypeOfExportEquals && !importType.qualifier) { + return undefined; + } + } + // import("foo") with no qualifier will reference the `export =` of the module, which may be referenced anyway. + return FindAllReferences.nodeEntry(reference.literal); + } + else { + return { + kind: 0 /* Span */, + fileName: reference.referencingFile.fileName, + textSpan: ts.createTextSpanFromRange(reference.ref), + }; + } + }); + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + switch (decl.kind) { + case 279 /* SourceFile */: + // Don't include the source file itself. (This may not be ideal behavior, but awkward to include an entire file as a reference.) + break; + case 244 /* ModuleDeclaration */: + if (sourceFilesSet.has(decl.getSourceFile().fileName)) { + references.push(FindAllReferences.nodeEntry(decl.name)); + } + break; + default: + // This may be merged with something. + ts.Debug.fail("Expected a module symbol to be declared by a SourceFile or ModuleDeclaration."); + } + } + var exported = symbol.exports.get("export=" /* ExportEquals */); + if (exported) { + for (var _b = 0, _c = exported.declarations; _b < _c.length; _b++) { + var decl = _c[_b]; + var sourceFile = decl.getSourceFile(); + if (sourceFilesSet.has(sourceFile.fileName)) { + // At `module.exports = ...`, reference node is `module` + var node = ts.isBinaryExpression(decl) && ts.isPropertyAccessExpression(decl.left) + ? decl.left.expression + : ts.isExportAssignment(decl) + ? ts.Debug.assertDefined(ts.findChildOfKind(decl, 85 /* ExportKeyword */, sourceFile)) + : ts.getNameOfDeclaration(decl) || decl; + references.push(FindAllReferences.nodeEntry(node)); + } + } + } + return references.length ? [{ definition: { type: 0 /* Symbol */, symbol: symbol }, references: references }] : ts.emptyArray; + } + /** getReferencedSymbols for special node kinds. */ + function getReferencedSymbolsSpecial(node, sourceFiles, cancellationToken) { + if (ts.isTypeKeyword(node.kind)) { + return getAllReferencesForKeyword(sourceFiles, node.kind, cancellationToken); + } + // Labels + if (ts.isJumpStatementTarget(node)) { + var labelDefinition = ts.getTargetLabel(node.parent, node.text); + // if we have a label definition, look within its statement for references, if not, then + // the label is undefined and we have no results.. + return labelDefinition && getLabelReferencesInNode(labelDefinition.parent, labelDefinition); + } + else if (ts.isLabelOfLabeledStatement(node)) { + // it is a label definition and not a target, search within the parent labeledStatement + return getLabelReferencesInNode(node.parent, node); + } + if (ts.isThis(node)) { + return getReferencesForThisKeyword(node, sourceFiles, cancellationToken); + } + if (node.kind === 98 /* SuperKeyword */) { + return getReferencesForSuperKeyword(node); + } + return undefined; + } + /** Core find-all-references algorithm for a normal symbol. */ + function getReferencedSymbolsForSymbol(originalSymbol, node, sourceFiles, sourceFilesSet, checker, cancellationToken, options) { + var symbol = node && skipPastExportOrImportSpecifierOrUnion(originalSymbol, node, checker, !!options.isForRename) || originalSymbol; + // Compute the meaning from the location and the symbol it references + var searchMeaning = node ? getIntersectingMeaningFromDeclarations(node, symbol) : 7 /* All */; + var result = []; + var state = new State(sourceFiles, sourceFilesSet, node ? getSpecialSearchKind(node) : 0 /* None */, checker, cancellationToken, searchMeaning, options, result); + var exportSpecifier = !options.isForRename ? undefined : ts.find(symbol.declarations, ts.isExportSpecifier); + if (exportSpecifier) { + // When renaming at an export specifier, rename the export and not the thing being exported. + getReferencesAtExportSpecifier(exportSpecifier.name, symbol, exportSpecifier, state.createSearch(node, originalSymbol, /*comingFrom*/ undefined), state, /*addReferencesHere*/ true, /*alwaysGetReferences*/ true); + } + else if (node && node.kind === 80 /* DefaultKeyword */) { + addReference(node, symbol, state); + searchForImportsOfExport(node, symbol, { exportingModuleSymbol: ts.Debug.assertDefined(symbol.parent, "Expected export symbol to have a parent"), exportKind: 1 /* Default */ }, state); + } + else { + var search = state.createSearch(node, symbol, /*comingFrom*/ undefined, { allSearchSymbols: node ? populateSearchSymbolSet(symbol, node, checker, !!options.isForRename, !!options.implementations) : [symbol] }); + // Try to get the smallest valid scope that we can limit our search to; + // otherwise we'll need to search globally (i.e. include each file). + var scope = getSymbolScope(symbol); + if (scope) { + getReferencesInContainer(scope, scope.getSourceFile(), search, state, /*addReferencesHere*/ !(ts.isSourceFile(scope) && !ts.contains(sourceFiles, scope))); + } + else { + // Global search + for (var _i = 0, _a = state.sourceFiles; _i < _a.length; _i++) { + var sourceFile = _a[_i]; + state.cancellationToken.throwIfCancellationRequested(); + searchForName(sourceFile, search, state); + } + } + } + return result; + } + function getSpecialSearchKind(node) { + switch (node.kind) { + case 124 /* ConstructorKeyword */: + return 1 /* Constructor */; + case 72 /* Identifier */: + if (ts.isClassLike(node.parent)) { + ts.Debug.assert(node.parent.name === node); + return 2 /* Class */; + } + // falls through + default: + return 0 /* None */; + } + } + /** Handle a few special cases relating to export/import specifiers. */ + function skipPastExportOrImportSpecifierOrUnion(symbol, node, checker, isForRename) { + var parent = node.parent; + if (ts.isExportSpecifier(parent) && !isForRename) { + return getLocalSymbolForExportSpecifier(node, symbol, parent, checker); + } + // If the symbol is declared as part of a declaration like `{ type: "a" } | { type: "b" }`, use the property on the union type to get more references. + return ts.firstDefined(symbol.declarations, function (decl) { + if (!decl.parent) { + // Assertions for GH#21814. We should be handling SourceFile symbols in `getReferencedSymbolsForModule` instead of getting here. + ts.Debug.fail("Unexpected symbol at " + ts.Debug.showSyntaxKind(node) + ": " + ts.Debug.showSymbol(symbol)); + } + return ts.isTypeLiteralNode(decl.parent) && ts.isUnionTypeNode(decl.parent.parent) + ? checker.getPropertyOfType(checker.getTypeFromTypeNode(decl.parent.parent), symbol.name) + : undefined; + }); + } + var SpecialSearchKind; + (function (SpecialSearchKind) { + SpecialSearchKind[SpecialSearchKind["None"] = 0] = "None"; + SpecialSearchKind[SpecialSearchKind["Constructor"] = 1] = "Constructor"; + SpecialSearchKind[SpecialSearchKind["Class"] = 2] = "Class"; + })(SpecialSearchKind || (SpecialSearchKind = {})); + /** + * Holds all state needed for the finding references. + * Unlike `Search`, there is only one `State`. + */ + var State = /** @class */ (function () { + function State(sourceFiles, sourceFilesSet, + /** True if we're searching for constructor references. */ + specialSearchKind, checker, cancellationToken, searchMeaning, options, result) { + this.sourceFiles = sourceFiles; + this.sourceFilesSet = sourceFilesSet; + this.specialSearchKind = specialSearchKind; + this.checker = checker; + this.cancellationToken = cancellationToken; + this.searchMeaning = searchMeaning; + this.options = options; + this.result = result; + /** Cache for `explicitlyinheritsFrom`. */ + this.inheritsFromCache = ts.createMap(); + /** + * Type nodes can contain multiple references to the same type. For example: + * let x: Foo & (Foo & Bar) = ... + * Because we are returning the implementation locations and not the identifier locations, + * duplicate entries would be returned here as each of the type references is part of + * the same implementation. For that reason, check before we add a new entry. + */ + this.markSeenContainingTypeReference = ts.nodeSeenTracker(); + /** + * It's possible that we will encounter the right side of `export { foo as bar } from "x";` more than once. + * For example: + * // b.ts + * export { foo as bar } from "./a"; + * import { bar } from "./b"; + * + * Normally at `foo as bar` we directly add `foo` and do not locally search for it (since it doesn't declare a local). + * But another reference to it may appear in the same source file. + * See `tests/cases/fourslash/transitiveExportImports3.ts`. + */ + this.markSeenReExportRHS = ts.nodeSeenTracker(); + this.symbolIdToReferences = []; + // Source file ID → symbol ID → Whether the symbol has been searched for in the source file. + this.sourceFileToSeenSymbols = []; + } + State.prototype.includesSourceFile = function (sourceFile) { + return this.sourceFilesSet.has(sourceFile.fileName); + }; + /** Gets every place to look for references of an exported symbols. See `ImportsResult` in `importTracker.ts` for more documentation. */ + State.prototype.getImportSearches = function (exportSymbol, exportInfo) { + if (!this.importTracker) + this.importTracker = FindAllReferences.createImportTracker(this.sourceFiles, this.sourceFilesSet, this.checker, this.cancellationToken); + return this.importTracker(exportSymbol, exportInfo, !!this.options.isForRename); + }; + /** @param allSearchSymbols set of additional symbols for use by `includes`. */ + State.prototype.createSearch = function (location, symbol, comingFrom, searchOptions) { + if (searchOptions === void 0) { searchOptions = {}; } + // Note: if this is an external module symbol, the name doesn't include quotes. + // Note: getLocalSymbolForExportDefault handles `export default class C {}`, but not `export default C` or `export { C as default }`. + // The other two forms seem to be handled downstream (e.g. in `skipPastExportOrImportSpecifier`), so special-casing the first form + // here appears to be intentional). + var _a = searchOptions.text, text = _a === void 0 ? ts.stripQuotes(ts.unescapeLeadingUnderscores((ts.getLocalSymbolForExportDefault(symbol) || symbol).escapedName)) : _a, _b = searchOptions.allSearchSymbols, allSearchSymbols = _b === void 0 ? [symbol] : _b; + var escapedText = ts.escapeLeadingUnderscores(text); + var parents = this.options.implementations && location ? getParentSymbolsOfPropertyAccess(location, symbol, this.checker) : undefined; + return { symbol: symbol, comingFrom: comingFrom, text: text, escapedText: escapedText, parents: parents, allSearchSymbols: allSearchSymbols, includes: function (sym) { return ts.contains(allSearchSymbols, sym); } }; + }; + /** + * Callback to add references for a particular searched symbol. + * This initializes a reference group, so only call this if you will add at least one reference. + */ + State.prototype.referenceAdder = function (searchSymbol) { + var symbolId = ts.getSymbolId(searchSymbol); + var references = this.symbolIdToReferences[symbolId]; + if (!references) { + references = this.symbolIdToReferences[symbolId] = []; + this.result.push({ definition: { type: 0 /* Symbol */, symbol: searchSymbol }, references: references }); + } + return function (node, kind) { return references.push(FindAllReferences.nodeEntry(node, kind)); }; + }; + /** Add a reference with no associated definition. */ + State.prototype.addStringOrCommentReference = function (fileName, textSpan) { + this.result.push({ + definition: undefined, + references: [{ kind: 0 /* Span */, fileName: fileName, textSpan: textSpan }] + }); + }; + /** Returns `true` the first time we search for a symbol in a file and `false` afterwards. */ + State.prototype.markSearchedSymbols = function (sourceFile, symbols) { + var sourceId = ts.getNodeId(sourceFile); + var seenSymbols = this.sourceFileToSeenSymbols[sourceId] || (this.sourceFileToSeenSymbols[sourceId] = ts.createMap()); + var anyNewSymbols = false; + for (var _i = 0, symbols_2 = symbols; _i < symbols_2.length; _i++) { + var sym = symbols_2[_i]; + anyNewSymbols = ts.addToSeen(seenSymbols, ts.getSymbolId(sym)) || anyNewSymbols; + } + return anyNewSymbols; + }; + return State; + }()); + /** Search for all imports of a given exported symbol using `State.getImportSearches`. */ + function searchForImportsOfExport(exportLocation, exportSymbol, exportInfo, state) { + var _a = state.getImportSearches(exportSymbol, exportInfo), importSearches = _a.importSearches, singleReferences = _a.singleReferences, indirectUsers = _a.indirectUsers; + // For `import { foo as bar }` just add the reference to `foo`, and don't otherwise search in the file. + if (singleReferences.length) { + var addRef = state.referenceAdder(exportSymbol); + for (var _i = 0, singleReferences_1 = singleReferences; _i < singleReferences_1.length; _i++) { + var singleRef = singleReferences_1[_i]; + if (shouldAddSingleReference(singleRef, state)) + addRef(singleRef); + } + } + // For each import, find all references to that import in its source file. + for (var _b = 0, importSearches_1 = importSearches; _b < importSearches_1.length; _b++) { + var _c = importSearches_1[_b], importLocation = _c[0], importSymbol = _c[1]; + getReferencesInSourceFile(importLocation.getSourceFile(), state.createSearch(importLocation, importSymbol, 1 /* Export */), state); + } + if (indirectUsers.length) { + var indirectSearch = void 0; + switch (exportInfo.exportKind) { + case 0 /* Named */: + indirectSearch = state.createSearch(exportLocation, exportSymbol, 1 /* Export */); + break; + case 1 /* Default */: + // Search for a property access to '.default'. This can't be renamed. + indirectSearch = state.options.isForRename ? undefined : state.createSearch(exportLocation, exportSymbol, 1 /* Export */, { text: "default" }); + break; + case 2 /* ExportEquals */: + break; + } + if (indirectSearch) { + for (var _d = 0, indirectUsers_1 = indirectUsers; _d < indirectUsers_1.length; _d++) { + var indirectUser = indirectUsers_1[_d]; + searchForName(indirectUser, indirectSearch, state); + } + } + } + } + function eachExportReference(sourceFiles, checker, cancellationToken, exportSymbol, exportingModuleSymbol, exportName, isDefaultExport, cb) { + var importTracker = FindAllReferences.createImportTracker(sourceFiles, ts.arrayToSet(sourceFiles, function (f) { return f.fileName; }), checker, cancellationToken); + var _a = importTracker(exportSymbol, { exportKind: isDefaultExport ? 1 /* Default */ : 0 /* Named */, exportingModuleSymbol: exportingModuleSymbol }, /*isForRename*/ false), importSearches = _a.importSearches, indirectUsers = _a.indirectUsers; + for (var _i = 0, importSearches_2 = importSearches; _i < importSearches_2.length; _i++) { + var importLocation = importSearches_2[_i][0]; + cb(importLocation); + } + for (var _b = 0, indirectUsers_2 = indirectUsers; _b < indirectUsers_2.length; _b++) { + var indirectUser = indirectUsers_2[_b]; + for (var _c = 0, _d = getPossibleSymbolReferenceNodes(indirectUser, isDefaultExport ? "default" : exportName); _c < _d.length; _c++) { + var node = _d[_c]; + // Import specifiers should be handled by importSearches + if (ts.isIdentifier(node) && !ts.isImportOrExportSpecifier(node.parent) && checker.getSymbolAtLocation(node) === exportSymbol) { + cb(node); + } + } + } + } + Core.eachExportReference = eachExportReference; + function shouldAddSingleReference(singleRef, state) { + if (!hasMatchingMeaning(singleRef, state)) + return false; + if (!state.options.isForRename) + return true; + // Don't rename an import type `import("./module-name")` when renaming `name` in `export = name;` + if (!ts.isIdentifier(singleRef)) + return false; + // At `default` in `import { default as x }` or `export { default as x }`, do add a reference, but do not rename. + return !(ts.isImportOrExportSpecifier(singleRef.parent) && singleRef.escapedText === "default" /* Default */); + } + // Go to the symbol we imported from and find references for it. + function searchForImportedSymbol(symbol, state) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + var exportingFile = declaration.getSourceFile(); + // Need to search in the file even if it's not in the search-file set, because it might export the symbol. + getReferencesInSourceFile(exportingFile, state.createSearch(declaration, symbol, 0 /* Import */), state, state.includesSourceFile(exportingFile)); + } + } + /** Search for all occurences of an identifier in a source file (and filter out the ones that match). */ + function searchForName(sourceFile, search, state) { + if (ts.getNameTable(sourceFile).get(search.escapedText) !== undefined) { + getReferencesInSourceFile(sourceFile, search, state); + } + } + function getPropertySymbolOfDestructuringAssignment(location, checker) { + return ts.isArrayLiteralOrObjectLiteralDestructuringPattern(location.parent.parent) + ? checker.getPropertySymbolOfDestructuringAssignment(location) + : undefined; + } + /** + * Determines the smallest scope in which a symbol may have named references. + * Note that not every construct has been accounted for. This function can + * probably be improved. + * + * @returns undefined if the scope cannot be determined, implying that + * a reference to a symbol can occur anywhere. + */ + function getSymbolScope(symbol) { + // If this is the symbol of a named function expression or named class expression, + // then named references are limited to its own scope. + var declarations = symbol.declarations, flags = symbol.flags, parent = symbol.parent, valueDeclaration = symbol.valueDeclaration; + if (valueDeclaration && (valueDeclaration.kind === 196 /* FunctionExpression */ || valueDeclaration.kind === 209 /* ClassExpression */)) { + return valueDeclaration; + } + if (!declarations) { + return undefined; + } + // If this is private property or method, the scope is the containing class + if (flags & (4 /* Property */ | 8192 /* Method */)) { + var privateDeclaration = ts.find(declarations, function (d) { return ts.hasModifier(d, 8 /* Private */); }); + if (privateDeclaration) { + return ts.getAncestor(privateDeclaration, 240 /* ClassDeclaration */); + } + // Else this is a public property and could be accessed from anywhere. + return undefined; + } + // If symbol is of object binding pattern element without property name we would want to + // look for property too and that could be anywhere + if (declarations.some(ts.isObjectBindingElementWithoutPropertyName)) { + return undefined; + } + /* + If the symbol has a parent, it's globally visible unless: + - It's a private property (handled above). + - It's a type parameter. + - The parent is an external module: then we should only search in the module (and recurse on the export later). + - But if the parent has `export as namespace`, the symbol is globally visible through that namespace. + */ + var exposedByParent = parent && !(symbol.flags & 262144 /* TypeParameter */); + if (exposedByParent && !(ts.isExternalModuleSymbol(parent) && !parent.globalExports)) { + return undefined; + } + var scope; + for (var _i = 0, declarations_1 = declarations; _i < declarations_1.length; _i++) { + var declaration = declarations_1[_i]; + var container = ts.getContainerNode(declaration); + if (scope && scope !== container) { + // Different declarations have different containers, bail out + return undefined; + } + if (!container || container.kind === 279 /* SourceFile */ && !ts.isExternalOrCommonJsModule(container)) { + // This is a global variable and not an external module, any declaration defined + // within this scope is visible outside the file + return undefined; + } + // The search scope is the container node + scope = container; + } + // If symbol.parent, this means we are in an export of an external module. (Otherwise we would have returned `undefined` above.) + // For an export of a module, we may be in a declaration file, and it may be accessed elsewhere. E.g.: + // declare module "a" { export type T = number; } + // declare module "b" { import { T } from "a"; export const x: T; } + // So we must search the whole source file. (Because we will mark the source file as seen, we we won't return to it when searching for imports.) + return exposedByParent ? scope.getSourceFile() : scope; // TODO: GH#18217 + } + /** Used as a quick check for whether a symbol is used at all in a file (besides its definition). */ + function isSymbolReferencedInFile(definition, checker, sourceFile) { + return eachSymbolReferenceInFile(definition, checker, sourceFile, function () { return true; }) || false; + } + Core.isSymbolReferencedInFile = isSymbolReferencedInFile; + function eachSymbolReferenceInFile(definition, checker, sourceFile, cb) { + var symbol = ts.isParameterPropertyDeclaration(definition.parent) + ? ts.first(checker.getSymbolsOfParameterPropertyDeclaration(definition.parent, definition.text)) + : checker.getSymbolAtLocation(definition); + if (!symbol) + return undefined; + for (var _i = 0, _a = getPossibleSymbolReferenceNodes(sourceFile, symbol.name); _i < _a.length; _i++) { + var token = _a[_i]; + if (!ts.isIdentifier(token) || token === definition || token.escapedText !== definition.escapedText) + continue; + var referenceSymbol = checker.getSymbolAtLocation(token); // See GH#19955 for why the type annotation is necessary + if (referenceSymbol === symbol + || checker.getShorthandAssignmentValueSymbol(token.parent) === symbol + || ts.isExportSpecifier(token.parent) && getLocalSymbolForExportSpecifier(token, referenceSymbol, token.parent, checker) === symbol) { + var res = cb(token); + if (res) + return res; + } + } + } + Core.eachSymbolReferenceInFile = eachSymbolReferenceInFile; + function eachSignatureCall(signature, sourceFiles, checker, cb) { + if (!signature.name || !ts.isIdentifier(signature.name)) + return; + var symbol = ts.Debug.assertDefined(checker.getSymbolAtLocation(signature.name)); + for (var _i = 0, sourceFiles_3 = sourceFiles; _i < sourceFiles_3.length; _i++) { + var sourceFile = sourceFiles_3[_i]; + for (var _a = 0, _b = getPossibleSymbolReferenceNodes(sourceFile, symbol.name); _a < _b.length; _a++) { + var name = _b[_a]; + if (!ts.isIdentifier(name) || name === signature.name || name.escapedText !== signature.name.escapedText) + continue; + var called = ts.climbPastPropertyAccess(name); + var call = called.parent; + if (!ts.isCallExpression(call) || call.expression !== called) + continue; + var referenceSymbol = checker.getSymbolAtLocation(name); + if (referenceSymbol && checker.getRootSymbols(referenceSymbol).some(function (s) { return s === symbol; })) { + cb(call); + } + } + } + } + Core.eachSignatureCall = eachSignatureCall; + function getPossibleSymbolReferenceNodes(sourceFile, symbolName, container) { + if (container === void 0) { container = sourceFile; } + return getPossibleSymbolReferencePositions(sourceFile, symbolName, container).map(function (pos) { return ts.getTouchingPropertyName(sourceFile, pos); }); + } + function getPossibleSymbolReferencePositions(sourceFile, symbolName, container) { + if (container === void 0) { container = sourceFile; } + var positions = []; + /// TODO: Cache symbol existence for files to save text search + // Also, need to make this work for unicode escapes. + // Be resilient in the face of a symbol with no name or zero length name + if (!symbolName || !symbolName.length) { + return positions; + } + var text = sourceFile.text; + var sourceLength = text.length; + var symbolNameLength = symbolName.length; + var position = text.indexOf(symbolName, container.pos); + while (position >= 0) { + // If we are past the end, stop looking + if (position > container.end) + break; + // We found a match. Make sure it's not part of a larger word (i.e. the char + // before and after it have to be a non-identifier char). + var endPosition = position + symbolNameLength; + if ((position === 0 || !ts.isIdentifierPart(text.charCodeAt(position - 1), 6 /* Latest */)) && + (endPosition === sourceLength || !ts.isIdentifierPart(text.charCodeAt(endPosition), 6 /* Latest */))) { + // Found a real match. Keep searching. + positions.push(position); + } + position = text.indexOf(symbolName, position + symbolNameLength + 1); + } + return positions; + } + function getLabelReferencesInNode(container, targetLabel) { + var sourceFile = container.getSourceFile(); + var labelName = targetLabel.text; + var references = ts.mapDefined(getPossibleSymbolReferenceNodes(sourceFile, labelName, container), function (node) { + // Only pick labels that are either the target label, or have a target that is the target label + return node === targetLabel || (ts.isJumpStatementTarget(node) && ts.getTargetLabel(node, labelName) === targetLabel) ? FindAllReferences.nodeEntry(node) : undefined; + }); + return [{ definition: { type: 1 /* Label */, node: targetLabel }, references: references }]; + } + function isValidReferencePosition(node, searchSymbolName) { + // Compare the length so we filter out strict superstrings of the symbol we are looking for + switch (node.kind) { + case 72 /* Identifier */: + return node.text.length === searchSymbolName.length; + case 10 /* StringLiteral */: { + var str = node; + return (ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(str) || ts.isNameOfModuleDeclaration(node) || ts.isExpressionOfExternalModuleImportEqualsDeclaration(node) || (ts.isCallExpression(node.parent) && ts.isBindableObjectDefinePropertyCall(node.parent) && node.parent.arguments[1] === node)) && + str.text.length === searchSymbolName.length; + } + case 8 /* NumericLiteral */: + return ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node) && node.text.length === searchSymbolName.length; + case 80 /* DefaultKeyword */: + return "default".length === searchSymbolName.length; + default: + return false; + } + } + function getAllReferencesForKeyword(sourceFiles, keywordKind, cancellationToken) { + var references = ts.flatMap(sourceFiles, function (sourceFile) { + cancellationToken.throwIfCancellationRequested(); + return ts.mapDefined(getPossibleSymbolReferenceNodes(sourceFile, ts.tokenToString(keywordKind), sourceFile), function (referenceLocation) { + return referenceLocation.kind === keywordKind ? FindAllReferences.nodeEntry(referenceLocation) : undefined; + }); + }); + return references.length ? [{ definition: { type: 2 /* Keyword */, node: references[0].node }, references: references }] : undefined; + } + function getReferencesInSourceFile(sourceFile, search, state, addReferencesHere) { + if (addReferencesHere === void 0) { addReferencesHere = true; } + state.cancellationToken.throwIfCancellationRequested(); + return getReferencesInContainer(sourceFile, sourceFile, search, state, addReferencesHere); + } + /** + * Search within node "container" for references for a search value, where the search value is defined as a + * tuple of(searchSymbol, searchText, searchLocation, and searchMeaning). + * searchLocation: a node where the search value + */ + function getReferencesInContainer(container, sourceFile, search, state, addReferencesHere) { + if (!state.markSearchedSymbols(sourceFile, search.allSearchSymbols)) { + return; + } + for (var _i = 0, _a = getPossibleSymbolReferencePositions(sourceFile, search.text, container); _i < _a.length; _i++) { + var position = _a[_i]; + getReferencesAtLocation(sourceFile, position, search, state, addReferencesHere); + } + } + function hasMatchingMeaning(referenceLocation, state) { + return !!(ts.getMeaningFromLocation(referenceLocation) & state.searchMeaning); + } + function getReferencesAtLocation(sourceFile, position, search, state, addReferencesHere) { + var referenceLocation = ts.getTouchingPropertyName(sourceFile, position); + if (!isValidReferencePosition(referenceLocation, search.text)) { + // This wasn't the start of a token. Check to see if it might be a + // match in a comment or string if that's what the caller is asking + // for. + if (!state.options.implementations && (state.options.findInStrings && ts.isInString(sourceFile, position) || state.options.findInComments && ts.isInNonReferenceComment(sourceFile, position))) { + // In the case where we're looking inside comments/strings, we don't have + // an actual definition. So just use 'undefined' here. Features like + // 'Rename' won't care (as they ignore the definitions), and features like + // 'FindReferences' will just filter out these results. + state.addStringOrCommentReference(sourceFile.fileName, ts.createTextSpan(position, search.text.length)); + } + return; + } + if (!hasMatchingMeaning(referenceLocation, state)) + return; + var referenceSymbol = state.checker.getSymbolAtLocation(referenceLocation); + if (!referenceSymbol) { + return; + } + var parent = referenceLocation.parent; + if (ts.isImportSpecifier(parent) && parent.propertyName === referenceLocation) { + // This is added through `singleReferences` in ImportsResult. If we happen to see it again, don't add it again. + return; + } + if (ts.isExportSpecifier(parent)) { + ts.Debug.assert(referenceLocation.kind === 72 /* Identifier */); + getReferencesAtExportSpecifier(referenceLocation, referenceSymbol, parent, search, state, addReferencesHere); + return; + } + var relatedSymbol = getRelatedSymbol(search, referenceSymbol, referenceLocation, state); + if (!relatedSymbol) { + getReferenceForShorthandProperty(referenceSymbol, search, state); + return; + } + switch (state.specialSearchKind) { + case 0 /* None */: + if (addReferencesHere) + addReference(referenceLocation, relatedSymbol, state); + break; + case 1 /* Constructor */: + addConstructorReferences(referenceLocation, sourceFile, search, state); + break; + case 2 /* Class */: + addClassStaticThisReferences(referenceLocation, search, state); + break; + default: + ts.Debug.assertNever(state.specialSearchKind); + } + getImportOrExportReferences(referenceLocation, referenceSymbol, search, state); + } + function getReferencesAtExportSpecifier(referenceLocation, referenceSymbol, exportSpecifier, search, state, addReferencesHere, alwaysGetReferences) { + var parent = exportSpecifier.parent, propertyName = exportSpecifier.propertyName, name = exportSpecifier.name; + var exportDeclaration = parent.parent; + var localSymbol = getLocalSymbolForExportSpecifier(referenceLocation, referenceSymbol, exportSpecifier, state.checker); + if (!alwaysGetReferences && !search.includes(localSymbol)) { + return; + } + if (!propertyName) { + // Don't rename at `export { default } from "m";`. (but do continue to search for imports of the re-export) + if (!(state.options.isForRename && (name.escapedText === "default" /* Default */))) { + addRef(); + } + } + else if (referenceLocation === propertyName) { + // For `export { foo as bar } from "baz"`, "`foo`" will be added from the singleReferences for import searches of the original export. + // For `export { foo as bar };`, where `foo` is a local, so add it now. + if (!exportDeclaration.moduleSpecifier) { + addRef(); + } + if (addReferencesHere && !state.options.isForRename && state.markSeenReExportRHS(name)) { + addReference(name, ts.Debug.assertDefined(exportSpecifier.symbol), state); + } + } + else { + if (state.markSeenReExportRHS(referenceLocation)) { + addRef(); + } + } + // For `export { foo as bar }`, rename `foo`, but not `bar`. + if (!state.options.isForRename || alwaysGetReferences) { + var exportKind = referenceLocation.originalKeywordKind === 80 /* DefaultKeyword */ ? 1 /* Default */ : 0 /* Named */; + var exportSymbol = ts.Debug.assertDefined(exportSpecifier.symbol); + var exportInfo = ts.Debug.assertDefined(FindAllReferences.getExportInfo(exportSymbol, exportKind, state.checker)); + searchForImportsOfExport(referenceLocation, exportSymbol, exportInfo, state); + } + // At `export { x } from "foo"`, also search for the imported symbol `"foo".x`. + if (search.comingFrom !== 1 /* Export */ && exportDeclaration.moduleSpecifier && !propertyName && !state.options.isForRename) { + var imported = state.checker.getExportSpecifierLocalTargetSymbol(exportSpecifier); + if (imported) + searchForImportedSymbol(imported, state); + } + function addRef() { + if (addReferencesHere) + addReference(referenceLocation, localSymbol, state); + } + } + function getLocalSymbolForExportSpecifier(referenceLocation, referenceSymbol, exportSpecifier, checker) { + return isExportSpecifierAlias(referenceLocation, exportSpecifier) && checker.getExportSpecifierLocalTargetSymbol(exportSpecifier) || referenceSymbol; + } + function isExportSpecifierAlias(referenceLocation, exportSpecifier) { + var parent = exportSpecifier.parent, propertyName = exportSpecifier.propertyName, name = exportSpecifier.name; + ts.Debug.assert(propertyName === referenceLocation || name === referenceLocation); + if (propertyName) { + // Given `export { foo as bar } [from "someModule"]`: It's an alias at `foo`, but at `bar` it's a new symbol. + return propertyName === referenceLocation; + } + else { + // `export { foo } from "foo"` is a re-export. + // `export { foo };` is not a re-export, it creates an alias for the local variable `foo`. + return !parent.parent.moduleSpecifier; + } + } + function getImportOrExportReferences(referenceLocation, referenceSymbol, search, state) { + var importOrExport = FindAllReferences.getImportOrExportSymbol(referenceLocation, referenceSymbol, state.checker, search.comingFrom === 1 /* Export */); + if (!importOrExport) + return; + var symbol = importOrExport.symbol; + if (importOrExport.kind === 0 /* Import */) { + if (!state.options.isForRename) { + searchForImportedSymbol(symbol, state); + } + } + else { + searchForImportsOfExport(referenceLocation, symbol, importOrExport.exportInfo, state); + } + } + function getReferenceForShorthandProperty(_a, search, state) { + var flags = _a.flags, valueDeclaration = _a.valueDeclaration; + var shorthandValueSymbol = state.checker.getShorthandAssignmentValueSymbol(valueDeclaration); + var name = valueDeclaration && ts.getNameOfDeclaration(valueDeclaration); + /* + * Because in short-hand property assignment, an identifier which stored as name of the short-hand property assignment + * has two meanings: property name and property value. Therefore when we do findAllReference at the position where + * an identifier is declared, the language service should return the position of the variable declaration as well as + * the position in short-hand property assignment excluding property accessing. However, if we do findAllReference at the + * position of property accessing, the referenceEntry of such position will be handled in the first case. + */ + if (!(flags & 33554432 /* Transient */) && name && search.includes(shorthandValueSymbol)) { + addReference(name, shorthandValueSymbol, state); + } + } + function addReference(referenceLocation, relatedSymbol, state) { + var _a = "kind" in relatedSymbol ? relatedSymbol : { kind: undefined, symbol: relatedSymbol }, kind = _a.kind, symbol = _a.symbol; + var addRef = state.referenceAdder(symbol); + if (state.options.implementations) { + addImplementationReferences(referenceLocation, addRef, state); + } + else { + addRef(referenceLocation, kind); + } + } + /** Adds references when a constructor is used with `new this()` in its own class and `super()` calls in subclasses. */ + function addConstructorReferences(referenceLocation, sourceFile, search, state) { + if (ts.isNewExpressionTarget(referenceLocation)) { + addReference(referenceLocation, search.symbol, state); + } + var pusher = function () { return state.referenceAdder(search.symbol); }; + if (ts.isClassLike(referenceLocation.parent)) { + ts.Debug.assert(referenceLocation.kind === 80 /* DefaultKeyword */ || referenceLocation.parent.name === referenceLocation); + // This is the class declaration containing the constructor. + findOwnConstructorReferences(search.symbol, sourceFile, pusher()); + } + else { + // If this class appears in `extends C`, then the extending class' "super" calls are references. + var classExtending = tryGetClassByExtendingIdentifier(referenceLocation); + if (classExtending) { + findSuperConstructorAccesses(classExtending, pusher()); + } + } + } + function addClassStaticThisReferences(referenceLocation, search, state) { + addReference(referenceLocation, search.symbol, state); + var classLike = referenceLocation.parent; + if (state.options.isForRename || !ts.isClassLike(classLike)) + return; + ts.Debug.assert(classLike.name === referenceLocation); + var addRef = state.referenceAdder(search.symbol); + for (var _i = 0, _a = classLike.members; _i < _a.length; _i++) { + var member = _a[_i]; + if (!(ts.isMethodOrAccessor(member) && ts.hasModifier(member, 32 /* Static */))) { + continue; + } + if (member.body) { + member.body.forEachChild(function cb(node) { + if (node.kind === 100 /* ThisKeyword */) { + addRef(node); + } + else if (!ts.isFunctionLike(node) && !ts.isClassLike(node)) { + node.forEachChild(cb); + } + }); + } + } + } + /** + * `classSymbol` is the class where the constructor was defined. + * Reference the constructor and all calls to `new this()`. + */ + function findOwnConstructorReferences(classSymbol, sourceFile, addNode) { + for (var _i = 0, _a = classSymbol.members.get("__constructor" /* Constructor */).declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + var ctrKeyword = ts.findChildOfKind(decl, 124 /* ConstructorKeyword */, sourceFile); + ts.Debug.assert(decl.kind === 157 /* Constructor */ && !!ctrKeyword); + addNode(ctrKeyword); + } + classSymbol.exports.forEach(function (member) { + var decl = member.valueDeclaration; + if (decl && decl.kind === 156 /* MethodDeclaration */) { + var body = decl.body; + if (body) { + forEachDescendantOfKind(body, 100 /* ThisKeyword */, function (thisKeyword) { + if (ts.isNewExpressionTarget(thisKeyword)) { + addNode(thisKeyword); + } + }); + } + } + }); + } + /** Find references to `super` in the constructor of an extending class. */ + function findSuperConstructorAccesses(cls, addNode) { + var ctr = cls.symbol.members.get("__constructor" /* Constructor */); + if (!ctr) { + return; + } + for (var _i = 0, _a = ctr.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + ts.Debug.assert(decl.kind === 157 /* Constructor */); + var body = decl.body; + if (body) { + forEachDescendantOfKind(body, 98 /* SuperKeyword */, function (node) { + if (ts.isCallExpressionTarget(node)) { + addNode(node); + } + }); + } + } + } + function addImplementationReferences(refNode, addReference, state) { + // Check if we found a function/propertyAssignment/method with an implementation or initializer + if (ts.isDeclarationName(refNode) && isImplementation(refNode.parent)) { + addReference(refNode); + return; + } + if (refNode.kind !== 72 /* Identifier */) { + return; + } + if (refNode.parent.kind === 276 /* ShorthandPropertyAssignment */) { + // Go ahead and dereference the shorthand assignment by going to its definition + getReferenceEntriesForShorthandPropertyAssignment(refNode, state.checker, addReference); + } + // Check if the node is within an extends or implements clause + var containingClass = getContainingClassIfInHeritageClause(refNode); + if (containingClass) { + addReference(containingClass); + return; + } + // If we got a type reference, try and see if the reference applies to any expressions that can implement an interface + // Find the first node whose parent isn't a type node -- i.e., the highest type node. + var typeNode = ts.findAncestor(refNode, function (a) { return !ts.isQualifiedName(a.parent) && !ts.isTypeNode(a.parent) && !ts.isTypeElement(a.parent); }); + var typeHavingNode = typeNode.parent; + if (ts.hasType(typeHavingNode) && typeHavingNode.type === typeNode && state.markSeenContainingTypeReference(typeHavingNode)) { + if (ts.hasInitializer(typeHavingNode)) { + addIfImplementation(typeHavingNode.initializer); + } + else if (ts.isFunctionLike(typeHavingNode) && typeHavingNode.body) { + var body = typeHavingNode.body; + if (body.kind === 218 /* Block */) { + ts.forEachReturnStatement(body, function (returnStatement) { + if (returnStatement.expression) + addIfImplementation(returnStatement.expression); + }); + } + else { + addIfImplementation(body); + } + } + else if (ts.isAssertionExpression(typeHavingNode)) { + addIfImplementation(typeHavingNode.expression); + } + } + function addIfImplementation(e) { + if (isImplementationExpression(e)) + addReference(e); + } + } + function getContainingClassIfInHeritageClause(node) { + return ts.isIdentifier(node) || ts.isPropertyAccessExpression(node) ? getContainingClassIfInHeritageClause(node.parent) + : ts.isExpressionWithTypeArguments(node) ? ts.tryCast(node.parent.parent, ts.isClassLike) : undefined; + } + /** + * Returns true if this is an expression that can be considered an implementation + */ + function isImplementationExpression(node) { + switch (node.kind) { + case 195 /* ParenthesizedExpression */: + return isImplementationExpression(node.expression); + case 197 /* ArrowFunction */: + case 196 /* FunctionExpression */: + case 188 /* ObjectLiteralExpression */: + case 209 /* ClassExpression */: + case 187 /* ArrayLiteralExpression */: + return true; + default: + return false; + } + } + /** + * Determines if the parent symbol occurs somewhere in the child's ancestry. If the parent symbol + * is an interface, determines if some ancestor of the child symbol extends or inherits from it. + * Also takes in a cache of previous results which makes this slightly more efficient and is + * necessary to avoid potential loops like so: + * class A extends B { } + * class B extends A { } + * + * We traverse the AST rather than using the type checker because users are typically only interested + * in explicit implementations of an interface/class when calling "Go to Implementation". Sibling + * implementations of types that share a common ancestor with the type whose implementation we are + * searching for need to be filtered out of the results. The type checker doesn't let us make the + * distinction between structurally compatible implementations and explicit implementations, so we + * must use the AST. + * + * @param symbol A class or interface Symbol + * @param parent Another class or interface Symbol + * @param cachedResults A map of symbol id pairs (i.e. "child,parent") to booleans indicating previous results + */ + function explicitlyInheritsFrom(symbol, parent, cachedResults, checker) { + if (symbol === parent) { + return true; + } + var key = ts.getSymbolId(symbol) + "," + ts.getSymbolId(parent); + var cached = cachedResults.get(key); + if (cached !== undefined) { + return cached; + } + // Set the key so that we don't infinitely recurse + cachedResults.set(key, false); + var inherits = symbol.declarations.some(function (declaration) { + return ts.getAllSuperTypeNodes(declaration).some(function (typeReference) { + var type = checker.getTypeAtLocation(typeReference); + return !!type && !!type.symbol && explicitlyInheritsFrom(type.symbol, parent, cachedResults, checker); + }); + }); + cachedResults.set(key, inherits); + return inherits; + } + function getReferencesForSuperKeyword(superKeyword) { + var searchSpaceNode = ts.getSuperContainer(superKeyword, /*stopOnFunctions*/ false); + if (!searchSpaceNode) { + return undefined; + } + // Whether 'super' occurs in a static context within a class. + var staticFlag = 32 /* Static */; + switch (searchSpaceNode.kind) { + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + staticFlag &= ts.getModifierFlags(searchSpaceNode); + searchSpaceNode = searchSpaceNode.parent; // re-assign to be the owning class + break; + default: + return undefined; + } + var sourceFile = searchSpaceNode.getSourceFile(); + var references = ts.mapDefined(getPossibleSymbolReferenceNodes(sourceFile, "super", searchSpaceNode), function (node) { + if (node.kind !== 98 /* SuperKeyword */) { + return; + } + var container = ts.getSuperContainer(node, /*stopOnFunctions*/ false); + // If we have a 'super' container, we must have an enclosing class. + // Now make sure the owning class is the same as the search-space + // and has the same static qualifier as the original 'super's owner. + return container && (32 /* Static */ & ts.getModifierFlags(container)) === staticFlag && container.parent.symbol === searchSpaceNode.symbol ? FindAllReferences.nodeEntry(node) : undefined; + }); + return [{ definition: { type: 0 /* Symbol */, symbol: searchSpaceNode.symbol }, references: references }]; + } + function getReferencesForThisKeyword(thisOrSuperKeyword, sourceFiles, cancellationToken) { + var searchSpaceNode = ts.getThisContainer(thisOrSuperKeyword, /* includeArrowFunctions */ false); + // Whether 'this' occurs in a static context within a class. + var staticFlag = 32 /* Static */; + switch (searchSpaceNode.kind) { + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + if (ts.isObjectLiteralMethod(searchSpaceNode)) { + break; + } + // falls through + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + staticFlag &= ts.getModifierFlags(searchSpaceNode); + searchSpaceNode = searchSpaceNode.parent; // re-assign to be the owning class + break; + case 279 /* SourceFile */: + if (ts.isExternalModule(searchSpaceNode)) { + return undefined; + } + // falls through + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + break; + // Computed properties in classes are not handled here because references to this are illegal, + // so there is no point finding references to them. + default: + return undefined; + } + var references = ts.flatMap(searchSpaceNode.kind === 279 /* SourceFile */ ? sourceFiles : [searchSpaceNode.getSourceFile()], function (sourceFile) { + cancellationToken.throwIfCancellationRequested(); + return getPossibleSymbolReferenceNodes(sourceFile, "this", ts.isSourceFile(searchSpaceNode) ? sourceFile : searchSpaceNode).filter(function (node) { + if (!ts.isThis(node)) { + return false; + } + var container = ts.getThisContainer(node, /* includeArrowFunctions */ false); + switch (searchSpaceNode.kind) { + case 196 /* FunctionExpression */: + case 239 /* FunctionDeclaration */: + return searchSpaceNode.symbol === container.symbol; + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + return ts.isObjectLiteralMethod(searchSpaceNode) && searchSpaceNode.symbol === container.symbol; + case 209 /* ClassExpression */: + case 240 /* ClassDeclaration */: + // Make sure the container belongs to the same class + // and has the appropriate static modifier from the original container. + return container.parent && searchSpaceNode.symbol === container.parent.symbol && (ts.getModifierFlags(container) & 32 /* Static */) === staticFlag; + case 279 /* SourceFile */: + return container.kind === 279 /* SourceFile */ && !ts.isExternalModule(container); + } + }); + }).map(function (n) { return FindAllReferences.nodeEntry(n); }); + var thisParameter = ts.firstDefined(references, function (r) { return ts.isParameter(r.node.parent) ? r.node : undefined; }); + return [{ + definition: { type: 3 /* This */, node: thisParameter || thisOrSuperKeyword }, + references: references + }]; + } + function getReferencesForStringLiteral(node, sourceFiles, cancellationToken) { + var references = ts.flatMap(sourceFiles, function (sourceFile) { + cancellationToken.throwIfCancellationRequested(); + return ts.mapDefined(getPossibleSymbolReferenceNodes(sourceFile, node.text), function (ref) { + return ts.isStringLiteral(ref) && ref.text === node.text ? FindAllReferences.nodeEntry(ref, 2 /* StringLiteral */) : undefined; + }); + }); + return [{ + definition: { type: 4 /* String */, node: node }, + references: references + }]; + } + // For certain symbol kinds, we need to include other symbols in the search set. + // This is not needed when searching for re-exports. + function populateSearchSymbolSet(symbol, location, checker, isForRename, implementations) { + var result = []; + forEachRelatedSymbol(symbol, location, checker, isForRename, function (sym, root, base) { result.push(base || root || sym); }, + /*allowBaseTypes*/ function () { return !implementations; }); + return result; + } + function forEachRelatedSymbol(symbol, location, checker, isForRenamePopulateSearchSymbolSet, cbSymbol, allowBaseTypes) { + var containingObjectLiteralElement = ts.getContainingObjectLiteralElement(location); + if (containingObjectLiteralElement) { + /* Because in short-hand property assignment, location has two meaning : property name and as value of the property + * When we do findAllReference at the position of the short-hand property assignment, we would want to have references to position of + * property name and variable declaration of the identifier. + * Like in below example, when querying for all references for an identifier 'name', of the property assignment, the language service + * should show both 'name' in 'obj' and 'name' in variable declaration + * const name = "Foo"; + * const obj = { name }; + * In order to do that, we will populate the search set with the value symbol of the identifier as a value of the property assignment + * so that when matching with potential reference symbol, both symbols from property declaration and variable declaration + * will be included correctly. + */ + var shorthandValueSymbol = checker.getShorthandAssignmentValueSymbol(location.parent); // gets the local symbol + if (shorthandValueSymbol && isForRenamePopulateSearchSymbolSet) { + // When renaming 'x' in `const o = { x }`, just rename the local variable, not the property. + return cbSymbol(shorthandValueSymbol, /*rootSymbol*/ undefined, /*baseSymbol*/ undefined, 3 /* SearchedLocalFoundProperty */); + } + // If the location is in a context sensitive location (i.e. in an object literal) try + // to get a contextual type for it, and add the property symbol from the contextual + // type to the search set + var contextualType = checker.getContextualType(containingObjectLiteralElement.parent); + var res_1 = contextualType && ts.firstDefined(ts.getPropertySymbolsFromContextualType(containingObjectLiteralElement, checker, contextualType, /*unionSymbolOk*/ true), function (sym) { return fromRoot(sym, 4 /* SearchedPropertyFoundLocal */); }); + if (res_1) + return res_1; + // If the location is name of property symbol from object literal destructuring pattern + // Search the property symbol + // for ( { property: p2 } of elems) { } + var propertySymbol = getPropertySymbolOfDestructuringAssignment(location, checker); + var res1 = propertySymbol && cbSymbol(propertySymbol, /*rootSymbol*/ undefined, /*baseSymbol*/ undefined, 4 /* SearchedPropertyFoundLocal */); + if (res1) + return res1; + var res2 = shorthandValueSymbol && cbSymbol(shorthandValueSymbol, /*rootSymbol*/ undefined, /*baseSymbol*/ undefined, 3 /* SearchedLocalFoundProperty */); + if (res2) + return res2; + } + var res = fromRoot(symbol); + if (res) + return res; + if (symbol.valueDeclaration && ts.isParameterPropertyDeclaration(symbol.valueDeclaration)) { + // For a parameter property, now try on the other symbol (property if this was a parameter, parameter if this was a property). + var paramProps = checker.getSymbolsOfParameterPropertyDeclaration(ts.cast(symbol.valueDeclaration, ts.isParameter), symbol.name); + ts.Debug.assert(paramProps.length === 2 && !!(paramProps[0].flags & 1 /* FunctionScopedVariable */) && !!(paramProps[1].flags & 4 /* Property */)); // is [parameter, property] + return fromRoot(symbol.flags & 1 /* FunctionScopedVariable */ ? paramProps[1] : paramProps[0]); + } + // symbolAtLocation for a binding element is the local symbol. See if the search symbol is the property. + // Don't do this when populating search set for a rename -- just rename the local. + if (!isForRenamePopulateSearchSymbolSet) { + var bindingElementPropertySymbol = ts.isObjectBindingElementWithoutPropertyName(location.parent) ? ts.getPropertySymbolFromBindingElement(checker, location.parent) : undefined; + return bindingElementPropertySymbol && fromRoot(bindingElementPropertySymbol, 4 /* SearchedPropertyFoundLocal */); + } + function fromRoot(sym, kind) { + // If this is a union property: + // - In populateSearchSymbolsSet we will add all the symbols from all its source symbols in all unioned types. + // - In findRelatedSymbol, we will just use the union symbol if any source symbol is included in the search. + // If the symbol is an instantiation from a another symbol (e.g. widened symbol): + // - In populateSearchSymbolsSet, add the root the list + // - In findRelatedSymbol, return the source symbol if that is in the search. (Do not return the instantiation symbol.) + return ts.firstDefined(checker.getRootSymbols(sym), function (rootSymbol) { + return cbSymbol(sym, rootSymbol, /*baseSymbol*/ undefined, kind) + // Add symbol of properties/methods of the same name in base classes and implemented interfaces definitions + || (rootSymbol.parent && rootSymbol.parent.flags & (32 /* Class */ | 64 /* Interface */) && allowBaseTypes(rootSymbol) + ? ts.getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.name, checker, function (base) { return cbSymbol(sym, rootSymbol, base, kind); }) + : undefined); + }); + } + } + function getRelatedSymbol(search, referenceSymbol, referenceLocation, state) { + var checker = state.checker; + return forEachRelatedSymbol(referenceSymbol, referenceLocation, checker, /*isForRenamePopulateSearchSymbolSet*/ false, function (sym, rootSymbol, baseSymbol, kind) { return search.includes(baseSymbol || rootSymbol || sym) + // For a base type, use the symbol for the derived type. For a synthetic (e.g. union) property, use the union symbol. + ? { symbol: rootSymbol && !(ts.getCheckFlags(sym) & 6 /* Synthetic */) ? rootSymbol : sym, kind: kind } + : undefined; }, + /*allowBaseTypes*/ function (rootSymbol) { + return !(search.parents && !search.parents.some(function (parent) { return explicitlyInheritsFrom(rootSymbol.parent, parent, state.inheritsFromCache, checker); })); + }); + } + /** + * Given an initial searchMeaning, extracted from a location, widen the search scope based on the declarations + * of the corresponding symbol. e.g. if we are searching for "Foo" in value position, but "Foo" references a class + * then we need to widen the search to include type positions as well. + * On the contrary, if we are searching for "Bar" in type position and we trace bar to an interface, and an uninstantiated + * module, we want to keep the search limited to only types, as the two declarations (interface and uninstantiated module) + * do not intersect in any of the three spaces. + */ + function getIntersectingMeaningFromDeclarations(node, symbol) { + var meaning = ts.getMeaningFromLocation(node); + var declarations = symbol.declarations; + if (declarations) { + var lastIterationMeaning = void 0; + do { + // The result is order-sensitive, for instance if initialMeaning === Namespace, and declarations = [class, instantiated module] + // we need to consider both as they initialMeaning intersects with the module in the namespace space, and the module + // intersects with the class in the value space. + // To achieve that we will keep iterating until the result stabilizes. + // Remember the last meaning + lastIterationMeaning = meaning; + for (var _i = 0, declarations_2 = declarations; _i < declarations_2.length; _i++) { + var declaration = declarations_2[_i]; + var declarationMeaning = ts.getMeaningFromDeclaration(declaration); + if (declarationMeaning & meaning) { + meaning |= declarationMeaning; + } + } + } while (meaning !== lastIterationMeaning); + } + return meaning; + } + Core.getIntersectingMeaningFromDeclarations = getIntersectingMeaningFromDeclarations; + function isImplementation(node) { + return !!(node.flags & 4194304 /* Ambient */) + || (ts.isVariableLike(node) ? ts.hasInitializer(node) + : ts.isFunctionLikeDeclaration(node) ? !!node.body + : ts.isClassLike(node) || ts.isModuleOrEnumDeclaration(node)); + } + function getReferenceEntriesForShorthandPropertyAssignment(node, checker, addReference) { + var refSymbol = checker.getSymbolAtLocation(node); + var shorthandSymbol = checker.getShorthandAssignmentValueSymbol(refSymbol.valueDeclaration); + if (shorthandSymbol) { + for (var _i = 0, _a = shorthandSymbol.getDeclarations(); _i < _a.length; _i++) { + var declaration = _a[_i]; + if (ts.getMeaningFromDeclaration(declaration) & 1 /* Value */) { + addReference(declaration); + } + } + } + } + Core.getReferenceEntriesForShorthandPropertyAssignment = getReferenceEntriesForShorthandPropertyAssignment; + function forEachDescendantOfKind(node, kind, action) { + ts.forEachChild(node, function (child) { + if (child.kind === kind) { + action(child); + } + forEachDescendantOfKind(child, kind, action); + }); + } + /** Get `C` given `N` if `N` is in the position `class C extends N` or `class C extends foo.N` where `N` is an identifier. */ + function tryGetClassByExtendingIdentifier(node) { + return ts.tryGetClassExtendingExpressionWithTypeArguments(ts.climbPastPropertyAccess(node).parent); + } + /** + * If we are just looking for implementations and this is a property access expression, we need to get the + * symbol of the local type of the symbol the property is being accessed on. This is because our search + * symbol may have a different parent symbol if the local type's symbol does not declare the property + * being accessed (i.e. it is declared in some parent class or interface) + */ + function getParentSymbolsOfPropertyAccess(location, symbol, checker) { + var propertyAccessExpression = ts.isRightSideOfPropertyAccess(location) ? location.parent : undefined; + var lhsType = propertyAccessExpression && checker.getTypeAtLocation(propertyAccessExpression.expression); + var res = ts.mapDefined(lhsType && (lhsType.isUnionOrIntersection() ? lhsType.types : lhsType.symbol === symbol.parent ? undefined : [lhsType]), function (t) { + return t.symbol && t.symbol.flags & (32 /* Class */ | 64 /* Interface */) ? t.symbol : undefined; + }); + return res.length === 0 ? undefined : res; + } + })(Core = FindAllReferences.Core || (FindAllReferences.Core = {})); + })(FindAllReferences = ts.FindAllReferences || (ts.FindAllReferences = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + function getEditsForFileRename(program, oldFileOrDirPath, newFileOrDirPath, host, formatContext, _preferences, sourceMapper) { + var useCaseSensitiveFileNames = ts.hostUsesCaseSensitiveFileNames(host); + var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); + var oldToNew = getPathUpdater(oldFileOrDirPath, newFileOrDirPath, getCanonicalFileName, sourceMapper); + var newToOld = getPathUpdater(newFileOrDirPath, oldFileOrDirPath, getCanonicalFileName, sourceMapper); + return ts.textChanges.ChangeTracker.with({ host: host, formatContext: formatContext }, function (changeTracker) { + updateTsconfigFiles(program, changeTracker, oldToNew, oldFileOrDirPath, newFileOrDirPath, host.getCurrentDirectory(), useCaseSensitiveFileNames); + updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName); + }); + } + ts.getEditsForFileRename = getEditsForFileRename; + // exported for tests + function getPathUpdater(oldFileOrDirPath, newFileOrDirPath, getCanonicalFileName, sourceMapper) { + var canonicalOldPath = getCanonicalFileName(oldFileOrDirPath); + return function (path) { + var originalPath = sourceMapper && sourceMapper.tryGetSourcePosition({ fileName: path, pos: 0 }); + var updatedPath = getUpdatedPath(originalPath ? originalPath.fileName : path); + return originalPath + ? updatedPath === undefined ? undefined : makeCorrespondingRelativeChange(originalPath.fileName, updatedPath, path, getCanonicalFileName) + : updatedPath; + }; + function getUpdatedPath(pathToUpdate) { + if (getCanonicalFileName(pathToUpdate) === canonicalOldPath) + return newFileOrDirPath; + var suffix = ts.tryRemoveDirectoryPrefix(pathToUpdate, canonicalOldPath, getCanonicalFileName); + return suffix === undefined ? undefined : newFileOrDirPath + "/" + suffix; + } + } + ts.getPathUpdater = getPathUpdater; + // Relative path from a0 to b0 should be same as relative path from a1 to b1. Returns b1. + function makeCorrespondingRelativeChange(a0, b0, a1, getCanonicalFileName) { + var rel = ts.getRelativePathFromFile(a0, b0, getCanonicalFileName); + return combinePathsSafe(ts.getDirectoryPath(a1), rel); + } + function updateTsconfigFiles(program, changeTracker, oldToNew, oldFileOrDirPath, newFileOrDirPath, currentDirectory, useCaseSensitiveFileNames) { + var configFile = program.getCompilerOptions().configFile; + if (!configFile) + return; + var configDir = ts.getDirectoryPath(configFile.fileName); + var jsonObjectLiteral = ts.getTsConfigObjectLiteralExpression(configFile); + if (!jsonObjectLiteral) + return; + forEachProperty(jsonObjectLiteral, function (property, propertyName) { + switch (propertyName) { + case "files": + case "include": + case "exclude": { + var foundExactMatch = updatePaths(property); + if (!foundExactMatch && propertyName === "include" && ts.isArrayLiteralExpression(property.initializer)) { + var includes = ts.mapDefined(property.initializer.elements, function (e) { return ts.isStringLiteral(e) ? e.text : undefined; }); + var matchers = ts.getFileMatcherPatterns(configDir, /*excludes*/ [], includes, useCaseSensitiveFileNames, currentDirectory); + // If there isn't some include for this, add a new one. + if (ts.getRegexFromPattern(ts.Debug.assertDefined(matchers.includeFilePattern), useCaseSensitiveFileNames).test(oldFileOrDirPath) && + !ts.getRegexFromPattern(ts.Debug.assertDefined(matchers.includeFilePattern), useCaseSensitiveFileNames).test(newFileOrDirPath)) { + changeTracker.insertNodeAfter(configFile, ts.last(property.initializer.elements), ts.createStringLiteral(relativePath(newFileOrDirPath))); + } + } + break; + } + case "compilerOptions": + forEachProperty(property.initializer, function (property, propertyName) { + var option = ts.getOptionFromName(propertyName); + if (option && (option.isFilePath || option.type === "list" && option.element.isFilePath)) { + updatePaths(property); + } + else if (propertyName === "paths") { + forEachProperty(property.initializer, function (pathsProperty) { + if (!ts.isArrayLiteralExpression(pathsProperty.initializer)) + return; + for (var _i = 0, _a = pathsProperty.initializer.elements; _i < _a.length; _i++) { + var e = _a[_i]; + tryUpdateString(e); + } + }); + } + }); + break; + } + }); + function updatePaths(property) { + // Type annotation needed due to #7294 + var elements = ts.isArrayLiteralExpression(property.initializer) ? property.initializer.elements : [property.initializer]; + var foundExactMatch = false; + for (var _i = 0, elements_1 = elements; _i < elements_1.length; _i++) { + var element = elements_1[_i]; + foundExactMatch = tryUpdateString(element) || foundExactMatch; + } + return foundExactMatch; + } + function tryUpdateString(element) { + if (!ts.isStringLiteral(element)) + return false; + var elementFileName = combinePathsSafe(configDir, element.text); + var updated = oldToNew(elementFileName); + if (updated !== undefined) { + changeTracker.replaceRangeWithText(configFile, createStringRange(element, configFile), relativePath(updated)); + return true; + } + return false; + } + function relativePath(path) { + return ts.getRelativePathFromDirectory(configDir, path, /*ignoreCase*/ !useCaseSensitiveFileNames); + } + } + function updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName) { + var allFiles = program.getSourceFiles(); + var _loop_3 = function (sourceFile) { + var newFromOld = oldToNew(sourceFile.path); + var newImportFromPath = newFromOld !== undefined ? newFromOld : sourceFile.path; + var newImportFromDirectory = ts.getDirectoryPath(newImportFromPath); + var oldFromNew = newToOld(sourceFile.fileName); + var oldImportFromPath = oldFromNew || sourceFile.fileName; + var oldImportFromDirectory = ts.getDirectoryPath(oldImportFromPath); + var importingSourceFileMoved = newFromOld !== undefined || oldFromNew !== undefined; + updateImportsWorker(sourceFile, changeTracker, function (referenceText) { + if (!ts.pathIsRelative(referenceText)) + return undefined; + var oldAbsolute = combinePathsSafe(oldImportFromDirectory, referenceText); + var newAbsolute = oldToNew(oldAbsolute); + return newAbsolute === undefined ? undefined : ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(newImportFromDirectory, newAbsolute, getCanonicalFileName)); + }, function (importLiteral) { + var importedModuleSymbol = program.getTypeChecker().getSymbolAtLocation(importLiteral); + // No need to update if it's an ambient module^M + if (importedModuleSymbol && importedModuleSymbol.declarations.some(function (d) { return ts.isAmbientModule(d); })) + return undefined; + var toImport = oldFromNew !== undefined + // If we're at the new location (file was already renamed), need to redo module resolution starting from the old location. + // TODO:GH#18217 + ? getSourceFileToImportFromResolved(ts.resolveModuleName(importLiteral.text, oldImportFromPath, program.getCompilerOptions(), host), oldToNew, host) + : getSourceFileToImport(importedModuleSymbol, importLiteral, sourceFile, program, host, oldToNew); + // Need an update if the imported file moved, or the importing file moved and was using a relative path. + return toImport !== undefined && (toImport.updated || (importingSourceFileMoved && ts.pathIsRelative(importLiteral.text))) + ? ts.moduleSpecifiers.updateModuleSpecifier(program.getCompilerOptions(), newImportFromPath, toImport.newFileName, host, allFiles, program.redirectTargetsMap, importLiteral.text) + : undefined; + }); + }; + for (var _i = 0, allFiles_1 = allFiles; _i < allFiles_1.length; _i++) { + var sourceFile = allFiles_1[_i]; + _loop_3(sourceFile); + } + } + function combineNormal(pathA, pathB) { + return ts.normalizePath(ts.combinePaths(pathA, pathB)); + } + function combinePathsSafe(pathA, pathB) { + return ts.ensurePathIsNonModuleName(combineNormal(pathA, pathB)); + } + function getSourceFileToImport(importedModuleSymbol, importLiteral, importingSourceFile, program, host, oldToNew) { + if (importedModuleSymbol) { + // `find` should succeed because we checked for ambient modules before calling this function. + var oldFileName = ts.find(importedModuleSymbol.declarations, ts.isSourceFile).fileName; + var newFileName = oldToNew(oldFileName); + return newFileName === undefined ? { newFileName: oldFileName, updated: false } : { newFileName: newFileName, updated: true }; + } + else { + var resolved = host.resolveModuleNames + ? host.getResolvedModuleWithFailedLookupLocationsFromCache && host.getResolvedModuleWithFailedLookupLocationsFromCache(importLiteral.text, importingSourceFile.fileName) + : program.getResolvedModuleWithFailedLookupLocationsFromCache(importLiteral.text, importingSourceFile.fileName); + return getSourceFileToImportFromResolved(resolved, oldToNew, host); + } + } + function getSourceFileToImportFromResolved(resolved, oldToNew, host) { + // Search through all locations looking for a moved file, and only then test already existing files. + // This is because if `a.ts` is compiled to `a.js` and `a.ts` is moved, we don't want to resolve anything to `a.js`, but to `a.ts`'s new location. + return tryEach(tryGetNewFile) || tryEach(tryGetOldFile); + function tryEach(cb) { + return resolved && ((resolved.resolvedModule && cb(resolved.resolvedModule.resolvedFileName)) || ts.firstDefined(resolved.failedLookupLocations, cb)); + } + function tryGetNewFile(oldFileName) { + var newFileName = oldToNew(oldFileName); + return newFileName !== undefined && host.fileExists(newFileName) ? { newFileName: newFileName, updated: true } : undefined; // TODO: GH#18217 + } + function tryGetOldFile(oldFileName) { + var newFileName = oldToNew(oldFileName); + return host.fileExists(oldFileName) ? newFileName !== undefined ? { newFileName: newFileName, updated: true } : { newFileName: oldFileName, updated: false } : undefined; // TODO: GH#18217 + } + } + function updateImportsWorker(sourceFile, changeTracker, updateRef, updateImport) { + for (var _i = 0, _a = sourceFile.referencedFiles || ts.emptyArray; _i < _a.length; _i++) { // TODO: GH#26162 + var ref = _a[_i]; + var updated = updateRef(ref.fileName); + if (updated !== undefined && updated !== sourceFile.text.slice(ref.pos, ref.end)) + changeTracker.replaceRangeWithText(sourceFile, ref, updated); + } + for (var _b = 0, _c = sourceFile.imports; _b < _c.length; _b++) { + var importStringLiteral = _c[_b]; + var updated = updateImport(importStringLiteral); + if (updated !== undefined && updated !== importStringLiteral.text) + changeTracker.replaceRangeWithText(sourceFile, createStringRange(importStringLiteral, sourceFile), updated); + } + } + function createStringRange(node, sourceFile) { + return ts.createRange(node.getStart(sourceFile) + 1, node.end - 1); + } + function forEachProperty(objectLiteral, cb) { + if (!ts.isObjectLiteralExpression(objectLiteral)) + return; + for (var _i = 0, _a = objectLiteral.properties; _i < _a.length; _i++) { + var property = _a[_i]; + if (ts.isPropertyAssignment(property) && ts.isStringLiteral(property.name)) { + cb(property, property.name.text); + } + } + } +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var GoToDefinition; + (function (GoToDefinition) { + function getDefinitionAtPosition(program, sourceFile, position) { + var reference = getReferenceAtPosition(sourceFile, position, program); + if (reference) { + return [getDefinitionInfoForFileReference(reference.fileName, reference.file.fileName)]; + } + var node = ts.getTouchingPropertyName(sourceFile, position); + if (node === sourceFile) { + return undefined; + } + var parent = node.parent; + // Labels + if (ts.isJumpStatementTarget(node)) { + var label = ts.getTargetLabel(node.parent, node.text); + return label ? [createDefinitionInfoFromName(label, "label" /* label */, node.text, /*containerName*/ undefined)] : undefined; // TODO: GH#18217 + } + var typeChecker = program.getTypeChecker(); + var symbol = getSymbol(node, typeChecker); + // Could not find a symbol e.g. node is string or number keyword, + // or the symbol was an internal symbol and does not have a declaration e.g. undefined symbol + if (!symbol) { + return getDefinitionInfoForIndexSignatures(node, typeChecker); + } + var calledDeclaration = tryGetSignatureDeclaration(typeChecker, node); + // Don't go to the component constructor definition for a JSX element, just go to the component definition. + if (calledDeclaration && !(ts.isJsxOpeningLikeElement(node.parent) && isConstructorLike(calledDeclaration))) { + var sigInfo = createDefinitionFromSignatureDeclaration(typeChecker, calledDeclaration); + // For a function, if this is the original function definition, return just sigInfo. + // If this is the original constructor definition, parent is the class. + if (typeChecker.getRootSymbols(symbol).some(function (s) { return symbolMatchesSignature(s, calledDeclaration); }) || + // TODO: GH#25533 Following check shouldn't be necessary if 'require' is an alias + symbol.declarations && symbol.declarations.some(function (d) { return ts.isVariableDeclaration(d) && !!d.initializer && ts.isRequireCall(d.initializer, /*checkArgumentIsStringLiteralLike*/ false); })) { + return [sigInfo]; + } + else { + var defs = getDefinitionFromSymbol(typeChecker, symbol, node) || ts.emptyArray; + // For a 'super()' call, put the signature first, else put the variable first. + return node.kind === 98 /* SuperKeyword */ ? [sigInfo].concat(defs) : defs.concat([sigInfo]); + } + } + // Because name in short-hand property assignment has two different meanings: property name and property value, + // using go-to-definition at such position should go to the variable declaration of the property value rather than + // go to the declaration of the property name (in this case stay at the same position). However, if go-to-definition + // is performed at the location of property access, we would like to go to definition of the property in the short-hand + // assignment. This case and others are handled by the following code. + if (node.parent.kind === 276 /* ShorthandPropertyAssignment */) { + var shorthandSymbol_1 = typeChecker.getShorthandAssignmentValueSymbol(symbol.valueDeclaration); + return shorthandSymbol_1 ? shorthandSymbol_1.declarations.map(function (decl) { return createDefinitionInfo(decl, typeChecker, shorthandSymbol_1, node); }) : []; + } + // If the node is the name of a BindingElement within an ObjectBindingPattern instead of just returning the + // declaration the symbol (which is itself), we should try to get to the original type of the ObjectBindingPattern + // and return the property declaration for the referenced property. + // For example: + // import('./foo').then(({ b/*goto*/ar }) => undefined); => should get use to the declaration in file "./foo" + // + // function bar(onfulfilled: (value: T) => void) { //....} + // interface Test { + // pr/*destination*/op1: number + // } + // bar(({pr/*goto*/op1})=>{}); + if (ts.isPropertyName(node) && ts.isBindingElement(parent) && ts.isObjectBindingPattern(parent.parent) && + (node === (parent.propertyName || parent.name))) { + var name_3 = ts.getNameFromPropertyName(node); + var type = typeChecker.getTypeAtLocation(parent.parent); + return name_3 === undefined ? ts.emptyArray : ts.flatMap(type.isUnion() ? type.types : [type], function (t) { + var prop = t.getProperty(name_3); + return prop && getDefinitionFromSymbol(typeChecker, prop, node); + }); + } + // If the current location we want to find its definition is in an object literal, try to get the contextual type for the + // object literal, lookup the property symbol in the contextual type, and use this for goto-definition. + // For example + // interface Props{ + // /*first*/prop1: number + // prop2: boolean + // } + // function Foo(arg: Props) {} + // Foo( { pr/*1*/op1: 10, prop2: true }) + var element = ts.getContainingObjectLiteralElement(node); + if (element) { + var contextualType = element && typeChecker.getContextualType(element.parent); + if (contextualType) { + return ts.flatMap(ts.getPropertySymbolsFromContextualType(element, typeChecker, contextualType, /*unionSymbolOk*/ false), function (propertySymbol) { + return getDefinitionFromSymbol(typeChecker, propertySymbol, node); + }); + } + } + return getDefinitionFromSymbol(typeChecker, symbol, node); + } + GoToDefinition.getDefinitionAtPosition = getDefinitionAtPosition; + /** + * True if we should not add definitions for both the signature symbol and the definition symbol. + * True for `const |f = |() => 0`, false for `function |f() {} const |g = f;`. + */ + function symbolMatchesSignature(s, calledDeclaration) { + return s === calledDeclaration.symbol || s === calledDeclaration.symbol.parent || + !ts.isCallLikeExpression(calledDeclaration.parent) && s === calledDeclaration.parent.symbol; + } + function getReferenceAtPosition(sourceFile, position, program) { + var referencePath = findReferenceInPosition(sourceFile.referencedFiles, position); + if (referencePath) { + var file = ts.tryResolveScriptReference(program, sourceFile, referencePath); + return file && { fileName: referencePath.fileName, file: file }; + } + var typeReferenceDirective = findReferenceInPosition(sourceFile.typeReferenceDirectives, position); + if (typeReferenceDirective) { + var reference = program.getResolvedTypeReferenceDirectives().get(typeReferenceDirective.fileName); + var file = reference && program.getSourceFile(reference.resolvedFileName); // TODO:GH#18217 + return file && { fileName: typeReferenceDirective.fileName, file: file }; + } + var libReferenceDirective = findReferenceInPosition(sourceFile.libReferenceDirectives, position); + if (libReferenceDirective) { + var file = program.getLibFileFromReference(libReferenceDirective); + return file && { fileName: libReferenceDirective.fileName, file: file }; + } + return undefined; + } + GoToDefinition.getReferenceAtPosition = getReferenceAtPosition; + /// Goto type + function getTypeDefinitionAtPosition(typeChecker, sourceFile, position) { + var node = ts.getTouchingPropertyName(sourceFile, position); + if (node === sourceFile) { + return undefined; + } + var symbol = typeChecker.getSymbolAtLocation(node); + if (!symbol) + return undefined; + var typeAtLocation = typeChecker.getTypeOfSymbolAtLocation(symbol, node); + var returnType = tryGetReturnTypeOfFunction(symbol, typeAtLocation, typeChecker); + var fromReturnType = returnType && definitionFromType(returnType, typeChecker, node); + // If a function returns 'void' or some other type with no definition, just return the function definition. + return fromReturnType && fromReturnType.length !== 0 ? fromReturnType : definitionFromType(typeAtLocation, typeChecker, node); + } + GoToDefinition.getTypeDefinitionAtPosition = getTypeDefinitionAtPosition; + function definitionFromType(type, checker, node) { + return ts.flatMap(type.isUnion() && !(type.flags & 32 /* Enum */) ? type.types : [type], function (t) { + return t.symbol && getDefinitionFromSymbol(checker, t.symbol, node); + }); + } + function tryGetReturnTypeOfFunction(symbol, type, checker) { + // If the type is just a function's inferred type, + // go-to-type should go to the return type instead, since go-to-definition takes you to the function anyway. + if (type.symbol === symbol || + // At `const f = () => {}`, the symbol is `f` and the type symbol is at `() => {}` + symbol.valueDeclaration && type.symbol && ts.isVariableDeclaration(symbol.valueDeclaration) && symbol.valueDeclaration.initializer === type.symbol.valueDeclaration) { + var sigs = type.getCallSignatures(); + if (sigs.length === 1) + return checker.getReturnTypeOfSignature(ts.first(sigs)); + } + return undefined; + } + function getDefinitionAndBoundSpan(program, sourceFile, position) { + var definitions = getDefinitionAtPosition(program, sourceFile, position); + if (!definitions || definitions.length === 0) { + return undefined; + } + // Check if position is on triple slash reference. + var comment = findReferenceInPosition(sourceFile.referencedFiles, position) || + findReferenceInPosition(sourceFile.typeReferenceDirectives, position) || + findReferenceInPosition(sourceFile.libReferenceDirectives, position); + if (comment) { + return { definitions: definitions, textSpan: ts.createTextSpanFromRange(comment) }; + } + var node = ts.getTouchingPropertyName(sourceFile, position); + var textSpan = ts.createTextSpan(node.getStart(), node.getWidth()); + return { definitions: definitions, textSpan: textSpan }; + } + GoToDefinition.getDefinitionAndBoundSpan = getDefinitionAndBoundSpan; + // At 'x.foo', see if the type of 'x' has an index signature, and if so find its declarations. + function getDefinitionInfoForIndexSignatures(node, checker) { + if (!ts.isPropertyAccessExpression(node.parent) || node.parent.name !== node) + return; + var type = checker.getTypeAtLocation(node.parent.expression); + return ts.mapDefined(type.isUnionOrIntersection() ? type.types : [type], function (nonUnionType) { + var info = checker.getIndexInfoOfType(nonUnionType, 0 /* String */); + return info && info.declaration && createDefinitionFromSignatureDeclaration(checker, info.declaration); + }); + } + function getSymbol(node, checker) { + var symbol = checker.getSymbolAtLocation(node); + // If this is an alias, and the request came at the declaration location + // get the aliased symbol instead. This allows for goto def on an import e.g. + // import {A, B} from "mod"; + // to jump to the implementation directly. + if (symbol && symbol.flags & 2097152 /* Alias */ && shouldSkipAlias(node, symbol.declarations[0])) { + var aliased = checker.getAliasedSymbol(symbol); + if (aliased.declarations) { + return aliased; + } + } + return symbol; + } + // Go to the original declaration for cases: + // + // (1) when the aliased symbol was declared in the location(parent). + // (2) when the aliased symbol is originating from an import. + // + function shouldSkipAlias(node, declaration) { + if (node.kind !== 72 /* Identifier */) { + return false; + } + if (node.parent === declaration) { + return true; + } + switch (declaration.kind) { + case 250 /* ImportClause */: + case 248 /* ImportEqualsDeclaration */: + return true; + case 253 /* ImportSpecifier */: + return declaration.parent.kind === 252 /* NamedImports */; + default: + return false; + } + } + function getDefinitionFromSymbol(typeChecker, symbol, node) { + return getConstructSignatureDefinition() || getCallSignatureDefinition() || ts.map(symbol.declarations, function (declaration) { return createDefinitionInfo(declaration, typeChecker, symbol, node); }); + function getConstructSignatureDefinition() { + // Applicable only if we are in a new expression, or we are on a constructor declaration + // and in either case the symbol has a construct signature definition, i.e. class + if (symbol.flags & 32 /* Class */ && (ts.isNewExpressionTarget(node) || node.kind === 124 /* ConstructorKeyword */)) { + var cls = ts.find(symbol.declarations, ts.isClassLike) || ts.Debug.fail("Expected declaration to have at least one class-like declaration"); + return getSignatureDefinition(cls.members, /*selectConstructors*/ true); + } + } + function getCallSignatureDefinition() { + return ts.isCallOrNewExpressionTarget(node) || ts.isNameOfFunctionDeclaration(node) + ? getSignatureDefinition(symbol.declarations, /*selectConstructors*/ false) + : undefined; + } + function getSignatureDefinition(signatureDeclarations, selectConstructors) { + if (!signatureDeclarations) { + return undefined; + } + var declarations = signatureDeclarations.filter(selectConstructors ? ts.isConstructorDeclaration : ts.isFunctionLike); + return declarations.length + ? [createDefinitionInfo(ts.find(declarations, function (d) { return !!d.body; }) || ts.last(declarations), typeChecker, symbol, node)] + : undefined; + } + } + /** Creates a DefinitionInfo from a Declaration, using the declaration's name if possible. */ + function createDefinitionInfo(declaration, checker, symbol, node) { + var symbolName = checker.symbolToString(symbol); // Do not get scoped name, just the name of the symbol + var symbolKind = ts.SymbolDisplay.getSymbolKind(checker, symbol, node); + var containerName = symbol.parent ? checker.symbolToString(symbol.parent, node) : ""; + return createDefinitionInfoFromName(declaration, symbolKind, symbolName, containerName); + } + /** Creates a DefinitionInfo directly from the name of a declaration. */ + function createDefinitionInfoFromName(declaration, symbolKind, symbolName, containerName) { + var name = ts.getNameOfDeclaration(declaration) || declaration; + var sourceFile = name.getSourceFile(); + return { + fileName: sourceFile.fileName, + textSpan: ts.createTextSpanFromNode(name, sourceFile), + kind: symbolKind, + name: symbolName, + containerKind: undefined, + containerName: containerName + }; + } + function createDefinitionFromSignatureDeclaration(typeChecker, decl) { + return createDefinitionInfo(decl, typeChecker, decl.symbol, decl); + } + function findReferenceInPosition(refs, pos) { + return ts.find(refs, function (ref) { return ts.textRangeContainsPositionInclusive(ref, pos); }); + } + GoToDefinition.findReferenceInPosition = findReferenceInPosition; + function getDefinitionInfoForFileReference(name, targetFileName) { + return { + fileName: targetFileName, + textSpan: ts.createTextSpanFromBounds(0, 0), + kind: "script" /* scriptElement */, + name: name, + containerName: undefined, + containerKind: undefined, + }; + } + /** Returns a CallLikeExpression where `node` is the target being invoked. */ + function getAncestorCallLikeExpression(node) { + var target = climbPastManyPropertyAccesses(node); + var callLike = target.parent; + return callLike && ts.isCallLikeExpression(callLike) && ts.getInvokedExpression(callLike) === target ? callLike : undefined; + } + function climbPastManyPropertyAccesses(node) { + return ts.isRightSideOfPropertyAccess(node) ? climbPastManyPropertyAccesses(node.parent) : node; + } + function tryGetSignatureDeclaration(typeChecker, node) { + var callLike = getAncestorCallLikeExpression(node); + var signature = callLike && typeChecker.getResolvedSignature(callLike); + // Don't go to a function type, go to the value having that type. + return ts.tryCast(signature && signature.declaration, function (d) { return ts.isFunctionLike(d) && !ts.isFunctionTypeNode(d); }); + } + function isConstructorLike(node) { + switch (node.kind) { + case 157 /* Constructor */: + case 166 /* ConstructorType */: + case 161 /* ConstructSignature */: + return true; + default: + return false; + } + } + })(GoToDefinition = ts.GoToDefinition || (ts.GoToDefinition = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var JsDoc; + (function (JsDoc) { + var jsDocTagNames = [ + "abstract", + "access", + "alias", + "argument", + "async", + "augments", + "author", + "borrows", + "callback", + "class", + "classdesc", + "constant", + "constructor", + "constructs", + "copyright", + "default", + "deprecated", + "description", + "emits", + "enum", + "event", + "example", + "exports", + "extends", + "external", + "field", + "file", + "fileoverview", + "fires", + "function", + "generator", + "global", + "hideconstructor", + "host", + "ignore", + "implements", + "inheritdoc", + "inner", + "instance", + "interface", + "kind", + "lends", + "license", + "listens", + "member", + "memberof", + "method", + "mixes", + "module", + "name", + "namespace", + "override", + "package", + "param", + "private", + "property", + "protected", + "public", + "readonly", + "requires", + "returns", + "see", + "since", + "static", + "summary", + "template", + "this", + "throws", + "todo", + "tutorial", + "type", + "typedef", + "var", + "variation", + "version", + "virtual", + "yields" + ]; + var jsDocTagNameCompletionEntries; + var jsDocTagCompletionEntries; + function getJsDocCommentsFromDeclarations(declarations) { + // Only collect doc comments from duplicate declarations once: + // In case of a union property there might be same declaration multiple times + // which only varies in type parameter + // Eg. const a: Array | Array; a.length + // The property length will have two declarations of property length coming + // from Array - Array and Array + var documentationComment = []; + forEachUnique(declarations, function (declaration) { + for (var _i = 0, _a = getCommentHavingNodes(declaration); _i < _a.length; _i++) { + var comment = _a[_i].comment; + if (comment === undefined) + continue; + if (documentationComment.length) { + documentationComment.push(ts.lineBreakPart()); + } + documentationComment.push(ts.textPart(comment)); + } + }); + return documentationComment; + } + JsDoc.getJsDocCommentsFromDeclarations = getJsDocCommentsFromDeclarations; + function getCommentHavingNodes(declaration) { + switch (declaration.kind) { + case 299 /* JSDocParameterTag */: + case 305 /* JSDocPropertyTag */: + return [declaration]; + case 297 /* JSDocCallbackTag */: + case 304 /* JSDocTypedefTag */: + return [declaration, declaration.parent]; + default: + return ts.getJSDocCommentsAndTags(declaration); + } + } + function getJsDocTagsFromDeclarations(declarations) { + // Only collect doc comments from duplicate declarations once. + var tags = []; + forEachUnique(declarations, function (declaration) { + for (var _i = 0, _a = ts.getJSDocTags(declaration); _i < _a.length; _i++) { + var tag = _a[_i]; + tags.push({ name: tag.tagName.text, text: getCommentText(tag) }); + } + }); + return tags; + } + JsDoc.getJsDocTagsFromDeclarations = getJsDocTagsFromDeclarations; + function getCommentText(tag) { + var comment = tag.comment; + switch (tag.kind) { + case 295 /* JSDocAugmentsTag */: + return withNode(tag.class); + case 303 /* JSDocTemplateTag */: + return withList(tag.typeParameters); + case 302 /* JSDocTypeTag */: + return withNode(tag.typeExpression); + case 304 /* JSDocTypedefTag */: + case 297 /* JSDocCallbackTag */: + case 305 /* JSDocPropertyTag */: + case 299 /* JSDocParameterTag */: + var name = tag.name; + return name ? withNode(name) : comment; + default: + return comment; + } + function withNode(node) { + return addComment(node.getText()); + } + function withList(list) { + return addComment(list.map(function (x) { return x.getText(); }).join(", ")); + } + function addComment(s) { + return comment === undefined ? s : s + " " + comment; + } + } + /** + * Iterates through 'array' by index and performs the callback on each element of array until the callback + * returns a truthy value, then returns that value. + * If no such value is found, the callback is applied to each element of array and undefined is returned. + */ + function forEachUnique(array, callback) { + if (array) { + for (var i = 0; i < array.length; i++) { + if (array.indexOf(array[i]) === i) { + var result = callback(array[i], i); + if (result) { + return result; + } + } + } + } + return undefined; + } + function getJSDocTagNameCompletions() { + return jsDocTagNameCompletionEntries || (jsDocTagNameCompletionEntries = ts.map(jsDocTagNames, function (tagName) { + return { + name: tagName, + kind: "keyword" /* keyword */, + kindModifiers: "", + sortText: "0", + }; + })); + } + JsDoc.getJSDocTagNameCompletions = getJSDocTagNameCompletions; + JsDoc.getJSDocTagNameCompletionDetails = getJSDocTagCompletionDetails; + function getJSDocTagCompletions() { + return jsDocTagCompletionEntries || (jsDocTagCompletionEntries = ts.map(jsDocTagNames, function (tagName) { + return { + name: "@" + tagName, + kind: "keyword" /* keyword */, + kindModifiers: "", + sortText: "0" + }; + })); + } + JsDoc.getJSDocTagCompletions = getJSDocTagCompletions; + function getJSDocTagCompletionDetails(name) { + return { + name: name, + kind: "" /* unknown */, + kindModifiers: "", + displayParts: [ts.textPart(name)], + documentation: ts.emptyArray, + tags: undefined, + codeActions: undefined, + }; + } + JsDoc.getJSDocTagCompletionDetails = getJSDocTagCompletionDetails; + function getJSDocParameterNameCompletions(tag) { + if (!ts.isIdentifier(tag.name)) { + return ts.emptyArray; + } + var nameThusFar = tag.name.text; + var jsdoc = tag.parent; + var fn = jsdoc.parent; + if (!ts.isFunctionLike(fn)) + return []; + return ts.mapDefined(fn.parameters, function (param) { + if (!ts.isIdentifier(param.name)) + return undefined; + var name = param.name.text; + if (jsdoc.tags.some(function (t) { return t !== tag && ts.isJSDocParameterTag(t) && ts.isIdentifier(t.name) && t.name.escapedText === name; }) // TODO: GH#18217 + || nameThusFar !== undefined && !ts.startsWith(name, nameThusFar)) { + return undefined; + } + return { name: name, kind: "parameter" /* parameterElement */, kindModifiers: "", sortText: "0" }; + }); + } + JsDoc.getJSDocParameterNameCompletions = getJSDocParameterNameCompletions; + function getJSDocParameterNameCompletionDetails(name) { + return { + name: name, + kind: "parameter" /* parameterElement */, + kindModifiers: "", + displayParts: [ts.textPart(name)], + documentation: ts.emptyArray, + tags: undefined, + codeActions: undefined, + }; + } + JsDoc.getJSDocParameterNameCompletionDetails = getJSDocParameterNameCompletionDetails; + /** + * Checks if position points to a valid position to add JSDoc comments, and if so, + * returns the appropriate template. Otherwise returns an empty string. + * Valid positions are + * - outside of comments, statements, and expressions, and + * - preceding a: + * - function/constructor/method declaration + * - class declarations + * - variable statements + * - namespace declarations + * - interface declarations + * - method signatures + * - type alias declarations + * + * Hosts should ideally check that: + * - The line is all whitespace up to 'position' before performing the insertion. + * - If the keystroke sequence "/\*\*" induced the call, we also check that the next + * non-whitespace character is '*', which (approximately) indicates whether we added + * the second '*' to complete an existing (JSDoc) comment. + * @param fileName The file in which to perform the check. + * @param position The (character-indexed) position in the file where the check should + * be performed. + */ + function getDocCommentTemplateAtPosition(newLine, sourceFile, position) { + var tokenAtPos = ts.getTokenAtPosition(sourceFile, position); + var existingDocComment = ts.findAncestor(tokenAtPos, ts.isJSDoc); + if (existingDocComment && (existingDocComment.comment !== undefined || ts.length(existingDocComment.tags))) { + // Non-empty comment already exists. + return undefined; + } + var tokenStart = tokenAtPos.getStart(sourceFile); + // Don't provide a doc comment template based on a *previous* node. (But an existing empty jsdoc comment will likely start before `position`.) + if (!existingDocComment && tokenStart < position) { + return undefined; + } + var commentOwnerInfo = getCommentOwnerInfo(tokenAtPos); + if (!commentOwnerInfo) { + return undefined; + } + var commentOwner = commentOwnerInfo.commentOwner, parameters = commentOwnerInfo.parameters; + if (commentOwner.getStart(sourceFile) < position) { + return undefined; + } + if (!parameters || parameters.length === 0) { + // if there are no parameters, just complete to a single line JSDoc comment + var singleLineResult = "/** */"; + return { newText: singleLineResult, caretOffset: 3 }; + } + var indentationStr = getIndentationStringAtPosition(sourceFile, position); + // A doc comment consists of the following + // * The opening comment line + // * the first line (without a param) for the object's untagged info (this is also where the caret ends up) + // * the '@param'-tagged lines + // * TODO: other tags. + // * the closing comment line + // * if the caret was directly in front of the object, then we add an extra line and indentation. + var preamble = "/**" + newLine + indentationStr + " * "; + var result = preamble + newLine + + parameterDocComments(parameters, ts.hasJSFileExtension(sourceFile.fileName), indentationStr, newLine) + + indentationStr + " */" + + (tokenStart === position ? newLine + indentationStr : ""); + return { newText: result, caretOffset: preamble.length }; + } + JsDoc.getDocCommentTemplateAtPosition = getDocCommentTemplateAtPosition; + function getIndentationStringAtPosition(sourceFile, position) { + var text = sourceFile.text; + var lineStart = ts.getLineStartPositionForPosition(position, sourceFile); + var pos = lineStart; + for (; pos <= position && ts.isWhiteSpaceSingleLine(text.charCodeAt(pos)); pos++) + ; + return text.slice(lineStart, pos); + } + function parameterDocComments(parameters, isJavaScriptFile, indentationStr, newLine) { + return parameters.map(function (_a, i) { + var name = _a.name, dotDotDotToken = _a.dotDotDotToken; + var paramName = name.kind === 72 /* Identifier */ ? name.text : "param" + i; + var type = isJavaScriptFile ? (dotDotDotToken ? "{...any} " : "{any} ") : ""; + return indentationStr + " * @param " + type + paramName + newLine; + }).join(""); + } + function getCommentOwnerInfo(tokenAtPos) { + return ts.forEachAncestor(tokenAtPos, getCommentOwnerInfoWorker); + } + function getCommentOwnerInfoWorker(commentOwner) { + switch (commentOwner.kind) { + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 156 /* MethodDeclaration */: + case 157 /* Constructor */: + case 155 /* MethodSignature */: + var parameters = commentOwner.parameters; + return { commentOwner: commentOwner, parameters: parameters }; + case 275 /* PropertyAssignment */: + return getCommentOwnerInfoWorker(commentOwner.initializer); + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + case 153 /* PropertySignature */: + case 243 /* EnumDeclaration */: + case 278 /* EnumMember */: + case 242 /* TypeAliasDeclaration */: + return { commentOwner: commentOwner }; + case 219 /* VariableStatement */: { + var varStatement = commentOwner; + var varDeclarations = varStatement.declarationList.declarations; + var parameters_1 = varDeclarations.length === 1 && varDeclarations[0].initializer + ? getParametersFromRightHandSideOfAssignment(varDeclarations[0].initializer) + : undefined; + return { commentOwner: commentOwner, parameters: parameters_1 }; + } + case 279 /* SourceFile */: + return "quit"; + case 244 /* ModuleDeclaration */: + // If in walking up the tree, we hit a a nested namespace declaration, + // then we must be somewhere within a dotted namespace name; however we don't + // want to give back a JSDoc template for the 'b' or 'c' in 'namespace a.b.c { }'. + return commentOwner.parent.kind === 244 /* ModuleDeclaration */ ? undefined : { commentOwner: commentOwner }; + case 204 /* BinaryExpression */: { + var be = commentOwner; + if (ts.getAssignmentDeclarationKind(be) === 0 /* None */) { + return "quit"; + } + var parameters_2 = ts.isFunctionLike(be.right) ? be.right.parameters : ts.emptyArray; + return { commentOwner: commentOwner, parameters: parameters_2 }; + } + } + } + /** + * Digs into an an initializer or RHS operand of an assignment operation + * to get the parameters of an apt signature corresponding to a + * function expression or a class expression. + * + * @param rightHandSide the expression which may contain an appropriate set of parameters + * @returns the parameters of a signature found on the RHS if one exists; otherwise 'emptyArray'. + */ + function getParametersFromRightHandSideOfAssignment(rightHandSide) { + while (rightHandSide.kind === 195 /* ParenthesizedExpression */) { + rightHandSide = rightHandSide.expression; + } + switch (rightHandSide.kind) { + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + return rightHandSide.parameters; + case 209 /* ClassExpression */: { + var ctr = ts.find(rightHandSide.members, ts.isConstructorDeclaration); + return ctr ? ctr.parameters : ts.emptyArray; + } + } + return ts.emptyArray; + } + })(JsDoc = ts.JsDoc || (ts.JsDoc = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var NavigateTo; + (function (NavigateTo) { + function getNavigateToItems(sourceFiles, checker, cancellationToken, searchValue, maxResultCount, excludeDtsFiles) { + var patternMatcher = ts.createPatternMatcher(searchValue); + if (!patternMatcher) + return ts.emptyArray; + var rawItems = []; + var _loop_4 = function (sourceFile) { + cancellationToken.throwIfCancellationRequested(); + if (excludeDtsFiles && sourceFile.isDeclarationFile) { + return "continue"; + } + sourceFile.getNamedDeclarations().forEach(function (declarations, name) { + getItemsFromNamedDeclaration(patternMatcher, name, declarations, checker, sourceFile.fileName, rawItems); + }); + }; + // Search the declarations in all files and output matched NavigateToItem into array of NavigateToItem[] + for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) { + var sourceFile = sourceFiles_4[_i]; + _loop_4(sourceFile); + } + rawItems.sort(compareNavigateToItems); + return (maxResultCount === undefined ? rawItems : rawItems.slice(0, maxResultCount)).map(createNavigateToItem); + } + NavigateTo.getNavigateToItems = getNavigateToItems; + function getItemsFromNamedDeclaration(patternMatcher, name, declarations, checker, fileName, rawItems) { + // First do a quick check to see if the name of the declaration matches the + // last portion of the (possibly) dotted name they're searching for. + var match = patternMatcher.getMatchForLastSegmentOfPattern(name); + if (!match) { + return; // continue to next named declarations + } + for (var _i = 0, declarations_3 = declarations; _i < declarations_3.length; _i++) { + var declaration = declarations_3[_i]; + if (!shouldKeepItem(declaration, checker)) + continue; + if (patternMatcher.patternContainsDots) { + // If the pattern has dots in it, then also see if the declaration container matches as well. + var fullMatch = patternMatcher.getFullMatch(getContainers(declaration), name); + if (fullMatch) { + rawItems.push({ name: name, fileName: fileName, matchKind: fullMatch.kind, isCaseSensitive: fullMatch.isCaseSensitive, declaration: declaration }); + } + } + else { + rawItems.push({ name: name, fileName: fileName, matchKind: match.kind, isCaseSensitive: match.isCaseSensitive, declaration: declaration }); + } + } + } + function shouldKeepItem(declaration, checker) { + switch (declaration.kind) { + case 250 /* ImportClause */: + case 253 /* ImportSpecifier */: + case 248 /* ImportEqualsDeclaration */: + var importer = checker.getSymbolAtLocation(declaration.name); // TODO: GH#18217 + var imported = checker.getAliasedSymbol(importer); + return importer.escapedName !== imported.escapedName; + default: + return true; + } + } + function tryAddSingleDeclarationName(declaration, containers) { + var name = ts.getNameOfDeclaration(declaration); + return !!name && (pushLiteral(name, containers) || name.kind === 149 /* ComputedPropertyName */ && tryAddComputedPropertyName(name.expression, containers)); + } + // Only added the names of computed properties if they're simple dotted expressions, like: + // + // [X.Y.Z]() { } + function tryAddComputedPropertyName(expression, containers) { + return pushLiteral(expression, containers) + || ts.isPropertyAccessExpression(expression) && (containers.push(expression.name.text), true) && tryAddComputedPropertyName(expression.expression, containers); + } + function pushLiteral(node, containers) { + return ts.isPropertyNameLiteral(node) && (containers.push(ts.getTextOfIdentifierOrLiteral(node)), true); + } + function getContainers(declaration) { + var containers = []; + // First, if we started with a computed property name, then add all but the last + // portion into the container array. + var name = ts.getNameOfDeclaration(declaration); + if (name && name.kind === 149 /* ComputedPropertyName */ && !tryAddComputedPropertyName(name.expression, containers)) { + return ts.emptyArray; + } + // Don't include the last portion. + containers.shift(); + // Now, walk up our containers, adding all their names to the container array. + var container = ts.getContainerNode(declaration); + while (container) { + if (!tryAddSingleDeclarationName(container, containers)) { + return ts.emptyArray; + } + container = ts.getContainerNode(container); + } + return containers.reverse(); + } + function compareNavigateToItems(i1, i2) { + // TODO(cyrusn): get the gamut of comparisons that VS already uses here. + return ts.compareValues(i1.matchKind, i2.matchKind) + || ts.compareStringsCaseSensitiveUI(i1.name, i2.name); + } + function createNavigateToItem(rawItem) { + var declaration = rawItem.declaration; + var container = ts.getContainerNode(declaration); + var containerName = container && ts.getNameOfDeclaration(container); + return { + name: rawItem.name, + kind: ts.getNodeKind(declaration), + kindModifiers: ts.getNodeModifiers(declaration), + matchKind: ts.PatternMatchKind[rawItem.matchKind], + isCaseSensitive: rawItem.isCaseSensitive, + fileName: rawItem.fileName, + textSpan: ts.createTextSpanFromNode(declaration), + // TODO(jfreeman): What should be the containerName when the container has a computed name? + containerName: containerName ? containerName.text : "", + containerKind: containerName ? ts.getNodeKind(container) : "" /* unknown */, + }; + } + })(NavigateTo = ts.NavigateTo || (ts.NavigateTo = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var NavigationBar; + (function (NavigationBar) { + /** + * Matches all whitespace characters in a string. Eg: + * + * "app. + * + * onactivated" + * + * matches because of the newline, whereas + * + * "app.onactivated" + * + * does not match. + */ + var whiteSpaceRegex = /\s+/g; + // Keep sourceFile handy so we don't have to search for it every time we need to call `getText`. + var curCancellationToken; + var curSourceFile; + /** + * For performance, we keep navigation bar parents on a stack rather than passing them through each recursion. + * `parent` is the current parent and is *not* stored in parentsStack. + * `startNode` sets a new parent and `endNode` returns to the previous parent. + */ + var parentsStack = []; + var parent; + // NavigationBarItem requires an array, but will not mutate it, so just give it this for performance. + var emptyChildItemArray = []; + function getNavigationBarItems(sourceFile, cancellationToken) { + curCancellationToken = cancellationToken; + curSourceFile = sourceFile; + try { + return ts.map(topLevelItems(rootNavigationBarNode(sourceFile)), convertToTopLevelItem); + } + finally { + reset(); + } + } + NavigationBar.getNavigationBarItems = getNavigationBarItems; + function getNavigationTree(sourceFile, cancellationToken) { + curCancellationToken = cancellationToken; + curSourceFile = sourceFile; + try { + return convertToTree(rootNavigationBarNode(sourceFile)); + } + finally { + reset(); + } + } + NavigationBar.getNavigationTree = getNavigationTree; + function reset() { + curSourceFile = undefined; + curCancellationToken = undefined; + parentsStack = []; + parent = undefined; + emptyChildItemArray = []; + } + function nodeText(node) { + return node.getText(curSourceFile); + } + function navigationBarNodeKind(n) { + return n.node.kind; + } + function pushChild(parent, child) { + if (parent.children) { + parent.children.push(child); + } + else { + parent.children = [child]; + } + } + function rootNavigationBarNode(sourceFile) { + ts.Debug.assert(!parentsStack.length); + var root = { node: sourceFile, name: undefined, additionalNodes: undefined, parent: undefined, children: undefined, indent: 0 }; + parent = root; + for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + addChildrenRecursively(statement); + } + endNode(); + ts.Debug.assert(!parent && !parentsStack.length); + return root; + } + function addLeafNode(node) { + pushChild(parent, emptyNavigationBarNode(node)); + } + function emptyNavigationBarNode(node) { + return { + node: node, + name: ts.isDeclaration(node) || ts.isExpression(node) ? ts.getNameOfDeclaration(node) : undefined, + additionalNodes: undefined, + parent: parent, + children: undefined, + indent: parent.indent + 1 + }; + } + /** + * Add a new level of NavigationBarNodes. + * This pushes to the stack, so you must call `endNode` when you are done adding to this node. + */ + function startNode(node) { + var navNode = emptyNavigationBarNode(node); + pushChild(parent, navNode); + // Save the old parent + parentsStack.push(parent); + parent = navNode; + } + /** Call after calling `startNode` and adding children to it. */ + function endNode() { + if (parent.children) { + mergeChildren(parent.children, parent); + sortChildren(parent.children); + } + parent = parentsStack.pop(); + } + function addNodeWithRecursiveChild(node, child) { + startNode(node); + addChildrenRecursively(child); + endNode(); + } + /** Look for navigation bar items in node's subtree, adding them to the current `parent`. */ + function addChildrenRecursively(node) { + curCancellationToken.throwIfCancellationRequested(); + if (!node || ts.isToken(node)) { + return; + } + switch (node.kind) { + case 157 /* Constructor */: + // Get parameter properties, and treat them as being on the *same* level as the constructor, not under it. + var ctr = node; + addNodeWithRecursiveChild(ctr, ctr.body); + // Parameter properties are children of the class, not the constructor. + for (var _i = 0, _a = ctr.parameters; _i < _a.length; _i++) { + var param = _a[_i]; + if (ts.isParameterPropertyDeclaration(param)) { + addLeafNode(param); + } + } + break; + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 155 /* MethodSignature */: + if (!ts.hasDynamicName(node)) { + addNodeWithRecursiveChild(node, node.body); + } + break; + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + if (!ts.hasDynamicName(node)) { + addLeafNode(node); + } + break; + case 250 /* ImportClause */: + var importClause = node; + // Handle default import case e.g.: + // import d from "mod"; + if (importClause.name) { + addLeafNode(importClause.name); + } + // Handle named bindings in imports e.g.: + // import * as NS from "mod"; + // import {a, b as B} from "mod"; + var namedBindings = importClause.namedBindings; + if (namedBindings) { + if (namedBindings.kind === 251 /* NamespaceImport */) { + addLeafNode(namedBindings); + } + else { + for (var _b = 0, _c = namedBindings.elements; _b < _c.length; _b++) { + var element = _c[_b]; + addLeafNode(element); + } + } + } + break; + case 186 /* BindingElement */: + case 237 /* VariableDeclaration */: + var _d = node, name = _d.name, initializer = _d.initializer; + if (ts.isBindingPattern(name)) { + addChildrenRecursively(name); + } + else if (initializer && isFunctionOrClassExpression(initializer)) { + if (initializer.name) { + // Don't add a node for the VariableDeclaration, just for the initializer. + addChildrenRecursively(initializer); + } + else { + // Add a node for the VariableDeclaration, but not for the initializer. + startNode(node); + ts.forEachChild(initializer, addChildrenRecursively); + endNode(); + } + } + else { + addNodeWithRecursiveChild(node, initializer); + } + break; + case 197 /* ArrowFunction */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + addNodeWithRecursiveChild(node, node.body); + break; + case 243 /* EnumDeclaration */: + startNode(node); + for (var _e = 0, _f = node.members; _e < _f.length; _e++) { + var member = _f[_e]; + if (!isComputedProperty(member)) { + addLeafNode(member); + } + } + endNode(); + break; + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 241 /* InterfaceDeclaration */: + startNode(node); + for (var _g = 0, _h = node.members; _g < _h.length; _g++) { + var member = _h[_g]; + addChildrenRecursively(member); + } + endNode(); + break; + case 244 /* ModuleDeclaration */: + addNodeWithRecursiveChild(node, getInteriorModule(node).body); + break; + case 257 /* ExportSpecifier */: + case 248 /* ImportEqualsDeclaration */: + case 162 /* IndexSignature */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 242 /* TypeAliasDeclaration */: + addLeafNode(node); + break; + case 204 /* BinaryExpression */: { + var special = ts.getAssignmentDeclarationKind(node); + switch (special) { + case 1 /* ExportsProperty */: + case 2 /* ModuleExports */: + case 3 /* PrototypeProperty */: + case 6 /* Prototype */: + addNodeWithRecursiveChild(node, node.right); + return; + case 4 /* ThisProperty */: + case 5 /* Property */: + case 0 /* None */: + case 7 /* ObjectDefinePropertyValue */: + case 8 /* ObjectDefinePropertyExports */: + case 9 /* ObjectDefinePrototypeProperty */: + break; + default: + ts.Debug.assertNever(special); + } + } + // falls through + default: + if (ts.hasJSDocNodes(node)) { + ts.forEach(node.jsDoc, function (jsDoc) { + ts.forEach(jsDoc.tags, function (tag) { + if (ts.isJSDocTypeAlias(tag)) { + addLeafNode(tag); + } + }); + }); + } + ts.forEachChild(node, addChildrenRecursively); + } + } + /** Merge declarations of the same kind. */ + function mergeChildren(children, node) { + var nameToItems = ts.createMap(); + ts.filterMutate(children, function (child) { + var declName = ts.getNameOfDeclaration(child.node); + var name = declName && nodeText(declName); + if (!name) { + // Anonymous items are never merged. + return true; + } + var itemsWithSameName = nameToItems.get(name); + if (!itemsWithSameName) { + nameToItems.set(name, child); + return true; + } + if (itemsWithSameName instanceof Array) { + for (var _i = 0, itemsWithSameName_1 = itemsWithSameName; _i < itemsWithSameName_1.length; _i++) { + var itemWithSameName = itemsWithSameName_1[_i]; + if (tryMerge(itemWithSameName, child, node)) { + return false; + } + } + itemsWithSameName.push(child); + return true; + } + else { + var itemWithSameName = itemsWithSameName; + if (tryMerge(itemWithSameName, child, node)) { + return false; + } + nameToItems.set(name, [itemWithSameName, child]); + return true; + } + }); + } + function tryMerge(a, b, parent) { + if (shouldReallyMerge(a.node, b.node, parent)) { + merge(a, b); + return true; + } + return false; + } + /** a and b have the same name, but they may not be mergeable. */ + function shouldReallyMerge(a, b, parent) { + if (a.kind !== b.kind || a.parent !== b.parent && !(isOwnChild(a, parent) && isOwnChild(b, parent))) { + return false; + } + switch (a.kind) { + case 154 /* PropertyDeclaration */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + return ts.hasModifier(a, 32 /* Static */) === ts.hasModifier(b, 32 /* Static */); + case 244 /* ModuleDeclaration */: + return areSameModule(a, b); + default: + return true; + } + } + // We want to merge own children like `I` in in `module A { interface I {} } module A { interface I {} }` + // We don't want to merge unrelated children like `m` in `const o = { a: { m() {} }, b: { m() {} } };` + function isOwnChild(n, parent) { + var par = ts.isModuleBlock(n.parent) ? n.parent.parent : n.parent; + return par === parent.node || ts.contains(parent.additionalNodes, par); + } + // We use 1 NavNode to represent 'A.B.C', but there are multiple source nodes. + // Only merge module nodes that have the same chain. Don't merge 'A.B.C' with 'A'! + function areSameModule(a, b) { + // TODO: GH#18217 + return a.body.kind === b.body.kind && (a.body.kind !== 244 /* ModuleDeclaration */ || areSameModule(a.body, b.body)); + } + /** Merge source into target. Source should be thrown away after this is called. */ + function merge(target, source) { + var _a; + target.additionalNodes = target.additionalNodes || []; + target.additionalNodes.push(source.node); + if (source.additionalNodes) { + (_a = target.additionalNodes).push.apply(_a, source.additionalNodes); + } + target.children = ts.concatenate(target.children, source.children); + if (target.children) { + mergeChildren(target.children, target); + sortChildren(target.children); + } + } + /** Recursively ensure that each NavNode's children are in sorted order. */ + function sortChildren(children) { + children.sort(compareChildren); + } + function compareChildren(child1, child2) { + return ts.compareStringsCaseSensitiveUI(tryGetName(child1.node), tryGetName(child2.node)) // TODO: GH#18217 + || ts.compareValues(navigationBarNodeKind(child1), navigationBarNodeKind(child2)); + } + /** + * This differs from getItemName because this is just used for sorting. + * We only sort nodes by name that have a more-or-less "direct" name, as opposed to `new()` and the like. + * So `new()` can still come before an `aardvark` method. + */ + function tryGetName(node) { + if (node.kind === 244 /* ModuleDeclaration */) { + return getModuleName(node); + } + var declName = ts.getNameOfDeclaration(node); + if (declName && ts.isPropertyName(declName)) { + return ts.unescapeLeadingUnderscores(ts.getPropertyNameForPropertyNameNode(declName)); // TODO: GH#18217 + } + switch (node.kind) { + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 209 /* ClassExpression */: + return getFunctionOrClassName(node); + default: + return undefined; + } + } + function getItemName(node, name) { + if (node.kind === 244 /* ModuleDeclaration */) { + return getModuleName(node); + } + if (name) { + var text = nodeText(name); + if (text.length > 0) { + return text; + } + } + switch (node.kind) { + case 279 /* SourceFile */: + var sourceFile = node; + return ts.isExternalModule(sourceFile) + ? "\"" + ts.escapeString(ts.getBaseFileName(ts.removeFileExtension(ts.normalizePath(sourceFile.fileName)))) + "\"" + : ""; + case 197 /* ArrowFunction */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + if (ts.getModifierFlags(node) & 512 /* Default */) { + return "default"; + } + // We may get a string with newlines or other whitespace in the case of an object dereference + // (eg: "app\n.onactivated"), so we should remove the whitespace for readabiltiy in the + // navigation bar. + return getFunctionOrClassName(node); + case 157 /* Constructor */: + return "constructor"; + case 161 /* ConstructSignature */: + return "new()"; + case 160 /* CallSignature */: + return "()"; + case 162 /* IndexSignature */: + return "[]"; + default: + return ""; + } + } + /** Flattens the NavNode tree to a list, keeping only the top-level items. */ + function topLevelItems(root) { + var topLevel = []; + function recur(item) { + if (isTopLevel(item)) { + topLevel.push(item); + if (item.children) { + for (var _i = 0, _a = item.children; _i < _a.length; _i++) { + var child = _a[_i]; + recur(child); + } + } + } + } + recur(root); + return topLevel; + function isTopLevel(item) { + switch (navigationBarNodeKind(item)) { + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 243 /* EnumDeclaration */: + case 241 /* InterfaceDeclaration */: + case 244 /* ModuleDeclaration */: + case 279 /* SourceFile */: + case 242 /* TypeAliasDeclaration */: + case 304 /* JSDocTypedefTag */: + case 297 /* JSDocCallbackTag */: + return true; + case 157 /* Constructor */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 237 /* VariableDeclaration */: + return hasSomeImportantChild(item); + case 197 /* ArrowFunction */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + return isTopLevelFunctionDeclaration(item); + default: + return false; + } + function isTopLevelFunctionDeclaration(item) { + if (!item.node.body) { + return false; + } + switch (navigationBarNodeKind(item.parent)) { + case 245 /* ModuleBlock */: + case 279 /* SourceFile */: + case 156 /* MethodDeclaration */: + case 157 /* Constructor */: + return true; + default: + return hasSomeImportantChild(item); + } + } + function hasSomeImportantChild(item) { + return ts.some(item.children, function (child) { + var childKind = navigationBarNodeKind(child); + return childKind !== 237 /* VariableDeclaration */ && childKind !== 186 /* BindingElement */; + }); + } + } + } + function convertToTree(n) { + return { + text: getItemName(n.node, n.name), + kind: ts.getNodeKind(n.node), + kindModifiers: getModifiers(n.node), + spans: getSpans(n), + nameSpan: n.name && getNodeSpan(n.name), + childItems: ts.map(n.children, convertToTree) + }; + } + function convertToTopLevelItem(n) { + return { + text: getItemName(n.node, n.name), + kind: ts.getNodeKind(n.node), + kindModifiers: getModifiers(n.node), + spans: getSpans(n), + childItems: ts.map(n.children, convertToChildItem) || emptyChildItemArray, + indent: n.indent, + bolded: false, + grayed: false + }; + function convertToChildItem(n) { + return { + text: getItemName(n.node, n.name), + kind: ts.getNodeKind(n.node), + kindModifiers: ts.getNodeModifiers(n.node), + spans: getSpans(n), + childItems: emptyChildItemArray, + indent: 0, + bolded: false, + grayed: false + }; + } + } + function getSpans(n) { + var spans = [getNodeSpan(n.node)]; + if (n.additionalNodes) { + for (var _i = 0, _a = n.additionalNodes; _i < _a.length; _i++) { + var node = _a[_i]; + spans.push(getNodeSpan(node)); + } + } + return spans; + } + function getModuleName(moduleDeclaration) { + // We want to maintain quotation marks. + if (ts.isAmbientModule(moduleDeclaration)) { + return ts.getTextOfNode(moduleDeclaration.name); + } + // Otherwise, we need to aggregate each identifier to build up the qualified name. + var result = []; + result.push(ts.getTextOfIdentifierOrLiteral(moduleDeclaration.name)); + while (moduleDeclaration.body && moduleDeclaration.body.kind === 244 /* ModuleDeclaration */) { + moduleDeclaration = moduleDeclaration.body; + result.push(ts.getTextOfIdentifierOrLiteral(moduleDeclaration.name)); + } + return result.join("."); + } + /** + * For 'module A.B.C', we want to get the node for 'C'. + * We store 'A' as associated with a NavNode, and use getModuleName to traverse down again. + */ + function getInteriorModule(decl) { + return decl.body && ts.isModuleDeclaration(decl.body) ? getInteriorModule(decl.body) : decl; + } + function isComputedProperty(member) { + return !member.name || member.name.kind === 149 /* ComputedPropertyName */; + } + function getNodeSpan(node) { + return node.kind === 279 /* SourceFile */ ? ts.createTextSpanFromRange(node) : ts.createTextSpanFromNode(node, curSourceFile); + } + function getModifiers(node) { + if (node.parent && node.parent.kind === 237 /* VariableDeclaration */) { + node = node.parent; + } + return ts.getNodeModifiers(node); + } + function getFunctionOrClassName(node) { + var parent = node.parent; + if (node.name && ts.getFullWidth(node.name) > 0) { + return ts.declarationNameToString(node.name); + } + // See if it is a var initializer. If so, use the var name. + else if (ts.isVariableDeclaration(parent)) { + return ts.declarationNameToString(parent.name); + } + // See if it is of the form " = function(){...}". If so, use the text from the left-hand side. + else if (ts.isBinaryExpression(parent) && parent.operatorToken.kind === 59 /* EqualsToken */) { + return nodeText(parent.left).replace(whiteSpaceRegex, ""); + } + // See if it is a property assignment, and if so use the property name + else if (ts.isPropertyAssignment(parent)) { + return nodeText(parent.name); + } + // Default exports are named "default" + else if (ts.getModifierFlags(node) & 512 /* Default */) { + return "default"; + } + else if (ts.isClassLike(node)) { + return ""; + } + else if (ts.isCallExpression(parent)) { + var name = getCalledExpressionName(parent.expression); + if (name !== undefined) { + var args = ts.mapDefined(parent.arguments, function (a) { return ts.isStringLiteral(a) ? a.getText(curSourceFile) : undefined; }).join(", "); + return name + "(" + args + ") callback"; + } + } + return ""; + } + function getCalledExpressionName(expr) { + if (ts.isIdentifier(expr)) { + return expr.text; + } + else if (ts.isPropertyAccessExpression(expr)) { + var left = getCalledExpressionName(expr.expression); + var right = expr.name.text; + return left === undefined ? right : left + "." + right; + } + else { + return undefined; + } + } + function isFunctionOrClassExpression(node) { + switch (node.kind) { + case 197 /* ArrowFunction */: + case 196 /* FunctionExpression */: + case 209 /* ClassExpression */: + return true; + default: + return false; + } + } + })(NavigationBar = ts.NavigationBar || (ts.NavigationBar = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var OrganizeImports; + (function (OrganizeImports) { + /** + * Organize imports by: + * 1) Removing unused imports + * 2) Coalescing imports from the same module + * 3) Sorting imports + */ + function organizeImports(sourceFile, formatContext, host, program, _preferences) { + var changeTracker = ts.textChanges.ChangeTracker.fromContext({ host: host, formatContext: formatContext }); + var coalesceAndOrganizeImports = function (importGroup) { return coalesceImports(removeUnusedImports(importGroup, sourceFile, program)); }; + // All of the old ImportDeclarations in the file, in syntactic order. + var topLevelImportDecls = sourceFile.statements.filter(ts.isImportDeclaration); + organizeImportsWorker(topLevelImportDecls, coalesceAndOrganizeImports); + // All of the old ExportDeclarations in the file, in syntactic order. + var topLevelExportDecls = sourceFile.statements.filter(ts.isExportDeclaration); + organizeImportsWorker(topLevelExportDecls, coalesceExports); + for (var _i = 0, _a = sourceFile.statements.filter(ts.isAmbientModule); _i < _a.length; _i++) { + var ambientModule = _a[_i]; + var ambientModuleBody = getModuleBlock(ambientModule); // TODO: GH#18217 + var ambientModuleImportDecls = ambientModuleBody.statements.filter(ts.isImportDeclaration); + organizeImportsWorker(ambientModuleImportDecls, coalesceAndOrganizeImports); + var ambientModuleExportDecls = ambientModuleBody.statements.filter(ts.isExportDeclaration); + organizeImportsWorker(ambientModuleExportDecls, coalesceExports); + } + return changeTracker.getChanges(); + function organizeImportsWorker(oldImportDecls, coalesce) { + if (ts.length(oldImportDecls) === 0) { + return; + } + // Special case: normally, we'd expect leading and trailing trivia to follow each import + // around as it's sorted. However, we do not want this to happen for leading trivia + // on the first import because it is probably the header comment for the file. + // Consider: we could do a more careful check that this trivia is actually a header, + // but the consequences of being wrong are very minor. + ts.suppressLeadingTrivia(oldImportDecls[0]); + var oldImportGroups = ts.group(oldImportDecls, function (importDecl) { return getExternalModuleName(importDecl.moduleSpecifier); }); + var sortedImportGroups = ts.stableSort(oldImportGroups, function (group1, group2) { return compareModuleSpecifiers(group1[0].moduleSpecifier, group2[0].moduleSpecifier); }); + var newImportDecls = ts.flatMap(sortedImportGroups, function (importGroup) { + return getExternalModuleName(importGroup[0].moduleSpecifier) + ? coalesce(importGroup) + : importGroup; + }); + // Delete or replace the first import. + if (newImportDecls.length === 0) { + changeTracker.delete(sourceFile, oldImportDecls[0]); + } + else { + // Note: Delete the surrounding trivia because it will have been retained in newImportDecls. + changeTracker.replaceNodeWithNodes(sourceFile, oldImportDecls[0], newImportDecls, { + useNonAdjustedStartPosition: true, + useNonAdjustedEndPosition: false, + suffix: ts.getNewLineOrDefaultFromHost(host, formatContext.options), + }); + } + // Delete any subsequent imports. + for (var i = 1; i < oldImportDecls.length; i++) { + changeTracker.delete(sourceFile, oldImportDecls[i]); + } + } + } + OrganizeImports.organizeImports = organizeImports; + function getModuleBlock(moduleDecl) { + var body = moduleDecl.body; + return body && !ts.isIdentifier(body) ? (ts.isModuleBlock(body) ? body : getModuleBlock(body)) : undefined; + } + function removeUnusedImports(oldImports, sourceFile, program) { + var typeChecker = program.getTypeChecker(); + var jsxNamespace = typeChecker.getJsxNamespace(); + var jsxElementsPresent = !!(sourceFile.transformFlags & 4 /* ContainsJsx */); + var usedImports = []; + for (var _i = 0, oldImports_1 = oldImports; _i < oldImports_1.length; _i++) { + var importDecl = oldImports_1[_i]; + var importClause = importDecl.importClause; + if (!importClause) { + // Imports without import clauses are assumed to be included for their side effects and are not removed. + usedImports.push(importDecl); + continue; + } + var name = importClause.name, namedBindings = importClause.namedBindings; + // Default import + if (name && !isDeclarationUsed(name)) { + name = undefined; + } + if (namedBindings) { + if (ts.isNamespaceImport(namedBindings)) { + // Namespace import + if (!isDeclarationUsed(namedBindings.name)) { + namedBindings = undefined; + } + } + else { + // List of named imports + var newElements = namedBindings.elements.filter(function (e) { return isDeclarationUsed(e.name); }); + if (newElements.length < namedBindings.elements.length) { + namedBindings = newElements.length + ? ts.updateNamedImports(namedBindings, newElements) + : undefined; + } + } + } + if (name || namedBindings) { + usedImports.push(updateImportDeclarationAndClause(importDecl, name, namedBindings)); + } + } + return usedImports; + function isDeclarationUsed(identifier) { + // The JSX factory symbol is always used if JSX elements are present - even if they are not allowed. + return jsxElementsPresent && (identifier.text === jsxNamespace) || ts.FindAllReferences.Core.isSymbolReferencedInFile(identifier, typeChecker, sourceFile); + } + } + function getExternalModuleName(specifier) { + return specifier !== undefined && ts.isStringLiteralLike(specifier) + ? specifier.text + : undefined; + } + // Internal for testing + /** + * @param importGroup a list of ImportDeclarations, all with the same module name. + */ + function coalesceImports(importGroup) { + if (importGroup.length === 0) { + return importGroup; + } + var _a = getCategorizedImports(importGroup), importWithoutClause = _a.importWithoutClause, defaultImports = _a.defaultImports, namespaceImports = _a.namespaceImports, namedImports = _a.namedImports; + var coalescedImports = []; + if (importWithoutClause) { + coalescedImports.push(importWithoutClause); + } + // Normally, we don't combine default and namespace imports, but it would be silly to + // produce two import declarations in this special case. + if (defaultImports.length === 1 && namespaceImports.length === 1 && namedImports.length === 0) { + // Add the namespace import to the existing default ImportDeclaration. + var defaultImport = defaultImports[0]; + coalescedImports.push(updateImportDeclarationAndClause(defaultImport, defaultImport.importClause.name, namespaceImports[0].importClause.namedBindings)); // TODO: GH#18217 + return coalescedImports; + } + var sortedNamespaceImports = ts.stableSort(namespaceImports, function (i1, i2) { + return compareIdentifiers(i1.importClause.namedBindings.name, i2.importClause.namedBindings.name); + }); // TODO: GH#18217 + for (var _i = 0, sortedNamespaceImports_1 = sortedNamespaceImports; _i < sortedNamespaceImports_1.length; _i++) { + var namespaceImport = sortedNamespaceImports_1[_i]; + // Drop the name, if any + coalescedImports.push(updateImportDeclarationAndClause(namespaceImport, /*name*/ undefined, namespaceImport.importClause.namedBindings)); // TODO: GH#18217 + } + if (defaultImports.length === 0 && namedImports.length === 0) { + return coalescedImports; + } + var newDefaultImport; + var newImportSpecifiers = []; + if (defaultImports.length === 1) { + newDefaultImport = defaultImports[0].importClause.name; + } + else { + for (var _b = 0, defaultImports_1 = defaultImports; _b < defaultImports_1.length; _b++) { + var defaultImport = defaultImports_1[_b]; + newImportSpecifiers.push(ts.createImportSpecifier(ts.createIdentifier("default"), defaultImport.importClause.name)); // TODO: GH#18217 + } + } + newImportSpecifiers.push.apply(newImportSpecifiers, ts.flatMap(namedImports, function (i) { return i.importClause.namedBindings.elements; })); // TODO: GH#18217 + var sortedImportSpecifiers = sortSpecifiers(newImportSpecifiers); + var importDecl = defaultImports.length > 0 + ? defaultImports[0] + : namedImports[0]; + var newNamedImports = sortedImportSpecifiers.length === 0 + ? newDefaultImport + ? undefined + : ts.createNamedImports(ts.emptyArray) + : namedImports.length === 0 + ? ts.createNamedImports(sortedImportSpecifiers) + : ts.updateNamedImports(namedImports[0].importClause.namedBindings, sortedImportSpecifiers); // TODO: GH#18217 + coalescedImports.push(updateImportDeclarationAndClause(importDecl, newDefaultImport, newNamedImports)); + return coalescedImports; + /* + * Returns entire import declarations because they may already have been rewritten and + * may lack parent pointers. The desired parts can easily be recovered based on the + * categorization. + * + * NB: There may be overlap between `defaultImports` and `namespaceImports`/`namedImports`. + */ + function getCategorizedImports(importGroup) { + var importWithoutClause; + var defaultImports = []; + var namespaceImports = []; + var namedImports = []; + for (var _i = 0, importGroup_1 = importGroup; _i < importGroup_1.length; _i++) { + var importDeclaration = importGroup_1[_i]; + if (importDeclaration.importClause === undefined) { + // Only the first such import is interesting - the others are redundant. + // Note: Unfortunately, we will lose trivia that was on this node. + importWithoutClause = importWithoutClause || importDeclaration; + continue; + } + var _a = importDeclaration.importClause, name = _a.name, namedBindings = _a.namedBindings; + if (name) { + defaultImports.push(importDeclaration); + } + if (namedBindings) { + if (ts.isNamespaceImport(namedBindings)) { + namespaceImports.push(importDeclaration); + } + else { + namedImports.push(importDeclaration); + } + } + } + return { + importWithoutClause: importWithoutClause, + defaultImports: defaultImports, + namespaceImports: namespaceImports, + namedImports: namedImports, + }; + } + } + OrganizeImports.coalesceImports = coalesceImports; + // Internal for testing + /** + * @param exportGroup a list of ExportDeclarations, all with the same module name. + */ + function coalesceExports(exportGroup) { + if (exportGroup.length === 0) { + return exportGroup; + } + var _a = getCategorizedExports(exportGroup), exportWithoutClause = _a.exportWithoutClause, namedExports = _a.namedExports; + var coalescedExports = []; + if (exportWithoutClause) { + coalescedExports.push(exportWithoutClause); + } + if (namedExports.length === 0) { + return coalescedExports; + } + var newExportSpecifiers = []; + newExportSpecifiers.push.apply(newExportSpecifiers, ts.flatMap(namedExports, function (i) { return (i.exportClause).elements; })); + var sortedExportSpecifiers = sortSpecifiers(newExportSpecifiers); + var exportDecl = namedExports[0]; + coalescedExports.push(ts.updateExportDeclaration(exportDecl, exportDecl.decorators, exportDecl.modifiers, ts.updateNamedExports(exportDecl.exportClause, sortedExportSpecifiers), exportDecl.moduleSpecifier)); + return coalescedExports; + /* + * Returns entire export declarations because they may already have been rewritten and + * may lack parent pointers. The desired parts can easily be recovered based on the + * categorization. + */ + function getCategorizedExports(exportGroup) { + var exportWithoutClause; + var namedExports = []; + for (var _i = 0, exportGroup_1 = exportGroup; _i < exportGroup_1.length; _i++) { + var exportDeclaration = exportGroup_1[_i]; + if (exportDeclaration.exportClause === undefined) { + // Only the first such export is interesting - the others are redundant. + // Note: Unfortunately, we will lose trivia that was on this node. + exportWithoutClause = exportWithoutClause || exportDeclaration; + } + else { + namedExports.push(exportDeclaration); + } + } + return { + exportWithoutClause: exportWithoutClause, + namedExports: namedExports, + }; + } + } + OrganizeImports.coalesceExports = coalesceExports; + function updateImportDeclarationAndClause(importDeclaration, name, namedBindings) { + return ts.updateImportDeclaration(importDeclaration, importDeclaration.decorators, importDeclaration.modifiers, ts.updateImportClause(importDeclaration.importClause, name, namedBindings), // TODO: GH#18217 + importDeclaration.moduleSpecifier); + } + function sortSpecifiers(specifiers) { + return ts.stableSort(specifiers, function (s1, s2) { + return compareIdentifiers(s1.propertyName || s1.name, s2.propertyName || s2.name) || + compareIdentifiers(s1.name, s2.name); + }); + } + /* internal */ // Exported for testing + function compareModuleSpecifiers(m1, m2) { + var name1 = getExternalModuleName(m1); + var name2 = getExternalModuleName(m2); + return ts.compareBooleans(name1 === undefined, name2 === undefined) || + ts.compareBooleans(ts.isExternalModuleNameRelative(name1), ts.isExternalModuleNameRelative(name2)) || + ts.compareStringsCaseInsensitive(name1, name2); + } + OrganizeImports.compareModuleSpecifiers = compareModuleSpecifiers; + function compareIdentifiers(s1, s2) { + return ts.compareStringsCaseInsensitive(s1.text, s2.text); + } + })(OrganizeImports = ts.OrganizeImports || (ts.OrganizeImports = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var OutliningElementsCollector; + (function (OutliningElementsCollector) { + function collectElements(sourceFile, cancellationToken) { + var res = []; + addNodeOutliningSpans(sourceFile, cancellationToken, res); + addRegionOutliningSpans(sourceFile, res); + return res.sort(function (span1, span2) { return span1.textSpan.start - span2.textSpan.start; }); + } + OutliningElementsCollector.collectElements = collectElements; + function addNodeOutliningSpans(sourceFile, cancellationToken, out) { + var depthRemaining = 40; + var current = 0; + var statements = sourceFile.statements; + var n = statements.length; + while (current < n) { + while (current < n && !ts.isAnyImportSyntax(statements[current])) { + visitNonImportNode(statements[current]); + current++; + } + if (current === n) + break; + var firstImport = current; + while (current < n && ts.isAnyImportSyntax(statements[current])) { + addOutliningForLeadingCommentsForNode(statements[current], sourceFile, cancellationToken, out); + current++; + } + var lastImport = current - 1; + if (lastImport !== firstImport) { + out.push(createOutliningSpanFromBounds(ts.findChildOfKind(statements[firstImport], 92 /* ImportKeyword */, sourceFile).getStart(sourceFile), statements[lastImport].getEnd(), "imports" /* Imports */)); + } + } + function visitNonImportNode(n) { + if (depthRemaining === 0) + return; + cancellationToken.throwIfCancellationRequested(); + if (ts.isDeclaration(n)) { + addOutliningForLeadingCommentsForNode(n, sourceFile, cancellationToken, out); + } + var span = getOutliningSpanForNode(n, sourceFile); + if (span) + out.push(span); + depthRemaining--; + if (ts.isIfStatement(n) && n.elseStatement && ts.isIfStatement(n.elseStatement)) { + // Consider an 'else if' to be on the same depth as the 'if'. + visitNonImportNode(n.expression); + visitNonImportNode(n.thenStatement); + depthRemaining++; + visitNonImportNode(n.elseStatement); + depthRemaining--; + } + else { + n.forEachChild(visitNonImportNode); + } + depthRemaining++; + } + } + function addRegionOutliningSpans(sourceFile, out) { + var regions = []; + var lineStarts = sourceFile.getLineStarts(); + for (var i = 0; i < lineStarts.length; i++) { + var currentLineStart = lineStarts[i]; + var lineEnd = i + 1 === lineStarts.length ? sourceFile.getEnd() : lineStarts[i + 1] - 1; + var lineText = sourceFile.text.substring(currentLineStart, lineEnd); + var result = isRegionDelimiter(lineText); + if (!result || ts.isInComment(sourceFile, currentLineStart)) { + continue; + } + if (!result[1]) { + var span = ts.createTextSpanFromBounds(sourceFile.text.indexOf("//", currentLineStart), lineEnd); + regions.push(createOutliningSpan(span, "region" /* Region */, span, /*autoCollapse*/ false, result[2] || "#region")); + } + else { + var region = regions.pop(); + if (region) { + region.textSpan.length = lineEnd - region.textSpan.start; + region.hintSpan.length = lineEnd - region.textSpan.start; + out.push(region); + } + } + } + } + var regionDelimiterRegExp = /^\s*\/\/\s*#(end)?region(?:\s+(.*))?(?:\r)?$/; + function isRegionDelimiter(lineText) { + return regionDelimiterRegExp.exec(lineText); + } + function addOutliningForLeadingCommentsForNode(n, sourceFile, cancellationToken, out) { + var comments = ts.getLeadingCommentRangesOfNode(n, sourceFile); + if (!comments) + return; + var firstSingleLineCommentStart = -1; + var lastSingleLineCommentEnd = -1; + var singleLineCommentCount = 0; + var sourceText = sourceFile.getFullText(); + for (var _i = 0, comments_1 = comments; _i < comments_1.length; _i++) { + var _a = comments_1[_i], kind = _a.kind, pos = _a.pos, end = _a.end; + cancellationToken.throwIfCancellationRequested(); + switch (kind) { + case 2 /* SingleLineCommentTrivia */: + // never fold region delimiters into single-line comment regions + var commentText = sourceText.slice(pos, end); + if (isRegionDelimiter(commentText)) { + combineAndAddMultipleSingleLineComments(); + singleLineCommentCount = 0; + break; + } + // For single line comments, combine consecutive ones (2 or more) into + // a single span from the start of the first till the end of the last + if (singleLineCommentCount === 0) { + firstSingleLineCommentStart = pos; + } + lastSingleLineCommentEnd = end; + singleLineCommentCount++; + break; + case 3 /* MultiLineCommentTrivia */: + combineAndAddMultipleSingleLineComments(); + out.push(createOutliningSpanFromBounds(pos, end, "comment" /* Comment */)); + singleLineCommentCount = 0; + break; + default: + ts.Debug.assertNever(kind); + } + } + combineAndAddMultipleSingleLineComments(); + function combineAndAddMultipleSingleLineComments() { + // Only outline spans of two or more consecutive single line comments + if (singleLineCommentCount > 1) { + out.push(createOutliningSpanFromBounds(firstSingleLineCommentStart, lastSingleLineCommentEnd, "comment" /* Comment */)); + } + } + } + function createOutliningSpanFromBounds(pos, end, kind) { + return createOutliningSpan(ts.createTextSpanFromBounds(pos, end), kind); + } + function getOutliningSpanForNode(n, sourceFile) { + switch (n.kind) { + case 218 /* Block */: + if (ts.isFunctionBlock(n)) { + return spanForNode(n.parent, /*autoCollapse*/ n.parent.kind !== 197 /* ArrowFunction */); + } + // Check if the block is standalone, or 'attached' to some parent statement. + // If the latter, we want to collapse the block, but consider its hint span + // to be the entire span of the parent. + switch (n.parent.kind) { + case 223 /* DoStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + case 225 /* ForStatement */: + case 222 /* IfStatement */: + case 224 /* WhileStatement */: + case 231 /* WithStatement */: + case 274 /* CatchClause */: + return spanForNode(n.parent); + case 235 /* TryStatement */: + // Could be the try-block, or the finally-block. + var tryStatement = n.parent; + if (tryStatement.tryBlock === n) { + return spanForNode(n.parent); + } + else if (tryStatement.finallyBlock === n) { + return spanForNode(ts.findChildOfKind(tryStatement, 88 /* FinallyKeyword */, sourceFile)); + } + // falls through + default: + // Block was a standalone block. In this case we want to only collapse + // the span of the block, independent of any parent span. + return createOutliningSpan(ts.createTextSpanFromNode(n, sourceFile), "code" /* Code */); + } + case 245 /* ModuleBlock */: + return spanForNode(n.parent); + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + case 243 /* EnumDeclaration */: + case 246 /* CaseBlock */: + return spanForNode(n); + case 188 /* ObjectLiteralExpression */: + return spanForObjectOrArrayLiteral(n); + case 187 /* ArrayLiteralExpression */: + return spanForObjectOrArrayLiteral(n, 22 /* OpenBracketToken */); + case 260 /* JsxElement */: + return spanForJSXElement(n); + case 261 /* JsxSelfClosingElement */: + case 262 /* JsxOpeningElement */: + return spanForJSXAttributes(n.attributes); + } + function spanForJSXElement(node) { + var textSpan = ts.createTextSpanFromBounds(node.openingElement.getStart(sourceFile), node.closingElement.getEnd()); + var tagName = node.openingElement.tagName.getText(sourceFile); + var bannerText = "<" + tagName + ">..."; + return createOutliningSpan(textSpan, "code" /* Code */, textSpan, /*autoCollapse*/ false, bannerText); + } + function spanForJSXAttributes(node) { + if (node.properties.length === 0) { + return undefined; + } + return createOutliningSpanFromBounds(node.getStart(sourceFile), node.getEnd(), "code" /* Code */); + } + function spanForObjectOrArrayLiteral(node, open) { + if (open === void 0) { open = 18 /* OpenBraceToken */; } + // If the block has no leading keywords and is inside an array literal, + // we only want to collapse the span of the block. + // Otherwise, the collapsed section will include the end of the previous line. + return spanForNode(node, /*autoCollapse*/ false, /*useFullStart*/ !ts.isArrayLiteralExpression(node.parent), open); + } + function spanForNode(hintSpanNode, autoCollapse, useFullStart, open) { + if (autoCollapse === void 0) { autoCollapse = false; } + if (useFullStart === void 0) { useFullStart = true; } + if (open === void 0) { open = 18 /* OpenBraceToken */; } + var openToken = ts.findChildOfKind(n, open, sourceFile); + var close = open === 18 /* OpenBraceToken */ ? 19 /* CloseBraceToken */ : 23 /* CloseBracketToken */; + var closeToken = ts.findChildOfKind(n, close, sourceFile); + if (!openToken || !closeToken) { + return undefined; + } + var textSpan = ts.createTextSpanFromBounds(useFullStart ? openToken.getFullStart() : openToken.getStart(sourceFile), closeToken.getEnd()); + return createOutliningSpan(textSpan, "code" /* Code */, ts.createTextSpanFromNode(hintSpanNode, sourceFile), autoCollapse); + } + } + function createOutliningSpan(textSpan, kind, hintSpan, autoCollapse, bannerText) { + if (hintSpan === void 0) { hintSpan = textSpan; } + if (autoCollapse === void 0) { autoCollapse = false; } + if (bannerText === void 0) { bannerText = "..."; } + return { textSpan: textSpan, kind: kind, hintSpan: hintSpan, bannerText: bannerText, autoCollapse: autoCollapse }; + } + })(OutliningElementsCollector = ts.OutliningElementsCollector || (ts.OutliningElementsCollector = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + // Note(cyrusn): this enum is ordered from strongest match type to weakest match type. + var PatternMatchKind; + (function (PatternMatchKind) { + PatternMatchKind[PatternMatchKind["exact"] = 0] = "exact"; + PatternMatchKind[PatternMatchKind["prefix"] = 1] = "prefix"; + PatternMatchKind[PatternMatchKind["substring"] = 2] = "substring"; + PatternMatchKind[PatternMatchKind["camelCase"] = 3] = "camelCase"; + })(PatternMatchKind = ts.PatternMatchKind || (ts.PatternMatchKind = {})); + function createPatternMatch(kind, isCaseSensitive) { + return { + kind: kind, + isCaseSensitive: isCaseSensitive + }; + } + function createPatternMatcher(pattern) { + // We'll often see the same candidate string many times when searching (For example, when + // we see the name of a module that is used everywhere, or the name of an overload). As + // such, we cache the information we compute about the candidate for the life of this + // pattern matcher so we don't have to compute it multiple times. + var stringToWordSpans = ts.createMap(); + var dotSeparatedSegments = pattern.trim().split(".").map(function (p) { return createSegment(p.trim()); }); + // A segment is considered invalid if we couldn't find any words in it. + if (dotSeparatedSegments.some(function (segment) { return !segment.subWordTextChunks.length; })) + return undefined; + return { + getFullMatch: function (containers, candidate) { return getFullMatch(containers, candidate, dotSeparatedSegments, stringToWordSpans); }, + getMatchForLastSegmentOfPattern: function (candidate) { return matchSegment(candidate, ts.last(dotSeparatedSegments), stringToWordSpans); }, + patternContainsDots: dotSeparatedSegments.length > 1 + }; + } + ts.createPatternMatcher = createPatternMatcher; + function getFullMatch(candidateContainers, candidate, dotSeparatedSegments, stringToWordSpans) { + // First, check that the last part of the dot separated pattern matches the name of the + // candidate. If not, then there's no point in proceeding and doing the more + // expensive work. + var candidateMatch = matchSegment(candidate, ts.last(dotSeparatedSegments), stringToWordSpans); + if (!candidateMatch) { + return undefined; + } + // -1 because the last part was checked against the name, and only the rest + // of the parts are checked against the container. + if (dotSeparatedSegments.length - 1 > candidateContainers.length) { + // There weren't enough container parts to match against the pattern parts. + // So this definitely doesn't match. + return undefined; + } + var bestMatch; + for (var i = dotSeparatedSegments.length - 2, j = candidateContainers.length - 1; i >= 0; i -= 1, j -= 1) { + bestMatch = betterMatch(bestMatch, matchSegment(candidateContainers[j], dotSeparatedSegments[i], stringToWordSpans)); + } + return bestMatch; + } + function getWordSpans(word, stringToWordSpans) { + var spans = stringToWordSpans.get(word); + if (!spans) { + stringToWordSpans.set(word, spans = breakIntoWordSpans(word)); + } + return spans; + } + function matchTextChunk(candidate, chunk, stringToWordSpans) { + var index = indexOfIgnoringCase(candidate, chunk.textLowerCase); + if (index === 0) { + // a) Check if the word is a prefix of the candidate, in a case insensitive or + // sensitive manner. If it does, return that there was an exact match if the word and candidate are the same length, else a prefix match. + return createPatternMatch(chunk.text.length === candidate.length ? PatternMatchKind.exact : PatternMatchKind.prefix, /*isCaseSensitive:*/ ts.startsWith(candidate, chunk.text)); + } + if (chunk.isLowerCase) { + if (index === -1) + return undefined; + // b) If the part is entirely lowercase, then check if it is contained anywhere in the + // candidate in a case insensitive manner. If so, return that there was a substring + // match. + // + // Note: We only have a substring match if the lowercase part is prefix match of some + // word part. That way we don't match something like 'Class' when the user types 'a'. + // But we would match 'FooAttribute' (since 'Attribute' starts with 'a'). + var wordSpans = getWordSpans(candidate, stringToWordSpans); + for (var _i = 0, wordSpans_1 = wordSpans; _i < wordSpans_1.length; _i++) { + var span = wordSpans_1[_i]; + if (partStartsWith(candidate, span, chunk.text, /*ignoreCase:*/ true)) { + return createPatternMatch(PatternMatchKind.substring, /*isCaseSensitive:*/ partStartsWith(candidate, span, chunk.text, /*ignoreCase:*/ false)); + } + } + // c) Is the pattern a substring of the candidate starting on one of the candidate's word boundaries? + // We could check every character boundary start of the candidate for the pattern. However, that's + // an m * n operation in the wost case. Instead, find the first instance of the pattern + // substring, and see if it starts on a capital letter. It seems unlikely that the user will try to + // filter the list based on a substring that starts on a capital letter and also with a lowercase one. + // (Pattern: fogbar, Candidate: quuxfogbarFogBar). + if (chunk.text.length < candidate.length && isUpperCaseLetter(candidate.charCodeAt(index))) { + return createPatternMatch(PatternMatchKind.substring, /*isCaseSensitive:*/ false); + } + } + else { + // d) If the part was not entirely lowercase, then check if it is contained in the + // candidate in a case *sensitive* manner. If so, return that there was a substring + // match. + if (candidate.indexOf(chunk.text) > 0) { + return createPatternMatch(PatternMatchKind.substring, /*isCaseSensitive:*/ true); + } + // e) If the part was not entirely lowercase, then attempt a camel cased match as well. + if (chunk.characterSpans.length > 0) { + var candidateParts = getWordSpans(candidate, stringToWordSpans); + var isCaseSensitive = tryCamelCaseMatch(candidate, candidateParts, chunk, /*ignoreCase:*/ false) ? true + : tryCamelCaseMatch(candidate, candidateParts, chunk, /*ignoreCase:*/ true) ? false : undefined; + if (isCaseSensitive !== undefined) { + return createPatternMatch(PatternMatchKind.camelCase, isCaseSensitive); + } + } + } + } + function matchSegment(candidate, segment, stringToWordSpans) { + // First check if the segment matches as is. This is also useful if the segment contains + // characters we would normally strip when splitting into parts that we also may want to + // match in the candidate. For example if the segment is "@int" and the candidate is + // "@int", then that will show up as an exact match here. + // + // Note: if the segment contains a space or an asterisk then we must assume that it's a + // multi-word segment. + if (every(segment.totalTextChunk.text, function (ch) { return ch !== 32 /* space */ && ch !== 42 /* asterisk */; })) { + var match = matchTextChunk(candidate, segment.totalTextChunk, stringToWordSpans); + if (match) + return match; + } + // The logic for pattern matching is now as follows: + // + // 1) Break the segment passed in into words. Breaking is rather simple and a + // good way to think about it that if gives you all the individual alphanumeric words + // of the pattern. + // + // 2) For each word try to match the word against the candidate value. + // + // 3) Matching is as follows: + // + // a) Check if the word is a prefix of the candidate, in a case insensitive or + // sensitive manner. If it does, return that there was an exact match if the word and candidate are the same length, else a prefix match. + // + // If the word is entirely lowercase: + // b) Then check if it is contained anywhere in the + // candidate in a case insensitive manner. If so, return that there was a substring + // match. + // + // Note: We only have a substring match if the lowercase part is prefix match of + // some word part. That way we don't match something like 'Class' when the user + // types 'a'. But we would match 'FooAttribute' (since 'Attribute' starts with + // 'a'). + // + // c) The word is all lower case. Is it a case insensitive substring of the candidate starting + // on a part boundary of the candidate? + // + // Else: + // d) If the word was not entirely lowercase, then check if it is contained in the + // candidate in a case *sensitive* manner. If so, return that there was a substring + // match. + // + // e) If the word was not entirely lowercase, then attempt a camel cased match as + // well. + // + // Only if all words have some sort of match is the pattern considered matched. + var subWordTextChunks = segment.subWordTextChunks; + var bestMatch; + for (var _i = 0, subWordTextChunks_1 = subWordTextChunks; _i < subWordTextChunks_1.length; _i++) { + var subWordTextChunk = subWordTextChunks_1[_i]; + bestMatch = betterMatch(bestMatch, matchTextChunk(candidate, subWordTextChunk, stringToWordSpans)); + } + return bestMatch; + } + function betterMatch(a, b) { + return ts.min(a, b, compareMatches); + } + function compareMatches(a, b) { + return a === undefined ? 1 /* GreaterThan */ : b === undefined ? -1 /* LessThan */ + : ts.compareValues(a.kind, b.kind) || ts.compareBooleans(!a.isCaseSensitive, !b.isCaseSensitive); + } + function partStartsWith(candidate, candidateSpan, pattern, ignoreCase, patternSpan) { + if (patternSpan === void 0) { patternSpan = { start: 0, length: pattern.length }; } + return patternSpan.length <= candidateSpan.length // If pattern part is longer than the candidate part there can never be a match. + && everyInRange(0, patternSpan.length, function (i) { return equalChars(pattern.charCodeAt(patternSpan.start + i), candidate.charCodeAt(candidateSpan.start + i), ignoreCase); }); + } + function equalChars(ch1, ch2, ignoreCase) { + return ignoreCase ? toLowerCase(ch1) === toLowerCase(ch2) : ch1 === ch2; + } + function tryCamelCaseMatch(candidate, candidateParts, chunk, ignoreCase) { + var chunkCharacterSpans = chunk.characterSpans; + // Note: we may have more pattern parts than candidate parts. This is because multiple + // pattern parts may match a candidate part. For example "SiUI" against "SimpleUI". + // We'll have 3 pattern parts Si/U/I against two candidate parts Simple/UI. However, U + // and I will both match in UI. + var currentCandidate = 0; + var currentChunkSpan = 0; + var firstMatch; + var contiguous; + while (true) { + // Let's consider our termination cases + if (currentChunkSpan === chunkCharacterSpans.length) { + return true; + } + else if (currentCandidate === candidateParts.length) { + // No match, since we still have more of the pattern to hit + return false; + } + var candidatePart = candidateParts[currentCandidate]; + var gotOneMatchThisCandidate = false; + // Consider the case of matching SiUI against SimpleUIElement. The candidate parts + // will be Simple/UI/Element, and the pattern parts will be Si/U/I. We'll match 'Si' + // against 'Simple' first. Then we'll match 'U' against 'UI'. However, we want to + // still keep matching pattern parts against that candidate part. + for (; currentChunkSpan < chunkCharacterSpans.length; currentChunkSpan++) { + var chunkCharacterSpan = chunkCharacterSpans[currentChunkSpan]; + if (gotOneMatchThisCandidate) { + // We've already gotten one pattern part match in this candidate. We will + // only continue trying to consumer pattern parts if the last part and this + // part are both upper case. + if (!isUpperCaseLetter(chunk.text.charCodeAt(chunkCharacterSpans[currentChunkSpan - 1].start)) || + !isUpperCaseLetter(chunk.text.charCodeAt(chunkCharacterSpans[currentChunkSpan].start))) { + break; + } + } + if (!partStartsWith(candidate, candidatePart, chunk.text, ignoreCase, chunkCharacterSpan)) { + break; + } + gotOneMatchThisCandidate = true; + firstMatch = firstMatch === undefined ? currentCandidate : firstMatch; + // If we were contiguous, then keep that value. If we weren't, then keep that + // value. If we don't know, then set the value to 'true' as an initial match is + // obviously contiguous. + contiguous = contiguous === undefined ? true : contiguous; + candidatePart = ts.createTextSpan(candidatePart.start + chunkCharacterSpan.length, candidatePart.length - chunkCharacterSpan.length); + } + // Check if we matched anything at all. If we didn't, then we need to unset the + // contiguous bit if we currently had it set. + // If we haven't set the bit yet, then that means we haven't matched anything so + // far, and we don't want to change that. + if (!gotOneMatchThisCandidate && contiguous !== undefined) { + contiguous = false; + } + // Move onto the next candidate. + currentCandidate++; + } + } + function createSegment(text) { + return { + totalTextChunk: createTextChunk(text), + subWordTextChunks: breakPatternIntoTextChunks(text) + }; + } + function isUpperCaseLetter(ch) { + // Fast check for the ascii range. + if (ch >= 65 /* A */ && ch <= 90 /* Z */) { + return true; + } + if (ch < 127 /* maxAsciiCharacter */ || !ts.isUnicodeIdentifierStart(ch, 6 /* Latest */)) { + return false; + } + // TODO: find a way to determine this for any unicode characters in a + // non-allocating manner. + var str = String.fromCharCode(ch); + return str === str.toUpperCase(); + } + function isLowerCaseLetter(ch) { + // Fast check for the ascii range. + if (ch >= 97 /* a */ && ch <= 122 /* z */) { + return true; + } + if (ch < 127 /* maxAsciiCharacter */ || !ts.isUnicodeIdentifierStart(ch, 6 /* Latest */)) { + return false; + } + // TODO: find a way to determine this for any unicode characters in a + // non-allocating manner. + var str = String.fromCharCode(ch); + return str === str.toLowerCase(); + } + // Assumes 'value' is already lowercase. + function indexOfIgnoringCase(str, value) { + var n = str.length - value.length; + var _loop_5 = function (start) { + if (every(value, function (valueChar, i) { return toLowerCase(str.charCodeAt(i + start)) === valueChar; })) { + return { value: start }; + } + }; + for (var start = 0; start <= n; start++) { + var state_1 = _loop_5(start); + if (typeof state_1 === "object") + return state_1.value; + } + return -1; + } + function toLowerCase(ch) { + // Fast convert for the ascii range. + if (ch >= 65 /* A */ && ch <= 90 /* Z */) { + return 97 /* a */ + (ch - 65 /* A */); + } + if (ch < 127 /* maxAsciiCharacter */) { + return ch; + } + // TODO: find a way to compute this for any unicode characters in a + // non-allocating manner. + return String.fromCharCode(ch).toLowerCase().charCodeAt(0); + } + function isDigit(ch) { + // TODO(cyrusn): Find a way to support this for unicode digits. + return ch >= 48 /* _0 */ && ch <= 57 /* _9 */; + } + function isWordChar(ch) { + return isUpperCaseLetter(ch) || isLowerCaseLetter(ch) || isDigit(ch) || ch === 95 /* _ */ || ch === 36 /* $ */; + } + function breakPatternIntoTextChunks(pattern) { + var result = []; + var wordStart = 0; + var wordLength = 0; + for (var i = 0; i < pattern.length; i++) { + var ch = pattern.charCodeAt(i); + if (isWordChar(ch)) { + if (wordLength === 0) { + wordStart = i; + } + wordLength++; + } + else { + if (wordLength > 0) { + result.push(createTextChunk(pattern.substr(wordStart, wordLength))); + wordLength = 0; + } + } + } + if (wordLength > 0) { + result.push(createTextChunk(pattern.substr(wordStart, wordLength))); + } + return result; + } + function createTextChunk(text) { + var textLowerCase = text.toLowerCase(); + return { + text: text, + textLowerCase: textLowerCase, + isLowerCase: text === textLowerCase, + characterSpans: breakIntoCharacterSpans(text) + }; + } + function breakIntoCharacterSpans(identifier) { + return breakIntoSpans(identifier, /*word:*/ false); + } + ts.breakIntoCharacterSpans = breakIntoCharacterSpans; + function breakIntoWordSpans(identifier) { + return breakIntoSpans(identifier, /*word:*/ true); + } + ts.breakIntoWordSpans = breakIntoWordSpans; + function breakIntoSpans(identifier, word) { + var result = []; + var wordStart = 0; + for (var i = 1; i < identifier.length; i++) { + var lastIsDigit = isDigit(identifier.charCodeAt(i - 1)); + var currentIsDigit = isDigit(identifier.charCodeAt(i)); + var hasTransitionFromLowerToUpper = transitionFromLowerToUpper(identifier, word, i); + var hasTransitionFromUpperToLower = word && transitionFromUpperToLower(identifier, i, wordStart); + if (charIsPunctuation(identifier.charCodeAt(i - 1)) || + charIsPunctuation(identifier.charCodeAt(i)) || + lastIsDigit !== currentIsDigit || + hasTransitionFromLowerToUpper || + hasTransitionFromUpperToLower) { + if (!isAllPunctuation(identifier, wordStart, i)) { + result.push(ts.createTextSpan(wordStart, i - wordStart)); + } + wordStart = i; + } + } + if (!isAllPunctuation(identifier, wordStart, identifier.length)) { + result.push(ts.createTextSpan(wordStart, identifier.length - wordStart)); + } + return result; + } + function charIsPunctuation(ch) { + switch (ch) { + case 33 /* exclamation */: + case 34 /* doubleQuote */: + case 35 /* hash */: + case 37 /* percent */: + case 38 /* ampersand */: + case 39 /* singleQuote */: + case 40 /* openParen */: + case 41 /* closeParen */: + case 42 /* asterisk */: + case 44 /* comma */: + case 45 /* minus */: + case 46 /* dot */: + case 47 /* slash */: + case 58 /* colon */: + case 59 /* semicolon */: + case 63 /* question */: + case 64 /* at */: + case 91 /* openBracket */: + case 92 /* backslash */: + case 93 /* closeBracket */: + case 95 /* _ */: + case 123 /* openBrace */: + case 125 /* closeBrace */: + return true; + } + return false; + } + function isAllPunctuation(identifier, start, end) { + return every(identifier, function (ch) { return charIsPunctuation(ch) && ch !== 95 /* _ */; }, start, end); + } + function transitionFromUpperToLower(identifier, index, wordStart) { + // Cases this supports: + // 1) IDisposable -> I, Disposable + // 2) UIElement -> UI, Element + // 3) HTMLDocument -> HTML, Document + // + // etc. + // We have a transition from an upper to a lower letter here. But we only + // want to break if all the letters that preceded are uppercase. i.e. if we + // have "Foo" we don't want to break that into "F, oo". But if we have + // "IFoo" or "UIFoo", then we want to break that into "I, Foo" and "UI, + // Foo". i.e. the last uppercase letter belongs to the lowercase letters + // that follows. Note: this will make the following not split properly: + // "HELLOthere". However, these sorts of names do not show up in .Net + // programs. + return index !== wordStart + && index + 1 < identifier.length + && isUpperCaseLetter(identifier.charCodeAt(index)) + && isLowerCaseLetter(identifier.charCodeAt(index + 1)) + && every(identifier, isUpperCaseLetter, wordStart, index); + } + function transitionFromLowerToUpper(identifier, word, index) { + var lastIsUpper = isUpperCaseLetter(identifier.charCodeAt(index - 1)); + var currentIsUpper = isUpperCaseLetter(identifier.charCodeAt(index)); + // See if the casing indicates we're starting a new word. Note: if we're breaking on + // words, then just seeing an upper case character isn't enough. Instead, it has to + // be uppercase and the previous character can't be uppercase. + // + // For example, breaking "AddMetadata" on words would make: Add Metadata + // + // on characters would be: A dd M etadata + // + // Break "AM" on words would be: AM + // + // on characters would be: A M + // + // We break the search string on characters. But we break the symbol name on words. + return currentIsUpper && (!word || !lastIsUpper); + } + function everyInRange(start, end, pred) { + for (var i = start; i < end; i++) { + if (!pred(i)) { + return false; + } + } + return true; + } + function every(s, pred, start, end) { + if (start === void 0) { start = 0; } + if (end === void 0) { end = s.length; } + return everyInRange(start, end, function (i) { return pred(s.charCodeAt(i), i); }); + } +})(ts || (ts = {})); +var ts; +(function (ts) { + function preProcessFile(sourceText, readImportFiles, detectJavaScriptImports) { + if (readImportFiles === void 0) { readImportFiles = true; } + if (detectJavaScriptImports === void 0) { detectJavaScriptImports = false; } + var pragmaContext = { + languageVersion: 1 /* ES5 */, + pragmas: undefined, + checkJsDirective: undefined, + referencedFiles: [], + typeReferenceDirectives: [], + libReferenceDirectives: [], + amdDependencies: [], + hasNoDefaultLib: undefined, + moduleName: undefined + }; + var importedFiles = []; + var ambientExternalModules; + var lastToken; + var currentToken; + var braceNesting = 0; + // assume that text represent an external module if it contains at least one top level import/export + // ambient modules that are found inside external modules are interpreted as module augmentations + var externalModule = false; + function nextToken() { + lastToken = currentToken; + currentToken = ts.scanner.scan(); + if (currentToken === 18 /* OpenBraceToken */) { + braceNesting++; + } + else if (currentToken === 19 /* CloseBraceToken */) { + braceNesting--; + } + return currentToken; + } + function getFileReference() { + var fileName = ts.scanner.getTokenValue(); + var pos = ts.scanner.getTokenPos(); + return { fileName: fileName, pos: pos, end: pos + fileName.length }; + } + function recordAmbientExternalModule() { + if (!ambientExternalModules) { + ambientExternalModules = []; + } + ambientExternalModules.push({ ref: getFileReference(), depth: braceNesting }); + } + function recordModuleName() { + importedFiles.push(getFileReference()); + markAsExternalModuleIfTopLevel(); + } + function markAsExternalModuleIfTopLevel() { + if (braceNesting === 0) { + externalModule = true; + } + } + /** + * Returns true if at least one token was consumed from the stream + */ + function tryConsumeDeclare() { + var token = ts.scanner.getToken(); + if (token === 125 /* DeclareKeyword */) { + // declare module "mod" + token = nextToken(); + if (token === 130 /* ModuleKeyword */) { + token = nextToken(); + if (token === 10 /* StringLiteral */) { + recordAmbientExternalModule(); + } + } + return true; + } + return false; + } + /** + * Returns true if at least one token was consumed from the stream + */ + function tryConsumeImport() { + if (lastToken === 24 /* DotToken */) { + return false; + } + var token = ts.scanner.getToken(); + if (token === 92 /* ImportKeyword */) { + token = nextToken(); + if (token === 20 /* OpenParenToken */) { + token = nextToken(); + if (token === 10 /* StringLiteral */) { + // import("mod"); + recordModuleName(); + return true; + } + } + else if (token === 10 /* StringLiteral */) { + // import "mod"; + recordModuleName(); + return true; + } + else { + if (token === 72 /* Identifier */ || ts.isKeyword(token)) { + token = nextToken(); + if (token === 144 /* FromKeyword */) { + token = nextToken(); + if (token === 10 /* StringLiteral */) { + // import d from "mod"; + recordModuleName(); + return true; + } + } + else if (token === 59 /* EqualsToken */) { + if (tryConsumeRequireCall(/*skipCurrentToken*/ true)) { + return true; + } + } + else if (token === 27 /* CommaToken */) { + // consume comma and keep going + token = nextToken(); + } + else { + // unknown syntax + return true; + } + } + if (token === 18 /* OpenBraceToken */) { + token = nextToken(); + // consume "{ a as B, c, d as D}" clauses + // make sure that it stops on EOF + while (token !== 19 /* CloseBraceToken */ && token !== 1 /* EndOfFileToken */) { + token = nextToken(); + } + if (token === 19 /* CloseBraceToken */) { + token = nextToken(); + if (token === 144 /* FromKeyword */) { + token = nextToken(); + if (token === 10 /* StringLiteral */) { + // import {a as A} from "mod"; + // import d, {a, b as B} from "mod" + recordModuleName(); + } + } + } + } + else if (token === 40 /* AsteriskToken */) { + token = nextToken(); + if (token === 119 /* AsKeyword */) { + token = nextToken(); + if (token === 72 /* Identifier */ || ts.isKeyword(token)) { + token = nextToken(); + if (token === 144 /* FromKeyword */) { + token = nextToken(); + if (token === 10 /* StringLiteral */) { + // import * as NS from "mod" + // import d, * as NS from "mod" + recordModuleName(); + } + } + } + } + } + } + return true; + } + return false; + } + function tryConsumeExport() { + var token = ts.scanner.getToken(); + if (token === 85 /* ExportKeyword */) { + markAsExternalModuleIfTopLevel(); + token = nextToken(); + if (token === 18 /* OpenBraceToken */) { + token = nextToken(); + // consume "{ a as B, c, d as D}" clauses + // make sure it stops on EOF + while (token !== 19 /* CloseBraceToken */ && token !== 1 /* EndOfFileToken */) { + token = nextToken(); + } + if (token === 19 /* CloseBraceToken */) { + token = nextToken(); + if (token === 144 /* FromKeyword */) { + token = nextToken(); + if (token === 10 /* StringLiteral */) { + // export {a as A} from "mod"; + // export {a, b as B} from "mod" + recordModuleName(); + } + } + } + } + else if (token === 40 /* AsteriskToken */) { + token = nextToken(); + if (token === 144 /* FromKeyword */) { + token = nextToken(); + if (token === 10 /* StringLiteral */) { + // export * from "mod" + recordModuleName(); + } + } + } + else if (token === 92 /* ImportKeyword */) { + token = nextToken(); + if (token === 72 /* Identifier */ || ts.isKeyword(token)) { + token = nextToken(); + if (token === 59 /* EqualsToken */) { + if (tryConsumeRequireCall(/*skipCurrentToken*/ true)) { + return true; + } + } + } + } + return true; + } + return false; + } + function tryConsumeRequireCall(skipCurrentToken) { + var token = skipCurrentToken ? nextToken() : ts.scanner.getToken(); + if (token === 134 /* RequireKeyword */) { + token = nextToken(); + if (token === 20 /* OpenParenToken */) { + token = nextToken(); + if (token === 10 /* StringLiteral */) { + // require("mod"); + recordModuleName(); + } + } + return true; + } + return false; + } + function tryConsumeDefine() { + var token = ts.scanner.getToken(); + if (token === 72 /* Identifier */ && ts.scanner.getTokenValue() === "define") { + token = nextToken(); + if (token !== 20 /* OpenParenToken */) { + return true; + } + token = nextToken(); + if (token === 10 /* StringLiteral */) { + // looks like define ("modname", ... - skip string literal and comma + token = nextToken(); + if (token === 27 /* CommaToken */) { + token = nextToken(); + } + else { + // unexpected token + return true; + } + } + // should be start of dependency list + if (token !== 22 /* OpenBracketToken */) { + return true; + } + // skip open bracket + token = nextToken(); + // scan until ']' or EOF + while (token !== 23 /* CloseBracketToken */ && token !== 1 /* EndOfFileToken */) { + // record string literals as module names + if (token === 10 /* StringLiteral */) { + recordModuleName(); + } + token = nextToken(); + } + return true; + } + return false; + } + function processImports() { + ts.scanner.setText(sourceText); + nextToken(); + // Look for: + // import "mod"; + // import d from "mod" + // import {a as A } from "mod"; + // import * as NS from "mod" + // import d, {a, b as B} from "mod" + // import i = require("mod"); + // import("mod"); + // export * from "mod" + // export {a as b} from "mod" + // export import i = require("mod") + // (for JavaScript files) require("mod") + // Do not look for: + // AnySymbol.import("mod") + // AnySymbol.nested.import("mod") + while (true) { + if (ts.scanner.getToken() === 1 /* EndOfFileToken */) { + break; + } + // check if at least one of alternative have moved scanner forward + if (tryConsumeDeclare() || + tryConsumeImport() || + tryConsumeExport() || + (detectJavaScriptImports && (tryConsumeRequireCall(/*skipCurrentToken*/ false) || tryConsumeDefine()))) { + continue; + } + else { + nextToken(); + } + } + ts.scanner.setText(undefined); + } + if (readImportFiles) { + processImports(); + } + ts.processCommentPragmas(pragmaContext, sourceText); + ts.processPragmasIntoFields(pragmaContext, ts.noop); + if (externalModule) { + // for external modules module all nested ambient modules are augmentations + if (ambientExternalModules) { + // move all detected ambient modules to imported files since they need to be resolved + for (var _i = 0, ambientExternalModules_1 = ambientExternalModules; _i < ambientExternalModules_1.length; _i++) { + var decl = ambientExternalModules_1[_i]; + importedFiles.push(decl.ref); + } + } + return { referencedFiles: pragmaContext.referencedFiles, typeReferenceDirectives: pragmaContext.typeReferenceDirectives, libReferenceDirectives: pragmaContext.libReferenceDirectives, importedFiles: importedFiles, isLibFile: !!pragmaContext.hasNoDefaultLib, ambientExternalModules: undefined }; + } + else { + // for global scripts ambient modules still can have augmentations - look for ambient modules with depth > 0 + var ambientModuleNames = void 0; + if (ambientExternalModules) { + for (var _a = 0, ambientExternalModules_2 = ambientExternalModules; _a < ambientExternalModules_2.length; _a++) { + var decl = ambientExternalModules_2[_a]; + if (decl.depth === 0) { + if (!ambientModuleNames) { + ambientModuleNames = []; + } + ambientModuleNames.push(decl.ref.fileName); + } + else { + importedFiles.push(decl.ref); + } + } + } + return { referencedFiles: pragmaContext.referencedFiles, typeReferenceDirectives: pragmaContext.typeReferenceDirectives, libReferenceDirectives: pragmaContext.libReferenceDirectives, importedFiles: importedFiles, isLibFile: !!pragmaContext.hasNoDefaultLib, ambientExternalModules: ambientModuleNames }; + } + } + ts.preProcessFile = preProcessFile; +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var Rename; + (function (Rename) { + function getRenameInfo(program, sourceFile, position) { + var node = ts.getTouchingPropertyName(sourceFile, position); + var renameInfo = node && nodeIsEligibleForRename(node) + ? getRenameInfoForNode(node, program.getTypeChecker(), sourceFile, function (declaration) { return program.isSourceFileDefaultLibrary(declaration.getSourceFile()); }) + : undefined; + return renameInfo || getRenameInfoError(ts.Diagnostics.You_cannot_rename_this_element); + } + Rename.getRenameInfo = getRenameInfo; + function getRenameInfoForNode(node, typeChecker, sourceFile, isDefinedInLibraryFile) { + var symbol = typeChecker.getSymbolAtLocation(node); + if (!symbol) + return; + // Only allow a symbol to be renamed if it actually has at least one declaration. + var declarations = symbol.declarations; + if (!declarations || declarations.length === 0) + return; + // Disallow rename for elements that are defined in the standard TypeScript library. + if (declarations.some(isDefinedInLibraryFile)) { + return getRenameInfoError(ts.Diagnostics.You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library); + } + // Cannot rename `default` as in `import { default as foo } from "./someModule"; + if (ts.isIdentifier(node) && node.originalKeywordKind === 80 /* DefaultKeyword */ && symbol.parent.flags & 1536 /* Module */) { + return undefined; + } + if (ts.isStringLiteralLike(node) && ts.tryGetImportFromModuleSpecifier(node)) { + return getRenameInfoForModule(node, sourceFile, symbol); + } + var kind = ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, node); + var specifierName = (ts.isImportOrExportSpecifierName(node) || ts.isStringOrNumericLiteralLike(node) && node.parent.kind === 149 /* ComputedPropertyName */) + ? ts.stripQuotes(ts.getTextOfIdentifierOrLiteral(node)) + : undefined; + var displayName = specifierName || typeChecker.symbolToString(symbol); + var fullDisplayName = specifierName || typeChecker.getFullyQualifiedName(symbol); + return getRenameInfoSuccess(displayName, fullDisplayName, kind, ts.SymbolDisplay.getSymbolModifiers(symbol), node, sourceFile); + } + function getRenameInfoForModule(node, sourceFile, moduleSymbol) { + if (!ts.isExternalModuleNameRelative(node.text)) { + return getRenameInfoError(ts.Diagnostics.You_cannot_rename_a_module_via_a_global_import); + } + var moduleSourceFile = ts.find(moduleSymbol.declarations, ts.isSourceFile); + if (!moduleSourceFile) + return undefined; + var withoutIndex = node.text.endsWith("/index") || node.text.endsWith("/index.js") ? undefined : ts.tryRemoveSuffix(ts.removeFileExtension(moduleSourceFile.fileName), "/index"); + var name = withoutIndex === undefined ? moduleSourceFile.fileName : withoutIndex; + var kind = withoutIndex === undefined ? "module" /* moduleElement */ : "directory" /* directory */; + var indexAfterLastSlash = node.text.lastIndexOf("/") + 1; + // Span should only be the last component of the path. + 1 to account for the quote character. + var triggerSpan = ts.createTextSpan(node.getStart(sourceFile) + 1 + indexAfterLastSlash, node.text.length - indexAfterLastSlash); + return { + canRename: true, + fileToRename: name, + kind: kind, + displayName: name, + fullDisplayName: name, + kindModifiers: "" /* none */, + triggerSpan: triggerSpan, + }; + } + function getRenameInfoSuccess(displayName, fullDisplayName, kind, kindModifiers, node, sourceFile) { + return { + canRename: true, + fileToRename: undefined, + kind: kind, + displayName: displayName, + fullDisplayName: fullDisplayName, + kindModifiers: kindModifiers, + triggerSpan: createTriggerSpanForNode(node, sourceFile) + }; + } + function getRenameInfoError(diagnostic) { + return { canRename: false, localizedErrorMessage: ts.getLocaleSpecificMessage(diagnostic) }; + } + function createTriggerSpanForNode(node, sourceFile) { + var start = node.getStart(sourceFile); + var width = node.getWidth(sourceFile); + if (node.kind === 10 /* StringLiteral */) { + // Exclude the quotes + start += 1; + width -= 2; + } + return ts.createTextSpan(start, width); + } + function nodeIsEligibleForRename(node) { + switch (node.kind) { + case 72 /* Identifier */: + case 10 /* StringLiteral */: + case 100 /* ThisKeyword */: + return true; + case 8 /* NumericLiteral */: + return ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node); + default: + return false; + } + } + })(Rename = ts.Rename || (ts.Rename = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var SignatureHelp; + (function (SignatureHelp) { + var InvocationKind; + (function (InvocationKind) { + InvocationKind[InvocationKind["Call"] = 0] = "Call"; + InvocationKind[InvocationKind["TypeArgs"] = 1] = "TypeArgs"; + InvocationKind[InvocationKind["Contextual"] = 2] = "Contextual"; + })(InvocationKind || (InvocationKind = {})); + function getSignatureHelpItems(program, sourceFile, position, triggerReason, cancellationToken) { + var typeChecker = program.getTypeChecker(); + // Decide whether to show signature help + var startingToken = ts.findTokenOnLeftOfPosition(sourceFile, position); + if (!startingToken) { + // We are at the beginning of the file + return undefined; + } + // Only need to be careful if the user typed a character and signature help wasn't showing. + var onlyUseSyntacticOwners = !!triggerReason && triggerReason.kind === "characterTyped"; + // Bail out quickly in the middle of a string or comment, don't provide signature help unless the user explicitly requested it. + if (onlyUseSyntacticOwners && (ts.isInString(sourceFile, position, startingToken) || ts.isInComment(sourceFile, position))) { + return undefined; + } + var isManuallyInvoked = !!triggerReason && triggerReason.kind === "invoked"; + var argumentInfo = getContainingArgumentInfo(startingToken, position, sourceFile, typeChecker, isManuallyInvoked); + if (!argumentInfo) + return undefined; + cancellationToken.throwIfCancellationRequested(); + // Extra syntactic and semantic filtering of signature help + var candidateInfo = getCandidateOrTypeInfo(argumentInfo, typeChecker, sourceFile, startingToken, onlyUseSyntacticOwners); + cancellationToken.throwIfCancellationRequested(); + if (!candidateInfo) { + // We didn't have any sig help items produced by the TS compiler. If this is a JS + // file, then see if we can figure out anything better. + return ts.isSourceFileJS(sourceFile) ? createJSSignatureHelpItems(argumentInfo, program, cancellationToken) : undefined; + } + return typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { + return candidateInfo.kind === 0 /* Candidate */ + ? createSignatureHelpItems(candidateInfo.candidates, candidateInfo.resolvedSignature, argumentInfo, sourceFile, typeChecker) + : createTypeHelpItems(candidateInfo.symbol, argumentInfo, sourceFile, typeChecker); + }); + } + SignatureHelp.getSignatureHelpItems = getSignatureHelpItems; + var CandidateOrTypeKind; + (function (CandidateOrTypeKind) { + CandidateOrTypeKind[CandidateOrTypeKind["Candidate"] = 0] = "Candidate"; + CandidateOrTypeKind[CandidateOrTypeKind["Type"] = 1] = "Type"; + })(CandidateOrTypeKind || (CandidateOrTypeKind = {})); + function getCandidateOrTypeInfo(_a, checker, sourceFile, startingToken, onlyUseSyntacticOwners) { + var invocation = _a.invocation, argumentCount = _a.argumentCount; + switch (invocation.kind) { + case 0 /* Call */: { + if (onlyUseSyntacticOwners && !isSyntacticOwner(startingToken, invocation.node, sourceFile)) { + return undefined; + } + var candidates = []; + var resolvedSignature = checker.getResolvedSignatureForSignatureHelp(invocation.node, candidates, argumentCount); // TODO: GH#18217 + return candidates.length === 0 ? undefined : { kind: 0 /* Candidate */, candidates: candidates, resolvedSignature: resolvedSignature }; + } + case 1 /* TypeArgs */: { + var called = invocation.called; + if (onlyUseSyntacticOwners && !containsPrecedingToken(startingToken, sourceFile, ts.isIdentifier(called) ? called.parent : called)) { + return undefined; + } + var candidates = ts.getPossibleGenericSignatures(called, argumentCount, checker); + if (candidates.length !== 0) + return { kind: 0 /* Candidate */, candidates: candidates, resolvedSignature: ts.first(candidates) }; + var symbol = checker.getSymbolAtLocation(called); + return symbol && { kind: 1 /* Type */, symbol: symbol }; + } + case 2 /* Contextual */: + return { kind: 0 /* Candidate */, candidates: [invocation.signature], resolvedSignature: invocation.signature }; + default: + return ts.Debug.assertNever(invocation); + } + } + function isSyntacticOwner(startingToken, node, sourceFile) { + if (!ts.isCallOrNewExpression(node)) + return false; + var invocationChildren = node.getChildren(sourceFile); + switch (startingToken.kind) { + case 20 /* OpenParenToken */: + return ts.contains(invocationChildren, startingToken); + case 27 /* CommaToken */: { + var containingList = ts.findContainingList(startingToken); + return !!containingList && ts.contains(invocationChildren, containingList); + } + case 28 /* LessThanToken */: + return containsPrecedingToken(startingToken, sourceFile, node.expression); + default: + return false; + } + } + function createJSSignatureHelpItems(argumentInfo, program, cancellationToken) { + if (argumentInfo.invocation.kind === 2 /* Contextual */) + return undefined; + // See if we can find some symbol with the call expression name that has call signatures. + var expression = getExpressionFromInvocation(argumentInfo.invocation); + var name = ts.isIdentifier(expression) ? expression.text : ts.isPropertyAccessExpression(expression) ? expression.name.text : undefined; + var typeChecker = program.getTypeChecker(); + return name === undefined ? undefined : ts.firstDefined(program.getSourceFiles(), function (sourceFile) { + return ts.firstDefined(sourceFile.getNamedDeclarations().get(name), function (declaration) { + var type = declaration.symbol && typeChecker.getTypeOfSymbolAtLocation(declaration.symbol, declaration); + var callSignatures = type && type.getCallSignatures(); + if (callSignatures && callSignatures.length) { + return typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { return createSignatureHelpItems(callSignatures, callSignatures[0], argumentInfo, sourceFile, typeChecker); }); + } + }); + }); + } + function containsPrecedingToken(startingToken, sourceFile, container) { + var precedingToken = ts.Debug.assertDefined(ts.findPrecedingToken(startingToken.getFullStart(), sourceFile, startingToken.parent, /*excludeJsdoc*/ true)); + return ts.rangeContainsRange(container, precedingToken); + } + function getArgumentInfoForCompletions(node, position, sourceFile) { + var info = getImmediatelyContainingArgumentInfo(node, position, sourceFile); + return !info || info.isTypeParameterList || info.invocation.kind !== 0 /* Call */ ? undefined + : { invocation: info.invocation.node, argumentCount: info.argumentCount, argumentIndex: info.argumentIndex }; + } + SignatureHelp.getArgumentInfoForCompletions = getArgumentInfoForCompletions; + function getArgumentOrParameterListInfo(node, sourceFile) { + var info = getArgumentOrParameterListAndIndex(node, sourceFile); + if (!info) + return undefined; + var list = info.list, argumentIndex = info.argumentIndex; + var argumentCount = getArgumentCount(list); + if (argumentIndex !== 0) { + ts.Debug.assertLessThan(argumentIndex, argumentCount); + } + var argumentsSpan = getApplicableSpanForArguments(list, sourceFile); + return { list: list, argumentIndex: argumentIndex, argumentCount: argumentCount, argumentsSpan: argumentsSpan }; + } + function getArgumentOrParameterListAndIndex(node, sourceFile) { + if (node.kind === 28 /* LessThanToken */ || node.kind === 20 /* OpenParenToken */) { + // Find the list that starts right *after* the < or ( token. + // If the user has just opened a list, consider this item 0. + return { list: getChildListThatStartsWithOpenerToken(node.parent, node, sourceFile), argumentIndex: 0 }; + } + else { + // findListItemInfo can return undefined if we are not in parent's argument list + // or type argument list. This includes cases where the cursor is: + // - To the right of the closing parenthesis, non-substitution template, or template tail. + // - Between the type arguments and the arguments (greater than token) + // - On the target of the call (parent.func) + // - On the 'new' keyword in a 'new' expression + var list = ts.findContainingList(node); + return list && { list: list, argumentIndex: getArgumentIndex(list, node) }; + } + } + /** + * Returns relevant information for the argument list and the current argument if we are + * in the argument of an invocation; returns undefined otherwise. + */ + function getImmediatelyContainingArgumentInfo(node, position, sourceFile) { + var parent = node.parent; + if (ts.isCallOrNewExpression(parent)) { + var invocation = parent; + // There are 3 cases to handle: + // 1. The token introduces a list, and should begin a signature help session + // 2. The token is either not associated with a list, or ends a list, so the session should end + // 3. The token is buried inside a list, and should give signature help + // + // The following are examples of each: + // + // Case 1: + // foo<#T, U>(#a, b) -> The token introduces a list, and should begin a signature help session + // Case 2: + // fo#o#(a, b)# -> The token is either not associated with a list, or ends a list, so the session should end + // Case 3: + // foo(a#, #b#) -> The token is buried inside a list, and should give signature help + // Find out if 'node' is an argument, a type argument, or neither + var info = getArgumentOrParameterListInfo(node, sourceFile); + if (!info) + return undefined; + var list = info.list, argumentIndex = info.argumentIndex, argumentCount = info.argumentCount, argumentsSpan = info.argumentsSpan; + var isTypeParameterList = !!parent.typeArguments && parent.typeArguments.pos === list.pos; + return { isTypeParameterList: isTypeParameterList, invocation: { kind: 0 /* Call */, node: invocation }, argumentsSpan: argumentsSpan, argumentIndex: argumentIndex, argumentCount: argumentCount }; + } + else if (ts.isNoSubstitutionTemplateLiteral(node) && ts.isTaggedTemplateExpression(parent)) { + // Check if we're actually inside the template; + // otherwise we'll fall out and return undefined. + if (ts.isInsideTemplateLiteral(node, position, sourceFile)) { + return getArgumentListInfoForTemplate(parent, /*argumentIndex*/ 0, sourceFile); + } + return undefined; + } + else if (ts.isTemplateHead(node) && parent.parent.kind === 193 /* TaggedTemplateExpression */) { + var templateExpression = parent; + var tagExpression = templateExpression.parent; + ts.Debug.assert(templateExpression.kind === 206 /* TemplateExpression */); + var argumentIndex = ts.isInsideTemplateLiteral(node, position, sourceFile) ? 0 : 1; + return getArgumentListInfoForTemplate(tagExpression, argumentIndex, sourceFile); + } + else if (ts.isTemplateSpan(parent) && ts.isTaggedTemplateExpression(parent.parent.parent)) { + var templateSpan = parent; + var tagExpression = parent.parent.parent; + // If we're just after a template tail, don't show signature help. + if (ts.isTemplateTail(node) && !ts.isInsideTemplateLiteral(node, position, sourceFile)) { + return undefined; + } + var spanIndex = templateSpan.parent.templateSpans.indexOf(templateSpan); + var argumentIndex = getArgumentIndexForTemplatePiece(spanIndex, node, position, sourceFile); + return getArgumentListInfoForTemplate(tagExpression, argumentIndex, sourceFile); + } + else if (ts.isJsxOpeningLikeElement(parent)) { + // Provide a signature help for JSX opening element or JSX self-closing element. + // This is not guarantee that JSX tag-name is resolved into stateless function component. (that is done in "getSignatureHelpItems") + // i.e + // export function MainButton(props: ButtonProps, context: any): JSX.Element { ... } + // ' 'b'. So, in this case the arg count will be 2. However, there + // is a small subtlety. If you have "Foo(a,)", then the child list will just have + // 'a' ''. So, in the case where the last child is a comma, we increase the + // arg count by one to compensate. + // + // Note: this subtlety only applies to the last comma. If you had "Foo(a,," then + // we'll have: 'a' '' '' + // That will give us 2 non-commas. We then add one for the last comma, giving us an + // arg count of 3. + var listChildren = argumentsList.getChildren(); + var argumentCount = ts.countWhere(listChildren, function (arg) { return arg.kind !== 27 /* CommaToken */; }); + if (listChildren.length > 0 && ts.last(listChildren).kind === 27 /* CommaToken */) { + argumentCount++; + } + return argumentCount; + } + // spanIndex is either the index for a given template span. + // This does not give appropriate results for a NoSubstitutionTemplateLiteral + function getArgumentIndexForTemplatePiece(spanIndex, node, position, sourceFile) { + // Because the TemplateStringsArray is the first argument, we have to offset each substitution expression by 1. + // There are three cases we can encounter: + // 1. We are precisely in the template literal (argIndex = 0). + // 2. We are in or to the right of the substitution expression (argIndex = spanIndex + 1). + // 3. We are directly to the right of the template literal, but because we look for the token on the left, + // not enough to put us in the substitution expression; we should consider ourselves part of + // the *next* span's expression by offsetting the index (argIndex = (spanIndex + 1) + 1). + // + // tslint:disable no-double-space + // Example: f `# abcd $#{# 1 + 1# }# efghi ${ #"#hello"# } # ` + // ^ ^ ^ ^ ^ ^ ^ ^ ^ + // Case: 1 1 3 2 1 3 2 2 1 + // tslint:enable no-double-space + ts.Debug.assert(position >= node.getStart(), "Assumed 'position' could not occur before node."); + if (ts.isTemplateLiteralToken(node)) { + if (ts.isInsideTemplateLiteral(node, position, sourceFile)) { + return 0; + } + return spanIndex + 2; + } + return spanIndex + 1; + } + function getArgumentListInfoForTemplate(tagExpression, argumentIndex, sourceFile) { + // argumentCount is either 1 or (numSpans + 1) to account for the template strings array argument. + var argumentCount = ts.isNoSubstitutionTemplateLiteral(tagExpression.template) ? 1 : tagExpression.template.templateSpans.length + 1; + if (argumentIndex !== 0) { + ts.Debug.assertLessThan(argumentIndex, argumentCount); + } + return { + isTypeParameterList: false, + invocation: { kind: 0 /* Call */, node: tagExpression }, + argumentsSpan: getApplicableSpanForTaggedTemplate(tagExpression, sourceFile), + argumentIndex: argumentIndex, + argumentCount: argumentCount + }; + } + function getApplicableSpanForArguments(argumentsList, sourceFile) { + // We use full start and skip trivia on the end because we want to include trivia on + // both sides. For example, + // + // foo( /*comment */ a, b, c /*comment*/ ) + // | | + // + // The applicable span is from the first bar to the second bar (inclusive, + // but not including parentheses) + var applicableSpanStart = argumentsList.getFullStart(); + var applicableSpanEnd = ts.skipTrivia(sourceFile.text, argumentsList.getEnd(), /*stopAfterLineBreak*/ false); + return ts.createTextSpan(applicableSpanStart, applicableSpanEnd - applicableSpanStart); + } + function getApplicableSpanForTaggedTemplate(taggedTemplate, sourceFile) { + var template = taggedTemplate.template; + var applicableSpanStart = template.getStart(); + var applicableSpanEnd = template.getEnd(); + // We need to adjust the end position for the case where the template does not have a tail. + // Otherwise, we will not show signature help past the expression. + // For example, + // + // ` ${ 1 + 1 foo(10) + // | | + // This is because a Missing node has no width. However, what we actually want is to include trivia + // leading up to the next token in case the user is about to type in a TemplateMiddle or TemplateTail. + if (template.kind === 206 /* TemplateExpression */) { + var lastSpan = ts.last(template.templateSpans); + if (lastSpan.literal.getFullWidth() === 0) { + applicableSpanEnd = ts.skipTrivia(sourceFile.text, applicableSpanEnd, /*stopAfterLineBreak*/ false); + } + } + return ts.createTextSpan(applicableSpanStart, applicableSpanEnd - applicableSpanStart); + } + function getContainingArgumentInfo(node, position, sourceFile, checker, isManuallyInvoked) { + var _loop_6 = function (n) { + // If the node is not a subspan of its parent, this is a big problem. + // There have been crashes that might be caused by this violation. + ts.Debug.assert(ts.rangeContainsRange(n.parent, n), "Not a subspan", function () { return "Child: " + ts.Debug.showSyntaxKind(n) + ", parent: " + ts.Debug.showSyntaxKind(n.parent); }); + var argumentInfo = getImmediatelyContainingArgumentOrContextualParameterInfo(n, position, sourceFile, checker); + if (argumentInfo) { + return { value: argumentInfo }; + } + }; + for (var n = node; isManuallyInvoked || (!ts.isBlock(n) && !ts.isSourceFile(n)); n = n.parent) { + var state_2 = _loop_6(n); + if (typeof state_2 === "object") + return state_2.value; + } + return undefined; + } + function getChildListThatStartsWithOpenerToken(parent, openerToken, sourceFile) { + var children = parent.getChildren(sourceFile); + var indexOfOpenerToken = children.indexOf(openerToken); + ts.Debug.assert(indexOfOpenerToken >= 0 && children.length > indexOfOpenerToken + 1); + return children[indexOfOpenerToken + 1]; + } + function getExpressionFromInvocation(invocation) { + return invocation.kind === 0 /* Call */ ? ts.getInvokedExpression(invocation.node) : invocation.called; + } + function getEnclosingDeclarationFromInvocation(invocation) { + return invocation.kind === 0 /* Call */ ? invocation.node : invocation.kind === 1 /* TypeArgs */ ? invocation.called : invocation.node; + } + var signatureHelpNodeBuilderFlags = 8192 /* OmitParameterModifiers */ | 70221824 /* IgnoreErrors */ | 16384 /* UseAliasDefinedOutsideCurrentScope */; + function createSignatureHelpItems(candidates, resolvedSignature, _a, sourceFile, typeChecker) { + var isTypeParameterList = _a.isTypeParameterList, argumentCount = _a.argumentCount, applicableSpan = _a.argumentsSpan, invocation = _a.invocation, argumentIndex = _a.argumentIndex; + var enclosingDeclaration = getEnclosingDeclarationFromInvocation(invocation); + var callTargetSymbol = invocation.kind === 2 /* Contextual */ ? invocation.symbol : typeChecker.getSymbolAtLocation(getExpressionFromInvocation(invocation)); + var callTargetDisplayParts = callTargetSymbol ? ts.symbolToDisplayParts(typeChecker, callTargetSymbol, /*enclosingDeclaration*/ undefined, /*meaning*/ undefined) : ts.emptyArray; + var items = candidates.map(function (candidateSignature) { return getSignatureHelpItem(candidateSignature, callTargetDisplayParts, isTypeParameterList, typeChecker, enclosingDeclaration, sourceFile); }); + if (argumentIndex !== 0) { + ts.Debug.assertLessThan(argumentIndex, argumentCount); + } + var selectedItemIndex = candidates.indexOf(resolvedSignature); + ts.Debug.assert(selectedItemIndex !== -1); // If candidates is non-empty it should always include bestSignature. We check for an empty candidates before calling this function. + return { items: items, applicableSpan: applicableSpan, selectedItemIndex: selectedItemIndex, argumentIndex: argumentIndex, argumentCount: argumentCount }; + } + function createTypeHelpItems(symbol, _a, sourceFile, checker) { + var argumentCount = _a.argumentCount, applicableSpan = _a.argumentsSpan, invocation = _a.invocation, argumentIndex = _a.argumentIndex; + var typeParameters = checker.getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); + if (!typeParameters) + return undefined; + var items = [getTypeHelpItem(symbol, typeParameters, checker, getEnclosingDeclarationFromInvocation(invocation), sourceFile)]; + return { items: items, applicableSpan: applicableSpan, selectedItemIndex: 0, argumentIndex: argumentIndex, argumentCount: argumentCount }; + } + function getTypeHelpItem(symbol, typeParameters, checker, enclosingDeclaration, sourceFile) { + var typeSymbolDisplay = ts.symbolToDisplayParts(checker, symbol); + var printer = ts.createPrinter({ removeComments: true }); + var parameters = typeParameters.map(function (t) { return createSignatureHelpParameterForTypeParameter(t, checker, enclosingDeclaration, sourceFile, printer); }); + var documentation = symbol.getDocumentationComment(checker); + var tags = symbol.getJsDocTags(); + var prefixDisplayParts = typeSymbolDisplay.concat([ts.punctuationPart(28 /* LessThanToken */)]); + return { isVariadic: false, prefixDisplayParts: prefixDisplayParts, suffixDisplayParts: [ts.punctuationPart(30 /* GreaterThanToken */)], separatorDisplayParts: separatorDisplayParts, parameters: parameters, documentation: documentation, tags: tags }; + } + var separatorDisplayParts = [ts.punctuationPart(27 /* CommaToken */), ts.spacePart()]; + function getSignatureHelpItem(candidateSignature, callTargetDisplayParts, isTypeParameterList, checker, enclosingDeclaration, sourceFile) { + var _a = (isTypeParameterList ? itemInfoForTypeParameters : itemInfoForParameters)(candidateSignature, checker, enclosingDeclaration, sourceFile), isVariadic = _a.isVariadic, parameters = _a.parameters, prefix = _a.prefix, suffix = _a.suffix; + var prefixDisplayParts = callTargetDisplayParts.concat(prefix); + var suffixDisplayParts = suffix.concat(returnTypeToDisplayParts(candidateSignature, enclosingDeclaration, checker)); + var documentation = candidateSignature.getDocumentationComment(checker); + var tags = candidateSignature.getJsDocTags(); + return { isVariadic: isVariadic, prefixDisplayParts: prefixDisplayParts, suffixDisplayParts: suffixDisplayParts, separatorDisplayParts: separatorDisplayParts, parameters: parameters, documentation: documentation, tags: tags }; + } + function returnTypeToDisplayParts(candidateSignature, enclosingDeclaration, checker) { + return ts.mapToDisplayParts(function (writer) { + writer.writePunctuation(":"); + writer.writeSpace(" "); + var predicate = checker.getTypePredicateOfSignature(candidateSignature); + if (predicate) { + checker.writeTypePredicate(predicate, enclosingDeclaration, /*flags*/ undefined, writer); + } + else { + checker.writeType(checker.getReturnTypeOfSignature(candidateSignature), enclosingDeclaration, /*flags*/ undefined, writer); + } + }); + } + function itemInfoForTypeParameters(candidateSignature, checker, enclosingDeclaration, sourceFile) { + var typeParameters = (candidateSignature.target || candidateSignature).typeParameters; + var printer = ts.createPrinter({ removeComments: true }); + var parameters = (typeParameters || ts.emptyArray).map(function (t) { return createSignatureHelpParameterForTypeParameter(t, checker, enclosingDeclaration, sourceFile, printer); }); + var parameterParts = ts.mapToDisplayParts(function (writer) { + var thisParameter = candidateSignature.thisParameter ? [checker.symbolToParameterDeclaration(candidateSignature.thisParameter, enclosingDeclaration, signatureHelpNodeBuilderFlags)] : []; + var params = ts.createNodeArray(thisParameter.concat(candidateSignature.parameters.map(function (param) { return checker.symbolToParameterDeclaration(param, enclosingDeclaration, signatureHelpNodeBuilderFlags); }))); + printer.writeList(2576 /* CallExpressionArguments */, params, sourceFile, writer); + }); + return { isVariadic: false, parameters: parameters, prefix: [ts.punctuationPart(28 /* LessThanToken */)], suffix: [ts.punctuationPart(30 /* GreaterThanToken */)].concat(parameterParts) }; + } + function itemInfoForParameters(candidateSignature, checker, enclosingDeclaration, sourceFile) { + var isVariadic = candidateSignature.hasRestParameter; + var printer = ts.createPrinter({ removeComments: true }); + var typeParameterParts = ts.mapToDisplayParts(function (writer) { + if (candidateSignature.typeParameters && candidateSignature.typeParameters.length) { + var args = ts.createNodeArray(candidateSignature.typeParameters.map(function (p) { return checker.typeParameterToDeclaration(p, enclosingDeclaration); })); + printer.writeList(53776 /* TypeParameters */, args, sourceFile, writer); + } + }); + var parameters = candidateSignature.parameters.map(function (p) { return createSignatureHelpParameterForParameter(p, checker, enclosingDeclaration, sourceFile, printer); }); + return { isVariadic: isVariadic, parameters: parameters, prefix: typeParameterParts.concat([ts.punctuationPart(20 /* OpenParenToken */)]), suffix: [ts.punctuationPart(21 /* CloseParenToken */)] }; + } + function createSignatureHelpParameterForParameter(parameter, checker, enclosingDeclaration, sourceFile, printer) { + var displayParts = ts.mapToDisplayParts(function (writer) { + var param = checker.symbolToParameterDeclaration(parameter, enclosingDeclaration, signatureHelpNodeBuilderFlags); + printer.writeNode(4 /* Unspecified */, param, sourceFile, writer); + }); + var isOptional = checker.isOptionalParameter(parameter.valueDeclaration); + return { name: parameter.name, documentation: parameter.getDocumentationComment(checker), displayParts: displayParts, isOptional: isOptional }; + } + function createSignatureHelpParameterForTypeParameter(typeParameter, checker, enclosingDeclaration, sourceFile, printer) { + var displayParts = ts.mapToDisplayParts(function (writer) { + var param = checker.typeParameterToDeclaration(typeParameter, enclosingDeclaration); + printer.writeNode(4 /* Unspecified */, param, sourceFile, writer); + }); + return { name: typeParameter.symbol.name, documentation: typeParameter.symbol.getDocumentationComment(checker), displayParts: displayParts, isOptional: false }; + } + })(SignatureHelp = ts.SignatureHelp || (ts.SignatureHelp = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var base64UrlRegExp = /^data:(?:application\/json(?:;charset=[uU][tT][fF]-8);base64,([A-Za-z0-9+\/=]+)$)?/; + function getSourceMapper(useCaseSensitiveFileNames, currentDirectory, log, host, getProgram) { + var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); + var sourcemappedFileCache; + return { tryGetSourcePosition: tryGetSourcePosition, tryGetGeneratedPosition: tryGetGeneratedPosition, toLineColumnOffset: toLineColumnOffset, clearCache: clearCache }; + function toPath(fileName) { + return ts.toPath(fileName, currentDirectory, getCanonicalFileName); + } + function scanForSourcemapURL(fileName) { + var mappedFile = sourcemappedFileCache.get(toPath(fileName)); + if (!mappedFile) { + return; + } + return ts.tryGetSourceMappingURL(mappedFile.text, ts.getLineStarts(mappedFile)); + } + function convertDocumentToSourceMapper(file, contents, mapFileName) { + var map = ts.tryParseRawSourceMap(contents); + if (!map || !map.sources || !map.file || !map.mappings) { + // obviously invalid map + return file.sourceMapper = ts.identitySourceMapConsumer; + } + var program = getProgram(); + return file.sourceMapper = ts.createDocumentPositionMapper({ + getSourceFileLike: function (s) { + // Lookup file in program, if provided + var file = program && program.getSourceFileByPath(s); + // file returned here could be .d.ts when asked for .ts file if projectReferences and module resolution created this source file + if (file === undefined || file.resolvedPath !== s) { + // Otherwise check the cache (which may hit disk) + return sourcemappedFileCache.get(s); + } + return file; + }, + getCanonicalFileName: getCanonicalFileName, + log: log, + }, map, mapFileName); + } + function getSourceMapper(fileName, file) { + if (!host.readFile || !host.fileExists) { + return file.sourceMapper = ts.identitySourceMapConsumer; + } + if (file.sourceMapper) { + return file.sourceMapper; + } + var mapFileName = scanForSourcemapURL(fileName); + if (mapFileName) { + var match = base64UrlRegExp.exec(mapFileName); + if (match) { + if (match[1]) { + var base64Object = match[1]; + return convertDocumentToSourceMapper(file, ts.base64decode(ts.sys, base64Object), fileName); + } + // Not a data URL we can parse, skip it + mapFileName = undefined; + } + } + var possibleMapLocations = []; + if (mapFileName) { + possibleMapLocations.push(mapFileName); + } + possibleMapLocations.push(fileName + ".map"); + for (var _i = 0, possibleMapLocations_1 = possibleMapLocations; _i < possibleMapLocations_1.length; _i++) { + var location = possibleMapLocations_1[_i]; + var mapPath = ts.toPath(location, ts.getDirectoryPath(fileName), getCanonicalFileName); + if (host.fileExists(mapPath)) { + return convertDocumentToSourceMapper(file, host.readFile(mapPath), mapPath); // TODO: GH#18217 + } + } + return file.sourceMapper = ts.identitySourceMapConsumer; + } + function tryGetSourcePosition(info) { + if (!ts.isDeclarationFileName(info.fileName)) + return undefined; + var file = getFile(info.fileName); + if (!file) + return undefined; + var newLoc = getSourceMapper(info.fileName, file).getSourcePosition(info); + return newLoc === info ? undefined : tryGetSourcePosition(newLoc) || newLoc; + } + function tryGetGeneratedPosition(info) { + var program = getProgram(); + var options = program.getCompilerOptions(); + var outPath = options.outFile || options.out; + var declarationPath = outPath ? + ts.removeFileExtension(outPath) + ".d.ts" /* Dts */ : + ts.getDeclarationEmitOutputFilePathWorker(info.fileName, program.getCompilerOptions(), currentDirectory, program.getCommonSourceDirectory(), getCanonicalFileName); + if (declarationPath === undefined) + return undefined; + var declarationFile = getFile(declarationPath); + if (!declarationFile) + return undefined; + var newLoc = getSourceMapper(declarationPath, declarationFile).getGeneratedPosition(info); + return newLoc === info ? undefined : newLoc; + } + function getFile(fileName) { + var path = toPath(fileName); + var file = getProgram().getSourceFileByPath(path); + if (file && file.resolvedPath === path) { + return file; + } + return sourcemappedFileCache.get(path); + } + function toLineColumnOffset(fileName, position) { + var file = getFile(fileName); // TODO: GH#18217 + return file.getLineAndCharacterOfPosition(position); + } + function clearCache() { + sourcemappedFileCache = createSourceFileLikeCache(host); + } + } + ts.getSourceMapper = getSourceMapper; + function createSourceFileLikeCache(host) { + var cached = ts.createMap(); + return { + get: function (path) { + if (cached.has(path)) { + return cached.get(path); + } + if (!host.fileExists || !host.readFile || !host.fileExists(path)) + return; + // And failing that, check the disk + var text = host.readFile(path); // TODO: GH#18217 + var file = { + text: text, + lineMap: undefined, + getLineAndCharacterOfPosition: function (pos) { + return ts.computeLineAndCharacterOfPosition(ts.getLineStarts(this), pos); + } + }; + cached.set(path, file); + return file; + } + }; + } +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + function computeSuggestionDiagnostics(sourceFile, program, cancellationToken) { + program.getSemanticDiagnostics(sourceFile, cancellationToken); + var diags = []; + var checker = program.getTypeChecker(); + if (sourceFile.commonJsModuleIndicator && + (ts.programContainsEs6Modules(program) || ts.compilerOptionsIndicateEs6Modules(program.getCompilerOptions())) && + containsTopLevelCommonjs(sourceFile)) { + diags.push(ts.createDiagnosticForNode(getErrorNodeFromCommonJsIndicator(sourceFile.commonJsModuleIndicator), ts.Diagnostics.File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module)); + } + var isJsFile = ts.isSourceFileJS(sourceFile); + check(sourceFile); + if (ts.getAllowSyntheticDefaultImports(program.getCompilerOptions())) { + for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { + var moduleSpecifier = _a[_i]; + var importNode = ts.importFromModuleSpecifier(moduleSpecifier); + var name = importNameForConvertToDefaultImport(importNode); + if (!name) + continue; + var module_1 = ts.getResolvedModule(sourceFile, moduleSpecifier.text); + var resolvedFile = module_1 && program.getSourceFile(module_1.resolvedFileName); + if (resolvedFile && resolvedFile.externalModuleIndicator && ts.isExportAssignment(resolvedFile.externalModuleIndicator) && resolvedFile.externalModuleIndicator.isExportEquals) { + diags.push(ts.createDiagnosticForNode(name, ts.Diagnostics.Import_may_be_converted_to_a_default_import)); + } + } + } + ts.addRange(diags, sourceFile.bindSuggestionDiagnostics); + ts.addRange(diags, program.getSuggestionDiagnostics(sourceFile, cancellationToken)); + return diags.sort(function (d1, d2) { return d1.start - d2.start; }); + function check(node) { + if (isJsFile) { + switch (node.kind) { + case 196 /* FunctionExpression */: + var decl = ts.getDeclarationOfExpando(node); + if (decl) { + var symbol_1 = decl.symbol; + if (symbol_1 && (symbol_1.exports && symbol_1.exports.size || symbol_1.members && symbol_1.members.size)) { + diags.push(ts.createDiagnosticForNode(ts.isVariableDeclaration(node.parent) ? node.parent.name : node, ts.Diagnostics.This_constructor_function_may_be_converted_to_a_class_declaration)); + break; + } + } + // falls through if no diagnostic was created + case 239 /* FunctionDeclaration */: + var symbol = node.symbol; + if (symbol.members && (symbol.members.size > 0)) { + diags.push(ts.createDiagnosticForNode(ts.isVariableDeclaration(node.parent) ? node.parent.name : node, ts.Diagnostics.This_constructor_function_may_be_converted_to_a_class_declaration)); + } + break; + } + } + else { + if (ts.isVariableStatement(node) && + node.parent === sourceFile && + node.declarationList.flags & 2 /* Const */ && + node.declarationList.declarations.length === 1) { + var init = node.declarationList.declarations[0].initializer; + if (init && ts.isRequireCall(init, /*checkArgumentIsStringLiteralLike*/ true)) { + diags.push(ts.createDiagnosticForNode(init, ts.Diagnostics.require_call_may_be_converted_to_an_import)); + } + } + if (ts.codefix.parameterShouldGetTypeFromJSDoc(node)) { + diags.push(ts.createDiagnosticForNode(node.name || node, ts.Diagnostics.JSDoc_types_may_be_moved_to_TypeScript_types)); + } + } + if (ts.isFunctionLikeDeclaration(node)) { + addConvertToAsyncFunctionDiagnostics(node, checker, diags); + } + node.forEachChild(check); + } + } + ts.computeSuggestionDiagnostics = computeSuggestionDiagnostics; + // convertToEs6Module only works on top-level, so don't trigger it if commonjs code only appears in nested scopes. + function containsTopLevelCommonjs(sourceFile) { + return sourceFile.statements.some(function (statement) { + switch (statement.kind) { + case 219 /* VariableStatement */: + return statement.declarationList.declarations.some(function (decl) { + return !!decl.initializer && ts.isRequireCall(propertyAccessLeftHandSide(decl.initializer), /*checkArgumentIsStringLiteralLike*/ true); + }); + case 221 /* ExpressionStatement */: { + var expression = statement.expression; + if (!ts.isBinaryExpression(expression)) + return ts.isRequireCall(expression, /*checkArgumentIsStringLiteralLike*/ true); + var kind = ts.getAssignmentDeclarationKind(expression); + return kind === 1 /* ExportsProperty */ || kind === 2 /* ModuleExports */; + } + default: + return false; + } + }); + } + function propertyAccessLeftHandSide(node) { + return ts.isPropertyAccessExpression(node) ? propertyAccessLeftHandSide(node.expression) : node; + } + function importNameForConvertToDefaultImport(node) { + switch (node.kind) { + case 249 /* ImportDeclaration */: + var importClause = node.importClause, moduleSpecifier = node.moduleSpecifier; + return importClause && !importClause.name && importClause.namedBindings && importClause.namedBindings.kind === 251 /* NamespaceImport */ && ts.isStringLiteral(moduleSpecifier) + ? importClause.namedBindings.name + : undefined; + case 248 /* ImportEqualsDeclaration */: + return node.name; + default: + return undefined; + } + } + function addConvertToAsyncFunctionDiagnostics(node, checker, diags) { + if (!ts.isAsyncFunction(node) && + node.body && + ts.isBlock(node.body) && + hasReturnStatementWithPromiseHandler(node.body) && + returnsPromise(node, checker)) { + diags.push(ts.createDiagnosticForNode(!node.name && ts.isVariableDeclaration(node.parent) && ts.isIdentifier(node.parent.name) ? node.parent.name : node, ts.Diagnostics.This_may_be_converted_to_an_async_function)); + } + } + function returnsPromise(node, checker) { + var functionType = checker.getTypeAtLocation(node); + var callSignatures = checker.getSignaturesOfType(functionType, 0 /* Call */); + var returnType = callSignatures.length ? checker.getReturnTypeOfSignature(callSignatures[0]) : undefined; + return !!returnType && !!checker.getPromisedTypeOfPromise(returnType); + } + function getErrorNodeFromCommonJsIndicator(commonJsModuleIndicator) { + return ts.isBinaryExpression(commonJsModuleIndicator) ? commonJsModuleIndicator.left : commonJsModuleIndicator; + } + function hasReturnStatementWithPromiseHandler(body) { + return !!ts.forEachReturnStatement(body, isReturnStatementWithFixablePromiseHandler); + } + function isReturnStatementWithFixablePromiseHandler(node) { + return ts.isReturnStatement(node) && !!node.expression && isFixablePromiseHandler(node.expression); + } + ts.isReturnStatementWithFixablePromiseHandler = isReturnStatementWithFixablePromiseHandler; + // Should be kept up to date with transformExpression in convertToAsyncFunction.ts + function isFixablePromiseHandler(node) { + // ensure outermost call exists and is a promise handler + if (!isPromiseHandler(node) || !node.arguments.every(isFixablePromiseArgument)) { + return false; + } + // ensure all chained calls are valid + var currentNode = node.expression; + while (isPromiseHandler(currentNode) || ts.isPropertyAccessExpression(currentNode)) { + if (ts.isCallExpression(currentNode) && !currentNode.arguments.every(isFixablePromiseArgument)) { + return false; + } + currentNode = currentNode.expression; + } + return true; + } + ts.isFixablePromiseHandler = isFixablePromiseHandler; + function isPromiseHandler(node) { + return ts.isCallExpression(node) && (ts.hasPropertyAccessExpressionWithName(node, "then") || ts.hasPropertyAccessExpressionWithName(node, "catch")); + } + // should be kept up to date with getTransformationBody in convertToAsyncFunction.ts + function isFixablePromiseArgument(arg) { + switch (arg.kind) { + case 96 /* NullKeyword */: + case 72 /* Identifier */: // identifier includes undefined + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + return true; + default: + return false; + } + } +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var SymbolDisplay; + (function (SymbolDisplay) { + // TODO(drosen): use contextual SemanticMeaning. + function getSymbolKind(typeChecker, symbol, location) { + var result = getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, location); + if (result !== "" /* unknown */) { + return result; + } + var flags = ts.getCombinedLocalAndExportSymbolFlags(symbol); + if (flags & 32 /* Class */) { + return ts.getDeclarationOfKind(symbol, 209 /* ClassExpression */) ? + "local class" /* localClassElement */ : "class" /* classElement */; + } + if (flags & 384 /* Enum */) + return "enum" /* enumElement */; + if (flags & 524288 /* TypeAlias */) + return "type" /* typeElement */; + if (flags & 64 /* Interface */) + return "interface" /* interfaceElement */; + if (flags & 262144 /* TypeParameter */) + return "type parameter" /* typeParameterElement */; + if (flags & 262144 /* TypeParameter */) + return "type parameter" /* typeParameterElement */; + if (flags & 8 /* EnumMember */) + return "enum member" /* enumMemberElement */; + if (flags & 2097152 /* Alias */) + return "alias" /* alias */; + if (flags & 1536 /* Module */) + return "module" /* moduleElement */; + return result; + } + SymbolDisplay.getSymbolKind = getSymbolKind; + function getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, location) { + var roots = typeChecker.getRootSymbols(symbol); + // If this is a method from a mapped type, leave as a method so long as it still has a call signature. + if (roots.length === 1 + && ts.first(roots).flags & 8192 /* Method */ + // Ensure the mapped version is still a method, as opposed to `{ [K in keyof I]: number }`. + && typeChecker.getTypeOfSymbolAtLocation(symbol, location).getNonNullableType().getCallSignatures().length !== 0) { + return "method" /* memberFunctionElement */; + } + if (typeChecker.isUndefinedSymbol(symbol)) { + return "var" /* variableElement */; + } + if (typeChecker.isArgumentsSymbol(symbol)) { + return "local var" /* localVariableElement */; + } + if (location.kind === 100 /* ThisKeyword */ && ts.isExpression(location)) { + return "parameter" /* parameterElement */; + } + var flags = ts.getCombinedLocalAndExportSymbolFlags(symbol); + if (flags & 3 /* Variable */) { + if (ts.isFirstDeclarationOfSymbolParameter(symbol)) { + return "parameter" /* parameterElement */; + } + else if (symbol.valueDeclaration && ts.isVarConst(symbol.valueDeclaration)) { + return "const" /* constElement */; + } + else if (ts.forEach(symbol.declarations, ts.isLet)) { + return "let" /* letElement */; + } + return isLocalVariableOrFunction(symbol) ? "local var" /* localVariableElement */ : "var" /* variableElement */; + } + if (flags & 16 /* Function */) + return isLocalVariableOrFunction(symbol) ? "local function" /* localFunctionElement */ : "function" /* functionElement */; + if (flags & 32768 /* GetAccessor */) + return "getter" /* memberGetAccessorElement */; + if (flags & 65536 /* SetAccessor */) + return "setter" /* memberSetAccessorElement */; + if (flags & 8192 /* Method */) + return "method" /* memberFunctionElement */; + if (flags & 16384 /* Constructor */) + return "constructor" /* constructorImplementationElement */; + if (flags & 4 /* Property */) { + if (flags & 33554432 /* Transient */ && symbol.checkFlags & 6 /* Synthetic */) { + // If union property is result of union of non method (property/accessors/variables), it is labeled as property + var unionPropertyKind = ts.forEach(typeChecker.getRootSymbols(symbol), function (rootSymbol) { + var rootSymbolFlags = rootSymbol.getFlags(); + if (rootSymbolFlags & (98308 /* PropertyOrAccessor */ | 3 /* Variable */)) { + return "property" /* memberVariableElement */; + } + // May be a Function if this was from `typeof N` with `namespace N { function f();. }`. + ts.Debug.assert(!!(rootSymbolFlags & (8192 /* Method */ | 16 /* Function */))); + }); + if (!unionPropertyKind) { + // If this was union of all methods, + // make sure it has call signatures before we can label it as method + var typeOfUnionProperty = typeChecker.getTypeOfSymbolAtLocation(symbol, location); + if (typeOfUnionProperty.getCallSignatures().length) { + return "method" /* memberFunctionElement */; + } + return "property" /* memberVariableElement */; + } + return unionPropertyKind; + } + // If we requested completions after `x.` at the top-level, we may be at a source file location. + switch (location.parent && location.parent.kind) { + // If we've typed a character of the attribute name, will be 'JsxAttribute', else will be 'JsxOpeningElement'. + case 262 /* JsxOpeningElement */: + case 260 /* JsxElement */: + case 261 /* JsxSelfClosingElement */: + return location.kind === 72 /* Identifier */ ? "property" /* memberVariableElement */ : "JSX attribute" /* jsxAttribute */; + case 267 /* JsxAttribute */: + return "JSX attribute" /* jsxAttribute */; + default: + return "property" /* memberVariableElement */; + } + } + return "" /* unknown */; + } + function getSymbolModifiers(symbol) { + var nodeModifiers = symbol && symbol.declarations && symbol.declarations.length > 0 + ? ts.getNodeModifiers(symbol.declarations[0]) + : "" /* none */; + var symbolModifiers = symbol && symbol.flags & 16777216 /* Optional */ ? + "optional" /* optionalModifier */ + : "" /* none */; + return nodeModifiers && symbolModifiers ? nodeModifiers + "," + symbolModifiers : nodeModifiers || symbolModifiers; + } + SymbolDisplay.getSymbolModifiers = getSymbolModifiers; + // TODO(drosen): Currently completion entry details passes the SemanticMeaning.All instead of using semanticMeaning of location + function getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, enclosingDeclaration, location, semanticMeaning, alias) { + if (semanticMeaning === void 0) { semanticMeaning = ts.getMeaningFromLocation(location); } + var displayParts = []; + var documentation; + var tags; + var symbolFlags = ts.getCombinedLocalAndExportSymbolFlags(symbol); + var symbolKind = semanticMeaning & 1 /* Value */ ? getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, location) : "" /* unknown */; + var hasAddedSymbolInfo = false; + var isThisExpression = location.kind === 100 /* ThisKeyword */ && ts.isInExpressionContext(location); + var type; + var printer; + var documentationFromAlias; + var tagsFromAlias; + if (location.kind === 100 /* ThisKeyword */ && !isThisExpression) { + return { displayParts: [ts.keywordPart(100 /* ThisKeyword */)], documentation: [], symbolKind: "primitive type" /* primitiveType */, tags: undefined }; + } + // Class at constructor site need to be shown as constructor apart from property,method, vars + if (symbolKind !== "" /* unknown */ || symbolFlags & 32 /* Class */ || symbolFlags & 2097152 /* Alias */) { + // If it is accessor they are allowed only if location is at name of the accessor + if (symbolKind === "getter" /* memberGetAccessorElement */ || symbolKind === "setter" /* memberSetAccessorElement */) { + symbolKind = "property" /* memberVariableElement */; + } + var signature = void 0; + type = isThisExpression ? typeChecker.getTypeAtLocation(location) : typeChecker.getTypeOfSymbolAtLocation(symbol.exportSymbol || symbol, location); + if (location.parent && location.parent.kind === 189 /* PropertyAccessExpression */) { + var right = location.parent.name; + // Either the location is on the right of a property access, or on the left and the right is missing + if (right === location || (right && right.getFullWidth() === 0)) { + location = location.parent; + } + } + // try get the call/construct signature from the type if it matches + var callExpressionLike = void 0; + if (ts.isCallOrNewExpression(location)) { + callExpressionLike = location; + } + else if (ts.isCallExpressionTarget(location) || ts.isNewExpressionTarget(location)) { + callExpressionLike = location.parent; + } + else if (location.parent && ts.isJsxOpeningLikeElement(location.parent) && ts.isFunctionLike(symbol.valueDeclaration)) { + callExpressionLike = location.parent; + } + if (callExpressionLike) { + var candidateSignatures = []; + signature = typeChecker.getResolvedSignature(callExpressionLike, candidateSignatures); // TODO: GH#18217 + var useConstructSignatures = callExpressionLike.kind === 192 /* NewExpression */ || (ts.isCallExpression(callExpressionLike) && callExpressionLike.expression.kind === 98 /* SuperKeyword */); + var allSignatures = useConstructSignatures ? type.getConstructSignatures() : type.getCallSignatures(); + if (!ts.contains(allSignatures, signature.target) && !ts.contains(allSignatures, signature)) { + // Get the first signature if there is one -- allSignatures may contain + // either the original signature or its target, so check for either + signature = allSignatures.length ? allSignatures[0] : undefined; + } + if (signature) { + if (useConstructSignatures && (symbolFlags & 32 /* Class */)) { + // Constructor + symbolKind = "constructor" /* constructorImplementationElement */; + addPrefixForAnyFunctionOrVar(type.symbol, symbolKind); + } + else if (symbolFlags & 2097152 /* Alias */) { + symbolKind = "alias" /* alias */; + pushSymbolKind(symbolKind); + displayParts.push(ts.spacePart()); + if (useConstructSignatures) { + displayParts.push(ts.keywordPart(95 /* NewKeyword */)); + displayParts.push(ts.spacePart()); + } + addFullSymbolName(symbol); + } + else { + addPrefixForAnyFunctionOrVar(symbol, symbolKind); + } + switch (symbolKind) { + case "JSX attribute" /* jsxAttribute */: + case "property" /* memberVariableElement */: + case "var" /* variableElement */: + case "const" /* constElement */: + case "let" /* letElement */: + case "parameter" /* parameterElement */: + case "local var" /* localVariableElement */: + // If it is call or construct signature of lambda's write type name + displayParts.push(ts.punctuationPart(57 /* ColonToken */)); + displayParts.push(ts.spacePart()); + if (!(ts.getObjectFlags(type) & 16 /* Anonymous */) && type.symbol) { + ts.addRange(displayParts, ts.symbolToDisplayParts(typeChecker, type.symbol, enclosingDeclaration, /*meaning*/ undefined, 4 /* AllowAnyNodeKind */ | 1 /* WriteTypeParametersOrArguments */)); + displayParts.push(ts.lineBreakPart()); + } + if (useConstructSignatures) { + displayParts.push(ts.keywordPart(95 /* NewKeyword */)); + displayParts.push(ts.spacePart()); + } + addSignatureDisplayParts(signature, allSignatures, 262144 /* WriteArrowStyleSignature */); + break; + default: + // Just signature + addSignatureDisplayParts(signature, allSignatures); + } + hasAddedSymbolInfo = true; + } + } + else if ((ts.isNameOfFunctionDeclaration(location) && !(symbolFlags & 98304 /* Accessor */)) || // name of function declaration + (location.kind === 124 /* ConstructorKeyword */ && location.parent.kind === 157 /* Constructor */)) { // At constructor keyword of constructor declaration + // get the signature from the declaration and write it + var functionDeclaration_1 = location.parent; + // Use function declaration to write the signatures only if the symbol corresponding to this declaration + var locationIsSymbolDeclaration = ts.find(symbol.declarations, function (declaration) { + return declaration === (location.kind === 124 /* ConstructorKeyword */ ? functionDeclaration_1.parent : functionDeclaration_1); + }); + if (locationIsSymbolDeclaration) { + var allSignatures = functionDeclaration_1.kind === 157 /* Constructor */ ? type.getNonNullableType().getConstructSignatures() : type.getNonNullableType().getCallSignatures(); + if (!typeChecker.isImplementationOfOverload(functionDeclaration_1)) { + signature = typeChecker.getSignatureFromDeclaration(functionDeclaration_1); // TODO: GH#18217 + } + else { + signature = allSignatures[0]; + } + if (functionDeclaration_1.kind === 157 /* Constructor */) { + // show (constructor) Type(...) signature + symbolKind = "constructor" /* constructorImplementationElement */; + addPrefixForAnyFunctionOrVar(type.symbol, symbolKind); + } + else { + // (function/method) symbol(..signature) + addPrefixForAnyFunctionOrVar(functionDeclaration_1.kind === 160 /* CallSignature */ && + !(type.symbol.flags & 2048 /* TypeLiteral */ || type.symbol.flags & 4096 /* ObjectLiteral */) ? type.symbol : symbol, symbolKind); + } + addSignatureDisplayParts(signature, allSignatures); + hasAddedSymbolInfo = true; + } + } + } + if (symbolFlags & 32 /* Class */ && !hasAddedSymbolInfo && !isThisExpression) { + addAliasPrefixIfNecessary(); + if (ts.getDeclarationOfKind(symbol, 209 /* ClassExpression */)) { + // Special case for class expressions because we would like to indicate that + // the class name is local to the class body (similar to function expression) + // (local class) class + pushSymbolKind("local class" /* localClassElement */); + } + else { + // Class declaration has name which is not local. + displayParts.push(ts.keywordPart(76 /* ClassKeyword */)); + } + displayParts.push(ts.spacePart()); + addFullSymbolName(symbol); + writeTypeParametersOfSymbol(symbol, sourceFile); + } + if ((symbolFlags & 64 /* Interface */) && (semanticMeaning & 2 /* Type */)) { + prefixNextMeaning(); + displayParts.push(ts.keywordPart(110 /* InterfaceKeyword */)); + displayParts.push(ts.spacePart()); + addFullSymbolName(symbol); + writeTypeParametersOfSymbol(symbol, sourceFile); + } + if ((symbolFlags & 524288 /* TypeAlias */) && (semanticMeaning & 2 /* Type */)) { + prefixNextMeaning(); + displayParts.push(ts.keywordPart(140 /* TypeKeyword */)); + displayParts.push(ts.spacePart()); + addFullSymbolName(symbol); + writeTypeParametersOfSymbol(symbol, sourceFile); + displayParts.push(ts.spacePart()); + displayParts.push(ts.operatorPart(59 /* EqualsToken */)); + displayParts.push(ts.spacePart()); + ts.addRange(displayParts, ts.typeToDisplayParts(typeChecker, typeChecker.getDeclaredTypeOfSymbol(symbol), enclosingDeclaration, 8388608 /* InTypeAlias */)); + } + if (symbolFlags & 384 /* Enum */) { + prefixNextMeaning(); + if (ts.some(symbol.declarations, function (d) { return ts.isEnumDeclaration(d) && ts.isEnumConst(d); })) { + displayParts.push(ts.keywordPart(77 /* ConstKeyword */)); + displayParts.push(ts.spacePart()); + } + displayParts.push(ts.keywordPart(84 /* EnumKeyword */)); + displayParts.push(ts.spacePart()); + addFullSymbolName(symbol); + } + if (symbolFlags & 1536 /* Module */) { + prefixNextMeaning(); + var declaration = ts.getDeclarationOfKind(symbol, 244 /* ModuleDeclaration */); + var isNamespace = declaration && declaration.name && declaration.name.kind === 72 /* Identifier */; + displayParts.push(ts.keywordPart(isNamespace ? 131 /* NamespaceKeyword */ : 130 /* ModuleKeyword */)); + displayParts.push(ts.spacePart()); + addFullSymbolName(symbol); + } + if ((symbolFlags & 262144 /* TypeParameter */) && (semanticMeaning & 2 /* Type */)) { + prefixNextMeaning(); + displayParts.push(ts.punctuationPart(20 /* OpenParenToken */)); + displayParts.push(ts.textPart("type parameter")); + displayParts.push(ts.punctuationPart(21 /* CloseParenToken */)); + displayParts.push(ts.spacePart()); + addFullSymbolName(symbol); + if (symbol.parent) { + // Class/Interface type parameter + addInPrefix(); + addFullSymbolName(symbol.parent, enclosingDeclaration); + writeTypeParametersOfSymbol(symbol.parent, enclosingDeclaration); + } + else { + // Method/function type parameter + var decl = ts.getDeclarationOfKind(symbol, 150 /* TypeParameter */); + if (decl === undefined) + return ts.Debug.fail(); + var declaration = decl.parent; + if (declaration) { + if (ts.isFunctionLikeKind(declaration.kind)) { + addInPrefix(); + var signature = typeChecker.getSignatureFromDeclaration(declaration); // TODO: GH#18217 + if (declaration.kind === 161 /* ConstructSignature */) { + displayParts.push(ts.keywordPart(95 /* NewKeyword */)); + displayParts.push(ts.spacePart()); + } + else if (declaration.kind !== 160 /* CallSignature */ && declaration.name) { + addFullSymbolName(declaration.symbol); + } + ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, sourceFile, 32 /* WriteTypeArgumentsOfSignature */)); + } + else if (declaration.kind === 242 /* TypeAliasDeclaration */) { + // Type alias type parameter + // For example + // type list = T[]; // Both T will go through same code path + addInPrefix(); + displayParts.push(ts.keywordPart(140 /* TypeKeyword */)); + displayParts.push(ts.spacePart()); + addFullSymbolName(declaration.symbol); + writeTypeParametersOfSymbol(declaration.symbol, sourceFile); + } + } + } + } + if (symbolFlags & 8 /* EnumMember */) { + symbolKind = "enum member" /* enumMemberElement */; + addPrefixForAnyFunctionOrVar(symbol, "enum member"); + var declaration = symbol.declarations[0]; + if (declaration.kind === 278 /* EnumMember */) { + var constantValue = typeChecker.getConstantValue(declaration); + if (constantValue !== undefined) { + displayParts.push(ts.spacePart()); + displayParts.push(ts.operatorPart(59 /* EqualsToken */)); + displayParts.push(ts.spacePart()); + displayParts.push(ts.displayPart(ts.getTextOfConstantValue(constantValue), typeof constantValue === "number" ? ts.SymbolDisplayPartKind.numericLiteral : ts.SymbolDisplayPartKind.stringLiteral)); + } + } + } + if (symbolFlags & 2097152 /* Alias */) { + prefixNextMeaning(); + if (!hasAddedSymbolInfo) { + var resolvedSymbol = typeChecker.getAliasedSymbol(symbol); + if (resolvedSymbol !== symbol && resolvedSymbol.declarations && resolvedSymbol.declarations.length > 0) { + var resolvedNode = resolvedSymbol.declarations[0]; + var declarationName = ts.getNameOfDeclaration(resolvedNode); + if (declarationName) { + var isExternalModuleDeclaration = ts.isModuleWithStringLiteralName(resolvedNode) && + ts.hasModifier(resolvedNode, 2 /* Ambient */); + var shouldUseAliasName = symbol.name !== "default" && !isExternalModuleDeclaration; + var resolvedInfo = getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, resolvedSymbol, ts.getSourceFileOfNode(resolvedNode), resolvedNode, declarationName, semanticMeaning, shouldUseAliasName ? symbol : resolvedSymbol); + displayParts.push.apply(displayParts, resolvedInfo.displayParts); + displayParts.push(ts.lineBreakPart()); + documentationFromAlias = resolvedInfo.documentation; + tagsFromAlias = resolvedInfo.tags; + } + } + } + switch (symbol.declarations[0].kind) { + case 247 /* NamespaceExportDeclaration */: + displayParts.push(ts.keywordPart(85 /* ExportKeyword */)); + displayParts.push(ts.spacePart()); + displayParts.push(ts.keywordPart(131 /* NamespaceKeyword */)); + break; + case 254 /* ExportAssignment */: + displayParts.push(ts.keywordPart(85 /* ExportKeyword */)); + displayParts.push(ts.spacePart()); + displayParts.push(ts.keywordPart(symbol.declarations[0].isExportEquals ? 59 /* EqualsToken */ : 80 /* DefaultKeyword */)); + break; + case 257 /* ExportSpecifier */: + displayParts.push(ts.keywordPart(85 /* ExportKeyword */)); + break; + default: + displayParts.push(ts.keywordPart(92 /* ImportKeyword */)); + } + displayParts.push(ts.spacePart()); + addFullSymbolName(symbol); + ts.forEach(symbol.declarations, function (declaration) { + if (declaration.kind === 248 /* ImportEqualsDeclaration */) { + var importEqualsDeclaration = declaration; + if (ts.isExternalModuleImportEqualsDeclaration(importEqualsDeclaration)) { + displayParts.push(ts.spacePart()); + displayParts.push(ts.operatorPart(59 /* EqualsToken */)); + displayParts.push(ts.spacePart()); + displayParts.push(ts.keywordPart(134 /* RequireKeyword */)); + displayParts.push(ts.punctuationPart(20 /* OpenParenToken */)); + displayParts.push(ts.displayPart(ts.getTextOfNode(ts.getExternalModuleImportEqualsDeclarationExpression(importEqualsDeclaration)), ts.SymbolDisplayPartKind.stringLiteral)); + displayParts.push(ts.punctuationPart(21 /* CloseParenToken */)); + } + else { + var internalAliasSymbol = typeChecker.getSymbolAtLocation(importEqualsDeclaration.moduleReference); + if (internalAliasSymbol) { + displayParts.push(ts.spacePart()); + displayParts.push(ts.operatorPart(59 /* EqualsToken */)); + displayParts.push(ts.spacePart()); + addFullSymbolName(internalAliasSymbol, enclosingDeclaration); + } + } + return true; + } + }); + } + if (!hasAddedSymbolInfo) { + if (symbolKind !== "" /* unknown */) { + if (type) { + if (isThisExpression) { + prefixNextMeaning(); + displayParts.push(ts.keywordPart(100 /* ThisKeyword */)); + } + else { + addPrefixForAnyFunctionOrVar(symbol, symbolKind); + } + // For properties, variables and local vars: show the type + if (symbolKind === "property" /* memberVariableElement */ || + symbolKind === "JSX attribute" /* jsxAttribute */ || + symbolFlags & 3 /* Variable */ || + symbolKind === "local var" /* localVariableElement */ || + isThisExpression) { + displayParts.push(ts.punctuationPart(57 /* ColonToken */)); + displayParts.push(ts.spacePart()); + // If the type is type parameter, format it specially + if (type.symbol && type.symbol.flags & 262144 /* TypeParameter */) { + var typeParameterParts = ts.mapToDisplayParts(function (writer) { + var param = typeChecker.typeParameterToDeclaration(type, enclosingDeclaration); + getPrinter().writeNode(4 /* Unspecified */, param, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosingDeclaration)), writer); + }); + ts.addRange(displayParts, typeParameterParts); + } + else { + ts.addRange(displayParts, ts.typeToDisplayParts(typeChecker, type, enclosingDeclaration)); + } + } + else if (symbolFlags & 16 /* Function */ || + symbolFlags & 8192 /* Method */ || + symbolFlags & 16384 /* Constructor */ || + symbolFlags & 131072 /* Signature */ || + symbolFlags & 98304 /* Accessor */ || + symbolKind === "method" /* memberFunctionElement */) { + var allSignatures = type.getNonNullableType().getCallSignatures(); + if (allSignatures.length) { + addSignatureDisplayParts(allSignatures[0], allSignatures); + } + } + } + } + else { + symbolKind = getSymbolKind(typeChecker, symbol, location); + } + } + if (!documentation) { + documentation = symbol.getDocumentationComment(typeChecker); + tags = symbol.getJsDocTags(); + if (documentation.length === 0 && symbolFlags & 4 /* Property */) { + // For some special property access expressions like `exports.foo = foo` or `module.exports.foo = foo` + // there documentation comments might be attached to the right hand side symbol of their declarations. + // The pattern of such special property access is that the parent symbol is the symbol of the file. + if (symbol.parent && ts.forEach(symbol.parent.declarations, function (declaration) { return declaration.kind === 279 /* SourceFile */; })) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (!declaration.parent || declaration.parent.kind !== 204 /* BinaryExpression */) { + continue; + } + var rhsSymbol = typeChecker.getSymbolAtLocation(declaration.parent.right); + if (!rhsSymbol) { + continue; + } + documentation = rhsSymbol.getDocumentationComment(typeChecker); + tags = rhsSymbol.getJsDocTags(); + if (documentation.length > 0) { + break; + } + } + } + } + } + if (documentation.length === 0 && documentationFromAlias) { + documentation = documentationFromAlias; + } + if (tags.length === 0 && tagsFromAlias) { + tags = tagsFromAlias; + } + return { displayParts: displayParts, documentation: documentation, symbolKind: symbolKind, tags: tags.length === 0 ? undefined : tags }; + function getPrinter() { + if (!printer) { + printer = ts.createPrinter({ removeComments: true }); + } + return printer; + } + function prefixNextMeaning() { + if (displayParts.length) { + displayParts.push(ts.lineBreakPart()); + } + addAliasPrefixIfNecessary(); + } + function addAliasPrefixIfNecessary() { + if (alias) { + pushSymbolKind("alias" /* alias */); + displayParts.push(ts.spacePart()); + } + } + function addInPrefix() { + displayParts.push(ts.spacePart()); + displayParts.push(ts.keywordPart(93 /* InKeyword */)); + displayParts.push(ts.spacePart()); + } + function addFullSymbolName(symbolToDisplay, enclosingDeclaration) { + if (alias && symbolToDisplay === symbol) { + symbolToDisplay = alias; + } + var fullSymbolDisplayParts = ts.symbolToDisplayParts(typeChecker, symbolToDisplay, enclosingDeclaration || sourceFile, /*meaning*/ undefined, 1 /* WriteTypeParametersOrArguments */ | 2 /* UseOnlyExternalAliasing */ | 4 /* AllowAnyNodeKind */); + ts.addRange(displayParts, fullSymbolDisplayParts); + if (symbol.flags & 16777216 /* Optional */) { + displayParts.push(ts.punctuationPart(56 /* QuestionToken */)); + } + } + function addPrefixForAnyFunctionOrVar(symbol, symbolKind) { + prefixNextMeaning(); + if (symbolKind) { + pushSymbolKind(symbolKind); + if (symbol && !ts.some(symbol.declarations, function (d) { return ts.isArrowFunction(d) || (ts.isFunctionExpression(d) || ts.isClassExpression(d)) && !d.name; })) { + displayParts.push(ts.spacePart()); + addFullSymbolName(symbol); + } + } + } + function pushSymbolKind(symbolKind) { + switch (symbolKind) { + case "var" /* variableElement */: + case "function" /* functionElement */: + case "let" /* letElement */: + case "const" /* constElement */: + case "constructor" /* constructorImplementationElement */: + displayParts.push(ts.textOrKeywordPart(symbolKind)); + return; + default: + displayParts.push(ts.punctuationPart(20 /* OpenParenToken */)); + displayParts.push(ts.textOrKeywordPart(symbolKind)); + displayParts.push(ts.punctuationPart(21 /* CloseParenToken */)); + return; + } + } + function addSignatureDisplayParts(signature, allSignatures, flags) { + if (flags === void 0) { flags = 0 /* None */; } + ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, enclosingDeclaration, flags | 32 /* WriteTypeArgumentsOfSignature */)); + if (allSignatures.length > 1) { + displayParts.push(ts.spacePart()); + displayParts.push(ts.punctuationPart(20 /* OpenParenToken */)); + displayParts.push(ts.operatorPart(38 /* PlusToken */)); + displayParts.push(ts.displayPart((allSignatures.length - 1).toString(), ts.SymbolDisplayPartKind.numericLiteral)); + displayParts.push(ts.spacePart()); + displayParts.push(ts.textPart(allSignatures.length === 2 ? "overload" : "overloads")); + displayParts.push(ts.punctuationPart(21 /* CloseParenToken */)); + } + var docComment = signature.getDocumentationComment(typeChecker); + documentation = docComment.length === 0 ? undefined : docComment; + tags = signature.getJsDocTags(); + } + function writeTypeParametersOfSymbol(symbol, enclosingDeclaration) { + var typeParameterParts = ts.mapToDisplayParts(function (writer) { + var params = typeChecker.symbolToTypeParameterDeclarations(symbol, enclosingDeclaration); + getPrinter().writeList(53776 /* TypeParameters */, params, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosingDeclaration)), writer); + }); + ts.addRange(displayParts, typeParameterParts); + } + } + SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind = getSymbolDisplayPartsDocumentationAndSymbolKind; + function isLocalVariableOrFunction(symbol) { + if (symbol.parent) { + return false; // This is exported symbol + } + return ts.forEach(symbol.declarations, function (declaration) { + // Function expressions are local + if (declaration.kind === 196 /* FunctionExpression */) { + return true; + } + if (declaration.kind !== 237 /* VariableDeclaration */ && declaration.kind !== 239 /* FunctionDeclaration */) { + return false; + } + // If the parent is not sourceFile or module block it is local variable + for (var parent = declaration.parent; !ts.isFunctionBlock(parent); parent = parent.parent) { + // Reached source file or module block + if (parent.kind === 279 /* SourceFile */ || parent.kind === 245 /* ModuleBlock */) { + return false; + } + } + // parent is in function block + return true; + }); + } + })(SymbolDisplay = ts.SymbolDisplay || (ts.SymbolDisplay = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + /* + * This function will compile source text from 'input' argument using specified compiler options. + * If not options are provided - it will use a set of default compiler options. + * Extra compiler options that will unconditionally be used by this function are: + * - isolatedModules = true + * - allowNonTsExtensions = true + * - noLib = true + * - noResolve = true + */ + function transpileModule(input, transpileOptions) { + var diagnostics = []; + var options = transpileOptions.compilerOptions ? fixupCompilerOptions(transpileOptions.compilerOptions, diagnostics) : ts.getDefaultCompilerOptions(); + options.isolatedModules = true; + // transpileModule does not write anything to disk so there is no need to verify that there are no conflicts between input and output paths. + options.suppressOutputPathCheck = true; + // Filename can be non-ts file. + options.allowNonTsExtensions = true; + // We are not returning a sourceFile for lib file when asked by the program, + // so pass --noLib to avoid reporting a file not found error. + options.noLib = true; + // Clear out other settings that would not be used in transpiling this module + options.lib = undefined; + options.types = undefined; + options.noEmit = undefined; + options.noEmitOnError = undefined; + options.paths = undefined; + options.rootDirs = undefined; + options.declaration = undefined; + options.composite = undefined; + options.declarationDir = undefined; + options.out = undefined; + options.outFile = undefined; + // We are not doing a full typecheck, we are not resolving the whole context, + // so pass --noResolve to avoid reporting missing file errors. + options.noResolve = true; + // if jsx is specified then treat file as .tsx + var inputFileName = transpileOptions.fileName || (options.jsx ? "module.tsx" : "module.ts"); + var sourceFile = ts.createSourceFile(inputFileName, input, options.target); // TODO: GH#18217 + if (transpileOptions.moduleName) { + sourceFile.moduleName = transpileOptions.moduleName; + } + if (transpileOptions.renamedDependencies) { + sourceFile.renamedDependencies = ts.createMapFromTemplate(transpileOptions.renamedDependencies); + } + var newLine = ts.getNewLineCharacter(options); + // Output + var outputText; + var sourceMapText; + // Create a compilerHost object to allow the compiler to read and write files + var compilerHost = { + getSourceFile: function (fileName) { return fileName === ts.normalizePath(inputFileName) ? sourceFile : undefined; }, + writeFile: function (name, text) { + if (ts.fileExtensionIs(name, ".map")) { + ts.Debug.assertEqual(sourceMapText, undefined, "Unexpected multiple source map outputs, file:", name); + sourceMapText = text; + } + else { + ts.Debug.assertEqual(outputText, undefined, "Unexpected multiple outputs, file:", name); + outputText = text; + } + }, + getDefaultLibFileName: function () { return "lib.d.ts"; }, + useCaseSensitiveFileNames: function () { return false; }, + getCanonicalFileName: function (fileName) { return fileName; }, + getCurrentDirectory: function () { return ""; }, + getNewLine: function () { return newLine; }, + fileExists: function (fileName) { return fileName === inputFileName; }, + readFile: function () { return ""; }, + directoryExists: function () { return true; }, + getDirectories: function () { return []; } + }; + var program = ts.createProgram([inputFileName], options, compilerHost); + if (transpileOptions.reportDiagnostics) { + ts.addRange(/*to*/ diagnostics, /*from*/ program.getSyntacticDiagnostics(sourceFile)); + ts.addRange(/*to*/ diagnostics, /*from*/ program.getOptionsDiagnostics()); + } + // Emit + program.emit(/*targetSourceFile*/ undefined, /*writeFile*/ undefined, /*cancellationToken*/ undefined, /*emitOnlyDtsFiles*/ undefined, transpileOptions.transformers); + if (outputText === undefined) + return ts.Debug.fail("Output generation failed"); + return { outputText: outputText, diagnostics: diagnostics, sourceMapText: sourceMapText }; + } + ts.transpileModule = transpileModule; + /* + * This is a shortcut function for transpileModule - it accepts transpileOptions as parameters and returns only outputText part of the result. + */ + function transpile(input, compilerOptions, fileName, diagnostics, moduleName) { + var output = transpileModule(input, { compilerOptions: compilerOptions, fileName: fileName, reportDiagnostics: !!diagnostics, moduleName: moduleName }); + // addRange correctly handles cases when wither 'from' or 'to' argument is missing + ts.addRange(diagnostics, output.diagnostics); + return output.outputText; + } + ts.transpile = transpile; + var commandLineOptionsStringToEnum; + /** JS users may pass in string values for enum compiler options (such as ModuleKind), so convert. */ + /*@internal*/ + function fixupCompilerOptions(options, diagnostics) { + // Lazily create this value to fix module loading errors. + commandLineOptionsStringToEnum = commandLineOptionsStringToEnum || ts.filter(ts.optionDeclarations, function (o) { + return typeof o.type === "object" && !ts.forEachEntry(o.type, function (v) { return typeof v !== "number"; }); + }); + options = ts.cloneCompilerOptions(options); + var _loop_7 = function (opt) { + if (!ts.hasProperty(options, opt.name)) { + return "continue"; + } + var value = options[opt.name]; + // Value should be a key of opt.type + if (ts.isString(value)) { + // If value is not a string, this will fail + options[opt.name] = ts.parseCustomTypeOption(opt, value, diagnostics); + } + else { + if (!ts.forEachEntry(opt.type, function (v) { return v === value; })) { + // Supplied value isn't a valid enum value. + diagnostics.push(ts.createCompilerDiagnosticForInvalidCustomType(opt)); + } + } + }; + for (var _i = 0, commandLineOptionsStringToEnum_1 = commandLineOptionsStringToEnum; _i < commandLineOptionsStringToEnum_1.length; _i++) { + var opt = commandLineOptionsStringToEnum_1[_i]; + _loop_7(opt); + } + return options; + } + ts.fixupCompilerOptions = fixupCompilerOptions; +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var formatting; + (function (formatting) { + var FormattingRequestKind; + (function (FormattingRequestKind) { + FormattingRequestKind[FormattingRequestKind["FormatDocument"] = 0] = "FormatDocument"; + FormattingRequestKind[FormattingRequestKind["FormatSelection"] = 1] = "FormatSelection"; + FormattingRequestKind[FormattingRequestKind["FormatOnEnter"] = 2] = "FormatOnEnter"; + FormattingRequestKind[FormattingRequestKind["FormatOnSemicolon"] = 3] = "FormatOnSemicolon"; + FormattingRequestKind[FormattingRequestKind["FormatOnOpeningCurlyBrace"] = 4] = "FormatOnOpeningCurlyBrace"; + FormattingRequestKind[FormattingRequestKind["FormatOnClosingCurlyBrace"] = 5] = "FormatOnClosingCurlyBrace"; + })(FormattingRequestKind = formatting.FormattingRequestKind || (formatting.FormattingRequestKind = {})); + var FormattingContext = /** @class */ (function () { + function FormattingContext(sourceFile, formattingRequestKind, options) { + this.sourceFile = sourceFile; + this.formattingRequestKind = formattingRequestKind; + this.options = options; + } + FormattingContext.prototype.updateContext = function (currentRange, currentTokenParent, nextRange, nextTokenParent, commonParent) { + this.currentTokenSpan = ts.Debug.assertDefined(currentRange); + this.currentTokenParent = ts.Debug.assertDefined(currentTokenParent); + this.nextTokenSpan = ts.Debug.assertDefined(nextRange); + this.nextTokenParent = ts.Debug.assertDefined(nextTokenParent); + this.contextNode = ts.Debug.assertDefined(commonParent); + // drop cached results + this.contextNodeAllOnSameLine = undefined; + this.nextNodeAllOnSameLine = undefined; + this.tokensAreOnSameLine = undefined; + this.contextNodeBlockIsOnOneLine = undefined; + this.nextNodeBlockIsOnOneLine = undefined; + }; + FormattingContext.prototype.ContextNodeAllOnSameLine = function () { + if (this.contextNodeAllOnSameLine === undefined) { + this.contextNodeAllOnSameLine = this.NodeIsOnOneLine(this.contextNode); + } + return this.contextNodeAllOnSameLine; + }; + FormattingContext.prototype.NextNodeAllOnSameLine = function () { + if (this.nextNodeAllOnSameLine === undefined) { + this.nextNodeAllOnSameLine = this.NodeIsOnOneLine(this.nextTokenParent); + } + return this.nextNodeAllOnSameLine; + }; + FormattingContext.prototype.TokensAreOnSameLine = function () { + if (this.tokensAreOnSameLine === undefined) { + var startLine = this.sourceFile.getLineAndCharacterOfPosition(this.currentTokenSpan.pos).line; + var endLine = this.sourceFile.getLineAndCharacterOfPosition(this.nextTokenSpan.pos).line; + this.tokensAreOnSameLine = (startLine === endLine); + } + return this.tokensAreOnSameLine; + }; + FormattingContext.prototype.ContextNodeBlockIsOnOneLine = function () { + if (this.contextNodeBlockIsOnOneLine === undefined) { + this.contextNodeBlockIsOnOneLine = this.BlockIsOnOneLine(this.contextNode); + } + return this.contextNodeBlockIsOnOneLine; + }; + FormattingContext.prototype.NextNodeBlockIsOnOneLine = function () { + if (this.nextNodeBlockIsOnOneLine === undefined) { + this.nextNodeBlockIsOnOneLine = this.BlockIsOnOneLine(this.nextTokenParent); + } + return this.nextNodeBlockIsOnOneLine; + }; + FormattingContext.prototype.NodeIsOnOneLine = function (node) { + var startLine = this.sourceFile.getLineAndCharacterOfPosition(node.getStart(this.sourceFile)).line; + var endLine = this.sourceFile.getLineAndCharacterOfPosition(node.getEnd()).line; + return startLine === endLine; + }; + FormattingContext.prototype.BlockIsOnOneLine = function (node) { + var openBrace = ts.findChildOfKind(node, 18 /* OpenBraceToken */, this.sourceFile); + var closeBrace = ts.findChildOfKind(node, 19 /* CloseBraceToken */, this.sourceFile); + if (openBrace && closeBrace) { + var startLine = this.sourceFile.getLineAndCharacterOfPosition(openBrace.getEnd()).line; + var endLine = this.sourceFile.getLineAndCharacterOfPosition(closeBrace.getStart(this.sourceFile)).line; + return startLine === endLine; + } + return false; + }; + return FormattingContext; + }()); + formatting.FormattingContext = FormattingContext; + })(formatting = ts.formatting || (ts.formatting = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var formatting; + (function (formatting) { + var standardScanner = ts.createScanner(6 /* Latest */, /*skipTrivia*/ false, 0 /* Standard */); + var jsxScanner = ts.createScanner(6 /* Latest */, /*skipTrivia*/ false, 1 /* JSX */); + var ScanAction; + (function (ScanAction) { + ScanAction[ScanAction["Scan"] = 0] = "Scan"; + ScanAction[ScanAction["RescanGreaterThanToken"] = 1] = "RescanGreaterThanToken"; + ScanAction[ScanAction["RescanSlashToken"] = 2] = "RescanSlashToken"; + ScanAction[ScanAction["RescanTemplateToken"] = 3] = "RescanTemplateToken"; + ScanAction[ScanAction["RescanJsxIdentifier"] = 4] = "RescanJsxIdentifier"; + ScanAction[ScanAction["RescanJsxText"] = 5] = "RescanJsxText"; + })(ScanAction || (ScanAction = {})); + function getFormattingScanner(text, languageVariant, startPos, endPos, cb) { + var scanner = languageVariant === 1 /* JSX */ ? jsxScanner : standardScanner; + scanner.setText(text); + scanner.setTextPos(startPos); + var wasNewLine = true; + var leadingTrivia; + var trailingTrivia; + var savedPos; + var lastScanAction; + var lastTokenInfo; + var res = cb({ + advance: advance, + readTokenInfo: readTokenInfo, + isOnToken: isOnToken, + getCurrentLeadingTrivia: function () { return leadingTrivia; }, + lastTrailingTriviaWasNewLine: function () { return wasNewLine; }, + skipToEndOf: skipToEndOf, + }); + lastTokenInfo = undefined; + scanner.setText(undefined); + return res; + function advance() { + lastTokenInfo = undefined; + var isStarted = scanner.getStartPos() !== startPos; + if (isStarted) { + wasNewLine = !!trailingTrivia && ts.last(trailingTrivia).kind === 4 /* NewLineTrivia */; + } + else { + scanner.scan(); + } + leadingTrivia = undefined; + trailingTrivia = undefined; + var pos = scanner.getStartPos(); + // Read leading trivia and token + while (pos < endPos) { + var t = scanner.getToken(); + if (!ts.isTrivia(t)) { + break; + } + // consume leading trivia + scanner.scan(); + var item = { + pos: pos, + end: scanner.getStartPos(), + kind: t + }; + pos = scanner.getStartPos(); + leadingTrivia = ts.append(leadingTrivia, item); + } + savedPos = scanner.getStartPos(); + } + function shouldRescanGreaterThanToken(node) { + switch (node.kind) { + case 32 /* GreaterThanEqualsToken */: + case 67 /* GreaterThanGreaterThanEqualsToken */: + case 68 /* GreaterThanGreaterThanGreaterThanEqualsToken */: + case 48 /* GreaterThanGreaterThanGreaterThanToken */: + case 47 /* GreaterThanGreaterThanToken */: + return true; + } + return false; + } + function shouldRescanJsxIdentifier(node) { + if (node.parent) { + switch (node.parent.kind) { + case 267 /* JsxAttribute */: + case 262 /* JsxOpeningElement */: + case 263 /* JsxClosingElement */: + case 261 /* JsxSelfClosingElement */: + // May parse an identifier like `module-layout`; that will be scanned as a keyword at first, but we should parse the whole thing to get an identifier. + return ts.isKeyword(node.kind) || node.kind === 72 /* Identifier */; + } + } + return false; + } + function shouldRescanJsxText(node) { + return node.kind === 11 /* JsxText */; + } + function shouldRescanSlashToken(container) { + return container.kind === 13 /* RegularExpressionLiteral */; + } + function shouldRescanTemplateToken(container) { + return container.kind === 16 /* TemplateMiddle */ || + container.kind === 17 /* TemplateTail */; + } + function startsWithSlashToken(t) { + return t === 42 /* SlashToken */ || t === 64 /* SlashEqualsToken */; + } + function readTokenInfo(n) { + ts.Debug.assert(isOnToken()); + // normally scanner returns the smallest available token + // check the kind of context node to determine if scanner should have more greedy behavior and consume more text. + var expectedScanAction = shouldRescanGreaterThanToken(n) + ? 1 /* RescanGreaterThanToken */ + : shouldRescanSlashToken(n) + ? 2 /* RescanSlashToken */ + : shouldRescanTemplateToken(n) + ? 3 /* RescanTemplateToken */ + : shouldRescanJsxIdentifier(n) + ? 4 /* RescanJsxIdentifier */ + : shouldRescanJsxText(n) + ? 5 /* RescanJsxText */ + : 0 /* Scan */; + if (lastTokenInfo && expectedScanAction === lastScanAction) { + // readTokenInfo was called before with the same expected scan action. + // No need to re-scan text, return existing 'lastTokenInfo' + // it is ok to call fixTokenKind here since it does not affect + // what portion of text is consumed. In contrast rescanning can change it, + // i.e. for '>=' when originally scanner eats just one character + // and rescanning forces it to consume more. + return fixTokenKind(lastTokenInfo, n); + } + if (scanner.getStartPos() !== savedPos) { + ts.Debug.assert(lastTokenInfo !== undefined); + // readTokenInfo was called before but scan action differs - rescan text + scanner.setTextPos(savedPos); + scanner.scan(); + } + var currentToken = getNextToken(n, expectedScanAction); + var token = { + pos: scanner.getStartPos(), + end: scanner.getTextPos(), + kind: currentToken + }; + // consume trailing trivia + if (trailingTrivia) { + trailingTrivia = undefined; + } + while (scanner.getStartPos() < endPos) { + currentToken = scanner.scan(); + if (!ts.isTrivia(currentToken)) { + break; + } + var trivia = { + pos: scanner.getStartPos(), + end: scanner.getTextPos(), + kind: currentToken + }; + if (!trailingTrivia) { + trailingTrivia = []; + } + trailingTrivia.push(trivia); + if (currentToken === 4 /* NewLineTrivia */) { + // move past new line + scanner.scan(); + break; + } + } + lastTokenInfo = { leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia, token: token }; + return fixTokenKind(lastTokenInfo, n); + } + function getNextToken(n, expectedScanAction) { + var token = scanner.getToken(); + lastScanAction = 0 /* Scan */; + switch (expectedScanAction) { + case 1 /* RescanGreaterThanToken */: + if (token === 30 /* GreaterThanToken */) { + lastScanAction = 1 /* RescanGreaterThanToken */; + var newToken = scanner.reScanGreaterToken(); + ts.Debug.assert(n.kind === newToken); + return newToken; + } + break; + case 2 /* RescanSlashToken */: + if (startsWithSlashToken(token)) { + lastScanAction = 2 /* RescanSlashToken */; + var newToken = scanner.reScanSlashToken(); + ts.Debug.assert(n.kind === newToken); + return newToken; + } + break; + case 3 /* RescanTemplateToken */: + if (token === 19 /* CloseBraceToken */) { + lastScanAction = 3 /* RescanTemplateToken */; + return scanner.reScanTemplateToken(); + } + break; + case 4 /* RescanJsxIdentifier */: + lastScanAction = 4 /* RescanJsxIdentifier */; + return scanner.scanJsxIdentifier(); + case 5 /* RescanJsxText */: + lastScanAction = 5 /* RescanJsxText */; + return scanner.reScanJsxToken(); + case 0 /* Scan */: + break; + default: + ts.Debug.assertNever(expectedScanAction); + } + return token; + } + function isOnToken() { + var current = lastTokenInfo ? lastTokenInfo.token.kind : scanner.getToken(); + var startPos = lastTokenInfo ? lastTokenInfo.token.pos : scanner.getStartPos(); + return startPos < endPos && current !== 1 /* EndOfFileToken */ && !ts.isTrivia(current); + } + // when containing node in the tree is token + // but its kind differs from the kind that was returned by the scanner, + // then kind needs to be fixed. This might happen in cases + // when parser interprets token differently, i.e keyword treated as identifier + function fixTokenKind(tokenInfo, container) { + if (ts.isToken(container) && tokenInfo.token.kind !== container.kind) { + tokenInfo.token.kind = container.kind; + } + return tokenInfo; + } + function skipToEndOf(node) { + scanner.setTextPos(node.end); + savedPos = scanner.getStartPos(); + lastScanAction = undefined; + lastTokenInfo = undefined; + wasNewLine = false; + leadingTrivia = undefined; + trailingTrivia = undefined; + } + } + formatting.getFormattingScanner = getFormattingScanner; + })(formatting = ts.formatting || (ts.formatting = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var formatting; + (function (formatting) { + formatting.anyContext = ts.emptyArray; + var RuleAction; + (function (RuleAction) { + RuleAction[RuleAction["Ignore"] = 1] = "Ignore"; + RuleAction[RuleAction["Space"] = 2] = "Space"; + RuleAction[RuleAction["NewLine"] = 4] = "NewLine"; + RuleAction[RuleAction["Delete"] = 8] = "Delete"; + })(RuleAction = formatting.RuleAction || (formatting.RuleAction = {})); + var RuleFlags; + (function (RuleFlags) { + RuleFlags[RuleFlags["None"] = 0] = "None"; + RuleFlags[RuleFlags["CanDeleteNewLines"] = 1] = "CanDeleteNewLines"; + })(RuleFlags = formatting.RuleFlags || (formatting.RuleFlags = {})); + })(formatting = ts.formatting || (ts.formatting = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var formatting; + (function (formatting) { + function getAllRules() { + var allTokens = []; + for (var token = 0 /* FirstToken */; token <= 147 /* LastToken */; token++) { + allTokens.push(token); + } + function anyTokenExcept() { + var tokens = []; + for (var _i = 0; _i < arguments.length; _i++) { + tokens[_i] = arguments[_i]; + } + return { tokens: allTokens.filter(function (t) { return !tokens.some(function (t2) { return t2 === t; }); }), isSpecific: false }; + } + var anyToken = { tokens: allTokens, isSpecific: false }; + var anyTokenIncludingMultilineComments = tokenRangeFrom(allTokens.concat([3 /* MultiLineCommentTrivia */])); + var keywords = tokenRangeFromRange(73 /* FirstKeyword */, 147 /* LastKeyword */); + var binaryOperators = tokenRangeFromRange(28 /* FirstBinaryOperator */, 71 /* LastBinaryOperator */); + var binaryKeywordOperators = [93 /* InKeyword */, 94 /* InstanceOfKeyword */, 147 /* OfKeyword */, 119 /* AsKeyword */, 128 /* IsKeyword */]; + var unaryPrefixOperators = [44 /* PlusPlusToken */, 45 /* MinusMinusToken */, 53 /* TildeToken */, 52 /* ExclamationToken */]; + var unaryPrefixExpressions = [ + 8 /* NumericLiteral */, 9 /* BigIntLiteral */, 72 /* Identifier */, 20 /* OpenParenToken */, + 22 /* OpenBracketToken */, 18 /* OpenBraceToken */, 100 /* ThisKeyword */, 95 /* NewKeyword */ + ]; + var unaryPreincrementExpressions = [72 /* Identifier */, 20 /* OpenParenToken */, 100 /* ThisKeyword */, 95 /* NewKeyword */]; + var unaryPostincrementExpressions = [72 /* Identifier */, 21 /* CloseParenToken */, 23 /* CloseBracketToken */, 95 /* NewKeyword */]; + var unaryPredecrementExpressions = [72 /* Identifier */, 20 /* OpenParenToken */, 100 /* ThisKeyword */, 95 /* NewKeyword */]; + var unaryPostdecrementExpressions = [72 /* Identifier */, 21 /* CloseParenToken */, 23 /* CloseBracketToken */, 95 /* NewKeyword */]; + var comments = [2 /* SingleLineCommentTrivia */, 3 /* MultiLineCommentTrivia */]; + var typeNames = [72 /* Identifier */].concat(ts.typeKeywords); + // Place a space before open brace in a function declaration + // TypeScript: Function can have return types, which can be made of tons of different token kinds + var functionOpenBraceLeftTokenRange = anyTokenIncludingMultilineComments; + // Place a space before open brace in a TypeScript declaration that has braces as children (class, module, enum, etc) + var typeScriptOpenBraceLeftTokenRange = tokenRangeFrom([72 /* Identifier */, 3 /* MultiLineCommentTrivia */, 76 /* ClassKeyword */, 85 /* ExportKeyword */, 92 /* ImportKeyword */]); + // Place a space before open brace in a control flow construct + var controlOpenBraceLeftTokenRange = tokenRangeFrom([21 /* CloseParenToken */, 3 /* MultiLineCommentTrivia */, 82 /* DoKeyword */, 103 /* TryKeyword */, 88 /* FinallyKeyword */, 83 /* ElseKeyword */]); + // These rules are higher in priority than user-configurable + var highPriorityCommonRules = [ + // Leave comments alone + rule("IgnoreBeforeComment", anyToken, comments, formatting.anyContext, 1 /* Ignore */), + rule("IgnoreAfterLineComment", 2 /* SingleLineCommentTrivia */, anyToken, formatting.anyContext, 1 /* Ignore */), + rule("NotSpaceBeforeColon", anyToken, 57 /* ColonToken */, [isNonJsxSameLineTokenContext, isNotBinaryOpContext, isNotTypeAnnotationContext], 8 /* Delete */), + rule("SpaceAfterColon", 57 /* ColonToken */, anyToken, [isNonJsxSameLineTokenContext, isNotBinaryOpContext], 2 /* Space */), + rule("NoSpaceBeforeQuestionMark", anyToken, 56 /* QuestionToken */, [isNonJsxSameLineTokenContext, isNotBinaryOpContext], 8 /* Delete */), + // insert space after '?' only when it is used in conditional operator + rule("SpaceAfterQuestionMarkInConditionalOperator", 56 /* QuestionToken */, anyToken, [isNonJsxSameLineTokenContext, isConditionalOperatorContext], 2 /* Space */), + // in other cases there should be no space between '?' and next token + rule("NoSpaceAfterQuestionMark", 56 /* QuestionToken */, anyToken, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceBeforeDot", anyToken, 24 /* DotToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceAfterDot", 24 /* DotToken */, anyToken, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceBetweenImportParenInImportType", 92 /* ImportKeyword */, 20 /* OpenParenToken */, [isNonJsxSameLineTokenContext, isImportTypeContext], 8 /* Delete */), + // Special handling of unary operators. + // Prefix operators generally shouldn't have a space between + // them and their target unary expression. + rule("NoSpaceAfterUnaryPrefixOperator", unaryPrefixOperators, unaryPrefixExpressions, [isNonJsxSameLineTokenContext, isNotBinaryOpContext], 8 /* Delete */), + rule("NoSpaceAfterUnaryPreincrementOperator", 44 /* PlusPlusToken */, unaryPreincrementExpressions, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceAfterUnaryPredecrementOperator", 45 /* MinusMinusToken */, unaryPredecrementExpressions, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceBeforeUnaryPostincrementOperator", unaryPostincrementExpressions, 44 /* PlusPlusToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceBeforeUnaryPostdecrementOperator", unaryPostdecrementExpressions, 45 /* MinusMinusToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + // More unary operator special-casing. + // DevDiv 181814: Be careful when removing leading whitespace + // around unary operators. Examples: + // 1 - -2 --X--> 1--2 + // a + ++b --X--> a+++b + rule("SpaceAfterPostincrementWhenFollowedByAdd", 44 /* PlusPlusToken */, 38 /* PlusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), + rule("SpaceAfterAddWhenFollowedByUnaryPlus", 38 /* PlusToken */, 38 /* PlusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), + rule("SpaceAfterAddWhenFollowedByPreincrement", 38 /* PlusToken */, 44 /* PlusPlusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), + rule("SpaceAfterPostdecrementWhenFollowedBySubtract", 45 /* MinusMinusToken */, 39 /* MinusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), + rule("SpaceAfterSubtractWhenFollowedByUnaryMinus", 39 /* MinusToken */, 39 /* MinusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), + rule("SpaceAfterSubtractWhenFollowedByPredecrement", 39 /* MinusToken */, 45 /* MinusMinusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), + rule("NoSpaceAfterCloseBrace", 19 /* CloseBraceToken */, [27 /* CommaToken */, 26 /* SemicolonToken */], [isNonJsxSameLineTokenContext], 8 /* Delete */), + // For functions and control block place } on a new line [multi-line rule] + rule("NewLineBeforeCloseBraceInBlockContext", anyTokenIncludingMultilineComments, 19 /* CloseBraceToken */, [isMultilineBlockContext], 4 /* NewLine */), + // Space/new line after }. + rule("SpaceAfterCloseBrace", 19 /* CloseBraceToken */, anyTokenExcept(21 /* CloseParenToken */), [isNonJsxSameLineTokenContext, isAfterCodeBlockContext], 2 /* Space */), + // Special case for (}, else) and (}, while) since else & while tokens are not part of the tree which makes SpaceAfterCloseBrace rule not applied + // Also should not apply to }) + rule("SpaceBetweenCloseBraceAndElse", 19 /* CloseBraceToken */, 83 /* ElseKeyword */, [isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceBetweenCloseBraceAndWhile", 19 /* CloseBraceToken */, 107 /* WhileKeyword */, [isNonJsxSameLineTokenContext], 2 /* Space */), + rule("NoSpaceBetweenEmptyBraceBrackets", 18 /* OpenBraceToken */, 19 /* CloseBraceToken */, [isNonJsxSameLineTokenContext, isObjectContext], 8 /* Delete */), + // Add a space after control dec context if the next character is an open bracket ex: 'if (false)[a, b] = [1, 2];' -> 'if (false) [a, b] = [1, 2];' + rule("SpaceAfterConditionalClosingParen", 21 /* CloseParenToken */, 22 /* OpenBracketToken */, [isControlDeclContext], 2 /* Space */), + rule("NoSpaceBetweenFunctionKeywordAndStar", 90 /* FunctionKeyword */, 40 /* AsteriskToken */, [isFunctionDeclarationOrFunctionExpressionContext], 8 /* Delete */), + rule("SpaceAfterStarInGeneratorDeclaration", 40 /* AsteriskToken */, [72 /* Identifier */, 20 /* OpenParenToken */], [isFunctionDeclarationOrFunctionExpressionContext], 2 /* Space */), + rule("SpaceAfterFunctionInFuncDecl", 90 /* FunctionKeyword */, anyToken, [isFunctionDeclContext], 2 /* Space */), + // Insert new line after { and before } in multi-line contexts. + rule("NewLineAfterOpenBraceInBlockContext", 18 /* OpenBraceToken */, anyToken, [isMultilineBlockContext], 4 /* NewLine */), + // For get/set members, we check for (identifier,identifier) since get/set don't have tokens and they are represented as just an identifier token. + // Though, we do extra check on the context to make sure we are dealing with get/set node. Example: + // get x() {} + // set x(val) {} + rule("SpaceAfterGetSetInMember", [126 /* GetKeyword */, 137 /* SetKeyword */], 72 /* Identifier */, [isFunctionDeclContext], 2 /* Space */), + rule("NoSpaceBetweenYieldKeywordAndStar", 117 /* YieldKeyword */, 40 /* AsteriskToken */, [isNonJsxSameLineTokenContext, isYieldOrYieldStarWithOperand], 8 /* Delete */), + rule("SpaceBetweenYieldOrYieldStarAndOperand", [117 /* YieldKeyword */, 40 /* AsteriskToken */], anyToken, [isNonJsxSameLineTokenContext, isYieldOrYieldStarWithOperand], 2 /* Space */), + rule("NoSpaceBetweenReturnAndSemicolon", 97 /* ReturnKeyword */, 26 /* SemicolonToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("SpaceAfterCertainKeywords", [105 /* VarKeyword */, 101 /* ThrowKeyword */, 95 /* NewKeyword */, 81 /* DeleteKeyword */, 97 /* ReturnKeyword */, 104 /* TypeOfKeyword */, 122 /* AwaitKeyword */], anyToken, [isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceAfterLetConstInVariableDeclaration", [111 /* LetKeyword */, 77 /* ConstKeyword */], anyToken, [isNonJsxSameLineTokenContext, isStartOfVariableDeclarationList], 2 /* Space */), + rule("NoSpaceBeforeOpenParenInFuncCall", anyToken, 20 /* OpenParenToken */, [isNonJsxSameLineTokenContext, isFunctionCallOrNewContext, isPreviousTokenNotComma], 8 /* Delete */), + // Special case for binary operators (that are keywords). For these we have to add a space and shouldn't follow any user options. + rule("SpaceBeforeBinaryKeywordOperator", anyToken, binaryKeywordOperators, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), + rule("SpaceAfterBinaryKeywordOperator", binaryKeywordOperators, anyToken, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), + rule("SpaceAfterVoidOperator", 106 /* VoidKeyword */, anyToken, [isNonJsxSameLineTokenContext, isVoidOpContext], 2 /* Space */), + // Async-await + rule("SpaceBetweenAsyncAndOpenParen", 121 /* AsyncKeyword */, 20 /* OpenParenToken */, [isArrowFunctionContext, isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceBetweenAsyncAndFunctionKeyword", 121 /* AsyncKeyword */, 90 /* FunctionKeyword */, [isNonJsxSameLineTokenContext], 2 /* Space */), + // Template string + rule("NoSpaceBetweenTagAndTemplateString", [72 /* Identifier */, 21 /* CloseParenToken */], [14 /* NoSubstitutionTemplateLiteral */, 15 /* TemplateHead */], [isNonJsxSameLineTokenContext], 8 /* Delete */), + // JSX opening elements + rule("SpaceBeforeJsxAttribute", anyToken, 72 /* Identifier */, [isNextTokenParentJsxAttribute, isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceBeforeSlashInJsxOpeningElement", anyToken, 42 /* SlashToken */, [isJsxSelfClosingElementContext, isNonJsxSameLineTokenContext], 2 /* Space */), + rule("NoSpaceBeforeGreaterThanTokenInJsxOpeningElement", 42 /* SlashToken */, 30 /* GreaterThanToken */, [isJsxSelfClosingElementContext, isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceBeforeEqualInJsxAttribute", anyToken, 59 /* EqualsToken */, [isJsxAttributeContext, isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceAfterEqualInJsxAttribute", 59 /* EqualsToken */, anyToken, [isJsxAttributeContext, isNonJsxSameLineTokenContext], 8 /* Delete */), + // TypeScript-specific rules + // Use of module as a function call. e.g.: import m2 = module("m2"); + rule("NoSpaceAfterModuleImport", [130 /* ModuleKeyword */, 134 /* RequireKeyword */], 20 /* OpenParenToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + // Add a space around certain TypeScript keywords + rule("SpaceAfterCertainTypeScriptKeywords", [ + 118 /* AbstractKeyword */, + 76 /* ClassKeyword */, + 125 /* DeclareKeyword */, + 80 /* DefaultKeyword */, + 84 /* EnumKeyword */, + 85 /* ExportKeyword */, + 86 /* ExtendsKeyword */, + 126 /* GetKeyword */, + 109 /* ImplementsKeyword */, + 92 /* ImportKeyword */, + 110 /* InterfaceKeyword */, + 130 /* ModuleKeyword */, + 131 /* NamespaceKeyword */, + 113 /* PrivateKeyword */, + 115 /* PublicKeyword */, + 114 /* ProtectedKeyword */, + 133 /* ReadonlyKeyword */, + 137 /* SetKeyword */, + 116 /* StaticKeyword */, + 140 /* TypeKeyword */, + 144 /* FromKeyword */, + 129 /* KeyOfKeyword */, + 127 /* InferKeyword */, + ], anyToken, [isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceBeforeCertainTypeScriptKeywords", anyToken, [86 /* ExtendsKeyword */, 109 /* ImplementsKeyword */, 144 /* FromKeyword */], [isNonJsxSameLineTokenContext], 2 /* Space */), + // Treat string literals in module names as identifiers, and add a space between the literal and the opening Brace braces, e.g.: module "m2" { + rule("SpaceAfterModuleName", 10 /* StringLiteral */, 18 /* OpenBraceToken */, [isModuleDeclContext], 2 /* Space */), + // Lambda expressions + rule("SpaceBeforeArrow", anyToken, 37 /* EqualsGreaterThanToken */, [isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceAfterArrow", 37 /* EqualsGreaterThanToken */, anyToken, [isNonJsxSameLineTokenContext], 2 /* Space */), + // Optional parameters and let args + rule("NoSpaceAfterEllipsis", 25 /* DotDotDotToken */, 72 /* Identifier */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceAfterOptionalParameters", 56 /* QuestionToken */, [21 /* CloseParenToken */, 27 /* CommaToken */], [isNonJsxSameLineTokenContext, isNotBinaryOpContext], 8 /* Delete */), + // Remove spaces in empty interface literals. e.g.: x: {} + rule("NoSpaceBetweenEmptyInterfaceBraceBrackets", 18 /* OpenBraceToken */, 19 /* CloseBraceToken */, [isNonJsxSameLineTokenContext, isObjectTypeContext], 8 /* Delete */), + // generics and type assertions + rule("NoSpaceBeforeOpenAngularBracket", typeNames, 28 /* LessThanToken */, [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext], 8 /* Delete */), + rule("NoSpaceBetweenCloseParenAndAngularBracket", 21 /* CloseParenToken */, 28 /* LessThanToken */, [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext], 8 /* Delete */), + rule("NoSpaceAfterOpenAngularBracket", 28 /* LessThanToken */, anyToken, [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext], 8 /* Delete */), + rule("NoSpaceBeforeCloseAngularBracket", anyToken, 30 /* GreaterThanToken */, [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext], 8 /* Delete */), + rule("NoSpaceAfterCloseAngularBracket", 30 /* GreaterThanToken */, [20 /* OpenParenToken */, 22 /* OpenBracketToken */, 30 /* GreaterThanToken */, 27 /* CommaToken */], [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext, isNotFunctionDeclContext /*To prevent an interference with the SpaceBeforeOpenParenInFuncDecl rule*/], 8 /* Delete */), + // decorators + rule("SpaceBeforeAt", [21 /* CloseParenToken */, 72 /* Identifier */], 58 /* AtToken */, [isNonJsxSameLineTokenContext], 2 /* Space */), + rule("NoSpaceAfterAt", 58 /* AtToken */, anyToken, [isNonJsxSameLineTokenContext], 8 /* Delete */), + // Insert space after @ in decorator + rule("SpaceAfterDecorator", anyToken, [ + 118 /* AbstractKeyword */, + 72 /* Identifier */, + 85 /* ExportKeyword */, + 80 /* DefaultKeyword */, + 76 /* ClassKeyword */, + 116 /* StaticKeyword */, + 115 /* PublicKeyword */, + 113 /* PrivateKeyword */, + 114 /* ProtectedKeyword */, + 126 /* GetKeyword */, + 137 /* SetKeyword */, + 22 /* OpenBracketToken */, + 40 /* AsteriskToken */, + ], [isEndOfDecoratorContextOnSameLine], 2 /* Space */), + rule("NoSpaceBeforeNonNullAssertionOperator", anyToken, 52 /* ExclamationToken */, [isNonJsxSameLineTokenContext, isNonNullAssertionContext], 8 /* Delete */), + rule("NoSpaceAfterNewKeywordOnConstructorSignature", 95 /* NewKeyword */, 20 /* OpenParenToken */, [isNonJsxSameLineTokenContext, isConstructorSignatureContext], 8 /* Delete */), + ]; + // These rules are applied after high priority + var userConfigurableRules = [ + // Treat constructor as an identifier in a function declaration, and remove spaces between constructor and following left parentheses + rule("SpaceAfterConstructor", 124 /* ConstructorKeyword */, 20 /* OpenParenToken */, [isOptionEnabled("insertSpaceAfterConstructor"), isNonJsxSameLineTokenContext], 2 /* Space */), + rule("NoSpaceAfterConstructor", 124 /* ConstructorKeyword */, 20 /* OpenParenToken */, [isOptionDisabledOrUndefined("insertSpaceAfterConstructor"), isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("SpaceAfterComma", 27 /* CommaToken */, anyToken, [isOptionEnabled("insertSpaceAfterCommaDelimiter"), isNonJsxSameLineTokenContext, isNonJsxElementOrFragmentContext, isNextTokenNotCloseBracket], 2 /* Space */), + rule("NoSpaceAfterComma", 27 /* CommaToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterCommaDelimiter"), isNonJsxSameLineTokenContext, isNonJsxElementOrFragmentContext], 8 /* Delete */), + // Insert space after function keyword for anonymous functions + rule("SpaceAfterAnonymousFunctionKeyword", 90 /* FunctionKeyword */, 20 /* OpenParenToken */, [isOptionEnabled("insertSpaceAfterFunctionKeywordForAnonymousFunctions"), isFunctionDeclContext], 2 /* Space */), + rule("NoSpaceAfterAnonymousFunctionKeyword", 90 /* FunctionKeyword */, 20 /* OpenParenToken */, [isOptionDisabledOrUndefined("insertSpaceAfterFunctionKeywordForAnonymousFunctions"), isFunctionDeclContext], 8 /* Delete */), + // Insert space after keywords in control flow statements + rule("SpaceAfterKeywordInControl", keywords, 20 /* OpenParenToken */, [isOptionEnabled("insertSpaceAfterKeywordsInControlFlowStatements"), isControlDeclContext], 2 /* Space */), + rule("NoSpaceAfterKeywordInControl", keywords, 20 /* OpenParenToken */, [isOptionDisabledOrUndefined("insertSpaceAfterKeywordsInControlFlowStatements"), isControlDeclContext], 8 /* Delete */), + // Insert space after opening and before closing nonempty parenthesis + rule("SpaceAfterOpenParen", 20 /* OpenParenToken */, anyToken, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceBeforeCloseParen", anyToken, 21 /* CloseParenToken */, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceBetweenOpenParens", 20 /* OpenParenToken */, 20 /* OpenParenToken */, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext], 2 /* Space */), + rule("NoSpaceBetweenParens", 20 /* OpenParenToken */, 21 /* CloseParenToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceAfterOpenParen", 20 /* OpenParenToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceBeforeCloseParen", anyToken, 21 /* CloseParenToken */, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext], 8 /* Delete */), + // Insert space after opening and before closing nonempty brackets + rule("SpaceAfterOpenBracket", 22 /* OpenBracketToken */, anyToken, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceBeforeCloseBracket", anyToken, 23 /* CloseBracketToken */, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), isNonJsxSameLineTokenContext], 2 /* Space */), + rule("NoSpaceBetweenBrackets", 22 /* OpenBracketToken */, 23 /* CloseBracketToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceAfterOpenBracket", 22 /* OpenBracketToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceBeforeCloseBracket", anyToken, 23 /* CloseBracketToken */, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), isNonJsxSameLineTokenContext], 8 /* Delete */), + // Insert a space after { and before } in single-line contexts, but remove space from empty object literals {}. + rule("SpaceAfterOpenBrace", 18 /* OpenBraceToken */, anyToken, [isOptionEnabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), isBraceWrappedContext], 2 /* Space */), + rule("SpaceBeforeCloseBrace", anyToken, 19 /* CloseBraceToken */, [isOptionEnabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), isBraceWrappedContext], 2 /* Space */), + rule("NoSpaceBetweenEmptyBraceBrackets", 18 /* OpenBraceToken */, 19 /* CloseBraceToken */, [isNonJsxSameLineTokenContext, isObjectContext], 8 /* Delete */), + rule("NoSpaceAfterOpenBrace", 18 /* OpenBraceToken */, anyToken, [isOptionDisabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceBeforeCloseBrace", anyToken, 19 /* CloseBraceToken */, [isOptionDisabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), isNonJsxSameLineTokenContext], 8 /* Delete */), + // Insert space after opening and before closing template string braces + rule("SpaceAfterTemplateHeadAndMiddle", [15 /* TemplateHead */, 16 /* TemplateMiddle */], anyToken, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceBeforeTemplateMiddleAndTail", anyToken, [16 /* TemplateMiddle */, 17 /* TemplateTail */], [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), isNonJsxSameLineTokenContext], 2 /* Space */), + rule("NoSpaceAfterTemplateHeadAndMiddle", [15 /* TemplateHead */, 16 /* TemplateMiddle */], anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceBeforeTemplateMiddleAndTail", anyToken, [16 /* TemplateMiddle */, 17 /* TemplateTail */], [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), isNonJsxSameLineTokenContext], 8 /* Delete */), + // No space after { and before } in JSX expression + rule("SpaceAfterOpenBraceInJsxExpression", 18 /* OpenBraceToken */, anyToken, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), isNonJsxSameLineTokenContext, isJsxExpressionContext], 2 /* Space */), + rule("SpaceBeforeCloseBraceInJsxExpression", anyToken, 19 /* CloseBraceToken */, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), isNonJsxSameLineTokenContext, isJsxExpressionContext], 2 /* Space */), + rule("NoSpaceAfterOpenBraceInJsxExpression", 18 /* OpenBraceToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), isNonJsxSameLineTokenContext, isJsxExpressionContext], 8 /* Delete */), + rule("NoSpaceBeforeCloseBraceInJsxExpression", anyToken, 19 /* CloseBraceToken */, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), isNonJsxSameLineTokenContext, isJsxExpressionContext], 8 /* Delete */), + // Insert space after semicolon in for statement + rule("SpaceAfterSemicolonInFor", 26 /* SemicolonToken */, anyToken, [isOptionEnabled("insertSpaceAfterSemicolonInForStatements"), isNonJsxSameLineTokenContext, isForContext], 2 /* Space */), + rule("NoSpaceAfterSemicolonInFor", 26 /* SemicolonToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterSemicolonInForStatements"), isNonJsxSameLineTokenContext, isForContext], 8 /* Delete */), + // Insert space before and after binary operators + rule("SpaceBeforeBinaryOperator", anyToken, binaryOperators, [isOptionEnabled("insertSpaceBeforeAndAfterBinaryOperators"), isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), + rule("SpaceAfterBinaryOperator", binaryOperators, anyToken, [isOptionEnabled("insertSpaceBeforeAndAfterBinaryOperators"), isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), + rule("NoSpaceBeforeBinaryOperator", anyToken, binaryOperators, [isOptionDisabledOrUndefined("insertSpaceBeforeAndAfterBinaryOperators"), isNonJsxSameLineTokenContext, isBinaryOpContext], 8 /* Delete */), + rule("NoSpaceAfterBinaryOperator", binaryOperators, anyToken, [isOptionDisabledOrUndefined("insertSpaceBeforeAndAfterBinaryOperators"), isNonJsxSameLineTokenContext, isBinaryOpContext], 8 /* Delete */), + rule("SpaceBeforeOpenParenInFuncDecl", anyToken, 20 /* OpenParenToken */, [isOptionEnabled("insertSpaceBeforeFunctionParenthesis"), isNonJsxSameLineTokenContext, isFunctionDeclContext], 2 /* Space */), + rule("NoSpaceBeforeOpenParenInFuncDecl", anyToken, 20 /* OpenParenToken */, [isOptionDisabledOrUndefined("insertSpaceBeforeFunctionParenthesis"), isNonJsxSameLineTokenContext, isFunctionDeclContext], 8 /* Delete */), + // Open Brace braces after control block + rule("NewLineBeforeOpenBraceInControl", controlOpenBraceLeftTokenRange, 18 /* OpenBraceToken */, [isOptionEnabled("placeOpenBraceOnNewLineForControlBlocks"), isControlDeclContext, isBeforeMultilineBlockContext], 4 /* NewLine */, 1 /* CanDeleteNewLines */), + // Open Brace braces after function + // TypeScript: Function can have return types, which can be made of tons of different token kinds + rule("NewLineBeforeOpenBraceInFunction", functionOpenBraceLeftTokenRange, 18 /* OpenBraceToken */, [isOptionEnabled("placeOpenBraceOnNewLineForFunctions"), isFunctionDeclContext, isBeforeMultilineBlockContext], 4 /* NewLine */, 1 /* CanDeleteNewLines */), + // Open Brace braces after TypeScript module/class/interface + rule("NewLineBeforeOpenBraceInTypeScriptDeclWithBlock", typeScriptOpenBraceLeftTokenRange, 18 /* OpenBraceToken */, [isOptionEnabled("placeOpenBraceOnNewLineForFunctions"), isTypeScriptDeclWithBlockContext, isBeforeMultilineBlockContext], 4 /* NewLine */, 1 /* CanDeleteNewLines */), + rule("SpaceAfterTypeAssertion", 30 /* GreaterThanToken */, anyToken, [isOptionEnabled("insertSpaceAfterTypeAssertion"), isNonJsxSameLineTokenContext, isTypeAssertionContext], 2 /* Space */), + rule("NoSpaceAfterTypeAssertion", 30 /* GreaterThanToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterTypeAssertion"), isNonJsxSameLineTokenContext, isTypeAssertionContext], 8 /* Delete */), + rule("SpaceBeforeTypeAnnotation", anyToken, 57 /* ColonToken */, [isOptionEnabled("insertSpaceBeforeTypeAnnotation"), isNonJsxSameLineTokenContext, isTypeAnnotationContext], 2 /* Space */), + rule("NoSpaceBeforeTypeAnnotation", anyToken, 57 /* ColonToken */, [isOptionDisabledOrUndefined("insertSpaceBeforeTypeAnnotation"), isNonJsxSameLineTokenContext, isTypeAnnotationContext], 8 /* Delete */), + ]; + // These rules are lower in priority than user-configurable. Rules earlier in this list have priority over rules later in the list. + var lowPriorityCommonRules = [ + // Space after keyword but not before ; or : or ? + rule("NoSpaceBeforeSemicolon", anyToken, 26 /* SemicolonToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("SpaceBeforeOpenBraceInControl", controlOpenBraceLeftTokenRange, 18 /* OpenBraceToken */, [isOptionDisabledOrUndefinedOrTokensOnSameLine("placeOpenBraceOnNewLineForControlBlocks"), isControlDeclContext, isNotFormatOnEnter, isSameLineTokenOrBeforeBlockContext], 2 /* Space */, 1 /* CanDeleteNewLines */), + rule("SpaceBeforeOpenBraceInFunction", functionOpenBraceLeftTokenRange, 18 /* OpenBraceToken */, [isOptionDisabledOrUndefinedOrTokensOnSameLine("placeOpenBraceOnNewLineForFunctions"), isFunctionDeclContext, isBeforeBlockContext, isNotFormatOnEnter, isSameLineTokenOrBeforeBlockContext], 2 /* Space */, 1 /* CanDeleteNewLines */), + rule("SpaceBeforeOpenBraceInTypeScriptDeclWithBlock", typeScriptOpenBraceLeftTokenRange, 18 /* OpenBraceToken */, [isOptionDisabledOrUndefinedOrTokensOnSameLine("placeOpenBraceOnNewLineForFunctions"), isTypeScriptDeclWithBlockContext, isNotFormatOnEnter, isSameLineTokenOrBeforeBlockContext], 2 /* Space */, 1 /* CanDeleteNewLines */), + rule("NoSpaceBeforeComma", anyToken, 27 /* CommaToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + // No space before and after indexer `x[]` + rule("NoSpaceBeforeOpenBracket", anyTokenExcept(121 /* AsyncKeyword */, 74 /* CaseKeyword */), 22 /* OpenBracketToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceAfterCloseBracket", 23 /* CloseBracketToken */, anyToken, [isNonJsxSameLineTokenContext, isNotBeforeBlockInFunctionDeclarationContext], 8 /* Delete */), + rule("SpaceAfterSemicolon", 26 /* SemicolonToken */, anyToken, [isNonJsxSameLineTokenContext], 2 /* Space */), + // Remove extra space between for and await + rule("SpaceBetweenForAndAwaitKeyword", 89 /* ForKeyword */, 122 /* AwaitKeyword */, [isNonJsxSameLineTokenContext], 2 /* Space */), + // Add a space between statements. All keywords except (do,else,case) has open/close parens after them. + // So, we have a rule to add a space for [),Any], [do,Any], [else,Any], and [case,Any] + rule("SpaceBetweenStatements", [21 /* CloseParenToken */, 82 /* DoKeyword */, 83 /* ElseKeyword */, 74 /* CaseKeyword */], anyToken, [isNonJsxSameLineTokenContext, isNonJsxElementOrFragmentContext, isNotForContext], 2 /* Space */), + // This low-pri rule takes care of "try {" and "finally {" in case the rule SpaceBeforeOpenBraceInControl didn't execute on FormatOnEnter. + rule("SpaceAfterTryFinally", [103 /* TryKeyword */, 88 /* FinallyKeyword */], 18 /* OpenBraceToken */, [isNonJsxSameLineTokenContext], 2 /* Space */), + ]; + return highPriorityCommonRules.concat(userConfigurableRules, lowPriorityCommonRules); + } + formatting.getAllRules = getAllRules; + function rule(debugName, left, right, context, action, flags) { + if (flags === void 0) { flags = 0 /* None */; } + return { leftTokenRange: toTokenRange(left), rightTokenRange: toTokenRange(right), rule: { debugName: debugName, context: context, action: action, flags: flags } }; + } + function tokenRangeFrom(tokens) { + return { tokens: tokens, isSpecific: true }; + } + function toTokenRange(arg) { + return typeof arg === "number" ? tokenRangeFrom([arg]) : ts.isArray(arg) ? tokenRangeFrom(arg) : arg; + } + function tokenRangeFromRange(from, to, except) { + if (except === void 0) { except = []; } + var tokens = []; + for (var token = from; token <= to; token++) { + if (!ts.contains(except, token)) { + tokens.push(token); + } + } + return tokenRangeFrom(tokens); + } + /// + /// Contexts + /// + function isOptionEnabled(optionName) { + return function (context) { return context.options && context.options.hasOwnProperty(optionName) && !!context.options[optionName]; }; + } + function isOptionDisabled(optionName) { + return function (context) { return context.options && context.options.hasOwnProperty(optionName) && !context.options[optionName]; }; + } + function isOptionDisabledOrUndefined(optionName) { + return function (context) { return !context.options || !context.options.hasOwnProperty(optionName) || !context.options[optionName]; }; + } + function isOptionDisabledOrUndefinedOrTokensOnSameLine(optionName) { + return function (context) { return !context.options || !context.options.hasOwnProperty(optionName) || !context.options[optionName] || context.TokensAreOnSameLine(); }; + } + function isOptionEnabledOrUndefined(optionName) { + return function (context) { return !context.options || !context.options.hasOwnProperty(optionName) || !!context.options[optionName]; }; + } + function isForContext(context) { + return context.contextNode.kind === 225 /* ForStatement */; + } + function isNotForContext(context) { + return !isForContext(context); + } + function isBinaryOpContext(context) { + switch (context.contextNode.kind) { + case 204 /* BinaryExpression */: + case 205 /* ConditionalExpression */: + case 175 /* ConditionalType */: + case 212 /* AsExpression */: + case 257 /* ExportSpecifier */: + case 253 /* ImportSpecifier */: + case 163 /* TypePredicate */: + case 173 /* UnionType */: + case 174 /* IntersectionType */: + return true; + // equals in binding elements: function foo([[x, y] = [1, 2]]) + case 186 /* BindingElement */: + // equals in type X = ... + case 242 /* TypeAliasDeclaration */: + // equal in import a = module('a'); + case 248 /* ImportEqualsDeclaration */: + // equal in let a = 0; + case 237 /* VariableDeclaration */: + // equal in p = 0; + case 151 /* Parameter */: + case 278 /* EnumMember */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + return context.currentTokenSpan.kind === 59 /* EqualsToken */ || context.nextTokenSpan.kind === 59 /* EqualsToken */; + // "in" keyword in for (let x in []) { } + case 226 /* ForInStatement */: + // "in" keyword in [P in keyof T]: T[P] + case 150 /* TypeParameter */: + return context.currentTokenSpan.kind === 93 /* InKeyword */ || context.nextTokenSpan.kind === 93 /* InKeyword */; + // Technically, "of" is not a binary operator, but format it the same way as "in" + case 227 /* ForOfStatement */: + return context.currentTokenSpan.kind === 147 /* OfKeyword */ || context.nextTokenSpan.kind === 147 /* OfKeyword */; + } + return false; + } + function isNotBinaryOpContext(context) { + return !isBinaryOpContext(context); + } + function isNotTypeAnnotationContext(context) { + return !isTypeAnnotationContext(context); + } + function isTypeAnnotationContext(context) { + var contextKind = context.contextNode.kind; + return contextKind === 154 /* PropertyDeclaration */ || + contextKind === 153 /* PropertySignature */ || + contextKind === 151 /* Parameter */ || + contextKind === 237 /* VariableDeclaration */ || + ts.isFunctionLikeKind(contextKind); + } + function isConditionalOperatorContext(context) { + return context.contextNode.kind === 205 /* ConditionalExpression */ || + context.contextNode.kind === 175 /* ConditionalType */; + } + function isSameLineTokenOrBeforeBlockContext(context) { + return context.TokensAreOnSameLine() || isBeforeBlockContext(context); + } + function isBraceWrappedContext(context) { + return context.contextNode.kind === 184 /* ObjectBindingPattern */ || + context.contextNode.kind === 181 /* MappedType */ || + isSingleLineBlockContext(context); + } + // This check is done before an open brace in a control construct, a function, or a typescript block declaration + function isBeforeMultilineBlockContext(context) { + return isBeforeBlockContext(context) && !(context.NextNodeAllOnSameLine() || context.NextNodeBlockIsOnOneLine()); + } + function isMultilineBlockContext(context) { + return isBlockContext(context) && !(context.ContextNodeAllOnSameLine() || context.ContextNodeBlockIsOnOneLine()); + } + function isSingleLineBlockContext(context) { + return isBlockContext(context) && (context.ContextNodeAllOnSameLine() || context.ContextNodeBlockIsOnOneLine()); + } + function isBlockContext(context) { + return nodeIsBlockContext(context.contextNode); + } + function isBeforeBlockContext(context) { + return nodeIsBlockContext(context.nextTokenParent); + } + // IMPORTANT!!! This method must return true ONLY for nodes with open and close braces as immediate children + function nodeIsBlockContext(node) { + if (nodeIsTypeScriptDeclWithBlockContext(node)) { + // This means we are in a context that looks like a block to the user, but in the grammar is actually not a node (it's a class, module, enum, object type literal, etc). + return true; + } + switch (node.kind) { + case 218 /* Block */: + case 246 /* CaseBlock */: + case 188 /* ObjectLiteralExpression */: + case 245 /* ModuleBlock */: + return true; + } + return false; + } + function isFunctionDeclContext(context) { + switch (context.contextNode.kind) { + case 239 /* FunctionDeclaration */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + // case SyntaxKind.MemberFunctionDeclaration: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + // case SyntaxKind.MethodSignature: + case 160 /* CallSignature */: + case 196 /* FunctionExpression */: + case 157 /* Constructor */: + case 197 /* ArrowFunction */: + // case SyntaxKind.ConstructorDeclaration: + // case SyntaxKind.SimpleArrowFunctionExpression: + // case SyntaxKind.ParenthesizedArrowFunctionExpression: + case 241 /* InterfaceDeclaration */: // This one is not truly a function, but for formatting purposes, it acts just like one + return true; + } + return false; + } + function isNotFunctionDeclContext(context) { + return !isFunctionDeclContext(context); + } + function isFunctionDeclarationOrFunctionExpressionContext(context) { + return context.contextNode.kind === 239 /* FunctionDeclaration */ || context.contextNode.kind === 196 /* FunctionExpression */; + } + function isTypeScriptDeclWithBlockContext(context) { + return nodeIsTypeScriptDeclWithBlockContext(context.contextNode); + } + function nodeIsTypeScriptDeclWithBlockContext(node) { + switch (node.kind) { + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 241 /* InterfaceDeclaration */: + case 243 /* EnumDeclaration */: + case 168 /* TypeLiteral */: + case 244 /* ModuleDeclaration */: + case 255 /* ExportDeclaration */: + case 256 /* NamedExports */: + case 249 /* ImportDeclaration */: + case 252 /* NamedImports */: + return true; + } + return false; + } + function isAfterCodeBlockContext(context) { + switch (context.currentTokenParent.kind) { + case 240 /* ClassDeclaration */: + case 244 /* ModuleDeclaration */: + case 243 /* EnumDeclaration */: + case 274 /* CatchClause */: + case 245 /* ModuleBlock */: + case 232 /* SwitchStatement */: + return true; + case 218 /* Block */: { + var blockParent = context.currentTokenParent.parent; + // In a codefix scenario, we can't rely on parents being set. So just always return true. + if (!blockParent || blockParent.kind !== 197 /* ArrowFunction */ && blockParent.kind !== 196 /* FunctionExpression */) { + return true; + } + } + } + return false; + } + function isControlDeclContext(context) { + switch (context.contextNode.kind) { + case 222 /* IfStatement */: + case 232 /* SwitchStatement */: + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + case 224 /* WhileStatement */: + case 235 /* TryStatement */: + case 223 /* DoStatement */: + case 231 /* WithStatement */: + // TODO + // case SyntaxKind.ElseClause: + case 274 /* CatchClause */: + return true; + default: + return false; + } + } + function isObjectContext(context) { + return context.contextNode.kind === 188 /* ObjectLiteralExpression */; + } + function isFunctionCallContext(context) { + return context.contextNode.kind === 191 /* CallExpression */; + } + function isNewContext(context) { + return context.contextNode.kind === 192 /* NewExpression */; + } + function isFunctionCallOrNewContext(context) { + return isFunctionCallContext(context) || isNewContext(context); + } + function isPreviousTokenNotComma(context) { + return context.currentTokenSpan.kind !== 27 /* CommaToken */; + } + function isNextTokenNotCloseBracket(context) { + return context.nextTokenSpan.kind !== 23 /* CloseBracketToken */; + } + function isArrowFunctionContext(context) { + return context.contextNode.kind === 197 /* ArrowFunction */; + } + function isImportTypeContext(context) { + return context.contextNode.kind === 183 /* ImportType */; + } + function isNonJsxSameLineTokenContext(context) { + return context.TokensAreOnSameLine() && context.contextNode.kind !== 11 /* JsxText */; + } + function isNonJsxElementOrFragmentContext(context) { + return context.contextNode.kind !== 260 /* JsxElement */ && context.contextNode.kind !== 264 /* JsxFragment */; + } + function isJsxExpressionContext(context) { + return context.contextNode.kind === 270 /* JsxExpression */ || context.contextNode.kind === 269 /* JsxSpreadAttribute */; + } + function isNextTokenParentJsxAttribute(context) { + return context.nextTokenParent.kind === 267 /* JsxAttribute */; + } + function isJsxAttributeContext(context) { + return context.contextNode.kind === 267 /* JsxAttribute */; + } + function isJsxSelfClosingElementContext(context) { + return context.contextNode.kind === 261 /* JsxSelfClosingElement */; + } + function isNotBeforeBlockInFunctionDeclarationContext(context) { + return !isFunctionDeclContext(context) && !isBeforeBlockContext(context); + } + function isEndOfDecoratorContextOnSameLine(context) { + return context.TokensAreOnSameLine() && + !!context.contextNode.decorators && + nodeIsInDecoratorContext(context.currentTokenParent) && + !nodeIsInDecoratorContext(context.nextTokenParent); + } + function nodeIsInDecoratorContext(node) { + while (ts.isExpressionNode(node)) { + node = node.parent; + } + return node.kind === 152 /* Decorator */; + } + function isStartOfVariableDeclarationList(context) { + return context.currentTokenParent.kind === 238 /* VariableDeclarationList */ && + context.currentTokenParent.getStart(context.sourceFile) === context.currentTokenSpan.pos; + } + function isNotFormatOnEnter(context) { + return context.formattingRequestKind !== 2 /* FormatOnEnter */; + } + function isModuleDeclContext(context) { + return context.contextNode.kind === 244 /* ModuleDeclaration */; + } + function isObjectTypeContext(context) { + return context.contextNode.kind === 168 /* TypeLiteral */; // && context.contextNode.parent.kind !== SyntaxKind.InterfaceDeclaration; + } + function isConstructorSignatureContext(context) { + return context.contextNode.kind === 161 /* ConstructSignature */; + } + function isTypeArgumentOrParameterOrAssertion(token, parent) { + if (token.kind !== 28 /* LessThanToken */ && token.kind !== 30 /* GreaterThanToken */) { + return false; + } + switch (parent.kind) { + case 164 /* TypeReference */: + case 194 /* TypeAssertionExpression */: + case 242 /* TypeAliasDeclaration */: + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 241 /* InterfaceDeclaration */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 191 /* CallExpression */: + case 192 /* NewExpression */: + case 211 /* ExpressionWithTypeArguments */: + return true; + default: + return false; + } + } + function isTypeArgumentOrParameterOrAssertionContext(context) { + return isTypeArgumentOrParameterOrAssertion(context.currentTokenSpan, context.currentTokenParent) || + isTypeArgumentOrParameterOrAssertion(context.nextTokenSpan, context.nextTokenParent); + } + function isTypeAssertionContext(context) { + return context.contextNode.kind === 194 /* TypeAssertionExpression */; + } + function isVoidOpContext(context) { + return context.currentTokenSpan.kind === 106 /* VoidKeyword */ && context.currentTokenParent.kind === 200 /* VoidExpression */; + } + function isYieldOrYieldStarWithOperand(context) { + return context.contextNode.kind === 207 /* YieldExpression */ && context.contextNode.expression !== undefined; + } + function isNonNullAssertionContext(context) { + return context.contextNode.kind === 213 /* NonNullExpression */; + } + })(formatting = ts.formatting || (ts.formatting = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var formatting; + (function (formatting) { + function getFormatContext(options) { + return { options: options, getRule: getRulesMap() }; + } + formatting.getFormatContext = getFormatContext; + var rulesMapCache; + function getRulesMap() { + if (rulesMapCache === undefined) { + rulesMapCache = createRulesMap(formatting.getAllRules()); + } + return rulesMapCache; + } + function createRulesMap(rules) { + var map = buildMap(rules); + return function (context) { + var bucket = map[getRuleBucketIndex(context.currentTokenSpan.kind, context.nextTokenSpan.kind)]; + return bucket && ts.find(bucket, function (rule) { return ts.every(rule.context, function (c) { return c(context); }); }); + }; + } + function buildMap(rules) { + // Map from bucket index to array of rules + var map = new Array(mapRowLength * mapRowLength); + // This array is used only during construction of the rulesbucket in the map + var rulesBucketConstructionStateList = new Array(map.length); + for (var _i = 0, rules_1 = rules; _i < rules_1.length; _i++) { + var rule = rules_1[_i]; + var specificRule = rule.leftTokenRange.isSpecific && rule.rightTokenRange.isSpecific; + for (var _a = 0, _b = rule.leftTokenRange.tokens; _a < _b.length; _a++) { + var left = _b[_a]; + for (var _c = 0, _d = rule.rightTokenRange.tokens; _c < _d.length; _c++) { + var right = _d[_c]; + var index = getRuleBucketIndex(left, right); + var rulesBucket = map[index]; + if (rulesBucket === undefined) { + rulesBucket = map[index] = []; + } + addRule(rulesBucket, rule.rule, specificRule, rulesBucketConstructionStateList, index); + } + } + } + return map; + } + function getRuleBucketIndex(row, column) { + ts.Debug.assert(row <= 147 /* LastKeyword */ && column <= 147 /* LastKeyword */, "Must compute formatting context from tokens"); + return (row * mapRowLength) + column; + } + var maskBitSize = 5; + var mask = 31; // MaskBitSize bits + var mapRowLength = 147 /* LastToken */ + 1; + var RulesPosition; + (function (RulesPosition) { + RulesPosition[RulesPosition["IgnoreRulesSpecific"] = 0] = "IgnoreRulesSpecific"; + RulesPosition[RulesPosition["IgnoreRulesAny"] = maskBitSize * 1] = "IgnoreRulesAny"; + RulesPosition[RulesPosition["ContextRulesSpecific"] = maskBitSize * 2] = "ContextRulesSpecific"; + RulesPosition[RulesPosition["ContextRulesAny"] = maskBitSize * 3] = "ContextRulesAny"; + RulesPosition[RulesPosition["NoContextRulesSpecific"] = maskBitSize * 4] = "NoContextRulesSpecific"; + RulesPosition[RulesPosition["NoContextRulesAny"] = maskBitSize * 5] = "NoContextRulesAny"; + })(RulesPosition || (RulesPosition = {})); + // The Rules list contains all the inserted rules into a rulebucket in the following order: + // 1- Ignore rules with specific token combination + // 2- Ignore rules with any token combination + // 3- Context rules with specific token combination + // 4- Context rules with any token combination + // 5- Non-context rules with specific token combination + // 6- Non-context rules with any token combination + // + // The member rulesInsertionIndexBitmap is used to describe the number of rules + // in each sub-bucket (above) hence can be used to know the index of where to insert + // the next rule. It's a bitmap which contains 6 different sections each is given 5 bits. + // + // Example: + // In order to insert a rule to the end of sub-bucket (3), we get the index by adding + // the values in the bitmap segments 3rd, 2nd, and 1st. + function addRule(rules, rule, specificTokens, constructionState, rulesBucketIndex) { + var position = rule.action === 1 /* Ignore */ + ? specificTokens ? RulesPosition.IgnoreRulesSpecific : RulesPosition.IgnoreRulesAny + : rule.context !== formatting.anyContext + ? specificTokens ? RulesPosition.ContextRulesSpecific : RulesPosition.ContextRulesAny + : specificTokens ? RulesPosition.NoContextRulesSpecific : RulesPosition.NoContextRulesAny; + var state = constructionState[rulesBucketIndex] || 0; + rules.splice(getInsertionIndex(state, position), 0, rule); + constructionState[rulesBucketIndex] = increaseInsertionIndex(state, position); + } + function getInsertionIndex(indexBitmap, maskPosition) { + var index = 0; + for (var pos = 0; pos <= maskPosition; pos += maskBitSize) { + index += indexBitmap & mask; + indexBitmap >>= maskBitSize; + } + return index; + } + function increaseInsertionIndex(indexBitmap, maskPosition) { + var value = ((indexBitmap >> maskPosition) & mask) + 1; + ts.Debug.assert((value & mask) === value, "Adding more rules into the sub-bucket than allowed. Maximum allowed is 32 rules."); + return (indexBitmap & ~(mask << maskPosition)) | (value << maskPosition); + } + })(formatting = ts.formatting || (ts.formatting = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var formatting; + (function (formatting) { + var Constants; + (function (Constants) { + Constants[Constants["Unknown"] = -1] = "Unknown"; + })(Constants || (Constants = {})); + function formatOnEnter(position, sourceFile, formatContext) { + var line = sourceFile.getLineAndCharacterOfPosition(position).line; + if (line === 0) { + return []; + } + // After the enter key, the cursor is now at a new line. The new line may or may not contain non-whitespace characters. + // If the new line has only whitespaces, we won't want to format this line, because that would remove the indentation as + // trailing whitespaces. So the end of the formatting span should be the later one between: + // 1. the end of the previous line + // 2. the last non-whitespace character in the current line + var endOfFormatSpan = ts.getEndLinePosition(line, sourceFile); + while (ts.isWhiteSpaceSingleLine(sourceFile.text.charCodeAt(endOfFormatSpan))) { + endOfFormatSpan--; + } + // if the character at the end of the span is a line break, we shouldn't include it, because it indicates we don't want to + // touch the current line at all. Also, on some OSes the line break consists of two characters (\r\n), we should test if the + // previous character before the end of format span is line break character as well. + if (ts.isLineBreak(sourceFile.text.charCodeAt(endOfFormatSpan))) { + endOfFormatSpan--; + } + var span = { + // get start position for the previous line + pos: ts.getStartPositionOfLine(line - 1, sourceFile), + // end value is exclusive so add 1 to the result + end: endOfFormatSpan + 1 + }; + return formatSpan(span, sourceFile, formatContext, 2 /* FormatOnEnter */); + } + formatting.formatOnEnter = formatOnEnter; + function formatOnSemicolon(position, sourceFile, formatContext) { + var semicolon = findImmediatelyPrecedingTokenOfKind(position, 26 /* SemicolonToken */, sourceFile); + return formatNodeLines(findOutermostNodeWithinListLevel(semicolon), sourceFile, formatContext, 3 /* FormatOnSemicolon */); + } + formatting.formatOnSemicolon = formatOnSemicolon; + function formatOnOpeningCurly(position, sourceFile, formatContext) { + var openingCurly = findImmediatelyPrecedingTokenOfKind(position, 18 /* OpenBraceToken */, sourceFile); + if (!openingCurly) { + return []; + } + var curlyBraceRange = openingCurly.parent; + var outermostNode = findOutermostNodeWithinListLevel(curlyBraceRange); + /** + * We limit the span to end at the opening curly to handle the case where + * the brace matched to that just typed will be incorrect after further edits. + * For example, we could type the opening curly for the following method + * body without brace-matching activated: + * ``` + * class C { + * foo() + * } + * ``` + * and we wouldn't want to move the closing brace. + */ + var textRange = { + pos: ts.getLineStartPositionForPosition(outermostNode.getStart(sourceFile), sourceFile), + end: position + }; + return formatSpan(textRange, sourceFile, formatContext, 4 /* FormatOnOpeningCurlyBrace */); + } + formatting.formatOnOpeningCurly = formatOnOpeningCurly; + function formatOnClosingCurly(position, sourceFile, formatContext) { + var precedingToken = findImmediatelyPrecedingTokenOfKind(position, 19 /* CloseBraceToken */, sourceFile); + return formatNodeLines(findOutermostNodeWithinListLevel(precedingToken), sourceFile, formatContext, 5 /* FormatOnClosingCurlyBrace */); + } + formatting.formatOnClosingCurly = formatOnClosingCurly; + function formatDocument(sourceFile, formatContext) { + var span = { + pos: 0, + end: sourceFile.text.length + }; + return formatSpan(span, sourceFile, formatContext, 0 /* FormatDocument */); + } + formatting.formatDocument = formatDocument; + function formatSelection(start, end, sourceFile, formatContext) { + // format from the beginning of the line + var span = { + pos: ts.getLineStartPositionForPosition(start, sourceFile), + end: end, + }; + return formatSpan(span, sourceFile, formatContext, 1 /* FormatSelection */); + } + formatting.formatSelection = formatSelection; + /** + * Validating `expectedTokenKind` ensures the token was typed in the context we expect (eg: not a comment). + * @param expectedTokenKind The kind of the last token constituting the desired parent node. + */ + function findImmediatelyPrecedingTokenOfKind(end, expectedTokenKind, sourceFile) { + var precedingToken = ts.findPrecedingToken(end, sourceFile); + return precedingToken && precedingToken.kind === expectedTokenKind && end === precedingToken.getEnd() ? + precedingToken : + undefined; + } + /** + * Finds the highest node enclosing `node` at the same list level as `node` + * and whose end does not exceed `node.end`. + * + * Consider typing the following + * ``` + * let x = 1; + * while (true) { + * } + * ``` + * Upon typing the closing curly, we want to format the entire `while`-statement, but not the preceding + * variable declaration. + */ + function findOutermostNodeWithinListLevel(node) { + var current = node; + while (current && + current.parent && + current.parent.end === node.end && + !isListElement(current.parent, current)) { + current = current.parent; + } + return current; + } + // Returns true if node is a element in some list in parent + // i.e. parent is class declaration with the list of members and node is one of members. + function isListElement(parent, node) { + switch (parent.kind) { + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + return ts.rangeContainsRange(parent.members, node); + case 244 /* ModuleDeclaration */: + var body = parent.body; + return !!body && body.kind === 245 /* ModuleBlock */ && ts.rangeContainsRange(body.statements, node); + case 279 /* SourceFile */: + case 218 /* Block */: + case 245 /* ModuleBlock */: + return ts.rangeContainsRange(parent.statements, node); + case 274 /* CatchClause */: + return ts.rangeContainsRange(parent.block.statements, node); + } + return false; + } + /** find node that fully contains given text range */ + function findEnclosingNode(range, sourceFile) { + return find(sourceFile); + function find(n) { + var candidate = ts.forEachChild(n, function (c) { return ts.startEndContainsRange(c.getStart(sourceFile), c.end, range) && c; }); + if (candidate) { + var result = find(candidate); + if (result) { + return result; + } + } + return n; + } + } + /** formatting is not applied to ranges that contain parse errors. + * This function will return a predicate that for a given text range will tell + * if there are any parse errors that overlap with the range. + */ + function prepareRangeContainsErrorFunction(errors, originalRange) { + if (!errors.length) { + return rangeHasNoErrors; + } + // pick only errors that fall in range + var sorted = errors + .filter(function (d) { return ts.rangeOverlapsWithStartEnd(originalRange, d.start, d.start + d.length); }) // TODO: GH#18217 + .sort(function (e1, e2) { return e1.start - e2.start; }); + if (!sorted.length) { + return rangeHasNoErrors; + } + var index = 0; + return function (r) { + // in current implementation sequence of arguments [r1, r2...] is monotonically increasing. + // 'index' tracks the index of the most recent error that was checked. + while (true) { + if (index >= sorted.length) { + // all errors in the range were already checked -> no error in specified range + return false; + } + var error = sorted[index]; + if (r.end <= error.start) { + // specified range ends before the error refered by 'index' - no error in range + return false; + } + if (ts.startEndOverlapsWithStartEnd(r.pos, r.end, error.start, error.start + error.length)) { + // specified range overlaps with error range + return true; + } + index++; + } + }; + function rangeHasNoErrors() { + return false; + } + } + /** + * Start of the original range might fall inside the comment - scanner will not yield appropriate results + * This function will look for token that is located before the start of target range + * and return its end as start position for the scanner. + */ + function getScanStartPosition(enclosingNode, originalRange, sourceFile) { + var start = enclosingNode.getStart(sourceFile); + if (start === originalRange.pos && enclosingNode.end === originalRange.end) { + return start; + } + var precedingToken = ts.findPrecedingToken(originalRange.pos, sourceFile); + if (!precedingToken) { + // no preceding token found - start from the beginning of enclosing node + return enclosingNode.pos; + } + // preceding token ends after the start of original range (i.e when originalRange.pos falls in the middle of literal) + // start from the beginning of enclosingNode to handle the entire 'originalRange' + if (precedingToken.end >= originalRange.pos) { + return enclosingNode.pos; + } + return precedingToken.end; + } + /* + * For cases like + * if (a || + * b ||$ + * c) {...} + * If we hit Enter at $ we want line ' b ||' to be indented. + * Formatting will be applied to the last two lines. + * Node that fully encloses these lines is binary expression 'a ||...'. + * Initial indentation for this node will be 0. + * Binary expressions don't introduce new indentation scopes, however it is possible + * that some parent node on the same line does - like if statement in this case. + * Note that we are considering parents only from the same line with initial node - + * if parent is on the different line - its delta was already contributed + * to the initial indentation. + */ + function getOwnOrInheritedDelta(n, options, sourceFile) { + var previousLine = -1 /* Unknown */; + var child; + while (n) { + var line = sourceFile.getLineAndCharacterOfPosition(n.getStart(sourceFile)).line; + if (previousLine !== -1 /* Unknown */ && line !== previousLine) { + break; + } + if (formatting.SmartIndenter.shouldIndentChildNode(options, n, child, sourceFile)) { + return options.indentSize; + } + previousLine = line; + child = n; + n = n.parent; + } + return 0; + } + function formatNodeGivenIndentation(node, sourceFileLike, languageVariant, initialIndentation, delta, formatContext) { + var range = { pos: 0, end: sourceFileLike.text.length }; + return formatting.getFormattingScanner(sourceFileLike.text, languageVariant, range.pos, range.end, function (scanner) { return formatSpanWorker(range, node, initialIndentation, delta, scanner, formatContext, 1 /* FormatSelection */, function (_) { return false; }, // assume that node does not have any errors + sourceFileLike); }); + } + formatting.formatNodeGivenIndentation = formatNodeGivenIndentation; + function formatNodeLines(node, sourceFile, formatContext, requestKind) { + if (!node) { + return []; + } + var span = { + pos: ts.getLineStartPositionForPosition(node.getStart(sourceFile), sourceFile), + end: node.end + }; + return formatSpan(span, sourceFile, formatContext, requestKind); + } + function formatSpan(originalRange, sourceFile, formatContext, requestKind) { + // find the smallest node that fully wraps the range and compute the initial indentation for the node + var enclosingNode = findEnclosingNode(originalRange, sourceFile); + return formatting.getFormattingScanner(sourceFile.text, sourceFile.languageVariant, getScanStartPosition(enclosingNode, originalRange, sourceFile), originalRange.end, function (scanner) { return formatSpanWorker(originalRange, enclosingNode, formatting.SmartIndenter.getIndentationForNode(enclosingNode, originalRange, sourceFile, formatContext.options), getOwnOrInheritedDelta(enclosingNode, formatContext.options, sourceFile), scanner, formatContext, requestKind, prepareRangeContainsErrorFunction(sourceFile.parseDiagnostics, originalRange), sourceFile); }); + } + function formatSpanWorker(originalRange, enclosingNode, initialIndentation, delta, formattingScanner, _a, requestKind, rangeContainsError, sourceFile) { + var options = _a.options, getRule = _a.getRule; + // formatting context is used by rules provider + var formattingContext = new formatting.FormattingContext(sourceFile, requestKind, options); + var previousRange; + var previousParent; + var previousRangeStartLine; + var lastIndentedLine; + var indentationOnLastIndentedLine = -1 /* Unknown */; + var edits = []; + formattingScanner.advance(); + if (formattingScanner.isOnToken()) { + var startLine = sourceFile.getLineAndCharacterOfPosition(enclosingNode.getStart(sourceFile)).line; + var undecoratedStartLine = startLine; + if (enclosingNode.decorators) { + undecoratedStartLine = sourceFile.getLineAndCharacterOfPosition(ts.getNonDecoratorTokenPosOfNode(enclosingNode, sourceFile)).line; + } + processNode(enclosingNode, enclosingNode, startLine, undecoratedStartLine, initialIndentation, delta); + } + if (!formattingScanner.isOnToken()) { + var leadingTrivia = formattingScanner.getCurrentLeadingTrivia(); + if (leadingTrivia) { + indentTriviaItems(leadingTrivia, initialIndentation, /*indentNextTokenOrTrivia*/ false, function (item) { return processRange(item, sourceFile.getLineAndCharacterOfPosition(item.pos), enclosingNode, enclosingNode, /*dynamicIndentation*/ undefined); }); + trimTrailingWhitespacesForRemainingRange(); + } + } + return edits; + // local functions + /** Tries to compute the indentation for a list element. + * If list element is not in range then + * function will pick its actual indentation + * so it can be pushed downstream as inherited indentation. + * If list element is in the range - its indentation will be equal + * to inherited indentation from its predecessors. + */ + function tryComputeIndentationForListItem(startPos, endPos, parentStartLine, range, inheritedIndentation) { + if (ts.rangeOverlapsWithStartEnd(range, startPos, endPos) || + ts.rangeContainsStartEnd(range, startPos, endPos) /* Not to miss zero-range nodes e.g. JsxText */) { + if (inheritedIndentation !== -1 /* Unknown */) { + return inheritedIndentation; + } + } + else { + var startLine = sourceFile.getLineAndCharacterOfPosition(startPos).line; + var startLinePosition = ts.getLineStartPositionForPosition(startPos, sourceFile); + var column = formatting.SmartIndenter.findFirstNonWhitespaceColumn(startLinePosition, startPos, sourceFile, options); + if (startLine !== parentStartLine || startPos === column) { + // Use the base indent size if it is greater than + // the indentation of the inherited predecessor. + var baseIndentSize = formatting.SmartIndenter.getBaseIndentation(options); + return baseIndentSize > column ? baseIndentSize : column; + } + } + return -1 /* Unknown */; + } + function computeIndentation(node, startLine, inheritedIndentation, parent, parentDynamicIndentation, effectiveParentStartLine) { + var delta = formatting.SmartIndenter.shouldIndentChildNode(options, node) ? options.indentSize : 0; + if (effectiveParentStartLine === startLine) { + // if node is located on the same line with the parent + // - inherit indentation from the parent + // - push children if either parent of node itself has non-zero delta + return { + indentation: startLine === lastIndentedLine ? indentationOnLastIndentedLine : parentDynamicIndentation.getIndentation(), + delta: Math.min(options.indentSize, parentDynamicIndentation.getDelta(node) + delta) + }; + } + else if (inheritedIndentation === -1 /* Unknown */) { + if (node.kind === 20 /* OpenParenToken */ && startLine === lastIndentedLine) { + // the is used for chaining methods formatting + // - we need to get the indentation on last line and the delta of parent + return { indentation: indentationOnLastIndentedLine, delta: parentDynamicIndentation.getDelta(node) }; + } + else if (formatting.SmartIndenter.childStartsOnTheSameLineWithElseInIfStatement(parent, node, startLine, sourceFile)) { + return { indentation: parentDynamicIndentation.getIndentation(), delta: delta }; + } + else { + return { indentation: parentDynamicIndentation.getIndentation() + parentDynamicIndentation.getDelta(node), delta: delta }; + } + } + else { + return { indentation: inheritedIndentation, delta: delta }; + } + } + function getFirstNonDecoratorTokenOfNode(node) { + if (node.modifiers && node.modifiers.length) { + return node.modifiers[0].kind; + } + switch (node.kind) { + case 240 /* ClassDeclaration */: return 76 /* ClassKeyword */; + case 241 /* InterfaceDeclaration */: return 110 /* InterfaceKeyword */; + case 239 /* FunctionDeclaration */: return 90 /* FunctionKeyword */; + case 243 /* EnumDeclaration */: return 243 /* EnumDeclaration */; + case 158 /* GetAccessor */: return 126 /* GetKeyword */; + case 159 /* SetAccessor */: return 137 /* SetKeyword */; + case 156 /* MethodDeclaration */: + if (node.asteriskToken) { + return 40 /* AsteriskToken */; + } + // falls through + case 154 /* PropertyDeclaration */: + case 151 /* Parameter */: + var name = ts.getNameOfDeclaration(node); + if (name) { + return name.kind; + } + } + } + function getDynamicIndentation(node, nodeStartLine, indentation, delta) { + return { + getIndentationForComment: function (kind, tokenIndentation, container) { + switch (kind) { + // preceding comment to the token that closes the indentation scope inherits the indentation from the scope + // .. { + // // comment + // } + case 19 /* CloseBraceToken */: + case 23 /* CloseBracketToken */: + case 21 /* CloseParenToken */: + return indentation + getDelta(container); + } + return tokenIndentation !== -1 /* Unknown */ ? tokenIndentation : indentation; + }, + // if list end token is LessThanToken '>' then its delta should be explicitly suppressed + // so that LessThanToken as a binary operator can still be indented. + // foo.then + // < + // number, + // string, + // >(); + // vs + // var a = xValue + // > yValue; + getIndentationForToken: function (line, kind, container, suppressDelta) { + return !suppressDelta && shouldAddDelta(line, kind, container) ? indentation + getDelta(container) : indentation; + }, + getIndentation: function () { return indentation; }, + getDelta: getDelta, + recomputeIndentation: function (lineAdded) { + if (node.parent && formatting.SmartIndenter.shouldIndentChildNode(options, node.parent, node, sourceFile)) { + indentation += lineAdded ? options.indentSize : -options.indentSize; + delta = formatting.SmartIndenter.shouldIndentChildNode(options, node) ? options.indentSize : 0; + } + } + }; + function shouldAddDelta(line, kind, container) { + switch (kind) { + // open and close brace, 'else' and 'while' (in do statement) tokens has indentation of the parent + case 18 /* OpenBraceToken */: + case 19 /* CloseBraceToken */: + case 21 /* CloseParenToken */: + case 83 /* ElseKeyword */: + case 107 /* WhileKeyword */: + case 58 /* AtToken */: + return false; + case 42 /* SlashToken */: + case 30 /* GreaterThanToken */: + switch (container.kind) { + case 262 /* JsxOpeningElement */: + case 263 /* JsxClosingElement */: + case 261 /* JsxSelfClosingElement */: + return false; + } + break; + case 22 /* OpenBracketToken */: + case 23 /* CloseBracketToken */: + if (container.kind !== 181 /* MappedType */) { + return false; + } + break; + } + // if token line equals to the line of containing node (this is a first token in the node) - use node indentation + return nodeStartLine !== line + // if this token is the first token following the list of decorators, we do not need to indent + && !(node.decorators && kind === getFirstNonDecoratorTokenOfNode(node)); + } + function getDelta(child) { + // Delta value should be zero when the node explicitly prevents indentation of the child node + return formatting.SmartIndenter.nodeWillIndentChild(options, node, child, sourceFile, /*indentByDefault*/ true) ? delta : 0; + } + } + function processNode(node, contextNode, nodeStartLine, undecoratedNodeStartLine, indentation, delta) { + if (!ts.rangeOverlapsWithStartEnd(originalRange, node.getStart(sourceFile), node.getEnd())) { + return; + } + var nodeDynamicIndentation = getDynamicIndentation(node, nodeStartLine, indentation, delta); + // a useful observations when tracking context node + // / + // [a] + // / | \ + // [b] [c] [d] + // node 'a' is a context node for nodes 'b', 'c', 'd' + // except for the leftmost leaf token in [b] - in this case context node ('e') is located somewhere above 'a' + // this rule can be applied recursively to child nodes of 'a'. + // + // context node is set to parent node value after processing every child node + // context node is set to parent of the token after processing every token + var childContextNode = contextNode; + // if there are any tokens that logically belong to node and interleave child nodes + // such tokens will be consumed in processChildNode for the child that follows them + ts.forEachChild(node, function (child) { + processChildNode(child, /*inheritedIndentation*/ -1 /* Unknown */, node, nodeDynamicIndentation, nodeStartLine, undecoratedNodeStartLine, /*isListItem*/ false); + }, function (nodes) { + processChildNodes(nodes, node, nodeStartLine, nodeDynamicIndentation); + }); + // proceed any tokens in the node that are located after child nodes + while (formattingScanner.isOnToken()) { + var tokenInfo = formattingScanner.readTokenInfo(node); + if (tokenInfo.token.end > node.end) { + break; + } + consumeTokenAndAdvanceScanner(tokenInfo, node, nodeDynamicIndentation, node); + } + function processChildNode(child, inheritedIndentation, parent, parentDynamicIndentation, parentStartLine, undecoratedParentStartLine, isListItem, isFirstListItem) { + var childStartPos = child.getStart(sourceFile); + var childStartLine = sourceFile.getLineAndCharacterOfPosition(childStartPos).line; + var undecoratedChildStartLine = childStartLine; + if (child.decorators) { + undecoratedChildStartLine = sourceFile.getLineAndCharacterOfPosition(ts.getNonDecoratorTokenPosOfNode(child, sourceFile)).line; + } + // if child is a list item - try to get its indentation, only if parent is within the original range. + var childIndentationAmount = -1 /* Unknown */; + if (isListItem && ts.rangeContainsRange(originalRange, parent)) { + childIndentationAmount = tryComputeIndentationForListItem(childStartPos, child.end, parentStartLine, originalRange, inheritedIndentation); + if (childIndentationAmount !== -1 /* Unknown */) { + inheritedIndentation = childIndentationAmount; + } + } + // child node is outside the target range - do not dive inside + if (!ts.rangeOverlapsWithStartEnd(originalRange, child.pos, child.end)) { + if (child.end < originalRange.pos) { + formattingScanner.skipToEndOf(child); + } + return inheritedIndentation; + } + if (child.getFullWidth() === 0) { + return inheritedIndentation; + } + while (formattingScanner.isOnToken()) { + // proceed any parent tokens that are located prior to child.getStart() + var tokenInfo = formattingScanner.readTokenInfo(node); + if (tokenInfo.token.end > childStartPos) { + // stop when formatting scanner advances past the beginning of the child + break; + } + consumeTokenAndAdvanceScanner(tokenInfo, node, parentDynamicIndentation, node); + } + if (!formattingScanner.isOnToken()) { + return inheritedIndentation; + } + // JSX text shouldn't affect indenting + if (ts.isToken(child) && child.kind !== 11 /* JsxText */) { + // if child node is a token, it does not impact indentation, proceed it using parent indentation scope rules + var tokenInfo = formattingScanner.readTokenInfo(child); + ts.Debug.assert(tokenInfo.token.end === child.end, "Token end is child end"); + consumeTokenAndAdvanceScanner(tokenInfo, node, parentDynamicIndentation, child); + return inheritedIndentation; + } + var effectiveParentStartLine = child.kind === 152 /* Decorator */ ? childStartLine : undecoratedParentStartLine; + var childIndentation = computeIndentation(child, childStartLine, childIndentationAmount, node, parentDynamicIndentation, effectiveParentStartLine); + processNode(child, childContextNode, childStartLine, undecoratedChildStartLine, childIndentation.indentation, childIndentation.delta); + if (child.kind === 11 /* JsxText */) { + var range = { pos: child.getStart(), end: child.getEnd() }; + indentMultilineCommentOrJsxText(range, childIndentation.indentation, /*firstLineIsIndented*/ true, /*indentFinalLine*/ false); + } + childContextNode = node; + if (isFirstListItem && parent.kind === 187 /* ArrayLiteralExpression */ && inheritedIndentation === -1 /* Unknown */) { + inheritedIndentation = childIndentation.indentation; + } + return inheritedIndentation; + } + function processChildNodes(nodes, parent, parentStartLine, parentDynamicIndentation) { + ts.Debug.assert(ts.isNodeArray(nodes)); + var listStartToken = getOpenTokenForList(parent, nodes); + var listDynamicIndentation = parentDynamicIndentation; + var startLine = parentStartLine; + if (listStartToken !== 0 /* Unknown */) { + // introduce a new indentation scope for lists (including list start and end tokens) + while (formattingScanner.isOnToken()) { + var tokenInfo = formattingScanner.readTokenInfo(parent); + if (tokenInfo.token.end > nodes.pos) { + // stop when formatting scanner moves past the beginning of node list + break; + } + else if (tokenInfo.token.kind === listStartToken) { + // consume list start token + startLine = sourceFile.getLineAndCharacterOfPosition(tokenInfo.token.pos).line; + consumeTokenAndAdvanceScanner(tokenInfo, parent, parentDynamicIndentation, parent); + var indentationOnListStartToken = void 0; + if (indentationOnLastIndentedLine !== -1 /* Unknown */) { + // scanner just processed list start token so consider last indentation as list indentation + // function foo(): { // last indentation was 0, list item will be indented based on this value + // foo: number; + // }: {}; + indentationOnListStartToken = indentationOnLastIndentedLine; + } + else { + var startLinePosition = ts.getLineStartPositionForPosition(tokenInfo.token.pos, sourceFile); + indentationOnListStartToken = formatting.SmartIndenter.findFirstNonWhitespaceColumn(startLinePosition, tokenInfo.token.pos, sourceFile, options); + } + listDynamicIndentation = getDynamicIndentation(parent, parentStartLine, indentationOnListStartToken, options.indentSize); // TODO: GH#18217 + } + else { + // consume any tokens that precede the list as child elements of 'node' using its indentation scope + consumeTokenAndAdvanceScanner(tokenInfo, parent, parentDynamicIndentation, parent); + } + } + } + var inheritedIndentation = -1 /* Unknown */; + for (var i = 0; i < nodes.length; i++) { + var child = nodes[i]; + inheritedIndentation = processChildNode(child, inheritedIndentation, node, listDynamicIndentation, startLine, startLine, /*isListItem*/ true, /*isFirstListItem*/ i === 0); + } + var listEndToken = getCloseTokenForOpenToken(listStartToken); + if (listEndToken !== 0 /* Unknown */ && formattingScanner.isOnToken()) { + var tokenInfo = formattingScanner.readTokenInfo(parent); + if (tokenInfo.token.kind === 27 /* CommaToken */ && ts.isCallLikeExpression(parent)) { + formattingScanner.advance(); + tokenInfo = formattingScanner.isOnToken() ? formattingScanner.readTokenInfo(parent) : undefined; + } + // consume the list end token only if it is still belong to the parent + // there might be the case when current token matches end token but does not considered as one + // function (x: function) <-- + // without this check close paren will be interpreted as list end token for function expression which is wrong + if (tokenInfo && tokenInfo.token.kind === listEndToken && ts.rangeContainsRange(parent, tokenInfo.token)) { + // consume list end token + consumeTokenAndAdvanceScanner(tokenInfo, parent, listDynamicIndentation, parent, /*isListEndToken*/ true); + } + } + } + function consumeTokenAndAdvanceScanner(currentTokenInfo, parent, dynamicIndentation, container, isListEndToken) { + ts.Debug.assert(ts.rangeContainsRange(parent, currentTokenInfo.token)); + var lastTriviaWasNewLine = formattingScanner.lastTrailingTriviaWasNewLine(); + var indentToken = false; + if (currentTokenInfo.leadingTrivia) { + processTrivia(currentTokenInfo.leadingTrivia, parent, childContextNode, dynamicIndentation); + } + var lineAction = 0 /* None */; + var isTokenInRange = ts.rangeContainsRange(originalRange, currentTokenInfo.token); + var tokenStart = sourceFile.getLineAndCharacterOfPosition(currentTokenInfo.token.pos); + if (isTokenInRange) { + var rangeHasError = rangeContainsError(currentTokenInfo.token); + // save previousRange since processRange will overwrite this value with current one + var savePreviousRange = previousRange; + lineAction = processRange(currentTokenInfo.token, tokenStart, parent, childContextNode, dynamicIndentation); + // do not indent comments\token if token range overlaps with some error + if (!rangeHasError) { + if (lineAction === 0 /* None */) { + // indent token only if end line of previous range does not match start line of the token + var prevEndLine = savePreviousRange && sourceFile.getLineAndCharacterOfPosition(savePreviousRange.end).line; + indentToken = lastTriviaWasNewLine && tokenStart.line !== prevEndLine; + } + else { + indentToken = lineAction === 1 /* LineAdded */; + } + } + } + if (currentTokenInfo.trailingTrivia) { + processTrivia(currentTokenInfo.trailingTrivia, parent, childContextNode, dynamicIndentation); + } + if (indentToken) { + var tokenIndentation = (isTokenInRange && !rangeContainsError(currentTokenInfo.token)) ? + dynamicIndentation.getIndentationForToken(tokenStart.line, currentTokenInfo.token.kind, container, !!isListEndToken) : + -1 /* Unknown */; + var indentNextTokenOrTrivia = true; + if (currentTokenInfo.leadingTrivia) { + var commentIndentation_1 = dynamicIndentation.getIndentationForComment(currentTokenInfo.token.kind, tokenIndentation, container); + indentNextTokenOrTrivia = indentTriviaItems(currentTokenInfo.leadingTrivia, commentIndentation_1, indentNextTokenOrTrivia, function (item) { return insertIndentation(item.pos, commentIndentation_1, /*lineAdded*/ false); }); + } + // indent token only if is it is in target range and does not overlap with any error ranges + if (tokenIndentation !== -1 /* Unknown */ && indentNextTokenOrTrivia) { + insertIndentation(currentTokenInfo.token.pos, tokenIndentation, lineAction === 1 /* LineAdded */); + lastIndentedLine = tokenStart.line; + indentationOnLastIndentedLine = tokenIndentation; + } + } + formattingScanner.advance(); + childContextNode = parent; + } + } + function indentTriviaItems(trivia, commentIndentation, indentNextTokenOrTrivia, indentSingleLine) { + for (var _i = 0, trivia_1 = trivia; _i < trivia_1.length; _i++) { + var triviaItem = trivia_1[_i]; + var triviaInRange = ts.rangeContainsRange(originalRange, triviaItem); + switch (triviaItem.kind) { + case 3 /* MultiLineCommentTrivia */: + if (triviaInRange) { + indentMultilineCommentOrJsxText(triviaItem, commentIndentation, /*firstLineIsIndented*/ !indentNextTokenOrTrivia); + } + indentNextTokenOrTrivia = false; + break; + case 2 /* SingleLineCommentTrivia */: + if (indentNextTokenOrTrivia && triviaInRange) { + indentSingleLine(triviaItem); + } + indentNextTokenOrTrivia = false; + break; + case 4 /* NewLineTrivia */: + indentNextTokenOrTrivia = true; + break; + } + } + return indentNextTokenOrTrivia; + } + function processTrivia(trivia, parent, contextNode, dynamicIndentation) { + for (var _i = 0, trivia_2 = trivia; _i < trivia_2.length; _i++) { + var triviaItem = trivia_2[_i]; + if (ts.isComment(triviaItem.kind) && ts.rangeContainsRange(originalRange, triviaItem)) { + var triviaItemStart = sourceFile.getLineAndCharacterOfPosition(triviaItem.pos); + processRange(triviaItem, triviaItemStart, parent, contextNode, dynamicIndentation); + } + } + } + function processRange(range, rangeStart, parent, contextNode, dynamicIndentation) { + var rangeHasError = rangeContainsError(range); + var lineAction = 0 /* None */; + if (!rangeHasError) { + if (!previousRange) { + // trim whitespaces starting from the beginning of the span up to the current line + var originalStart = sourceFile.getLineAndCharacterOfPosition(originalRange.pos); + trimTrailingWhitespacesForLines(originalStart.line, rangeStart.line); + } + else { + lineAction = + processPair(range, rangeStart.line, parent, previousRange, previousRangeStartLine, previousParent, contextNode, dynamicIndentation); + } + } + previousRange = range; + previousParent = parent; + previousRangeStartLine = rangeStart.line; + return lineAction; + } + function processPair(currentItem, currentStartLine, currentParent, previousItem, previousStartLine, previousParent, contextNode, dynamicIndentation) { + formattingContext.updateContext(previousItem, previousParent, currentItem, currentParent, contextNode); + var rule = getRule(formattingContext); + var trimTrailingWhitespaces; + var lineAction = 0 /* None */; + if (rule) { + lineAction = applyRuleEdits(rule, previousItem, previousStartLine, currentItem, currentStartLine); + switch (lineAction) { + case 2 /* LineRemoved */: + // Handle the case where the next line is moved to be the end of this line. + // In this case we don't indent the next line in the next pass. + if (currentParent.getStart(sourceFile) === currentItem.pos) { + dynamicIndentation.recomputeIndentation(/*lineAddedByFormatting*/ false); + } + break; + case 1 /* LineAdded */: + // Handle the case where token2 is moved to the new line. + // In this case we indent token2 in the next pass but we set + // sameLineIndent flag to notify the indenter that the indentation is within the line. + if (currentParent.getStart(sourceFile) === currentItem.pos) { + dynamicIndentation.recomputeIndentation(/*lineAddedByFormatting*/ true); + } + break; + default: + ts.Debug.assert(lineAction === 0 /* None */); + } + // We need to trim trailing whitespace between the tokens if they were on different lines, and no rule was applied to put them on the same line + trimTrailingWhitespaces = !(rule.action & 8 /* Delete */) && rule.flags !== 1 /* CanDeleteNewLines */; + } + else { + trimTrailingWhitespaces = true; + } + if (currentStartLine !== previousStartLine && trimTrailingWhitespaces) { + // We need to trim trailing whitespace between the tokens if they were on different lines, and no rule was applied to put them on the same line + trimTrailingWhitespacesForLines(previousStartLine, currentStartLine, previousItem); + } + return lineAction; + } + function insertIndentation(pos, indentation, lineAdded) { + var indentationString = getIndentationString(indentation, options); + if (lineAdded) { + // new line is added before the token by the formatting rules + // insert indentation string at the very beginning of the token + recordReplace(pos, 0, indentationString); + } + else { + var tokenStart = sourceFile.getLineAndCharacterOfPosition(pos); + var startLinePosition = ts.getStartPositionOfLine(tokenStart.line, sourceFile); + if (indentation !== characterToColumn(startLinePosition, tokenStart.character) || indentationIsDifferent(indentationString, startLinePosition)) { + recordReplace(startLinePosition, tokenStart.character, indentationString); + } + } + } + function characterToColumn(startLinePosition, characterInLine) { + var column = 0; + for (var i = 0; i < characterInLine; i++) { + if (sourceFile.text.charCodeAt(startLinePosition + i) === 9 /* tab */) { + column += options.tabSize - column % options.tabSize; + } + else { + column++; + } + } + return column; + } + function indentationIsDifferent(indentationString, startLinePosition) { + return indentationString !== sourceFile.text.substr(startLinePosition, indentationString.length); + } + function indentMultilineCommentOrJsxText(commentRange, indentation, firstLineIsIndented, indentFinalLine) { + if (indentFinalLine === void 0) { indentFinalLine = true; } + // split comment in lines + var startLine = sourceFile.getLineAndCharacterOfPosition(commentRange.pos).line; + var endLine = sourceFile.getLineAndCharacterOfPosition(commentRange.end).line; + if (startLine === endLine) { + if (!firstLineIsIndented) { + // treat as single line comment + insertIndentation(commentRange.pos, indentation, /*lineAdded*/ false); + } + return; + } + var parts = []; + var startPos = commentRange.pos; + for (var line = startLine; line < endLine; line++) { + var endOfLine = ts.getEndLinePosition(line, sourceFile); + parts.push({ pos: startPos, end: endOfLine }); + startPos = ts.getStartPositionOfLine(line + 1, sourceFile); + } + if (indentFinalLine) { + parts.push({ pos: startPos, end: commentRange.end }); + } + if (parts.length === 0) + return; + var startLinePos = ts.getStartPositionOfLine(startLine, sourceFile); + var nonWhitespaceColumnInFirstPart = formatting.SmartIndenter.findFirstNonWhitespaceCharacterAndColumn(startLinePos, parts[0].pos, sourceFile, options); + if (indentation === nonWhitespaceColumnInFirstPart.column) { + return; + } + var startIndex = 0; + if (firstLineIsIndented) { + startIndex = 1; + startLine++; + } + // shift all parts on the delta size + var delta = indentation - nonWhitespaceColumnInFirstPart.column; + for (var i = startIndex; i < parts.length; i++, startLine++) { + var startLinePos_1 = ts.getStartPositionOfLine(startLine, sourceFile); + var nonWhitespaceCharacterAndColumn = i === 0 + ? nonWhitespaceColumnInFirstPart + : formatting.SmartIndenter.findFirstNonWhitespaceCharacterAndColumn(parts[i].pos, parts[i].end, sourceFile, options); + var newIndentation = nonWhitespaceCharacterAndColumn.column + delta; + if (newIndentation > 0) { + var indentationString = getIndentationString(newIndentation, options); + recordReplace(startLinePos_1, nonWhitespaceCharacterAndColumn.character, indentationString); + } + else { + recordDelete(startLinePos_1, nonWhitespaceCharacterAndColumn.character); + } + } + } + function trimTrailingWhitespacesForLines(line1, line2, range) { + for (var line = line1; line < line2; line++) { + var lineStartPosition = ts.getStartPositionOfLine(line, sourceFile); + var lineEndPosition = ts.getEndLinePosition(line, sourceFile); + // do not trim whitespaces in comments or template expression + if (range && (ts.isComment(range.kind) || ts.isStringOrRegularExpressionOrTemplateLiteral(range.kind)) && range.pos <= lineEndPosition && range.end > lineEndPosition) { + continue; + } + var whitespaceStart = getTrailingWhitespaceStartPosition(lineStartPosition, lineEndPosition); + if (whitespaceStart !== -1) { + ts.Debug.assert(whitespaceStart === lineStartPosition || !ts.isWhiteSpaceSingleLine(sourceFile.text.charCodeAt(whitespaceStart - 1))); + recordDelete(whitespaceStart, lineEndPosition + 1 - whitespaceStart); + } + } + } + /** + * @param start The position of the first character in range + * @param end The position of the last character in range + */ + function getTrailingWhitespaceStartPosition(start, end) { + var pos = end; + while (pos >= start && ts.isWhiteSpaceSingleLine(sourceFile.text.charCodeAt(pos))) { + pos--; + } + if (pos !== end) { + return pos + 1; + } + return -1; + } + /** + * Trimming will be done for lines after the previous range + */ + function trimTrailingWhitespacesForRemainingRange() { + var startPosition = previousRange ? previousRange.end : originalRange.pos; + var startLine = sourceFile.getLineAndCharacterOfPosition(startPosition).line; + var endLine = sourceFile.getLineAndCharacterOfPosition(originalRange.end).line; + trimTrailingWhitespacesForLines(startLine, endLine + 1, previousRange); + } + function recordDelete(start, len) { + if (len) { + edits.push(ts.createTextChangeFromStartLength(start, len, "")); + } + } + function recordReplace(start, len, newText) { + if (len || newText) { + edits.push(ts.createTextChangeFromStartLength(start, len, newText)); + } + } + function applyRuleEdits(rule, previousRange, previousStartLine, currentRange, currentStartLine) { + var onLaterLine = currentStartLine !== previousStartLine; + switch (rule.action) { + case 1 /* Ignore */: + // no action required + return 0 /* None */; + case 8 /* Delete */: + if (previousRange.end !== currentRange.pos) { + // delete characters starting from t1.end up to t2.pos exclusive + recordDelete(previousRange.end, currentRange.pos - previousRange.end); + return onLaterLine ? 2 /* LineRemoved */ : 0 /* None */; + } + break; + case 4 /* NewLine */: + // exit early if we on different lines and rule cannot change number of newlines + // if line1 and line2 are on subsequent lines then no edits are required - ok to exit + // if line1 and line2 are separated with more than one newline - ok to exit since we cannot delete extra new lines + if (rule.flags !== 1 /* CanDeleteNewLines */ && previousStartLine !== currentStartLine) { + return 0 /* None */; + } + // edit should not be applied if we have one line feed between elements + var lineDelta = currentStartLine - previousStartLine; + if (lineDelta !== 1) { + recordReplace(previousRange.end, currentRange.pos - previousRange.end, options.newLineCharacter); + return onLaterLine ? 0 /* None */ : 1 /* LineAdded */; + } + break; + case 2 /* Space */: + // exit early if we on different lines and rule cannot change number of newlines + if (rule.flags !== 1 /* CanDeleteNewLines */ && previousStartLine !== currentStartLine) { + return 0 /* None */; + } + var posDelta = currentRange.pos - previousRange.end; + if (posDelta !== 1 || sourceFile.text.charCodeAt(previousRange.end) !== 32 /* space */) { + recordReplace(previousRange.end, currentRange.pos - previousRange.end, " "); + return onLaterLine ? 2 /* LineRemoved */ : 0 /* None */; + } + } + return 0 /* None */; + } + } + var LineAction; + (function (LineAction) { + LineAction[LineAction["None"] = 0] = "None"; + LineAction[LineAction["LineAdded"] = 1] = "LineAdded"; + LineAction[LineAction["LineRemoved"] = 2] = "LineRemoved"; + })(LineAction || (LineAction = {})); + /** + * @param precedingToken pass `null` if preceding token was already computed and result was `undefined`. + */ + function getRangeOfEnclosingComment(sourceFile, position, precedingToken, // tslint:disable-line:no-null-keyword + tokenAtPosition) { + if (tokenAtPosition === void 0) { tokenAtPosition = ts.getTokenAtPosition(sourceFile, position); } + var jsdoc = ts.findAncestor(tokenAtPosition, ts.isJSDoc); + if (jsdoc) + tokenAtPosition = jsdoc.parent; + var tokenStart = tokenAtPosition.getStart(sourceFile); + if (tokenStart <= position && position < tokenAtPosition.getEnd()) { + return undefined; + } + precedingToken = precedingToken === null ? undefined : precedingToken === undefined ? ts.findPrecedingToken(position, sourceFile) : precedingToken; + // Between two consecutive tokens, all comments are either trailing on the former + // or leading on the latter (and none are in both lists). + var trailingRangesOfPreviousToken = precedingToken && ts.getTrailingCommentRanges(sourceFile.text, precedingToken.end); + var leadingCommentRangesOfNextToken = ts.getLeadingCommentRangesOfNode(tokenAtPosition, sourceFile); + var commentRanges = ts.concatenate(trailingRangesOfPreviousToken, leadingCommentRangesOfNextToken); + return commentRanges && ts.find(commentRanges, function (range) { return ts.rangeContainsPositionExclusive(range, position) || + // The end marker of a single-line comment does not include the newline character. + // With caret at `^`, in the following case, we are inside a comment (^ denotes the cursor position): + // + // // asdf ^\n + // + // But for closed multi-line comments, we don't want to be inside the comment in the following case: + // + // /* asdf */^ + // + // However, unterminated multi-line comments *do* contain their end. + // + // Internally, we represent the end of the comment at the newline and closing '/', respectively. + // + position === range.end && (range.kind === 2 /* SingleLineCommentTrivia */ || position === sourceFile.getFullWidth()); }); + } + formatting.getRangeOfEnclosingComment = getRangeOfEnclosingComment; + function getOpenTokenForList(node, list) { + switch (node.kind) { + case 157 /* Constructor */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 197 /* ArrowFunction */: + if (node.typeParameters === list) { + return 28 /* LessThanToken */; + } + else if (node.parameters === list) { + return 20 /* OpenParenToken */; + } + break; + case 191 /* CallExpression */: + case 192 /* NewExpression */: + if (node.typeArguments === list) { + return 28 /* LessThanToken */; + } + else if (node.arguments === list) { + return 20 /* OpenParenToken */; + } + break; + case 164 /* TypeReference */: + if (node.typeArguments === list) { + return 28 /* LessThanToken */; + } + break; + case 168 /* TypeLiteral */: + return 18 /* OpenBraceToken */; + } + return 0 /* Unknown */; + } + function getCloseTokenForOpenToken(kind) { + switch (kind) { + case 20 /* OpenParenToken */: + return 21 /* CloseParenToken */; + case 28 /* LessThanToken */: + return 30 /* GreaterThanToken */; + case 18 /* OpenBraceToken */: + return 19 /* CloseBraceToken */; + } + return 0 /* Unknown */; + } + var internedSizes; + var internedTabsIndentation; + var internedSpacesIndentation; + function getIndentationString(indentation, options) { + // reset interned strings if FormatCodeOptions were changed + var resetInternedStrings = !internedSizes || (internedSizes.tabSize !== options.tabSize || internedSizes.indentSize !== options.indentSize); + if (resetInternedStrings) { + internedSizes = { tabSize: options.tabSize, indentSize: options.indentSize }; + internedTabsIndentation = internedSpacesIndentation = undefined; + } + if (!options.convertTabsToSpaces) { + var tabs = Math.floor(indentation / options.tabSize); + var spaces = indentation - tabs * options.tabSize; + var tabString = void 0; + if (!internedTabsIndentation) { + internedTabsIndentation = []; + } + if (internedTabsIndentation[tabs] === undefined) { + internedTabsIndentation[tabs] = tabString = ts.repeatString("\t", tabs); + } + else { + tabString = internedTabsIndentation[tabs]; + } + return spaces ? tabString + ts.repeatString(" ", spaces) : tabString; + } + else { + var spacesString = void 0; + var quotient = Math.floor(indentation / options.indentSize); + var remainder = indentation % options.indentSize; + if (!internedSpacesIndentation) { + internedSpacesIndentation = []; + } + if (internedSpacesIndentation[quotient] === undefined) { + spacesString = ts.repeatString(" ", options.indentSize * quotient); + internedSpacesIndentation[quotient] = spacesString; + } + else { + spacesString = internedSpacesIndentation[quotient]; + } + return remainder ? spacesString + ts.repeatString(" ", remainder) : spacesString; + } + } + formatting.getIndentationString = getIndentationString; + })(formatting = ts.formatting || (ts.formatting = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var formatting; + (function (formatting) { + var SmartIndenter; + (function (SmartIndenter) { + var Value; + (function (Value) { + Value[Value["Unknown"] = -1] = "Unknown"; + })(Value || (Value = {})); + /** + * @param assumeNewLineBeforeCloseBrace + * `false` when called on text from a real source file. + * `true` when we need to assume `position` is on a newline. + * + * This is useful for codefixes. Consider + * ``` + * function f() { + * |} + * ``` + * with `position` at `|`. + * + * When inserting some text after an open brace, we would like to get indentation as if a newline was already there. + * By default indentation at `position` will be 0 so 'assumeNewLineBeforeCloseBrace' overrides this behavior. + */ + function getIndentation(position, sourceFile, options, assumeNewLineBeforeCloseBrace) { + if (assumeNewLineBeforeCloseBrace === void 0) { assumeNewLineBeforeCloseBrace = false; } + if (position > sourceFile.text.length) { + return getBaseIndentation(options); // past EOF + } + // no indentation when the indent style is set to none, + // so we can return fast + if (options.indentStyle === ts.IndentStyle.None) { + return 0; + } + var precedingToken = ts.findPrecedingToken(position, sourceFile, /*startNode*/ undefined, /*excludeJsdoc*/ true); + var enclosingCommentRange = formatting.getRangeOfEnclosingComment(sourceFile, position, precedingToken || null); // tslint:disable-line:no-null-keyword + if (enclosingCommentRange && enclosingCommentRange.kind === 3 /* MultiLineCommentTrivia */) { + return getCommentIndent(sourceFile, position, options, enclosingCommentRange); + } + if (!precedingToken) { + return getBaseIndentation(options); + } + // no indentation in string \regex\template literals + var precedingTokenIsLiteral = ts.isStringOrRegularExpressionOrTemplateLiteral(precedingToken.kind); + if (precedingTokenIsLiteral && precedingToken.getStart(sourceFile) <= position && position < precedingToken.end) { + return 0; + } + var lineAtPosition = sourceFile.getLineAndCharacterOfPosition(position).line; + // indentation is first non-whitespace character in a previous line + // for block indentation, we should look for a line which contains something that's not + // whitespace. + if (options.indentStyle === ts.IndentStyle.Block) { + return getBlockIndent(sourceFile, position, options); + } + if (precedingToken.kind === 27 /* CommaToken */ && precedingToken.parent.kind !== 204 /* BinaryExpression */) { + // previous token is comma that separates items in list - find the previous item and try to derive indentation from it + var actualIndentation = getActualIndentationForListItemBeforeComma(precedingToken, sourceFile, options); + if (actualIndentation !== -1 /* Unknown */) { + return actualIndentation; + } + } + var containerList = getListByPosition(position, precedingToken.parent, sourceFile); + // use list position if the preceding token is before any list items + if (containerList && !ts.rangeContainsRange(containerList, precedingToken)) { + return getActualIndentationForListStartLine(containerList, sourceFile, options) + options.indentSize; // TODO: GH#18217 + } + return getSmartIndent(sourceFile, position, precedingToken, lineAtPosition, assumeNewLineBeforeCloseBrace, options); + } + SmartIndenter.getIndentation = getIndentation; + function getCommentIndent(sourceFile, position, options, enclosingCommentRange) { + var previousLine = ts.getLineAndCharacterOfPosition(sourceFile, position).line - 1; + var commentStartLine = ts.getLineAndCharacterOfPosition(sourceFile, enclosingCommentRange.pos).line; + ts.Debug.assert(commentStartLine >= 0); + if (previousLine <= commentStartLine) { + return findFirstNonWhitespaceColumn(ts.getStartPositionOfLine(commentStartLine, sourceFile), position, sourceFile, options); + } + var startPositionOfLine = ts.getStartPositionOfLine(previousLine, sourceFile); + var _a = findFirstNonWhitespaceCharacterAndColumn(startPositionOfLine, position, sourceFile, options), column = _a.column, character = _a.character; + if (column === 0) { + return column; + } + var firstNonWhitespaceCharacterCode = sourceFile.text.charCodeAt(startPositionOfLine + character); + return firstNonWhitespaceCharacterCode === 42 /* asterisk */ ? column - 1 : column; + } + function getBlockIndent(sourceFile, position, options) { + // move backwards until we find a line with a non-whitespace character, + // then find the first non-whitespace character for that line. + var current = position; + while (current > 0) { + var char = sourceFile.text.charCodeAt(current); + if (!ts.isWhiteSpaceLike(char)) { + break; + } + current--; + } + var lineStart = ts.getLineStartPositionForPosition(current, sourceFile); + return findFirstNonWhitespaceColumn(lineStart, current, sourceFile, options); + } + function getSmartIndent(sourceFile, position, precedingToken, lineAtPosition, assumeNewLineBeforeCloseBrace, options) { + // try to find node that can contribute to indentation and includes 'position' starting from 'precedingToken' + // if such node is found - compute initial indentation for 'position' inside this node + var previous; + var current = precedingToken; + while (current) { + if (ts.positionBelongsToNode(current, position, sourceFile) && shouldIndentChildNode(options, current, previous, sourceFile, /*isNextChild*/ true)) { + var currentStart = getStartLineAndCharacterForNode(current, sourceFile); + var nextTokenKind = nextTokenIsCurlyBraceOnSameLineAsCursor(precedingToken, current, lineAtPosition, sourceFile); + var indentationDelta = nextTokenKind !== 0 /* Unknown */ + // handle cases when codefix is about to be inserted before the close brace + ? assumeNewLineBeforeCloseBrace && nextTokenKind === 2 /* CloseBrace */ ? options.indentSize : 0 + : lineAtPosition !== currentStart.line ? options.indentSize : 0; + return getIndentationForNodeWorker(current, currentStart, /*ignoreActualIndentationRange*/ undefined, indentationDelta, sourceFile, /*isNextChild*/ true, options); // TODO: GH#18217 + } + // check if current node is a list item - if yes, take indentation from it + // do not consider parent-child line sharing yet: + // function foo(a + // | preceding node 'a' does share line with its parent but indentation is expected + var actualIndentation = getActualIndentationForListItem(current, sourceFile, options, /*listIndentsChild*/ true); + if (actualIndentation !== -1 /* Unknown */) { + return actualIndentation; + } + previous = current; + current = current.parent; + } + // no parent was found - return the base indentation of the SourceFile + return getBaseIndentation(options); + } + function getIndentationForNode(n, ignoreActualIndentationRange, sourceFile, options) { + var start = sourceFile.getLineAndCharacterOfPosition(n.getStart(sourceFile)); + return getIndentationForNodeWorker(n, start, ignoreActualIndentationRange, /*indentationDelta*/ 0, sourceFile, /*isNextChild*/ false, options); + } + SmartIndenter.getIndentationForNode = getIndentationForNode; + function getBaseIndentation(options) { + return options.baseIndentSize || 0; + } + SmartIndenter.getBaseIndentation = getBaseIndentation; + function getIndentationForNodeWorker(current, currentStart, ignoreActualIndentationRange, indentationDelta, sourceFile, isNextChild, options) { + var parent = current.parent; + // Walk up the tree and collect indentation for parent-child node pairs. Indentation is not added if + // * parent and child nodes start on the same line, or + // * parent is an IfStatement and child starts on the same line as an 'else clause'. + while (parent) { + var useActualIndentation = true; + if (ignoreActualIndentationRange) { + var start = current.getStart(sourceFile); + useActualIndentation = start < ignoreActualIndentationRange.pos || start > ignoreActualIndentationRange.end; + } + var containingListOrParentStart = getContainingListOrParentStart(parent, current, sourceFile); + var parentAndChildShareLine = containingListOrParentStart.line === currentStart.line || + childStartsOnTheSameLineWithElseInIfStatement(parent, current, currentStart.line, sourceFile); + if (useActualIndentation) { + // check if current node is a list item - if yes, take indentation from it + var actualIndentation = getActualIndentationForListItem(current, sourceFile, options, !parentAndChildShareLine); + if (actualIndentation !== -1 /* Unknown */) { + return actualIndentation + indentationDelta; + } + // try to fetch actual indentation for current node from source text + actualIndentation = getActualIndentationForNode(current, parent, currentStart, parentAndChildShareLine, sourceFile, options); + if (actualIndentation !== -1 /* Unknown */) { + return actualIndentation + indentationDelta; + } + } + // increase indentation if parent node wants its content to be indented and parent and child nodes don't start on the same line + if (shouldIndentChildNode(options, parent, current, sourceFile, isNextChild) && !parentAndChildShareLine) { + indentationDelta += options.indentSize; + } + // In our AST, a call argument's `parent` is the call-expression, not the argument list. + // We would like to increase indentation based on the relationship between an argument and its argument-list, + // so we spoof the starting position of the (parent) call-expression to match the (non-parent) argument-list. + // But, the spoofed start-value could then cause a problem when comparing the start position of the call-expression + // to *its* parent (in the case of an iife, an expression statement), adding an extra level of indentation. + // + // Instead, when at an argument, we unspoof the starting position of the enclosing call expression + // *after* applying indentation for the argument. + var useTrueStart = isArgumentAndStartLineOverlapsExpressionBeingCalled(parent, current, currentStart.line, sourceFile); + current = parent; + parent = current.parent; + currentStart = useTrueStart ? sourceFile.getLineAndCharacterOfPosition(current.getStart(sourceFile)) : containingListOrParentStart; + } + return indentationDelta + getBaseIndentation(options); + } + function getContainingListOrParentStart(parent, child, sourceFile) { + var containingList = getContainingList(child, sourceFile); + var startPos = containingList ? containingList.pos : parent.getStart(sourceFile); + return sourceFile.getLineAndCharacterOfPosition(startPos); + } + /* + * Function returns Value.Unknown if indentation cannot be determined + */ + function getActualIndentationForListItemBeforeComma(commaToken, sourceFile, options) { + // previous token is comma that separates items in list - find the previous item and try to derive indentation from it + var commaItemInfo = ts.findListItemInfo(commaToken); + if (commaItemInfo && commaItemInfo.listItemIndex > 0) { + return deriveActualIndentationFromList(commaItemInfo.list.getChildren(), commaItemInfo.listItemIndex - 1, sourceFile, options); + } + else { + // handle broken code gracefully + return -1 /* Unknown */; + } + } + /* + * Function returns Value.Unknown if actual indentation for node should not be used (i.e because node is nested expression) + */ + function getActualIndentationForNode(current, parent, currentLineAndChar, parentAndChildShareLine, sourceFile, options) { + // actual indentation is used for statements\declarations if one of cases below is true: + // - parent is SourceFile - by default immediate children of SourceFile are not indented except when user indents them manually + // - parent and child are not on the same line + var useActualIndentation = (ts.isDeclaration(current) || ts.isStatementButNotDeclaration(current)) && + (parent.kind === 279 /* SourceFile */ || !parentAndChildShareLine); + if (!useActualIndentation) { + return -1 /* Unknown */; + } + return findColumnForFirstNonWhitespaceCharacterInLine(currentLineAndChar, sourceFile, options); + } + var NextTokenKind; + (function (NextTokenKind) { + NextTokenKind[NextTokenKind["Unknown"] = 0] = "Unknown"; + NextTokenKind[NextTokenKind["OpenBrace"] = 1] = "OpenBrace"; + NextTokenKind[NextTokenKind["CloseBrace"] = 2] = "CloseBrace"; + })(NextTokenKind || (NextTokenKind = {})); + function nextTokenIsCurlyBraceOnSameLineAsCursor(precedingToken, current, lineAtPosition, sourceFile) { + var nextToken = ts.findNextToken(precedingToken, current, sourceFile); + if (!nextToken) { + return 0 /* Unknown */; + } + if (nextToken.kind === 18 /* OpenBraceToken */) { + // open braces are always indented at the parent level + return 1 /* OpenBrace */; + } + else if (nextToken.kind === 19 /* CloseBraceToken */) { + // close braces are indented at the parent level if they are located on the same line with cursor + // this means that if new line will be added at $ position, this case will be indented + // class A { + // $ + // } + /// and this one - not + // class A { + // $} + var nextTokenStartLine = getStartLineAndCharacterForNode(nextToken, sourceFile).line; + return lineAtPosition === nextTokenStartLine ? 2 /* CloseBrace */ : 0 /* Unknown */; + } + return 0 /* Unknown */; + } + function getStartLineAndCharacterForNode(n, sourceFile) { + return sourceFile.getLineAndCharacterOfPosition(n.getStart(sourceFile)); + } + function isArgumentAndStartLineOverlapsExpressionBeingCalled(parent, child, childStartLine, sourceFile) { + if (!(ts.isCallExpression(parent) && ts.contains(parent.arguments, child))) { + return false; + } + var expressionOfCallExpressionEnd = parent.expression.getEnd(); + var expressionOfCallExpressionEndLine = ts.getLineAndCharacterOfPosition(sourceFile, expressionOfCallExpressionEnd).line; + return expressionOfCallExpressionEndLine === childStartLine; + } + SmartIndenter.isArgumentAndStartLineOverlapsExpressionBeingCalled = isArgumentAndStartLineOverlapsExpressionBeingCalled; + function childStartsOnTheSameLineWithElseInIfStatement(parent, child, childStartLine, sourceFile) { + if (parent.kind === 222 /* IfStatement */ && parent.elseStatement === child) { + var elseKeyword = ts.findChildOfKind(parent, 83 /* ElseKeyword */, sourceFile); + ts.Debug.assert(elseKeyword !== undefined); + var elseKeywordStartLine = getStartLineAndCharacterForNode(elseKeyword, sourceFile).line; + return elseKeywordStartLine === childStartLine; + } + return false; + } + SmartIndenter.childStartsOnTheSameLineWithElseInIfStatement = childStartsOnTheSameLineWithElseInIfStatement; + function getContainingList(node, sourceFile) { + return node.parent && getListByRange(node.getStart(sourceFile), node.getEnd(), node.parent, sourceFile); + } + SmartIndenter.getContainingList = getContainingList; + function getListByPosition(pos, node, sourceFile) { + return node && getListByRange(pos, pos, node, sourceFile); + } + function getListByRange(start, end, node, sourceFile) { + switch (node.kind) { + case 164 /* TypeReference */: + return getList(node.typeArguments); + case 188 /* ObjectLiteralExpression */: + return getList(node.properties); + case 187 /* ArrayLiteralExpression */: + return getList(node.elements); + case 168 /* TypeLiteral */: + return getList(node.members); + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 160 /* CallSignature */: + case 157 /* Constructor */: + case 166 /* ConstructorType */: + case 161 /* ConstructSignature */: + return getList(node.typeParameters) || getList(node.parameters); + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 241 /* InterfaceDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 303 /* JSDocTemplateTag */: + return getList(node.typeParameters); + case 192 /* NewExpression */: + case 191 /* CallExpression */: + return getList(node.typeArguments) || getList(node.arguments); + case 238 /* VariableDeclarationList */: + return getList(node.declarations); + case 252 /* NamedImports */: + case 256 /* NamedExports */: + return getList(node.elements); + case 184 /* ObjectBindingPattern */: + case 185 /* ArrayBindingPattern */: + return getList(node.elements); + } + function getList(list) { + return list && ts.rangeContainsStartEnd(getVisualListRange(node, list, sourceFile), start, end) ? list : undefined; + } + } + function getVisualListRange(node, list, sourceFile) { + var children = node.getChildren(sourceFile); + for (var i = 1; i < children.length - 1; i++) { + if (children[i].pos === list.pos && children[i].end === list.end) { + return { pos: children[i - 1].end, end: children[i + 1].getStart(sourceFile) }; + } + } + return list; + } + function getActualIndentationForListStartLine(list, sourceFile, options) { + if (!list) { + return -1 /* Unknown */; + } + return findColumnForFirstNonWhitespaceCharacterInLine(sourceFile.getLineAndCharacterOfPosition(list.pos), sourceFile, options); + } + function getActualIndentationForListItem(node, sourceFile, options, listIndentsChild) { + if (node.parent && node.parent.kind === 238 /* VariableDeclarationList */) { + // VariableDeclarationList has no wrapping tokens + return -1 /* Unknown */; + } + var containingList = getContainingList(node, sourceFile); + if (containingList) { + var index = containingList.indexOf(node); + if (index !== -1) { + var result = deriveActualIndentationFromList(containingList, index, sourceFile, options); + if (result !== -1 /* Unknown */) { + return result; + } + } + return getActualIndentationForListStartLine(containingList, sourceFile, options) + (listIndentsChild ? options.indentSize : 0); // TODO: GH#18217 + } + return -1 /* Unknown */; + } + function deriveActualIndentationFromList(list, index, sourceFile, options) { + ts.Debug.assert(index >= 0 && index < list.length); + var node = list[index]; + // walk toward the start of the list starting from current node and check if the line is the same for all items. + // if end line for item [i - 1] differs from the start line for item [i] - find column of the first non-whitespace character on the line of item [i] + var lineAndCharacter = getStartLineAndCharacterForNode(node, sourceFile); + for (var i = index - 1; i >= 0; i--) { + if (list[i].kind === 27 /* CommaToken */) { + continue; + } + // skip list items that ends on the same line with the current list element + var prevEndLine = sourceFile.getLineAndCharacterOfPosition(list[i].end).line; + if (prevEndLine !== lineAndCharacter.line) { + return findColumnForFirstNonWhitespaceCharacterInLine(lineAndCharacter, sourceFile, options); + } + lineAndCharacter = getStartLineAndCharacterForNode(list[i], sourceFile); + } + return -1 /* Unknown */; + } + function findColumnForFirstNonWhitespaceCharacterInLine(lineAndCharacter, sourceFile, options) { + var lineStart = sourceFile.getPositionOfLineAndCharacter(lineAndCharacter.line, 0); + return findFirstNonWhitespaceColumn(lineStart, lineStart + lineAndCharacter.character, sourceFile, options); + } + /** + * Character is the actual index of the character since the beginning of the line. + * Column - position of the character after expanding tabs to spaces. + * "0\t2$" + * value of 'character' for '$' is 3 + * value of 'column' for '$' is 6 (assuming that tab size is 4) + */ + function findFirstNonWhitespaceCharacterAndColumn(startPos, endPos, sourceFile, options) { + var character = 0; + var column = 0; + for (var pos = startPos; pos < endPos; pos++) { + var ch = sourceFile.text.charCodeAt(pos); + if (!ts.isWhiteSpaceSingleLine(ch)) { + break; + } + if (ch === 9 /* tab */) { + column += options.tabSize + (column % options.tabSize); + } + else { + column++; + } + character++; + } + return { column: column, character: character }; + } + SmartIndenter.findFirstNonWhitespaceCharacterAndColumn = findFirstNonWhitespaceCharacterAndColumn; + function findFirstNonWhitespaceColumn(startPos, endPos, sourceFile, options) { + return findFirstNonWhitespaceCharacterAndColumn(startPos, endPos, sourceFile, options).column; + } + SmartIndenter.findFirstNonWhitespaceColumn = findFirstNonWhitespaceColumn; + function nodeWillIndentChild(settings, parent, child, sourceFile, indentByDefault) { + var childKind = child ? child.kind : 0 /* Unknown */; + switch (parent.kind) { + case 221 /* ExpressionStatement */: + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 241 /* InterfaceDeclaration */: + case 243 /* EnumDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 187 /* ArrayLiteralExpression */: + case 218 /* Block */: + case 245 /* ModuleBlock */: + case 188 /* ObjectLiteralExpression */: + case 168 /* TypeLiteral */: + case 181 /* MappedType */: + case 170 /* TupleType */: + case 246 /* CaseBlock */: + case 272 /* DefaultClause */: + case 271 /* CaseClause */: + case 195 /* ParenthesizedExpression */: + case 189 /* PropertyAccessExpression */: + case 191 /* CallExpression */: + case 192 /* NewExpression */: + case 219 /* VariableStatement */: + case 254 /* ExportAssignment */: + case 230 /* ReturnStatement */: + case 205 /* ConditionalExpression */: + case 185 /* ArrayBindingPattern */: + case 184 /* ObjectBindingPattern */: + case 262 /* JsxOpeningElement */: + case 265 /* JsxOpeningFragment */: + case 261 /* JsxSelfClosingElement */: + case 270 /* JsxExpression */: + case 155 /* MethodSignature */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 151 /* Parameter */: + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + case 177 /* ParenthesizedType */: + case 193 /* TaggedTemplateExpression */: + case 201 /* AwaitExpression */: + case 256 /* NamedExports */: + case 252 /* NamedImports */: + case 257 /* ExportSpecifier */: + case 253 /* ImportSpecifier */: + case 154 /* PropertyDeclaration */: + return true; + case 237 /* VariableDeclaration */: + case 275 /* PropertyAssignment */: + if (!settings.indentMultiLineObjectLiteralBeginningOnBlankLine && sourceFile && childKind === 188 /* ObjectLiteralExpression */) { // TODO: GH#18217 + return rangeIsOnOneLine(sourceFile, child); + } + return true; + case 223 /* DoStatement */: + case 224 /* WhileStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + case 225 /* ForStatement */: + case 222 /* IfStatement */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 156 /* MethodDeclaration */: + case 197 /* ArrowFunction */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + return childKind !== 218 /* Block */; + case 255 /* ExportDeclaration */: + return childKind !== 256 /* NamedExports */; + case 249 /* ImportDeclaration */: + return childKind !== 250 /* ImportClause */ || + (!!child.namedBindings && child.namedBindings.kind !== 252 /* NamedImports */); + case 260 /* JsxElement */: + return childKind !== 263 /* JsxClosingElement */; + case 264 /* JsxFragment */: + return childKind !== 266 /* JsxClosingFragment */; + case 174 /* IntersectionType */: + case 173 /* UnionType */: + if (childKind === 168 /* TypeLiteral */) { + return false; + } + // falls through + } + // No explicit rule for given nodes so the result will follow the default value argument + return indentByDefault; + } + SmartIndenter.nodeWillIndentChild = nodeWillIndentChild; + function isControlFlowEndingStatement(kind, parent) { + switch (kind) { + case 230 /* ReturnStatement */: + case 234 /* ThrowStatement */: + case 228 /* ContinueStatement */: + case 229 /* BreakStatement */: + return parent.kind !== 218 /* Block */; + default: + return false; + } + } + /** + * True when the parent node should indent the given child by an explicit rule. + * @param isNextChild If true, we are judging indent of a hypothetical child *after* this one, not the current child. + */ + function shouldIndentChildNode(settings, parent, child, sourceFile, isNextChild) { + if (isNextChild === void 0) { isNextChild = false; } + return nodeWillIndentChild(settings, parent, child, sourceFile, /*indentByDefault*/ false) + && !(isNextChild && child && isControlFlowEndingStatement(child.kind, parent)); + } + SmartIndenter.shouldIndentChildNode = shouldIndentChildNode; + function rangeIsOnOneLine(sourceFile, range) { + var rangeStart = ts.skipTrivia(sourceFile.text, range.pos); + var startLine = sourceFile.getLineAndCharacterOfPosition(rangeStart).line; + var endLine = sourceFile.getLineAndCharacterOfPosition(range.end).line; + return startLine === endLine; + } + })(SmartIndenter = formatting.SmartIndenter || (formatting.SmartIndenter = {})); + })(formatting = ts.formatting || (ts.formatting = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var textChanges; + (function (textChanges_3) { + /** + * Currently for simplicity we store recovered positions on the node itself. + * It can be changed to side-table later if we decide that current design is too invasive. + */ + function getPos(n) { + var result = n.__pos; + ts.Debug.assert(typeof result === "number"); + return result; + } + function setPos(n, pos) { + ts.Debug.assert(typeof pos === "number"); + n.__pos = pos; + } + function getEnd(n) { + var result = n.__end; + ts.Debug.assert(typeof result === "number"); + return result; + } + function setEnd(n, end) { + ts.Debug.assert(typeof end === "number"); + n.__end = end; + } + var Position; + (function (Position) { + Position[Position["FullStart"] = 0] = "FullStart"; + Position[Position["Start"] = 1] = "Start"; + })(Position = textChanges_3.Position || (textChanges_3.Position = {})); + function skipWhitespacesAndLineBreaks(text, start) { + return ts.skipTrivia(text, start, /*stopAfterLineBreak*/ false, /*stopAtComments*/ true); + } + function hasCommentsBeforeLineBreak(text, start) { + var i = start; + while (i < text.length) { + var ch = text.charCodeAt(i); + if (ts.isWhiteSpaceSingleLine(ch)) { + i++; + continue; + } + return ch === 47 /* slash */; + } + return false; + } + textChanges_3.useNonAdjustedPositions = { + useNonAdjustedStartPosition: true, + useNonAdjustedEndPosition: true, + }; + var ChangeKind; + (function (ChangeKind) { + ChangeKind[ChangeKind["Remove"] = 0] = "Remove"; + ChangeKind[ChangeKind["ReplaceWithSingleNode"] = 1] = "ReplaceWithSingleNode"; + ChangeKind[ChangeKind["ReplaceWithMultipleNodes"] = 2] = "ReplaceWithMultipleNodes"; + ChangeKind[ChangeKind["Text"] = 3] = "Text"; + })(ChangeKind || (ChangeKind = {})); + function getAdjustedRange(sourceFile, startNode, endNode, options) { + return { pos: getAdjustedStartPosition(sourceFile, startNode, options, Position.Start), end: getAdjustedEndPosition(sourceFile, endNode, options) }; + } + function getAdjustedStartPosition(sourceFile, node, options, position) { + if (options.useNonAdjustedStartPosition) { + return node.getStart(sourceFile); + } + var fullStart = node.getFullStart(); + var start = node.getStart(sourceFile); + if (fullStart === start) { + return start; + } + var fullStartLine = ts.getLineStartPositionForPosition(fullStart, sourceFile); + var startLine = ts.getLineStartPositionForPosition(start, sourceFile); + if (startLine === fullStartLine) { + // full start and start of the node are on the same line + // a, b; + // ^ ^ + // | start + // fullstart + // when b is replaced - we usually want to keep the leading trvia + // when b is deleted - we delete it + return position === Position.Start ? start : fullStart; + } + // get start position of the line following the line that contains fullstart position + // (but only if the fullstart isn't the very beginning of the file) + var nextLineStart = fullStart > 0 ? 1 : 0; + var adjustedStartPosition = ts.getStartPositionOfLine(ts.getLineOfLocalPosition(sourceFile, fullStartLine) + nextLineStart, sourceFile); + // skip whitespaces/newlines + adjustedStartPosition = skipWhitespacesAndLineBreaks(sourceFile.text, adjustedStartPosition); + return ts.getStartPositionOfLine(ts.getLineOfLocalPosition(sourceFile, adjustedStartPosition), sourceFile); + } + function getAdjustedEndPosition(sourceFile, node, options) { + var end = node.end; + if (options.useNonAdjustedEndPosition || ts.isExpression(node)) { + return end; + } + var newEnd = ts.skipTrivia(sourceFile.text, end, /*stopAfterLineBreak*/ true); + return newEnd !== end && ts.isLineBreak(sourceFile.text.charCodeAt(newEnd - 1)) + ? newEnd + : end; + } + /** + * Checks if 'candidate' argument is a legal separator in the list that contains 'node' as an element + */ + function isSeparator(node, candidate) { + return !!candidate && !!node.parent && (candidate.kind === 27 /* CommaToken */ || (candidate.kind === 26 /* SemicolonToken */ && node.parent.kind === 188 /* ObjectLiteralExpression */)); + } + function spaces(count) { + var s = ""; + for (var i = 0; i < count; i++) { + s += " "; + } + return s; + } + var ChangeTracker = /** @class */ (function () { + /** Public for tests only. Other callers should use `ChangeTracker.with`. */ + function ChangeTracker(newLineCharacter, formatContext) { + this.newLineCharacter = newLineCharacter; + this.formatContext = formatContext; + this.changes = []; + this.newFiles = []; + this.classesWithNodesInsertedAtStart = ts.createMap(); // Set implemented as Map + this.deletedNodes = []; + } + ChangeTracker.fromContext = function (context) { + return new ChangeTracker(ts.getNewLineOrDefaultFromHost(context.host, context.formatContext.options), context.formatContext); + }; + ChangeTracker.with = function (context, cb) { + var tracker = ChangeTracker.fromContext(context); + cb(tracker); + return tracker.getChanges(); + }; + ChangeTracker.prototype.deleteRange = function (sourceFile, range) { + this.changes.push({ kind: ChangeKind.Remove, sourceFile: sourceFile, range: range }); + }; + ChangeTracker.prototype.delete = function (sourceFile, node) { + this.deletedNodes.push({ sourceFile: sourceFile, node: node }); + }; + ChangeTracker.prototype.deleteModifier = function (sourceFile, modifier) { + this.deleteRange(sourceFile, { pos: modifier.getStart(sourceFile), end: ts.skipTrivia(sourceFile.text, modifier.end, /*stopAfterLineBreak*/ true) }); + }; + ChangeTracker.prototype.deleteNodeRange = function (sourceFile, startNode, endNode, options) { + if (options === void 0) { options = {}; } + var startPosition = getAdjustedStartPosition(sourceFile, startNode, options, Position.FullStart); + var endPosition = getAdjustedEndPosition(sourceFile, endNode, options); + this.deleteRange(sourceFile, { pos: startPosition, end: endPosition }); + }; + ChangeTracker.prototype.deleteNodeRangeExcludingEnd = function (sourceFile, startNode, afterEndNode, options) { + if (options === void 0) { options = {}; } + var startPosition = getAdjustedStartPosition(sourceFile, startNode, options, Position.FullStart); + var endPosition = afterEndNode === undefined ? sourceFile.text.length : getAdjustedStartPosition(sourceFile, afterEndNode, options, Position.FullStart); + this.deleteRange(sourceFile, { pos: startPosition, end: endPosition }); + }; + ChangeTracker.prototype.replaceRange = function (sourceFile, range, newNode, options) { + if (options === void 0) { options = {}; } + this.changes.push({ kind: ChangeKind.ReplaceWithSingleNode, sourceFile: sourceFile, range: range, options: options, node: newNode }); + }; + ChangeTracker.prototype.replaceNode = function (sourceFile, oldNode, newNode, options) { + if (options === void 0) { options = textChanges_3.useNonAdjustedPositions; } + this.replaceRange(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, options), newNode, options); + }; + ChangeTracker.prototype.replaceNodeRange = function (sourceFile, startNode, endNode, newNode, options) { + if (options === void 0) { options = textChanges_3.useNonAdjustedPositions; } + this.replaceRange(sourceFile, getAdjustedRange(sourceFile, startNode, endNode, options), newNode, options); + }; + ChangeTracker.prototype.replaceRangeWithNodes = function (sourceFile, range, newNodes, options) { + if (options === void 0) { options = {}; } + this.changes.push({ kind: ChangeKind.ReplaceWithMultipleNodes, sourceFile: sourceFile, range: range, options: options, nodes: newNodes }); + }; + ChangeTracker.prototype.replaceNodeWithNodes = function (sourceFile, oldNode, newNodes, options) { + if (options === void 0) { options = textChanges_3.useNonAdjustedPositions; } + this.replaceRangeWithNodes(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, options), newNodes, options); + }; + ChangeTracker.prototype.replaceNodeWithText = function (sourceFile, oldNode, text) { + this.replaceRangeWithText(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, textChanges_3.useNonAdjustedPositions), text); + }; + ChangeTracker.prototype.replaceNodeRangeWithNodes = function (sourceFile, startNode, endNode, newNodes, options) { + if (options === void 0) { options = textChanges_3.useNonAdjustedPositions; } + this.replaceRangeWithNodes(sourceFile, getAdjustedRange(sourceFile, startNode, endNode, options), newNodes, options); + }; + ChangeTracker.prototype.nextCommaToken = function (sourceFile, node) { + var next = ts.findNextToken(node, node.parent, sourceFile); + return next && next.kind === 27 /* CommaToken */ ? next : undefined; + }; + ChangeTracker.prototype.replacePropertyAssignment = function (sourceFile, oldNode, newNode) { + var suffix = this.nextCommaToken(sourceFile, oldNode) ? "" : ("," + this.newLineCharacter); + this.replaceNode(sourceFile, oldNode, newNode, { suffix: suffix }); + }; + ChangeTracker.prototype.insertNodeAt = function (sourceFile, pos, newNode, options) { + if (options === void 0) { options = {}; } + this.replaceRange(sourceFile, ts.createRange(pos), newNode, options); + }; + ChangeTracker.prototype.insertNodesAt = function (sourceFile, pos, newNodes, options) { + if (options === void 0) { options = {}; } + this.replaceRangeWithNodes(sourceFile, ts.createRange(pos), newNodes, options); + }; + ChangeTracker.prototype.insertNodeAtTopOfFile = function (sourceFile, newNode, blankLineBetween) { + var pos = getInsertionPositionAtSourceFileTop(sourceFile); + this.insertNodeAt(sourceFile, pos, newNode, { + prefix: pos === 0 ? undefined : this.newLineCharacter, + suffix: (ts.isLineBreak(sourceFile.text.charCodeAt(pos)) ? "" : this.newLineCharacter) + (blankLineBetween ? this.newLineCharacter : ""), + }); + }; + ChangeTracker.prototype.insertNodeBefore = function (sourceFile, before, newNode, blankLineBetween) { + if (blankLineBetween === void 0) { blankLineBetween = false; } + this.insertNodeAt(sourceFile, getAdjustedStartPosition(sourceFile, before, {}, Position.Start), newNode, this.getOptionsForInsertNodeBefore(before, blankLineBetween)); + }; + ChangeTracker.prototype.insertModifierBefore = function (sourceFile, modifier, before) { + var pos = before.getStart(sourceFile); + this.insertNodeAt(sourceFile, pos, ts.createToken(modifier), { suffix: " " }); + }; + ChangeTracker.prototype.insertLastModifierBefore = function (sourceFile, modifier, before) { + if (!before.modifiers) { + this.insertModifierBefore(sourceFile, modifier, before); + return; + } + var pos = before.modifiers.end; + this.insertNodeAt(sourceFile, pos, ts.createToken(modifier), { prefix: " " }); + }; + ChangeTracker.prototype.insertCommentBeforeLine = function (sourceFile, lineNumber, position, commentText) { + var lineStartPosition = ts.getStartPositionOfLine(lineNumber, sourceFile); + var startPosition = ts.getFirstNonSpaceCharacterPosition(sourceFile.text, lineStartPosition); + // First try to see if we can put the comment on the previous line. + // We need to make sure that we are not in the middle of a string literal or a comment. + // If so, we do not want to separate the node from its comment if we can. + // Otherwise, add an extra new line immediately before the error span. + var insertAtLineStart = isValidLocationToAddComment(sourceFile, startPosition); + var token = ts.getTouchingToken(sourceFile, insertAtLineStart ? startPosition : position); + var indent = sourceFile.text.slice(lineStartPosition, startPosition); + var text = (insertAtLineStart ? "" : this.newLineCharacter) + "//" + commentText + this.newLineCharacter + indent; + this.insertText(sourceFile, token.getStart(sourceFile), text); + }; + ChangeTracker.prototype.insertJsdocCommentBefore = function (sourceFile, node, tag) { + var fnStart = node.getStart(sourceFile); + if (node.jsDoc) { + for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { + var jsdoc = _a[_i]; + this.deleteRange(sourceFile, { + pos: ts.getLineStartPositionForPosition(jsdoc.getStart(sourceFile), sourceFile), + end: getAdjustedEndPosition(sourceFile, jsdoc, /*options*/ {}) + }); + } + } + var startPosition = ts.getPrecedingNonSpaceCharacterPosition(sourceFile.text, fnStart - 1); + var indent = sourceFile.text.slice(startPosition, fnStart); + this.insertNodeAt(sourceFile, fnStart, tag, { preserveLeadingWhitespace: false, suffix: this.newLineCharacter + indent }); + }; + ChangeTracker.prototype.replaceRangeWithText = function (sourceFile, range, text) { + this.changes.push({ kind: ChangeKind.Text, sourceFile: sourceFile, range: range, text: text }); + }; + ChangeTracker.prototype.insertText = function (sourceFile, pos, text) { + this.replaceRangeWithText(sourceFile, ts.createRange(pos), text); + }; + /** Prefer this over replacing a node with another that has a type annotation, as it avoids reformatting the other parts of the node. */ + ChangeTracker.prototype.tryInsertTypeAnnotation = function (sourceFile, node, type) { + var endNode; + if (ts.isFunctionLike(node)) { + endNode = ts.findChildOfKind(node, 21 /* CloseParenToken */, sourceFile); + if (!endNode) { + if (!ts.isArrowFunction(node)) + return; // Function missing parentheses, give up + // If no `)`, is an arrow function `x => x`, so use the end of the first parameter + endNode = ts.first(node.parameters); + } + } + else { + endNode = node.kind !== 237 /* VariableDeclaration */ && node.questionToken ? node.questionToken : node.name; + } + this.insertNodeAt(sourceFile, endNode.end, type, { prefix: ": " }); + }; + ChangeTracker.prototype.insertTypeParameters = function (sourceFile, node, typeParameters) { + // If no `(`, is an arrow function `x => x`, so use the pos of the first parameter + var start = (ts.findChildOfKind(node, 20 /* OpenParenToken */, sourceFile) || ts.first(node.parameters)).getStart(sourceFile); + this.insertNodesAt(sourceFile, start, typeParameters, { prefix: "<", suffix: ">" }); + }; + ChangeTracker.prototype.getOptionsForInsertNodeBefore = function (before, doubleNewlines) { + if (ts.isStatement(before) || ts.isClassElement(before)) { + return { suffix: doubleNewlines ? this.newLineCharacter + this.newLineCharacter : this.newLineCharacter }; + } + else if (ts.isVariableDeclaration(before)) { // insert `x = 1, ` into `const x = 1, y = 2; + return { suffix: ", " }; + } + else if (ts.isParameter(before)) { + return {}; + } + else if (ts.isStringLiteral(before) && ts.isImportDeclaration(before.parent) || ts.isNamedImports(before)) { + return { suffix: ", " }; + } + return ts.Debug.failBadSyntaxKind(before); // We haven't handled this kind of node yet -- add it + }; + ChangeTracker.prototype.insertNodeAtConstructorStart = function (sourceFile, ctr, newStatement) { + var firstStatement = ts.firstOrUndefined(ctr.body.statements); + if (!firstStatement || !ctr.body.multiLine) { + this.replaceConstructorBody(sourceFile, ctr, [newStatement].concat(ctr.body.statements)); + } + else { + this.insertNodeBefore(sourceFile, firstStatement, newStatement); + } + }; + ChangeTracker.prototype.insertNodeAtConstructorEnd = function (sourceFile, ctr, newStatement) { + var lastStatement = ts.lastOrUndefined(ctr.body.statements); + if (!lastStatement || !ctr.body.multiLine) { + this.replaceConstructorBody(sourceFile, ctr, ctr.body.statements.concat([newStatement])); + } + else { + this.insertNodeAfter(sourceFile, lastStatement, newStatement); + } + }; + ChangeTracker.prototype.replaceConstructorBody = function (sourceFile, ctr, statements) { + this.replaceNode(sourceFile, ctr.body, ts.createBlock(statements, /*multiLine*/ true)); + }; + ChangeTracker.prototype.insertNodeAtEndOfScope = function (sourceFile, scope, newNode) { + var pos = getAdjustedStartPosition(sourceFile, scope.getLastToken(), {}, Position.Start); + this.insertNodeAt(sourceFile, pos, newNode, { + prefix: ts.isLineBreak(sourceFile.text.charCodeAt(scope.getLastToken().pos)) ? this.newLineCharacter : this.newLineCharacter + this.newLineCharacter, + suffix: this.newLineCharacter + }); + }; + ChangeTracker.prototype.insertNodeAtClassStart = function (sourceFile, cls, newElement) { + this.insertNodeAtStartWorker(sourceFile, cls, newElement); + }; + ChangeTracker.prototype.insertNodeAtObjectStart = function (sourceFile, obj, newElement) { + this.insertNodeAtStartWorker(sourceFile, obj, newElement); + }; + ChangeTracker.prototype.insertNodeAtStartWorker = function (sourceFile, cls, newElement) { + var clsStart = cls.getStart(sourceFile); + var indentation = ts.formatting.SmartIndenter.findFirstNonWhitespaceColumn(ts.getLineStartPositionForPosition(clsStart, sourceFile), clsStart, sourceFile, this.formatContext.options) + + this.formatContext.options.indentSize; + this.insertNodeAt(sourceFile, getMembersOrProperties(cls).pos, newElement, __assign({ indentation: indentation }, this.getInsertNodeAtStartPrefixSuffix(sourceFile, cls))); + }; + ChangeTracker.prototype.getInsertNodeAtStartPrefixSuffix = function (sourceFile, cls) { + var comma = ts.isObjectLiteralExpression(cls) ? "," : ""; + if (getMembersOrProperties(cls).length === 0) { + if (ts.addToSeen(this.classesWithNodesInsertedAtStart, ts.getNodeId(cls), { node: cls, sourceFile: sourceFile })) { + // For `class C {\n}`, don't add the trailing "\n" + var shouldSuffix = ts.positionsAreOnSameLine.apply(void 0, getClassOrObjectBraceEnds(cls, sourceFile).concat([sourceFile])); // TODO: GH#4130 remove 'as any' + return { prefix: this.newLineCharacter, suffix: comma + (shouldSuffix ? this.newLineCharacter : "") }; + } + else { + return { prefix: "", suffix: comma + this.newLineCharacter }; + } + } + else { + return { prefix: this.newLineCharacter, suffix: comma }; + } + }; + ChangeTracker.prototype.insertNodeAfterComma = function (sourceFile, after, newNode) { + var endPosition = this.insertNodeAfterWorker(sourceFile, this.nextCommaToken(sourceFile, after) || after, newNode); + this.insertNodeAt(sourceFile, endPosition, newNode, this.getInsertNodeAfterOptions(sourceFile, after)); + }; + ChangeTracker.prototype.insertNodeAfter = function (sourceFile, after, newNode) { + var endPosition = this.insertNodeAfterWorker(sourceFile, after, newNode); + this.insertNodeAt(sourceFile, endPosition, newNode, this.getInsertNodeAfterOptions(sourceFile, after)); + }; + ChangeTracker.prototype.insertNodeAtEndOfList = function (sourceFile, list, newNode) { + this.insertNodeAt(sourceFile, list.end, newNode, { prefix: ", " }); + }; + ChangeTracker.prototype.insertNodesAfter = function (sourceFile, after, newNodes) { + var endPosition = this.insertNodeAfterWorker(sourceFile, after, ts.first(newNodes)); + this.insertNodesAt(sourceFile, endPosition, newNodes, this.getInsertNodeAfterOptions(sourceFile, after)); + }; + ChangeTracker.prototype.insertNodeAfterWorker = function (sourceFile, after, newNode) { + if (needSemicolonBetween(after, newNode)) { + // check if previous statement ends with semicolon + // if not - insert semicolon to preserve the code from changing the meaning due to ASI + if (sourceFile.text.charCodeAt(after.end - 1) !== 59 /* semicolon */) { + this.replaceRange(sourceFile, ts.createRange(after.end), ts.createToken(26 /* SemicolonToken */)); + } + } + var endPosition = getAdjustedEndPosition(sourceFile, after, {}); + return endPosition; + }; + ChangeTracker.prototype.getInsertNodeAfterOptions = function (sourceFile, after) { + var options = this.getInsertNodeAfterOptionsWorker(after); + return __assign({}, options, { prefix: after.end === sourceFile.end && ts.isStatement(after) ? (options.prefix ? "\n" + options.prefix : "\n") : options.prefix }); + }; + ChangeTracker.prototype.getInsertNodeAfterOptionsWorker = function (node) { + switch (node.kind) { + case 240 /* ClassDeclaration */: + case 244 /* ModuleDeclaration */: + return { prefix: this.newLineCharacter, suffix: this.newLineCharacter }; + case 237 /* VariableDeclaration */: + case 10 /* StringLiteral */: + case 72 /* Identifier */: + return { prefix: ", " }; + case 275 /* PropertyAssignment */: + return { suffix: "," + this.newLineCharacter }; + case 85 /* ExportKeyword */: + return { prefix: " " }; + case 151 /* Parameter */: + return {}; + default: + ts.Debug.assert(ts.isStatement(node) || ts.isClassOrTypeElement(node)); // Else we haven't handled this kind of node yet -- add it + return { suffix: this.newLineCharacter }; + } + }; + ChangeTracker.prototype.insertName = function (sourceFile, node, name) { + ts.Debug.assert(!node.name); + if (node.kind === 197 /* ArrowFunction */) { + var arrow = ts.findChildOfKind(node, 37 /* EqualsGreaterThanToken */, sourceFile); + var lparen = ts.findChildOfKind(node, 20 /* OpenParenToken */, sourceFile); + if (lparen) { + // `() => {}` --> `function f() {}` + this.insertNodesAt(sourceFile, lparen.getStart(sourceFile), [ts.createToken(90 /* FunctionKeyword */), ts.createIdentifier(name)], { joiner: " " }); + deleteNode(this, sourceFile, arrow); + } + else { + // `x => {}` -> `function f(x) {}` + this.insertText(sourceFile, ts.first(node.parameters).getStart(sourceFile), "function " + name + "("); + // Replacing full range of arrow to get rid of the leading space -- replace ` =>` with `)` + this.replaceRange(sourceFile, arrow, ts.createToken(21 /* CloseParenToken */)); + } + if (node.body.kind !== 218 /* Block */) { + // `() => 0` => `function f() { return 0; }` + this.insertNodesAt(sourceFile, node.body.getStart(sourceFile), [ts.createToken(18 /* OpenBraceToken */), ts.createToken(97 /* ReturnKeyword */)], { joiner: " ", suffix: " " }); + this.insertNodesAt(sourceFile, node.body.end, [ts.createToken(26 /* SemicolonToken */), ts.createToken(19 /* CloseBraceToken */)], { joiner: " " }); + } + } + else { + var pos = ts.findChildOfKind(node, node.kind === 196 /* FunctionExpression */ ? 90 /* FunctionKeyword */ : 76 /* ClassKeyword */, sourceFile).end; + this.insertNodeAt(sourceFile, pos, ts.createIdentifier(name), { prefix: " " }); + } + }; + ChangeTracker.prototype.insertExportModifier = function (sourceFile, node) { + this.insertText(sourceFile, node.getStart(sourceFile), "export "); + }; + /** + * This function should be used to insert nodes in lists when nodes don't carry separators as the part of the node range, + * i.e. arguments in arguments lists, parameters in parameter lists etc. + * Note that separators are part of the node in statements and class elements. + */ + ChangeTracker.prototype.insertNodeInListAfter = function (sourceFile, after, newNode, containingList) { + if (containingList === void 0) { containingList = ts.formatting.SmartIndenter.getContainingList(after, sourceFile); } + if (!containingList) { + ts.Debug.fail("node is not a list element"); + return; + } + var index = ts.indexOfNode(containingList, after); + if (index < 0) { + return; + } + var end = after.getEnd(); + if (index !== containingList.length - 1) { + // any element except the last one + // use next sibling as an anchor + var nextToken = ts.getTokenAtPosition(sourceFile, after.end); + if (nextToken && isSeparator(after, nextToken)) { + // for list + // a, b, c + // create change for adding 'e' after 'a' as + // - find start of next element after a (it is b) + // - use this start as start and end position in final change + // - build text of change by formatting the text of node + separator + whitespace trivia of b + // in multiline case it will work as + // a, + // b, + // c, + // result - '*' denotes leading trivia that will be inserted after new text (displayed as '#') + // a,* + // ***insertedtext# + // ###b, + // c, + // find line and character of the next element + var lineAndCharOfNextElement = ts.getLineAndCharacterOfPosition(sourceFile, skipWhitespacesAndLineBreaks(sourceFile.text, containingList[index + 1].getFullStart())); + // find line and character of the token that precedes next element (usually it is separator) + var lineAndCharOfNextToken = ts.getLineAndCharacterOfPosition(sourceFile, nextToken.end); + var prefix = void 0; + var startPos = void 0; + if (lineAndCharOfNextToken.line === lineAndCharOfNextElement.line) { + // next element is located on the same line with separator: + // a,$$$$b + // ^ ^ + // | |-next element + // |-separator + // where $$$ is some leading trivia + // for a newly inserted node we'll maintain the same relative position comparing to separator and replace leading trivia with spaces + // a, x,$$$$b + // ^ ^ ^ + // | | |-next element + // | |-new inserted node padded with spaces + // |-separator + startPos = nextToken.end; + prefix = spaces(lineAndCharOfNextElement.character - lineAndCharOfNextToken.character); + } + else { + // next element is located on different line that separator + // let insert position be the beginning of the line that contains next element + startPos = ts.getStartPositionOfLine(lineAndCharOfNextElement.line, sourceFile); + } + // write separator and leading trivia of the next element as suffix + var suffix = "" + ts.tokenToString(nextToken.kind) + sourceFile.text.substring(nextToken.end, containingList[index + 1].getStart(sourceFile)); + this.replaceRange(sourceFile, ts.createRange(startPos, containingList[index + 1].getStart(sourceFile)), newNode, { prefix: prefix, suffix: suffix }); + } + } + else { + var afterStart = after.getStart(sourceFile); + var afterStartLinePosition = ts.getLineStartPositionForPosition(afterStart, sourceFile); + var separator = void 0; + var multilineList = false; + // insert element after the last element in the list that has more than one item + // pick the element preceding the after element to: + // - pick the separator + // - determine if list is a multiline + if (containingList.length === 1) { + // if list has only one element then we'll format is as multiline if node has comment in trailing trivia, or as singleline otherwise + // i.e. var x = 1 // this is x + // | new element will be inserted at this position + separator = 27 /* CommaToken */; + } + else { + // element has more than one element, pick separator from the list + var tokenBeforeInsertPosition = ts.findPrecedingToken(after.pos, sourceFile); + separator = isSeparator(after, tokenBeforeInsertPosition) ? tokenBeforeInsertPosition.kind : 27 /* CommaToken */; + // determine if list is multiline by checking lines of after element and element that precedes it. + var afterMinusOneStartLinePosition = ts.getLineStartPositionForPosition(containingList[index - 1].getStart(sourceFile), sourceFile); + multilineList = afterMinusOneStartLinePosition !== afterStartLinePosition; + } + if (hasCommentsBeforeLineBreak(sourceFile.text, after.end)) { + // in this case we'll always treat containing list as multiline + multilineList = true; + } + if (multilineList) { + // insert separator immediately following the 'after' node to preserve comments in trailing trivia + this.replaceRange(sourceFile, ts.createRange(end), ts.createToken(separator)); + // use the same indentation as 'after' item + var indentation = ts.formatting.SmartIndenter.findFirstNonWhitespaceColumn(afterStartLinePosition, afterStart, sourceFile, this.formatContext.options); + // insert element before the line break on the line that contains 'after' element + var insertPos = ts.skipTrivia(sourceFile.text, end, /*stopAfterLineBreak*/ true, /*stopAtComments*/ false); + if (insertPos !== end && ts.isLineBreak(sourceFile.text.charCodeAt(insertPos - 1))) { + insertPos--; + } + this.replaceRange(sourceFile, ts.createRange(insertPos), newNode, { indentation: indentation, prefix: this.newLineCharacter }); + } + else { + this.replaceRange(sourceFile, ts.createRange(end), newNode, { prefix: ts.tokenToString(separator) + " " }); + } + } + }; + ChangeTracker.prototype.finishClassesWithNodesInsertedAtStart = function () { + var _this = this; + this.classesWithNodesInsertedAtStart.forEach(function (_a) { + var node = _a.node, sourceFile = _a.sourceFile; + var _b = getClassOrObjectBraceEnds(node, sourceFile), openBraceEnd = _b[0], closeBraceEnd = _b[1]; + // For `class C { }` remove the whitespace inside the braces. + if (ts.positionsAreOnSameLine(openBraceEnd, closeBraceEnd, sourceFile) && openBraceEnd !== closeBraceEnd - 1) { + _this.deleteRange(sourceFile, ts.createRange(openBraceEnd, closeBraceEnd - 1)); + } + }); + }; + ChangeTracker.prototype.finishDeleteDeclarations = function () { + var _this = this; + var deletedNodesInLists = new ts.NodeSet(); // Stores nodes in lists that we already deleted. Used to avoid deleting `, ` twice in `a, b`. + var _loop_8 = function (sourceFile, node) { + if (!this_1.deletedNodes.some(function (d) { return d.sourceFile === sourceFile && ts.rangeContainsRangeExclusive(d.node, node); })) { + if (ts.isArray(node)) { + this_1.deleteRange(sourceFile, ts.rangeOfTypeParameters(node)); + } + else { + deleteDeclaration.deleteDeclaration(this_1, deletedNodesInLists, sourceFile, node); + } + } + }; + var this_1 = this; + for (var _i = 0, _a = this.deletedNodes; _i < _a.length; _i++) { + var _b = _a[_i], sourceFile = _b.sourceFile, node = _b.node; + _loop_8(sourceFile, node); + } + deletedNodesInLists.forEach(function (node) { + var sourceFile = node.getSourceFile(); + var list = ts.formatting.SmartIndenter.getContainingList(node, sourceFile); + if (node !== ts.last(list)) + return; + var lastNonDeletedIndex = ts.findLastIndex(list, function (n) { return !deletedNodesInLists.has(n); }, list.length - 2); + if (lastNonDeletedIndex !== -1) { + _this.deleteRange(sourceFile, { pos: list[lastNonDeletedIndex].end, end: startPositionToDeleteNodeInList(sourceFile, list[lastNonDeletedIndex + 1]) }); + } + }); + }; + /** + * Note: after calling this, the TextChanges object must be discarded! + * @param validate only for tests + * The reason we must validate as part of this method is that `getNonFormattedText` changes the node's positions, + * so we can only call this once and can't get the non-formatted text separately. + */ + ChangeTracker.prototype.getChanges = function (validate) { + this.finishDeleteDeclarations(); + this.finishClassesWithNodesInsertedAtStart(); + var changes = changesToText.getTextChangesFromChanges(this.changes, this.newLineCharacter, this.formatContext, validate); + for (var _i = 0, _a = this.newFiles; _i < _a.length; _i++) { + var _b = _a[_i], oldFile = _b.oldFile, fileName = _b.fileName, statements = _b.statements; + changes.push(changesToText.newFileChanges(oldFile, fileName, statements, this.newLineCharacter, this.formatContext)); + } + return changes; + }; + ChangeTracker.prototype.createNewFile = function (oldFile, fileName, statements) { + this.newFiles.push({ oldFile: oldFile, fileName: fileName, statements: statements }); + }; + return ChangeTracker; + }()); + textChanges_3.ChangeTracker = ChangeTracker; + // find first non-whitespace position in the leading trivia of the node + function startPositionToDeleteNodeInList(sourceFile, node) { + return ts.skipTrivia(sourceFile.text, getAdjustedStartPosition(sourceFile, node, {}, Position.FullStart), /*stopAfterLineBreak*/ false, /*stopAtComments*/ true); + } + function getClassOrObjectBraceEnds(cls, sourceFile) { + return [ts.findChildOfKind(cls, 18 /* OpenBraceToken */, sourceFile).end, ts.findChildOfKind(cls, 19 /* CloseBraceToken */, sourceFile).end]; + } + function getMembersOrProperties(cls) { + return ts.isObjectLiteralExpression(cls) ? cls.properties : cls.members; + } + function getNewFileText(statements, scriptKind, newLineCharacter, formatContext) { + return changesToText.newFileChangesWorker(/*oldFile*/ undefined, scriptKind, statements, newLineCharacter, formatContext); + } + textChanges_3.getNewFileText = getNewFileText; + var changesToText; + (function (changesToText) { + function getTextChangesFromChanges(changes, newLineCharacter, formatContext, validate) { + return ts.group(changes, function (c) { return c.sourceFile.path; }).map(function (changesInFile) { + var sourceFile = changesInFile[0].sourceFile; + // order changes by start position + // If the start position is the same, put the shorter range first, since an empty range (x, x) may precede (x, y) but not vice-versa. + var normalized = ts.stableSort(changesInFile, function (a, b) { return (a.range.pos - b.range.pos) || (a.range.end - b.range.end); }); + var _loop_9 = function (i) { + ts.Debug.assert(normalized[i].range.end <= normalized[i + 1].range.pos, "Changes overlap", function () { + return JSON.stringify(normalized[i].range) + " and " + JSON.stringify(normalized[i + 1].range); + }); + }; + // verify that change intervals do not overlap, except possibly at end points. + for (var i = 0; i < normalized.length - 1; i++) { + _loop_9(i); + } + var textChanges = normalized.map(function (c) { + return ts.createTextChange(ts.createTextSpanFromRange(c.range), computeNewText(c, sourceFile, newLineCharacter, formatContext, validate)); + }); + return { fileName: sourceFile.fileName, textChanges: textChanges }; + }); + } + changesToText.getTextChangesFromChanges = getTextChangesFromChanges; + function newFileChanges(oldFile, fileName, statements, newLineCharacter, formatContext) { + var text = newFileChangesWorker(oldFile, ts.getScriptKindFromFileName(fileName), statements, newLineCharacter, formatContext); + return { fileName: fileName, textChanges: [ts.createTextChange(ts.createTextSpan(0, 0), text)], isNewFile: true }; + } + changesToText.newFileChanges = newFileChanges; + function newFileChangesWorker(oldFile, scriptKind, statements, newLineCharacter, formatContext) { + // TODO: this emits the file, parses it back, then formats it that -- may be a less roundabout way to do this + var nonFormattedText = statements.map(function (s) { return getNonformattedText(s, oldFile, newLineCharacter).text; }).join(newLineCharacter); + var sourceFile = ts.createSourceFile("any file name", nonFormattedText, 6 /* ESNext */, /*setParentNodes*/ true, scriptKind); + var changes = ts.formatting.formatDocument(sourceFile, formatContext); + return applyChanges(nonFormattedText, changes) + newLineCharacter; + } + changesToText.newFileChangesWorker = newFileChangesWorker; + function computeNewText(change, sourceFile, newLineCharacter, formatContext, validate) { + if (change.kind === ChangeKind.Remove) { + return ""; + } + if (change.kind === ChangeKind.Text) { + return change.text; + } + var _a = change.options, options = _a === void 0 ? {} : _a, pos = change.range.pos; + var format = function (n) { return getFormattedTextOfNode(n, sourceFile, pos, options, newLineCharacter, formatContext, validate); }; + var text = change.kind === ChangeKind.ReplaceWithMultipleNodes + ? change.nodes.map(function (n) { return ts.removeSuffix(format(n), newLineCharacter); }).join(change.options.joiner || newLineCharacter) // TODO: GH#18217 + : format(change.node); + // strip initial indentation (spaces or tabs) if text will be inserted in the middle of the line + var noIndent = (options.preserveLeadingWhitespace || options.indentation !== undefined || ts.getLineStartPositionForPosition(pos, sourceFile) === pos) ? text : text.replace(/^\s+/, ""); + return (options.prefix || "") + noIndent + (options.suffix || ""); + } + /** Note: this may mutate `nodeIn`. */ + function getFormattedTextOfNode(nodeIn, sourceFile, pos, _a, newLineCharacter, formatContext, validate) { + var indentation = _a.indentation, prefix = _a.prefix, delta = _a.delta; + var _b = getNonformattedText(nodeIn, sourceFile, newLineCharacter), node = _b.node, text = _b.text; + if (validate) + validate(node, text); + var formatOptions = formatContext.options; + var initialIndentation = indentation !== undefined + ? indentation + : ts.formatting.SmartIndenter.getIndentation(pos, sourceFile, formatOptions, prefix === newLineCharacter || ts.getLineStartPositionForPosition(pos, sourceFile) === pos); + if (delta === undefined) { + delta = ts.formatting.SmartIndenter.shouldIndentChildNode(formatContext.options, nodeIn) ? (formatOptions.indentSize || 0) : 0; + } + var file = { text: text, getLineAndCharacterOfPosition: function (pos) { return ts.getLineAndCharacterOfPosition(this, pos); } }; + var changes = ts.formatting.formatNodeGivenIndentation(node, file, sourceFile.languageVariant, initialIndentation, delta, formatContext); + return applyChanges(text, changes); + } + /** Note: output node may be mutated input node. */ + function getNonformattedText(node, sourceFile, newLineCharacter) { + var writer = new Writer(newLineCharacter); + var newLine = newLineCharacter === "\n" ? 1 /* LineFeed */ : 0 /* CarriageReturnLineFeed */; + ts.createPrinter({ newLine: newLine, neverAsciiEscape: true }, writer).writeNode(4 /* Unspecified */, node, sourceFile, writer); + return { text: writer.getText(), node: assignPositionsToNode(node) }; + } + changesToText.getNonformattedText = getNonformattedText; + })(changesToText || (changesToText = {})); + function applyChanges(text, changes) { + for (var i = changes.length - 1; i >= 0; i--) { + var _a = changes[i], span = _a.span, newText = _a.newText; + text = "" + text.substring(0, span.start) + newText + text.substring(ts.textSpanEnd(span)); + } + return text; + } + textChanges_3.applyChanges = applyChanges; + function isTrivia(s) { + return ts.skipTrivia(s, 0) === s.length; + } + function assignPositionsToNode(node) { + var visited = ts.visitEachChild(node, assignPositionsToNode, ts.nullTransformationContext, assignPositionsToNodeArray, assignPositionsToNode); // TODO: GH#18217 + // create proxy node for non synthesized nodes + var newNode = ts.nodeIsSynthesized(visited) ? visited : Object.create(visited); + newNode.pos = getPos(node); + newNode.end = getEnd(node); + return newNode; + } + function assignPositionsToNodeArray(nodes, visitor, test, start, count) { + var visited = ts.visitNodes(nodes, visitor, test, start, count); + if (!visited) { + return visited; + } + // clone nodearray if necessary + var nodeArray = visited === nodes ? ts.createNodeArray(visited.slice(0)) : visited; + nodeArray.pos = getPos(nodes); + nodeArray.end = getEnd(nodes); + return nodeArray; + } + var Writer = /** @class */ (function () { + function Writer(newLine) { + var _this = this; + this.lastNonTriviaPosition = 0; + this.writer = ts.createTextWriter(newLine); + this.onEmitNode = function (hint, node, printCallback) { + if (node) { + setPos(node, _this.lastNonTriviaPosition); + } + printCallback(hint, node); + if (node) { + setEnd(node, _this.lastNonTriviaPosition); + } + }; + this.onBeforeEmitNodeArray = function (nodes) { + if (nodes) { + setPos(nodes, _this.lastNonTriviaPosition); + } + }; + this.onAfterEmitNodeArray = function (nodes) { + if (nodes) { + setEnd(nodes, _this.lastNonTriviaPosition); + } + }; + this.onBeforeEmitToken = function (node) { + if (node) { + setPos(node, _this.lastNonTriviaPosition); + } + }; + this.onAfterEmitToken = function (node) { + if (node) { + setEnd(node, _this.lastNonTriviaPosition); + } + }; + } + Writer.prototype.setLastNonTriviaPosition = function (s, force) { + if (force || !isTrivia(s)) { + this.lastNonTriviaPosition = this.writer.getTextPos(); + var i = 0; + while (ts.isWhiteSpaceLike(s.charCodeAt(s.length - i - 1))) { + i++; + } + // trim trailing whitespaces + this.lastNonTriviaPosition -= i; + } + }; + Writer.prototype.write = function (s) { + this.writer.write(s); + this.setLastNonTriviaPosition(s, /*force*/ false); + }; + Writer.prototype.writeComment = function (s) { + this.writer.writeComment(s); + }; + Writer.prototype.writeKeyword = function (s) { + this.writer.writeKeyword(s); + this.setLastNonTriviaPosition(s, /*force*/ false); + }; + Writer.prototype.writeOperator = function (s) { + this.writer.writeOperator(s); + this.setLastNonTriviaPosition(s, /*force*/ false); + }; + Writer.prototype.writePunctuation = function (s) { + this.writer.writePunctuation(s); + this.setLastNonTriviaPosition(s, /*force*/ false); + }; + Writer.prototype.writeTrailingSemicolon = function (s) { + this.writer.writeTrailingSemicolon(s); + this.setLastNonTriviaPosition(s, /*force*/ false); + }; + Writer.prototype.writeParameter = function (s) { + this.writer.writeParameter(s); + this.setLastNonTriviaPosition(s, /*force*/ false); + }; + Writer.prototype.writeProperty = function (s) { + this.writer.writeProperty(s); + this.setLastNonTriviaPosition(s, /*force*/ false); + }; + Writer.prototype.writeSpace = function (s) { + this.writer.writeSpace(s); + this.setLastNonTriviaPosition(s, /*force*/ false); + }; + Writer.prototype.writeStringLiteral = function (s) { + this.writer.writeStringLiteral(s); + this.setLastNonTriviaPosition(s, /*force*/ false); + }; + Writer.prototype.writeSymbol = function (s, sym) { + this.writer.writeSymbol(s, sym); + this.setLastNonTriviaPosition(s, /*force*/ false); + }; + Writer.prototype.writeLine = function () { + this.writer.writeLine(); + }; + Writer.prototype.increaseIndent = function () { + this.writer.increaseIndent(); + }; + Writer.prototype.decreaseIndent = function () { + this.writer.decreaseIndent(); + }; + Writer.prototype.getText = function () { + return this.writer.getText(); + }; + Writer.prototype.rawWrite = function (s) { + this.writer.rawWrite(s); + this.setLastNonTriviaPosition(s, /*force*/ false); + }; + Writer.prototype.writeLiteral = function (s) { + this.writer.writeLiteral(s); + this.setLastNonTriviaPosition(s, /*force*/ true); + }; + Writer.prototype.getTextPos = function () { + return this.writer.getTextPos(); + }; + Writer.prototype.getLine = function () { + return this.writer.getLine(); + }; + Writer.prototype.getColumn = function () { + return this.writer.getColumn(); + }; + Writer.prototype.getIndent = function () { + return this.writer.getIndent(); + }; + Writer.prototype.isAtStartOfLine = function () { + return this.writer.isAtStartOfLine(); + }; + Writer.prototype.clear = function () { + this.writer.clear(); + this.lastNonTriviaPosition = 0; + }; + return Writer; + }()); + function getInsertionPositionAtSourceFileTop(sourceFile) { + var lastPrologue; + for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { + var node = _a[_i]; + if (ts.isPrologueDirective(node)) { + lastPrologue = node; + } + else { + break; + } + } + var position = 0; + var text = sourceFile.text; + if (lastPrologue) { + position = lastPrologue.end; + advancePastLineBreak(); + return position; + } + var shebang = ts.getShebang(text); + if (shebang !== undefined) { + position = shebang.length; + advancePastLineBreak(); + } + // For a source file, it is possible there are detached comments we should not skip + var ranges = ts.getLeadingCommentRanges(text, position); + if (!ranges) + return position; + // However we should still skip a pinned comment at the top + if (ranges.length && ranges[0].kind === 3 /* MultiLineCommentTrivia */ && ts.isPinnedComment(text, ranges[0].pos)) { + position = ranges[0].end; + advancePastLineBreak(); + ranges = ranges.slice(1); + } + // As well as any triple slash references + for (var _b = 0, ranges_1 = ranges; _b < ranges_1.length; _b++) { + var range = ranges_1[_b]; + if (range.kind === 2 /* SingleLineCommentTrivia */ && ts.isRecognizedTripleSlashComment(text, range.pos, range.end)) { + position = range.end; + advancePastLineBreak(); + continue; + } + break; + } + return position; + function advancePastLineBreak() { + if (position < text.length) { + var charCode = text.charCodeAt(position); + if (ts.isLineBreak(charCode)) { + position++; + if (position < text.length && charCode === 13 /* carriageReturn */ && text.charCodeAt(position) === 10 /* lineFeed */) { + position++; + } + } + } + } + } + function isValidLocationToAddComment(sourceFile, position) { + return !ts.isInComment(sourceFile, position) && !ts.isInString(sourceFile, position) && !ts.isInTemplateString(sourceFile, position) && !ts.isInJSXText(sourceFile, position); + } + textChanges_3.isValidLocationToAddComment = isValidLocationToAddComment; + function needSemicolonBetween(a, b) { + return (ts.isPropertySignature(a) || ts.isPropertyDeclaration(a)) && ts.isClassOrTypeElement(b) && b.name.kind === 149 /* ComputedPropertyName */ + || ts.isStatementButNotDeclaration(a) && ts.isStatementButNotDeclaration(b); // TODO: only if b would start with a `(` or `[` + } + var deleteDeclaration; + (function (deleteDeclaration_1) { + function deleteDeclaration(changes, deletedNodesInLists, sourceFile, node) { + switch (node.kind) { + case 151 /* Parameter */: { + var oldFunction = node.parent; + if (ts.isArrowFunction(oldFunction) && + oldFunction.parameters.length === 1 && + !ts.findChildOfKind(oldFunction, 20 /* OpenParenToken */, sourceFile)) { + // Lambdas with exactly one parameter are special because, after removal, there + // must be an empty parameter list (i.e. `()`) and this won't necessarily be the + // case if the parameter is simply removed (e.g. in `x => 1`). + changes.replaceNodeWithText(sourceFile, node, "()"); + } + else { + deleteNodeInList(changes, deletedNodesInLists, sourceFile, node); + } + break; + } + case 249 /* ImportDeclaration */: + deleteNode(changes, sourceFile, node, + // For first import, leave header comment in place + node === sourceFile.imports[0].parent ? { useNonAdjustedStartPosition: true, useNonAdjustedEndPosition: false } : undefined); + break; + case 186 /* BindingElement */: + var pattern = node.parent; + var preserveComma = pattern.kind === 185 /* ArrayBindingPattern */ && node !== ts.last(pattern.elements); + if (preserveComma) { + deleteNode(changes, sourceFile, node); + } + else { + deleteNodeInList(changes, deletedNodesInLists, sourceFile, node); + } + break; + case 237 /* VariableDeclaration */: + deleteVariableDeclaration(changes, deletedNodesInLists, sourceFile, node); + break; + case 150 /* TypeParameter */: + deleteNodeInList(changes, deletedNodesInLists, sourceFile, node); + break; + case 253 /* ImportSpecifier */: + var namedImports = node.parent; + if (namedImports.elements.length === 1) { + deleteImportBinding(changes, sourceFile, namedImports); + } + else { + deleteNodeInList(changes, deletedNodesInLists, sourceFile, node); + } + break; + case 251 /* NamespaceImport */: + deleteImportBinding(changes, sourceFile, node); + break; + default: + if (ts.isImportClause(node.parent) && node.parent.name === node) { + deleteDefaultImport(changes, sourceFile, node.parent); + } + else if (ts.isCallLikeExpression(node.parent)) { + deleteNodeInList(changes, deletedNodesInLists, sourceFile, node); + } + else { + deleteNode(changes, sourceFile, node, node.kind === 26 /* SemicolonToken */ ? { useNonAdjustedEndPosition: true } : undefined); + } + } + } + deleteDeclaration_1.deleteDeclaration = deleteDeclaration; + function deleteDefaultImport(changes, sourceFile, importClause) { + if (!importClause.namedBindings) { + // Delete the whole import + deleteNode(changes, sourceFile, importClause.parent); + } + else { + // import |d,| * as ns from './file' + var start = importClause.name.getStart(sourceFile); + var nextToken = ts.getTokenAtPosition(sourceFile, importClause.name.end); + if (nextToken && nextToken.kind === 27 /* CommaToken */) { + // shift first non-whitespace position after comma to the start position of the node + var end = ts.skipTrivia(sourceFile.text, nextToken.end, /*stopAfterLineBreaks*/ false, /*stopAtComments*/ true); + changes.deleteRange(sourceFile, { pos: start, end: end }); + } + else { + deleteNode(changes, sourceFile, importClause.name); + } + } + } + function deleteImportBinding(changes, sourceFile, node) { + if (node.parent.name) { + // Delete named imports while preserving the default import + // import d|, * as ns| from './file' + // import d|, { a }| from './file' + var previousToken = ts.Debug.assertDefined(ts.getTokenAtPosition(sourceFile, node.pos - 1)); + changes.deleteRange(sourceFile, { pos: previousToken.getStart(sourceFile), end: node.end }); + } + else { + // Delete the entire import declaration + // |import * as ns from './file'| + // |import { a } from './file'| + var importDecl = ts.getAncestor(node, 249 /* ImportDeclaration */); + deleteNode(changes, sourceFile, importDecl); + } + } + function deleteVariableDeclaration(changes, deletedNodesInLists, sourceFile, node) { + var parent = node.parent; + if (parent.kind === 274 /* CatchClause */) { + // TODO: There's currently no unused diagnostic for this, could be a suggestion + changes.deleteNodeRange(sourceFile, ts.findChildOfKind(parent, 20 /* OpenParenToken */, sourceFile), ts.findChildOfKind(parent, 21 /* CloseParenToken */, sourceFile)); + return; + } + if (parent.declarations.length !== 1) { + deleteNodeInList(changes, deletedNodesInLists, sourceFile, node); + return; + } + var gp = parent.parent; + switch (gp.kind) { + case 227 /* ForOfStatement */: + case 226 /* ForInStatement */: + changes.replaceNode(sourceFile, node, ts.createObjectLiteral()); + break; + case 225 /* ForStatement */: + deleteNode(changes, sourceFile, parent); + break; + case 219 /* VariableStatement */: + deleteNode(changes, sourceFile, gp); + break; + default: + ts.Debug.assertNever(gp); + } + } + })(deleteDeclaration || (deleteDeclaration = {})); + /** Warning: This deletes comments too. See `copyComments` in `convertFunctionToEs6Class`. */ + // Exported for tests only! (TODO: improve tests to not need this) + function deleteNode(changes, sourceFile, node, options) { + if (options === void 0) { options = {}; } + var startPosition = getAdjustedStartPosition(sourceFile, node, options, Position.FullStart); + var endPosition = getAdjustedEndPosition(sourceFile, node, options); + changes.deleteRange(sourceFile, { pos: startPosition, end: endPosition }); + } + textChanges_3.deleteNode = deleteNode; + function deleteNodeInList(changes, deletedNodesInLists, sourceFile, node) { + var containingList = ts.Debug.assertDefined(ts.formatting.SmartIndenter.getContainingList(node, sourceFile)); + var index = ts.indexOfNode(containingList, node); + ts.Debug.assert(index !== -1); + if (containingList.length === 1) { + deleteNode(changes, sourceFile, node); + return; + } + // Note: We will only delete a comma *after* a node. This will leave a trailing comma if we delete the last node. + // That's handled in the end by `finishTrailingCommaAfterDeletingNodesInList`. + ts.Debug.assert(!deletedNodesInLists.has(node), "Deleting a node twice"); + deletedNodesInLists.add(node); + changes.deleteRange(sourceFile, { + pos: startPositionToDeleteNodeInList(sourceFile, node), + end: index === containingList.length - 1 ? getAdjustedEndPosition(sourceFile, node, {}) : startPositionToDeleteNodeInList(sourceFile, containingList[index + 1]), + }); + } + })(textChanges = ts.textChanges || (ts.textChanges = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var errorCodeToFixes = ts.createMultiMap(); + var fixIdToRegistration = ts.createMap(); + function diagnosticToString(diag) { + return ts.isArray(diag) + ? ts.formatStringFromArgs(ts.getLocaleSpecificMessage(diag[0]), diag.slice(1)) + : ts.getLocaleSpecificMessage(diag); + } + function createCodeFixActionNoFixId(fixName, changes, description) { + return createCodeFixActionWorker(fixName, diagnosticToString(description), changes, /*fixId*/ undefined, /*fixAllDescription*/ undefined); + } + codefix.createCodeFixActionNoFixId = createCodeFixActionNoFixId; + function createCodeFixAction(fixName, changes, description, fixId, fixAllDescription, command) { + return createCodeFixActionWorker(fixName, diagnosticToString(description), changes, fixId, diagnosticToString(fixAllDescription), command); + } + codefix.createCodeFixAction = createCodeFixAction; + function createCodeFixActionWorker(fixName, description, changes, fixId, fixAllDescription, command) { + return { fixName: fixName, description: description, changes: changes, fixId: fixId, fixAllDescription: fixAllDescription, commands: command ? [command] : undefined }; + } + function registerCodeFix(reg) { + for (var _i = 0, _a = reg.errorCodes; _i < _a.length; _i++) { + var error = _a[_i]; + errorCodeToFixes.add(String(error), reg); + } + if (reg.fixIds) { + for (var _b = 0, _c = reg.fixIds; _b < _c.length; _b++) { + var fixId = _c[_b]; + ts.Debug.assert(!fixIdToRegistration.has(fixId)); + fixIdToRegistration.set(fixId, reg); + } + } + } + codefix.registerCodeFix = registerCodeFix; + function getSupportedErrorCodes() { + return ts.arrayFrom(errorCodeToFixes.keys()); + } + codefix.getSupportedErrorCodes = getSupportedErrorCodes; + function getFixes(context) { + return ts.flatMap(errorCodeToFixes.get(String(context.errorCode)) || ts.emptyArray, function (f) { return f.getCodeActions(context); }); + } + codefix.getFixes = getFixes; + function getAllFixes(context) { + // Currently fixId is always a string. + return fixIdToRegistration.get(ts.cast(context.fixId, ts.isString)).getAllCodeActions(context); + } + codefix.getAllFixes = getAllFixes; + function createCombinedCodeActions(changes, commands) { + return { changes: changes, commands: commands }; + } + codefix.createCombinedCodeActions = createCombinedCodeActions; + function createFileTextChanges(fileName, textChanges) { + return { fileName: fileName, textChanges: textChanges }; + } + codefix.createFileTextChanges = createFileTextChanges; + function codeFixAll(context, errorCodes, use) { + var commands = []; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return eachDiagnostic(context, errorCodes, function (diag) { return use(t, diag, commands); }); }); + return createCombinedCodeActions(changes, commands.length === 0 ? undefined : commands); + } + codefix.codeFixAll = codeFixAll; + function eachDiagnostic(_a, errorCodes, cb) { + var program = _a.program, sourceFile = _a.sourceFile, cancellationToken = _a.cancellationToken; + for (var _i = 0, _b = program.getSemanticDiagnostics(sourceFile, cancellationToken).concat(ts.computeSuggestionDiagnostics(sourceFile, program, cancellationToken)); _i < _b.length; _i++) { + var diag = _b[_i]; + if (ts.contains(errorCodes, diag.code)) { + cb(diag); + } + } + } + codefix.eachDiagnostic = eachDiagnostic; + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var refactor; + (function (refactor_1) { + // A map with the refactor code as key, the refactor itself as value + // e.g. nonSuggestableRefactors[refactorCode] -> the refactor you want + var refactors = ts.createMap(); + /** @param name An unique code associated with each refactor. Does not have to be human-readable. */ + function registerRefactor(name, refactor) { + refactors.set(name, refactor); + } + refactor_1.registerRefactor = registerRefactor; + function getApplicableRefactors(context) { + return ts.arrayFrom(ts.flatMapIterator(refactors.values(), function (refactor) { + return context.cancellationToken && context.cancellationToken.isCancellationRequested() ? undefined : refactor.getAvailableActions(context); + })); + } + refactor_1.getApplicableRefactors = getApplicableRefactors; + function getEditsForRefactor(context, refactorName, actionName) { + var refactor = refactors.get(refactorName); + return refactor && refactor.getEditsForAction(context, actionName); + } + refactor_1.getEditsForRefactor = getEditsForRefactor; + })(refactor = ts.refactor || (ts.refactor = {})); + function getRefactorContextSpan(_a) { + var startPosition = _a.startPosition, endPosition = _a.endPosition; + return ts.createTextSpanFromBounds(startPosition, endPosition === undefined ? startPosition : endPosition); + } + ts.getRefactorContextSpan = getRefactorContextSpan; +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "addConvertToUnknownForNonOverlappingTypes"; + var errorCodes = [ts.Diagnostics.Conversion_of_type_0_to_type_1_may_be_a_mistake_because_neither_type_sufficiently_overlaps_with_the_other_If_this_was_intentional_convert_the_expression_to_unknown_first.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return makeChange(t, context.sourceFile, context.span.start); }); + return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Add_unknown_conversion_for_non_overlapping_types, fixId, ts.Diagnostics.Add_unknown_to_all_conversions_of_non_overlapping_types)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { return makeChange(changes, diag.file, diag.start); }); }, + }); + function makeChange(changeTracker, sourceFile, pos) { + var token = ts.getTokenAtPosition(sourceFile, pos); + var assertion = ts.Debug.assertDefined(ts.findAncestor(token, function (n) { return ts.isAsExpression(n) || ts.isTypeAssertion(n); })); + var replacement = ts.isAsExpression(assertion) + ? ts.createAsExpression(assertion.expression, ts.createKeywordTypeNode(143 /* UnknownKeyword */)) + : ts.createTypeAssertion(ts.createKeywordTypeNode(143 /* UnknownKeyword */), assertion.expression); + changeTracker.replaceNode(sourceFile, assertion.expression, replacement); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "addMissingInvocationForDecorator"; + var errorCodes = [ts.Diagnostics._0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write_0.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return makeChange(t, context.sourceFile, context.span.start); }); + return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Call_decorator_expression, fixId, ts.Diagnostics.Add_to_all_uncalled_decorators)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { return makeChange(changes, diag.file, diag.start); }); }, + }); + function makeChange(changeTracker, sourceFile, pos) { + var token = ts.getTokenAtPosition(sourceFile, pos); + var decorator = ts.findAncestor(token, ts.isDecorator); + ts.Debug.assert(!!decorator, "Expected position to be owned by a decorator."); + var replacement = ts.createCall(decorator.expression, /*typeArguments*/ undefined, /*argumentsArray*/ undefined); + changeTracker.replaceNode(sourceFile, decorator.expression, replacement); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "addNameToNamelessParameter"; + var errorCodes = [ts.Diagnostics.Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return makeChange(t, context.sourceFile, context.span.start); }); + return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Add_parameter_name, fixId, ts.Diagnostics.Add_names_to_all_parameters_without_names)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { return makeChange(changes, diag.file, diag.start); }); }, + }); + function makeChange(changeTracker, sourceFile, pos) { + var token = ts.getTokenAtPosition(sourceFile, pos); + if (!ts.isIdentifier(token)) { + return ts.Debug.fail("add-name-to-nameless-parameter operates on identifiers, but got a " + ts.formatSyntaxKind(token.kind)); + } + var param = token.parent; + if (!ts.isParameter(param)) { + return ts.Debug.fail("Tried to add a parameter name to a non-parameter: " + ts.formatSyntaxKind(token.kind)); + } + var i = param.parent.parameters.indexOf(param); + ts.Debug.assert(!param.type, "Tried to add a parameter name to a parameter that already had one."); + ts.Debug.assert(i > -1, "Parameter not found in parent parameter list."); + var replacement = ts.createParameter( + /*decorators*/ undefined, param.modifiers, param.dotDotDotToken, "arg" + i, param.questionToken, ts.createTypeReferenceNode(token, /*typeArguments*/ undefined), param.initializer); + changeTracker.replaceNode(sourceFile, token, replacement); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "annotateWithTypeFromJSDoc"; + var errorCodes = [ts.Diagnostics.JSDoc_types_may_be_moved_to_TypeScript_types.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var decl = getDeclaration(context.sourceFile, context.span.start); + if (!decl) + return; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, context.sourceFile, decl); }); + return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Annotate_with_type_from_JSDoc, fixId, ts.Diagnostics.Annotate_everything_with_types_from_JSDoc)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var decl = getDeclaration(diag.file, diag.start); + if (decl) + doChange(changes, diag.file, decl); + }); }, + }); + function getDeclaration(file, pos) { + var name = ts.getTokenAtPosition(file, pos); + // For an arrow function with no name, 'name' lands on the first parameter. + return ts.tryCast(ts.isParameter(name.parent) ? name.parent.parent : name.parent, parameterShouldGetTypeFromJSDoc); + } + function parameterShouldGetTypeFromJSDoc(node) { + return isDeclarationWithType(node) && hasUsableJSDoc(node); + } + codefix.parameterShouldGetTypeFromJSDoc = parameterShouldGetTypeFromJSDoc; + function hasUsableJSDoc(decl) { + return ts.isFunctionLikeDeclaration(decl) + ? decl.parameters.some(hasUsableJSDoc) || (!decl.type && !!ts.getJSDocReturnType(decl)) + : !decl.type && !!ts.getJSDocType(decl); + } + function doChange(changes, sourceFile, decl) { + if (ts.isFunctionLikeDeclaration(decl) && (ts.getJSDocReturnType(decl) || decl.parameters.some(function (p) { return !!ts.getJSDocType(p); }))) { + if (!decl.typeParameters) { + var typeParameters = ts.getJSDocTypeParameterDeclarations(decl); + if (typeParameters.length) + changes.insertTypeParameters(sourceFile, decl, typeParameters); + } + var needParens = ts.isArrowFunction(decl) && !ts.findChildOfKind(decl, 20 /* OpenParenToken */, sourceFile); + if (needParens) + changes.insertNodeBefore(sourceFile, ts.first(decl.parameters), ts.createToken(20 /* OpenParenToken */)); + for (var _i = 0, _a = decl.parameters; _i < _a.length; _i++) { + var param = _a[_i]; + if (!param.type) { + var paramType = ts.getJSDocType(param); + if (paramType) + changes.tryInsertTypeAnnotation(sourceFile, param, transformJSDocType(paramType)); + } + } + if (needParens) + changes.insertNodeAfter(sourceFile, ts.last(decl.parameters), ts.createToken(21 /* CloseParenToken */)); + if (!decl.type) { + var returnType = ts.getJSDocReturnType(decl); + if (returnType) + changes.tryInsertTypeAnnotation(sourceFile, decl, transformJSDocType(returnType)); + } + } + else { + var jsdocType = ts.Debug.assertDefined(ts.getJSDocType(decl)); // If not defined, shouldn't have been an error to fix + ts.Debug.assert(!decl.type); // If defined, shouldn't have been an error to fix. + changes.tryInsertTypeAnnotation(sourceFile, decl, transformJSDocType(jsdocType)); + } + } + function isDeclarationWithType(node) { + return ts.isFunctionLikeDeclaration(node) || + node.kind === 237 /* VariableDeclaration */ || + node.kind === 153 /* PropertySignature */ || + node.kind === 154 /* PropertyDeclaration */; + } + function transformJSDocType(node) { + switch (node.kind) { + case 284 /* JSDocAllType */: + case 285 /* JSDocUnknownType */: + return ts.createTypeReferenceNode("any", ts.emptyArray); + case 288 /* JSDocOptionalType */: + return transformJSDocOptionalType(node); + case 287 /* JSDocNonNullableType */: + return transformJSDocType(node.type); + case 286 /* JSDocNullableType */: + return transformJSDocNullableType(node); + case 290 /* JSDocVariadicType */: + return transformJSDocVariadicType(node); + case 289 /* JSDocFunctionType */: + return transformJSDocFunctionType(node); + case 164 /* TypeReference */: + return transformJSDocTypeReference(node); + default: + var visited = ts.visitEachChild(node, transformJSDocType, /*context*/ undefined); // TODO: GH#18217 + ts.setEmitFlags(visited, 1 /* SingleLine */); + return visited; + } + } + function transformJSDocOptionalType(node) { + return ts.createUnionTypeNode([ts.visitNode(node.type, transformJSDocType), ts.createTypeReferenceNode("undefined", ts.emptyArray)]); + } + function transformJSDocNullableType(node) { + return ts.createUnionTypeNode([ts.visitNode(node.type, transformJSDocType), ts.createTypeReferenceNode("null", ts.emptyArray)]); + } + function transformJSDocVariadicType(node) { + return ts.createArrayTypeNode(ts.visitNode(node.type, transformJSDocType)); + } + function transformJSDocFunctionType(node) { + return ts.createFunctionTypeNode(ts.emptyArray, node.parameters.map(transformJSDocParameter), node.type); + } + function transformJSDocParameter(node) { + var index = node.parent.parameters.indexOf(node); + var isRest = node.type.kind === 290 /* JSDocVariadicType */ && index === node.parent.parameters.length - 1; // TODO: GH#18217 + var name = node.name || (isRest ? "rest" : "arg" + index); + var dotdotdot = isRest ? ts.createToken(25 /* DotDotDotToken */) : node.dotDotDotToken; + return ts.createParameter(node.decorators, node.modifiers, dotdotdot, name, node.questionToken, ts.visitNode(node.type, transformJSDocType), node.initializer); + } + function transformJSDocTypeReference(node) { + var name = node.typeName; + var args = node.typeArguments; + if (ts.isIdentifier(node.typeName)) { + if (ts.isJSDocIndexSignature(node)) { + return transformJSDocIndexSignature(node); + } + var text = node.typeName.text; + switch (node.typeName.text) { + case "String": + case "Boolean": + case "Object": + case "Number": + text = text.toLowerCase(); + break; + case "array": + case "date": + case "promise": + text = text[0].toUpperCase() + text.slice(1); + break; + } + name = ts.createIdentifier(text); + if ((text === "Array" || text === "Promise") && !node.typeArguments) { + args = ts.createNodeArray([ts.createTypeReferenceNode("any", ts.emptyArray)]); + } + else { + args = ts.visitNodes(node.typeArguments, transformJSDocType); + } + } + return ts.createTypeReferenceNode(name, args); + } + function transformJSDocIndexSignature(node) { + var index = ts.createParameter( + /*decorators*/ undefined, + /*modifiers*/ undefined, + /*dotDotDotToken*/ undefined, node.typeArguments[0].kind === 135 /* NumberKeyword */ ? "n" : "s", + /*questionToken*/ undefined, ts.createTypeReferenceNode(node.typeArguments[0].kind === 135 /* NumberKeyword */ ? "number" : "string", []), + /*initializer*/ undefined); + var indexSignature = ts.createTypeLiteralNode([ts.createIndexSignature(/*decorators*/ undefined, /*modifiers*/ undefined, [index], node.typeArguments[1])]); + ts.setEmitFlags(indexSignature, 1 /* SingleLine */); + return indexSignature; + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "inferFromUsage"; + var errorCodes = [ + // Variable declarations + ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code, + // Variable uses + ts.Diagnostics.Variable_0_implicitly_has_an_1_type.code, + // Parameter declarations + ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code, + ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code, + // Get Accessor declarations + ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation.code, + ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type.code, + // Set Accessor declarations + ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code, + // Property declarations + ts.Diagnostics.Member_0_implicitly_has_an_1_type.code, + //// Suggestions + // Variable declarations + ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_but_a_better_type_may_be_inferred_from_usage.code, + // Variable uses + ts.Diagnostics.Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code, + // Parameter declarations + ts.Diagnostics.Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code, + ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage.code, + // Get Accessor declarations + ts.Diagnostics.Property_0_implicitly_has_type_any_but_a_better_type_for_its_get_accessor_may_be_inferred_from_usage.code, + ts.Diagnostics._0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage.code, + // Set Accessor declarations + ts.Diagnostics.Property_0_implicitly_has_type_any_but_a_better_type_for_its_set_accessor_may_be_inferred_from_usage.code, + // Property declarations + ts.Diagnostics.Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code, + ]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var sourceFile = context.sourceFile, program = context.program, start = context.span.start, errorCode = context.errorCode, cancellationToken = context.cancellationToken, host = context.host; + var token = ts.getTokenAtPosition(sourceFile, start); + var declaration; + var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { declaration = doChange(changes, sourceFile, token, errorCode, program, cancellationToken, /*markSeen*/ ts.returnTrue, host); }); + var name = declaration && ts.getNameOfDeclaration(declaration); + return !name || changes.length === 0 ? undefined + : [codefix.createCodeFixAction(fixId, changes, [getDiagnostic(errorCode, token), name.getText(sourceFile)], fixId, ts.Diagnostics.Infer_all_types_from_usage)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { + var sourceFile = context.sourceFile, program = context.program, cancellationToken = context.cancellationToken, host = context.host; + var markSeen = ts.nodeSeenTracker(); + return codefix.codeFixAll(context, errorCodes, function (changes, err) { + doChange(changes, sourceFile, ts.getTokenAtPosition(err.file, err.start), err.code, program, cancellationToken, markSeen, host); + }); + }, + }); + function getDiagnostic(errorCode, token) { + switch (errorCode) { + case ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code: + case ts.Diagnostics.Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code: + return ts.isSetAccessorDeclaration(ts.getContainingFunction(token)) ? ts.Diagnostics.Infer_type_of_0_from_usage : ts.Diagnostics.Infer_parameter_types_from_usage; // TODO: GH#18217 + case ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code: + case ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage.code: + return ts.Diagnostics.Infer_parameter_types_from_usage; + default: + return ts.Diagnostics.Infer_type_of_0_from_usage; + } + } + /** Map suggestion code to error code */ + function mapSuggestionDiagnostic(errorCode) { + switch (errorCode) { + case ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_but_a_better_type_may_be_inferred_from_usage.code: + return ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code; + case ts.Diagnostics.Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code: + return ts.Diagnostics.Variable_0_implicitly_has_an_1_type.code; + case ts.Diagnostics.Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code: + return ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code; + case ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage.code: + return ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code; + case ts.Diagnostics.Property_0_implicitly_has_type_any_but_a_better_type_for_its_get_accessor_may_be_inferred_from_usage.code: + return ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation.code; + case ts.Diagnostics._0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage.code: + return ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type.code; + case ts.Diagnostics.Property_0_implicitly_has_type_any_but_a_better_type_for_its_set_accessor_may_be_inferred_from_usage.code: + return ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code; + case ts.Diagnostics.Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code: + return ts.Diagnostics.Member_0_implicitly_has_an_1_type.code; + } + return errorCode; + } + function doChange(changes, sourceFile, token, errorCode, program, cancellationToken, markSeen, host) { + if (!ts.isParameterPropertyModifier(token.kind) && token.kind !== 72 /* Identifier */ && token.kind !== 25 /* DotDotDotToken */ && token.kind !== 100 /* ThisKeyword */) { + return undefined; + } + var parent = token.parent; + errorCode = mapSuggestionDiagnostic(errorCode); + switch (errorCode) { + // Variable and Property declarations + case ts.Diagnostics.Member_0_implicitly_has_an_1_type.code: + case ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code: + if ((ts.isVariableDeclaration(parent) && markSeen(parent)) || ts.isPropertyDeclaration(parent) || ts.isPropertySignature(parent)) { // handle bad location + annotateVariableDeclaration(changes, sourceFile, parent, program, host, cancellationToken); + return parent; + } + if (ts.isPropertyAccessExpression(parent)) { + var type = inferTypeForVariableFromUsage(parent.name, program, cancellationToken); + var typeNode = getTypeNodeIfAccessible(type, parent, program, host); + if (typeNode) { + // Note that the codefix will never fire with an existing `@type` tag, so there is no need to merge tags + var typeTag = ts.createJSDocTypeTag(ts.createJSDocTypeExpression(typeNode), /*comment*/ ""); + addJSDocTags(changes, sourceFile, ts.cast(parent.parent.parent, ts.isExpressionStatement), [typeTag]); + } + return parent; + } + return undefined; + case ts.Diagnostics.Variable_0_implicitly_has_an_1_type.code: { + var symbol = program.getTypeChecker().getSymbolAtLocation(token); + if (symbol && symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && markSeen(symbol.valueDeclaration)) { + annotateVariableDeclaration(changes, sourceFile, symbol.valueDeclaration, program, host, cancellationToken); + return symbol.valueDeclaration; + } + return undefined; + } + } + var containingFunction = ts.getContainingFunction(token); + if (containingFunction === undefined) { + return undefined; + } + switch (errorCode) { + // Parameter declarations + case ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code: + if (ts.isSetAccessorDeclaration(containingFunction)) { + annotateSetAccessor(changes, sourceFile, containingFunction, program, host, cancellationToken); + return containingFunction; + } + // falls through + case ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code: + if (markSeen(containingFunction)) { + var param = ts.cast(parent, ts.isParameter); + annotateParameters(changes, sourceFile, param, containingFunction, program, host, cancellationToken); + return param; + } + return undefined; + // Get Accessor declarations + case ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation.code: + case ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type.code: + if (ts.isGetAccessorDeclaration(containingFunction) && ts.isIdentifier(containingFunction.name)) { + annotate(changes, sourceFile, containingFunction, inferTypeForVariableFromUsage(containingFunction.name, program, cancellationToken), program, host); + return containingFunction; + } + return undefined; + // Set Accessor declarations + case ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code: + if (ts.isSetAccessorDeclaration(containingFunction)) { + annotateSetAccessor(changes, sourceFile, containingFunction, program, host, cancellationToken); + return containingFunction; + } + return undefined; + default: + return ts.Debug.fail(String(errorCode)); + } + } + function annotateVariableDeclaration(changes, sourceFile, declaration, program, host, cancellationToken) { + if (ts.isIdentifier(declaration.name)) { + annotate(changes, sourceFile, declaration, inferTypeForVariableFromUsage(declaration.name, program, cancellationToken), program, host); + } + } + function annotateParameters(changes, sourceFile, parameterDeclaration, containingFunction, program, host, cancellationToken) { + if (!ts.isIdentifier(parameterDeclaration.name)) { + return; + } + var parameterInferences = inferTypeForParametersFromUsage(containingFunction, sourceFile, program, cancellationToken) || + containingFunction.parameters.map(function (p) { return ({ + declaration: p, + type: ts.isIdentifier(p.name) ? inferTypeForVariableFromUsage(p.name, program, cancellationToken) : program.getTypeChecker().getAnyType() + }); }); + ts.Debug.assert(containingFunction.parameters.length === parameterInferences.length); + if (ts.isInJSFile(containingFunction)) { + annotateJSDocParameters(changes, sourceFile, parameterInferences, program, host); + } + else { + var needParens = ts.isArrowFunction(containingFunction) && !ts.findChildOfKind(containingFunction, 20 /* OpenParenToken */, sourceFile); + if (needParens) + changes.insertNodeBefore(sourceFile, ts.first(containingFunction.parameters), ts.createToken(20 /* OpenParenToken */)); + for (var _i = 0, parameterInferences_1 = parameterInferences; _i < parameterInferences_1.length; _i++) { + var _a = parameterInferences_1[_i], declaration = _a.declaration, type = _a.type; + if (declaration && !declaration.type && !declaration.initializer) { + annotate(changes, sourceFile, declaration, type, program, host); + } + } + if (needParens) + changes.insertNodeAfter(sourceFile, ts.last(containingFunction.parameters), ts.createToken(21 /* CloseParenToken */)); + } + } + function annotateSetAccessor(changes, sourceFile, setAccessorDeclaration, program, host, cancellationToken) { + var param = ts.firstOrUndefined(setAccessorDeclaration.parameters); + if (param && ts.isIdentifier(setAccessorDeclaration.name) && ts.isIdentifier(param.name)) { + var type = inferTypeForVariableFromUsage(setAccessorDeclaration.name, program, cancellationToken); + if (type === program.getTypeChecker().getAnyType()) { + type = inferTypeForVariableFromUsage(param.name, program, cancellationToken); + } + if (ts.isInJSFile(setAccessorDeclaration)) { + annotateJSDocParameters(changes, sourceFile, [{ declaration: param, type: type }], program, host); + } + else { + annotate(changes, sourceFile, param, type, program, host); + } + } + } + function annotate(changes, sourceFile, declaration, type, program, host) { + var typeNode = getTypeNodeIfAccessible(type, declaration, program, host); + if (typeNode) { + if (ts.isInJSFile(sourceFile) && declaration.kind !== 153 /* PropertySignature */) { + var parent = ts.isVariableDeclaration(declaration) ? ts.tryCast(declaration.parent.parent, ts.isVariableStatement) : declaration; + if (!parent) { + return; + } + var typeExpression = ts.createJSDocTypeExpression(typeNode); + var typeTag = ts.isGetAccessorDeclaration(declaration) ? ts.createJSDocReturnTag(typeExpression, "") : ts.createJSDocTypeTag(typeExpression, ""); + addJSDocTags(changes, sourceFile, parent, [typeTag]); + } + else { + changes.tryInsertTypeAnnotation(sourceFile, declaration, typeNode); + } + } + } + function annotateJSDocParameters(changes, sourceFile, parameterInferences, program, host) { + var signature = parameterInferences.length && parameterInferences[0].declaration.parent; + if (!signature) { + return; + } + var paramTags = ts.mapDefined(parameterInferences, function (inference) { + var param = inference.declaration; + // only infer parameters that have (1) no type and (2) an accessible inferred type + if (param.initializer || ts.getJSDocType(param) || !ts.isIdentifier(param.name)) + return; + var typeNode = inference.type && getTypeNodeIfAccessible(inference.type, param, program, host); + var name = ts.getSynthesizedClone(param.name); + ts.setEmitFlags(name, 1536 /* NoComments */ | 2048 /* NoNestedComments */); + return typeNode && ts.createJSDocParamTag(name, !!inference.isOptional, ts.createJSDocTypeExpression(typeNode), ""); + }); + addJSDocTags(changes, sourceFile, signature, paramTags); + } + function addJSDocTags(changes, sourceFile, parent, newTags) { + var comments = ts.mapDefined(parent.jsDoc, function (j) { return j.comment; }); + var oldTags = ts.flatMapToMutable(parent.jsDoc, function (j) { return j.tags; }); + var unmergedNewTags = newTags.filter(function (newTag) { return !oldTags || !oldTags.some(function (tag, i) { + var merged = tryMergeJsdocTags(tag, newTag); + if (merged) + oldTags[i] = merged; + return !!merged; + }); }); + var tag = ts.createJSDocComment(comments.join("\n"), ts.createNodeArray((oldTags || ts.emptyArray).concat(unmergedNewTags))); + changes.insertJsdocCommentBefore(sourceFile, parent, tag); + } + function tryMergeJsdocTags(oldTag, newTag) { + if (oldTag.kind !== newTag.kind) { + return undefined; + } + switch (oldTag.kind) { + case 299 /* JSDocParameterTag */: { + var oldParam = oldTag; + var newParam = newTag; + return ts.isIdentifier(oldParam.name) && ts.isIdentifier(newParam.name) && oldParam.name.escapedText === newParam.name.escapedText + ? ts.createJSDocParamTag(newParam.name, newParam.isBracketed, newParam.typeExpression, oldParam.comment) + : undefined; + } + case 300 /* JSDocReturnTag */: + return ts.createJSDocReturnTag(newTag.typeExpression, oldTag.comment); + } + } + function getTypeNodeIfAccessible(type, enclosingScope, program, host) { + var checker = program.getTypeChecker(); + var typeIsAccessible = true; + var notAccessible = function () { typeIsAccessible = false; }; + var res = checker.typeToTypeNode(type, enclosingScope, /*flags*/ undefined, { + trackSymbol: function (symbol, declaration, meaning) { + // TODO: GH#18217 + typeIsAccessible = typeIsAccessible && checker.isSymbolAccessible(symbol, declaration, meaning, /*shouldComputeAliasToMarkVisible*/ false).accessibility === 0 /* Accessible */; + }, + reportInaccessibleThisError: notAccessible, + reportPrivateInBaseOfClassExpression: notAccessible, + reportInaccessibleUniqueSymbolError: notAccessible, + moduleResolverHost: { + readFile: host.readFile, + fileExists: host.fileExists, + directoryExists: host.directoryExists, + getSourceFiles: program.getSourceFiles, + getCurrentDirectory: program.getCurrentDirectory, + getCommonSourceDirectory: program.getCommonSourceDirectory, + } + }); + return typeIsAccessible ? res : undefined; + } + function getReferences(token, program, cancellationToken) { + // Position shouldn't matter since token is not a SourceFile. + return ts.mapDefined(ts.FindAllReferences.getReferenceEntriesForNode(-1, token, program, program.getSourceFiles(), cancellationToken), function (entry) { + return entry.kind !== 0 /* Span */ ? ts.tryCast(entry.node, ts.isIdentifier) : undefined; + }); + } + function inferTypeForVariableFromUsage(token, program, cancellationToken) { + var references = getReferences(token, program, cancellationToken); + var checker = program.getTypeChecker(); + var types = InferFromReference.inferTypesFromReferences(references, checker, cancellationToken); + return InferFromReference.unifyFromContext(types, checker); + } + function inferTypeForParametersFromUsage(containingFunction, sourceFile, program, cancellationToken) { + var searchToken; + switch (containingFunction.kind) { + case 157 /* Constructor */: + searchToken = ts.findChildOfKind(containingFunction, 124 /* ConstructorKeyword */, sourceFile); + break; + case 197 /* ArrowFunction */: + case 196 /* FunctionExpression */: + var parent = containingFunction.parent; + searchToken = ts.isVariableDeclaration(parent) && ts.isIdentifier(parent.name) ? + parent.name : + containingFunction.name; + break; + case 239 /* FunctionDeclaration */: + case 156 /* MethodDeclaration */: + searchToken = containingFunction.name; + break; + } + if (searchToken) { + return InferFromReference.inferTypeForParametersFromReferences(getReferences(searchToken, program, cancellationToken), containingFunction, program, cancellationToken); + } + } + var InferFromReference; + (function (InferFromReference) { + function inferTypesFromReferences(references, checker, cancellationToken) { + var usageContext = {}; + for (var _i = 0, references_1 = references; _i < references_1.length; _i++) { + var reference = references_1[_i]; + cancellationToken.throwIfCancellationRequested(); + inferTypeFromContext(reference, checker, usageContext); + } + return inferFromContext(usageContext, checker); + } + InferFromReference.inferTypesFromReferences = inferTypesFromReferences; + function inferTypeForParametersFromReferences(references, declaration, program, cancellationToken) { + var checker = program.getTypeChecker(); + if (references.length === 0) { + return undefined; + } + if (!declaration.parameters) { + return undefined; + } + var usageContext = {}; + for (var _i = 0, references_2 = references; _i < references_2.length; _i++) { + var reference = references_2[_i]; + cancellationToken.throwIfCancellationRequested(); + inferTypeFromContext(reference, checker, usageContext); + } + var callContexts = (usageContext.constructContexts || []).concat(usageContext.callContexts || []); + return declaration.parameters.map(function (parameter, parameterIndex) { + var types = []; + var isRest = ts.isRestParameter(parameter); + var isOptional = false; + for (var _i = 0, callContexts_1 = callContexts; _i < callContexts_1.length; _i++) { + var callContext = callContexts_1[_i]; + if (callContext.argumentTypes.length <= parameterIndex) { + isOptional = ts.isInJSFile(declaration); + types.push(checker.getUndefinedType()); + } + else if (isRest) { + for (var i = parameterIndex; i < callContext.argumentTypes.length; i++) { + types.push(checker.getBaseTypeOfLiteralType(callContext.argumentTypes[i])); + } + } + else { + types.push(checker.getBaseTypeOfLiteralType(callContext.argumentTypes[parameterIndex])); + } + } + if (ts.isIdentifier(parameter.name)) { + var inferred = inferTypesFromReferences(getReferences(parameter.name, program, cancellationToken), checker, cancellationToken); + types.push.apply(types, (isRest ? ts.mapDefined(inferred, checker.getElementTypeOfArrayType) : inferred)); + } + var type = unifyFromContext(types, checker); + return { + type: isRest ? checker.createArrayType(type) : type, + isOptional: isOptional && !isRest, + declaration: parameter + }; + }); + } + InferFromReference.inferTypeForParametersFromReferences = inferTypeForParametersFromReferences; + function inferTypeFromContext(node, checker, usageContext) { + while (ts.isRightSideOfQualifiedNameOrPropertyAccess(node)) { + node = node.parent; + } + switch (node.parent.kind) { + case 203 /* PostfixUnaryExpression */: + usageContext.isNumber = true; + break; + case 202 /* PrefixUnaryExpression */: + inferTypeFromPrefixUnaryExpressionContext(node.parent, usageContext); + break; + case 204 /* BinaryExpression */: + inferTypeFromBinaryExpressionContext(node, node.parent, checker, usageContext); + break; + case 271 /* CaseClause */: + case 272 /* DefaultClause */: + inferTypeFromSwitchStatementLabelContext(node.parent, checker, usageContext); + break; + case 191 /* CallExpression */: + case 192 /* NewExpression */: + if (node.parent.expression === node) { + inferTypeFromCallExpressionContext(node.parent, checker, usageContext); + } + else { + inferTypeFromContextualType(node, checker, usageContext); + } + break; + case 189 /* PropertyAccessExpression */: + inferTypeFromPropertyAccessExpressionContext(node.parent, checker, usageContext); + break; + case 190 /* ElementAccessExpression */: + inferTypeFromPropertyElementExpressionContext(node.parent, node, checker, usageContext); + break; + case 237 /* VariableDeclaration */: { + var _a = node.parent, name = _a.name, initializer = _a.initializer; + if (node === name) { + if (initializer) { // This can happen for `let x = null;` which still has an implicit-any error. + addCandidateType(usageContext, checker.getTypeAtLocation(initializer)); + } + break; + } + } + // falls through + default: + return inferTypeFromContextualType(node, checker, usageContext); + } + } + function inferTypeFromContextualType(node, checker, usageContext) { + if (ts.isExpressionNode(node)) { + addCandidateType(usageContext, checker.getContextualType(node)); + } + } + function inferTypeFromPrefixUnaryExpressionContext(node, usageContext) { + switch (node.operator) { + case 44 /* PlusPlusToken */: + case 45 /* MinusMinusToken */: + case 39 /* MinusToken */: + case 53 /* TildeToken */: + usageContext.isNumber = true; + break; + case 38 /* PlusToken */: + usageContext.isNumberOrString = true; + break; + // case SyntaxKind.ExclamationToken: + // no inferences here; + } + } + function inferTypeFromBinaryExpressionContext(node, parent, checker, usageContext) { + switch (parent.operatorToken.kind) { + // ExponentiationOperator + case 41 /* AsteriskAsteriskToken */: + // MultiplicativeOperator + case 40 /* AsteriskToken */: + case 42 /* SlashToken */: + case 43 /* PercentToken */: + // ShiftOperator + case 46 /* LessThanLessThanToken */: + case 47 /* GreaterThanGreaterThanToken */: + case 48 /* GreaterThanGreaterThanGreaterThanToken */: + // BitwiseOperator + case 49 /* AmpersandToken */: + case 50 /* BarToken */: + case 51 /* CaretToken */: + // CompoundAssignmentOperator + case 61 /* MinusEqualsToken */: + case 63 /* AsteriskAsteriskEqualsToken */: + case 62 /* AsteriskEqualsToken */: + case 64 /* SlashEqualsToken */: + case 65 /* PercentEqualsToken */: + case 69 /* AmpersandEqualsToken */: + case 70 /* BarEqualsToken */: + case 71 /* CaretEqualsToken */: + case 66 /* LessThanLessThanEqualsToken */: + case 68 /* GreaterThanGreaterThanGreaterThanEqualsToken */: + case 67 /* GreaterThanGreaterThanEqualsToken */: + // AdditiveOperator + case 39 /* MinusToken */: + // RelationalOperator + case 28 /* LessThanToken */: + case 31 /* LessThanEqualsToken */: + case 30 /* GreaterThanToken */: + case 32 /* GreaterThanEqualsToken */: + var operandType = checker.getTypeAtLocation(parent.left === node ? parent.right : parent.left); + if (operandType.flags & 1056 /* EnumLike */) { + addCandidateType(usageContext, operandType); + } + else { + usageContext.isNumber = true; + } + break; + case 60 /* PlusEqualsToken */: + case 38 /* PlusToken */: + var otherOperandType = checker.getTypeAtLocation(parent.left === node ? parent.right : parent.left); + if (otherOperandType.flags & 1056 /* EnumLike */) { + addCandidateType(usageContext, otherOperandType); + } + else if (otherOperandType.flags & 296 /* NumberLike */) { + usageContext.isNumber = true; + } + else if (otherOperandType.flags & 132 /* StringLike */) { + usageContext.isString = true; + } + else { + usageContext.isNumberOrString = true; + } + break; + // AssignmentOperators + case 59 /* EqualsToken */: + case 33 /* EqualsEqualsToken */: + case 35 /* EqualsEqualsEqualsToken */: + case 36 /* ExclamationEqualsEqualsToken */: + case 34 /* ExclamationEqualsToken */: + addCandidateType(usageContext, checker.getTypeAtLocation(parent.left === node ? parent.right : parent.left)); + break; + case 93 /* InKeyword */: + if (node === parent.left) { + usageContext.isString = true; + } + break; + // LogicalOperator + case 55 /* BarBarToken */: + if (node === parent.left && + (node.parent.parent.kind === 237 /* VariableDeclaration */ || ts.isAssignmentExpression(node.parent.parent, /*excludeCompoundAssignment*/ true))) { + // var x = x || {}; + // TODO: use getFalsyflagsOfType + addCandidateType(usageContext, checker.getTypeAtLocation(parent.right)); + } + break; + case 54 /* AmpersandAmpersandToken */: + case 27 /* CommaToken */: + case 94 /* InstanceOfKeyword */: + // nothing to infer here + break; + } + } + function inferTypeFromSwitchStatementLabelContext(parent, checker, usageContext) { + addCandidateType(usageContext, checker.getTypeAtLocation(parent.parent.parent.expression)); + } + function inferTypeFromCallExpressionContext(parent, checker, usageContext) { + var callContext = { + argumentTypes: [], + returnType: {} + }; + if (parent.arguments) { + for (var _i = 0, _a = parent.arguments; _i < _a.length; _i++) { + var argument = _a[_i]; + callContext.argumentTypes.push(checker.getTypeAtLocation(argument)); + } + } + inferTypeFromContext(parent, checker, callContext.returnType); + if (parent.kind === 191 /* CallExpression */) { + (usageContext.callContexts || (usageContext.callContexts = [])).push(callContext); + } + else { + (usageContext.constructContexts || (usageContext.constructContexts = [])).push(callContext); + } + } + function inferTypeFromPropertyAccessExpressionContext(parent, checker, usageContext) { + var name = ts.escapeLeadingUnderscores(parent.name.text); + if (!usageContext.properties) { + usageContext.properties = ts.createUnderscoreEscapedMap(); + } + var propertyUsageContext = usageContext.properties.get(name) || {}; + inferTypeFromContext(parent, checker, propertyUsageContext); + usageContext.properties.set(name, propertyUsageContext); + } + function inferTypeFromPropertyElementExpressionContext(parent, node, checker, usageContext) { + if (node === parent.argumentExpression) { + usageContext.isNumberOrString = true; + return; + } + else { + var indexType = checker.getTypeAtLocation(parent.argumentExpression); + var indexUsageContext = {}; + inferTypeFromContext(parent, checker, indexUsageContext); + if (indexType.flags & 296 /* NumberLike */) { + usageContext.numberIndexContext = indexUsageContext; + } + else { + usageContext.stringIndexContext = indexUsageContext; + } + } + } + function removeLowPriorityInferences(inferences, priorities) { + var toRemove = []; + for (var _i = 0, inferences_1 = inferences; _i < inferences_1.length; _i++) { + var i = inferences_1[_i]; + for (var _a = 0, priorities_1 = priorities; _a < priorities_1.length; _a++) { + var _b = priorities_1[_a], high = _b.high, low = _b.low; + if (high(i)) { + ts.Debug.assert(!low(i)); + toRemove.push(low); + } + } + } + return inferences.filter(function (i) { return toRemove.every(function (f) { return !f(i); }); }); + } + function unifyFromContext(inferences, checker, fallback) { + if (fallback === void 0) { fallback = checker.getAnyType(); } + if (!inferences.length) + return fallback; + // 1. string or number individually override string | number + // 2. non-any, non-void overrides any or void + // 3. non-nullable, non-any, non-void, non-anonymous overrides anonymous types + var stringNumber = checker.getUnionType([checker.getStringType(), checker.getNumberType()]); + var priorities = [ + { + high: function (t) { return t === checker.getStringType() || t === checker.getNumberType(); }, + low: function (t) { return t === stringNumber; } + }, + { + high: function (t) { return !(t.flags & (1 /* Any */ | 16384 /* Void */)); }, + low: function (t) { return !!(t.flags & (1 /* Any */ | 16384 /* Void */)); } + }, + { + high: function (t) { return !(t.flags & (98304 /* Nullable */ | 1 /* Any */ | 16384 /* Void */)) && !(checker.getObjectFlags(t) & 16 /* Anonymous */); }, + low: function (t) { return !!(checker.getObjectFlags(t) & 16 /* Anonymous */); } + } + ]; + var good = removeLowPriorityInferences(inferences, priorities); + var anons = good.filter(function (i) { return checker.getObjectFlags(i) & 16 /* Anonymous */; }); + if (anons.length) { + good = good.filter(function (i) { return !(checker.getObjectFlags(i) & 16 /* Anonymous */); }); + good.push(unifyAnonymousTypes(anons, checker)); + } + return checker.getWidenedType(checker.getUnionType(good)); + } + InferFromReference.unifyFromContext = unifyFromContext; + function unifyAnonymousTypes(anons, checker) { + if (anons.length === 1) { + return anons[0]; + } + var calls = []; + var constructs = []; + var stringIndices = []; + var numberIndices = []; + var stringIndexReadonly = false; + var numberIndexReadonly = false; + var props = ts.createMultiMap(); + for (var _i = 0, anons_1 = anons; _i < anons_1.length; _i++) { + var anon = anons_1[_i]; + for (var _a = 0, _b = checker.getPropertiesOfType(anon); _a < _b.length; _a++) { + var p = _b[_a]; + props.add(p.name, checker.getTypeOfSymbolAtLocation(p, p.valueDeclaration)); + } + calls.push.apply(calls, checker.getSignaturesOfType(anon, 0 /* Call */)); + constructs.push.apply(constructs, checker.getSignaturesOfType(anon, 1 /* Construct */)); + if (anon.stringIndexInfo) { + stringIndices.push(anon.stringIndexInfo.type); + stringIndexReadonly = stringIndexReadonly || anon.stringIndexInfo.isReadonly; + } + if (anon.numberIndexInfo) { + numberIndices.push(anon.numberIndexInfo.type); + numberIndexReadonly = numberIndexReadonly || anon.numberIndexInfo.isReadonly; + } + } + var members = ts.mapEntries(props, function (name, types) { + var isOptional = types.length < anons.length ? 16777216 /* Optional */ : 0; + var s = checker.createSymbol(4 /* Property */ | isOptional, name); + s.type = checker.getUnionType(types); + return [name, s]; + }); + return checker.createAnonymousType(anons[0].symbol, members, calls, constructs, stringIndices.length ? checker.createIndexInfo(checker.getUnionType(stringIndices), stringIndexReadonly) : undefined, numberIndices.length ? checker.createIndexInfo(checker.getUnionType(numberIndices), numberIndexReadonly) : undefined); + } + function inferFromContext(usageContext, checker) { + var types = []; + if (usageContext.isNumber) { + types.push(checker.getNumberType()); + } + if (usageContext.isString) { + types.push(checker.getStringType()); + } + if (usageContext.isNumberOrString) { + types.push(checker.getUnionType([checker.getStringType(), checker.getNumberType()])); + } + types.push.apply(types, (usageContext.candidateTypes || []).map(function (t) { return checker.getBaseTypeOfLiteralType(t); })); + if (usageContext.properties && hasCallContext(usageContext.properties.get("then"))) { + var paramType = getParameterTypeFromCallContexts(0, usageContext.properties.get("then").callContexts, /*isRestParameter*/ false, checker); // TODO: GH#18217 + var types_1 = paramType.getCallSignatures().map(function (c) { return c.getReturnType(); }); + types_1.push(checker.createPromiseType(types_1.length ? checker.getUnionType(types_1, 2 /* Subtype */) : checker.getAnyType())); + } + else if (usageContext.properties && hasCallContext(usageContext.properties.get("push"))) { + types.push(checker.createArrayType(getParameterTypeFromCallContexts(0, usageContext.properties.get("push").callContexts, /*isRestParameter*/ false, checker))); + } + if (usageContext.numberIndexContext) { + types.push(checker.createArrayType(recur(usageContext.numberIndexContext))); + } + else if (usageContext.properties || usageContext.callContexts || usageContext.constructContexts || usageContext.stringIndexContext) { + var members_1 = ts.createUnderscoreEscapedMap(); + var callSignatures = []; + var constructSignatures = []; + var stringIndexInfo = void 0; + if (usageContext.properties) { + usageContext.properties.forEach(function (context, name) { + var symbol = checker.createSymbol(4 /* Property */, name); + symbol.type = recur(context); + members_1.set(name, symbol); + }); + } + if (usageContext.callContexts) { + for (var _i = 0, _a = usageContext.callContexts; _i < _a.length; _i++) { + var callContext = _a[_i]; + callSignatures.push(getSignatureFromCallContext(callContext, checker)); + } + } + if (usageContext.constructContexts) { + for (var _b = 0, _c = usageContext.constructContexts; _b < _c.length; _b++) { + var constructContext = _c[_b]; + constructSignatures.push(getSignatureFromCallContext(constructContext, checker)); + } + } + if (usageContext.stringIndexContext) { + stringIndexInfo = checker.createIndexInfo(recur(usageContext.stringIndexContext), /*isReadonly*/ false); + } + types.push(checker.createAnonymousType(/*symbol*/ undefined, members_1, callSignatures, constructSignatures, stringIndexInfo, /*numberIndexInfo*/ undefined)); // TODO: GH#18217 + } + return types; + function recur(innerContext) { + return unifyFromContext(inferFromContext(innerContext, checker), checker); + } + } + function getParameterTypeFromCallContexts(parameterIndex, callContexts, isRestParameter, checker) { + var types = []; + if (callContexts) { + for (var _i = 0, callContexts_2 = callContexts; _i < callContexts_2.length; _i++) { + var callContext = callContexts_2[_i]; + if (callContext.argumentTypes.length > parameterIndex) { + if (isRestParameter) { + types = ts.concatenate(types, ts.map(callContext.argumentTypes.slice(parameterIndex), function (a) { return checker.getBaseTypeOfLiteralType(a); })); + } + else { + types.push(checker.getBaseTypeOfLiteralType(callContext.argumentTypes[parameterIndex])); + } + } + } + } + if (types.length) { + var type = checker.getWidenedType(checker.getUnionType(types, 2 /* Subtype */)); + return isRestParameter ? checker.createArrayType(type) : type; + } + return undefined; + } + function getSignatureFromCallContext(callContext, checker) { + var parameters = []; + for (var i = 0; i < callContext.argumentTypes.length; i++) { + var symbol = checker.createSymbol(1 /* FunctionScopedVariable */, ts.escapeLeadingUnderscores("arg" + i)); + symbol.type = checker.getWidenedType(checker.getBaseTypeOfLiteralType(callContext.argumentTypes[i])); + parameters.push(symbol); + } + var returnType = unifyFromContext(inferFromContext(callContext.returnType, checker), checker, checker.getVoidType()); + // TODO: GH#18217 + return checker.createSignature(/*declaration*/ undefined, /*typeParameters*/ undefined, /*thisParameter*/ undefined, parameters, returnType, /*typePredicate*/ undefined, callContext.argumentTypes.length, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + } + function addCandidateType(context, type) { + if (type && !(type.flags & 1 /* Any */) && !(type.flags & 131072 /* Never */)) { + (context.candidateTypes || (context.candidateTypes = [])).push(type); + } + } + function hasCallContext(usageContext) { + return !!usageContext && !!usageContext.callContexts; + } + })(InferFromReference || (InferFromReference = {})); + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "convertFunctionToEs6Class"; + var errorCodes = [ts.Diagnostics.This_constructor_function_may_be_converted_to_a_class_declaration.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, context.sourceFile, context.span.start, context.program.getTypeChecker()); }); + return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Convert_function_to_an_ES2015_class, fixId, ts.Diagnostics.Convert_all_constructor_functions_to_classes)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, err) { return doChange(changes, err.file, err.start, context.program.getTypeChecker()); }); }, + }); + function doChange(changes, sourceFile, position, checker) { + var ctorSymbol = checker.getSymbolAtLocation(ts.getTokenAtPosition(sourceFile, position)); + if (!ctorSymbol || !(ctorSymbol.flags & (16 /* Function */ | 3 /* Variable */))) { + // Bad input + return undefined; + } + var ctorDeclaration = ctorSymbol.valueDeclaration; + var precedingNode; + var newClassDeclaration; + switch (ctorDeclaration.kind) { + case 239 /* FunctionDeclaration */: + precedingNode = ctorDeclaration; + changes.delete(sourceFile, ctorDeclaration); + newClassDeclaration = createClassFromFunctionDeclaration(ctorDeclaration); + break; + case 237 /* VariableDeclaration */: + precedingNode = ctorDeclaration.parent.parent; + newClassDeclaration = createClassFromVariableDeclaration(ctorDeclaration); + if (ctorDeclaration.parent.declarations.length === 1) { + ts.copyComments(precedingNode, newClassDeclaration, sourceFile); // TODO: GH#18217 + changes.delete(sourceFile, precedingNode); + } + else { + changes.delete(sourceFile, ctorDeclaration); + } + break; + } + if (!newClassDeclaration) { + return undefined; + } + ts.copyComments(ctorDeclaration, newClassDeclaration, sourceFile); + // Because the preceding node could be touched, we need to insert nodes before delete nodes. + changes.insertNodeAfter(sourceFile, precedingNode, newClassDeclaration); + function createClassElementsFromSymbol(symbol) { + var memberElements = []; + // all instance members are stored in the "member" array of symbol + if (symbol.members) { + symbol.members.forEach(function (member) { + var memberElement = createClassElement(member, /*modifiers*/ undefined); + if (memberElement) { + memberElements.push(memberElement); + } + }); + } + // all static members are stored in the "exports" array of symbol + if (symbol.exports) { + symbol.exports.forEach(function (member) { + var memberElement = createClassElement(member, [ts.createToken(116 /* StaticKeyword */)]); + if (memberElement) { + memberElements.push(memberElement); + } + }); + } + return memberElements; + function shouldConvertDeclaration(_target, source) { + // Right now the only thing we can convert are function expressions - other values shouldn't get + // transformed. We can update this once ES public class properties are available. + return ts.isFunctionLike(source); + } + function createClassElement(symbol, modifiers) { + // Right now the only thing we can convert are function expressions, which are marked as methods + if (!(symbol.flags & 8192 /* Method */)) { + return; + } + var memberDeclaration = symbol.valueDeclaration; + var assignmentBinaryExpression = memberDeclaration.parent; + if (!shouldConvertDeclaration(memberDeclaration, assignmentBinaryExpression.right)) { + return; + } + // delete the entire statement if this expression is the sole expression to take care of the semicolon at the end + var nodeToDelete = assignmentBinaryExpression.parent && assignmentBinaryExpression.parent.kind === 221 /* ExpressionStatement */ + ? assignmentBinaryExpression.parent : assignmentBinaryExpression; + changes.delete(sourceFile, nodeToDelete); + if (!assignmentBinaryExpression.right) { + return ts.createProperty([], modifiers, symbol.name, /*questionToken*/ undefined, + /*type*/ undefined, /*initializer*/ undefined); + } + switch (assignmentBinaryExpression.right.kind) { + case 196 /* FunctionExpression */: { + var functionExpression = assignmentBinaryExpression.right; + var fullModifiers = ts.concatenate(modifiers, getModifierKindFromSource(functionExpression, 121 /* AsyncKeyword */)); + var method = ts.createMethod(/*decorators*/ undefined, fullModifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined, + /*typeParameters*/ undefined, functionExpression.parameters, /*type*/ undefined, functionExpression.body); + ts.copyComments(assignmentBinaryExpression, method, sourceFile); + return method; + } + case 197 /* ArrowFunction */: { + var arrowFunction = assignmentBinaryExpression.right; + var arrowFunctionBody = arrowFunction.body; + var bodyBlock = void 0; + // case 1: () => { return [1,2,3] } + if (arrowFunctionBody.kind === 218 /* Block */) { + bodyBlock = arrowFunctionBody; + } + // case 2: () => [1,2,3] + else { + bodyBlock = ts.createBlock([ts.createReturn(arrowFunctionBody)]); + } + var fullModifiers = ts.concatenate(modifiers, getModifierKindFromSource(arrowFunction, 121 /* AsyncKeyword */)); + var method = ts.createMethod(/*decorators*/ undefined, fullModifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined, + /*typeParameters*/ undefined, arrowFunction.parameters, /*type*/ undefined, bodyBlock); + ts.copyComments(assignmentBinaryExpression, method, sourceFile); + return method; + } + default: { + // Don't try to declare members in JavaScript files + if (ts.isSourceFileJS(sourceFile)) { + return; + } + var prop = ts.createProperty(/*decorators*/ undefined, modifiers, memberDeclaration.name, /*questionToken*/ undefined, + /*type*/ undefined, assignmentBinaryExpression.right); + ts.copyComments(assignmentBinaryExpression.parent, prop, sourceFile); + return prop; + } + } + } + } + function createClassFromVariableDeclaration(node) { + var initializer = node.initializer; + if (!initializer || initializer.kind !== 196 /* FunctionExpression */) { + return undefined; + } + if (node.name.kind !== 72 /* Identifier */) { + return undefined; + } + var memberElements = createClassElementsFromSymbol(node.symbol); + if (initializer.body) { + memberElements.unshift(ts.createConstructor(/*decorators*/ undefined, /*modifiers*/ undefined, initializer.parameters, initializer.body)); + } + var modifiers = getModifierKindFromSource(precedingNode, 85 /* ExportKeyword */); + var cls = ts.createClassDeclaration(/*decorators*/ undefined, modifiers, node.name, + /*typeParameters*/ undefined, /*heritageClauses*/ undefined, memberElements); + // Don't call copyComments here because we'll already leave them in place + return cls; + } + function createClassFromFunctionDeclaration(node) { + var memberElements = createClassElementsFromSymbol(ctorSymbol); + if (node.body) { + memberElements.unshift(ts.createConstructor(/*decorators*/ undefined, /*modifiers*/ undefined, node.parameters, node.body)); + } + var modifiers = getModifierKindFromSource(node, 85 /* ExportKeyword */); + var cls = ts.createClassDeclaration(/*decorators*/ undefined, modifiers, node.name, + /*typeParameters*/ undefined, /*heritageClauses*/ undefined, memberElements); + // Don't call copyComments here because we'll already leave them in place + return cls; + } + } + function getModifierKindFromSource(source, kind) { + return ts.filter(source.modifiers, function (modifier) { return modifier.kind === kind; }); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "convertToAsyncFunction"; + var errorCodes = [ts.Diagnostics.This_may_be_converted_to_an_async_function.code]; + var codeActionSucceeded = true; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + codeActionSucceeded = true; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return convertToAsyncFunction(t, context.sourceFile, context.span.start, context.program.getTypeChecker(), context); }); + return codeActionSucceeded ? [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Convert_to_async_function, fixId, ts.Diagnostics.Convert_all_to_async_functions)] : []; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, err) { return convertToAsyncFunction(changes, err.file, err.start, context.program.getTypeChecker(), context); }); }, + }); + function convertToAsyncFunction(changes, sourceFile, position, checker, context) { + // get the function declaration - returns a promise + var tokenAtPosition = ts.getTokenAtPosition(sourceFile, position); + var functionToConvert; + // if the parent of a FunctionLikeDeclaration is a variable declaration, the convertToAsync diagnostic will be reported on the variable name + if (ts.isIdentifier(tokenAtPosition) && ts.isVariableDeclaration(tokenAtPosition.parent) && + tokenAtPosition.parent.initializer && ts.isFunctionLikeDeclaration(tokenAtPosition.parent.initializer)) { + functionToConvert = tokenAtPosition.parent.initializer; + } + else { + functionToConvert = ts.tryCast(ts.getContainingFunction(ts.getTokenAtPosition(sourceFile, position)), ts.isFunctionLikeDeclaration); + } + if (!functionToConvert) { + return; + } + var synthNamesMap = ts.createMap(); + var originalTypeMap = ts.createMap(); + var allVarNames = []; + var isInJavascript = ts.isInJSFile(functionToConvert); + var setOfExpressionsToReturn = getAllPromiseExpressionsToReturn(functionToConvert, checker); + var functionToConvertRenamed = renameCollidingVarNames(functionToConvert, checker, synthNamesMap, context, setOfExpressionsToReturn, originalTypeMap, allVarNames); + var constIdentifiers = getConstIdentifiers(synthNamesMap); + var returnStatements = functionToConvertRenamed.body && ts.isBlock(functionToConvertRenamed.body) ? getReturnStatementsWithPromiseHandlers(functionToConvertRenamed.body) : ts.emptyArray; + var transformer = { checker: checker, synthNamesMap: synthNamesMap, allVarNames: allVarNames, setOfExpressionsToReturn: setOfExpressionsToReturn, constIdentifiers: constIdentifiers, originalTypeMap: originalTypeMap, isInJSFile: isInJavascript }; + if (!returnStatements.length) { + return; + } + // add the async keyword + changes.insertLastModifierBefore(sourceFile, 121 /* AsyncKeyword */, functionToConvert); + function startTransformation(node, nodeToReplace) { + var newNodes = transformExpression(node, transformer, node); + changes.replaceNodeWithNodes(sourceFile, nodeToReplace, newNodes); + } + var _loop_10 = function (statement) { + ts.forEachChild(statement, function visit(node) { + if (ts.isCallExpression(node)) { + startTransformation(node, statement); + } + else if (!ts.isFunctionLike(node)) { + ts.forEachChild(node, visit); + } + }); + }; + for (var _i = 0, returnStatements_1 = returnStatements; _i < returnStatements_1.length; _i++) { + var statement = returnStatements_1[_i]; + _loop_10(statement); + } + } + function getReturnStatementsWithPromiseHandlers(body) { + var res = []; + ts.forEachReturnStatement(body, function (ret) { + if (ts.isReturnStatementWithFixablePromiseHandler(ret)) + res.push(ret); + }); + return res; + } + // Returns the identifiers that are never reassigned in the refactor + function getConstIdentifiers(synthNamesMap) { + var constIdentifiers = []; + synthNamesMap.forEach(function (val) { + if (val.numberOfAssignmentsOriginal === 0) { + constIdentifiers.push(val.identifier); + } + }); + return constIdentifiers; + } + /* + Finds all of the expressions of promise type that should not be saved in a variable during the refactor + */ + function getAllPromiseExpressionsToReturn(func, checker) { + if (!func.body) { + return ts.createMap(); + } + var setOfExpressionsToReturn = ts.createMap(); + ts.forEachChild(func.body, function visit(node) { + if (isPromiseReturningExpression(node, checker, "then")) { + setOfExpressionsToReturn.set(ts.getNodeId(node).toString(), true); + ts.forEach(node.arguments, visit); + } + else if (isPromiseReturningExpression(node, checker, "catch")) { + setOfExpressionsToReturn.set(ts.getNodeId(node).toString(), true); + // if .catch() is the last call in the chain, move leftward in the chain until we hit something else that should be returned + ts.forEachChild(node, visit); + } + else if (isPromiseReturningExpression(node, checker)) { + setOfExpressionsToReturn.set(ts.getNodeId(node).toString(), true); + // don't recurse here, since we won't refactor any children or arguments of the expression + } + else { + ts.forEachChild(node, visit); + } + }); + return setOfExpressionsToReturn; + } + /* + Returns true if node is a promise returning expression + If name is not undefined, node is a promise returning call of name + */ + function isPromiseReturningExpression(node, checker, name) { + var isNodeExpression = name ? ts.isCallExpression(node) : ts.isExpression(node); + var isExpressionOfName = isNodeExpression && (!name || ts.hasPropertyAccessExpressionWithName(node, name)); + var nodeType = isExpressionOfName && checker.getTypeAtLocation(node); + return !!(nodeType && checker.getPromisedTypeOfPromise(nodeType)); + } + function declaredInFile(symbol, sourceFile) { + return symbol.valueDeclaration && symbol.valueDeclaration.getSourceFile() === sourceFile; + } + /* + Renaming of identifiers may be neccesary as the refactor changes scopes - + This function collects all existing identifier names and names of identifiers that will be created in the refactor. + It then checks for any collisions and renames them through getSynthesizedDeepClone + */ + function renameCollidingVarNames(nodeToRename, checker, synthNamesMap, context, setOfAllExpressionsToReturn, originalType, allVarNames) { + var identsToRenameMap = ts.createMap(); // key is the symbol id + var collidingSymbolMap = ts.createMap(); + ts.forEachChild(nodeToRename, function visit(node) { + if (!ts.isIdentifier(node)) { + ts.forEachChild(node, visit); + return; + } + var symbol = checker.getSymbolAtLocation(node); + var isDefinedInFile = symbol && declaredInFile(symbol, context.sourceFile); + if (symbol && isDefinedInFile) { + var type = checker.getTypeAtLocation(node); + var lastCallSignature = getLastCallSignature(type, checker); + var symbolIdString = ts.getSymbolId(symbol).toString(); + // if the identifier refers to a function we want to add the new synthesized variable for the declaration (ex. blob in let blob = res(arg)) + // Note - the choice of the last call signature is arbitrary + if (lastCallSignature && !ts.isFunctionLikeDeclaration(node.parent) && !synthNamesMap.has(symbolIdString)) { + var firstParameter = ts.firstOrUndefined(lastCallSignature.parameters); + var ident = firstParameter && ts.isParameter(firstParameter.valueDeclaration) && ts.tryCast(firstParameter.valueDeclaration.name, ts.isIdentifier) || ts.createOptimisticUniqueName("result"); + var synthName = getNewNameIfConflict(ident, collidingSymbolMap); + synthNamesMap.set(symbolIdString, synthName); + allVarNames.push({ identifier: synthName.identifier, symbol: symbol }); + addNameToFrequencyMap(collidingSymbolMap, ident.text, symbol); + } + // we only care about identifiers that are parameters and declarations (don't care about other uses) + else if (node.parent && (ts.isParameter(node.parent) || ts.isVariableDeclaration(node.parent))) { + var originalName = node.text; + var collidingSymbols = collidingSymbolMap.get(originalName); + // if the identifier name conflicts with a different identifier that we've already seen + if (collidingSymbols && collidingSymbols.some(function (prevSymbol) { return prevSymbol !== symbol; })) { + var newName = getNewNameIfConflict(node, collidingSymbolMap); + identsToRenameMap.set(symbolIdString, newName.identifier); + synthNamesMap.set(symbolIdString, newName); + allVarNames.push({ identifier: newName.identifier, symbol: symbol }); + addNameToFrequencyMap(collidingSymbolMap, originalName, symbol); + } + else { + var identifier = ts.getSynthesizedDeepClone(node); + identsToRenameMap.set(symbolIdString, identifier); + synthNamesMap.set(symbolIdString, { identifier: identifier, types: [], numberOfAssignmentsOriginal: allVarNames.filter(function (elem) { return elem.identifier.text === node.text; }).length /*, numberOfAssignmentsSynthesized: 0*/ }); + if ((ts.isParameter(node.parent) && isExpressionOrCallOnTypePromise(node.parent.parent)) || ts.isVariableDeclaration(node.parent)) { + allVarNames.push({ identifier: identifier, symbol: symbol }); + addNameToFrequencyMap(collidingSymbolMap, originalName, symbol); + } + } + } + } + }); + return ts.getSynthesizedDeepCloneWithRenames(nodeToRename, /*includeTrivia*/ true, identsToRenameMap, checker, deepCloneCallback); + function isExpressionOrCallOnTypePromise(child) { + var node = child.parent; + if (ts.isCallExpression(node) || ts.isIdentifier(node) && !setOfAllExpressionsToReturn.get(ts.getNodeId(node).toString())) { + var nodeType = checker.getTypeAtLocation(node); + var isPromise = nodeType && checker.getPromisedTypeOfPromise(nodeType); + return !!isPromise; + } + return false; + } + function deepCloneCallback(node, clone) { + if (ts.isIdentifier(node)) { + var symbol = checker.getSymbolAtLocation(node); + var symboldIdString = symbol && ts.getSymbolId(symbol).toString(); + var renameInfo = symbol && synthNamesMap.get(symboldIdString); + if (renameInfo) { + var type = checker.getTypeAtLocation(node); + originalType.set(ts.getNodeId(clone).toString(), type); + } + } + var val = setOfAllExpressionsToReturn.get(ts.getNodeId(node).toString()); + if (val !== undefined) { + setOfAllExpressionsToReturn.delete(ts.getNodeId(node).toString()); + setOfAllExpressionsToReturn.set(ts.getNodeId(clone).toString(), val); + } + } + } + function addNameToFrequencyMap(renamedVarNameFrequencyMap, originalName, symbol) { + if (renamedVarNameFrequencyMap.has(originalName)) { + renamedVarNameFrequencyMap.get(originalName).push(symbol); + } + else { + renamedVarNameFrequencyMap.set(originalName, [symbol]); + } + } + function getNewNameIfConflict(name, originalNames) { + var numVarsSameName = (originalNames.get(name.text) || ts.emptyArray).length; + var numberOfAssignmentsOriginal = 0; + var identifier = numVarsSameName === 0 ? name : ts.createIdentifier(name.text + "_" + numVarsSameName); + return { identifier: identifier, types: [], numberOfAssignmentsOriginal: numberOfAssignmentsOriginal }; + } + // dispatch function to recursively build the refactoring + // should be kept up to date with isFixablePromiseHandler in suggestionDiagnostics.ts + function transformExpression(node, transformer, outermostParent, prevArgName) { + if (!node) { + return ts.emptyArray; + } + var originalType = ts.isIdentifier(node) && transformer.originalTypeMap.get(ts.getNodeId(node).toString()); + var nodeType = originalType || transformer.checker.getTypeAtLocation(node); + if (ts.isCallExpression(node) && ts.hasPropertyAccessExpressionWithName(node, "then") && nodeType && !!transformer.checker.getPromisedTypeOfPromise(nodeType)) { + return transformThen(node, transformer, outermostParent, prevArgName); + } + else if (ts.isCallExpression(node) && ts.hasPropertyAccessExpressionWithName(node, "catch") && nodeType && !!transformer.checker.getPromisedTypeOfPromise(nodeType)) { + return transformCatch(node, transformer, prevArgName); + } + else if (ts.isPropertyAccessExpression(node)) { + return transformExpression(node.expression, transformer, outermostParent, prevArgName); + } + else if (nodeType && transformer.checker.getPromisedTypeOfPromise(nodeType)) { + return transformPromiseCall(node, transformer, prevArgName); + } + codeActionSucceeded = false; + return ts.emptyArray; + } + function transformCatch(node, transformer, prevArgName) { + var func = node.arguments[0]; + var argName = getArgName(func, transformer); + var shouldReturn = transformer.setOfExpressionsToReturn.get(ts.getNodeId(node).toString()); + /* + If there is another call in the chain after the .catch() we are transforming, we will need to save the result of both paths (try block and catch block) + To do this, we will need to synthesize a variable that we were not aware of while we were adding identifiers to the synthNamesMap + We will use the prevArgName and then update the synthNamesMap with a new variable name for the next transformation step + */ + if (prevArgName && !shouldReturn) { + prevArgName.numberOfAssignmentsOriginal = 2; // Try block and catch block + transformer.synthNamesMap.forEach(function (val, key) { + if (val.identifier.text === prevArgName.identifier.text) { + var newSynthName = createUniqueSynthName(prevArgName); + transformer.synthNamesMap.set(key, newSynthName); + } + }); + // update the constIdentifiers list + if (transformer.constIdentifiers.some(function (elem) { return elem.text === prevArgName.identifier.text; })) { + transformer.constIdentifiers.push(createUniqueSynthName(prevArgName).identifier); + } + } + var tryBlock = ts.createBlock(transformExpression(node.expression, transformer, node, prevArgName)); + var transformationBody = getTransformationBody(func, prevArgName, argName, node, transformer); + var catchArg = argName ? argName.identifier.text : "e"; + var catchClause = ts.createCatchClause(catchArg, ts.createBlock(transformationBody)); + /* + In order to avoid an implicit any, we will synthesize a type for the declaration using the unions of the types of both paths (try block and catch block) + */ + var varDeclList; + if (prevArgName && !shouldReturn) { + var typeArray = prevArgName.types; + var unionType = transformer.checker.getUnionType(typeArray, 2 /* Subtype */); + var unionTypeNode = transformer.isInJSFile ? undefined : transformer.checker.typeToTypeNode(unionType); + var varDecl = [ts.createVariableDeclaration(ts.getSynthesizedDeepClone(prevArgName.identifier), unionTypeNode)]; + varDeclList = ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList(varDecl, 1 /* Let */)); + } + var tryStatement = ts.createTry(tryBlock, catchClause, /*finallyBlock*/ undefined); + return varDeclList ? [varDeclList, tryStatement] : [tryStatement]; + } + function createUniqueSynthName(prevArgName) { + var renamedPrevArg = ts.createOptimisticUniqueName(prevArgName.identifier.text); + var newSynthName = { identifier: renamedPrevArg, types: [], numberOfAssignmentsOriginal: 0 }; + return newSynthName; + } + function transformThen(node, transformer, outermostParent, prevArgName) { + var _a = node.arguments, res = _a[0], rej = _a[1]; + if (!res) { + return transformExpression(node.expression, transformer, outermostParent); + } + var argNameRes = getArgName(res, transformer); + var transformationBody = getTransformationBody(res, prevArgName, argNameRes, node, transformer); + if (rej) { + var argNameRej = getArgName(rej, transformer); + var tryBlock = ts.createBlock(transformExpression(node.expression, transformer, node, argNameRes).concat(transformationBody)); + var transformationBody2 = getTransformationBody(rej, prevArgName, argNameRej, node, transformer); + var catchArg = argNameRej ? argNameRej.identifier.text : "e"; + var catchClause = ts.createCatchClause(catchArg, ts.createBlock(transformationBody2)); + return [ts.createTry(tryBlock, catchClause, /* finallyBlock */ undefined)]; + } + return transformExpression(node.expression, transformer, node, argNameRes).concat(transformationBody); + } + function getFlagOfIdentifier(node, constIdentifiers) { + var inArr = constIdentifiers.some(function (elem) { return elem.text === node.text; }); + return inArr ? 2 /* Const */ : 1 /* Let */; + } + function transformPromiseCall(node, transformer, prevArgName) { + var shouldReturn = transformer.setOfExpressionsToReturn.get(ts.getNodeId(node).toString()); + // the identifier is empty when the handler (.then()) ignores the argument - In this situation we do not need to save the result of the promise returning call + var originalNodeParent = node.original ? node.original.parent : node.parent; + if (prevArgName && !shouldReturn && (!originalNodeParent || ts.isPropertyAccessExpression(originalNodeParent))) { + return createTransformedStatement(prevArgName, ts.createAwait(node), transformer); + } + else if (!prevArgName && !shouldReturn && (!originalNodeParent || ts.isPropertyAccessExpression(originalNodeParent))) { + return [ts.createStatement(ts.createAwait(node))]; + } + return [ts.createReturn(ts.getSynthesizedDeepClone(node))]; + } + function createTransformedStatement(prevArgName, rightHandSide, transformer) { + if (!prevArgName || prevArgName.identifier.text.length === 0) { + // if there's no argName to assign to, there still might be side effects + return [ts.createStatement(rightHandSide)]; + } + if (prevArgName.types.length < prevArgName.numberOfAssignmentsOriginal) { + // if the variable has already been declared, we don't need "let" or "const" + return [ts.createStatement(ts.createAssignment(ts.getSynthesizedDeepClone(prevArgName.identifier), rightHandSide))]; + } + return [ts.createVariableStatement(/*modifiers*/ undefined, (ts.createVariableDeclarationList([ts.createVariableDeclaration(ts.getSynthesizedDeepClone(prevArgName.identifier), /*type*/ undefined, rightHandSide)], getFlagOfIdentifier(prevArgName.identifier, transformer.constIdentifiers))))]; + } + // should be kept up to date with isFixablePromiseArgument in suggestionDiagnostics.ts + function getTransformationBody(func, prevArgName, argName, parent, transformer) { + var shouldReturn = transformer.setOfExpressionsToReturn.get(ts.getNodeId(parent).toString()); + switch (func.kind) { + case 96 /* NullKeyword */: + // do not produce a transformed statement for a null argument + break; + case 72 /* Identifier */: // identifier includes undefined + if (!argName) { + // undefined was argument passed to promise handler + break; + } + var synthCall = ts.createCall(ts.getSynthesizedDeepClone(func), /*typeArguments*/ undefined, [argName.identifier]); + if (shouldReturn) { + return [ts.createReturn(synthCall)]; + } + var type = transformer.originalTypeMap.get(ts.getNodeId(func).toString()) || transformer.checker.getTypeAtLocation(func); + var callSignatures = transformer.checker.getSignaturesOfType(type, 0 /* Call */); + if (!callSignatures.length) { + // if identifier in handler has no call signatures, it's invalid + codeActionSucceeded = false; + break; + } + var returnType = callSignatures[0].getReturnType(); + var varDeclOrAssignment = createTransformedStatement(prevArgName, ts.createAwait(synthCall), transformer); + if (prevArgName) { + prevArgName.types.push(returnType); + } + return varDeclOrAssignment; + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: { + var funcBody = func.body; + // Arrow functions with block bodies { } will enter this control flow + if (ts.isBlock(funcBody)) { + var refactoredStmts = []; + var seenReturnStatement = false; + for (var _i = 0, _a = funcBody.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + if (ts.isReturnStatement(statement)) { + seenReturnStatement = true; + } + if (ts.isReturnStatementWithFixablePromiseHandler(statement)) { + refactoredStmts = refactoredStmts.concat(getInnerTransformationBody(transformer, [statement], prevArgName)); + } + else { + refactoredStmts.push(statement); + } + } + return shouldReturn ? refactoredStmts.map(function (s) { return ts.getSynthesizedDeepClone(s); }) : + removeReturns(refactoredStmts, prevArgName === undefined ? undefined : prevArgName.identifier, transformer, seenReturnStatement); + } + else { + var innerRetStmts = ts.isFixablePromiseHandler(funcBody) ? [ts.createReturn(funcBody)] : ts.emptyArray; + var innerCbBody = getInnerTransformationBody(transformer, innerRetStmts, prevArgName); + if (innerCbBody.length > 0) { + return innerCbBody; + } + var type_1 = transformer.checker.getTypeAtLocation(func); + var returnType_1 = getLastCallSignature(type_1, transformer.checker).getReturnType(); + var rightHandSide = ts.getSynthesizedDeepClone(funcBody); + var possiblyAwaitedRightHandSide = !!transformer.checker.getPromisedTypeOfPromise(returnType_1) ? ts.createAwait(rightHandSide) : rightHandSide; + if (!shouldReturn) { + var transformedStatement = createTransformedStatement(prevArgName, possiblyAwaitedRightHandSide, transformer); + if (prevArgName) { + prevArgName.types.push(returnType_1); + } + return transformedStatement; + } + else { + return [ts.createReturn(possiblyAwaitedRightHandSide)]; + } + } + } + default: + // If no cases apply, we've found a transformation body we don't know how to handle, so the refactoring should no-op to avoid deleting code. + codeActionSucceeded = false; + break; + } + return ts.emptyArray; + } + function getLastCallSignature(type, checker) { + var callSignatures = checker.getSignaturesOfType(type, 0 /* Call */); + return ts.lastOrUndefined(callSignatures); + } + function removeReturns(stmts, prevArgName, transformer, seenReturnStatement) { + var ret = []; + for (var _i = 0, stmts_1 = stmts; _i < stmts_1.length; _i++) { + var stmt = stmts_1[_i]; + if (ts.isReturnStatement(stmt)) { + if (stmt.expression) { + var possiblyAwaitedExpression = isPromiseReturningExpression(stmt.expression, transformer.checker) ? ts.createAwait(stmt.expression) : stmt.expression; + if (prevArgName === undefined) { + ret.push(ts.createExpressionStatement(possiblyAwaitedExpression)); + } + else { + ret.push(ts.createVariableStatement(/*modifiers*/ undefined, (ts.createVariableDeclarationList([ts.createVariableDeclaration(prevArgName, /*type*/ undefined, possiblyAwaitedExpression)], getFlagOfIdentifier(prevArgName, transformer.constIdentifiers))))); + } + } + } + else { + ret.push(ts.getSynthesizedDeepClone(stmt)); + } + } + // if block has no return statement, need to define prevArgName as undefined to prevent undeclared variables + if (!seenReturnStatement && prevArgName !== undefined) { + ret.push(ts.createVariableStatement(/*modifiers*/ undefined, (ts.createVariableDeclarationList([ts.createVariableDeclaration(prevArgName, /*type*/ undefined, ts.createIdentifier("undefined"))], getFlagOfIdentifier(prevArgName, transformer.constIdentifiers))))); + } + return ret; + } + function getInnerTransformationBody(transformer, innerRetStmts, prevArgName) { + var innerCbBody = []; + for (var _i = 0, innerRetStmts_1 = innerRetStmts; _i < innerRetStmts_1.length; _i++) { + var stmt = innerRetStmts_1[_i]; + ts.forEachChild(stmt, function visit(node) { + if (ts.isCallExpression(node)) { + var temp = transformExpression(node, transformer, node, prevArgName); + innerCbBody = innerCbBody.concat(temp); + if (innerCbBody.length > 0) { + return; + } + } + else if (!ts.isFunctionLike(node)) { + ts.forEachChild(node, visit); + } + }); + } + return innerCbBody; + } + function getArgName(funcNode, transformer) { + var numberOfAssignmentsOriginal = 0; + var types = []; + var name; + if (ts.isFunctionLikeDeclaration(funcNode)) { + if (funcNode.parameters.length > 0) { + var param = funcNode.parameters[0].name; + name = getMapEntryOrDefault(param); + } + } + else if (ts.isIdentifier(funcNode)) { + name = getMapEntryOrDefault(funcNode); + } + // return undefined argName when arg is null or undefined + if (!name || name.identifier.text === "undefined") { + return undefined; + } + return name; + function getMapEntryOrDefault(identifier) { + var originalNode = getOriginalNode(identifier); + var symbol = getSymbol(originalNode); + if (!symbol) { + return { identifier: identifier, types: types, numberOfAssignmentsOriginal: numberOfAssignmentsOriginal }; + } + var mapEntry = transformer.synthNamesMap.get(ts.getSymbolId(symbol).toString()); + return mapEntry || { identifier: identifier, types: types, numberOfAssignmentsOriginal: numberOfAssignmentsOriginal }; + } + function getSymbol(node) { + return node.symbol ? node.symbol : transformer.checker.getSymbolAtLocation(node); + } + function getOriginalNode(node) { + return node.original ? node.original : node; + } + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + codefix.registerCodeFix({ + errorCodes: [ts.Diagnostics.File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module.code], + getCodeActions: function (context) { + var sourceFile = context.sourceFile, program = context.program, preferences = context.preferences; + var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { + var moduleExportsChangedToDefault = convertFileToEs6Module(sourceFile, program.getTypeChecker(), changes, program.getCompilerOptions().target, ts.getQuotePreference(sourceFile, preferences)); + if (moduleExportsChangedToDefault) { + for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { + var importingFile = _a[_i]; + fixImportOfModuleExports(importingFile, sourceFile, changes, ts.getQuotePreference(importingFile, preferences)); + } + } + }); + // No support for fix-all since this applies to the whole file at once anyway. + return [codefix.createCodeFixActionNoFixId("convertToEs6Module", changes, ts.Diagnostics.Convert_to_ES6_module)]; + }, + }); + function fixImportOfModuleExports(importingFile, exportingFile, changes, quotePreference) { + for (var _i = 0, _a = importingFile.imports; _i < _a.length; _i++) { + var moduleSpecifier = _a[_i]; + var imported = ts.getResolvedModule(importingFile, moduleSpecifier.text); + if (!imported || imported.resolvedFileName !== exportingFile.fileName) { + continue; + } + var importNode = ts.importFromModuleSpecifier(moduleSpecifier); + switch (importNode.kind) { + case 248 /* ImportEqualsDeclaration */: + changes.replaceNode(importingFile, importNode, ts.makeImport(importNode.name, /*namedImports*/ undefined, moduleSpecifier, quotePreference)); + break; + case 191 /* CallExpression */: + if (ts.isRequireCall(importNode, /*checkArgumentIsStringLiteralLike*/ false)) { + changes.replaceNode(importingFile, importNode, ts.createPropertyAccess(ts.getSynthesizedDeepClone(importNode), "default")); + } + break; + } + } + } + /** @returns Whether we converted a `module.exports =` to a default export. */ + function convertFileToEs6Module(sourceFile, checker, changes, target, quotePreference) { + var identifiers = { original: collectFreeIdentifiers(sourceFile), additional: ts.createMap() }; + var exports = collectExportRenames(sourceFile, checker, identifiers); + convertExportsAccesses(sourceFile, exports, changes); + var moduleExportsChangedToDefault = false; + for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + var moduleExportsChanged = convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports, quotePreference); + moduleExportsChangedToDefault = moduleExportsChangedToDefault || moduleExportsChanged; + } + return moduleExportsChangedToDefault; + } + function collectExportRenames(sourceFile, checker, identifiers) { + var res = ts.createMap(); + forEachExportReference(sourceFile, function (node) { + var _a = node.name, text = _a.text, originalKeywordKind = _a.originalKeywordKind; + if (!res.has(text) && (originalKeywordKind !== undefined && ts.isNonContextualKeyword(originalKeywordKind) + || checker.resolveName(node.name.text, node, 67220415 /* Value */, /*excludeGlobals*/ true))) { + // Unconditionally add an underscore in case `text` is a keyword. + res.set(text, makeUniqueName("_" + text, identifiers)); + } + }); + return res; + } + function convertExportsAccesses(sourceFile, exports, changes) { + forEachExportReference(sourceFile, function (node, isAssignmentLhs) { + if (isAssignmentLhs) { + return; + } + var text = node.name.text; + changes.replaceNode(sourceFile, node, ts.createIdentifier(exports.get(text) || text)); + }); + } + function forEachExportReference(sourceFile, cb) { + sourceFile.forEachChild(function recur(node) { + if (ts.isPropertyAccessExpression(node) && ts.isExportsOrModuleExportsOrAlias(sourceFile, node.expression)) { + var parent = node.parent; + cb(node, ts.isBinaryExpression(parent) && parent.left === node && parent.operatorToken.kind === 59 /* EqualsToken */); + } + node.forEachChild(recur); + }); + } + function convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports, quotePreference) { + switch (statement.kind) { + case 219 /* VariableStatement */: + convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target, quotePreference); + return false; + case 221 /* ExpressionStatement */: { + var expression = statement.expression; + switch (expression.kind) { + case 191 /* CallExpression */: { + if (ts.isRequireCall(expression, /*checkArgumentIsStringLiteralLike*/ true)) { + // For side-effecting require() call, just make a side-effecting import. + changes.replaceNode(sourceFile, statement, ts.makeImport(/*name*/ undefined, /*namedImports*/ undefined, expression.arguments[0], quotePreference)); + } + return false; + } + case 204 /* BinaryExpression */: { + var operatorToken = expression.operatorToken; + return operatorToken.kind === 59 /* EqualsToken */ && convertAssignment(sourceFile, checker, expression, changes, exports); + } + } + } + // falls through + default: + return false; + } + } + function convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target, quotePreference) { + var declarationList = statement.declarationList; + var foundImport = false; + var newNodes = ts.flatMap(declarationList.declarations, function (decl) { + var name = decl.name, initializer = decl.initializer; + if (initializer) { + if (ts.isExportsOrModuleExportsOrAlias(sourceFile, initializer)) { + // `const alias = module.exports;` can be removed. + foundImport = true; + return []; + } + else if (ts.isRequireCall(initializer, /*checkArgumentIsStringLiteralLike*/ true)) { + foundImport = true; + return convertSingleImport(sourceFile, name, initializer.arguments[0], changes, checker, identifiers, target, quotePreference); + } + else if (ts.isPropertyAccessExpression(initializer) && ts.isRequireCall(initializer.expression, /*checkArgumentIsStringLiteralLike*/ true)) { + foundImport = true; + return convertPropertyAccessImport(name, initializer.name.text, initializer.expression.arguments[0], identifiers, quotePreference); + } + } + // Move it out to its own variable statement. (This will not be used if `!foundImport`) + return ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([decl], declarationList.flags)); + }); + if (foundImport) { + // useNonAdjustedEndPosition to ensure we don't eat the newline after the statement. + changes.replaceNodeWithNodes(sourceFile, statement, newNodes); + } + } + /** Converts `const name = require("moduleSpecifier").propertyName` */ + function convertPropertyAccessImport(name, propertyName, moduleSpecifier, identifiers, quotePreference) { + switch (name.kind) { + case 184 /* ObjectBindingPattern */: + case 185 /* ArrayBindingPattern */: { + // `const [a, b] = require("c").d` --> `import { d } from "c"; const [a, b] = d;` + var tmp = makeUniqueName(propertyName, identifiers); + return [ + makeSingleImport(tmp, propertyName, moduleSpecifier, quotePreference), + makeConst(/*modifiers*/ undefined, name, ts.createIdentifier(tmp)), + ]; + } + case 72 /* Identifier */: + // `const a = require("b").c` --> `import { c as a } from "./b"; + return [makeSingleImport(name.text, propertyName, moduleSpecifier, quotePreference)]; + default: + return ts.Debug.assertNever(name); + } + } + function convertAssignment(sourceFile, checker, assignment, changes, exports) { + var left = assignment.left, right = assignment.right; + if (!ts.isPropertyAccessExpression(left)) { + return false; + } + if (ts.isExportsOrModuleExportsOrAlias(sourceFile, left)) { + if (ts.isExportsOrModuleExportsOrAlias(sourceFile, right)) { + // `const alias = module.exports;` or `module.exports = alias;` can be removed. + changes.delete(sourceFile, assignment.parent); + } + else { + var replacement = ts.isObjectLiteralExpression(right) ? tryChangeModuleExportsObject(right) + : ts.isRequireCall(right, /*checkArgumentIsStringLiteralLike*/ true) ? convertReExportAll(right.arguments[0], checker) + : undefined; + if (replacement) { + changes.replaceNodeWithNodes(sourceFile, assignment.parent, replacement[0]); + return replacement[1]; + } + else { + changes.replaceRangeWithText(sourceFile, ts.createRange(left.getStart(sourceFile), right.pos), "export default"); + return true; + } + } + } + else if (ts.isExportsOrModuleExportsOrAlias(sourceFile, left.expression)) { + convertNamedExport(sourceFile, assignment, changes, exports); + } + return false; + } + /** + * Convert `module.exports = { ... }` to individual exports.. + * We can't always do this if the module has interesting members -- then it will be a default export instead. + */ + function tryChangeModuleExportsObject(object) { + var statements = ts.mapAllOrFail(object.properties, function (prop) { + switch (prop.kind) { + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + // TODO: Maybe we should handle this? See fourslash test `refactorConvertToEs6Module_export_object_shorthand.ts`. + case 276 /* ShorthandPropertyAssignment */: + case 277 /* SpreadAssignment */: + return undefined; + case 275 /* PropertyAssignment */: + return !ts.isIdentifier(prop.name) ? undefined : convertExportsDotXEquals_replaceNode(prop.name.text, prop.initializer); + case 156 /* MethodDeclaration */: + return !ts.isIdentifier(prop.name) ? undefined : functionExpressionToDeclaration(prop.name.text, [ts.createToken(85 /* ExportKeyword */)], prop); + default: + ts.Debug.assertNever(prop); + } + }); + return statements && [statements, false]; + } + function convertNamedExport(sourceFile, assignment, changes, exports) { + // If "originalKeywordKind" was set, this is e.g. `exports. + var text = assignment.left.name.text; + var rename = exports.get(text); + if (rename !== undefined) { + /* + const _class = 0; + export { _class as class }; + */ + var newNodes = [ + makeConst(/*modifiers*/ undefined, rename, assignment.right), + makeExportDeclaration([ts.createExportSpecifier(rename, text)]), + ]; + changes.replaceNodeWithNodes(sourceFile, assignment.parent, newNodes); + } + else { + convertExportsPropertyAssignment(assignment, sourceFile, changes); + } + } + function convertReExportAll(reExported, checker) { + // `module.exports = require("x");` ==> `export * from "x"; export { default } from "x";` + var moduleSpecifier = reExported.text; + var moduleSymbol = checker.getSymbolAtLocation(reExported); + var exports = moduleSymbol ? moduleSymbol.exports : ts.emptyUnderscoreEscapedMap; + return exports.has("export=") + ? [[reExportDefault(moduleSpecifier)], true] + : !exports.has("default") + ? [[reExportStar(moduleSpecifier)], false] + // If there's some non-default export, must include both `export *` and `export default`. + : exports.size > 1 ? [[reExportStar(moduleSpecifier), reExportDefault(moduleSpecifier)], true] : [[reExportDefault(moduleSpecifier)], true]; + } + function reExportStar(moduleSpecifier) { + return makeExportDeclaration(/*exportClause*/ undefined, moduleSpecifier); + } + function reExportDefault(moduleSpecifier) { + return makeExportDeclaration([ts.createExportSpecifier(/*propertyName*/ undefined, "default")], moduleSpecifier); + } + function convertExportsPropertyAssignment(_a, sourceFile, changes) { + var left = _a.left, right = _a.right, parent = _a.parent; + var name = left.name.text; + if ((ts.isFunctionExpression(right) || ts.isArrowFunction(right) || ts.isClassExpression(right)) && (!right.name || right.name.text === name)) { + // `exports.f = function() {}` -> `export function f() {}` -- Replace `exports.f = ` with `export `, and insert the name after `function`. + changes.replaceRange(sourceFile, { pos: left.getStart(sourceFile), end: right.getStart(sourceFile) }, ts.createToken(85 /* ExportKeyword */), { suffix: " " }); + if (!right.name) + changes.insertName(sourceFile, right, name); + var semi = ts.findChildOfKind(parent, 26 /* SemicolonToken */, sourceFile); + if (semi) + changes.delete(sourceFile, semi); + } + else { + // `exports.f = function g() {}` -> `export const f = function g() {}` -- just replace `exports.` with `export const ` + changes.replaceNodeRangeWithNodes(sourceFile, left.expression, ts.findChildOfKind(left, 24 /* DotToken */, sourceFile), [ts.createToken(85 /* ExportKeyword */), ts.createToken(77 /* ConstKeyword */)], { joiner: " ", suffix: " " }); + } + } + // TODO: GH#22492 this will cause an error if a change has been made inside the body of the node. + function convertExportsDotXEquals_replaceNode(name, exported) { + var modifiers = [ts.createToken(85 /* ExportKeyword */)]; + switch (exported.kind) { + case 196 /* FunctionExpression */: { + var expressionName = exported.name; + if (expressionName && expressionName.text !== name) { + // `exports.f = function g() {}` -> `export const f = function g() {}` + return exportConst(); + } + } + // falls through + case 197 /* ArrowFunction */: + // `exports.f = function() {}` --> `export function f() {}` + return functionExpressionToDeclaration(name, modifiers, exported); + case 209 /* ClassExpression */: + // `exports.C = class {}` --> `export class C {}` + return classExpressionToDeclaration(name, modifiers, exported); + default: + return exportConst(); + } + function exportConst() { + // `exports.x = 0;` --> `export const x = 0;` + return makeConst(modifiers, ts.createIdentifier(name), exported); // TODO: GH#18217 + } + } + /** + * Converts `const <> = require("x");`. + * Returns nodes that will replace the variable declaration for the commonjs import. + * May also make use `changes` to remove qualifiers at the use sites of imports, to change `mod.x` to `x`. + */ + function convertSingleImport(file, name, moduleSpecifier, changes, checker, identifiers, target, quotePreference) { + switch (name.kind) { + case 184 /* ObjectBindingPattern */: { + var importSpecifiers = ts.mapAllOrFail(name.elements, function (e) { + return e.dotDotDotToken || e.initializer || e.propertyName && !ts.isIdentifier(e.propertyName) || !ts.isIdentifier(e.name) + ? undefined + : makeImportSpecifier(e.propertyName && e.propertyName.text, e.name.text); + }); // tslint:disable-line no-unnecessary-type-assertion (TODO: GH#18217) + if (importSpecifiers) { + return [ts.makeImport(/*name*/ undefined, importSpecifiers, moduleSpecifier, quotePreference)]; + } + } + // falls through -- object destructuring has an interesting pattern and must be a variable declaration + case 185 /* ArrayBindingPattern */: { + /* + import x from "x"; + const [a, b, c] = x; + */ + var tmp = makeUniqueName(codefix.moduleSpecifierToValidIdentifier(moduleSpecifier.text, target), identifiers); + return [ + ts.makeImport(ts.createIdentifier(tmp), /*namedImports*/ undefined, moduleSpecifier, quotePreference), + makeConst(/*modifiers*/ undefined, ts.getSynthesizedDeepClone(name), ts.createIdentifier(tmp)), + ]; + } + case 72 /* Identifier */: + return convertSingleIdentifierImport(file, name, moduleSpecifier, changes, checker, identifiers, quotePreference); + default: + return ts.Debug.assertNever(name); + } + } + /** + * Convert `import x = require("x").` + * Also converts uses like `x.y()` to `y()` and uses a named import. + */ + function convertSingleIdentifierImport(file, name, moduleSpecifier, changes, checker, identifiers, quotePreference) { + var nameSymbol = checker.getSymbolAtLocation(name); + // Maps from module property name to name actually used. (The same if there isn't shadowing.) + var namedBindingsNames = ts.createMap(); + // True if there is some non-property use like `x()` or `f(x)`. + var needDefaultImport = false; + for (var _i = 0, _a = identifiers.original.get(name.text); _i < _a.length; _i++) { + var use = _a[_i]; + if (checker.getSymbolAtLocation(use) !== nameSymbol || use === name) { + // This was a use of a different symbol with the same name, due to shadowing. Ignore. + continue; + } + var parent = use.parent; + if (ts.isPropertyAccessExpression(parent)) { + var expression = parent.expression, propertyName = parent.name.text; + ts.Debug.assert(expression === use); // Else shouldn't have been in `collectIdentifiers` + var idName = namedBindingsNames.get(propertyName); + if (idName === undefined) { + idName = makeUniqueName(propertyName, identifiers); + namedBindingsNames.set(propertyName, idName); + } + changes.replaceNode(file, parent, ts.createIdentifier(idName)); + } + else { + needDefaultImport = true; + } + } + var namedBindings = namedBindingsNames.size === 0 ? undefined : ts.arrayFrom(ts.mapIterator(namedBindingsNames.entries(), function (_a) { + var propertyName = _a[0], idName = _a[1]; + return ts.createImportSpecifier(propertyName === idName ? undefined : ts.createIdentifier(propertyName), ts.createIdentifier(idName)); + })); + if (!namedBindings) { + // If it was unused, ensure that we at least import *something*. + needDefaultImport = true; + } + return [ts.makeImport(needDefaultImport ? ts.getSynthesizedDeepClone(name) : undefined, namedBindings, moduleSpecifier, quotePreference)]; + } + // Identifiers helpers + function makeUniqueName(name, identifiers) { + while (identifiers.original.has(name) || identifiers.additional.has(name)) { + name = "_" + name; + } + identifiers.additional.set(name, true); + return name; + } + function collectFreeIdentifiers(file) { + var map = ts.createMultiMap(); + forEachFreeIdentifier(file, function (id) { return map.add(id.text, id); }); + return map; + } + /** + * A free identifier is an identifier that can be accessed through name lookup as a local variable. + * In the expression `x.y`, `x` is a free identifier, but `y` is not. + */ + function forEachFreeIdentifier(node, cb) { + if (ts.isIdentifier(node) && isFreeIdentifier(node)) + cb(node); + node.forEachChild(function (child) { return forEachFreeIdentifier(child, cb); }); + } + function isFreeIdentifier(node) { + var parent = node.parent; + switch (parent.kind) { + case 189 /* PropertyAccessExpression */: + return parent.name !== node; + case 186 /* BindingElement */: + return parent.propertyName !== node; + case 253 /* ImportSpecifier */: + return parent.propertyName !== node; + default: + return true; + } + } + // Node helpers + function functionExpressionToDeclaration(name, additionalModifiers, fn) { + return ts.createFunctionDeclaration(ts.getSynthesizedDeepClones(fn.decorators), // TODO: GH#19915 Don't think this is even legal. + ts.concatenate(additionalModifiers, ts.getSynthesizedDeepClones(fn.modifiers)), ts.getSynthesizedDeepClone(fn.asteriskToken), name, ts.getSynthesizedDeepClones(fn.typeParameters), ts.getSynthesizedDeepClones(fn.parameters), ts.getSynthesizedDeepClone(fn.type), ts.convertToFunctionBody(ts.getSynthesizedDeepClone(fn.body))); + } + function classExpressionToDeclaration(name, additionalModifiers, cls) { + return ts.createClassDeclaration(ts.getSynthesizedDeepClones(cls.decorators), // TODO: GH#19915 Don't think this is even legal. + ts.concatenate(additionalModifiers, ts.getSynthesizedDeepClones(cls.modifiers)), name, ts.getSynthesizedDeepClones(cls.typeParameters), ts.getSynthesizedDeepClones(cls.heritageClauses), ts.getSynthesizedDeepClones(cls.members)); + } + function makeSingleImport(localName, propertyName, moduleSpecifier, quotePreference) { + return propertyName === "default" + ? ts.makeImport(ts.createIdentifier(localName), /*namedImports*/ undefined, moduleSpecifier, quotePreference) + : ts.makeImport(/*name*/ undefined, [makeImportSpecifier(propertyName, localName)], moduleSpecifier, quotePreference); + } + function makeImportSpecifier(propertyName, name) { + return ts.createImportSpecifier(propertyName !== undefined && propertyName !== name ? ts.createIdentifier(propertyName) : undefined, ts.createIdentifier(name)); + } + function makeConst(modifiers, name, init) { + return ts.createVariableStatement(modifiers, ts.createVariableDeclarationList([ts.createVariableDeclaration(name, /*type*/ undefined, init)], 2 /* Const */)); + } + function makeExportDeclaration(exportSpecifiers, moduleSpecifier) { + return ts.createExportDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, exportSpecifiers && ts.createNamedExports(exportSpecifiers), moduleSpecifier === undefined ? undefined : ts.createLiteral(moduleSpecifier)); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "correctQualifiedNameToIndexedAccessType"; + var errorCodes = [ts.Diagnostics.Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_property_1_in_0_with_0_1.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var qualifiedName = getQualifiedName(context.sourceFile, context.span.start); + if (!qualifiedName) + return undefined; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, context.sourceFile, qualifiedName); }); + var newText = qualifiedName.left.text + "[\"" + qualifiedName.right.text + "\"]"; + return [codefix.createCodeFixAction(fixId, changes, [ts.Diagnostics.Rewrite_as_the_indexed_access_type_0, newText], fixId, ts.Diagnostics.Rewrite_all_as_indexed_access_types)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var q = getQualifiedName(diag.file, diag.start); + if (q) { + doChange(changes, diag.file, q); + } + }); }, + }); + function getQualifiedName(sourceFile, pos) { + var qualifiedName = ts.findAncestor(ts.getTokenAtPosition(sourceFile, pos), ts.isQualifiedName); + ts.Debug.assert(!!qualifiedName, "Expected position to be owned by a qualified name."); + return ts.isIdentifier(qualifiedName.left) ? qualifiedName : undefined; + } + function doChange(changeTracker, sourceFile, qualifiedName) { + var rightText = qualifiedName.right.text; + var replacement = ts.createIndexedAccessTypeNode(ts.createTypeReferenceNode(qualifiedName.left, /*typeArguments*/ undefined), ts.createLiteralTypeNode(ts.createLiteral(rightText))); + changeTracker.replaceNode(sourceFile, qualifiedName, replacement); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var errorCodes = [ts.Diagnostics.Class_0_incorrectly_implements_interface_1.code, + ts.Diagnostics.Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass.code]; + var fixId = "fixClassIncorrectlyImplementsInterface"; // TODO: share a group with fixClassDoesntImplementInheritedAbstractMember? + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var program = context.program, sourceFile = context.sourceFile, span = context.span; + var classDeclaration = getClass(sourceFile, span.start); + var checker = program.getTypeChecker(); + return ts.mapDefined(ts.getClassImplementsHeritageClauseElements(classDeclaration), function (implementedTypeNode) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMissingDeclarations(checker, implementedTypeNode, sourceFile, classDeclaration, t, context.preferences); }); + return changes.length === 0 ? undefined : codefix.createCodeFixAction(fixId, changes, [ts.Diagnostics.Implement_interface_0, implementedTypeNode.getText(sourceFile)], fixId, ts.Diagnostics.Implement_all_unimplemented_interfaces); + }); + }, + fixIds: [fixId], + getAllCodeActions: function (context) { + var seenClassDeclarations = ts.createMap(); + return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var classDeclaration = getClass(diag.file, diag.start); + if (ts.addToSeen(seenClassDeclarations, ts.getNodeId(classDeclaration))) { + for (var _i = 0, _a = ts.getClassImplementsHeritageClauseElements(classDeclaration); _i < _a.length; _i++) { + var implementedTypeNode = _a[_i]; + addMissingDeclarations(context.program.getTypeChecker(), implementedTypeNode, diag.file, classDeclaration, changes, context.preferences); + } + } + }); + }, + }); + function getClass(sourceFile, pos) { + return ts.Debug.assertDefined(ts.getContainingClass(ts.getTokenAtPosition(sourceFile, pos))); + } + function symbolPointsToNonPrivateMember(symbol) { + return !(ts.getModifierFlags(symbol.valueDeclaration) & 8 /* Private */); + } + function addMissingDeclarations(checker, implementedTypeNode, sourceFile, classDeclaration, changeTracker, preferences) { + var maybeHeritageClauseSymbol = getHeritageClauseSymbolTable(classDeclaration, checker); + // Note that this is ultimately derived from a map indexed by symbol names, + // so duplicates cannot occur. + var implementedType = checker.getTypeAtLocation(implementedTypeNode); + var implementedTypeSymbols = checker.getPropertiesOfType(implementedType); + var nonPrivateAndNotExistedInHeritageClauseMembers = implementedTypeSymbols.filter(ts.and(symbolPointsToNonPrivateMember, function (symbol) { return !maybeHeritageClauseSymbol.has(symbol.escapedName); })); + var classType = checker.getTypeAtLocation(classDeclaration); + if (!classType.getNumberIndexType()) { + createMissingIndexSignatureDeclaration(implementedType, 1 /* Number */); + } + if (!classType.getStringIndexType()) { + createMissingIndexSignatureDeclaration(implementedType, 0 /* String */); + } + codefix.createMissingMemberNodes(classDeclaration, nonPrivateAndNotExistedInHeritageClauseMembers, checker, preferences, function (member) { return changeTracker.insertNodeAtClassStart(sourceFile, classDeclaration, member); }); + function createMissingIndexSignatureDeclaration(type, kind) { + var indexInfoOfKind = checker.getIndexInfoOfType(type, kind); + if (indexInfoOfKind) { + changeTracker.insertNodeAtClassStart(sourceFile, classDeclaration, checker.indexInfoToIndexSignatureDeclaration(indexInfoOfKind, kind, classDeclaration)); + } + } + } + function getHeritageClauseSymbolTable(classDeclaration, checker) { + var heritageClauseNode = ts.getEffectiveBaseTypeNode(classDeclaration); + if (!heritageClauseNode) + return ts.createSymbolTable(); + var heritageClauseType = checker.getTypeAtLocation(heritageClauseNode); + var heritageClauseTypeSymbols = checker.getPropertiesOfType(heritageClauseType); + return ts.createSymbolTable(heritageClauseTypeSymbols.filter(symbolPointsToNonPrivateMember)); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + codefix.importFixId = "fixMissingImport"; + var errorCodes = [ + ts.Diagnostics.Cannot_find_name_0.code, + ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1.code, + ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0.code, + ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_static_member_1_0.code, + ts.Diagnostics.Cannot_find_namespace_0.code, + ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code, + ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here.code, + ]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var errorCode = context.errorCode, preferences = context.preferences, sourceFile = context.sourceFile, span = context.span; + var info = getFixesInfo(context, errorCode, span.start); + if (!info) + return undefined; + var fixes = info.fixes, symbolName = info.symbolName; + var quotePreference = ts.getQuotePreference(sourceFile, preferences); + return fixes.map(function (fix) { return codeActionForFix(context, sourceFile, symbolName, fix, quotePreference); }); + }, + fixIds: [codefix.importFixId], + getAllCodeActions: function (context) { + var sourceFile = context.sourceFile, preferences = context.preferences; + // Namespace fixes don't conflict, so just build a list. + var addToNamespace = []; + var importType = []; + // Keys are import clause node IDs. + var addToExisting = ts.createMap(); + // Keys are module specifiers. + var newImports = ts.createMap(); + codefix.eachDiagnostic(context, errorCodes, function (diag) { + var info = getFixesInfo(context, diag.code, diag.start); + if (!info || !info.fixes.length) + return; + var fixes = info.fixes, symbolName = info.symbolName; + var fix = ts.first(fixes); + switch (fix.kind) { + case 0 /* UseNamespace */: + addToNamespace.push(fix); + break; + case 1 /* ImportType */: + importType.push(fix); + break; + case 2 /* AddToExisting */: { + var importClause = fix.importClause, importKind = fix.importKind; + var key = String(ts.getNodeId(importClause)); + var entry = addToExisting.get(key); + if (!entry) { + addToExisting.set(key, entry = { importClause: importClause, defaultImport: undefined, namedImports: [] }); + } + if (importKind === 0 /* Named */) { + ts.pushIfUnique(entry.namedImports, symbolName); + } + else { + ts.Debug.assert(entry.defaultImport === undefined || entry.defaultImport === symbolName); + entry.defaultImport = symbolName; + } + break; + } + case 3 /* AddNew */: { + var moduleSpecifier = fix.moduleSpecifier, importKind = fix.importKind; + var entry = newImports.get(moduleSpecifier); + if (!entry) { + newImports.set(moduleSpecifier, entry = { defaultImport: undefined, namedImports: [], namespaceLikeImport: undefined }); + } + switch (importKind) { + case 1 /* Default */: + ts.Debug.assert(entry.defaultImport === undefined || entry.defaultImport === symbolName); + entry.defaultImport = symbolName; + break; + case 0 /* Named */: + ts.pushIfUnique(entry.namedImports, symbolName); + break; + case 3 /* Equals */: + case 2 /* Namespace */: + ts.Debug.assert(entry.namespaceLikeImport === undefined || entry.namespaceLikeImport.name === symbolName); + entry.namespaceLikeImport = { importKind: importKind, name: symbolName }; + break; + } + break; + } + default: + ts.Debug.assertNever(fix); + } + }); + return codefix.createCombinedCodeActions(ts.textChanges.ChangeTracker.with(context, function (changes) { + var quotePreference = ts.getQuotePreference(sourceFile, preferences); + for (var _i = 0, addToNamespace_1 = addToNamespace; _i < addToNamespace_1.length; _i++) { + var fix = addToNamespace_1[_i]; + addNamespaceQualifier(changes, sourceFile, fix); + } + for (var _a = 0, importType_1 = importType; _a < importType_1.length; _a++) { + var fix = importType_1[_a]; + addImportType(changes, sourceFile, fix, quotePreference); + } + addToExisting.forEach(function (_a) { + var importClause = _a.importClause, defaultImport = _a.defaultImport, namedImports = _a.namedImports; + doAddExistingFix(changes, sourceFile, importClause, defaultImport, namedImports); + }); + newImports.forEach(function (imports, moduleSpecifier) { + addNewImports(changes, sourceFile, moduleSpecifier, quotePreference, imports); + }); + })); + }, + }); + // Sorted with the preferred fix coming first. + var ImportFixKind; + (function (ImportFixKind) { + ImportFixKind[ImportFixKind["UseNamespace"] = 0] = "UseNamespace"; + ImportFixKind[ImportFixKind["ImportType"] = 1] = "ImportType"; + ImportFixKind[ImportFixKind["AddToExisting"] = 2] = "AddToExisting"; + ImportFixKind[ImportFixKind["AddNew"] = 3] = "AddNew"; + })(ImportFixKind || (ImportFixKind = {})); + var ImportKind; + (function (ImportKind) { + ImportKind[ImportKind["Named"] = 0] = "Named"; + ImportKind[ImportKind["Default"] = 1] = "Default"; + ImportKind[ImportKind["Namespace"] = 2] = "Namespace"; + ImportKind[ImportKind["Equals"] = 3] = "Equals"; + })(ImportKind || (ImportKind = {})); + function getImportCompletionAction(exportedSymbol, moduleSymbol, sourceFile, symbolName, host, program, formatContext, position, preferences) { + var exportInfos = getAllReExportingModules(exportedSymbol, moduleSymbol, symbolName, sourceFile, program.getCompilerOptions(), program.getTypeChecker(), program.getSourceFiles()); + ts.Debug.assert(exportInfos.some(function (info) { return info.moduleSymbol === moduleSymbol; })); + // We sort the best codefixes first, so taking `first` is best for completions. + var moduleSpecifier = ts.first(getNewImportInfos(program, sourceFile, position, exportInfos, host, preferences)).moduleSpecifier; + var fix = ts.first(getFixForImport(exportInfos, symbolName, position, program, sourceFile, host, preferences)); + return { moduleSpecifier: moduleSpecifier, codeAction: codeFixActionToCodeAction(codeActionForFix({ host: host, formatContext: formatContext }, sourceFile, symbolName, fix, ts.getQuotePreference(sourceFile, preferences))) }; + } + codefix.getImportCompletionAction = getImportCompletionAction; + function codeFixActionToCodeAction(_a) { + var description = _a.description, changes = _a.changes, commands = _a.commands; + return { description: description, changes: changes, commands: commands }; + } + function getAllReExportingModules(exportedSymbol, exportingModuleSymbol, symbolName, sourceFile, compilerOptions, checker, allSourceFiles) { + var result = []; + forEachExternalModule(checker, allSourceFiles, function (moduleSymbol, moduleFile) { + // Don't import from a re-export when looking "up" like to `./index` or `../index`. + if (moduleFile && moduleSymbol !== exportingModuleSymbol && ts.startsWith(sourceFile.fileName, ts.getDirectoryPath(moduleFile.fileName))) { + return; + } + var defaultInfo = getDefaultLikeExportInfo(moduleSymbol, checker, compilerOptions); + if (defaultInfo && defaultInfo.name === symbolName && ts.skipAlias(defaultInfo.symbol, checker) === exportedSymbol) { + result.push({ moduleSymbol: moduleSymbol, importKind: defaultInfo.kind, exportedSymbolIsTypeOnly: isTypeOnlySymbol(defaultInfo.symbol, checker) }); + } + for (var _i = 0, _a = checker.getExportsOfModule(moduleSymbol); _i < _a.length; _i++) { + var exported = _a[_i]; + if (exported.name === symbolName && ts.skipAlias(exported, checker) === exportedSymbol) { + result.push({ moduleSymbol: moduleSymbol, importKind: 0 /* Named */, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exported, checker) }); + } + } + }); + return result; + } + function isTypeOnlySymbol(s, checker) { + return !(ts.skipAlias(s, checker).flags & 67220415 /* Value */); + } + function getFixForImport(exportInfos, symbolName, position, program, sourceFile, host, preferences) { + var checker = program.getTypeChecker(); + var existingImports = ts.flatMap(exportInfos, function (info) { return getExistingImportDeclarations(info, checker, sourceFile); }); + var useNamespace = position === undefined ? undefined : tryUseExistingNamespaceImport(existingImports, symbolName, position, checker); + var addToExisting = tryAddToExistingImport(existingImports); + // Don't bother providing an action to add a new import if we can add to an existing one. + var addImport = addToExisting ? [addToExisting] : getFixesForAddImport(exportInfos, existingImports, program, sourceFile, position, host, preferences); + return (useNamespace ? [useNamespace] : ts.emptyArray).concat(addImport); + } + function tryUseExistingNamespaceImport(existingImports, symbolName, position, checker) { + // It is possible that multiple import statements with the same specifier exist in the file. + // e.g. + // + // import * as ns from "foo"; + // import { member1, member2 } from "foo"; + // + // member3/**/ <-- cusor here + // + // in this case we should provie 2 actions: + // 1. change "member3" to "ns.member3" + // 2. add "member3" to the second import statement's import list + // and it is up to the user to decide which one fits best. + return ts.firstDefined(existingImports, function (_a) { + var declaration = _a.declaration; + var namespace = getNamespaceImportName(declaration); + if (namespace) { + var moduleSymbol = checker.getAliasedSymbol(checker.getSymbolAtLocation(namespace)); + if (moduleSymbol && moduleSymbol.exports.has(ts.escapeLeadingUnderscores(symbolName))) { + return { kind: 0 /* UseNamespace */, namespacePrefix: namespace.text, position: position }; + } + } + }); + } + function tryAddToExistingImport(existingImports) { + return ts.firstDefined(existingImports, function (_a) { + var declaration = _a.declaration, importKind = _a.importKind; + if (declaration.kind !== 249 /* ImportDeclaration */) + return undefined; + var importClause = declaration.importClause; + if (!importClause) + return undefined; + var name = importClause.name, namedBindings = importClause.namedBindings; + return importKind === 1 /* Default */ && !name || importKind === 0 /* Named */ && (!namedBindings || namedBindings.kind === 252 /* NamedImports */) + ? { kind: 2 /* AddToExisting */, importClause: importClause, importKind: importKind } + : undefined; + }); + } + function getNamespaceImportName(declaration) { + if (declaration.kind === 249 /* ImportDeclaration */) { + var namedBindings = declaration.importClause && ts.isImportClause(declaration.importClause) && declaration.importClause.namedBindings; + return namedBindings && namedBindings.kind === 251 /* NamespaceImport */ ? namedBindings.name : undefined; + } + else { + return declaration.name; + } + } + function getExistingImportDeclarations(_a, checker, sourceFile) { + var moduleSymbol = _a.moduleSymbol, importKind = _a.importKind, exportedSymbolIsTypeOnly = _a.exportedSymbolIsTypeOnly; + // Can't use an es6 import for a type in JS. + return exportedSymbolIsTypeOnly && ts.isSourceFileJS(sourceFile) ? ts.emptyArray : ts.mapDefined(sourceFile.imports, function (moduleSpecifier) { + var i = ts.importFromModuleSpecifier(moduleSpecifier); + return (i.kind === 249 /* ImportDeclaration */ || i.kind === 248 /* ImportEqualsDeclaration */) + && checker.getSymbolAtLocation(moduleSpecifier) === moduleSymbol ? { declaration: i, importKind: importKind } : undefined; + }); + } + function getNewImportInfos(program, sourceFile, position, moduleSymbols, host, preferences) { + var isJs = ts.isSourceFileJS(sourceFile); + var choicesForEachExportingModule = ts.flatMap(moduleSymbols, function (_a) { + var moduleSymbol = _a.moduleSymbol, importKind = _a.importKind, exportedSymbolIsTypeOnly = _a.exportedSymbolIsTypeOnly; + return ts.moduleSpecifiers.getModuleSpecifiers(moduleSymbol, program.getCompilerOptions(), sourceFile, host, program.getSourceFiles(), preferences, program.redirectTargetsMap) + .map(function (moduleSpecifier) { + // `position` should only be undefined at a missing jsx namespace, in which case we shouldn't be looking for pure types. + return exportedSymbolIsTypeOnly && isJs ? { kind: 1 /* ImportType */, moduleSpecifier: moduleSpecifier, position: ts.Debug.assertDefined(position) } : { kind: 3 /* AddNew */, moduleSpecifier: moduleSpecifier, importKind: importKind }; + }); + }); + // Sort to keep the shortest paths first + return ts.sort(choicesForEachExportingModule, function (a, b) { return a.moduleSpecifier.length - b.moduleSpecifier.length; }); + } + function getFixesForAddImport(exportInfos, existingImports, program, sourceFile, position, host, preferences) { + var existingDeclaration = ts.firstDefined(existingImports, newImportInfoFromExistingSpecifier); + return existingDeclaration ? [existingDeclaration] : getNewImportInfos(program, sourceFile, position, exportInfos, host, preferences); + } + function newImportInfoFromExistingSpecifier(_a) { + var declaration = _a.declaration, importKind = _a.importKind; + var expression = declaration.kind === 249 /* ImportDeclaration */ + ? declaration.moduleSpecifier + : declaration.moduleReference.kind === 259 /* ExternalModuleReference */ + ? declaration.moduleReference.expression + : undefined; + return expression && ts.isStringLiteral(expression) ? { kind: 3 /* AddNew */, moduleSpecifier: expression.text, importKind: importKind } : undefined; + } + function getFixesInfo(context, errorCode, pos) { + var symbolToken = ts.getTokenAtPosition(context.sourceFile, pos); + var info = errorCode === ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code + ? getFixesInfoForUMDImport(context, symbolToken) + : ts.isIdentifier(symbolToken) ? getFixesInfoForNonUMDImport(context, symbolToken) : undefined; + return info && __assign({}, info, { fixes: ts.sort(info.fixes, function (a, b) { return a.kind - b.kind; }) }); + } + function getFixesInfoForUMDImport(_a, token) { + var sourceFile = _a.sourceFile, program = _a.program, host = _a.host, preferences = _a.preferences; + var checker = program.getTypeChecker(); + var umdSymbol = getUmdSymbol(token, checker); + if (!umdSymbol) + return undefined; + var symbol = checker.getAliasedSymbol(umdSymbol); + var symbolName = umdSymbol.name; + var exportInfos = [{ moduleSymbol: symbol, importKind: getUmdImportKind(program.getCompilerOptions()), exportedSymbolIsTypeOnly: false }]; + var fixes = getFixForImport(exportInfos, symbolName, ts.isIdentifier(token) ? token.getStart(sourceFile) : undefined, program, sourceFile, host, preferences); + return { fixes: fixes, symbolName: symbolName }; + } + function getUmdSymbol(token, checker) { + // try the identifier to see if it is the umd symbol + var umdSymbol = ts.isIdentifier(token) ? checker.getSymbolAtLocation(token) : undefined; + if (ts.isUMDExportSymbol(umdSymbol)) + return umdSymbol; + // The error wasn't for the symbolAtLocation, it was for the JSX tag itself, which needs access to e.g. `React`. + var parent = token.parent; + return (ts.isJsxOpeningLikeElement(parent) && parent.tagName === token) || ts.isJsxOpeningFragment(parent) + ? ts.tryCast(checker.resolveName(checker.getJsxNamespace(parent), ts.isJsxOpeningLikeElement(parent) ? token : parent, 67220415 /* Value */, /*excludeGlobals*/ false), ts.isUMDExportSymbol) + : undefined; + } + function getUmdImportKind(compilerOptions) { + // Import a synthetic `default` if enabled. + if (ts.getAllowSyntheticDefaultImports(compilerOptions)) { + return 1 /* Default */; + } + // When a synthetic `default` is unavailable, use `import..require` if the module kind supports it. + var moduleKind = ts.getEmitModuleKind(compilerOptions); + switch (moduleKind) { + case ts.ModuleKind.AMD: + case ts.ModuleKind.CommonJS: + case ts.ModuleKind.UMD: + return 3 /* Equals */; + case ts.ModuleKind.System: + case ts.ModuleKind.ES2015: + case ts.ModuleKind.ESNext: + case ts.ModuleKind.None: + // Fall back to the `import * as ns` style import. + return 2 /* Namespace */; + default: + return ts.Debug.assertNever(moduleKind); + } + } + function getFixesInfoForNonUMDImport(_a, symbolToken) { + var sourceFile = _a.sourceFile, program = _a.program, cancellationToken = _a.cancellationToken, host = _a.host, preferences = _a.preferences; + var checker = program.getTypeChecker(); + // If we're at ``, we must check if `Foo` is already in scope, and if so, get an import for `React` instead. + var symbolName = ts.isJsxOpeningLikeElement(symbolToken.parent) + && symbolToken.parent.tagName === symbolToken + && (ts.isIntrinsicJsxName(symbolToken.text) || checker.resolveName(symbolToken.text, symbolToken, 67108863 /* All */, /*excludeGlobals*/ false)) + ? checker.getJsxNamespace() + : symbolToken.text; + // "default" is a keyword and not a legal identifier for the import, so we don't expect it here + ts.Debug.assert(symbolName !== "default" /* Default */); + var fixes = ts.arrayFrom(ts.flatMapIterator(getExportInfos(symbolName, ts.getMeaningFromLocation(symbolToken), cancellationToken, sourceFile, checker, program).entries(), function (_a) { + var _ = _a[0], exportInfos = _a[1]; + return getFixForImport(exportInfos, symbolName, symbolToken.getStart(sourceFile), program, sourceFile, host, preferences); + })); + return { fixes: fixes, symbolName: symbolName }; + } + // Returns a map from an exported symbol's ID to a list of every way it's (re-)exported. + function getExportInfos(symbolName, currentTokenMeaning, cancellationToken, sourceFile, checker, program) { + // For each original symbol, keep all re-exports of that symbol together so we can call `getCodeActionsForImport` on the whole group at once. + // Maps symbol id to info for modules providing that symbol (original export + re-exports). + var originalSymbolToExportInfos = ts.createMultiMap(); + function addSymbol(moduleSymbol, exportedSymbol, importKind) { + originalSymbolToExportInfos.add(ts.getUniqueSymbolId(exportedSymbol, checker).toString(), { moduleSymbol: moduleSymbol, importKind: importKind, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exportedSymbol, checker) }); + } + forEachExternalModuleToImportFrom(checker, sourceFile, program.getSourceFiles(), function (moduleSymbol) { + cancellationToken.throwIfCancellationRequested(); + var defaultInfo = getDefaultLikeExportInfo(moduleSymbol, checker, program.getCompilerOptions()); + if (defaultInfo && defaultInfo.name === symbolName && symbolHasMeaning(defaultInfo.symbolForMeaning, currentTokenMeaning)) { + addSymbol(moduleSymbol, defaultInfo.symbol, defaultInfo.kind); + } + // check exports with the same name + var exportSymbolWithIdenticalName = checker.tryGetMemberInModuleExportsAndProperties(symbolName, moduleSymbol); + if (exportSymbolWithIdenticalName && symbolHasMeaning(exportSymbolWithIdenticalName, currentTokenMeaning)) { + addSymbol(moduleSymbol, exportSymbolWithIdenticalName, 0 /* Named */); + } + }); + return originalSymbolToExportInfos; + } + function getDefaultLikeExportInfo(moduleSymbol, checker, compilerOptions) { + var exported = getDefaultLikeExportWorker(moduleSymbol, checker); + if (!exported) + return undefined; + var symbol = exported.symbol, kind = exported.kind; + var info = getDefaultExportInfoWorker(symbol, moduleSymbol, checker, compilerOptions); + return info && __assign({ symbol: symbol, kind: kind }, info); + } + function getDefaultLikeExportWorker(moduleSymbol, checker) { + var defaultExport = checker.tryGetMemberInModuleExports("default" /* Default */, moduleSymbol); + if (defaultExport) + return { symbol: defaultExport, kind: 1 /* Default */ }; + var exportEquals = checker.resolveExternalModuleSymbol(moduleSymbol); + return exportEquals === moduleSymbol ? undefined : { symbol: exportEquals, kind: 3 /* Equals */ }; + } + function getDefaultExportInfoWorker(defaultExport, moduleSymbol, checker, compilerOptions) { + var localSymbol = ts.getLocalSymbolForExportDefault(defaultExport); + if (localSymbol) + return { symbolForMeaning: localSymbol, name: localSymbol.name }; + var name = getNameForExportDefault(defaultExport); + if (name !== undefined) + return { symbolForMeaning: defaultExport, name: name }; + if (defaultExport.flags & 2097152 /* Alias */) { + var aliased = checker.getImmediateAliasedSymbol(defaultExport); + return aliased && getDefaultExportInfoWorker(aliased, ts.Debug.assertDefined(aliased.parent), checker, compilerOptions); + } + else { + return { symbolForMeaning: defaultExport, name: moduleSymbolToValidIdentifier(moduleSymbol, compilerOptions.target) }; + } + } + function getNameForExportDefault(symbol) { + return symbol.declarations && ts.firstDefined(symbol.declarations, function (declaration) { + if (ts.isExportAssignment(declaration)) { + if (ts.isIdentifier(declaration.expression)) { + return declaration.expression.text; + } + } + else if (ts.isExportSpecifier(declaration)) { + ts.Debug.assert(declaration.name.text === "default" /* Default */); + return declaration.propertyName && declaration.propertyName.text; + } + }); + } + function codeActionForFix(context, sourceFile, symbolName, fix, quotePreference) { + var diag; + var changes = ts.textChanges.ChangeTracker.with(context, function (tracker) { + diag = codeActionForFixWorker(tracker, sourceFile, symbolName, fix, quotePreference); + }); + return codefix.createCodeFixAction("import", changes, diag, codefix.importFixId, ts.Diagnostics.Add_all_missing_imports); + } + function codeActionForFixWorker(changes, sourceFile, symbolName, fix, quotePreference) { + switch (fix.kind) { + case 0 /* UseNamespace */: + addNamespaceQualifier(changes, sourceFile, fix); + return [ts.Diagnostics.Change_0_to_1, symbolName, fix.namespacePrefix + "." + symbolName]; + case 1 /* ImportType */: + addImportType(changes, sourceFile, fix, quotePreference); + return [ts.Diagnostics.Change_0_to_1, symbolName, getImportTypePrefix(fix.moduleSpecifier, quotePreference) + symbolName]; + case 2 /* AddToExisting */: { + var importClause = fix.importClause, importKind = fix.importKind; + doAddExistingFix(changes, sourceFile, importClause, importKind === 1 /* Default */ ? symbolName : undefined, importKind === 0 /* Named */ ? [symbolName] : ts.emptyArray); + var moduleSpecifierWithoutQuotes = ts.stripQuotes(importClause.parent.moduleSpecifier.getText()); + return [importKind === 1 /* Default */ ? ts.Diagnostics.Add_default_import_0_to_existing_import_declaration_from_1 : ts.Diagnostics.Add_0_to_existing_import_declaration_from_1, symbolName, moduleSpecifierWithoutQuotes]; // you too! + } + case 3 /* AddNew */: { + var importKind = fix.importKind, moduleSpecifier = fix.moduleSpecifier; + addNewImports(changes, sourceFile, moduleSpecifier, quotePreference, importKind === 1 /* Default */ ? { defaultImport: symbolName, namedImports: ts.emptyArray, namespaceLikeImport: undefined } + : importKind === 0 /* Named */ ? { defaultImport: undefined, namedImports: [symbolName], namespaceLikeImport: undefined } + : { defaultImport: undefined, namedImports: ts.emptyArray, namespaceLikeImport: { importKind: importKind, name: symbolName } }); + return [importKind === 1 /* Default */ ? ts.Diagnostics.Import_default_0_from_module_1 : ts.Diagnostics.Import_0_from_module_1, symbolName, moduleSpecifier]; + } + default: + return ts.Debug.assertNever(fix); + } + } + function doAddExistingFix(changes, sourceFile, clause, defaultImport, namedImports) { + if (defaultImport) { + ts.Debug.assert(!clause.name); + changes.insertNodeAt(sourceFile, clause.getStart(sourceFile), ts.createIdentifier(defaultImport), { suffix: ", " }); + } + if (namedImports.length) { + var specifiers = namedImports.map(function (name) { return ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(name)); }); + if (clause.namedBindings && ts.cast(clause.namedBindings, ts.isNamedImports).elements.length) { + for (var _i = 0, specifiers_1 = specifiers; _i < specifiers_1.length; _i++) { + var spec = specifiers_1[_i]; + changes.insertNodeInListAfter(sourceFile, ts.last(ts.cast(clause.namedBindings, ts.isNamedImports).elements), spec); + } + } + else { + if (specifiers.length) { + var namedImports_1 = ts.createNamedImports(specifiers); + if (clause.namedBindings) { + changes.replaceNode(sourceFile, clause.namedBindings, namedImports_1); + } + else { + changes.insertNodeAfter(sourceFile, ts.Debug.assertDefined(clause.name), namedImports_1); + } + } + } + } + } + function addNamespaceQualifier(changes, sourceFile, _a) { + var namespacePrefix = _a.namespacePrefix, position = _a.position; + changes.insertText(sourceFile, position, namespacePrefix + "."); + } + function addImportType(changes, sourceFile, _a, quotePreference) { + var moduleSpecifier = _a.moduleSpecifier, position = _a.position; + changes.insertText(sourceFile, position, getImportTypePrefix(moduleSpecifier, quotePreference)); + } + function getImportTypePrefix(moduleSpecifier, quotePreference) { + var quote = ts.getQuoteFromPreference(quotePreference); + return "import(" + quote + moduleSpecifier + quote + ")."; + } + function addNewImports(changes, sourceFile, moduleSpecifier, quotePreference, _a) { + var defaultImport = _a.defaultImport, namedImports = _a.namedImports, namespaceLikeImport = _a.namespaceLikeImport; + var quotedModuleSpecifier = ts.makeStringLiteral(moduleSpecifier, quotePreference); + if (defaultImport !== undefined || namedImports.length) { + ts.insertImport(changes, sourceFile, ts.makeImport(defaultImport === undefined ? undefined : ts.createIdentifier(defaultImport), namedImports.map(function (n) { return ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(n)); }), moduleSpecifier, quotePreference)); + } + if (namespaceLikeImport) { + ts.insertImport(changes, sourceFile, namespaceLikeImport.importKind === 3 /* Equals */ + ? ts.createImportEqualsDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createIdentifier(namespaceLikeImport.name), ts.createExternalModuleReference(quotedModuleSpecifier)) + : ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(ts.createIdentifier(namespaceLikeImport.name))), quotedModuleSpecifier)); + } + } + function symbolHasMeaning(_a, meaning) { + var declarations = _a.declarations; + return ts.some(declarations, function (decl) { return !!(ts.getMeaningFromDeclaration(decl) & meaning); }); + } + function forEachExternalModuleToImportFrom(checker, from, allSourceFiles, cb) { + forEachExternalModule(checker, allSourceFiles, function (module, sourceFile) { + if (sourceFile === undefined || sourceFile !== from && isImportablePath(from.fileName, sourceFile.fileName)) { + cb(module); + } + }); + } + codefix.forEachExternalModuleToImportFrom = forEachExternalModuleToImportFrom; + function forEachExternalModule(checker, allSourceFiles, cb) { + for (var _i = 0, _a = checker.getAmbientModules(); _i < _a.length; _i++) { + var ambient = _a[_i]; + cb(ambient, /*sourceFile*/ undefined); + } + for (var _b = 0, allSourceFiles_1 = allSourceFiles; _b < allSourceFiles_1.length; _b++) { + var sourceFile = allSourceFiles_1[_b]; + if (ts.isExternalOrCommonJsModule(sourceFile)) { + cb(checker.getMergedSymbol(sourceFile.symbol), sourceFile); + } + } + } + /** + * Don't include something from a `node_modules` that isn't actually reachable by a global import. + * A relative import to node_modules is usually a bad idea. + */ + function isImportablePath(fromPath, toPath) { + // If it's in a `node_modules` but is not reachable from here via a global import, don't bother. + var toNodeModules = ts.forEachAncestorDirectory(toPath, function (ancestor) { return ts.getBaseFileName(ancestor) === "node_modules" ? ancestor : undefined; }); + return toNodeModules === undefined || ts.startsWith(fromPath, ts.getDirectoryPath(toNodeModules)); + } + function moduleSymbolToValidIdentifier(moduleSymbol, target) { + return moduleSpecifierToValidIdentifier(ts.removeFileExtension(ts.stripQuotes(moduleSymbol.name)), target); + } + codefix.moduleSymbolToValidIdentifier = moduleSymbolToValidIdentifier; + function moduleSpecifierToValidIdentifier(moduleSpecifier, target) { + var baseName = ts.getBaseFileName(ts.removeSuffix(moduleSpecifier, "/index")); + var res = ""; + var lastCharWasValid = true; + var firstCharCode = baseName.charCodeAt(0); + if (ts.isIdentifierStart(firstCharCode, target)) { + res += String.fromCharCode(firstCharCode); + } + else { + lastCharWasValid = false; + } + for (var i = 1; i < baseName.length; i++) { + var ch = baseName.charCodeAt(i); + var isValid = ts.isIdentifierPart(ch, target); + if (isValid) { + var char = String.fromCharCode(ch); + if (!lastCharWasValid) { + char = char.toUpperCase(); + } + res += char; + } + lastCharWasValid = isValid; + } + // Need `|| "_"` to ensure result isn't empty. + return !ts.isStringANonContextualKeyword(res) ? res || "_" : "_" + res; + } + codefix.moduleSpecifierToValidIdentifier = moduleSpecifierToValidIdentifier; + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "fixSpelling"; + var errorCodes = [ + ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2.code, + ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1.code, + ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0.code, + ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_static_member_1_0.code, + ts.Diagnostics.Module_0_has_no_exported_member_1_Did_you_mean_2.code, + ]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var sourceFile = context.sourceFile; + var info = getInfo(sourceFile, context.span.start, context); + if (!info) + return undefined; + var node = info.node, suggestion = info.suggestion; + var target = context.host.getCompilationSettings().target; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, node, suggestion, target); }); + return [codefix.createCodeFixAction("spelling", changes, [ts.Diagnostics.Change_spelling_to_0, suggestion], fixId, ts.Diagnostics.Fix_all_detected_spelling_errors)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var info = getInfo(diag.file, diag.start, context); + var target = context.host.getCompilationSettings().target; + if (info) + doChange(changes, context.sourceFile, info.node, info.suggestion, target); + }); }, + }); + function getInfo(sourceFile, pos, context) { + // This is the identifier of the misspelled word. eg: + // this.speling = 1; + // ^^^^^^^ + var node = ts.getTokenAtPosition(sourceFile, pos); + var checker = context.program.getTypeChecker(); + var suggestion; + if (ts.isPropertyAccessExpression(node.parent) && node.parent.name === node) { + ts.Debug.assert(node.kind === 72 /* Identifier */); + var containingType = checker.getTypeAtLocation(node.parent.expression); + suggestion = checker.getSuggestionForNonexistentProperty(node, containingType); + } + else if (ts.isImportSpecifier(node.parent) && node.parent.name === node) { + ts.Debug.assert(node.kind === 72 /* Identifier */); + var importDeclaration = ts.findAncestor(node, ts.isImportDeclaration); + var resolvedSourceFile = getResolvedSourceFileFromImportDeclaration(sourceFile, context, importDeclaration); + if (resolvedSourceFile && resolvedSourceFile.symbol) { + suggestion = checker.getSuggestionForNonexistentExport(node, resolvedSourceFile.symbol); + } + } + else { + var meaning = ts.getMeaningFromLocation(node); + var name = ts.getTextOfNode(node); + ts.Debug.assert(name !== undefined, "name should be defined"); + suggestion = checker.getSuggestionForNonexistentSymbol(node, name, convertSemanticMeaningToSymbolFlags(meaning)); + } + return suggestion === undefined ? undefined : { node: node, suggestion: suggestion }; + } + function doChange(changes, sourceFile, node, suggestion, target) { + if (!ts.isIdentifierText(suggestion, target) && ts.isPropertyAccessExpression(node.parent)) { + changes.replaceNode(sourceFile, node.parent, ts.createElementAccess(node.parent.expression, ts.createLiteral(suggestion))); + } + else { + changes.replaceNode(sourceFile, node, ts.createIdentifier(suggestion)); + } + } + function convertSemanticMeaningToSymbolFlags(meaning) { + var flags = 0; + if (meaning & 4 /* Namespace */) { + flags |= 1920 /* Namespace */; + } + if (meaning & 2 /* Type */) { + flags |= 67897832 /* Type */; + } + if (meaning & 1 /* Value */) { + flags |= 67220415 /* Value */; + } + return flags; + } + function getResolvedSourceFileFromImportDeclaration(sourceFile, context, importDeclaration) { + if (!importDeclaration || !ts.isStringLiteralLike(importDeclaration.moduleSpecifier)) + return undefined; + var resolvedModule = ts.getResolvedModule(sourceFile, importDeclaration.moduleSpecifier.text); + if (!resolvedModule) + return undefined; + return context.program.getSourceFile(resolvedModule.resolvedFileName); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixName = "addMissingMember"; + var errorCodes = [ + ts.Diagnostics.Property_0_does_not_exist_on_type_1.code, + ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2.code, + ts.Diagnostics.Property_0_is_missing_in_type_1_but_required_in_type_2.code, + ts.Diagnostics.Type_0_is_missing_the_following_properties_from_type_1_Colon_2.code, + ts.Diagnostics.Type_0_is_missing_the_following_properties_from_type_1_Colon_2_and_3_more.code + ]; + var fixId = "addMissingMember"; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var info = getInfo(context.sourceFile, context.span.start, context.program.getTypeChecker()); + if (!info) + return undefined; + if (info.kind === 0 /* Enum */) { + var token_1 = info.token, parentDeclaration_1 = info.parentDeclaration; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addEnumMemberDeclaration(t, context.program.getTypeChecker(), token_1, parentDeclaration_1); }); + return [codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Add_missing_enum_member_0, token_1.text], fixId, ts.Diagnostics.Add_all_missing_members)]; + } + var parentDeclaration = info.parentDeclaration, declSourceFile = info.declSourceFile, inJs = info.inJs, makeStatic = info.makeStatic, token = info.token, call = info.call; + var methodCodeAction = call && getActionForMethodDeclaration(context, declSourceFile, parentDeclaration, token, call, makeStatic, inJs, context.preferences); + var addMember = inJs && !ts.isInterfaceDeclaration(parentDeclaration) ? + ts.singleElementArray(getActionsForAddMissingMemberInJavascriptFile(context, declSourceFile, parentDeclaration, token.text, makeStatic)) : + getActionsForAddMissingMemberInTypeScriptFile(context, declSourceFile, parentDeclaration, token, makeStatic); + return ts.concatenate(ts.singleElementArray(methodCodeAction), addMember); + }, + fixIds: [fixId], + getAllCodeActions: function (context) { + var program = context.program, preferences = context.preferences; + var checker = program.getTypeChecker(); + var seen = ts.createMap(); + var typeDeclToMembers = new ts.NodeMap(); + return codefix.createCombinedCodeActions(ts.textChanges.ChangeTracker.with(context, function (changes) { + codefix.eachDiagnostic(context, errorCodes, function (diag) { + var info = getInfo(diag.file, diag.start, checker); + if (!info || !ts.addToSeen(seen, ts.getNodeId(info.parentDeclaration) + "#" + info.token.text)) { + return; + } + if (info.kind === 0 /* Enum */) { + var token = info.token, parentDeclaration = info.parentDeclaration; + addEnumMemberDeclaration(changes, checker, token, parentDeclaration); + } + else { + var parentDeclaration = info.parentDeclaration, token_2 = info.token; + var infos = typeDeclToMembers.getOrUpdate(parentDeclaration, function () { return []; }); + if (!infos.some(function (i) { return i.token.text === token_2.text; })) + infos.push(info); + } + }); + typeDeclToMembers.forEach(function (infos, classDeclaration) { + var supers = getAllSupers(classDeclaration, checker); + var _loop_11 = function (info) { + // If some superclass added this property, don't add it again. + if (supers.some(function (superClassOrInterface) { + var superInfos = typeDeclToMembers.get(superClassOrInterface); + return !!superInfos && superInfos.some(function (_a) { + var token = _a.token; + return token.text === info.token.text; + }); + })) + return "continue"; + var parentDeclaration = info.parentDeclaration, declSourceFile = info.declSourceFile, inJs = info.inJs, makeStatic = info.makeStatic, token = info.token, call = info.call; + // Always prefer to add a method declaration if possible. + if (call) { + addMethodDeclaration(context, changes, declSourceFile, parentDeclaration, token, call, makeStatic, inJs, preferences); + } + else { + if (inJs && !ts.isInterfaceDeclaration(parentDeclaration)) { + addMissingMemberInJs(changes, declSourceFile, parentDeclaration, token.text, makeStatic); + } + else { + var typeNode = getTypeNode(program.getTypeChecker(), parentDeclaration, token); + addPropertyDeclaration(changes, declSourceFile, parentDeclaration, token.text, typeNode, makeStatic); + } + } + }; + for (var _i = 0, infos_1 = infos; _i < infos_1.length; _i++) { + var info = infos_1[_i]; + _loop_11(info); + } + }); + })); + }, + }); + function getAllSupers(decl, checker) { + var res = []; + while (decl) { + var superElement = ts.getClassExtendsHeritageElement(decl); + var superSymbol = superElement && checker.getSymbolAtLocation(superElement.expression); + var superDecl = superSymbol && ts.find(superSymbol.declarations, ts.isClassLike); + if (superDecl) { + res.push(superDecl); + } + decl = superDecl; + } + return res; + } + var InfoKind; + (function (InfoKind) { + InfoKind[InfoKind["Enum"] = 0] = "Enum"; + InfoKind[InfoKind["ClassOrInterface"] = 1] = "ClassOrInterface"; + })(InfoKind || (InfoKind = {})); + function getInfo(tokenSourceFile, tokenPos, checker) { + // The identifier of the missing property. eg: + // this.missing = 1; + // ^^^^^^^ + var token = ts.getTokenAtPosition(tokenSourceFile, tokenPos); + if (!ts.isIdentifier(token)) { + return undefined; + } + var parent = token.parent; + if (!ts.isPropertyAccessExpression(parent)) + return undefined; + var leftExpressionType = ts.skipConstraint(checker.getTypeAtLocation(parent.expression)); + var symbol = leftExpressionType.symbol; + if (!symbol || !symbol.declarations) + return undefined; + // Prefer to change the class instead of the interface if they are merged + var classOrInterface = ts.find(symbol.declarations, ts.isClassLike) || ts.find(symbol.declarations, ts.isInterfaceDeclaration); + if (classOrInterface) { + var makeStatic = (leftExpressionType.target || leftExpressionType) !== checker.getDeclaredTypeOfSymbol(symbol); + var declSourceFile = classOrInterface.getSourceFile(); + var inJs = ts.isSourceFileJS(declSourceFile); + var call = ts.tryCast(parent.parent, ts.isCallExpression); + return { kind: 1 /* ClassOrInterface */, token: token, parentDeclaration: classOrInterface, makeStatic: makeStatic, declSourceFile: declSourceFile, inJs: inJs, call: call }; + } + var enumDeclaration = ts.find(symbol.declarations, ts.isEnumDeclaration); + if (enumDeclaration) { + return { kind: 0 /* Enum */, token: token, parentDeclaration: enumDeclaration }; + } + return undefined; + } + function getActionsForAddMissingMemberInJavascriptFile(context, declSourceFile, classDeclaration, tokenName, makeStatic) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMissingMemberInJs(t, declSourceFile, classDeclaration, tokenName, makeStatic); }); + return changes.length === 0 ? undefined + : codefix.createCodeFixAction(fixName, changes, [makeStatic ? ts.Diagnostics.Initialize_static_property_0 : ts.Diagnostics.Initialize_property_0_in_the_constructor, tokenName], fixId, ts.Diagnostics.Add_all_missing_members); + } + function addMissingMemberInJs(changeTracker, declSourceFile, classDeclaration, tokenName, makeStatic) { + if (makeStatic) { + if (classDeclaration.kind === 209 /* ClassExpression */) { + return; + } + var className = classDeclaration.name.getText(); + var staticInitialization = initializePropertyToUndefined(ts.createIdentifier(className), tokenName); + changeTracker.insertNodeAfter(declSourceFile, classDeclaration, staticInitialization); + } + else { + var classConstructor = ts.getFirstConstructorWithBody(classDeclaration); + if (!classConstructor) { + return; + } + var propertyInitialization = initializePropertyToUndefined(ts.createThis(), tokenName); + changeTracker.insertNodeAtConstructorEnd(declSourceFile, classConstructor, propertyInitialization); + } + } + function initializePropertyToUndefined(obj, propertyName) { + return ts.createStatement(ts.createAssignment(ts.createPropertyAccess(obj, propertyName), ts.createIdentifier("undefined"))); + } + function getActionsForAddMissingMemberInTypeScriptFile(context, declSourceFile, classDeclaration, token, makeStatic) { + var typeNode = getTypeNode(context.program.getTypeChecker(), classDeclaration, token); + var addProp = createAddPropertyDeclarationAction(context, declSourceFile, classDeclaration, makeStatic, token.text, typeNode); + return makeStatic ? [addProp] : [addProp, createAddIndexSignatureAction(context, declSourceFile, classDeclaration, token.text, typeNode)]; + } + function getTypeNode(checker, classDeclaration, token) { + var typeNode; + if (token.parent.parent.kind === 204 /* BinaryExpression */) { + var binaryExpression = token.parent.parent; + var otherExpression = token.parent === binaryExpression.left ? binaryExpression.right : binaryExpression.left; + var widenedType = checker.getWidenedType(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(otherExpression))); + typeNode = checker.typeToTypeNode(widenedType, classDeclaration); + } + else { + var contextualType = checker.getContextualType(token.parent); + typeNode = contextualType ? checker.typeToTypeNode(contextualType) : undefined; + } + return typeNode || ts.createKeywordTypeNode(120 /* AnyKeyword */); + } + function createAddPropertyDeclarationAction(context, declSourceFile, classDeclaration, makeStatic, tokenName, typeNode) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addPropertyDeclaration(t, declSourceFile, classDeclaration, tokenName, typeNode, makeStatic); }); + return codefix.createCodeFixAction(fixName, changes, [makeStatic ? ts.Diagnostics.Declare_static_property_0 : ts.Diagnostics.Declare_property_0, tokenName], fixId, ts.Diagnostics.Add_all_missing_members); + } + function addPropertyDeclaration(changeTracker, declSourceFile, classDeclaration, tokenName, typeNode, makeStatic) { + var property = ts.createProperty( + /*decorators*/ undefined, + /*modifiers*/ makeStatic ? [ts.createToken(116 /* StaticKeyword */)] : undefined, tokenName, + /*questionToken*/ undefined, typeNode, + /*initializer*/ undefined); + var lastProp = getNodeToInsertPropertyAfter(classDeclaration); + if (lastProp) { + changeTracker.insertNodeAfter(declSourceFile, lastProp, property); + } + else { + changeTracker.insertNodeAtClassStart(declSourceFile, classDeclaration, property); + } + } + // Gets the last of the first run of PropertyDeclarations, or undefined if the class does not start with a PropertyDeclaration. + function getNodeToInsertPropertyAfter(cls) { + var res; + for (var _i = 0, _a = cls.members; _i < _a.length; _i++) { + var member = _a[_i]; + if (!ts.isPropertyDeclaration(member)) + break; + res = member; + } + return res; + } + function createAddIndexSignatureAction(context, declSourceFile, classDeclaration, tokenName, typeNode) { + // Index signatures cannot have the static modifier. + var stringTypeNode = ts.createKeywordTypeNode(138 /* StringKeyword */); + var indexingParameter = ts.createParameter( + /*decorators*/ undefined, + /*modifiers*/ undefined, + /*dotDotDotToken*/ undefined, "x", + /*questionToken*/ undefined, stringTypeNode, + /*initializer*/ undefined); + var indexSignature = ts.createIndexSignature( + /*decorators*/ undefined, + /*modifiers*/ undefined, [indexingParameter], typeNode); + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.insertNodeAtClassStart(declSourceFile, classDeclaration, indexSignature); }); + // No fixId here because code-fix-all currently only works on adding individual named properties. + return codefix.createCodeFixActionNoFixId(fixName, changes, [ts.Diagnostics.Add_index_signature_for_property_0, tokenName]); + } + function getActionForMethodDeclaration(context, declSourceFile, classDeclaration, token, callExpression, makeStatic, inJs, preferences) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMethodDeclaration(context, t, declSourceFile, classDeclaration, token, callExpression, makeStatic, inJs, preferences); }); + return codefix.createCodeFixAction(fixName, changes, [makeStatic ? ts.Diagnostics.Declare_static_method_0 : ts.Diagnostics.Declare_method_0, token.text], fixId, ts.Diagnostics.Add_all_missing_members); + } + function addMethodDeclaration(context, changeTracker, declSourceFile, typeDecl, token, callExpression, makeStatic, inJs, preferences) { + var methodDeclaration = codefix.createMethodFromCallExpression(context, callExpression, token.text, inJs, makeStatic, preferences, !ts.isInterfaceDeclaration(typeDecl)); + var containingMethodDeclaration = ts.getAncestor(callExpression, 156 /* MethodDeclaration */); + if (containingMethodDeclaration && containingMethodDeclaration.parent === typeDecl) { + changeTracker.insertNodeAfter(declSourceFile, containingMethodDeclaration, methodDeclaration); + } + else { + changeTracker.insertNodeAtClassStart(declSourceFile, typeDecl, methodDeclaration); + } + } + function addEnumMemberDeclaration(changes, checker, token, enumDeclaration) { + /** + * create initializer only literal enum that has string initializer. + * value of initializer is a string literal that equal to name of enum member. + * numeric enum or empty enum will not create initializer. + */ + var hasStringInitializer = ts.some(enumDeclaration.members, function (member) { + var type = checker.getTypeAtLocation(member); + return !!(type && type.flags & 132 /* StringLike */); + }); + var enumMember = ts.createEnumMember(token, hasStringInitializer ? ts.createStringLiteral(token.text) : undefined); + changes.replaceNode(enumDeclaration.getSourceFile(), enumDeclaration, ts.updateEnumDeclaration(enumDeclaration, enumDeclaration.decorators, enumDeclaration.modifiers, enumDeclaration.name, ts.concatenate(enumDeclaration.members, ts.singleElementArray(enumMember)))); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "addMissingNewOperator"; + var errorCodes = [ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var sourceFile = context.sourceFile, span = context.span; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMissingNewOperator(t, sourceFile, span); }); + return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Add_missing_new_operator_to_call, fixId, ts.Diagnostics.Add_missing_new_operator_to_all_calls)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + return addMissingNewOperator(changes, context.sourceFile, diag); + }); }, + }); + function addMissingNewOperator(changes, sourceFile, span) { + var call = ts.cast(findAncestorMatchingSpan(sourceFile, span), ts.isCallExpression); + var newExpression = ts.createNew(call.expression, call.typeArguments, call.arguments); + changes.replaceNode(sourceFile, call, newExpression); + } + function findAncestorMatchingSpan(sourceFile, span) { + var token = ts.getTokenAtPosition(sourceFile, span.start); + var end = ts.textSpanEnd(span); + while (token.end < end) { + token = token.parent; + } + return token; + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixName = "fixCannotFindModule"; + var fixIdInstallTypesPackage = "installTypesPackage"; + var fixIdGenerateTypes = "generateTypes"; + var errorCodeCannotFindModule = ts.Diagnostics.Cannot_find_module_0.code; + var errorCodes = [ + errorCodeCannotFindModule, + ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type.code, + ]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var host = context.host, sourceFile = context.sourceFile, start = context.span.start; + var packageName = tryGetImportedPackageName(sourceFile, start); + if (packageName === undefined) + return undefined; + var typesPackageName = getTypesPackageNameToInstall(packageName, host, context.errorCode); + return typesPackageName === undefined + ? ts.singleElementArray(tryGetGenerateTypesAction(context, packageName)) + : [codefix.createCodeFixAction(fixName, /*changes*/ [], [ts.Diagnostics.Install_0, typesPackageName], fixIdInstallTypesPackage, ts.Diagnostics.Install_all_missing_types_packages, getInstallCommand(sourceFile.fileName, typesPackageName))]; + }, + fixIds: [fixIdInstallTypesPackage, fixIdGenerateTypes], + getAllCodeActions: function (context) { + var savedTypesDir = null; // tslint:disable-line no-null-keyword + return codefix.codeFixAll(context, errorCodes, function (changes, diag, commands) { + var packageName = tryGetImportedPackageName(diag.file, diag.start); + if (packageName === undefined) + return undefined; + switch (context.fixId) { + case fixIdInstallTypesPackage: { + var pkg = getTypesPackageNameToInstall(packageName, context.host, diag.code); + if (pkg) { + commands.push(getInstallCommand(diag.file.fileName, pkg)); + } + break; + } + case fixIdGenerateTypes: { + var typesDir = savedTypesDir !== null ? savedTypesDir : savedTypesDir = getOrCreateTypesDirectory(changes, context); + var command = typesDir === undefined ? undefined : tryGenerateTypes(typesDir, packageName, context); + if (command) + commands.push(command); + break; + } + default: + ts.Debug.fail("Bad fixId: " + context.fixId); + } + }); + }, + }); + function tryGetGenerateTypesAction(context, packageName) { + var command; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { + var typesDir = getOrCreateTypesDirectory(t, context); + command = typesDir === undefined ? undefined : tryGenerateTypes(typesDir, packageName, context); + }); + return command && codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Generate_types_for_0, packageName], fixIdGenerateTypes, ts.Diagnostics.Generate_types_for_all_packages_without_types, command); + } + function tryGenerateTypes(typesDir, packageName, context) { + var file = context.sourceFile.fileName; + var fileToGenerateTypesFor = ts.tryResolveJSModule(packageName, ts.getDirectoryPath(file), context.host); // TODO: GH#18217 + if (fileToGenerateTypesFor === undefined) + return undefined; + var outputFileName = ts.resolvePath(ts.getDirectoryPath(context.program.getCompilerOptions().configFile.fileName), typesDir, packageName + ".d.ts"); + if (context.host.fileExists(outputFileName)) + return undefined; + return { type: "generate types", file: file, fileToGenerateTypesFor: fileToGenerateTypesFor, outputFileName: outputFileName }; + } + // If no types directory exists yet, adds it to tsconfig.json + function getOrCreateTypesDirectory(changes, context) { + var configFile = context.program.getCompilerOptions().configFile; + if (!configFile) + return undefined; + var tsconfigObjectLiteral = ts.getTsConfigObjectLiteralExpression(configFile); + if (!tsconfigObjectLiteral) + return undefined; + var compilerOptionsProperty = findProperty(tsconfigObjectLiteral, "compilerOptions"); + if (!compilerOptionsProperty) { + var newCompilerOptions = ts.createObjectLiteral([makeDefaultBaseUrl(), makeDefaultPaths()]); + changes.insertNodeAtObjectStart(configFile, tsconfigObjectLiteral, createJsonPropertyAssignment("compilerOptions", newCompilerOptions)); + return defaultTypesDirectoryName; + } + var compilerOptions = compilerOptionsProperty.initializer; + if (!ts.isObjectLiteralExpression(compilerOptions)) + return defaultTypesDirectoryName; + var baseUrl = getOrAddBaseUrl(changes, configFile, compilerOptions); + var typesDirectoryFromPathMapping = getOrAddPathMapping(changes, configFile, compilerOptions); + return ts.combinePaths(baseUrl, typesDirectoryFromPathMapping); + } + var defaultBaseUrl = "."; + function makeDefaultBaseUrl() { + return createJsonPropertyAssignment("baseUrl", ts.createStringLiteral(defaultBaseUrl)); + } + function getOrAddBaseUrl(changes, tsconfig, compilerOptions) { + var baseUrlProp = findProperty(compilerOptions, "baseUrl"); + if (baseUrlProp) { + return ts.isStringLiteral(baseUrlProp.initializer) ? baseUrlProp.initializer.text : defaultBaseUrl; + } + else { + changes.insertNodeAtObjectStart(tsconfig, compilerOptions, makeDefaultBaseUrl()); + return defaultBaseUrl; + } + } + var defaultTypesDirectoryName = "types"; + function makeDefaultPathMapping() { + return createJsonPropertyAssignment("*", ts.createArrayLiteral([ts.createStringLiteral(defaultTypesDirectoryName + "/*")])); + } + function makeDefaultPaths() { + return createJsonPropertyAssignment("paths", ts.createObjectLiteral([makeDefaultPathMapping()])); + } + function getOrAddPathMapping(changes, tsconfig, compilerOptions) { + var paths = findProperty(compilerOptions, "paths"); + if (!paths || !ts.isObjectLiteralExpression(paths.initializer)) { + changes.insertNodeAtObjectStart(tsconfig, compilerOptions, makeDefaultPaths()); + return defaultTypesDirectoryName; + } + // Look for an existing path mapping. Should look like `"*": "foo/*"`. + var existing = ts.firstDefined(paths.initializer.properties, function (prop) { + return ts.isPropertyAssignment(prop) && ts.isStringLiteral(prop.name) && prop.name.text === "*" && ts.isArrayLiteralExpression(prop.initializer) + ? ts.firstDefined(prop.initializer.elements, function (value) { return ts.isStringLiteral(value) ? ts.tryRemoveSuffix(value.text, "/*") : undefined; }) + : undefined; + }); + if (existing) + return existing; + changes.insertNodeAtObjectStart(tsconfig, paths.initializer, makeDefaultPathMapping()); + return defaultTypesDirectoryName; + } + function createJsonPropertyAssignment(name, initializer) { + return ts.createPropertyAssignment(ts.createStringLiteral(name), initializer); + } + function findProperty(obj, name) { + return ts.find(obj.properties, function (p) { return ts.isPropertyAssignment(p) && !!p.name && ts.isStringLiteral(p.name) && p.name.text === name; }); + } + function getInstallCommand(fileName, packageName) { + return { type: "install package", file: fileName, packageName: packageName }; + } + function tryGetImportedPackageName(sourceFile, pos) { + var moduleName = ts.cast(ts.getTokenAtPosition(sourceFile, pos), ts.isStringLiteral).text; + var packageName = ts.parsePackageName(moduleName).packageName; + return ts.isExternalModuleNameRelative(packageName) ? undefined : packageName; + } + function getTypesPackageNameToInstall(packageName, host, diagCode) { + return diagCode === errorCodeCannotFindModule + ? (ts.JsTyping.nodeCoreModules.has(packageName) ? "@types/node" : undefined) + : (host.isKnownTypesPackageName(packageName) ? ts.getTypesPackageName(packageName) : undefined); // TODO: GH#18217 + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var errorCodes = [ + ts.Diagnostics.Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2.code, + ts.Diagnostics.Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1.code, + ]; + var fixId = "fixClassDoesntImplementInheritedAbstractMember"; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var program = context.program, sourceFile = context.sourceFile, span = context.span; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { + return addMissingMembers(getClass(sourceFile, span.start), sourceFile, program.getTypeChecker(), t, context.preferences); + }); + return changes.length === 0 ? undefined : [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Implement_inherited_abstract_class, fixId, ts.Diagnostics.Implement_all_inherited_abstract_classes)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { + var seenClassDeclarations = ts.createMap(); + return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var classDeclaration = getClass(diag.file, diag.start); + if (ts.addToSeen(seenClassDeclarations, ts.getNodeId(classDeclaration))) { + addMissingMembers(classDeclaration, context.sourceFile, context.program.getTypeChecker(), changes, context.preferences); + } + }); + }, + }); + function getClass(sourceFile, pos) { + // Token is the identifier in the case of a class declaration + // or the class keyword token in the case of a class expression. + var token = ts.getTokenAtPosition(sourceFile, pos); + return ts.cast(token.parent, ts.isClassLike); + } + function addMissingMembers(classDeclaration, sourceFile, checker, changeTracker, preferences) { + var extendsNode = ts.getEffectiveBaseTypeNode(classDeclaration); + var instantiatedExtendsType = checker.getTypeAtLocation(extendsNode); + // Note that this is ultimately derived from a map indexed by symbol names, + // so duplicates cannot occur. + var abstractAndNonPrivateExtendsSymbols = checker.getPropertiesOfType(instantiatedExtendsType).filter(symbolPointsToNonPrivateAndAbstractMember); + codefix.createMissingMemberNodes(classDeclaration, abstractAndNonPrivateExtendsSymbols, checker, preferences, function (member) { return changeTracker.insertNodeAtClassStart(sourceFile, classDeclaration, member); }); + } + function symbolPointsToNonPrivateAndAbstractMember(symbol) { + // See `codeFixClassExtendAbstractProtectedProperty.ts` in https://github.com/Microsoft/TypeScript/pull/11547/files + // (now named `codeFixClassExtendAbstractPrivateProperty.ts`) + var flags = ts.getModifierFlags(ts.first(symbol.getDeclarations())); + return !(flags & 8 /* Private */) && !!(flags & 128 /* Abstract */); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "classSuperMustPrecedeThisAccess"; + var errorCodes = [ts.Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var sourceFile = context.sourceFile, span = context.span; + var nodes = getNodes(sourceFile, span.start); + if (!nodes) + return undefined; + var constructor = nodes.constructor, superCall = nodes.superCall; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, constructor, superCall); }); + return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Make_super_call_the_first_statement_in_the_constructor, fixId, ts.Diagnostics.Make_all_super_calls_the_first_statement_in_their_constructor)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { + var sourceFile = context.sourceFile; + var seenClasses = ts.createMap(); // Ensure we only do this once per class. + return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var nodes = getNodes(diag.file, diag.start); + if (!nodes) + return; + var constructor = nodes.constructor, superCall = nodes.superCall; + if (ts.addToSeen(seenClasses, ts.getNodeId(constructor.parent))) { + doChange(changes, sourceFile, constructor, superCall); + } + }); + }, + }); + function doChange(changes, sourceFile, constructor, superCall) { + changes.insertNodeAtConstructorStart(sourceFile, constructor, superCall); + changes.delete(sourceFile, superCall); + } + function getNodes(sourceFile, pos) { + var token = ts.getTokenAtPosition(sourceFile, pos); + if (token.kind !== 100 /* ThisKeyword */) + return undefined; + var constructor = ts.getContainingFunction(token); + var superCall = findSuperCall(constructor.body); + // figure out if the `this` access is actually inside the supercall + // i.e. super(this.a), since in that case we won't suggest a fix + return superCall && !superCall.expression.arguments.some(function (arg) { return ts.isPropertyAccessExpression(arg) && arg.expression === token; }) ? { constructor: constructor, superCall: superCall } : undefined; + } + function findSuperCall(n) { + return ts.isExpressionStatement(n) && ts.isSuperCall(n.expression) + ? n + : ts.isFunctionLike(n) + ? undefined + : ts.forEachChild(n, findSuperCall); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "constructorForDerivedNeedSuperCall"; + var errorCodes = [ts.Diagnostics.Constructors_for_derived_classes_must_contain_a_super_call.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var sourceFile = context.sourceFile, span = context.span; + var ctr = getNode(sourceFile, span.start); + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, ctr); }); + return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Add_missing_super_call, fixId, ts.Diagnostics.Add_all_missing_super_calls)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + return doChange(changes, context.sourceFile, getNode(diag.file, diag.start)); + }); }, + }); + function getNode(sourceFile, pos) { + var token = ts.getTokenAtPosition(sourceFile, pos); + ts.Debug.assert(token.kind === 124 /* ConstructorKeyword */); + return token.parent; + } + function doChange(changes, sourceFile, ctr) { + var superCall = ts.createStatement(ts.createCall(ts.createSuper(), /*typeArguments*/ undefined, /*argumentsArray*/ ts.emptyArray)); + changes.insertNodeAtConstructorStart(sourceFile, ctr, superCall); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "extendsInterfaceBecomesImplements"; + var errorCodes = [ts.Diagnostics.Cannot_extend_an_interface_0_Did_you_mean_implements.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var sourceFile = context.sourceFile; + var nodes = getNodes(sourceFile, context.span.start); + if (!nodes) + return undefined; + var extendsToken = nodes.extendsToken, heritageClauses = nodes.heritageClauses; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChanges(t, sourceFile, extendsToken, heritageClauses); }); + return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Change_extends_to_implements, fixId, ts.Diagnostics.Change_all_extended_interfaces_to_implements)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var nodes = getNodes(diag.file, diag.start); + if (nodes) + doChanges(changes, diag.file, nodes.extendsToken, nodes.heritageClauses); + }); }, + }); + function getNodes(sourceFile, pos) { + var token = ts.getTokenAtPosition(sourceFile, pos); + var heritageClauses = ts.getContainingClass(token).heritageClauses; + var extendsToken = heritageClauses[0].getFirstToken(); + return extendsToken.kind === 86 /* ExtendsKeyword */ ? { extendsToken: extendsToken, heritageClauses: heritageClauses } : undefined; + } + function doChanges(changes, sourceFile, extendsToken, heritageClauses) { + changes.replaceNode(sourceFile, extendsToken, ts.createToken(109 /* ImplementsKeyword */)); + // If there is already an implements clause, replace the implements keyword with a comma. + if (heritageClauses.length === 2 && + heritageClauses[0].token === 86 /* ExtendsKeyword */ && + heritageClauses[1].token === 109 /* ImplementsKeyword */) { + var implementsToken = heritageClauses[1].getFirstToken(); + var implementsFullStart = implementsToken.getFullStart(); + changes.replaceRange(sourceFile, { pos: implementsFullStart, end: implementsFullStart }, ts.createToken(27 /* CommaToken */)); + // Rough heuristic: delete trailing whitespace after keyword so that it's not excessive. + // (Trailing because leading might be indentation, which is more sensitive.) + var text = sourceFile.text; + var end = implementsToken.end; + while (end < text.length && ts.isWhiteSpaceSingleLine(text.charCodeAt(end))) { + end++; + } + changes.deleteRange(sourceFile, { pos: implementsToken.getStart(), end: end }); + } + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "forgottenThisPropertyAccess"; + var didYouMeanStaticMemberCode = ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_static_member_1_0.code; + var errorCodes = [ + ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0.code, + didYouMeanStaticMemberCode, + ]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var sourceFile = context.sourceFile; + var info = getInfo(sourceFile, context.span.start, context.errorCode); + if (!info) { + return undefined; + } + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, info); }); + return [codefix.createCodeFixAction(fixId, changes, [ts.Diagnostics.Add_0_to_unresolved_variable, info.className || "this"], fixId, ts.Diagnostics.Add_qualifier_to_all_unresolved_variables_matching_a_member_name)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var info = getInfo(diag.file, diag.start, diag.code); + if (info) + doChange(changes, context.sourceFile, info); + }); }, + }); + function getInfo(sourceFile, pos, diagCode) { + var node = ts.getTokenAtPosition(sourceFile, pos); + if (!ts.isIdentifier(node)) + return undefined; + return { node: node, className: diagCode === didYouMeanStaticMemberCode ? ts.getContainingClass(node).name.text : undefined }; + } + function doChange(changes, sourceFile, _a) { + var node = _a.node, className = _a.className; + // TODO (https://github.com/Microsoft/TypeScript/issues/21246): use shared helper + ts.suppressLeadingAndTrailingTrivia(node); + changes.replaceNode(sourceFile, node, ts.createPropertyAccess(className ? ts.createIdentifier(className) : ts.createThis(), node)); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixName = "unusedIdentifier"; + var fixIdPrefix = "unusedIdentifier_prefix"; + var fixIdDelete = "unusedIdentifier_delete"; + var fixIdInfer = "unusedIdentifier_infer"; + var errorCodes = [ + ts.Diagnostics._0_is_declared_but_its_value_is_never_read.code, + ts.Diagnostics._0_is_declared_but_never_used.code, + ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read.code, + ts.Diagnostics.All_imports_in_import_declaration_are_unused.code, + ts.Diagnostics.All_destructured_elements_are_unused.code, + ts.Diagnostics.All_variables_are_unused.code, + ts.Diagnostics.All_type_parameters_are_unused.code, + ]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var errorCode = context.errorCode, sourceFile = context.sourceFile, program = context.program; + var checker = program.getTypeChecker(); + var sourceFiles = program.getSourceFiles(); + var token = ts.getTokenAtPosition(sourceFile, context.span.start); + if (ts.isJSDocTemplateTag(token)) { + return [createDeleteFix(ts.textChanges.ChangeTracker.with(context, function (t) { return t.delete(sourceFile, token); }), ts.Diagnostics.Remove_template_tag)]; + } + if (token.kind === 28 /* LessThanToken */) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return deleteTypeParameters(t, sourceFile, token); }); + return [createDeleteFix(changes, ts.Diagnostics.Remove_type_parameters)]; + } + var importDecl = tryGetFullImport(token); + if (importDecl) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.delete(sourceFile, importDecl); }); + return [createDeleteFix(changes, [ts.Diagnostics.Remove_import_from_0, ts.showModuleSpecifier(importDecl)])]; + } + var delDestructure = ts.textChanges.ChangeTracker.with(context, function (t) { + return tryDeleteFullDestructure(token, t, sourceFile, checker, sourceFiles, /*isFixAll*/ false); + }); + if (delDestructure.length) { + return [createDeleteFix(delDestructure, ts.Diagnostics.Remove_destructuring)]; + } + var delVar = ts.textChanges.ChangeTracker.with(context, function (t) { return tryDeleteFullVariableStatement(sourceFile, token, t); }); + if (delVar.length) { + return [createDeleteFix(delVar, ts.Diagnostics.Remove_variable_statement)]; + } + var result = []; + if (token.kind === 127 /* InferKeyword */) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return changeInferToUnknown(t, sourceFile, token); }); + var name = ts.cast(token.parent, ts.isInferTypeNode).typeParameter.name.text; + result.push(codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Replace_infer_0_with_unknown, name], fixIdInfer, ts.Diagnostics.Replace_all_unused_infer_with_unknown)); + } + else { + var deletion = ts.textChanges.ChangeTracker.with(context, function (t) { + return tryDeleteDeclaration(sourceFile, token, t, checker, sourceFiles, /*isFixAll*/ false); + }); + if (deletion.length) { + var name = ts.isComputedPropertyName(token.parent) ? token.parent : token; + result.push(createDeleteFix(deletion, [ts.Diagnostics.Remove_declaration_for_Colon_0, name.getText(sourceFile)])); + } + } + var prefix = ts.textChanges.ChangeTracker.with(context, function (t) { return tryPrefixDeclaration(t, errorCode, sourceFile, token); }); + if (prefix.length) { + result.push(codefix.createCodeFixAction(fixName, prefix, [ts.Diagnostics.Prefix_0_with_an_underscore, token.getText(sourceFile)], fixIdPrefix, ts.Diagnostics.Prefix_all_unused_declarations_with_where_possible)); + } + return result; + }, + fixIds: [fixIdPrefix, fixIdDelete, fixIdInfer], + getAllCodeActions: function (context) { + var sourceFile = context.sourceFile, program = context.program; + var checker = program.getTypeChecker(); + var sourceFiles = program.getSourceFiles(); + return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var token = ts.getTokenAtPosition(sourceFile, diag.start); + switch (context.fixId) { + case fixIdPrefix: + tryPrefixDeclaration(changes, diag.code, sourceFile, token); + break; + case fixIdDelete: { + if (token.kind === 127 /* InferKeyword */) + break; // Can't delete + var importDecl = tryGetFullImport(token); + if (importDecl) { + changes.delete(sourceFile, importDecl); + } + else if (ts.isJSDocTemplateTag(token)) { + changes.delete(sourceFile, token); + } + else if (token.kind === 28 /* LessThanToken */) { + deleteTypeParameters(changes, sourceFile, token); + } + else if (!tryDeleteFullDestructure(token, changes, sourceFile, checker, sourceFiles, /*isFixAll*/ true) && + !tryDeleteFullVariableStatement(sourceFile, token, changes)) { + tryDeleteDeclaration(sourceFile, token, changes, checker, sourceFiles, /*isFixAll*/ true); + } + break; + } + case fixIdInfer: + if (token.kind === 127 /* InferKeyword */) { + changeInferToUnknown(changes, sourceFile, token); + } + break; + default: + ts.Debug.fail(JSON.stringify(context.fixId)); + } + }); + }, + }); + function changeInferToUnknown(changes, sourceFile, token) { + changes.replaceNode(sourceFile, token.parent, ts.createKeywordTypeNode(143 /* UnknownKeyword */)); + } + function createDeleteFix(changes, diag) { + return codefix.createCodeFixAction(fixName, changes, diag, fixIdDelete, ts.Diagnostics.Delete_all_unused_declarations); + } + function deleteTypeParameters(changes, sourceFile, token) { + changes.delete(sourceFile, ts.Debug.assertDefined(ts.cast(token.parent, ts.isDeclarationWithTypeParameterChildren).typeParameters)); + } + // Sometimes the diagnostic span is an entire ImportDeclaration, so we should remove the whole thing. + function tryGetFullImport(token) { + return token.kind === 92 /* ImportKeyword */ ? ts.tryCast(token.parent, ts.isImportDeclaration) : undefined; + } + function tryDeleteFullDestructure(token, changes, sourceFile, checker, sourceFiles, isFixAll) { + if (token.kind !== 18 /* OpenBraceToken */ || !ts.isObjectBindingPattern(token.parent)) + return false; + var decl = token.parent.parent; + if (decl.kind === 151 /* Parameter */) { + tryDeleteParameter(changes, sourceFile, decl, checker, sourceFiles, isFixAll); + } + else { + changes.delete(sourceFile, decl); + } + return true; + } + function tryDeleteFullVariableStatement(sourceFile, token, changes) { + var declarationList = ts.tryCast(token.parent, ts.isVariableDeclarationList); + if (declarationList && declarationList.getChildren(sourceFile)[0] === token) { + changes.delete(sourceFile, declarationList.parent.kind === 219 /* VariableStatement */ ? declarationList.parent : declarationList); + return true; + } + return false; + } + function tryPrefixDeclaration(changes, errorCode, sourceFile, token) { + // Don't offer to prefix a property. + if (errorCode === ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read.code) + return; + if (token.kind === 127 /* InferKeyword */) { + token = ts.cast(token.parent, ts.isInferTypeNode).typeParameter.name; + } + if (ts.isIdentifier(token) && canPrefix(token)) { + changes.replaceNode(sourceFile, token, ts.createIdentifier("_" + token.text)); + } + } + function canPrefix(token) { + switch (token.parent.kind) { + case 151 /* Parameter */: + case 150 /* TypeParameter */: + return true; + case 237 /* VariableDeclaration */: { + var varDecl = token.parent; + switch (varDecl.parent.parent.kind) { + case 227 /* ForOfStatement */: + case 226 /* ForInStatement */: + return true; + } + } + } + return false; + } + function tryDeleteDeclaration(sourceFile, token, changes, checker, sourceFiles, isFixAll) { + tryDeleteDeclarationWorker(token, changes, sourceFile, checker, sourceFiles, isFixAll); + if (ts.isIdentifier(token)) + deleteAssignments(changes, sourceFile, token, checker); + } + function deleteAssignments(changes, sourceFile, token, checker) { + ts.FindAllReferences.Core.eachSymbolReferenceInFile(token, checker, sourceFile, function (ref) { + if (ts.isPropertyAccessExpression(ref.parent) && ref.parent.name === ref) + ref = ref.parent; + if (ts.isBinaryExpression(ref.parent) && ts.isExpressionStatement(ref.parent.parent) && ref.parent.left === ref) { + changes.delete(sourceFile, ref.parent.parent); + } + }); + } + function tryDeleteDeclarationWorker(token, changes, sourceFile, checker, sourceFiles, isFixAll) { + var parent = token.parent; + if (ts.isParameter(parent)) { + tryDeleteParameter(changes, sourceFile, parent, checker, sourceFiles, isFixAll); + } + else { + changes.delete(sourceFile, ts.isImportClause(parent) ? token : ts.isComputedPropertyName(parent) ? parent.parent : parent); + } + } + function tryDeleteParameter(changes, sourceFile, p, checker, sourceFiles, isFixAll) { + if (mayDeleteParameter(p, checker, isFixAll)) { + if (p.modifiers && p.modifiers.length > 0 + && (!ts.isIdentifier(p.name) || ts.FindAllReferences.Core.isSymbolReferencedInFile(p.name, checker, sourceFile))) { + p.modifiers.forEach(function (modifier) { + changes.deleteModifier(sourceFile, modifier); + }); + } + else { + changes.delete(sourceFile, p); + deleteUnusedArguments(changes, sourceFile, p, sourceFiles, checker); + } + } + } + function mayDeleteParameter(p, checker, isFixAll) { + var parent = p.parent; + switch (parent.kind) { + case 156 /* MethodDeclaration */: + // Don't remove a parameter if this overrides something. + var symbol = checker.getSymbolAtLocation(parent.name); + if (ts.isMemberSymbolInBaseType(symbol, checker)) + return false; + // falls through + case 157 /* Constructor */: + case 239 /* FunctionDeclaration */: + return true; + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: { + // Can't remove a non-last parameter in a callback. Can remove a parameter in code-fix-all if future parameters are also unused. + var parameters = parent.parameters; + var index = parameters.indexOf(p); + ts.Debug.assert(index !== -1); + return isFixAll + ? parameters.slice(index + 1).every(function (p) { return p.name.kind === 72 /* Identifier */ && !p.symbol.isReferenced; }) + : index === parameters.length - 1; + } + case 159 /* SetAccessor */: + // Setter must have a parameter + return false; + default: + return ts.Debug.failBadSyntaxKind(parent); + } + } + function deleteUnusedArguments(changes, sourceFile, deletedParameter, sourceFiles, checker) { + ts.FindAllReferences.Core.eachSignatureCall(deletedParameter.parent, sourceFiles, checker, function (call) { + var index = deletedParameter.parent.parameters.indexOf(deletedParameter); + if (call.arguments.length > index) { // Just in case the call didn't provide enough arguments. + changes.delete(sourceFile, call.arguments[index]); + } + }); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "fixUnreachableCode"; + var errorCodes = [ts.Diagnostics.Unreachable_code_detected.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, context.sourceFile, context.span.start, context.span.length); }); + return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Remove_unreachable_code, fixId, ts.Diagnostics.Remove_all_unreachable_code)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { return doChange(changes, diag.file, diag.start, diag.length); }); }, + }); + function doChange(changes, sourceFile, start, length) { + var token = ts.getTokenAtPosition(sourceFile, start); + var statement = ts.findAncestor(token, ts.isStatement); + ts.Debug.assert(statement.getStart(sourceFile) === token.getStart(sourceFile)); + var container = (ts.isBlock(statement.parent) ? statement.parent : statement).parent; + if (!ts.isBlock(statement.parent) || statement === ts.first(statement.parent.statements)) { + switch (container.kind) { + case 222 /* IfStatement */: + if (container.elseStatement) { + if (ts.isBlock(statement.parent)) { + break; + } + else { + changes.replaceNode(sourceFile, statement, ts.createBlock(ts.emptyArray)); + } + return; + } + // falls through + case 224 /* WhileStatement */: + case 225 /* ForStatement */: + changes.delete(sourceFile, container); + return; + } + } + if (ts.isBlock(statement.parent)) { + var end_2 = start + length; + var lastStatement = ts.Debug.assertDefined(lastWhere(ts.sliceAfter(statement.parent.statements, statement), function (s) { return s.pos < end_2; })); + changes.deleteNodeRange(sourceFile, statement, lastStatement); + } + else { + changes.delete(sourceFile, statement); + } + } + function lastWhere(a, pred) { + var last; + for (var _i = 0, a_1 = a; _i < a_1.length; _i++) { + var value = a_1[_i]; + if (!pred(value)) + break; + last = value; + } + return last; + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "fixUnusedLabel"; + var errorCodes = [ts.Diagnostics.Unused_label.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, context.sourceFile, context.span.start); }); + return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Remove_unused_label, fixId, ts.Diagnostics.Remove_all_unused_labels)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { return doChange(changes, diag.file, diag.start); }); }, + }); + function doChange(changes, sourceFile, start) { + var token = ts.getTokenAtPosition(sourceFile, start); + var labeledStatement = ts.cast(token.parent, ts.isLabeledStatement); + var pos = token.getStart(sourceFile); + var statementPos = labeledStatement.statement.getStart(sourceFile); + // If label is on a separate line, just delete the rest of that line, but not the indentation of the labeled statement. + var end = ts.positionsAreOnSameLine(pos, statementPos, sourceFile) ? statementPos + : ts.skipTrivia(sourceFile.text, ts.findChildOfKind(labeledStatement, 57 /* ColonToken */, sourceFile).end, /*stopAfterLineBreak*/ true); + changes.deleteRange(sourceFile, { pos: pos, end: end }); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixIdPlain = "fixJSDocTypes_plain"; + var fixIdNullable = "fixJSDocTypes_nullable"; + var errorCodes = [ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var sourceFile = context.sourceFile; + var checker = context.program.getTypeChecker(); + var info = getInfo(sourceFile, context.span.start, checker); + if (!info) + return undefined; + var typeNode = info.typeNode, type = info.type; + var original = typeNode.getText(sourceFile); + var actions = [fix(type, fixIdPlain, ts.Diagnostics.Change_all_jsdoc_style_types_to_TypeScript)]; + if (typeNode.kind === 286 /* JSDocNullableType */) { + // for nullable types, suggest the flow-compatible `T | null | undefined` + // in addition to the jsdoc/closure-compatible `T | null` + actions.push(fix(checker.getNullableType(type, 32768 /* Undefined */), fixIdNullable, ts.Diagnostics.Change_all_jsdoc_style_types_to_TypeScript_and_add_undefined_to_nullable_types)); + } + return actions; + function fix(type, fixId, fixAllDescription) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, typeNode, type, checker); }); + return codefix.createCodeFixAction("jdocTypes", changes, [ts.Diagnostics.Change_0_to_1, original, checker.typeToString(type)], fixId, fixAllDescription); + } + }, + fixIds: [fixIdPlain, fixIdNullable], + getAllCodeActions: function (context) { + var fixId = context.fixId, program = context.program, sourceFile = context.sourceFile; + var checker = program.getTypeChecker(); + return codefix.codeFixAll(context, errorCodes, function (changes, err) { + var info = getInfo(err.file, err.start, checker); + if (!info) + return; + var typeNode = info.typeNode, type = info.type; + var fixedType = typeNode.kind === 286 /* JSDocNullableType */ && fixId === fixIdNullable ? checker.getNullableType(type, 32768 /* Undefined */) : type; + doChange(changes, sourceFile, typeNode, fixedType, checker); + }); + } + }); + function doChange(changes, sourceFile, oldTypeNode, newType, checker) { + changes.replaceNode(sourceFile, oldTypeNode, checker.typeToTypeNode(newType, /*enclosingDeclaration*/ oldTypeNode)); // TODO: GH#18217 + } + function getInfo(sourceFile, pos, checker) { + var decl = ts.findAncestor(ts.getTokenAtPosition(sourceFile, pos), isTypeContainer); + var typeNode = decl && decl.type; + return typeNode && { typeNode: typeNode, type: checker.getTypeFromTypeNode(typeNode) }; + } + function isTypeContainer(node) { + // NOTE: Some locations are not handled yet: + // MappedTypeNode.typeParameters and SignatureDeclaration.typeParameters, as well as CallExpression.typeArguments + switch (node.kind) { + case 212 /* AsExpression */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 239 /* FunctionDeclaration */: + case 158 /* GetAccessor */: + case 162 /* IndexSignature */: + case 181 /* MappedType */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 151 /* Parameter */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 159 /* SetAccessor */: + case 242 /* TypeAliasDeclaration */: + case 194 /* TypeAssertionExpression */: + case 237 /* VariableDeclaration */: + return true; + default: + return false; + } + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "fixAwaitInSyncFunction"; + var errorCodes = [ + ts.Diagnostics.await_expression_is_only_allowed_within_an_async_function.code, + ts.Diagnostics.A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator.code, + ]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var sourceFile = context.sourceFile, span = context.span; + var nodes = getNodes(sourceFile, span.start); + if (!nodes) + return undefined; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, nodes); }); + return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Add_async_modifier_to_containing_function, fixId, ts.Diagnostics.Add_all_missing_async_modifiers)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var nodes = getNodes(diag.file, diag.start); + if (!nodes) + return; + doChange(changes, context.sourceFile, nodes); + }); }, + }); + function getReturnType(expr) { + if (expr.type) { + return expr.type; + } + if (ts.isVariableDeclaration(expr.parent) && + expr.parent.type && + ts.isFunctionTypeNode(expr.parent.type)) { + return expr.parent.type.type; + } + } + function getNodes(sourceFile, start) { + var token = ts.getTokenAtPosition(sourceFile, start); + var containingFunction = ts.getContainingFunction(token); + if (!containingFunction) { + return; + } + var insertBefore; + switch (containingFunction.kind) { + case 156 /* MethodDeclaration */: + insertBefore = containingFunction.name; + break; + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + insertBefore = ts.findChildOfKind(containingFunction, 90 /* FunctionKeyword */, sourceFile); + break; + case 197 /* ArrowFunction */: + insertBefore = ts.findChildOfKind(containingFunction, 20 /* OpenParenToken */, sourceFile) || ts.first(containingFunction.parameters); + break; + default: + return; + } + return insertBefore && { + insertBefore: insertBefore, + returnType: getReturnType(containingFunction) + }; + } + function doChange(changes, sourceFile, _a) { + var insertBefore = _a.insertBefore, returnType = _a.returnType; + if (returnType) { + var entityName = ts.getEntityNameFromTypeNode(returnType); + if (!entityName || entityName.kind !== 72 /* Identifier */ || entityName.text !== "Promise") { + changes.replaceNode(sourceFile, returnType, ts.createTypeReferenceNode("Promise", ts.createNodeArray([returnType]))); + } + } + changes.insertModifierBefore(sourceFile, 121 /* AsyncKeyword */, insertBefore); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixName = "disableJsDiagnostics"; + var fixId = "disableJsDiagnostics"; + var errorCodes = ts.mapDefined(Object.keys(ts.Diagnostics), function (key) { + var diag = ts.Diagnostics[key]; + return diag.category === ts.DiagnosticCategory.Error ? diag.code : undefined; + }); + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var sourceFile = context.sourceFile, program = context.program, span = context.span, host = context.host, formatContext = context.formatContext; + if (!ts.isInJSFile(sourceFile) || !ts.isCheckJsEnabledForFile(sourceFile, program.getCompilerOptions())) { + return undefined; + } + var fixes = [ + // fixId unnecessary because adding `// @ts-nocheck` even once will ignore every error in the file. + codefix.createCodeFixActionNoFixId(fixName, [codefix.createFileTextChanges(sourceFile.fileName, [ + ts.createTextChange(sourceFile.checkJsDirective + ? ts.createTextSpanFromBounds(sourceFile.checkJsDirective.pos, sourceFile.checkJsDirective.end) + : ts.createTextSpan(0, 0), "// @ts-nocheck" + ts.getNewLineOrDefaultFromHost(host, formatContext.options)), + ])], ts.Diagnostics.Disable_checking_for_this_file), + ]; + if (ts.textChanges.isValidLocationToAddComment(sourceFile, span.start)) { + fixes.unshift(codefix.createCodeFixAction(fixName, ts.textChanges.ChangeTracker.with(context, function (t) { return makeChange(t, sourceFile, span.start); }), ts.Diagnostics.Ignore_this_error_message, fixId, ts.Diagnostics.Add_ts_ignore_to_all_error_messages)); + } + return fixes; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { + var seenLines = ts.createMap(); + return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + if (ts.textChanges.isValidLocationToAddComment(diag.file, diag.start)) { + makeChange(changes, diag.file, diag.start, seenLines); + } + }); + }, + }); + function makeChange(changes, sourceFile, position, seenLines) { + var lineNumber = ts.getLineAndCharacterOfPosition(sourceFile, position).line; + // Only need to add `// @ts-ignore` for a line once. + if (!seenLines || ts.addToSeen(seenLines, lineNumber)) { + changes.insertCommentBeforeLine(sourceFile, lineNumber, position, " @ts-ignore"); + } + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + /** + * Finds members of the resolved type that are missing in the class pointed to by class decl + * and generates source code for the missing members. + * @param possiblyMissingSymbols The collection of symbols to filter and then get insertions for. + * @returns Empty string iff there are no member insertions. + */ + function createMissingMemberNodes(classDeclaration, possiblyMissingSymbols, checker, preferences, out) { + var classMembers = classDeclaration.symbol.members; + for (var _i = 0, possiblyMissingSymbols_1 = possiblyMissingSymbols; _i < possiblyMissingSymbols_1.length; _i++) { + var symbol = possiblyMissingSymbols_1[_i]; + if (!classMembers.has(symbol.escapedName)) { + addNewNodeForMemberSymbol(symbol, classDeclaration, checker, preferences, out); + } + } + } + codefix.createMissingMemberNodes = createMissingMemberNodes; + /** + * @returns Empty string iff there we can't figure out a representation for `symbol` in `enclosingDeclaration`. + */ + function addNewNodeForMemberSymbol(symbol, enclosingDeclaration, checker, preferences, out) { + var declarations = symbol.getDeclarations(); + if (!(declarations && declarations.length)) { + return undefined; + } + var declaration = declarations[0]; + var name = ts.getSynthesizedDeepClone(ts.getNameOfDeclaration(declaration), /*includeTrivia*/ false); + var visibilityModifier = createVisibilityModifier(ts.getModifierFlags(declaration)); + var modifiers = visibilityModifier ? ts.createNodeArray([visibilityModifier]) : undefined; + var type = checker.getWidenedType(checker.getTypeOfSymbolAtLocation(symbol, enclosingDeclaration)); + var optional = !!(symbol.flags & 16777216 /* Optional */); + switch (declaration.kind) { + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 153 /* PropertySignature */: + case 154 /* PropertyDeclaration */: + var typeNode = checker.typeToTypeNode(type, enclosingDeclaration); + out(ts.createProperty( + /*decorators*/ undefined, modifiers, name, optional ? ts.createToken(56 /* QuestionToken */) : undefined, typeNode, + /*initializer*/ undefined)); + break; + case 155 /* MethodSignature */: + case 156 /* MethodDeclaration */: + // The signature for the implementation appears as an entry in `signatures` iff + // there is only one signature. + // If there are overloads and an implementation signature, it appears as an + // extra declaration that isn't a signature for `type`. + // If there is more than one overload but no implementation signature + // (eg: an abstract method or interface declaration), there is a 1-1 + // correspondence of declarations and signatures. + var signatures = checker.getSignaturesOfType(type, 0 /* Call */); + if (!ts.some(signatures)) { + break; + } + if (declarations.length === 1) { + ts.Debug.assert(signatures.length === 1); + var signature = signatures[0]; + outputMethod(signature, modifiers, name, createStubbedMethodBody(preferences)); + break; + } + for (var _i = 0, signatures_1 = signatures; _i < signatures_1.length; _i++) { + var signature = signatures_1[_i]; + // Need to ensure nodes are fresh each time so they can have different positions. + outputMethod(signature, ts.getSynthesizedDeepClones(modifiers, /*includeTrivia*/ false), ts.getSynthesizedDeepClone(name, /*includeTrivia*/ false)); + } + if (declarations.length > signatures.length) { + var signature = checker.getSignatureFromDeclaration(declarations[declarations.length - 1]); + outputMethod(signature, modifiers, name, createStubbedMethodBody(preferences)); + } + else { + ts.Debug.assert(declarations.length === signatures.length); + out(createMethodImplementingSignatures(signatures, name, optional, modifiers, preferences)); + } + break; + } + function outputMethod(signature, modifiers, name, body) { + var method = signatureToMethodDeclaration(checker, signature, enclosingDeclaration, modifiers, name, optional, body); + if (method) + out(method); + } + } + function signatureToMethodDeclaration(checker, signature, enclosingDeclaration, modifiers, name, optional, body) { + var signatureDeclaration = checker.signatureToSignatureDeclaration(signature, 156 /* MethodDeclaration */, enclosingDeclaration, 256 /* SuppressAnyReturnType */); + if (!signatureDeclaration) { + return undefined; + } + signatureDeclaration.decorators = undefined; + signatureDeclaration.modifiers = modifiers; + signatureDeclaration.name = name; + signatureDeclaration.questionToken = optional ? ts.createToken(56 /* QuestionToken */) : undefined; + signatureDeclaration.body = body; + return signatureDeclaration; + } + function createMethodFromCallExpression(context, call, methodName, inJs, makeStatic, preferences, body) { + var typeArguments = call.typeArguments, args = call.arguments, parent = call.parent; + var checker = context.program.getTypeChecker(); + var types = ts.map(args, function (arg) { + // Widen the type so we don't emit nonsense annotations like "function fn(x: 3) {" + return checker.typeToTypeNode(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(arg))); + }); + var names = ts.map(args, function (arg) { + return ts.isIdentifier(arg) ? arg.text : + ts.isPropertyAccessExpression(arg) ? arg.name.text : undefined; + }); + var contextualType = checker.getContextualType(call); + var returnType = inJs ? undefined : contextualType && checker.typeToTypeNode(contextualType, call) || ts.createKeywordTypeNode(120 /* AnyKeyword */); + return ts.createMethod( + /*decorators*/ undefined, + /*modifiers*/ makeStatic ? [ts.createToken(116 /* StaticKeyword */)] : undefined, + /*asteriskToken*/ ts.isYieldExpression(parent) ? ts.createToken(40 /* AsteriskToken */) : undefined, methodName, + /*questionToken*/ undefined, + /*typeParameters*/ inJs ? undefined : ts.map(typeArguments, function (_, i) { + return ts.createTypeParameterDeclaration(84 /* T */ + typeArguments.length - 1 <= 90 /* Z */ ? String.fromCharCode(84 /* T */ + i) : "T" + i); + }), + /*parameters*/ createDummyParameters(args.length, names, types, /*minArgumentCount*/ undefined, inJs), + /*type*/ returnType, body ? createStubbedMethodBody(preferences) : undefined); + } + codefix.createMethodFromCallExpression = createMethodFromCallExpression; + function createDummyParameters(argCount, names, types, minArgumentCount, inJs) { + var parameters = []; + for (var i = 0; i < argCount; i++) { + var newParameter = ts.createParameter( + /*decorators*/ undefined, + /*modifiers*/ undefined, + /*dotDotDotToken*/ undefined, + /*name*/ names && names[i] || "arg" + i, + /*questionToken*/ minArgumentCount !== undefined && i >= minArgumentCount ? ts.createToken(56 /* QuestionToken */) : undefined, + /*type*/ inJs ? undefined : types && types[i] || ts.createKeywordTypeNode(120 /* AnyKeyword */), + /*initializer*/ undefined); + parameters.push(newParameter); + } + return parameters; + } + function createMethodImplementingSignatures(signatures, name, optional, modifiers, preferences) { + /** This is *a* signature with the maximal number of arguments, + * such that if there is a "maximal" signature without rest arguments, + * this is one of them. + */ + var maxArgsSignature = signatures[0]; + var minArgumentCount = signatures[0].minArgumentCount; + var someSigHasRestParameter = false; + for (var _i = 0, signatures_2 = signatures; _i < signatures_2.length; _i++) { + var sig = signatures_2[_i]; + minArgumentCount = Math.min(sig.minArgumentCount, minArgumentCount); + if (sig.hasRestParameter) { + someSigHasRestParameter = true; + } + if (sig.parameters.length >= maxArgsSignature.parameters.length && (!sig.hasRestParameter || maxArgsSignature.hasRestParameter)) { + maxArgsSignature = sig; + } + } + var maxNonRestArgs = maxArgsSignature.parameters.length - (maxArgsSignature.hasRestParameter ? 1 : 0); + var maxArgsParameterSymbolNames = maxArgsSignature.parameters.map(function (symbol) { return symbol.name; }); + var parameters = createDummyParameters(maxNonRestArgs, maxArgsParameterSymbolNames, /* types */ undefined, minArgumentCount, /*inJs*/ false); + if (someSigHasRestParameter) { + var anyArrayType = ts.createArrayTypeNode(ts.createKeywordTypeNode(120 /* AnyKeyword */)); + var restParameter = ts.createParameter( + /*decorators*/ undefined, + /*modifiers*/ undefined, ts.createToken(25 /* DotDotDotToken */), maxArgsParameterSymbolNames[maxNonRestArgs] || "rest", + /*questionToken*/ maxNonRestArgs >= minArgumentCount ? ts.createToken(56 /* QuestionToken */) : undefined, anyArrayType, + /*initializer*/ undefined); + parameters.push(restParameter); + } + return createStubbedMethod(modifiers, name, optional, + /*typeParameters*/ undefined, parameters, + /*returnType*/ undefined, preferences); + } + function createStubbedMethod(modifiers, name, optional, typeParameters, parameters, returnType, preferences) { + return ts.createMethod( + /*decorators*/ undefined, modifiers, + /*asteriskToken*/ undefined, name, optional ? ts.createToken(56 /* QuestionToken */) : undefined, typeParameters, parameters, returnType, createStubbedMethodBody(preferences)); + } + function createStubbedMethodBody(preferences) { + return ts.createBlock([ts.createThrow(ts.createNew(ts.createIdentifier("Error"), + /*typeArguments*/ undefined, [ts.createLiteral("Method not implemented.", /*isSingleQuote*/ preferences.quotePreference === "single")]))], + /*multiline*/ true); + } + function createVisibilityModifier(flags) { + if (flags & 4 /* Public */) { + return ts.createToken(115 /* PublicKeyword */); + } + else if (flags & 16 /* Protected */) { + return ts.createToken(114 /* ProtectedKeyword */); + } + return undefined; + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixName = "invalidImportSyntax"; + function getCodeFixesForImportDeclaration(context, node) { + var sourceFile = ts.getSourceFileOfNode(node); + var namespace = ts.getNamespaceDeclarationNode(node); + var opts = context.program.getCompilerOptions(); + var variations = []; + // import Bluebird from "bluebird"; + variations.push(createAction(context, sourceFile, node, ts.makeImport(namespace.name, /*namedImports*/ undefined, node.moduleSpecifier, ts.getQuotePreference(sourceFile, context.preferences)))); + if (ts.getEmitModuleKind(opts) === ts.ModuleKind.CommonJS) { + // import Bluebird = require("bluebird"); + variations.push(createAction(context, sourceFile, node, ts.createImportEqualsDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, namespace.name, ts.createExternalModuleReference(node.moduleSpecifier)))); + } + return variations; + } + function createAction(context, sourceFile, node, replacement) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.replaceNode(sourceFile, node, replacement); }); + return codefix.createCodeFixActionNoFixId(fixName, changes, [ts.Diagnostics.Replace_import_with_0, changes[0].textChanges[0].newText]); + } + codefix.registerCodeFix({ + errorCodes: [ + ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures.code, + ts.Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature.code, + ], + getCodeActions: getActionsForUsageOfInvalidImport + }); + function getActionsForUsageOfInvalidImport(context) { + var sourceFile = context.sourceFile; + var targetKind = ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures.code === context.errorCode ? 191 /* CallExpression */ : 192 /* NewExpression */; + var node = ts.findAncestor(ts.getTokenAtPosition(sourceFile, context.span.start), function (a) { return a.kind === targetKind && a.getStart() === context.span.start && a.getEnd() === (context.span.start + context.span.length); }); + if (!node) { + return []; + } + var expr = node.expression; + return getImportCodeFixesForExpression(context, expr); + } + codefix.registerCodeFix({ + errorCodes: [ + // The following error codes cover pretty much all assignability errors that could involve an expression + ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1.code, + ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1.code, + ts.Diagnostics.Type_0_is_not_assignable_to_type_1.code, + ts.Diagnostics.Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated.code, + ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1.code, + ts.Diagnostics.Property_0_of_type_1_is_not_assignable_to_string_index_type_2.code, + ts.Diagnostics.Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2.code, + ts.Diagnostics.Numeric_index_type_0_is_not_assignable_to_string_index_type_1.code, + ts.Diagnostics.Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2.code, + ts.Diagnostics.Property_0_in_type_1_is_not_assignable_to_type_2.code, + ts.Diagnostics.Property_0_of_JSX_spread_attribute_is_not_assignable_to_target_property.code, + ts.Diagnostics.The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1.code, + ], + getCodeActions: getActionsForInvalidImportLocation + }); + function getActionsForInvalidImportLocation(context) { + var sourceFile = context.sourceFile; + var node = ts.findAncestor(ts.getTokenAtPosition(sourceFile, context.span.start), function (a) { return a.getStart() === context.span.start && a.getEnd() === (context.span.start + context.span.length); }); + if (!node) { + return []; + } + return getImportCodeFixesForExpression(context, node); + } + function getImportCodeFixesForExpression(context, expr) { + var type = context.program.getTypeChecker().getTypeAtLocation(expr); + if (!(type.symbol && type.symbol.originatingImport)) { + return []; + } + var fixes = []; + var relatedImport = type.symbol.originatingImport; // TODO: GH#18217 + if (!ts.isImportCall(relatedImport)) { + ts.addRange(fixes, getCodeFixesForImportDeclaration(context, relatedImport)); + } + if (ts.isExpression(expr) && !(ts.isNamedDeclaration(expr.parent) && expr.parent.name === expr)) { + var sourceFile_1 = context.sourceFile; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.replaceNode(sourceFile_1, expr, ts.createPropertyAccess(expr, "default"), {}); }); + fixes.push(codefix.createCodeFixActionNoFixId(fixName, changes, ts.Diagnostics.Use_synthetic_default_member)); + } + return fixes; + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixName = "strictClassInitialization"; + var fixIdAddDefiniteAssignmentAssertions = "addMissingPropertyDefiniteAssignmentAssertions"; + var fixIdAddUndefinedType = "addMissingPropertyUndefinedType"; + var fixIdAddInitializer = "addMissingPropertyInitializer"; + var errorCodes = [ts.Diagnostics.Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var propertyDeclaration = getPropertyDeclaration(context.sourceFile, context.span.start); + if (!propertyDeclaration) + return; + var result = [ + getActionForAddMissingUndefinedType(context, propertyDeclaration), + getActionForAddMissingDefiniteAssignmentAssertion(context, propertyDeclaration) + ]; + ts.append(result, getActionForAddMissingInitializer(context, propertyDeclaration)); + return result; + }, + fixIds: [fixIdAddDefiniteAssignmentAssertions, fixIdAddUndefinedType, fixIdAddInitializer], + getAllCodeActions: function (context) { + return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var propertyDeclaration = getPropertyDeclaration(diag.file, diag.start); + if (!propertyDeclaration) + return; + switch (context.fixId) { + case fixIdAddDefiniteAssignmentAssertions: + addDefiniteAssignmentAssertion(changes, diag.file, propertyDeclaration); + break; + case fixIdAddUndefinedType: + addUndefinedType(changes, diag.file, propertyDeclaration); + break; + case fixIdAddInitializer: + var checker = context.program.getTypeChecker(); + var initializer = getInitializer(checker, propertyDeclaration); + if (!initializer) + return; + addInitializer(changes, diag.file, propertyDeclaration, initializer); + break; + default: + ts.Debug.fail(JSON.stringify(context.fixId)); + } + }); + }, + }); + function getPropertyDeclaration(sourceFile, pos) { + var token = ts.getTokenAtPosition(sourceFile, pos); + return ts.isIdentifier(token) ? ts.cast(token.parent, ts.isPropertyDeclaration) : undefined; + } + function getActionForAddMissingDefiniteAssignmentAssertion(context, propertyDeclaration) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addDefiniteAssignmentAssertion(t, context.sourceFile, propertyDeclaration); }); + return codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Add_definite_assignment_assertion_to_property_0, propertyDeclaration.getText()], fixIdAddDefiniteAssignmentAssertions, ts.Diagnostics.Add_definite_assignment_assertions_to_all_uninitialized_properties); + } + function addDefiniteAssignmentAssertion(changeTracker, propertyDeclarationSourceFile, propertyDeclaration) { + var property = ts.updateProperty(propertyDeclaration, propertyDeclaration.decorators, propertyDeclaration.modifiers, propertyDeclaration.name, ts.createToken(52 /* ExclamationToken */), propertyDeclaration.type, propertyDeclaration.initializer); + changeTracker.replaceNode(propertyDeclarationSourceFile, propertyDeclaration, property); + } + function getActionForAddMissingUndefinedType(context, propertyDeclaration) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addUndefinedType(t, context.sourceFile, propertyDeclaration); }); + return codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Add_undefined_type_to_property_0, propertyDeclaration.name.getText()], fixIdAddUndefinedType, ts.Diagnostics.Add_undefined_type_to_all_uninitialized_properties); + } + function addUndefinedType(changeTracker, propertyDeclarationSourceFile, propertyDeclaration) { + var undefinedTypeNode = ts.createKeywordTypeNode(141 /* UndefinedKeyword */); + var type = propertyDeclaration.type; // TODO: GH#18217 + var types = ts.isUnionTypeNode(type) ? type.types.concat(undefinedTypeNode) : [type, undefinedTypeNode]; + changeTracker.replaceNode(propertyDeclarationSourceFile, type, ts.createUnionTypeNode(types)); + } + function getActionForAddMissingInitializer(context, propertyDeclaration) { + var checker = context.program.getTypeChecker(); + var initializer = getInitializer(checker, propertyDeclaration); + if (!initializer) + return undefined; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addInitializer(t, context.sourceFile, propertyDeclaration, initializer); }); + return codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Add_initializer_to_property_0, propertyDeclaration.name.getText()], fixIdAddInitializer, ts.Diagnostics.Add_initializers_to_all_uninitialized_properties); + } + function addInitializer(changeTracker, propertyDeclarationSourceFile, propertyDeclaration, initializer) { + var property = ts.updateProperty(propertyDeclaration, propertyDeclaration.decorators, propertyDeclaration.modifiers, propertyDeclaration.name, propertyDeclaration.questionToken, propertyDeclaration.type, initializer); + changeTracker.replaceNode(propertyDeclarationSourceFile, propertyDeclaration, property); + } + function getInitializer(checker, propertyDeclaration) { + return getDefaultValueFromType(checker, checker.getTypeFromTypeNode(propertyDeclaration.type)); // TODO: GH#18217 + } + function getDefaultValueFromType(checker, type) { + if (type.flags & 512 /* BooleanLiteral */) { + return (type === checker.getFalseType() || type === checker.getFalseType(/*fresh*/ true)) ? ts.createFalse() : ts.createTrue(); + } + else if (type.isLiteral()) { + return ts.createLiteral(type.value); + } + else if (type.isUnion()) { + return ts.firstDefined(type.types, function (t) { return getDefaultValueFromType(checker, t); }); + } + else if (type.isClass()) { + var classDeclaration = ts.getClassLikeDeclarationOfSymbol(type.symbol); + if (!classDeclaration || ts.hasModifier(classDeclaration, 128 /* Abstract */)) + return undefined; + var constructorDeclaration = ts.getFirstConstructorWithBody(classDeclaration); + if (constructorDeclaration && constructorDeclaration.parameters.length) + return undefined; + return ts.createNew(ts.createIdentifier(type.symbol.name), /*typeArguments*/ undefined, /*argumentsArray*/ undefined); + } + else if (checker.isArrayLikeType(type)) { + return ts.createArrayLiteral(); + } + return undefined; + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + function generateTypesForModule(name, moduleValue, formatSettings) { + return generateTypesForModuleOrGlobal(name, moduleValue, formatSettings, 0 /* ExportEquals */); + } + ts.generateTypesForModule = generateTypesForModule; + function generateTypesForGlobal(name, globalValue, formatSettings) { + return generateTypesForModuleOrGlobal(name, globalValue, formatSettings, 3 /* Global */); + } + ts.generateTypesForGlobal = generateTypesForGlobal; + function generateTypesForModuleOrGlobal(name, globalValue, formatSettings, outputKind) { + return valueInfoToDeclarationFileText(ts.inspectValue(name, globalValue), formatSettings, outputKind); + } + /* @internal */ + function valueInfoToDeclarationFileText(valueInfo, formatSettings, outputKind) { + if (outputKind === void 0) { outputKind = 0 /* ExportEquals */; } + return ts.textChanges.getNewFileText(toStatements(valueInfo, outputKind), 3 /* TS */, formatSettings.newLineCharacter || "\n", ts.formatting.getFormatContext(formatSettings)); + } + ts.valueInfoToDeclarationFileText = valueInfoToDeclarationFileText; + var OutputKind; + (function (OutputKind) { + OutputKind[OutputKind["ExportEquals"] = 0] = "ExportEquals"; + OutputKind[OutputKind["NamedExport"] = 1] = "NamedExport"; + OutputKind[OutputKind["NamespaceMember"] = 2] = "NamespaceMember"; + OutputKind[OutputKind["Global"] = 3] = "Global"; + })(OutputKind || (OutputKind = {})); + function toNamespaceMemberStatements(info) { + return toStatements(info, 2 /* NamespaceMember */); + } + function toStatements(info, kind) { + var isDefault = info.name === "default" /* Default */; + var name = isDefault ? "_default" : info.name; + if (!isValidIdentifier(name) || isDefault && kind !== 1 /* NamedExport */) + return ts.emptyArray; + var modifiers = isDefault && info.kind === 2 /* FunctionOrClass */ ? [ts.createModifier(85 /* ExportKeyword */), ts.createModifier(80 /* DefaultKeyword */)] + : kind === 3 /* Global */ || kind === 0 /* ExportEquals */ ? [ts.createModifier(125 /* DeclareKeyword */)] + : kind === 1 /* NamedExport */ ? [ts.createModifier(85 /* ExportKeyword */)] + : undefined; + var exportEquals = function () { return kind === 0 /* ExportEquals */ ? [exportEqualsOrDefault(info.name, /*isExportEquals*/ true)] : ts.emptyArray; }; + var exportDefault = function () { return isDefault ? [exportEqualsOrDefault("_default", /*isExportEquals*/ false)] : ts.emptyArray; }; + switch (info.kind) { + case 2 /* FunctionOrClass */: + return exportEquals().concat(functionOrClassToStatements(modifiers, name, info)); + case 3 /* Object */: + var members = info.members, hasNontrivialPrototype = info.hasNontrivialPrototype; + if (!hasNontrivialPrototype) { + if (kind === 0 /* ExportEquals */) { + return ts.flatMap(members, function (v) { return toStatements(v, 1 /* NamedExport */); }); + } + if (members.some(function (m) { return m.kind === 2 /* FunctionOrClass */; })) { + // If some member is a function, use a namespace so it gets a FunctionDeclaration or ClassDeclaration. + return exportDefault().concat([createNamespace(modifiers, name, ts.flatMap(members, toNamespaceMemberStatements))]); + } + } + // falls through + case 0 /* Const */: + case 1 /* Array */: { + var comment = info.kind === 0 /* Const */ ? info.comment : undefined; + var constVar = ts.createVariableStatement(modifiers, ts.createVariableDeclarationList([ts.createVariableDeclaration(name, toType(info))], 2 /* Const */)); + return exportEquals().concat(exportDefault(), [addComment(constVar, comment)]); + } + default: + return ts.Debug.assertNever(info); + } + } + function exportEqualsOrDefault(name, isExportEquals) { + return ts.createExportAssignment(/*decorators*/ undefined, /*modifiers*/ undefined, isExportEquals, ts.createIdentifier(name)); + } + function functionOrClassToStatements(modifiers, name, _a) { + var source = _a.source, prototypeMembers = _a.prototypeMembers, namespaceMembers = _a.namespaceMembers; + var fnAst = parseClassOrFunctionBody(source); + var _b = fnAst === undefined ? { parameters: ts.emptyArray, returnType: anyType() } : getParametersAndReturnType(fnAst), parameters = _b.parameters, returnType = _b.returnType; + var protoOrInstanceMembers = ts.createMap(); + if (typeof fnAst === "object") + getConstructorFunctionInstanceProperties(fnAst, protoOrInstanceMembers); + for (var _i = 0, prototypeMembers_1 = prototypeMembers; _i < prototypeMembers_1.length; _i++) { + var p = prototypeMembers_1[_i]; + // ignore non-functions on the prototype + if (p.kind === 2 /* FunctionOrClass */) { + var m = tryGetMethod(p); + if (m) { + protoOrInstanceMembers.set(p.name, m); + } + } + } + var classStaticMembers = protoOrInstanceMembers.size !== 0 || fnAst === undefined || typeof fnAst !== "number" && fnAst.kind === 157 /* Constructor */ ? [] : undefined; + var namespaceStatements = ts.flatMap(namespaceMembers, function (info) { + if (!isValidIdentifier(info.name)) + return undefined; + if (classStaticMembers) { + switch (info.kind) { + case 3 /* Object */: + if (info.members.some(function (m) { return m.kind === 2 /* FunctionOrClass */; })) { + break; + } + // falls through + case 1 /* Array */: + case 0 /* Const */: + classStaticMembers.push(addComment(ts.createProperty(/*decorators*/ undefined, [ts.createModifier(116 /* StaticKeyword */)], info.name, /*questionOrExclamationToken*/ undefined, toType(info), /*initializer*/ undefined), info.kind === 0 /* Const */ ? info.comment : undefined)); + return undefined; + case 2 /* FunctionOrClass */: + if (!info.namespaceMembers.length) { // Else, can't merge a static method with a namespace. Must make it a function on the namespace. + var sig = tryGetMethod(info, [ts.createModifier(116 /* StaticKeyword */)]); + if (sig) { + classStaticMembers.push(sig); + return undefined; + } + } + break; + default: + ts.Debug.assertNever(info); + } + } + return toStatements(info, 2 /* NamespaceMember */); + }); + var decl = classStaticMembers + ? ts.createClassDeclaration( + /*decorators*/ undefined, modifiers, name, + /*typeParameters*/ undefined, + /*heritageClauses*/ undefined, classStaticMembers.concat((parameters.length ? [ts.createConstructor(/*decorators*/ undefined, /*modifiers*/ undefined, parameters, /*body*/ undefined)] : ts.emptyArray), ts.arrayFrom(protoOrInstanceMembers.values()))) + : ts.createFunctionDeclaration(/*decorators*/ undefined, modifiers, /*asteriskToken*/ undefined, name, /*typeParameters*/ undefined, parameters, returnType, /*body*/ undefined); + return [decl].concat((namespaceStatements.length === 0 ? ts.emptyArray : [createNamespace(modifiers && modifiers.map(function (m) { return ts.getSynthesizedDeepClone(m); }), name, namespaceStatements)])); + } + function tryGetMethod(_a, modifiers) { + var name = _a.name, source = _a.source; + if (!isValidIdentifier(name)) + return undefined; + var fnAst = parseClassOrFunctionBody(source); + if (fnAst === undefined || (typeof fnAst !== "number" && fnAst.kind === 157 /* Constructor */)) + return undefined; + var sig = getParametersAndReturnType(fnAst); + return sig && ts.createMethod( + /*decorators*/ undefined, modifiers, + /*asteriskToken*/ undefined, name, + /*questionToken*/ undefined, + /*typeParameters*/ undefined, sig.parameters, sig.returnType, + /*body*/ undefined); + } + function toType(info) { + switch (info.kind) { + case 0 /* Const */: + return ts.createTypeReferenceNode(info.typeName, /*typeArguments*/ undefined); + case 1 /* Array */: + return ts.createArrayTypeNode(toType(info.inner)); + case 2 /* FunctionOrClass */: + return ts.createTypeReferenceNode("Function", /*typeArguments*/ undefined); // Normally we create a FunctionDeclaration, but this can happen for a function in an array. + case 3 /* Object */: + return ts.createTypeLiteralNode(info.members.map(function (m) { return ts.createPropertySignature(/*modifiers*/ undefined, toPropertyName(m.name), /*questionToken*/ undefined, toType(m), /*initializer*/ undefined); })); + default: + return ts.Debug.assertNever(info); + } + } + function toPropertyName(name) { + return ts.isIdentifierText(name, 6 /* ESNext */) ? ts.createIdentifier(name) : ts.createStringLiteral(name); + } + // Parses assignments to "this.x" in the constructor into class property declarations + function getConstructorFunctionInstanceProperties(fnAst, members) { + forEachOwnNodeOfFunction(fnAst, function (node) { + if (ts.isAssignmentExpression(node, /*excludeCompoundAssignment*/ true) && + ts.isPropertyAccessExpression(node.left) && node.left.expression.kind === 100 /* ThisKeyword */) { + var name_4 = node.left.name.text; + if (!ts.isJsPrivate(name_4)) { + ts.getOrUpdate(members, name_4, function () { return ts.createProperty(/*decorators*/ undefined, /*modifiers*/ undefined, name_4, /*questionOrExclamationToken*/ undefined, anyType(), /*initializer*/ undefined); }); + } + } + }); + } + function getParametersAndReturnType(fnAst) { + if (typeof fnAst === "number") { + return { parameters: ts.fill(fnAst, function (i) { return makeParameter("p" + i, anyType()); }), returnType: anyType() }; + } + var usedArguments = false, hasReturn = false; + forEachOwnNodeOfFunction(fnAst, function (node) { + usedArguments = usedArguments || ts.isIdentifier(node) && node.text === "arguments"; + hasReturn = hasReturn || ts.isReturnStatement(node) && !!node.expression && node.expression.kind !== 200 /* VoidExpression */; + }); + var parameters = fnAst.parameters.map(function (p) { return makeParameter("" + p.name.getText(), inferParameterType(fnAst, p)); }).concat((usedArguments ? [makeRestParameter()] : ts.emptyArray)); + return { parameters: parameters, returnType: hasReturn ? anyType() : ts.createKeywordTypeNode(106 /* VoidKeyword */) }; + } + function makeParameter(name, type) { + return ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, name, /*questionToken*/ undefined, type); + } + function makeRestParameter() { + return ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createToken(25 /* DotDotDotToken */), "args", /*questionToken*/ undefined, ts.createArrayTypeNode(anyType())); + } + /** Returns 'undefined' for class with no declared constructor */ + function parseClassOrFunctionBody(source) { + if (typeof source === "number") + return source; + var classOrFunction = ts.tryCast(parseExpression(source), function (node) { return ts.isFunctionExpression(node) || ts.isArrowFunction(node) || ts.isClassExpression(node); }); + return classOrFunction + ? ts.isClassExpression(classOrFunction) ? ts.find(classOrFunction.members, ts.isConstructorDeclaration) : classOrFunction + // If that didn't parse, it's a method `m() {}`. Parse again inside of an object literal. + : ts.cast(ts.first(ts.cast(parseExpression("{ " + source + " }"), ts.isObjectLiteralExpression).properties), ts.isMethodDeclaration); + } + function parseExpression(expr) { + var text = "const _ = " + expr; + var srcFile = ts.createSourceFile("test.ts", text, 6 /* Latest */, /*setParentNodes*/ true); + return ts.first(ts.cast(ts.first(srcFile.statements), ts.isVariableStatement).declarationList.declarations).initializer; + } + function inferParameterType(_fn, _param) { + // TODO: Inspect function body for clues (see inferFromUsage.ts) + return anyType(); + } + // Descends through all nodes in a function, but not in nested functions. + function forEachOwnNodeOfFunction(fnAst, cb) { + fnAst.body.forEachChild(function recur(node) { + cb(node); + if (!ts.isFunctionLike(node)) + node.forEachChild(recur); + }); + } + function isValidIdentifier(name) { + var keyword = ts.stringToToken(name); + return !(keyword && ts.isNonContextualKeyword(keyword)) && ts.isIdentifierText(name, 6 /* ESNext */); + } + function addComment(node, comment) { + if (comment !== undefined) + ts.addSyntheticLeadingComment(node, 2 /* SingleLineCommentTrivia */, comment); + return node; + } + function anyType() { + return ts.createKeywordTypeNode(120 /* AnyKeyword */); + } + function createNamespace(modifiers, name, statements) { + return ts.createModuleDeclaration(/*decorators*/ undefined, modifiers, ts.createIdentifier(name), ts.createModuleBlock(statements), 16 /* Namespace */); + } +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "requireInTs"; + var errorCodes = [ts.Diagnostics.require_call_may_be_converted_to_an_import.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, context.sourceFile, context.span.start, context.program); }); + return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Convert_require_to_import, fixId, ts.Diagnostics.Convert_all_require_to_import)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { return doChange(changes, diag.file, diag.start, context.program); }); }, + }); + function doChange(changes, sourceFile, pos, program) { + var _a = getInfo(sourceFile, pos), statement = _a.statement, name = _a.name, required = _a.required; + changes.replaceNode(sourceFile, statement, ts.getAllowSyntheticDefaultImports(program.getCompilerOptions()) + ? ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createImportClause(name, /*namedBindings*/ undefined), required) + : ts.createImportEqualsDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, name, ts.createExternalModuleReference(required))); + } + function getInfo(sourceFile, pos) { + var parent = ts.getTokenAtPosition(sourceFile, pos).parent; + if (!ts.isRequireCall(parent, /*checkArgumentIsStringLiteralLike*/ true)) + throw ts.Debug.failBadSyntaxKind(parent); + var decl = ts.cast(parent.parent, ts.isVariableDeclaration); + return { statement: ts.cast(decl.parent.parent, ts.isVariableStatement), name: ts.cast(decl.name, ts.isIdentifier), required: parent.arguments[0] }; + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "useDefaultImport"; + var errorCodes = [ts.Diagnostics.Import_may_be_converted_to_a_default_import.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var sourceFile = context.sourceFile, start = context.span.start; + var info = getInfo(sourceFile, start); + if (!info) + return undefined; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, info, context.preferences); }); + return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Convert_to_default_import, fixId, ts.Diagnostics.Convert_all_to_default_imports)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var info = getInfo(diag.file, diag.start); + if (info) + doChange(changes, diag.file, info, context.preferences); + }); }, + }); + function getInfo(sourceFile, pos) { + var name = ts.getTokenAtPosition(sourceFile, pos); + if (!ts.isIdentifier(name)) + return undefined; // bad input + var parent = name.parent; + if (ts.isImportEqualsDeclaration(parent) && ts.isExternalModuleReference(parent.moduleReference)) { + return { importNode: parent, name: name, moduleSpecifier: parent.moduleReference.expression }; + } + else if (ts.isNamespaceImport(parent)) { + var importNode = parent.parent.parent; + return { importNode: importNode, name: name, moduleSpecifier: importNode.moduleSpecifier }; + } + } + function doChange(changes, sourceFile, info, preferences) { + changes.replaceNode(sourceFile, info.importNode, ts.makeImport(info.name, /*namedImports*/ undefined, info.moduleSpecifier, ts.getQuotePreference(sourceFile, preferences))); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixIdAddMissingTypeof = "fixAddModuleReferTypeMissingTypeof"; + var fixId = fixIdAddMissingTypeof; + var errorCodes = [ts.Diagnostics.Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var sourceFile = context.sourceFile, span = context.span; + var importType = getImportTypeNode(sourceFile, span.start); + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, importType); }); + return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Add_missing_typeof, fixId, ts.Diagnostics.Add_missing_typeof)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + return doChange(changes, context.sourceFile, getImportTypeNode(diag.file, diag.start)); + }); }, + }); + function getImportTypeNode(sourceFile, pos) { + var token = ts.getTokenAtPosition(sourceFile, pos); + ts.Debug.assert(token.kind === 92 /* ImportKeyword */); + ts.Debug.assert(token.parent.kind === 183 /* ImportType */); + return token.parent; + } + function doChange(changes, sourceFile, importType) { + var newTypeNode = ts.updateImportTypeNode(importType, importType.argument, importType.qualifier, importType.typeArguments, /* isTypeOf */ true); + changes.replaceNode(sourceFile, importType, newTypeNode); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixIdAddMissingTypeof = "fixConvertToMappedObjectType"; + var fixId = fixIdAddMissingTypeof; + var errorCodes = [ts.Diagnostics.An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var sourceFile = context.sourceFile, span = context.span; + var info = getInfo(sourceFile, span.start); + if (!info) + return undefined; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, info); }); + var name = ts.idText(info.container.name); + return [codefix.createCodeFixAction(fixId, changes, [ts.Diagnostics.Convert_0_to_mapped_object_type, name], fixId, [ts.Diagnostics.Convert_0_to_mapped_object_type, name])]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var info = getInfo(diag.file, diag.start); + if (info) + doChange(changes, diag.file, info); + }); } + }); + function getInfo(sourceFile, pos) { + var token = ts.getTokenAtPosition(sourceFile, pos); + var indexSignature = ts.cast(token.parent.parent, ts.isIndexSignatureDeclaration); + if (ts.isClassDeclaration(indexSignature.parent)) + return undefined; + var container = ts.isInterfaceDeclaration(indexSignature.parent) ? indexSignature.parent : ts.cast(indexSignature.parent.parent, ts.isTypeAliasDeclaration); + return { indexSignature: indexSignature, container: container }; + } + function createTypeAliasFromInterface(declaration, type) { + return ts.createTypeAliasDeclaration(declaration.decorators, declaration.modifiers, declaration.name, declaration.typeParameters, type); + } + function doChange(changes, sourceFile, _a) { + var indexSignature = _a.indexSignature, container = _a.container; + var members = ts.isInterfaceDeclaration(container) ? container.members : container.type.members; + var otherMembers = members.filter(function (member) { return !ts.isIndexSignatureDeclaration(member); }); + var parameter = ts.first(indexSignature.parameters); + var mappedTypeParameter = ts.createTypeParameterDeclaration(ts.cast(parameter.name, ts.isIdentifier), parameter.type); + var mappedIntersectionType = ts.createMappedTypeNode(ts.hasReadonlyModifier(indexSignature) ? ts.createModifier(133 /* ReadonlyKeyword */) : undefined, mappedTypeParameter, indexSignature.questionToken, indexSignature.type); + var intersectionType = ts.createIntersectionTypeNode(ts.getAllSuperTypeNodes(container).concat([ + mappedIntersectionType + ], (otherMembers.length ? [ts.createTypeLiteralNode(otherMembers)] : ts.emptyArray))); + changes.replaceNode(sourceFile, container, createTypeAliasFromInterface(container, intersectionType)); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var refactor; + (function (refactor) { + var refactorName = "Convert export"; + var actionNameDefaultToNamed = "Convert default export to named export"; + var actionNameNamedToDefault = "Convert named export to default export"; + refactor.registerRefactor(refactorName, { + getAvailableActions: function (context) { + var info = getInfo(context); + if (!info) + return ts.emptyArray; + var description = info.wasDefault ? ts.Diagnostics.Convert_default_export_to_named_export.message : ts.Diagnostics.Convert_named_export_to_default_export.message; + var actionName = info.wasDefault ? actionNameDefaultToNamed : actionNameNamedToDefault; + return [{ name: refactorName, description: description, actions: [{ name: actionName, description: description }] }]; + }, + getEditsForAction: function (context, actionName) { + ts.Debug.assert(actionName === actionNameDefaultToNamed || actionName === actionNameNamedToDefault); + var edits = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(context.file, context.program, ts.Debug.assertDefined(getInfo(context)), t, context.cancellationToken); }); + return { edits: edits, renameFilename: undefined, renameLocation: undefined }; + }, + }); + function getInfo(context) { + var file = context.file; + var span = ts.getRefactorContextSpan(context); + var token = ts.getTokenAtPosition(file, span.start); + var exportNode = ts.getParentNodeInSpan(token, file, span); + if (!exportNode || (!ts.isSourceFile(exportNode.parent) && !(ts.isModuleBlock(exportNode.parent) && ts.isAmbientModule(exportNode.parent.parent)))) { + return undefined; + } + var exportingModuleSymbol = ts.isSourceFile(exportNode.parent) ? exportNode.parent.symbol : exportNode.parent.parent.symbol; + var flags = ts.getModifierFlags(exportNode); + var wasDefault = !!(flags & 512 /* Default */); + // If source file already has a default export, don't offer refactor. + if (!(flags & 1 /* Export */) || !wasDefault && exportingModuleSymbol.exports.has("default" /* Default */)) { + return undefined; + } + switch (exportNode.kind) { + case 239 /* FunctionDeclaration */: + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + case 243 /* EnumDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 244 /* ModuleDeclaration */: { + var node = exportNode; + return node.name && ts.isIdentifier(node.name) ? { exportNode: node, exportName: node.name, wasDefault: wasDefault, exportingModuleSymbol: exportingModuleSymbol } : undefined; + } + case 219 /* VariableStatement */: { + var vs = exportNode; + // Must be `export const x = something;`. + if (!(vs.declarationList.flags & 2 /* Const */) || vs.declarationList.declarations.length !== 1) { + return undefined; + } + var decl = ts.first(vs.declarationList.declarations); + if (!decl.initializer) + return undefined; + ts.Debug.assert(!wasDefault); + return ts.isIdentifier(decl.name) ? { exportNode: vs, exportName: decl.name, wasDefault: wasDefault, exportingModuleSymbol: exportingModuleSymbol } : undefined; + } + default: + return undefined; + } + } + function doChange(exportingSourceFile, program, info, changes, cancellationToken) { + changeExport(exportingSourceFile, info, changes, program.getTypeChecker()); + changeImports(program, info, changes, cancellationToken); + } + function changeExport(exportingSourceFile, _a, changes, checker) { + var wasDefault = _a.wasDefault, exportNode = _a.exportNode, exportName = _a.exportName; + if (wasDefault) { + changes.delete(exportingSourceFile, ts.Debug.assertDefined(ts.findModifier(exportNode, 80 /* DefaultKeyword */))); + } + else { + var exportKeyword = ts.Debug.assertDefined(ts.findModifier(exportNode, 85 /* ExportKeyword */)); + switch (exportNode.kind) { + case 239 /* FunctionDeclaration */: + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + changes.insertNodeAfter(exportingSourceFile, exportKeyword, ts.createToken(80 /* DefaultKeyword */)); + break; + case 219 /* VariableStatement */: + // If 'x' isn't used in this file, `export const x = 0;` --> `export default 0;` + if (!ts.FindAllReferences.Core.isSymbolReferencedInFile(exportName, checker, exportingSourceFile)) { + // We checked in `getInfo` that an initializer exists. + changes.replaceNode(exportingSourceFile, exportNode, ts.createExportDefault(ts.Debug.assertDefined(ts.first(exportNode.declarationList.declarations).initializer))); + break; + } + // falls through + case 243 /* EnumDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 244 /* ModuleDeclaration */: + // `export type T = number;` -> `type T = number; export default T;` + changes.deleteModifier(exportingSourceFile, exportKeyword); + changes.insertNodeAfter(exportingSourceFile, exportNode, ts.createExportDefault(ts.createIdentifier(exportName.text))); + break; + default: + ts.Debug.assertNever(exportNode); + } + } + } + function changeImports(program, _a, changes, cancellationToken) { + var wasDefault = _a.wasDefault, exportName = _a.exportName, exportingModuleSymbol = _a.exportingModuleSymbol; + var checker = program.getTypeChecker(); + var exportSymbol = ts.Debug.assertDefined(checker.getSymbolAtLocation(exportName)); + ts.FindAllReferences.Core.eachExportReference(program.getSourceFiles(), checker, cancellationToken, exportSymbol, exportingModuleSymbol, exportName.text, wasDefault, function (ref) { + var importingSourceFile = ref.getSourceFile(); + if (wasDefault) { + changeDefaultToNamedImport(importingSourceFile, ref, changes, exportName.text); + } + else { + changeNamedToDefaultImport(importingSourceFile, ref, changes); + } + }); + } + function changeDefaultToNamedImport(importingSourceFile, ref, changes, exportName) { + var parent = ref.parent; + switch (parent.kind) { + case 189 /* PropertyAccessExpression */: + // `a.default` --> `a.foo` + changes.replaceNode(importingSourceFile, ref, ts.createIdentifier(exportName)); + break; + case 253 /* ImportSpecifier */: + case 257 /* ExportSpecifier */: { + var spec = parent; + // `default as foo` --> `foo`, `default as bar` --> `foo as bar` + changes.replaceNode(importingSourceFile, spec, makeImportSpecifier(exportName, spec.name.text)); + break; + } + case 250 /* ImportClause */: { + var clause = parent; + ts.Debug.assert(clause.name === ref); + var spec = makeImportSpecifier(exportName, ref.text); + var namedBindings = clause.namedBindings; + if (!namedBindings) { + // `import foo from "./a";` --> `import { foo } from "./a";` + changes.replaceNode(importingSourceFile, ref, ts.createNamedImports([spec])); + } + else if (namedBindings.kind === 251 /* NamespaceImport */) { + // `import foo, * as a from "./a";` --> `import * as a from ".a/"; import { foo } from "./a";` + changes.deleteRange(importingSourceFile, { pos: ref.getStart(importingSourceFile), end: namedBindings.getStart(importingSourceFile) }); + var quotePreference = ts.isStringLiteral(clause.parent.moduleSpecifier) ? ts.quotePreferenceFromString(clause.parent.moduleSpecifier, importingSourceFile) : 1 /* Double */; + var newImport = ts.makeImport(/*default*/ undefined, [makeImportSpecifier(exportName, ref.text)], clause.parent.moduleSpecifier, quotePreference); + changes.insertNodeAfter(importingSourceFile, clause.parent, newImport); + } + else { + // `import foo, { bar } from "./a"` --> `import { bar, foo } from "./a";` + changes.delete(importingSourceFile, ref); + changes.insertNodeAtEndOfList(importingSourceFile, namedBindings.elements, spec); + } + break; + } + default: + ts.Debug.failBadSyntaxKind(parent); + } + } + function changeNamedToDefaultImport(importingSourceFile, ref, changes) { + var parent = ref.parent; + switch (parent.kind) { + case 189 /* PropertyAccessExpression */: + // `a.foo` --> `a.default` + changes.replaceNode(importingSourceFile, ref, ts.createIdentifier("default")); + break; + case 253 /* ImportSpecifier */: { + // `import { foo } from "./a";` --> `import foo from "./a";` + // `import { foo as bar } from "./a";` --> `import bar from "./a";` + var defaultImport = ts.createIdentifier(parent.name.text); + if (parent.parent.elements.length === 1) { + changes.replaceNode(importingSourceFile, parent.parent, defaultImport); + } + else { + changes.delete(importingSourceFile, parent); + changes.insertNodeBefore(importingSourceFile, parent.parent, defaultImport); + } + break; + } + case 257 /* ExportSpecifier */: { + // `export { foo } from "./a";` --> `export { default as foo } from "./a";` + // `export { foo as bar } from "./a";` --> `export { default as bar } from "./a";` + // `export { foo as default } from "./a";` --> `export { default } from "./a";` + // (Because `export foo from "./a";` isn't valid syntax.) + changes.replaceNode(importingSourceFile, parent, makeExportSpecifier("default", parent.name.text)); + break; + } + default: + ts.Debug.assertNever(parent); + } + } + function makeImportSpecifier(propertyName, name) { + return ts.createImportSpecifier(propertyName === name ? undefined : ts.createIdentifier(propertyName), ts.createIdentifier(name)); + } + function makeExportSpecifier(propertyName, name) { + return ts.createExportSpecifier(propertyName === name ? undefined : ts.createIdentifier(propertyName), ts.createIdentifier(name)); + } + })(refactor = ts.refactor || (ts.refactor = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var refactor; + (function (refactor) { + var refactorName = "Convert import"; + var actionNameNamespaceToNamed = "Convert namespace import to named imports"; + var actionNameNamedToNamespace = "Convert named imports to namespace import"; + refactor.registerRefactor(refactorName, { + getAvailableActions: function (context) { + var i = getImportToConvert(context); + if (!i) + return ts.emptyArray; + var description = i.kind === 251 /* NamespaceImport */ ? ts.Diagnostics.Convert_namespace_import_to_named_imports.message : ts.Diagnostics.Convert_named_imports_to_namespace_import.message; + var actionName = i.kind === 251 /* NamespaceImport */ ? actionNameNamespaceToNamed : actionNameNamedToNamespace; + return [{ name: refactorName, description: description, actions: [{ name: actionName, description: description }] }]; + }, + getEditsForAction: function (context, actionName) { + ts.Debug.assert(actionName === actionNameNamespaceToNamed || actionName === actionNameNamedToNamespace); + var edits = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(context.file, context.program, t, ts.Debug.assertDefined(getImportToConvert(context))); }); + return { edits: edits, renameFilename: undefined, renameLocation: undefined }; + } + }); + // Can convert imports of the form `import * as m from "m";` or `import d, { x, y } from "m";`. + function getImportToConvert(context) { + var file = context.file; + var span = ts.getRefactorContextSpan(context); + var token = ts.getTokenAtPosition(file, span.start); + var importDecl = ts.getParentNodeInSpan(token, file, span); + if (!importDecl || !ts.isImportDeclaration(importDecl)) + return undefined; + var importClause = importDecl.importClause; + return importClause && importClause.namedBindings; + } + function doChange(sourceFile, program, changes, toConvert) { + var checker = program.getTypeChecker(); + if (toConvert.kind === 251 /* NamespaceImport */) { + doChangeNamespaceToNamed(sourceFile, checker, changes, toConvert, ts.getAllowSyntheticDefaultImports(program.getCompilerOptions())); + } + else { + doChangeNamedToNamespace(sourceFile, checker, changes, toConvert); + } + } + function doChangeNamespaceToNamed(sourceFile, checker, changes, toConvert, allowSyntheticDefaultImports) { + var usedAsNamespaceOrDefault = false; + var nodesToReplace = []; + var conflictingNames = ts.createMap(); + ts.FindAllReferences.Core.eachSymbolReferenceInFile(toConvert.name, checker, sourceFile, function (id) { + if (!ts.isPropertyAccessExpression(id.parent)) { + usedAsNamespaceOrDefault = true; + } + else { + var parent = ts.cast(id.parent, ts.isPropertyAccessExpression); + var exportName = parent.name.text; + if (checker.resolveName(exportName, id, 67108863 /* All */, /*excludeGlobals*/ true)) { + conflictingNames.set(exportName, true); + } + ts.Debug.assert(parent.expression === id); + nodesToReplace.push(parent); + } + }); + // We may need to change `mod.x` to `_x` to avoid a name conflict. + var exportNameToImportName = ts.createMap(); + for (var _i = 0, nodesToReplace_1 = nodesToReplace; _i < nodesToReplace_1.length; _i++) { + var propertyAccess = nodesToReplace_1[_i]; + var exportName = propertyAccess.name.text; + var importName = exportNameToImportName.get(exportName); + if (importName === undefined) { + exportNameToImportName.set(exportName, importName = conflictingNames.has(exportName) ? ts.getUniqueName(exportName, sourceFile) : exportName); + } + changes.replaceNode(sourceFile, propertyAccess, ts.createIdentifier(importName)); + } + var importSpecifiers = []; + exportNameToImportName.forEach(function (name, propertyName) { + importSpecifiers.push(ts.createImportSpecifier(name === propertyName ? undefined : ts.createIdentifier(propertyName), ts.createIdentifier(name))); + }); + var importDecl = toConvert.parent.parent; + if (usedAsNamespaceOrDefault && !allowSyntheticDefaultImports) { + // Need to leave the namespace import alone + changes.insertNodeAfter(sourceFile, importDecl, updateImport(importDecl, /*defaultImportName*/ undefined, importSpecifiers)); + } + else { + changes.replaceNode(sourceFile, importDecl, updateImport(importDecl, usedAsNamespaceOrDefault ? ts.createIdentifier(toConvert.name.text) : undefined, importSpecifiers)); + } + } + function doChangeNamedToNamespace(sourceFile, checker, changes, toConvert) { + var importDecl = toConvert.parent.parent; + var moduleSpecifier = importDecl.moduleSpecifier; + var preferredName = moduleSpecifier && ts.isStringLiteral(moduleSpecifier) ? ts.codefix.moduleSpecifierToValidIdentifier(moduleSpecifier.text, 6 /* ESNext */) : "module"; + var namespaceNameConflicts = toConvert.elements.some(function (element) { + return ts.FindAllReferences.Core.eachSymbolReferenceInFile(element.name, checker, sourceFile, function (id) { + return !!checker.resolveName(preferredName, id, 67108863 /* All */, /*excludeGlobals*/ true); + }) || false; + }); + var namespaceImportName = namespaceNameConflicts ? ts.getUniqueName(preferredName, sourceFile) : preferredName; + var neededNamedImports = []; + var _loop_12 = function (element) { + var propertyName = (element.propertyName || element.name).text; + ts.FindAllReferences.Core.eachSymbolReferenceInFile(element.name, checker, sourceFile, function (id) { + var access = ts.createPropertyAccess(ts.createIdentifier(namespaceImportName), propertyName); + if (ts.isShorthandPropertyAssignment(id.parent)) { + changes.replaceNode(sourceFile, id.parent, ts.createPropertyAssignment(id.text, access)); + } + else if (ts.isExportSpecifier(id.parent) && !id.parent.propertyName) { + if (!neededNamedImports.some(function (n) { return n.name === element.name; })) { + neededNamedImports.push(ts.createImportSpecifier(element.propertyName && ts.createIdentifier(element.propertyName.text), ts.createIdentifier(element.name.text))); + } + } + else { + changes.replaceNode(sourceFile, id, access); + } + }); + }; + for (var _i = 0, _a = toConvert.elements; _i < _a.length; _i++) { + var element = _a[_i]; + _loop_12(element); + } + changes.replaceNode(sourceFile, toConvert, ts.createNamespaceImport(ts.createIdentifier(namespaceImportName))); + if (neededNamedImports.length) { + changes.insertNodeAfter(sourceFile, toConvert.parent.parent, updateImport(importDecl, /*defaultImportName*/ undefined, neededNamedImports)); + } + } + function updateImport(old, defaultImportName, elements) { + return ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createImportClause(defaultImportName, elements && elements.length ? ts.createNamedImports(elements) : undefined), old.moduleSpecifier); + } + })(refactor = ts.refactor || (ts.refactor = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var refactor; + (function (refactor) { + var extractSymbol; + (function (extractSymbol) { + var refactorName = "Extract Symbol"; + refactor.registerRefactor(refactorName, { getAvailableActions: getAvailableActions, getEditsForAction: getEditsForAction }); + /** + * Compute the associated code actions + * Exported for tests. + */ + function getAvailableActions(context) { + var rangeToExtract = getRangeToExtract(context.file, ts.getRefactorContextSpan(context)); + var targetRange = rangeToExtract.targetRange; + if (targetRange === undefined) { + return ts.emptyArray; + } + var extractions = getPossibleExtractions(targetRange, context); + if (extractions === undefined) { + // No extractions possible + return ts.emptyArray; + } + var functionActions = []; + var usedFunctionNames = ts.createMap(); + var constantActions = []; + var usedConstantNames = ts.createMap(); + var i = 0; + for (var _i = 0, extractions_1 = extractions; _i < extractions_1.length; _i++) { + var _a = extractions_1[_i], functionExtraction = _a.functionExtraction, constantExtraction = _a.constantExtraction; + // Skip these since we don't have a way to report errors yet + if (functionExtraction.errors.length === 0) { + // Don't issue refactorings with duplicated names. + // Scopes come back in "innermost first" order, so extractions will + // preferentially go into nearer scopes + var description = functionExtraction.description; + if (!usedFunctionNames.has(description)) { + usedFunctionNames.set(description, true); + functionActions.push({ + description: description, + name: "function_scope_" + i + }); + } + } + // Skip these since we don't have a way to report errors yet + if (constantExtraction.errors.length === 0) { + // Don't issue refactorings with duplicated names. + // Scopes come back in "innermost first" order, so extractions will + // preferentially go into nearer scopes + var description = constantExtraction.description; + if (!usedConstantNames.has(description)) { + usedConstantNames.set(description, true); + constantActions.push({ + description: description, + name: "constant_scope_" + i + }); + } + } + // *do* increment i anyway because we'll look for the i-th scope + // later when actually doing the refactoring if the user requests it + i++; + } + var infos = []; + if (functionActions.length) { + infos.push({ + name: refactorName, + description: ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_function), + actions: functionActions + }); + } + if (constantActions.length) { + infos.push({ + name: refactorName, + description: ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_constant), + actions: constantActions + }); + } + return infos.length ? infos : ts.emptyArray; + } + extractSymbol.getAvailableActions = getAvailableActions; + /* Exported for tests */ + function getEditsForAction(context, actionName) { + var rangeToExtract = getRangeToExtract(context.file, ts.getRefactorContextSpan(context)); + var targetRange = rangeToExtract.targetRange; // TODO:GH#18217 + var parsedFunctionIndexMatch = /^function_scope_(\d+)$/.exec(actionName); + if (parsedFunctionIndexMatch) { + var index = +parsedFunctionIndexMatch[1]; + ts.Debug.assert(isFinite(index), "Expected to parse a finite number from the function scope index"); + return getFunctionExtractionAtIndex(targetRange, context, index); + } + var parsedConstantIndexMatch = /^constant_scope_(\d+)$/.exec(actionName); + if (parsedConstantIndexMatch) { + var index = +parsedConstantIndexMatch[1]; + ts.Debug.assert(isFinite(index), "Expected to parse a finite number from the constant scope index"); + return getConstantExtractionAtIndex(targetRange, context, index); + } + ts.Debug.fail("Unrecognized action name"); + } + extractSymbol.getEditsForAction = getEditsForAction; + // Move these into diagnostic messages if they become user-facing + var Messages; + (function (Messages) { + function createMessage(message) { + return { message: message, code: 0, category: ts.DiagnosticCategory.Message, key: message }; + } + Messages.cannotExtractRange = createMessage("Cannot extract range."); + Messages.cannotExtractImport = createMessage("Cannot extract import statement."); + Messages.cannotExtractSuper = createMessage("Cannot extract super call."); + Messages.cannotExtractEmpty = createMessage("Cannot extract empty range."); + Messages.expressionExpected = createMessage("expression expected."); + Messages.uselessConstantType = createMessage("No reason to extract constant of type."); + Messages.statementOrExpressionExpected = createMessage("Statement or expression expected."); + Messages.cannotExtractRangeContainingConditionalBreakOrContinueStatements = createMessage("Cannot extract range containing conditional break or continue statements."); + Messages.cannotExtractRangeContainingConditionalReturnStatement = createMessage("Cannot extract range containing conditional return statement."); + Messages.cannotExtractRangeContainingLabeledBreakOrContinueStatementWithTargetOutsideOfTheRange = createMessage("Cannot extract range containing labeled break or continue with target outside of the range."); + Messages.cannotExtractRangeThatContainsWritesToReferencesLocatedOutsideOfTheTargetRangeInGenerators = createMessage("Cannot extract range containing writes to references located outside of the target range in generators."); + Messages.typeWillNotBeVisibleInTheNewScope = createMessage("Type will not visible in the new scope."); + Messages.functionWillNotBeVisibleInTheNewScope = createMessage("Function will not visible in the new scope."); + Messages.cannotExtractIdentifier = createMessage("Select more than a single identifier."); + Messages.cannotExtractExportedEntity = createMessage("Cannot extract exported declaration"); + Messages.cannotWriteInExpression = createMessage("Cannot write back side-effects when extracting an expression"); + Messages.cannotExtractReadonlyPropertyInitializerOutsideConstructor = createMessage("Cannot move initialization of read-only class property outside of the constructor"); + Messages.cannotExtractAmbientBlock = createMessage("Cannot extract code from ambient contexts"); + Messages.cannotAccessVariablesFromNestedScopes = createMessage("Cannot access variables from nested scopes"); + Messages.cannotExtractToOtherFunctionLike = createMessage("Cannot extract method to a function-like scope that is not a function"); + Messages.cannotExtractToJSClass = createMessage("Cannot extract constant to a class scope in JS"); + Messages.cannotExtractToExpressionArrowFunction = createMessage("Cannot extract constant to an arrow function without a block"); + })(Messages = extractSymbol.Messages || (extractSymbol.Messages = {})); + var RangeFacts; + (function (RangeFacts) { + RangeFacts[RangeFacts["None"] = 0] = "None"; + RangeFacts[RangeFacts["HasReturn"] = 1] = "HasReturn"; + RangeFacts[RangeFacts["IsGenerator"] = 2] = "IsGenerator"; + RangeFacts[RangeFacts["IsAsyncFunction"] = 4] = "IsAsyncFunction"; + RangeFacts[RangeFacts["UsesThis"] = 8] = "UsesThis"; + /** + * The range is in a function which needs the 'static' modifier in a class + */ + RangeFacts[RangeFacts["InStaticRegion"] = 16] = "InStaticRegion"; + })(RangeFacts || (RangeFacts = {})); + /** + * getRangeToExtract takes a span inside a text file and returns either an expression or an array + * of statements representing the minimum set of nodes needed to extract the entire span. This + * process may fail, in which case a set of errors is returned instead (these are currently + * not shown to the user, but can be used by us diagnostically) + */ + // exported only for tests + function getRangeToExtract(sourceFile, span) { + var length = span.length; + if (length === 0) { + return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractEmpty)] }; + } + // Walk up starting from the the start position until we find a non-SourceFile node that subsumes the selected span. + // This may fail (e.g. you select two statements in the root of a source file) + var start = ts.getParentNodeInSpan(ts.getTokenAtPosition(sourceFile, span.start), sourceFile, span); + // Do the same for the ending position + var end = ts.getParentNodeInSpan(ts.findTokenOnLeftOfPosition(sourceFile, ts.textSpanEnd(span)), sourceFile, span); + var declarations = []; + // We'll modify these flags as we walk the tree to collect data + // about what things need to be done as part of the extraction. + var rangeFacts = RangeFacts.None; + if (!start || !end) { + // cannot find either start or end node + return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractRange)] }; + } + if (start.parent !== end.parent) { + // start and end nodes belong to different subtrees + return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractRange)] }; + } + if (start !== end) { + // start and end should be statements and parent should be either block or a source file + if (!isBlockLike(start.parent)) { + return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractRange)] }; + } + var statements = []; + var start2 = start; // TODO: GH#18217 Need to alias `start` to get this to compile. See https://github.com/Microsoft/TypeScript/issues/19955#issuecomment-344118248 + for (var _i = 0, _a = start2.parent.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + if (statement === start || statements.length) { + var errors_1 = checkNode(statement); + if (errors_1) { + return { errors: errors_1 }; + } + statements.push(statement); + } + if (statement === end) { + break; + } + } + if (!statements.length) { + // https://github.com/Microsoft/TypeScript/issues/20559 + // Ranges like [|case 1: break;|] will fail to populate `statements` because + // they will never find `start` in `start.parent.statements`. + // Consider: We could support ranges like [|case 1:|] by refining them to just + // the expression. + return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractRange)] }; + } + return { targetRange: { range: statements, facts: rangeFacts, declarations: declarations } }; + } + if (ts.isReturnStatement(start) && !start.expression) { + // Makes no sense to extract an expression-less return statement. + return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractRange)] }; + } + // We have a single node (start) + var node = refineNode(start); + var errors = checkRootNode(node) || checkNode(node); + if (errors) { + return { errors: errors }; + } + return { targetRange: { range: getStatementOrExpressionRange(node), facts: rangeFacts, declarations: declarations } }; // TODO: GH#18217 + /** + * Attempt to refine the extraction node (generally, by shrinking it) to produce better results. + * @param node The unrefined extraction node. + */ + function refineNode(node) { + if (ts.isReturnStatement(node)) { + if (node.expression) { + return node.expression; + } + } + else if (ts.isVariableStatement(node)) { + var numInitializers = 0; + var lastInitializer = void 0; + for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (declaration.initializer) { + numInitializers++; + lastInitializer = declaration.initializer; + } + } + if (numInitializers === 1) { + return lastInitializer; + } + // No special handling if there are multiple initializers. + } + else if (ts.isVariableDeclaration(node)) { + if (node.initializer) { + return node.initializer; + } + } + return node; + } + function checkRootNode(node) { + if (ts.isIdentifier(ts.isExpressionStatement(node) ? node.expression : node)) { + return [ts.createDiagnosticForNode(node, Messages.cannotExtractIdentifier)]; + } + return undefined; + } + function checkForStaticContext(nodeToCheck, containingClass) { + var current = nodeToCheck; + while (current !== containingClass) { + if (current.kind === 154 /* PropertyDeclaration */) { + if (ts.hasModifier(current, 32 /* Static */)) { + rangeFacts |= RangeFacts.InStaticRegion; + } + break; + } + else if (current.kind === 151 /* Parameter */) { + var ctorOrMethod = ts.getContainingFunction(current); + if (ctorOrMethod.kind === 157 /* Constructor */) { + rangeFacts |= RangeFacts.InStaticRegion; + } + break; + } + else if (current.kind === 156 /* MethodDeclaration */) { + if (ts.hasModifier(current, 32 /* Static */)) { + rangeFacts |= RangeFacts.InStaticRegion; + } + } + current = current.parent; + } + } + // Verifies whether we can actually extract this node or not. + function checkNode(nodeToCheck) { + var PermittedJumps; + (function (PermittedJumps) { + PermittedJumps[PermittedJumps["None"] = 0] = "None"; + PermittedJumps[PermittedJumps["Break"] = 1] = "Break"; + PermittedJumps[PermittedJumps["Continue"] = 2] = "Continue"; + PermittedJumps[PermittedJumps["Return"] = 4] = "Return"; + })(PermittedJumps || (PermittedJumps = {})); + // We believe it's true because the node is from the (unmodified) tree. + ts.Debug.assert(nodeToCheck.pos <= nodeToCheck.end, "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809"); + // For understanding how skipTrivia functioned: + ts.Debug.assert(!ts.positionIsSynthesized(nodeToCheck.pos), "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809"); + if (!ts.isStatement(nodeToCheck) && !(ts.isExpressionNode(nodeToCheck) && isExtractableExpression(nodeToCheck))) { + return [ts.createDiagnosticForNode(nodeToCheck, Messages.statementOrExpressionExpected)]; + } + if (nodeToCheck.flags & 4194304 /* Ambient */) { + return [ts.createDiagnosticForNode(nodeToCheck, Messages.cannotExtractAmbientBlock)]; + } + // If we're in a class, see whether we're in a static region (static property initializer, static method, class constructor parameter default) + var containingClass = ts.getContainingClass(nodeToCheck); + if (containingClass) { + checkForStaticContext(nodeToCheck, containingClass); + } + var errors; + var permittedJumps = 4 /* Return */; + var seenLabels; + visit(nodeToCheck); + return errors; + function visit(node) { + if (errors) { + // already found an error - can stop now + return true; + } + if (ts.isDeclaration(node)) { + var declaringNode = (node.kind === 237 /* VariableDeclaration */) ? node.parent.parent : node; + if (ts.hasModifier(declaringNode, 1 /* Export */)) { + // TODO: GH#18217 Silly to use `errors ||` since it's definitely not defined (see top of `visit`) + // Also, if we're only pushing one error, just use `let error: Diagnostic | undefined`! + // Also TODO: GH#19956 + (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractExportedEntity)); + return true; + } + declarations.push(node.symbol); + } + // Some things can't be extracted in certain situations + switch (node.kind) { + case 249 /* ImportDeclaration */: + (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractImport)); + return true; + case 98 /* SuperKeyword */: + // For a super *constructor call*, we have to be extracting the entire class, + // but a super *method call* simply implies a 'this' reference + if (node.parent.kind === 191 /* CallExpression */) { + // Super constructor call + var containingClass_1 = ts.getContainingClass(node); // TODO:GH#18217 + if (containingClass_1.pos < span.start || containingClass_1.end >= (span.start + span.length)) { + (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractSuper)); + return true; + } + } + else { + rangeFacts |= RangeFacts.UsesThis; + } + break; + } + if (ts.isFunctionLikeDeclaration(node) || ts.isClassLike(node)) { + switch (node.kind) { + case 239 /* FunctionDeclaration */: + case 240 /* ClassDeclaration */: + if (ts.isSourceFile(node.parent) && node.parent.externalModuleIndicator === undefined) { + // You cannot extract global declarations + (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.functionWillNotBeVisibleInTheNewScope)); + } + break; + } + // do not dive into functions or classes + return false; + } + var savedPermittedJumps = permittedJumps; + switch (node.kind) { + case 222 /* IfStatement */: + permittedJumps = 0 /* None */; + break; + case 235 /* TryStatement */: + // forbid all jumps inside try blocks + permittedJumps = 0 /* None */; + break; + case 218 /* Block */: + if (node.parent && node.parent.kind === 235 /* TryStatement */ && node.parent.finallyBlock === node) { + // allow unconditional returns from finally blocks + permittedJumps = 4 /* Return */; + } + break; + case 271 /* CaseClause */: + // allow unlabeled break inside case clauses + permittedJumps |= 1 /* Break */; + break; + default: + if (ts.isIterationStatement(node, /*lookInLabeledStatements*/ false)) { + // allow unlabeled break/continue inside loops + permittedJumps |= 1 /* Break */ | 2 /* Continue */; + } + break; + } + switch (node.kind) { + case 178 /* ThisType */: + case 100 /* ThisKeyword */: + rangeFacts |= RangeFacts.UsesThis; + break; + case 233 /* LabeledStatement */: + { + var label = node.label; + (seenLabels || (seenLabels = [])).push(label.escapedText); + ts.forEachChild(node, visit); + seenLabels.pop(); + break; + } + case 229 /* BreakStatement */: + case 228 /* ContinueStatement */: + { + var label = node.label; + if (label) { + if (!ts.contains(seenLabels, label.escapedText)) { + // attempts to jump to label that is not in range to be extracted + (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractRangeContainingLabeledBreakOrContinueStatementWithTargetOutsideOfTheRange)); + } + } + else { + if (!(permittedJumps & (node.kind === 229 /* BreakStatement */ ? 1 /* Break */ : 2 /* Continue */))) { + // attempt to break or continue in a forbidden context + (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractRangeContainingConditionalBreakOrContinueStatements)); + } + } + break; + } + case 201 /* AwaitExpression */: + rangeFacts |= RangeFacts.IsAsyncFunction; + break; + case 207 /* YieldExpression */: + rangeFacts |= RangeFacts.IsGenerator; + break; + case 230 /* ReturnStatement */: + if (permittedJumps & 4 /* Return */) { + rangeFacts |= RangeFacts.HasReturn; + } + else { + (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractRangeContainingConditionalReturnStatement)); + } + break; + default: + ts.forEachChild(node, visit); + break; + } + permittedJumps = savedPermittedJumps; + } + } + } + extractSymbol.getRangeToExtract = getRangeToExtract; + function getStatementOrExpressionRange(node) { + if (ts.isStatement(node)) { + return [node]; + } + else if (ts.isExpressionNode(node)) { + // If our selection is the expression in an ExpressionStatement, expand + // the selection to include the enclosing Statement (this stops us + // from trying to care about the return value of the extracted function + // and eliminates double semicolon insertion in certain scenarios) + return ts.isExpressionStatement(node.parent) ? [node.parent] : node; + } + return undefined; + } + function isScope(node) { + return ts.isFunctionLikeDeclaration(node) || ts.isSourceFile(node) || ts.isModuleBlock(node) || ts.isClassLike(node); + } + /** + * Computes possible places we could extract the function into. For example, + * you may be able to extract into a class method *or* local closure *or* namespace function, + * depending on what's in the extracted body. + */ + function collectEnclosingScopes(range) { + var current = isReadonlyArray(range.range) ? ts.first(range.range) : range.range; + if (range.facts & RangeFacts.UsesThis) { + // if range uses this as keyword or as type inside the class then it can only be extracted to a method of the containing class + var containingClass = ts.getContainingClass(current); + if (containingClass) { + var containingFunction = ts.findAncestor(current, ts.isFunctionLikeDeclaration); + return containingFunction + ? [containingFunction, containingClass] + : [containingClass]; + } + } + var scopes = []; + while (true) { + current = current.parent; + // A function parameter's initializer is actually in the outer scope, not the function declaration + if (current.kind === 151 /* Parameter */) { + // Skip all the way to the outer scope of the function that declared this parameter + current = ts.findAncestor(current, function (parent) { return ts.isFunctionLikeDeclaration(parent); }).parent; + } + // We want to find the nearest parent where we can place an "equivalent" sibling to the node we're extracting out of. + // Walk up to the closest parent of a place where we can logically put a sibling: + // * Function declaration + // * Class declaration or expression + // * Module/namespace or source file + if (isScope(current)) { + scopes.push(current); + if (current.kind === 279 /* SourceFile */) { + return scopes; + } + } + } + } + function getFunctionExtractionAtIndex(targetRange, context, requestedChangesIndex) { + var _a = getPossibleExtractionsWorker(targetRange, context), scopes = _a.scopes, _b = _a.readsAndWrites, target = _b.target, usagesPerScope = _b.usagesPerScope, functionErrorsPerScope = _b.functionErrorsPerScope, exposedVariableDeclarations = _b.exposedVariableDeclarations; + ts.Debug.assert(!functionErrorsPerScope[requestedChangesIndex].length, "The extraction went missing? How?"); + context.cancellationToken.throwIfCancellationRequested(); // TODO: GH#18217 + return extractFunctionInScope(target, scopes[requestedChangesIndex], usagesPerScope[requestedChangesIndex], exposedVariableDeclarations, targetRange, context); + } + function getConstantExtractionAtIndex(targetRange, context, requestedChangesIndex) { + var _a = getPossibleExtractionsWorker(targetRange, context), scopes = _a.scopes, _b = _a.readsAndWrites, target = _b.target, usagesPerScope = _b.usagesPerScope, constantErrorsPerScope = _b.constantErrorsPerScope, exposedVariableDeclarations = _b.exposedVariableDeclarations; + ts.Debug.assert(!constantErrorsPerScope[requestedChangesIndex].length, "The extraction went missing? How?"); + ts.Debug.assert(exposedVariableDeclarations.length === 0, "Extract constant accepted a range containing a variable declaration?"); + context.cancellationToken.throwIfCancellationRequested(); + var expression = ts.isExpression(target) + ? target + : target.statements[0].expression; + return extractConstantInScope(expression, scopes[requestedChangesIndex], usagesPerScope[requestedChangesIndex], targetRange.facts, context); + } + /** + * Given a piece of text to extract ('targetRange'), computes a list of possible extractions. + * Each returned ExtractResultForScope corresponds to a possible target scope and is either a set of changes + * or an error explaining why we can't extract into that scope. + */ + function getPossibleExtractions(targetRange, context) { + var _a = getPossibleExtractionsWorker(targetRange, context), scopes = _a.scopes, _b = _a.readsAndWrites, functionErrorsPerScope = _b.functionErrorsPerScope, constantErrorsPerScope = _b.constantErrorsPerScope; + // Need the inner type annotation to avoid https://github.com/Microsoft/TypeScript/issues/7547 + var extractions = scopes.map(function (scope, i) { + var functionDescriptionPart = getDescriptionForFunctionInScope(scope); + var constantDescriptionPart = getDescriptionForConstantInScope(scope); + var scopeDescription = ts.isFunctionLikeDeclaration(scope) + ? getDescriptionForFunctionLikeDeclaration(scope) + : ts.isClassLike(scope) + ? getDescriptionForClassLikeDeclaration(scope) + : getDescriptionForModuleLikeDeclaration(scope); + var functionDescription; + var constantDescription; + if (scopeDescription === 1 /* Global */) { + functionDescription = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_to_0_in_1_scope), [functionDescriptionPart, "global"]); + constantDescription = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_to_0_in_1_scope), [constantDescriptionPart, "global"]); + } + else if (scopeDescription === 0 /* Module */) { + functionDescription = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_to_0_in_1_scope), [functionDescriptionPart, "module"]); + constantDescription = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_to_0_in_1_scope), [constantDescriptionPart, "module"]); + } + else { + functionDescription = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_to_0_in_1), [functionDescriptionPart, scopeDescription]); + constantDescription = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_to_0_in_1), [constantDescriptionPart, scopeDescription]); + } + // Customize the phrasing for the innermost scope to increase clarity. + if (i === 0 && !ts.isClassLike(scope)) { + constantDescription = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_to_0_in_enclosing_scope), [constantDescriptionPart]); + } + return { + functionExtraction: { + description: functionDescription, + errors: functionErrorsPerScope[i], + }, + constantExtraction: { + description: constantDescription, + errors: constantErrorsPerScope[i], + }, + }; + }); + return extractions; + } + function getPossibleExtractionsWorker(targetRange, context) { + var sourceFile = context.file; + var scopes = collectEnclosingScopes(targetRange); + var enclosingTextRange = getEnclosingTextRange(targetRange, sourceFile); + var readsAndWrites = collectReadsAndWrites(targetRange, scopes, enclosingTextRange, sourceFile, context.program.getTypeChecker(), context.cancellationToken); + return { scopes: scopes, readsAndWrites: readsAndWrites }; + } + function getDescriptionForFunctionInScope(scope) { + return ts.isFunctionLikeDeclaration(scope) + ? "inner function" + : ts.isClassLike(scope) + ? "method" + : "function"; + } + function getDescriptionForConstantInScope(scope) { + return ts.isClassLike(scope) + ? "readonly field" + : "constant"; + } + function getDescriptionForFunctionLikeDeclaration(scope) { + switch (scope.kind) { + case 157 /* Constructor */: + return "constructor"; + case 196 /* FunctionExpression */: + case 239 /* FunctionDeclaration */: + return scope.name + ? "function '" + scope.name.text + "'" + : "anonymous function"; + case 197 /* ArrowFunction */: + return "arrow function"; + case 156 /* MethodDeclaration */: + return "method '" + scope.name.getText() + "'"; + case 158 /* GetAccessor */: + return "'get " + scope.name.getText() + "'"; + case 159 /* SetAccessor */: + return "'set " + scope.name.getText() + "'"; + default: + throw ts.Debug.assertNever(scope); + } + } + function getDescriptionForClassLikeDeclaration(scope) { + return scope.kind === 240 /* ClassDeclaration */ + ? scope.name ? "class '" + scope.name.text + "'" : "anonymous class declaration" + : scope.name ? "class expression '" + scope.name.text + "'" : "anonymous class expression"; + } + function getDescriptionForModuleLikeDeclaration(scope) { + return scope.kind === 245 /* ModuleBlock */ + ? "namespace '" + scope.parent.name.getText() + "'" + : scope.externalModuleIndicator ? 0 /* Module */ : 1 /* Global */; + } + var SpecialScope; + (function (SpecialScope) { + SpecialScope[SpecialScope["Module"] = 0] = "Module"; + SpecialScope[SpecialScope["Global"] = 1] = "Global"; + })(SpecialScope || (SpecialScope = {})); + /** + * Result of 'extractRange' operation for a specific scope. + * Stores either a list of changes that should be applied to extract a range or a list of errors + */ + function extractFunctionInScope(node, scope, _a, exposedVariableDeclarations, range, context) { + var usagesInScope = _a.usages, typeParameterUsages = _a.typeParameterUsages, substitutions = _a.substitutions; + var checker = context.program.getTypeChecker(); + // Make a unique name for the extracted function + var file = scope.getSourceFile(); + var functionNameText = ts.getUniqueName(ts.isClassLike(scope) ? "newMethod" : "newFunction", file); + var isJS = ts.isInJSFile(scope); + var functionName = ts.createIdentifier(functionNameText); + var returnType; + var parameters = []; + var callArguments = []; + var writes; + usagesInScope.forEach(function (usage, name) { + var typeNode; + if (!isJS) { + var type = checker.getTypeOfSymbolAtLocation(usage.symbol, usage.node); + // Widen the type so we don't emit nonsense annotations like "function fn(x: 3) {" + type = checker.getBaseTypeOfLiteralType(type); + typeNode = checker.typeToTypeNode(type, scope, 1 /* NoTruncation */); + } + var paramDecl = ts.createParameter( + /*decorators*/ undefined, + /*modifiers*/ undefined, + /*dotDotDotToken*/ undefined, + /*name*/ name, + /*questionToken*/ undefined, typeNode); + parameters.push(paramDecl); + if (usage.usage === 2 /* Write */) { + (writes || (writes = [])).push(usage); + } + callArguments.push(ts.createIdentifier(name)); + }); + var typeParametersAndDeclarations = ts.arrayFrom(typeParameterUsages.values()).map(function (type) { return ({ type: type, declaration: getFirstDeclaration(type) }); }); + var sortedTypeParametersAndDeclarations = typeParametersAndDeclarations.sort(compareTypesByDeclarationOrder); + var typeParameters = sortedTypeParametersAndDeclarations.length === 0 + ? undefined + : sortedTypeParametersAndDeclarations.map(function (t) { return t.declaration; }); + // Strictly speaking, we should check whether each name actually binds to the appropriate type + // parameter. In cases of shadowing, they may not. + var callTypeArguments = typeParameters !== undefined + ? typeParameters.map(function (decl) { return ts.createTypeReferenceNode(decl.name, /*typeArguments*/ undefined); }) + : undefined; + // Provide explicit return types for contextually-typed functions + // to avoid problems when there are literal types present + if (ts.isExpression(node) && !isJS) { + var contextualType = checker.getContextualType(node); + returnType = checker.typeToTypeNode(contextualType, scope, 1 /* NoTruncation */); // TODO: GH#18217 + } + var _b = transformFunctionBody(node, exposedVariableDeclarations, writes, substitutions, !!(range.facts & RangeFacts.HasReturn)), body = _b.body, returnValueProperty = _b.returnValueProperty; + ts.suppressLeadingAndTrailingTrivia(body); + var newFunction; + if (ts.isClassLike(scope)) { + // always create private method in TypeScript files + var modifiers = isJS ? [] : [ts.createToken(113 /* PrivateKeyword */)]; + if (range.facts & RangeFacts.InStaticRegion) { + modifiers.push(ts.createToken(116 /* StaticKeyword */)); + } + if (range.facts & RangeFacts.IsAsyncFunction) { + modifiers.push(ts.createToken(121 /* AsyncKeyword */)); + } + newFunction = ts.createMethod( + /*decorators*/ undefined, modifiers.length ? modifiers : undefined, range.facts & RangeFacts.IsGenerator ? ts.createToken(40 /* AsteriskToken */) : undefined, functionName, + /*questionToken*/ undefined, typeParameters, parameters, returnType, body); + } + else { + newFunction = ts.createFunctionDeclaration( + /*decorators*/ undefined, range.facts & RangeFacts.IsAsyncFunction ? [ts.createToken(121 /* AsyncKeyword */)] : undefined, range.facts & RangeFacts.IsGenerator ? ts.createToken(40 /* AsteriskToken */) : undefined, functionName, typeParameters, parameters, returnType, body); + } + var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); + var minInsertionPos = (isReadonlyArray(range.range) ? ts.last(range.range) : range.range).end; + var nodeToInsertBefore = getNodeToInsertFunctionBefore(minInsertionPos, scope); + if (nodeToInsertBefore) { + changeTracker.insertNodeBefore(context.file, nodeToInsertBefore, newFunction, /*blankLineBetween*/ true); + } + else { + changeTracker.insertNodeAtEndOfScope(context.file, scope, newFunction); + } + var newNodes = []; + // replace range with function call + var called = getCalledExpression(scope, range, functionNameText); + var call = ts.createCall(called, callTypeArguments, // Note that no attempt is made to take advantage of type argument inference + callArguments); + if (range.facts & RangeFacts.IsGenerator) { + call = ts.createYield(ts.createToken(40 /* AsteriskToken */), call); + } + if (range.facts & RangeFacts.IsAsyncFunction) { + call = ts.createAwait(call); + } + if (exposedVariableDeclarations.length && !writes) { + // No need to mix declarations and writes. + // How could any variables be exposed if there's a return statement? + ts.Debug.assert(!returnValueProperty); + ts.Debug.assert(!(range.facts & RangeFacts.HasReturn)); + if (exposedVariableDeclarations.length === 1) { + // Declaring exactly one variable: let x = newFunction(); + var variableDeclaration = exposedVariableDeclarations[0]; + newNodes.push(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(ts.getSynthesizedDeepClone(variableDeclaration.name), /*type*/ ts.getSynthesizedDeepClone(variableDeclaration.type), /*initializer*/ call)], // TODO (acasey): test binding patterns + variableDeclaration.parent.flags))); + } + else { + // Declaring multiple variables / return properties: + // let {x, y} = newFunction(); + var bindingElements = []; + var typeElements = []; + var commonNodeFlags = exposedVariableDeclarations[0].parent.flags; + var sawExplicitType = false; + for (var _i = 0, exposedVariableDeclarations_1 = exposedVariableDeclarations; _i < exposedVariableDeclarations_1.length; _i++) { + var variableDeclaration = exposedVariableDeclarations_1[_i]; + bindingElements.push(ts.createBindingElement( + /*dotDotDotToken*/ undefined, + /*propertyName*/ undefined, + /*name*/ ts.getSynthesizedDeepClone(variableDeclaration.name))); + // Being returned through an object literal will have widened the type. + var variableType = checker.typeToTypeNode(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(variableDeclaration)), scope, 1 /* NoTruncation */); + typeElements.push(ts.createPropertySignature( + /*modifiers*/ undefined, + /*name*/ variableDeclaration.symbol.name, + /*questionToken*/ undefined, + /*type*/ variableType, + /*initializer*/ undefined)); + sawExplicitType = sawExplicitType || variableDeclaration.type !== undefined; + commonNodeFlags = commonNodeFlags & variableDeclaration.parent.flags; + } + var typeLiteral = sawExplicitType ? ts.createTypeLiteralNode(typeElements) : undefined; + if (typeLiteral) { + ts.setEmitFlags(typeLiteral, 1 /* SingleLine */); + } + newNodes.push(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(ts.createObjectBindingPattern(bindingElements), + /*type*/ typeLiteral, + /*initializer*/ call)], commonNodeFlags))); + } + } + else if (exposedVariableDeclarations.length || writes) { + if (exposedVariableDeclarations.length) { + // CONSIDER: we're going to create one statement per variable, but we could actually preserve their original grouping. + for (var _c = 0, exposedVariableDeclarations_2 = exposedVariableDeclarations; _c < exposedVariableDeclarations_2.length; _c++) { + var variableDeclaration = exposedVariableDeclarations_2[_c]; + var flags = variableDeclaration.parent.flags; + if (flags & 2 /* Const */) { + flags = (flags & ~2 /* Const */) | 1 /* Let */; + } + newNodes.push(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(variableDeclaration.symbol.name, getTypeDeepCloneUnionUndefined(variableDeclaration.type))], flags))); + } + } + if (returnValueProperty) { + // has both writes and return, need to create variable declaration to hold return value; + newNodes.push(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(returnValueProperty, getTypeDeepCloneUnionUndefined(returnType))], 1 /* Let */))); + } + var assignments = getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes); + if (returnValueProperty) { + assignments.unshift(ts.createShorthandPropertyAssignment(returnValueProperty)); + } + // propagate writes back + if (assignments.length === 1) { + // We would only have introduced a return value property if there had been + // other assignments to make. + ts.Debug.assert(!returnValueProperty); + newNodes.push(ts.createStatement(ts.createAssignment(assignments[0].name, call))); + if (range.facts & RangeFacts.HasReturn) { + newNodes.push(ts.createReturn()); + } + } + else { + // emit e.g. + // { a, b, __return } = newFunction(a, b); + // return __return; + newNodes.push(ts.createStatement(ts.createAssignment(ts.createObjectLiteral(assignments), call))); + if (returnValueProperty) { + newNodes.push(ts.createReturn(ts.createIdentifier(returnValueProperty))); + } + } + } + else { + if (range.facts & RangeFacts.HasReturn) { + newNodes.push(ts.createReturn(call)); + } + else if (isReadonlyArray(range.range)) { + newNodes.push(ts.createStatement(call)); + } + else { + newNodes.push(call); + } + } + if (isReadonlyArray(range.range)) { + changeTracker.replaceNodeRangeWithNodes(context.file, ts.first(range.range), ts.last(range.range), newNodes); + } + else { + changeTracker.replaceNodeWithNodes(context.file, range.range, newNodes); + } + var edits = changeTracker.getChanges(); + var renameRange = isReadonlyArray(range.range) ? ts.first(range.range) : range.range; + var renameFilename = renameRange.getSourceFile().fileName; + var renameLocation = ts.getRenameLocation(edits, renameFilename, functionNameText, /*isDeclaredBeforeUse*/ false); + return { renameFilename: renameFilename, renameLocation: renameLocation, edits: edits }; + function getTypeDeepCloneUnionUndefined(typeNode) { + if (typeNode === undefined) { + return undefined; + } + var clone = ts.getSynthesizedDeepClone(typeNode); + var withoutParens = clone; + while (ts.isParenthesizedTypeNode(withoutParens)) { + withoutParens = withoutParens.type; + } + return ts.isUnionTypeNode(withoutParens) && ts.find(withoutParens.types, function (t) { return t.kind === 141 /* UndefinedKeyword */; }) + ? clone + : ts.createUnionTypeNode([clone, ts.createKeywordTypeNode(141 /* UndefinedKeyword */)]); + } + } + /** + * Result of 'extractRange' operation for a specific scope. + * Stores either a list of changes that should be applied to extract a range or a list of errors + */ + function extractConstantInScope(node, scope, _a, rangeFacts, context) { + var substitutions = _a.substitutions; + var checker = context.program.getTypeChecker(); + // Make a unique name for the extracted variable + var file = scope.getSourceFile(); + var localNameText = ts.getUniqueName(ts.isClassLike(scope) ? "newProperty" : "newLocal", file); + var isJS = ts.isInJSFile(scope); + var variableType = isJS || !checker.isContextSensitive(node) + ? undefined + : checker.typeToTypeNode(checker.getContextualType(node), scope, 1 /* NoTruncation */); // TODO: GH#18217 + var initializer = transformConstantInitializer(node, substitutions); + ts.suppressLeadingAndTrailingTrivia(initializer); + var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); + if (ts.isClassLike(scope)) { + ts.Debug.assert(!isJS); // See CannotExtractToJSClass + var modifiers = []; + modifiers.push(ts.createToken(113 /* PrivateKeyword */)); + if (rangeFacts & RangeFacts.InStaticRegion) { + modifiers.push(ts.createToken(116 /* StaticKeyword */)); + } + modifiers.push(ts.createToken(133 /* ReadonlyKeyword */)); + var newVariable = ts.createProperty( + /*decorators*/ undefined, modifiers, localNameText, + /*questionToken*/ undefined, variableType, initializer); + var localReference = ts.createPropertyAccess(rangeFacts & RangeFacts.InStaticRegion + ? ts.createIdentifier(scope.name.getText()) // TODO: GH#18217 + : ts.createThis(), ts.createIdentifier(localNameText)); + // Declare + var maxInsertionPos = node.pos; + var nodeToInsertBefore = getNodeToInsertPropertyBefore(maxInsertionPos, scope); + changeTracker.insertNodeBefore(context.file, nodeToInsertBefore, newVariable, /*blankLineBetween*/ true); + // Consume + changeTracker.replaceNode(context.file, node, localReference); + } + else { + var newVariableDeclaration = ts.createVariableDeclaration(localNameText, variableType, initializer); + // If the node is part of an initializer in a list of variable declarations, insert a new + // variable declaration into the list (in case it depends on earlier ones). + // CONSIDER: If the declaration list isn't const, we might want to split it into multiple + // lists so that the newly extracted one can be const. + var oldVariableDeclaration = getContainingVariableDeclarationIfInList(node, scope); + if (oldVariableDeclaration) { + // Declare + // CONSIDER: could detect that each is on a separate line (See `extractConstant_VariableList_MultipleLines` in `extractConstants.ts`) + changeTracker.insertNodeBefore(context.file, oldVariableDeclaration, newVariableDeclaration); + // Consume + var localReference = ts.createIdentifier(localNameText); + changeTracker.replaceNode(context.file, node, localReference); + } + else if (node.parent.kind === 221 /* ExpressionStatement */ && scope === ts.findAncestor(node, isScope)) { + // If the parent is an expression statement and the target scope is the immediately enclosing one, + // replace the statement with the declaration. + var newVariableStatement = ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([newVariableDeclaration], 2 /* Const */)); + changeTracker.replaceNode(context.file, node.parent, newVariableStatement); + } + else { + var newVariableStatement = ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([newVariableDeclaration], 2 /* Const */)); + // Declare + var nodeToInsertBefore = getNodeToInsertConstantBefore(node, scope); + if (nodeToInsertBefore.pos === 0) { + changeTracker.insertNodeAtTopOfFile(context.file, newVariableStatement, /*blankLineBetween*/ false); + } + else { + changeTracker.insertNodeBefore(context.file, nodeToInsertBefore, newVariableStatement, /*blankLineBetween*/ false); + } + // Consume + if (node.parent.kind === 221 /* ExpressionStatement */) { + // If the parent is an expression statement, delete it. + changeTracker.delete(context.file, node.parent); + } + else { + var localReference = ts.createIdentifier(localNameText); + changeTracker.replaceNode(context.file, node, localReference); + } + } + } + var edits = changeTracker.getChanges(); + var renameFilename = node.getSourceFile().fileName; + var renameLocation = ts.getRenameLocation(edits, renameFilename, localNameText, /*isDeclaredBeforeUse*/ true); + return { renameFilename: renameFilename, renameLocation: renameLocation, edits: edits }; + } + function getContainingVariableDeclarationIfInList(node, scope) { + var prevNode; + while (node !== undefined && node !== scope) { + if (ts.isVariableDeclaration(node) && + node.initializer === prevNode && + ts.isVariableDeclarationList(node.parent) && + node.parent.declarations.length > 1) { + return node; + } + prevNode = node; + node = node.parent; + } + } + function getFirstDeclaration(type) { + var firstDeclaration; + var symbol = type.symbol; + if (symbol && symbol.declarations) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (firstDeclaration === undefined || declaration.pos < firstDeclaration.pos) { + firstDeclaration = declaration; + } + } + } + return firstDeclaration; + } + function compareTypesByDeclarationOrder(_a, _b) { + var type1 = _a.type, declaration1 = _a.declaration; + var type2 = _b.type, declaration2 = _b.declaration; + return ts.compareProperties(declaration1, declaration2, "pos", ts.compareValues) + || ts.compareStringsCaseSensitive(type1.symbol ? type1.symbol.getName() : "", type2.symbol ? type2.symbol.getName() : "") + || ts.compareValues(type1.id, type2.id); + } + function getCalledExpression(scope, range, functionNameText) { + var functionReference = ts.createIdentifier(functionNameText); + if (ts.isClassLike(scope)) { + var lhs = range.facts & RangeFacts.InStaticRegion ? ts.createIdentifier(scope.name.text) : ts.createThis(); // TODO: GH#18217 + return ts.createPropertyAccess(lhs, functionReference); + } + else { + return functionReference; + } + } + function transformFunctionBody(body, exposedVariableDeclarations, writes, substitutions, hasReturn) { + var hasWritesOrVariableDeclarations = writes !== undefined || exposedVariableDeclarations.length > 0; + if (ts.isBlock(body) && !hasWritesOrVariableDeclarations && substitutions.size === 0) { + // already block, no declarations or writes to propagate back, no substitutions - can use node as is + return { body: ts.createBlock(body.statements, /*multLine*/ true), returnValueProperty: undefined }; + } + var returnValueProperty; + var ignoreReturns = false; + var statements = ts.createNodeArray(ts.isBlock(body) ? body.statements.slice(0) : [ts.isStatement(body) ? body : ts.createReturn(body)]); + // rewrite body if either there are writes that should be propagated back via return statements or there are substitutions + if (hasWritesOrVariableDeclarations || substitutions.size) { + var rewrittenStatements = ts.visitNodes(statements, visitor).slice(); + if (hasWritesOrVariableDeclarations && !hasReturn && ts.isStatement(body)) { + // add return at the end to propagate writes back in case if control flow falls out of the function body + // it is ok to know that range has at least one return since it we only allow unconditional returns + var assignments = getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes); + if (assignments.length === 1) { + rewrittenStatements.push(ts.createReturn(assignments[0].name)); + } + else { + rewrittenStatements.push(ts.createReturn(ts.createObjectLiteral(assignments))); + } + } + return { body: ts.createBlock(rewrittenStatements, /*multiLine*/ true), returnValueProperty: returnValueProperty }; + } + else { + return { body: ts.createBlock(statements, /*multiLine*/ true), returnValueProperty: undefined }; + } + function visitor(node) { + if (!ignoreReturns && node.kind === 230 /* ReturnStatement */ && hasWritesOrVariableDeclarations) { + var assignments = getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes); + if (node.expression) { + if (!returnValueProperty) { + returnValueProperty = "__return"; + } + assignments.unshift(ts.createPropertyAssignment(returnValueProperty, ts.visitNode(node.expression, visitor))); + } + if (assignments.length === 1) { + return ts.createReturn(assignments[0].name); + } + else { + return ts.createReturn(ts.createObjectLiteral(assignments)); + } + } + else { + var oldIgnoreReturns = ignoreReturns; + ignoreReturns = ignoreReturns || ts.isFunctionLikeDeclaration(node) || ts.isClassLike(node); + var substitution = substitutions.get(ts.getNodeId(node).toString()); + var result = substitution ? ts.getSynthesizedDeepClone(substitution) : ts.visitEachChild(node, visitor, ts.nullTransformationContext); + ignoreReturns = oldIgnoreReturns; + return result; + } + } + } + function transformConstantInitializer(initializer, substitutions) { + return substitutions.size + ? visitor(initializer) + : initializer; + function visitor(node) { + var substitution = substitutions.get(ts.getNodeId(node).toString()); + return substitution ? ts.getSynthesizedDeepClone(substitution) : ts.visitEachChild(node, visitor, ts.nullTransformationContext); + } + } + function getStatementsOrClassElements(scope) { + if (ts.isFunctionLikeDeclaration(scope)) { + var body = scope.body; // TODO: GH#18217 + if (ts.isBlock(body)) { + return body.statements; + } + } + else if (ts.isModuleBlock(scope) || ts.isSourceFile(scope)) { + return scope.statements; + } + else if (ts.isClassLike(scope)) { + return scope.members; + } + else { + ts.assertType(scope); + } + return ts.emptyArray; + } + /** + * If `scope` contains a function after `minPos`, then return the first such function. + * Otherwise, return `undefined`. + */ + function getNodeToInsertFunctionBefore(minPos, scope) { + return ts.find(getStatementsOrClassElements(scope), function (child) { + return child.pos >= minPos && ts.isFunctionLikeDeclaration(child) && !ts.isConstructorDeclaration(child); + }); + } + function getNodeToInsertPropertyBefore(maxPos, scope) { + var members = scope.members; + ts.Debug.assert(members.length > 0); // There must be at least one child, since we extracted from one. + var prevMember; + var allProperties = true; + for (var _i = 0, members_2 = members; _i < members_2.length; _i++) { + var member = members_2[_i]; + if (member.pos > maxPos) { + return prevMember || members[0]; + } + if (allProperties && !ts.isPropertyDeclaration(member)) { + // If it is non-vacuously true that all preceding members are properties, + // insert before the current member (i.e. at the end of the list of properties). + if (prevMember !== undefined) { + return member; + } + allProperties = false; + } + prevMember = member; + } + if (prevMember === undefined) + return ts.Debug.fail(); // If the loop didn't return, then it did set prevMember. + return prevMember; + } + function getNodeToInsertConstantBefore(node, scope) { + ts.Debug.assert(!ts.isClassLike(scope)); + var prevScope; + for (var curr = node; curr !== scope; curr = curr.parent) { + if (isScope(curr)) { + prevScope = curr; + } + } + for (var curr = (prevScope || node).parent;; curr = curr.parent) { + if (isBlockLike(curr)) { + var prevStatement = void 0; + for (var _i = 0, _a = curr.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + if (statement.pos > node.pos) { + break; + } + prevStatement = statement; + } + if (!prevStatement && ts.isCaseClause(curr)) { + // We must have been in the expression of the case clause. + ts.Debug.assert(ts.isSwitchStatement(curr.parent.parent)); + return curr.parent.parent; + } + // There must be at least one statement since we started in one. + return ts.Debug.assertDefined(prevStatement); + } + ts.Debug.assert(curr !== scope, "Didn't encounter a block-like before encountering scope"); + } + } + function getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes) { + var variableAssignments = ts.map(exposedVariableDeclarations, function (v) { return ts.createShorthandPropertyAssignment(v.symbol.name); }); + var writeAssignments = ts.map(writes, function (w) { return ts.createShorthandPropertyAssignment(w.symbol.name); }); + // TODO: GH#18217 `variableAssignments` not possibly undefined! + return variableAssignments === undefined + ? writeAssignments + : writeAssignments === undefined + ? variableAssignments + : variableAssignments.concat(writeAssignments); + } + function isReadonlyArray(v) { + return ts.isArray(v); + } + /** + * Produces a range that spans the entirety of nodes, given a selection + * that might start/end in the middle of nodes. + * + * For example, when the user makes a selection like this + * v---v + * var someThing = foo + bar; + * this returns ^-------^ + */ + function getEnclosingTextRange(targetRange, sourceFile) { + return isReadonlyArray(targetRange.range) + ? { pos: ts.first(targetRange.range).getStart(sourceFile), end: ts.last(targetRange.range).getEnd() } + : targetRange.range; + } + var Usage; + (function (Usage) { + // value should be passed to extracted method + Usage[Usage["Read"] = 1] = "Read"; + // value should be passed to extracted method and propagated back + Usage[Usage["Write"] = 2] = "Write"; + })(Usage || (Usage = {})); + function collectReadsAndWrites(targetRange, scopes, enclosingTextRange, sourceFile, checker, cancellationToken) { + var allTypeParameterUsages = ts.createMap(); // Key is type ID + var usagesPerScope = []; + var substitutionsPerScope = []; + var functionErrorsPerScope = []; + var constantErrorsPerScope = []; + var visibleDeclarationsInExtractedRange = []; + var exposedVariableSymbolSet = ts.createMap(); // Key is symbol ID + var exposedVariableDeclarations = []; + var firstExposedNonVariableDeclaration; + var expression = !isReadonlyArray(targetRange.range) + ? targetRange.range + : targetRange.range.length === 1 && ts.isExpressionStatement(targetRange.range[0]) + ? targetRange.range[0].expression + : undefined; + var expressionDiagnostic; + if (expression === undefined) { + var statements = targetRange.range; + var start = ts.first(statements).getStart(); + var end = ts.last(statements).end; + expressionDiagnostic = ts.createFileDiagnostic(sourceFile, start, end - start, Messages.expressionExpected); + } + else if (checker.getTypeAtLocation(expression).flags & (16384 /* Void */ | 131072 /* Never */)) { + expressionDiagnostic = ts.createDiagnosticForNode(expression, Messages.uselessConstantType); + } + // initialize results + for (var _i = 0, scopes_1 = scopes; _i < scopes_1.length; _i++) { + var scope = scopes_1[_i]; + usagesPerScope.push({ usages: ts.createMap(), typeParameterUsages: ts.createMap(), substitutions: ts.createMap() }); + substitutionsPerScope.push(ts.createMap()); + functionErrorsPerScope.push(ts.isFunctionLikeDeclaration(scope) && scope.kind !== 239 /* FunctionDeclaration */ + ? [ts.createDiagnosticForNode(scope, Messages.cannotExtractToOtherFunctionLike)] + : []); + var constantErrors = []; + if (expressionDiagnostic) { + constantErrors.push(expressionDiagnostic); + } + if (ts.isClassLike(scope) && ts.isInJSFile(scope)) { + constantErrors.push(ts.createDiagnosticForNode(scope, Messages.cannotExtractToJSClass)); + } + if (ts.isArrowFunction(scope) && !ts.isBlock(scope.body)) { + // TODO (https://github.com/Microsoft/TypeScript/issues/18924): allow this + constantErrors.push(ts.createDiagnosticForNode(scope, Messages.cannotExtractToExpressionArrowFunction)); + } + constantErrorsPerScope.push(constantErrors); + } + var seenUsages = ts.createMap(); + var target = isReadonlyArray(targetRange.range) ? ts.createBlock(targetRange.range) : targetRange.range; + var unmodifiedNode = isReadonlyArray(targetRange.range) ? ts.first(targetRange.range) : targetRange.range; + var inGenericContext = isInGenericContext(unmodifiedNode); + collectUsages(target); + // Unfortunately, this code takes advantage of the knowledge that the generated method + // will use the contextual type of an expression as the return type of the extracted + // method (and will therefore "use" all the types involved). + if (inGenericContext && !isReadonlyArray(targetRange.range)) { + var contextualType = checker.getContextualType(targetRange.range); // TODO: GH#18217 + recordTypeParameterUsages(contextualType); + } + if (allTypeParameterUsages.size > 0) { + var seenTypeParameterUsages = ts.createMap(); // Key is type ID + var i_1 = 0; + for (var curr = unmodifiedNode; curr !== undefined && i_1 < scopes.length; curr = curr.parent) { + if (curr === scopes[i_1]) { + // Copy current contents of seenTypeParameterUsages into scope. + seenTypeParameterUsages.forEach(function (typeParameter, id) { + usagesPerScope[i_1].typeParameterUsages.set(id, typeParameter); + }); + i_1++; + } + // Note that we add the current node's type parameters *after* updating the corresponding scope. + if (ts.isDeclarationWithTypeParameters(curr)) { + for (var _a = 0, _b = ts.getEffectiveTypeParameterDeclarations(curr); _a < _b.length; _a++) { + var typeParameterDecl = _b[_a]; + var typeParameter = checker.getTypeAtLocation(typeParameterDecl); + if (allTypeParameterUsages.has(typeParameter.id.toString())) { + seenTypeParameterUsages.set(typeParameter.id.toString(), typeParameter); + } + } + } + } + // If we didn't get through all the scopes, then there were some that weren't in our + // parent chain (impossible at time of writing). A conservative solution would be to + // copy allTypeParameterUsages into all remaining scopes. + ts.Debug.assert(i_1 === scopes.length); + } + // If there are any declarations in the extracted block that are used in the same enclosing + // lexical scope, we can't move the extraction "up" as those declarations will become unreachable + if (visibleDeclarationsInExtractedRange.length) { + var containingLexicalScopeOfExtraction = ts.isBlockScope(scopes[0], scopes[0].parent) + ? scopes[0] + : ts.getEnclosingBlockScopeContainer(scopes[0]); + ts.forEachChild(containingLexicalScopeOfExtraction, checkForUsedDeclarations); + } + var _loop_13 = function (i) { + var scopeUsages = usagesPerScope[i]; + // Special case: in the innermost scope, all usages are available. + // (The computed value reflects the value at the top-level of the scope, but the + // local will actually be declared at the same level as the extracted expression). + if (i > 0 && (scopeUsages.usages.size > 0 || scopeUsages.typeParameterUsages.size > 0)) { + var errorNode = isReadonlyArray(targetRange.range) ? targetRange.range[0] : targetRange.range; + constantErrorsPerScope[i].push(ts.createDiagnosticForNode(errorNode, Messages.cannotAccessVariablesFromNestedScopes)); + } + var hasWrite = false; + var readonlyClassPropertyWrite; + usagesPerScope[i].usages.forEach(function (value) { + if (value.usage === 2 /* Write */) { + hasWrite = true; + if (value.symbol.flags & 106500 /* ClassMember */ && + value.symbol.valueDeclaration && + ts.hasModifier(value.symbol.valueDeclaration, 64 /* Readonly */)) { + readonlyClassPropertyWrite = value.symbol.valueDeclaration; + } + } + }); + // If an expression was extracted, then there shouldn't have been any variable declarations. + ts.Debug.assert(isReadonlyArray(targetRange.range) || exposedVariableDeclarations.length === 0); + if (hasWrite && !isReadonlyArray(targetRange.range)) { + var diag = ts.createDiagnosticForNode(targetRange.range, Messages.cannotWriteInExpression); + functionErrorsPerScope[i].push(diag); + constantErrorsPerScope[i].push(diag); + } + else if (readonlyClassPropertyWrite && i > 0) { + var diag = ts.createDiagnosticForNode(readonlyClassPropertyWrite, Messages.cannotExtractReadonlyPropertyInitializerOutsideConstructor); + functionErrorsPerScope[i].push(diag); + constantErrorsPerScope[i].push(diag); + } + else if (firstExposedNonVariableDeclaration) { + var diag = ts.createDiagnosticForNode(firstExposedNonVariableDeclaration, Messages.cannotExtractExportedEntity); + functionErrorsPerScope[i].push(diag); + constantErrorsPerScope[i].push(diag); + } + }; + for (var i = 0; i < scopes.length; i++) { + _loop_13(i); + } + return { target: target, usagesPerScope: usagesPerScope, functionErrorsPerScope: functionErrorsPerScope, constantErrorsPerScope: constantErrorsPerScope, exposedVariableDeclarations: exposedVariableDeclarations }; + function isInGenericContext(node) { + return !!ts.findAncestor(node, function (n) { return ts.isDeclarationWithTypeParameters(n) && ts.getEffectiveTypeParameterDeclarations(n).length !== 0; }); + } + function recordTypeParameterUsages(type) { + // PERF: This is potentially very expensive. `type` could be a library type with + // a lot of properties, each of which the walker will visit. Unfortunately, the + // solution isn't as trivial as filtering to user types because of (e.g.) Array. + var symbolWalker = checker.getSymbolWalker(function () { return (cancellationToken.throwIfCancellationRequested(), true); }); + var visitedTypes = symbolWalker.walkType(type).visitedTypes; + for (var _i = 0, visitedTypes_1 = visitedTypes; _i < visitedTypes_1.length; _i++) { + var visitedType = visitedTypes_1[_i]; + if (visitedType.isTypeParameter()) { + allTypeParameterUsages.set(visitedType.id.toString(), visitedType); + } + } + } + function collectUsages(node, valueUsage) { + if (valueUsage === void 0) { valueUsage = 1 /* Read */; } + if (inGenericContext) { + var type = checker.getTypeAtLocation(node); + recordTypeParameterUsages(type); + } + if (ts.isDeclaration(node) && node.symbol) { + visibleDeclarationsInExtractedRange.push(node); + } + if (ts.isAssignmentExpression(node)) { + // use 'write' as default usage for values + collectUsages(node.left, 2 /* Write */); + collectUsages(node.right); + } + else if (ts.isUnaryExpressionWithWrite(node)) { + collectUsages(node.operand, 2 /* Write */); + } + else if (ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node)) { + // use 'write' as default usage for values + ts.forEachChild(node, collectUsages); + } + else if (ts.isIdentifier(node)) { + if (!node.parent) { + return; + } + if (ts.isQualifiedName(node.parent) && node !== node.parent.left) { + return; + } + if (ts.isPropertyAccessExpression(node.parent) && node !== node.parent.expression) { + return; + } + recordUsage(node, valueUsage, /*isTypeNode*/ ts.isPartOfTypeNode(node)); + } + else { + ts.forEachChild(node, collectUsages); + } + } + function recordUsage(n, usage, isTypeNode) { + var symbolId = recordUsagebySymbol(n, usage, isTypeNode); + if (symbolId) { + for (var i = 0; i < scopes.length; i++) { + // push substitution from map to map to simplify rewriting + var substitution = substitutionsPerScope[i].get(symbolId); + if (substitution) { + usagesPerScope[i].substitutions.set(ts.getNodeId(n).toString(), substitution); + } + } + } + } + function recordUsagebySymbol(identifier, usage, isTypeName) { + var symbol = getSymbolReferencedByIdentifier(identifier); + if (!symbol) { + // cannot find symbol - do nothing + return undefined; + } + var symbolId = ts.getSymbolId(symbol).toString(); + var lastUsage = seenUsages.get(symbolId); + // there are two kinds of value usages + // - reads - if range contains a read from the value located outside of the range then value should be passed as a parameter + // - writes - if range contains a write to a value located outside the range the value should be passed as a parameter and + // returned as a return value + // 'write' case is a superset of 'read' so if we already have processed 'write' of some symbol there is not need to handle 'read' + // since all information is already recorded + if (lastUsage && lastUsage >= usage) { + return symbolId; + } + seenUsages.set(symbolId, usage); + if (lastUsage) { + // if we get here this means that we are trying to handle 'write' and 'read' was already processed + // walk scopes and update existing records. + for (var _i = 0, usagesPerScope_1 = usagesPerScope; _i < usagesPerScope_1.length; _i++) { + var perScope = usagesPerScope_1[_i]; + var prevEntry = perScope.usages.get(identifier.text); + if (prevEntry) { + perScope.usages.set(identifier.text, { usage: usage, symbol: symbol, node: identifier }); + } + } + return symbolId; + } + // find first declaration in this file + var decls = symbol.getDeclarations(); + var declInFile = decls && ts.find(decls, function (d) { return d.getSourceFile() === sourceFile; }); + if (!declInFile) { + return undefined; + } + if (ts.rangeContainsStartEnd(enclosingTextRange, declInFile.getStart(), declInFile.end)) { + // declaration is located in range to be extracted - do nothing + return undefined; + } + if (targetRange.facts & RangeFacts.IsGenerator && usage === 2 /* Write */) { + // this is write to a reference located outside of the target scope and range is extracted into generator + // currently this is unsupported scenario + var diag = ts.createDiagnosticForNode(identifier, Messages.cannotExtractRangeThatContainsWritesToReferencesLocatedOutsideOfTheTargetRangeInGenerators); + for (var _a = 0, functionErrorsPerScope_1 = functionErrorsPerScope; _a < functionErrorsPerScope_1.length; _a++) { + var errors = functionErrorsPerScope_1[_a]; + errors.push(diag); + } + for (var _b = 0, constantErrorsPerScope_1 = constantErrorsPerScope; _b < constantErrorsPerScope_1.length; _b++) { + var errors = constantErrorsPerScope_1[_b]; + errors.push(diag); + } + } + for (var i = 0; i < scopes.length; i++) { + var scope = scopes[i]; + var resolvedSymbol = checker.resolveName(symbol.name, scope, symbol.flags, /*excludeGlobals*/ false); + if (resolvedSymbol === symbol) { + continue; + } + if (!substitutionsPerScope[i].has(symbolId)) { + var substitution = tryReplaceWithQualifiedNameOrPropertyAccess(symbol.exportSymbol || symbol, scope, isTypeName); + if (substitution) { + substitutionsPerScope[i].set(symbolId, substitution); + } + else if (isTypeName) { + // If the symbol is a type parameter that won't be in scope, we'll pass it as a type argument + // so there's no problem. + if (!(symbol.flags & 262144 /* TypeParameter */)) { + var diag = ts.createDiagnosticForNode(identifier, Messages.typeWillNotBeVisibleInTheNewScope); + functionErrorsPerScope[i].push(diag); + constantErrorsPerScope[i].push(diag); + } + } + else { + usagesPerScope[i].usages.set(identifier.text, { usage: usage, symbol: symbol, node: identifier }); + } + } + } + return symbolId; + } + function checkForUsedDeclarations(node) { + // If this node is entirely within the original extraction range, we don't need to do anything. + if (node === targetRange.range || (isReadonlyArray(targetRange.range) && targetRange.range.indexOf(node) >= 0)) { + return; + } + // Otherwise check and recurse. + var sym = ts.isIdentifier(node) + ? getSymbolReferencedByIdentifier(node) + : checker.getSymbolAtLocation(node); + if (sym) { + var decl = ts.find(visibleDeclarationsInExtractedRange, function (d) { return d.symbol === sym; }); + if (decl) { + if (ts.isVariableDeclaration(decl)) { + var idString = decl.symbol.id.toString(); + if (!exposedVariableSymbolSet.has(idString)) { + exposedVariableDeclarations.push(decl); + exposedVariableSymbolSet.set(idString, true); + } + } + else { + // CONSIDER: this includes binding elements, which we could + // expose in the same way as variables. + firstExposedNonVariableDeclaration = firstExposedNonVariableDeclaration || decl; + } + } + } + ts.forEachChild(node, checkForUsedDeclarations); + } + /** + * Return the symbol referenced by an identifier (even if it declares a different symbol). + */ + function getSymbolReferencedByIdentifier(identifier) { + // If the identifier is both a property name and its value, we're only interested in its value + // (since the name is a declaration and will be included in the extracted range). + return identifier.parent && ts.isShorthandPropertyAssignment(identifier.parent) && identifier.parent.name === identifier + ? checker.getShorthandAssignmentValueSymbol(identifier.parent) + : checker.getSymbolAtLocation(identifier); + } + function tryReplaceWithQualifiedNameOrPropertyAccess(symbol, scopeDecl, isTypeNode) { + if (!symbol) { + return undefined; + } + var decls = symbol.getDeclarations(); + if (decls && decls.some(function (d) { return d.parent === scopeDecl; })) { + return ts.createIdentifier(symbol.name); + } + var prefix = tryReplaceWithQualifiedNameOrPropertyAccess(symbol.parent, scopeDecl, isTypeNode); + if (prefix === undefined) { + return undefined; + } + return isTypeNode + ? ts.createQualifiedName(prefix, ts.createIdentifier(symbol.name)) + : ts.createPropertyAccess(prefix, symbol.name); + } + } + /** + * Computes whether or not a node represents an expression in a position where it could + * be extracted. + * The isExpression() in utilities.ts returns some false positives we need to handle, + * such as `import x from 'y'` -- the 'y' is a StringLiteral but is *not* an expression + * in the sense of something that you could extract on + */ + function isExtractableExpression(node) { + var parent = node.parent; + switch (parent.kind) { + case 278 /* EnumMember */: + return false; + } + switch (node.kind) { + case 10 /* StringLiteral */: + return parent.kind !== 249 /* ImportDeclaration */ && + parent.kind !== 253 /* ImportSpecifier */; + case 208 /* SpreadElement */: + case 184 /* ObjectBindingPattern */: + case 186 /* BindingElement */: + return false; + case 72 /* Identifier */: + return parent.kind !== 186 /* BindingElement */ && + parent.kind !== 253 /* ImportSpecifier */ && + parent.kind !== 257 /* ExportSpecifier */; + } + return true; + } + function isBlockLike(node) { + switch (node.kind) { + case 218 /* Block */: + case 279 /* SourceFile */: + case 245 /* ModuleBlock */: + case 271 /* CaseClause */: + return true; + default: + return false; + } + } + })(extractSymbol = refactor.extractSymbol || (refactor.extractSymbol = {})); + })(refactor = ts.refactor || (ts.refactor = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var refactor; + (function (refactor) { + var generateGetAccessorAndSetAccessor; + (function (generateGetAccessorAndSetAccessor) { + var actionName = "Generate 'get' and 'set' accessors"; + var actionDescription = ts.Diagnostics.Generate_get_and_set_accessors.message; + refactor.registerRefactor(actionName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions }); + function getAvailableActions(context) { + if (!getConvertibleFieldAtPosition(context)) + return ts.emptyArray; + return [{ + name: actionName, + description: actionDescription, + actions: [ + { + name: actionName, + description: actionDescription + } + ] + }]; + } + function getEditsForAction(context, _actionName) { + var file = context.file; + var fieldInfo = getConvertibleFieldAtPosition(context); + if (!fieldInfo) + return undefined; + var isJS = ts.isSourceFileJS(file); + var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); + var isStatic = fieldInfo.isStatic, isReadonly = fieldInfo.isReadonly, fieldName = fieldInfo.fieldName, accessorName = fieldInfo.accessorName, originalName = fieldInfo.originalName, type = fieldInfo.type, container = fieldInfo.container, declaration = fieldInfo.declaration, renameAccessor = fieldInfo.renameAccessor; + ts.suppressLeadingAndTrailingTrivia(fieldName); + ts.suppressLeadingAndTrailingTrivia(declaration); + ts.suppressLeadingAndTrailingTrivia(container); + var isInClassLike = ts.isClassLike(container); + // avoid Readonly modifier because it will convert to get accessor + var modifierFlags = ts.getModifierFlags(declaration) & ~64 /* Readonly */; + var accessorModifiers = isInClassLike + ? !modifierFlags || modifierFlags & 8 /* Private */ + ? getModifiers(isJS, isStatic, 115 /* PublicKeyword */) + : ts.createNodeArray(ts.createModifiersFromModifierFlags(modifierFlags)) + : undefined; + var fieldModifiers = isInClassLike ? getModifiers(isJS, isStatic, 113 /* PrivateKeyword */) : undefined; + updateFieldDeclaration(changeTracker, file, declaration, fieldName, fieldModifiers); + var getAccessor = generateGetAccessor(fieldName, accessorName, type, accessorModifiers, isStatic, container); + ts.suppressLeadingAndTrailingTrivia(getAccessor); + insertAccessor(changeTracker, file, getAccessor, declaration, container); + if (isReadonly) { + // readonly modifier only existed in classLikeDeclaration + var constructor = ts.getFirstConstructorWithBody(container); + if (constructor) { + updateReadonlyPropertyInitializerStatementConstructor(changeTracker, file, constructor, fieldName.text, originalName); + } + } + else { + var setAccessor = generateSetAccessor(fieldName, accessorName, type, accessorModifiers, isStatic, container); + ts.suppressLeadingAndTrailingTrivia(setAccessor); + insertAccessor(changeTracker, file, setAccessor, declaration, container); + } + var edits = changeTracker.getChanges(); + var renameFilename = file.fileName; + var nameNeedRename = renameAccessor ? accessorName : fieldName; + var renameLocationOffset = ts.isIdentifier(nameNeedRename) ? 0 : -1; + var renameLocation = renameLocationOffset + ts.getRenameLocation(edits, renameFilename, nameNeedRename.text, /*preferLastLocation*/ ts.isParameter(declaration)); + return { renameFilename: renameFilename, renameLocation: renameLocation, edits: edits }; + } + function isConvertibleName(name) { + return ts.isIdentifier(name) || ts.isStringLiteral(name); + } + function isAcceptedDeclaration(node) { + return ts.isParameterPropertyDeclaration(node) || ts.isPropertyDeclaration(node) || ts.isPropertyAssignment(node); + } + function createPropertyName(name, originalName) { + return ts.isIdentifier(originalName) ? ts.createIdentifier(name) : ts.createLiteral(name); + } + function createAccessorAccessExpression(fieldName, isStatic, container) { + var leftHead = isStatic ? container.name : ts.createThis(); // TODO: GH#18217 + return ts.isIdentifier(fieldName) ? ts.createPropertyAccess(leftHead, fieldName) : ts.createElementAccess(leftHead, ts.createLiteral(fieldName)); + } + function getModifiers(isJS, isStatic, accessModifier) { + var modifiers = ts.append(!isJS ? [ts.createToken(accessModifier)] : undefined, isStatic ? ts.createToken(116 /* StaticKeyword */) : undefined); + return modifiers && ts.createNodeArray(modifiers); + } + function startsWithUnderscore(name) { + return name.charCodeAt(0) === 95 /* _ */; + } + function getConvertibleFieldAtPosition(context) { + var file = context.file, startPosition = context.startPosition, endPosition = context.endPosition; + var node = ts.getTokenAtPosition(file, startPosition); + var declaration = ts.findAncestor(node.parent, isAcceptedDeclaration); + // make sure declaration have AccessibilityModifier or Static Modifier or Readonly Modifier + var meaning = 28 /* AccessibilityModifier */ | 32 /* Static */ | 64 /* Readonly */; + if (!declaration || !ts.nodeOverlapsWithStartEnd(declaration.name, file, startPosition, endPosition) // TODO: GH#18217 + || !isConvertibleName(declaration.name) || (ts.getModifierFlags(declaration) | meaning) !== meaning) + return undefined; + var name = declaration.name.text; + var startWithUnderscore = startsWithUnderscore(name); + var fieldName = createPropertyName(startWithUnderscore ? name : ts.getUniqueName("_" + name, file), declaration.name); + var accessorName = createPropertyName(startWithUnderscore ? ts.getUniqueName(name.substring(1), file) : name, declaration.name); + return { + isStatic: ts.hasStaticModifier(declaration), + isReadonly: ts.hasReadonlyModifier(declaration), + type: ts.getTypeAnnotationNode(declaration), + container: declaration.kind === 151 /* Parameter */ ? declaration.parent.parent : declaration.parent, + originalName: declaration.name.text, + declaration: declaration, + fieldName: fieldName, + accessorName: accessorName, + renameAccessor: startWithUnderscore + }; + } + function generateGetAccessor(fieldName, accessorName, type, modifiers, isStatic, container) { + return ts.createGetAccessor( + /*decorators*/ undefined, modifiers, accessorName, + /*parameters*/ undefined, // TODO: GH#18217 + type, ts.createBlock([ + ts.createReturn(createAccessorAccessExpression(fieldName, isStatic, container)) + ], /*multiLine*/ true)); + } + function generateSetAccessor(fieldName, accessorName, type, modifiers, isStatic, container) { + return ts.createSetAccessor( + /*decorators*/ undefined, modifiers, accessorName, [ts.createParameter( + /*decorators*/ undefined, + /*modifiers*/ undefined, + /*dotDotDotToken*/ undefined, ts.createIdentifier("value"), + /*questionToken*/ undefined, type)], ts.createBlock([ + ts.createStatement(ts.createAssignment(createAccessorAccessExpression(fieldName, isStatic, container), ts.createIdentifier("value"))) + ], /*multiLine*/ true)); + } + function updatePropertyDeclaration(changeTracker, file, declaration, fieldName, modifiers) { + var property = ts.updateProperty(declaration, declaration.decorators, modifiers, fieldName, declaration.questionToken || declaration.exclamationToken, declaration.type, declaration.initializer); + changeTracker.replaceNode(file, declaration, property); + } + function updatePropertyAssignmentDeclaration(changeTracker, file, declaration, fieldName) { + var assignment = ts.updatePropertyAssignment(declaration, fieldName, declaration.initializer); + changeTracker.replacePropertyAssignment(file, declaration, assignment); + } + function updateFieldDeclaration(changeTracker, file, declaration, fieldName, modifiers) { + if (ts.isPropertyDeclaration(declaration)) { + updatePropertyDeclaration(changeTracker, file, declaration, fieldName, modifiers); + } + else if (ts.isPropertyAssignment(declaration)) { + updatePropertyAssignmentDeclaration(changeTracker, file, declaration, fieldName); + } + else { + changeTracker.replaceNode(file, declaration, ts.updateParameter(declaration, declaration.decorators, modifiers, declaration.dotDotDotToken, ts.cast(fieldName, ts.isIdentifier), declaration.questionToken, declaration.type, declaration.initializer)); + } + } + function insertAccessor(changeTracker, file, accessor, declaration, container) { + ts.isParameterPropertyDeclaration(declaration) + ? changeTracker.insertNodeAtClassStart(file, container, accessor) + : ts.isPropertyAssignment(declaration) + ? changeTracker.insertNodeAfterComma(file, declaration, accessor) + : changeTracker.insertNodeAfter(file, declaration, accessor); + } + function updateReadonlyPropertyInitializerStatementConstructor(changeTracker, file, constructor, fieldName, originalName) { + if (!constructor.body) + return; + constructor.body.forEachChild(function recur(node) { + if (ts.isElementAccessExpression(node) && + node.expression.kind === 100 /* ThisKeyword */ && + ts.isStringLiteral(node.argumentExpression) && + node.argumentExpression.text === originalName && + ts.isWriteAccess(node)) { + changeTracker.replaceNode(file, node.argumentExpression, ts.createStringLiteral(fieldName)); + } + if (ts.isPropertyAccessExpression(node) && node.expression.kind === 100 /* ThisKeyword */ && node.name.text === originalName && ts.isWriteAccess(node)) { + changeTracker.replaceNode(file, node.name, ts.createIdentifier(fieldName)); + } + if (!ts.isFunctionLike(node) && !ts.isClassLike(node)) { + node.forEachChild(recur); + } + }); + } + })(generateGetAccessorAndSetAccessor = refactor.generateGetAccessorAndSetAccessor || (refactor.generateGetAccessorAndSetAccessor = {})); + })(refactor = ts.refactor || (ts.refactor = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var refactor; + (function (refactor) { + var refactorName = "Move to a new file"; + refactor.registerRefactor(refactorName, { + getAvailableActions: function (context) { + if (!context.preferences.allowTextChangesInNewFiles || getStatementsToMove(context) === undefined) + return ts.emptyArray; + var description = ts.getLocaleSpecificMessage(ts.Diagnostics.Move_to_a_new_file); + return [{ name: refactorName, description: description, actions: [{ name: refactorName, description: description }] }]; + }, + getEditsForAction: function (context, actionName) { + ts.Debug.assert(actionName === refactorName); + var statements = ts.Debug.assertDefined(getStatementsToMove(context)); + var edits = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(context.file, context.program, statements, t, context.host, context.preferences); }); + return { edits: edits, renameFilename: undefined, renameLocation: undefined }; + } + }); + function getRangeToMove(context) { + var file = context.file; + var range = ts.createTextRangeFromSpan(ts.getRefactorContextSpan(context)); + var statements = file.statements; + var startNodeIndex = ts.findIndex(statements, function (s) { return s.end > range.pos; }); + if (startNodeIndex === -1) + return undefined; + var startStatement = statements[startNodeIndex]; + if (ts.isNamedDeclaration(startStatement) && startStatement.name && ts.rangeContainsRange(startStatement.name, range)) { + return { toMove: [statements[startNodeIndex]], afterLast: statements[startNodeIndex + 1] }; + } + // Can't only partially include the start node or be partially into the next node + if (range.pos > startStatement.getStart(file)) + return undefined; + var afterEndNodeIndex = ts.findIndex(statements, function (s) { return s.end > range.end; }, startNodeIndex); + // Can't be partially into the next node + if (afterEndNodeIndex !== -1 && (afterEndNodeIndex === 0 || statements[afterEndNodeIndex].getStart(file) < range.end)) + return undefined; + return { + toMove: statements.slice(startNodeIndex, afterEndNodeIndex === -1 ? statements.length : afterEndNodeIndex), + afterLast: afterEndNodeIndex === -1 ? undefined : statements[afterEndNodeIndex], + }; + } + function doChange(oldFile, program, toMove, changes, host, preferences) { + var checker = program.getTypeChecker(); + var usage = getUsageInfo(oldFile, toMove.all, checker); + var currentDirectory = ts.getDirectoryPath(oldFile.fileName); + var extension = ts.extensionFromPath(oldFile.fileName); + var newModuleName = makeUniqueModuleName(getNewModuleName(usage.movedSymbols), extension, currentDirectory, host); + var newFileNameWithExtension = newModuleName + extension; + // If previous file was global, this is easy. + changes.createNewFile(oldFile, ts.combinePaths(currentDirectory, newFileNameWithExtension), getNewStatementsAndRemoveFromOldFile(oldFile, usage, changes, toMove, program, newModuleName, preferences)); + addNewFileToTsconfig(program, changes, oldFile.fileName, newFileNameWithExtension, ts.hostGetCanonicalFileName(host)); + } + // Filters imports out of the range of statements to move. Imports will be copied to the new file anyway, and may still be needed in the old file. + function getStatementsToMove(context) { + var rangeToMove = getRangeToMove(context); + if (rangeToMove === undefined) + return undefined; + var all = []; + var ranges = []; + var toMove = rangeToMove.toMove, afterLast = rangeToMove.afterLast; + ts.getRangesWhere(toMove, function (s) { return !isPureImport(s); }, function (start, afterEndIndex) { + for (var i = start; i < afterEndIndex; i++) + all.push(toMove[i]); + ranges.push({ first: toMove[start], afterLast: afterLast }); + }); + return all.length === 0 ? undefined : { all: all, ranges: ranges }; + } + function isPureImport(node) { + switch (node.kind) { + case 249 /* ImportDeclaration */: + return true; + case 248 /* ImportEqualsDeclaration */: + return !ts.hasModifier(node, 1 /* Export */); + case 219 /* VariableStatement */: + return node.declarationList.declarations.every(function (d) { return !!d.initializer && ts.isRequireCall(d.initializer, /*checkArgumentIsStringLiteralLike*/ true); }); + default: + return false; + } + } + function addNewFileToTsconfig(program, changes, oldFileName, newFileNameWithExtension, getCanonicalFileName) { + var cfg = program.getCompilerOptions().configFile; + if (!cfg) + return; + var newFileAbsolutePath = ts.normalizePath(ts.combinePaths(oldFileName, "..", newFileNameWithExtension)); + var newFilePath = ts.getRelativePathFromFile(cfg.fileName, newFileAbsolutePath, getCanonicalFileName); + var cfgObject = cfg.statements[0] && ts.tryCast(cfg.statements[0].expression, ts.isObjectLiteralExpression); + var filesProp = cfgObject && ts.find(cfgObject.properties, function (prop) { + return ts.isPropertyAssignment(prop) && ts.isStringLiteral(prop.name) && prop.name.text === "files"; + }); + if (filesProp && ts.isArrayLiteralExpression(filesProp.initializer)) { + changes.insertNodeInListAfter(cfg, ts.last(filesProp.initializer.elements), ts.createLiteral(newFilePath), filesProp.initializer.elements); + } + } + function getNewStatementsAndRemoveFromOldFile(oldFile, usage, changes, toMove, program, newModuleName, preferences) { + var checker = program.getTypeChecker(); + if (!oldFile.externalModuleIndicator && !oldFile.commonJsModuleIndicator) { + deleteMovedStatements(oldFile, toMove.ranges, changes); + return toMove.all; + } + var useEs6ModuleSyntax = !!oldFile.externalModuleIndicator; + var quotePreference = ts.getQuotePreference(oldFile, preferences); + var importsFromNewFile = createOldFileImportsFromNewFile(usage.oldFileImportsFromNewFile, newModuleName, useEs6ModuleSyntax, quotePreference); + if (importsFromNewFile) { + ts.insertImport(changes, oldFile, importsFromNewFile); + } + deleteUnusedOldImports(oldFile, toMove.all, changes, usage.unusedImportsFromOldFile, checker); + deleteMovedStatements(oldFile, toMove.ranges, changes); + updateImportsInOtherFiles(changes, program, oldFile, usage.movedSymbols, newModuleName); + return getNewFileImportsAndAddExportInOldFile(oldFile, usage.oldImportsNeededByNewFile, usage.newFileImportsFromOldFile, changes, checker, useEs6ModuleSyntax, quotePreference).concat(addExports(oldFile, toMove.all, usage.oldFileImportsFromNewFile, useEs6ModuleSyntax)); + } + function deleteMovedStatements(sourceFile, moved, changes) { + for (var _i = 0, moved_1 = moved; _i < moved_1.length; _i++) { + var _a = moved_1[_i], first_1 = _a.first, afterLast = _a.afterLast; + changes.deleteNodeRangeExcludingEnd(sourceFile, first_1, afterLast); + } + } + function deleteUnusedOldImports(oldFile, toMove, changes, toDelete, checker) { + for (var _i = 0, _a = oldFile.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + if (ts.contains(toMove, statement)) + continue; + forEachImportInStatement(statement, function (i) { return deleteUnusedImports(oldFile, i, changes, function (name) { return toDelete.has(checker.getSymbolAtLocation(name)); }); }); + } + } + function updateImportsInOtherFiles(changes, program, oldFile, movedSymbols, newModuleName) { + var checker = program.getTypeChecker(); + var _loop_14 = function (sourceFile) { + if (sourceFile === oldFile) + return "continue"; + var _loop_15 = function (statement) { + forEachImportInStatement(statement, function (importNode) { + if (checker.getSymbolAtLocation(moduleSpecifierFromImport(importNode)) !== oldFile.symbol) + return; + var shouldMove = function (name) { + var symbol = ts.isBindingElement(name.parent) + ? ts.getPropertySymbolFromBindingElement(checker, name.parent) + : ts.skipAlias(checker.getSymbolAtLocation(name), checker); // TODO: GH#18217 + return !!symbol && movedSymbols.has(symbol); + }; + deleteUnusedImports(sourceFile, importNode, changes, shouldMove); // These will be changed to imports from the new file + var newModuleSpecifier = ts.combinePaths(ts.getDirectoryPath(moduleSpecifierFromImport(importNode).text), newModuleName); + var newImportDeclaration = filterImport(importNode, ts.createLiteral(newModuleSpecifier), shouldMove); + if (newImportDeclaration) + changes.insertNodeAfter(sourceFile, statement, newImportDeclaration); + var ns = getNamespaceLikeImport(importNode); + if (ns) + updateNamespaceLikeImport(changes, sourceFile, checker, movedSymbols, newModuleName, newModuleSpecifier, ns, importNode); + }); + }; + for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + _loop_15(statement); + } + }; + for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { + var sourceFile = _a[_i]; + _loop_14(sourceFile); + } + } + function getNamespaceLikeImport(node) { + switch (node.kind) { + case 249 /* ImportDeclaration */: + return node.importClause && node.importClause.namedBindings && node.importClause.namedBindings.kind === 251 /* NamespaceImport */ ? + node.importClause.namedBindings.name : undefined; + case 248 /* ImportEqualsDeclaration */: + return node.name; + case 237 /* VariableDeclaration */: + return ts.tryCast(node.name, ts.isIdentifier); + default: + return ts.Debug.assertNever(node); + } + } + function updateNamespaceLikeImport(changes, sourceFile, checker, movedSymbols, newModuleName, newModuleSpecifier, oldImportId, oldImportNode) { + var preferredNewNamespaceName = ts.codefix.moduleSpecifierToValidIdentifier(newModuleName, 6 /* ESNext */); + var needUniqueName = false; + var toChange = []; + ts.FindAllReferences.Core.eachSymbolReferenceInFile(oldImportId, checker, sourceFile, function (ref) { + if (!ts.isPropertyAccessExpression(ref.parent)) + return; + needUniqueName = needUniqueName || !!checker.resolveName(preferredNewNamespaceName, ref, 67108863 /* All */, /*excludeGlobals*/ true); + if (movedSymbols.has(checker.getSymbolAtLocation(ref.parent.name))) { + toChange.push(ref); + } + }); + if (toChange.length) { + var newNamespaceName = needUniqueName ? ts.getUniqueName(preferredNewNamespaceName, sourceFile) : preferredNewNamespaceName; + for (var _i = 0, toChange_1 = toChange; _i < toChange_1.length; _i++) { + var ref = toChange_1[_i]; + changes.replaceNode(sourceFile, ref, ts.createIdentifier(newNamespaceName)); + } + changes.insertNodeAfter(sourceFile, oldImportNode, updateNamespaceLikeImportNode(oldImportNode, newModuleName, newModuleSpecifier)); + } + } + function updateNamespaceLikeImportNode(node, newNamespaceName, newModuleSpecifier) { + var newNamespaceId = ts.createIdentifier(newNamespaceName); + var newModuleString = ts.createLiteral(newModuleSpecifier); + switch (node.kind) { + case 249 /* ImportDeclaration */: + return ts.createImportDeclaration( + /*decorators*/ undefined, /*modifiers*/ undefined, ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(newNamespaceId)), newModuleString); + case 248 /* ImportEqualsDeclaration */: + return ts.createImportEqualsDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, newNamespaceId, ts.createExternalModuleReference(newModuleString)); + case 237 /* VariableDeclaration */: + return ts.createVariableDeclaration(newNamespaceId, /*type*/ undefined, createRequireCall(newModuleString)); + default: + return ts.Debug.assertNever(node); + } + } + function moduleSpecifierFromImport(i) { + return (i.kind === 249 /* ImportDeclaration */ ? i.moduleSpecifier + : i.kind === 248 /* ImportEqualsDeclaration */ ? i.moduleReference.expression + : i.initializer.arguments[0]); + } + function forEachImportInStatement(statement, cb) { + if (ts.isImportDeclaration(statement)) { + if (ts.isStringLiteral(statement.moduleSpecifier)) + cb(statement); + } + else if (ts.isImportEqualsDeclaration(statement)) { + if (ts.isExternalModuleReference(statement.moduleReference) && ts.isStringLiteralLike(statement.moduleReference.expression)) { + cb(statement); + } + } + else if (ts.isVariableStatement(statement)) { + for (var _i = 0, _a = statement.declarationList.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + if (decl.initializer && ts.isRequireCall(decl.initializer, /*checkArgumentIsStringLiteralLike*/ true)) { + cb(decl); + } + } + } + } + function createOldFileImportsFromNewFile(newFileNeedExport, newFileNameWithExtension, useEs6Imports, quotePreference) { + var defaultImport; + var imports = []; + newFileNeedExport.forEach(function (symbol) { + if (symbol.escapedName === "default" /* Default */) { + defaultImport = ts.createIdentifier(ts.symbolNameNoDefault(symbol)); // TODO: GH#18217 + } + else { + imports.push(symbol.name); + } + }); + return makeImportOrRequire(defaultImport, imports, newFileNameWithExtension, useEs6Imports, quotePreference); + } + function makeImportOrRequire(defaultImport, imports, path, useEs6Imports, quotePreference) { + path = ts.ensurePathIsNonModuleName(path); + if (useEs6Imports) { + var specifiers = imports.map(function (i) { return ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(i)); }); + return ts.makeImportIfNecessary(defaultImport, specifiers, path, quotePreference); + } + else { + ts.Debug.assert(!defaultImport); // If there's a default export, it should have been an es6 module. + var bindingElements = imports.map(function (i) { return ts.createBindingElement(/*dotDotDotToken*/ undefined, /*propertyName*/ undefined, i); }); + return bindingElements.length + ? makeVariableStatement(ts.createObjectBindingPattern(bindingElements), /*type*/ undefined, createRequireCall(ts.createLiteral(path))) + : undefined; + } + } + function makeVariableStatement(name, type, initializer, flags) { + if (flags === void 0) { flags = 2 /* Const */; } + return ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(name, type, initializer)], flags)); + } + function createRequireCall(moduleSpecifier) { + return ts.createCall(ts.createIdentifier("require"), /*typeArguments*/ undefined, [moduleSpecifier]); + } + function addExports(sourceFile, toMove, needExport, useEs6Exports) { + return ts.flatMap(toMove, function (statement) { + if (isTopLevelDeclarationStatement(statement) && + !isExported(sourceFile, statement, useEs6Exports) && + forEachTopLevelDeclaration(statement, function (d) { return needExport.has(ts.Debug.assertDefined(d.symbol)); })) { + var exports_1 = addExport(statement, useEs6Exports); + if (exports_1) + return exports_1; + } + return statement; + }); + } + function deleteUnusedImports(sourceFile, importDecl, changes, isUnused) { + switch (importDecl.kind) { + case 249 /* ImportDeclaration */: + deleteUnusedImportsInDeclaration(sourceFile, importDecl, changes, isUnused); + break; + case 248 /* ImportEqualsDeclaration */: + if (isUnused(importDecl.name)) { + changes.delete(sourceFile, importDecl); + } + break; + case 237 /* VariableDeclaration */: + deleteUnusedImportsInVariableDeclaration(sourceFile, importDecl, changes, isUnused); + break; + default: + ts.Debug.assertNever(importDecl); + } + } + function deleteUnusedImportsInDeclaration(sourceFile, importDecl, changes, isUnused) { + if (!importDecl.importClause) + return; + var _a = importDecl.importClause, name = _a.name, namedBindings = _a.namedBindings; + var defaultUnused = !name || isUnused(name); + var namedBindingsUnused = !namedBindings || + (namedBindings.kind === 251 /* NamespaceImport */ ? isUnused(namedBindings.name) : namedBindings.elements.length !== 0 && namedBindings.elements.every(function (e) { return isUnused(e.name); })); + if (defaultUnused && namedBindingsUnused) { + changes.delete(sourceFile, importDecl); + } + else { + if (name && defaultUnused) { + changes.delete(sourceFile, name); + } + if (namedBindings) { + if (namedBindingsUnused) { + changes.delete(sourceFile, namedBindings); + } + else if (namedBindings.kind === 252 /* NamedImports */) { + for (var _i = 0, _b = namedBindings.elements; _i < _b.length; _i++) { + var element = _b[_i]; + if (isUnused(element.name)) + changes.delete(sourceFile, element); + } + } + } + } + } + function deleteUnusedImportsInVariableDeclaration(sourceFile, varDecl, changes, isUnused) { + var name = varDecl.name; + switch (name.kind) { + case 72 /* Identifier */: + if (isUnused(name)) { + changes.delete(sourceFile, name); + } + break; + case 185 /* ArrayBindingPattern */: + break; + case 184 /* ObjectBindingPattern */: + if (name.elements.every(function (e) { return ts.isIdentifier(e.name) && isUnused(e.name); })) { + changes.delete(sourceFile, ts.isVariableDeclarationList(varDecl.parent) && varDecl.parent.declarations.length === 1 ? varDecl.parent.parent : varDecl); + } + else { + for (var _i = 0, _a = name.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (ts.isIdentifier(element.name) && isUnused(element.name)) { + changes.delete(sourceFile, element.name); + } + } + } + break; + } + } + function getNewFileImportsAndAddExportInOldFile(oldFile, importsToCopy, newFileImportsFromOldFile, changes, checker, useEs6ModuleSyntax, quotePreference) { + var copiedOldImports = []; + for (var _i = 0, _a = oldFile.statements; _i < _a.length; _i++) { + var oldStatement = _a[_i]; + forEachImportInStatement(oldStatement, function (i) { + ts.append(copiedOldImports, filterImport(i, moduleSpecifierFromImport(i), function (name) { return importsToCopy.has(checker.getSymbolAtLocation(name)); })); + }); + } + // Also, import things used from the old file, and insert 'export' modifiers as necessary in the old file. + var oldFileDefault; + var oldFileNamedImports = []; + var markSeenTop = ts.nodeSeenTracker(); // Needed because multiple declarations may appear in `const x = 0, y = 1;`. + newFileImportsFromOldFile.forEach(function (symbol) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + if (!isTopLevelDeclaration(decl)) + continue; + var name = nameOfTopLevelDeclaration(decl); + if (!name) + continue; + var top = getTopLevelDeclarationStatement(decl); + if (markSeenTop(top)) { + addExportToChanges(oldFile, top, changes, useEs6ModuleSyntax); + } + if (ts.hasModifier(decl, 512 /* Default */)) { + oldFileDefault = name; + } + else { + oldFileNamedImports.push(name.text); + } + } + }); + ts.append(copiedOldImports, makeImportOrRequire(oldFileDefault, oldFileNamedImports, ts.removeFileExtension(ts.getBaseFileName(oldFile.fileName)), useEs6ModuleSyntax, quotePreference)); + return copiedOldImports; + } + function makeUniqueModuleName(moduleName, extension, inDirectory, host) { + var newModuleName = moduleName; + for (var i = 1;; i++) { + var name = ts.combinePaths(inDirectory, newModuleName + extension); + if (!host.fileExists(name)) + return newModuleName; // TODO: GH#18217 + newModuleName = moduleName + "." + i; + } + } + function getNewModuleName(movedSymbols) { + return movedSymbols.forEachEntry(ts.symbolNameNoDefault) || "newFile"; + } + function getUsageInfo(oldFile, toMove, checker) { + var movedSymbols = new SymbolSet(); + var oldImportsNeededByNewFile = new SymbolSet(); + var newFileImportsFromOldFile = new SymbolSet(); + for (var _i = 0, toMove_1 = toMove; _i < toMove_1.length; _i++) { + var statement = toMove_1[_i]; + forEachTopLevelDeclaration(statement, function (decl) { + movedSymbols.add(ts.Debug.assertDefined(ts.isExpressionStatement(decl) ? checker.getSymbolAtLocation(decl.expression.left) : decl.symbol)); + }); + } + for (var _a = 0, toMove_2 = toMove; _a < toMove_2.length; _a++) { + var statement = toMove_2[_a]; + forEachReference(statement, checker, function (symbol) { + if (!symbol.declarations) + return; + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + if (isInImport(decl)) { + oldImportsNeededByNewFile.add(symbol); + } + else if (isTopLevelDeclaration(decl) && sourceFileOfTopLevelDeclaration(decl) === oldFile && !movedSymbols.has(symbol)) { + newFileImportsFromOldFile.add(symbol); + } + } + }); + } + var unusedImportsFromOldFile = oldImportsNeededByNewFile.clone(); + var oldFileImportsFromNewFile = new SymbolSet(); + for (var _b = 0, _c = oldFile.statements; _b < _c.length; _b++) { + var statement = _c[_b]; + if (ts.contains(toMove, statement)) + continue; + forEachReference(statement, checker, function (symbol) { + if (movedSymbols.has(symbol)) + oldFileImportsFromNewFile.add(symbol); + unusedImportsFromOldFile.delete(symbol); + }); + } + return { movedSymbols: movedSymbols, newFileImportsFromOldFile: newFileImportsFromOldFile, oldFileImportsFromNewFile: oldFileImportsFromNewFile, oldImportsNeededByNewFile: oldImportsNeededByNewFile, unusedImportsFromOldFile: unusedImportsFromOldFile }; + } + // Below should all be utilities + function isInImport(decl) { + switch (decl.kind) { + case 248 /* ImportEqualsDeclaration */: + case 253 /* ImportSpecifier */: + case 250 /* ImportClause */: + return true; + case 237 /* VariableDeclaration */: + return isVariableDeclarationInImport(decl); + case 186 /* BindingElement */: + return ts.isVariableDeclaration(decl.parent.parent) && isVariableDeclarationInImport(decl.parent.parent); + default: + return false; + } + } + function isVariableDeclarationInImport(decl) { + return ts.isSourceFile(decl.parent.parent.parent) && + decl.initializer && ts.isRequireCall(decl.initializer, /*checkArgumentIsStringLiteralLike*/ true); + } + function filterImport(i, moduleSpecifier, keep) { + switch (i.kind) { + case 249 /* ImportDeclaration */: { + var clause = i.importClause; + if (!clause) + return undefined; + var defaultImport = clause.name && keep(clause.name) ? clause.name : undefined; + var namedBindings = clause.namedBindings && filterNamedBindings(clause.namedBindings, keep); + return defaultImport || namedBindings + ? ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createImportClause(defaultImport, namedBindings), moduleSpecifier) + : undefined; + } + case 248 /* ImportEqualsDeclaration */: + return keep(i.name) ? i : undefined; + case 237 /* VariableDeclaration */: { + var name = filterBindingName(i.name, keep); + return name ? makeVariableStatement(name, i.type, createRequireCall(moduleSpecifier), i.parent.flags) : undefined; + } + default: + return ts.Debug.assertNever(i); + } + } + function filterNamedBindings(namedBindings, keep) { + if (namedBindings.kind === 251 /* NamespaceImport */) { + return keep(namedBindings.name) ? namedBindings : undefined; + } + else { + var newElements = namedBindings.elements.filter(function (e) { return keep(e.name); }); + return newElements.length ? ts.createNamedImports(newElements) : undefined; + } + } + function filterBindingName(name, keep) { + switch (name.kind) { + case 72 /* Identifier */: + return keep(name) ? name : undefined; + case 185 /* ArrayBindingPattern */: + return name; + case 184 /* ObjectBindingPattern */: { + // We can't handle nested destructurings or property names well here, so just copy them all. + var newElements = name.elements.filter(function (prop) { return prop.propertyName || !ts.isIdentifier(prop.name) || keep(prop.name); }); + return newElements.length ? ts.createObjectBindingPattern(newElements) : undefined; + } + } + } + function forEachReference(node, checker, onReference) { + node.forEachChild(function cb(node) { + if (ts.isIdentifier(node) && !ts.isDeclarationName(node)) { + var sym = checker.getSymbolAtLocation(node); + if (sym) + onReference(sym); + } + else { + node.forEachChild(cb); + } + }); + } + var SymbolSet = /** @class */ (function () { + function SymbolSet() { + this.map = ts.createMap(); + } + SymbolSet.prototype.add = function (symbol) { + this.map.set(String(ts.getSymbolId(symbol)), symbol); + }; + SymbolSet.prototype.has = function (symbol) { + return this.map.has(String(ts.getSymbolId(symbol))); + }; + SymbolSet.prototype.delete = function (symbol) { + this.map.delete(String(ts.getSymbolId(symbol))); + }; + SymbolSet.prototype.forEach = function (cb) { + this.map.forEach(cb); + }; + SymbolSet.prototype.forEachEntry = function (cb) { + return ts.forEachEntry(this.map, cb); + }; + SymbolSet.prototype.clone = function () { + var clone = new SymbolSet(); + ts.copyEntries(this.map, clone.map); + return clone; + }; + return SymbolSet; + }()); + function isTopLevelDeclaration(node) { + return isNonVariableTopLevelDeclaration(node) && ts.isSourceFile(node.parent) || ts.isVariableDeclaration(node) && ts.isSourceFile(node.parent.parent.parent); + } + function sourceFileOfTopLevelDeclaration(node) { + return ts.isVariableDeclaration(node) ? node.parent.parent.parent : node.parent; + } + function isTopLevelDeclarationStatement(node) { + ts.Debug.assert(ts.isSourceFile(node.parent)); + return isNonVariableTopLevelDeclaration(node) || ts.isVariableStatement(node); + } + function isNonVariableTopLevelDeclaration(node) { + switch (node.kind) { + case 239 /* FunctionDeclaration */: + case 240 /* ClassDeclaration */: + case 244 /* ModuleDeclaration */: + case 243 /* EnumDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 241 /* InterfaceDeclaration */: + case 248 /* ImportEqualsDeclaration */: + return true; + default: + return false; + } + } + function forEachTopLevelDeclaration(statement, cb) { + switch (statement.kind) { + case 239 /* FunctionDeclaration */: + case 240 /* ClassDeclaration */: + case 244 /* ModuleDeclaration */: + case 243 /* EnumDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 241 /* InterfaceDeclaration */: + case 248 /* ImportEqualsDeclaration */: + return cb(statement); + case 219 /* VariableStatement */: + return ts.firstDefined(statement.declarationList.declarations, function (decl) { return forEachTopLevelDeclarationInBindingName(decl.name, cb); }); + case 221 /* ExpressionStatement */: { + var expression = statement.expression; + return ts.isBinaryExpression(expression) && ts.getAssignmentDeclarationKind(expression) === 1 /* ExportsProperty */ + ? cb(statement) + : undefined; + } + } + } + function forEachTopLevelDeclarationInBindingName(name, cb) { + switch (name.kind) { + case 72 /* Identifier */: + return cb(ts.cast(name.parent, function (x) { return ts.isVariableDeclaration(x) || ts.isBindingElement(x); })); + case 185 /* ArrayBindingPattern */: + case 184 /* ObjectBindingPattern */: + return ts.firstDefined(name.elements, function (em) { return ts.isOmittedExpression(em) ? undefined : forEachTopLevelDeclarationInBindingName(em.name, cb); }); + default: + return ts.Debug.assertNever(name); + } + } + function nameOfTopLevelDeclaration(d) { + return ts.isExpressionStatement(d) ? d.expression.left.name : ts.tryCast(d.name, ts.isIdentifier); + } + function getTopLevelDeclarationStatement(d) { + switch (d.kind) { + case 237 /* VariableDeclaration */: + return d.parent.parent; + case 186 /* BindingElement */: + return getTopLevelDeclarationStatement(ts.cast(d.parent.parent, function (p) { return ts.isVariableDeclaration(p) || ts.isBindingElement(p); })); + default: + return d; + } + } + function addExportToChanges(sourceFile, decl, changes, useEs6Exports) { + if (isExported(sourceFile, decl, useEs6Exports)) + return; + if (useEs6Exports) { + if (!ts.isExpressionStatement(decl)) + changes.insertExportModifier(sourceFile, decl); + } + else { + var names = getNamesToExportInCommonJS(decl); + if (names.length !== 0) + changes.insertNodesAfter(sourceFile, decl, names.map(createExportAssignment)); + } + } + function isExported(sourceFile, decl, useEs6Exports) { + if (useEs6Exports) { + return !ts.isExpressionStatement(decl) && ts.hasModifier(decl, 1 /* Export */); + } + else { + return getNamesToExportInCommonJS(decl).some(function (name) { return sourceFile.symbol.exports.has(ts.escapeLeadingUnderscores(name)); }); + } + } + function addExport(decl, useEs6Exports) { + return useEs6Exports ? [addEs6Export(decl)] : addCommonjsExport(decl); + } + function addEs6Export(d) { + var modifiers = ts.concatenate([ts.createModifier(85 /* ExportKeyword */)], d.modifiers); + switch (d.kind) { + case 239 /* FunctionDeclaration */: + return ts.updateFunctionDeclaration(d, d.decorators, modifiers, d.asteriskToken, d.name, d.typeParameters, d.parameters, d.type, d.body); + case 240 /* ClassDeclaration */: + return ts.updateClassDeclaration(d, d.decorators, modifiers, d.name, d.typeParameters, d.heritageClauses, d.members); + case 219 /* VariableStatement */: + return ts.updateVariableStatement(d, modifiers, d.declarationList); + case 244 /* ModuleDeclaration */: + return ts.updateModuleDeclaration(d, d.decorators, modifiers, d.name, d.body); + case 243 /* EnumDeclaration */: + return ts.updateEnumDeclaration(d, d.decorators, modifiers, d.name, d.members); + case 242 /* TypeAliasDeclaration */: + return ts.updateTypeAliasDeclaration(d, d.decorators, modifiers, d.name, d.typeParameters, d.type); + case 241 /* InterfaceDeclaration */: + return ts.updateInterfaceDeclaration(d, d.decorators, modifiers, d.name, d.typeParameters, d.heritageClauses, d.members); + case 248 /* ImportEqualsDeclaration */: + return ts.updateImportEqualsDeclaration(d, d.decorators, modifiers, d.name, d.moduleReference); + case 221 /* ExpressionStatement */: + return ts.Debug.fail(); // Shouldn't try to add 'export' keyword to `exports.x = ...` + default: + return ts.Debug.assertNever(d); + } + } + function addCommonjsExport(decl) { + return [decl].concat(getNamesToExportInCommonJS(decl).map(createExportAssignment)); + } + function getNamesToExportInCommonJS(decl) { + switch (decl.kind) { + case 239 /* FunctionDeclaration */: + case 240 /* ClassDeclaration */: + return [decl.name.text]; // TODO: GH#18217 + case 219 /* VariableStatement */: + return ts.mapDefined(decl.declarationList.declarations, function (d) { return ts.isIdentifier(d.name) ? d.name.text : undefined; }); + case 244 /* ModuleDeclaration */: + case 243 /* EnumDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 241 /* InterfaceDeclaration */: + case 248 /* ImportEqualsDeclaration */: + return ts.emptyArray; + case 221 /* ExpressionStatement */: + return ts.Debug.fail(); // Shouldn't try to add 'export' keyword to `exports.x = ...` + default: + return ts.Debug.assertNever(decl); + } + } + /** Creates `exports.x = x;` */ + function createExportAssignment(name) { + return ts.createExpressionStatement(ts.createBinary(ts.createPropertyAccess(ts.createIdentifier("exports"), ts.createIdentifier(name)), 59 /* EqualsToken */, ts.createIdentifier(name))); + } + })(refactor = ts.refactor || (ts.refactor = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var refactor; + (function (refactor) { + var addOrRemoveBracesToArrowFunction; + (function (addOrRemoveBracesToArrowFunction) { + var refactorName = "Add or remove braces in an arrow function"; + var refactorDescription = ts.Diagnostics.Add_or_remove_braces_in_an_arrow_function.message; + var addBracesActionName = "Add braces to arrow function"; + var removeBracesActionName = "Remove braces from arrow function"; + var addBracesActionDescription = ts.Diagnostics.Add_braces_to_arrow_function.message; + var removeBracesActionDescription = ts.Diagnostics.Remove_braces_from_arrow_function.message; + refactor.registerRefactor(refactorName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions }); + function getAvailableActions(context) { + var file = context.file, startPosition = context.startPosition; + var info = getConvertibleArrowFunctionAtPosition(file, startPosition); + if (!info) + return ts.emptyArray; + return [{ + name: refactorName, + description: refactorDescription, + actions: [ + info.addBraces ? + { + name: addBracesActionName, + description: addBracesActionDescription + } : { + name: removeBracesActionName, + description: removeBracesActionDescription + } + ] + }]; + } + function getEditsForAction(context, actionName) { + var file = context.file, startPosition = context.startPosition; + var info = getConvertibleArrowFunctionAtPosition(file, startPosition); + if (!info) + return undefined; + var expression = info.expression, returnStatement = info.returnStatement, func = info.func; + var body; + if (actionName === addBracesActionName) { + var returnStatement_1 = ts.createReturn(expression); + body = ts.createBlock([returnStatement_1], /* multiLine */ true); + ts.suppressLeadingAndTrailingTrivia(body); + ts.copyComments(expression, returnStatement_1, file, 3 /* MultiLineCommentTrivia */, /* hasTrailingNewLine */ true); + } + else if (actionName === removeBracesActionName && returnStatement) { + var actualExpression = expression || ts.createVoidZero(); + body = needsParentheses(actualExpression) ? ts.createParen(actualExpression) : actualExpression; + ts.suppressLeadingAndTrailingTrivia(body); + ts.copyComments(returnStatement, body, file, 3 /* MultiLineCommentTrivia */, /* hasTrailingNewLine */ false); + } + else { + ts.Debug.fail("invalid action"); + } + var edits = ts.textChanges.ChangeTracker.with(context, function (t) { return t.replaceNode(file, func.body, body); }); + return { renameFilename: undefined, renameLocation: undefined, edits: edits }; + } + function needsParentheses(expression) { + return ts.isBinaryExpression(expression) && expression.operatorToken.kind === 27 /* CommaToken */ || ts.isObjectLiteralExpression(expression); + } + function getConvertibleArrowFunctionAtPosition(file, startPosition) { + var node = ts.getTokenAtPosition(file, startPosition); + var func = ts.getContainingFunction(node); + if (!func || !ts.isArrowFunction(func) || (!ts.rangeContainsRange(func, node) || ts.rangeContainsRange(func.body, node))) + return undefined; + if (ts.isExpression(func.body)) { + return { + func: func, + addBraces: true, + expression: func.body + }; + } + else if (func.body.statements.length === 1) { + var firstStatement = ts.first(func.body.statements); + if (ts.isReturnStatement(firstStatement)) { + return { + func: func, + addBraces: false, + expression: firstStatement.expression, + returnStatement: firstStatement + }; + } + } + return undefined; + } + })(addOrRemoveBracesToArrowFunction = refactor.addOrRemoveBracesToArrowFunction || (refactor.addOrRemoveBracesToArrowFunction = {})); + })(refactor = ts.refactor || (ts.refactor = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + /** The version of the language service API */ + ts.servicesVersion = "0.8"; + function createNode(kind, pos, end, parent) { + var node = ts.isNodeKind(kind) ? new NodeObject(kind, pos, end) : + kind === 72 /* Identifier */ ? new IdentifierObject(72 /* Identifier */, pos, end) : + new TokenObject(kind, pos, end); + node.parent = parent; + node.flags = parent.flags & 12679168 /* ContextFlags */; + return node; + } + var NodeObject = /** @class */ (function () { + function NodeObject(kind, pos, end) { + this.pos = pos; + this.end = end; + this.flags = 0 /* None */; + this.transformFlags = undefined; // TODO: GH#18217 + this.parent = undefined; + this.kind = kind; + } + NodeObject.prototype.assertHasRealPosition = function (message) { + // tslint:disable-next-line:debug-assert + ts.Debug.assert(!ts.positionIsSynthesized(this.pos) && !ts.positionIsSynthesized(this.end), message || "Node must have a real position for this operation"); + }; + NodeObject.prototype.getSourceFile = function () { + return ts.getSourceFileOfNode(this); + }; + NodeObject.prototype.getStart = function (sourceFile, includeJsDocComment) { + this.assertHasRealPosition(); + return ts.getTokenPosOfNode(this, sourceFile, includeJsDocComment); + }; + NodeObject.prototype.getFullStart = function () { + this.assertHasRealPosition(); + return this.pos; + }; + NodeObject.prototype.getEnd = function () { + this.assertHasRealPosition(); + return this.end; + }; + NodeObject.prototype.getWidth = function (sourceFile) { + this.assertHasRealPosition(); + return this.getEnd() - this.getStart(sourceFile); + }; + NodeObject.prototype.getFullWidth = function () { + this.assertHasRealPosition(); + return this.end - this.pos; + }; + NodeObject.prototype.getLeadingTriviaWidth = function (sourceFile) { + this.assertHasRealPosition(); + return this.getStart(sourceFile) - this.pos; + }; + NodeObject.prototype.getFullText = function (sourceFile) { + this.assertHasRealPosition(); + return (sourceFile || this.getSourceFile()).text.substring(this.pos, this.end); + }; + NodeObject.prototype.getText = function (sourceFile) { + this.assertHasRealPosition(); + if (!sourceFile) { + sourceFile = this.getSourceFile(); + } + return sourceFile.text.substring(this.getStart(sourceFile), this.getEnd()); + }; + NodeObject.prototype.getChildCount = function (sourceFile) { + return this.getChildren(sourceFile).length; + }; + NodeObject.prototype.getChildAt = function (index, sourceFile) { + return this.getChildren(sourceFile)[index]; + }; + NodeObject.prototype.getChildren = function (sourceFile) { + this.assertHasRealPosition("Node without a real position cannot be scanned and thus has no token nodes - use forEachChild and collect the result if that's fine"); + return this._children || (this._children = createChildren(this, sourceFile)); + }; + NodeObject.prototype.getFirstToken = function (sourceFile) { + this.assertHasRealPosition(); + var children = this.getChildren(sourceFile); + if (!children.length) { + return undefined; + } + var child = ts.find(children, function (kid) { return kid.kind < 283 /* FirstJSDocNode */ || kid.kind > 305 /* LastJSDocNode */; }); + return child.kind < 148 /* FirstNode */ ? + child : + child.getFirstToken(sourceFile); + }; + NodeObject.prototype.getLastToken = function (sourceFile) { + this.assertHasRealPosition(); + var children = this.getChildren(sourceFile); + var child = ts.lastOrUndefined(children); + if (!child) { + return undefined; + } + return child.kind < 148 /* FirstNode */ ? child : child.getLastToken(sourceFile); + }; + NodeObject.prototype.forEachChild = function (cbNode, cbNodeArray) { + return ts.forEachChild(this, cbNode, cbNodeArray); + }; + return NodeObject; + }()); + function createChildren(node, sourceFile) { + if (!ts.isNodeKind(node.kind)) { + return ts.emptyArray; + } + var children = []; + if (ts.isJSDocCommentContainingNode(node)) { + /** Don't add trivia for "tokens" since this is in a comment. */ + node.forEachChild(function (child) { children.push(child); }); + return children; + } + ts.scanner.setText((sourceFile || node.getSourceFile()).text); + var pos = node.pos; + var processNode = function (child) { + addSyntheticNodes(children, pos, child.pos, node); + children.push(child); + pos = child.end; + }; + var processNodes = function (nodes) { + addSyntheticNodes(children, pos, nodes.pos, node); + children.push(createSyntaxList(nodes, node)); + pos = nodes.end; + }; + // jsDocComments need to be the first children + ts.forEach(node.jsDoc, processNode); + // For syntactic classifications, all trivia are classified together, including jsdoc comments. + // For that to work, the jsdoc comments should still be the leading trivia of the first child. + // Restoring the scanner position ensures that. + pos = node.pos; + node.forEachChild(processNode, processNodes); + addSyntheticNodes(children, pos, node.end, node); + ts.scanner.setText(undefined); + return children; + } + function addSyntheticNodes(nodes, pos, end, parent) { + ts.scanner.setTextPos(pos); + while (pos < end) { + var token = ts.scanner.scan(); + var textPos = ts.scanner.getTextPos(); + if (textPos <= end) { + if (token === 72 /* Identifier */) { + ts.Debug.fail("Did not expect " + ts.Debug.showSyntaxKind(parent) + " to have an Identifier in its trivia"); + } + nodes.push(createNode(token, pos, textPos, parent)); + } + pos = textPos; + if (token === 1 /* EndOfFileToken */) { + break; + } + } + } + function createSyntaxList(nodes, parent) { + var list = createNode(306 /* SyntaxList */, nodes.pos, nodes.end, parent); + list._children = []; + var pos = nodes.pos; + for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) { + var node = nodes_1[_i]; + addSyntheticNodes(list._children, pos, node.pos, parent); + list._children.push(node); + pos = node.end; + } + addSyntheticNodes(list._children, pos, nodes.end, parent); + return list; + } + var TokenOrIdentifierObject = /** @class */ (function () { + function TokenOrIdentifierObject(pos, end) { + // Set properties in same order as NodeObject + this.pos = pos; + this.end = end; + this.flags = 0 /* None */; + this.parent = undefined; + } + TokenOrIdentifierObject.prototype.getSourceFile = function () { + return ts.getSourceFileOfNode(this); + }; + TokenOrIdentifierObject.prototype.getStart = function (sourceFile, includeJsDocComment) { + return ts.getTokenPosOfNode(this, sourceFile, includeJsDocComment); + }; + TokenOrIdentifierObject.prototype.getFullStart = function () { + return this.pos; + }; + TokenOrIdentifierObject.prototype.getEnd = function () { + return this.end; + }; + TokenOrIdentifierObject.prototype.getWidth = function (sourceFile) { + return this.getEnd() - this.getStart(sourceFile); + }; + TokenOrIdentifierObject.prototype.getFullWidth = function () { + return this.end - this.pos; + }; + TokenOrIdentifierObject.prototype.getLeadingTriviaWidth = function (sourceFile) { + return this.getStart(sourceFile) - this.pos; + }; + TokenOrIdentifierObject.prototype.getFullText = function (sourceFile) { + return (sourceFile || this.getSourceFile()).text.substring(this.pos, this.end); + }; + TokenOrIdentifierObject.prototype.getText = function (sourceFile) { + if (!sourceFile) { + sourceFile = this.getSourceFile(); + } + return sourceFile.text.substring(this.getStart(sourceFile), this.getEnd()); + }; + TokenOrIdentifierObject.prototype.getChildCount = function () { + return 0; + }; + TokenOrIdentifierObject.prototype.getChildAt = function () { + return undefined; // TODO: GH#18217 + }; + TokenOrIdentifierObject.prototype.getChildren = function () { + return this.kind === 1 /* EndOfFileToken */ ? this.jsDoc || ts.emptyArray : ts.emptyArray; + }; + TokenOrIdentifierObject.prototype.getFirstToken = function () { + return undefined; + }; + TokenOrIdentifierObject.prototype.getLastToken = function () { + return undefined; + }; + TokenOrIdentifierObject.prototype.forEachChild = function () { + return undefined; + }; + return TokenOrIdentifierObject; + }()); + var SymbolObject = /** @class */ (function () { + function SymbolObject(flags, name) { + this.flags = flags; + this.escapedName = name; + } + SymbolObject.prototype.getFlags = function () { + return this.flags; + }; + Object.defineProperty(SymbolObject.prototype, "name", { + get: function () { + return ts.symbolName(this); + }, + enumerable: true, + configurable: true + }); + SymbolObject.prototype.getEscapedName = function () { + return this.escapedName; + }; + SymbolObject.prototype.getName = function () { + return this.name; + }; + SymbolObject.prototype.getDeclarations = function () { + return this.declarations; + }; + SymbolObject.prototype.getDocumentationComment = function (checker) { + if (!this.documentationComment) { + this.documentationComment = ts.emptyArray; // Set temporarily to avoid an infinite loop finding inherited docs + this.documentationComment = getDocumentationComment(this.declarations, checker); + } + return this.documentationComment; + }; + SymbolObject.prototype.getJsDocTags = function () { + if (this.tags === undefined) { + this.tags = ts.JsDoc.getJsDocTagsFromDeclarations(this.declarations); + } + return this.tags; + }; + return SymbolObject; + }()); + var TokenObject = /** @class */ (function (_super) { + __extends(TokenObject, _super); + function TokenObject(kind, pos, end) { + var _this = _super.call(this, pos, end) || this; + _this.kind = kind; + return _this; + } + return TokenObject; + }(TokenOrIdentifierObject)); + var IdentifierObject = /** @class */ (function (_super) { + __extends(IdentifierObject, _super); + function IdentifierObject(_kind, pos, end) { + return _super.call(this, pos, end) || this; + } + Object.defineProperty(IdentifierObject.prototype, "text", { + get: function () { + return ts.idText(this); + }, + enumerable: true, + configurable: true + }); + return IdentifierObject; + }(TokenOrIdentifierObject)); + IdentifierObject.prototype.kind = 72 /* Identifier */; + var TypeObject = /** @class */ (function () { + function TypeObject(checker, flags) { + this.checker = checker; + this.flags = flags; + } + TypeObject.prototype.getFlags = function () { + return this.flags; + }; + TypeObject.prototype.getSymbol = function () { + return this.symbol; + }; + TypeObject.prototype.getProperties = function () { + return this.checker.getPropertiesOfType(this); + }; + TypeObject.prototype.getProperty = function (propertyName) { + return this.checker.getPropertyOfType(this, propertyName); + }; + TypeObject.prototype.getApparentProperties = function () { + return this.checker.getAugmentedPropertiesOfType(this); + }; + TypeObject.prototype.getCallSignatures = function () { + return this.checker.getSignaturesOfType(this, 0 /* Call */); + }; + TypeObject.prototype.getConstructSignatures = function () { + return this.checker.getSignaturesOfType(this, 1 /* Construct */); + }; + TypeObject.prototype.getStringIndexType = function () { + return this.checker.getIndexTypeOfType(this, 0 /* String */); + }; + TypeObject.prototype.getNumberIndexType = function () { + return this.checker.getIndexTypeOfType(this, 1 /* Number */); + }; + TypeObject.prototype.getBaseTypes = function () { + return this.isClassOrInterface() ? this.checker.getBaseTypes(this) : undefined; + }; + TypeObject.prototype.getNonNullableType = function () { + return this.checker.getNonNullableType(this); + }; + TypeObject.prototype.getConstraint = function () { + return this.checker.getBaseConstraintOfType(this); + }; + TypeObject.prototype.getDefault = function () { + return this.checker.getDefaultFromTypeParameter(this); + }; + TypeObject.prototype.isUnion = function () { + return !!(this.flags & 1048576 /* Union */); + }; + TypeObject.prototype.isIntersection = function () { + return !!(this.flags & 2097152 /* Intersection */); + }; + TypeObject.prototype.isUnionOrIntersection = function () { + return !!(this.flags & 3145728 /* UnionOrIntersection */); + }; + TypeObject.prototype.isLiteral = function () { + return !!(this.flags & 384 /* StringOrNumberLiteral */); + }; + TypeObject.prototype.isStringLiteral = function () { + return !!(this.flags & 128 /* StringLiteral */); + }; + TypeObject.prototype.isNumberLiteral = function () { + return !!(this.flags & 256 /* NumberLiteral */); + }; + TypeObject.prototype.isTypeParameter = function () { + return !!(this.flags & 262144 /* TypeParameter */); + }; + TypeObject.prototype.isClassOrInterface = function () { + return !!(ts.getObjectFlags(this) & 3 /* ClassOrInterface */); + }; + TypeObject.prototype.isClass = function () { + return !!(ts.getObjectFlags(this) & 1 /* Class */); + }; + return TypeObject; + }()); + var SignatureObject = /** @class */ (function () { + function SignatureObject(checker) { + this.checker = checker; + } + SignatureObject.prototype.getDeclaration = function () { + return this.declaration; + }; + SignatureObject.prototype.getTypeParameters = function () { + return this.typeParameters; + }; + SignatureObject.prototype.getParameters = function () { + return this.parameters; + }; + SignatureObject.prototype.getReturnType = function () { + return this.checker.getReturnTypeOfSignature(this); + }; + SignatureObject.prototype.getDocumentationComment = function () { + return this.documentationComment || (this.documentationComment = getDocumentationComment(ts.singleElementArray(this.declaration), this.checker)); + }; + SignatureObject.prototype.getJsDocTags = function () { + if (this.jsDocTags === undefined) { + this.jsDocTags = this.declaration ? ts.JsDoc.getJsDocTagsFromDeclarations([this.declaration]) : []; + } + return this.jsDocTags; + }; + return SignatureObject; + }()); + /** + * Returns whether or not the given node has a JSDoc "inheritDoc" tag on it. + * @param node the Node in question. + * @returns `true` if `node` has a JSDoc "inheritDoc" tag on it, otherwise `false`. + */ + function hasJSDocInheritDocTag(node) { + return ts.getJSDocTags(node).some(function (tag) { return tag.tagName.text === "inheritDoc"; }); + } + function getDocumentationComment(declarations, checker) { + if (!declarations) + return ts.emptyArray; + var doc = ts.JsDoc.getJsDocCommentsFromDeclarations(declarations); + if (doc.length === 0 || declarations.some(hasJSDocInheritDocTag)) { + for (var _i = 0, declarations_4 = declarations; _i < declarations_4.length; _i++) { + var declaration = declarations_4[_i]; + var inheritedDocs = findInheritedJSDocComments(declaration, declaration.symbol.name, checker); // TODO: GH#18217 + // TODO: GH#16312 Return a ReadonlyArray, avoid copying inheritedDocs + if (inheritedDocs) + doc = doc.length === 0 ? inheritedDocs.slice() : inheritedDocs.concat(ts.lineBreakPart(), doc); + } + } + return doc; + } + /** + * Attempts to find JSDoc comments for possibly-inherited properties. Checks superclasses then traverses + * implemented interfaces until a symbol is found with the same name and with documentation. + * @param declaration The possibly-inherited declaration to find comments for. + * @param propertyName The name of the possibly-inherited property. + * @param typeChecker A TypeChecker, used to find inherited properties. + * @returns A filled array of documentation comments if any were found, otherwise an empty array. + */ + function findInheritedJSDocComments(declaration, propertyName, typeChecker) { + return ts.firstDefined(declaration.parent ? ts.getAllSuperTypeNodes(declaration.parent) : ts.emptyArray, function (superTypeNode) { + var superType = typeChecker.getTypeAtLocation(superTypeNode); + var baseProperty = superType && typeChecker.getPropertyOfType(superType, propertyName); + var inheritedDocs = baseProperty && baseProperty.getDocumentationComment(typeChecker); + return inheritedDocs && inheritedDocs.length ? inheritedDocs : undefined; + }); + } + var SourceFileObject = /** @class */ (function (_super) { + __extends(SourceFileObject, _super); + function SourceFileObject(kind, pos, end) { + return _super.call(this, kind, pos, end) || this; + } + SourceFileObject.prototype.update = function (newText, textChangeRange) { + return ts.updateSourceFile(this, newText, textChangeRange); + }; + SourceFileObject.prototype.getLineAndCharacterOfPosition = function (position) { + return ts.getLineAndCharacterOfPosition(this, position); + }; + SourceFileObject.prototype.getLineStarts = function () { + return ts.getLineStarts(this); + }; + SourceFileObject.prototype.getPositionOfLineAndCharacter = function (line, character) { + return ts.getPositionOfLineAndCharacter(this, line, character); + }; + SourceFileObject.prototype.getLineEndOfPosition = function (pos) { + var line = this.getLineAndCharacterOfPosition(pos).line; + var lineStarts = this.getLineStarts(); + var lastCharPos; + if (line + 1 >= lineStarts.length) { + lastCharPos = this.getEnd(); + } + if (!lastCharPos) { + lastCharPos = lineStarts[line + 1] - 1; + } + var fullText = this.getFullText(); + // if the new line is "\r\n", we should return the last non-new-line-character position + return fullText[lastCharPos] === "\n" && fullText[lastCharPos - 1] === "\r" ? lastCharPos - 1 : lastCharPos; + }; + SourceFileObject.prototype.getNamedDeclarations = function () { + if (!this.namedDeclarations) { + this.namedDeclarations = this.computeNamedDeclarations(); + } + return this.namedDeclarations; + }; + SourceFileObject.prototype.computeNamedDeclarations = function () { + var result = ts.createMultiMap(); + this.forEachChild(visit); + return result; + function addDeclaration(declaration) { + var name = getDeclarationName(declaration); + if (name) { + result.add(name, declaration); + } + } + function getDeclarations(name) { + var declarations = result.get(name); + if (!declarations) { + result.set(name, declarations = []); + } + return declarations; + } + function getDeclarationName(declaration) { + var name = ts.getNonAssignedNameOfDeclaration(declaration); + return name && (ts.isComputedPropertyName(name) && ts.isPropertyAccessExpression(name.expression) ? name.expression.name.text + : ts.isPropertyName(name) ? ts.getNameFromPropertyName(name) : undefined); + } + function visit(node) { + switch (node.kind) { + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + var functionDeclaration = node; + var declarationName = getDeclarationName(functionDeclaration); + if (declarationName) { + var declarations = getDeclarations(declarationName); + var lastDeclaration = ts.lastOrUndefined(declarations); + // Check whether this declaration belongs to an "overload group". + if (lastDeclaration && functionDeclaration.parent === lastDeclaration.parent && functionDeclaration.symbol === lastDeclaration.symbol) { + // Overwrite the last declaration if it was an overload + // and this one is an implementation. + if (functionDeclaration.body && !lastDeclaration.body) { + declarations[declarations.length - 1] = functionDeclaration; + } + } + else { + declarations.push(functionDeclaration); + } + } + ts.forEachChild(node, visit); + break; + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 241 /* InterfaceDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 243 /* EnumDeclaration */: + case 244 /* ModuleDeclaration */: + case 248 /* ImportEqualsDeclaration */: + case 257 /* ExportSpecifier */: + case 253 /* ImportSpecifier */: + case 250 /* ImportClause */: + case 251 /* NamespaceImport */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 168 /* TypeLiteral */: + addDeclaration(node); + ts.forEachChild(node, visit); + break; + case 151 /* Parameter */: + // Only consider parameter properties + if (!ts.hasModifier(node, 92 /* ParameterPropertyModifier */)) { + break; + } + // falls through + case 237 /* VariableDeclaration */: + case 186 /* BindingElement */: { + var decl = node; + if (ts.isBindingPattern(decl.name)) { + ts.forEachChild(decl.name, visit); + break; + } + if (decl.initializer) { + visit(decl.initializer); + } + } + // falls through + case 278 /* EnumMember */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + addDeclaration(node); + break; + case 255 /* ExportDeclaration */: + // Handle named exports case e.g.: + // export {a, b as B} from "mod"; + if (node.exportClause) { + ts.forEach(node.exportClause.elements, visit); + } + break; + case 249 /* ImportDeclaration */: + var importClause = node.importClause; + if (importClause) { + // Handle default import case e.g.: + // import d from "mod"; + if (importClause.name) { + addDeclaration(importClause.name); + } + // Handle named bindings in imports e.g.: + // import * as NS from "mod"; + // import {a, b as B} from "mod"; + if (importClause.namedBindings) { + if (importClause.namedBindings.kind === 251 /* NamespaceImport */) { + addDeclaration(importClause.namedBindings); + } + else { + ts.forEach(importClause.namedBindings.elements, visit); + } + } + } + break; + case 204 /* BinaryExpression */: + if (ts.getAssignmentDeclarationKind(node) !== 0 /* None */) { + addDeclaration(node); + } + // falls through + default: + ts.forEachChild(node, visit); + } + } + }; + return SourceFileObject; + }(NodeObject)); + var SourceMapSourceObject = /** @class */ (function () { + function SourceMapSourceObject(fileName, text, skipTrivia) { + this.fileName = fileName; + this.text = text; + this.skipTrivia = skipTrivia; + } + SourceMapSourceObject.prototype.getLineAndCharacterOfPosition = function (pos) { + return ts.getLineAndCharacterOfPosition(this, pos); + }; + return SourceMapSourceObject; + }()); + function getServicesObjectAllocator() { + return { + getNodeConstructor: function () { return NodeObject; }, + getTokenConstructor: function () { return TokenObject; }, + getIdentifierConstructor: function () { return IdentifierObject; }, + getSourceFileConstructor: function () { return SourceFileObject; }, + getSymbolConstructor: function () { return SymbolObject; }, + getTypeConstructor: function () { return TypeObject; }, + getSignatureConstructor: function () { return SignatureObject; }, + getSourceMapSourceConstructor: function () { return SourceMapSourceObject; }, + }; + } + function toEditorSettings(optionsAsMap) { + var allPropertiesAreCamelCased = true; + for (var key in optionsAsMap) { + if (ts.hasProperty(optionsAsMap, key) && !isCamelCase(key)) { + allPropertiesAreCamelCased = false; + break; + } + } + if (allPropertiesAreCamelCased) { + return optionsAsMap; + } + var settings = {}; + for (var key in optionsAsMap) { + if (ts.hasProperty(optionsAsMap, key)) { + var newKey = isCamelCase(key) ? key : key.charAt(0).toLowerCase() + key.substr(1); + settings[newKey] = optionsAsMap[key]; + } + } + return settings; + } + ts.toEditorSettings = toEditorSettings; + function isCamelCase(s) { + return !s.length || s.charAt(0) === s.charAt(0).toLowerCase(); + } + function displayPartsToString(displayParts) { + if (displayParts) { + return ts.map(displayParts, function (displayPart) { return displayPart.text; }).join(""); + } + return ""; + } + ts.displayPartsToString = displayPartsToString; + function getDefaultCompilerOptions() { + // Always default to "ScriptTarget.ES5" for the language service + return { + target: 1 /* ES5 */, + jsx: 1 /* Preserve */ + }; + } + ts.getDefaultCompilerOptions = getDefaultCompilerOptions; + function getSupportedCodeFixes() { + return ts.codefix.getSupportedErrorCodes(); + } + ts.getSupportedCodeFixes = getSupportedCodeFixes; + // Cache host information about script Should be refreshed + // at each language service public entry point, since we don't know when + // the set of scripts handled by the host changes. + var HostCache = /** @class */ (function () { + function HostCache(host, getCanonicalFileName) { + this.host = host; + // script id => script index + this.currentDirectory = host.getCurrentDirectory(); + this.fileNameToEntry = ts.createMap(); + // Initialize the list with the root file names + var rootFileNames = host.getScriptFileNames(); + for (var _i = 0, rootFileNames_1 = rootFileNames; _i < rootFileNames_1.length; _i++) { + var fileName = rootFileNames_1[_i]; + this.createEntry(fileName, ts.toPath(fileName, this.currentDirectory, getCanonicalFileName)); + } + // store the compilation settings + this._compilationSettings = host.getCompilationSettings() || getDefaultCompilerOptions(); + } + HostCache.prototype.compilationSettings = function () { + return this._compilationSettings; + }; + HostCache.prototype.getProjectReferences = function () { + return this.host.getProjectReferences && this.host.getProjectReferences(); + }; + HostCache.prototype.createEntry = function (fileName, path) { + var entry; + var scriptSnapshot = this.host.getScriptSnapshot(fileName); + if (scriptSnapshot) { + entry = { + hostFileName: fileName, + version: this.host.getScriptVersion(fileName), + scriptSnapshot: scriptSnapshot, + scriptKind: ts.getScriptKind(fileName, this.host) + }; + } + else { + entry = fileName; + } + this.fileNameToEntry.set(path, entry); + return entry; + }; + HostCache.prototype.getEntryByPath = function (path) { + return this.fileNameToEntry.get(path); + }; + HostCache.prototype.getHostFileInformation = function (path) { + var entry = this.fileNameToEntry.get(path); + return !ts.isString(entry) ? entry : undefined; + }; + HostCache.prototype.getOrCreateEntryByPath = function (fileName, path) { + var info = this.getEntryByPath(path) || this.createEntry(fileName, path); + return ts.isString(info) ? undefined : info; // TODO: GH#18217 + }; + HostCache.prototype.getRootFileNames = function () { + var names = []; + this.fileNameToEntry.forEach(function (entry) { + if (ts.isString(entry)) { + names.push(entry); + } + else { + if (entry.scriptKind !== 6 /* JSON */) { + names.push(entry.hostFileName); + } + } + }); + return names; + }; + HostCache.prototype.getVersion = function (path) { + var file = this.getHostFileInformation(path); + return (file && file.version); // TODO: GH#18217 + }; + HostCache.prototype.getScriptSnapshot = function (path) { + var file = this.getHostFileInformation(path); + return (file && file.scriptSnapshot); // TODO: GH#18217 + }; + return HostCache; + }()); + var SyntaxTreeCache = /** @class */ (function () { + function SyntaxTreeCache(host) { + this.host = host; + } + SyntaxTreeCache.prototype.getCurrentSourceFile = function (fileName) { + var scriptSnapshot = this.host.getScriptSnapshot(fileName); + if (!scriptSnapshot) { + // The host does not know about this file. + throw new Error("Could not find file: '" + fileName + "'."); + } + var scriptKind = ts.getScriptKind(fileName, this.host); + var version = this.host.getScriptVersion(fileName); + var sourceFile; + if (this.currentFileName !== fileName) { + // This is a new file, just parse it + sourceFile = createLanguageServiceSourceFile(fileName, scriptSnapshot, 6 /* Latest */, version, /*setNodeParents*/ true, scriptKind); + } + else if (this.currentFileVersion !== version) { + // This is the same file, just a newer version. Incrementally parse the file. + var editRange = scriptSnapshot.getChangeRange(this.currentFileScriptSnapshot); + sourceFile = updateLanguageServiceSourceFile(this.currentSourceFile, scriptSnapshot, version, editRange); + } + if (sourceFile) { + // All done, ensure state is up to date + this.currentFileVersion = version; + this.currentFileName = fileName; + this.currentFileScriptSnapshot = scriptSnapshot; + this.currentSourceFile = sourceFile; + } + return this.currentSourceFile; + }; + return SyntaxTreeCache; + }()); + function setSourceFileFields(sourceFile, scriptSnapshot, version) { + sourceFile.version = version; + sourceFile.scriptSnapshot = scriptSnapshot; + } + function createLanguageServiceSourceFile(fileName, scriptSnapshot, scriptTarget, version, setNodeParents, scriptKind) { + var sourceFile = ts.createSourceFile(fileName, ts.getSnapshotText(scriptSnapshot), scriptTarget, setNodeParents, scriptKind); + setSourceFileFields(sourceFile, scriptSnapshot, version); + return sourceFile; + } + ts.createLanguageServiceSourceFile = createLanguageServiceSourceFile; + ts.disableIncrementalParsing = false; + function updateLanguageServiceSourceFile(sourceFile, scriptSnapshot, version, textChangeRange, aggressiveChecks) { + // If we were given a text change range, and our version or open-ness changed, then + // incrementally parse this file. + if (textChangeRange) { + if (version !== sourceFile.version) { + // Once incremental parsing is ready, then just call into this function. + if (!ts.disableIncrementalParsing) { + var newText = void 0; + // grab the fragment from the beginning of the original text to the beginning of the span + var prefix = textChangeRange.span.start !== 0 + ? sourceFile.text.substr(0, textChangeRange.span.start) + : ""; + // grab the fragment from the end of the span till the end of the original text + var suffix = ts.textSpanEnd(textChangeRange.span) !== sourceFile.text.length + ? sourceFile.text.substr(ts.textSpanEnd(textChangeRange.span)) + : ""; + if (textChangeRange.newLength === 0) { + // edit was a deletion - just combine prefix and suffix + newText = prefix && suffix ? prefix + suffix : prefix || suffix; + } + else { + // it was actual edit, fetch the fragment of new text that correspond to new span + var changedText = scriptSnapshot.getText(textChangeRange.span.start, textChangeRange.span.start + textChangeRange.newLength); + // combine prefix, changed text and suffix + newText = prefix && suffix + ? prefix + changedText + suffix + : prefix + ? (prefix + changedText) + : (changedText + suffix); + } + var newSourceFile = ts.updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks); + setSourceFileFields(newSourceFile, scriptSnapshot, version); + // after incremental parsing nameTable might not be up-to-date + // drop it so it can be lazily recreated later + newSourceFile.nameTable = undefined; + // dispose all resources held by old script snapshot + if (sourceFile !== newSourceFile && sourceFile.scriptSnapshot) { + if (sourceFile.scriptSnapshot.dispose) { + sourceFile.scriptSnapshot.dispose(); + } + sourceFile.scriptSnapshot = undefined; + } + return newSourceFile; + } + } + } + // Otherwise, just create a new source file. + return createLanguageServiceSourceFile(sourceFile.fileName, scriptSnapshot, sourceFile.languageVersion, version, /*setNodeParents*/ true, sourceFile.scriptKind); + } + ts.updateLanguageServiceSourceFile = updateLanguageServiceSourceFile; + var CancellationTokenObject = /** @class */ (function () { + function CancellationTokenObject(cancellationToken) { + this.cancellationToken = cancellationToken; + } + CancellationTokenObject.prototype.isCancellationRequested = function () { + return !!this.cancellationToken && this.cancellationToken.isCancellationRequested(); + }; + CancellationTokenObject.prototype.throwIfCancellationRequested = function () { + if (this.isCancellationRequested()) { + throw new ts.OperationCanceledException(); + } + }; + return CancellationTokenObject; + }()); + /* @internal */ + /** A cancellation that throttles calls to the host */ + var ThrottledCancellationToken = /** @class */ (function () { + function ThrottledCancellationToken(hostCancellationToken, throttleWaitMilliseconds) { + if (throttleWaitMilliseconds === void 0) { throttleWaitMilliseconds = 20; } + this.hostCancellationToken = hostCancellationToken; + this.throttleWaitMilliseconds = throttleWaitMilliseconds; + // Store when we last tried to cancel. Checking cancellation can be expensive (as we have + // to marshall over to the host layer). So we only bother actually checking once enough + // time has passed. + this.lastCancellationCheckTime = 0; + } + ThrottledCancellationToken.prototype.isCancellationRequested = function () { + var time = ts.timestamp(); + var duration = Math.abs(time - this.lastCancellationCheckTime); + if (duration >= this.throttleWaitMilliseconds) { + // Check no more than once every throttle wait milliseconds + this.lastCancellationCheckTime = time; + return this.hostCancellationToken.isCancellationRequested(); + } + return false; + }; + ThrottledCancellationToken.prototype.throwIfCancellationRequested = function () { + if (this.isCancellationRequested()) { + throw new ts.OperationCanceledException(); + } + }; + return ThrottledCancellationToken; + }()); + ts.ThrottledCancellationToken = ThrottledCancellationToken; + function createLanguageService(host, documentRegistry, syntaxOnly) { + if (documentRegistry === void 0) { documentRegistry = ts.createDocumentRegistry(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames(), host.getCurrentDirectory()); } + if (syntaxOnly === void 0) { syntaxOnly = false; } + var _a; + var syntaxTreeCache = new SyntaxTreeCache(host); + var program; + var lastProjectVersion; + var lastTypesRootVersion = 0; + var cancellationToken = new CancellationTokenObject(host.getCancellationToken && host.getCancellationToken()); + var currentDirectory = host.getCurrentDirectory(); + // Check if the localized messages json is set, otherwise query the host for it + if (!ts.localizedDiagnosticMessages && host.getLocalizedDiagnosticMessages) { + ts.localizedDiagnosticMessages = host.getLocalizedDiagnosticMessages(); + } + function log(message) { + if (host.log) { + host.log(message); + } + } + var useCaseSensitiveFileNames = ts.hostUsesCaseSensitiveFileNames(host); + var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); + var sourceMapper = ts.getSourceMapper(useCaseSensitiveFileNames, currentDirectory, log, host, function () { return program; }); + function getValidSourceFile(fileName) { + var sourceFile = program.getSourceFile(fileName); + if (!sourceFile) { + throw new Error("Could not find file: '" + fileName + "'."); + } + return sourceFile; + } + function synchronizeHostData() { + ts.Debug.assert(!syntaxOnly); + // perform fast check if host supports it + if (host.getProjectVersion) { + var hostProjectVersion = host.getProjectVersion(); + if (hostProjectVersion) { + if (lastProjectVersion === hostProjectVersion && !host.hasChangedAutomaticTypeDirectiveNames) { + return; + } + lastProjectVersion = hostProjectVersion; + } + } + var typeRootsVersion = host.getTypeRootsVersion ? host.getTypeRootsVersion() : 0; + if (lastTypesRootVersion !== typeRootsVersion) { + log("TypeRoots version has changed; provide new program"); + program = undefined; // TODO: GH#18217 + lastTypesRootVersion = typeRootsVersion; + } + // Get a fresh cache of the host information + var hostCache = new HostCache(host, getCanonicalFileName); + var rootFileNames = hostCache.getRootFileNames(); + var hasInvalidatedResolution = host.hasInvalidatedResolution || ts.returnFalse; + var projectReferences = hostCache.getProjectReferences(); + // If the program is already up-to-date, we can reuse it + if (ts.isProgramUptoDate(program, rootFileNames, hostCache.compilationSettings(), function (path) { return hostCache.getVersion(path); }, fileExists, hasInvalidatedResolution, !!host.hasChangedAutomaticTypeDirectiveNames, projectReferences)) { + return; + } + // IMPORTANT - It is critical from this moment onward that we do not check + // cancellation tokens. We are about to mutate source files from a previous program + // instance. If we cancel midway through, we may end up in an inconsistent state where + // the program points to old source files that have been invalidated because of + // incremental parsing. + var newSettings = hostCache.compilationSettings(); + // Now create a new compiler + var compilerHost = { + getSourceFile: getOrCreateSourceFile, + getSourceFileByPath: getOrCreateSourceFileByPath, + getCancellationToken: function () { return cancellationToken; }, + getCanonicalFileName: getCanonicalFileName, + useCaseSensitiveFileNames: function () { return useCaseSensitiveFileNames; }, + getNewLine: function () { return ts.getNewLineCharacter(newSettings, function () { return ts.getNewLineOrDefaultFromHost(host); }); }, + getDefaultLibFileName: function (options) { return host.getDefaultLibFileName(options); }, + writeFile: ts.noop, + getCurrentDirectory: function () { return currentDirectory; }, + fileExists: fileExists, + readFile: function (fileName) { + // stub missing host functionality + var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); + var entry = hostCache && hostCache.getEntryByPath(path); + if (entry) { + return ts.isString(entry) ? undefined : ts.getSnapshotText(entry.scriptSnapshot); + } + return host.readFile && host.readFile(fileName); + }, + realpath: host.realpath && (function (path) { return host.realpath(path); }), + directoryExists: function (directoryName) { + return ts.directoryProbablyExists(directoryName, host); + }, + getDirectories: function (path) { + return host.getDirectories ? host.getDirectories(path) : []; + }, + readDirectory: function (path, extensions, exclude, include, depth) { + ts.Debug.assertDefined(host.readDirectory, "'LanguageServiceHost.readDirectory' must be implemented to correctly process 'projectReferences'"); + return host.readDirectory(path, extensions, exclude, include, depth); + }, + onReleaseOldSourceFile: onReleaseOldSourceFile, + hasInvalidatedResolution: hasInvalidatedResolution, + hasChangedAutomaticTypeDirectiveNames: host.hasChangedAutomaticTypeDirectiveNames + }; + if (host.trace) { + compilerHost.trace = function (message) { return host.trace(message); }; + } + if (host.resolveModuleNames) { + compilerHost.resolveModuleNames = function (moduleNames, containingFile, reusedNames, redirectedReference) { return host.resolveModuleNames(moduleNames, containingFile, reusedNames, redirectedReference); }; + } + if (host.resolveTypeReferenceDirectives) { + compilerHost.resolveTypeReferenceDirectives = function (typeReferenceDirectiveNames, containingFile, redirectedReference) { + return host.resolveTypeReferenceDirectives(typeReferenceDirectiveNames, containingFile, redirectedReference); + }; + } + var documentRegistryBucketKey = documentRegistry.getKeyForCompilationSettings(newSettings); + var options = { + rootNames: rootFileNames, + options: newSettings, + host: compilerHost, + oldProgram: program, + projectReferences: projectReferences + }; + program = ts.createProgram(options); + // hostCache is captured in the closure for 'getOrCreateSourceFile' but it should not be used past this point. + // It needs to be cleared to allow all collected snapshots to be released + hostCache = undefined; + // We reset this cache on structure invalidation so we don't hold on to outdated files for long; however we can't use the `compilerHost` above, + // Because it only functions until `hostCache` is cleared, while we'll potentially need the functionality to lazily read sourcemap files during + // the course of whatever called `synchronizeHostData` + sourceMapper.clearCache(); + // Make sure all the nodes in the program are both bound, and have their parent + // pointers set property. + program.getTypeChecker(); + return; + function fileExists(fileName) { + var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); + var entry = hostCache && hostCache.getEntryByPath(path); + return entry ? + !ts.isString(entry) : + (!!host.fileExists && host.fileExists(fileName)); + } + // Release any files we have acquired in the old program but are + // not part of the new program. + function onReleaseOldSourceFile(oldSourceFile, oldOptions) { + var oldSettingsKey = documentRegistry.getKeyForCompilationSettings(oldOptions); + documentRegistry.releaseDocumentWithKey(oldSourceFile.resolvedPath, oldSettingsKey); + } + function getOrCreateSourceFile(fileName, languageVersion, onError, shouldCreateNewSourceFile) { + return getOrCreateSourceFileByPath(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), languageVersion, onError, shouldCreateNewSourceFile); + } + function getOrCreateSourceFileByPath(fileName, path, _languageVersion, _onError, shouldCreateNewSourceFile) { + ts.Debug.assert(hostCache !== undefined, "getOrCreateSourceFileByPath called after typical CompilerHost lifetime, check the callstack something with a reference to an old host."); + // The program is asking for this file, check first if the host can locate it. + // If the host can not locate the file, then it does not exist. return undefined + // to the program to allow reporting of errors for missing files. + var hostFileInformation = hostCache && hostCache.getOrCreateEntryByPath(fileName, path); + if (!hostFileInformation) { + return undefined; + } + // Check if the language version has changed since we last created a program; if they are the same, + // it is safe to reuse the sourceFiles; if not, then the shape of the AST can change, and the oldSourceFile + // can not be reused. we have to dump all syntax trees and create new ones. + if (!shouldCreateNewSourceFile) { + // Check if the old program had this file already + var oldSourceFile = program && program.getSourceFileByPath(path); + if (oldSourceFile) { + // We already had a source file for this file name. Go to the registry to + // ensure that we get the right up to date version of it. We need this to + // address the following race-condition. Specifically, say we have the following: + // + // LS1 + // \ + // DocumentRegistry + // / + // LS2 + // + // Each LS has a reference to file 'foo.ts' at version 1. LS2 then updates + // it's version of 'foo.ts' to version 2. This will cause LS2 and the + // DocumentRegistry to have version 2 of the document. HOwever, LS1 will + // have version 1. And *importantly* this source file will be *corrupt*. + // The act of creating version 2 of the file irrevocably damages the version + // 1 file. + // + // So, later when we call into LS1, we need to make sure that it doesn't use + // it's source file any more, and instead defers to DocumentRegistry to get + // either version 1, version 2 (or some other version) depending on what the + // host says should be used. + // We do not support the scenario where a host can modify a registered + // file's script kind, i.e. in one project some file is treated as ".ts" + // and in another as ".js" + ts.Debug.assertEqual(hostFileInformation.scriptKind, oldSourceFile.scriptKind, "Registered script kind should match new script kind.", path); + return documentRegistry.updateDocumentWithKey(fileName, path, newSettings, documentRegistryBucketKey, hostFileInformation.scriptSnapshot, hostFileInformation.version, hostFileInformation.scriptKind); + } + // We didn't already have the file. Fall through and acquire it from the registry. + } + // Could not find this file in the old program, create a new SourceFile for it. + return documentRegistry.acquireDocumentWithKey(fileName, path, newSettings, documentRegistryBucketKey, hostFileInformation.scriptSnapshot, hostFileInformation.version, hostFileInformation.scriptKind); + } + } + // TODO: GH#18217 frequently asserted as defined + function getProgram() { + if (syntaxOnly) { + ts.Debug.assert(program === undefined); + return undefined; + } + synchronizeHostData(); + return program; + } + function cleanupSemanticCache() { + program = undefined; // TODO: GH#18217 + } + function dispose() { + if (program) { + ts.forEach(program.getSourceFiles(), function (f) { + return documentRegistry.releaseDocument(f.fileName, program.getCompilerOptions()); + }); + program = undefined; // TODO: GH#18217 + } + host = undefined; + } + /// Diagnostics + function getSyntacticDiagnostics(fileName) { + synchronizeHostData(); + return program.getSyntacticDiagnostics(getValidSourceFile(fileName), cancellationToken).slice(); + } + /** + * getSemanticDiagnostics return array of Diagnostics. If '-d' is not enabled, only report semantic errors + * If '-d' enabled, report both semantic and emitter errors + */ + function getSemanticDiagnostics(fileName) { + synchronizeHostData(); + var targetSourceFile = getValidSourceFile(fileName); + // Only perform the action per file regardless of '-out' flag as LanguageServiceHost is expected to call this function per file. + // Therefore only get diagnostics for given file. + var semanticDiagnostics = program.getSemanticDiagnostics(targetSourceFile, cancellationToken); + if (!ts.getEmitDeclarations(program.getCompilerOptions())) { + return semanticDiagnostics.slice(); + } + // If '-d' is enabled, check for emitter error. One example of emitter error is export class implements non-export interface + var declarationDiagnostics = program.getDeclarationDiagnostics(targetSourceFile, cancellationToken); + return semanticDiagnostics.concat(declarationDiagnostics); + } + function getSuggestionDiagnostics(fileName) { + synchronizeHostData(); + return ts.computeSuggestionDiagnostics(getValidSourceFile(fileName), program, cancellationToken); + } + function getCompilerOptionsDiagnostics() { + synchronizeHostData(); + return program.getOptionsDiagnostics(cancellationToken).concat(program.getGlobalDiagnostics(cancellationToken)); + } + function getCompletionsAtPosition(fileName, position, options) { + if (options === void 0) { options = ts.emptyOptions; } + // Convert from deprecated options names to new names + var fullPreferences = __assign({}, ts.identity(options), { includeCompletionsForModuleExports: options.includeCompletionsForModuleExports || options.includeExternalModuleExports, includeCompletionsWithInsertText: options.includeCompletionsWithInsertText || options.includeInsertTextCompletions }); + synchronizeHostData(); + return ts.Completions.getCompletionsAtPosition(host, program, log, getValidSourceFile(fileName), position, fullPreferences, options.triggerCharacter); + } + function getCompletionEntryDetails(fileName, position, name, formattingOptions, source, preferences) { + if (preferences === void 0) { preferences = ts.emptyOptions; } + synchronizeHostData(); + return ts.Completions.getCompletionEntryDetails(program, log, getValidSourceFile(fileName), position, { name: name, source: source }, host, (formattingOptions && ts.formatting.getFormatContext(formattingOptions)), // TODO: GH#18217 + preferences, cancellationToken); + } + function getCompletionEntrySymbol(fileName, position, name, source) { + synchronizeHostData(); + return ts.Completions.getCompletionEntrySymbol(program, log, getValidSourceFile(fileName), position, { name: name, source: source }); + } + function getQuickInfoAtPosition(fileName, position) { + synchronizeHostData(); + var sourceFile = getValidSourceFile(fileName); + var node = ts.getTouchingPropertyName(sourceFile, position); + if (node === sourceFile) { + // Avoid giving quickInfo for the sourceFile as a whole. + return undefined; + } + var typeChecker = program.getTypeChecker(); + var symbol = getSymbolAtLocationForQuickInfo(node, typeChecker); + if (!symbol || typeChecker.isUnknownSymbol(symbol)) { + var type_2 = shouldGetType(sourceFile, node, position) ? typeChecker.getTypeAtLocation(node) : undefined; + return type_2 && { + kind: "" /* unknown */, + kindModifiers: "" /* none */, + textSpan: ts.createTextSpanFromNode(node, sourceFile), + displayParts: typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { return ts.typeToDisplayParts(typeChecker, type_2, ts.getContainerNode(node)); }), + documentation: type_2.symbol ? type_2.symbol.getDocumentationComment(typeChecker) : undefined, + tags: type_2.symbol ? type_2.symbol.getJsDocTags() : undefined + }; + } + var _a = typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { + return ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, ts.getContainerNode(node), node); + }), symbolKind = _a.symbolKind, displayParts = _a.displayParts, documentation = _a.documentation, tags = _a.tags; + return { + kind: symbolKind, + kindModifiers: ts.SymbolDisplay.getSymbolModifiers(symbol), + textSpan: ts.createTextSpanFromNode(node, sourceFile), + displayParts: displayParts, + documentation: documentation, + tags: tags, + }; + } + function shouldGetType(sourceFile, node, position) { + switch (node.kind) { + case 72 /* Identifier */: + return !ts.isLabelName(node) && !ts.isTagName(node); + case 189 /* PropertyAccessExpression */: + case 148 /* QualifiedName */: + // Don't return quickInfo if inside the comment in `a/**/.b` + return !ts.isInComment(sourceFile, position); + case 100 /* ThisKeyword */: + case 178 /* ThisType */: + case 98 /* SuperKeyword */: + return true; + default: + return false; + } + } + /// Goto definition + function getDefinitionAtPosition(fileName, position) { + synchronizeHostData(); + return ts.GoToDefinition.getDefinitionAtPosition(program, getValidSourceFile(fileName), position); + } + function getDefinitionAndBoundSpan(fileName, position) { + synchronizeHostData(); + return ts.GoToDefinition.getDefinitionAndBoundSpan(program, getValidSourceFile(fileName), position); + } + function getTypeDefinitionAtPosition(fileName, position) { + synchronizeHostData(); + return ts.GoToDefinition.getTypeDefinitionAtPosition(program.getTypeChecker(), getValidSourceFile(fileName), position); + } + /// Goto implementation + function getImplementationAtPosition(fileName, position) { + synchronizeHostData(); + return ts.FindAllReferences.getImplementationsAtPosition(program, cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position); + } + /// References and Occurrences + function getOccurrencesAtPosition(fileName, position) { + return ts.flatMap(getDocumentHighlights(fileName, position, [fileName]), function (entry) { return entry.highlightSpans.map(function (highlightSpan) { return ({ + fileName: entry.fileName, + textSpan: highlightSpan.textSpan, + isWriteAccess: highlightSpan.kind === "writtenReference" /* writtenReference */, + isDefinition: false, + isInString: highlightSpan.isInString, + }); }); }); + } + function getDocumentHighlights(fileName, position, filesToSearch) { + var normalizedFileName = ts.normalizePath(fileName); + ts.Debug.assert(filesToSearch.some(function (f) { return ts.normalizePath(f) === normalizedFileName; })); + synchronizeHostData(); + var sourceFilesToSearch = filesToSearch.map(getValidSourceFile); + var sourceFile = getValidSourceFile(fileName); + return ts.DocumentHighlights.getDocumentHighlights(program, cancellationToken, sourceFile, position, sourceFilesToSearch); + } + function findRenameLocations(fileName, position, findInStrings, findInComments) { + synchronizeHostData(); + var sourceFile = getValidSourceFile(fileName); + var node = ts.getTouchingPropertyName(sourceFile, position); + if (ts.isIdentifier(node) && (ts.isJsxOpeningElement(node.parent) || ts.isJsxClosingElement(node.parent)) && ts.isIntrinsicJsxName(node.escapedText)) { + var _a = node.parent.parent, openingElement = _a.openingElement, closingElement = _a.closingElement; + return [openingElement, closingElement].map(function (node) { + return ({ fileName: sourceFile.fileName, textSpan: ts.createTextSpanFromNode(node.tagName, sourceFile) }); + }); + } + else { + return getReferencesWorker(node, position, { findInStrings: findInStrings, findInComments: findInComments, isForRename: true }, ts.FindAllReferences.toRenameLocation); + } + } + function getReferencesAtPosition(fileName, position) { + synchronizeHostData(); + return getReferencesWorker(ts.getTouchingPropertyName(getValidSourceFile(fileName), position), position, {}, ts.FindAllReferences.toReferenceEntry); + } + function getReferencesWorker(node, position, options, cb) { + synchronizeHostData(); + // Exclude default library when renaming as commonly user don't want to change that file. + var sourceFiles = options && options.isForRename + ? program.getSourceFiles().filter(function (sourceFile) { return !program.isSourceFileDefaultLibrary(sourceFile); }) + : program.getSourceFiles(); + return ts.FindAllReferences.findReferenceOrRenameEntries(program, cancellationToken, sourceFiles, node, position, options, cb); + } + function findReferences(fileName, position) { + synchronizeHostData(); + return ts.FindAllReferences.findReferencedSymbols(program, cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position); + } + function getNavigateToItems(searchValue, maxResultCount, fileName, excludeDtsFiles) { + if (excludeDtsFiles === void 0) { excludeDtsFiles = false; } + synchronizeHostData(); + var sourceFiles = fileName ? [getValidSourceFile(fileName)] : program.getSourceFiles(); + return ts.NavigateTo.getNavigateToItems(sourceFiles, program.getTypeChecker(), cancellationToken, searchValue, maxResultCount, excludeDtsFiles); + } + function getEmitOutput(fileName, emitOnlyDtsFiles) { + if (emitOnlyDtsFiles === void 0) { emitOnlyDtsFiles = false; } + synchronizeHostData(); + var sourceFile = getValidSourceFile(fileName); + var customTransformers = host.getCustomTransformers && host.getCustomTransformers(); + return ts.getFileEmitOutput(program, sourceFile, emitOnlyDtsFiles, cancellationToken, customTransformers); + } + // Signature help + /** + * This is a semantic operation. + */ + function getSignatureHelpItems(fileName, position, _a) { + var triggerReason = (_a === void 0 ? ts.emptyOptions : _a).triggerReason; + synchronizeHostData(); + var sourceFile = getValidSourceFile(fileName); + return ts.SignatureHelp.getSignatureHelpItems(program, sourceFile, position, triggerReason, cancellationToken); + } + /// Syntactic features + function getNonBoundSourceFile(fileName) { + return syntaxTreeCache.getCurrentSourceFile(fileName); + } + function getNameOrDottedNameSpan(fileName, startPos, _endPos) { + var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); + // Get node at the location + var node = ts.getTouchingPropertyName(sourceFile, startPos); + if (node === sourceFile) { + return undefined; + } + switch (node.kind) { + case 189 /* PropertyAccessExpression */: + case 148 /* QualifiedName */: + case 10 /* StringLiteral */: + case 87 /* FalseKeyword */: + case 102 /* TrueKeyword */: + case 96 /* NullKeyword */: + case 98 /* SuperKeyword */: + case 100 /* ThisKeyword */: + case 178 /* ThisType */: + case 72 /* Identifier */: + break; + // Cant create the text span + default: + return undefined; + } + var nodeForStartPos = node; + while (true) { + if (ts.isRightSideOfPropertyAccess(nodeForStartPos) || ts.isRightSideOfQualifiedName(nodeForStartPos)) { + // If on the span is in right side of the the property or qualified name, return the span from the qualified name pos to end of this node + nodeForStartPos = nodeForStartPos.parent; + } + else if (ts.isNameOfModuleDeclaration(nodeForStartPos)) { + // If this is name of a module declarations, check if this is right side of dotted module name + // If parent of the module declaration which is parent of this node is module declaration and its body is the module declaration that this node is name of + // Then this name is name from dotted module + if (nodeForStartPos.parent.parent.kind === 244 /* ModuleDeclaration */ && + nodeForStartPos.parent.parent.body === nodeForStartPos.parent) { + // Use parent module declarations name for start pos + nodeForStartPos = nodeForStartPos.parent.parent.name; + } + else { + // We have to use this name for start pos + break; + } + } + else { + // Is not a member expression so we have found the node for start pos + break; + } + } + return ts.createTextSpanFromBounds(nodeForStartPos.getStart(), node.getEnd()); + } + function getBreakpointStatementAtPosition(fileName, position) { + // doesn't use compiler - no need to synchronize with host + var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); + return ts.BreakpointResolver.spanInSourceFileAtLocation(sourceFile, position); + } + function getNavigationBarItems(fileName) { + return ts.NavigationBar.getNavigationBarItems(syntaxTreeCache.getCurrentSourceFile(fileName), cancellationToken); + } + function getNavigationTree(fileName) { + return ts.NavigationBar.getNavigationTree(syntaxTreeCache.getCurrentSourceFile(fileName), cancellationToken); + } + function isTsOrTsxFile(fileName) { + var kind = ts.getScriptKind(fileName, host); + return kind === 3 /* TS */ || kind === 4 /* TSX */; + } + function getSemanticClassifications(fileName, span) { + if (!isTsOrTsxFile(fileName)) { + // do not run semantic classification on non-ts-or-tsx files + return []; + } + synchronizeHostData(); + return ts.getSemanticClassifications(program.getTypeChecker(), cancellationToken, getValidSourceFile(fileName), program.getClassifiableNames(), span); + } + function getEncodedSemanticClassifications(fileName, span) { + if (!isTsOrTsxFile(fileName)) { + // do not run semantic classification on non-ts-or-tsx files + return { spans: [], endOfLineState: 0 /* None */ }; + } + synchronizeHostData(); + return ts.getEncodedSemanticClassifications(program.getTypeChecker(), cancellationToken, getValidSourceFile(fileName), program.getClassifiableNames(), span); + } + function getSyntacticClassifications(fileName, span) { + // doesn't use compiler - no need to synchronize with host + return ts.getSyntacticClassifications(cancellationToken, syntaxTreeCache.getCurrentSourceFile(fileName), span); + } + function getEncodedSyntacticClassifications(fileName, span) { + // doesn't use compiler - no need to synchronize with host + return ts.getEncodedSyntacticClassifications(cancellationToken, syntaxTreeCache.getCurrentSourceFile(fileName), span); + } + function getOutliningSpans(fileName) { + // doesn't use compiler - no need to synchronize with host + var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); + return ts.OutliningElementsCollector.collectElements(sourceFile, cancellationToken); + } + var braceMatching = ts.createMapFromTemplate((_a = {}, + _a[18 /* OpenBraceToken */] = 19 /* CloseBraceToken */, + _a[20 /* OpenParenToken */] = 21 /* CloseParenToken */, + _a[22 /* OpenBracketToken */] = 23 /* CloseBracketToken */, + _a[30 /* GreaterThanToken */] = 28 /* LessThanToken */, + _a)); + braceMatching.forEach(function (value, key) { return braceMatching.set(value.toString(), Number(key)); }); + function getBraceMatchingAtPosition(fileName, position) { + var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); + var token = ts.getTouchingToken(sourceFile, position); + var matchKind = token.getStart(sourceFile) === position ? braceMatching.get(token.kind.toString()) : undefined; + var match = matchKind && ts.findChildOfKind(token.parent, matchKind, sourceFile); + // We want to order the braces when we return the result. + return match ? [ts.createTextSpanFromNode(token, sourceFile), ts.createTextSpanFromNode(match, sourceFile)].sort(function (a, b) { return a.start - b.start; }) : ts.emptyArray; + } + function getIndentationAtPosition(fileName, position, editorOptions) { + var start = ts.timestamp(); + var settings = toEditorSettings(editorOptions); + var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); + log("getIndentationAtPosition: getCurrentSourceFile: " + (ts.timestamp() - start)); + start = ts.timestamp(); + var result = ts.formatting.SmartIndenter.getIndentation(position, sourceFile, settings); + log("getIndentationAtPosition: computeIndentation : " + (ts.timestamp() - start)); + return result; + } + function getFormattingEditsForRange(fileName, start, end, options) { + var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); + return ts.formatting.formatSelection(start, end, sourceFile, ts.formatting.getFormatContext(toEditorSettings(options))); + } + function getFormattingEditsForDocument(fileName, options) { + return ts.formatting.formatDocument(syntaxTreeCache.getCurrentSourceFile(fileName), ts.formatting.getFormatContext(toEditorSettings(options))); + } + function getFormattingEditsAfterKeystroke(fileName, position, key, options) { + var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); + var formatContext = ts.formatting.getFormatContext(toEditorSettings(options)); + if (!ts.isInComment(sourceFile, position)) { + switch (key) { + case "{": + return ts.formatting.formatOnOpeningCurly(position, sourceFile, formatContext); + case "}": + return ts.formatting.formatOnClosingCurly(position, sourceFile, formatContext); + case ";": + return ts.formatting.formatOnSemicolon(position, sourceFile, formatContext); + case "\n": + return ts.formatting.formatOnEnter(position, sourceFile, formatContext); + } + } + return []; + } + function getCodeFixesAtPosition(fileName, start, end, errorCodes, formatOptions, preferences) { + if (preferences === void 0) { preferences = ts.emptyOptions; } + synchronizeHostData(); + var sourceFile = getValidSourceFile(fileName); + var span = ts.createTextSpanFromBounds(start, end); + var formatContext = ts.formatting.getFormatContext(formatOptions); + return ts.flatMap(ts.deduplicate(errorCodes, ts.equateValues, ts.compareValues), function (errorCode) { + cancellationToken.throwIfCancellationRequested(); + return ts.codefix.getFixes({ errorCode: errorCode, sourceFile: sourceFile, span: span, program: program, host: host, cancellationToken: cancellationToken, formatContext: formatContext, preferences: preferences }); + }); + } + function getCombinedCodeFix(scope, fixId, formatOptions, preferences) { + if (preferences === void 0) { preferences = ts.emptyOptions; } + synchronizeHostData(); + ts.Debug.assert(scope.type === "file"); + var sourceFile = getValidSourceFile(scope.fileName); + var formatContext = ts.formatting.getFormatContext(formatOptions); + return ts.codefix.getAllFixes({ fixId: fixId, sourceFile: sourceFile, program: program, host: host, cancellationToken: cancellationToken, formatContext: formatContext, preferences: preferences }); + } + function organizeImports(scope, formatOptions, preferences) { + if (preferences === void 0) { preferences = ts.emptyOptions; } + synchronizeHostData(); + ts.Debug.assert(scope.type === "file"); + var sourceFile = getValidSourceFile(scope.fileName); + var formatContext = ts.formatting.getFormatContext(formatOptions); + return ts.OrganizeImports.organizeImports(sourceFile, formatContext, host, program, preferences); + } + function getEditsForFileRename(oldFilePath, newFilePath, formatOptions, preferences) { + if (preferences === void 0) { preferences = ts.emptyOptions; } + return ts.getEditsForFileRename(getProgram(), oldFilePath, newFilePath, host, ts.formatting.getFormatContext(formatOptions), preferences, sourceMapper); + } + function applyCodeActionCommand(fileName, actionOrFormatSettingsOrUndefined) { + var action = typeof fileName === "string" ? actionOrFormatSettingsOrUndefined : fileName; + var formatSettings = typeof fileName !== "string" ? actionOrFormatSettingsOrUndefined : undefined; + return ts.isArray(action) ? Promise.all(action.map(function (a) { return applySingleCodeActionCommand(a, formatSettings); })) : applySingleCodeActionCommand(action, formatSettings); + } + function applySingleCodeActionCommand(action, formatSettings) { + var getPath = function (path) { return ts.toPath(path, currentDirectory, getCanonicalFileName); }; + switch (action.type) { + case "install package": + return host.installPackage + ? host.installPackage({ fileName: getPath(action.file), packageName: action.packageName }) + : Promise.reject("Host does not implement `installPackage`"); + case "generate types": { + var fileToGenerateTypesFor = action.fileToGenerateTypesFor, outputFileName_1 = action.outputFileName; + if (!host.inspectValue) + return Promise.reject("Host does not implement `installPackage`"); + var valueInfoPromise = host.inspectValue({ fileNameToRequire: fileToGenerateTypesFor }); + return valueInfoPromise.then(function (valueInfo) { + var fullOut = getPath(outputFileName_1); + host.writeFile(fullOut, ts.valueInfoToDeclarationFileText(valueInfo, formatSettings || ts.testFormatSettings)); // TODO: GH#18217 + return { successMessage: "Wrote types to '" + fullOut + "'" }; + }); + } + default: + return ts.Debug.assertNever(action); + } + } + function getDocCommentTemplateAtPosition(fileName, position) { + return ts.JsDoc.getDocCommentTemplateAtPosition(ts.getNewLineOrDefaultFromHost(host), syntaxTreeCache.getCurrentSourceFile(fileName), position); + } + function isValidBraceCompletionAtPosition(fileName, position, openingBrace) { + // '<' is currently not supported, figuring out if we're in a Generic Type vs. a comparison is too + // expensive to do during typing scenarios + // i.e. whether we're dealing with: + // var x = new foo<| ( with class foo{} ) + // or + // var y = 3 <| + if (openingBrace === 60 /* lessThan */) { + return false; + } + var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); + // Check if in a context where we don't want to perform any insertion + if (ts.isInString(sourceFile, position)) { + return false; + } + if (ts.isInsideJsxElementOrAttribute(sourceFile, position)) { + return openingBrace === 123 /* openBrace */; + } + if (ts.isInTemplateString(sourceFile, position)) { + return false; + } + switch (openingBrace) { + case 39 /* singleQuote */: + case 34 /* doubleQuote */: + case 96 /* backtick */: + return !ts.isInComment(sourceFile, position); + } + return true; + } + function getJsxClosingTagAtPosition(fileName, position) { + var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); + var token = ts.findPrecedingToken(position, sourceFile); + if (!token) + return undefined; + var element = token.kind === 30 /* GreaterThanToken */ && ts.isJsxOpeningElement(token.parent) ? token.parent.parent + : ts.isJsxText(token) ? token.parent : undefined; + if (element && isUnclosedTag(element)) { + return { newText: "" }; + } + } + function isUnclosedTag(_a) { + var openingElement = _a.openingElement, closingElement = _a.closingElement, parent = _a.parent; + return !ts.tagNamesAreEquivalent(openingElement.tagName, closingElement.tagName) || + ts.isJsxElement(parent) && ts.tagNamesAreEquivalent(openingElement.tagName, parent.openingElement.tagName) && isUnclosedTag(parent); + } + function getSpanOfEnclosingComment(fileName, position, onlyMultiLine) { + var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); + var range = ts.formatting.getRangeOfEnclosingComment(sourceFile, position); + return range && (!onlyMultiLine || range.kind === 3 /* MultiLineCommentTrivia */) ? ts.createTextSpanFromRange(range) : undefined; + } + function getTodoComments(fileName, descriptors) { + // Note: while getting todo comments seems like a syntactic operation, we actually + // treat it as a semantic operation here. This is because we expect our host to call + // this on every single file. If we treat this syntactically, then that will cause + // us to populate and throw away the tree in our syntax tree cache for each file. By + // treating this as a semantic operation, we can access any tree without throwing + // anything away. + synchronizeHostData(); + var sourceFile = getValidSourceFile(fileName); + cancellationToken.throwIfCancellationRequested(); + var fileContents = sourceFile.text; + var result = []; + // Exclude node_modules files as we don't want to show the todos of external libraries. + if (descriptors.length > 0 && !isNodeModulesFile(sourceFile.fileName)) { + var regExp = getTodoCommentsRegExp(); + var matchArray = void 0; + while (matchArray = regExp.exec(fileContents)) { + cancellationToken.throwIfCancellationRequested(); + // If we got a match, here is what the match array will look like. Say the source text is: + // + // " // hack 1" + // + // The result array with the regexp: will be: + // + // ["// hack 1", "// ", "hack 1", undefined, "hack"] + // + // Here are the relevant capture groups: + // 0) The full match for the entire regexp. + // 1) The preamble to the message portion. + // 2) The message portion. + // 3...N) The descriptor that was matched - by index. 'undefined' for each + // descriptor that didn't match. an actual value if it did match. + // + // i.e. 'undefined' in position 3 above means TODO(jason) didn't match. + // "hack" in position 4 means HACK did match. + var firstDescriptorCaptureIndex = 3; + ts.Debug.assert(matchArray.length === descriptors.length + firstDescriptorCaptureIndex); + var preamble = matchArray[1]; + var matchPosition = matchArray.index + preamble.length; + // OK, we have found a match in the file. This is only an acceptable match if + // it is contained within a comment. + if (!ts.isInComment(sourceFile, matchPosition)) { + continue; + } + var descriptor = void 0; + for (var i = 0; i < descriptors.length; i++) { + if (matchArray[i + firstDescriptorCaptureIndex]) { + descriptor = descriptors[i]; + } + } + if (descriptor === undefined) + return ts.Debug.fail(); + // We don't want to match something like 'TODOBY', so we make sure a non + // letter/digit follows the match. + if (isLetterOrDigit(fileContents.charCodeAt(matchPosition + descriptor.text.length))) { + continue; + } + var message = matchArray[2]; + result.push({ descriptor: descriptor, message: message, position: matchPosition }); + } + } + return result; + function escapeRegExp(str) { + return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"); + } + function getTodoCommentsRegExp() { + // NOTE: `?:` means 'non-capture group'. It allows us to have groups without having to + // filter them out later in the final result array. + // TODO comments can appear in one of the following forms: + // + // 1) // TODO or /////////// TODO + // + // 2) /* TODO or /********** TODO + // + // 3) /* + // * TODO + // */ + // + // The following three regexps are used to match the start of the text up to the TODO + // comment portion. + var singleLineCommentStart = /(?:\/\/+\s*)/.source; + var multiLineCommentStart = /(?:\/\*+\s*)/.source; + var anyNumberOfSpacesAndAsterisksAtStartOfLine = /(?:^(?:\s|\*)*)/.source; + // Match any of the above three TODO comment start regexps. + // Note that the outermost group *is* a capture group. We want to capture the preamble + // so that we can determine the starting position of the TODO comment match. + var preamble = "(" + anyNumberOfSpacesAndAsterisksAtStartOfLine + "|" + singleLineCommentStart + "|" + multiLineCommentStart + ")"; + // Takes the descriptors and forms a regexp that matches them as if they were literals. + // For example, if the descriptors are "TODO(jason)" and "HACK", then this will be: + // + // (?:(TODO\(jason\))|(HACK)) + // + // Note that the outermost group is *not* a capture group, but the innermost groups + // *are* capture groups. By capturing the inner literals we can determine after + // matching which descriptor we are dealing with. + var literals = "(?:" + ts.map(descriptors, function (d) { return "(" + escapeRegExp(d.text) + ")"; }).join("|") + ")"; + // After matching a descriptor literal, the following regexp matches the rest of the + // text up to the end of the line (or */). + var endOfLineOrEndOfComment = /(?:$|\*\/)/.source; + var messageRemainder = /(?:.*?)/.source; + // This is the portion of the match we'll return as part of the TODO comment result. We + // match the literal portion up to the end of the line or end of comment. + var messagePortion = "(" + literals + messageRemainder + ")"; + var regExpString = preamble + messagePortion + endOfLineOrEndOfComment; + // The final regexp will look like this: + // /((?:\/\/+\s*)|(?:\/\*+\s*)|(?:^(?:\s|\*)*))((?:(TODO\(jason\))|(HACK))(?:.*?))(?:$|\*\/)/gim + // The flags of the regexp are important here. + // 'g' is so that we are doing a global search and can find matches several times + // in the input. + // + // 'i' is for case insensitivity (We do this to match C# TODO comment code). + // + // 'm' is so we can find matches in a multi-line input. + return new RegExp(regExpString, "gim"); + } + function isLetterOrDigit(char) { + return (char >= 97 /* a */ && char <= 122 /* z */) || + (char >= 65 /* A */ && char <= 90 /* Z */) || + (char >= 48 /* _0 */ && char <= 57 /* _9 */); + } + function isNodeModulesFile(path) { + return ts.stringContains(path, "/node_modules/"); + } + } + function getRenameInfo(fileName, position) { + synchronizeHostData(); + return ts.Rename.getRenameInfo(program, getValidSourceFile(fileName), position); + } + function getRefactorContext(file, positionOrRange, preferences, formatOptions) { + var _a = typeof positionOrRange === "number" ? [positionOrRange, undefined] : [positionOrRange.pos, positionOrRange.end], startPosition = _a[0], endPosition = _a[1]; + return { + file: file, + startPosition: startPosition, + endPosition: endPosition, + program: getProgram(), + host: host, + formatContext: ts.formatting.getFormatContext(formatOptions), + cancellationToken: cancellationToken, + preferences: preferences, + }; + } + function getApplicableRefactors(fileName, positionOrRange, preferences) { + if (preferences === void 0) { preferences = ts.emptyOptions; } + synchronizeHostData(); + var file = getValidSourceFile(fileName); + return ts.refactor.getApplicableRefactors(getRefactorContext(file, positionOrRange, preferences)); + } + function getEditsForRefactor(fileName, formatOptions, positionOrRange, refactorName, actionName, preferences) { + if (preferences === void 0) { preferences = ts.emptyOptions; } + synchronizeHostData(); + var file = getValidSourceFile(fileName); + return ts.refactor.getEditsForRefactor(getRefactorContext(file, positionOrRange, preferences, formatOptions), refactorName, actionName); + } + return { + dispose: dispose, + cleanupSemanticCache: cleanupSemanticCache, + getSyntacticDiagnostics: getSyntacticDiagnostics, + getSemanticDiagnostics: getSemanticDiagnostics, + getSuggestionDiagnostics: getSuggestionDiagnostics, + getCompilerOptionsDiagnostics: getCompilerOptionsDiagnostics, + getSyntacticClassifications: getSyntacticClassifications, + getSemanticClassifications: getSemanticClassifications, + getEncodedSyntacticClassifications: getEncodedSyntacticClassifications, + getEncodedSemanticClassifications: getEncodedSemanticClassifications, + getCompletionsAtPosition: getCompletionsAtPosition, + getCompletionEntryDetails: getCompletionEntryDetails, + getCompletionEntrySymbol: getCompletionEntrySymbol, + getSignatureHelpItems: getSignatureHelpItems, + getQuickInfoAtPosition: getQuickInfoAtPosition, + getDefinitionAtPosition: getDefinitionAtPosition, + getDefinitionAndBoundSpan: getDefinitionAndBoundSpan, + getImplementationAtPosition: getImplementationAtPosition, + getTypeDefinitionAtPosition: getTypeDefinitionAtPosition, + getReferencesAtPosition: getReferencesAtPosition, + findReferences: findReferences, + getOccurrencesAtPosition: getOccurrencesAtPosition, + getDocumentHighlights: getDocumentHighlights, + getNameOrDottedNameSpan: getNameOrDottedNameSpan, + getBreakpointStatementAtPosition: getBreakpointStatementAtPosition, + getNavigateToItems: getNavigateToItems, + getRenameInfo: getRenameInfo, + findRenameLocations: findRenameLocations, + getNavigationBarItems: getNavigationBarItems, + getNavigationTree: getNavigationTree, + getOutliningSpans: getOutliningSpans, + getTodoComments: getTodoComments, + getBraceMatchingAtPosition: getBraceMatchingAtPosition, + getIndentationAtPosition: getIndentationAtPosition, + getFormattingEditsForRange: getFormattingEditsForRange, + getFormattingEditsForDocument: getFormattingEditsForDocument, + getFormattingEditsAfterKeystroke: getFormattingEditsAfterKeystroke, + getDocCommentTemplateAtPosition: getDocCommentTemplateAtPosition, + isValidBraceCompletionAtPosition: isValidBraceCompletionAtPosition, + getJsxClosingTagAtPosition: getJsxClosingTagAtPosition, + getSpanOfEnclosingComment: getSpanOfEnclosingComment, + getCodeFixesAtPosition: getCodeFixesAtPosition, + getCombinedCodeFix: getCombinedCodeFix, + applyCodeActionCommand: applyCodeActionCommand, + organizeImports: organizeImports, + getEditsForFileRename: getEditsForFileRename, + getEmitOutput: getEmitOutput, + getNonBoundSourceFile: getNonBoundSourceFile, + getProgram: getProgram, + getApplicableRefactors: getApplicableRefactors, + getEditsForRefactor: getEditsForRefactor, + toLineColumnOffset: sourceMapper.toLineColumnOffset, + getSourceMapper: function () { return sourceMapper; }, + }; + } + ts.createLanguageService = createLanguageService; + /* @internal */ + /** Names in the name table are escaped, so an identifier `__foo` will have a name table entry `___foo`. */ + function getNameTable(sourceFile) { + if (!sourceFile.nameTable) { + initializeNameTable(sourceFile); + } + return sourceFile.nameTable; // TODO: GH#18217 + } + ts.getNameTable = getNameTable; + function initializeNameTable(sourceFile) { + var nameTable = sourceFile.nameTable = ts.createUnderscoreEscapedMap(); + sourceFile.forEachChild(function walk(node) { + if (ts.isIdentifier(node) && !ts.isTagName(node) && node.escapedText || ts.isStringOrNumericLiteralLike(node) && literalIsName(node)) { + var text = ts.getEscapedTextOfIdentifierOrLiteral(node); + nameTable.set(text, nameTable.get(text) === undefined ? node.pos : -1); + } + ts.forEachChild(node, walk); + if (ts.hasJSDocNodes(node)) { + for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { + var jsDoc = _a[_i]; + ts.forEachChild(jsDoc, walk); + } + } + }); + } + /** + * We want to store any numbers/strings if they were a name that could be + * related to a declaration. So, if we have 'import x = require("something")' + * then we want 'something' to be in the name table. Similarly, if we have + * "a['propname']" then we want to store "propname" in the name table. + */ + function literalIsName(node) { + return ts.isDeclarationName(node) || + node.parent.kind === 259 /* ExternalModuleReference */ || + isArgumentOfElementAccessExpression(node) || + ts.isLiteralComputedPropertyDeclarationName(node); + } + /** + * Returns the containing object literal property declaration given a possible name node, e.g. "a" in x = { "a": 1 } + */ + /* @internal */ + function getContainingObjectLiteralElement(node) { + var element = getContainingObjectLiteralElementWorker(node); + return element && (ts.isObjectLiteralExpression(element.parent) || ts.isJsxAttributes(element.parent)) ? element : undefined; + } + ts.getContainingObjectLiteralElement = getContainingObjectLiteralElement; + function getContainingObjectLiteralElementWorker(node) { + switch (node.kind) { + case 10 /* StringLiteral */: + case 8 /* NumericLiteral */: + if (node.parent.kind === 149 /* ComputedPropertyName */) { + return ts.isObjectLiteralElement(node.parent.parent) ? node.parent.parent : undefined; + } + // falls through + case 72 /* Identifier */: + return ts.isObjectLiteralElement(node.parent) && + (node.parent.parent.kind === 188 /* ObjectLiteralExpression */ || node.parent.parent.kind === 268 /* JsxAttributes */) && + node.parent.name === node ? node.parent : undefined; + } + return undefined; + } + function getSymbolAtLocationForQuickInfo(node, checker) { + var object = getContainingObjectLiteralElement(node); + if (object) { + var contextualType = checker.getContextualType(object.parent); + var properties = contextualType && getPropertySymbolsFromContextualType(object, checker, contextualType, /*unionSymbolOk*/ false); + if (properties && properties.length === 1) { + return ts.first(properties); + } + } + return checker.getSymbolAtLocation(node); + } + /** Gets all symbols for one property. Does not get symbols for every property. */ + /* @internal */ + function getPropertySymbolsFromContextualType(node, checker, contextualType, unionSymbolOk) { + var name = ts.getNameFromPropertyName(node.name); + if (!name) + return ts.emptyArray; + if (!contextualType.isUnion()) { + var symbol = contextualType.getProperty(name); + return symbol ? [symbol] : ts.emptyArray; + } + var discriminatedPropertySymbols = ts.mapDefined(contextualType.types, function (t) { return ts.isObjectLiteralExpression(node.parent) && checker.isTypeInvalidDueToUnionDiscriminant(t, node.parent) ? undefined : t.getProperty(name); }); + if (unionSymbolOk && (discriminatedPropertySymbols.length === 0 || discriminatedPropertySymbols.length === contextualType.types.length)) { + var symbol = contextualType.getProperty(name); + if (symbol) + return [symbol]; + } + if (discriminatedPropertySymbols.length === 0) { + // Bad discriminant -- do again without discriminating + return ts.mapDefined(contextualType.types, function (t) { return t.getProperty(name); }); + } + return discriminatedPropertySymbols; + } + ts.getPropertySymbolsFromContextualType = getPropertySymbolsFromContextualType; + function isArgumentOfElementAccessExpression(node) { + return node && + node.parent && + node.parent.kind === 190 /* ElementAccessExpression */ && + node.parent.argumentExpression === node; + } + /** + * Get the path of the default library files (lib.d.ts) as distributed with the typescript + * node package. + * The functionality is not supported if the ts module is consumed outside of a node module. + */ + function getDefaultLibFilePath(options) { + // Check __dirname is defined and that we are on a node.js system. + if (typeof __dirname !== "undefined") { + return __dirname + ts.directorySeparator + ts.getDefaultLibFileName(options); + } + throw new Error("getDefaultLibFilePath is only supported when consumed as a node module. "); + } + ts.getDefaultLibFilePath = getDefaultLibFilePath; + ts.objectAllocator = getServicesObjectAllocator(); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var BreakpointResolver; + (function (BreakpointResolver) { + /** + * Get the breakpoint span in given sourceFile + */ + function spanInSourceFileAtLocation(sourceFile, position) { + // Cannot set breakpoint in dts file + if (sourceFile.isDeclarationFile) { + return undefined; + } + var tokenAtLocation = ts.getTokenAtPosition(sourceFile, position); + var lineOfPosition = sourceFile.getLineAndCharacterOfPosition(position).line; + if (sourceFile.getLineAndCharacterOfPosition(tokenAtLocation.getStart(sourceFile)).line > lineOfPosition) { + // Get previous token if the token is returned starts on new line + // eg: let x =10; |--- cursor is here + // let y = 10; + // token at position will return let keyword on second line as the token but we would like to use + // token on same line if trailing trivia (comments or white spaces on same line) part of the last token on that line + var preceding = ts.findPrecedingToken(tokenAtLocation.pos, sourceFile); + // It's a blank line + if (!preceding || sourceFile.getLineAndCharacterOfPosition(preceding.getEnd()).line !== lineOfPosition) { + return undefined; + } + tokenAtLocation = preceding; + } + // Cannot set breakpoint in ambient declarations + if (tokenAtLocation.flags & 4194304 /* Ambient */) { + return undefined; + } + // Get the span in the node based on its syntax + return spanInNode(tokenAtLocation); + function textSpan(startNode, endNode) { + var start = startNode.decorators ? + ts.skipTrivia(sourceFile.text, startNode.decorators.end) : + startNode.getStart(sourceFile); + return ts.createTextSpanFromBounds(start, (endNode || startNode).getEnd()); + } + function textSpanEndingAtNextToken(startNode, previousTokenToFindNextEndToken) { + return textSpan(startNode, ts.findNextToken(previousTokenToFindNextEndToken, previousTokenToFindNextEndToken.parent, sourceFile)); + } + function spanInNodeIfStartsOnSameLine(node, otherwiseOnNode) { + if (node && lineOfPosition === sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile)).line) { + return spanInNode(node); + } + return spanInNode(otherwiseOnNode); + } + function spanInNodeArray(nodeArray) { + return ts.createTextSpanFromBounds(ts.skipTrivia(sourceFile.text, nodeArray.pos), nodeArray.end); + } + function spanInPreviousNode(node) { + return spanInNode(ts.findPrecedingToken(node.pos, sourceFile)); + } + function spanInNextNode(node) { + return spanInNode(ts.findNextToken(node, node.parent, sourceFile)); + } + function spanInNode(node) { + if (node) { + var parent = node.parent; + switch (node.kind) { + case 219 /* VariableStatement */: + // Span on first variable declaration + return spanInVariableDeclaration(node.declarationList.declarations[0]); + case 237 /* VariableDeclaration */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + return spanInVariableDeclaration(node); + case 151 /* Parameter */: + return spanInParameterDeclaration(node); + case 239 /* FunctionDeclaration */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 157 /* Constructor */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + return spanInFunctionDeclaration(node); + case 218 /* Block */: + if (ts.isFunctionBlock(node)) { + return spanInFunctionBlock(node); + } + // falls through + case 245 /* ModuleBlock */: + return spanInBlock(node); + case 274 /* CatchClause */: + return spanInBlock(node.block); + case 221 /* ExpressionStatement */: + // span on the expression + return textSpan(node.expression); + case 230 /* ReturnStatement */: + // span on return keyword and expression if present + return textSpan(node.getChildAt(0), node.expression); + case 224 /* WhileStatement */: + // Span on while(...) + return textSpanEndingAtNextToken(node, node.expression); + case 223 /* DoStatement */: + // span in statement of the do statement + return spanInNode(node.statement); + case 236 /* DebuggerStatement */: + // span on debugger keyword + return textSpan(node.getChildAt(0)); + case 222 /* IfStatement */: + // set on if(..) span + return textSpanEndingAtNextToken(node, node.expression); + case 233 /* LabeledStatement */: + // span in statement + return spanInNode(node.statement); + case 229 /* BreakStatement */: + case 228 /* ContinueStatement */: + // On break or continue keyword and label if present + return textSpan(node.getChildAt(0), node.label); + case 225 /* ForStatement */: + return spanInForStatement(node); + case 226 /* ForInStatement */: + // span of for (a in ...) + return textSpanEndingAtNextToken(node, node.expression); + case 227 /* ForOfStatement */: + // span in initializer + return spanInInitializerOfForLike(node); + case 232 /* SwitchStatement */: + // span on switch(...) + return textSpanEndingAtNextToken(node, node.expression); + case 271 /* CaseClause */: + case 272 /* DefaultClause */: + // span in first statement of the clause + return spanInNode(node.statements[0]); + case 235 /* TryStatement */: + // span in try block + return spanInBlock(node.tryBlock); + case 234 /* ThrowStatement */: + // span in throw ... + return textSpan(node, node.expression); + case 254 /* ExportAssignment */: + // span on export = id + return textSpan(node, node.expression); + case 248 /* ImportEqualsDeclaration */: + // import statement without including semicolon + return textSpan(node, node.moduleReference); + case 249 /* ImportDeclaration */: + // import statement without including semicolon + return textSpan(node, node.moduleSpecifier); + case 255 /* ExportDeclaration */: + // import statement without including semicolon + return textSpan(node, node.moduleSpecifier); + case 244 /* ModuleDeclaration */: + // span on complete module if it is instantiated + if (ts.getModuleInstanceState(node) !== 1 /* Instantiated */) { + return undefined; + } + // falls through + case 240 /* ClassDeclaration */: + case 243 /* EnumDeclaration */: + case 278 /* EnumMember */: + case 186 /* BindingElement */: + // span on complete node + return textSpan(node); + case 231 /* WithStatement */: + // span in statement + return spanInNode(node.statement); + case 152 /* Decorator */: + return spanInNodeArray(parent.decorators); + case 184 /* ObjectBindingPattern */: + case 185 /* ArrayBindingPattern */: + return spanInBindingPattern(node); + // No breakpoint in interface, type alias + case 241 /* InterfaceDeclaration */: + case 242 /* TypeAliasDeclaration */: + return undefined; + // Tokens: + case 26 /* SemicolonToken */: + case 1 /* EndOfFileToken */: + return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(node.pos, sourceFile)); + case 27 /* CommaToken */: + return spanInPreviousNode(node); + case 18 /* OpenBraceToken */: + return spanInOpenBraceToken(node); + case 19 /* CloseBraceToken */: + return spanInCloseBraceToken(node); + case 23 /* CloseBracketToken */: + return spanInCloseBracketToken(node); + case 20 /* OpenParenToken */: + return spanInOpenParenToken(node); + case 21 /* CloseParenToken */: + return spanInCloseParenToken(node); + case 57 /* ColonToken */: + return spanInColonToken(node); + case 30 /* GreaterThanToken */: + case 28 /* LessThanToken */: + return spanInGreaterThanOrLessThanToken(node); + // Keywords: + case 107 /* WhileKeyword */: + return spanInWhileKeyword(node); + case 83 /* ElseKeyword */: + case 75 /* CatchKeyword */: + case 88 /* FinallyKeyword */: + return spanInNextNode(node); + case 147 /* OfKeyword */: + return spanInOfKeyword(node); + default: + // Destructuring pattern in destructuring assignment + // [a, b, c] of + // [a, b, c] = expression + if (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node)) { + return spanInArrayLiteralOrObjectLiteralDestructuringPattern(node); + } + // Set breakpoint on identifier element of destructuring pattern + // `a` or `...c` or `d: x` from + // `[a, b, ...c]` or `{ a, b }` or `{ d: x }` from destructuring pattern + if ((node.kind === 72 /* Identifier */ || + node.kind === 208 /* SpreadElement */ || + node.kind === 275 /* PropertyAssignment */ || + node.kind === 276 /* ShorthandPropertyAssignment */) && + ts.isArrayLiteralOrObjectLiteralDestructuringPattern(parent)) { + return textSpan(node); + } + if (node.kind === 204 /* BinaryExpression */) { + var _a = node, left = _a.left, operatorToken = _a.operatorToken; + // Set breakpoint in destructuring pattern if its destructuring assignment + // [a, b, c] or {a, b, c} of + // [a, b, c] = expression or + // {a, b, c} = expression + if (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(left)) { + return spanInArrayLiteralOrObjectLiteralDestructuringPattern(left); + } + if (operatorToken.kind === 59 /* EqualsToken */ && ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent)) { + // Set breakpoint on assignment expression element of destructuring pattern + // a = expression of + // [a = expression, b, c] = someExpression or + // { a = expression, b, c } = someExpression + return textSpan(node); + } + if (operatorToken.kind === 27 /* CommaToken */) { + return spanInNode(left); + } + } + if (ts.isExpressionNode(node)) { + switch (parent.kind) { + case 223 /* DoStatement */: + // Set span as if on while keyword + return spanInPreviousNode(node); + case 152 /* Decorator */: + // Set breakpoint on the decorator emit + return spanInNode(node.parent); + case 225 /* ForStatement */: + case 227 /* ForOfStatement */: + return textSpan(node); + case 204 /* BinaryExpression */: + if (node.parent.operatorToken.kind === 27 /* CommaToken */) { + // If this is a comma expression, the breakpoint is possible in this expression + return textSpan(node); + } + break; + case 197 /* ArrowFunction */: + if (node.parent.body === node) { + // If this is body of arrow function, it is allowed to have the breakpoint + return textSpan(node); + } + break; + } + } + switch (node.parent.kind) { + case 275 /* PropertyAssignment */: + // If this is name of property assignment, set breakpoint in the initializer + if (node.parent.name === node && + !ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent.parent)) { + return spanInNode(node.parent.initializer); + } + break; + case 194 /* TypeAssertionExpression */: + // Breakpoint in type assertion goes to its operand + if (node.parent.type === node) { + return spanInNextNode(node.parent.type); + } + break; + case 237 /* VariableDeclaration */: + case 151 /* Parameter */: { + // initializer of variable/parameter declaration go to previous node + var _b = node.parent, initializer = _b.initializer, type = _b.type; + if (initializer === node || type === node || ts.isAssignmentOperator(node.kind)) { + return spanInPreviousNode(node); + } + break; + } + case 204 /* BinaryExpression */: { + var left = node.parent.left; + if (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(left) && node !== left) { + // If initializer of destructuring assignment move to previous token + return spanInPreviousNode(node); + } + break; + } + default: + // return type of function go to previous token + if (ts.isFunctionLike(node.parent) && node.parent.type === node) { + return spanInPreviousNode(node); + } + } + // Default go to parent to set the breakpoint + return spanInNode(node.parent); + } + } + function textSpanFromVariableDeclaration(variableDeclaration) { + if (ts.isVariableDeclarationList(variableDeclaration.parent) && variableDeclaration.parent.declarations[0] === variableDeclaration) { + // First declaration - include let keyword + return textSpan(ts.findPrecedingToken(variableDeclaration.pos, sourceFile, variableDeclaration.parent), variableDeclaration); + } + else { + // Span only on this declaration + return textSpan(variableDeclaration); + } + } + function spanInVariableDeclaration(variableDeclaration) { + // If declaration of for in statement, just set the span in parent + if (variableDeclaration.parent.parent.kind === 226 /* ForInStatement */) { + return spanInNode(variableDeclaration.parent.parent); + } + var parent = variableDeclaration.parent; + // If this is a destructuring pattern, set breakpoint in binding pattern + if (ts.isBindingPattern(variableDeclaration.name)) { + return spanInBindingPattern(variableDeclaration.name); + } + // Breakpoint is possible in variableDeclaration only if there is initialization + // or its declaration from 'for of' + if (variableDeclaration.initializer || + ts.hasModifier(variableDeclaration, 1 /* Export */) || + parent.parent.kind === 227 /* ForOfStatement */) { + return textSpanFromVariableDeclaration(variableDeclaration); + } + if (ts.isVariableDeclarationList(variableDeclaration.parent) && + variableDeclaration.parent.declarations[0] !== variableDeclaration) { + // If we cannot set breakpoint on this declaration, set it on previous one + // Because the variable declaration may be binding pattern and + // we would like to set breakpoint in last binding element if that's the case, + // use preceding token instead + return spanInNode(ts.findPrecedingToken(variableDeclaration.pos, sourceFile, variableDeclaration.parent)); + } + } + function canHaveSpanInParameterDeclaration(parameter) { + // Breakpoint is possible on parameter only if it has initializer, is a rest parameter, or has public or private modifier + return !!parameter.initializer || parameter.dotDotDotToken !== undefined || + ts.hasModifier(parameter, 4 /* Public */ | 8 /* Private */); + } + function spanInParameterDeclaration(parameter) { + if (ts.isBindingPattern(parameter.name)) { + // Set breakpoint in binding pattern + return spanInBindingPattern(parameter.name); + } + else if (canHaveSpanInParameterDeclaration(parameter)) { + return textSpan(parameter); + } + else { + var functionDeclaration = parameter.parent; + var indexOfParameter = functionDeclaration.parameters.indexOf(parameter); + ts.Debug.assert(indexOfParameter !== -1); + if (indexOfParameter !== 0) { + // Not a first parameter, go to previous parameter + return spanInParameterDeclaration(functionDeclaration.parameters[indexOfParameter - 1]); + } + else { + // Set breakpoint in the function declaration body + return spanInNode(functionDeclaration.body); + } + } + } + function canFunctionHaveSpanInWholeDeclaration(functionDeclaration) { + return ts.hasModifier(functionDeclaration, 1 /* Export */) || + (functionDeclaration.parent.kind === 240 /* ClassDeclaration */ && functionDeclaration.kind !== 157 /* Constructor */); + } + function spanInFunctionDeclaration(functionDeclaration) { + // No breakpoints in the function signature + if (!functionDeclaration.body) { + return undefined; + } + if (canFunctionHaveSpanInWholeDeclaration(functionDeclaration)) { + // Set the span on whole function declaration + return textSpan(functionDeclaration); + } + // Set span in function body + return spanInNode(functionDeclaration.body); + } + function spanInFunctionBlock(block) { + var nodeForSpanInBlock = block.statements.length ? block.statements[0] : block.getLastToken(); + if (canFunctionHaveSpanInWholeDeclaration(block.parent)) { + return spanInNodeIfStartsOnSameLine(block.parent, nodeForSpanInBlock); + } + return spanInNode(nodeForSpanInBlock); + } + function spanInBlock(block) { + switch (block.parent.kind) { + case 244 /* ModuleDeclaration */: + if (ts.getModuleInstanceState(block.parent) !== 1 /* Instantiated */) { + return undefined; + } + // falls through + // Set on parent if on same line otherwise on first statement + case 224 /* WhileStatement */: + case 222 /* IfStatement */: + case 226 /* ForInStatement */: + return spanInNodeIfStartsOnSameLine(block.parent, block.statements[0]); + // Set span on previous token if it starts on same line otherwise on the first statement of the block + case 225 /* ForStatement */: + case 227 /* ForOfStatement */: + return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(block.pos, sourceFile, block.parent), block.statements[0]); + } + // Default action is to set on first statement + return spanInNode(block.statements[0]); + } + function spanInInitializerOfForLike(forLikeStatement) { + if (forLikeStatement.initializer.kind === 238 /* VariableDeclarationList */) { + // Declaration list - set breakpoint in first declaration + var variableDeclarationList = forLikeStatement.initializer; + if (variableDeclarationList.declarations.length > 0) { + return spanInNode(variableDeclarationList.declarations[0]); + } + } + else { + // Expression - set breakpoint in it + return spanInNode(forLikeStatement.initializer); + } + } + function spanInForStatement(forStatement) { + if (forStatement.initializer) { + return spanInInitializerOfForLike(forStatement); + } + if (forStatement.condition) { + return textSpan(forStatement.condition); + } + if (forStatement.incrementor) { + return textSpan(forStatement.incrementor); + } + } + function spanInBindingPattern(bindingPattern) { + // Set breakpoint in first binding element + var firstBindingElement = ts.forEach(bindingPattern.elements, function (element) { return element.kind !== 210 /* OmittedExpression */ ? element : undefined; }); + if (firstBindingElement) { + return spanInNode(firstBindingElement); + } + // Empty binding pattern of binding element, set breakpoint on binding element + if (bindingPattern.parent.kind === 186 /* BindingElement */) { + return textSpan(bindingPattern.parent); + } + // Variable declaration is used as the span + return textSpanFromVariableDeclaration(bindingPattern.parent); + } + function spanInArrayLiteralOrObjectLiteralDestructuringPattern(node) { + ts.Debug.assert(node.kind !== 185 /* ArrayBindingPattern */ && node.kind !== 184 /* ObjectBindingPattern */); + var elements = node.kind === 187 /* ArrayLiteralExpression */ ? node.elements : node.properties; + var firstBindingElement = ts.forEach(elements, function (element) { return element.kind !== 210 /* OmittedExpression */ ? element : undefined; }); + if (firstBindingElement) { + return spanInNode(firstBindingElement); + } + // Could be ArrayLiteral from destructuring assignment or + // just nested element in another destructuring assignment + // set breakpoint on assignment when parent is destructuring assignment + // Otherwise set breakpoint for this element + return textSpan(node.parent.kind === 204 /* BinaryExpression */ ? node.parent : node); + } + // Tokens: + function spanInOpenBraceToken(node) { + switch (node.parent.kind) { + case 243 /* EnumDeclaration */: + var enumDeclaration = node.parent; + return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(node.pos, sourceFile, node.parent), enumDeclaration.members.length ? enumDeclaration.members[0] : enumDeclaration.getLastToken(sourceFile)); + case 240 /* ClassDeclaration */: + var classDeclaration = node.parent; + return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(node.pos, sourceFile, node.parent), classDeclaration.members.length ? classDeclaration.members[0] : classDeclaration.getLastToken(sourceFile)); + case 246 /* CaseBlock */: + return spanInNodeIfStartsOnSameLine(node.parent.parent, node.parent.clauses[0]); + } + // Default to parent node + return spanInNode(node.parent); + } + function spanInCloseBraceToken(node) { + switch (node.parent.kind) { + case 245 /* ModuleBlock */: + // If this is not an instantiated module block, no bp span + if (ts.getModuleInstanceState(node.parent.parent) !== 1 /* Instantiated */) { + return undefined; + } + // falls through + case 243 /* EnumDeclaration */: + case 240 /* ClassDeclaration */: + // Span on close brace token + return textSpan(node); + case 218 /* Block */: + if (ts.isFunctionBlock(node.parent)) { + // Span on close brace token + return textSpan(node); + } + // falls through + case 274 /* CatchClause */: + return spanInNode(ts.lastOrUndefined(node.parent.statements)); + case 246 /* CaseBlock */: + // breakpoint in last statement of the last clause + var caseBlock = node.parent; + var lastClause = ts.lastOrUndefined(caseBlock.clauses); + if (lastClause) { + return spanInNode(ts.lastOrUndefined(lastClause.statements)); + } + return undefined; + case 184 /* ObjectBindingPattern */: + // Breakpoint in last binding element or binding pattern if it contains no elements + var bindingPattern = node.parent; + return spanInNode(ts.lastOrUndefined(bindingPattern.elements) || bindingPattern); + // Default to parent node + default: + if (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent)) { + // Breakpoint in last binding element or binding pattern if it contains no elements + var objectLiteral = node.parent; + return textSpan(ts.lastOrUndefined(objectLiteral.properties) || objectLiteral); + } + return spanInNode(node.parent); + } + } + function spanInCloseBracketToken(node) { + switch (node.parent.kind) { + case 185 /* ArrayBindingPattern */: + // Breakpoint in last binding element or binding pattern if it contains no elements + var bindingPattern = node.parent; + return textSpan(ts.lastOrUndefined(bindingPattern.elements) || bindingPattern); + default: + if (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent)) { + // Breakpoint in last binding element or binding pattern if it contains no elements + var arrayLiteral = node.parent; + return textSpan(ts.lastOrUndefined(arrayLiteral.elements) || arrayLiteral); + } + // Default to parent node + return spanInNode(node.parent); + } + } + function spanInOpenParenToken(node) { + if (node.parent.kind === 223 /* DoStatement */ || // Go to while keyword and do action instead + node.parent.kind === 191 /* CallExpression */ || + node.parent.kind === 192 /* NewExpression */) { + return spanInPreviousNode(node); + } + if (node.parent.kind === 195 /* ParenthesizedExpression */) { + return spanInNextNode(node); + } + // Default to parent node + return spanInNode(node.parent); + } + function spanInCloseParenToken(node) { + // Is this close paren token of parameter list, set span in previous token + switch (node.parent.kind) { + case 196 /* FunctionExpression */: + case 239 /* FunctionDeclaration */: + case 197 /* ArrowFunction */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 157 /* Constructor */: + case 224 /* WhileStatement */: + case 223 /* DoStatement */: + case 225 /* ForStatement */: + case 227 /* ForOfStatement */: + case 191 /* CallExpression */: + case 192 /* NewExpression */: + case 195 /* ParenthesizedExpression */: + return spanInPreviousNode(node); + // Default to parent node + default: + return spanInNode(node.parent); + } + } + function spanInColonToken(node) { + // Is this : specifying return annotation of the function declaration + if (ts.isFunctionLike(node.parent) || + node.parent.kind === 275 /* PropertyAssignment */ || + node.parent.kind === 151 /* Parameter */) { + return spanInPreviousNode(node); + } + return spanInNode(node.parent); + } + function spanInGreaterThanOrLessThanToken(node) { + if (node.parent.kind === 194 /* TypeAssertionExpression */) { + return spanInNextNode(node); + } + return spanInNode(node.parent); + } + function spanInWhileKeyword(node) { + if (node.parent.kind === 223 /* DoStatement */) { + // Set span on while expression + return textSpanEndingAtNextToken(node, node.parent.expression); + } + // Default to parent node + return spanInNode(node.parent); + } + function spanInOfKeyword(node) { + if (node.parent.kind === 227 /* ForOfStatement */) { + // Set using next token + return spanInNextNode(node); + } + // Default to parent node + return spanInNode(node.parent); + } + } + } + BreakpointResolver.spanInSourceFileAtLocation = spanInSourceFileAtLocation; + })(BreakpointResolver = ts.BreakpointResolver || (ts.BreakpointResolver = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + /** + * Transform one or more nodes using the supplied transformers. + * @param source A single `Node` or an array of `Node` objects. + * @param transformers An array of `TransformerFactory` callbacks used to process the transformation. + * @param compilerOptions Optional compiler options. + */ + function transform(source, transformers, compilerOptions) { + var diagnostics = []; + compilerOptions = ts.fixupCompilerOptions(compilerOptions, diagnostics); // TODO: GH#18217 + var nodes = ts.isArray(source) ? source : [source]; + var result = ts.transformNodes(/*resolver*/ undefined, /*emitHost*/ undefined, compilerOptions, nodes, transformers, /*allowDtsFiles*/ true); + result.diagnostics = ts.concatenate(result.diagnostics, diagnostics); + return result; + } + ts.transform = transform; +})(ts || (ts = {})); +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +/* @internal */ +var debugObjectHost = (function () { return this; })(); +// We need to use 'null' to interface with the managed side. +/* tslint:disable:no-null-keyword */ +/* tslint:disable:no-in-operator */ +/* @internal */ +var ts; +(function (ts) { + function logInternalError(logger, err) { + if (logger) { + logger.log("*INTERNAL ERROR* - Exception in typescript services: " + err.message); + } + } + var ScriptSnapshotShimAdapter = /** @class */ (function () { + function ScriptSnapshotShimAdapter(scriptSnapshotShim) { + this.scriptSnapshotShim = scriptSnapshotShim; + } + ScriptSnapshotShimAdapter.prototype.getText = function (start, end) { + return this.scriptSnapshotShim.getText(start, end); + }; + ScriptSnapshotShimAdapter.prototype.getLength = function () { + return this.scriptSnapshotShim.getLength(); + }; + ScriptSnapshotShimAdapter.prototype.getChangeRange = function (oldSnapshot) { + var oldSnapshotShim = oldSnapshot; + var encoded = this.scriptSnapshotShim.getChangeRange(oldSnapshotShim.scriptSnapshotShim); + if (encoded === null) { + return null; // TODO: GH#18217 + } + var decoded = JSON.parse(encoded); // TODO: GH#18217 + return ts.createTextChangeRange(ts.createTextSpan(decoded.span.start, decoded.span.length), decoded.newLength); + }; + ScriptSnapshotShimAdapter.prototype.dispose = function () { + // if scriptSnapshotShim is a COM object then property check becomes method call with no arguments + // 'in' does not have this effect + if ("dispose" in this.scriptSnapshotShim) { + this.scriptSnapshotShim.dispose(); // TODO: GH#18217 Can we just use `if (this.scriptSnapshotShim.dispose)`? + } + }; + return ScriptSnapshotShimAdapter; + }()); + var LanguageServiceShimHostAdapter = /** @class */ (function () { + function LanguageServiceShimHostAdapter(shimHost) { + var _this = this; + this.shimHost = shimHost; + this.loggingEnabled = false; + this.tracingEnabled = false; + // if shimHost is a COM object then property check will become method call with no arguments. + // 'in' does not have this effect. + if ("getModuleResolutionsForFile" in this.shimHost) { + this.resolveModuleNames = function (moduleNames, containingFile) { + var resolutionsInFile = JSON.parse(_this.shimHost.getModuleResolutionsForFile(containingFile)); // TODO: GH#18217 + return ts.map(moduleNames, function (name) { + var result = ts.getProperty(resolutionsInFile, name); + return result ? { resolvedFileName: result, extension: ts.extensionFromPath(result), isExternalLibraryImport: false } : undefined; + }); + }; + } + if ("directoryExists" in this.shimHost) { + this.directoryExists = function (directoryName) { return _this.shimHost.directoryExists(directoryName); }; + } + if ("getTypeReferenceDirectiveResolutionsForFile" in this.shimHost) { + this.resolveTypeReferenceDirectives = function (typeDirectiveNames, containingFile) { + var typeDirectivesForFile = JSON.parse(_this.shimHost.getTypeReferenceDirectiveResolutionsForFile(containingFile)); // TODO: GH#18217 + return ts.map(typeDirectiveNames, function (name) { return ts.getProperty(typeDirectivesForFile, name); }); + }; + } + } + LanguageServiceShimHostAdapter.prototype.log = function (s) { + if (this.loggingEnabled) { + this.shimHost.log(s); + } + }; + LanguageServiceShimHostAdapter.prototype.trace = function (s) { + if (this.tracingEnabled) { + this.shimHost.trace(s); + } + }; + LanguageServiceShimHostAdapter.prototype.error = function (s) { + this.shimHost.error(s); + }; + LanguageServiceShimHostAdapter.prototype.getProjectVersion = function () { + if (!this.shimHost.getProjectVersion) { + // shimmed host does not support getProjectVersion + return undefined; // TODO: GH#18217 + } + return this.shimHost.getProjectVersion(); + }; + LanguageServiceShimHostAdapter.prototype.getTypeRootsVersion = function () { + if (!this.shimHost.getTypeRootsVersion) { + return 0; + } + return this.shimHost.getTypeRootsVersion(); + }; + LanguageServiceShimHostAdapter.prototype.useCaseSensitiveFileNames = function () { + return this.shimHost.useCaseSensitiveFileNames ? this.shimHost.useCaseSensitiveFileNames() : false; + }; + LanguageServiceShimHostAdapter.prototype.getCompilationSettings = function () { + var settingsJson = this.shimHost.getCompilationSettings(); + if (settingsJson === null || settingsJson === "") { + throw Error("LanguageServiceShimHostAdapter.getCompilationSettings: empty compilationSettings"); + } + var compilerOptions = JSON.parse(settingsJson); + // permit language service to handle all files (filtering should be performed on the host side) + compilerOptions.allowNonTsExtensions = true; + return compilerOptions; + }; + LanguageServiceShimHostAdapter.prototype.getScriptFileNames = function () { + var encoded = this.shimHost.getScriptFileNames(); + return JSON.parse(encoded); + }; + LanguageServiceShimHostAdapter.prototype.getScriptSnapshot = function (fileName) { + var scriptSnapshot = this.shimHost.getScriptSnapshot(fileName); + return scriptSnapshot && new ScriptSnapshotShimAdapter(scriptSnapshot); + }; + LanguageServiceShimHostAdapter.prototype.getScriptKind = function (fileName) { + if ("getScriptKind" in this.shimHost) { + return this.shimHost.getScriptKind(fileName); // TODO: GH#18217 + } + else { + return 0 /* Unknown */; + } + }; + LanguageServiceShimHostAdapter.prototype.getScriptVersion = function (fileName) { + return this.shimHost.getScriptVersion(fileName); + }; + LanguageServiceShimHostAdapter.prototype.getLocalizedDiagnosticMessages = function () { + var diagnosticMessagesJson = this.shimHost.getLocalizedDiagnosticMessages(); + if (diagnosticMessagesJson === null || diagnosticMessagesJson === "") { + return null; + } + try { + return JSON.parse(diagnosticMessagesJson); + } + catch (e) { + this.log(e.description || "diagnosticMessages.generated.json has invalid JSON format"); + return null; + } + }; + LanguageServiceShimHostAdapter.prototype.getCancellationToken = function () { + var hostCancellationToken = this.shimHost.getCancellationToken(); + return new ts.ThrottledCancellationToken(hostCancellationToken); + }; + LanguageServiceShimHostAdapter.prototype.getCurrentDirectory = function () { + return this.shimHost.getCurrentDirectory(); + }; + LanguageServiceShimHostAdapter.prototype.getDirectories = function (path) { + return JSON.parse(this.shimHost.getDirectories(path)); + }; + LanguageServiceShimHostAdapter.prototype.getDefaultLibFileName = function (options) { + return this.shimHost.getDefaultLibFileName(JSON.stringify(options)); + }; + LanguageServiceShimHostAdapter.prototype.readDirectory = function (path, extensions, exclude, include, depth) { + var pattern = ts.getFileMatcherPatterns(path, exclude, include, this.shimHost.useCaseSensitiveFileNames(), this.shimHost.getCurrentDirectory()); // TODO: GH#18217 + return JSON.parse(this.shimHost.readDirectory(path, JSON.stringify(extensions), JSON.stringify(pattern.basePaths), pattern.excludePattern, pattern.includeFilePattern, pattern.includeDirectoryPattern, depth)); + }; + LanguageServiceShimHostAdapter.prototype.readFile = function (path, encoding) { + return this.shimHost.readFile(path, encoding); + }; + LanguageServiceShimHostAdapter.prototype.fileExists = function (path) { + return this.shimHost.fileExists(path); + }; + return LanguageServiceShimHostAdapter; + }()); + ts.LanguageServiceShimHostAdapter = LanguageServiceShimHostAdapter; + var CoreServicesShimHostAdapter = /** @class */ (function () { + function CoreServicesShimHostAdapter(shimHost) { + var _this = this; + this.shimHost = shimHost; + this.useCaseSensitiveFileNames = this.shimHost.useCaseSensitiveFileNames ? this.shimHost.useCaseSensitiveFileNames() : false; + if ("directoryExists" in this.shimHost) { + this.directoryExists = function (directoryName) { return _this.shimHost.directoryExists(directoryName); }; + } + else { + this.directoryExists = undefined; // TODO: GH#18217 + } + if ("realpath" in this.shimHost) { + this.realpath = function (path) { return _this.shimHost.realpath(path); }; // TODO: GH#18217 + } + else { + this.realpath = undefined; // TODO: GH#18217 + } + } + CoreServicesShimHostAdapter.prototype.readDirectory = function (rootDir, extensions, exclude, include, depth) { + var pattern = ts.getFileMatcherPatterns(rootDir, exclude, include, this.shimHost.useCaseSensitiveFileNames(), this.shimHost.getCurrentDirectory()); // TODO: GH#18217 + return JSON.parse(this.shimHost.readDirectory(rootDir, JSON.stringify(extensions), JSON.stringify(pattern.basePaths), pattern.excludePattern, pattern.includeFilePattern, pattern.includeDirectoryPattern, depth)); + }; + CoreServicesShimHostAdapter.prototype.fileExists = function (fileName) { + return this.shimHost.fileExists(fileName); + }; + CoreServicesShimHostAdapter.prototype.readFile = function (fileName) { + return this.shimHost.readFile(fileName); + }; + CoreServicesShimHostAdapter.prototype.getDirectories = function (path) { + return JSON.parse(this.shimHost.getDirectories(path)); + }; + return CoreServicesShimHostAdapter; + }()); + ts.CoreServicesShimHostAdapter = CoreServicesShimHostAdapter; + function simpleForwardCall(logger, actionDescription, action, logPerformance) { + var start; + if (logPerformance) { + logger.log(actionDescription); + start = ts.timestamp(); + } + var result = action(); + if (logPerformance) { + var end = ts.timestamp(); + logger.log(actionDescription + " completed in " + (end - start) + " msec"); + if (ts.isString(result)) { + var str = result; + if (str.length > 128) { + str = str.substring(0, 128) + "..."; + } + logger.log(" result.length=" + str.length + ", result='" + JSON.stringify(str) + "'"); + } + } + return result; + } + function forwardJSONCall(logger, actionDescription, action, logPerformance) { + return forwardCall(logger, actionDescription, /*returnJson*/ true, action, logPerformance); + } + function forwardCall(logger, actionDescription, returnJson, action, logPerformance) { + try { + var result = simpleForwardCall(logger, actionDescription, action, logPerformance); + return returnJson ? JSON.stringify({ result: result }) : result; + } + catch (err) { + if (err instanceof ts.OperationCanceledException) { + return JSON.stringify({ canceled: true }); + } + logInternalError(logger, err); + err.description = actionDescription; + return JSON.stringify({ error: err }); + } + } + var ShimBase = /** @class */ (function () { + function ShimBase(factory) { + this.factory = factory; + factory.registerShim(this); + } + ShimBase.prototype.dispose = function (_dummy) { + this.factory.unregisterShim(this); + }; + return ShimBase; + }()); + function realizeDiagnostics(diagnostics, newLine) { + return diagnostics.map(function (d) { return realizeDiagnostic(d, newLine); }); + } + ts.realizeDiagnostics = realizeDiagnostics; + function realizeDiagnostic(diagnostic, newLine) { + return { + message: ts.flattenDiagnosticMessageText(diagnostic.messageText, newLine), + start: diagnostic.start, + length: diagnostic.length, + category: ts.diagnosticCategoryName(diagnostic), + code: diagnostic.code, + reportsUnnecessary: diagnostic.reportsUnnecessary, + }; + } + var LanguageServiceShimObject = /** @class */ (function (_super) { + __extends(LanguageServiceShimObject, _super); + function LanguageServiceShimObject(factory, host, languageService) { + var _this = _super.call(this, factory) || this; + _this.host = host; + _this.languageService = languageService; + _this.logPerformance = false; + _this.logger = _this.host; + return _this; + } + LanguageServiceShimObject.prototype.forwardJSONCall = function (actionDescription, action) { + return forwardJSONCall(this.logger, actionDescription, action, this.logPerformance); + }; + /// DISPOSE + /** + * Ensure (almost) deterministic release of internal Javascript resources when + * some external native objects holds onto us (e.g. Com/Interop). + */ + LanguageServiceShimObject.prototype.dispose = function (dummy) { + this.logger.log("dispose()"); + this.languageService.dispose(); + this.languageService = null; + // force a GC + if (debugObjectHost && debugObjectHost.CollectGarbage) { + debugObjectHost.CollectGarbage(); + this.logger.log("CollectGarbage()"); + } + this.logger = null; + _super.prototype.dispose.call(this, dummy); + }; + /// REFRESH + /** + * Update the list of scripts known to the compiler + */ + LanguageServiceShimObject.prototype.refresh = function (throwOnError) { + this.forwardJSONCall("refresh(" + throwOnError + ")", function () { return null; }); + }; + LanguageServiceShimObject.prototype.cleanupSemanticCache = function () { + var _this = this; + this.forwardJSONCall("cleanupSemanticCache()", function () { + _this.languageService.cleanupSemanticCache(); + return null; + }); + }; + LanguageServiceShimObject.prototype.realizeDiagnostics = function (diagnostics) { + var newLine = ts.getNewLineOrDefaultFromHost(this.host); + return realizeDiagnostics(diagnostics, newLine); + }; + LanguageServiceShimObject.prototype.getSyntacticClassifications = function (fileName, start, length) { + var _this = this; + return this.forwardJSONCall("getSyntacticClassifications('" + fileName + "', " + start + ", " + length + ")", function () { return _this.languageService.getSyntacticClassifications(fileName, ts.createTextSpan(start, length)); }); + }; + LanguageServiceShimObject.prototype.getSemanticClassifications = function (fileName, start, length) { + var _this = this; + return this.forwardJSONCall("getSemanticClassifications('" + fileName + "', " + start + ", " + length + ")", function () { return _this.languageService.getSemanticClassifications(fileName, ts.createTextSpan(start, length)); }); + }; + LanguageServiceShimObject.prototype.getEncodedSyntacticClassifications = function (fileName, start, length) { + var _this = this; + return this.forwardJSONCall("getEncodedSyntacticClassifications('" + fileName + "', " + start + ", " + length + ")", + // directly serialize the spans out to a string. This is much faster to decode + // on the managed side versus a full JSON array. + function () { return convertClassifications(_this.languageService.getEncodedSyntacticClassifications(fileName, ts.createTextSpan(start, length))); }); + }; + LanguageServiceShimObject.prototype.getEncodedSemanticClassifications = function (fileName, start, length) { + var _this = this; + return this.forwardJSONCall("getEncodedSemanticClassifications('" + fileName + "', " + start + ", " + length + ")", + // directly serialize the spans out to a string. This is much faster to decode + // on the managed side versus a full JSON array. + function () { return convertClassifications(_this.languageService.getEncodedSemanticClassifications(fileName, ts.createTextSpan(start, length))); }); + }; + LanguageServiceShimObject.prototype.getSyntacticDiagnostics = function (fileName) { + var _this = this; + return this.forwardJSONCall("getSyntacticDiagnostics('" + fileName + "')", function () { + var diagnostics = _this.languageService.getSyntacticDiagnostics(fileName); + return _this.realizeDiagnostics(diagnostics); + }); + }; + LanguageServiceShimObject.prototype.getSemanticDiagnostics = function (fileName) { + var _this = this; + return this.forwardJSONCall("getSemanticDiagnostics('" + fileName + "')", function () { + var diagnostics = _this.languageService.getSemanticDiagnostics(fileName); + return _this.realizeDiagnostics(diagnostics); + }); + }; + LanguageServiceShimObject.prototype.getSuggestionDiagnostics = function (fileName) { + var _this = this; + return this.forwardJSONCall("getSuggestionDiagnostics('" + fileName + "')", function () { return _this.realizeDiagnostics(_this.languageService.getSuggestionDiagnostics(fileName)); }); + }; + LanguageServiceShimObject.prototype.getCompilerOptionsDiagnostics = function () { + var _this = this; + return this.forwardJSONCall("getCompilerOptionsDiagnostics()", function () { + var diagnostics = _this.languageService.getCompilerOptionsDiagnostics(); + return _this.realizeDiagnostics(diagnostics); + }); + }; + /// QUICKINFO + /** + * Computes a string representation of the type at the requested position + * in the active file. + */ + LanguageServiceShimObject.prototype.getQuickInfoAtPosition = function (fileName, position) { + var _this = this; + return this.forwardJSONCall("getQuickInfoAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getQuickInfoAtPosition(fileName, position); }); + }; + /// NAMEORDOTTEDNAMESPAN + /** + * Computes span information of the name or dotted name at the requested position + * in the active file. + */ + LanguageServiceShimObject.prototype.getNameOrDottedNameSpan = function (fileName, startPos, endPos) { + var _this = this; + return this.forwardJSONCall("getNameOrDottedNameSpan('" + fileName + "', " + startPos + ", " + endPos + ")", function () { return _this.languageService.getNameOrDottedNameSpan(fileName, startPos, endPos); }); + }; + /** + * STATEMENTSPAN + * Computes span information of statement at the requested position in the active file. + */ + LanguageServiceShimObject.prototype.getBreakpointStatementAtPosition = function (fileName, position) { + var _this = this; + return this.forwardJSONCall("getBreakpointStatementAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getBreakpointStatementAtPosition(fileName, position); }); + }; + /// SIGNATUREHELP + LanguageServiceShimObject.prototype.getSignatureHelpItems = function (fileName, position, options) { + var _this = this; + return this.forwardJSONCall("getSignatureHelpItems('" + fileName + "', " + position + ")", function () { return _this.languageService.getSignatureHelpItems(fileName, position, options); }); + }; + /// GOTO DEFINITION + /** + * Computes the definition location and file for the symbol + * at the requested position. + */ + LanguageServiceShimObject.prototype.getDefinitionAtPosition = function (fileName, position) { + var _this = this; + return this.forwardJSONCall("getDefinitionAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getDefinitionAtPosition(fileName, position); }); + }; + /** + * Computes the definition location and file for the symbol + * at the requested position. + */ + LanguageServiceShimObject.prototype.getDefinitionAndBoundSpan = function (fileName, position) { + var _this = this; + return this.forwardJSONCall("getDefinitionAndBoundSpan('" + fileName + "', " + position + ")", function () { return _this.languageService.getDefinitionAndBoundSpan(fileName, position); }); + }; + /// GOTO Type + /** + * Computes the definition location of the type of the symbol + * at the requested position. + */ + LanguageServiceShimObject.prototype.getTypeDefinitionAtPosition = function (fileName, position) { + var _this = this; + return this.forwardJSONCall("getTypeDefinitionAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getTypeDefinitionAtPosition(fileName, position); }); + }; + /// GOTO Implementation + /** + * Computes the implementation location of the symbol + * at the requested position. + */ + LanguageServiceShimObject.prototype.getImplementationAtPosition = function (fileName, position) { + var _this = this; + return this.forwardJSONCall("getImplementationAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getImplementationAtPosition(fileName, position); }); + }; + LanguageServiceShimObject.prototype.getRenameInfo = function (fileName, position) { + var _this = this; + return this.forwardJSONCall("getRenameInfo('" + fileName + "', " + position + ")", function () { return _this.languageService.getRenameInfo(fileName, position); }); + }; + LanguageServiceShimObject.prototype.findRenameLocations = function (fileName, position, findInStrings, findInComments) { + var _this = this; + return this.forwardJSONCall("findRenameLocations('" + fileName + "', " + position + ", " + findInStrings + ", " + findInComments + ")", function () { return _this.languageService.findRenameLocations(fileName, position, findInStrings, findInComments); }); + }; + /// GET BRACE MATCHING + LanguageServiceShimObject.prototype.getBraceMatchingAtPosition = function (fileName, position) { + var _this = this; + return this.forwardJSONCall("getBraceMatchingAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getBraceMatchingAtPosition(fileName, position); }); + }; + LanguageServiceShimObject.prototype.isValidBraceCompletionAtPosition = function (fileName, position, openingBrace) { + var _this = this; + return this.forwardJSONCall("isValidBraceCompletionAtPosition('" + fileName + "', " + position + ", " + openingBrace + ")", function () { return _this.languageService.isValidBraceCompletionAtPosition(fileName, position, openingBrace); }); + }; + LanguageServiceShimObject.prototype.getSpanOfEnclosingComment = function (fileName, position, onlyMultiLine) { + var _this = this; + return this.forwardJSONCall("getSpanOfEnclosingComment('" + fileName + "', " + position + ")", function () { return _this.languageService.getSpanOfEnclosingComment(fileName, position, onlyMultiLine); }); + }; + /// GET SMART INDENT + LanguageServiceShimObject.prototype.getIndentationAtPosition = function (fileName, position, options /*Services.EditorOptions*/) { + var _this = this; + return this.forwardJSONCall("getIndentationAtPosition('" + fileName + "', " + position + ")", function () { + var localOptions = JSON.parse(options); + return _this.languageService.getIndentationAtPosition(fileName, position, localOptions); + }); + }; + /// GET REFERENCES + LanguageServiceShimObject.prototype.getReferencesAtPosition = function (fileName, position) { + var _this = this; + return this.forwardJSONCall("getReferencesAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getReferencesAtPosition(fileName, position); }); + }; + LanguageServiceShimObject.prototype.findReferences = function (fileName, position) { + var _this = this; + return this.forwardJSONCall("findReferences('" + fileName + "', " + position + ")", function () { return _this.languageService.findReferences(fileName, position); }); + }; + LanguageServiceShimObject.prototype.getOccurrencesAtPosition = function (fileName, position) { + var _this = this; + return this.forwardJSONCall("getOccurrencesAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getOccurrencesAtPosition(fileName, position); }); + }; + LanguageServiceShimObject.prototype.getDocumentHighlights = function (fileName, position, filesToSearch) { + var _this = this; + return this.forwardJSONCall("getDocumentHighlights('" + fileName + "', " + position + ")", function () { + var results = _this.languageService.getDocumentHighlights(fileName, position, JSON.parse(filesToSearch)); + // workaround for VS document highlighting issue - keep only items from the initial file + var normalizedName = ts.normalizeSlashes(fileName).toLowerCase(); + return ts.filter(results, function (r) { return ts.normalizeSlashes(r.fileName).toLowerCase() === normalizedName; }); + }); + }; + /// COMPLETION LISTS + /** + * Get a string based representation of the completions + * to provide at the given source position and providing a member completion + * list if requested. + */ + LanguageServiceShimObject.prototype.getCompletionsAtPosition = function (fileName, position, preferences) { + var _this = this; + return this.forwardJSONCall("getCompletionsAtPosition('" + fileName + "', " + position + ", " + preferences + ")", function () { return _this.languageService.getCompletionsAtPosition(fileName, position, preferences); }); + }; + /** Get a string based representation of a completion list entry details */ + LanguageServiceShimObject.prototype.getCompletionEntryDetails = function (fileName, position, entryName, formatOptions, source, preferences) { + var _this = this; + return this.forwardJSONCall("getCompletionEntryDetails('" + fileName + "', " + position + ", '" + entryName + "')", function () { + var localOptions = formatOptions === undefined ? undefined : JSON.parse(formatOptions); + return _this.languageService.getCompletionEntryDetails(fileName, position, entryName, localOptions, source, preferences); + }); + }; + LanguageServiceShimObject.prototype.getFormattingEditsForRange = function (fileName, start, end, options /*Services.FormatCodeOptions*/) { + var _this = this; + return this.forwardJSONCall("getFormattingEditsForRange('" + fileName + "', " + start + ", " + end + ")", function () { + var localOptions = JSON.parse(options); + return _this.languageService.getFormattingEditsForRange(fileName, start, end, localOptions); + }); + }; + LanguageServiceShimObject.prototype.getFormattingEditsForDocument = function (fileName, options /*Services.FormatCodeOptions*/) { + var _this = this; + return this.forwardJSONCall("getFormattingEditsForDocument('" + fileName + "')", function () { + var localOptions = JSON.parse(options); + return _this.languageService.getFormattingEditsForDocument(fileName, localOptions); + }); + }; + LanguageServiceShimObject.prototype.getFormattingEditsAfterKeystroke = function (fileName, position, key, options /*Services.FormatCodeOptions*/) { + var _this = this; + return this.forwardJSONCall("getFormattingEditsAfterKeystroke('" + fileName + "', " + position + ", '" + key + "')", function () { + var localOptions = JSON.parse(options); + return _this.languageService.getFormattingEditsAfterKeystroke(fileName, position, key, localOptions); + }); + }; + LanguageServiceShimObject.prototype.getDocCommentTemplateAtPosition = function (fileName, position) { + var _this = this; + return this.forwardJSONCall("getDocCommentTemplateAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getDocCommentTemplateAtPosition(fileName, position); }); + }; + /// NAVIGATE TO + /** Return a list of symbols that are interesting to navigate to */ + LanguageServiceShimObject.prototype.getNavigateToItems = function (searchValue, maxResultCount, fileName) { + var _this = this; + return this.forwardJSONCall("getNavigateToItems('" + searchValue + "', " + maxResultCount + ", " + fileName + ")", function () { return _this.languageService.getNavigateToItems(searchValue, maxResultCount, fileName); }); + }; + LanguageServiceShimObject.prototype.getNavigationBarItems = function (fileName) { + var _this = this; + return this.forwardJSONCall("getNavigationBarItems('" + fileName + "')", function () { return _this.languageService.getNavigationBarItems(fileName); }); + }; + LanguageServiceShimObject.prototype.getNavigationTree = function (fileName) { + var _this = this; + return this.forwardJSONCall("getNavigationTree('" + fileName + "')", function () { return _this.languageService.getNavigationTree(fileName); }); + }; + LanguageServiceShimObject.prototype.getOutliningSpans = function (fileName) { + var _this = this; + return this.forwardJSONCall("getOutliningSpans('" + fileName + "')", function () { return _this.languageService.getOutliningSpans(fileName); }); + }; + LanguageServiceShimObject.prototype.getTodoComments = function (fileName, descriptors) { + var _this = this; + return this.forwardJSONCall("getTodoComments('" + fileName + "')", function () { return _this.languageService.getTodoComments(fileName, JSON.parse(descriptors)); }); + }; + /// Emit + LanguageServiceShimObject.prototype.getEmitOutput = function (fileName) { + var _this = this; + return this.forwardJSONCall("getEmitOutput('" + fileName + "')", function () { return _this.languageService.getEmitOutput(fileName); }); + }; + LanguageServiceShimObject.prototype.getEmitOutputObject = function (fileName) { + var _this = this; + return forwardCall(this.logger, "getEmitOutput('" + fileName + "')", + /*returnJson*/ false, function () { return _this.languageService.getEmitOutput(fileName); }, this.logPerformance); + }; + return LanguageServiceShimObject; + }(ShimBase)); + function convertClassifications(classifications) { + return { spans: classifications.spans.join(","), endOfLineState: classifications.endOfLineState }; + } + var ClassifierShimObject = /** @class */ (function (_super) { + __extends(ClassifierShimObject, _super); + function ClassifierShimObject(factory, logger) { + var _this = _super.call(this, factory) || this; + _this.logger = logger; + _this.logPerformance = false; + _this.classifier = ts.createClassifier(); + return _this; + } + ClassifierShimObject.prototype.getEncodedLexicalClassifications = function (text, lexState, syntacticClassifierAbsent) { + var _this = this; + if (syntacticClassifierAbsent === void 0) { syntacticClassifierAbsent = false; } + return forwardJSONCall(this.logger, "getEncodedLexicalClassifications", function () { return convertClassifications(_this.classifier.getEncodedLexicalClassifications(text, lexState, syntacticClassifierAbsent)); }, this.logPerformance); + }; + /// COLORIZATION + ClassifierShimObject.prototype.getClassificationsForLine = function (text, lexState, classifyKeywordsInGenerics) { + if (classifyKeywordsInGenerics === void 0) { classifyKeywordsInGenerics = false; } + var classification = this.classifier.getClassificationsForLine(text, lexState, classifyKeywordsInGenerics); + var result = ""; + for (var _i = 0, _a = classification.entries; _i < _a.length; _i++) { + var item = _a[_i]; + result += item.length + "\n"; + result += item.classification + "\n"; + } + result += classification.finalLexState; + return result; + }; + return ClassifierShimObject; + }(ShimBase)); + var CoreServicesShimObject = /** @class */ (function (_super) { + __extends(CoreServicesShimObject, _super); + function CoreServicesShimObject(factory, logger, host) { + var _this = _super.call(this, factory) || this; + _this.logger = logger; + _this.host = host; + _this.logPerformance = false; + return _this; + } + CoreServicesShimObject.prototype.forwardJSONCall = function (actionDescription, action) { + return forwardJSONCall(this.logger, actionDescription, action, this.logPerformance); + }; + CoreServicesShimObject.prototype.resolveModuleName = function (fileName, moduleName, compilerOptionsJson) { + var _this = this; + return this.forwardJSONCall("resolveModuleName('" + fileName + "')", function () { + var compilerOptions = JSON.parse(compilerOptionsJson); + var result = ts.resolveModuleName(moduleName, ts.normalizeSlashes(fileName), compilerOptions, _this.host); + var resolvedFileName = result.resolvedModule ? result.resolvedModule.resolvedFileName : undefined; + if (result.resolvedModule && result.resolvedModule.extension !== ".ts" /* Ts */ && result.resolvedModule.extension !== ".tsx" /* Tsx */ && result.resolvedModule.extension !== ".d.ts" /* Dts */) { + resolvedFileName = undefined; + } + return { + resolvedFileName: resolvedFileName, + failedLookupLocations: result.failedLookupLocations + }; + }); + }; + CoreServicesShimObject.prototype.resolveTypeReferenceDirective = function (fileName, typeReferenceDirective, compilerOptionsJson) { + var _this = this; + return this.forwardJSONCall("resolveTypeReferenceDirective(" + fileName + ")", function () { + var compilerOptions = JSON.parse(compilerOptionsJson); + var result = ts.resolveTypeReferenceDirective(typeReferenceDirective, ts.normalizeSlashes(fileName), compilerOptions, _this.host); + return { + resolvedFileName: result.resolvedTypeReferenceDirective ? result.resolvedTypeReferenceDirective.resolvedFileName : undefined, + primary: result.resolvedTypeReferenceDirective ? result.resolvedTypeReferenceDirective.primary : true, + failedLookupLocations: result.failedLookupLocations + }; + }); + }; + CoreServicesShimObject.prototype.getPreProcessedFileInfo = function (fileName, sourceTextSnapshot) { + var _this = this; + return this.forwardJSONCall("getPreProcessedFileInfo('" + fileName + "')", function () { + // for now treat files as JavaScript + var result = ts.preProcessFile(ts.getSnapshotText(sourceTextSnapshot), /* readImportFiles */ true, /* detectJavaScriptImports */ true); + return { + referencedFiles: _this.convertFileReferences(result.referencedFiles), + importedFiles: _this.convertFileReferences(result.importedFiles), + ambientExternalModules: result.ambientExternalModules, + isLibFile: result.isLibFile, + typeReferenceDirectives: _this.convertFileReferences(result.typeReferenceDirectives), + libReferenceDirectives: _this.convertFileReferences(result.libReferenceDirectives) + }; + }); + }; + CoreServicesShimObject.prototype.getAutomaticTypeDirectiveNames = function (compilerOptionsJson) { + var _this = this; + return this.forwardJSONCall("getAutomaticTypeDirectiveNames('" + compilerOptionsJson + "')", function () { + var compilerOptions = JSON.parse(compilerOptionsJson); + return ts.getAutomaticTypeDirectiveNames(compilerOptions, _this.host); + }); + }; + CoreServicesShimObject.prototype.convertFileReferences = function (refs) { + if (!refs) { + return undefined; + } + var result = []; + for (var _i = 0, refs_1 = refs; _i < refs_1.length; _i++) { + var ref = refs_1[_i]; + result.push({ + path: ts.normalizeSlashes(ref.fileName), + position: ref.pos, + length: ref.end - ref.pos + }); + } + return result; + }; + CoreServicesShimObject.prototype.getTSConfigFileInfo = function (fileName, sourceTextSnapshot) { + var _this = this; + return this.forwardJSONCall("getTSConfigFileInfo('" + fileName + "')", function () { + var result = ts.parseJsonText(fileName, ts.getSnapshotText(sourceTextSnapshot)); + var normalizedFileName = ts.normalizeSlashes(fileName); + var configFile = ts.parseJsonSourceFileConfigFileContent(result, _this.host, ts.getDirectoryPath(normalizedFileName), /*existingOptions*/ {}, normalizedFileName); + return { + options: configFile.options, + typeAcquisition: configFile.typeAcquisition, + files: configFile.fileNames, + raw: configFile.raw, + errors: realizeDiagnostics(result.parseDiagnostics.concat(configFile.errors), "\r\n") + }; + }); + }; + CoreServicesShimObject.prototype.getDefaultCompilationSettings = function () { + return this.forwardJSONCall("getDefaultCompilationSettings()", function () { return ts.getDefaultCompilerOptions(); }); + }; + CoreServicesShimObject.prototype.discoverTypings = function (discoverTypingsJson) { + var _this = this; + var getCanonicalFileName = ts.createGetCanonicalFileName(/*useCaseSensitivefileNames:*/ false); + return this.forwardJSONCall("discoverTypings()", function () { + var info = JSON.parse(discoverTypingsJson); + if (_this.safeList === undefined) { + _this.safeList = ts.JsTyping.loadSafeList(_this.host, ts.toPath(info.safeListPath, info.safeListPath, getCanonicalFileName)); + } + return ts.JsTyping.discoverTypings(_this.host, function (msg) { return _this.logger.log(msg); }, info.fileNames, ts.toPath(info.projectRootPath, info.projectRootPath, getCanonicalFileName), _this.safeList, info.packageNameToTypingLocation, info.typeAcquisition, info.unresolvedImports, info.typesRegistry); + }); + }; + return CoreServicesShimObject; + }(ShimBase)); + var TypeScriptServicesFactory = /** @class */ (function () { + function TypeScriptServicesFactory() { + this._shims = []; + } + /* + * Returns script API version. + */ + TypeScriptServicesFactory.prototype.getServicesVersion = function () { + return ts.servicesVersion; + }; + TypeScriptServicesFactory.prototype.createLanguageServiceShim = function (host) { + try { + if (this.documentRegistry === undefined) { + this.documentRegistry = ts.createDocumentRegistry(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames(), host.getCurrentDirectory()); + } + var hostAdapter = new LanguageServiceShimHostAdapter(host); + var languageService = ts.createLanguageService(hostAdapter, this.documentRegistry, /*syntaxOnly*/ false); + return new LanguageServiceShimObject(this, host, languageService); + } + catch (err) { + logInternalError(host, err); + throw err; + } + }; + TypeScriptServicesFactory.prototype.createClassifierShim = function (logger) { + try { + return new ClassifierShimObject(this, logger); + } + catch (err) { + logInternalError(logger, err); + throw err; + } + }; + TypeScriptServicesFactory.prototype.createCoreServicesShim = function (host) { + try { + var adapter = new CoreServicesShimHostAdapter(host); + return new CoreServicesShimObject(this, host, adapter); + } + catch (err) { + logInternalError(host, err); + throw err; + } + }; + TypeScriptServicesFactory.prototype.close = function () { + // Forget all the registered shims + ts.clear(this._shims); + this.documentRegistry = undefined; + }; + TypeScriptServicesFactory.prototype.registerShim = function (shim) { + this._shims.push(shim); + }; + TypeScriptServicesFactory.prototype.unregisterShim = function (shim) { + for (var i = 0; i < this._shims.length; i++) { + if (this._shims[i] === shim) { + delete this._shims[i]; + return; + } + } + throw new Error("Invalid operation"); + }; + return TypeScriptServicesFactory; + }()); + ts.TypeScriptServicesFactory = TypeScriptServicesFactory; + if (typeof module !== "undefined" && module.exports) { + module.exports = ts; + } +})(ts || (ts = {})); +/* tslint:enable:no-in-operator */ +/* tslint:enable:no-null */ +/// TODO: this is used by VS, clean this up on both sides of the interface +/* @internal */ +var TypeScript; +(function (TypeScript) { + var Services; + (function (Services) { + Services.TypeScriptServicesFactory = ts.TypeScriptServicesFactory; + })(Services = TypeScript.Services || (TypeScript.Services = {})); +})(TypeScript || (TypeScript = {})); +// 'toolsVersion' gets consumed by the managed side, so it's not unused. +// TODO: it should be moved into a namespace though. +/* @internal */ +var toolsVersion = ts.versionMajorMinor; +//# sourceMappingURL=services.js.map +"use strict"; +/* @internal */ +var ts; +(function (ts) { + var server; + (function (server) { + // tslint:disable variable-name + server.ActionSet = "action::set"; + server.ActionInvalidate = "action::invalidate"; + server.ActionPackageInstalled = "action::packageInstalled"; + server.ActionValueInspected = "action::valueInspected"; + server.EventTypesRegistry = "event::typesRegistry"; + server.EventBeginInstallTypes = "event::beginInstallTypes"; + server.EventEndInstallTypes = "event::endInstallTypes"; + server.EventInitializationFailed = "event::initializationFailed"; + var Arguments; + (function (Arguments) { + Arguments.GlobalCacheLocation = "--globalTypingsCacheLocation"; + Arguments.LogFile = "--logFile"; + Arguments.EnableTelemetry = "--enableTelemetry"; + Arguments.TypingSafeListLocation = "--typingSafeListLocation"; + Arguments.TypesMapLocation = "--typesMapLocation"; + /** + * This argument specifies the location of the NPM executable. + * typingsInstaller will run the command with `${npmLocation} install ...`. + */ + Arguments.NpmLocation = "--npmLocation"; + })(Arguments = server.Arguments || (server.Arguments = {})); + function hasArgument(argumentName) { + return ts.sys.args.indexOf(argumentName) >= 0; + } + server.hasArgument = hasArgument; + function findArgument(argumentName) { + var index = ts.sys.args.indexOf(argumentName); + return index >= 0 && index < ts.sys.args.length - 1 + ? ts.sys.args[index + 1] + : undefined; + } + server.findArgument = findArgument; + function nowString() { + // E.g. "12:34:56.789" + var d = new Date(); + return d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds() + "." + d.getMilliseconds(); + } + server.nowString = nowString; + })(server = ts.server || (ts.server = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var JsTyping; + (function (JsTyping) { + function isTypingUpToDate(cachedTyping, availableTypingVersions) { + var availableVersion = new ts.Version(ts.getProperty(availableTypingVersions, "ts" + ts.versionMajorMinor) || ts.getProperty(availableTypingVersions, "latest")); + return availableVersion.compareTo(cachedTyping.version) <= 0; + } + JsTyping.isTypingUpToDate = isTypingUpToDate; + JsTyping.nodeCoreModuleList = [ + "assert", + "async_hooks", + "buffer", + "child_process", + "cluster", + "console", + "constants", + "crypto", + "dgram", + "dns", + "domain", + "events", + "fs", + "http", + "https", + "http2", + "inspector", + "net", + "os", + "path", + "perf_hooks", + "process", + "punycode", + "querystring", + "readline", + "repl", + "stream", + "string_decoder", + "timers", + "tls", + "tty", + "url", + "util", + "v8", + "vm", + "zlib" + ]; + JsTyping.nodeCoreModules = ts.arrayToSet(JsTyping.nodeCoreModuleList); + function loadSafeList(host, safeListPath) { + var result = ts.readConfigFile(safeListPath, function (path) { return host.readFile(path); }); + return ts.createMapFromTemplate(result.config); + } + JsTyping.loadSafeList = loadSafeList; + function loadTypesMap(host, typesMapPath) { + var result = ts.readConfigFile(typesMapPath, function (path) { return host.readFile(path); }); + if (result.config) { + return ts.createMapFromTemplate(result.config.simpleMap); + } + return undefined; + } + JsTyping.loadTypesMap = loadTypesMap; + /** + * @param host is the object providing I/O related operations. + * @param fileNames are the file names that belong to the same project + * @param projectRootPath is the path to the project root directory + * @param safeListPath is the path used to retrieve the safe list + * @param packageNameToTypingLocation is the map of package names to their cached typing locations and installed versions + * @param typeAcquisition is used to customize the typing acquisition process + * @param compilerOptions are used as a source for typing inference + */ + function discoverTypings(host, log, fileNames, projectRootPath, safeList, packageNameToTypingLocation, typeAcquisition, unresolvedImports, typesRegistry) { + if (!typeAcquisition || !typeAcquisition.enable) { + return { cachedTypingPaths: [], newTypingNames: [], filesToWatch: [] }; + } + // A typing name to typing file path mapping + var inferredTypings = ts.createMap(); + // Only infer typings for .js and .jsx files + fileNames = ts.mapDefined(fileNames, function (fileName) { + var path = ts.normalizePath(fileName); + if (ts.hasJSFileExtension(path)) { + return path; + } + }); + var filesToWatch = []; + if (typeAcquisition.include) + addInferredTypings(typeAcquisition.include, "Explicitly included types"); + var exclude = typeAcquisition.exclude || []; + // Directories to search for package.json, bower.json and other typing information + var possibleSearchDirs = ts.arrayToSet(fileNames, ts.getDirectoryPath); + possibleSearchDirs.set(projectRootPath, true); + possibleSearchDirs.forEach(function (_true, searchDir) { + var packageJsonPath = ts.combinePaths(searchDir, "package.json"); + getTypingNamesFromJson(packageJsonPath, filesToWatch); + var bowerJsonPath = ts.combinePaths(searchDir, "bower.json"); + getTypingNamesFromJson(bowerJsonPath, filesToWatch); + var bowerComponentsPath = ts.combinePaths(searchDir, "bower_components"); + getTypingNamesFromPackagesFolder(bowerComponentsPath, filesToWatch); + var nodeModulesPath = ts.combinePaths(searchDir, "node_modules"); + getTypingNamesFromPackagesFolder(nodeModulesPath, filesToWatch); + }); + getTypingNamesFromSourceFileNames(fileNames); + // add typings for unresolved imports + if (unresolvedImports) { + var module_1 = ts.deduplicate(unresolvedImports.map(function (moduleId) { return JsTyping.nodeCoreModules.has(moduleId) ? "node" : moduleId; }), ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive); + addInferredTypings(module_1, "Inferred typings from unresolved imports"); + } + // Add the cached typing locations for inferred typings that are already installed + packageNameToTypingLocation.forEach(function (typing, name) { + var registryEntry = typesRegistry.get(name); + if (inferredTypings.has(name) && inferredTypings.get(name) === undefined && registryEntry !== undefined && isTypingUpToDate(typing, registryEntry)) { + inferredTypings.set(name, typing.typingLocation); + } + }); + // Remove typings that the user has added to the exclude list + for (var _i = 0, exclude_1 = exclude; _i < exclude_1.length; _i++) { + var excludeTypingName = exclude_1[_i]; + var didDelete = inferredTypings.delete(excludeTypingName); + if (didDelete && log) + log("Typing for " + excludeTypingName + " is in exclude list, will be ignored."); + } + var newTypingNames = []; + var cachedTypingPaths = []; + inferredTypings.forEach(function (inferred, typing) { + if (inferred !== undefined) { + cachedTypingPaths.push(inferred); + } + else { + newTypingNames.push(typing); + } + }); + var result = { cachedTypingPaths: cachedTypingPaths, newTypingNames: newTypingNames, filesToWatch: filesToWatch }; + if (log) + log("Result: " + JSON.stringify(result)); + return result; + function addInferredTyping(typingName) { + if (!inferredTypings.has(typingName)) { + inferredTypings.set(typingName, undefined); // TODO: GH#18217 + } + } + function addInferredTypings(typingNames, message) { + if (log) + log(message + ": " + JSON.stringify(typingNames)); + ts.forEach(typingNames, addInferredTyping); + } + /** + * Get the typing info from common package manager json files like package.json or bower.json + */ + function getTypingNamesFromJson(jsonPath, filesToWatch) { + if (!host.fileExists(jsonPath)) { + return; + } + filesToWatch.push(jsonPath); + var jsonConfig = ts.readConfigFile(jsonPath, function (path) { return host.readFile(path); }).config; + var jsonTypingNames = ts.flatMap([jsonConfig.dependencies, jsonConfig.devDependencies, jsonConfig.optionalDependencies, jsonConfig.peerDependencies], ts.getOwnKeys); + addInferredTypings(jsonTypingNames, "Typing names in '" + jsonPath + "' dependencies"); + } + /** + * Infer typing names from given file names. For example, the file name "jquery-min.2.3.4.js" + * should be inferred to the 'jquery' typing name; and "angular-route.1.2.3.js" should be inferred + * to the 'angular-route' typing name. + * @param fileNames are the names for source files in the project + */ + function getTypingNamesFromSourceFileNames(fileNames) { + var fromFileNames = ts.mapDefined(fileNames, function (j) { + if (!ts.hasJSFileExtension(j)) + return undefined; + var inferredTypingName = ts.removeFileExtension(ts.getBaseFileName(j.toLowerCase())); + var cleanedTypingName = ts.removeMinAndVersionNumbers(inferredTypingName); + return safeList.get(cleanedTypingName); + }); + if (fromFileNames.length) { + addInferredTypings(fromFileNames, "Inferred typings from file names"); + } + var hasJsxFile = ts.some(fileNames, function (f) { return ts.fileExtensionIs(f, ".jsx" /* Jsx */); }); + if (hasJsxFile) { + if (log) + log("Inferred 'react' typings due to presence of '.jsx' extension"); + addInferredTyping("react"); + } + } + /** + * Infer typing names from packages folder (ex: node_module, bower_components) + * @param packagesFolderPath is the path to the packages folder + */ + function getTypingNamesFromPackagesFolder(packagesFolderPath, filesToWatch) { + filesToWatch.push(packagesFolderPath); + // Todo: add support for ModuleResolutionHost too + if (!host.directoryExists(packagesFolderPath)) { + return; + } + // depth of 2, so we access `node_modules/foo` but not `node_modules/foo/bar` + var fileNames = host.readDirectory(packagesFolderPath, [".json" /* Json */], /*excludes*/ undefined, /*includes*/ undefined, /*depth*/ 2); + if (log) + log("Searching for typing names in " + packagesFolderPath + "; all files: " + JSON.stringify(fileNames)); + var packageNames = []; + for (var _i = 0, fileNames_1 = fileNames; _i < fileNames_1.length; _i++) { + var fileName = fileNames_1[_i]; + var normalizedFileName = ts.normalizePath(fileName); + var baseFileName = ts.getBaseFileName(normalizedFileName); + if (baseFileName !== "package.json" && baseFileName !== "bower.json") { + continue; + } + var result_1 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); }); + var packageJson = result_1.config; + // npm 3's package.json contains a "_requiredBy" field + // we should include all the top level module names for npm 2, and only module names whose + // "_requiredBy" field starts with "#" or equals "/" for npm 3. + if (baseFileName === "package.json" && packageJson._requiredBy && + ts.filter(packageJson._requiredBy, function (r) { return r[0] === "#" || r === "/"; }).length === 0) { + continue; + } + // If the package has its own d.ts typings, those will take precedence. Otherwise the package name will be used + // to download d.ts files from DefinitelyTyped + if (!packageJson.name) { + continue; + } + var ownTypes = packageJson.types || packageJson.typings; + if (ownTypes) { + var absolutePath = ts.getNormalizedAbsolutePath(ownTypes, ts.getDirectoryPath(normalizedFileName)); + if (log) + log(" Package '" + packageJson.name + "' provides its own types."); + inferredTypings.set(packageJson.name, absolutePath); + } + else { + packageNames.push(packageJson.name); + } + } + addInferredTypings(packageNames, " Found package names"); + } + } + JsTyping.discoverTypings = discoverTypings; + var PackageNameValidationResult; + (function (PackageNameValidationResult) { + PackageNameValidationResult[PackageNameValidationResult["Ok"] = 0] = "Ok"; + PackageNameValidationResult[PackageNameValidationResult["ScopedPackagesNotSupported"] = 1] = "ScopedPackagesNotSupported"; + PackageNameValidationResult[PackageNameValidationResult["EmptyName"] = 2] = "EmptyName"; + PackageNameValidationResult[PackageNameValidationResult["NameTooLong"] = 3] = "NameTooLong"; + PackageNameValidationResult[PackageNameValidationResult["NameStartsWithDot"] = 4] = "NameStartsWithDot"; + PackageNameValidationResult[PackageNameValidationResult["NameStartsWithUnderscore"] = 5] = "NameStartsWithUnderscore"; + PackageNameValidationResult[PackageNameValidationResult["NameContainsNonURISafeCharacters"] = 6] = "NameContainsNonURISafeCharacters"; + })(PackageNameValidationResult = JsTyping.PackageNameValidationResult || (JsTyping.PackageNameValidationResult = {})); + var maxPackageNameLength = 214; + /** + * Validates package name using rules defined at https://docs.npmjs.com/files/package.json + */ + function validatePackageName(packageName) { + if (!packageName) { + return 2 /* EmptyName */; + } + if (packageName.length > maxPackageNameLength) { + return 3 /* NameTooLong */; + } + if (packageName.charCodeAt(0) === 46 /* dot */) { + return 4 /* NameStartsWithDot */; + } + if (packageName.charCodeAt(0) === 95 /* _ */) { + return 5 /* NameStartsWithUnderscore */; + } + // check if name is scope package like: starts with @ and has one '/' in the middle + // scoped packages are not currently supported + // TODO: when support will be added we'll need to split and check both scope and package name + if (/^@[^/]+\/[^/]+$/.test(packageName)) { + return 1 /* ScopedPackagesNotSupported */; + } + if (encodeURIComponent(packageName) !== packageName) { + return 6 /* NameContainsNonURISafeCharacters */; + } + return 0 /* Ok */; + } + JsTyping.validatePackageName = validatePackageName; + function renderPackageNameValidationFailure(result, typing) { + switch (result) { + case 2 /* EmptyName */: + return "Package name '" + typing + "' cannot be empty"; + case 3 /* NameTooLong */: + return "Package name '" + typing + "' should be less than " + maxPackageNameLength + " characters"; + case 4 /* NameStartsWithDot */: + return "Package name '" + typing + "' cannot start with '.'"; + case 5 /* NameStartsWithUnderscore */: + return "Package name '" + typing + "' cannot start with '_'"; + case 1 /* ScopedPackagesNotSupported */: + return "Package '" + typing + "' is scoped and currently is not supported"; + case 6 /* NameContainsNonURISafeCharacters */: + return "Package name '" + typing + "' contains non URI safe characters"; + case 0 /* Ok */: + return ts.Debug.fail(); // Shouldn't have called this. + default: + throw ts.Debug.assertNever(result); + } + } + JsTyping.renderPackageNameValidationFailure = renderPackageNameValidationFailure; + })(JsTyping = ts.JsTyping || (ts.JsTyping = {})); +})(ts || (ts = {})); +//# sourceMappingURL=jsTyping.js.map +"use strict"; +var __assign = (this && this.__assign) || function () { + __assign = Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; + }; + return __assign.apply(this, arguments); +}; +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +var __rest = (this && this.__rest) || function (s, e) { + var t = {}; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) + t[p] = s[p]; + if (s != null && typeof Object.getOwnPropertySymbols === "function") + for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) if (e.indexOf(p[i]) < 0) + t[p[i]] = s[p[i]]; + return t; +}; +var ts; +(function (ts) { + var server; + (function (server) { + var LogLevel; + (function (LogLevel) { + LogLevel[LogLevel["terse"] = 0] = "terse"; + LogLevel[LogLevel["normal"] = 1] = "normal"; + LogLevel[LogLevel["requestTime"] = 2] = "requestTime"; + LogLevel[LogLevel["verbose"] = 3] = "verbose"; + })(LogLevel = server.LogLevel || (server.LogLevel = {})); + server.emptyArray = createSortedArray(); + var Msg; + (function (Msg) { + Msg["Err"] = "Err"; + Msg["Info"] = "Info"; + Msg["Perf"] = "Perf"; + })(Msg = server.Msg || (server.Msg = {})); + function createInstallTypingsRequest(project, typeAcquisition, unresolvedImports, cachePath) { + return { + projectName: project.getProjectName(), + fileNames: project.getFileNames(true, true).concat(project.getExcludedFiles()), + compilerOptions: project.getCompilationSettings(), + typeAcquisition: typeAcquisition, + unresolvedImports: unresolvedImports, + projectRootPath: project.getCurrentDirectory(), + cachePath: cachePath, + kind: "discover" + }; + } + server.createInstallTypingsRequest = createInstallTypingsRequest; + var Errors; + (function (Errors) { + function ThrowNoProject() { + throw new Error("No Project."); + } + Errors.ThrowNoProject = ThrowNoProject; + function ThrowProjectLanguageServiceDisabled() { + throw new Error("The project's language service is disabled."); + } + Errors.ThrowProjectLanguageServiceDisabled = ThrowProjectLanguageServiceDisabled; + function ThrowProjectDoesNotContainDocument(fileName, project) { + throw new Error("Project '" + project.getProjectName() + "' does not contain document '" + fileName + "'"); + } + Errors.ThrowProjectDoesNotContainDocument = ThrowProjectDoesNotContainDocument; + })(Errors = server.Errors || (server.Errors = {})); + function toNormalizedPath(fileName) { + return ts.normalizePath(fileName); + } + server.toNormalizedPath = toNormalizedPath; + function normalizedPathToPath(normalizedPath, currentDirectory, getCanonicalFileName) { + var f = ts.isRootedDiskPath(normalizedPath) ? normalizedPath : ts.getNormalizedAbsolutePath(normalizedPath, currentDirectory); + return getCanonicalFileName(f); + } + server.normalizedPathToPath = normalizedPathToPath; + function asNormalizedPath(fileName) { + return fileName; + } + server.asNormalizedPath = asNormalizedPath; + function createNormalizedPathMap() { + var map = ts.createMap(); + return { + get: function (path) { + return map.get(path); + }, + set: function (path, value) { + map.set(path, value); + }, + contains: function (path) { + return map.has(path); + }, + remove: function (path) { + map.delete(path); + } + }; + } + server.createNormalizedPathMap = createNormalizedPathMap; + function isInferredProjectName(name) { + return /dev\/null\/inferredProject\d+\*/.test(name); + } + server.isInferredProjectName = isInferredProjectName; + function makeInferredProjectName(counter) { + return "/dev/null/inferredProject" + counter + "*"; + } + server.makeInferredProjectName = makeInferredProjectName; + function createSortedArray() { + return []; + } + server.createSortedArray = createSortedArray; + })(server = ts.server || (ts.server = {})); +})(ts || (ts = {})); +(function (ts) { + var server; + (function (server) { + var ThrottledOperations = (function () { + function ThrottledOperations(host, logger) { + this.host = host; + this.pendingTimeouts = ts.createMap(); + this.logger = logger.hasLevel(server.LogLevel.verbose) ? logger : undefined; + } + ThrottledOperations.prototype.schedule = function (operationId, delay, cb) { + var pendingTimeout = this.pendingTimeouts.get(operationId); + if (pendingTimeout) { + this.host.clearTimeout(pendingTimeout); + } + this.pendingTimeouts.set(operationId, this.host.setTimeout(ThrottledOperations.run, delay, this, operationId, cb)); + if (this.logger) { + this.logger.info("Scheduled: " + operationId + (pendingTimeout ? ", Cancelled earlier one" : "")); + } + }; + ThrottledOperations.run = function (self, operationId, cb) { + self.pendingTimeouts.delete(operationId); + if (self.logger) { + self.logger.info("Running: " + operationId); + } + cb(); + }; + return ThrottledOperations; + }()); + server.ThrottledOperations = ThrottledOperations; + var GcTimer = (function () { + function GcTimer(host, delay, logger) { + this.host = host; + this.delay = delay; + this.logger = logger; + } + GcTimer.prototype.scheduleCollect = function () { + if (!this.host.gc || this.timerId !== undefined) { + return; + } + this.timerId = this.host.setTimeout(GcTimer.run, this.delay, this); + }; + GcTimer.run = function (self) { + self.timerId = undefined; + var log = self.logger.hasLevel(server.LogLevel.requestTime); + var before = log && self.host.getMemoryUsage(); + self.host.gc(); + if (log) { + var after = self.host.getMemoryUsage(); + self.logger.perftrc("GC::before " + before + ", after " + after); + } + }; + return GcTimer; + }()); + server.GcTimer = GcTimer; + function getBaseConfigFileName(configFilePath) { + var base = ts.getBaseFileName(configFilePath); + return base === "tsconfig.json" || base === "jsconfig.json" ? base : undefined; + } + server.getBaseConfigFileName = getBaseConfigFileName; + function removeSorted(array, remove, compare) { + if (!array || array.length === 0) { + return; + } + if (array[0] === remove) { + array.splice(0, 1); + return; + } + var removeIndex = ts.binarySearch(array, remove, ts.identity, compare); + if (removeIndex >= 0) { + array.splice(removeIndex, 1); + } + } + server.removeSorted = removeSorted; + var indentStr = "\n "; + function indent(str) { + return indentStr + str.replace(/\n/g, indentStr); + } + server.indent = indent; + function stringifyIndented(json) { + return indentStr + JSON.stringify(json); + } + server.stringifyIndented = stringifyIndented; + })(server = ts.server || (ts.server = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + var server; + (function (server) { + var protocol; + (function (protocol) { + var CommandTypes; + (function (CommandTypes) { + CommandTypes["JsxClosingTag"] = "jsxClosingTag"; + CommandTypes["Brace"] = "brace"; + CommandTypes["BraceFull"] = "brace-full"; + CommandTypes["BraceCompletion"] = "braceCompletion"; + CommandTypes["GetSpanOfEnclosingComment"] = "getSpanOfEnclosingComment"; + CommandTypes["Change"] = "change"; + CommandTypes["Close"] = "close"; + CommandTypes["Completions"] = "completions"; + CommandTypes["CompletionInfo"] = "completionInfo"; + CommandTypes["CompletionsFull"] = "completions-full"; + CommandTypes["CompletionDetails"] = "completionEntryDetails"; + CommandTypes["CompletionDetailsFull"] = "completionEntryDetails-full"; + CommandTypes["CompileOnSaveAffectedFileList"] = "compileOnSaveAffectedFileList"; + CommandTypes["CompileOnSaveEmitFile"] = "compileOnSaveEmitFile"; + CommandTypes["Configure"] = "configure"; + CommandTypes["Definition"] = "definition"; + CommandTypes["DefinitionFull"] = "definition-full"; + CommandTypes["DefinitionAndBoundSpan"] = "definitionAndBoundSpan"; + CommandTypes["DefinitionAndBoundSpanFull"] = "definitionAndBoundSpan-full"; + CommandTypes["Implementation"] = "implementation"; + CommandTypes["ImplementationFull"] = "implementation-full"; + CommandTypes["EmitOutput"] = "emit-output"; + CommandTypes["Exit"] = "exit"; + CommandTypes["Format"] = "format"; + CommandTypes["Formatonkey"] = "formatonkey"; + CommandTypes["FormatFull"] = "format-full"; + CommandTypes["FormatonkeyFull"] = "formatonkey-full"; + CommandTypes["FormatRangeFull"] = "formatRange-full"; + CommandTypes["Geterr"] = "geterr"; + CommandTypes["GeterrForProject"] = "geterrForProject"; + CommandTypes["SemanticDiagnosticsSync"] = "semanticDiagnosticsSync"; + CommandTypes["SyntacticDiagnosticsSync"] = "syntacticDiagnosticsSync"; + CommandTypes["SuggestionDiagnosticsSync"] = "suggestionDiagnosticsSync"; + CommandTypes["NavBar"] = "navbar"; + CommandTypes["NavBarFull"] = "navbar-full"; + CommandTypes["Navto"] = "navto"; + CommandTypes["NavtoFull"] = "navto-full"; + CommandTypes["NavTree"] = "navtree"; + CommandTypes["NavTreeFull"] = "navtree-full"; + CommandTypes["Occurrences"] = "occurrences"; + CommandTypes["DocumentHighlights"] = "documentHighlights"; + CommandTypes["DocumentHighlightsFull"] = "documentHighlights-full"; + CommandTypes["Open"] = "open"; + CommandTypes["Quickinfo"] = "quickinfo"; + CommandTypes["QuickinfoFull"] = "quickinfo-full"; + CommandTypes["References"] = "references"; + CommandTypes["ReferencesFull"] = "references-full"; + CommandTypes["Reload"] = "reload"; + CommandTypes["Rename"] = "rename"; + CommandTypes["RenameInfoFull"] = "rename-full"; + CommandTypes["RenameLocationsFull"] = "renameLocations-full"; + CommandTypes["Saveto"] = "saveto"; + CommandTypes["SignatureHelp"] = "signatureHelp"; + CommandTypes["SignatureHelpFull"] = "signatureHelp-full"; + CommandTypes["Status"] = "status"; + CommandTypes["TypeDefinition"] = "typeDefinition"; + CommandTypes["ProjectInfo"] = "projectInfo"; + CommandTypes["ReloadProjects"] = "reloadProjects"; + CommandTypes["Unknown"] = "unknown"; + CommandTypes["OpenExternalProject"] = "openExternalProject"; + CommandTypes["OpenExternalProjects"] = "openExternalProjects"; + CommandTypes["CloseExternalProject"] = "closeExternalProject"; + CommandTypes["SynchronizeProjectList"] = "synchronizeProjectList"; + CommandTypes["ApplyChangedToOpenFiles"] = "applyChangedToOpenFiles"; + CommandTypes["EncodedSemanticClassificationsFull"] = "encodedSemanticClassifications-full"; + CommandTypes["Cleanup"] = "cleanup"; + CommandTypes["GetOutliningSpans"] = "getOutliningSpans"; + CommandTypes["GetOutliningSpansFull"] = "outliningSpans"; + CommandTypes["TodoComments"] = "todoComments"; + CommandTypes["Indentation"] = "indentation"; + CommandTypes["DocCommentTemplate"] = "docCommentTemplate"; + CommandTypes["CompilerOptionsDiagnosticsFull"] = "compilerOptionsDiagnostics-full"; + CommandTypes["NameOrDottedNameSpan"] = "nameOrDottedNameSpan"; + CommandTypes["BreakpointStatement"] = "breakpointStatement"; + CommandTypes["CompilerOptionsForInferredProjects"] = "compilerOptionsForInferredProjects"; + CommandTypes["GetCodeFixes"] = "getCodeFixes"; + CommandTypes["GetCodeFixesFull"] = "getCodeFixes-full"; + CommandTypes["GetCombinedCodeFix"] = "getCombinedCodeFix"; + CommandTypes["GetCombinedCodeFixFull"] = "getCombinedCodeFix-full"; + CommandTypes["ApplyCodeActionCommand"] = "applyCodeActionCommand"; + CommandTypes["GetSupportedCodeFixes"] = "getSupportedCodeFixes"; + CommandTypes["GetApplicableRefactors"] = "getApplicableRefactors"; + CommandTypes["GetEditsForRefactor"] = "getEditsForRefactor"; + CommandTypes["GetEditsForRefactorFull"] = "getEditsForRefactor-full"; + CommandTypes["OrganizeImports"] = "organizeImports"; + CommandTypes["OrganizeImportsFull"] = "organizeImports-full"; + CommandTypes["GetEditsForFileRename"] = "getEditsForFileRename"; + CommandTypes["GetEditsForFileRenameFull"] = "getEditsForFileRename-full"; + CommandTypes["ConfigurePlugin"] = "configurePlugin"; + })(CommandTypes = protocol.CommandTypes || (protocol.CommandTypes = {})); + var IndentStyle; + (function (IndentStyle) { + IndentStyle["None"] = "None"; + IndentStyle["Block"] = "Block"; + IndentStyle["Smart"] = "Smart"; + })(IndentStyle = protocol.IndentStyle || (protocol.IndentStyle = {})); + var JsxEmit; + (function (JsxEmit) { + JsxEmit["None"] = "None"; + JsxEmit["Preserve"] = "Preserve"; + JsxEmit["ReactNative"] = "ReactNative"; + JsxEmit["React"] = "React"; + })(JsxEmit = protocol.JsxEmit || (protocol.JsxEmit = {})); + var ModuleKind; + (function (ModuleKind) { + ModuleKind["None"] = "None"; + ModuleKind["CommonJS"] = "CommonJS"; + ModuleKind["AMD"] = "AMD"; + ModuleKind["UMD"] = "UMD"; + ModuleKind["System"] = "System"; + ModuleKind["ES6"] = "ES6"; + ModuleKind["ES2015"] = "ES2015"; + ModuleKind["ESNext"] = "ESNext"; + })(ModuleKind = protocol.ModuleKind || (protocol.ModuleKind = {})); + var ModuleResolutionKind; + (function (ModuleResolutionKind) { + ModuleResolutionKind["Classic"] = "Classic"; + ModuleResolutionKind["Node"] = "Node"; + })(ModuleResolutionKind = protocol.ModuleResolutionKind || (protocol.ModuleResolutionKind = {})); + var NewLineKind; + (function (NewLineKind) { + NewLineKind["Crlf"] = "Crlf"; + NewLineKind["Lf"] = "Lf"; + })(NewLineKind = protocol.NewLineKind || (protocol.NewLineKind = {})); + var ScriptTarget; + (function (ScriptTarget) { + ScriptTarget["ES3"] = "ES3"; + ScriptTarget["ES5"] = "ES5"; + ScriptTarget["ES6"] = "ES6"; + ScriptTarget["ES2015"] = "ES2015"; + ScriptTarget["ES2016"] = "ES2016"; + ScriptTarget["ES2017"] = "ES2017"; + ScriptTarget["ESNext"] = "ESNext"; + })(ScriptTarget = protocol.ScriptTarget || (protocol.ScriptTarget = {})); + })(protocol = server.protocol || (server.protocol = {})); + })(server = ts.server || (ts.server = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + var server; + (function (server) { + var TextStorage = (function () { + function TextStorage(host, fileName, initialVersion, info) { + this.host = host; + this.fileName = fileName; + this.info = info; + this.isOpen = false; + this.ownFileText = false; + this.pendingReloadFromDisk = false; + this.version = initialVersion || { svc: 0, text: 0 }; + } + TextStorage.prototype.getVersion = function () { + return this.svc + ? "SVC-" + this.version.svc + "-" + this.svc.getSnapshotVersion() + : "Text-" + this.version.text; + }; + TextStorage.prototype.hasScriptVersionCache_TestOnly = function () { + return this.svc !== undefined; + }; + TextStorage.prototype.useScriptVersionCache_TestOnly = function () { + this.switchToScriptVersionCache(); + }; + TextStorage.prototype.useText = function (newText) { + this.svc = undefined; + this.text = newText; + this.lineMap = undefined; + this.fileSize = undefined; + this.version.text++; + }; + TextStorage.prototype.edit = function (start, end, newText) { + this.switchToScriptVersionCache().edit(start, end - start, newText); + this.ownFileText = false; + this.text = undefined; + this.lineMap = undefined; + this.fileSize = undefined; + }; + TextStorage.prototype.reload = function (newText) { + ts.Debug.assert(newText !== undefined); + this.pendingReloadFromDisk = false; + if (this.text !== newText) { + this.useText(newText); + this.ownFileText = false; + return true; + } + return false; + }; + TextStorage.prototype.reloadWithFileText = function (tempFileName) { + var _a = this.getFileTextAndSize(tempFileName), newText = _a.text, fileSize = _a.fileSize; + var reloaded = this.reload(newText); + this.fileSize = fileSize; + this.ownFileText = !tempFileName || tempFileName === this.fileName; + return reloaded; + }; + TextStorage.prototype.reloadFromDisk = function () { + if (!this.pendingReloadFromDisk && !this.ownFileText) { + return this.reloadWithFileText(); + } + return false; + }; + TextStorage.prototype.delayReloadFromFileIntoText = function () { + this.pendingReloadFromDisk = true; + }; + TextStorage.prototype.getTelemetryFileSize = function () { + return !!this.fileSize + ? this.fileSize + : !!this.text + ? this.text.length + : !!this.svc + ? this.svc.getSnapshot().getLength() + : this.getSnapshot().getLength(); + }; + TextStorage.prototype.getSnapshot = function () { + return this.useScriptVersionCacheIfValidOrOpen() + ? this.svc.getSnapshot() + : ts.ScriptSnapshot.fromString(this.getOrLoadText()); + }; + TextStorage.prototype.getLineInfo = function (line) { + return this.switchToScriptVersionCache().getLineInfo(line); + }; + TextStorage.prototype.lineToTextSpan = function (line) { + if (!this.useScriptVersionCacheIfValidOrOpen()) { + var lineMap = this.getLineMap(); + var start = lineMap[line]; + var end = line + 1 < lineMap.length ? lineMap[line + 1] : this.text.length; + return ts.createTextSpanFromBounds(start, end); + } + return this.svc.lineToTextSpan(line); + }; + TextStorage.prototype.lineOffsetToPosition = function (line, offset) { + if (!this.useScriptVersionCacheIfValidOrOpen()) { + return ts.computePositionOfLineAndCharacter(this.getLineMap(), line - 1, offset - 1, this.text); + } + return this.svc.lineOffsetToPosition(line, offset); + }; + TextStorage.prototype.positionToLineOffset = function (position) { + if (!this.useScriptVersionCacheIfValidOrOpen()) { + var _a = ts.computeLineAndCharacterOfPosition(this.getLineMap(), position), line = _a.line, character = _a.character; + return { line: line + 1, offset: character + 1 }; + } + return this.svc.positionToLineOffset(position); + }; + TextStorage.prototype.getFileTextAndSize = function (tempFileName) { + var _this = this; + var text; + var fileName = tempFileName || this.fileName; + var getText = function () { return text === undefined ? (text = _this.host.readFile(fileName) || "") : text; }; + if (!ts.hasTSFileExtension(this.fileName)) { + var fileSize = this.host.getFileSize ? this.host.getFileSize(fileName) : getText().length; + if (fileSize > server.maxFileSize) { + ts.Debug.assert(!!this.info.containingProjects.length); + var service = this.info.containingProjects[0].projectService; + service.logger.info("Skipped loading contents of large file " + fileName + " for info " + this.info.fileName + ": fileSize: " + fileSize); + this.info.containingProjects[0].projectService.sendLargeFileReferencedEvent(fileName, fileSize); + return { text: "", fileSize: fileSize }; + } + } + return { text: getText() }; + }; + TextStorage.prototype.switchToScriptVersionCache = function () { + if (!this.svc || this.pendingReloadFromDisk) { + this.svc = server.ScriptVersionCache.fromString(this.getOrLoadText()); + this.version.svc++; + } + return this.svc; + }; + TextStorage.prototype.useScriptVersionCacheIfValidOrOpen = function () { + if (this.isOpen) { + return this.switchToScriptVersionCache(); + } + if (this.pendingReloadFromDisk) { + this.reloadWithFileText(); + } + return this.svc; + }; + TextStorage.prototype.getOrLoadText = function () { + if (this.text === undefined || this.pendingReloadFromDisk) { + ts.Debug.assert(!this.svc || this.pendingReloadFromDisk, "ScriptVersionCache should not be set when reloading from disk"); + this.reloadWithFileText(); + } + return this.text; + }; + TextStorage.prototype.getLineMap = function () { + ts.Debug.assert(!this.svc, "ScriptVersionCache should not be set"); + return this.lineMap || (this.lineMap = ts.computeLineStarts(this.getOrLoadText())); + }; + return TextStorage; + }()); + server.TextStorage = TextStorage; + function isDynamicFileName(fileName) { + return fileName[0] === "^" || ts.getBaseFileName(fileName)[0] === "^"; + } + server.isDynamicFileName = isDynamicFileName; + var ScriptInfo = (function () { + function ScriptInfo(host, fileName, scriptKind, hasMixedContent, path, initialVersion) { + this.host = host; + this.fileName = fileName; + this.scriptKind = scriptKind; + this.hasMixedContent = hasMixedContent; + this.path = path; + this.containingProjects = []; + this.isDynamic = isDynamicFileName(fileName); + this.textStorage = new TextStorage(host, fileName, initialVersion, this); + if (hasMixedContent || this.isDynamic) { + this.textStorage.reload(""); + this.realpath = this.path; + } + this.scriptKind = scriptKind + ? scriptKind + : ts.getScriptKindFromFileName(fileName); + } + ScriptInfo.prototype.getVersion = function () { + return this.textStorage.version; + }; + ScriptInfo.prototype.getTelemetryFileSize = function () { + return this.textStorage.getTelemetryFileSize(); + }; + ScriptInfo.prototype.isDynamicOrHasMixedContent = function () { + return this.hasMixedContent || this.isDynamic; + }; + ScriptInfo.prototype.isScriptOpen = function () { + return this.textStorage.isOpen; + }; + ScriptInfo.prototype.open = function (newText) { + this.textStorage.isOpen = true; + if (newText !== undefined && + this.textStorage.reload(newText)) { + this.markContainingProjectsAsDirty(); + } + }; + ScriptInfo.prototype.close = function (fileExists) { + if (fileExists === void 0) { fileExists = true; } + this.textStorage.isOpen = false; + if (this.isDynamicOrHasMixedContent() || !fileExists) { + if (this.textStorage.reload("")) { + this.markContainingProjectsAsDirty(); + } + } + else if (this.textStorage.reloadFromDisk()) { + this.markContainingProjectsAsDirty(); + } + }; + ScriptInfo.prototype.getSnapshot = function () { + return this.textStorage.getSnapshot(); + }; + ScriptInfo.prototype.ensureRealPath = function () { + if (this.realpath === undefined) { + this.realpath = this.path; + if (this.host.realpath) { + ts.Debug.assert(!!this.containingProjects.length); + var project = this.containingProjects[0]; + var realpath = this.host.realpath(this.path); + if (realpath) { + this.realpath = project.toPath(realpath); + if (this.realpath !== this.path) { + project.projectService.realpathToScriptInfos.add(this.realpath, this); + } + } + } + } + }; + ScriptInfo.prototype.getRealpathIfDifferent = function () { + return this.realpath && this.realpath !== this.path ? this.realpath : undefined; + }; + ScriptInfo.prototype.getFormatCodeSettings = function () { return this.formatSettings; }; + ScriptInfo.prototype.getPreferences = function () { return this.preferences; }; + ScriptInfo.prototype.attachToProject = function (project) { + var isNew = !this.isAttached(project); + if (isNew) { + this.containingProjects.push(project); + project.onFileAddedOrRemoved(); + if (!project.getCompilerOptions().preserveSymlinks) { + this.ensureRealPath(); + } + } + return isNew; + }; + ScriptInfo.prototype.isAttached = function (project) { + switch (this.containingProjects.length) { + case 0: return false; + case 1: return this.containingProjects[0] === project; + case 2: return this.containingProjects[0] === project || this.containingProjects[1] === project; + default: return ts.contains(this.containingProjects, project); + } + }; + ScriptInfo.prototype.detachFromProject = function (project) { + switch (this.containingProjects.length) { + case 0: + return; + case 1: + if (this.containingProjects[0] === project) { + project.onFileAddedOrRemoved(); + this.containingProjects.pop(); + } + break; + case 2: + if (this.containingProjects[0] === project) { + project.onFileAddedOrRemoved(); + this.containingProjects[0] = this.containingProjects.pop(); + } + else if (this.containingProjects[1] === project) { + project.onFileAddedOrRemoved(); + this.containingProjects.pop(); + } + break; + default: + if (ts.unorderedRemoveItem(this.containingProjects, project)) { + project.onFileAddedOrRemoved(); + } + break; + } + }; + ScriptInfo.prototype.detachAllProjects = function () { + for (var _i = 0, _a = this.containingProjects; _i < _a.length; _i++) { + var p = _a[_i]; + if (p.projectKind === server.ProjectKind.Configured) { + p.getCachedDirectoryStructureHost().addOrDeleteFile(this.fileName, this.path, ts.FileWatcherEventKind.Deleted); + } + var isInfoRoot = p.isRoot(this); + p.removeFile(this, false, false); + if (isInfoRoot && p.projectKind !== server.ProjectKind.Inferred) { + p.addMissingFileRoot(this.fileName); + } + } + ts.clear(this.containingProjects); + }; + ScriptInfo.prototype.getDefaultProject = function () { + switch (this.containingProjects.length) { + case 0: + return server.Errors.ThrowNoProject(); + case 1: + return this.containingProjects[0]; + default: + var firstExternalProject = void 0; + for (var _i = 0, _a = this.containingProjects; _i < _a.length; _i++) { + var project = _a[_i]; + if (project.projectKind === server.ProjectKind.Configured) { + return project; + } + else if (project.projectKind === server.ProjectKind.External && !firstExternalProject) { + firstExternalProject = project; + } + } + return firstExternalProject || this.containingProjects[0]; + } + }; + ScriptInfo.prototype.registerFileUpdate = function () { + for (var _i = 0, _a = this.containingProjects; _i < _a.length; _i++) { + var p = _a[_i]; + p.registerFileUpdate(this.path); + } + }; + ScriptInfo.prototype.setOptions = function (formatSettings, preferences) { + if (formatSettings) { + if (!this.formatSettings) { + this.formatSettings = ts.getDefaultFormatCodeSettings(this.host.newLine); + ts.assign(this.formatSettings, formatSettings); + } + else { + this.formatSettings = __assign({}, this.formatSettings, formatSettings); + } + } + if (preferences) { + if (!this.preferences) { + this.preferences = ts.emptyOptions; + } + this.preferences = __assign({}, this.preferences, preferences); + } + }; + ScriptInfo.prototype.getLatestVersion = function () { + return this.textStorage.getVersion(); + }; + ScriptInfo.prototype.saveTo = function (fileName) { + this.host.writeFile(fileName, ts.getSnapshotText(this.textStorage.getSnapshot())); + }; + ScriptInfo.prototype.delayReloadNonMixedContentFile = function () { + ts.Debug.assert(!this.isDynamicOrHasMixedContent()); + this.textStorage.delayReloadFromFileIntoText(); + this.markContainingProjectsAsDirty(); + }; + ScriptInfo.prototype.reloadFromFile = function (tempFileName) { + if (this.isDynamicOrHasMixedContent()) { + this.textStorage.reload(""); + this.markContainingProjectsAsDirty(); + return true; + } + else { + if (this.textStorage.reloadWithFileText(tempFileName)) { + this.markContainingProjectsAsDirty(); + return true; + } + } + return false; + }; + ScriptInfo.prototype.getLineInfo = function (line) { + return this.textStorage.getLineInfo(line); + }; + ScriptInfo.prototype.editContent = function (start, end, newText) { + this.textStorage.edit(start, end, newText); + this.markContainingProjectsAsDirty(); + }; + ScriptInfo.prototype.markContainingProjectsAsDirty = function () { + for (var _i = 0, _a = this.containingProjects; _i < _a.length; _i++) { + var p = _a[_i]; + p.markAsDirty(); + } + }; + ScriptInfo.prototype.isOrphan = function () { + return !ts.forEach(this.containingProjects, function (p) { return !p.isOrphan(); }); + }; + ScriptInfo.prototype.lineToTextSpan = function (line) { + return this.textStorage.lineToTextSpan(line); + }; + ScriptInfo.prototype.lineOffsetToPosition = function (line, offset) { + return this.textStorage.lineOffsetToPosition(line, offset); + }; + ScriptInfo.prototype.positionToLineOffset = function (position) { + return this.textStorage.positionToLineOffset(position); + }; + ScriptInfo.prototype.isJavaScript = function () { + return this.scriptKind === 1 || this.scriptKind === 2; + }; + return ScriptInfo; + }()); + server.ScriptInfo = ScriptInfo; + })(server = ts.server || (ts.server = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + var server; + (function (server) { + server.nullTypingsInstaller = { + isKnownTypesPackageName: ts.returnFalse, + installPackage: ts.notImplemented, + inspectValue: ts.notImplemented, + enqueueInstallTypingsRequest: ts.noop, + attach: ts.noop, + onProjectClosed: ts.noop, + globalTypingsCacheLocation: undefined + }; + function setIsEqualTo(arr1, arr2) { + if (arr1 === arr2) { + return true; + } + if ((arr1 || server.emptyArray).length === 0 && (arr2 || server.emptyArray).length === 0) { + return true; + } + var set = ts.createMap(); + var unique = 0; + for (var _i = 0, _a = arr1; _i < _a.length; _i++) { + var v = _a[_i]; + if (set.get(v) !== true) { + set.set(v, true); + unique++; + } + } + for (var _b = 0, _c = arr2; _b < _c.length; _b++) { + var v = _c[_b]; + var isSet = set.get(v); + if (isSet === undefined) { + return false; + } + if (isSet === true) { + set.set(v, false); + unique--; + } + } + return unique === 0; + } + function typeAcquisitionChanged(opt1, opt2) { + return opt1.enable !== opt2.enable || + !setIsEqualTo(opt1.include, opt2.include) || + !setIsEqualTo(opt1.exclude, opt2.exclude); + } + function compilerOptionsChanged(opt1, opt2) { + return opt1.allowJs !== opt2.allowJs; + } + function unresolvedImportsChanged(imports1, imports2) { + if (imports1 === imports2) { + return false; + } + return !ts.arrayIsEqualTo(imports1, imports2); + } + var TypingsCache = (function () { + function TypingsCache(installer) { + this.installer = installer; + this.perProjectCache = ts.createMap(); + } + TypingsCache.prototype.isKnownTypesPackageName = function (name) { + return this.installer.isKnownTypesPackageName(name); + }; + TypingsCache.prototype.installPackage = function (options) { + return this.installer.installPackage(options); + }; + TypingsCache.prototype.inspectValue = function (options) { + return this.installer.inspectValue(options); + }; + TypingsCache.prototype.enqueueInstallTypingsForProject = function (project, unresolvedImports, forceRefresh) { + var typeAcquisition = project.getTypeAcquisition(); + if (!typeAcquisition || !typeAcquisition.enable) { + return; + } + var entry = this.perProjectCache.get(project.getProjectName()); + if (forceRefresh || + !entry || + typeAcquisitionChanged(typeAcquisition, entry.typeAcquisition) || + compilerOptionsChanged(project.getCompilationSettings(), entry.compilerOptions) || + unresolvedImportsChanged(unresolvedImports, entry.unresolvedImports)) { + this.perProjectCache.set(project.getProjectName(), { + compilerOptions: project.getCompilationSettings(), + typeAcquisition: typeAcquisition, + typings: entry ? entry.typings : server.emptyArray, + unresolvedImports: unresolvedImports, + poisoned: true + }); + this.installer.enqueueInstallTypingsRequest(project, typeAcquisition, unresolvedImports); + } + }; + TypingsCache.prototype.updateTypingsForProject = function (projectName, compilerOptions, typeAcquisition, unresolvedImports, newTypings) { + var typings = ts.sort(newTypings); + this.perProjectCache.set(projectName, { + compilerOptions: compilerOptions, + typeAcquisition: typeAcquisition, + typings: typings, + unresolvedImports: unresolvedImports, + poisoned: false + }); + return !typeAcquisition || !typeAcquisition.enable ? server.emptyArray : typings; + }; + TypingsCache.prototype.onProjectClosed = function (project) { + this.perProjectCache.delete(project.getProjectName()); + this.installer.onProjectClosed(project); + }; + return TypingsCache; + }()); + server.TypingsCache = TypingsCache; + })(server = ts.server || (ts.server = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + var server; + (function (server) { + var ProjectKind; + (function (ProjectKind) { + ProjectKind[ProjectKind["Inferred"] = 0] = "Inferred"; + ProjectKind[ProjectKind["Configured"] = 1] = "Configured"; + ProjectKind[ProjectKind["External"] = 2] = "External"; + })(ProjectKind = server.ProjectKind || (server.ProjectKind = {})); + function countEachFileTypes(infos, includeSizes) { + if (includeSizes === void 0) { includeSizes = false; } + var result = { + js: 0, jsSize: 0, + jsx: 0, jsxSize: 0, + ts: 0, tsSize: 0, + tsx: 0, tsxSize: 0, + dts: 0, dtsSize: 0, + deferred: 0, deferredSize: 0, + }; + for (var _i = 0, infos_1 = infos; _i < infos_1.length; _i++) { + var info = infos_1[_i]; + var fileSize = includeSizes ? info.getTelemetryFileSize() : 0; + switch (info.scriptKind) { + case 1: + result.js += 1; + result.jsSize += fileSize; + break; + case 2: + result.jsx += 1; + result.jsxSize += fileSize; + break; + case 3: + if (ts.fileExtensionIs(info.fileName, ".d.ts")) { + result.dts += 1; + result.dtsSize += fileSize; + } + else { + result.ts += 1; + result.tsSize += fileSize; + } + break; + case 4: + result.tsx += 1; + result.tsxSize += fileSize; + break; + case 7: + result.deferred += 1; + result.deferredSize += fileSize; + break; + } + } + return result; + } + server.countEachFileTypes = countEachFileTypes; + function hasOneOrMoreJsAndNoTsFiles(project) { + var counts = countEachFileTypes(project.getScriptInfos()); + return counts.js > 0 && counts.ts === 0 && counts.tsx === 0; + } + function allRootFilesAreJsOrDts(project) { + var counts = countEachFileTypes(project.getRootScriptInfos()); + return counts.ts === 0 && counts.tsx === 0; + } + server.allRootFilesAreJsOrDts = allRootFilesAreJsOrDts; + function allFilesAreJsOrDts(project) { + var counts = countEachFileTypes(project.getScriptInfos()); + return counts.ts === 0 && counts.tsx === 0; + } + server.allFilesAreJsOrDts = allFilesAreJsOrDts; + function hasNoTypeScriptSource(fileNames) { + return !fileNames.some(function (fileName) { return (ts.fileExtensionIs(fileName, ".ts") && !ts.fileExtensionIs(fileName, ".d.ts")) || ts.fileExtensionIs(fileName, ".tsx"); }); + } + server.hasNoTypeScriptSource = hasNoTypeScriptSource; + function isScriptInfo(value) { + return value instanceof server.ScriptInfo; + } + server.isScriptInfo = isScriptInfo; + var Project = (function () { + function Project(projectName, projectKind, projectService, documentRegistry, hasExplicitListOfFiles, lastFileExceededProgramSize, compilerOptions, compileOnSaveEnabled, directoryStructureHost, currentDirectory) { + var _this = this; + this.projectName = projectName; + this.projectKind = projectKind; + this.projectService = projectService; + this.documentRegistry = documentRegistry; + this.compilerOptions = compilerOptions; + this.compileOnSaveEnabled = compileOnSaveEnabled; + this.rootFiles = []; + this.rootFilesMap = ts.createMap(); + this.plugins = []; + this.cachedUnresolvedImportsPerFile = ts.createMap(); + this.hasAddedorRemovedFiles = false; + this.lastReportedVersion = 0; + this.projectProgramVersion = 0; + this.projectStateVersion = 0; + this.isInitialLoadPending = ts.returnFalse; + this.dirty = false; + this.hasChangedAutomaticTypeDirectiveNames = false; + this.typingFiles = server.emptyArray; + this.directoryStructureHost = directoryStructureHost; + this.currentDirectory = this.projectService.getNormalizedAbsolutePath(currentDirectory || ""); + this.getCanonicalFileName = this.projectService.toCanonicalFileName; + this.cancellationToken = new ts.ThrottledCancellationToken(this.projectService.cancellationToken, this.projectService.throttleWaitMilliseconds); + if (!this.compilerOptions) { + this.compilerOptions = ts.getDefaultCompilerOptions(); + this.compilerOptions.allowNonTsExtensions = true; + this.compilerOptions.allowJs = true; + } + else if (hasExplicitListOfFiles || this.compilerOptions.allowJs || this.projectService.hasDeferredExtension()) { + this.compilerOptions.allowNonTsExtensions = true; + } + this.languageServiceEnabled = !projectService.syntaxOnly; + this.setInternalCompilerOptionsForEmittingJsFiles(); + var host = this.projectService.host; + if (this.projectService.logger.loggingEnabled()) { + this.trace = function (s) { return _this.writeLog(s); }; + } + else if (host.trace) { + this.trace = function (s) { return host.trace(s); }; + } + if (host.realpath) { + this.realpath = function (path) { return host.realpath(path); }; + } + this.resolutionCache = ts.createResolutionCache(this, currentDirectory && this.currentDirectory, true); + this.languageService = ts.createLanguageService(this, this.documentRegistry, projectService.syntaxOnly); + if (lastFileExceededProgramSize) { + this.disableLanguageService(lastFileExceededProgramSize); + } + this.markAsDirty(); + this.projectService.pendingEnsureProjectForOpenFiles = true; + } + Project.prototype.isNonTsProject = function () { + server.updateProjectIfDirty(this); + return allFilesAreJsOrDts(this); + }; + Project.prototype.isJsOnlyProject = function () { + server.updateProjectIfDirty(this); + return hasOneOrMoreJsAndNoTsFiles(this); + }; + Project.resolveModule = function (moduleName, initialDir, host, log) { + var resolvedPath = ts.normalizeSlashes(host.resolvePath(ts.combinePaths(initialDir, "node_modules"))); + log("Loading " + moduleName + " from " + initialDir + " (resolved to " + resolvedPath + ")"); + var result = host.require(resolvedPath, moduleName); + if (result.error) { + var err = result.error.stack || result.error.message || JSON.stringify(result.error); + log("Failed to load module '" + moduleName + "': " + err); + return undefined; + } + return result.module; + }; + Project.prototype.isKnownTypesPackageName = function (name) { + return this.typingsCache.isKnownTypesPackageName(name); + }; + Project.prototype.installPackage = function (options) { + return this.typingsCache.installPackage(__assign({}, options, { projectName: this.projectName, projectRootPath: this.toPath(this.currentDirectory) })); + }; + Project.prototype.inspectValue = function (options) { + return this.typingsCache.inspectValue(options); + }; + Object.defineProperty(Project.prototype, "typingsCache", { + get: function () { + return this.projectService.typingsCache; + }, + enumerable: true, + configurable: true + }); + Project.prototype.getCompilationSettings = function () { + return this.compilerOptions; + }; + Project.prototype.getCompilerOptions = function () { + return this.getCompilationSettings(); + }; + Project.prototype.getNewLine = function () { + return this.projectService.host.newLine; + }; + Project.prototype.getProjectVersion = function () { + return this.projectStateVersion.toString(); + }; + Project.prototype.getProjectReferences = function () { + return undefined; + }; + Project.prototype.getScriptFileNames = function () { + var _this = this; + if (!this.rootFiles) { + return ts.emptyArray; + } + var result; + this.rootFilesMap.forEach(function (value) { + if (_this.languageServiceEnabled || (isScriptInfo(value) && value.isScriptOpen())) { + (result || (result = [])).push(isScriptInfo(value) ? value.fileName : value); + } + }); + return ts.addRange(result, this.typingFiles) || ts.emptyArray; + }; + Project.prototype.getOrCreateScriptInfoAndAttachToProject = function (fileName) { + var scriptInfo = this.projectService.getOrCreateScriptInfoNotOpenedByClient(fileName, this.currentDirectory, this.directoryStructureHost); + if (scriptInfo) { + var existingValue = this.rootFilesMap.get(scriptInfo.path); + if (existingValue !== scriptInfo && existingValue !== undefined) { + this.rootFiles.push(scriptInfo); + this.rootFilesMap.set(scriptInfo.path, scriptInfo); + } + scriptInfo.attachToProject(this); + } + return scriptInfo; + }; + Project.prototype.getScriptKind = function (fileName) { + var info = this.getOrCreateScriptInfoAndAttachToProject(fileName); + return (info && info.scriptKind); + }; + Project.prototype.getScriptVersion = function (filename) { + var info = this.getOrCreateScriptInfoAndAttachToProject(filename); + return (info && info.getLatestVersion()); + }; + Project.prototype.getScriptSnapshot = function (filename) { + var scriptInfo = this.getOrCreateScriptInfoAndAttachToProject(filename); + if (scriptInfo) { + return scriptInfo.getSnapshot(); + } + }; + Project.prototype.getCancellationToken = function () { + return this.cancellationToken; + }; + Project.prototype.getCurrentDirectory = function () { + return this.currentDirectory; + }; + Project.prototype.getDefaultLibFileName = function () { + var nodeModuleBinDir = ts.getDirectoryPath(ts.normalizePath(this.projectService.getExecutingFilePath())); + return ts.combinePaths(nodeModuleBinDir, ts.getDefaultLibFileName(this.compilerOptions)); + }; + Project.prototype.useCaseSensitiveFileNames = function () { + return this.projectService.host.useCaseSensitiveFileNames; + }; + Project.prototype.readDirectory = function (path, extensions, exclude, include, depth) { + return this.directoryStructureHost.readDirectory(path, extensions, exclude, include, depth); + }; + Project.prototype.readFile = function (fileName) { + return this.projectService.host.readFile(fileName); + }; + Project.prototype.writeFile = function (fileName, content) { + return this.projectService.host.writeFile(fileName, content); + }; + Project.prototype.fileExists = function (file) { + var path = this.toPath(file); + return !this.isWatchedMissingFile(path) && this.directoryStructureHost.fileExists(file); + }; + Project.prototype.resolveModuleNames = function (moduleNames, containingFile, reusedNames, redirectedReference) { + return this.resolutionCache.resolveModuleNames(moduleNames, containingFile, reusedNames, redirectedReference); + }; + Project.prototype.getResolvedModuleWithFailedLookupLocationsFromCache = function (moduleName, containingFile) { + return this.resolutionCache.getResolvedModuleWithFailedLookupLocationsFromCache(moduleName, containingFile); + }; + Project.prototype.resolveTypeReferenceDirectives = function (typeDirectiveNames, containingFile, redirectedReference) { + return this.resolutionCache.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile, redirectedReference); + }; + Project.prototype.directoryExists = function (path) { + return this.directoryStructureHost.directoryExists(path); + }; + Project.prototype.getDirectories = function (path) { + return this.directoryStructureHost.getDirectories(path); + }; + Project.prototype.getCachedDirectoryStructureHost = function () { + return undefined; + }; + Project.prototype.toPath = function (fileName) { + return ts.toPath(fileName, this.currentDirectory, this.projectService.toCanonicalFileName); + }; + Project.prototype.watchDirectoryOfFailedLookupLocation = function (directory, cb, flags) { + return this.projectService.watchFactory.watchDirectory(this.projectService.host, directory, cb, flags, "Directory of Failed lookup locations in module resolution", this); + }; + Project.prototype.onInvalidatedResolution = function () { + this.projectService.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles(this); + }; + Project.prototype.watchTypeRootsDirectory = function (directory, cb, flags) { + return this.projectService.watchFactory.watchDirectory(this.projectService.host, directory, cb, flags, "Type root directory", this); + }; + Project.prototype.onChangedAutomaticTypeDirectiveNames = function () { + this.hasChangedAutomaticTypeDirectiveNames = true; + this.projectService.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles(this); + }; + Project.prototype.getGlobalCache = function () { + return this.getTypeAcquisition().enable ? this.projectService.typingsInstaller.globalTypingsCacheLocation : undefined; + }; + Project.prototype.writeLog = function (s) { + this.projectService.logger.info(s); + }; + Project.prototype.log = function (s) { + this.writeLog(s); + }; + Project.prototype.error = function (s) { + this.projectService.logger.msg(s, server.Msg.Err); + }; + Project.prototype.setInternalCompilerOptionsForEmittingJsFiles = function () { + if (this.projectKind === ProjectKind.Inferred || this.projectKind === ProjectKind.External) { + this.compilerOptions.noEmitForJsFiles = true; + } + }; + Project.prototype.getGlobalProjectErrors = function () { + return server.emptyArray; + }; + Project.prototype.getAllProjectErrors = function () { + return server.emptyArray; + }; + Project.prototype.getLanguageService = function (ensureSynchronized) { + if (ensureSynchronized === void 0) { ensureSynchronized = true; } + if (ensureSynchronized) { + server.updateProjectIfDirty(this); + } + return this.languageService; + }; + Project.prototype.getSourceMapper = function () { + return this.getLanguageService().getSourceMapper(); + }; + Project.prototype.shouldEmitFile = function (scriptInfo) { + return scriptInfo && !scriptInfo.isDynamicOrHasMixedContent(); + }; + Project.prototype.getCompileOnSaveAffectedFileList = function (scriptInfo) { + var _this = this; + if (!this.languageServiceEnabled) { + return []; + } + server.updateProjectIfDirty(this); + this.builderState = ts.BuilderState.create(this.program, this.projectService.toCanonicalFileName, this.builderState); + return ts.mapDefined(ts.BuilderState.getFilesAffectedBy(this.builderState, this.program, scriptInfo.path, this.cancellationToken, function (data) { return _this.projectService.host.createHash(data); }), function (sourceFile) { return _this.shouldEmitFile(_this.projectService.getScriptInfoForPath(sourceFile.path)) ? sourceFile.fileName : undefined; }); + }; + Project.prototype.emitFile = function (scriptInfo, writeFile) { + if (!this.languageServiceEnabled || !this.shouldEmitFile(scriptInfo)) { + return false; + } + var _a = this.getLanguageService(false).getEmitOutput(scriptInfo.fileName), emitSkipped = _a.emitSkipped, outputFiles = _a.outputFiles; + if (!emitSkipped) { + for (var _i = 0, outputFiles_1 = outputFiles; _i < outputFiles_1.length; _i++) { + var outputFile = outputFiles_1[_i]; + var outputFileAbsoluteFileName = ts.getNormalizedAbsolutePath(outputFile.name, this.currentDirectory); + writeFile(outputFileAbsoluteFileName, outputFile.text, outputFile.writeByteOrderMark); + } + } + return !emitSkipped; + }; + Project.prototype.enableLanguageService = function () { + if (this.languageServiceEnabled || this.projectService.syntaxOnly) { + return; + } + this.languageServiceEnabled = true; + this.lastFileExceededProgramSize = undefined; + this.projectService.onUpdateLanguageServiceStateForProject(this, true); + }; + Project.prototype.disableLanguageService = function (lastFileExceededProgramSize) { + if (!this.languageServiceEnabled) { + return; + } + ts.Debug.assert(!this.projectService.syntaxOnly); + this.languageService.cleanupSemanticCache(); + this.languageServiceEnabled = false; + this.lastFileExceededProgramSize = lastFileExceededProgramSize; + this.builderState = undefined; + this.resolutionCache.closeTypeRootsWatch(); + this.projectService.onUpdateLanguageServiceStateForProject(this, false); + }; + Project.prototype.getProjectName = function () { + return this.projectName; + }; + Project.prototype.removeLocalTypingsFromTypeAcquisition = function (newTypeAcquisition) { + if (!newTypeAcquisition || !newTypeAcquisition.include) { + return newTypeAcquisition; + } + return __assign({}, newTypeAcquisition, { include: this.removeExistingTypings(newTypeAcquisition.include) }); + }; + Project.prototype.getExternalFiles = function () { + var _this = this; + return ts.sort(ts.flatMap(this.plugins, function (plugin) { + if (typeof plugin.module.getExternalFiles !== "function") + return; + try { + return plugin.module.getExternalFiles(_this); + } + catch (e) { + _this.projectService.logger.info("A plugin threw an exception in getExternalFiles: " + e); + if (e.stack) { + _this.projectService.logger.info(e.stack); + } + } + })); + }; + Project.prototype.getSourceFile = function (path) { + if (!this.program) { + return undefined; + } + return this.program.getSourceFileByPath(path); + }; + Project.prototype.getSourceFileOrConfigFile = function (path) { + var options = this.program.getCompilerOptions(); + return path === options.configFilePath ? options.configFile : this.getSourceFile(path); + }; + Project.prototype.close = function () { + var _this = this; + if (this.program) { + for (var _i = 0, _a = this.program.getSourceFiles(); _i < _a.length; _i++) { + var f = _a[_i]; + this.detachScriptInfoIfNotRoot(f.fileName); + } + this.program.forEachResolvedProjectReference(function (ref) { + if (ref) { + _this.detachScriptInfoFromProject(ref.sourceFile.fileName); + } + }); + } + ts.forEach(this.externalFiles, function (externalFile) { return _this.detachScriptInfoIfNotRoot(externalFile); }); + for (var _b = 0, _c = this.rootFiles; _b < _c.length; _b++) { + var root = _c[_b]; + root.detachFromProject(this); + } + this.projectService.pendingEnsureProjectForOpenFiles = true; + this.rootFiles = undefined; + this.rootFilesMap = undefined; + this.externalFiles = undefined; + this.program = undefined; + this.builderState = undefined; + this.resolutionCache.clear(); + this.resolutionCache = undefined; + this.cachedUnresolvedImportsPerFile = undefined; + this.directoryStructureHost = undefined; + if (this.missingFilesMap) { + ts.clearMap(this.missingFilesMap, ts.closeFileWatcher); + this.missingFilesMap = undefined; + } + this.languageService.dispose(); + this.languageService = undefined; + }; + Project.prototype.detachScriptInfoIfNotRoot = function (uncheckedFilename) { + var info = this.projectService.getScriptInfo(uncheckedFilename); + if (info && !this.isRoot(info)) { + info.detachFromProject(this); + } + }; + Project.prototype.isClosed = function () { + return this.rootFiles === undefined; + }; + Project.prototype.hasRoots = function () { + return this.rootFiles && this.rootFiles.length > 0; + }; + Project.prototype.isOrphan = function () { + return false; + }; + Project.prototype.getRootFiles = function () { + return this.rootFiles && this.rootFiles.map(function (info) { return info.fileName; }); + }; + Project.prototype.getRootFilesMap = function () { + return this.rootFilesMap; + }; + Project.prototype.getRootScriptInfos = function () { + return this.rootFiles; + }; + Project.prototype.getScriptInfos = function () { + var _this = this; + if (!this.languageServiceEnabled) { + return this.rootFiles; + } + return ts.map(this.program.getSourceFiles(), function (sourceFile) { + var scriptInfo = _this.projectService.getScriptInfoForPath(sourceFile.resolvedPath); + ts.Debug.assert(!!scriptInfo, "getScriptInfo", function () { return "scriptInfo for a file '" + sourceFile.fileName + "' Path: '" + sourceFile.path + "' / '" + sourceFile.resolvedPath + "' is missing."; }); + return scriptInfo; + }); + }; + Project.prototype.getExcludedFiles = function () { + return server.emptyArray; + }; + Project.prototype.getFileNames = function (excludeFilesFromExternalLibraries, excludeConfigFiles) { + if (!this.program) { + return []; + } + if (!this.languageServiceEnabled) { + var rootFiles = this.getRootFiles(); + if (this.compilerOptions) { + var defaultLibrary = ts.getDefaultLibFilePath(this.compilerOptions); + if (defaultLibrary) { + (rootFiles || (rootFiles = [])).push(server.asNormalizedPath(defaultLibrary)); + } + } + return rootFiles; + } + var result = []; + for (var _i = 0, _a = this.program.getSourceFiles(); _i < _a.length; _i++) { + var f = _a[_i]; + if (excludeFilesFromExternalLibraries && this.program.isSourceFileFromExternalLibrary(f)) { + continue; + } + result.push(server.asNormalizedPath(f.fileName)); + } + if (!excludeConfigFiles) { + var configFile = this.program.getCompilerOptions().configFile; + if (configFile) { + result.push(server.asNormalizedPath(configFile.fileName)); + if (configFile.extendedSourceFiles) { + for (var _b = 0, _c = configFile.extendedSourceFiles; _b < _c.length; _b++) { + var f = _c[_b]; + result.push(server.asNormalizedPath(f)); + } + } + } + } + return result; + }; + Project.prototype.hasConfigFile = function (configFilePath) { + if (this.program && this.languageServiceEnabled) { + var configFile = this.program.getCompilerOptions().configFile; + if (configFile) { + if (configFilePath === server.asNormalizedPath(configFile.fileName)) { + return true; + } + if (configFile.extendedSourceFiles) { + for (var _i = 0, _a = configFile.extendedSourceFiles; _i < _a.length; _i++) { + var f = _a[_i]; + if (configFilePath === server.asNormalizedPath(f)) { + return true; + } + } + } + } + } + return false; + }; + Project.prototype.containsScriptInfo = function (info) { + return this.isRoot(info) || (!!this.program && this.program.getSourceFileByPath(info.path) !== undefined); + }; + Project.prototype.containsFile = function (filename, requireOpen) { + var info = this.projectService.getScriptInfoForNormalizedPath(filename); + if (info && (info.isScriptOpen() || !requireOpen)) { + return this.containsScriptInfo(info); + } + return false; + }; + Project.prototype.isRoot = function (info) { + return this.rootFilesMap && this.rootFilesMap.get(info.path) === info; + }; + Project.prototype.addRoot = function (info) { + ts.Debug.assert(!this.isRoot(info)); + this.rootFiles.push(info); + this.rootFilesMap.set(info.path, info); + info.attachToProject(this); + this.markAsDirty(); + }; + Project.prototype.addMissingFileRoot = function (fileName) { + var path = this.projectService.toPath(fileName); + this.rootFilesMap.set(path, fileName); + this.markAsDirty(); + }; + Project.prototype.removeFile = function (info, fileExists, detachFromProject) { + if (this.isRoot(info)) { + this.removeRoot(info); + } + if (fileExists) { + this.resolutionCache.removeResolutionsOfFile(info.path); + } + else { + this.resolutionCache.invalidateResolutionOfFile(info.path); + } + this.cachedUnresolvedImportsPerFile.delete(info.path); + if (detachFromProject) { + info.detachFromProject(this); + } + this.markAsDirty(); + }; + Project.prototype.registerFileUpdate = function (fileName) { + (this.updatedFileNames || (this.updatedFileNames = ts.createMap())).set(fileName, true); + }; + Project.prototype.markAsDirty = function () { + if (!this.dirty) { + this.projectStateVersion++; + this.dirty = true; + } + }; + Project.prototype.onFileAddedOrRemoved = function () { + this.hasAddedorRemovedFiles = true; + }; + Project.prototype.updateGraph = function () { + this.resolutionCache.startRecordingFilesWithChangedResolutions(); + var hasNewProgram = this.updateGraphWorker(); + var hasAddedorRemovedFiles = this.hasAddedorRemovedFiles; + this.hasAddedorRemovedFiles = false; + var changedFiles = this.resolutionCache.finishRecordingFilesWithChangedResolutions() || server.emptyArray; + for (var _i = 0, changedFiles_1 = changedFiles; _i < changedFiles_1.length; _i++) { + var file = changedFiles_1[_i]; + this.cachedUnresolvedImportsPerFile.delete(file); + } + if (this.languageServiceEnabled) { + if (hasNewProgram || changedFiles.length) { + this.lastCachedUnresolvedImportsList = getUnresolvedImports(this.program, this.cachedUnresolvedImportsPerFile); + } + this.projectService.typingsCache.enqueueInstallTypingsForProject(this, this.lastCachedUnresolvedImportsList, hasAddedorRemovedFiles); + } + else { + this.lastCachedUnresolvedImportsList = undefined; + } + if (hasNewProgram) { + this.projectProgramVersion++; + } + return !hasNewProgram; + }; + Project.prototype.updateTypingFiles = function (typingFiles) { + var _this = this; + ts.enumerateInsertsAndDeletes(typingFiles, this.typingFiles, ts.getStringComparer(!this.useCaseSensitiveFileNames()), ts.noop, function (removed) { return _this.detachScriptInfoFromProject(removed); }); + this.typingFiles = typingFiles; + this.resolutionCache.setFilesWithInvalidatedNonRelativeUnresolvedImports(this.cachedUnresolvedImportsPerFile); + }; + Project.prototype.getCurrentProgram = function () { + return this.program; + }; + Project.prototype.removeExistingTypings = function (include) { + var existing = ts.getAutomaticTypeDirectiveNames(this.getCompilerOptions(), this.directoryStructureHost); + return include.filter(function (i) { return existing.indexOf(i) < 0; }); + }; + Project.prototype.updateGraphWorker = function () { + var _this = this; + var oldProgram = this.program; + ts.Debug.assert(!this.isClosed(), "Called update graph worker of closed project"); + this.writeLog("Starting updateGraphWorker: Project: " + this.getProjectName()); + var start = ts.timestamp(); + this.hasInvalidatedResolution = this.resolutionCache.createHasInvalidatedResolution(); + this.resolutionCache.startCachingPerDirectoryResolution(); + this.program = this.languageService.getProgram(); + this.dirty = false; + this.resolutionCache.finishCachingPerDirectoryResolution(); + ts.Debug.assert(oldProgram === undefined || this.program !== undefined); + var hasNewProgram = this.program && (!oldProgram || (this.program !== oldProgram && !(oldProgram.structureIsReused & 2))); + this.hasChangedAutomaticTypeDirectiveNames = false; + if (hasNewProgram) { + if (oldProgram) { + for (var _i = 0, _a = oldProgram.getSourceFiles(); _i < _a.length; _i++) { + var f = _a[_i]; + var newFile = this.program.getSourceFileByPath(f.resolvedPath); + if (!newFile || (f.resolvedPath === f.path && newFile.resolvedPath !== f.path)) { + this.detachScriptInfoFromProject(f.fileName, !!this.program.getSourceFileByPath(f.path)); + } + } + oldProgram.forEachResolvedProjectReference(function (resolvedProjectReference, resolvedProjectReferencePath) { + if (resolvedProjectReference && !_this.program.getResolvedProjectReferenceByPath(resolvedProjectReferencePath)) { + _this.detachScriptInfoFromProject(resolvedProjectReference.sourceFile.fileName); + } + }); + } + ts.updateMissingFilePathsWatch(this.program, this.missingFilesMap || (this.missingFilesMap = ts.createMap()), function (missingFilePath) { return _this.addMissingFileWatcher(missingFilePath); }); + if (this.languageServiceEnabled) { + this.resolutionCache.updateTypeRootsWatch(); + } + } + var oldExternalFiles = this.externalFiles || server.emptyArray; + this.externalFiles = this.getExternalFiles(); + ts.enumerateInsertsAndDeletes(this.externalFiles, oldExternalFiles, ts.getStringComparer(!this.useCaseSensitiveFileNames()), function (inserted) { + var scriptInfo = _this.projectService.getOrCreateScriptInfoNotOpenedByClient(inserted, _this.currentDirectory, _this.directoryStructureHost); + scriptInfo.attachToProject(_this); + }, function (removed) { return _this.detachScriptInfoFromProject(removed); }); + var elapsed = ts.timestamp() - start; + this.writeLog("Finishing updateGraphWorker: Project: " + this.getProjectName() + " Version: " + this.getProjectVersion() + " structureChanged: " + hasNewProgram + " Elapsed: " + elapsed + "ms"); + return hasNewProgram; + }; + Project.prototype.detachScriptInfoFromProject = function (uncheckedFileName, noRemoveResolution) { + var scriptInfoToDetach = this.projectService.getScriptInfo(uncheckedFileName); + if (scriptInfoToDetach) { + scriptInfoToDetach.detachFromProject(this); + if (!noRemoveResolution) { + this.resolutionCache.removeResolutionsOfFile(scriptInfoToDetach.path); + } + } + }; + Project.prototype.addMissingFileWatcher = function (missingFilePath) { + var _this = this; + var fileWatcher = this.projectService.watchFactory.watchFile(this.projectService.host, missingFilePath, function (fileName, eventKind) { + if (_this.projectKind === ProjectKind.Configured) { + _this.getCachedDirectoryStructureHost().addOrDeleteFile(fileName, missingFilePath, eventKind); + } + if (eventKind === ts.FileWatcherEventKind.Created && _this.missingFilesMap.has(missingFilePath)) { + _this.missingFilesMap.delete(missingFilePath); + fileWatcher.close(); + _this.projectService.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles(_this); + } + }, ts.PollingInterval.Medium, "Missing file from program", this); + return fileWatcher; + }; + Project.prototype.isWatchedMissingFile = function (path) { + return !!this.missingFilesMap && this.missingFilesMap.has(path); + }; + Project.prototype.getScriptInfoForNormalizedPath = function (fileName) { + var scriptInfo = this.projectService.getScriptInfoForPath(this.toPath(fileName)); + if (scriptInfo && !scriptInfo.isAttached(this)) { + return server.Errors.ThrowProjectDoesNotContainDocument(fileName, this); + } + return scriptInfo; + }; + Project.prototype.getScriptInfo = function (uncheckedFileName) { + return this.projectService.getScriptInfo(uncheckedFileName); + }; + Project.prototype.filesToString = function (writeProjectFileNames) { + if (!this.program) { + return "\tFiles (0)\n"; + } + var sourceFiles = this.program.getSourceFiles(); + var strBuilder = "\tFiles (" + sourceFiles.length + ")\n"; + if (writeProjectFileNames) { + for (var _i = 0, sourceFiles_1 = sourceFiles; _i < sourceFiles_1.length; _i++) { + var file = sourceFiles_1[_i]; + strBuilder += "\t" + file.fileName + "\n"; + } + } + return strBuilder; + }; + Project.prototype.print = function (counter) { + this.writeLog("Project '" + this.projectName + "' (" + ProjectKind[this.projectKind] + ") " + (counter === undefined ? "" : counter)); + this.writeLog(this.filesToString(this.projectService.logger.hasLevel(server.LogLevel.verbose))); + this.writeLog("-----------------------------------------------"); + }; + Project.prototype.setCompilerOptions = function (compilerOptions) { + if (compilerOptions) { + compilerOptions.allowNonTsExtensions = true; + var oldOptions = this.compilerOptions; + this.compilerOptions = compilerOptions; + this.setInternalCompilerOptionsForEmittingJsFiles(); + if (ts.changesAffectModuleResolution(oldOptions, compilerOptions)) { + this.cachedUnresolvedImportsPerFile.clear(); + this.lastCachedUnresolvedImportsList = undefined; + this.resolutionCache.clear(); + } + this.markAsDirty(); + } + }; + Project.prototype.getChangesSinceVersion = function (lastKnownVersion) { + if (!this.isInitialLoadPending()) { + server.updateProjectIfDirty(this); + } + var info = { + projectName: this.getProjectName(), + version: this.projectProgramVersion, + isInferred: this.projectKind === ProjectKind.Inferred, + options: this.getCompilationSettings(), + languageServiceDisabled: !this.languageServiceEnabled, + lastFileExceededProgramSize: this.lastFileExceededProgramSize + }; + var updatedFileNames = this.updatedFileNames; + this.updatedFileNames = undefined; + if (this.lastReportedFileNames && lastKnownVersion === this.lastReportedVersion) { + if (this.projectProgramVersion === this.lastReportedVersion && !updatedFileNames) { + return { info: info, projectErrors: this.getGlobalProjectErrors() }; + } + var lastReportedFileNames_1 = this.lastReportedFileNames; + var externalFiles = this.getExternalFiles().map(function (f) { return server.toNormalizedPath(f); }); + var currentFiles_1 = ts.arrayToSet(this.getFileNames().concat(externalFiles)); + var added_1 = []; + var removed_1 = []; + var updated = updatedFileNames ? ts.arrayFrom(updatedFileNames.keys()) : []; + ts.forEachKey(currentFiles_1, function (id) { + if (!lastReportedFileNames_1.has(id)) { + added_1.push(id); + } + }); + ts.forEachKey(lastReportedFileNames_1, function (id) { + if (!currentFiles_1.has(id)) { + removed_1.push(id); + } + }); + this.lastReportedFileNames = currentFiles_1; + this.lastReportedVersion = this.projectProgramVersion; + return { info: info, changes: { added: added_1, removed: removed_1, updated: updated }, projectErrors: this.getGlobalProjectErrors() }; + } + else { + var projectFileNames = this.getFileNames(); + var externalFiles = this.getExternalFiles().map(function (f) { return server.toNormalizedPath(f); }); + var allFiles = projectFileNames.concat(externalFiles); + this.lastReportedFileNames = ts.arrayToSet(allFiles); + this.lastReportedVersion = this.projectProgramVersion; + return { info: info, files: allFiles, projectErrors: this.getGlobalProjectErrors() }; + } + }; + Project.prototype.removeRoot = function (info) { + ts.orderedRemoveItem(this.rootFiles, info); + this.rootFilesMap.delete(info.path); + }; + Project.prototype.enableGlobalPlugins = function (options, pluginConfigOverrides) { + var host = this.projectService.host; + if (!host.require) { + this.projectService.logger.info("Plugins were requested but not running in environment that supports 'require'. Nothing will be loaded"); + return; + } + var searchPaths = [ts.combinePaths(this.projectService.getExecutingFilePath(), "../../..")].concat(this.projectService.pluginProbeLocations); + if (this.projectService.globalPlugins) { + var _loop_1 = function (globalPluginName) { + if (!globalPluginName) + return "continue"; + if (options.plugins && options.plugins.some(function (p) { return p.name === globalPluginName; })) + return "continue"; + this_1.projectService.logger.info("Loading global plugin " + globalPluginName); + this_1.enablePlugin({ name: globalPluginName, global: true }, searchPaths, pluginConfigOverrides); + }; + var this_1 = this; + for (var _i = 0, _a = this.projectService.globalPlugins; _i < _a.length; _i++) { + var globalPluginName = _a[_i]; + _loop_1(globalPluginName); + } + } + }; + Project.prototype.enablePlugin = function (pluginConfigEntry, searchPaths, pluginConfigOverrides) { + var _this = this; + this.projectService.logger.info("Enabling plugin " + pluginConfigEntry.name + " from candidate paths: " + searchPaths.join(",")); + var log = function (message) { + _this.projectService.logger.info(message); + }; + var resolvedModule = ts.firstDefined(searchPaths, function (searchPath) { + return Project.resolveModule(pluginConfigEntry.name, searchPath, _this.projectService.host, log); + }); + if (resolvedModule) { + var configurationOverride = pluginConfigOverrides && pluginConfigOverrides.get(pluginConfigEntry.name); + if (configurationOverride) { + var pluginName = pluginConfigEntry.name; + pluginConfigEntry = configurationOverride; + pluginConfigEntry.name = pluginName; + } + this.enableProxy(resolvedModule, pluginConfigEntry); + } + else { + this.projectService.logger.info("Couldn't find " + pluginConfigEntry.name); + } + }; + Project.prototype.enableProxy = function (pluginModuleFactory, configEntry) { + try { + if (typeof pluginModuleFactory !== "function") { + this.projectService.logger.info("Skipped loading plugin " + configEntry.name + " because it did expose a proper factory function"); + return; + } + var info = { + config: configEntry, + project: this, + languageService: this.languageService, + languageServiceHost: this, + serverHost: this.projectService.host + }; + var pluginModule = pluginModuleFactory({ typescript: ts }); + var newLS = pluginModule.create(info); + for (var _i = 0, _a = Object.keys(this.languageService); _i < _a.length; _i++) { + var k = _a[_i]; + if (!(k in newLS)) { + this.projectService.logger.info("Plugin activation warning: Missing proxied method " + k + " in created LS. Patching."); + newLS[k] = this.languageService[k]; + } + } + this.projectService.logger.info("Plugin validation succeded"); + this.languageService = newLS; + this.plugins.push({ name: configEntry.name, module: pluginModule }); + } + catch (e) { + this.projectService.logger.info("Plugin activation failed: " + e); + } + }; + Project.prototype.onPluginConfigurationChanged = function (pluginName, configuration) { + this.plugins.filter(function (plugin) { return plugin.name === pluginName; }).forEach(function (plugin) { + if (plugin.module.onConfigurationChanged) { + plugin.module.onConfigurationChanged(configuration); + } + }); + }; + Project.prototype.refreshDiagnostics = function () { + this.projectService.sendProjectsUpdatedInBackgroundEvent(); + }; + return Project; + }()); + server.Project = Project; + function getUnresolvedImports(program, cachedUnresolvedImportsPerFile) { + var ambientModules = program.getTypeChecker().getAmbientModules().map(function (mod) { return ts.stripQuotes(mod.getName()); }); + return ts.sortAndDeduplicate(ts.flatMap(program.getSourceFiles(), function (sourceFile) { + return extractUnresolvedImportsFromSourceFile(sourceFile, ambientModules, cachedUnresolvedImportsPerFile); + })); + } + function extractUnresolvedImportsFromSourceFile(file, ambientModules, cachedUnresolvedImportsPerFile) { + return ts.getOrUpdate(cachedUnresolvedImportsPerFile, file.path, function () { + if (!file.resolvedModules) + return server.emptyArray; + var unresolvedImports; + file.resolvedModules.forEach(function (resolvedModule, name) { + if ((!resolvedModule || !ts.resolutionExtensionIsTSOrJson(resolvedModule.extension)) && + !ts.isExternalModuleNameRelative(name) && + !ambientModules.some(function (m) { return m === name; })) { + unresolvedImports = ts.append(unresolvedImports, ts.parsePackageName(name).packageName); + } + }); + return unresolvedImports || server.emptyArray; + }); + } + var InferredProject = (function (_super) { + __extends(InferredProject, _super); + function InferredProject(projectService, documentRegistry, compilerOptions, projectRootPath, currentDirectory, pluginConfigOverrides) { + var _this = _super.call(this, InferredProject.newName(), ProjectKind.Inferred, projectService, documentRegistry, undefined, undefined, compilerOptions, false, projectService.host, currentDirectory) || this; + _this._isJsInferredProject = false; + _this.projectRootPath = projectRootPath && projectService.toCanonicalFileName(projectRootPath); + if (!projectRootPath && !projectService.useSingleInferredProject) { + _this.canonicalCurrentDirectory = projectService.toCanonicalFileName(_this.currentDirectory); + } + _this.enableGlobalPlugins(_this.getCompilerOptions(), pluginConfigOverrides); + return _this; + } + InferredProject.prototype.toggleJsInferredProject = function (isJsInferredProject) { + if (isJsInferredProject !== this._isJsInferredProject) { + this._isJsInferredProject = isJsInferredProject; + this.setCompilerOptions(); + } + }; + InferredProject.prototype.setCompilerOptions = function (options) { + if (!options && !this.getCompilationSettings()) { + return; + } + var newOptions = ts.cloneCompilerOptions(options || this.getCompilationSettings()); + if (this._isJsInferredProject && typeof newOptions.maxNodeModuleJsDepth !== "number") { + newOptions.maxNodeModuleJsDepth = 2; + } + else if (!this._isJsInferredProject) { + newOptions.maxNodeModuleJsDepth = undefined; + } + newOptions.allowJs = true; + _super.prototype.setCompilerOptions.call(this, newOptions); + }; + InferredProject.prototype.addRoot = function (info) { + ts.Debug.assert(info.isScriptOpen()); + this.projectService.startWatchingConfigFilesForInferredProjectRoot(info); + if (!this._isJsInferredProject && info.isJavaScript()) { + this.toggleJsInferredProject(true); + } + _super.prototype.addRoot.call(this, info); + }; + InferredProject.prototype.removeRoot = function (info) { + this.projectService.stopWatchingConfigFilesForInferredProjectRoot(info); + _super.prototype.removeRoot.call(this, info); + if (this._isJsInferredProject && info.isJavaScript()) { + if (ts.every(this.getRootScriptInfos(), function (rootInfo) { return !rootInfo.isJavaScript(); })) { + this.toggleJsInferredProject(false); + } + } + }; + InferredProject.prototype.isOrphan = function () { + return !this.hasRoots(); + }; + InferredProject.prototype.isProjectWithSingleRoot = function () { + return (!this.projectRootPath && !this.projectService.useSingleInferredProject) || + this.getRootScriptInfos().length === 1; + }; + InferredProject.prototype.close = function () { + var _this = this; + ts.forEach(this.getRootScriptInfos(), function (info) { return _this.projectService.stopWatchingConfigFilesForInferredProjectRoot(info); }); + _super.prototype.close.call(this); + }; + InferredProject.prototype.getTypeAcquisition = function () { + return { + enable: allRootFilesAreJsOrDts(this), + include: [], + exclude: [] + }; + }; + InferredProject.newName = (function () { + var nextId = 1; + return function () { + var id = nextId; + nextId++; + return server.makeInferredProjectName(id); + }; + })(); + return InferredProject; + }(Project)); + server.InferredProject = InferredProject; + var ConfiguredProject = (function (_super) { + __extends(ConfiguredProject, _super); + function ConfiguredProject(configFileName, projectService, documentRegistry, cachedDirectoryStructureHost) { + var _this = _super.call(this, configFileName, ProjectKind.Configured, projectService, documentRegistry, false, undefined, {}, false, cachedDirectoryStructureHost, ts.getDirectoryPath(configFileName)) || this; + _this.canConfigFileJsonReportNoInputFiles = false; + _this.externalProjectRefCount = 0; + _this.isInitialLoadPending = ts.returnTrue; + _this.sendLoadingProjectFinish = false; + _this.canonicalConfigFilePath = server.asNormalizedPath(projectService.toCanonicalFileName(configFileName)); + return _this; + } + ConfiguredProject.prototype.updateGraph = function () { + this.isInitialLoadPending = ts.returnFalse; + var reloadLevel = this.pendingReload; + this.pendingReload = ts.ConfigFileProgramReloadLevel.None; + var result; + switch (reloadLevel) { + case ts.ConfigFileProgramReloadLevel.Partial: + result = this.projectService.reloadFileNamesOfConfiguredProject(this); + break; + case ts.ConfigFileProgramReloadLevel.Full: + var reason = ts.Debug.assertDefined(this.pendingReloadReason); + this.pendingReloadReason = undefined; + this.projectService.reloadConfiguredProject(this, reason); + result = true; + break; + default: + result = _super.prototype.updateGraph.call(this); + } + this.projectService.sendProjectLoadingFinishEvent(this); + this.projectService.sendProjectTelemetry(this); + this.projectService.sendSurveyReady(this); + return result; + }; + ConfiguredProject.prototype.getCachedDirectoryStructureHost = function () { + return this.directoryStructureHost; + }; + ConfiguredProject.prototype.getConfigFilePath = function () { + return server.asNormalizedPath(this.getProjectName()); + }; + ConfiguredProject.prototype.getProjectReferences = function () { + return this.projectReferences; + }; + ConfiguredProject.prototype.updateReferences = function (refs) { + this.projectReferences = refs; + }; + ConfiguredProject.prototype.forEachResolvedProjectReference = function (cb) { + var program = this.getCurrentProgram(); + return program && program.forEachResolvedProjectReference(cb); + }; + ConfiguredProject.prototype.enablePluginsWithOptions = function (options, pluginConfigOverrides) { + var host = this.projectService.host; + if (!host.require) { + this.projectService.logger.info("Plugins were requested but not running in environment that supports 'require'. Nothing will be loaded"); + return; + } + var searchPaths = [ts.combinePaths(this.projectService.getExecutingFilePath(), "../../..")].concat(this.projectService.pluginProbeLocations); + if (this.projectService.allowLocalPluginLoads) { + var local = ts.getDirectoryPath(this.canonicalConfigFilePath); + this.projectService.logger.info("Local plugin loading enabled; adding " + local + " to search paths"); + searchPaths.unshift(local); + } + if (options.plugins) { + for (var _i = 0, _a = options.plugins; _i < _a.length; _i++) { + var pluginConfigEntry = _a[_i]; + this.enablePlugin(pluginConfigEntry, searchPaths, pluginConfigOverrides); + } + } + this.enableGlobalPlugins(options, pluginConfigOverrides); + }; + ConfiguredProject.prototype.getGlobalProjectErrors = function () { + return ts.filter(this.projectErrors, function (diagnostic) { return !diagnostic.file; }) || server.emptyArray; + }; + ConfiguredProject.prototype.getAllProjectErrors = function () { + return this.projectErrors || server.emptyArray; + }; + ConfiguredProject.prototype.setProjectErrors = function (projectErrors) { + this.projectErrors = projectErrors; + }; + ConfiguredProject.prototype.setTypeAcquisition = function (newTypeAcquisition) { + this.typeAcquisition = this.removeLocalTypingsFromTypeAcquisition(newTypeAcquisition); + }; + ConfiguredProject.prototype.getTypeAcquisition = function () { + return this.typeAcquisition; + }; + ConfiguredProject.prototype.watchWildcards = function (wildcardDirectories) { + var _this = this; + ts.updateWatchingWildcardDirectories(this.directoriesWatchedForWildcards || (this.directoriesWatchedForWildcards = ts.createMap()), wildcardDirectories, function (directory, flags) { return _this.projectService.watchWildcardDirectory(directory, flags, _this); }); + }; + ConfiguredProject.prototype.stopWatchingWildCards = function () { + if (this.directoriesWatchedForWildcards) { + ts.clearMap(this.directoriesWatchedForWildcards, ts.closeFileWatcherOf); + this.directoriesWatchedForWildcards = undefined; + } + }; + ConfiguredProject.prototype.close = function () { + if (this.configFileWatcher) { + this.configFileWatcher.close(); + this.configFileWatcher = undefined; + } + this.stopWatchingWildCards(); + this.projectErrors = undefined; + this.configFileSpecs = undefined; + _super.prototype.close.call(this); + }; + ConfiguredProject.prototype.addExternalProjectReference = function () { + this.externalProjectRefCount++; + }; + ConfiguredProject.prototype.deleteExternalProjectReference = function () { + this.externalProjectRefCount--; + }; + ConfiguredProject.prototype.hasOpenRef = function () { + var _this = this; + if (!!this.externalProjectRefCount) { + return true; + } + if (this.isClosed()) { + return false; + } + var configFileExistenceInfo = this.projectService.getConfigFileExistenceInfo(this); + if (this.projectService.hasPendingProjectUpdate(this)) { + return !!configFileExistenceInfo.openFilesImpactedByConfigFile.size; + } + return ts.forEachEntry(configFileExistenceInfo.openFilesImpactedByConfigFile, function (_value, infoPath) { return _this.containsScriptInfo(_this.projectService.getScriptInfoForPath(infoPath)); }) || false; + }; + ConfiguredProject.prototype.hasExternalProjectRef = function () { + return !!this.externalProjectRefCount; + }; + ConfiguredProject.prototype.getEffectiveTypeRoots = function () { + return ts.getEffectiveTypeRoots(this.getCompilationSettings(), this.directoryStructureHost) || []; + }; + ConfiguredProject.prototype.updateErrorOnNoInputFiles = function (fileNameResult) { + ts.updateErrorForNoInputFiles(fileNameResult, this.getConfigFilePath(), this.configFileSpecs, this.projectErrors, this.canConfigFileJsonReportNoInputFiles); + }; + return ConfiguredProject; + }(Project)); + server.ConfiguredProject = ConfiguredProject; + var ExternalProject = (function (_super) { + __extends(ExternalProject, _super); + function ExternalProject(externalProjectName, projectService, documentRegistry, compilerOptions, lastFileExceededProgramSize, compileOnSaveEnabled, projectFilePath) { + var _this = _super.call(this, externalProjectName, ProjectKind.External, projectService, documentRegistry, true, lastFileExceededProgramSize, compilerOptions, compileOnSaveEnabled, projectService.host, ts.getDirectoryPath(projectFilePath || ts.normalizeSlashes(externalProjectName))) || this; + _this.externalProjectName = externalProjectName; + _this.compileOnSaveEnabled = compileOnSaveEnabled; + _this.excludedFiles = []; + return _this; + } + ExternalProject.prototype.updateGraph = function () { + var result = _super.prototype.updateGraph.call(this); + this.projectService.sendProjectTelemetry(this); + this.projectService.sendSurveyReady(this); + return result; + }; + ExternalProject.prototype.getExcludedFiles = function () { + return this.excludedFiles; + }; + ExternalProject.prototype.getTypeAcquisition = function () { + return this.typeAcquisition; + }; + ExternalProject.prototype.setTypeAcquisition = function (newTypeAcquisition) { + ts.Debug.assert(!!newTypeAcquisition, "newTypeAcquisition may not be null/undefined"); + ts.Debug.assert(!!newTypeAcquisition.include, "newTypeAcquisition.include may not be null/undefined"); + ts.Debug.assert(!!newTypeAcquisition.exclude, "newTypeAcquisition.exclude may not be null/undefined"); + ts.Debug.assert(typeof newTypeAcquisition.enable === "boolean", "newTypeAcquisition.enable may not be null/undefined"); + this.typeAcquisition = this.removeLocalTypingsFromTypeAcquisition(newTypeAcquisition); + }; + return ExternalProject; + }(Project)); + server.ExternalProject = ExternalProject; + })(server = ts.server || (ts.server = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + var server; + (function (server) { + server.maxProgramSizeForNonTsFiles = 20 * 1024 * 1024; + server.maxFileSize = 4 * 1024 * 1024; + server.ProjectsUpdatedInBackgroundEvent = "projectsUpdatedInBackground"; + server.ProjectLoadingStartEvent = "projectLoadingStart"; + server.ProjectLoadingFinishEvent = "projectLoadingFinish"; + server.SurveyReady = "surveyReady"; + server.LargeFileReferencedEvent = "largeFileReferenced"; + server.ConfigFileDiagEvent = "configFileDiag"; + server.ProjectLanguageServiceStateEvent = "projectLanguageServiceState"; + server.ProjectInfoTelemetryEvent = "projectInfo"; + server.OpenFileInfoTelemetryEvent = "openFileInfo"; + function prepareConvertersForEnumLikeCompilerOptions(commandLineOptions) { + var map = ts.createMap(); + for (var _i = 0, commandLineOptions_1 = commandLineOptions; _i < commandLineOptions_1.length; _i++) { + var option = commandLineOptions_1[_i]; + if (typeof option.type === "object") { + var optionMap = option.type; + optionMap.forEach(function (value) { + ts.Debug.assert(typeof value === "number"); + }); + map.set(option.name, optionMap); + } + } + return map; + } + var compilerOptionConverters = prepareConvertersForEnumLikeCompilerOptions(ts.optionDeclarations); + var indentStyle = ts.createMapFromTemplate({ + none: ts.IndentStyle.None, + block: ts.IndentStyle.Block, + smart: ts.IndentStyle.Smart + }); + var defaultTypeSafeList = { + "jquery": { + match: /jquery(-(\.?\d+)+)?(\.intellisense)?(\.min)?\.js$/i, + types: ["jquery"] + }, + "WinJS": { + match: /^(.*\/winjs-[.\d]+)\/js\/base\.js$/i, + exclude: [["^", 1, "/.*"]], + types: ["winjs"] + }, + "Kendo": { + match: /^(.*\/kendo(-ui)?)\/kendo\.all(\.min)?\.js$/i, + exclude: [["^", 1, "/.*"]], + types: ["kendo-ui"] + }, + "Office Nuget": { + match: /^(.*\/office\/1)\/excel-\d+\.debug\.js$/i, + exclude: [["^", 1, "/.*"]], + types: ["office"] + }, + "References": { + match: /^(.*\/_references\.js)$/i, + exclude: [["^", 1, "$"]] + } + }; + function convertFormatOptions(protocolOptions) { + if (ts.isString(protocolOptions.indentStyle)) { + protocolOptions.indentStyle = indentStyle.get(protocolOptions.indentStyle.toLowerCase()); + ts.Debug.assert(protocolOptions.indentStyle !== undefined); + } + return protocolOptions; + } + server.convertFormatOptions = convertFormatOptions; + function convertCompilerOptions(protocolOptions) { + compilerOptionConverters.forEach(function (mappedValues, id) { + var propertyValue = protocolOptions[id]; + if (ts.isString(propertyValue)) { + protocolOptions[id] = mappedValues.get(propertyValue.toLowerCase()); + } + }); + return protocolOptions; + } + server.convertCompilerOptions = convertCompilerOptions; + function tryConvertScriptKindName(scriptKindName) { + return ts.isString(scriptKindName) ? convertScriptKindName(scriptKindName) : scriptKindName; + } + server.tryConvertScriptKindName = tryConvertScriptKindName; + function convertScriptKindName(scriptKindName) { + switch (scriptKindName) { + case "JS": + return 1; + case "JSX": + return 2; + case "TS": + return 3; + case "TSX": + return 4; + default: + return 0; + } + } + server.convertScriptKindName = convertScriptKindName; + function convertUserPreferences(preferences) { + var lazyConfiguredProjectsFromExternalProject = preferences.lazyConfiguredProjectsFromExternalProject, userPreferences = __rest(preferences, ["lazyConfiguredProjectsFromExternalProject"]); + return userPreferences; + } + server.convertUserPreferences = convertUserPreferences; + var fileNamePropertyReader = { + getFileName: function (x) { return x; }, + getScriptKind: function (fileName, extraFileExtensions) { + var result; + if (extraFileExtensions) { + var fileExtension_1 = ts.getAnyExtensionFromPath(fileName); + if (fileExtension_1) { + ts.some(extraFileExtensions, function (info) { + if (info.extension === fileExtension_1) { + result = info.scriptKind; + return true; + } + return false; + }); + } + } + return result; + }, + hasMixedContent: function (fileName, extraFileExtensions) { return ts.some(extraFileExtensions, function (ext) { return ext.isMixedContent && ts.fileExtensionIs(fileName, ext.extension); }); }, + }; + var externalFilePropertyReader = { + getFileName: function (x) { return x.fileName; }, + getScriptKind: function (x) { return tryConvertScriptKindName(x.scriptKind); }, + hasMixedContent: function (x) { return !!x.hasMixedContent; }, + }; + function findProjectByName(projectName, projects) { + for (var _i = 0, projects_1 = projects; _i < projects_1.length; _i++) { + var proj = projects_1[_i]; + if (proj.getProjectName() === projectName) { + return proj; + } + } + } + var WatchType; + (function (WatchType) { + WatchType["ConfigFilePath"] = "Config file for the program"; + WatchType["MissingFilePath"] = "Missing file from program"; + WatchType["WildcardDirectories"] = "Wild card directory"; + WatchType["ClosedScriptInfo"] = "Closed Script info"; + WatchType["ConfigFileForInferredRoot"] = "Config file for the inferred project root"; + WatchType["FailedLookupLocation"] = "Directory of Failed lookup locations in module resolution"; + WatchType["TypeRoots"] = "Type root directory"; + WatchType["NodeModulesForClosedScriptInfo"] = "node_modules for closed script infos in them"; + })(WatchType = server.WatchType || (server.WatchType = {})); + var ConfigFileWatcherStatus; + (function (ConfigFileWatcherStatus) { + ConfigFileWatcherStatus["ReloadingFiles"] = "Reloading configured projects for files"; + ConfigFileWatcherStatus["ReloadingInferredRootFiles"] = "Reloading configured projects for only inferred root files"; + ConfigFileWatcherStatus["UpdatedCallback"] = "Updated the callback"; + ConfigFileWatcherStatus["OpenFilesImpactedByConfigFileAdd"] = "File added to open files impacted by this config file"; + ConfigFileWatcherStatus["OpenFilesImpactedByConfigFileRemove"] = "File removed from open files impacted by this config file"; + ConfigFileWatcherStatus["RootOfInferredProjectTrue"] = "Open file was set as Inferred root"; + ConfigFileWatcherStatus["RootOfInferredProjectFalse"] = "Open file was set as not inferred root"; + })(ConfigFileWatcherStatus || (ConfigFileWatcherStatus = {})); + function isOpenScriptInfo(infoOrFileName) { + return !!infoOrFileName.containingProjects; + } + function getDetailWatchInfo(watchType, project) { + return "Project: " + (project ? project.getProjectName() : "") + " WatchType: " + watchType; + } + function isScriptInfoWatchedFromNodeModules(info) { + return !info.isScriptOpen() && info.mTime !== undefined; + } + function updateProjectIfDirty(project) { + return project.dirty && project.updateGraph(); + } + server.updateProjectIfDirty = updateProjectIfDirty; + function setProjectOptionsUsed(project) { + if (project.projectKind === server.ProjectKind.Configured) { + project.projectOptions = true; + } + } + var ProjectService = (function () { + function ProjectService(opts) { + var _this = this; + this.filenameToScriptInfo = ts.createMap(); + this.scriptInfoInNodeModulesWatchers = ts.createMap(); + this.filenameToScriptInfoVersion = ts.createMap(); + this.allJsFilesForOpenFileTelemetry = ts.createMap(); + this.externalProjectToConfiguredProjectMap = ts.createMap(); + this.externalProjects = []; + this.inferredProjects = []; + this.configuredProjects = ts.createMap(); + this.openFiles = ts.createMap(); + this.openFilesWithNonRootedDiskPath = ts.createMap(); + this.compilerOptionsForInferredProjectsPerProjectRoot = ts.createMap(); + this.projectToSizeMap = ts.createMap(); + this.configFileExistenceInfoCache = ts.createMap(); + this.safelist = defaultTypeSafeList; + this.legacySafelist = ts.createMap(); + this.pendingProjectUpdates = ts.createMap(); + this.pendingEnsureProjectForOpenFiles = false; + this.seenProjects = ts.createMap(); + this.seenSurveyProjects = ts.createMap(); + this.host = opts.host; + this.logger = opts.logger; + this.cancellationToken = opts.cancellationToken; + this.useSingleInferredProject = opts.useSingleInferredProject; + this.useInferredProjectPerProjectRoot = opts.useInferredProjectPerProjectRoot; + this.typingsInstaller = opts.typingsInstaller || server.nullTypingsInstaller; + this.throttleWaitMilliseconds = opts.throttleWaitMilliseconds; + this.eventHandler = opts.eventHandler; + this.suppressDiagnosticEvents = opts.suppressDiagnosticEvents; + this.globalPlugins = opts.globalPlugins || server.emptyArray; + this.pluginProbeLocations = opts.pluginProbeLocations || server.emptyArray; + this.allowLocalPluginLoads = !!opts.allowLocalPluginLoads; + this.typesMapLocation = (opts.typesMapLocation === undefined) ? ts.combinePaths(ts.getDirectoryPath(this.getExecutingFilePath()), "typesMap.json") : opts.typesMapLocation; + this.syntaxOnly = opts.syntaxOnly; + ts.Debug.assert(!!this.host.createHash, "'ServerHost.createHash' is required for ProjectService"); + if (this.host.realpath) { + this.realpathToScriptInfos = ts.createMultiMap(); + } + this.currentDirectory = server.toNormalizedPath(this.host.getCurrentDirectory()); + this.toCanonicalFileName = ts.createGetCanonicalFileName(this.host.useCaseSensitiveFileNames); + this.globalCacheLocationDirectoryPath = this.typingsInstaller.globalTypingsCacheLocation + ? ts.ensureTrailingDirectorySeparator(this.toPath(this.typingsInstaller.globalTypingsCacheLocation)) + : undefined; + this.throttledOperations = new server.ThrottledOperations(this.host, this.logger); + if (this.typesMapLocation) { + this.loadTypesMap(); + } + else { + this.logger.info("No types map provided; using the default"); + } + this.typingsInstaller.attach(this); + this.typingsCache = new server.TypingsCache(this.typingsInstaller); + this.hostConfiguration = { + formatCodeOptions: ts.getDefaultFormatCodeSettings(this.host.newLine), + preferences: ts.emptyOptions, + hostInfo: "Unknown host", + extraFileExtensions: [] + }; + this.documentRegistry = ts.createDocumentRegistryInternal(this.host.useCaseSensitiveFileNames, this.currentDirectory, this); + var watchLogLevel = this.logger.hasLevel(server.LogLevel.verbose) ? ts.WatchLogLevel.Verbose : + this.logger.loggingEnabled() ? ts.WatchLogLevel.TriggerOnly : ts.WatchLogLevel.None; + var log = watchLogLevel !== ts.WatchLogLevel.None ? (function (s) { return _this.logger.info(s); }) : ts.noop; + this.watchFactory = ts.getWatchFactory(watchLogLevel, log, getDetailWatchInfo); + } + ProjectService.prototype.toPath = function (fileName) { + return ts.toPath(fileName, this.currentDirectory, this.toCanonicalFileName); + }; + ProjectService.prototype.getExecutingFilePath = function () { + return this.getNormalizedAbsolutePath(this.host.getExecutingFilePath()); + }; + ProjectService.prototype.getNormalizedAbsolutePath = function (fileName) { + return ts.getNormalizedAbsolutePath(fileName, this.host.getCurrentDirectory()); + }; + ProjectService.prototype.setDocument = function (key, path, sourceFile) { + var info = ts.Debug.assertDefined(this.getScriptInfoForPath(path)); + info.cacheSourceFile = { key: key, sourceFile: sourceFile }; + }; + ProjectService.prototype.getDocument = function (key, path) { + var info = this.getScriptInfoForPath(path); + return info && info.cacheSourceFile && info.cacheSourceFile.key === key ? info.cacheSourceFile.sourceFile : undefined; + }; + ProjectService.prototype.ensureInferredProjectsUpToDate_TestOnly = function () { + this.ensureProjectStructuresUptoDate(); + }; + ProjectService.prototype.getCompilerOptionsForInferredProjects = function () { + return this.compilerOptionsForInferredProjects; + }; + ProjectService.prototype.onUpdateLanguageServiceStateForProject = function (project, languageServiceEnabled) { + if (!this.eventHandler) { + return; + } + var event = { + eventName: server.ProjectLanguageServiceStateEvent, + data: { project: project, languageServiceEnabled: languageServiceEnabled } + }; + this.eventHandler(event); + }; + ProjectService.prototype.loadTypesMap = function () { + try { + var fileContent = this.host.readFile(this.typesMapLocation); + if (fileContent === undefined) { + this.logger.info("Provided types map file \"" + this.typesMapLocation + "\" doesn't exist"); + return; + } + var raw = JSON.parse(fileContent); + for (var _i = 0, _a = Object.keys(raw.typesMap); _i < _a.length; _i++) { + var k = _a[_i]; + raw.typesMap[k].match = new RegExp(raw.typesMap[k].match, "i"); + } + this.safelist = raw.typesMap; + for (var key in raw.simpleMap) { + if (raw.simpleMap.hasOwnProperty(key)) { + this.legacySafelist.set(key, raw.simpleMap[key].toLowerCase()); + } + } + } + catch (e) { + this.logger.info("Error loading types map: " + e); + this.safelist = defaultTypeSafeList; + this.legacySafelist.clear(); + } + }; + ProjectService.prototype.updateTypingsForProject = function (response) { + var project = this.findProject(response.projectName); + if (!project) { + return; + } + switch (response.kind) { + case server.ActionSet: + project.updateTypingFiles(this.typingsCache.updateTypingsForProject(response.projectName, response.compilerOptions, response.typeAcquisition, response.unresolvedImports, response.typings)); + break; + case server.ActionInvalidate: + this.typingsCache.enqueueInstallTypingsForProject(project, project.lastCachedUnresolvedImportsList, true); + return; + } + this.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles(project); + }; + ProjectService.prototype.delayEnsureProjectForOpenFiles = function () { + var _this = this; + this.pendingEnsureProjectForOpenFiles = true; + this.throttledOperations.schedule("*ensureProjectForOpenFiles*", 250, function () { + if (_this.pendingProjectUpdates.size !== 0) { + _this.delayEnsureProjectForOpenFiles(); + } + else { + if (_this.pendingEnsureProjectForOpenFiles) { + _this.ensureProjectForOpenFiles(); + _this.sendProjectsUpdatedInBackgroundEvent(); + } + } + }); + }; + ProjectService.prototype.delayUpdateProjectGraph = function (project) { + var _this = this; + project.markAsDirty(); + var projectName = project.getProjectName(); + this.pendingProjectUpdates.set(projectName, project); + this.throttledOperations.schedule(projectName, 250, function () { + if (_this.pendingProjectUpdates.delete(projectName)) { + updateProjectIfDirty(project); + } + }); + }; + ProjectService.prototype.hasPendingProjectUpdate = function (project) { + return this.pendingProjectUpdates.has(project.getProjectName()); + }; + ProjectService.prototype.sendProjectsUpdatedInBackgroundEvent = function () { + var _this = this; + if (!this.eventHandler) { + return; + } + var event = { + eventName: server.ProjectsUpdatedInBackgroundEvent, + data: { + openFiles: ts.arrayFrom(this.openFiles.keys(), function (path) { return _this.getScriptInfoForPath(path).fileName; }) + } + }; + this.eventHandler(event); + }; + ProjectService.prototype.sendSurveyReadyEvent = function (surveyId) { + if (!this.eventHandler) { + return; + } + this.eventHandler({ eventName: server.SurveyReady, data: { surveyId: surveyId } }); + }; + ProjectService.prototype.sendLargeFileReferencedEvent = function (file, fileSize) { + if (!this.eventHandler) { + return; + } + var event = { + eventName: server.LargeFileReferencedEvent, + data: { file: file, fileSize: fileSize, maxFileSize: server.maxFileSize } + }; + this.eventHandler(event); + }; + ProjectService.prototype.sendProjectLoadingStartEvent = function (project, reason) { + if (!this.eventHandler) { + return; + } + project.sendLoadingProjectFinish = true; + var event = { + eventName: server.ProjectLoadingStartEvent, + data: { project: project, reason: reason } + }; + this.eventHandler(event); + }; + ProjectService.prototype.sendProjectLoadingFinishEvent = function (project) { + if (!this.eventHandler || !project.sendLoadingProjectFinish) { + return; + } + project.sendLoadingProjectFinish = false; + var event = { + eventName: server.ProjectLoadingFinishEvent, + data: { project: project } + }; + this.eventHandler(event); + }; + ProjectService.prototype.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles = function (project) { + this.delayUpdateProjectGraph(project); + this.delayEnsureProjectForOpenFiles(); + }; + ProjectService.prototype.delayUpdateProjectGraphs = function (projects) { + if (projects.length) { + for (var _i = 0, projects_2 = projects; _i < projects_2.length; _i++) { + var project = projects_2[_i]; + this.delayUpdateProjectGraph(project); + } + this.delayEnsureProjectForOpenFiles(); + } + }; + ProjectService.prototype.setCompilerOptionsForInferredProjects = function (projectCompilerOptions, projectRootPath) { + ts.Debug.assert(projectRootPath === undefined || this.useInferredProjectPerProjectRoot, "Setting compiler options per project root path is only supported when useInferredProjectPerProjectRoot is enabled"); + var compilerOptions = convertCompilerOptions(projectCompilerOptions); + compilerOptions.allowNonTsExtensions = true; + var canonicalProjectRootPath = projectRootPath && this.toCanonicalFileName(projectRootPath); + if (canonicalProjectRootPath) { + this.compilerOptionsForInferredProjectsPerProjectRoot.set(canonicalProjectRootPath, compilerOptions); + } + else { + this.compilerOptionsForInferredProjects = compilerOptions; + } + for (var _i = 0, _a = this.inferredProjects; _i < _a.length; _i++) { + var project = _a[_i]; + if (canonicalProjectRootPath ? + project.projectRootPath === canonicalProjectRootPath : + !project.projectRootPath || !this.compilerOptionsForInferredProjectsPerProjectRoot.has(project.projectRootPath)) { + project.setCompilerOptions(compilerOptions); + project.compileOnSaveEnabled = compilerOptions.compileOnSave; + project.markAsDirty(); + this.delayUpdateProjectGraph(project); + } + } + this.delayEnsureProjectForOpenFiles(); + }; + ProjectService.prototype.findProject = function (projectName) { + if (projectName === undefined) { + return undefined; + } + if (server.isInferredProjectName(projectName)) { + return findProjectByName(projectName, this.inferredProjects); + } + return this.findExternalProjectByProjectName(projectName) || this.findConfiguredProjectByProjectName(server.toNormalizedPath(projectName)); + }; + ProjectService.prototype.forEachProject = function (cb) { + this.externalProjects.forEach(cb); + this.configuredProjects.forEach(cb); + this.inferredProjects.forEach(cb); + }; + ProjectService.prototype.forEachEnabledProject = function (cb) { + this.forEachProject(function (project) { + if (!project.isOrphan() && project.languageServiceEnabled) { + cb(project); + } + }); + }; + ProjectService.prototype.getDefaultProjectForFile = function (fileName, ensureProject) { + return ensureProject ? this.ensureDefaultProjectForFile(fileName) : this.tryGetDefaultProjectForFile(fileName); + }; + ProjectService.prototype.tryGetDefaultProjectForFile = function (fileName) { + var scriptInfo = this.getScriptInfoForNormalizedPath(fileName); + return scriptInfo && !scriptInfo.isOrphan() ? scriptInfo.getDefaultProject() : undefined; + }; + ProjectService.prototype.ensureDefaultProjectForFile = function (fileName) { + return this.tryGetDefaultProjectForFile(fileName) || this.doEnsureDefaultProjectForFile(fileName); + }; + ProjectService.prototype.doEnsureDefaultProjectForFile = function (fileName) { + this.ensureProjectStructuresUptoDate(); + var scriptInfo = this.getScriptInfoForNormalizedPath(fileName); + return scriptInfo ? scriptInfo.getDefaultProject() : (this.logErrorForScriptInfoNotFound(fileName), server.Errors.ThrowNoProject()); + }; + ProjectService.prototype.getScriptInfoEnsuringProjectsUptoDate = function (uncheckedFileName) { + this.ensureProjectStructuresUptoDate(); + return this.getScriptInfo(uncheckedFileName); + }; + ProjectService.prototype.ensureProjectStructuresUptoDate = function () { + var hasChanges = this.pendingEnsureProjectForOpenFiles; + this.pendingProjectUpdates.clear(); + var updateGraph = function (project) { + hasChanges = updateProjectIfDirty(project) || hasChanges; + }; + this.externalProjects.forEach(updateGraph); + this.configuredProjects.forEach(updateGraph); + this.inferredProjects.forEach(updateGraph); + if (hasChanges) { + this.ensureProjectForOpenFiles(); + } + }; + ProjectService.prototype.getFormatCodeOptions = function (file) { + var info = this.getScriptInfoForNormalizedPath(file); + return info && info.getFormatCodeSettings() || this.hostConfiguration.formatCodeOptions; + }; + ProjectService.prototype.getPreferences = function (file) { + var info = this.getScriptInfoForNormalizedPath(file); + return info && info.getPreferences() || this.hostConfiguration.preferences; + }; + ProjectService.prototype.getHostFormatCodeOptions = function () { + return this.hostConfiguration.formatCodeOptions; + }; + ProjectService.prototype.getHostPreferences = function () { + return this.hostConfiguration.preferences; + }; + ProjectService.prototype.onSourceFileChanged = function (fileName, eventKind, path) { + var info = this.getScriptInfoForPath(path); + if (!info) { + this.logger.msg("Error: got watch notification for unknown file: " + fileName); + } + else { + if (info.containingProjects) { + info.containingProjects.forEach(function (project) { return project.resolutionCache.removeResolutionsFromProjectReferenceRedirects(info.path); }); + } + if (eventKind === ts.FileWatcherEventKind.Deleted) { + this.handleDeletedFile(info); + } + else if (!info.isScriptOpen()) { + info.delayReloadNonMixedContentFile(); + this.delayUpdateProjectGraphs(info.containingProjects); + } + } + }; + ProjectService.prototype.handleDeletedFile = function (info) { + this.stopWatchingScriptInfo(info); + if (!info.isScriptOpen()) { + this.deleteScriptInfo(info); + var containingProjects = info.containingProjects.slice(); + info.detachAllProjects(); + this.delayUpdateProjectGraphs(containingProjects); + } + }; + ProjectService.prototype.watchWildcardDirectory = function (directory, flags, project) { + var _this = this; + return this.watchFactory.watchDirectory(this.host, directory, function (fileOrDirectory) { + var fileOrDirectoryPath = _this.toPath(fileOrDirectory); + project.getCachedDirectoryStructureHost().addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); + if (ts.isPathInNodeModulesStartingWithDot(fileOrDirectoryPath)) + return; + var configFilename = project.getConfigFilePath(); + if (fileOrDirectoryPath !== directory && ts.hasExtension(fileOrDirectoryPath) && !ts.isSupportedSourceFileName(fileOrDirectory, project.getCompilationSettings(), _this.hostConfiguration.extraFileExtensions)) { + _this.logger.info("Project: " + configFilename + " Detected file add/remove of non supported extension: " + fileOrDirectory); + return; + } + if (project.pendingReload !== ts.ConfigFileProgramReloadLevel.Full) { + project.pendingReload = ts.ConfigFileProgramReloadLevel.Partial; + _this.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles(project); + } + }, flags, "Wild card directory", project); + }; + ProjectService.prototype.getConfigFileExistenceInfo = function (project) { + return this.configFileExistenceInfoCache.get(project.canonicalConfigFilePath); + }; + ProjectService.prototype.onConfigChangedForConfiguredProject = function (project, eventKind) { + var configFileExistenceInfo = this.getConfigFileExistenceInfo(project); + if (eventKind === ts.FileWatcherEventKind.Deleted) { + configFileExistenceInfo.exists = false; + this.removeProject(project); + this.logConfigFileWatchUpdate(project.getConfigFilePath(), project.canonicalConfigFilePath, configFileExistenceInfo, "Reloading configured projects for files"); + this.delayReloadConfiguredProjectForFiles(configFileExistenceInfo, false); + } + else { + this.logConfigFileWatchUpdate(project.getConfigFilePath(), project.canonicalConfigFilePath, configFileExistenceInfo, "Reloading configured projects for only inferred root files"); + project.pendingReload = ts.ConfigFileProgramReloadLevel.Full; + project.pendingReloadReason = "Change in config file detected"; + this.delayUpdateProjectGraph(project); + this.delayReloadConfiguredProjectForFiles(configFileExistenceInfo, true); + } + }; + ProjectService.prototype.onConfigFileChangeForOpenScriptInfo = function (configFileName, eventKind) { + var canonicalConfigPath = server.normalizedPathToPath(configFileName, this.currentDirectory, this.toCanonicalFileName); + var configFileExistenceInfo = this.configFileExistenceInfoCache.get(canonicalConfigPath); + configFileExistenceInfo.exists = (eventKind !== ts.FileWatcherEventKind.Deleted); + this.logConfigFileWatchUpdate(configFileName, canonicalConfigPath, configFileExistenceInfo, "Reloading configured projects for files"); + this.delayReloadConfiguredProjectForFiles(configFileExistenceInfo, false); + }; + ProjectService.prototype.removeProject = function (project) { + var _this = this; + this.logger.info("`remove Project::"); + project.print(); + project.close(); + if (ts.Debug.shouldAssert(1)) { + this.filenameToScriptInfo.forEach(function (info) { return ts.Debug.assert(!info.isAttached(project), "Found script Info still attached to project", function () { return project.projectName + ": ScriptInfos still attached: " + JSON.stringify(ts.mapDefined(ts.arrayFrom(_this.filenameToScriptInfo.values()), function (info) { return info.isAttached(project) ? info : undefined; })); }); }); + } + this.pendingProjectUpdates.delete(project.getProjectName()); + switch (project.projectKind) { + case server.ProjectKind.External: + ts.unorderedRemoveItem(this.externalProjects, project); + this.projectToSizeMap.delete(project.getProjectName()); + break; + case server.ProjectKind.Configured: + this.configuredProjects.delete(project.canonicalConfigFilePath); + this.projectToSizeMap.delete(project.canonicalConfigFilePath); + this.setConfigFileExistenceInfoByClosedConfiguredProject(project); + break; + case server.ProjectKind.Inferred: + ts.unorderedRemoveItem(this.inferredProjects, project); + break; + } + }; + ProjectService.prototype.assignOrphanScriptInfoToInferredProject = function (info, projectRootPath) { + ts.Debug.assert(info.isOrphan()); + var project = this.getOrCreateInferredProjectForProjectRootPathIfEnabled(info, projectRootPath) || + this.getOrCreateSingleInferredProjectIfEnabled() || + this.getOrCreateSingleInferredWithoutProjectRoot(info.isDynamic ? this.currentDirectory : ts.getDirectoryPath(info.path)); + project.addRoot(info); + if (info.containingProjects[0] !== project) { + info.detachFromProject(project); + info.containingProjects.unshift(project); + } + project.updateGraph(); + if (!this.useSingleInferredProject && !project.projectRootPath) { + var _loop_2 = function (inferredProject) { + if (inferredProject === project || inferredProject.isOrphan()) { + return "continue"; + } + var roots = inferredProject.getRootScriptInfos(); + ts.Debug.assert(roots.length === 1 || !!inferredProject.projectRootPath); + if (roots.length === 1 && ts.forEach(roots[0].containingProjects, function (p) { return p !== roots[0].containingProjects[0] && !p.isOrphan(); })) { + inferredProject.removeFile(roots[0], true, true); + } + }; + for (var _i = 0, _a = this.inferredProjects; _i < _a.length; _i++) { + var inferredProject = _a[_i]; + _loop_2(inferredProject); + } + } + return project; + }; + ProjectService.prototype.closeOpenFile = function (info) { + var _this = this; + var fileExists = this.host.fileExists(info.fileName); + info.close(fileExists); + this.stopWatchingConfigFilesForClosedScriptInfo(info); + var canonicalFileName = this.toCanonicalFileName(info.fileName); + if (this.openFilesWithNonRootedDiskPath.get(canonicalFileName) === info) { + this.openFilesWithNonRootedDiskPath.delete(canonicalFileName); + } + var ensureProjectsForOpenFiles = false; + for (var _i = 0, _a = info.containingProjects; _i < _a.length; _i++) { + var p = _a[_i]; + if (p.projectKind === server.ProjectKind.Configured) { + if (info.hasMixedContent) { + info.registerFileUpdate(); + } + } + else if (p.projectKind === server.ProjectKind.Inferred && p.isRoot(info)) { + if (p.isProjectWithSingleRoot()) { + ensureProjectsForOpenFiles = true; + } + p.removeFile(info, fileExists, true); + } + if (!p.languageServiceEnabled) { + p.markAsDirty(); + } + } + this.openFiles.delete(info.path); + if (ensureProjectsForOpenFiles) { + this.openFiles.forEach(function (projectRootPath, path) { + var info = _this.getScriptInfoForPath(path); + if (info.isOrphan()) { + _this.assignOrphanScriptInfoToInferredProject(info, projectRootPath); + } + }); + } + if (fileExists) { + this.watchClosedScriptInfo(info); + } + else { + this.handleDeletedFile(info); + } + }; + ProjectService.prototype.deleteScriptInfo = function (info) { + this.filenameToScriptInfo.delete(info.path); + this.filenameToScriptInfoVersion.set(info.path, info.getVersion()); + var realpath = info.getRealpathIfDifferent(); + if (realpath) { + this.realpathToScriptInfos.remove(realpath, info); + } + }; + ProjectService.prototype.configFileExists = function (configFileName, canonicalConfigFilePath, info) { + var configFileExistenceInfo = this.configFileExistenceInfoCache.get(canonicalConfigFilePath); + if (configFileExistenceInfo) { + if (isOpenScriptInfo(info) && !configFileExistenceInfo.openFilesImpactedByConfigFile.has(info.path)) { + configFileExistenceInfo.openFilesImpactedByConfigFile.set(info.path, false); + this.logConfigFileWatchUpdate(configFileName, canonicalConfigFilePath, configFileExistenceInfo, "File added to open files impacted by this config file"); + } + return configFileExistenceInfo.exists; + } + var exists = this.host.fileExists(configFileName); + var openFilesImpactedByConfigFile = ts.createMap(); + if (isOpenScriptInfo(info)) { + openFilesImpactedByConfigFile.set(info.path, false); + } + configFileExistenceInfo = { exists: exists, openFilesImpactedByConfigFile: openFilesImpactedByConfigFile }; + this.configFileExistenceInfoCache.set(canonicalConfigFilePath, configFileExistenceInfo); + this.logConfigFileWatchUpdate(configFileName, canonicalConfigFilePath, configFileExistenceInfo, "File added to open files impacted by this config file"); + return exists; + }; + ProjectService.prototype.setConfigFileExistenceByNewConfiguredProject = function (project) { + var configFileExistenceInfo = this.getConfigFileExistenceInfo(project); + if (configFileExistenceInfo) { + ts.Debug.assert(configFileExistenceInfo.exists); + if (configFileExistenceInfo.configFileWatcherForRootOfInferredProject) { + var configFileName = project.getConfigFilePath(); + configFileExistenceInfo.configFileWatcherForRootOfInferredProject.close(); + configFileExistenceInfo.configFileWatcherForRootOfInferredProject = undefined; + this.logConfigFileWatchUpdate(configFileName, project.canonicalConfigFilePath, configFileExistenceInfo, "Updated the callback"); + } + } + else { + this.configFileExistenceInfoCache.set(project.canonicalConfigFilePath, { + exists: true, + openFilesImpactedByConfigFile: ts.createMap() + }); + } + }; + ProjectService.prototype.configFileExistenceImpactsRootOfInferredProject = function (configFileExistenceInfo) { + return ts.forEachEntry(configFileExistenceInfo.openFilesImpactedByConfigFile, function (isRootOfInferredProject) { return isRootOfInferredProject; }); + }; + ProjectService.prototype.setConfigFileExistenceInfoByClosedConfiguredProject = function (closedProject) { + var configFileExistenceInfo = this.getConfigFileExistenceInfo(closedProject); + ts.Debug.assert(!!configFileExistenceInfo); + if (configFileExistenceInfo.openFilesImpactedByConfigFile.size) { + var configFileName = closedProject.getConfigFilePath(); + if (this.configFileExistenceImpactsRootOfInferredProject(configFileExistenceInfo)) { + ts.Debug.assert(!configFileExistenceInfo.configFileWatcherForRootOfInferredProject); + this.createConfigFileWatcherOfConfigFileExistence(configFileName, closedProject.canonicalConfigFilePath, configFileExistenceInfo); + } + } + else { + this.configFileExistenceInfoCache.delete(closedProject.canonicalConfigFilePath); + } + }; + ProjectService.prototype.logConfigFileWatchUpdate = function (configFileName, canonicalConfigFilePath, configFileExistenceInfo, status) { + var _this = this; + if (!this.logger.hasLevel(server.LogLevel.verbose)) { + return; + } + var inferredRoots = []; + var otherFiles = []; + configFileExistenceInfo.openFilesImpactedByConfigFile.forEach(function (isRootOfInferredProject, key) { + var info = _this.getScriptInfoForPath(key); + (isRootOfInferredProject ? inferredRoots : otherFiles).push(info.fileName); + }); + var watches = []; + if (configFileExistenceInfo.configFileWatcherForRootOfInferredProject) { + watches.push("Config file for the inferred project root"); + } + if (this.configuredProjects.has(canonicalConfigFilePath)) { + watches.push("Config file for the program"); + } + this.logger.info("ConfigFilePresence:: Current Watches: " + watches + ":: File: " + configFileName + " Currently impacted open files: RootsOfInferredProjects: " + inferredRoots + " OtherOpenFiles: " + otherFiles + " Status: " + status); + }; + ProjectService.prototype.createConfigFileWatcherOfConfigFileExistence = function (configFileName, canonicalConfigFilePath, configFileExistenceInfo) { + var _this = this; + configFileExistenceInfo.configFileWatcherForRootOfInferredProject = this.watchFactory.watchFile(this.host, configFileName, function (_filename, eventKind) { return _this.onConfigFileChangeForOpenScriptInfo(configFileName, eventKind); }, ts.PollingInterval.High, "Config file for the inferred project root"); + this.logConfigFileWatchUpdate(configFileName, canonicalConfigFilePath, configFileExistenceInfo, "Updated the callback"); + }; + ProjectService.prototype.closeConfigFileWatcherOfConfigFileExistenceInfo = function (configFileExistenceInfo) { + if (configFileExistenceInfo.configFileWatcherForRootOfInferredProject && + !this.configFileExistenceImpactsRootOfInferredProject(configFileExistenceInfo)) { + configFileExistenceInfo.configFileWatcherForRootOfInferredProject.close(); + configFileExistenceInfo.configFileWatcherForRootOfInferredProject = undefined; + } + }; + ProjectService.prototype.stopWatchingConfigFilesForClosedScriptInfo = function (info) { + var _this = this; + ts.Debug.assert(!info.isScriptOpen()); + this.forEachConfigFileLocation(info, function (configFileName, canonicalConfigFilePath) { + var configFileExistenceInfo = _this.configFileExistenceInfoCache.get(canonicalConfigFilePath); + if (configFileExistenceInfo) { + var infoIsRootOfInferredProject = configFileExistenceInfo.openFilesImpactedByConfigFile.get(info.path); + configFileExistenceInfo.openFilesImpactedByConfigFile.delete(info.path); + _this.logConfigFileWatchUpdate(configFileName, canonicalConfigFilePath, configFileExistenceInfo, "File removed from open files impacted by this config file"); + if (infoIsRootOfInferredProject) { + _this.closeConfigFileWatcherOfConfigFileExistenceInfo(configFileExistenceInfo); + } + if (!configFileExistenceInfo.openFilesImpactedByConfigFile.size && + !_this.getConfiguredProjectByCanonicalConfigFilePath(canonicalConfigFilePath)) { + ts.Debug.assert(!configFileExistenceInfo.configFileWatcherForRootOfInferredProject); + _this.configFileExistenceInfoCache.delete(canonicalConfigFilePath); + } + } + }); + }; + ProjectService.prototype.startWatchingConfigFilesForInferredProjectRoot = function (info) { + var _this = this; + ts.Debug.assert(info.isScriptOpen()); + this.forEachConfigFileLocation(info, function (configFileName, canonicalConfigFilePath) { + var configFileExistenceInfo = _this.configFileExistenceInfoCache.get(canonicalConfigFilePath); + if (!configFileExistenceInfo) { + configFileExistenceInfo = { + exists: _this.host.fileExists(configFileName), + openFilesImpactedByConfigFile: ts.createMap() + }; + _this.configFileExistenceInfoCache.set(canonicalConfigFilePath, configFileExistenceInfo); + } + configFileExistenceInfo.openFilesImpactedByConfigFile.set(info.path, true); + _this.logConfigFileWatchUpdate(configFileName, canonicalConfigFilePath, configFileExistenceInfo, "Open file was set as Inferred root"); + if (!configFileExistenceInfo.configFileWatcherForRootOfInferredProject && + !_this.getConfiguredProjectByCanonicalConfigFilePath(canonicalConfigFilePath)) { + _this.createConfigFileWatcherOfConfigFileExistence(configFileName, canonicalConfigFilePath, configFileExistenceInfo); + } + }); + }; + ProjectService.prototype.stopWatchingConfigFilesForInferredProjectRoot = function (info) { + var _this = this; + this.forEachConfigFileLocation(info, function (configFileName, canonicalConfigFilePath) { + var configFileExistenceInfo = _this.configFileExistenceInfoCache.get(canonicalConfigFilePath); + if (configFileExistenceInfo && configFileExistenceInfo.openFilesImpactedByConfigFile.has(info.path)) { + ts.Debug.assert(info.isScriptOpen()); + configFileExistenceInfo.openFilesImpactedByConfigFile.set(info.path, false); + _this.logConfigFileWatchUpdate(configFileName, canonicalConfigFilePath, configFileExistenceInfo, "Open file was set as not inferred root"); + _this.closeConfigFileWatcherOfConfigFileExistenceInfo(configFileExistenceInfo); + } + }); + }; + ProjectService.prototype.forEachConfigFileLocation = function (info, action) { + var _this = this; + if (this.syntaxOnly) { + return undefined; + } + ts.Debug.assert(!isOpenScriptInfo(info) || this.openFiles.has(info.path)); + var projectRootPath = this.openFiles.get(info.path); + var searchPath = server.asNormalizedPath(ts.getDirectoryPath(info.fileName)); + var isSearchPathInProjectRoot = function () { return ts.containsPath(projectRootPath, searchPath, _this.currentDirectory, !_this.host.useCaseSensitiveFileNames); }; + var anySearchPathOk = !projectRootPath || !isSearchPathInProjectRoot(); + do { + var canonicalSearchPath = server.normalizedPathToPath(searchPath, this.currentDirectory, this.toCanonicalFileName); + var tsconfigFileName = server.asNormalizedPath(ts.combinePaths(searchPath, "tsconfig.json")); + var result = action(tsconfigFileName, ts.combinePaths(canonicalSearchPath, "tsconfig.json")); + if (result) { + return tsconfigFileName; + } + var jsconfigFileName = server.asNormalizedPath(ts.combinePaths(searchPath, "jsconfig.json")); + result = action(jsconfigFileName, ts.combinePaths(canonicalSearchPath, "jsconfig.json")); + if (result) { + return jsconfigFileName; + } + var parentPath = server.asNormalizedPath(ts.getDirectoryPath(searchPath)); + if (parentPath === searchPath) { + break; + } + searchPath = parentPath; + } while (anySearchPathOk || isSearchPathInProjectRoot()); + return undefined; + }; + ProjectService.prototype.getConfigFileNameForFile = function (info) { + var _this = this; + if (isOpenScriptInfo(info)) + ts.Debug.assert(info.isScriptOpen()); + this.logger.info("Search path: " + ts.getDirectoryPath(info.fileName)); + var configFileName = this.forEachConfigFileLocation(info, function (configFileName, canonicalConfigFilePath) { + return _this.configFileExists(configFileName, canonicalConfigFilePath, info); + }); + if (configFileName) { + this.logger.info("For info: " + info.fileName + " :: Config file name: " + configFileName); + } + else { + this.logger.info("For info: " + info.fileName + " :: No config files found."); + } + return configFileName; + }; + ProjectService.prototype.printProjects = function () { + var _this = this; + if (!this.logger.hasLevel(server.LogLevel.normal)) { + return; + } + var writeProjectFileNames = this.logger.hasLevel(server.LogLevel.verbose); + this.logger.startGroup(); + var counter = printProjectsWithCounter(this.externalProjects, 0); + counter = printProjectsWithCounter(ts.arrayFrom(this.configuredProjects.values()), counter); + printProjectsWithCounter(this.inferredProjects, counter); + this.logger.info("Open files: "); + this.openFiles.forEach(function (projectRootPath, path) { + var info = _this.getScriptInfoForPath(path); + _this.logger.info("\tFileName: " + info.fileName + " ProjectRootPath: " + projectRootPath); + if (writeProjectFileNames) { + _this.logger.info("\t\tProjects: " + info.containingProjects.map(function (p) { return p.getProjectName(); })); + } + }); + this.logger.endGroup(); + }; + ProjectService.prototype.findConfiguredProjectByProjectName = function (configFileName) { + var canonicalConfigFilePath = server.asNormalizedPath(this.toCanonicalFileName(configFileName)); + return this.getConfiguredProjectByCanonicalConfigFilePath(canonicalConfigFilePath); + }; + ProjectService.prototype.getConfiguredProjectByCanonicalConfigFilePath = function (canonicalConfigFilePath) { + return this.configuredProjects.get(canonicalConfigFilePath); + }; + ProjectService.prototype.findExternalProjectByProjectName = function (projectFileName) { + return findProjectByName(projectFileName, this.externalProjects); + }; + ProjectService.prototype.getFilenameForExceededTotalSizeLimitForNonTsFiles = function (name, options, fileNames, propertyReader) { + if (options && options.disableSizeLimit || !this.host.getFileSize) { + return; + } + var availableSpace = server.maxProgramSizeForNonTsFiles; + this.projectToSizeMap.set(name, 0); + this.projectToSizeMap.forEach(function (val) { return (availableSpace -= (val || 0)); }); + var totalNonTsFileSize = 0; + for (var _i = 0, fileNames_1 = fileNames; _i < fileNames_1.length; _i++) { + var f = fileNames_1[_i]; + var fileName = propertyReader.getFileName(f); + if (ts.hasTSFileExtension(fileName)) { + continue; + } + totalNonTsFileSize += this.host.getFileSize(fileName); + if (totalNonTsFileSize > server.maxProgramSizeForNonTsFiles || totalNonTsFileSize > availableSpace) { + this.logger.info(getExceedLimitMessage({ propertyReader: propertyReader, hasTSFileExtension: ts.hasTSFileExtension, host: this.host }, totalNonTsFileSize)); + return fileName; + } + } + this.projectToSizeMap.set(name, totalNonTsFileSize); + return; + function getExceedLimitMessage(context, totalNonTsFileSize) { + var files = getTop5LargestFiles(context); + return "Non TS file size exceeded limit (" + totalNonTsFileSize + "). Largest files: " + files.map(function (file) { return file.name + ":" + file.size; }).join(", "); + } + function getTop5LargestFiles(_a) { + var propertyReader = _a.propertyReader, hasTSFileExtension = _a.hasTSFileExtension, host = _a.host; + return fileNames.map(function (f) { return propertyReader.getFileName(f); }) + .filter(function (name) { return hasTSFileExtension(name); }) + .map(function (name) { return ({ name: name, size: host.getFileSize(name) }); }) + .sort(function (a, b) { return b.size - a.size; }) + .slice(0, 5); + } + }; + ProjectService.prototype.createExternalProject = function (projectFileName, files, options, typeAcquisition, excludedFiles) { + var compilerOptions = convertCompilerOptions(options); + var project = new server.ExternalProject(projectFileName, this, this.documentRegistry, compilerOptions, this.getFilenameForExceededTotalSizeLimitForNonTsFiles(projectFileName, compilerOptions, files, externalFilePropertyReader), options.compileOnSave === undefined ? true : options.compileOnSave); + project.excludedFiles = excludedFiles; + this.addFilesToNonInferredProject(project, files, externalFilePropertyReader, typeAcquisition); + this.externalProjects.push(project); + return project; + }; + ProjectService.prototype.sendSurveyReady = function (project) { + if (this.seenSurveyProjects.has(project.projectName)) { + return; + } + if (project.getCompilerOptions().checkJs !== undefined) { + var name = "checkJs"; + this.logger.info("Survey " + name + " is ready"); + this.sendSurveyReadyEvent(name); + this.seenSurveyProjects.set(project.projectName, true); + } + }; + ProjectService.prototype.sendProjectTelemetry = function (project) { + if (this.seenProjects.has(project.projectName)) { + setProjectOptionsUsed(project); + return; + } + this.seenProjects.set(project.projectName, true); + if (!this.eventHandler || !this.host.createSHA256Hash) { + setProjectOptionsUsed(project); + return; + } + var projectOptions = project.projectKind === server.ProjectKind.Configured ? project.projectOptions : undefined; + setProjectOptionsUsed(project); + var data = { + projectId: this.host.createSHA256Hash(project.projectName), + fileStats: server.countEachFileTypes(project.getScriptInfos(), true), + compilerOptions: ts.convertCompilerOptionsForTelemetry(project.getCompilationSettings()), + typeAcquisition: convertTypeAcquisition(project.getTypeAcquisition()), + extends: projectOptions && projectOptions.configHasExtendsProperty, + files: projectOptions && projectOptions.configHasFilesProperty, + include: projectOptions && projectOptions.configHasIncludeProperty, + exclude: projectOptions && projectOptions.configHasExcludeProperty, + compileOnSave: project.compileOnSaveEnabled, + configFileName: configFileName(), + projectType: project instanceof server.ExternalProject ? "external" : "configured", + languageServiceEnabled: project.languageServiceEnabled, + version: ts.version, + }; + this.eventHandler({ eventName: server.ProjectInfoTelemetryEvent, data: data }); + function configFileName() { + if (!(project instanceof server.ConfiguredProject)) { + return "other"; + } + return server.getBaseConfigFileName(project.getConfigFilePath()) || "other"; + } + function convertTypeAcquisition(_a) { + var enable = _a.enable, include = _a.include, exclude = _a.exclude; + return { + enable: enable, + include: include !== undefined && include.length !== 0, + exclude: exclude !== undefined && exclude.length !== 0, + }; + } + }; + ProjectService.prototype.addFilesToNonInferredProject = function (project, files, propertyReader, typeAcquisition) { + this.updateNonInferredProjectFiles(project, files, propertyReader); + project.setTypeAcquisition(typeAcquisition); + }; + ProjectService.prototype.createConfiguredProject = function (configFileName) { + var _this = this; + var cachedDirectoryStructureHost = ts.createCachedDirectoryStructureHost(this.host, this.host.getCurrentDirectory(), this.host.useCaseSensitiveFileNames); + this.logger.info("Opened configuration file " + configFileName); + var project = new server.ConfiguredProject(configFileName, this, this.documentRegistry, cachedDirectoryStructureHost); + project.configFileWatcher = this.watchFactory.watchFile(this.host, configFileName, function (_fileName, eventKind) { return _this.onConfigChangedForConfiguredProject(project, eventKind); }, ts.PollingInterval.High, "Config file for the program", project); + this.configuredProjects.set(project.canonicalConfigFilePath, project); + this.setConfigFileExistenceByNewConfiguredProject(project); + return project; + }; + ProjectService.prototype.createConfiguredProjectWithDelayLoad = function (configFileName, reason) { + var project = this.createConfiguredProject(configFileName); + project.pendingReload = ts.ConfigFileProgramReloadLevel.Full; + project.pendingReloadReason = reason; + return project; + }; + ProjectService.prototype.createAndLoadConfiguredProject = function (configFileName, reason) { + var project = this.createConfiguredProject(configFileName); + this.loadConfiguredProject(project, reason); + return project; + }; + ProjectService.prototype.createLoadAndUpdateConfiguredProject = function (configFileName, reason) { + var project = this.createAndLoadConfiguredProject(configFileName, reason); + project.updateGraph(); + return project; + }; + ProjectService.prototype.loadConfiguredProject = function (project, reason) { + this.sendProjectLoadingStartEvent(project, reason); + var configFilename = ts.normalizePath(project.getConfigFilePath()); + var configFileContent = this.host.readFile(configFilename); + var result = ts.parseJsonText(configFilename, configFileContent); + if (!result.endOfFileToken) { + result.endOfFileToken = { kind: 1 }; + } + var configFileErrors = result.parseDiagnostics; + var parsedCommandLine = ts.parseJsonSourceFileConfigFileContent(result, project.getCachedDirectoryStructureHost(), ts.getDirectoryPath(configFilename), {}, configFilename, [], this.hostConfiguration.extraFileExtensions); + if (parsedCommandLine.errors.length) { + configFileErrors.push.apply(configFileErrors, parsedCommandLine.errors); + } + ts.Debug.assert(!!parsedCommandLine.fileNames); + var compilerOptions = parsedCommandLine.options; + if (!project.projectOptions) { + project.projectOptions = { + configHasExtendsProperty: parsedCommandLine.raw.extends !== undefined, + configHasFilesProperty: parsedCommandLine.raw.files !== undefined, + configHasIncludeProperty: parsedCommandLine.raw.include !== undefined, + configHasExcludeProperty: parsedCommandLine.raw.exclude !== undefined + }; + } + project.configFileSpecs = parsedCommandLine.configFileSpecs; + project.canConfigFileJsonReportNoInputFiles = ts.canJsonReportNoInutFiles(parsedCommandLine.raw); + project.setProjectErrors(configFileErrors); + project.updateReferences(parsedCommandLine.projectReferences); + var lastFileExceededProgramSize = this.getFilenameForExceededTotalSizeLimitForNonTsFiles(project.canonicalConfigFilePath, compilerOptions, parsedCommandLine.fileNames, fileNamePropertyReader); + if (lastFileExceededProgramSize) { + project.disableLanguageService(lastFileExceededProgramSize); + project.stopWatchingWildCards(); + } + else { + project.enableLanguageService(); + project.watchWildcards(ts.createMapFromTemplate(parsedCommandLine.wildcardDirectories)); + } + project.enablePluginsWithOptions(compilerOptions, this.currentPluginConfigOverrides); + var filesToAdd = parsedCommandLine.fileNames.concat(project.getExternalFiles()); + this.updateRootAndOptionsOfNonInferredProject(project, filesToAdd, fileNamePropertyReader, compilerOptions, parsedCommandLine.typeAcquisition, parsedCommandLine.compileOnSave); + }; + ProjectService.prototype.updateNonInferredProjectFiles = function (project, files, propertyReader) { + var projectRootFilesMap = project.getRootFilesMap(); + var newRootScriptInfoMap = ts.createMap(); + for (var _i = 0, files_1 = files; _i < files_1.length; _i++) { + var f = files_1[_i]; + var newRootFile = propertyReader.getFileName(f); + var normalizedPath = server.toNormalizedPath(newRootFile); + var isDynamic = server.isDynamicFileName(normalizedPath); + var scriptInfo = void 0; + var path = void 0; + if (!isDynamic && !project.fileExists(newRootFile)) { + path = server.normalizedPathToPath(normalizedPath, this.currentDirectory, this.toCanonicalFileName); + var existingValue = projectRootFilesMap.get(path); + if (server.isScriptInfo(existingValue)) { + project.removeFile(existingValue, false, true); + } + projectRootFilesMap.set(path, normalizedPath); + scriptInfo = normalizedPath; + } + else { + var scriptKind = propertyReader.getScriptKind(f, this.hostConfiguration.extraFileExtensions); + var hasMixedContent = propertyReader.hasMixedContent(f, this.hostConfiguration.extraFileExtensions); + scriptInfo = this.getOrCreateScriptInfoNotOpenedByClientForNormalizedPath(normalizedPath, project.currentDirectory, scriptKind, hasMixedContent, project.directoryStructureHost); + path = scriptInfo.path; + if (!project.isRoot(scriptInfo)) { + project.addRoot(scriptInfo); + if (scriptInfo.isScriptOpen()) { + this.removeRootOfInferredProjectIfNowPartOfOtherProject(scriptInfo); + } + } + } + newRootScriptInfoMap.set(path, scriptInfo); + } + if (projectRootFilesMap.size > newRootScriptInfoMap.size) { + projectRootFilesMap.forEach(function (value, path) { + if (!newRootScriptInfoMap.has(path)) { + if (server.isScriptInfo(value)) { + project.removeFile(value, project.fileExists(path), true); + } + else { + projectRootFilesMap.delete(path); + } + } + }); + } + project.markAsDirty(); + }; + ProjectService.prototype.updateRootAndOptionsOfNonInferredProject = function (project, newUncheckedFiles, propertyReader, newOptions, newTypeAcquisition, compileOnSave) { + project.setCompilerOptions(newOptions); + if (compileOnSave !== undefined) { + project.compileOnSaveEnabled = compileOnSave; + } + this.addFilesToNonInferredProject(project, newUncheckedFiles, propertyReader, newTypeAcquisition); + }; + ProjectService.prototype.reloadFileNamesOfConfiguredProject = function (project) { + var configFileSpecs = project.configFileSpecs; + var configFileName = project.getConfigFilePath(); + var fileNamesResult = ts.getFileNamesFromConfigSpecs(configFileSpecs, ts.getDirectoryPath(configFileName), project.getCompilationSettings(), project.getCachedDirectoryStructureHost(), this.hostConfiguration.extraFileExtensions); + project.updateErrorOnNoInputFiles(fileNamesResult); + this.updateNonInferredProjectFiles(project, fileNamesResult.fileNames.concat(project.getExternalFiles()), fileNamePropertyReader); + return project.updateGraph(); + }; + ProjectService.prototype.reloadConfiguredProject = function (project, reason) { + var host = project.getCachedDirectoryStructureHost(); + host.clearCache(); + var configFileName = project.getConfigFilePath(); + this.logger.info("Reloading configured project " + configFileName); + this.loadConfiguredProject(project, reason); + project.updateGraph(); + this.sendConfigFileDiagEvent(project, configFileName); + }; + ProjectService.prototype.sendConfigFileDiagEvent = function (project, triggerFile) { + if (!this.eventHandler || this.suppressDiagnosticEvents) { + return; + } + var diagnostics = project.getLanguageService().getCompilerOptionsDiagnostics(); + diagnostics.push.apply(diagnostics, project.getAllProjectErrors()); + this.eventHandler({ + eventName: server.ConfigFileDiagEvent, + data: { configFileName: project.getConfigFilePath(), diagnostics: diagnostics, triggerFile: triggerFile } + }); + }; + ProjectService.prototype.getOrCreateInferredProjectForProjectRootPathIfEnabled = function (info, projectRootPath) { + if (info.isDynamic || !this.useInferredProjectPerProjectRoot) { + return undefined; + } + if (projectRootPath) { + var canonicalProjectRootPath = this.toCanonicalFileName(projectRootPath); + for (var _i = 0, _a = this.inferredProjects; _i < _a.length; _i++) { + var project = _a[_i]; + if (project.projectRootPath === canonicalProjectRootPath) { + return project; + } + } + return this.createInferredProject(projectRootPath, false, projectRootPath); + } + var bestMatch; + for (var _b = 0, _c = this.inferredProjects; _b < _c.length; _b++) { + var project = _c[_b]; + if (!project.projectRootPath) + continue; + if (!ts.containsPath(project.projectRootPath, info.path, this.host.getCurrentDirectory(), !this.host.useCaseSensitiveFileNames)) + continue; + if (bestMatch && bestMatch.projectRootPath.length > project.projectRootPath.length) + continue; + bestMatch = project; + } + return bestMatch; + }; + ProjectService.prototype.getOrCreateSingleInferredProjectIfEnabled = function () { + if (!this.useSingleInferredProject) { + return undefined; + } + if (this.inferredProjects.length > 0 && this.inferredProjects[0].projectRootPath === undefined) { + return this.inferredProjects[0]; + } + return this.createInferredProject(undefined, true); + }; + ProjectService.prototype.getOrCreateSingleInferredWithoutProjectRoot = function (currentDirectory) { + ts.Debug.assert(!this.useSingleInferredProject); + var expectedCurrentDirectory = this.toCanonicalFileName(this.getNormalizedAbsolutePath(currentDirectory || "")); + for (var _i = 0, _a = this.inferredProjects; _i < _a.length; _i++) { + var inferredProject = _a[_i]; + if (!inferredProject.projectRootPath && + inferredProject.isOrphan() && + inferredProject.canonicalCurrentDirectory === expectedCurrentDirectory) { + return inferredProject; + } + } + return this.createInferredProject(currentDirectory); + }; + ProjectService.prototype.createInferredProject = function (currentDirectory, isSingleInferredProject, projectRootPath) { + var compilerOptions = projectRootPath && this.compilerOptionsForInferredProjectsPerProjectRoot.get(projectRootPath) || this.compilerOptionsForInferredProjects; + var project = new server.InferredProject(this, this.documentRegistry, compilerOptions, projectRootPath, currentDirectory, this.currentPluginConfigOverrides); + if (isSingleInferredProject) { + this.inferredProjects.unshift(project); + } + else { + this.inferredProjects.push(project); + } + return project; + }; + ProjectService.prototype.getOrCreateScriptInfoNotOpenedByClient = function (uncheckedFileName, currentDirectory, hostToQueryFileExistsOn) { + return this.getOrCreateScriptInfoNotOpenedByClientForNormalizedPath(server.toNormalizedPath(uncheckedFileName), currentDirectory, undefined, undefined, hostToQueryFileExistsOn); + }; + ProjectService.prototype.getScriptInfo = function (uncheckedFileName) { + return this.getScriptInfoForNormalizedPath(server.toNormalizedPath(uncheckedFileName)); + }; + ProjectService.prototype.getScriptInfoOrConfig = function (uncheckedFileName) { + var path = server.toNormalizedPath(uncheckedFileName); + var info = this.getScriptInfoForNormalizedPath(path); + if (info) + return info; + var configProject = this.configuredProjects.get(uncheckedFileName); + return configProject && configProject.getCompilerOptions().configFile; + }; + ProjectService.prototype.logErrorForScriptInfoNotFound = function (fileName) { + var names = ts.arrayFrom(this.filenameToScriptInfo.entries()).map(function (_a) { + var path = _a[0], scriptInfo = _a[1]; + return ({ path: path, fileName: scriptInfo.fileName }); + }); + this.logger.msg("Could not find file " + JSON.stringify(fileName) + ".\nAll files are: " + JSON.stringify(names), server.Msg.Err); + }; + ProjectService.prototype.getSymlinkedProjects = function (info) { + var projects; + if (this.realpathToScriptInfos) { + var realpath = info.getRealpathIfDifferent(); + if (realpath) { + ts.forEach(this.realpathToScriptInfos.get(realpath), combineProjects); + } + ts.forEach(this.realpathToScriptInfos.get(info.path), combineProjects); + } + return projects; + function combineProjects(toAddInfo) { + if (toAddInfo !== info) { + var _loop_3 = function (project) { + if (project.languageServiceEnabled && + !project.isOrphan() && + !project.getCompilerOptions().preserveSymlinks && + !ts.contains(info.containingProjects, project)) { + if (!projects) { + projects = ts.createMultiMap(); + projects.add(toAddInfo.path, project); + } + else if (!ts.forEachEntry(projects, function (projs, path) { return path === toAddInfo.path ? false : ts.contains(projs, project); })) { + projects.add(toAddInfo.path, project); + } + } + }; + for (var _i = 0, _a = toAddInfo.containingProjects; _i < _a.length; _i++) { + var project = _a[_i]; + _loop_3(project); + } + } + } + }; + ProjectService.prototype.watchClosedScriptInfo = function (info) { + var _this = this; + ts.Debug.assert(!info.fileWatcher); + if (!info.isDynamicOrHasMixedContent() && + (!this.globalCacheLocationDirectoryPath || + !ts.startsWith(info.path, this.globalCacheLocationDirectoryPath))) { + var indexOfNodeModules = info.path.indexOf("/node_modules/"); + if (!this.host.getModifiedTime || indexOfNodeModules === -1) { + info.fileWatcher = this.watchFactory.watchFilePath(this.host, info.fileName, function (fileName, eventKind, path) { return _this.onSourceFileChanged(fileName, eventKind, path); }, ts.PollingInterval.Medium, info.path, "Closed Script info"); + } + else { + info.mTime = this.getModifiedTime(info); + info.fileWatcher = this.watchClosedScriptInfoInNodeModules(info.path.substr(0, indexOfNodeModules)); + } + } + }; + ProjectService.prototype.watchClosedScriptInfoInNodeModules = function (dir) { + var _this = this; + var existing = this.scriptInfoInNodeModulesWatchers.get(dir); + if (existing) { + existing.refCount++; + return existing; + } + var watchDir = dir + "/node_modules"; + var watcher = this.watchFactory.watchDirectory(this.host, watchDir, function (fileOrDirectory) { + var fileOrDirectoryPath = _this.toPath(fileOrDirectory); + if (ts.isPathInNodeModulesStartingWithDot(fileOrDirectoryPath)) + return; + ts.Debug.assert(result.refCount > 0); + if (watchDir === fileOrDirectoryPath) { + _this.refreshScriptInfosInDirectory(watchDir); + } + else { + var info = _this.getScriptInfoForPath(fileOrDirectoryPath); + if (info) { + if (isScriptInfoWatchedFromNodeModules(info)) { + _this.refreshScriptInfo(info); + } + } + else if (!ts.hasExtension(fileOrDirectoryPath)) { + _this.refreshScriptInfosInDirectory(fileOrDirectoryPath); + } + } + }, 1, "node_modules for closed script infos in them"); + var result = { + close: function () { + if (result.refCount === 1) { + watcher.close(); + _this.scriptInfoInNodeModulesWatchers.delete(dir); + } + else { + result.refCount--; + } + }, + refCount: 1 + }; + this.scriptInfoInNodeModulesWatchers.set(dir, result); + return result; + }; + ProjectService.prototype.getModifiedTime = function (info) { + return (this.host.getModifiedTime(info.path) || ts.missingFileModifiedTime).getTime(); + }; + ProjectService.prototype.refreshScriptInfo = function (info) { + var mTime = this.getModifiedTime(info); + if (mTime !== info.mTime) { + var eventKind = ts.getFileWatcherEventKind(info.mTime, mTime); + info.mTime = mTime; + this.onSourceFileChanged(info.fileName, eventKind, info.path); + } + }; + ProjectService.prototype.refreshScriptInfosInDirectory = function (dir) { + var _this = this; + dir = dir + ts.directorySeparator; + this.filenameToScriptInfo.forEach(function (info) { + if (isScriptInfoWatchedFromNodeModules(info) && ts.startsWith(info.path, dir)) { + _this.refreshScriptInfo(info); + } + }); + }; + ProjectService.prototype.stopWatchingScriptInfo = function (info) { + if (info.fileWatcher) { + info.fileWatcher.close(); + info.fileWatcher = undefined; + } + }; + ProjectService.prototype.getOrCreateScriptInfoNotOpenedByClientForNormalizedPath = function (fileName, currentDirectory, scriptKind, hasMixedContent, hostToQueryFileExistsOn) { + if (ts.isRootedDiskPath(fileName) || server.isDynamicFileName(fileName)) { + return this.getOrCreateScriptInfoWorker(fileName, currentDirectory, false, undefined, scriptKind, hasMixedContent, hostToQueryFileExistsOn); + } + var info = this.openFilesWithNonRootedDiskPath.get(this.toCanonicalFileName(fileName)); + if (info) { + return info; + } + return undefined; + }; + ProjectService.prototype.getOrCreateScriptInfoOpenedByClientForNormalizedPath = function (fileName, currentDirectory, fileContent, scriptKind, hasMixedContent) { + return this.getOrCreateScriptInfoWorker(fileName, currentDirectory, true, fileContent, scriptKind, hasMixedContent); + }; + ProjectService.prototype.getOrCreateScriptInfoForNormalizedPath = function (fileName, openedByClient, fileContent, scriptKind, hasMixedContent, hostToQueryFileExistsOn) { + return this.getOrCreateScriptInfoWorker(fileName, this.currentDirectory, openedByClient, fileContent, scriptKind, hasMixedContent, hostToQueryFileExistsOn); + }; + ProjectService.prototype.getOrCreateScriptInfoWorker = function (fileName, currentDirectory, openedByClient, fileContent, scriptKind, hasMixedContent, hostToQueryFileExistsOn) { + var _this = this; + ts.Debug.assert(fileContent === undefined || openedByClient, "ScriptInfo needs to be opened by client to be able to set its user defined content"); + var path = server.normalizedPathToPath(fileName, currentDirectory, this.toCanonicalFileName); + var info = this.getScriptInfoForPath(path); + if (!info) { + var isDynamic = server.isDynamicFileName(fileName); + ts.Debug.assert(ts.isRootedDiskPath(fileName) || isDynamic || openedByClient, "", function () { return JSON.stringify({ fileName: fileName, currentDirectory: currentDirectory, hostCurrentDirectory: _this.currentDirectory, openKeys: ts.arrayFrom(_this.openFilesWithNonRootedDiskPath.keys()) }) + "\nScript info with non-dynamic relative file name can only be open script info or in context of host currentDirectory"; }); + ts.Debug.assert(!ts.isRootedDiskPath(fileName) || this.currentDirectory === currentDirectory || !this.openFilesWithNonRootedDiskPath.has(this.toCanonicalFileName(fileName)), "", function () { return JSON.stringify({ fileName: fileName, currentDirectory: currentDirectory, hostCurrentDirectory: _this.currentDirectory, openKeys: ts.arrayFrom(_this.openFilesWithNonRootedDiskPath.keys()) }) + "\nOpen script files with non rooted disk path opened with current directory context cannot have same canonical names"; }); + ts.Debug.assert(!isDynamic || this.currentDirectory === currentDirectory, "", function () { return JSON.stringify({ fileName: fileName, currentDirectory: currentDirectory, hostCurrentDirectory: _this.currentDirectory, openKeys: ts.arrayFrom(_this.openFilesWithNonRootedDiskPath.keys()) }) + "\nDynamic files must always have current directory context since containing external project name will always match the script info name."; }); + if (!openedByClient && !isDynamic && !(hostToQueryFileExistsOn || this.host).fileExists(fileName)) { + return; + } + info = new server.ScriptInfo(this.host, fileName, scriptKind, !!hasMixedContent, path, this.filenameToScriptInfoVersion.get(path)); + this.filenameToScriptInfo.set(info.path, info); + this.filenameToScriptInfoVersion.delete(info.path); + if (!openedByClient) { + this.watchClosedScriptInfo(info); + } + else if (!ts.isRootedDiskPath(fileName) && !isDynamic) { + this.openFilesWithNonRootedDiskPath.set(this.toCanonicalFileName(fileName), info); + } + } + if (openedByClient && !info.isScriptOpen()) { + this.stopWatchingScriptInfo(info); + info.open(fileContent); + if (hasMixedContent) { + info.registerFileUpdate(); + } + } + else { + ts.Debug.assert(fileContent === undefined); + } + return info; + }; + ProjectService.prototype.getScriptInfoForNormalizedPath = function (fileName) { + return !ts.isRootedDiskPath(fileName) && this.openFilesWithNonRootedDiskPath.get(this.toCanonicalFileName(fileName)) || + this.getScriptInfoForPath(server.normalizedPathToPath(fileName, this.currentDirectory, this.toCanonicalFileName)); + }; + ProjectService.prototype.getScriptInfoForPath = function (fileName) { + return this.filenameToScriptInfo.get(fileName); + }; + ProjectService.prototype.setHostConfiguration = function (args) { + var _this = this; + if (args.file) { + var info = this.getScriptInfoForNormalizedPath(server.toNormalizedPath(args.file)); + if (info) { + info.setOptions(convertFormatOptions(args.formatOptions), args.preferences); + this.logger.info("Host configuration update for file " + args.file); + } + } + else { + if (args.hostInfo !== undefined) { + this.hostConfiguration.hostInfo = args.hostInfo; + this.logger.info("Host information " + args.hostInfo); + } + if (args.formatOptions) { + this.hostConfiguration.formatCodeOptions = __assign({}, this.hostConfiguration.formatCodeOptions, convertFormatOptions(args.formatOptions)); + this.logger.info("Format host information updated"); + } + if (args.preferences) { + var lazyConfiguredProjectsFromExternalProject = this.hostConfiguration.preferences.lazyConfiguredProjectsFromExternalProject; + this.hostConfiguration.preferences = __assign({}, this.hostConfiguration.preferences, args.preferences); + if (lazyConfiguredProjectsFromExternalProject && !this.hostConfiguration.preferences.lazyConfiguredProjectsFromExternalProject) { + this.configuredProjects.forEach(function (project) { + if (project.hasExternalProjectRef() && + project.pendingReload === ts.ConfigFileProgramReloadLevel.Full && + !_this.pendingProjectUpdates.has(project.getProjectName())) { + project.updateGraph(); + } + }); + } + } + if (args.extraFileExtensions) { + this.hostConfiguration.extraFileExtensions = args.extraFileExtensions; + this.reloadProjects(); + this.logger.info("Host file extension mappings updated"); + } + } + }; + ProjectService.prototype.closeLog = function () { + this.logger.close(); + }; + ProjectService.prototype.reloadProjects = function () { + this.logger.info("reload projects."); + this.reloadConfiguredProjectForFiles(this.openFiles, false, ts.returnTrue, "User requested reload projects"); + this.ensureProjectForOpenFiles(); + }; + ProjectService.prototype.delayReloadConfiguredProjectForFiles = function (configFileExistenceInfo, ignoreIfNotRootOfInferredProject) { + this.reloadConfiguredProjectForFiles(configFileExistenceInfo.openFilesImpactedByConfigFile, true, ignoreIfNotRootOfInferredProject ? + function (isRootOfInferredProject) { return isRootOfInferredProject; } : + ts.returnTrue, "Change in config file detected"); + this.delayEnsureProjectForOpenFiles(); + }; + ProjectService.prototype.reloadConfiguredProjectForFiles = function (openFiles, delayReload, shouldReloadProjectFor, reason) { + var _this = this; + var updatedProjects = ts.createMap(); + openFiles.forEach(function (openFileValue, path) { + if (!shouldReloadProjectFor(openFileValue)) { + return; + } + var info = _this.getScriptInfoForPath(path); + ts.Debug.assert(info.isScriptOpen()); + var configFileName = _this.getConfigFileNameForFile(info); + if (configFileName) { + var project = _this.findConfiguredProjectByProjectName(configFileName) || _this.createConfiguredProject(configFileName); + if (!updatedProjects.has(configFileName)) { + if (delayReload) { + project.pendingReload = ts.ConfigFileProgramReloadLevel.Full; + project.pendingReloadReason = reason; + _this.delayUpdateProjectGraph(project); + } + else { + _this.reloadConfiguredProject(project, reason); + } + updatedProjects.set(configFileName, true); + } + } + }); + }; + ProjectService.prototype.removeRootOfInferredProjectIfNowPartOfOtherProject = function (info) { + ts.Debug.assert(info.containingProjects.length > 0); + var firstProject = info.containingProjects[0]; + if (!firstProject.isOrphan() && + firstProject.projectKind === server.ProjectKind.Inferred && + firstProject.isRoot(info) && + ts.forEach(info.containingProjects, function (p) { return p !== firstProject && !p.isOrphan(); })) { + firstProject.removeFile(info, true, true); + } + }; + ProjectService.prototype.ensureProjectForOpenFiles = function () { + var _this = this; + this.logger.info("Structure before ensureProjectForOpenFiles:"); + this.printProjects(); + this.openFiles.forEach(function (projectRootPath, path) { + var info = _this.getScriptInfoForPath(path); + if (info.isOrphan()) { + _this.assignOrphanScriptInfoToInferredProject(info, projectRootPath); + } + else { + _this.removeRootOfInferredProjectIfNowPartOfOtherProject(info); + } + }); + this.pendingEnsureProjectForOpenFiles = false; + this.inferredProjects.forEach(updateProjectIfDirty); + this.logger.info("Structure after ensureProjectForOpenFiles:"); + this.printProjects(); + }; + ProjectService.prototype.openClientFile = function (fileName, fileContent, scriptKind, projectRootPath) { + return this.openClientFileWithNormalizedPath(server.toNormalizedPath(fileName), fileContent, scriptKind, false, projectRootPath ? server.toNormalizedPath(projectRootPath) : undefined); + }; + ProjectService.prototype.getOriginalLocationEnsuringConfiguredProject = function (project, location) { + var originalLocation = project.getSourceMapper().tryGetSourcePosition(location); + if (!originalLocation) + return undefined; + var fileName = originalLocation.fileName; + if (!this.getScriptInfo(fileName) && !this.host.fileExists(fileName)) + return undefined; + var originalFileInfo = { fileName: server.toNormalizedPath(fileName), path: this.toPath(fileName) }; + var configFileName = this.getConfigFileNameForFile(originalFileInfo); + if (!configFileName) + return undefined; + var configuredProject = this.findConfiguredProjectByProjectName(configFileName) || + this.createAndLoadConfiguredProject(configFileName, "Creating project for original file: " + originalFileInfo.fileName + " for location: " + location.fileName); + updateProjectIfDirty(configuredProject); + addOriginalConfiguredProject(configuredProject); + var originalScriptInfo = this.getScriptInfo(fileName); + if (!originalScriptInfo || !originalScriptInfo.containingProjects.length) + return undefined; + originalScriptInfo.containingProjects.forEach(function (project) { + if (project.projectKind === server.ProjectKind.Configured) { + addOriginalConfiguredProject(project); + } + }); + return originalLocation; + function addOriginalConfiguredProject(originalProject) { + if (!project.originalConfiguredProjects) { + project.originalConfiguredProjects = ts.createMap(); + } + project.originalConfiguredProjects.set(originalProject.canonicalConfigFilePath, true); + } + }; + ProjectService.prototype.fileExists = function (fileName) { + return this.filenameToScriptInfo.has(fileName) || this.host.fileExists(fileName); + }; + ProjectService.prototype.findExternalProjectContainingOpenScriptInfo = function (info) { + return ts.find(this.externalProjects, function (proj) { + updateProjectIfDirty(proj); + return proj.containsScriptInfo(info); + }); + }; + ProjectService.prototype.openClientFileWithNormalizedPath = function (fileName, fileContent, scriptKind, hasMixedContent, projectRootPath) { + var _this = this; + var configFileName; + var configFileErrors; + var info = this.getOrCreateScriptInfoOpenedByClientForNormalizedPath(fileName, projectRootPath ? this.getNormalizedAbsolutePath(projectRootPath) : this.currentDirectory, fileContent, scriptKind, hasMixedContent); + this.openFiles.set(info.path, projectRootPath); + var project = this.findExternalProjectContainingOpenScriptInfo(info); + if (!project && !this.syntaxOnly) { + configFileName = this.getConfigFileNameForFile(info); + if (configFileName) { + project = this.findConfiguredProjectByProjectName(configFileName); + if (!project) { + project = this.createLoadAndUpdateConfiguredProject(configFileName, "Creating possible configured project for " + fileName + " to open"); + if (info.isOrphan()) { + configFileName = undefined; + } + else { + configFileErrors = project.getAllProjectErrors(); + this.sendConfigFileDiagEvent(project, fileName); + } + } + else { + updateProjectIfDirty(project); + } + } + } + info.containingProjects.forEach(updateProjectIfDirty); + if (info.isOrphan()) { + this.assignOrphanScriptInfoToInferredProject(info, projectRootPath); + } + ts.Debug.assert(!info.isOrphan()); + this.removeOrphanConfiguredProjects(); + for (var _i = 0, _a = this.inferredProjects.slice(); _i < _a.length; _i++) { + var inferredProject = _a[_i]; + if (inferredProject.isOrphan()) { + this.removeProject(inferredProject); + } + } + this.filenameToScriptInfo.forEach(function (info) { + if (!info.isScriptOpen() && info.isOrphan()) { + _this.stopWatchingScriptInfo(info); + _this.deleteScriptInfo(info); + } + }); + this.printProjects(); + this.telemetryOnOpenFile(info); + return { configFileName: configFileName, configFileErrors: configFileErrors }; + }; + ProjectService.prototype.removeOrphanConfiguredProjects = function () { + var _this = this; + var toRemoveConfiguredProjects = ts.cloneMap(this.configuredProjects); + this.inferredProjects.forEach(markOriginalProjectsAsUsed); + this.externalProjects.forEach(markOriginalProjectsAsUsed); + this.configuredProjects.forEach(function (project) { + if (project.hasOpenRef()) { + toRemoveConfiguredProjects.delete(project.canonicalConfigFilePath); + markOriginalProjectsAsUsed(project); + } + else { + project.forEachResolvedProjectReference(function (ref) { + if (ref) { + var refProject = _this.configuredProjects.get(ref.sourceFile.path); + if (refProject && refProject.hasOpenRef()) { + toRemoveConfiguredProjects.delete(project.canonicalConfigFilePath); + } + } + }); + } + }); + toRemoveConfiguredProjects.forEach(function (project) { return _this.removeProject(project); }); + function markOriginalProjectsAsUsed(project) { + if (!project.isOrphan() && project.originalConfiguredProjects) { + project.originalConfiguredProjects.forEach(function (_value, configuredProjectPath) { return toRemoveConfiguredProjects.delete(configuredProjectPath); }); + } + } + }; + ProjectService.prototype.telemetryOnOpenFile = function (scriptInfo) { + if (this.syntaxOnly || !this.eventHandler || !scriptInfo.isJavaScript() || !ts.addToSeen(this.allJsFilesForOpenFileTelemetry, scriptInfo.path)) { + return; + } + var info = { checkJs: !!scriptInfo.getDefaultProject().getSourceFile(scriptInfo.path).checkJsDirective }; + this.eventHandler({ eventName: server.OpenFileInfoTelemetryEvent, data: { info: info } }); + }; + ProjectService.prototype.closeClientFile = function (uncheckedFileName) { + var info = this.getScriptInfoForNormalizedPath(server.toNormalizedPath(uncheckedFileName)); + if (info) { + this.closeOpenFile(info); + } + this.printProjects(); + }; + ProjectService.prototype.collectChanges = function (lastKnownProjectVersions, currentProjects, result) { + var _loop_4 = function (proj) { + var knownProject = ts.find(lastKnownProjectVersions, function (p) { return p.projectName === proj.getProjectName(); }); + result.push(proj.getChangesSinceVersion(knownProject && knownProject.version)); + }; + for (var _i = 0, currentProjects_1 = currentProjects; _i < currentProjects_1.length; _i++) { + var proj = currentProjects_1[_i]; + _loop_4(proj); + } + }; + ProjectService.prototype.synchronizeProjectList = function (knownProjects) { + var files = []; + this.collectChanges(knownProjects, this.externalProjects, files); + this.collectChanges(knownProjects, ts.arrayFrom(this.configuredProjects.values()), files); + this.collectChanges(knownProjects, this.inferredProjects, files); + return files; + }; + ProjectService.prototype.applyChangesInOpenFiles = function (openFiles, changedFiles, closedFiles) { + if (openFiles) { + for (var _i = 0, openFiles_1 = openFiles; _i < openFiles_1.length; _i++) { + var file = openFiles_1[_i]; + var scriptInfo = this.getScriptInfo(file.fileName); + ts.Debug.assert(!scriptInfo || !scriptInfo.isScriptOpen(), "Script should not exist and not be open already"); + var normalizedPath = scriptInfo ? scriptInfo.fileName : server.toNormalizedPath(file.fileName); + this.openClientFileWithNormalizedPath(normalizedPath, file.content, tryConvertScriptKindName(file.scriptKind), file.hasMixedContent); + } + } + if (changedFiles) { + for (var _a = 0, changedFiles_2 = changedFiles; _a < changedFiles_2.length; _a++) { + var file = changedFiles_2[_a]; + var scriptInfo = this.getScriptInfo(file.fileName); + ts.Debug.assert(!!scriptInfo); + this.applyChangesToFile(scriptInfo, file.changes); + } + } + if (closedFiles) { + for (var _b = 0, closedFiles_1 = closedFiles; _b < closedFiles_1.length; _b++) { + var file = closedFiles_1[_b]; + this.closeClientFile(file); + } + } + }; + ProjectService.prototype.applyChangesToFile = function (scriptInfo, changes) { + for (var i = changes.length - 1; i >= 0; i--) { + var change = changes[i]; + scriptInfo.editContent(change.span.start, change.span.start + change.span.length, change.newText); + } + }; + ProjectService.prototype.closeConfiguredProjectReferencedFromExternalProject = function (configFile) { + var configuredProject = this.findConfiguredProjectByProjectName(configFile); + if (configuredProject) { + configuredProject.deleteExternalProjectReference(); + if (!configuredProject.hasOpenRef()) { + this.removeProject(configuredProject); + return; + } + } + }; + ProjectService.prototype.closeExternalProject = function (uncheckedFileName) { + var fileName = server.toNormalizedPath(uncheckedFileName); + var configFiles = this.externalProjectToConfiguredProjectMap.get(fileName); + if (configFiles) { + for (var _i = 0, configFiles_1 = configFiles; _i < configFiles_1.length; _i++) { + var configFile = configFiles_1[_i]; + this.closeConfiguredProjectReferencedFromExternalProject(configFile); + } + this.externalProjectToConfiguredProjectMap.delete(fileName); + } + else { + var externalProject = this.findExternalProjectByProjectName(uncheckedFileName); + if (externalProject) { + this.removeProject(externalProject); + } + } + }; + ProjectService.prototype.openExternalProjects = function (projects) { + var _this = this; + var projectsToClose = ts.arrayToMap(this.externalProjects, function (p) { return p.getProjectName(); }, function (_) { return true; }); + ts.forEachKey(this.externalProjectToConfiguredProjectMap, function (externalProjectName) { + projectsToClose.set(externalProjectName, true); + }); + for (var _i = 0, projects_3 = projects; _i < projects_3.length; _i++) { + var externalProject = projects_3[_i]; + this.openExternalProject(externalProject); + projectsToClose.delete(externalProject.projectFileName); + } + ts.forEachKey(projectsToClose, function (externalProjectName) { + _this.closeExternalProject(externalProjectName); + }); + }; + ProjectService.escapeFilenameForRegex = function (filename) { + return filename.replace(this.filenameEscapeRegexp, "\\$&"); + }; + ProjectService.prototype.resetSafeList = function () { + this.safelist = defaultTypeSafeList; + }; + ProjectService.prototype.applySafeList = function (proj) { + var _this = this; + var rootFiles = proj.rootFiles; + var typeAcquisition = proj.typeAcquisition; + ts.Debug.assert(!!typeAcquisition, "proj.typeAcquisition should be set by now"); + if (typeAcquisition.enable === false) { + return []; + } + var typeAcqInclude = typeAcquisition.include || (typeAcquisition.include = []); + var excludeRules = []; + var normalizedNames = rootFiles.map(function (f) { return ts.normalizeSlashes(f.fileName); }); + var excludedFiles = []; + var _loop_5 = function (name) { + var rule = this_2.safelist[name]; + for (var _i = 0, normalizedNames_1 = normalizedNames; _i < normalizedNames_1.length; _i++) { + var root = normalizedNames_1[_i]; + if (rule.match.test(root)) { + this_2.logger.info("Excluding files based on rule " + name + " matching file '" + root + "'"); + if (rule.types) { + for (var _a = 0, _b = rule.types; _a < _b.length; _a++) { + var type = _b[_a]; + if (typeAcqInclude.indexOf(type) < 0) { + typeAcqInclude.push(type); + } + } + } + if (rule.exclude) { + var _loop_7 = function (exclude) { + var processedRule = root.replace(rule.match, function () { + var groups = []; + for (var _i = 0; _i < arguments.length; _i++) { + groups[_i] = arguments[_i]; + } + return exclude.map(function (groupNumberOrString) { + if (typeof groupNumberOrString === "number") { + if (!ts.isString(groups[groupNumberOrString])) { + _this.logger.info("Incorrect RegExp specification in safelist rule " + name + " - not enough groups"); + return "\\*"; + } + return ProjectService.escapeFilenameForRegex(groups[groupNumberOrString]); + } + return groupNumberOrString; + }).join(""); + }); + if (excludeRules.indexOf(processedRule) === -1) { + excludeRules.push(processedRule); + } + }; + for (var _c = 0, _d = rule.exclude; _c < _d.length; _c++) { + var exclude = _d[_c]; + _loop_7(exclude); + } + } + else { + var escaped = ProjectService.escapeFilenameForRegex(root); + if (excludeRules.indexOf(escaped) < 0) { + excludeRules.push(escaped); + } + } + } + } + }; + var this_2 = this; + for (var _i = 0, _a = Object.keys(this.safelist); _i < _a.length; _i++) { + var name = _a[_i]; + _loop_5(name); + } + var excludeRegexes = excludeRules.map(function (e) { return new RegExp(e, "i"); }); + var filesToKeep = []; + var _loop_6 = function (i) { + if (excludeRegexes.some(function (re) { return re.test(normalizedNames[i]); })) { + excludedFiles.push(normalizedNames[i]); + } + else { + var exclude = false; + if (typeAcquisition.enable || typeAcquisition.enableAutoDiscovery) { + var baseName = ts.getBaseFileName(normalizedNames[i].toLowerCase()); + if (ts.fileExtensionIs(baseName, "js")) { + var inferredTypingName = ts.removeFileExtension(baseName); + var cleanedTypingName = ts.removeMinAndVersionNumbers(inferredTypingName); + var typeName = this_3.legacySafelist.get(cleanedTypingName); + if (typeName !== undefined) { + this_3.logger.info("Excluded '" + normalizedNames[i] + "' because it matched " + cleanedTypingName + " from the legacy safelist"); + excludedFiles.push(normalizedNames[i]); + exclude = true; + if (typeAcqInclude.indexOf(typeName) < 0) { + typeAcqInclude.push(typeName); + } + } + } + } + if (!exclude) { + if (/^.+[\.-]min\.js$/.test(normalizedNames[i])) { + excludedFiles.push(normalizedNames[i]); + } + else { + filesToKeep.push(proj.rootFiles[i]); + } + } + } + }; + var this_3 = this; + for (var i = 0; i < proj.rootFiles.length; i++) { + _loop_6(i); + } + proj.rootFiles = filesToKeep; + return excludedFiles; + }; + ProjectService.prototype.openExternalProject = function (proj) { + if (proj.typingOptions && !proj.typeAcquisition) { + var typeAcquisition = ts.convertEnableAutoDiscoveryToEnable(proj.typingOptions); + proj.typeAcquisition = typeAcquisition; + } + proj.typeAcquisition = proj.typeAcquisition || {}; + proj.typeAcquisition.include = proj.typeAcquisition.include || []; + proj.typeAcquisition.exclude = proj.typeAcquisition.exclude || []; + if (proj.typeAcquisition.enable === undefined) { + proj.typeAcquisition.enable = server.hasNoTypeScriptSource(proj.rootFiles.map(function (f) { return f.fileName; })); + } + var excludedFiles = this.applySafeList(proj); + var tsConfigFiles; + var rootFiles = []; + for (var _i = 0, _a = proj.rootFiles; _i < _a.length; _i++) { + var file = _a[_i]; + var normalized = server.toNormalizedPath(file.fileName); + if (server.getBaseConfigFileName(normalized)) { + if (!this.syntaxOnly && this.host.fileExists(normalized)) { + (tsConfigFiles || (tsConfigFiles = [])).push(normalized); + } + } + else { + rootFiles.push(file); + } + } + if (tsConfigFiles) { + tsConfigFiles.sort(); + } + var externalProject = this.findExternalProjectByProjectName(proj.projectFileName); + var exisingConfigFiles; + if (externalProject) { + externalProject.excludedFiles = excludedFiles; + if (!tsConfigFiles) { + var compilerOptions = convertCompilerOptions(proj.options); + var lastFileExceededProgramSize = this.getFilenameForExceededTotalSizeLimitForNonTsFiles(proj.projectFileName, compilerOptions, proj.rootFiles, externalFilePropertyReader); + if (lastFileExceededProgramSize) { + externalProject.disableLanguageService(lastFileExceededProgramSize); + } + else { + externalProject.enableLanguageService(); + } + this.updateRootAndOptionsOfNonInferredProject(externalProject, proj.rootFiles, externalFilePropertyReader, compilerOptions, proj.typeAcquisition, proj.options.compileOnSave); + externalProject.updateGraph(); + return; + } + this.closeExternalProject(proj.projectFileName); + } + else if (this.externalProjectToConfiguredProjectMap.get(proj.projectFileName)) { + if (!tsConfigFiles) { + this.closeExternalProject(proj.projectFileName); + } + else { + var oldConfigFiles = this.externalProjectToConfiguredProjectMap.get(proj.projectFileName); + var iNew = 0; + var iOld = 0; + while (iNew < tsConfigFiles.length && iOld < oldConfigFiles.length) { + var newConfig = tsConfigFiles[iNew]; + var oldConfig = oldConfigFiles[iOld]; + if (oldConfig < newConfig) { + this.closeConfiguredProjectReferencedFromExternalProject(oldConfig); + iOld++; + } + else if (oldConfig > newConfig) { + iNew++; + } + else { + (exisingConfigFiles || (exisingConfigFiles = [])).push(oldConfig); + iOld++; + iNew++; + } + } + for (var i = iOld; i < oldConfigFiles.length; i++) { + this.closeConfiguredProjectReferencedFromExternalProject(oldConfigFiles[i]); + } + } + } + if (tsConfigFiles) { + this.externalProjectToConfiguredProjectMap.set(proj.projectFileName, tsConfigFiles); + for (var _b = 0, tsConfigFiles_1 = tsConfigFiles; _b < tsConfigFiles_1.length; _b++) { + var tsconfigFile = tsConfigFiles_1[_b]; + var project = this.findConfiguredProjectByProjectName(tsconfigFile); + if (!project) { + project = this.getHostPreferences().lazyConfiguredProjectsFromExternalProject ? + this.createConfiguredProjectWithDelayLoad(tsconfigFile, "Creating configured project in external project: " + proj.projectFileName) : + this.createLoadAndUpdateConfiguredProject(tsconfigFile, "Creating configured project in external project: " + proj.projectFileName); + } + if (project && !ts.contains(exisingConfigFiles, tsconfigFile)) { + project.addExternalProjectReference(); + } + } + } + else { + this.externalProjectToConfiguredProjectMap.delete(proj.projectFileName); + var project = this.createExternalProject(proj.projectFileName, rootFiles, proj.options, proj.typeAcquisition, excludedFiles); + project.updateGraph(); + } + }; + ProjectService.prototype.hasDeferredExtension = function () { + for (var _i = 0, _a = this.hostConfiguration.extraFileExtensions; _i < _a.length; _i++) { + var extension = _a[_i]; + if (extension.scriptKind === 7) { + return true; + } + } + return false; + }; + ProjectService.prototype.configurePlugin = function (args) { + this.forEachEnabledProject(function (project) { return project.onPluginConfigurationChanged(args.pluginName, args.configuration); }); + this.currentPluginConfigOverrides = this.currentPluginConfigOverrides || ts.createMap(); + this.currentPluginConfigOverrides.set(args.pluginName, args.configuration); + }; + ProjectService.filenameEscapeRegexp = /[-\/\\^$*+?.()|[\]{}]/g; + return ProjectService; + }()); + server.ProjectService = ProjectService; + function isConfigFile(config) { + return config.kind !== undefined; + } + server.isConfigFile = isConfigFile; + function printProjectsWithCounter(projects, counter) { + for (var _i = 0, projects_4 = projects; _i < projects_4.length; _i++) { + var project = projects_4[_i]; + project.print(counter); + counter++; + } + return counter; + } + })(server = ts.server || (ts.server = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + var server; + (function (server) { + server.nullCancellationToken = { + isCancellationRequested: function () { return false; }, + setRequest: function () { return void 0; }, + resetRequest: function () { return void 0; } + }; + function hrTimeToMilliseconds(time) { + var seconds = time[0]; + var nanoseconds = time[1]; + return ((1e9 * seconds) + nanoseconds) / 1000000.0; + } + function isDeclarationFileInJSOnlyNonConfiguredProject(project, file) { + if ((project.projectKind === server.ProjectKind.Inferred || project.projectKind === server.ProjectKind.External) && + project.isJsOnlyProject()) { + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + return scriptInfo && !scriptInfo.isJavaScript(); + } + return false; + } + function formatDiag(fileName, project, diag) { + var scriptInfo = project.getScriptInfoForNormalizedPath(fileName); + return { + start: scriptInfo.positionToLineOffset(diag.start), + end: scriptInfo.positionToLineOffset(diag.start + diag.length), + text: ts.flattenDiagnosticMessageText(diag.messageText, "\n"), + code: diag.code, + category: ts.diagnosticCategoryName(diag), + reportsUnnecessary: diag.reportsUnnecessary, + source: diag.source, + relatedInformation: ts.map(diag.relatedInformation, formatRelatedInformation), + }; + } + function formatRelatedInformation(info) { + if (!info.file) { + return { + message: ts.flattenDiagnosticMessageText(info.messageText, "\n"), + category: ts.diagnosticCategoryName(info), + code: info.code + }; + } + return { + span: { + start: convertToLocation(ts.getLineAndCharacterOfPosition(info.file, info.start)), + end: convertToLocation(ts.getLineAndCharacterOfPosition(info.file, info.start + info.length)), + file: info.file.fileName + }, + message: ts.flattenDiagnosticMessageText(info.messageText, "\n"), + category: ts.diagnosticCategoryName(info), + code: info.code + }; + } + function convertToLocation(lineAndCharacter) { + return { line: lineAndCharacter.line + 1, offset: lineAndCharacter.character + 1 }; + } + function formatConfigFileDiag(diag, includeFileName) { + var start = (diag.file && convertToLocation(ts.getLineAndCharacterOfPosition(diag.file, diag.start))); + var end = (diag.file && convertToLocation(ts.getLineAndCharacterOfPosition(diag.file, diag.start + diag.length))); + var text = ts.flattenDiagnosticMessageText(diag.messageText, "\n"); + var code = diag.code, source = diag.source; + var category = ts.diagnosticCategoryName(diag); + var common = { + start: start, + end: end, + text: text, + code: code, + category: category, + reportsUnnecessary: diag.reportsUnnecessary, + source: source, + relatedInformation: ts.map(diag.relatedInformation, formatRelatedInformation), + }; + return includeFileName + ? __assign({}, common, { fileName: diag.file && diag.file.fileName }) : common; + } + function allEditsBeforePos(edits, pos) { + return edits.every(function (edit) { return ts.textSpanEnd(edit.span) < pos; }); + } + server.CommandNames = server.protocol.CommandTypes; + function formatMessage(msg, logger, byteLength, newLine) { + var verboseLogging = logger.hasLevel(server.LogLevel.verbose); + var json = JSON.stringify(msg); + if (verboseLogging) { + logger.info(msg.type + ":" + server.indent(json)); + } + var len = byteLength(json, "utf8"); + return "Content-Length: " + (1 + len) + "\r\n\r\n" + json + newLine; + } + server.formatMessage = formatMessage; + var MultistepOperation = (function () { + function MultistepOperation(operationHost) { + this.operationHost = operationHost; + } + MultistepOperation.prototype.startNew = function (action) { + this.complete(); + this.requestId = this.operationHost.getCurrentRequestId(); + this.executeAction(action); + }; + MultistepOperation.prototype.complete = function () { + if (this.requestId !== undefined) { + this.operationHost.sendRequestCompletedEvent(this.requestId); + this.requestId = undefined; + } + this.setTimerHandle(undefined); + this.setImmediateId(undefined); + }; + MultistepOperation.prototype.immediate = function (action) { + var _this = this; + var requestId = this.requestId; + ts.Debug.assert(requestId === this.operationHost.getCurrentRequestId(), "immediate: incorrect request id"); + this.setImmediateId(this.operationHost.getServerHost().setImmediate(function () { + _this.immediateId = undefined; + _this.operationHost.executeWithRequestId(requestId, function () { return _this.executeAction(action); }); + })); + }; + MultistepOperation.prototype.delay = function (ms, action) { + var _this = this; + var requestId = this.requestId; + ts.Debug.assert(requestId === this.operationHost.getCurrentRequestId(), "delay: incorrect request id"); + this.setTimerHandle(this.operationHost.getServerHost().setTimeout(function () { + _this.timerHandle = undefined; + _this.operationHost.executeWithRequestId(requestId, function () { return _this.executeAction(action); }); + }, ms)); + }; + MultistepOperation.prototype.executeAction = function (action) { + var stop = false; + try { + if (this.operationHost.isCancellationRequested()) { + stop = true; + } + else { + action(this); + } + } + catch (e) { + stop = true; + if (!(e instanceof ts.OperationCanceledException)) { + this.operationHost.logError(e, "delayed processing of request " + this.requestId); + } + } + if (stop || !this.hasPendingWork()) { + this.complete(); + } + }; + MultistepOperation.prototype.setTimerHandle = function (timerHandle) { + if (this.timerHandle !== undefined) { + this.operationHost.getServerHost().clearTimeout(this.timerHandle); + } + this.timerHandle = timerHandle; + }; + MultistepOperation.prototype.setImmediateId = function (immediateId) { + if (this.immediateId !== undefined) { + this.operationHost.getServerHost().clearImmediate(this.immediateId); + } + this.immediateId = immediateId; + }; + MultistepOperation.prototype.hasPendingWork = function () { + return !!this.timerHandle || !!this.immediateId; + }; + return MultistepOperation; + }()); + function toEvent(eventName, body) { + return { + seq: 0, + type: "event", + event: eventName, + body: body + }; + } + server.toEvent = toEvent; + function combineProjectOutput(defaultValue, getValue, projects, action) { + var outputs = ts.flatMapToMutable(ts.isArray(projects) ? projects : projects.projects, function (project) { return action(project, defaultValue); }); + if (!ts.isArray(projects) && projects.symLinkedProjects) { + projects.symLinkedProjects.forEach(function (projects, path) { + var value = getValue(path); + outputs.push.apply(outputs, ts.flatMap(projects, function (project) { return action(project, value); })); + }); + } + return ts.deduplicate(outputs, ts.equateValues); + } + function combineProjectOutputFromEveryProject(projectService, action, areEqual) { + var outputs = []; + projectService.forEachEnabledProject(function (project) { + var theseOutputs = action(project); + outputs.push.apply(outputs, theseOutputs.filter(function (output) { return !outputs.some(function (o) { return areEqual(o, output); }); })); + }); + return outputs; + } + function combineProjectOutputWhileOpeningReferencedProjects(projects, defaultProject, action, getLocation, resultsEqual) { + var outputs = []; + combineProjectOutputWorker(projects, defaultProject, undefined, function (_a, tryAddToTodo) { + var project = _a.project; + for (var _i = 0, _b = action(project); _i < _b.length; _i++) { + var output = _b[_i]; + if (!ts.contains(outputs, output, resultsEqual) && !tryAddToTodo(project, getLocation(output))) { + outputs.push(output); + } + } + }, undefined); + return outputs; + } + function combineProjectOutputForRenameLocations(projects, defaultProject, initialLocation, findInStrings, findInComments) { + var outputs = []; + combineProjectOutputWorker(projects, defaultProject, initialLocation, function (_a, tryAddToTodo) { + var project = _a.project, location = _a.location; + for (var _i = 0, _b = project.getLanguageService().findRenameLocations(location.fileName, location.pos, findInStrings, findInComments) || server.emptyArray; _i < _b.length; _i++) { + var output = _b[_i]; + if (!ts.contains(outputs, output, ts.documentSpansEqual) && !tryAddToTodo(project, documentSpanLocation(output))) { + outputs.push(output); + } + } + }, function () { return getDefinitionLocation(defaultProject, initialLocation); }); + return outputs; + } + function getDefinitionLocation(defaultProject, initialLocation) { + var infos = defaultProject.getLanguageService().getDefinitionAtPosition(initialLocation.fileName, initialLocation.pos); + var info = infos && ts.firstOrUndefined(infos); + return info && { fileName: info.fileName, pos: info.textSpan.start }; + } + function combineProjectOutputForReferences(projects, defaultProject, initialLocation) { + var outputs = []; + combineProjectOutputWorker(projects, defaultProject, initialLocation, function (_a, getMappedLocation) { + var project = _a.project, location = _a.location; + var _loop_8 = function (outputReferencedSymbol) { + var mappedDefinitionFile = getMappedLocation(project, documentSpanLocation(outputReferencedSymbol.definition)); + var definition = mappedDefinitionFile === undefined ? outputReferencedSymbol.definition : __assign({}, outputReferencedSymbol.definition, { textSpan: ts.createTextSpan(mappedDefinitionFile.pos, outputReferencedSymbol.definition.textSpan.length), fileName: mappedDefinitionFile.fileName }); + var symbolToAddTo = ts.find(outputs, function (o) { return ts.documentSpansEqual(o.definition, definition); }); + if (!symbolToAddTo) { + symbolToAddTo = { definition: definition, references: [] }; + outputs.push(symbolToAddTo); + } + for (var _i = 0, _a = outputReferencedSymbol.references; _i < _a.length; _i++) { + var ref = _a[_i]; + if (!ts.contains(symbolToAddTo.references, ref, ts.documentSpansEqual) && !getMappedLocation(project, documentSpanLocation(ref))) { + symbolToAddTo.references.push(ref); + } + } + }; + for (var _i = 0, _b = project.getLanguageService().findReferences(location.fileName, location.pos) || server.emptyArray; _i < _b.length; _i++) { + var outputReferencedSymbol = _b[_i]; + _loop_8(outputReferencedSymbol); + } + }, function () { return getDefinitionLocation(defaultProject, initialLocation); }); + return outputs.filter(function (o) { return o.references.length !== 0; }); + } + function forEachProjectInProjects(projects, path, cb) { + for (var _i = 0, _a = ts.isArray(projects) ? projects : projects.projects; _i < _a.length; _i++) { + var project = _a[_i]; + cb(project, path); + } + if (!ts.isArray(projects) && projects.symLinkedProjects) { + projects.symLinkedProjects.forEach(function (symlinkedProjects, symlinkedPath) { + for (var _i = 0, symlinkedProjects_1 = symlinkedProjects; _i < symlinkedProjects_1.length; _i++) { + var project = symlinkedProjects_1[_i]; + cb(project, symlinkedPath); + } + }); + } + } + function combineProjectOutputWorker(projects, defaultProject, initialLocation, cb, getDefinition) { + var projectService = defaultProject.projectService; + var toDo; + var seenProjects = ts.createMap(); + forEachProjectInProjects(projects, initialLocation && initialLocation.fileName, function (project, path) { + var location = (initialLocation ? { fileName: path, pos: initialLocation.pos } : undefined); + toDo = callbackProjectAndLocation({ project: project, location: location }, projectService, toDo, seenProjects, cb); + }); + if (getDefinition) { + var memGetDefinition_1 = ts.memoize(getDefinition); + projectService.forEachEnabledProject(function (project) { + if (!ts.addToSeen(seenProjects, project.projectName)) + return; + var definition = getDefinitionInProject(memGetDefinition_1(), defaultProject, project); + if (definition) { + toDo = callbackProjectAndLocation({ project: project, location: definition }, projectService, toDo, seenProjects, cb); + } + }); + } + while (toDo && toDo.length) { + toDo = callbackProjectAndLocation(ts.Debug.assertDefined(toDo.pop()), projectService, toDo, seenProjects, cb); + } + } + function getDefinitionInProject(definition, definingProject, project) { + if (!definition || project.containsFile(server.toNormalizedPath(definition.fileName))) + return definition; + var mappedDefinition = definingProject.getLanguageService().getSourceMapper().tryGetGeneratedPosition(definition); + return mappedDefinition && project.containsFile(server.toNormalizedPath(mappedDefinition.fileName)) ? mappedDefinition : undefined; + } + function callbackProjectAndLocation(projectAndLocation, projectService, toDo, seenProjects, cb) { + if (projectAndLocation.project.getCancellationToken().isCancellationRequested()) + return undefined; + cb(projectAndLocation, function (project, location) { + seenProjects.set(projectAndLocation.project.projectName, true); + var originalLocation = projectService.getOriginalLocationEnsuringConfiguredProject(project, location); + if (!originalLocation) + return undefined; + var originalScriptInfo = projectService.getScriptInfo(originalLocation.fileName); + toDo = toDo || []; + for (var _i = 0, _a = originalScriptInfo.containingProjects; _i < _a.length; _i++) { + var project_1 = _a[_i]; + addToTodo({ project: project_1, location: originalLocation }, toDo, seenProjects); + } + var symlinkedProjectsMap = projectService.getSymlinkedProjects(originalScriptInfo); + if (symlinkedProjectsMap) { + symlinkedProjectsMap.forEach(function (symlinkedProjects) { + for (var _i = 0, symlinkedProjects_2 = symlinkedProjects; _i < symlinkedProjects_2.length; _i++) { + var symlinkedProject = symlinkedProjects_2[_i]; + addToTodo({ project: symlinkedProject, location: originalLocation }, toDo, seenProjects); + } + }); + } + return originalLocation; + }); + return toDo; + } + function addToTodo(projectAndLocation, toDo, seenProjects) { + if (ts.addToSeen(seenProjects, projectAndLocation.project.projectName)) + toDo.push(projectAndLocation); + } + function documentSpanLocation(_a) { + var fileName = _a.fileName, textSpan = _a.textSpan; + return { fileName: fileName, pos: textSpan.start }; + } + function getMappedLocation(location, projectService, project) { + var mapsTo = project.getSourceMapper().tryGetSourcePosition(location); + return mapsTo && projectService.fileExists(server.toNormalizedPath(mapsTo.fileName)) ? mapsTo : undefined; + } + var Session = (function () { + function Session(opts) { + var _a; + var _this = this; + this.changeSeq = 0; + this.handlers = ts.createMapFromTemplate((_a = {}, + _a[server.CommandNames.Status] = function () { + var response = { version: ts.version }; + return _this.requiredResponse(response); + }, + _a[server.CommandNames.OpenExternalProject] = function (request) { + _this.projectService.openExternalProject(request.arguments); + return _this.requiredResponse(true); + }, + _a[server.CommandNames.OpenExternalProjects] = function (request) { + _this.projectService.openExternalProjects(request.arguments.projects); + return _this.requiredResponse(true); + }, + _a[server.CommandNames.CloseExternalProject] = function (request) { + _this.projectService.closeExternalProject(request.arguments.projectFileName); + return _this.requiredResponse(true); + }, + _a[server.CommandNames.SynchronizeProjectList] = function (request) { + var result = _this.projectService.synchronizeProjectList(request.arguments.knownProjects); + if (!result.some(function (p) { return p.projectErrors && p.projectErrors.length !== 0; })) { + return _this.requiredResponse(result); + } + var converted = ts.map(result, function (p) { + if (!p.projectErrors || p.projectErrors.length === 0) { + return p; + } + return { + info: p.info, + changes: p.changes, + files: p.files, + projectErrors: _this.convertToDiagnosticsWithLinePosition(p.projectErrors, undefined) + }; + }); + return _this.requiredResponse(converted); + }, + _a[server.CommandNames.ApplyChangedToOpenFiles] = function (request) { + _this.changeSeq++; + _this.projectService.applyChangesInOpenFiles(request.arguments.openFiles, request.arguments.changedFiles, request.arguments.closedFiles); + return _this.requiredResponse(true); + }, + _a[server.CommandNames.Exit] = function () { + _this.exit(); + return _this.notRequired(); + }, + _a[server.CommandNames.Definition] = function (request) { + return _this.requiredResponse(_this.getDefinition(request.arguments, true)); + }, + _a[server.CommandNames.DefinitionFull] = function (request) { + return _this.requiredResponse(_this.getDefinition(request.arguments, false)); + }, + _a[server.CommandNames.DefinitionAndBoundSpan] = function (request) { + return _this.requiredResponse(_this.getDefinitionAndBoundSpan(request.arguments, true)); + }, + _a[server.CommandNames.DefinitionAndBoundSpanFull] = function (request) { + return _this.requiredResponse(_this.getDefinitionAndBoundSpan(request.arguments, false)); + }, + _a[server.CommandNames.EmitOutput] = function (request) { + return _this.requiredResponse(_this.getEmitOutput(request.arguments)); + }, + _a[server.CommandNames.TypeDefinition] = function (request) { + return _this.requiredResponse(_this.getTypeDefinition(request.arguments)); + }, + _a[server.CommandNames.Implementation] = function (request) { + return _this.requiredResponse(_this.getImplementation(request.arguments, true)); + }, + _a[server.CommandNames.ImplementationFull] = function (request) { + return _this.requiredResponse(_this.getImplementation(request.arguments, false)); + }, + _a[server.CommandNames.References] = function (request) { + return _this.requiredResponse(_this.getReferences(request.arguments, true)); + }, + _a[server.CommandNames.ReferencesFull] = function (request) { + return _this.requiredResponse(_this.getReferences(request.arguments, false)); + }, + _a[server.CommandNames.Rename] = function (request) { + return _this.requiredResponse(_this.getRenameLocations(request.arguments, true)); + }, + _a[server.CommandNames.RenameLocationsFull] = function (request) { + return _this.requiredResponse(_this.getRenameLocations(request.arguments, false)); + }, + _a[server.CommandNames.RenameInfoFull] = function (request) { + return _this.requiredResponse(_this.getRenameInfo(request.arguments)); + }, + _a[server.CommandNames.Open] = function (request) { + _this.openClientFile(server.toNormalizedPath(request.arguments.file), request.arguments.fileContent, server.convertScriptKindName(request.arguments.scriptKindName), request.arguments.projectRootPath ? server.toNormalizedPath(request.arguments.projectRootPath) : undefined); + return _this.notRequired(); + }, + _a[server.CommandNames.Quickinfo] = function (request) { + return _this.requiredResponse(_this.getQuickInfoWorker(request.arguments, true)); + }, + _a[server.CommandNames.QuickinfoFull] = function (request) { + return _this.requiredResponse(_this.getQuickInfoWorker(request.arguments, false)); + }, + _a[server.CommandNames.GetOutliningSpans] = function (request) { + return _this.requiredResponse(_this.getOutliningSpans(request.arguments, true)); + }, + _a[server.CommandNames.GetOutliningSpansFull] = function (request) { + return _this.requiredResponse(_this.getOutliningSpans(request.arguments, false)); + }, + _a[server.CommandNames.TodoComments] = function (request) { + return _this.requiredResponse(_this.getTodoComments(request.arguments)); + }, + _a[server.CommandNames.Indentation] = function (request) { + return _this.requiredResponse(_this.getIndentation(request.arguments)); + }, + _a[server.CommandNames.NameOrDottedNameSpan] = function (request) { + return _this.requiredResponse(_this.getNameOrDottedNameSpan(request.arguments)); + }, + _a[server.CommandNames.BreakpointStatement] = function (request) { + return _this.requiredResponse(_this.getBreakpointStatement(request.arguments)); + }, + _a[server.CommandNames.BraceCompletion] = function (request) { + return _this.requiredResponse(_this.isValidBraceCompletion(request.arguments)); + }, + _a[server.CommandNames.DocCommentTemplate] = function (request) { + return _this.requiredResponse(_this.getDocCommentTemplate(request.arguments)); + }, + _a[server.CommandNames.GetSpanOfEnclosingComment] = function (request) { + return _this.requiredResponse(_this.getSpanOfEnclosingComment(request.arguments)); + }, + _a[server.CommandNames.Format] = function (request) { + return _this.requiredResponse(_this.getFormattingEditsForRange(request.arguments)); + }, + _a[server.CommandNames.Formatonkey] = function (request) { + return _this.requiredResponse(_this.getFormattingEditsAfterKeystroke(request.arguments)); + }, + _a[server.CommandNames.FormatFull] = function (request) { + return _this.requiredResponse(_this.getFormattingEditsForDocumentFull(request.arguments)); + }, + _a[server.CommandNames.FormatonkeyFull] = function (request) { + return _this.requiredResponse(_this.getFormattingEditsAfterKeystrokeFull(request.arguments)); + }, + _a[server.CommandNames.FormatRangeFull] = function (request) { + return _this.requiredResponse(_this.getFormattingEditsForRangeFull(request.arguments)); + }, + _a[server.CommandNames.CompletionInfo] = function (request) { + return _this.requiredResponse(_this.getCompletions(request.arguments, server.CommandNames.CompletionInfo)); + }, + _a[server.CommandNames.Completions] = function (request) { + return _this.requiredResponse(_this.getCompletions(request.arguments, server.CommandNames.Completions)); + }, + _a[server.CommandNames.CompletionsFull] = function (request) { + return _this.requiredResponse(_this.getCompletions(request.arguments, server.CommandNames.CompletionsFull)); + }, + _a[server.CommandNames.CompletionDetails] = function (request) { + return _this.requiredResponse(_this.getCompletionEntryDetails(request.arguments, true)); + }, + _a[server.CommandNames.CompletionDetailsFull] = function (request) { + return _this.requiredResponse(_this.getCompletionEntryDetails(request.arguments, false)); + }, + _a[server.CommandNames.CompileOnSaveAffectedFileList] = function (request) { + return _this.requiredResponse(_this.getCompileOnSaveAffectedFileList(request.arguments)); + }, + _a[server.CommandNames.CompileOnSaveEmitFile] = function (request) { + return _this.requiredResponse(_this.emitFile(request.arguments)); + }, + _a[server.CommandNames.SignatureHelp] = function (request) { + return _this.requiredResponse(_this.getSignatureHelpItems(request.arguments, true)); + }, + _a[server.CommandNames.SignatureHelpFull] = function (request) { + return _this.requiredResponse(_this.getSignatureHelpItems(request.arguments, false)); + }, + _a[server.CommandNames.CompilerOptionsDiagnosticsFull] = function (request) { + return _this.requiredResponse(_this.getCompilerOptionsDiagnostics(request.arguments)); + }, + _a[server.CommandNames.EncodedSemanticClassificationsFull] = function (request) { + return _this.requiredResponse(_this.getEncodedSemanticClassifications(request.arguments)); + }, + _a[server.CommandNames.Cleanup] = function () { + _this.cleanup(); + return _this.requiredResponse(true); + }, + _a[server.CommandNames.SemanticDiagnosticsSync] = function (request) { + return _this.requiredResponse(_this.getSemanticDiagnosticsSync(request.arguments)); + }, + _a[server.CommandNames.SyntacticDiagnosticsSync] = function (request) { + return _this.requiredResponse(_this.getSyntacticDiagnosticsSync(request.arguments)); + }, + _a[server.CommandNames.SuggestionDiagnosticsSync] = function (request) { + return _this.requiredResponse(_this.getSuggestionDiagnosticsSync(request.arguments)); + }, + _a[server.CommandNames.Geterr] = function (request) { + _this.errorCheck.startNew(function (next) { return _this.getDiagnostics(next, request.arguments.delay, request.arguments.files); }); + return _this.notRequired(); + }, + _a[server.CommandNames.GeterrForProject] = function (request) { + _this.errorCheck.startNew(function (next) { return _this.getDiagnosticsForProject(next, request.arguments.delay, request.arguments.file); }); + return _this.notRequired(); + }, + _a[server.CommandNames.Change] = function (request) { + _this.change(request.arguments); + return _this.notRequired(); + }, + _a[server.CommandNames.Configure] = function (request) { + _this.projectService.setHostConfiguration(request.arguments); + _this.doOutput(undefined, server.CommandNames.Configure, request.seq, true); + return _this.notRequired(); + }, + _a[server.CommandNames.Reload] = function (request) { + _this.reload(request.arguments, request.seq); + return _this.requiredResponse({ reloadFinished: true }); + }, + _a[server.CommandNames.Saveto] = function (request) { + var savetoArgs = request.arguments; + _this.saveToTmp(savetoArgs.file, savetoArgs.tmpfile); + return _this.notRequired(); + }, + _a[server.CommandNames.Close] = function (request) { + var closeArgs = request.arguments; + _this.closeClientFile(closeArgs.file); + return _this.notRequired(); + }, + _a[server.CommandNames.Navto] = function (request) { + return _this.requiredResponse(_this.getNavigateToItems(request.arguments, true)); + }, + _a[server.CommandNames.NavtoFull] = function (request) { + return _this.requiredResponse(_this.getNavigateToItems(request.arguments, false)); + }, + _a[server.CommandNames.Brace] = function (request) { + return _this.requiredResponse(_this.getBraceMatching(request.arguments, true)); + }, + _a[server.CommandNames.BraceFull] = function (request) { + return _this.requiredResponse(_this.getBraceMatching(request.arguments, false)); + }, + _a[server.CommandNames.NavBar] = function (request) { + return _this.requiredResponse(_this.getNavigationBarItems(request.arguments, true)); + }, + _a[server.CommandNames.NavBarFull] = function (request) { + return _this.requiredResponse(_this.getNavigationBarItems(request.arguments, false)); + }, + _a[server.CommandNames.NavTree] = function (request) { + return _this.requiredResponse(_this.getNavigationTree(request.arguments, true)); + }, + _a[server.CommandNames.NavTreeFull] = function (request) { + return _this.requiredResponse(_this.getNavigationTree(request.arguments, false)); + }, + _a[server.CommandNames.Occurrences] = function (request) { + return _this.requiredResponse(_this.getOccurrences(request.arguments)); + }, + _a[server.CommandNames.DocumentHighlights] = function (request) { + return _this.requiredResponse(_this.getDocumentHighlights(request.arguments, true)); + }, + _a[server.CommandNames.DocumentHighlightsFull] = function (request) { + return _this.requiredResponse(_this.getDocumentHighlights(request.arguments, false)); + }, + _a[server.CommandNames.CompilerOptionsForInferredProjects] = function (request) { + _this.setCompilerOptionsForInferredProjects(request.arguments); + return _this.requiredResponse(true); + }, + _a[server.CommandNames.ProjectInfo] = function (request) { + return _this.requiredResponse(_this.getProjectInfo(request.arguments)); + }, + _a[server.CommandNames.ReloadProjects] = function () { + _this.projectService.reloadProjects(); + return _this.notRequired(); + }, + _a[server.CommandNames.JsxClosingTag] = function (request) { + return _this.requiredResponse(_this.getJsxClosingTag(request.arguments)); + }, + _a[server.CommandNames.GetCodeFixes] = function (request) { + return _this.requiredResponse(_this.getCodeFixes(request.arguments, true)); + }, + _a[server.CommandNames.GetCodeFixesFull] = function (request) { + return _this.requiredResponse(_this.getCodeFixes(request.arguments, false)); + }, + _a[server.CommandNames.GetCombinedCodeFix] = function (request) { + return _this.requiredResponse(_this.getCombinedCodeFix(request.arguments, true)); + }, + _a[server.CommandNames.GetCombinedCodeFixFull] = function (request) { + return _this.requiredResponse(_this.getCombinedCodeFix(request.arguments, false)); + }, + _a[server.CommandNames.ApplyCodeActionCommand] = function (request) { + return _this.requiredResponse(_this.applyCodeActionCommand(request.arguments)); + }, + _a[server.CommandNames.GetSupportedCodeFixes] = function () { + return _this.requiredResponse(_this.getSupportedCodeFixes()); + }, + _a[server.CommandNames.GetApplicableRefactors] = function (request) { + return _this.requiredResponse(_this.getApplicableRefactors(request.arguments)); + }, + _a[server.CommandNames.GetEditsForRefactor] = function (request) { + return _this.requiredResponse(_this.getEditsForRefactor(request.arguments, true)); + }, + _a[server.CommandNames.GetEditsForRefactorFull] = function (request) { + return _this.requiredResponse(_this.getEditsForRefactor(request.arguments, false)); + }, + _a[server.CommandNames.OrganizeImports] = function (request) { + return _this.requiredResponse(_this.organizeImports(request.arguments, true)); + }, + _a[server.CommandNames.OrganizeImportsFull] = function (request) { + return _this.requiredResponse(_this.organizeImports(request.arguments, false)); + }, + _a[server.CommandNames.GetEditsForFileRename] = function (request) { + return _this.requiredResponse(_this.getEditsForFileRename(request.arguments, true)); + }, + _a[server.CommandNames.GetEditsForFileRenameFull] = function (request) { + return _this.requiredResponse(_this.getEditsForFileRename(request.arguments, false)); + }, + _a[server.CommandNames.ConfigurePlugin] = function (request) { + _this.configurePlugin(request.arguments); + return _this.notRequired(); + }, + _a)); + this.host = opts.host; + this.cancellationToken = opts.cancellationToken; + this.typingsInstaller = opts.typingsInstaller; + this.byteLength = opts.byteLength; + this.hrtime = opts.hrtime; + this.logger = opts.logger; + this.canUseEvents = opts.canUseEvents; + this.suppressDiagnosticEvents = opts.suppressDiagnosticEvents; + this.noGetErrOnBackgroundUpdate = opts.noGetErrOnBackgroundUpdate; + var throttleWaitMilliseconds = opts.throttleWaitMilliseconds; + this.eventHandler = this.canUseEvents + ? opts.eventHandler || (function (event) { return _this.defaultEventHandler(event); }) + : undefined; + var multistepOperationHost = { + executeWithRequestId: function (requestId, action) { return _this.executeWithRequestId(requestId, action); }, + getCurrentRequestId: function () { return _this.currentRequestId; }, + getServerHost: function () { return _this.host; }, + logError: function (err, cmd) { return _this.logError(err, cmd); }, + sendRequestCompletedEvent: function (requestId) { return _this.sendRequestCompletedEvent(requestId); }, + isCancellationRequested: function () { return _this.cancellationToken.isCancellationRequested(); } + }; + this.errorCheck = new MultistepOperation(multistepOperationHost); + var settings = { + host: this.host, + logger: this.logger, + cancellationToken: this.cancellationToken, + useSingleInferredProject: opts.useSingleInferredProject, + useInferredProjectPerProjectRoot: opts.useInferredProjectPerProjectRoot, + typingsInstaller: this.typingsInstaller, + throttleWaitMilliseconds: throttleWaitMilliseconds, + eventHandler: this.eventHandler, + suppressDiagnosticEvents: this.suppressDiagnosticEvents, + globalPlugins: opts.globalPlugins, + pluginProbeLocations: opts.pluginProbeLocations, + allowLocalPluginLoads: opts.allowLocalPluginLoads, + typesMapLocation: opts.typesMapLocation, + syntaxOnly: opts.syntaxOnly, + }; + this.projectService = new server.ProjectService(settings); + this.gcTimer = new server.GcTimer(this.host, 7000, this.logger); + } + Session.prototype.sendRequestCompletedEvent = function (requestId) { + this.event({ request_seq: requestId }, "requestCompleted"); + }; + Session.prototype.defaultEventHandler = function (event) { + switch (event.eventName) { + case server.ProjectsUpdatedInBackgroundEvent: + var openFiles = event.data.openFiles; + this.projectsUpdatedInBackgroundEvent(openFiles); + break; + case server.ProjectLoadingStartEvent: + var _a = event.data, project = _a.project, reason = _a.reason; + this.event({ projectName: project.getProjectName(), reason: reason }, server.ProjectLoadingStartEvent); + break; + case server.ProjectLoadingFinishEvent: + var finishProject = event.data.project; + this.event({ projectName: finishProject.getProjectName() }, server.ProjectLoadingFinishEvent); + break; + case server.LargeFileReferencedEvent: + var _b = event.data, file = _b.file, fileSize = _b.fileSize, maxFileSize_1 = _b.maxFileSize; + this.event({ file: file, fileSize: fileSize, maxFileSize: maxFileSize_1 }, server.LargeFileReferencedEvent); + break; + case server.ConfigFileDiagEvent: + var _c = event.data, triggerFile = _c.triggerFile, configFile = _c.configFileName, diagnostics = _c.diagnostics; + var bakedDiags = ts.map(diagnostics, function (diagnostic) { return formatConfigFileDiag(diagnostic, true); }); + this.event({ + triggerFile: triggerFile, + configFile: configFile, + diagnostics: bakedDiags + }, server.ConfigFileDiagEvent); + break; + case server.SurveyReady: + var surveyId = event.data.surveyId; + this.event({ surveyId: surveyId }, server.SurveyReady); + break; + case server.ProjectLanguageServiceStateEvent: { + var eventName = server.ProjectLanguageServiceStateEvent; + this.event({ + projectName: event.data.project.getProjectName(), + languageServiceEnabled: event.data.languageServiceEnabled + }, eventName); + break; + } + case server.ProjectInfoTelemetryEvent: { + var eventName = "telemetry"; + this.event({ + telemetryEventName: event.eventName, + payload: event.data, + }, eventName); + break; + } + } + }; + Session.prototype.projectsUpdatedInBackgroundEvent = function (openFiles) { + var _this = this; + this.projectService.logger.info("got projects updated in background, updating diagnostics for " + openFiles); + if (openFiles.length) { + if (!this.suppressDiagnosticEvents && !this.noGetErrOnBackgroundUpdate) { + var checkList_1 = this.createCheckList(openFiles); + this.errorCheck.startNew(function (next) { return _this.updateErrorCheck(next, checkList_1, 100, true); }); + } + this.event({ + openFiles: openFiles + }, server.ProjectsUpdatedInBackgroundEvent); + } + }; + Session.prototype.logError = function (err, cmd) { + this.logErrorWorker(err, cmd); + }; + Session.prototype.logErrorWorker = function (err, cmd, fileRequest) { + var msg = "Exception on executing command " + cmd; + if (err.message) { + msg += ":\n" + server.indent(err.message); + if (err.stack) { + msg += "\n" + server.indent(err.stack); + } + } + if (fileRequest && this.logger.hasLevel(server.LogLevel.verbose)) { + try { + var _a = this.getFileAndProject(fileRequest), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + if (scriptInfo) { + var text = ts.getSnapshotText(scriptInfo.getSnapshot()); + msg += "\n\nFile text of " + fileRequest.file + ":" + server.indent(text) + "\n"; + } + } + catch (_b) { } + } + this.logger.msg(msg, server.Msg.Err); + }; + Session.prototype.send = function (msg) { + if (msg.type === "event" && !this.canUseEvents) { + if (this.logger.hasLevel(server.LogLevel.verbose)) { + this.logger.info("Session does not support events: ignored event: " + JSON.stringify(msg)); + } + return; + } + this.host.write(formatMessage(msg, this.logger, this.byteLength, this.host.newLine)); + }; + Session.prototype.event = function (body, eventName) { + this.send(toEvent(eventName, body)); + }; + Session.prototype.output = function (info, cmdName, reqSeq, errorMsg) { + this.doOutput(info, cmdName, reqSeq, !errorMsg, errorMsg); + }; + Session.prototype.doOutput = function (info, cmdName, reqSeq, success, message) { + var res = { + seq: 0, + type: "response", + command: cmdName, + request_seq: reqSeq, + success: success, + }; + if (success) { + var metadata = void 0; + if (ts.isArray(info)) { + res.body = info; + metadata = info.metadata; + delete info.metadata; + } + else if (typeof info === "object") { + if (info.metadata) { + var _a = info, infoMetadata = _a.metadata, body = __rest(_a, ["metadata"]); + res.body = body; + metadata = infoMetadata; + } + else { + res.body = info; + } + } + else { + res.body = info; + } + if (metadata) + res.metadata = metadata; + } + else { + ts.Debug.assert(info === undefined); + } + if (message) { + res.message = message; + } + this.send(res); + }; + Session.prototype.semanticCheck = function (file, project) { + var diags = isDeclarationFileInJSOnlyNonConfiguredProject(project, file) + ? server.emptyArray + : project.getLanguageService().getSemanticDiagnostics(file); + this.sendDiagnosticsEvent(file, project, diags, "semanticDiag"); + }; + Session.prototype.syntacticCheck = function (file, project) { + this.sendDiagnosticsEvent(file, project, project.getLanguageService().getSyntacticDiagnostics(file), "syntaxDiag"); + }; + Session.prototype.suggestionCheck = function (file, project) { + this.sendDiagnosticsEvent(file, project, project.getLanguageService().getSuggestionDiagnostics(file), "suggestionDiag"); + }; + Session.prototype.sendDiagnosticsEvent = function (file, project, diagnostics, kind) { + try { + this.event({ file: file, diagnostics: diagnostics.map(function (diag) { return formatDiag(file, project, diag); }) }, kind); + } + catch (err) { + this.logError(err, kind); + } + }; + Session.prototype.updateErrorCheck = function (next, checkList, ms, requireOpen) { + var _this = this; + if (requireOpen === void 0) { requireOpen = true; } + ts.Debug.assert(!this.suppressDiagnosticEvents); + var seq = this.changeSeq; + var followMs = Math.min(ms, 200); + var index = 0; + var checkOne = function () { + if (_this.changeSeq !== seq) { + return; + } + var _a = checkList[index], fileName = _a.fileName, project = _a.project; + index++; + server.updateProjectIfDirty(project); + if (!project.containsFile(fileName, requireOpen)) { + return; + } + _this.syntacticCheck(fileName, project); + if (_this.changeSeq !== seq) { + return; + } + next.immediate(function () { + _this.semanticCheck(fileName, project); + if (_this.changeSeq !== seq) { + return; + } + var goNext = function () { + if (checkList.length > index) { + next.delay(followMs, checkOne); + } + }; + if (_this.getPreferences(fileName).disableSuggestions) { + goNext(); + } + else { + next.immediate(function () { + _this.suggestionCheck(fileName, project); + goNext(); + }); + } + }); + }; + if (checkList.length > index && this.changeSeq === seq) { + next.delay(ms, checkOne); + } + }; + Session.prototype.cleanProjects = function (caption, projects) { + if (!projects) { + return; + } + this.logger.info("cleaning " + caption); + for (var _i = 0, projects_5 = projects; _i < projects_5.length; _i++) { + var p = projects_5[_i]; + p.getLanguageService(false).cleanupSemanticCache(); + } + }; + Session.prototype.cleanup = function () { + this.cleanProjects("inferred projects", this.projectService.inferredProjects); + this.cleanProjects("configured projects", ts.arrayFrom(this.projectService.configuredProjects.values())); + this.cleanProjects("external projects", this.projectService.externalProjects); + if (this.host.gc) { + this.logger.info("host.gc()"); + this.host.gc(); + } + }; + Session.prototype.getEncodedSemanticClassifications = function (args) { + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + return project.getLanguageService().getEncodedSemanticClassifications(file, args); + }; + Session.prototype.getProject = function (projectFileName) { + return projectFileName === undefined ? undefined : this.projectService.findProject(projectFileName); + }; + Session.prototype.getConfigFileAndProject = function (args) { + var project = this.getProject(args.projectFileName); + var file = server.toNormalizedPath(args.file); + return { + configFile: project && project.hasConfigFile(file) ? file : undefined, + project: project + }; + }; + Session.prototype.getConfigFileDiagnostics = function (configFile, project, includeLinePosition) { + var projectErrors = project.getAllProjectErrors(); + var optionsErrors = project.getLanguageService().getCompilerOptionsDiagnostics(); + var diagnosticsForConfigFile = ts.filter(ts.concatenate(projectErrors, optionsErrors), function (diagnostic) { return !!diagnostic.file && diagnostic.file.fileName === configFile; }); + return includeLinePosition ? + this.convertToDiagnosticsWithLinePositionFromDiagnosticFile(diagnosticsForConfigFile) : + ts.map(diagnosticsForConfigFile, function (diagnostic) { return formatConfigFileDiag(diagnostic, false); }); + }; + Session.prototype.convertToDiagnosticsWithLinePositionFromDiagnosticFile = function (diagnostics) { + var _this = this; + return diagnostics.map(function (d) { return ({ + message: ts.flattenDiagnosticMessageText(d.messageText, _this.host.newLine), + start: d.start, + length: d.length, + category: ts.diagnosticCategoryName(d), + code: d.code, + startLocation: (d.file && convertToLocation(ts.getLineAndCharacterOfPosition(d.file, d.start))), + endLocation: (d.file && convertToLocation(ts.getLineAndCharacterOfPosition(d.file, d.start + d.length))), + relatedInformation: ts.map(d.relatedInformation, formatRelatedInformation) + }); }); + }; + Session.prototype.getCompilerOptionsDiagnostics = function (args) { + var project = this.getProject(args.projectFileName); + return this.convertToDiagnosticsWithLinePosition(ts.filter(project.getLanguageService().getCompilerOptionsDiagnostics(), function (diagnostic) { return !diagnostic.file; }), undefined); + }; + Session.prototype.convertToDiagnosticsWithLinePosition = function (diagnostics, scriptInfo) { + var _this = this; + return diagnostics.map(function (d) { return ({ + message: ts.flattenDiagnosticMessageText(d.messageText, _this.host.newLine), + start: d.start, + length: d.length, + category: ts.diagnosticCategoryName(d), + code: d.code, + source: d.source, + startLocation: scriptInfo && scriptInfo.positionToLineOffset(d.start), + endLocation: scriptInfo && scriptInfo.positionToLineOffset(d.start + d.length), + reportsUnnecessary: d.reportsUnnecessary, + relatedInformation: ts.map(d.relatedInformation, formatRelatedInformation), + }); }); + }; + Session.prototype.getDiagnosticsWorker = function (args, isSemantic, selector, includeLinePosition) { + var _a = this.getFileAndProject(args), project = _a.project, file = _a.file; + if (isSemantic && isDeclarationFileInJSOnlyNonConfiguredProject(project, file)) { + return server.emptyArray; + } + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var diagnostics = selector(project, file); + return includeLinePosition + ? this.convertToDiagnosticsWithLinePosition(diagnostics, scriptInfo) + : diagnostics.map(function (d) { return formatDiag(file, project, d); }); + }; + Session.prototype.getDefinition = function (args, simplifiedResult) { + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + var position = this.getPositionInFile(args, file); + var definitions = this.mapDefinitionInfoLocations(project.getLanguageService().getDefinitionAtPosition(file, position) || server.emptyArray, project); + return simplifiedResult ? this.mapDefinitionInfo(definitions, project) : definitions.map(Session.mapToOriginalLocation); + }; + Session.prototype.mapDefinitionInfoLocations = function (definitions, project) { + var _this = this; + return definitions.map(function (info) { + var newLoc = getMappedLocation(documentSpanLocation(info), _this.projectService, project); + return !newLoc ? info : { + containerKind: info.containerKind, + containerName: info.containerName, + fileName: newLoc.fileName, + kind: info.kind, + name: info.name, + textSpan: { + start: newLoc.pos, + length: info.textSpan.length + }, + originalFileName: info.fileName, + originalTextSpan: info.textSpan, + }; + }); + }; + Session.prototype.getDefinitionAndBoundSpan = function (args, simplifiedResult) { + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + var position = this.getPositionInFile(args, file); + var scriptInfo = ts.Debug.assertDefined(project.getScriptInfo(file)); + var unmappedDefinitionAndBoundSpan = project.getLanguageService().getDefinitionAndBoundSpan(file, position); + if (!unmappedDefinitionAndBoundSpan || !unmappedDefinitionAndBoundSpan.definitions) { + return { + definitions: server.emptyArray, + textSpan: undefined + }; + } + var definitions = this.mapDefinitionInfoLocations(unmappedDefinitionAndBoundSpan.definitions, project); + var textSpan = unmappedDefinitionAndBoundSpan.textSpan; + if (simplifiedResult) { + return { + definitions: this.mapDefinitionInfo(definitions, project), + textSpan: this.toLocationTextSpan(textSpan, scriptInfo) + }; + } + return { + definitions: definitions.map(Session.mapToOriginalLocation), + textSpan: textSpan, + }; + }; + Session.prototype.getEmitOutput = function (args) { + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + return project.getLanguageService().getEmitOutput(file); + }; + Session.prototype.mapDefinitionInfo = function (definitions, project) { + var _this = this; + return definitions.map(function (def) { return _this.toFileSpan(def.fileName, def.textSpan, project); }); + }; + Session.mapToOriginalLocation = function (def) { + if (def.originalFileName) { + ts.Debug.assert(def.originalTextSpan !== undefined, "originalTextSpan should be present if originalFileName is"); + return __assign({}, def, { fileName: def.originalFileName, textSpan: def.originalTextSpan, targetFileName: def.fileName, targetTextSpan: def.textSpan }); + } + return def; + }; + Session.prototype.toFileSpan = function (fileName, textSpan, project) { + var ls = project.getLanguageService(); + var start = ls.toLineColumnOffset(fileName, textSpan.start); + var end = ls.toLineColumnOffset(fileName, ts.textSpanEnd(textSpan)); + return { + file: fileName, + start: { line: start.line + 1, offset: start.character + 1 }, + end: { line: end.line + 1, offset: end.character + 1 } + }; + }; + Session.prototype.getTypeDefinition = function (args) { + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + var position = this.getPositionInFile(args, file); + var definitions = this.mapDefinitionInfoLocations(project.getLanguageService().getTypeDefinitionAtPosition(file, position) || server.emptyArray, project); + return this.mapDefinitionInfo(definitions, project); + }; + Session.prototype.mapImplementationLocations = function (implementations, project) { + var _this = this; + return implementations.map(function (info) { + var newLoc = getMappedLocation(documentSpanLocation(info), _this.projectService, project); + return !newLoc ? info : { + fileName: newLoc.fileName, + kind: info.kind, + displayParts: info.displayParts, + textSpan: { + start: newLoc.pos, + length: info.textSpan.length + }, + originalFileName: info.fileName, + originalTextSpan: info.textSpan, + }; + }); + }; + Session.prototype.getImplementation = function (args, simplifiedResult) { + var _this = this; + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + var position = this.getPositionInFile(args, file); + var implementations = this.mapImplementationLocations(project.getLanguageService().getImplementationAtPosition(file, position) || server.emptyArray, project); + if (simplifiedResult) { + return implementations.map(function (_a) { + var fileName = _a.fileName, textSpan = _a.textSpan; + return _this.toFileSpan(fileName, textSpan, project); + }); + } + return implementations.map(Session.mapToOriginalLocation); + }; + Session.prototype.getOccurrences = function (args) { + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + var position = this.getPositionInFile(args, file); + var occurrences = project.getLanguageService().getOccurrencesAtPosition(file, position); + if (!occurrences) { + return server.emptyArray; + } + return occurrences.map(function (occurrence) { + var fileName = occurrence.fileName, isWriteAccess = occurrence.isWriteAccess, textSpan = occurrence.textSpan, isInString = occurrence.isInString; + var scriptInfo = project.getScriptInfo(fileName); + var result = { + start: scriptInfo.positionToLineOffset(textSpan.start), + end: scriptInfo.positionToLineOffset(ts.textSpanEnd(textSpan)), + file: fileName, + isWriteAccess: isWriteAccess, + }; + if (isInString) { + result.isInString = isInString; + } + return result; + }); + }; + Session.prototype.getSyntacticDiagnosticsSync = function (args) { + var configFile = this.getConfigFileAndProject(args).configFile; + if (configFile) { + return server.emptyArray; + } + return this.getDiagnosticsWorker(args, false, function (project, file) { return project.getLanguageService().getSyntacticDiagnostics(file); }, !!args.includeLinePosition); + }; + Session.prototype.getSemanticDiagnosticsSync = function (args) { + var _a = this.getConfigFileAndProject(args), configFile = _a.configFile, project = _a.project; + if (configFile) { + return this.getConfigFileDiagnostics(configFile, project, !!args.includeLinePosition); + } + return this.getDiagnosticsWorker(args, true, function (project, file) { return project.getLanguageService().getSemanticDiagnostics(file); }, !!args.includeLinePosition); + }; + Session.prototype.getSuggestionDiagnosticsSync = function (args) { + var configFile = this.getConfigFileAndProject(args).configFile; + if (configFile) { + return server.emptyArray; + } + return this.getDiagnosticsWorker(args, true, function (project, file) { return project.getLanguageService().getSuggestionDiagnostics(file); }, !!args.includeLinePosition); + }; + Session.prototype.getJsxClosingTag = function (args) { + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + var position = this.getPositionInFile(args, file); + var tag = project.getLanguageService().getJsxClosingTagAtPosition(file, position); + return tag === undefined ? undefined : { newText: tag.newText, caretOffset: 0 }; + }; + Session.prototype.getDocumentHighlights = function (args, simplifiedResult) { + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + var position = this.getPositionInFile(args, file); + var documentHighlights = project.getLanguageService().getDocumentHighlights(file, position, args.filesToSearch); + if (!documentHighlights) { + return server.emptyArray; + } + if (simplifiedResult) { + return documentHighlights.map(convertToDocumentHighlightsItem); + } + else { + return documentHighlights; + } + function convertToDocumentHighlightsItem(documentHighlights) { + var fileName = documentHighlights.fileName, highlightSpans = documentHighlights.highlightSpans; + var scriptInfo = project.getScriptInfo(fileName); + return { + file: fileName, + highlightSpans: highlightSpans.map(convertHighlightSpan) + }; + function convertHighlightSpan(highlightSpan) { + var textSpan = highlightSpan.textSpan, kind = highlightSpan.kind; + var start = scriptInfo.positionToLineOffset(textSpan.start); + var end = scriptInfo.positionToLineOffset(ts.textSpanEnd(textSpan)); + return { start: start, end: end, kind: kind }; + } + } + }; + Session.prototype.setCompilerOptionsForInferredProjects = function (args) { + this.projectService.setCompilerOptionsForInferredProjects(args.options, args.projectRootPath); + }; + Session.prototype.getProjectInfo = function (args) { + return this.getProjectInfoWorker(args.file, args.projectFileName, args.needFileNameList, false); + }; + Session.prototype.getProjectInfoWorker = function (uncheckedFileName, projectFileName, needFileNameList, excludeConfigFiles) { + var project = this.getFileAndProjectWorker(uncheckedFileName, projectFileName).project; + server.updateProjectIfDirty(project); + var projectInfo = { + configFileName: project.getProjectName(), + languageServiceDisabled: !project.languageServiceEnabled, + fileNames: needFileNameList ? project.getFileNames(false, excludeConfigFiles) : undefined + }; + return projectInfo; + }; + Session.prototype.getRenameInfo = function (args) { + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + var position = this.getPositionInFile(args, file); + return project.getLanguageService().getRenameInfo(file, position); + }; + Session.prototype.getProjects = function (args, getScriptInfoEnsuringProjectsUptoDate, ignoreNoProjectError) { + var projects; + var symLinkedProjects; + if (args.projectFileName) { + var project = this.getProject(args.projectFileName); + if (project) { + projects = [project]; + } + } + else { + var scriptInfo = getScriptInfoEnsuringProjectsUptoDate ? + this.projectService.getScriptInfoEnsuringProjectsUptoDate(args.file) : + this.projectService.getScriptInfo(args.file); + if (!scriptInfo) { + if (ignoreNoProjectError) + return server.emptyArray; + this.projectService.logErrorForScriptInfoNotFound(args.file); + return server.Errors.ThrowNoProject(); + } + projects = scriptInfo.containingProjects; + symLinkedProjects = this.projectService.getSymlinkedProjects(scriptInfo); + } + projects = ts.filter(projects, function (p) { return p.languageServiceEnabled && !p.isOrphan(); }); + if (!ignoreNoProjectError && (!projects || !projects.length) && !symLinkedProjects) { + this.projectService.logErrorForScriptInfoNotFound(args.file); + return server.Errors.ThrowNoProject(); + } + return symLinkedProjects ? { projects: projects, symLinkedProjects: symLinkedProjects } : projects; + }; + Session.prototype.getDefaultProject = function (args) { + if (args.projectFileName) { + var project = this.getProject(args.projectFileName); + if (project) { + return project; + } + } + var info = this.projectService.getScriptInfo(args.file); + return info.getDefaultProject(); + }; + Session.prototype.getRenameLocations = function (args, simplifiedResult) { + var file = server.toNormalizedPath(args.file); + var position = this.getPositionInFile(args, file); + var projects = this.getProjects(args); + var locations = combineProjectOutputForRenameLocations(projects, this.getDefaultProject(args), { fileName: args.file, pos: position }, !!args.findInStrings, !!args.findInComments); + if (!simplifiedResult) + return locations; + var defaultProject = this.getDefaultProject(args); + var renameInfo = this.mapRenameInfo(defaultProject.getLanguageService().getRenameInfo(file, position), ts.Debug.assertDefined(this.projectService.getScriptInfo(file))); + return { info: renameInfo, locs: this.toSpanGroups(locations) }; + }; + Session.prototype.mapRenameInfo = function (info, scriptInfo) { + if (info.canRename) { + var canRename = info.canRename, fileToRename = info.fileToRename, displayName = info.displayName, fullDisplayName = info.fullDisplayName, kind = info.kind, kindModifiers = info.kindModifiers, triggerSpan = info.triggerSpan; + return ts.identity({ canRename: canRename, fileToRename: fileToRename, displayName: displayName, fullDisplayName: fullDisplayName, kind: kind, kindModifiers: kindModifiers, triggerSpan: this.toLocationTextSpan(triggerSpan, scriptInfo) }); + } + else { + return info; + } + }; + Session.prototype.toSpanGroups = function (locations) { + var map = ts.createMap(); + for (var _i = 0, locations_1 = locations; _i < locations_1.length; _i++) { + var _a = locations_1[_i]; + var fileName = _a.fileName, textSpan = _a.textSpan, _ = _a.originalTextSpan, _1 = _a.originalFileName, prefixSuffixText = __rest(_a, ["fileName", "textSpan", "originalTextSpan", "originalFileName"]); + var group_1 = map.get(fileName); + if (!group_1) + map.set(fileName, group_1 = { file: fileName, locs: [] }); + var scriptInfo = ts.Debug.assertDefined(this.projectService.getScriptInfo(fileName)); + group_1.locs.push(__assign({}, this.toLocationTextSpan(textSpan, scriptInfo), prefixSuffixText)); + } + return ts.arrayFrom(map.values()); + }; + Session.prototype.getReferences = function (args, simplifiedResult) { + var _this = this; + var file = server.toNormalizedPath(args.file); + var projects = this.getProjects(args); + var position = this.getPositionInFile(args, file); + var references = combineProjectOutputForReferences(projects, this.getDefaultProject(args), { fileName: args.file, pos: position }); + if (simplifiedResult) { + var defaultProject = this.getDefaultProject(args); + var scriptInfo = defaultProject.getScriptInfoForNormalizedPath(file); + var nameInfo = defaultProject.getLanguageService().getQuickInfoAtPosition(file, position); + var symbolDisplayString = nameInfo ? ts.displayPartsToString(nameInfo.displayParts) : ""; + var nameSpan = nameInfo && nameInfo.textSpan; + var symbolStartOffset = nameSpan ? scriptInfo.positionToLineOffset(nameSpan.start).offset : 0; + var symbolName_1 = nameSpan ? scriptInfo.getSnapshot().getText(nameSpan.start, ts.textSpanEnd(nameSpan)) : ""; + var refs = ts.flatMap(references, function (referencedSymbol) { + return referencedSymbol.references.map(function (_a) { + var fileName = _a.fileName, textSpan = _a.textSpan, isWriteAccess = _a.isWriteAccess, isDefinition = _a.isDefinition; + var scriptInfo = ts.Debug.assertDefined(_this.projectService.getScriptInfo(fileName)); + var start = scriptInfo.positionToLineOffset(textSpan.start); + var lineSpan = scriptInfo.lineToTextSpan(start.line - 1); + var lineText = scriptInfo.getSnapshot().getText(lineSpan.start, ts.textSpanEnd(lineSpan)).replace(/\r|\n/g, ""); + return __assign({}, toFileSpan(fileName, textSpan, scriptInfo), { lineText: lineText, isWriteAccess: isWriteAccess, isDefinition: isDefinition }); + }); + }); + var result = { refs: refs, symbolName: symbolName_1, symbolStartOffset: symbolStartOffset, symbolDisplayString: symbolDisplayString }; + return result; + } + else { + return references; + } + }; + Session.prototype.openClientFile = function (fileName, fileContent, scriptKind, projectRootPath) { + this.projectService.openClientFileWithNormalizedPath(fileName, fileContent, scriptKind, false, projectRootPath); + }; + Session.prototype.getPosition = function (args, scriptInfo) { + return args.position !== undefined ? args.position : scriptInfo.lineOffsetToPosition(args.line, args.offset); + }; + Session.prototype.getPositionInFile = function (args, file) { + var scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file); + return this.getPosition(args, scriptInfo); + }; + Session.prototype.getFileAndProject = function (args) { + return this.getFileAndProjectWorker(args.file, args.projectFileName); + }; + Session.prototype.getFileAndLanguageServiceForSyntacticOperation = function (args) { + var file = server.toNormalizedPath(args.file); + var project = this.getProject(args.projectFileName) || this.projectService.tryGetDefaultProjectForFile(file); + if (!project) { + return server.Errors.ThrowNoProject(); + } + return { + file: file, + languageService: project.getLanguageService(false) + }; + }; + Session.prototype.getFileAndProjectWorker = function (uncheckedFileName, projectFileName) { + var file = server.toNormalizedPath(uncheckedFileName); + var project = this.getProject(projectFileName) || this.projectService.ensureDefaultProjectForFile(file); + return { file: file, project: project }; + }; + Session.prototype.getOutliningSpans = function (args, simplifiedResult) { + var _this = this; + var _a = this.getFileAndLanguageServiceForSyntacticOperation(args), file = _a.file, languageService = _a.languageService; + var spans = languageService.getOutliningSpans(file); + if (simplifiedResult) { + var scriptInfo_1 = this.projectService.getScriptInfoForNormalizedPath(file); + return spans.map(function (s) { return ({ + textSpan: _this.toLocationTextSpan(s.textSpan, scriptInfo_1), + hintSpan: _this.toLocationTextSpan(s.hintSpan, scriptInfo_1), + bannerText: s.bannerText, + autoCollapse: s.autoCollapse, + kind: s.kind + }); }); + } + else { + return spans; + } + }; + Session.prototype.getTodoComments = function (args) { + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + return project.getLanguageService().getTodoComments(file, args.descriptors); + }; + Session.prototype.getDocCommentTemplate = function (args) { + var _a = this.getFileAndLanguageServiceForSyntacticOperation(args), file = _a.file, languageService = _a.languageService; + var position = this.getPositionInFile(args, file); + return languageService.getDocCommentTemplateAtPosition(file, position); + }; + Session.prototype.getSpanOfEnclosingComment = function (args) { + var _a = this.getFileAndLanguageServiceForSyntacticOperation(args), file = _a.file, languageService = _a.languageService; + var onlyMultiLine = args.onlyMultiLine; + var position = this.getPositionInFile(args, file); + return languageService.getSpanOfEnclosingComment(file, position, onlyMultiLine); + }; + Session.prototype.getIndentation = function (args) { + var _a = this.getFileAndLanguageServiceForSyntacticOperation(args), file = _a.file, languageService = _a.languageService; + var position = this.getPositionInFile(args, file); + var options = args.options ? server.convertFormatOptions(args.options) : this.getFormatOptions(file); + var indentation = languageService.getIndentationAtPosition(file, position, options); + return { position: position, indentation: indentation }; + }; + Session.prototype.getBreakpointStatement = function (args) { + var _a = this.getFileAndLanguageServiceForSyntacticOperation(args), file = _a.file, languageService = _a.languageService; + var position = this.getPositionInFile(args, file); + return languageService.getBreakpointStatementAtPosition(file, position); + }; + Session.prototype.getNameOrDottedNameSpan = function (args) { + var _a = this.getFileAndLanguageServiceForSyntacticOperation(args), file = _a.file, languageService = _a.languageService; + var position = this.getPositionInFile(args, file); + return languageService.getNameOrDottedNameSpan(file, position, position); + }; + Session.prototype.isValidBraceCompletion = function (args) { + var _a = this.getFileAndLanguageServiceForSyntacticOperation(args), file = _a.file, languageService = _a.languageService; + var position = this.getPositionInFile(args, file); + return languageService.isValidBraceCompletionAtPosition(file, position, args.openingBrace.charCodeAt(0)); + }; + Session.prototype.getQuickInfoWorker = function (args, simplifiedResult) { + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + var scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file); + var quickInfo = project.getLanguageService().getQuickInfoAtPosition(file, this.getPosition(args, scriptInfo)); + if (!quickInfo) { + return undefined; + } + if (simplifiedResult) { + var displayString = ts.displayPartsToString(quickInfo.displayParts); + var docString = ts.displayPartsToString(quickInfo.documentation); + return { + kind: quickInfo.kind, + kindModifiers: quickInfo.kindModifiers, + start: scriptInfo.positionToLineOffset(quickInfo.textSpan.start), + end: scriptInfo.positionToLineOffset(ts.textSpanEnd(quickInfo.textSpan)), + displayString: displayString, + documentation: docString, + tags: quickInfo.tags || [] + }; + } + else { + return quickInfo; + } + }; + Session.prototype.getFormattingEditsForRange = function (args) { + var _this = this; + var _a = this.getFileAndLanguageServiceForSyntacticOperation(args), file = _a.file, languageService = _a.languageService; + var scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file); + var startPosition = scriptInfo.lineOffsetToPosition(args.line, args.offset); + var endPosition = scriptInfo.lineOffsetToPosition(args.endLine, args.endOffset); + var edits = languageService.getFormattingEditsForRange(file, startPosition, endPosition, this.getFormatOptions(file)); + if (!edits) { + return undefined; + } + return edits.map(function (edit) { return _this.convertTextChangeToCodeEdit(edit, scriptInfo); }); + }; + Session.prototype.getFormattingEditsForRangeFull = function (args) { + var _a = this.getFileAndLanguageServiceForSyntacticOperation(args), file = _a.file, languageService = _a.languageService; + var options = args.options ? server.convertFormatOptions(args.options) : this.getFormatOptions(file); + return languageService.getFormattingEditsForRange(file, args.position, args.endPosition, options); + }; + Session.prototype.getFormattingEditsForDocumentFull = function (args) { + var _a = this.getFileAndLanguageServiceForSyntacticOperation(args), file = _a.file, languageService = _a.languageService; + var options = args.options ? server.convertFormatOptions(args.options) : this.getFormatOptions(file); + return languageService.getFormattingEditsForDocument(file, options); + }; + Session.prototype.getFormattingEditsAfterKeystrokeFull = function (args) { + var _a = this.getFileAndLanguageServiceForSyntacticOperation(args), file = _a.file, languageService = _a.languageService; + var options = args.options ? server.convertFormatOptions(args.options) : this.getFormatOptions(file); + return languageService.getFormattingEditsAfterKeystroke(file, args.position, args.key, options); + }; + Session.prototype.getFormattingEditsAfterKeystroke = function (args) { + var _a = this.getFileAndLanguageServiceForSyntacticOperation(args), file = _a.file, languageService = _a.languageService; + var scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file); + var position = scriptInfo.lineOffsetToPosition(args.line, args.offset); + var formatOptions = this.getFormatOptions(file); + var edits = languageService.getFormattingEditsAfterKeystroke(file, position, args.key, formatOptions); + if ((args.key === "\n") && ((!edits) || (edits.length === 0) || allEditsBeforePos(edits, position))) { + var _b = scriptInfo.getLineInfo(args.line), lineText = _b.lineText, absolutePosition = _b.absolutePosition; + if (lineText && lineText.search("\\S") < 0) { + var preferredIndent = languageService.getIndentationAtPosition(file, position, formatOptions); + var hasIndent = 0; + var i = void 0, len = void 0; + for (i = 0, len = lineText.length; i < len; i++) { + if (lineText.charAt(i) === " ") { + hasIndent++; + } + else if (lineText.charAt(i) === "\t") { + hasIndent += formatOptions.tabSize; + } + else { + break; + } + } + if (preferredIndent !== hasIndent) { + var firstNoWhiteSpacePosition = absolutePosition + i; + edits.push({ + span: ts.createTextSpanFromBounds(absolutePosition, firstNoWhiteSpacePosition), + newText: ts.formatting.getIndentationString(preferredIndent, formatOptions) + }); + } + } + } + if (!edits) { + return undefined; + } + return edits.map(function (edit) { + return { + start: scriptInfo.positionToLineOffset(edit.span.start), + end: scriptInfo.positionToLineOffset(ts.textSpanEnd(edit.span)), + newText: edit.newText ? edit.newText : "" + }; + }); + }; + Session.prototype.getCompletions = function (args, kind) { + var _this = this; + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + var scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file); + var position = this.getPosition(args, scriptInfo); + var completions = project.getLanguageService().getCompletionsAtPosition(file, position, __assign({}, server.convertUserPreferences(this.getPreferences(file)), { triggerCharacter: args.triggerCharacter, includeExternalModuleExports: args.includeExternalModuleExports, includeInsertTextCompletions: args.includeInsertTextCompletions })); + if (completions === undefined) + return undefined; + if (kind === "completions-full") + return completions; + var prefix = args.prefix || ""; + var entries = ts.mapDefined(completions.entries, function (entry) { + if (completions.isMemberCompletion || ts.startsWith(entry.name.toLowerCase(), prefix.toLowerCase())) { + var name = entry.name, kind_1 = entry.kind, kindModifiers = entry.kindModifiers, sortText = entry.sortText, insertText = entry.insertText, replacementSpan = entry.replacementSpan, hasAction = entry.hasAction, source = entry.source, isRecommended = entry.isRecommended; + var convertedSpan = replacementSpan ? _this.toLocationTextSpan(replacementSpan, scriptInfo) : undefined; + return { name: name, kind: kind_1, kindModifiers: kindModifiers, sortText: sortText, insertText: insertText, replacementSpan: convertedSpan, hasAction: hasAction || undefined, source: source, isRecommended: isRecommended }; + } + }).sort(function (a, b) { return ts.compareStringsCaseSensitiveUI(a.name, b.name); }); + if (kind === "completions") { + if (completions.metadata) + entries.metadata = completions.metadata; + return entries; + } + var res = __assign({}, completions, { entries: entries }); + return res; + }; + Session.prototype.getCompletionEntryDetails = function (args, simplifiedResult) { + var _this = this; + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + var scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file); + var position = this.getPosition(args, scriptInfo); + var formattingOptions = project.projectService.getFormatCodeOptions(file); + var result = ts.mapDefined(args.entryNames, function (entryName) { + var _a = typeof entryName === "string" ? { name: entryName, source: undefined } : entryName, name = _a.name, source = _a.source; + return project.getLanguageService().getCompletionEntryDetails(file, position, name, formattingOptions, source, _this.getPreferences(file)); + }); + return simplifiedResult + ? result.map(function (details) { return (__assign({}, details, { codeActions: ts.map(details.codeActions, function (action) { return _this.mapCodeAction(action); }) })); }) + : result; + }; + Session.prototype.getCompileOnSaveAffectedFileList = function (args) { + var _this = this; + var projects = this.getProjects(args, true, true); + var info = this.projectService.getScriptInfo(args.file); + if (!info) { + return server.emptyArray; + } + return combineProjectOutput(info, function (path) { return _this.projectService.getScriptInfoForPath(path); }, projects, function (project, info) { + var result; + if (project.compileOnSaveEnabled && project.languageServiceEnabled && !project.isOrphan() && !project.getCompilationSettings().noEmit) { + result = { + projectFileName: project.getProjectName(), + fileNames: project.getCompileOnSaveAffectedFileList(info), + projectUsesOutFile: !!project.getCompilationSettings().outFile || !!project.getCompilationSettings().out + }; + } + return result; + }); + }; + Session.prototype.emitFile = function (args) { + var _this = this; + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + if (!project) { + server.Errors.ThrowNoProject(); + } + if (!project.languageServiceEnabled) { + return false; + } + var scriptInfo = project.getScriptInfo(file); + return project.emitFile(scriptInfo, function (path, data, writeByteOrderMark) { return _this.host.writeFile(path, data, writeByteOrderMark); }); + }; + Session.prototype.getSignatureHelpItems = function (args, simplifiedResult) { + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + var scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file); + var position = this.getPosition(args, scriptInfo); + var helpItems = project.getLanguageService().getSignatureHelpItems(file, position, args); + if (!helpItems) { + return undefined; + } + if (simplifiedResult) { + var span = helpItems.applicableSpan; + return { + items: helpItems.items, + applicableSpan: { + start: scriptInfo.positionToLineOffset(span.start), + end: scriptInfo.positionToLineOffset(span.start + span.length) + }, + selectedItemIndex: helpItems.selectedItemIndex, + argumentIndex: helpItems.argumentIndex, + argumentCount: helpItems.argumentCount, + }; + } + else { + return helpItems; + } + }; + Session.prototype.createCheckList = function (fileNames, defaultProject) { + var _this = this; + return ts.mapDefined(fileNames, function (uncheckedFileName) { + var fileName = server.toNormalizedPath(uncheckedFileName); + var project = defaultProject || _this.projectService.tryGetDefaultProjectForFile(fileName); + return project && { fileName: fileName, project: project }; + }); + }; + Session.prototype.getDiagnostics = function (next, delay, fileNames) { + if (this.suppressDiagnosticEvents) { + return; + } + var checkList = this.createCheckList(fileNames); + if (checkList.length > 0) { + this.updateErrorCheck(next, checkList, delay); + } + }; + Session.prototype.change = function (args) { + var scriptInfo = this.projectService.getScriptInfo(args.file); + ts.Debug.assert(!!scriptInfo); + var start = scriptInfo.lineOffsetToPosition(args.line, args.offset); + var end = scriptInfo.lineOffsetToPosition(args.endLine, args.endOffset); + if (start >= 0) { + this.changeSeq++; + this.projectService.applyChangesToFile(scriptInfo, [{ + span: { start: start, length: end - start }, + newText: args.insertString + }]); + } + }; + Session.prototype.reload = function (args, reqSeq) { + var file = server.toNormalizedPath(args.file); + var tempFileName = args.tmpfile === undefined ? undefined : server.toNormalizedPath(args.tmpfile); + var info = this.projectService.getScriptInfoForNormalizedPath(file); + if (info) { + this.changeSeq++; + if (info.reloadFromFile(tempFileName)) { + this.doOutput(undefined, server.CommandNames.Reload, reqSeq, true); + } + } + }; + Session.prototype.saveToTmp = function (fileName, tempFileName) { + var scriptInfo = this.projectService.getScriptInfo(fileName); + if (scriptInfo) { + scriptInfo.saveTo(tempFileName); + } + }; + Session.prototype.closeClientFile = function (fileName) { + if (!fileName) { + return; + } + var file = ts.normalizePath(fileName); + this.projectService.closeClientFile(file); + }; + Session.prototype.mapLocationNavigationBarItems = function (items, scriptInfo) { + var _this = this; + return ts.map(items, function (item) { return ({ + text: item.text, + kind: item.kind, + kindModifiers: item.kindModifiers, + spans: item.spans.map(function (span) { return _this.toLocationTextSpan(span, scriptInfo); }), + childItems: _this.mapLocationNavigationBarItems(item.childItems, scriptInfo), + indent: item.indent + }); }); + }; + Session.prototype.getNavigationBarItems = function (args, simplifiedResult) { + var _a = this.getFileAndLanguageServiceForSyntacticOperation(args), file = _a.file, languageService = _a.languageService; + var items = languageService.getNavigationBarItems(file); + return !items + ? undefined + : simplifiedResult + ? this.mapLocationNavigationBarItems(items, this.projectService.getScriptInfoForNormalizedPath(file)) + : items; + }; + Session.prototype.toLocationNavigationTree = function (tree, scriptInfo) { + var _this = this; + return { + text: tree.text, + kind: tree.kind, + kindModifiers: tree.kindModifiers, + spans: tree.spans.map(function (span) { return _this.toLocationTextSpan(span, scriptInfo); }), + nameSpan: tree.nameSpan && this.toLocationTextSpan(tree.nameSpan, scriptInfo), + childItems: ts.map(tree.childItems, function (item) { return _this.toLocationNavigationTree(item, scriptInfo); }) + }; + }; + Session.prototype.toLocationTextSpan = function (span, scriptInfo) { + return { + start: scriptInfo.positionToLineOffset(span.start), + end: scriptInfo.positionToLineOffset(ts.textSpanEnd(span)) + }; + }; + Session.prototype.getNavigationTree = function (args, simplifiedResult) { + var _a = this.getFileAndLanguageServiceForSyntacticOperation(args), file = _a.file, languageService = _a.languageService; + var tree = languageService.getNavigationTree(file); + return !tree + ? undefined + : simplifiedResult + ? this.toLocationNavigationTree(tree, this.projectService.getScriptInfoForNormalizedPath(file)) + : tree; + }; + Session.prototype.getNavigateToItems = function (args, simplifiedResult) { + var _this = this; + var full = this.getFullNavigateToItems(args); + return !simplifiedResult ? full : full.map(function (navItem) { + var _a = _this.getFileAndProject({ file: navItem.fileName }), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfo(file); + var bakedItem = { + name: navItem.name, + kind: navItem.kind, + isCaseSensitive: navItem.isCaseSensitive, + matchKind: navItem.matchKind, + file: navItem.fileName, + start: scriptInfo.positionToLineOffset(navItem.textSpan.start), + end: scriptInfo.positionToLineOffset(ts.textSpanEnd(navItem.textSpan)) + }; + if (navItem.kindModifiers && (navItem.kindModifiers !== "")) { + bakedItem.kindModifiers = navItem.kindModifiers; + } + if (navItem.containerName && (navItem.containerName.length > 0)) { + bakedItem.containerName = navItem.containerName; + } + if (navItem.containerKind && (navItem.containerKind.length > 0)) { + bakedItem.containerKind = navItem.containerKind; + } + return bakedItem; + }); + }; + Session.prototype.getFullNavigateToItems = function (args) { + var currentFileOnly = args.currentFileOnly, searchValue = args.searchValue, maxResultCount = args.maxResultCount; + if (currentFileOnly) { + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + return project.getLanguageService().getNavigateToItems(searchValue, maxResultCount, file); + } + else { + return combineProjectOutputWhileOpeningReferencedProjects(this.getProjects(args), this.getDefaultProject(args), function (project) { + return project.getLanguageService().getNavigateToItems(searchValue, maxResultCount, undefined, project.isNonTsProject()); + }, documentSpanLocation, navigateToItemIsEqualTo); + } + function navigateToItemIsEqualTo(a, b) { + if (a === b) { + return true; + } + if (!a || !b) { + return false; + } + return a.containerKind === b.containerKind && + a.containerName === b.containerName && + a.fileName === b.fileName && + a.isCaseSensitive === b.isCaseSensitive && + a.kind === b.kind && + a.kindModifiers === b.containerName && + a.matchKind === b.matchKind && + a.name === b.name && + a.textSpan.start === b.textSpan.start && + a.textSpan.length === b.textSpan.length; + } + }; + Session.prototype.getSupportedCodeFixes = function () { + return ts.getSupportedCodeFixes(); + }; + Session.prototype.isLocation = function (locationOrSpan) { + return locationOrSpan.line !== undefined; + }; + Session.prototype.extractPositionOrRange = function (args, scriptInfo) { + var position; + var textRange; + if (this.isLocation(args)) { + position = getPosition(args); + } + else { + var _a = this.getStartAndEndPosition(args, scriptInfo), startPosition = _a.startPosition, endPosition = _a.endPosition; + textRange = { pos: startPosition, end: endPosition }; + } + return ts.Debug.assertDefined(position === undefined ? textRange : position); + function getPosition(loc) { + return loc.position !== undefined ? loc.position : scriptInfo.lineOffsetToPosition(loc.line, loc.offset); + } + }; + Session.prototype.getApplicableRefactors = function (args) { + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + return project.getLanguageService().getApplicableRefactors(file, this.extractPositionOrRange(args, scriptInfo), this.getPreferences(file)); + }; + Session.prototype.getEditsForRefactor = function (args, simplifiedResult) { + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var result = project.getLanguageService().getEditsForRefactor(file, this.getFormatOptions(file), this.extractPositionOrRange(args, scriptInfo), args.refactor, args.action, this.getPreferences(file)); + if (result === undefined) { + return { + edits: [] + }; + } + if (simplifiedResult) { + var renameFilename = result.renameFilename, renameLocation = result.renameLocation, edits = result.edits; + var mappedRenameLocation = void 0; + if (renameFilename !== undefined && renameLocation !== undefined) { + var renameScriptInfo = project.getScriptInfoForNormalizedPath(server.toNormalizedPath(renameFilename)); + mappedRenameLocation = getLocationInNewDocument(ts.getSnapshotText(renameScriptInfo.getSnapshot()), renameFilename, renameLocation, edits); + } + return { renameLocation: mappedRenameLocation, renameFilename: renameFilename, edits: this.mapTextChangesToCodeEdits(edits) }; + } + else { + return result; + } + }; + Session.prototype.organizeImports = function (_a, simplifiedResult) { + var scope = _a.scope; + ts.Debug.assert(scope.type === "file"); + var _b = this.getFileAndProject(scope.args), file = _b.file, project = _b.project; + var changes = project.getLanguageService().organizeImports({ type: "file", fileName: file }, this.getFormatOptions(file), this.getPreferences(file)); + if (simplifiedResult) { + return this.mapTextChangesToCodeEdits(changes); + } + else { + return changes; + } + }; + Session.prototype.getEditsForFileRename = function (args, simplifiedResult) { + var _this = this; + var oldPath = server.toNormalizedPath(args.oldFilePath); + var newPath = server.toNormalizedPath(args.newFilePath); + var formatOptions = this.getHostFormatOptions(); + var preferences = this.getHostPreferences(); + var changes = combineProjectOutputFromEveryProject(this.projectService, function (project) { return project.getLanguageService().getEditsForFileRename(oldPath, newPath, formatOptions, preferences); }, function (a, b) { return a.fileName === b.fileName; }); + return simplifiedResult ? changes.map(function (c) { return _this.mapTextChangeToCodeEdit(c); }) : changes; + }; + Session.prototype.getCodeFixes = function (args, simplifiedResult) { + var _this = this; + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var _b = this.getStartAndEndPosition(args, scriptInfo), startPosition = _b.startPosition, endPosition = _b.endPosition; + var codeActions = project.getLanguageService().getCodeFixesAtPosition(file, startPosition, endPosition, args.errorCodes, this.getFormatOptions(file), this.getPreferences(file)); + return simplifiedResult ? codeActions.map(function (codeAction) { return _this.mapCodeFixAction(codeAction); }) : codeActions; + }; + Session.prototype.getCombinedCodeFix = function (_a, simplifiedResult) { + var scope = _a.scope, fixId = _a.fixId; + ts.Debug.assert(scope.type === "file"); + var _b = this.getFileAndProject(scope.args), file = _b.file, project = _b.project; + var res = project.getLanguageService().getCombinedCodeFix({ type: "file", fileName: file }, fixId, this.getFormatOptions(file), this.getPreferences(file)); + if (simplifiedResult) { + return { changes: this.mapTextChangesToCodeEdits(res.changes), commands: res.commands }; + } + else { + return res; + } + }; + Session.prototype.applyCodeActionCommand = function (args) { + var commands = args.command; + for (var _i = 0, _a = ts.toArray(commands); _i < _a.length; _i++) { + var command = _a[_i]; + var _b = this.getFileAndProject(command), file = _b.file, project = _b.project; + project.getLanguageService().applyCodeActionCommand(command, this.getFormatOptions(file)).then(function (_result) { }, function (_error) { }); + } + return {}; + }; + Session.prototype.getStartAndEndPosition = function (args, scriptInfo) { + var startPosition, endPosition; + if (args.startPosition !== undefined) { + startPosition = args.startPosition; + } + else { + startPosition = scriptInfo.lineOffsetToPosition(args.startLine, args.startOffset); + args.startPosition = startPosition; + } + if (args.endPosition !== undefined) { + endPosition = args.endPosition; + } + else { + endPosition = scriptInfo.lineOffsetToPosition(args.endLine, args.endOffset); + args.endPosition = endPosition; + } + return { startPosition: startPosition, endPosition: endPosition }; + }; + Session.prototype.mapCodeAction = function (_a) { + var description = _a.description, changes = _a.changes, commands = _a.commands; + return { description: description, changes: this.mapTextChangesToCodeEdits(changes), commands: commands }; + }; + Session.prototype.mapCodeFixAction = function (_a) { + var fixName = _a.fixName, description = _a.description, changes = _a.changes, commands = _a.commands, fixId = _a.fixId, fixAllDescription = _a.fixAllDescription; + return { fixName: fixName, description: description, changes: this.mapTextChangesToCodeEdits(changes), commands: commands, fixId: fixId, fixAllDescription: fixAllDescription }; + }; + Session.prototype.mapTextChangesToCodeEdits = function (textChanges) { + var _this = this; + return textChanges.map(function (change) { return _this.mapTextChangeToCodeEdit(change); }); + }; + Session.prototype.mapTextChangeToCodeEdit = function (textChanges) { + var scriptInfo = this.projectService.getScriptInfoOrConfig(textChanges.fileName); + if (!!textChanges.isNewFile === !!scriptInfo) { + if (!scriptInfo) { + this.projectService.logErrorForScriptInfoNotFound(textChanges.fileName); + } + ts.Debug.fail("Expected isNewFile for (only) new files. " + JSON.stringify({ isNewFile: !!textChanges.isNewFile, hasScriptInfo: !!scriptInfo })); + } + return scriptInfo + ? { fileName: textChanges.fileName, textChanges: textChanges.textChanges.map(function (textChange) { return convertTextChangeToCodeEdit(textChange, scriptInfo); }) } + : convertNewFileTextChangeToCodeEdit(textChanges); + }; + Session.prototype.convertTextChangeToCodeEdit = function (change, scriptInfo) { + return { + start: scriptInfo.positionToLineOffset(change.span.start), + end: scriptInfo.positionToLineOffset(change.span.start + change.span.length), + newText: change.newText ? change.newText : "" + }; + }; + Session.prototype.getBraceMatching = function (args, simplifiedResult) { + var _this = this; + var _a = this.getFileAndLanguageServiceForSyntacticOperation(args), file = _a.file, languageService = _a.languageService; + var scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file); + var position = this.getPosition(args, scriptInfo); + var spans = languageService.getBraceMatchingAtPosition(file, position); + return !spans + ? undefined + : simplifiedResult + ? spans.map(function (span) { return _this.toLocationTextSpan(span, scriptInfo); }) + : spans; + }; + Session.prototype.getDiagnosticsForProject = function (next, delay, fileName) { + if (this.suppressDiagnosticEvents) { + return; + } + var _a = this.getProjectInfoWorker(fileName, undefined, true, true), fileNames = _a.fileNames, languageServiceDisabled = _a.languageServiceDisabled; + if (languageServiceDisabled) { + return; + } + var fileNamesInProject = fileNames.filter(function (value) { return !ts.stringContains(value, "lib.d.ts"); }); + if (fileNamesInProject.length === 0) { + return; + } + var highPriorityFiles = []; + var mediumPriorityFiles = []; + var lowPriorityFiles = []; + var veryLowPriorityFiles = []; + var normalizedFileName = server.toNormalizedPath(fileName); + var project = this.projectService.ensureDefaultProjectForFile(normalizedFileName); + for (var _i = 0, fileNamesInProject_1 = fileNamesInProject; _i < fileNamesInProject_1.length; _i++) { + var fileNameInProject = fileNamesInProject_1[_i]; + if (this.getCanonicalFileName(fileNameInProject) === this.getCanonicalFileName(fileName)) { + highPriorityFiles.push(fileNameInProject); + } + else { + var info = this.projectService.getScriptInfo(fileNameInProject); + if (!info.isScriptOpen()) { + if (ts.fileExtensionIs(fileNameInProject, ".d.ts")) { + veryLowPriorityFiles.push(fileNameInProject); + } + else { + lowPriorityFiles.push(fileNameInProject); + } + } + else { + mediumPriorityFiles.push(fileNameInProject); + } + } + } + var sortedFiles = highPriorityFiles.concat(mediumPriorityFiles, lowPriorityFiles, veryLowPriorityFiles); + var checkList = sortedFiles.map(function (fileName) { return ({ fileName: fileName, project: project }); }); + this.updateErrorCheck(next, checkList, delay, false); + }; + Session.prototype.configurePlugin = function (args) { + this.projectService.configurePlugin(args); + }; + Session.prototype.getCanonicalFileName = function (fileName) { + var name = this.host.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); + return ts.normalizePath(name); + }; + Session.prototype.exit = function () { }; + Session.prototype.notRequired = function () { + return { responseRequired: false }; + }; + Session.prototype.requiredResponse = function (response) { + return { response: response, responseRequired: true }; + }; + Session.prototype.addProtocolHandler = function (command, handler) { + if (this.handlers.has(command)) { + throw new Error("Protocol handler already exists for command \"" + command + "\""); + } + this.handlers.set(command, handler); + }; + Session.prototype.setCurrentRequest = function (requestId) { + ts.Debug.assert(this.currentRequestId === undefined); + this.currentRequestId = requestId; + this.cancellationToken.setRequest(requestId); + }; + Session.prototype.resetCurrentRequest = function (requestId) { + ts.Debug.assert(this.currentRequestId === requestId); + this.currentRequestId = undefined; + this.cancellationToken.resetRequest(requestId); + }; + Session.prototype.executeWithRequestId = function (requestId, f) { + try { + this.setCurrentRequest(requestId); + return f(); + } + finally { + this.resetCurrentRequest(requestId); + } + }; + Session.prototype.executeCommand = function (request) { + var handler = this.handlers.get(request.command); + if (handler) { + return this.executeWithRequestId(request.seq, function () { return handler(request); }); + } + else { + this.logger.msg("Unrecognized JSON command:" + server.stringifyIndented(request), server.Msg.Err); + this.doOutput(undefined, server.CommandNames.Unknown, request.seq, false, "Unrecognized JSON command: " + request.command); + return { responseRequired: false }; + } + }; + Session.prototype.onMessage = function (message) { + this.gcTimer.scheduleCollect(); + var start; + if (this.logger.hasLevel(server.LogLevel.requestTime)) { + start = this.hrtime(); + if (this.logger.hasLevel(server.LogLevel.verbose)) { + this.logger.info("request:" + server.indent(message)); + } + } + var request; + var relevantFile; + try { + request = JSON.parse(message); + relevantFile = request.arguments && request.arguments.file ? request.arguments : undefined; + var _a = this.executeCommand(request), response = _a.response, responseRequired = _a.responseRequired; + if (this.logger.hasLevel(server.LogLevel.requestTime)) { + var elapsedTime = hrTimeToMilliseconds(this.hrtime(start)).toFixed(4); + if (responseRequired) { + this.logger.perftrc(request.seq + "::" + request.command + ": elapsed time (in milliseconds) " + elapsedTime); + } + else { + this.logger.perftrc(request.seq + "::" + request.command + ": async elapsed time (in milliseconds) " + elapsedTime); + } + } + if (response) { + this.doOutput(response, request.command, request.seq, true); + } + else if (responseRequired) { + this.doOutput(undefined, request.command, request.seq, false, "No content available."); + } + } + catch (err) { + if (err instanceof ts.OperationCanceledException) { + this.doOutput({ canceled: true }, request.command, request.seq, true); + return; + } + this.logErrorWorker(err, message, relevantFile); + this.doOutput(undefined, request ? request.command : server.CommandNames.Unknown, request ? request.seq : 0, false, "Error processing request. " + err.message + "\n" + err.stack); + } + }; + Session.prototype.getFormatOptions = function (file) { + return this.projectService.getFormatCodeOptions(file); + }; + Session.prototype.getPreferences = function (file) { + return this.projectService.getPreferences(file); + }; + Session.prototype.getHostFormatOptions = function () { + return this.projectService.getHostFormatCodeOptions(); + }; + Session.prototype.getHostPreferences = function () { + return this.projectService.getHostPreferences(); + }; + return Session; + }()); + server.Session = Session; + function toFileSpan(fileName, textSpan, scriptInfo) { + return { file: fileName, start: scriptInfo.positionToLineOffset(textSpan.start), end: scriptInfo.positionToLineOffset(ts.textSpanEnd(textSpan)) }; + } + function convertTextChangeToCodeEdit(change, scriptInfo) { + return { start: positionToLineOffset(scriptInfo, change.span.start), end: positionToLineOffset(scriptInfo, ts.textSpanEnd(change.span)), newText: change.newText }; + } + function positionToLineOffset(info, position) { + return server.isConfigFile(info) ? locationFromLineAndCharacter(info.getLineAndCharacterOfPosition(position)) : info.positionToLineOffset(position); + } + function locationFromLineAndCharacter(lc) { + return { line: lc.line + 1, offset: lc.character + 1 }; + } + function convertNewFileTextChangeToCodeEdit(textChanges) { + ts.Debug.assert(textChanges.textChanges.length === 1); + var change = ts.first(textChanges.textChanges); + ts.Debug.assert(change.span.start === 0 && change.span.length === 0); + return { fileName: textChanges.fileName, textChanges: [{ start: { line: 0, offset: 0 }, end: { line: 0, offset: 0 }, newText: change.newText }] }; + } + function getLocationInNewDocument(oldText, renameFilename, renameLocation, edits) { + var newText = applyEdits(oldText, renameFilename, edits); + var _a = ts.computeLineAndCharacterOfPosition(ts.computeLineStarts(newText), renameLocation), line = _a.line, character = _a.character; + return { line: line + 1, offset: character + 1 }; + } + server.getLocationInNewDocument = getLocationInNewDocument; + function applyEdits(text, textFilename, edits) { + for (var _i = 0, edits_1 = edits; _i < edits_1.length; _i++) { + var _a = edits_1[_i], fileName = _a.fileName, textChanges_1 = _a.textChanges; + if (fileName !== textFilename) { + continue; + } + for (var i = textChanges_1.length - 1; i >= 0; i--) { + var _b = textChanges_1[i], newText = _b.newText, _c = _b.span, start = _c.start, length_1 = _c.length; + text = text.slice(0, start) + newText + text.slice(start + length_1); + } + } + return text; + } + })(server = ts.server || (ts.server = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + var server; + (function (server) { + var lineCollectionCapacity = 4; + var CharRangeSection; + (function (CharRangeSection) { + CharRangeSection[CharRangeSection["PreStart"] = 0] = "PreStart"; + CharRangeSection[CharRangeSection["Start"] = 1] = "Start"; + CharRangeSection[CharRangeSection["Entire"] = 2] = "Entire"; + CharRangeSection[CharRangeSection["Mid"] = 3] = "Mid"; + CharRangeSection[CharRangeSection["End"] = 4] = "End"; + CharRangeSection[CharRangeSection["PostEnd"] = 5] = "PostEnd"; + })(CharRangeSection || (CharRangeSection = {})); + var EditWalker = (function () { + function EditWalker() { + this.goSubtree = true; + this.lineIndex = new LineIndex(); + this.endBranch = []; + this.state = 2; + this.initialText = ""; + this.trailingText = ""; + this.lineIndex.root = new LineNode(); + this.startPath = [this.lineIndex.root]; + this.stack = [this.lineIndex.root]; + } + Object.defineProperty(EditWalker.prototype, "done", { + get: function () { return false; }, + enumerable: true, + configurable: true + }); + EditWalker.prototype.insertLines = function (insertedText, suppressTrailingText) { + if (suppressTrailingText) { + this.trailingText = ""; + } + if (insertedText) { + insertedText = this.initialText + insertedText + this.trailingText; + } + else { + insertedText = this.initialText + this.trailingText; + } + var lm = LineIndex.linesFromText(insertedText); + var lines = lm.lines; + if (lines.length > 1) { + if (lines[lines.length - 1] === "") { + lines.pop(); + } + } + var branchParent; + var lastZeroCount; + for (var k = this.endBranch.length - 1; k >= 0; k--) { + this.endBranch[k].updateCounts(); + if (this.endBranch[k].charCount() === 0) { + lastZeroCount = this.endBranch[k]; + if (k > 0) { + branchParent = this.endBranch[k - 1]; + } + else { + branchParent = this.branchNode; + } + } + } + if (lastZeroCount) { + branchParent.remove(lastZeroCount); + } + var leafNode = this.startPath[this.startPath.length - 1]; + if (lines.length > 0) { + leafNode.text = lines[0]; + if (lines.length > 1) { + var insertedNodes = new Array(lines.length - 1); + var startNode = leafNode; + for (var i = 1; i < lines.length; i++) { + insertedNodes[i - 1] = new LineLeaf(lines[i]); + } + var pathIndex = this.startPath.length - 2; + while (pathIndex >= 0) { + var insertionNode = this.startPath[pathIndex]; + insertedNodes = insertionNode.insertAt(startNode, insertedNodes); + pathIndex--; + startNode = insertionNode; + } + var insertedNodesLen = insertedNodes.length; + while (insertedNodesLen > 0) { + var newRoot = new LineNode(); + newRoot.add(this.lineIndex.root); + insertedNodes = newRoot.insertAt(this.lineIndex.root, insertedNodes); + insertedNodesLen = insertedNodes.length; + this.lineIndex.root = newRoot; + } + this.lineIndex.root.updateCounts(); + } + else { + for (var j = this.startPath.length - 2; j >= 0; j--) { + this.startPath[j].updateCounts(); + } + } + } + else { + var insertionNode = this.startPath[this.startPath.length - 2]; + insertionNode.remove(leafNode); + for (var j = this.startPath.length - 2; j >= 0; j--) { + this.startPath[j].updateCounts(); + } + } + return this.lineIndex; + }; + EditWalker.prototype.post = function (_relativeStart, _relativeLength, lineCollection) { + if (lineCollection === this.lineCollectionAtBranch) { + this.state = 4; + } + this.stack.pop(); + }; + EditWalker.prototype.pre = function (_relativeStart, _relativeLength, lineCollection, _parent, nodeType) { + var currentNode = this.stack[this.stack.length - 1]; + if ((this.state === 2) && (nodeType === 1)) { + this.state = 1; + this.branchNode = currentNode; + this.lineCollectionAtBranch = lineCollection; + } + var child; + function fresh(node) { + if (node.isLeaf()) { + return new LineLeaf(""); + } + else + return new LineNode(); + } + switch (nodeType) { + case 0: + this.goSubtree = false; + if (this.state !== 4) { + currentNode.add(lineCollection); + } + break; + case 1: + if (this.state === 4) { + this.goSubtree = false; + } + else { + child = fresh(lineCollection); + currentNode.add(child); + this.startPath.push(child); + } + break; + case 2: + if (this.state !== 4) { + child = fresh(lineCollection); + currentNode.add(child); + this.startPath.push(child); + } + else { + if (!lineCollection.isLeaf()) { + child = fresh(lineCollection); + currentNode.add(child); + this.endBranch.push(child); + } + } + break; + case 3: + this.goSubtree = false; + break; + case 4: + if (this.state !== 4) { + this.goSubtree = false; + } + else { + if (!lineCollection.isLeaf()) { + child = fresh(lineCollection); + currentNode.add(child); + this.endBranch.push(child); + } + } + break; + case 5: + this.goSubtree = false; + if (this.state !== 1) { + currentNode.add(lineCollection); + } + break; + } + if (this.goSubtree) { + this.stack.push(child); + } + }; + EditWalker.prototype.leaf = function (relativeStart, relativeLength, ll) { + if (this.state === 1) { + this.initialText = ll.text.substring(0, relativeStart); + } + else if (this.state === 2) { + this.initialText = ll.text.substring(0, relativeStart); + this.trailingText = ll.text.substring(relativeStart + relativeLength); + } + else { + this.trailingText = ll.text.substring(relativeStart + relativeLength); + } + }; + return EditWalker; + }()); + var TextChange = (function () { + function TextChange(pos, deleteLen, insertedText) { + this.pos = pos; + this.deleteLen = deleteLen; + this.insertedText = insertedText; + } + TextChange.prototype.getTextChangeRange = function () { + return ts.createTextChangeRange(ts.createTextSpan(this.pos, this.deleteLen), this.insertedText ? this.insertedText.length : 0); + }; + return TextChange; + }()); + var ScriptVersionCache = (function () { + function ScriptVersionCache() { + this.changes = []; + this.versions = new Array(ScriptVersionCache.maxVersions); + this.minVersion = 0; + this.currentVersion = 0; + } + ScriptVersionCache.prototype.versionToIndex = function (version) { + if (version < this.minVersion || version > this.currentVersion) { + return undefined; + } + return version % ScriptVersionCache.maxVersions; + }; + ScriptVersionCache.prototype.currentVersionToIndex = function () { + return this.currentVersion % ScriptVersionCache.maxVersions; + }; + ScriptVersionCache.prototype.edit = function (pos, deleteLen, insertedText) { + this.changes.push(new TextChange(pos, deleteLen, insertedText)); + if (this.changes.length > ScriptVersionCache.changeNumberThreshold || + deleteLen > ScriptVersionCache.changeLengthThreshold || + insertedText && insertedText.length > ScriptVersionCache.changeLengthThreshold) { + this.getSnapshot(); + } + }; + ScriptVersionCache.prototype.getSnapshot = function () { return this._getSnapshot(); }; + ScriptVersionCache.prototype._getSnapshot = function () { + var snap = this.versions[this.currentVersionToIndex()]; + if (this.changes.length > 0) { + var snapIndex = snap.index; + for (var _i = 0, _a = this.changes; _i < _a.length; _i++) { + var change = _a[_i]; + snapIndex = snapIndex.edit(change.pos, change.deleteLen, change.insertedText); + } + snap = new LineIndexSnapshot(this.currentVersion + 1, this, snapIndex, this.changes); + this.currentVersion = snap.version; + this.versions[this.currentVersionToIndex()] = snap; + this.changes = []; + if ((this.currentVersion - this.minVersion) >= ScriptVersionCache.maxVersions) { + this.minVersion = (this.currentVersion - ScriptVersionCache.maxVersions) + 1; + } + } + return snap; + }; + ScriptVersionCache.prototype.getSnapshotVersion = function () { + return this._getSnapshot().version; + }; + ScriptVersionCache.prototype.getLineInfo = function (line) { + return this._getSnapshot().index.lineNumberToInfo(line); + }; + ScriptVersionCache.prototype.lineOffsetToPosition = function (line, column) { + return this._getSnapshot().index.absolutePositionOfStartOfLine(line) + (column - 1); + }; + ScriptVersionCache.prototype.positionToLineOffset = function (position) { + return this._getSnapshot().index.positionToLineOffset(position); + }; + ScriptVersionCache.prototype.lineToTextSpan = function (line) { + var index = this._getSnapshot().index; + var _a = index.lineNumberToInfo(line + 1), lineText = _a.lineText, absolutePosition = _a.absolutePosition; + var len = lineText !== undefined ? lineText.length : index.absolutePositionOfStartOfLine(line + 2) - absolutePosition; + return ts.createTextSpan(absolutePosition, len); + }; + ScriptVersionCache.prototype.getTextChangesBetweenVersions = function (oldVersion, newVersion) { + if (oldVersion < newVersion) { + if (oldVersion >= this.minVersion) { + var textChangeRanges = []; + for (var i = oldVersion + 1; i <= newVersion; i++) { + var snap = this.versions[this.versionToIndex(i)]; + for (var _i = 0, _a = snap.changesSincePreviousVersion; _i < _a.length; _i++) { + var textChange = _a[_i]; + textChangeRanges.push(textChange.getTextChangeRange()); + } + } + return ts.collapseTextChangeRangesAcrossMultipleVersions(textChangeRanges); + } + else { + return undefined; + } + } + else { + return ts.unchangedTextChangeRange; + } + }; + ScriptVersionCache.fromString = function (script) { + var svc = new ScriptVersionCache(); + var snap = new LineIndexSnapshot(0, svc, new LineIndex()); + svc.versions[svc.currentVersion] = snap; + var lm = LineIndex.linesFromText(script); + snap.index.load(lm.lines); + return svc; + }; + ScriptVersionCache.changeNumberThreshold = 8; + ScriptVersionCache.changeLengthThreshold = 256; + ScriptVersionCache.maxVersions = 8; + return ScriptVersionCache; + }()); + server.ScriptVersionCache = ScriptVersionCache; + var LineIndexSnapshot = (function () { + function LineIndexSnapshot(version, cache, index, changesSincePreviousVersion) { + if (changesSincePreviousVersion === void 0) { changesSincePreviousVersion = server.emptyArray; } + this.version = version; + this.cache = cache; + this.index = index; + this.changesSincePreviousVersion = changesSincePreviousVersion; + } + LineIndexSnapshot.prototype.getText = function (rangeStart, rangeEnd) { + return this.index.getText(rangeStart, rangeEnd - rangeStart); + }; + LineIndexSnapshot.prototype.getLength = function () { + return this.index.getLength(); + }; + LineIndexSnapshot.prototype.getChangeRange = function (oldSnapshot) { + if (oldSnapshot instanceof LineIndexSnapshot && this.cache === oldSnapshot.cache) { + if (this.version <= oldSnapshot.version) { + return ts.unchangedTextChangeRange; + } + else { + return this.cache.getTextChangesBetweenVersions(oldSnapshot.version, this.version); + } + } + }; + return LineIndexSnapshot; + }()); + var LineIndex = (function () { + function LineIndex() { + this.checkEdits = false; + } + LineIndex.prototype.absolutePositionOfStartOfLine = function (oneBasedLine) { + return this.lineNumberToInfo(oneBasedLine).absolutePosition; + }; + LineIndex.prototype.positionToLineOffset = function (position) { + var _a = this.root.charOffsetToLineInfo(1, position), oneBasedLine = _a.oneBasedLine, zeroBasedColumn = _a.zeroBasedColumn; + return { line: oneBasedLine, offset: zeroBasedColumn + 1 }; + }; + LineIndex.prototype.positionToColumnAndLineText = function (position) { + return this.root.charOffsetToLineInfo(1, position); + }; + LineIndex.prototype.lineNumberToInfo = function (oneBasedLine) { + var lineCount = this.root.lineCount(); + if (oneBasedLine <= lineCount) { + var _a = this.root.lineNumberToInfo(oneBasedLine, 0), position = _a.position, leaf = _a.leaf; + return { absolutePosition: position, lineText: leaf && leaf.text }; + } + else { + return { absolutePosition: this.root.charCount(), lineText: undefined }; + } + }; + LineIndex.prototype.load = function (lines) { + if (lines.length > 0) { + var leaves = []; + for (var i = 0; i < lines.length; i++) { + leaves[i] = new LineLeaf(lines[i]); + } + this.root = LineIndex.buildTreeFromBottom(leaves); + } + else { + this.root = new LineNode(); + } + }; + LineIndex.prototype.walk = function (rangeStart, rangeLength, walkFns) { + this.root.walk(rangeStart, rangeLength, walkFns); + }; + LineIndex.prototype.getText = function (rangeStart, rangeLength) { + var accum = ""; + if ((rangeLength > 0) && (rangeStart < this.root.charCount())) { + this.walk(rangeStart, rangeLength, { + goSubtree: true, + done: false, + leaf: function (relativeStart, relativeLength, ll) { + accum = accum.concat(ll.text.substring(relativeStart, relativeStart + relativeLength)); + } + }); + } + return accum; + }; + LineIndex.prototype.getLength = function () { + return this.root.charCount(); + }; + LineIndex.prototype.every = function (f, rangeStart, rangeEnd) { + if (!rangeEnd) { + rangeEnd = this.root.charCount(); + } + var walkFns = { + goSubtree: true, + done: false, + leaf: function (relativeStart, relativeLength, ll) { + if (!f(ll, relativeStart, relativeLength)) { + this.done = true; + } + } + }; + this.walk(rangeStart, rangeEnd - rangeStart, walkFns); + return !walkFns.done; + }; + LineIndex.prototype.edit = function (pos, deleteLength, newText) { + if (this.root.charCount() === 0) { + ts.Debug.assert(deleteLength === 0); + if (newText !== undefined) { + this.load(LineIndex.linesFromText(newText).lines); + return this; + } + return undefined; + } + else { + var checkText = void 0; + if (this.checkEdits) { + var source = this.getText(0, this.root.charCount()); + checkText = source.slice(0, pos) + newText + source.slice(pos + deleteLength); + } + var walker = new EditWalker(); + var suppressTrailingText = false; + if (pos >= this.root.charCount()) { + pos = this.root.charCount() - 1; + var endString = this.getText(pos, 1); + if (newText) { + newText = endString + newText; + } + else { + newText = endString; + } + deleteLength = 0; + suppressTrailingText = true; + } + else if (deleteLength > 0) { + var e = pos + deleteLength; + var _a = this.positionToColumnAndLineText(e), zeroBasedColumn = _a.zeroBasedColumn, lineText = _a.lineText; + if (zeroBasedColumn === 0) { + deleteLength += lineText.length; + newText = newText ? newText + lineText : lineText; + } + } + this.root.walk(pos, deleteLength, walker); + walker.insertLines(newText, suppressTrailingText); + if (this.checkEdits) { + var updatedText = walker.lineIndex.getText(0, walker.lineIndex.getLength()); + ts.Debug.assert(checkText === updatedText, "buffer edit mismatch"); + } + return walker.lineIndex; + } + }; + LineIndex.buildTreeFromBottom = function (nodes) { + if (nodes.length < lineCollectionCapacity) { + return new LineNode(nodes); + } + var interiorNodes = new Array(Math.ceil(nodes.length / lineCollectionCapacity)); + var nodeIndex = 0; + for (var i = 0; i < interiorNodes.length; i++) { + var end = Math.min(nodeIndex + lineCollectionCapacity, nodes.length); + interiorNodes[i] = new LineNode(nodes.slice(nodeIndex, end)); + nodeIndex = end; + } + return this.buildTreeFromBottom(interiorNodes); + }; + LineIndex.linesFromText = function (text) { + var lineMap = ts.computeLineStarts(text); + if (lineMap.length === 0) { + return { lines: [], lineMap: lineMap }; + } + var lines = new Array(lineMap.length); + var lc = lineMap.length - 1; + for (var lmi = 0; lmi < lc; lmi++) { + lines[lmi] = text.substring(lineMap[lmi], lineMap[lmi + 1]); + } + var endText = text.substring(lineMap[lc]); + if (endText.length > 0) { + lines[lc] = endText; + } + else { + lines.pop(); + } + return { lines: lines, lineMap: lineMap }; + }; + return LineIndex; + }()); + server.LineIndex = LineIndex; + var LineNode = (function () { + function LineNode(children) { + if (children === void 0) { children = []; } + this.children = children; + this.totalChars = 0; + this.totalLines = 0; + if (children.length) + this.updateCounts(); + } + LineNode.prototype.isLeaf = function () { + return false; + }; + LineNode.prototype.updateCounts = function () { + this.totalChars = 0; + this.totalLines = 0; + for (var _i = 0, _a = this.children; _i < _a.length; _i++) { + var child = _a[_i]; + this.totalChars += child.charCount(); + this.totalLines += child.lineCount(); + } + }; + LineNode.prototype.execWalk = function (rangeStart, rangeLength, walkFns, childIndex, nodeType) { + if (walkFns.pre) { + walkFns.pre(rangeStart, rangeLength, this.children[childIndex], this, nodeType); + } + if (walkFns.goSubtree) { + this.children[childIndex].walk(rangeStart, rangeLength, walkFns); + if (walkFns.post) { + walkFns.post(rangeStart, rangeLength, this.children[childIndex], this, nodeType); + } + } + else { + walkFns.goSubtree = true; + } + return walkFns.done; + }; + LineNode.prototype.skipChild = function (relativeStart, relativeLength, childIndex, walkFns, nodeType) { + if (walkFns.pre && (!walkFns.done)) { + walkFns.pre(relativeStart, relativeLength, this.children[childIndex], this, nodeType); + walkFns.goSubtree = true; + } + }; + LineNode.prototype.walk = function (rangeStart, rangeLength, walkFns) { + var childIndex = 0; + var childCharCount = this.children[childIndex].charCount(); + var adjustedStart = rangeStart; + while (adjustedStart >= childCharCount) { + this.skipChild(adjustedStart, rangeLength, childIndex, walkFns, 0); + adjustedStart -= childCharCount; + childIndex++; + childCharCount = this.children[childIndex].charCount(); + } + if ((adjustedStart + rangeLength) <= childCharCount) { + if (this.execWalk(adjustedStart, rangeLength, walkFns, childIndex, 2)) { + return; + } + } + else { + if (this.execWalk(adjustedStart, childCharCount - adjustedStart, walkFns, childIndex, 1)) { + return; + } + var adjustedLength = rangeLength - (childCharCount - adjustedStart); + childIndex++; + var child = this.children[childIndex]; + childCharCount = child.charCount(); + while (adjustedLength > childCharCount) { + if (this.execWalk(0, childCharCount, walkFns, childIndex, 3)) { + return; + } + adjustedLength -= childCharCount; + childIndex++; + childCharCount = this.children[childIndex].charCount(); + } + if (adjustedLength > 0) { + if (this.execWalk(0, adjustedLength, walkFns, childIndex, 4)) { + return; + } + } + } + if (walkFns.pre) { + var clen = this.children.length; + if (childIndex < (clen - 1)) { + for (var ej = childIndex + 1; ej < clen; ej++) { + this.skipChild(0, 0, ej, walkFns, 5); + } + } + } + }; + LineNode.prototype.charOffsetToLineInfo = function (lineNumberAccumulator, relativePosition) { + if (this.children.length === 0) { + return { oneBasedLine: lineNumberAccumulator, zeroBasedColumn: relativePosition, lineText: undefined }; + } + for (var _i = 0, _a = this.children; _i < _a.length; _i++) { + var child = _a[_i]; + if (child.charCount() > relativePosition) { + if (child.isLeaf()) { + return { oneBasedLine: lineNumberAccumulator, zeroBasedColumn: relativePosition, lineText: child.text }; + } + else { + return child.charOffsetToLineInfo(lineNumberAccumulator, relativePosition); + } + } + else { + relativePosition -= child.charCount(); + lineNumberAccumulator += child.lineCount(); + } + } + var leaf = this.lineNumberToInfo(this.lineCount(), 0).leaf; + return { oneBasedLine: this.lineCount(), zeroBasedColumn: leaf ? leaf.charCount() : 0, lineText: undefined }; + }; + LineNode.prototype.lineNumberToInfo = function (relativeOneBasedLine, positionAccumulator) { + for (var _i = 0, _a = this.children; _i < _a.length; _i++) { + var child = _a[_i]; + var childLineCount = child.lineCount(); + if (childLineCount >= relativeOneBasedLine) { + return child.isLeaf() ? { position: positionAccumulator, leaf: child } : child.lineNumberToInfo(relativeOneBasedLine, positionAccumulator); + } + else { + relativeOneBasedLine -= childLineCount; + positionAccumulator += child.charCount(); + } + } + return { position: positionAccumulator, leaf: undefined }; + }; + LineNode.prototype.splitAfter = function (childIndex) { + var splitNode; + var clen = this.children.length; + childIndex++; + var endLength = childIndex; + if (childIndex < clen) { + splitNode = new LineNode(); + while (childIndex < clen) { + splitNode.add(this.children[childIndex]); + childIndex++; + } + splitNode.updateCounts(); + } + this.children.length = endLength; + return splitNode; + }; + LineNode.prototype.remove = function (child) { + var childIndex = this.findChildIndex(child); + var clen = this.children.length; + if (childIndex < (clen - 1)) { + for (var i = childIndex; i < (clen - 1); i++) { + this.children[i] = this.children[i + 1]; + } + } + this.children.pop(); + }; + LineNode.prototype.findChildIndex = function (child) { + var childIndex = this.children.indexOf(child); + ts.Debug.assert(childIndex !== -1); + return childIndex; + }; + LineNode.prototype.insertAt = function (child, nodes) { + var childIndex = this.findChildIndex(child); + var clen = this.children.length; + var nodeCount = nodes.length; + if ((clen < lineCollectionCapacity) && (childIndex === (clen - 1)) && (nodeCount === 1)) { + this.add(nodes[0]); + this.updateCounts(); + return []; + } + else { + var shiftNode = this.splitAfter(childIndex); + var nodeIndex = 0; + childIndex++; + while ((childIndex < lineCollectionCapacity) && (nodeIndex < nodeCount)) { + this.children[childIndex] = nodes[nodeIndex]; + childIndex++; + nodeIndex++; + } + var splitNodes = []; + var splitNodeCount = 0; + if (nodeIndex < nodeCount) { + splitNodeCount = Math.ceil((nodeCount - nodeIndex) / lineCollectionCapacity); + splitNodes = new Array(splitNodeCount); + var splitNodeIndex = 0; + for (var i = 0; i < splitNodeCount; i++) { + splitNodes[i] = new LineNode(); + } + var splitNode = splitNodes[0]; + while (nodeIndex < nodeCount) { + splitNode.add(nodes[nodeIndex]); + nodeIndex++; + if (splitNode.children.length === lineCollectionCapacity) { + splitNodeIndex++; + splitNode = splitNodes[splitNodeIndex]; + } + } + for (var i = splitNodes.length - 1; i >= 0; i--) { + if (splitNodes[i].children.length === 0) { + splitNodes.pop(); + } + } + } + if (shiftNode) { + splitNodes.push(shiftNode); + } + this.updateCounts(); + for (var i = 0; i < splitNodeCount; i++) { + splitNodes[i].updateCounts(); + } + return splitNodes; + } + }; + LineNode.prototype.add = function (collection) { + this.children.push(collection); + ts.Debug.assert(this.children.length <= lineCollectionCapacity); + }; + LineNode.prototype.charCount = function () { + return this.totalChars; + }; + LineNode.prototype.lineCount = function () { + return this.totalLines; + }; + return LineNode; + }()); + var LineLeaf = (function () { + function LineLeaf(text) { + this.text = text; + } + LineLeaf.prototype.isLeaf = function () { + return true; + }; + LineLeaf.prototype.walk = function (rangeStart, rangeLength, walkFns) { + walkFns.leaf(rangeStart, rangeLength, this); + }; + LineLeaf.prototype.charCount = function () { + return this.text.length; + }; + LineLeaf.prototype.lineCount = function () { + return 1; + }; + return LineLeaf; + }()); + })(server = ts.server || (ts.server = {})); +})(ts || (ts = {})); +//# sourceMappingURL=server.js.map +// tslint:disable no-unnecessary-type-assertion (TODO: tslint can't find node types) +var ts; +(function (ts) { + var server; + (function (server) { + var childProcess = require("child_process"); + var os = require("os"); + var net = require("net"); + function getGlobalTypingsCacheLocation() { + switch (process.platform) { + case "win32": { + var basePath = process.env.LOCALAPPDATA || + process.env.APPDATA || + (os.homedir && os.homedir()) || + process.env.USERPROFILE || + (process.env.HOMEDRIVE && process.env.HOMEPATH && ts.normalizeSlashes(process.env.HOMEDRIVE + process.env.HOMEPATH)) || + os.tmpdir(); + return ts.combinePaths(ts.combinePaths(ts.normalizeSlashes(basePath), "Microsoft/TypeScript"), ts.versionMajorMinor); + } + case "openbsd": + case "freebsd": + case "darwin": + case "linux": + case "android": { + var cacheLocation = getNonWindowsCacheLocation(process.platform === "darwin"); + return ts.combinePaths(ts.combinePaths(cacheLocation, "typescript"), ts.versionMajorMinor); + } + default: + return ts.Debug.fail("unsupported platform '" + process.platform + "'"); + } + } + function getNonWindowsCacheLocation(platformIsDarwin) { + if (process.env.XDG_CACHE_HOME) { + return process.env.XDG_CACHE_HOME; + } + var usersDir = platformIsDarwin ? "Users" : "home"; + var homePath = (os.homedir && os.homedir()) || + process.env.HOME || + ((process.env.LOGNAME || process.env.USER) && "/" + usersDir + "/" + (process.env.LOGNAME || process.env.USER)) || + os.tmpdir(); + var cacheFolder = platformIsDarwin + ? "Library/Caches" + : ".cache"; + return ts.combinePaths(ts.normalizeSlashes(homePath), cacheFolder); + } + var readline = require("readline"); + var fs = require("fs"); + var rl = readline.createInterface({ + input: process.stdin, + output: process.stdout, + terminal: false, + }); + var Logger = /** @class */ (function () { + function Logger(logFilename, traceToConsole, level) { + this.logFilename = logFilename; + this.traceToConsole = traceToConsole; + this.level = level; + this.fd = -1; + this.seq = 0; + this.inGroup = false; + this.firstInGroup = true; + if (this.logFilename) { + try { + this.fd = fs.openSync(this.logFilename, "w"); + } + catch (_) { + // swallow the error and keep logging disabled if file cannot be opened + } + } + } + Logger.padStringRight = function (str, padding) { + return (str + padding).slice(0, padding.length); + }; + Logger.prototype.close = function () { + if (this.fd >= 0) { + fs.close(this.fd, ts.noop); + } + }; + Logger.prototype.getLogFileName = function () { + return this.logFilename; + }; + Logger.prototype.perftrc = function (s) { + this.msg(s, server.Msg.Perf); + }; + Logger.prototype.info = function (s) { + this.msg(s, server.Msg.Info); + }; + Logger.prototype.err = function (s) { + this.msg(s, server.Msg.Err); + }; + Logger.prototype.startGroup = function () { + this.inGroup = true; + this.firstInGroup = true; + }; + Logger.prototype.endGroup = function () { + this.inGroup = false; + }; + Logger.prototype.loggingEnabled = function () { + return !!this.logFilename || this.traceToConsole; + }; + Logger.prototype.hasLevel = function (level) { + return this.loggingEnabled() && this.level >= level; + }; + Logger.prototype.msg = function (s, type) { + if (type === void 0) { type = server.Msg.Err; } + if (!this.canWrite) + return; + s = "[" + server.nowString() + "] " + s + "\n"; + if (!this.inGroup || this.firstInGroup) { + var prefix = Logger.padStringRight(type + " " + this.seq.toString(), " "); + s = prefix + s; + } + this.write(s); + if (!this.inGroup) { + this.seq++; + } + }; + Object.defineProperty(Logger.prototype, "canWrite", { + get: function () { + return this.fd >= 0 || this.traceToConsole; + }, + enumerable: true, + configurable: true + }); + Logger.prototype.write = function (s) { + if (this.fd >= 0) { + var buf = sys.bufferFrom(s); + // tslint:disable-next-line no-null-keyword + fs.writeSync(this.fd, buf, 0, buf.length, /*position*/ null); // TODO: GH#18217 + } + if (this.traceToConsole) { + console.warn(s); + } + }; + return Logger; + }()); + var NodeTypingsInstaller = /** @class */ (function () { + function NodeTypingsInstaller(telemetryEnabled, logger, host, globalTypingsCacheLocation, typingSafeListLocation, typesMapLocation, npmLocation, event) { + this.telemetryEnabled = telemetryEnabled; + this.logger = logger; + this.host = host; + this.globalTypingsCacheLocation = globalTypingsCacheLocation; + this.typingSafeListLocation = typingSafeListLocation; + this.typesMapLocation = typesMapLocation; + this.npmLocation = npmLocation; + this.event = event; + this.activeRequestCount = 0; + this.requestQueue = []; + this.requestMap = ts.createMap(); // Maps operation ID to newest requestQueue entry with that ID + /** We will lazily request the types registry on the first call to `isKnownTypesPackageName` and store it in `typesRegistryCache`. */ + this.requestedRegistry = false; + } + NodeTypingsInstaller.prototype.isKnownTypesPackageName = function (name) { + // We want to avoid looking this up in the registry as that is expensive. So first check that it's actually an NPM package. + var validationResult = ts.JsTyping.validatePackageName(name); + if (validationResult !== 0 /* Ok */) { + return false; + } + if (this.requestedRegistry) { + return !!this.typesRegistryCache && this.typesRegistryCache.has(name); + } + this.requestedRegistry = true; + this.send({ kind: "typesRegistry" }); + return false; + }; + NodeTypingsInstaller.prototype.installPackage = function (options) { + var _this = this; + this.send(__assign({ kind: "installPackage" }, options)); + ts.Debug.assert(this.packageInstalledPromise === undefined); + return new Promise(function (resolve, reject) { + _this.packageInstalledPromise = { resolve: resolve, reject: reject }; + }); + }; + NodeTypingsInstaller.prototype.inspectValue = function (options) { + var _this = this; + this.send({ kind: "inspectValue", options: options }); + ts.Debug.assert(this.inspectValuePromise === undefined); + return new Promise(function (resolve) { _this.inspectValuePromise = { resolve: resolve }; }); + }; + NodeTypingsInstaller.prototype.attach = function (projectService) { + var _this = this; + this.projectService = projectService; + if (this.logger.hasLevel(server.LogLevel.requestTime)) { + this.logger.info("Binding..."); + } + var args = [server.Arguments.GlobalCacheLocation, this.globalTypingsCacheLocation]; + if (this.telemetryEnabled) { + args.push(server.Arguments.EnableTelemetry); + } + if (this.logger.loggingEnabled() && this.logger.getLogFileName()) { + args.push(server.Arguments.LogFile, ts.combinePaths(ts.getDirectoryPath(ts.normalizeSlashes(this.logger.getLogFileName())), "ti-" + process.pid + ".log")); + } + if (this.typingSafeListLocation) { + args.push(server.Arguments.TypingSafeListLocation, this.typingSafeListLocation); + } + if (this.typesMapLocation) { + args.push(server.Arguments.TypesMapLocation, this.typesMapLocation); + } + if (this.npmLocation) { + args.push(server.Arguments.NpmLocation, this.npmLocation); + } + var execArgv = []; + for (var _i = 0, _a = process.execArgv; _i < _a.length; _i++) { + var arg = _a[_i]; + var match = /^--((?:debug|inspect)(?:-brk)?)(?:=(\d+))?$/.exec(arg); + if (match) { + // if port is specified - use port + 1 + // otherwise pick a default port depending on if 'debug' or 'inspect' and use its value + 1 + var currentPort = match[2] !== undefined + ? +match[2] + : match[1].charAt(0) === "d" ? 5858 : 9229; + execArgv.push("--" + match[1] + "=" + (currentPort + 1)); + break; + } + } + this.installer = childProcess.fork(ts.combinePaths(__dirname, "typingsInstaller.js"), args, { execArgv: execArgv }); + this.installer.on("message", function (m) { return _this.handleMessage(m); }); + this.event({ pid: this.installer.pid }, "typingsInstallerPid"); + process.on("exit", function () { + _this.installer.kill(); + }); + }; + NodeTypingsInstaller.prototype.onProjectClosed = function (p) { + this.send({ projectName: p.getProjectName(), kind: "closeProject" }); + }; + NodeTypingsInstaller.prototype.send = function (rq) { + this.installer.send(rq); + }; + NodeTypingsInstaller.prototype.enqueueInstallTypingsRequest = function (project, typeAcquisition, unresolvedImports) { + var _this = this; + var request = server.createInstallTypingsRequest(project, typeAcquisition, unresolvedImports); + if (this.logger.hasLevel(server.LogLevel.verbose)) { + if (this.logger.hasLevel(server.LogLevel.verbose)) { + this.logger.info("Scheduling throttled operation:" + server.stringifyIndented(request)); + } + } + var operationId = project.getProjectName(); + var operation = function () { + if (_this.logger.hasLevel(server.LogLevel.verbose)) { + _this.logger.info("Sending request:" + server.stringifyIndented(request)); + } + _this.send(request); + }; + var queuedRequest = { operationId: operationId, operation: operation }; + if (this.activeRequestCount < NodeTypingsInstaller.maxActiveRequestCount) { + this.scheduleRequest(queuedRequest); + } + else { + if (this.logger.hasLevel(server.LogLevel.verbose)) { + this.logger.info("Deferring request for: " + operationId); + } + this.requestQueue.push(queuedRequest); + this.requestMap.set(operationId, queuedRequest); + } + }; + NodeTypingsInstaller.prototype.handleMessage = function (response) { + if (this.logger.hasLevel(server.LogLevel.verbose)) { + this.logger.info("Received response:" + server.stringifyIndented(response)); + } + switch (response.kind) { + case server.EventTypesRegistry: + this.typesRegistryCache = ts.createMapFromTemplate(response.typesRegistry); + break; + case server.ActionPackageInstalled: { + var success = response.success, message = response.message; + if (success) { + this.packageInstalledPromise.resolve({ successMessage: message }); + } + else { + this.packageInstalledPromise.reject(message); + } + this.packageInstalledPromise = undefined; + this.projectService.updateTypingsForProject(response); + // The behavior is the same as for setTypings, so send the same event. + this.event(response, "setTypings"); + break; + } + case server.ActionValueInspected: + this.inspectValuePromise.resolve(response.result); + this.inspectValuePromise = undefined; + break; + case server.EventInitializationFailed: + { + var body = { + message: response.message + }; + var eventName = "typesInstallerInitializationFailed"; + this.event(body, eventName); + break; + } + case server.EventBeginInstallTypes: + { + var body = { + eventId: response.eventId, + packages: response.packagesToInstall, + }; + var eventName = "beginInstallTypes"; + this.event(body, eventName); + break; + } + case server.EventEndInstallTypes: + { + if (this.telemetryEnabled) { + var body_1 = { + telemetryEventName: "typingsInstalled", + payload: { + installedPackages: response.packagesToInstall.join(","), + installSuccess: response.installSuccess, + typingsInstallerVersion: response.typingsInstallerVersion + } + }; + var eventName_1 = "telemetry"; + this.event(body_1, eventName_1); + } + var body = { + eventId: response.eventId, + packages: response.packagesToInstall, + success: response.installSuccess, + }; + var eventName = "endInstallTypes"; + this.event(body, eventName); + break; + } + case server.ActionInvalidate: + { + this.projectService.updateTypingsForProject(response); + break; + } + case server.ActionSet: + { + if (this.activeRequestCount > 0) { + this.activeRequestCount--; + } + else { + ts.Debug.fail("Received too many responses"); + } + while (this.requestQueue.length > 0) { + var queuedRequest = this.requestQueue.shift(); + if (this.requestMap.get(queuedRequest.operationId) === queuedRequest) { + this.requestMap.delete(queuedRequest.operationId); + this.scheduleRequest(queuedRequest); + break; + } + if (this.logger.hasLevel(server.LogLevel.verbose)) { + this.logger.info("Skipping defunct request for: " + queuedRequest.operationId); + } + } + this.projectService.updateTypingsForProject(response); + this.event(response, "setTypings"); + break; + } + default: + ts.assertType(response); + } + }; + NodeTypingsInstaller.prototype.scheduleRequest = function (request) { + if (this.logger.hasLevel(server.LogLevel.verbose)) { + this.logger.info("Scheduling request for: " + request.operationId); + } + this.activeRequestCount++; + this.host.setTimeout(request.operation, NodeTypingsInstaller.requestDelayMillis); + }; + // This number is essentially arbitrary. Processing more than one typings request + // at a time makes sense, but having too many in the pipe results in a hang + // (see https://github.com/nodejs/node/issues/7657). + // It would be preferable to base our limit on the amount of space left in the + // buffer, but we have yet to find a way to retrieve that value. + NodeTypingsInstaller.maxActiveRequestCount = 10; + NodeTypingsInstaller.requestDelayMillis = 100; + return NodeTypingsInstaller; + }()); + var IOSession = /** @class */ (function (_super) { + __extends(IOSession, _super); + function IOSession() { + var _this = this; + var event = function (body, eventName) { + if (_this.constructed) { + _this.event(body, eventName); + } + else { + // It is unsafe to dereference `this` before initialization completes, + // so we defer until the next tick. + // + // Construction should finish before the next tick fires, so we do not need to do this recursively. + setImmediate(function () { return _this.event(body, eventName); }); + } + }; + var host = sys; + var typingsInstaller = disableAutomaticTypingAcquisition + ? undefined + : new NodeTypingsInstaller(telemetryEnabled, logger, host, getGlobalTypingsCacheLocation(), typingSafeListLocation, typesMapLocation, npmLocation, event); + _this = _super.call(this, { + host: host, + cancellationToken: cancellationToken, + useSingleInferredProject: useSingleInferredProject, + useInferredProjectPerProjectRoot: useInferredProjectPerProjectRoot, + typingsInstaller: typingsInstaller || server.nullTypingsInstaller, + byteLength: Buffer.byteLength, + hrtime: process.hrtime, + logger: logger, + canUseEvents: true, + suppressDiagnosticEvents: suppressDiagnosticEvents, + syntaxOnly: syntaxOnly, + noGetErrOnBackgroundUpdate: noGetErrOnBackgroundUpdate, + globalPlugins: globalPlugins, + pluginProbeLocations: pluginProbeLocations, + allowLocalPluginLoads: allowLocalPluginLoads, + typesMapLocation: typesMapLocation, + }) || this; + _this.eventPort = eventPort; + if (_this.canUseEvents && _this.eventPort) { + var s_1 = net.connect({ port: _this.eventPort }, function () { + _this.eventSocket = s_1; + if (_this.socketEventQueue) { + // flush queue. + for (var _i = 0, _a = _this.socketEventQueue; _i < _a.length; _i++) { + var event_1 = _a[_i]; + _this.writeToEventSocket(event_1.body, event_1.eventName); + } + _this.socketEventQueue = undefined; + } + }); + } + _this.constructed = true; + return _this; + } + IOSession.prototype.event = function (body, eventName) { + ts.Debug.assert(!!this.constructed, "Should only call `IOSession.prototype.event` on an initialized IOSession"); + if (this.canUseEvents && this.eventPort) { + if (!this.eventSocket) { + if (this.logger.hasLevel(server.LogLevel.verbose)) { + this.logger.info("eventPort: event \"" + eventName + "\" queued, but socket not yet initialized"); + } + (this.socketEventQueue || (this.socketEventQueue = [])).push({ body: body, eventName: eventName }); + return; + } + else { + ts.Debug.assert(this.socketEventQueue === undefined); + this.writeToEventSocket(body, eventName); + } + } + else { + _super.prototype.event.call(this, body, eventName); + } + }; + IOSession.prototype.writeToEventSocket = function (body, eventName) { + this.eventSocket.write(server.formatMessage(server.toEvent(eventName, body), this.logger, this.byteLength, this.host.newLine), "utf8"); + }; + IOSession.prototype.exit = function () { + this.logger.info("Exiting..."); + this.projectService.closeLog(); + process.exit(0); + }; + IOSession.prototype.listen = function () { + var _this = this; + rl.on("line", function (input) { + var message = input.trim(); + _this.onMessage(message); + }); + rl.on("close", function () { + _this.exit(); + }); + }; + return IOSession; + }(server.Session)); + function parseLoggingEnvironmentString(logEnvStr) { + if (!logEnvStr) { + return {}; + } + var logEnv = { logToFile: true }; + var args = logEnvStr.split(" "); + var len = args.length - 1; + for (var i = 0; i < len; i += 2) { + var option = args[i]; + var _a = getEntireValue(i + 1), value = _a.value, extraPartCounter = _a.extraPartCounter; + i += extraPartCounter; + if (option && value) { + switch (option) { + case "-file": + logEnv.file = value; + break; + case "-level": + var level = getLogLevel(value); + logEnv.detailLevel = level !== undefined ? level : server.LogLevel.normal; + break; + case "-traceToConsole": + logEnv.traceToConsole = value.toLowerCase() === "true"; + break; + case "-logToFile": + logEnv.logToFile = value.toLowerCase() === "true"; + break; + } + } + } + return logEnv; + function getEntireValue(initialIndex) { + var pathStart = args[initialIndex]; + var extraPartCounter = 0; + if (pathStart.charCodeAt(0) === 34 /* doubleQuote */ && + pathStart.charCodeAt(pathStart.length - 1) !== 34 /* doubleQuote */) { + for (var i = initialIndex + 1; i < args.length; i++) { + pathStart += " "; + pathStart += args[i]; + extraPartCounter++; + if (pathStart.charCodeAt(pathStart.length - 1) === 34 /* doubleQuote */) + break; + } + } + return { value: ts.stripQuotes(pathStart), extraPartCounter: extraPartCounter }; + } + } + function getLogLevel(level) { + if (level) { + var l = level.toLowerCase(); + for (var name in server.LogLevel) { + if (isNaN(+name) && l === name.toLowerCase()) { + return server.LogLevel[name]; + } + } + } + return undefined; + } + // TSS_LOG "{ level: "normal | verbose | terse", file?: string}" + function createLogger() { + var cmdLineLogFileName = server.findArgument("--logFile"); + var cmdLineVerbosity = getLogLevel(server.findArgument("--logVerbosity")); + var envLogOptions = parseLoggingEnvironmentString(process.env.TSS_LOG); + var unsubstitutedLogFileName = cmdLineLogFileName + ? ts.stripQuotes(cmdLineLogFileName) + : envLogOptions.logToFile + ? envLogOptions.file || (__dirname + "/.log" + process.pid.toString()) + : undefined; + var substitutedLogFileName = unsubstitutedLogFileName + ? unsubstitutedLogFileName.replace("PID", process.pid.toString()) + : undefined; + var logVerbosity = cmdLineVerbosity || envLogOptions.detailLevel; + return new Logger(substitutedLogFileName, envLogOptions.traceToConsole, logVerbosity); // TODO: GH#18217 + } + // This places log file in the directory containing editorServices.js + // TODO: check that this location is writable + // average async stat takes about 30 microseconds + // set chunk size to do 30 files in < 1 millisecond + function createPollingWatchedFileSet(interval, chunkSize) { + if (interval === void 0) { interval = 2500; } + if (chunkSize === void 0) { chunkSize = 30; } + var watchedFiles = []; + var nextFileToCheck = 0; + return { getModifiedTime: getModifiedTime, poll: poll, startWatchTimer: startWatchTimer, addFile: addFile, removeFile: removeFile }; + function getModifiedTime(fileName) { + return fs.statSync(fileName).mtime; + } + function poll(checkedIndex) { + var watchedFile = watchedFiles[checkedIndex]; + if (!watchedFile) { + return; + } + fs.stat(watchedFile.fileName, function (err, stats) { + if (err) { + if (err.code === "ENOENT") { + if (watchedFile.mtime.getTime() !== 0) { + watchedFile.mtime = ts.missingFileModifiedTime; + watchedFile.callback(watchedFile.fileName, ts.FileWatcherEventKind.Deleted); + } + } + else { + watchedFile.callback(watchedFile.fileName, ts.FileWatcherEventKind.Changed); + } + } + else { + ts.onWatchedFileStat(watchedFile, stats.mtime); + } + }); + } + // this implementation uses polling and + // stat due to inconsistencies of fs.watch + // and efficiency of stat on modern filesystems + function startWatchTimer() { + setInterval(function () { + var count = 0; + var nextToCheck = nextFileToCheck; + var firstCheck = -1; + while ((count < chunkSize) && (nextToCheck !== firstCheck)) { + poll(nextToCheck); + if (firstCheck < 0) { + firstCheck = nextToCheck; + } + nextToCheck++; + if (nextToCheck === watchedFiles.length) { + nextToCheck = 0; + } + count++; + } + nextFileToCheck = nextToCheck; + }, interval); + } + function addFile(fileName, callback) { + var file = { + fileName: fileName, + callback: callback, + mtime: sys.fileExists(fileName) + ? getModifiedTime(fileName) + : ts.missingFileModifiedTime // Any subsequent modification will occur after this time + }; + watchedFiles.push(file); + if (watchedFiles.length === 1) { + startWatchTimer(); + } + return file; + } + function removeFile(file) { + ts.unorderedRemoveItem(watchedFiles, file); + } + } + // REVIEW: for now this implementation uses polling. + // The advantage of polling is that it works reliably + // on all os and with network mounted files. + // For 90 referenced files, the average time to detect + // changes is 2*msInterval (by default 5 seconds). + // The overhead of this is .04 percent (1/2500) with + // average pause of < 1 millisecond (and max + // pause less than 1.5 milliseconds); question is + // do we anticipate reference sets in the 100s and + // do we care about waiting 10-20 seconds to detect + // changes for large reference sets? If so, do we want + // to increase the chunk size or decrease the interval + // time dynamically to match the large reference set? + var pollingWatchedFileSet = createPollingWatchedFileSet(); + var pending = []; + var canWrite = true; + function writeMessage(buf) { + if (!canWrite) { + pending.push(buf); + } + else { + canWrite = false; + process.stdout.write(buf, setCanWriteFlagAndWriteMessageIfNecessary); + } + } + function setCanWriteFlagAndWriteMessageIfNecessary() { + canWrite = true; + if (pending.length) { + writeMessage(pending.shift()); + } + } + function extractWatchDirectoryCacheKey(path, currentDriveKey) { + path = ts.normalizeSlashes(path); + if (isUNCPath(path)) { + // UNC path: extract server name + // //server/location + // ^ <- from 0 to this position + var firstSlash = path.indexOf(ts.directorySeparator, 2); + return firstSlash !== -1 ? path.substring(0, firstSlash).toLowerCase() : path; + } + var rootLength = ts.getRootLength(path); + if (rootLength === 0) { + // relative path - assume file is on the current drive + return currentDriveKey; + } + if (path.charCodeAt(1) === 58 /* colon */ && path.charCodeAt(2) === 47 /* slash */) { + // rooted path that starts with c:/... - extract drive letter + return path.charAt(0).toLowerCase(); + } + if (path.charCodeAt(0) === 47 /* slash */ && path.charCodeAt(1) !== 47 /* slash */) { + // rooted path that starts with slash - /somename - use key for current drive + return currentDriveKey; + } + // do not cache any other cases + return undefined; + } + function isUNCPath(s) { + return s.length > 2 && s.charCodeAt(0) === 47 /* slash */ && s.charCodeAt(1) === 47 /* slash */; + } + var logger = createLogger(); + var sys = ts.sys; + var nodeVersion = ts.getNodeMajorVersion(); + // use watchGuard process on Windows when node version is 4 or later + var useWatchGuard = process.platform === "win32" && nodeVersion >= 4; + var originalWatchDirectory = sys.watchDirectory.bind(sys); + var noopWatcher = { close: ts.noop }; + // This is the function that catches the exceptions when watching directory, and yet lets project service continue to function + // Eg. on linux the number of watches are limited and one could easily exhaust watches and the exception ENOSPC is thrown when creating watcher at that point + function watchDirectorySwallowingException(path, callback, recursive) { + try { + return originalWatchDirectory(path, callback, recursive); + } + catch (e) { + logger.info("Exception when creating directory watcher: " + e.message); + return noopWatcher; + } + } + if (useWatchGuard) { + var currentDrive_1 = extractWatchDirectoryCacheKey(sys.resolvePath(sys.getCurrentDirectory()), /*currentDriveKey*/ undefined); + var statusCache_1 = ts.createMap(); + sys.watchDirectory = function (path, callback, recursive) { + var cacheKey = extractWatchDirectoryCacheKey(path, currentDrive_1); + var status = cacheKey && statusCache_1.get(cacheKey); + if (status === undefined) { + if (logger.hasLevel(server.LogLevel.verbose)) { + logger.info(cacheKey + " for path " + path + " not found in cache..."); + } + try { + var args = [ts.combinePaths(__dirname, "watchGuard.js"), path]; + if (logger.hasLevel(server.LogLevel.verbose)) { + logger.info("Starting " + process.execPath + " with args:" + server.stringifyIndented(args)); + } + childProcess.execFileSync(process.execPath, args, { stdio: "ignore", env: { ELECTRON_RUN_AS_NODE: "1" } }); + status = true; + if (logger.hasLevel(server.LogLevel.verbose)) { + logger.info("WatchGuard for path " + path + " returned: OK"); + } + } + catch (e) { + status = false; + if (logger.hasLevel(server.LogLevel.verbose)) { + logger.info("WatchGuard for path " + path + " returned: " + e.message); + } + } + if (cacheKey) { + statusCache_1.set(cacheKey, status); + } + } + else if (logger.hasLevel(server.LogLevel.verbose)) { + logger.info("watchDirectory for " + path + " uses cached drive information."); + } + if (status) { + // this drive is safe to use - call real 'watchDirectory' + return watchDirectorySwallowingException(path, callback, recursive); + } + else { + // this drive is unsafe - return no-op watcher + return noopWatcher; + } + }; + } + else { + sys.watchDirectory = watchDirectorySwallowingException; + } + // Override sys.write because fs.writeSync is not reliable on Node 4 + sys.write = function (s) { return writeMessage(sys.bufferFrom(s, "utf8")); }; + sys.watchFile = function (fileName, callback) { + var watchedFile = pollingWatchedFileSet.addFile(fileName, callback); + return { + close: function () { return pollingWatchedFileSet.removeFile(watchedFile); } + }; + }; + sys.setTimeout = setTimeout; + sys.clearTimeout = clearTimeout; + sys.setImmediate = setImmediate; + sys.clearImmediate = clearImmediate; + if (typeof global !== "undefined" && global.gc) { + sys.gc = function () { return global.gc(); }; + } + sys.require = function (initialDir, moduleName) { + try { + return { module: require(ts.resolveJSModule(moduleName, initialDir, sys)), error: undefined }; + } + catch (error) { + return { module: undefined, error: error }; + } + }; + var cancellationToken; + try { + var factory = require("./cancellationToken"); + cancellationToken = factory(sys.args); + } + catch (e) { + cancellationToken = server.nullCancellationToken; + } + var eventPort; + { + var str = server.findArgument("--eventPort"); + var v = str === undefined ? undefined : parseInt(str); + if (v !== undefined && !isNaN(v)) { + eventPort = v; + } + } + var localeStr = server.findArgument("--locale"); + if (localeStr) { + ts.validateLocaleAndSetLanguage(localeStr, sys); + } + ts.setStackTraceLimit(); + var typingSafeListLocation = server.findArgument(server.Arguments.TypingSafeListLocation); // TODO: GH#18217 + var typesMapLocation = server.findArgument(server.Arguments.TypesMapLocation) || ts.combinePaths(ts.getDirectoryPath(sys.getExecutingFilePath()), "typesMap.json"); + var npmLocation = server.findArgument(server.Arguments.NpmLocation); + function parseStringArray(argName) { + var arg = server.findArgument(argName); + if (arg === undefined) { + return server.emptyArray; + } + return arg.split(",").filter(function (name) { return name !== ""; }); + } + var globalPlugins = parseStringArray("--globalPlugins"); + var pluginProbeLocations = parseStringArray("--pluginProbeLocations"); + var allowLocalPluginLoads = server.hasArgument("--allowLocalPluginLoads"); + var useSingleInferredProject = server.hasArgument("--useSingleInferredProject"); + var useInferredProjectPerProjectRoot = server.hasArgument("--useInferredProjectPerProjectRoot"); + var disableAutomaticTypingAcquisition = server.hasArgument("--disableAutomaticTypingAcquisition"); + var suppressDiagnosticEvents = server.hasArgument("--suppressDiagnosticEvents"); + var syntaxOnly = server.hasArgument("--syntaxOnly"); + var telemetryEnabled = server.hasArgument(server.Arguments.EnableTelemetry); + var noGetErrOnBackgroundUpdate = server.hasArgument("--noGetErrOnBackgroundUpdate"); + logger.info("Starting TS Server"); + logger.info("Version: " + ts.version); + logger.info("Arguments: " + process.argv.join(" ")); + logger.info("Platform: " + os.platform() + " NodeVersion: " + nodeVersion + " CaseSensitive: " + sys.useCaseSensitiveFileNames); + var ioSession = new IOSession(); + process.on("uncaughtException", function (err) { + ioSession.logError(err, "unknown"); + }); + // See https://github.com/Microsoft/TypeScript/issues/11348 + // tslint:disable-next-line no-unnecessary-type-assertion-2 + process.noAsar = true; + // Start listening + ioSession.listen(); + })(server = ts.server || (ts.server = {})); +})(ts || (ts = {})); +//# sourceMappingURL=tsserver.js.map \ No newline at end of file diff --git a/node_modules/typescript/lib/tsserverlibrary.d.ts b/node_modules/typescript/lib/tsserverlibrary.d.ts new file mode 100644 index 0000000..e67f6d3 --- /dev/null +++ b/node_modules/typescript/lib/tsserverlibrary.d.ts @@ -0,0 +1,8943 @@ +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + +declare namespace ts { + const versionMajorMinor = "3.2"; + /** The version of the TypeScript compiler release */ + const version: string; +} +declare namespace ts { + /** + * Type of objects whose values are all of the same type. + * The `in` and `for-in` operators can *not* be safely used, + * since `Object.prototype` may be modified by outside code. + */ + interface MapLike { + [index: string]: T; + } + interface SortedReadonlyArray extends ReadonlyArray { + " __sortedArrayBrand": any; + } + interface SortedArray extends Array { + " __sortedArrayBrand": any; + } + /** ES6 Map interface, only read methods included. */ + interface ReadonlyMap { + get(key: string): T | undefined; + has(key: string): boolean; + forEach(action: (value: T, key: string) => void): void; + readonly size: number; + keys(): Iterator; + values(): Iterator; + entries(): Iterator<[string, T]>; + } + /** ES6 Map interface. */ + interface Map extends ReadonlyMap { + set(key: string, value: T): this; + delete(key: string): boolean; + clear(): void; + } + /** ES6 Iterator type. */ + interface Iterator { + next(): { + value: T; + done: false; + } | { + value: never; + done: true; + }; + } + /** Array that is only intended to be pushed to, never read. */ + interface Push { + push(...values: T[]): void; + } +} +declare namespace ts { + type Path = string & { + __pathBrand: any; + }; + interface TextRange { + pos: number; + end: number; + } + type JsDocSyntaxKind = SyntaxKind.EndOfFileToken | SyntaxKind.WhitespaceTrivia | SyntaxKind.AtToken | SyntaxKind.NewLineTrivia | SyntaxKind.AsteriskToken | SyntaxKind.OpenBraceToken | SyntaxKind.CloseBraceToken | SyntaxKind.LessThanToken | SyntaxKind.OpenBracketToken | SyntaxKind.CloseBracketToken | SyntaxKind.EqualsToken | SyntaxKind.CommaToken | SyntaxKind.DotToken | SyntaxKind.Identifier | SyntaxKind.NoSubstitutionTemplateLiteral | SyntaxKind.Unknown | KeywordSyntaxKind; + type KeywordSyntaxKind = SyntaxKind.AbstractKeyword | SyntaxKind.AnyKeyword | SyntaxKind.AsKeyword | SyntaxKind.BigIntKeyword | SyntaxKind.BooleanKeyword | SyntaxKind.BreakKeyword | SyntaxKind.CaseKeyword | SyntaxKind.CatchKeyword | SyntaxKind.ClassKeyword | SyntaxKind.ContinueKeyword | SyntaxKind.ConstKeyword | SyntaxKind.ConstructorKeyword | SyntaxKind.DebuggerKeyword | SyntaxKind.DeclareKeyword | SyntaxKind.DefaultKeyword | SyntaxKind.DeleteKeyword | SyntaxKind.DoKeyword | SyntaxKind.ElseKeyword | SyntaxKind.EnumKeyword | SyntaxKind.ExportKeyword | SyntaxKind.ExtendsKeyword | SyntaxKind.FalseKeyword | SyntaxKind.FinallyKeyword | SyntaxKind.ForKeyword | SyntaxKind.FromKeyword | SyntaxKind.FunctionKeyword | SyntaxKind.GetKeyword | SyntaxKind.IfKeyword | SyntaxKind.ImplementsKeyword | SyntaxKind.ImportKeyword | SyntaxKind.InKeyword | SyntaxKind.InferKeyword | SyntaxKind.InstanceOfKeyword | SyntaxKind.InterfaceKeyword | SyntaxKind.IsKeyword | SyntaxKind.KeyOfKeyword | SyntaxKind.LetKeyword | SyntaxKind.ModuleKeyword | SyntaxKind.NamespaceKeyword | SyntaxKind.NeverKeyword | SyntaxKind.NewKeyword | SyntaxKind.NullKeyword | SyntaxKind.NumberKeyword | SyntaxKind.ObjectKeyword | SyntaxKind.PackageKeyword | SyntaxKind.PrivateKeyword | SyntaxKind.ProtectedKeyword | SyntaxKind.PublicKeyword | SyntaxKind.ReadonlyKeyword | SyntaxKind.RequireKeyword | SyntaxKind.GlobalKeyword | SyntaxKind.ReturnKeyword | SyntaxKind.SetKeyword | SyntaxKind.StaticKeyword | SyntaxKind.StringKeyword | SyntaxKind.SuperKeyword | SyntaxKind.SwitchKeyword | SyntaxKind.SymbolKeyword | SyntaxKind.ThisKeyword | SyntaxKind.ThrowKeyword | SyntaxKind.TrueKeyword | SyntaxKind.TryKeyword | SyntaxKind.TypeKeyword | SyntaxKind.TypeOfKeyword | SyntaxKind.UndefinedKeyword | SyntaxKind.UniqueKeyword | SyntaxKind.UnknownKeyword | SyntaxKind.VarKeyword | SyntaxKind.VoidKeyword | SyntaxKind.WhileKeyword | SyntaxKind.WithKeyword | SyntaxKind.YieldKeyword | SyntaxKind.AsyncKeyword | SyntaxKind.AwaitKeyword | SyntaxKind.OfKeyword; + type JsxTokenSyntaxKind = SyntaxKind.LessThanSlashToken | SyntaxKind.EndOfFileToken | SyntaxKind.ConflictMarkerTrivia | SyntaxKind.JsxText | SyntaxKind.JsxTextAllWhiteSpaces | SyntaxKind.OpenBraceToken | SyntaxKind.LessThanToken; + enum SyntaxKind { + Unknown = 0, + EndOfFileToken = 1, + SingleLineCommentTrivia = 2, + MultiLineCommentTrivia = 3, + NewLineTrivia = 4, + WhitespaceTrivia = 5, + ShebangTrivia = 6, + ConflictMarkerTrivia = 7, + NumericLiteral = 8, + BigIntLiteral = 9, + StringLiteral = 10, + JsxText = 11, + JsxTextAllWhiteSpaces = 12, + RegularExpressionLiteral = 13, + NoSubstitutionTemplateLiteral = 14, + TemplateHead = 15, + TemplateMiddle = 16, + TemplateTail = 17, + OpenBraceToken = 18, + CloseBraceToken = 19, + OpenParenToken = 20, + CloseParenToken = 21, + OpenBracketToken = 22, + CloseBracketToken = 23, + DotToken = 24, + DotDotDotToken = 25, + SemicolonToken = 26, + CommaToken = 27, + LessThanToken = 28, + LessThanSlashToken = 29, + GreaterThanToken = 30, + LessThanEqualsToken = 31, + GreaterThanEqualsToken = 32, + EqualsEqualsToken = 33, + ExclamationEqualsToken = 34, + EqualsEqualsEqualsToken = 35, + ExclamationEqualsEqualsToken = 36, + EqualsGreaterThanToken = 37, + PlusToken = 38, + MinusToken = 39, + AsteriskToken = 40, + AsteriskAsteriskToken = 41, + SlashToken = 42, + PercentToken = 43, + PlusPlusToken = 44, + MinusMinusToken = 45, + LessThanLessThanToken = 46, + GreaterThanGreaterThanToken = 47, + GreaterThanGreaterThanGreaterThanToken = 48, + AmpersandToken = 49, + BarToken = 50, + CaretToken = 51, + ExclamationToken = 52, + TildeToken = 53, + AmpersandAmpersandToken = 54, + BarBarToken = 55, + QuestionToken = 56, + ColonToken = 57, + AtToken = 58, + EqualsToken = 59, + PlusEqualsToken = 60, + MinusEqualsToken = 61, + AsteriskEqualsToken = 62, + AsteriskAsteriskEqualsToken = 63, + SlashEqualsToken = 64, + PercentEqualsToken = 65, + LessThanLessThanEqualsToken = 66, + GreaterThanGreaterThanEqualsToken = 67, + GreaterThanGreaterThanGreaterThanEqualsToken = 68, + AmpersandEqualsToken = 69, + BarEqualsToken = 70, + CaretEqualsToken = 71, + Identifier = 72, + BreakKeyword = 73, + CaseKeyword = 74, + CatchKeyword = 75, + ClassKeyword = 76, + ConstKeyword = 77, + ContinueKeyword = 78, + DebuggerKeyword = 79, + DefaultKeyword = 80, + DeleteKeyword = 81, + DoKeyword = 82, + ElseKeyword = 83, + EnumKeyword = 84, + ExportKeyword = 85, + ExtendsKeyword = 86, + FalseKeyword = 87, + FinallyKeyword = 88, + ForKeyword = 89, + FunctionKeyword = 90, + IfKeyword = 91, + ImportKeyword = 92, + InKeyword = 93, + InstanceOfKeyword = 94, + NewKeyword = 95, + NullKeyword = 96, + ReturnKeyword = 97, + SuperKeyword = 98, + SwitchKeyword = 99, + ThisKeyword = 100, + ThrowKeyword = 101, + TrueKeyword = 102, + TryKeyword = 103, + TypeOfKeyword = 104, + VarKeyword = 105, + VoidKeyword = 106, + WhileKeyword = 107, + WithKeyword = 108, + ImplementsKeyword = 109, + InterfaceKeyword = 110, + LetKeyword = 111, + PackageKeyword = 112, + PrivateKeyword = 113, + ProtectedKeyword = 114, + PublicKeyword = 115, + StaticKeyword = 116, + YieldKeyword = 117, + AbstractKeyword = 118, + AsKeyword = 119, + AnyKeyword = 120, + AsyncKeyword = 121, + AwaitKeyword = 122, + BooleanKeyword = 123, + ConstructorKeyword = 124, + DeclareKeyword = 125, + GetKeyword = 126, + InferKeyword = 127, + IsKeyword = 128, + KeyOfKeyword = 129, + ModuleKeyword = 130, + NamespaceKeyword = 131, + NeverKeyword = 132, + ReadonlyKeyword = 133, + RequireKeyword = 134, + NumberKeyword = 135, + ObjectKeyword = 136, + SetKeyword = 137, + StringKeyword = 138, + SymbolKeyword = 139, + TypeKeyword = 140, + UndefinedKeyword = 141, + UniqueKeyword = 142, + UnknownKeyword = 143, + FromKeyword = 144, + GlobalKeyword = 145, + BigIntKeyword = 146, + OfKeyword = 147, + QualifiedName = 148, + ComputedPropertyName = 149, + TypeParameter = 150, + Parameter = 151, + Decorator = 152, + PropertySignature = 153, + PropertyDeclaration = 154, + MethodSignature = 155, + MethodDeclaration = 156, + Constructor = 157, + GetAccessor = 158, + SetAccessor = 159, + CallSignature = 160, + ConstructSignature = 161, + IndexSignature = 162, + TypePredicate = 163, + TypeReference = 164, + FunctionType = 165, + ConstructorType = 166, + TypeQuery = 167, + TypeLiteral = 168, + ArrayType = 169, + TupleType = 170, + OptionalType = 171, + RestType = 172, + UnionType = 173, + IntersectionType = 174, + ConditionalType = 175, + InferType = 176, + ParenthesizedType = 177, + ThisType = 178, + TypeOperator = 179, + IndexedAccessType = 180, + MappedType = 181, + LiteralType = 182, + ImportType = 183, + ObjectBindingPattern = 184, + ArrayBindingPattern = 185, + BindingElement = 186, + ArrayLiteralExpression = 187, + ObjectLiteralExpression = 188, + PropertyAccessExpression = 189, + ElementAccessExpression = 190, + CallExpression = 191, + NewExpression = 192, + TaggedTemplateExpression = 193, + TypeAssertionExpression = 194, + ParenthesizedExpression = 195, + FunctionExpression = 196, + ArrowFunction = 197, + DeleteExpression = 198, + TypeOfExpression = 199, + VoidExpression = 200, + AwaitExpression = 201, + PrefixUnaryExpression = 202, + PostfixUnaryExpression = 203, + BinaryExpression = 204, + ConditionalExpression = 205, + TemplateExpression = 206, + YieldExpression = 207, + SpreadElement = 208, + ClassExpression = 209, + OmittedExpression = 210, + ExpressionWithTypeArguments = 211, + AsExpression = 212, + NonNullExpression = 213, + MetaProperty = 214, + SyntheticExpression = 215, + TemplateSpan = 216, + SemicolonClassElement = 217, + Block = 218, + VariableStatement = 219, + EmptyStatement = 220, + ExpressionStatement = 221, + IfStatement = 222, + DoStatement = 223, + WhileStatement = 224, + ForStatement = 225, + ForInStatement = 226, + ForOfStatement = 227, + ContinueStatement = 228, + BreakStatement = 229, + ReturnStatement = 230, + WithStatement = 231, + SwitchStatement = 232, + LabeledStatement = 233, + ThrowStatement = 234, + TryStatement = 235, + DebuggerStatement = 236, + VariableDeclaration = 237, + VariableDeclarationList = 238, + FunctionDeclaration = 239, + ClassDeclaration = 240, + InterfaceDeclaration = 241, + TypeAliasDeclaration = 242, + EnumDeclaration = 243, + ModuleDeclaration = 244, + ModuleBlock = 245, + CaseBlock = 246, + NamespaceExportDeclaration = 247, + ImportEqualsDeclaration = 248, + ImportDeclaration = 249, + ImportClause = 250, + NamespaceImport = 251, + NamedImports = 252, + ImportSpecifier = 253, + ExportAssignment = 254, + ExportDeclaration = 255, + NamedExports = 256, + ExportSpecifier = 257, + MissingDeclaration = 258, + ExternalModuleReference = 259, + JsxElement = 260, + JsxSelfClosingElement = 261, + JsxOpeningElement = 262, + JsxClosingElement = 263, + JsxFragment = 264, + JsxOpeningFragment = 265, + JsxClosingFragment = 266, + JsxAttribute = 267, + JsxAttributes = 268, + JsxSpreadAttribute = 269, + JsxExpression = 270, + CaseClause = 271, + DefaultClause = 272, + HeritageClause = 273, + CatchClause = 274, + PropertyAssignment = 275, + ShorthandPropertyAssignment = 276, + SpreadAssignment = 277, + EnumMember = 278, + SourceFile = 279, + Bundle = 280, + UnparsedSource = 281, + InputFiles = 282, + JSDocTypeExpression = 283, + JSDocAllType = 284, + JSDocUnknownType = 285, + JSDocNullableType = 286, + JSDocNonNullableType = 287, + JSDocOptionalType = 288, + JSDocFunctionType = 289, + JSDocVariadicType = 290, + JSDocComment = 291, + JSDocTypeLiteral = 292, + JSDocSignature = 293, + JSDocTag = 294, + JSDocAugmentsTag = 295, + JSDocClassTag = 296, + JSDocCallbackTag = 297, + JSDocEnumTag = 298, + JSDocParameterTag = 299, + JSDocReturnTag = 300, + JSDocThisTag = 301, + JSDocTypeTag = 302, + JSDocTemplateTag = 303, + JSDocTypedefTag = 304, + JSDocPropertyTag = 305, + SyntaxList = 306, + NotEmittedStatement = 307, + PartiallyEmittedExpression = 308, + CommaListExpression = 309, + MergeDeclarationMarker = 310, + EndOfDeclarationMarker = 311, + Count = 312, + FirstAssignment = 59, + LastAssignment = 71, + FirstCompoundAssignment = 60, + LastCompoundAssignment = 71, + FirstReservedWord = 73, + LastReservedWord = 108, + FirstKeyword = 73, + LastKeyword = 147, + FirstFutureReservedWord = 109, + LastFutureReservedWord = 117, + FirstTypeNode = 163, + LastTypeNode = 183, + FirstPunctuation = 18, + LastPunctuation = 71, + FirstToken = 0, + LastToken = 147, + FirstTriviaToken = 2, + LastTriviaToken = 7, + FirstLiteralToken = 8, + LastLiteralToken = 14, + FirstTemplateToken = 14, + LastTemplateToken = 17, + FirstBinaryOperator = 28, + LastBinaryOperator = 71, + FirstNode = 148, + FirstJSDocNode = 283, + LastJSDocNode = 305, + FirstJSDocTagNode = 294, + LastJSDocTagNode = 305 + } + enum NodeFlags { + None = 0, + Let = 1, + Const = 2, + NestedNamespace = 4, + Synthesized = 8, + Namespace = 16, + ExportContext = 32, + ContainsThis = 64, + HasImplicitReturn = 128, + HasExplicitReturn = 256, + GlobalAugmentation = 512, + HasAsyncFunctions = 1024, + DisallowInContext = 2048, + YieldContext = 4096, + DecoratorContext = 8192, + AwaitContext = 16384, + ThisNodeHasError = 32768, + JavaScriptFile = 65536, + ThisNodeOrAnySubNodesHasError = 131072, + HasAggregatedChildData = 262144, + JSDoc = 2097152, + JsonFile = 16777216, + BlockScoped = 3, + ReachabilityCheckFlags = 384, + ReachabilityAndEmitFlags = 1408, + ContextFlags = 12679168, + TypeExcludesFlags = 20480 + } + enum ModifierFlags { + None = 0, + Export = 1, + Ambient = 2, + Public = 4, + Private = 8, + Protected = 16, + Static = 32, + Readonly = 64, + Abstract = 128, + Async = 256, + Default = 512, + Const = 2048, + HasComputedFlags = 536870912, + AccessibilityModifier = 28, + ParameterPropertyModifier = 92, + NonPublicAccessibilityModifier = 24, + TypeScriptModifier = 2270, + ExportDefault = 513, + All = 3071 + } + enum JsxFlags { + None = 0, + /** An element from a named property of the JSX.IntrinsicElements interface */ + IntrinsicNamedElement = 1, + /** An element inferred from the string index signature of the JSX.IntrinsicElements interface */ + IntrinsicIndexedElement = 2, + IntrinsicElement = 3 + } + interface Node extends TextRange { + kind: SyntaxKind; + flags: NodeFlags; + decorators?: NodeArray; + modifiers?: ModifiersArray; + parent: Node; + } + interface JSDocContainer { + } + type HasJSDoc = ParameterDeclaration | CallSignatureDeclaration | ConstructSignatureDeclaration | MethodSignature | PropertySignature | ArrowFunction | ParenthesizedExpression | SpreadAssignment | ShorthandPropertyAssignment | PropertyAssignment | FunctionExpression | LabeledStatement | ExpressionStatement | VariableStatement | FunctionDeclaration | ConstructorDeclaration | MethodDeclaration | PropertyDeclaration | AccessorDeclaration | ClassLikeDeclaration | InterfaceDeclaration | TypeAliasDeclaration | EnumMember | EnumDeclaration | ModuleDeclaration | ImportEqualsDeclaration | IndexSignatureDeclaration | FunctionTypeNode | ConstructorTypeNode | JSDocFunctionType | ExportDeclaration | EndOfFileToken; + type HasType = SignatureDeclaration | VariableDeclaration | ParameterDeclaration | PropertySignature | PropertyDeclaration | TypePredicateNode | ParenthesizedTypeNode | TypeOperatorNode | MappedTypeNode | AssertionExpression | TypeAliasDeclaration | JSDocTypeExpression | JSDocNonNullableType | JSDocNullableType | JSDocOptionalType | JSDocVariadicType; + type HasInitializer = HasExpressionInitializer | ForStatement | ForInStatement | ForOfStatement | JsxAttribute; + type HasExpressionInitializer = VariableDeclaration | ParameterDeclaration | BindingElement | PropertySignature | PropertyDeclaration | PropertyAssignment | EnumMember; + interface NodeArray extends ReadonlyArray, TextRange { + hasTrailingComma?: boolean; + } + interface Token extends Node { + kind: TKind; + } + type DotDotDotToken = Token; + type QuestionToken = Token; + type ExclamationToken = Token; + type ColonToken = Token; + type EqualsToken = Token; + type AsteriskToken = Token; + type EqualsGreaterThanToken = Token; + type EndOfFileToken = Token & JSDocContainer; + type ReadonlyToken = Token; + type AwaitKeywordToken = Token; + type PlusToken = Token; + type MinusToken = Token; + type Modifier = Token | Token | Token | Token | Token | Token | Token | Token | Token | Token | Token; + type ModifiersArray = NodeArray; + interface Identifier extends PrimaryExpression, Declaration { + kind: SyntaxKind.Identifier; + /** + * Prefer to use `id.unescapedText`. (Note: This is available only in services, not internally to the TypeScript compiler.) + * Text of identifier, but if the identifier begins with two underscores, this will begin with three. + */ + escapedText: __String; + originalKeywordKind?: SyntaxKind; + isInJSDocNamespace?: boolean; + } + interface TransientIdentifier extends Identifier { + resolvedSymbol: Symbol; + } + interface QualifiedName extends Node { + kind: SyntaxKind.QualifiedName; + left: EntityName; + right: Identifier; + } + type EntityName = Identifier | QualifiedName; + type PropertyName = Identifier | StringLiteral | NumericLiteral | ComputedPropertyName; + type DeclarationName = Identifier | StringLiteralLike | NumericLiteral | ComputedPropertyName | BindingPattern; + interface Declaration extends Node { + _declarationBrand: any; + } + interface NamedDeclaration extends Declaration { + name?: DeclarationName; + } + interface DeclarationStatement extends NamedDeclaration, Statement { + name?: Identifier | StringLiteral | NumericLiteral; + } + interface ComputedPropertyName extends Node { + parent: Declaration; + kind: SyntaxKind.ComputedPropertyName; + expression: Expression; + } + interface Decorator extends Node { + kind: SyntaxKind.Decorator; + parent: NamedDeclaration; + expression: LeftHandSideExpression; + } + interface TypeParameterDeclaration extends NamedDeclaration { + kind: SyntaxKind.TypeParameter; + parent: DeclarationWithTypeParameterChildren | InferTypeNode; + name: Identifier; + /** Note: Consider calling `getEffectiveConstraintOfTypeParameter` */ + constraint?: TypeNode; + default?: TypeNode; + expression?: Expression; + } + interface SignatureDeclarationBase extends NamedDeclaration, JSDocContainer { + kind: SignatureDeclaration["kind"]; + name?: PropertyName; + typeParameters?: NodeArray; + parameters: NodeArray; + type?: TypeNode; + } + type SignatureDeclaration = CallSignatureDeclaration | ConstructSignatureDeclaration | MethodSignature | IndexSignatureDeclaration | FunctionTypeNode | ConstructorTypeNode | JSDocFunctionType | FunctionDeclaration | MethodDeclaration | ConstructorDeclaration | AccessorDeclaration | FunctionExpression | ArrowFunction; + interface CallSignatureDeclaration extends SignatureDeclarationBase, TypeElement { + kind: SyntaxKind.CallSignature; + } + interface ConstructSignatureDeclaration extends SignatureDeclarationBase, TypeElement { + kind: SyntaxKind.ConstructSignature; + } + type BindingName = Identifier | BindingPattern; + interface VariableDeclaration extends NamedDeclaration { + kind: SyntaxKind.VariableDeclaration; + parent: VariableDeclarationList | CatchClause; + name: BindingName; + exclamationToken?: ExclamationToken; + type?: TypeNode; + initializer?: Expression; + } + interface VariableDeclarationList extends Node { + kind: SyntaxKind.VariableDeclarationList; + parent: VariableStatement | ForStatement | ForOfStatement | ForInStatement; + declarations: NodeArray; + } + interface ParameterDeclaration extends NamedDeclaration, JSDocContainer { + kind: SyntaxKind.Parameter; + parent: SignatureDeclaration; + dotDotDotToken?: DotDotDotToken; + name: BindingName; + questionToken?: QuestionToken; + type?: TypeNode; + initializer?: Expression; + } + interface BindingElement extends NamedDeclaration { + kind: SyntaxKind.BindingElement; + parent: BindingPattern; + propertyName?: PropertyName; + dotDotDotToken?: DotDotDotToken; + name: BindingName; + initializer?: Expression; + } + interface PropertySignature extends TypeElement, JSDocContainer { + kind: SyntaxKind.PropertySignature; + name: PropertyName; + questionToken?: QuestionToken; + type?: TypeNode; + initializer?: Expression; + } + interface PropertyDeclaration extends ClassElement, JSDocContainer { + kind: SyntaxKind.PropertyDeclaration; + parent: ClassLikeDeclaration; + name: PropertyName; + questionToken?: QuestionToken; + exclamationToken?: ExclamationToken; + type?: TypeNode; + initializer?: Expression; + } + interface ObjectLiteralElement extends NamedDeclaration { + _objectLiteralBrandBrand: any; + name?: PropertyName; + } + /** Unlike ObjectLiteralElement, excludes JSXAttribute and JSXSpreadAttribute. */ + type ObjectLiteralElementLike = PropertyAssignment | ShorthandPropertyAssignment | SpreadAssignment | MethodDeclaration | AccessorDeclaration; + interface PropertyAssignment extends ObjectLiteralElement, JSDocContainer { + parent: ObjectLiteralExpression; + kind: SyntaxKind.PropertyAssignment; + name: PropertyName; + questionToken?: QuestionToken; + initializer: Expression; + } + interface ShorthandPropertyAssignment extends ObjectLiteralElement, JSDocContainer { + parent: ObjectLiteralExpression; + kind: SyntaxKind.ShorthandPropertyAssignment; + name: Identifier; + questionToken?: QuestionToken; + exclamationToken?: ExclamationToken; + equalsToken?: Token; + objectAssignmentInitializer?: Expression; + } + interface SpreadAssignment extends ObjectLiteralElement, JSDocContainer { + parent: ObjectLiteralExpression; + kind: SyntaxKind.SpreadAssignment; + expression: Expression; + } + type VariableLikeDeclaration = VariableDeclaration | ParameterDeclaration | BindingElement | PropertyDeclaration | PropertyAssignment | PropertySignature | JsxAttribute | ShorthandPropertyAssignment | EnumMember | JSDocPropertyTag | JSDocParameterTag; + interface PropertyLikeDeclaration extends NamedDeclaration { + name: PropertyName; + } + interface ObjectBindingPattern extends Node { + kind: SyntaxKind.ObjectBindingPattern; + parent: VariableDeclaration | ParameterDeclaration | BindingElement; + elements: NodeArray; + } + interface ArrayBindingPattern extends Node { + kind: SyntaxKind.ArrayBindingPattern; + parent: VariableDeclaration | ParameterDeclaration | BindingElement; + elements: NodeArray; + } + type BindingPattern = ObjectBindingPattern | ArrayBindingPattern; + type ArrayBindingElement = BindingElement | OmittedExpression; + /** + * Several node kinds share function-like features such as a signature, + * a name, and a body. These nodes should extend FunctionLikeDeclarationBase. + * Examples: + * - FunctionDeclaration + * - MethodDeclaration + * - AccessorDeclaration + */ + interface FunctionLikeDeclarationBase extends SignatureDeclarationBase { + _functionLikeDeclarationBrand: any; + asteriskToken?: AsteriskToken; + questionToken?: QuestionToken; + exclamationToken?: ExclamationToken; + body?: Block | Expression; + } + type FunctionLikeDeclaration = FunctionDeclaration | MethodDeclaration | GetAccessorDeclaration | SetAccessorDeclaration | ConstructorDeclaration | FunctionExpression | ArrowFunction; + /** @deprecated Use SignatureDeclaration */ + type FunctionLike = SignatureDeclaration; + interface FunctionDeclaration extends FunctionLikeDeclarationBase, DeclarationStatement { + kind: SyntaxKind.FunctionDeclaration; + name?: Identifier; + body?: FunctionBody; + } + interface MethodSignature extends SignatureDeclarationBase, TypeElement { + kind: SyntaxKind.MethodSignature; + parent: ObjectTypeDeclaration; + name: PropertyName; + } + interface MethodDeclaration extends FunctionLikeDeclarationBase, ClassElement, ObjectLiteralElement, JSDocContainer { + kind: SyntaxKind.MethodDeclaration; + parent: ClassLikeDeclaration | ObjectLiteralExpression; + name: PropertyName; + body?: FunctionBody; + } + interface ConstructorDeclaration extends FunctionLikeDeclarationBase, ClassElement, JSDocContainer { + kind: SyntaxKind.Constructor; + parent: ClassLikeDeclaration; + body?: FunctionBody; + } + /** For when we encounter a semicolon in a class declaration. ES6 allows these as class elements. */ + interface SemicolonClassElement extends ClassElement { + kind: SyntaxKind.SemicolonClassElement; + parent: ClassLikeDeclaration; + } + interface GetAccessorDeclaration extends FunctionLikeDeclarationBase, ClassElement, ObjectLiteralElement, JSDocContainer { + kind: SyntaxKind.GetAccessor; + parent: ClassLikeDeclaration | ObjectLiteralExpression; + name: PropertyName; + body?: FunctionBody; + } + interface SetAccessorDeclaration extends FunctionLikeDeclarationBase, ClassElement, ObjectLiteralElement, JSDocContainer { + kind: SyntaxKind.SetAccessor; + parent: ClassLikeDeclaration | ObjectLiteralExpression; + name: PropertyName; + body?: FunctionBody; + } + type AccessorDeclaration = GetAccessorDeclaration | SetAccessorDeclaration; + interface IndexSignatureDeclaration extends SignatureDeclarationBase, ClassElement, TypeElement { + kind: SyntaxKind.IndexSignature; + parent: ObjectTypeDeclaration; + } + interface TypeNode extends Node { + _typeNodeBrand: any; + } + interface KeywordTypeNode extends TypeNode { + kind: SyntaxKind.AnyKeyword | SyntaxKind.UnknownKeyword | SyntaxKind.NumberKeyword | SyntaxKind.BigIntKeyword | SyntaxKind.ObjectKeyword | SyntaxKind.BooleanKeyword | SyntaxKind.StringKeyword | SyntaxKind.SymbolKeyword | SyntaxKind.ThisKeyword | SyntaxKind.VoidKeyword | SyntaxKind.UndefinedKeyword | SyntaxKind.NullKeyword | SyntaxKind.NeverKeyword; + } + interface ImportTypeNode extends NodeWithTypeArguments { + kind: SyntaxKind.ImportType; + isTypeOf?: boolean; + argument: TypeNode; + qualifier?: EntityName; + } + interface ThisTypeNode extends TypeNode { + kind: SyntaxKind.ThisType; + } + type FunctionOrConstructorTypeNode = FunctionTypeNode | ConstructorTypeNode; + interface FunctionOrConstructorTypeNodeBase extends TypeNode, SignatureDeclarationBase { + kind: SyntaxKind.FunctionType | SyntaxKind.ConstructorType; + type: TypeNode; + } + interface FunctionTypeNode extends FunctionOrConstructorTypeNodeBase { + kind: SyntaxKind.FunctionType; + } + interface ConstructorTypeNode extends FunctionOrConstructorTypeNodeBase { + kind: SyntaxKind.ConstructorType; + } + interface NodeWithTypeArguments extends TypeNode { + typeArguments?: NodeArray; + } + type TypeReferenceType = TypeReferenceNode | ExpressionWithTypeArguments; + interface TypeReferenceNode extends NodeWithTypeArguments { + kind: SyntaxKind.TypeReference; + typeName: EntityName; + } + interface TypePredicateNode extends TypeNode { + kind: SyntaxKind.TypePredicate; + parent: SignatureDeclaration | JSDocTypeExpression; + parameterName: Identifier | ThisTypeNode; + type: TypeNode; + } + interface TypeQueryNode extends TypeNode { + kind: SyntaxKind.TypeQuery; + exprName: EntityName; + } + interface TypeLiteralNode extends TypeNode, Declaration { + kind: SyntaxKind.TypeLiteral; + members: NodeArray; + } + interface ArrayTypeNode extends TypeNode { + kind: SyntaxKind.ArrayType; + elementType: TypeNode; + } + interface TupleTypeNode extends TypeNode { + kind: SyntaxKind.TupleType; + elementTypes: NodeArray; + } + interface OptionalTypeNode extends TypeNode { + kind: SyntaxKind.OptionalType; + type: TypeNode; + } + interface RestTypeNode extends TypeNode { + kind: SyntaxKind.RestType; + type: TypeNode; + } + type UnionOrIntersectionTypeNode = UnionTypeNode | IntersectionTypeNode; + interface UnionTypeNode extends TypeNode { + kind: SyntaxKind.UnionType; + types: NodeArray; + } + interface IntersectionTypeNode extends TypeNode { + kind: SyntaxKind.IntersectionType; + types: NodeArray; + } + interface ConditionalTypeNode extends TypeNode { + kind: SyntaxKind.ConditionalType; + checkType: TypeNode; + extendsType: TypeNode; + trueType: TypeNode; + falseType: TypeNode; + } + interface InferTypeNode extends TypeNode { + kind: SyntaxKind.InferType; + typeParameter: TypeParameterDeclaration; + } + interface ParenthesizedTypeNode extends TypeNode { + kind: SyntaxKind.ParenthesizedType; + type: TypeNode; + } + interface TypeOperatorNode extends TypeNode { + kind: SyntaxKind.TypeOperator; + operator: SyntaxKind.KeyOfKeyword | SyntaxKind.UniqueKeyword; + type: TypeNode; + } + interface IndexedAccessTypeNode extends TypeNode { + kind: SyntaxKind.IndexedAccessType; + objectType: TypeNode; + indexType: TypeNode; + } + interface MappedTypeNode extends TypeNode, Declaration { + kind: SyntaxKind.MappedType; + readonlyToken?: ReadonlyToken | PlusToken | MinusToken; + typeParameter: TypeParameterDeclaration; + questionToken?: QuestionToken | PlusToken | MinusToken; + type?: TypeNode; + } + interface LiteralTypeNode extends TypeNode { + kind: SyntaxKind.LiteralType; + literal: BooleanLiteral | LiteralExpression | PrefixUnaryExpression; + } + interface StringLiteral extends LiteralExpression { + kind: SyntaxKind.StringLiteral; + } + type StringLiteralLike = StringLiteral | NoSubstitutionTemplateLiteral; + interface Expression extends Node { + _expressionBrand: any; + } + interface OmittedExpression extends Expression { + kind: SyntaxKind.OmittedExpression; + } + interface PartiallyEmittedExpression extends LeftHandSideExpression { + kind: SyntaxKind.PartiallyEmittedExpression; + expression: Expression; + } + interface UnaryExpression extends Expression { + _unaryExpressionBrand: any; + } + /** Deprecated, please use UpdateExpression */ + type IncrementExpression = UpdateExpression; + interface UpdateExpression extends UnaryExpression { + _updateExpressionBrand: any; + } + type PrefixUnaryOperator = SyntaxKind.PlusPlusToken | SyntaxKind.MinusMinusToken | SyntaxKind.PlusToken | SyntaxKind.MinusToken | SyntaxKind.TildeToken | SyntaxKind.ExclamationToken; + interface PrefixUnaryExpression extends UpdateExpression { + kind: SyntaxKind.PrefixUnaryExpression; + operator: PrefixUnaryOperator; + operand: UnaryExpression; + } + type PostfixUnaryOperator = SyntaxKind.PlusPlusToken | SyntaxKind.MinusMinusToken; + interface PostfixUnaryExpression extends UpdateExpression { + kind: SyntaxKind.PostfixUnaryExpression; + operand: LeftHandSideExpression; + operator: PostfixUnaryOperator; + } + interface LeftHandSideExpression extends UpdateExpression { + _leftHandSideExpressionBrand: any; + } + interface MemberExpression extends LeftHandSideExpression { + _memberExpressionBrand: any; + } + interface PrimaryExpression extends MemberExpression { + _primaryExpressionBrand: any; + } + interface NullLiteral extends PrimaryExpression, TypeNode { + kind: SyntaxKind.NullKeyword; + } + interface BooleanLiteral extends PrimaryExpression, TypeNode { + kind: SyntaxKind.TrueKeyword | SyntaxKind.FalseKeyword; + } + interface ThisExpression extends PrimaryExpression, KeywordTypeNode { + kind: SyntaxKind.ThisKeyword; + } + interface SuperExpression extends PrimaryExpression { + kind: SyntaxKind.SuperKeyword; + } + interface ImportExpression extends PrimaryExpression { + kind: SyntaxKind.ImportKeyword; + } + interface DeleteExpression extends UnaryExpression { + kind: SyntaxKind.DeleteExpression; + expression: UnaryExpression; + } + interface TypeOfExpression extends UnaryExpression { + kind: SyntaxKind.TypeOfExpression; + expression: UnaryExpression; + } + interface VoidExpression extends UnaryExpression { + kind: SyntaxKind.VoidExpression; + expression: UnaryExpression; + } + interface AwaitExpression extends UnaryExpression { + kind: SyntaxKind.AwaitExpression; + expression: UnaryExpression; + } + interface YieldExpression extends Expression { + kind: SyntaxKind.YieldExpression; + asteriskToken?: AsteriskToken; + expression?: Expression; + } + interface SyntheticExpression extends Expression { + kind: SyntaxKind.SyntheticExpression; + isSpread: boolean; + type: Type; + } + type ExponentiationOperator = SyntaxKind.AsteriskAsteriskToken; + type MultiplicativeOperator = SyntaxKind.AsteriskToken | SyntaxKind.SlashToken | SyntaxKind.PercentToken; + type MultiplicativeOperatorOrHigher = ExponentiationOperator | MultiplicativeOperator; + type AdditiveOperator = SyntaxKind.PlusToken | SyntaxKind.MinusToken; + type AdditiveOperatorOrHigher = MultiplicativeOperatorOrHigher | AdditiveOperator; + type ShiftOperator = SyntaxKind.LessThanLessThanToken | SyntaxKind.GreaterThanGreaterThanToken | SyntaxKind.GreaterThanGreaterThanGreaterThanToken; + type ShiftOperatorOrHigher = AdditiveOperatorOrHigher | ShiftOperator; + type RelationalOperator = SyntaxKind.LessThanToken | SyntaxKind.LessThanEqualsToken | SyntaxKind.GreaterThanToken | SyntaxKind.GreaterThanEqualsToken | SyntaxKind.InstanceOfKeyword | SyntaxKind.InKeyword; + type RelationalOperatorOrHigher = ShiftOperatorOrHigher | RelationalOperator; + type EqualityOperator = SyntaxKind.EqualsEqualsToken | SyntaxKind.EqualsEqualsEqualsToken | SyntaxKind.ExclamationEqualsEqualsToken | SyntaxKind.ExclamationEqualsToken; + type EqualityOperatorOrHigher = RelationalOperatorOrHigher | EqualityOperator; + type BitwiseOperator = SyntaxKind.AmpersandToken | SyntaxKind.BarToken | SyntaxKind.CaretToken; + type BitwiseOperatorOrHigher = EqualityOperatorOrHigher | BitwiseOperator; + type LogicalOperator = SyntaxKind.AmpersandAmpersandToken | SyntaxKind.BarBarToken; + type LogicalOperatorOrHigher = BitwiseOperatorOrHigher | LogicalOperator; + type CompoundAssignmentOperator = SyntaxKind.PlusEqualsToken | SyntaxKind.MinusEqualsToken | SyntaxKind.AsteriskAsteriskEqualsToken | SyntaxKind.AsteriskEqualsToken | SyntaxKind.SlashEqualsToken | SyntaxKind.PercentEqualsToken | SyntaxKind.AmpersandEqualsToken | SyntaxKind.BarEqualsToken | SyntaxKind.CaretEqualsToken | SyntaxKind.LessThanLessThanEqualsToken | SyntaxKind.GreaterThanGreaterThanGreaterThanEqualsToken | SyntaxKind.GreaterThanGreaterThanEqualsToken; + type AssignmentOperator = SyntaxKind.EqualsToken | CompoundAssignmentOperator; + type AssignmentOperatorOrHigher = LogicalOperatorOrHigher | AssignmentOperator; + type BinaryOperator = AssignmentOperatorOrHigher | SyntaxKind.CommaToken; + type BinaryOperatorToken = Token; + interface BinaryExpression extends Expression, Declaration { + kind: SyntaxKind.BinaryExpression; + left: Expression; + operatorToken: BinaryOperatorToken; + right: Expression; + } + type AssignmentOperatorToken = Token; + interface AssignmentExpression extends BinaryExpression { + left: LeftHandSideExpression; + operatorToken: TOperator; + } + interface ObjectDestructuringAssignment extends AssignmentExpression { + left: ObjectLiteralExpression; + } + interface ArrayDestructuringAssignment extends AssignmentExpression { + left: ArrayLiteralExpression; + } + type DestructuringAssignment = ObjectDestructuringAssignment | ArrayDestructuringAssignment; + type BindingOrAssignmentElement = VariableDeclaration | ParameterDeclaration | BindingElement | PropertyAssignment | ShorthandPropertyAssignment | SpreadAssignment | OmittedExpression | SpreadElement | ArrayLiteralExpression | ObjectLiteralExpression | AssignmentExpression | Identifier | PropertyAccessExpression | ElementAccessExpression; + type BindingOrAssignmentElementRestIndicator = DotDotDotToken | SpreadElement | SpreadAssignment; + type BindingOrAssignmentElementTarget = BindingOrAssignmentPattern | Identifier | PropertyAccessExpression | ElementAccessExpression | OmittedExpression; + type ObjectBindingOrAssignmentPattern = ObjectBindingPattern | ObjectLiteralExpression; + type ArrayBindingOrAssignmentPattern = ArrayBindingPattern | ArrayLiteralExpression; + type AssignmentPattern = ObjectLiteralExpression | ArrayLiteralExpression; + type BindingOrAssignmentPattern = ObjectBindingOrAssignmentPattern | ArrayBindingOrAssignmentPattern; + interface ConditionalExpression extends Expression { + kind: SyntaxKind.ConditionalExpression; + condition: Expression; + questionToken: QuestionToken; + whenTrue: Expression; + colonToken: ColonToken; + whenFalse: Expression; + } + type FunctionBody = Block; + type ConciseBody = FunctionBody | Expression; + interface FunctionExpression extends PrimaryExpression, FunctionLikeDeclarationBase, JSDocContainer { + kind: SyntaxKind.FunctionExpression; + name?: Identifier; + body: FunctionBody; + } + interface ArrowFunction extends Expression, FunctionLikeDeclarationBase, JSDocContainer { + kind: SyntaxKind.ArrowFunction; + equalsGreaterThanToken: EqualsGreaterThanToken; + body: ConciseBody; + name: never; + } + interface LiteralLikeNode extends Node { + text: string; + isUnterminated?: boolean; + hasExtendedUnicodeEscape?: boolean; + } + interface LiteralExpression extends LiteralLikeNode, PrimaryExpression { + _literalExpressionBrand: any; + } + interface RegularExpressionLiteral extends LiteralExpression { + kind: SyntaxKind.RegularExpressionLiteral; + } + interface NoSubstitutionTemplateLiteral extends LiteralExpression { + kind: SyntaxKind.NoSubstitutionTemplateLiteral; + } + interface NumericLiteral extends LiteralExpression { + kind: SyntaxKind.NumericLiteral; + } + interface BigIntLiteral extends LiteralExpression { + kind: SyntaxKind.BigIntLiteral; + } + interface TemplateHead extends LiteralLikeNode { + kind: SyntaxKind.TemplateHead; + parent: TemplateExpression; + } + interface TemplateMiddle extends LiteralLikeNode { + kind: SyntaxKind.TemplateMiddle; + parent: TemplateSpan; + } + interface TemplateTail extends LiteralLikeNode { + kind: SyntaxKind.TemplateTail; + parent: TemplateSpan; + } + type TemplateLiteral = TemplateExpression | NoSubstitutionTemplateLiteral; + interface TemplateExpression extends PrimaryExpression { + kind: SyntaxKind.TemplateExpression; + head: TemplateHead; + templateSpans: NodeArray; + } + interface TemplateSpan extends Node { + kind: SyntaxKind.TemplateSpan; + parent: TemplateExpression; + expression: Expression; + literal: TemplateMiddle | TemplateTail; + } + interface ParenthesizedExpression extends PrimaryExpression, JSDocContainer { + kind: SyntaxKind.ParenthesizedExpression; + expression: Expression; + } + interface ArrayLiteralExpression extends PrimaryExpression { + kind: SyntaxKind.ArrayLiteralExpression; + elements: NodeArray; + } + interface SpreadElement extends Expression { + kind: SyntaxKind.SpreadElement; + parent: ArrayLiteralExpression | CallExpression | NewExpression; + expression: Expression; + } + /** + * This interface is a base interface for ObjectLiteralExpression and JSXAttributes to extend from. JSXAttributes is similar to + * ObjectLiteralExpression in that it contains array of properties; however, JSXAttributes' properties can only be + * JSXAttribute or JSXSpreadAttribute. ObjectLiteralExpression, on the other hand, can only have properties of type + * ObjectLiteralElement (e.g. PropertyAssignment, ShorthandPropertyAssignment etc.) + */ + interface ObjectLiteralExpressionBase extends PrimaryExpression, Declaration { + properties: NodeArray; + } + interface ObjectLiteralExpression extends ObjectLiteralExpressionBase { + kind: SyntaxKind.ObjectLiteralExpression; + } + type EntityNameExpression = Identifier | PropertyAccessEntityNameExpression; + type EntityNameOrEntityNameExpression = EntityName | EntityNameExpression; + interface PropertyAccessExpression extends MemberExpression, NamedDeclaration { + kind: SyntaxKind.PropertyAccessExpression; + expression: LeftHandSideExpression; + name: Identifier; + } + interface SuperPropertyAccessExpression extends PropertyAccessExpression { + expression: SuperExpression; + } + /** Brand for a PropertyAccessExpression which, like a QualifiedName, consists of a sequence of identifiers separated by dots. */ + interface PropertyAccessEntityNameExpression extends PropertyAccessExpression { + _propertyAccessExpressionLikeQualifiedNameBrand?: any; + expression: EntityNameExpression; + } + interface ElementAccessExpression extends MemberExpression { + kind: SyntaxKind.ElementAccessExpression; + expression: LeftHandSideExpression; + argumentExpression: Expression; + } + interface SuperElementAccessExpression extends ElementAccessExpression { + expression: SuperExpression; + } + type SuperProperty = SuperPropertyAccessExpression | SuperElementAccessExpression; + interface CallExpression extends LeftHandSideExpression, Declaration { + kind: SyntaxKind.CallExpression; + expression: LeftHandSideExpression; + typeArguments?: NodeArray; + arguments: NodeArray; + } + interface SuperCall extends CallExpression { + expression: SuperExpression; + } + interface ImportCall extends CallExpression { + expression: ImportExpression; + } + interface ExpressionWithTypeArguments extends NodeWithTypeArguments { + kind: SyntaxKind.ExpressionWithTypeArguments; + parent: HeritageClause | JSDocAugmentsTag; + expression: LeftHandSideExpression; + } + interface NewExpression extends PrimaryExpression, Declaration { + kind: SyntaxKind.NewExpression; + expression: LeftHandSideExpression; + typeArguments?: NodeArray; + arguments?: NodeArray; + } + interface TaggedTemplateExpression extends MemberExpression { + kind: SyntaxKind.TaggedTemplateExpression; + tag: LeftHandSideExpression; + typeArguments?: NodeArray; + template: TemplateLiteral; + } + type CallLikeExpression = CallExpression | NewExpression | TaggedTemplateExpression | Decorator | JsxOpeningLikeElement; + interface AsExpression extends Expression { + kind: SyntaxKind.AsExpression; + expression: Expression; + type: TypeNode; + } + interface TypeAssertion extends UnaryExpression { + kind: SyntaxKind.TypeAssertionExpression; + type: TypeNode; + expression: UnaryExpression; + } + type AssertionExpression = TypeAssertion | AsExpression; + interface NonNullExpression extends LeftHandSideExpression { + kind: SyntaxKind.NonNullExpression; + expression: Expression; + } + interface MetaProperty extends PrimaryExpression { + kind: SyntaxKind.MetaProperty; + keywordToken: SyntaxKind.NewKeyword | SyntaxKind.ImportKeyword; + name: Identifier; + } + interface JsxElement extends PrimaryExpression { + kind: SyntaxKind.JsxElement; + openingElement: JsxOpeningElement; + children: NodeArray; + closingElement: JsxClosingElement; + } + type JsxOpeningLikeElement = JsxSelfClosingElement | JsxOpeningElement; + type JsxAttributeLike = JsxAttribute | JsxSpreadAttribute; + type JsxTagNameExpression = Identifier | ThisExpression | JsxTagNamePropertyAccess; + interface JsxTagNamePropertyAccess extends PropertyAccessExpression { + expression: JsxTagNameExpression; + } + interface JsxAttributes extends ObjectLiteralExpressionBase { + parent: JsxOpeningLikeElement; + } + interface JsxOpeningElement extends Expression { + kind: SyntaxKind.JsxOpeningElement; + parent: JsxElement; + tagName: JsxTagNameExpression; + typeArguments?: NodeArray; + attributes: JsxAttributes; + } + interface JsxSelfClosingElement extends PrimaryExpression { + kind: SyntaxKind.JsxSelfClosingElement; + tagName: JsxTagNameExpression; + typeArguments?: NodeArray; + attributes: JsxAttributes; + } + interface JsxFragment extends PrimaryExpression { + kind: SyntaxKind.JsxFragment; + openingFragment: JsxOpeningFragment; + children: NodeArray; + closingFragment: JsxClosingFragment; + } + interface JsxOpeningFragment extends Expression { + kind: SyntaxKind.JsxOpeningFragment; + parent: JsxFragment; + } + interface JsxClosingFragment extends Expression { + kind: SyntaxKind.JsxClosingFragment; + parent: JsxFragment; + } + interface JsxAttribute extends ObjectLiteralElement { + kind: SyntaxKind.JsxAttribute; + parent: JsxAttributes; + name: Identifier; + initializer?: StringLiteral | JsxExpression; + } + interface JsxSpreadAttribute extends ObjectLiteralElement { + kind: SyntaxKind.JsxSpreadAttribute; + parent: JsxAttributes; + expression: Expression; + } + interface JsxClosingElement extends Node { + kind: SyntaxKind.JsxClosingElement; + parent: JsxElement; + tagName: JsxTagNameExpression; + } + interface JsxExpression extends Expression { + kind: SyntaxKind.JsxExpression; + parent: JsxElement | JsxAttributeLike; + dotDotDotToken?: Token; + expression?: Expression; + } + interface JsxText extends Node { + kind: SyntaxKind.JsxText; + containsOnlyWhiteSpaces: boolean; + parent: JsxElement; + } + type JsxChild = JsxText | JsxExpression | JsxElement | JsxSelfClosingElement | JsxFragment; + interface Statement extends Node { + _statementBrand: any; + } + interface NotEmittedStatement extends Statement { + kind: SyntaxKind.NotEmittedStatement; + } + /** + * A list of comma-separated expressions. This node is only created by transformations. + */ + interface CommaListExpression extends Expression { + kind: SyntaxKind.CommaListExpression; + elements: NodeArray; + } + interface EmptyStatement extends Statement { + kind: SyntaxKind.EmptyStatement; + } + interface DebuggerStatement extends Statement { + kind: SyntaxKind.DebuggerStatement; + } + interface MissingDeclaration extends DeclarationStatement { + kind: SyntaxKind.MissingDeclaration; + name?: Identifier; + } + type BlockLike = SourceFile | Block | ModuleBlock | CaseOrDefaultClause; + interface Block extends Statement { + kind: SyntaxKind.Block; + statements: NodeArray; + } + interface VariableStatement extends Statement, JSDocContainer { + kind: SyntaxKind.VariableStatement; + declarationList: VariableDeclarationList; + } + interface ExpressionStatement extends Statement, JSDocContainer { + kind: SyntaxKind.ExpressionStatement; + expression: Expression; + } + interface IfStatement extends Statement { + kind: SyntaxKind.IfStatement; + expression: Expression; + thenStatement: Statement; + elseStatement?: Statement; + } + interface IterationStatement extends Statement { + statement: Statement; + } + interface DoStatement extends IterationStatement { + kind: SyntaxKind.DoStatement; + expression: Expression; + } + interface WhileStatement extends IterationStatement { + kind: SyntaxKind.WhileStatement; + expression: Expression; + } + type ForInitializer = VariableDeclarationList | Expression; + interface ForStatement extends IterationStatement { + kind: SyntaxKind.ForStatement; + initializer?: ForInitializer; + condition?: Expression; + incrementor?: Expression; + } + type ForInOrOfStatement = ForInStatement | ForOfStatement; + interface ForInStatement extends IterationStatement { + kind: SyntaxKind.ForInStatement; + initializer: ForInitializer; + expression: Expression; + } + interface ForOfStatement extends IterationStatement { + kind: SyntaxKind.ForOfStatement; + awaitModifier?: AwaitKeywordToken; + initializer: ForInitializer; + expression: Expression; + } + interface BreakStatement extends Statement { + kind: SyntaxKind.BreakStatement; + label?: Identifier; + } + interface ContinueStatement extends Statement { + kind: SyntaxKind.ContinueStatement; + label?: Identifier; + } + type BreakOrContinueStatement = BreakStatement | ContinueStatement; + interface ReturnStatement extends Statement { + kind: SyntaxKind.ReturnStatement; + expression?: Expression; + } + interface WithStatement extends Statement { + kind: SyntaxKind.WithStatement; + expression: Expression; + statement: Statement; + } + interface SwitchStatement extends Statement { + kind: SyntaxKind.SwitchStatement; + expression: Expression; + caseBlock: CaseBlock; + possiblyExhaustive?: boolean; + } + interface CaseBlock extends Node { + kind: SyntaxKind.CaseBlock; + parent: SwitchStatement; + clauses: NodeArray; + } + interface CaseClause extends Node { + kind: SyntaxKind.CaseClause; + parent: CaseBlock; + expression: Expression; + statements: NodeArray; + } + interface DefaultClause extends Node { + kind: SyntaxKind.DefaultClause; + parent: CaseBlock; + statements: NodeArray; + } + type CaseOrDefaultClause = CaseClause | DefaultClause; + interface LabeledStatement extends Statement, JSDocContainer { + kind: SyntaxKind.LabeledStatement; + label: Identifier; + statement: Statement; + } + interface ThrowStatement extends Statement { + kind: SyntaxKind.ThrowStatement; + expression?: Expression; + } + interface TryStatement extends Statement { + kind: SyntaxKind.TryStatement; + tryBlock: Block; + catchClause?: CatchClause; + finallyBlock?: Block; + } + interface CatchClause extends Node { + kind: SyntaxKind.CatchClause; + parent: TryStatement; + variableDeclaration?: VariableDeclaration; + block: Block; + } + type ObjectTypeDeclaration = ClassLikeDeclaration | InterfaceDeclaration | TypeLiteralNode; + type DeclarationWithTypeParameters = DeclarationWithTypeParameterChildren | JSDocTypedefTag | JSDocCallbackTag | JSDocSignature; + type DeclarationWithTypeParameterChildren = SignatureDeclaration | ClassLikeDeclaration | InterfaceDeclaration | TypeAliasDeclaration | JSDocTemplateTag; + interface ClassLikeDeclarationBase extends NamedDeclaration, JSDocContainer { + kind: SyntaxKind.ClassDeclaration | SyntaxKind.ClassExpression; + name?: Identifier; + typeParameters?: NodeArray; + heritageClauses?: NodeArray; + members: NodeArray; + } + interface ClassDeclaration extends ClassLikeDeclarationBase, DeclarationStatement { + kind: SyntaxKind.ClassDeclaration; + /** May be undefined in `export default class { ... }`. */ + name?: Identifier; + } + interface ClassExpression extends ClassLikeDeclarationBase, PrimaryExpression { + kind: SyntaxKind.ClassExpression; + } + type ClassLikeDeclaration = ClassDeclaration | ClassExpression; + interface ClassElement extends NamedDeclaration { + _classElementBrand: any; + name?: PropertyName; + } + interface TypeElement extends NamedDeclaration { + _typeElementBrand: any; + name?: PropertyName; + questionToken?: QuestionToken; + } + interface InterfaceDeclaration extends DeclarationStatement, JSDocContainer { + kind: SyntaxKind.InterfaceDeclaration; + name: Identifier; + typeParameters?: NodeArray; + heritageClauses?: NodeArray; + members: NodeArray; + } + interface HeritageClause extends Node { + kind: SyntaxKind.HeritageClause; + parent: InterfaceDeclaration | ClassLikeDeclaration; + token: SyntaxKind.ExtendsKeyword | SyntaxKind.ImplementsKeyword; + types: NodeArray; + } + interface TypeAliasDeclaration extends DeclarationStatement, JSDocContainer { + kind: SyntaxKind.TypeAliasDeclaration; + name: Identifier; + typeParameters?: NodeArray; + type: TypeNode; + } + interface EnumMember extends NamedDeclaration, JSDocContainer { + kind: SyntaxKind.EnumMember; + parent: EnumDeclaration; + name: PropertyName; + initializer?: Expression; + } + interface EnumDeclaration extends DeclarationStatement, JSDocContainer { + kind: SyntaxKind.EnumDeclaration; + name: Identifier; + members: NodeArray; + } + type ModuleName = Identifier | StringLiteral; + type ModuleBody = NamespaceBody | JSDocNamespaceBody; + interface ModuleDeclaration extends DeclarationStatement, JSDocContainer { + kind: SyntaxKind.ModuleDeclaration; + parent: ModuleBody | SourceFile; + name: ModuleName; + body?: ModuleBody | JSDocNamespaceDeclaration; + } + type NamespaceBody = ModuleBlock | NamespaceDeclaration; + interface NamespaceDeclaration extends ModuleDeclaration { + name: Identifier; + body: NamespaceBody; + } + type JSDocNamespaceBody = Identifier | JSDocNamespaceDeclaration; + interface JSDocNamespaceDeclaration extends ModuleDeclaration { + name: Identifier; + body?: JSDocNamespaceBody; + } + interface ModuleBlock extends Node, Statement { + kind: SyntaxKind.ModuleBlock; + parent: ModuleDeclaration; + statements: NodeArray; + } + type ModuleReference = EntityName | ExternalModuleReference; + /** + * One of: + * - import x = require("mod"); + * - import x = M.x; + */ + interface ImportEqualsDeclaration extends DeclarationStatement, JSDocContainer { + kind: SyntaxKind.ImportEqualsDeclaration; + parent: SourceFile | ModuleBlock; + name: Identifier; + moduleReference: ModuleReference; + } + interface ExternalModuleReference extends Node { + kind: SyntaxKind.ExternalModuleReference; + parent: ImportEqualsDeclaration; + expression: Expression; + } + interface ImportDeclaration extends Statement { + kind: SyntaxKind.ImportDeclaration; + parent: SourceFile | ModuleBlock; + importClause?: ImportClause; + /** If this is not a StringLiteral it will be a grammar error. */ + moduleSpecifier: Expression; + } + type NamedImportBindings = NamespaceImport | NamedImports; + interface ImportClause extends NamedDeclaration { + kind: SyntaxKind.ImportClause; + parent: ImportDeclaration; + name?: Identifier; + namedBindings?: NamedImportBindings; + } + interface NamespaceImport extends NamedDeclaration { + kind: SyntaxKind.NamespaceImport; + parent: ImportClause; + name: Identifier; + } + interface NamespaceExportDeclaration extends DeclarationStatement { + kind: SyntaxKind.NamespaceExportDeclaration; + name: Identifier; + } + interface ExportDeclaration extends DeclarationStatement, JSDocContainer { + kind: SyntaxKind.ExportDeclaration; + parent: SourceFile | ModuleBlock; + /** Will not be assigned in the case of `export * from "foo";` */ + exportClause?: NamedExports; + /** If this is not a StringLiteral it will be a grammar error. */ + moduleSpecifier?: Expression; + } + interface NamedImports extends Node { + kind: SyntaxKind.NamedImports; + parent: ImportClause; + elements: NodeArray; + } + interface NamedExports extends Node { + kind: SyntaxKind.NamedExports; + parent: ExportDeclaration; + elements: NodeArray; + } + type NamedImportsOrExports = NamedImports | NamedExports; + interface ImportSpecifier extends NamedDeclaration { + kind: SyntaxKind.ImportSpecifier; + parent: NamedImports; + propertyName?: Identifier; + name: Identifier; + } + interface ExportSpecifier extends NamedDeclaration { + kind: SyntaxKind.ExportSpecifier; + parent: NamedExports; + propertyName?: Identifier; + name: Identifier; + } + type ImportOrExportSpecifier = ImportSpecifier | ExportSpecifier; + /** + * This is either an `export =` or an `export default` declaration. + * Unless `isExportEquals` is set, this node was parsed as an `export default`. + */ + interface ExportAssignment extends DeclarationStatement { + kind: SyntaxKind.ExportAssignment; + parent: SourceFile; + isExportEquals?: boolean; + expression: Expression; + } + interface FileReference extends TextRange { + fileName: string; + } + interface CheckJsDirective extends TextRange { + enabled: boolean; + } + type CommentKind = SyntaxKind.SingleLineCommentTrivia | SyntaxKind.MultiLineCommentTrivia; + interface CommentRange extends TextRange { + hasTrailingNewLine?: boolean; + kind: CommentKind; + } + interface SynthesizedComment extends CommentRange { + text: string; + pos: -1; + end: -1; + } + interface JSDocTypeExpression extends TypeNode { + kind: SyntaxKind.JSDocTypeExpression; + type: TypeNode; + } + interface JSDocType extends TypeNode { + _jsDocTypeBrand: any; + } + interface JSDocAllType extends JSDocType { + kind: SyntaxKind.JSDocAllType; + } + interface JSDocUnknownType extends JSDocType { + kind: SyntaxKind.JSDocUnknownType; + } + interface JSDocNonNullableType extends JSDocType { + kind: SyntaxKind.JSDocNonNullableType; + type: TypeNode; + } + interface JSDocNullableType extends JSDocType { + kind: SyntaxKind.JSDocNullableType; + type: TypeNode; + } + interface JSDocOptionalType extends JSDocType { + kind: SyntaxKind.JSDocOptionalType; + type: TypeNode; + } + interface JSDocFunctionType extends JSDocType, SignatureDeclarationBase { + kind: SyntaxKind.JSDocFunctionType; + } + interface JSDocVariadicType extends JSDocType { + kind: SyntaxKind.JSDocVariadicType; + type: TypeNode; + } + type JSDocTypeReferencingNode = JSDocVariadicType | JSDocOptionalType | JSDocNullableType | JSDocNonNullableType; + interface JSDoc extends Node { + kind: SyntaxKind.JSDocComment; + parent: HasJSDoc; + tags?: NodeArray; + comment?: string; + } + interface JSDocTag extends Node { + parent: JSDoc | JSDocTypeLiteral; + tagName: Identifier; + comment?: string; + } + interface JSDocUnknownTag extends JSDocTag { + kind: SyntaxKind.JSDocTag; + } + /** + * Note that `@extends` is a synonym of `@augments`. + * Both tags are represented by this interface. + */ + interface JSDocAugmentsTag extends JSDocTag { + kind: SyntaxKind.JSDocAugmentsTag; + class: ExpressionWithTypeArguments & { + expression: Identifier | PropertyAccessEntityNameExpression; + }; + } + interface JSDocClassTag extends JSDocTag { + kind: SyntaxKind.JSDocClassTag; + } + interface JSDocEnumTag extends JSDocTag { + kind: SyntaxKind.JSDocEnumTag; + typeExpression?: JSDocTypeExpression; + } + interface JSDocThisTag extends JSDocTag { + kind: SyntaxKind.JSDocThisTag; + typeExpression?: JSDocTypeExpression; + } + interface JSDocTemplateTag extends JSDocTag { + kind: SyntaxKind.JSDocTemplateTag; + constraint: JSDocTypeExpression | undefined; + typeParameters: NodeArray; + } + interface JSDocReturnTag extends JSDocTag { + kind: SyntaxKind.JSDocReturnTag; + typeExpression?: JSDocTypeExpression; + } + interface JSDocTypeTag extends JSDocTag { + kind: SyntaxKind.JSDocTypeTag; + typeExpression?: JSDocTypeExpression; + } + interface JSDocTypedefTag extends JSDocTag, NamedDeclaration { + parent: JSDoc; + kind: SyntaxKind.JSDocTypedefTag; + fullName?: JSDocNamespaceDeclaration | Identifier; + name?: Identifier; + typeExpression?: JSDocTypeExpression | JSDocTypeLiteral; + } + interface JSDocCallbackTag extends JSDocTag, NamedDeclaration { + parent: JSDoc; + kind: SyntaxKind.JSDocCallbackTag; + fullName?: JSDocNamespaceDeclaration | Identifier; + name?: Identifier; + typeExpression: JSDocSignature; + } + interface JSDocSignature extends JSDocType, Declaration { + kind: SyntaxKind.JSDocSignature; + typeParameters?: ReadonlyArray; + parameters: ReadonlyArray; + type: JSDocReturnTag | undefined; + } + interface JSDocPropertyLikeTag extends JSDocTag, Declaration { + parent: JSDoc; + name: EntityName; + typeExpression?: JSDocTypeExpression; + /** Whether the property name came before the type -- non-standard for JSDoc, but Typescript-like */ + isNameFirst: boolean; + isBracketed: boolean; + } + interface JSDocPropertyTag extends JSDocPropertyLikeTag { + kind: SyntaxKind.JSDocPropertyTag; + } + interface JSDocParameterTag extends JSDocPropertyLikeTag { + kind: SyntaxKind.JSDocParameterTag; + } + interface JSDocTypeLiteral extends JSDocType { + kind: SyntaxKind.JSDocTypeLiteral; + jsDocPropertyTags?: ReadonlyArray; + /** If true, then this type literal represents an *array* of its type. */ + isArrayType?: boolean; + } + enum FlowFlags { + Unreachable = 1, + Start = 2, + BranchLabel = 4, + LoopLabel = 8, + Assignment = 16, + TrueCondition = 32, + FalseCondition = 64, + SwitchClause = 128, + ArrayMutation = 256, + Referenced = 512, + Shared = 1024, + PreFinally = 2048, + AfterFinally = 4096, + Label = 12, + Condition = 96 + } + interface FlowLock { + locked?: boolean; + } + interface AfterFinallyFlow extends FlowNodeBase, FlowLock { + antecedent: FlowNode; + } + interface PreFinallyFlow extends FlowNodeBase { + antecedent: FlowNode; + lock: FlowLock; + } + type FlowNode = AfterFinallyFlow | PreFinallyFlow | FlowStart | FlowLabel | FlowAssignment | FlowCondition | FlowSwitchClause | FlowArrayMutation; + interface FlowNodeBase { + flags: FlowFlags; + id?: number; + } + interface FlowStart extends FlowNodeBase { + container?: FunctionExpression | ArrowFunction | MethodDeclaration; + } + interface FlowLabel extends FlowNodeBase { + antecedents: FlowNode[] | undefined; + } + interface FlowAssignment extends FlowNodeBase { + node: Expression | VariableDeclaration | BindingElement; + antecedent: FlowNode; + } + interface FlowCondition extends FlowNodeBase { + expression: Expression; + antecedent: FlowNode; + } + interface FlowSwitchClause extends FlowNodeBase { + switchStatement: SwitchStatement; + clauseStart: number; + clauseEnd: number; + antecedent: FlowNode; + } + interface FlowArrayMutation extends FlowNodeBase { + node: CallExpression | BinaryExpression; + antecedent: FlowNode; + } + type FlowType = Type | IncompleteType; + interface IncompleteType { + flags: TypeFlags; + type: Type; + } + interface AmdDependency { + path: string; + name?: string; + } + interface SourceFile extends Declaration { + kind: SyntaxKind.SourceFile; + statements: NodeArray; + endOfFileToken: Token; + fileName: string; + text: string; + amdDependencies: ReadonlyArray; + moduleName?: string; + referencedFiles: ReadonlyArray; + typeReferenceDirectives: ReadonlyArray; + libReferenceDirectives: ReadonlyArray; + languageVariant: LanguageVariant; + isDeclarationFile: boolean; + /** + * lib.d.ts should have a reference comment like + * + * /// + * + * If any other file has this comment, it signals not to include lib.d.ts + * because this containing file is intended to act as a default library. + */ + hasNoDefaultLib: boolean; + languageVersion: ScriptTarget; + } + interface Bundle extends Node { + kind: SyntaxKind.Bundle; + prepends: ReadonlyArray; + sourceFiles: ReadonlyArray; + } + interface InputFiles extends Node { + kind: SyntaxKind.InputFiles; + javascriptText: string; + javascriptMapPath?: string; + javascriptMapText?: string; + declarationText: string; + declarationMapPath?: string; + declarationMapText?: string; + } + interface UnparsedSource extends Node { + kind: SyntaxKind.UnparsedSource; + text: string; + sourceMapPath?: string; + sourceMapText?: string; + } + interface JsonSourceFile extends SourceFile { + statements: NodeArray; + } + interface TsConfigSourceFile extends JsonSourceFile { + extendedSourceFiles?: string[]; + } + interface JsonMinusNumericLiteral extends PrefixUnaryExpression { + kind: SyntaxKind.PrefixUnaryExpression; + operator: SyntaxKind.MinusToken; + operand: NumericLiteral; + } + interface JsonObjectExpressionStatement extends ExpressionStatement { + expression: ObjectLiteralExpression | ArrayLiteralExpression | JsonMinusNumericLiteral | NumericLiteral | StringLiteral | BooleanLiteral | NullLiteral; + } + interface ScriptReferenceHost { + getCompilerOptions(): CompilerOptions; + getSourceFile(fileName: string): SourceFile | undefined; + getSourceFileByPath(path: Path): SourceFile | undefined; + getCurrentDirectory(): string; + } + interface ParseConfigHost { + useCaseSensitiveFileNames: boolean; + readDirectory(rootDir: string, extensions: ReadonlyArray, excludes: ReadonlyArray | undefined, includes: ReadonlyArray, depth?: number): ReadonlyArray; + /** + * Gets a value indicating whether the specified path exists and is a file. + * @param path The path to test. + */ + fileExists(path: string): boolean; + readFile(path: string): string | undefined; + trace?(s: string): void; + } + /** + * Branded string for keeping track of when we've turned an ambiguous path + * specified like "./blah" to an absolute path to an actual + * tsconfig file, e.g. "/root/blah/tsconfig.json" + */ + type ResolvedConfigFileName = string & { + _isResolvedConfigFileName: never; + }; + type WriteFileCallback = (fileName: string, data: string, writeByteOrderMark: boolean, onError: ((message: string) => void) | undefined, sourceFiles?: ReadonlyArray) => void; + class OperationCanceledException { + } + interface CancellationToken { + isCancellationRequested(): boolean; + /** @throws OperationCanceledException if isCancellationRequested is true */ + throwIfCancellationRequested(): void; + } + interface Program extends ScriptReferenceHost { + /** + * Get a list of root file names that were passed to a 'createProgram' + */ + getRootFileNames(): ReadonlyArray; + /** + * Get a list of files in the program + */ + getSourceFiles(): ReadonlyArray; + /** + * Emits the JavaScript and declaration files. If targetSourceFile is not specified, then + * the JavaScript and declaration files will be produced for all the files in this program. + * If targetSourceFile is specified, then only the JavaScript and declaration for that + * specific file will be generated. + * + * If writeFile is not specified then the writeFile callback from the compiler host will be + * used for writing the JavaScript and declaration files. Otherwise, the writeFile parameter + * will be invoked when writing the JavaScript and declaration files. + */ + emit(targetSourceFile?: SourceFile, writeFile?: WriteFileCallback, cancellationToken?: CancellationToken, emitOnlyDtsFiles?: boolean, customTransformers?: CustomTransformers): EmitResult; + getOptionsDiagnostics(cancellationToken?: CancellationToken): ReadonlyArray; + getGlobalDiagnostics(cancellationToken?: CancellationToken): ReadonlyArray; + getSyntacticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray; + /** The first time this is called, it will return global diagnostics (no location). */ + getSemanticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray; + getDeclarationDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray; + getConfigFileParsingDiagnostics(): ReadonlyArray; + /** + * Gets a type checker that can be used to semantically analyze source files in the program. + */ + getTypeChecker(): TypeChecker; + isSourceFileFromExternalLibrary(file: SourceFile): boolean; + isSourceFileDefaultLibrary(file: SourceFile): boolean; + getProjectReferences(): ReadonlyArray | undefined; + getResolvedProjectReferences(): ReadonlyArray | undefined; + } + interface ResolvedProjectReference { + commandLine: ParsedCommandLine; + sourceFile: SourceFile; + references?: ReadonlyArray; + } + interface CustomTransformers { + /** Custom transformers to evaluate before built-in .js transformations. */ + before?: TransformerFactory[]; + /** Custom transformers to evaluate after built-in .js transformations. */ + after?: TransformerFactory[]; + /** Custom transformers to evaluate after built-in .d.ts transformations. */ + afterDeclarations?: TransformerFactory[]; + } + interface SourceMapSpan { + /** Line number in the .js file. */ + emittedLine: number; + /** Column number in the .js file. */ + emittedColumn: number; + /** Line number in the .ts file. */ + sourceLine: number; + /** Column number in the .ts file. */ + sourceColumn: number; + /** Optional name (index into names array) associated with this span. */ + nameIndex?: number; + /** .ts file (index into sources array) associated with this span */ + sourceIndex: number; + } + /** Return code used by getEmitOutput function to indicate status of the function */ + enum ExitStatus { + Success = 0, + DiagnosticsPresent_OutputsSkipped = 1, + DiagnosticsPresent_OutputsGenerated = 2 + } + interface EmitResult { + emitSkipped: boolean; + /** Contains declaration emit diagnostics */ + diagnostics: ReadonlyArray; + emittedFiles?: string[]; + } + interface TypeChecker { + getTypeOfSymbolAtLocation(symbol: Symbol, node: Node): Type; + getDeclaredTypeOfSymbol(symbol: Symbol): Type; + getPropertiesOfType(type: Type): Symbol[]; + getPropertyOfType(type: Type, propertyName: string): Symbol | undefined; + getIndexInfoOfType(type: Type, kind: IndexKind): IndexInfo | undefined; + getSignaturesOfType(type: Type, kind: SignatureKind): ReadonlyArray; + getIndexTypeOfType(type: Type, kind: IndexKind): Type | undefined; + getBaseTypes(type: InterfaceType): BaseType[]; + getBaseTypeOfLiteralType(type: Type): Type; + getWidenedType(type: Type): Type; + getReturnTypeOfSignature(signature: Signature): Type; + getNullableType(type: Type, flags: TypeFlags): Type; + getNonNullableType(type: Type): Type; + /** Note that the resulting nodes cannot be checked. */ + typeToTypeNode(type: Type, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): TypeNode | undefined; + /** Note that the resulting nodes cannot be checked. */ + signatureToSignatureDeclaration(signature: Signature, kind: SyntaxKind, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): (SignatureDeclaration & { + typeArguments?: NodeArray; + }) | undefined; + /** Note that the resulting nodes cannot be checked. */ + indexInfoToIndexSignatureDeclaration(indexInfo: IndexInfo, kind: IndexKind, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): IndexSignatureDeclaration | undefined; + /** Note that the resulting nodes cannot be checked. */ + symbolToEntityName(symbol: Symbol, meaning: SymbolFlags, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): EntityName | undefined; + /** Note that the resulting nodes cannot be checked. */ + symbolToExpression(symbol: Symbol, meaning: SymbolFlags, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): Expression | undefined; + /** Note that the resulting nodes cannot be checked. */ + symbolToTypeParameterDeclarations(symbol: Symbol, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): NodeArray | undefined; + /** Note that the resulting nodes cannot be checked. */ + symbolToParameterDeclaration(symbol: Symbol, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): ParameterDeclaration | undefined; + /** Note that the resulting nodes cannot be checked. */ + typeParameterToDeclaration(parameter: TypeParameter, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): TypeParameterDeclaration | undefined; + getSymbolsInScope(location: Node, meaning: SymbolFlags): Symbol[]; + getSymbolAtLocation(node: Node): Symbol | undefined; + getSymbolsOfParameterPropertyDeclaration(parameter: ParameterDeclaration, parameterName: string): Symbol[]; + /** + * The function returns the value (local variable) symbol of an identifier in the short-hand property assignment. + * This is necessary as an identifier in short-hand property assignment can contains two meaning: property name and property value. + */ + getShorthandAssignmentValueSymbol(location: Node): Symbol | undefined; + getExportSpecifierLocalTargetSymbol(location: ExportSpecifier): Symbol | undefined; + /** + * If a symbol is a local symbol with an associated exported symbol, returns the exported symbol. + * Otherwise returns its input. + * For example, at `export type T = number;`: + * - `getSymbolAtLocation` at the location `T` will return the exported symbol for `T`. + * - But the result of `getSymbolsInScope` will contain the *local* symbol for `T`, not the exported symbol. + * - Calling `getExportSymbolOfSymbol` on that local symbol will return the exported symbol. + */ + getExportSymbolOfSymbol(symbol: Symbol): Symbol; + getPropertySymbolOfDestructuringAssignment(location: Identifier): Symbol | undefined; + getTypeAtLocation(node: Node): Type; + getTypeFromTypeNode(node: TypeNode): Type; + signatureToString(signature: Signature, enclosingDeclaration?: Node, flags?: TypeFormatFlags, kind?: SignatureKind): string; + typeToString(type: Type, enclosingDeclaration?: Node, flags?: TypeFormatFlags): string; + symbolToString(symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags, flags?: SymbolFormatFlags): string; + typePredicateToString(predicate: TypePredicate, enclosingDeclaration?: Node, flags?: TypeFormatFlags): string; + getFullyQualifiedName(symbol: Symbol): string; + getAugmentedPropertiesOfType(type: Type): Symbol[]; + getRootSymbols(symbol: Symbol): ReadonlyArray; + getContextualType(node: Expression): Type | undefined; + /** + * returns unknownSignature in the case of an error. + * returns undefined if the node is not valid. + * @param argumentCount Apparent number of arguments, passed in case of a possibly incomplete call. This should come from an ArgumentListInfo. See `signatureHelp.ts`. + */ + getResolvedSignature(node: CallLikeExpression, candidatesOutArray?: Signature[], argumentCount?: number): Signature | undefined; + getSignatureFromDeclaration(declaration: SignatureDeclaration): Signature | undefined; + isImplementationOfOverload(node: SignatureDeclaration): boolean | undefined; + isUndefinedSymbol(symbol: Symbol): boolean; + isArgumentsSymbol(symbol: Symbol): boolean; + isUnknownSymbol(symbol: Symbol): boolean; + getConstantValue(node: EnumMember | PropertyAccessExpression | ElementAccessExpression): string | number | undefined; + isValidPropertyAccess(node: PropertyAccessExpression | QualifiedName | ImportTypeNode, propertyName: string): boolean; + /** Follow all aliases to get the original symbol. */ + getAliasedSymbol(symbol: Symbol): Symbol; + getExportsOfModule(moduleSymbol: Symbol): Symbol[]; + getJsxIntrinsicTagNamesAt(location: Node): Symbol[]; + isOptionalParameter(node: ParameterDeclaration): boolean; + getAmbientModules(): Symbol[]; + tryGetMemberInModuleExports(memberName: string, moduleSymbol: Symbol): Symbol | undefined; + getApparentType(type: Type): Type; + getBaseConstraintOfType(type: Type): Type | undefined; + getDefaultFromTypeParameter(type: Type): Type | undefined; + /** + * Depending on the operation performed, it may be appropriate to throw away the checker + * if the cancellation token is triggered. Typically, if it is used for error checking + * and the operation is cancelled, then it should be discarded, otherwise it is safe to keep. + */ + runWithCancellationToken(token: CancellationToken, cb: (checker: TypeChecker) => T): T; + } + enum NodeBuilderFlags { + None = 0, + NoTruncation = 1, + WriteArrayAsGenericType = 2, + GenerateNamesForShadowedTypeParams = 4, + UseStructuralFallback = 8, + ForbidIndexedAccessSymbolReferences = 16, + WriteTypeArgumentsOfSignature = 32, + UseFullyQualifiedType = 64, + UseOnlyExternalAliasing = 128, + SuppressAnyReturnType = 256, + WriteTypeParametersInQualifiedName = 512, + MultilineObjectLiterals = 1024, + WriteClassExpressionAsTypeLiteral = 2048, + UseTypeOfFunction = 4096, + OmitParameterModifiers = 8192, + UseAliasDefinedOutsideCurrentScope = 16384, + AllowThisInObjectLiteral = 32768, + AllowQualifedNameInPlaceOfIdentifier = 65536, + AllowAnonymousIdentifier = 131072, + AllowEmptyUnionOrIntersection = 262144, + AllowEmptyTuple = 524288, + AllowUniqueESSymbolType = 1048576, + AllowEmptyIndexInfoType = 2097152, + AllowNodeModulesRelativePaths = 67108864, + IgnoreErrors = 70221824, + InObjectTypeLiteral = 4194304, + InTypeAlias = 8388608, + InInitialEntityName = 16777216, + InReverseMappedType = 33554432 + } + enum TypeFormatFlags { + None = 0, + NoTruncation = 1, + WriteArrayAsGenericType = 2, + UseStructuralFallback = 8, + WriteTypeArgumentsOfSignature = 32, + UseFullyQualifiedType = 64, + SuppressAnyReturnType = 256, + MultilineObjectLiterals = 1024, + WriteClassExpressionAsTypeLiteral = 2048, + UseTypeOfFunction = 4096, + OmitParameterModifiers = 8192, + UseAliasDefinedOutsideCurrentScope = 16384, + AllowUniqueESSymbolType = 1048576, + AddUndefined = 131072, + WriteArrowStyleSignature = 262144, + InArrayType = 524288, + InElementType = 2097152, + InFirstTypeArgument = 4194304, + InTypeAlias = 8388608, + /** @deprecated */ WriteOwnNameForAnyLike = 0, + NodeBuilderFlagsMask = 9469291 + } + enum SymbolFormatFlags { + None = 0, + WriteTypeParametersOrArguments = 1, + UseOnlyExternalAliasing = 2, + AllowAnyNodeKind = 4, + UseAliasDefinedOutsideCurrentScope = 8 + } + enum TypePredicateKind { + This = 0, + Identifier = 1 + } + interface TypePredicateBase { + kind: TypePredicateKind; + type: Type; + } + interface ThisTypePredicate extends TypePredicateBase { + kind: TypePredicateKind.This; + } + interface IdentifierTypePredicate extends TypePredicateBase { + kind: TypePredicateKind.Identifier; + parameterName: string; + parameterIndex: number; + } + type TypePredicate = IdentifierTypePredicate | ThisTypePredicate; + enum SymbolFlags { + None = 0, + FunctionScopedVariable = 1, + BlockScopedVariable = 2, + Property = 4, + EnumMember = 8, + Function = 16, + Class = 32, + Interface = 64, + ConstEnum = 128, + RegularEnum = 256, + ValueModule = 512, + NamespaceModule = 1024, + TypeLiteral = 2048, + ObjectLiteral = 4096, + Method = 8192, + Constructor = 16384, + GetAccessor = 32768, + SetAccessor = 65536, + Signature = 131072, + TypeParameter = 262144, + TypeAlias = 524288, + ExportValue = 1048576, + Alias = 2097152, + Prototype = 4194304, + ExportStar = 8388608, + Optional = 16777216, + Transient = 33554432, + Assignment = 67108864, + ModuleExports = 134217728, + Enum = 384, + Variable = 3, + Value = 67220415, + Type = 67897832, + Namespace = 1920, + Module = 1536, + Accessor = 98304, + FunctionScopedVariableExcludes = 67220414, + BlockScopedVariableExcludes = 67220415, + ParameterExcludes = 67220415, + PropertyExcludes = 0, + EnumMemberExcludes = 68008959, + FunctionExcludes = 67219887, + ClassExcludes = 68008383, + InterfaceExcludes = 67897736, + RegularEnumExcludes = 68008191, + ConstEnumExcludes = 68008831, + ValueModuleExcludes = 110735, + NamespaceModuleExcludes = 0, + MethodExcludes = 67212223, + GetAccessorExcludes = 67154879, + SetAccessorExcludes = 67187647, + TypeParameterExcludes = 67635688, + TypeAliasExcludes = 67897832, + AliasExcludes = 2097152, + ModuleMember = 2623475, + ExportHasLocal = 944, + BlockScoped = 418, + PropertyOrAccessor = 98308, + ClassMember = 106500 + } + interface Symbol { + flags: SymbolFlags; + escapedName: __String; + declarations: Declaration[]; + valueDeclaration: Declaration; + members?: SymbolTable; + exports?: SymbolTable; + globalExports?: SymbolTable; + } + enum InternalSymbolName { + Call = "__call", + Constructor = "__constructor", + New = "__new", + Index = "__index", + ExportStar = "__export", + Global = "__global", + Missing = "__missing", + Type = "__type", + Object = "__object", + JSXAttributes = "__jsxAttributes", + Class = "__class", + Function = "__function", + Computed = "__computed", + Resolving = "__resolving__", + ExportEquals = "export=", + Default = "default", + This = "this" + } + /** + * This represents a string whose leading underscore have been escaped by adding extra leading underscores. + * The shape of this brand is rather unique compared to others we've used. + * Instead of just an intersection of a string and an object, it is that union-ed + * with an intersection of void and an object. This makes it wholly incompatible + * with a normal string (which is good, it cannot be misused on assignment or on usage), + * while still being comparable with a normal string via === (also good) and castable from a string. + */ + type __String = (string & { + __escapedIdentifier: void; + }) | (void & { + __escapedIdentifier: void; + }) | InternalSymbolName; + /** ReadonlyMap where keys are `__String`s. */ + interface ReadonlyUnderscoreEscapedMap { + get(key: __String): T | undefined; + has(key: __String): boolean; + forEach(action: (value: T, key: __String) => void): void; + readonly size: number; + keys(): Iterator<__String>; + values(): Iterator; + entries(): Iterator<[__String, T]>; + } + /** Map where keys are `__String`s. */ + interface UnderscoreEscapedMap extends ReadonlyUnderscoreEscapedMap { + set(key: __String, value: T): this; + delete(key: __String): boolean; + clear(): void; + } + /** SymbolTable based on ES6 Map interface. */ + type SymbolTable = UnderscoreEscapedMap; + enum TypeFlags { + Any = 1, + Unknown = 2, + String = 4, + Number = 8, + Boolean = 16, + Enum = 32, + BigInt = 64, + StringLiteral = 128, + NumberLiteral = 256, + BooleanLiteral = 512, + EnumLiteral = 1024, + BigIntLiteral = 2048, + ESSymbol = 4096, + UniqueESSymbol = 8192, + Void = 16384, + Undefined = 32768, + Null = 65536, + Never = 131072, + TypeParameter = 262144, + Object = 524288, + Union = 1048576, + Intersection = 2097152, + Index = 4194304, + IndexedAccess = 8388608, + Conditional = 16777216, + Substitution = 33554432, + NonPrimitive = 67108864, + Literal = 2944, + Unit = 109440, + StringOrNumberLiteral = 384, + PossiblyFalsy = 117724, + StringLike = 132, + NumberLike = 296, + BigIntLike = 2112, + BooleanLike = 528, + EnumLike = 1056, + ESSymbolLike = 12288, + VoidLike = 49152, + UnionOrIntersection = 3145728, + StructuredType = 3670016, + TypeVariable = 8650752, + InstantiableNonPrimitive = 58982400, + InstantiablePrimitive = 4194304, + Instantiable = 63176704, + StructuredOrInstantiable = 66846720, + Narrowable = 133970943, + NotUnionOrUnit = 67637251 + } + type DestructuringPattern = BindingPattern | ObjectLiteralExpression | ArrayLiteralExpression; + interface Type { + flags: TypeFlags; + symbol: Symbol; + pattern?: DestructuringPattern; + aliasSymbol?: Symbol; + aliasTypeArguments?: ReadonlyArray; + } + interface LiteralType extends Type { + value: string | number | PseudoBigInt; + freshType: LiteralType; + regularType: LiteralType; + } + interface UniqueESSymbolType extends Type { + symbol: Symbol; + } + interface StringLiteralType extends LiteralType { + value: string; + } + interface NumberLiteralType extends LiteralType { + value: number; + } + interface BigIntLiteralType extends LiteralType { + value: PseudoBigInt; + } + interface EnumType extends Type { + } + enum ObjectFlags { + Class = 1, + Interface = 2, + Reference = 4, + Tuple = 8, + Anonymous = 16, + Mapped = 32, + Instantiated = 64, + ObjectLiteral = 128, + EvolvingArray = 256, + ObjectLiteralPatternWithComputedProperties = 512, + ContainsSpread = 1024, + ReverseMapped = 2048, + JsxAttributes = 4096, + MarkerType = 8192, + JSLiteral = 16384, + FreshLiteral = 32768, + ClassOrInterface = 3 + } + interface ObjectType extends Type { + objectFlags: ObjectFlags; + } + /** Class and interface types (ObjectFlags.Class and ObjectFlags.Interface). */ + interface InterfaceType extends ObjectType { + typeParameters: TypeParameter[] | undefined; + outerTypeParameters: TypeParameter[] | undefined; + localTypeParameters: TypeParameter[] | undefined; + thisType: TypeParameter | undefined; + } + type BaseType = ObjectType | IntersectionType; + interface InterfaceTypeWithDeclaredMembers extends InterfaceType { + declaredProperties: Symbol[]; + declaredCallSignatures: Signature[]; + declaredConstructSignatures: Signature[]; + declaredStringIndexInfo?: IndexInfo; + declaredNumberIndexInfo?: IndexInfo; + } + /** + * Type references (ObjectFlags.Reference). When a class or interface has type parameters or + * a "this" type, references to the class or interface are made using type references. The + * typeArguments property specifies the types to substitute for the type parameters of the + * class or interface and optionally includes an extra element that specifies the type to + * substitute for "this" in the resulting instantiation. When no extra argument is present, + * the type reference itself is substituted for "this". The typeArguments property is undefined + * if the class or interface has no type parameters and the reference isn't specifying an + * explicit "this" argument. + */ + interface TypeReference extends ObjectType { + target: GenericType; + typeArguments?: ReadonlyArray; + } + interface GenericType extends InterfaceType, TypeReference { + } + interface TupleType extends GenericType { + minLength: number; + hasRestElement: boolean; + associatedNames?: __String[]; + } + interface TupleTypeReference extends TypeReference { + target: TupleType; + } + interface UnionOrIntersectionType extends Type { + types: Type[]; + } + interface UnionType extends UnionOrIntersectionType { + } + interface IntersectionType extends UnionOrIntersectionType { + } + type StructuredType = ObjectType | UnionType | IntersectionType; + interface EvolvingArrayType extends ObjectType { + elementType: Type; + finalArrayType?: Type; + } + interface InstantiableType extends Type { + } + interface TypeParameter extends InstantiableType { + } + interface IndexedAccessType extends InstantiableType { + objectType: Type; + indexType: Type; + constraint?: Type; + simplified?: Type; + } + type TypeVariable = TypeParameter | IndexedAccessType; + interface IndexType extends InstantiableType { + type: InstantiableType | UnionOrIntersectionType; + } + interface ConditionalRoot { + node: ConditionalTypeNode; + checkType: Type; + extendsType: Type; + trueType: Type; + falseType: Type; + isDistributive: boolean; + inferTypeParameters?: TypeParameter[]; + outerTypeParameters?: TypeParameter[]; + instantiations?: Map; + aliasSymbol?: Symbol; + aliasTypeArguments?: Type[]; + } + interface ConditionalType extends InstantiableType { + root: ConditionalRoot; + checkType: Type; + extendsType: Type; + resolvedTrueType?: Type; + resolvedFalseType?: Type; + } + interface SubstitutionType extends InstantiableType { + typeVariable: TypeVariable; + substitute: Type; + } + enum SignatureKind { + Call = 0, + Construct = 1 + } + interface Signature { + declaration?: SignatureDeclaration | JSDocSignature; + typeParameters?: ReadonlyArray; + parameters: ReadonlyArray; + } + enum IndexKind { + String = 0, + Number = 1 + } + interface IndexInfo { + type: Type; + isReadonly: boolean; + declaration?: IndexSignatureDeclaration; + } + enum InferencePriority { + NakedTypeVariable = 1, + HomomorphicMappedType = 2, + MappedTypeConstraint = 4, + ReturnType = 8, + LiteralKeyof = 16, + NoConstraints = 32, + AlwaysStrict = 64, + PriorityImpliesCombination = 28 + } + /** @deprecated Use FileExtensionInfo instead. */ + type JsFileExtensionInfo = FileExtensionInfo; + interface FileExtensionInfo { + extension: string; + isMixedContent: boolean; + scriptKind?: ScriptKind; + } + interface DiagnosticMessage { + key: string; + category: DiagnosticCategory; + code: number; + message: string; + reportsUnnecessary?: {}; + } + /** + * A linked list of formatted diagnostic messages to be used as part of a multiline message. + * It is built from the bottom up, leaving the head to be the "main" diagnostic. + * While it seems that DiagnosticMessageChain is structurally similar to DiagnosticMessage, + * the difference is that messages are all preformatted in DMC. + */ + interface DiagnosticMessageChain { + messageText: string; + category: DiagnosticCategory; + code: number; + next?: DiagnosticMessageChain; + } + interface Diagnostic extends DiagnosticRelatedInformation { + /** May store more in future. For now, this will simply be `true` to indicate when a diagnostic is an unused-identifier diagnostic. */ + reportsUnnecessary?: {}; + source?: string; + relatedInformation?: DiagnosticRelatedInformation[]; + } + interface DiagnosticRelatedInformation { + category: DiagnosticCategory; + code: number; + file: SourceFile | undefined; + start: number | undefined; + length: number | undefined; + messageText: string | DiagnosticMessageChain; + } + interface DiagnosticWithLocation extends Diagnostic { + file: SourceFile; + start: number; + length: number; + } + enum DiagnosticCategory { + Warning = 0, + Error = 1, + Suggestion = 2, + Message = 3 + } + enum ModuleResolutionKind { + Classic = 1, + NodeJs = 2 + } + interface PluginImport { + name: string; + } + interface ProjectReference { + /** A normalized path on disk */ + path: string; + /** The path as the user originally wrote it */ + originalPath?: string; + /** True if the output of this reference should be prepended to the output of this project. Only valid for --outFile compilations */ + prepend?: boolean; + /** True if it is intended that this reference form a circularity */ + circular?: boolean; + } + type CompilerOptionsValue = string | number | boolean | (string | number)[] | string[] | MapLike | PluginImport[] | ProjectReference[] | null | undefined; + interface CompilerOptions { + allowJs?: boolean; + allowSyntheticDefaultImports?: boolean; + allowUnreachableCode?: boolean; + allowUnusedLabels?: boolean; + alwaysStrict?: boolean; + baseUrl?: string; + charset?: string; + checkJs?: boolean; + declaration?: boolean; + declarationMap?: boolean; + emitDeclarationOnly?: boolean; + declarationDir?: string; + disableSizeLimit?: boolean; + downlevelIteration?: boolean; + emitBOM?: boolean; + emitDecoratorMetadata?: boolean; + experimentalDecorators?: boolean; + forceConsistentCasingInFileNames?: boolean; + importHelpers?: boolean; + inlineSourceMap?: boolean; + inlineSources?: boolean; + isolatedModules?: boolean; + jsx?: JsxEmit; + keyofStringsOnly?: boolean; + lib?: string[]; + locale?: string; + mapRoot?: string; + maxNodeModuleJsDepth?: number; + module?: ModuleKind; + moduleResolution?: ModuleResolutionKind; + newLine?: NewLineKind; + noEmit?: boolean; + noEmitHelpers?: boolean; + noEmitOnError?: boolean; + noErrorTruncation?: boolean; + noFallthroughCasesInSwitch?: boolean; + noImplicitAny?: boolean; + noImplicitReturns?: boolean; + noImplicitThis?: boolean; + noStrictGenericChecks?: boolean; + noUnusedLocals?: boolean; + noUnusedParameters?: boolean; + noImplicitUseStrict?: boolean; + noLib?: boolean; + noResolve?: boolean; + out?: string; + outDir?: string; + outFile?: string; + paths?: MapLike; + preserveConstEnums?: boolean; + preserveSymlinks?: boolean; + project?: string; + reactNamespace?: string; + jsxFactory?: string; + composite?: boolean; + removeComments?: boolean; + rootDir?: string; + rootDirs?: string[]; + skipLibCheck?: boolean; + skipDefaultLibCheck?: boolean; + sourceMap?: boolean; + sourceRoot?: string; + strict?: boolean; + strictFunctionTypes?: boolean; + strictBindCallApply?: boolean; + strictNullChecks?: boolean; + strictPropertyInitialization?: boolean; + stripInternal?: boolean; + suppressExcessPropertyErrors?: boolean; + suppressImplicitAnyIndexErrors?: boolean; + target?: ScriptTarget; + traceResolution?: boolean; + resolveJsonModule?: boolean; + types?: string[]; + /** Paths used to compute primary types search locations */ + typeRoots?: string[]; + esModuleInterop?: boolean; + [option: string]: CompilerOptionsValue | TsConfigSourceFile | undefined; + } + interface TypeAcquisition { + enableAutoDiscovery?: boolean; + enable?: boolean; + include?: string[]; + exclude?: string[]; + [option: string]: string[] | boolean | undefined; + } + enum ModuleKind { + None = 0, + CommonJS = 1, + AMD = 2, + UMD = 3, + System = 4, + ES2015 = 5, + ESNext = 6 + } + enum JsxEmit { + None = 0, + Preserve = 1, + React = 2, + ReactNative = 3 + } + enum NewLineKind { + CarriageReturnLineFeed = 0, + LineFeed = 1 + } + interface LineAndCharacter { + /** 0-based. */ + line: number; + character: number; + } + enum ScriptKind { + Unknown = 0, + JS = 1, + JSX = 2, + TS = 3, + TSX = 4, + External = 5, + JSON = 6, + /** + * Used on extensions that doesn't define the ScriptKind but the content defines it. + * Deferred extensions are going to be included in all project contexts. + */ + Deferred = 7 + } + enum ScriptTarget { + ES3 = 0, + ES5 = 1, + ES2015 = 2, + ES2016 = 3, + ES2017 = 4, + ES2018 = 5, + ESNext = 6, + JSON = 100, + Latest = 6 + } + enum LanguageVariant { + Standard = 0, + JSX = 1 + } + /** Either a parsed command line or a parsed tsconfig.json */ + interface ParsedCommandLine { + options: CompilerOptions; + typeAcquisition?: TypeAcquisition; + fileNames: string[]; + projectReferences?: ReadonlyArray; + raw?: any; + errors: Diagnostic[]; + wildcardDirectories?: MapLike; + compileOnSave?: boolean; + } + enum WatchDirectoryFlags { + None = 0, + Recursive = 1 + } + interface ExpandResult { + fileNames: string[]; + wildcardDirectories: MapLike; + } + interface CreateProgramOptions { + rootNames: ReadonlyArray; + options: CompilerOptions; + projectReferences?: ReadonlyArray; + host?: CompilerHost; + oldProgram?: Program; + configFileParsingDiagnostics?: ReadonlyArray; + } + interface ModuleResolutionHost { + fileExists(fileName: string): boolean; + readFile(fileName: string): string | undefined; + trace?(s: string): void; + directoryExists?(directoryName: string): boolean; + /** + * Resolve a symbolic link. + * @see https://nodejs.org/api/fs.html#fs_fs_realpathsync_path_options + */ + realpath?(path: string): string; + getCurrentDirectory?(): string; + getDirectories?(path: string): string[]; + } + /** + * Represents the result of module resolution. + * Module resolution will pick up tsx/jsx/js files even if '--jsx' and '--allowJs' are turned off. + * The Program will then filter results based on these flags. + * + * Prefer to return a `ResolvedModuleFull` so that the file type does not have to be inferred. + */ + interface ResolvedModule { + /** Path of the file the module was resolved to. */ + resolvedFileName: string; + /** True if `resolvedFileName` comes from `node_modules`. */ + isExternalLibraryImport?: boolean; + } + /** + * ResolvedModule with an explicitly provided `extension` property. + * Prefer this over `ResolvedModule`. + * If changing this, remember to change `moduleResolutionIsEqualTo`. + */ + interface ResolvedModuleFull extends ResolvedModule { + /** + * Extension of resolvedFileName. This must match what's at the end of resolvedFileName. + * This is optional for backwards-compatibility, but will be added if not provided. + */ + extension: Extension; + packageId?: PackageId; + } + /** + * Unique identifier with a package name and version. + * If changing this, remember to change `packageIdIsEqual`. + */ + interface PackageId { + /** + * Name of the package. + * Should not include `@types`. + * If accessing a non-index file, this should include its name e.g. "foo/bar". + */ + name: string; + /** + * Name of a submodule within this package. + * May be "". + */ + subModuleName: string; + /** Version of the package, e.g. "1.2.3" */ + version: string; + } + enum Extension { + Ts = ".ts", + Tsx = ".tsx", + Dts = ".d.ts", + Js = ".js", + Jsx = ".jsx", + Json = ".json" + } + interface ResolvedModuleWithFailedLookupLocations { + readonly resolvedModule: ResolvedModuleFull | undefined; + } + interface ResolvedTypeReferenceDirective { + primary: boolean; + resolvedFileName: string | undefined; + packageId?: PackageId; + /** True if `resolvedFileName` comes from `node_modules`. */ + isExternalLibraryImport?: boolean; + } + interface ResolvedTypeReferenceDirectiveWithFailedLookupLocations { + readonly resolvedTypeReferenceDirective: ResolvedTypeReferenceDirective | undefined; + readonly failedLookupLocations: ReadonlyArray; + } + interface CompilerHost extends ModuleResolutionHost { + getSourceFile(fileName: string, languageVersion: ScriptTarget, onError?: (message: string) => void, shouldCreateNewSourceFile?: boolean): SourceFile | undefined; + getSourceFileByPath?(fileName: string, path: Path, languageVersion: ScriptTarget, onError?: (message: string) => void, shouldCreateNewSourceFile?: boolean): SourceFile | undefined; + getCancellationToken?(): CancellationToken; + getDefaultLibFileName(options: CompilerOptions): string; + getDefaultLibLocation?(): string; + writeFile: WriteFileCallback; + getCurrentDirectory(): string; + getDirectories(path: string): string[]; + getCanonicalFileName(fileName: string): string; + useCaseSensitiveFileNames(): boolean; + getNewLine(): string; + readDirectory?(rootDir: string, extensions: ReadonlyArray, excludes: ReadonlyArray | undefined, includes: ReadonlyArray, depth?: number): string[]; + resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[], redirectedReference?: ResolvedProjectReference): (ResolvedModule | undefined)[]; + /** + * This method is a companion for 'resolveModuleNames' and is used to resolve 'types' references to actual type declaration files + */ + resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string, redirectedReference?: ResolvedProjectReference): (ResolvedTypeReferenceDirective | undefined)[]; + getEnvironmentVariable?(name: string): string | undefined; + createHash?(data: string): string; + } + interface SourceMapRange extends TextRange { + source?: SourceMapSource; + } + interface SourceMapSource { + fileName: string; + text: string; + skipTrivia?: (pos: number) => number; + } + enum EmitFlags { + None = 0, + SingleLine = 1, + AdviseOnEmitNode = 2, + NoSubstitution = 4, + CapturesThis = 8, + NoLeadingSourceMap = 16, + NoTrailingSourceMap = 32, + NoSourceMap = 48, + NoNestedSourceMaps = 64, + NoTokenLeadingSourceMaps = 128, + NoTokenTrailingSourceMaps = 256, + NoTokenSourceMaps = 384, + NoLeadingComments = 512, + NoTrailingComments = 1024, + NoComments = 1536, + NoNestedComments = 2048, + HelperName = 4096, + ExportName = 8192, + LocalName = 16384, + InternalName = 32768, + Indented = 65536, + NoIndentation = 131072, + AsyncFunctionBody = 262144, + ReuseTempVariableScope = 524288, + CustomPrologue = 1048576, + NoHoisting = 2097152, + HasEndOfDeclarationMarker = 4194304, + Iterator = 8388608, + NoAsciiEscaping = 16777216 + } + interface EmitHelper { + readonly name: string; + readonly scoped: boolean; + readonly text: string | ((node: EmitHelperUniqueNameCallback) => string); + readonly priority?: number; + } + type EmitHelperUniqueNameCallback = (name: string) => string; + enum EmitHint { + SourceFile = 0, + Expression = 1, + IdentifierName = 2, + MappedTypeParameter = 3, + Unspecified = 4, + EmbeddedStatement = 5 + } + interface TransformationContext { + /** Gets the compiler options supplied to the transformer. */ + getCompilerOptions(): CompilerOptions; + /** Starts a new lexical environment. */ + startLexicalEnvironment(): void; + /** Suspends the current lexical environment, usually after visiting a parameter list. */ + suspendLexicalEnvironment(): void; + /** Resumes a suspended lexical environment, usually before visiting a function body. */ + resumeLexicalEnvironment(): void; + /** Ends a lexical environment, returning any declarations. */ + endLexicalEnvironment(): Statement[] | undefined; + /** Hoists a function declaration to the containing scope. */ + hoistFunctionDeclaration(node: FunctionDeclaration): void; + /** Hoists a variable declaration to the containing scope. */ + hoistVariableDeclaration(node: Identifier): void; + /** Records a request for a non-scoped emit helper in the current context. */ + requestEmitHelper(helper: EmitHelper): void; + /** Gets and resets the requested non-scoped emit helpers. */ + readEmitHelpers(): EmitHelper[] | undefined; + /** Enables expression substitutions in the pretty printer for the provided SyntaxKind. */ + enableSubstitution(kind: SyntaxKind): void; + /** Determines whether expression substitutions are enabled for the provided node. */ + isSubstitutionEnabled(node: Node): boolean; + /** + * Hook used by transformers to substitute expressions just before they + * are emitted by the pretty printer. + * + * NOTE: Transformation hooks should only be modified during `Transformer` initialization, + * before returning the `NodeTransformer` callback. + */ + onSubstituteNode: (hint: EmitHint, node: Node) => Node; + /** + * Enables before/after emit notifications in the pretty printer for the provided + * SyntaxKind. + */ + enableEmitNotification(kind: SyntaxKind): void; + /** + * Determines whether before/after emit notifications should be raised in the pretty + * printer when it emits a node. + */ + isEmitNotificationEnabled(node: Node): boolean; + /** + * Hook used to allow transformers to capture state before or after + * the printer emits a node. + * + * NOTE: Transformation hooks should only be modified during `Transformer` initialization, + * before returning the `NodeTransformer` callback. + */ + onEmitNode: (hint: EmitHint, node: Node, emitCallback: (hint: EmitHint, node: Node) => void) => void; + } + interface TransformationResult { + /** Gets the transformed source files. */ + transformed: T[]; + /** Gets diagnostics for the transformation. */ + diagnostics?: DiagnosticWithLocation[]; + /** + * Gets a substitute for a node, if one is available; otherwise, returns the original node. + * + * @param hint A hint as to the intended usage of the node. + * @param node The node to substitute. + */ + substituteNode(hint: EmitHint, node: Node): Node; + /** + * Emits a node with possible notification. + * + * @param hint A hint as to the intended usage of the node. + * @param node The node to emit. + * @param emitCallback A callback used to emit the node. + */ + emitNodeWithNotification(hint: EmitHint, node: Node, emitCallback: (hint: EmitHint, node: Node) => void): void; + /** + * Clean up EmitNode entries on any parse-tree nodes. + */ + dispose(): void; + } + /** + * A function that is used to initialize and return a `Transformer` callback, which in turn + * will be used to transform one or more nodes. + */ + type TransformerFactory = (context: TransformationContext) => Transformer; + /** + * A function that transforms a node. + */ + type Transformer = (node: T) => T; + /** + * A function that accepts and possibly transforms a node. + */ + type Visitor = (node: Node) => VisitResult; + type VisitResult = T | T[] | undefined; + interface Printer { + /** + * Print a node and its subtree as-is, without any emit transformations. + * @param hint A value indicating the purpose of a node. This is primarily used to + * distinguish between an `Identifier` used in an expression position, versus an + * `Identifier` used as an `IdentifierName` as part of a declaration. For most nodes you + * should just pass `Unspecified`. + * @param node The node to print. The node and its subtree are printed as-is, without any + * emit transformations. + * @param sourceFile A source file that provides context for the node. The source text of + * the file is used to emit the original source content for literals and identifiers, while + * the identifiers of the source file are used when generating unique names to avoid + * collisions. + */ + printNode(hint: EmitHint, node: Node, sourceFile: SourceFile): string; + /** + * Prints a list of nodes using the given format flags + */ + printList(format: ListFormat, list: NodeArray, sourceFile: SourceFile): string; + /** + * Prints a source file as-is, without any emit transformations. + */ + printFile(sourceFile: SourceFile): string; + /** + * Prints a bundle of source files as-is, without any emit transformations. + */ + printBundle(bundle: Bundle): string; + } + interface PrintHandlers { + /** + * A hook used by the Printer when generating unique names to avoid collisions with + * globally defined names that exist outside of the current source file. + */ + hasGlobalName?(name: string): boolean; + /** + * A hook used by the Printer to provide notifications prior to emitting a node. A + * compatible implementation **must** invoke `emitCallback` with the provided `hint` and + * `node` values. + * @param hint A hint indicating the intended purpose of the node. + * @param node The node to emit. + * @param emitCallback A callback that, when invoked, will emit the node. + * @example + * ```ts + * var printer = createPrinter(printerOptions, { + * onEmitNode(hint, node, emitCallback) { + * // set up or track state prior to emitting the node... + * emitCallback(hint, node); + * // restore state after emitting the node... + * } + * }); + * ``` + */ + onEmitNode?(hint: EmitHint, node: Node | undefined, emitCallback: (hint: EmitHint, node: Node | undefined) => void): void; + /** + * A hook used by the Printer to perform just-in-time substitution of a node. This is + * primarily used by node transformations that need to substitute one node for another, + * such as replacing `myExportedVar` with `exports.myExportedVar`. + * @param hint A hint indicating the intended purpose of the node. + * @param node The node to emit. + * @example + * ```ts + * var printer = createPrinter(printerOptions, { + * substituteNode(hint, node) { + * // perform substitution if necessary... + * return node; + * } + * }); + * ``` + */ + substituteNode?(hint: EmitHint, node: Node): Node; + } + interface PrinterOptions { + removeComments?: boolean; + newLine?: NewLineKind; + omitTrailingSemicolon?: boolean; + noEmitHelpers?: boolean; + } + interface GetEffectiveTypeRootsHost { + directoryExists?(directoryName: string): boolean; + getCurrentDirectory?(): string; + } + interface TextSpan { + start: number; + length: number; + } + interface TextChangeRange { + span: TextSpan; + newLength: number; + } + interface SyntaxList extends Node { + _children: Node[]; + } + enum ListFormat { + None = 0, + SingleLine = 0, + MultiLine = 1, + PreserveLines = 2, + LinesMask = 3, + NotDelimited = 0, + BarDelimited = 4, + AmpersandDelimited = 8, + CommaDelimited = 16, + AsteriskDelimited = 32, + DelimitersMask = 60, + AllowTrailingComma = 64, + Indented = 128, + SpaceBetweenBraces = 256, + SpaceBetweenSiblings = 512, + Braces = 1024, + Parenthesis = 2048, + AngleBrackets = 4096, + SquareBrackets = 8192, + BracketsMask = 15360, + OptionalIfUndefined = 16384, + OptionalIfEmpty = 32768, + Optional = 49152, + PreferNewLine = 65536, + NoTrailingNewLine = 131072, + NoInterveningComments = 262144, + NoSpaceIfEmpty = 524288, + SingleElement = 1048576, + Modifiers = 262656, + HeritageClauses = 512, + SingleLineTypeLiteralMembers = 768, + MultiLineTypeLiteralMembers = 32897, + TupleTypeElements = 528, + UnionTypeConstituents = 516, + IntersectionTypeConstituents = 520, + ObjectBindingPatternElements = 525136, + ArrayBindingPatternElements = 524880, + ObjectLiteralExpressionProperties = 526226, + ArrayLiteralExpressionElements = 8914, + CommaListElements = 528, + CallExpressionArguments = 2576, + NewExpressionArguments = 18960, + TemplateExpressionSpans = 262144, + SingleLineBlockStatements = 768, + MultiLineBlockStatements = 129, + VariableDeclarationList = 528, + SingleLineFunctionBodyStatements = 768, + MultiLineFunctionBodyStatements = 1, + ClassHeritageClauses = 0, + ClassMembers = 129, + InterfaceMembers = 129, + EnumMembers = 145, + CaseBlockClauses = 129, + NamedImportsOrExportsElements = 525136, + JsxElementOrFragmentChildren = 262144, + JsxElementAttributes = 262656, + CaseOrDefaultClauseStatements = 163969, + HeritageClauseTypes = 528, + SourceFileStatements = 131073, + Decorators = 49153, + TypeArguments = 53776, + TypeParameters = 53776, + Parameters = 2576, + IndexSignatureParameters = 8848, + JSDocComment = 33 + } + interface UserPreferences { + readonly disableSuggestions?: boolean; + readonly quotePreference?: "double" | "single"; + readonly includeCompletionsForModuleExports?: boolean; + readonly includeCompletionsWithInsertText?: boolean; + readonly importModuleSpecifierPreference?: "relative" | "non-relative"; + /** Determines whether we import `foo/index.ts` as "foo", "foo/index", or "foo/index.js" */ + readonly importModuleSpecifierEnding?: "minimal" | "index" | "js"; + readonly allowTextChangesInNewFiles?: boolean; + } + /** Represents a bigint literal value without requiring bigint support */ + interface PseudoBigInt { + negative: boolean; + base10Value: string; + } +} +declare function setTimeout(handler: (...args: any[]) => void, timeout: number): any; +declare function clearTimeout(handle: any): void; +declare namespace ts { + enum FileWatcherEventKind { + Created = 0, + Changed = 1, + Deleted = 2 + } + type FileWatcherCallback = (fileName: string, eventKind: FileWatcherEventKind) => void; + type DirectoryWatcherCallback = (fileName: string) => void; + interface System { + args: string[]; + newLine: string; + useCaseSensitiveFileNames: boolean; + write(s: string): void; + writeOutputIsTTY?(): boolean; + readFile(path: string, encoding?: string): string | undefined; + getFileSize?(path: string): number; + writeFile(path: string, data: string, writeByteOrderMark?: boolean): void; + /** + * @pollingInterval - this parameter is used in polling-based watchers and ignored in watchers that + * use native OS file watching + */ + watchFile?(path: string, callback: FileWatcherCallback, pollingInterval?: number): FileWatcher; + watchDirectory?(path: string, callback: DirectoryWatcherCallback, recursive?: boolean): FileWatcher; + resolvePath(path: string): string; + fileExists(path: string): boolean; + directoryExists(path: string): boolean; + createDirectory(path: string): void; + getExecutingFilePath(): string; + getCurrentDirectory(): string; + getDirectories(path: string): string[]; + readDirectory(path: string, extensions?: ReadonlyArray, exclude?: ReadonlyArray, include?: ReadonlyArray, depth?: number): string[]; + getModifiedTime?(path: string): Date | undefined; + setModifiedTime?(path: string, time: Date): void; + deleteFile?(path: string): void; + /** + * A good implementation is node.js' `crypto.createHash`. (https://nodejs.org/api/crypto.html#crypto_crypto_createhash_algorithm) + */ + createHash?(data: string): string; + /** This must be cryptographically secure. Only implement this method using `crypto.createHash("sha256")`. */ + createSHA256Hash?(data: string): string; + getMemoryUsage?(): number; + exit(exitCode?: number): void; + realpath?(path: string): string; + setTimeout?(callback: (...args: any[]) => void, ms: number, ...args: any[]): any; + clearTimeout?(timeoutId: any): void; + clearScreen?(): void; + base64decode?(input: string): string; + base64encode?(input: string): string; + } + interface FileWatcher { + close(): void; + } + function getNodeMajorVersion(): number | undefined; + let sys: System; +} +declare namespace ts { + type ErrorCallback = (message: DiagnosticMessage, length: number) => void; + interface Scanner { + getStartPos(): number; + getToken(): SyntaxKind; + getTextPos(): number; + getTokenPos(): number; + getTokenText(): string; + getTokenValue(): string; + hasExtendedUnicodeEscape(): boolean; + hasPrecedingLineBreak(): boolean; + isIdentifier(): boolean; + isReservedWord(): boolean; + isUnterminated(): boolean; + reScanGreaterToken(): SyntaxKind; + reScanSlashToken(): SyntaxKind; + reScanTemplateToken(): SyntaxKind; + scanJsxIdentifier(): SyntaxKind; + scanJsxAttributeValue(): SyntaxKind; + reScanJsxToken(): JsxTokenSyntaxKind; + scanJsxToken(): JsxTokenSyntaxKind; + scanJSDocToken(): JsDocSyntaxKind; + scan(): SyntaxKind; + getText(): string; + setText(text: string | undefined, start?: number, length?: number): void; + setOnError(onError: ErrorCallback | undefined): void; + setScriptTarget(scriptTarget: ScriptTarget): void; + setLanguageVariant(variant: LanguageVariant): void; + setTextPos(textPos: number): void; + lookAhead(callback: () => T): T; + scanRange(start: number, length: number, callback: () => T): T; + tryScan(callback: () => T): T; + } + function tokenToString(t: SyntaxKind): string | undefined; + function getPositionOfLineAndCharacter(sourceFile: SourceFileLike, line: number, character: number): number; + function getLineAndCharacterOfPosition(sourceFile: SourceFileLike, position: number): LineAndCharacter; + function isWhiteSpaceLike(ch: number): boolean; + /** Does not include line breaks. For that, see isWhiteSpaceLike. */ + function isWhiteSpaceSingleLine(ch: number): boolean; + function isLineBreak(ch: number): boolean; + function couldStartTrivia(text: string, pos: number): boolean; + function forEachLeadingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean) => U): U | undefined; + function forEachLeadingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T) => U, state: T): U | undefined; + function forEachTrailingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean) => U): U | undefined; + function forEachTrailingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T) => U, state: T): U | undefined; + function reduceEachLeadingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T, memo: U) => U, state: T, initial: U): U | undefined; + function reduceEachTrailingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T, memo: U) => U, state: T, initial: U): U | undefined; + function getLeadingCommentRanges(text: string, pos: number): CommentRange[] | undefined; + function getTrailingCommentRanges(text: string, pos: number): CommentRange[] | undefined; + /** Optionally, get the shebang */ + function getShebang(text: string): string | undefined; + function isIdentifierStart(ch: number, languageVersion: ScriptTarget | undefined): boolean; + function isIdentifierPart(ch: number, languageVersion: ScriptTarget | undefined): boolean; + function createScanner(languageVersion: ScriptTarget, skipTrivia: boolean, languageVariant?: LanguageVariant, textInitial?: string, onError?: ErrorCallback, start?: number, length?: number): Scanner; +} +declare namespace ts { + function isExternalModuleNameRelative(moduleName: string): boolean; + function sortAndDeduplicateDiagnostics(diagnostics: ReadonlyArray): SortedReadonlyArray; +} +declare namespace ts { + function getDefaultLibFileName(options: CompilerOptions): string; + function textSpanEnd(span: TextSpan): number; + function textSpanIsEmpty(span: TextSpan): boolean; + function textSpanContainsPosition(span: TextSpan, position: number): boolean; + function textSpanContainsTextSpan(span: TextSpan, other: TextSpan): boolean; + function textSpanOverlapsWith(span: TextSpan, other: TextSpan): boolean; + function textSpanOverlap(span1: TextSpan, span2: TextSpan): TextSpan | undefined; + function textSpanIntersectsWithTextSpan(span: TextSpan, other: TextSpan): boolean; + function textSpanIntersectsWith(span: TextSpan, start: number, length: number): boolean; + function decodedTextSpanIntersectsWith(start1: number, length1: number, start2: number, length2: number): boolean; + function textSpanIntersectsWithPosition(span: TextSpan, position: number): boolean; + function textSpanIntersection(span1: TextSpan, span2: TextSpan): TextSpan | undefined; + function createTextSpan(start: number, length: number): TextSpan; + function createTextSpanFromBounds(start: number, end: number): TextSpan; + function textChangeRangeNewSpan(range: TextChangeRange): TextSpan; + function textChangeRangeIsUnchanged(range: TextChangeRange): boolean; + function createTextChangeRange(span: TextSpan, newLength: number): TextChangeRange; + let unchangedTextChangeRange: TextChangeRange; + /** + * Called to merge all the changes that occurred across several versions of a script snapshot + * into a single change. i.e. if a user keeps making successive edits to a script we will + * have a text change from V1 to V2, V2 to V3, ..., Vn. + * + * This function will then merge those changes into a single change range valid between V1 and + * Vn. + */ + function collapseTextChangeRangesAcrossMultipleVersions(changes: ReadonlyArray): TextChangeRange; + function getTypeParameterOwner(d: Declaration): Declaration | undefined; + type ParameterPropertyDeclaration = ParameterDeclaration & { + parent: ConstructorDeclaration; + name: Identifier; + }; + function isParameterPropertyDeclaration(node: Node): node is ParameterPropertyDeclaration; + function isEmptyBindingPattern(node: BindingName): node is BindingPattern; + function isEmptyBindingElement(node: BindingElement): boolean; + function walkUpBindingElementsAndPatterns(binding: BindingElement): VariableDeclaration | ParameterDeclaration; + function getCombinedModifierFlags(node: Declaration): ModifierFlags; + function getCombinedNodeFlags(node: Node): NodeFlags; + /** + * Checks to see if the locale is in the appropriate format, + * and if it is, attempts to set the appropriate language. + */ + function validateLocaleAndSetLanguage(locale: string, sys: { + getExecutingFilePath(): string; + resolvePath(path: string): string; + fileExists(fileName: string): boolean; + readFile(fileName: string): string | undefined; + }, errors?: Push): void; + function getOriginalNode(node: Node): Node; + function getOriginalNode(node: Node, nodeTest: (node: Node) => node is T): T; + function getOriginalNode(node: Node | undefined): Node | undefined; + function getOriginalNode(node: Node | undefined, nodeTest: (node: Node | undefined) => node is T): T | undefined; + /** + * Gets a value indicating whether a node originated in the parse tree. + * + * @param node The node to test. + */ + function isParseTreeNode(node: Node): boolean; + /** + * Gets the original parse tree node for a node. + * + * @param node The original node. + * @returns The original parse tree node if found; otherwise, undefined. + */ + function getParseTreeNode(node: Node): Node; + /** + * Gets the original parse tree node for a node. + * + * @param node The original node. + * @param nodeTest A callback used to ensure the correct type of parse tree node is returned. + * @returns The original parse tree node if found; otherwise, undefined. + */ + function getParseTreeNode(node: Node | undefined, nodeTest?: (node: Node) => node is T): T | undefined; + /** Add an extra underscore to identifiers that start with two underscores to avoid issues with magic names like '__proto__' */ + function escapeLeadingUnderscores(identifier: string): __String; + /** + * Remove extra underscore from escaped identifier text content. + * + * @param identifier The escaped identifier text. + * @returns The unescaped identifier text. + */ + function unescapeLeadingUnderscores(identifier: __String): string; + function idText(identifier: Identifier): string; + function symbolName(symbol: Symbol): string; + function getNameOfJSDocTypedef(declaration: JSDocTypedefTag): Identifier | undefined; + function getNameOfDeclaration(declaration: Declaration | Expression): DeclarationName | undefined; + /** + * Gets the JSDoc parameter tags for the node if present. + * + * @remarks Returns any JSDoc param tag whose name matches the provided + * parameter, whether a param tag on a containing function + * expression, or a param tag on a variable declaration whose + * initializer is the containing function. The tags closest to the + * node are returned first, so in the previous example, the param + * tag on the containing function expression would be first. + * + * For binding patterns, parameter tags are matched by position. + */ + function getJSDocParameterTags(param: ParameterDeclaration): ReadonlyArray; + /** + * Gets the JSDoc type parameter tags for the node if present. + * + * @remarks Returns any JSDoc template tag whose names match the provided + * parameter, whether a template tag on a containing function + * expression, or a template tag on a variable declaration whose + * initializer is the containing function. The tags closest to the + * node are returned first, so in the previous example, the template + * tag on the containing function expression would be first. + */ + function getJSDocTypeParameterTags(param: TypeParameterDeclaration): ReadonlyArray; + /** + * Return true if the node has JSDoc parameter tags. + * + * @remarks Includes parameter tags that are not directly on the node, + * for example on a variable declaration whose initializer is a function expression. + */ + function hasJSDocParameterTags(node: FunctionLikeDeclaration | SignatureDeclaration): boolean; + /** Gets the JSDoc augments tag for the node if present */ + function getJSDocAugmentsTag(node: Node): JSDocAugmentsTag | undefined; + /** Gets the JSDoc class tag for the node if present */ + function getJSDocClassTag(node: Node): JSDocClassTag | undefined; + /** Gets the JSDoc enum tag for the node if present */ + function getJSDocEnumTag(node: Node): JSDocEnumTag | undefined; + /** Gets the JSDoc this tag for the node if present */ + function getJSDocThisTag(node: Node): JSDocThisTag | undefined; + /** Gets the JSDoc return tag for the node if present */ + function getJSDocReturnTag(node: Node): JSDocReturnTag | undefined; + /** Gets the JSDoc template tag for the node if present */ + function getJSDocTemplateTag(node: Node): JSDocTemplateTag | undefined; + /** Gets the JSDoc type tag for the node if present and valid */ + function getJSDocTypeTag(node: Node): JSDocTypeTag | undefined; + /** + * Gets the type node for the node if provided via JSDoc. + * + * @remarks The search includes any JSDoc param tag that relates + * to the provided parameter, for example a type tag on the + * parameter itself, or a param tag on a containing function + * expression, or a param tag on a variable declaration whose + * initializer is the containing function. The tags closest to the + * node are examined first, so in the previous example, the type + * tag directly on the node would be returned. + */ + function getJSDocType(node: Node): TypeNode | undefined; + /** + * Gets the return type node for the node if provided via JSDoc return tag or type tag. + * + * @remarks `getJSDocReturnTag` just gets the whole JSDoc tag. This function + * gets the type from inside the braces, after the fat arrow, etc. + */ + function getJSDocReturnType(node: Node): TypeNode | undefined; + /** Get all JSDoc tags related to a node, including those on parent nodes. */ + function getJSDocTags(node: Node): ReadonlyArray; + /** Gets all JSDoc tags of a specified kind, or undefined if not present. */ + function getAllJSDocTagsOfKind(node: Node, kind: SyntaxKind): ReadonlyArray; + /** + * Gets the effective type parameters. If the node was parsed in a + * JavaScript file, gets the type parameters from the `@template` tag from JSDoc. + */ + function getEffectiveTypeParameterDeclarations(node: DeclarationWithTypeParameters): ReadonlyArray; + function getEffectiveConstraintOfTypeParameter(node: TypeParameterDeclaration): TypeNode | undefined; +} +declare namespace ts { + function isNumericLiteral(node: Node): node is NumericLiteral; + function isBigIntLiteral(node: Node): node is BigIntLiteral; + function isStringLiteral(node: Node): node is StringLiteral; + function isJsxText(node: Node): node is JsxText; + function isRegularExpressionLiteral(node: Node): node is RegularExpressionLiteral; + function isNoSubstitutionTemplateLiteral(node: Node): node is NoSubstitutionTemplateLiteral; + function isTemplateHead(node: Node): node is TemplateHead; + function isTemplateMiddle(node: Node): node is TemplateMiddle; + function isTemplateTail(node: Node): node is TemplateTail; + function isIdentifier(node: Node): node is Identifier; + function isQualifiedName(node: Node): node is QualifiedName; + function isComputedPropertyName(node: Node): node is ComputedPropertyName; + function isTypeParameterDeclaration(node: Node): node is TypeParameterDeclaration; + function isParameter(node: Node): node is ParameterDeclaration; + function isDecorator(node: Node): node is Decorator; + function isPropertySignature(node: Node): node is PropertySignature; + function isPropertyDeclaration(node: Node): node is PropertyDeclaration; + function isMethodSignature(node: Node): node is MethodSignature; + function isMethodDeclaration(node: Node): node is MethodDeclaration; + function isConstructorDeclaration(node: Node): node is ConstructorDeclaration; + function isGetAccessorDeclaration(node: Node): node is GetAccessorDeclaration; + function isSetAccessorDeclaration(node: Node): node is SetAccessorDeclaration; + function isCallSignatureDeclaration(node: Node): node is CallSignatureDeclaration; + function isConstructSignatureDeclaration(node: Node): node is ConstructSignatureDeclaration; + function isIndexSignatureDeclaration(node: Node): node is IndexSignatureDeclaration; + function isTypePredicateNode(node: Node): node is TypePredicateNode; + function isTypeReferenceNode(node: Node): node is TypeReferenceNode; + function isFunctionTypeNode(node: Node): node is FunctionTypeNode; + function isConstructorTypeNode(node: Node): node is ConstructorTypeNode; + function isTypeQueryNode(node: Node): node is TypeQueryNode; + function isTypeLiteralNode(node: Node): node is TypeLiteralNode; + function isArrayTypeNode(node: Node): node is ArrayTypeNode; + function isTupleTypeNode(node: Node): node is TupleTypeNode; + function isUnionTypeNode(node: Node): node is UnionTypeNode; + function isIntersectionTypeNode(node: Node): node is IntersectionTypeNode; + function isConditionalTypeNode(node: Node): node is ConditionalTypeNode; + function isInferTypeNode(node: Node): node is InferTypeNode; + function isParenthesizedTypeNode(node: Node): node is ParenthesizedTypeNode; + function isThisTypeNode(node: Node): node is ThisTypeNode; + function isTypeOperatorNode(node: Node): node is TypeOperatorNode; + function isIndexedAccessTypeNode(node: Node): node is IndexedAccessTypeNode; + function isMappedTypeNode(node: Node): node is MappedTypeNode; + function isLiteralTypeNode(node: Node): node is LiteralTypeNode; + function isImportTypeNode(node: Node): node is ImportTypeNode; + function isObjectBindingPattern(node: Node): node is ObjectBindingPattern; + function isArrayBindingPattern(node: Node): node is ArrayBindingPattern; + function isBindingElement(node: Node): node is BindingElement; + function isArrayLiteralExpression(node: Node): node is ArrayLiteralExpression; + function isObjectLiteralExpression(node: Node): node is ObjectLiteralExpression; + function isPropertyAccessExpression(node: Node): node is PropertyAccessExpression; + function isElementAccessExpression(node: Node): node is ElementAccessExpression; + function isCallExpression(node: Node): node is CallExpression; + function isNewExpression(node: Node): node is NewExpression; + function isTaggedTemplateExpression(node: Node): node is TaggedTemplateExpression; + function isTypeAssertion(node: Node): node is TypeAssertion; + function isParenthesizedExpression(node: Node): node is ParenthesizedExpression; + function skipPartiallyEmittedExpressions(node: Expression): Expression; + function skipPartiallyEmittedExpressions(node: Node): Node; + function isFunctionExpression(node: Node): node is FunctionExpression; + function isArrowFunction(node: Node): node is ArrowFunction; + function isDeleteExpression(node: Node): node is DeleteExpression; + function isTypeOfExpression(node: Node): node is TypeOfExpression; + function isVoidExpression(node: Node): node is VoidExpression; + function isAwaitExpression(node: Node): node is AwaitExpression; + function isPrefixUnaryExpression(node: Node): node is PrefixUnaryExpression; + function isPostfixUnaryExpression(node: Node): node is PostfixUnaryExpression; + function isBinaryExpression(node: Node): node is BinaryExpression; + function isConditionalExpression(node: Node): node is ConditionalExpression; + function isTemplateExpression(node: Node): node is TemplateExpression; + function isYieldExpression(node: Node): node is YieldExpression; + function isSpreadElement(node: Node): node is SpreadElement; + function isClassExpression(node: Node): node is ClassExpression; + function isOmittedExpression(node: Node): node is OmittedExpression; + function isExpressionWithTypeArguments(node: Node): node is ExpressionWithTypeArguments; + function isAsExpression(node: Node): node is AsExpression; + function isNonNullExpression(node: Node): node is NonNullExpression; + function isMetaProperty(node: Node): node is MetaProperty; + function isTemplateSpan(node: Node): node is TemplateSpan; + function isSemicolonClassElement(node: Node): node is SemicolonClassElement; + function isBlock(node: Node): node is Block; + function isVariableStatement(node: Node): node is VariableStatement; + function isEmptyStatement(node: Node): node is EmptyStatement; + function isExpressionStatement(node: Node): node is ExpressionStatement; + function isIfStatement(node: Node): node is IfStatement; + function isDoStatement(node: Node): node is DoStatement; + function isWhileStatement(node: Node): node is WhileStatement; + function isForStatement(node: Node): node is ForStatement; + function isForInStatement(node: Node): node is ForInStatement; + function isForOfStatement(node: Node): node is ForOfStatement; + function isContinueStatement(node: Node): node is ContinueStatement; + function isBreakStatement(node: Node): node is BreakStatement; + function isBreakOrContinueStatement(node: Node): node is BreakOrContinueStatement; + function isReturnStatement(node: Node): node is ReturnStatement; + function isWithStatement(node: Node): node is WithStatement; + function isSwitchStatement(node: Node): node is SwitchStatement; + function isLabeledStatement(node: Node): node is LabeledStatement; + function isThrowStatement(node: Node): node is ThrowStatement; + function isTryStatement(node: Node): node is TryStatement; + function isDebuggerStatement(node: Node): node is DebuggerStatement; + function isVariableDeclaration(node: Node): node is VariableDeclaration; + function isVariableDeclarationList(node: Node): node is VariableDeclarationList; + function isFunctionDeclaration(node: Node): node is FunctionDeclaration; + function isClassDeclaration(node: Node): node is ClassDeclaration; + function isInterfaceDeclaration(node: Node): node is InterfaceDeclaration; + function isTypeAliasDeclaration(node: Node): node is TypeAliasDeclaration; + function isEnumDeclaration(node: Node): node is EnumDeclaration; + function isModuleDeclaration(node: Node): node is ModuleDeclaration; + function isModuleBlock(node: Node): node is ModuleBlock; + function isCaseBlock(node: Node): node is CaseBlock; + function isNamespaceExportDeclaration(node: Node): node is NamespaceExportDeclaration; + function isImportEqualsDeclaration(node: Node): node is ImportEqualsDeclaration; + function isImportDeclaration(node: Node): node is ImportDeclaration; + function isImportClause(node: Node): node is ImportClause; + function isNamespaceImport(node: Node): node is NamespaceImport; + function isNamedImports(node: Node): node is NamedImports; + function isImportSpecifier(node: Node): node is ImportSpecifier; + function isExportAssignment(node: Node): node is ExportAssignment; + function isExportDeclaration(node: Node): node is ExportDeclaration; + function isNamedExports(node: Node): node is NamedExports; + function isExportSpecifier(node: Node): node is ExportSpecifier; + function isMissingDeclaration(node: Node): node is MissingDeclaration; + function isExternalModuleReference(node: Node): node is ExternalModuleReference; + function isJsxElement(node: Node): node is JsxElement; + function isJsxSelfClosingElement(node: Node): node is JsxSelfClosingElement; + function isJsxOpeningElement(node: Node): node is JsxOpeningElement; + function isJsxClosingElement(node: Node): node is JsxClosingElement; + function isJsxFragment(node: Node): node is JsxFragment; + function isJsxOpeningFragment(node: Node): node is JsxOpeningFragment; + function isJsxClosingFragment(node: Node): node is JsxClosingFragment; + function isJsxAttribute(node: Node): node is JsxAttribute; + function isJsxAttributes(node: Node): node is JsxAttributes; + function isJsxSpreadAttribute(node: Node): node is JsxSpreadAttribute; + function isJsxExpression(node: Node): node is JsxExpression; + function isCaseClause(node: Node): node is CaseClause; + function isDefaultClause(node: Node): node is DefaultClause; + function isHeritageClause(node: Node): node is HeritageClause; + function isCatchClause(node: Node): node is CatchClause; + function isPropertyAssignment(node: Node): node is PropertyAssignment; + function isShorthandPropertyAssignment(node: Node): node is ShorthandPropertyAssignment; + function isSpreadAssignment(node: Node): node is SpreadAssignment; + function isEnumMember(node: Node): node is EnumMember; + function isSourceFile(node: Node): node is SourceFile; + function isBundle(node: Node): node is Bundle; + function isUnparsedSource(node: Node): node is UnparsedSource; + function isJSDocTypeExpression(node: Node): node is JSDocTypeExpression; + function isJSDocAllType(node: JSDocAllType): node is JSDocAllType; + function isJSDocUnknownType(node: Node): node is JSDocUnknownType; + function isJSDocNullableType(node: Node): node is JSDocNullableType; + function isJSDocNonNullableType(node: Node): node is JSDocNonNullableType; + function isJSDocOptionalType(node: Node): node is JSDocOptionalType; + function isJSDocFunctionType(node: Node): node is JSDocFunctionType; + function isJSDocVariadicType(node: Node): node is JSDocVariadicType; + function isJSDoc(node: Node): node is JSDoc; + function isJSDocAugmentsTag(node: Node): node is JSDocAugmentsTag; + function isJSDocClassTag(node: Node): node is JSDocClassTag; + function isJSDocEnumTag(node: Node): node is JSDocEnumTag; + function isJSDocThisTag(node: Node): node is JSDocThisTag; + function isJSDocParameterTag(node: Node): node is JSDocParameterTag; + function isJSDocReturnTag(node: Node): node is JSDocReturnTag; + function isJSDocTypeTag(node: Node): node is JSDocTypeTag; + function isJSDocTemplateTag(node: Node): node is JSDocTemplateTag; + function isJSDocTypedefTag(node: Node): node is JSDocTypedefTag; + function isJSDocPropertyTag(node: Node): node is JSDocPropertyTag; + function isJSDocPropertyLikeTag(node: Node): node is JSDocPropertyLikeTag; + function isJSDocTypeLiteral(node: Node): node is JSDocTypeLiteral; + function isJSDocCallbackTag(node: Node): node is JSDocCallbackTag; + function isJSDocSignature(node: Node): node is JSDocSignature; +} +declare namespace ts { + /** + * True if node is of some token syntax kind. + * For example, this is true for an IfKeyword but not for an IfStatement. + * Literals are considered tokens, except TemplateLiteral, but does include TemplateHead/Middle/Tail. + */ + function isToken(n: Node): boolean; + function isLiteralExpression(node: Node): node is LiteralExpression; + type TemplateLiteralToken = NoSubstitutionTemplateLiteral | TemplateHead | TemplateMiddle | TemplateTail; + function isTemplateLiteralToken(node: Node): node is TemplateLiteralToken; + function isTemplateMiddleOrTemplateTail(node: Node): node is TemplateMiddle | TemplateTail; + function isImportOrExportSpecifier(node: Node): node is ImportSpecifier | ExportSpecifier; + function isStringTextContainingNode(node: Node): node is StringLiteral | TemplateLiteralToken; + function isModifier(node: Node): node is Modifier; + function isEntityName(node: Node): node is EntityName; + function isPropertyName(node: Node): node is PropertyName; + function isBindingName(node: Node): node is BindingName; + function isFunctionLike(node: Node): node is SignatureDeclaration; + function isClassElement(node: Node): node is ClassElement; + function isClassLike(node: Node): node is ClassLikeDeclaration; + function isAccessor(node: Node): node is AccessorDeclaration; + function isTypeElement(node: Node): node is TypeElement; + function isClassOrTypeElement(node: Node): node is ClassElement | TypeElement; + function isObjectLiteralElementLike(node: Node): node is ObjectLiteralElementLike; + /** + * Node test that determines whether a node is a valid type node. + * This differs from the `isPartOfTypeNode` function which determines whether a node is *part* + * of a TypeNode. + */ + function isTypeNode(node: Node): node is TypeNode; + function isFunctionOrConstructorTypeNode(node: Node): node is FunctionTypeNode | ConstructorTypeNode; + function isPropertyAccessOrQualifiedName(node: Node): node is PropertyAccessExpression | QualifiedName; + function isCallLikeExpression(node: Node): node is CallLikeExpression; + function isCallOrNewExpression(node: Node): node is CallExpression | NewExpression; + function isTemplateLiteral(node: Node): node is TemplateLiteral; + function isAssertionExpression(node: Node): node is AssertionExpression; + function isIterationStatement(node: Node, lookInLabeledStatements: false): node is IterationStatement; + function isIterationStatement(node: Node, lookInLabeledStatements: boolean): node is IterationStatement | LabeledStatement; + function isJsxOpeningLikeElement(node: Node): node is JsxOpeningLikeElement; + function isCaseOrDefaultClause(node: Node): node is CaseOrDefaultClause; + /** True if node is of a kind that may contain comment text. */ + function isJSDocCommentContainingNode(node: Node): boolean; + function isSetAccessor(node: Node): node is SetAccessorDeclaration; + function isGetAccessor(node: Node): node is GetAccessorDeclaration; + function isObjectLiteralElement(node: Node): node is ObjectLiteralElement; + function isStringLiteralLike(node: Node): node is StringLiteralLike; +} +declare namespace ts { + function createNode(kind: SyntaxKind, pos?: number, end?: number): Node; + /** + * Invokes a callback for each child of the given node. The 'cbNode' callback is invoked for all child nodes + * stored in properties. If a 'cbNodes' callback is specified, it is invoked for embedded arrays; otherwise, + * embedded arrays are flattened and the 'cbNode' callback is invoked for each element. If a callback returns + * a truthy value, iteration stops and that value is returned. Otherwise, undefined is returned. + * + * @param node a given node to visit its children + * @param cbNode a callback to be invoked for all child nodes + * @param cbNodes a callback to be invoked for embedded array + * + * @remarks `forEachChild` must visit the children of a node in the order + * that they appear in the source code. The language service depends on this property to locate nodes by position. + */ + function forEachChild(node: Node, cbNode: (node: Node) => T | undefined, cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined; + function createSourceFile(fileName: string, sourceText: string, languageVersion: ScriptTarget, setParentNodes?: boolean, scriptKind?: ScriptKind): SourceFile; + function parseIsolatedEntityName(text: string, languageVersion: ScriptTarget): EntityName | undefined; + /** + * Parse json text into SyntaxTree and return node and parse errors if any + * @param fileName + * @param sourceText + */ + function parseJsonText(fileName: string, sourceText: string): JsonSourceFile; + function isExternalModule(file: SourceFile): boolean; + function updateSourceFile(sourceFile: SourceFile, newText: string, textChangeRange: TextChangeRange, aggressiveChecks?: boolean): SourceFile; +} +declare namespace ts { + function parseCommandLine(commandLine: ReadonlyArray, readFile?: (path: string) => string | undefined): ParsedCommandLine; + type DiagnosticReporter = (diagnostic: Diagnostic) => void; + /** + * Reports config file diagnostics + */ + interface ConfigFileDiagnosticsReporter { + /** + * Reports unrecoverable error when parsing config file + */ + onUnRecoverableConfigFileDiagnostic: DiagnosticReporter; + } + /** + * Interface extending ParseConfigHost to support ParseConfigFile that reads config file and reports errors + */ + interface ParseConfigFileHost extends ParseConfigHost, ConfigFileDiagnosticsReporter { + getCurrentDirectory(): string; + } + /** + * Reads the config file, reports errors if any and exits if the config file cannot be found + */ + function getParsedCommandLineOfConfigFile(configFileName: string, optionsToExtend: CompilerOptions, host: ParseConfigFileHost): ParsedCommandLine | undefined; + /** + * Read tsconfig.json file + * @param fileName The path to the config file + */ + function readConfigFile(fileName: string, readFile: (path: string) => string | undefined): { + config?: any; + error?: Diagnostic; + }; + /** + * Parse the text of the tsconfig.json file + * @param fileName The path to the config file + * @param jsonText The text of the config file + */ + function parseConfigFileTextToJson(fileName: string, jsonText: string): { + config?: any; + error?: Diagnostic; + }; + /** + * Read tsconfig.json file + * @param fileName The path to the config file + */ + function readJsonConfigFile(fileName: string, readFile: (path: string) => string | undefined): TsConfigSourceFile; + /** + * Convert the json syntax tree into the json value + */ + function convertToObject(sourceFile: JsonSourceFile, errors: Push): any; + /** + * Parse the contents of a config file (tsconfig.json). + * @param json The contents of the config file to parse + * @param host Instance of ParseConfigHost used to enumerate files in folder. + * @param basePath A root directory to resolve relative path entries in the config + * file to. e.g. outDir + */ + function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[], extraFileExtensions?: ReadonlyArray): ParsedCommandLine; + /** + * Parse the contents of a config file (tsconfig.json). + * @param jsonNode The contents of the config file to parse + * @param host Instance of ParseConfigHost used to enumerate files in folder. + * @param basePath A root directory to resolve relative path entries in the config + * file to. e.g. outDir + */ + function parseJsonSourceFileConfigFileContent(sourceFile: TsConfigSourceFile, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[], extraFileExtensions?: ReadonlyArray): ParsedCommandLine; + function convertCompilerOptionsFromJson(jsonOptions: any, basePath: string, configFileName?: string): { + options: CompilerOptions; + errors: Diagnostic[]; + }; + function convertTypeAcquisitionFromJson(jsonOptions: any, basePath: string, configFileName?: string): { + options: TypeAcquisition; + errors: Diagnostic[]; + }; +} +declare namespace ts { + function getEffectiveTypeRoots(options: CompilerOptions, host: GetEffectiveTypeRootsHost): string[] | undefined; + /** + * @param {string | undefined} containingFile - file that contains type reference directive, can be undefined if containing file is unknown. + * This is possible in case if resolution is performed for directives specified via 'types' parameter. In this case initial path for secondary lookups + * is assumed to be the same as root directory of the project. + */ + function resolveTypeReferenceDirective(typeReferenceDirectiveName: string, containingFile: string | undefined, options: CompilerOptions, host: ModuleResolutionHost, redirectedReference?: ResolvedProjectReference): ResolvedTypeReferenceDirectiveWithFailedLookupLocations; + /** + * Given a set of options, returns the set of type directive names + * that should be included for this program automatically. + * This list could either come from the config file, + * or from enumerating the types root + initial secondary types lookup location. + * More type directives might appear in the program later as a result of loading actual source files; + * this list is only the set of defaults that are implicitly included. + */ + function getAutomaticTypeDirectiveNames(options: CompilerOptions, host: ModuleResolutionHost): string[]; + /** + * Cached module resolutions per containing directory. + * This assumes that any module id will have the same resolution for sibling files located in the same folder. + */ + interface ModuleResolutionCache extends NonRelativeModuleNameResolutionCache { + getOrCreateCacheForDirectory(directoryName: string, redirectedReference?: ResolvedProjectReference): Map; + } + /** + * Stored map from non-relative module name to a table: directory -> result of module lookup in this directory + * We support only non-relative module names because resolution of relative module names is usually more deterministic and thus less expensive. + */ + interface NonRelativeModuleNameResolutionCache { + getOrCreateCacheForModuleName(nonRelativeModuleName: string, redirectedReference?: ResolvedProjectReference): PerModuleNameCache; + } + interface PerModuleNameCache { + get(directory: string): ResolvedModuleWithFailedLookupLocations | undefined; + set(directory: string, result: ResolvedModuleWithFailedLookupLocations): void; + } + function createModuleResolutionCache(currentDirectory: string, getCanonicalFileName: (s: string) => string): ModuleResolutionCache; + function resolveModuleNameFromCache(moduleName: string, containingFile: string, cache: ModuleResolutionCache): ResolvedModuleWithFailedLookupLocations | undefined; + function resolveModuleName(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: ModuleResolutionCache, redirectedReference?: ResolvedProjectReference): ResolvedModuleWithFailedLookupLocations; + function nodeModuleNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: ModuleResolutionCache, redirectedReference?: ResolvedProjectReference): ResolvedModuleWithFailedLookupLocations; + function classicNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: NonRelativeModuleNameResolutionCache, redirectedReference?: ResolvedProjectReference): ResolvedModuleWithFailedLookupLocations; +} +declare namespace ts { + function createNodeArray(elements?: ReadonlyArray, hasTrailingComma?: boolean): NodeArray; + /** If a node is passed, creates a string literal whose source text is read from a source node during emit. */ + function createLiteral(value: string | StringLiteral | NoSubstitutionTemplateLiteral | NumericLiteral | Identifier): StringLiteral; + function createLiteral(value: number | PseudoBigInt): NumericLiteral; + function createLiteral(value: boolean): BooleanLiteral; + function createLiteral(value: string | number | PseudoBigInt | boolean): PrimaryExpression; + function createNumericLiteral(value: string): NumericLiteral; + function createBigIntLiteral(value: string): BigIntLiteral; + function createStringLiteral(text: string): StringLiteral; + function createRegularExpressionLiteral(text: string): RegularExpressionLiteral; + function createIdentifier(text: string): Identifier; + function updateIdentifier(node: Identifier): Identifier; + /** Create a unique temporary variable. */ + function createTempVariable(recordTempVariable: ((node: Identifier) => void) | undefined): Identifier; + /** Create a unique temporary variable for use in a loop. */ + function createLoopVariable(): Identifier; + /** Create a unique name based on the supplied text. */ + function createUniqueName(text: string): Identifier; + /** Create a unique name based on the supplied text. */ + function createOptimisticUniqueName(text: string): Identifier; + /** Create a unique name based on the supplied text. This does not consider names injected by the transformer. */ + function createFileLevelUniqueName(text: string): Identifier; + /** Create a unique name generated for a node. */ + function getGeneratedNameForNode(node: Node | undefined): Identifier; + function createToken(token: TKind): Token; + function createSuper(): SuperExpression; + function createThis(): ThisExpression & Token; + function createNull(): NullLiteral & Token; + function createTrue(): BooleanLiteral & Token; + function createFalse(): BooleanLiteral & Token; + function createModifier(kind: T): Token; + function createModifiersFromModifierFlags(flags: ModifierFlags): Modifier[]; + function createQualifiedName(left: EntityName, right: string | Identifier): QualifiedName; + function updateQualifiedName(node: QualifiedName, left: EntityName, right: Identifier): QualifiedName; + function createComputedPropertyName(expression: Expression): ComputedPropertyName; + function updateComputedPropertyName(node: ComputedPropertyName, expression: Expression): ComputedPropertyName; + function createTypeParameterDeclaration(name: string | Identifier, constraint?: TypeNode, defaultType?: TypeNode): TypeParameterDeclaration; + function updateTypeParameterDeclaration(node: TypeParameterDeclaration, name: Identifier, constraint: TypeNode | undefined, defaultType: TypeNode | undefined): TypeParameterDeclaration; + function createParameter(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, dotDotDotToken: DotDotDotToken | undefined, name: string | BindingName, questionToken?: QuestionToken, type?: TypeNode, initializer?: Expression): ParameterDeclaration; + function updateParameter(node: ParameterDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, dotDotDotToken: DotDotDotToken | undefined, name: string | BindingName, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): ParameterDeclaration; + function createDecorator(expression: Expression): Decorator; + function updateDecorator(node: Decorator, expression: Expression): Decorator; + function createPropertySignature(modifiers: ReadonlyArray | undefined, name: PropertyName | string, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): PropertySignature; + function updatePropertySignature(node: PropertySignature, modifiers: ReadonlyArray | undefined, name: PropertyName, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): PropertySignature; + function createProperty(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: string | PropertyName, questionOrExclamationToken: QuestionToken | ExclamationToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): PropertyDeclaration; + function updateProperty(node: PropertyDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: string | PropertyName, questionOrExclamationToken: QuestionToken | ExclamationToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): PropertyDeclaration; + function createMethodSignature(typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined): MethodSignature; + function updateMethodSignature(node: MethodSignature, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined, name: PropertyName, questionToken: QuestionToken | undefined): MethodSignature; + function createMethod(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, asteriskToken: AsteriskToken | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined, typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode | undefined, body: Block | undefined): MethodDeclaration; + function updateMethod(node: MethodDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, asteriskToken: AsteriskToken | undefined, name: PropertyName, questionToken: QuestionToken | undefined, typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode | undefined, body: Block | undefined): MethodDeclaration; + function createConstructor(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, parameters: ReadonlyArray, body: Block | undefined): ConstructorDeclaration; + function updateConstructor(node: ConstructorDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, parameters: ReadonlyArray, body: Block | undefined): ConstructorDeclaration; + function createGetAccessor(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: string | PropertyName, parameters: ReadonlyArray, type: TypeNode | undefined, body: Block | undefined): GetAccessorDeclaration; + function updateGetAccessor(node: GetAccessorDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: PropertyName, parameters: ReadonlyArray, type: TypeNode | undefined, body: Block | undefined): GetAccessorDeclaration; + function createSetAccessor(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: string | PropertyName, parameters: ReadonlyArray, body: Block | undefined): SetAccessorDeclaration; + function updateSetAccessor(node: SetAccessorDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: PropertyName, parameters: ReadonlyArray, body: Block | undefined): SetAccessorDeclaration; + function createCallSignature(typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode | undefined): CallSignatureDeclaration; + function updateCallSignature(node: CallSignatureDeclaration, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined): CallSignatureDeclaration; + function createConstructSignature(typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode | undefined): ConstructSignatureDeclaration; + function updateConstructSignature(node: ConstructSignatureDeclaration, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined): ConstructSignatureDeclaration; + function createIndexSignature(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode): IndexSignatureDeclaration; + function updateIndexSignature(node: IndexSignatureDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode): IndexSignatureDeclaration; + function createKeywordTypeNode(kind: KeywordTypeNode["kind"]): KeywordTypeNode; + function createTypePredicateNode(parameterName: Identifier | ThisTypeNode | string, type: TypeNode): TypePredicateNode; + function updateTypePredicateNode(node: TypePredicateNode, parameterName: Identifier | ThisTypeNode, type: TypeNode): TypePredicateNode; + function createTypeReferenceNode(typeName: string | EntityName, typeArguments: ReadonlyArray | undefined): TypeReferenceNode; + function updateTypeReferenceNode(node: TypeReferenceNode, typeName: EntityName, typeArguments: NodeArray | undefined): TypeReferenceNode; + function createFunctionTypeNode(typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode | undefined): FunctionTypeNode; + function updateFunctionTypeNode(node: FunctionTypeNode, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined): FunctionTypeNode; + function createConstructorTypeNode(typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode | undefined): ConstructorTypeNode; + function updateConstructorTypeNode(node: ConstructorTypeNode, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined): ConstructorTypeNode; + function createTypeQueryNode(exprName: EntityName): TypeQueryNode; + function updateTypeQueryNode(node: TypeQueryNode, exprName: EntityName): TypeQueryNode; + function createTypeLiteralNode(members: ReadonlyArray | undefined): TypeLiteralNode; + function updateTypeLiteralNode(node: TypeLiteralNode, members: NodeArray): TypeLiteralNode; + function createArrayTypeNode(elementType: TypeNode): ArrayTypeNode; + function updateArrayTypeNode(node: ArrayTypeNode, elementType: TypeNode): ArrayTypeNode; + function createTupleTypeNode(elementTypes: ReadonlyArray): TupleTypeNode; + function updateTupleTypeNode(node: TupleTypeNode, elementTypes: ReadonlyArray): TupleTypeNode; + function createOptionalTypeNode(type: TypeNode): OptionalTypeNode; + function updateOptionalTypeNode(node: OptionalTypeNode, type: TypeNode): OptionalTypeNode; + function createRestTypeNode(type: TypeNode): RestTypeNode; + function updateRestTypeNode(node: RestTypeNode, type: TypeNode): RestTypeNode; + function createUnionTypeNode(types: ReadonlyArray): UnionTypeNode; + function updateUnionTypeNode(node: UnionTypeNode, types: NodeArray): UnionTypeNode; + function createIntersectionTypeNode(types: ReadonlyArray): IntersectionTypeNode; + function updateIntersectionTypeNode(node: IntersectionTypeNode, types: NodeArray): IntersectionTypeNode; + function createUnionOrIntersectionTypeNode(kind: SyntaxKind.UnionType | SyntaxKind.IntersectionType, types: ReadonlyArray): UnionOrIntersectionTypeNode; + function createConditionalTypeNode(checkType: TypeNode, extendsType: TypeNode, trueType: TypeNode, falseType: TypeNode): ConditionalTypeNode; + function updateConditionalTypeNode(node: ConditionalTypeNode, checkType: TypeNode, extendsType: TypeNode, trueType: TypeNode, falseType: TypeNode): ConditionalTypeNode; + function createInferTypeNode(typeParameter: TypeParameterDeclaration): InferTypeNode; + function updateInferTypeNode(node: InferTypeNode, typeParameter: TypeParameterDeclaration): InferTypeNode; + function createImportTypeNode(argument: TypeNode, qualifier?: EntityName, typeArguments?: ReadonlyArray, isTypeOf?: boolean): ImportTypeNode; + function updateImportTypeNode(node: ImportTypeNode, argument: TypeNode, qualifier?: EntityName, typeArguments?: ReadonlyArray, isTypeOf?: boolean): ImportTypeNode; + function createParenthesizedType(type: TypeNode): ParenthesizedTypeNode; + function updateParenthesizedType(node: ParenthesizedTypeNode, type: TypeNode): ParenthesizedTypeNode; + function createThisTypeNode(): ThisTypeNode; + function createTypeOperatorNode(type: TypeNode): TypeOperatorNode; + function createTypeOperatorNode(operator: SyntaxKind.KeyOfKeyword | SyntaxKind.UniqueKeyword, type: TypeNode): TypeOperatorNode; + function updateTypeOperatorNode(node: TypeOperatorNode, type: TypeNode): TypeOperatorNode; + function createIndexedAccessTypeNode(objectType: TypeNode, indexType: TypeNode): IndexedAccessTypeNode; + function updateIndexedAccessTypeNode(node: IndexedAccessTypeNode, objectType: TypeNode, indexType: TypeNode): IndexedAccessTypeNode; + function createMappedTypeNode(readonlyToken: ReadonlyToken | PlusToken | MinusToken | undefined, typeParameter: TypeParameterDeclaration, questionToken: QuestionToken | PlusToken | MinusToken | undefined, type: TypeNode | undefined): MappedTypeNode; + function updateMappedTypeNode(node: MappedTypeNode, readonlyToken: ReadonlyToken | PlusToken | MinusToken | undefined, typeParameter: TypeParameterDeclaration, questionToken: QuestionToken | PlusToken | MinusToken | undefined, type: TypeNode | undefined): MappedTypeNode; + function createLiteralTypeNode(literal: LiteralTypeNode["literal"]): LiteralTypeNode; + function updateLiteralTypeNode(node: LiteralTypeNode, literal: LiteralTypeNode["literal"]): LiteralTypeNode; + function createObjectBindingPattern(elements: ReadonlyArray): ObjectBindingPattern; + function updateObjectBindingPattern(node: ObjectBindingPattern, elements: ReadonlyArray): ObjectBindingPattern; + function createArrayBindingPattern(elements: ReadonlyArray): ArrayBindingPattern; + function updateArrayBindingPattern(node: ArrayBindingPattern, elements: ReadonlyArray): ArrayBindingPattern; + function createBindingElement(dotDotDotToken: DotDotDotToken | undefined, propertyName: string | PropertyName | undefined, name: string | BindingName, initializer?: Expression): BindingElement; + function updateBindingElement(node: BindingElement, dotDotDotToken: DotDotDotToken | undefined, propertyName: PropertyName | undefined, name: BindingName, initializer: Expression | undefined): BindingElement; + function createArrayLiteral(elements?: ReadonlyArray, multiLine?: boolean): ArrayLiteralExpression; + function updateArrayLiteral(node: ArrayLiteralExpression, elements: ReadonlyArray): ArrayLiteralExpression; + function createObjectLiteral(properties?: ReadonlyArray, multiLine?: boolean): ObjectLiteralExpression; + function updateObjectLiteral(node: ObjectLiteralExpression, properties: ReadonlyArray): ObjectLiteralExpression; + function createPropertyAccess(expression: Expression, name: string | Identifier | undefined): PropertyAccessExpression; + function updatePropertyAccess(node: PropertyAccessExpression, expression: Expression, name: Identifier): PropertyAccessExpression; + function createElementAccess(expression: Expression, index: number | Expression): ElementAccessExpression; + function updateElementAccess(node: ElementAccessExpression, expression: Expression, argumentExpression: Expression): ElementAccessExpression; + function createCall(expression: Expression, typeArguments: ReadonlyArray | undefined, argumentsArray: ReadonlyArray | undefined): CallExpression; + function updateCall(node: CallExpression, expression: Expression, typeArguments: ReadonlyArray | undefined, argumentsArray: ReadonlyArray): CallExpression; + function createNew(expression: Expression, typeArguments: ReadonlyArray | undefined, argumentsArray: ReadonlyArray | undefined): NewExpression; + function updateNew(node: NewExpression, expression: Expression, typeArguments: ReadonlyArray | undefined, argumentsArray: ReadonlyArray | undefined): NewExpression; + /** @deprecated */ function createTaggedTemplate(tag: Expression, template: TemplateLiteral): TaggedTemplateExpression; + function createTaggedTemplate(tag: Expression, typeArguments: ReadonlyArray | undefined, template: TemplateLiteral): TaggedTemplateExpression; + /** @deprecated */ function updateTaggedTemplate(node: TaggedTemplateExpression, tag: Expression, template: TemplateLiteral): TaggedTemplateExpression; + function updateTaggedTemplate(node: TaggedTemplateExpression, tag: Expression, typeArguments: ReadonlyArray | undefined, template: TemplateLiteral): TaggedTemplateExpression; + function createTypeAssertion(type: TypeNode, expression: Expression): TypeAssertion; + function updateTypeAssertion(node: TypeAssertion, type: TypeNode, expression: Expression): TypeAssertion; + function createParen(expression: Expression): ParenthesizedExpression; + function updateParen(node: ParenthesizedExpression, expression: Expression): ParenthesizedExpression; + function createFunctionExpression(modifiers: ReadonlyArray | undefined, asteriskToken: AsteriskToken | undefined, name: string | Identifier | undefined, typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray | undefined, type: TypeNode | undefined, body: Block): FunctionExpression; + function updateFunctionExpression(node: FunctionExpression, modifiers: ReadonlyArray | undefined, asteriskToken: AsteriskToken | undefined, name: Identifier | undefined, typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode | undefined, body: Block): FunctionExpression; + function createArrowFunction(modifiers: ReadonlyArray | undefined, typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode | undefined, equalsGreaterThanToken: EqualsGreaterThanToken | undefined, body: ConciseBody): ArrowFunction; + function updateArrowFunction(node: ArrowFunction, modifiers: ReadonlyArray | undefined, typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode | undefined, equalsGreaterThanToken: Token, body: ConciseBody): ArrowFunction; + function createDelete(expression: Expression): DeleteExpression; + function updateDelete(node: DeleteExpression, expression: Expression): DeleteExpression; + function createTypeOf(expression: Expression): TypeOfExpression; + function updateTypeOf(node: TypeOfExpression, expression: Expression): TypeOfExpression; + function createVoid(expression: Expression): VoidExpression; + function updateVoid(node: VoidExpression, expression: Expression): VoidExpression; + function createAwait(expression: Expression): AwaitExpression; + function updateAwait(node: AwaitExpression, expression: Expression): AwaitExpression; + function createPrefix(operator: PrefixUnaryOperator, operand: Expression): PrefixUnaryExpression; + function updatePrefix(node: PrefixUnaryExpression, operand: Expression): PrefixUnaryExpression; + function createPostfix(operand: Expression, operator: PostfixUnaryOperator): PostfixUnaryExpression; + function updatePostfix(node: PostfixUnaryExpression, operand: Expression): PostfixUnaryExpression; + function createBinary(left: Expression, operator: BinaryOperator | BinaryOperatorToken, right: Expression): BinaryExpression; + function updateBinary(node: BinaryExpression, left: Expression, right: Expression, operator?: BinaryOperator | BinaryOperatorToken): BinaryExpression; + /** @deprecated */ function createConditional(condition: Expression, whenTrue: Expression, whenFalse: Expression): ConditionalExpression; + function createConditional(condition: Expression, questionToken: QuestionToken, whenTrue: Expression, colonToken: ColonToken, whenFalse: Expression): ConditionalExpression; + function updateConditional(node: ConditionalExpression, condition: Expression, questionToken: Token, whenTrue: Expression, colonToken: Token, whenFalse: Expression): ConditionalExpression; + function createTemplateExpression(head: TemplateHead, templateSpans: ReadonlyArray): TemplateExpression; + function updateTemplateExpression(node: TemplateExpression, head: TemplateHead, templateSpans: ReadonlyArray): TemplateExpression; + function createTemplateHead(text: string): TemplateHead; + function createTemplateMiddle(text: string): TemplateMiddle; + function createTemplateTail(text: string): TemplateTail; + function createNoSubstitutionTemplateLiteral(text: string): NoSubstitutionTemplateLiteral; + function createYield(expression?: Expression): YieldExpression; + function createYield(asteriskToken: AsteriskToken | undefined, expression: Expression): YieldExpression; + function updateYield(node: YieldExpression, asteriskToken: AsteriskToken | undefined, expression: Expression): YieldExpression; + function createSpread(expression: Expression): SpreadElement; + function updateSpread(node: SpreadElement, expression: Expression): SpreadElement; + function createClassExpression(modifiers: ReadonlyArray | undefined, name: string | Identifier | undefined, typeParameters: ReadonlyArray | undefined, heritageClauses: ReadonlyArray | undefined, members: ReadonlyArray): ClassExpression; + function updateClassExpression(node: ClassExpression, modifiers: ReadonlyArray | undefined, name: Identifier | undefined, typeParameters: ReadonlyArray | undefined, heritageClauses: ReadonlyArray | undefined, members: ReadonlyArray): ClassExpression; + function createOmittedExpression(): OmittedExpression; + function createExpressionWithTypeArguments(typeArguments: ReadonlyArray | undefined, expression: Expression): ExpressionWithTypeArguments; + function updateExpressionWithTypeArguments(node: ExpressionWithTypeArguments, typeArguments: ReadonlyArray | undefined, expression: Expression): ExpressionWithTypeArguments; + function createAsExpression(expression: Expression, type: TypeNode): AsExpression; + function updateAsExpression(node: AsExpression, expression: Expression, type: TypeNode): AsExpression; + function createNonNullExpression(expression: Expression): NonNullExpression; + function updateNonNullExpression(node: NonNullExpression, expression: Expression): NonNullExpression; + function createMetaProperty(keywordToken: MetaProperty["keywordToken"], name: Identifier): MetaProperty; + function updateMetaProperty(node: MetaProperty, name: Identifier): MetaProperty; + function createTemplateSpan(expression: Expression, literal: TemplateMiddle | TemplateTail): TemplateSpan; + function updateTemplateSpan(node: TemplateSpan, expression: Expression, literal: TemplateMiddle | TemplateTail): TemplateSpan; + function createSemicolonClassElement(): SemicolonClassElement; + function createBlock(statements: ReadonlyArray, multiLine?: boolean): Block; + function updateBlock(node: Block, statements: ReadonlyArray): Block; + function createVariableStatement(modifiers: ReadonlyArray | undefined, declarationList: VariableDeclarationList | ReadonlyArray): VariableStatement; + function updateVariableStatement(node: VariableStatement, modifiers: ReadonlyArray | undefined, declarationList: VariableDeclarationList): VariableStatement; + function createEmptyStatement(): EmptyStatement; + function createExpressionStatement(expression: Expression): ExpressionStatement; + function updateExpressionStatement(node: ExpressionStatement, expression: Expression): ExpressionStatement; + /** @deprecated Use `createExpressionStatement` instead. */ + const createStatement: typeof createExpressionStatement; + /** @deprecated Use `updateExpressionStatement` instead. */ + const updateStatement: typeof updateExpressionStatement; + function createIf(expression: Expression, thenStatement: Statement, elseStatement?: Statement): IfStatement; + function updateIf(node: IfStatement, expression: Expression, thenStatement: Statement, elseStatement: Statement | undefined): IfStatement; + function createDo(statement: Statement, expression: Expression): DoStatement; + function updateDo(node: DoStatement, statement: Statement, expression: Expression): DoStatement; + function createWhile(expression: Expression, statement: Statement): WhileStatement; + function updateWhile(node: WhileStatement, expression: Expression, statement: Statement): WhileStatement; + function createFor(initializer: ForInitializer | undefined, condition: Expression | undefined, incrementor: Expression | undefined, statement: Statement): ForStatement; + function updateFor(node: ForStatement, initializer: ForInitializer | undefined, condition: Expression | undefined, incrementor: Expression | undefined, statement: Statement): ForStatement; + function createForIn(initializer: ForInitializer, expression: Expression, statement: Statement): ForInStatement; + function updateForIn(node: ForInStatement, initializer: ForInitializer, expression: Expression, statement: Statement): ForInStatement; + function createForOf(awaitModifier: AwaitKeywordToken | undefined, initializer: ForInitializer, expression: Expression, statement: Statement): ForOfStatement; + function updateForOf(node: ForOfStatement, awaitModifier: AwaitKeywordToken | undefined, initializer: ForInitializer, expression: Expression, statement: Statement): ForOfStatement; + function createContinue(label?: string | Identifier): ContinueStatement; + function updateContinue(node: ContinueStatement, label: Identifier | undefined): ContinueStatement; + function createBreak(label?: string | Identifier): BreakStatement; + function updateBreak(node: BreakStatement, label: Identifier | undefined): BreakStatement; + function createReturn(expression?: Expression): ReturnStatement; + function updateReturn(node: ReturnStatement, expression: Expression | undefined): ReturnStatement; + function createWith(expression: Expression, statement: Statement): WithStatement; + function updateWith(node: WithStatement, expression: Expression, statement: Statement): WithStatement; + function createSwitch(expression: Expression, caseBlock: CaseBlock): SwitchStatement; + function updateSwitch(node: SwitchStatement, expression: Expression, caseBlock: CaseBlock): SwitchStatement; + function createLabel(label: string | Identifier, statement: Statement): LabeledStatement; + function updateLabel(node: LabeledStatement, label: Identifier, statement: Statement): LabeledStatement; + function createThrow(expression: Expression): ThrowStatement; + function updateThrow(node: ThrowStatement, expression: Expression): ThrowStatement; + function createTry(tryBlock: Block, catchClause: CatchClause | undefined, finallyBlock: Block | undefined): TryStatement; + function updateTry(node: TryStatement, tryBlock: Block, catchClause: CatchClause | undefined, finallyBlock: Block | undefined): TryStatement; + function createDebuggerStatement(): DebuggerStatement; + function createVariableDeclaration(name: string | BindingName, type?: TypeNode, initializer?: Expression): VariableDeclaration; + function updateVariableDeclaration(node: VariableDeclaration, name: BindingName, type: TypeNode | undefined, initializer: Expression | undefined): VariableDeclaration; + function createVariableDeclarationList(declarations: ReadonlyArray, flags?: NodeFlags): VariableDeclarationList; + function updateVariableDeclarationList(node: VariableDeclarationList, declarations: ReadonlyArray): VariableDeclarationList; + function createFunctionDeclaration(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, asteriskToken: AsteriskToken | undefined, name: string | Identifier | undefined, typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode | undefined, body: Block | undefined): FunctionDeclaration; + function updateFunctionDeclaration(node: FunctionDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, asteriskToken: AsteriskToken | undefined, name: Identifier | undefined, typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode | undefined, body: Block | undefined): FunctionDeclaration; + function createClassDeclaration(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: string | Identifier | undefined, typeParameters: ReadonlyArray | undefined, heritageClauses: ReadonlyArray | undefined, members: ReadonlyArray): ClassDeclaration; + function updateClassDeclaration(node: ClassDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: Identifier | undefined, typeParameters: ReadonlyArray | undefined, heritageClauses: ReadonlyArray | undefined, members: ReadonlyArray): ClassDeclaration; + function createInterfaceDeclaration(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: string | Identifier, typeParameters: ReadonlyArray | undefined, heritageClauses: ReadonlyArray | undefined, members: ReadonlyArray): InterfaceDeclaration; + function updateInterfaceDeclaration(node: InterfaceDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: Identifier, typeParameters: ReadonlyArray | undefined, heritageClauses: ReadonlyArray | undefined, members: ReadonlyArray): InterfaceDeclaration; + function createTypeAliasDeclaration(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: string | Identifier, typeParameters: ReadonlyArray | undefined, type: TypeNode): TypeAliasDeclaration; + function updateTypeAliasDeclaration(node: TypeAliasDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: Identifier, typeParameters: ReadonlyArray | undefined, type: TypeNode): TypeAliasDeclaration; + function createEnumDeclaration(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: string | Identifier, members: ReadonlyArray): EnumDeclaration; + function updateEnumDeclaration(node: EnumDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: Identifier, members: ReadonlyArray): EnumDeclaration; + function createModuleDeclaration(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: ModuleName, body: ModuleBody | undefined, flags?: NodeFlags): ModuleDeclaration; + function updateModuleDeclaration(node: ModuleDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: ModuleName, body: ModuleBody | undefined): ModuleDeclaration; + function createModuleBlock(statements: ReadonlyArray): ModuleBlock; + function updateModuleBlock(node: ModuleBlock, statements: ReadonlyArray): ModuleBlock; + function createCaseBlock(clauses: ReadonlyArray): CaseBlock; + function updateCaseBlock(node: CaseBlock, clauses: ReadonlyArray): CaseBlock; + function createNamespaceExportDeclaration(name: string | Identifier): NamespaceExportDeclaration; + function updateNamespaceExportDeclaration(node: NamespaceExportDeclaration, name: Identifier): NamespaceExportDeclaration; + function createImportEqualsDeclaration(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: string | Identifier, moduleReference: ModuleReference): ImportEqualsDeclaration; + function updateImportEqualsDeclaration(node: ImportEqualsDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: Identifier, moduleReference: ModuleReference): ImportEqualsDeclaration; + function createImportDeclaration(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, importClause: ImportClause | undefined, moduleSpecifier: Expression): ImportDeclaration; + function updateImportDeclaration(node: ImportDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, importClause: ImportClause | undefined, moduleSpecifier: Expression): ImportDeclaration; + function createImportClause(name: Identifier | undefined, namedBindings: NamedImportBindings | undefined): ImportClause; + function updateImportClause(node: ImportClause, name: Identifier | undefined, namedBindings: NamedImportBindings | undefined): ImportClause; + function createNamespaceImport(name: Identifier): NamespaceImport; + function updateNamespaceImport(node: NamespaceImport, name: Identifier): NamespaceImport; + function createNamedImports(elements: ReadonlyArray): NamedImports; + function updateNamedImports(node: NamedImports, elements: ReadonlyArray): NamedImports; + function createImportSpecifier(propertyName: Identifier | undefined, name: Identifier): ImportSpecifier; + function updateImportSpecifier(node: ImportSpecifier, propertyName: Identifier | undefined, name: Identifier): ImportSpecifier; + function createExportAssignment(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, isExportEquals: boolean | undefined, expression: Expression): ExportAssignment; + function updateExportAssignment(node: ExportAssignment, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, expression: Expression): ExportAssignment; + function createExportDeclaration(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, exportClause: NamedExports | undefined, moduleSpecifier?: Expression): ExportDeclaration; + function updateExportDeclaration(node: ExportDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, exportClause: NamedExports | undefined, moduleSpecifier: Expression | undefined): ExportDeclaration; + function createNamedExports(elements: ReadonlyArray): NamedExports; + function updateNamedExports(node: NamedExports, elements: ReadonlyArray): NamedExports; + function createExportSpecifier(propertyName: string | Identifier | undefined, name: string | Identifier): ExportSpecifier; + function updateExportSpecifier(node: ExportSpecifier, propertyName: Identifier | undefined, name: Identifier): ExportSpecifier; + function createExternalModuleReference(expression: Expression): ExternalModuleReference; + function updateExternalModuleReference(node: ExternalModuleReference, expression: Expression): ExternalModuleReference; + function createJsxElement(openingElement: JsxOpeningElement, children: ReadonlyArray, closingElement: JsxClosingElement): JsxElement; + function updateJsxElement(node: JsxElement, openingElement: JsxOpeningElement, children: ReadonlyArray, closingElement: JsxClosingElement): JsxElement; + function createJsxSelfClosingElement(tagName: JsxTagNameExpression, typeArguments: ReadonlyArray | undefined, attributes: JsxAttributes): JsxSelfClosingElement; + function updateJsxSelfClosingElement(node: JsxSelfClosingElement, tagName: JsxTagNameExpression, typeArguments: ReadonlyArray | undefined, attributes: JsxAttributes): JsxSelfClosingElement; + function createJsxOpeningElement(tagName: JsxTagNameExpression, typeArguments: ReadonlyArray | undefined, attributes: JsxAttributes): JsxOpeningElement; + function updateJsxOpeningElement(node: JsxOpeningElement, tagName: JsxTagNameExpression, typeArguments: ReadonlyArray | undefined, attributes: JsxAttributes): JsxOpeningElement; + function createJsxClosingElement(tagName: JsxTagNameExpression): JsxClosingElement; + function updateJsxClosingElement(node: JsxClosingElement, tagName: JsxTagNameExpression): JsxClosingElement; + function createJsxFragment(openingFragment: JsxOpeningFragment, children: ReadonlyArray, closingFragment: JsxClosingFragment): JsxFragment; + function updateJsxFragment(node: JsxFragment, openingFragment: JsxOpeningFragment, children: ReadonlyArray, closingFragment: JsxClosingFragment): JsxFragment; + function createJsxAttribute(name: Identifier, initializer: StringLiteral | JsxExpression): JsxAttribute; + function updateJsxAttribute(node: JsxAttribute, name: Identifier, initializer: StringLiteral | JsxExpression): JsxAttribute; + function createJsxAttributes(properties: ReadonlyArray): JsxAttributes; + function updateJsxAttributes(node: JsxAttributes, properties: ReadonlyArray): JsxAttributes; + function createJsxSpreadAttribute(expression: Expression): JsxSpreadAttribute; + function updateJsxSpreadAttribute(node: JsxSpreadAttribute, expression: Expression): JsxSpreadAttribute; + function createJsxExpression(dotDotDotToken: DotDotDotToken | undefined, expression: Expression | undefined): JsxExpression; + function updateJsxExpression(node: JsxExpression, expression: Expression | undefined): JsxExpression; + function createCaseClause(expression: Expression, statements: ReadonlyArray): CaseClause; + function updateCaseClause(node: CaseClause, expression: Expression, statements: ReadonlyArray): CaseClause; + function createDefaultClause(statements: ReadonlyArray): DefaultClause; + function updateDefaultClause(node: DefaultClause, statements: ReadonlyArray): DefaultClause; + function createHeritageClause(token: HeritageClause["token"], types: ReadonlyArray): HeritageClause; + function updateHeritageClause(node: HeritageClause, types: ReadonlyArray): HeritageClause; + function createCatchClause(variableDeclaration: string | VariableDeclaration | undefined, block: Block): CatchClause; + function updateCatchClause(node: CatchClause, variableDeclaration: VariableDeclaration | undefined, block: Block): CatchClause; + function createPropertyAssignment(name: string | PropertyName, initializer: Expression): PropertyAssignment; + function updatePropertyAssignment(node: PropertyAssignment, name: PropertyName, initializer: Expression): PropertyAssignment; + function createShorthandPropertyAssignment(name: string | Identifier, objectAssignmentInitializer?: Expression): ShorthandPropertyAssignment; + function updateShorthandPropertyAssignment(node: ShorthandPropertyAssignment, name: Identifier, objectAssignmentInitializer: Expression | undefined): ShorthandPropertyAssignment; + function createSpreadAssignment(expression: Expression): SpreadAssignment; + function updateSpreadAssignment(node: SpreadAssignment, expression: Expression): SpreadAssignment; + function createEnumMember(name: string | PropertyName, initializer?: Expression): EnumMember; + function updateEnumMember(node: EnumMember, name: PropertyName, initializer: Expression | undefined): EnumMember; + function updateSourceFileNode(node: SourceFile, statements: ReadonlyArray, isDeclarationFile?: boolean, referencedFiles?: SourceFile["referencedFiles"], typeReferences?: SourceFile["typeReferenceDirectives"], hasNoDefaultLib?: boolean, libReferences?: SourceFile["libReferenceDirectives"]): SourceFile; + /** + * Creates a shallow, memberwise clone of a node for mutation. + */ + function getMutableClone(node: T): T; + /** + * Creates a synthetic statement to act as a placeholder for a not-emitted statement in + * order to preserve comments. + * + * @param original The original statement. + */ + function createNotEmittedStatement(original: Node): NotEmittedStatement; + /** + * Creates a synthetic expression to act as a placeholder for a not-emitted expression in + * order to preserve comments or sourcemap positions. + * + * @param expression The inner expression to emit. + * @param original The original outer expression. + * @param location The location for the expression. Defaults to the positions from "original" if provided. + */ + function createPartiallyEmittedExpression(expression: Expression, original?: Node): PartiallyEmittedExpression; + function updatePartiallyEmittedExpression(node: PartiallyEmittedExpression, expression: Expression): PartiallyEmittedExpression; + function createCommaList(elements: ReadonlyArray): CommaListExpression; + function updateCommaList(node: CommaListExpression, elements: ReadonlyArray): CommaListExpression; + function createBundle(sourceFiles: ReadonlyArray, prepends?: ReadonlyArray): Bundle; + function createUnparsedSourceFile(text: string): UnparsedSource; + function createUnparsedSourceFile(text: string, mapPath: string | undefined, map: string | undefined): UnparsedSource; + function createInputFiles(javascript: string, declaration: string): InputFiles; + function createInputFiles(javascript: string, declaration: string, javascriptMapPath: string | undefined, javascriptMapText: string | undefined, declarationMapPath: string | undefined, declarationMapText: string | undefined): InputFiles; + function updateBundle(node: Bundle, sourceFiles: ReadonlyArray, prepends?: ReadonlyArray): Bundle; + function createImmediatelyInvokedFunctionExpression(statements: ReadonlyArray): CallExpression; + function createImmediatelyInvokedFunctionExpression(statements: ReadonlyArray, param: ParameterDeclaration, paramValue: Expression): CallExpression; + function createImmediatelyInvokedArrowFunction(statements: ReadonlyArray): CallExpression; + function createImmediatelyInvokedArrowFunction(statements: ReadonlyArray, param: ParameterDeclaration, paramValue: Expression): CallExpression; + function createComma(left: Expression, right: Expression): Expression; + function createLessThan(left: Expression, right: Expression): Expression; + function createAssignment(left: ObjectLiteralExpression | ArrayLiteralExpression, right: Expression): DestructuringAssignment; + function createAssignment(left: Expression, right: Expression): BinaryExpression; + function createStrictEquality(left: Expression, right: Expression): BinaryExpression; + function createStrictInequality(left: Expression, right: Expression): BinaryExpression; + function createAdd(left: Expression, right: Expression): BinaryExpression; + function createSubtract(left: Expression, right: Expression): BinaryExpression; + function createPostfixIncrement(operand: Expression): PostfixUnaryExpression; + function createLogicalAnd(left: Expression, right: Expression): BinaryExpression; + function createLogicalOr(left: Expression, right: Expression): BinaryExpression; + function createLogicalNot(operand: Expression): PrefixUnaryExpression; + function createVoidZero(): VoidExpression; + function createExportDefault(expression: Expression): ExportAssignment; + function createExternalModuleExport(exportName: Identifier): ExportDeclaration; + /** + * Clears any EmitNode entries from parse-tree nodes. + * @param sourceFile A source file. + */ + function disposeEmitNodes(sourceFile: SourceFile): void; + function setTextRange(range: T, location: TextRange | undefined): T; + /** + * Sets flags that control emit behavior of a node. + */ + function setEmitFlags(node: T, emitFlags: EmitFlags): T; + /** + * Gets a custom text range to use when emitting source maps. + */ + function getSourceMapRange(node: Node): SourceMapRange; + /** + * Sets a custom text range to use when emitting source maps. + */ + function setSourceMapRange(node: T, range: SourceMapRange | undefined): T; + /** + * Create an external source map source file reference + */ + function createSourceMapSource(fileName: string, text: string, skipTrivia?: (pos: number) => number): SourceMapSource; + /** + * Gets the TextRange to use for source maps for a token of a node. + */ + function getTokenSourceMapRange(node: Node, token: SyntaxKind): SourceMapRange | undefined; + /** + * Sets the TextRange to use for source maps for a token of a node. + */ + function setTokenSourceMapRange(node: T, token: SyntaxKind, range: SourceMapRange | undefined): T; + /** + * Gets a custom text range to use when emitting comments. + */ + function getCommentRange(node: Node): TextRange; + /** + * Sets a custom text range to use when emitting comments. + */ + function setCommentRange(node: T, range: TextRange): T; + function getSyntheticLeadingComments(node: Node): SynthesizedComment[] | undefined; + function setSyntheticLeadingComments(node: T, comments: SynthesizedComment[] | undefined): T; + function addSyntheticLeadingComment(node: T, kind: SyntaxKind.SingleLineCommentTrivia | SyntaxKind.MultiLineCommentTrivia, text: string, hasTrailingNewLine?: boolean): T; + function getSyntheticTrailingComments(node: Node): SynthesizedComment[] | undefined; + function setSyntheticTrailingComments(node: T, comments: SynthesizedComment[] | undefined): T; + function addSyntheticTrailingComment(node: T, kind: SyntaxKind.SingleLineCommentTrivia | SyntaxKind.MultiLineCommentTrivia, text: string, hasTrailingNewLine?: boolean): T; + function moveSyntheticComments(node: T, original: Node): T; + /** + * Gets the constant value to emit for an expression. + */ + function getConstantValue(node: PropertyAccessExpression | ElementAccessExpression): string | number | undefined; + /** + * Sets the constant value to emit for an expression. + */ + function setConstantValue(node: PropertyAccessExpression | ElementAccessExpression, value: string | number): PropertyAccessExpression | ElementAccessExpression; + /** + * Adds an EmitHelper to a node. + */ + function addEmitHelper(node: T, helper: EmitHelper): T; + /** + * Add EmitHelpers to a node. + */ + function addEmitHelpers(node: T, helpers: EmitHelper[] | undefined): T; + /** + * Removes an EmitHelper from a node. + */ + function removeEmitHelper(node: Node, helper: EmitHelper): boolean; + /** + * Gets the EmitHelpers of a node. + */ + function getEmitHelpers(node: Node): EmitHelper[] | undefined; + /** + * Moves matching emit helpers from a source node to a target node. + */ + function moveEmitHelpers(source: Node, target: Node, predicate: (helper: EmitHelper) => boolean): void; + function setOriginalNode(node: T, original: Node | undefined): T; +} +declare namespace ts { + /** + * Visits a Node using the supplied visitor, possibly returning a new Node in its place. + * + * @param node The Node to visit. + * @param visitor The callback used to visit the Node. + * @param test A callback to execute to verify the Node is valid. + * @param lift An optional callback to execute to lift a NodeArray into a valid Node. + */ + function visitNode(node: T | undefined, visitor: Visitor | undefined, test?: (node: Node) => boolean, lift?: (node: NodeArray) => T): T; + /** + * Visits a Node using the supplied visitor, possibly returning a new Node in its place. + * + * @param node The Node to visit. + * @param visitor The callback used to visit the Node. + * @param test A callback to execute to verify the Node is valid. + * @param lift An optional callback to execute to lift a NodeArray into a valid Node. + */ + function visitNode(node: T | undefined, visitor: Visitor | undefined, test?: (node: Node) => boolean, lift?: (node: NodeArray) => T): T | undefined; + /** + * Visits a NodeArray using the supplied visitor, possibly returning a new NodeArray in its place. + * + * @param nodes The NodeArray to visit. + * @param visitor The callback used to visit a Node. + * @param test A node test to execute for each node. + * @param start An optional value indicating the starting offset at which to start visiting. + * @param count An optional value indicating the maximum number of nodes to visit. + */ + function visitNodes(nodes: NodeArray | undefined, visitor: Visitor, test?: (node: Node) => boolean, start?: number, count?: number): NodeArray; + /** + * Visits a NodeArray using the supplied visitor, possibly returning a new NodeArray in its place. + * + * @param nodes The NodeArray to visit. + * @param visitor The callback used to visit a Node. + * @param test A node test to execute for each node. + * @param start An optional value indicating the starting offset at which to start visiting. + * @param count An optional value indicating the maximum number of nodes to visit. + */ + function visitNodes(nodes: NodeArray | undefined, visitor: Visitor, test?: (node: Node) => boolean, start?: number, count?: number): NodeArray | undefined; + /** + * Starts a new lexical environment and visits a statement list, ending the lexical environment + * and merging hoisted declarations upon completion. + */ + function visitLexicalEnvironment(statements: NodeArray, visitor: Visitor, context: TransformationContext, start?: number, ensureUseStrict?: boolean): NodeArray; + /** + * Starts a new lexical environment and visits a parameter list, suspending the lexical + * environment upon completion. + */ + function visitParameterList(nodes: NodeArray | undefined, visitor: Visitor, context: TransformationContext, nodesVisitor?: typeof visitNodes): NodeArray; + /** + * Resumes a suspended lexical environment and visits a function body, ending the lexical + * environment and merging hoisted declarations upon completion. + */ + function visitFunctionBody(node: FunctionBody, visitor: Visitor, context: TransformationContext): FunctionBody; + /** + * Resumes a suspended lexical environment and visits a function body, ending the lexical + * environment and merging hoisted declarations upon completion. + */ + function visitFunctionBody(node: FunctionBody | undefined, visitor: Visitor, context: TransformationContext): FunctionBody | undefined; + /** + * Resumes a suspended lexical environment and visits a concise body, ending the lexical + * environment and merging hoisted declarations upon completion. + */ + function visitFunctionBody(node: ConciseBody, visitor: Visitor, context: TransformationContext): ConciseBody; + /** + * Visits each child of a Node using the supplied visitor, possibly returning a new Node of the same kind in its place. + * + * @param node The Node whose children will be visited. + * @param visitor The callback used to visit each child. + * @param context A lexical environment context for the visitor. + */ + function visitEachChild(node: T, visitor: Visitor, context: TransformationContext): T; + /** + * Visits each child of a Node using the supplied visitor, possibly returning a new Node of the same kind in its place. + * + * @param node The Node whose children will be visited. + * @param visitor The callback used to visit each child. + * @param context A lexical environment context for the visitor. + */ + function visitEachChild(node: T | undefined, visitor: Visitor, context: TransformationContext, nodesVisitor?: typeof visitNodes, tokenVisitor?: Visitor): T | undefined; +} +declare namespace ts { + function createPrinter(printerOptions?: PrinterOptions, handlers?: PrintHandlers): Printer; +} +declare namespace ts { + function findConfigFile(searchPath: string, fileExists: (fileName: string) => boolean, configName?: string): string | undefined; + function resolveTripleslashReference(moduleName: string, containingFile: string): string; + function createCompilerHost(options: CompilerOptions, setParentNodes?: boolean): CompilerHost; + function getPreEmitDiagnostics(program: Program, sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray; + interface FormatDiagnosticsHost { + getCurrentDirectory(): string; + getCanonicalFileName(fileName: string): string; + getNewLine(): string; + } + function formatDiagnostics(diagnostics: ReadonlyArray, host: FormatDiagnosticsHost): string; + function formatDiagnostic(diagnostic: Diagnostic, host: FormatDiagnosticsHost): string; + function formatDiagnosticsWithColorAndContext(diagnostics: ReadonlyArray, host: FormatDiagnosticsHost): string; + function flattenDiagnosticMessageText(messageText: string | DiagnosticMessageChain | undefined, newLine: string): string; + function getConfigFileParsingDiagnostics(configFileParseResult: ParsedCommandLine): ReadonlyArray; + /** + * Create a new 'Program' instance. A Program is an immutable collection of 'SourceFile's and a 'CompilerOptions' + * that represent a compilation unit. + * + * Creating a program proceeds from a set of root files, expanding the set of inputs by following imports and + * triple-slash-reference-path directives transitively. '@types' and triple-slash-reference-types are also pulled in. + * + * @param createProgramOptions - The options for creating a program. + * @returns A 'Program' object. + */ + function createProgram(createProgramOptions: CreateProgramOptions): Program; + /** + * Create a new 'Program' instance. A Program is an immutable collection of 'SourceFile's and a 'CompilerOptions' + * that represent a compilation unit. + * + * Creating a program proceeds from a set of root files, expanding the set of inputs by following imports and + * triple-slash-reference-path directives transitively. '@types' and triple-slash-reference-types are also pulled in. + * + * @param rootNames - A set of root files. + * @param options - The compiler options which should be used. + * @param host - The host interacts with the underlying file system. + * @param oldProgram - Reuses an old program structure. + * @param configFileParsingDiagnostics - error during config file parsing + * @returns A 'Program' object. + */ + function createProgram(rootNames: ReadonlyArray, options: CompilerOptions, host?: CompilerHost, oldProgram?: Program, configFileParsingDiagnostics?: ReadonlyArray): Program; + /** @deprecated */ interface ResolveProjectReferencePathHost { + fileExists(fileName: string): boolean; + } + /** + * Returns the target config filename of a project reference. + * Note: The file might not exist. + */ + function resolveProjectReferencePath(ref: ProjectReference): ResolvedConfigFileName; + /** @deprecated */ function resolveProjectReferencePath(host: ResolveProjectReferencePathHost, ref: ProjectReference): ResolvedConfigFileName; +} +declare namespace ts { + interface EmitOutput { + outputFiles: OutputFile[]; + emitSkipped: boolean; + } + interface OutputFile { + name: string; + writeByteOrderMark: boolean; + text: string; + } +} +declare namespace ts { + type AffectedFileResult = { + result: T; + affected: SourceFile | Program; + } | undefined; + interface BuilderProgramHost { + /** + * return true if file names are treated with case sensitivity + */ + useCaseSensitiveFileNames(): boolean; + /** + * If provided this would be used this hash instead of actual file shape text for detecting changes + */ + createHash?: (data: string) => string; + /** + * When emit or emitNextAffectedFile are called without writeFile, + * this callback if present would be used to write files + */ + writeFile?: WriteFileCallback; + } + /** + * Builder to manage the program state changes + */ + interface BuilderProgram { + /** + * Returns current program + */ + getProgram(): Program; + /** + * Get compiler options of the program + */ + getCompilerOptions(): CompilerOptions; + /** + * Get the source file in the program with file name + */ + getSourceFile(fileName: string): SourceFile | undefined; + /** + * Get a list of files in the program + */ + getSourceFiles(): ReadonlyArray; + /** + * Get the diagnostics for compiler options + */ + getOptionsDiagnostics(cancellationToken?: CancellationToken): ReadonlyArray; + /** + * Get the diagnostics that dont belong to any file + */ + getGlobalDiagnostics(cancellationToken?: CancellationToken): ReadonlyArray; + /** + * Get the diagnostics from config file parsing + */ + getConfigFileParsingDiagnostics(): ReadonlyArray; + /** + * Get the syntax diagnostics, for all source files if source file is not supplied + */ + getSyntacticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray; + /** + * Get all the dependencies of the file + */ + getAllDependencies(sourceFile: SourceFile): ReadonlyArray; + /** + * Gets the semantic diagnostics from the program corresponding to this state of file (if provided) or whole program + * The semantic diagnostics are cached and managed here + * Note that it is assumed that when asked about semantic diagnostics through this API, + * the file has been taken out of affected files so it is safe to use cache or get from program and cache the diagnostics + * In case of SemanticDiagnosticsBuilderProgram if the source file is not provided, + * it will iterate through all the affected files, to ensure that cache stays valid and yet provide a way to get all semantic diagnostics + */ + getSemanticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray; + /** + * Emits the JavaScript and declaration files. + * When targetSource file is specified, emits the files corresponding to that source file, + * otherwise for the whole program. + * In case of EmitAndSemanticDiagnosticsBuilderProgram, when targetSourceFile is specified, + * it is assumed that that file is handled from affected file list. If targetSourceFile is not specified, + * it will only emit all the affected files instead of whole program + * + * The first of writeFile if provided, writeFile of BuilderProgramHost if provided, writeFile of compiler host + * in that order would be used to write the files + */ + emit(targetSourceFile?: SourceFile, writeFile?: WriteFileCallback, cancellationToken?: CancellationToken, emitOnlyDtsFiles?: boolean, customTransformers?: CustomTransformers): EmitResult; + /** + * Get the current directory of the program + */ + getCurrentDirectory(): string; + } + /** + * The builder that caches the semantic diagnostics for the program and handles the changed files and affected files + */ + interface SemanticDiagnosticsBuilderProgram extends BuilderProgram { + /** + * Gets the semantic diagnostics from the program for the next affected file and caches it + * Returns undefined if the iteration is complete + */ + getSemanticDiagnosticsOfNextAffectedFile(cancellationToken?: CancellationToken, ignoreSourceFile?: (sourceFile: SourceFile) => boolean): AffectedFileResult>; + } + /** + * The builder that can handle the changes in program and iterate through changed file to emit the files + * The semantic diagnostics are cached per file and managed by clearing for the changed/affected files + */ + interface EmitAndSemanticDiagnosticsBuilderProgram extends BuilderProgram { + /** + * Emits the next affected file's emit result (EmitResult and sourceFiles emitted) or returns undefined if iteration is complete + * The first of writeFile if provided, writeFile of BuilderProgramHost if provided, writeFile of compiler host + * in that order would be used to write the files + */ + emitNextAffectedFile(writeFile?: WriteFileCallback, cancellationToken?: CancellationToken, emitOnlyDtsFiles?: boolean, customTransformers?: CustomTransformers): AffectedFileResult; + } + /** + * Create the builder to manage semantic diagnostics and cache them + */ + function createSemanticDiagnosticsBuilderProgram(newProgram: Program, host: BuilderProgramHost, oldProgram?: SemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): SemanticDiagnosticsBuilderProgram; + function createSemanticDiagnosticsBuilderProgram(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: SemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray, projectReferences?: ReadonlyArray): SemanticDiagnosticsBuilderProgram; + /** + * Create the builder that can handle the changes in program and iterate through changed files + * to emit the those files and manage semantic diagnostics cache as well + */ + function createEmitAndSemanticDiagnosticsBuilderProgram(newProgram: Program, host: BuilderProgramHost, oldProgram?: EmitAndSemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): EmitAndSemanticDiagnosticsBuilderProgram; + function createEmitAndSemanticDiagnosticsBuilderProgram(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: EmitAndSemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray, projectReferences?: ReadonlyArray): EmitAndSemanticDiagnosticsBuilderProgram; + /** + * Creates a builder thats just abstraction over program and can be used with watch + */ + function createAbstractBuilder(newProgram: Program, host: BuilderProgramHost, oldProgram?: BuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): BuilderProgram; + function createAbstractBuilder(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: BuilderProgram, configFileParsingDiagnostics?: ReadonlyArray, projectReferences?: ReadonlyArray): BuilderProgram; +} +declare namespace ts { + type WatchStatusReporter = (diagnostic: Diagnostic, newLine: string, options: CompilerOptions) => void; + /** Create the program with rootNames and options, if they are undefined, oldProgram and new configFile diagnostics create new program */ + type CreateProgram = (rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: T, configFileParsingDiagnostics?: ReadonlyArray, projectReferences?: ReadonlyArray | undefined) => T; + /** Host that has watch functionality used in --watch mode */ + interface WatchHost { + /** If provided, called with Diagnostic message that informs about change in watch status */ + onWatchStatusChange?(diagnostic: Diagnostic, newLine: string, options: CompilerOptions): void; + /** Used to watch changes in source files, missing files needed to update the program or config file */ + watchFile(path: string, callback: FileWatcherCallback, pollingInterval?: number): FileWatcher; + /** Used to watch resolved module's failed lookup locations, config file specs, type roots where auto type reference directives are added */ + watchDirectory(path: string, callback: DirectoryWatcherCallback, recursive?: boolean): FileWatcher; + /** If provided, will be used to set delayed compilation, so that multiple changes in short span are compiled together */ + setTimeout?(callback: (...args: any[]) => void, ms: number, ...args: any[]): any; + /** If provided, will be used to reset existing delayed compilation */ + clearTimeout?(timeoutId: any): void; + } + interface WatchCompilerHost extends WatchHost { + /** + * Used to create the program when need for program creation or recreation detected + */ + createProgram: CreateProgram; + /** If provided, callback to invoke after every new program creation */ + afterProgramCreate?(program: T): void; + useCaseSensitiveFileNames(): boolean; + getNewLine(): string; + getCurrentDirectory(): string; + getDefaultLibFileName(options: CompilerOptions): string; + getDefaultLibLocation?(): string; + createHash?(data: string): string; + /** + * Use to check file presence for source files and + * if resolveModuleNames is not provided (complier is in charge of module resolution) then module files as well + */ + fileExists(path: string): boolean; + /** + * Use to read file text for source files and + * if resolveModuleNames is not provided (complier is in charge of module resolution) then module files as well + */ + readFile(path: string, encoding?: string): string | undefined; + /** If provided, used for module resolution as well as to handle directory structure */ + directoryExists?(path: string): boolean; + /** If provided, used in resolutions as well as handling directory structure */ + getDirectories?(path: string): string[]; + /** If provided, used to cache and handle directory structure modifications */ + readDirectory?(path: string, extensions?: ReadonlyArray, exclude?: ReadonlyArray, include?: ReadonlyArray, depth?: number): string[]; + /** Symbol links resolution */ + realpath?(path: string): string; + /** If provided would be used to write log about compilation */ + trace?(s: string): void; + /** If provided is used to get the environment variable */ + getEnvironmentVariable?(name: string): string | undefined; + /** If provided, used to resolve the module names, otherwise typescript's default module resolution */ + resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[], redirectedReference?: ResolvedProjectReference): (ResolvedModule | undefined)[]; + /** If provided, used to resolve type reference directives, otherwise typescript's default resolution */ + resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string, redirectedReference?: ResolvedProjectReference): (ResolvedTypeReferenceDirective | undefined)[]; + } + /** + * Host to create watch with root files and options + */ + interface WatchCompilerHostOfFilesAndCompilerOptions extends WatchCompilerHost { + /** root files to use to generate program */ + rootFiles: string[]; + /** Compiler options */ + options: CompilerOptions; + /** Project References */ + projectReferences?: ReadonlyArray; + } + /** + * Host to create watch with config file + */ + interface WatchCompilerHostOfConfigFile extends WatchCompilerHost, ConfigFileDiagnosticsReporter { + /** Name of the config file to compile */ + configFileName: string; + /** Options to extend */ + optionsToExtend?: CompilerOptions; + /** + * Used to generate source file names from the config file and its include, exclude, files rules + * and also to cache the directory stucture + */ + readDirectory(path: string, extensions?: ReadonlyArray, exclude?: ReadonlyArray, include?: ReadonlyArray, depth?: number): string[]; + } + interface Watch { + /** Synchronize with host and get updated program */ + getProgram(): T; + } + /** + * Creates the watch what generates program using the config file + */ + interface WatchOfConfigFile extends Watch { + } + /** + * Creates the watch that generates program using the root files and compiler options + */ + interface WatchOfFilesAndCompilerOptions extends Watch { + /** Updates the root files in the program, only if this is not config file compilation */ + updateRootFileNames(fileNames: string[]): void; + } + /** + * Create the watch compiler host for either configFile or fileNames and its options + */ + function createWatchCompilerHost(configFileName: string, optionsToExtend: CompilerOptions | undefined, system: System, createProgram?: CreateProgram, reportDiagnostic?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter): WatchCompilerHostOfConfigFile; + function createWatchCompilerHost(rootFiles: string[], options: CompilerOptions, system: System, createProgram?: CreateProgram, reportDiagnostic?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter, projectReferences?: ReadonlyArray): WatchCompilerHostOfFilesAndCompilerOptions; + /** + * Creates the watch from the host for root files and compiler options + */ + function createWatchProgram(host: WatchCompilerHostOfFilesAndCompilerOptions): WatchOfFilesAndCompilerOptions; + /** + * Creates the watch from the host for config file + */ + function createWatchProgram(host: WatchCompilerHostOfConfigFile): WatchOfConfigFile; +} +declare namespace ts.server { + type ActionSet = "action::set"; + type ActionInvalidate = "action::invalidate"; + type ActionPackageInstalled = "action::packageInstalled"; + type ActionValueInspected = "action::valueInspected"; + type EventTypesRegistry = "event::typesRegistry"; + type EventBeginInstallTypes = "event::beginInstallTypes"; + type EventEndInstallTypes = "event::endInstallTypes"; + type EventInitializationFailed = "event::initializationFailed"; + interface TypingInstallerResponse { + readonly kind: ActionSet | ActionInvalidate | EventTypesRegistry | ActionPackageInstalled | ActionValueInspected | EventBeginInstallTypes | EventEndInstallTypes | EventInitializationFailed; + } + interface TypingInstallerRequestWithProjectName { + readonly projectName: string; + } + interface DiscoverTypings extends TypingInstallerRequestWithProjectName { + readonly fileNames: string[]; + readonly projectRootPath: Path; + readonly compilerOptions: CompilerOptions; + readonly typeAcquisition: TypeAcquisition; + readonly unresolvedImports: SortedReadonlyArray; + readonly cachePath?: string; + readonly kind: "discover"; + } + interface CloseProject extends TypingInstallerRequestWithProjectName { + readonly kind: "closeProject"; + } + interface TypesRegistryRequest { + readonly kind: "typesRegistry"; + } + interface InstallPackageRequest extends TypingInstallerRequestWithProjectName { + readonly kind: "installPackage"; + readonly fileName: Path; + readonly packageName: string; + readonly projectRootPath: Path; + } + interface PackageInstalledResponse extends ProjectResponse { + readonly kind: ActionPackageInstalled; + readonly success: boolean; + readonly message: string; + } + interface InitializationFailedResponse extends TypingInstallerResponse { + readonly kind: EventInitializationFailed; + readonly message: string; + } + interface ProjectResponse extends TypingInstallerResponse { + readonly projectName: string; + } + interface InvalidateCachedTypings extends ProjectResponse { + readonly kind: ActionInvalidate; + } + interface InstallTypes extends ProjectResponse { + readonly kind: EventBeginInstallTypes | EventEndInstallTypes; + readonly eventId: number; + readonly typingsInstallerVersion: string; + readonly packagesToInstall: ReadonlyArray; + } + interface BeginInstallTypes extends InstallTypes { + readonly kind: EventBeginInstallTypes; + } + interface EndInstallTypes extends InstallTypes { + readonly kind: EventEndInstallTypes; + readonly installSuccess: boolean; + } + interface SetTypings extends ProjectResponse { + readonly typeAcquisition: TypeAcquisition; + readonly compilerOptions: CompilerOptions; + readonly typings: string[]; + readonly unresolvedImports: SortedReadonlyArray; + readonly kind: ActionSet; + } +} +declare namespace ts { + interface Node { + getSourceFile(): SourceFile; + getChildCount(sourceFile?: SourceFile): number; + getChildAt(index: number, sourceFile?: SourceFile): Node; + getChildren(sourceFile?: SourceFile): Node[]; + getStart(sourceFile?: SourceFile, includeJsDocComment?: boolean): number; + getFullStart(): number; + getEnd(): number; + getWidth(sourceFile?: SourceFileLike): number; + getFullWidth(): number; + getLeadingTriviaWidth(sourceFile?: SourceFile): number; + getFullText(sourceFile?: SourceFile): string; + getText(sourceFile?: SourceFile): string; + getFirstToken(sourceFile?: SourceFile): Node | undefined; + getLastToken(sourceFile?: SourceFile): Node | undefined; + forEachChild(cbNode: (node: Node) => T | undefined, cbNodeArray?: (nodes: NodeArray) => T | undefined): T | undefined; + } + interface Identifier { + readonly text: string; + } + interface Symbol { + readonly name: string; + getFlags(): SymbolFlags; + getEscapedName(): __String; + getName(): string; + getDeclarations(): Declaration[] | undefined; + getDocumentationComment(typeChecker: TypeChecker | undefined): SymbolDisplayPart[]; + getJsDocTags(): JSDocTagInfo[]; + } + interface Type { + getFlags(): TypeFlags; + getSymbol(): Symbol | undefined; + getProperties(): Symbol[]; + getProperty(propertyName: string): Symbol | undefined; + getApparentProperties(): Symbol[]; + getCallSignatures(): ReadonlyArray; + getConstructSignatures(): ReadonlyArray; + getStringIndexType(): Type | undefined; + getNumberIndexType(): Type | undefined; + getBaseTypes(): BaseType[] | undefined; + getNonNullableType(): Type; + getConstraint(): Type | undefined; + getDefault(): Type | undefined; + isUnion(): this is UnionType; + isIntersection(): this is IntersectionType; + isUnionOrIntersection(): this is UnionOrIntersectionType; + isLiteral(): this is LiteralType; + isStringLiteral(): this is StringLiteralType; + isNumberLiteral(): this is NumberLiteralType; + isTypeParameter(): this is TypeParameter; + isClassOrInterface(): this is InterfaceType; + isClass(): this is InterfaceType; + } + interface Signature { + getDeclaration(): SignatureDeclaration; + getTypeParameters(): TypeParameter[] | undefined; + getParameters(): Symbol[]; + getReturnType(): Type; + getDocumentationComment(typeChecker: TypeChecker | undefined): SymbolDisplayPart[]; + getJsDocTags(): JSDocTagInfo[]; + } + interface SourceFile { + getLineAndCharacterOfPosition(pos: number): LineAndCharacter; + getLineEndOfPosition(pos: number): number; + getLineStarts(): ReadonlyArray; + getPositionOfLineAndCharacter(line: number, character: number): number; + update(newText: string, textChangeRange: TextChangeRange): SourceFile; + } + interface SourceFileLike { + getLineAndCharacterOfPosition(pos: number): LineAndCharacter; + } + interface SourceMapSource { + getLineAndCharacterOfPosition(pos: number): LineAndCharacter; + } + /** + * Represents an immutable snapshot of a script at a specified time.Once acquired, the + * snapshot is observably immutable. i.e. the same calls with the same parameters will return + * the same values. + */ + interface IScriptSnapshot { + /** Gets a portion of the script snapshot specified by [start, end). */ + getText(start: number, end: number): string; + /** Gets the length of this script snapshot. */ + getLength(): number; + /** + * Gets the TextChangeRange that describe how the text changed between this text and + * an older version. This information is used by the incremental parser to determine + * what sections of the script need to be re-parsed. 'undefined' can be returned if the + * change range cannot be determined. However, in that case, incremental parsing will + * not happen and the entire document will be re - parsed. + */ + getChangeRange(oldSnapshot: IScriptSnapshot): TextChangeRange | undefined; + /** Releases all resources held by this script snapshot */ + dispose?(): void; + } + namespace ScriptSnapshot { + function fromString(text: string): IScriptSnapshot; + } + interface PreProcessedFileInfo { + referencedFiles: FileReference[]; + typeReferenceDirectives: FileReference[]; + libReferenceDirectives: FileReference[]; + importedFiles: FileReference[]; + ambientExternalModules?: string[]; + isLibFile: boolean; + } + interface HostCancellationToken { + isCancellationRequested(): boolean; + } + interface InstallPackageOptions { + fileName: Path; + packageName: string; + } + interface LanguageServiceHost extends GetEffectiveTypeRootsHost { + getCompilationSettings(): CompilerOptions; + getNewLine?(): string; + getProjectVersion?(): string; + getScriptFileNames(): string[]; + getScriptKind?(fileName: string): ScriptKind; + getScriptVersion(fileName: string): string; + getScriptSnapshot(fileName: string): IScriptSnapshot | undefined; + getProjectReferences?(): ReadonlyArray | undefined; + getLocalizedDiagnosticMessages?(): any; + getCancellationToken?(): HostCancellationToken; + getCurrentDirectory(): string; + getDefaultLibFileName(options: CompilerOptions): string; + log?(s: string): void; + trace?(s: string): void; + error?(s: string): void; + useCaseSensitiveFileNames?(): boolean; + readDirectory?(path: string, extensions?: ReadonlyArray, exclude?: ReadonlyArray, include?: ReadonlyArray, depth?: number): string[]; + readFile?(path: string, encoding?: string): string | undefined; + realpath?(path: string): string; + fileExists?(path: string): boolean; + getTypeRootsVersion?(): number; + resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[], redirectedReference?: ResolvedProjectReference): (ResolvedModule | undefined)[]; + getResolvedModuleWithFailedLookupLocationsFromCache?(modulename: string, containingFile: string): ResolvedModuleWithFailedLookupLocations | undefined; + resolveTypeReferenceDirectives?(typeDirectiveNames: string[], containingFile: string, redirectedReference?: ResolvedProjectReference): (ResolvedTypeReferenceDirective | undefined)[]; + getDirectories?(directoryName: string): string[]; + /** + * Gets a set of custom transformers to use during emit. + */ + getCustomTransformers?(): CustomTransformers | undefined; + isKnownTypesPackageName?(name: string): boolean; + installPackage?(options: InstallPackageOptions): Promise; + writeFile?(fileName: string, content: string): void; + } + type WithMetadata = T & { + metadata?: unknown; + }; + interface LanguageService { + cleanupSemanticCache(): void; + getSyntacticDiagnostics(fileName: string): DiagnosticWithLocation[]; + /** The first time this is called, it will return global diagnostics (no location). */ + getSemanticDiagnostics(fileName: string): Diagnostic[]; + getSuggestionDiagnostics(fileName: string): DiagnosticWithLocation[]; + getCompilerOptionsDiagnostics(): Diagnostic[]; + /** + * @deprecated Use getEncodedSyntacticClassifications instead. + */ + getSyntacticClassifications(fileName: string, span: TextSpan): ClassifiedSpan[]; + /** + * @deprecated Use getEncodedSemanticClassifications instead. + */ + getSemanticClassifications(fileName: string, span: TextSpan): ClassifiedSpan[]; + getEncodedSyntacticClassifications(fileName: string, span: TextSpan): Classifications; + getEncodedSemanticClassifications(fileName: string, span: TextSpan): Classifications; + getCompletionsAtPosition(fileName: string, position: number, options: GetCompletionsAtPositionOptions | undefined): WithMetadata | undefined; + getCompletionEntryDetails(fileName: string, position: number, name: string, formatOptions: FormatCodeOptions | FormatCodeSettings | undefined, source: string | undefined, preferences: UserPreferences | undefined): CompletionEntryDetails | undefined; + getCompletionEntrySymbol(fileName: string, position: number, name: string, source: string | undefined): Symbol | undefined; + getQuickInfoAtPosition(fileName: string, position: number): QuickInfo | undefined; + getNameOrDottedNameSpan(fileName: string, startPos: number, endPos: number): TextSpan | undefined; + getBreakpointStatementAtPosition(fileName: string, position: number): TextSpan | undefined; + getSignatureHelpItems(fileName: string, position: number, options: SignatureHelpItemsOptions | undefined): SignatureHelpItems | undefined; + getRenameInfo(fileName: string, position: number): RenameInfo; + findRenameLocations(fileName: string, position: number, findInStrings: boolean, findInComments: boolean): ReadonlyArray | undefined; + getDefinitionAtPosition(fileName: string, position: number): ReadonlyArray | undefined; + getDefinitionAndBoundSpan(fileName: string, position: number): DefinitionInfoAndBoundSpan | undefined; + getTypeDefinitionAtPosition(fileName: string, position: number): ReadonlyArray | undefined; + getImplementationAtPosition(fileName: string, position: number): ReadonlyArray | undefined; + getReferencesAtPosition(fileName: string, position: number): ReferenceEntry[] | undefined; + findReferences(fileName: string, position: number): ReferencedSymbol[] | undefined; + getDocumentHighlights(fileName: string, position: number, filesToSearch: string[]): DocumentHighlights[] | undefined; + /** @deprecated */ + getOccurrencesAtPosition(fileName: string, position: number): ReadonlyArray | undefined; + getNavigateToItems(searchValue: string, maxResultCount?: number, fileName?: string, excludeDtsFiles?: boolean): NavigateToItem[]; + getNavigationBarItems(fileName: string): NavigationBarItem[]; + getNavigationTree(fileName: string): NavigationTree; + getOutliningSpans(fileName: string): OutliningSpan[]; + getTodoComments(fileName: string, descriptors: TodoCommentDescriptor[]): TodoComment[]; + getBraceMatchingAtPosition(fileName: string, position: number): TextSpan[]; + getIndentationAtPosition(fileName: string, position: number, options: EditorOptions | EditorSettings): number; + getFormattingEditsForRange(fileName: string, start: number, end: number, options: FormatCodeOptions | FormatCodeSettings): TextChange[]; + getFormattingEditsForDocument(fileName: string, options: FormatCodeOptions | FormatCodeSettings): TextChange[]; + getFormattingEditsAfterKeystroke(fileName: string, position: number, key: string, options: FormatCodeOptions | FormatCodeSettings): TextChange[]; + getDocCommentTemplateAtPosition(fileName: string, position: number): TextInsertion | undefined; + isValidBraceCompletionAtPosition(fileName: string, position: number, openingBrace: number): boolean; + /** + * This will return a defined result if the position is after the `>` of the opening tag, or somewhere in the text, of a JSXElement with no closing tag. + * Editors should call this after `>` is typed. + */ + getJsxClosingTagAtPosition(fileName: string, position: number): JsxClosingTagInfo | undefined; + getSpanOfEnclosingComment(fileName: string, position: number, onlyMultiLine: boolean): TextSpan | undefined; + toLineColumnOffset?(fileName: string, position: number): LineAndCharacter; + getCodeFixesAtPosition(fileName: string, start: number, end: number, errorCodes: ReadonlyArray, formatOptions: FormatCodeSettings, preferences: UserPreferences): ReadonlyArray; + getCombinedCodeFix(scope: CombinedCodeFixScope, fixId: {}, formatOptions: FormatCodeSettings, preferences: UserPreferences): CombinedCodeActions; + applyCodeActionCommand(action: CodeActionCommand, formatSettings?: FormatCodeSettings): Promise; + applyCodeActionCommand(action: CodeActionCommand[], formatSettings?: FormatCodeSettings): Promise; + applyCodeActionCommand(action: CodeActionCommand | CodeActionCommand[], formatSettings?: FormatCodeSettings): Promise; + /** @deprecated `fileName` will be ignored */ + applyCodeActionCommand(fileName: string, action: CodeActionCommand): Promise; + /** @deprecated `fileName` will be ignored */ + applyCodeActionCommand(fileName: string, action: CodeActionCommand[]): Promise; + /** @deprecated `fileName` will be ignored */ + applyCodeActionCommand(fileName: string, action: CodeActionCommand | CodeActionCommand[]): Promise; + getApplicableRefactors(fileName: string, positionOrRange: number | TextRange, preferences: UserPreferences | undefined): ApplicableRefactorInfo[]; + getEditsForRefactor(fileName: string, formatOptions: FormatCodeSettings, positionOrRange: number | TextRange, refactorName: string, actionName: string, preferences: UserPreferences | undefined): RefactorEditInfo | undefined; + organizeImports(scope: OrganizeImportsScope, formatOptions: FormatCodeSettings, preferences: UserPreferences | undefined): ReadonlyArray; + getEditsForFileRename(oldFilePath: string, newFilePath: string, formatOptions: FormatCodeSettings, preferences: UserPreferences | undefined): ReadonlyArray; + getEmitOutput(fileName: string, emitOnlyDtsFiles?: boolean): EmitOutput; + getProgram(): Program | undefined; + dispose(): void; + } + interface JsxClosingTagInfo { + readonly newText: string; + } + interface CombinedCodeFixScope { + type: "file"; + fileName: string; + } + type OrganizeImportsScope = CombinedCodeFixScope; + type CompletionsTriggerCharacter = "." | '"' | "'" | "`" | "/" | "@" | "<"; + interface GetCompletionsAtPositionOptions extends UserPreferences { + /** + * If the editor is asking for completions because a certain character was typed + * (as opposed to when the user explicitly requested them) this should be set. + */ + triggerCharacter?: CompletionsTriggerCharacter; + /** @deprecated Use includeCompletionsForModuleExports */ + includeExternalModuleExports?: boolean; + /** @deprecated Use includeCompletionsWithInsertText */ + includeInsertTextCompletions?: boolean; + } + type SignatureHelpTriggerCharacter = "," | "(" | "<"; + type SignatureHelpRetriggerCharacter = SignatureHelpTriggerCharacter | ")"; + interface SignatureHelpItemsOptions { + triggerReason?: SignatureHelpTriggerReason; + } + type SignatureHelpTriggerReason = SignatureHelpInvokedReason | SignatureHelpCharacterTypedReason | SignatureHelpRetriggeredReason; + /** + * Signals that the user manually requested signature help. + * The language service will unconditionally attempt to provide a result. + */ + interface SignatureHelpInvokedReason { + kind: "invoked"; + triggerCharacter?: undefined; + } + /** + * Signals that the signature help request came from a user typing a character. + * Depending on the character and the syntactic context, the request may or may not be served a result. + */ + interface SignatureHelpCharacterTypedReason { + kind: "characterTyped"; + /** + * Character that was responsible for triggering signature help. + */ + triggerCharacter: SignatureHelpTriggerCharacter; + } + /** + * Signals that this signature help request came from typing a character or moving the cursor. + * This should only occur if a signature help session was already active and the editor needs to see if it should adjust. + * The language service will unconditionally attempt to provide a result. + * `triggerCharacter` can be `undefined` for a retrigger caused by a cursor move. + */ + interface SignatureHelpRetriggeredReason { + kind: "retrigger"; + /** + * Character that was responsible for triggering signature help. + */ + triggerCharacter?: SignatureHelpRetriggerCharacter; + } + interface ApplyCodeActionCommandResult { + successMessage: string; + } + interface Classifications { + spans: number[]; + endOfLineState: EndOfLineState; + } + interface ClassifiedSpan { + textSpan: TextSpan; + classificationType: ClassificationTypeNames; + } + /** + * Navigation bar interface designed for visual studio's dual-column layout. + * This does not form a proper tree. + * The navbar is returned as a list of top-level items, each of which has a list of child items. + * Child items always have an empty array for their `childItems`. + */ + interface NavigationBarItem { + text: string; + kind: ScriptElementKind; + kindModifiers: string; + spans: TextSpan[]; + childItems: NavigationBarItem[]; + indent: number; + bolded: boolean; + grayed: boolean; + } + /** + * Node in a tree of nested declarations in a file. + * The top node is always a script or module node. + */ + interface NavigationTree { + /** Name of the declaration, or a short description, e.g. "". */ + text: string; + kind: ScriptElementKind; + /** ScriptElementKindModifier separated by commas, e.g. "public,abstract" */ + kindModifiers: string; + /** + * Spans of the nodes that generated this declaration. + * There will be more than one if this is the result of merging. + */ + spans: TextSpan[]; + nameSpan: TextSpan | undefined; + /** Present if non-empty */ + childItems?: NavigationTree[]; + } + interface TodoCommentDescriptor { + text: string; + priority: number; + } + interface TodoComment { + descriptor: TodoCommentDescriptor; + message: string; + position: number; + } + interface TextChange { + span: TextSpan; + newText: string; + } + interface FileTextChanges { + fileName: string; + textChanges: TextChange[]; + isNewFile?: boolean; + } + interface CodeAction { + /** Description of the code action to display in the UI of the editor */ + description: string; + /** Text changes to apply to each file as part of the code action */ + changes: FileTextChanges[]; + /** + * If the user accepts the code fix, the editor should send the action back in a `applyAction` request. + * This allows the language service to have side effects (e.g. installing dependencies) upon a code fix. + */ + commands?: CodeActionCommand[]; + } + interface CodeFixAction extends CodeAction { + /** Short name to identify the fix, for use by telemetry. */ + fixName: string; + /** + * If present, one may call 'getCombinedCodeFix' with this fixId. + * This may be omitted to indicate that the code fix can't be applied in a group. + */ + fixId?: {}; + fixAllDescription?: string; + } + interface CombinedCodeActions { + changes: ReadonlyArray; + commands?: ReadonlyArray; + } + type CodeActionCommand = InstallPackageAction | GenerateTypesAction; + interface InstallPackageAction { + } + interface GenerateTypesAction extends GenerateTypesOptions { + } + interface GenerateTypesOptions { + readonly file: string; + readonly fileToGenerateTypesFor: string; + readonly outputFileName: string; + } + /** + * A set of one or more available refactoring actions, grouped under a parent refactoring. + */ + interface ApplicableRefactorInfo { + /** + * The programmatic name of the refactoring + */ + name: string; + /** + * A description of this refactoring category to show to the user. + * If the refactoring gets inlined (see below), this text will not be visible. + */ + description: string; + /** + * Inlineable refactorings can have their actions hoisted out to the top level + * of a context menu. Non-inlineanable refactorings should always be shown inside + * their parent grouping. + * + * If not specified, this value is assumed to be 'true' + */ + inlineable?: boolean; + actions: RefactorActionInfo[]; + } + /** + * Represents a single refactoring action - for example, the "Extract Method..." refactor might + * offer several actions, each corresponding to a surround class or closure to extract into. + */ + interface RefactorActionInfo { + /** + * The programmatic name of the refactoring action + */ + name: string; + /** + * A description of this refactoring action to show to the user. + * If the parent refactoring is inlined away, this will be the only text shown, + * so this description should make sense by itself if the parent is inlineable=true + */ + description: string; + } + /** + * A set of edits to make in response to a refactor action, plus an optional + * location where renaming should be invoked from + */ + interface RefactorEditInfo { + edits: FileTextChanges[]; + renameFilename?: string; + renameLocation?: number; + commands?: CodeActionCommand[]; + } + interface TextInsertion { + newText: string; + /** The position in newText the caret should point to after the insertion. */ + caretOffset: number; + } + interface DocumentSpan { + textSpan: TextSpan; + fileName: string; + /** + * If the span represents a location that was remapped (e.g. via a .d.ts.map file), + * then the original filename and span will be specified here + */ + originalTextSpan?: TextSpan; + originalFileName?: string; + } + interface RenameLocation extends DocumentSpan { + readonly prefixText?: string; + readonly suffixText?: string; + } + interface ReferenceEntry extends DocumentSpan { + isWriteAccess: boolean; + isDefinition: boolean; + isInString?: true; + } + interface ImplementationLocation extends DocumentSpan { + kind: ScriptElementKind; + displayParts: SymbolDisplayPart[]; + } + interface DocumentHighlights { + fileName: string; + highlightSpans: HighlightSpan[]; + } + enum HighlightSpanKind { + none = "none", + definition = "definition", + reference = "reference", + writtenReference = "writtenReference" + } + interface HighlightSpan { + fileName?: string; + isInString?: true; + textSpan: TextSpan; + kind: HighlightSpanKind; + } + interface NavigateToItem { + name: string; + kind: ScriptElementKind; + kindModifiers: string; + matchKind: "exact" | "prefix" | "substring" | "camelCase"; + isCaseSensitive: boolean; + fileName: string; + textSpan: TextSpan; + containerName: string; + containerKind: ScriptElementKind; + } + enum IndentStyle { + None = 0, + Block = 1, + Smart = 2 + } + interface EditorOptions { + BaseIndentSize?: number; + IndentSize: number; + TabSize: number; + NewLineCharacter: string; + ConvertTabsToSpaces: boolean; + IndentStyle: IndentStyle; + } + interface EditorSettings { + baseIndentSize?: number; + indentSize?: number; + tabSize?: number; + newLineCharacter?: string; + convertTabsToSpaces?: boolean; + indentStyle?: IndentStyle; + } + interface FormatCodeOptions extends EditorOptions { + InsertSpaceAfterCommaDelimiter: boolean; + InsertSpaceAfterSemicolonInForStatements: boolean; + InsertSpaceBeforeAndAfterBinaryOperators: boolean; + InsertSpaceAfterConstructor?: boolean; + InsertSpaceAfterKeywordsInControlFlowStatements: boolean; + InsertSpaceAfterFunctionKeywordForAnonymousFunctions: boolean; + InsertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: boolean; + InsertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: boolean; + InsertSpaceAfterOpeningAndBeforeClosingNonemptyBraces?: boolean; + InsertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: boolean; + InsertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces?: boolean; + InsertSpaceAfterTypeAssertion?: boolean; + InsertSpaceBeforeFunctionParenthesis?: boolean; + PlaceOpenBraceOnNewLineForFunctions: boolean; + PlaceOpenBraceOnNewLineForControlBlocks: boolean; + insertSpaceBeforeTypeAnnotation?: boolean; + } + interface FormatCodeSettings extends EditorSettings { + readonly insertSpaceAfterCommaDelimiter?: boolean; + readonly insertSpaceAfterSemicolonInForStatements?: boolean; + readonly insertSpaceBeforeAndAfterBinaryOperators?: boolean; + readonly insertSpaceAfterConstructor?: boolean; + readonly insertSpaceAfterKeywordsInControlFlowStatements?: boolean; + readonly insertSpaceAfterFunctionKeywordForAnonymousFunctions?: boolean; + readonly insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis?: boolean; + readonly insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets?: boolean; + readonly insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces?: boolean; + readonly insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces?: boolean; + readonly insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces?: boolean; + readonly insertSpaceAfterTypeAssertion?: boolean; + readonly insertSpaceBeforeFunctionParenthesis?: boolean; + readonly placeOpenBraceOnNewLineForFunctions?: boolean; + readonly placeOpenBraceOnNewLineForControlBlocks?: boolean; + readonly insertSpaceBeforeTypeAnnotation?: boolean; + readonly indentMultiLineObjectLiteralBeginningOnBlankLine?: boolean; + } + function getDefaultFormatCodeSettings(newLineCharacter?: string): FormatCodeSettings; + interface DefinitionInfo extends DocumentSpan { + kind: ScriptElementKind; + name: string; + containerKind: ScriptElementKind; + containerName: string; + } + interface DefinitionInfoAndBoundSpan { + definitions?: ReadonlyArray; + textSpan: TextSpan; + } + interface ReferencedSymbolDefinitionInfo extends DefinitionInfo { + displayParts: SymbolDisplayPart[]; + } + interface ReferencedSymbol { + definition: ReferencedSymbolDefinitionInfo; + references: ReferenceEntry[]; + } + enum SymbolDisplayPartKind { + aliasName = 0, + className = 1, + enumName = 2, + fieldName = 3, + interfaceName = 4, + keyword = 5, + lineBreak = 6, + numericLiteral = 7, + stringLiteral = 8, + localName = 9, + methodName = 10, + moduleName = 11, + operator = 12, + parameterName = 13, + propertyName = 14, + punctuation = 15, + space = 16, + text = 17, + typeParameterName = 18, + enumMemberName = 19, + functionName = 20, + regularExpressionLiteral = 21 + } + interface SymbolDisplayPart { + text: string; + kind: string; + } + interface JSDocTagInfo { + name: string; + text?: string; + } + interface QuickInfo { + kind: ScriptElementKind; + kindModifiers: string; + textSpan: TextSpan; + displayParts?: SymbolDisplayPart[]; + documentation?: SymbolDisplayPart[]; + tags?: JSDocTagInfo[]; + } + type RenameInfo = RenameInfoSuccess | RenameInfoFailure; + interface RenameInfoSuccess { + canRename: true; + /** + * File or directory to rename. + * If set, `getEditsForFileRename` should be called instead of `findRenameLocations`. + */ + fileToRename?: string; + displayName: string; + fullDisplayName: string; + kind: ScriptElementKind; + kindModifiers: string; + triggerSpan: TextSpan; + } + interface RenameInfoFailure { + canRename: false; + localizedErrorMessage: string; + } + interface SignatureHelpParameter { + name: string; + documentation: SymbolDisplayPart[]; + displayParts: SymbolDisplayPart[]; + isOptional: boolean; + } + /** + * Represents a single signature to show in signature help. + * The id is used for subsequent calls into the language service to ask questions about the + * signature help item in the context of any documents that have been updated. i.e. after + * an edit has happened, while signature help is still active, the host can ask important + * questions like 'what parameter is the user currently contained within?'. + */ + interface SignatureHelpItem { + isVariadic: boolean; + prefixDisplayParts: SymbolDisplayPart[]; + suffixDisplayParts: SymbolDisplayPart[]; + separatorDisplayParts: SymbolDisplayPart[]; + parameters: SignatureHelpParameter[]; + documentation: SymbolDisplayPart[]; + tags: JSDocTagInfo[]; + } + /** + * Represents a set of signature help items, and the preferred item that should be selected. + */ + interface SignatureHelpItems { + items: SignatureHelpItem[]; + applicableSpan: TextSpan; + selectedItemIndex: number; + argumentIndex: number; + argumentCount: number; + } + interface CompletionInfo { + /** Not true for all glboal completions. This will be true if the enclosing scope matches a few syntax kinds. See `isSnippetScope`. */ + isGlobalCompletion: boolean; + isMemberCompletion: boolean; + /** + * true when the current location also allows for a new identifier + */ + isNewIdentifierLocation: boolean; + entries: CompletionEntry[]; + } + interface CompletionEntry { + name: string; + kind: ScriptElementKind; + kindModifiers?: string; + sortText: string; + insertText?: string; + /** + * An optional span that indicates the text to be replaced by this completion item. + * If present, this span should be used instead of the default one. + * It will be set if the required span differs from the one generated by the default replacement behavior. + */ + replacementSpan?: TextSpan; + hasAction?: true; + source?: string; + isRecommended?: true; + } + interface CompletionEntryDetails { + name: string; + kind: ScriptElementKind; + kindModifiers: string; + displayParts: SymbolDisplayPart[]; + documentation?: SymbolDisplayPart[]; + tags?: JSDocTagInfo[]; + codeActions?: CodeAction[]; + source?: SymbolDisplayPart[]; + } + interface OutliningSpan { + /** The span of the document to actually collapse. */ + textSpan: TextSpan; + /** The span of the document to display when the user hovers over the collapsed span. */ + hintSpan: TextSpan; + /** The text to display in the editor for the collapsed region. */ + bannerText: string; + /** + * Whether or not this region should be automatically collapsed when + * the 'Collapse to Definitions' command is invoked. + */ + autoCollapse: boolean; + /** + * Classification of the contents of the span + */ + kind: OutliningSpanKind; + } + enum OutliningSpanKind { + /** Single or multi-line comments */ + Comment = "comment", + /** Sections marked by '// #region' and '// #endregion' comments */ + Region = "region", + /** Declarations and expressions */ + Code = "code", + /** Contiguous blocks of import declarations */ + Imports = "imports" + } + enum OutputFileType { + JavaScript = 0, + SourceMap = 1, + Declaration = 2 + } + enum EndOfLineState { + None = 0, + InMultiLineCommentTrivia = 1, + InSingleQuoteStringLiteral = 2, + InDoubleQuoteStringLiteral = 3, + InTemplateHeadOrNoSubstitutionTemplate = 4, + InTemplateMiddleOrTail = 5, + InTemplateSubstitutionPosition = 6 + } + enum TokenClass { + Punctuation = 0, + Keyword = 1, + Operator = 2, + Comment = 3, + Whitespace = 4, + Identifier = 5, + NumberLiteral = 6, + BigIntLiteral = 7, + StringLiteral = 8, + RegExpLiteral = 9 + } + interface ClassificationResult { + finalLexState: EndOfLineState; + entries: ClassificationInfo[]; + } + interface ClassificationInfo { + length: number; + classification: TokenClass; + } + interface Classifier { + /** + * Gives lexical classifications of tokens on a line without any syntactic context. + * For instance, a token consisting of the text 'string' can be either an identifier + * named 'string' or the keyword 'string', however, because this classifier is not aware, + * it relies on certain heuristics to give acceptable results. For classifications where + * speed trumps accuracy, this function is preferable; however, for true accuracy, the + * syntactic classifier is ideal. In fact, in certain editing scenarios, combining the + * lexical, syntactic, and semantic classifiers may issue the best user experience. + * + * @param text The text of a line to classify. + * @param lexState The state of the lexical classifier at the end of the previous line. + * @param syntacticClassifierAbsent Whether the client is *not* using a syntactic classifier. + * If there is no syntactic classifier (syntacticClassifierAbsent=true), + * certain heuristics may be used in its place; however, if there is a + * syntactic classifier (syntacticClassifierAbsent=false), certain + * classifications which may be incorrectly categorized will be given + * back as Identifiers in order to allow the syntactic classifier to + * subsume the classification. + * @deprecated Use getLexicalClassifications instead. + */ + getClassificationsForLine(text: string, lexState: EndOfLineState, syntacticClassifierAbsent: boolean): ClassificationResult; + getEncodedLexicalClassifications(text: string, endOfLineState: EndOfLineState, syntacticClassifierAbsent: boolean): Classifications; + } + enum ScriptElementKind { + unknown = "", + warning = "warning", + /** predefined type (void) or keyword (class) */ + keyword = "keyword", + /** top level script node */ + scriptElement = "script", + /** module foo {} */ + moduleElement = "module", + /** class X {} */ + classElement = "class", + /** var x = class X {} */ + localClassElement = "local class", + /** interface Y {} */ + interfaceElement = "interface", + /** type T = ... */ + typeElement = "type", + /** enum E */ + enumElement = "enum", + enumMemberElement = "enum member", + /** + * Inside module and script only + * const v = .. + */ + variableElement = "var", + /** Inside function */ + localVariableElement = "local var", + /** + * Inside module and script only + * function f() { } + */ + functionElement = "function", + /** Inside function */ + localFunctionElement = "local function", + /** class X { [public|private]* foo() {} } */ + memberFunctionElement = "method", + /** class X { [public|private]* [get|set] foo:number; } */ + memberGetAccessorElement = "getter", + memberSetAccessorElement = "setter", + /** + * class X { [public|private]* foo:number; } + * interface Y { foo:number; } + */ + memberVariableElement = "property", + /** class X { constructor() { } } */ + constructorImplementationElement = "constructor", + /** interface Y { ():number; } */ + callSignatureElement = "call", + /** interface Y { []:number; } */ + indexSignatureElement = "index", + /** interface Y { new():Y; } */ + constructSignatureElement = "construct", + /** function foo(*Y*: string) */ + parameterElement = "parameter", + typeParameterElement = "type parameter", + primitiveType = "primitive type", + label = "label", + alias = "alias", + constElement = "const", + letElement = "let", + directory = "directory", + externalModuleName = "external module name", + /** + * + */ + jsxAttribute = "JSX attribute", + /** String literal */ + string = "string" + } + enum ScriptElementKindModifier { + none = "", + publicMemberModifier = "public", + privateMemberModifier = "private", + protectedMemberModifier = "protected", + exportedModifier = "export", + ambientModifier = "declare", + staticModifier = "static", + abstractModifier = "abstract", + optionalModifier = "optional", + dtsModifier = ".d.ts", + tsModifier = ".ts", + tsxModifier = ".tsx", + jsModifier = ".js", + jsxModifier = ".jsx", + jsonModifier = ".json" + } + enum ClassificationTypeNames { + comment = "comment", + identifier = "identifier", + keyword = "keyword", + numericLiteral = "number", + bigintLiteral = "bigint", + operator = "operator", + stringLiteral = "string", + whiteSpace = "whitespace", + text = "text", + punctuation = "punctuation", + className = "class name", + enumName = "enum name", + interfaceName = "interface name", + moduleName = "module name", + typeParameterName = "type parameter name", + typeAliasName = "type alias name", + parameterName = "parameter name", + docCommentTagName = "doc comment tag name", + jsxOpenTagName = "jsx open tag name", + jsxCloseTagName = "jsx close tag name", + jsxSelfClosingTagName = "jsx self closing tag name", + jsxAttribute = "jsx attribute", + jsxText = "jsx text", + jsxAttributeStringLiteralValue = "jsx attribute string literal value" + } + enum ClassificationType { + comment = 1, + identifier = 2, + keyword = 3, + numericLiteral = 4, + operator = 5, + stringLiteral = 6, + regularExpressionLiteral = 7, + whiteSpace = 8, + text = 9, + punctuation = 10, + className = 11, + enumName = 12, + interfaceName = 13, + moduleName = 14, + typeParameterName = 15, + typeAliasName = 16, + parameterName = 17, + docCommentTagName = 18, + jsxOpenTagName = 19, + jsxCloseTagName = 20, + jsxSelfClosingTagName = 21, + jsxAttribute = 22, + jsxText = 23, + jsxAttributeStringLiteralValue = 24, + bigintLiteral = 25 + } +} +declare namespace ts { + function createClassifier(): Classifier; +} +declare namespace ts { + /** + * The document registry represents a store of SourceFile objects that can be shared between + * multiple LanguageService instances. A LanguageService instance holds on the SourceFile (AST) + * of files in the context. + * SourceFile objects account for most of the memory usage by the language service. Sharing + * the same DocumentRegistry instance between different instances of LanguageService allow + * for more efficient memory utilization since all projects will share at least the library + * file (lib.d.ts). + * + * A more advanced use of the document registry is to serialize sourceFile objects to disk + * and re-hydrate them when needed. + * + * To create a default DocumentRegistry, use createDocumentRegistry to create one, and pass it + * to all subsequent createLanguageService calls. + */ + interface DocumentRegistry { + /** + * Request a stored SourceFile with a given fileName and compilationSettings. + * The first call to acquire will call createLanguageServiceSourceFile to generate + * the SourceFile if was not found in the registry. + * + * @param fileName The name of the file requested + * @param compilationSettings Some compilation settings like target affects the + * shape of a the resulting SourceFile. This allows the DocumentRegistry to store + * multiple copies of the same file for different compilation settings. + * @param scriptSnapshot Text of the file. Only used if the file was not found + * in the registry and a new one was created. + * @param version Current version of the file. Only used if the file was not found + * in the registry and a new one was created. + */ + acquireDocument(fileName: string, compilationSettings: CompilerOptions, scriptSnapshot: IScriptSnapshot, version: string, scriptKind?: ScriptKind): SourceFile; + acquireDocumentWithKey(fileName: string, path: Path, compilationSettings: CompilerOptions, key: DocumentRegistryBucketKey, scriptSnapshot: IScriptSnapshot, version: string, scriptKind?: ScriptKind): SourceFile; + /** + * Request an updated version of an already existing SourceFile with a given fileName + * and compilationSettings. The update will in-turn call updateLanguageServiceSourceFile + * to get an updated SourceFile. + * + * @param fileName The name of the file requested + * @param compilationSettings Some compilation settings like target affects the + * shape of a the resulting SourceFile. This allows the DocumentRegistry to store + * multiple copies of the same file for different compilation settings. + * @param scriptSnapshot Text of the file. + * @param version Current version of the file. + */ + updateDocument(fileName: string, compilationSettings: CompilerOptions, scriptSnapshot: IScriptSnapshot, version: string, scriptKind?: ScriptKind): SourceFile; + updateDocumentWithKey(fileName: string, path: Path, compilationSettings: CompilerOptions, key: DocumentRegistryBucketKey, scriptSnapshot: IScriptSnapshot, version: string, scriptKind?: ScriptKind): SourceFile; + getKeyForCompilationSettings(settings: CompilerOptions): DocumentRegistryBucketKey; + /** + * Informs the DocumentRegistry that a file is not needed any longer. + * + * Note: It is not allowed to call release on a SourceFile that was not acquired from + * this registry originally. + * + * @param fileName The name of the file to be released + * @param compilationSettings The compilation settings used to acquire the file + */ + releaseDocument(fileName: string, compilationSettings: CompilerOptions): void; + releaseDocumentWithKey(path: Path, key: DocumentRegistryBucketKey): void; + reportStats(): string; + } + type DocumentRegistryBucketKey = string & { + __bucketKey: any; + }; + function createDocumentRegistry(useCaseSensitiveFileNames?: boolean, currentDirectory?: string): DocumentRegistry; +} +declare namespace ts { + function preProcessFile(sourceText: string, readImportFiles?: boolean, detectJavaScriptImports?: boolean): PreProcessedFileInfo; +} +declare namespace ts { + interface TranspileOptions { + compilerOptions?: CompilerOptions; + fileName?: string; + reportDiagnostics?: boolean; + moduleName?: string; + renamedDependencies?: MapLike; + transformers?: CustomTransformers; + } + interface TranspileOutput { + outputText: string; + diagnostics?: Diagnostic[]; + sourceMapText?: string; + } + function transpileModule(input: string, transpileOptions: TranspileOptions): TranspileOutput; + function transpile(input: string, compilerOptions?: CompilerOptions, fileName?: string, diagnostics?: Diagnostic[], moduleName?: string): string; +} +declare namespace ts { + function generateTypesForModule(name: string, moduleValue: unknown, formatSettings: FormatCodeSettings): string; + function generateTypesForGlobal(name: string, globalValue: unknown, formatSettings: FormatCodeSettings): string; +} +declare namespace ts { + /** The version of the language service API */ + const servicesVersion = "0.8"; + function toEditorSettings(options: EditorOptions | EditorSettings): EditorSettings; + function displayPartsToString(displayParts: SymbolDisplayPart[] | undefined): string; + function getDefaultCompilerOptions(): CompilerOptions; + function getSupportedCodeFixes(): string[]; + function createLanguageServiceSourceFile(fileName: string, scriptSnapshot: IScriptSnapshot, scriptTarget: ScriptTarget, version: string, setNodeParents: boolean, scriptKind?: ScriptKind): SourceFile; + let disableIncrementalParsing: boolean; + function updateLanguageServiceSourceFile(sourceFile: SourceFile, scriptSnapshot: IScriptSnapshot, version: string, textChangeRange: TextChangeRange | undefined, aggressiveChecks?: boolean): SourceFile; + function createLanguageService(host: LanguageServiceHost, documentRegistry?: DocumentRegistry, syntaxOnly?: boolean): LanguageService; + /** + * Get the path of the default library files (lib.d.ts) as distributed with the typescript + * node package. + * The functionality is not supported if the ts module is consumed outside of a node module. + */ + function getDefaultLibFilePath(options: CompilerOptions): string; +} +declare namespace ts { + /** + * Transform one or more nodes using the supplied transformers. + * @param source A single `Node` or an array of `Node` objects. + * @param transformers An array of `TransformerFactory` callbacks used to process the transformation. + * @param compilerOptions Optional compiler options. + */ + function transform(source: T | T[], transformers: TransformerFactory[], compilerOptions?: CompilerOptions): TransformationResult; +} +declare namespace ts.server { + interface CompressedData { + length: number; + compressionKind: string; + data: any; + } + type RequireResult = { + module: {}; + error: undefined; + } | { + module: undefined; + error: { + stack?: string; + message?: string; + }; + }; + interface ServerHost extends System { + watchFile(path: string, callback: FileWatcherCallback, pollingInterval?: number): FileWatcher; + watchDirectory(path: string, callback: DirectoryWatcherCallback, recursive?: boolean): FileWatcher; + setTimeout(callback: (...args: any[]) => void, ms: number, ...args: any[]): any; + clearTimeout(timeoutId: any): void; + setImmediate(callback: (...args: any[]) => void, ...args: any[]): any; + clearImmediate(timeoutId: any): void; + gc?(): void; + trace?(s: string): void; + require?(initialPath: string, moduleName: string): RequireResult; + } +} +declare namespace ts.server { + enum LogLevel { + terse = 0, + normal = 1, + requestTime = 2, + verbose = 3 + } + const emptyArray: SortedReadonlyArray; + interface Logger { + close(): void; + hasLevel(level: LogLevel): boolean; + loggingEnabled(): boolean; + perftrc(s: string): void; + info(s: string): void; + startGroup(): void; + endGroup(): void; + msg(s: string, type?: Msg): void; + getLogFileName(): string | undefined; + } + enum Msg { + Err = "Err", + Info = "Info", + Perf = "Perf" + } + namespace Msg { + /** @deprecated Only here for backwards-compatibility. Prefer just `Msg`. */ + type Types = Msg; + } + function createInstallTypingsRequest(project: Project, typeAcquisition: TypeAcquisition, unresolvedImports: SortedReadonlyArray, cachePath?: string): DiscoverTypings; + namespace Errors { + function ThrowNoProject(): never; + function ThrowProjectLanguageServiceDisabled(): never; + function ThrowProjectDoesNotContainDocument(fileName: string, project: Project): never; + } + type NormalizedPath = string & { + __normalizedPathTag: any; + }; + function toNormalizedPath(fileName: string): NormalizedPath; + function normalizedPathToPath(normalizedPath: NormalizedPath, currentDirectory: string, getCanonicalFileName: (f: string) => string): Path; + function asNormalizedPath(fileName: string): NormalizedPath; + interface NormalizedPathMap { + get(path: NormalizedPath): T | undefined; + set(path: NormalizedPath, value: T): void; + contains(path: NormalizedPath): boolean; + remove(path: NormalizedPath): void; + } + function createNormalizedPathMap(): NormalizedPathMap; + function isInferredProjectName(name: string): boolean; + function makeInferredProjectName(counter: number): string; + function createSortedArray(): SortedArray; +} +/** + * Declaration module describing the TypeScript Server protocol + */ +declare namespace ts.server.protocol { + enum CommandTypes { + JsxClosingTag = "jsxClosingTag", + Brace = "brace", + BraceCompletion = "braceCompletion", + GetSpanOfEnclosingComment = "getSpanOfEnclosingComment", + Change = "change", + Close = "close", + /** @deprecated Prefer CompletionInfo -- see comment on CompletionsResponse */ + Completions = "completions", + CompletionInfo = "completionInfo", + CompletionDetails = "completionEntryDetails", + CompileOnSaveAffectedFileList = "compileOnSaveAffectedFileList", + CompileOnSaveEmitFile = "compileOnSaveEmitFile", + Configure = "configure", + Definition = "definition", + DefinitionAndBoundSpan = "definitionAndBoundSpan", + Implementation = "implementation", + Exit = "exit", + Format = "format", + Formatonkey = "formatonkey", + Geterr = "geterr", + GeterrForProject = "geterrForProject", + SemanticDiagnosticsSync = "semanticDiagnosticsSync", + SyntacticDiagnosticsSync = "syntacticDiagnosticsSync", + SuggestionDiagnosticsSync = "suggestionDiagnosticsSync", + NavBar = "navbar", + Navto = "navto", + NavTree = "navtree", + NavTreeFull = "navtree-full", + /** @deprecated */ + Occurrences = "occurrences", + DocumentHighlights = "documentHighlights", + Open = "open", + Quickinfo = "quickinfo", + References = "references", + Reload = "reload", + Rename = "rename", + Saveto = "saveto", + SignatureHelp = "signatureHelp", + Status = "status", + TypeDefinition = "typeDefinition", + ProjectInfo = "projectInfo", + ReloadProjects = "reloadProjects", + Unknown = "unknown", + OpenExternalProject = "openExternalProject", + OpenExternalProjects = "openExternalProjects", + CloseExternalProject = "closeExternalProject", + GetOutliningSpans = "getOutliningSpans", + TodoComments = "todoComments", + Indentation = "indentation", + DocCommentTemplate = "docCommentTemplate", + CompilerOptionsForInferredProjects = "compilerOptionsForInferredProjects", + GetCodeFixes = "getCodeFixes", + GetCombinedCodeFix = "getCombinedCodeFix", + ApplyCodeActionCommand = "applyCodeActionCommand", + GetSupportedCodeFixes = "getSupportedCodeFixes", + GetApplicableRefactors = "getApplicableRefactors", + GetEditsForRefactor = "getEditsForRefactor", + OrganizeImports = "organizeImports", + GetEditsForFileRename = "getEditsForFileRename", + ConfigurePlugin = "configurePlugin" + } + /** + * A TypeScript Server message + */ + interface Message { + /** + * Sequence number of the message + */ + seq: number; + /** + * One of "request", "response", or "event" + */ + type: "request" | "response" | "event"; + } + /** + * Client-initiated request message + */ + interface Request extends Message { + type: "request"; + /** + * The command to execute + */ + command: string; + /** + * Object containing arguments for the command + */ + arguments?: any; + } + /** + * Request to reload the project structure for all the opened files + */ + interface ReloadProjectsRequest extends Message { + command: CommandTypes.ReloadProjects; + } + /** + * Server-initiated event message + */ + interface Event extends Message { + type: "event"; + /** + * Name of event + */ + event: string; + /** + * Event-specific information + */ + body?: any; + } + /** + * Response by server to client request message. + */ + interface Response extends Message { + type: "response"; + /** + * Sequence number of the request message. + */ + request_seq: number; + /** + * Outcome of the request. + */ + success: boolean; + /** + * The command requested. + */ + command: string; + /** + * If success === false, this should always be provided. + * Otherwise, may (or may not) contain a success message. + */ + message?: string; + /** + * Contains message body if success === true. + */ + body?: any; + /** + * Contains extra information that plugin can include to be passed on + */ + metadata?: unknown; + } + /** + * Arguments for FileRequest messages. + */ + interface FileRequestArgs { + /** + * The file for the request (absolute pathname required). + */ + file: string; + projectFileName?: string; + } + interface StatusRequest extends Request { + command: CommandTypes.Status; + } + interface StatusResponseBody { + /** + * The TypeScript version (`ts.version`). + */ + version: string; + } + /** + * Response to StatusRequest + */ + interface StatusResponse extends Response { + body: StatusResponseBody; + } + /** + * Requests a JS Doc comment template for a given position + */ + interface DocCommentTemplateRequest extends FileLocationRequest { + command: CommandTypes.DocCommentTemplate; + } + /** + * Response to DocCommentTemplateRequest + */ + interface DocCommandTemplateResponse extends Response { + body?: TextInsertion; + } + /** + * A request to get TODO comments from the file + */ + interface TodoCommentRequest extends FileRequest { + command: CommandTypes.TodoComments; + arguments: TodoCommentRequestArgs; + } + /** + * Arguments for TodoCommentRequest request. + */ + interface TodoCommentRequestArgs extends FileRequestArgs { + /** + * Array of target TodoCommentDescriptors that describes TODO comments to be found + */ + descriptors: TodoCommentDescriptor[]; + } + /** + * Response for TodoCommentRequest request. + */ + interface TodoCommentsResponse extends Response { + body?: TodoComment[]; + } + /** + * A request to determine if the caret is inside a comment. + */ + interface SpanOfEnclosingCommentRequest extends FileLocationRequest { + command: CommandTypes.GetSpanOfEnclosingComment; + arguments: SpanOfEnclosingCommentRequestArgs; + } + interface SpanOfEnclosingCommentRequestArgs extends FileLocationRequestArgs { + /** + * Requires that the enclosing span be a multi-line comment, or else the request returns undefined. + */ + onlyMultiLine: boolean; + } + /** + * Request to obtain outlining spans in file. + */ + interface OutliningSpansRequest extends FileRequest { + command: CommandTypes.GetOutliningSpans; + } + interface OutliningSpan { + /** The span of the document to actually collapse. */ + textSpan: TextSpan; + /** The span of the document to display when the user hovers over the collapsed span. */ + hintSpan: TextSpan; + /** The text to display in the editor for the collapsed region. */ + bannerText: string; + /** + * Whether or not this region should be automatically collapsed when + * the 'Collapse to Definitions' command is invoked. + */ + autoCollapse: boolean; + /** + * Classification of the contents of the span + */ + kind: OutliningSpanKind; + } + /** + * Response to OutliningSpansRequest request. + */ + interface OutliningSpansResponse extends Response { + body?: OutliningSpan[]; + } + /** + * A request to get indentation for a location in file + */ + interface IndentationRequest extends FileLocationRequest { + command: CommandTypes.Indentation; + arguments: IndentationRequestArgs; + } + /** + * Response for IndentationRequest request. + */ + interface IndentationResponse extends Response { + body?: IndentationResult; + } + /** + * Indentation result representing where indentation should be placed + */ + interface IndentationResult { + /** + * The base position in the document that the indent should be relative to + */ + position: number; + /** + * The number of columns the indent should be at relative to the position's column. + */ + indentation: number; + } + /** + * Arguments for IndentationRequest request. + */ + interface IndentationRequestArgs extends FileLocationRequestArgs { + /** + * An optional set of settings to be used when computing indentation. + * If argument is omitted - then it will use settings for file that were previously set via 'configure' request or global settings. + */ + options?: EditorSettings; + } + /** + * Arguments for ProjectInfoRequest request. + */ + interface ProjectInfoRequestArgs extends FileRequestArgs { + /** + * Indicate if the file name list of the project is needed + */ + needFileNameList: boolean; + } + /** + * A request to get the project information of the current file. + */ + interface ProjectInfoRequest extends Request { + command: CommandTypes.ProjectInfo; + arguments: ProjectInfoRequestArgs; + } + /** + * A request to retrieve compiler options diagnostics for a project + */ + interface CompilerOptionsDiagnosticsRequest extends Request { + arguments: CompilerOptionsDiagnosticsRequestArgs; + } + /** + * Arguments for CompilerOptionsDiagnosticsRequest request. + */ + interface CompilerOptionsDiagnosticsRequestArgs { + /** + * Name of the project to retrieve compiler options diagnostics. + */ + projectFileName: string; + } + /** + * Response message body for "projectInfo" request + */ + interface ProjectInfo { + /** + * For configured project, this is the normalized path of the 'tsconfig.json' file + * For inferred project, this is undefined + */ + configFileName: string; + /** + * The list of normalized file name in the project, including 'lib.d.ts' + */ + fileNames?: string[]; + /** + * Indicates if the project has a active language service instance + */ + languageServiceDisabled?: boolean; + } + /** + * Represents diagnostic info that includes location of diagnostic in two forms + * - start position and length of the error span + * - startLocation and endLocation - a pair of Location objects that store start/end line and offset of the error span. + */ + interface DiagnosticWithLinePosition { + message: string; + start: number; + length: number; + startLocation: Location; + endLocation: Location; + category: string; + code: number; + /** May store more in future. For now, this will simply be `true` to indicate when a diagnostic is an unused-identifier diagnostic. */ + reportsUnnecessary?: {}; + relatedInformation?: DiagnosticRelatedInformation[]; + } + /** + * Response message for "projectInfo" request + */ + interface ProjectInfoResponse extends Response { + body?: ProjectInfo; + } + /** + * Request whose sole parameter is a file name. + */ + interface FileRequest extends Request { + arguments: FileRequestArgs; + } + /** + * Instances of this interface specify a location in a source file: + * (file, line, character offset), where line and character offset are 1-based. + */ + interface FileLocationRequestArgs extends FileRequestArgs { + /** + * The line number for the request (1-based). + */ + line: number; + /** + * The character offset (on the line) for the request (1-based). + */ + offset: number; + } + type FileLocationOrRangeRequestArgs = FileLocationRequestArgs | FileRangeRequestArgs; + /** + * Request refactorings at a given position or selection area. + */ + interface GetApplicableRefactorsRequest extends Request { + command: CommandTypes.GetApplicableRefactors; + arguments: GetApplicableRefactorsRequestArgs; + } + type GetApplicableRefactorsRequestArgs = FileLocationOrRangeRequestArgs; + /** + * Response is a list of available refactorings. + * Each refactoring exposes one or more "Actions"; a user selects one action to invoke a refactoring + */ + interface GetApplicableRefactorsResponse extends Response { + body?: ApplicableRefactorInfo[]; + } + /** + * A set of one or more available refactoring actions, grouped under a parent refactoring. + */ + interface ApplicableRefactorInfo { + /** + * The programmatic name of the refactoring + */ + name: string; + /** + * A description of this refactoring category to show to the user. + * If the refactoring gets inlined (see below), this text will not be visible. + */ + description: string; + /** + * Inlineable refactorings can have their actions hoisted out to the top level + * of a context menu. Non-inlineanable refactorings should always be shown inside + * their parent grouping. + * + * If not specified, this value is assumed to be 'true' + */ + inlineable?: boolean; + actions: RefactorActionInfo[]; + } + /** + * Represents a single refactoring action - for example, the "Extract Method..." refactor might + * offer several actions, each corresponding to a surround class or closure to extract into. + */ + interface RefactorActionInfo { + /** + * The programmatic name of the refactoring action + */ + name: string; + /** + * A description of this refactoring action to show to the user. + * If the parent refactoring is inlined away, this will be the only text shown, + * so this description should make sense by itself if the parent is inlineable=true + */ + description: string; + } + interface GetEditsForRefactorRequest extends Request { + command: CommandTypes.GetEditsForRefactor; + arguments: GetEditsForRefactorRequestArgs; + } + /** + * Request the edits that a particular refactoring action produces. + * Callers must specify the name of the refactor and the name of the action. + */ + type GetEditsForRefactorRequestArgs = FileLocationOrRangeRequestArgs & { + refactor: string; + action: string; + }; + interface GetEditsForRefactorResponse extends Response { + body?: RefactorEditInfo; + } + interface RefactorEditInfo { + edits: FileCodeEdits[]; + /** + * An optional location where the editor should start a rename operation once + * the refactoring edits have been applied + */ + renameLocation?: Location; + renameFilename?: string; + } + /** + * Organize imports by: + * 1) Removing unused imports + * 2) Coalescing imports from the same module + * 3) Sorting imports + */ + interface OrganizeImportsRequest extends Request { + command: CommandTypes.OrganizeImports; + arguments: OrganizeImportsRequestArgs; + } + type OrganizeImportsScope = GetCombinedCodeFixScope; + interface OrganizeImportsRequestArgs { + scope: OrganizeImportsScope; + } + interface OrganizeImportsResponse extends Response { + body: ReadonlyArray; + } + interface GetEditsForFileRenameRequest extends Request { + command: CommandTypes.GetEditsForFileRename; + arguments: GetEditsForFileRenameRequestArgs; + } + /** Note: Paths may also be directories. */ + interface GetEditsForFileRenameRequestArgs { + readonly oldFilePath: string; + readonly newFilePath: string; + } + interface GetEditsForFileRenameResponse extends Response { + body: ReadonlyArray; + } + /** + * Request for the available codefixes at a specific position. + */ + interface CodeFixRequest extends Request { + command: CommandTypes.GetCodeFixes; + arguments: CodeFixRequestArgs; + } + interface GetCombinedCodeFixRequest extends Request { + command: CommandTypes.GetCombinedCodeFix; + arguments: GetCombinedCodeFixRequestArgs; + } + interface GetCombinedCodeFixResponse extends Response { + body: CombinedCodeActions; + } + interface ApplyCodeActionCommandRequest extends Request { + command: CommandTypes.ApplyCodeActionCommand; + arguments: ApplyCodeActionCommandRequestArgs; + } + interface ApplyCodeActionCommandResponse extends Response { + } + interface FileRangeRequestArgs extends FileRequestArgs { + /** + * The line number for the request (1-based). + */ + startLine: number; + /** + * The character offset (on the line) for the request (1-based). + */ + startOffset: number; + /** + * The line number for the request (1-based). + */ + endLine: number; + /** + * The character offset (on the line) for the request (1-based). + */ + endOffset: number; + } + /** + * Instances of this interface specify errorcodes on a specific location in a sourcefile. + */ + interface CodeFixRequestArgs extends FileRangeRequestArgs { + /** + * Errorcodes we want to get the fixes for. + */ + errorCodes: ReadonlyArray; + } + interface GetCombinedCodeFixRequestArgs { + scope: GetCombinedCodeFixScope; + fixId: {}; + } + interface GetCombinedCodeFixScope { + type: "file"; + args: FileRequestArgs; + } + interface ApplyCodeActionCommandRequestArgs { + /** May also be an array of commands. */ + command: {}; + } + /** + * Response for GetCodeFixes request. + */ + interface GetCodeFixesResponse extends Response { + body?: CodeAction[]; + } + /** + * A request whose arguments specify a file location (file, line, col). + */ + interface FileLocationRequest extends FileRequest { + arguments: FileLocationRequestArgs; + } + /** + * A request to get codes of supported code fixes. + */ + interface GetSupportedCodeFixesRequest extends Request { + command: CommandTypes.GetSupportedCodeFixes; + } + /** + * A response for GetSupportedCodeFixesRequest request. + */ + interface GetSupportedCodeFixesResponse extends Response { + /** + * List of error codes supported by the server. + */ + body?: string[]; + } + /** + * Arguments for EncodedSemanticClassificationsRequest request. + */ + interface EncodedSemanticClassificationsRequestArgs extends FileRequestArgs { + /** + * Start position of the span. + */ + start: number; + /** + * Length of the span. + */ + length: number; + } + /** + * Arguments in document highlight request; include: filesToSearch, file, + * line, offset. + */ + interface DocumentHighlightsRequestArgs extends FileLocationRequestArgs { + /** + * List of files to search for document highlights. + */ + filesToSearch: string[]; + } + /** + * Go to definition request; value of command field is + * "definition". Return response giving the file locations that + * define the symbol found in file at location line, col. + */ + interface DefinitionRequest extends FileLocationRequest { + command: CommandTypes.Definition; + } + interface DefinitionAndBoundSpanRequest extends FileLocationRequest { + readonly command: CommandTypes.DefinitionAndBoundSpan; + } + interface DefinitionAndBoundSpanResponse extends Response { + readonly body: DefinitionInfoAndBoundSpan; + } + /** + * Go to type request; value of command field is + * "typeDefinition". Return response giving the file locations that + * define the type for the symbol found in file at location line, col. + */ + interface TypeDefinitionRequest extends FileLocationRequest { + command: CommandTypes.TypeDefinition; + } + /** + * Go to implementation request; value of command field is + * "implementation". Return response giving the file locations that + * implement the symbol found in file at location line, col. + */ + interface ImplementationRequest extends FileLocationRequest { + command: CommandTypes.Implementation; + } + /** + * Location in source code expressed as (one-based) line and (one-based) column offset. + */ + interface Location { + line: number; + offset: number; + } + /** + * Object found in response messages defining a span of text in source code. + */ + interface TextSpan { + /** + * First character of the definition. + */ + start: Location; + /** + * One character past last character of the definition. + */ + end: Location; + } + /** + * Object found in response messages defining a span of text in a specific source file. + */ + interface FileSpan extends TextSpan { + /** + * File containing text span. + */ + file: string; + } + interface DefinitionInfoAndBoundSpan { + definitions: ReadonlyArray; + textSpan: TextSpan; + } + /** + * Definition response message. Gives text range for definition. + */ + interface DefinitionResponse extends Response { + body?: FileSpan[]; + } + interface DefinitionInfoAndBoundSpanReponse extends Response { + body?: DefinitionInfoAndBoundSpan; + } + /** + * Definition response message. Gives text range for definition. + */ + interface TypeDefinitionResponse extends Response { + body?: FileSpan[]; + } + /** + * Implementation response message. Gives text range for implementations. + */ + interface ImplementationResponse extends Response { + body?: FileSpan[]; + } + /** + * Request to get brace completion for a location in the file. + */ + interface BraceCompletionRequest extends FileLocationRequest { + command: CommandTypes.BraceCompletion; + arguments: BraceCompletionRequestArgs; + } + /** + * Argument for BraceCompletionRequest request. + */ + interface BraceCompletionRequestArgs extends FileLocationRequestArgs { + /** + * Kind of opening brace + */ + openingBrace: string; + } + interface JsxClosingTagRequest extends FileLocationRequest { + readonly command: CommandTypes.JsxClosingTag; + readonly arguments: JsxClosingTagRequestArgs; + } + interface JsxClosingTagRequestArgs extends FileLocationRequestArgs { + } + interface JsxClosingTagResponse extends Response { + readonly body: TextInsertion; + } + /** + * @deprecated + * Get occurrences request; value of command field is + * "occurrences". Return response giving spans that are relevant + * in the file at a given line and column. + */ + interface OccurrencesRequest extends FileLocationRequest { + command: CommandTypes.Occurrences; + } + /** @deprecated */ + interface OccurrencesResponseItem extends FileSpan { + /** + * True if the occurrence is a write location, false otherwise. + */ + isWriteAccess: boolean; + /** + * True if the occurrence is in a string, undefined otherwise; + */ + isInString?: true; + } + /** @deprecated */ + interface OccurrencesResponse extends Response { + body?: OccurrencesResponseItem[]; + } + /** + * Get document highlights request; value of command field is + * "documentHighlights". Return response giving spans that are relevant + * in the file at a given line and column. + */ + interface DocumentHighlightsRequest extends FileLocationRequest { + command: CommandTypes.DocumentHighlights; + arguments: DocumentHighlightsRequestArgs; + } + /** + * Span augmented with extra information that denotes the kind of the highlighting to be used for span. + */ + interface HighlightSpan extends TextSpan { + kind: HighlightSpanKind; + } + /** + * Represents a set of highligh spans for a give name + */ + interface DocumentHighlightsItem { + /** + * File containing highlight spans. + */ + file: string; + /** + * Spans to highlight in file. + */ + highlightSpans: HighlightSpan[]; + } + /** + * Response for a DocumentHighlightsRequest request. + */ + interface DocumentHighlightsResponse extends Response { + body?: DocumentHighlightsItem[]; + } + /** + * Find references request; value of command field is + * "references". Return response giving the file locations that + * reference the symbol found in file at location line, col. + */ + interface ReferencesRequest extends FileLocationRequest { + command: CommandTypes.References; + } + interface ReferencesResponseItem extends FileSpan { + /** Text of line containing the reference. Including this + * with the response avoids latency of editor loading files + * to show text of reference line (the server already has + * loaded the referencing files). + */ + lineText: string; + /** + * True if reference is a write location, false otherwise. + */ + isWriteAccess: boolean; + /** + * True if reference is a definition, false otherwise. + */ + isDefinition: boolean; + } + /** + * The body of a "references" response message. + */ + interface ReferencesResponseBody { + /** + * The file locations referencing the symbol. + */ + refs: ReadonlyArray; + /** + * The name of the symbol. + */ + symbolName: string; + /** + * The start character offset of the symbol (on the line provided by the references request). + */ + symbolStartOffset: number; + /** + * The full display name of the symbol. + */ + symbolDisplayString: string; + } + /** + * Response to "references" request. + */ + interface ReferencesResponse extends Response { + body?: ReferencesResponseBody; + } + /** + * Argument for RenameRequest request. + */ + interface RenameRequestArgs extends FileLocationRequestArgs { + /** + * Should text at specified location be found/changed in comments? + */ + findInComments?: boolean; + /** + * Should text at specified location be found/changed in strings? + */ + findInStrings?: boolean; + } + /** + * Rename request; value of command field is "rename". Return + * response giving the file locations that reference the symbol + * found in file at location line, col. Also return full display + * name of the symbol so that client can print it unambiguously. + */ + interface RenameRequest extends FileLocationRequest { + command: CommandTypes.Rename; + arguments: RenameRequestArgs; + } + /** + * Information about the item to be renamed. + */ + type RenameInfo = RenameInfoSuccess | RenameInfoFailure; + interface RenameInfoSuccess { + /** + * True if item can be renamed. + */ + canRename: true; + /** + * File or directory to rename. + * If set, `getEditsForFileRename` should be called instead of `findRenameLocations`. + */ + fileToRename?: string; + /** + * Display name of the item to be renamed. + */ + displayName: string; + /** + * Full display name of item to be renamed. + */ + fullDisplayName: string; + /** + * The items's kind (such as 'className' or 'parameterName' or plain 'text'). + */ + kind: ScriptElementKind; + /** + * Optional modifiers for the kind (such as 'public'). + */ + kindModifiers: string; + /** Span of text to rename. */ + triggerSpan: TextSpan; + } + interface RenameInfoFailure { + canRename: false; + /** + * Error message if item can not be renamed. + */ + localizedErrorMessage: string; + } + /** + * A group of text spans, all in 'file'. + */ + interface SpanGroup { + /** The file to which the spans apply */ + file: string; + /** The text spans in this group */ + locs: RenameTextSpan[]; + } + interface RenameTextSpan extends TextSpan { + readonly prefixText?: string; + readonly suffixText?: string; + } + interface RenameResponseBody { + /** + * Information about the item to be renamed. + */ + info: RenameInfo; + /** + * An array of span groups (one per file) that refer to the item to be renamed. + */ + locs: ReadonlyArray; + } + /** + * Rename response message. + */ + interface RenameResponse extends Response { + body?: RenameResponseBody; + } + /** + * Represents a file in external project. + * External project is project whose set of files, compilation options and open\close state + * is maintained by the client (i.e. if all this data come from .csproj file in Visual Studio). + * External project will exist even if all files in it are closed and should be closed explicitly. + * If external project includes one or more tsconfig.json/jsconfig.json files then tsserver will + * create configured project for every config file but will maintain a link that these projects were created + * as a result of opening external project so they should be removed once external project is closed. + */ + interface ExternalFile { + /** + * Name of file file + */ + fileName: string; + /** + * Script kind of the file + */ + scriptKind?: ScriptKindName | ts.ScriptKind; + /** + * Whether file has mixed content (i.e. .cshtml file that combines html markup with C#/JavaScript) + */ + hasMixedContent?: boolean; + /** + * Content of the file + */ + content?: string; + } + /** + * Represent an external project + */ + interface ExternalProject { + /** + * Project name + */ + projectFileName: string; + /** + * List of root files in project + */ + rootFiles: ExternalFile[]; + /** + * Compiler options for the project + */ + options: ExternalProjectCompilerOptions; + /** + * @deprecated typingOptions. Use typeAcquisition instead + */ + typingOptions?: TypeAcquisition; + /** + * Explicitly specified type acquisition for the project + */ + typeAcquisition?: TypeAcquisition; + } + interface CompileOnSaveMixin { + /** + * If compile on save is enabled for the project + */ + compileOnSave?: boolean; + } + /** + * For external projects, some of the project settings are sent together with + * compiler settings. + */ + type ExternalProjectCompilerOptions = CompilerOptions & CompileOnSaveMixin; + /** + * Represents a set of changes that happen in project + */ + interface ProjectChanges { + /** + * List of added files + */ + added: string[]; + /** + * List of removed files + */ + removed: string[]; + /** + * List of updated files + */ + updated: string[]; + } + /** + * Information found in a configure request. + */ + interface ConfigureRequestArguments { + /** + * Information about the host, for example 'Emacs 24.4' or + * 'Sublime Text version 3075' + */ + hostInfo?: string; + /** + * If present, tab settings apply only to this file. + */ + file?: string; + /** + * The format options to use during formatting and other code editing features. + */ + formatOptions?: FormatCodeSettings; + preferences?: UserPreferences; + /** + * The host's additional supported .js file extensions + */ + extraFileExtensions?: FileExtensionInfo[]; + } + /** + * Configure request; value of command field is "configure". Specifies + * host information, such as host type, tab size, and indent size. + */ + interface ConfigureRequest extends Request { + command: CommandTypes.Configure; + arguments: ConfigureRequestArguments; + } + /** + * Response to "configure" request. This is just an acknowledgement, so + * no body field is required. + */ + interface ConfigureResponse extends Response { + } + interface ConfigurePluginRequestArguments { + pluginName: string; + configuration: any; + } + interface ConfigurePluginRequest extends Request { + command: CommandTypes.ConfigurePlugin; + arguments: ConfigurePluginRequestArguments; + } + /** + * Information found in an "open" request. + */ + interface OpenRequestArgs extends FileRequestArgs { + /** + * Used when a version of the file content is known to be more up to date than the one on disk. + * Then the known content will be used upon opening instead of the disk copy + */ + fileContent?: string; + /** + * Used to specify the script kind of the file explicitly. It could be one of the following: + * "TS", "JS", "TSX", "JSX" + */ + scriptKindName?: ScriptKindName; + /** + * Used to limit the searching for project config file. If given the searching will stop at this + * root path; otherwise it will go all the way up to the dist root path. + */ + projectRootPath?: string; + } + type ScriptKindName = "TS" | "JS" | "TSX" | "JSX"; + /** + * Open request; value of command field is "open". Notify the + * server that the client has file open. The server will not + * monitor the filesystem for changes in this file and will assume + * that the client is updating the server (using the change and/or + * reload messages) when the file changes. Server does not currently + * send a response to an open request. + */ + interface OpenRequest extends Request { + command: CommandTypes.Open; + arguments: OpenRequestArgs; + } + /** + * Request to open or update external project + */ + interface OpenExternalProjectRequest extends Request { + command: CommandTypes.OpenExternalProject; + arguments: OpenExternalProjectArgs; + } + /** + * Arguments to OpenExternalProjectRequest request + */ + type OpenExternalProjectArgs = ExternalProject; + /** + * Request to open multiple external projects + */ + interface OpenExternalProjectsRequest extends Request { + command: CommandTypes.OpenExternalProjects; + arguments: OpenExternalProjectsArgs; + } + /** + * Arguments to OpenExternalProjectsRequest + */ + interface OpenExternalProjectsArgs { + /** + * List of external projects to open or update + */ + projects: ExternalProject[]; + } + /** + * Response to OpenExternalProjectRequest request. This is just an acknowledgement, so + * no body field is required. + */ + interface OpenExternalProjectResponse extends Response { + } + /** + * Response to OpenExternalProjectsRequest request. This is just an acknowledgement, so + * no body field is required. + */ + interface OpenExternalProjectsResponse extends Response { + } + /** + * Request to close external project. + */ + interface CloseExternalProjectRequest extends Request { + command: CommandTypes.CloseExternalProject; + arguments: CloseExternalProjectRequestArgs; + } + /** + * Arguments to CloseExternalProjectRequest request + */ + interface CloseExternalProjectRequestArgs { + /** + * Name of the project to close + */ + projectFileName: string; + } + /** + * Response to CloseExternalProjectRequest request. This is just an acknowledgement, so + * no body field is required. + */ + interface CloseExternalProjectResponse extends Response { + } + /** + * Request to set compiler options for inferred projects. + * External projects are opened / closed explicitly. + * Configured projects are opened when user opens loose file that has 'tsconfig.json' or 'jsconfig.json' anywhere in one of containing folders. + * This configuration file will be used to obtain a list of files and configuration settings for the project. + * Inferred projects are created when user opens a loose file that is not the part of external project + * or configured project and will contain only open file and transitive closure of referenced files if 'useOneInferredProject' is false, + * or all open loose files and its transitive closure of referenced files if 'useOneInferredProject' is true. + */ + interface SetCompilerOptionsForInferredProjectsRequest extends Request { + command: CommandTypes.CompilerOptionsForInferredProjects; + arguments: SetCompilerOptionsForInferredProjectsArgs; + } + /** + * Argument for SetCompilerOptionsForInferredProjectsRequest request. + */ + interface SetCompilerOptionsForInferredProjectsArgs { + /** + * Compiler options to be used with inferred projects. + */ + options: ExternalProjectCompilerOptions; + /** + * Specifies the project root path used to scope compiler options. + * It is an error to provide this property if the server has not been started with + * `useInferredProjectPerProjectRoot` enabled. + */ + projectRootPath?: string; + } + /** + * Response to SetCompilerOptionsForInferredProjectsResponse request. This is just an acknowledgement, so + * no body field is required. + */ + interface SetCompilerOptionsForInferredProjectsResponse extends Response { + } + /** + * Exit request; value of command field is "exit". Ask the server process + * to exit. + */ + interface ExitRequest extends Request { + command: CommandTypes.Exit; + } + /** + * Close request; value of command field is "close". Notify the + * server that the client has closed a previously open file. If + * file is still referenced by open files, the server will resume + * monitoring the filesystem for changes to file. Server does not + * currently send a response to a close request. + */ + interface CloseRequest extends FileRequest { + command: CommandTypes.Close; + } + /** + * Request to obtain the list of files that should be regenerated if target file is recompiled. + * NOTE: this us query-only operation and does not generate any output on disk. + */ + interface CompileOnSaveAffectedFileListRequest extends FileRequest { + command: CommandTypes.CompileOnSaveAffectedFileList; + } + /** + * Contains a list of files that should be regenerated in a project + */ + interface CompileOnSaveAffectedFileListSingleProject { + /** + * Project name + */ + projectFileName: string; + /** + * List of files names that should be recompiled + */ + fileNames: string[]; + /** + * true if project uses outFile or out compiler option + */ + projectUsesOutFile: boolean; + } + /** + * Response for CompileOnSaveAffectedFileListRequest request; + */ + interface CompileOnSaveAffectedFileListResponse extends Response { + body: CompileOnSaveAffectedFileListSingleProject[]; + } + /** + * Request to recompile the file. All generated outputs (.js, .d.ts or .js.map files) is written on disk. + */ + interface CompileOnSaveEmitFileRequest extends FileRequest { + command: CommandTypes.CompileOnSaveEmitFile; + arguments: CompileOnSaveEmitFileRequestArgs; + } + /** + * Arguments for CompileOnSaveEmitFileRequest + */ + interface CompileOnSaveEmitFileRequestArgs extends FileRequestArgs { + /** + * if true - then file should be recompiled even if it does not have any changes. + */ + forced?: boolean; + } + /** + * Quickinfo request; value of command field is + * "quickinfo". Return response giving a quick type and + * documentation string for the symbol found in file at location + * line, col. + */ + interface QuickInfoRequest extends FileLocationRequest { + command: CommandTypes.Quickinfo; + } + /** + * Body of QuickInfoResponse. + */ + interface QuickInfoResponseBody { + /** + * The symbol's kind (such as 'className' or 'parameterName' or plain 'text'). + */ + kind: ScriptElementKind; + /** + * Optional modifiers for the kind (such as 'public'). + */ + kindModifiers: string; + /** + * Starting file location of symbol. + */ + start: Location; + /** + * One past last character of symbol. + */ + end: Location; + /** + * Type and kind of symbol. + */ + displayString: string; + /** + * Documentation associated with symbol. + */ + documentation: string; + /** + * JSDoc tags associated with symbol. + */ + tags: JSDocTagInfo[]; + } + /** + * Quickinfo response message. + */ + interface QuickInfoResponse extends Response { + body?: QuickInfoResponseBody; + } + /** + * Arguments for format messages. + */ + interface FormatRequestArgs extends FileLocationRequestArgs { + /** + * Last line of range for which to format text in file. + */ + endLine: number; + /** + * Character offset on last line of range for which to format text in file. + */ + endOffset: number; + /** + * Format options to be used. + */ + options?: FormatCodeSettings; + } + /** + * Format request; value of command field is "format". Return + * response giving zero or more edit instructions. The edit + * instructions will be sorted in file order. Applying the edit + * instructions in reverse to file will result in correctly + * reformatted text. + */ + interface FormatRequest extends FileLocationRequest { + command: CommandTypes.Format; + arguments: FormatRequestArgs; + } + /** + * Object found in response messages defining an editing + * instruction for a span of text in source code. The effect of + * this instruction is to replace the text starting at start and + * ending one character before end with newText. For an insertion, + * the text span is empty. For a deletion, newText is empty. + */ + interface CodeEdit { + /** + * First character of the text span to edit. + */ + start: Location; + /** + * One character past last character of the text span to edit. + */ + end: Location; + /** + * Replace the span defined above with this string (may be + * the empty string). + */ + newText: string; + } + interface FileCodeEdits { + fileName: string; + textChanges: CodeEdit[]; + } + interface CodeFixResponse extends Response { + /** The code actions that are available */ + body?: CodeFixAction[]; + } + interface CodeAction { + /** Description of the code action to display in the UI of the editor */ + description: string; + /** Text changes to apply to each file as part of the code action */ + changes: FileCodeEdits[]; + /** A command is an opaque object that should be passed to `ApplyCodeActionCommandRequestArgs` without modification. */ + commands?: {}[]; + } + interface CombinedCodeActions { + changes: ReadonlyArray; + commands?: ReadonlyArray<{}>; + } + interface CodeFixAction extends CodeAction { + /** Short name to identify the fix, for use by telemetry. */ + fixName: string; + /** + * If present, one may call 'getCombinedCodeFix' with this fixId. + * This may be omitted to indicate that the code fix can't be applied in a group. + */ + fixId?: {}; + /** Should be present if and only if 'fixId' is. */ + fixAllDescription?: string; + } + /** + * Format and format on key response message. + */ + interface FormatResponse extends Response { + body?: CodeEdit[]; + } + /** + * Arguments for format on key messages. + */ + interface FormatOnKeyRequestArgs extends FileLocationRequestArgs { + /** + * Key pressed (';', '\n', or '}'). + */ + key: string; + options?: FormatCodeSettings; + } + /** + * Format on key request; value of command field is + * "formatonkey". Given file location and key typed (as string), + * return response giving zero or more edit instructions. The + * edit instructions will be sorted in file order. Applying the + * edit instructions in reverse to file will result in correctly + * reformatted text. + */ + interface FormatOnKeyRequest extends FileLocationRequest { + command: CommandTypes.Formatonkey; + arguments: FormatOnKeyRequestArgs; + } + type CompletionsTriggerCharacter = "." | '"' | "'" | "`" | "/" | "@" | "<"; + /** + * Arguments for completions messages. + */ + interface CompletionsRequestArgs extends FileLocationRequestArgs { + /** + * Optional prefix to apply to possible completions. + */ + prefix?: string; + /** + * Character that was responsible for triggering completion. + * Should be `undefined` if a user manually requested completion. + */ + triggerCharacter?: CompletionsTriggerCharacter; + /** + * @deprecated Use UserPreferences.includeCompletionsForModuleExports + */ + includeExternalModuleExports?: boolean; + /** + * @deprecated Use UserPreferences.includeCompletionsWithInsertText + */ + includeInsertTextCompletions?: boolean; + } + /** + * Completions request; value of command field is "completions". + * Given a file location (file, line, col) and a prefix (which may + * be the empty string), return the possible completions that + * begin with prefix. + */ + interface CompletionsRequest extends FileLocationRequest { + command: CommandTypes.Completions | CommandTypes.CompletionInfo; + arguments: CompletionsRequestArgs; + } + /** + * Arguments for completion details request. + */ + interface CompletionDetailsRequestArgs extends FileLocationRequestArgs { + /** + * Names of one or more entries for which to obtain details. + */ + entryNames: (string | CompletionEntryIdentifier)[]; + } + interface CompletionEntryIdentifier { + name: string; + source?: string; + } + /** + * Completion entry details request; value of command field is + * "completionEntryDetails". Given a file location (file, line, + * col) and an array of completion entry names return more + * detailed information for each completion entry. + */ + interface CompletionDetailsRequest extends FileLocationRequest { + command: CommandTypes.CompletionDetails; + arguments: CompletionDetailsRequestArgs; + } + /** + * Part of a symbol description. + */ + interface SymbolDisplayPart { + /** + * Text of an item describing the symbol. + */ + text: string; + /** + * The symbol's kind (such as 'className' or 'parameterName' or plain 'text'). + */ + kind: string; + } + /** + * An item found in a completion response. + */ + interface CompletionEntry { + /** + * The symbol's name. + */ + name: string; + /** + * The symbol's kind (such as 'className' or 'parameterName'). + */ + kind: ScriptElementKind; + /** + * Optional modifiers for the kind (such as 'public'). + */ + kindModifiers?: string; + /** + * A string that is used for comparing completion items so that they can be ordered. This + * is often the same as the name but may be different in certain circumstances. + */ + sortText: string; + /** + * Text to insert instead of `name`. + * This is used to support bracketed completions; If `name` might be "a-b" but `insertText` would be `["a-b"]`, + * coupled with `replacementSpan` to replace a dotted access with a bracket access. + */ + insertText?: string; + /** + * An optional span that indicates the text to be replaced by this completion item. + * If present, this span should be used instead of the default one. + * It will be set if the required span differs from the one generated by the default replacement behavior. + */ + replacementSpan?: TextSpan; + /** + * Indicates whether commiting this completion entry will require additional code actions to be + * made to avoid errors. The CompletionEntryDetails will have these actions. + */ + hasAction?: true; + /** + * Identifier (not necessarily human-readable) identifying where this completion came from. + */ + source?: string; + /** + * If true, this completion should be highlighted as recommended. There will only be one of these. + * This will be set when we know the user should write an expression with a certain type and that type is an enum or constructable class. + * Then either that enum/class or a namespace containing it will be the recommended symbol. + */ + isRecommended?: true; + } + /** + * Additional completion entry details, available on demand + */ + interface CompletionEntryDetails { + /** + * The symbol's name. + */ + name: string; + /** + * The symbol's kind (such as 'className' or 'parameterName'). + */ + kind: ScriptElementKind; + /** + * Optional modifiers for the kind (such as 'public'). + */ + kindModifiers: string; + /** + * Display parts of the symbol (similar to quick info). + */ + displayParts: SymbolDisplayPart[]; + /** + * Documentation strings for the symbol. + */ + documentation?: SymbolDisplayPart[]; + /** + * JSDoc tags for the symbol. + */ + tags?: JSDocTagInfo[]; + /** + * The associated code actions for this entry + */ + codeActions?: CodeAction[]; + /** + * Human-readable description of the `source` from the CompletionEntry. + */ + source?: SymbolDisplayPart[]; + } + /** @deprecated Prefer CompletionInfoResponse, which supports several top-level fields in addition to the array of entries. */ + interface CompletionsResponse extends Response { + body?: CompletionEntry[]; + } + interface CompletionInfoResponse extends Response { + body?: CompletionInfo; + } + interface CompletionInfo { + readonly isGlobalCompletion: boolean; + readonly isMemberCompletion: boolean; + readonly isNewIdentifierLocation: boolean; + readonly entries: ReadonlyArray; + } + interface CompletionDetailsResponse extends Response { + body?: CompletionEntryDetails[]; + } + /** + * Signature help information for a single parameter + */ + interface SignatureHelpParameter { + /** + * The parameter's name + */ + name: string; + /** + * Documentation of the parameter. + */ + documentation: SymbolDisplayPart[]; + /** + * Display parts of the parameter. + */ + displayParts: SymbolDisplayPart[]; + /** + * Whether the parameter is optional or not. + */ + isOptional: boolean; + } + /** + * Represents a single signature to show in signature help. + */ + interface SignatureHelpItem { + /** + * Whether the signature accepts a variable number of arguments. + */ + isVariadic: boolean; + /** + * The prefix display parts. + */ + prefixDisplayParts: SymbolDisplayPart[]; + /** + * The suffix display parts. + */ + suffixDisplayParts: SymbolDisplayPart[]; + /** + * The separator display parts. + */ + separatorDisplayParts: SymbolDisplayPart[]; + /** + * The signature helps items for the parameters. + */ + parameters: SignatureHelpParameter[]; + /** + * The signature's documentation + */ + documentation: SymbolDisplayPart[]; + /** + * The signature's JSDoc tags + */ + tags: JSDocTagInfo[]; + } + /** + * Signature help items found in the response of a signature help request. + */ + interface SignatureHelpItems { + /** + * The signature help items. + */ + items: SignatureHelpItem[]; + /** + * The span for which signature help should appear on a signature + */ + applicableSpan: TextSpan; + /** + * The item selected in the set of available help items. + */ + selectedItemIndex: number; + /** + * The argument selected in the set of parameters. + */ + argumentIndex: number; + /** + * The argument count + */ + argumentCount: number; + } + type SignatureHelpTriggerCharacter = "," | "(" | "<"; + type SignatureHelpRetriggerCharacter = SignatureHelpTriggerCharacter | ")"; + /** + * Arguments of a signature help request. + */ + interface SignatureHelpRequestArgs extends FileLocationRequestArgs { + /** + * Reason why signature help was invoked. + * See each individual possible + */ + triggerReason?: SignatureHelpTriggerReason; + } + type SignatureHelpTriggerReason = SignatureHelpInvokedReason | SignatureHelpCharacterTypedReason | SignatureHelpRetriggeredReason; + /** + * Signals that the user manually requested signature help. + * The language service will unconditionally attempt to provide a result. + */ + interface SignatureHelpInvokedReason { + kind: "invoked"; + triggerCharacter?: undefined; + } + /** + * Signals that the signature help request came from a user typing a character. + * Depending on the character and the syntactic context, the request may or may not be served a result. + */ + interface SignatureHelpCharacterTypedReason { + kind: "characterTyped"; + /** + * Character that was responsible for triggering signature help. + */ + triggerCharacter: SignatureHelpTriggerCharacter; + } + /** + * Signals that this signature help request came from typing a character or moving the cursor. + * This should only occur if a signature help session was already active and the editor needs to see if it should adjust. + * The language service will unconditionally attempt to provide a result. + * `triggerCharacter` can be `undefined` for a retrigger caused by a cursor move. + */ + interface SignatureHelpRetriggeredReason { + kind: "retrigger"; + /** + * Character that was responsible for triggering signature help. + */ + triggerCharacter?: SignatureHelpRetriggerCharacter; + } + /** + * Signature help request; value of command field is "signatureHelp". + * Given a file location (file, line, col), return the signature + * help. + */ + interface SignatureHelpRequest extends FileLocationRequest { + command: CommandTypes.SignatureHelp; + arguments: SignatureHelpRequestArgs; + } + /** + * Response object for a SignatureHelpRequest. + */ + interface SignatureHelpResponse extends Response { + body?: SignatureHelpItems; + } + /** + * Synchronous request for semantic diagnostics of one file. + */ + interface SemanticDiagnosticsSyncRequest extends FileRequest { + command: CommandTypes.SemanticDiagnosticsSync; + arguments: SemanticDiagnosticsSyncRequestArgs; + } + interface SemanticDiagnosticsSyncRequestArgs extends FileRequestArgs { + includeLinePosition?: boolean; + } + /** + * Response object for synchronous sematic diagnostics request. + */ + interface SemanticDiagnosticsSyncResponse extends Response { + body?: Diagnostic[] | DiagnosticWithLinePosition[]; + } + interface SuggestionDiagnosticsSyncRequest extends FileRequest { + command: CommandTypes.SuggestionDiagnosticsSync; + arguments: SuggestionDiagnosticsSyncRequestArgs; + } + type SuggestionDiagnosticsSyncRequestArgs = SemanticDiagnosticsSyncRequestArgs; + type SuggestionDiagnosticsSyncResponse = SemanticDiagnosticsSyncResponse; + /** + * Synchronous request for syntactic diagnostics of one file. + */ + interface SyntacticDiagnosticsSyncRequest extends FileRequest { + command: CommandTypes.SyntacticDiagnosticsSync; + arguments: SyntacticDiagnosticsSyncRequestArgs; + } + interface SyntacticDiagnosticsSyncRequestArgs extends FileRequestArgs { + includeLinePosition?: boolean; + } + /** + * Response object for synchronous syntactic diagnostics request. + */ + interface SyntacticDiagnosticsSyncResponse extends Response { + body?: Diagnostic[] | DiagnosticWithLinePosition[]; + } + /** + * Arguments for GeterrForProject request. + */ + interface GeterrForProjectRequestArgs { + /** + * the file requesting project error list + */ + file: string; + /** + * Delay in milliseconds to wait before starting to compute + * errors for the files in the file list + */ + delay: number; + } + /** + * GeterrForProjectRequest request; value of command field is + * "geterrForProject". It works similarly with 'Geterr', only + * it request for every file in this project. + */ + interface GeterrForProjectRequest extends Request { + command: CommandTypes.GeterrForProject; + arguments: GeterrForProjectRequestArgs; + } + /** + * Arguments for geterr messages. + */ + interface GeterrRequestArgs { + /** + * List of file names for which to compute compiler errors. + * The files will be checked in list order. + */ + files: string[]; + /** + * Delay in milliseconds to wait before starting to compute + * errors for the files in the file list + */ + delay: number; + } + /** + * Geterr request; value of command field is "geterr". Wait for + * delay milliseconds and then, if during the wait no change or + * reload messages have arrived for the first file in the files + * list, get the syntactic errors for the file, field requests, + * and then get the semantic errors for the file. Repeat with a + * smaller delay for each subsequent file on the files list. Best + * practice for an editor is to send a file list containing each + * file that is currently visible, in most-recently-used order. + */ + interface GeterrRequest extends Request { + command: CommandTypes.Geterr; + arguments: GeterrRequestArgs; + } + type RequestCompletedEventName = "requestCompleted"; + /** + * Event that is sent when server have finished processing request with specified id. + */ + interface RequestCompletedEvent extends Event { + event: RequestCompletedEventName; + body: RequestCompletedEventBody; + } + interface RequestCompletedEventBody { + request_seq: number; + } + /** + * Item of diagnostic information found in a DiagnosticEvent message. + */ + interface Diagnostic { + /** + * Starting file location at which text applies. + */ + start: Location; + /** + * The last file location at which the text applies. + */ + end: Location; + /** + * Text of diagnostic message. + */ + text: string; + /** + * The category of the diagnostic message, e.g. "error", "warning", or "suggestion". + */ + category: string; + reportsUnnecessary?: {}; + /** + * Any related spans the diagnostic may have, such as other locations relevant to an error, such as declarartion sites + */ + relatedInformation?: DiagnosticRelatedInformation[]; + /** + * The error code of the diagnostic message. + */ + code?: number; + /** + * The name of the plugin reporting the message. + */ + source?: string; + } + interface DiagnosticWithFileName extends Diagnostic { + /** + * Name of the file the diagnostic is in + */ + fileName: string; + } + /** + * Represents additional spans returned with a diagnostic which are relevant to it + */ + interface DiagnosticRelatedInformation { + /** + * The category of the related information message, e.g. "error", "warning", or "suggestion". + */ + category: string; + /** + * The code used ot identify the related information + */ + code: number; + /** + * Text of related or additional information. + */ + message: string; + /** + * Associated location + */ + span?: FileSpan; + } + interface DiagnosticEventBody { + /** + * The file for which diagnostic information is reported. + */ + file: string; + /** + * An array of diagnostic information items. + */ + diagnostics: Diagnostic[]; + } + type DiagnosticEventKind = "semanticDiag" | "syntaxDiag" | "suggestionDiag"; + /** + * Event message for DiagnosticEventKind event types. + * These events provide syntactic and semantic errors for a file. + */ + interface DiagnosticEvent extends Event { + body?: DiagnosticEventBody; + event: DiagnosticEventKind; + } + interface ConfigFileDiagnosticEventBody { + /** + * The file which trigged the searching and error-checking of the config file + */ + triggerFile: string; + /** + * The name of the found config file. + */ + configFile: string; + /** + * An arry of diagnostic information items for the found config file. + */ + diagnostics: DiagnosticWithFileName[]; + } + /** + * Event message for "configFileDiag" event type. + * This event provides errors for a found config file. + */ + interface ConfigFileDiagnosticEvent extends Event { + body?: ConfigFileDiagnosticEventBody; + event: "configFileDiag"; + } + type ProjectLanguageServiceStateEventName = "projectLanguageServiceState"; + interface ProjectLanguageServiceStateEvent extends Event { + event: ProjectLanguageServiceStateEventName; + body?: ProjectLanguageServiceStateEventBody; + } + interface ProjectLanguageServiceStateEventBody { + /** + * Project name that has changes in the state of language service. + * For configured projects this will be the config file path. + * For external projects this will be the name of the projects specified when project was open. + * For inferred projects this event is not raised. + */ + projectName: string; + /** + * True if language service state switched from disabled to enabled + * and false otherwise. + */ + languageServiceEnabled: boolean; + } + type ProjectsUpdatedInBackgroundEventName = "projectsUpdatedInBackground"; + interface ProjectsUpdatedInBackgroundEvent extends Event { + event: ProjectsUpdatedInBackgroundEventName; + body: ProjectsUpdatedInBackgroundEventBody; + } + interface ProjectsUpdatedInBackgroundEventBody { + /** + * Current set of open files + */ + openFiles: string[]; + } + type ProjectLoadingStartEventName = "projectLoadingStart"; + interface ProjectLoadingStartEvent extends Event { + event: ProjectLoadingStartEventName; + body: ProjectLoadingStartEventBody; + } + interface ProjectLoadingStartEventBody { + /** name of the project */ + projectName: string; + /** reason for loading */ + reason: string; + } + type ProjectLoadingFinishEventName = "projectLoadingFinish"; + interface ProjectLoadingFinishEvent extends Event { + event: ProjectLoadingFinishEventName; + body: ProjectLoadingFinishEventBody; + } + interface ProjectLoadingFinishEventBody { + /** name of the project */ + projectName: string; + } + type SurveyReadyEventName = "surveyReady"; + interface SurveyReadyEvent extends Event { + event: SurveyReadyEventName; + body: SurveyReadyEventBody; + } + interface SurveyReadyEventBody { + /** Name of the survey. This is an internal machine- and programmer-friendly name */ + surveyId: string; + } + type LargeFileReferencedEventName = "largeFileReferenced"; + interface LargeFileReferencedEvent extends Event { + event: LargeFileReferencedEventName; + body: LargeFileReferencedEventBody; + } + interface LargeFileReferencedEventBody { + /** + * name of the large file being loaded + */ + file: string; + /** + * size of the file + */ + fileSize: number; + /** + * max file size allowed on the server + */ + maxFileSize: number; + } + /** + * Arguments for reload request. + */ + interface ReloadRequestArgs extends FileRequestArgs { + /** + * Name of temporary file from which to reload file + * contents. May be same as file. + */ + tmpfile: string; + } + /** + * Reload request message; value of command field is "reload". + * Reload contents of file with name given by the 'file' argument + * from temporary file with name given by the 'tmpfile' argument. + * The two names can be identical. + */ + interface ReloadRequest extends FileRequest { + command: CommandTypes.Reload; + arguments: ReloadRequestArgs; + } + /** + * Response to "reload" request. This is just an acknowledgement, so + * no body field is required. + */ + interface ReloadResponse extends Response { + } + /** + * Arguments for saveto request. + */ + interface SavetoRequestArgs extends FileRequestArgs { + /** + * Name of temporary file into which to save server's view of + * file contents. + */ + tmpfile: string; + } + /** + * Saveto request message; value of command field is "saveto". + * For debugging purposes, save to a temporaryfile (named by + * argument 'tmpfile') the contents of file named by argument + * 'file'. The server does not currently send a response to a + * "saveto" request. + */ + interface SavetoRequest extends FileRequest { + command: CommandTypes.Saveto; + arguments: SavetoRequestArgs; + } + /** + * Arguments for navto request message. + */ + interface NavtoRequestArgs extends FileRequestArgs { + /** + * Search term to navigate to from current location; term can + * be '.*' or an identifier prefix. + */ + searchValue: string; + /** + * Optional limit on the number of items to return. + */ + maxResultCount?: number; + /** + * Optional flag to indicate we want results for just the current file + * or the entire project. + */ + currentFileOnly?: boolean; + projectFileName?: string; + } + /** + * Navto request message; value of command field is "navto". + * Return list of objects giving file locations and symbols that + * match the search term given in argument 'searchTerm'. The + * context for the search is given by the named file. + */ + interface NavtoRequest extends FileRequest { + command: CommandTypes.Navto; + arguments: NavtoRequestArgs; + } + /** + * An item found in a navto response. + */ + interface NavtoItem extends FileSpan { + /** + * The symbol's name. + */ + name: string; + /** + * The symbol's kind (such as 'className' or 'parameterName'). + */ + kind: ScriptElementKind; + /** + * exact, substring, or prefix. + */ + matchKind: string; + /** + * If this was a case sensitive or insensitive match. + */ + isCaseSensitive: boolean; + /** + * Optional modifiers for the kind (such as 'public'). + */ + kindModifiers?: string; + /** + * Name of symbol's container symbol (if any); for example, + * the class name if symbol is a class member. + */ + containerName?: string; + /** + * Kind of symbol's container symbol (if any). + */ + containerKind?: ScriptElementKind; + } + /** + * Navto response message. Body is an array of navto items. Each + * item gives a symbol that matched the search term. + */ + interface NavtoResponse extends Response { + body?: NavtoItem[]; + } + /** + * Arguments for change request message. + */ + interface ChangeRequestArgs extends FormatRequestArgs { + /** + * Optional string to insert at location (file, line, offset). + */ + insertString?: string; + } + /** + * Change request message; value of command field is "change". + * Update the server's view of the file named by argument 'file'. + * Server does not currently send a response to a change request. + */ + interface ChangeRequest extends FileLocationRequest { + command: CommandTypes.Change; + arguments: ChangeRequestArgs; + } + /** + * Response to "brace" request. + */ + interface BraceResponse extends Response { + body?: TextSpan[]; + } + /** + * Brace matching request; value of command field is "brace". + * Return response giving the file locations of matching braces + * found in file at location line, offset. + */ + interface BraceRequest extends FileLocationRequest { + command: CommandTypes.Brace; + } + /** + * NavBar items request; value of command field is "navbar". + * Return response giving the list of navigation bar entries + * extracted from the requested file. + */ + interface NavBarRequest extends FileRequest { + command: CommandTypes.NavBar; + } + /** + * NavTree request; value of command field is "navtree". + * Return response giving the navigation tree of the requested file. + */ + interface NavTreeRequest extends FileRequest { + command: CommandTypes.NavTree; + } + interface NavigationBarItem { + /** + * The item's display text. + */ + text: string; + /** + * The symbol's kind (such as 'className' or 'parameterName'). + */ + kind: ScriptElementKind; + /** + * Optional modifiers for the kind (such as 'public'). + */ + kindModifiers?: string; + /** + * The definition locations of the item. + */ + spans: TextSpan[]; + /** + * Optional children. + */ + childItems?: NavigationBarItem[]; + /** + * Number of levels deep this item should appear. + */ + indent: number; + } + /** protocol.NavigationTree is identical to ts.NavigationTree, except using protocol.TextSpan instead of ts.TextSpan */ + interface NavigationTree { + text: string; + kind: ScriptElementKind; + kindModifiers: string; + spans: TextSpan[]; + nameSpan: TextSpan | undefined; + childItems?: NavigationTree[]; + } + type TelemetryEventName = "telemetry"; + interface TelemetryEvent extends Event { + event: TelemetryEventName; + body: TelemetryEventBody; + } + interface TelemetryEventBody { + telemetryEventName: string; + payload: any; + } + type TypesInstallerInitializationFailedEventName = "typesInstallerInitializationFailed"; + interface TypesInstallerInitializationFailedEvent extends Event { + event: TypesInstallerInitializationFailedEventName; + body: TypesInstallerInitializationFailedEventBody; + } + interface TypesInstallerInitializationFailedEventBody { + message: string; + } + type TypingsInstalledTelemetryEventName = "typingsInstalled"; + interface TypingsInstalledTelemetryEventBody extends TelemetryEventBody { + telemetryEventName: TypingsInstalledTelemetryEventName; + payload: TypingsInstalledTelemetryEventPayload; + } + interface TypingsInstalledTelemetryEventPayload { + /** + * Comma separated list of installed typing packages + */ + installedPackages: string; + /** + * true if install request succeeded, otherwise - false + */ + installSuccess: boolean; + /** + * version of typings installer + */ + typingsInstallerVersion: string; + } + type BeginInstallTypesEventName = "beginInstallTypes"; + type EndInstallTypesEventName = "endInstallTypes"; + interface BeginInstallTypesEvent extends Event { + event: BeginInstallTypesEventName; + body: BeginInstallTypesEventBody; + } + interface EndInstallTypesEvent extends Event { + event: EndInstallTypesEventName; + body: EndInstallTypesEventBody; + } + interface InstallTypesEventBody { + /** + * correlation id to match begin and end events + */ + eventId: number; + /** + * list of packages to install + */ + packages: ReadonlyArray; + } + interface BeginInstallTypesEventBody extends InstallTypesEventBody { + } + interface EndInstallTypesEventBody extends InstallTypesEventBody { + /** + * true if installation succeeded, otherwise false + */ + success: boolean; + } + interface NavBarResponse extends Response { + body?: NavigationBarItem[]; + } + interface NavTreeResponse extends Response { + body?: NavigationTree; + } + enum IndentStyle { + None = "None", + Block = "Block", + Smart = "Smart" + } + interface EditorSettings { + baseIndentSize?: number; + indentSize?: number; + tabSize?: number; + newLineCharacter?: string; + convertTabsToSpaces?: boolean; + indentStyle?: IndentStyle | ts.IndentStyle; + } + interface FormatCodeSettings extends EditorSettings { + insertSpaceAfterCommaDelimiter?: boolean; + insertSpaceAfterSemicolonInForStatements?: boolean; + insertSpaceBeforeAndAfterBinaryOperators?: boolean; + insertSpaceAfterConstructor?: boolean; + insertSpaceAfterKeywordsInControlFlowStatements?: boolean; + insertSpaceAfterFunctionKeywordForAnonymousFunctions?: boolean; + insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis?: boolean; + insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets?: boolean; + insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces?: boolean; + insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces?: boolean; + insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces?: boolean; + insertSpaceAfterTypeAssertion?: boolean; + insertSpaceBeforeFunctionParenthesis?: boolean; + placeOpenBraceOnNewLineForFunctions?: boolean; + placeOpenBraceOnNewLineForControlBlocks?: boolean; + insertSpaceBeforeTypeAnnotation?: boolean; + } + interface UserPreferences { + readonly disableSuggestions?: boolean; + readonly quotePreference?: "double" | "single"; + /** + * If enabled, TypeScript will search through all external modules' exports and add them to the completions list. + * This affects lone identifier completions but not completions on the right hand side of `obj.`. + */ + readonly includeCompletionsForModuleExports?: boolean; + /** + * If enabled, the completion list will include completions with invalid identifier names. + * For those entries, The `insertText` and `replacementSpan` properties will be set to change from `.x` property access to `["x"]`. + */ + readonly includeCompletionsWithInsertText?: boolean; + readonly importModuleSpecifierPreference?: "relative" | "non-relative"; + readonly allowTextChangesInNewFiles?: boolean; + readonly lazyConfiguredProjectsFromExternalProject?: boolean; + } + interface CompilerOptions { + allowJs?: boolean; + allowSyntheticDefaultImports?: boolean; + allowUnreachableCode?: boolean; + allowUnusedLabels?: boolean; + alwaysStrict?: boolean; + baseUrl?: string; + charset?: string; + checkJs?: boolean; + declaration?: boolean; + declarationDir?: string; + disableSizeLimit?: boolean; + downlevelIteration?: boolean; + emitBOM?: boolean; + emitDecoratorMetadata?: boolean; + experimentalDecorators?: boolean; + forceConsistentCasingInFileNames?: boolean; + importHelpers?: boolean; + inlineSourceMap?: boolean; + inlineSources?: boolean; + isolatedModules?: boolean; + jsx?: JsxEmit | ts.JsxEmit; + lib?: string[]; + locale?: string; + mapRoot?: string; + maxNodeModuleJsDepth?: number; + module?: ModuleKind | ts.ModuleKind; + moduleResolution?: ModuleResolutionKind | ts.ModuleResolutionKind; + newLine?: NewLineKind | ts.NewLineKind; + noEmit?: boolean; + noEmitHelpers?: boolean; + noEmitOnError?: boolean; + noErrorTruncation?: boolean; + noFallthroughCasesInSwitch?: boolean; + noImplicitAny?: boolean; + noImplicitReturns?: boolean; + noImplicitThis?: boolean; + noUnusedLocals?: boolean; + noUnusedParameters?: boolean; + noImplicitUseStrict?: boolean; + noLib?: boolean; + noResolve?: boolean; + out?: string; + outDir?: string; + outFile?: string; + paths?: MapLike; + plugins?: PluginImport[]; + preserveConstEnums?: boolean; + preserveSymlinks?: boolean; + project?: string; + reactNamespace?: string; + removeComments?: boolean; + references?: ProjectReference[]; + rootDir?: string; + rootDirs?: string[]; + skipLibCheck?: boolean; + skipDefaultLibCheck?: boolean; + sourceMap?: boolean; + sourceRoot?: string; + strict?: boolean; + strictNullChecks?: boolean; + suppressExcessPropertyErrors?: boolean; + suppressImplicitAnyIndexErrors?: boolean; + target?: ScriptTarget | ts.ScriptTarget; + traceResolution?: boolean; + resolveJsonModule?: boolean; + types?: string[]; + /** Paths used to used to compute primary types search locations */ + typeRoots?: string[]; + [option: string]: CompilerOptionsValue | undefined; + } + enum JsxEmit { + None = "None", + Preserve = "Preserve", + ReactNative = "ReactNative", + React = "React" + } + enum ModuleKind { + None = "None", + CommonJS = "CommonJS", + AMD = "AMD", + UMD = "UMD", + System = "System", + ES6 = "ES6", + ES2015 = "ES2015", + ESNext = "ESNext" + } + enum ModuleResolutionKind { + Classic = "Classic", + Node = "Node" + } + enum NewLineKind { + Crlf = "Crlf", + Lf = "Lf" + } + enum ScriptTarget { + ES3 = "ES3", + ES5 = "ES5", + ES6 = "ES6", + ES2015 = "ES2015", + ES2016 = "ES2016", + ES2017 = "ES2017", + ESNext = "ESNext" + } +} +declare namespace ts.server { + interface ScriptInfoVersion { + svc: number; + text: number; + } + class ScriptInfo { + private readonly host; + readonly fileName: NormalizedPath; + readonly scriptKind: ScriptKind; + readonly hasMixedContent: boolean; + readonly path: Path; + /** + * All projects that include this file + */ + readonly containingProjects: Project[]; + private formatSettings; + private preferences; + private textStorage; + constructor(host: ServerHost, fileName: NormalizedPath, scriptKind: ScriptKind, hasMixedContent: boolean, path: Path, initialVersion?: ScriptInfoVersion); + isScriptOpen(): boolean; + open(newText: string): void; + close(fileExists?: boolean): void; + getSnapshot(): IScriptSnapshot; + private ensureRealPath; + getFormatCodeSettings(): FormatCodeSettings | undefined; + getPreferences(): protocol.UserPreferences | undefined; + attachToProject(project: Project): boolean; + isAttached(project: Project): boolean; + detachFromProject(project: Project): void; + detachAllProjects(): void; + getDefaultProject(): Project; + registerFileUpdate(): void; + setOptions(formatSettings: FormatCodeSettings, preferences: protocol.UserPreferences | undefined): void; + getLatestVersion(): string; + saveTo(fileName: string): void; + reloadFromFile(tempFileName?: NormalizedPath): boolean; + editContent(start: number, end: number, newText: string): void; + markContainingProjectsAsDirty(): void; + isOrphan(): boolean; + /** + * @param line 1 based index + */ + lineToTextSpan(line: number): TextSpan; + /** + * @param line 1 based index + * @param offset 1 based index + */ + lineOffsetToPosition(line: number, offset: number): number; + positionToLineOffset(position: number): protocol.Location; + isJavaScript(): boolean; + } +} +declare namespace ts.server { + interface InstallPackageOptionsWithProject extends InstallPackageOptions { + projectName: string; + projectRootPath: Path; + } + interface ITypingsInstaller { + isKnownTypesPackageName(name: string): boolean; + installPackage(options: InstallPackageOptionsWithProject): Promise; + enqueueInstallTypingsRequest(p: Project, typeAcquisition: TypeAcquisition, unresolvedImports: SortedReadonlyArray | undefined): void; + attach(projectService: ProjectService): void; + onProjectClosed(p: Project): void; + readonly globalTypingsCacheLocation: string | undefined; + } + const nullTypingsInstaller: ITypingsInstaller; +} +declare namespace ts.server { + enum ProjectKind { + Inferred = 0, + Configured = 1, + External = 2 + } + function allRootFilesAreJsOrDts(project: Project): boolean; + function allFilesAreJsOrDts(project: Project): boolean; + interface PluginCreateInfo { + project: Project; + languageService: LanguageService; + languageServiceHost: LanguageServiceHost; + serverHost: ServerHost; + config: any; + } + interface PluginModule { + create(createInfo: PluginCreateInfo): LanguageService; + getExternalFiles?(proj: Project): string[]; + onConfigurationChanged?(config: any): void; + } + interface PluginModuleWithName { + name: string; + module: PluginModule; + } + type PluginModuleFactory = (mod: { + typescript: typeof ts; + }) => PluginModule; + /** + * The project root can be script info - if root is present, + * or it could be just normalized path if root wasnt present on the host(only for non inferred project) + */ + type ProjectRoot = ScriptInfo | NormalizedPath; + abstract class Project implements LanguageServiceHost, ModuleResolutionHost { + readonly projectName: string; + readonly projectKind: ProjectKind; + readonly projectService: ProjectService; + private documentRegistry; + private compilerOptions; + compileOnSaveEnabled: boolean; + private rootFiles; + private rootFilesMap; + private program; + private externalFiles; + private missingFilesMap; + private plugins; + private lastFileExceededProgramSize; + protected languageService: LanguageService; + languageServiceEnabled: boolean; + readonly trace?: (s: string) => void; + readonly realpath?: (path: string) => string; + private builderState; + /** + * Set of files names that were updated since the last call to getChangesSinceVersion. + */ + private updatedFileNames; + /** + * Set of files that was returned from the last call to getChangesSinceVersion. + */ + private lastReportedFileNames; + /** + * Last version that was reported. + */ + private lastReportedVersion; + /** + * Current project's program version. (incremented everytime new program is created that is not complete reuse from the old one) + * This property is changed in 'updateGraph' based on the set of files in program + */ + private projectProgramVersion; + /** + * Current version of the project state. It is changed when: + * - new root file was added/removed + * - edit happen in some file that is currently included in the project. + * This property is different from projectStructureVersion since in most cases edits don't affect set of files in the project + */ + private projectStateVersion; + protected isInitialLoadPending: () => boolean; + private readonly cancellationToken; + isNonTsProject(): boolean; + isJsOnlyProject(): boolean; + static resolveModule(moduleName: string, initialDir: string, host: ServerHost, log: (message: string) => void): {} | undefined; + isKnownTypesPackageName(name: string): boolean; + installPackage(options: InstallPackageOptions): Promise; + private readonly typingsCache; + getCompilationSettings(): CompilerOptions; + getCompilerOptions(): CompilerOptions; + getNewLine(): string; + getProjectVersion(): string; + getProjectReferences(): ReadonlyArray | undefined; + getScriptFileNames(): string[]; + private getOrCreateScriptInfoAndAttachToProject; + getScriptKind(fileName: string): ScriptKind; + getScriptVersion(filename: string): string; + getScriptSnapshot(filename: string): IScriptSnapshot | undefined; + getCancellationToken(): HostCancellationToken; + getCurrentDirectory(): string; + getDefaultLibFileName(): string; + useCaseSensitiveFileNames(): boolean; + readDirectory(path: string, extensions?: ReadonlyArray, exclude?: ReadonlyArray, include?: ReadonlyArray, depth?: number): string[]; + readFile(fileName: string): string | undefined; + writeFile(fileName: string, content: string): void; + fileExists(file: string): boolean; + resolveModuleNames(moduleNames: string[], containingFile: string, reusedNames?: string[], redirectedReference?: ResolvedProjectReference): (ResolvedModuleFull | undefined)[]; + getResolvedModuleWithFailedLookupLocationsFromCache(moduleName: string, containingFile: string): ResolvedModuleWithFailedLookupLocations | undefined; + resolveTypeReferenceDirectives(typeDirectiveNames: string[], containingFile: string, redirectedReference?: ResolvedProjectReference): (ResolvedTypeReferenceDirective | undefined)[]; + directoryExists(path: string): boolean; + getDirectories(path: string): string[]; + log(s: string): void; + error(s: string): void; + private setInternalCompilerOptionsForEmittingJsFiles; + /** + * Get the errors that dont have any file name associated + */ + getGlobalProjectErrors(): ReadonlyArray; + getAllProjectErrors(): ReadonlyArray; + getLanguageService(ensureSynchronized?: boolean): LanguageService; + private shouldEmitFile; + getCompileOnSaveAffectedFileList(scriptInfo: ScriptInfo): string[]; + /** + * Returns true if emit was conducted + */ + emitFile(scriptInfo: ScriptInfo, writeFile: (path: string, data: string, writeByteOrderMark?: boolean) => void): boolean; + enableLanguageService(): void; + disableLanguageService(lastFileExceededProgramSize?: string): void; + getProjectName(): string; + abstract getTypeAcquisition(): TypeAcquisition; + protected removeLocalTypingsFromTypeAcquisition(newTypeAcquisition: TypeAcquisition): TypeAcquisition; + getExternalFiles(): SortedReadonlyArray; + getSourceFile(path: Path): SourceFile | undefined; + close(): void; + private detachScriptInfoIfNotRoot; + isClosed(): boolean; + hasRoots(): boolean; + getRootFiles(): NormalizedPath[]; + getRootScriptInfos(): ScriptInfo[]; + getScriptInfos(): ScriptInfo[]; + getExcludedFiles(): ReadonlyArray; + getFileNames(excludeFilesFromExternalLibraries?: boolean, excludeConfigFiles?: boolean): NormalizedPath[]; + hasConfigFile(configFilePath: NormalizedPath): boolean; + containsScriptInfo(info: ScriptInfo): boolean; + containsFile(filename: NormalizedPath, requireOpen?: boolean): boolean; + isRoot(info: ScriptInfo): boolean; + addRoot(info: ScriptInfo): void; + addMissingFileRoot(fileName: NormalizedPath): void; + removeFile(info: ScriptInfo, fileExists: boolean, detachFromProject: boolean): void; + registerFileUpdate(fileName: string): void; + markAsDirty(): void; + /** + * Updates set of files that contribute to this project + * @returns: true if set of files in the project stays the same and false - otherwise. + */ + updateGraph(): boolean; + protected removeExistingTypings(include: string[]): string[]; + private updateGraphWorker; + private detachScriptInfoFromProject; + private addMissingFileWatcher; + private isWatchedMissingFile; + getScriptInfoForNormalizedPath(fileName: NormalizedPath): ScriptInfo | undefined; + getScriptInfo(uncheckedFileName: string): ScriptInfo | undefined; + filesToString(writeProjectFileNames: boolean): string; + setCompilerOptions(compilerOptions: CompilerOptions): void; + protected removeRoot(info: ScriptInfo): void; + protected enableGlobalPlugins(options: CompilerOptions, pluginConfigOverrides: Map | undefined): void; + protected enablePlugin(pluginConfigEntry: PluginImport, searchPaths: string[], pluginConfigOverrides: Map | undefined): void; + private enableProxy; + /** Starts a new check for diagnostics. Call this if some file has updated that would cause diagnostics to be changed. */ + refreshDiagnostics(): void; + } + /** + * If a file is opened and no tsconfig (or jsconfig) is found, + * the file and its imports/references are put into an InferredProject. + */ + class InferredProject extends Project { + private static readonly newName; + private _isJsInferredProject; + toggleJsInferredProject(isJsInferredProject: boolean): void; + setCompilerOptions(options?: CompilerOptions): void; + /** this is canonical project root path */ + readonly projectRootPath: string | undefined; + addRoot(info: ScriptInfo): void; + removeRoot(info: ScriptInfo): void; + isProjectWithSingleRoot(): boolean; + close(): void; + getTypeAcquisition(): TypeAcquisition; + } + /** + * If a file is opened, the server will look for a tsconfig (or jsconfig) + * and if successfull create a ConfiguredProject for it. + * Otherwise it will create an InferredProject. + */ + class ConfiguredProject extends Project { + private typeAcquisition; + private directoriesWatchedForWildcards; + readonly canonicalConfigFilePath: NormalizedPath; + /** Ref count to the project when opened from external project */ + private externalProjectRefCount; + private projectErrors; + private projectReferences; + protected isInitialLoadPending: () => boolean; + /** + * If the project has reload from disk pending, it reloads (and then updates graph as part of that) instead of just updating the graph + * @returns: true if set of files in the project stays the same and false - otherwise. + */ + updateGraph(): boolean; + getConfigFilePath(): NormalizedPath; + getProjectReferences(): ReadonlyArray | undefined; + updateReferences(refs: ReadonlyArray | undefined): void; + /** + * Get the errors that dont have any file name associated + */ + getGlobalProjectErrors(): ReadonlyArray; + /** + * Get all the project errors + */ + getAllProjectErrors(): ReadonlyArray; + setProjectErrors(projectErrors: Diagnostic[]): void; + setTypeAcquisition(newTypeAcquisition: TypeAcquisition): void; + getTypeAcquisition(): TypeAcquisition; + close(): void; + getEffectiveTypeRoots(): string[]; + } + /** + * Project whose configuration is handled externally, such as in a '.csproj'. + * These are created only if a host explicitly calls `openExternalProject`. + */ + class ExternalProject extends Project { + externalProjectName: string; + compileOnSaveEnabled: boolean; + excludedFiles: ReadonlyArray; + private typeAcquisition; + updateGraph(): boolean; + getExcludedFiles(): ReadonlyArray; + getTypeAcquisition(): TypeAcquisition; + setTypeAcquisition(newTypeAcquisition: TypeAcquisition): void; + } +} +declare namespace ts.server { + const maxProgramSizeForNonTsFiles: number; + const ProjectsUpdatedInBackgroundEvent = "projectsUpdatedInBackground"; + const ProjectLoadingStartEvent = "projectLoadingStart"; + const ProjectLoadingFinishEvent = "projectLoadingFinish"; + const SurveyReady = "surveyReady"; + const LargeFileReferencedEvent = "largeFileReferenced"; + const ConfigFileDiagEvent = "configFileDiag"; + const ProjectLanguageServiceStateEvent = "projectLanguageServiceState"; + const ProjectInfoTelemetryEvent = "projectInfo"; + const OpenFileInfoTelemetryEvent = "openFileInfo"; + interface ProjectsUpdatedInBackgroundEvent { + eventName: typeof ProjectsUpdatedInBackgroundEvent; + data: { + openFiles: string[]; + }; + } + interface ProjectLoadingStartEvent { + eventName: typeof ProjectLoadingStartEvent; + data: { + project: Project; + reason: string; + }; + } + interface ProjectLoadingFinishEvent { + eventName: typeof ProjectLoadingFinishEvent; + data: { + project: Project; + }; + } + interface SurveyReady { + eventName: typeof SurveyReady; + data: { + surveyId: string; + }; + } + interface LargeFileReferencedEvent { + eventName: typeof LargeFileReferencedEvent; + data: { + file: string; + fileSize: number; + maxFileSize: number; + }; + } + interface ConfigFileDiagEvent { + eventName: typeof ConfigFileDiagEvent; + data: { + triggerFile: string; + configFileName: string; + diagnostics: ReadonlyArray; + }; + } + interface ProjectLanguageServiceStateEvent { + eventName: typeof ProjectLanguageServiceStateEvent; + data: { + project: Project; + languageServiceEnabled: boolean; + }; + } + /** This will be converted to the payload of a protocol.TelemetryEvent in session.defaultEventHandler. */ + interface ProjectInfoTelemetryEvent { + readonly eventName: typeof ProjectInfoTelemetryEvent; + readonly data: ProjectInfoTelemetryEventData; + } + interface ProjectInfoTelemetryEventData { + /** Cryptographically secure hash of project file location. */ + readonly projectId: string; + /** Count of file extensions seen in the project. */ + readonly fileStats: FileStats; + /** + * Any compiler options that might contain paths will be taken out. + * Enum compiler options will be converted to strings. + */ + readonly compilerOptions: CompilerOptions; + readonly extends: boolean | undefined; + readonly files: boolean | undefined; + readonly include: boolean | undefined; + readonly exclude: boolean | undefined; + readonly compileOnSave: boolean; + readonly typeAcquisition: ProjectInfoTypeAcquisitionData; + readonly configFileName: "tsconfig.json" | "jsconfig.json" | "other"; + readonly projectType: "external" | "configured"; + readonly languageServiceEnabled: boolean; + /** TypeScript version used by the server. */ + readonly version: string; + } + /** + * Info that we may send about a file that was just opened. + * Info about a file will only be sent once per session, even if the file changes in ways that might affect the info. + * Currently this is only sent for '.js' files. + */ + interface OpenFileInfoTelemetryEvent { + readonly eventName: typeof OpenFileInfoTelemetryEvent; + readonly data: OpenFileInfoTelemetryEventData; + } + interface OpenFileInfoTelemetryEventData { + readonly info: OpenFileInfo; + } + interface ProjectInfoTypeAcquisitionData { + readonly enable: boolean | undefined; + readonly include: boolean; + readonly exclude: boolean; + } + interface FileStats { + readonly js: number; + readonly jsSize?: number; + readonly jsx: number; + readonly jsxSize?: number; + readonly ts: number; + readonly tsSize?: number; + readonly tsx: number; + readonly tsxSize?: number; + readonly dts: number; + readonly dtsSize?: number; + readonly deferred: number; + readonly deferredSize?: number; + } + interface OpenFileInfo { + readonly checkJs: boolean; + } + type ProjectServiceEvent = LargeFileReferencedEvent | SurveyReady | ProjectsUpdatedInBackgroundEvent | ProjectLoadingStartEvent | ProjectLoadingFinishEvent | ConfigFileDiagEvent | ProjectLanguageServiceStateEvent | ProjectInfoTelemetryEvent | OpenFileInfoTelemetryEvent; + type ProjectServiceEventHandler = (event: ProjectServiceEvent) => void; + interface SafeList { + [name: string]: { + match: RegExp; + exclude?: (string | number)[][]; + types?: string[]; + }; + } + interface TypesMapFile { + typesMap: SafeList; + simpleMap: { + [libName: string]: string; + }; + } + function convertFormatOptions(protocolOptions: protocol.FormatCodeSettings): FormatCodeSettings; + function convertCompilerOptions(protocolOptions: protocol.ExternalProjectCompilerOptions): CompilerOptions & protocol.CompileOnSaveMixin; + function tryConvertScriptKindName(scriptKindName: protocol.ScriptKindName | ScriptKind): ScriptKind; + function convertScriptKindName(scriptKindName: protocol.ScriptKindName): ScriptKind.Unknown | ScriptKind.JS | ScriptKind.JSX | ScriptKind.TS | ScriptKind.TSX; + interface HostConfiguration { + formatCodeOptions: FormatCodeSettings; + preferences: protocol.UserPreferences; + hostInfo: string; + extraFileExtensions?: FileExtensionInfo[]; + } + interface OpenConfiguredProjectResult { + configFileName?: NormalizedPath; + configFileErrors?: ReadonlyArray; + } + interface ProjectServiceOptions { + host: ServerHost; + logger: Logger; + cancellationToken: HostCancellationToken; + useSingleInferredProject: boolean; + useInferredProjectPerProjectRoot: boolean; + typingsInstaller: ITypingsInstaller; + eventHandler?: ProjectServiceEventHandler; + suppressDiagnosticEvents?: boolean; + throttleWaitMilliseconds?: number; + globalPlugins?: ReadonlyArray; + pluginProbeLocations?: ReadonlyArray; + allowLocalPluginLoads?: boolean; + typesMapLocation?: string; + syntaxOnly?: boolean; + } + class ProjectService { + /** + * Container of all known scripts + */ + private readonly filenameToScriptInfo; + private readonly scriptInfoInNodeModulesWatchers; + /** + * Contains all the deleted script info's version information so that + * it does not reset when creating script info again + * (and could have potentially collided with version where contents mismatch) + */ + private readonly filenameToScriptInfoVersion; + private readonly allJsFilesForOpenFileTelemetry; + /** + * maps external project file name to list of config files that were the part of this project + */ + private readonly externalProjectToConfiguredProjectMap; + /** + * external projects (configuration and list of root files is not controlled by tsserver) + */ + readonly externalProjects: ExternalProject[]; + /** + * projects built from openFileRoots + */ + readonly inferredProjects: InferredProject[]; + /** + * projects specified by a tsconfig.json file + */ + readonly configuredProjects: Map; + /** + * Open files: with value being project root path, and key being Path of the file that is open + */ + readonly openFiles: Map; + /** + * Map of open files that are opened without complete path but have projectRoot as current directory + */ + private readonly openFilesWithNonRootedDiskPath; + private compilerOptionsForInferredProjects; + private compilerOptionsForInferredProjectsPerProjectRoot; + /** + * Project size for configured or external projects + */ + private readonly projectToSizeMap; + /** + * This is a map of config file paths existance that doesnt need query to disk + * - The entry can be present because there is inferred project that needs to watch addition of config file to directory + * In this case the exists could be true/false based on config file is present or not + * - Or it is present if we have configured project open with config file at that location + * In this case the exists property is always true + */ + private readonly configFileExistenceInfoCache; + private readonly throttledOperations; + private readonly hostConfiguration; + private safelist; + private readonly legacySafelist; + private pendingProjectUpdates; + readonly currentDirectory: NormalizedPath; + readonly toCanonicalFileName: (f: string) => string; + readonly host: ServerHost; + readonly logger: Logger; + readonly cancellationToken: HostCancellationToken; + readonly useSingleInferredProject: boolean; + readonly useInferredProjectPerProjectRoot: boolean; + readonly typingsInstaller: ITypingsInstaller; + private readonly globalCacheLocationDirectoryPath; + readonly throttleWaitMilliseconds?: number; + private readonly eventHandler?; + private readonly suppressDiagnosticEvents?; + readonly globalPlugins: ReadonlyArray; + readonly pluginProbeLocations: ReadonlyArray; + readonly allowLocalPluginLoads: boolean; + private currentPluginConfigOverrides; + readonly typesMapLocation: string | undefined; + readonly syntaxOnly?: boolean; + /** Tracks projects that we have already sent telemetry for. */ + private readonly seenProjects; + /** Tracks projects that we have already sent survey events for. */ + private readonly seenSurveyProjects; + constructor(opts: ProjectServiceOptions); + toPath(fileName: string): Path; + private loadTypesMap; + updateTypingsForProject(response: SetTypings | InvalidateCachedTypings | PackageInstalledResponse): void; + private delayEnsureProjectForOpenFiles; + private delayUpdateProjectGraph; + private delayUpdateProjectGraphs; + setCompilerOptionsForInferredProjects(projectCompilerOptions: protocol.ExternalProjectCompilerOptions, projectRootPath?: string): void; + findProject(projectName: string): Project | undefined; + getDefaultProjectForFile(fileName: NormalizedPath, ensureProject: boolean): Project | undefined; + private doEnsureDefaultProjectForFile; + getScriptInfoEnsuringProjectsUptoDate(uncheckedFileName: string): ScriptInfo | undefined; + /** + * Ensures the project structures are upto date + * This means, + * - we go through all the projects and update them if they are dirty + * - if updates reflect some change in structure or there was pending request to ensure projects for open files + * ensure that each open script info has project + */ + private ensureProjectStructuresUptoDate; + getFormatCodeOptions(file: NormalizedPath): FormatCodeSettings; + getPreferences(file: NormalizedPath): protocol.UserPreferences; + getHostFormatCodeOptions(): FormatCodeSettings; + getHostPreferences(): protocol.UserPreferences; + private onSourceFileChanged; + private handleDeletedFile; + private onConfigChangedForConfiguredProject; + /** + * This is the callback function for the config file add/remove/change at any location + * that matters to open script info but doesnt have configured project open + * for the config file + */ + private onConfigFileChangeForOpenScriptInfo; + private removeProject; + /** + * Remove this file from the set of open, non-configured files. + * @param info The file that has been closed or newly configured + */ + private closeOpenFile; + private deleteScriptInfo; + private configFileExists; + private setConfigFileExistenceByNewConfiguredProject; + /** + * Returns true if the configFileExistenceInfo is needed/impacted by open files that are root of inferred project + */ + private configFileExistenceImpactsRootOfInferredProject; + private setConfigFileExistenceInfoByClosedConfiguredProject; + private logConfigFileWatchUpdate; + /** + * Create the watcher for the configFileExistenceInfo + */ + private createConfigFileWatcherOfConfigFileExistence; + /** + * Close the config file watcher in the cached ConfigFileExistenceInfo + * if there arent any open files that are root of inferred project + */ + private closeConfigFileWatcherOfConfigFileExistenceInfo; + /** + * This is called on file close, so that we stop watching the config file for this script info + */ + private stopWatchingConfigFilesForClosedScriptInfo; + /** + * This function tries to search for a tsconfig.json for the given file. + * This is different from the method the compiler uses because + * the compiler can assume it will always start searching in the + * current directory (the directory in which tsc was invoked). + * The server must start searching from the directory containing + * the newly opened file. + */ + private forEachConfigFileLocation; + /** + * This function tries to search for a tsconfig.json for the given file. + * This is different from the method the compiler uses because + * the compiler can assume it will always start searching in the + * current directory (the directory in which tsc was invoked). + * The server must start searching from the directory containing + * the newly opened file. + * If script info is passed in, it is asserted to be open script info + * otherwise just file name + */ + private getConfigFileNameForFile; + private printProjects; + private findConfiguredProjectByProjectName; + private getConfiguredProjectByCanonicalConfigFilePath; + private findExternalProjectByProjectName; + /** Get a filename if the language service exceeds the maximum allowed program size; otherwise returns undefined. */ + private getFilenameForExceededTotalSizeLimitForNonTsFiles; + private createExternalProject; + private addFilesToNonInferredProject; + private createConfiguredProject; + private updateNonInferredProjectFiles; + private updateRootAndOptionsOfNonInferredProject; + private sendConfigFileDiagEvent; + private getOrCreateInferredProjectForProjectRootPathIfEnabled; + private getOrCreateSingleInferredProjectIfEnabled; + private getOrCreateSingleInferredWithoutProjectRoot; + private createInferredProject; + getScriptInfo(uncheckedFileName: string): ScriptInfo | undefined; + private watchClosedScriptInfo; + private watchClosedScriptInfoInNodeModules; + private getModifiedTime; + private refreshScriptInfo; + private refreshScriptInfosInDirectory; + private stopWatchingScriptInfo; + private getOrCreateScriptInfoNotOpenedByClientForNormalizedPath; + private getOrCreateScriptInfoOpenedByClientForNormalizedPath; + getOrCreateScriptInfoForNormalizedPath(fileName: NormalizedPath, openedByClient: boolean, fileContent?: string, scriptKind?: ScriptKind, hasMixedContent?: boolean, hostToQueryFileExistsOn?: { + fileExists(path: string): boolean; + }): ScriptInfo | undefined; + private getOrCreateScriptInfoWorker; + /** + * This gets the script info for the normalized path. If the path is not rooted disk path then the open script info with project root context is preferred + */ + getScriptInfoForNormalizedPath(fileName: NormalizedPath): ScriptInfo | undefined; + getScriptInfoForPath(fileName: Path): ScriptInfo | undefined; + setHostConfiguration(args: protocol.ConfigureRequestArguments): void; + closeLog(): void; + /** + * This function rebuilds the project for every file opened by the client + * This does not reload contents of open files from disk. But we could do that if needed + */ + reloadProjects(): void; + private delayReloadConfiguredProjectForFiles; + /** + * This function goes through all the openFiles and tries to file the config file for them. + * If the config file is found and it refers to existing project, it reloads it either immediately + * or schedules it for reload depending on delayReload option + * If the there is no existing project it just opens the configured project for the config file + * reloadForInfo provides a way to filter out files to reload configured project for + */ + private reloadConfiguredProjectForFiles; + /** + * Remove the root of inferred project if script info is part of another project + */ + private removeRootOfInferredProjectIfNowPartOfOtherProject; + /** + * This function is to update the project structure for every inferred project. + * It is called on the premise that all the configured projects are + * up to date. + * This will go through open files and assign them to inferred project if open file is not part of any other project + * After that all the inferred project graphs are updated + */ + private ensureProjectForOpenFiles; + /** + * Open file whose contents is managed by the client + * @param filename is absolute pathname + * @param fileContent is a known version of the file content that is more up to date than the one on disk + */ + openClientFile(fileName: string, fileContent?: string, scriptKind?: ScriptKind, projectRootPath?: string): OpenConfiguredProjectResult; + private findExternalProjectContainingOpenScriptInfo; + openClientFileWithNormalizedPath(fileName: NormalizedPath, fileContent?: string, scriptKind?: ScriptKind, hasMixedContent?: boolean, projectRootPath?: NormalizedPath): OpenConfiguredProjectResult; + private removeOrphanConfiguredProjects; + private telemetryOnOpenFile; + /** + * Close file whose contents is managed by the client + * @param filename is absolute pathname + */ + closeClientFile(uncheckedFileName: string): void; + private collectChanges; + private closeConfiguredProjectReferencedFromExternalProject; + closeExternalProject(uncheckedFileName: string): void; + openExternalProjects(projects: protocol.ExternalProject[]): void; + /** Makes a filename safe to insert in a RegExp */ + private static readonly filenameEscapeRegexp; + private static escapeFilenameForRegex; + resetSafeList(): void; + applySafeList(proj: protocol.ExternalProject): NormalizedPath[]; + openExternalProject(proj: protocol.ExternalProject): void; + hasDeferredExtension(): boolean; + configurePlugin(args: protocol.ConfigurePluginRequestArguments): void; + } +} +declare namespace ts.server { + interface ServerCancellationToken extends HostCancellationToken { + setRequest(requestId: number): void; + resetRequest(requestId: number): void; + } + const nullCancellationToken: ServerCancellationToken; + interface PendingErrorCheck { + fileName: NormalizedPath; + project: Project; + } + type CommandNames = protocol.CommandTypes; + const CommandNames: any; + function formatMessage(msg: T, logger: Logger, byteLength: (s: string, encoding: string) => number, newLine: string): string; + type Event = (body: T, eventName: string) => void; + interface EventSender { + event: Event; + } + interface SessionOptions { + host: ServerHost; + cancellationToken: ServerCancellationToken; + useSingleInferredProject: boolean; + useInferredProjectPerProjectRoot: boolean; + typingsInstaller: ITypingsInstaller; + byteLength: (buf: string, encoding?: string) => number; + hrtime: (start?: number[]) => number[]; + logger: Logger; + /** + * If falsy, all events are suppressed. + */ + canUseEvents: boolean; + eventHandler?: ProjectServiceEventHandler; + /** Has no effect if eventHandler is also specified. */ + suppressDiagnosticEvents?: boolean; + syntaxOnly?: boolean; + throttleWaitMilliseconds?: number; + noGetErrOnBackgroundUpdate?: boolean; + globalPlugins?: ReadonlyArray; + pluginProbeLocations?: ReadonlyArray; + allowLocalPluginLoads?: boolean; + typesMapLocation?: string; + } + class Session implements EventSender { + private readonly gcTimer; + protected projectService: ProjectService; + private changeSeq; + private currentRequestId; + private errorCheck; + protected host: ServerHost; + private readonly cancellationToken; + protected readonly typingsInstaller: ITypingsInstaller; + protected byteLength: (buf: string, encoding?: string) => number; + private hrtime; + protected logger: Logger; + protected canUseEvents: boolean; + private suppressDiagnosticEvents?; + private eventHandler; + private readonly noGetErrOnBackgroundUpdate?; + constructor(opts: SessionOptions); + private sendRequestCompletedEvent; + private defaultEventHandler; + private projectsUpdatedInBackgroundEvent; + logError(err: Error, cmd: string): void; + private logErrorWorker; + send(msg: protocol.Message): void; + event(body: T, eventName: string): void; + /** @deprecated */ + output(info: any, cmdName: string, reqSeq?: number, errorMsg?: string): void; + private doOutput; + private semanticCheck; + private syntacticCheck; + private suggestionCheck; + private sendDiagnosticsEvent; + /** It is the caller's responsibility to verify that `!this.suppressDiagnosticEvents`. */ + private updateErrorCheck; + private cleanProjects; + private cleanup; + private getEncodedSemanticClassifications; + private getProject; + private getConfigFileAndProject; + private getConfigFileDiagnostics; + private convertToDiagnosticsWithLinePositionFromDiagnosticFile; + private getCompilerOptionsDiagnostics; + private convertToDiagnosticsWithLinePosition; + private getDiagnosticsWorker; + private getDefinition; + private mapDefinitionInfoLocations; + private getDefinitionAndBoundSpan; + private getEmitOutput; + private mapDefinitionInfo; + private static mapToOriginalLocation; + private toFileSpan; + private getTypeDefinition; + private mapImplementationLocations; + private getImplementation; + private getOccurrences; + private getSyntacticDiagnosticsSync; + private getSemanticDiagnosticsSync; + private getSuggestionDiagnosticsSync; + private getJsxClosingTag; + private getDocumentHighlights; + private setCompilerOptionsForInferredProjects; + private getProjectInfo; + private getProjectInfoWorker; + private getRenameInfo; + private getProjects; + private getDefaultProject; + private getRenameLocations; + private mapRenameInfo; + private toSpanGroups; + private getReferences; + /** + * @param fileName is the name of the file to be opened + * @param fileContent is a version of the file content that is known to be more up to date than the one on disk + */ + private openClientFile; + private getPosition; + private getPositionInFile; + private getFileAndProject; + private getFileAndLanguageServiceForSyntacticOperation; + private getFileAndProjectWorker; + private getOutliningSpans; + private getTodoComments; + private getDocCommentTemplate; + private getSpanOfEnclosingComment; + private getIndentation; + private getBreakpointStatement; + private getNameOrDottedNameSpan; + private isValidBraceCompletion; + private getQuickInfoWorker; + private getFormattingEditsForRange; + private getFormattingEditsForRangeFull; + private getFormattingEditsForDocumentFull; + private getFormattingEditsAfterKeystrokeFull; + private getFormattingEditsAfterKeystroke; + private getCompletions; + private getCompletionEntryDetails; + private getCompileOnSaveAffectedFileList; + private emitFile; + private getSignatureHelpItems; + private createCheckList; + private getDiagnostics; + private change; + private reload; + private saveToTmp; + private closeClientFile; + private mapLocationNavigationBarItems; + private getNavigationBarItems; + private toLocationNavigationTree; + private toLocationTextSpan; + private getNavigationTree; + private getNavigateToItems; + private getFullNavigateToItems; + private getSupportedCodeFixes; + private isLocation; + private extractPositionOrRange; + private getApplicableRefactors; + private getEditsForRefactor; + private organizeImports; + private getEditsForFileRename; + private getCodeFixes; + private getCombinedCodeFix; + private applyCodeActionCommand; + private getStartAndEndPosition; + private mapCodeAction; + private mapCodeFixAction; + private mapTextChangesToCodeEdits; + private mapTextChangeToCodeEdit; + private convertTextChangeToCodeEdit; + private getBraceMatching; + private getDiagnosticsForProject; + private configurePlugin; + getCanonicalFileName(fileName: string): string; + exit(): void; + private notRequired; + private requiredResponse; + private handlers; + addProtocolHandler(command: string, handler: (request: protocol.Request) => HandlerResponse): void; + private setCurrentRequest; + private resetCurrentRequest; + executeWithRequestId(requestId: number, f: () => T): T; + executeCommand(request: protocol.Request): HandlerResponse; + onMessage(message: string): void; + private getFormatOptions; + private getPreferences; + private getHostFormatOptions; + private getHostPreferences; + } + interface HandlerResponse { + response?: {}; + responseRequired?: boolean; + } +} + +export = ts; +export as namespace ts; \ No newline at end of file diff --git a/node_modules/typescript/lib/tsserverlibrary.js b/node_modules/typescript/lib/tsserverlibrary.js new file mode 100644 index 0000000..997b33e --- /dev/null +++ b/node_modules/typescript/lib/tsserverlibrary.js @@ -0,0 +1,127410 @@ +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + +"use strict"; +var __assign = (this && this.__assign) || function () { + __assign = Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; + }; + return __assign.apply(this, arguments); +}; +var __generator = (this && this.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } +}; +var __makeTemplateObject = (this && this.__makeTemplateObject) || function (cooked, raw) { + if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } + return cooked; +}; +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +var __rest = (this && this.__rest) || function (s, e) { + var t = {}; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) + t[p] = s[p]; + if (s != null && typeof Object.getOwnPropertySymbols === "function") + for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) if (e.indexOf(p[i]) < 0) + t[p[i]] = s[p[i]]; + return t; +}; +var ts; +(function (ts) { + // WARNING: The script `configureNightly.ts` uses a regexp to parse out these values. + // If changing the text in this section, be sure to test `configureNightly` too. + ts.versionMajorMinor = "3.2"; + /** The version of the TypeScript compiler release */ + ts.version = ts.versionMajorMinor + ".2"; +})(ts || (ts = {})); +(function (ts) { + /* @internal */ + var Comparison; + (function (Comparison) { + Comparison[Comparison["LessThan"] = -1] = "LessThan"; + Comparison[Comparison["EqualTo"] = 0] = "EqualTo"; + Comparison[Comparison["GreaterThan"] = 1] = "GreaterThan"; + })(Comparison = ts.Comparison || (ts.Comparison = {})); +})(ts || (ts = {})); +/* @internal */ +(function (ts) { + ts.emptyArray = []; + /** Create a MapLike with good performance. */ + function createDictionaryObject() { + var map = Object.create(/*prototype*/ null); // tslint:disable-line:no-null-keyword + // Using 'delete' on an object causes V8 to put the object in dictionary mode. + // This disables creation of hidden classes, which are expensive when an object is + // constantly changing shape. + map.__ = undefined; + delete map.__; + return map; + } + /** Create a new map. If a template object is provided, the map will copy entries from it. */ + function createMap() { + return new ts.MapCtr(); + } + ts.createMap = createMap; + function createMapFromEntries(entries) { + var map = createMap(); + for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) { + var _a = entries_1[_i], key = _a[0], value = _a[1]; + map.set(key, value); + } + return map; + } + ts.createMapFromEntries = createMapFromEntries; + function createMapFromTemplate(template) { + var map = new ts.MapCtr(); + // Copies keys/values from template. Note that for..in will not throw if + // template is undefined, and instead will just exit the loop. + for (var key in template) { + if (hasOwnProperty.call(template, key)) { + map.set(key, template[key]); + } + } + return map; + } + ts.createMapFromTemplate = createMapFromTemplate; + // Internet Explorer's Map doesn't support iteration, so don't use it. + // tslint:disable-next-line no-in-operator variable-name + ts.MapCtr = typeof Map !== "undefined" && "entries" in Map.prototype ? Map : shimMap(); + // Keep the class inside a function so it doesn't get compiled if it's not used. + function shimMap() { + var MapIterator = /** @class */ (function () { + function MapIterator(data, selector) { + this.index = 0; + this.data = data; + this.selector = selector; + this.keys = Object.keys(data); + } + MapIterator.prototype.next = function () { + var index = this.index; + if (index < this.keys.length) { + this.index++; + return { value: this.selector(this.data, this.keys[index]), done: false }; + } + return { value: undefined, done: true }; + }; + return MapIterator; + }()); + return /** @class */ (function () { + function class_1() { + this.data = createDictionaryObject(); + this.size = 0; + } + class_1.prototype.get = function (key) { + return this.data[key]; + }; + class_1.prototype.set = function (key, value) { + if (!this.has(key)) { + this.size++; + } + this.data[key] = value; + return this; + }; + class_1.prototype.has = function (key) { + // tslint:disable-next-line:no-in-operator + return key in this.data; + }; + class_1.prototype.delete = function (key) { + if (this.has(key)) { + this.size--; + delete this.data[key]; + return true; + } + return false; + }; + class_1.prototype.clear = function () { + this.data = createDictionaryObject(); + this.size = 0; + }; + class_1.prototype.keys = function () { + return new MapIterator(this.data, function (_data, key) { return key; }); + }; + class_1.prototype.values = function () { + return new MapIterator(this.data, function (data, key) { return data[key]; }); + }; + class_1.prototype.entries = function () { + return new MapIterator(this.data, function (data, key) { return [key, data[key]]; }); + }; + class_1.prototype.forEach = function (action) { + for (var key in this.data) { + action(this.data[key], key); + } + }; + return class_1; + }()); + } + function length(array) { + return array ? array.length : 0; + } + ts.length = length; + /** + * Iterates through 'array' by index and performs the callback on each element of array until the callback + * returns a truthy value, then returns that value. + * If no such value is found, the callback is applied to each element of array and undefined is returned. + */ + function forEach(array, callback) { + if (array) { + for (var i = 0; i < array.length; i++) { + var result = callback(array[i], i); + if (result) { + return result; + } + } + } + return undefined; + } + ts.forEach = forEach; + /** Like `forEach`, but suitable for use with numbers and strings (which may be falsy). */ + function firstDefined(array, callback) { + if (array === undefined) { + return undefined; + } + for (var i = 0; i < array.length; i++) { + var result = callback(array[i], i); + if (result !== undefined) { + return result; + } + } + return undefined; + } + ts.firstDefined = firstDefined; + function firstDefinedIterator(iter, callback) { + while (true) { + var _a = iter.next(), value = _a.value, done = _a.done; + if (done) { + return undefined; + } + var result = callback(value); + if (result !== undefined) { + return result; + } + } + } + ts.firstDefinedIterator = firstDefinedIterator; + function zipWith(arrayA, arrayB, callback) { + var result = []; + Debug.assertEqual(arrayA.length, arrayB.length); + for (var i = 0; i < arrayA.length; i++) { + result.push(callback(arrayA[i], arrayB[i], i)); + } + return result; + } + ts.zipWith = zipWith; + function zipToIterator(arrayA, arrayB) { + Debug.assertEqual(arrayA.length, arrayB.length); + var i = 0; + return { + next: function () { + if (i === arrayA.length) { + return { value: undefined, done: true }; + } + i++; + return { value: [arrayA[i - 1], arrayB[i - 1]], done: false }; + } + }; + } + ts.zipToIterator = zipToIterator; + function zipToMap(keys, values) { + Debug.assert(keys.length === values.length); + var map = createMap(); + for (var i = 0; i < keys.length; ++i) { + map.set(keys[i], values[i]); + } + return map; + } + ts.zipToMap = zipToMap; + /** + * Iterates through `array` by index and performs the callback on each element of array until the callback + * returns a falsey value, then returns false. + * If no such value is found, the callback is applied to each element of array and `true` is returned. + */ + function every(array, callback) { + if (array) { + for (var i = 0; i < array.length; i++) { + if (!callback(array[i], i)) { + return false; + } + } + } + return true; + } + ts.every = every; + function find(array, predicate) { + for (var i = 0; i < array.length; i++) { + var value = array[i]; + if (predicate(value, i)) { + return value; + } + } + return undefined; + } + ts.find = find; + function findLast(array, predicate) { + for (var i = array.length - 1; i >= 0; i--) { + var value = array[i]; + if (predicate(value, i)) { + return value; + } + } + return undefined; + } + ts.findLast = findLast; + /** Works like Array.prototype.findIndex, returning `-1` if no element satisfying the predicate is found. */ + function findIndex(array, predicate, startIndex) { + for (var i = startIndex || 0; i < array.length; i++) { + if (predicate(array[i], i)) { + return i; + } + } + return -1; + } + ts.findIndex = findIndex; + function findLastIndex(array, predicate, startIndex) { + for (var i = startIndex === undefined ? array.length - 1 : startIndex; i >= 0; i--) { + if (predicate(array[i], i)) { + return i; + } + } + return -1; + } + ts.findLastIndex = findLastIndex; + /** + * Returns the first truthy result of `callback`, or else fails. + * This is like `forEach`, but never returns undefined. + */ + function findMap(array, callback) { + for (var i = 0; i < array.length; i++) { + var result = callback(array[i], i); + if (result) { + return result; + } + } + return Debug.fail(); + } + ts.findMap = findMap; + function contains(array, value, equalityComparer) { + if (equalityComparer === void 0) { equalityComparer = equateValues; } + if (array) { + for (var _i = 0, array_1 = array; _i < array_1.length; _i++) { + var v = array_1[_i]; + if (equalityComparer(v, value)) { + return true; + } + } + } + return false; + } + ts.contains = contains; + function arraysEqual(a, b, equalityComparer) { + if (equalityComparer === void 0) { equalityComparer = equateValues; } + return a.length === b.length && a.every(function (x, i) { return equalityComparer(x, b[i]); }); + } + ts.arraysEqual = arraysEqual; + function indexOfAnyCharCode(text, charCodes, start) { + for (var i = start || 0; i < text.length; i++) { + if (contains(charCodes, text.charCodeAt(i))) { + return i; + } + } + return -1; + } + ts.indexOfAnyCharCode = indexOfAnyCharCode; + function countWhere(array, predicate) { + var count = 0; + if (array) { + for (var i = 0; i < array.length; i++) { + var v = array[i]; + if (predicate(v, i)) { + count++; + } + } + } + return count; + } + ts.countWhere = countWhere; + function filter(array, f) { + if (array) { + var len = array.length; + var i = 0; + while (i < len && f(array[i])) + i++; + if (i < len) { + var result = array.slice(0, i); + i++; + while (i < len) { + var item = array[i]; + if (f(item)) { + result.push(item); + } + i++; + } + return result; + } + } + return array; + } + ts.filter = filter; + function filterMutate(array, f) { + var outIndex = 0; + for (var i = 0; i < array.length; i++) { + if (f(array[i], i, array)) { + array[outIndex] = array[i]; + outIndex++; + } + } + array.length = outIndex; + } + ts.filterMutate = filterMutate; + function clear(array) { + array.length = 0; + } + ts.clear = clear; + function map(array, f) { + var result; + if (array) { + result = []; + for (var i = 0; i < array.length; i++) { + result.push(f(array[i], i)); + } + } + return result; + } + ts.map = map; + function mapIterator(iter, mapFn) { + return { + next: function () { + var iterRes = iter.next(); + return iterRes.done ? iterRes : { value: mapFn(iterRes.value), done: false }; + } + }; + } + ts.mapIterator = mapIterator; + function sameMap(array, f) { + if (array) { + for (var i = 0; i < array.length; i++) { + var item = array[i]; + var mapped = f(item, i); + if (item !== mapped) { + var result = array.slice(0, i); + result.push(mapped); + for (i++; i < array.length; i++) { + result.push(f(array[i], i)); + } + return result; + } + } + } + return array; + } + ts.sameMap = sameMap; + function flatten(array) { + var result; + if (array) { + result = []; + for (var _i = 0, array_2 = array; _i < array_2.length; _i++) { + var v = array_2[_i]; + if (v) { + if (isArray(v)) { + addRange(result, v); + } + else { + result.push(v); + } + } + } + } + return result; + } + ts.flatten = flatten; + /** + * Maps an array. If the mapped value is an array, it is spread into the result. + * + * @param array The array to map. + * @param mapfn The callback used to map the result into one or more values. + */ + function flatMap(array, mapfn) { + var result; + if (array) { + for (var i = 0; i < array.length; i++) { + var v = mapfn(array[i], i); + if (v) { + if (isArray(v)) { + result = addRange(result, v); + } + else { + result = append(result, v); + } + } + } + } + return result || ts.emptyArray; + } + ts.flatMap = flatMap; + function flatMapToMutable(array, mapfn) { + var result = []; + if (array) { + for (var i = 0; i < array.length; i++) { + var v = mapfn(array[i], i); + if (v) { + if (isArray(v)) { + addRange(result, v); + } + else { + result.push(v); + } + } + } + } + return result; + } + ts.flatMapToMutable = flatMapToMutable; + function flatMapIterator(iter, mapfn) { + var first = iter.next(); + if (first.done) { + return ts.emptyIterator; + } + var currentIter = getIterator(first.value); + return { + next: function () { + while (true) { + var currentRes = currentIter.next(); + if (!currentRes.done) { + return currentRes; + } + var iterRes = iter.next(); + if (iterRes.done) { + return iterRes; + } + currentIter = getIterator(iterRes.value); + } + }, + }; + function getIterator(x) { + var res = mapfn(x); + return res === undefined ? ts.emptyIterator : isArray(res) ? arrayIterator(res) : res; + } + } + ts.flatMapIterator = flatMapIterator; + function sameFlatMap(array, mapfn) { + var result; + if (array) { + for (var i = 0; i < array.length; i++) { + var item = array[i]; + var mapped = mapfn(item, i); + if (result || item !== mapped || isArray(mapped)) { + if (!result) { + result = array.slice(0, i); + } + if (isArray(mapped)) { + addRange(result, mapped); + } + else { + result.push(mapped); + } + } + } + } + return result || array; + } + ts.sameFlatMap = sameFlatMap; + function mapAllOrFail(array, mapFn) { + var result = []; + for (var i = 0; i < array.length; i++) { + var mapped = mapFn(array[i], i); + if (mapped === undefined) { + return undefined; + } + result.push(mapped); + } + return result; + } + ts.mapAllOrFail = mapAllOrFail; + function mapDefined(array, mapFn) { + var result = []; + if (array) { + for (var i = 0; i < array.length; i++) { + var mapped = mapFn(array[i], i); + if (mapped !== undefined) { + result.push(mapped); + } + } + } + return result; + } + ts.mapDefined = mapDefined; + function mapDefinedIterator(iter, mapFn) { + return { + next: function () { + while (true) { + var res = iter.next(); + if (res.done) { + return res; + } + var value = mapFn(res.value); + if (value !== undefined) { + return { value: value, done: false }; + } + } + } + }; + } + ts.mapDefinedIterator = mapDefinedIterator; + ts.emptyIterator = { next: function () { return ({ value: undefined, done: true }); } }; + function singleIterator(value) { + var done = false; + return { + next: function () { + var wasDone = done; + done = true; + return wasDone ? { value: undefined, done: true } : { value: value, done: false }; + } + }; + } + ts.singleIterator = singleIterator; + function spanMap(array, keyfn, mapfn) { + var result; + if (array) { + result = []; + var len = array.length; + var previousKey = void 0; + var key = void 0; + var start = 0; + var pos = 0; + while (start < len) { + while (pos < len) { + var value = array[pos]; + key = keyfn(value, pos); + if (pos === 0) { + previousKey = key; + } + else if (key !== previousKey) { + break; + } + pos++; + } + if (start < pos) { + var v = mapfn(array.slice(start, pos), previousKey, start, pos); + if (v) { + result.push(v); + } + start = pos; + } + previousKey = key; + pos++; + } + } + return result; + } + ts.spanMap = spanMap; + function mapEntries(map, f) { + if (!map) { + return undefined; + } + var result = createMap(); + map.forEach(function (value, key) { + var _a = f(key, value), newKey = _a[0], newValue = _a[1]; + result.set(newKey, newValue); + }); + return result; + } + ts.mapEntries = mapEntries; + function some(array, predicate) { + if (array) { + if (predicate) { + for (var _i = 0, array_3 = array; _i < array_3.length; _i++) { + var v = array_3[_i]; + if (predicate(v)) { + return true; + } + } + } + else { + return array.length > 0; + } + } + return false; + } + ts.some = some; + /** Calls the callback with (start, afterEnd) index pairs for each range where 'pred' is true. */ + function getRangesWhere(arr, pred, cb) { + var start; + for (var i = 0; i < arr.length; i++) { + if (pred(arr[i])) { + start = start === undefined ? i : start; + } + else { + if (start !== undefined) { + cb(start, i); + start = undefined; + } + } + } + if (start !== undefined) + cb(start, arr.length); + } + ts.getRangesWhere = getRangesWhere; + function concatenate(array1, array2) { + if (!some(array2)) + return array1; + if (!some(array1)) + return array2; + return array1.concat(array2); + } + ts.concatenate = concatenate; + function deduplicateRelational(array, equalityComparer, comparer) { + // Perform a stable sort of the array. This ensures the first entry in a list of + // duplicates remains the first entry in the result. + var indices = array.map(function (_, i) { return i; }); + stableSortIndices(array, indices, comparer); + var last = array[indices[0]]; + var deduplicated = [indices[0]]; + for (var i = 1; i < indices.length; i++) { + var index = indices[i]; + var item = array[index]; + if (!equalityComparer(last, item)) { + deduplicated.push(index); + last = item; + } + } + // restore original order + deduplicated.sort(); + return deduplicated.map(function (i) { return array[i]; }); + } + function deduplicateEquality(array, equalityComparer) { + var result = []; + for (var _i = 0, array_4 = array; _i < array_4.length; _i++) { + var item = array_4[_i]; + pushIfUnique(result, item, equalityComparer); + } + return result; + } + /** + * Deduplicates an unsorted array. + * @param equalityComparer An optional `EqualityComparer` used to determine if two values are duplicates. + * @param comparer An optional `Comparer` used to sort entries before comparison, though the + * result will remain in the original order in `array`. + */ + function deduplicate(array, equalityComparer, comparer) { + return array.length === 0 ? [] : + array.length === 1 ? array.slice() : + comparer ? deduplicateRelational(array, equalityComparer, comparer) : + deduplicateEquality(array, equalityComparer); + } + ts.deduplicate = deduplicate; + /** + * Deduplicates an array that has already been sorted. + */ + function deduplicateSorted(array, comparer) { + if (array.length === 0) + return ts.emptyArray; + var last = array[0]; + var deduplicated = [last]; + for (var i = 1; i < array.length; i++) { + var next = array[i]; + switch (comparer(next, last)) { + // equality comparison + case true: + // relational comparison + case 0 /* EqualTo */: + continue; + case -1 /* LessThan */: + // If `array` is sorted, `next` should **never** be less than `last`. + return Debug.fail("Array is unsorted."); + } + deduplicated.push(last = next); + } + return deduplicated; + } + function insertSorted(array, insert, compare) { + if (array.length === 0) { + array.push(insert); + return; + } + var insertIndex = binarySearch(array, insert, identity, compare); + if (insertIndex < 0) { + array.splice(~insertIndex, 0, insert); + } + } + ts.insertSorted = insertSorted; + function sortAndDeduplicate(array, comparer, equalityComparer) { + return deduplicateSorted(sort(array, comparer), equalityComparer || comparer || compareStringsCaseSensitive); + } + ts.sortAndDeduplicate = sortAndDeduplicate; + function arrayIsEqualTo(array1, array2, equalityComparer) { + if (equalityComparer === void 0) { equalityComparer = equateValues; } + if (!array1 || !array2) { + return array1 === array2; + } + if (array1.length !== array2.length) { + return false; + } + for (var i = 0; i < array1.length; i++) { + if (!equalityComparer(array1[i], array2[i], i)) { + return false; + } + } + return true; + } + ts.arrayIsEqualTo = arrayIsEqualTo; + function compact(array) { + var result; + if (array) { + for (var i = 0; i < array.length; i++) { + var v = array[i]; + if (result || !v) { + if (!result) { + result = array.slice(0, i); + } + if (v) { + result.push(v); + } + } + } + } + return result || array; + } + ts.compact = compact; + /** + * Gets the relative complement of `arrayA` with respect to `arrayB`, returning the elements that + * are not present in `arrayA` but are present in `arrayB`. Assumes both arrays are sorted + * based on the provided comparer. + */ + function relativeComplement(arrayA, arrayB, comparer) { + if (!arrayB || !arrayA || arrayB.length === 0 || arrayA.length === 0) + return arrayB; + var result = []; + loopB: for (var offsetA = 0, offsetB = 0; offsetB < arrayB.length; offsetB++) { + if (offsetB > 0) { + // Ensure `arrayB` is properly sorted. + Debug.assertGreaterThanOrEqual(comparer(arrayB[offsetB], arrayB[offsetB - 1]), 0 /* EqualTo */); + } + loopA: for (var startA = offsetA; offsetA < arrayA.length; offsetA++) { + if (offsetA > startA) { + // Ensure `arrayA` is properly sorted. We only need to perform this check if + // `offsetA` has changed since we entered the loop. + Debug.assertGreaterThanOrEqual(comparer(arrayA[offsetA], arrayA[offsetA - 1]), 0 /* EqualTo */); + } + switch (comparer(arrayB[offsetB], arrayA[offsetA])) { + case -1 /* LessThan */: + // If B is less than A, B does not exist in arrayA. Add B to the result and + // move to the next element in arrayB without changing the current position + // in arrayA. + result.push(arrayB[offsetB]); + continue loopB; + case 0 /* EqualTo */: + // If B is equal to A, B exists in arrayA. Move to the next element in + // arrayB without adding B to the result or changing the current position + // in arrayA. + continue loopB; + case 1 /* GreaterThan */: + // If B is greater than A, we need to keep looking for B in arrayA. Move to + // the next element in arrayA and recheck. + continue loopA; + } + } + } + return result; + } + ts.relativeComplement = relativeComplement; + function sum(array, prop) { + var result = 0; + for (var _i = 0, array_5 = array; _i < array_5.length; _i++) { + var v = array_5[_i]; + result += v[prop]; + } + return result; + } + ts.sum = sum; + function append(to, value) { + if (value === undefined) + return to; + if (to === undefined) + return [value]; + to.push(value); + return to; + } + ts.append = append; + /** + * Gets the actual offset into an array for a relative offset. Negative offsets indicate a + * position offset from the end of the array. + */ + function toOffset(array, offset) { + return offset < 0 ? array.length + offset : offset; + } + function addRange(to, from, start, end) { + if (from === undefined || from.length === 0) + return to; + if (to === undefined) + return from.slice(start, end); + start = start === undefined ? 0 : toOffset(from, start); + end = end === undefined ? from.length : toOffset(from, end); + for (var i = start; i < end && i < from.length; i++) { + if (from[i] !== undefined) { + to.push(from[i]); + } + } + return to; + } + ts.addRange = addRange; + /** + * @return Whether the value was added. + */ + function pushIfUnique(array, toAdd, equalityComparer) { + if (contains(array, toAdd, equalityComparer)) { + return false; + } + else { + array.push(toAdd); + return true; + } + } + ts.pushIfUnique = pushIfUnique; + /** + * Unlike `pushIfUnique`, this can take `undefined` as an input, and returns a new array. + */ + function appendIfUnique(array, toAdd, equalityComparer) { + if (array) { + pushIfUnique(array, toAdd, equalityComparer); + return array; + } + else { + return [toAdd]; + } + } + ts.appendIfUnique = appendIfUnique; + function stableSortIndices(array, indices, comparer) { + // sort indices by value then position + indices.sort(function (x, y) { return comparer(array[x], array[y]) || compareValues(x, y); }); + } + /** + * Returns a new sorted array. + */ + function sort(array, comparer) { + return (array.length === 0 ? array : array.slice().sort(comparer)); + } + ts.sort = sort; + function arrayIterator(array) { + var i = 0; + return { next: function () { + if (i === array.length) { + return { value: undefined, done: true }; + } + else { + i++; + return { value: array[i - 1], done: false }; + } + } }; + } + ts.arrayIterator = arrayIterator; + /** + * Stable sort of an array. Elements equal to each other maintain their relative position in the array. + */ + function stableSort(array, comparer) { + var indices = array.map(function (_, i) { return i; }); + stableSortIndices(array, indices, comparer); + return indices.map(function (i) { return array[i]; }); + } + ts.stableSort = stableSort; + function rangeEquals(array1, array2, pos, end) { + while (pos < end) { + if (array1[pos] !== array2[pos]) { + return false; + } + pos++; + } + return true; + } + ts.rangeEquals = rangeEquals; + /** + * Returns the element at a specific offset in an array if non-empty, `undefined` otherwise. + * A negative offset indicates the element should be retrieved from the end of the array. + */ + function elementAt(array, offset) { + if (array) { + offset = toOffset(array, offset); + if (offset < array.length) { + return array[offset]; + } + } + return undefined; + } + ts.elementAt = elementAt; + /** + * Returns the first element of an array if non-empty, `undefined` otherwise. + */ + function firstOrUndefined(array) { + return array.length === 0 ? undefined : array[0]; + } + ts.firstOrUndefined = firstOrUndefined; + function first(array) { + Debug.assert(array.length !== 0); + return array[0]; + } + ts.first = first; + /** + * Returns the last element of an array if non-empty, `undefined` otherwise. + */ + function lastOrUndefined(array) { + return array.length === 0 ? undefined : array[array.length - 1]; + } + ts.lastOrUndefined = lastOrUndefined; + function last(array) { + Debug.assert(array.length !== 0); + return array[array.length - 1]; + } + ts.last = last; + /** + * Returns the only element of an array if it contains only one element, `undefined` otherwise. + */ + function singleOrUndefined(array) { + return array && array.length === 1 + ? array[0] + : undefined; + } + ts.singleOrUndefined = singleOrUndefined; + function singleOrMany(array) { + return array && array.length === 1 + ? array[0] + : array; + } + ts.singleOrMany = singleOrMany; + function replaceElement(array, index, value) { + var result = array.slice(0); + result[index] = value; + return result; + } + ts.replaceElement = replaceElement; + /** + * Performs a binary search, finding the index at which `value` occurs in `array`. + * If no such index is found, returns the 2's-complement of first index at which + * `array[index]` exceeds `value`. + * @param array A sorted array whose first element must be no larger than number + * @param value The value to be searched for in the array. + * @param keySelector A callback used to select the search key from `value` and each element of + * `array`. + * @param keyComparer A callback used to compare two keys in a sorted array. + * @param offset An offset into `array` at which to start the search. + */ + function binarySearch(array, value, keySelector, keyComparer, offset) { + return binarySearchKey(array, keySelector(value), keySelector, keyComparer, offset); + } + ts.binarySearch = binarySearch; + /** + * Performs a binary search, finding the index at which an object with `key` occurs in `array`. + * If no such index is found, returns the 2's-complement of first index at which + * `array[index]` exceeds `key`. + * @param array A sorted array whose first element must be no larger than number + * @param key The key to be searched for in the array. + * @param keySelector A callback used to select the search key from each element of `array`. + * @param keyComparer A callback used to compare two keys in a sorted array. + * @param offset An offset into `array` at which to start the search. + */ + function binarySearchKey(array, key, keySelector, keyComparer, offset) { + if (!some(array)) { + return -1; + } + var low = offset || 0; + var high = array.length - 1; + while (low <= high) { + var middle = low + ((high - low) >> 1); + var midKey = keySelector(array[middle]); + switch (keyComparer(midKey, key)) { + case -1 /* LessThan */: + low = middle + 1; + break; + case 0 /* EqualTo */: + return middle; + case 1 /* GreaterThan */: + high = middle - 1; + break; + } + } + return ~low; + } + ts.binarySearchKey = binarySearchKey; + function reduceLeft(array, f, initial, start, count) { + if (array && array.length > 0) { + var size = array.length; + if (size > 0) { + var pos = start === undefined || start < 0 ? 0 : start; + var end = count === undefined || pos + count > size - 1 ? size - 1 : pos + count; + var result = void 0; + if (arguments.length <= 2) { + result = array[pos]; + pos++; + } + else { + result = initial; + } + while (pos <= end) { + result = f(result, array[pos], pos); + pos++; + } + return result; + } + } + return initial; + } + ts.reduceLeft = reduceLeft; + var hasOwnProperty = Object.prototype.hasOwnProperty; + /** + * Indicates whether a map-like contains an own property with the specified key. + * + * @param map A map-like. + * @param key A property key. + */ + function hasProperty(map, key) { + return hasOwnProperty.call(map, key); + } + ts.hasProperty = hasProperty; + /** + * Gets the value of an owned property in a map-like. + * + * @param map A map-like. + * @param key A property key. + */ + function getProperty(map, key) { + return hasOwnProperty.call(map, key) ? map[key] : undefined; + } + ts.getProperty = getProperty; + /** + * Gets the owned, enumerable property keys of a map-like. + */ + function getOwnKeys(map) { + var keys = []; + for (var key in map) { + if (hasOwnProperty.call(map, key)) { + keys.push(key); + } + } + return keys; + } + ts.getOwnKeys = getOwnKeys; + function getOwnValues(sparseArray) { + var values = []; + for (var key in sparseArray) { + if (hasOwnProperty.call(sparseArray, key)) { + values.push(sparseArray[key]); + } + } + return values; + } + ts.getOwnValues = getOwnValues; + function arrayFrom(iterator, map) { + var _a; + var result = []; + for (var _b = iterator.next(), value = _b.value, done = _b.done; !done; _a = iterator.next(), value = _a.value, done = _a.done, _a) { + result.push(map ? map(value) : value); + } + return result; + } + ts.arrayFrom = arrayFrom; + function assign(t) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + for (var _a = 0, args_1 = args; _a < args_1.length; _a++) { + var arg = args_1[_a]; + for (var p in arg) { + if (hasProperty(arg, p)) { + t[p] = arg[p]; // TODO: GH#23368 + } + } + } + return t; + } + ts.assign = assign; + /** + * Performs a shallow equality comparison of the contents of two map-likes. + * + * @param left A map-like whose properties should be compared. + * @param right A map-like whose properties should be compared. + */ + function equalOwnProperties(left, right, equalityComparer) { + if (equalityComparer === void 0) { equalityComparer = equateValues; } + if (left === right) + return true; + if (!left || !right) + return false; + for (var key in left) { + if (hasOwnProperty.call(left, key)) { + if (!hasOwnProperty.call(right, key)) + return false; + if (!equalityComparer(left[key], right[key])) + return false; + } + } + for (var key in right) { + if (hasOwnProperty.call(right, key)) { + if (!hasOwnProperty.call(left, key)) + return false; + } + } + return true; + } + ts.equalOwnProperties = equalOwnProperties; + function arrayToMap(array, makeKey, makeValue) { + if (makeValue === void 0) { makeValue = identity; } + var result = createMap(); + for (var _i = 0, array_6 = array; _i < array_6.length; _i++) { + var value = array_6[_i]; + var key = makeKey(value); + if (key !== undefined) + result.set(key, makeValue(value)); + } + return result; + } + ts.arrayToMap = arrayToMap; + function arrayToNumericMap(array, makeKey, makeValue) { + if (makeValue === void 0) { makeValue = identity; } + var result = []; + for (var _i = 0, array_7 = array; _i < array_7.length; _i++) { + var value = array_7[_i]; + result[makeKey(value)] = makeValue(value); + } + return result; + } + ts.arrayToNumericMap = arrayToNumericMap; + function arrayToMultiMap(values, makeKey, makeValue) { + if (makeValue === void 0) { makeValue = identity; } + var result = createMultiMap(); + for (var _i = 0, values_1 = values; _i < values_1.length; _i++) { + var value = values_1[_i]; + result.add(makeKey(value), makeValue(value)); + } + return result; + } + ts.arrayToMultiMap = arrayToMultiMap; + function group(values, getGroupId) { + return arrayFrom(arrayToMultiMap(values, getGroupId).values()); + } + ts.group = group; + function clone(object) { + var result = {}; + for (var id in object) { + if (hasOwnProperty.call(object, id)) { + result[id] = object[id]; + } + } + return result; + } + ts.clone = clone; + function extend(first, second) { + var result = {}; + for (var id in second) { + if (hasOwnProperty.call(second, id)) { + result[id] = second[id]; + } + } + for (var id in first) { + if (hasOwnProperty.call(first, id)) { + result[id] = first[id]; + } + } + return result; + } + ts.extend = extend; + function createMultiMap() { + var map = createMap(); + map.add = multiMapAdd; + map.remove = multiMapRemove; + return map; + } + ts.createMultiMap = createMultiMap; + function multiMapAdd(key, value) { + var values = this.get(key); + if (values) { + values.push(value); + } + else { + this.set(key, values = [value]); + } + return values; + } + function multiMapRemove(key, value) { + var values = this.get(key); + if (values) { + unorderedRemoveItem(values, value); + if (!values.length) { + this.delete(key); + } + } + } + /** + * Tests whether a value is an array. + */ + function isArray(value) { + return Array.isArray ? Array.isArray(value) : value instanceof Array; + } + ts.isArray = isArray; + function toArray(value) { + return isArray(value) ? value : [value]; + } + ts.toArray = toArray; + /** + * Tests whether a value is string + */ + function isString(text) { + return typeof text === "string"; + } + ts.isString = isString; + function isNumber(x) { + return typeof x === "number"; + } + ts.isNumber = isNumber; + function tryCast(value, test) { + return value !== undefined && test(value) ? value : undefined; + } + ts.tryCast = tryCast; + function cast(value, test) { + if (value !== undefined && test(value)) + return value; + return Debug.fail("Invalid cast. The supplied value " + value + " did not pass the test '" + Debug.getFunctionName(test) + "'."); + } + ts.cast = cast; + /** Does nothing. */ + function noop(_) { } // tslint:disable-line no-empty + ts.noop = noop; + /** Do nothing and return false */ + function returnFalse() { return false; } + ts.returnFalse = returnFalse; + /** Do nothing and return true */ + function returnTrue() { return true; } + ts.returnTrue = returnTrue; + /** Returns its argument. */ + function identity(x) { return x; } + ts.identity = identity; + /** Returns lower case string */ + function toLowerCase(x) { return x.toLowerCase(); } + ts.toLowerCase = toLowerCase; + /** Throws an error because a function is not implemented. */ + function notImplemented() { + throw new Error("Not implemented"); + } + ts.notImplemented = notImplemented; + function memoize(callback) { + var value; + return function () { + if (callback) { + value = callback(); + callback = undefined; + } + return value; + }; + } + ts.memoize = memoize; + function chain(a, b, c, d, e) { + if (e) { + var args_2 = []; + for (var i = 0; i < arguments.length; i++) { + args_2[i] = arguments[i]; + } + return function (t) { return compose.apply(void 0, map(args_2, function (f) { return f(t); })); }; + } + else if (d) { + return function (t) { return compose(a(t), b(t), c(t), d(t)); }; + } + else if (c) { + return function (t) { return compose(a(t), b(t), c(t)); }; + } + else if (b) { + return function (t) { return compose(a(t), b(t)); }; + } + else if (a) { + return function (t) { return compose(a(t)); }; + } + else { + return function (_) { return function (u) { return u; }; }; + } + } + ts.chain = chain; + function compose(a, b, c, d, e) { + if (e) { + var args_3 = []; + for (var i = 0; i < arguments.length; i++) { + args_3[i] = arguments[i]; + } + return function (t) { return reduceLeft(args_3, function (u, f) { return f(u); }, t); }; + } + else if (d) { + return function (t) { return d(c(b(a(t)))); }; + } + else if (c) { + return function (t) { return c(b(a(t))); }; + } + else if (b) { + return function (t) { return b(a(t)); }; + } + else if (a) { + return function (t) { return a(t); }; + } + else { + return function (t) { return t; }; + } + } + ts.compose = compose; + var AssertionLevel; + (function (AssertionLevel) { + AssertionLevel[AssertionLevel["None"] = 0] = "None"; + AssertionLevel[AssertionLevel["Normal"] = 1] = "Normal"; + AssertionLevel[AssertionLevel["Aggressive"] = 2] = "Aggressive"; + AssertionLevel[AssertionLevel["VeryAggressive"] = 3] = "VeryAggressive"; + })(AssertionLevel = ts.AssertionLevel || (ts.AssertionLevel = {})); + var Debug; + (function (Debug) { + Debug.currentAssertionLevel = 0 /* None */; + Debug.isDebugging = false; + function shouldAssert(level) { + return Debug.currentAssertionLevel >= level; + } + Debug.shouldAssert = shouldAssert; + function assert(expression, message, verboseDebugInfo, stackCrawlMark) { + if (!expression) { + if (verboseDebugInfo) { + message += "\r\nVerbose Debug Information: " + (typeof verboseDebugInfo === "string" ? verboseDebugInfo : verboseDebugInfo()); + } + fail(message ? "False expression: " + message : "False expression.", stackCrawlMark || assert); + } + } + Debug.assert = assert; + function assertEqual(a, b, msg, msg2) { + if (a !== b) { + var message = msg ? msg2 ? msg + " " + msg2 : msg : ""; + fail("Expected " + a + " === " + b + ". " + message); + } + } + Debug.assertEqual = assertEqual; + function assertLessThan(a, b, msg) { + if (a >= b) { + fail("Expected " + a + " < " + b + ". " + (msg || "")); + } + } + Debug.assertLessThan = assertLessThan; + function assertLessThanOrEqual(a, b) { + if (a > b) { + fail("Expected " + a + " <= " + b); + } + } + Debug.assertLessThanOrEqual = assertLessThanOrEqual; + function assertGreaterThanOrEqual(a, b) { + if (a < b) { + fail("Expected " + a + " >= " + b); + } + } + Debug.assertGreaterThanOrEqual = assertGreaterThanOrEqual; + function fail(message, stackCrawlMark) { + debugger; + var e = new Error(message ? "Debug Failure. " + message : "Debug Failure."); + if (Error.captureStackTrace) { + Error.captureStackTrace(e, stackCrawlMark || fail); + } + throw e; + } + Debug.fail = fail; + function assertDefined(value, message) { + if (value === undefined || value === null) + return fail(message); + return value; + } + Debug.assertDefined = assertDefined; + function assertEachDefined(value, message) { + for (var _i = 0, value_1 = value; _i < value_1.length; _i++) { + var v = value_1[_i]; + assertDefined(v, message); + } + return value; + } + Debug.assertEachDefined = assertEachDefined; + function assertNever(member, message, stackCrawlMark) { + if (message === void 0) { message = "Illegal value:"; } + var detail = "kind" in member && "pos" in member ? "SyntaxKind: " + Debug.showSyntaxKind(member) : JSON.stringify(member); + return fail(message + " " + detail, stackCrawlMark || assertNever); + } + Debug.assertNever = assertNever; + function getFunctionName(func) { + if (typeof func !== "function") { + return ""; + } + else if (func.hasOwnProperty("name")) { + return func.name; + } + else { + var text = Function.prototype.toString.call(func); + var match = /^function\s+([\w\$]+)\s*\(/.exec(text); + return match ? match[1] : ""; + } + } + Debug.getFunctionName = getFunctionName; + })(Debug = ts.Debug || (ts.Debug = {})); + function equateValues(a, b) { + return a === b; + } + ts.equateValues = equateValues; + /** + * Compare the equality of two strings using a case-sensitive ordinal comparison. + * + * Case-sensitive comparisons compare both strings one code-point at a time using the integer + * value of each code-point after applying `toUpperCase` to each string. We always map both + * strings to their upper-case form as some unicode characters do not properly round-trip to + * lowercase (such as `ẞ` (German sharp capital s)). + */ + function equateStringsCaseInsensitive(a, b) { + return a === b + || a !== undefined + && b !== undefined + && a.toUpperCase() === b.toUpperCase(); + } + ts.equateStringsCaseInsensitive = equateStringsCaseInsensitive; + /** + * Compare the equality of two strings using a case-sensitive ordinal comparison. + * + * Case-sensitive comparisons compare both strings one code-point at a time using the + * integer value of each code-point. + */ + function equateStringsCaseSensitive(a, b) { + return equateValues(a, b); + } + ts.equateStringsCaseSensitive = equateStringsCaseSensitive; + function compareComparableValues(a, b) { + return a === b ? 0 /* EqualTo */ : + a === undefined ? -1 /* LessThan */ : + b === undefined ? 1 /* GreaterThan */ : + a < b ? -1 /* LessThan */ : + 1 /* GreaterThan */; + } + /** + * Compare two numeric values for their order relative to each other. + * To compare strings, use any of the `compareStrings` functions. + */ + function compareValues(a, b) { + return compareComparableValues(a, b); + } + ts.compareValues = compareValues; + function min(a, b, compare) { + return compare(a, b) === -1 /* LessThan */ ? a : b; + } + ts.min = min; + /** + * Compare two strings using a case-insensitive ordinal comparison. + * + * Ordinal comparisons are based on the difference between the unicode code points of both + * strings. Characters with multiple unicode representations are considered unequal. Ordinal + * comparisons provide predictable ordering, but place "a" after "B". + * + * Case-insensitive comparisons compare both strings one code-point at a time using the integer + * value of each code-point after applying `toUpperCase` to each string. We always map both + * strings to their upper-case form as some unicode characters do not properly round-trip to + * lowercase (such as `ẞ` (German sharp capital s)). + */ + function compareStringsCaseInsensitive(a, b) { + if (a === b) + return 0 /* EqualTo */; + if (a === undefined) + return -1 /* LessThan */; + if (b === undefined) + return 1 /* GreaterThan */; + a = a.toUpperCase(); + b = b.toUpperCase(); + return a < b ? -1 /* LessThan */ : a > b ? 1 /* GreaterThan */ : 0 /* EqualTo */; + } + ts.compareStringsCaseInsensitive = compareStringsCaseInsensitive; + /** + * Compare two strings using a case-sensitive ordinal comparison. + * + * Ordinal comparisons are based on the difference between the unicode code points of both + * strings. Characters with multiple unicode representations are considered unequal. Ordinal + * comparisons provide predictable ordering, but place "a" after "B". + * + * Case-sensitive comparisons compare both strings one code-point at a time using the integer + * value of each code-point. + */ + function compareStringsCaseSensitive(a, b) { + return compareComparableValues(a, b); + } + ts.compareStringsCaseSensitive = compareStringsCaseSensitive; + function getStringComparer(ignoreCase) { + return ignoreCase ? compareStringsCaseInsensitive : compareStringsCaseSensitive; + } + ts.getStringComparer = getStringComparer; + /** + * Creates a string comparer for use with string collation in the UI. + */ + var createUIStringComparer = (function () { + var defaultComparer; + var enUSComparer; + var stringComparerFactory = getStringComparerFactory(); + return createStringComparer; + function compareWithCallback(a, b, comparer) { + if (a === b) + return 0 /* EqualTo */; + if (a === undefined) + return -1 /* LessThan */; + if (b === undefined) + return 1 /* GreaterThan */; + var value = comparer(a, b); + return value < 0 ? -1 /* LessThan */ : value > 0 ? 1 /* GreaterThan */ : 0 /* EqualTo */; + } + function createIntlCollatorStringComparer(locale) { + // Intl.Collator.prototype.compare is bound to the collator. See NOTE in + // http://www.ecma-international.org/ecma-402/2.0/#sec-Intl.Collator.prototype.compare + var comparer = new Intl.Collator(locale, { usage: "sort", sensitivity: "variant" }).compare; + return function (a, b) { return compareWithCallback(a, b, comparer); }; + } + function createLocaleCompareStringComparer(locale) { + // if the locale is not the default locale (`undefined`), use the fallback comparer. + if (locale !== undefined) + return createFallbackStringComparer(); + return function (a, b) { return compareWithCallback(a, b, compareStrings); }; + function compareStrings(a, b) { + return a.localeCompare(b); + } + } + function createFallbackStringComparer() { + // An ordinal comparison puts "A" after "b", but for the UI we want "A" before "b". + // We first sort case insensitively. So "Aaa" will come before "baa". + // Then we sort case sensitively, so "aaa" will come before "Aaa". + // + // For case insensitive comparisons we always map both strings to their + // upper-case form as some unicode characters do not properly round-trip to + // lowercase (such as `ẞ` (German sharp capital s)). + return function (a, b) { return compareWithCallback(a, b, compareDictionaryOrder); }; + function compareDictionaryOrder(a, b) { + return compareStrings(a.toUpperCase(), b.toUpperCase()) || compareStrings(a, b); + } + function compareStrings(a, b) { + return a < b ? -1 /* LessThan */ : a > b ? 1 /* GreaterThan */ : 0 /* EqualTo */; + } + } + function getStringComparerFactory() { + // If the host supports Intl, we use it for comparisons using the default locale. + if (typeof Intl === "object" && typeof Intl.Collator === "function") { + return createIntlCollatorStringComparer; + } + // If the host does not support Intl, we fall back to localeCompare. + // localeCompare in Node v0.10 is just an ordinal comparison, so don't use it. + if (typeof String.prototype.localeCompare === "function" && + typeof String.prototype.toLocaleUpperCase === "function" && + "a".localeCompare("B") < 0) { + return createLocaleCompareStringComparer; + } + // Otherwise, fall back to ordinal comparison: + return createFallbackStringComparer; + } + function createStringComparer(locale) { + // Hold onto common string comparers. This avoids constantly reallocating comparers during + // tests. + if (locale === undefined) { + return defaultComparer || (defaultComparer = stringComparerFactory(locale)); + } + else if (locale === "en-US") { + return enUSComparer || (enUSComparer = stringComparerFactory(locale)); + } + else { + return stringComparerFactory(locale); + } + } + })(); + var uiComparerCaseSensitive; + var uiLocale; + function getUILocale() { + return uiLocale; + } + ts.getUILocale = getUILocale; + function setUILocale(value) { + if (uiLocale !== value) { + uiLocale = value; + uiComparerCaseSensitive = undefined; + } + } + ts.setUILocale = setUILocale; + /** + * Compare two strings in a using the case-sensitive sort behavior of the UI locale. + * + * Ordering is not predictable between different host locales, but is best for displaying + * ordered data for UI presentation. Characters with multiple unicode representations may + * be considered equal. + * + * Case-sensitive comparisons compare strings that differ in base characters, or + * accents/diacritic marks, or case as unequal. + */ + function compareStringsCaseSensitiveUI(a, b) { + var comparer = uiComparerCaseSensitive || (uiComparerCaseSensitive = createUIStringComparer(uiLocale)); + return comparer(a, b); + } + ts.compareStringsCaseSensitiveUI = compareStringsCaseSensitiveUI; + function compareProperties(a, b, key, comparer) { + return a === b ? 0 /* EqualTo */ : + a === undefined ? -1 /* LessThan */ : + b === undefined ? 1 /* GreaterThan */ : + comparer(a[key], b[key]); + } + ts.compareProperties = compareProperties; + /** True is greater than false. */ + function compareBooleans(a, b) { + return compareValues(a ? 1 : 0, b ? 1 : 0); + } + ts.compareBooleans = compareBooleans; + /** + * Given a name and a list of names that are *not* equal to the name, return a spelling suggestion if there is one that is close enough. + * Names less than length 3 only check for case-insensitive equality, not Levenshtein distance. + * + * If there is a candidate that's the same except for case, return that. + * If there is a candidate that's within one edit of the name, return that. + * Otherwise, return the candidate with the smallest Levenshtein distance, + * except for candidates: + * * With no name + * * Whose length differs from the target name by more than 0.34 of the length of the name. + * * Whose levenshtein distance is more than 0.4 of the length of the name + * (0.4 allows 1 substitution/transposition for every 5 characters, + * and 1 insertion/deletion at 3 characters) + */ + function getSpellingSuggestion(name, candidates, getName) { + var maximumLengthDifference = Math.min(2, Math.floor(name.length * 0.34)); + var bestDistance = Math.floor(name.length * 0.4) + 1; // If the best result isn't better than this, don't bother. + var bestCandidate; + var justCheckExactMatches = false; + var nameLowerCase = name.toLowerCase(); + for (var _i = 0, candidates_1 = candidates; _i < candidates_1.length; _i++) { + var candidate = candidates_1[_i]; + var candidateName = getName(candidate); + if (candidateName !== undefined && Math.abs(candidateName.length - nameLowerCase.length) <= maximumLengthDifference) { + var candidateNameLowerCase = candidateName.toLowerCase(); + if (candidateNameLowerCase === nameLowerCase) { + if (candidateName === name) { + continue; + } + return candidate; + } + if (justCheckExactMatches) { + continue; + } + if (candidateName.length < 3) { + // Don't bother, user would have noticed a 2-character name having an extra character + continue; + } + // Only care about a result better than the best so far. + var distance = levenshteinWithMax(nameLowerCase, candidateNameLowerCase, bestDistance - 1); + if (distance === undefined) { + continue; + } + if (distance < 3) { + justCheckExactMatches = true; + bestCandidate = candidate; + } + else { + Debug.assert(distance < bestDistance); // Else `levenshteinWithMax` should return undefined + bestDistance = distance; + bestCandidate = candidate; + } + } + } + return bestCandidate; + } + ts.getSpellingSuggestion = getSpellingSuggestion; + function levenshteinWithMax(s1, s2, max) { + var previous = new Array(s2.length + 1); + var current = new Array(s2.length + 1); + /** Represents any value > max. We don't care about the particular value. */ + var big = max + 1; + for (var i = 0; i <= s2.length; i++) { + previous[i] = i; + } + for (var i = 1; i <= s1.length; i++) { + var c1 = s1.charCodeAt(i - 1); + var minJ = i > max ? i - max : 1; + var maxJ = s2.length > max + i ? max + i : s2.length; + current[0] = i; + /** Smallest value of the matrix in the ith column. */ + var colMin = i; + for (var j = 1; j < minJ; j++) { + current[j] = big; + } + for (var j = minJ; j <= maxJ; j++) { + var dist = c1 === s2.charCodeAt(j - 1) + ? previous[j - 1] + : Math.min(/*delete*/ previous[j] + 1, /*insert*/ current[j - 1] + 1, /*substitute*/ previous[j - 1] + 2); + current[j] = dist; + colMin = Math.min(colMin, dist); + } + for (var j = maxJ + 1; j <= s2.length; j++) { + current[j] = big; + } + if (colMin > max) { + // Give up -- everything in this column is > max and it can't get better in future columns. + return undefined; + } + var temp = previous; + previous = current; + current = temp; + } + var res = previous[s2.length]; + return res > max ? undefined : res; + } + function endsWith(str, suffix) { + var expectedPos = str.length - suffix.length; + return expectedPos >= 0 && str.indexOf(suffix, expectedPos) === expectedPos; + } + ts.endsWith = endsWith; + function removeSuffix(str, suffix) { + return endsWith(str, suffix) ? str.slice(0, str.length - suffix.length) : str; + } + ts.removeSuffix = removeSuffix; + function tryRemoveSuffix(str, suffix) { + return endsWith(str, suffix) ? str.slice(0, str.length - suffix.length) : undefined; + } + ts.tryRemoveSuffix = tryRemoveSuffix; + function stringContains(str, substring) { + return str.indexOf(substring) !== -1; + } + ts.stringContains = stringContains; + function fileExtensionIs(path, extension) { + return path.length > extension.length && endsWith(path, extension); + } + ts.fileExtensionIs = fileExtensionIs; + function fileExtensionIsOneOf(path, extensions) { + for (var _i = 0, extensions_1 = extensions; _i < extensions_1.length; _i++) { + var extension = extensions_1[_i]; + if (fileExtensionIs(path, extension)) { + return true; + } + } + return false; + } + ts.fileExtensionIsOneOf = fileExtensionIsOneOf; + /** + * Takes a string like "jquery-min.4.2.3" and returns "jquery" + */ + function removeMinAndVersionNumbers(fileName) { + // Match a "." or "-" followed by a version number or 'min' at the end of the name + var trailingMinOrVersion = /[.-]((min)|(\d+(\.\d+)*))$/; + // The "min" or version may both be present, in either order, so try applying the above twice. + return fileName.replace(trailingMinOrVersion, "").replace(trailingMinOrVersion, ""); + } + ts.removeMinAndVersionNumbers = removeMinAndVersionNumbers; + /** Remove an item from an array, moving everything to its right one space left. */ + function orderedRemoveItem(array, item) { + for (var i = 0; i < array.length; i++) { + if (array[i] === item) { + orderedRemoveItemAt(array, i); + return true; + } + } + return false; + } + ts.orderedRemoveItem = orderedRemoveItem; + /** Remove an item by index from an array, moving everything to its right one space left. */ + function orderedRemoveItemAt(array, index) { + // This seems to be faster than either `array.splice(i, 1)` or `array.copyWithin(i, i+ 1)`. + for (var i = index; i < array.length - 1; i++) { + array[i] = array[i + 1]; + } + array.pop(); + } + ts.orderedRemoveItemAt = orderedRemoveItemAt; + function unorderedRemoveItemAt(array, index) { + // Fill in the "hole" left at `index`. + array[index] = array[array.length - 1]; + array.pop(); + } + ts.unorderedRemoveItemAt = unorderedRemoveItemAt; + /** Remove the *first* occurrence of `item` from the array. */ + function unorderedRemoveItem(array, item) { + return unorderedRemoveFirstItemWhere(array, function (element) { return element === item; }); + } + ts.unorderedRemoveItem = unorderedRemoveItem; + /** Remove the *first* element satisfying `predicate`. */ + function unorderedRemoveFirstItemWhere(array, predicate) { + for (var i = 0; i < array.length; i++) { + if (predicate(array[i])) { + unorderedRemoveItemAt(array, i); + return true; + } + } + return false; + } + function createGetCanonicalFileName(useCaseSensitiveFileNames) { + return useCaseSensitiveFileNames ? identity : toLowerCase; + } + ts.createGetCanonicalFileName = createGetCanonicalFileName; + function patternText(_a) { + var prefix = _a.prefix, suffix = _a.suffix; + return prefix + "*" + suffix; + } + ts.patternText = patternText; + /** + * Given that candidate matches pattern, returns the text matching the '*'. + * E.g.: matchedText(tryParsePattern("foo*baz"), "foobarbaz") === "bar" + */ + function matchedText(pattern, candidate) { + Debug.assert(isPatternMatch(pattern, candidate)); + return candidate.substring(pattern.prefix.length, candidate.length - pattern.suffix.length); + } + ts.matchedText = matchedText; + /** Return the object corresponding to the best pattern to match `candidate`. */ + function findBestPatternMatch(values, getPattern, candidate) { + var matchedValue; + // use length of prefix as betterness criteria + var longestMatchPrefixLength = -1; + for (var _i = 0, values_2 = values; _i < values_2.length; _i++) { + var v = values_2[_i]; + var pattern = getPattern(v); + if (isPatternMatch(pattern, candidate) && pattern.prefix.length > longestMatchPrefixLength) { + longestMatchPrefixLength = pattern.prefix.length; + matchedValue = v; + } + } + return matchedValue; + } + ts.findBestPatternMatch = findBestPatternMatch; + function startsWith(str, prefix) { + return str.lastIndexOf(prefix, 0) === 0; + } + ts.startsWith = startsWith; + function removePrefix(str, prefix) { + return startsWith(str, prefix) ? str.substr(prefix.length) : str; + } + ts.removePrefix = removePrefix; + function tryRemovePrefix(str, prefix, getCanonicalFileName) { + if (getCanonicalFileName === void 0) { getCanonicalFileName = identity; } + return startsWith(getCanonicalFileName(str), getCanonicalFileName(prefix)) ? str.substring(prefix.length) : undefined; + } + ts.tryRemovePrefix = tryRemovePrefix; + function isPatternMatch(_a, candidate) { + var prefix = _a.prefix, suffix = _a.suffix; + return candidate.length >= prefix.length + suffix.length && + startsWith(candidate, prefix) && + endsWith(candidate, suffix); + } + function and(f, g) { + return function (arg) { return f(arg) && g(arg); }; + } + ts.and = and; + function or(f, g) { + return function (arg) { return f(arg) || g(arg); }; + } + ts.or = or; + function assertType(_) { } // tslint:disable-line no-empty + ts.assertType = assertType; + function singleElementArray(t) { + return t === undefined ? undefined : [t]; + } + ts.singleElementArray = singleElementArray; + function enumerateInsertsAndDeletes(newItems, oldItems, comparer, inserted, deleted, unchanged) { + unchanged = unchanged || noop; + var newIndex = 0; + var oldIndex = 0; + var newLen = newItems.length; + var oldLen = oldItems.length; + while (newIndex < newLen && oldIndex < oldLen) { + var newItem = newItems[newIndex]; + var oldItem = oldItems[oldIndex]; + var compareResult = comparer(newItem, oldItem); + if (compareResult === -1 /* LessThan */) { + inserted(newItem); + newIndex++; + } + else if (compareResult === 1 /* GreaterThan */) { + deleted(oldItem); + oldIndex++; + } + else { + unchanged(oldItem, newItem); + newIndex++; + oldIndex++; + } + } + while (newIndex < newLen) { + inserted(newItems[newIndex++]); + } + while (oldIndex < oldLen) { + deleted(oldItems[oldIndex++]); + } + } + ts.enumerateInsertsAndDeletes = enumerateInsertsAndDeletes; + function fill(length, cb) { + return new Array(length).fill(0).map(function (_, i) { return cb(i); }); + } + ts.fill = fill; +})(ts || (ts = {})); +/*@internal*/ +var ts; +(function (ts) { + /** Gets a timestamp with (at least) ms resolution */ + ts.timestamp = typeof performance !== "undefined" && performance.now ? function () { return performance.now(); } : Date.now ? Date.now : function () { return +(new Date()); }; +})(ts || (ts = {})); +/*@internal*/ +/** Performance measurements for the compiler. */ +(function (ts) { + var performance; + (function (performance) { + // NOTE: cannot use ts.noop as core.ts loads after this + var profilerEvent = typeof onProfilerEvent === "function" && onProfilerEvent.profiler === true ? onProfilerEvent : function () { }; + var enabled = false; + var profilerStart = 0; + var counts; + var marks; + var measures; + function createTimerIf(condition, measureName, startMarkName, endMarkName) { + return condition ? createTimer(measureName, startMarkName, endMarkName) : performance.nullTimer; + } + performance.createTimerIf = createTimerIf; + function createTimer(measureName, startMarkName, endMarkName) { + var enterCount = 0; + return { + enter: enter, + exit: exit + }; + function enter() { + if (++enterCount === 1) { + mark(startMarkName); + } + } + function exit() { + if (--enterCount === 0) { + mark(endMarkName); + measure(measureName, startMarkName, endMarkName); + } + else if (enterCount < 0) { + ts.Debug.fail("enter/exit count does not match."); + } + } + } + performance.createTimer = createTimer; + performance.nullTimer = { enter: ts.noop, exit: ts.noop }; + /** + * Marks a performance event. + * + * @param markName The name of the mark. + */ + function mark(markName) { + if (enabled) { + marks.set(markName, ts.timestamp()); + counts.set(markName, (counts.get(markName) || 0) + 1); + profilerEvent(markName); + } + } + performance.mark = mark; + /** + * Adds a performance measurement with the specified name. + * + * @param measureName The name of the performance measurement. + * @param startMarkName The name of the starting mark. If not supplied, the point at which the + * profiler was enabled is used. + * @param endMarkName The name of the ending mark. If not supplied, the current timestamp is + * used. + */ + function measure(measureName, startMarkName, endMarkName) { + if (enabled) { + var end = endMarkName && marks.get(endMarkName) || ts.timestamp(); + var start = startMarkName && marks.get(startMarkName) || profilerStart; + measures.set(measureName, (measures.get(measureName) || 0) + (end - start)); + } + } + performance.measure = measure; + /** + * Gets the number of times a marker was encountered. + * + * @param markName The name of the mark. + */ + function getCount(markName) { + return counts && counts.get(markName) || 0; + } + performance.getCount = getCount; + /** + * Gets the total duration of all measurements with the supplied name. + * + * @param measureName The name of the measure whose durations should be accumulated. + */ + function getDuration(measureName) { + return measures && measures.get(measureName) || 0; + } + performance.getDuration = getDuration; + /** + * Iterate over each measure, performing some action + * + * @param cb The action to perform for each measure + */ + function forEachMeasure(cb) { + measures.forEach(function (measure, key) { + cb(key, measure); + }); + } + performance.forEachMeasure = forEachMeasure; + /** Enables (and resets) performance measurements for the compiler. */ + function enable() { + counts = ts.createMap(); + marks = ts.createMap(); + measures = ts.createMap(); + enabled = true; + profilerStart = ts.timestamp(); + } + performance.enable = enable; + /** Disables performance measurements for the compiler. */ + function disable() { + enabled = false; + } + performance.disable = disable; + })(performance = ts.performance || (ts.performance = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + // https://semver.org/#spec-item-2 + // > A normal version number MUST take the form X.Y.Z where X, Y, and Z are non-negative + // > integers, and MUST NOT contain leading zeroes. X is the major version, Y is the minor + // > version, and Z is the patch version. Each element MUST increase numerically. + // + // NOTE: We differ here in that we allow X and X.Y, with missing parts having the default + // value of `0`. + var versionRegExp = /^(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\-([a-z0-9-.]+))?(?:\+([a-z0-9-.]+))?)?)?$/i; + // https://semver.org/#spec-item-9 + // > A pre-release version MAY be denoted by appending a hyphen and a series of dot separated + // > identifiers immediately following the patch version. Identifiers MUST comprise only ASCII + // > alphanumerics and hyphen [0-9A-Za-z-]. Identifiers MUST NOT be empty. Numeric identifiers + // > MUST NOT include leading zeroes. + var prereleaseRegExp = /^(?:0|[1-9]\d*|[a-z-][a-z0-9-]*)(?:\.(?:0|[1-9]\d*|[a-z-][a-z0-9-]*))*$/i; + // https://semver.org/#spec-item-10 + // > Build metadata MAY be denoted by appending a plus sign and a series of dot separated + // > identifiers immediately following the patch or pre-release version. Identifiers MUST + // > comprise only ASCII alphanumerics and hyphen [0-9A-Za-z-]. Identifiers MUST NOT be empty. + var buildRegExp = /^[a-z0-9-]+(?:\.[a-z0-9-]+)*$/i; + // https://semver.org/#spec-item-9 + // > Numeric identifiers MUST NOT include leading zeroes. + var numericIdentifierRegExp = /^(0|[1-9]\d*)$/; + /** + * Describes a precise semantic version number, https://semver.org + */ + var Version = /** @class */ (function () { + function Version(major, minor, patch, prerelease, build) { + if (minor === void 0) { minor = 0; } + if (patch === void 0) { patch = 0; } + if (prerelease === void 0) { prerelease = ""; } + if (build === void 0) { build = ""; } + if (typeof major === "string") { + var result = ts.Debug.assertDefined(tryParseComponents(major), "Invalid version"); + (major = result.major, minor = result.minor, patch = result.patch, prerelease = result.prerelease, build = result.build); + } + ts.Debug.assert(major >= 0, "Invalid argument: major"); + ts.Debug.assert(minor >= 0, "Invalid argument: minor"); + ts.Debug.assert(patch >= 0, "Invalid argument: patch"); + ts.Debug.assert(!prerelease || prereleaseRegExp.test(prerelease), "Invalid argument: prerelease"); + ts.Debug.assert(!build || buildRegExp.test(build), "Invalid argument: build"); + this.major = major; + this.minor = minor; + this.patch = patch; + this.prerelease = prerelease ? prerelease.split(".") : ts.emptyArray; + this.build = build ? build.split(".") : ts.emptyArray; + } + Version.tryParse = function (text) { + var result = tryParseComponents(text); + if (!result) + return undefined; + var major = result.major, minor = result.minor, patch = result.patch, prerelease = result.prerelease, build = result.build; + return new Version(major, minor, patch, prerelease, build); + }; + Version.prototype.compareTo = function (other) { + // https://semver.org/#spec-item-11 + // > Precedence is determined by the first difference when comparing each of these + // > identifiers from left to right as follows: Major, minor, and patch versions are + // > always compared numerically. + // + // https://semver.org/#spec-item-11 + // > Precedence for two pre-release versions with the same major, minor, and patch version + // > MUST be determined by comparing each dot separated identifier from left to right until + // > a difference is found [...] + // + // https://semver.org/#spec-item-11 + // > Build metadata does not figure into precedence + if (this === other) + return 0 /* EqualTo */; + if (other === undefined) + return 1 /* GreaterThan */; + return ts.compareValues(this.major, other.major) + || ts.compareValues(this.minor, other.minor) + || ts.compareValues(this.patch, other.patch) + || comparePrerelaseIdentifiers(this.prerelease, other.prerelease); + }; + Version.prototype.increment = function (field) { + switch (field) { + case "major": return new Version(this.major + 1, 0, 0); + case "minor": return new Version(this.major, this.minor + 1, 0); + case "patch": return new Version(this.major, this.minor, this.patch + 1); + default: return ts.Debug.assertNever(field); + } + }; + Version.prototype.toString = function () { + var result = this.major + "." + this.minor + "." + this.patch; + if (ts.some(this.prerelease)) + result += "-" + this.prerelease.join("."); + if (ts.some(this.build)) + result += "+" + this.build.join("."); + return result; + }; + Version.zero = new Version(0, 0, 0); + return Version; + }()); + ts.Version = Version; + function tryParseComponents(text) { + var match = versionRegExp.exec(text); + if (!match) + return undefined; + var major = match[1], _a = match[2], minor = _a === void 0 ? "0" : _a, _b = match[3], patch = _b === void 0 ? "0" : _b, _c = match[4], prerelease = _c === void 0 ? "" : _c, _d = match[5], build = _d === void 0 ? "" : _d; + if (prerelease && !prereleaseRegExp.test(prerelease)) + return undefined; + if (build && !buildRegExp.test(build)) + return undefined; + return { + major: parseInt(major, 10), + minor: parseInt(minor, 10), + patch: parseInt(patch, 10), + prerelease: prerelease, + build: build + }; + } + function comparePrerelaseIdentifiers(left, right) { + // https://semver.org/#spec-item-11 + // > When major, minor, and patch are equal, a pre-release version has lower precedence + // > than a normal version. + if (left === right) + return 0 /* EqualTo */; + if (left.length === 0) + return right.length === 0 ? 0 /* EqualTo */ : 1 /* GreaterThan */; + if (right.length === 0) + return -1 /* LessThan */; + // https://semver.org/#spec-item-11 + // > Precedence for two pre-release versions with the same major, minor, and patch version + // > MUST be determined by comparing each dot separated identifier from left to right until + // > a difference is found [...] + var length = Math.min(left.length, right.length); + for (var i = 0; i < length; i++) { + var leftIdentifier = left[i]; + var rightIdentifier = right[i]; + if (leftIdentifier === rightIdentifier) + continue; + var leftIsNumeric = numericIdentifierRegExp.test(leftIdentifier); + var rightIsNumeric = numericIdentifierRegExp.test(rightIdentifier); + if (leftIsNumeric || rightIsNumeric) { + // https://semver.org/#spec-item-11 + // > Numeric identifiers always have lower precedence than non-numeric identifiers. + if (leftIsNumeric !== rightIsNumeric) + return leftIsNumeric ? -1 /* LessThan */ : 1 /* GreaterThan */; + // https://semver.org/#spec-item-11 + // > identifiers consisting of only digits are compared numerically + var result = ts.compareValues(+leftIdentifier, +rightIdentifier); + if (result) + return result; + } + else { + // https://semver.org/#spec-item-11 + // > identifiers with letters or hyphens are compared lexically in ASCII sort order. + var result = ts.compareStringsCaseSensitive(leftIdentifier, rightIdentifier); + if (result) + return result; + } + } + // https://semver.org/#spec-item-11 + // > A larger set of pre-release fields has a higher precedence than a smaller set, if all + // > of the preceding identifiers are equal. + return ts.compareValues(left.length, right.length); + } + /** + * Describes a semantic version range, per https://github.com/npm/node-semver#ranges + */ + var VersionRange = /** @class */ (function () { + function VersionRange(spec) { + this._alternatives = spec ? ts.Debug.assertDefined(parseRange(spec), "Invalid range spec.") : ts.emptyArray; + } + VersionRange.tryParse = function (text) { + var sets = parseRange(text); + if (sets) { + var range = new VersionRange(""); + range._alternatives = sets; + return range; + } + return undefined; + }; + VersionRange.prototype.test = function (version) { + if (typeof version === "string") + version = new Version(version); + return testDisjunction(version, this._alternatives); + }; + VersionRange.prototype.toString = function () { + return formatDisjunction(this._alternatives); + }; + return VersionRange; + }()); + ts.VersionRange = VersionRange; + // https://github.com/npm/node-semver#range-grammar + // + // range-set ::= range ( logical-or range ) * + // range ::= hyphen | simple ( ' ' simple ) * | '' + // logical-or ::= ( ' ' ) * '||' ( ' ' ) * + var logicalOrRegExp = /\s*\|\|\s*/g; + var whitespaceRegExp = /\s+/g; + // https://github.com/npm/node-semver#range-grammar + // + // partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )? + // xr ::= 'x' | 'X' | '*' | nr + // nr ::= '0' | ['1'-'9'] ( ['0'-'9'] ) * + // qualifier ::= ( '-' pre )? ( '+' build )? + // pre ::= parts + // build ::= parts + // parts ::= part ( '.' part ) * + // part ::= nr | [-0-9A-Za-z]+ + var partialRegExp = /^([xX*0]|[1-9]\d*)(?:\.([xX*0]|[1-9]\d*)(?:\.([xX*0]|[1-9]\d*)(?:-([a-z0-9-.]+))?(?:\+([a-z0-9-.]+))?)?)?$/i; + // https://github.com/npm/node-semver#range-grammar + // + // hyphen ::= partial ' - ' partial + var hyphenRegExp = /^\s*([a-z0-9-+.*]+)\s+-\s+([a-z0-9-+.*]+)\s*$/i; + // https://github.com/npm/node-semver#range-grammar + // + // simple ::= primitive | partial | tilde | caret + // primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial + // tilde ::= '~' partial + // caret ::= '^' partial + var rangeRegExp = /^\s*(~|\^|<|<=|>|>=|=)?\s*([a-z0-9-+.*]+)$/i; + function parseRange(text) { + var alternatives = []; + for (var _i = 0, _a = text.trim().split(logicalOrRegExp); _i < _a.length; _i++) { + var range = _a[_i]; + if (!range) + continue; + var comparators = []; + var match = hyphenRegExp.exec(range); + if (match) { + if (!parseHyphen(match[1], match[2], comparators)) + return undefined; + } + else { + for (var _b = 0, _c = range.split(whitespaceRegExp); _b < _c.length; _b++) { + var simple = _c[_b]; + var match_1 = rangeRegExp.exec(simple); + if (!match_1 || !parseComparator(match_1[1], match_1[2], comparators)) + return undefined; + } + } + alternatives.push(comparators); + } + return alternatives; + } + function parsePartial(text) { + var match = partialRegExp.exec(text); + if (!match) + return undefined; + var major = match[1], _a = match[2], minor = _a === void 0 ? "*" : _a, _b = match[3], patch = _b === void 0 ? "*" : _b, prerelease = match[4], build = match[5]; + var version = new Version(isWildcard(major) ? 0 : parseInt(major, 10), isWildcard(major) || isWildcard(minor) ? 0 : parseInt(minor, 10), isWildcard(major) || isWildcard(minor) || isWildcard(patch) ? 0 : parseInt(patch, 10), prerelease, build); + return { version: version, major: major, minor: minor, patch: patch }; + } + function parseHyphen(left, right, comparators) { + var leftResult = parsePartial(left); + if (!leftResult) + return false; + var rightResult = parsePartial(right); + if (!rightResult) + return false; + if (!isWildcard(leftResult.major)) { + comparators.push(createComparator(">=", leftResult.version)); + } + if (!isWildcard(rightResult.major)) { + comparators.push(isWildcard(rightResult.minor) ? createComparator("<", rightResult.version.increment("major")) : + isWildcard(rightResult.patch) ? createComparator("<", rightResult.version.increment("minor")) : + createComparator("<=", rightResult.version)); + } + return true; + } + function parseComparator(operator, text, comparators) { + var result = parsePartial(text); + if (!result) + return false; + var version = result.version, major = result.major, minor = result.minor, patch = result.patch; + if (!isWildcard(major)) { + switch (operator) { + case "~": + comparators.push(createComparator(">=", version)); + comparators.push(createComparator("<", version.increment(isWildcard(minor) ? "major" : + "minor"))); + break; + case "^": + comparators.push(createComparator(">=", version)); + comparators.push(createComparator("<", version.increment(version.major > 0 || isWildcard(minor) ? "major" : + version.minor > 0 || isWildcard(patch) ? "minor" : + "patch"))); + break; + case "<": + case ">=": + comparators.push(createComparator(operator, version)); + break; + case "<=": + case ">": + comparators.push(isWildcard(minor) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("major")) : + isWildcard(patch) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("minor")) : + createComparator(operator, version)); + break; + case "=": + case undefined: + if (isWildcard(minor) || isWildcard(patch)) { + comparators.push(createComparator(">=", version)); + comparators.push(createComparator("<", version.increment(isWildcard(minor) ? "major" : "minor"))); + } + else { + comparators.push(createComparator("=", version)); + } + break; + default: + // unrecognized + return false; + } + } + else if (operator === "<" || operator === ">") { + comparators.push(createComparator("<", Version.zero)); + } + return true; + } + function isWildcard(part) { + return part === "*" || part === "x" || part === "X"; + } + function createComparator(operator, operand) { + return { operator: operator, operand: operand }; + } + function testDisjunction(version, alternatives) { + // an empty disjunction is treated as "*" (all versions) + if (alternatives.length === 0) + return true; + for (var _i = 0, alternatives_1 = alternatives; _i < alternatives_1.length; _i++) { + var alternative = alternatives_1[_i]; + if (testAlternative(version, alternative)) + return true; + } + return false; + } + function testAlternative(version, comparators) { + for (var _i = 0, comparators_1 = comparators; _i < comparators_1.length; _i++) { + var comparator = comparators_1[_i]; + if (!testComparator(version, comparator.operator, comparator.operand)) + return false; + } + return true; + } + function testComparator(version, operator, operand) { + var cmp = version.compareTo(operand); + switch (operator) { + case "<": return cmp < 0; + case "<=": return cmp <= 0; + case ">": return cmp > 0; + case ">=": return cmp >= 0; + case "=": return cmp === 0; + default: return ts.Debug.assertNever(operator); + } + } + function formatDisjunction(alternatives) { + return ts.map(alternatives, formatAlternative).join(" || ") || "*"; + } + function formatAlternative(comparators) { + return ts.map(comparators, formatComparator).join(" "); + } + function formatComparator(comparator) { + return "" + comparator.operator + comparator.operand; + } +})(ts || (ts = {})); +var ts; +(function (ts) { + // token > SyntaxKind.Identifier => token is a keyword + // Also, If you add a new SyntaxKind be sure to keep the `Markers` section at the bottom in sync + var SyntaxKind; + (function (SyntaxKind) { + SyntaxKind[SyntaxKind["Unknown"] = 0] = "Unknown"; + SyntaxKind[SyntaxKind["EndOfFileToken"] = 1] = "EndOfFileToken"; + SyntaxKind[SyntaxKind["SingleLineCommentTrivia"] = 2] = "SingleLineCommentTrivia"; + SyntaxKind[SyntaxKind["MultiLineCommentTrivia"] = 3] = "MultiLineCommentTrivia"; + SyntaxKind[SyntaxKind["NewLineTrivia"] = 4] = "NewLineTrivia"; + SyntaxKind[SyntaxKind["WhitespaceTrivia"] = 5] = "WhitespaceTrivia"; + // We detect and preserve #! on the first line + SyntaxKind[SyntaxKind["ShebangTrivia"] = 6] = "ShebangTrivia"; + // We detect and provide better error recovery when we encounter a git merge marker. This + // allows us to edit files with git-conflict markers in them in a much more pleasant manner. + SyntaxKind[SyntaxKind["ConflictMarkerTrivia"] = 7] = "ConflictMarkerTrivia"; + // Literals + SyntaxKind[SyntaxKind["NumericLiteral"] = 8] = "NumericLiteral"; + SyntaxKind[SyntaxKind["BigIntLiteral"] = 9] = "BigIntLiteral"; + SyntaxKind[SyntaxKind["StringLiteral"] = 10] = "StringLiteral"; + SyntaxKind[SyntaxKind["JsxText"] = 11] = "JsxText"; + SyntaxKind[SyntaxKind["JsxTextAllWhiteSpaces"] = 12] = "JsxTextAllWhiteSpaces"; + SyntaxKind[SyntaxKind["RegularExpressionLiteral"] = 13] = "RegularExpressionLiteral"; + SyntaxKind[SyntaxKind["NoSubstitutionTemplateLiteral"] = 14] = "NoSubstitutionTemplateLiteral"; + // Pseudo-literals + SyntaxKind[SyntaxKind["TemplateHead"] = 15] = "TemplateHead"; + SyntaxKind[SyntaxKind["TemplateMiddle"] = 16] = "TemplateMiddle"; + SyntaxKind[SyntaxKind["TemplateTail"] = 17] = "TemplateTail"; + // Punctuation + SyntaxKind[SyntaxKind["OpenBraceToken"] = 18] = "OpenBraceToken"; + SyntaxKind[SyntaxKind["CloseBraceToken"] = 19] = "CloseBraceToken"; + SyntaxKind[SyntaxKind["OpenParenToken"] = 20] = "OpenParenToken"; + SyntaxKind[SyntaxKind["CloseParenToken"] = 21] = "CloseParenToken"; + SyntaxKind[SyntaxKind["OpenBracketToken"] = 22] = "OpenBracketToken"; + SyntaxKind[SyntaxKind["CloseBracketToken"] = 23] = "CloseBracketToken"; + SyntaxKind[SyntaxKind["DotToken"] = 24] = "DotToken"; + SyntaxKind[SyntaxKind["DotDotDotToken"] = 25] = "DotDotDotToken"; + SyntaxKind[SyntaxKind["SemicolonToken"] = 26] = "SemicolonToken"; + SyntaxKind[SyntaxKind["CommaToken"] = 27] = "CommaToken"; + SyntaxKind[SyntaxKind["LessThanToken"] = 28] = "LessThanToken"; + SyntaxKind[SyntaxKind["LessThanSlashToken"] = 29] = "LessThanSlashToken"; + SyntaxKind[SyntaxKind["GreaterThanToken"] = 30] = "GreaterThanToken"; + SyntaxKind[SyntaxKind["LessThanEqualsToken"] = 31] = "LessThanEqualsToken"; + SyntaxKind[SyntaxKind["GreaterThanEqualsToken"] = 32] = "GreaterThanEqualsToken"; + SyntaxKind[SyntaxKind["EqualsEqualsToken"] = 33] = "EqualsEqualsToken"; + SyntaxKind[SyntaxKind["ExclamationEqualsToken"] = 34] = "ExclamationEqualsToken"; + SyntaxKind[SyntaxKind["EqualsEqualsEqualsToken"] = 35] = "EqualsEqualsEqualsToken"; + SyntaxKind[SyntaxKind["ExclamationEqualsEqualsToken"] = 36] = "ExclamationEqualsEqualsToken"; + SyntaxKind[SyntaxKind["EqualsGreaterThanToken"] = 37] = "EqualsGreaterThanToken"; + SyntaxKind[SyntaxKind["PlusToken"] = 38] = "PlusToken"; + SyntaxKind[SyntaxKind["MinusToken"] = 39] = "MinusToken"; + SyntaxKind[SyntaxKind["AsteriskToken"] = 40] = "AsteriskToken"; + SyntaxKind[SyntaxKind["AsteriskAsteriskToken"] = 41] = "AsteriskAsteriskToken"; + SyntaxKind[SyntaxKind["SlashToken"] = 42] = "SlashToken"; + SyntaxKind[SyntaxKind["PercentToken"] = 43] = "PercentToken"; + SyntaxKind[SyntaxKind["PlusPlusToken"] = 44] = "PlusPlusToken"; + SyntaxKind[SyntaxKind["MinusMinusToken"] = 45] = "MinusMinusToken"; + SyntaxKind[SyntaxKind["LessThanLessThanToken"] = 46] = "LessThanLessThanToken"; + SyntaxKind[SyntaxKind["GreaterThanGreaterThanToken"] = 47] = "GreaterThanGreaterThanToken"; + SyntaxKind[SyntaxKind["GreaterThanGreaterThanGreaterThanToken"] = 48] = "GreaterThanGreaterThanGreaterThanToken"; + SyntaxKind[SyntaxKind["AmpersandToken"] = 49] = "AmpersandToken"; + SyntaxKind[SyntaxKind["BarToken"] = 50] = "BarToken"; + SyntaxKind[SyntaxKind["CaretToken"] = 51] = "CaretToken"; + SyntaxKind[SyntaxKind["ExclamationToken"] = 52] = "ExclamationToken"; + SyntaxKind[SyntaxKind["TildeToken"] = 53] = "TildeToken"; + SyntaxKind[SyntaxKind["AmpersandAmpersandToken"] = 54] = "AmpersandAmpersandToken"; + SyntaxKind[SyntaxKind["BarBarToken"] = 55] = "BarBarToken"; + SyntaxKind[SyntaxKind["QuestionToken"] = 56] = "QuestionToken"; + SyntaxKind[SyntaxKind["ColonToken"] = 57] = "ColonToken"; + SyntaxKind[SyntaxKind["AtToken"] = 58] = "AtToken"; + // Assignments + SyntaxKind[SyntaxKind["EqualsToken"] = 59] = "EqualsToken"; + SyntaxKind[SyntaxKind["PlusEqualsToken"] = 60] = "PlusEqualsToken"; + SyntaxKind[SyntaxKind["MinusEqualsToken"] = 61] = "MinusEqualsToken"; + SyntaxKind[SyntaxKind["AsteriskEqualsToken"] = 62] = "AsteriskEqualsToken"; + SyntaxKind[SyntaxKind["AsteriskAsteriskEqualsToken"] = 63] = "AsteriskAsteriskEqualsToken"; + SyntaxKind[SyntaxKind["SlashEqualsToken"] = 64] = "SlashEqualsToken"; + SyntaxKind[SyntaxKind["PercentEqualsToken"] = 65] = "PercentEqualsToken"; + SyntaxKind[SyntaxKind["LessThanLessThanEqualsToken"] = 66] = "LessThanLessThanEqualsToken"; + SyntaxKind[SyntaxKind["GreaterThanGreaterThanEqualsToken"] = 67] = "GreaterThanGreaterThanEqualsToken"; + SyntaxKind[SyntaxKind["GreaterThanGreaterThanGreaterThanEqualsToken"] = 68] = "GreaterThanGreaterThanGreaterThanEqualsToken"; + SyntaxKind[SyntaxKind["AmpersandEqualsToken"] = 69] = "AmpersandEqualsToken"; + SyntaxKind[SyntaxKind["BarEqualsToken"] = 70] = "BarEqualsToken"; + SyntaxKind[SyntaxKind["CaretEqualsToken"] = 71] = "CaretEqualsToken"; + // Identifiers + SyntaxKind[SyntaxKind["Identifier"] = 72] = "Identifier"; + // Reserved words + SyntaxKind[SyntaxKind["BreakKeyword"] = 73] = "BreakKeyword"; + SyntaxKind[SyntaxKind["CaseKeyword"] = 74] = "CaseKeyword"; + SyntaxKind[SyntaxKind["CatchKeyword"] = 75] = "CatchKeyword"; + SyntaxKind[SyntaxKind["ClassKeyword"] = 76] = "ClassKeyword"; + SyntaxKind[SyntaxKind["ConstKeyword"] = 77] = "ConstKeyword"; + SyntaxKind[SyntaxKind["ContinueKeyword"] = 78] = "ContinueKeyword"; + SyntaxKind[SyntaxKind["DebuggerKeyword"] = 79] = "DebuggerKeyword"; + SyntaxKind[SyntaxKind["DefaultKeyword"] = 80] = "DefaultKeyword"; + SyntaxKind[SyntaxKind["DeleteKeyword"] = 81] = "DeleteKeyword"; + SyntaxKind[SyntaxKind["DoKeyword"] = 82] = "DoKeyword"; + SyntaxKind[SyntaxKind["ElseKeyword"] = 83] = "ElseKeyword"; + SyntaxKind[SyntaxKind["EnumKeyword"] = 84] = "EnumKeyword"; + SyntaxKind[SyntaxKind["ExportKeyword"] = 85] = "ExportKeyword"; + SyntaxKind[SyntaxKind["ExtendsKeyword"] = 86] = "ExtendsKeyword"; + SyntaxKind[SyntaxKind["FalseKeyword"] = 87] = "FalseKeyword"; + SyntaxKind[SyntaxKind["FinallyKeyword"] = 88] = "FinallyKeyword"; + SyntaxKind[SyntaxKind["ForKeyword"] = 89] = "ForKeyword"; + SyntaxKind[SyntaxKind["FunctionKeyword"] = 90] = "FunctionKeyword"; + SyntaxKind[SyntaxKind["IfKeyword"] = 91] = "IfKeyword"; + SyntaxKind[SyntaxKind["ImportKeyword"] = 92] = "ImportKeyword"; + SyntaxKind[SyntaxKind["InKeyword"] = 93] = "InKeyword"; + SyntaxKind[SyntaxKind["InstanceOfKeyword"] = 94] = "InstanceOfKeyword"; + SyntaxKind[SyntaxKind["NewKeyword"] = 95] = "NewKeyword"; + SyntaxKind[SyntaxKind["NullKeyword"] = 96] = "NullKeyword"; + SyntaxKind[SyntaxKind["ReturnKeyword"] = 97] = "ReturnKeyword"; + SyntaxKind[SyntaxKind["SuperKeyword"] = 98] = "SuperKeyword"; + SyntaxKind[SyntaxKind["SwitchKeyword"] = 99] = "SwitchKeyword"; + SyntaxKind[SyntaxKind["ThisKeyword"] = 100] = "ThisKeyword"; + SyntaxKind[SyntaxKind["ThrowKeyword"] = 101] = "ThrowKeyword"; + SyntaxKind[SyntaxKind["TrueKeyword"] = 102] = "TrueKeyword"; + SyntaxKind[SyntaxKind["TryKeyword"] = 103] = "TryKeyword"; + SyntaxKind[SyntaxKind["TypeOfKeyword"] = 104] = "TypeOfKeyword"; + SyntaxKind[SyntaxKind["VarKeyword"] = 105] = "VarKeyword"; + SyntaxKind[SyntaxKind["VoidKeyword"] = 106] = "VoidKeyword"; + SyntaxKind[SyntaxKind["WhileKeyword"] = 107] = "WhileKeyword"; + SyntaxKind[SyntaxKind["WithKeyword"] = 108] = "WithKeyword"; + // Strict mode reserved words + SyntaxKind[SyntaxKind["ImplementsKeyword"] = 109] = "ImplementsKeyword"; + SyntaxKind[SyntaxKind["InterfaceKeyword"] = 110] = "InterfaceKeyword"; + SyntaxKind[SyntaxKind["LetKeyword"] = 111] = "LetKeyword"; + SyntaxKind[SyntaxKind["PackageKeyword"] = 112] = "PackageKeyword"; + SyntaxKind[SyntaxKind["PrivateKeyword"] = 113] = "PrivateKeyword"; + SyntaxKind[SyntaxKind["ProtectedKeyword"] = 114] = "ProtectedKeyword"; + SyntaxKind[SyntaxKind["PublicKeyword"] = 115] = "PublicKeyword"; + SyntaxKind[SyntaxKind["StaticKeyword"] = 116] = "StaticKeyword"; + SyntaxKind[SyntaxKind["YieldKeyword"] = 117] = "YieldKeyword"; + // Contextual keywords + SyntaxKind[SyntaxKind["AbstractKeyword"] = 118] = "AbstractKeyword"; + SyntaxKind[SyntaxKind["AsKeyword"] = 119] = "AsKeyword"; + SyntaxKind[SyntaxKind["AnyKeyword"] = 120] = "AnyKeyword"; + SyntaxKind[SyntaxKind["AsyncKeyword"] = 121] = "AsyncKeyword"; + SyntaxKind[SyntaxKind["AwaitKeyword"] = 122] = "AwaitKeyword"; + SyntaxKind[SyntaxKind["BooleanKeyword"] = 123] = "BooleanKeyword"; + SyntaxKind[SyntaxKind["ConstructorKeyword"] = 124] = "ConstructorKeyword"; + SyntaxKind[SyntaxKind["DeclareKeyword"] = 125] = "DeclareKeyword"; + SyntaxKind[SyntaxKind["GetKeyword"] = 126] = "GetKeyword"; + SyntaxKind[SyntaxKind["InferKeyword"] = 127] = "InferKeyword"; + SyntaxKind[SyntaxKind["IsKeyword"] = 128] = "IsKeyword"; + SyntaxKind[SyntaxKind["KeyOfKeyword"] = 129] = "KeyOfKeyword"; + SyntaxKind[SyntaxKind["ModuleKeyword"] = 130] = "ModuleKeyword"; + SyntaxKind[SyntaxKind["NamespaceKeyword"] = 131] = "NamespaceKeyword"; + SyntaxKind[SyntaxKind["NeverKeyword"] = 132] = "NeverKeyword"; + SyntaxKind[SyntaxKind["ReadonlyKeyword"] = 133] = "ReadonlyKeyword"; + SyntaxKind[SyntaxKind["RequireKeyword"] = 134] = "RequireKeyword"; + SyntaxKind[SyntaxKind["NumberKeyword"] = 135] = "NumberKeyword"; + SyntaxKind[SyntaxKind["ObjectKeyword"] = 136] = "ObjectKeyword"; + SyntaxKind[SyntaxKind["SetKeyword"] = 137] = "SetKeyword"; + SyntaxKind[SyntaxKind["StringKeyword"] = 138] = "StringKeyword"; + SyntaxKind[SyntaxKind["SymbolKeyword"] = 139] = "SymbolKeyword"; + SyntaxKind[SyntaxKind["TypeKeyword"] = 140] = "TypeKeyword"; + SyntaxKind[SyntaxKind["UndefinedKeyword"] = 141] = "UndefinedKeyword"; + SyntaxKind[SyntaxKind["UniqueKeyword"] = 142] = "UniqueKeyword"; + SyntaxKind[SyntaxKind["UnknownKeyword"] = 143] = "UnknownKeyword"; + SyntaxKind[SyntaxKind["FromKeyword"] = 144] = "FromKeyword"; + SyntaxKind[SyntaxKind["GlobalKeyword"] = 145] = "GlobalKeyword"; + SyntaxKind[SyntaxKind["BigIntKeyword"] = 146] = "BigIntKeyword"; + SyntaxKind[SyntaxKind["OfKeyword"] = 147] = "OfKeyword"; + // Parse tree nodes + // Names + SyntaxKind[SyntaxKind["QualifiedName"] = 148] = "QualifiedName"; + SyntaxKind[SyntaxKind["ComputedPropertyName"] = 149] = "ComputedPropertyName"; + // Signature elements + SyntaxKind[SyntaxKind["TypeParameter"] = 150] = "TypeParameter"; + SyntaxKind[SyntaxKind["Parameter"] = 151] = "Parameter"; + SyntaxKind[SyntaxKind["Decorator"] = 152] = "Decorator"; + // TypeMember + SyntaxKind[SyntaxKind["PropertySignature"] = 153] = "PropertySignature"; + SyntaxKind[SyntaxKind["PropertyDeclaration"] = 154] = "PropertyDeclaration"; + SyntaxKind[SyntaxKind["MethodSignature"] = 155] = "MethodSignature"; + SyntaxKind[SyntaxKind["MethodDeclaration"] = 156] = "MethodDeclaration"; + SyntaxKind[SyntaxKind["Constructor"] = 157] = "Constructor"; + SyntaxKind[SyntaxKind["GetAccessor"] = 158] = "GetAccessor"; + SyntaxKind[SyntaxKind["SetAccessor"] = 159] = "SetAccessor"; + SyntaxKind[SyntaxKind["CallSignature"] = 160] = "CallSignature"; + SyntaxKind[SyntaxKind["ConstructSignature"] = 161] = "ConstructSignature"; + SyntaxKind[SyntaxKind["IndexSignature"] = 162] = "IndexSignature"; + // Type + SyntaxKind[SyntaxKind["TypePredicate"] = 163] = "TypePredicate"; + SyntaxKind[SyntaxKind["TypeReference"] = 164] = "TypeReference"; + SyntaxKind[SyntaxKind["FunctionType"] = 165] = "FunctionType"; + SyntaxKind[SyntaxKind["ConstructorType"] = 166] = "ConstructorType"; + SyntaxKind[SyntaxKind["TypeQuery"] = 167] = "TypeQuery"; + SyntaxKind[SyntaxKind["TypeLiteral"] = 168] = "TypeLiteral"; + SyntaxKind[SyntaxKind["ArrayType"] = 169] = "ArrayType"; + SyntaxKind[SyntaxKind["TupleType"] = 170] = "TupleType"; + SyntaxKind[SyntaxKind["OptionalType"] = 171] = "OptionalType"; + SyntaxKind[SyntaxKind["RestType"] = 172] = "RestType"; + SyntaxKind[SyntaxKind["UnionType"] = 173] = "UnionType"; + SyntaxKind[SyntaxKind["IntersectionType"] = 174] = "IntersectionType"; + SyntaxKind[SyntaxKind["ConditionalType"] = 175] = "ConditionalType"; + SyntaxKind[SyntaxKind["InferType"] = 176] = "InferType"; + SyntaxKind[SyntaxKind["ParenthesizedType"] = 177] = "ParenthesizedType"; + SyntaxKind[SyntaxKind["ThisType"] = 178] = "ThisType"; + SyntaxKind[SyntaxKind["TypeOperator"] = 179] = "TypeOperator"; + SyntaxKind[SyntaxKind["IndexedAccessType"] = 180] = "IndexedAccessType"; + SyntaxKind[SyntaxKind["MappedType"] = 181] = "MappedType"; + SyntaxKind[SyntaxKind["LiteralType"] = 182] = "LiteralType"; + SyntaxKind[SyntaxKind["ImportType"] = 183] = "ImportType"; + // Binding patterns + SyntaxKind[SyntaxKind["ObjectBindingPattern"] = 184] = "ObjectBindingPattern"; + SyntaxKind[SyntaxKind["ArrayBindingPattern"] = 185] = "ArrayBindingPattern"; + SyntaxKind[SyntaxKind["BindingElement"] = 186] = "BindingElement"; + // Expression + SyntaxKind[SyntaxKind["ArrayLiteralExpression"] = 187] = "ArrayLiteralExpression"; + SyntaxKind[SyntaxKind["ObjectLiteralExpression"] = 188] = "ObjectLiteralExpression"; + SyntaxKind[SyntaxKind["PropertyAccessExpression"] = 189] = "PropertyAccessExpression"; + SyntaxKind[SyntaxKind["ElementAccessExpression"] = 190] = "ElementAccessExpression"; + SyntaxKind[SyntaxKind["CallExpression"] = 191] = "CallExpression"; + SyntaxKind[SyntaxKind["NewExpression"] = 192] = "NewExpression"; + SyntaxKind[SyntaxKind["TaggedTemplateExpression"] = 193] = "TaggedTemplateExpression"; + SyntaxKind[SyntaxKind["TypeAssertionExpression"] = 194] = "TypeAssertionExpression"; + SyntaxKind[SyntaxKind["ParenthesizedExpression"] = 195] = "ParenthesizedExpression"; + SyntaxKind[SyntaxKind["FunctionExpression"] = 196] = "FunctionExpression"; + SyntaxKind[SyntaxKind["ArrowFunction"] = 197] = "ArrowFunction"; + SyntaxKind[SyntaxKind["DeleteExpression"] = 198] = "DeleteExpression"; + SyntaxKind[SyntaxKind["TypeOfExpression"] = 199] = "TypeOfExpression"; + SyntaxKind[SyntaxKind["VoidExpression"] = 200] = "VoidExpression"; + SyntaxKind[SyntaxKind["AwaitExpression"] = 201] = "AwaitExpression"; + SyntaxKind[SyntaxKind["PrefixUnaryExpression"] = 202] = "PrefixUnaryExpression"; + SyntaxKind[SyntaxKind["PostfixUnaryExpression"] = 203] = "PostfixUnaryExpression"; + SyntaxKind[SyntaxKind["BinaryExpression"] = 204] = "BinaryExpression"; + SyntaxKind[SyntaxKind["ConditionalExpression"] = 205] = "ConditionalExpression"; + SyntaxKind[SyntaxKind["TemplateExpression"] = 206] = "TemplateExpression"; + SyntaxKind[SyntaxKind["YieldExpression"] = 207] = "YieldExpression"; + SyntaxKind[SyntaxKind["SpreadElement"] = 208] = "SpreadElement"; + SyntaxKind[SyntaxKind["ClassExpression"] = 209] = "ClassExpression"; + SyntaxKind[SyntaxKind["OmittedExpression"] = 210] = "OmittedExpression"; + SyntaxKind[SyntaxKind["ExpressionWithTypeArguments"] = 211] = "ExpressionWithTypeArguments"; + SyntaxKind[SyntaxKind["AsExpression"] = 212] = "AsExpression"; + SyntaxKind[SyntaxKind["NonNullExpression"] = 213] = "NonNullExpression"; + SyntaxKind[SyntaxKind["MetaProperty"] = 214] = "MetaProperty"; + SyntaxKind[SyntaxKind["SyntheticExpression"] = 215] = "SyntheticExpression"; + // Misc + SyntaxKind[SyntaxKind["TemplateSpan"] = 216] = "TemplateSpan"; + SyntaxKind[SyntaxKind["SemicolonClassElement"] = 217] = "SemicolonClassElement"; + // Element + SyntaxKind[SyntaxKind["Block"] = 218] = "Block"; + SyntaxKind[SyntaxKind["VariableStatement"] = 219] = "VariableStatement"; + SyntaxKind[SyntaxKind["EmptyStatement"] = 220] = "EmptyStatement"; + SyntaxKind[SyntaxKind["ExpressionStatement"] = 221] = "ExpressionStatement"; + SyntaxKind[SyntaxKind["IfStatement"] = 222] = "IfStatement"; + SyntaxKind[SyntaxKind["DoStatement"] = 223] = "DoStatement"; + SyntaxKind[SyntaxKind["WhileStatement"] = 224] = "WhileStatement"; + SyntaxKind[SyntaxKind["ForStatement"] = 225] = "ForStatement"; + SyntaxKind[SyntaxKind["ForInStatement"] = 226] = "ForInStatement"; + SyntaxKind[SyntaxKind["ForOfStatement"] = 227] = "ForOfStatement"; + SyntaxKind[SyntaxKind["ContinueStatement"] = 228] = "ContinueStatement"; + SyntaxKind[SyntaxKind["BreakStatement"] = 229] = "BreakStatement"; + SyntaxKind[SyntaxKind["ReturnStatement"] = 230] = "ReturnStatement"; + SyntaxKind[SyntaxKind["WithStatement"] = 231] = "WithStatement"; + SyntaxKind[SyntaxKind["SwitchStatement"] = 232] = "SwitchStatement"; + SyntaxKind[SyntaxKind["LabeledStatement"] = 233] = "LabeledStatement"; + SyntaxKind[SyntaxKind["ThrowStatement"] = 234] = "ThrowStatement"; + SyntaxKind[SyntaxKind["TryStatement"] = 235] = "TryStatement"; + SyntaxKind[SyntaxKind["DebuggerStatement"] = 236] = "DebuggerStatement"; + SyntaxKind[SyntaxKind["VariableDeclaration"] = 237] = "VariableDeclaration"; + SyntaxKind[SyntaxKind["VariableDeclarationList"] = 238] = "VariableDeclarationList"; + SyntaxKind[SyntaxKind["FunctionDeclaration"] = 239] = "FunctionDeclaration"; + SyntaxKind[SyntaxKind["ClassDeclaration"] = 240] = "ClassDeclaration"; + SyntaxKind[SyntaxKind["InterfaceDeclaration"] = 241] = "InterfaceDeclaration"; + SyntaxKind[SyntaxKind["TypeAliasDeclaration"] = 242] = "TypeAliasDeclaration"; + SyntaxKind[SyntaxKind["EnumDeclaration"] = 243] = "EnumDeclaration"; + SyntaxKind[SyntaxKind["ModuleDeclaration"] = 244] = "ModuleDeclaration"; + SyntaxKind[SyntaxKind["ModuleBlock"] = 245] = "ModuleBlock"; + SyntaxKind[SyntaxKind["CaseBlock"] = 246] = "CaseBlock"; + SyntaxKind[SyntaxKind["NamespaceExportDeclaration"] = 247] = "NamespaceExportDeclaration"; + SyntaxKind[SyntaxKind["ImportEqualsDeclaration"] = 248] = "ImportEqualsDeclaration"; + SyntaxKind[SyntaxKind["ImportDeclaration"] = 249] = "ImportDeclaration"; + SyntaxKind[SyntaxKind["ImportClause"] = 250] = "ImportClause"; + SyntaxKind[SyntaxKind["NamespaceImport"] = 251] = "NamespaceImport"; + SyntaxKind[SyntaxKind["NamedImports"] = 252] = "NamedImports"; + SyntaxKind[SyntaxKind["ImportSpecifier"] = 253] = "ImportSpecifier"; + SyntaxKind[SyntaxKind["ExportAssignment"] = 254] = "ExportAssignment"; + SyntaxKind[SyntaxKind["ExportDeclaration"] = 255] = "ExportDeclaration"; + SyntaxKind[SyntaxKind["NamedExports"] = 256] = "NamedExports"; + SyntaxKind[SyntaxKind["ExportSpecifier"] = 257] = "ExportSpecifier"; + SyntaxKind[SyntaxKind["MissingDeclaration"] = 258] = "MissingDeclaration"; + // Module references + SyntaxKind[SyntaxKind["ExternalModuleReference"] = 259] = "ExternalModuleReference"; + // JSX + SyntaxKind[SyntaxKind["JsxElement"] = 260] = "JsxElement"; + SyntaxKind[SyntaxKind["JsxSelfClosingElement"] = 261] = "JsxSelfClosingElement"; + SyntaxKind[SyntaxKind["JsxOpeningElement"] = 262] = "JsxOpeningElement"; + SyntaxKind[SyntaxKind["JsxClosingElement"] = 263] = "JsxClosingElement"; + SyntaxKind[SyntaxKind["JsxFragment"] = 264] = "JsxFragment"; + SyntaxKind[SyntaxKind["JsxOpeningFragment"] = 265] = "JsxOpeningFragment"; + SyntaxKind[SyntaxKind["JsxClosingFragment"] = 266] = "JsxClosingFragment"; + SyntaxKind[SyntaxKind["JsxAttribute"] = 267] = "JsxAttribute"; + SyntaxKind[SyntaxKind["JsxAttributes"] = 268] = "JsxAttributes"; + SyntaxKind[SyntaxKind["JsxSpreadAttribute"] = 269] = "JsxSpreadAttribute"; + SyntaxKind[SyntaxKind["JsxExpression"] = 270] = "JsxExpression"; + // Clauses + SyntaxKind[SyntaxKind["CaseClause"] = 271] = "CaseClause"; + SyntaxKind[SyntaxKind["DefaultClause"] = 272] = "DefaultClause"; + SyntaxKind[SyntaxKind["HeritageClause"] = 273] = "HeritageClause"; + SyntaxKind[SyntaxKind["CatchClause"] = 274] = "CatchClause"; + // Property assignments + SyntaxKind[SyntaxKind["PropertyAssignment"] = 275] = "PropertyAssignment"; + SyntaxKind[SyntaxKind["ShorthandPropertyAssignment"] = 276] = "ShorthandPropertyAssignment"; + SyntaxKind[SyntaxKind["SpreadAssignment"] = 277] = "SpreadAssignment"; + // Enum + SyntaxKind[SyntaxKind["EnumMember"] = 278] = "EnumMember"; + // Top-level nodes + SyntaxKind[SyntaxKind["SourceFile"] = 279] = "SourceFile"; + SyntaxKind[SyntaxKind["Bundle"] = 280] = "Bundle"; + SyntaxKind[SyntaxKind["UnparsedSource"] = 281] = "UnparsedSource"; + SyntaxKind[SyntaxKind["InputFiles"] = 282] = "InputFiles"; + // JSDoc nodes + SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 283] = "JSDocTypeExpression"; + // The * type + SyntaxKind[SyntaxKind["JSDocAllType"] = 284] = "JSDocAllType"; + // The ? type + SyntaxKind[SyntaxKind["JSDocUnknownType"] = 285] = "JSDocUnknownType"; + SyntaxKind[SyntaxKind["JSDocNullableType"] = 286] = "JSDocNullableType"; + SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 287] = "JSDocNonNullableType"; + SyntaxKind[SyntaxKind["JSDocOptionalType"] = 288] = "JSDocOptionalType"; + SyntaxKind[SyntaxKind["JSDocFunctionType"] = 289] = "JSDocFunctionType"; + SyntaxKind[SyntaxKind["JSDocVariadicType"] = 290] = "JSDocVariadicType"; + SyntaxKind[SyntaxKind["JSDocComment"] = 291] = "JSDocComment"; + SyntaxKind[SyntaxKind["JSDocTypeLiteral"] = 292] = "JSDocTypeLiteral"; + SyntaxKind[SyntaxKind["JSDocSignature"] = 293] = "JSDocSignature"; + SyntaxKind[SyntaxKind["JSDocTag"] = 294] = "JSDocTag"; + SyntaxKind[SyntaxKind["JSDocAugmentsTag"] = 295] = "JSDocAugmentsTag"; + SyntaxKind[SyntaxKind["JSDocClassTag"] = 296] = "JSDocClassTag"; + SyntaxKind[SyntaxKind["JSDocCallbackTag"] = 297] = "JSDocCallbackTag"; + SyntaxKind[SyntaxKind["JSDocEnumTag"] = 298] = "JSDocEnumTag"; + SyntaxKind[SyntaxKind["JSDocParameterTag"] = 299] = "JSDocParameterTag"; + SyntaxKind[SyntaxKind["JSDocReturnTag"] = 300] = "JSDocReturnTag"; + SyntaxKind[SyntaxKind["JSDocThisTag"] = 301] = "JSDocThisTag"; + SyntaxKind[SyntaxKind["JSDocTypeTag"] = 302] = "JSDocTypeTag"; + SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 303] = "JSDocTemplateTag"; + SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 304] = "JSDocTypedefTag"; + SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 305] = "JSDocPropertyTag"; + // Synthesized list + SyntaxKind[SyntaxKind["SyntaxList"] = 306] = "SyntaxList"; + // Transformation nodes + SyntaxKind[SyntaxKind["NotEmittedStatement"] = 307] = "NotEmittedStatement"; + SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 308] = "PartiallyEmittedExpression"; + SyntaxKind[SyntaxKind["CommaListExpression"] = 309] = "CommaListExpression"; + SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 310] = "MergeDeclarationMarker"; + SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 311] = "EndOfDeclarationMarker"; + // Enum value count + SyntaxKind[SyntaxKind["Count"] = 312] = "Count"; + // Markers + SyntaxKind[SyntaxKind["FirstAssignment"] = 59] = "FirstAssignment"; + SyntaxKind[SyntaxKind["LastAssignment"] = 71] = "LastAssignment"; + SyntaxKind[SyntaxKind["FirstCompoundAssignment"] = 60] = "FirstCompoundAssignment"; + SyntaxKind[SyntaxKind["LastCompoundAssignment"] = 71] = "LastCompoundAssignment"; + SyntaxKind[SyntaxKind["FirstReservedWord"] = 73] = "FirstReservedWord"; + SyntaxKind[SyntaxKind["LastReservedWord"] = 108] = "LastReservedWord"; + SyntaxKind[SyntaxKind["FirstKeyword"] = 73] = "FirstKeyword"; + SyntaxKind[SyntaxKind["LastKeyword"] = 147] = "LastKeyword"; + SyntaxKind[SyntaxKind["FirstFutureReservedWord"] = 109] = "FirstFutureReservedWord"; + SyntaxKind[SyntaxKind["LastFutureReservedWord"] = 117] = "LastFutureReservedWord"; + SyntaxKind[SyntaxKind["FirstTypeNode"] = 163] = "FirstTypeNode"; + SyntaxKind[SyntaxKind["LastTypeNode"] = 183] = "LastTypeNode"; + SyntaxKind[SyntaxKind["FirstPunctuation"] = 18] = "FirstPunctuation"; + SyntaxKind[SyntaxKind["LastPunctuation"] = 71] = "LastPunctuation"; + SyntaxKind[SyntaxKind["FirstToken"] = 0] = "FirstToken"; + SyntaxKind[SyntaxKind["LastToken"] = 147] = "LastToken"; + SyntaxKind[SyntaxKind["FirstTriviaToken"] = 2] = "FirstTriviaToken"; + SyntaxKind[SyntaxKind["LastTriviaToken"] = 7] = "LastTriviaToken"; + SyntaxKind[SyntaxKind["FirstLiteralToken"] = 8] = "FirstLiteralToken"; + SyntaxKind[SyntaxKind["LastLiteralToken"] = 14] = "LastLiteralToken"; + SyntaxKind[SyntaxKind["FirstTemplateToken"] = 14] = "FirstTemplateToken"; + SyntaxKind[SyntaxKind["LastTemplateToken"] = 17] = "LastTemplateToken"; + SyntaxKind[SyntaxKind["FirstBinaryOperator"] = 28] = "FirstBinaryOperator"; + SyntaxKind[SyntaxKind["LastBinaryOperator"] = 71] = "LastBinaryOperator"; + SyntaxKind[SyntaxKind["FirstNode"] = 148] = "FirstNode"; + SyntaxKind[SyntaxKind["FirstJSDocNode"] = 283] = "FirstJSDocNode"; + SyntaxKind[SyntaxKind["LastJSDocNode"] = 305] = "LastJSDocNode"; + SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 294] = "FirstJSDocTagNode"; + SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 305] = "LastJSDocTagNode"; + /* @internal */ SyntaxKind[SyntaxKind["FirstContextualKeyword"] = 118] = "FirstContextualKeyword"; + /* @internal */ SyntaxKind[SyntaxKind["LastContextualKeyword"] = 147] = "LastContextualKeyword"; + })(SyntaxKind = ts.SyntaxKind || (ts.SyntaxKind = {})); + var NodeFlags; + (function (NodeFlags) { + NodeFlags[NodeFlags["None"] = 0] = "None"; + NodeFlags[NodeFlags["Let"] = 1] = "Let"; + NodeFlags[NodeFlags["Const"] = 2] = "Const"; + NodeFlags[NodeFlags["NestedNamespace"] = 4] = "NestedNamespace"; + NodeFlags[NodeFlags["Synthesized"] = 8] = "Synthesized"; + NodeFlags[NodeFlags["Namespace"] = 16] = "Namespace"; + NodeFlags[NodeFlags["ExportContext"] = 32] = "ExportContext"; + NodeFlags[NodeFlags["ContainsThis"] = 64] = "ContainsThis"; + NodeFlags[NodeFlags["HasImplicitReturn"] = 128] = "HasImplicitReturn"; + NodeFlags[NodeFlags["HasExplicitReturn"] = 256] = "HasExplicitReturn"; + NodeFlags[NodeFlags["GlobalAugmentation"] = 512] = "GlobalAugmentation"; + NodeFlags[NodeFlags["HasAsyncFunctions"] = 1024] = "HasAsyncFunctions"; + NodeFlags[NodeFlags["DisallowInContext"] = 2048] = "DisallowInContext"; + NodeFlags[NodeFlags["YieldContext"] = 4096] = "YieldContext"; + NodeFlags[NodeFlags["DecoratorContext"] = 8192] = "DecoratorContext"; + NodeFlags[NodeFlags["AwaitContext"] = 16384] = "AwaitContext"; + NodeFlags[NodeFlags["ThisNodeHasError"] = 32768] = "ThisNodeHasError"; + NodeFlags[NodeFlags["JavaScriptFile"] = 65536] = "JavaScriptFile"; + NodeFlags[NodeFlags["ThisNodeOrAnySubNodesHasError"] = 131072] = "ThisNodeOrAnySubNodesHasError"; + NodeFlags[NodeFlags["HasAggregatedChildData"] = 262144] = "HasAggregatedChildData"; + // These flags will be set when the parser encounters a dynamic import expression or 'import.meta' to avoid + // walking the tree if the flags are not set. However, these flags are just a approximation + // (hence why it's named "PossiblyContainsDynamicImport") because once set, the flags never get cleared. + // During editing, if a dynamic import is removed, incremental parsing will *NOT* clear this flag. + // This means that the tree will always be traversed during module resolution, or when looking for external module indicators. + // However, the removal operation should not occur often and in the case of the + // removal, it is likely that users will add the import anyway. + // The advantage of this approach is its simplicity. For the case of batch compilation, + // we guarantee that users won't have to pay the price of walking the tree if a dynamic import isn't used. + /* @internal */ NodeFlags[NodeFlags["PossiblyContainsDynamicImport"] = 524288] = "PossiblyContainsDynamicImport"; + /* @internal */ NodeFlags[NodeFlags["PossiblyContainsImportMeta"] = 1048576] = "PossiblyContainsImportMeta"; + NodeFlags[NodeFlags["JSDoc"] = 2097152] = "JSDoc"; + /* @internal */ NodeFlags[NodeFlags["Ambient"] = 4194304] = "Ambient"; + /* @internal */ NodeFlags[NodeFlags["InWithStatement"] = 8388608] = "InWithStatement"; + NodeFlags[NodeFlags["JsonFile"] = 16777216] = "JsonFile"; + NodeFlags[NodeFlags["BlockScoped"] = 3] = "BlockScoped"; + NodeFlags[NodeFlags["ReachabilityCheckFlags"] = 384] = "ReachabilityCheckFlags"; + NodeFlags[NodeFlags["ReachabilityAndEmitFlags"] = 1408] = "ReachabilityAndEmitFlags"; + // Parsing context flags + NodeFlags[NodeFlags["ContextFlags"] = 12679168] = "ContextFlags"; + // Exclude these flags when parsing a Type + NodeFlags[NodeFlags["TypeExcludesFlags"] = 20480] = "TypeExcludesFlags"; + // Represents all flags that are potentially set once and + // never cleared on SourceFiles which get re-used in between incremental parses. + // See the comment above on `PossiblyContainsDynamicImport` and `PossiblyContainsImportMeta`. + /* @internal */ NodeFlags[NodeFlags["PermanentlySetIncrementalFlags"] = 1572864] = "PermanentlySetIncrementalFlags"; + })(NodeFlags = ts.NodeFlags || (ts.NodeFlags = {})); + var ModifierFlags; + (function (ModifierFlags) { + ModifierFlags[ModifierFlags["None"] = 0] = "None"; + ModifierFlags[ModifierFlags["Export"] = 1] = "Export"; + ModifierFlags[ModifierFlags["Ambient"] = 2] = "Ambient"; + ModifierFlags[ModifierFlags["Public"] = 4] = "Public"; + ModifierFlags[ModifierFlags["Private"] = 8] = "Private"; + ModifierFlags[ModifierFlags["Protected"] = 16] = "Protected"; + ModifierFlags[ModifierFlags["Static"] = 32] = "Static"; + ModifierFlags[ModifierFlags["Readonly"] = 64] = "Readonly"; + ModifierFlags[ModifierFlags["Abstract"] = 128] = "Abstract"; + ModifierFlags[ModifierFlags["Async"] = 256] = "Async"; + ModifierFlags[ModifierFlags["Default"] = 512] = "Default"; + ModifierFlags[ModifierFlags["Const"] = 2048] = "Const"; + ModifierFlags[ModifierFlags["HasComputedFlags"] = 536870912] = "HasComputedFlags"; + ModifierFlags[ModifierFlags["AccessibilityModifier"] = 28] = "AccessibilityModifier"; + // Accessibility modifiers and 'readonly' can be attached to a parameter in a constructor to make it a property. + ModifierFlags[ModifierFlags["ParameterPropertyModifier"] = 92] = "ParameterPropertyModifier"; + ModifierFlags[ModifierFlags["NonPublicAccessibilityModifier"] = 24] = "NonPublicAccessibilityModifier"; + ModifierFlags[ModifierFlags["TypeScriptModifier"] = 2270] = "TypeScriptModifier"; + ModifierFlags[ModifierFlags["ExportDefault"] = 513] = "ExportDefault"; + ModifierFlags[ModifierFlags["All"] = 3071] = "All"; + })(ModifierFlags = ts.ModifierFlags || (ts.ModifierFlags = {})); + var JsxFlags; + (function (JsxFlags) { + JsxFlags[JsxFlags["None"] = 0] = "None"; + /** An element from a named property of the JSX.IntrinsicElements interface */ + JsxFlags[JsxFlags["IntrinsicNamedElement"] = 1] = "IntrinsicNamedElement"; + /** An element inferred from the string index signature of the JSX.IntrinsicElements interface */ + JsxFlags[JsxFlags["IntrinsicIndexedElement"] = 2] = "IntrinsicIndexedElement"; + JsxFlags[JsxFlags["IntrinsicElement"] = 3] = "IntrinsicElement"; + })(JsxFlags = ts.JsxFlags || (ts.JsxFlags = {})); + /* @internal */ + var RelationComparisonResult; + (function (RelationComparisonResult) { + RelationComparisonResult[RelationComparisonResult["Succeeded"] = 1] = "Succeeded"; + RelationComparisonResult[RelationComparisonResult["Failed"] = 2] = "Failed"; + RelationComparisonResult[RelationComparisonResult["FailedAndReported"] = 3] = "FailedAndReported"; + })(RelationComparisonResult = ts.RelationComparisonResult || (ts.RelationComparisonResult = {})); + /*@internal*/ + var GeneratedIdentifierFlags; + (function (GeneratedIdentifierFlags) { + // Kinds + GeneratedIdentifierFlags[GeneratedIdentifierFlags["None"] = 0] = "None"; + GeneratedIdentifierFlags[GeneratedIdentifierFlags["Auto"] = 1] = "Auto"; + GeneratedIdentifierFlags[GeneratedIdentifierFlags["Loop"] = 2] = "Loop"; + GeneratedIdentifierFlags[GeneratedIdentifierFlags["Unique"] = 3] = "Unique"; + GeneratedIdentifierFlags[GeneratedIdentifierFlags["Node"] = 4] = "Node"; + GeneratedIdentifierFlags[GeneratedIdentifierFlags["KindMask"] = 7] = "KindMask"; + // Flags + GeneratedIdentifierFlags[GeneratedIdentifierFlags["ReservedInNestedScopes"] = 8] = "ReservedInNestedScopes"; + GeneratedIdentifierFlags[GeneratedIdentifierFlags["Optimistic"] = 16] = "Optimistic"; + GeneratedIdentifierFlags[GeneratedIdentifierFlags["FileLevel"] = 32] = "FileLevel"; + })(GeneratedIdentifierFlags = ts.GeneratedIdentifierFlags || (ts.GeneratedIdentifierFlags = {})); + /* @internal */ + var TokenFlags; + (function (TokenFlags) { + TokenFlags[TokenFlags["None"] = 0] = "None"; + TokenFlags[TokenFlags["PrecedingLineBreak"] = 1] = "PrecedingLineBreak"; + TokenFlags[TokenFlags["PrecedingJSDocComment"] = 2] = "PrecedingJSDocComment"; + TokenFlags[TokenFlags["Unterminated"] = 4] = "Unterminated"; + TokenFlags[TokenFlags["ExtendedUnicodeEscape"] = 8] = "ExtendedUnicodeEscape"; + TokenFlags[TokenFlags["Scientific"] = 16] = "Scientific"; + TokenFlags[TokenFlags["Octal"] = 32] = "Octal"; + TokenFlags[TokenFlags["HexSpecifier"] = 64] = "HexSpecifier"; + TokenFlags[TokenFlags["BinarySpecifier"] = 128] = "BinarySpecifier"; + TokenFlags[TokenFlags["OctalSpecifier"] = 256] = "OctalSpecifier"; + TokenFlags[TokenFlags["ContainsSeparator"] = 512] = "ContainsSeparator"; + TokenFlags[TokenFlags["BinaryOrOctalSpecifier"] = 384] = "BinaryOrOctalSpecifier"; + TokenFlags[TokenFlags["NumericLiteralFlags"] = 1008] = "NumericLiteralFlags"; + })(TokenFlags = ts.TokenFlags || (ts.TokenFlags = {})); + var FlowFlags; + (function (FlowFlags) { + FlowFlags[FlowFlags["Unreachable"] = 1] = "Unreachable"; + FlowFlags[FlowFlags["Start"] = 2] = "Start"; + FlowFlags[FlowFlags["BranchLabel"] = 4] = "BranchLabel"; + FlowFlags[FlowFlags["LoopLabel"] = 8] = "LoopLabel"; + FlowFlags[FlowFlags["Assignment"] = 16] = "Assignment"; + FlowFlags[FlowFlags["TrueCondition"] = 32] = "TrueCondition"; + FlowFlags[FlowFlags["FalseCondition"] = 64] = "FalseCondition"; + FlowFlags[FlowFlags["SwitchClause"] = 128] = "SwitchClause"; + FlowFlags[FlowFlags["ArrayMutation"] = 256] = "ArrayMutation"; + FlowFlags[FlowFlags["Referenced"] = 512] = "Referenced"; + FlowFlags[FlowFlags["Shared"] = 1024] = "Shared"; + FlowFlags[FlowFlags["PreFinally"] = 2048] = "PreFinally"; + FlowFlags[FlowFlags["AfterFinally"] = 4096] = "AfterFinally"; + FlowFlags[FlowFlags["Label"] = 12] = "Label"; + FlowFlags[FlowFlags["Condition"] = 96] = "Condition"; + })(FlowFlags = ts.FlowFlags || (ts.FlowFlags = {})); + var OperationCanceledException = /** @class */ (function () { + function OperationCanceledException() { + } + return OperationCanceledException; + }()); + ts.OperationCanceledException = OperationCanceledException; + /* @internal */ + var StructureIsReused; + (function (StructureIsReused) { + StructureIsReused[StructureIsReused["Not"] = 0] = "Not"; + StructureIsReused[StructureIsReused["SafeModules"] = 1] = "SafeModules"; + StructureIsReused[StructureIsReused["Completely"] = 2] = "Completely"; + })(StructureIsReused = ts.StructureIsReused || (ts.StructureIsReused = {})); + /** Return code used by getEmitOutput function to indicate status of the function */ + var ExitStatus; + (function (ExitStatus) { + // Compiler ran successfully. Either this was a simple do-nothing compilation (for example, + // when -version or -help was provided, or this was a normal compilation, no diagnostics + // were produced, and all outputs were generated successfully. + ExitStatus[ExitStatus["Success"] = 0] = "Success"; + // Diagnostics were produced and because of them no code was generated. + ExitStatus[ExitStatus["DiagnosticsPresent_OutputsSkipped"] = 1] = "DiagnosticsPresent_OutputsSkipped"; + // Diagnostics were produced and outputs were generated in spite of them. + ExitStatus[ExitStatus["DiagnosticsPresent_OutputsGenerated"] = 2] = "DiagnosticsPresent_OutputsGenerated"; + })(ExitStatus = ts.ExitStatus || (ts.ExitStatus = {})); + /* @internal */ + var UnionReduction; + (function (UnionReduction) { + UnionReduction[UnionReduction["None"] = 0] = "None"; + UnionReduction[UnionReduction["Literal"] = 1] = "Literal"; + UnionReduction[UnionReduction["Subtype"] = 2] = "Subtype"; + })(UnionReduction = ts.UnionReduction || (ts.UnionReduction = {})); + // NOTE: If modifying this enum, must modify `TypeFormatFlags` too! + var NodeBuilderFlags; + (function (NodeBuilderFlags) { + NodeBuilderFlags[NodeBuilderFlags["None"] = 0] = "None"; + // Options + NodeBuilderFlags[NodeBuilderFlags["NoTruncation"] = 1] = "NoTruncation"; + NodeBuilderFlags[NodeBuilderFlags["WriteArrayAsGenericType"] = 2] = "WriteArrayAsGenericType"; + NodeBuilderFlags[NodeBuilderFlags["GenerateNamesForShadowedTypeParams"] = 4] = "GenerateNamesForShadowedTypeParams"; + NodeBuilderFlags[NodeBuilderFlags["UseStructuralFallback"] = 8] = "UseStructuralFallback"; + NodeBuilderFlags[NodeBuilderFlags["ForbidIndexedAccessSymbolReferences"] = 16] = "ForbidIndexedAccessSymbolReferences"; + NodeBuilderFlags[NodeBuilderFlags["WriteTypeArgumentsOfSignature"] = 32] = "WriteTypeArgumentsOfSignature"; + NodeBuilderFlags[NodeBuilderFlags["UseFullyQualifiedType"] = 64] = "UseFullyQualifiedType"; + NodeBuilderFlags[NodeBuilderFlags["UseOnlyExternalAliasing"] = 128] = "UseOnlyExternalAliasing"; + NodeBuilderFlags[NodeBuilderFlags["SuppressAnyReturnType"] = 256] = "SuppressAnyReturnType"; + NodeBuilderFlags[NodeBuilderFlags["WriteTypeParametersInQualifiedName"] = 512] = "WriteTypeParametersInQualifiedName"; + NodeBuilderFlags[NodeBuilderFlags["MultilineObjectLiterals"] = 1024] = "MultilineObjectLiterals"; + NodeBuilderFlags[NodeBuilderFlags["WriteClassExpressionAsTypeLiteral"] = 2048] = "WriteClassExpressionAsTypeLiteral"; + NodeBuilderFlags[NodeBuilderFlags["UseTypeOfFunction"] = 4096] = "UseTypeOfFunction"; + NodeBuilderFlags[NodeBuilderFlags["OmitParameterModifiers"] = 8192] = "OmitParameterModifiers"; + NodeBuilderFlags[NodeBuilderFlags["UseAliasDefinedOutsideCurrentScope"] = 16384] = "UseAliasDefinedOutsideCurrentScope"; + // Error handling + NodeBuilderFlags[NodeBuilderFlags["AllowThisInObjectLiteral"] = 32768] = "AllowThisInObjectLiteral"; + NodeBuilderFlags[NodeBuilderFlags["AllowQualifedNameInPlaceOfIdentifier"] = 65536] = "AllowQualifedNameInPlaceOfIdentifier"; + NodeBuilderFlags[NodeBuilderFlags["AllowAnonymousIdentifier"] = 131072] = "AllowAnonymousIdentifier"; + NodeBuilderFlags[NodeBuilderFlags["AllowEmptyUnionOrIntersection"] = 262144] = "AllowEmptyUnionOrIntersection"; + NodeBuilderFlags[NodeBuilderFlags["AllowEmptyTuple"] = 524288] = "AllowEmptyTuple"; + NodeBuilderFlags[NodeBuilderFlags["AllowUniqueESSymbolType"] = 1048576] = "AllowUniqueESSymbolType"; + NodeBuilderFlags[NodeBuilderFlags["AllowEmptyIndexInfoType"] = 2097152] = "AllowEmptyIndexInfoType"; + // Errors (cont.) + NodeBuilderFlags[NodeBuilderFlags["AllowNodeModulesRelativePaths"] = 67108864] = "AllowNodeModulesRelativePaths"; + /* @internal */ NodeBuilderFlags[NodeBuilderFlags["DoNotIncludeSymbolChain"] = 134217728] = "DoNotIncludeSymbolChain"; + NodeBuilderFlags[NodeBuilderFlags["IgnoreErrors"] = 70221824] = "IgnoreErrors"; + // State + NodeBuilderFlags[NodeBuilderFlags["InObjectTypeLiteral"] = 4194304] = "InObjectTypeLiteral"; + NodeBuilderFlags[NodeBuilderFlags["InTypeAlias"] = 8388608] = "InTypeAlias"; + NodeBuilderFlags[NodeBuilderFlags["InInitialEntityName"] = 16777216] = "InInitialEntityName"; + NodeBuilderFlags[NodeBuilderFlags["InReverseMappedType"] = 33554432] = "InReverseMappedType"; + })(NodeBuilderFlags = ts.NodeBuilderFlags || (ts.NodeBuilderFlags = {})); + // Ensure the shared flags between this and `NodeBuilderFlags` stay in alignment + var TypeFormatFlags; + (function (TypeFormatFlags) { + TypeFormatFlags[TypeFormatFlags["None"] = 0] = "None"; + TypeFormatFlags[TypeFormatFlags["NoTruncation"] = 1] = "NoTruncation"; + TypeFormatFlags[TypeFormatFlags["WriteArrayAsGenericType"] = 2] = "WriteArrayAsGenericType"; + // hole because there's a hole in node builder flags + TypeFormatFlags[TypeFormatFlags["UseStructuralFallback"] = 8] = "UseStructuralFallback"; + // hole because there's a hole in node builder flags + TypeFormatFlags[TypeFormatFlags["WriteTypeArgumentsOfSignature"] = 32] = "WriteTypeArgumentsOfSignature"; + TypeFormatFlags[TypeFormatFlags["UseFullyQualifiedType"] = 64] = "UseFullyQualifiedType"; + // hole because `UseOnlyExternalAliasing` is here in node builder flags, but functions which take old flags use `SymbolFormatFlags` instead + TypeFormatFlags[TypeFormatFlags["SuppressAnyReturnType"] = 256] = "SuppressAnyReturnType"; + // hole because `WriteTypeParametersInQualifiedName` is here in node builder flags, but functions which take old flags use `SymbolFormatFlags` for this instead + TypeFormatFlags[TypeFormatFlags["MultilineObjectLiterals"] = 1024] = "MultilineObjectLiterals"; + TypeFormatFlags[TypeFormatFlags["WriteClassExpressionAsTypeLiteral"] = 2048] = "WriteClassExpressionAsTypeLiteral"; + TypeFormatFlags[TypeFormatFlags["UseTypeOfFunction"] = 4096] = "UseTypeOfFunction"; + TypeFormatFlags[TypeFormatFlags["OmitParameterModifiers"] = 8192] = "OmitParameterModifiers"; + TypeFormatFlags[TypeFormatFlags["UseAliasDefinedOutsideCurrentScope"] = 16384] = "UseAliasDefinedOutsideCurrentScope"; + // even though `T` can't be accessed in the current scope. + // Error Handling + TypeFormatFlags[TypeFormatFlags["AllowUniqueESSymbolType"] = 1048576] = "AllowUniqueESSymbolType"; + // TypeFormatFlags exclusive + TypeFormatFlags[TypeFormatFlags["AddUndefined"] = 131072] = "AddUndefined"; + TypeFormatFlags[TypeFormatFlags["WriteArrowStyleSignature"] = 262144] = "WriteArrowStyleSignature"; + // State + TypeFormatFlags[TypeFormatFlags["InArrayType"] = 524288] = "InArrayType"; + TypeFormatFlags[TypeFormatFlags["InElementType"] = 2097152] = "InElementType"; + TypeFormatFlags[TypeFormatFlags["InFirstTypeArgument"] = 4194304] = "InFirstTypeArgument"; + TypeFormatFlags[TypeFormatFlags["InTypeAlias"] = 8388608] = "InTypeAlias"; + /** @deprecated */ TypeFormatFlags[TypeFormatFlags["WriteOwnNameForAnyLike"] = 0] = "WriteOwnNameForAnyLike"; + TypeFormatFlags[TypeFormatFlags["NodeBuilderFlagsMask"] = 9469291] = "NodeBuilderFlagsMask"; + })(TypeFormatFlags = ts.TypeFormatFlags || (ts.TypeFormatFlags = {})); + var SymbolFormatFlags; + (function (SymbolFormatFlags) { + SymbolFormatFlags[SymbolFormatFlags["None"] = 0] = "None"; + // Write symbols's type argument if it is instantiated symbol + // eg. class C { p: T } <-- Show p as C.p here + // var a: C; + // var p = a.p; <--- Here p is property of C so show it as C.p instead of just C.p + SymbolFormatFlags[SymbolFormatFlags["WriteTypeParametersOrArguments"] = 1] = "WriteTypeParametersOrArguments"; + // Use only external alias information to get the symbol name in the given context + // eg. module m { export class c { } } import x = m.c; + // When this flag is specified m.c will be used to refer to the class instead of alias symbol x + SymbolFormatFlags[SymbolFormatFlags["UseOnlyExternalAliasing"] = 2] = "UseOnlyExternalAliasing"; + // Build symbol name using any nodes needed, instead of just components of an entity name + SymbolFormatFlags[SymbolFormatFlags["AllowAnyNodeKind"] = 4] = "AllowAnyNodeKind"; + // Prefer aliases which are not directly visible + SymbolFormatFlags[SymbolFormatFlags["UseAliasDefinedOutsideCurrentScope"] = 8] = "UseAliasDefinedOutsideCurrentScope"; + // Skip building an accessible symbol chain + /* @internal */ SymbolFormatFlags[SymbolFormatFlags["DoNotIncludeSymbolChain"] = 16] = "DoNotIncludeSymbolChain"; + })(SymbolFormatFlags = ts.SymbolFormatFlags || (ts.SymbolFormatFlags = {})); + /* @internal */ + var SymbolAccessibility; + (function (SymbolAccessibility) { + SymbolAccessibility[SymbolAccessibility["Accessible"] = 0] = "Accessible"; + SymbolAccessibility[SymbolAccessibility["NotAccessible"] = 1] = "NotAccessible"; + SymbolAccessibility[SymbolAccessibility["CannotBeNamed"] = 2] = "CannotBeNamed"; + })(SymbolAccessibility = ts.SymbolAccessibility || (ts.SymbolAccessibility = {})); + /* @internal */ + var SyntheticSymbolKind; + (function (SyntheticSymbolKind) { + SyntheticSymbolKind[SyntheticSymbolKind["UnionOrIntersection"] = 0] = "UnionOrIntersection"; + SyntheticSymbolKind[SyntheticSymbolKind["Spread"] = 1] = "Spread"; + })(SyntheticSymbolKind = ts.SyntheticSymbolKind || (ts.SyntheticSymbolKind = {})); + var TypePredicateKind; + (function (TypePredicateKind) { + TypePredicateKind[TypePredicateKind["This"] = 0] = "This"; + TypePredicateKind[TypePredicateKind["Identifier"] = 1] = "Identifier"; + })(TypePredicateKind = ts.TypePredicateKind || (ts.TypePredicateKind = {})); + /** Indicates how to serialize the name for a TypeReferenceNode when emitting decorator metadata */ + /* @internal */ + var TypeReferenceSerializationKind; + (function (TypeReferenceSerializationKind) { + TypeReferenceSerializationKind[TypeReferenceSerializationKind["Unknown"] = 0] = "Unknown"; + // should be emitted using a safe fallback. + TypeReferenceSerializationKind[TypeReferenceSerializationKind["TypeWithConstructSignatureAndValue"] = 1] = "TypeWithConstructSignatureAndValue"; + // function that can be reached at runtime (e.g. a `class` + // declaration or a `var` declaration for the static side + // of a type, such as the global `Promise` type in lib.d.ts). + TypeReferenceSerializationKind[TypeReferenceSerializationKind["VoidNullableOrNeverType"] = 2] = "VoidNullableOrNeverType"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["NumberLikeType"] = 3] = "NumberLikeType"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["BigIntLikeType"] = 4] = "BigIntLikeType"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["StringLikeType"] = 5] = "StringLikeType"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["BooleanType"] = 6] = "BooleanType"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["ArrayLikeType"] = 7] = "ArrayLikeType"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["ESSymbolType"] = 8] = "ESSymbolType"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["Promise"] = 9] = "Promise"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["TypeWithCallSignature"] = 10] = "TypeWithCallSignature"; + // with call signatures. + TypeReferenceSerializationKind[TypeReferenceSerializationKind["ObjectType"] = 11] = "ObjectType"; + })(TypeReferenceSerializationKind = ts.TypeReferenceSerializationKind || (ts.TypeReferenceSerializationKind = {})); + var SymbolFlags; + (function (SymbolFlags) { + SymbolFlags[SymbolFlags["None"] = 0] = "None"; + SymbolFlags[SymbolFlags["FunctionScopedVariable"] = 1] = "FunctionScopedVariable"; + SymbolFlags[SymbolFlags["BlockScopedVariable"] = 2] = "BlockScopedVariable"; + SymbolFlags[SymbolFlags["Property"] = 4] = "Property"; + SymbolFlags[SymbolFlags["EnumMember"] = 8] = "EnumMember"; + SymbolFlags[SymbolFlags["Function"] = 16] = "Function"; + SymbolFlags[SymbolFlags["Class"] = 32] = "Class"; + SymbolFlags[SymbolFlags["Interface"] = 64] = "Interface"; + SymbolFlags[SymbolFlags["ConstEnum"] = 128] = "ConstEnum"; + SymbolFlags[SymbolFlags["RegularEnum"] = 256] = "RegularEnum"; + SymbolFlags[SymbolFlags["ValueModule"] = 512] = "ValueModule"; + SymbolFlags[SymbolFlags["NamespaceModule"] = 1024] = "NamespaceModule"; + SymbolFlags[SymbolFlags["TypeLiteral"] = 2048] = "TypeLiteral"; + SymbolFlags[SymbolFlags["ObjectLiteral"] = 4096] = "ObjectLiteral"; + SymbolFlags[SymbolFlags["Method"] = 8192] = "Method"; + SymbolFlags[SymbolFlags["Constructor"] = 16384] = "Constructor"; + SymbolFlags[SymbolFlags["GetAccessor"] = 32768] = "GetAccessor"; + SymbolFlags[SymbolFlags["SetAccessor"] = 65536] = "SetAccessor"; + SymbolFlags[SymbolFlags["Signature"] = 131072] = "Signature"; + SymbolFlags[SymbolFlags["TypeParameter"] = 262144] = "TypeParameter"; + SymbolFlags[SymbolFlags["TypeAlias"] = 524288] = "TypeAlias"; + SymbolFlags[SymbolFlags["ExportValue"] = 1048576] = "ExportValue"; + SymbolFlags[SymbolFlags["Alias"] = 2097152] = "Alias"; + SymbolFlags[SymbolFlags["Prototype"] = 4194304] = "Prototype"; + SymbolFlags[SymbolFlags["ExportStar"] = 8388608] = "ExportStar"; + SymbolFlags[SymbolFlags["Optional"] = 16777216] = "Optional"; + SymbolFlags[SymbolFlags["Transient"] = 33554432] = "Transient"; + SymbolFlags[SymbolFlags["Assignment"] = 67108864] = "Assignment"; + SymbolFlags[SymbolFlags["ModuleExports"] = 134217728] = "ModuleExports"; + /* @internal */ + SymbolFlags[SymbolFlags["All"] = 67108863] = "All"; + SymbolFlags[SymbolFlags["Enum"] = 384] = "Enum"; + SymbolFlags[SymbolFlags["Variable"] = 3] = "Variable"; + SymbolFlags[SymbolFlags["Value"] = 67220415] = "Value"; + SymbolFlags[SymbolFlags["Type"] = 67897832] = "Type"; + SymbolFlags[SymbolFlags["Namespace"] = 1920] = "Namespace"; + SymbolFlags[SymbolFlags["Module"] = 1536] = "Module"; + SymbolFlags[SymbolFlags["Accessor"] = 98304] = "Accessor"; + // Variables can be redeclared, but can not redeclare a block-scoped declaration with the + // same name, or any other value that is not a variable, e.g. ValueModule or Class + SymbolFlags[SymbolFlags["FunctionScopedVariableExcludes"] = 67220414] = "FunctionScopedVariableExcludes"; + // Block-scoped declarations are not allowed to be re-declared + // they can not merge with anything in the value space + SymbolFlags[SymbolFlags["BlockScopedVariableExcludes"] = 67220415] = "BlockScopedVariableExcludes"; + SymbolFlags[SymbolFlags["ParameterExcludes"] = 67220415] = "ParameterExcludes"; + SymbolFlags[SymbolFlags["PropertyExcludes"] = 0] = "PropertyExcludes"; + SymbolFlags[SymbolFlags["EnumMemberExcludes"] = 68008959] = "EnumMemberExcludes"; + SymbolFlags[SymbolFlags["FunctionExcludes"] = 67219887] = "FunctionExcludes"; + SymbolFlags[SymbolFlags["ClassExcludes"] = 68008383] = "ClassExcludes"; + SymbolFlags[SymbolFlags["InterfaceExcludes"] = 67897736] = "InterfaceExcludes"; + SymbolFlags[SymbolFlags["RegularEnumExcludes"] = 68008191] = "RegularEnumExcludes"; + SymbolFlags[SymbolFlags["ConstEnumExcludes"] = 68008831] = "ConstEnumExcludes"; + SymbolFlags[SymbolFlags["ValueModuleExcludes"] = 110735] = "ValueModuleExcludes"; + SymbolFlags[SymbolFlags["NamespaceModuleExcludes"] = 0] = "NamespaceModuleExcludes"; + SymbolFlags[SymbolFlags["MethodExcludes"] = 67212223] = "MethodExcludes"; + SymbolFlags[SymbolFlags["GetAccessorExcludes"] = 67154879] = "GetAccessorExcludes"; + SymbolFlags[SymbolFlags["SetAccessorExcludes"] = 67187647] = "SetAccessorExcludes"; + SymbolFlags[SymbolFlags["TypeParameterExcludes"] = 67635688] = "TypeParameterExcludes"; + SymbolFlags[SymbolFlags["TypeAliasExcludes"] = 67897832] = "TypeAliasExcludes"; + SymbolFlags[SymbolFlags["AliasExcludes"] = 2097152] = "AliasExcludes"; + SymbolFlags[SymbolFlags["ModuleMember"] = 2623475] = "ModuleMember"; + SymbolFlags[SymbolFlags["ExportHasLocal"] = 944] = "ExportHasLocal"; + SymbolFlags[SymbolFlags["BlockScoped"] = 418] = "BlockScoped"; + SymbolFlags[SymbolFlags["PropertyOrAccessor"] = 98308] = "PropertyOrAccessor"; + SymbolFlags[SymbolFlags["ClassMember"] = 106500] = "ClassMember"; + /* @internal */ + // The set of things we consider semantically classifiable. Used to speed up the LS during + // classification. + SymbolFlags[SymbolFlags["Classifiable"] = 2885600] = "Classifiable"; + /* @internal */ + SymbolFlags[SymbolFlags["LateBindingContainer"] = 6240] = "LateBindingContainer"; + })(SymbolFlags = ts.SymbolFlags || (ts.SymbolFlags = {})); + /* @internal */ + var EnumKind; + (function (EnumKind) { + EnumKind[EnumKind["Numeric"] = 0] = "Numeric"; + EnumKind[EnumKind["Literal"] = 1] = "Literal"; // Literal enum (each member has a TypeFlags.EnumLiteral type) + })(EnumKind = ts.EnumKind || (ts.EnumKind = {})); + /* @internal */ + var CheckFlags; + (function (CheckFlags) { + CheckFlags[CheckFlags["Instantiated"] = 1] = "Instantiated"; + CheckFlags[CheckFlags["SyntheticProperty"] = 2] = "SyntheticProperty"; + CheckFlags[CheckFlags["SyntheticMethod"] = 4] = "SyntheticMethod"; + CheckFlags[CheckFlags["Readonly"] = 8] = "Readonly"; + CheckFlags[CheckFlags["Partial"] = 16] = "Partial"; + CheckFlags[CheckFlags["HasNonUniformType"] = 32] = "HasNonUniformType"; + CheckFlags[CheckFlags["ContainsPublic"] = 64] = "ContainsPublic"; + CheckFlags[CheckFlags["ContainsProtected"] = 128] = "ContainsProtected"; + CheckFlags[CheckFlags["ContainsPrivate"] = 256] = "ContainsPrivate"; + CheckFlags[CheckFlags["ContainsStatic"] = 512] = "ContainsStatic"; + CheckFlags[CheckFlags["Late"] = 1024] = "Late"; + CheckFlags[CheckFlags["ReverseMapped"] = 2048] = "ReverseMapped"; + CheckFlags[CheckFlags["OptionalParameter"] = 4096] = "OptionalParameter"; + CheckFlags[CheckFlags["RestParameter"] = 8192] = "RestParameter"; + CheckFlags[CheckFlags["Synthetic"] = 6] = "Synthetic"; + })(CheckFlags = ts.CheckFlags || (ts.CheckFlags = {})); + var InternalSymbolName; + (function (InternalSymbolName) { + InternalSymbolName["Call"] = "__call"; + InternalSymbolName["Constructor"] = "__constructor"; + InternalSymbolName["New"] = "__new"; + InternalSymbolName["Index"] = "__index"; + InternalSymbolName["ExportStar"] = "__export"; + InternalSymbolName["Global"] = "__global"; + InternalSymbolName["Missing"] = "__missing"; + InternalSymbolName["Type"] = "__type"; + InternalSymbolName["Object"] = "__object"; + InternalSymbolName["JSXAttributes"] = "__jsxAttributes"; + InternalSymbolName["Class"] = "__class"; + InternalSymbolName["Function"] = "__function"; + InternalSymbolName["Computed"] = "__computed"; + InternalSymbolName["Resolving"] = "__resolving__"; + InternalSymbolName["ExportEquals"] = "export="; + InternalSymbolName["Default"] = "default"; + InternalSymbolName["This"] = "this"; + })(InternalSymbolName = ts.InternalSymbolName || (ts.InternalSymbolName = {})); + /* @internal */ + var NodeCheckFlags; + (function (NodeCheckFlags) { + NodeCheckFlags[NodeCheckFlags["TypeChecked"] = 1] = "TypeChecked"; + NodeCheckFlags[NodeCheckFlags["LexicalThis"] = 2] = "LexicalThis"; + NodeCheckFlags[NodeCheckFlags["CaptureThis"] = 4] = "CaptureThis"; + NodeCheckFlags[NodeCheckFlags["CaptureNewTarget"] = 8] = "CaptureNewTarget"; + NodeCheckFlags[NodeCheckFlags["SuperInstance"] = 256] = "SuperInstance"; + NodeCheckFlags[NodeCheckFlags["SuperStatic"] = 512] = "SuperStatic"; + NodeCheckFlags[NodeCheckFlags["ContextChecked"] = 1024] = "ContextChecked"; + NodeCheckFlags[NodeCheckFlags["AsyncMethodWithSuper"] = 2048] = "AsyncMethodWithSuper"; + NodeCheckFlags[NodeCheckFlags["AsyncMethodWithSuperBinding"] = 4096] = "AsyncMethodWithSuperBinding"; + NodeCheckFlags[NodeCheckFlags["CaptureArguments"] = 8192] = "CaptureArguments"; + NodeCheckFlags[NodeCheckFlags["EnumValuesComputed"] = 16384] = "EnumValuesComputed"; + NodeCheckFlags[NodeCheckFlags["LexicalModuleMergesWithClass"] = 32768] = "LexicalModuleMergesWithClass"; + NodeCheckFlags[NodeCheckFlags["LoopWithCapturedBlockScopedBinding"] = 65536] = "LoopWithCapturedBlockScopedBinding"; + NodeCheckFlags[NodeCheckFlags["ContainsCapturedBlockScopeBinding"] = 131072] = "ContainsCapturedBlockScopeBinding"; + NodeCheckFlags[NodeCheckFlags["CapturedBlockScopedBinding"] = 262144] = "CapturedBlockScopedBinding"; + NodeCheckFlags[NodeCheckFlags["BlockScopedBindingInLoop"] = 524288] = "BlockScopedBindingInLoop"; + NodeCheckFlags[NodeCheckFlags["ClassWithBodyScopedClassBinding"] = 1048576] = "ClassWithBodyScopedClassBinding"; + NodeCheckFlags[NodeCheckFlags["BodyScopedClassBinding"] = 2097152] = "BodyScopedClassBinding"; + NodeCheckFlags[NodeCheckFlags["NeedsLoopOutParameter"] = 4194304] = "NeedsLoopOutParameter"; + NodeCheckFlags[NodeCheckFlags["AssignmentsMarked"] = 8388608] = "AssignmentsMarked"; + NodeCheckFlags[NodeCheckFlags["ClassWithConstructorReference"] = 16777216] = "ClassWithConstructorReference"; + NodeCheckFlags[NodeCheckFlags["ConstructorReferenceInClass"] = 33554432] = "ConstructorReferenceInClass"; + })(NodeCheckFlags = ts.NodeCheckFlags || (ts.NodeCheckFlags = {})); + var TypeFlags; + (function (TypeFlags) { + TypeFlags[TypeFlags["Any"] = 1] = "Any"; + TypeFlags[TypeFlags["Unknown"] = 2] = "Unknown"; + TypeFlags[TypeFlags["String"] = 4] = "String"; + TypeFlags[TypeFlags["Number"] = 8] = "Number"; + TypeFlags[TypeFlags["Boolean"] = 16] = "Boolean"; + TypeFlags[TypeFlags["Enum"] = 32] = "Enum"; + TypeFlags[TypeFlags["BigInt"] = 64] = "BigInt"; + TypeFlags[TypeFlags["StringLiteral"] = 128] = "StringLiteral"; + TypeFlags[TypeFlags["NumberLiteral"] = 256] = "NumberLiteral"; + TypeFlags[TypeFlags["BooleanLiteral"] = 512] = "BooleanLiteral"; + TypeFlags[TypeFlags["EnumLiteral"] = 1024] = "EnumLiteral"; + TypeFlags[TypeFlags["BigIntLiteral"] = 2048] = "BigIntLiteral"; + TypeFlags[TypeFlags["ESSymbol"] = 4096] = "ESSymbol"; + TypeFlags[TypeFlags["UniqueESSymbol"] = 8192] = "UniqueESSymbol"; + TypeFlags[TypeFlags["Void"] = 16384] = "Void"; + TypeFlags[TypeFlags["Undefined"] = 32768] = "Undefined"; + TypeFlags[TypeFlags["Null"] = 65536] = "Null"; + TypeFlags[TypeFlags["Never"] = 131072] = "Never"; + TypeFlags[TypeFlags["TypeParameter"] = 262144] = "TypeParameter"; + TypeFlags[TypeFlags["Object"] = 524288] = "Object"; + TypeFlags[TypeFlags["Union"] = 1048576] = "Union"; + TypeFlags[TypeFlags["Intersection"] = 2097152] = "Intersection"; + TypeFlags[TypeFlags["Index"] = 4194304] = "Index"; + TypeFlags[TypeFlags["IndexedAccess"] = 8388608] = "IndexedAccess"; + TypeFlags[TypeFlags["Conditional"] = 16777216] = "Conditional"; + TypeFlags[TypeFlags["Substitution"] = 33554432] = "Substitution"; + TypeFlags[TypeFlags["NonPrimitive"] = 67108864] = "NonPrimitive"; + /* @internal */ + TypeFlags[TypeFlags["ContainsWideningType"] = 134217728] = "ContainsWideningType"; + /* @internal */ + TypeFlags[TypeFlags["ContainsObjectLiteral"] = 268435456] = "ContainsObjectLiteral"; + /* @internal */ + TypeFlags[TypeFlags["ContainsAnyFunctionType"] = 536870912] = "ContainsAnyFunctionType"; + /* @internal */ + TypeFlags[TypeFlags["AnyOrUnknown"] = 3] = "AnyOrUnknown"; + /* @internal */ + TypeFlags[TypeFlags["Nullable"] = 98304] = "Nullable"; + TypeFlags[TypeFlags["Literal"] = 2944] = "Literal"; + TypeFlags[TypeFlags["Unit"] = 109440] = "Unit"; + TypeFlags[TypeFlags["StringOrNumberLiteral"] = 384] = "StringOrNumberLiteral"; + /* @internal */ + TypeFlags[TypeFlags["StringOrNumberLiteralOrUnique"] = 8576] = "StringOrNumberLiteralOrUnique"; + /* @internal */ + TypeFlags[TypeFlags["DefinitelyFalsy"] = 117632] = "DefinitelyFalsy"; + TypeFlags[TypeFlags["PossiblyFalsy"] = 117724] = "PossiblyFalsy"; + /* @internal */ + TypeFlags[TypeFlags["Intrinsic"] = 67359327] = "Intrinsic"; + /* @internal */ + TypeFlags[TypeFlags["Primitive"] = 131068] = "Primitive"; + TypeFlags[TypeFlags["StringLike"] = 132] = "StringLike"; + TypeFlags[TypeFlags["NumberLike"] = 296] = "NumberLike"; + TypeFlags[TypeFlags["BigIntLike"] = 2112] = "BigIntLike"; + TypeFlags[TypeFlags["BooleanLike"] = 528] = "BooleanLike"; + TypeFlags[TypeFlags["EnumLike"] = 1056] = "EnumLike"; + TypeFlags[TypeFlags["ESSymbolLike"] = 12288] = "ESSymbolLike"; + TypeFlags[TypeFlags["VoidLike"] = 49152] = "VoidLike"; + /* @internal */ + TypeFlags[TypeFlags["DisjointDomains"] = 67238908] = "DisjointDomains"; + TypeFlags[TypeFlags["UnionOrIntersection"] = 3145728] = "UnionOrIntersection"; + TypeFlags[TypeFlags["StructuredType"] = 3670016] = "StructuredType"; + TypeFlags[TypeFlags["TypeVariable"] = 8650752] = "TypeVariable"; + TypeFlags[TypeFlags["InstantiableNonPrimitive"] = 58982400] = "InstantiableNonPrimitive"; + TypeFlags[TypeFlags["InstantiablePrimitive"] = 4194304] = "InstantiablePrimitive"; + TypeFlags[TypeFlags["Instantiable"] = 63176704] = "Instantiable"; + TypeFlags[TypeFlags["StructuredOrInstantiable"] = 66846720] = "StructuredOrInstantiable"; + // 'Narrowable' types are types where narrowing actually narrows. + // This *should* be every type other than null, undefined, void, and never + TypeFlags[TypeFlags["Narrowable"] = 133970943] = "Narrowable"; + TypeFlags[TypeFlags["NotUnionOrUnit"] = 67637251] = "NotUnionOrUnit"; + /* @internal */ + TypeFlags[TypeFlags["NotPrimitiveUnion"] = 66994211] = "NotPrimitiveUnion"; + /* @internal */ + TypeFlags[TypeFlags["RequiresWidening"] = 402653184] = "RequiresWidening"; + /* @internal */ + TypeFlags[TypeFlags["PropagatingFlags"] = 939524096] = "PropagatingFlags"; + // The following flags are used for different purposes during union and intersection type construction + /* @internal */ + TypeFlags[TypeFlags["NonWideningType"] = 134217728] = "NonWideningType"; + /* @internal */ + TypeFlags[TypeFlags["Wildcard"] = 268435456] = "Wildcard"; + /* @internal */ + TypeFlags[TypeFlags["EmptyObject"] = 536870912] = "EmptyObject"; + /* @internal */ + TypeFlags[TypeFlags["ConstructionFlags"] = 939524096] = "ConstructionFlags"; + // The following flag is used for different purposes by maybeTypeOfKind + /* @internal */ + TypeFlags[TypeFlags["GenericMappedType"] = 134217728] = "GenericMappedType"; + })(TypeFlags = ts.TypeFlags || (ts.TypeFlags = {})); + var ObjectFlags; + (function (ObjectFlags) { + ObjectFlags[ObjectFlags["Class"] = 1] = "Class"; + ObjectFlags[ObjectFlags["Interface"] = 2] = "Interface"; + ObjectFlags[ObjectFlags["Reference"] = 4] = "Reference"; + ObjectFlags[ObjectFlags["Tuple"] = 8] = "Tuple"; + ObjectFlags[ObjectFlags["Anonymous"] = 16] = "Anonymous"; + ObjectFlags[ObjectFlags["Mapped"] = 32] = "Mapped"; + ObjectFlags[ObjectFlags["Instantiated"] = 64] = "Instantiated"; + ObjectFlags[ObjectFlags["ObjectLiteral"] = 128] = "ObjectLiteral"; + ObjectFlags[ObjectFlags["EvolvingArray"] = 256] = "EvolvingArray"; + ObjectFlags[ObjectFlags["ObjectLiteralPatternWithComputedProperties"] = 512] = "ObjectLiteralPatternWithComputedProperties"; + ObjectFlags[ObjectFlags["ContainsSpread"] = 1024] = "ContainsSpread"; + ObjectFlags[ObjectFlags["ReverseMapped"] = 2048] = "ReverseMapped"; + ObjectFlags[ObjectFlags["JsxAttributes"] = 4096] = "JsxAttributes"; + ObjectFlags[ObjectFlags["MarkerType"] = 8192] = "MarkerType"; + ObjectFlags[ObjectFlags["JSLiteral"] = 16384] = "JSLiteral"; + ObjectFlags[ObjectFlags["FreshLiteral"] = 32768] = "FreshLiteral"; + ObjectFlags[ObjectFlags["ClassOrInterface"] = 3] = "ClassOrInterface"; + })(ObjectFlags = ts.ObjectFlags || (ts.ObjectFlags = {})); + /* @internal */ + var Variance; + (function (Variance) { + Variance[Variance["Invariant"] = 0] = "Invariant"; + Variance[Variance["Covariant"] = 1] = "Covariant"; + Variance[Variance["Contravariant"] = 2] = "Contravariant"; + Variance[Variance["Bivariant"] = 3] = "Bivariant"; + Variance[Variance["Independent"] = 4] = "Independent"; + })(Variance = ts.Variance || (ts.Variance = {})); + /* @internal */ + var JsxReferenceKind; + (function (JsxReferenceKind) { + JsxReferenceKind[JsxReferenceKind["Component"] = 0] = "Component"; + JsxReferenceKind[JsxReferenceKind["Function"] = 1] = "Function"; + JsxReferenceKind[JsxReferenceKind["Mixed"] = 2] = "Mixed"; + })(JsxReferenceKind = ts.JsxReferenceKind || (ts.JsxReferenceKind = {})); + var SignatureKind; + (function (SignatureKind) { + SignatureKind[SignatureKind["Call"] = 0] = "Call"; + SignatureKind[SignatureKind["Construct"] = 1] = "Construct"; + })(SignatureKind = ts.SignatureKind || (ts.SignatureKind = {})); + var IndexKind; + (function (IndexKind) { + IndexKind[IndexKind["String"] = 0] = "String"; + IndexKind[IndexKind["Number"] = 1] = "Number"; + })(IndexKind = ts.IndexKind || (ts.IndexKind = {})); + var InferencePriority; + (function (InferencePriority) { + InferencePriority[InferencePriority["NakedTypeVariable"] = 1] = "NakedTypeVariable"; + InferencePriority[InferencePriority["HomomorphicMappedType"] = 2] = "HomomorphicMappedType"; + InferencePriority[InferencePriority["MappedTypeConstraint"] = 4] = "MappedTypeConstraint"; + InferencePriority[InferencePriority["ReturnType"] = 8] = "ReturnType"; + InferencePriority[InferencePriority["LiteralKeyof"] = 16] = "LiteralKeyof"; + InferencePriority[InferencePriority["NoConstraints"] = 32] = "NoConstraints"; + InferencePriority[InferencePriority["AlwaysStrict"] = 64] = "AlwaysStrict"; + InferencePriority[InferencePriority["PriorityImpliesCombination"] = 28] = "PriorityImpliesCombination"; + })(InferencePriority = ts.InferencePriority || (ts.InferencePriority = {})); + /* @internal */ + var InferenceFlags; + (function (InferenceFlags) { + InferenceFlags[InferenceFlags["None"] = 0] = "None"; + InferenceFlags[InferenceFlags["NoDefault"] = 1] = "NoDefault"; + InferenceFlags[InferenceFlags["AnyDefault"] = 2] = "AnyDefault"; + })(InferenceFlags = ts.InferenceFlags || (ts.InferenceFlags = {})); + /** + * Ternary values are defined such that + * x & y is False if either x or y is False. + * x & y is Maybe if either x or y is Maybe, but neither x or y is False. + * x & y is True if both x and y are True. + * x | y is False if both x and y are False. + * x | y is Maybe if either x or y is Maybe, but neither x or y is True. + * x | y is True if either x or y is True. + */ + /* @internal */ + var Ternary; + (function (Ternary) { + Ternary[Ternary["False"] = 0] = "False"; + Ternary[Ternary["Maybe"] = 1] = "Maybe"; + Ternary[Ternary["True"] = -1] = "True"; + })(Ternary = ts.Ternary || (ts.Ternary = {})); + /* @internal */ + var AssignmentDeclarationKind; + (function (AssignmentDeclarationKind) { + AssignmentDeclarationKind[AssignmentDeclarationKind["None"] = 0] = "None"; + /// exports.name = expr + AssignmentDeclarationKind[AssignmentDeclarationKind["ExportsProperty"] = 1] = "ExportsProperty"; + /// module.exports = expr + AssignmentDeclarationKind[AssignmentDeclarationKind["ModuleExports"] = 2] = "ModuleExports"; + /// className.prototype.name = expr + AssignmentDeclarationKind[AssignmentDeclarationKind["PrototypeProperty"] = 3] = "PrototypeProperty"; + /// this.name = expr + AssignmentDeclarationKind[AssignmentDeclarationKind["ThisProperty"] = 4] = "ThisProperty"; + // F.name = expr + AssignmentDeclarationKind[AssignmentDeclarationKind["Property"] = 5] = "Property"; + // F.prototype = { ... } + AssignmentDeclarationKind[AssignmentDeclarationKind["Prototype"] = 6] = "Prototype"; + // Object.defineProperty(x, 'name', { value: any, writable?: boolean (false by default) }); + // Object.defineProperty(x, 'name', { get: Function, set: Function }); + // Object.defineProperty(x, 'name', { get: Function }); + // Object.defineProperty(x, 'name', { set: Function }); + AssignmentDeclarationKind[AssignmentDeclarationKind["ObjectDefinePropertyValue"] = 7] = "ObjectDefinePropertyValue"; + // Object.defineProperty(exports || module.exports, 'name', ...); + AssignmentDeclarationKind[AssignmentDeclarationKind["ObjectDefinePropertyExports"] = 8] = "ObjectDefinePropertyExports"; + // Object.defineProperty(Foo.prototype, 'name', ...); + AssignmentDeclarationKind[AssignmentDeclarationKind["ObjectDefinePrototypeProperty"] = 9] = "ObjectDefinePrototypeProperty"; + })(AssignmentDeclarationKind = ts.AssignmentDeclarationKind || (ts.AssignmentDeclarationKind = {})); + var DiagnosticCategory; + (function (DiagnosticCategory) { + DiagnosticCategory[DiagnosticCategory["Warning"] = 0] = "Warning"; + DiagnosticCategory[DiagnosticCategory["Error"] = 1] = "Error"; + DiagnosticCategory[DiagnosticCategory["Suggestion"] = 2] = "Suggestion"; + DiagnosticCategory[DiagnosticCategory["Message"] = 3] = "Message"; + })(DiagnosticCategory = ts.DiagnosticCategory || (ts.DiagnosticCategory = {})); + /* @internal */ + function diagnosticCategoryName(d, lowerCase) { + if (lowerCase === void 0) { lowerCase = true; } + var name = DiagnosticCategory[d.category]; + return lowerCase ? name.toLowerCase() : name; + } + ts.diagnosticCategoryName = diagnosticCategoryName; + var ModuleResolutionKind; + (function (ModuleResolutionKind) { + ModuleResolutionKind[ModuleResolutionKind["Classic"] = 1] = "Classic"; + ModuleResolutionKind[ModuleResolutionKind["NodeJs"] = 2] = "NodeJs"; + })(ModuleResolutionKind = ts.ModuleResolutionKind || (ts.ModuleResolutionKind = {})); + var ModuleKind; + (function (ModuleKind) { + ModuleKind[ModuleKind["None"] = 0] = "None"; + ModuleKind[ModuleKind["CommonJS"] = 1] = "CommonJS"; + ModuleKind[ModuleKind["AMD"] = 2] = "AMD"; + ModuleKind[ModuleKind["UMD"] = 3] = "UMD"; + ModuleKind[ModuleKind["System"] = 4] = "System"; + ModuleKind[ModuleKind["ES2015"] = 5] = "ES2015"; + ModuleKind[ModuleKind["ESNext"] = 6] = "ESNext"; + })(ModuleKind = ts.ModuleKind || (ts.ModuleKind = {})); + var JsxEmit; + (function (JsxEmit) { + JsxEmit[JsxEmit["None"] = 0] = "None"; + JsxEmit[JsxEmit["Preserve"] = 1] = "Preserve"; + JsxEmit[JsxEmit["React"] = 2] = "React"; + JsxEmit[JsxEmit["ReactNative"] = 3] = "ReactNative"; + })(JsxEmit = ts.JsxEmit || (ts.JsxEmit = {})); + var NewLineKind; + (function (NewLineKind) { + NewLineKind[NewLineKind["CarriageReturnLineFeed"] = 0] = "CarriageReturnLineFeed"; + NewLineKind[NewLineKind["LineFeed"] = 1] = "LineFeed"; + })(NewLineKind = ts.NewLineKind || (ts.NewLineKind = {})); + var ScriptKind; + (function (ScriptKind) { + ScriptKind[ScriptKind["Unknown"] = 0] = "Unknown"; + ScriptKind[ScriptKind["JS"] = 1] = "JS"; + ScriptKind[ScriptKind["JSX"] = 2] = "JSX"; + ScriptKind[ScriptKind["TS"] = 3] = "TS"; + ScriptKind[ScriptKind["TSX"] = 4] = "TSX"; + ScriptKind[ScriptKind["External"] = 5] = "External"; + ScriptKind[ScriptKind["JSON"] = 6] = "JSON"; + /** + * Used on extensions that doesn't define the ScriptKind but the content defines it. + * Deferred extensions are going to be included in all project contexts. + */ + ScriptKind[ScriptKind["Deferred"] = 7] = "Deferred"; + })(ScriptKind = ts.ScriptKind || (ts.ScriptKind = {})); + var ScriptTarget; + (function (ScriptTarget) { + ScriptTarget[ScriptTarget["ES3"] = 0] = "ES3"; + ScriptTarget[ScriptTarget["ES5"] = 1] = "ES5"; + ScriptTarget[ScriptTarget["ES2015"] = 2] = "ES2015"; + ScriptTarget[ScriptTarget["ES2016"] = 3] = "ES2016"; + ScriptTarget[ScriptTarget["ES2017"] = 4] = "ES2017"; + ScriptTarget[ScriptTarget["ES2018"] = 5] = "ES2018"; + ScriptTarget[ScriptTarget["ESNext"] = 6] = "ESNext"; + ScriptTarget[ScriptTarget["JSON"] = 100] = "JSON"; + ScriptTarget[ScriptTarget["Latest"] = 6] = "Latest"; + })(ScriptTarget = ts.ScriptTarget || (ts.ScriptTarget = {})); + var LanguageVariant; + (function (LanguageVariant) { + LanguageVariant[LanguageVariant["Standard"] = 0] = "Standard"; + LanguageVariant[LanguageVariant["JSX"] = 1] = "JSX"; + })(LanguageVariant = ts.LanguageVariant || (ts.LanguageVariant = {})); + var WatchDirectoryFlags; + (function (WatchDirectoryFlags) { + WatchDirectoryFlags[WatchDirectoryFlags["None"] = 0] = "None"; + WatchDirectoryFlags[WatchDirectoryFlags["Recursive"] = 1] = "Recursive"; + })(WatchDirectoryFlags = ts.WatchDirectoryFlags || (ts.WatchDirectoryFlags = {})); + /* @internal */ + var CharacterCodes; + (function (CharacterCodes) { + CharacterCodes[CharacterCodes["nullCharacter"] = 0] = "nullCharacter"; + CharacterCodes[CharacterCodes["maxAsciiCharacter"] = 127] = "maxAsciiCharacter"; + CharacterCodes[CharacterCodes["lineFeed"] = 10] = "lineFeed"; + CharacterCodes[CharacterCodes["carriageReturn"] = 13] = "carriageReturn"; + CharacterCodes[CharacterCodes["lineSeparator"] = 8232] = "lineSeparator"; + CharacterCodes[CharacterCodes["paragraphSeparator"] = 8233] = "paragraphSeparator"; + CharacterCodes[CharacterCodes["nextLine"] = 133] = "nextLine"; + // Unicode 3.0 space characters + CharacterCodes[CharacterCodes["space"] = 32] = "space"; + CharacterCodes[CharacterCodes["nonBreakingSpace"] = 160] = "nonBreakingSpace"; + CharacterCodes[CharacterCodes["enQuad"] = 8192] = "enQuad"; + CharacterCodes[CharacterCodes["emQuad"] = 8193] = "emQuad"; + CharacterCodes[CharacterCodes["enSpace"] = 8194] = "enSpace"; + CharacterCodes[CharacterCodes["emSpace"] = 8195] = "emSpace"; + CharacterCodes[CharacterCodes["threePerEmSpace"] = 8196] = "threePerEmSpace"; + CharacterCodes[CharacterCodes["fourPerEmSpace"] = 8197] = "fourPerEmSpace"; + CharacterCodes[CharacterCodes["sixPerEmSpace"] = 8198] = "sixPerEmSpace"; + CharacterCodes[CharacterCodes["figureSpace"] = 8199] = "figureSpace"; + CharacterCodes[CharacterCodes["punctuationSpace"] = 8200] = "punctuationSpace"; + CharacterCodes[CharacterCodes["thinSpace"] = 8201] = "thinSpace"; + CharacterCodes[CharacterCodes["hairSpace"] = 8202] = "hairSpace"; + CharacterCodes[CharacterCodes["zeroWidthSpace"] = 8203] = "zeroWidthSpace"; + CharacterCodes[CharacterCodes["narrowNoBreakSpace"] = 8239] = "narrowNoBreakSpace"; + CharacterCodes[CharacterCodes["ideographicSpace"] = 12288] = "ideographicSpace"; + CharacterCodes[CharacterCodes["mathematicalSpace"] = 8287] = "mathematicalSpace"; + CharacterCodes[CharacterCodes["ogham"] = 5760] = "ogham"; + CharacterCodes[CharacterCodes["_"] = 95] = "_"; + CharacterCodes[CharacterCodes["$"] = 36] = "$"; + CharacterCodes[CharacterCodes["_0"] = 48] = "_0"; + CharacterCodes[CharacterCodes["_1"] = 49] = "_1"; + CharacterCodes[CharacterCodes["_2"] = 50] = "_2"; + CharacterCodes[CharacterCodes["_3"] = 51] = "_3"; + CharacterCodes[CharacterCodes["_4"] = 52] = "_4"; + CharacterCodes[CharacterCodes["_5"] = 53] = "_5"; + CharacterCodes[CharacterCodes["_6"] = 54] = "_6"; + CharacterCodes[CharacterCodes["_7"] = 55] = "_7"; + CharacterCodes[CharacterCodes["_8"] = 56] = "_8"; + CharacterCodes[CharacterCodes["_9"] = 57] = "_9"; + CharacterCodes[CharacterCodes["a"] = 97] = "a"; + CharacterCodes[CharacterCodes["b"] = 98] = "b"; + CharacterCodes[CharacterCodes["c"] = 99] = "c"; + CharacterCodes[CharacterCodes["d"] = 100] = "d"; + CharacterCodes[CharacterCodes["e"] = 101] = "e"; + CharacterCodes[CharacterCodes["f"] = 102] = "f"; + CharacterCodes[CharacterCodes["g"] = 103] = "g"; + CharacterCodes[CharacterCodes["h"] = 104] = "h"; + CharacterCodes[CharacterCodes["i"] = 105] = "i"; + CharacterCodes[CharacterCodes["j"] = 106] = "j"; + CharacterCodes[CharacterCodes["k"] = 107] = "k"; + CharacterCodes[CharacterCodes["l"] = 108] = "l"; + CharacterCodes[CharacterCodes["m"] = 109] = "m"; + CharacterCodes[CharacterCodes["n"] = 110] = "n"; + CharacterCodes[CharacterCodes["o"] = 111] = "o"; + CharacterCodes[CharacterCodes["p"] = 112] = "p"; + CharacterCodes[CharacterCodes["q"] = 113] = "q"; + CharacterCodes[CharacterCodes["r"] = 114] = "r"; + CharacterCodes[CharacterCodes["s"] = 115] = "s"; + CharacterCodes[CharacterCodes["t"] = 116] = "t"; + CharacterCodes[CharacterCodes["u"] = 117] = "u"; + CharacterCodes[CharacterCodes["v"] = 118] = "v"; + CharacterCodes[CharacterCodes["w"] = 119] = "w"; + CharacterCodes[CharacterCodes["x"] = 120] = "x"; + CharacterCodes[CharacterCodes["y"] = 121] = "y"; + CharacterCodes[CharacterCodes["z"] = 122] = "z"; + CharacterCodes[CharacterCodes["A"] = 65] = "A"; + CharacterCodes[CharacterCodes["B"] = 66] = "B"; + CharacterCodes[CharacterCodes["C"] = 67] = "C"; + CharacterCodes[CharacterCodes["D"] = 68] = "D"; + CharacterCodes[CharacterCodes["E"] = 69] = "E"; + CharacterCodes[CharacterCodes["F"] = 70] = "F"; + CharacterCodes[CharacterCodes["G"] = 71] = "G"; + CharacterCodes[CharacterCodes["H"] = 72] = "H"; + CharacterCodes[CharacterCodes["I"] = 73] = "I"; + CharacterCodes[CharacterCodes["J"] = 74] = "J"; + CharacterCodes[CharacterCodes["K"] = 75] = "K"; + CharacterCodes[CharacterCodes["L"] = 76] = "L"; + CharacterCodes[CharacterCodes["M"] = 77] = "M"; + CharacterCodes[CharacterCodes["N"] = 78] = "N"; + CharacterCodes[CharacterCodes["O"] = 79] = "O"; + CharacterCodes[CharacterCodes["P"] = 80] = "P"; + CharacterCodes[CharacterCodes["Q"] = 81] = "Q"; + CharacterCodes[CharacterCodes["R"] = 82] = "R"; + CharacterCodes[CharacterCodes["S"] = 83] = "S"; + CharacterCodes[CharacterCodes["T"] = 84] = "T"; + CharacterCodes[CharacterCodes["U"] = 85] = "U"; + CharacterCodes[CharacterCodes["V"] = 86] = "V"; + CharacterCodes[CharacterCodes["W"] = 87] = "W"; + CharacterCodes[CharacterCodes["X"] = 88] = "X"; + CharacterCodes[CharacterCodes["Y"] = 89] = "Y"; + CharacterCodes[CharacterCodes["Z"] = 90] = "Z"; + CharacterCodes[CharacterCodes["ampersand"] = 38] = "ampersand"; + CharacterCodes[CharacterCodes["asterisk"] = 42] = "asterisk"; + CharacterCodes[CharacterCodes["at"] = 64] = "at"; + CharacterCodes[CharacterCodes["backslash"] = 92] = "backslash"; + CharacterCodes[CharacterCodes["backtick"] = 96] = "backtick"; + CharacterCodes[CharacterCodes["bar"] = 124] = "bar"; + CharacterCodes[CharacterCodes["caret"] = 94] = "caret"; + CharacterCodes[CharacterCodes["closeBrace"] = 125] = "closeBrace"; + CharacterCodes[CharacterCodes["closeBracket"] = 93] = "closeBracket"; + CharacterCodes[CharacterCodes["closeParen"] = 41] = "closeParen"; + CharacterCodes[CharacterCodes["colon"] = 58] = "colon"; + CharacterCodes[CharacterCodes["comma"] = 44] = "comma"; + CharacterCodes[CharacterCodes["dot"] = 46] = "dot"; + CharacterCodes[CharacterCodes["doubleQuote"] = 34] = "doubleQuote"; + CharacterCodes[CharacterCodes["equals"] = 61] = "equals"; + CharacterCodes[CharacterCodes["exclamation"] = 33] = "exclamation"; + CharacterCodes[CharacterCodes["greaterThan"] = 62] = "greaterThan"; + CharacterCodes[CharacterCodes["hash"] = 35] = "hash"; + CharacterCodes[CharacterCodes["lessThan"] = 60] = "lessThan"; + CharacterCodes[CharacterCodes["minus"] = 45] = "minus"; + CharacterCodes[CharacterCodes["openBrace"] = 123] = "openBrace"; + CharacterCodes[CharacterCodes["openBracket"] = 91] = "openBracket"; + CharacterCodes[CharacterCodes["openParen"] = 40] = "openParen"; + CharacterCodes[CharacterCodes["percent"] = 37] = "percent"; + CharacterCodes[CharacterCodes["plus"] = 43] = "plus"; + CharacterCodes[CharacterCodes["question"] = 63] = "question"; + CharacterCodes[CharacterCodes["semicolon"] = 59] = "semicolon"; + CharacterCodes[CharacterCodes["singleQuote"] = 39] = "singleQuote"; + CharacterCodes[CharacterCodes["slash"] = 47] = "slash"; + CharacterCodes[CharacterCodes["tilde"] = 126] = "tilde"; + CharacterCodes[CharacterCodes["backspace"] = 8] = "backspace"; + CharacterCodes[CharacterCodes["formFeed"] = 12] = "formFeed"; + CharacterCodes[CharacterCodes["byteOrderMark"] = 65279] = "byteOrderMark"; + CharacterCodes[CharacterCodes["tab"] = 9] = "tab"; + CharacterCodes[CharacterCodes["verticalTab"] = 11] = "verticalTab"; + })(CharacterCodes = ts.CharacterCodes || (ts.CharacterCodes = {})); + var Extension; + (function (Extension) { + Extension["Ts"] = ".ts"; + Extension["Tsx"] = ".tsx"; + Extension["Dts"] = ".d.ts"; + Extension["Js"] = ".js"; + Extension["Jsx"] = ".jsx"; + Extension["Json"] = ".json"; + })(Extension = ts.Extension || (ts.Extension = {})); + /* @internal */ + var TransformFlags; + (function (TransformFlags) { + TransformFlags[TransformFlags["None"] = 0] = "None"; + // Facts + // - Flags used to indicate that a node or subtree contains syntax that requires transformation. + TransformFlags[TransformFlags["TypeScript"] = 1] = "TypeScript"; + TransformFlags[TransformFlags["ContainsTypeScript"] = 2] = "ContainsTypeScript"; + TransformFlags[TransformFlags["ContainsJsx"] = 4] = "ContainsJsx"; + TransformFlags[TransformFlags["ContainsESNext"] = 8] = "ContainsESNext"; + TransformFlags[TransformFlags["ContainsES2017"] = 16] = "ContainsES2017"; + TransformFlags[TransformFlags["ContainsES2016"] = 32] = "ContainsES2016"; + TransformFlags[TransformFlags["ES2015"] = 64] = "ES2015"; + TransformFlags[TransformFlags["ContainsES2015"] = 128] = "ContainsES2015"; + TransformFlags[TransformFlags["Generator"] = 256] = "Generator"; + TransformFlags[TransformFlags["ContainsGenerator"] = 512] = "ContainsGenerator"; + TransformFlags[TransformFlags["DestructuringAssignment"] = 1024] = "DestructuringAssignment"; + TransformFlags[TransformFlags["ContainsDestructuringAssignment"] = 2048] = "ContainsDestructuringAssignment"; + // Markers + // - Flags used to indicate that a subtree contains a specific transformation. + TransformFlags[TransformFlags["ContainsTypeScriptClassSyntax"] = 4096] = "ContainsTypeScriptClassSyntax"; + TransformFlags[TransformFlags["ContainsLexicalThis"] = 8192] = "ContainsLexicalThis"; + TransformFlags[TransformFlags["ContainsCapturedLexicalThis"] = 16384] = "ContainsCapturedLexicalThis"; + TransformFlags[TransformFlags["ContainsLexicalThisInComputedPropertyName"] = 32768] = "ContainsLexicalThisInComputedPropertyName"; + TransformFlags[TransformFlags["ContainsDefaultValueAssignments"] = 65536] = "ContainsDefaultValueAssignments"; + TransformFlags[TransformFlags["ContainsRestOrSpread"] = 131072] = "ContainsRestOrSpread"; + TransformFlags[TransformFlags["ContainsObjectRestOrSpread"] = 262144] = "ContainsObjectRestOrSpread"; + TransformFlags[TransformFlags["ContainsComputedPropertyName"] = 524288] = "ContainsComputedPropertyName"; + TransformFlags[TransformFlags["ContainsBlockScopedBinding"] = 1048576] = "ContainsBlockScopedBinding"; + TransformFlags[TransformFlags["ContainsBindingPattern"] = 2097152] = "ContainsBindingPattern"; + TransformFlags[TransformFlags["ContainsYield"] = 4194304] = "ContainsYield"; + TransformFlags[TransformFlags["ContainsHoistedDeclarationOrCompletion"] = 8388608] = "ContainsHoistedDeclarationOrCompletion"; + TransformFlags[TransformFlags["ContainsDynamicImport"] = 16777216] = "ContainsDynamicImport"; + TransformFlags[TransformFlags["Super"] = 33554432] = "Super"; + TransformFlags[TransformFlags["ContainsSuper"] = 67108864] = "ContainsSuper"; + // Please leave this as 1 << 29. + // It is the maximum bit we can set before we outgrow the size of a v8 small integer (SMI) on an x86 system. + // It is a good reminder of how much room we have left + TransformFlags[TransformFlags["HasComputedFlags"] = 536870912] = "HasComputedFlags"; + // Assertions + // - Bitmasks that are used to assert facts about the syntax of a node and its subtree. + TransformFlags[TransformFlags["AssertTypeScript"] = 3] = "AssertTypeScript"; + TransformFlags[TransformFlags["AssertJsx"] = 4] = "AssertJsx"; + TransformFlags[TransformFlags["AssertESNext"] = 8] = "AssertESNext"; + TransformFlags[TransformFlags["AssertES2017"] = 16] = "AssertES2017"; + TransformFlags[TransformFlags["AssertES2016"] = 32] = "AssertES2016"; + TransformFlags[TransformFlags["AssertES2015"] = 192] = "AssertES2015"; + TransformFlags[TransformFlags["AssertGenerator"] = 768] = "AssertGenerator"; + TransformFlags[TransformFlags["AssertDestructuringAssignment"] = 3072] = "AssertDestructuringAssignment"; + // Scope Exclusions + // - Bitmasks that exclude flags from propagating out of a specific context + // into the subtree flags of their container. + TransformFlags[TransformFlags["OuterExpressionExcludes"] = 536872257] = "OuterExpressionExcludes"; + TransformFlags[TransformFlags["PropertyAccessExcludes"] = 570426689] = "PropertyAccessExcludes"; + TransformFlags[TransformFlags["NodeExcludes"] = 637535553] = "NodeExcludes"; + TransformFlags[TransformFlags["ArrowFunctionExcludes"] = 653604161] = "ArrowFunctionExcludes"; + TransformFlags[TransformFlags["FunctionExcludes"] = 653620545] = "FunctionExcludes"; + TransformFlags[TransformFlags["ConstructorExcludes"] = 653616449] = "ConstructorExcludes"; + TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = 653616449] = "MethodOrAccessorExcludes"; + TransformFlags[TransformFlags["ClassExcludes"] = 638121281] = "ClassExcludes"; + TransformFlags[TransformFlags["ModuleExcludes"] = 647001409] = "ModuleExcludes"; + TransformFlags[TransformFlags["TypeExcludes"] = -3] = "TypeExcludes"; + TransformFlags[TransformFlags["ObjectLiteralExcludes"] = 638358849] = "ObjectLiteralExcludes"; + TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = 637666625] = "ArrayLiteralOrCallOrNewExcludes"; + TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = 639894849] = "VariableDeclarationListExcludes"; + TransformFlags[TransformFlags["ParameterExcludes"] = 637535553] = "ParameterExcludes"; + TransformFlags[TransformFlags["CatchClauseExcludes"] = 637797697] = "CatchClauseExcludes"; + TransformFlags[TransformFlags["BindingPatternExcludes"] = 637666625] = "BindingPatternExcludes"; + // Masks + // - Additional bitmasks + TransformFlags[TransformFlags["ES2015FunctionSyntaxMask"] = 81920] = "ES2015FunctionSyntaxMask"; + })(TransformFlags = ts.TransformFlags || (ts.TransformFlags = {})); + var EmitFlags; + (function (EmitFlags) { + EmitFlags[EmitFlags["None"] = 0] = "None"; + EmitFlags[EmitFlags["SingleLine"] = 1] = "SingleLine"; + EmitFlags[EmitFlags["AdviseOnEmitNode"] = 2] = "AdviseOnEmitNode"; + EmitFlags[EmitFlags["NoSubstitution"] = 4] = "NoSubstitution"; + EmitFlags[EmitFlags["CapturesThis"] = 8] = "CapturesThis"; + EmitFlags[EmitFlags["NoLeadingSourceMap"] = 16] = "NoLeadingSourceMap"; + EmitFlags[EmitFlags["NoTrailingSourceMap"] = 32] = "NoTrailingSourceMap"; + EmitFlags[EmitFlags["NoSourceMap"] = 48] = "NoSourceMap"; + EmitFlags[EmitFlags["NoNestedSourceMaps"] = 64] = "NoNestedSourceMaps"; + EmitFlags[EmitFlags["NoTokenLeadingSourceMaps"] = 128] = "NoTokenLeadingSourceMaps"; + EmitFlags[EmitFlags["NoTokenTrailingSourceMaps"] = 256] = "NoTokenTrailingSourceMaps"; + EmitFlags[EmitFlags["NoTokenSourceMaps"] = 384] = "NoTokenSourceMaps"; + EmitFlags[EmitFlags["NoLeadingComments"] = 512] = "NoLeadingComments"; + EmitFlags[EmitFlags["NoTrailingComments"] = 1024] = "NoTrailingComments"; + EmitFlags[EmitFlags["NoComments"] = 1536] = "NoComments"; + EmitFlags[EmitFlags["NoNestedComments"] = 2048] = "NoNestedComments"; + EmitFlags[EmitFlags["HelperName"] = 4096] = "HelperName"; + EmitFlags[EmitFlags["ExportName"] = 8192] = "ExportName"; + EmitFlags[EmitFlags["LocalName"] = 16384] = "LocalName"; + EmitFlags[EmitFlags["InternalName"] = 32768] = "InternalName"; + EmitFlags[EmitFlags["Indented"] = 65536] = "Indented"; + EmitFlags[EmitFlags["NoIndentation"] = 131072] = "NoIndentation"; + EmitFlags[EmitFlags["AsyncFunctionBody"] = 262144] = "AsyncFunctionBody"; + EmitFlags[EmitFlags["ReuseTempVariableScope"] = 524288] = "ReuseTempVariableScope"; + EmitFlags[EmitFlags["CustomPrologue"] = 1048576] = "CustomPrologue"; + EmitFlags[EmitFlags["NoHoisting"] = 2097152] = "NoHoisting"; + EmitFlags[EmitFlags["HasEndOfDeclarationMarker"] = 4194304] = "HasEndOfDeclarationMarker"; + EmitFlags[EmitFlags["Iterator"] = 8388608] = "Iterator"; + EmitFlags[EmitFlags["NoAsciiEscaping"] = 16777216] = "NoAsciiEscaping"; + /*@internal*/ EmitFlags[EmitFlags["TypeScriptClassWrapper"] = 33554432] = "TypeScriptClassWrapper"; + /*@internal*/ EmitFlags[EmitFlags["NeverApplyImportHelper"] = 67108864] = "NeverApplyImportHelper"; + })(EmitFlags = ts.EmitFlags || (ts.EmitFlags = {})); + /** + * Used by the checker, this enum keeps track of external emit helpers that should be type + * checked. + */ + /* @internal */ + var ExternalEmitHelpers; + (function (ExternalEmitHelpers) { + ExternalEmitHelpers[ExternalEmitHelpers["Extends"] = 1] = "Extends"; + ExternalEmitHelpers[ExternalEmitHelpers["Assign"] = 2] = "Assign"; + ExternalEmitHelpers[ExternalEmitHelpers["Rest"] = 4] = "Rest"; + ExternalEmitHelpers[ExternalEmitHelpers["Decorate"] = 8] = "Decorate"; + ExternalEmitHelpers[ExternalEmitHelpers["Metadata"] = 16] = "Metadata"; + ExternalEmitHelpers[ExternalEmitHelpers["Param"] = 32] = "Param"; + ExternalEmitHelpers[ExternalEmitHelpers["Awaiter"] = 64] = "Awaiter"; + ExternalEmitHelpers[ExternalEmitHelpers["Generator"] = 128] = "Generator"; + ExternalEmitHelpers[ExternalEmitHelpers["Values"] = 256] = "Values"; + ExternalEmitHelpers[ExternalEmitHelpers["Read"] = 512] = "Read"; + ExternalEmitHelpers[ExternalEmitHelpers["Spread"] = 1024] = "Spread"; + ExternalEmitHelpers[ExternalEmitHelpers["Await"] = 2048] = "Await"; + ExternalEmitHelpers[ExternalEmitHelpers["AsyncGenerator"] = 4096] = "AsyncGenerator"; + ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegator"] = 8192] = "AsyncDelegator"; + ExternalEmitHelpers[ExternalEmitHelpers["AsyncValues"] = 16384] = "AsyncValues"; + ExternalEmitHelpers[ExternalEmitHelpers["ExportStar"] = 32768] = "ExportStar"; + ExternalEmitHelpers[ExternalEmitHelpers["MakeTemplateObject"] = 65536] = "MakeTemplateObject"; + ExternalEmitHelpers[ExternalEmitHelpers["FirstEmitHelper"] = 1] = "FirstEmitHelper"; + ExternalEmitHelpers[ExternalEmitHelpers["LastEmitHelper"] = 65536] = "LastEmitHelper"; + // Helpers included by ES2015 for..of + ExternalEmitHelpers[ExternalEmitHelpers["ForOfIncludes"] = 256] = "ForOfIncludes"; + // Helpers included by ES2017 for..await..of + ExternalEmitHelpers[ExternalEmitHelpers["ForAwaitOfIncludes"] = 16384] = "ForAwaitOfIncludes"; + // Helpers included by ES2017 async generators + ExternalEmitHelpers[ExternalEmitHelpers["AsyncGeneratorIncludes"] = 6144] = "AsyncGeneratorIncludes"; + // Helpers included by yield* in ES2017 async generators + ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegatorIncludes"] = 26624] = "AsyncDelegatorIncludes"; + // Helpers included by ES2015 spread + ExternalEmitHelpers[ExternalEmitHelpers["SpreadIncludes"] = 1536] = "SpreadIncludes"; + })(ExternalEmitHelpers = ts.ExternalEmitHelpers || (ts.ExternalEmitHelpers = {})); + var EmitHint; + (function (EmitHint) { + EmitHint[EmitHint["SourceFile"] = 0] = "SourceFile"; + EmitHint[EmitHint["Expression"] = 1] = "Expression"; + EmitHint[EmitHint["IdentifierName"] = 2] = "IdentifierName"; + EmitHint[EmitHint["MappedTypeParameter"] = 3] = "MappedTypeParameter"; + EmitHint[EmitHint["Unspecified"] = 4] = "Unspecified"; + EmitHint[EmitHint["EmbeddedStatement"] = 5] = "EmbeddedStatement"; + })(EmitHint = ts.EmitHint || (ts.EmitHint = {})); + var ListFormat; + (function (ListFormat) { + ListFormat[ListFormat["None"] = 0] = "None"; + // Line separators + ListFormat[ListFormat["SingleLine"] = 0] = "SingleLine"; + ListFormat[ListFormat["MultiLine"] = 1] = "MultiLine"; + ListFormat[ListFormat["PreserveLines"] = 2] = "PreserveLines"; + ListFormat[ListFormat["LinesMask"] = 3] = "LinesMask"; + // Delimiters + ListFormat[ListFormat["NotDelimited"] = 0] = "NotDelimited"; + ListFormat[ListFormat["BarDelimited"] = 4] = "BarDelimited"; + ListFormat[ListFormat["AmpersandDelimited"] = 8] = "AmpersandDelimited"; + ListFormat[ListFormat["CommaDelimited"] = 16] = "CommaDelimited"; + ListFormat[ListFormat["AsteriskDelimited"] = 32] = "AsteriskDelimited"; + ListFormat[ListFormat["DelimitersMask"] = 60] = "DelimitersMask"; + ListFormat[ListFormat["AllowTrailingComma"] = 64] = "AllowTrailingComma"; + // Whitespace + ListFormat[ListFormat["Indented"] = 128] = "Indented"; + ListFormat[ListFormat["SpaceBetweenBraces"] = 256] = "SpaceBetweenBraces"; + ListFormat[ListFormat["SpaceBetweenSiblings"] = 512] = "SpaceBetweenSiblings"; + // Brackets/Braces + ListFormat[ListFormat["Braces"] = 1024] = "Braces"; + ListFormat[ListFormat["Parenthesis"] = 2048] = "Parenthesis"; + ListFormat[ListFormat["AngleBrackets"] = 4096] = "AngleBrackets"; + ListFormat[ListFormat["SquareBrackets"] = 8192] = "SquareBrackets"; + ListFormat[ListFormat["BracketsMask"] = 15360] = "BracketsMask"; + ListFormat[ListFormat["OptionalIfUndefined"] = 16384] = "OptionalIfUndefined"; + ListFormat[ListFormat["OptionalIfEmpty"] = 32768] = "OptionalIfEmpty"; + ListFormat[ListFormat["Optional"] = 49152] = "Optional"; + // Other + ListFormat[ListFormat["PreferNewLine"] = 65536] = "PreferNewLine"; + ListFormat[ListFormat["NoTrailingNewLine"] = 131072] = "NoTrailingNewLine"; + ListFormat[ListFormat["NoInterveningComments"] = 262144] = "NoInterveningComments"; + ListFormat[ListFormat["NoSpaceIfEmpty"] = 524288] = "NoSpaceIfEmpty"; + ListFormat[ListFormat["SingleElement"] = 1048576] = "SingleElement"; + // Precomputed Formats + ListFormat[ListFormat["Modifiers"] = 262656] = "Modifiers"; + ListFormat[ListFormat["HeritageClauses"] = 512] = "HeritageClauses"; + ListFormat[ListFormat["SingleLineTypeLiteralMembers"] = 768] = "SingleLineTypeLiteralMembers"; + ListFormat[ListFormat["MultiLineTypeLiteralMembers"] = 32897] = "MultiLineTypeLiteralMembers"; + ListFormat[ListFormat["TupleTypeElements"] = 528] = "TupleTypeElements"; + ListFormat[ListFormat["UnionTypeConstituents"] = 516] = "UnionTypeConstituents"; + ListFormat[ListFormat["IntersectionTypeConstituents"] = 520] = "IntersectionTypeConstituents"; + ListFormat[ListFormat["ObjectBindingPatternElements"] = 525136] = "ObjectBindingPatternElements"; + ListFormat[ListFormat["ArrayBindingPatternElements"] = 524880] = "ArrayBindingPatternElements"; + ListFormat[ListFormat["ObjectLiteralExpressionProperties"] = 526226] = "ObjectLiteralExpressionProperties"; + ListFormat[ListFormat["ArrayLiteralExpressionElements"] = 8914] = "ArrayLiteralExpressionElements"; + ListFormat[ListFormat["CommaListElements"] = 528] = "CommaListElements"; + ListFormat[ListFormat["CallExpressionArguments"] = 2576] = "CallExpressionArguments"; + ListFormat[ListFormat["NewExpressionArguments"] = 18960] = "NewExpressionArguments"; + ListFormat[ListFormat["TemplateExpressionSpans"] = 262144] = "TemplateExpressionSpans"; + ListFormat[ListFormat["SingleLineBlockStatements"] = 768] = "SingleLineBlockStatements"; + ListFormat[ListFormat["MultiLineBlockStatements"] = 129] = "MultiLineBlockStatements"; + ListFormat[ListFormat["VariableDeclarationList"] = 528] = "VariableDeclarationList"; + ListFormat[ListFormat["SingleLineFunctionBodyStatements"] = 768] = "SingleLineFunctionBodyStatements"; + ListFormat[ListFormat["MultiLineFunctionBodyStatements"] = 1] = "MultiLineFunctionBodyStatements"; + ListFormat[ListFormat["ClassHeritageClauses"] = 0] = "ClassHeritageClauses"; + ListFormat[ListFormat["ClassMembers"] = 129] = "ClassMembers"; + ListFormat[ListFormat["InterfaceMembers"] = 129] = "InterfaceMembers"; + ListFormat[ListFormat["EnumMembers"] = 145] = "EnumMembers"; + ListFormat[ListFormat["CaseBlockClauses"] = 129] = "CaseBlockClauses"; + ListFormat[ListFormat["NamedImportsOrExportsElements"] = 525136] = "NamedImportsOrExportsElements"; + ListFormat[ListFormat["JsxElementOrFragmentChildren"] = 262144] = "JsxElementOrFragmentChildren"; + ListFormat[ListFormat["JsxElementAttributes"] = 262656] = "JsxElementAttributes"; + ListFormat[ListFormat["CaseOrDefaultClauseStatements"] = 163969] = "CaseOrDefaultClauseStatements"; + ListFormat[ListFormat["HeritageClauseTypes"] = 528] = "HeritageClauseTypes"; + ListFormat[ListFormat["SourceFileStatements"] = 131073] = "SourceFileStatements"; + ListFormat[ListFormat["Decorators"] = 49153] = "Decorators"; + ListFormat[ListFormat["TypeArguments"] = 53776] = "TypeArguments"; + ListFormat[ListFormat["TypeParameters"] = 53776] = "TypeParameters"; + ListFormat[ListFormat["Parameters"] = 2576] = "Parameters"; + ListFormat[ListFormat["IndexSignatureParameters"] = 8848] = "IndexSignatureParameters"; + ListFormat[ListFormat["JSDocComment"] = 33] = "JSDocComment"; + })(ListFormat = ts.ListFormat || (ts.ListFormat = {})); + /* @internal */ + var PragmaKindFlags; + (function (PragmaKindFlags) { + PragmaKindFlags[PragmaKindFlags["None"] = 0] = "None"; + /** + * Triple slash comment of the form + * /// + */ + PragmaKindFlags[PragmaKindFlags["TripleSlashXML"] = 1] = "TripleSlashXML"; + /** + * Single line comment of the form + * // @pragma-name argval1 argval2 + * or + * /// @pragma-name argval1 argval2 + */ + PragmaKindFlags[PragmaKindFlags["SingleLine"] = 2] = "SingleLine"; + /** + * Multiline non-jsdoc pragma of the form + * /* @pragma-name argval1 argval2 * / + */ + PragmaKindFlags[PragmaKindFlags["MultiLine"] = 4] = "MultiLine"; + PragmaKindFlags[PragmaKindFlags["All"] = 7] = "All"; + PragmaKindFlags[PragmaKindFlags["Default"] = 7] = "Default"; + })(PragmaKindFlags = ts.PragmaKindFlags || (ts.PragmaKindFlags = {})); + /** + * This function only exists to cause exact types to be inferred for all the literals within `commentPragmas` + */ + /* @internal */ + function _contextuallyTypePragmas(args) { + return args; + } + // While not strictly a type, this is here because `PragmaMap` needs to be here to be used with `SourceFile`, and we don't + // fancy effectively defining it twice, once in value-space and once in type-space + /* @internal */ + ts.commentPragmas = _contextuallyTypePragmas({ + "reference": { + args: [ + { name: "types", optional: true, captureSpan: true }, + { name: "lib", optional: true, captureSpan: true }, + { name: "path", optional: true, captureSpan: true }, + { name: "no-default-lib", optional: true } + ], + kind: 1 /* TripleSlashXML */ + }, + "amd-dependency": { + args: [{ name: "path" }, { name: "name", optional: true }], + kind: 1 /* TripleSlashXML */ + }, + "amd-module": { + args: [{ name: "name" }], + kind: 1 /* TripleSlashXML */ + }, + "ts-check": { + kind: 2 /* SingleLine */ + }, + "ts-nocheck": { + kind: 2 /* SingleLine */ + }, + "jsx": { + args: [{ name: "factory" }], + kind: 4 /* MultiLine */ + }, + }); +})(ts || (ts = {})); +var ts; +(function (ts) { + /** + * Set a high stack trace limit to provide more information in case of an error. + * Called for command-line and server use cases. + * Not called if TypeScript is used as a library. + */ + /* @internal */ + function setStackTraceLimit() { + if (Error.stackTraceLimit < 100) { // Also tests that we won't set the property if it doesn't exist. + Error.stackTraceLimit = 100; + } + } + ts.setStackTraceLimit = setStackTraceLimit; + var FileWatcherEventKind; + (function (FileWatcherEventKind) { + FileWatcherEventKind[FileWatcherEventKind["Created"] = 0] = "Created"; + FileWatcherEventKind[FileWatcherEventKind["Changed"] = 1] = "Changed"; + FileWatcherEventKind[FileWatcherEventKind["Deleted"] = 2] = "Deleted"; + })(FileWatcherEventKind = ts.FileWatcherEventKind || (ts.FileWatcherEventKind = {})); + /* @internal */ + var PollingInterval; + (function (PollingInterval) { + PollingInterval[PollingInterval["High"] = 2000] = "High"; + PollingInterval[PollingInterval["Medium"] = 500] = "Medium"; + PollingInterval[PollingInterval["Low"] = 250] = "Low"; + })(PollingInterval = ts.PollingInterval || (ts.PollingInterval = {})); + /* @internal */ + ts.missingFileModifiedTime = new Date(0); // Any subsequent modification will occur after this time + function createPollingIntervalBasedLevels(levels) { + var _a; + return _a = {}, + _a[PollingInterval.Low] = levels.Low, + _a[PollingInterval.Medium] = levels.Medium, + _a[PollingInterval.High] = levels.High, + _a; + } + var defaultChunkLevels = { Low: 32, Medium: 64, High: 256 }; + var pollingChunkSize = createPollingIntervalBasedLevels(defaultChunkLevels); + /* @internal */ + ts.unchangedPollThresholds = createPollingIntervalBasedLevels(defaultChunkLevels); + /* @internal */ + function setCustomPollingValues(system) { + if (!system.getEnvironmentVariable) { + return; + } + var pollingIntervalChanged = setCustomLevels("TSC_WATCH_POLLINGINTERVAL", PollingInterval); + pollingChunkSize = getCustomPollingBasedLevels("TSC_WATCH_POLLINGCHUNKSIZE", defaultChunkLevels) || pollingChunkSize; + ts.unchangedPollThresholds = getCustomPollingBasedLevels("TSC_WATCH_UNCHANGEDPOLLTHRESHOLDS", defaultChunkLevels) || ts.unchangedPollThresholds; + function getLevel(envVar, level) { + return system.getEnvironmentVariable(envVar + "_" + level.toUpperCase()); + } + function getCustomLevels(baseVariable) { + var customLevels; + setCustomLevel("Low"); + setCustomLevel("Medium"); + setCustomLevel("High"); + return customLevels; + function setCustomLevel(level) { + var customLevel = getLevel(baseVariable, level); + if (customLevel) { + (customLevels || (customLevels = {}))[level] = Number(customLevel); + } + } + } + function setCustomLevels(baseVariable, levels) { + var customLevels = getCustomLevels(baseVariable); + if (customLevels) { + setLevel("Low"); + setLevel("Medium"); + setLevel("High"); + return true; + } + return false; + function setLevel(level) { + levels[level] = customLevels[level] || levels[level]; + } + } + function getCustomPollingBasedLevels(baseVariable, defaultLevels) { + var customLevels = getCustomLevels(baseVariable); + return (pollingIntervalChanged || customLevels) && + createPollingIntervalBasedLevels(customLevels ? __assign({}, defaultLevels, customLevels) : defaultLevels); + } + } + ts.setCustomPollingValues = setCustomPollingValues; + /* @internal */ + function createDynamicPriorityPollingWatchFile(host) { + var watchedFiles = []; + var changedFilesInLastPoll = []; + var lowPollingIntervalQueue = createPollingIntervalQueue(PollingInterval.Low); + var mediumPollingIntervalQueue = createPollingIntervalQueue(PollingInterval.Medium); + var highPollingIntervalQueue = createPollingIntervalQueue(PollingInterval.High); + return watchFile; + function watchFile(fileName, callback, defaultPollingInterval) { + var file = { + fileName: fileName, + callback: callback, + unchangedPolls: 0, + mtime: getModifiedTime(fileName) + }; + watchedFiles.push(file); + addToPollingIntervalQueue(file, defaultPollingInterval); + return { + close: function () { + file.isClosed = true; + // Remove from watchedFiles + ts.unorderedRemoveItem(watchedFiles, file); + // Do not update polling interval queue since that will happen as part of polling + } + }; + } + function createPollingIntervalQueue(pollingInterval) { + var queue = []; + queue.pollingInterval = pollingInterval; + queue.pollIndex = 0; + queue.pollScheduled = false; + return queue; + } + function pollPollingIntervalQueue(queue) { + queue.pollIndex = pollQueue(queue, queue.pollingInterval, queue.pollIndex, pollingChunkSize[queue.pollingInterval]); + // Set the next polling index and timeout + if (queue.length) { + scheduleNextPoll(queue.pollingInterval); + } + else { + ts.Debug.assert(queue.pollIndex === 0); + queue.pollScheduled = false; + } + } + function pollLowPollingIntervalQueue(queue) { + // Always poll complete list of changedFilesInLastPoll + pollQueue(changedFilesInLastPoll, PollingInterval.Low, /*pollIndex*/ 0, changedFilesInLastPoll.length); + // Finally do the actual polling of the queue + pollPollingIntervalQueue(queue); + // Schedule poll if there are files in changedFilesInLastPoll but no files in the actual queue + // as pollPollingIntervalQueue wont schedule for next poll + if (!queue.pollScheduled && changedFilesInLastPoll.length) { + scheduleNextPoll(PollingInterval.Low); + } + } + function pollQueue(queue, pollingInterval, pollIndex, chunkSize) { + // Max visit would be all elements of the queue + var needsVisit = queue.length; + var definedValueCopyToIndex = pollIndex; + for (var polled = 0; polled < chunkSize && needsVisit > 0; nextPollIndex(), needsVisit--) { + var watchedFile = queue[pollIndex]; + if (!watchedFile) { + continue; + } + else if (watchedFile.isClosed) { + queue[pollIndex] = undefined; + continue; + } + polled++; + var fileChanged = onWatchedFileStat(watchedFile, getModifiedTime(watchedFile.fileName)); + if (watchedFile.isClosed) { + // Closed watcher as part of callback + queue[pollIndex] = undefined; + } + else if (fileChanged) { + watchedFile.unchangedPolls = 0; + // Changed files go to changedFilesInLastPoll queue + if (queue !== changedFilesInLastPoll) { + queue[pollIndex] = undefined; + addChangedFileToLowPollingIntervalQueue(watchedFile); + } + } + else if (watchedFile.unchangedPolls !== ts.unchangedPollThresholds[pollingInterval]) { + watchedFile.unchangedPolls++; + } + else if (queue === changedFilesInLastPoll) { + // Restart unchangedPollCount for unchanged file and move to low polling interval queue + watchedFile.unchangedPolls = 1; + queue[pollIndex] = undefined; + addToPollingIntervalQueue(watchedFile, PollingInterval.Low); + } + else if (pollingInterval !== PollingInterval.High) { + watchedFile.unchangedPolls++; + queue[pollIndex] = undefined; + addToPollingIntervalQueue(watchedFile, pollingInterval === PollingInterval.Low ? PollingInterval.Medium : PollingInterval.High); + } + if (queue[pollIndex]) { + // Copy this file to the non hole location + if (definedValueCopyToIndex < pollIndex) { + queue[definedValueCopyToIndex] = watchedFile; + queue[pollIndex] = undefined; + } + definedValueCopyToIndex++; + } + } + // Return next poll index + return pollIndex; + function nextPollIndex() { + pollIndex++; + if (pollIndex === queue.length) { + if (definedValueCopyToIndex < pollIndex) { + // There are holes from nextDefinedValueIndex to end of queue, change queue size + queue.length = definedValueCopyToIndex; + } + pollIndex = 0; + definedValueCopyToIndex = 0; + } + } + } + function pollingIntervalQueue(pollingInterval) { + switch (pollingInterval) { + case PollingInterval.Low: + return lowPollingIntervalQueue; + case PollingInterval.Medium: + return mediumPollingIntervalQueue; + case PollingInterval.High: + return highPollingIntervalQueue; + } + } + function addToPollingIntervalQueue(file, pollingInterval) { + pollingIntervalQueue(pollingInterval).push(file); + scheduleNextPollIfNotAlreadyScheduled(pollingInterval); + } + function addChangedFileToLowPollingIntervalQueue(file) { + changedFilesInLastPoll.push(file); + scheduleNextPollIfNotAlreadyScheduled(PollingInterval.Low); + } + function scheduleNextPollIfNotAlreadyScheduled(pollingInterval) { + if (!pollingIntervalQueue(pollingInterval).pollScheduled) { + scheduleNextPoll(pollingInterval); + } + } + function scheduleNextPoll(pollingInterval) { + pollingIntervalQueue(pollingInterval).pollScheduled = host.setTimeout(pollingInterval === PollingInterval.Low ? pollLowPollingIntervalQueue : pollPollingIntervalQueue, pollingInterval, pollingIntervalQueue(pollingInterval)); + } + function getModifiedTime(fileName) { + return host.getModifiedTime(fileName) || ts.missingFileModifiedTime; + } + } + ts.createDynamicPriorityPollingWatchFile = createDynamicPriorityPollingWatchFile; + /** + * Returns true if file status changed + */ + /*@internal*/ + function onWatchedFileStat(watchedFile, modifiedTime) { + var oldTime = watchedFile.mtime.getTime(); + var newTime = modifiedTime.getTime(); + if (oldTime !== newTime) { + watchedFile.mtime = modifiedTime; + watchedFile.callback(watchedFile.fileName, getFileWatcherEventKind(oldTime, newTime)); + return true; + } + return false; + } + ts.onWatchedFileStat = onWatchedFileStat; + /*@internal*/ + function getFileWatcherEventKind(oldTime, newTime) { + return oldTime === 0 + ? FileWatcherEventKind.Created + : newTime === 0 + ? FileWatcherEventKind.Deleted + : FileWatcherEventKind.Changed; + } + ts.getFileWatcherEventKind = getFileWatcherEventKind; + /** + * Watch the directory recursively using host provided method to watch child directories + * that means if this is recursive watcher, watch the children directories as well + * (eg on OS that dont support recursive watch using fs.watch use fs.watchFile) + */ + /*@internal*/ + function createRecursiveDirectoryWatcher(host) { + var cache = ts.createMap(); + var callbackCache = ts.createMultiMap(); + var filePathComparer = ts.getStringComparer(!host.useCaseSensitiveFileNames); + var toCanonicalFilePath = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); + return createDirectoryWatcher; + /** + * Create the directory watcher for the dirPath. + */ + function createDirectoryWatcher(dirName, callback) { + var dirPath = toCanonicalFilePath(dirName); + var directoryWatcher = cache.get(dirPath); + if (directoryWatcher) { + directoryWatcher.refCount++; + } + else { + directoryWatcher = { + watcher: host.watchDirectory(dirName, function (fileName) { + // Call the actual callback + callbackCache.forEach(function (callbacks, rootDirName) { + if (rootDirName === dirPath || (ts.startsWith(dirPath, rootDirName) && dirPath[rootDirName.length] === ts.directorySeparator)) { + callbacks.forEach(function (callback) { return callback(fileName); }); + } + }); + // Iterate through existing children and update the watches if needed + updateChildWatches(dirName, dirPath); + }), + refCount: 1, + childWatches: ts.emptyArray + }; + cache.set(dirPath, directoryWatcher); + updateChildWatches(dirName, dirPath); + } + if (callback) { + callbackCache.add(dirPath, callback); + } + return { + dirName: dirName, + close: function () { + var directoryWatcher = ts.Debug.assertDefined(cache.get(dirPath)); + if (callback) + callbackCache.remove(dirPath, callback); + directoryWatcher.refCount--; + if (directoryWatcher.refCount) + return; + cache.delete(dirPath); + ts.closeFileWatcherOf(directoryWatcher); + directoryWatcher.childWatches.forEach(ts.closeFileWatcher); + } + }; + } + function updateChildWatches(dirName, dirPath) { + // Iterate through existing children and update the watches if needed + var parentWatcher = cache.get(dirPath); + if (parentWatcher) { + parentWatcher.childWatches = watchChildDirectories(dirName, parentWatcher.childWatches); + } + } + /** + * Watch the directories in the parentDir + */ + function watchChildDirectories(parentDir, existingChildWatches) { + var newChildWatches; + ts.enumerateInsertsAndDeletes(host.directoryExists(parentDir) ? ts.mapDefined(host.getAccessibleSortedChildDirectories(parentDir), function (child) { + var childFullName = ts.getNormalizedAbsolutePath(child, parentDir); + // Filter our the symbolic link directories since those arent included in recursive watch + // which is same behaviour when recursive: true is passed to fs.watch + return filePathComparer(childFullName, ts.normalizePath(host.realpath(childFullName))) === 0 /* EqualTo */ ? childFullName : undefined; + }) : ts.emptyArray, existingChildWatches, function (child, childWatcher) { return filePathComparer(child, childWatcher.dirName); }, createAndAddChildDirectoryWatcher, ts.closeFileWatcher, addChildDirectoryWatcher); + return newChildWatches || ts.emptyArray; + /** + * Create new childDirectoryWatcher and add it to the new ChildDirectoryWatcher list + */ + function createAndAddChildDirectoryWatcher(childName) { + var result = createDirectoryWatcher(childName); + addChildDirectoryWatcher(result); + } + /** + * Add child directory watcher to the new ChildDirectoryWatcher list + */ + function addChildDirectoryWatcher(childWatcher) { + (newChildWatches || (newChildWatches = [])).push(childWatcher); + } + } + } + ts.createRecursiveDirectoryWatcher = createRecursiveDirectoryWatcher; + function getNodeMajorVersion() { + if (typeof process === "undefined") { + return undefined; + } + var version = process.version; + if (!version) { + return undefined; + } + var dot = version.indexOf("."); + if (dot === -1) { + return undefined; + } + return parseInt(version.substring(1, dot)); + } + ts.getNodeMajorVersion = getNodeMajorVersion; + // TODO: GH#18217 this is used as if it's certainly defined in many places. + ts.sys = (function () { + // NodeJS detects "\uFEFF" at the start of the string and *replaces* it with the actual + // byte order mark from the specified encoding. Using any other byte order mark does + // not actually work. + var byteOrderMarkIndicator = "\uFEFF"; + function getNodeSystem() { + var _fs = require("fs"); + var _path = require("path"); + var _os = require("os"); + // crypto can be absent on reduced node installations + var _crypto; + try { + _crypto = require("crypto"); + } + catch (_a) { + _crypto = undefined; + } + var Buffer = require("buffer").Buffer; + var nodeVersion = getNodeMajorVersion(); + var isNode4OrLater = nodeVersion >= 4; + var platform = _os.platform(); + var useCaseSensitiveFileNames = isFileSystemCaseSensitive(); + var FileSystemEntryKind; + (function (FileSystemEntryKind) { + FileSystemEntryKind[FileSystemEntryKind["File"] = 0] = "File"; + FileSystemEntryKind[FileSystemEntryKind["Directory"] = 1] = "Directory"; + })(FileSystemEntryKind || (FileSystemEntryKind = {})); + var useNonPollingWatchers = process.env.TSC_NONPOLLING_WATCHER; + var tscWatchFile = process.env.TSC_WATCHFILE; + var tscWatchDirectory = process.env.TSC_WATCHDIRECTORY; + var dynamicPollingWatchFile; + var nodeSystem = { + args: process.argv.slice(2), + newLine: _os.EOL, + useCaseSensitiveFileNames: useCaseSensitiveFileNames, + write: function (s) { + process.stdout.write(s); + }, + writeOutputIsTTY: function () { + return process.stdout.isTTY; + }, + readFile: readFile, + writeFile: writeFile, + watchFile: getWatchFile(), + watchDirectory: getWatchDirectory(), + resolvePath: function (path) { return _path.resolve(path); }, + fileExists: fileExists, + directoryExists: directoryExists, + createDirectory: function (directoryName) { + if (!nodeSystem.directoryExists(directoryName)) { + _fs.mkdirSync(directoryName); + } + }, + getExecutingFilePath: function () { + return __filename; + }, + getCurrentDirectory: function () { + return process.cwd(); + }, + getDirectories: getDirectories, + getEnvironmentVariable: function (name) { + return process.env[name] || ""; + }, + readDirectory: readDirectory, + getModifiedTime: getModifiedTime, + setModifiedTime: setModifiedTime, + deleteFile: deleteFile, + createHash: _crypto ? createMD5HashUsingNativeCrypto : generateDjb2Hash, + createSHA256Hash: _crypto ? createSHA256Hash : undefined, + getMemoryUsage: function () { + if (global.gc) { + global.gc(); + } + return process.memoryUsage().heapUsed; + }, + getFileSize: function (path) { + try { + var stat = _fs.statSync(path); + if (stat.isFile()) { + return stat.size; + } + } + catch ( /*ignore*/_a) { /*ignore*/ } + return 0; + }, + exit: function (exitCode) { + process.exit(exitCode); + }, + realpath: realpath, + debugMode: ts.some(process.execArgv, function (arg) { return /^--(inspect|debug)(-brk)?(=\d+)?$/i.test(arg); }), + tryEnableSourceMapsForHost: function () { + try { + require("source-map-support").install(); + } + catch (_a) { + // Could not enable source maps. + } + }, + setTimeout: setTimeout, + clearTimeout: clearTimeout, + clearScreen: function () { + process.stdout.write("\x1Bc"); + }, + setBlocking: function () { + if (process.stdout && process.stdout._handle && process.stdout._handle.setBlocking) { + process.stdout._handle.setBlocking(true); + } + }, + bufferFrom: bufferFrom, + base64decode: function (input) { return bufferFrom(input, "base64").toString("utf8"); }, + base64encode: function (input) { return bufferFrom(input).toString("base64"); }, + }; + return nodeSystem; + function bufferFrom(input, encoding) { + // See https://github.com/Microsoft/TypeScript/issues/25652 + return Buffer.from && Buffer.from !== Int8Array.from + ? Buffer.from(input, encoding) + : new Buffer(input, encoding); + } + function isFileSystemCaseSensitive() { + // win32\win64 are case insensitive platforms + if (platform === "win32" || platform === "win64") { + return false; + } + // If this file exists under a different case, we must be case-insensitve. + return !fileExists(swapCase(__filename)); + } + /** Convert all lowercase chars to uppercase, and vice-versa */ + function swapCase(s) { + return s.replace(/\w/g, function (ch) { + var up = ch.toUpperCase(); + return ch === up ? ch.toLowerCase() : up; + }); + } + function getWatchFile() { + switch (tscWatchFile) { + case "PriorityPollingInterval": + // Use polling interval based on priority when create watch using host.watchFile + return fsWatchFile; + case "DynamicPriorityPolling": + // Use polling interval but change the interval depending on file changes and their default polling interval + return createDynamicPriorityPollingWatchFile({ getModifiedTime: getModifiedTime, setTimeout: setTimeout }); + case "UseFsEvents": + // Use notifications from FS to watch with falling back to fs.watchFile + return watchFileUsingFsWatch; + case "UseFsEventsWithFallbackDynamicPolling": + // Use notifications from FS to watch with falling back to dynamic watch file + dynamicPollingWatchFile = createDynamicPriorityPollingWatchFile({ getModifiedTime: getModifiedTime, setTimeout: setTimeout }); + return createWatchFileUsingDynamicWatchFile(dynamicPollingWatchFile); + case "UseFsEventsOnParentDirectory": + // Use notifications from FS to watch with falling back to fs.watchFile + return createNonPollingWatchFile(); + } + return useNonPollingWatchers ? + createNonPollingWatchFile() : + // Default to do not use polling interval as it is before this experiment branch + function (fileName, callback) { return fsWatchFile(fileName, callback); }; + } + function getWatchDirectory() { + // Node 4.0 `fs.watch` function supports the "recursive" option on both OSX and Windows + // (ref: https://github.com/nodejs/node/pull/2649 and https://github.com/Microsoft/TypeScript/issues/4643) + var fsSupportsRecursive = isNode4OrLater && (process.platform === "win32" || process.platform === "darwin"); + if (fsSupportsRecursive) { + return watchDirectoryUsingFsWatch; + } + var watchDirectory = tscWatchDirectory === "RecursiveDirectoryUsingFsWatchFile" ? + createWatchDirectoryUsing(fsWatchFile) : + tscWatchDirectory === "RecursiveDirectoryUsingDynamicPriorityPolling" ? + createWatchDirectoryUsing(dynamicPollingWatchFile || createDynamicPriorityPollingWatchFile({ getModifiedTime: getModifiedTime, setTimeout: setTimeout })) : + watchDirectoryUsingFsWatch; + var watchDirectoryRecursively = createRecursiveDirectoryWatcher({ + useCaseSensitiveFileNames: useCaseSensitiveFileNames, + directoryExists: directoryExists, + getAccessibleSortedChildDirectories: function (path) { return getAccessibleFileSystemEntries(path).directories; }, + watchDirectory: watchDirectory, + realpath: realpath + }); + return function (directoryName, callback, recursive) { + if (recursive) { + return watchDirectoryRecursively(directoryName, callback); + } + return watchDirectory(directoryName, callback); + }; + } + function createNonPollingWatchFile() { + // One file can have multiple watchers + var fileWatcherCallbacks = ts.createMultiMap(); + var dirWatchers = ts.createMap(); + var toCanonicalName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); + return nonPollingWatchFile; + function nonPollingWatchFile(fileName, callback) { + var filePath = toCanonicalName(fileName); + fileWatcherCallbacks.add(filePath, callback); + var dirPath = ts.getDirectoryPath(filePath) || "."; + var watcher = dirWatchers.get(dirPath) || createDirectoryWatcher(ts.getDirectoryPath(fileName) || ".", dirPath); + watcher.referenceCount++; + return { + close: function () { + if (watcher.referenceCount === 1) { + watcher.close(); + dirWatchers.delete(dirPath); + } + else { + watcher.referenceCount--; + } + fileWatcherCallbacks.remove(filePath, callback); + } + }; + } + function createDirectoryWatcher(dirName, dirPath) { + var watcher = fsWatchDirectory(dirName, function (_eventName, relativeFileName) { + // When files are deleted from disk, the triggered "rename" event would have a relativefileName of "undefined" + if (!ts.isString(relativeFileName)) { + return; + } + var fileName = ts.getNormalizedAbsolutePath(relativeFileName, dirName); + // Some applications save a working file via rename operations + var callbacks = fileName && fileWatcherCallbacks.get(toCanonicalName(fileName)); + if (callbacks) { + for (var _i = 0, callbacks_1 = callbacks; _i < callbacks_1.length; _i++) { + var fileCallback = callbacks_1[_i]; + fileCallback(fileName, FileWatcherEventKind.Changed); + } + } + }); + watcher.referenceCount = 0; + dirWatchers.set(dirPath, watcher); + return watcher; + } + } + function fsWatchFile(fileName, callback, pollingInterval) { + _fs.watchFile(fileName, { persistent: true, interval: pollingInterval || 250 }, fileChanged); + var eventKind; + return { + close: function () { return _fs.unwatchFile(fileName, fileChanged); } + }; + function fileChanged(curr, prev) { + // previous event kind check is to ensure we recongnize the file as previously also missing when it is restored or renamed twice (that is it disappears and reappears) + // In such case, prevTime returned is same as prev time of event when file was deleted as per node documentation + var isPreviouslyDeleted = +prev.mtime === 0 || eventKind === FileWatcherEventKind.Deleted; + if (+curr.mtime === 0) { + if (isPreviouslyDeleted) { + // Already deleted file, no need to callback again + return; + } + eventKind = FileWatcherEventKind.Deleted; + } + else if (isPreviouslyDeleted) { + eventKind = FileWatcherEventKind.Created; + } + // If there is no change in modified time, ignore the event + else if (+curr.mtime === +prev.mtime) { + return; + } + else { + // File changed + eventKind = FileWatcherEventKind.Changed; + } + callback(fileName, eventKind); + } + } + function createFileWatcherCallback(callback) { + return function (_fileName, eventKind) { return callback(eventKind === FileWatcherEventKind.Changed ? "change" : "rename", ""); }; + } + function createFsWatchCallbackForFileWatcherCallback(fileName, callback) { + return function (eventName) { + if (eventName === "rename") { + callback(fileName, fileExists(fileName) ? FileWatcherEventKind.Created : FileWatcherEventKind.Deleted); + } + else { + // Change + callback(fileName, FileWatcherEventKind.Changed); + } + }; + } + function createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback) { + return function (eventName, relativeFileName) { + // In watchDirectory we only care about adding and removing files (when event name is + // "rename"); changes made within files are handled by corresponding fileWatchers (when + // event name is "change") + if (eventName === "rename") { + // When deleting a file, the passed baseFileName is null + callback(!relativeFileName ? directoryName : ts.normalizePath(ts.combinePaths(directoryName, relativeFileName))); + } + }; + } + function fsWatch(fileOrDirectory, entryKind, callback, recursive, fallbackPollingWatchFile, pollingInterval) { + var options; + /** Watcher for the file system entry depending on whether it is missing or present */ + var watcher = !fileSystemEntryExists(fileOrDirectory, entryKind) ? + watchMissingFileSystemEntry() : + watchPresentFileSystemEntry(); + return { + close: function () { + // Close the watcher (either existing file system entry watcher or missing file system entry watcher) + watcher.close(); + watcher = undefined; + } + }; + /** + * Invoke the callback with rename and update the watcher if not closed + * @param createWatcher + */ + function invokeCallbackAndUpdateWatcher(createWatcher) { + // Call the callback for current directory + callback("rename", ""); + // If watcher is not closed, update it + if (watcher) { + watcher.close(); + watcher = createWatcher(); + } + } + /** + * Watch the file or directory that is currently present + * and when the watched file or directory is deleted, switch to missing file system entry watcher + */ + function watchPresentFileSystemEntry() { + // Node 4.0 `fs.watch` function supports the "recursive" option on both OSX and Windows + // (ref: https://github.com/nodejs/node/pull/2649 and https://github.com/Microsoft/TypeScript/issues/4643) + if (options === undefined) { + if (isNode4OrLater && (process.platform === "win32" || process.platform === "darwin")) { + options = { persistent: true, recursive: !!recursive }; + } + else { + options = { persistent: true }; + } + } + try { + var presentWatcher = _fs.watch(fileOrDirectory, options, callback); + // Watch the missing file or directory or error + presentWatcher.on("error", function () { return invokeCallbackAndUpdateWatcher(watchMissingFileSystemEntry); }); + return presentWatcher; + } + catch (e) { + // Catch the exception and use polling instead + // Eg. on linux the number of watches are limited and one could easily exhaust watches and the exception ENOSPC is thrown when creating watcher at that point + // so instead of throwing error, use fs.watchFile + return watchPresentFileSystemEntryWithFsWatchFile(); + } + } + /** + * Watch the file or directory using fs.watchFile since fs.watch threw exception + * Eg. on linux the number of watches are limited and one could easily exhaust watches and the exception ENOSPC is thrown when creating watcher at that point + */ + function watchPresentFileSystemEntryWithFsWatchFile() { + return fallbackPollingWatchFile(fileOrDirectory, createFileWatcherCallback(callback), pollingInterval); + } + /** + * Watch the file or directory that is missing + * and switch to existing file or directory when the missing filesystem entry is created + */ + function watchMissingFileSystemEntry() { + return fallbackPollingWatchFile(fileOrDirectory, function (_fileName, eventKind) { + if (eventKind === FileWatcherEventKind.Created && fileSystemEntryExists(fileOrDirectory, entryKind)) { + // Call the callback for current file or directory + // For now it could be callback for the inner directory creation, + // but just return current directory, better than current no-op + invokeCallbackAndUpdateWatcher(watchPresentFileSystemEntry); + } + }, pollingInterval); + } + } + function watchFileUsingFsWatch(fileName, callback, pollingInterval) { + return fsWatch(fileName, 0 /* File */, createFsWatchCallbackForFileWatcherCallback(fileName, callback), /*recursive*/ false, fsWatchFile, pollingInterval); + } + function createWatchFileUsingDynamicWatchFile(watchFile) { + return function (fileName, callback, pollingInterval) { return fsWatch(fileName, 0 /* File */, createFsWatchCallbackForFileWatcherCallback(fileName, callback), /*recursive*/ false, watchFile, pollingInterval); }; + } + function fsWatchDirectory(directoryName, callback, recursive) { + return fsWatch(directoryName, 1 /* Directory */, callback, !!recursive, fsWatchFile); + } + function watchDirectoryUsingFsWatch(directoryName, callback, recursive) { + return fsWatchDirectory(directoryName, createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback), recursive); + } + function createWatchDirectoryUsing(fsWatchFile) { + return function (directoryName, callback) { return fsWatchFile(directoryName, function () { return callback(directoryName); }, PollingInterval.Medium); }; + } + function readFile(fileName, _encoding) { + if (!fileExists(fileName)) { + return undefined; + } + var buffer = _fs.readFileSync(fileName); + var len = buffer.length; + if (len >= 2 && buffer[0] === 0xFE && buffer[1] === 0xFF) { + // Big endian UTF-16 byte order mark detected. Since big endian is not supported by node.js, + // flip all byte pairs and treat as little endian. + len &= ~1; // Round down to a multiple of 2 + for (var i = 0; i < len; i += 2) { + var temp = buffer[i]; + buffer[i] = buffer[i + 1]; + buffer[i + 1] = temp; + } + return buffer.toString("utf16le", 2); + } + if (len >= 2 && buffer[0] === 0xFF && buffer[1] === 0xFE) { + // Little endian UTF-16 byte order mark detected + return buffer.toString("utf16le", 2); + } + if (len >= 3 && buffer[0] === 0xEF && buffer[1] === 0xBB && buffer[2] === 0xBF) { + // UTF-8 byte order mark detected + return buffer.toString("utf8", 3); + } + // Default is UTF-8 with no byte order mark + return buffer.toString("utf8"); + } + function writeFile(fileName, data, writeByteOrderMark) { + // If a BOM is required, emit one + if (writeByteOrderMark) { + data = byteOrderMarkIndicator + data; + } + var fd; + try { + fd = _fs.openSync(fileName, "w"); + _fs.writeSync(fd, data, /*position*/ undefined, "utf8"); + } + finally { + if (fd !== undefined) { + _fs.closeSync(fd); + } + } + } + function getAccessibleFileSystemEntries(path) { + try { + var entries = _fs.readdirSync(path || ".").sort(); + var files = []; + var directories = []; + for (var _i = 0, entries_2 = entries; _i < entries_2.length; _i++) { + var entry = entries_2[_i]; + // This is necessary because on some file system node fails to exclude + // "." and "..". See https://github.com/nodejs/node/issues/4002 + if (entry === "." || entry === "..") { + continue; + } + var name = ts.combinePaths(path, entry); + var stat = void 0; + try { + stat = _fs.statSync(name); + } + catch (e) { + continue; + } + if (stat.isFile()) { + files.push(entry); + } + else if (stat.isDirectory()) { + directories.push(entry); + } + } + return { files: files, directories: directories }; + } + catch (e) { + return ts.emptyFileSystemEntries; + } + } + function readDirectory(path, extensions, excludes, includes, depth) { + return ts.matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, process.cwd(), depth, getAccessibleFileSystemEntries); + } + function fileSystemEntryExists(path, entryKind) { + try { + var stat = _fs.statSync(path); + switch (entryKind) { + case 0 /* File */: return stat.isFile(); + case 1 /* Directory */: return stat.isDirectory(); + default: return false; + } + } + catch (e) { + return false; + } + } + function fileExists(path) { + return fileSystemEntryExists(path, 0 /* File */); + } + function directoryExists(path) { + return fileSystemEntryExists(path, 1 /* Directory */); + } + function getDirectories(path) { + return ts.filter(_fs.readdirSync(path), function (dir) { return fileSystemEntryExists(ts.combinePaths(path, dir), 1 /* Directory */); }); + } + function realpath(path) { + try { + return _fs.realpathSync(path); + } + catch (_a) { + return path; + } + } + function getModifiedTime(path) { + try { + return _fs.statSync(path).mtime; + } + catch (e) { + return undefined; + } + } + function setModifiedTime(path, time) { + try { + _fs.utimesSync(path, time, time); + } + catch (e) { + return; + } + } + function deleteFile(path) { + try { + return _fs.unlinkSync(path); + } + catch (e) { + return; + } + } + /** + * djb2 hashing algorithm + * http://www.cse.yorku.ca/~oz/hash.html + */ + function generateDjb2Hash(data) { + var chars = data.split("").map(function (str) { return str.charCodeAt(0); }); + return "" + chars.reduce(function (prev, curr) { return ((prev << 5) + prev) + curr; }, 5381); + } + function createMD5HashUsingNativeCrypto(data) { + var hash = _crypto.createHash("md5"); + hash.update(data); + return hash.digest("hex"); + } + function createSHA256Hash(data) { + var hash = _crypto.createHash("sha256"); + hash.update(data); + return hash.digest("hex"); + } + } + function getChakraSystem() { + var realpath = ChakraHost.realpath && (function (path) { return ChakraHost.realpath(path); }); + return { + newLine: ChakraHost.newLine || "\r\n", + args: ChakraHost.args, + useCaseSensitiveFileNames: !!ChakraHost.useCaseSensitiveFileNames, + write: ChakraHost.echo, + readFile: function (path, _encoding) { + // encoding is automatically handled by the implementation in ChakraHost + return ChakraHost.readFile(path); + }, + writeFile: function (path, data, writeByteOrderMark) { + // If a BOM is required, emit one + if (writeByteOrderMark) { + data = byteOrderMarkIndicator + data; + } + ChakraHost.writeFile(path, data); + }, + resolvePath: ChakraHost.resolvePath, + fileExists: ChakraHost.fileExists, + deleteFile: ChakraHost.deleteFile, + getModifiedTime: ChakraHost.getModifiedTime, + setModifiedTime: ChakraHost.setModifiedTime, + directoryExists: ChakraHost.directoryExists, + createDirectory: ChakraHost.createDirectory, + getExecutingFilePath: function () { return ChakraHost.executingFile; }, + getCurrentDirectory: function () { return ChakraHost.currentDirectory; }, + getDirectories: ChakraHost.getDirectories, + getEnvironmentVariable: ChakraHost.getEnvironmentVariable || (function () { return ""; }), + readDirectory: function (path, extensions, excludes, includes, _depth) { + var pattern = ts.getFileMatcherPatterns(path, excludes, includes, !!ChakraHost.useCaseSensitiveFileNames, ChakraHost.currentDirectory); + return ChakraHost.readDirectory(path, extensions, pattern.basePaths, pattern.excludePattern, pattern.includeFilePattern, pattern.includeDirectoryPattern); + }, + exit: ChakraHost.quit, + realpath: realpath + }; + } + function recursiveCreateDirectory(directoryPath, sys) { + var basePath = ts.getDirectoryPath(directoryPath); + var shouldCreateParent = basePath !== "" && directoryPath !== basePath && !sys.directoryExists(basePath); + if (shouldCreateParent) { + recursiveCreateDirectory(basePath, sys); + } + if (shouldCreateParent || !sys.directoryExists(directoryPath)) { + sys.createDirectory(directoryPath); + } + } + var sys; + if (typeof ChakraHost !== "undefined") { + sys = getChakraSystem(); + } + else if (typeof process !== "undefined" && process.nextTick && !process.browser && typeof require !== "undefined") { + // process and process.nextTick checks if current environment is node-like + // process.browser check excludes webpack and browserify + sys = getNodeSystem(); + } + if (sys) { + // patch writefile to create folder before writing the file + var originalWriteFile_1 = sys.writeFile; + sys.writeFile = function (path, data, writeBom) { + var directoryPath = ts.getDirectoryPath(ts.normalizeSlashes(path)); + if (directoryPath && !sys.directoryExists(directoryPath)) { + recursiveCreateDirectory(directoryPath, sys); + } + originalWriteFile_1.call(sys, path, data, writeBom); + }; + } + return sys; + })(); + if (ts.sys && ts.sys.getEnvironmentVariable) { + setCustomPollingValues(ts.sys); + ts.Debug.currentAssertionLevel = /^development$/i.test(ts.sys.getEnvironmentVariable("NODE_ENV")) + ? 1 /* Normal */ + : 0 /* None */; + } + if (ts.sys && ts.sys.debugMode) { + ts.Debug.isDebugging = true; + } +})(ts || (ts = {})); +// +// generated from './diagnosticInformationMap.generated.ts' by 'src/compiler' +/* @internal */ +var ts; +(function (ts) { + function diag(code, category, key, message, reportsUnnecessary) { + return { code: code, category: category, key: key, message: message, reportsUnnecessary: reportsUnnecessary }; + } + // tslint:disable-next-line variable-name + ts.Diagnostics = { + Unterminated_string_literal: diag(1002, ts.DiagnosticCategory.Error, "Unterminated_string_literal_1002", "Unterminated string literal."), + Identifier_expected: diag(1003, ts.DiagnosticCategory.Error, "Identifier_expected_1003", "Identifier expected."), + _0_expected: diag(1005, ts.DiagnosticCategory.Error, "_0_expected_1005", "'{0}' expected."), + A_file_cannot_have_a_reference_to_itself: diag(1006, ts.DiagnosticCategory.Error, "A_file_cannot_have_a_reference_to_itself_1006", "A file cannot have a reference to itself."), + Trailing_comma_not_allowed: diag(1009, ts.DiagnosticCategory.Error, "Trailing_comma_not_allowed_1009", "Trailing comma not allowed."), + Asterisk_Slash_expected: diag(1010, ts.DiagnosticCategory.Error, "Asterisk_Slash_expected_1010", "'*/' expected."), + An_element_access_expression_should_take_an_argument: diag(1011, ts.DiagnosticCategory.Error, "An_element_access_expression_should_take_an_argument_1011", "An element access expression should take an argument."), + Unexpected_token: diag(1012, ts.DiagnosticCategory.Error, "Unexpected_token_1012", "Unexpected token."), + A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma: diag(1013, ts.DiagnosticCategory.Error, "A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma_1013", "A rest parameter or binding pattern may not have a trailing comma."), + A_rest_parameter_must_be_last_in_a_parameter_list: diag(1014, ts.DiagnosticCategory.Error, "A_rest_parameter_must_be_last_in_a_parameter_list_1014", "A rest parameter must be last in a parameter list."), + Parameter_cannot_have_question_mark_and_initializer: diag(1015, ts.DiagnosticCategory.Error, "Parameter_cannot_have_question_mark_and_initializer_1015", "Parameter cannot have question mark and initializer."), + A_required_parameter_cannot_follow_an_optional_parameter: diag(1016, ts.DiagnosticCategory.Error, "A_required_parameter_cannot_follow_an_optional_parameter_1016", "A required parameter cannot follow an optional parameter."), + An_index_signature_cannot_have_a_rest_parameter: diag(1017, ts.DiagnosticCategory.Error, "An_index_signature_cannot_have_a_rest_parameter_1017", "An index signature cannot have a rest parameter."), + An_index_signature_parameter_cannot_have_an_accessibility_modifier: diag(1018, ts.DiagnosticCategory.Error, "An_index_signature_parameter_cannot_have_an_accessibility_modifier_1018", "An index signature parameter cannot have an accessibility modifier."), + An_index_signature_parameter_cannot_have_a_question_mark: diag(1019, ts.DiagnosticCategory.Error, "An_index_signature_parameter_cannot_have_a_question_mark_1019", "An index signature parameter cannot have a question mark."), + An_index_signature_parameter_cannot_have_an_initializer: diag(1020, ts.DiagnosticCategory.Error, "An_index_signature_parameter_cannot_have_an_initializer_1020", "An index signature parameter cannot have an initializer."), + An_index_signature_must_have_a_type_annotation: diag(1021, ts.DiagnosticCategory.Error, "An_index_signature_must_have_a_type_annotation_1021", "An index signature must have a type annotation."), + An_index_signature_parameter_must_have_a_type_annotation: diag(1022, ts.DiagnosticCategory.Error, "An_index_signature_parameter_must_have_a_type_annotation_1022", "An index signature parameter must have a type annotation."), + An_index_signature_parameter_type_must_be_string_or_number: diag(1023, ts.DiagnosticCategory.Error, "An_index_signature_parameter_type_must_be_string_or_number_1023", "An index signature parameter type must be 'string' or 'number'."), + readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature: diag(1024, ts.DiagnosticCategory.Error, "readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024", "'readonly' modifier can only appear on a property declaration or index signature."), + Accessibility_modifier_already_seen: diag(1028, ts.DiagnosticCategory.Error, "Accessibility_modifier_already_seen_1028", "Accessibility modifier already seen."), + _0_modifier_must_precede_1_modifier: diag(1029, ts.DiagnosticCategory.Error, "_0_modifier_must_precede_1_modifier_1029", "'{0}' modifier must precede '{1}' modifier."), + _0_modifier_already_seen: diag(1030, ts.DiagnosticCategory.Error, "_0_modifier_already_seen_1030", "'{0}' modifier already seen."), + _0_modifier_cannot_appear_on_a_class_element: diag(1031, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_a_class_element_1031", "'{0}' modifier cannot appear on a class element."), + super_must_be_followed_by_an_argument_list_or_member_access: diag(1034, ts.DiagnosticCategory.Error, "super_must_be_followed_by_an_argument_list_or_member_access_1034", "'super' must be followed by an argument list or member access."), + Only_ambient_modules_can_use_quoted_names: diag(1035, ts.DiagnosticCategory.Error, "Only_ambient_modules_can_use_quoted_names_1035", "Only ambient modules can use quoted names."), + Statements_are_not_allowed_in_ambient_contexts: diag(1036, ts.DiagnosticCategory.Error, "Statements_are_not_allowed_in_ambient_contexts_1036", "Statements are not allowed in ambient contexts."), + A_declare_modifier_cannot_be_used_in_an_already_ambient_context: diag(1038, ts.DiagnosticCategory.Error, "A_declare_modifier_cannot_be_used_in_an_already_ambient_context_1038", "A 'declare' modifier cannot be used in an already ambient context."), + Initializers_are_not_allowed_in_ambient_contexts: diag(1039, ts.DiagnosticCategory.Error, "Initializers_are_not_allowed_in_ambient_contexts_1039", "Initializers are not allowed in ambient contexts."), + _0_modifier_cannot_be_used_in_an_ambient_context: diag(1040, ts.DiagnosticCategory.Error, "_0_modifier_cannot_be_used_in_an_ambient_context_1040", "'{0}' modifier cannot be used in an ambient context."), + _0_modifier_cannot_be_used_with_a_class_declaration: diag(1041, ts.DiagnosticCategory.Error, "_0_modifier_cannot_be_used_with_a_class_declaration_1041", "'{0}' modifier cannot be used with a class declaration."), + _0_modifier_cannot_be_used_here: diag(1042, ts.DiagnosticCategory.Error, "_0_modifier_cannot_be_used_here_1042", "'{0}' modifier cannot be used here."), + _0_modifier_cannot_appear_on_a_data_property: diag(1043, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_a_data_property_1043", "'{0}' modifier cannot appear on a data property."), + _0_modifier_cannot_appear_on_a_module_or_namespace_element: diag(1044, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_a_module_or_namespace_element_1044", "'{0}' modifier cannot appear on a module or namespace element."), + A_0_modifier_cannot_be_used_with_an_interface_declaration: diag(1045, ts.DiagnosticCategory.Error, "A_0_modifier_cannot_be_used_with_an_interface_declaration_1045", "A '{0}' modifier cannot be used with an interface declaration."), + A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file: diag(1046, ts.DiagnosticCategory.Error, "A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file_1046", "A 'declare' modifier is required for a top level declaration in a .d.ts file."), + A_rest_parameter_cannot_be_optional: diag(1047, ts.DiagnosticCategory.Error, "A_rest_parameter_cannot_be_optional_1047", "A rest parameter cannot be optional."), + A_rest_parameter_cannot_have_an_initializer: diag(1048, ts.DiagnosticCategory.Error, "A_rest_parameter_cannot_have_an_initializer_1048", "A rest parameter cannot have an initializer."), + A_set_accessor_must_have_exactly_one_parameter: diag(1049, ts.DiagnosticCategory.Error, "A_set_accessor_must_have_exactly_one_parameter_1049", "A 'set' accessor must have exactly one parameter."), + A_set_accessor_cannot_have_an_optional_parameter: diag(1051, ts.DiagnosticCategory.Error, "A_set_accessor_cannot_have_an_optional_parameter_1051", "A 'set' accessor cannot have an optional parameter."), + A_set_accessor_parameter_cannot_have_an_initializer: diag(1052, ts.DiagnosticCategory.Error, "A_set_accessor_parameter_cannot_have_an_initializer_1052", "A 'set' accessor parameter cannot have an initializer."), + A_set_accessor_cannot_have_rest_parameter: diag(1053, ts.DiagnosticCategory.Error, "A_set_accessor_cannot_have_rest_parameter_1053", "A 'set' accessor cannot have rest parameter."), + A_get_accessor_cannot_have_parameters: diag(1054, ts.DiagnosticCategory.Error, "A_get_accessor_cannot_have_parameters_1054", "A 'get' accessor cannot have parameters."), + Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value: diag(1055, ts.DiagnosticCategory.Error, "Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Prom_1055", "Type '{0}' is not a valid async function return type in ES5/ES3 because it does not refer to a Promise-compatible constructor value."), + Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher: diag(1056, ts.DiagnosticCategory.Error, "Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher_1056", "Accessors are only available when targeting ECMAScript 5 and higher."), + An_async_function_or_method_must_have_a_valid_awaitable_return_type: diag(1057, ts.DiagnosticCategory.Error, "An_async_function_or_method_must_have_a_valid_awaitable_return_type_1057", "An async function or method must have a valid awaitable return type."), + The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1058, ts.DiagnosticCategory.Error, "The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_t_1058", "The return type of an async function must either be a valid promise or must not contain a callable 'then' member."), + A_promise_must_have_a_then_method: diag(1059, ts.DiagnosticCategory.Error, "A_promise_must_have_a_then_method_1059", "A promise must have a 'then' method."), + The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback: diag(1060, ts.DiagnosticCategory.Error, "The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback_1060", "The first parameter of the 'then' method of a promise must be a callback."), + Enum_member_must_have_initializer: diag(1061, ts.DiagnosticCategory.Error, "Enum_member_must_have_initializer_1061", "Enum member must have initializer."), + Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method: diag(1062, ts.DiagnosticCategory.Error, "Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method_1062", "Type is referenced directly or indirectly in the fulfillment callback of its own 'then' method."), + An_export_assignment_cannot_be_used_in_a_namespace: diag(1063, ts.DiagnosticCategory.Error, "An_export_assignment_cannot_be_used_in_a_namespace_1063", "An export assignment cannot be used in a namespace."), + The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type: diag(1064, ts.DiagnosticCategory.Error, "The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_1064", "The return type of an async function or method must be the global Promise type."), + In_ambient_enum_declarations_member_initializer_must_be_constant_expression: diag(1066, ts.DiagnosticCategory.Error, "In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066", "In ambient enum declarations member initializer must be constant expression."), + Unexpected_token_A_constructor_method_accessor_or_property_was_expected: diag(1068, ts.DiagnosticCategory.Error, "Unexpected_token_A_constructor_method_accessor_or_property_was_expected_1068", "Unexpected token. A constructor, method, accessor, or property was expected."), + Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces: diag(1069, ts.DiagnosticCategory.Error, "Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces_1069", "Unexpected token. A type parameter name was expected without curly braces."), + _0_modifier_cannot_appear_on_a_type_member: diag(1070, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_a_type_member_1070", "'{0}' modifier cannot appear on a type member."), + _0_modifier_cannot_appear_on_an_index_signature: diag(1071, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_an_index_signature_1071", "'{0}' modifier cannot appear on an index signature."), + A_0_modifier_cannot_be_used_with_an_import_declaration: diag(1079, ts.DiagnosticCategory.Error, "A_0_modifier_cannot_be_used_with_an_import_declaration_1079", "A '{0}' modifier cannot be used with an import declaration."), + Invalid_reference_directive_syntax: diag(1084, ts.DiagnosticCategory.Error, "Invalid_reference_directive_syntax_1084", "Invalid 'reference' directive syntax."), + Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0: diag(1085, ts.DiagnosticCategory.Error, "Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0_1085", "Octal literals are not available when targeting ECMAScript 5 and higher. Use the syntax '{0}'."), + An_accessor_cannot_be_declared_in_an_ambient_context: diag(1086, ts.DiagnosticCategory.Error, "An_accessor_cannot_be_declared_in_an_ambient_context_1086", "An accessor cannot be declared in an ambient context."), + _0_modifier_cannot_appear_on_a_constructor_declaration: diag(1089, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_a_constructor_declaration_1089", "'{0}' modifier cannot appear on a constructor declaration."), + _0_modifier_cannot_appear_on_a_parameter: diag(1090, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_a_parameter_1090", "'{0}' modifier cannot appear on a parameter."), + Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement: diag(1091, ts.DiagnosticCategory.Error, "Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement_1091", "Only a single variable declaration is allowed in a 'for...in' statement."), + Type_parameters_cannot_appear_on_a_constructor_declaration: diag(1092, ts.DiagnosticCategory.Error, "Type_parameters_cannot_appear_on_a_constructor_declaration_1092", "Type parameters cannot appear on a constructor declaration."), + Type_annotation_cannot_appear_on_a_constructor_declaration: diag(1093, ts.DiagnosticCategory.Error, "Type_annotation_cannot_appear_on_a_constructor_declaration_1093", "Type annotation cannot appear on a constructor declaration."), + An_accessor_cannot_have_type_parameters: diag(1094, ts.DiagnosticCategory.Error, "An_accessor_cannot_have_type_parameters_1094", "An accessor cannot have type parameters."), + A_set_accessor_cannot_have_a_return_type_annotation: diag(1095, ts.DiagnosticCategory.Error, "A_set_accessor_cannot_have_a_return_type_annotation_1095", "A 'set' accessor cannot have a return type annotation."), + An_index_signature_must_have_exactly_one_parameter: diag(1096, ts.DiagnosticCategory.Error, "An_index_signature_must_have_exactly_one_parameter_1096", "An index signature must have exactly one parameter."), + _0_list_cannot_be_empty: diag(1097, ts.DiagnosticCategory.Error, "_0_list_cannot_be_empty_1097", "'{0}' list cannot be empty."), + Type_parameter_list_cannot_be_empty: diag(1098, ts.DiagnosticCategory.Error, "Type_parameter_list_cannot_be_empty_1098", "Type parameter list cannot be empty."), + Type_argument_list_cannot_be_empty: diag(1099, ts.DiagnosticCategory.Error, "Type_argument_list_cannot_be_empty_1099", "Type argument list cannot be empty."), + Invalid_use_of_0_in_strict_mode: diag(1100, ts.DiagnosticCategory.Error, "Invalid_use_of_0_in_strict_mode_1100", "Invalid use of '{0}' in strict mode."), + with_statements_are_not_allowed_in_strict_mode: diag(1101, ts.DiagnosticCategory.Error, "with_statements_are_not_allowed_in_strict_mode_1101", "'with' statements are not allowed in strict mode."), + delete_cannot_be_called_on_an_identifier_in_strict_mode: diag(1102, ts.DiagnosticCategory.Error, "delete_cannot_be_called_on_an_identifier_in_strict_mode_1102", "'delete' cannot be called on an identifier in strict mode."), + A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator: diag(1103, ts.DiagnosticCategory.Error, "A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator_1103", "A 'for-await-of' statement is only allowed within an async function or async generator."), + A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement: diag(1104, ts.DiagnosticCategory.Error, "A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement_1104", "A 'continue' statement can only be used within an enclosing iteration statement."), + A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement: diag(1105, ts.DiagnosticCategory.Error, "A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement_1105", "A 'break' statement can only be used within an enclosing iteration or switch statement."), + Jump_target_cannot_cross_function_boundary: diag(1107, ts.DiagnosticCategory.Error, "Jump_target_cannot_cross_function_boundary_1107", "Jump target cannot cross function boundary."), + A_return_statement_can_only_be_used_within_a_function_body: diag(1108, ts.DiagnosticCategory.Error, "A_return_statement_can_only_be_used_within_a_function_body_1108", "A 'return' statement can only be used within a function body."), + Expression_expected: diag(1109, ts.DiagnosticCategory.Error, "Expression_expected_1109", "Expression expected."), + Type_expected: diag(1110, ts.DiagnosticCategory.Error, "Type_expected_1110", "Type expected."), + A_default_clause_cannot_appear_more_than_once_in_a_switch_statement: diag(1113, ts.DiagnosticCategory.Error, "A_default_clause_cannot_appear_more_than_once_in_a_switch_statement_1113", "A 'default' clause cannot appear more than once in a 'switch' statement."), + Duplicate_label_0: diag(1114, ts.DiagnosticCategory.Error, "Duplicate_label_0_1114", "Duplicate label '{0}'."), + A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement: diag(1115, ts.DiagnosticCategory.Error, "A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement_1115", "A 'continue' statement can only jump to a label of an enclosing iteration statement."), + A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement: diag(1116, ts.DiagnosticCategory.Error, "A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement_1116", "A 'break' statement can only jump to a label of an enclosing statement."), + An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode: diag(1117, ts.DiagnosticCategory.Error, "An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode_1117", "An object literal cannot have multiple properties with the same name in strict mode."), + An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name: diag(1118, ts.DiagnosticCategory.Error, "An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name_1118", "An object literal cannot have multiple get/set accessors with the same name."), + An_object_literal_cannot_have_property_and_accessor_with_the_same_name: diag(1119, ts.DiagnosticCategory.Error, "An_object_literal_cannot_have_property_and_accessor_with_the_same_name_1119", "An object literal cannot have property and accessor with the same name."), + An_export_assignment_cannot_have_modifiers: diag(1120, ts.DiagnosticCategory.Error, "An_export_assignment_cannot_have_modifiers_1120", "An export assignment cannot have modifiers."), + Octal_literals_are_not_allowed_in_strict_mode: diag(1121, ts.DiagnosticCategory.Error, "Octal_literals_are_not_allowed_in_strict_mode_1121", "Octal literals are not allowed in strict mode."), + Variable_declaration_list_cannot_be_empty: diag(1123, ts.DiagnosticCategory.Error, "Variable_declaration_list_cannot_be_empty_1123", "Variable declaration list cannot be empty."), + Digit_expected: diag(1124, ts.DiagnosticCategory.Error, "Digit_expected_1124", "Digit expected."), + Hexadecimal_digit_expected: diag(1125, ts.DiagnosticCategory.Error, "Hexadecimal_digit_expected_1125", "Hexadecimal digit expected."), + Unexpected_end_of_text: diag(1126, ts.DiagnosticCategory.Error, "Unexpected_end_of_text_1126", "Unexpected end of text."), + Invalid_character: diag(1127, ts.DiagnosticCategory.Error, "Invalid_character_1127", "Invalid character."), + Declaration_or_statement_expected: diag(1128, ts.DiagnosticCategory.Error, "Declaration_or_statement_expected_1128", "Declaration or statement expected."), + Statement_expected: diag(1129, ts.DiagnosticCategory.Error, "Statement_expected_1129", "Statement expected."), + case_or_default_expected: diag(1130, ts.DiagnosticCategory.Error, "case_or_default_expected_1130", "'case' or 'default' expected."), + Property_or_signature_expected: diag(1131, ts.DiagnosticCategory.Error, "Property_or_signature_expected_1131", "Property or signature expected."), + Enum_member_expected: diag(1132, ts.DiagnosticCategory.Error, "Enum_member_expected_1132", "Enum member expected."), + Variable_declaration_expected: diag(1134, ts.DiagnosticCategory.Error, "Variable_declaration_expected_1134", "Variable declaration expected."), + Argument_expression_expected: diag(1135, ts.DiagnosticCategory.Error, "Argument_expression_expected_1135", "Argument expression expected."), + Property_assignment_expected: diag(1136, ts.DiagnosticCategory.Error, "Property_assignment_expected_1136", "Property assignment expected."), + Expression_or_comma_expected: diag(1137, ts.DiagnosticCategory.Error, "Expression_or_comma_expected_1137", "Expression or comma expected."), + Parameter_declaration_expected: diag(1138, ts.DiagnosticCategory.Error, "Parameter_declaration_expected_1138", "Parameter declaration expected."), + Type_parameter_declaration_expected: diag(1139, ts.DiagnosticCategory.Error, "Type_parameter_declaration_expected_1139", "Type parameter declaration expected."), + Type_argument_expected: diag(1140, ts.DiagnosticCategory.Error, "Type_argument_expected_1140", "Type argument expected."), + String_literal_expected: diag(1141, ts.DiagnosticCategory.Error, "String_literal_expected_1141", "String literal expected."), + Line_break_not_permitted_here: diag(1142, ts.DiagnosticCategory.Error, "Line_break_not_permitted_here_1142", "Line break not permitted here."), + or_expected: diag(1144, ts.DiagnosticCategory.Error, "or_expected_1144", "'{' or ';' expected."), + Declaration_expected: diag(1146, ts.DiagnosticCategory.Error, "Declaration_expected_1146", "Declaration expected."), + Import_declarations_in_a_namespace_cannot_reference_a_module: diag(1147, ts.DiagnosticCategory.Error, "Import_declarations_in_a_namespace_cannot_reference_a_module_1147", "Import declarations in a namespace cannot reference a module."), + Cannot_use_imports_exports_or_module_augmentations_when_module_is_none: diag(1148, ts.DiagnosticCategory.Error, "Cannot_use_imports_exports_or_module_augmentations_when_module_is_none_1148", "Cannot use imports, exports, or module augmentations when '--module' is 'none'."), + File_name_0_differs_from_already_included_file_name_1_only_in_casing: diag(1149, ts.DiagnosticCategory.Error, "File_name_0_differs_from_already_included_file_name_1_only_in_casing_1149", "File name '{0}' differs from already included file name '{1}' only in casing."), + new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead: diag(1150, ts.DiagnosticCategory.Error, "new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead_1150", "'new T[]' cannot be used to create an array. Use 'new Array()' instead."), + const_declarations_must_be_initialized: diag(1155, ts.DiagnosticCategory.Error, "const_declarations_must_be_initialized_1155", "'const' declarations must be initialized."), + const_declarations_can_only_be_declared_inside_a_block: diag(1156, ts.DiagnosticCategory.Error, "const_declarations_can_only_be_declared_inside_a_block_1156", "'const' declarations can only be declared inside a block."), + let_declarations_can_only_be_declared_inside_a_block: diag(1157, ts.DiagnosticCategory.Error, "let_declarations_can_only_be_declared_inside_a_block_1157", "'let' declarations can only be declared inside a block."), + Unterminated_template_literal: diag(1160, ts.DiagnosticCategory.Error, "Unterminated_template_literal_1160", "Unterminated template literal."), + Unterminated_regular_expression_literal: diag(1161, ts.DiagnosticCategory.Error, "Unterminated_regular_expression_literal_1161", "Unterminated regular expression literal."), + An_object_member_cannot_be_declared_optional: diag(1162, ts.DiagnosticCategory.Error, "An_object_member_cannot_be_declared_optional_1162", "An object member cannot be declared optional."), + A_yield_expression_is_only_allowed_in_a_generator_body: diag(1163, ts.DiagnosticCategory.Error, "A_yield_expression_is_only_allowed_in_a_generator_body_1163", "A 'yield' expression is only allowed in a generator body."), + Computed_property_names_are_not_allowed_in_enums: diag(1164, ts.DiagnosticCategory.Error, "Computed_property_names_are_not_allowed_in_enums_1164", "Computed property names are not allowed in enums."), + A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: diag(1165, ts.DiagnosticCategory.Error, "A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_t_1165", "A computed property name in an ambient context must refer to an expression whose type is a literal type or a 'unique symbol' type."), + A_computed_property_name_in_a_class_property_declaration_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: diag(1166, ts.DiagnosticCategory.Error, "A_computed_property_name_in_a_class_property_declaration_must_refer_to_an_expression_whose_type_is_a_1166", "A computed property name in a class property declaration must refer to an expression whose type is a literal type or a 'unique symbol' type."), + A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: diag(1168, ts.DiagnosticCategory.Error, "A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_ty_1168", "A computed property name in a method overload must refer to an expression whose type is a literal type or a 'unique symbol' type."), + A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: diag(1169, ts.DiagnosticCategory.Error, "A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_1169", "A computed property name in an interface must refer to an expression whose type is a literal type or a 'unique symbol' type."), + A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: diag(1170, ts.DiagnosticCategory.Error, "A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type__1170", "A computed property name in a type literal must refer to an expression whose type is a literal type or a 'unique symbol' type."), + A_comma_expression_is_not_allowed_in_a_computed_property_name: diag(1171, ts.DiagnosticCategory.Error, "A_comma_expression_is_not_allowed_in_a_computed_property_name_1171", "A comma expression is not allowed in a computed property name."), + extends_clause_already_seen: diag(1172, ts.DiagnosticCategory.Error, "extends_clause_already_seen_1172", "'extends' clause already seen."), + extends_clause_must_precede_implements_clause: diag(1173, ts.DiagnosticCategory.Error, "extends_clause_must_precede_implements_clause_1173", "'extends' clause must precede 'implements' clause."), + Classes_can_only_extend_a_single_class: diag(1174, ts.DiagnosticCategory.Error, "Classes_can_only_extend_a_single_class_1174", "Classes can only extend a single class."), + implements_clause_already_seen: diag(1175, ts.DiagnosticCategory.Error, "implements_clause_already_seen_1175", "'implements' clause already seen."), + Interface_declaration_cannot_have_implements_clause: diag(1176, ts.DiagnosticCategory.Error, "Interface_declaration_cannot_have_implements_clause_1176", "Interface declaration cannot have 'implements' clause."), + Binary_digit_expected: diag(1177, ts.DiagnosticCategory.Error, "Binary_digit_expected_1177", "Binary digit expected."), + Octal_digit_expected: diag(1178, ts.DiagnosticCategory.Error, "Octal_digit_expected_1178", "Octal digit expected."), + Unexpected_token_expected: diag(1179, ts.DiagnosticCategory.Error, "Unexpected_token_expected_1179", "Unexpected token. '{' expected."), + Property_destructuring_pattern_expected: diag(1180, ts.DiagnosticCategory.Error, "Property_destructuring_pattern_expected_1180", "Property destructuring pattern expected."), + Array_element_destructuring_pattern_expected: diag(1181, ts.DiagnosticCategory.Error, "Array_element_destructuring_pattern_expected_1181", "Array element destructuring pattern expected."), + A_destructuring_declaration_must_have_an_initializer: diag(1182, ts.DiagnosticCategory.Error, "A_destructuring_declaration_must_have_an_initializer_1182", "A destructuring declaration must have an initializer."), + An_implementation_cannot_be_declared_in_ambient_contexts: diag(1183, ts.DiagnosticCategory.Error, "An_implementation_cannot_be_declared_in_ambient_contexts_1183", "An implementation cannot be declared in ambient contexts."), + Modifiers_cannot_appear_here: diag(1184, ts.DiagnosticCategory.Error, "Modifiers_cannot_appear_here_1184", "Modifiers cannot appear here."), + Merge_conflict_marker_encountered: diag(1185, ts.DiagnosticCategory.Error, "Merge_conflict_marker_encountered_1185", "Merge conflict marker encountered."), + A_rest_element_cannot_have_an_initializer: diag(1186, ts.DiagnosticCategory.Error, "A_rest_element_cannot_have_an_initializer_1186", "A rest element cannot have an initializer."), + A_parameter_property_may_not_be_declared_using_a_binding_pattern: diag(1187, ts.DiagnosticCategory.Error, "A_parameter_property_may_not_be_declared_using_a_binding_pattern_1187", "A parameter property may not be declared using a binding pattern."), + Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement: diag(1188, ts.DiagnosticCategory.Error, "Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement_1188", "Only a single variable declaration is allowed in a 'for...of' statement."), + The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer: diag(1189, ts.DiagnosticCategory.Error, "The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer_1189", "The variable declaration of a 'for...in' statement cannot have an initializer."), + The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer: diag(1190, ts.DiagnosticCategory.Error, "The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer_1190", "The variable declaration of a 'for...of' statement cannot have an initializer."), + An_import_declaration_cannot_have_modifiers: diag(1191, ts.DiagnosticCategory.Error, "An_import_declaration_cannot_have_modifiers_1191", "An import declaration cannot have modifiers."), + Module_0_has_no_default_export: diag(1192, ts.DiagnosticCategory.Error, "Module_0_has_no_default_export_1192", "Module '{0}' has no default export."), + An_export_declaration_cannot_have_modifiers: diag(1193, ts.DiagnosticCategory.Error, "An_export_declaration_cannot_have_modifiers_1193", "An export declaration cannot have modifiers."), + Export_declarations_are_not_permitted_in_a_namespace: diag(1194, ts.DiagnosticCategory.Error, "Export_declarations_are_not_permitted_in_a_namespace_1194", "Export declarations are not permitted in a namespace."), + Catch_clause_variable_cannot_have_a_type_annotation: diag(1196, ts.DiagnosticCategory.Error, "Catch_clause_variable_cannot_have_a_type_annotation_1196", "Catch clause variable cannot have a type annotation."), + Catch_clause_variable_cannot_have_an_initializer: diag(1197, ts.DiagnosticCategory.Error, "Catch_clause_variable_cannot_have_an_initializer_1197", "Catch clause variable cannot have an initializer."), + An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive: diag(1198, ts.DiagnosticCategory.Error, "An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive_1198", "An extended Unicode escape value must be between 0x0 and 0x10FFFF inclusive."), + Unterminated_Unicode_escape_sequence: diag(1199, ts.DiagnosticCategory.Error, "Unterminated_Unicode_escape_sequence_1199", "Unterminated Unicode escape sequence."), + Line_terminator_not_permitted_before_arrow: diag(1200, ts.DiagnosticCategory.Error, "Line_terminator_not_permitted_before_arrow_1200", "Line terminator not permitted before arrow."), + Import_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_import_Asterisk_as_ns_from_mod_import_a_from_mod_import_d_from_mod_or_another_module_format_instead: diag(1202, ts.DiagnosticCategory.Error, "Import_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_import_Asterisk_as_1202", "Import assignment cannot be used when targeting ECMAScript modules. Consider using 'import * as ns from \"mod\"', 'import {a} from \"mod\"', 'import d from \"mod\"', or another module format instead."), + Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or_another_module_format_instead: diag(1203, ts.DiagnosticCategory.Error, "Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or__1203", "Export assignment cannot be used when targeting ECMAScript modules. Consider using 'export default' or another module format instead."), + Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided: diag(1205, ts.DiagnosticCategory.Error, "Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205", "Cannot re-export a type when the '--isolatedModules' flag is provided."), + Decorators_are_not_valid_here: diag(1206, ts.DiagnosticCategory.Error, "Decorators_are_not_valid_here_1206", "Decorators are not valid here."), + Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name: diag(1207, ts.DiagnosticCategory.Error, "Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name_1207", "Decorators cannot be applied to multiple get/set accessors of the same name."), + Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided: diag(1208, ts.DiagnosticCategory.Error, "Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided_1208", "Cannot compile namespaces when the '--isolatedModules' flag is provided."), + Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided: diag(1209, ts.DiagnosticCategory.Error, "Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided_1209", "Ambient const enums are not allowed when the '--isolatedModules' flag is provided."), + Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode: diag(1210, ts.DiagnosticCategory.Error, "Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode_1210", "Invalid use of '{0}'. Class definitions are automatically in strict mode."), + A_class_declaration_without_the_default_modifier_must_have_a_name: diag(1211, ts.DiagnosticCategory.Error, "A_class_declaration_without_the_default_modifier_must_have_a_name_1211", "A class declaration without the 'default' modifier must have a name."), + Identifier_expected_0_is_a_reserved_word_in_strict_mode: diag(1212, ts.DiagnosticCategory.Error, "Identifier_expected_0_is_a_reserved_word_in_strict_mode_1212", "Identifier expected. '{0}' is a reserved word in strict mode."), + Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode: diag(1213, ts.DiagnosticCategory.Error, "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_stric_1213", "Identifier expected. '{0}' is a reserved word in strict mode. Class definitions are automatically in strict mode."), + Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode: diag(1214, ts.DiagnosticCategory.Error, "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode_1214", "Identifier expected. '{0}' is a reserved word in strict mode. Modules are automatically in strict mode."), + Invalid_use_of_0_Modules_are_automatically_in_strict_mode: diag(1215, ts.DiagnosticCategory.Error, "Invalid_use_of_0_Modules_are_automatically_in_strict_mode_1215", "Invalid use of '{0}'. Modules are automatically in strict mode."), + Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules: diag(1216, ts.DiagnosticCategory.Error, "Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules_1216", "Identifier expected. '__esModule' is reserved as an exported marker when transforming ECMAScript modules."), + Export_assignment_is_not_supported_when_module_flag_is_system: diag(1218, ts.DiagnosticCategory.Error, "Export_assignment_is_not_supported_when_module_flag_is_system_1218", "Export assignment is not supported when '--module' flag is 'system'."), + Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_to_remove_this_warning: diag(1219, ts.DiagnosticCategory.Error, "Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_t_1219", "Experimental support for decorators is a feature that is subject to change in a future release. Set the 'experimentalDecorators' option to remove this warning."), + Generators_are_only_available_when_targeting_ECMAScript_2015_or_higher: diag(1220, ts.DiagnosticCategory.Error, "Generators_are_only_available_when_targeting_ECMAScript_2015_or_higher_1220", "Generators are only available when targeting ECMAScript 2015 or higher."), + Generators_are_not_allowed_in_an_ambient_context: diag(1221, ts.DiagnosticCategory.Error, "Generators_are_not_allowed_in_an_ambient_context_1221", "Generators are not allowed in an ambient context."), + An_overload_signature_cannot_be_declared_as_a_generator: diag(1222, ts.DiagnosticCategory.Error, "An_overload_signature_cannot_be_declared_as_a_generator_1222", "An overload signature cannot be declared as a generator."), + _0_tag_already_specified: diag(1223, ts.DiagnosticCategory.Error, "_0_tag_already_specified_1223", "'{0}' tag already specified."), + Signature_0_must_be_a_type_predicate: diag(1224, ts.DiagnosticCategory.Error, "Signature_0_must_be_a_type_predicate_1224", "Signature '{0}' must be a type predicate."), + Cannot_find_parameter_0: diag(1225, ts.DiagnosticCategory.Error, "Cannot_find_parameter_0_1225", "Cannot find parameter '{0}'."), + Type_predicate_0_is_not_assignable_to_1: diag(1226, ts.DiagnosticCategory.Error, "Type_predicate_0_is_not_assignable_to_1_1226", "Type predicate '{0}' is not assignable to '{1}'."), + Parameter_0_is_not_in_the_same_position_as_parameter_1: diag(1227, ts.DiagnosticCategory.Error, "Parameter_0_is_not_in_the_same_position_as_parameter_1_1227", "Parameter '{0}' is not in the same position as parameter '{1}'."), + A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods: diag(1228, ts.DiagnosticCategory.Error, "A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods_1228", "A type predicate is only allowed in return type position for functions and methods."), + A_type_predicate_cannot_reference_a_rest_parameter: diag(1229, ts.DiagnosticCategory.Error, "A_type_predicate_cannot_reference_a_rest_parameter_1229", "A type predicate cannot reference a rest parameter."), + A_type_predicate_cannot_reference_element_0_in_a_binding_pattern: diag(1230, ts.DiagnosticCategory.Error, "A_type_predicate_cannot_reference_element_0_in_a_binding_pattern_1230", "A type predicate cannot reference element '{0}' in a binding pattern."), + An_export_assignment_can_only_be_used_in_a_module: diag(1231, ts.DiagnosticCategory.Error, "An_export_assignment_can_only_be_used_in_a_module_1231", "An export assignment can only be used in a module."), + An_import_declaration_can_only_be_used_in_a_namespace_or_module: diag(1232, ts.DiagnosticCategory.Error, "An_import_declaration_can_only_be_used_in_a_namespace_or_module_1232", "An import declaration can only be used in a namespace or module."), + An_export_declaration_can_only_be_used_in_a_module: diag(1233, ts.DiagnosticCategory.Error, "An_export_declaration_can_only_be_used_in_a_module_1233", "An export declaration can only be used in a module."), + An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file: diag(1234, ts.DiagnosticCategory.Error, "An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file_1234", "An ambient module declaration is only allowed at the top level in a file."), + A_namespace_declaration_is_only_allowed_in_a_namespace_or_module: diag(1235, ts.DiagnosticCategory.Error, "A_namespace_declaration_is_only_allowed_in_a_namespace_or_module_1235", "A namespace declaration is only allowed in a namespace or module."), + The_return_type_of_a_property_decorator_function_must_be_either_void_or_any: diag(1236, ts.DiagnosticCategory.Error, "The_return_type_of_a_property_decorator_function_must_be_either_void_or_any_1236", "The return type of a property decorator function must be either 'void' or 'any'."), + The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any: diag(1237, ts.DiagnosticCategory.Error, "The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any_1237", "The return type of a parameter decorator function must be either 'void' or 'any'."), + Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression: diag(1238, ts.DiagnosticCategory.Error, "Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression_1238", "Unable to resolve signature of class decorator when called as an expression."), + Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression: diag(1239, ts.DiagnosticCategory.Error, "Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression_1239", "Unable to resolve signature of parameter decorator when called as an expression."), + Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression: diag(1240, ts.DiagnosticCategory.Error, "Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression_1240", "Unable to resolve signature of property decorator when called as an expression."), + Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression: diag(1241, ts.DiagnosticCategory.Error, "Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression_1241", "Unable to resolve signature of method decorator when called as an expression."), + abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration: diag(1242, ts.DiagnosticCategory.Error, "abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration_1242", "'abstract' modifier can only appear on a class, method, or property declaration."), + _0_modifier_cannot_be_used_with_1_modifier: diag(1243, ts.DiagnosticCategory.Error, "_0_modifier_cannot_be_used_with_1_modifier_1243", "'{0}' modifier cannot be used with '{1}' modifier."), + Abstract_methods_can_only_appear_within_an_abstract_class: diag(1244, ts.DiagnosticCategory.Error, "Abstract_methods_can_only_appear_within_an_abstract_class_1244", "Abstract methods can only appear within an abstract class."), + Method_0_cannot_have_an_implementation_because_it_is_marked_abstract: diag(1245, ts.DiagnosticCategory.Error, "Method_0_cannot_have_an_implementation_because_it_is_marked_abstract_1245", "Method '{0}' cannot have an implementation because it is marked abstract."), + An_interface_property_cannot_have_an_initializer: diag(1246, ts.DiagnosticCategory.Error, "An_interface_property_cannot_have_an_initializer_1246", "An interface property cannot have an initializer."), + A_type_literal_property_cannot_have_an_initializer: diag(1247, ts.DiagnosticCategory.Error, "A_type_literal_property_cannot_have_an_initializer_1247", "A type literal property cannot have an initializer."), + A_class_member_cannot_have_the_0_keyword: diag(1248, ts.DiagnosticCategory.Error, "A_class_member_cannot_have_the_0_keyword_1248", "A class member cannot have the '{0}' keyword."), + A_decorator_can_only_decorate_a_method_implementation_not_an_overload: diag(1249, ts.DiagnosticCategory.Error, "A_decorator_can_only_decorate_a_method_implementation_not_an_overload_1249", "A decorator can only decorate a method implementation, not an overload."), + Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5: diag(1250, ts.DiagnosticCategory.Error, "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_1250", "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'."), + Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_definitions_are_automatically_in_strict_mode: diag(1251, ts.DiagnosticCategory.Error, "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_d_1251", "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Class definitions are automatically in strict mode."), + Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_are_automatically_in_strict_mode: diag(1252, ts.DiagnosticCategory.Error, "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_1252", "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Modules are automatically in strict mode."), + _0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag: diag(1253, ts.DiagnosticCategory.Error, "_0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag_1253", "'{0}' tag cannot be used independently as a top level JSDoc tag."), + A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_reference: diag(1254, ts.DiagnosticCategory.Error, "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_refere_1254", "A 'const' initializer in an ambient context must be a string or numeric literal or literal enum reference."), + A_definite_assignment_assertion_is_not_permitted_in_this_context: diag(1255, ts.DiagnosticCategory.Error, "A_definite_assignment_assertion_is_not_permitted_in_this_context_1255", "A definite assignment assertion '!' is not permitted in this context."), + A_rest_element_must_be_last_in_a_tuple_type: diag(1256, ts.DiagnosticCategory.Error, "A_rest_element_must_be_last_in_a_tuple_type_1256", "A rest element must be last in a tuple type."), + A_required_element_cannot_follow_an_optional_element: diag(1257, ts.DiagnosticCategory.Error, "A_required_element_cannot_follow_an_optional_element_1257", "A required element cannot follow an optional element."), + with_statements_are_not_allowed_in_an_async_function_block: diag(1300, ts.DiagnosticCategory.Error, "with_statements_are_not_allowed_in_an_async_function_block_1300", "'with' statements are not allowed in an async function block."), + await_expression_is_only_allowed_within_an_async_function: diag(1308, ts.DiagnosticCategory.Error, "await_expression_is_only_allowed_within_an_async_function_1308", "'await' expression is only allowed within an async function."), + can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment: diag(1312, ts.DiagnosticCategory.Error, "can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment_1312", "'=' can only be used in an object literal property inside a destructuring assignment."), + The_body_of_an_if_statement_cannot_be_the_empty_statement: diag(1313, ts.DiagnosticCategory.Error, "The_body_of_an_if_statement_cannot_be_the_empty_statement_1313", "The body of an 'if' statement cannot be the empty statement."), + Global_module_exports_may_only_appear_in_module_files: diag(1314, ts.DiagnosticCategory.Error, "Global_module_exports_may_only_appear_in_module_files_1314", "Global module exports may only appear in module files."), + Global_module_exports_may_only_appear_in_declaration_files: diag(1315, ts.DiagnosticCategory.Error, "Global_module_exports_may_only_appear_in_declaration_files_1315", "Global module exports may only appear in declaration files."), + Global_module_exports_may_only_appear_at_top_level: diag(1316, ts.DiagnosticCategory.Error, "Global_module_exports_may_only_appear_at_top_level_1316", "Global module exports may only appear at top level."), + A_parameter_property_cannot_be_declared_using_a_rest_parameter: diag(1317, ts.DiagnosticCategory.Error, "A_parameter_property_cannot_be_declared_using_a_rest_parameter_1317", "A parameter property cannot be declared using a rest parameter."), + An_abstract_accessor_cannot_have_an_implementation: diag(1318, ts.DiagnosticCategory.Error, "An_abstract_accessor_cannot_have_an_implementation_1318", "An abstract accessor cannot have an implementation."), + A_default_export_can_only_be_used_in_an_ECMAScript_style_module: diag(1319, ts.DiagnosticCategory.Error, "A_default_export_can_only_be_used_in_an_ECMAScript_style_module_1319", "A default export can only be used in an ECMAScript-style module."), + Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1320, ts.DiagnosticCategory.Error, "Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member_1320", "Type of 'await' operand must either be a valid promise or must not contain a callable 'then' member."), + Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1321, ts.DiagnosticCategory.Error, "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321", "Type of 'yield' operand in an async generator must either be a valid promise or must not contain a callable 'then' member."), + Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1322, ts.DiagnosticCategory.Error, "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322", "Type of iterated elements of a 'yield*' operand must either be a valid promise or must not contain a callable 'then' member."), + Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext: diag(1323, ts.DiagnosticCategory.Error, "Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext_1323", "Dynamic import is only supported when '--module' flag is 'commonjs' or 'esNext'."), + Dynamic_import_must_have_one_specifier_as_an_argument: diag(1324, ts.DiagnosticCategory.Error, "Dynamic_import_must_have_one_specifier_as_an_argument_1324", "Dynamic import must have one specifier as an argument."), + Specifier_of_dynamic_import_cannot_be_spread_element: diag(1325, ts.DiagnosticCategory.Error, "Specifier_of_dynamic_import_cannot_be_spread_element_1325", "Specifier of dynamic import cannot be spread element."), + Dynamic_import_cannot_have_type_arguments: diag(1326, ts.DiagnosticCategory.Error, "Dynamic_import_cannot_have_type_arguments_1326", "Dynamic import cannot have type arguments"), + String_literal_with_double_quotes_expected: diag(1327, ts.DiagnosticCategory.Error, "String_literal_with_double_quotes_expected_1327", "String literal with double quotes expected."), + Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_literal: diag(1328, ts.DiagnosticCategory.Error, "Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_li_1328", "Property value can only be string literal, numeric literal, 'true', 'false', 'null', object literal or array literal."), + _0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write_0: diag(1329, ts.DiagnosticCategory.Error, "_0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write__1329", "'{0}' accepts too few arguments to be used as a decorator here. Did you mean to call it first and write '@{0}()'?"), + A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly: diag(1330, ts.DiagnosticCategory.Error, "A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly_1330", "A property of an interface or type literal whose type is a 'unique symbol' type must be 'readonly'."), + A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly: diag(1331, ts.DiagnosticCategory.Error, "A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly_1331", "A property of a class whose type is a 'unique symbol' type must be both 'static' and 'readonly'."), + A_variable_whose_type_is_a_unique_symbol_type_must_be_const: diag(1332, ts.DiagnosticCategory.Error, "A_variable_whose_type_is_a_unique_symbol_type_must_be_const_1332", "A variable whose type is a 'unique symbol' type must be 'const'."), + unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name: diag(1333, ts.DiagnosticCategory.Error, "unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name_1333", "'unique symbol' types may not be used on a variable declaration with a binding name."), + unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement: diag(1334, ts.DiagnosticCategory.Error, "unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement_1334", "'unique symbol' types are only allowed on variables in a variable statement."), + unique_symbol_types_are_not_allowed_here: diag(1335, ts.DiagnosticCategory.Error, "unique_symbol_types_are_not_allowed_here_1335", "'unique symbol' types are not allowed here."), + An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead: diag(1336, ts.DiagnosticCategory.Error, "An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead_1336", "An index signature parameter type cannot be a type alias. Consider writing '[{0}: {1}]: {2}' instead."), + An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead: diag(1337, ts.DiagnosticCategory.Error, "An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead_1337", "An index signature parameter type cannot be a union type. Consider using a mapped object type instead."), + infer_declarations_are_only_permitted_in_the_extends_clause_of_a_conditional_type: diag(1338, ts.DiagnosticCategory.Error, "infer_declarations_are_only_permitted_in_the_extends_clause_of_a_conditional_type_1338", "'infer' declarations are only permitted in the 'extends' clause of a conditional type."), + Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here: diag(1339, ts.DiagnosticCategory.Error, "Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here_1339", "Module '{0}' does not refer to a value, but is used as a value here."), + Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0: diag(1340, ts.DiagnosticCategory.Error, "Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0_1340", "Module '{0}' does not refer to a type, but is used as a type here. Did you mean 'typeof import('{0}')'?"), + Type_arguments_cannot_be_used_here: diag(1342, ts.DiagnosticCategory.Error, "Type_arguments_cannot_be_used_here_1342", "Type arguments cannot be used here."), + The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_options: diag(1343, ts.DiagnosticCategory.Error, "The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_option_1343", "The 'import.meta' meta-property is only allowed using 'ESNext' for the 'target' and 'module' compiler options."), + A_label_is_not_allowed_here: diag(1344, ts.DiagnosticCategory.Error, "A_label_is_not_allowed_here_1344", "'A label is not allowed here."), + An_expression_of_type_void_cannot_be_tested_for_truthiness: diag(1345, ts.DiagnosticCategory.Error, "An_expression_of_type_void_cannot_be_tested_for_truthiness_1345", "An expression of type 'void' cannot be tested for truthiness"), + This_parameter_is_not_allowed_with_use_strict_directive: diag(1346, ts.DiagnosticCategory.Error, "This_parameter_is_not_allowed_with_use_strict_directive_1346", "This parameter is not allowed with 'use strict' directive."), + use_strict_directive_cannot_be_used_with_non_simple_parameter_list: diag(1347, ts.DiagnosticCategory.Error, "use_strict_directive_cannot_be_used_with_non_simple_parameter_list_1347", "'use strict' directive cannot be used with non-simple parameter list."), + Non_simple_parameter_declared_here: diag(1348, ts.DiagnosticCategory.Error, "Non_simple_parameter_declared_here_1348", "Non-simple parameter declared here."), + use_strict_directive_used_here: diag(1349, ts.DiagnosticCategory.Error, "use_strict_directive_used_here_1349", "'use strict' directive used here."), + Print_the_final_configuration_instead_of_building: diag(1350, ts.DiagnosticCategory.Message, "Print_the_final_configuration_instead_of_building_1350", "Print the final configuration instead of building."), + Duplicate_identifier_0: diag(2300, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_2300", "Duplicate identifier '{0}'."), + Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: diag(2301, ts.DiagnosticCategory.Error, "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301", "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor."), + Static_members_cannot_reference_class_type_parameters: diag(2302, ts.DiagnosticCategory.Error, "Static_members_cannot_reference_class_type_parameters_2302", "Static members cannot reference class type parameters."), + Circular_definition_of_import_alias_0: diag(2303, ts.DiagnosticCategory.Error, "Circular_definition_of_import_alias_0_2303", "Circular definition of import alias '{0}'."), + Cannot_find_name_0: diag(2304, ts.DiagnosticCategory.Error, "Cannot_find_name_0_2304", "Cannot find name '{0}'."), + Module_0_has_no_exported_member_1: diag(2305, ts.DiagnosticCategory.Error, "Module_0_has_no_exported_member_1_2305", "Module '{0}' has no exported member '{1}'."), + File_0_is_not_a_module: diag(2306, ts.DiagnosticCategory.Error, "File_0_is_not_a_module_2306", "File '{0}' is not a module."), + Cannot_find_module_0: diag(2307, ts.DiagnosticCategory.Error, "Cannot_find_module_0_2307", "Cannot find module '{0}'."), + Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambiguity: diag(2308, ts.DiagnosticCategory.Error, "Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambig_2308", "Module {0} has already exported a member named '{1}'. Consider explicitly re-exporting to resolve the ambiguity."), + An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements: diag(2309, ts.DiagnosticCategory.Error, "An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements_2309", "An export assignment cannot be used in a module with other exported elements."), + Type_0_recursively_references_itself_as_a_base_type: diag(2310, ts.DiagnosticCategory.Error, "Type_0_recursively_references_itself_as_a_base_type_2310", "Type '{0}' recursively references itself as a base type."), + A_class_may_only_extend_another_class: diag(2311, ts.DiagnosticCategory.Error, "A_class_may_only_extend_another_class_2311", "A class may only extend another class."), + An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_members: diag(2312, ts.DiagnosticCategory.Error, "An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_me_2312", "An interface can only extend an object type or intersection of object types with statically known members."), + Type_parameter_0_has_a_circular_constraint: diag(2313, ts.DiagnosticCategory.Error, "Type_parameter_0_has_a_circular_constraint_2313", "Type parameter '{0}' has a circular constraint."), + Generic_type_0_requires_1_type_argument_s: diag(2314, ts.DiagnosticCategory.Error, "Generic_type_0_requires_1_type_argument_s_2314", "Generic type '{0}' requires {1} type argument(s)."), + Type_0_is_not_generic: diag(2315, ts.DiagnosticCategory.Error, "Type_0_is_not_generic_2315", "Type '{0}' is not generic."), + Global_type_0_must_be_a_class_or_interface_type: diag(2316, ts.DiagnosticCategory.Error, "Global_type_0_must_be_a_class_or_interface_type_2316", "Global type '{0}' must be a class or interface type."), + Global_type_0_must_have_1_type_parameter_s: diag(2317, ts.DiagnosticCategory.Error, "Global_type_0_must_have_1_type_parameter_s_2317", "Global type '{0}' must have {1} type parameter(s)."), + Cannot_find_global_type_0: diag(2318, ts.DiagnosticCategory.Error, "Cannot_find_global_type_0_2318", "Cannot find global type '{0}'."), + Named_property_0_of_types_1_and_2_are_not_identical: diag(2319, ts.DiagnosticCategory.Error, "Named_property_0_of_types_1_and_2_are_not_identical_2319", "Named property '{0}' of types '{1}' and '{2}' are not identical."), + Interface_0_cannot_simultaneously_extend_types_1_and_2: diag(2320, ts.DiagnosticCategory.Error, "Interface_0_cannot_simultaneously_extend_types_1_and_2_2320", "Interface '{0}' cannot simultaneously extend types '{1}' and '{2}'."), + Excessive_stack_depth_comparing_types_0_and_1: diag(2321, ts.DiagnosticCategory.Error, "Excessive_stack_depth_comparing_types_0_and_1_2321", "Excessive stack depth comparing types '{0}' and '{1}'."), + Type_0_is_not_assignable_to_type_1: diag(2322, ts.DiagnosticCategory.Error, "Type_0_is_not_assignable_to_type_1_2322", "Type '{0}' is not assignable to type '{1}'."), + Cannot_redeclare_exported_variable_0: diag(2323, ts.DiagnosticCategory.Error, "Cannot_redeclare_exported_variable_0_2323", "Cannot redeclare exported variable '{0}'."), + Property_0_is_missing_in_type_1: diag(2324, ts.DiagnosticCategory.Error, "Property_0_is_missing_in_type_1_2324", "Property '{0}' is missing in type '{1}'."), + Property_0_is_private_in_type_1_but_not_in_type_2: diag(2325, ts.DiagnosticCategory.Error, "Property_0_is_private_in_type_1_but_not_in_type_2_2325", "Property '{0}' is private in type '{1}' but not in type '{2}'."), + Types_of_property_0_are_incompatible: diag(2326, ts.DiagnosticCategory.Error, "Types_of_property_0_are_incompatible_2326", "Types of property '{0}' are incompatible."), + Property_0_is_optional_in_type_1_but_required_in_type_2: diag(2327, ts.DiagnosticCategory.Error, "Property_0_is_optional_in_type_1_but_required_in_type_2_2327", "Property '{0}' is optional in type '{1}' but required in type '{2}'."), + Types_of_parameters_0_and_1_are_incompatible: diag(2328, ts.DiagnosticCategory.Error, "Types_of_parameters_0_and_1_are_incompatible_2328", "Types of parameters '{0}' and '{1}' are incompatible."), + Index_signature_is_missing_in_type_0: diag(2329, ts.DiagnosticCategory.Error, "Index_signature_is_missing_in_type_0_2329", "Index signature is missing in type '{0}'."), + Index_signatures_are_incompatible: diag(2330, ts.DiagnosticCategory.Error, "Index_signatures_are_incompatible_2330", "Index signatures are incompatible."), + this_cannot_be_referenced_in_a_module_or_namespace_body: diag(2331, ts.DiagnosticCategory.Error, "this_cannot_be_referenced_in_a_module_or_namespace_body_2331", "'this' cannot be referenced in a module or namespace body."), + this_cannot_be_referenced_in_current_location: diag(2332, ts.DiagnosticCategory.Error, "this_cannot_be_referenced_in_current_location_2332", "'this' cannot be referenced in current location."), + this_cannot_be_referenced_in_constructor_arguments: diag(2333, ts.DiagnosticCategory.Error, "this_cannot_be_referenced_in_constructor_arguments_2333", "'this' cannot be referenced in constructor arguments."), + this_cannot_be_referenced_in_a_static_property_initializer: diag(2334, ts.DiagnosticCategory.Error, "this_cannot_be_referenced_in_a_static_property_initializer_2334", "'this' cannot be referenced in a static property initializer."), + super_can_only_be_referenced_in_a_derived_class: diag(2335, ts.DiagnosticCategory.Error, "super_can_only_be_referenced_in_a_derived_class_2335", "'super' can only be referenced in a derived class."), + super_cannot_be_referenced_in_constructor_arguments: diag(2336, ts.DiagnosticCategory.Error, "super_cannot_be_referenced_in_constructor_arguments_2336", "'super' cannot be referenced in constructor arguments."), + Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors: diag(2337, ts.DiagnosticCategory.Error, "Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors_2337", "Super calls are not permitted outside constructors or in nested functions inside constructors."), + super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_derived_class: diag(2338, ts.DiagnosticCategory.Error, "super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_der_2338", "'super' property access is permitted only in a constructor, member function, or member accessor of a derived class."), + Property_0_does_not_exist_on_type_1: diag(2339, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_2339", "Property '{0}' does not exist on type '{1}'."), + Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword: diag(2340, ts.DiagnosticCategory.Error, "Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword_2340", "Only public and protected methods of the base class are accessible via the 'super' keyword."), + Property_0_is_private_and_only_accessible_within_class_1: diag(2341, ts.DiagnosticCategory.Error, "Property_0_is_private_and_only_accessible_within_class_1_2341", "Property '{0}' is private and only accessible within class '{1}'."), + An_index_expression_argument_must_be_of_type_string_number_symbol_or_any: diag(2342, ts.DiagnosticCategory.Error, "An_index_expression_argument_must_be_of_type_string_number_symbol_or_any_2342", "An index expression argument must be of type 'string', 'number', 'symbol', or 'any'."), + This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1: diag(2343, ts.DiagnosticCategory.Error, "This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1_2343", "This syntax requires an imported helper named '{1}', but module '{0}' has no exported member '{1}'."), + Type_0_does_not_satisfy_the_constraint_1: diag(2344, ts.DiagnosticCategory.Error, "Type_0_does_not_satisfy_the_constraint_1_2344", "Type '{0}' does not satisfy the constraint '{1}'."), + Argument_of_type_0_is_not_assignable_to_parameter_of_type_1: diag(2345, ts.DiagnosticCategory.Error, "Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_2345", "Argument of type '{0}' is not assignable to parameter of type '{1}'."), + Call_target_does_not_contain_any_signatures: diag(2346, ts.DiagnosticCategory.Error, "Call_target_does_not_contain_any_signatures_2346", "Call target does not contain any signatures."), + Untyped_function_calls_may_not_accept_type_arguments: diag(2347, ts.DiagnosticCategory.Error, "Untyped_function_calls_may_not_accept_type_arguments_2347", "Untyped function calls may not accept type arguments."), + Value_of_type_0_is_not_callable_Did_you_mean_to_include_new: diag(2348, ts.DiagnosticCategory.Error, "Value_of_type_0_is_not_callable_Did_you_mean_to_include_new_2348", "Value of type '{0}' is not callable. Did you mean to include 'new'?"), + Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures: diag(2349, ts.DiagnosticCategory.Error, "Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatur_2349", "Cannot invoke an expression whose type lacks a call signature. Type '{0}' has no compatible call signatures."), + Only_a_void_function_can_be_called_with_the_new_keyword: diag(2350, ts.DiagnosticCategory.Error, "Only_a_void_function_can_be_called_with_the_new_keyword_2350", "Only a void function can be called with the 'new' keyword."), + Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature: diag(2351, ts.DiagnosticCategory.Error, "Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature_2351", "Cannot use 'new' with an expression whose type lacks a call or construct signature."), + Conversion_of_type_0_to_type_1_may_be_a_mistake_because_neither_type_sufficiently_overlaps_with_the_other_If_this_was_intentional_convert_the_expression_to_unknown_first: diag(2352, ts.DiagnosticCategory.Error, "Conversion_of_type_0_to_type_1_may_be_a_mistake_because_neither_type_sufficiently_overlaps_with_the__2352", "Conversion of type '{0}' to type '{1}' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first."), + Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1: diag(2353, ts.DiagnosticCategory.Error, "Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1_2353", "Object literal may only specify known properties, and '{0}' does not exist in type '{1}'."), + This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found: diag(2354, ts.DiagnosticCategory.Error, "This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found_2354", "This syntax requires an imported helper but module '{0}' cannot be found."), + A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value: diag(2355, ts.DiagnosticCategory.Error, "A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value_2355", "A function whose declared type is neither 'void' nor 'any' must return a value."), + An_arithmetic_operand_must_be_of_type_any_number_bigint_or_an_enum_type: diag(2356, ts.DiagnosticCategory.Error, "An_arithmetic_operand_must_be_of_type_any_number_bigint_or_an_enum_type_2356", "An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type."), + The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access: diag(2357, ts.DiagnosticCategory.Error, "The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access_2357", "The operand of an increment or decrement operator must be a variable or a property access."), + The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter: diag(2358, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_paramete_2358", "The left-hand side of an 'instanceof' expression must be of type 'any', an object type or a type parameter."), + The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_Function_interface_type: diag(2359, ts.DiagnosticCategory.Error, "The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_F_2359", "The right-hand side of an 'instanceof' expression must be of type 'any' or of a type assignable to the 'Function' interface type."), + The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol: diag(2360, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol_2360", "The left-hand side of an 'in' expression must be of type 'any', 'string', 'number', or 'symbol'."), + The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter: diag(2361, ts.DiagnosticCategory.Error, "The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter_2361", "The right-hand side of an 'in' expression must be of type 'any', an object type or a type parameter."), + The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type: diag(2362, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type_2362", "The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type."), + The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type: diag(2363, ts.DiagnosticCategory.Error, "The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type_2363", "The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type."), + The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access: diag(2364, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access_2364", "The left-hand side of an assignment expression must be a variable or a property access."), + Operator_0_cannot_be_applied_to_types_1_and_2: diag(2365, ts.DiagnosticCategory.Error, "Operator_0_cannot_be_applied_to_types_1_and_2_2365", "Operator '{0}' cannot be applied to types '{1}' and '{2}'."), + Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined: diag(2366, ts.DiagnosticCategory.Error, "Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined_2366", "Function lacks ending return statement and return type does not include 'undefined'."), + This_condition_will_always_return_0_since_the_types_1_and_2_have_no_overlap: diag(2367, ts.DiagnosticCategory.Error, "This_condition_will_always_return_0_since_the_types_1_and_2_have_no_overlap_2367", "This condition will always return '{0}' since the types '{1}' and '{2}' have no overlap."), + Type_parameter_name_cannot_be_0: diag(2368, ts.DiagnosticCategory.Error, "Type_parameter_name_cannot_be_0_2368", "Type parameter name cannot be '{0}'."), + A_parameter_property_is_only_allowed_in_a_constructor_implementation: diag(2369, ts.DiagnosticCategory.Error, "A_parameter_property_is_only_allowed_in_a_constructor_implementation_2369", "A parameter property is only allowed in a constructor implementation."), + A_rest_parameter_must_be_of_an_array_type: diag(2370, ts.DiagnosticCategory.Error, "A_rest_parameter_must_be_of_an_array_type_2370", "A rest parameter must be of an array type."), + A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation: diag(2371, ts.DiagnosticCategory.Error, "A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation_2371", "A parameter initializer is only allowed in a function or constructor implementation."), + Parameter_0_cannot_be_referenced_in_its_initializer: diag(2372, ts.DiagnosticCategory.Error, "Parameter_0_cannot_be_referenced_in_its_initializer_2372", "Parameter '{0}' cannot be referenced in its initializer."), + Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it: diag(2373, ts.DiagnosticCategory.Error, "Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it_2373", "Initializer of parameter '{0}' cannot reference identifier '{1}' declared after it."), + Duplicate_string_index_signature: diag(2374, ts.DiagnosticCategory.Error, "Duplicate_string_index_signature_2374", "Duplicate string index signature."), + Duplicate_number_index_signature: diag(2375, ts.DiagnosticCategory.Error, "Duplicate_number_index_signature_2375", "Duplicate number index signature."), + A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_properties_or_has_parameter_properties: diag(2376, ts.DiagnosticCategory.Error, "A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_proper_2376", "A 'super' call must be the first statement in the constructor when a class contains initialized properties or has parameter properties."), + Constructors_for_derived_classes_must_contain_a_super_call: diag(2377, ts.DiagnosticCategory.Error, "Constructors_for_derived_classes_must_contain_a_super_call_2377", "Constructors for derived classes must contain a 'super' call."), + A_get_accessor_must_return_a_value: diag(2378, ts.DiagnosticCategory.Error, "A_get_accessor_must_return_a_value_2378", "A 'get' accessor must return a value."), + Getter_and_setter_accessors_do_not_agree_in_visibility: diag(2379, ts.DiagnosticCategory.Error, "Getter_and_setter_accessors_do_not_agree_in_visibility_2379", "Getter and setter accessors do not agree in visibility."), + get_and_set_accessor_must_have_the_same_type: diag(2380, ts.DiagnosticCategory.Error, "get_and_set_accessor_must_have_the_same_type_2380", "'get' and 'set' accessor must have the same type."), + A_signature_with_an_implementation_cannot_use_a_string_literal_type: diag(2381, ts.DiagnosticCategory.Error, "A_signature_with_an_implementation_cannot_use_a_string_literal_type_2381", "A signature with an implementation cannot use a string literal type."), + Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature: diag(2382, ts.DiagnosticCategory.Error, "Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature_2382", "Specialized overload signature is not assignable to any non-specialized signature."), + Overload_signatures_must_all_be_exported_or_non_exported: diag(2383, ts.DiagnosticCategory.Error, "Overload_signatures_must_all_be_exported_or_non_exported_2383", "Overload signatures must all be exported or non-exported."), + Overload_signatures_must_all_be_ambient_or_non_ambient: diag(2384, ts.DiagnosticCategory.Error, "Overload_signatures_must_all_be_ambient_or_non_ambient_2384", "Overload signatures must all be ambient or non-ambient."), + Overload_signatures_must_all_be_public_private_or_protected: diag(2385, ts.DiagnosticCategory.Error, "Overload_signatures_must_all_be_public_private_or_protected_2385", "Overload signatures must all be public, private or protected."), + Overload_signatures_must_all_be_optional_or_required: diag(2386, ts.DiagnosticCategory.Error, "Overload_signatures_must_all_be_optional_or_required_2386", "Overload signatures must all be optional or required."), + Function_overload_must_be_static: diag(2387, ts.DiagnosticCategory.Error, "Function_overload_must_be_static_2387", "Function overload must be static."), + Function_overload_must_not_be_static: diag(2388, ts.DiagnosticCategory.Error, "Function_overload_must_not_be_static_2388", "Function overload must not be static."), + Function_implementation_name_must_be_0: diag(2389, ts.DiagnosticCategory.Error, "Function_implementation_name_must_be_0_2389", "Function implementation name must be '{0}'."), + Constructor_implementation_is_missing: diag(2390, ts.DiagnosticCategory.Error, "Constructor_implementation_is_missing_2390", "Constructor implementation is missing."), + Function_implementation_is_missing_or_not_immediately_following_the_declaration: diag(2391, ts.DiagnosticCategory.Error, "Function_implementation_is_missing_or_not_immediately_following_the_declaration_2391", "Function implementation is missing or not immediately following the declaration."), + Multiple_constructor_implementations_are_not_allowed: diag(2392, ts.DiagnosticCategory.Error, "Multiple_constructor_implementations_are_not_allowed_2392", "Multiple constructor implementations are not allowed."), + Duplicate_function_implementation: diag(2393, ts.DiagnosticCategory.Error, "Duplicate_function_implementation_2393", "Duplicate function implementation."), + Overload_signature_is_not_compatible_with_function_implementation: diag(2394, ts.DiagnosticCategory.Error, "Overload_signature_is_not_compatible_with_function_implementation_2394", "Overload signature is not compatible with function implementation."), + Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local: diag(2395, ts.DiagnosticCategory.Error, "Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local_2395", "Individual declarations in merged declaration '{0}' must be all exported or all local."), + Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters: diag(2396, ts.DiagnosticCategory.Error, "Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters_2396", "Duplicate identifier 'arguments'. Compiler uses 'arguments' to initialize rest parameters."), + Declaration_name_conflicts_with_built_in_global_identifier_0: diag(2397, ts.DiagnosticCategory.Error, "Declaration_name_conflicts_with_built_in_global_identifier_0_2397", "Declaration name conflicts with built-in global identifier '{0}'."), + Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference: diag(2399, ts.DiagnosticCategory.Error, "Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference_2399", "Duplicate identifier '_this'. Compiler uses variable declaration '_this' to capture 'this' reference."), + Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference: diag(2400, ts.DiagnosticCategory.Error, "Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference_2400", "Expression resolves to variable declaration '_this' that compiler uses to capture 'this' reference."), + Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference: diag(2401, ts.DiagnosticCategory.Error, "Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference_2401", "Duplicate identifier '_super'. Compiler uses '_super' to capture base class reference."), + Expression_resolves_to_super_that_compiler_uses_to_capture_base_class_reference: diag(2402, ts.DiagnosticCategory.Error, "Expression_resolves_to_super_that_compiler_uses_to_capture_base_class_reference_2402", "Expression resolves to '_super' that compiler uses to capture base class reference."), + Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2: diag(2403, ts.DiagnosticCategory.Error, "Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_t_2403", "Subsequent variable declarations must have the same type. Variable '{0}' must be of type '{1}', but here has type '{2}'."), + The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation: diag(2404, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation_2404", "The left-hand side of a 'for...in' statement cannot use a type annotation."), + The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any: diag(2405, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any_2405", "The left-hand side of a 'for...in' statement must be of type 'string' or 'any'."), + The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access: diag(2406, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access_2406", "The left-hand side of a 'for...in' statement must be a variable or a property access."), + The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_but_here_has_type_0: diag(2407, ts.DiagnosticCategory.Error, "The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_but_2407", "The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter, but here has type '{0}'."), + Setters_cannot_return_a_value: diag(2408, ts.DiagnosticCategory.Error, "Setters_cannot_return_a_value_2408", "Setters cannot return a value."), + Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class: diag(2409, ts.DiagnosticCategory.Error, "Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class_2409", "Return type of constructor signature must be assignable to the instance type of the class."), + The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any: diag(2410, ts.DiagnosticCategory.Error, "The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any_2410", "The 'with' statement is not supported. All symbols in a 'with' block will have type 'any'."), + Property_0_of_type_1_is_not_assignable_to_string_index_type_2: diag(2411, ts.DiagnosticCategory.Error, "Property_0_of_type_1_is_not_assignable_to_string_index_type_2_2411", "Property '{0}' of type '{1}' is not assignable to string index type '{2}'."), + Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2: diag(2412, ts.DiagnosticCategory.Error, "Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2_2412", "Property '{0}' of type '{1}' is not assignable to numeric index type '{2}'."), + Numeric_index_type_0_is_not_assignable_to_string_index_type_1: diag(2413, ts.DiagnosticCategory.Error, "Numeric_index_type_0_is_not_assignable_to_string_index_type_1_2413", "Numeric index type '{0}' is not assignable to string index type '{1}'."), + Class_name_cannot_be_0: diag(2414, ts.DiagnosticCategory.Error, "Class_name_cannot_be_0_2414", "Class name cannot be '{0}'."), + Class_0_incorrectly_extends_base_class_1: diag(2415, ts.DiagnosticCategory.Error, "Class_0_incorrectly_extends_base_class_1_2415", "Class '{0}' incorrectly extends base class '{1}'."), + Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2: diag(2416, ts.DiagnosticCategory.Error, "Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2_2416", "Property '{0}' in type '{1}' is not assignable to the same property in base type '{2}'."), + Class_static_side_0_incorrectly_extends_base_class_static_side_1: diag(2417, ts.DiagnosticCategory.Error, "Class_static_side_0_incorrectly_extends_base_class_static_side_1_2417", "Class static side '{0}' incorrectly extends base class static side '{1}'."), + Type_of_computed_property_s_value_is_0_which_is_not_assignable_to_type_1: diag(2418, ts.DiagnosticCategory.Error, "Type_of_computed_property_s_value_is_0_which_is_not_assignable_to_type_1_2418", "Type of computed property's value is '{0}', which is not assignable to type '{1}'."), + Class_0_incorrectly_implements_interface_1: diag(2420, ts.DiagnosticCategory.Error, "Class_0_incorrectly_implements_interface_1_2420", "Class '{0}' incorrectly implements interface '{1}'."), + A_class_can_only_implement_an_object_type_or_intersection_of_object_types_with_statically_known_members: diag(2422, ts.DiagnosticCategory.Error, "A_class_can_only_implement_an_object_type_or_intersection_of_object_types_with_statically_known_memb_2422", "A class can only implement an object type or intersection of object types with statically known members."), + Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor: diag(2423, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_access_2423", "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member accessor."), + Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_property: diag(2424, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_proper_2424", "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member property."), + Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_function: diag(2425, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_functi_2425", "Class '{0}' defines instance member property '{1}', but extended class '{2}' defines it as instance member function."), + Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function: diag(2426, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_functi_2426", "Class '{0}' defines instance member accessor '{1}', but extended class '{2}' defines it as instance member function."), + Interface_name_cannot_be_0: diag(2427, ts.DiagnosticCategory.Error, "Interface_name_cannot_be_0_2427", "Interface name cannot be '{0}'."), + All_declarations_of_0_must_have_identical_type_parameters: diag(2428, ts.DiagnosticCategory.Error, "All_declarations_of_0_must_have_identical_type_parameters_2428", "All declarations of '{0}' must have identical type parameters."), + Interface_0_incorrectly_extends_interface_1: diag(2430, ts.DiagnosticCategory.Error, "Interface_0_incorrectly_extends_interface_1_2430", "Interface '{0}' incorrectly extends interface '{1}'."), + Enum_name_cannot_be_0: diag(2431, ts.DiagnosticCategory.Error, "Enum_name_cannot_be_0_2431", "Enum name cannot be '{0}'."), + In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enum_element: diag(2432, ts.DiagnosticCategory.Error, "In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enu_2432", "In an enum with multiple declarations, only one declaration can omit an initializer for its first enum element."), + A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merged: diag(2433, ts.DiagnosticCategory.Error, "A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merg_2433", "A namespace declaration cannot be in a different file from a class or function with which it is merged."), + A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged: diag(2434, ts.DiagnosticCategory.Error, "A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged_2434", "A namespace declaration cannot be located prior to a class or function with which it is merged."), + Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces: diag(2435, ts.DiagnosticCategory.Error, "Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces_2435", "Ambient modules cannot be nested in other modules or namespaces."), + Ambient_module_declaration_cannot_specify_relative_module_name: diag(2436, ts.DiagnosticCategory.Error, "Ambient_module_declaration_cannot_specify_relative_module_name_2436", "Ambient module declaration cannot specify relative module name."), + Module_0_is_hidden_by_a_local_declaration_with_the_same_name: diag(2437, ts.DiagnosticCategory.Error, "Module_0_is_hidden_by_a_local_declaration_with_the_same_name_2437", "Module '{0}' is hidden by a local declaration with the same name."), + Import_name_cannot_be_0: diag(2438, ts.DiagnosticCategory.Error, "Import_name_cannot_be_0_2438", "Import name cannot be '{0}'."), + Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relative_module_name: diag(2439, ts.DiagnosticCategory.Error, "Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relati_2439", "Import or export declaration in an ambient module declaration cannot reference module through relative module name."), + Import_declaration_conflicts_with_local_declaration_of_0: diag(2440, ts.DiagnosticCategory.Error, "Import_declaration_conflicts_with_local_declaration_of_0_2440", "Import declaration conflicts with local declaration of '{0}'."), + Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module: diag(2441, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_2441", "Duplicate identifier '{0}'. Compiler reserves name '{1}' in top level scope of a module."), + Types_have_separate_declarations_of_a_private_property_0: diag(2442, ts.DiagnosticCategory.Error, "Types_have_separate_declarations_of_a_private_property_0_2442", "Types have separate declarations of a private property '{0}'."), + Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2: diag(2443, ts.DiagnosticCategory.Error, "Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2_2443", "Property '{0}' is protected but type '{1}' is not a class derived from '{2}'."), + Property_0_is_protected_in_type_1_but_public_in_type_2: diag(2444, ts.DiagnosticCategory.Error, "Property_0_is_protected_in_type_1_but_public_in_type_2_2444", "Property '{0}' is protected in type '{1}' but public in type '{2}'."), + Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses: diag(2445, ts.DiagnosticCategory.Error, "Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses_2445", "Property '{0}' is protected and only accessible within class '{1}' and its subclasses."), + Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1: diag(2446, ts.DiagnosticCategory.Error, "Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1_2446", "Property '{0}' is protected and only accessible through an instance of class '{1}'."), + The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead: diag(2447, ts.DiagnosticCategory.Error, "The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead_2447", "The '{0}' operator is not allowed for boolean types. Consider using '{1}' instead."), + Block_scoped_variable_0_used_before_its_declaration: diag(2448, ts.DiagnosticCategory.Error, "Block_scoped_variable_0_used_before_its_declaration_2448", "Block-scoped variable '{0}' used before its declaration."), + Class_0_used_before_its_declaration: diag(2449, ts.DiagnosticCategory.Error, "Class_0_used_before_its_declaration_2449", "Class '{0}' used before its declaration."), + Enum_0_used_before_its_declaration: diag(2450, ts.DiagnosticCategory.Error, "Enum_0_used_before_its_declaration_2450", "Enum '{0}' used before its declaration."), + Cannot_redeclare_block_scoped_variable_0: diag(2451, ts.DiagnosticCategory.Error, "Cannot_redeclare_block_scoped_variable_0_2451", "Cannot redeclare block-scoped variable '{0}'."), + An_enum_member_cannot_have_a_numeric_name: diag(2452, ts.DiagnosticCategory.Error, "An_enum_member_cannot_have_a_numeric_name_2452", "An enum member cannot have a numeric name."), + The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_type_arguments_explicitly: diag(2453, ts.DiagnosticCategory.Error, "The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_typ_2453", "The type argument for type parameter '{0}' cannot be inferred from the usage. Consider specifying the type arguments explicitly."), + Variable_0_is_used_before_being_assigned: diag(2454, ts.DiagnosticCategory.Error, "Variable_0_is_used_before_being_assigned_2454", "Variable '{0}' is used before being assigned."), + Type_argument_candidate_1_is_not_a_valid_type_argument_because_it_is_not_a_supertype_of_candidate_0: diag(2455, ts.DiagnosticCategory.Error, "Type_argument_candidate_1_is_not_a_valid_type_argument_because_it_is_not_a_supertype_of_candidate_0_2455", "Type argument candidate '{1}' is not a valid type argument because it is not a supertype of candidate '{0}'."), + Type_alias_0_circularly_references_itself: diag(2456, ts.DiagnosticCategory.Error, "Type_alias_0_circularly_references_itself_2456", "Type alias '{0}' circularly references itself."), + Type_alias_name_cannot_be_0: diag(2457, ts.DiagnosticCategory.Error, "Type_alias_name_cannot_be_0_2457", "Type alias name cannot be '{0}'."), + An_AMD_module_cannot_have_multiple_name_assignments: diag(2458, ts.DiagnosticCategory.Error, "An_AMD_module_cannot_have_multiple_name_assignments_2458", "An AMD module cannot have multiple name assignments."), + Type_0_has_no_property_1_and_no_string_index_signature: diag(2459, ts.DiagnosticCategory.Error, "Type_0_has_no_property_1_and_no_string_index_signature_2459", "Type '{0}' has no property '{1}' and no string index signature."), + Type_0_has_no_property_1: diag(2460, ts.DiagnosticCategory.Error, "Type_0_has_no_property_1_2460", "Type '{0}' has no property '{1}'."), + Type_0_is_not_an_array_type: diag(2461, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_2461", "Type '{0}' is not an array type."), + A_rest_element_must_be_last_in_a_destructuring_pattern: diag(2462, ts.DiagnosticCategory.Error, "A_rest_element_must_be_last_in_a_destructuring_pattern_2462", "A rest element must be last in a destructuring pattern."), + A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature: diag(2463, ts.DiagnosticCategory.Error, "A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature_2463", "A binding pattern parameter cannot be optional in an implementation signature."), + A_computed_property_name_must_be_of_type_string_number_symbol_or_any: diag(2464, ts.DiagnosticCategory.Error, "A_computed_property_name_must_be_of_type_string_number_symbol_or_any_2464", "A computed property name must be of type 'string', 'number', 'symbol', or 'any'."), + this_cannot_be_referenced_in_a_computed_property_name: diag(2465, ts.DiagnosticCategory.Error, "this_cannot_be_referenced_in_a_computed_property_name_2465", "'this' cannot be referenced in a computed property name."), + super_cannot_be_referenced_in_a_computed_property_name: diag(2466, ts.DiagnosticCategory.Error, "super_cannot_be_referenced_in_a_computed_property_name_2466", "'super' cannot be referenced in a computed property name."), + A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type: diag(2467, ts.DiagnosticCategory.Error, "A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type_2467", "A computed property name cannot reference a type parameter from its containing type."), + Cannot_find_global_value_0: diag(2468, ts.DiagnosticCategory.Error, "Cannot_find_global_value_0_2468", "Cannot find global value '{0}'."), + The_0_operator_cannot_be_applied_to_type_symbol: diag(2469, ts.DiagnosticCategory.Error, "The_0_operator_cannot_be_applied_to_type_symbol_2469", "The '{0}' operator cannot be applied to type 'symbol'."), + Symbol_reference_does_not_refer_to_the_global_Symbol_constructor_object: diag(2470, ts.DiagnosticCategory.Error, "Symbol_reference_does_not_refer_to_the_global_Symbol_constructor_object_2470", "'Symbol' reference does not refer to the global Symbol constructor object."), + A_computed_property_name_of_the_form_0_must_be_of_type_symbol: diag(2471, ts.DiagnosticCategory.Error, "A_computed_property_name_of_the_form_0_must_be_of_type_symbol_2471", "A computed property name of the form '{0}' must be of type 'symbol'."), + Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher: diag(2472, ts.DiagnosticCategory.Error, "Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher_2472", "Spread operator in 'new' expressions is only available when targeting ECMAScript 5 and higher."), + Enum_declarations_must_all_be_const_or_non_const: diag(2473, ts.DiagnosticCategory.Error, "Enum_declarations_must_all_be_const_or_non_const_2473", "Enum declarations must all be const or non-const."), + In_const_enum_declarations_member_initializer_must_be_constant_expression: diag(2474, ts.DiagnosticCategory.Error, "In_const_enum_declarations_member_initializer_must_be_constant_expression_2474", "In 'const' enum declarations member initializer must be constant expression."), + const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment_or_type_query: diag(2475, ts.DiagnosticCategory.Error, "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475", "'const' enums can only be used in property or index access expressions or the right hand side of an import declaration or export assignment or type query."), + A_const_enum_member_can_only_be_accessed_using_a_string_literal: diag(2476, ts.DiagnosticCategory.Error, "A_const_enum_member_can_only_be_accessed_using_a_string_literal_2476", "A const enum member can only be accessed using a string literal."), + const_enum_member_initializer_was_evaluated_to_a_non_finite_value: diag(2477, ts.DiagnosticCategory.Error, "const_enum_member_initializer_was_evaluated_to_a_non_finite_value_2477", "'const' enum member initializer was evaluated to a non-finite value."), + const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN: diag(2478, ts.DiagnosticCategory.Error, "const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN_2478", "'const' enum member initializer was evaluated to disallowed value 'NaN'."), + Property_0_does_not_exist_on_const_enum_1: diag(2479, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_const_enum_1_2479", "Property '{0}' does not exist on 'const' enum '{1}'."), + let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations: diag(2480, ts.DiagnosticCategory.Error, "let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations_2480", "'let' is not allowed to be used as a name in 'let' or 'const' declarations."), + Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1: diag(2481, ts.DiagnosticCategory.Error, "Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1_2481", "Cannot initialize outer scoped variable '{0}' in the same scope as block scoped declaration '{1}'."), + The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation: diag(2483, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation_2483", "The left-hand side of a 'for...of' statement cannot use a type annotation."), + Export_declaration_conflicts_with_exported_declaration_of_0: diag(2484, ts.DiagnosticCategory.Error, "Export_declaration_conflicts_with_exported_declaration_of_0_2484", "Export declaration conflicts with exported declaration of '{0}'."), + The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access: diag(2487, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access_2487", "The left-hand side of a 'for...of' statement must be a variable or a property access."), + Type_0_must_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2488, ts.DiagnosticCategory.Error, "Type_0_must_have_a_Symbol_iterator_method_that_returns_an_iterator_2488", "Type '{0}' must have a '[Symbol.iterator]()' method that returns an iterator."), + An_iterator_must_have_a_next_method: diag(2489, ts.DiagnosticCategory.Error, "An_iterator_must_have_a_next_method_2489", "An iterator must have a 'next()' method."), + The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property: diag(2490, ts.DiagnosticCategory.Error, "The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property_2490", "The type returned by the 'next()' method of an iterator must have a 'value' property."), + The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern: diag(2491, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern_2491", "The left-hand side of a 'for...in' statement cannot be a destructuring pattern."), + Cannot_redeclare_identifier_0_in_catch_clause: diag(2492, ts.DiagnosticCategory.Error, "Cannot_redeclare_identifier_0_in_catch_clause_2492", "Cannot redeclare identifier '{0}' in catch clause."), + Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2: diag(2493, ts.DiagnosticCategory.Error, "Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2_2493", "Tuple type '{0}' with length '{1}' cannot be assigned to tuple with length '{2}'."), + Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher: diag(2494, ts.DiagnosticCategory.Error, "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494", "Using a string in a 'for...of' statement is only supported in ECMAScript 5 and higher."), + Type_0_is_not_an_array_type_or_a_string_type: diag(2495, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_a_string_type_2495", "Type '{0}' is not an array type or a string type."), + The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_standard_function_expression: diag(2496, ts.DiagnosticCategory.Error, "The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_stand_2496", "The 'arguments' object cannot be referenced in an arrow function in ES3 and ES5. Consider using a standard function expression."), + Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct: diag(2497, ts.DiagnosticCategory.Error, "Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct_2497", "Module '{0}' resolves to a non-module entity and cannot be imported using this construct."), + Module_0_uses_export_and_cannot_be_used_with_export_Asterisk: diag(2498, ts.DiagnosticCategory.Error, "Module_0_uses_export_and_cannot_be_used_with_export_Asterisk_2498", "Module '{0}' uses 'export =' and cannot be used with 'export *'."), + An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments: diag(2499, ts.DiagnosticCategory.Error, "An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments_2499", "An interface can only extend an identifier/qualified-name with optional type arguments."), + A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments: diag(2500, ts.DiagnosticCategory.Error, "A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments_2500", "A class can only implement an identifier/qualified-name with optional type arguments."), + A_rest_element_cannot_contain_a_binding_pattern: diag(2501, ts.DiagnosticCategory.Error, "A_rest_element_cannot_contain_a_binding_pattern_2501", "A rest element cannot contain a binding pattern."), + _0_is_referenced_directly_or_indirectly_in_its_own_type_annotation: diag(2502, ts.DiagnosticCategory.Error, "_0_is_referenced_directly_or_indirectly_in_its_own_type_annotation_2502", "'{0}' is referenced directly or indirectly in its own type annotation."), + Cannot_find_namespace_0: diag(2503, ts.DiagnosticCategory.Error, "Cannot_find_namespace_0_2503", "Cannot find namespace '{0}'."), + Type_0_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator: diag(2504, ts.DiagnosticCategory.Error, "Type_0_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator_2504", "Type '{0}' must have a '[Symbol.asyncIterator]()' method that returns an async iterator."), + A_generator_cannot_have_a_void_type_annotation: diag(2505, ts.DiagnosticCategory.Error, "A_generator_cannot_have_a_void_type_annotation_2505", "A generator cannot have a 'void' type annotation."), + _0_is_referenced_directly_or_indirectly_in_its_own_base_expression: diag(2506, ts.DiagnosticCategory.Error, "_0_is_referenced_directly_or_indirectly_in_its_own_base_expression_2506", "'{0}' is referenced directly or indirectly in its own base expression."), + Type_0_is_not_a_constructor_function_type: diag(2507, ts.DiagnosticCategory.Error, "Type_0_is_not_a_constructor_function_type_2507", "Type '{0}' is not a constructor function type."), + No_base_constructor_has_the_specified_number_of_type_arguments: diag(2508, ts.DiagnosticCategory.Error, "No_base_constructor_has_the_specified_number_of_type_arguments_2508", "No base constructor has the specified number of type arguments."), + Base_constructor_return_type_0_is_not_an_object_type_or_intersection_of_object_types_with_statically_known_members: diag(2509, ts.DiagnosticCategory.Error, "Base_constructor_return_type_0_is_not_an_object_type_or_intersection_of_object_types_with_statically_2509", "Base constructor return type '{0}' is not an object type or intersection of object types with statically known members."), + Base_constructors_must_all_have_the_same_return_type: diag(2510, ts.DiagnosticCategory.Error, "Base_constructors_must_all_have_the_same_return_type_2510", "Base constructors must all have the same return type."), + Cannot_create_an_instance_of_an_abstract_class: diag(2511, ts.DiagnosticCategory.Error, "Cannot_create_an_instance_of_an_abstract_class_2511", "Cannot create an instance of an abstract class."), + Overload_signatures_must_all_be_abstract_or_non_abstract: diag(2512, ts.DiagnosticCategory.Error, "Overload_signatures_must_all_be_abstract_or_non_abstract_2512", "Overload signatures must all be abstract or non-abstract."), + Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression: diag(2513, ts.DiagnosticCategory.Error, "Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression_2513", "Abstract method '{0}' in class '{1}' cannot be accessed via super expression."), + Classes_containing_abstract_methods_must_be_marked_abstract: diag(2514, ts.DiagnosticCategory.Error, "Classes_containing_abstract_methods_must_be_marked_abstract_2514", "Classes containing abstract methods must be marked abstract."), + Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2: diag(2515, ts.DiagnosticCategory.Error, "Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2_2515", "Non-abstract class '{0}' does not implement inherited abstract member '{1}' from class '{2}'."), + All_declarations_of_an_abstract_method_must_be_consecutive: diag(2516, ts.DiagnosticCategory.Error, "All_declarations_of_an_abstract_method_must_be_consecutive_2516", "All declarations of an abstract method must be consecutive."), + Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type: diag(2517, ts.DiagnosticCategory.Error, "Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type_2517", "Cannot assign an abstract constructor type to a non-abstract constructor type."), + A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard: diag(2518, ts.DiagnosticCategory.Error, "A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard_2518", "A 'this'-based type guard is not compatible with a parameter-based type guard."), + An_async_iterator_must_have_a_next_method: diag(2519, ts.DiagnosticCategory.Error, "An_async_iterator_must_have_a_next_method_2519", "An async iterator must have a 'next()' method."), + Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions: diag(2520, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions_2520", "Duplicate identifier '{0}'. Compiler uses declaration '{1}' to support async functions."), + Expression_resolves_to_variable_declaration_0_that_compiler_uses_to_support_async_functions: diag(2521, ts.DiagnosticCategory.Error, "Expression_resolves_to_variable_declaration_0_that_compiler_uses_to_support_async_functions_2521", "Expression resolves to variable declaration '{0}' that compiler uses to support async functions."), + The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_using_a_standard_function_or_method: diag(2522, ts.DiagnosticCategory.Error, "The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_usi_2522", "The 'arguments' object cannot be referenced in an async function or method in ES3 and ES5. Consider using a standard function or method."), + yield_expressions_cannot_be_used_in_a_parameter_initializer: diag(2523, ts.DiagnosticCategory.Error, "yield_expressions_cannot_be_used_in_a_parameter_initializer_2523", "'yield' expressions cannot be used in a parameter initializer."), + await_expressions_cannot_be_used_in_a_parameter_initializer: diag(2524, ts.DiagnosticCategory.Error, "await_expressions_cannot_be_used_in_a_parameter_initializer_2524", "'await' expressions cannot be used in a parameter initializer."), + Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value: diag(2525, ts.DiagnosticCategory.Error, "Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value_2525", "Initializer provides no value for this binding element and the binding element has no default value."), + A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface: diag(2526, ts.DiagnosticCategory.Error, "A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface_2526", "A 'this' type is available only in a non-static member of a class or interface."), + The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary: diag(2527, ts.DiagnosticCategory.Error, "The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary_2527", "The inferred type of '{0}' references an inaccessible '{1}' type. A type annotation is necessary."), + A_module_cannot_have_multiple_default_exports: diag(2528, ts.DiagnosticCategory.Error, "A_module_cannot_have_multiple_default_exports_2528", "A module cannot have multiple default exports."), + Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_functions: diag(2529, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_func_2529", "Duplicate identifier '{0}'. Compiler reserves name '{1}' in top level scope of a module containing async functions."), + Property_0_is_incompatible_with_index_signature: diag(2530, ts.DiagnosticCategory.Error, "Property_0_is_incompatible_with_index_signature_2530", "Property '{0}' is incompatible with index signature."), + Object_is_possibly_null: diag(2531, ts.DiagnosticCategory.Error, "Object_is_possibly_null_2531", "Object is possibly 'null'."), + Object_is_possibly_undefined: diag(2532, ts.DiagnosticCategory.Error, "Object_is_possibly_undefined_2532", "Object is possibly 'undefined'."), + Object_is_possibly_null_or_undefined: diag(2533, ts.DiagnosticCategory.Error, "Object_is_possibly_null_or_undefined_2533", "Object is possibly 'null' or 'undefined'."), + A_function_returning_never_cannot_have_a_reachable_end_point: diag(2534, ts.DiagnosticCategory.Error, "A_function_returning_never_cannot_have_a_reachable_end_point_2534", "A function returning 'never' cannot have a reachable end point."), + Enum_type_0_has_members_with_initializers_that_are_not_literals: diag(2535, ts.DiagnosticCategory.Error, "Enum_type_0_has_members_with_initializers_that_are_not_literals_2535", "Enum type '{0}' has members with initializers that are not literals."), + Type_0_cannot_be_used_to_index_type_1: diag(2536, ts.DiagnosticCategory.Error, "Type_0_cannot_be_used_to_index_type_1_2536", "Type '{0}' cannot be used to index type '{1}'."), + Type_0_has_no_matching_index_signature_for_type_1: diag(2537, ts.DiagnosticCategory.Error, "Type_0_has_no_matching_index_signature_for_type_1_2537", "Type '{0}' has no matching index signature for type '{1}'."), + Type_0_cannot_be_used_as_an_index_type: diag(2538, ts.DiagnosticCategory.Error, "Type_0_cannot_be_used_as_an_index_type_2538", "Type '{0}' cannot be used as an index type."), + Cannot_assign_to_0_because_it_is_not_a_variable: diag(2539, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_not_a_variable_2539", "Cannot assign to '{0}' because it is not a variable."), + Cannot_assign_to_0_because_it_is_a_read_only_property: diag(2540, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_a_read_only_property_2540", "Cannot assign to '{0}' because it is a read-only property."), + The_target_of_an_assignment_must_be_a_variable_or_a_property_access: diag(2541, ts.DiagnosticCategory.Error, "The_target_of_an_assignment_must_be_a_variable_or_a_property_access_2541", "The target of an assignment must be a variable or a property access."), + Index_signature_in_type_0_only_permits_reading: diag(2542, ts.DiagnosticCategory.Error, "Index_signature_in_type_0_only_permits_reading_2542", "Index signature in type '{0}' only permits reading."), + Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference: diag(2543, ts.DiagnosticCategory.Error, "Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_me_2543", "Duplicate identifier '_newTarget'. Compiler uses variable declaration '_newTarget' to capture 'new.target' meta-property reference."), + Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta_property_reference: diag(2544, ts.DiagnosticCategory.Error, "Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta__2544", "Expression resolves to variable declaration '_newTarget' that compiler uses to capture 'new.target' meta-property reference."), + A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any: diag(2545, ts.DiagnosticCategory.Error, "A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any_2545", "A mixin class must have a constructor with a single rest parameter of type 'any[]'."), + Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1: diag(2546, ts.DiagnosticCategory.Error, "Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1_2546", "Property '{0}' has conflicting declarations and is inaccessible in type '{1}'."), + The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property: diag(2547, ts.DiagnosticCategory.Error, "The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value__2547", "The type returned by the 'next()' method of an async iterator must be a promise for a type with a 'value' property."), + Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2548, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548", "Type '{0}' is not an array type or does not have a '[Symbol.iterator]()' method that returns an iterator."), + Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2549, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549", "Type '{0}' is not an array type or a string type or does not have a '[Symbol.iterator]()' method that returns an iterator."), + Property_0_does_not_exist_on_type_1_Did_you_mean_2: diag(2551, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551", "Property '{0}' does not exist on type '{1}'. Did you mean '{2}'?"), + Cannot_find_name_0_Did_you_mean_1: diag(2552, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Did_you_mean_1_2552", "Cannot find name '{0}'. Did you mean '{1}'?"), + Computed_values_are_not_permitted_in_an_enum_with_string_valued_members: diag(2553, ts.DiagnosticCategory.Error, "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553", "Computed values are not permitted in an enum with string valued members."), + Expected_0_arguments_but_got_1: diag(2554, ts.DiagnosticCategory.Error, "Expected_0_arguments_but_got_1_2554", "Expected {0} arguments, but got {1}."), + Expected_at_least_0_arguments_but_got_1: diag(2555, ts.DiagnosticCategory.Error, "Expected_at_least_0_arguments_but_got_1_2555", "Expected at least {0} arguments, but got {1}."), + Expected_0_arguments_but_got_1_or_more: diag(2556, ts.DiagnosticCategory.Error, "Expected_0_arguments_but_got_1_or_more_2556", "Expected {0} arguments, but got {1} or more."), + Expected_at_least_0_arguments_but_got_1_or_more: diag(2557, ts.DiagnosticCategory.Error, "Expected_at_least_0_arguments_but_got_1_or_more_2557", "Expected at least {0} arguments, but got {1} or more."), + Expected_0_type_arguments_but_got_1: diag(2558, ts.DiagnosticCategory.Error, "Expected_0_type_arguments_but_got_1_2558", "Expected {0} type arguments, but got {1}."), + Type_0_has_no_properties_in_common_with_type_1: diag(2559, ts.DiagnosticCategory.Error, "Type_0_has_no_properties_in_common_with_type_1_2559", "Type '{0}' has no properties in common with type '{1}'."), + Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it: diag(2560, ts.DiagnosticCategory.Error, "Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it_2560", "Value of type '{0}' has no properties in common with type '{1}'. Did you mean to call it?"), + Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_write_2: diag(2561, ts.DiagnosticCategory.Error, "Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_writ_2561", "Object literal may only specify known properties, but '{0}' does not exist in type '{1}'. Did you mean to write '{2}'?"), + Base_class_expressions_cannot_reference_class_type_parameters: diag(2562, ts.DiagnosticCategory.Error, "Base_class_expressions_cannot_reference_class_type_parameters_2562", "Base class expressions cannot reference class type parameters."), + The_containing_function_or_module_body_is_too_large_for_control_flow_analysis: diag(2563, ts.DiagnosticCategory.Error, "The_containing_function_or_module_body_is_too_large_for_control_flow_analysis_2563", "The containing function or module body is too large for control flow analysis."), + Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor: diag(2564, ts.DiagnosticCategory.Error, "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor_2564", "Property '{0}' has no initializer and is not definitely assigned in the constructor."), + Property_0_is_used_before_being_assigned: diag(2565, ts.DiagnosticCategory.Error, "Property_0_is_used_before_being_assigned_2565", "Property '{0}' is used before being assigned."), + A_rest_element_cannot_have_a_property_name: diag(2566, ts.DiagnosticCategory.Error, "A_rest_element_cannot_have_a_property_name_2566", "A rest element cannot have a property name."), + Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations: diag(2567, ts.DiagnosticCategory.Error, "Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations_2567", "Enum declarations can only merge with namespace or other enum declarations."), + Type_0_is_not_an_array_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators: diag(2568, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators_2568", "Type '{0}' is not an array type. Use compiler option '--downlevelIteration' to allow iterating of iterators."), + Type_0_is_not_an_array_type_or_a_string_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators: diag(2569, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_a_string_type_Use_compiler_option_downlevelIteration_to_allow_iterati_2569", "Type '{0}' is not an array type or a string type. Use compiler option '--downlevelIteration' to allow iterating of iterators."), + Property_0_does_not_exist_on_type_1_Did_you_forget_to_use_await: diag(2570, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_Did_you_forget_to_use_await_2570", "Property '{0}' does not exist on type '{1}'. Did you forget to use 'await'?"), + Object_is_of_type_unknown: diag(2571, ts.DiagnosticCategory.Error, "Object_is_of_type_unknown_2571", "Object is of type 'unknown'."), + Rest_signatures_are_incompatible: diag(2572, ts.DiagnosticCategory.Error, "Rest_signatures_are_incompatible_2572", "Rest signatures are incompatible."), + Property_0_is_incompatible_with_rest_element_type: diag(2573, ts.DiagnosticCategory.Error, "Property_0_is_incompatible_with_rest_element_type_2573", "Property '{0}' is incompatible with rest element type."), + A_rest_element_type_must_be_an_array_type: diag(2574, ts.DiagnosticCategory.Error, "A_rest_element_type_must_be_an_array_type_2574", "A rest element type must be an array type."), + No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments: diag(2575, ts.DiagnosticCategory.Error, "No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments_2575", "No overload expects {0} arguments, but overloads do exist that expect either {1} or {2} arguments."), + Property_0_is_a_static_member_of_type_1: diag(2576, ts.DiagnosticCategory.Error, "Property_0_is_a_static_member_of_type_1_2576", "Property '{0}' is a static member of type '{1}'"), + Return_type_annotation_circularly_references_itself: diag(2577, ts.DiagnosticCategory.Error, "Return_type_annotation_circularly_references_itself_2577", "Return type annotation circularly references itself."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_and_then_add_node_to_the_types_field_in_your_tsconfig: diag(2580, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_and_th_2580", "Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i @types/node` and then add `node` to the types field in your tsconfig."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_and_then_add_jquery_to_the_types_field_in_your_tsconfig: diag(2581, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_an_2581", "Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i @types/jquery` and then add `jquery` to the types field in your tsconfig."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha_and_then_add_jest_or_mocha_to_the_types_field_in_your_tsconfig: diag(2582, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashje_2582", "Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha` and then add `jest` or `mocha` to the types field in your tsconfig."), + Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later: diag(2583, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2583", "Cannot find name '{0}'. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later."), + Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom: diag(2584, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2584", "Cannot find name '{0}'. Do you need to change your target library? Try changing the `lib` compiler option to include 'dom'."), + _0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later: diag(2585, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_2585", "'{0}' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later."), + Enum_type_0_circularly_references_itself: diag(2586, ts.DiagnosticCategory.Error, "Enum_type_0_circularly_references_itself_2586", "Enum type '{0}' circularly references itself."), + JSDoc_type_0_circularly_references_itself: diag(2587, ts.DiagnosticCategory.Error, "JSDoc_type_0_circularly_references_itself_2587", "JSDoc type '{0}' circularly references itself."), + Cannot_assign_to_0_because_it_is_a_constant: diag(2588, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_a_constant_2588", "Cannot assign to '{0}' because it is a constant."), + JSX_element_attributes_type_0_may_not_be_a_union_type: diag(2600, ts.DiagnosticCategory.Error, "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", "JSX element attributes type '{0}' may not be a union type."), + The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: diag(2601, ts.DiagnosticCategory.Error, "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", "The return type of a JSX element constructor must return an object type."), + JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: diag(2602, ts.DiagnosticCategory.Error, "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist."), + Property_0_in_type_1_is_not_assignable_to_type_2: diag(2603, ts.DiagnosticCategory.Error, "Property_0_in_type_1_is_not_assignable_to_type_2_2603", "Property '{0}' in type '{1}' is not assignable to type '{2}'."), + JSX_element_type_0_does_not_have_any_construct_or_call_signatures: diag(2604, ts.DiagnosticCategory.Error, "JSX_element_type_0_does_not_have_any_construct_or_call_signatures_2604", "JSX element type '{0}' does not have any construct or call signatures."), + JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements: diag(2605, ts.DiagnosticCategory.Error, "JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements_2605", "JSX element type '{0}' is not a constructor function for JSX elements."), + Property_0_of_JSX_spread_attribute_is_not_assignable_to_target_property: diag(2606, ts.DiagnosticCategory.Error, "Property_0_of_JSX_spread_attribute_is_not_assignable_to_target_property_2606", "Property '{0}' of JSX spread attribute is not assignable to target property."), + JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property: diag(2607, ts.DiagnosticCategory.Error, "JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property_2607", "JSX element class does not support attributes because it does not have a '{0}' property."), + The_global_type_JSX_0_may_not_have_more_than_one_property: diag(2608, ts.DiagnosticCategory.Error, "The_global_type_JSX_0_may_not_have_more_than_one_property_2608", "The global type 'JSX.{0}' may not have more than one property."), + JSX_spread_child_must_be_an_array_type: diag(2609, ts.DiagnosticCategory.Error, "JSX_spread_child_must_be_an_array_type_2609", "JSX spread child must be an array type."), + Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity: diag(2649, ts.DiagnosticCategory.Error, "Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity_2649", "Cannot augment module '{0}' with value exports because it resolves to a non-module entity."), + A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums: diag(2651, ts.DiagnosticCategory.Error, "A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_memb_2651", "A member initializer in a enum declaration cannot reference members declared after it, including members defined in other enums."), + Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead: diag(2652, ts.DiagnosticCategory.Error, "Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_d_2652", "Merged declaration '{0}' cannot include a default export declaration. Consider adding a separate 'export default {0}' declaration instead."), + Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1: diag(2653, ts.DiagnosticCategory.Error, "Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1_2653", "Non-abstract class expression does not implement inherited abstract member '{0}' from class '{1}'."), + Exported_external_package_typings_file_cannot_contain_tripleslash_references_Please_contact_the_package_author_to_update_the_package_definition: diag(2654, ts.DiagnosticCategory.Error, "Exported_external_package_typings_file_cannot_contain_tripleslash_references_Please_contact_the_pack_2654", "Exported external package typings file cannot contain tripleslash references. Please contact the package author to update the package definition."), + Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_the_package_definition: diag(2656, ts.DiagnosticCategory.Error, "Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_2656", "Exported external package typings file '{0}' is not a module. Please contact the package author to update the package definition."), + JSX_expressions_must_have_one_parent_element: diag(2657, ts.DiagnosticCategory.Error, "JSX_expressions_must_have_one_parent_element_2657", "JSX expressions must have one parent element."), + Type_0_provides_no_match_for_the_signature_1: diag(2658, ts.DiagnosticCategory.Error, "Type_0_provides_no_match_for_the_signature_1_2658", "Type '{0}' provides no match for the signature '{1}'."), + super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_higher: diag(2659, ts.DiagnosticCategory.Error, "super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_highe_2659", "'super' is only allowed in members of object literal expressions when option 'target' is 'ES2015' or higher."), + super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions: diag(2660, ts.DiagnosticCategory.Error, "super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions_2660", "'super' can only be referenced in members of derived classes or object literal expressions."), + Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module: diag(2661, ts.DiagnosticCategory.Error, "Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module_2661", "Cannot export '{0}'. Only local declarations can be exported from a module."), + Cannot_find_name_0_Did_you_mean_the_static_member_1_0: diag(2662, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Did_you_mean_the_static_member_1_0_2662", "Cannot find name '{0}'. Did you mean the static member '{1}.{0}'?"), + Cannot_find_name_0_Did_you_mean_the_instance_member_this_0: diag(2663, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Did_you_mean_the_instance_member_this_0_2663", "Cannot find name '{0}'. Did you mean the instance member 'this.{0}'?"), + Invalid_module_name_in_augmentation_module_0_cannot_be_found: diag(2664, ts.DiagnosticCategory.Error, "Invalid_module_name_in_augmentation_module_0_cannot_be_found_2664", "Invalid module name in augmentation, module '{0}' cannot be found."), + Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented: diag(2665, ts.DiagnosticCategory.Error, "Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augm_2665", "Invalid module name in augmentation. Module '{0}' resolves to an untyped module at '{1}', which cannot be augmented."), + Exports_and_export_assignments_are_not_permitted_in_module_augmentations: diag(2666, ts.DiagnosticCategory.Error, "Exports_and_export_assignments_are_not_permitted_in_module_augmentations_2666", "Exports and export assignments are not permitted in module augmentations."), + Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_module: diag(2667, ts.DiagnosticCategory.Error, "Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_mod_2667", "Imports are not permitted in module augmentations. Consider moving them to the enclosing external module."), + export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always_visible: diag(2668, ts.DiagnosticCategory.Error, "export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always__2668", "'export' modifier cannot be applied to ambient modules and module augmentations since they are always visible."), + Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_declarations: diag(2669, ts.DiagnosticCategory.Error, "Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_2669", "Augmentations for the global scope can only be directly nested in external modules or ambient module declarations."), + Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambient_context: diag(2670, ts.DiagnosticCategory.Error, "Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambien_2670", "Augmentations for the global scope should have 'declare' modifier unless they appear in already ambient context."), + Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity: diag(2671, ts.DiagnosticCategory.Error, "Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity_2671", "Cannot augment module '{0}' because it resolves to a non-module entity."), + Cannot_assign_a_0_constructor_type_to_a_1_constructor_type: diag(2672, ts.DiagnosticCategory.Error, "Cannot_assign_a_0_constructor_type_to_a_1_constructor_type_2672", "Cannot assign a '{0}' constructor type to a '{1}' constructor type."), + Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration: diag(2673, ts.DiagnosticCategory.Error, "Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration_2673", "Constructor of class '{0}' is private and only accessible within the class declaration."), + Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration: diag(2674, ts.DiagnosticCategory.Error, "Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration_2674", "Constructor of class '{0}' is protected and only accessible within the class declaration."), + Cannot_extend_a_class_0_Class_constructor_is_marked_as_private: diag(2675, ts.DiagnosticCategory.Error, "Cannot_extend_a_class_0_Class_constructor_is_marked_as_private_2675", "Cannot extend a class '{0}'. Class constructor is marked as private."), + Accessors_must_both_be_abstract_or_non_abstract: diag(2676, ts.DiagnosticCategory.Error, "Accessors_must_both_be_abstract_or_non_abstract_2676", "Accessors must both be abstract or non-abstract."), + A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type: diag(2677, ts.DiagnosticCategory.Error, "A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type_2677", "A type predicate's type must be assignable to its parameter's type."), + Type_0_is_not_comparable_to_type_1: diag(2678, ts.DiagnosticCategory.Error, "Type_0_is_not_comparable_to_type_1_2678", "Type '{0}' is not comparable to type '{1}'."), + A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void: diag(2679, ts.DiagnosticCategory.Error, "A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void_2679", "A function that is called with the 'new' keyword cannot have a 'this' type that is 'void'."), + A_0_parameter_must_be_the_first_parameter: diag(2680, ts.DiagnosticCategory.Error, "A_0_parameter_must_be_the_first_parameter_2680", "A '{0}' parameter must be the first parameter."), + A_constructor_cannot_have_a_this_parameter: diag(2681, ts.DiagnosticCategory.Error, "A_constructor_cannot_have_a_this_parameter_2681", "A constructor cannot have a 'this' parameter."), + get_and_set_accessor_must_have_the_same_this_type: diag(2682, ts.DiagnosticCategory.Error, "get_and_set_accessor_must_have_the_same_this_type_2682", "'get' and 'set' accessor must have the same 'this' type."), + this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation: diag(2683, ts.DiagnosticCategory.Error, "this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_2683", "'this' implicitly has type 'any' because it does not have a type annotation."), + The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1: diag(2684, ts.DiagnosticCategory.Error, "The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1_2684", "The 'this' context of type '{0}' is not assignable to method's 'this' of type '{1}'."), + The_this_types_of_each_signature_are_incompatible: diag(2685, ts.DiagnosticCategory.Error, "The_this_types_of_each_signature_are_incompatible_2685", "The 'this' types of each signature are incompatible."), + _0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead: diag(2686, ts.DiagnosticCategory.Error, "_0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead_2686", "'{0}' refers to a UMD global, but the current file is a module. Consider adding an import instead."), + All_declarations_of_0_must_have_identical_modifiers: diag(2687, ts.DiagnosticCategory.Error, "All_declarations_of_0_must_have_identical_modifiers_2687", "All declarations of '{0}' must have identical modifiers."), + Cannot_find_type_definition_file_for_0: diag(2688, ts.DiagnosticCategory.Error, "Cannot_find_type_definition_file_for_0_2688", "Cannot find type definition file for '{0}'."), + Cannot_extend_an_interface_0_Did_you_mean_implements: diag(2689, ts.DiagnosticCategory.Error, "Cannot_extend_an_interface_0_Did_you_mean_implements_2689", "Cannot extend an interface '{0}'. Did you mean 'implements'?"), + An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead: diag(2691, ts.DiagnosticCategory.Error, "An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead_2691", "An import path cannot end with a '{0}' extension. Consider importing '{1}' instead."), + _0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible: diag(2692, ts.DiagnosticCategory.Error, "_0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible_2692", "'{0}' is a primitive, but '{1}' is a wrapper object. Prefer using '{0}' when possible."), + _0_only_refers_to_a_type_but_is_being_used_as_a_value_here: diag(2693, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_2693", "'{0}' only refers to a type, but is being used as a value here."), + Namespace_0_has_no_exported_member_1: diag(2694, ts.DiagnosticCategory.Error, "Namespace_0_has_no_exported_member_1_2694", "Namespace '{0}' has no exported member '{1}'."), + Left_side_of_comma_operator_is_unused_and_has_no_side_effects: diag(2695, ts.DiagnosticCategory.Error, "Left_side_of_comma_operator_is_unused_and_has_no_side_effects_2695", "Left side of comma operator is unused and has no side effects.", /*reportsUnnecessary*/ true), + The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead: diag(2696, ts.DiagnosticCategory.Error, "The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead_2696", "The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead?"), + An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option: diag(2697, ts.DiagnosticCategory.Error, "An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_in_2697", "An async function or method must return a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your `--lib` option."), + Spread_types_may_only_be_created_from_object_types: diag(2698, ts.DiagnosticCategory.Error, "Spread_types_may_only_be_created_from_object_types_2698", "Spread types may only be created from object types."), + Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1: diag(2699, ts.DiagnosticCategory.Error, "Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1_2699", "Static property '{0}' conflicts with built-in property 'Function.{0}' of constructor function '{1}'."), + Rest_types_may_only_be_created_from_object_types: diag(2700, ts.DiagnosticCategory.Error, "Rest_types_may_only_be_created_from_object_types_2700", "Rest types may only be created from object types."), + The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access: diag(2701, ts.DiagnosticCategory.Error, "The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access_2701", "The target of an object rest assignment must be a variable or a property access."), + _0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here: diag(2702, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here_2702", "'{0}' only refers to a type, but is being used as a namespace here."), + The_operand_of_a_delete_operator_must_be_a_property_reference: diag(2703, ts.DiagnosticCategory.Error, "The_operand_of_a_delete_operator_must_be_a_property_reference_2703", "The operand of a delete operator must be a property reference."), + The_operand_of_a_delete_operator_cannot_be_a_read_only_property: diag(2704, ts.DiagnosticCategory.Error, "The_operand_of_a_delete_operator_cannot_be_a_read_only_property_2704", "The operand of a delete operator cannot be a read-only property."), + An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option: diag(2705, ts.DiagnosticCategory.Error, "An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_de_2705", "An async function or method in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your `--lib` option."), + Required_type_parameters_may_not_follow_optional_type_parameters: diag(2706, ts.DiagnosticCategory.Error, "Required_type_parameters_may_not_follow_optional_type_parameters_2706", "Required type parameters may not follow optional type parameters."), + Generic_type_0_requires_between_1_and_2_type_arguments: diag(2707, ts.DiagnosticCategory.Error, "Generic_type_0_requires_between_1_and_2_type_arguments_2707", "Generic type '{0}' requires between {1} and {2} type arguments."), + Cannot_use_namespace_0_as_a_value: diag(2708, ts.DiagnosticCategory.Error, "Cannot_use_namespace_0_as_a_value_2708", "Cannot use namespace '{0}' as a value."), + Cannot_use_namespace_0_as_a_type: diag(2709, ts.DiagnosticCategory.Error, "Cannot_use_namespace_0_as_a_type_2709", "Cannot use namespace '{0}' as a type."), + _0_are_specified_twice_The_attribute_named_0_will_be_overwritten: diag(2710, ts.DiagnosticCategory.Error, "_0_are_specified_twice_The_attribute_named_0_will_be_overwritten_2710", "'{0}' are specified twice. The attribute named '{0}' will be overwritten."), + A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option: diag(2711, ts.DiagnosticCategory.Error, "A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES20_2711", "A dynamic import call returns a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your `--lib` option."), + A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option: diag(2712, ts.DiagnosticCategory.Error, "A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declarat_2712", "A dynamic import call in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your `--lib` option."), + Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_property_1_in_0_with_0_1: diag(2713, ts.DiagnosticCategory.Error, "Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_p_2713", "Cannot access '{0}.{1}' because '{0}' is a type, but not a namespace. Did you mean to retrieve the type of the property '{1}' in '{0}' with '{0}[\"{1}\"]'?"), + The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context: diag(2714, ts.DiagnosticCategory.Error, "The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context_2714", "The expression of an export assignment must be an identifier or qualified name in an ambient context."), + Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor: diag(2715, ts.DiagnosticCategory.Error, "Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor_2715", "Abstract property '{0}' in class '{1}' cannot be accessed in the constructor."), + Type_parameter_0_has_a_circular_default: diag(2716, ts.DiagnosticCategory.Error, "Type_parameter_0_has_a_circular_default_2716", "Type parameter '{0}' has a circular default."), + Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_type_2: diag(2717, ts.DiagnosticCategory.Error, "Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_t_2717", "Subsequent property declarations must have the same type. Property '{0}' must be of type '{1}', but here has type '{2}'."), + Duplicate_declaration_0: diag(2718, ts.DiagnosticCategory.Error, "Duplicate_declaration_0_2718", "Duplicate declaration '{0}'."), + Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated: diag(2719, ts.DiagnosticCategory.Error, "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_2719", "Type '{0}' is not assignable to type '{1}'. Two different types with this name exist, but they are unrelated."), + Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass: diag(2720, ts.DiagnosticCategory.Error, "Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclas_2720", "Class '{0}' incorrectly implements class '{1}'. Did you mean to extend '{1}' and inherit its members as a subclass?"), + Cannot_invoke_an_object_which_is_possibly_null: diag(2721, ts.DiagnosticCategory.Error, "Cannot_invoke_an_object_which_is_possibly_null_2721", "Cannot invoke an object which is possibly 'null'."), + Cannot_invoke_an_object_which_is_possibly_undefined: diag(2722, ts.DiagnosticCategory.Error, "Cannot_invoke_an_object_which_is_possibly_undefined_2722", "Cannot invoke an object which is possibly 'undefined'."), + Cannot_invoke_an_object_which_is_possibly_null_or_undefined: diag(2723, ts.DiagnosticCategory.Error, "Cannot_invoke_an_object_which_is_possibly_null_or_undefined_2723", "Cannot invoke an object which is possibly 'null' or 'undefined'."), + Module_0_has_no_exported_member_1_Did_you_mean_2: diag(2724, ts.DiagnosticCategory.Error, "Module_0_has_no_exported_member_1_Did_you_mean_2_2724", "Module '{0}' has no exported member '{1}'. Did you mean '{2}'?"), + Class_name_cannot_be_Object_when_targeting_ES5_with_module_0: diag(2725, ts.DiagnosticCategory.Error, "Class_name_cannot_be_Object_when_targeting_ES5_with_module_0_2725", "Class name cannot be 'Object' when targeting ES5 with module {0}."), + Cannot_find_lib_definition_for_0: diag(2726, ts.DiagnosticCategory.Error, "Cannot_find_lib_definition_for_0_2726", "Cannot find lib definition for '{0}'."), + Cannot_find_lib_definition_for_0_Did_you_mean_1: diag(2727, ts.DiagnosticCategory.Error, "Cannot_find_lib_definition_for_0_Did_you_mean_1_2727", "Cannot find lib definition for '{0}'. Did you mean '{1}'?"), + _0_is_declared_here: diag(2728, ts.DiagnosticCategory.Message, "_0_is_declared_here_2728", "'{0}' is declared here."), + Property_0_is_used_before_its_initialization: diag(2729, ts.DiagnosticCategory.Error, "Property_0_is_used_before_its_initialization_2729", "Property '{0}' is used before its initialization."), + An_arrow_function_cannot_have_a_this_parameter: diag(2730, ts.DiagnosticCategory.Error, "An_arrow_function_cannot_have_a_this_parameter_2730", "An arrow function cannot have a 'this' parameter."), + Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_in_String: diag(2731, ts.DiagnosticCategory.Error, "Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_i_2731", "Implicit conversion of a 'symbol' to a 'string' will fail at runtime. Consider wrapping this expression in 'String(...)'."), + Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension: diag(2732, ts.DiagnosticCategory.Error, "Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension_2732", "Cannot find module '{0}'. Consider using '--resolveJsonModule' to import module with '.json' extension"), + It_is_highly_likely_that_you_are_missing_a_semicolon: diag(2734, ts.DiagnosticCategory.Error, "It_is_highly_likely_that_you_are_missing_a_semicolon_2734", "It is highly likely that you are missing a semicolon."), + Did_you_mean_for_0_to_be_constrained_to_type_new_args_Colon_any_1: diag(2735, ts.DiagnosticCategory.Error, "Did_you_mean_for_0_to_be_constrained_to_type_new_args_Colon_any_1_2735", "Did you mean for '{0}' to be constrained to type 'new (...args: any[]) => {1}'?"), + Operator_0_cannot_be_applied_to_type_1: diag(2736, ts.DiagnosticCategory.Error, "Operator_0_cannot_be_applied_to_type_1_2736", "Operator '{0}' cannot be applied to type '{1}'."), + BigInt_literals_are_not_available_when_targeting_lower_than_ESNext: diag(2737, ts.DiagnosticCategory.Error, "BigInt_literals_are_not_available_when_targeting_lower_than_ESNext_2737", "BigInt literals are not available when targeting lower than ESNext."), + An_outer_value_of_this_is_shadowed_by_this_container: diag(2738, ts.DiagnosticCategory.Message, "An_outer_value_of_this_is_shadowed_by_this_container_2738", "An outer value of 'this' is shadowed by this container."), + Type_0_is_missing_the_following_properties_from_type_1_Colon_2: diag(2739, ts.DiagnosticCategory.Error, "Type_0_is_missing_the_following_properties_from_type_1_Colon_2_2739", "Type '{0}' is missing the following properties from type '{1}': {2}"), + Type_0_is_missing_the_following_properties_from_type_1_Colon_2_and_3_more: diag(2740, ts.DiagnosticCategory.Error, "Type_0_is_missing_the_following_properties_from_type_1_Colon_2_and_3_more_2740", "Type '{0}' is missing the following properties from type '{1}': {2}, and {3} more."), + Property_0_is_missing_in_type_1_but_required_in_type_2: diag(2741, ts.DiagnosticCategory.Error, "Property_0_is_missing_in_type_1_but_required_in_type_2_2741", "Property '{0}' is missing in type '{1}' but required in type '{2}'."), + The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_annotation_is_necessary: diag(2742, ts.DiagnosticCategory.Error, "The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_a_2742", "The inferred type of '{0}' cannot be named without a reference to '{1}'. This is likely not portable. A type annotation is necessary."), + Import_declaration_0_is_using_private_name_1: diag(4000, ts.DiagnosticCategory.Error, "Import_declaration_0_is_using_private_name_1_4000", "Import declaration '{0}' is using private name '{1}'."), + Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: diag(4002, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", "Type parameter '{0}' of exported class has or is using private name '{1}'."), + Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: diag(4004, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", "Type parameter '{0}' of exported interface has or is using private name '{1}'."), + Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1: diag(4006, ts.DiagnosticCategory.Error, "Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4006", "Type parameter '{0}' of constructor signature from exported interface has or is using private name '{1}'."), + Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1: diag(4008, ts.DiagnosticCategory.Error, "Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4008", "Type parameter '{0}' of call signature from exported interface has or is using private name '{1}'."), + Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1: diag(4010, ts.DiagnosticCategory.Error, "Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4010", "Type parameter '{0}' of public static method from exported class has or is using private name '{1}'."), + Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1: diag(4012, ts.DiagnosticCategory.Error, "Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4012", "Type parameter '{0}' of public method from exported class has or is using private name '{1}'."), + Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1: diag(4014, ts.DiagnosticCategory.Error, "Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4014", "Type parameter '{0}' of method from exported interface has or is using private name '{1}'."), + Type_parameter_0_of_exported_function_has_or_is_using_private_name_1: diag(4016, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_function_has_or_is_using_private_name_1_4016", "Type parameter '{0}' of exported function has or is using private name '{1}'."), + Implements_clause_of_exported_class_0_has_or_is_using_private_name_1: diag(4019, ts.DiagnosticCategory.Error, "Implements_clause_of_exported_class_0_has_or_is_using_private_name_1_4019", "Implements clause of exported class '{0}' has or is using private name '{1}'."), + extends_clause_of_exported_class_0_has_or_is_using_private_name_1: diag(4020, ts.DiagnosticCategory.Error, "extends_clause_of_exported_class_0_has_or_is_using_private_name_1_4020", "'extends' clause of exported class '{0}' has or is using private name '{1}'."), + extends_clause_of_exported_interface_0_has_or_is_using_private_name_1: diag(4022, ts.DiagnosticCategory.Error, "extends_clause_of_exported_interface_0_has_or_is_using_private_name_1_4022", "'extends' clause of exported interface '{0}' has or is using private name '{1}'."), + Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4023, ts.DiagnosticCategory.Error, "Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4023", "Exported variable '{0}' has or is using name '{1}' from external module {2} but cannot be named."), + Exported_variable_0_has_or_is_using_name_1_from_private_module_2: diag(4024, ts.DiagnosticCategory.Error, "Exported_variable_0_has_or_is_using_name_1_from_private_module_2_4024", "Exported variable '{0}' has or is using name '{1}' from private module '{2}'."), + Exported_variable_0_has_or_is_using_private_name_1: diag(4025, ts.DiagnosticCategory.Error, "Exported_variable_0_has_or_is_using_private_name_1_4025", "Exported variable '{0}' has or is using private name '{1}'."), + Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4026, ts.DiagnosticCategory.Error, "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot__4026", "Public static property '{0}' of exported class has or is using name '{1}' from external module {2} but cannot be named."), + Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4027, ts.DiagnosticCategory.Error, "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4027", "Public static property '{0}' of exported class has or is using name '{1}' from private module '{2}'."), + Public_static_property_0_of_exported_class_has_or_is_using_private_name_1: diag(4028, ts.DiagnosticCategory.Error, "Public_static_property_0_of_exported_class_has_or_is_using_private_name_1_4028", "Public static property '{0}' of exported class has or is using private name '{1}'."), + Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4029, ts.DiagnosticCategory.Error, "Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_name_4029", "Public property '{0}' of exported class has or is using name '{1}' from external module {2} but cannot be named."), + Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4030, ts.DiagnosticCategory.Error, "Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4030", "Public property '{0}' of exported class has or is using name '{1}' from private module '{2}'."), + Public_property_0_of_exported_class_has_or_is_using_private_name_1: diag(4031, ts.DiagnosticCategory.Error, "Public_property_0_of_exported_class_has_or_is_using_private_name_1_4031", "Public property '{0}' of exported class has or is using private name '{1}'."), + Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4032, ts.DiagnosticCategory.Error, "Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4032", "Property '{0}' of exported interface has or is using name '{1}' from private module '{2}'."), + Property_0_of_exported_interface_has_or_is_using_private_name_1: diag(4033, ts.DiagnosticCategory.Error, "Property_0_of_exported_interface_has_or_is_using_private_name_1_4033", "Property '{0}' of exported interface has or is using private name '{1}'."), + Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4034, ts.DiagnosticCategory.Error, "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_name_1_from_private_mod_4034", "Parameter type of public static setter '{0}' from exported class has or is using name '{1}' from private module '{2}'."), + Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1: diag(4035, ts.DiagnosticCategory.Error, "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1_4035", "Parameter type of public static setter '{0}' from exported class has or is using private name '{1}'."), + Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4036, ts.DiagnosticCategory.Error, "Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2_4036", "Parameter type of public setter '{0}' from exported class has or is using name '{1}' from private module '{2}'."), + Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_private_name_1: diag(4037, ts.DiagnosticCategory.Error, "Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_private_name_1_4037", "Parameter type of public setter '{0}' from exported class has or is using private name '{1}'."), + Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4038, ts.DiagnosticCategory.Error, "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_external_modul_4038", "Return type of public static getter '{0}' from exported class has or is using name '{1}' from external module {2} but cannot be named."), + Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4039, ts.DiagnosticCategory.Error, "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_4039", "Return type of public static getter '{0}' from exported class has or is using name '{1}' from private module '{2}'."), + Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_private_name_1: diag(4040, ts.DiagnosticCategory.Error, "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_private_name_1_4040", "Return type of public static getter '{0}' from exported class has or is using private name '{1}'."), + Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4041, ts.DiagnosticCategory.Error, "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_4041", "Return type of public getter '{0}' from exported class has or is using name '{1}' from external module {2} but cannot be named."), + Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4042, ts.DiagnosticCategory.Error, "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2_4042", "Return type of public getter '{0}' from exported class has or is using name '{1}' from private module '{2}'."), + Return_type_of_public_getter_0_from_exported_class_has_or_is_using_private_name_1: diag(4043, ts.DiagnosticCategory.Error, "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_private_name_1_4043", "Return type of public getter '{0}' from exported class has or is using private name '{1}'."), + Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1: diag(4044, ts.DiagnosticCategory.Error, "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_mod_4044", "Return type of constructor signature from exported interface has or is using name '{0}' from private module '{1}'."), + Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0: diag(4045, ts.DiagnosticCategory.Error, "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0_4045", "Return type of constructor signature from exported interface has or is using private name '{0}'."), + Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1: diag(4046, ts.DiagnosticCategory.Error, "Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4046", "Return type of call signature from exported interface has or is using name '{0}' from private module '{1}'."), + Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0: diag(4047, ts.DiagnosticCategory.Error, "Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0_4047", "Return type of call signature from exported interface has or is using private name '{0}'."), + Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1: diag(4048, ts.DiagnosticCategory.Error, "Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4048", "Return type of index signature from exported interface has or is using name '{0}' from private module '{1}'."), + Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0: diag(4049, ts.DiagnosticCategory.Error, "Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0_4049", "Return type of index signature from exported interface has or is using private name '{0}'."), + Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: diag(4050, ts.DiagnosticCategory.Error, "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module__4050", "Return type of public static method from exported class has or is using name '{0}' from external module {1} but cannot be named."), + Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1: diag(4051, ts.DiagnosticCategory.Error, "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4051", "Return type of public static method from exported class has or is using name '{0}' from private module '{1}'."), + Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0: diag(4052, ts.DiagnosticCategory.Error, "Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0_4052", "Return type of public static method from exported class has or is using private name '{0}'."), + Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: diag(4053, ts.DiagnosticCategory.Error, "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_c_4053", "Return type of public method from exported class has or is using name '{0}' from external module {1} but cannot be named."), + Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1: diag(4054, ts.DiagnosticCategory.Error, "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4054", "Return type of public method from exported class has or is using name '{0}' from private module '{1}'."), + Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0: diag(4055, ts.DiagnosticCategory.Error, "Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0_4055", "Return type of public method from exported class has or is using private name '{0}'."), + Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1: diag(4056, ts.DiagnosticCategory.Error, "Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4056", "Return type of method from exported interface has or is using name '{0}' from private module '{1}'."), + Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0: diag(4057, ts.DiagnosticCategory.Error, "Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0_4057", "Return type of method from exported interface has or is using private name '{0}'."), + Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: diag(4058, ts.DiagnosticCategory.Error, "Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named_4058", "Return type of exported function has or is using name '{0}' from external module {1} but cannot be named."), + Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1: diag(4059, ts.DiagnosticCategory.Error, "Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1_4059", "Return type of exported function has or is using name '{0}' from private module '{1}'."), + Return_type_of_exported_function_has_or_is_using_private_name_0: diag(4060, ts.DiagnosticCategory.Error, "Return_type_of_exported_function_has_or_is_using_private_name_0_4060", "Return type of exported function has or is using private name '{0}'."), + Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4061, ts.DiagnosticCategory.Error, "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_can_4061", "Parameter '{0}' of constructor from exported class has or is using name '{1}' from external module {2} but cannot be named."), + Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4062, ts.DiagnosticCategory.Error, "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2_4062", "Parameter '{0}' of constructor from exported class has or is using name '{1}' from private module '{2}'."), + Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1: diag(4063, ts.DiagnosticCategory.Error, "Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1_4063", "Parameter '{0}' of constructor from exported class has or is using private name '{1}'."), + Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4064, ts.DiagnosticCategory.Error, "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_mod_4064", "Parameter '{0}' of constructor signature from exported interface has or is using name '{1}' from private module '{2}'."), + Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1: diag(4065, ts.DiagnosticCategory.Error, "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4065", "Parameter '{0}' of constructor signature from exported interface has or is using private name '{1}'."), + Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4066, ts.DiagnosticCategory.Error, "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4066", "Parameter '{0}' of call signature from exported interface has or is using name '{1}' from private module '{2}'."), + Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1: diag(4067, ts.DiagnosticCategory.Error, "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4067", "Parameter '{0}' of call signature from exported interface has or is using private name '{1}'."), + Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4068, ts.DiagnosticCategory.Error, "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module__4068", "Parameter '{0}' of public static method from exported class has or is using name '{1}' from external module {2} but cannot be named."), + Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4069, ts.DiagnosticCategory.Error, "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4069", "Parameter '{0}' of public static method from exported class has or is using name '{1}' from private module '{2}'."), + Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1: diag(4070, ts.DiagnosticCategory.Error, "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4070", "Parameter '{0}' of public static method from exported class has or is using private name '{1}'."), + Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4071, ts.DiagnosticCategory.Error, "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_c_4071", "Parameter '{0}' of public method from exported class has or is using name '{1}' from external module {2} but cannot be named."), + Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4072, ts.DiagnosticCategory.Error, "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4072", "Parameter '{0}' of public method from exported class has or is using name '{1}' from private module '{2}'."), + Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1: diag(4073, ts.DiagnosticCategory.Error, "Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4073", "Parameter '{0}' of public method from exported class has or is using private name '{1}'."), + Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4074, ts.DiagnosticCategory.Error, "Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4074", "Parameter '{0}' of method from exported interface has or is using name '{1}' from private module '{2}'."), + Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1: diag(4075, ts.DiagnosticCategory.Error, "Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4075", "Parameter '{0}' of method from exported interface has or is using private name '{1}'."), + Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4076, ts.DiagnosticCategory.Error, "Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4076", "Parameter '{0}' of exported function has or is using name '{1}' from external module {2} but cannot be named."), + Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2: diag(4077, ts.DiagnosticCategory.Error, "Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2_4077", "Parameter '{0}' of exported function has or is using name '{1}' from private module '{2}'."), + Parameter_0_of_exported_function_has_or_is_using_private_name_1: diag(4078, ts.DiagnosticCategory.Error, "Parameter_0_of_exported_function_has_or_is_using_private_name_1_4078", "Parameter '{0}' of exported function has or is using private name '{1}'."), + Exported_type_alias_0_has_or_is_using_private_name_1: diag(4081, ts.DiagnosticCategory.Error, "Exported_type_alias_0_has_or_is_using_private_name_1_4081", "Exported type alias '{0}' has or is using private name '{1}'."), + Default_export_of_the_module_has_or_is_using_private_name_0: diag(4082, ts.DiagnosticCategory.Error, "Default_export_of_the_module_has_or_is_using_private_name_0_4082", "Default export of the module has or is using private name '{0}'."), + Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1: diag(4083, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1_4083", "Type parameter '{0}' of exported type alias has or is using private name '{1}'."), + Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict: diag(4090, ts.DiagnosticCategory.Error, "Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_librar_4090", "Conflicting definitions for '{0}' found at '{1}' and '{2}'. Consider installing a specific version of this library to resolve the conflict."), + Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4091, ts.DiagnosticCategory.Error, "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4091", "Parameter '{0}' of index signature from exported interface has or is using name '{1}' from private module '{2}'."), + Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1: diag(4092, ts.DiagnosticCategory.Error, "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1_4092", "Parameter '{0}' of index signature from exported interface has or is using private name '{1}'."), + Property_0_of_exported_class_expression_may_not_be_private_or_protected: diag(4094, ts.DiagnosticCategory.Error, "Property_0_of_exported_class_expression_may_not_be_private_or_protected_4094", "Property '{0}' of exported class expression may not be private or protected."), + Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4095, ts.DiagnosticCategory.Error, "Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_4095", "Public static method '{0}' of exported class has or is using name '{1}' from external module {2} but cannot be named."), + Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4096, ts.DiagnosticCategory.Error, "Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4096", "Public static method '{0}' of exported class has or is using name '{1}' from private module '{2}'."), + Public_static_method_0_of_exported_class_has_or_is_using_private_name_1: diag(4097, ts.DiagnosticCategory.Error, "Public_static_method_0_of_exported_class_has_or_is_using_private_name_1_4097", "Public static method '{0}' of exported class has or is using private name '{1}'."), + Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4098, ts.DiagnosticCategory.Error, "Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4098", "Public method '{0}' of exported class has or is using name '{1}' from external module {2} but cannot be named."), + Public_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4099, ts.DiagnosticCategory.Error, "Public_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4099", "Public method '{0}' of exported class has or is using name '{1}' from private module '{2}'."), + Public_method_0_of_exported_class_has_or_is_using_private_name_1: diag(4100, ts.DiagnosticCategory.Error, "Public_method_0_of_exported_class_has_or_is_using_private_name_1_4100", "Public method '{0}' of exported class has or is using private name '{1}'."), + Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4101, ts.DiagnosticCategory.Error, "Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4101", "Method '{0}' of exported interface has or is using name '{1}' from private module '{2}'."), + Method_0_of_exported_interface_has_or_is_using_private_name_1: diag(4102, ts.DiagnosticCategory.Error, "Method_0_of_exported_interface_has_or_is_using_private_name_1_4102", "Method '{0}' of exported interface has or is using private name '{1}'."), + The_current_host_does_not_support_the_0_option: diag(5001, ts.DiagnosticCategory.Error, "The_current_host_does_not_support_the_0_option_5001", "The current host does not support the '{0}' option."), + Cannot_find_the_common_subdirectory_path_for_the_input_files: diag(5009, ts.DiagnosticCategory.Error, "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009", "Cannot find the common subdirectory path for the input files."), + File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: diag(5010, ts.DiagnosticCategory.Error, "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010", "File specification cannot end in a recursive directory wildcard ('**'): '{0}'."), + Cannot_read_file_0_Colon_1: diag(5012, ts.DiagnosticCategory.Error, "Cannot_read_file_0_Colon_1_5012", "Cannot read file '{0}': {1}."), + Failed_to_parse_file_0_Colon_1: diag(5014, ts.DiagnosticCategory.Error, "Failed_to_parse_file_0_Colon_1_5014", "Failed to parse file '{0}': {1}."), + Unknown_compiler_option_0: diag(5023, ts.DiagnosticCategory.Error, "Unknown_compiler_option_0_5023", "Unknown compiler option '{0}'."), + Compiler_option_0_requires_a_value_of_type_1: diag(5024, ts.DiagnosticCategory.Error, "Compiler_option_0_requires_a_value_of_type_1_5024", "Compiler option '{0}' requires a value of type {1}."), + Could_not_write_file_0_Colon_1: diag(5033, ts.DiagnosticCategory.Error, "Could_not_write_file_0_Colon_1_5033", "Could not write file '{0}': {1}."), + Option_project_cannot_be_mixed_with_source_files_on_a_command_line: diag(5042, ts.DiagnosticCategory.Error, "Option_project_cannot_be_mixed_with_source_files_on_a_command_line_5042", "Option 'project' cannot be mixed with source files on a command line."), + Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher: diag(5047, ts.DiagnosticCategory.Error, "Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES_5047", "Option 'isolatedModules' can only be used when either option '--module' is provided or option 'target' is 'ES2015' or higher."), + Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided: diag(5051, ts.DiagnosticCategory.Error, "Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided_5051", "Option '{0} can only be used when either option '--inlineSourceMap' or option '--sourceMap' is provided."), + Option_0_cannot_be_specified_without_specifying_option_1: diag(5052, ts.DiagnosticCategory.Error, "Option_0_cannot_be_specified_without_specifying_option_1_5052", "Option '{0}' cannot be specified without specifying option '{1}'."), + Option_0_cannot_be_specified_with_option_1: diag(5053, ts.DiagnosticCategory.Error, "Option_0_cannot_be_specified_with_option_1_5053", "Option '{0}' cannot be specified with option '{1}'."), + A_tsconfig_json_file_is_already_defined_at_Colon_0: diag(5054, ts.DiagnosticCategory.Error, "A_tsconfig_json_file_is_already_defined_at_Colon_0_5054", "A 'tsconfig.json' file is already defined at: '{0}'."), + Cannot_write_file_0_because_it_would_overwrite_input_file: diag(5055, ts.DiagnosticCategory.Error, "Cannot_write_file_0_because_it_would_overwrite_input_file_5055", "Cannot write file '{0}' because it would overwrite input file."), + Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files: diag(5056, ts.DiagnosticCategory.Error, "Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files_5056", "Cannot write file '{0}' because it would be overwritten by multiple input files."), + Cannot_find_a_tsconfig_json_file_at_the_specified_directory_Colon_0: diag(5057, ts.DiagnosticCategory.Error, "Cannot_find_a_tsconfig_json_file_at_the_specified_directory_Colon_0_5057", "Cannot find a tsconfig.json file at the specified directory: '{0}'."), + The_specified_path_does_not_exist_Colon_0: diag(5058, ts.DiagnosticCategory.Error, "The_specified_path_does_not_exist_Colon_0_5058", "The specified path does not exist: '{0}'."), + Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier: diag(5059, ts.DiagnosticCategory.Error, "Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier_5059", "Invalid value for '--reactNamespace'. '{0}' is not a valid identifier."), + Option_paths_cannot_be_used_without_specifying_baseUrl_option: diag(5060, ts.DiagnosticCategory.Error, "Option_paths_cannot_be_used_without_specifying_baseUrl_option_5060", "Option 'paths' cannot be used without specifying '--baseUrl' option."), + Pattern_0_can_have_at_most_one_Asterisk_character: diag(5061, ts.DiagnosticCategory.Error, "Pattern_0_can_have_at_most_one_Asterisk_character_5061", "Pattern '{0}' can have at most one '*' character."), + Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character: diag(5062, ts.DiagnosticCategory.Error, "Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character_5062", "Substitution '{0}' in pattern '{1}' in can have at most one '*' character."), + Substitutions_for_pattern_0_should_be_an_array: diag(5063, ts.DiagnosticCategory.Error, "Substitutions_for_pattern_0_should_be_an_array_5063", "Substitutions for pattern '{0}' should be an array."), + Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2: diag(5064, ts.DiagnosticCategory.Error, "Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2_5064", "Substitution '{0}' for pattern '{1}' has incorrect type, expected 'string', got '{2}'."), + File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: diag(5065, ts.DiagnosticCategory.Error, "File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildca_5065", "File specification cannot contain a parent directory ('..') that appears after a recursive directory wildcard ('**'): '{0}'."), + Substitutions_for_pattern_0_shouldn_t_be_an_empty_array: diag(5066, ts.DiagnosticCategory.Error, "Substitutions_for_pattern_0_shouldn_t_be_an_empty_array_5066", "Substitutions for pattern '{0}' shouldn't be an empty array."), + Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name: diag(5067, ts.DiagnosticCategory.Error, "Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name_5067", "Invalid value for 'jsxFactory'. '{0}' is not a valid identifier or qualified-name."), + Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig: diag(5068, ts.DiagnosticCategory.Error, "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068", "Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig."), + Option_0_cannot_be_specified_without_specifying_option_1_or_option_2: diag(5069, ts.DiagnosticCategory.Error, "Option_0_cannot_be_specified_without_specifying_option_1_or_option_2_5069", "Option '{0}' cannot be specified without specifying option '{1}' or option '{2}'."), + Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy: diag(5070, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070", "Option '--resolveJsonModule' cannot be specified without 'node' module resolution strategy."), + Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_esNext: diag(5071, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_5071", "Option '--resolveJsonModule' can only be specified when module code generation is 'commonjs', 'amd', 'es2015' or 'esNext'."), + Unknown_build_option_0: diag(5072, ts.DiagnosticCategory.Error, "Unknown_build_option_0_5072", "Unknown build option '{0}'."), + Build_option_0_requires_a_value_of_type_1: diag(5073, ts.DiagnosticCategory.Error, "Build_option_0_requires_a_value_of_type_1_5073", "Build option '{0}' requires a value of type {1}."), + Generates_a_sourcemap_for_each_corresponding_d_ts_file: diag(6000, ts.DiagnosticCategory.Message, "Generates_a_sourcemap_for_each_corresponding_d_ts_file_6000", "Generates a sourcemap for each corresponding '.d.ts' file."), + Concatenate_and_emit_output_to_single_file: diag(6001, ts.DiagnosticCategory.Message, "Concatenate_and_emit_output_to_single_file_6001", "Concatenate and emit output to single file."), + Generates_corresponding_d_ts_file: diag(6002, ts.DiagnosticCategory.Message, "Generates_corresponding_d_ts_file_6002", "Generates corresponding '.d.ts' file."), + Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations: diag(6003, ts.DiagnosticCategory.Message, "Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations_6003", "Specify the location where debugger should locate map files instead of generated locations."), + Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations: diag(6004, ts.DiagnosticCategory.Message, "Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations_6004", "Specify the location where debugger should locate TypeScript files instead of source locations."), + Watch_input_files: diag(6005, ts.DiagnosticCategory.Message, "Watch_input_files_6005", "Watch input files."), + Redirect_output_structure_to_the_directory: diag(6006, ts.DiagnosticCategory.Message, "Redirect_output_structure_to_the_directory_6006", "Redirect output structure to the directory."), + Do_not_erase_const_enum_declarations_in_generated_code: diag(6007, ts.DiagnosticCategory.Message, "Do_not_erase_const_enum_declarations_in_generated_code_6007", "Do not erase const enum declarations in generated code."), + Do_not_emit_outputs_if_any_errors_were_reported: diag(6008, ts.DiagnosticCategory.Message, "Do_not_emit_outputs_if_any_errors_were_reported_6008", "Do not emit outputs if any errors were reported."), + Do_not_emit_comments_to_output: diag(6009, ts.DiagnosticCategory.Message, "Do_not_emit_comments_to_output_6009", "Do not emit comments to output."), + Do_not_emit_outputs: diag(6010, ts.DiagnosticCategory.Message, "Do_not_emit_outputs_6010", "Do not emit outputs."), + Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking: diag(6011, ts.DiagnosticCategory.Message, "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011", "Allow default imports from modules with no default export. This does not affect code emit, just typechecking."), + Skip_type_checking_of_declaration_files: diag(6012, ts.DiagnosticCategory.Message, "Skip_type_checking_of_declaration_files_6012", "Skip type checking of declaration files."), + Do_not_resolve_the_real_path_of_symlinks: diag(6013, ts.DiagnosticCategory.Message, "Do_not_resolve_the_real_path_of_symlinks_6013", "Do not resolve the real path of symlinks."), + Only_emit_d_ts_declaration_files: diag(6014, ts.DiagnosticCategory.Message, "Only_emit_d_ts_declaration_files_6014", "Only emit '.d.ts' declaration files."), + Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_or_ESNEXT: diag(6015, ts.DiagnosticCategory.Message, "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_or_ESNEXT_6015", "Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'."), + Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext: diag(6016, ts.DiagnosticCategory.Message, "Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext_6016", "Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'."), + Print_this_message: diag(6017, ts.DiagnosticCategory.Message, "Print_this_message_6017", "Print this message."), + Print_the_compiler_s_version: diag(6019, ts.DiagnosticCategory.Message, "Print_the_compiler_s_version_6019", "Print the compiler's version."), + Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json: diag(6020, ts.DiagnosticCategory.Message, "Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json_6020", "Compile the project given the path to its configuration file, or to a folder with a 'tsconfig.json'."), + Syntax_Colon_0: diag(6023, ts.DiagnosticCategory.Message, "Syntax_Colon_0_6023", "Syntax: {0}"), + options: diag(6024, ts.DiagnosticCategory.Message, "options_6024", "options"), + file: diag(6025, ts.DiagnosticCategory.Message, "file_6025", "file"), + Examples_Colon_0: diag(6026, ts.DiagnosticCategory.Message, "Examples_Colon_0_6026", "Examples: {0}"), + Options_Colon: diag(6027, ts.DiagnosticCategory.Message, "Options_Colon_6027", "Options:"), + Version_0: diag(6029, ts.DiagnosticCategory.Message, "Version_0_6029", "Version {0}"), + Insert_command_line_options_and_files_from_a_file: diag(6030, ts.DiagnosticCategory.Message, "Insert_command_line_options_and_files_from_a_file_6030", "Insert command line options and files from a file."), + Starting_compilation_in_watch_mode: diag(6031, ts.DiagnosticCategory.Message, "Starting_compilation_in_watch_mode_6031", "Starting compilation in watch mode..."), + File_change_detected_Starting_incremental_compilation: diag(6032, ts.DiagnosticCategory.Message, "File_change_detected_Starting_incremental_compilation_6032", "File change detected. Starting incremental compilation..."), + KIND: diag(6034, ts.DiagnosticCategory.Message, "KIND_6034", "KIND"), + FILE: diag(6035, ts.DiagnosticCategory.Message, "FILE_6035", "FILE"), + VERSION: diag(6036, ts.DiagnosticCategory.Message, "VERSION_6036", "VERSION"), + LOCATION: diag(6037, ts.DiagnosticCategory.Message, "LOCATION_6037", "LOCATION"), + DIRECTORY: diag(6038, ts.DiagnosticCategory.Message, "DIRECTORY_6038", "DIRECTORY"), + STRATEGY: diag(6039, ts.DiagnosticCategory.Message, "STRATEGY_6039", "STRATEGY"), + FILE_OR_DIRECTORY: diag(6040, ts.DiagnosticCategory.Message, "FILE_OR_DIRECTORY_6040", "FILE OR DIRECTORY"), + Generates_corresponding_map_file: diag(6043, ts.DiagnosticCategory.Message, "Generates_corresponding_map_file_6043", "Generates corresponding '.map' file."), + Compiler_option_0_expects_an_argument: diag(6044, ts.DiagnosticCategory.Error, "Compiler_option_0_expects_an_argument_6044", "Compiler option '{0}' expects an argument."), + Unterminated_quoted_string_in_response_file_0: diag(6045, ts.DiagnosticCategory.Error, "Unterminated_quoted_string_in_response_file_0_6045", "Unterminated quoted string in response file '{0}'."), + Argument_for_0_option_must_be_Colon_1: diag(6046, ts.DiagnosticCategory.Error, "Argument_for_0_option_must_be_Colon_1_6046", "Argument for '{0}' option must be: {1}."), + Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1: diag(6048, ts.DiagnosticCategory.Error, "Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1_6048", "Locale must be of the form or -. For example '{0}' or '{1}'."), + Unsupported_locale_0: diag(6049, ts.DiagnosticCategory.Error, "Unsupported_locale_0_6049", "Unsupported locale '{0}'."), + Unable_to_open_file_0: diag(6050, ts.DiagnosticCategory.Error, "Unable_to_open_file_0_6050", "Unable to open file '{0}'."), + Corrupted_locale_file_0: diag(6051, ts.DiagnosticCategory.Error, "Corrupted_locale_file_0_6051", "Corrupted locale file {0}."), + Raise_error_on_expressions_and_declarations_with_an_implied_any_type: diag(6052, ts.DiagnosticCategory.Message, "Raise_error_on_expressions_and_declarations_with_an_implied_any_type_6052", "Raise error on expressions and declarations with an implied 'any' type."), + File_0_not_found: diag(6053, ts.DiagnosticCategory.Error, "File_0_not_found_6053", "File '{0}' not found."), + File_0_has_unsupported_extension_The_only_supported_extensions_are_1: diag(6054, ts.DiagnosticCategory.Error, "File_0_has_unsupported_extension_The_only_supported_extensions_are_1_6054", "File '{0}' has unsupported extension. The only supported extensions are {1}."), + Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures: diag(6055, ts.DiagnosticCategory.Message, "Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures_6055", "Suppress noImplicitAny errors for indexing objects lacking index signatures."), + Do_not_emit_declarations_for_code_that_has_an_internal_annotation: diag(6056, ts.DiagnosticCategory.Message, "Do_not_emit_declarations_for_code_that_has_an_internal_annotation_6056", "Do not emit declarations for code that has an '@internal' annotation."), + Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir: diag(6058, ts.DiagnosticCategory.Message, "Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir_6058", "Specify the root directory of input files. Use to control the output directory structure with --outDir."), + File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files: diag(6059, ts.DiagnosticCategory.Error, "File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files_6059", "File '{0}' is not under 'rootDir' '{1}'. 'rootDir' is expected to contain all source files."), + Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix: diag(6060, ts.DiagnosticCategory.Message, "Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix_6060", "Specify the end of line sequence to be used when emitting files: 'CRLF' (dos) or 'LF' (unix)."), + NEWLINE: diag(6061, ts.DiagnosticCategory.Message, "NEWLINE_6061", "NEWLINE"), + Option_0_can_only_be_specified_in_tsconfig_json_file: diag(6064, ts.DiagnosticCategory.Error, "Option_0_can_only_be_specified_in_tsconfig_json_file_6064", "Option '{0}' can only be specified in 'tsconfig.json' file."), + Enables_experimental_support_for_ES7_decorators: diag(6065, ts.DiagnosticCategory.Message, "Enables_experimental_support_for_ES7_decorators_6065", "Enables experimental support for ES7 decorators."), + Enables_experimental_support_for_emitting_type_metadata_for_decorators: diag(6066, ts.DiagnosticCategory.Message, "Enables_experimental_support_for_emitting_type_metadata_for_decorators_6066", "Enables experimental support for emitting type metadata for decorators."), + Enables_experimental_support_for_ES7_async_functions: diag(6068, ts.DiagnosticCategory.Message, "Enables_experimental_support_for_ES7_async_functions_6068", "Enables experimental support for ES7 async functions."), + Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6: diag(6069, ts.DiagnosticCategory.Message, "Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6_6069", "Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6)."), + Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file: diag(6070, ts.DiagnosticCategory.Message, "Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file_6070", "Initializes a TypeScript project and creates a tsconfig.json file."), + Successfully_created_a_tsconfig_json_file: diag(6071, ts.DiagnosticCategory.Message, "Successfully_created_a_tsconfig_json_file_6071", "Successfully created a tsconfig.json file."), + Suppress_excess_property_checks_for_object_literals: diag(6072, ts.DiagnosticCategory.Message, "Suppress_excess_property_checks_for_object_literals_6072", "Suppress excess property checks for object literals."), + Stylize_errors_and_messages_using_color_and_context_experimental: diag(6073, ts.DiagnosticCategory.Message, "Stylize_errors_and_messages_using_color_and_context_experimental_6073", "Stylize errors and messages using color and context (experimental)."), + Do_not_report_errors_on_unused_labels: diag(6074, ts.DiagnosticCategory.Message, "Do_not_report_errors_on_unused_labels_6074", "Do not report errors on unused labels."), + Report_error_when_not_all_code_paths_in_function_return_a_value: diag(6075, ts.DiagnosticCategory.Message, "Report_error_when_not_all_code_paths_in_function_return_a_value_6075", "Report error when not all code paths in function return a value."), + Report_errors_for_fallthrough_cases_in_switch_statement: diag(6076, ts.DiagnosticCategory.Message, "Report_errors_for_fallthrough_cases_in_switch_statement_6076", "Report errors for fallthrough cases in switch statement."), + Do_not_report_errors_on_unreachable_code: diag(6077, ts.DiagnosticCategory.Message, "Do_not_report_errors_on_unreachable_code_6077", "Do not report errors on unreachable code."), + Disallow_inconsistently_cased_references_to_the_same_file: diag(6078, ts.DiagnosticCategory.Message, "Disallow_inconsistently_cased_references_to_the_same_file_6078", "Disallow inconsistently-cased references to the same file."), + Specify_library_files_to_be_included_in_the_compilation: diag(6079, ts.DiagnosticCategory.Message, "Specify_library_files_to_be_included_in_the_compilation_6079", "Specify library files to be included in the compilation."), + Specify_JSX_code_generation_Colon_preserve_react_native_or_react: diag(6080, ts.DiagnosticCategory.Message, "Specify_JSX_code_generation_Colon_preserve_react_native_or_react_6080", "Specify JSX code generation: 'preserve', 'react-native', or 'react'."), + File_0_has_an_unsupported_extension_so_skipping_it: diag(6081, ts.DiagnosticCategory.Message, "File_0_has_an_unsupported_extension_so_skipping_it_6081", "File '{0}' has an unsupported extension, so skipping it."), + Only_amd_and_system_modules_are_supported_alongside_0: diag(6082, ts.DiagnosticCategory.Error, "Only_amd_and_system_modules_are_supported_alongside_0_6082", "Only 'amd' and 'system' modules are supported alongside --{0}."), + Base_directory_to_resolve_non_absolute_module_names: diag(6083, ts.DiagnosticCategory.Message, "Base_directory_to_resolve_non_absolute_module_names_6083", "Base directory to resolve non-absolute module names."), + Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react_JSX_emit: diag(6084, ts.DiagnosticCategory.Message, "Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react__6084", "[Deprecated] Use '--jsxFactory' instead. Specify the object invoked for createElement when targeting 'react' JSX emit"), + Enable_tracing_of_the_name_resolution_process: diag(6085, ts.DiagnosticCategory.Message, "Enable_tracing_of_the_name_resolution_process_6085", "Enable tracing of the name resolution process."), + Resolving_module_0_from_1: diag(6086, ts.DiagnosticCategory.Message, "Resolving_module_0_from_1_6086", "======== Resolving module '{0}' from '{1}'. ========"), + Explicitly_specified_module_resolution_kind_Colon_0: diag(6087, ts.DiagnosticCategory.Message, "Explicitly_specified_module_resolution_kind_Colon_0_6087", "Explicitly specified module resolution kind: '{0}'."), + Module_resolution_kind_is_not_specified_using_0: diag(6088, ts.DiagnosticCategory.Message, "Module_resolution_kind_is_not_specified_using_0_6088", "Module resolution kind is not specified, using '{0}'."), + Module_name_0_was_successfully_resolved_to_1: diag(6089, ts.DiagnosticCategory.Message, "Module_name_0_was_successfully_resolved_to_1_6089", "======== Module name '{0}' was successfully resolved to '{1}'. ========"), + Module_name_0_was_not_resolved: diag(6090, ts.DiagnosticCategory.Message, "Module_name_0_was_not_resolved_6090", "======== Module name '{0}' was not resolved. ========"), + paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0: diag(6091, ts.DiagnosticCategory.Message, "paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0_6091", "'paths' option is specified, looking for a pattern to match module name '{0}'."), + Module_name_0_matched_pattern_1: diag(6092, ts.DiagnosticCategory.Message, "Module_name_0_matched_pattern_1_6092", "Module name '{0}', matched pattern '{1}'."), + Trying_substitution_0_candidate_module_location_Colon_1: diag(6093, ts.DiagnosticCategory.Message, "Trying_substitution_0_candidate_module_location_Colon_1_6093", "Trying substitution '{0}', candidate module location: '{1}'."), + Resolving_module_name_0_relative_to_base_url_1_2: diag(6094, ts.DiagnosticCategory.Message, "Resolving_module_name_0_relative_to_base_url_1_2_6094", "Resolving module name '{0}' relative to base url '{1}' - '{2}'."), + Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1: diag(6095, ts.DiagnosticCategory.Message, "Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1_6095", "Loading module as file / folder, candidate module location '{0}', target file type '{1}'."), + File_0_does_not_exist: diag(6096, ts.DiagnosticCategory.Message, "File_0_does_not_exist_6096", "File '{0}' does not exist."), + File_0_exist_use_it_as_a_name_resolution_result: diag(6097, ts.DiagnosticCategory.Message, "File_0_exist_use_it_as_a_name_resolution_result_6097", "File '{0}' exist - use it as a name resolution result."), + Loading_module_0_from_node_modules_folder_target_file_type_1: diag(6098, ts.DiagnosticCategory.Message, "Loading_module_0_from_node_modules_folder_target_file_type_1_6098", "Loading module '{0}' from 'node_modules' folder, target file type '{1}'."), + Found_package_json_at_0: diag(6099, ts.DiagnosticCategory.Message, "Found_package_json_at_0_6099", "Found 'package.json' at '{0}'."), + package_json_does_not_have_a_0_field: diag(6100, ts.DiagnosticCategory.Message, "package_json_does_not_have_a_0_field_6100", "'package.json' does not have a '{0}' field."), + package_json_has_0_field_1_that_references_2: diag(6101, ts.DiagnosticCategory.Message, "package_json_has_0_field_1_that_references_2_6101", "'package.json' has '{0}' field '{1}' that references '{2}'."), + Allow_javascript_files_to_be_compiled: diag(6102, ts.DiagnosticCategory.Message, "Allow_javascript_files_to_be_compiled_6102", "Allow javascript files to be compiled."), + Option_0_should_have_array_of_strings_as_a_value: diag(6103, ts.DiagnosticCategory.Error, "Option_0_should_have_array_of_strings_as_a_value_6103", "Option '{0}' should have array of strings as a value."), + Checking_if_0_is_the_longest_matching_prefix_for_1_2: diag(6104, ts.DiagnosticCategory.Message, "Checking_if_0_is_the_longest_matching_prefix_for_1_2_6104", "Checking if '{0}' is the longest matching prefix for '{1}' - '{2}'."), + Expected_type_of_0_field_in_package_json_to_be_1_got_2: diag(6105, ts.DiagnosticCategory.Message, "Expected_type_of_0_field_in_package_json_to_be_1_got_2_6105", "Expected type of '{0}' field in 'package.json' to be '{1}', got '{2}'."), + baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1: diag(6106, ts.DiagnosticCategory.Message, "baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1_6106", "'baseUrl' option is set to '{0}', using this value to resolve non-relative module name '{1}'."), + rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0: diag(6107, ts.DiagnosticCategory.Message, "rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107", "'rootDirs' option is set, using it to resolve relative module name '{0}'."), + Longest_matching_prefix_for_0_is_1: diag(6108, ts.DiagnosticCategory.Message, "Longest_matching_prefix_for_0_is_1_6108", "Longest matching prefix for '{0}' is '{1}'."), + Loading_0_from_the_root_dir_1_candidate_location_2: diag(6109, ts.DiagnosticCategory.Message, "Loading_0_from_the_root_dir_1_candidate_location_2_6109", "Loading '{0}' from the root dir '{1}', candidate location '{2}'."), + Trying_other_entries_in_rootDirs: diag(6110, ts.DiagnosticCategory.Message, "Trying_other_entries_in_rootDirs_6110", "Trying other entries in 'rootDirs'."), + Module_resolution_using_rootDirs_has_failed: diag(6111, ts.DiagnosticCategory.Message, "Module_resolution_using_rootDirs_has_failed_6111", "Module resolution using 'rootDirs' has failed."), + Do_not_emit_use_strict_directives_in_module_output: diag(6112, ts.DiagnosticCategory.Message, "Do_not_emit_use_strict_directives_in_module_output_6112", "Do not emit 'use strict' directives in module output."), + Enable_strict_null_checks: diag(6113, ts.DiagnosticCategory.Message, "Enable_strict_null_checks_6113", "Enable strict null checks."), + Unknown_option_excludes_Did_you_mean_exclude: diag(6114, ts.DiagnosticCategory.Error, "Unknown_option_excludes_Did_you_mean_exclude_6114", "Unknown option 'excludes'. Did you mean 'exclude'?"), + Raise_error_on_this_expressions_with_an_implied_any_type: diag(6115, ts.DiagnosticCategory.Message, "Raise_error_on_this_expressions_with_an_implied_any_type_6115", "Raise error on 'this' expressions with an implied 'any' type."), + Resolving_type_reference_directive_0_containing_file_1_root_directory_2: diag(6116, ts.DiagnosticCategory.Message, "Resolving_type_reference_directive_0_containing_file_1_root_directory_2_6116", "======== Resolving type reference directive '{0}', containing file '{1}', root directory '{2}'. ========"), + Resolving_using_primary_search_paths: diag(6117, ts.DiagnosticCategory.Message, "Resolving_using_primary_search_paths_6117", "Resolving using primary search paths..."), + Resolving_from_node_modules_folder: diag(6118, ts.DiagnosticCategory.Message, "Resolving_from_node_modules_folder_6118", "Resolving from node_modules folder..."), + Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2: diag(6119, ts.DiagnosticCategory.Message, "Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2_6119", "======== Type reference directive '{0}' was successfully resolved to '{1}', primary: {2}. ========"), + Type_reference_directive_0_was_not_resolved: diag(6120, ts.DiagnosticCategory.Message, "Type_reference_directive_0_was_not_resolved_6120", "======== Type reference directive '{0}' was not resolved. ========"), + Resolving_with_primary_search_path_0: diag(6121, ts.DiagnosticCategory.Message, "Resolving_with_primary_search_path_0_6121", "Resolving with primary search path '{0}'."), + Root_directory_cannot_be_determined_skipping_primary_search_paths: diag(6122, ts.DiagnosticCategory.Message, "Root_directory_cannot_be_determined_skipping_primary_search_paths_6122", "Root directory cannot be determined, skipping primary search paths."), + Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set: diag(6123, ts.DiagnosticCategory.Message, "Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set_6123", "======== Resolving type reference directive '{0}', containing file '{1}', root directory not set. ========"), + Type_declaration_files_to_be_included_in_compilation: diag(6124, ts.DiagnosticCategory.Message, "Type_declaration_files_to_be_included_in_compilation_6124", "Type declaration files to be included in compilation."), + Looking_up_in_node_modules_folder_initial_location_0: diag(6125, ts.DiagnosticCategory.Message, "Looking_up_in_node_modules_folder_initial_location_0_6125", "Looking up in 'node_modules' folder, initial location '{0}'."), + Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder: diag(6126, ts.DiagnosticCategory.Message, "Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126", "Containing file is not specified and root directory cannot be determined, skipping lookup in 'node_modules' folder."), + Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1: diag(6127, ts.DiagnosticCategory.Message, "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1_6127", "======== Resolving type reference directive '{0}', containing file not set, root directory '{1}'. ========"), + Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set: diag(6128, ts.DiagnosticCategory.Message, "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set_6128", "======== Resolving type reference directive '{0}', containing file not set, root directory not set. ========"), + Resolving_real_path_for_0_result_1: diag(6130, ts.DiagnosticCategory.Message, "Resolving_real_path_for_0_result_1_6130", "Resolving real path for '{0}', result '{1}'."), + Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system: diag(6131, ts.DiagnosticCategory.Error, "Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system_6131", "Cannot compile modules using option '{0}' unless the '--module' flag is 'amd' or 'system'."), + File_name_0_has_a_1_extension_stripping_it: diag(6132, ts.DiagnosticCategory.Message, "File_name_0_has_a_1_extension_stripping_it_6132", "File name '{0}' has a '{1}' extension - stripping it."), + _0_is_declared_but_its_value_is_never_read: diag(6133, ts.DiagnosticCategory.Error, "_0_is_declared_but_its_value_is_never_read_6133", "'{0}' is declared but its value is never read.", /*reportsUnnecessary*/ true), + Report_errors_on_unused_locals: diag(6134, ts.DiagnosticCategory.Message, "Report_errors_on_unused_locals_6134", "Report errors on unused locals."), + Report_errors_on_unused_parameters: diag(6135, ts.DiagnosticCategory.Message, "Report_errors_on_unused_parameters_6135", "Report errors on unused parameters."), + The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files: diag(6136, ts.DiagnosticCategory.Message, "The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files_6136", "The maximum dependency depth to search under node_modules and load JavaScript files."), + Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1: diag(6137, ts.DiagnosticCategory.Error, "Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1_6137", "Cannot import type declaration files. Consider importing '{0}' instead of '{1}'."), + Property_0_is_declared_but_its_value_is_never_read: diag(6138, ts.DiagnosticCategory.Error, "Property_0_is_declared_but_its_value_is_never_read_6138", "Property '{0}' is declared but its value is never read.", /*reportsUnnecessary*/ true), + Import_emit_helpers_from_tslib: diag(6139, ts.DiagnosticCategory.Message, "Import_emit_helpers_from_tslib_6139", "Import emit helpers from 'tslib'."), + Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2: diag(6140, ts.DiagnosticCategory.Error, "Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using__6140", "Auto discovery for typings is enabled in project '{0}'. Running extra resolution pass for module '{1}' using cache location '{2}'."), + Parse_in_strict_mode_and_emit_use_strict_for_each_source_file: diag(6141, ts.DiagnosticCategory.Message, "Parse_in_strict_mode_and_emit_use_strict_for_each_source_file_6141", "Parse in strict mode and emit \"use strict\" for each source file."), + Module_0_was_resolved_to_1_but_jsx_is_not_set: diag(6142, ts.DiagnosticCategory.Error, "Module_0_was_resolved_to_1_but_jsx_is_not_set_6142", "Module '{0}' was resolved to '{1}', but '--jsx' is not set."), + Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1: diag(6144, ts.DiagnosticCategory.Message, "Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1_6144", "Module '{0}' was resolved as locally declared ambient module in file '{1}'."), + Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified: diag(6145, ts.DiagnosticCategory.Message, "Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified_6145", "Module '{0}' was resolved as ambient module declared in '{1}' since this file was not modified."), + Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h: diag(6146, ts.DiagnosticCategory.Message, "Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h_6146", "Specify the JSX factory function to use when targeting 'react' JSX emit, e.g. 'React.createElement' or 'h'."), + Resolution_for_module_0_was_found_in_cache_from_location_1: diag(6147, ts.DiagnosticCategory.Message, "Resolution_for_module_0_was_found_in_cache_from_location_1_6147", "Resolution for module '{0}' was found in cache from location '{1}'."), + Directory_0_does_not_exist_skipping_all_lookups_in_it: diag(6148, ts.DiagnosticCategory.Message, "Directory_0_does_not_exist_skipping_all_lookups_in_it_6148", "Directory '{0}' does not exist, skipping all lookups in it."), + Show_diagnostic_information: diag(6149, ts.DiagnosticCategory.Message, "Show_diagnostic_information_6149", "Show diagnostic information."), + Show_verbose_diagnostic_information: diag(6150, ts.DiagnosticCategory.Message, "Show_verbose_diagnostic_information_6150", "Show verbose diagnostic information."), + Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file: diag(6151, ts.DiagnosticCategory.Message, "Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file_6151", "Emit a single file with source maps instead of having a separate file."), + Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap_to_be_set: diag(6152, ts.DiagnosticCategory.Message, "Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap__6152", "Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set."), + Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule: diag(6153, ts.DiagnosticCategory.Message, "Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule_6153", "Transpile each file as a separate module (similar to 'ts.transpileModule')."), + Print_names_of_generated_files_part_of_the_compilation: diag(6154, ts.DiagnosticCategory.Message, "Print_names_of_generated_files_part_of_the_compilation_6154", "Print names of generated files part of the compilation."), + Print_names_of_files_part_of_the_compilation: diag(6155, ts.DiagnosticCategory.Message, "Print_names_of_files_part_of_the_compilation_6155", "Print names of files part of the compilation."), + The_locale_used_when_displaying_messages_to_the_user_e_g_en_us: diag(6156, ts.DiagnosticCategory.Message, "The_locale_used_when_displaying_messages_to_the_user_e_g_en_us_6156", "The locale used when displaying messages to the user (e.g. 'en-us')"), + Do_not_generate_custom_helper_functions_like_extends_in_compiled_output: diag(6157, ts.DiagnosticCategory.Message, "Do_not_generate_custom_helper_functions_like_extends_in_compiled_output_6157", "Do not generate custom helper functions like '__extends' in compiled output."), + Do_not_include_the_default_library_file_lib_d_ts: diag(6158, ts.DiagnosticCategory.Message, "Do_not_include_the_default_library_file_lib_d_ts_6158", "Do not include the default library file (lib.d.ts)."), + Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files: diag(6159, ts.DiagnosticCategory.Message, "Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files_6159", "Do not add triple-slash references or imported modules to the list of compiled files."), + Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files: diag(6160, ts.DiagnosticCategory.Message, "Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files_6160", "[Deprecated] Use '--skipLibCheck' instead. Skip type checking of default library declaration files."), + List_of_folders_to_include_type_definitions_from: diag(6161, ts.DiagnosticCategory.Message, "List_of_folders_to_include_type_definitions_from_6161", "List of folders to include type definitions from."), + Disable_size_limitations_on_JavaScript_projects: diag(6162, ts.DiagnosticCategory.Message, "Disable_size_limitations_on_JavaScript_projects_6162", "Disable size limitations on JavaScript projects."), + The_character_set_of_the_input_files: diag(6163, ts.DiagnosticCategory.Message, "The_character_set_of_the_input_files_6163", "The character set of the input files."), + Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files: diag(6164, ts.DiagnosticCategory.Message, "Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files_6164", "Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files."), + Do_not_truncate_error_messages: diag(6165, ts.DiagnosticCategory.Message, "Do_not_truncate_error_messages_6165", "Do not truncate error messages."), + Output_directory_for_generated_declaration_files: diag(6166, ts.DiagnosticCategory.Message, "Output_directory_for_generated_declaration_files_6166", "Output directory for generated declaration files."), + A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl: diag(6167, ts.DiagnosticCategory.Message, "A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl_6167", "A series of entries which re-map imports to lookup locations relative to the 'baseUrl'."), + List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime: diag(6168, ts.DiagnosticCategory.Message, "List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime_6168", "List of root folders whose combined content represents the structure of the project at runtime."), + Show_all_compiler_options: diag(6169, ts.DiagnosticCategory.Message, "Show_all_compiler_options_6169", "Show all compiler options."), + Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file: diag(6170, ts.DiagnosticCategory.Message, "Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file_6170", "[Deprecated] Use '--outFile' instead. Concatenate and emit output to single file"), + Command_line_Options: diag(6171, ts.DiagnosticCategory.Message, "Command_line_Options_6171", "Command-line Options"), + Basic_Options: diag(6172, ts.DiagnosticCategory.Message, "Basic_Options_6172", "Basic Options"), + Strict_Type_Checking_Options: diag(6173, ts.DiagnosticCategory.Message, "Strict_Type_Checking_Options_6173", "Strict Type-Checking Options"), + Module_Resolution_Options: diag(6174, ts.DiagnosticCategory.Message, "Module_Resolution_Options_6174", "Module Resolution Options"), + Source_Map_Options: diag(6175, ts.DiagnosticCategory.Message, "Source_Map_Options_6175", "Source Map Options"), + Additional_Checks: diag(6176, ts.DiagnosticCategory.Message, "Additional_Checks_6176", "Additional Checks"), + Experimental_Options: diag(6177, ts.DiagnosticCategory.Message, "Experimental_Options_6177", "Experimental Options"), + Advanced_Options: diag(6178, ts.DiagnosticCategory.Message, "Advanced_Options_6178", "Advanced Options"), + Provide_full_support_for_iterables_in_for_of_spread_and_destructuring_when_targeting_ES5_or_ES3: diag(6179, ts.DiagnosticCategory.Message, "Provide_full_support_for_iterables_in_for_of_spread_and_destructuring_when_targeting_ES5_or_ES3_6179", "Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'."), + Enable_all_strict_type_checking_options: diag(6180, ts.DiagnosticCategory.Message, "Enable_all_strict_type_checking_options_6180", "Enable all strict type-checking options."), + List_of_language_service_plugins: diag(6181, ts.DiagnosticCategory.Message, "List_of_language_service_plugins_6181", "List of language service plugins."), + Scoped_package_detected_looking_in_0: diag(6182, ts.DiagnosticCategory.Message, "Scoped_package_detected_looking_in_0_6182", "Scoped package detected, looking in '{0}'"), + Reusing_resolution_of_module_0_to_file_1_from_old_program: diag(6183, ts.DiagnosticCategory.Message, "Reusing_resolution_of_module_0_to_file_1_from_old_program_6183", "Reusing resolution of module '{0}' to file '{1}' from old program."), + Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program: diag(6184, ts.DiagnosticCategory.Message, "Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program_6184", "Reusing module resolutions originating in '{0}' since resolutions are unchanged from old program."), + Disable_strict_checking_of_generic_signatures_in_function_types: diag(6185, ts.DiagnosticCategory.Message, "Disable_strict_checking_of_generic_signatures_in_function_types_6185", "Disable strict checking of generic signatures in function types."), + Enable_strict_checking_of_function_types: diag(6186, ts.DiagnosticCategory.Message, "Enable_strict_checking_of_function_types_6186", "Enable strict checking of function types."), + Enable_strict_checking_of_property_initialization_in_classes: diag(6187, ts.DiagnosticCategory.Message, "Enable_strict_checking_of_property_initialization_in_classes_6187", "Enable strict checking of property initialization in classes."), + Numeric_separators_are_not_allowed_here: diag(6188, ts.DiagnosticCategory.Error, "Numeric_separators_are_not_allowed_here_6188", "Numeric separators are not allowed here."), + Multiple_consecutive_numeric_separators_are_not_permitted: diag(6189, ts.DiagnosticCategory.Error, "Multiple_consecutive_numeric_separators_are_not_permitted_6189", "Multiple consecutive numeric separators are not permitted."), + Found_package_json_at_0_Package_ID_is_1: diag(6190, ts.DiagnosticCategory.Message, "Found_package_json_at_0_Package_ID_is_1_6190", "Found 'package.json' at '{0}'. Package ID is '{1}'."), + Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen: diag(6191, ts.DiagnosticCategory.Message, "Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen_6191", "Whether to keep outdated console output in watch mode instead of clearing the screen."), + All_imports_in_import_declaration_are_unused: diag(6192, ts.DiagnosticCategory.Error, "All_imports_in_import_declaration_are_unused_6192", "All imports in import declaration are unused.", /*reportsUnnecessary*/ true), + Found_1_error_Watching_for_file_changes: diag(6193, ts.DiagnosticCategory.Message, "Found_1_error_Watching_for_file_changes_6193", "Found 1 error. Watching for file changes."), + Found_0_errors_Watching_for_file_changes: diag(6194, ts.DiagnosticCategory.Message, "Found_0_errors_Watching_for_file_changes_6194", "Found {0} errors. Watching for file changes."), + Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols: diag(6195, ts.DiagnosticCategory.Message, "Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols_6195", "Resolve 'keyof' to string valued property names only (no numbers or symbols)."), + _0_is_declared_but_never_used: diag(6196, ts.DiagnosticCategory.Error, "_0_is_declared_but_never_used_6196", "'{0}' is declared but never used.", /*reportsUnnecessary*/ true), + Include_modules_imported_with_json_extension: diag(6197, ts.DiagnosticCategory.Message, "Include_modules_imported_with_json_extension_6197", "Include modules imported with '.json' extension"), + All_destructured_elements_are_unused: diag(6198, ts.DiagnosticCategory.Error, "All_destructured_elements_are_unused_6198", "All destructured elements are unused.", /*reportsUnnecessary*/ true), + All_variables_are_unused: diag(6199, ts.DiagnosticCategory.Error, "All_variables_are_unused_6199", "All variables are unused.", /*reportsUnnecessary*/ true), + Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0: diag(6200, ts.DiagnosticCategory.Error, "Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0_6200", "Definitions of the following identifiers conflict with those in another file: {0}"), + Conflicts_are_in_this_file: diag(6201, ts.DiagnosticCategory.Message, "Conflicts_are_in_this_file_6201", "Conflicts are in this file."), + _0_was_also_declared_here: diag(6203, ts.DiagnosticCategory.Message, "_0_was_also_declared_here_6203", "'{0}' was also declared here."), + and_here: diag(6204, ts.DiagnosticCategory.Message, "and_here_6204", "and here."), + All_type_parameters_are_unused: diag(6205, ts.DiagnosticCategory.Error, "All_type_parameters_are_unused_6205", "All type parameters are unused"), + package_json_has_a_typesVersions_field_with_version_specific_path_mappings: diag(6206, ts.DiagnosticCategory.Message, "package_json_has_a_typesVersions_field_with_version_specific_path_mappings_6206", "'package.json' has a 'typesVersions' field with version-specific path mappings."), + package_json_does_not_have_a_typesVersions_entry_that_matches_version_0: diag(6207, ts.DiagnosticCategory.Message, "package_json_does_not_have_a_typesVersions_entry_that_matches_version_0_6207", "'package.json' does not have a 'typesVersions' entry that matches version '{0}'."), + package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2: diag(6208, ts.DiagnosticCategory.Message, "package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_ma_6208", "'package.json' has a 'typesVersions' entry '{0}' that matches compiler version '{1}', looking for a pattern to match module name '{2}'."), + package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range: diag(6209, ts.DiagnosticCategory.Message, "package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range_6209", "'package.json' has a 'typesVersions' entry '{0}' that is not a valid semver range."), + An_argument_for_0_was_not_provided: diag(6210, ts.DiagnosticCategory.Message, "An_argument_for_0_was_not_provided_6210", "An argument for '{0}' was not provided."), + An_argument_matching_this_binding_pattern_was_not_provided: diag(6211, ts.DiagnosticCategory.Message, "An_argument_matching_this_binding_pattern_was_not_provided_6211", "An argument matching this binding pattern was not provided."), + Did_you_mean_to_call_this_expression: diag(6212, ts.DiagnosticCategory.Message, "Did_you_mean_to_call_this_expression_6212", "Did you mean to call this expression?"), + Did_you_mean_to_use_new_with_this_expression: diag(6213, ts.DiagnosticCategory.Message, "Did_you_mean_to_use_new_with_this_expression_6213", "Did you mean to use 'new' with this expression?"), + Enable_strict_bind_call_and_apply_methods_on_functions: diag(6214, ts.DiagnosticCategory.Message, "Enable_strict_bind_call_and_apply_methods_on_functions_6214", "Enable strict 'bind', 'call', and 'apply' methods on functions."), + Using_compiler_options_of_project_reference_redirect_0: diag(6215, ts.DiagnosticCategory.Message, "Using_compiler_options_of_project_reference_redirect_0_6215", "Using compiler options of project reference redirect '{0}'."), + Found_1_error: diag(6216, ts.DiagnosticCategory.Message, "Found_1_error_6216", "Found 1 error."), + Found_0_errors: diag(6217, ts.DiagnosticCategory.Message, "Found_0_errors_6217", "Found {0} errors."), + Projects_to_reference: diag(6300, ts.DiagnosticCategory.Message, "Projects_to_reference_6300", "Projects to reference"), + Enable_project_compilation: diag(6302, ts.DiagnosticCategory.Message, "Enable_project_compilation_6302", "Enable project compilation"), + Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0: diag(6202, ts.DiagnosticCategory.Error, "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202", "Project references may not form a circular graph. Cycle detected: {0}"), + Composite_projects_may_not_disable_declaration_emit: diag(6304, ts.DiagnosticCategory.Error, "Composite_projects_may_not_disable_declaration_emit_6304", "Composite projects may not disable declaration emit."), + Output_file_0_has_not_been_built_from_source_file_1: diag(6305, ts.DiagnosticCategory.Error, "Output_file_0_has_not_been_built_from_source_file_1_6305", "Output file '{0}' has not been built from source file '{1}'."), + Referenced_project_0_must_have_setting_composite_Colon_true: diag(6306, ts.DiagnosticCategory.Error, "Referenced_project_0_must_have_setting_composite_Colon_true_6306", "Referenced project '{0}' must have setting \"composite\": true."), + File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern: diag(6307, ts.DiagnosticCategory.Error, "File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern_6307", "File '{0}' is not in project file list. Projects must list all files or use an 'include' pattern."), + Cannot_prepend_project_0_because_it_does_not_have_outFile_set: diag(6308, ts.DiagnosticCategory.Error, "Cannot_prepend_project_0_because_it_does_not_have_outFile_set_6308", "Cannot prepend project '{0}' because it does not have 'outFile' set"), + Output_file_0_from_project_1_does_not_exist: diag(6309, ts.DiagnosticCategory.Error, "Output_file_0_from_project_1_does_not_exist_6309", "Output file '{0}' from project '{1}' does not exist"), + Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2: diag(6350, ts.DiagnosticCategory.Message, "Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2_6350", "Project '{0}' is out of date because oldest output '{1}' is older than newest input '{2}'"), + Project_0_is_up_to_date_because_newest_input_1_is_older_than_oldest_output_2: diag(6351, ts.DiagnosticCategory.Message, "Project_0_is_up_to_date_because_newest_input_1_is_older_than_oldest_output_2_6351", "Project '{0}' is up to date because newest input '{1}' is older than oldest output '{2}'"), + Project_0_is_out_of_date_because_output_file_1_does_not_exist: diag(6352, ts.DiagnosticCategory.Message, "Project_0_is_out_of_date_because_output_file_1_does_not_exist_6352", "Project '{0}' is out of date because output file '{1}' does not exist"), + Project_0_is_out_of_date_because_its_dependency_1_is_out_of_date: diag(6353, ts.DiagnosticCategory.Message, "Project_0_is_out_of_date_because_its_dependency_1_is_out_of_date_6353", "Project '{0}' is out of date because its dependency '{1}' is out of date"), + Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies: diag(6354, ts.DiagnosticCategory.Message, "Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies_6354", "Project '{0}' is up to date with .d.ts files from its dependencies"), + Projects_in_this_build_Colon_0: diag(6355, ts.DiagnosticCategory.Message, "Projects_in_this_build_Colon_0_6355", "Projects in this build: {0}"), + A_non_dry_build_would_delete_the_following_files_Colon_0: diag(6356, ts.DiagnosticCategory.Message, "A_non_dry_build_would_delete_the_following_files_Colon_0_6356", "A non-dry build would delete the following files: {0}"), + A_non_dry_build_would_build_project_0: diag(6357, ts.DiagnosticCategory.Message, "A_non_dry_build_would_build_project_0_6357", "A non-dry build would build project '{0}'"), + Building_project_0: diag(6358, ts.DiagnosticCategory.Message, "Building_project_0_6358", "Building project '{0}'..."), + Updating_output_timestamps_of_project_0: diag(6359, ts.DiagnosticCategory.Message, "Updating_output_timestamps_of_project_0_6359", "Updating output timestamps of project '{0}'..."), + delete_this_Project_0_is_up_to_date_because_it_was_previously_built: diag(6360, ts.DiagnosticCategory.Message, "delete_this_Project_0_is_up_to_date_because_it_was_previously_built_6360", "delete this - Project '{0}' is up to date because it was previously built"), + Project_0_is_up_to_date: diag(6361, ts.DiagnosticCategory.Message, "Project_0_is_up_to_date_6361", "Project '{0}' is up to date"), + Skipping_build_of_project_0_because_its_dependency_1_has_errors: diag(6362, ts.DiagnosticCategory.Message, "Skipping_build_of_project_0_because_its_dependency_1_has_errors_6362", "Skipping build of project '{0}' because its dependency '{1}' has errors"), + Project_0_can_t_be_built_because_its_dependency_1_has_errors: diag(6363, ts.DiagnosticCategory.Message, "Project_0_can_t_be_built_because_its_dependency_1_has_errors_6363", "Project '{0}' can't be built because its dependency '{1}' has errors"), + Build_one_or_more_projects_and_their_dependencies_if_out_of_date: diag(6364, ts.DiagnosticCategory.Message, "Build_one_or_more_projects_and_their_dependencies_if_out_of_date_6364", "Build one or more projects and their dependencies, if out of date"), + Delete_the_outputs_of_all_projects: diag(6365, ts.DiagnosticCategory.Message, "Delete_the_outputs_of_all_projects_6365", "Delete the outputs of all projects"), + Enable_verbose_logging: diag(6366, ts.DiagnosticCategory.Message, "Enable_verbose_logging_6366", "Enable verbose logging"), + Show_what_would_be_built_or_deleted_if_specified_with_clean: diag(6367, ts.DiagnosticCategory.Message, "Show_what_would_be_built_or_deleted_if_specified_with_clean_6367", "Show what would be built (or deleted, if specified with '--clean')"), + Build_all_projects_including_those_that_appear_to_be_up_to_date: diag(6368, ts.DiagnosticCategory.Message, "Build_all_projects_including_those_that_appear_to_be_up_to_date_6368", "Build all projects, including those that appear to be up to date"), + Option_build_must_be_the_first_command_line_argument: diag(6369, ts.DiagnosticCategory.Error, "Option_build_must_be_the_first_command_line_argument_6369", "Option '--build' must be the first command line argument."), + Options_0_and_1_cannot_be_combined: diag(6370, ts.DiagnosticCategory.Error, "Options_0_and_1_cannot_be_combined_6370", "Options '{0}' and '{1}' cannot be combined."), + The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1: diag(6500, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1_6500", "The expected type comes from property '{0}' which is declared here on type '{1}'"), + The_expected_type_comes_from_this_index_signature: diag(6501, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_this_index_signature_6501", "The expected type comes from this index signature."), + The_expected_type_comes_from_the_return_type_of_this_signature: diag(6502, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_the_return_type_of_this_signature_6502", "The expected type comes from the return type of this signature."), + Variable_0_implicitly_has_an_1_type: diag(7005, ts.DiagnosticCategory.Error, "Variable_0_implicitly_has_an_1_type_7005", "Variable '{0}' implicitly has an '{1}' type."), + Parameter_0_implicitly_has_an_1_type: diag(7006, ts.DiagnosticCategory.Error, "Parameter_0_implicitly_has_an_1_type_7006", "Parameter '{0}' implicitly has an '{1}' type."), + Member_0_implicitly_has_an_1_type: diag(7008, ts.DiagnosticCategory.Error, "Member_0_implicitly_has_an_1_type_7008", "Member '{0}' implicitly has an '{1}' type."), + new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type: diag(7009, ts.DiagnosticCategory.Error, "new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type_7009", "'new' expression, whose target lacks a construct signature, implicitly has an 'any' type."), + _0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type: diag(7010, ts.DiagnosticCategory.Error, "_0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type_7010", "'{0}', which lacks return-type annotation, implicitly has an '{1}' return type."), + Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type: diag(7011, ts.DiagnosticCategory.Error, "Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type_7011", "Function expression, which lacks return-type annotation, implicitly has an '{0}' return type."), + Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: diag(7013, ts.DiagnosticCategory.Error, "Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7013", "Construct signature, which lacks return-type annotation, implicitly has an 'any' return type."), + Function_type_which_lacks_return_type_annotation_implicitly_has_an_0_return_type: diag(7014, ts.DiagnosticCategory.Error, "Function_type_which_lacks_return_type_annotation_implicitly_has_an_0_return_type_7014", "Function type, which lacks return-type annotation, implicitly has an '{0}' return type."), + Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number: diag(7015, ts.DiagnosticCategory.Error, "Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015", "Element implicitly has an 'any' type because index expression is not of type 'number'."), + Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type: diag(7016, ts.DiagnosticCategory.Error, "Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type_7016", "Could not find a declaration file for module '{0}'. '{1}' implicitly has an 'any' type."), + Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature: diag(7017, ts.DiagnosticCategory.Error, "Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature_7017", "Element implicitly has an 'any' type because type '{0}' has no index signature."), + Object_literal_s_property_0_implicitly_has_an_1_type: diag(7018, ts.DiagnosticCategory.Error, "Object_literal_s_property_0_implicitly_has_an_1_type_7018", "Object literal's property '{0}' implicitly has an '{1}' type."), + Rest_parameter_0_implicitly_has_an_any_type: diag(7019, ts.DiagnosticCategory.Error, "Rest_parameter_0_implicitly_has_an_any_type_7019", "Rest parameter '{0}' implicitly has an 'any[]' type."), + Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: diag(7020, ts.DiagnosticCategory.Error, "Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7020", "Call signature, which lacks return-type annotation, implicitly has an 'any' return type."), + _0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer: diag(7022, ts.DiagnosticCategory.Error, "_0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or__7022", "'{0}' implicitly has type 'any' because it does not have a type annotation and is referenced directly or indirectly in its own initializer."), + _0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions: diag(7023, ts.DiagnosticCategory.Error, "_0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_reference_7023", "'{0}' implicitly has return type 'any' because it does not have a return type annotation and is referenced directly or indirectly in one of its return expressions."), + Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions: diag(7024, ts.DiagnosticCategory.Error, "Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_ref_7024", "Function implicitly has return type 'any' because it does not have a return type annotation and is referenced directly or indirectly in one of its return expressions."), + Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_type: diag(7025, ts.DiagnosticCategory.Error, "Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_typ_7025", "Generator implicitly has type '{0}' because it does not yield any values. Consider supplying a return type."), + JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists: diag(7026, ts.DiagnosticCategory.Error, "JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists_7026", "JSX element implicitly has type 'any' because no interface 'JSX.{0}' exists."), + Unreachable_code_detected: diag(7027, ts.DiagnosticCategory.Error, "Unreachable_code_detected_7027", "Unreachable code detected.", /*reportsUnnecessary*/ true), + Unused_label: diag(7028, ts.DiagnosticCategory.Error, "Unused_label_7028", "Unused label.", /*reportsUnnecessary*/ true), + Fallthrough_case_in_switch: diag(7029, ts.DiagnosticCategory.Error, "Fallthrough_case_in_switch_7029", "Fallthrough case in switch."), + Not_all_code_paths_return_a_value: diag(7030, ts.DiagnosticCategory.Error, "Not_all_code_paths_return_a_value_7030", "Not all code paths return a value."), + Binding_element_0_implicitly_has_an_1_type: diag(7031, ts.DiagnosticCategory.Error, "Binding_element_0_implicitly_has_an_1_type_7031", "Binding element '{0}' implicitly has an '{1}' type."), + Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation: diag(7032, ts.DiagnosticCategory.Error, "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032", "Property '{0}' implicitly has type 'any', because its set accessor lacks a parameter type annotation."), + Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation: diag(7033, ts.DiagnosticCategory.Error, "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033", "Property '{0}' implicitly has type 'any', because its get accessor lacks a return type annotation."), + Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined: diag(7034, ts.DiagnosticCategory.Error, "Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined_7034", "Variable '{0}' implicitly has type '{1}' in some locations where its type cannot be determined."), + Try_npm_install_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0: diag(7035, ts.DiagnosticCategory.Error, "Try_npm_install_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_mod_7035", "Try `npm install @types/{1}` if it exists or add a new declaration (.d.ts) file containing `declare module '{0}';`"), + Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0: diag(7036, ts.DiagnosticCategory.Error, "Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036", "Dynamic import's specifier must be of type 'string', but here has type '{0}'."), + Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for_all_imports_Implies_allowSyntheticDefaultImports: diag(7037, ts.DiagnosticCategory.Message, "Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for__7037", "Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'."), + Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_Consider_using_a_default_import_or_import_require_here_instead: diag(7038, ts.DiagnosticCategory.Message, "Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cau_7038", "Type originates at this import. A namespace-style import cannot be called or constructed, and will cause a failure at runtime. Consider using a default import or import require here instead."), + Mapped_object_type_implicitly_has_an_any_template_type: diag(7039, ts.DiagnosticCategory.Error, "Mapped_object_type_implicitly_has_an_any_template_type_7039", "Mapped object type implicitly has an 'any' template type."), + If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1: diag(7040, ts.DiagnosticCategory.Error, "If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_S_7040", "If the '{0}' package actually exposes this module, consider sending a pull request to amend 'https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/{1}`"), + The_containing_arrow_function_captures_the_global_value_of_this_which_implicitly_has_type_any: diag(7041, ts.DiagnosticCategory.Error, "The_containing_arrow_function_captures_the_global_value_of_this_which_implicitly_has_type_any_7041", "The containing arrow function captures the global value of 'this' which implicitly has type 'any'."), + Module_0_was_resolved_to_1_but_resolveJsonModule_is_not_used: diag(7042, ts.DiagnosticCategory.Error, "Module_0_was_resolved_to_1_but_resolveJsonModule_is_not_used_7042", "Module '{0}' was resolved to '{1}', but '--resolveJsonModule' is not used."), + Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage: diag(7043, ts.DiagnosticCategory.Suggestion, "Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7043", "Variable '{0}' implicitly has an '{1}' type, but a better type may be inferred from usage."), + Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage: diag(7044, ts.DiagnosticCategory.Suggestion, "Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7044", "Parameter '{0}' implicitly has an '{1}' type, but a better type may be inferred from usage."), + Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage: diag(7045, ts.DiagnosticCategory.Suggestion, "Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7045", "Member '{0}' implicitly has an '{1}' type, but a better type may be inferred from usage."), + Variable_0_implicitly_has_type_1_in_some_locations_but_a_better_type_may_be_inferred_from_usage: diag(7046, ts.DiagnosticCategory.Suggestion, "Variable_0_implicitly_has_type_1_in_some_locations_but_a_better_type_may_be_inferred_from_usage_7046", "Variable '{0}' implicitly has type '{1}' in some locations, but a better type may be inferred from usage."), + Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage: diag(7047, ts.DiagnosticCategory.Suggestion, "Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage_7047", "Rest parameter '{0}' implicitly has an 'any[]' type, but a better type may be inferred from usage."), + Property_0_implicitly_has_type_any_but_a_better_type_for_its_get_accessor_may_be_inferred_from_usage: diag(7048, ts.DiagnosticCategory.Suggestion, "Property_0_implicitly_has_type_any_but_a_better_type_for_its_get_accessor_may_be_inferred_from_usage_7048", "Property '{0}' implicitly has type 'any', but a better type for its get accessor may be inferred from usage."), + Property_0_implicitly_has_type_any_but_a_better_type_for_its_set_accessor_may_be_inferred_from_usage: diag(7049, ts.DiagnosticCategory.Suggestion, "Property_0_implicitly_has_type_any_but_a_better_type_for_its_set_accessor_may_be_inferred_from_usage_7049", "Property '{0}' implicitly has type 'any', but a better type for its set accessor may be inferred from usage."), + _0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage: diag(7050, ts.DiagnosticCategory.Suggestion, "_0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage_7050", "'{0}' implicitly has an '{1}' return type, but a better type may be inferred from usage."), + Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1: diag(7051, ts.DiagnosticCategory.Error, "Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1_7051", "Parameter has a name but no type. Did you mean '{0}: {1}'?"), + You_cannot_rename_this_element: diag(8000, ts.DiagnosticCategory.Error, "You_cannot_rename_this_element_8000", "You cannot rename this element."), + You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library: diag(8001, ts.DiagnosticCategory.Error, "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001", "You cannot rename elements that are defined in the standard TypeScript library."), + import_can_only_be_used_in_a_ts_file: diag(8002, ts.DiagnosticCategory.Error, "import_can_only_be_used_in_a_ts_file_8002", "'import ... =' can only be used in a .ts file."), + export_can_only_be_used_in_a_ts_file: diag(8003, ts.DiagnosticCategory.Error, "export_can_only_be_used_in_a_ts_file_8003", "'export=' can only be used in a .ts file."), + type_parameter_declarations_can_only_be_used_in_a_ts_file: diag(8004, ts.DiagnosticCategory.Error, "type_parameter_declarations_can_only_be_used_in_a_ts_file_8004", "'type parameter declarations' can only be used in a .ts file."), + implements_clauses_can_only_be_used_in_a_ts_file: diag(8005, ts.DiagnosticCategory.Error, "implements_clauses_can_only_be_used_in_a_ts_file_8005", "'implements clauses' can only be used in a .ts file."), + interface_declarations_can_only_be_used_in_a_ts_file: diag(8006, ts.DiagnosticCategory.Error, "interface_declarations_can_only_be_used_in_a_ts_file_8006", "'interface declarations' can only be used in a .ts file."), + module_declarations_can_only_be_used_in_a_ts_file: diag(8007, ts.DiagnosticCategory.Error, "module_declarations_can_only_be_used_in_a_ts_file_8007", "'module declarations' can only be used in a .ts file."), + type_aliases_can_only_be_used_in_a_ts_file: diag(8008, ts.DiagnosticCategory.Error, "type_aliases_can_only_be_used_in_a_ts_file_8008", "'type aliases' can only be used in a .ts file."), + _0_can_only_be_used_in_a_ts_file: diag(8009, ts.DiagnosticCategory.Error, "_0_can_only_be_used_in_a_ts_file_8009", "'{0}' can only be used in a .ts file."), + types_can_only_be_used_in_a_ts_file: diag(8010, ts.DiagnosticCategory.Error, "types_can_only_be_used_in_a_ts_file_8010", "'types' can only be used in a .ts file."), + type_arguments_can_only_be_used_in_a_ts_file: diag(8011, ts.DiagnosticCategory.Error, "type_arguments_can_only_be_used_in_a_ts_file_8011", "'type arguments' can only be used in a .ts file."), + parameter_modifiers_can_only_be_used_in_a_ts_file: diag(8012, ts.DiagnosticCategory.Error, "parameter_modifiers_can_only_be_used_in_a_ts_file_8012", "'parameter modifiers' can only be used in a .ts file."), + non_null_assertions_can_only_be_used_in_a_ts_file: diag(8013, ts.DiagnosticCategory.Error, "non_null_assertions_can_only_be_used_in_a_ts_file_8013", "'non-null assertions' can only be used in a .ts file."), + enum_declarations_can_only_be_used_in_a_ts_file: diag(8015, ts.DiagnosticCategory.Error, "enum_declarations_can_only_be_used_in_a_ts_file_8015", "'enum declarations' can only be used in a .ts file."), + type_assertion_expressions_can_only_be_used_in_a_ts_file: diag(8016, ts.DiagnosticCategory.Error, "type_assertion_expressions_can_only_be_used_in_a_ts_file_8016", "'type assertion expressions' can only be used in a .ts file."), + Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0: diag(8017, ts.DiagnosticCategory.Error, "Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0_8017", "Octal literal types must use ES2015 syntax. Use the syntax '{0}'."), + Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0: diag(8018, ts.DiagnosticCategory.Error, "Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0_8018", "Octal literals are not allowed in enums members initializer. Use the syntax '{0}'."), + Report_errors_in_js_files: diag(8019, ts.DiagnosticCategory.Message, "Report_errors_in_js_files_8019", "Report errors in .js files."), + JSDoc_types_can_only_be_used_inside_documentation_comments: diag(8020, ts.DiagnosticCategory.Error, "JSDoc_types_can_only_be_used_inside_documentation_comments_8020", "JSDoc types can only be used inside documentation comments."), + JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags: diag(8021, ts.DiagnosticCategory.Error, "JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags_8021", "JSDoc '@typedef' tag should either have a type annotation or be followed by '@property' or '@member' tags."), + JSDoc_0_is_not_attached_to_a_class: diag(8022, ts.DiagnosticCategory.Error, "JSDoc_0_is_not_attached_to_a_class_8022", "JSDoc '@{0}' is not attached to a class."), + JSDoc_0_1_does_not_match_the_extends_2_clause: diag(8023, ts.DiagnosticCategory.Error, "JSDoc_0_1_does_not_match_the_extends_2_clause_8023", "JSDoc '@{0} {1}' does not match the 'extends {2}' clause."), + JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name: diag(8024, ts.DiagnosticCategory.Error, "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_8024", "JSDoc '@param' tag has name '{0}', but there is no parameter with that name."), + Class_declarations_cannot_have_more_than_one_augments_or_extends_tag: diag(8025, ts.DiagnosticCategory.Error, "Class_declarations_cannot_have_more_than_one_augments_or_extends_tag_8025", "Class declarations cannot have more than one `@augments` or `@extends` tag."), + Expected_0_type_arguments_provide_these_with_an_extends_tag: diag(8026, ts.DiagnosticCategory.Error, "Expected_0_type_arguments_provide_these_with_an_extends_tag_8026", "Expected {0} type arguments; provide these with an '@extends' tag."), + Expected_0_1_type_arguments_provide_these_with_an_extends_tag: diag(8027, ts.DiagnosticCategory.Error, "Expected_0_1_type_arguments_provide_these_with_an_extends_tag_8027", "Expected {0}-{1} type arguments; provide these with an '@extends' tag."), + JSDoc_may_only_appear_in_the_last_parameter_of_a_signature: diag(8028, ts.DiagnosticCategory.Error, "JSDoc_may_only_appear_in_the_last_parameter_of_a_signature_8028", "JSDoc '...' may only appear in the last parameter of a signature."), + JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_had_an_array_type: diag(8029, ts.DiagnosticCategory.Error, "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_h_8029", "JSDoc '@param' tag has name '{0}', but there is no parameter with that name. It would match 'arguments' if it had an array type."), + The_type_of_a_function_declaration_must_match_the_function_s_signature: diag(8030, ts.DiagnosticCategory.Error, "The_type_of_a_function_declaration_must_match_the_function_s_signature_8030", "The type of a function declaration must match the function's signature."), + You_cannot_rename_a_module_via_a_global_import: diag(8031, ts.DiagnosticCategory.Error, "You_cannot_rename_a_module_via_a_global_import_8031", "You cannot rename a module via a global import."), + Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_class_extends_clause: diag(9002, ts.DiagnosticCategory.Error, "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002", "Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clause."), + class_expressions_are_not_currently_supported: diag(9003, ts.DiagnosticCategory.Error, "class_expressions_are_not_currently_supported_9003", "'class' expressions are not currently supported."), + Language_service_is_disabled: diag(9004, ts.DiagnosticCategory.Error, "Language_service_is_disabled_9004", "Language service is disabled."), + JSX_attributes_must_only_be_assigned_a_non_empty_expression: diag(17000, ts.DiagnosticCategory.Error, "JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000", "JSX attributes must only be assigned a non-empty 'expression'."), + JSX_elements_cannot_have_multiple_attributes_with_the_same_name: diag(17001, ts.DiagnosticCategory.Error, "JSX_elements_cannot_have_multiple_attributes_with_the_same_name_17001", "JSX elements cannot have multiple attributes with the same name."), + Expected_corresponding_JSX_closing_tag_for_0: diag(17002, ts.DiagnosticCategory.Error, "Expected_corresponding_JSX_closing_tag_for_0_17002", "Expected corresponding JSX closing tag for '{0}'."), + JSX_attribute_expected: diag(17003, ts.DiagnosticCategory.Error, "JSX_attribute_expected_17003", "JSX attribute expected."), + Cannot_use_JSX_unless_the_jsx_flag_is_provided: diag(17004, ts.DiagnosticCategory.Error, "Cannot_use_JSX_unless_the_jsx_flag_is_provided_17004", "Cannot use JSX unless the '--jsx' flag is provided."), + A_constructor_cannot_contain_a_super_call_when_its_class_extends_null: diag(17005, ts.DiagnosticCategory.Error, "A_constructor_cannot_contain_a_super_call_when_its_class_extends_null_17005", "A constructor cannot contain a 'super' call when its class extends 'null'."), + An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses: diag(17006, ts.DiagnosticCategory.Error, "An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_ex_17006", "An unary expression with the '{0}' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses."), + A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses: diag(17007, ts.DiagnosticCategory.Error, "A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Con_17007", "A type assertion expression is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses."), + JSX_element_0_has_no_corresponding_closing_tag: diag(17008, ts.DiagnosticCategory.Error, "JSX_element_0_has_no_corresponding_closing_tag_17008", "JSX element '{0}' has no corresponding closing tag."), + super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class: diag(17009, ts.DiagnosticCategory.Error, "super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class_17009", "'super' must be called before accessing 'this' in the constructor of a derived class."), + Unknown_type_acquisition_option_0: diag(17010, ts.DiagnosticCategory.Error, "Unknown_type_acquisition_option_0_17010", "Unknown type acquisition option '{0}'."), + super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class: diag(17011, ts.DiagnosticCategory.Error, "super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class_17011", "'super' must be called before accessing a property of 'super' in the constructor of a derived class."), + _0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2: diag(17012, ts.DiagnosticCategory.Error, "_0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2_17012", "'{0}' is not a valid meta-property for keyword '{1}'. Did you mean '{2}'?"), + Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constructor: diag(17013, ts.DiagnosticCategory.Error, "Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constru_17013", "Meta-property '{0}' is only allowed in the body of a function declaration, function expression, or constructor."), + JSX_fragment_has_no_corresponding_closing_tag: diag(17014, ts.DiagnosticCategory.Error, "JSX_fragment_has_no_corresponding_closing_tag_17014", "JSX fragment has no corresponding closing tag."), + Expected_corresponding_closing_tag_for_JSX_fragment: diag(17015, ts.DiagnosticCategory.Error, "Expected_corresponding_closing_tag_for_JSX_fragment_17015", "Expected corresponding closing tag for JSX fragment."), + JSX_fragment_is_not_supported_when_using_jsxFactory: diag(17016, ts.DiagnosticCategory.Error, "JSX_fragment_is_not_supported_when_using_jsxFactory_17016", "JSX fragment is not supported when using --jsxFactory"), + JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma: diag(17017, ts.DiagnosticCategory.Error, "JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma_17017", "JSX fragment is not supported when using an inline JSX factory pragma"), + Circularity_detected_while_resolving_configuration_Colon_0: diag(18000, ts.DiagnosticCategory.Error, "Circularity_detected_while_resolving_configuration_Colon_0_18000", "Circularity detected while resolving configuration: {0}"), + A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not: diag(18001, ts.DiagnosticCategory.Error, "A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not_18001", "A path in an 'extends' option must be relative or rooted, but '{0}' is not."), + The_files_list_in_config_file_0_is_empty: diag(18002, ts.DiagnosticCategory.Error, "The_files_list_in_config_file_0_is_empty_18002", "The 'files' list in config file '{0}' is empty."), + No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2: diag(18003, ts.DiagnosticCategory.Error, "No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2_18003", "No inputs were found in config file '{0}'. Specified 'include' paths were '{1}' and 'exclude' paths were '{2}'."), + File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module: diag(80001, ts.DiagnosticCategory.Suggestion, "File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module_80001", "File is a CommonJS module; it may be converted to an ES6 module."), + This_constructor_function_may_be_converted_to_a_class_declaration: diag(80002, ts.DiagnosticCategory.Suggestion, "This_constructor_function_may_be_converted_to_a_class_declaration_80002", "This constructor function may be converted to a class declaration."), + Import_may_be_converted_to_a_default_import: diag(80003, ts.DiagnosticCategory.Suggestion, "Import_may_be_converted_to_a_default_import_80003", "Import may be converted to a default import."), + JSDoc_types_may_be_moved_to_TypeScript_types: diag(80004, ts.DiagnosticCategory.Suggestion, "JSDoc_types_may_be_moved_to_TypeScript_types_80004", "JSDoc types may be moved to TypeScript types."), + require_call_may_be_converted_to_an_import: diag(80005, ts.DiagnosticCategory.Suggestion, "require_call_may_be_converted_to_an_import_80005", "'require' call may be converted to an import."), + This_may_be_converted_to_an_async_function: diag(80006, ts.DiagnosticCategory.Suggestion, "This_may_be_converted_to_an_async_function_80006", "This may be converted to an async function."), + Add_missing_super_call: diag(90001, ts.DiagnosticCategory.Message, "Add_missing_super_call_90001", "Add missing 'super()' call"), + Make_super_call_the_first_statement_in_the_constructor: diag(90002, ts.DiagnosticCategory.Message, "Make_super_call_the_first_statement_in_the_constructor_90002", "Make 'super()' call the first statement in the constructor"), + Change_extends_to_implements: diag(90003, ts.DiagnosticCategory.Message, "Change_extends_to_implements_90003", "Change 'extends' to 'implements'"), + Remove_declaration_for_Colon_0: diag(90004, ts.DiagnosticCategory.Message, "Remove_declaration_for_Colon_0_90004", "Remove declaration for: '{0}'"), + Remove_import_from_0: diag(90005, ts.DiagnosticCategory.Message, "Remove_import_from_0_90005", "Remove import from '{0}'"), + Implement_interface_0: diag(90006, ts.DiagnosticCategory.Message, "Implement_interface_0_90006", "Implement interface '{0}'"), + Implement_inherited_abstract_class: diag(90007, ts.DiagnosticCategory.Message, "Implement_inherited_abstract_class_90007", "Implement inherited abstract class"), + Add_0_to_unresolved_variable: diag(90008, ts.DiagnosticCategory.Message, "Add_0_to_unresolved_variable_90008", "Add '{0}.' to unresolved variable"), + Remove_destructuring: diag(90009, ts.DiagnosticCategory.Message, "Remove_destructuring_90009", "Remove destructuring"), + Remove_variable_statement: diag(90010, ts.DiagnosticCategory.Message, "Remove_variable_statement_90010", "Remove variable statement"), + Remove_template_tag: diag(90011, ts.DiagnosticCategory.Message, "Remove_template_tag_90011", "Remove template tag"), + Remove_type_parameters: diag(90012, ts.DiagnosticCategory.Message, "Remove_type_parameters_90012", "Remove type parameters"), + Import_0_from_module_1: diag(90013, ts.DiagnosticCategory.Message, "Import_0_from_module_1_90013", "Import '{0}' from module \"{1}\""), + Change_0_to_1: diag(90014, ts.DiagnosticCategory.Message, "Change_0_to_1_90014", "Change '{0}' to '{1}'"), + Add_0_to_existing_import_declaration_from_1: diag(90015, ts.DiagnosticCategory.Message, "Add_0_to_existing_import_declaration_from_1_90015", "Add '{0}' to existing import declaration from \"{1}\""), + Declare_property_0: diag(90016, ts.DiagnosticCategory.Message, "Declare_property_0_90016", "Declare property '{0}'"), + Add_index_signature_for_property_0: diag(90017, ts.DiagnosticCategory.Message, "Add_index_signature_for_property_0_90017", "Add index signature for property '{0}'"), + Disable_checking_for_this_file: diag(90018, ts.DiagnosticCategory.Message, "Disable_checking_for_this_file_90018", "Disable checking for this file"), + Ignore_this_error_message: diag(90019, ts.DiagnosticCategory.Message, "Ignore_this_error_message_90019", "Ignore this error message"), + Initialize_property_0_in_the_constructor: diag(90020, ts.DiagnosticCategory.Message, "Initialize_property_0_in_the_constructor_90020", "Initialize property '{0}' in the constructor"), + Initialize_static_property_0: diag(90021, ts.DiagnosticCategory.Message, "Initialize_static_property_0_90021", "Initialize static property '{0}'"), + Change_spelling_to_0: diag(90022, ts.DiagnosticCategory.Message, "Change_spelling_to_0_90022", "Change spelling to '{0}'"), + Declare_method_0: diag(90023, ts.DiagnosticCategory.Message, "Declare_method_0_90023", "Declare method '{0}'"), + Declare_static_method_0: diag(90024, ts.DiagnosticCategory.Message, "Declare_static_method_0_90024", "Declare static method '{0}'"), + Prefix_0_with_an_underscore: diag(90025, ts.DiagnosticCategory.Message, "Prefix_0_with_an_underscore_90025", "Prefix '{0}' with an underscore"), + Rewrite_as_the_indexed_access_type_0: diag(90026, ts.DiagnosticCategory.Message, "Rewrite_as_the_indexed_access_type_0_90026", "Rewrite as the indexed access type '{0}'"), + Declare_static_property_0: diag(90027, ts.DiagnosticCategory.Message, "Declare_static_property_0_90027", "Declare static property '{0}'"), + Call_decorator_expression: diag(90028, ts.DiagnosticCategory.Message, "Call_decorator_expression_90028", "Call decorator expression"), + Add_async_modifier_to_containing_function: diag(90029, ts.DiagnosticCategory.Message, "Add_async_modifier_to_containing_function_90029", "Add async modifier to containing function"), + Replace_infer_0_with_unknown: diag(90030, ts.DiagnosticCategory.Message, "Replace_infer_0_with_unknown_90030", "Replace 'infer {0}' with 'unknown'"), + Replace_all_unused_infer_with_unknown: diag(90031, ts.DiagnosticCategory.Message, "Replace_all_unused_infer_with_unknown_90031", "Replace all unused 'infer' with 'unknown'"), + Import_default_0_from_module_1: diag(90032, ts.DiagnosticCategory.Message, "Import_default_0_from_module_1_90032", "Import default '{0}' from module \"{1}\""), + Add_default_import_0_to_existing_import_declaration_from_1: diag(90033, ts.DiagnosticCategory.Message, "Add_default_import_0_to_existing_import_declaration_from_1_90033", "Add default import '{0}' to existing import declaration from \"{1}\""), + Add_parameter_name: diag(90034, ts.DiagnosticCategory.Message, "Add_parameter_name_90034", "Add parameter name"), + Convert_function_to_an_ES2015_class: diag(95001, ts.DiagnosticCategory.Message, "Convert_function_to_an_ES2015_class_95001", "Convert function to an ES2015 class"), + Convert_function_0_to_class: diag(95002, ts.DiagnosticCategory.Message, "Convert_function_0_to_class_95002", "Convert function '{0}' to class"), + Extract_to_0_in_1: diag(95004, ts.DiagnosticCategory.Message, "Extract_to_0_in_1_95004", "Extract to {0} in {1}"), + Extract_function: diag(95005, ts.DiagnosticCategory.Message, "Extract_function_95005", "Extract function"), + Extract_constant: diag(95006, ts.DiagnosticCategory.Message, "Extract_constant_95006", "Extract constant"), + Extract_to_0_in_enclosing_scope: diag(95007, ts.DiagnosticCategory.Message, "Extract_to_0_in_enclosing_scope_95007", "Extract to {0} in enclosing scope"), + Extract_to_0_in_1_scope: diag(95008, ts.DiagnosticCategory.Message, "Extract_to_0_in_1_scope_95008", "Extract to {0} in {1} scope"), + Annotate_with_type_from_JSDoc: diag(95009, ts.DiagnosticCategory.Message, "Annotate_with_type_from_JSDoc_95009", "Annotate with type from JSDoc"), + Annotate_with_types_from_JSDoc: diag(95010, ts.DiagnosticCategory.Message, "Annotate_with_types_from_JSDoc_95010", "Annotate with types from JSDoc"), + Infer_type_of_0_from_usage: diag(95011, ts.DiagnosticCategory.Message, "Infer_type_of_0_from_usage_95011", "Infer type of '{0}' from usage"), + Infer_parameter_types_from_usage: diag(95012, ts.DiagnosticCategory.Message, "Infer_parameter_types_from_usage_95012", "Infer parameter types from usage"), + Convert_to_default_import: diag(95013, ts.DiagnosticCategory.Message, "Convert_to_default_import_95013", "Convert to default import"), + Install_0: diag(95014, ts.DiagnosticCategory.Message, "Install_0_95014", "Install '{0}'"), + Replace_import_with_0: diag(95015, ts.DiagnosticCategory.Message, "Replace_import_with_0_95015", "Replace import with '{0}'."), + Use_synthetic_default_member: diag(95016, ts.DiagnosticCategory.Message, "Use_synthetic_default_member_95016", "Use synthetic 'default' member."), + Convert_to_ES6_module: diag(95017, ts.DiagnosticCategory.Message, "Convert_to_ES6_module_95017", "Convert to ES6 module"), + Add_undefined_type_to_property_0: diag(95018, ts.DiagnosticCategory.Message, "Add_undefined_type_to_property_0_95018", "Add 'undefined' type to property '{0}'"), + Add_initializer_to_property_0: diag(95019, ts.DiagnosticCategory.Message, "Add_initializer_to_property_0_95019", "Add initializer to property '{0}'"), + Add_definite_assignment_assertion_to_property_0: diag(95020, ts.DiagnosticCategory.Message, "Add_definite_assignment_assertion_to_property_0_95020", "Add definite assignment assertion to property '{0}'"), + Add_all_missing_members: diag(95022, ts.DiagnosticCategory.Message, "Add_all_missing_members_95022", "Add all missing members"), + Infer_all_types_from_usage: diag(95023, ts.DiagnosticCategory.Message, "Infer_all_types_from_usage_95023", "Infer all types from usage"), + Delete_all_unused_declarations: diag(95024, ts.DiagnosticCategory.Message, "Delete_all_unused_declarations_95024", "Delete all unused declarations"), + Prefix_all_unused_declarations_with_where_possible: diag(95025, ts.DiagnosticCategory.Message, "Prefix_all_unused_declarations_with_where_possible_95025", "Prefix all unused declarations with '_' where possible"), + Fix_all_detected_spelling_errors: diag(95026, ts.DiagnosticCategory.Message, "Fix_all_detected_spelling_errors_95026", "Fix all detected spelling errors"), + Add_initializers_to_all_uninitialized_properties: diag(95027, ts.DiagnosticCategory.Message, "Add_initializers_to_all_uninitialized_properties_95027", "Add initializers to all uninitialized properties"), + Add_definite_assignment_assertions_to_all_uninitialized_properties: diag(95028, ts.DiagnosticCategory.Message, "Add_definite_assignment_assertions_to_all_uninitialized_properties_95028", "Add definite assignment assertions to all uninitialized properties"), + Add_undefined_type_to_all_uninitialized_properties: diag(95029, ts.DiagnosticCategory.Message, "Add_undefined_type_to_all_uninitialized_properties_95029", "Add undefined type to all uninitialized properties"), + Change_all_jsdoc_style_types_to_TypeScript: diag(95030, ts.DiagnosticCategory.Message, "Change_all_jsdoc_style_types_to_TypeScript_95030", "Change all jsdoc-style types to TypeScript"), + Change_all_jsdoc_style_types_to_TypeScript_and_add_undefined_to_nullable_types: diag(95031, ts.DiagnosticCategory.Message, "Change_all_jsdoc_style_types_to_TypeScript_and_add_undefined_to_nullable_types_95031", "Change all jsdoc-style types to TypeScript (and add '| undefined' to nullable types)"), + Implement_all_unimplemented_interfaces: diag(95032, ts.DiagnosticCategory.Message, "Implement_all_unimplemented_interfaces_95032", "Implement all unimplemented interfaces"), + Install_all_missing_types_packages: diag(95033, ts.DiagnosticCategory.Message, "Install_all_missing_types_packages_95033", "Install all missing types packages"), + Rewrite_all_as_indexed_access_types: diag(95034, ts.DiagnosticCategory.Message, "Rewrite_all_as_indexed_access_types_95034", "Rewrite all as indexed access types"), + Convert_all_to_default_imports: diag(95035, ts.DiagnosticCategory.Message, "Convert_all_to_default_imports_95035", "Convert all to default imports"), + Make_all_super_calls_the_first_statement_in_their_constructor: diag(95036, ts.DiagnosticCategory.Message, "Make_all_super_calls_the_first_statement_in_their_constructor_95036", "Make all 'super()' calls the first statement in their constructor"), + Add_qualifier_to_all_unresolved_variables_matching_a_member_name: diag(95037, ts.DiagnosticCategory.Message, "Add_qualifier_to_all_unresolved_variables_matching_a_member_name_95037", "Add qualifier to all unresolved variables matching a member name"), + Change_all_extended_interfaces_to_implements: diag(95038, ts.DiagnosticCategory.Message, "Change_all_extended_interfaces_to_implements_95038", "Change all extended interfaces to 'implements'"), + Add_all_missing_super_calls: diag(95039, ts.DiagnosticCategory.Message, "Add_all_missing_super_calls_95039", "Add all missing super calls"), + Implement_all_inherited_abstract_classes: diag(95040, ts.DiagnosticCategory.Message, "Implement_all_inherited_abstract_classes_95040", "Implement all inherited abstract classes"), + Add_all_missing_async_modifiers: diag(95041, ts.DiagnosticCategory.Message, "Add_all_missing_async_modifiers_95041", "Add all missing 'async' modifiers"), + Add_ts_ignore_to_all_error_messages: diag(95042, ts.DiagnosticCategory.Message, "Add_ts_ignore_to_all_error_messages_95042", "Add '@ts-ignore' to all error messages"), + Annotate_everything_with_types_from_JSDoc: diag(95043, ts.DiagnosticCategory.Message, "Annotate_everything_with_types_from_JSDoc_95043", "Annotate everything with types from JSDoc"), + Add_to_all_uncalled_decorators: diag(95044, ts.DiagnosticCategory.Message, "Add_to_all_uncalled_decorators_95044", "Add '()' to all uncalled decorators"), + Convert_all_constructor_functions_to_classes: diag(95045, ts.DiagnosticCategory.Message, "Convert_all_constructor_functions_to_classes_95045", "Convert all constructor functions to classes"), + Generate_get_and_set_accessors: diag(95046, ts.DiagnosticCategory.Message, "Generate_get_and_set_accessors_95046", "Generate 'get' and 'set' accessors"), + Convert_require_to_import: diag(95047, ts.DiagnosticCategory.Message, "Convert_require_to_import_95047", "Convert 'require' to 'import'"), + Convert_all_require_to_import: diag(95048, ts.DiagnosticCategory.Message, "Convert_all_require_to_import_95048", "Convert all 'require' to 'import'"), + Move_to_a_new_file: diag(95049, ts.DiagnosticCategory.Message, "Move_to_a_new_file_95049", "Move to a new file"), + Remove_unreachable_code: diag(95050, ts.DiagnosticCategory.Message, "Remove_unreachable_code_95050", "Remove unreachable code"), + Remove_all_unreachable_code: diag(95051, ts.DiagnosticCategory.Message, "Remove_all_unreachable_code_95051", "Remove all unreachable code"), + Add_missing_typeof: diag(95052, ts.DiagnosticCategory.Message, "Add_missing_typeof_95052", "Add missing 'typeof'"), + Remove_unused_label: diag(95053, ts.DiagnosticCategory.Message, "Remove_unused_label_95053", "Remove unused label"), + Remove_all_unused_labels: diag(95054, ts.DiagnosticCategory.Message, "Remove_all_unused_labels_95054", "Remove all unused labels"), + Convert_0_to_mapped_object_type: diag(95055, ts.DiagnosticCategory.Message, "Convert_0_to_mapped_object_type_95055", "Convert '{0}' to mapped object type"), + Convert_namespace_import_to_named_imports: diag(95056, ts.DiagnosticCategory.Message, "Convert_namespace_import_to_named_imports_95056", "Convert namespace import to named imports"), + Convert_named_imports_to_namespace_import: diag(95057, ts.DiagnosticCategory.Message, "Convert_named_imports_to_namespace_import_95057", "Convert named imports to namespace import"), + Add_or_remove_braces_in_an_arrow_function: diag(95058, ts.DiagnosticCategory.Message, "Add_or_remove_braces_in_an_arrow_function_95058", "Add or remove braces in an arrow function"), + Add_braces_to_arrow_function: diag(95059, ts.DiagnosticCategory.Message, "Add_braces_to_arrow_function_95059", "Add braces to arrow function"), + Remove_braces_from_arrow_function: diag(95060, ts.DiagnosticCategory.Message, "Remove_braces_from_arrow_function_95060", "Remove braces from arrow function"), + Convert_default_export_to_named_export: diag(95061, ts.DiagnosticCategory.Message, "Convert_default_export_to_named_export_95061", "Convert default export to named export"), + Convert_named_export_to_default_export: diag(95062, ts.DiagnosticCategory.Message, "Convert_named_export_to_default_export_95062", "Convert named export to default export"), + Add_missing_enum_member_0: diag(95063, ts.DiagnosticCategory.Message, "Add_missing_enum_member_0_95063", "Add missing enum member '{0}'"), + Add_all_missing_imports: diag(95064, ts.DiagnosticCategory.Message, "Add_all_missing_imports_95064", "Add all missing imports"), + Convert_to_async_function: diag(95065, ts.DiagnosticCategory.Message, "Convert_to_async_function_95065", "Convert to async function"), + Convert_all_to_async_functions: diag(95066, ts.DiagnosticCategory.Message, "Convert_all_to_async_functions_95066", "Convert all to async functions"), + Generate_types_for_0: diag(95067, ts.DiagnosticCategory.Message, "Generate_types_for_0_95067", "Generate types for '{0}'"), + Generate_types_for_all_packages_without_types: diag(95068, ts.DiagnosticCategory.Message, "Generate_types_for_all_packages_without_types_95068", "Generate types for all packages without types"), + Add_unknown_conversion_for_non_overlapping_types: diag(95069, ts.DiagnosticCategory.Message, "Add_unknown_conversion_for_non_overlapping_types_95069", "Add 'unknown' conversion for non-overlapping types"), + Add_unknown_to_all_conversions_of_non_overlapping_types: diag(95070, ts.DiagnosticCategory.Message, "Add_unknown_to_all_conversions_of_non_overlapping_types_95070", "Add 'unknown' to all conversions of non-overlapping types"), + Add_missing_new_operator_to_call: diag(95071, ts.DiagnosticCategory.Message, "Add_missing_new_operator_to_call_95071", "Add missing 'new' operator to call"), + Add_missing_new_operator_to_all_calls: diag(95072, ts.DiagnosticCategory.Message, "Add_missing_new_operator_to_all_calls_95072", "Add missing 'new' operator to all calls"), + Add_names_to_all_parameters_without_names: diag(95073, ts.DiagnosticCategory.Message, "Add_names_to_all_parameters_without_names_95073", "Add names to all parameters without names"), + }; +})(ts || (ts = {})); +var ts; +(function (ts) { + var _a; + /* @internal */ + function tokenIsIdentifierOrKeyword(token) { + return token >= 72 /* Identifier */; + } + ts.tokenIsIdentifierOrKeyword = tokenIsIdentifierOrKeyword; + /* @internal */ + function tokenIsIdentifierOrKeywordOrGreaterThan(token) { + return token === 30 /* GreaterThanToken */ || tokenIsIdentifierOrKeyword(token); + } + ts.tokenIsIdentifierOrKeywordOrGreaterThan = tokenIsIdentifierOrKeywordOrGreaterThan; + var textToKeywordObj = (_a = { + abstract: 118 /* AbstractKeyword */, + any: 120 /* AnyKeyword */, + as: 119 /* AsKeyword */, + bigint: 146 /* BigIntKeyword */, + boolean: 123 /* BooleanKeyword */, + break: 73 /* BreakKeyword */, + case: 74 /* CaseKeyword */, + catch: 75 /* CatchKeyword */, + class: 76 /* ClassKeyword */, + continue: 78 /* ContinueKeyword */, + const: 77 /* ConstKeyword */ + }, + _a["" + "constructor"] = 124 /* ConstructorKeyword */, + _a.debugger = 79 /* DebuggerKeyword */, + _a.declare = 125 /* DeclareKeyword */, + _a.default = 80 /* DefaultKeyword */, + _a.delete = 81 /* DeleteKeyword */, + _a.do = 82 /* DoKeyword */, + _a.else = 83 /* ElseKeyword */, + _a.enum = 84 /* EnumKeyword */, + _a.export = 85 /* ExportKeyword */, + _a.extends = 86 /* ExtendsKeyword */, + _a.false = 87 /* FalseKeyword */, + _a.finally = 88 /* FinallyKeyword */, + _a.for = 89 /* ForKeyword */, + _a.from = 144 /* FromKeyword */, + _a.function = 90 /* FunctionKeyword */, + _a.get = 126 /* GetKeyword */, + _a.if = 91 /* IfKeyword */, + _a.implements = 109 /* ImplementsKeyword */, + _a.import = 92 /* ImportKeyword */, + _a.in = 93 /* InKeyword */, + _a.infer = 127 /* InferKeyword */, + _a.instanceof = 94 /* InstanceOfKeyword */, + _a.interface = 110 /* InterfaceKeyword */, + _a.is = 128 /* IsKeyword */, + _a.keyof = 129 /* KeyOfKeyword */, + _a.let = 111 /* LetKeyword */, + _a.module = 130 /* ModuleKeyword */, + _a.namespace = 131 /* NamespaceKeyword */, + _a.never = 132 /* NeverKeyword */, + _a.new = 95 /* NewKeyword */, + _a.null = 96 /* NullKeyword */, + _a.number = 135 /* NumberKeyword */, + _a.object = 136 /* ObjectKeyword */, + _a.package = 112 /* PackageKeyword */, + _a.private = 113 /* PrivateKeyword */, + _a.protected = 114 /* ProtectedKeyword */, + _a.public = 115 /* PublicKeyword */, + _a.readonly = 133 /* ReadonlyKeyword */, + _a.require = 134 /* RequireKeyword */, + _a.global = 145 /* GlobalKeyword */, + _a.return = 97 /* ReturnKeyword */, + _a.set = 137 /* SetKeyword */, + _a.static = 116 /* StaticKeyword */, + _a.string = 138 /* StringKeyword */, + _a.super = 98 /* SuperKeyword */, + _a.switch = 99 /* SwitchKeyword */, + _a.symbol = 139 /* SymbolKeyword */, + _a.this = 100 /* ThisKeyword */, + _a.throw = 101 /* ThrowKeyword */, + _a.true = 102 /* TrueKeyword */, + _a.try = 103 /* TryKeyword */, + _a.type = 140 /* TypeKeyword */, + _a.typeof = 104 /* TypeOfKeyword */, + _a.undefined = 141 /* UndefinedKeyword */, + _a.unique = 142 /* UniqueKeyword */, + _a.unknown = 143 /* UnknownKeyword */, + _a.var = 105 /* VarKeyword */, + _a.void = 106 /* VoidKeyword */, + _a.while = 107 /* WhileKeyword */, + _a.with = 108 /* WithKeyword */, + _a.yield = 117 /* YieldKeyword */, + _a.async = 121 /* AsyncKeyword */, + _a.await = 122 /* AwaitKeyword */, + _a.of = 147 /* OfKeyword */, + _a); + var textToKeyword = ts.createMapFromTemplate(textToKeywordObj); + var textToToken = ts.createMapFromTemplate(__assign({}, textToKeywordObj, { "{": 18 /* OpenBraceToken */, "}": 19 /* CloseBraceToken */, "(": 20 /* OpenParenToken */, ")": 21 /* CloseParenToken */, "[": 22 /* OpenBracketToken */, "]": 23 /* CloseBracketToken */, ".": 24 /* DotToken */, "...": 25 /* DotDotDotToken */, ";": 26 /* SemicolonToken */, ",": 27 /* CommaToken */, "<": 28 /* LessThanToken */, ">": 30 /* GreaterThanToken */, "<=": 31 /* LessThanEqualsToken */, ">=": 32 /* GreaterThanEqualsToken */, "==": 33 /* EqualsEqualsToken */, "!=": 34 /* ExclamationEqualsToken */, "===": 35 /* EqualsEqualsEqualsToken */, "!==": 36 /* ExclamationEqualsEqualsToken */, "=>": 37 /* EqualsGreaterThanToken */, "+": 38 /* PlusToken */, "-": 39 /* MinusToken */, "**": 41 /* AsteriskAsteriskToken */, "*": 40 /* AsteriskToken */, "/": 42 /* SlashToken */, "%": 43 /* PercentToken */, "++": 44 /* PlusPlusToken */, "--": 45 /* MinusMinusToken */, "<<": 46 /* LessThanLessThanToken */, ">": 47 /* GreaterThanGreaterThanToken */, ">>>": 48 /* GreaterThanGreaterThanGreaterThanToken */, "&": 49 /* AmpersandToken */, "|": 50 /* BarToken */, "^": 51 /* CaretToken */, "!": 52 /* ExclamationToken */, "~": 53 /* TildeToken */, "&&": 54 /* AmpersandAmpersandToken */, "||": 55 /* BarBarToken */, "?": 56 /* QuestionToken */, ":": 57 /* ColonToken */, "=": 59 /* EqualsToken */, "+=": 60 /* PlusEqualsToken */, "-=": 61 /* MinusEqualsToken */, "*=": 62 /* AsteriskEqualsToken */, "**=": 63 /* AsteriskAsteriskEqualsToken */, "/=": 64 /* SlashEqualsToken */, "%=": 65 /* PercentEqualsToken */, "<<=": 66 /* LessThanLessThanEqualsToken */, ">>=": 67 /* GreaterThanGreaterThanEqualsToken */, ">>>=": 68 /* GreaterThanGreaterThanGreaterThanEqualsToken */, "&=": 69 /* AmpersandEqualsToken */, "|=": 70 /* BarEqualsToken */, "^=": 71 /* CaretEqualsToken */, "@": 58 /* AtToken */ })); + /* + As per ECMAScript Language Specification 3th Edition, Section 7.6: Identifiers + IdentifierStart :: + Can contain Unicode 3.0.0 categories: + Uppercase letter (Lu), + Lowercase letter (Ll), + Titlecase letter (Lt), + Modifier letter (Lm), + Other letter (Lo), or + Letter number (Nl). + IdentifierPart :: = + Can contain IdentifierStart + Unicode 3.0.0 categories: + Non-spacing mark (Mn), + Combining spacing mark (Mc), + Decimal number (Nd), or + Connector punctuation (Pc). + + Codepoint ranges for ES3 Identifiers are extracted from the Unicode 3.0.0 specification at: + http://www.unicode.org/Public/3.0-Update/UnicodeData-3.0.0.txt + */ + var unicodeES3IdentifierStart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 543, 546, 563, 592, 685, 688, 696, 699, 705, 720, 721, 736, 740, 750, 750, 890, 890, 902, 902, 904, 906, 908, 908, 910, 929, 931, 974, 976, 983, 986, 1011, 1024, 1153, 1164, 1220, 1223, 1224, 1227, 1228, 1232, 1269, 1272, 1273, 1329, 1366, 1369, 1369, 1377, 1415, 1488, 1514, 1520, 1522, 1569, 1594, 1600, 1610, 1649, 1747, 1749, 1749, 1765, 1766, 1786, 1788, 1808, 1808, 1810, 1836, 1920, 1957, 2309, 2361, 2365, 2365, 2384, 2384, 2392, 2401, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2524, 2525, 2527, 2529, 2544, 2545, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2649, 2652, 2654, 2654, 2674, 2676, 2693, 2699, 2701, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2749, 2749, 2768, 2768, 2784, 2784, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2870, 2873, 2877, 2877, 2908, 2909, 2911, 2913, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 2997, 2999, 3001, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3168, 3169, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3294, 3294, 3296, 3297, 3333, 3340, 3342, 3344, 3346, 3368, 3370, 3385, 3424, 3425, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3585, 3632, 3634, 3635, 3648, 3654, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3760, 3762, 3763, 3773, 3773, 3776, 3780, 3782, 3782, 3804, 3805, 3840, 3840, 3904, 3911, 3913, 3946, 3976, 3979, 4096, 4129, 4131, 4135, 4137, 4138, 4176, 4181, 4256, 4293, 4304, 4342, 4352, 4441, 4447, 4514, 4520, 4601, 4608, 4614, 4616, 4678, 4680, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4742, 4744, 4744, 4746, 4749, 4752, 4782, 4784, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4814, 4816, 4822, 4824, 4846, 4848, 4878, 4880, 4880, 4882, 4885, 4888, 4894, 4896, 4934, 4936, 4954, 5024, 5108, 5121, 5740, 5743, 5750, 5761, 5786, 5792, 5866, 6016, 6067, 6176, 6263, 6272, 6312, 7680, 7835, 7840, 7929, 7936, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8319, 8319, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8497, 8499, 8505, 8544, 8579, 12293, 12295, 12321, 12329, 12337, 12341, 12344, 12346, 12353, 12436, 12445, 12446, 12449, 12538, 12540, 12542, 12549, 12588, 12593, 12686, 12704, 12727, 13312, 19893, 19968, 40869, 40960, 42124, 44032, 55203, 63744, 64045, 64256, 64262, 64275, 64279, 64285, 64285, 64287, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65136, 65138, 65140, 65140, 65142, 65276, 65313, 65338, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500,]; + var unicodeES3IdentifierPart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 543, 546, 563, 592, 685, 688, 696, 699, 705, 720, 721, 736, 740, 750, 750, 768, 846, 864, 866, 890, 890, 902, 902, 904, 906, 908, 908, 910, 929, 931, 974, 976, 983, 986, 1011, 1024, 1153, 1155, 1158, 1164, 1220, 1223, 1224, 1227, 1228, 1232, 1269, 1272, 1273, 1329, 1366, 1369, 1369, 1377, 1415, 1425, 1441, 1443, 1465, 1467, 1469, 1471, 1471, 1473, 1474, 1476, 1476, 1488, 1514, 1520, 1522, 1569, 1594, 1600, 1621, 1632, 1641, 1648, 1747, 1749, 1756, 1759, 1768, 1770, 1773, 1776, 1788, 1808, 1836, 1840, 1866, 1920, 1968, 2305, 2307, 2309, 2361, 2364, 2381, 2384, 2388, 2392, 2403, 2406, 2415, 2433, 2435, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2492, 2492, 2494, 2500, 2503, 2504, 2507, 2509, 2519, 2519, 2524, 2525, 2527, 2531, 2534, 2545, 2562, 2562, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2620, 2620, 2622, 2626, 2631, 2632, 2635, 2637, 2649, 2652, 2654, 2654, 2662, 2676, 2689, 2691, 2693, 2699, 2701, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2748, 2757, 2759, 2761, 2763, 2765, 2768, 2768, 2784, 2784, 2790, 2799, 2817, 2819, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2870, 2873, 2876, 2883, 2887, 2888, 2891, 2893, 2902, 2903, 2908, 2909, 2911, 2913, 2918, 2927, 2946, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 2997, 2999, 3001, 3006, 3010, 3014, 3016, 3018, 3021, 3031, 3031, 3047, 3055, 3073, 3075, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3134, 3140, 3142, 3144, 3146, 3149, 3157, 3158, 3168, 3169, 3174, 3183, 3202, 3203, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3262, 3268, 3270, 3272, 3274, 3277, 3285, 3286, 3294, 3294, 3296, 3297, 3302, 3311, 3330, 3331, 3333, 3340, 3342, 3344, 3346, 3368, 3370, 3385, 3390, 3395, 3398, 3400, 3402, 3405, 3415, 3415, 3424, 3425, 3430, 3439, 3458, 3459, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3530, 3530, 3535, 3540, 3542, 3542, 3544, 3551, 3570, 3571, 3585, 3642, 3648, 3662, 3664, 3673, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3769, 3771, 3773, 3776, 3780, 3782, 3782, 3784, 3789, 3792, 3801, 3804, 3805, 3840, 3840, 3864, 3865, 3872, 3881, 3893, 3893, 3895, 3895, 3897, 3897, 3902, 3911, 3913, 3946, 3953, 3972, 3974, 3979, 3984, 3991, 3993, 4028, 4038, 4038, 4096, 4129, 4131, 4135, 4137, 4138, 4140, 4146, 4150, 4153, 4160, 4169, 4176, 4185, 4256, 4293, 4304, 4342, 4352, 4441, 4447, 4514, 4520, 4601, 4608, 4614, 4616, 4678, 4680, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4742, 4744, 4744, 4746, 4749, 4752, 4782, 4784, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4814, 4816, 4822, 4824, 4846, 4848, 4878, 4880, 4880, 4882, 4885, 4888, 4894, 4896, 4934, 4936, 4954, 4969, 4977, 5024, 5108, 5121, 5740, 5743, 5750, 5761, 5786, 5792, 5866, 6016, 6099, 6112, 6121, 6160, 6169, 6176, 6263, 6272, 6313, 7680, 7835, 7840, 7929, 7936, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8255, 8256, 8319, 8319, 8400, 8412, 8417, 8417, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8497, 8499, 8505, 8544, 8579, 12293, 12295, 12321, 12335, 12337, 12341, 12344, 12346, 12353, 12436, 12441, 12442, 12445, 12446, 12449, 12542, 12549, 12588, 12593, 12686, 12704, 12727, 13312, 19893, 19968, 40869, 40960, 42124, 44032, 55203, 63744, 64045, 64256, 64262, 64275, 64279, 64285, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65056, 65059, 65075, 65076, 65101, 65103, 65136, 65138, 65140, 65140, 65142, 65276, 65296, 65305, 65313, 65338, 65343, 65343, 65345, 65370, 65381, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500,]; + /* + As per ECMAScript Language Specification 5th Edition, Section 7.6: ISyntaxToken Names and Identifiers + IdentifierStart :: + Can contain Unicode 6.2 categories: + Uppercase letter (Lu), + Lowercase letter (Ll), + Titlecase letter (Lt), + Modifier letter (Lm), + Other letter (Lo), or + Letter number (Nl). + IdentifierPart :: + Can contain IdentifierStart + Unicode 6.2 categories: + Non-spacing mark (Mn), + Combining spacing mark (Mc), + Decimal number (Nd), + Connector punctuation (Pc), + , or + . + + Codepoint ranges for ES5 Identifiers are extracted from the Unicode 6.2 specification at: + http://www.unicode.org/Public/6.2.0/ucd/UnicodeData.txt + */ + var unicodeES5IdentifierStart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 705, 710, 721, 736, 740, 748, 748, 750, 750, 880, 884, 886, 887, 890, 893, 902, 902, 904, 906, 908, 908, 910, 929, 931, 1013, 1015, 1153, 1162, 1319, 1329, 1366, 1369, 1369, 1377, 1415, 1488, 1514, 1520, 1522, 1568, 1610, 1646, 1647, 1649, 1747, 1749, 1749, 1765, 1766, 1774, 1775, 1786, 1788, 1791, 1791, 1808, 1808, 1810, 1839, 1869, 1957, 1969, 1969, 1994, 2026, 2036, 2037, 2042, 2042, 2048, 2069, 2074, 2074, 2084, 2084, 2088, 2088, 2112, 2136, 2208, 2208, 2210, 2220, 2308, 2361, 2365, 2365, 2384, 2384, 2392, 2401, 2417, 2423, 2425, 2431, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2493, 2493, 2510, 2510, 2524, 2525, 2527, 2529, 2544, 2545, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2649, 2652, 2654, 2654, 2674, 2676, 2693, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2749, 2749, 2768, 2768, 2784, 2785, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2869, 2873, 2877, 2877, 2908, 2909, 2911, 2913, 2929, 2929, 2947, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 3001, 3024, 3024, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3133, 3133, 3160, 3161, 3168, 3169, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3261, 3261, 3294, 3294, 3296, 3297, 3313, 3314, 3333, 3340, 3342, 3344, 3346, 3386, 3389, 3389, 3406, 3406, 3424, 3425, 3450, 3455, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3585, 3632, 3634, 3635, 3648, 3654, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3760, 3762, 3763, 3773, 3773, 3776, 3780, 3782, 3782, 3804, 3807, 3840, 3840, 3904, 3911, 3913, 3948, 3976, 3980, 4096, 4138, 4159, 4159, 4176, 4181, 4186, 4189, 4193, 4193, 4197, 4198, 4206, 4208, 4213, 4225, 4238, 4238, 4256, 4293, 4295, 4295, 4301, 4301, 4304, 4346, 4348, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4744, 4746, 4749, 4752, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4822, 4824, 4880, 4882, 4885, 4888, 4954, 4992, 5007, 5024, 5108, 5121, 5740, 5743, 5759, 5761, 5786, 5792, 5866, 5870, 5872, 5888, 5900, 5902, 5905, 5920, 5937, 5952, 5969, 5984, 5996, 5998, 6000, 6016, 6067, 6103, 6103, 6108, 6108, 6176, 6263, 6272, 6312, 6314, 6314, 6320, 6389, 6400, 6428, 6480, 6509, 6512, 6516, 6528, 6571, 6593, 6599, 6656, 6678, 6688, 6740, 6823, 6823, 6917, 6963, 6981, 6987, 7043, 7072, 7086, 7087, 7098, 7141, 7168, 7203, 7245, 7247, 7258, 7293, 7401, 7404, 7406, 7409, 7413, 7414, 7424, 7615, 7680, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8305, 8305, 8319, 8319, 8336, 8348, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8505, 8508, 8511, 8517, 8521, 8526, 8526, 8544, 8584, 11264, 11310, 11312, 11358, 11360, 11492, 11499, 11502, 11506, 11507, 11520, 11557, 11559, 11559, 11565, 11565, 11568, 11623, 11631, 11631, 11648, 11670, 11680, 11686, 11688, 11694, 11696, 11702, 11704, 11710, 11712, 11718, 11720, 11726, 11728, 11734, 11736, 11742, 11823, 11823, 12293, 12295, 12321, 12329, 12337, 12341, 12344, 12348, 12353, 12438, 12445, 12447, 12449, 12538, 12540, 12543, 12549, 12589, 12593, 12686, 12704, 12730, 12784, 12799, 13312, 19893, 19968, 40908, 40960, 42124, 42192, 42237, 42240, 42508, 42512, 42527, 42538, 42539, 42560, 42606, 42623, 42647, 42656, 42735, 42775, 42783, 42786, 42888, 42891, 42894, 42896, 42899, 42912, 42922, 43000, 43009, 43011, 43013, 43015, 43018, 43020, 43042, 43072, 43123, 43138, 43187, 43250, 43255, 43259, 43259, 43274, 43301, 43312, 43334, 43360, 43388, 43396, 43442, 43471, 43471, 43520, 43560, 43584, 43586, 43588, 43595, 43616, 43638, 43642, 43642, 43648, 43695, 43697, 43697, 43701, 43702, 43705, 43709, 43712, 43712, 43714, 43714, 43739, 43741, 43744, 43754, 43762, 43764, 43777, 43782, 43785, 43790, 43793, 43798, 43808, 43814, 43816, 43822, 43968, 44002, 44032, 55203, 55216, 55238, 55243, 55291, 63744, 64109, 64112, 64217, 64256, 64262, 64275, 64279, 64285, 64285, 64287, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65136, 65140, 65142, 65276, 65313, 65338, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500,]; + var unicodeES5IdentifierPart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 705, 710, 721, 736, 740, 748, 748, 750, 750, 768, 884, 886, 887, 890, 893, 902, 902, 904, 906, 908, 908, 910, 929, 931, 1013, 1015, 1153, 1155, 1159, 1162, 1319, 1329, 1366, 1369, 1369, 1377, 1415, 1425, 1469, 1471, 1471, 1473, 1474, 1476, 1477, 1479, 1479, 1488, 1514, 1520, 1522, 1552, 1562, 1568, 1641, 1646, 1747, 1749, 1756, 1759, 1768, 1770, 1788, 1791, 1791, 1808, 1866, 1869, 1969, 1984, 2037, 2042, 2042, 2048, 2093, 2112, 2139, 2208, 2208, 2210, 2220, 2276, 2302, 2304, 2403, 2406, 2415, 2417, 2423, 2425, 2431, 2433, 2435, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2492, 2500, 2503, 2504, 2507, 2510, 2519, 2519, 2524, 2525, 2527, 2531, 2534, 2545, 2561, 2563, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2620, 2620, 2622, 2626, 2631, 2632, 2635, 2637, 2641, 2641, 2649, 2652, 2654, 2654, 2662, 2677, 2689, 2691, 2693, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2748, 2757, 2759, 2761, 2763, 2765, 2768, 2768, 2784, 2787, 2790, 2799, 2817, 2819, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2869, 2873, 2876, 2884, 2887, 2888, 2891, 2893, 2902, 2903, 2908, 2909, 2911, 2915, 2918, 2927, 2929, 2929, 2946, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 3001, 3006, 3010, 3014, 3016, 3018, 3021, 3024, 3024, 3031, 3031, 3046, 3055, 3073, 3075, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3133, 3140, 3142, 3144, 3146, 3149, 3157, 3158, 3160, 3161, 3168, 3171, 3174, 3183, 3202, 3203, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3260, 3268, 3270, 3272, 3274, 3277, 3285, 3286, 3294, 3294, 3296, 3299, 3302, 3311, 3313, 3314, 3330, 3331, 3333, 3340, 3342, 3344, 3346, 3386, 3389, 3396, 3398, 3400, 3402, 3406, 3415, 3415, 3424, 3427, 3430, 3439, 3450, 3455, 3458, 3459, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3530, 3530, 3535, 3540, 3542, 3542, 3544, 3551, 3570, 3571, 3585, 3642, 3648, 3662, 3664, 3673, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3769, 3771, 3773, 3776, 3780, 3782, 3782, 3784, 3789, 3792, 3801, 3804, 3807, 3840, 3840, 3864, 3865, 3872, 3881, 3893, 3893, 3895, 3895, 3897, 3897, 3902, 3911, 3913, 3948, 3953, 3972, 3974, 3991, 3993, 4028, 4038, 4038, 4096, 4169, 4176, 4253, 4256, 4293, 4295, 4295, 4301, 4301, 4304, 4346, 4348, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4744, 4746, 4749, 4752, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4822, 4824, 4880, 4882, 4885, 4888, 4954, 4957, 4959, 4992, 5007, 5024, 5108, 5121, 5740, 5743, 5759, 5761, 5786, 5792, 5866, 5870, 5872, 5888, 5900, 5902, 5908, 5920, 5940, 5952, 5971, 5984, 5996, 5998, 6000, 6002, 6003, 6016, 6099, 6103, 6103, 6108, 6109, 6112, 6121, 6155, 6157, 6160, 6169, 6176, 6263, 6272, 6314, 6320, 6389, 6400, 6428, 6432, 6443, 6448, 6459, 6470, 6509, 6512, 6516, 6528, 6571, 6576, 6601, 6608, 6617, 6656, 6683, 6688, 6750, 6752, 6780, 6783, 6793, 6800, 6809, 6823, 6823, 6912, 6987, 6992, 7001, 7019, 7027, 7040, 7155, 7168, 7223, 7232, 7241, 7245, 7293, 7376, 7378, 7380, 7414, 7424, 7654, 7676, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8204, 8205, 8255, 8256, 8276, 8276, 8305, 8305, 8319, 8319, 8336, 8348, 8400, 8412, 8417, 8417, 8421, 8432, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8505, 8508, 8511, 8517, 8521, 8526, 8526, 8544, 8584, 11264, 11310, 11312, 11358, 11360, 11492, 11499, 11507, 11520, 11557, 11559, 11559, 11565, 11565, 11568, 11623, 11631, 11631, 11647, 11670, 11680, 11686, 11688, 11694, 11696, 11702, 11704, 11710, 11712, 11718, 11720, 11726, 11728, 11734, 11736, 11742, 11744, 11775, 11823, 11823, 12293, 12295, 12321, 12335, 12337, 12341, 12344, 12348, 12353, 12438, 12441, 12442, 12445, 12447, 12449, 12538, 12540, 12543, 12549, 12589, 12593, 12686, 12704, 12730, 12784, 12799, 13312, 19893, 19968, 40908, 40960, 42124, 42192, 42237, 42240, 42508, 42512, 42539, 42560, 42607, 42612, 42621, 42623, 42647, 42655, 42737, 42775, 42783, 42786, 42888, 42891, 42894, 42896, 42899, 42912, 42922, 43000, 43047, 43072, 43123, 43136, 43204, 43216, 43225, 43232, 43255, 43259, 43259, 43264, 43309, 43312, 43347, 43360, 43388, 43392, 43456, 43471, 43481, 43520, 43574, 43584, 43597, 43600, 43609, 43616, 43638, 43642, 43643, 43648, 43714, 43739, 43741, 43744, 43759, 43762, 43766, 43777, 43782, 43785, 43790, 43793, 43798, 43808, 43814, 43816, 43822, 43968, 44010, 44012, 44013, 44016, 44025, 44032, 55203, 55216, 55238, 55243, 55291, 63744, 64109, 64112, 64217, 64256, 64262, 64275, 64279, 64285, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65024, 65039, 65056, 65062, 65075, 65076, 65101, 65103, 65136, 65140, 65142, 65276, 65296, 65305, 65313, 65338, 65343, 65343, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500,]; + function lookupInUnicodeMap(code, map) { + // Bail out quickly if it couldn't possibly be in the map. + if (code < map[0]) { + return false; + } + // Perform binary search in one of the Unicode range maps + var lo = 0; + var hi = map.length; + var mid; + while (lo + 1 < hi) { + mid = lo + (hi - lo) / 2; + // mid has to be even to catch a range's beginning + mid -= mid % 2; + if (map[mid] <= code && code <= map[mid + 1]) { + return true; + } + if (code < map[mid]) { + hi = mid; + } + else { + lo = mid + 2; + } + } + return false; + } + /* @internal */ function isUnicodeIdentifierStart(code, languageVersion) { + return languageVersion >= 1 /* ES5 */ ? + lookupInUnicodeMap(code, unicodeES5IdentifierStart) : + lookupInUnicodeMap(code, unicodeES3IdentifierStart); + } + ts.isUnicodeIdentifierStart = isUnicodeIdentifierStart; + function isUnicodeIdentifierPart(code, languageVersion) { + return languageVersion >= 1 /* ES5 */ ? + lookupInUnicodeMap(code, unicodeES5IdentifierPart) : + lookupInUnicodeMap(code, unicodeES3IdentifierPart); + } + function makeReverseMap(source) { + var result = []; + source.forEach(function (value, name) { + result[value] = name; + }); + return result; + } + var tokenStrings = makeReverseMap(textToToken); + function tokenToString(t) { + return tokenStrings[t]; + } + ts.tokenToString = tokenToString; + /* @internal */ + function stringToToken(s) { + return textToToken.get(s); + } + ts.stringToToken = stringToToken; + /* @internal */ + function computeLineStarts(text) { + var result = new Array(); + var pos = 0; + var lineStart = 0; + while (pos < text.length) { + var ch = text.charCodeAt(pos); + pos++; + switch (ch) { + case 13 /* carriageReturn */: + if (text.charCodeAt(pos) === 10 /* lineFeed */) { + pos++; + } + // falls through + case 10 /* lineFeed */: + result.push(lineStart); + lineStart = pos; + break; + default: + if (ch > 127 /* maxAsciiCharacter */ && isLineBreak(ch)) { + result.push(lineStart); + lineStart = pos; + } + break; + } + } + result.push(lineStart); + return result; + } + ts.computeLineStarts = computeLineStarts; + function getPositionOfLineAndCharacter(sourceFile, line, character) { + return computePositionOfLineAndCharacter(getLineStarts(sourceFile), line, character, sourceFile.text); + } + ts.getPositionOfLineAndCharacter = getPositionOfLineAndCharacter; + /* @internal */ + function getPositionOfLineAndCharacterWithEdits(sourceFile, line, character) { + return computePositionOfLineAndCharacter(getLineStarts(sourceFile), line, character, sourceFile.text, /*allowEdits*/ true); + } + ts.getPositionOfLineAndCharacterWithEdits = getPositionOfLineAndCharacterWithEdits; + /* @internal */ + function computePositionOfLineAndCharacter(lineStarts, line, character, debugText, allowEdits) { + if (line < 0 || line >= lineStarts.length) { + if (allowEdits) { + // Clamp line to nearest allowable value + line = line < 0 ? 0 : line >= lineStarts.length ? lineStarts.length - 1 : line; + } + else { + ts.Debug.fail("Bad line number. Line: " + line + ", lineStarts.length: " + lineStarts.length + " , line map is correct? " + (debugText !== undefined ? ts.arraysEqual(lineStarts, computeLineStarts(debugText)) : "unknown")); + } + } + var res = lineStarts[line] + character; + if (allowEdits) { + // Clamp to nearest allowable values to allow the underlying to be edited without crashing (accuracy is lost, instead) + // TODO: Somehow track edits between file as it was during the creation of sourcemap we have and the current file and + // apply them to the computed position to improve accuracy + return res > lineStarts[line + 1] ? lineStarts[line + 1] : typeof debugText === "string" && res > debugText.length ? debugText.length : res; + } + if (line < lineStarts.length - 1) { + ts.Debug.assert(res < lineStarts[line + 1]); + } + else if (debugText !== undefined) { + ts.Debug.assert(res <= debugText.length); // Allow single character overflow for trailing newline + } + return res; + } + ts.computePositionOfLineAndCharacter = computePositionOfLineAndCharacter; + /* @internal */ + function getLineStarts(sourceFile) { + return sourceFile.lineMap || (sourceFile.lineMap = computeLineStarts(sourceFile.text)); + } + ts.getLineStarts = getLineStarts; + /* @internal */ + /** + * We assume the first line starts at position 0 and 'position' is non-negative. + */ + function computeLineAndCharacterOfPosition(lineStarts, position) { + var lineNumber = ts.binarySearch(lineStarts, position, ts.identity, ts.compareValues); + if (lineNumber < 0) { + // If the actual position was not found, + // the binary search returns the 2's-complement of the next line start + // e.g. if the line starts at [5, 10, 23, 80] and the position requested was 20 + // then the search will return -2. + // + // We want the index of the previous line start, so we subtract 1. + // Review 2's-complement if this is confusing. + lineNumber = ~lineNumber - 1; + ts.Debug.assert(lineNumber !== -1, "position cannot precede the beginning of the file"); + } + return { + line: lineNumber, + character: position - lineStarts[lineNumber] + }; + } + ts.computeLineAndCharacterOfPosition = computeLineAndCharacterOfPosition; + function getLineAndCharacterOfPosition(sourceFile, position) { + return computeLineAndCharacterOfPosition(getLineStarts(sourceFile), position); + } + ts.getLineAndCharacterOfPosition = getLineAndCharacterOfPosition; + function isWhiteSpaceLike(ch) { + return isWhiteSpaceSingleLine(ch) || isLineBreak(ch); + } + ts.isWhiteSpaceLike = isWhiteSpaceLike; + /** Does not include line breaks. For that, see isWhiteSpaceLike. */ + function isWhiteSpaceSingleLine(ch) { + // Note: nextLine is in the Zs space, and should be considered to be a whitespace. + // It is explicitly not a line-break as it isn't in the exact set specified by EcmaScript. + return ch === 32 /* space */ || + ch === 9 /* tab */ || + ch === 11 /* verticalTab */ || + ch === 12 /* formFeed */ || + ch === 160 /* nonBreakingSpace */ || + ch === 133 /* nextLine */ || + ch === 5760 /* ogham */ || + ch >= 8192 /* enQuad */ && ch <= 8203 /* zeroWidthSpace */ || + ch === 8239 /* narrowNoBreakSpace */ || + ch === 8287 /* mathematicalSpace */ || + ch === 12288 /* ideographicSpace */ || + ch === 65279 /* byteOrderMark */; + } + ts.isWhiteSpaceSingleLine = isWhiteSpaceSingleLine; + function isLineBreak(ch) { + // ES5 7.3: + // The ECMAScript line terminator characters are listed in Table 3. + // Table 3: Line Terminator Characters + // Code Unit Value Name Formal Name + // \u000A Line Feed + // \u000D Carriage Return + // \u2028 Line separator + // \u2029 Paragraph separator + // Only the characters in Table 3 are treated as line terminators. Other new line or line + // breaking characters are treated as white space but not as line terminators. + return ch === 10 /* lineFeed */ || + ch === 13 /* carriageReturn */ || + ch === 8232 /* lineSeparator */ || + ch === 8233 /* paragraphSeparator */; + } + ts.isLineBreak = isLineBreak; + function isDigit(ch) { + return ch >= 48 /* _0 */ && ch <= 57 /* _9 */; + } + /* @internal */ + function isOctalDigit(ch) { + return ch >= 48 /* _0 */ && ch <= 55 /* _7 */; + } + ts.isOctalDigit = isOctalDigit; + function couldStartTrivia(text, pos) { + // Keep in sync with skipTrivia + var ch = text.charCodeAt(pos); + switch (ch) { + case 13 /* carriageReturn */: + case 10 /* lineFeed */: + case 9 /* tab */: + case 11 /* verticalTab */: + case 12 /* formFeed */: + case 32 /* space */: + case 47 /* slash */: + // starts of normal trivia + case 60 /* lessThan */: + case 124 /* bar */: + case 61 /* equals */: + case 62 /* greaterThan */: + // Starts of conflict marker trivia + return true; + case 35 /* hash */: + // Only if its the beginning can we have #! trivia + return pos === 0; + default: + return ch > 127 /* maxAsciiCharacter */; + } + } + ts.couldStartTrivia = couldStartTrivia; + /* @internal */ + function skipTrivia(text, pos, stopAfterLineBreak, stopAtComments) { + if (stopAtComments === void 0) { stopAtComments = false; } + if (ts.positionIsSynthesized(pos)) { + return pos; + } + // Keep in sync with couldStartTrivia + while (true) { + var ch = text.charCodeAt(pos); + switch (ch) { + case 13 /* carriageReturn */: + if (text.charCodeAt(pos + 1) === 10 /* lineFeed */) { + pos++; + } + // falls through + case 10 /* lineFeed */: + pos++; + if (stopAfterLineBreak) { + return pos; + } + continue; + case 9 /* tab */: + case 11 /* verticalTab */: + case 12 /* formFeed */: + case 32 /* space */: + pos++; + continue; + case 47 /* slash */: + if (stopAtComments) { + break; + } + if (text.charCodeAt(pos + 1) === 47 /* slash */) { + pos += 2; + while (pos < text.length) { + if (isLineBreak(text.charCodeAt(pos))) { + break; + } + pos++; + } + continue; + } + if (text.charCodeAt(pos + 1) === 42 /* asterisk */) { + pos += 2; + while (pos < text.length) { + if (text.charCodeAt(pos) === 42 /* asterisk */ && text.charCodeAt(pos + 1) === 47 /* slash */) { + pos += 2; + break; + } + pos++; + } + continue; + } + break; + case 60 /* lessThan */: + case 124 /* bar */: + case 61 /* equals */: + case 62 /* greaterThan */: + if (isConflictMarkerTrivia(text, pos)) { + pos = scanConflictMarkerTrivia(text, pos); + continue; + } + break; + case 35 /* hash */: + if (pos === 0 && isShebangTrivia(text, pos)) { + pos = scanShebangTrivia(text, pos); + continue; + } + break; + default: + if (ch > 127 /* maxAsciiCharacter */ && (isWhiteSpaceLike(ch))) { + pos++; + continue; + } + break; + } + return pos; + } + } + ts.skipTrivia = skipTrivia; + // All conflict markers consist of the same character repeated seven times. If it is + // a <<<<<<< or >>>>>>> marker then it is also followed by a space. + var mergeConflictMarkerLength = "<<<<<<<".length; + function isConflictMarkerTrivia(text, pos) { + ts.Debug.assert(pos >= 0); + // Conflict markers must be at the start of a line. + if (pos === 0 || isLineBreak(text.charCodeAt(pos - 1))) { + var ch = text.charCodeAt(pos); + if ((pos + mergeConflictMarkerLength) < text.length) { + for (var i = 0; i < mergeConflictMarkerLength; i++) { + if (text.charCodeAt(pos + i) !== ch) { + return false; + } + } + return ch === 61 /* equals */ || + text.charCodeAt(pos + mergeConflictMarkerLength) === 32 /* space */; + } + } + return false; + } + function scanConflictMarkerTrivia(text, pos, error) { + if (error) { + error(ts.Diagnostics.Merge_conflict_marker_encountered, pos, mergeConflictMarkerLength); + } + var ch = text.charCodeAt(pos); + var len = text.length; + if (ch === 60 /* lessThan */ || ch === 62 /* greaterThan */) { + while (pos < len && !isLineBreak(text.charCodeAt(pos))) { + pos++; + } + } + else { + ts.Debug.assert(ch === 124 /* bar */ || ch === 61 /* equals */); + // Consume everything from the start of a ||||||| or ======= marker to the start + // of the next ======= or >>>>>>> marker. + while (pos < len) { + var currentChar = text.charCodeAt(pos); + if ((currentChar === 61 /* equals */ || currentChar === 62 /* greaterThan */) && currentChar !== ch && isConflictMarkerTrivia(text, pos)) { + break; + } + pos++; + } + } + return pos; + } + var shebangTriviaRegex = /^#!.*/; + function isShebangTrivia(text, pos) { + // Shebangs check must only be done at the start of the file + ts.Debug.assert(pos === 0); + return shebangTriviaRegex.test(text); + } + function scanShebangTrivia(text, pos) { + var shebang = shebangTriviaRegex.exec(text)[0]; + pos = pos + shebang.length; + return pos; + } + /** + * Invokes a callback for each comment range following the provided position. + * + * Single-line comment ranges include the leading double-slash characters but not the ending + * line break. Multi-line comment ranges include the leading slash-asterisk and trailing + * asterisk-slash characters. + * + * @param reduce If true, accumulates the result of calling the callback in a fashion similar + * to reduceLeft. If false, iteration stops when the callback returns a truthy value. + * @param text The source text to scan. + * @param pos The position at which to start scanning. + * @param trailing If false, whitespace is skipped until the first line break and comments + * between that location and the next token are returned. If true, comments occurring + * between the given position and the next line break are returned. + * @param cb The callback to execute as each comment range is encountered. + * @param state A state value to pass to each iteration of the callback. + * @param initial An initial value to pass when accumulating results (when "reduce" is true). + * @returns If "reduce" is true, the accumulated value. If "reduce" is false, the first truthy + * return value of the callback. + */ + function iterateCommentRanges(reduce, text, pos, trailing, cb, state, initial) { + var pendingPos; + var pendingEnd; + var pendingKind; + var pendingHasTrailingNewLine; + var hasPendingCommentRange = false; + var collecting = trailing || pos === 0; + var accumulator = initial; + scan: while (pos >= 0 && pos < text.length) { + var ch = text.charCodeAt(pos); + switch (ch) { + case 13 /* carriageReturn */: + if (text.charCodeAt(pos + 1) === 10 /* lineFeed */) { + pos++; + } + // falls through + case 10 /* lineFeed */: + pos++; + if (trailing) { + break scan; + } + collecting = true; + if (hasPendingCommentRange) { + pendingHasTrailingNewLine = true; + } + continue; + case 9 /* tab */: + case 11 /* verticalTab */: + case 12 /* formFeed */: + case 32 /* space */: + pos++; + continue; + case 47 /* slash */: + var nextChar = text.charCodeAt(pos + 1); + var hasTrailingNewLine = false; + if (nextChar === 47 /* slash */ || nextChar === 42 /* asterisk */) { + var kind = nextChar === 47 /* slash */ ? 2 /* SingleLineCommentTrivia */ : 3 /* MultiLineCommentTrivia */; + var startPos = pos; + pos += 2; + if (nextChar === 47 /* slash */) { + while (pos < text.length) { + if (isLineBreak(text.charCodeAt(pos))) { + hasTrailingNewLine = true; + break; + } + pos++; + } + } + else { + while (pos < text.length) { + if (text.charCodeAt(pos) === 42 /* asterisk */ && text.charCodeAt(pos + 1) === 47 /* slash */) { + pos += 2; + break; + } + pos++; + } + } + if (collecting) { + if (hasPendingCommentRange) { + accumulator = cb(pendingPos, pendingEnd, pendingKind, pendingHasTrailingNewLine, state, accumulator); + if (!reduce && accumulator) { + // If we are not reducing and we have a truthy result, return it. + return accumulator; + } + } + pendingPos = startPos; + pendingEnd = pos; + pendingKind = kind; + pendingHasTrailingNewLine = hasTrailingNewLine; + hasPendingCommentRange = true; + } + continue; + } + break scan; + default: + if (ch > 127 /* maxAsciiCharacter */ && (isWhiteSpaceLike(ch))) { + if (hasPendingCommentRange && isLineBreak(ch)) { + pendingHasTrailingNewLine = true; + } + pos++; + continue; + } + break scan; + } + } + if (hasPendingCommentRange) { + accumulator = cb(pendingPos, pendingEnd, pendingKind, pendingHasTrailingNewLine, state, accumulator); + } + return accumulator; + } + function forEachLeadingCommentRange(text, pos, cb, state) { + return iterateCommentRanges(/*reduce*/ false, text, pos, /*trailing*/ false, cb, state); + } + ts.forEachLeadingCommentRange = forEachLeadingCommentRange; + function forEachTrailingCommentRange(text, pos, cb, state) { + return iterateCommentRanges(/*reduce*/ false, text, pos, /*trailing*/ true, cb, state); + } + ts.forEachTrailingCommentRange = forEachTrailingCommentRange; + function reduceEachLeadingCommentRange(text, pos, cb, state, initial) { + return iterateCommentRanges(/*reduce*/ true, text, pos, /*trailing*/ false, cb, state, initial); + } + ts.reduceEachLeadingCommentRange = reduceEachLeadingCommentRange; + function reduceEachTrailingCommentRange(text, pos, cb, state, initial) { + return iterateCommentRanges(/*reduce*/ true, text, pos, /*trailing*/ true, cb, state, initial); + } + ts.reduceEachTrailingCommentRange = reduceEachTrailingCommentRange; + function appendCommentRange(pos, end, kind, hasTrailingNewLine, _state, comments) { + if (!comments) { + comments = []; + } + comments.push({ kind: kind, pos: pos, end: end, hasTrailingNewLine: hasTrailingNewLine }); + return comments; + } + function getLeadingCommentRanges(text, pos) { + return reduceEachLeadingCommentRange(text, pos, appendCommentRange, /*state*/ undefined, /*initial*/ undefined); + } + ts.getLeadingCommentRanges = getLeadingCommentRanges; + function getTrailingCommentRanges(text, pos) { + return reduceEachTrailingCommentRange(text, pos, appendCommentRange, /*state*/ undefined, /*initial*/ undefined); + } + ts.getTrailingCommentRanges = getTrailingCommentRanges; + /** Optionally, get the shebang */ + function getShebang(text) { + var match = shebangTriviaRegex.exec(text); + if (match) { + return match[0]; + } + } + ts.getShebang = getShebang; + function isIdentifierStart(ch, languageVersion) { + return ch >= 65 /* A */ && ch <= 90 /* Z */ || ch >= 97 /* a */ && ch <= 122 /* z */ || + ch === 36 /* $ */ || ch === 95 /* _ */ || + ch > 127 /* maxAsciiCharacter */ && isUnicodeIdentifierStart(ch, languageVersion); + } + ts.isIdentifierStart = isIdentifierStart; + function isIdentifierPart(ch, languageVersion) { + return ch >= 65 /* A */ && ch <= 90 /* Z */ || ch >= 97 /* a */ && ch <= 122 /* z */ || + ch >= 48 /* _0 */ && ch <= 57 /* _9 */ || ch === 36 /* $ */ || ch === 95 /* _ */ || + ch > 127 /* maxAsciiCharacter */ && isUnicodeIdentifierPart(ch, languageVersion); + } + ts.isIdentifierPart = isIdentifierPart; + /* @internal */ + function isIdentifierText(name, languageVersion) { + if (!isIdentifierStart(name.charCodeAt(0), languageVersion)) { + return false; + } + for (var i = 1; i < name.length; i++) { + if (!isIdentifierPart(name.charCodeAt(i), languageVersion)) { + return false; + } + } + return true; + } + ts.isIdentifierText = isIdentifierText; + // Creates a scanner over a (possibly unspecified) range of a piece of text. + function createScanner(languageVersion, skipTrivia, languageVariant, textInitial, onError, start, length) { + if (languageVariant === void 0) { languageVariant = 0 /* Standard */; } + var text = textInitial; + // Current position (end position of text of current token) + var pos; + // end of text + var end; + // Start position of whitespace before current token + var startPos; + // Start position of text of current token + var tokenPos; + var token; + var tokenValue; + var tokenFlags; + var inJSDocType = 0; + setText(text, start, length); + return { + getStartPos: function () { return startPos; }, + getTextPos: function () { return pos; }, + getToken: function () { return token; }, + getTokenPos: function () { return tokenPos; }, + getTokenText: function () { return text.substring(tokenPos, pos); }, + getTokenValue: function () { return tokenValue; }, + hasExtendedUnicodeEscape: function () { return (tokenFlags & 8 /* ExtendedUnicodeEscape */) !== 0; }, + hasPrecedingLineBreak: function () { return (tokenFlags & 1 /* PrecedingLineBreak */) !== 0; }, + isIdentifier: function () { return token === 72 /* Identifier */ || token > 108 /* LastReservedWord */; }, + isReservedWord: function () { return token >= 73 /* FirstReservedWord */ && token <= 108 /* LastReservedWord */; }, + isUnterminated: function () { return (tokenFlags & 4 /* Unterminated */) !== 0; }, + getTokenFlags: function () { return tokenFlags; }, + reScanGreaterToken: reScanGreaterToken, + reScanSlashToken: reScanSlashToken, + reScanTemplateToken: reScanTemplateToken, + scanJsxIdentifier: scanJsxIdentifier, + scanJsxAttributeValue: scanJsxAttributeValue, + reScanJsxToken: reScanJsxToken, + scanJsxToken: scanJsxToken, + scanJSDocToken: scanJSDocToken, + scan: scan, + getText: getText, + setText: setText, + setScriptTarget: setScriptTarget, + setLanguageVariant: setLanguageVariant, + setOnError: setOnError, + setTextPos: setTextPos, + setInJSDocType: setInJSDocType, + tryScan: tryScan, + lookAhead: lookAhead, + scanRange: scanRange, + }; + function error(message, errPos, length) { + if (errPos === void 0) { errPos = pos; } + if (onError) { + var oldPos = pos; + pos = errPos; + onError(message, length || 0); + pos = oldPos; + } + } + function scanNumberFragment() { + var start = pos; + var allowSeparator = false; + var isPreviousTokenSeparator = false; + var result = ""; + while (true) { + var ch = text.charCodeAt(pos); + if (ch === 95 /* _ */) { + tokenFlags |= 512 /* ContainsSeparator */; + if (allowSeparator) { + allowSeparator = false; + isPreviousTokenSeparator = true; + result += text.substring(start, pos); + } + else if (isPreviousTokenSeparator) { + error(ts.Diagnostics.Multiple_consecutive_numeric_separators_are_not_permitted, pos, 1); + } + else { + error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos, 1); + } + pos++; + start = pos; + continue; + } + if (isDigit(ch)) { + allowSeparator = true; + isPreviousTokenSeparator = false; + pos++; + continue; + } + break; + } + if (text.charCodeAt(pos - 1) === 95 /* _ */) { + error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos - 1, 1); + } + return result + text.substring(start, pos); + } + function scanNumber() { + var start = pos; + var mainFragment = scanNumberFragment(); + var decimalFragment; + var scientificFragment; + if (text.charCodeAt(pos) === 46 /* dot */) { + pos++; + decimalFragment = scanNumberFragment(); + } + var end = pos; + if (text.charCodeAt(pos) === 69 /* E */ || text.charCodeAt(pos) === 101 /* e */) { + pos++; + tokenFlags |= 16 /* Scientific */; + if (text.charCodeAt(pos) === 43 /* plus */ || text.charCodeAt(pos) === 45 /* minus */) + pos++; + var preNumericPart = pos; + var finalFragment = scanNumberFragment(); + if (!finalFragment) { + error(ts.Diagnostics.Digit_expected); + } + else { + scientificFragment = text.substring(end, preNumericPart) + finalFragment; + end = pos; + } + } + var result; + if (tokenFlags & 512 /* ContainsSeparator */) { + result = mainFragment; + if (decimalFragment) { + result += "." + decimalFragment; + } + if (scientificFragment) { + result += scientificFragment; + } + } + else { + result = text.substring(start, end); // No need to use all the fragments; no _ removal needed + } + if (decimalFragment !== undefined || tokenFlags & 16 /* Scientific */) { + return { + type: 8 /* NumericLiteral */, + value: "" + +result // if value is not an integer, it can be safely coerced to a number + }; + } + else { + tokenValue = result; + var type = checkBigIntSuffix(); // if value is an integer, check whether it is a bigint + return { type: type, value: tokenValue }; + } + } + function scanOctalDigits() { + var start = pos; + while (isOctalDigit(text.charCodeAt(pos))) { + pos++; + } + return +(text.substring(start, pos)); + } + /** + * Scans the given number of hexadecimal digits in the text, + * returning -1 if the given number is unavailable. + */ + function scanExactNumberOfHexDigits(count, canHaveSeparators) { + var valueString = scanHexDigits(/*minCount*/ count, /*scanAsManyAsPossible*/ false, canHaveSeparators); + return valueString ? parseInt(valueString, 16) : -1; + } + /** + * Scans as many hexadecimal digits as are available in the text, + * returning "" if the given number of digits was unavailable. + */ + function scanMinimumNumberOfHexDigits(count, canHaveSeparators) { + return scanHexDigits(/*minCount*/ count, /*scanAsManyAsPossible*/ true, canHaveSeparators); + } + function scanHexDigits(minCount, scanAsManyAsPossible, canHaveSeparators) { + var valueChars = []; + var allowSeparator = false; + var isPreviousTokenSeparator = false; + while (valueChars.length < minCount || scanAsManyAsPossible) { + var ch = text.charCodeAt(pos); + if (canHaveSeparators && ch === 95 /* _ */) { + tokenFlags |= 512 /* ContainsSeparator */; + if (allowSeparator) { + allowSeparator = false; + isPreviousTokenSeparator = true; + } + else if (isPreviousTokenSeparator) { + error(ts.Diagnostics.Multiple_consecutive_numeric_separators_are_not_permitted, pos, 1); + } + else { + error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos, 1); + } + pos++; + continue; + } + allowSeparator = canHaveSeparators; + if (ch >= 65 /* A */ && ch <= 70 /* F */) { + ch += 97 /* a */ - 65 /* A */; // standardize hex literals to lowercase + } + else if (!((ch >= 48 /* _0 */ && ch <= 57 /* _9 */) || + (ch >= 97 /* a */ && ch <= 102 /* f */))) { + break; + } + valueChars.push(ch); + pos++; + isPreviousTokenSeparator = false; + } + if (valueChars.length < minCount) { + valueChars = []; + } + if (text.charCodeAt(pos - 1) === 95 /* _ */) { + error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos - 1, 1); + } + return String.fromCharCode.apply(String, valueChars); + } + function scanString(jsxAttributeString) { + if (jsxAttributeString === void 0) { jsxAttributeString = false; } + var quote = text.charCodeAt(pos); + pos++; + var result = ""; + var start = pos; + while (true) { + if (pos >= end) { + result += text.substring(start, pos); + tokenFlags |= 4 /* Unterminated */; + error(ts.Diagnostics.Unterminated_string_literal); + break; + } + var ch = text.charCodeAt(pos); + if (ch === quote) { + result += text.substring(start, pos); + pos++; + break; + } + if (ch === 92 /* backslash */ && !jsxAttributeString) { + result += text.substring(start, pos); + result += scanEscapeSequence(); + start = pos; + continue; + } + if (isLineBreak(ch) && !jsxAttributeString) { + result += text.substring(start, pos); + tokenFlags |= 4 /* Unterminated */; + error(ts.Diagnostics.Unterminated_string_literal); + break; + } + pos++; + } + return result; + } + /** + * Sets the current 'tokenValue' and returns a NoSubstitutionTemplateLiteral or + * a literal component of a TemplateExpression. + */ + function scanTemplateAndSetTokenValue() { + var startedWithBacktick = text.charCodeAt(pos) === 96 /* backtick */; + pos++; + var start = pos; + var contents = ""; + var resultingToken; + while (true) { + if (pos >= end) { + contents += text.substring(start, pos); + tokenFlags |= 4 /* Unterminated */; + error(ts.Diagnostics.Unterminated_template_literal); + resultingToken = startedWithBacktick ? 14 /* NoSubstitutionTemplateLiteral */ : 17 /* TemplateTail */; + break; + } + var currChar = text.charCodeAt(pos); + // '`' + if (currChar === 96 /* backtick */) { + contents += text.substring(start, pos); + pos++; + resultingToken = startedWithBacktick ? 14 /* NoSubstitutionTemplateLiteral */ : 17 /* TemplateTail */; + break; + } + // '${' + if (currChar === 36 /* $ */ && pos + 1 < end && text.charCodeAt(pos + 1) === 123 /* openBrace */) { + contents += text.substring(start, pos); + pos += 2; + resultingToken = startedWithBacktick ? 15 /* TemplateHead */ : 16 /* TemplateMiddle */; + break; + } + // Escape character + if (currChar === 92 /* backslash */) { + contents += text.substring(start, pos); + contents += scanEscapeSequence(); + start = pos; + continue; + } + // Speculated ECMAScript 6 Spec 11.8.6.1: + // and LineTerminatorSequences are normalized to for Template Values + if (currChar === 13 /* carriageReturn */) { + contents += text.substring(start, pos); + pos++; + if (pos < end && text.charCodeAt(pos) === 10 /* lineFeed */) { + pos++; + } + contents += "\n"; + start = pos; + continue; + } + pos++; + } + ts.Debug.assert(resultingToken !== undefined); + tokenValue = contents; + return resultingToken; + } + function scanEscapeSequence() { + pos++; + if (pos >= end) { + error(ts.Diagnostics.Unexpected_end_of_text); + return ""; + } + var ch = text.charCodeAt(pos); + pos++; + switch (ch) { + case 48 /* _0 */: + return "\0"; + case 98 /* b */: + return "\b"; + case 116 /* t */: + return "\t"; + case 110 /* n */: + return "\n"; + case 118 /* v */: + return "\v"; + case 102 /* f */: + return "\f"; + case 114 /* r */: + return "\r"; + case 39 /* singleQuote */: + return "\'"; + case 34 /* doubleQuote */: + return "\""; + case 117 /* u */: + // '\u{DDDDDDDD}' + if (pos < end && text.charCodeAt(pos) === 123 /* openBrace */) { + tokenFlags |= 8 /* ExtendedUnicodeEscape */; + pos++; + return scanExtendedUnicodeEscape(); + } + // '\uDDDD' + return scanHexadecimalEscape(/*numDigits*/ 4); + case 120 /* x */: + // '\xDD' + return scanHexadecimalEscape(/*numDigits*/ 2); + // when encountering a LineContinuation (i.e. a backslash and a line terminator sequence), + // the line terminator is interpreted to be "the empty code unit sequence". + case 13 /* carriageReturn */: + if (pos < end && text.charCodeAt(pos) === 10 /* lineFeed */) { + pos++; + } + // falls through + case 10 /* lineFeed */: + case 8232 /* lineSeparator */: + case 8233 /* paragraphSeparator */: + return ""; + default: + return String.fromCharCode(ch); + } + } + function scanHexadecimalEscape(numDigits) { + var escapedValue = scanExactNumberOfHexDigits(numDigits, /*canHaveSeparators*/ false); + if (escapedValue >= 0) { + return String.fromCharCode(escapedValue); + } + else { + error(ts.Diagnostics.Hexadecimal_digit_expected); + return ""; + } + } + function scanExtendedUnicodeEscape() { + var escapedValueString = scanMinimumNumberOfHexDigits(1, /*canHaveSeparators*/ false); + var escapedValue = escapedValueString ? parseInt(escapedValueString, 16) : -1; + var isInvalidExtendedEscape = false; + // Validate the value of the digit + if (escapedValue < 0) { + error(ts.Diagnostics.Hexadecimal_digit_expected); + isInvalidExtendedEscape = true; + } + else if (escapedValue > 0x10FFFF) { + error(ts.Diagnostics.An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive); + isInvalidExtendedEscape = true; + } + if (pos >= end) { + error(ts.Diagnostics.Unexpected_end_of_text); + isInvalidExtendedEscape = true; + } + else if (text.charCodeAt(pos) === 125 /* closeBrace */) { + // Only swallow the following character up if it's a '}'. + pos++; + } + else { + error(ts.Diagnostics.Unterminated_Unicode_escape_sequence); + isInvalidExtendedEscape = true; + } + if (isInvalidExtendedEscape) { + return ""; + } + return utf16EncodeAsString(escapedValue); + } + // Derived from the 10.1.1 UTF16Encoding of the ES6 Spec. + function utf16EncodeAsString(codePoint) { + ts.Debug.assert(0x0 <= codePoint && codePoint <= 0x10FFFF); + if (codePoint <= 65535) { + return String.fromCharCode(codePoint); + } + var codeUnit1 = Math.floor((codePoint - 65536) / 1024) + 0xD800; + var codeUnit2 = ((codePoint - 65536) % 1024) + 0xDC00; + return String.fromCharCode(codeUnit1, codeUnit2); + } + // Current character is known to be a backslash. Check for Unicode escape of the form '\uXXXX' + // and return code point value if valid Unicode escape is found. Otherwise return -1. + function peekUnicodeEscape() { + if (pos + 5 < end && text.charCodeAt(pos + 1) === 117 /* u */) { + var start_1 = pos; + pos += 2; + var value = scanExactNumberOfHexDigits(4, /*canHaveSeparators*/ false); + pos = start_1; + return value; + } + return -1; + } + function scanIdentifierParts() { + var result = ""; + var start = pos; + while (pos < end) { + var ch = text.charCodeAt(pos); + if (isIdentifierPart(ch, languageVersion)) { + pos++; + } + else if (ch === 92 /* backslash */) { + ch = peekUnicodeEscape(); + if (!(ch >= 0 && isIdentifierPart(ch, languageVersion))) { + break; + } + result += text.substring(start, pos); + result += String.fromCharCode(ch); + // Valid Unicode escape is always six characters + pos += 6; + start = pos; + } + else { + break; + } + } + result += text.substring(start, pos); + return result; + } + function getIdentifierToken() { + // Reserved words are between 2 and 11 characters long and start with a lowercase letter + var len = tokenValue.length; + if (len >= 2 && len <= 11) { + var ch = tokenValue.charCodeAt(0); + if (ch >= 97 /* a */ && ch <= 122 /* z */) { + var keyword = textToKeyword.get(tokenValue); + if (keyword !== undefined) { + return token = keyword; + } + } + } + return token = 72 /* Identifier */; + } + function scanBinaryOrOctalDigits(base) { + var value = ""; + // For counting number of digits; Valid binaryIntegerLiteral must have at least one binary digit following B or b. + // Similarly valid octalIntegerLiteral must have at least one octal digit following o or O. + var separatorAllowed = false; + var isPreviousTokenSeparator = false; + while (true) { + var ch = text.charCodeAt(pos); + // Numeric separators are allowed anywhere within a numeric literal, except not at the beginning, or following another separator + if (ch === 95 /* _ */) { + tokenFlags |= 512 /* ContainsSeparator */; + if (separatorAllowed) { + separatorAllowed = false; + isPreviousTokenSeparator = true; + } + else if (isPreviousTokenSeparator) { + error(ts.Diagnostics.Multiple_consecutive_numeric_separators_are_not_permitted, pos, 1); + } + else { + error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos, 1); + } + pos++; + continue; + } + separatorAllowed = true; + if (!isDigit(ch) || ch - 48 /* _0 */ >= base) { + break; + } + value += text[pos]; + pos++; + isPreviousTokenSeparator = false; + } + if (text.charCodeAt(pos - 1) === 95 /* _ */) { + // Literal ends with underscore - not allowed + error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos - 1, 1); + } + return value; + } + function checkBigIntSuffix() { + if (text.charCodeAt(pos) === 110 /* n */) { + tokenValue += "n"; + // Use base 10 instead of base 2 or base 8 for shorter literals + if (tokenFlags & 384 /* BinaryOrOctalSpecifier */) { + tokenValue = ts.parsePseudoBigInt(tokenValue) + "n"; + } + pos++; + return 9 /* BigIntLiteral */; + } + else { // not a bigint, so can convert to number in simplified form + // Number() may not support 0b or 0o, so use parseInt() instead + var numericValue = tokenFlags & 128 /* BinarySpecifier */ + ? parseInt(tokenValue.slice(2), 2) // skip "0b" + : tokenFlags & 256 /* OctalSpecifier */ + ? parseInt(tokenValue.slice(2), 8) // skip "0o" + : +tokenValue; + tokenValue = "" + numericValue; + return 8 /* NumericLiteral */; + } + } + function scan() { + var _a; + startPos = pos; + tokenFlags = 0; + var asteriskSeen = false; + while (true) { + tokenPos = pos; + if (pos >= end) { + return token = 1 /* EndOfFileToken */; + } + var ch = text.charCodeAt(pos); + // Special handling for shebang + if (ch === 35 /* hash */ && pos === 0 && isShebangTrivia(text, pos)) { + pos = scanShebangTrivia(text, pos); + if (skipTrivia) { + continue; + } + else { + return token = 6 /* ShebangTrivia */; + } + } + switch (ch) { + case 10 /* lineFeed */: + case 13 /* carriageReturn */: + tokenFlags |= 1 /* PrecedingLineBreak */; + if (skipTrivia) { + pos++; + continue; + } + else { + if (ch === 13 /* carriageReturn */ && pos + 1 < end && text.charCodeAt(pos + 1) === 10 /* lineFeed */) { + // consume both CR and LF + pos += 2; + } + else { + pos++; + } + return token = 4 /* NewLineTrivia */; + } + case 9 /* tab */: + case 11 /* verticalTab */: + case 12 /* formFeed */: + case 32 /* space */: + case 160 /* nonBreakingSpace */: + case 5760 /* ogham */: + case 8192 /* enQuad */: + case 8193 /* emQuad */: + case 8194 /* enSpace */: + case 8195 /* emSpace */: + case 8196 /* threePerEmSpace */: + case 8197 /* fourPerEmSpace */: + case 8198 /* sixPerEmSpace */: + case 8199 /* figureSpace */: + case 8200 /* punctuationSpace */: + case 8201 /* thinSpace */: + case 8202 /* hairSpace */: + case 8203 /* zeroWidthSpace */: + case 8239 /* narrowNoBreakSpace */: + case 8287 /* mathematicalSpace */: + case 12288 /* ideographicSpace */: + case 65279 /* byteOrderMark */: + if (skipTrivia) { + pos++; + continue; + } + else { + while (pos < end && isWhiteSpaceSingleLine(text.charCodeAt(pos))) { + pos++; + } + return token = 5 /* WhitespaceTrivia */; + } + case 33 /* exclamation */: + if (text.charCodeAt(pos + 1) === 61 /* equals */) { + if (text.charCodeAt(pos + 2) === 61 /* equals */) { + return pos += 3, token = 36 /* ExclamationEqualsEqualsToken */; + } + return pos += 2, token = 34 /* ExclamationEqualsToken */; + } + pos++; + return token = 52 /* ExclamationToken */; + case 34 /* doubleQuote */: + case 39 /* singleQuote */: + tokenValue = scanString(); + return token = 10 /* StringLiteral */; + case 96 /* backtick */: + return token = scanTemplateAndSetTokenValue(); + case 37 /* percent */: + if (text.charCodeAt(pos + 1) === 61 /* equals */) { + return pos += 2, token = 65 /* PercentEqualsToken */; + } + pos++; + return token = 43 /* PercentToken */; + case 38 /* ampersand */: + if (text.charCodeAt(pos + 1) === 38 /* ampersand */) { + return pos += 2, token = 54 /* AmpersandAmpersandToken */; + } + if (text.charCodeAt(pos + 1) === 61 /* equals */) { + return pos += 2, token = 69 /* AmpersandEqualsToken */; + } + pos++; + return token = 49 /* AmpersandToken */; + case 40 /* openParen */: + pos++; + return token = 20 /* OpenParenToken */; + case 41 /* closeParen */: + pos++; + return token = 21 /* CloseParenToken */; + case 42 /* asterisk */: + if (text.charCodeAt(pos + 1) === 61 /* equals */) { + return pos += 2, token = 62 /* AsteriskEqualsToken */; + } + if (text.charCodeAt(pos + 1) === 42 /* asterisk */) { + if (text.charCodeAt(pos + 2) === 61 /* equals */) { + return pos += 3, token = 63 /* AsteriskAsteriskEqualsToken */; + } + return pos += 2, token = 41 /* AsteriskAsteriskToken */; + } + pos++; + if (inJSDocType && !asteriskSeen && (tokenFlags & 1 /* PrecedingLineBreak */)) { + // decoration at the start of a JSDoc comment line + asteriskSeen = true; + continue; + } + return token = 40 /* AsteriskToken */; + case 43 /* plus */: + if (text.charCodeAt(pos + 1) === 43 /* plus */) { + return pos += 2, token = 44 /* PlusPlusToken */; + } + if (text.charCodeAt(pos + 1) === 61 /* equals */) { + return pos += 2, token = 60 /* PlusEqualsToken */; + } + pos++; + return token = 38 /* PlusToken */; + case 44 /* comma */: + pos++; + return token = 27 /* CommaToken */; + case 45 /* minus */: + if (text.charCodeAt(pos + 1) === 45 /* minus */) { + return pos += 2, token = 45 /* MinusMinusToken */; + } + if (text.charCodeAt(pos + 1) === 61 /* equals */) { + return pos += 2, token = 61 /* MinusEqualsToken */; + } + pos++; + return token = 39 /* MinusToken */; + case 46 /* dot */: + if (isDigit(text.charCodeAt(pos + 1))) { + tokenValue = scanNumber().value; + return token = 8 /* NumericLiteral */; + } + if (text.charCodeAt(pos + 1) === 46 /* dot */ && text.charCodeAt(pos + 2) === 46 /* dot */) { + return pos += 3, token = 25 /* DotDotDotToken */; + } + pos++; + return token = 24 /* DotToken */; + case 47 /* slash */: + // Single-line comment + if (text.charCodeAt(pos + 1) === 47 /* slash */) { + pos += 2; + while (pos < end) { + if (isLineBreak(text.charCodeAt(pos))) { + break; + } + pos++; + } + if (skipTrivia) { + continue; + } + else { + return token = 2 /* SingleLineCommentTrivia */; + } + } + // Multi-line comment + if (text.charCodeAt(pos + 1) === 42 /* asterisk */) { + pos += 2; + if (text.charCodeAt(pos) === 42 /* asterisk */ && text.charCodeAt(pos + 1) !== 47 /* slash */) { + tokenFlags |= 2 /* PrecedingJSDocComment */; + } + var commentClosed = false; + while (pos < end) { + var ch_1 = text.charCodeAt(pos); + if (ch_1 === 42 /* asterisk */ && text.charCodeAt(pos + 1) === 47 /* slash */) { + pos += 2; + commentClosed = true; + break; + } + if (isLineBreak(ch_1)) { + tokenFlags |= 1 /* PrecedingLineBreak */; + } + pos++; + } + if (!commentClosed) { + error(ts.Diagnostics.Asterisk_Slash_expected); + } + if (skipTrivia) { + continue; + } + else { + if (!commentClosed) { + tokenFlags |= 4 /* Unterminated */; + } + return token = 3 /* MultiLineCommentTrivia */; + } + } + if (text.charCodeAt(pos + 1) === 61 /* equals */) { + return pos += 2, token = 64 /* SlashEqualsToken */; + } + pos++; + return token = 42 /* SlashToken */; + case 48 /* _0 */: + if (pos + 2 < end && (text.charCodeAt(pos + 1) === 88 /* X */ || text.charCodeAt(pos + 1) === 120 /* x */)) { + pos += 2; + tokenValue = scanMinimumNumberOfHexDigits(1, /*canHaveSeparators*/ true); + if (!tokenValue) { + error(ts.Diagnostics.Hexadecimal_digit_expected); + tokenValue = "0"; + } + tokenValue = "0x" + tokenValue; + tokenFlags |= 64 /* HexSpecifier */; + return token = checkBigIntSuffix(); + } + else if (pos + 2 < end && (text.charCodeAt(pos + 1) === 66 /* B */ || text.charCodeAt(pos + 1) === 98 /* b */)) { + pos += 2; + tokenValue = scanBinaryOrOctalDigits(/* base */ 2); + if (!tokenValue) { + error(ts.Diagnostics.Binary_digit_expected); + tokenValue = "0"; + } + tokenValue = "0b" + tokenValue; + tokenFlags |= 128 /* BinarySpecifier */; + return token = checkBigIntSuffix(); + } + else if (pos + 2 < end && (text.charCodeAt(pos + 1) === 79 /* O */ || text.charCodeAt(pos + 1) === 111 /* o */)) { + pos += 2; + tokenValue = scanBinaryOrOctalDigits(/* base */ 8); + if (!tokenValue) { + error(ts.Diagnostics.Octal_digit_expected); + tokenValue = "0"; + } + tokenValue = "0o" + tokenValue; + tokenFlags |= 256 /* OctalSpecifier */; + return token = checkBigIntSuffix(); + } + // Try to parse as an octal + if (pos + 1 < end && isOctalDigit(text.charCodeAt(pos + 1))) { + tokenValue = "" + scanOctalDigits(); + tokenFlags |= 32 /* Octal */; + return token = 8 /* NumericLiteral */; + } + // This fall-through is a deviation from the EcmaScript grammar. The grammar says that a leading zero + // can only be followed by an octal digit, a dot, or the end of the number literal. However, we are being + // permissive and allowing decimal digits of the form 08* and 09* (which many browsers also do). + // falls through + case 49 /* _1 */: + case 50 /* _2 */: + case 51 /* _3 */: + case 52 /* _4 */: + case 53 /* _5 */: + case 54 /* _6 */: + case 55 /* _7 */: + case 56 /* _8 */: + case 57 /* _9 */: + (_a = scanNumber(), token = _a.type, tokenValue = _a.value); + return token; + case 58 /* colon */: + pos++; + return token = 57 /* ColonToken */; + case 59 /* semicolon */: + pos++; + return token = 26 /* SemicolonToken */; + case 60 /* lessThan */: + if (isConflictMarkerTrivia(text, pos)) { + pos = scanConflictMarkerTrivia(text, pos, error); + if (skipTrivia) { + continue; + } + else { + return token = 7 /* ConflictMarkerTrivia */; + } + } + if (text.charCodeAt(pos + 1) === 60 /* lessThan */) { + if (text.charCodeAt(pos + 2) === 61 /* equals */) { + return pos += 3, token = 66 /* LessThanLessThanEqualsToken */; + } + return pos += 2, token = 46 /* LessThanLessThanToken */; + } + if (text.charCodeAt(pos + 1) === 61 /* equals */) { + return pos += 2, token = 31 /* LessThanEqualsToken */; + } + if (languageVariant === 1 /* JSX */ && + text.charCodeAt(pos + 1) === 47 /* slash */ && + text.charCodeAt(pos + 2) !== 42 /* asterisk */) { + return pos += 2, token = 29 /* LessThanSlashToken */; + } + pos++; + return token = 28 /* LessThanToken */; + case 61 /* equals */: + if (isConflictMarkerTrivia(text, pos)) { + pos = scanConflictMarkerTrivia(text, pos, error); + if (skipTrivia) { + continue; + } + else { + return token = 7 /* ConflictMarkerTrivia */; + } + } + if (text.charCodeAt(pos + 1) === 61 /* equals */) { + if (text.charCodeAt(pos + 2) === 61 /* equals */) { + return pos += 3, token = 35 /* EqualsEqualsEqualsToken */; + } + return pos += 2, token = 33 /* EqualsEqualsToken */; + } + if (text.charCodeAt(pos + 1) === 62 /* greaterThan */) { + return pos += 2, token = 37 /* EqualsGreaterThanToken */; + } + pos++; + return token = 59 /* EqualsToken */; + case 62 /* greaterThan */: + if (isConflictMarkerTrivia(text, pos)) { + pos = scanConflictMarkerTrivia(text, pos, error); + if (skipTrivia) { + continue; + } + else { + return token = 7 /* ConflictMarkerTrivia */; + } + } + pos++; + return token = 30 /* GreaterThanToken */; + case 63 /* question */: + pos++; + return token = 56 /* QuestionToken */; + case 91 /* openBracket */: + pos++; + return token = 22 /* OpenBracketToken */; + case 93 /* closeBracket */: + pos++; + return token = 23 /* CloseBracketToken */; + case 94 /* caret */: + if (text.charCodeAt(pos + 1) === 61 /* equals */) { + return pos += 2, token = 71 /* CaretEqualsToken */; + } + pos++; + return token = 51 /* CaretToken */; + case 123 /* openBrace */: + pos++; + return token = 18 /* OpenBraceToken */; + case 124 /* bar */: + if (isConflictMarkerTrivia(text, pos)) { + pos = scanConflictMarkerTrivia(text, pos, error); + if (skipTrivia) { + continue; + } + else { + return token = 7 /* ConflictMarkerTrivia */; + } + } + if (text.charCodeAt(pos + 1) === 124 /* bar */) { + return pos += 2, token = 55 /* BarBarToken */; + } + if (text.charCodeAt(pos + 1) === 61 /* equals */) { + return pos += 2, token = 70 /* BarEqualsToken */; + } + pos++; + return token = 50 /* BarToken */; + case 125 /* closeBrace */: + pos++; + return token = 19 /* CloseBraceToken */; + case 126 /* tilde */: + pos++; + return token = 53 /* TildeToken */; + case 64 /* at */: + pos++; + return token = 58 /* AtToken */; + case 92 /* backslash */: + var cookedChar = peekUnicodeEscape(); + if (cookedChar >= 0 && isIdentifierStart(cookedChar, languageVersion)) { + pos += 6; + tokenValue = String.fromCharCode(cookedChar) + scanIdentifierParts(); + return token = getIdentifierToken(); + } + error(ts.Diagnostics.Invalid_character); + pos++; + return token = 0 /* Unknown */; + default: + if (isIdentifierStart(ch, languageVersion)) { + pos++; + while (pos < end && isIdentifierPart(ch = text.charCodeAt(pos), languageVersion)) + pos++; + tokenValue = text.substring(tokenPos, pos); + if (ch === 92 /* backslash */) { + tokenValue += scanIdentifierParts(); + } + return token = getIdentifierToken(); + } + else if (isWhiteSpaceSingleLine(ch)) { + pos++; + continue; + } + else if (isLineBreak(ch)) { + tokenFlags |= 1 /* PrecedingLineBreak */; + pos++; + continue; + } + error(ts.Diagnostics.Invalid_character); + pos++; + return token = 0 /* Unknown */; + } + } + } + function reScanGreaterToken() { + if (token === 30 /* GreaterThanToken */) { + if (text.charCodeAt(pos) === 62 /* greaterThan */) { + if (text.charCodeAt(pos + 1) === 62 /* greaterThan */) { + if (text.charCodeAt(pos + 2) === 61 /* equals */) { + return pos += 3, token = 68 /* GreaterThanGreaterThanGreaterThanEqualsToken */; + } + return pos += 2, token = 48 /* GreaterThanGreaterThanGreaterThanToken */; + } + if (text.charCodeAt(pos + 1) === 61 /* equals */) { + return pos += 2, token = 67 /* GreaterThanGreaterThanEqualsToken */; + } + pos++; + return token = 47 /* GreaterThanGreaterThanToken */; + } + if (text.charCodeAt(pos) === 61 /* equals */) { + pos++; + return token = 32 /* GreaterThanEqualsToken */; + } + } + return token; + } + function reScanSlashToken() { + if (token === 42 /* SlashToken */ || token === 64 /* SlashEqualsToken */) { + var p = tokenPos + 1; + var inEscape = false; + var inCharacterClass = false; + while (true) { + // If we reach the end of a file, or hit a newline, then this is an unterminated + // regex. Report error and return what we have so far. + if (p >= end) { + tokenFlags |= 4 /* Unterminated */; + error(ts.Diagnostics.Unterminated_regular_expression_literal); + break; + } + var ch = text.charCodeAt(p); + if (isLineBreak(ch)) { + tokenFlags |= 4 /* Unterminated */; + error(ts.Diagnostics.Unterminated_regular_expression_literal); + break; + } + if (inEscape) { + // Parsing an escape character; + // reset the flag and just advance to the next char. + inEscape = false; + } + else if (ch === 47 /* slash */ && !inCharacterClass) { + // A slash within a character class is permissible, + // but in general it signals the end of the regexp literal. + p++; + break; + } + else if (ch === 91 /* openBracket */) { + inCharacterClass = true; + } + else if (ch === 92 /* backslash */) { + inEscape = true; + } + else if (ch === 93 /* closeBracket */) { + inCharacterClass = false; + } + p++; + } + while (p < end && isIdentifierPart(text.charCodeAt(p), languageVersion)) { + p++; + } + pos = p; + tokenValue = text.substring(tokenPos, pos); + token = 13 /* RegularExpressionLiteral */; + } + return token; + } + /** + * Unconditionally back up and scan a template expression portion. + */ + function reScanTemplateToken() { + ts.Debug.assert(token === 19 /* CloseBraceToken */, "'reScanTemplateToken' should only be called on a '}'"); + pos = tokenPos; + return token = scanTemplateAndSetTokenValue(); + } + function reScanJsxToken() { + pos = tokenPos = startPos; + return token = scanJsxToken(); + } + function scanJsxToken() { + startPos = tokenPos = pos; + if (pos >= end) { + return token = 1 /* EndOfFileToken */; + } + var char = text.charCodeAt(pos); + if (char === 60 /* lessThan */) { + if (text.charCodeAt(pos + 1) === 47 /* slash */) { + pos += 2; + return token = 29 /* LessThanSlashToken */; + } + pos++; + return token = 28 /* LessThanToken */; + } + if (char === 123 /* openBrace */) { + pos++; + return token = 18 /* OpenBraceToken */; + } + // First non-whitespace character on this line. + var firstNonWhitespace = 0; + // These initial values are special because the first line is: + // firstNonWhitespace = 0 to indicate that we want leading whitspace, + while (pos < end) { + char = text.charCodeAt(pos); + if (char === 123 /* openBrace */) { + break; + } + if (char === 60 /* lessThan */) { + if (isConflictMarkerTrivia(text, pos)) { + pos = scanConflictMarkerTrivia(text, pos, error); + return token = 7 /* ConflictMarkerTrivia */; + } + break; + } + // FirstNonWhitespace is 0, then we only see whitespaces so far. If we see a linebreak, we want to ignore that whitespaces. + // i.e (- : whitespace) + //
      ---- + //
      becomes
      + // + //
      ----
      becomes
      ----
      + if (isLineBreak(char) && firstNonWhitespace === 0) { + firstNonWhitespace = -1; + } + else if (!isWhiteSpaceLike(char)) { + firstNonWhitespace = pos; + } + pos++; + } + return firstNonWhitespace === -1 ? 12 /* JsxTextAllWhiteSpaces */ : 11 /* JsxText */; + } + // Scans a JSX identifier; these differ from normal identifiers in that + // they allow dashes + function scanJsxIdentifier() { + if (tokenIsIdentifierOrKeyword(token)) { + var firstCharPosition = pos; + while (pos < end) { + var ch = text.charCodeAt(pos); + if (ch === 45 /* minus */ || ((firstCharPosition === pos) ? isIdentifierStart(ch, languageVersion) : isIdentifierPart(ch, languageVersion))) { + pos++; + } + else { + break; + } + } + tokenValue += text.substring(firstCharPosition, pos); + } + return token; + } + function scanJsxAttributeValue() { + startPos = pos; + switch (text.charCodeAt(pos)) { + case 34 /* doubleQuote */: + case 39 /* singleQuote */: + tokenValue = scanString(/*jsxAttributeString*/ true); + return token = 10 /* StringLiteral */; + default: + // If this scans anything other than `{`, it's a parse error. + return scan(); + } + } + function scanJSDocToken() { + startPos = tokenPos = pos; + tokenFlags = 0; + if (pos >= end) { + return token = 1 /* EndOfFileToken */; + } + var ch = text.charCodeAt(pos); + pos++; + switch (ch) { + case 9 /* tab */: + case 11 /* verticalTab */: + case 12 /* formFeed */: + case 32 /* space */: + while (pos < end && isWhiteSpaceSingleLine(text.charCodeAt(pos))) { + pos++; + } + return token = 5 /* WhitespaceTrivia */; + case 64 /* at */: + return token = 58 /* AtToken */; + case 10 /* lineFeed */: + case 13 /* carriageReturn */: + tokenFlags |= 1 /* PrecedingLineBreak */; + return token = 4 /* NewLineTrivia */; + case 42 /* asterisk */: + return token = 40 /* AsteriskToken */; + case 123 /* openBrace */: + return token = 18 /* OpenBraceToken */; + case 125 /* closeBrace */: + return token = 19 /* CloseBraceToken */; + case 91 /* openBracket */: + return token = 22 /* OpenBracketToken */; + case 93 /* closeBracket */: + return token = 23 /* CloseBracketToken */; + case 60 /* lessThan */: + return token = 28 /* LessThanToken */; + case 61 /* equals */: + return token = 59 /* EqualsToken */; + case 44 /* comma */: + return token = 27 /* CommaToken */; + case 46 /* dot */: + return token = 24 /* DotToken */; + case 96 /* backtick */: + while (pos < end && text.charCodeAt(pos) !== 96 /* backtick */) { + pos++; + } + tokenValue = text.substring(tokenPos + 1, pos); + pos++; + return token = 14 /* NoSubstitutionTemplateLiteral */; + } + if (isIdentifierStart(ch, 6 /* Latest */)) { + while (isIdentifierPart(text.charCodeAt(pos), 6 /* Latest */) && pos < end) { + pos++; + } + tokenValue = text.substring(tokenPos, pos); + return token = getIdentifierToken(); + } + else { + return token = 0 /* Unknown */; + } + } + function speculationHelper(callback, isLookahead) { + var savePos = pos; + var saveStartPos = startPos; + var saveTokenPos = tokenPos; + var saveToken = token; + var saveTokenValue = tokenValue; + var saveTokenFlags = tokenFlags; + var result = callback(); + // If our callback returned something 'falsy' or we're just looking ahead, + // then unconditionally restore us to where we were. + if (!result || isLookahead) { + pos = savePos; + startPos = saveStartPos; + tokenPos = saveTokenPos; + token = saveToken; + tokenValue = saveTokenValue; + tokenFlags = saveTokenFlags; + } + return result; + } + function scanRange(start, length, callback) { + var saveEnd = end; + var savePos = pos; + var saveStartPos = startPos; + var saveTokenPos = tokenPos; + var saveToken = token; + var saveTokenValue = tokenValue; + var saveTokenFlags = tokenFlags; + setText(text, start, length); + var result = callback(); + end = saveEnd; + pos = savePos; + startPos = saveStartPos; + tokenPos = saveTokenPos; + token = saveToken; + tokenValue = saveTokenValue; + tokenFlags = saveTokenFlags; + return result; + } + function lookAhead(callback) { + return speculationHelper(callback, /*isLookahead*/ true); + } + function tryScan(callback) { + return speculationHelper(callback, /*isLookahead*/ false); + } + function getText() { + return text; + } + function setText(newText, start, length) { + text = newText || ""; + end = length === undefined ? text.length : start + length; + setTextPos(start || 0); + } + function setOnError(errorCallback) { + onError = errorCallback; + } + function setScriptTarget(scriptTarget) { + languageVersion = scriptTarget; + } + function setLanguageVariant(variant) { + languageVariant = variant; + } + function setTextPos(textPos) { + ts.Debug.assert(textPos >= 0); + pos = textPos; + startPos = textPos; + tokenPos = textPos; + token = 0 /* Unknown */; + tokenValue = undefined; + tokenFlags = 0; + } + function setInJSDocType(inType) { + inJSDocType += inType ? 1 : -1; + } + } + ts.createScanner = createScanner; +})(ts || (ts = {})); +var ts; +(function (ts) { + function isExternalModuleNameRelative(moduleName) { + // TypeScript 1.0 spec (April 2014): 11.2.1 + // An external module name is "relative" if the first term is "." or "..". + // Update: We also consider a path like `C:\foo.ts` "relative" because we do not search for it in `node_modules` or treat it as an ambient module. + return ts.pathIsRelative(moduleName) || ts.isRootedDiskPath(moduleName); + } + ts.isExternalModuleNameRelative = isExternalModuleNameRelative; + function sortAndDeduplicateDiagnostics(diagnostics) { + return ts.sortAndDeduplicate(diagnostics, ts.compareDiagnostics); + } + ts.sortAndDeduplicateDiagnostics = sortAndDeduplicateDiagnostics; +})(ts || (ts = {})); +/* @internal */ +(function (ts) { + ts.resolvingEmptyArray = []; + ts.emptyMap = ts.createMap(); + ts.emptyUnderscoreEscapedMap = ts.emptyMap; + ts.externalHelpersModuleNameText = "tslib"; + ts.defaultMaximumTruncationLength = 160; + function getDeclarationOfKind(symbol, kind) { + var declarations = symbol.declarations; + if (declarations) { + for (var _i = 0, declarations_1 = declarations; _i < declarations_1.length; _i++) { + var declaration = declarations_1[_i]; + if (declaration.kind === kind) { + return declaration; + } + } + } + return undefined; + } + ts.getDeclarationOfKind = getDeclarationOfKind; + /** Create a new escaped identifier map. */ + function createUnderscoreEscapedMap() { + return new ts.MapCtr(); + } + ts.createUnderscoreEscapedMap = createUnderscoreEscapedMap; + function hasEntries(map) { + return !!map && !!map.size; + } + ts.hasEntries = hasEntries; + function createSymbolTable(symbols) { + var result = ts.createMap(); + if (symbols) { + for (var _i = 0, symbols_1 = symbols; _i < symbols_1.length; _i++) { + var symbol = symbols_1[_i]; + result.set(symbol.escapedName, symbol); + } + } + return result; + } + ts.createSymbolTable = createSymbolTable; + var stringWriter = createSingleLineStringWriter(); + function createSingleLineStringWriter() { + var str = ""; + var writeText = function (text) { return str += text; }; + return { + getText: function () { return str; }, + write: writeText, + rawWrite: writeText, + writeKeyword: writeText, + writeOperator: writeText, + writePunctuation: writeText, + writeSpace: writeText, + writeStringLiteral: writeText, + writeLiteral: writeText, + writeParameter: writeText, + writeProperty: writeText, + writeSymbol: function (s, _) { return writeText(s); }, + writeTrailingSemicolon: writeText, + writeComment: writeText, + getTextPos: function () { return str.length; }, + getLine: function () { return 0; }, + getColumn: function () { return 0; }, + getIndent: function () { return 0; }, + isAtStartOfLine: function () { return false; }, + // Completely ignore indentation for string writers. And map newlines to + // a single space. + writeLine: function () { return str += " "; }, + increaseIndent: ts.noop, + decreaseIndent: ts.noop, + clear: function () { return str = ""; }, + trackSymbol: ts.noop, + reportInaccessibleThisError: ts.noop, + reportInaccessibleUniqueSymbolError: ts.noop, + reportPrivateInBaseOfClassExpression: ts.noop, + }; + } + function toPath(fileName, basePath, getCanonicalFileName) { + var nonCanonicalizedPath = ts.isRootedDiskPath(fileName) + ? ts.normalizePath(fileName) + : ts.getNormalizedAbsolutePath(fileName, basePath); + return getCanonicalFileName(nonCanonicalizedPath); + } + ts.toPath = toPath; + function changesAffectModuleResolution(oldOptions, newOptions) { + return oldOptions.configFilePath !== newOptions.configFilePath || ts.moduleResolutionOptionDeclarations.some(function (o) { + return !ts.isJsonEqual(ts.getCompilerOptionValue(oldOptions, o), ts.getCompilerOptionValue(newOptions, o)); + }); + } + ts.changesAffectModuleResolution = changesAffectModuleResolution; + function findAncestor(node, callback) { + while (node) { + var result = callback(node); + if (result === "quit") { + return undefined; + } + else if (result) { + return node; + } + node = node.parent; + } + return undefined; + } + ts.findAncestor = findAncestor; + function forEachAncestor(node, callback) { + while (true) { + var res = callback(node); + if (res === "quit") + return undefined; + if (res !== undefined) + return res; + if (ts.isSourceFile(node)) + return undefined; + node = node.parent; + } + } + ts.forEachAncestor = forEachAncestor; + function forEachEntry(map, callback) { + var _a; + var iterator = map.entries(); + for (var _b = iterator.next(), pair = _b.value, done = _b.done; !done; _a = iterator.next(), pair = _a.value, done = _a.done, _a) { + var key = pair[0], value = pair[1]; + var result = callback(value, key); + if (result) { + return result; + } + } + return undefined; + } + ts.forEachEntry = forEachEntry; + function forEachKey(map, callback) { + var _a; + var iterator = map.keys(); + for (var _b = iterator.next(), key = _b.value, done = _b.done; !done; _a = iterator.next(), key = _a.value, done = _a.done, _a) { + var result = callback(key); + if (result) { + return result; + } + } + return undefined; + } + ts.forEachKey = forEachKey; + function copyEntries(source, target) { + source.forEach(function (value, key) { + target.set(key, value); + }); + } + ts.copyEntries = copyEntries; + function arrayToSet(array, makeKey) { + return ts.arrayToMap(array, makeKey || (function (s) { return s; }), function () { return true; }); + } + ts.arrayToSet = arrayToSet; + function cloneMap(map) { + var clone = ts.createMap(); + copyEntries(map, clone); + return clone; + } + ts.cloneMap = cloneMap; + function usingSingleLineStringWriter(action) { + var oldString = stringWriter.getText(); + try { + action(stringWriter); + return stringWriter.getText(); + } + finally { + stringWriter.clear(); + stringWriter.writeKeyword(oldString); + } + } + ts.usingSingleLineStringWriter = usingSingleLineStringWriter; + function getFullWidth(node) { + return node.end - node.pos; + } + ts.getFullWidth = getFullWidth; + function getResolvedModule(sourceFile, moduleNameText) { + return sourceFile && sourceFile.resolvedModules && sourceFile.resolvedModules.get(moduleNameText); + } + ts.getResolvedModule = getResolvedModule; + function setResolvedModule(sourceFile, moduleNameText, resolvedModule) { + if (!sourceFile.resolvedModules) { + sourceFile.resolvedModules = ts.createMap(); + } + sourceFile.resolvedModules.set(moduleNameText, resolvedModule); + } + ts.setResolvedModule = setResolvedModule; + function setResolvedTypeReferenceDirective(sourceFile, typeReferenceDirectiveName, resolvedTypeReferenceDirective) { + if (!sourceFile.resolvedTypeReferenceDirectiveNames) { + sourceFile.resolvedTypeReferenceDirectiveNames = ts.createMap(); + } + sourceFile.resolvedTypeReferenceDirectiveNames.set(typeReferenceDirectiveName, resolvedTypeReferenceDirective); + } + ts.setResolvedTypeReferenceDirective = setResolvedTypeReferenceDirective; + function projectReferenceIsEqualTo(oldRef, newRef) { + return oldRef.path === newRef.path && + !oldRef.prepend === !newRef.prepend && + !oldRef.circular === !newRef.circular; + } + ts.projectReferenceIsEqualTo = projectReferenceIsEqualTo; + function moduleResolutionIsEqualTo(oldResolution, newResolution) { + return oldResolution.isExternalLibraryImport === newResolution.isExternalLibraryImport && + oldResolution.extension === newResolution.extension && + oldResolution.resolvedFileName === newResolution.resolvedFileName && + oldResolution.originalPath === newResolution.originalPath && + packageIdIsEqual(oldResolution.packageId, newResolution.packageId); + } + ts.moduleResolutionIsEqualTo = moduleResolutionIsEqualTo; + function packageIdIsEqual(a, b) { + return a === b || !!a && !!b && a.name === b.name && a.subModuleName === b.subModuleName && a.version === b.version; + } + function packageIdToString(_a) { + var name = _a.name, subModuleName = _a.subModuleName, version = _a.version; + var fullName = subModuleName ? name + "/" + subModuleName : name; + return fullName + "@" + version; + } + ts.packageIdToString = packageIdToString; + function typeDirectiveIsEqualTo(oldResolution, newResolution) { + return oldResolution.resolvedFileName === newResolution.resolvedFileName && oldResolution.primary === newResolution.primary; + } + ts.typeDirectiveIsEqualTo = typeDirectiveIsEqualTo; + function hasChangesInResolutions(names, newResolutions, oldResolutions, comparer) { + ts.Debug.assert(names.length === newResolutions.length); + for (var i = 0; i < names.length; i++) { + var newResolution = newResolutions[i]; + var oldResolution = oldResolutions && oldResolutions.get(names[i]); + var changed = oldResolution + ? !newResolution || !comparer(oldResolution, newResolution) + : newResolution; + if (changed) { + return true; + } + } + return false; + } + ts.hasChangesInResolutions = hasChangesInResolutions; + // Returns true if this node contains a parse error anywhere underneath it. + function containsParseError(node) { + aggregateChildData(node); + return (node.flags & 131072 /* ThisNodeOrAnySubNodesHasError */) !== 0; + } + ts.containsParseError = containsParseError; + function aggregateChildData(node) { + if (!(node.flags & 262144 /* HasAggregatedChildData */)) { + // A node is considered to contain a parse error if: + // a) the parser explicitly marked that it had an error + // b) any of it's children reported that it had an error. + var thisNodeOrAnySubNodesHasError = ((node.flags & 32768 /* ThisNodeHasError */) !== 0) || + ts.forEachChild(node, containsParseError); + // If so, mark ourselves accordingly. + if (thisNodeOrAnySubNodesHasError) { + node.flags |= 131072 /* ThisNodeOrAnySubNodesHasError */; + } + // Also mark that we've propagated the child information to this node. This way we can + // always consult the bit directly on this node without needing to check its children + // again. + node.flags |= 262144 /* HasAggregatedChildData */; + } + } + function getSourceFileOfNode(node) { + while (node && node.kind !== 279 /* SourceFile */) { + node = node.parent; + } + return node; + } + ts.getSourceFileOfNode = getSourceFileOfNode; + function isStatementWithLocals(node) { + switch (node.kind) { + case 218 /* Block */: + case 246 /* CaseBlock */: + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + return true; + } + return false; + } + ts.isStatementWithLocals = isStatementWithLocals; + function getStartPositionOfLine(line, sourceFile) { + ts.Debug.assert(line >= 0); + return ts.getLineStarts(sourceFile)[line]; + } + ts.getStartPositionOfLine = getStartPositionOfLine; + // This is a useful function for debugging purposes. + function nodePosToString(node) { + var file = getSourceFileOfNode(node); + var loc = ts.getLineAndCharacterOfPosition(file, node.pos); + return file.fileName + "(" + (loc.line + 1) + "," + (loc.character + 1) + ")"; + } + ts.nodePosToString = nodePosToString; + function getEndLinePosition(line, sourceFile) { + ts.Debug.assert(line >= 0); + var lineStarts = ts.getLineStarts(sourceFile); + var lineIndex = line; + var sourceText = sourceFile.text; + if (lineIndex + 1 === lineStarts.length) { + // last line - return EOF + return sourceText.length - 1; + } + else { + // current line start + var start = lineStarts[lineIndex]; + // take the start position of the next line - 1 = it should be some line break + var pos = lineStarts[lineIndex + 1] - 1; + ts.Debug.assert(ts.isLineBreak(sourceText.charCodeAt(pos))); + // walk backwards skipping line breaks, stop the the beginning of current line. + // i.e: + // + // $ <- end of line for this position should match the start position + while (start <= pos && ts.isLineBreak(sourceText.charCodeAt(pos))) { + pos--; + } + return pos; + } + } + ts.getEndLinePosition = getEndLinePosition; + /** + * Returns a value indicating whether a name is unique globally or within the current file. + * Note: This does not consider whether a name appears as a free identifier or not, so at the expression `x.y` this includes both `x` and `y`. + */ + function isFileLevelUniqueName(sourceFile, name, hasGlobalName) { + return !(hasGlobalName && hasGlobalName(name)) && !sourceFile.identifiers.has(name); + } + ts.isFileLevelUniqueName = isFileLevelUniqueName; + // Returns true if this node is missing from the actual source code. A 'missing' node is different + // from 'undefined/defined'. When a node is undefined (which can happen for optional nodes + // in the tree), it is definitely missing. However, a node may be defined, but still be + // missing. This happens whenever the parser knows it needs to parse something, but can't + // get anything in the source code that it expects at that location. For example: + // + // let a: ; + // + // Here, the Type in the Type-Annotation is not-optional (as there is a colon in the source + // code). So the parser will attempt to parse out a type, and will create an actual node. + // However, this node will be 'missing' in the sense that no actual source-code/tokens are + // contained within it. + function nodeIsMissing(node) { + if (node === undefined) { + return true; + } + return node.pos === node.end && node.pos >= 0 && node.kind !== 1 /* EndOfFileToken */; + } + ts.nodeIsMissing = nodeIsMissing; + function nodeIsPresent(node) { + return !nodeIsMissing(node); + } + ts.nodeIsPresent = nodeIsPresent; + /** + * Prepends statements to an array while taking care of prologue directives. + */ + function addStatementsAfterPrologue(to, from) { + if (from === undefined || from.length === 0) + return to; + var statementIndex = 0; + // skip all prologue directives to insert at the correct position + for (; statementIndex < to.length; ++statementIndex) { + if (!isPrologueDirective(to[statementIndex])) { + break; + } + } + to.splice.apply(to, [statementIndex, 0].concat(from)); + return to; + } + ts.addStatementsAfterPrologue = addStatementsAfterPrologue; + /** + * Determine if the given comment is a triple-slash + * + * @return true if the comment is a triple-slash comment else false + */ + function isRecognizedTripleSlashComment(text, commentPos, commentEnd) { + // Verify this is /// comment, but do the regexp match only when we first can find /// in the comment text + // so that we don't end up computing comment string and doing match for all // comments + if (text.charCodeAt(commentPos + 1) === 47 /* slash */ && + commentPos + 2 < commentEnd && + text.charCodeAt(commentPos + 2) === 47 /* slash */) { + var textSubStr = text.substring(commentPos, commentEnd); + return textSubStr.match(ts.fullTripleSlashReferencePathRegEx) || + textSubStr.match(ts.fullTripleSlashAMDReferencePathRegEx) || + textSubStr.match(fullTripleSlashReferenceTypeReferenceDirectiveRegEx) || + textSubStr.match(defaultLibReferenceRegEx) ? + true : false; + } + return false; + } + ts.isRecognizedTripleSlashComment = isRecognizedTripleSlashComment; + function isPinnedComment(text, start) { + return text.charCodeAt(start + 1) === 42 /* asterisk */ && + text.charCodeAt(start + 2) === 33 /* exclamation */; + } + ts.isPinnedComment = isPinnedComment; + function getTokenPosOfNode(node, sourceFile, includeJsDoc) { + // With nodes that have no width (i.e. 'Missing' nodes), we actually *don't* + // want to skip trivia because this will launch us forward to the next token. + if (nodeIsMissing(node)) { + return node.pos; + } + if (ts.isJSDocNode(node)) { + return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos, /*stopAfterLineBreak*/ false, /*stopAtComments*/ true); + } + if (includeJsDoc && ts.hasJSDocNodes(node)) { + return getTokenPosOfNode(node.jsDoc[0]); + } + // For a syntax list, it is possible that one of its children has JSDocComment nodes, while + // the syntax list itself considers them as normal trivia. Therefore if we simply skip + // trivia for the list, we may have skipped the JSDocComment as well. So we should process its + // first child to determine the actual position of its first token. + if (node.kind === 306 /* SyntaxList */ && node._children.length > 0) { + return getTokenPosOfNode(node._children[0], sourceFile, includeJsDoc); + } + return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos); + } + ts.getTokenPosOfNode = getTokenPosOfNode; + function getNonDecoratorTokenPosOfNode(node, sourceFile) { + if (nodeIsMissing(node) || !node.decorators) { + return getTokenPosOfNode(node, sourceFile); + } + return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.decorators.end); + } + ts.getNonDecoratorTokenPosOfNode = getNonDecoratorTokenPosOfNode; + function getSourceTextOfNodeFromSourceFile(sourceFile, node, includeTrivia) { + if (includeTrivia === void 0) { includeTrivia = false; } + return getTextOfNodeFromSourceText(sourceFile.text, node, includeTrivia); + } + ts.getSourceTextOfNodeFromSourceFile = getSourceTextOfNodeFromSourceFile; + function isJSDocTypeExpressionOrChild(node) { + return node.kind === 283 /* JSDocTypeExpression */ || (node.parent && isJSDocTypeExpressionOrChild(node.parent)); + } + function getTextOfNodeFromSourceText(sourceText, node, includeTrivia) { + if (includeTrivia === void 0) { includeTrivia = false; } + if (nodeIsMissing(node)) { + return ""; + } + var text = sourceText.substring(includeTrivia ? node.pos : ts.skipTrivia(sourceText, node.pos), node.end); + if (isJSDocTypeExpressionOrChild(node)) { + // strip space + asterisk at line start + text = text.replace(/(^|\r?\n|\r)\s*\*\s*/g, "$1"); + } + return text; + } + ts.getTextOfNodeFromSourceText = getTextOfNodeFromSourceText; + function getTextOfNode(node, includeTrivia) { + if (includeTrivia === void 0) { includeTrivia = false; } + return getSourceTextOfNodeFromSourceFile(getSourceFileOfNode(node), node, includeTrivia); + } + ts.getTextOfNode = getTextOfNode; + function getPos(range) { + return range.pos; + } + /** + * Note: it is expected that the `nodeArray` and the `node` are within the same file. + * For example, searching for a `SourceFile` in a `SourceFile[]` wouldn't work. + */ + function indexOfNode(nodeArray, node) { + return ts.binarySearch(nodeArray, node, getPos, ts.compareValues); + } + ts.indexOfNode = indexOfNode; + /** + * Gets flags that control emit behavior of a node. + */ + function getEmitFlags(node) { + var emitNode = node.emitNode; + return emitNode && emitNode.flags || 0; + } + ts.getEmitFlags = getEmitFlags; + function getLiteralText(node, sourceFile, neverAsciiEscape) { + // If we don't need to downlevel and we can reach the original source text using + // the node's parent reference, then simply get the text as it was originally written. + if (!nodeIsSynthesized(node) && node.parent && !((ts.isNumericLiteral(node) && node.numericLiteralFlags & 512 /* ContainsSeparator */) || + ts.isBigIntLiteral(node))) { + return getSourceTextOfNodeFromSourceFile(sourceFile, node); + } + var escapeText = neverAsciiEscape || (getEmitFlags(node) & 16777216 /* NoAsciiEscaping */) ? escapeString : escapeNonAsciiString; + // If we can't reach the original source text, use the canonical form if it's a number, + // or a (possibly escaped) quoted form of the original text if it's string-like. + switch (node.kind) { + case 10 /* StringLiteral */: + if (node.singleQuote) { + return "'" + escapeText(node.text, 39 /* singleQuote */) + "'"; + } + else { + return '"' + escapeText(node.text, 34 /* doubleQuote */) + '"'; + } + case 14 /* NoSubstitutionTemplateLiteral */: + return "`" + escapeText(node.text, 96 /* backtick */) + "`"; + case 15 /* TemplateHead */: + // tslint:disable-next-line no-invalid-template-strings + return "`" + escapeText(node.text, 96 /* backtick */) + "${"; + case 16 /* TemplateMiddle */: + // tslint:disable-next-line no-invalid-template-strings + return "}" + escapeText(node.text, 96 /* backtick */) + "${"; + case 17 /* TemplateTail */: + return "}" + escapeText(node.text, 96 /* backtick */) + "`"; + case 8 /* NumericLiteral */: + case 9 /* BigIntLiteral */: + case 13 /* RegularExpressionLiteral */: + return node.text; + } + return ts.Debug.fail("Literal kind '" + node.kind + "' not accounted for."); + } + ts.getLiteralText = getLiteralText; + function getTextOfConstantValue(value) { + return ts.isString(value) ? '"' + escapeNonAsciiString(value) + '"' : "" + value; + } + ts.getTextOfConstantValue = getTextOfConstantValue; + // Make an identifier from an external module name by extracting the string after the last "/" and replacing + // all non-alphanumeric characters with underscores + function makeIdentifierFromModuleName(moduleName) { + return ts.getBaseFileName(moduleName).replace(/^(\d)/, "_$1").replace(/\W/g, "_"); + } + ts.makeIdentifierFromModuleName = makeIdentifierFromModuleName; + function isBlockOrCatchScoped(declaration) { + return (ts.getCombinedNodeFlags(declaration) & 3 /* BlockScoped */) !== 0 || + isCatchClauseVariableDeclarationOrBindingElement(declaration); + } + ts.isBlockOrCatchScoped = isBlockOrCatchScoped; + function isCatchClauseVariableDeclarationOrBindingElement(declaration) { + var node = getRootDeclaration(declaration); + return node.kind === 237 /* VariableDeclaration */ && node.parent.kind === 274 /* CatchClause */; + } + ts.isCatchClauseVariableDeclarationOrBindingElement = isCatchClauseVariableDeclarationOrBindingElement; + function isAmbientModule(node) { + return ts.isModuleDeclaration(node) && (node.name.kind === 10 /* StringLiteral */ || isGlobalScopeAugmentation(node)); + } + ts.isAmbientModule = isAmbientModule; + function isModuleWithStringLiteralName(node) { + return ts.isModuleDeclaration(node) && node.name.kind === 10 /* StringLiteral */; + } + ts.isModuleWithStringLiteralName = isModuleWithStringLiteralName; + function isNonGlobalAmbientModule(node) { + return ts.isModuleDeclaration(node) && ts.isStringLiteral(node.name); + } + ts.isNonGlobalAmbientModule = isNonGlobalAmbientModule; + /** + * An effective module (namespace) declaration is either + * 1. An actual declaration: namespace X { ... } + * 2. A Javascript declaration, which is: + * An identifier in a nested property access expression: Y in `X.Y.Z = { ... }` + */ + function isEffectiveModuleDeclaration(node) { + return ts.isModuleDeclaration(node) || ts.isIdentifier(node); + } + ts.isEffectiveModuleDeclaration = isEffectiveModuleDeclaration; + /** Given a symbol for a module, checks that it is a shorthand ambient module. */ + function isShorthandAmbientModuleSymbol(moduleSymbol) { + return isShorthandAmbientModule(moduleSymbol.valueDeclaration); + } + ts.isShorthandAmbientModuleSymbol = isShorthandAmbientModuleSymbol; + function isShorthandAmbientModule(node) { + // The only kind of module that can be missing a body is a shorthand ambient module. + return node && node.kind === 244 /* ModuleDeclaration */ && (!node.body); + } + function isBlockScopedContainerTopLevel(node) { + return node.kind === 279 /* SourceFile */ || + node.kind === 244 /* ModuleDeclaration */ || + ts.isFunctionLike(node); + } + ts.isBlockScopedContainerTopLevel = isBlockScopedContainerTopLevel; + function isGlobalScopeAugmentation(module) { + return !!(module.flags & 512 /* GlobalAugmentation */); + } + ts.isGlobalScopeAugmentation = isGlobalScopeAugmentation; + function isExternalModuleAugmentation(node) { + return isAmbientModule(node) && isModuleAugmentationExternal(node); + } + ts.isExternalModuleAugmentation = isExternalModuleAugmentation; + function isModuleAugmentationExternal(node) { + // external module augmentation is a ambient module declaration that is either: + // - defined in the top level scope and source file is an external module + // - defined inside ambient module declaration located in the top level scope and source file not an external module + switch (node.parent.kind) { + case 279 /* SourceFile */: + return ts.isExternalModule(node.parent); + case 245 /* ModuleBlock */: + return isAmbientModule(node.parent.parent) && ts.isSourceFile(node.parent.parent.parent) && !ts.isExternalModule(node.parent.parent.parent); + } + return false; + } + ts.isModuleAugmentationExternal = isModuleAugmentationExternal; + function getNonAugmentationDeclaration(symbol) { + return ts.find(symbol.declarations, function (d) { return !isExternalModuleAugmentation(d) && !(ts.isModuleDeclaration(d) && isGlobalScopeAugmentation(d)); }); + } + ts.getNonAugmentationDeclaration = getNonAugmentationDeclaration; + function isEffectiveExternalModule(node, compilerOptions) { + return ts.isExternalModule(node) || compilerOptions.isolatedModules || ((ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS) && !!node.commonJsModuleIndicator); + } + ts.isEffectiveExternalModule = isEffectiveExternalModule; + function isBlockScope(node, parentNode) { + switch (node.kind) { + case 279 /* SourceFile */: + case 246 /* CaseBlock */: + case 274 /* CatchClause */: + case 244 /* ModuleDeclaration */: + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + case 157 /* Constructor */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + return true; + case 218 /* Block */: + // function block is not considered block-scope container + // see comment in binder.ts: bind(...), case for SyntaxKind.Block + return !ts.isFunctionLike(parentNode); + } + return false; + } + ts.isBlockScope = isBlockScope; + function isDeclarationWithTypeParameters(node) { + switch (node.kind) { + case 297 /* JSDocCallbackTag */: + case 304 /* JSDocTypedefTag */: + case 293 /* JSDocSignature */: + return true; + default: + ts.assertType(node); + return isDeclarationWithTypeParameterChildren(node); + } + } + ts.isDeclarationWithTypeParameters = isDeclarationWithTypeParameters; + function isDeclarationWithTypeParameterChildren(node) { + switch (node.kind) { + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 155 /* MethodSignature */: + case 162 /* IndexSignature */: + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + case 289 /* JSDocFunctionType */: + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 241 /* InterfaceDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 303 /* JSDocTemplateTag */: + case 239 /* FunctionDeclaration */: + case 156 /* MethodDeclaration */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + return true; + default: + ts.assertType(node); + return false; + } + } + ts.isDeclarationWithTypeParameterChildren = isDeclarationWithTypeParameterChildren; + function isAnyImportSyntax(node) { + switch (node.kind) { + case 249 /* ImportDeclaration */: + case 248 /* ImportEqualsDeclaration */: + return true; + default: + return false; + } + } + ts.isAnyImportSyntax = isAnyImportSyntax; + function isLateVisibilityPaintedStatement(node) { + switch (node.kind) { + case 249 /* ImportDeclaration */: + case 248 /* ImportEqualsDeclaration */: + case 219 /* VariableStatement */: + case 240 /* ClassDeclaration */: + case 239 /* FunctionDeclaration */: + case 244 /* ModuleDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 241 /* InterfaceDeclaration */: + case 243 /* EnumDeclaration */: + return true; + default: + return false; + } + } + ts.isLateVisibilityPaintedStatement = isLateVisibilityPaintedStatement; + function isAnyImportOrReExport(node) { + return isAnyImportSyntax(node) || ts.isExportDeclaration(node); + } + ts.isAnyImportOrReExport = isAnyImportOrReExport; + // Gets the nearest enclosing block scope container that has the provided node + // as a descendant, that is not the provided node. + function getEnclosingBlockScopeContainer(node) { + return findAncestor(node.parent, function (current) { return isBlockScope(current, current.parent); }); + } + ts.getEnclosingBlockScopeContainer = getEnclosingBlockScopeContainer; + // Return display name of an identifier + // Computed property names will just be emitted as "[]", where is the source + // text of the expression in the computed property. + function declarationNameToString(name) { + return !name || getFullWidth(name) === 0 ? "(Missing)" : getTextOfNode(name); + } + ts.declarationNameToString = declarationNameToString; + function getNameFromIndexInfo(info) { + return info.declaration ? declarationNameToString(info.declaration.parameters[0].name) : undefined; + } + ts.getNameFromIndexInfo = getNameFromIndexInfo; + function getTextOfPropertyName(name) { + switch (name.kind) { + case 72 /* Identifier */: + return name.escapedText; + case 10 /* StringLiteral */: + case 8 /* NumericLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: + return ts.escapeLeadingUnderscores(name.text); + case 149 /* ComputedPropertyName */: + return isStringOrNumericLiteralLike(name.expression) ? ts.escapeLeadingUnderscores(name.expression.text) : undefined; // TODO: GH#18217 Almost all uses of this assume the result to be defined! + default: + return ts.Debug.assertNever(name); + } + } + ts.getTextOfPropertyName = getTextOfPropertyName; + function entityNameToString(name) { + switch (name.kind) { + case 72 /* Identifier */: + return getFullWidth(name) === 0 ? ts.idText(name) : getTextOfNode(name); + case 148 /* QualifiedName */: + return entityNameToString(name.left) + "." + entityNameToString(name.right); + case 189 /* PropertyAccessExpression */: + return entityNameToString(name.expression) + "." + entityNameToString(name.name); + default: + throw ts.Debug.assertNever(name); + } + } + ts.entityNameToString = entityNameToString; + function createDiagnosticForNode(node, message, arg0, arg1, arg2, arg3) { + var sourceFile = getSourceFileOfNode(node); + return createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2, arg3); + } + ts.createDiagnosticForNode = createDiagnosticForNode; + function createDiagnosticForNodeArray(sourceFile, nodes, message, arg0, arg1, arg2, arg3) { + var start = ts.skipTrivia(sourceFile.text, nodes.pos); + return ts.createFileDiagnostic(sourceFile, start, nodes.end - start, message, arg0, arg1, arg2, arg3); + } + ts.createDiagnosticForNodeArray = createDiagnosticForNodeArray; + function createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2, arg3) { + var span = getErrorSpanForNode(sourceFile, node); + return ts.createFileDiagnostic(sourceFile, span.start, span.length, message, arg0, arg1, arg2, arg3); + } + ts.createDiagnosticForNodeInSourceFile = createDiagnosticForNodeInSourceFile; + function createDiagnosticForNodeFromMessageChain(node, messageChain, relatedInformation) { + var sourceFile = getSourceFileOfNode(node); + var span = getErrorSpanForNode(sourceFile, node); + return { + file: sourceFile, + start: span.start, + length: span.length, + code: messageChain.code, + category: messageChain.category, + messageText: messageChain.next ? messageChain : messageChain.messageText, + relatedInformation: relatedInformation + }; + } + ts.createDiagnosticForNodeFromMessageChain = createDiagnosticForNodeFromMessageChain; + function getSpanOfTokenAtPosition(sourceFile, pos) { + var scanner = ts.createScanner(sourceFile.languageVersion, /*skipTrivia*/ true, sourceFile.languageVariant, sourceFile.text, /*onError:*/ undefined, pos); + scanner.scan(); + var start = scanner.getTokenPos(); + return ts.createTextSpanFromBounds(start, scanner.getTextPos()); + } + ts.getSpanOfTokenAtPosition = getSpanOfTokenAtPosition; + function getErrorSpanForArrowFunction(sourceFile, node) { + var pos = ts.skipTrivia(sourceFile.text, node.pos); + if (node.body && node.body.kind === 218 /* Block */) { + var startLine = ts.getLineAndCharacterOfPosition(sourceFile, node.body.pos).line; + var endLine = ts.getLineAndCharacterOfPosition(sourceFile, node.body.end).line; + if (startLine < endLine) { + // The arrow function spans multiple lines, + // make the error span be the first line, inclusive. + return ts.createTextSpan(pos, getEndLinePosition(startLine, sourceFile) - pos + 1); + } + } + return ts.createTextSpanFromBounds(pos, node.end); + } + function getErrorSpanForNode(sourceFile, node) { + var errorNode = node; + switch (node.kind) { + case 279 /* SourceFile */: + var pos_1 = ts.skipTrivia(sourceFile.text, 0, /*stopAfterLineBreak*/ false); + if (pos_1 === sourceFile.text.length) { + // file is empty - return span for the beginning of the file + return ts.createTextSpan(0, 0); + } + return getSpanOfTokenAtPosition(sourceFile, pos_1); + // This list is a work in progress. Add missing node kinds to improve their error + // spans. + case 237 /* VariableDeclaration */: + case 186 /* BindingElement */: + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 241 /* InterfaceDeclaration */: + case 244 /* ModuleDeclaration */: + case 243 /* EnumDeclaration */: + case 278 /* EnumMember */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 242 /* TypeAliasDeclaration */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + errorNode = node.name; + break; + case 197 /* ArrowFunction */: + return getErrorSpanForArrowFunction(sourceFile, node); + } + if (errorNode === undefined) { + // If we don't have a better node, then just set the error on the first token of + // construct. + return getSpanOfTokenAtPosition(sourceFile, node.pos); + } + var isMissing = nodeIsMissing(errorNode); + var pos = isMissing + ? errorNode.pos + : ts.skipTrivia(sourceFile.text, errorNode.pos); + // These asserts should all be satisfied for a properly constructed `errorNode`. + if (isMissing) { + ts.Debug.assert(pos === errorNode.pos, "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809"); + ts.Debug.assert(pos === errorNode.end, "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809"); + } + else { + ts.Debug.assert(pos >= errorNode.pos, "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809"); + ts.Debug.assert(pos <= errorNode.end, "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809"); + } + return ts.createTextSpanFromBounds(pos, errorNode.end); + } + ts.getErrorSpanForNode = getErrorSpanForNode; + function isExternalOrCommonJsModule(file) { + return (file.externalModuleIndicator || file.commonJsModuleIndicator) !== undefined; + } + ts.isExternalOrCommonJsModule = isExternalOrCommonJsModule; + function isJsonSourceFile(file) { + return file.scriptKind === 6 /* JSON */; + } + ts.isJsonSourceFile = isJsonSourceFile; + function isEnumConst(node) { + return !!(ts.getCombinedModifierFlags(node) & 2048 /* Const */); + } + ts.isEnumConst = isEnumConst; + function isDeclarationReadonly(declaration) { + return !!(ts.getCombinedModifierFlags(declaration) & 64 /* Readonly */ && !ts.isParameterPropertyDeclaration(declaration)); + } + ts.isDeclarationReadonly = isDeclarationReadonly; + function isVarConst(node) { + return !!(ts.getCombinedNodeFlags(node) & 2 /* Const */); + } + ts.isVarConst = isVarConst; + function isLet(node) { + return !!(ts.getCombinedNodeFlags(node) & 1 /* Let */); + } + ts.isLet = isLet; + function isSuperCall(n) { + return n.kind === 191 /* CallExpression */ && n.expression.kind === 98 /* SuperKeyword */; + } + ts.isSuperCall = isSuperCall; + function isImportCall(n) { + return n.kind === 191 /* CallExpression */ && n.expression.kind === 92 /* ImportKeyword */; + } + ts.isImportCall = isImportCall; + function isLiteralImportTypeNode(n) { + return ts.isImportTypeNode(n) && ts.isLiteralTypeNode(n.argument) && ts.isStringLiteral(n.argument.literal); + } + ts.isLiteralImportTypeNode = isLiteralImportTypeNode; + function isPrologueDirective(node) { + return node.kind === 221 /* ExpressionStatement */ + && node.expression.kind === 10 /* StringLiteral */; + } + ts.isPrologueDirective = isPrologueDirective; + function getLeadingCommentRangesOfNode(node, sourceFileOfNode) { + return node.kind !== 11 /* JsxText */ ? ts.getLeadingCommentRanges(sourceFileOfNode.text, node.pos) : undefined; + } + ts.getLeadingCommentRangesOfNode = getLeadingCommentRangesOfNode; + function getJSDocCommentRanges(node, text) { + var commentRanges = (node.kind === 151 /* Parameter */ || + node.kind === 150 /* TypeParameter */ || + node.kind === 196 /* FunctionExpression */ || + node.kind === 197 /* ArrowFunction */ || + node.kind === 195 /* ParenthesizedExpression */) ? + ts.concatenate(ts.getTrailingCommentRanges(text, node.pos), ts.getLeadingCommentRanges(text, node.pos)) : + ts.getLeadingCommentRanges(text, node.pos); + // True if the comment starts with '/**' but not if it is '/**/' + return ts.filter(commentRanges, function (comment) { + return text.charCodeAt(comment.pos + 1) === 42 /* asterisk */ && + text.charCodeAt(comment.pos + 2) === 42 /* asterisk */ && + text.charCodeAt(comment.pos + 3) !== 47 /* slash */; + }); + } + ts.getJSDocCommentRanges = getJSDocCommentRanges; + ts.fullTripleSlashReferencePathRegEx = /^(\/\/\/\s*/; + var fullTripleSlashReferenceTypeReferenceDirectiveRegEx = /^(\/\/\/\s*/; + ts.fullTripleSlashAMDReferencePathRegEx = /^(\/\/\/\s*/; + var defaultLibReferenceRegEx = /^(\/\/\/\s*/; + function isPartOfTypeNode(node) { + if (163 /* FirstTypeNode */ <= node.kind && node.kind <= 183 /* LastTypeNode */) { + return true; + } + switch (node.kind) { + case 120 /* AnyKeyword */: + case 143 /* UnknownKeyword */: + case 135 /* NumberKeyword */: + case 146 /* BigIntKeyword */: + case 138 /* StringKeyword */: + case 123 /* BooleanKeyword */: + case 139 /* SymbolKeyword */: + case 136 /* ObjectKeyword */: + case 141 /* UndefinedKeyword */: + case 132 /* NeverKeyword */: + return true; + case 106 /* VoidKeyword */: + return node.parent.kind !== 200 /* VoidExpression */; + case 211 /* ExpressionWithTypeArguments */: + return !isExpressionWithTypeArgumentsInClassExtendsClause(node); + case 150 /* TypeParameter */: + return node.parent.kind === 181 /* MappedType */ || node.parent.kind === 176 /* InferType */; + // Identifiers and qualified names may be type nodes, depending on their context. Climb + // above them to find the lowest container + case 72 /* Identifier */: + // If the identifier is the RHS of a qualified name, then it's a type iff its parent is. + if (node.parent.kind === 148 /* QualifiedName */ && node.parent.right === node) { + node = node.parent; + } + else if (node.parent.kind === 189 /* PropertyAccessExpression */ && node.parent.name === node) { + node = node.parent; + } + // At this point, node is either a qualified name or an identifier + ts.Debug.assert(node.kind === 72 /* Identifier */ || node.kind === 148 /* QualifiedName */ || node.kind === 189 /* PropertyAccessExpression */, "'node' was expected to be a qualified name, identifier or property access in 'isPartOfTypeNode'."); + // falls through + case 148 /* QualifiedName */: + case 189 /* PropertyAccessExpression */: + case 100 /* ThisKeyword */: { + var parent = node.parent; + if (parent.kind === 167 /* TypeQuery */) { + return false; + } + if (parent.kind === 183 /* ImportType */) { + return !parent.isTypeOf; + } + // Do not recursively call isPartOfTypeNode on the parent. In the example: + // + // let a: A.B.C; + // + // Calling isPartOfTypeNode would consider the qualified name A.B a type node. + // Only C and A.B.C are type nodes. + if (163 /* FirstTypeNode */ <= parent.kind && parent.kind <= 183 /* LastTypeNode */) { + return true; + } + switch (parent.kind) { + case 211 /* ExpressionWithTypeArguments */: + return !isExpressionWithTypeArgumentsInClassExtendsClause(parent); + case 150 /* TypeParameter */: + return node === parent.constraint; + case 303 /* JSDocTemplateTag */: + return node === parent.constraint; + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 151 /* Parameter */: + case 237 /* VariableDeclaration */: + return node === parent.type; + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 157 /* Constructor */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + return node === parent.type; + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 162 /* IndexSignature */: + return node === parent.type; + case 194 /* TypeAssertionExpression */: + return node === parent.type; + case 191 /* CallExpression */: + case 192 /* NewExpression */: + return ts.contains(parent.typeArguments, node); + case 193 /* TaggedTemplateExpression */: + // TODO (drosen): TaggedTemplateExpressions may eventually support type arguments. + return false; + } + } + } + return false; + } + ts.isPartOfTypeNode = isPartOfTypeNode; + function isChildOfNodeWithKind(node, kind) { + while (node) { + if (node.kind === kind) { + return true; + } + node = node.parent; + } + return false; + } + ts.isChildOfNodeWithKind = isChildOfNodeWithKind; + // Warning: This has the same semantics as the forEach family of functions, + // in that traversal terminates in the event that 'visitor' supplies a truthy value. + function forEachReturnStatement(body, visitor) { + return traverse(body); + function traverse(node) { + switch (node.kind) { + case 230 /* ReturnStatement */: + return visitor(node); + case 246 /* CaseBlock */: + case 218 /* Block */: + case 222 /* IfStatement */: + case 223 /* DoStatement */: + case 224 /* WhileStatement */: + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + case 231 /* WithStatement */: + case 232 /* SwitchStatement */: + case 271 /* CaseClause */: + case 272 /* DefaultClause */: + case 233 /* LabeledStatement */: + case 235 /* TryStatement */: + case 274 /* CatchClause */: + return ts.forEachChild(node, traverse); + } + } + } + ts.forEachReturnStatement = forEachReturnStatement; + function forEachYieldExpression(body, visitor) { + return traverse(body); + function traverse(node) { + switch (node.kind) { + case 207 /* YieldExpression */: + visitor(node); + var operand = node.expression; + if (operand) { + traverse(operand); + } + return; + case 243 /* EnumDeclaration */: + case 241 /* InterfaceDeclaration */: + case 244 /* ModuleDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + // These are not allowed inside a generator now, but eventually they may be allowed + // as local types. Regardless, any yield statements contained within them should be + // skipped in this traversal. + return; + default: + if (ts.isFunctionLike(node)) { + if (node.name && node.name.kind === 149 /* ComputedPropertyName */) { + // Note that we will not include methods/accessors of a class because they would require + // first descending into the class. This is by design. + traverse(node.name.expression); + return; + } + } + else if (!isPartOfTypeNode(node)) { + // This is the general case, which should include mostly expressions and statements. + // Also includes NodeArrays. + ts.forEachChild(node, traverse); + } + } + } + } + ts.forEachYieldExpression = forEachYieldExpression; + /** + * Gets the most likely element type for a TypeNode. This is not an exhaustive test + * as it assumes a rest argument can only be an array type (either T[], or Array). + * + * @param node The type node. + */ + function getRestParameterElementType(node) { + if (node && node.kind === 169 /* ArrayType */) { + return node.elementType; + } + else if (node && node.kind === 164 /* TypeReference */) { + return ts.singleOrUndefined(node.typeArguments); + } + else { + return undefined; + } + } + ts.getRestParameterElementType = getRestParameterElementType; + function getMembersOfDeclaration(node) { + switch (node.kind) { + case 241 /* InterfaceDeclaration */: + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 168 /* TypeLiteral */: + return node.members; + case 188 /* ObjectLiteralExpression */: + return node.properties; + } + } + ts.getMembersOfDeclaration = getMembersOfDeclaration; + function isVariableLike(node) { + if (node) { + switch (node.kind) { + case 186 /* BindingElement */: + case 278 /* EnumMember */: + case 151 /* Parameter */: + case 275 /* PropertyAssignment */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 276 /* ShorthandPropertyAssignment */: + case 237 /* VariableDeclaration */: + return true; + } + } + return false; + } + ts.isVariableLike = isVariableLike; + function isVariableLikeOrAccessor(node) { + return isVariableLike(node) || ts.isAccessor(node); + } + ts.isVariableLikeOrAccessor = isVariableLikeOrAccessor; + function isVariableDeclarationInVariableStatement(node) { + return node.parent.kind === 238 /* VariableDeclarationList */ + && node.parent.parent.kind === 219 /* VariableStatement */; + } + ts.isVariableDeclarationInVariableStatement = isVariableDeclarationInVariableStatement; + function isValidESSymbolDeclaration(node) { + return ts.isVariableDeclaration(node) ? isVarConst(node) && ts.isIdentifier(node.name) && isVariableDeclarationInVariableStatement(node) : + ts.isPropertyDeclaration(node) ? hasReadonlyModifier(node) && hasStaticModifier(node) : + ts.isPropertySignature(node) && hasReadonlyModifier(node); + } + ts.isValidESSymbolDeclaration = isValidESSymbolDeclaration; + function introducesArgumentsExoticObject(node) { + switch (node.kind) { + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + return true; + } + return false; + } + ts.introducesArgumentsExoticObject = introducesArgumentsExoticObject; + function unwrapInnermostStatementOfLabel(node, beforeUnwrapLabelCallback) { + while (true) { + if (beforeUnwrapLabelCallback) { + beforeUnwrapLabelCallback(node); + } + if (node.statement.kind !== 233 /* LabeledStatement */) { + return node.statement; + } + node = node.statement; + } + } + ts.unwrapInnermostStatementOfLabel = unwrapInnermostStatementOfLabel; + function isFunctionBlock(node) { + return node && node.kind === 218 /* Block */ && ts.isFunctionLike(node.parent); + } + ts.isFunctionBlock = isFunctionBlock; + function isObjectLiteralMethod(node) { + return node && node.kind === 156 /* MethodDeclaration */ && node.parent.kind === 188 /* ObjectLiteralExpression */; + } + ts.isObjectLiteralMethod = isObjectLiteralMethod; + function isObjectLiteralOrClassExpressionMethod(node) { + return node.kind === 156 /* MethodDeclaration */ && + (node.parent.kind === 188 /* ObjectLiteralExpression */ || + node.parent.kind === 209 /* ClassExpression */); + } + ts.isObjectLiteralOrClassExpressionMethod = isObjectLiteralOrClassExpressionMethod; + function isIdentifierTypePredicate(predicate) { + return predicate && predicate.kind === 1 /* Identifier */; + } + ts.isIdentifierTypePredicate = isIdentifierTypePredicate; + function isThisTypePredicate(predicate) { + return predicate && predicate.kind === 0 /* This */; + } + ts.isThisTypePredicate = isThisTypePredicate; + function getPropertyAssignment(objectLiteral, key, key2) { + return objectLiteral.properties.filter(function (property) { + if (property.kind === 275 /* PropertyAssignment */) { + var propName = getTextOfPropertyName(property.name); + return key === propName || (!!key2 && key2 === propName); + } + return false; + }); + } + ts.getPropertyAssignment = getPropertyAssignment; + function getTsConfigObjectLiteralExpression(tsConfigSourceFile) { + if (tsConfigSourceFile && tsConfigSourceFile.statements.length) { + var expression = tsConfigSourceFile.statements[0].expression; + return ts.tryCast(expression, ts.isObjectLiteralExpression); + } + } + ts.getTsConfigObjectLiteralExpression = getTsConfigObjectLiteralExpression; + function getTsConfigPropArrayElementValue(tsConfigSourceFile, propKey, elementValue) { + return ts.firstDefined(getTsConfigPropArray(tsConfigSourceFile, propKey), function (property) { + return ts.isArrayLiteralExpression(property.initializer) ? + ts.find(property.initializer.elements, function (element) { return ts.isStringLiteral(element) && element.text === elementValue; }) : + undefined; + }); + } + ts.getTsConfigPropArrayElementValue = getTsConfigPropArrayElementValue; + function getTsConfigPropArray(tsConfigSourceFile, propKey) { + var jsonObjectLiteral = getTsConfigObjectLiteralExpression(tsConfigSourceFile); + return jsonObjectLiteral ? getPropertyAssignment(jsonObjectLiteral, propKey) : ts.emptyArray; + } + ts.getTsConfigPropArray = getTsConfigPropArray; + function getContainingFunction(node) { + return findAncestor(node.parent, ts.isFunctionLike); + } + ts.getContainingFunction = getContainingFunction; + function getContainingClass(node) { + return findAncestor(node.parent, ts.isClassLike); + } + ts.getContainingClass = getContainingClass; + function getThisContainer(node, includeArrowFunctions) { + ts.Debug.assert(node.kind !== 279 /* SourceFile */); + while (true) { + node = node.parent; + if (!node) { + return ts.Debug.fail(); // If we never pass in a SourceFile, this should be unreachable, since we'll stop when we reach that. + } + switch (node.kind) { + case 149 /* ComputedPropertyName */: + // If the grandparent node is an object literal (as opposed to a class), + // then the computed property is not a 'this' container. + // A computed property name in a class needs to be a this container + // so that we can error on it. + if (ts.isClassLike(node.parent.parent)) { + return node; + } + // If this is a computed property, then the parent should not + // make it a this container. The parent might be a property + // in an object literal, like a method or accessor. But in order for + // such a parent to be a this container, the reference must be in + // the *body* of the container. + node = node.parent; + break; + case 152 /* Decorator */: + // Decorators are always applied outside of the body of a class or method. + if (node.parent.kind === 151 /* Parameter */ && ts.isClassElement(node.parent.parent)) { + // If the decorator's parent is a Parameter, we resolve the this container from + // the grandparent class declaration. + node = node.parent.parent; + } + else if (ts.isClassElement(node.parent)) { + // If the decorator's parent is a class element, we resolve the 'this' container + // from the parent class declaration. + node = node.parent; + } + break; + case 197 /* ArrowFunction */: + if (!includeArrowFunctions) { + continue; + } + // falls through + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 244 /* ModuleDeclaration */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 162 /* IndexSignature */: + case 243 /* EnumDeclaration */: + case 279 /* SourceFile */: + return node; + } + } + } + ts.getThisContainer = getThisContainer; + function getNewTargetContainer(node) { + var container = getThisContainer(node, /*includeArrowFunctions*/ false); + if (container) { + switch (container.kind) { + case 157 /* Constructor */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + return container; + } + } + return undefined; + } + ts.getNewTargetContainer = getNewTargetContainer; + /** + * Given an super call/property node, returns the closest node where + * - a super call/property access is legal in the node and not legal in the parent node the node. + * i.e. super call is legal in constructor but not legal in the class body. + * - the container is an arrow function (so caller might need to call getSuperContainer again in case it needs to climb higher) + * - a super call/property is definitely illegal in the container (but might be legal in some subnode) + * i.e. super property access is illegal in function declaration but can be legal in the statement list + */ + function getSuperContainer(node, stopOnFunctions) { + while (true) { + node = node.parent; + if (!node) { + return node; + } + switch (node.kind) { + case 149 /* ComputedPropertyName */: + node = node.parent; + break; + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + if (!stopOnFunctions) { + continue; + } + // falls through + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + return node; + case 152 /* Decorator */: + // Decorators are always applied outside of the body of a class or method. + if (node.parent.kind === 151 /* Parameter */ && ts.isClassElement(node.parent.parent)) { + // If the decorator's parent is a Parameter, we resolve the this container from + // the grandparent class declaration. + node = node.parent.parent; + } + else if (ts.isClassElement(node.parent)) { + // If the decorator's parent is a class element, we resolve the 'this' container + // from the parent class declaration. + node = node.parent; + } + break; + } + } + } + ts.getSuperContainer = getSuperContainer; + function getImmediatelyInvokedFunctionExpression(func) { + if (func.kind === 196 /* FunctionExpression */ || func.kind === 197 /* ArrowFunction */) { + var prev = func; + var parent = func.parent; + while (parent.kind === 195 /* ParenthesizedExpression */) { + prev = parent; + parent = parent.parent; + } + if (parent.kind === 191 /* CallExpression */ && parent.expression === prev) { + return parent; + } + } + } + ts.getImmediatelyInvokedFunctionExpression = getImmediatelyInvokedFunctionExpression; + /** + * Determines whether a node is a property or element access expression for `super`. + */ + function isSuperProperty(node) { + var kind = node.kind; + return (kind === 189 /* PropertyAccessExpression */ || kind === 190 /* ElementAccessExpression */) + && node.expression.kind === 98 /* SuperKeyword */; + } + ts.isSuperProperty = isSuperProperty; + /** + * Determines whether a node is a property or element access expression for `this`. + */ + function isThisProperty(node) { + var kind = node.kind; + return (kind === 189 /* PropertyAccessExpression */ || kind === 190 /* ElementAccessExpression */) + && node.expression.kind === 100 /* ThisKeyword */; + } + ts.isThisProperty = isThisProperty; + function getEntityNameFromTypeNode(node) { + switch (node.kind) { + case 164 /* TypeReference */: + return node.typeName; + case 211 /* ExpressionWithTypeArguments */: + return isEntityNameExpression(node.expression) + ? node.expression + : undefined; + case 72 /* Identifier */: + case 148 /* QualifiedName */: + return node; + } + return undefined; + } + ts.getEntityNameFromTypeNode = getEntityNameFromTypeNode; + function getInvokedExpression(node) { + switch (node.kind) { + case 193 /* TaggedTemplateExpression */: + return node.tag; + case 262 /* JsxOpeningElement */: + case 261 /* JsxSelfClosingElement */: + return node.tagName; + default: + return node.expression; + } + } + ts.getInvokedExpression = getInvokedExpression; + function nodeCanBeDecorated(node, parent, grandparent) { + switch (node.kind) { + case 240 /* ClassDeclaration */: + // classes are valid targets + return true; + case 154 /* PropertyDeclaration */: + // property declarations are valid if their parent is a class declaration. + return parent.kind === 240 /* ClassDeclaration */; + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 156 /* MethodDeclaration */: + // if this method has a body and its parent is a class declaration, this is a valid target. + return node.body !== undefined + && parent.kind === 240 /* ClassDeclaration */; + case 151 /* Parameter */: + // if the parameter's parent has a body and its grandparent is a class declaration, this is a valid target; + return parent.body !== undefined + && (parent.kind === 157 /* Constructor */ + || parent.kind === 156 /* MethodDeclaration */ + || parent.kind === 159 /* SetAccessor */) + && grandparent.kind === 240 /* ClassDeclaration */; + } + return false; + } + ts.nodeCanBeDecorated = nodeCanBeDecorated; + function nodeIsDecorated(node, parent, grandparent) { + return node.decorators !== undefined + && nodeCanBeDecorated(node, parent, grandparent); // TODO: GH#18217 + } + ts.nodeIsDecorated = nodeIsDecorated; + function nodeOrChildIsDecorated(node, parent, grandparent) { + return nodeIsDecorated(node, parent, grandparent) || childIsDecorated(node, parent); // TODO: GH#18217 + } + ts.nodeOrChildIsDecorated = nodeOrChildIsDecorated; + function childIsDecorated(node, parent) { + switch (node.kind) { + case 240 /* ClassDeclaration */: + return ts.some(node.members, function (m) { return nodeOrChildIsDecorated(m, node, parent); }); // TODO: GH#18217 + case 156 /* MethodDeclaration */: + case 159 /* SetAccessor */: + return ts.some(node.parameters, function (p) { return nodeIsDecorated(p, node, parent); }); // TODO: GH#18217 + default: + return false; + } + } + ts.childIsDecorated = childIsDecorated; + function isJSXTagName(node) { + var parent = node.parent; + if (parent.kind === 262 /* JsxOpeningElement */ || + parent.kind === 261 /* JsxSelfClosingElement */ || + parent.kind === 263 /* JsxClosingElement */) { + return parent.tagName === node; + } + return false; + } + ts.isJSXTagName = isJSXTagName; + function isExpressionNode(node) { + switch (node.kind) { + case 98 /* SuperKeyword */: + case 96 /* NullKeyword */: + case 102 /* TrueKeyword */: + case 87 /* FalseKeyword */: + case 13 /* RegularExpressionLiteral */: + case 187 /* ArrayLiteralExpression */: + case 188 /* ObjectLiteralExpression */: + case 189 /* PropertyAccessExpression */: + case 190 /* ElementAccessExpression */: + case 191 /* CallExpression */: + case 192 /* NewExpression */: + case 193 /* TaggedTemplateExpression */: + case 212 /* AsExpression */: + case 194 /* TypeAssertionExpression */: + case 213 /* NonNullExpression */: + case 195 /* ParenthesizedExpression */: + case 196 /* FunctionExpression */: + case 209 /* ClassExpression */: + case 197 /* ArrowFunction */: + case 200 /* VoidExpression */: + case 198 /* DeleteExpression */: + case 199 /* TypeOfExpression */: + case 202 /* PrefixUnaryExpression */: + case 203 /* PostfixUnaryExpression */: + case 204 /* BinaryExpression */: + case 205 /* ConditionalExpression */: + case 208 /* SpreadElement */: + case 206 /* TemplateExpression */: + case 14 /* NoSubstitutionTemplateLiteral */: + case 210 /* OmittedExpression */: + case 260 /* JsxElement */: + case 261 /* JsxSelfClosingElement */: + case 264 /* JsxFragment */: + case 207 /* YieldExpression */: + case 201 /* AwaitExpression */: + case 214 /* MetaProperty */: + return true; + case 148 /* QualifiedName */: + while (node.parent.kind === 148 /* QualifiedName */) { + node = node.parent; + } + return node.parent.kind === 167 /* TypeQuery */ || isJSXTagName(node); + case 72 /* Identifier */: + if (node.parent.kind === 167 /* TypeQuery */ || isJSXTagName(node)) { + return true; + } + // falls through + case 8 /* NumericLiteral */: + case 9 /* BigIntLiteral */: + case 10 /* StringLiteral */: + case 100 /* ThisKeyword */: + return isInExpressionContext(node); + default: + return false; + } + } + ts.isExpressionNode = isExpressionNode; + function isInExpressionContext(node) { + var parent = node.parent; + switch (parent.kind) { + case 237 /* VariableDeclaration */: + case 151 /* Parameter */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 278 /* EnumMember */: + case 275 /* PropertyAssignment */: + case 186 /* BindingElement */: + return parent.initializer === node; + case 221 /* ExpressionStatement */: + case 222 /* IfStatement */: + case 223 /* DoStatement */: + case 224 /* WhileStatement */: + case 230 /* ReturnStatement */: + case 231 /* WithStatement */: + case 232 /* SwitchStatement */: + case 271 /* CaseClause */: + case 234 /* ThrowStatement */: + return parent.expression === node; + case 225 /* ForStatement */: + var forStatement = parent; + return (forStatement.initializer === node && forStatement.initializer.kind !== 238 /* VariableDeclarationList */) || + forStatement.condition === node || + forStatement.incrementor === node; + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + var forInStatement = parent; + return (forInStatement.initializer === node && forInStatement.initializer.kind !== 238 /* VariableDeclarationList */) || + forInStatement.expression === node; + case 194 /* TypeAssertionExpression */: + case 212 /* AsExpression */: + return node === parent.expression; + case 216 /* TemplateSpan */: + return node === parent.expression; + case 149 /* ComputedPropertyName */: + return node === parent.expression; + case 152 /* Decorator */: + case 270 /* JsxExpression */: + case 269 /* JsxSpreadAttribute */: + case 277 /* SpreadAssignment */: + return true; + case 211 /* ExpressionWithTypeArguments */: + return parent.expression === node && isExpressionWithTypeArgumentsInClassExtendsClause(parent); + case 276 /* ShorthandPropertyAssignment */: + return parent.objectAssignmentInitializer === node; + default: + return isExpressionNode(parent); + } + } + ts.isInExpressionContext = isInExpressionContext; + function isExternalModuleImportEqualsDeclaration(node) { + return node.kind === 248 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 259 /* ExternalModuleReference */; + } + ts.isExternalModuleImportEqualsDeclaration = isExternalModuleImportEqualsDeclaration; + function getExternalModuleImportEqualsDeclarationExpression(node) { + ts.Debug.assert(isExternalModuleImportEqualsDeclaration(node)); + return node.moduleReference.expression; + } + ts.getExternalModuleImportEqualsDeclarationExpression = getExternalModuleImportEqualsDeclarationExpression; + function isInternalModuleImportEqualsDeclaration(node) { + return node.kind === 248 /* ImportEqualsDeclaration */ && node.moduleReference.kind !== 259 /* ExternalModuleReference */; + } + ts.isInternalModuleImportEqualsDeclaration = isInternalModuleImportEqualsDeclaration; + function isSourceFileJS(file) { + return isInJSFile(file); + } + ts.isSourceFileJS = isSourceFileJS; + function isSourceFileNotJS(file) { + return !isInJSFile(file); + } + ts.isSourceFileNotJS = isSourceFileNotJS; + function isInJSFile(node) { + return !!node && !!(node.flags & 65536 /* JavaScriptFile */); + } + ts.isInJSFile = isInJSFile; + function isInJsonFile(node) { + return !!node && !!(node.flags & 16777216 /* JsonFile */); + } + ts.isInJsonFile = isInJsonFile; + function isInJSDoc(node) { + return !!node && !!(node.flags & 2097152 /* JSDoc */); + } + ts.isInJSDoc = isInJSDoc; + function isJSDocIndexSignature(node) { + return ts.isTypeReferenceNode(node) && + ts.isIdentifier(node.typeName) && + node.typeName.escapedText === "Object" && + node.typeArguments && node.typeArguments.length === 2 && + (node.typeArguments[0].kind === 138 /* StringKeyword */ || node.typeArguments[0].kind === 135 /* NumberKeyword */); + } + ts.isJSDocIndexSignature = isJSDocIndexSignature; + function isRequireCall(callExpression, checkArgumentIsStringLiteralLike) { + if (callExpression.kind !== 191 /* CallExpression */) { + return false; + } + var _a = callExpression, expression = _a.expression, args = _a.arguments; + if (expression.kind !== 72 /* Identifier */ || expression.escapedText !== "require") { + return false; + } + if (args.length !== 1) { + return false; + } + var arg = args[0]; + return !checkArgumentIsStringLiteralLike || ts.isStringLiteralLike(arg); + } + ts.isRequireCall = isRequireCall; + function isSingleOrDoubleQuote(charCode) { + return charCode === 39 /* singleQuote */ || charCode === 34 /* doubleQuote */; + } + ts.isSingleOrDoubleQuote = isSingleOrDoubleQuote; + function isStringDoubleQuoted(str, sourceFile) { + return getSourceTextOfNodeFromSourceFile(sourceFile, str).charCodeAt(0) === 34 /* doubleQuote */; + } + ts.isStringDoubleQuoted = isStringDoubleQuoted; + function getDeclarationOfExpando(node) { + if (!node.parent) { + return undefined; + } + var name; + var decl; + if (ts.isVariableDeclaration(node.parent) && node.parent.initializer === node) { + if (!isInJSFile(node) && !isVarConst(node.parent)) { + return undefined; + } + name = node.parent.name; + decl = node.parent; + } + else if (ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 59 /* EqualsToken */ && node.parent.right === node) { + name = node.parent.left; + decl = name; + } + else if (ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 55 /* BarBarToken */) { + if (ts.isVariableDeclaration(node.parent.parent) && node.parent.parent.initializer === node.parent) { + name = node.parent.parent.name; + decl = node.parent.parent; + } + else if (ts.isBinaryExpression(node.parent.parent) && node.parent.parent.operatorToken.kind === 59 /* EqualsToken */ && node.parent.parent.right === node.parent) { + name = node.parent.parent.left; + decl = name; + } + if (!name || !isEntityNameExpression(name) || !isSameEntityName(name, node.parent.left)) { + return undefined; + } + } + if (!name || !getExpandoInitializer(node, isPrototypeAccess(name))) { + return undefined; + } + return decl; + } + ts.getDeclarationOfExpando = getDeclarationOfExpando; + function isAssignmentDeclaration(decl) { + return ts.isBinaryExpression(decl) || ts.isPropertyAccessExpression(decl) || ts.isIdentifier(decl) || ts.isCallExpression(decl); + } + ts.isAssignmentDeclaration = isAssignmentDeclaration; + /** Get the initializer, taking into account defaulted Javascript initializers */ + function getEffectiveInitializer(node) { + if (isInJSFile(node) && node.initializer && + ts.isBinaryExpression(node.initializer) && node.initializer.operatorToken.kind === 55 /* BarBarToken */ && + node.name && isEntityNameExpression(node.name) && isSameEntityName(node.name, node.initializer.left)) { + return node.initializer.right; + } + return node.initializer; + } + ts.getEffectiveInitializer = getEffectiveInitializer; + /** Get the declaration initializer when it is container-like (See getExpandoInitializer). */ + function getDeclaredExpandoInitializer(node) { + var init = getEffectiveInitializer(node); + return init && getExpandoInitializer(init, isPrototypeAccess(node.name)); + } + ts.getDeclaredExpandoInitializer = getDeclaredExpandoInitializer; + function hasExpandoValueProperty(node, isPrototypeAssignment) { + return ts.forEach(node.properties, function (p) { return ts.isPropertyAssignment(p) && ts.isIdentifier(p.name) && p.name.escapedText === "value" && p.initializer && getExpandoInitializer(p.initializer, isPrototypeAssignment); }); + } + /** + * Get the assignment 'initializer' -- the righthand side-- when the initializer is container-like (See getExpandoInitializer). + * We treat the right hand side of assignments with container-like initalizers as declarations. + */ + function getAssignedExpandoInitializer(node) { + if (node && node.parent && ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 59 /* EqualsToken */) { + var isPrototypeAssignment = isPrototypeAccess(node.parent.left); + return getExpandoInitializer(node.parent.right, isPrototypeAssignment) || + getDefaultedExpandoInitializer(node.parent.left, node.parent.right, isPrototypeAssignment); + } + if (node && ts.isCallExpression(node) && isBindableObjectDefinePropertyCall(node)) { + var result = hasExpandoValueProperty(node.arguments[2], node.arguments[1].text === "prototype"); + if (result) { + return result; + } + } + } + ts.getAssignedExpandoInitializer = getAssignedExpandoInitializer; + /** + * Recognized expando initializers are: + * 1. (function() {})() -- IIFEs + * 2. function() { } -- Function expressions + * 3. class { } -- Class expressions + * 4. {} -- Empty object literals + * 5. { ... } -- Non-empty object literals, when used to initialize a prototype, like `C.prototype = { m() { } }` + * + * This function returns the provided initializer, or undefined if it is not valid. + */ + function getExpandoInitializer(initializer, isPrototypeAssignment) { + if (ts.isCallExpression(initializer)) { + var e = skipParentheses(initializer.expression); + return e.kind === 196 /* FunctionExpression */ || e.kind === 197 /* ArrowFunction */ ? initializer : undefined; + } + if (initializer.kind === 196 /* FunctionExpression */ || + initializer.kind === 209 /* ClassExpression */ || + initializer.kind === 197 /* ArrowFunction */) { + return initializer; + } + if (ts.isObjectLiteralExpression(initializer) && (initializer.properties.length === 0 || isPrototypeAssignment)) { + return initializer; + } + } + ts.getExpandoInitializer = getExpandoInitializer; + /** + * A defaulted expando initializer matches the pattern + * `Lhs = Lhs || ExpandoInitializer` + * or `var Lhs = Lhs || ExpandoInitializer` + * + * The second Lhs is required to be the same as the first except that it may be prefixed with + * 'window.', 'global.' or 'self.' The second Lhs is otherwise ignored by the binder and checker. + */ + function getDefaultedExpandoInitializer(name, initializer, isPrototypeAssignment) { + var e = ts.isBinaryExpression(initializer) && initializer.operatorToken.kind === 55 /* BarBarToken */ && getExpandoInitializer(initializer.right, isPrototypeAssignment); + if (e && isSameEntityName(name, initializer.left)) { + return e; + } + } + function isDefaultedExpandoInitializer(node) { + var name = ts.isVariableDeclaration(node.parent) ? node.parent.name : + ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 59 /* EqualsToken */ ? node.parent.left : + undefined; + return name && getExpandoInitializer(node.right, isPrototypeAccess(name)) && isEntityNameExpression(name) && isSameEntityName(name, node.left); + } + ts.isDefaultedExpandoInitializer = isDefaultedExpandoInitializer; + /** Given an expando initializer, return its declaration name, or the left-hand side of the assignment if it's part of an assignment declaration. */ + function getNameOfExpando(node) { + if (ts.isBinaryExpression(node.parent)) { + var parent = (node.parent.operatorToken.kind === 55 /* BarBarToken */ && ts.isBinaryExpression(node.parent.parent)) ? node.parent.parent : node.parent; + if (parent.operatorToken.kind === 59 /* EqualsToken */ && ts.isIdentifier(parent.left)) { + return parent.left; + } + } + else if (ts.isVariableDeclaration(node.parent)) { + return node.parent.name; + } + } + ts.getNameOfExpando = getNameOfExpando; + /** + * Is the 'declared' name the same as the one in the initializer? + * @return true for identical entity names, as well as ones where the initializer is prefixed with + * 'window', 'self' or 'global'. For example: + * + * var my = my || {} + * var min = window.min || {} + * my.app = self.my.app || class { } + */ + function isSameEntityName(name, initializer) { + if (ts.isIdentifier(name) && ts.isIdentifier(initializer)) { + return name.escapedText === initializer.escapedText; + } + if (ts.isIdentifier(name) && ts.isPropertyAccessExpression(initializer)) { + return (initializer.expression.kind === 100 /* ThisKeyword */ || + ts.isIdentifier(initializer.expression) && + (initializer.expression.escapedText === "window" || + initializer.expression.escapedText === "self" || + initializer.expression.escapedText === "global")) && + isSameEntityName(name, initializer.name); + } + if (ts.isPropertyAccessExpression(name) && ts.isPropertyAccessExpression(initializer)) { + return name.name.escapedText === initializer.name.escapedText && isSameEntityName(name.expression, initializer.expression); + } + return false; + } + function getRightMostAssignedExpression(node) { + while (isAssignmentExpression(node, /*excludeCompoundAssignments*/ true)) { + node = node.right; + } + return node; + } + ts.getRightMostAssignedExpression = getRightMostAssignedExpression; + function isExportsIdentifier(node) { + return ts.isIdentifier(node) && node.escapedText === "exports"; + } + ts.isExportsIdentifier = isExportsIdentifier; + function isModuleExportsPropertyAccessExpression(node) { + return ts.isPropertyAccessExpression(node) && ts.isIdentifier(node.expression) && node.expression.escapedText === "module" && node.name.escapedText === "exports"; + } + ts.isModuleExportsPropertyAccessExpression = isModuleExportsPropertyAccessExpression; + /// Given a BinaryExpression, returns SpecialPropertyAssignmentKind for the various kinds of property + /// assignments we treat as special in the binder + function getAssignmentDeclarationKind(expr) { + var special = getAssignmentDeclarationKindWorker(expr); + return special === 5 /* Property */ || isInJSFile(expr) ? special : 0 /* None */; + } + ts.getAssignmentDeclarationKind = getAssignmentDeclarationKind; + function isBindableObjectDefinePropertyCall(expr) { + return ts.length(expr.arguments) === 3 && + ts.isPropertyAccessExpression(expr.expression) && + ts.isIdentifier(expr.expression.expression) && + ts.idText(expr.expression.expression) === "Object" && + ts.idText(expr.expression.name) === "defineProperty" && + isStringOrNumericLiteralLike(expr.arguments[1]) && + isEntityNameExpression(expr.arguments[0]); + } + ts.isBindableObjectDefinePropertyCall = isBindableObjectDefinePropertyCall; + function getAssignmentDeclarationKindWorker(expr) { + if (ts.isCallExpression(expr)) { + if (!isBindableObjectDefinePropertyCall(expr)) { + return 0 /* None */; + } + var entityName = expr.arguments[0]; + if (isExportsIdentifier(entityName) || isModuleExportsPropertyAccessExpression(entityName)) { + return 8 /* ObjectDefinePropertyExports */; + } + if (ts.isPropertyAccessExpression(entityName) && entityName.name.escapedText === "prototype" && isEntityNameExpression(entityName.expression)) { + return 9 /* ObjectDefinePrototypeProperty */; + } + return 7 /* ObjectDefinePropertyValue */; + } + if (expr.operatorToken.kind !== 59 /* EqualsToken */ || + !ts.isPropertyAccessExpression(expr.left)) { + return 0 /* None */; + } + var lhs = expr.left; + if (isEntityNameExpression(lhs.expression) && lhs.name.escapedText === "prototype" && ts.isObjectLiteralExpression(getInitializerOfBinaryExpression(expr))) { + // F.prototype = { ... } + return 6 /* Prototype */; + } + return getAssignmentDeclarationPropertyAccessKind(lhs); + } + function getAssignmentDeclarationPropertyAccessKind(lhs) { + if (lhs.expression.kind === 100 /* ThisKeyword */) { + return 4 /* ThisProperty */; + } + else if (isModuleExportsPropertyAccessExpression(lhs)) { + // module.exports = expr + return 2 /* ModuleExports */; + } + else if (isEntityNameExpression(lhs.expression)) { + if (isPrototypeAccess(lhs.expression)) { + // F.G....prototype.x = expr + return 3 /* PrototypeProperty */; + } + var nextToLast = lhs; + while (ts.isPropertyAccessExpression(nextToLast.expression)) { + nextToLast = nextToLast.expression; + } + ts.Debug.assert(ts.isIdentifier(nextToLast.expression)); + var id = nextToLast.expression; + if (id.escapedText === "exports" || + id.escapedText === "module" && nextToLast.name.escapedText === "exports") { + // exports.name = expr OR module.exports.name = expr + return 1 /* ExportsProperty */; + } + // F.G...x = expr + return 5 /* Property */; + } + return 0 /* None */; + } + ts.getAssignmentDeclarationPropertyAccessKind = getAssignmentDeclarationPropertyAccessKind; + function getInitializerOfBinaryExpression(expr) { + while (ts.isBinaryExpression(expr.right)) { + expr = expr.right; + } + return expr.right; + } + ts.getInitializerOfBinaryExpression = getInitializerOfBinaryExpression; + function isPrototypePropertyAssignment(node) { + return ts.isBinaryExpression(node) && getAssignmentDeclarationKind(node) === 3 /* PrototypeProperty */; + } + ts.isPrototypePropertyAssignment = isPrototypePropertyAssignment; + function isSpecialPropertyDeclaration(expr) { + return isInJSFile(expr) && + expr.parent && expr.parent.kind === 221 /* ExpressionStatement */ && + !!ts.getJSDocTypeTag(expr.parent); + } + ts.isSpecialPropertyDeclaration = isSpecialPropertyDeclaration; + function isFunctionSymbol(symbol) { + if (!symbol || !symbol.valueDeclaration) { + return false; + } + var decl = symbol.valueDeclaration; + return decl.kind === 239 /* FunctionDeclaration */ || ts.isVariableDeclaration(decl) && decl.initializer && ts.isFunctionLike(decl.initializer); + } + ts.isFunctionSymbol = isFunctionSymbol; + function importFromModuleSpecifier(node) { + return tryGetImportFromModuleSpecifier(node) || ts.Debug.fail(ts.Debug.showSyntaxKind(node.parent)); + } + ts.importFromModuleSpecifier = importFromModuleSpecifier; + function tryGetImportFromModuleSpecifier(node) { + switch (node.parent.kind) { + case 249 /* ImportDeclaration */: + case 255 /* ExportDeclaration */: + return node.parent; + case 259 /* ExternalModuleReference */: + return node.parent.parent; + case 191 /* CallExpression */: + return isImportCall(node.parent) || isRequireCall(node.parent, /*checkArg*/ false) ? node.parent : undefined; + case 182 /* LiteralType */: + ts.Debug.assert(ts.isStringLiteral(node)); + return ts.tryCast(node.parent.parent, ts.isImportTypeNode); + default: + return undefined; + } + } + ts.tryGetImportFromModuleSpecifier = tryGetImportFromModuleSpecifier; + function getExternalModuleName(node) { + switch (node.kind) { + case 249 /* ImportDeclaration */: + case 255 /* ExportDeclaration */: + return node.moduleSpecifier; + case 248 /* ImportEqualsDeclaration */: + return node.moduleReference.kind === 259 /* ExternalModuleReference */ ? node.moduleReference.expression : undefined; + case 183 /* ImportType */: + return isLiteralImportTypeNode(node) ? node.argument.literal : undefined; + default: + return ts.Debug.assertNever(node); + } + } + ts.getExternalModuleName = getExternalModuleName; + function getNamespaceDeclarationNode(node) { + switch (node.kind) { + case 249 /* ImportDeclaration */: + return node.importClause && ts.tryCast(node.importClause.namedBindings, ts.isNamespaceImport); + case 248 /* ImportEqualsDeclaration */: + return node; + case 255 /* ExportDeclaration */: + return undefined; + default: + return ts.Debug.assertNever(node); + } + } + ts.getNamespaceDeclarationNode = getNamespaceDeclarationNode; + function isDefaultImport(node) { + return node.kind === 249 /* ImportDeclaration */ && !!node.importClause && !!node.importClause.name; + } + ts.isDefaultImport = isDefaultImport; + function hasQuestionToken(node) { + if (node) { + switch (node.kind) { + case 151 /* Parameter */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 276 /* ShorthandPropertyAssignment */: + case 275 /* PropertyAssignment */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + return node.questionToken !== undefined; + } + } + return false; + } + ts.hasQuestionToken = hasQuestionToken; + function isJSDocConstructSignature(node) { + var param = ts.isJSDocFunctionType(node) ? ts.firstOrUndefined(node.parameters) : undefined; + var name = ts.tryCast(param && param.name, ts.isIdentifier); + return !!name && name.escapedText === "new"; + } + ts.isJSDocConstructSignature = isJSDocConstructSignature; + function isJSDocTypeAlias(node) { + return node.kind === 304 /* JSDocTypedefTag */ || node.kind === 297 /* JSDocCallbackTag */; + } + ts.isJSDocTypeAlias = isJSDocTypeAlias; + function isTypeAlias(node) { + return isJSDocTypeAlias(node) || ts.isTypeAliasDeclaration(node); + } + ts.isTypeAlias = isTypeAlias; + function getSourceOfAssignment(node) { + return ts.isExpressionStatement(node) && + node.expression && ts.isBinaryExpression(node.expression) && + node.expression.operatorToken.kind === 59 /* EqualsToken */ + ? node.expression.right + : undefined; + } + function getSourceOfDefaultedAssignment(node) { + return ts.isExpressionStatement(node) && + ts.isBinaryExpression(node.expression) && + getAssignmentDeclarationKind(node.expression) !== 0 /* None */ && + ts.isBinaryExpression(node.expression.right) && + node.expression.right.operatorToken.kind === 55 /* BarBarToken */ + ? node.expression.right.right + : undefined; + } + function getSingleInitializerOfVariableStatementOrPropertyDeclaration(node) { + switch (node.kind) { + case 219 /* VariableStatement */: + var v = getSingleVariableOfVariableStatement(node); + return v && v.initializer; + case 154 /* PropertyDeclaration */: + return node.initializer; + case 275 /* PropertyAssignment */: + return node.initializer; + } + } + function getSingleVariableOfVariableStatement(node) { + return ts.isVariableStatement(node) ? ts.firstOrUndefined(node.declarationList.declarations) : undefined; + } + function getNestedModuleDeclaration(node) { + return ts.isModuleDeclaration(node) && + node.body && + node.body.kind === 244 /* ModuleDeclaration */ + ? node.body + : undefined; + } + function getJSDocCommentsAndTags(hostNode) { + var result; + // Pull parameter comments from declaring function as well + if (isVariableLike(hostNode) && ts.hasInitializer(hostNode) && ts.hasJSDocNodes(hostNode.initializer)) { + result = ts.addRange(result, hostNode.initializer.jsDoc); + } + var node = hostNode; + while (node && node.parent) { + if (ts.hasJSDocNodes(node)) { + result = ts.addRange(result, node.jsDoc); + } + if (node.kind === 151 /* Parameter */) { + result = ts.addRange(result, ts.getJSDocParameterTags(node)); + break; + } + if (node.kind === 150 /* TypeParameter */) { + result = ts.addRange(result, ts.getJSDocTypeParameterTags(node)); + break; + } + node = getNextJSDocCommentLocation(node); + } + return result || ts.emptyArray; + } + ts.getJSDocCommentsAndTags = getJSDocCommentsAndTags; + function getNextJSDocCommentLocation(node) { + var parent = node.parent; + if (parent.kind === 275 /* PropertyAssignment */ || + parent.kind === 154 /* PropertyDeclaration */ || + parent.kind === 221 /* ExpressionStatement */ && node.kind === 189 /* PropertyAccessExpression */ || + getNestedModuleDeclaration(parent) || + ts.isBinaryExpression(node) && node.operatorToken.kind === 59 /* EqualsToken */) { + return parent; + } + // Try to recognize this pattern when node is initializer of variable declaration and JSDoc comments are on containing variable statement. + // /** + // * @param {number} name + // * @returns {number} + // */ + // var x = function(name) { return name.length; } + else if (parent.parent && + (getSingleVariableOfVariableStatement(parent.parent) === node || + ts.isBinaryExpression(parent) && parent.operatorToken.kind === 59 /* EqualsToken */)) { + return parent.parent; + } + else if (parent.parent && parent.parent.parent && + (getSingleVariableOfVariableStatement(parent.parent.parent) || + getSingleInitializerOfVariableStatementOrPropertyDeclaration(parent.parent.parent) === node || + getSourceOfDefaultedAssignment(parent.parent.parent))) { + return parent.parent.parent; + } + } + /** Does the opposite of `getJSDocParameterTags`: given a JSDoc parameter, finds the parameter corresponding to it. */ + function getParameterSymbolFromJSDoc(node) { + if (node.symbol) { + return node.symbol; + } + if (!ts.isIdentifier(node.name)) { + return undefined; + } + var name = node.name.escapedText; + var decl = getHostSignatureFromJSDoc(node); + if (!decl) { + return undefined; + } + var parameter = ts.find(decl.parameters, function (p) { return p.name.kind === 72 /* Identifier */ && p.name.escapedText === name; }); + return parameter && parameter.symbol; + } + ts.getParameterSymbolFromJSDoc = getParameterSymbolFromJSDoc; + function getHostSignatureFromJSDoc(node) { + return getHostSignatureFromJSDocHost(getJSDocHost(node)); + } + ts.getHostSignatureFromJSDoc = getHostSignatureFromJSDoc; + function getHostSignatureFromJSDocHost(host) { + var decl = getSourceOfDefaultedAssignment(host) || + getSourceOfAssignment(host) || + getSingleInitializerOfVariableStatementOrPropertyDeclaration(host) || + getSingleVariableOfVariableStatement(host) || + getNestedModuleDeclaration(host) || + host; + return decl && ts.isFunctionLike(decl) ? decl : undefined; + } + ts.getHostSignatureFromJSDocHost = getHostSignatureFromJSDocHost; + function getJSDocHost(node) { + return ts.Debug.assertDefined(findAncestor(node.parent, ts.isJSDoc)).parent; + } + ts.getJSDocHost = getJSDocHost; + function getTypeParameterFromJsDoc(node) { + var name = node.name.escapedText; + var typeParameters = node.parent.parent.parent.typeParameters; + return ts.find(typeParameters, function (p) { return p.name.escapedText === name; }); + } + ts.getTypeParameterFromJsDoc = getTypeParameterFromJsDoc; + function hasRestParameter(s) { + var last = ts.lastOrUndefined(s.parameters); + return !!last && isRestParameter(last); + } + ts.hasRestParameter = hasRestParameter; + function isRestParameter(node) { + var type = ts.isJSDocParameterTag(node) ? (node.typeExpression && node.typeExpression.type) : node.type; + return node.dotDotDotToken !== undefined || !!type && type.kind === 290 /* JSDocVariadicType */; + } + ts.isRestParameter = isRestParameter; + var AssignmentKind; + (function (AssignmentKind) { + AssignmentKind[AssignmentKind["None"] = 0] = "None"; + AssignmentKind[AssignmentKind["Definite"] = 1] = "Definite"; + AssignmentKind[AssignmentKind["Compound"] = 2] = "Compound"; + })(AssignmentKind = ts.AssignmentKind || (ts.AssignmentKind = {})); + function getAssignmentTargetKind(node) { + var parent = node.parent; + while (true) { + switch (parent.kind) { + case 204 /* BinaryExpression */: + var binaryOperator = parent.operatorToken.kind; + return isAssignmentOperator(binaryOperator) && parent.left === node ? + binaryOperator === 59 /* EqualsToken */ ? 1 /* Definite */ : 2 /* Compound */ : + 0 /* None */; + case 202 /* PrefixUnaryExpression */: + case 203 /* PostfixUnaryExpression */: + var unaryOperator = parent.operator; + return unaryOperator === 44 /* PlusPlusToken */ || unaryOperator === 45 /* MinusMinusToken */ ? 2 /* Compound */ : 0 /* None */; + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + return parent.initializer === node ? 1 /* Definite */ : 0 /* None */; + case 195 /* ParenthesizedExpression */: + case 187 /* ArrayLiteralExpression */: + case 208 /* SpreadElement */: + case 213 /* NonNullExpression */: + node = parent; + break; + case 276 /* ShorthandPropertyAssignment */: + if (parent.name !== node) { + return 0 /* None */; + } + node = parent.parent; + break; + case 275 /* PropertyAssignment */: + if (parent.name === node) { + return 0 /* None */; + } + node = parent.parent; + break; + default: + return 0 /* None */; + } + parent = node.parent; + } + } + ts.getAssignmentTargetKind = getAssignmentTargetKind; + // A node is an assignment target if it is on the left hand side of an '=' token, if it is parented by a property + // assignment in an object literal that is an assignment target, or if it is parented by an array literal that is + // an assignment target. Examples include 'a = xxx', '{ p: a } = xxx', '[{ a }] = xxx'. + // (Note that `p` is not a target in the above examples, only `a`.) + function isAssignmentTarget(node) { + return getAssignmentTargetKind(node) !== 0 /* None */; + } + ts.isAssignmentTarget = isAssignmentTarget; + /** + * Indicates whether a node could contain a `var` VariableDeclarationList that contributes to + * the same `var` declaration scope as the node's parent. + */ + function isNodeWithPossibleHoistedDeclaration(node) { + switch (node.kind) { + case 218 /* Block */: + case 219 /* VariableStatement */: + case 231 /* WithStatement */: + case 222 /* IfStatement */: + case 232 /* SwitchStatement */: + case 246 /* CaseBlock */: + case 271 /* CaseClause */: + case 272 /* DefaultClause */: + case 233 /* LabeledStatement */: + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + case 223 /* DoStatement */: + case 224 /* WhileStatement */: + case 235 /* TryStatement */: + case 274 /* CatchClause */: + return true; + } + return false; + } + ts.isNodeWithPossibleHoistedDeclaration = isNodeWithPossibleHoistedDeclaration; + function isValueSignatureDeclaration(node) { + return ts.isFunctionExpression(node) || ts.isArrowFunction(node) || ts.isMethodOrAccessor(node) || ts.isFunctionDeclaration(node) || ts.isConstructorDeclaration(node); + } + ts.isValueSignatureDeclaration = isValueSignatureDeclaration; + function walkUp(node, kind) { + while (node && node.kind === kind) { + node = node.parent; + } + return node; + } + function walkUpParenthesizedTypes(node) { + return walkUp(node, 177 /* ParenthesizedType */); + } + ts.walkUpParenthesizedTypes = walkUpParenthesizedTypes; + function walkUpParenthesizedExpressions(node) { + return walkUp(node, 195 /* ParenthesizedExpression */); + } + ts.walkUpParenthesizedExpressions = walkUpParenthesizedExpressions; + function skipParentheses(node) { + while (node.kind === 195 /* ParenthesizedExpression */) { + node = node.expression; + } + return node; + } + ts.skipParentheses = skipParentheses; + function skipParenthesesUp(node) { + while (node.kind === 195 /* ParenthesizedExpression */) { + node = node.parent; + } + return node; + } + // a node is delete target iff. it is PropertyAccessExpression/ElementAccessExpression with parentheses skipped + function isDeleteTarget(node) { + if (node.kind !== 189 /* PropertyAccessExpression */ && node.kind !== 190 /* ElementAccessExpression */) { + return false; + } + node = walkUpParenthesizedExpressions(node.parent); + return node && node.kind === 198 /* DeleteExpression */; + } + ts.isDeleteTarget = isDeleteTarget; + function isNodeDescendantOf(node, ancestor) { + while (node) { + if (node === ancestor) + return true; + node = node.parent; + } + return false; + } + ts.isNodeDescendantOf = isNodeDescendantOf; + // True if `name` is the name of a declaration node + function isDeclarationName(name) { + return !ts.isSourceFile(name) && !ts.isBindingPattern(name) && ts.isDeclaration(name.parent) && name.parent.name === name; + } + ts.isDeclarationName = isDeclarationName; + // See GH#16030 + function getDeclarationFromName(name) { + var parent = name.parent; + switch (name.kind) { + case 10 /* StringLiteral */: + case 8 /* NumericLiteral */: + if (ts.isComputedPropertyName(parent)) + return parent.parent; + // falls through + case 72 /* Identifier */: + if (ts.isDeclaration(parent)) { + return parent.name === name ? parent : undefined; + } + else if (ts.isQualifiedName(parent)) { + var tag = parent.parent; + return ts.isJSDocParameterTag(tag) && tag.name === parent ? tag : undefined; + } + else { + var binExp = parent.parent; + return ts.isBinaryExpression(binExp) && + getAssignmentDeclarationKind(binExp) !== 0 /* None */ && + (binExp.left.symbol || binExp.symbol) && + ts.getNameOfDeclaration(binExp) === name + ? binExp + : undefined; + } + default: + return undefined; + } + } + ts.getDeclarationFromName = getDeclarationFromName; + function isLiteralComputedPropertyDeclarationName(node) { + return (node.kind === 10 /* StringLiteral */ || node.kind === 8 /* NumericLiteral */) && + node.parent.kind === 149 /* ComputedPropertyName */ && + ts.isDeclaration(node.parent.parent); + } + ts.isLiteralComputedPropertyDeclarationName = isLiteralComputedPropertyDeclarationName; + // Return true if the given identifier is classified as an IdentifierName + function isIdentifierName(node) { + var parent = node.parent; + switch (parent.kind) { + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 278 /* EnumMember */: + case 275 /* PropertyAssignment */: + case 189 /* PropertyAccessExpression */: + // Name in member declaration or property name in property access + return parent.name === node; + case 148 /* QualifiedName */: + // Name on right hand side of dot in a type query or type reference + if (parent.right === node) { + while (parent.kind === 148 /* QualifiedName */) { + parent = parent.parent; + } + return parent.kind === 167 /* TypeQuery */ || parent.kind === 164 /* TypeReference */; + } + return false; + case 186 /* BindingElement */: + case 253 /* ImportSpecifier */: + // Property name in binding element or import specifier + return parent.propertyName === node; + case 257 /* ExportSpecifier */: + case 267 /* JsxAttribute */: + // Any name in an export specifier or JSX Attribute + return true; + } + return false; + } + ts.isIdentifierName = isIdentifierName; + // An alias symbol is created by one of the following declarations: + // import = ... + // import from ... + // import * as from ... + // import { x as } from ... + // export { x as } from ... + // export = + // export default + // module.exports = + function isAliasSymbolDeclaration(node) { + return node.kind === 248 /* ImportEqualsDeclaration */ || + node.kind === 247 /* NamespaceExportDeclaration */ || + node.kind === 250 /* ImportClause */ && !!node.name || + node.kind === 251 /* NamespaceImport */ || + node.kind === 253 /* ImportSpecifier */ || + node.kind === 257 /* ExportSpecifier */ || + node.kind === 254 /* ExportAssignment */ && exportAssignmentIsAlias(node) || + ts.isBinaryExpression(node) && getAssignmentDeclarationKind(node) === 2 /* ModuleExports */ && exportAssignmentIsAlias(node); + } + ts.isAliasSymbolDeclaration = isAliasSymbolDeclaration; + function exportAssignmentIsAlias(node) { + var e = ts.isExportAssignment(node) ? node.expression : node.right; + return isEntityNameExpression(e) || ts.isClassExpression(e); + } + ts.exportAssignmentIsAlias = exportAssignmentIsAlias; + function getEffectiveBaseTypeNode(node) { + if (isInJSFile(node)) { + // Prefer an @augments tag because it may have type parameters. + var tag = ts.getJSDocAugmentsTag(node); + if (tag) { + return tag.class; + } + } + return getClassExtendsHeritageElement(node); + } + ts.getEffectiveBaseTypeNode = getEffectiveBaseTypeNode; + function getClassExtendsHeritageElement(node) { + var heritageClause = getHeritageClause(node.heritageClauses, 86 /* ExtendsKeyword */); + return heritageClause && heritageClause.types.length > 0 ? heritageClause.types[0] : undefined; + } + ts.getClassExtendsHeritageElement = getClassExtendsHeritageElement; + function getClassImplementsHeritageClauseElements(node) { + var heritageClause = getHeritageClause(node.heritageClauses, 109 /* ImplementsKeyword */); + return heritageClause ? heritageClause.types : undefined; + } + ts.getClassImplementsHeritageClauseElements = getClassImplementsHeritageClauseElements; + /** Returns the node in an `extends` or `implements` clause of a class or interface. */ + function getAllSuperTypeNodes(node) { + return ts.isInterfaceDeclaration(node) ? getInterfaceBaseTypeNodes(node) || ts.emptyArray + : ts.isClassLike(node) ? ts.concatenate(ts.singleElementArray(getEffectiveBaseTypeNode(node)), getClassImplementsHeritageClauseElements(node)) || ts.emptyArray + : ts.emptyArray; + } + ts.getAllSuperTypeNodes = getAllSuperTypeNodes; + function getInterfaceBaseTypeNodes(node) { + var heritageClause = getHeritageClause(node.heritageClauses, 86 /* ExtendsKeyword */); + return heritageClause ? heritageClause.types : undefined; + } + ts.getInterfaceBaseTypeNodes = getInterfaceBaseTypeNodes; + function getHeritageClause(clauses, kind) { + if (clauses) { + for (var _i = 0, clauses_1 = clauses; _i < clauses_1.length; _i++) { + var clause = clauses_1[_i]; + if (clause.token === kind) { + return clause; + } + } + } + return undefined; + } + ts.getHeritageClause = getHeritageClause; + function tryResolveScriptReference(host, sourceFile, reference) { + if (!host.getCompilerOptions().noResolve) { + var referenceFileName = ts.isRootedDiskPath(reference.fileName) ? reference.fileName : ts.combinePaths(ts.getDirectoryPath(sourceFile.fileName), reference.fileName); + return host.getSourceFile(referenceFileName); + } + } + ts.tryResolveScriptReference = tryResolveScriptReference; + function getAncestor(node, kind) { + while (node) { + if (node.kind === kind) { + return node; + } + node = node.parent; + } + return undefined; + } + ts.getAncestor = getAncestor; + function isKeyword(token) { + return 73 /* FirstKeyword */ <= token && token <= 147 /* LastKeyword */; + } + ts.isKeyword = isKeyword; + function isContextualKeyword(token) { + return 118 /* FirstContextualKeyword */ <= token && token <= 147 /* LastContextualKeyword */; + } + ts.isContextualKeyword = isContextualKeyword; + function isNonContextualKeyword(token) { + return isKeyword(token) && !isContextualKeyword(token); + } + ts.isNonContextualKeyword = isNonContextualKeyword; + function isStringANonContextualKeyword(name) { + var token = ts.stringToToken(name); + return token !== undefined && isNonContextualKeyword(token); + } + ts.isStringANonContextualKeyword = isStringANonContextualKeyword; + function isIdentifierANonContextualKeyword(_a) { + var originalKeywordKind = _a.originalKeywordKind; + return !!originalKeywordKind && !isContextualKeyword(originalKeywordKind); + } + ts.isIdentifierANonContextualKeyword = isIdentifierANonContextualKeyword; + function isTrivia(token) { + return 2 /* FirstTriviaToken */ <= token && token <= 7 /* LastTriviaToken */; + } + ts.isTrivia = isTrivia; + var FunctionFlags; + (function (FunctionFlags) { + FunctionFlags[FunctionFlags["Normal"] = 0] = "Normal"; + FunctionFlags[FunctionFlags["Generator"] = 1] = "Generator"; + FunctionFlags[FunctionFlags["Async"] = 2] = "Async"; + FunctionFlags[FunctionFlags["Invalid"] = 4] = "Invalid"; + FunctionFlags[FunctionFlags["AsyncGenerator"] = 3] = "AsyncGenerator"; + })(FunctionFlags = ts.FunctionFlags || (ts.FunctionFlags = {})); + function getFunctionFlags(node) { + if (!node) { + return 4 /* Invalid */; + } + var flags = 0 /* Normal */; + switch (node.kind) { + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 156 /* MethodDeclaration */: + if (node.asteriskToken) { + flags |= 1 /* Generator */; + } + // falls through + case 197 /* ArrowFunction */: + if (hasModifier(node, 256 /* Async */)) { + flags |= 2 /* Async */; + } + break; + } + if (!node.body) { + flags |= 4 /* Invalid */; + } + return flags; + } + ts.getFunctionFlags = getFunctionFlags; + function isAsyncFunction(node) { + switch (node.kind) { + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 156 /* MethodDeclaration */: + return node.body !== undefined + && node.asteriskToken === undefined + && hasModifier(node, 256 /* Async */); + } + return false; + } + ts.isAsyncFunction = isAsyncFunction; + function isStringOrNumericLiteralLike(node) { + return ts.isStringLiteralLike(node) || ts.isNumericLiteral(node); + } + ts.isStringOrNumericLiteralLike = isStringOrNumericLiteralLike; + /** + * A declaration has a dynamic name if both of the following are true: + * 1. The declaration has a computed property name + * 2. The computed name is *not* expressed as Symbol., where name + * is a property of the Symbol constructor that denotes a built in + * Symbol. + */ + function hasDynamicName(declaration) { + var name = ts.getNameOfDeclaration(declaration); + return !!name && isDynamicName(name); + } + ts.hasDynamicName = hasDynamicName; + function isDynamicName(name) { + return name.kind === 149 /* ComputedPropertyName */ && + !isStringOrNumericLiteralLike(name.expression) && + !isWellKnownSymbolSyntactically(name.expression); + } + ts.isDynamicName = isDynamicName; + /** + * Checks if the expression is of the form: + * Symbol.name + * where Symbol is literally the word "Symbol", and name is any identifierName + */ + function isWellKnownSymbolSyntactically(node) { + return ts.isPropertyAccessExpression(node) && isESSymbolIdentifier(node.expression); + } + ts.isWellKnownSymbolSyntactically = isWellKnownSymbolSyntactically; + function getPropertyNameForPropertyNameNode(name) { + switch (name.kind) { + case 72 /* Identifier */: + return name.escapedText; + case 10 /* StringLiteral */: + case 8 /* NumericLiteral */: + return ts.escapeLeadingUnderscores(name.text); + case 149 /* ComputedPropertyName */: + var nameExpression = name.expression; + if (isWellKnownSymbolSyntactically(nameExpression)) { + return getPropertyNameForKnownSymbolName(ts.idText(nameExpression.name)); + } + else if (isStringOrNumericLiteralLike(nameExpression)) { + return ts.escapeLeadingUnderscores(nameExpression.text); + } + return undefined; + default: + return ts.Debug.assertNever(name); + } + } + ts.getPropertyNameForPropertyNameNode = getPropertyNameForPropertyNameNode; + function isPropertyNameLiteral(node) { + switch (node.kind) { + case 72 /* Identifier */: + case 10 /* StringLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: + case 8 /* NumericLiteral */: + return true; + default: + return false; + } + } + ts.isPropertyNameLiteral = isPropertyNameLiteral; + function getTextOfIdentifierOrLiteral(node) { + return node.kind === 72 /* Identifier */ ? ts.idText(node) : node.text; + } + ts.getTextOfIdentifierOrLiteral = getTextOfIdentifierOrLiteral; + function getEscapedTextOfIdentifierOrLiteral(node) { + return node.kind === 72 /* Identifier */ ? node.escapedText : ts.escapeLeadingUnderscores(node.text); + } + ts.getEscapedTextOfIdentifierOrLiteral = getEscapedTextOfIdentifierOrLiteral; + function getPropertyNameForKnownSymbolName(symbolName) { + return "__@" + symbolName; + } + ts.getPropertyNameForKnownSymbolName = getPropertyNameForKnownSymbolName; + function isKnownSymbol(symbol) { + return ts.startsWith(symbol.escapedName, "__@"); + } + ts.isKnownSymbol = isKnownSymbol; + /** + * Includes the word "Symbol" with unicode escapes + */ + function isESSymbolIdentifier(node) { + return node.kind === 72 /* Identifier */ && node.escapedText === "Symbol"; + } + ts.isESSymbolIdentifier = isESSymbolIdentifier; + function isPushOrUnshiftIdentifier(node) { + return node.escapedText === "push" || node.escapedText === "unshift"; + } + ts.isPushOrUnshiftIdentifier = isPushOrUnshiftIdentifier; + function isParameterDeclaration(node) { + var root = getRootDeclaration(node); + return root.kind === 151 /* Parameter */; + } + ts.isParameterDeclaration = isParameterDeclaration; + function getRootDeclaration(node) { + while (node.kind === 186 /* BindingElement */) { + node = node.parent.parent; + } + return node; + } + ts.getRootDeclaration = getRootDeclaration; + function nodeStartsNewLexicalEnvironment(node) { + var kind = node.kind; + return kind === 157 /* Constructor */ + || kind === 196 /* FunctionExpression */ + || kind === 239 /* FunctionDeclaration */ + || kind === 197 /* ArrowFunction */ + || kind === 156 /* MethodDeclaration */ + || kind === 158 /* GetAccessor */ + || kind === 159 /* SetAccessor */ + || kind === 244 /* ModuleDeclaration */ + || kind === 279 /* SourceFile */; + } + ts.nodeStartsNewLexicalEnvironment = nodeStartsNewLexicalEnvironment; + function nodeIsSynthesized(range) { + return ts.positionIsSynthesized(range.pos) + || ts.positionIsSynthesized(range.end); + } + ts.nodeIsSynthesized = nodeIsSynthesized; + function getOriginalSourceFile(sourceFile) { + return ts.getParseTreeNode(sourceFile, ts.isSourceFile) || sourceFile; + } + ts.getOriginalSourceFile = getOriginalSourceFile; + var Associativity; + (function (Associativity) { + Associativity[Associativity["Left"] = 0] = "Left"; + Associativity[Associativity["Right"] = 1] = "Right"; + })(Associativity = ts.Associativity || (ts.Associativity = {})); + function getExpressionAssociativity(expression) { + var operator = getOperator(expression); + var hasArguments = expression.kind === 192 /* NewExpression */ && expression.arguments !== undefined; + return getOperatorAssociativity(expression.kind, operator, hasArguments); + } + ts.getExpressionAssociativity = getExpressionAssociativity; + function getOperatorAssociativity(kind, operator, hasArguments) { + switch (kind) { + case 192 /* NewExpression */: + return hasArguments ? 0 /* Left */ : 1 /* Right */; + case 202 /* PrefixUnaryExpression */: + case 199 /* TypeOfExpression */: + case 200 /* VoidExpression */: + case 198 /* DeleteExpression */: + case 201 /* AwaitExpression */: + case 205 /* ConditionalExpression */: + case 207 /* YieldExpression */: + return 1 /* Right */; + case 204 /* BinaryExpression */: + switch (operator) { + case 41 /* AsteriskAsteriskToken */: + case 59 /* EqualsToken */: + case 60 /* PlusEqualsToken */: + case 61 /* MinusEqualsToken */: + case 63 /* AsteriskAsteriskEqualsToken */: + case 62 /* AsteriskEqualsToken */: + case 64 /* SlashEqualsToken */: + case 65 /* PercentEqualsToken */: + case 66 /* LessThanLessThanEqualsToken */: + case 67 /* GreaterThanGreaterThanEqualsToken */: + case 68 /* GreaterThanGreaterThanGreaterThanEqualsToken */: + case 69 /* AmpersandEqualsToken */: + case 71 /* CaretEqualsToken */: + case 70 /* BarEqualsToken */: + return 1 /* Right */; + } + } + return 0 /* Left */; + } + ts.getOperatorAssociativity = getOperatorAssociativity; + function getExpressionPrecedence(expression) { + var operator = getOperator(expression); + var hasArguments = expression.kind === 192 /* NewExpression */ && expression.arguments !== undefined; + return getOperatorPrecedence(expression.kind, operator, hasArguments); + } + ts.getExpressionPrecedence = getExpressionPrecedence; + function getOperator(expression) { + if (expression.kind === 204 /* BinaryExpression */) { + return expression.operatorToken.kind; + } + else if (expression.kind === 202 /* PrefixUnaryExpression */ || expression.kind === 203 /* PostfixUnaryExpression */) { + return expression.operator; + } + else { + return expression.kind; + } + } + ts.getOperator = getOperator; + function getOperatorPrecedence(nodeKind, operatorKind, hasArguments) { + switch (nodeKind) { + case 309 /* CommaListExpression */: + return 0; + case 208 /* SpreadElement */: + return 1; + case 207 /* YieldExpression */: + return 2; + case 205 /* ConditionalExpression */: + return 4; + case 204 /* BinaryExpression */: + switch (operatorKind) { + case 27 /* CommaToken */: + return 0; + case 59 /* EqualsToken */: + case 60 /* PlusEqualsToken */: + case 61 /* MinusEqualsToken */: + case 63 /* AsteriskAsteriskEqualsToken */: + case 62 /* AsteriskEqualsToken */: + case 64 /* SlashEqualsToken */: + case 65 /* PercentEqualsToken */: + case 66 /* LessThanLessThanEqualsToken */: + case 67 /* GreaterThanGreaterThanEqualsToken */: + case 68 /* GreaterThanGreaterThanGreaterThanEqualsToken */: + case 69 /* AmpersandEqualsToken */: + case 71 /* CaretEqualsToken */: + case 70 /* BarEqualsToken */: + return 3; + default: + return getBinaryOperatorPrecedence(operatorKind); + } + case 202 /* PrefixUnaryExpression */: + case 199 /* TypeOfExpression */: + case 200 /* VoidExpression */: + case 198 /* DeleteExpression */: + case 201 /* AwaitExpression */: + return 16; + case 203 /* PostfixUnaryExpression */: + return 17; + case 191 /* CallExpression */: + return 18; + case 192 /* NewExpression */: + return hasArguments ? 19 : 18; + case 193 /* TaggedTemplateExpression */: + case 189 /* PropertyAccessExpression */: + case 190 /* ElementAccessExpression */: + return 19; + case 100 /* ThisKeyword */: + case 98 /* SuperKeyword */: + case 72 /* Identifier */: + case 96 /* NullKeyword */: + case 102 /* TrueKeyword */: + case 87 /* FalseKeyword */: + case 8 /* NumericLiteral */: + case 9 /* BigIntLiteral */: + case 10 /* StringLiteral */: + case 187 /* ArrayLiteralExpression */: + case 188 /* ObjectLiteralExpression */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 209 /* ClassExpression */: + case 260 /* JsxElement */: + case 261 /* JsxSelfClosingElement */: + case 264 /* JsxFragment */: + case 13 /* RegularExpressionLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: + case 206 /* TemplateExpression */: + case 195 /* ParenthesizedExpression */: + case 210 /* OmittedExpression */: + return 20; + default: + return -1; + } + } + ts.getOperatorPrecedence = getOperatorPrecedence; + function getBinaryOperatorPrecedence(kind) { + switch (kind) { + case 55 /* BarBarToken */: + return 5; + case 54 /* AmpersandAmpersandToken */: + return 6; + case 50 /* BarToken */: + return 7; + case 51 /* CaretToken */: + return 8; + case 49 /* AmpersandToken */: + return 9; + case 33 /* EqualsEqualsToken */: + case 34 /* ExclamationEqualsToken */: + case 35 /* EqualsEqualsEqualsToken */: + case 36 /* ExclamationEqualsEqualsToken */: + return 10; + case 28 /* LessThanToken */: + case 30 /* GreaterThanToken */: + case 31 /* LessThanEqualsToken */: + case 32 /* GreaterThanEqualsToken */: + case 94 /* InstanceOfKeyword */: + case 93 /* InKeyword */: + case 119 /* AsKeyword */: + return 11; + case 46 /* LessThanLessThanToken */: + case 47 /* GreaterThanGreaterThanToken */: + case 48 /* GreaterThanGreaterThanGreaterThanToken */: + return 12; + case 38 /* PlusToken */: + case 39 /* MinusToken */: + return 13; + case 40 /* AsteriskToken */: + case 42 /* SlashToken */: + case 43 /* PercentToken */: + return 14; + case 41 /* AsteriskAsteriskToken */: + return 15; + } + // -1 is lower than all other precedences. Returning it will cause binary expression + // parsing to stop. + return -1; + } + ts.getBinaryOperatorPrecedence = getBinaryOperatorPrecedence; + function createDiagnosticCollection() { + var nonFileDiagnostics = []; // See GH#19873 + var filesWithDiagnostics = []; + var fileDiagnostics = ts.createMap(); + var hasReadNonFileDiagnostics = false; + return { + add: add, + lookup: lookup, + getGlobalDiagnostics: getGlobalDiagnostics, + getDiagnostics: getDiagnostics, + reattachFileDiagnostics: reattachFileDiagnostics + }; + function reattachFileDiagnostics(newFile) { + ts.forEach(fileDiagnostics.get(newFile.fileName), function (diagnostic) { return diagnostic.file = newFile; }); + } + function lookup(diagnostic) { + var diagnostics; + if (diagnostic.file) { + diagnostics = fileDiagnostics.get(diagnostic.file.fileName); + } + else { + diagnostics = nonFileDiagnostics; + } + if (!diagnostics) { + return undefined; + } + var result = ts.binarySearch(diagnostics, diagnostic, ts.identity, ts.compareDiagnosticsSkipRelatedInformation); + if (result >= 0) { + return diagnostics[result]; + } + return undefined; + } + function add(diagnostic) { + var diagnostics; + if (diagnostic.file) { + diagnostics = fileDiagnostics.get(diagnostic.file.fileName); + if (!diagnostics) { + diagnostics = []; // See GH#19873 + fileDiagnostics.set(diagnostic.file.fileName, diagnostics); + ts.insertSorted(filesWithDiagnostics, diagnostic.file.fileName, ts.compareStringsCaseSensitive); + } + } + else { + // If we've already read the non-file diagnostics, do not modify the existing array. + if (hasReadNonFileDiagnostics) { + hasReadNonFileDiagnostics = false; + nonFileDiagnostics = nonFileDiagnostics.slice(); + } + diagnostics = nonFileDiagnostics; + } + ts.insertSorted(diagnostics, diagnostic, ts.compareDiagnostics); + } + function getGlobalDiagnostics() { + hasReadNonFileDiagnostics = true; + return nonFileDiagnostics; + } + function getDiagnostics(fileName) { + if (fileName) { + return fileDiagnostics.get(fileName) || []; + } + var fileDiags = ts.flatMapToMutable(filesWithDiagnostics, function (f) { return fileDiagnostics.get(f); }); + if (!nonFileDiagnostics.length) { + return fileDiags; + } + fileDiags.unshift.apply(fileDiags, nonFileDiagnostics); + return fileDiags; + } + } + ts.createDiagnosticCollection = createDiagnosticCollection; + // This consists of the first 19 unprintable ASCII characters, canonical escapes, lineSeparator, + // paragraphSeparator, and nextLine. The latter three are just desirable to suppress new lines in + // the language service. These characters should be escaped when printing, and if any characters are added, + // the map below must be updated. Note that this regexp *does not* include the 'delete' character. + // There is no reason for this other than that JSON.stringify does not handle it either. + var doubleQuoteEscapedCharsRegExp = /[\\\"\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g; + var singleQuoteEscapedCharsRegExp = /[\\\'\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g; + var backtickQuoteEscapedCharsRegExp = /[\\\`\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g; + var escapedCharsMap = ts.createMapFromTemplate({ + "\t": "\\t", + "\v": "\\v", + "\f": "\\f", + "\b": "\\b", + "\r": "\\r", + "\n": "\\n", + "\\": "\\\\", + "\"": "\\\"", + "\'": "\\\'", + "\`": "\\\`", + "\u2028": "\\u2028", + "\u2029": "\\u2029", + "\u0085": "\\u0085" // nextLine + }); + /** + * Based heavily on the abstract 'Quote'/'QuoteJSONString' operation from ECMA-262 (24.3.2.2), + * but augmented for a few select characters (e.g. lineSeparator, paragraphSeparator, nextLine) + * Note that this doesn't actually wrap the input in double quotes. + */ + function escapeString(s, quoteChar) { + var escapedCharsRegExp = quoteChar === 96 /* backtick */ ? backtickQuoteEscapedCharsRegExp : + quoteChar === 39 /* singleQuote */ ? singleQuoteEscapedCharsRegExp : + doubleQuoteEscapedCharsRegExp; + return s.replace(escapedCharsRegExp, getReplacement); + } + ts.escapeString = escapeString; + function getReplacement(c, offset, input) { + if (c.charCodeAt(0) === 0 /* nullCharacter */) { + var lookAhead = input.charCodeAt(offset + c.length); + if (lookAhead >= 48 /* _0 */ && lookAhead <= 57 /* _9 */) { + // If the null character is followed by digits, print as a hex escape to prevent the result from parsing as an octal (which is forbidden in strict mode) + return "\\x00"; + } + // Otherwise, keep printing a literal \0 for the null character + return "\\0"; + } + return escapedCharsMap.get(c) || get16BitUnicodeEscapeSequence(c.charCodeAt(0)); + } + function isIntrinsicJsxName(name) { + var ch = name.charCodeAt(0); + return (ch >= 97 /* a */ && ch <= 122 /* z */) || ts.stringContains(name, "-"); + } + ts.isIntrinsicJsxName = isIntrinsicJsxName; + function get16BitUnicodeEscapeSequence(charCode) { + var hexCharCode = charCode.toString(16).toUpperCase(); + var paddedHexCode = ("0000" + hexCharCode).slice(-4); + return "\\u" + paddedHexCode; + } + var nonAsciiCharacters = /[^\u0000-\u007F]/g; + function escapeNonAsciiString(s, quoteChar) { + s = escapeString(s, quoteChar); + // Replace non-ASCII characters with '\uNNNN' escapes if any exist. + // Otherwise just return the original string. + return nonAsciiCharacters.test(s) ? + s.replace(nonAsciiCharacters, function (c) { return get16BitUnicodeEscapeSequence(c.charCodeAt(0)); }) : + s; + } + ts.escapeNonAsciiString = escapeNonAsciiString; + var indentStrings = ["", " "]; + function getIndentString(level) { + if (indentStrings[level] === undefined) { + indentStrings[level] = getIndentString(level - 1) + indentStrings[1]; + } + return indentStrings[level]; + } + ts.getIndentString = getIndentString; + function getIndentSize() { + return indentStrings[1].length; + } + ts.getIndentSize = getIndentSize; + function createTextWriter(newLine) { + var output; + var indent; + var lineStart; + var lineCount; + var linePos; + function updateLineCountAndPosFor(s) { + var lineStartsOfS = ts.computeLineStarts(s); + if (lineStartsOfS.length > 1) { + lineCount = lineCount + lineStartsOfS.length - 1; + linePos = output.length - s.length + ts.last(lineStartsOfS); + lineStart = (linePos - output.length) === 0; + } + else { + lineStart = false; + } + } + function write(s) { + if (s && s.length) { + if (lineStart) { + s = getIndentString(indent) + s; + lineStart = false; + } + output += s; + updateLineCountAndPosFor(s); + } + } + function reset() { + output = ""; + indent = 0; + lineStart = true; + lineCount = 0; + linePos = 0; + } + function rawWrite(s) { + if (s !== undefined) { + output += s; + updateLineCountAndPosFor(s); + } + } + function writeLiteral(s) { + if (s && s.length) { + write(s); + } + } + function writeLine() { + if (!lineStart) { + output += newLine; + lineCount++; + linePos = output.length; + lineStart = true; + } + } + reset(); + return { + write: write, + rawWrite: rawWrite, + writeLiteral: writeLiteral, + writeLine: writeLine, + increaseIndent: function () { indent++; }, + decreaseIndent: function () { indent--; }, + getIndent: function () { return indent; }, + getTextPos: function () { return output.length; }, + getLine: function () { return lineCount; }, + getColumn: function () { return lineStart ? indent * getIndentSize() : output.length - linePos; }, + getText: function () { return output; }, + isAtStartOfLine: function () { return lineStart; }, + clear: reset, + reportInaccessibleThisError: ts.noop, + reportPrivateInBaseOfClassExpression: ts.noop, + reportInaccessibleUniqueSymbolError: ts.noop, + trackSymbol: ts.noop, + writeKeyword: write, + writeOperator: write, + writeParameter: write, + writeProperty: write, + writePunctuation: write, + writeSpace: write, + writeStringLiteral: write, + writeSymbol: function (s, _) { return write(s); }, + writeTrailingSemicolon: write, + writeComment: write + }; + } + ts.createTextWriter = createTextWriter; + function getTrailingSemicolonOmittingWriter(writer) { + var pendingTrailingSemicolon = false; + function commitPendingTrailingSemicolon() { + if (pendingTrailingSemicolon) { + writer.writeTrailingSemicolon(";"); + pendingTrailingSemicolon = false; + } + } + return __assign({}, writer, { writeTrailingSemicolon: function () { + pendingTrailingSemicolon = true; + }, + writeLiteral: function (s) { + commitPendingTrailingSemicolon(); + writer.writeLiteral(s); + }, + writeStringLiteral: function (s) { + commitPendingTrailingSemicolon(); + writer.writeStringLiteral(s); + }, + writeSymbol: function (s, sym) { + commitPendingTrailingSemicolon(); + writer.writeSymbol(s, sym); + }, + writePunctuation: function (s) { + commitPendingTrailingSemicolon(); + writer.writePunctuation(s); + }, + writeKeyword: function (s) { + commitPendingTrailingSemicolon(); + writer.writeKeyword(s); + }, + writeOperator: function (s) { + commitPendingTrailingSemicolon(); + writer.writeOperator(s); + }, + writeParameter: function (s) { + commitPendingTrailingSemicolon(); + writer.writeParameter(s); + }, + writeSpace: function (s) { + commitPendingTrailingSemicolon(); + writer.writeSpace(s); + }, + writeProperty: function (s) { + commitPendingTrailingSemicolon(); + writer.writeProperty(s); + }, + writeComment: function (s) { + commitPendingTrailingSemicolon(); + writer.writeComment(s); + }, + writeLine: function () { + commitPendingTrailingSemicolon(); + writer.writeLine(); + }, + increaseIndent: function () { + commitPendingTrailingSemicolon(); + writer.increaseIndent(); + }, + decreaseIndent: function () { + commitPendingTrailingSemicolon(); + writer.decreaseIndent(); + } }); + } + ts.getTrailingSemicolonOmittingWriter = getTrailingSemicolonOmittingWriter; + function getResolvedExternalModuleName(host, file, referenceFile) { + return file.moduleName || getExternalModuleNameFromPath(host, file.fileName, referenceFile && referenceFile.fileName); + } + ts.getResolvedExternalModuleName = getResolvedExternalModuleName; + function getExternalModuleNameFromDeclaration(host, resolver, declaration) { + var file = resolver.getExternalModuleFileFromDeclaration(declaration); + if (!file || file.isDeclarationFile) { + return undefined; + } + return getResolvedExternalModuleName(host, file); + } + ts.getExternalModuleNameFromDeclaration = getExternalModuleNameFromDeclaration; + /** + * Resolves a local path to a path which is absolute to the base of the emit + */ + function getExternalModuleNameFromPath(host, fileName, referencePath) { + var getCanonicalFileName = function (f) { return host.getCanonicalFileName(f); }; + var dir = toPath(referencePath ? ts.getDirectoryPath(referencePath) : host.getCommonSourceDirectory(), host.getCurrentDirectory(), getCanonicalFileName); + var filePath = ts.getNormalizedAbsolutePath(fileName, host.getCurrentDirectory()); + var relativePath = ts.getRelativePathToDirectoryOrUrl(dir, filePath, dir, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); + var extensionless = ts.removeFileExtension(relativePath); + return referencePath ? ts.ensurePathIsNonModuleName(extensionless) : extensionless; + } + ts.getExternalModuleNameFromPath = getExternalModuleNameFromPath; + function getOwnEmitOutputFilePath(fileName, host, extension) { + var compilerOptions = host.getCompilerOptions(); + var emitOutputFilePathWithoutExtension; + if (compilerOptions.outDir) { + emitOutputFilePathWithoutExtension = ts.removeFileExtension(getSourceFilePathInNewDir(fileName, host, compilerOptions.outDir)); + } + else { + emitOutputFilePathWithoutExtension = ts.removeFileExtension(fileName); + } + return emitOutputFilePathWithoutExtension + extension; + } + ts.getOwnEmitOutputFilePath = getOwnEmitOutputFilePath; + function getDeclarationEmitOutputFilePath(fileName, host) { + return getDeclarationEmitOutputFilePathWorker(fileName, host.getCompilerOptions(), host.getCurrentDirectory(), host.getCommonSourceDirectory(), function (f) { return host.getCanonicalFileName(f); }); + } + ts.getDeclarationEmitOutputFilePath = getDeclarationEmitOutputFilePath; + function getDeclarationEmitOutputFilePathWorker(fileName, options, currentDirectory, commonSourceDirectory, getCanonicalFileName) { + var outputDir = options.declarationDir || options.outDir; // Prefer declaration folder if specified + var path = outputDir + ? getSourceFilePathInNewDirWorker(fileName, outputDir, currentDirectory, commonSourceDirectory, getCanonicalFileName) + : fileName; + return ts.removeFileExtension(path) + ".d.ts" /* Dts */; + } + ts.getDeclarationEmitOutputFilePathWorker = getDeclarationEmitOutputFilePathWorker; + /** + * Gets the source files that are expected to have an emit output. + * + * Originally part of `forEachExpectedEmitFile`, this functionality was extracted to support + * transformations. + * + * @param host An EmitHost. + * @param targetSourceFile An optional target source file to emit. + */ + function getSourceFilesToEmit(host, targetSourceFile) { + var options = host.getCompilerOptions(); + var isSourceFileFromExternalLibrary = function (file) { return host.isSourceFileFromExternalLibrary(file); }; + if (options.outFile || options.out) { + var moduleKind = ts.getEmitModuleKind(options); + var moduleEmitEnabled_1 = options.emitDeclarationOnly || moduleKind === ts.ModuleKind.AMD || moduleKind === ts.ModuleKind.System; + // Can emit only sources that are not declaration file and are either non module code or module with --module or --target es6 specified + return ts.filter(host.getSourceFiles(), function (sourceFile) { + return (moduleEmitEnabled_1 || !ts.isExternalModule(sourceFile)) && sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary); + }); + } + else { + var sourceFiles = targetSourceFile === undefined ? host.getSourceFiles() : [targetSourceFile]; + return ts.filter(sourceFiles, function (sourceFile) { return sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary); }); + } + } + ts.getSourceFilesToEmit = getSourceFilesToEmit; + /** Don't call this for `--outFile`, just for `--outDir` or plain emit. `--outFile` needs additional checks. */ + function sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary) { + return !(options.noEmitForJsFiles && isSourceFileJS(sourceFile)) && !sourceFile.isDeclarationFile && !isSourceFileFromExternalLibrary(sourceFile); + } + ts.sourceFileMayBeEmitted = sourceFileMayBeEmitted; + function getSourceFilePathInNewDir(fileName, host, newDirPath) { + return getSourceFilePathInNewDirWorker(fileName, newDirPath, host.getCurrentDirectory(), host.getCommonSourceDirectory(), function (f) { return host.getCanonicalFileName(f); }); + } + ts.getSourceFilePathInNewDir = getSourceFilePathInNewDir; + function getSourceFilePathInNewDirWorker(fileName, newDirPath, currentDirectory, commonSourceDirectory, getCanonicalFileName) { + var sourceFilePath = ts.getNormalizedAbsolutePath(fileName, currentDirectory); + var isSourceFileInCommonSourceDirectory = getCanonicalFileName(sourceFilePath).indexOf(getCanonicalFileName(commonSourceDirectory)) === 0; + sourceFilePath = isSourceFileInCommonSourceDirectory ? sourceFilePath.substring(commonSourceDirectory.length) : sourceFilePath; + return ts.combinePaths(newDirPath, sourceFilePath); + } + ts.getSourceFilePathInNewDirWorker = getSourceFilePathInNewDirWorker; + function writeFile(host, diagnostics, fileName, data, writeByteOrderMark, sourceFiles) { + host.writeFile(fileName, data, writeByteOrderMark, function (hostErrorMessage) { + diagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Could_not_write_file_0_Colon_1, fileName, hostErrorMessage)); + }, sourceFiles); + } + ts.writeFile = writeFile; + function getLineOfLocalPosition(currentSourceFile, pos) { + return ts.getLineAndCharacterOfPosition(currentSourceFile, pos).line; + } + ts.getLineOfLocalPosition = getLineOfLocalPosition; + function getLineOfLocalPositionFromLineMap(lineMap, pos) { + return ts.computeLineAndCharacterOfPosition(lineMap, pos).line; + } + ts.getLineOfLocalPositionFromLineMap = getLineOfLocalPositionFromLineMap; + function getFirstConstructorWithBody(node) { + return ts.find(node.members, function (member) { return ts.isConstructorDeclaration(member) && nodeIsPresent(member.body); }); + } + ts.getFirstConstructorWithBody = getFirstConstructorWithBody; + function getSetAccessorValueParameter(accessor) { + if (accessor && accessor.parameters.length > 0) { + var hasThis = accessor.parameters.length === 2 && parameterIsThisKeyword(accessor.parameters[0]); + return accessor.parameters[hasThis ? 1 : 0]; + } + } + /** Get the type annotation for the value parameter. */ + function getSetAccessorTypeAnnotationNode(accessor) { + var parameter = getSetAccessorValueParameter(accessor); + return parameter && parameter.type; + } + ts.getSetAccessorTypeAnnotationNode = getSetAccessorTypeAnnotationNode; + function getThisParameter(signature) { + // callback tags do not currently support this parameters + if (signature.parameters.length && !ts.isJSDocSignature(signature)) { + var thisParameter = signature.parameters[0]; + if (parameterIsThisKeyword(thisParameter)) { + return thisParameter; + } + } + } + ts.getThisParameter = getThisParameter; + function parameterIsThisKeyword(parameter) { + return isThisIdentifier(parameter.name); + } + ts.parameterIsThisKeyword = parameterIsThisKeyword; + function isThisIdentifier(node) { + return !!node && node.kind === 72 /* Identifier */ && identifierIsThisKeyword(node); + } + ts.isThisIdentifier = isThisIdentifier; + function identifierIsThisKeyword(id) { + return id.originalKeywordKind === 100 /* ThisKeyword */; + } + ts.identifierIsThisKeyword = identifierIsThisKeyword; + function getAllAccessorDeclarations(declarations, accessor) { + // TODO: GH#18217 + var firstAccessor; + var secondAccessor; + var getAccessor; + var setAccessor; + if (hasDynamicName(accessor)) { + firstAccessor = accessor; + if (accessor.kind === 158 /* GetAccessor */) { + getAccessor = accessor; + } + else if (accessor.kind === 159 /* SetAccessor */) { + setAccessor = accessor; + } + else { + ts.Debug.fail("Accessor has wrong kind"); + } + } + else { + ts.forEach(declarations, function (member) { + if (ts.isAccessor(member) + && hasModifier(member, 32 /* Static */) === hasModifier(accessor, 32 /* Static */)) { + var memberName = getPropertyNameForPropertyNameNode(member.name); + var accessorName = getPropertyNameForPropertyNameNode(accessor.name); + if (memberName === accessorName) { + if (!firstAccessor) { + firstAccessor = member; + } + else if (!secondAccessor) { + secondAccessor = member; + } + if (member.kind === 158 /* GetAccessor */ && !getAccessor) { + getAccessor = member; + } + if (member.kind === 159 /* SetAccessor */ && !setAccessor) { + setAccessor = member; + } + } + } + }); + } + return { + firstAccessor: firstAccessor, + secondAccessor: secondAccessor, + getAccessor: getAccessor, + setAccessor: setAccessor + }; + } + ts.getAllAccessorDeclarations = getAllAccessorDeclarations; + /** + * Gets the effective type annotation of a variable, parameter, or property. If the node was + * parsed in a JavaScript file, gets the type annotation from JSDoc. + */ + function getEffectiveTypeAnnotationNode(node) { + var type = node.type; + if (type || !isInJSFile(node)) + return type; + return ts.isJSDocPropertyLikeTag(node) ? node.typeExpression && node.typeExpression.type : ts.getJSDocType(node); + } + ts.getEffectiveTypeAnnotationNode = getEffectiveTypeAnnotationNode; + function getTypeAnnotationNode(node) { + return node.type; + } + ts.getTypeAnnotationNode = getTypeAnnotationNode; + /** + * Gets the effective return type annotation of a signature. If the node was parsed in a + * JavaScript file, gets the return type annotation from JSDoc. + */ + function getEffectiveReturnTypeNode(node) { + return ts.isJSDocSignature(node) ? + node.type && node.type.typeExpression && node.type.typeExpression.type : + node.type || (isInJSFile(node) ? ts.getJSDocReturnType(node) : undefined); + } + ts.getEffectiveReturnTypeNode = getEffectiveReturnTypeNode; + function getJSDocTypeParameterDeclarations(node) { + return ts.flatMap(ts.getJSDocTags(node), function (tag) { return isNonTypeAliasTemplate(tag) ? tag.typeParameters : undefined; }); + } + ts.getJSDocTypeParameterDeclarations = getJSDocTypeParameterDeclarations; + /** template tags are only available when a typedef isn't already using them */ + function isNonTypeAliasTemplate(tag) { + return ts.isJSDocTemplateTag(tag) && !(tag.parent.kind === 291 /* JSDocComment */ && tag.parent.tags.some(isJSDocTypeAlias)); + } + /** + * Gets the effective type annotation of the value parameter of a set accessor. If the node + * was parsed in a JavaScript file, gets the type annotation from JSDoc. + */ + function getEffectiveSetAccessorTypeAnnotationNode(node) { + var parameter = getSetAccessorValueParameter(node); + return parameter && getEffectiveTypeAnnotationNode(parameter); + } + ts.getEffectiveSetAccessorTypeAnnotationNode = getEffectiveSetAccessorTypeAnnotationNode; + function emitNewLineBeforeLeadingComments(lineMap, writer, node, leadingComments) { + emitNewLineBeforeLeadingCommentsOfPosition(lineMap, writer, node.pos, leadingComments); + } + ts.emitNewLineBeforeLeadingComments = emitNewLineBeforeLeadingComments; + function emitNewLineBeforeLeadingCommentsOfPosition(lineMap, writer, pos, leadingComments) { + // If the leading comments start on different line than the start of node, write new line + if (leadingComments && leadingComments.length && pos !== leadingComments[0].pos && + getLineOfLocalPositionFromLineMap(lineMap, pos) !== getLineOfLocalPositionFromLineMap(lineMap, leadingComments[0].pos)) { + writer.writeLine(); + } + } + ts.emitNewLineBeforeLeadingCommentsOfPosition = emitNewLineBeforeLeadingCommentsOfPosition; + function emitNewLineBeforeLeadingCommentOfPosition(lineMap, writer, pos, commentPos) { + // If the leading comments start on different line than the start of node, write new line + if (pos !== commentPos && + getLineOfLocalPositionFromLineMap(lineMap, pos) !== getLineOfLocalPositionFromLineMap(lineMap, commentPos)) { + writer.writeLine(); + } + } + ts.emitNewLineBeforeLeadingCommentOfPosition = emitNewLineBeforeLeadingCommentOfPosition; + function emitComments(text, lineMap, writer, comments, leadingSeparator, trailingSeparator, newLine, writeComment) { + if (comments && comments.length > 0) { + if (leadingSeparator) { + writer.writeSpace(" "); + } + var emitInterveningSeparator = false; + for (var _i = 0, comments_1 = comments; _i < comments_1.length; _i++) { + var comment = comments_1[_i]; + if (emitInterveningSeparator) { + writer.writeSpace(" "); + emitInterveningSeparator = false; + } + writeComment(text, lineMap, writer, comment.pos, comment.end, newLine); + if (comment.hasTrailingNewLine) { + writer.writeLine(); + } + else { + emitInterveningSeparator = true; + } + } + if (emitInterveningSeparator && trailingSeparator) { + writer.writeSpace(" "); + } + } + } + ts.emitComments = emitComments; + /** + * Detached comment is a comment at the top of file or function body that is separated from + * the next statement by space. + */ + function emitDetachedComments(text, lineMap, writer, writeComment, node, newLine, removeComments) { + var leadingComments; + var currentDetachedCommentInfo; + if (removeComments) { + // removeComments is true, only reserve pinned comment at the top of file + // For example: + // /*! Pinned Comment */ + // + // var x = 10; + if (node.pos === 0) { + leadingComments = ts.filter(ts.getLeadingCommentRanges(text, node.pos), isPinnedCommentLocal); + } + } + else { + // removeComments is false, just get detached as normal and bypass the process to filter comment + leadingComments = ts.getLeadingCommentRanges(text, node.pos); + } + if (leadingComments) { + var detachedComments = []; + var lastComment = void 0; + for (var _i = 0, leadingComments_1 = leadingComments; _i < leadingComments_1.length; _i++) { + var comment = leadingComments_1[_i]; + if (lastComment) { + var lastCommentLine = getLineOfLocalPositionFromLineMap(lineMap, lastComment.end); + var commentLine = getLineOfLocalPositionFromLineMap(lineMap, comment.pos); + if (commentLine >= lastCommentLine + 2) { + // There was a blank line between the last comment and this comment. This + // comment is not part of the copyright comments. Return what we have so + // far. + break; + } + } + detachedComments.push(comment); + lastComment = comment; + } + if (detachedComments.length) { + // All comments look like they could have been part of the copyright header. Make + // sure there is at least one blank line between it and the node. If not, it's not + // a copyright header. + var lastCommentLine = getLineOfLocalPositionFromLineMap(lineMap, ts.last(detachedComments).end); + var nodeLine = getLineOfLocalPositionFromLineMap(lineMap, ts.skipTrivia(text, node.pos)); + if (nodeLine >= lastCommentLine + 2) { + // Valid detachedComments + emitNewLineBeforeLeadingComments(lineMap, writer, node, leadingComments); + emitComments(text, lineMap, writer, detachedComments, /*leadingSeparator*/ false, /*trailingSeparator*/ true, newLine, writeComment); + currentDetachedCommentInfo = { nodePos: node.pos, detachedCommentEndPos: ts.last(detachedComments).end }; + } + } + } + return currentDetachedCommentInfo; + function isPinnedCommentLocal(comment) { + return isPinnedComment(text, comment.pos); + } + } + ts.emitDetachedComments = emitDetachedComments; + function writeCommentRange(text, lineMap, writer, commentPos, commentEnd, newLine) { + if (text.charCodeAt(commentPos + 1) === 42 /* asterisk */) { + var firstCommentLineAndCharacter = ts.computeLineAndCharacterOfPosition(lineMap, commentPos); + var lineCount = lineMap.length; + var firstCommentLineIndent = void 0; + for (var pos = commentPos, currentLine = firstCommentLineAndCharacter.line; pos < commentEnd; currentLine++) { + var nextLineStart = (currentLine + 1) === lineCount + ? text.length + 1 + : lineMap[currentLine + 1]; + if (pos !== commentPos) { + // If we are not emitting first line, we need to write the spaces to adjust the alignment + if (firstCommentLineIndent === undefined) { + firstCommentLineIndent = calculateIndent(text, lineMap[firstCommentLineAndCharacter.line], commentPos); + } + // These are number of spaces writer is going to write at current indent + var currentWriterIndentSpacing = writer.getIndent() * getIndentSize(); + // Number of spaces we want to be writing + // eg: Assume writer indent + // module m { + // /* starts at character 9 this is line 1 + // * starts at character pos 4 line --1 = 8 - 8 + 3 + // More left indented comment */ --2 = 8 - 8 + 2 + // class c { } + // } + // module m { + // /* this is line 1 -- Assume current writer indent 8 + // * line --3 = 8 - 4 + 5 + // More right indented comment */ --4 = 8 - 4 + 11 + // class c { } + // } + var spacesToEmit = currentWriterIndentSpacing - firstCommentLineIndent + calculateIndent(text, pos, nextLineStart); + if (spacesToEmit > 0) { + var numberOfSingleSpacesToEmit = spacesToEmit % getIndentSize(); + var indentSizeSpaceString = getIndentString((spacesToEmit - numberOfSingleSpacesToEmit) / getIndentSize()); + // Write indent size string ( in eg 1: = "", 2: "" , 3: string with 8 spaces 4: string with 12 spaces + writer.rawWrite(indentSizeSpaceString); + // Emit the single spaces (in eg: 1: 3 spaces, 2: 2 spaces, 3: 1 space, 4: 3 spaces) + while (numberOfSingleSpacesToEmit) { + writer.rawWrite(" "); + numberOfSingleSpacesToEmit--; + } + } + else { + // No spaces to emit write empty string + writer.rawWrite(""); + } + } + // Write the comment line text + writeTrimmedCurrentLine(text, commentEnd, writer, newLine, pos, nextLineStart); + pos = nextLineStart; + } + } + else { + // Single line comment of style //.... + writer.writeComment(text.substring(commentPos, commentEnd)); + } + } + ts.writeCommentRange = writeCommentRange; + function writeTrimmedCurrentLine(text, commentEnd, writer, newLine, pos, nextLineStart) { + var end = Math.min(commentEnd, nextLineStart - 1); + var currentLineText = text.substring(pos, end).replace(/^\s+|\s+$/g, ""); + if (currentLineText) { + // trimmed forward and ending spaces text + writer.writeComment(currentLineText); + if (end !== commentEnd) { + writer.writeLine(); + } + } + else { + // Empty string - make sure we write empty line + writer.rawWrite(newLine); + } + } + function calculateIndent(text, pos, end) { + var currentLineIndent = 0; + for (; pos < end && ts.isWhiteSpaceSingleLine(text.charCodeAt(pos)); pos++) { + if (text.charCodeAt(pos) === 9 /* tab */) { + // Tabs = TabSize = indent size and go to next tabStop + currentLineIndent += getIndentSize() - (currentLineIndent % getIndentSize()); + } + else { + // Single space + currentLineIndent++; + } + } + return currentLineIndent; + } + function hasModifiers(node) { + return getModifierFlags(node) !== 0 /* None */; + } + ts.hasModifiers = hasModifiers; + function hasModifier(node, flags) { + return !!getSelectedModifierFlags(node, flags); + } + ts.hasModifier = hasModifier; + function hasStaticModifier(node) { + return hasModifier(node, 32 /* Static */); + } + ts.hasStaticModifier = hasStaticModifier; + function hasReadonlyModifier(node) { + return hasModifier(node, 64 /* Readonly */); + } + ts.hasReadonlyModifier = hasReadonlyModifier; + function getSelectedModifierFlags(node, flags) { + return getModifierFlags(node) & flags; + } + ts.getSelectedModifierFlags = getSelectedModifierFlags; + function getModifierFlags(node) { + if (node.modifierFlagsCache & 536870912 /* HasComputedFlags */) { + return node.modifierFlagsCache & ~536870912 /* HasComputedFlags */; + } + var flags = getModifierFlagsNoCache(node); + node.modifierFlagsCache = flags | 536870912 /* HasComputedFlags */; + return flags; + } + ts.getModifierFlags = getModifierFlags; + function getModifierFlagsNoCache(node) { + var flags = 0 /* None */; + if (node.modifiers) { + for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) { + var modifier = _a[_i]; + flags |= modifierToFlag(modifier.kind); + } + } + if (node.flags & 4 /* NestedNamespace */ || (node.kind === 72 /* Identifier */ && node.isInJSDocNamespace)) { + flags |= 1 /* Export */; + } + return flags; + } + ts.getModifierFlagsNoCache = getModifierFlagsNoCache; + function modifierToFlag(token) { + switch (token) { + case 116 /* StaticKeyword */: return 32 /* Static */; + case 115 /* PublicKeyword */: return 4 /* Public */; + case 114 /* ProtectedKeyword */: return 16 /* Protected */; + case 113 /* PrivateKeyword */: return 8 /* Private */; + case 118 /* AbstractKeyword */: return 128 /* Abstract */; + case 85 /* ExportKeyword */: return 1 /* Export */; + case 125 /* DeclareKeyword */: return 2 /* Ambient */; + case 77 /* ConstKeyword */: return 2048 /* Const */; + case 80 /* DefaultKeyword */: return 512 /* Default */; + case 121 /* AsyncKeyword */: return 256 /* Async */; + case 133 /* ReadonlyKeyword */: return 64 /* Readonly */; + } + return 0 /* None */; + } + ts.modifierToFlag = modifierToFlag; + function isLogicalOperator(token) { + return token === 55 /* BarBarToken */ + || token === 54 /* AmpersandAmpersandToken */ + || token === 52 /* ExclamationToken */; + } + ts.isLogicalOperator = isLogicalOperator; + function isAssignmentOperator(token) { + return token >= 59 /* FirstAssignment */ && token <= 71 /* LastAssignment */; + } + ts.isAssignmentOperator = isAssignmentOperator; + /** Get `C` given `N` if `N` is in the position `class C extends N` where `N` is an ExpressionWithTypeArguments. */ + function tryGetClassExtendingExpressionWithTypeArguments(node) { + var cls = tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node); + return cls && !cls.isImplements ? cls.class : undefined; + } + ts.tryGetClassExtendingExpressionWithTypeArguments = tryGetClassExtendingExpressionWithTypeArguments; + function tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node) { + return ts.isExpressionWithTypeArguments(node) + && ts.isHeritageClause(node.parent) + && ts.isClassLike(node.parent.parent) + ? { class: node.parent.parent, isImplements: node.parent.token === 109 /* ImplementsKeyword */ } + : undefined; + } + ts.tryGetClassImplementingOrExtendingExpressionWithTypeArguments = tryGetClassImplementingOrExtendingExpressionWithTypeArguments; + function isAssignmentExpression(node, excludeCompoundAssignment) { + return ts.isBinaryExpression(node) + && (excludeCompoundAssignment + ? node.operatorToken.kind === 59 /* EqualsToken */ + : isAssignmentOperator(node.operatorToken.kind)) + && ts.isLeftHandSideExpression(node.left); + } + ts.isAssignmentExpression = isAssignmentExpression; + function isDestructuringAssignment(node) { + if (isAssignmentExpression(node, /*excludeCompoundAssignment*/ true)) { + var kind = node.left.kind; + return kind === 188 /* ObjectLiteralExpression */ + || kind === 187 /* ArrayLiteralExpression */; + } + return false; + } + ts.isDestructuringAssignment = isDestructuringAssignment; + function isExpressionWithTypeArgumentsInClassExtendsClause(node) { + return tryGetClassExtendingExpressionWithTypeArguments(node) !== undefined; + } + ts.isExpressionWithTypeArgumentsInClassExtendsClause = isExpressionWithTypeArgumentsInClassExtendsClause; + function isEntityNameExpression(node) { + return node.kind === 72 /* Identifier */ || isPropertyAccessEntityNameExpression(node); + } + ts.isEntityNameExpression = isEntityNameExpression; + function isPropertyAccessEntityNameExpression(node) { + return ts.isPropertyAccessExpression(node) && isEntityNameExpression(node.expression); + } + ts.isPropertyAccessEntityNameExpression = isPropertyAccessEntityNameExpression; + function isPrototypeAccess(node) { + return ts.isPropertyAccessExpression(node) && node.name.escapedText === "prototype"; + } + ts.isPrototypeAccess = isPrototypeAccess; + function isRightSideOfQualifiedNameOrPropertyAccess(node) { + return (node.parent.kind === 148 /* QualifiedName */ && node.parent.right === node) || + (node.parent.kind === 189 /* PropertyAccessExpression */ && node.parent.name === node); + } + ts.isRightSideOfQualifiedNameOrPropertyAccess = isRightSideOfQualifiedNameOrPropertyAccess; + function isEmptyObjectLiteral(expression) { + return expression.kind === 188 /* ObjectLiteralExpression */ && + expression.properties.length === 0; + } + ts.isEmptyObjectLiteral = isEmptyObjectLiteral; + function isEmptyArrayLiteral(expression) { + return expression.kind === 187 /* ArrayLiteralExpression */ && + expression.elements.length === 0; + } + ts.isEmptyArrayLiteral = isEmptyArrayLiteral; + function getLocalSymbolForExportDefault(symbol) { + return isExportDefaultSymbol(symbol) ? symbol.declarations[0].localSymbol : undefined; + } + ts.getLocalSymbolForExportDefault = getLocalSymbolForExportDefault; + function isExportDefaultSymbol(symbol) { + return symbol && ts.length(symbol.declarations) > 0 && hasModifier(symbol.declarations[0], 512 /* Default */); + } + /** Return ".ts", ".d.ts", or ".tsx", if that is the extension. */ + function tryExtractTSExtension(fileName) { + return ts.find(ts.supportedTSExtensionsForExtractExtension, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + } + ts.tryExtractTSExtension = tryExtractTSExtension; + /** + * Replace each instance of non-ascii characters by one, two, three, or four escape sequences + * representing the UTF-8 encoding of the character, and return the expanded char code list. + */ + function getExpandedCharCodes(input) { + var output = []; + var length = input.length; + for (var i = 0; i < length; i++) { + var charCode = input.charCodeAt(i); + // handle utf8 + if (charCode < 0x80) { + output.push(charCode); + } + else if (charCode < 0x800) { + output.push((charCode >> 6) | 192); + output.push((charCode & 63) | 128); + } + else if (charCode < 0x10000) { + output.push((charCode >> 12) | 224); + output.push(((charCode >> 6) & 63) | 128); + output.push((charCode & 63) | 128); + } + else if (charCode < 0x20000) { + output.push((charCode >> 18) | 240); + output.push(((charCode >> 12) & 63) | 128); + output.push(((charCode >> 6) & 63) | 128); + output.push((charCode & 63) | 128); + } + else { + ts.Debug.assert(false, "Unexpected code point"); + } + } + return output; + } + var base64Digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; + /** + * Converts a string to a base-64 encoded ASCII string. + */ + function convertToBase64(input) { + var result = ""; + var charCodes = getExpandedCharCodes(input); + var i = 0; + var length = charCodes.length; + var byte1, byte2, byte3, byte4; + while (i < length) { + // Convert every 6-bits in the input 3 character points + // into a base64 digit + byte1 = charCodes[i] >> 2; + byte2 = (charCodes[i] & 3) << 4 | charCodes[i + 1] >> 4; + byte3 = (charCodes[i + 1] & 15) << 2 | charCodes[i + 2] >> 6; + byte4 = charCodes[i + 2] & 63; + // We are out of characters in the input, set the extra + // digits to 64 (padding character). + if (i + 1 >= length) { + byte3 = byte4 = 64; + } + else if (i + 2 >= length) { + byte4 = 64; + } + // Write to the output + result += base64Digits.charAt(byte1) + base64Digits.charAt(byte2) + base64Digits.charAt(byte3) + base64Digits.charAt(byte4); + i += 3; + } + return result; + } + ts.convertToBase64 = convertToBase64; + function getStringFromExpandedCharCodes(codes) { + var output = ""; + var i = 0; + var length = codes.length; + while (i < length) { + var charCode = codes[i]; + if (charCode < 0x80) { + output += String.fromCharCode(charCode); + i++; + } + else if ((charCode & 192) === 192) { + var value = charCode & 63; + i++; + var nextCode = codes[i]; + while ((nextCode & 192) === 128) { + value = (value << 6) | (nextCode & 63); + i++; + nextCode = codes[i]; + } + // `value` may be greater than 10FFFF (the maximum unicode codepoint) - JS will just make this into an invalid character for us + output += String.fromCharCode(value); + } + else { + // We don't want to kill the process when decoding fails (due to a following char byte not + // following a leading char), so we just print the (bad) value + output += String.fromCharCode(charCode); + i++; + } + } + return output; + } + function base64encode(host, input) { + if (host && host.base64encode) { + return host.base64encode(input); + } + return convertToBase64(input); + } + ts.base64encode = base64encode; + function base64decode(host, input) { + if (host && host.base64decode) { + return host.base64decode(input); + } + var length = input.length; + var expandedCharCodes = []; + var i = 0; + while (i < length) { + // Stop decoding once padding characters are present + if (input.charCodeAt(i) === base64Digits.charCodeAt(64)) { + break; + } + // convert 4 input digits into three characters, ignoring padding characters at the end + var ch1 = base64Digits.indexOf(input[i]); + var ch2 = base64Digits.indexOf(input[i + 1]); + var ch3 = base64Digits.indexOf(input[i + 2]); + var ch4 = base64Digits.indexOf(input[i + 3]); + var code1 = ((ch1 & 63) << 2) | ((ch2 >> 4) & 3); + var code2 = ((ch2 & 15) << 4) | ((ch3 >> 2) & 15); + var code3 = ((ch3 & 3) << 6) | (ch4 & 63); + if (code2 === 0 && ch3 !== 0) { // code2 decoded to zero, but ch3 was padding - elide code2 and code3 + expandedCharCodes.push(code1); + } + else if (code3 === 0 && ch4 !== 0) { // code3 decoded to zero, but ch4 was padding, elide code3 + expandedCharCodes.push(code1, code2); + } + else { + expandedCharCodes.push(code1, code2, code3); + } + i += 4; + } + return getStringFromExpandedCharCodes(expandedCharCodes); + } + ts.base64decode = base64decode; + function readJson(path, host) { + try { + var jsonText = host.readFile(path); + if (!jsonText) + return {}; + var result = ts.parseConfigFileTextToJson(path, jsonText); + if (result.error) { + return {}; + } + return result.config; + } + catch (e) { + // gracefully handle if readFile fails or returns not JSON + return {}; + } + } + ts.readJson = readJson; + function directoryProbablyExists(directoryName, host) { + // if host does not support 'directoryExists' assume that directory will exist + return !host.directoryExists || host.directoryExists(directoryName); + } + ts.directoryProbablyExists = directoryProbablyExists; + var carriageReturnLineFeed = "\r\n"; + var lineFeed = "\n"; + function getNewLineCharacter(options, getNewLine) { + switch (options.newLine) { + case 0 /* CarriageReturnLineFeed */: + return carriageReturnLineFeed; + case 1 /* LineFeed */: + return lineFeed; + } + return getNewLine ? getNewLine() : ts.sys ? ts.sys.newLine : carriageReturnLineFeed; + } + ts.getNewLineCharacter = getNewLineCharacter; + /** + * Formats an enum value as a string for debugging and debug assertions. + */ + function formatEnum(value, enumObject, isFlags) { + if (value === void 0) { value = 0; } + var members = getEnumMembers(enumObject); + if (value === 0) { + return members.length > 0 && members[0][0] === 0 ? members[0][1] : "0"; + } + if (isFlags) { + var result = ""; + var remainingFlags = value; + for (var i = members.length - 1; i >= 0 && remainingFlags !== 0; i--) { + var _a = members[i], enumValue = _a[0], enumName = _a[1]; + if (enumValue !== 0 && (remainingFlags & enumValue) === enumValue) { + remainingFlags &= ~enumValue; + result = "" + enumName + (result ? ", " : "") + result; + } + } + if (remainingFlags === 0) { + return result; + } + } + else { + for (var _i = 0, members_1 = members; _i < members_1.length; _i++) { + var _b = members_1[_i], enumValue = _b[0], enumName = _b[1]; + if (enumValue === value) { + return enumName; + } + } + } + return value.toString(); + } + function getEnumMembers(enumObject) { + var result = []; + for (var name in enumObject) { + var value = enumObject[name]; + if (typeof value === "number") { + result.push([value, name]); + } + } + return ts.stableSort(result, function (x, y) { return ts.compareValues(x[0], y[0]); }); + } + function formatSyntaxKind(kind) { + return formatEnum(kind, ts.SyntaxKind, /*isFlags*/ false); + } + ts.formatSyntaxKind = formatSyntaxKind; + function formatModifierFlags(flags) { + return formatEnum(flags, ts.ModifierFlags, /*isFlags*/ true); + } + ts.formatModifierFlags = formatModifierFlags; + function formatTransformFlags(flags) { + return formatEnum(flags, ts.TransformFlags, /*isFlags*/ true); + } + ts.formatTransformFlags = formatTransformFlags; + function formatEmitFlags(flags) { + return formatEnum(flags, ts.EmitFlags, /*isFlags*/ true); + } + ts.formatEmitFlags = formatEmitFlags; + function formatSymbolFlags(flags) { + return formatEnum(flags, ts.SymbolFlags, /*isFlags*/ true); + } + ts.formatSymbolFlags = formatSymbolFlags; + function formatTypeFlags(flags) { + return formatEnum(flags, ts.TypeFlags, /*isFlags*/ true); + } + ts.formatTypeFlags = formatTypeFlags; + function formatObjectFlags(flags) { + return formatEnum(flags, ts.ObjectFlags, /*isFlags*/ true); + } + ts.formatObjectFlags = formatObjectFlags; + /** + * Creates a new TextRange from the provided pos and end. + * + * @param pos The start position. + * @param end The end position. + */ + function createRange(pos, end) { + if (end === void 0) { end = pos; } + ts.Debug.assert(end >= pos || end === -1); + return { pos: pos, end: end }; + } + ts.createRange = createRange; + /** + * Creates a new TextRange from a provided range with a new end position. + * + * @param range A TextRange. + * @param end The new end position. + */ + function moveRangeEnd(range, end) { + return createRange(range.pos, end); + } + ts.moveRangeEnd = moveRangeEnd; + /** + * Creates a new TextRange from a provided range with a new start position. + * + * @param range A TextRange. + * @param pos The new Start position. + */ + function moveRangePos(range, pos) { + return createRange(pos, range.end); + } + ts.moveRangePos = moveRangePos; + /** + * Moves the start position of a range past any decorators. + */ + function moveRangePastDecorators(node) { + return node.decorators && node.decorators.length > 0 + ? moveRangePos(node, node.decorators.end) + : node; + } + ts.moveRangePastDecorators = moveRangePastDecorators; + /** + * Moves the start position of a range past any decorators or modifiers. + */ + function moveRangePastModifiers(node) { + return node.modifiers && node.modifiers.length > 0 + ? moveRangePos(node, node.modifiers.end) + : moveRangePastDecorators(node); + } + ts.moveRangePastModifiers = moveRangePastModifiers; + /** + * Determines whether a TextRange has the same start and end positions. + * + * @param range A TextRange. + */ + function isCollapsedRange(range) { + return range.pos === range.end; + } + ts.isCollapsedRange = isCollapsedRange; + /** + * Creates a new TextRange for a token at the provides start position. + * + * @param pos The start position. + * @param token The token. + */ + function createTokenRange(pos, token) { + return createRange(pos, pos + ts.tokenToString(token).length); + } + ts.createTokenRange = createTokenRange; + function rangeIsOnSingleLine(range, sourceFile) { + return rangeStartIsOnSameLineAsRangeEnd(range, range, sourceFile); + } + ts.rangeIsOnSingleLine = rangeIsOnSingleLine; + function rangeStartPositionsAreOnSameLine(range1, range2, sourceFile) { + return positionsAreOnSameLine(getStartPositionOfRange(range1, sourceFile), getStartPositionOfRange(range2, sourceFile), sourceFile); + } + ts.rangeStartPositionsAreOnSameLine = rangeStartPositionsAreOnSameLine; + function rangeEndPositionsAreOnSameLine(range1, range2, sourceFile) { + return positionsAreOnSameLine(range1.end, range2.end, sourceFile); + } + ts.rangeEndPositionsAreOnSameLine = rangeEndPositionsAreOnSameLine; + function rangeStartIsOnSameLineAsRangeEnd(range1, range2, sourceFile) { + return positionsAreOnSameLine(getStartPositionOfRange(range1, sourceFile), range2.end, sourceFile); + } + ts.rangeStartIsOnSameLineAsRangeEnd = rangeStartIsOnSameLineAsRangeEnd; + function rangeEndIsOnSameLineAsRangeStart(range1, range2, sourceFile) { + return positionsAreOnSameLine(range1.end, getStartPositionOfRange(range2, sourceFile), sourceFile); + } + ts.rangeEndIsOnSameLineAsRangeStart = rangeEndIsOnSameLineAsRangeStart; + function positionsAreOnSameLine(pos1, pos2, sourceFile) { + return pos1 === pos2 || + getLineOfLocalPosition(sourceFile, pos1) === getLineOfLocalPosition(sourceFile, pos2); + } + ts.positionsAreOnSameLine = positionsAreOnSameLine; + function getStartPositionOfRange(range, sourceFile) { + return ts.positionIsSynthesized(range.pos) ? -1 : ts.skipTrivia(sourceFile.text, range.pos); + } + ts.getStartPositionOfRange = getStartPositionOfRange; + /** + * Determines whether a name was originally the declaration name of an enum or namespace + * declaration. + */ + function isDeclarationNameOfEnumOrNamespace(node) { + var parseNode = ts.getParseTreeNode(node); + if (parseNode) { + switch (parseNode.parent.kind) { + case 243 /* EnumDeclaration */: + case 244 /* ModuleDeclaration */: + return parseNode === parseNode.parent.name; + } + } + return false; + } + ts.isDeclarationNameOfEnumOrNamespace = isDeclarationNameOfEnumOrNamespace; + function getInitializedVariables(node) { + return ts.filter(node.declarations, isInitializedVariable); + } + ts.getInitializedVariables = getInitializedVariables; + function isInitializedVariable(node) { + return node.initializer !== undefined; + } + function isWatchSet(options) { + // Firefox has Object.prototype.watch + return options.watch && options.hasOwnProperty("watch"); + } + ts.isWatchSet = isWatchSet; + function closeFileWatcher(watcher) { + watcher.close(); + } + ts.closeFileWatcher = closeFileWatcher; + function getCheckFlags(symbol) { + return symbol.flags & 33554432 /* Transient */ ? symbol.checkFlags : 0; + } + ts.getCheckFlags = getCheckFlags; + function getDeclarationModifierFlagsFromSymbol(s) { + if (s.valueDeclaration) { + var flags = ts.getCombinedModifierFlags(s.valueDeclaration); + return s.parent && s.parent.flags & 32 /* Class */ ? flags : flags & ~28 /* AccessibilityModifier */; + } + if (getCheckFlags(s) & 6 /* Synthetic */) { + var checkFlags = s.checkFlags; + var accessModifier = checkFlags & 256 /* ContainsPrivate */ ? 8 /* Private */ : + checkFlags & 64 /* ContainsPublic */ ? 4 /* Public */ : + 16 /* Protected */; + var staticModifier = checkFlags & 512 /* ContainsStatic */ ? 32 /* Static */ : 0; + return accessModifier | staticModifier; + } + if (s.flags & 4194304 /* Prototype */) { + return 4 /* Public */ | 32 /* Static */; + } + return 0; + } + ts.getDeclarationModifierFlagsFromSymbol = getDeclarationModifierFlagsFromSymbol; + function skipAlias(symbol, checker) { + return symbol.flags & 2097152 /* Alias */ ? checker.getAliasedSymbol(symbol) : symbol; + } + ts.skipAlias = skipAlias; + /** See comment on `declareModuleMember` in `binder.ts`. */ + function getCombinedLocalAndExportSymbolFlags(symbol) { + return symbol.exportSymbol ? symbol.exportSymbol.flags | symbol.flags : symbol.flags; + } + ts.getCombinedLocalAndExportSymbolFlags = getCombinedLocalAndExportSymbolFlags; + function isWriteOnlyAccess(node) { + return accessKind(node) === 1 /* Write */; + } + ts.isWriteOnlyAccess = isWriteOnlyAccess; + function isWriteAccess(node) { + return accessKind(node) !== 0 /* Read */; + } + ts.isWriteAccess = isWriteAccess; + var AccessKind; + (function (AccessKind) { + /** Only reads from a variable. */ + AccessKind[AccessKind["Read"] = 0] = "Read"; + /** Only writes to a variable without using the result. E.g.: `x++;`. */ + AccessKind[AccessKind["Write"] = 1] = "Write"; + /** Writes to a variable and uses the result as an expression. E.g.: `f(x++);`. */ + AccessKind[AccessKind["ReadWrite"] = 2] = "ReadWrite"; + })(AccessKind || (AccessKind = {})); + function accessKind(node) { + var parent = node.parent; + if (!parent) + return 0 /* Read */; + switch (parent.kind) { + case 195 /* ParenthesizedExpression */: + return accessKind(parent); + case 203 /* PostfixUnaryExpression */: + case 202 /* PrefixUnaryExpression */: + var operator = parent.operator; + return operator === 44 /* PlusPlusToken */ || operator === 45 /* MinusMinusToken */ ? writeOrReadWrite() : 0 /* Read */; + case 204 /* BinaryExpression */: + var _a = parent, left = _a.left, operatorToken = _a.operatorToken; + return left === node && isAssignmentOperator(operatorToken.kind) ? + operatorToken.kind === 59 /* EqualsToken */ ? 1 /* Write */ : writeOrReadWrite() + : 0 /* Read */; + case 189 /* PropertyAccessExpression */: + return parent.name !== node ? 0 /* Read */ : accessKind(parent); + case 275 /* PropertyAssignment */: { + var parentAccess = accessKind(parent.parent); + // In `({ x: varname }) = { x: 1 }`, the left `x` is a read, the right `x` is a write. + return node === parent.name ? reverseAccessKind(parentAccess) : parentAccess; + } + case 276 /* ShorthandPropertyAssignment */: + // Assume it's the local variable being accessed, since we don't check public properties for --noUnusedLocals. + return node === parent.objectAssignmentInitializer ? 0 /* Read */ : accessKind(parent.parent); + case 187 /* ArrayLiteralExpression */: + return accessKind(parent); + default: + return 0 /* Read */; + } + function writeOrReadWrite() { + // If grandparent is not an ExpressionStatement, this is used as an expression in addition to having a side effect. + return parent.parent && skipParenthesesUp(parent.parent).kind === 221 /* ExpressionStatement */ ? 1 /* Write */ : 2 /* ReadWrite */; + } + } + function reverseAccessKind(a) { + switch (a) { + case 0 /* Read */: + return 1 /* Write */; + case 1 /* Write */: + return 0 /* Read */; + case 2 /* ReadWrite */: + return 2 /* ReadWrite */; + default: + return ts.Debug.assertNever(a); + } + } + function compareDataObjects(dst, src) { + if (!dst || !src || Object.keys(dst).length !== Object.keys(src).length) { + return false; + } + for (var e in dst) { + if (typeof dst[e] === "object") { + if (!compareDataObjects(dst[e], src[e])) { + return false; + } + } + else if (typeof dst[e] !== "function") { + if (dst[e] !== src[e]) { + return false; + } + } + } + return true; + } + ts.compareDataObjects = compareDataObjects; + /** + * clears already present map by calling onDeleteExistingValue callback before deleting that key/value + */ + function clearMap(map, onDeleteValue) { + // Remove all + map.forEach(onDeleteValue); + map.clear(); + } + ts.clearMap = clearMap; + /** + * Mutates the map with newMap such that keys in map will be same as newMap. + */ + function mutateMap(map, newMap, options) { + var createNewValue = options.createNewValue, onDeleteValue = options.onDeleteValue, onExistingValue = options.onExistingValue; + // Needs update + map.forEach(function (existingValue, key) { + var valueInNewMap = newMap.get(key); + // Not present any more in new map, remove it + if (valueInNewMap === undefined) { + map.delete(key); + onDeleteValue(existingValue, key); + } + // If present notify about existing values + else if (onExistingValue) { + onExistingValue(existingValue, valueInNewMap, key); + } + }); + // Add new values that are not already present + newMap.forEach(function (valueInNewMap, key) { + if (!map.has(key)) { + // New values + map.set(key, createNewValue(key, valueInNewMap)); + } + }); + } + ts.mutateMap = mutateMap; + /** Calls `callback` on `directory` and every ancestor directory it has, returning the first defined result. */ + function forEachAncestorDirectory(directory, callback) { + while (true) { + var result = callback(directory); + if (result !== undefined) { + return result; + } + var parentPath = ts.getDirectoryPath(directory); + if (parentPath === directory) { + return undefined; + } + directory = parentPath; + } + } + ts.forEachAncestorDirectory = forEachAncestorDirectory; + // Return true if the given type is the constructor type for an abstract class + function isAbstractConstructorType(type) { + return !!(getObjectFlags(type) & 16 /* Anonymous */) && !!type.symbol && isAbstractConstructorSymbol(type.symbol); + } + ts.isAbstractConstructorType = isAbstractConstructorType; + function isAbstractConstructorSymbol(symbol) { + if (symbol.flags & 32 /* Class */) { + var declaration = getClassLikeDeclarationOfSymbol(symbol); + return !!declaration && hasModifier(declaration, 128 /* Abstract */); + } + return false; + } + ts.isAbstractConstructorSymbol = isAbstractConstructorSymbol; + function getClassLikeDeclarationOfSymbol(symbol) { + return ts.find(symbol.declarations, ts.isClassLike); + } + ts.getClassLikeDeclarationOfSymbol = getClassLikeDeclarationOfSymbol; + function getObjectFlags(type) { + return type.flags & 524288 /* Object */ ? type.objectFlags : 0; + } + ts.getObjectFlags = getObjectFlags; + function typeHasCallOrConstructSignatures(type, checker) { + return checker.getSignaturesOfType(type, 0 /* Call */).length !== 0 || checker.getSignaturesOfType(type, 1 /* Construct */).length !== 0; + } + ts.typeHasCallOrConstructSignatures = typeHasCallOrConstructSignatures; + function forSomeAncestorDirectory(directory, callback) { + return !!forEachAncestorDirectory(directory, function (d) { return callback(d) ? true : undefined; }); + } + ts.forSomeAncestorDirectory = forSomeAncestorDirectory; + function isUMDExportSymbol(symbol) { + return !!symbol && !!symbol.declarations && !!symbol.declarations[0] && ts.isNamespaceExportDeclaration(symbol.declarations[0]); + } + ts.isUMDExportSymbol = isUMDExportSymbol; + function showModuleSpecifier(_a) { + var moduleSpecifier = _a.moduleSpecifier; + return ts.isStringLiteral(moduleSpecifier) ? moduleSpecifier.text : getTextOfNode(moduleSpecifier); + } + ts.showModuleSpecifier = showModuleSpecifier; + function getLastChild(node) { + var lastChild; + ts.forEachChild(node, function (child) { + if (nodeIsPresent(child)) + lastChild = child; + }, function (children) { + // As an optimization, jump straight to the end of the list. + for (var i = children.length - 1; i >= 0; i--) { + if (nodeIsPresent(children[i])) { + lastChild = children[i]; + break; + } + } + }); + return lastChild; + } + ts.getLastChild = getLastChild; + function addToSeen(seen, key, value) { + if (value === void 0) { value = true; } + key = String(key); + if (seen.has(key)) { + return false; + } + seen.set(key, value); + return true; + } + ts.addToSeen = addToSeen; + function isObjectTypeDeclaration(node) { + return ts.isClassLike(node) || ts.isInterfaceDeclaration(node) || ts.isTypeLiteralNode(node); + } + ts.isObjectTypeDeclaration = isObjectTypeDeclaration; + function isTypeNodeKind(kind) { + return (kind >= 163 /* FirstTypeNode */ && kind <= 183 /* LastTypeNode */) + || kind === 120 /* AnyKeyword */ + || kind === 143 /* UnknownKeyword */ + || kind === 135 /* NumberKeyword */ + || kind === 146 /* BigIntKeyword */ + || kind === 136 /* ObjectKeyword */ + || kind === 123 /* BooleanKeyword */ + || kind === 138 /* StringKeyword */ + || kind === 139 /* SymbolKeyword */ + || kind === 100 /* ThisKeyword */ + || kind === 106 /* VoidKeyword */ + || kind === 141 /* UndefinedKeyword */ + || kind === 96 /* NullKeyword */ + || kind === 132 /* NeverKeyword */ + || kind === 211 /* ExpressionWithTypeArguments */ + || kind === 284 /* JSDocAllType */ + || kind === 285 /* JSDocUnknownType */ + || kind === 286 /* JSDocNullableType */ + || kind === 287 /* JSDocNonNullableType */ + || kind === 288 /* JSDocOptionalType */ + || kind === 289 /* JSDocFunctionType */ + || kind === 290 /* JSDocVariadicType */; + } + ts.isTypeNodeKind = isTypeNodeKind; +})(ts || (ts = {})); +(function (ts) { + function getDefaultLibFileName(options) { + switch (options.target) { + case 6 /* ESNext */: + return "lib.esnext.full.d.ts"; + case 5 /* ES2018 */: + return "lib.es2018.full.d.ts"; + case 4 /* ES2017 */: + return "lib.es2017.full.d.ts"; + case 3 /* ES2016 */: + return "lib.es2016.full.d.ts"; + case 2 /* ES2015 */: + return "lib.es6.d.ts"; // We don't use lib.es2015.full.d.ts due to breaking change. + default: + return "lib.d.ts"; + } + } + ts.getDefaultLibFileName = getDefaultLibFileName; + function textSpanEnd(span) { + return span.start + span.length; + } + ts.textSpanEnd = textSpanEnd; + function textSpanIsEmpty(span) { + return span.length === 0; + } + ts.textSpanIsEmpty = textSpanIsEmpty; + function textSpanContainsPosition(span, position) { + return position >= span.start && position < textSpanEnd(span); + } + ts.textSpanContainsPosition = textSpanContainsPosition; + /* @internal */ + function textRangeContainsPositionInclusive(span, position) { + return position >= span.pos && position <= span.end; + } + ts.textRangeContainsPositionInclusive = textRangeContainsPositionInclusive; + // Returns true if 'span' contains 'other'. + function textSpanContainsTextSpan(span, other) { + return other.start >= span.start && textSpanEnd(other) <= textSpanEnd(span); + } + ts.textSpanContainsTextSpan = textSpanContainsTextSpan; + function textSpanOverlapsWith(span, other) { + return textSpanOverlap(span, other) !== undefined; + } + ts.textSpanOverlapsWith = textSpanOverlapsWith; + function textSpanOverlap(span1, span2) { + var overlap = textSpanIntersection(span1, span2); + return overlap && overlap.length === 0 ? undefined : overlap; + } + ts.textSpanOverlap = textSpanOverlap; + function textSpanIntersectsWithTextSpan(span, other) { + return decodedTextSpanIntersectsWith(span.start, span.length, other.start, other.length); + } + ts.textSpanIntersectsWithTextSpan = textSpanIntersectsWithTextSpan; + function textSpanIntersectsWith(span, start, length) { + return decodedTextSpanIntersectsWith(span.start, span.length, start, length); + } + ts.textSpanIntersectsWith = textSpanIntersectsWith; + function decodedTextSpanIntersectsWith(start1, length1, start2, length2) { + var end1 = start1 + length1; + var end2 = start2 + length2; + return start2 <= end1 && end2 >= start1; + } + ts.decodedTextSpanIntersectsWith = decodedTextSpanIntersectsWith; + function textSpanIntersectsWithPosition(span, position) { + return position <= textSpanEnd(span) && position >= span.start; + } + ts.textSpanIntersectsWithPosition = textSpanIntersectsWithPosition; + function textSpanIntersection(span1, span2) { + var start = Math.max(span1.start, span2.start); + var end = Math.min(textSpanEnd(span1), textSpanEnd(span2)); + return start <= end ? createTextSpanFromBounds(start, end) : undefined; + } + ts.textSpanIntersection = textSpanIntersection; + function createTextSpan(start, length) { + if (start < 0) { + throw new Error("start < 0"); + } + if (length < 0) { + throw new Error("length < 0"); + } + return { start: start, length: length }; + } + ts.createTextSpan = createTextSpan; + function createTextSpanFromBounds(start, end) { + return createTextSpan(start, end - start); + } + ts.createTextSpanFromBounds = createTextSpanFromBounds; + function textChangeRangeNewSpan(range) { + return createTextSpan(range.span.start, range.newLength); + } + ts.textChangeRangeNewSpan = textChangeRangeNewSpan; + function textChangeRangeIsUnchanged(range) { + return textSpanIsEmpty(range.span) && range.newLength === 0; + } + ts.textChangeRangeIsUnchanged = textChangeRangeIsUnchanged; + function createTextChangeRange(span, newLength) { + if (newLength < 0) { + throw new Error("newLength < 0"); + } + return { span: span, newLength: newLength }; + } + ts.createTextChangeRange = createTextChangeRange; + ts.unchangedTextChangeRange = createTextChangeRange(createTextSpan(0, 0), 0); + /** + * Called to merge all the changes that occurred across several versions of a script snapshot + * into a single change. i.e. if a user keeps making successive edits to a script we will + * have a text change from V1 to V2, V2 to V3, ..., Vn. + * + * This function will then merge those changes into a single change range valid between V1 and + * Vn. + */ + function collapseTextChangeRangesAcrossMultipleVersions(changes) { + if (changes.length === 0) { + return ts.unchangedTextChangeRange; + } + if (changes.length === 1) { + return changes[0]; + } + // We change from talking about { { oldStart, oldLength }, newLength } to { oldStart, oldEnd, newEnd } + // as it makes things much easier to reason about. + var change0 = changes[0]; + var oldStartN = change0.span.start; + var oldEndN = textSpanEnd(change0.span); + var newEndN = oldStartN + change0.newLength; + for (var i = 1; i < changes.length; i++) { + var nextChange = changes[i]; + // Consider the following case: + // i.e. two edits. The first represents the text change range { { 10, 50 }, 30 }. i.e. The span starting + // at 10, with length 50 is reduced to length 30. The second represents the text change range { { 30, 30 }, 40 }. + // i.e. the span starting at 30 with length 30 is increased to length 40. + // + // 0 10 20 30 40 50 60 70 80 90 100 + // ------------------------------------------------------------------------------------------------------- + // | / + // | /---- + // T1 | /---- + // | /---- + // | /---- + // ------------------------------------------------------------------------------------------------------- + // | \ + // | \ + // T2 | \ + // | \ + // | \ + // ------------------------------------------------------------------------------------------------------- + // + // Merging these turns out to not be too difficult. First, determining the new start of the change is trivial + // it's just the min of the old and new starts. i.e.: + // + // 0 10 20 30 40 50 60 70 80 90 100 + // ------------------------------------------------------------*------------------------------------------ + // | / + // | /---- + // T1 | /---- + // | /---- + // | /---- + // ----------------------------------------$-------------------$------------------------------------------ + // . | \ + // . | \ + // T2 . | \ + // . | \ + // . | \ + // ----------------------------------------------------------------------*-------------------------------- + // + // (Note the dots represent the newly inferred start. + // Determining the new and old end is also pretty simple. Basically it boils down to paying attention to the + // absolute positions at the asterisks, and the relative change between the dollar signs. Basically, we see + // which if the two $'s precedes the other, and we move that one forward until they line up. in this case that + // means: + // + // 0 10 20 30 40 50 60 70 80 90 100 + // --------------------------------------------------------------------------------*---------------------- + // | / + // | /---- + // T1 | /---- + // | /---- + // | /---- + // ------------------------------------------------------------$------------------------------------------ + // . | \ + // . | \ + // T2 . | \ + // . | \ + // . | \ + // ----------------------------------------------------------------------*-------------------------------- + // + // In other words (in this case), we're recognizing that the second edit happened after where the first edit + // ended with a delta of 20 characters (60 - 40). Thus, if we go back in time to where the first edit started + // that's the same as if we started at char 80 instead of 60. + // + // As it so happens, the same logic applies if the second edit precedes the first edit. In that case rather + // than pushing the first edit forward to match the second, we'll push the second edit forward to match the + // first. + // + // In this case that means we have { oldStart: 10, oldEnd: 80, newEnd: 70 } or, in TextChangeRange + // semantics: { { start: 10, length: 70 }, newLength: 60 } + // + // The math then works out as follows. + // If we have { oldStart1, oldEnd1, newEnd1 } and { oldStart2, oldEnd2, newEnd2 } then we can compute the + // final result like so: + // + // { + // oldStart3: Min(oldStart1, oldStart2), + // oldEnd3: Max(oldEnd1, oldEnd1 + (oldEnd2 - newEnd1)), + // newEnd3: Max(newEnd2, newEnd2 + (newEnd1 - oldEnd2)) + // } + var oldStart1 = oldStartN; + var oldEnd1 = oldEndN; + var newEnd1 = newEndN; + var oldStart2 = nextChange.span.start; + var oldEnd2 = textSpanEnd(nextChange.span); + var newEnd2 = oldStart2 + nextChange.newLength; + oldStartN = Math.min(oldStart1, oldStart2); + oldEndN = Math.max(oldEnd1, oldEnd1 + (oldEnd2 - newEnd1)); + newEndN = Math.max(newEnd2, newEnd2 + (newEnd1 - oldEnd2)); + } + return createTextChangeRange(createTextSpanFromBounds(oldStartN, oldEndN), /*newLength*/ newEndN - oldStartN); + } + ts.collapseTextChangeRangesAcrossMultipleVersions = collapseTextChangeRangesAcrossMultipleVersions; + function getTypeParameterOwner(d) { + if (d && d.kind === 150 /* TypeParameter */) { + for (var current = d; current; current = current.parent) { + if (ts.isFunctionLike(current) || ts.isClassLike(current) || current.kind === 241 /* InterfaceDeclaration */) { + return current; + } + } + } + } + ts.getTypeParameterOwner = getTypeParameterOwner; + function isParameterPropertyDeclaration(node) { + return ts.hasModifier(node, 92 /* ParameterPropertyModifier */) && node.parent.kind === 157 /* Constructor */; + } + ts.isParameterPropertyDeclaration = isParameterPropertyDeclaration; + function isEmptyBindingPattern(node) { + if (ts.isBindingPattern(node)) { + return ts.every(node.elements, isEmptyBindingElement); + } + return false; + } + ts.isEmptyBindingPattern = isEmptyBindingPattern; + function isEmptyBindingElement(node) { + if (ts.isOmittedExpression(node)) { + return true; + } + return isEmptyBindingPattern(node.name); + } + ts.isEmptyBindingElement = isEmptyBindingElement; + function walkUpBindingElementsAndPatterns(binding) { + var node = binding.parent; + while (ts.isBindingElement(node.parent)) { + node = node.parent.parent; + } + return node.parent; + } + ts.walkUpBindingElementsAndPatterns = walkUpBindingElementsAndPatterns; + function getCombinedFlags(node, getFlags) { + if (ts.isBindingElement(node)) { + node = walkUpBindingElementsAndPatterns(node); + } + var flags = getFlags(node); + if (node.kind === 237 /* VariableDeclaration */) { + node = node.parent; + } + if (node && node.kind === 238 /* VariableDeclarationList */) { + flags |= getFlags(node); + node = node.parent; + } + if (node && node.kind === 219 /* VariableStatement */) { + flags |= getFlags(node); + } + return flags; + } + function getCombinedModifierFlags(node) { + return getCombinedFlags(node, ts.getModifierFlags); + } + ts.getCombinedModifierFlags = getCombinedModifierFlags; + // Returns the node flags for this node and all relevant parent nodes. This is done so that + // nodes like variable declarations and binding elements can returned a view of their flags + // that includes the modifiers from their container. i.e. flags like export/declare aren't + // stored on the variable declaration directly, but on the containing variable statement + // (if it has one). Similarly, flags for let/const are store on the variable declaration + // list. By calling this function, all those flags are combined so that the client can treat + // the node as if it actually had those flags. + function getCombinedNodeFlags(node) { + return getCombinedFlags(node, function (n) { return n.flags; }); + } + ts.getCombinedNodeFlags = getCombinedNodeFlags; + /** + * Checks to see if the locale is in the appropriate format, + * and if it is, attempts to set the appropriate language. + */ + function validateLocaleAndSetLanguage(locale, sys, errors) { + var matchResult = /^([a-z]+)([_\-]([a-z]+))?$/.exec(locale.toLowerCase()); + if (!matchResult) { + if (errors) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1, "en", "ja-jp")); + } + return; + } + var language = matchResult[1]; + var territory = matchResult[3]; + // First try the entire locale, then fall back to just language if that's all we have. + // Either ways do not fail, and fallback to the English diagnostic strings. + if (!trySetLanguageAndTerritory(language, territory, errors)) { + trySetLanguageAndTerritory(language, /*territory*/ undefined, errors); + } + // Set the UI locale for string collation + ts.setUILocale(locale); + function trySetLanguageAndTerritory(language, territory, errors) { + var compilerFilePath = ts.normalizePath(sys.getExecutingFilePath()); + var containingDirectoryPath = ts.getDirectoryPath(compilerFilePath); + var filePath = ts.combinePaths(containingDirectoryPath, language); + if (territory) { + filePath = filePath + "-" + territory; + } + filePath = sys.resolvePath(ts.combinePaths(filePath, "diagnosticMessages.generated.json")); + if (!sys.fileExists(filePath)) { + return false; + } + // TODO: Add codePage support for readFile? + var fileContents = ""; + try { + fileContents = sys.readFile(filePath); + } + catch (e) { + if (errors) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unable_to_open_file_0, filePath)); + } + return false; + } + try { + // tslint:disable-next-line no-unnecessary-qualifier (making clear this is a global mutation!) + ts.localizedDiagnosticMessages = JSON.parse(fileContents); + } + catch (_a) { + if (errors) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Corrupted_locale_file_0, filePath)); + } + return false; + } + return true; + } + } + ts.validateLocaleAndSetLanguage = validateLocaleAndSetLanguage; + function getOriginalNode(node, nodeTest) { + if (node) { + while (node.original !== undefined) { + node = node.original; + } + } + return !nodeTest || nodeTest(node) ? node : undefined; + } + ts.getOriginalNode = getOriginalNode; + /** + * Gets a value indicating whether a node originated in the parse tree. + * + * @param node The node to test. + */ + function isParseTreeNode(node) { + return (node.flags & 8 /* Synthesized */) === 0; + } + ts.isParseTreeNode = isParseTreeNode; + function getParseTreeNode(node, nodeTest) { + if (node === undefined || isParseTreeNode(node)) { + return node; + } + node = getOriginalNode(node); + if (isParseTreeNode(node) && (!nodeTest || nodeTest(node))) { + return node; + } + return undefined; + } + ts.getParseTreeNode = getParseTreeNode; + /** Add an extra underscore to identifiers that start with two underscores to avoid issues with magic names like '__proto__' */ + function escapeLeadingUnderscores(identifier) { + return (identifier.length >= 2 && identifier.charCodeAt(0) === 95 /* _ */ && identifier.charCodeAt(1) === 95 /* _ */ ? "_" + identifier : identifier); + } + ts.escapeLeadingUnderscores = escapeLeadingUnderscores; + /** + * Remove extra underscore from escaped identifier text content. + * + * @param identifier The escaped identifier text. + * @returns The unescaped identifier text. + */ + function unescapeLeadingUnderscores(identifier) { + var id = identifier; + return id.length >= 3 && id.charCodeAt(0) === 95 /* _ */ && id.charCodeAt(1) === 95 /* _ */ && id.charCodeAt(2) === 95 /* _ */ ? id.substr(1) : id; + } + ts.unescapeLeadingUnderscores = unescapeLeadingUnderscores; + function idText(identifier) { + return unescapeLeadingUnderscores(identifier.escapedText); + } + ts.idText = idText; + function symbolName(symbol) { + return unescapeLeadingUnderscores(symbol.escapedName); + } + ts.symbolName = symbolName; + /** + * A JSDocTypedef tag has an _optional_ name field - if a name is not directly present, we should + * attempt to draw the name from the node the declaration is on (as that declaration is what its' symbol + * will be merged with) + */ + function nameForNamelessJSDocTypedef(declaration) { + var hostNode = declaration.parent.parent; + if (!hostNode) { + return undefined; + } + // Covers classes, functions - any named declaration host node + if (ts.isDeclaration(hostNode)) { + return getDeclarationIdentifier(hostNode); + } + // Covers remaining cases (returning undefined if none match). + switch (hostNode.kind) { + case 219 /* VariableStatement */: + if (hostNode.declarationList && hostNode.declarationList.declarations[0]) { + return getDeclarationIdentifier(hostNode.declarationList.declarations[0]); + } + break; + case 221 /* ExpressionStatement */: + var expr = hostNode.expression; + switch (expr.kind) { + case 189 /* PropertyAccessExpression */: + return expr.name; + case 190 /* ElementAccessExpression */: + var arg = expr.argumentExpression; + if (ts.isIdentifier(arg)) { + return arg; + } + } + break; + case 195 /* ParenthesizedExpression */: { + return getDeclarationIdentifier(hostNode.expression); + } + case 233 /* LabeledStatement */: { + if (ts.isDeclaration(hostNode.statement) || ts.isExpression(hostNode.statement)) { + return getDeclarationIdentifier(hostNode.statement); + } + break; + } + } + } + function getDeclarationIdentifier(node) { + var name = getNameOfDeclaration(node); + return name && ts.isIdentifier(name) ? name : undefined; + } + function getNameOfJSDocTypedef(declaration) { + return declaration.name || nameForNamelessJSDocTypedef(declaration); + } + ts.getNameOfJSDocTypedef = getNameOfJSDocTypedef; + /** @internal */ + function isNamedDeclaration(node) { + return !!node.name; // A 'name' property should always be a DeclarationName. + } + ts.isNamedDeclaration = isNamedDeclaration; + /** @internal */ + function getNonAssignedNameOfDeclaration(declaration) { + switch (declaration.kind) { + case 72 /* Identifier */: + return declaration; + case 305 /* JSDocPropertyTag */: + case 299 /* JSDocParameterTag */: { + var name = declaration.name; + if (name.kind === 148 /* QualifiedName */) { + return name.right; + } + break; + } + case 191 /* CallExpression */: + case 204 /* BinaryExpression */: { + var expr = declaration; + switch (ts.getAssignmentDeclarationKind(expr)) { + case 1 /* ExportsProperty */: + case 4 /* ThisProperty */: + case 5 /* Property */: + case 3 /* PrototypeProperty */: + return expr.left.name; + case 7 /* ObjectDefinePropertyValue */: + case 8 /* ObjectDefinePropertyExports */: + case 9 /* ObjectDefinePrototypeProperty */: + return expr.arguments[1]; + default: + return undefined; + } + } + case 304 /* JSDocTypedefTag */: + return getNameOfJSDocTypedef(declaration); + case 254 /* ExportAssignment */: { + var expression = declaration.expression; + return ts.isIdentifier(expression) ? expression : undefined; + } + } + return declaration.name; + } + ts.getNonAssignedNameOfDeclaration = getNonAssignedNameOfDeclaration; + function getNameOfDeclaration(declaration) { + if (declaration === undefined) + return undefined; + return getNonAssignedNameOfDeclaration(declaration) || + (ts.isFunctionExpression(declaration) || ts.isClassExpression(declaration) ? getAssignedName(declaration) : undefined); + } + ts.getNameOfDeclaration = getNameOfDeclaration; + function getAssignedName(node) { + if (!node.parent) { + return undefined; + } + else if (ts.isPropertyAssignment(node.parent) || ts.isBindingElement(node.parent)) { + return node.parent.name; + } + else if (ts.isBinaryExpression(node.parent) && node === node.parent.right) { + if (ts.isIdentifier(node.parent.left)) { + return node.parent.left; + } + else if (ts.isPropertyAccessExpression(node.parent.left)) { + return node.parent.left.name; + } + } + } + /** + * Gets the JSDoc parameter tags for the node if present. + * + * @remarks Returns any JSDoc param tag whose name matches the provided + * parameter, whether a param tag on a containing function + * expression, or a param tag on a variable declaration whose + * initializer is the containing function. The tags closest to the + * node are returned first, so in the previous example, the param + * tag on the containing function expression would be first. + * + * For binding patterns, parameter tags are matched by position. + */ + function getJSDocParameterTags(param) { + if (param.name) { + if (ts.isIdentifier(param.name)) { + var name_1 = param.name.escapedText; + return getJSDocTags(param.parent).filter(function (tag) { return ts.isJSDocParameterTag(tag) && ts.isIdentifier(tag.name) && tag.name.escapedText === name_1; }); + } + else { + var i = param.parent.parameters.indexOf(param); + ts.Debug.assert(i > -1, "Parameters should always be in their parents' parameter list"); + var paramTags = getJSDocTags(param.parent).filter(ts.isJSDocParameterTag); + if (i < paramTags.length) { + return [paramTags[i]]; + } + } + } + // return empty array for: out-of-order binding patterns and JSDoc function syntax, which has un-named parameters + return ts.emptyArray; + } + ts.getJSDocParameterTags = getJSDocParameterTags; + /** + * Gets the JSDoc type parameter tags for the node if present. + * + * @remarks Returns any JSDoc template tag whose names match the provided + * parameter, whether a template tag on a containing function + * expression, or a template tag on a variable declaration whose + * initializer is the containing function. The tags closest to the + * node are returned first, so in the previous example, the template + * tag on the containing function expression would be first. + */ + function getJSDocTypeParameterTags(param) { + var name = param.name.escapedText; + return getJSDocTags(param.parent).filter(function (tag) { + return ts.isJSDocTemplateTag(tag) && tag.typeParameters.some(function (tp) { return tp.name.escapedText === name; }); + }); + } + ts.getJSDocTypeParameterTags = getJSDocTypeParameterTags; + /** + * Return true if the node has JSDoc parameter tags. + * + * @remarks Includes parameter tags that are not directly on the node, + * for example on a variable declaration whose initializer is a function expression. + */ + function hasJSDocParameterTags(node) { + return !!getFirstJSDocTag(node, ts.isJSDocParameterTag); + } + ts.hasJSDocParameterTags = hasJSDocParameterTags; + /** Gets the JSDoc augments tag for the node if present */ + function getJSDocAugmentsTag(node) { + return getFirstJSDocTag(node, ts.isJSDocAugmentsTag); + } + ts.getJSDocAugmentsTag = getJSDocAugmentsTag; + /** Gets the JSDoc class tag for the node if present */ + function getJSDocClassTag(node) { + return getFirstJSDocTag(node, ts.isJSDocClassTag); + } + ts.getJSDocClassTag = getJSDocClassTag; + /** Gets the JSDoc enum tag for the node if present */ + function getJSDocEnumTag(node) { + return getFirstJSDocTag(node, ts.isJSDocEnumTag); + } + ts.getJSDocEnumTag = getJSDocEnumTag; + /** Gets the JSDoc this tag for the node if present */ + function getJSDocThisTag(node) { + return getFirstJSDocTag(node, ts.isJSDocThisTag); + } + ts.getJSDocThisTag = getJSDocThisTag; + /** Gets the JSDoc return tag for the node if present */ + function getJSDocReturnTag(node) { + return getFirstJSDocTag(node, ts.isJSDocReturnTag); + } + ts.getJSDocReturnTag = getJSDocReturnTag; + /** Gets the JSDoc template tag for the node if present */ + function getJSDocTemplateTag(node) { + return getFirstJSDocTag(node, ts.isJSDocTemplateTag); + } + ts.getJSDocTemplateTag = getJSDocTemplateTag; + /** Gets the JSDoc type tag for the node if present and valid */ + function getJSDocTypeTag(node) { + // We should have already issued an error if there were multiple type jsdocs, so just use the first one. + var tag = getFirstJSDocTag(node, ts.isJSDocTypeTag); + if (tag && tag.typeExpression && tag.typeExpression.type) { + return tag; + } + return undefined; + } + ts.getJSDocTypeTag = getJSDocTypeTag; + /** + * Gets the type node for the node if provided via JSDoc. + * + * @remarks The search includes any JSDoc param tag that relates + * to the provided parameter, for example a type tag on the + * parameter itself, or a param tag on a containing function + * expression, or a param tag on a variable declaration whose + * initializer is the containing function. The tags closest to the + * node are examined first, so in the previous example, the type + * tag directly on the node would be returned. + */ + function getJSDocType(node) { + var tag = getFirstJSDocTag(node, ts.isJSDocTypeTag); + if (!tag && ts.isParameter(node)) { + tag = ts.find(getJSDocParameterTags(node), function (tag) { return !!tag.typeExpression; }); + } + return tag && tag.typeExpression && tag.typeExpression.type; + } + ts.getJSDocType = getJSDocType; + /** + * Gets the return type node for the node if provided via JSDoc return tag or type tag. + * + * @remarks `getJSDocReturnTag` just gets the whole JSDoc tag. This function + * gets the type from inside the braces, after the fat arrow, etc. + */ + function getJSDocReturnType(node) { + var returnTag = getJSDocReturnTag(node); + if (returnTag && returnTag.typeExpression) { + return returnTag.typeExpression.type; + } + var typeTag = getJSDocTypeTag(node); + if (typeTag && typeTag.typeExpression) { + var type = typeTag.typeExpression.type; + if (ts.isTypeLiteralNode(type)) { + var sig = ts.find(type.members, ts.isCallSignatureDeclaration); + return sig && sig.type; + } + if (ts.isFunctionTypeNode(type)) { + return type.type; + } + } + } + ts.getJSDocReturnType = getJSDocReturnType; + /** Get all JSDoc tags related to a node, including those on parent nodes. */ + function getJSDocTags(node) { + var tags = node.jsDocCache; + // If cache is 'null', that means we did the work of searching for JSDoc tags and came up with nothing. + if (tags === undefined) { + var comments = ts.getJSDocCommentsAndTags(node); + ts.Debug.assert(comments.length < 2 || comments[0] !== comments[1]); + node.jsDocCache = tags = ts.flatMap(comments, function (j) { return ts.isJSDoc(j) ? j.tags : j; }); + } + return tags; + } + ts.getJSDocTags = getJSDocTags; + /** Get the first JSDoc tag of a specified kind, or undefined if not present. */ + function getFirstJSDocTag(node, predicate) { + return ts.find(getJSDocTags(node), predicate); + } + /** Gets all JSDoc tags of a specified kind, or undefined if not present. */ + function getAllJSDocTagsOfKind(node, kind) { + return getJSDocTags(node).filter(function (doc) { return doc.kind === kind; }); + } + ts.getAllJSDocTagsOfKind = getAllJSDocTagsOfKind; + /** + * Gets the effective type parameters. If the node was parsed in a + * JavaScript file, gets the type parameters from the `@template` tag from JSDoc. + */ + function getEffectiveTypeParameterDeclarations(node) { + if (ts.isJSDocSignature(node)) { + return ts.emptyArray; + } + if (ts.isJSDocTypeAlias(node)) { + ts.Debug.assert(node.parent.kind === 291 /* JSDocComment */); + return ts.flatMap(node.parent.tags, function (tag) { return ts.isJSDocTemplateTag(tag) ? tag.typeParameters : undefined; }); + } + if (node.typeParameters) { + return node.typeParameters; + } + if (ts.isInJSFile(node)) { + var decls = ts.getJSDocTypeParameterDeclarations(node); + if (decls.length) { + return decls; + } + var typeTag = getJSDocType(node); + if (typeTag && ts.isFunctionTypeNode(typeTag) && typeTag.typeParameters) { + return typeTag.typeParameters; + } + } + return ts.emptyArray; + } + ts.getEffectiveTypeParameterDeclarations = getEffectiveTypeParameterDeclarations; + function getEffectiveConstraintOfTypeParameter(node) { + return node.constraint ? node.constraint + : ts.isJSDocTemplateTag(node.parent) && node === node.parent.typeParameters[0] + ? node.parent.constraint + : undefined; + } + ts.getEffectiveConstraintOfTypeParameter = getEffectiveConstraintOfTypeParameter; +})(ts || (ts = {})); +// Simple node tests of the form `node.kind === SyntaxKind.Foo`. +(function (ts) { + // Literals + function isNumericLiteral(node) { + return node.kind === 8 /* NumericLiteral */; + } + ts.isNumericLiteral = isNumericLiteral; + function isBigIntLiteral(node) { + return node.kind === 9 /* BigIntLiteral */; + } + ts.isBigIntLiteral = isBigIntLiteral; + function isStringLiteral(node) { + return node.kind === 10 /* StringLiteral */; + } + ts.isStringLiteral = isStringLiteral; + function isJsxText(node) { + return node.kind === 11 /* JsxText */; + } + ts.isJsxText = isJsxText; + function isRegularExpressionLiteral(node) { + return node.kind === 13 /* RegularExpressionLiteral */; + } + ts.isRegularExpressionLiteral = isRegularExpressionLiteral; + function isNoSubstitutionTemplateLiteral(node) { + return node.kind === 14 /* NoSubstitutionTemplateLiteral */; + } + ts.isNoSubstitutionTemplateLiteral = isNoSubstitutionTemplateLiteral; + // Pseudo-literals + function isTemplateHead(node) { + return node.kind === 15 /* TemplateHead */; + } + ts.isTemplateHead = isTemplateHead; + function isTemplateMiddle(node) { + return node.kind === 16 /* TemplateMiddle */; + } + ts.isTemplateMiddle = isTemplateMiddle; + function isTemplateTail(node) { + return node.kind === 17 /* TemplateTail */; + } + ts.isTemplateTail = isTemplateTail; + function isIdentifier(node) { + return node.kind === 72 /* Identifier */; + } + ts.isIdentifier = isIdentifier; + // Names + function isQualifiedName(node) { + return node.kind === 148 /* QualifiedName */; + } + ts.isQualifiedName = isQualifiedName; + function isComputedPropertyName(node) { + return node.kind === 149 /* ComputedPropertyName */; + } + ts.isComputedPropertyName = isComputedPropertyName; + // Signature elements + function isTypeParameterDeclaration(node) { + return node.kind === 150 /* TypeParameter */; + } + ts.isTypeParameterDeclaration = isTypeParameterDeclaration; + function isParameter(node) { + return node.kind === 151 /* Parameter */; + } + ts.isParameter = isParameter; + function isDecorator(node) { + return node.kind === 152 /* Decorator */; + } + ts.isDecorator = isDecorator; + // TypeMember + function isPropertySignature(node) { + return node.kind === 153 /* PropertySignature */; + } + ts.isPropertySignature = isPropertySignature; + function isPropertyDeclaration(node) { + return node.kind === 154 /* PropertyDeclaration */; + } + ts.isPropertyDeclaration = isPropertyDeclaration; + function isMethodSignature(node) { + return node.kind === 155 /* MethodSignature */; + } + ts.isMethodSignature = isMethodSignature; + function isMethodDeclaration(node) { + return node.kind === 156 /* MethodDeclaration */; + } + ts.isMethodDeclaration = isMethodDeclaration; + function isConstructorDeclaration(node) { + return node.kind === 157 /* Constructor */; + } + ts.isConstructorDeclaration = isConstructorDeclaration; + function isGetAccessorDeclaration(node) { + return node.kind === 158 /* GetAccessor */; + } + ts.isGetAccessorDeclaration = isGetAccessorDeclaration; + function isSetAccessorDeclaration(node) { + return node.kind === 159 /* SetAccessor */; + } + ts.isSetAccessorDeclaration = isSetAccessorDeclaration; + function isCallSignatureDeclaration(node) { + return node.kind === 160 /* CallSignature */; + } + ts.isCallSignatureDeclaration = isCallSignatureDeclaration; + function isConstructSignatureDeclaration(node) { + return node.kind === 161 /* ConstructSignature */; + } + ts.isConstructSignatureDeclaration = isConstructSignatureDeclaration; + function isIndexSignatureDeclaration(node) { + return node.kind === 162 /* IndexSignature */; + } + ts.isIndexSignatureDeclaration = isIndexSignatureDeclaration; + /* @internal */ + function isGetOrSetAccessorDeclaration(node) { + return node.kind === 159 /* SetAccessor */ || node.kind === 158 /* GetAccessor */; + } + ts.isGetOrSetAccessorDeclaration = isGetOrSetAccessorDeclaration; + // Type + function isTypePredicateNode(node) { + return node.kind === 163 /* TypePredicate */; + } + ts.isTypePredicateNode = isTypePredicateNode; + function isTypeReferenceNode(node) { + return node.kind === 164 /* TypeReference */; + } + ts.isTypeReferenceNode = isTypeReferenceNode; + function isFunctionTypeNode(node) { + return node.kind === 165 /* FunctionType */; + } + ts.isFunctionTypeNode = isFunctionTypeNode; + function isConstructorTypeNode(node) { + return node.kind === 166 /* ConstructorType */; + } + ts.isConstructorTypeNode = isConstructorTypeNode; + function isTypeQueryNode(node) { + return node.kind === 167 /* TypeQuery */; + } + ts.isTypeQueryNode = isTypeQueryNode; + function isTypeLiteralNode(node) { + return node.kind === 168 /* TypeLiteral */; + } + ts.isTypeLiteralNode = isTypeLiteralNode; + function isArrayTypeNode(node) { + return node.kind === 169 /* ArrayType */; + } + ts.isArrayTypeNode = isArrayTypeNode; + function isTupleTypeNode(node) { + return node.kind === 170 /* TupleType */; + } + ts.isTupleTypeNode = isTupleTypeNode; + function isUnionTypeNode(node) { + return node.kind === 173 /* UnionType */; + } + ts.isUnionTypeNode = isUnionTypeNode; + function isIntersectionTypeNode(node) { + return node.kind === 174 /* IntersectionType */; + } + ts.isIntersectionTypeNode = isIntersectionTypeNode; + function isConditionalTypeNode(node) { + return node.kind === 175 /* ConditionalType */; + } + ts.isConditionalTypeNode = isConditionalTypeNode; + function isInferTypeNode(node) { + return node.kind === 176 /* InferType */; + } + ts.isInferTypeNode = isInferTypeNode; + function isParenthesizedTypeNode(node) { + return node.kind === 177 /* ParenthesizedType */; + } + ts.isParenthesizedTypeNode = isParenthesizedTypeNode; + function isThisTypeNode(node) { + return node.kind === 178 /* ThisType */; + } + ts.isThisTypeNode = isThisTypeNode; + function isTypeOperatorNode(node) { + return node.kind === 179 /* TypeOperator */; + } + ts.isTypeOperatorNode = isTypeOperatorNode; + function isIndexedAccessTypeNode(node) { + return node.kind === 180 /* IndexedAccessType */; + } + ts.isIndexedAccessTypeNode = isIndexedAccessTypeNode; + function isMappedTypeNode(node) { + return node.kind === 181 /* MappedType */; + } + ts.isMappedTypeNode = isMappedTypeNode; + function isLiteralTypeNode(node) { + return node.kind === 182 /* LiteralType */; + } + ts.isLiteralTypeNode = isLiteralTypeNode; + function isImportTypeNode(node) { + return node.kind === 183 /* ImportType */; + } + ts.isImportTypeNode = isImportTypeNode; + // Binding patterns + function isObjectBindingPattern(node) { + return node.kind === 184 /* ObjectBindingPattern */; + } + ts.isObjectBindingPattern = isObjectBindingPattern; + function isArrayBindingPattern(node) { + return node.kind === 185 /* ArrayBindingPattern */; + } + ts.isArrayBindingPattern = isArrayBindingPattern; + function isBindingElement(node) { + return node.kind === 186 /* BindingElement */; + } + ts.isBindingElement = isBindingElement; + // Expression + function isArrayLiteralExpression(node) { + return node.kind === 187 /* ArrayLiteralExpression */; + } + ts.isArrayLiteralExpression = isArrayLiteralExpression; + function isObjectLiteralExpression(node) { + return node.kind === 188 /* ObjectLiteralExpression */; + } + ts.isObjectLiteralExpression = isObjectLiteralExpression; + function isPropertyAccessExpression(node) { + return node.kind === 189 /* PropertyAccessExpression */; + } + ts.isPropertyAccessExpression = isPropertyAccessExpression; + function isElementAccessExpression(node) { + return node.kind === 190 /* ElementAccessExpression */; + } + ts.isElementAccessExpression = isElementAccessExpression; + function isCallExpression(node) { + return node.kind === 191 /* CallExpression */; + } + ts.isCallExpression = isCallExpression; + function isNewExpression(node) { + return node.kind === 192 /* NewExpression */; + } + ts.isNewExpression = isNewExpression; + function isTaggedTemplateExpression(node) { + return node.kind === 193 /* TaggedTemplateExpression */; + } + ts.isTaggedTemplateExpression = isTaggedTemplateExpression; + function isTypeAssertion(node) { + return node.kind === 194 /* TypeAssertionExpression */; + } + ts.isTypeAssertion = isTypeAssertion; + function isParenthesizedExpression(node) { + return node.kind === 195 /* ParenthesizedExpression */; + } + ts.isParenthesizedExpression = isParenthesizedExpression; + function skipPartiallyEmittedExpressions(node) { + while (node.kind === 308 /* PartiallyEmittedExpression */) { + node = node.expression; + } + return node; + } + ts.skipPartiallyEmittedExpressions = skipPartiallyEmittedExpressions; + function isFunctionExpression(node) { + return node.kind === 196 /* FunctionExpression */; + } + ts.isFunctionExpression = isFunctionExpression; + function isArrowFunction(node) { + return node.kind === 197 /* ArrowFunction */; + } + ts.isArrowFunction = isArrowFunction; + function isDeleteExpression(node) { + return node.kind === 198 /* DeleteExpression */; + } + ts.isDeleteExpression = isDeleteExpression; + function isTypeOfExpression(node) { + return node.kind === 199 /* TypeOfExpression */; + } + ts.isTypeOfExpression = isTypeOfExpression; + function isVoidExpression(node) { + return node.kind === 200 /* VoidExpression */; + } + ts.isVoidExpression = isVoidExpression; + function isAwaitExpression(node) { + return node.kind === 201 /* AwaitExpression */; + } + ts.isAwaitExpression = isAwaitExpression; + function isPrefixUnaryExpression(node) { + return node.kind === 202 /* PrefixUnaryExpression */; + } + ts.isPrefixUnaryExpression = isPrefixUnaryExpression; + function isPostfixUnaryExpression(node) { + return node.kind === 203 /* PostfixUnaryExpression */; + } + ts.isPostfixUnaryExpression = isPostfixUnaryExpression; + function isBinaryExpression(node) { + return node.kind === 204 /* BinaryExpression */; + } + ts.isBinaryExpression = isBinaryExpression; + function isConditionalExpression(node) { + return node.kind === 205 /* ConditionalExpression */; + } + ts.isConditionalExpression = isConditionalExpression; + function isTemplateExpression(node) { + return node.kind === 206 /* TemplateExpression */; + } + ts.isTemplateExpression = isTemplateExpression; + function isYieldExpression(node) { + return node.kind === 207 /* YieldExpression */; + } + ts.isYieldExpression = isYieldExpression; + function isSpreadElement(node) { + return node.kind === 208 /* SpreadElement */; + } + ts.isSpreadElement = isSpreadElement; + function isClassExpression(node) { + return node.kind === 209 /* ClassExpression */; + } + ts.isClassExpression = isClassExpression; + function isOmittedExpression(node) { + return node.kind === 210 /* OmittedExpression */; + } + ts.isOmittedExpression = isOmittedExpression; + function isExpressionWithTypeArguments(node) { + return node.kind === 211 /* ExpressionWithTypeArguments */; + } + ts.isExpressionWithTypeArguments = isExpressionWithTypeArguments; + function isAsExpression(node) { + return node.kind === 212 /* AsExpression */; + } + ts.isAsExpression = isAsExpression; + function isNonNullExpression(node) { + return node.kind === 213 /* NonNullExpression */; + } + ts.isNonNullExpression = isNonNullExpression; + function isMetaProperty(node) { + return node.kind === 214 /* MetaProperty */; + } + ts.isMetaProperty = isMetaProperty; + // Misc + function isTemplateSpan(node) { + return node.kind === 216 /* TemplateSpan */; + } + ts.isTemplateSpan = isTemplateSpan; + function isSemicolonClassElement(node) { + return node.kind === 217 /* SemicolonClassElement */; + } + ts.isSemicolonClassElement = isSemicolonClassElement; + // Block + function isBlock(node) { + return node.kind === 218 /* Block */; + } + ts.isBlock = isBlock; + function isVariableStatement(node) { + return node.kind === 219 /* VariableStatement */; + } + ts.isVariableStatement = isVariableStatement; + function isEmptyStatement(node) { + return node.kind === 220 /* EmptyStatement */; + } + ts.isEmptyStatement = isEmptyStatement; + function isExpressionStatement(node) { + return node.kind === 221 /* ExpressionStatement */; + } + ts.isExpressionStatement = isExpressionStatement; + function isIfStatement(node) { + return node.kind === 222 /* IfStatement */; + } + ts.isIfStatement = isIfStatement; + function isDoStatement(node) { + return node.kind === 223 /* DoStatement */; + } + ts.isDoStatement = isDoStatement; + function isWhileStatement(node) { + return node.kind === 224 /* WhileStatement */; + } + ts.isWhileStatement = isWhileStatement; + function isForStatement(node) { + return node.kind === 225 /* ForStatement */; + } + ts.isForStatement = isForStatement; + function isForInStatement(node) { + return node.kind === 226 /* ForInStatement */; + } + ts.isForInStatement = isForInStatement; + function isForOfStatement(node) { + return node.kind === 227 /* ForOfStatement */; + } + ts.isForOfStatement = isForOfStatement; + function isContinueStatement(node) { + return node.kind === 228 /* ContinueStatement */; + } + ts.isContinueStatement = isContinueStatement; + function isBreakStatement(node) { + return node.kind === 229 /* BreakStatement */; + } + ts.isBreakStatement = isBreakStatement; + function isBreakOrContinueStatement(node) { + return node.kind === 229 /* BreakStatement */ || node.kind === 228 /* ContinueStatement */; + } + ts.isBreakOrContinueStatement = isBreakOrContinueStatement; + function isReturnStatement(node) { + return node.kind === 230 /* ReturnStatement */; + } + ts.isReturnStatement = isReturnStatement; + function isWithStatement(node) { + return node.kind === 231 /* WithStatement */; + } + ts.isWithStatement = isWithStatement; + function isSwitchStatement(node) { + return node.kind === 232 /* SwitchStatement */; + } + ts.isSwitchStatement = isSwitchStatement; + function isLabeledStatement(node) { + return node.kind === 233 /* LabeledStatement */; + } + ts.isLabeledStatement = isLabeledStatement; + function isThrowStatement(node) { + return node.kind === 234 /* ThrowStatement */; + } + ts.isThrowStatement = isThrowStatement; + function isTryStatement(node) { + return node.kind === 235 /* TryStatement */; + } + ts.isTryStatement = isTryStatement; + function isDebuggerStatement(node) { + return node.kind === 236 /* DebuggerStatement */; + } + ts.isDebuggerStatement = isDebuggerStatement; + function isVariableDeclaration(node) { + return node.kind === 237 /* VariableDeclaration */; + } + ts.isVariableDeclaration = isVariableDeclaration; + function isVariableDeclarationList(node) { + return node.kind === 238 /* VariableDeclarationList */; + } + ts.isVariableDeclarationList = isVariableDeclarationList; + function isFunctionDeclaration(node) { + return node.kind === 239 /* FunctionDeclaration */; + } + ts.isFunctionDeclaration = isFunctionDeclaration; + function isClassDeclaration(node) { + return node.kind === 240 /* ClassDeclaration */; + } + ts.isClassDeclaration = isClassDeclaration; + function isInterfaceDeclaration(node) { + return node.kind === 241 /* InterfaceDeclaration */; + } + ts.isInterfaceDeclaration = isInterfaceDeclaration; + function isTypeAliasDeclaration(node) { + return node.kind === 242 /* TypeAliasDeclaration */; + } + ts.isTypeAliasDeclaration = isTypeAliasDeclaration; + function isEnumDeclaration(node) { + return node.kind === 243 /* EnumDeclaration */; + } + ts.isEnumDeclaration = isEnumDeclaration; + function isModuleDeclaration(node) { + return node.kind === 244 /* ModuleDeclaration */; + } + ts.isModuleDeclaration = isModuleDeclaration; + function isModuleBlock(node) { + return node.kind === 245 /* ModuleBlock */; + } + ts.isModuleBlock = isModuleBlock; + function isCaseBlock(node) { + return node.kind === 246 /* CaseBlock */; + } + ts.isCaseBlock = isCaseBlock; + function isNamespaceExportDeclaration(node) { + return node.kind === 247 /* NamespaceExportDeclaration */; + } + ts.isNamespaceExportDeclaration = isNamespaceExportDeclaration; + function isImportEqualsDeclaration(node) { + return node.kind === 248 /* ImportEqualsDeclaration */; + } + ts.isImportEqualsDeclaration = isImportEqualsDeclaration; + function isImportDeclaration(node) { + return node.kind === 249 /* ImportDeclaration */; + } + ts.isImportDeclaration = isImportDeclaration; + function isImportClause(node) { + return node.kind === 250 /* ImportClause */; + } + ts.isImportClause = isImportClause; + function isNamespaceImport(node) { + return node.kind === 251 /* NamespaceImport */; + } + ts.isNamespaceImport = isNamespaceImport; + function isNamedImports(node) { + return node.kind === 252 /* NamedImports */; + } + ts.isNamedImports = isNamedImports; + function isImportSpecifier(node) { + return node.kind === 253 /* ImportSpecifier */; + } + ts.isImportSpecifier = isImportSpecifier; + function isExportAssignment(node) { + return node.kind === 254 /* ExportAssignment */; + } + ts.isExportAssignment = isExportAssignment; + function isExportDeclaration(node) { + return node.kind === 255 /* ExportDeclaration */; + } + ts.isExportDeclaration = isExportDeclaration; + function isNamedExports(node) { + return node.kind === 256 /* NamedExports */; + } + ts.isNamedExports = isNamedExports; + function isExportSpecifier(node) { + return node.kind === 257 /* ExportSpecifier */; + } + ts.isExportSpecifier = isExportSpecifier; + function isMissingDeclaration(node) { + return node.kind === 258 /* MissingDeclaration */; + } + ts.isMissingDeclaration = isMissingDeclaration; + // Module References + function isExternalModuleReference(node) { + return node.kind === 259 /* ExternalModuleReference */; + } + ts.isExternalModuleReference = isExternalModuleReference; + // JSX + function isJsxElement(node) { + return node.kind === 260 /* JsxElement */; + } + ts.isJsxElement = isJsxElement; + function isJsxSelfClosingElement(node) { + return node.kind === 261 /* JsxSelfClosingElement */; + } + ts.isJsxSelfClosingElement = isJsxSelfClosingElement; + function isJsxOpeningElement(node) { + return node.kind === 262 /* JsxOpeningElement */; + } + ts.isJsxOpeningElement = isJsxOpeningElement; + function isJsxClosingElement(node) { + return node.kind === 263 /* JsxClosingElement */; + } + ts.isJsxClosingElement = isJsxClosingElement; + function isJsxFragment(node) { + return node.kind === 264 /* JsxFragment */; + } + ts.isJsxFragment = isJsxFragment; + function isJsxOpeningFragment(node) { + return node.kind === 265 /* JsxOpeningFragment */; + } + ts.isJsxOpeningFragment = isJsxOpeningFragment; + function isJsxClosingFragment(node) { + return node.kind === 266 /* JsxClosingFragment */; + } + ts.isJsxClosingFragment = isJsxClosingFragment; + function isJsxAttribute(node) { + return node.kind === 267 /* JsxAttribute */; + } + ts.isJsxAttribute = isJsxAttribute; + function isJsxAttributes(node) { + return node.kind === 268 /* JsxAttributes */; + } + ts.isJsxAttributes = isJsxAttributes; + function isJsxSpreadAttribute(node) { + return node.kind === 269 /* JsxSpreadAttribute */; + } + ts.isJsxSpreadAttribute = isJsxSpreadAttribute; + function isJsxExpression(node) { + return node.kind === 270 /* JsxExpression */; + } + ts.isJsxExpression = isJsxExpression; + // Clauses + function isCaseClause(node) { + return node.kind === 271 /* CaseClause */; + } + ts.isCaseClause = isCaseClause; + function isDefaultClause(node) { + return node.kind === 272 /* DefaultClause */; + } + ts.isDefaultClause = isDefaultClause; + function isHeritageClause(node) { + return node.kind === 273 /* HeritageClause */; + } + ts.isHeritageClause = isHeritageClause; + function isCatchClause(node) { + return node.kind === 274 /* CatchClause */; + } + ts.isCatchClause = isCatchClause; + // Property assignments + function isPropertyAssignment(node) { + return node.kind === 275 /* PropertyAssignment */; + } + ts.isPropertyAssignment = isPropertyAssignment; + function isShorthandPropertyAssignment(node) { + return node.kind === 276 /* ShorthandPropertyAssignment */; + } + ts.isShorthandPropertyAssignment = isShorthandPropertyAssignment; + function isSpreadAssignment(node) { + return node.kind === 277 /* SpreadAssignment */; + } + ts.isSpreadAssignment = isSpreadAssignment; + // Enum + function isEnumMember(node) { + return node.kind === 278 /* EnumMember */; + } + ts.isEnumMember = isEnumMember; + // Top-level nodes + function isSourceFile(node) { + return node.kind === 279 /* SourceFile */; + } + ts.isSourceFile = isSourceFile; + function isBundle(node) { + return node.kind === 280 /* Bundle */; + } + ts.isBundle = isBundle; + function isUnparsedSource(node) { + return node.kind === 281 /* UnparsedSource */; + } + ts.isUnparsedSource = isUnparsedSource; + // JSDoc + function isJSDocTypeExpression(node) { + return node.kind === 283 /* JSDocTypeExpression */; + } + ts.isJSDocTypeExpression = isJSDocTypeExpression; + function isJSDocAllType(node) { + return node.kind === 284 /* JSDocAllType */; + } + ts.isJSDocAllType = isJSDocAllType; + function isJSDocUnknownType(node) { + return node.kind === 285 /* JSDocUnknownType */; + } + ts.isJSDocUnknownType = isJSDocUnknownType; + function isJSDocNullableType(node) { + return node.kind === 286 /* JSDocNullableType */; + } + ts.isJSDocNullableType = isJSDocNullableType; + function isJSDocNonNullableType(node) { + return node.kind === 287 /* JSDocNonNullableType */; + } + ts.isJSDocNonNullableType = isJSDocNonNullableType; + function isJSDocOptionalType(node) { + return node.kind === 288 /* JSDocOptionalType */; + } + ts.isJSDocOptionalType = isJSDocOptionalType; + function isJSDocFunctionType(node) { + return node.kind === 289 /* JSDocFunctionType */; + } + ts.isJSDocFunctionType = isJSDocFunctionType; + function isJSDocVariadicType(node) { + return node.kind === 290 /* JSDocVariadicType */; + } + ts.isJSDocVariadicType = isJSDocVariadicType; + function isJSDoc(node) { + return node.kind === 291 /* JSDocComment */; + } + ts.isJSDoc = isJSDoc; + function isJSDocAugmentsTag(node) { + return node.kind === 295 /* JSDocAugmentsTag */; + } + ts.isJSDocAugmentsTag = isJSDocAugmentsTag; + function isJSDocClassTag(node) { + return node.kind === 296 /* JSDocClassTag */; + } + ts.isJSDocClassTag = isJSDocClassTag; + function isJSDocEnumTag(node) { + return node.kind === 298 /* JSDocEnumTag */; + } + ts.isJSDocEnumTag = isJSDocEnumTag; + function isJSDocThisTag(node) { + return node.kind === 301 /* JSDocThisTag */; + } + ts.isJSDocThisTag = isJSDocThisTag; + function isJSDocParameterTag(node) { + return node.kind === 299 /* JSDocParameterTag */; + } + ts.isJSDocParameterTag = isJSDocParameterTag; + function isJSDocReturnTag(node) { + return node.kind === 300 /* JSDocReturnTag */; + } + ts.isJSDocReturnTag = isJSDocReturnTag; + function isJSDocTypeTag(node) { + return node.kind === 302 /* JSDocTypeTag */; + } + ts.isJSDocTypeTag = isJSDocTypeTag; + function isJSDocTemplateTag(node) { + return node.kind === 303 /* JSDocTemplateTag */; + } + ts.isJSDocTemplateTag = isJSDocTemplateTag; + function isJSDocTypedefTag(node) { + return node.kind === 304 /* JSDocTypedefTag */; + } + ts.isJSDocTypedefTag = isJSDocTypedefTag; + function isJSDocPropertyTag(node) { + return node.kind === 305 /* JSDocPropertyTag */; + } + ts.isJSDocPropertyTag = isJSDocPropertyTag; + function isJSDocPropertyLikeTag(node) { + return node.kind === 305 /* JSDocPropertyTag */ || node.kind === 299 /* JSDocParameterTag */; + } + ts.isJSDocPropertyLikeTag = isJSDocPropertyLikeTag; + function isJSDocTypeLiteral(node) { + return node.kind === 292 /* JSDocTypeLiteral */; + } + ts.isJSDocTypeLiteral = isJSDocTypeLiteral; + function isJSDocCallbackTag(node) { + return node.kind === 297 /* JSDocCallbackTag */; + } + ts.isJSDocCallbackTag = isJSDocCallbackTag; + function isJSDocSignature(node) { + return node.kind === 293 /* JSDocSignature */; + } + ts.isJSDocSignature = isJSDocSignature; +})(ts || (ts = {})); +// Node tests +// +// All node tests in the following list should *not* reference parent pointers so that +// they may be used with transformations. +(function (ts) { + /* @internal */ + function isSyntaxList(n) { + return n.kind === 306 /* SyntaxList */; + } + ts.isSyntaxList = isSyntaxList; + /* @internal */ + function isNode(node) { + return isNodeKind(node.kind); + } + ts.isNode = isNode; + /* @internal */ + function isNodeKind(kind) { + return kind >= 148 /* FirstNode */; + } + ts.isNodeKind = isNodeKind; + /** + * True if node is of some token syntax kind. + * For example, this is true for an IfKeyword but not for an IfStatement. + * Literals are considered tokens, except TemplateLiteral, but does include TemplateHead/Middle/Tail. + */ + function isToken(n) { + return n.kind >= 0 /* FirstToken */ && n.kind <= 147 /* LastToken */; + } + ts.isToken = isToken; + // Node Arrays + /* @internal */ + function isNodeArray(array) { + return array.hasOwnProperty("pos") && array.hasOwnProperty("end"); + } + ts.isNodeArray = isNodeArray; + // Literals + /* @internal */ + function isLiteralKind(kind) { + return 8 /* FirstLiteralToken */ <= kind && kind <= 14 /* LastLiteralToken */; + } + ts.isLiteralKind = isLiteralKind; + function isLiteralExpression(node) { + return isLiteralKind(node.kind); + } + ts.isLiteralExpression = isLiteralExpression; + // Pseudo-literals + /* @internal */ + function isTemplateLiteralKind(kind) { + return 14 /* FirstTemplateToken */ <= kind && kind <= 17 /* LastTemplateToken */; + } + ts.isTemplateLiteralKind = isTemplateLiteralKind; + function isTemplateLiteralToken(node) { + return isTemplateLiteralKind(node.kind); + } + ts.isTemplateLiteralToken = isTemplateLiteralToken; + function isTemplateMiddleOrTemplateTail(node) { + var kind = node.kind; + return kind === 16 /* TemplateMiddle */ + || kind === 17 /* TemplateTail */; + } + ts.isTemplateMiddleOrTemplateTail = isTemplateMiddleOrTemplateTail; + function isImportOrExportSpecifier(node) { + return ts.isImportSpecifier(node) || ts.isExportSpecifier(node); + } + ts.isImportOrExportSpecifier = isImportOrExportSpecifier; + function isStringTextContainingNode(node) { + return node.kind === 10 /* StringLiteral */ || isTemplateLiteralKind(node.kind); + } + ts.isStringTextContainingNode = isStringTextContainingNode; + // Identifiers + /* @internal */ + function isGeneratedIdentifier(node) { + return ts.isIdentifier(node) && (node.autoGenerateFlags & 7 /* KindMask */) > 0 /* None */; + } + ts.isGeneratedIdentifier = isGeneratedIdentifier; + // Keywords + /* @internal */ + function isModifierKind(token) { + switch (token) { + case 118 /* AbstractKeyword */: + case 121 /* AsyncKeyword */: + case 77 /* ConstKeyword */: + case 125 /* DeclareKeyword */: + case 80 /* DefaultKeyword */: + case 85 /* ExportKeyword */: + case 115 /* PublicKeyword */: + case 113 /* PrivateKeyword */: + case 114 /* ProtectedKeyword */: + case 133 /* ReadonlyKeyword */: + case 116 /* StaticKeyword */: + return true; + } + return false; + } + ts.isModifierKind = isModifierKind; + /* @internal */ + function isParameterPropertyModifier(kind) { + return !!(ts.modifierToFlag(kind) & 92 /* ParameterPropertyModifier */); + } + ts.isParameterPropertyModifier = isParameterPropertyModifier; + /* @internal */ + function isClassMemberModifier(idToken) { + return isParameterPropertyModifier(idToken) || idToken === 116 /* StaticKeyword */; + } + ts.isClassMemberModifier = isClassMemberModifier; + function isModifier(node) { + return isModifierKind(node.kind); + } + ts.isModifier = isModifier; + function isEntityName(node) { + var kind = node.kind; + return kind === 148 /* QualifiedName */ + || kind === 72 /* Identifier */; + } + ts.isEntityName = isEntityName; + function isPropertyName(node) { + var kind = node.kind; + return kind === 72 /* Identifier */ + || kind === 10 /* StringLiteral */ + || kind === 8 /* NumericLiteral */ + || kind === 149 /* ComputedPropertyName */; + } + ts.isPropertyName = isPropertyName; + function isBindingName(node) { + var kind = node.kind; + return kind === 72 /* Identifier */ + || kind === 184 /* ObjectBindingPattern */ + || kind === 185 /* ArrayBindingPattern */; + } + ts.isBindingName = isBindingName; + // Functions + function isFunctionLike(node) { + return node && isFunctionLikeKind(node.kind); + } + ts.isFunctionLike = isFunctionLike; + /* @internal */ + function isFunctionLikeDeclaration(node) { + return node && isFunctionLikeDeclarationKind(node.kind); + } + ts.isFunctionLikeDeclaration = isFunctionLikeDeclaration; + function isFunctionLikeDeclarationKind(kind) { + switch (kind) { + case 239 /* FunctionDeclaration */: + case 156 /* MethodDeclaration */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + return true; + default: + return false; + } + } + /* @internal */ + function isFunctionLikeKind(kind) { + switch (kind) { + case 155 /* MethodSignature */: + case 160 /* CallSignature */: + case 293 /* JSDocSignature */: + case 161 /* ConstructSignature */: + case 162 /* IndexSignature */: + case 165 /* FunctionType */: + case 289 /* JSDocFunctionType */: + case 166 /* ConstructorType */: + return true; + default: + return isFunctionLikeDeclarationKind(kind); + } + } + ts.isFunctionLikeKind = isFunctionLikeKind; + /* @internal */ + function isFunctionOrModuleBlock(node) { + return ts.isSourceFile(node) || ts.isModuleBlock(node) || ts.isBlock(node) && isFunctionLike(node.parent); + } + ts.isFunctionOrModuleBlock = isFunctionOrModuleBlock; + // Classes + function isClassElement(node) { + var kind = node.kind; + return kind === 157 /* Constructor */ + || kind === 154 /* PropertyDeclaration */ + || kind === 156 /* MethodDeclaration */ + || kind === 158 /* GetAccessor */ + || kind === 159 /* SetAccessor */ + || kind === 162 /* IndexSignature */ + || kind === 217 /* SemicolonClassElement */; + } + ts.isClassElement = isClassElement; + function isClassLike(node) { + return node && (node.kind === 240 /* ClassDeclaration */ || node.kind === 209 /* ClassExpression */); + } + ts.isClassLike = isClassLike; + function isAccessor(node) { + return node && (node.kind === 158 /* GetAccessor */ || node.kind === 159 /* SetAccessor */); + } + ts.isAccessor = isAccessor; + /* @internal */ + function isMethodOrAccessor(node) { + switch (node.kind) { + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + return true; + default: + return false; + } + } + ts.isMethodOrAccessor = isMethodOrAccessor; + // Type members + function isTypeElement(node) { + var kind = node.kind; + return kind === 161 /* ConstructSignature */ + || kind === 160 /* CallSignature */ + || kind === 153 /* PropertySignature */ + || kind === 155 /* MethodSignature */ + || kind === 162 /* IndexSignature */; + } + ts.isTypeElement = isTypeElement; + function isClassOrTypeElement(node) { + return isTypeElement(node) || isClassElement(node); + } + ts.isClassOrTypeElement = isClassOrTypeElement; + function isObjectLiteralElementLike(node) { + var kind = node.kind; + return kind === 275 /* PropertyAssignment */ + || kind === 276 /* ShorthandPropertyAssignment */ + || kind === 277 /* SpreadAssignment */ + || kind === 156 /* MethodDeclaration */ + || kind === 158 /* GetAccessor */ + || kind === 159 /* SetAccessor */; + } + ts.isObjectLiteralElementLike = isObjectLiteralElementLike; + // Type + /** + * Node test that determines whether a node is a valid type node. + * This differs from the `isPartOfTypeNode` function which determines whether a node is *part* + * of a TypeNode. + */ + function isTypeNode(node) { + return ts.isTypeNodeKind(node.kind); + } + ts.isTypeNode = isTypeNode; + function isFunctionOrConstructorTypeNode(node) { + switch (node.kind) { + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + return true; + } + return false; + } + ts.isFunctionOrConstructorTypeNode = isFunctionOrConstructorTypeNode; + // Binding patterns + /* @internal */ + function isBindingPattern(node) { + if (node) { + var kind = node.kind; + return kind === 185 /* ArrayBindingPattern */ + || kind === 184 /* ObjectBindingPattern */; + } + return false; + } + ts.isBindingPattern = isBindingPattern; + /* @internal */ + function isAssignmentPattern(node) { + var kind = node.kind; + return kind === 187 /* ArrayLiteralExpression */ + || kind === 188 /* ObjectLiteralExpression */; + } + ts.isAssignmentPattern = isAssignmentPattern; + /* @internal */ + function isArrayBindingElement(node) { + var kind = node.kind; + return kind === 186 /* BindingElement */ + || kind === 210 /* OmittedExpression */; + } + ts.isArrayBindingElement = isArrayBindingElement; + /** + * Determines whether the BindingOrAssignmentElement is a BindingElement-like declaration + */ + /* @internal */ + function isDeclarationBindingElement(bindingElement) { + switch (bindingElement.kind) { + case 237 /* VariableDeclaration */: + case 151 /* Parameter */: + case 186 /* BindingElement */: + return true; + } + return false; + } + ts.isDeclarationBindingElement = isDeclarationBindingElement; + /** + * Determines whether a node is a BindingOrAssignmentPattern + */ + /* @internal */ + function isBindingOrAssignmentPattern(node) { + return isObjectBindingOrAssignmentPattern(node) + || isArrayBindingOrAssignmentPattern(node); + } + ts.isBindingOrAssignmentPattern = isBindingOrAssignmentPattern; + /** + * Determines whether a node is an ObjectBindingOrAssignmentPattern + */ + /* @internal */ + function isObjectBindingOrAssignmentPattern(node) { + switch (node.kind) { + case 184 /* ObjectBindingPattern */: + case 188 /* ObjectLiteralExpression */: + return true; + } + return false; + } + ts.isObjectBindingOrAssignmentPattern = isObjectBindingOrAssignmentPattern; + /** + * Determines whether a node is an ArrayBindingOrAssignmentPattern + */ + /* @internal */ + function isArrayBindingOrAssignmentPattern(node) { + switch (node.kind) { + case 185 /* ArrayBindingPattern */: + case 187 /* ArrayLiteralExpression */: + return true; + } + return false; + } + ts.isArrayBindingOrAssignmentPattern = isArrayBindingOrAssignmentPattern; + /* @internal */ + function isPropertyAccessOrQualifiedNameOrImportTypeNode(node) { + var kind = node.kind; + return kind === 189 /* PropertyAccessExpression */ + || kind === 148 /* QualifiedName */ + || kind === 183 /* ImportType */; + } + ts.isPropertyAccessOrQualifiedNameOrImportTypeNode = isPropertyAccessOrQualifiedNameOrImportTypeNode; + // Expression + function isPropertyAccessOrQualifiedName(node) { + var kind = node.kind; + return kind === 189 /* PropertyAccessExpression */ + || kind === 148 /* QualifiedName */; + } + ts.isPropertyAccessOrQualifiedName = isPropertyAccessOrQualifiedName; + function isCallLikeExpression(node) { + switch (node.kind) { + case 262 /* JsxOpeningElement */: + case 261 /* JsxSelfClosingElement */: + case 191 /* CallExpression */: + case 192 /* NewExpression */: + case 193 /* TaggedTemplateExpression */: + case 152 /* Decorator */: + return true; + default: + return false; + } + } + ts.isCallLikeExpression = isCallLikeExpression; + function isCallOrNewExpression(node) { + return node.kind === 191 /* CallExpression */ || node.kind === 192 /* NewExpression */; + } + ts.isCallOrNewExpression = isCallOrNewExpression; + function isTemplateLiteral(node) { + var kind = node.kind; + return kind === 206 /* TemplateExpression */ + || kind === 14 /* NoSubstitutionTemplateLiteral */; + } + ts.isTemplateLiteral = isTemplateLiteral; + /* @internal */ + function isLeftHandSideExpression(node) { + return isLeftHandSideExpressionKind(ts.skipPartiallyEmittedExpressions(node).kind); + } + ts.isLeftHandSideExpression = isLeftHandSideExpression; + function isLeftHandSideExpressionKind(kind) { + switch (kind) { + case 189 /* PropertyAccessExpression */: + case 190 /* ElementAccessExpression */: + case 192 /* NewExpression */: + case 191 /* CallExpression */: + case 260 /* JsxElement */: + case 261 /* JsxSelfClosingElement */: + case 264 /* JsxFragment */: + case 193 /* TaggedTemplateExpression */: + case 187 /* ArrayLiteralExpression */: + case 195 /* ParenthesizedExpression */: + case 188 /* ObjectLiteralExpression */: + case 209 /* ClassExpression */: + case 196 /* FunctionExpression */: + case 72 /* Identifier */: + case 13 /* RegularExpressionLiteral */: + case 8 /* NumericLiteral */: + case 9 /* BigIntLiteral */: + case 10 /* StringLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: + case 206 /* TemplateExpression */: + case 87 /* FalseKeyword */: + case 96 /* NullKeyword */: + case 100 /* ThisKeyword */: + case 102 /* TrueKeyword */: + case 98 /* SuperKeyword */: + case 213 /* NonNullExpression */: + case 214 /* MetaProperty */: + case 92 /* ImportKeyword */: // technically this is only an Expression if it's in a CallExpression + return true; + default: + return false; + } + } + /* @internal */ + function isUnaryExpression(node) { + return isUnaryExpressionKind(ts.skipPartiallyEmittedExpressions(node).kind); + } + ts.isUnaryExpression = isUnaryExpression; + function isUnaryExpressionKind(kind) { + switch (kind) { + case 202 /* PrefixUnaryExpression */: + case 203 /* PostfixUnaryExpression */: + case 198 /* DeleteExpression */: + case 199 /* TypeOfExpression */: + case 200 /* VoidExpression */: + case 201 /* AwaitExpression */: + case 194 /* TypeAssertionExpression */: + return true; + default: + return isLeftHandSideExpressionKind(kind); + } + } + /* @internal */ + function isUnaryExpressionWithWrite(expr) { + switch (expr.kind) { + case 203 /* PostfixUnaryExpression */: + return true; + case 202 /* PrefixUnaryExpression */: + return expr.operator === 44 /* PlusPlusToken */ || + expr.operator === 45 /* MinusMinusToken */; + default: + return false; + } + } + ts.isUnaryExpressionWithWrite = isUnaryExpressionWithWrite; + /* @internal */ + /** + * Determines whether a node is an expression based only on its kind. + * Use `isExpressionNode` if not in transforms. + */ + function isExpression(node) { + return isExpressionKind(ts.skipPartiallyEmittedExpressions(node).kind); + } + ts.isExpression = isExpression; + function isExpressionKind(kind) { + switch (kind) { + case 205 /* ConditionalExpression */: + case 207 /* YieldExpression */: + case 197 /* ArrowFunction */: + case 204 /* BinaryExpression */: + case 208 /* SpreadElement */: + case 212 /* AsExpression */: + case 210 /* OmittedExpression */: + case 309 /* CommaListExpression */: + case 308 /* PartiallyEmittedExpression */: + return true; + default: + return isUnaryExpressionKind(kind); + } + } + function isAssertionExpression(node) { + var kind = node.kind; + return kind === 194 /* TypeAssertionExpression */ + || kind === 212 /* AsExpression */; + } + ts.isAssertionExpression = isAssertionExpression; + /* @internal */ + function isPartiallyEmittedExpression(node) { + return node.kind === 308 /* PartiallyEmittedExpression */; + } + ts.isPartiallyEmittedExpression = isPartiallyEmittedExpression; + /* @internal */ + function isNotEmittedStatement(node) { + return node.kind === 307 /* NotEmittedStatement */; + } + ts.isNotEmittedStatement = isNotEmittedStatement; + /* @internal */ + function isNotEmittedOrPartiallyEmittedNode(node) { + return isNotEmittedStatement(node) + || isPartiallyEmittedExpression(node); + } + ts.isNotEmittedOrPartiallyEmittedNode = isNotEmittedOrPartiallyEmittedNode; + function isIterationStatement(node, lookInLabeledStatements) { + switch (node.kind) { + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + case 223 /* DoStatement */: + case 224 /* WhileStatement */: + return true; + case 233 /* LabeledStatement */: + return lookInLabeledStatements && isIterationStatement(node.statement, lookInLabeledStatements); + } + return false; + } + ts.isIterationStatement = isIterationStatement; + /* @internal */ + function isForInOrOfStatement(node) { + return node.kind === 226 /* ForInStatement */ || node.kind === 227 /* ForOfStatement */; + } + ts.isForInOrOfStatement = isForInOrOfStatement; + // Element + /* @internal */ + function isConciseBody(node) { + return ts.isBlock(node) + || isExpression(node); + } + ts.isConciseBody = isConciseBody; + /* @internal */ + function isFunctionBody(node) { + return ts.isBlock(node); + } + ts.isFunctionBody = isFunctionBody; + /* @internal */ + function isForInitializer(node) { + return ts.isVariableDeclarationList(node) + || isExpression(node); + } + ts.isForInitializer = isForInitializer; + /* @internal */ + function isModuleBody(node) { + var kind = node.kind; + return kind === 245 /* ModuleBlock */ + || kind === 244 /* ModuleDeclaration */ + || kind === 72 /* Identifier */; + } + ts.isModuleBody = isModuleBody; + /* @internal */ + function isNamespaceBody(node) { + var kind = node.kind; + return kind === 245 /* ModuleBlock */ + || kind === 244 /* ModuleDeclaration */; + } + ts.isNamespaceBody = isNamespaceBody; + /* @internal */ + function isJSDocNamespaceBody(node) { + var kind = node.kind; + return kind === 72 /* Identifier */ + || kind === 244 /* ModuleDeclaration */; + } + ts.isJSDocNamespaceBody = isJSDocNamespaceBody; + /* @internal */ + function isNamedImportBindings(node) { + var kind = node.kind; + return kind === 252 /* NamedImports */ + || kind === 251 /* NamespaceImport */; + } + ts.isNamedImportBindings = isNamedImportBindings; + /* @internal */ + function isModuleOrEnumDeclaration(node) { + return node.kind === 244 /* ModuleDeclaration */ || node.kind === 243 /* EnumDeclaration */; + } + ts.isModuleOrEnumDeclaration = isModuleOrEnumDeclaration; + function isDeclarationKind(kind) { + return kind === 197 /* ArrowFunction */ + || kind === 186 /* BindingElement */ + || kind === 240 /* ClassDeclaration */ + || kind === 209 /* ClassExpression */ + || kind === 157 /* Constructor */ + || kind === 243 /* EnumDeclaration */ + || kind === 278 /* EnumMember */ + || kind === 257 /* ExportSpecifier */ + || kind === 239 /* FunctionDeclaration */ + || kind === 196 /* FunctionExpression */ + || kind === 158 /* GetAccessor */ + || kind === 250 /* ImportClause */ + || kind === 248 /* ImportEqualsDeclaration */ + || kind === 253 /* ImportSpecifier */ + || kind === 241 /* InterfaceDeclaration */ + || kind === 267 /* JsxAttribute */ + || kind === 156 /* MethodDeclaration */ + || kind === 155 /* MethodSignature */ + || kind === 244 /* ModuleDeclaration */ + || kind === 247 /* NamespaceExportDeclaration */ + || kind === 251 /* NamespaceImport */ + || kind === 151 /* Parameter */ + || kind === 275 /* PropertyAssignment */ + || kind === 154 /* PropertyDeclaration */ + || kind === 153 /* PropertySignature */ + || kind === 159 /* SetAccessor */ + || kind === 276 /* ShorthandPropertyAssignment */ + || kind === 242 /* TypeAliasDeclaration */ + || kind === 150 /* TypeParameter */ + || kind === 237 /* VariableDeclaration */ + || kind === 304 /* JSDocTypedefTag */ + || kind === 297 /* JSDocCallbackTag */ + || kind === 305 /* JSDocPropertyTag */; + } + function isDeclarationStatementKind(kind) { + return kind === 239 /* FunctionDeclaration */ + || kind === 258 /* MissingDeclaration */ + || kind === 240 /* ClassDeclaration */ + || kind === 241 /* InterfaceDeclaration */ + || kind === 242 /* TypeAliasDeclaration */ + || kind === 243 /* EnumDeclaration */ + || kind === 244 /* ModuleDeclaration */ + || kind === 249 /* ImportDeclaration */ + || kind === 248 /* ImportEqualsDeclaration */ + || kind === 255 /* ExportDeclaration */ + || kind === 254 /* ExportAssignment */ + || kind === 247 /* NamespaceExportDeclaration */; + } + function isStatementKindButNotDeclarationKind(kind) { + return kind === 229 /* BreakStatement */ + || kind === 228 /* ContinueStatement */ + || kind === 236 /* DebuggerStatement */ + || kind === 223 /* DoStatement */ + || kind === 221 /* ExpressionStatement */ + || kind === 220 /* EmptyStatement */ + || kind === 226 /* ForInStatement */ + || kind === 227 /* ForOfStatement */ + || kind === 225 /* ForStatement */ + || kind === 222 /* IfStatement */ + || kind === 233 /* LabeledStatement */ + || kind === 230 /* ReturnStatement */ + || kind === 232 /* SwitchStatement */ + || kind === 234 /* ThrowStatement */ + || kind === 235 /* TryStatement */ + || kind === 219 /* VariableStatement */ + || kind === 224 /* WhileStatement */ + || kind === 231 /* WithStatement */ + || kind === 307 /* NotEmittedStatement */ + || kind === 311 /* EndOfDeclarationMarker */ + || kind === 310 /* MergeDeclarationMarker */; + } + /* @internal */ + function isDeclaration(node) { + if (node.kind === 150 /* TypeParameter */) { + return node.parent.kind !== 303 /* JSDocTemplateTag */ || ts.isInJSFile(node); + } + return isDeclarationKind(node.kind); + } + ts.isDeclaration = isDeclaration; + /* @internal */ + function isDeclarationStatement(node) { + return isDeclarationStatementKind(node.kind); + } + ts.isDeclarationStatement = isDeclarationStatement; + /** + * Determines whether the node is a statement that is not also a declaration + */ + /* @internal */ + function isStatementButNotDeclaration(node) { + return isStatementKindButNotDeclarationKind(node.kind); + } + ts.isStatementButNotDeclaration = isStatementButNotDeclaration; + /* @internal */ + function isStatement(node) { + var kind = node.kind; + return isStatementKindButNotDeclarationKind(kind) + || isDeclarationStatementKind(kind) + || isBlockStatement(node); + } + ts.isStatement = isStatement; + function isBlockStatement(node) { + if (node.kind !== 218 /* Block */) + return false; + if (node.parent !== undefined) { + if (node.parent.kind === 235 /* TryStatement */ || node.parent.kind === 274 /* CatchClause */) { + return false; + } + } + return !ts.isFunctionBlock(node); + } + // Module references + /* @internal */ + function isModuleReference(node) { + var kind = node.kind; + return kind === 259 /* ExternalModuleReference */ + || kind === 148 /* QualifiedName */ + || kind === 72 /* Identifier */; + } + ts.isModuleReference = isModuleReference; + // JSX + /* @internal */ + function isJsxTagNameExpression(node) { + var kind = node.kind; + return kind === 100 /* ThisKeyword */ + || kind === 72 /* Identifier */ + || kind === 189 /* PropertyAccessExpression */; + } + ts.isJsxTagNameExpression = isJsxTagNameExpression; + /* @internal */ + function isJsxChild(node) { + var kind = node.kind; + return kind === 260 /* JsxElement */ + || kind === 270 /* JsxExpression */ + || kind === 261 /* JsxSelfClosingElement */ + || kind === 11 /* JsxText */ + || kind === 264 /* JsxFragment */; + } + ts.isJsxChild = isJsxChild; + /* @internal */ + function isJsxAttributeLike(node) { + var kind = node.kind; + return kind === 267 /* JsxAttribute */ + || kind === 269 /* JsxSpreadAttribute */; + } + ts.isJsxAttributeLike = isJsxAttributeLike; + /* @internal */ + function isStringLiteralOrJsxExpression(node) { + var kind = node.kind; + return kind === 10 /* StringLiteral */ + || kind === 270 /* JsxExpression */; + } + ts.isStringLiteralOrJsxExpression = isStringLiteralOrJsxExpression; + function isJsxOpeningLikeElement(node) { + var kind = node.kind; + return kind === 262 /* JsxOpeningElement */ + || kind === 261 /* JsxSelfClosingElement */; + } + ts.isJsxOpeningLikeElement = isJsxOpeningLikeElement; + // Clauses + function isCaseOrDefaultClause(node) { + var kind = node.kind; + return kind === 271 /* CaseClause */ + || kind === 272 /* DefaultClause */; + } + ts.isCaseOrDefaultClause = isCaseOrDefaultClause; + // JSDoc + /** True if node is of some JSDoc syntax kind. */ + /* @internal */ + function isJSDocNode(node) { + return node.kind >= 283 /* FirstJSDocNode */ && node.kind <= 305 /* LastJSDocNode */; + } + ts.isJSDocNode = isJSDocNode; + /** True if node is of a kind that may contain comment text. */ + function isJSDocCommentContainingNode(node) { + return node.kind === 291 /* JSDocComment */ || isJSDocTag(node) || ts.isJSDocTypeLiteral(node) || ts.isJSDocSignature(node); + } + ts.isJSDocCommentContainingNode = isJSDocCommentContainingNode; + // TODO: determine what this does before making it public. + /* @internal */ + function isJSDocTag(node) { + return node.kind >= 294 /* FirstJSDocTagNode */ && node.kind <= 305 /* LastJSDocTagNode */; + } + ts.isJSDocTag = isJSDocTag; + function isSetAccessor(node) { + return node.kind === 159 /* SetAccessor */; + } + ts.isSetAccessor = isSetAccessor; + function isGetAccessor(node) { + return node.kind === 158 /* GetAccessor */; + } + ts.isGetAccessor = isGetAccessor; + /** True if has jsdoc nodes attached to it. */ + /* @internal */ + // TODO: GH#19856 Would like to return `node is Node & { jsDoc: JSDoc[] }` but it causes long compile times + function hasJSDocNodes(node) { + var jsDoc = node.jsDoc; + return !!jsDoc && jsDoc.length > 0; + } + ts.hasJSDocNodes = hasJSDocNodes; + /** True if has type node attached to it. */ + /* @internal */ + function hasType(node) { + return !!node.type; + } + ts.hasType = hasType; + /** True if has initializer node attached to it. */ + /* @internal */ + function hasInitializer(node) { + return !!node.initializer; + } + ts.hasInitializer = hasInitializer; + /** True if has initializer node attached to it. */ + /* @internal */ + function hasOnlyExpressionInitializer(node) { + return hasInitializer(node) && !ts.isForStatement(node) && !ts.isForInStatement(node) && !ts.isForOfStatement(node) && !ts.isJsxAttribute(node); + } + ts.hasOnlyExpressionInitializer = hasOnlyExpressionInitializer; + function isObjectLiteralElement(node) { + return node.kind === 267 /* JsxAttribute */ || node.kind === 269 /* JsxSpreadAttribute */ || isObjectLiteralElementLike(node); + } + ts.isObjectLiteralElement = isObjectLiteralElement; + /* @internal */ + function isTypeReferenceType(node) { + return node.kind === 164 /* TypeReference */ || node.kind === 211 /* ExpressionWithTypeArguments */; + } + ts.isTypeReferenceType = isTypeReferenceType; + var MAX_SMI_X86 = 1073741823; + /* @internal */ + function guessIndentation(lines) { + var indentation = MAX_SMI_X86; + for (var _i = 0, lines_1 = lines; _i < lines_1.length; _i++) { + var line = lines_1[_i]; + if (!line.length) { + continue; + } + var i = 0; + for (; i < line.length && i < indentation; i++) { + if (!ts.isWhiteSpaceLike(line.charCodeAt(i))) { + break; + } + } + if (i < indentation) { + indentation = i; + } + if (indentation === 0) { + return 0; + } + } + return indentation === MAX_SMI_X86 ? undefined : indentation; + } + ts.guessIndentation = guessIndentation; + function isStringLiteralLike(node) { + return node.kind === 10 /* StringLiteral */ || node.kind === 14 /* NoSubstitutionTemplateLiteral */; + } + ts.isStringLiteralLike = isStringLiteralLike; +})(ts || (ts = {})); +/* @internal */ +(function (ts) { + function isNamedImportsOrExports(node) { + return node.kind === 252 /* NamedImports */ || node.kind === 256 /* NamedExports */; + } + ts.isNamedImportsOrExports = isNamedImportsOrExports; + function Symbol(flags, name) { + this.flags = flags; + this.escapedName = name; + this.declarations = undefined; + this.valueDeclaration = undefined; + this.id = undefined; + this.mergeId = undefined; + this.parent = undefined; + } + function Type(checker, flags) { + this.flags = flags; + if (ts.Debug.isDebugging) { + this.checker = checker; + } + } + function Signature() { } // tslint:disable-line no-empty + function Node(kind, pos, end) { + this.pos = pos; + this.end = end; + this.kind = kind; + this.id = 0; + this.flags = 0 /* None */; + this.modifierFlagsCache = 0 /* None */; + this.transformFlags = 0 /* None */; + this.parent = undefined; + this.original = undefined; + } + function SourceMapSource(fileName, text, skipTrivia) { + this.fileName = fileName; + this.text = text; + this.skipTrivia = skipTrivia || (function (pos) { return pos; }); + } + ts.objectAllocator = { + getNodeConstructor: function () { return Node; }, + getTokenConstructor: function () { return Node; }, + getIdentifierConstructor: function () { return Node; }, + getSourceFileConstructor: function () { return Node; }, + getSymbolConstructor: function () { return Symbol; }, + getTypeConstructor: function () { return Type; }, + getSignatureConstructor: function () { return Signature; }, + getSourceMapSourceConstructor: function () { return SourceMapSource; }, + }; + function formatStringFromArgs(text, args, baseIndex) { + if (baseIndex === void 0) { baseIndex = 0; } + return text.replace(/{(\d+)}/g, function (_match, index) { return "" + ts.Debug.assertDefined(args[+index + baseIndex]); }); + } + ts.formatStringFromArgs = formatStringFromArgs; + function getLocaleSpecificMessage(message) { + return ts.localizedDiagnosticMessages && ts.localizedDiagnosticMessages[message.key] || message.message; + } + ts.getLocaleSpecificMessage = getLocaleSpecificMessage; + function createFileDiagnostic(file, start, length, message) { + ts.Debug.assertGreaterThanOrEqual(start, 0); + ts.Debug.assertGreaterThanOrEqual(length, 0); + if (file) { + ts.Debug.assertLessThanOrEqual(start, file.text.length); + ts.Debug.assertLessThanOrEqual(start + length, file.text.length); + } + var text = getLocaleSpecificMessage(message); + if (arguments.length > 4) { + text = formatStringFromArgs(text, arguments, 4); + } + return { + file: file, + start: start, + length: length, + messageText: text, + category: message.category, + code: message.code, + reportsUnnecessary: message.reportsUnnecessary, + }; + } + ts.createFileDiagnostic = createFileDiagnostic; + function formatMessage(_dummy, message) { + var text = getLocaleSpecificMessage(message); + if (arguments.length > 2) { + text = formatStringFromArgs(text, arguments, 2); + } + return text; + } + ts.formatMessage = formatMessage; + function createCompilerDiagnostic(message) { + var text = getLocaleSpecificMessage(message); + if (arguments.length > 1) { + text = formatStringFromArgs(text, arguments, 1); + } + return { + file: undefined, + start: undefined, + length: undefined, + messageText: text, + category: message.category, + code: message.code, + reportsUnnecessary: message.reportsUnnecessary, + }; + } + ts.createCompilerDiagnostic = createCompilerDiagnostic; + function createCompilerDiagnosticFromMessageChain(chain) { + return { + file: undefined, + start: undefined, + length: undefined, + code: chain.code, + category: chain.category, + messageText: chain.next ? chain : chain.messageText, + }; + } + ts.createCompilerDiagnosticFromMessageChain = createCompilerDiagnosticFromMessageChain; + function chainDiagnosticMessages(details, message) { + var text = getLocaleSpecificMessage(message); + if (arguments.length > 2) { + text = formatStringFromArgs(text, arguments, 2); + } + return { + messageText: text, + category: message.category, + code: message.code, + next: details + }; + } + ts.chainDiagnosticMessages = chainDiagnosticMessages; + function concatenateDiagnosticMessageChains(headChain, tailChain) { + var lastChain = headChain; + while (lastChain.next) { + lastChain = lastChain.next; + } + lastChain.next = tailChain; + return headChain; + } + ts.concatenateDiagnosticMessageChains = concatenateDiagnosticMessageChains; + function getDiagnosticFilePath(diagnostic) { + return diagnostic.file ? diagnostic.file.path : undefined; + } + function compareDiagnostics(d1, d2) { + return compareDiagnosticsSkipRelatedInformation(d1, d2) || + compareRelatedInformation(d1, d2) || + 0 /* EqualTo */; + } + ts.compareDiagnostics = compareDiagnostics; + function compareDiagnosticsSkipRelatedInformation(d1, d2) { + return ts.compareStringsCaseSensitive(getDiagnosticFilePath(d1), getDiagnosticFilePath(d2)) || + ts.compareValues(d1.start, d2.start) || + ts.compareValues(d1.length, d2.length) || + ts.compareValues(d1.code, d2.code) || + compareMessageText(d1.messageText, d2.messageText) || + 0 /* EqualTo */; + } + ts.compareDiagnosticsSkipRelatedInformation = compareDiagnosticsSkipRelatedInformation; + function compareRelatedInformation(d1, d2) { + if (!d1.relatedInformation && !d2.relatedInformation) { + return 0 /* EqualTo */; + } + if (d1.relatedInformation && d2.relatedInformation) { + return ts.compareValues(d1.relatedInformation.length, d2.relatedInformation.length) || ts.forEach(d1.relatedInformation, function (d1i, index) { + var d2i = d2.relatedInformation[index]; + return compareDiagnostics(d1i, d2i); // EqualTo is 0, so falsy, and will cause the next item to be compared + }) || 0 /* EqualTo */; + } + return d1.relatedInformation ? -1 /* LessThan */ : 1 /* GreaterThan */; + } + function compareMessageText(t1, t2) { + var text1 = t1; + var text2 = t2; + while (text1 && text2) { + // We still have both chains. + var string1 = ts.isString(text1) ? text1 : text1.messageText; + var string2 = ts.isString(text2) ? text2 : text2.messageText; + var res = ts.compareStringsCaseSensitive(string1, string2); + if (res) { + return res; + } + text1 = ts.isString(text1) ? undefined : text1.next; + text2 = ts.isString(text2) ? undefined : text2.next; + } + if (!text1 && !text2) { + // if the chains are done, then these messages are the same. + return 0 /* EqualTo */; + } + // We still have one chain remaining. The shorter chain should come first. + return text1 ? 1 /* GreaterThan */ : -1 /* LessThan */; + } + function getEmitScriptTarget(compilerOptions) { + return compilerOptions.target || 0 /* ES3 */; + } + ts.getEmitScriptTarget = getEmitScriptTarget; + function getEmitModuleKind(compilerOptions) { + return typeof compilerOptions.module === "number" ? + compilerOptions.module : + getEmitScriptTarget(compilerOptions) >= 2 /* ES2015 */ ? ts.ModuleKind.ES2015 : ts.ModuleKind.CommonJS; + } + ts.getEmitModuleKind = getEmitModuleKind; + function getEmitModuleResolutionKind(compilerOptions) { + var moduleResolution = compilerOptions.moduleResolution; + if (moduleResolution === undefined) { + moduleResolution = getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS ? ts.ModuleResolutionKind.NodeJs : ts.ModuleResolutionKind.Classic; + } + return moduleResolution; + } + ts.getEmitModuleResolutionKind = getEmitModuleResolutionKind; + function hasJsonModuleEmitEnabled(options) { + switch (getEmitModuleKind(options)) { + case ts.ModuleKind.CommonJS: + case ts.ModuleKind.AMD: + case ts.ModuleKind.ES2015: + case ts.ModuleKind.ESNext: + return true; + default: + return false; + } + } + ts.hasJsonModuleEmitEnabled = hasJsonModuleEmitEnabled; + function unreachableCodeIsError(options) { + return options.allowUnreachableCode === false; + } + ts.unreachableCodeIsError = unreachableCodeIsError; + function unusedLabelIsError(options) { + return options.allowUnusedLabels === false; + } + ts.unusedLabelIsError = unusedLabelIsError; + function getAreDeclarationMapsEnabled(options) { + return !!(getEmitDeclarations(options) && options.declarationMap); + } + ts.getAreDeclarationMapsEnabled = getAreDeclarationMapsEnabled; + function getAllowSyntheticDefaultImports(compilerOptions) { + var moduleKind = getEmitModuleKind(compilerOptions); + return compilerOptions.allowSyntheticDefaultImports !== undefined + ? compilerOptions.allowSyntheticDefaultImports + : compilerOptions.esModuleInterop || + moduleKind === ts.ModuleKind.System; + } + ts.getAllowSyntheticDefaultImports = getAllowSyntheticDefaultImports; + function getEmitDeclarations(compilerOptions) { + return !!(compilerOptions.declaration || compilerOptions.composite); + } + ts.getEmitDeclarations = getEmitDeclarations; + function getStrictOptionValue(compilerOptions, flag) { + return compilerOptions[flag] === undefined ? !!compilerOptions.strict : !!compilerOptions[flag]; + } + ts.getStrictOptionValue = getStrictOptionValue; + function compilerOptionsAffectSemanticDiagnostics(newOptions, oldOptions) { + return oldOptions !== newOptions && + ts.semanticDiagnosticsOptionDeclarations.some(function (option) { return !ts.isJsonEqual(getCompilerOptionValue(oldOptions, option), getCompilerOptionValue(newOptions, option)); }); + } + ts.compilerOptionsAffectSemanticDiagnostics = compilerOptionsAffectSemanticDiagnostics; + function getCompilerOptionValue(options, option) { + return option.strictFlag ? getStrictOptionValue(options, option.name) : options[option.name]; + } + ts.getCompilerOptionValue = getCompilerOptionValue; + function hasZeroOrOneAsteriskCharacter(str) { + var seenAsterisk = false; + for (var i = 0; i < str.length; i++) { + if (str.charCodeAt(i) === 42 /* asterisk */) { + if (!seenAsterisk) { + seenAsterisk = true; + } + else { + // have already seen asterisk + return false; + } + } + } + return true; + } + ts.hasZeroOrOneAsteriskCharacter = hasZeroOrOneAsteriskCharacter; + /** + * Internally, we represent paths as strings with '/' as the directory separator. + * When we make system calls (eg: LanguageServiceHost.getDirectory()), + * we expect the host to correctly handle paths in our specified format. + */ + ts.directorySeparator = "/"; + var altDirectorySeparator = "\\"; + var urlSchemeSeparator = "://"; + var backslashRegExp = /\\/g; + /** + * Normalize path separators. + */ + function normalizeSlashes(path) { + return path.replace(backslashRegExp, ts.directorySeparator); + } + ts.normalizeSlashes = normalizeSlashes; + function isVolumeCharacter(charCode) { + return (charCode >= 97 /* a */ && charCode <= 122 /* z */) || + (charCode >= 65 /* A */ && charCode <= 90 /* Z */); + } + function getFileUrlVolumeSeparatorEnd(url, start) { + var ch0 = url.charCodeAt(start); + if (ch0 === 58 /* colon */) + return start + 1; + if (ch0 === 37 /* percent */ && url.charCodeAt(start + 1) === 51 /* _3 */) { + var ch2 = url.charCodeAt(start + 2); + if (ch2 === 97 /* a */ || ch2 === 65 /* A */) + return start + 3; + } + return -1; + } + /** + * Returns length of the root part of a path or URL (i.e. length of "/", "x:/", "//server/share/, file:///user/files"). + * If the root is part of a URL, the twos-complement of the root length is returned. + */ + function getEncodedRootLength(path) { + if (!path) + return 0; + var ch0 = path.charCodeAt(0); + // POSIX or UNC + if (ch0 === 47 /* slash */ || ch0 === 92 /* backslash */) { + if (path.charCodeAt(1) !== ch0) + return 1; // POSIX: "/" (or non-normalized "\") + var p1 = path.indexOf(ch0 === 47 /* slash */ ? ts.directorySeparator : altDirectorySeparator, 2); + if (p1 < 0) + return path.length; // UNC: "//server" or "\\server" + return p1 + 1; // UNC: "//server/" or "\\server\" + } + // DOS + if (isVolumeCharacter(ch0) && path.charCodeAt(1) === 58 /* colon */) { + var ch2 = path.charCodeAt(2); + if (ch2 === 47 /* slash */ || ch2 === 92 /* backslash */) + return 3; // DOS: "c:/" or "c:\" + if (path.length === 2) + return 2; // DOS: "c:" (but not "c:d") + } + // URL + var schemeEnd = path.indexOf(urlSchemeSeparator); + if (schemeEnd !== -1) { + var authorityStart = schemeEnd + urlSchemeSeparator.length; + var authorityEnd = path.indexOf(ts.directorySeparator, authorityStart); + if (authorityEnd !== -1) { // URL: "file:///", "file://server/", "file://server/path" + // For local "file" URLs, include the leading DOS volume (if present). + // Per https://www.ietf.org/rfc/rfc1738.txt, a host of "" or "localhost" is a + // special case interpreted as "the machine from which the URL is being interpreted". + var scheme = path.slice(0, schemeEnd); + var authority = path.slice(authorityStart, authorityEnd); + if (scheme === "file" && (authority === "" || authority === "localhost") && + isVolumeCharacter(path.charCodeAt(authorityEnd + 1))) { + var volumeSeparatorEnd = getFileUrlVolumeSeparatorEnd(path, authorityEnd + 2); + if (volumeSeparatorEnd !== -1) { + if (path.charCodeAt(volumeSeparatorEnd) === 47 /* slash */) { + // URL: "file:///c:/", "file://localhost/c:/", "file:///c%3a/", "file://localhost/c%3a/" + return ~(volumeSeparatorEnd + 1); + } + if (volumeSeparatorEnd === path.length) { + // URL: "file:///c:", "file://localhost/c:", "file:///c$3a", "file://localhost/c%3a" + // but not "file:///c:d" or "file:///c%3ad" + return ~volumeSeparatorEnd; + } + } + } + return ~(authorityEnd + 1); // URL: "file://server/", "http://server/" + } + return ~path.length; // URL: "file://server", "http://server" + } + // relative + return 0; + } + /** + * Returns length of the root part of a path or URL (i.e. length of "/", "x:/", "//server/share/, file:///user/files"). + * + * For example: + * ```ts + * getRootLength("a") === 0 // "" + * getRootLength("/") === 1 // "/" + * getRootLength("c:") === 2 // "c:" + * getRootLength("c:d") === 0 // "" + * getRootLength("c:/") === 3 // "c:/" + * getRootLength("c:\\") === 3 // "c:\\" + * getRootLength("//server") === 7 // "//server" + * getRootLength("//server/share") === 8 // "//server/" + * getRootLength("\\\\server") === 7 // "\\\\server" + * getRootLength("\\\\server\\share") === 8 // "\\\\server\\" + * getRootLength("file:///path") === 8 // "file:///" + * getRootLength("file:///c:") === 10 // "file:///c:" + * getRootLength("file:///c:d") === 8 // "file:///" + * getRootLength("file:///c:/path") === 11 // "file:///c:/" + * getRootLength("file://server") === 13 // "file://server" + * getRootLength("file://server/path") === 14 // "file://server/" + * getRootLength("http://server") === 13 // "http://server" + * getRootLength("http://server/path") === 14 // "http://server/" + * ``` + */ + function getRootLength(path) { + var rootLength = getEncodedRootLength(path); + return rootLength < 0 ? ~rootLength : rootLength; + } + ts.getRootLength = getRootLength; + // TODO(rbuckton): replace references with `resolvePath` + function normalizePath(path) { + return ts.resolvePath(path); + } + ts.normalizePath = normalizePath; + function normalizePathAndParts(path) { + path = normalizeSlashes(path); + var _a = reducePathComponents(getPathComponents(path)), root = _a[0], parts = _a.slice(1); + if (parts.length) { + var joinedParts = root + parts.join(ts.directorySeparator); + return { path: ts.hasTrailingDirectorySeparator(path) ? ts.ensureTrailingDirectorySeparator(joinedParts) : joinedParts, parts: parts }; + } + else { + return { path: root, parts: parts }; + } + } + ts.normalizePathAndParts = normalizePathAndParts; + function getDirectoryPath(path) { + path = normalizeSlashes(path); + // If the path provided is itself the root, then return it. + var rootLength = getRootLength(path); + if (rootLength === path.length) + return path; + // return the leading portion of the path up to the last (non-terminal) directory separator + // but not including any trailing directory separator. + path = ts.removeTrailingDirectorySeparator(path); + return path.slice(0, Math.max(rootLength, path.lastIndexOf(ts.directorySeparator))); + } + ts.getDirectoryPath = getDirectoryPath; + function startsWithDirectory(fileName, directoryName, getCanonicalFileName) { + var canonicalFileName = getCanonicalFileName(fileName); + var canonicalDirectoryName = getCanonicalFileName(directoryName); + return ts.startsWith(canonicalFileName, canonicalDirectoryName + "/") || ts.startsWith(canonicalFileName, canonicalDirectoryName + "\\"); + } + ts.startsWithDirectory = startsWithDirectory; + function isUrl(path) { + return getEncodedRootLength(path) < 0; + } + ts.isUrl = isUrl; + function pathIsRelative(path) { + return /^\.\.?($|[\\/])/.test(path); + } + ts.pathIsRelative = pathIsRelative; + /** + * Determines whether a path is an absolute path (e.g. starts with `/`, or a dos path + * like `c:`, `c:\` or `c:/`). + */ + function isRootedDiskPath(path) { + return getEncodedRootLength(path) > 0; + } + ts.isRootedDiskPath = isRootedDiskPath; + /** + * Determines whether a path consists only of a path root. + */ + function isDiskPathRoot(path) { + var rootLength = getEncodedRootLength(path); + return rootLength > 0 && rootLength === path.length; + } + ts.isDiskPathRoot = isDiskPathRoot; + function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) { + return !isRootedDiskPath(absoluteOrRelativePath) + ? absoluteOrRelativePath + : ts.getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); + } + ts.convertToRelativePath = convertToRelativePath; + function pathComponents(path, rootLength) { + var root = path.substring(0, rootLength); + var rest = path.substring(rootLength).split(ts.directorySeparator); + if (rest.length && !ts.lastOrUndefined(rest)) + rest.pop(); + return [root].concat(rest); + } + /** + * Parse a path into an array containing a root component (at index 0) and zero or more path + * components (at indices > 0). The result is not normalized. + * If the path is relative, the root component is `""`. + * If the path is absolute, the root component includes the first path separator (`/`). + */ + function getPathComponents(path, currentDirectory) { + if (currentDirectory === void 0) { currentDirectory = ""; } + path = ts.combinePaths(currentDirectory, path); + var rootLength = getRootLength(path); + return pathComponents(path, rootLength); + } + ts.getPathComponents = getPathComponents; + /** + * Reduce an array of path components to a more simplified path by navigating any + * `"."` or `".."` entries in the path. + */ + function reducePathComponents(components) { + if (!ts.some(components)) + return []; + var reduced = [components[0]]; + for (var i = 1; i < components.length; i++) { + var component = components[i]; + if (!component) + continue; + if (component === ".") + continue; + if (component === "..") { + if (reduced.length > 1) { + if (reduced[reduced.length - 1] !== "..") { + reduced.pop(); + continue; + } + } + else if (reduced[0]) + continue; + } + reduced.push(component); + } + return reduced; + } + ts.reducePathComponents = reducePathComponents; + /** + * Parse a path into an array containing a root component (at index 0) and zero or more path + * components (at indices > 0). The result is normalized. + * If the path is relative, the root component is `""`. + * If the path is absolute, the root component includes the first path separator (`/`). + */ + function getNormalizedPathComponents(path, currentDirectory) { + return reducePathComponents(getPathComponents(path, currentDirectory)); + } + ts.getNormalizedPathComponents = getNormalizedPathComponents; + function getNormalizedAbsolutePath(fileName, currentDirectory) { + return getPathFromPathComponents(getNormalizedPathComponents(fileName, currentDirectory)); + } + ts.getNormalizedAbsolutePath = getNormalizedAbsolutePath; + /** + * Formats a parsed path consisting of a root component (at index 0) and zero or more path + * segments (at indices > 0). + */ + function getPathFromPathComponents(pathComponents) { + if (pathComponents.length === 0) + return ""; + var root = pathComponents[0] && ts.ensureTrailingDirectorySeparator(pathComponents[0]); + return root + pathComponents.slice(1).join(ts.directorySeparator); + } + ts.getPathFromPathComponents = getPathFromPathComponents; +})(ts || (ts = {})); +/* @internal */ +(function (ts) { + function getPathComponentsRelativeTo(from, to, stringEqualityComparer, getCanonicalFileName) { + var fromComponents = ts.reducePathComponents(ts.getPathComponents(from)); + var toComponents = ts.reducePathComponents(ts.getPathComponents(to)); + var start; + for (start = 0; start < fromComponents.length && start < toComponents.length; start++) { + var fromComponent = getCanonicalFileName(fromComponents[start]); + var toComponent = getCanonicalFileName(toComponents[start]); + var comparer = start === 0 ? ts.equateStringsCaseInsensitive : stringEqualityComparer; + if (!comparer(fromComponent, toComponent)) + break; + } + if (start === 0) { + return toComponents; + } + var components = toComponents.slice(start); + var relative = []; + for (; start < fromComponents.length; start++) { + relative.push(".."); + } + return [""].concat(relative, components); + } + ts.getPathComponentsRelativeTo = getPathComponentsRelativeTo; + function getRelativePathFromFile(from, to, getCanonicalFileName) { + return ensurePathIsNonModuleName(getRelativePathFromDirectory(ts.getDirectoryPath(from), to, getCanonicalFileName)); + } + ts.getRelativePathFromFile = getRelativePathFromFile; + function getRelativePathFromDirectory(fromDirectory, to, getCanonicalFileNameOrIgnoreCase) { + Debug.assert((ts.getRootLength(fromDirectory) > 0) === (ts.getRootLength(to) > 0), "Paths must either both be absolute or both be relative"); + var getCanonicalFileName = typeof getCanonicalFileNameOrIgnoreCase === "function" ? getCanonicalFileNameOrIgnoreCase : ts.identity; + var ignoreCase = typeof getCanonicalFileNameOrIgnoreCase === "boolean" ? getCanonicalFileNameOrIgnoreCase : false; + var pathComponents = getPathComponentsRelativeTo(fromDirectory, to, ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive, getCanonicalFileName); + return ts.getPathFromPathComponents(pathComponents); + } + ts.getRelativePathFromDirectory = getRelativePathFromDirectory; + function getRelativePathToDirectoryOrUrl(directoryPathOrUrl, relativeOrAbsolutePath, currentDirectory, getCanonicalFileName, isAbsolutePathAnUrl) { + var pathComponents = getPathComponentsRelativeTo(resolvePath(currentDirectory, directoryPathOrUrl), resolvePath(currentDirectory, relativeOrAbsolutePath), ts.equateStringsCaseSensitive, getCanonicalFileName); + var firstComponent = pathComponents[0]; + if (isAbsolutePathAnUrl && ts.isRootedDiskPath(firstComponent)) { + var prefix = firstComponent.charAt(0) === ts.directorySeparator ? "file://" : "file:///"; + pathComponents[0] = prefix + firstComponent; + } + return ts.getPathFromPathComponents(pathComponents); + } + ts.getRelativePathToDirectoryOrUrl = getRelativePathToDirectoryOrUrl; + /** + * Ensures a path is either absolute (prefixed with `/` or `c:`) or dot-relative (prefixed + * with `./` or `../`) so as not to be confused with an unprefixed module name. + */ + function ensurePathIsNonModuleName(path) { + return ts.getRootLength(path) === 0 && !ts.pathIsRelative(path) ? "./" + path : path; + } + ts.ensurePathIsNonModuleName = ensurePathIsNonModuleName; + function getBaseFileName(path, extensions, ignoreCase) { + path = ts.normalizeSlashes(path); + // if the path provided is itself the root, then it has not file name. + var rootLength = ts.getRootLength(path); + if (rootLength === path.length) + return ""; + // return the trailing portion of the path starting after the last (non-terminal) directory + // separator but not including any trailing directory separator. + path = removeTrailingDirectorySeparator(path); + var name = path.slice(Math.max(ts.getRootLength(path), path.lastIndexOf(ts.directorySeparator) + 1)); + var extension = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(name, extensions, ignoreCase) : undefined; + return extension ? name.slice(0, name.length - extension.length) : name; + } + ts.getBaseFileName = getBaseFileName; + /** + * Combines paths. If a path is absolute, it replaces any previous path. + */ + function combinePaths(path) { + var paths = []; + for (var _i = 1; _i < arguments.length; _i++) { + paths[_i - 1] = arguments[_i]; + } + if (path) + path = ts.normalizeSlashes(path); + for (var _a = 0, paths_1 = paths; _a < paths_1.length; _a++) { + var relativePath = paths_1[_a]; + if (!relativePath) + continue; + relativePath = ts.normalizeSlashes(relativePath); + if (!path || ts.getRootLength(relativePath) !== 0) { + path = relativePath; + } + else { + path = ensureTrailingDirectorySeparator(path) + relativePath; + } + } + return path; + } + ts.combinePaths = combinePaths; + /** + * Combines and resolves paths. If a path is absolute, it replaces any previous path. Any + * `.` and `..` path components are resolved. + */ + function resolvePath(path) { + var paths = []; + for (var _i = 1; _i < arguments.length; _i++) { + paths[_i - 1] = arguments[_i]; + } + var combined = ts.some(paths) ? combinePaths.apply(void 0, [path].concat(paths)) : ts.normalizeSlashes(path); + var normalized = ts.getPathFromPathComponents(ts.reducePathComponents(ts.getPathComponents(combined))); + return normalized && hasTrailingDirectorySeparator(combined) ? ensureTrailingDirectorySeparator(normalized) : normalized; + } + ts.resolvePath = resolvePath; + /** + * Determines whether a path has a trailing separator (`/` or `\\`). + */ + function hasTrailingDirectorySeparator(path) { + if (path.length === 0) + return false; + var ch = path.charCodeAt(path.length - 1); + return ch === 47 /* slash */ || ch === 92 /* backslash */; + } + ts.hasTrailingDirectorySeparator = hasTrailingDirectorySeparator; + function removeTrailingDirectorySeparator(path) { + if (hasTrailingDirectorySeparator(path)) { + return path.substr(0, path.length - 1); + } + return path; + } + ts.removeTrailingDirectorySeparator = removeTrailingDirectorySeparator; + function ensureTrailingDirectorySeparator(path) { + if (!hasTrailingDirectorySeparator(path)) { + return path + ts.directorySeparator; + } + return path; + } + ts.ensureTrailingDirectorySeparator = ensureTrailingDirectorySeparator; + function comparePathsWorker(a, b, componentComparer) { + if (a === b) + return 0 /* EqualTo */; + if (a === undefined) + return -1 /* LessThan */; + if (b === undefined) + return 1 /* GreaterThan */; + var aComponents = ts.reducePathComponents(ts.getPathComponents(a)); + var bComponents = ts.reducePathComponents(ts.getPathComponents(b)); + var sharedLength = Math.min(aComponents.length, bComponents.length); + for (var i = 0; i < sharedLength; i++) { + var stringComparer = i === 0 ? ts.compareStringsCaseInsensitive : componentComparer; + var result = stringComparer(aComponents[i], bComponents[i]); + if (result !== 0 /* EqualTo */) { + return result; + } + } + return ts.compareValues(aComponents.length, bComponents.length); + } + /** + * Performs a case-sensitive comparison of two paths. + */ + function comparePathsCaseSensitive(a, b) { + return comparePathsWorker(a, b, ts.compareStringsCaseSensitive); + } + ts.comparePathsCaseSensitive = comparePathsCaseSensitive; + /** + * Performs a case-insensitive comparison of two paths. + */ + function comparePathsCaseInsensitive(a, b) { + return comparePathsWorker(a, b, ts.compareStringsCaseInsensitive); + } + ts.comparePathsCaseInsensitive = comparePathsCaseInsensitive; + function comparePaths(a, b, currentDirectory, ignoreCase) { + if (typeof currentDirectory === "string") { + a = combinePaths(currentDirectory, a); + b = combinePaths(currentDirectory, b); + } + else if (typeof currentDirectory === "boolean") { + ignoreCase = currentDirectory; + } + return comparePathsWorker(a, b, ts.getStringComparer(ignoreCase)); + } + ts.comparePaths = comparePaths; + function containsPath(parent, child, currentDirectory, ignoreCase) { + if (typeof currentDirectory === "string") { + parent = combinePaths(currentDirectory, parent); + child = combinePaths(currentDirectory, child); + } + else if (typeof currentDirectory === "boolean") { + ignoreCase = currentDirectory; + } + if (parent === undefined || child === undefined) + return false; + if (parent === child) + return true; + var parentComponents = ts.reducePathComponents(ts.getPathComponents(parent)); + var childComponents = ts.reducePathComponents(ts.getPathComponents(child)); + if (childComponents.length < parentComponents.length) { + return false; + } + var componentEqualityComparer = ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive; + for (var i = 0; i < parentComponents.length; i++) { + var equalityComparer = i === 0 ? ts.equateStringsCaseInsensitive : componentEqualityComparer; + if (!equalityComparer(parentComponents[i], childComponents[i])) { + return false; + } + } + return true; + } + ts.containsPath = containsPath; + function isDirectorySeparator(charCode) { + return charCode === 47 /* slash */ || charCode === 92 /* backslash */; + } + function stripLeadingDirectorySeparator(s) { + return isDirectorySeparator(s.charCodeAt(0)) ? s.slice(1) : undefined; + } + function tryRemoveDirectoryPrefix(path, dirPath, getCanonicalFileName) { + var withoutPrefix = ts.tryRemovePrefix(path, dirPath, getCanonicalFileName); + return withoutPrefix === undefined ? undefined : stripLeadingDirectorySeparator(withoutPrefix); + } + ts.tryRemoveDirectoryPrefix = tryRemoveDirectoryPrefix; + // Reserved characters, forces escaping of any non-word (or digit), non-whitespace character. + // It may be inefficient (we could just match (/[-[\]{}()*+?.,\\^$|#\s]/g), but this is future + // proof. + var reservedCharacterPattern = /[^\w\s\/]/g; + function regExpEscape(text) { + return text.replace(reservedCharacterPattern, escapeRegExpCharacter); + } + ts.regExpEscape = regExpEscape; + function escapeRegExpCharacter(match) { + return "\\" + match; + } + var wildcardCharCodes = [42 /* asterisk */, 63 /* question */]; + function hasExtension(fileName) { + return ts.stringContains(getBaseFileName(fileName), "."); + } + ts.hasExtension = hasExtension; + ts.commonPackageFolders = ["node_modules", "bower_components", "jspm_packages"]; + var implicitExcludePathRegexPattern = "(?!(" + ts.commonPackageFolders.join("|") + ")(/|$))"; + var filesMatcher = { + /** + * Matches any single directory segment unless it is the last segment and a .min.js file + * Breakdown: + * [^./] # matches everything up to the first . character (excluding directory separators) + * (\\.(?!min\\.js$))? # matches . characters but not if they are part of the .min.js file extension + */ + singleAsteriskRegexFragment: "([^./]|(\\.(?!min\\.js$))?)*", + /** + * Regex for the ** wildcard. Matches any number of subdirectories. When used for including + * files or directories, does not match subdirectories that start with a . character + */ + doubleAsteriskRegexFragment: "(/" + implicitExcludePathRegexPattern + "[^/.][^/]*)*?", + replaceWildcardCharacter: function (match) { return replaceWildcardCharacter(match, filesMatcher.singleAsteriskRegexFragment); } + }; + var directoriesMatcher = { + singleAsteriskRegexFragment: "[^/]*", + /** + * Regex for the ** wildcard. Matches any number of subdirectories. When used for including + * files or directories, does not match subdirectories that start with a . character + */ + doubleAsteriskRegexFragment: "(/" + implicitExcludePathRegexPattern + "[^/.][^/]*)*?", + replaceWildcardCharacter: function (match) { return replaceWildcardCharacter(match, directoriesMatcher.singleAsteriskRegexFragment); } + }; + var excludeMatcher = { + singleAsteriskRegexFragment: "[^/]*", + doubleAsteriskRegexFragment: "(/.+?)?", + replaceWildcardCharacter: function (match) { return replaceWildcardCharacter(match, excludeMatcher.singleAsteriskRegexFragment); } + }; + var wildcardMatchers = { + files: filesMatcher, + directories: directoriesMatcher, + exclude: excludeMatcher + }; + function getRegularExpressionForWildcard(specs, basePath, usage) { + var patterns = getRegularExpressionsForWildcards(specs, basePath, usage); + if (!patterns || !patterns.length) { + return undefined; + } + var pattern = patterns.map(function (pattern) { return "(" + pattern + ")"; }).join("|"); + // If excluding, match "foo/bar/baz...", but if including, only allow "foo". + var terminator = usage === "exclude" ? "($|/)" : "$"; + return "^(" + pattern + ")" + terminator; + } + ts.getRegularExpressionForWildcard = getRegularExpressionForWildcard; + function getRegularExpressionsForWildcards(specs, basePath, usage) { + if (specs === undefined || specs.length === 0) { + return undefined; + } + return ts.flatMap(specs, function (spec) { + return spec && getSubPatternFromSpec(spec, basePath, usage, wildcardMatchers[usage]); + }); + } + ts.getRegularExpressionsForWildcards = getRegularExpressionsForWildcards; + /** + * An "includes" path "foo" is implicitly a glob "foo/** /*" (without the space) if its last component has no extension, + * and does not contain any glob characters itself. + */ + function isImplicitGlob(lastPathComponent) { + return !/[.*?]/.test(lastPathComponent); + } + ts.isImplicitGlob = isImplicitGlob; + function getSubPatternFromSpec(spec, basePath, usage, _a) { + var singleAsteriskRegexFragment = _a.singleAsteriskRegexFragment, doubleAsteriskRegexFragment = _a.doubleAsteriskRegexFragment, replaceWildcardCharacter = _a.replaceWildcardCharacter; + var subpattern = ""; + var hasWrittenComponent = false; + var components = ts.getNormalizedPathComponents(spec, basePath); + var lastComponent = ts.last(components); + if (usage !== "exclude" && lastComponent === "**") { + return undefined; + } + // getNormalizedPathComponents includes the separator for the root component. + // We need to remove to create our regex correctly. + components[0] = removeTrailingDirectorySeparator(components[0]); + if (isImplicitGlob(lastComponent)) { + components.push("**", "*"); + } + var optionalCount = 0; + for (var _i = 0, components_1 = components; _i < components_1.length; _i++) { + var component = components_1[_i]; + if (component === "**") { + subpattern += doubleAsteriskRegexFragment; + } + else { + if (usage === "directories") { + subpattern += "("; + optionalCount++; + } + if (hasWrittenComponent) { + subpattern += ts.directorySeparator; + } + if (usage !== "exclude") { + var componentPattern = ""; + // The * and ? wildcards should not match directories or files that start with . if they + // appear first in a component. Dotted directories and files can be included explicitly + // like so: **/.*/.* + if (component.charCodeAt(0) === 42 /* asterisk */) { + componentPattern += "([^./]" + singleAsteriskRegexFragment + ")?"; + component = component.substr(1); + } + else if (component.charCodeAt(0) === 63 /* question */) { + componentPattern += "[^./]"; + component = component.substr(1); + } + componentPattern += component.replace(reservedCharacterPattern, replaceWildcardCharacter); + // Patterns should not include subfolders like node_modules unless they are + // explicitly included as part of the path. + // + // As an optimization, if the component pattern is the same as the component, + // then there definitely were no wildcard characters and we do not need to + // add the exclusion pattern. + if (componentPattern !== component) { + subpattern += implicitExcludePathRegexPattern; + } + subpattern += componentPattern; + } + else { + subpattern += component.replace(reservedCharacterPattern, replaceWildcardCharacter); + } + } + hasWrittenComponent = true; + } + while (optionalCount > 0) { + subpattern += ")?"; + optionalCount--; + } + return subpattern; + } + function replaceWildcardCharacter(match, singleAsteriskRegexFragment) { + return match === "*" ? singleAsteriskRegexFragment : match === "?" ? "[^/]" : "\\" + match; + } + /** @param path directory of the tsconfig.json */ + function getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory) { + path = ts.normalizePath(path); + currentDirectory = ts.normalizePath(currentDirectory); + var absolutePath = combinePaths(currentDirectory, path); + return { + includeFilePatterns: ts.map(getRegularExpressionsForWildcards(includes, absolutePath, "files"), function (pattern) { return "^" + pattern + "$"; }), + includeFilePattern: getRegularExpressionForWildcard(includes, absolutePath, "files"), + includeDirectoryPattern: getRegularExpressionForWildcard(includes, absolutePath, "directories"), + excludePattern: getRegularExpressionForWildcard(excludes, absolutePath, "exclude"), + basePaths: getBasePaths(path, includes, useCaseSensitiveFileNames) + }; + } + ts.getFileMatcherPatterns = getFileMatcherPatterns; + function getRegexFromPattern(pattern, useCaseSensitiveFileNames) { + return new RegExp(pattern, useCaseSensitiveFileNames ? "" : "i"); + } + ts.getRegexFromPattern = getRegexFromPattern; + /** @param path directory of the tsconfig.json */ + function matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries) { + path = ts.normalizePath(path); + currentDirectory = ts.normalizePath(currentDirectory); + var patterns = getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory); + var includeFileRegexes = patterns.includeFilePatterns && patterns.includeFilePatterns.map(function (pattern) { return getRegexFromPattern(pattern, useCaseSensitiveFileNames); }); + var includeDirectoryRegex = patterns.includeDirectoryPattern && getRegexFromPattern(patterns.includeDirectoryPattern, useCaseSensitiveFileNames); + var excludeRegex = patterns.excludePattern && getRegexFromPattern(patterns.excludePattern, useCaseSensitiveFileNames); + // Associate an array of results with each include regex. This keeps results in order of the "include" order. + // If there are no "includes", then just put everything in results[0]. + var results = includeFileRegexes ? includeFileRegexes.map(function () { return []; }) : [[]]; + for (var _i = 0, _a = patterns.basePaths; _i < _a.length; _i++) { + var basePath = _a[_i]; + visitDirectory(basePath, combinePaths(currentDirectory, basePath), depth); + } + return ts.flatten(results); + function visitDirectory(path, absolutePath, depth) { + var _a = getFileSystemEntries(path), files = _a.files, directories = _a.directories; + var _loop_1 = function (current) { + var name = combinePaths(path, current); + var absoluteName = combinePaths(absolutePath, current); + if (extensions && !ts.fileExtensionIsOneOf(name, extensions)) + return "continue"; + if (excludeRegex && excludeRegex.test(absoluteName)) + return "continue"; + if (!includeFileRegexes) { + results[0].push(name); + } + else { + var includeIndex = ts.findIndex(includeFileRegexes, function (re) { return re.test(absoluteName); }); + if (includeIndex !== -1) { + results[includeIndex].push(name); + } + } + }; + for (var _i = 0, _b = ts.sort(files, ts.compareStringsCaseSensitive); _i < _b.length; _i++) { + var current = _b[_i]; + _loop_1(current); + } + if (depth !== undefined) { + depth--; + if (depth === 0) { + return; + } + } + for (var _c = 0, _d = ts.sort(directories, ts.compareStringsCaseSensitive); _c < _d.length; _c++) { + var current = _d[_c]; + var name = combinePaths(path, current); + var absoluteName = combinePaths(absolutePath, current); + if ((!includeDirectoryRegex || includeDirectoryRegex.test(absoluteName)) && + (!excludeRegex || !excludeRegex.test(absoluteName))) { + visitDirectory(name, absoluteName, depth); + } + } + } + } + ts.matchFiles = matchFiles; + /** + * Computes the unique non-wildcard base paths amongst the provided include patterns. + */ + function getBasePaths(path, includes, useCaseSensitiveFileNames) { + // Storage for our results in the form of literal paths (e.g. the paths as written by the user). + var basePaths = [path]; + if (includes) { + // Storage for literal base paths amongst the include patterns. + var includeBasePaths = []; + for (var _i = 0, includes_1 = includes; _i < includes_1.length; _i++) { + var include = includes_1[_i]; + // We also need to check the relative paths by converting them to absolute and normalizing + // in case they escape the base path (e.g "..\somedirectory") + var absolute = ts.isRootedDiskPath(include) ? include : ts.normalizePath(combinePaths(path, include)); + // Append the literal and canonical candidate base paths. + includeBasePaths.push(getIncludeBasePath(absolute)); + } + // Sort the offsets array using either the literal or canonical path representations. + includeBasePaths.sort(ts.getStringComparer(!useCaseSensitiveFileNames)); + var _loop_2 = function (includeBasePath) { + if (ts.every(basePaths, function (basePath) { return !containsPath(basePath, includeBasePath, path, !useCaseSensitiveFileNames); })) { + basePaths.push(includeBasePath); + } + }; + // Iterate over each include base path and include unique base paths that are not a + // subpath of an existing base path + for (var _a = 0, includeBasePaths_1 = includeBasePaths; _a < includeBasePaths_1.length; _a++) { + var includeBasePath = includeBasePaths_1[_a]; + _loop_2(includeBasePath); + } + } + return basePaths; + } + function getIncludeBasePath(absolute) { + var wildcardOffset = ts.indexOfAnyCharCode(absolute, wildcardCharCodes); + if (wildcardOffset < 0) { + // No "*" or "?" in the path + return !hasExtension(absolute) + ? absolute + : removeTrailingDirectorySeparator(ts.getDirectoryPath(absolute)); + } + return absolute.substring(0, absolute.lastIndexOf(ts.directorySeparator, wildcardOffset)); + } + function ensureScriptKind(fileName, scriptKind) { + // Using scriptKind as a condition handles both: + // - 'scriptKind' is unspecified and thus it is `undefined` + // - 'scriptKind' is set and it is `Unknown` (0) + // If the 'scriptKind' is 'undefined' or 'Unknown' then we attempt + // to get the ScriptKind from the file name. If it cannot be resolved + // from the file name then the default 'TS' script kind is returned. + return scriptKind || getScriptKindFromFileName(fileName) || 3 /* TS */; + } + ts.ensureScriptKind = ensureScriptKind; + function getScriptKindFromFileName(fileName) { + var ext = fileName.substr(fileName.lastIndexOf(".")); + switch (ext.toLowerCase()) { + case ".js" /* Js */: + return 1 /* JS */; + case ".jsx" /* Jsx */: + return 2 /* JSX */; + case ".ts" /* Ts */: + return 3 /* TS */; + case ".tsx" /* Tsx */: + return 4 /* TSX */; + case ".json" /* Json */: + return 6 /* JSON */; + default: + return 0 /* Unknown */; + } + } + ts.getScriptKindFromFileName = getScriptKindFromFileName; + /** + * List of supported extensions in order of file resolution precedence. + */ + ts.supportedTSExtensions = [".ts" /* Ts */, ".tsx" /* Tsx */, ".d.ts" /* Dts */]; + ts.supportedTSExtensionsWithJson = [".ts" /* Ts */, ".tsx" /* Tsx */, ".d.ts" /* Dts */, ".json" /* Json */]; + /** Must have ".d.ts" first because if ".ts" goes first, that will be detected as the extension instead of ".d.ts". */ + ts.supportedTSExtensionsForExtractExtension = [".d.ts" /* Dts */, ".ts" /* Ts */, ".tsx" /* Tsx */]; + ts.supportedJSExtensions = [".js" /* Js */, ".jsx" /* Jsx */]; + ts.supportedJSAndJsonExtensions = [".js" /* Js */, ".jsx" /* Jsx */, ".json" /* Json */]; + var allSupportedExtensions = ts.supportedTSExtensions.concat(ts.supportedJSExtensions); + var allSupportedExtensionsWithJson = ts.supportedTSExtensions.concat(ts.supportedJSExtensions, [".json" /* Json */]); + function getSupportedExtensions(options, extraFileExtensions) { + var needJsExtensions = options && options.allowJs; + if (!extraFileExtensions || extraFileExtensions.length === 0) { + return needJsExtensions ? allSupportedExtensions : ts.supportedTSExtensions; + } + var extensions = (needJsExtensions ? allSupportedExtensions : ts.supportedTSExtensions).concat(ts.mapDefined(extraFileExtensions, function (x) { return x.scriptKind === 7 /* Deferred */ || needJsExtensions && isJSLike(x.scriptKind) ? x.extension : undefined; })); + return ts.deduplicate(extensions, ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive); + } + ts.getSupportedExtensions = getSupportedExtensions; + function getSuppoertedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions) { + if (!options || !options.resolveJsonModule) { + return supportedExtensions; + } + if (supportedExtensions === allSupportedExtensions) { + return allSupportedExtensionsWithJson; + } + if (supportedExtensions === ts.supportedTSExtensions) { + return ts.supportedTSExtensionsWithJson; + } + return supportedExtensions.concat([".json" /* Json */]); + } + ts.getSuppoertedExtensionsWithJsonIfResolveJsonModule = getSuppoertedExtensionsWithJsonIfResolveJsonModule; + function isJSLike(scriptKind) { + return scriptKind === 1 /* JS */ || scriptKind === 2 /* JSX */; + } + function hasJSFileExtension(fileName) { + return ts.some(ts.supportedJSExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + } + ts.hasJSFileExtension = hasJSFileExtension; + function hasJSOrJsonFileExtension(fileName) { + return ts.supportedJSAndJsonExtensions.some(function (ext) { return ts.fileExtensionIs(fileName, ext); }); + } + ts.hasJSOrJsonFileExtension = hasJSOrJsonFileExtension; + function hasTSFileExtension(fileName) { + return ts.some(ts.supportedTSExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + } + ts.hasTSFileExtension = hasTSFileExtension; + function isSupportedSourceFileName(fileName, compilerOptions, extraFileExtensions) { + if (!fileName) { + return false; + } + var supportedExtensions = getSupportedExtensions(compilerOptions, extraFileExtensions); + for (var _i = 0, _a = getSuppoertedExtensionsWithJsonIfResolveJsonModule(compilerOptions, supportedExtensions); _i < _a.length; _i++) { + var extension = _a[_i]; + if (ts.fileExtensionIs(fileName, extension)) { + return true; + } + } + return false; + } + ts.isSupportedSourceFileName = isSupportedSourceFileName; + /** + * Extension boundaries by priority. Lower numbers indicate higher priorities, and are + * aligned to the offset of the highest priority extension in the + * allSupportedExtensions array. + */ + var ExtensionPriority; + (function (ExtensionPriority) { + ExtensionPriority[ExtensionPriority["TypeScriptFiles"] = 0] = "TypeScriptFiles"; + ExtensionPriority[ExtensionPriority["DeclarationAndJavaScriptFiles"] = 2] = "DeclarationAndJavaScriptFiles"; + ExtensionPriority[ExtensionPriority["Highest"] = 0] = "Highest"; + ExtensionPriority[ExtensionPriority["Lowest"] = 2] = "Lowest"; + })(ExtensionPriority = ts.ExtensionPriority || (ts.ExtensionPriority = {})); + function getExtensionPriority(path, supportedExtensions) { + for (var i = supportedExtensions.length - 1; i >= 0; i--) { + if (ts.fileExtensionIs(path, supportedExtensions[i])) { + return adjustExtensionPriority(i, supportedExtensions); + } + } + // If its not in the list of supported extensions, this is likely a + // TypeScript file with a non-ts extension + return 0 /* Highest */; + } + ts.getExtensionPriority = getExtensionPriority; + /** + * Adjusts an extension priority to be the highest priority within the same range. + */ + function adjustExtensionPriority(extensionPriority, supportedExtensions) { + if (extensionPriority < 2 /* DeclarationAndJavaScriptFiles */) { + return 0 /* TypeScriptFiles */; + } + else if (extensionPriority < supportedExtensions.length) { + return 2 /* DeclarationAndJavaScriptFiles */; + } + else { + return supportedExtensions.length; + } + } + ts.adjustExtensionPriority = adjustExtensionPriority; + /** + * Gets the next lowest extension priority for a given priority. + */ + function getNextLowestExtensionPriority(extensionPriority, supportedExtensions) { + if (extensionPriority < 2 /* DeclarationAndJavaScriptFiles */) { + return 2 /* DeclarationAndJavaScriptFiles */; + } + else { + return supportedExtensions.length; + } + } + ts.getNextLowestExtensionPriority = getNextLowestExtensionPriority; + var extensionsToRemove = [".d.ts" /* Dts */, ".ts" /* Ts */, ".js" /* Js */, ".tsx" /* Tsx */, ".jsx" /* Jsx */, ".json" /* Json */]; + function removeFileExtension(path) { + for (var _i = 0, extensionsToRemove_1 = extensionsToRemove; _i < extensionsToRemove_1.length; _i++) { + var ext = extensionsToRemove_1[_i]; + var extensionless = tryRemoveExtension(path, ext); + if (extensionless !== undefined) { + return extensionless; + } + } + return path; + } + ts.removeFileExtension = removeFileExtension; + function tryRemoveExtension(path, extension) { + return ts.fileExtensionIs(path, extension) ? removeExtension(path, extension) : undefined; + } + ts.tryRemoveExtension = tryRemoveExtension; + function removeExtension(path, extension) { + return path.substring(0, path.length - extension.length); + } + ts.removeExtension = removeExtension; + function changeExtension(path, newExtension) { + return changeAnyExtension(path, newExtension, extensionsToRemove, /*ignoreCase*/ false); + } + ts.changeExtension = changeExtension; + function changeAnyExtension(path, ext, extensions, ignoreCase) { + var pathext = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(path, extensions, ignoreCase) : getAnyExtensionFromPath(path); + return pathext ? path.slice(0, path.length - pathext.length) + (ts.startsWith(ext, ".") ? ext : "." + ext) : path; + } + ts.changeAnyExtension = changeAnyExtension; + var Debug; + (function (Debug) { + function showSymbol(symbol) { + var symbolFlags = ts.SymbolFlags; + return "{ flags: " + (symbolFlags ? showFlags(symbol.flags, symbolFlags) : symbol.flags) + "; declarations: " + ts.map(symbol.declarations, showSyntaxKind) + " }"; + } + Debug.showSymbol = showSymbol; + function showFlags(flags, flagsEnum) { + var out = []; + for (var pow = 0; pow <= 30; pow++) { + var n = 1 << pow; + if (flags & n) { + out.push(flagsEnum[n]); + } + } + return out.join("|"); + } + function showSyntaxKind(node) { + var syntaxKind = ts.SyntaxKind; + return syntaxKind ? syntaxKind[node.kind] : node.kind.toString(); + } + Debug.showSyntaxKind = showSyntaxKind; + })(Debug = ts.Debug || (ts.Debug = {})); + function tryParsePattern(pattern) { + // This should be verified outside of here and a proper error thrown. + Debug.assert(ts.hasZeroOrOneAsteriskCharacter(pattern)); + var indexOfStar = pattern.indexOf("*"); + return indexOfStar === -1 ? undefined : { + prefix: pattern.substr(0, indexOfStar), + suffix: pattern.substr(indexOfStar + 1) + }; + } + ts.tryParsePattern = tryParsePattern; + function positionIsSynthesized(pos) { + // This is a fast way of testing the following conditions: + // pos === undefined || pos === null || isNaN(pos) || pos < 0; + return !(pos >= 0); + } + ts.positionIsSynthesized = positionIsSynthesized; + /** True if an extension is one of the supported TypeScript extensions. */ + function extensionIsTS(ext) { + return ext === ".ts" /* Ts */ || ext === ".tsx" /* Tsx */ || ext === ".d.ts" /* Dts */; + } + ts.extensionIsTS = extensionIsTS; + function resolutionExtensionIsTSOrJson(ext) { + return extensionIsTS(ext) || ext === ".json" /* Json */; + } + ts.resolutionExtensionIsTSOrJson = resolutionExtensionIsTSOrJson; + /** + * Gets the extension from a path. + * Path must have a valid extension. + */ + function extensionFromPath(path) { + var ext = tryGetExtensionFromPath(path); + return ext !== undefined ? ext : Debug.fail("File " + path + " has unknown extension."); + } + ts.extensionFromPath = extensionFromPath; + function isAnySupportedFileExtension(path) { + return tryGetExtensionFromPath(path) !== undefined; + } + ts.isAnySupportedFileExtension = isAnySupportedFileExtension; + function tryGetExtensionFromPath(path) { + return ts.find(extensionsToRemove, function (e) { return ts.fileExtensionIs(path, e); }); + } + ts.tryGetExtensionFromPath = tryGetExtensionFromPath; + function getAnyExtensionFromPathWorker(path, extensions, stringEqualityComparer) { + if (typeof extensions === "string") + extensions = [extensions]; + for (var _i = 0, extensions_2 = extensions; _i < extensions_2.length; _i++) { + var extension = extensions_2[_i]; + if (!ts.startsWith(extension, ".")) + extension = "." + extension; + if (path.length >= extension.length && path.charAt(path.length - extension.length) === ".") { + var pathExtension = path.slice(path.length - extension.length); + if (stringEqualityComparer(pathExtension, extension)) { + return pathExtension; + } + } + } + return ""; + } + function getAnyExtensionFromPath(path, extensions, ignoreCase) { + // Retrieves any string from the final "." onwards from a base file name. + // Unlike extensionFromPath, which throws an exception on unrecognized extensions. + if (extensions) { + return getAnyExtensionFromPathWorker(path, extensions, ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive); + } + var baseFileName = getBaseFileName(path); + var extensionIndex = baseFileName.lastIndexOf("."); + if (extensionIndex >= 0) { + return baseFileName.substring(extensionIndex); + } + return ""; + } + ts.getAnyExtensionFromPath = getAnyExtensionFromPath; + function isCheckJsEnabledForFile(sourceFile, compilerOptions) { + return sourceFile.checkJsDirective ? sourceFile.checkJsDirective.enabled : compilerOptions.checkJs; + } + ts.isCheckJsEnabledForFile = isCheckJsEnabledForFile; + ts.emptyFileSystemEntries = { + files: ts.emptyArray, + directories: ts.emptyArray + }; + /** + * patternStrings contains both pattern strings (containing "*") and regular strings. + * Return an exact match if possible, or a pattern match, or undefined. + * (These are verified by verifyCompilerOptions to have 0 or 1 "*" characters.) + */ + function matchPatternOrExact(patternStrings, candidate) { + var patterns = []; + for (var _i = 0, patternStrings_1 = patternStrings; _i < patternStrings_1.length; _i++) { + var patternString = patternStrings_1[_i]; + var pattern = tryParsePattern(patternString); + if (pattern) { + patterns.push(pattern); + } + else if (patternString === candidate) { + // pattern was matched as is - no need to search further + return patternString; + } + } + return ts.findBestPatternMatch(patterns, function (_) { return _; }, candidate); + } + ts.matchPatternOrExact = matchPatternOrExact; + function sliceAfter(arr, value) { + var index = arr.indexOf(value); + Debug.assert(index !== -1); + return arr.slice(index); + } + ts.sliceAfter = sliceAfter; + function minAndMax(arr, getValue) { + Debug.assert(arr.length !== 0); + var min = getValue(arr[0]); + var max = min; + for (var i = 1; i < arr.length; i++) { + var value = getValue(arr[i]); + if (value < min) { + min = value; + } + else if (value > max) { + max = value; + } + } + return { min: min, max: max }; + } + ts.minAndMax = minAndMax; + var NodeSet = /** @class */ (function () { + function NodeSet() { + this.map = ts.createMap(); + } + NodeSet.prototype.add = function (node) { + this.map.set(String(ts.getNodeId(node)), node); + }; + NodeSet.prototype.tryAdd = function (node) { + if (this.has(node)) + return false; + this.add(node); + return true; + }; + NodeSet.prototype.has = function (node) { + return this.map.has(String(ts.getNodeId(node))); + }; + NodeSet.prototype.forEach = function (cb) { + this.map.forEach(cb); + }; + NodeSet.prototype.some = function (pred) { + return ts.forEachEntry(this.map, pred) || false; + }; + return NodeSet; + }()); + ts.NodeSet = NodeSet; + var NodeMap = /** @class */ (function () { + function NodeMap() { + this.map = ts.createMap(); + } + NodeMap.prototype.get = function (node) { + var res = this.map.get(String(ts.getNodeId(node))); + return res && res.value; + }; + NodeMap.prototype.getOrUpdate = function (node, setValue) { + var res = this.get(node); + if (res) + return res; + var value = setValue(); + this.set(node, value); + return value; + }; + NodeMap.prototype.set = function (node, value) { + this.map.set(String(ts.getNodeId(node)), { node: node, value: value }); + }; + NodeMap.prototype.has = function (node) { + return this.map.has(String(ts.getNodeId(node))); + }; + NodeMap.prototype.forEach = function (cb) { + this.map.forEach(function (_a) { + var node = _a.node, value = _a.value; + return cb(value, node); + }); + }; + return NodeMap; + }()); + ts.NodeMap = NodeMap; + function rangeOfNode(node) { + return { pos: ts.getTokenPosOfNode(node), end: node.end }; + } + ts.rangeOfNode = rangeOfNode; + function rangeOfTypeParameters(typeParameters) { + // Include the `<>` + return { pos: typeParameters.pos - 1, end: typeParameters.end + 1 }; + } + ts.rangeOfTypeParameters = rangeOfTypeParameters; + function skipTypeChecking(sourceFile, options) { + // If skipLibCheck is enabled, skip reporting errors if file is a declaration file. + // If skipDefaultLibCheck is enabled, skip reporting errors if file contains a + // '/// ' directive. + return options.skipLibCheck && sourceFile.isDeclarationFile || options.skipDefaultLibCheck && sourceFile.hasNoDefaultLib; + } + ts.skipTypeChecking = skipTypeChecking; + function isJsonEqual(a, b) { + return a === b || typeof a === "object" && a !== null && typeof b === "object" && b !== null && ts.equalOwnProperties(a, b, isJsonEqual); + } + ts.isJsonEqual = isJsonEqual; + function getOrUpdate(map, key, getDefault) { + var got = map.get(key); + if (got === undefined) { + var value = getDefault(); + map.set(key, value); + return value; + } + else { + return got; + } + } + ts.getOrUpdate = getOrUpdate; + /** + * Converts a bigint literal string, e.g. `0x1234n`, + * to its decimal string representation, e.g. `4660`. + */ + function parsePseudoBigInt(stringValue) { + var log2Base; + switch (stringValue.charCodeAt(1)) { // "x" in "0x123" + case 98 /* b */: + case 66 /* B */: // 0b or 0B + log2Base = 1; + break; + case 111 /* o */: + case 79 /* O */: // 0o or 0O + log2Base = 3; + break; + case 120 /* x */: + case 88 /* X */: // 0x or 0X + log2Base = 4; + break; + default: // already in decimal; omit trailing "n" + var nIndex = stringValue.length - 1; + // Skip leading 0s + var nonZeroStart = 0; + while (stringValue.charCodeAt(nonZeroStart) === 48 /* _0 */) { + nonZeroStart++; + } + return stringValue.slice(nonZeroStart, nIndex) || "0"; + } + // Omit leading "0b", "0o", or "0x", and trailing "n" + var startIndex = 2, endIndex = stringValue.length - 1; + var bitsNeeded = (endIndex - startIndex) * log2Base; + // Stores the value specified by the string as a LE array of 16-bit integers + // using Uint16 instead of Uint32 so combining steps can use bitwise operators + var segments = new Uint16Array((bitsNeeded >>> 4) + (bitsNeeded & 15 ? 1 : 0)); + // Add the digits, one at a time + for (var i = endIndex - 1, bitOffset = 0; i >= startIndex; i--, bitOffset += log2Base) { + var segment = bitOffset >>> 4; + var digitChar = stringValue.charCodeAt(i); + // Find character range: 0-9 < A-F < a-f + var digit = digitChar <= 57 /* _9 */ + ? digitChar - 48 /* _0 */ + : 10 + digitChar - + (digitChar <= 70 /* F */ ? 65 /* A */ : 97 /* a */); + var shiftedDigit = digit << (bitOffset & 15); + segments[segment] |= shiftedDigit; + var residual = shiftedDigit >>> 16; + if (residual) + segments[segment + 1] |= residual; // overflows segment + } + // Repeatedly divide segments by 10 and add remainder to base10Value + var base10Value = ""; + var firstNonzeroSegment = segments.length - 1; + var segmentsRemaining = true; + while (segmentsRemaining) { + var mod10 = 0; + segmentsRemaining = false; + for (var segment = firstNonzeroSegment; segment >= 0; segment--) { + var newSegment = mod10 << 16 | segments[segment]; + var segmentValue = (newSegment / 10) | 0; + segments[segment] = segmentValue; + mod10 = newSegment - segmentValue * 10; + if (segmentValue && !segmentsRemaining) { + firstNonzeroSegment = segment; + segmentsRemaining = true; + } + } + base10Value = mod10 + base10Value; + } + return base10Value; + } + ts.parsePseudoBigInt = parsePseudoBigInt; + function pseudoBigIntToString(_a) { + var negative = _a.negative, base10Value = _a.base10Value; + return (negative && base10Value !== "0" ? "-" : "") + base10Value; + } + ts.pseudoBigIntToString = pseudoBigIntToString; +})(ts || (ts = {})); +var ts; +(function (ts) { + var SignatureFlags; + (function (SignatureFlags) { + SignatureFlags[SignatureFlags["None"] = 0] = "None"; + SignatureFlags[SignatureFlags["Yield"] = 1] = "Yield"; + SignatureFlags[SignatureFlags["Await"] = 2] = "Await"; + SignatureFlags[SignatureFlags["Type"] = 4] = "Type"; + SignatureFlags[SignatureFlags["IgnoreMissingOpenBrace"] = 16] = "IgnoreMissingOpenBrace"; + SignatureFlags[SignatureFlags["JSDoc"] = 32] = "JSDoc"; + })(SignatureFlags || (SignatureFlags = {})); + // tslint:disable variable-name + var NodeConstructor; + var TokenConstructor; + var IdentifierConstructor; + var SourceFileConstructor; + // tslint:enable variable-name + function createNode(kind, pos, end) { + if (kind === 279 /* SourceFile */) { + return new (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor()))(kind, pos, end); + } + else if (kind === 72 /* Identifier */) { + return new (IdentifierConstructor || (IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor()))(kind, pos, end); + } + else if (!ts.isNodeKind(kind)) { + return new (TokenConstructor || (TokenConstructor = ts.objectAllocator.getTokenConstructor()))(kind, pos, end); + } + else { + return new (NodeConstructor || (NodeConstructor = ts.objectAllocator.getNodeConstructor()))(kind, pos, end); + } + } + ts.createNode = createNode; + function visitNode(cbNode, node) { + return node && cbNode(node); + } + function visitNodes(cbNode, cbNodes, nodes) { + if (nodes) { + if (cbNodes) { + return cbNodes(nodes); + } + for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) { + var node = nodes_1[_i]; + var result = cbNode(node); + if (result) { + return result; + } + } + } + } + /*@internal*/ + function isJSDocLikeText(text, start) { + return text.charCodeAt(start + 1) === 42 /* asterisk */ && + text.charCodeAt(start + 2) === 42 /* asterisk */ && + text.charCodeAt(start + 3) !== 47 /* slash */; + } + ts.isJSDocLikeText = isJSDocLikeText; + /** + * Invokes a callback for each child of the given node. The 'cbNode' callback is invoked for all child nodes + * stored in properties. If a 'cbNodes' callback is specified, it is invoked for embedded arrays; otherwise, + * embedded arrays are flattened and the 'cbNode' callback is invoked for each element. If a callback returns + * a truthy value, iteration stops and that value is returned. Otherwise, undefined is returned. + * + * @param node a given node to visit its children + * @param cbNode a callback to be invoked for all child nodes + * @param cbNodes a callback to be invoked for embedded array + * + * @remarks `forEachChild` must visit the children of a node in the order + * that they appear in the source code. The language service depends on this property to locate nodes by position. + */ + function forEachChild(node, cbNode, cbNodes) { + if (!node || node.kind <= 147 /* LastToken */) { + return; + } + switch (node.kind) { + case 148 /* QualifiedName */: + return visitNode(cbNode, node.left) || + visitNode(cbNode, node.right); + case 150 /* TypeParameter */: + return visitNode(cbNode, node.name) || + visitNode(cbNode, node.constraint) || + visitNode(cbNode, node.default) || + visitNode(cbNode, node.expression); + case 276 /* ShorthandPropertyAssignment */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.exclamationToken) || + visitNode(cbNode, node.equalsToken) || + visitNode(cbNode, node.objectAssignmentInitializer); + case 277 /* SpreadAssignment */: + return visitNode(cbNode, node.expression); + case 151 /* Parameter */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.dotDotDotToken) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.type) || + visitNode(cbNode, node.initializer); + case 154 /* PropertyDeclaration */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.exclamationToken) || + visitNode(cbNode, node.type) || + visitNode(cbNode, node.initializer); + case 153 /* PropertySignature */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.type) || + visitNode(cbNode, node.initializer); + case 275 /* PropertyAssignment */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.initializer); + case 237 /* VariableDeclaration */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.exclamationToken) || + visitNode(cbNode, node.type) || + visitNode(cbNode, node.initializer); + case 186 /* BindingElement */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.dotDotDotToken) || + visitNode(cbNode, node.propertyName) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.initializer); + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 162 /* IndexSignature */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type); + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 196 /* FunctionExpression */: + case 239 /* FunctionDeclaration */: + case 197 /* ArrowFunction */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.asteriskToken) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.exclamationToken) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type) || + visitNode(cbNode, node.equalsGreaterThanToken) || + visitNode(cbNode, node.body); + case 164 /* TypeReference */: + return visitNode(cbNode, node.typeName) || + visitNodes(cbNode, cbNodes, node.typeArguments); + case 163 /* TypePredicate */: + return visitNode(cbNode, node.parameterName) || + visitNode(cbNode, node.type); + case 167 /* TypeQuery */: + return visitNode(cbNode, node.exprName); + case 168 /* TypeLiteral */: + return visitNodes(cbNode, cbNodes, node.members); + case 169 /* ArrayType */: + return visitNode(cbNode, node.elementType); + case 170 /* TupleType */: + return visitNodes(cbNode, cbNodes, node.elementTypes); + case 173 /* UnionType */: + case 174 /* IntersectionType */: + return visitNodes(cbNode, cbNodes, node.types); + case 175 /* ConditionalType */: + return visitNode(cbNode, node.checkType) || + visitNode(cbNode, node.extendsType) || + visitNode(cbNode, node.trueType) || + visitNode(cbNode, node.falseType); + case 176 /* InferType */: + return visitNode(cbNode, node.typeParameter); + case 183 /* ImportType */: + return visitNode(cbNode, node.argument) || + visitNode(cbNode, node.qualifier) || + visitNodes(cbNode, cbNodes, node.typeArguments); + case 177 /* ParenthesizedType */: + case 179 /* TypeOperator */: + return visitNode(cbNode, node.type); + case 180 /* IndexedAccessType */: + return visitNode(cbNode, node.objectType) || + visitNode(cbNode, node.indexType); + case 181 /* MappedType */: + return visitNode(cbNode, node.readonlyToken) || + visitNode(cbNode, node.typeParameter) || + visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.type); + case 182 /* LiteralType */: + return visitNode(cbNode, node.literal); + case 184 /* ObjectBindingPattern */: + case 185 /* ArrayBindingPattern */: + return visitNodes(cbNode, cbNodes, node.elements); + case 187 /* ArrayLiteralExpression */: + return visitNodes(cbNode, cbNodes, node.elements); + case 188 /* ObjectLiteralExpression */: + return visitNodes(cbNode, cbNodes, node.properties); + case 189 /* PropertyAccessExpression */: + return visitNode(cbNode, node.expression) || + visitNode(cbNode, node.name); + case 190 /* ElementAccessExpression */: + return visitNode(cbNode, node.expression) || + visitNode(cbNode, node.argumentExpression); + case 191 /* CallExpression */: + case 192 /* NewExpression */: + return visitNode(cbNode, node.expression) || + visitNodes(cbNode, cbNodes, node.typeArguments) || + visitNodes(cbNode, cbNodes, node.arguments); + case 193 /* TaggedTemplateExpression */: + return visitNode(cbNode, node.tag) || + visitNodes(cbNode, cbNodes, node.typeArguments) || + visitNode(cbNode, node.template); + case 194 /* TypeAssertionExpression */: + return visitNode(cbNode, node.type) || + visitNode(cbNode, node.expression); + case 195 /* ParenthesizedExpression */: + return visitNode(cbNode, node.expression); + case 198 /* DeleteExpression */: + return visitNode(cbNode, node.expression); + case 199 /* TypeOfExpression */: + return visitNode(cbNode, node.expression); + case 200 /* VoidExpression */: + return visitNode(cbNode, node.expression); + case 202 /* PrefixUnaryExpression */: + return visitNode(cbNode, node.operand); + case 207 /* YieldExpression */: + return visitNode(cbNode, node.asteriskToken) || + visitNode(cbNode, node.expression); + case 201 /* AwaitExpression */: + return visitNode(cbNode, node.expression); + case 203 /* PostfixUnaryExpression */: + return visitNode(cbNode, node.operand); + case 204 /* BinaryExpression */: + return visitNode(cbNode, node.left) || + visitNode(cbNode, node.operatorToken) || + visitNode(cbNode, node.right); + case 212 /* AsExpression */: + return visitNode(cbNode, node.expression) || + visitNode(cbNode, node.type); + case 213 /* NonNullExpression */: + return visitNode(cbNode, node.expression); + case 214 /* MetaProperty */: + return visitNode(cbNode, node.name); + case 205 /* ConditionalExpression */: + return visitNode(cbNode, node.condition) || + visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.whenTrue) || + visitNode(cbNode, node.colonToken) || + visitNode(cbNode, node.whenFalse); + case 208 /* SpreadElement */: + return visitNode(cbNode, node.expression); + case 218 /* Block */: + case 245 /* ModuleBlock */: + return visitNodes(cbNode, cbNodes, node.statements); + case 279 /* SourceFile */: + return visitNodes(cbNode, cbNodes, node.statements) || + visitNode(cbNode, node.endOfFileToken); + case 219 /* VariableStatement */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.declarationList); + case 238 /* VariableDeclarationList */: + return visitNodes(cbNode, cbNodes, node.declarations); + case 221 /* ExpressionStatement */: + return visitNode(cbNode, node.expression); + case 222 /* IfStatement */: + return visitNode(cbNode, node.expression) || + visitNode(cbNode, node.thenStatement) || + visitNode(cbNode, node.elseStatement); + case 223 /* DoStatement */: + return visitNode(cbNode, node.statement) || + visitNode(cbNode, node.expression); + case 224 /* WhileStatement */: + return visitNode(cbNode, node.expression) || + visitNode(cbNode, node.statement); + case 225 /* ForStatement */: + return visitNode(cbNode, node.initializer) || + visitNode(cbNode, node.condition) || + visitNode(cbNode, node.incrementor) || + visitNode(cbNode, node.statement); + case 226 /* ForInStatement */: + return visitNode(cbNode, node.initializer) || + visitNode(cbNode, node.expression) || + visitNode(cbNode, node.statement); + case 227 /* ForOfStatement */: + return visitNode(cbNode, node.awaitModifier) || + visitNode(cbNode, node.initializer) || + visitNode(cbNode, node.expression) || + visitNode(cbNode, node.statement); + case 228 /* ContinueStatement */: + case 229 /* BreakStatement */: + return visitNode(cbNode, node.label); + case 230 /* ReturnStatement */: + return visitNode(cbNode, node.expression); + case 231 /* WithStatement */: + return visitNode(cbNode, node.expression) || + visitNode(cbNode, node.statement); + case 232 /* SwitchStatement */: + return visitNode(cbNode, node.expression) || + visitNode(cbNode, node.caseBlock); + case 246 /* CaseBlock */: + return visitNodes(cbNode, cbNodes, node.clauses); + case 271 /* CaseClause */: + return visitNode(cbNode, node.expression) || + visitNodes(cbNode, cbNodes, node.statements); + case 272 /* DefaultClause */: + return visitNodes(cbNode, cbNodes, node.statements); + case 233 /* LabeledStatement */: + return visitNode(cbNode, node.label) || + visitNode(cbNode, node.statement); + case 234 /* ThrowStatement */: + return visitNode(cbNode, node.expression); + case 235 /* TryStatement */: + return visitNode(cbNode, node.tryBlock) || + visitNode(cbNode, node.catchClause) || + visitNode(cbNode, node.finallyBlock); + case 274 /* CatchClause */: + return visitNode(cbNode, node.variableDeclaration) || + visitNode(cbNode, node.block); + case 152 /* Decorator */: + return visitNode(cbNode, node.expression); + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.heritageClauses) || + visitNodes(cbNode, cbNodes, node.members); + case 241 /* InterfaceDeclaration */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.heritageClauses) || + visitNodes(cbNode, cbNodes, node.members); + case 242 /* TypeAliasDeclaration */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNode(cbNode, node.type); + case 243 /* EnumDeclaration */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNodes(cbNode, cbNodes, node.members); + case 278 /* EnumMember */: + return visitNode(cbNode, node.name) || + visitNode(cbNode, node.initializer); + case 244 /* ModuleDeclaration */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.body); + case 248 /* ImportEqualsDeclaration */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.moduleReference); + case 249 /* ImportDeclaration */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.importClause) || + visitNode(cbNode, node.moduleSpecifier); + case 250 /* ImportClause */: + return visitNode(cbNode, node.name) || + visitNode(cbNode, node.namedBindings); + case 247 /* NamespaceExportDeclaration */: + return visitNode(cbNode, node.name); + case 251 /* NamespaceImport */: + return visitNode(cbNode, node.name); + case 252 /* NamedImports */: + case 256 /* NamedExports */: + return visitNodes(cbNode, cbNodes, node.elements); + case 255 /* ExportDeclaration */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.exportClause) || + visitNode(cbNode, node.moduleSpecifier); + case 253 /* ImportSpecifier */: + case 257 /* ExportSpecifier */: + return visitNode(cbNode, node.propertyName) || + visitNode(cbNode, node.name); + case 254 /* ExportAssignment */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.expression); + case 206 /* TemplateExpression */: + return visitNode(cbNode, node.head) || visitNodes(cbNode, cbNodes, node.templateSpans); + case 216 /* TemplateSpan */: + return visitNode(cbNode, node.expression) || visitNode(cbNode, node.literal); + case 149 /* ComputedPropertyName */: + return visitNode(cbNode, node.expression); + case 273 /* HeritageClause */: + return visitNodes(cbNode, cbNodes, node.types); + case 211 /* ExpressionWithTypeArguments */: + return visitNode(cbNode, node.expression) || + visitNodes(cbNode, cbNodes, node.typeArguments); + case 259 /* ExternalModuleReference */: + return visitNode(cbNode, node.expression); + case 258 /* MissingDeclaration */: + return visitNodes(cbNode, cbNodes, node.decorators); + case 309 /* CommaListExpression */: + return visitNodes(cbNode, cbNodes, node.elements); + case 260 /* JsxElement */: + return visitNode(cbNode, node.openingElement) || + visitNodes(cbNode, cbNodes, node.children) || + visitNode(cbNode, node.closingElement); + case 264 /* JsxFragment */: + return visitNode(cbNode, node.openingFragment) || + visitNodes(cbNode, cbNodes, node.children) || + visitNode(cbNode, node.closingFragment); + case 261 /* JsxSelfClosingElement */: + case 262 /* JsxOpeningElement */: + return visitNode(cbNode, node.tagName) || + visitNodes(cbNode, cbNodes, node.typeArguments) || + visitNode(cbNode, node.attributes); + case 268 /* JsxAttributes */: + return visitNodes(cbNode, cbNodes, node.properties); + case 267 /* JsxAttribute */: + return visitNode(cbNode, node.name) || + visitNode(cbNode, node.initializer); + case 269 /* JsxSpreadAttribute */: + return visitNode(cbNode, node.expression); + case 270 /* JsxExpression */: + return visitNode(cbNode, node.dotDotDotToken) || + visitNode(cbNode, node.expression); + case 263 /* JsxClosingElement */: + return visitNode(cbNode, node.tagName); + case 171 /* OptionalType */: + case 172 /* RestType */: + case 283 /* JSDocTypeExpression */: + case 287 /* JSDocNonNullableType */: + case 286 /* JSDocNullableType */: + case 288 /* JSDocOptionalType */: + case 290 /* JSDocVariadicType */: + return visitNode(cbNode, node.type); + case 289 /* JSDocFunctionType */: + return visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type); + case 291 /* JSDocComment */: + return visitNodes(cbNode, cbNodes, node.tags); + case 299 /* JSDocParameterTag */: + case 305 /* JSDocPropertyTag */: + return visitNode(cbNode, node.tagName) || + (node.isNameFirst + ? visitNode(cbNode, node.name) || + visitNode(cbNode, node.typeExpression) + : visitNode(cbNode, node.typeExpression) || + visitNode(cbNode, node.name)); + case 295 /* JSDocAugmentsTag */: + return visitNode(cbNode, node.tagName) || + visitNode(cbNode, node.class); + case 303 /* JSDocTemplateTag */: + return visitNode(cbNode, node.tagName) || + visitNode(cbNode, node.constraint) || + visitNodes(cbNode, cbNodes, node.typeParameters); + case 304 /* JSDocTypedefTag */: + return visitNode(cbNode, node.tagName) || + (node.typeExpression && + node.typeExpression.kind === 283 /* JSDocTypeExpression */ + ? visitNode(cbNode, node.typeExpression) || + visitNode(cbNode, node.fullName) + : visitNode(cbNode, node.fullName) || + visitNode(cbNode, node.typeExpression)); + case 297 /* JSDocCallbackTag */: + return visitNode(cbNode, node.tagName) || + visitNode(cbNode, node.fullName) || + visitNode(cbNode, node.typeExpression); + case 300 /* JSDocReturnTag */: + case 302 /* JSDocTypeTag */: + case 301 /* JSDocThisTag */: + case 298 /* JSDocEnumTag */: + return visitNode(cbNode, node.tagName) || + visitNode(cbNode, node.typeExpression); + case 293 /* JSDocSignature */: + return ts.forEach(node.typeParameters, cbNode) || + ts.forEach(node.parameters, cbNode) || + visitNode(cbNode, node.type); + case 292 /* JSDocTypeLiteral */: + return ts.forEach(node.jsDocPropertyTags, cbNode); + case 294 /* JSDocTag */: + case 296 /* JSDocClassTag */: + return visitNode(cbNode, node.tagName); + case 308 /* PartiallyEmittedExpression */: + return visitNode(cbNode, node.expression); + } + } + ts.forEachChild = forEachChild; + function createSourceFile(fileName, sourceText, languageVersion, setParentNodes, scriptKind) { + if (setParentNodes === void 0) { setParentNodes = false; } + ts.performance.mark("beforeParse"); + var result; + if (languageVersion === 100 /* JSON */) { + result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes, 6 /* JSON */); + } + else { + result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes, scriptKind); + } + ts.performance.mark("afterParse"); + ts.performance.measure("Parse", "beforeParse", "afterParse"); + return result; + } + ts.createSourceFile = createSourceFile; + function parseIsolatedEntityName(text, languageVersion) { + return Parser.parseIsolatedEntityName(text, languageVersion); + } + ts.parseIsolatedEntityName = parseIsolatedEntityName; + /** + * Parse json text into SyntaxTree and return node and parse errors if any + * @param fileName + * @param sourceText + */ + function parseJsonText(fileName, sourceText) { + return Parser.parseJsonText(fileName, sourceText); + } + ts.parseJsonText = parseJsonText; + // See also `isExternalOrCommonJsModule` in utilities.ts + function isExternalModule(file) { + return file.externalModuleIndicator !== undefined; + } + ts.isExternalModule = isExternalModule; + // Produces a new SourceFile for the 'newText' provided. The 'textChangeRange' parameter + // indicates what changed between the 'text' that this SourceFile has and the 'newText'. + // The SourceFile will be created with the compiler attempting to reuse as many nodes from + // this file as possible. + // + // Note: this function mutates nodes from this SourceFile. That means any existing nodes + // from this SourceFile that are being held onto may change as a result (including + // becoming detached from any SourceFile). It is recommended that this SourceFile not + // be used once 'update' is called on it. + function updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks) { + if (aggressiveChecks === void 0) { aggressiveChecks = false; } + var newSourceFile = IncrementalParser.updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks); + // Because new source file node is created, it may not have the flag PossiblyContainDynamicImport. This is the case if there is no new edit to add dynamic import. + // We will manually port the flag to the new source file. + newSourceFile.flags |= (sourceFile.flags & 1572864 /* PermanentlySetIncrementalFlags */); + return newSourceFile; + } + ts.updateSourceFile = updateSourceFile; + /* @internal */ + function parseIsolatedJSDocComment(content, start, length) { + var result = Parser.JSDocParser.parseIsolatedJSDocComment(content, start, length); + if (result && result.jsDoc) { + // because the jsDocComment was parsed out of the source file, it might + // not be covered by the fixupParentReferences. + Parser.fixupParentReferences(result.jsDoc); + } + return result; + } + ts.parseIsolatedJSDocComment = parseIsolatedJSDocComment; + /* @internal */ + // Exposed only for testing. + function parseJSDocTypeExpressionForTests(content, start, length) { + return Parser.JSDocParser.parseJSDocTypeExpressionForTests(content, start, length); + } + ts.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests; + // Implement the parser as a singleton module. We do this for perf reasons because creating + // parser instances can actually be expensive enough to impact us on projects with many source + // files. + var Parser; + (function (Parser) { + // Share a single scanner across all calls to parse a source file. This helps speed things + // up by avoiding the cost of creating/compiling scanners over and over again. + var scanner = ts.createScanner(6 /* Latest */, /*skipTrivia*/ true); + var disallowInAndDecoratorContext = 2048 /* DisallowInContext */ | 8192 /* DecoratorContext */; + // capture constructors in 'initializeState' to avoid null checks + // tslint:disable variable-name + var NodeConstructor; + var TokenConstructor; + var IdentifierConstructor; + var SourceFileConstructor; + // tslint:enable variable-name + var sourceFile; + var parseDiagnostics; + var syntaxCursor; + var currentToken; + var sourceText; + var nodeCount; + var identifiers; + var identifierCount; + var parsingContext; + // Flags that dictate what parsing context we're in. For example: + // Whether or not we are in strict parsing mode. All that changes in strict parsing mode is + // that some tokens that would be considered identifiers may be considered keywords. + // + // When adding more parser context flags, consider which is the more common case that the + // flag will be in. This should be the 'false' state for that flag. The reason for this is + // that we don't store data in our nodes unless the value is in the *non-default* state. So, + // for example, more often than code 'allows-in' (or doesn't 'disallow-in'). We opt for + // 'disallow-in' set to 'false'. Otherwise, if we had 'allowsIn' set to 'true', then almost + // all nodes would need extra state on them to store this info. + // + // Note: 'allowIn' and 'allowYield' track 1:1 with the [in] and [yield] concepts in the ES6 + // grammar specification. + // + // An important thing about these context concepts. By default they are effectively inherited + // while parsing through every grammar production. i.e. if you don't change them, then when + // you parse a sub-production, it will have the same context values as the parent production. + // This is great most of the time. After all, consider all the 'expression' grammar productions + // and how nearly all of them pass along the 'in' and 'yield' context values: + // + // EqualityExpression[In, Yield] : + // RelationalExpression[?In, ?Yield] + // EqualityExpression[?In, ?Yield] == RelationalExpression[?In, ?Yield] + // EqualityExpression[?In, ?Yield] != RelationalExpression[?In, ?Yield] + // EqualityExpression[?In, ?Yield] === RelationalExpression[?In, ?Yield] + // EqualityExpression[?In, ?Yield] !== RelationalExpression[?In, ?Yield] + // + // Where you have to be careful is then understanding what the points are in the grammar + // where the values are *not* passed along. For example: + // + // SingleNameBinding[Yield,GeneratorParameter] + // [+GeneratorParameter]BindingIdentifier[Yield] Initializer[In]opt + // [~GeneratorParameter]BindingIdentifier[?Yield]Initializer[In, ?Yield]opt + // + // Here this is saying that if the GeneratorParameter context flag is set, that we should + // explicitly set the 'yield' context flag to false before calling into the BindingIdentifier + // and we should explicitly unset the 'yield' context flag before calling into the Initializer. + // production. Conversely, if the GeneratorParameter context flag is not set, then we + // should leave the 'yield' context flag alone. + // + // Getting this all correct is tricky and requires careful reading of the grammar to + // understand when these values should be changed versus when they should be inherited. + // + // Note: it should not be necessary to save/restore these flags during speculative/lookahead + // parsing. These context flags are naturally stored and restored through normal recursive + // descent parsing and unwinding. + var contextFlags; + // Whether or not we've had a parse error since creating the last AST node. If we have + // encountered an error, it will be stored on the next AST node we create. Parse errors + // can be broken down into three categories: + // + // 1) An error that occurred during scanning. For example, an unterminated literal, or a + // character that was completely not understood. + // + // 2) A token was expected, but was not present. This type of error is commonly produced + // by the 'parseExpected' function. + // + // 3) A token was present that no parsing function was able to consume. This type of error + // only occurs in the 'abortParsingListOrMoveToNextToken' function when the parser + // decides to skip the token. + // + // In all of these cases, we want to mark the next node as having had an error before it. + // With this mark, we can know in incremental settings if this node can be reused, or if + // we have to reparse it. If we don't keep this information around, we may just reuse the + // node. in that event we would then not produce the same errors as we did before, causing + // significant confusion problems. + // + // Note: it is necessary that this value be saved/restored during speculative/lookahead + // parsing. During lookahead parsing, we will often create a node. That node will have + // this value attached, and then this value will be set back to 'false'. If we decide to + // rewind, we must get back to the same value we had prior to the lookahead. + // + // Note: any errors at the end of the file that do not precede a regular node, should get + // attached to the EOF token. + var parseErrorBeforeNextFinishedNode = false; + function parseSourceFile(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes, scriptKind) { + if (setParentNodes === void 0) { setParentNodes = false; } + scriptKind = ts.ensureScriptKind(fileName, scriptKind); + if (scriptKind === 6 /* JSON */) { + var result_1 = parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes); + ts.convertToObjectWorker(result_1, result_1.parseDiagnostics, /*returnValue*/ false, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined); + result_1.referencedFiles = ts.emptyArray; + result_1.typeReferenceDirectives = ts.emptyArray; + result_1.libReferenceDirectives = ts.emptyArray; + result_1.amdDependencies = ts.emptyArray; + result_1.hasNoDefaultLib = false; + result_1.pragmas = ts.emptyMap; + return result_1; + } + initializeState(sourceText, languageVersion, syntaxCursor, scriptKind); + var result = parseSourceFileWorker(fileName, languageVersion, setParentNodes, scriptKind); + clearState(); + return result; + } + Parser.parseSourceFile = parseSourceFile; + function parseIsolatedEntityName(content, languageVersion) { + // Choice of `isDeclarationFile` should be arbitrary + initializeState(content, languageVersion, /*syntaxCursor*/ undefined, 1 /* JS */); + // Prime the scanner. + nextToken(); + var entityName = parseEntityName(/*allowReservedWords*/ true); + var isInvalid = token() === 1 /* EndOfFileToken */ && !parseDiagnostics.length; + clearState(); + return isInvalid ? entityName : undefined; + } + Parser.parseIsolatedEntityName = parseIsolatedEntityName; + function parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes) { + if (languageVersion === void 0) { languageVersion = 2 /* ES2015 */; } + initializeState(sourceText, languageVersion, syntaxCursor, 6 /* JSON */); + // Set source file so that errors will be reported with this file name + sourceFile = createSourceFile(fileName, 2 /* ES2015 */, 6 /* JSON */, /*isDeclaration*/ false); + sourceFile.flags = contextFlags; + // Prime the scanner. + nextToken(); + var pos = getNodePos(); + if (token() === 1 /* EndOfFileToken */) { + sourceFile.statements = createNodeArray([], pos, pos); + sourceFile.endOfFileToken = parseTokenNode(); + } + else { + var statement = createNode(221 /* ExpressionStatement */); + switch (token()) { + case 22 /* OpenBracketToken */: + statement.expression = parseArrayLiteralExpression(); + break; + case 102 /* TrueKeyword */: + case 87 /* FalseKeyword */: + case 96 /* NullKeyword */: + statement.expression = parseTokenNode(); + break; + case 39 /* MinusToken */: + if (lookAhead(function () { return nextToken() === 8 /* NumericLiteral */ && nextToken() !== 57 /* ColonToken */; })) { + statement.expression = parsePrefixUnaryExpression(); + } + else { + statement.expression = parseObjectLiteralExpression(); + } + break; + case 8 /* NumericLiteral */: + case 10 /* StringLiteral */: + if (lookAhead(function () { return nextToken() !== 57 /* ColonToken */; })) { + statement.expression = parseLiteralNode(); + break; + } + // falls through + default: + statement.expression = parseObjectLiteralExpression(); + break; + } + finishNode(statement); + sourceFile.statements = createNodeArray([statement], pos); + sourceFile.endOfFileToken = parseExpectedToken(1 /* EndOfFileToken */, ts.Diagnostics.Unexpected_token); + } + if (setParentNodes) { + fixupParentReferences(sourceFile); + } + sourceFile.parseDiagnostics = parseDiagnostics; + var result = sourceFile; + clearState(); + return result; + } + Parser.parseJsonText = parseJsonText; + function getLanguageVariant(scriptKind) { + // .tsx and .jsx files are treated as jsx language variant. + return scriptKind === 4 /* TSX */ || scriptKind === 2 /* JSX */ || scriptKind === 1 /* JS */ || scriptKind === 6 /* JSON */ ? 1 /* JSX */ : 0 /* Standard */; + } + function initializeState(_sourceText, languageVersion, _syntaxCursor, scriptKind) { + NodeConstructor = ts.objectAllocator.getNodeConstructor(); + TokenConstructor = ts.objectAllocator.getTokenConstructor(); + IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor(); + SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor(); + sourceText = _sourceText; + syntaxCursor = _syntaxCursor; + parseDiagnostics = []; + parsingContext = 0; + identifiers = ts.createMap(); + identifierCount = 0; + nodeCount = 0; + switch (scriptKind) { + case 1 /* JS */: + case 2 /* JSX */: + contextFlags = 65536 /* JavaScriptFile */; + break; + case 6 /* JSON */: + contextFlags = 65536 /* JavaScriptFile */ | 16777216 /* JsonFile */; + break; + default: + contextFlags = 0 /* None */; + break; + } + parseErrorBeforeNextFinishedNode = false; + // Initialize and prime the scanner before parsing the source elements. + scanner.setText(sourceText); + scanner.setOnError(scanError); + scanner.setScriptTarget(languageVersion); + scanner.setLanguageVariant(getLanguageVariant(scriptKind)); + } + function clearState() { + // Clear out the text the scanner is pointing at, so it doesn't keep anything alive unnecessarily. + scanner.setText(""); + scanner.setOnError(undefined); + // Clear any data. We don't want to accidentally hold onto it for too long. + parseDiagnostics = undefined; + sourceFile = undefined; + identifiers = undefined; + syntaxCursor = undefined; + sourceText = undefined; + } + function parseSourceFileWorker(fileName, languageVersion, setParentNodes, scriptKind) { + var isDeclarationFile = isDeclarationFileName(fileName); + if (isDeclarationFile) { + contextFlags |= 4194304 /* Ambient */; + } + sourceFile = createSourceFile(fileName, languageVersion, scriptKind, isDeclarationFile); + sourceFile.flags = contextFlags; + // Prime the scanner. + nextToken(); + // A member of ReadonlyArray isn't assignable to a member of T[] (and prevents a direct cast) - but this is where we set up those members so they can be readonly in the future + processCommentPragmas(sourceFile, sourceText); + processPragmasIntoFields(sourceFile, reportPragmaDiagnostic); + sourceFile.statements = parseList(0 /* SourceElements */, parseStatement); + ts.Debug.assert(token() === 1 /* EndOfFileToken */); + sourceFile.endOfFileToken = addJSDocComment(parseTokenNode()); + setExternalModuleIndicator(sourceFile); + sourceFile.nodeCount = nodeCount; + sourceFile.identifierCount = identifierCount; + sourceFile.identifiers = identifiers; + sourceFile.parseDiagnostics = parseDiagnostics; + if (setParentNodes) { + fixupParentReferences(sourceFile); + } + return sourceFile; + function reportPragmaDiagnostic(pos, end, diagnostic) { + parseDiagnostics.push(ts.createFileDiagnostic(sourceFile, pos, end, diagnostic)); + } + } + function addJSDocComment(node) { + ts.Debug.assert(!node.jsDoc); // Should only be called once per node + var jsDoc = ts.mapDefined(ts.getJSDocCommentRanges(node, sourceFile.text), function (comment) { return JSDocParser.parseJSDocComment(node, comment.pos, comment.end - comment.pos); }); + if (jsDoc.length) + node.jsDoc = jsDoc; + return node; + } + function fixupParentReferences(rootNode) { + // normally parent references are set during binding. However, for clients that only need + // a syntax tree, and no semantic features, then the binding process is an unnecessary + // overhead. This functions allows us to set all the parents, without all the expense of + // binding. + var parent = rootNode; + forEachChild(rootNode, visitNode); + return; + function visitNode(n) { + // walk down setting parents that differ from the parent we think it should be. This + // allows us to quickly bail out of setting parents for subtrees during incremental + // parsing + if (n.parent !== parent) { + n.parent = parent; + var saveParent = parent; + parent = n; + forEachChild(n, visitNode); + if (ts.hasJSDocNodes(n)) { + for (var _i = 0, _a = n.jsDoc; _i < _a.length; _i++) { + var jsDoc = _a[_i]; + jsDoc.parent = n; + parent = jsDoc; + forEachChild(jsDoc, visitNode); + } + } + parent = saveParent; + } + } + } + Parser.fixupParentReferences = fixupParentReferences; + function createSourceFile(fileName, languageVersion, scriptKind, isDeclarationFile) { + // code from createNode is inlined here so createNode won't have to deal with special case of creating source files + // this is quite rare comparing to other nodes and createNode should be as fast as possible + var sourceFile = new SourceFileConstructor(279 /* SourceFile */, /*pos*/ 0, /* end */ sourceText.length); + nodeCount++; + sourceFile.text = sourceText; + sourceFile.bindDiagnostics = []; + sourceFile.bindSuggestionDiagnostics = undefined; + sourceFile.languageVersion = languageVersion; + sourceFile.fileName = ts.normalizePath(fileName); + sourceFile.languageVariant = getLanguageVariant(scriptKind); + sourceFile.isDeclarationFile = isDeclarationFile; + sourceFile.scriptKind = scriptKind; + return sourceFile; + } + function setContextFlag(val, flag) { + if (val) { + contextFlags |= flag; + } + else { + contextFlags &= ~flag; + } + } + function setDisallowInContext(val) { + setContextFlag(val, 2048 /* DisallowInContext */); + } + function setYieldContext(val) { + setContextFlag(val, 4096 /* YieldContext */); + } + function setDecoratorContext(val) { + setContextFlag(val, 8192 /* DecoratorContext */); + } + function setAwaitContext(val) { + setContextFlag(val, 16384 /* AwaitContext */); + } + function doOutsideOfContext(context, func) { + // contextFlagsToClear will contain only the context flags that are + // currently set that we need to temporarily clear + // We don't just blindly reset to the previous flags to ensure + // that we do not mutate cached flags for the incremental + // parser (ThisNodeHasError, ThisNodeOrAnySubNodesHasError, and + // HasAggregatedChildData). + var contextFlagsToClear = context & contextFlags; + if (contextFlagsToClear) { + // clear the requested context flags + setContextFlag(/*val*/ false, contextFlagsToClear); + var result = func(); + // restore the context flags we just cleared + setContextFlag(/*val*/ true, contextFlagsToClear); + return result; + } + // no need to do anything special as we are not in any of the requested contexts + return func(); + } + function doInsideOfContext(context, func) { + // contextFlagsToSet will contain only the context flags that + // are not currently set that we need to temporarily enable. + // We don't just blindly reset to the previous flags to ensure + // that we do not mutate cached flags for the incremental + // parser (ThisNodeHasError, ThisNodeOrAnySubNodesHasError, and + // HasAggregatedChildData). + var contextFlagsToSet = context & ~contextFlags; + if (contextFlagsToSet) { + // set the requested context flags + setContextFlag(/*val*/ true, contextFlagsToSet); + var result = func(); + // reset the context flags we just set + setContextFlag(/*val*/ false, contextFlagsToSet); + return result; + } + // no need to do anything special as we are already in all of the requested contexts + return func(); + } + function allowInAnd(func) { + return doOutsideOfContext(2048 /* DisallowInContext */, func); + } + function disallowInAnd(func) { + return doInsideOfContext(2048 /* DisallowInContext */, func); + } + function doInYieldContext(func) { + return doInsideOfContext(4096 /* YieldContext */, func); + } + function doInDecoratorContext(func) { + return doInsideOfContext(8192 /* DecoratorContext */, func); + } + function doInAwaitContext(func) { + return doInsideOfContext(16384 /* AwaitContext */, func); + } + function doOutsideOfAwaitContext(func) { + return doOutsideOfContext(16384 /* AwaitContext */, func); + } + function doInYieldAndAwaitContext(func) { + return doInsideOfContext(4096 /* YieldContext */ | 16384 /* AwaitContext */, func); + } + function inContext(flags) { + return (contextFlags & flags) !== 0; + } + function inYieldContext() { + return inContext(4096 /* YieldContext */); + } + function inDisallowInContext() { + return inContext(2048 /* DisallowInContext */); + } + function inDecoratorContext() { + return inContext(8192 /* DecoratorContext */); + } + function inAwaitContext() { + return inContext(16384 /* AwaitContext */); + } + function parseErrorAtCurrentToken(message, arg0) { + parseErrorAt(scanner.getTokenPos(), scanner.getTextPos(), message, arg0); + } + function parseErrorAtPosition(start, length, message, arg0) { + // Don't report another error if it would just be at the same position as the last error. + var lastError = ts.lastOrUndefined(parseDiagnostics); + if (!lastError || start !== lastError.start) { + parseDiagnostics.push(ts.createFileDiagnostic(sourceFile, start, length, message, arg0)); + } + // Mark that we've encountered an error. We'll set an appropriate bit on the next + // node we finish so that it can't be reused incrementally. + parseErrorBeforeNextFinishedNode = true; + } + function parseErrorAt(start, end, message, arg0) { + parseErrorAtPosition(start, end - start, message, arg0); + } + function parseErrorAtRange(range, message, arg0) { + parseErrorAt(range.pos, range.end, message, arg0); + } + function scanError(message, length) { + parseErrorAtPosition(scanner.getTextPos(), length, message); + } + function getNodePos() { + return scanner.getStartPos(); + } + // Use this function to access the current token instead of reading the currentToken + // variable. Since function results aren't narrowed in control flow analysis, this ensures + // that the type checker doesn't make wrong assumptions about the type of the current + // token (e.g. a call to nextToken() changes the current token but the checker doesn't + // reason about this side effect). Mainstream VMs inline simple functions like this, so + // there is no performance penalty. + function token() { + return currentToken; + } + function nextToken() { + return currentToken = scanner.scan(); + } + function reScanGreaterToken() { + return currentToken = scanner.reScanGreaterToken(); + } + function reScanSlashToken() { + return currentToken = scanner.reScanSlashToken(); + } + function reScanTemplateToken() { + return currentToken = scanner.reScanTemplateToken(); + } + function scanJsxIdentifier() { + return currentToken = scanner.scanJsxIdentifier(); + } + function scanJsxText() { + return currentToken = scanner.scanJsxToken(); + } + function scanJsxAttributeValue() { + return currentToken = scanner.scanJsxAttributeValue(); + } + function speculationHelper(callback, isLookAhead) { + // Keep track of the state we'll need to rollback to if lookahead fails (or if the + // caller asked us to always reset our state). + var saveToken = currentToken; + var saveParseDiagnosticsLength = parseDiagnostics.length; + var saveParseErrorBeforeNextFinishedNode = parseErrorBeforeNextFinishedNode; + // Note: it is not actually necessary to save/restore the context flags here. That's + // because the saving/restoring of these flags happens naturally through the recursive + // descent nature of our parser. However, we still store this here just so we can + // assert that invariant holds. + var saveContextFlags = contextFlags; + // If we're only looking ahead, then tell the scanner to only lookahead as well. + // Otherwise, if we're actually speculatively parsing, then tell the scanner to do the + // same. + var result = isLookAhead + ? scanner.lookAhead(callback) + : scanner.tryScan(callback); + ts.Debug.assert(saveContextFlags === contextFlags); + // If our callback returned something 'falsy' or we're just looking ahead, + // then unconditionally restore us to where we were. + if (!result || isLookAhead) { + currentToken = saveToken; + parseDiagnostics.length = saveParseDiagnosticsLength; + parseErrorBeforeNextFinishedNode = saveParseErrorBeforeNextFinishedNode; + } + return result; + } + /** Invokes the provided callback then unconditionally restores the parser to the state it + * was in immediately prior to invoking the callback. The result of invoking the callback + * is returned from this function. + */ + function lookAhead(callback) { + return speculationHelper(callback, /*isLookAhead*/ true); + } + /** Invokes the provided callback. If the callback returns something falsy, then it restores + * the parser to the state it was in immediately prior to invoking the callback. If the + * callback returns something truthy, then the parser state is not rolled back. The result + * of invoking the callback is returned from this function. + */ + function tryParse(callback) { + return speculationHelper(callback, /*isLookAhead*/ false); + } + // Ignore strict mode flag because we will report an error in type checker instead. + function isIdentifier() { + if (token() === 72 /* Identifier */) { + return true; + } + // If we have a 'yield' keyword, and we're in the [yield] context, then 'yield' is + // considered a keyword and is not an identifier. + if (token() === 117 /* YieldKeyword */ && inYieldContext()) { + return false; + } + // If we have a 'await' keyword, and we're in the [Await] context, then 'await' is + // considered a keyword and is not an identifier. + if (token() === 122 /* AwaitKeyword */ && inAwaitContext()) { + return false; + } + return token() > 108 /* LastReservedWord */; + } + function parseExpected(kind, diagnosticMessage, shouldAdvance) { + if (shouldAdvance === void 0) { shouldAdvance = true; } + if (token() === kind) { + if (shouldAdvance) { + nextToken(); + } + return true; + } + // Report specific message if provided with one. Otherwise, report generic fallback message. + if (diagnosticMessage) { + parseErrorAtCurrentToken(diagnosticMessage); + } + else { + parseErrorAtCurrentToken(ts.Diagnostics._0_expected, ts.tokenToString(kind)); + } + return false; + } + function parseOptional(t) { + if (token() === t) { + nextToken(); + return true; + } + return false; + } + function parseOptionalToken(t) { + if (token() === t) { + return parseTokenNode(); + } + return undefined; + } + function parseExpectedToken(t, diagnosticMessage, arg0) { + return parseOptionalToken(t) || + createMissingNode(t, /*reportAtCurrentPosition*/ false, diagnosticMessage || ts.Diagnostics._0_expected, arg0 || ts.tokenToString(t)); + } + function parseTokenNode() { + var node = createNode(token()); + nextToken(); + return finishNode(node); + } + function canParseSemicolon() { + // If there's a real semicolon, then we can always parse it out. + if (token() === 26 /* SemicolonToken */) { + return true; + } + // We can parse out an optional semicolon in ASI cases in the following cases. + return token() === 19 /* CloseBraceToken */ || token() === 1 /* EndOfFileToken */ || scanner.hasPrecedingLineBreak(); + } + function parseSemicolon() { + if (canParseSemicolon()) { + if (token() === 26 /* SemicolonToken */) { + // consume the semicolon if it was explicitly provided. + nextToken(); + } + return true; + } + else { + return parseExpected(26 /* SemicolonToken */); + } + } + function createNode(kind, pos) { + nodeCount++; + var p = pos >= 0 ? pos : scanner.getStartPos(); + return ts.isNodeKind(kind) || kind === 0 /* Unknown */ ? new NodeConstructor(kind, p, p) : + kind === 72 /* Identifier */ ? new IdentifierConstructor(kind, p, p) : + new TokenConstructor(kind, p, p); + } + function createNodeWithJSDoc(kind, pos) { + var node = createNode(kind, pos); + if (scanner.getTokenFlags() & 2 /* PrecedingJSDocComment */) { + addJSDocComment(node); + } + return node; + } + function createNodeArray(elements, pos, end) { + // Since the element list of a node array is typically created by starting with an empty array and + // repeatedly calling push(), the list may not have the optimal memory layout. We invoke slice() for + // small arrays (1 to 4 elements) to give the VM a chance to allocate an optimal representation. + var length = elements.length; + var array = (length >= 1 && length <= 4 ? elements.slice() : elements); + array.pos = pos; + array.end = end === undefined ? scanner.getStartPos() : end; + return array; + } + function finishNode(node, end) { + node.end = end === undefined ? scanner.getStartPos() : end; + if (contextFlags) { + node.flags |= contextFlags; + } + // Keep track on the node if we encountered an error while parsing it. If we did, then + // we cannot reuse the node incrementally. Once we've marked this node, clear out the + // flag so that we don't mark any subsequent nodes. + if (parseErrorBeforeNextFinishedNode) { + parseErrorBeforeNextFinishedNode = false; + node.flags |= 32768 /* ThisNodeHasError */; + } + return node; + } + function createMissingNode(kind, reportAtCurrentPosition, diagnosticMessage, arg0) { + if (reportAtCurrentPosition) { + parseErrorAtPosition(scanner.getStartPos(), 0, diagnosticMessage, arg0); + } + else if (diagnosticMessage) { + parseErrorAtCurrentToken(diagnosticMessage, arg0); + } + var result = createNode(kind); + if (kind === 72 /* Identifier */) { + result.escapedText = ""; + } + else if (ts.isLiteralKind(kind) || ts.isTemplateLiteralKind(kind)) { + result.text = ""; + } + return finishNode(result); + } + function internIdentifier(text) { + var identifier = identifiers.get(text); + if (identifier === undefined) { + identifiers.set(text, identifier = text); + } + return identifier; + } + // An identifier that starts with two underscores has an extra underscore character prepended to it to avoid issues + // with magic property names like '__proto__'. The 'identifiers' object is used to share a single string instance for + // each identifier in order to reduce memory consumption. + function createIdentifier(isIdentifier, diagnosticMessage) { + identifierCount++; + if (isIdentifier) { + var node = createNode(72 /* Identifier */); + // Store original token kind if it is not just an Identifier so we can report appropriate error later in type checker + if (token() !== 72 /* Identifier */) { + node.originalKeywordKind = token(); + } + node.escapedText = ts.escapeLeadingUnderscores(internIdentifier(scanner.getTokenValue())); + nextToken(); + return finishNode(node); + } + // Only for end of file because the error gets reported incorrectly on embedded script tags. + var reportAtCurrentPosition = token() === 1 /* EndOfFileToken */; + return createMissingNode(72 /* Identifier */, reportAtCurrentPosition, diagnosticMessage || ts.Diagnostics.Identifier_expected); + } + function parseIdentifier(diagnosticMessage) { + return createIdentifier(isIdentifier(), diagnosticMessage); + } + function parseIdentifierName(diagnosticMessage) { + return createIdentifier(ts.tokenIsIdentifierOrKeyword(token()), diagnosticMessage); + } + function isLiteralPropertyName() { + return ts.tokenIsIdentifierOrKeyword(token()) || + token() === 10 /* StringLiteral */ || + token() === 8 /* NumericLiteral */; + } + function parsePropertyNameWorker(allowComputedPropertyNames) { + if (token() === 10 /* StringLiteral */ || token() === 8 /* NumericLiteral */) { + var node = parseLiteralNode(); + node.text = internIdentifier(node.text); + return node; + } + if (allowComputedPropertyNames && token() === 22 /* OpenBracketToken */) { + return parseComputedPropertyName(); + } + return parseIdentifierName(); + } + function parsePropertyName() { + return parsePropertyNameWorker(/*allowComputedPropertyNames*/ true); + } + function parseComputedPropertyName() { + // PropertyName [Yield]: + // LiteralPropertyName + // ComputedPropertyName[?Yield] + var node = createNode(149 /* ComputedPropertyName */); + parseExpected(22 /* OpenBracketToken */); + // We parse any expression (including a comma expression). But the grammar + // says that only an assignment expression is allowed, so the grammar checker + // will error if it sees a comma expression. + node.expression = allowInAnd(parseExpression); + parseExpected(23 /* CloseBracketToken */); + return finishNode(node); + } + function parseContextualModifier(t) { + return token() === t && tryParse(nextTokenCanFollowModifier); + } + function nextTokenIsOnSameLineAndCanFollowModifier() { + nextToken(); + if (scanner.hasPrecedingLineBreak()) { + return false; + } + return canFollowModifier(); + } + function nextTokenCanFollowModifier() { + switch (token()) { + case 77 /* ConstKeyword */: + // 'const' is only a modifier if followed by 'enum'. + return nextToken() === 84 /* EnumKeyword */; + case 85 /* ExportKeyword */: + nextToken(); + if (token() === 80 /* DefaultKeyword */) { + return lookAhead(nextTokenCanFollowDefaultKeyword); + } + return token() !== 40 /* AsteriskToken */ && token() !== 119 /* AsKeyword */ && token() !== 18 /* OpenBraceToken */ && canFollowModifier(); + case 80 /* DefaultKeyword */: + return nextTokenCanFollowDefaultKeyword(); + case 116 /* StaticKeyword */: + case 126 /* GetKeyword */: + case 137 /* SetKeyword */: + nextToken(); + return canFollowModifier(); + default: + return nextTokenIsOnSameLineAndCanFollowModifier(); + } + } + function parseAnyContextualModifier() { + return ts.isModifierKind(token()) && tryParse(nextTokenCanFollowModifier); + } + function canFollowModifier() { + return token() === 22 /* OpenBracketToken */ + || token() === 18 /* OpenBraceToken */ + || token() === 40 /* AsteriskToken */ + || token() === 25 /* DotDotDotToken */ + || isLiteralPropertyName(); + } + function nextTokenCanFollowDefaultKeyword() { + nextToken(); + return token() === 76 /* ClassKeyword */ || token() === 90 /* FunctionKeyword */ || + token() === 110 /* InterfaceKeyword */ || + (token() === 118 /* AbstractKeyword */ && lookAhead(nextTokenIsClassKeywordOnSameLine)) || + (token() === 121 /* AsyncKeyword */ && lookAhead(nextTokenIsFunctionKeywordOnSameLine)); + } + // True if positioned at the start of a list element + function isListElement(parsingContext, inErrorRecovery) { + var node = currentNode(parsingContext); + if (node) { + return true; + } + switch (parsingContext) { + case 0 /* SourceElements */: + case 1 /* BlockStatements */: + case 3 /* SwitchClauseStatements */: + // If we're in error recovery, then we don't want to treat ';' as an empty statement. + // The problem is that ';' can show up in far too many contexts, and if we see one + // and assume it's a statement, then we may bail out inappropriately from whatever + // we're parsing. For example, if we have a semicolon in the middle of a class, then + // we really don't want to assume the class is over and we're on a statement in the + // outer module. We just want to consume and move on. + return !(token() === 26 /* SemicolonToken */ && inErrorRecovery) && isStartOfStatement(); + case 2 /* SwitchClauses */: + return token() === 74 /* CaseKeyword */ || token() === 80 /* DefaultKeyword */; + case 4 /* TypeMembers */: + return lookAhead(isTypeMemberStart); + case 5 /* ClassMembers */: + // We allow semicolons as class elements (as specified by ES6) as long as we're + // not in error recovery. If we're in error recovery, we don't want an errant + // semicolon to be treated as a class member (since they're almost always used + // for statements. + return lookAhead(isClassMemberStart) || (token() === 26 /* SemicolonToken */ && !inErrorRecovery); + case 6 /* EnumMembers */: + // Include open bracket computed properties. This technically also lets in indexers, + // which would be a candidate for improved error reporting. + return token() === 22 /* OpenBracketToken */ || isLiteralPropertyName(); + case 12 /* ObjectLiteralMembers */: + switch (token()) { + case 22 /* OpenBracketToken */: + case 40 /* AsteriskToken */: + case 25 /* DotDotDotToken */: + case 24 /* DotToken */: // Not an object literal member, but don't want to close the object (see `tests/cases/fourslash/completionsDotInObjectLiteral.ts`) + return true; + default: + return isLiteralPropertyName(); + } + case 18 /* RestProperties */: + return isLiteralPropertyName(); + case 9 /* ObjectBindingElements */: + return token() === 22 /* OpenBracketToken */ || token() === 25 /* DotDotDotToken */ || isLiteralPropertyName(); + case 7 /* HeritageClauseElement */: + // If we see `{ ... }` then only consume it as an expression if it is followed by `,` or `{` + // That way we won't consume the body of a class in its heritage clause. + if (token() === 18 /* OpenBraceToken */) { + return lookAhead(isValidHeritageClauseObjectLiteral); + } + if (!inErrorRecovery) { + return isStartOfLeftHandSideExpression() && !isHeritageClauseExtendsOrImplementsKeyword(); + } + else { + // If we're in error recovery we tighten up what we're willing to match. + // That way we don't treat something like "this" as a valid heritage clause + // element during recovery. + return isIdentifier() && !isHeritageClauseExtendsOrImplementsKeyword(); + } + case 8 /* VariableDeclarations */: + return isIdentifierOrPattern(); + case 10 /* ArrayBindingElements */: + return token() === 27 /* CommaToken */ || token() === 25 /* DotDotDotToken */ || isIdentifierOrPattern(); + case 19 /* TypeParameters */: + return isIdentifier(); + case 15 /* ArrayLiteralMembers */: + switch (token()) { + case 27 /* CommaToken */: + case 24 /* DotToken */: // Not an array literal member, but don't want to close the array (see `tests/cases/fourslash/completionsDotInArrayLiteralInObjectLiteral.ts`) + return true; + } + // falls through + case 11 /* ArgumentExpressions */: + return token() === 25 /* DotDotDotToken */ || isStartOfExpression(); + case 16 /* Parameters */: + return isStartOfParameter(/*isJSDocParameter*/ false); + case 17 /* JSDocParameters */: + return isStartOfParameter(/*isJSDocParameter*/ true); + case 20 /* TypeArguments */: + case 21 /* TupleElementTypes */: + return token() === 27 /* CommaToken */ || isStartOfType(); + case 22 /* HeritageClauses */: + return isHeritageClause(); + case 23 /* ImportOrExportSpecifiers */: + return ts.tokenIsIdentifierOrKeyword(token()); + case 13 /* JsxAttributes */: + return ts.tokenIsIdentifierOrKeyword(token()) || token() === 18 /* OpenBraceToken */; + case 14 /* JsxChildren */: + return true; + } + return ts.Debug.fail("Non-exhaustive case in 'isListElement'."); + } + function isValidHeritageClauseObjectLiteral() { + ts.Debug.assert(token() === 18 /* OpenBraceToken */); + if (nextToken() === 19 /* CloseBraceToken */) { + // if we see "extends {}" then only treat the {} as what we're extending (and not + // the class body) if we have: + // + // extends {} { + // extends {}, + // extends {} extends + // extends {} implements + var next = nextToken(); + return next === 27 /* CommaToken */ || next === 18 /* OpenBraceToken */ || next === 86 /* ExtendsKeyword */ || next === 109 /* ImplementsKeyword */; + } + return true; + } + function nextTokenIsIdentifier() { + nextToken(); + return isIdentifier(); + } + function nextTokenIsIdentifierOrKeyword() { + nextToken(); + return ts.tokenIsIdentifierOrKeyword(token()); + } + function nextTokenIsIdentifierOrKeywordOrGreaterThan() { + nextToken(); + return ts.tokenIsIdentifierOrKeywordOrGreaterThan(token()); + } + function isHeritageClauseExtendsOrImplementsKeyword() { + if (token() === 109 /* ImplementsKeyword */ || + token() === 86 /* ExtendsKeyword */) { + return lookAhead(nextTokenIsStartOfExpression); + } + return false; + } + function nextTokenIsStartOfExpression() { + nextToken(); + return isStartOfExpression(); + } + function nextTokenIsStartOfType() { + nextToken(); + return isStartOfType(); + } + // True if positioned at a list terminator + function isListTerminator(kind) { + if (token() === 1 /* EndOfFileToken */) { + // Being at the end of the file ends all lists. + return true; + } + switch (kind) { + case 1 /* BlockStatements */: + case 2 /* SwitchClauses */: + case 4 /* TypeMembers */: + case 5 /* ClassMembers */: + case 6 /* EnumMembers */: + case 12 /* ObjectLiteralMembers */: + case 9 /* ObjectBindingElements */: + case 23 /* ImportOrExportSpecifiers */: + return token() === 19 /* CloseBraceToken */; + case 3 /* SwitchClauseStatements */: + return token() === 19 /* CloseBraceToken */ || token() === 74 /* CaseKeyword */ || token() === 80 /* DefaultKeyword */; + case 7 /* HeritageClauseElement */: + return token() === 18 /* OpenBraceToken */ || token() === 86 /* ExtendsKeyword */ || token() === 109 /* ImplementsKeyword */; + case 8 /* VariableDeclarations */: + return isVariableDeclaratorListTerminator(); + case 19 /* TypeParameters */: + // Tokens other than '>' are here for better error recovery + return token() === 30 /* GreaterThanToken */ || token() === 20 /* OpenParenToken */ || token() === 18 /* OpenBraceToken */ || token() === 86 /* ExtendsKeyword */ || token() === 109 /* ImplementsKeyword */; + case 11 /* ArgumentExpressions */: + // Tokens other than ')' are here for better error recovery + return token() === 21 /* CloseParenToken */ || token() === 26 /* SemicolonToken */; + case 15 /* ArrayLiteralMembers */: + case 21 /* TupleElementTypes */: + case 10 /* ArrayBindingElements */: + return token() === 23 /* CloseBracketToken */; + case 17 /* JSDocParameters */: + case 16 /* Parameters */: + case 18 /* RestProperties */: + // Tokens other than ')' and ']' (the latter for index signatures) are here for better error recovery + return token() === 21 /* CloseParenToken */ || token() === 23 /* CloseBracketToken */ /*|| token === SyntaxKind.OpenBraceToken*/; + case 20 /* TypeArguments */: + // All other tokens should cause the type-argument to terminate except comma token + return token() !== 27 /* CommaToken */; + case 22 /* HeritageClauses */: + return token() === 18 /* OpenBraceToken */ || token() === 19 /* CloseBraceToken */; + case 13 /* JsxAttributes */: + return token() === 30 /* GreaterThanToken */ || token() === 42 /* SlashToken */; + case 14 /* JsxChildren */: + return token() === 28 /* LessThanToken */ && lookAhead(nextTokenIsSlash); + default: + return false; + } + } + function isVariableDeclaratorListTerminator() { + // If we can consume a semicolon (either explicitly, or with ASI), then consider us done + // with parsing the list of variable declarators. + if (canParseSemicolon()) { + return true; + } + // in the case where we're parsing the variable declarator of a 'for-in' statement, we + // are done if we see an 'in' keyword in front of us. Same with for-of + if (isInOrOfKeyword(token())) { + return true; + } + // ERROR RECOVERY TWEAK: + // For better error recovery, if we see an '=>' then we just stop immediately. We've got an + // arrow function here and it's going to be very unlikely that we'll resynchronize and get + // another variable declaration. + if (token() === 37 /* EqualsGreaterThanToken */) { + return true; + } + // Keep trying to parse out variable declarators. + return false; + } + // True if positioned at element or terminator of the current list or any enclosing list + function isInSomeParsingContext() { + for (var kind = 0; kind < 24 /* Count */; kind++) { + if (parsingContext & (1 << kind)) { + if (isListElement(kind, /*inErrorRecovery*/ true) || isListTerminator(kind)) { + return true; + } + } + } + return false; + } + // Parses a list of elements + function parseList(kind, parseElement) { + var saveParsingContext = parsingContext; + parsingContext |= 1 << kind; + var list = []; + var listPos = getNodePos(); + while (!isListTerminator(kind)) { + if (isListElement(kind, /*inErrorRecovery*/ false)) { + var element = parseListElement(kind, parseElement); + list.push(element); + continue; + } + if (abortParsingListOrMoveToNextToken(kind)) { + break; + } + } + parsingContext = saveParsingContext; + return createNodeArray(list, listPos); + } + function parseListElement(parsingContext, parseElement) { + var node = currentNode(parsingContext); + if (node) { + return consumeNode(node); + } + return parseElement(); + } + function currentNode(parsingContext) { + // If there is an outstanding parse error that we've encountered, but not attached to + // some node, then we cannot get a node from the old source tree. This is because we + // want to mark the next node we encounter as being unusable. + // + // Note: This may be too conservative. Perhaps we could reuse the node and set the bit + // on it (or its leftmost child) as having the error. For now though, being conservative + // is nice and likely won't ever affect perf. + if (parseErrorBeforeNextFinishedNode) { + return undefined; + } + if (!syntaxCursor) { + // if we don't have a cursor, we could never return a node from the old tree. + return undefined; + } + var node = syntaxCursor.currentNode(scanner.getStartPos()); + // Can't reuse a missing node. + if (ts.nodeIsMissing(node)) { + return undefined; + } + // Can't reuse a node that intersected the change range. + if (node.intersectsChange) { + return undefined; + } + // Can't reuse a node that contains a parse error. This is necessary so that we + // produce the same set of errors again. + if (ts.containsParseError(node)) { + return undefined; + } + // We can only reuse a node if it was parsed under the same strict mode that we're + // currently in. i.e. if we originally parsed a node in non-strict mode, but then + // the user added 'using strict' at the top of the file, then we can't use that node + // again as the presence of strict mode may cause us to parse the tokens in the file + // differently. + // + // Note: we *can* reuse tokens when the strict mode changes. That's because tokens + // are unaffected by strict mode. It's just the parser will decide what to do with it + // differently depending on what mode it is in. + // + // This also applies to all our other context flags as well. + var nodeContextFlags = node.flags & 12679168 /* ContextFlags */; + if (nodeContextFlags !== contextFlags) { + return undefined; + } + // Ok, we have a node that looks like it could be reused. Now verify that it is valid + // in the current list parsing context that we're currently at. + if (!canReuseNode(node, parsingContext)) { + return undefined; + } + if (node.jsDocCache) { + // jsDocCache may include tags from parent nodes, which might have been modified. + node.jsDocCache = undefined; + } + return node; + } + function consumeNode(node) { + // Move the scanner so it is after the node we just consumed. + scanner.setTextPos(node.end); + nextToken(); + return node; + } + function canReuseNode(node, parsingContext) { + switch (parsingContext) { + case 5 /* ClassMembers */: + return isReusableClassMember(node); + case 2 /* SwitchClauses */: + return isReusableSwitchClause(node); + case 0 /* SourceElements */: + case 1 /* BlockStatements */: + case 3 /* SwitchClauseStatements */: + return isReusableStatement(node); + case 6 /* EnumMembers */: + return isReusableEnumMember(node); + case 4 /* TypeMembers */: + return isReusableTypeMember(node); + case 8 /* VariableDeclarations */: + return isReusableVariableDeclaration(node); + case 17 /* JSDocParameters */: + case 16 /* Parameters */: + return isReusableParameter(node); + case 18 /* RestProperties */: + return false; + // Any other lists we do not care about reusing nodes in. But feel free to add if + // you can do so safely. Danger areas involve nodes that may involve speculative + // parsing. If speculative parsing is involved with the node, then the range the + // parser reached while looking ahead might be in the edited range (see the example + // in canReuseVariableDeclaratorNode for a good case of this). + case 22 /* HeritageClauses */: + // This would probably be safe to reuse. There is no speculative parsing with + // heritage clauses. + case 19 /* TypeParameters */: + // This would probably be safe to reuse. There is no speculative parsing with + // type parameters. Note that that's because type *parameters* only occur in + // unambiguous *type* contexts. While type *arguments* occur in very ambiguous + // *expression* contexts. + case 21 /* TupleElementTypes */: + // This would probably be safe to reuse. There is no speculative parsing with + // tuple types. + // Technically, type argument list types are probably safe to reuse. While + // speculative parsing is involved with them (since type argument lists are only + // produced from speculative parsing a < as a type argument list), we only have + // the types because speculative parsing succeeded. Thus, the lookahead never + // went past the end of the list and rewound. + case 20 /* TypeArguments */: + // Note: these are almost certainly not safe to ever reuse. Expressions commonly + // need a large amount of lookahead, and we should not reuse them as they may + // have actually intersected the edit. + case 11 /* ArgumentExpressions */: + // This is not safe to reuse for the same reason as the 'AssignmentExpression' + // cases. i.e. a property assignment may end with an expression, and thus might + // have lookahead far beyond it's old node. + case 12 /* ObjectLiteralMembers */: + // This is probably not safe to reuse. There can be speculative parsing with + // type names in a heritage clause. There can be generic names in the type + // name list, and there can be left hand side expressions (which can have type + // arguments.) + case 7 /* HeritageClauseElement */: + // Perhaps safe to reuse, but it's unlikely we'd see more than a dozen attributes + // on any given element. Same for children. + case 13 /* JsxAttributes */: + case 14 /* JsxChildren */: + } + return false; + } + function isReusableClassMember(node) { + if (node) { + switch (node.kind) { + case 157 /* Constructor */: + case 162 /* IndexSignature */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 154 /* PropertyDeclaration */: + case 217 /* SemicolonClassElement */: + return true; + case 156 /* MethodDeclaration */: + // Method declarations are not necessarily reusable. An object-literal + // may have a method calls "constructor(...)" and we must reparse that + // into an actual .ConstructorDeclaration. + var methodDeclaration = node; + var nameIsConstructor = methodDeclaration.name.kind === 72 /* Identifier */ && + methodDeclaration.name.originalKeywordKind === 124 /* ConstructorKeyword */; + return !nameIsConstructor; + } + } + return false; + } + function isReusableSwitchClause(node) { + if (node) { + switch (node.kind) { + case 271 /* CaseClause */: + case 272 /* DefaultClause */: + return true; + } + } + return false; + } + function isReusableStatement(node) { + if (node) { + switch (node.kind) { + case 239 /* FunctionDeclaration */: + case 219 /* VariableStatement */: + case 218 /* Block */: + case 222 /* IfStatement */: + case 221 /* ExpressionStatement */: + case 234 /* ThrowStatement */: + case 230 /* ReturnStatement */: + case 232 /* SwitchStatement */: + case 229 /* BreakStatement */: + case 228 /* ContinueStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + case 225 /* ForStatement */: + case 224 /* WhileStatement */: + case 231 /* WithStatement */: + case 220 /* EmptyStatement */: + case 235 /* TryStatement */: + case 233 /* LabeledStatement */: + case 223 /* DoStatement */: + case 236 /* DebuggerStatement */: + case 249 /* ImportDeclaration */: + case 248 /* ImportEqualsDeclaration */: + case 255 /* ExportDeclaration */: + case 254 /* ExportAssignment */: + case 244 /* ModuleDeclaration */: + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + case 243 /* EnumDeclaration */: + case 242 /* TypeAliasDeclaration */: + return true; + } + } + return false; + } + function isReusableEnumMember(node) { + return node.kind === 278 /* EnumMember */; + } + function isReusableTypeMember(node) { + if (node) { + switch (node.kind) { + case 161 /* ConstructSignature */: + case 155 /* MethodSignature */: + case 162 /* IndexSignature */: + case 153 /* PropertySignature */: + case 160 /* CallSignature */: + return true; + } + } + return false; + } + function isReusableVariableDeclaration(node) { + if (node.kind !== 237 /* VariableDeclaration */) { + return false; + } + // Very subtle incremental parsing bug. Consider the following code: + // + // let v = new List < A, B + // + // This is actually legal code. It's a list of variable declarators "v = new List() + // + // then we have a problem. "v = new List= 0) { + // Always preserve a trailing comma by marking it on the NodeArray + result.hasTrailingComma = true; + } + return result; + } + function createMissingList() { + var list = createNodeArray([], getNodePos()); + list.isMissingList = true; + return list; + } + function isMissingList(arr) { + return !!arr.isMissingList; + } + function parseBracketedList(kind, parseElement, open, close) { + if (parseExpected(open)) { + var result = parseDelimitedList(kind, parseElement); + parseExpected(close); + return result; + } + return createMissingList(); + } + function parseEntityName(allowReservedWords, diagnosticMessage) { + var entity = allowReservedWords ? parseIdentifierName(diagnosticMessage) : parseIdentifier(diagnosticMessage); + var dotPos = scanner.getStartPos(); + while (parseOptional(24 /* DotToken */)) { + if (token() === 28 /* LessThanToken */) { + // the entity is part of a JSDoc-style generic, so record the trailing dot for later error reporting + entity.jsdocDotPos = dotPos; + break; + } + dotPos = scanner.getStartPos(); + entity = createQualifiedName(entity, parseRightSideOfDot(allowReservedWords)); + } + return entity; + } + function createQualifiedName(entity, name) { + var node = createNode(148 /* QualifiedName */, entity.pos); + node.left = entity; + node.right = name; + return finishNode(node); + } + function parseRightSideOfDot(allowIdentifierNames) { + // Technically a keyword is valid here as all identifiers and keywords are identifier names. + // However, often we'll encounter this in error situations when the identifier or keyword + // is actually starting another valid construct. + // + // So, we check for the following specific case: + // + // name. + // identifierOrKeyword identifierNameOrKeyword + // + // Note: the newlines are important here. For example, if that above code + // were rewritten into: + // + // name.identifierOrKeyword + // identifierNameOrKeyword + // + // Then we would consider it valid. That's because ASI would take effect and + // the code would be implicitly: "name.identifierOrKeyword; identifierNameOrKeyword". + // In the first case though, ASI will not take effect because there is not a + // line terminator after the identifier or keyword. + if (scanner.hasPrecedingLineBreak() && ts.tokenIsIdentifierOrKeyword(token())) { + var matchesPattern = lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine); + if (matchesPattern) { + // Report that we need an identifier. However, report it right after the dot, + // and not on the next token. This is because the next token might actually + // be an identifier and the error would be quite confusing. + return createMissingNode(72 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Identifier_expected); + } + } + return allowIdentifierNames ? parseIdentifierName() : parseIdentifier(); + } + function parseTemplateExpression() { + var template = createNode(206 /* TemplateExpression */); + template.head = parseTemplateHead(); + ts.Debug.assert(template.head.kind === 15 /* TemplateHead */, "Template head has wrong token kind"); + var list = []; + var listPos = getNodePos(); + do { + list.push(parseTemplateSpan()); + } while (ts.last(list).literal.kind === 16 /* TemplateMiddle */); + template.templateSpans = createNodeArray(list, listPos); + return finishNode(template); + } + function parseTemplateSpan() { + var span = createNode(216 /* TemplateSpan */); + span.expression = allowInAnd(parseExpression); + var literal; + if (token() === 19 /* CloseBraceToken */) { + reScanTemplateToken(); + literal = parseTemplateMiddleOrTemplateTail(); + } + else { + literal = parseExpectedToken(17 /* TemplateTail */, ts.Diagnostics._0_expected, ts.tokenToString(19 /* CloseBraceToken */)); + } + span.literal = literal; + return finishNode(span); + } + function parseLiteralNode() { + return parseLiteralLikeNode(token()); + } + function parseTemplateHead() { + var fragment = parseLiteralLikeNode(token()); + ts.Debug.assert(fragment.kind === 15 /* TemplateHead */, "Template head has wrong token kind"); + return fragment; + } + function parseTemplateMiddleOrTemplateTail() { + var fragment = parseLiteralLikeNode(token()); + ts.Debug.assert(fragment.kind === 16 /* TemplateMiddle */ || fragment.kind === 17 /* TemplateTail */, "Template fragment has wrong token kind"); + return fragment; + } + function parseLiteralLikeNode(kind) { + var node = createNode(kind); + node.text = scanner.getTokenValue(); + if (scanner.hasExtendedUnicodeEscape()) { + node.hasExtendedUnicodeEscape = true; + } + if (scanner.isUnterminated()) { + node.isUnterminated = true; + } + // Octal literals are not allowed in strict mode or ES5 + // Note that theoretically the following condition would hold true literals like 009, + // which is not octal.But because of how the scanner separates the tokens, we would + // never get a token like this. Instead, we would get 00 and 9 as two separate tokens. + // We also do not need to check for negatives because any prefix operator would be part of a + // parent unary expression. + if (node.kind === 8 /* NumericLiteral */) { + node.numericLiteralFlags = scanner.getTokenFlags() & 1008 /* NumericLiteralFlags */; + } + nextToken(); + finishNode(node); + return node; + } + // TYPES + function parseTypeReference() { + var node = createNode(164 /* TypeReference */); + node.typeName = parseEntityName(/*allowReservedWords*/ true, ts.Diagnostics.Type_expected); + if (!scanner.hasPrecedingLineBreak() && token() === 28 /* LessThanToken */) { + node.typeArguments = parseBracketedList(20 /* TypeArguments */, parseType, 28 /* LessThanToken */, 30 /* GreaterThanToken */); + } + return finishNode(node); + } + // If true, we should abort parsing an error function. + function typeHasArrowFunctionBlockingParseError(node) { + switch (node.kind) { + case 164 /* TypeReference */: + return ts.nodeIsMissing(node.typeName); + case 165 /* FunctionType */: + case 166 /* ConstructorType */: { + var _a = node, parameters = _a.parameters, type = _a.type; + return isMissingList(parameters) || typeHasArrowFunctionBlockingParseError(type); + } + case 177 /* ParenthesizedType */: + return typeHasArrowFunctionBlockingParseError(node.type); + default: + return false; + } + } + function parseThisTypePredicate(lhs) { + nextToken(); + var node = createNode(163 /* TypePredicate */, lhs.pos); + node.parameterName = lhs; + node.type = parseType(); + return finishNode(node); + } + function parseThisTypeNode() { + var node = createNode(178 /* ThisType */); + nextToken(); + return finishNode(node); + } + function parseJSDocAllType(postFixEquals) { + var result = createNode(284 /* JSDocAllType */); + if (postFixEquals) { + return createPostfixType(288 /* JSDocOptionalType */, result); + } + else { + nextToken(); + } + return finishNode(result); + } + function parseJSDocNonNullableType() { + var result = createNode(287 /* JSDocNonNullableType */); + nextToken(); + result.type = parseNonArrayType(); + return finishNode(result); + } + function parseJSDocUnknownOrNullableType() { + var pos = scanner.getStartPos(); + // skip the ? + nextToken(); + // Need to lookahead to decide if this is a nullable or unknown type. + // Here are cases where we'll pick the unknown type: + // + // Foo(?, + // { a: ? } + // Foo(?) + // Foo + // Foo(?= + // (?| + if (token() === 27 /* CommaToken */ || + token() === 19 /* CloseBraceToken */ || + token() === 21 /* CloseParenToken */ || + token() === 30 /* GreaterThanToken */ || + token() === 59 /* EqualsToken */ || + token() === 50 /* BarToken */) { + var result = createNode(285 /* JSDocUnknownType */, pos); + return finishNode(result); + } + else { + var result = createNode(286 /* JSDocNullableType */, pos); + result.type = parseType(); + return finishNode(result); + } + } + function parseJSDocFunctionType() { + if (lookAhead(nextTokenIsOpenParen)) { + var result = createNodeWithJSDoc(289 /* JSDocFunctionType */); + nextToken(); + fillSignature(57 /* ColonToken */, 4 /* Type */ | 32 /* JSDoc */, result); + return finishNode(result); + } + var node = createNode(164 /* TypeReference */); + node.typeName = parseIdentifierName(); + return finishNode(node); + } + function parseJSDocParameter() { + var parameter = createNode(151 /* Parameter */); + if (token() === 100 /* ThisKeyword */ || token() === 95 /* NewKeyword */) { + parameter.name = parseIdentifierName(); + parseExpected(57 /* ColonToken */); + } + parameter.type = parseJSDocType(); + return finishNode(parameter); + } + function parseJSDocType() { + scanner.setInJSDocType(true); + var dotdotdot = parseOptionalToken(25 /* DotDotDotToken */); + var type = parseTypeOrTypePredicate(); + scanner.setInJSDocType(false); + if (dotdotdot) { + var variadic = createNode(290 /* JSDocVariadicType */, dotdotdot.pos); + variadic.type = type; + type = finishNode(variadic); + } + if (token() === 59 /* EqualsToken */) { + return createPostfixType(288 /* JSDocOptionalType */, type); + } + return type; + } + function parseTypeQuery() { + var node = createNode(167 /* TypeQuery */); + parseExpected(104 /* TypeOfKeyword */); + node.exprName = parseEntityName(/*allowReservedWords*/ true); + return finishNode(node); + } + function parseTypeParameter() { + var node = createNode(150 /* TypeParameter */); + node.name = parseIdentifier(); + if (parseOptional(86 /* ExtendsKeyword */)) { + // It's not uncommon for people to write improper constraints to a generic. If the + // user writes a constraint that is an expression and not an actual type, then parse + // it out as an expression (so we can recover well), but report that a type is needed + // instead. + if (isStartOfType() || !isStartOfExpression()) { + node.constraint = parseType(); + } + else { + // It was not a type, and it looked like an expression. Parse out an expression + // here so we recover well. Note: it is important that we call parseUnaryExpression + // and not parseExpression here. If the user has: + // + // + // + // We do *not* want to consume the `>` as we're consuming the expression for "". + node.expression = parseUnaryExpressionOrHigher(); + } + } + if (parseOptional(59 /* EqualsToken */)) { + node.default = parseType(); + } + return finishNode(node); + } + function parseTypeParameters() { + if (token() === 28 /* LessThanToken */) { + return parseBracketedList(19 /* TypeParameters */, parseTypeParameter, 28 /* LessThanToken */, 30 /* GreaterThanToken */); + } + } + function parseParameterType() { + if (parseOptional(57 /* ColonToken */)) { + return parseType(); + } + return undefined; + } + function isStartOfParameter(isJSDocParameter) { + return token() === 25 /* DotDotDotToken */ || + isIdentifierOrPattern() || + ts.isModifierKind(token()) || + token() === 58 /* AtToken */ || + isStartOfType(/*inStartOfParameter*/ !isJSDocParameter); + } + function parseParameter() { + var node = createNodeWithJSDoc(151 /* Parameter */); + if (token() === 100 /* ThisKeyword */) { + node.name = createIdentifier(/*isIdentifier*/ true); + node.type = parseParameterType(); + return finishNode(node); + } + node.decorators = parseDecorators(); + node.modifiers = parseModifiers(); + node.dotDotDotToken = parseOptionalToken(25 /* DotDotDotToken */); + // FormalParameter [Yield,Await]: + // BindingElement[?Yield,?Await] + node.name = parseIdentifierOrPattern(); + if (ts.getFullWidth(node.name) === 0 && !ts.hasModifiers(node) && ts.isModifierKind(token())) { + // in cases like + // 'use strict' + // function foo(static) + // isParameter('static') === true, because of isModifier('static') + // however 'static' is not a legal identifier in a strict mode. + // so result of this function will be ParameterDeclaration (flags = 0, name = missing, type = undefined, initializer = undefined) + // and current token will not change => parsing of the enclosing parameter list will last till the end of time (or OOM) + // to avoid this we'll advance cursor to the next token. + nextToken(); + } + node.questionToken = parseOptionalToken(56 /* QuestionToken */); + node.type = parseParameterType(); + node.initializer = parseInitializer(); + return finishNode(node); + } + /** + * Note: If returnToken is EqualsGreaterThanToken, `signature.type` will always be defined. + * @returns If return type parsing succeeds + */ + function fillSignature(returnToken, flags, signature) { + if (!(flags & 32 /* JSDoc */)) { + signature.typeParameters = parseTypeParameters(); + } + var parametersParsedSuccessfully = parseParameterList(signature, flags); + if (shouldParseReturnType(returnToken, !!(flags & 4 /* Type */))) { + signature.type = parseTypeOrTypePredicate(); + if (typeHasArrowFunctionBlockingParseError(signature.type)) + return false; + } + return parametersParsedSuccessfully; + } + function shouldParseReturnType(returnToken, isType) { + if (returnToken === 37 /* EqualsGreaterThanToken */) { + parseExpected(returnToken); + return true; + } + else if (parseOptional(57 /* ColonToken */)) { + return true; + } + else if (isType && token() === 37 /* EqualsGreaterThanToken */) { + // This is easy to get backward, especially in type contexts, so parse the type anyway + parseErrorAtCurrentToken(ts.Diagnostics._0_expected, ts.tokenToString(57 /* ColonToken */)); + nextToken(); + return true; + } + return false; + } + // Returns true on success. + function parseParameterList(signature, flags) { + // FormalParameters [Yield,Await]: (modified) + // [empty] + // FormalParameterList[?Yield,Await] + // + // FormalParameter[Yield,Await]: (modified) + // BindingElement[?Yield,Await] + // + // BindingElement [Yield,Await]: (modified) + // SingleNameBinding[?Yield,?Await] + // BindingPattern[?Yield,?Await]Initializer [In, ?Yield,?Await] opt + // + // SingleNameBinding [Yield,Await]: + // BindingIdentifier[?Yield,?Await]Initializer [In, ?Yield,?Await] opt + if (!parseExpected(20 /* OpenParenToken */)) { + signature.parameters = createMissingList(); + return false; + } + var savedYieldContext = inYieldContext(); + var savedAwaitContext = inAwaitContext(); + setYieldContext(!!(flags & 1 /* Yield */)); + setAwaitContext(!!(flags & 2 /* Await */)); + signature.parameters = flags & 32 /* JSDoc */ ? + parseDelimitedList(17 /* JSDocParameters */, parseJSDocParameter) : + parseDelimitedList(16 /* Parameters */, parseParameter); + setYieldContext(savedYieldContext); + setAwaitContext(savedAwaitContext); + return parseExpected(21 /* CloseParenToken */); + } + function parseTypeMemberSemicolon() { + // We allow type members to be separated by commas or (possibly ASI) semicolons. + // First check if it was a comma. If so, we're done with the member. + if (parseOptional(27 /* CommaToken */)) { + return; + } + // Didn't have a comma. We must have a (possible ASI) semicolon. + parseSemicolon(); + } + function parseSignatureMember(kind) { + var node = createNodeWithJSDoc(kind); + if (kind === 161 /* ConstructSignature */) { + parseExpected(95 /* NewKeyword */); + } + fillSignature(57 /* ColonToken */, 4 /* Type */, node); + parseTypeMemberSemicolon(); + return finishNode(node); + } + function isIndexSignature() { + return token() === 22 /* OpenBracketToken */ && lookAhead(isUnambiguouslyIndexSignature); + } + function isUnambiguouslyIndexSignature() { + // The only allowed sequence is: + // + // [id: + // + // However, for error recovery, we also check the following cases: + // + // [... + // [id, + // [id?, + // [id?: + // [id?] + // [public id + // [private id + // [protected id + // [] + // + nextToken(); + if (token() === 25 /* DotDotDotToken */ || token() === 23 /* CloseBracketToken */) { + return true; + } + if (ts.isModifierKind(token())) { + nextToken(); + if (isIdentifier()) { + return true; + } + } + else if (!isIdentifier()) { + return false; + } + else { + // Skip the identifier + nextToken(); + } + // A colon signifies a well formed indexer + // A comma should be a badly formed indexer because comma expressions are not allowed + // in computed properties. + if (token() === 57 /* ColonToken */ || token() === 27 /* CommaToken */) { + return true; + } + // Question mark could be an indexer with an optional property, + // or it could be a conditional expression in a computed property. + if (token() !== 56 /* QuestionToken */) { + return false; + } + // If any of the following tokens are after the question mark, it cannot + // be a conditional expression, so treat it as an indexer. + nextToken(); + return token() === 57 /* ColonToken */ || token() === 27 /* CommaToken */ || token() === 23 /* CloseBracketToken */; + } + function parseIndexSignatureDeclaration(node) { + node.kind = 162 /* IndexSignature */; + node.parameters = parseBracketedList(16 /* Parameters */, parseParameter, 22 /* OpenBracketToken */, 23 /* CloseBracketToken */); + node.type = parseTypeAnnotation(); + parseTypeMemberSemicolon(); + return finishNode(node); + } + function parsePropertyOrMethodSignature(node) { + node.name = parsePropertyName(); + node.questionToken = parseOptionalToken(56 /* QuestionToken */); + if (token() === 20 /* OpenParenToken */ || token() === 28 /* LessThanToken */) { + node.kind = 155 /* MethodSignature */; + // Method signatures don't exist in expression contexts. So they have neither + // [Yield] nor [Await] + fillSignature(57 /* ColonToken */, 4 /* Type */, node); + } + else { + node.kind = 153 /* PropertySignature */; + node.type = parseTypeAnnotation(); + if (token() === 59 /* EqualsToken */) { + // Although type literal properties cannot not have initializers, we attempt + // to parse an initializer so we can report in the checker that an interface + // property or type literal property cannot have an initializer. + node.initializer = parseInitializer(); + } + } + parseTypeMemberSemicolon(); + return finishNode(node); + } + function isTypeMemberStart() { + // Return true if we have the start of a signature member + if (token() === 20 /* OpenParenToken */ || token() === 28 /* LessThanToken */) { + return true; + } + var idToken = false; + // Eat up all modifiers, but hold on to the last one in case it is actually an identifier + while (ts.isModifierKind(token())) { + idToken = true; + nextToken(); + } + // Index signatures and computed property names are type members + if (token() === 22 /* OpenBracketToken */) { + return true; + } + // Try to get the first property-like token following all modifiers + if (isLiteralPropertyName()) { + idToken = true; + nextToken(); + } + // If we were able to get any potential identifier, check that it is + // the start of a member declaration + if (idToken) { + return token() === 20 /* OpenParenToken */ || + token() === 28 /* LessThanToken */ || + token() === 56 /* QuestionToken */ || + token() === 57 /* ColonToken */ || + token() === 27 /* CommaToken */ || + canParseSemicolon(); + } + return false; + } + function parseTypeMember() { + if (token() === 20 /* OpenParenToken */ || token() === 28 /* LessThanToken */) { + return parseSignatureMember(160 /* CallSignature */); + } + if (token() === 95 /* NewKeyword */ && lookAhead(nextTokenIsOpenParenOrLessThan)) { + return parseSignatureMember(161 /* ConstructSignature */); + } + var node = createNodeWithJSDoc(0 /* Unknown */); + node.modifiers = parseModifiers(); + if (isIndexSignature()) { + return parseIndexSignatureDeclaration(node); + } + return parsePropertyOrMethodSignature(node); + } + function nextTokenIsOpenParenOrLessThan() { + nextToken(); + return token() === 20 /* OpenParenToken */ || token() === 28 /* LessThanToken */; + } + function nextTokenIsDot() { + return nextToken() === 24 /* DotToken */; + } + function nextTokenIsOpenParenOrLessThanOrDot() { + switch (nextToken()) { + case 20 /* OpenParenToken */: + case 28 /* LessThanToken */: + case 24 /* DotToken */: + return true; + } + return false; + } + function parseTypeLiteral() { + var node = createNode(168 /* TypeLiteral */); + node.members = parseObjectTypeMembers(); + return finishNode(node); + } + function parseObjectTypeMembers() { + var members; + if (parseExpected(18 /* OpenBraceToken */)) { + members = parseList(4 /* TypeMembers */, parseTypeMember); + parseExpected(19 /* CloseBraceToken */); + } + else { + members = createMissingList(); + } + return members; + } + function isStartOfMappedType() { + nextToken(); + if (token() === 38 /* PlusToken */ || token() === 39 /* MinusToken */) { + return nextToken() === 133 /* ReadonlyKeyword */; + } + if (token() === 133 /* ReadonlyKeyword */) { + nextToken(); + } + return token() === 22 /* OpenBracketToken */ && nextTokenIsIdentifier() && nextToken() === 93 /* InKeyword */; + } + function parseMappedTypeParameter() { + var node = createNode(150 /* TypeParameter */); + node.name = parseIdentifier(); + parseExpected(93 /* InKeyword */); + node.constraint = parseType(); + return finishNode(node); + } + function parseMappedType() { + var node = createNode(181 /* MappedType */); + parseExpected(18 /* OpenBraceToken */); + if (token() === 133 /* ReadonlyKeyword */ || token() === 38 /* PlusToken */ || token() === 39 /* MinusToken */) { + node.readonlyToken = parseTokenNode(); + if (node.readonlyToken.kind !== 133 /* ReadonlyKeyword */) { + parseExpectedToken(133 /* ReadonlyKeyword */); + } + } + parseExpected(22 /* OpenBracketToken */); + node.typeParameter = parseMappedTypeParameter(); + parseExpected(23 /* CloseBracketToken */); + if (token() === 56 /* QuestionToken */ || token() === 38 /* PlusToken */ || token() === 39 /* MinusToken */) { + node.questionToken = parseTokenNode(); + if (node.questionToken.kind !== 56 /* QuestionToken */) { + parseExpectedToken(56 /* QuestionToken */); + } + } + node.type = parseTypeAnnotation(); + parseSemicolon(); + parseExpected(19 /* CloseBraceToken */); + return finishNode(node); + } + function parseTupleElementType() { + var pos = getNodePos(); + if (parseOptional(25 /* DotDotDotToken */)) { + var node = createNode(172 /* RestType */, pos); + node.type = parseType(); + return finishNode(node); + } + var type = parseType(); + if (!(contextFlags & 2097152 /* JSDoc */) && type.kind === 286 /* JSDocNullableType */ && type.pos === type.type.pos) { + type.kind = 171 /* OptionalType */; + } + return type; + } + function parseTupleType() { + var node = createNode(170 /* TupleType */); + node.elementTypes = parseBracketedList(21 /* TupleElementTypes */, parseTupleElementType, 22 /* OpenBracketToken */, 23 /* CloseBracketToken */); + return finishNode(node); + } + function parseParenthesizedType() { + var node = createNode(177 /* ParenthesizedType */); + parseExpected(20 /* OpenParenToken */); + node.type = parseType(); + parseExpected(21 /* CloseParenToken */); + return finishNode(node); + } + function parseFunctionOrConstructorType() { + var pos = getNodePos(); + var kind = parseOptional(95 /* NewKeyword */) ? 166 /* ConstructorType */ : 165 /* FunctionType */; + var node = createNodeWithJSDoc(kind, pos); + fillSignature(37 /* EqualsGreaterThanToken */, 4 /* Type */, node); + return finishNode(node); + } + function parseKeywordAndNoDot() { + var node = parseTokenNode(); + return token() === 24 /* DotToken */ ? undefined : node; + } + function parseLiteralTypeNode(negative) { + var node = createNode(182 /* LiteralType */); + var unaryMinusExpression; + if (negative) { + unaryMinusExpression = createNode(202 /* PrefixUnaryExpression */); + unaryMinusExpression.operator = 39 /* MinusToken */; + nextToken(); + } + var expression = token() === 102 /* TrueKeyword */ || token() === 87 /* FalseKeyword */ + ? parseTokenNode() + : parseLiteralLikeNode(token()); + if (negative) { + unaryMinusExpression.operand = expression; + finishNode(unaryMinusExpression); + expression = unaryMinusExpression; + } + node.literal = expression; + return finishNode(node); + } + function isStartOfTypeOfImportType() { + nextToken(); + return token() === 92 /* ImportKeyword */; + } + function parseImportType() { + sourceFile.flags |= 524288 /* PossiblyContainsDynamicImport */; + var node = createNode(183 /* ImportType */); + if (parseOptional(104 /* TypeOfKeyword */)) { + node.isTypeOf = true; + } + parseExpected(92 /* ImportKeyword */); + parseExpected(20 /* OpenParenToken */); + node.argument = parseType(); + parseExpected(21 /* CloseParenToken */); + if (parseOptional(24 /* DotToken */)) { + node.qualifier = parseEntityName(/*allowReservedWords*/ true, ts.Diagnostics.Type_expected); + } + node.typeArguments = tryParseTypeArguments(); + return finishNode(node); + } + function nextTokenIsNumericOrBigIntLiteral() { + nextToken(); + return token() === 8 /* NumericLiteral */ || token() === 9 /* BigIntLiteral */; + } + function parseNonArrayType() { + switch (token()) { + case 120 /* AnyKeyword */: + case 143 /* UnknownKeyword */: + case 138 /* StringKeyword */: + case 135 /* NumberKeyword */: + case 146 /* BigIntKeyword */: + case 139 /* SymbolKeyword */: + case 123 /* BooleanKeyword */: + case 141 /* UndefinedKeyword */: + case 132 /* NeverKeyword */: + case 136 /* ObjectKeyword */: + // If these are followed by a dot, then parse these out as a dotted type reference instead. + return tryParse(parseKeywordAndNoDot) || parseTypeReference(); + case 40 /* AsteriskToken */: + return parseJSDocAllType(/*postfixEquals*/ false); + case 62 /* AsteriskEqualsToken */: + return parseJSDocAllType(/*postfixEquals*/ true); + case 56 /* QuestionToken */: + return parseJSDocUnknownOrNullableType(); + case 90 /* FunctionKeyword */: + return parseJSDocFunctionType(); + case 52 /* ExclamationToken */: + return parseJSDocNonNullableType(); + case 14 /* NoSubstitutionTemplateLiteral */: + case 10 /* StringLiteral */: + case 8 /* NumericLiteral */: + case 9 /* BigIntLiteral */: + case 102 /* TrueKeyword */: + case 87 /* FalseKeyword */: + return parseLiteralTypeNode(); + case 39 /* MinusToken */: + return lookAhead(nextTokenIsNumericOrBigIntLiteral) ? parseLiteralTypeNode(/*negative*/ true) : parseTypeReference(); + case 106 /* VoidKeyword */: + case 96 /* NullKeyword */: + return parseTokenNode(); + case 100 /* ThisKeyword */: { + var thisKeyword = parseThisTypeNode(); + if (token() === 128 /* IsKeyword */ && !scanner.hasPrecedingLineBreak()) { + return parseThisTypePredicate(thisKeyword); + } + else { + return thisKeyword; + } + } + case 104 /* TypeOfKeyword */: + return lookAhead(isStartOfTypeOfImportType) ? parseImportType() : parseTypeQuery(); + case 18 /* OpenBraceToken */: + return lookAhead(isStartOfMappedType) ? parseMappedType() : parseTypeLiteral(); + case 22 /* OpenBracketToken */: + return parseTupleType(); + case 20 /* OpenParenToken */: + return parseParenthesizedType(); + case 92 /* ImportKeyword */: + return parseImportType(); + default: + return parseTypeReference(); + } + } + function isStartOfType(inStartOfParameter) { + switch (token()) { + case 120 /* AnyKeyword */: + case 143 /* UnknownKeyword */: + case 138 /* StringKeyword */: + case 135 /* NumberKeyword */: + case 146 /* BigIntKeyword */: + case 123 /* BooleanKeyword */: + case 139 /* SymbolKeyword */: + case 142 /* UniqueKeyword */: + case 106 /* VoidKeyword */: + case 141 /* UndefinedKeyword */: + case 96 /* NullKeyword */: + case 100 /* ThisKeyword */: + case 104 /* TypeOfKeyword */: + case 132 /* NeverKeyword */: + case 18 /* OpenBraceToken */: + case 22 /* OpenBracketToken */: + case 28 /* LessThanToken */: + case 50 /* BarToken */: + case 49 /* AmpersandToken */: + case 95 /* NewKeyword */: + case 10 /* StringLiteral */: + case 8 /* NumericLiteral */: + case 9 /* BigIntLiteral */: + case 102 /* TrueKeyword */: + case 87 /* FalseKeyword */: + case 136 /* ObjectKeyword */: + case 40 /* AsteriskToken */: + case 56 /* QuestionToken */: + case 52 /* ExclamationToken */: + case 25 /* DotDotDotToken */: + case 127 /* InferKeyword */: + case 92 /* ImportKeyword */: + return true; + case 90 /* FunctionKeyword */: + return !inStartOfParameter; + case 39 /* MinusToken */: + return !inStartOfParameter && lookAhead(nextTokenIsNumericOrBigIntLiteral); + case 20 /* OpenParenToken */: + // Only consider '(' the start of a type if followed by ')', '...', an identifier, a modifier, + // or something that starts a type. We don't want to consider things like '(1)' a type. + return !inStartOfParameter && lookAhead(isStartOfParenthesizedOrFunctionType); + default: + return isIdentifier(); + } + } + function isStartOfParenthesizedOrFunctionType() { + nextToken(); + return token() === 21 /* CloseParenToken */ || isStartOfParameter(/*isJSDocParameter*/ false) || isStartOfType(); + } + function parsePostfixTypeOrHigher() { + var type = parseNonArrayType(); + while (!scanner.hasPrecedingLineBreak()) { + switch (token()) { + case 52 /* ExclamationToken */: + type = createPostfixType(287 /* JSDocNonNullableType */, type); + break; + case 56 /* QuestionToken */: + // If not in JSDoc and next token is start of a type we have a conditional type + if (!(contextFlags & 2097152 /* JSDoc */) && lookAhead(nextTokenIsStartOfType)) { + return type; + } + type = createPostfixType(286 /* JSDocNullableType */, type); + break; + case 22 /* OpenBracketToken */: + parseExpected(22 /* OpenBracketToken */); + if (isStartOfType()) { + var node = createNode(180 /* IndexedAccessType */, type.pos); + node.objectType = type; + node.indexType = parseType(); + parseExpected(23 /* CloseBracketToken */); + type = finishNode(node); + } + else { + var node = createNode(169 /* ArrayType */, type.pos); + node.elementType = type; + parseExpected(23 /* CloseBracketToken */); + type = finishNode(node); + } + break; + default: + return type; + } + } + return type; + } + function createPostfixType(kind, type) { + nextToken(); + var postfix = createNode(kind, type.pos); + postfix.type = type; + return finishNode(postfix); + } + function parseTypeOperator(operator) { + var node = createNode(179 /* TypeOperator */); + parseExpected(operator); + node.operator = operator; + node.type = parseTypeOperatorOrHigher(); + return finishNode(node); + } + function parseInferType() { + var node = createNode(176 /* InferType */); + parseExpected(127 /* InferKeyword */); + var typeParameter = createNode(150 /* TypeParameter */); + typeParameter.name = parseIdentifier(); + node.typeParameter = finishNode(typeParameter); + return finishNode(node); + } + function parseTypeOperatorOrHigher() { + var operator = token(); + switch (operator) { + case 129 /* KeyOfKeyword */: + case 142 /* UniqueKeyword */: + return parseTypeOperator(operator); + case 127 /* InferKeyword */: + return parseInferType(); + } + return parsePostfixTypeOrHigher(); + } + function parseUnionOrIntersectionType(kind, parseConstituentType, operator) { + parseOptional(operator); + var type = parseConstituentType(); + if (token() === operator) { + var types = [type]; + while (parseOptional(operator)) { + types.push(parseConstituentType()); + } + var node = createNode(kind, type.pos); + node.types = createNodeArray(types, type.pos); + type = finishNode(node); + } + return type; + } + function parseIntersectionTypeOrHigher() { + return parseUnionOrIntersectionType(174 /* IntersectionType */, parseTypeOperatorOrHigher, 49 /* AmpersandToken */); + } + function parseUnionTypeOrHigher() { + return parseUnionOrIntersectionType(173 /* UnionType */, parseIntersectionTypeOrHigher, 50 /* BarToken */); + } + function isStartOfFunctionType() { + if (token() === 28 /* LessThanToken */) { + return true; + } + return token() === 20 /* OpenParenToken */ && lookAhead(isUnambiguouslyStartOfFunctionType); + } + function skipParameterStart() { + if (ts.isModifierKind(token())) { + // Skip modifiers + parseModifiers(); + } + if (isIdentifier() || token() === 100 /* ThisKeyword */) { + nextToken(); + return true; + } + if (token() === 22 /* OpenBracketToken */ || token() === 18 /* OpenBraceToken */) { + // Return true if we can parse an array or object binding pattern with no errors + var previousErrorCount = parseDiagnostics.length; + parseIdentifierOrPattern(); + return previousErrorCount === parseDiagnostics.length; + } + return false; + } + function isUnambiguouslyStartOfFunctionType() { + nextToken(); + if (token() === 21 /* CloseParenToken */ || token() === 25 /* DotDotDotToken */) { + // ( ) + // ( ... + return true; + } + if (skipParameterStart()) { + // We successfully skipped modifiers (if any) and an identifier or binding pattern, + // now see if we have something that indicates a parameter declaration + if (token() === 57 /* ColonToken */ || token() === 27 /* CommaToken */ || + token() === 56 /* QuestionToken */ || token() === 59 /* EqualsToken */) { + // ( xxx : + // ( xxx , + // ( xxx ? + // ( xxx = + return true; + } + if (token() === 21 /* CloseParenToken */) { + nextToken(); + if (token() === 37 /* EqualsGreaterThanToken */) { + // ( xxx ) => + return true; + } + } + } + return false; + } + function parseTypeOrTypePredicate() { + var typePredicateVariable = isIdentifier() && tryParse(parseTypePredicatePrefix); + var type = parseType(); + if (typePredicateVariable) { + var node = createNode(163 /* TypePredicate */, typePredicateVariable.pos); + node.parameterName = typePredicateVariable; + node.type = type; + return finishNode(node); + } + else { + return type; + } + } + function parseTypePredicatePrefix() { + var id = parseIdentifier(); + if (token() === 128 /* IsKeyword */ && !scanner.hasPrecedingLineBreak()) { + nextToken(); + return id; + } + } + function parseType() { + // The rules about 'yield' only apply to actual code/expression contexts. They don't + // apply to 'type' contexts. So we disable these parameters here before moving on. + return doOutsideOfContext(20480 /* TypeExcludesFlags */, parseTypeWorker); + } + function parseTypeWorker(noConditionalTypes) { + if (isStartOfFunctionType() || token() === 95 /* NewKeyword */) { + return parseFunctionOrConstructorType(); + } + var type = parseUnionTypeOrHigher(); + if (!noConditionalTypes && !scanner.hasPrecedingLineBreak() && parseOptional(86 /* ExtendsKeyword */)) { + var node = createNode(175 /* ConditionalType */, type.pos); + node.checkType = type; + // The type following 'extends' is not permitted to be another conditional type + node.extendsType = parseTypeWorker(/*noConditionalTypes*/ true); + parseExpected(56 /* QuestionToken */); + node.trueType = parseTypeWorker(); + parseExpected(57 /* ColonToken */); + node.falseType = parseTypeWorker(); + return finishNode(node); + } + return type; + } + function parseTypeAnnotation() { + return parseOptional(57 /* ColonToken */) ? parseType() : undefined; + } + // EXPRESSIONS + function isStartOfLeftHandSideExpression() { + switch (token()) { + case 100 /* ThisKeyword */: + case 98 /* SuperKeyword */: + case 96 /* NullKeyword */: + case 102 /* TrueKeyword */: + case 87 /* FalseKeyword */: + case 8 /* NumericLiteral */: + case 9 /* BigIntLiteral */: + case 10 /* StringLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: + case 15 /* TemplateHead */: + case 20 /* OpenParenToken */: + case 22 /* OpenBracketToken */: + case 18 /* OpenBraceToken */: + case 90 /* FunctionKeyword */: + case 76 /* ClassKeyword */: + case 95 /* NewKeyword */: + case 42 /* SlashToken */: + case 64 /* SlashEqualsToken */: + case 72 /* Identifier */: + return true; + case 92 /* ImportKeyword */: + return lookAhead(nextTokenIsOpenParenOrLessThanOrDot); + default: + return isIdentifier(); + } + } + function isStartOfExpression() { + if (isStartOfLeftHandSideExpression()) { + return true; + } + switch (token()) { + case 38 /* PlusToken */: + case 39 /* MinusToken */: + case 53 /* TildeToken */: + case 52 /* ExclamationToken */: + case 81 /* DeleteKeyword */: + case 104 /* TypeOfKeyword */: + case 106 /* VoidKeyword */: + case 44 /* PlusPlusToken */: + case 45 /* MinusMinusToken */: + case 28 /* LessThanToken */: + case 122 /* AwaitKeyword */: + case 117 /* YieldKeyword */: + // Yield/await always starts an expression. Either it is an identifier (in which case + // it is definitely an expression). Or it's a keyword (either because we're in + // a generator or async function, or in strict mode (or both)) and it started a yield or await expression. + return true; + default: + // Error tolerance. If we see the start of some binary operator, we consider + // that the start of an expression. That way we'll parse out a missing identifier, + // give a good message about an identifier being missing, and then consume the + // rest of the binary expression. + if (isBinaryOperator()) { + return true; + } + return isIdentifier(); + } + } + function isStartOfExpressionStatement() { + // As per the grammar, none of '{' or 'function' or 'class' can start an expression statement. + return token() !== 18 /* OpenBraceToken */ && + token() !== 90 /* FunctionKeyword */ && + token() !== 76 /* ClassKeyword */ && + token() !== 58 /* AtToken */ && + isStartOfExpression(); + } + function parseExpression() { + // Expression[in]: + // AssignmentExpression[in] + // Expression[in] , AssignmentExpression[in] + // clear the decorator context when parsing Expression, as it should be unambiguous when parsing a decorator + var saveDecoratorContext = inDecoratorContext(); + if (saveDecoratorContext) { + setDecoratorContext(/*val*/ false); + } + var expr = parseAssignmentExpressionOrHigher(); + var operatorToken; + while ((operatorToken = parseOptionalToken(27 /* CommaToken */))) { + expr = makeBinaryExpression(expr, operatorToken, parseAssignmentExpressionOrHigher()); + } + if (saveDecoratorContext) { + setDecoratorContext(/*val*/ true); + } + return expr; + } + function parseInitializer() { + return parseOptional(59 /* EqualsToken */) ? parseAssignmentExpressionOrHigher() : undefined; + } + function parseAssignmentExpressionOrHigher() { + // AssignmentExpression[in,yield]: + // 1) ConditionalExpression[?in,?yield] + // 2) LeftHandSideExpression = AssignmentExpression[?in,?yield] + // 3) LeftHandSideExpression AssignmentOperator AssignmentExpression[?in,?yield] + // 4) ArrowFunctionExpression[?in,?yield] + // 5) AsyncArrowFunctionExpression[in,yield,await] + // 6) [+Yield] YieldExpression[?In] + // + // Note: for ease of implementation we treat productions '2' and '3' as the same thing. + // (i.e. they're both BinaryExpressions with an assignment operator in it). + // First, do the simple check if we have a YieldExpression (production '6'). + if (isYieldExpression()) { + return parseYieldExpression(); + } + // Then, check if we have an arrow function (production '4' and '5') that starts with a parenthesized + // parameter list or is an async arrow function. + // AsyncArrowFunctionExpression: + // 1) async[no LineTerminator here]AsyncArrowBindingIdentifier[?Yield][no LineTerminator here]=>AsyncConciseBody[?In] + // 2) CoverCallExpressionAndAsyncArrowHead[?Yield, ?Await][no LineTerminator here]=>AsyncConciseBody[?In] + // Production (1) of AsyncArrowFunctionExpression is parsed in "tryParseAsyncSimpleArrowFunctionExpression". + // And production (2) is parsed in "tryParseParenthesizedArrowFunctionExpression". + // + // If we do successfully parse arrow-function, we must *not* recurse for productions 1, 2 or 3. An ArrowFunction is + // not a LeftHandSideExpression, nor does it start a ConditionalExpression. So we are done + // with AssignmentExpression if we see one. + var arrowExpression = tryParseParenthesizedArrowFunctionExpression() || tryParseAsyncSimpleArrowFunctionExpression(); + if (arrowExpression) { + return arrowExpression; + } + // Now try to see if we're in production '1', '2' or '3'. A conditional expression can + // start with a LogicalOrExpression, while the assignment productions can only start with + // LeftHandSideExpressions. + // + // So, first, we try to just parse out a BinaryExpression. If we get something that is a + // LeftHandSide or higher, then we can try to parse out the assignment expression part. + // Otherwise, we try to parse out the conditional expression bit. We want to allow any + // binary expression here, so we pass in the 'lowest' precedence here so that it matches + // and consumes anything. + var expr = parseBinaryExpressionOrHigher(/*precedence*/ 0); + // To avoid a look-ahead, we did not handle the case of an arrow function with a single un-parenthesized + // parameter ('x => ...') above. We handle it here by checking if the parsed expression was a single + // identifier and the current token is an arrow. + if (expr.kind === 72 /* Identifier */ && token() === 37 /* EqualsGreaterThanToken */) { + return parseSimpleArrowFunctionExpression(expr); + } + // Now see if we might be in cases '2' or '3'. + // If the expression was a LHS expression, and we have an assignment operator, then + // we're in '2' or '3'. Consume the assignment and return. + // + // Note: we call reScanGreaterToken so that we get an appropriately merged token + // for cases like `> > =` becoming `>>=` + if (ts.isLeftHandSideExpression(expr) && ts.isAssignmentOperator(reScanGreaterToken())) { + return makeBinaryExpression(expr, parseTokenNode(), parseAssignmentExpressionOrHigher()); + } + // It wasn't an assignment or a lambda. This is a conditional expression: + return parseConditionalExpressionRest(expr); + } + function isYieldExpression() { + if (token() === 117 /* YieldKeyword */) { + // If we have a 'yield' keyword, and this is a context where yield expressions are + // allowed, then definitely parse out a yield expression. + if (inYieldContext()) { + return true; + } + // We're in a context where 'yield expr' is not allowed. However, if we can + // definitely tell that the user was trying to parse a 'yield expr' and not + // just a normal expr that start with a 'yield' identifier, then parse out + // a 'yield expr'. We can then report an error later that they are only + // allowed in generator expressions. + // + // for example, if we see 'yield(foo)', then we'll have to treat that as an + // invocation expression of something called 'yield'. However, if we have + // 'yield foo' then that is not legal as a normal expression, so we can + // definitely recognize this as a yield expression. + // + // for now we just check if the next token is an identifier. More heuristics + // can be added here later as necessary. We just need to make sure that we + // don't accidentally consume something legal. + return lookAhead(nextTokenIsIdentifierOrKeywordOrLiteralOnSameLine); + } + return false; + } + function nextTokenIsIdentifierOnSameLine() { + nextToken(); + return !scanner.hasPrecedingLineBreak() && isIdentifier(); + } + function parseYieldExpression() { + var node = createNode(207 /* YieldExpression */); + // YieldExpression[In] : + // yield + // yield [no LineTerminator here] [Lexical goal InputElementRegExp]AssignmentExpression[?In, Yield] + // yield [no LineTerminator here] * [Lexical goal InputElementRegExp]AssignmentExpression[?In, Yield] + nextToken(); + if (!scanner.hasPrecedingLineBreak() && + (token() === 40 /* AsteriskToken */ || isStartOfExpression())) { + node.asteriskToken = parseOptionalToken(40 /* AsteriskToken */); + node.expression = parseAssignmentExpressionOrHigher(); + return finishNode(node); + } + else { + // if the next token is not on the same line as yield. or we don't have an '*' or + // the start of an expression, then this is just a simple "yield" expression. + return finishNode(node); + } + } + function parseSimpleArrowFunctionExpression(identifier, asyncModifier) { + ts.Debug.assert(token() === 37 /* EqualsGreaterThanToken */, "parseSimpleArrowFunctionExpression should only have been called if we had a =>"); + var node; + if (asyncModifier) { + node = createNode(197 /* ArrowFunction */, asyncModifier.pos); + node.modifiers = asyncModifier; + } + else { + node = createNode(197 /* ArrowFunction */, identifier.pos); + } + var parameter = createNode(151 /* Parameter */, identifier.pos); + parameter.name = identifier; + finishNode(parameter); + node.parameters = createNodeArray([parameter], parameter.pos, parameter.end); + node.equalsGreaterThanToken = parseExpectedToken(37 /* EqualsGreaterThanToken */); + node.body = parseArrowFunctionExpressionBody(/*isAsync*/ !!asyncModifier); + return addJSDocComment(finishNode(node)); + } + function tryParseParenthesizedArrowFunctionExpression() { + var triState = isParenthesizedArrowFunctionExpression(); + if (triState === 0 /* False */) { + // It's definitely not a parenthesized arrow function expression. + return undefined; + } + // If we definitely have an arrow function, then we can just parse one, not requiring a + // following => or { token. Otherwise, we *might* have an arrow function. Try to parse + // it out, but don't allow any ambiguity, and return 'undefined' if this could be an + // expression instead. + var arrowFunction = triState === 1 /* True */ + ? parseParenthesizedArrowFunctionExpressionHead(/*allowAmbiguity*/ true) + : tryParse(parsePossibleParenthesizedArrowFunctionExpressionHead); + if (!arrowFunction) { + // Didn't appear to actually be a parenthesized arrow function. Just bail out. + return undefined; + } + var isAsync = ts.hasModifier(arrowFunction, 256 /* Async */); + // If we have an arrow, then try to parse the body. Even if not, try to parse if we + // have an opening brace, just in case we're in an error state. + var lastToken = token(); + arrowFunction.equalsGreaterThanToken = parseExpectedToken(37 /* EqualsGreaterThanToken */); + arrowFunction.body = (lastToken === 37 /* EqualsGreaterThanToken */ || lastToken === 18 /* OpenBraceToken */) + ? parseArrowFunctionExpressionBody(isAsync) + : parseIdentifier(); + return finishNode(arrowFunction); + } + // True -> We definitely expect a parenthesized arrow function here. + // False -> There *cannot* be a parenthesized arrow function here. + // Unknown -> There *might* be a parenthesized arrow function here. + // Speculatively look ahead to be sure, and rollback if not. + function isParenthesizedArrowFunctionExpression() { + if (token() === 20 /* OpenParenToken */ || token() === 28 /* LessThanToken */ || token() === 121 /* AsyncKeyword */) { + return lookAhead(isParenthesizedArrowFunctionExpressionWorker); + } + if (token() === 37 /* EqualsGreaterThanToken */) { + // ERROR RECOVERY TWEAK: + // If we see a standalone => try to parse it as an arrow function expression as that's + // likely what the user intended to write. + return 1 /* True */; + } + // Definitely not a parenthesized arrow function. + return 0 /* False */; + } + function isParenthesizedArrowFunctionExpressionWorker() { + if (token() === 121 /* AsyncKeyword */) { + nextToken(); + if (scanner.hasPrecedingLineBreak()) { + return 0 /* False */; + } + if (token() !== 20 /* OpenParenToken */ && token() !== 28 /* LessThanToken */) { + return 0 /* False */; + } + } + var first = token(); + var second = nextToken(); + if (first === 20 /* OpenParenToken */) { + if (second === 21 /* CloseParenToken */) { + // Simple cases: "() =>", "(): ", and "() {". + // This is an arrow function with no parameters. + // The last one is not actually an arrow function, + // but this is probably what the user intended. + var third = nextToken(); + switch (third) { + case 37 /* EqualsGreaterThanToken */: + case 57 /* ColonToken */: + case 18 /* OpenBraceToken */: + return 1 /* True */; + default: + return 0 /* False */; + } + } + // If encounter "([" or "({", this could be the start of a binding pattern. + // Examples: + // ([ x ]) => { } + // ({ x }) => { } + // ([ x ]) + // ({ x }) + if (second === 22 /* OpenBracketToken */ || second === 18 /* OpenBraceToken */) { + return 2 /* Unknown */; + } + // Simple case: "(..." + // This is an arrow function with a rest parameter. + if (second === 25 /* DotDotDotToken */) { + return 1 /* True */; + } + // Check for "(xxx yyy", where xxx is a modifier and yyy is an identifier. This + // isn't actually allowed, but we want to treat it as a lambda so we can provide + // a good error message. + if (ts.isModifierKind(second) && second !== 121 /* AsyncKeyword */ && lookAhead(nextTokenIsIdentifier)) { + return 1 /* True */; + } + // If we had "(" followed by something that's not an identifier, + // then this definitely doesn't look like a lambda. "this" is not + // valid, but we want to parse it and then give a semantic error. + if (!isIdentifier() && second !== 100 /* ThisKeyword */) { + return 0 /* False */; + } + switch (nextToken()) { + case 57 /* ColonToken */: + // If we have something like "(a:", then we must have a + // type-annotated parameter in an arrow function expression. + return 1 /* True */; + case 56 /* QuestionToken */: + nextToken(); + // If we have "(a?:" or "(a?," or "(a?=" or "(a?)" then it is definitely a lambda. + if (token() === 57 /* ColonToken */ || token() === 27 /* CommaToken */ || token() === 59 /* EqualsToken */ || token() === 21 /* CloseParenToken */) { + return 1 /* True */; + } + // Otherwise it is definitely not a lambda. + return 0 /* False */; + case 27 /* CommaToken */: + case 59 /* EqualsToken */: + case 21 /* CloseParenToken */: + // If we have "(a," or "(a=" or "(a)" this *could* be an arrow function + return 2 /* Unknown */; + } + // It is definitely not an arrow function + return 0 /* False */; + } + else { + ts.Debug.assert(first === 28 /* LessThanToken */); + // If we have "<" not followed by an identifier, + // then this definitely is not an arrow function. + if (!isIdentifier()) { + return 0 /* False */; + } + // JSX overrides + if (sourceFile.languageVariant === 1 /* JSX */) { + var isArrowFunctionInJsx = lookAhead(function () { + var third = nextToken(); + if (third === 86 /* ExtendsKeyword */) { + var fourth = nextToken(); + switch (fourth) { + case 59 /* EqualsToken */: + case 30 /* GreaterThanToken */: + return false; + default: + return true; + } + } + else if (third === 27 /* CommaToken */) { + return true; + } + return false; + }); + if (isArrowFunctionInJsx) { + return 1 /* True */; + } + return 0 /* False */; + } + // This *could* be a parenthesized arrow function. + return 2 /* Unknown */; + } + } + function parsePossibleParenthesizedArrowFunctionExpressionHead() { + return parseParenthesizedArrowFunctionExpressionHead(/*allowAmbiguity*/ false); + } + function tryParseAsyncSimpleArrowFunctionExpression() { + // We do a check here so that we won't be doing unnecessarily call to "lookAhead" + if (token() === 121 /* AsyncKeyword */) { + if (lookAhead(isUnParenthesizedAsyncArrowFunctionWorker) === 1 /* True */) { + var asyncModifier = parseModifiersForArrowFunction(); + var expr = parseBinaryExpressionOrHigher(/*precedence*/ 0); + return parseSimpleArrowFunctionExpression(expr, asyncModifier); + } + } + return undefined; + } + function isUnParenthesizedAsyncArrowFunctionWorker() { + // AsyncArrowFunctionExpression: + // 1) async[no LineTerminator here]AsyncArrowBindingIdentifier[?Yield][no LineTerminator here]=>AsyncConciseBody[?In] + // 2) CoverCallExpressionAndAsyncArrowHead[?Yield, ?Await][no LineTerminator here]=>AsyncConciseBody[?In] + if (token() === 121 /* AsyncKeyword */) { + nextToken(); + // If the "async" is followed by "=>" token then it is not a beginning of an async arrow-function + // but instead a simple arrow-function which will be parsed inside "parseAssignmentExpressionOrHigher" + if (scanner.hasPrecedingLineBreak() || token() === 37 /* EqualsGreaterThanToken */) { + return 0 /* False */; + } + // Check for un-parenthesized AsyncArrowFunction + var expr = parseBinaryExpressionOrHigher(/*precedence*/ 0); + if (!scanner.hasPrecedingLineBreak() && expr.kind === 72 /* Identifier */ && token() === 37 /* EqualsGreaterThanToken */) { + return 1 /* True */; + } + } + return 0 /* False */; + } + function parseParenthesizedArrowFunctionExpressionHead(allowAmbiguity) { + var node = createNodeWithJSDoc(197 /* ArrowFunction */); + node.modifiers = parseModifiersForArrowFunction(); + var isAsync = ts.hasModifier(node, 256 /* Async */) ? 2 /* Await */ : 0 /* None */; + // Arrow functions are never generators. + // + // If we're speculatively parsing a signature for a parenthesized arrow function, then + // we have to have a complete parameter list. Otherwise we might see something like + // a => (b => c) + // And think that "(b =>" was actually a parenthesized arrow function with a missing + // close paren. + if (!fillSignature(57 /* ColonToken */, isAsync, node) && !allowAmbiguity) { + return undefined; + } + // Parsing a signature isn't enough. + // Parenthesized arrow signatures often look like other valid expressions. + // For instance: + // - "(x = 10)" is an assignment expression parsed as a signature with a default parameter value. + // - "(x,y)" is a comma expression parsed as a signature with two parameters. + // - "a ? (b): c" will have "(b):" parsed as a signature with a return type annotation. + // + // So we need just a bit of lookahead to ensure that it can only be a signature. + if (!allowAmbiguity && token() !== 37 /* EqualsGreaterThanToken */ && token() !== 18 /* OpenBraceToken */) { + // Returning undefined here will cause our caller to rewind to where we started from. + return undefined; + } + return node; + } + function parseArrowFunctionExpressionBody(isAsync) { + if (token() === 18 /* OpenBraceToken */) { + return parseFunctionBlock(isAsync ? 2 /* Await */ : 0 /* None */); + } + if (token() !== 26 /* SemicolonToken */ && + token() !== 90 /* FunctionKeyword */ && + token() !== 76 /* ClassKeyword */ && + isStartOfStatement() && + !isStartOfExpressionStatement()) { + // Check if we got a plain statement (i.e. no expression-statements, no function/class expressions/declarations) + // + // Here we try to recover from a potential error situation in the case where the + // user meant to supply a block. For example, if the user wrote: + // + // a => + // let v = 0; + // } + // + // they may be missing an open brace. Check to see if that's the case so we can + // try to recover better. If we don't do this, then the next close curly we see may end + // up preemptively closing the containing construct. + // + // Note: even when 'IgnoreMissingOpenBrace' is passed, parseBody will still error. + return parseFunctionBlock(16 /* IgnoreMissingOpenBrace */ | (isAsync ? 2 /* Await */ : 0 /* None */)); + } + return isAsync + ? doInAwaitContext(parseAssignmentExpressionOrHigher) + : doOutsideOfAwaitContext(parseAssignmentExpressionOrHigher); + } + function parseConditionalExpressionRest(leftOperand) { + // Note: we are passed in an expression which was produced from parseBinaryExpressionOrHigher. + var questionToken = parseOptionalToken(56 /* QuestionToken */); + if (!questionToken) { + return leftOperand; + } + // Note: we explicitly 'allowIn' in the whenTrue part of the condition expression, and + // we do not that for the 'whenFalse' part. + var node = createNode(205 /* ConditionalExpression */, leftOperand.pos); + node.condition = leftOperand; + node.questionToken = questionToken; + node.whenTrue = doOutsideOfContext(disallowInAndDecoratorContext, parseAssignmentExpressionOrHigher); + node.colonToken = parseExpectedToken(57 /* ColonToken */); + node.whenFalse = ts.nodeIsPresent(node.colonToken) + ? parseAssignmentExpressionOrHigher() + : createMissingNode(72 /* Identifier */, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, ts.tokenToString(57 /* ColonToken */)); + return finishNode(node); + } + function parseBinaryExpressionOrHigher(precedence) { + var leftOperand = parseUnaryExpressionOrHigher(); + return parseBinaryExpressionRest(precedence, leftOperand); + } + function isInOrOfKeyword(t) { + return t === 93 /* InKeyword */ || t === 147 /* OfKeyword */; + } + function parseBinaryExpressionRest(precedence, leftOperand) { + while (true) { + // We either have a binary operator here, or we're finished. We call + // reScanGreaterToken so that we merge token sequences like > and = into >= + reScanGreaterToken(); + var newPrecedence = ts.getBinaryOperatorPrecedence(token()); + // Check the precedence to see if we should "take" this operator + // - For left associative operator (all operator but **), consume the operator, + // recursively call the function below, and parse binaryExpression as a rightOperand + // of the caller if the new precedence of the operator is greater then or equal to the current precedence. + // For example: + // a - b - c; + // ^token; leftOperand = b. Return b to the caller as a rightOperand + // a * b - c + // ^token; leftOperand = b. Return b to the caller as a rightOperand + // a - b * c; + // ^token; leftOperand = b. Return b * c to the caller as a rightOperand + // - For right associative operator (**), consume the operator, recursively call the function + // and parse binaryExpression as a rightOperand of the caller if the new precedence of + // the operator is strictly grater than the current precedence + // For example: + // a ** b ** c; + // ^^token; leftOperand = b. Return b ** c to the caller as a rightOperand + // a - b ** c; + // ^^token; leftOperand = b. Return b ** c to the caller as a rightOperand + // a ** b - c + // ^token; leftOperand = b. Return b to the caller as a rightOperand + var consumeCurrentOperator = token() === 41 /* AsteriskAsteriskToken */ ? + newPrecedence >= precedence : + newPrecedence > precedence; + if (!consumeCurrentOperator) { + break; + } + if (token() === 93 /* InKeyword */ && inDisallowInContext()) { + break; + } + if (token() === 119 /* AsKeyword */) { + // Make sure we *do* perform ASI for constructs like this: + // var x = foo + // as (Bar) + // This should be parsed as an initialized variable, followed + // by a function call to 'as' with the argument 'Bar' + if (scanner.hasPrecedingLineBreak()) { + break; + } + else { + nextToken(); + leftOperand = makeAsExpression(leftOperand, parseType()); + } + } + else { + leftOperand = makeBinaryExpression(leftOperand, parseTokenNode(), parseBinaryExpressionOrHigher(newPrecedence)); + } + } + return leftOperand; + } + function isBinaryOperator() { + if (inDisallowInContext() && token() === 93 /* InKeyword */) { + return false; + } + return ts.getBinaryOperatorPrecedence(token()) > 0; + } + function makeBinaryExpression(left, operatorToken, right) { + var node = createNode(204 /* BinaryExpression */, left.pos); + node.left = left; + node.operatorToken = operatorToken; + node.right = right; + return finishNode(node); + } + function makeAsExpression(left, right) { + var node = createNode(212 /* AsExpression */, left.pos); + node.expression = left; + node.type = right; + return finishNode(node); + } + function parsePrefixUnaryExpression() { + var node = createNode(202 /* PrefixUnaryExpression */); + node.operator = token(); + nextToken(); + node.operand = parseSimpleUnaryExpression(); + return finishNode(node); + } + function parseDeleteExpression() { + var node = createNode(198 /* DeleteExpression */); + nextToken(); + node.expression = parseSimpleUnaryExpression(); + return finishNode(node); + } + function parseTypeOfExpression() { + var node = createNode(199 /* TypeOfExpression */); + nextToken(); + node.expression = parseSimpleUnaryExpression(); + return finishNode(node); + } + function parseVoidExpression() { + var node = createNode(200 /* VoidExpression */); + nextToken(); + node.expression = parseSimpleUnaryExpression(); + return finishNode(node); + } + function isAwaitExpression() { + if (token() === 122 /* AwaitKeyword */) { + if (inAwaitContext()) { + return true; + } + // here we are using similar heuristics as 'isYieldExpression' + return lookAhead(nextTokenIsIdentifierOrKeywordOrLiteralOnSameLine); + } + return false; + } + function parseAwaitExpression() { + var node = createNode(201 /* AwaitExpression */); + nextToken(); + node.expression = parseSimpleUnaryExpression(); + return finishNode(node); + } + /** + * Parse ES7 exponential expression and await expression + * + * ES7 ExponentiationExpression: + * 1) UnaryExpression[?Yield] + * 2) UpdateExpression[?Yield] ** ExponentiationExpression[?Yield] + * + */ + function parseUnaryExpressionOrHigher() { + /** + * ES7 UpdateExpression: + * 1) LeftHandSideExpression[?Yield] + * 2) LeftHandSideExpression[?Yield][no LineTerminator here]++ + * 3) LeftHandSideExpression[?Yield][no LineTerminator here]-- + * 4) ++UnaryExpression[?Yield] + * 5) --UnaryExpression[?Yield] + */ + if (isUpdateExpression()) { + var updateExpression = parseUpdateExpression(); + return token() === 41 /* AsteriskAsteriskToken */ ? + parseBinaryExpressionRest(ts.getBinaryOperatorPrecedence(token()), updateExpression) : + updateExpression; + } + /** + * ES7 UnaryExpression: + * 1) UpdateExpression[?yield] + * 2) delete UpdateExpression[?yield] + * 3) void UpdateExpression[?yield] + * 4) typeof UpdateExpression[?yield] + * 5) + UpdateExpression[?yield] + * 6) - UpdateExpression[?yield] + * 7) ~ UpdateExpression[?yield] + * 8) ! UpdateExpression[?yield] + */ + var unaryOperator = token(); + var simpleUnaryExpression = parseSimpleUnaryExpression(); + if (token() === 41 /* AsteriskAsteriskToken */) { + var pos = ts.skipTrivia(sourceText, simpleUnaryExpression.pos); + var end = simpleUnaryExpression.end; + if (simpleUnaryExpression.kind === 194 /* TypeAssertionExpression */) { + parseErrorAt(pos, end, ts.Diagnostics.A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses); + } + else { + parseErrorAt(pos, end, ts.Diagnostics.An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses, ts.tokenToString(unaryOperator)); + } + } + return simpleUnaryExpression; + } + /** + * Parse ES7 simple-unary expression or higher: + * + * ES7 UnaryExpression: + * 1) UpdateExpression[?yield] + * 2) delete UnaryExpression[?yield] + * 3) void UnaryExpression[?yield] + * 4) typeof UnaryExpression[?yield] + * 5) + UnaryExpression[?yield] + * 6) - UnaryExpression[?yield] + * 7) ~ UnaryExpression[?yield] + * 8) ! UnaryExpression[?yield] + * 9) [+Await] await UnaryExpression[?yield] + */ + function parseSimpleUnaryExpression() { + switch (token()) { + case 38 /* PlusToken */: + case 39 /* MinusToken */: + case 53 /* TildeToken */: + case 52 /* ExclamationToken */: + return parsePrefixUnaryExpression(); + case 81 /* DeleteKeyword */: + return parseDeleteExpression(); + case 104 /* TypeOfKeyword */: + return parseTypeOfExpression(); + case 106 /* VoidKeyword */: + return parseVoidExpression(); + case 28 /* LessThanToken */: + // This is modified UnaryExpression grammar in TypeScript + // UnaryExpression (modified): + // < type > UnaryExpression + return parseTypeAssertion(); + case 122 /* AwaitKeyword */: + if (isAwaitExpression()) { + return parseAwaitExpression(); + } + // falls through + default: + return parseUpdateExpression(); + } + } + /** + * Check if the current token can possibly be an ES7 increment expression. + * + * ES7 UpdateExpression: + * LeftHandSideExpression[?Yield] + * LeftHandSideExpression[?Yield][no LineTerminator here]++ + * LeftHandSideExpression[?Yield][no LineTerminator here]-- + * ++LeftHandSideExpression[?Yield] + * --LeftHandSideExpression[?Yield] + */ + function isUpdateExpression() { + // This function is called inside parseUnaryExpression to decide + // whether to call parseSimpleUnaryExpression or call parseUpdateExpression directly + switch (token()) { + case 38 /* PlusToken */: + case 39 /* MinusToken */: + case 53 /* TildeToken */: + case 52 /* ExclamationToken */: + case 81 /* DeleteKeyword */: + case 104 /* TypeOfKeyword */: + case 106 /* VoidKeyword */: + case 122 /* AwaitKeyword */: + return false; + case 28 /* LessThanToken */: + // If we are not in JSX context, we are parsing TypeAssertion which is an UnaryExpression + if (sourceFile.languageVariant !== 1 /* JSX */) { + return false; + } + // We are in JSX context and the token is part of JSXElement. + // falls through + default: + return true; + } + } + /** + * Parse ES7 UpdateExpression. UpdateExpression is used instead of ES6's PostFixExpression. + * + * ES7 UpdateExpression[yield]: + * 1) LeftHandSideExpression[?yield] + * 2) LeftHandSideExpression[?yield] [[no LineTerminator here]]++ + * 3) LeftHandSideExpression[?yield] [[no LineTerminator here]]-- + * 4) ++LeftHandSideExpression[?yield] + * 5) --LeftHandSideExpression[?yield] + * In TypeScript (2), (3) are parsed as PostfixUnaryExpression. (4), (5) are parsed as PrefixUnaryExpression + */ + function parseUpdateExpression() { + if (token() === 44 /* PlusPlusToken */ || token() === 45 /* MinusMinusToken */) { + var node = createNode(202 /* PrefixUnaryExpression */); + node.operator = token(); + nextToken(); + node.operand = parseLeftHandSideExpressionOrHigher(); + return finishNode(node); + } + else if (sourceFile.languageVariant === 1 /* JSX */ && token() === 28 /* LessThanToken */ && lookAhead(nextTokenIsIdentifierOrKeywordOrGreaterThan)) { + // JSXElement is part of primaryExpression + return parseJsxElementOrSelfClosingElementOrFragment(/*inExpressionContext*/ true); + } + var expression = parseLeftHandSideExpressionOrHigher(); + ts.Debug.assert(ts.isLeftHandSideExpression(expression)); + if ((token() === 44 /* PlusPlusToken */ || token() === 45 /* MinusMinusToken */) && !scanner.hasPrecedingLineBreak()) { + var node = createNode(203 /* PostfixUnaryExpression */, expression.pos); + node.operand = expression; + node.operator = token(); + nextToken(); + return finishNode(node); + } + return expression; + } + function parseLeftHandSideExpressionOrHigher() { + // Original Ecma: + // LeftHandSideExpression: See 11.2 + // NewExpression + // CallExpression + // + // Our simplification: + // + // LeftHandSideExpression: See 11.2 + // MemberExpression + // CallExpression + // + // See comment in parseMemberExpressionOrHigher on how we replaced NewExpression with + // MemberExpression to make our lives easier. + // + // to best understand the below code, it's important to see how CallExpression expands + // out into its own productions: + // + // CallExpression: + // MemberExpression Arguments + // CallExpression Arguments + // CallExpression[Expression] + // CallExpression.IdentifierName + // import (AssignmentExpression) + // super Arguments + // super.IdentifierName + // + // Because of the recursion in these calls, we need to bottom out first. There are three + // bottom out states we can run into: 1) We see 'super' which must start either of + // the last two CallExpression productions. 2) We see 'import' which must start import call. + // 3)we have a MemberExpression which either completes the LeftHandSideExpression, + // or starts the beginning of the first four CallExpression productions. + var expression; + if (token() === 92 /* ImportKeyword */) { + if (lookAhead(nextTokenIsOpenParenOrLessThan)) { + // We don't want to eagerly consume all import keyword as import call expression so we look ahead to find "(" + // For example: + // var foo3 = require("subfolder + // import * as foo1 from "module-from-node + // We want this import to be a statement rather than import call expression + sourceFile.flags |= 524288 /* PossiblyContainsDynamicImport */; + expression = parseTokenNode(); + } + else if (lookAhead(nextTokenIsDot)) { + // This is an 'import.*' metaproperty (i.e. 'import.meta') + var fullStart = scanner.getStartPos(); + nextToken(); // advance past the 'import' + nextToken(); // advance past the dot + var node = createNode(214 /* MetaProperty */, fullStart); + node.keywordToken = 92 /* ImportKeyword */; + node.name = parseIdentifierName(); + expression = finishNode(node); + sourceFile.flags |= 1048576 /* PossiblyContainsImportMeta */; + } + else { + expression = parseMemberExpressionOrHigher(); + } + } + else { + expression = token() === 98 /* SuperKeyword */ ? parseSuperExpression() : parseMemberExpressionOrHigher(); + } + // Now, we *may* be complete. However, we might have consumed the start of a + // CallExpression. As such, we need to consume the rest of it here to be complete. + return parseCallExpressionRest(expression); + } + function parseMemberExpressionOrHigher() { + // Note: to make our lives simpler, we decompose the NewExpression productions and + // place ObjectCreationExpression and FunctionExpression into PrimaryExpression. + // like so: + // + // PrimaryExpression : See 11.1 + // this + // Identifier + // Literal + // ArrayLiteral + // ObjectLiteral + // (Expression) + // FunctionExpression + // new MemberExpression Arguments? + // + // MemberExpression : See 11.2 + // PrimaryExpression + // MemberExpression[Expression] + // MemberExpression.IdentifierName + // + // CallExpression : See 11.2 + // MemberExpression + // CallExpression Arguments + // CallExpression[Expression] + // CallExpression.IdentifierName + // + // Technically this is ambiguous. i.e. CallExpression defines: + // + // CallExpression: + // CallExpression Arguments + // + // If you see: "new Foo()" + // + // Then that could be treated as a single ObjectCreationExpression, or it could be + // treated as the invocation of "new Foo". We disambiguate that in code (to match + // the original grammar) by making sure that if we see an ObjectCreationExpression + // we always consume arguments if they are there. So we treat "new Foo()" as an + // object creation only, and not at all as an invocation. Another way to think + // about this is that for every "new" that we see, we will consume an argument list if + // it is there as part of the *associated* object creation node. Any additional + // argument lists we see, will become invocation expressions. + // + // Because there are no other places in the grammar now that refer to FunctionExpression + // or ObjectCreationExpression, it is safe to push down into the PrimaryExpression + // production. + // + // Because CallExpression and MemberExpression are left recursive, we need to bottom out + // of the recursion immediately. So we parse out a primary expression to start with. + var expression = parsePrimaryExpression(); + return parseMemberExpressionRest(expression); + } + function parseSuperExpression() { + var expression = parseTokenNode(); + if (token() === 20 /* OpenParenToken */ || token() === 24 /* DotToken */ || token() === 22 /* OpenBracketToken */) { + return expression; + } + // If we have seen "super" it must be followed by '(' or '.'. + // If it wasn't then just try to parse out a '.' and report an error. + var node = createNode(189 /* PropertyAccessExpression */, expression.pos); + node.expression = expression; + parseExpectedToken(24 /* DotToken */, ts.Diagnostics.super_must_be_followed_by_an_argument_list_or_member_access); + node.name = parseRightSideOfDot(/*allowIdentifierNames*/ true); + return finishNode(node); + } + function parseJsxElementOrSelfClosingElementOrFragment(inExpressionContext) { + var opening = parseJsxOpeningOrSelfClosingElementOrOpeningFragment(inExpressionContext); + var result; + if (opening.kind === 262 /* JsxOpeningElement */) { + var node = createNode(260 /* JsxElement */, opening.pos); + node.openingElement = opening; + node.children = parseJsxChildren(node.openingElement); + node.closingElement = parseJsxClosingElement(inExpressionContext); + if (!tagNamesAreEquivalent(node.openingElement.tagName, node.closingElement.tagName)) { + parseErrorAtRange(node.closingElement, ts.Diagnostics.Expected_corresponding_JSX_closing_tag_for_0, ts.getTextOfNodeFromSourceText(sourceText, node.openingElement.tagName)); + } + result = finishNode(node); + } + else if (opening.kind === 265 /* JsxOpeningFragment */) { + var node = createNode(264 /* JsxFragment */, opening.pos); + node.openingFragment = opening; + node.children = parseJsxChildren(node.openingFragment); + node.closingFragment = parseJsxClosingFragment(inExpressionContext); + result = finishNode(node); + } + else { + ts.Debug.assert(opening.kind === 261 /* JsxSelfClosingElement */); + // Nothing else to do for self-closing elements + result = opening; + } + // If the user writes the invalid code '
      ' in an expression context (i.e. not wrapped in + // an enclosing tag), we'll naively try to parse ^ this as a 'less than' operator and the remainder of the tag + // as garbage, which will cause the formatter to badly mangle the JSX. Perform a speculative parse of a JSX + // element if we see a < token so that we can wrap it in a synthetic binary expression so the formatter + // does less damage and we can report a better error. + // Since JSX elements are invalid < operands anyway, this lookahead parse will only occur in error scenarios + // of one sort or another. + if (inExpressionContext && token() === 28 /* LessThanToken */) { + var invalidElement = tryParse(function () { return parseJsxElementOrSelfClosingElementOrFragment(/*inExpressionContext*/ true); }); + if (invalidElement) { + parseErrorAtCurrentToken(ts.Diagnostics.JSX_expressions_must_have_one_parent_element); + var badNode = createNode(204 /* BinaryExpression */, result.pos); + badNode.end = invalidElement.end; + badNode.left = result; + badNode.right = invalidElement; + badNode.operatorToken = createMissingNode(27 /* CommaToken */, /*reportAtCurrentPosition*/ false, /*diagnosticMessage*/ undefined); // TODO: GH#18217 + badNode.operatorToken.pos = badNode.operatorToken.end = badNode.right.pos; + return badNode; + } + } + return result; + } + function parseJsxText() { + var node = createNode(11 /* JsxText */); + node.containsOnlyWhiteSpaces = currentToken === 12 /* JsxTextAllWhiteSpaces */; + currentToken = scanner.scanJsxToken(); + return finishNode(node); + } + function parseJsxChild(openingTag, token) { + switch (token) { + case 1 /* EndOfFileToken */: + // If we hit EOF, issue the error at the tag that lacks the closing element + // rather than at the end of the file (which is useless) + if (ts.isJsxOpeningFragment(openingTag)) { + parseErrorAtRange(openingTag, ts.Diagnostics.JSX_fragment_has_no_corresponding_closing_tag); + } + else { + parseErrorAtRange(openingTag.tagName, ts.Diagnostics.JSX_element_0_has_no_corresponding_closing_tag, ts.getTextOfNodeFromSourceText(sourceText, openingTag.tagName)); + } + return undefined; + case 29 /* LessThanSlashToken */: + case 7 /* ConflictMarkerTrivia */: + return undefined; + case 11 /* JsxText */: + case 12 /* JsxTextAllWhiteSpaces */: + return parseJsxText(); + case 18 /* OpenBraceToken */: + return parseJsxExpression(/*inExpressionContext*/ false); + case 28 /* LessThanToken */: + return parseJsxElementOrSelfClosingElementOrFragment(/*inExpressionContext*/ false); + default: + return ts.Debug.assertNever(token); + } + } + function parseJsxChildren(openingTag) { + var list = []; + var listPos = getNodePos(); + var saveParsingContext = parsingContext; + parsingContext |= 1 << 14 /* JsxChildren */; + while (true) { + var child = parseJsxChild(openingTag, currentToken = scanner.reScanJsxToken()); + if (!child) + break; + list.push(child); + } + parsingContext = saveParsingContext; + return createNodeArray(list, listPos); + } + function parseJsxAttributes() { + var jsxAttributes = createNode(268 /* JsxAttributes */); + jsxAttributes.properties = parseList(13 /* JsxAttributes */, parseJsxAttribute); + return finishNode(jsxAttributes); + } + function parseJsxOpeningOrSelfClosingElementOrOpeningFragment(inExpressionContext) { + var fullStart = scanner.getStartPos(); + parseExpected(28 /* LessThanToken */); + if (token() === 30 /* GreaterThanToken */) { + // See below for explanation of scanJsxText + var node_1 = createNode(265 /* JsxOpeningFragment */, fullStart); + scanJsxText(); + return finishNode(node_1); + } + var tagName = parseJsxElementName(); + var typeArguments = tryParseTypeArguments(); + var attributes = parseJsxAttributes(); + var node; + if (token() === 30 /* GreaterThanToken */) { + // Closing tag, so scan the immediately-following text with the JSX scanning instead + // of regular scanning to avoid treating illegal characters (e.g. '#') as immediate + // scanning errors + node = createNode(262 /* JsxOpeningElement */, fullStart); + scanJsxText(); + } + else { + parseExpected(42 /* SlashToken */); + if (inExpressionContext) { + parseExpected(30 /* GreaterThanToken */); + } + else { + parseExpected(30 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false); + scanJsxText(); + } + node = createNode(261 /* JsxSelfClosingElement */, fullStart); + } + node.tagName = tagName; + node.typeArguments = typeArguments; + node.attributes = attributes; + return finishNode(node); + } + function parseJsxElementName() { + scanJsxIdentifier(); + // JsxElement can have name in the form of + // propertyAccessExpression + // primaryExpression in the form of an identifier and "this" keyword + // We can't just simply use parseLeftHandSideExpressionOrHigher because then we will start consider class,function etc as a keyword + // We only want to consider "this" as a primaryExpression + var expression = token() === 100 /* ThisKeyword */ ? + parseTokenNode() : parseIdentifierName(); + while (parseOptional(24 /* DotToken */)) { + var propertyAccess = createNode(189 /* PropertyAccessExpression */, expression.pos); + propertyAccess.expression = expression; + propertyAccess.name = parseRightSideOfDot(/*allowIdentifierNames*/ true); + expression = finishNode(propertyAccess); + } + return expression; + } + function parseJsxExpression(inExpressionContext) { + var node = createNode(270 /* JsxExpression */); + if (!parseExpected(18 /* OpenBraceToken */)) { + return undefined; + } + if (token() !== 19 /* CloseBraceToken */) { + node.dotDotDotToken = parseOptionalToken(25 /* DotDotDotToken */); + node.expression = parseAssignmentExpressionOrHigher(); + } + if (inExpressionContext) { + parseExpected(19 /* CloseBraceToken */); + } + else { + parseExpected(19 /* CloseBraceToken */, /*message*/ undefined, /*shouldAdvance*/ false); + scanJsxText(); + } + return finishNode(node); + } + function parseJsxAttribute() { + if (token() === 18 /* OpenBraceToken */) { + return parseJsxSpreadAttribute(); + } + scanJsxIdentifier(); + var node = createNode(267 /* JsxAttribute */); + node.name = parseIdentifierName(); + if (token() === 59 /* EqualsToken */) { + switch (scanJsxAttributeValue()) { + case 10 /* StringLiteral */: + node.initializer = parseLiteralNode(); + break; + default: + node.initializer = parseJsxExpression(/*inExpressionContext*/ true); + break; + } + } + return finishNode(node); + } + function parseJsxSpreadAttribute() { + var node = createNode(269 /* JsxSpreadAttribute */); + parseExpected(18 /* OpenBraceToken */); + parseExpected(25 /* DotDotDotToken */); + node.expression = parseExpression(); + parseExpected(19 /* CloseBraceToken */); + return finishNode(node); + } + function parseJsxClosingElement(inExpressionContext) { + var node = createNode(263 /* JsxClosingElement */); + parseExpected(29 /* LessThanSlashToken */); + node.tagName = parseJsxElementName(); + if (inExpressionContext) { + parseExpected(30 /* GreaterThanToken */); + } + else { + parseExpected(30 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false); + scanJsxText(); + } + return finishNode(node); + } + function parseJsxClosingFragment(inExpressionContext) { + var node = createNode(266 /* JsxClosingFragment */); + parseExpected(29 /* LessThanSlashToken */); + if (ts.tokenIsIdentifierOrKeyword(token())) { + parseErrorAtRange(parseJsxElementName(), ts.Diagnostics.Expected_corresponding_closing_tag_for_JSX_fragment); + } + if (inExpressionContext) { + parseExpected(30 /* GreaterThanToken */); + } + else { + parseExpected(30 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false); + scanJsxText(); + } + return finishNode(node); + } + function parseTypeAssertion() { + var node = createNode(194 /* TypeAssertionExpression */); + parseExpected(28 /* LessThanToken */); + node.type = parseType(); + parseExpected(30 /* GreaterThanToken */); + node.expression = parseSimpleUnaryExpression(); + return finishNode(node); + } + function parseMemberExpressionRest(expression) { + while (true) { + var dotToken = parseOptionalToken(24 /* DotToken */); + if (dotToken) { + var propertyAccess = createNode(189 /* PropertyAccessExpression */, expression.pos); + propertyAccess.expression = expression; + propertyAccess.name = parseRightSideOfDot(/*allowIdentifierNames*/ true); + expression = finishNode(propertyAccess); + continue; + } + if (token() === 52 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) { + nextToken(); + var nonNullExpression = createNode(213 /* NonNullExpression */, expression.pos); + nonNullExpression.expression = expression; + expression = finishNode(nonNullExpression); + continue; + } + // when in the [Decorator] context, we do not parse ElementAccess as it could be part of a ComputedPropertyName + if (!inDecoratorContext() && parseOptional(22 /* OpenBracketToken */)) { + var indexedAccess = createNode(190 /* ElementAccessExpression */, expression.pos); + indexedAccess.expression = expression; + if (token() === 23 /* CloseBracketToken */) { + indexedAccess.argumentExpression = createMissingNode(72 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.An_element_access_expression_should_take_an_argument); + } + else { + var argument = allowInAnd(parseExpression); + if (ts.isStringOrNumericLiteralLike(argument)) { + argument.text = internIdentifier(argument.text); + } + indexedAccess.argumentExpression = argument; + } + parseExpected(23 /* CloseBracketToken */); + expression = finishNode(indexedAccess); + continue; + } + if (isTemplateStartOfTaggedTemplate()) { + expression = parseTaggedTemplateRest(expression, /*typeArguments*/ undefined); + continue; + } + return expression; + } + } + function isTemplateStartOfTaggedTemplate() { + return token() === 14 /* NoSubstitutionTemplateLiteral */ || token() === 15 /* TemplateHead */; + } + function parseTaggedTemplateRest(tag, typeArguments) { + var tagExpression = createNode(193 /* TaggedTemplateExpression */, tag.pos); + tagExpression.tag = tag; + tagExpression.typeArguments = typeArguments; + tagExpression.template = token() === 14 /* NoSubstitutionTemplateLiteral */ + ? parseLiteralNode() + : parseTemplateExpression(); + return finishNode(tagExpression); + } + function parseCallExpressionRest(expression) { + while (true) { + expression = parseMemberExpressionRest(expression); + if (token() === 28 /* LessThanToken */) { + // See if this is the start of a generic invocation. If so, consume it and + // keep checking for postfix expressions. Otherwise, it's just a '<' that's + // part of an arithmetic expression. Break out so we consume it higher in the + // stack. + var typeArguments = tryParse(parseTypeArgumentsInExpression); + if (!typeArguments) { + return expression; + } + if (isTemplateStartOfTaggedTemplate()) { + expression = parseTaggedTemplateRest(expression, typeArguments); + continue; + } + var callExpr = createNode(191 /* CallExpression */, expression.pos); + callExpr.expression = expression; + callExpr.typeArguments = typeArguments; + callExpr.arguments = parseArgumentList(); + expression = finishNode(callExpr); + continue; + } + else if (token() === 20 /* OpenParenToken */) { + var callExpr = createNode(191 /* CallExpression */, expression.pos); + callExpr.expression = expression; + callExpr.arguments = parseArgumentList(); + expression = finishNode(callExpr); + continue; + } + return expression; + } + } + function parseArgumentList() { + parseExpected(20 /* OpenParenToken */); + var result = parseDelimitedList(11 /* ArgumentExpressions */, parseArgumentExpression); + parseExpected(21 /* CloseParenToken */); + return result; + } + function parseTypeArgumentsInExpression() { + if (!parseOptional(28 /* LessThanToken */)) { + return undefined; + } + var typeArguments = parseDelimitedList(20 /* TypeArguments */, parseType); + if (!parseExpected(30 /* GreaterThanToken */)) { + // If it doesn't have the closing `>` then it's definitely not an type argument list. + return undefined; + } + // If we have a '<', then only parse this as a argument list if the type arguments + // are complete and we have an open paren. if we don't, rewind and return nothing. + return typeArguments && canFollowTypeArgumentsInExpression() + ? typeArguments + : undefined; + } + function canFollowTypeArgumentsInExpression() { + switch (token()) { + case 20 /* OpenParenToken */: // foo( + case 14 /* NoSubstitutionTemplateLiteral */: // foo `...` + case 15 /* TemplateHead */: // foo `...${100}...` + // these are the only tokens can legally follow a type argument + // list. So we definitely want to treat them as type arg lists. + case 24 /* DotToken */: // foo. + case 21 /* CloseParenToken */: // foo) + case 23 /* CloseBracketToken */: // foo] + case 57 /* ColonToken */: // foo: + case 26 /* SemicolonToken */: // foo; + case 56 /* QuestionToken */: // foo? + case 33 /* EqualsEqualsToken */: // foo == + case 35 /* EqualsEqualsEqualsToken */: // foo === + case 34 /* ExclamationEqualsToken */: // foo != + case 36 /* ExclamationEqualsEqualsToken */: // foo !== + case 54 /* AmpersandAmpersandToken */: // foo && + case 55 /* BarBarToken */: // foo || + case 51 /* CaretToken */: // foo ^ + case 49 /* AmpersandToken */: // foo & + case 50 /* BarToken */: // foo | + case 19 /* CloseBraceToken */: // foo } + case 1 /* EndOfFileToken */: // foo + // these cases can't legally follow a type arg list. However, they're not legal + // expressions either. The user is probably in the middle of a generic type. So + // treat it as such. + return true; + case 27 /* CommaToken */: // foo, + case 18 /* OpenBraceToken */: // foo { + // We don't want to treat these as type arguments. Otherwise we'll parse this + // as an invocation expression. Instead, we want to parse out the expression + // in isolation from the type arguments. + default: + // Anything else treat as an expression. + return false; + } + } + function parsePrimaryExpression() { + switch (token()) { + case 8 /* NumericLiteral */: + case 9 /* BigIntLiteral */: + case 10 /* StringLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: + return parseLiteralNode(); + case 100 /* ThisKeyword */: + case 98 /* SuperKeyword */: + case 96 /* NullKeyword */: + case 102 /* TrueKeyword */: + case 87 /* FalseKeyword */: + return parseTokenNode(); + case 20 /* OpenParenToken */: + return parseParenthesizedExpression(); + case 22 /* OpenBracketToken */: + return parseArrayLiteralExpression(); + case 18 /* OpenBraceToken */: + return parseObjectLiteralExpression(); + case 121 /* AsyncKeyword */: + // Async arrow functions are parsed earlier in parseAssignmentExpressionOrHigher. + // If we encounter `async [no LineTerminator here] function` then this is an async + // function; otherwise, its an identifier. + if (!lookAhead(nextTokenIsFunctionKeywordOnSameLine)) { + break; + } + return parseFunctionExpression(); + case 76 /* ClassKeyword */: + return parseClassExpression(); + case 90 /* FunctionKeyword */: + return parseFunctionExpression(); + case 95 /* NewKeyword */: + return parseNewExpressionOrNewDotTarget(); + case 42 /* SlashToken */: + case 64 /* SlashEqualsToken */: + if (reScanSlashToken() === 13 /* RegularExpressionLiteral */) { + return parseLiteralNode(); + } + break; + case 15 /* TemplateHead */: + return parseTemplateExpression(); + } + return parseIdentifier(ts.Diagnostics.Expression_expected); + } + function parseParenthesizedExpression() { + var node = createNodeWithJSDoc(195 /* ParenthesizedExpression */); + parseExpected(20 /* OpenParenToken */); + node.expression = allowInAnd(parseExpression); + parseExpected(21 /* CloseParenToken */); + return finishNode(node); + } + function parseSpreadElement() { + var node = createNode(208 /* SpreadElement */); + parseExpected(25 /* DotDotDotToken */); + node.expression = parseAssignmentExpressionOrHigher(); + return finishNode(node); + } + function parseArgumentOrArrayLiteralElement() { + return token() === 25 /* DotDotDotToken */ ? parseSpreadElement() : + token() === 27 /* CommaToken */ ? createNode(210 /* OmittedExpression */) : + parseAssignmentExpressionOrHigher(); + } + function parseArgumentExpression() { + return doOutsideOfContext(disallowInAndDecoratorContext, parseArgumentOrArrayLiteralElement); + } + function parseArrayLiteralExpression() { + var node = createNode(187 /* ArrayLiteralExpression */); + parseExpected(22 /* OpenBracketToken */); + if (scanner.hasPrecedingLineBreak()) { + node.multiLine = true; + } + node.elements = parseDelimitedList(15 /* ArrayLiteralMembers */, parseArgumentOrArrayLiteralElement); + parseExpected(23 /* CloseBracketToken */); + return finishNode(node); + } + function parseObjectLiteralElement() { + var node = createNodeWithJSDoc(0 /* Unknown */); + if (parseOptionalToken(25 /* DotDotDotToken */)) { + node.kind = 277 /* SpreadAssignment */; + node.expression = parseAssignmentExpressionOrHigher(); + return finishNode(node); + } + node.decorators = parseDecorators(); + node.modifiers = parseModifiers(); + if (parseContextualModifier(126 /* GetKeyword */)) { + return parseAccessorDeclaration(node, 158 /* GetAccessor */); + } + if (parseContextualModifier(137 /* SetKeyword */)) { + return parseAccessorDeclaration(node, 159 /* SetAccessor */); + } + var asteriskToken = parseOptionalToken(40 /* AsteriskToken */); + var tokenIsIdentifier = isIdentifier(); + node.name = parsePropertyName(); + // Disallowing of optional property assignments and definite assignment assertion happens in the grammar checker. + node.questionToken = parseOptionalToken(56 /* QuestionToken */); + node.exclamationToken = parseOptionalToken(52 /* ExclamationToken */); + if (asteriskToken || token() === 20 /* OpenParenToken */ || token() === 28 /* LessThanToken */) { + return parseMethodDeclaration(node, asteriskToken); + } + // check if it is short-hand property assignment or normal property assignment + // NOTE: if token is EqualsToken it is interpreted as CoverInitializedName production + // CoverInitializedName[Yield] : + // IdentifierReference[?Yield] Initializer[In, ?Yield] + // this is necessary because ObjectLiteral productions are also used to cover grammar for ObjectAssignmentPattern + var isShorthandPropertyAssignment = tokenIsIdentifier && (token() !== 57 /* ColonToken */); + if (isShorthandPropertyAssignment) { + node.kind = 276 /* ShorthandPropertyAssignment */; + var equalsToken = parseOptionalToken(59 /* EqualsToken */); + if (equalsToken) { + node.equalsToken = equalsToken; + node.objectAssignmentInitializer = allowInAnd(parseAssignmentExpressionOrHigher); + } + } + else { + node.kind = 275 /* PropertyAssignment */; + parseExpected(57 /* ColonToken */); + node.initializer = allowInAnd(parseAssignmentExpressionOrHigher); + } + return finishNode(node); + } + function parseObjectLiteralExpression() { + var node = createNode(188 /* ObjectLiteralExpression */); + parseExpected(18 /* OpenBraceToken */); + if (scanner.hasPrecedingLineBreak()) { + node.multiLine = true; + } + node.properties = parseDelimitedList(12 /* ObjectLiteralMembers */, parseObjectLiteralElement, /*considerSemicolonAsDelimiter*/ true); + parseExpected(19 /* CloseBraceToken */); + return finishNode(node); + } + function parseFunctionExpression() { + // GeneratorExpression: + // function* BindingIdentifier [Yield][opt](FormalParameters[Yield]){ GeneratorBody } + // + // FunctionExpression: + // function BindingIdentifier[opt](FormalParameters){ FunctionBody } + var saveDecoratorContext = inDecoratorContext(); + if (saveDecoratorContext) { + setDecoratorContext(/*val*/ false); + } + var node = createNodeWithJSDoc(196 /* FunctionExpression */); + node.modifiers = parseModifiers(); + parseExpected(90 /* FunctionKeyword */); + node.asteriskToken = parseOptionalToken(40 /* AsteriskToken */); + var isGenerator = node.asteriskToken ? 1 /* Yield */ : 0 /* None */; + var isAsync = ts.hasModifier(node, 256 /* Async */) ? 2 /* Await */ : 0 /* None */; + node.name = + isGenerator && isAsync ? doInYieldAndAwaitContext(parseOptionalIdentifier) : + isGenerator ? doInYieldContext(parseOptionalIdentifier) : + isAsync ? doInAwaitContext(parseOptionalIdentifier) : + parseOptionalIdentifier(); + fillSignature(57 /* ColonToken */, isGenerator | isAsync, node); + node.body = parseFunctionBlock(isGenerator | isAsync); + if (saveDecoratorContext) { + setDecoratorContext(/*val*/ true); + } + return finishNode(node); + } + function parseOptionalIdentifier() { + return isIdentifier() ? parseIdentifier() : undefined; + } + function parseNewExpressionOrNewDotTarget() { + var fullStart = scanner.getStartPos(); + parseExpected(95 /* NewKeyword */); + if (parseOptional(24 /* DotToken */)) { + var node_2 = createNode(214 /* MetaProperty */, fullStart); + node_2.keywordToken = 95 /* NewKeyword */; + node_2.name = parseIdentifierName(); + return finishNode(node_2); + } + var expression = parsePrimaryExpression(); + var typeArguments; + while (true) { + expression = parseMemberExpressionRest(expression); + typeArguments = tryParse(parseTypeArgumentsInExpression); + if (isTemplateStartOfTaggedTemplate()) { + ts.Debug.assert(!!typeArguments, "Expected a type argument list; all plain tagged template starts should be consumed in 'parseMemberExpressionRest'"); + expression = parseTaggedTemplateRest(expression, typeArguments); + typeArguments = undefined; + } + break; + } + var node = createNode(192 /* NewExpression */, fullStart); + node.expression = expression; + node.typeArguments = typeArguments; + if (node.typeArguments || token() === 20 /* OpenParenToken */) { + node.arguments = parseArgumentList(); + } + return finishNode(node); + } + // STATEMENTS + function parseBlock(ignoreMissingOpenBrace, diagnosticMessage) { + var node = createNode(218 /* Block */); + if (parseExpected(18 /* OpenBraceToken */, diagnosticMessage) || ignoreMissingOpenBrace) { + if (scanner.hasPrecedingLineBreak()) { + node.multiLine = true; + } + node.statements = parseList(1 /* BlockStatements */, parseStatement); + parseExpected(19 /* CloseBraceToken */); + } + else { + node.statements = createMissingList(); + } + return finishNode(node); + } + function parseFunctionBlock(flags, diagnosticMessage) { + var savedYieldContext = inYieldContext(); + setYieldContext(!!(flags & 1 /* Yield */)); + var savedAwaitContext = inAwaitContext(); + setAwaitContext(!!(flags & 2 /* Await */)); + // We may be in a [Decorator] context when parsing a function expression or + // arrow function. The body of the function is not in [Decorator] context. + var saveDecoratorContext = inDecoratorContext(); + if (saveDecoratorContext) { + setDecoratorContext(/*val*/ false); + } + var block = parseBlock(!!(flags & 16 /* IgnoreMissingOpenBrace */), diagnosticMessage); + if (saveDecoratorContext) { + setDecoratorContext(/*val*/ true); + } + setYieldContext(savedYieldContext); + setAwaitContext(savedAwaitContext); + return block; + } + function parseEmptyStatement() { + var node = createNode(220 /* EmptyStatement */); + parseExpected(26 /* SemicolonToken */); + return finishNode(node); + } + function parseIfStatement() { + var node = createNode(222 /* IfStatement */); + parseExpected(91 /* IfKeyword */); + parseExpected(20 /* OpenParenToken */); + node.expression = allowInAnd(parseExpression); + parseExpected(21 /* CloseParenToken */); + node.thenStatement = parseStatement(); + node.elseStatement = parseOptional(83 /* ElseKeyword */) ? parseStatement() : undefined; + return finishNode(node); + } + function parseDoStatement() { + var node = createNode(223 /* DoStatement */); + parseExpected(82 /* DoKeyword */); + node.statement = parseStatement(); + parseExpected(107 /* WhileKeyword */); + parseExpected(20 /* OpenParenToken */); + node.expression = allowInAnd(parseExpression); + parseExpected(21 /* CloseParenToken */); + // From: https://mail.mozilla.org/pipermail/es-discuss/2011-August/016188.html + // 157 min --- All allen at wirfs-brock.com CONF --- "do{;}while(false)false" prohibited in + // spec but allowed in consensus reality. Approved -- this is the de-facto standard whereby + // do;while(0)x will have a semicolon inserted before x. + parseOptional(26 /* SemicolonToken */); + return finishNode(node); + } + function parseWhileStatement() { + var node = createNode(224 /* WhileStatement */); + parseExpected(107 /* WhileKeyword */); + parseExpected(20 /* OpenParenToken */); + node.expression = allowInAnd(parseExpression); + parseExpected(21 /* CloseParenToken */); + node.statement = parseStatement(); + return finishNode(node); + } + function parseForOrForInOrForOfStatement() { + var pos = getNodePos(); + parseExpected(89 /* ForKeyword */); + var awaitToken = parseOptionalToken(122 /* AwaitKeyword */); + parseExpected(20 /* OpenParenToken */); + var initializer; + if (token() !== 26 /* SemicolonToken */) { + if (token() === 105 /* VarKeyword */ || token() === 111 /* LetKeyword */ || token() === 77 /* ConstKeyword */) { + initializer = parseVariableDeclarationList(/*inForStatementInitializer*/ true); + } + else { + initializer = disallowInAnd(parseExpression); + } + } + var forOrForInOrForOfStatement; + if (awaitToken ? parseExpected(147 /* OfKeyword */) : parseOptional(147 /* OfKeyword */)) { + var forOfStatement = createNode(227 /* ForOfStatement */, pos); + forOfStatement.awaitModifier = awaitToken; + forOfStatement.initializer = initializer; + forOfStatement.expression = allowInAnd(parseAssignmentExpressionOrHigher); + parseExpected(21 /* CloseParenToken */); + forOrForInOrForOfStatement = forOfStatement; + } + else if (parseOptional(93 /* InKeyword */)) { + var forInStatement = createNode(226 /* ForInStatement */, pos); + forInStatement.initializer = initializer; + forInStatement.expression = allowInAnd(parseExpression); + parseExpected(21 /* CloseParenToken */); + forOrForInOrForOfStatement = forInStatement; + } + else { + var forStatement = createNode(225 /* ForStatement */, pos); + forStatement.initializer = initializer; + parseExpected(26 /* SemicolonToken */); + if (token() !== 26 /* SemicolonToken */ && token() !== 21 /* CloseParenToken */) { + forStatement.condition = allowInAnd(parseExpression); + } + parseExpected(26 /* SemicolonToken */); + if (token() !== 21 /* CloseParenToken */) { + forStatement.incrementor = allowInAnd(parseExpression); + } + parseExpected(21 /* CloseParenToken */); + forOrForInOrForOfStatement = forStatement; + } + forOrForInOrForOfStatement.statement = parseStatement(); + return finishNode(forOrForInOrForOfStatement); + } + function parseBreakOrContinueStatement(kind) { + var node = createNode(kind); + parseExpected(kind === 229 /* BreakStatement */ ? 73 /* BreakKeyword */ : 78 /* ContinueKeyword */); + if (!canParseSemicolon()) { + node.label = parseIdentifier(); + } + parseSemicolon(); + return finishNode(node); + } + function parseReturnStatement() { + var node = createNode(230 /* ReturnStatement */); + parseExpected(97 /* ReturnKeyword */); + if (!canParseSemicolon()) { + node.expression = allowInAnd(parseExpression); + } + parseSemicolon(); + return finishNode(node); + } + function parseWithStatement() { + var node = createNode(231 /* WithStatement */); + parseExpected(108 /* WithKeyword */); + parseExpected(20 /* OpenParenToken */); + node.expression = allowInAnd(parseExpression); + parseExpected(21 /* CloseParenToken */); + node.statement = doInsideOfContext(8388608 /* InWithStatement */, parseStatement); + return finishNode(node); + } + function parseCaseClause() { + var node = createNode(271 /* CaseClause */); + parseExpected(74 /* CaseKeyword */); + node.expression = allowInAnd(parseExpression); + parseExpected(57 /* ColonToken */); + node.statements = parseList(3 /* SwitchClauseStatements */, parseStatement); + return finishNode(node); + } + function parseDefaultClause() { + var node = createNode(272 /* DefaultClause */); + parseExpected(80 /* DefaultKeyword */); + parseExpected(57 /* ColonToken */); + node.statements = parseList(3 /* SwitchClauseStatements */, parseStatement); + return finishNode(node); + } + function parseCaseOrDefaultClause() { + return token() === 74 /* CaseKeyword */ ? parseCaseClause() : parseDefaultClause(); + } + function parseSwitchStatement() { + var node = createNode(232 /* SwitchStatement */); + parseExpected(99 /* SwitchKeyword */); + parseExpected(20 /* OpenParenToken */); + node.expression = allowInAnd(parseExpression); + parseExpected(21 /* CloseParenToken */); + var caseBlock = createNode(246 /* CaseBlock */); + parseExpected(18 /* OpenBraceToken */); + caseBlock.clauses = parseList(2 /* SwitchClauses */, parseCaseOrDefaultClause); + parseExpected(19 /* CloseBraceToken */); + node.caseBlock = finishNode(caseBlock); + return finishNode(node); + } + function parseThrowStatement() { + // ThrowStatement[Yield] : + // throw [no LineTerminator here]Expression[In, ?Yield]; + // Because of automatic semicolon insertion, we need to report error if this + // throw could be terminated with a semicolon. Note: we can't call 'parseExpression' + // directly as that might consume an expression on the following line. + // We just return 'undefined' in that case. The actual error will be reported in the + // grammar walker. + var node = createNode(234 /* ThrowStatement */); + parseExpected(101 /* ThrowKeyword */); + node.expression = scanner.hasPrecedingLineBreak() ? undefined : allowInAnd(parseExpression); + parseSemicolon(); + return finishNode(node); + } + // TODO: Review for error recovery + function parseTryStatement() { + var node = createNode(235 /* TryStatement */); + parseExpected(103 /* TryKeyword */); + node.tryBlock = parseBlock(/*ignoreMissingOpenBrace*/ false); + node.catchClause = token() === 75 /* CatchKeyword */ ? parseCatchClause() : undefined; + // If we don't have a catch clause, then we must have a finally clause. Try to parse + // one out no matter what. + if (!node.catchClause || token() === 88 /* FinallyKeyword */) { + parseExpected(88 /* FinallyKeyword */); + node.finallyBlock = parseBlock(/*ignoreMissingOpenBrace*/ false); + } + return finishNode(node); + } + function parseCatchClause() { + var result = createNode(274 /* CatchClause */); + parseExpected(75 /* CatchKeyword */); + if (parseOptional(20 /* OpenParenToken */)) { + result.variableDeclaration = parseVariableDeclaration(); + parseExpected(21 /* CloseParenToken */); + } + else { + // Keep shape of node to avoid degrading performance. + result.variableDeclaration = undefined; + } + result.block = parseBlock(/*ignoreMissingOpenBrace*/ false); + return finishNode(result); + } + function parseDebuggerStatement() { + var node = createNode(236 /* DebuggerStatement */); + parseExpected(79 /* DebuggerKeyword */); + parseSemicolon(); + return finishNode(node); + } + function parseExpressionOrLabeledStatement() { + // Avoiding having to do the lookahead for a labeled statement by just trying to parse + // out an expression, seeing if it is identifier and then seeing if it is followed by + // a colon. + var node = createNodeWithJSDoc(0 /* Unknown */); + var expression = allowInAnd(parseExpression); + if (expression.kind === 72 /* Identifier */ && parseOptional(57 /* ColonToken */)) { + node.kind = 233 /* LabeledStatement */; + node.label = expression; + node.statement = parseStatement(); + } + else { + node.kind = 221 /* ExpressionStatement */; + node.expression = expression; + parseSemicolon(); + } + return finishNode(node); + } + function nextTokenIsIdentifierOrKeywordOnSameLine() { + nextToken(); + return ts.tokenIsIdentifierOrKeyword(token()) && !scanner.hasPrecedingLineBreak(); + } + function nextTokenIsClassKeywordOnSameLine() { + nextToken(); + return token() === 76 /* ClassKeyword */ && !scanner.hasPrecedingLineBreak(); + } + function nextTokenIsFunctionKeywordOnSameLine() { + nextToken(); + return token() === 90 /* FunctionKeyword */ && !scanner.hasPrecedingLineBreak(); + } + function nextTokenIsIdentifierOrKeywordOrLiteralOnSameLine() { + nextToken(); + return (ts.tokenIsIdentifierOrKeyword(token()) || token() === 8 /* NumericLiteral */ || token() === 9 /* BigIntLiteral */ || token() === 10 /* StringLiteral */) && !scanner.hasPrecedingLineBreak(); + } + function isDeclaration() { + while (true) { + switch (token()) { + case 105 /* VarKeyword */: + case 111 /* LetKeyword */: + case 77 /* ConstKeyword */: + case 90 /* FunctionKeyword */: + case 76 /* ClassKeyword */: + case 84 /* EnumKeyword */: + return true; + // 'declare', 'module', 'namespace', 'interface'* and 'type' are all legal JavaScript identifiers; + // however, an identifier cannot be followed by another identifier on the same line. This is what we + // count on to parse out the respective declarations. For instance, we exploit this to say that + // + // namespace n + // + // can be none other than the beginning of a namespace declaration, but need to respect that JavaScript sees + // + // namespace + // n + // + // as the identifier 'namespace' on one line followed by the identifier 'n' on another. + // We need to look one token ahead to see if it permissible to try parsing a declaration. + // + // *Note*: 'interface' is actually a strict mode reserved word. So while + // + // "use strict" + // interface + // I {} + // + // could be legal, it would add complexity for very little gain. + case 110 /* InterfaceKeyword */: + case 140 /* TypeKeyword */: + return nextTokenIsIdentifierOnSameLine(); + case 130 /* ModuleKeyword */: + case 131 /* NamespaceKeyword */: + return nextTokenIsIdentifierOrStringLiteralOnSameLine(); + case 118 /* AbstractKeyword */: + case 121 /* AsyncKeyword */: + case 125 /* DeclareKeyword */: + case 113 /* PrivateKeyword */: + case 114 /* ProtectedKeyword */: + case 115 /* PublicKeyword */: + case 133 /* ReadonlyKeyword */: + nextToken(); + // ASI takes effect for this modifier. + if (scanner.hasPrecedingLineBreak()) { + return false; + } + continue; + case 145 /* GlobalKeyword */: + nextToken(); + return token() === 18 /* OpenBraceToken */ || token() === 72 /* Identifier */ || token() === 85 /* ExportKeyword */; + case 92 /* ImportKeyword */: + nextToken(); + return token() === 10 /* StringLiteral */ || token() === 40 /* AsteriskToken */ || + token() === 18 /* OpenBraceToken */ || ts.tokenIsIdentifierOrKeyword(token()); + case 85 /* ExportKeyword */: + nextToken(); + if (token() === 59 /* EqualsToken */ || token() === 40 /* AsteriskToken */ || + token() === 18 /* OpenBraceToken */ || token() === 80 /* DefaultKeyword */ || + token() === 119 /* AsKeyword */) { + return true; + } + continue; + case 116 /* StaticKeyword */: + nextToken(); + continue; + default: + return false; + } + } + } + function isStartOfDeclaration() { + return lookAhead(isDeclaration); + } + function isStartOfStatement() { + switch (token()) { + case 58 /* AtToken */: + case 26 /* SemicolonToken */: + case 18 /* OpenBraceToken */: + case 105 /* VarKeyword */: + case 111 /* LetKeyword */: + case 90 /* FunctionKeyword */: + case 76 /* ClassKeyword */: + case 84 /* EnumKeyword */: + case 91 /* IfKeyword */: + case 82 /* DoKeyword */: + case 107 /* WhileKeyword */: + case 89 /* ForKeyword */: + case 78 /* ContinueKeyword */: + case 73 /* BreakKeyword */: + case 97 /* ReturnKeyword */: + case 108 /* WithKeyword */: + case 99 /* SwitchKeyword */: + case 101 /* ThrowKeyword */: + case 103 /* TryKeyword */: + case 79 /* DebuggerKeyword */: + // 'catch' and 'finally' do not actually indicate that the code is part of a statement, + // however, we say they are here so that we may gracefully parse them and error later. + case 75 /* CatchKeyword */: + case 88 /* FinallyKeyword */: + return true; + case 92 /* ImportKeyword */: + return isStartOfDeclaration() || lookAhead(nextTokenIsOpenParenOrLessThanOrDot); + case 77 /* ConstKeyword */: + case 85 /* ExportKeyword */: + return isStartOfDeclaration(); + case 121 /* AsyncKeyword */: + case 125 /* DeclareKeyword */: + case 110 /* InterfaceKeyword */: + case 130 /* ModuleKeyword */: + case 131 /* NamespaceKeyword */: + case 140 /* TypeKeyword */: + case 145 /* GlobalKeyword */: + // When these don't start a declaration, they're an identifier in an expression statement + return true; + case 115 /* PublicKeyword */: + case 113 /* PrivateKeyword */: + case 114 /* ProtectedKeyword */: + case 116 /* StaticKeyword */: + case 133 /* ReadonlyKeyword */: + // When these don't start a declaration, they may be the start of a class member if an identifier + // immediately follows. Otherwise they're an identifier in an expression statement. + return isStartOfDeclaration() || !lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine); + default: + return isStartOfExpression(); + } + } + function nextTokenIsIdentifierOrStartOfDestructuring() { + nextToken(); + return isIdentifier() || token() === 18 /* OpenBraceToken */ || token() === 22 /* OpenBracketToken */; + } + function isLetDeclaration() { + // In ES6 'let' always starts a lexical declaration if followed by an identifier or { + // or [. + return lookAhead(nextTokenIsIdentifierOrStartOfDestructuring); + } + function parseStatement() { + switch (token()) { + case 26 /* SemicolonToken */: + return parseEmptyStatement(); + case 18 /* OpenBraceToken */: + return parseBlock(/*ignoreMissingOpenBrace*/ false); + case 105 /* VarKeyword */: + return parseVariableStatement(createNodeWithJSDoc(237 /* VariableDeclaration */)); + case 111 /* LetKeyword */: + if (isLetDeclaration()) { + return parseVariableStatement(createNodeWithJSDoc(237 /* VariableDeclaration */)); + } + break; + case 90 /* FunctionKeyword */: + return parseFunctionDeclaration(createNodeWithJSDoc(239 /* FunctionDeclaration */)); + case 76 /* ClassKeyword */: + return parseClassDeclaration(createNodeWithJSDoc(240 /* ClassDeclaration */)); + case 91 /* IfKeyword */: + return parseIfStatement(); + case 82 /* DoKeyword */: + return parseDoStatement(); + case 107 /* WhileKeyword */: + return parseWhileStatement(); + case 89 /* ForKeyword */: + return parseForOrForInOrForOfStatement(); + case 78 /* ContinueKeyword */: + return parseBreakOrContinueStatement(228 /* ContinueStatement */); + case 73 /* BreakKeyword */: + return parseBreakOrContinueStatement(229 /* BreakStatement */); + case 97 /* ReturnKeyword */: + return parseReturnStatement(); + case 108 /* WithKeyword */: + return parseWithStatement(); + case 99 /* SwitchKeyword */: + return parseSwitchStatement(); + case 101 /* ThrowKeyword */: + return parseThrowStatement(); + case 103 /* TryKeyword */: + // Include 'catch' and 'finally' for error recovery. + case 75 /* CatchKeyword */: + case 88 /* FinallyKeyword */: + return parseTryStatement(); + case 79 /* DebuggerKeyword */: + return parseDebuggerStatement(); + case 58 /* AtToken */: + return parseDeclaration(); + case 121 /* AsyncKeyword */: + case 110 /* InterfaceKeyword */: + case 140 /* TypeKeyword */: + case 130 /* ModuleKeyword */: + case 131 /* NamespaceKeyword */: + case 125 /* DeclareKeyword */: + case 77 /* ConstKeyword */: + case 84 /* EnumKeyword */: + case 85 /* ExportKeyword */: + case 92 /* ImportKeyword */: + case 113 /* PrivateKeyword */: + case 114 /* ProtectedKeyword */: + case 115 /* PublicKeyword */: + case 118 /* AbstractKeyword */: + case 116 /* StaticKeyword */: + case 133 /* ReadonlyKeyword */: + case 145 /* GlobalKeyword */: + if (isStartOfDeclaration()) { + return parseDeclaration(); + } + break; + } + return parseExpressionOrLabeledStatement(); + } + function isDeclareModifier(modifier) { + return modifier.kind === 125 /* DeclareKeyword */; + } + function parseDeclaration() { + var node = createNodeWithJSDoc(0 /* Unknown */); + node.decorators = parseDecorators(); + node.modifiers = parseModifiers(); + if (ts.some(node.modifiers, isDeclareModifier)) { + for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) { + var m = _a[_i]; + m.flags |= 4194304 /* Ambient */; + } + return doInsideOfContext(4194304 /* Ambient */, function () { return parseDeclarationWorker(node); }); + } + else { + return parseDeclarationWorker(node); + } + } + function parseDeclarationWorker(node) { + switch (token()) { + case 105 /* VarKeyword */: + case 111 /* LetKeyword */: + case 77 /* ConstKeyword */: + return parseVariableStatement(node); + case 90 /* FunctionKeyword */: + return parseFunctionDeclaration(node); + case 76 /* ClassKeyword */: + return parseClassDeclaration(node); + case 110 /* InterfaceKeyword */: + return parseInterfaceDeclaration(node); + case 140 /* TypeKeyword */: + return parseTypeAliasDeclaration(node); + case 84 /* EnumKeyword */: + return parseEnumDeclaration(node); + case 145 /* GlobalKeyword */: + case 130 /* ModuleKeyword */: + case 131 /* NamespaceKeyword */: + return parseModuleDeclaration(node); + case 92 /* ImportKeyword */: + return parseImportDeclarationOrImportEqualsDeclaration(node); + case 85 /* ExportKeyword */: + nextToken(); + switch (token()) { + case 80 /* DefaultKeyword */: + case 59 /* EqualsToken */: + return parseExportAssignment(node); + case 119 /* AsKeyword */: + return parseNamespaceExportDeclaration(node); + default: + return parseExportDeclaration(node); + } + default: + if (node.decorators || node.modifiers) { + // We reached this point because we encountered decorators and/or modifiers and assumed a declaration + // would follow. For recovery and error reporting purposes, return an incomplete declaration. + var missing = createMissingNode(258 /* MissingDeclaration */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected); + missing.pos = node.pos; + missing.decorators = node.decorators; + missing.modifiers = node.modifiers; + return finishNode(missing); + } + return undefined; // TODO: GH#18217 + } + } + function nextTokenIsIdentifierOrStringLiteralOnSameLine() { + nextToken(); + return !scanner.hasPrecedingLineBreak() && (isIdentifier() || token() === 10 /* StringLiteral */); + } + function parseFunctionBlockOrSemicolon(flags, diagnosticMessage) { + if (token() !== 18 /* OpenBraceToken */ && canParseSemicolon()) { + parseSemicolon(); + return; + } + return parseFunctionBlock(flags, diagnosticMessage); + } + // DECLARATIONS + function parseArrayBindingElement() { + if (token() === 27 /* CommaToken */) { + return createNode(210 /* OmittedExpression */); + } + var node = createNode(186 /* BindingElement */); + node.dotDotDotToken = parseOptionalToken(25 /* DotDotDotToken */); + node.name = parseIdentifierOrPattern(); + node.initializer = parseInitializer(); + return finishNode(node); + } + function parseObjectBindingElement() { + var node = createNode(186 /* BindingElement */); + node.dotDotDotToken = parseOptionalToken(25 /* DotDotDotToken */); + var tokenIsIdentifier = isIdentifier(); + var propertyName = parsePropertyName(); + if (tokenIsIdentifier && token() !== 57 /* ColonToken */) { + node.name = propertyName; + } + else { + parseExpected(57 /* ColonToken */); + node.propertyName = propertyName; + node.name = parseIdentifierOrPattern(); + } + node.initializer = parseInitializer(); + return finishNode(node); + } + function parseObjectBindingPattern() { + var node = createNode(184 /* ObjectBindingPattern */); + parseExpected(18 /* OpenBraceToken */); + node.elements = parseDelimitedList(9 /* ObjectBindingElements */, parseObjectBindingElement); + parseExpected(19 /* CloseBraceToken */); + return finishNode(node); + } + function parseArrayBindingPattern() { + var node = createNode(185 /* ArrayBindingPattern */); + parseExpected(22 /* OpenBracketToken */); + node.elements = parseDelimitedList(10 /* ArrayBindingElements */, parseArrayBindingElement); + parseExpected(23 /* CloseBracketToken */); + return finishNode(node); + } + function isIdentifierOrPattern() { + return token() === 18 /* OpenBraceToken */ || token() === 22 /* OpenBracketToken */ || isIdentifier(); + } + function parseIdentifierOrPattern() { + if (token() === 22 /* OpenBracketToken */) { + return parseArrayBindingPattern(); + } + if (token() === 18 /* OpenBraceToken */) { + return parseObjectBindingPattern(); + } + return parseIdentifier(); + } + function parseVariableDeclarationAllowExclamation() { + return parseVariableDeclaration(/*allowExclamation*/ true); + } + function parseVariableDeclaration(allowExclamation) { + var node = createNode(237 /* VariableDeclaration */); + node.name = parseIdentifierOrPattern(); + if (allowExclamation && node.name.kind === 72 /* Identifier */ && + token() === 52 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) { + node.exclamationToken = parseTokenNode(); + } + node.type = parseTypeAnnotation(); + if (!isInOrOfKeyword(token())) { + node.initializer = parseInitializer(); + } + return finishNode(node); + } + function parseVariableDeclarationList(inForStatementInitializer) { + var node = createNode(238 /* VariableDeclarationList */); + switch (token()) { + case 105 /* VarKeyword */: + break; + case 111 /* LetKeyword */: + node.flags |= 1 /* Let */; + break; + case 77 /* ConstKeyword */: + node.flags |= 2 /* Const */; + break; + default: + ts.Debug.fail(); + } + nextToken(); + // The user may have written the following: + // + // for (let of X) { } + // + // In this case, we want to parse an empty declaration list, and then parse 'of' + // as a keyword. The reason this is not automatic is that 'of' is a valid identifier. + // So we need to look ahead to determine if 'of' should be treated as a keyword in + // this context. + // The checker will then give an error that there is an empty declaration list. + if (token() === 147 /* OfKeyword */ && lookAhead(canFollowContextualOfKeyword)) { + node.declarations = createMissingList(); + } + else { + var savedDisallowIn = inDisallowInContext(); + setDisallowInContext(inForStatementInitializer); + node.declarations = parseDelimitedList(8 /* VariableDeclarations */, inForStatementInitializer ? parseVariableDeclaration : parseVariableDeclarationAllowExclamation); + setDisallowInContext(savedDisallowIn); + } + return finishNode(node); + } + function canFollowContextualOfKeyword() { + return nextTokenIsIdentifier() && nextToken() === 21 /* CloseParenToken */; + } + function parseVariableStatement(node) { + node.kind = 219 /* VariableStatement */; + node.declarationList = parseVariableDeclarationList(/*inForStatementInitializer*/ false); + parseSemicolon(); + return finishNode(node); + } + function parseFunctionDeclaration(node) { + node.kind = 239 /* FunctionDeclaration */; + parseExpected(90 /* FunctionKeyword */); + node.asteriskToken = parseOptionalToken(40 /* AsteriskToken */); + node.name = ts.hasModifier(node, 512 /* Default */) ? parseOptionalIdentifier() : parseIdentifier(); + var isGenerator = node.asteriskToken ? 1 /* Yield */ : 0 /* None */; + var isAsync = ts.hasModifier(node, 256 /* Async */) ? 2 /* Await */ : 0 /* None */; + fillSignature(57 /* ColonToken */, isGenerator | isAsync, node); + node.body = parseFunctionBlockOrSemicolon(isGenerator | isAsync, ts.Diagnostics.or_expected); + return finishNode(node); + } + function parseConstructorDeclaration(node) { + node.kind = 157 /* Constructor */; + parseExpected(124 /* ConstructorKeyword */); + fillSignature(57 /* ColonToken */, 0 /* None */, node); + node.body = parseFunctionBlockOrSemicolon(0 /* None */, ts.Diagnostics.or_expected); + return finishNode(node); + } + function parseMethodDeclaration(node, asteriskToken, diagnosticMessage) { + node.kind = 156 /* MethodDeclaration */; + node.asteriskToken = asteriskToken; + var isGenerator = asteriskToken ? 1 /* Yield */ : 0 /* None */; + var isAsync = ts.hasModifier(node, 256 /* Async */) ? 2 /* Await */ : 0 /* None */; + fillSignature(57 /* ColonToken */, isGenerator | isAsync, node); + node.body = parseFunctionBlockOrSemicolon(isGenerator | isAsync, diagnosticMessage); + return finishNode(node); + } + function parsePropertyDeclaration(node) { + node.kind = 154 /* PropertyDeclaration */; + if (!node.questionToken && token() === 52 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) { + node.exclamationToken = parseTokenNode(); + } + node.type = parseTypeAnnotation(); + // For instance properties specifically, since they are evaluated inside the constructor, + // we do *not * want to parse yield expressions, so we specifically turn the yield context + // off. The grammar would look something like this: + // + // MemberVariableDeclaration[Yield]: + // AccessibilityModifier_opt PropertyName TypeAnnotation_opt Initializer_opt[In]; + // AccessibilityModifier_opt static_opt PropertyName TypeAnnotation_opt Initializer_opt[In, ?Yield]; + // + // The checker may still error in the static case to explicitly disallow the yield expression. + node.initializer = ts.hasModifier(node, 32 /* Static */) + ? allowInAnd(parseInitializer) + : doOutsideOfContext(4096 /* YieldContext */ | 2048 /* DisallowInContext */, parseInitializer); + parseSemicolon(); + return finishNode(node); + } + function parsePropertyOrMethodDeclaration(node) { + var asteriskToken = parseOptionalToken(40 /* AsteriskToken */); + node.name = parsePropertyName(); + // Note: this is not legal as per the grammar. But we allow it in the parser and + // report an error in the grammar checker. + node.questionToken = parseOptionalToken(56 /* QuestionToken */); + if (asteriskToken || token() === 20 /* OpenParenToken */ || token() === 28 /* LessThanToken */) { + return parseMethodDeclaration(node, asteriskToken, ts.Diagnostics.or_expected); + } + return parsePropertyDeclaration(node); + } + function parseAccessorDeclaration(node, kind) { + node.kind = kind; + node.name = parsePropertyName(); + fillSignature(57 /* ColonToken */, 0 /* None */, node); + node.body = parseFunctionBlockOrSemicolon(0 /* None */); + return finishNode(node); + } + function isClassMemberStart() { + var idToken; + if (token() === 58 /* AtToken */) { + return true; + } + // Eat up all modifiers, but hold on to the last one in case it is actually an identifier. + while (ts.isModifierKind(token())) { + idToken = token(); + // If the idToken is a class modifier (protected, private, public, and static), it is + // certain that we are starting to parse class member. This allows better error recovery + // Example: + // public foo() ... // true + // public @dec blah ... // true; we will then report an error later + // export public ... // true; we will then report an error later + if (ts.isClassMemberModifier(idToken)) { + return true; + } + nextToken(); + } + if (token() === 40 /* AsteriskToken */) { + return true; + } + // Try to get the first property-like token following all modifiers. + // This can either be an identifier or the 'get' or 'set' keywords. + if (isLiteralPropertyName()) { + idToken = token(); + nextToken(); + } + // Index signatures and computed properties are class members; we can parse. + if (token() === 22 /* OpenBracketToken */) { + return true; + } + // If we were able to get any potential identifier... + if (idToken !== undefined) { + // If we have a non-keyword identifier, or if we have an accessor, then it's safe to parse. + if (!ts.isKeyword(idToken) || idToken === 137 /* SetKeyword */ || idToken === 126 /* GetKeyword */) { + return true; + } + // If it *is* a keyword, but not an accessor, check a little farther along + // to see if it should actually be parsed as a class member. + switch (token()) { + case 20 /* OpenParenToken */: // Method declaration + case 28 /* LessThanToken */: // Generic Method declaration + case 52 /* ExclamationToken */: // Non-null assertion on property name + case 57 /* ColonToken */: // Type Annotation for declaration + case 59 /* EqualsToken */: // Initializer for declaration + case 56 /* QuestionToken */: // Not valid, but permitted so that it gets caught later on. + return true; + default: + // Covers + // - Semicolons (declaration termination) + // - Closing braces (end-of-class, must be declaration) + // - End-of-files (not valid, but permitted so that it gets caught later on) + // - Line-breaks (enabling *automatic semicolon insertion*) + return canParseSemicolon(); + } + } + return false; + } + function parseDecorators() { + var list; + var listPos = getNodePos(); + while (true) { + var decoratorStart = getNodePos(); + if (!parseOptional(58 /* AtToken */)) { + break; + } + var decorator = createNode(152 /* Decorator */, decoratorStart); + decorator.expression = doInDecoratorContext(parseLeftHandSideExpressionOrHigher); + finishNode(decorator); + (list || (list = [])).push(decorator); + } + return list && createNodeArray(list, listPos); + } + /* + * There are situations in which a modifier like 'const' will appear unexpectedly, such as on a class member. + * In those situations, if we are entirely sure that 'const' is not valid on its own (such as when ASI takes effect + * and turns it into a standalone declaration), then it is better to parse it and report an error later. + * + * In such situations, 'permitInvalidConstAsModifier' should be set to true. + */ + function parseModifiers(permitInvalidConstAsModifier) { + var list; + var listPos = getNodePos(); + while (true) { + var modifierStart = scanner.getStartPos(); + var modifierKind = token(); + if (token() === 77 /* ConstKeyword */ && permitInvalidConstAsModifier) { + // We need to ensure that any subsequent modifiers appear on the same line + // so that when 'const' is a standalone declaration, we don't issue an error. + if (!tryParse(nextTokenIsOnSameLineAndCanFollowModifier)) { + break; + } + } + else { + if (!parseAnyContextualModifier()) { + break; + } + } + var modifier = finishNode(createNode(modifierKind, modifierStart)); + (list || (list = [])).push(modifier); + } + return list && createNodeArray(list, listPos); + } + function parseModifiersForArrowFunction() { + var modifiers; + if (token() === 121 /* AsyncKeyword */) { + var modifierStart = scanner.getStartPos(); + var modifierKind = token(); + nextToken(); + var modifier = finishNode(createNode(modifierKind, modifierStart)); + modifiers = createNodeArray([modifier], modifierStart); + } + return modifiers; + } + function parseClassElement() { + if (token() === 26 /* SemicolonToken */) { + var result = createNode(217 /* SemicolonClassElement */); + nextToken(); + return finishNode(result); + } + var node = createNodeWithJSDoc(0 /* Unknown */); + node.decorators = parseDecorators(); + node.modifiers = parseModifiers(/*permitInvalidConstAsModifier*/ true); + if (parseContextualModifier(126 /* GetKeyword */)) { + return parseAccessorDeclaration(node, 158 /* GetAccessor */); + } + if (parseContextualModifier(137 /* SetKeyword */)) { + return parseAccessorDeclaration(node, 159 /* SetAccessor */); + } + if (token() === 124 /* ConstructorKeyword */) { + return parseConstructorDeclaration(node); + } + if (isIndexSignature()) { + return parseIndexSignatureDeclaration(node); + } + // It is very important that we check this *after* checking indexers because + // the [ token can start an index signature or a computed property name + if (ts.tokenIsIdentifierOrKeyword(token()) || + token() === 10 /* StringLiteral */ || + token() === 8 /* NumericLiteral */ || + token() === 40 /* AsteriskToken */ || + token() === 22 /* OpenBracketToken */) { + return parsePropertyOrMethodDeclaration(node); + } + if (node.decorators || node.modifiers) { + // treat this as a property declaration with a missing name. + node.name = createMissingNode(72 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected); + return parsePropertyDeclaration(node); + } + // 'isClassMemberStart' should have hinted not to attempt parsing. + return ts.Debug.fail("Should not have attempted to parse class member declaration."); + } + function parseClassExpression() { + return parseClassDeclarationOrExpression(createNodeWithJSDoc(0 /* Unknown */), 209 /* ClassExpression */); + } + function parseClassDeclaration(node) { + return parseClassDeclarationOrExpression(node, 240 /* ClassDeclaration */); + } + function parseClassDeclarationOrExpression(node, kind) { + node.kind = kind; + parseExpected(76 /* ClassKeyword */); + node.name = parseNameOfClassDeclarationOrExpression(); + node.typeParameters = parseTypeParameters(); + node.heritageClauses = parseHeritageClauses(); + if (parseExpected(18 /* OpenBraceToken */)) { + // ClassTail[Yield,Await] : (Modified) See 14.5 + // ClassHeritage[?Yield,?Await]opt { ClassBody[?Yield,?Await]opt } + node.members = parseClassMembers(); + parseExpected(19 /* CloseBraceToken */); + } + else { + node.members = createMissingList(); + } + return finishNode(node); + } + function parseNameOfClassDeclarationOrExpression() { + // implements is a future reserved word so + // 'class implements' might mean either + // - class expression with omitted name, 'implements' starts heritage clause + // - class with name 'implements' + // 'isImplementsClause' helps to disambiguate between these two cases + return isIdentifier() && !isImplementsClause() + ? parseIdentifier() + : undefined; + } + function isImplementsClause() { + return token() === 109 /* ImplementsKeyword */ && lookAhead(nextTokenIsIdentifierOrKeyword); + } + function parseHeritageClauses() { + // ClassTail[Yield,Await] : (Modified) See 14.5 + // ClassHeritage[?Yield,?Await]opt { ClassBody[?Yield,?Await]opt } + if (isHeritageClause()) { + return parseList(22 /* HeritageClauses */, parseHeritageClause); + } + return undefined; + } + function parseHeritageClause() { + var tok = token(); + ts.Debug.assert(tok === 86 /* ExtendsKeyword */ || tok === 109 /* ImplementsKeyword */); // isListElement() should ensure this. + var node = createNode(273 /* HeritageClause */); + node.token = tok; + nextToken(); + node.types = parseDelimitedList(7 /* HeritageClauseElement */, parseExpressionWithTypeArguments); + return finishNode(node); + } + function parseExpressionWithTypeArguments() { + var node = createNode(211 /* ExpressionWithTypeArguments */); + node.expression = parseLeftHandSideExpressionOrHigher(); + node.typeArguments = tryParseTypeArguments(); + return finishNode(node); + } + function tryParseTypeArguments() { + return token() === 28 /* LessThanToken */ + ? parseBracketedList(20 /* TypeArguments */, parseType, 28 /* LessThanToken */, 30 /* GreaterThanToken */) + : undefined; + } + function isHeritageClause() { + return token() === 86 /* ExtendsKeyword */ || token() === 109 /* ImplementsKeyword */; + } + function parseClassMembers() { + return parseList(5 /* ClassMembers */, parseClassElement); + } + function parseInterfaceDeclaration(node) { + node.kind = 241 /* InterfaceDeclaration */; + parseExpected(110 /* InterfaceKeyword */); + node.name = parseIdentifier(); + node.typeParameters = parseTypeParameters(); + node.heritageClauses = parseHeritageClauses(); + node.members = parseObjectTypeMembers(); + return finishNode(node); + } + function parseTypeAliasDeclaration(node) { + node.kind = 242 /* TypeAliasDeclaration */; + parseExpected(140 /* TypeKeyword */); + node.name = parseIdentifier(); + node.typeParameters = parseTypeParameters(); + parseExpected(59 /* EqualsToken */); + node.type = parseType(); + parseSemicolon(); + return finishNode(node); + } + // In an ambient declaration, the grammar only allows integer literals as initializers. + // In a non-ambient declaration, the grammar allows uninitialized members only in a + // ConstantEnumMemberSection, which starts at the beginning of an enum declaration + // or any time an integer literal initializer is encountered. + function parseEnumMember() { + var node = createNodeWithJSDoc(278 /* EnumMember */); + node.name = parsePropertyName(); + node.initializer = allowInAnd(parseInitializer); + return finishNode(node); + } + function parseEnumDeclaration(node) { + node.kind = 243 /* EnumDeclaration */; + parseExpected(84 /* EnumKeyword */); + node.name = parseIdentifier(); + if (parseExpected(18 /* OpenBraceToken */)) { + node.members = parseDelimitedList(6 /* EnumMembers */, parseEnumMember); + parseExpected(19 /* CloseBraceToken */); + } + else { + node.members = createMissingList(); + } + return finishNode(node); + } + function parseModuleBlock() { + var node = createNode(245 /* ModuleBlock */); + if (parseExpected(18 /* OpenBraceToken */)) { + node.statements = parseList(1 /* BlockStatements */, parseStatement); + parseExpected(19 /* CloseBraceToken */); + } + else { + node.statements = createMissingList(); + } + return finishNode(node); + } + function parseModuleOrNamespaceDeclaration(node, flags) { + node.kind = 244 /* ModuleDeclaration */; + // If we are parsing a dotted namespace name, we want to + // propagate the 'Namespace' flag across the names if set. + var namespaceFlag = flags & 16 /* Namespace */; + node.flags |= flags; + node.name = parseIdentifier(); + node.body = parseOptional(24 /* DotToken */) + ? parseModuleOrNamespaceDeclaration(createNode(0 /* Unknown */), 4 /* NestedNamespace */ | namespaceFlag) + : parseModuleBlock(); + return finishNode(node); + } + function parseAmbientExternalModuleDeclaration(node) { + node.kind = 244 /* ModuleDeclaration */; + if (token() === 145 /* GlobalKeyword */) { + // parse 'global' as name of global scope augmentation + node.name = parseIdentifier(); + node.flags |= 512 /* GlobalAugmentation */; + } + else { + node.name = parseLiteralNode(); + node.name.text = internIdentifier(node.name.text); + } + if (token() === 18 /* OpenBraceToken */) { + node.body = parseModuleBlock(); + } + else { + parseSemicolon(); + } + return finishNode(node); + } + function parseModuleDeclaration(node) { + var flags = 0; + if (token() === 145 /* GlobalKeyword */) { + // global augmentation + return parseAmbientExternalModuleDeclaration(node); + } + else if (parseOptional(131 /* NamespaceKeyword */)) { + flags |= 16 /* Namespace */; + } + else { + parseExpected(130 /* ModuleKeyword */); + if (token() === 10 /* StringLiteral */) { + return parseAmbientExternalModuleDeclaration(node); + } + } + return parseModuleOrNamespaceDeclaration(node, flags); + } + function isExternalModuleReference() { + return token() === 134 /* RequireKeyword */ && + lookAhead(nextTokenIsOpenParen); + } + function nextTokenIsOpenParen() { + return nextToken() === 20 /* OpenParenToken */; + } + function nextTokenIsSlash() { + return nextToken() === 42 /* SlashToken */; + } + function parseNamespaceExportDeclaration(node) { + node.kind = 247 /* NamespaceExportDeclaration */; + parseExpected(119 /* AsKeyword */); + parseExpected(131 /* NamespaceKeyword */); + node.name = parseIdentifier(); + parseSemicolon(); + return finishNode(node); + } + function parseImportDeclarationOrImportEqualsDeclaration(node) { + parseExpected(92 /* ImportKeyword */); + var afterImportPos = scanner.getStartPos(); + var identifier; + if (isIdentifier()) { + identifier = parseIdentifier(); + if (token() !== 27 /* CommaToken */ && token() !== 144 /* FromKeyword */) { + return parseImportEqualsDeclaration(node, identifier); + } + } + // Import statement + node.kind = 249 /* ImportDeclaration */; + // ImportDeclaration: + // import ImportClause from ModuleSpecifier ; + // import ModuleSpecifier; + if (identifier || // import id + token() === 40 /* AsteriskToken */ || // import * + token() === 18 /* OpenBraceToken */) { // import { + node.importClause = parseImportClause(identifier, afterImportPos); + parseExpected(144 /* FromKeyword */); + } + node.moduleSpecifier = parseModuleSpecifier(); + parseSemicolon(); + return finishNode(node); + } + function parseImportEqualsDeclaration(node, identifier) { + node.kind = 248 /* ImportEqualsDeclaration */; + node.name = identifier; + parseExpected(59 /* EqualsToken */); + node.moduleReference = parseModuleReference(); + parseSemicolon(); + return finishNode(node); + } + function parseImportClause(identifier, fullStart) { + // ImportClause: + // ImportedDefaultBinding + // NameSpaceImport + // NamedImports + // ImportedDefaultBinding, NameSpaceImport + // ImportedDefaultBinding, NamedImports + var importClause = createNode(250 /* ImportClause */, fullStart); + if (identifier) { + // ImportedDefaultBinding: + // ImportedBinding + importClause.name = identifier; + } + // If there was no default import or if there is comma token after default import + // parse namespace or named imports + if (!importClause.name || + parseOptional(27 /* CommaToken */)) { + importClause.namedBindings = token() === 40 /* AsteriskToken */ ? parseNamespaceImport() : parseNamedImportsOrExports(252 /* NamedImports */); + } + return finishNode(importClause); + } + function parseModuleReference() { + return isExternalModuleReference() + ? parseExternalModuleReference() + : parseEntityName(/*allowReservedWords*/ false); + } + function parseExternalModuleReference() { + var node = createNode(259 /* ExternalModuleReference */); + parseExpected(134 /* RequireKeyword */); + parseExpected(20 /* OpenParenToken */); + node.expression = parseModuleSpecifier(); + parseExpected(21 /* CloseParenToken */); + return finishNode(node); + } + function parseModuleSpecifier() { + if (token() === 10 /* StringLiteral */) { + var result = parseLiteralNode(); + result.text = internIdentifier(result.text); + return result; + } + else { + // We allow arbitrary expressions here, even though the grammar only allows string + // literals. We check to ensure that it is only a string literal later in the grammar + // check pass. + return parseExpression(); + } + } + function parseNamespaceImport() { + // NameSpaceImport: + // * as ImportedBinding + var namespaceImport = createNode(251 /* NamespaceImport */); + parseExpected(40 /* AsteriskToken */); + parseExpected(119 /* AsKeyword */); + namespaceImport.name = parseIdentifier(); + return finishNode(namespaceImport); + } + function parseNamedImportsOrExports(kind) { + var node = createNode(kind); + // NamedImports: + // { } + // { ImportsList } + // { ImportsList, } + // ImportsList: + // ImportSpecifier + // ImportsList, ImportSpecifier + node.elements = parseBracketedList(23 /* ImportOrExportSpecifiers */, kind === 252 /* NamedImports */ ? parseImportSpecifier : parseExportSpecifier, 18 /* OpenBraceToken */, 19 /* CloseBraceToken */); + return finishNode(node); + } + function parseExportSpecifier() { + return parseImportOrExportSpecifier(257 /* ExportSpecifier */); + } + function parseImportSpecifier() { + return parseImportOrExportSpecifier(253 /* ImportSpecifier */); + } + function parseImportOrExportSpecifier(kind) { + var node = createNode(kind); + // ImportSpecifier: + // BindingIdentifier + // IdentifierName as BindingIdentifier + // ExportSpecifier: + // IdentifierName + // IdentifierName as IdentifierName + var checkIdentifierIsKeyword = ts.isKeyword(token()) && !isIdentifier(); + var checkIdentifierStart = scanner.getTokenPos(); + var checkIdentifierEnd = scanner.getTextPos(); + var identifierName = parseIdentifierName(); + if (token() === 119 /* AsKeyword */) { + node.propertyName = identifierName; + parseExpected(119 /* AsKeyword */); + checkIdentifierIsKeyword = ts.isKeyword(token()) && !isIdentifier(); + checkIdentifierStart = scanner.getTokenPos(); + checkIdentifierEnd = scanner.getTextPos(); + node.name = parseIdentifierName(); + } + else { + node.name = identifierName; + } + if (kind === 253 /* ImportSpecifier */ && checkIdentifierIsKeyword) { + parseErrorAt(checkIdentifierStart, checkIdentifierEnd, ts.Diagnostics.Identifier_expected); + } + return finishNode(node); + } + function parseExportDeclaration(node) { + node.kind = 255 /* ExportDeclaration */; + if (parseOptional(40 /* AsteriskToken */)) { + parseExpected(144 /* FromKeyword */); + node.moduleSpecifier = parseModuleSpecifier(); + } + else { + node.exportClause = parseNamedImportsOrExports(256 /* NamedExports */); + // It is not uncommon to accidentally omit the 'from' keyword. Additionally, in editing scenarios, + // the 'from' keyword can be parsed as a named export when the export clause is unterminated (i.e. `export { from "moduleName";`) + // If we don't have a 'from' keyword, see if we have a string literal such that ASI won't take effect. + if (token() === 144 /* FromKeyword */ || (token() === 10 /* StringLiteral */ && !scanner.hasPrecedingLineBreak())) { + parseExpected(144 /* FromKeyword */); + node.moduleSpecifier = parseModuleSpecifier(); + } + } + parseSemicolon(); + return finishNode(node); + } + function parseExportAssignment(node) { + node.kind = 254 /* ExportAssignment */; + if (parseOptional(59 /* EqualsToken */)) { + node.isExportEquals = true; + } + else { + parseExpected(80 /* DefaultKeyword */); + } + node.expression = parseAssignmentExpressionOrHigher(); + parseSemicolon(); + return finishNode(node); + } + function setExternalModuleIndicator(sourceFile) { + // Try to use the first top-level import/export when available, then + // fall back to looking for an 'import.meta' somewhere in the tree if necessary. + sourceFile.externalModuleIndicator = + ts.forEach(sourceFile.statements, isAnExternalModuleIndicatorNode) || + getImportMetaIfNecessary(sourceFile); + } + function isAnExternalModuleIndicatorNode(node) { + return ts.hasModifier(node, 1 /* Export */) + || node.kind === 248 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 259 /* ExternalModuleReference */ + || node.kind === 249 /* ImportDeclaration */ + || node.kind === 254 /* ExportAssignment */ + || node.kind === 255 /* ExportDeclaration */ + ? node + : undefined; + } + function getImportMetaIfNecessary(sourceFile) { + return sourceFile.flags & 1048576 /* PossiblyContainsImportMeta */ ? + walkTreeForExternalModuleIndicators(sourceFile) : + undefined; + } + function walkTreeForExternalModuleIndicators(node) { + return isImportMeta(node) ? node : forEachChild(node, walkTreeForExternalModuleIndicators); + } + function isImportMeta(node) { + return ts.isMetaProperty(node) && node.keywordToken === 92 /* ImportKeyword */ && node.name.escapedText === "meta"; + } + var ParsingContext; + (function (ParsingContext) { + ParsingContext[ParsingContext["SourceElements"] = 0] = "SourceElements"; + ParsingContext[ParsingContext["BlockStatements"] = 1] = "BlockStatements"; + ParsingContext[ParsingContext["SwitchClauses"] = 2] = "SwitchClauses"; + ParsingContext[ParsingContext["SwitchClauseStatements"] = 3] = "SwitchClauseStatements"; + ParsingContext[ParsingContext["TypeMembers"] = 4] = "TypeMembers"; + ParsingContext[ParsingContext["ClassMembers"] = 5] = "ClassMembers"; + ParsingContext[ParsingContext["EnumMembers"] = 6] = "EnumMembers"; + ParsingContext[ParsingContext["HeritageClauseElement"] = 7] = "HeritageClauseElement"; + ParsingContext[ParsingContext["VariableDeclarations"] = 8] = "VariableDeclarations"; + ParsingContext[ParsingContext["ObjectBindingElements"] = 9] = "ObjectBindingElements"; + ParsingContext[ParsingContext["ArrayBindingElements"] = 10] = "ArrayBindingElements"; + ParsingContext[ParsingContext["ArgumentExpressions"] = 11] = "ArgumentExpressions"; + ParsingContext[ParsingContext["ObjectLiteralMembers"] = 12] = "ObjectLiteralMembers"; + ParsingContext[ParsingContext["JsxAttributes"] = 13] = "JsxAttributes"; + ParsingContext[ParsingContext["JsxChildren"] = 14] = "JsxChildren"; + ParsingContext[ParsingContext["ArrayLiteralMembers"] = 15] = "ArrayLiteralMembers"; + ParsingContext[ParsingContext["Parameters"] = 16] = "Parameters"; + ParsingContext[ParsingContext["JSDocParameters"] = 17] = "JSDocParameters"; + ParsingContext[ParsingContext["RestProperties"] = 18] = "RestProperties"; + ParsingContext[ParsingContext["TypeParameters"] = 19] = "TypeParameters"; + ParsingContext[ParsingContext["TypeArguments"] = 20] = "TypeArguments"; + ParsingContext[ParsingContext["TupleElementTypes"] = 21] = "TupleElementTypes"; + ParsingContext[ParsingContext["HeritageClauses"] = 22] = "HeritageClauses"; + ParsingContext[ParsingContext["ImportOrExportSpecifiers"] = 23] = "ImportOrExportSpecifiers"; + ParsingContext[ParsingContext["Count"] = 24] = "Count"; // Number of parsing contexts + })(ParsingContext || (ParsingContext = {})); + var Tristate; + (function (Tristate) { + Tristate[Tristate["False"] = 0] = "False"; + Tristate[Tristate["True"] = 1] = "True"; + Tristate[Tristate["Unknown"] = 2] = "Unknown"; + })(Tristate || (Tristate = {})); + var JSDocParser; + (function (JSDocParser) { + function parseJSDocTypeExpressionForTests(content, start, length) { + initializeState(content, 6 /* Latest */, /*_syntaxCursor:*/ undefined, 1 /* JS */); + sourceFile = createSourceFile("file.js", 6 /* Latest */, 1 /* JS */, /*isDeclarationFile*/ false); + scanner.setText(content, start, length); + currentToken = scanner.scan(); + var jsDocTypeExpression = parseJSDocTypeExpression(); + var diagnostics = parseDiagnostics; + clearState(); + return jsDocTypeExpression ? { jsDocTypeExpression: jsDocTypeExpression, diagnostics: diagnostics } : undefined; + } + JSDocParser.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests; + // Parses out a JSDoc type expression. + function parseJSDocTypeExpression(mayOmitBraces) { + var result = createNode(283 /* JSDocTypeExpression */); + var hasBrace = (mayOmitBraces ? parseOptional : parseExpected)(18 /* OpenBraceToken */); + result.type = doInsideOfContext(2097152 /* JSDoc */, parseJSDocType); + if (!mayOmitBraces || hasBrace) { + parseExpected(19 /* CloseBraceToken */); + } + fixupParentReferences(result); + return finishNode(result); + } + JSDocParser.parseJSDocTypeExpression = parseJSDocTypeExpression; + function parseIsolatedJSDocComment(content, start, length) { + initializeState(content, 6 /* Latest */, /*_syntaxCursor:*/ undefined, 1 /* JS */); + sourceFile = { languageVariant: 0 /* Standard */, text: content }; // tslint:disable-line no-object-literal-type-assertion + var jsDoc = parseJSDocCommentWorker(start, length); + var diagnostics = parseDiagnostics; + clearState(); + return jsDoc ? { jsDoc: jsDoc, diagnostics: diagnostics } : undefined; + } + JSDocParser.parseIsolatedJSDocComment = parseIsolatedJSDocComment; + function parseJSDocComment(parent, start, length) { + var _a; + var saveToken = currentToken; + var saveParseDiagnosticsLength = parseDiagnostics.length; + var saveParseErrorBeforeNextFinishedNode = parseErrorBeforeNextFinishedNode; + var comment = parseJSDocCommentWorker(start, length); + if (comment) { + comment.parent = parent; + } + if (contextFlags & 65536 /* JavaScriptFile */) { + if (!sourceFile.jsDocDiagnostics) { + sourceFile.jsDocDiagnostics = []; + } + (_a = sourceFile.jsDocDiagnostics).push.apply(_a, parseDiagnostics); + } + currentToken = saveToken; + parseDiagnostics.length = saveParseDiagnosticsLength; + parseErrorBeforeNextFinishedNode = saveParseErrorBeforeNextFinishedNode; + return comment; + } + JSDocParser.parseJSDocComment = parseJSDocComment; + var JSDocState; + (function (JSDocState) { + JSDocState[JSDocState["BeginningOfLine"] = 0] = "BeginningOfLine"; + JSDocState[JSDocState["SawAsterisk"] = 1] = "SawAsterisk"; + JSDocState[JSDocState["SavingComments"] = 2] = "SavingComments"; + })(JSDocState || (JSDocState = {})); + var PropertyLikeParse; + (function (PropertyLikeParse) { + PropertyLikeParse[PropertyLikeParse["Property"] = 1] = "Property"; + PropertyLikeParse[PropertyLikeParse["Parameter"] = 2] = "Parameter"; + PropertyLikeParse[PropertyLikeParse["CallbackParameter"] = 4] = "CallbackParameter"; + })(PropertyLikeParse || (PropertyLikeParse = {})); + function parseJSDocCommentWorker(start, length) { + if (start === void 0) { start = 0; } + var content = sourceText; + var end = length === undefined ? content.length : start + length; + length = end - start; + ts.Debug.assert(start >= 0); + ts.Debug.assert(start <= end); + ts.Debug.assert(end <= content.length); + // Check for /** (JSDoc opening part) + if (!isJSDocLikeText(content, start)) { + return undefined; + } + var tags; + var tagsPos; + var tagsEnd; + var comments = []; + // + 3 for leading /**, - 5 in total for /** */ + return scanner.scanRange(start + 3, length - 5, function () { + // Initially we can parse out a tag. We also have seen a starting asterisk. + // This is so that /** * @type */ doesn't parse. + var state = 1 /* SawAsterisk */; + var margin; + // + 4 for leading '/** ' + var indent = start - Math.max(content.lastIndexOf("\n", start), 0) + 4; + function pushComment(text) { + if (!margin) { + margin = indent; + } + comments.push(text); + indent += text.length; + } + nextJSDocToken(); + while (parseOptionalJsdoc(5 /* WhitespaceTrivia */)) + ; + if (parseOptionalJsdoc(4 /* NewLineTrivia */)) { + state = 0 /* BeginningOfLine */; + indent = 0; + } + loop: while (true) { + switch (token()) { + case 58 /* AtToken */: + if (state === 0 /* BeginningOfLine */ || state === 1 /* SawAsterisk */) { + removeTrailingWhitespace(comments); + addTag(parseTag(indent)); + // NOTE: According to usejsdoc.org, a tag goes to end of line, except the last tag. + // Real-world comments may break this rule, so "BeginningOfLine" will not be a real line beginning + // for malformed examples like `/** @param {string} x @returns {number} the length */` + state = 0 /* BeginningOfLine */; + margin = undefined; + indent++; + } + else { + pushComment(scanner.getTokenText()); + } + break; + case 4 /* NewLineTrivia */: + comments.push(scanner.getTokenText()); + state = 0 /* BeginningOfLine */; + indent = 0; + break; + case 40 /* AsteriskToken */: + var asterisk = scanner.getTokenText(); + if (state === 1 /* SawAsterisk */ || state === 2 /* SavingComments */) { + // If we've already seen an asterisk, then we can no longer parse a tag on this line + state = 2 /* SavingComments */; + pushComment(asterisk); + } + else { + // Ignore the first asterisk on a line + state = 1 /* SawAsterisk */; + indent += asterisk.length; + } + break; + case 5 /* WhitespaceTrivia */: + // only collect whitespace if we're already saving comments or have just crossed the comment indent margin + var whitespace = scanner.getTokenText(); + if (state === 2 /* SavingComments */) { + comments.push(whitespace); + } + else if (margin !== undefined && indent + whitespace.length > margin) { + comments.push(whitespace.slice(margin - indent - 1)); + } + indent += whitespace.length; + break; + case 1 /* EndOfFileToken */: + break loop; + default: + // Anything else is doc comment text. We just save it. Because it + // wasn't a tag, we can no longer parse a tag on this line until we hit the next + // line break. + state = 2 /* SavingComments */; + pushComment(scanner.getTokenText()); + break; + } + nextJSDocToken(); + } + removeLeadingNewlines(comments); + removeTrailingWhitespace(comments); + return createJSDocComment(); + }); + function removeLeadingNewlines(comments) { + while (comments.length && (comments[0] === "\n" || comments[0] === "\r")) { + comments.shift(); + } + } + function removeTrailingWhitespace(comments) { + while (comments.length && comments[comments.length - 1].trim() === "") { + comments.pop(); + } + } + function createJSDocComment() { + var result = createNode(291 /* JSDocComment */, start); + result.tags = tags && createNodeArray(tags, tagsPos, tagsEnd); + result.comment = comments.length ? comments.join("") : undefined; + return finishNode(result, end); + } + function isNextNonwhitespaceTokenEndOfFile() { + // We must use infinite lookahead, as there could be any number of newlines :( + while (true) { + nextJSDocToken(); + if (token() === 1 /* EndOfFileToken */) { + return true; + } + if (!(token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */)) { + return false; + } + } + } + function skipWhitespace() { + if (token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) { + if (lookAhead(isNextNonwhitespaceTokenEndOfFile)) { + return; // Don't skip whitespace prior to EoF (or end of comment) - that shouldn't be included in any node's range + } + } + while (token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) { + nextJSDocToken(); + } + } + function skipWhitespaceOrAsterisk() { + if (token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) { + if (lookAhead(isNextNonwhitespaceTokenEndOfFile)) { + return; // Don't skip whitespace prior to EoF (or end of comment) - that shouldn't be included in any node's range + } + } + var precedingLineBreak = scanner.hasPrecedingLineBreak(); + while ((precedingLineBreak && token() === 40 /* AsteriskToken */) || token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) { + if (token() === 4 /* NewLineTrivia */) { + precedingLineBreak = true; + } + else if (token() === 40 /* AsteriskToken */) { + precedingLineBreak = false; + } + nextJSDocToken(); + } + } + function parseTag(indent) { + ts.Debug.assert(token() === 58 /* AtToken */); + var start = scanner.getTokenPos(); + nextJSDocToken(); + var tagName = parseJSDocIdentifierName(/*message*/ undefined); + skipWhitespaceOrAsterisk(); + var tag; + switch (tagName.escapedText) { + case "augments": + case "extends": + tag = parseAugmentsTag(start, tagName); + break; + case "class": + case "constructor": + tag = parseClassTag(start, tagName); + break; + case "this": + tag = parseThisTag(start, tagName); + break; + case "enum": + tag = parseEnumTag(start, tagName); + break; + case "arg": + case "argument": + case "param": + return parseParameterOrPropertyTag(start, tagName, 2 /* Parameter */, indent); + case "return": + case "returns": + tag = parseReturnTag(start, tagName); + break; + case "template": + tag = parseTemplateTag(start, tagName); + break; + case "type": + tag = parseTypeTag(start, tagName); + break; + case "typedef": + tag = parseTypedefTag(start, tagName, indent); + break; + case "callback": + tag = parseCallbackTag(start, tagName, indent); + break; + default: + tag = parseUnknownTag(start, tagName); + break; + } + if (!tag.comment) { + // some tags, like typedef and callback, have already parsed their comments earlier + tag.comment = parseTagComments(indent + tag.end - tag.pos); + } + return tag; + } + function parseTagComments(indent) { + var comments = []; + var state = 0 /* BeginningOfLine */; + var margin; + function pushComment(text) { + if (!margin) { + margin = indent; + } + comments.push(text); + indent += text.length; + } + var tok = token(); + loop: while (true) { + switch (tok) { + case 4 /* NewLineTrivia */: + if (state >= 1 /* SawAsterisk */) { + state = 0 /* BeginningOfLine */; + comments.push(scanner.getTokenText()); + } + indent = 0; + break; + case 58 /* AtToken */: + scanner.setTextPos(scanner.getTextPos() - 1); + // falls through + case 1 /* EndOfFileToken */: + // Done + break loop; + case 5 /* WhitespaceTrivia */: + if (state === 2 /* SavingComments */) { + pushComment(scanner.getTokenText()); + } + else { + var whitespace = scanner.getTokenText(); + // if the whitespace crosses the margin, take only the whitespace that passes the margin + if (margin !== undefined && indent + whitespace.length > margin) { + comments.push(whitespace.slice(margin - indent - 1)); + } + indent += whitespace.length; + } + break; + case 18 /* OpenBraceToken */: + state = 2 /* SavingComments */; + if (lookAhead(function () { return nextJSDocToken() === 58 /* AtToken */ && ts.tokenIsIdentifierOrKeyword(nextJSDocToken()) && scanner.getTokenText() === "link"; })) { + pushComment(scanner.getTokenText()); + nextJSDocToken(); + pushComment(scanner.getTokenText()); + nextJSDocToken(); + } + pushComment(scanner.getTokenText()); + break; + case 40 /* AsteriskToken */: + if (state === 0 /* BeginningOfLine */) { + // leading asterisks start recording on the *next* (non-whitespace) token + state = 1 /* SawAsterisk */; + indent += 1; + break; + } + // record the * as a comment + // falls through + default: + state = 2 /* SavingComments */; // leading identifiers start recording as well + pushComment(scanner.getTokenText()); + break; + } + tok = nextJSDocToken(); + } + removeLeadingNewlines(comments); + removeTrailingWhitespace(comments); + return comments.length === 0 ? undefined : comments.join(""); + } + function parseUnknownTag(start, tagName) { + var result = createNode(294 /* JSDocTag */, start); + result.tagName = tagName; + return finishNode(result); + } + function addTag(tag) { + if (!tag) { + return; + } + if (!tags) { + tags = [tag]; + tagsPos = tag.pos; + } + else { + tags.push(tag); + } + tagsEnd = tag.end; + } + function tryParseTypeExpression() { + skipWhitespaceOrAsterisk(); + return token() === 18 /* OpenBraceToken */ ? parseJSDocTypeExpression() : undefined; + } + function parseBracketNameInPropertyAndParamTag() { + if (token() === 14 /* NoSubstitutionTemplateLiteral */) { + // a markdown-quoted name: `arg` is not legal jsdoc, but occurs in the wild + return { name: createIdentifier(/*isIdentifier*/ true), isBracketed: false }; + } + // Looking for something like '[foo]', 'foo', '[foo.bar]' or 'foo.bar' + var isBracketed = parseOptional(22 /* OpenBracketToken */); + var name = parseJSDocEntityName(); + if (isBracketed) { + skipWhitespace(); + // May have an optional default, e.g. '[foo = 42]' + if (parseOptionalToken(59 /* EqualsToken */)) { + parseExpression(); + } + parseExpected(23 /* CloseBracketToken */); + } + return { name: name, isBracketed: isBracketed }; + } + function isObjectOrObjectArrayTypeReference(node) { + switch (node.kind) { + case 136 /* ObjectKeyword */: + return true; + case 169 /* ArrayType */: + return isObjectOrObjectArrayTypeReference(node.elementType); + default: + return ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) && node.typeName.escapedText === "Object"; + } + } + function parseParameterOrPropertyTag(start, tagName, target, indent) { + var typeExpression = tryParseTypeExpression(); + var isNameFirst = !typeExpression; + skipWhitespaceOrAsterisk(); + var _a = parseBracketNameInPropertyAndParamTag(), name = _a.name, isBracketed = _a.isBracketed; + skipWhitespace(); + if (isNameFirst) { + typeExpression = tryParseTypeExpression(); + } + var result = target === 1 /* Property */ ? + createNode(305 /* JSDocPropertyTag */, start) : + createNode(299 /* JSDocParameterTag */, start); + var comment = parseTagComments(indent + scanner.getStartPos() - start); + var nestedTypeLiteral = target !== 4 /* CallbackParameter */ && parseNestedTypeLiteral(typeExpression, name, target, indent); + if (nestedTypeLiteral) { + typeExpression = nestedTypeLiteral; + isNameFirst = true; + } + result.tagName = tagName; + result.typeExpression = typeExpression; + result.name = name; + result.isNameFirst = isNameFirst; + result.isBracketed = isBracketed; + result.comment = comment; + return finishNode(result); + } + function parseNestedTypeLiteral(typeExpression, name, target, indent) { + if (typeExpression && isObjectOrObjectArrayTypeReference(typeExpression.type)) { + var typeLiteralExpression = createNode(283 /* JSDocTypeExpression */, scanner.getTokenPos()); + var child = void 0; + var jsdocTypeLiteral = void 0; + var start_2 = scanner.getStartPos(); + var children = void 0; + while (child = tryParse(function () { return parseChildParameterOrPropertyTag(target, indent, name); })) { + if (child.kind === 299 /* JSDocParameterTag */ || child.kind === 305 /* JSDocPropertyTag */) { + children = ts.append(children, child); + } + } + if (children) { + jsdocTypeLiteral = createNode(292 /* JSDocTypeLiteral */, start_2); + jsdocTypeLiteral.jsDocPropertyTags = children; + if (typeExpression.type.kind === 169 /* ArrayType */) { + jsdocTypeLiteral.isArrayType = true; + } + typeLiteralExpression.type = finishNode(jsdocTypeLiteral); + return finishNode(typeLiteralExpression); + } + } + } + function parseReturnTag(start, tagName) { + if (ts.forEach(tags, function (t) { return t.kind === 300 /* JSDocReturnTag */; })) { + parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText); + } + var result = createNode(300 /* JSDocReturnTag */, start); + result.tagName = tagName; + result.typeExpression = tryParseTypeExpression(); + return finishNode(result); + } + function parseTypeTag(start, tagName) { + if (ts.forEach(tags, function (t) { return t.kind === 302 /* JSDocTypeTag */; })) { + parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText); + } + var result = createNode(302 /* JSDocTypeTag */, start); + result.tagName = tagName; + result.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true); + return finishNode(result); + } + function parseAugmentsTag(start, tagName) { + var result = createNode(295 /* JSDocAugmentsTag */, start); + result.tagName = tagName; + result.class = parseExpressionWithTypeArgumentsForAugments(); + return finishNode(result); + } + function parseExpressionWithTypeArgumentsForAugments() { + var usedBrace = parseOptional(18 /* OpenBraceToken */); + var node = createNode(211 /* ExpressionWithTypeArguments */); + node.expression = parsePropertyAccessEntityNameExpression(); + node.typeArguments = tryParseTypeArguments(); + var res = finishNode(node); + if (usedBrace) { + parseExpected(19 /* CloseBraceToken */); + } + return res; + } + function parsePropertyAccessEntityNameExpression() { + var node = parseJSDocIdentifierName(); + while (parseOptional(24 /* DotToken */)) { + var prop = createNode(189 /* PropertyAccessExpression */, node.pos); + prop.expression = node; + prop.name = parseJSDocIdentifierName(); + node = finishNode(prop); + } + return node; + } + function parseClassTag(start, tagName) { + var tag = createNode(296 /* JSDocClassTag */, start); + tag.tagName = tagName; + return finishNode(tag); + } + function parseThisTag(start, tagName) { + var tag = createNode(301 /* JSDocThisTag */, start); + tag.tagName = tagName; + tag.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true); + skipWhitespace(); + return finishNode(tag); + } + function parseEnumTag(start, tagName) { + var tag = createNode(298 /* JSDocEnumTag */, start); + tag.tagName = tagName; + tag.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true); + skipWhitespace(); + return finishNode(tag); + } + function parseTypedefTag(start, tagName, indent) { + var typeExpression = tryParseTypeExpression(); + skipWhitespaceOrAsterisk(); + var typedefTag = createNode(304 /* JSDocTypedefTag */, start); + typedefTag.tagName = tagName; + typedefTag.fullName = parseJSDocTypeNameWithNamespace(); + typedefTag.name = getJSDocTypeAliasName(typedefTag.fullName); + skipWhitespace(); + typedefTag.comment = parseTagComments(indent); + typedefTag.typeExpression = typeExpression; + var end; + if (!typeExpression || isObjectOrObjectArrayTypeReference(typeExpression.type)) { + var child = void 0; + var jsdocTypeLiteral = void 0; + var childTypeTag = void 0; + while (child = tryParse(function () { return parseChildPropertyTag(indent); })) { + if (!jsdocTypeLiteral) { + jsdocTypeLiteral = createNode(292 /* JSDocTypeLiteral */, start); + } + if (child.kind === 302 /* JSDocTypeTag */) { + if (childTypeTag) { + break; + } + else { + childTypeTag = child; + } + } + else { + jsdocTypeLiteral.jsDocPropertyTags = ts.append(jsdocTypeLiteral.jsDocPropertyTags, child); + } + } + if (jsdocTypeLiteral) { + if (typeExpression && typeExpression.type.kind === 169 /* ArrayType */) { + jsdocTypeLiteral.isArrayType = true; + } + typedefTag.typeExpression = childTypeTag && childTypeTag.typeExpression && !isObjectOrObjectArrayTypeReference(childTypeTag.typeExpression.type) ? + childTypeTag.typeExpression : + finishNode(jsdocTypeLiteral); + end = typedefTag.typeExpression.end; + } + } + // Only include the characters between the name end and the next token if a comment was actually parsed out - otherwise it's just whitespace + return finishNode(typedefTag, end || typedefTag.comment !== undefined ? scanner.getStartPos() : (typedefTag.fullName || typedefTag.typeExpression || typedefTag.tagName).end); + } + function parseJSDocTypeNameWithNamespace(nested) { + var pos = scanner.getTokenPos(); + if (!ts.tokenIsIdentifierOrKeyword(token())) { + return undefined; + } + var typeNameOrNamespaceName = parseJSDocIdentifierName(); + if (parseOptional(24 /* DotToken */)) { + var jsDocNamespaceNode = createNode(244 /* ModuleDeclaration */, pos); + if (nested) { + jsDocNamespaceNode.flags |= 4 /* NestedNamespace */; + } + jsDocNamespaceNode.name = typeNameOrNamespaceName; + jsDocNamespaceNode.body = parseJSDocTypeNameWithNamespace(/*nested*/ true); + return finishNode(jsDocNamespaceNode); + } + if (nested) { + typeNameOrNamespaceName.isInJSDocNamespace = true; + } + return typeNameOrNamespaceName; + } + function parseCallbackTag(start, tagName, indent) { + var callbackTag = createNode(297 /* JSDocCallbackTag */, start); + callbackTag.tagName = tagName; + callbackTag.fullName = parseJSDocTypeNameWithNamespace(); + callbackTag.name = getJSDocTypeAliasName(callbackTag.fullName); + skipWhitespace(); + callbackTag.comment = parseTagComments(indent); + var child; + var jsdocSignature = createNode(293 /* JSDocSignature */, start); + jsdocSignature.parameters = []; + while (child = tryParse(function () { return parseChildParameterOrPropertyTag(4 /* CallbackParameter */, indent); })) { + jsdocSignature.parameters = ts.append(jsdocSignature.parameters, child); + } + var returnTag = tryParse(function () { + if (parseOptionalJsdoc(58 /* AtToken */)) { + var tag = parseTag(indent); + if (tag && tag.kind === 300 /* JSDocReturnTag */) { + return tag; + } + } + }); + if (returnTag) { + jsdocSignature.type = returnTag; + } + callbackTag.typeExpression = finishNode(jsdocSignature); + return finishNode(callbackTag); + } + function getJSDocTypeAliasName(fullName) { + if (fullName) { + var rightNode = fullName; + while (true) { + if (ts.isIdentifier(rightNode) || !rightNode.body) { + return ts.isIdentifier(rightNode) ? rightNode : rightNode.name; + } + rightNode = rightNode.body; + } + } + } + function escapedTextsEqual(a, b) { + while (!ts.isIdentifier(a) || !ts.isIdentifier(b)) { + if (!ts.isIdentifier(a) && !ts.isIdentifier(b) && a.right.escapedText === b.right.escapedText) { + a = a.left; + b = b.left; + } + else { + return false; + } + } + return a.escapedText === b.escapedText; + } + function parseChildPropertyTag(indent) { + return parseChildParameterOrPropertyTag(1 /* Property */, indent); + } + function parseChildParameterOrPropertyTag(target, indent, name) { + var canParseTag = true; + var seenAsterisk = false; + while (true) { + switch (nextJSDocToken()) { + case 58 /* AtToken */: + if (canParseTag) { + var child = tryParseChildTag(target, indent); + if (child && (child.kind === 299 /* JSDocParameterTag */ || child.kind === 305 /* JSDocPropertyTag */) && + target !== 4 /* CallbackParameter */ && + name && (ts.isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) { + return false; + } + return child; + } + seenAsterisk = false; + break; + case 4 /* NewLineTrivia */: + canParseTag = true; + seenAsterisk = false; + break; + case 40 /* AsteriskToken */: + if (seenAsterisk) { + canParseTag = false; + } + seenAsterisk = true; + break; + case 72 /* Identifier */: + canParseTag = false; + break; + case 1 /* EndOfFileToken */: + return false; + } + } + } + function tryParseChildTag(target, indent) { + ts.Debug.assert(token() === 58 /* AtToken */); + var start = scanner.getStartPos(); + nextJSDocToken(); + var tagName = parseJSDocIdentifierName(); + skipWhitespace(); + var t; + switch (tagName.escapedText) { + case "type": + return target === 1 /* Property */ && parseTypeTag(start, tagName); + case "prop": + case "property": + t = 1 /* Property */; + break; + case "arg": + case "argument": + case "param": + t = 2 /* Parameter */ | 4 /* CallbackParameter */; + break; + default: + return false; + } + if (!(target & t)) { + return false; + } + return parseParameterOrPropertyTag(start, tagName, target, indent); + } + function parseTemplateTag(start, tagName) { + // the template tag looks like '@template {Constraint} T,U,V' + var constraint; + if (token() === 18 /* OpenBraceToken */) { + constraint = parseJSDocTypeExpression(); + } + var typeParameters = []; + var typeParametersPos = getNodePos(); + do { + skipWhitespace(); + var typeParameter = createNode(150 /* TypeParameter */); + typeParameter.name = parseJSDocIdentifierName(ts.Diagnostics.Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces); + finishNode(typeParameter); + skipWhitespace(); + typeParameters.push(typeParameter); + } while (parseOptionalJsdoc(27 /* CommaToken */)); + var result = createNode(303 /* JSDocTemplateTag */, start); + result.tagName = tagName; + result.constraint = constraint; + result.typeParameters = createNodeArray(typeParameters, typeParametersPos); + finishNode(result); + return result; + } + function nextJSDocToken() { + return currentToken = scanner.scanJSDocToken(); + } + function parseOptionalJsdoc(t) { + if (token() === t) { + nextJSDocToken(); + return true; + } + return false; + } + function parseJSDocEntityName() { + var entity = parseJSDocIdentifierName(); + if (parseOptional(22 /* OpenBracketToken */)) { + parseExpected(23 /* CloseBracketToken */); + // Note that y[] is accepted as an entity name, but the postfix brackets are not saved for checking. + // Technically usejsdoc.org requires them for specifying a property of a type equivalent to Array<{ x: ...}> + // but it's not worth it to enforce that restriction. + } + while (parseOptional(24 /* DotToken */)) { + var name = parseJSDocIdentifierName(); + if (parseOptional(22 /* OpenBracketToken */)) { + parseExpected(23 /* CloseBracketToken */); + } + entity = createQualifiedName(entity, name); + } + return entity; + } + function parseJSDocIdentifierName(message) { + if (!ts.tokenIsIdentifierOrKeyword(token())) { + return createMissingNode(72 /* Identifier */, /*reportAtCurrentPosition*/ !message, message || ts.Diagnostics.Identifier_expected); + } + var pos = scanner.getTokenPos(); + var end = scanner.getTextPos(); + var result = createNode(72 /* Identifier */, pos); + result.escapedText = ts.escapeLeadingUnderscores(scanner.getTokenText()); + finishNode(result, end); + nextJSDocToken(); + return result; + } + } + JSDocParser.parseJSDocCommentWorker = parseJSDocCommentWorker; + })(JSDocParser = Parser.JSDocParser || (Parser.JSDocParser = {})); + })(Parser || (Parser = {})); + var IncrementalParser; + (function (IncrementalParser) { + function updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks) { + aggressiveChecks = aggressiveChecks || ts.Debug.shouldAssert(2 /* Aggressive */); + checkChangeRange(sourceFile, newText, textChangeRange, aggressiveChecks); + if (ts.textChangeRangeIsUnchanged(textChangeRange)) { + // if the text didn't change, then we can just return our current source file as-is. + return sourceFile; + } + if (sourceFile.statements.length === 0) { + // If we don't have any statements in the current source file, then there's no real + // way to incrementally parse. So just do a full parse instead. + return Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, /*syntaxCursor*/ undefined, /*setParentNodes*/ true, sourceFile.scriptKind); + } + // Make sure we're not trying to incrementally update a source file more than once. Once + // we do an update the original source file is considered unusable from that point onwards. + // + // This is because we do incremental parsing in-place. i.e. we take nodes from the old + // tree and give them new positions and parents. From that point on, trusting the old + // tree at all is not possible as far too much of it may violate invariants. + var incrementalSourceFile = sourceFile; + ts.Debug.assert(!incrementalSourceFile.hasBeenIncrementallyParsed); + incrementalSourceFile.hasBeenIncrementallyParsed = true; + var oldText = sourceFile.text; + var syntaxCursor = createSyntaxCursor(sourceFile); + // Make the actual change larger so that we know to reparse anything whose lookahead + // might have intersected the change. + var changeRange = extendToAffectedRange(sourceFile, textChangeRange); + checkChangeRange(sourceFile, newText, changeRange, aggressiveChecks); + // Ensure that extending the affected range only moved the start of the change range + // earlier in the file. + ts.Debug.assert(changeRange.span.start <= textChangeRange.span.start); + ts.Debug.assert(ts.textSpanEnd(changeRange.span) === ts.textSpanEnd(textChangeRange.span)); + ts.Debug.assert(ts.textSpanEnd(ts.textChangeRangeNewSpan(changeRange)) === ts.textSpanEnd(ts.textChangeRangeNewSpan(textChangeRange))); + // The is the amount the nodes after the edit range need to be adjusted. It can be + // positive (if the edit added characters), negative (if the edit deleted characters) + // or zero (if this was a pure overwrite with nothing added/removed). + var delta = ts.textChangeRangeNewSpan(changeRange).length - changeRange.span.length; + // If we added or removed characters during the edit, then we need to go and adjust all + // the nodes after the edit. Those nodes may move forward (if we inserted chars) or they + // may move backward (if we deleted chars). + // + // Doing this helps us out in two ways. First, it means that any nodes/tokens we want + // to reuse are already at the appropriate position in the new text. That way when we + // reuse them, we don't have to figure out if they need to be adjusted. Second, it makes + // it very easy to determine if we can reuse a node. If the node's position is at where + // we are in the text, then we can reuse it. Otherwise we can't. If the node's position + // is ahead of us, then we'll need to rescan tokens. If the node's position is behind + // us, then we'll need to skip it or crumble it as appropriate + // + // We will also adjust the positions of nodes that intersect the change range as well. + // By doing this, we ensure that all the positions in the old tree are consistent, not + // just the positions of nodes entirely before/after the change range. By being + // consistent, we can then easily map from positions to nodes in the old tree easily. + // + // Also, mark any syntax elements that intersect the changed span. We know, up front, + // that we cannot reuse these elements. + updateTokenPositionsAndMarkElements(incrementalSourceFile, changeRange.span.start, ts.textSpanEnd(changeRange.span), ts.textSpanEnd(ts.textChangeRangeNewSpan(changeRange)), delta, oldText, newText, aggressiveChecks); + // Now that we've set up our internal incremental state just proceed and parse the + // source file in the normal fashion. When possible the parser will retrieve and + // reuse nodes from the old tree. + // + // Note: passing in 'true' for setNodeParents is very important. When incrementally + // parsing, we will be reusing nodes from the old tree, and placing it into new + // parents. If we don't set the parents now, we'll end up with an observably + // inconsistent tree. Setting the parents on the new tree should be very fast. We + // will immediately bail out of walking any subtrees when we can see that their parents + // are already correct. + var result = Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, syntaxCursor, /*setParentNodes*/ true, sourceFile.scriptKind); + return result; + } + IncrementalParser.updateSourceFile = updateSourceFile; + function moveElementEntirelyPastChangeRange(element, isArray, delta, oldText, newText, aggressiveChecks) { + if (isArray) { + visitArray(element); + } + else { + visitNode(element); + } + return; + function visitNode(node) { + var text = ""; + if (aggressiveChecks && shouldCheckNode(node)) { + text = oldText.substring(node.pos, node.end); + } + // Ditch any existing LS children we may have created. This way we can avoid + // moving them forward. + if (node._children) { + node._children = undefined; + } + node.pos += delta; + node.end += delta; + if (aggressiveChecks && shouldCheckNode(node)) { + ts.Debug.assert(text === newText.substring(node.pos, node.end)); + } + forEachChild(node, visitNode, visitArray); + if (ts.hasJSDocNodes(node)) { + for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { + var jsDocComment = _a[_i]; + visitNode(jsDocComment); + } + } + checkNodePositions(node, aggressiveChecks); + } + function visitArray(array) { + array._children = undefined; + array.pos += delta; + array.end += delta; + for (var _i = 0, array_8 = array; _i < array_8.length; _i++) { + var node = array_8[_i]; + visitNode(node); + } + } + } + function shouldCheckNode(node) { + switch (node.kind) { + case 10 /* StringLiteral */: + case 8 /* NumericLiteral */: + case 72 /* Identifier */: + return true; + } + return false; + } + function adjustIntersectingElement(element, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta) { + ts.Debug.assert(element.end >= changeStart, "Adjusting an element that was entirely before the change range"); + ts.Debug.assert(element.pos <= changeRangeOldEnd, "Adjusting an element that was entirely after the change range"); + ts.Debug.assert(element.pos <= element.end); + // We have an element that intersects the change range in some way. It may have its + // start, or its end (or both) in the changed range. We want to adjust any part + // that intersects such that the final tree is in a consistent state. i.e. all + // children have spans within the span of their parent, and all siblings are ordered + // properly. + // We may need to update both the 'pos' and the 'end' of the element. + // If the 'pos' is before the start of the change, then we don't need to touch it. + // If it isn't, then the 'pos' must be inside the change. How we update it will + // depend if delta is positive or negative. If delta is positive then we have + // something like: + // + // -------------------AAA----------------- + // -------------------BBBCCCCCCC----------------- + // + // In this case, we consider any node that started in the change range to still be + // starting at the same position. + // + // however, if the delta is negative, then we instead have something like this: + // + // -------------------XXXYYYYYYY----------------- + // -------------------ZZZ----------------- + // + // In this case, any element that started in the 'X' range will keep its position. + // However any element that started after that will have their pos adjusted to be + // at the end of the new range. i.e. any node that started in the 'Y' range will + // be adjusted to have their start at the end of the 'Z' range. + // + // The element will keep its position if possible. Or Move backward to the new-end + // if it's in the 'Y' range. + element.pos = Math.min(element.pos, changeRangeNewEnd); + // If the 'end' is after the change range, then we always adjust it by the delta + // amount. However, if the end is in the change range, then how we adjust it + // will depend on if delta is positive or negative. If delta is positive then we + // have something like: + // + // -------------------AAA----------------- + // -------------------BBBCCCCCCC----------------- + // + // In this case, we consider any node that ended inside the change range to keep its + // end position. + // + // however, if the delta is negative, then we instead have something like this: + // + // -------------------XXXYYYYYYY----------------- + // -------------------ZZZ----------------- + // + // In this case, any element that ended in the 'X' range will keep its position. + // However any element that ended after that will have their pos adjusted to be + // at the end of the new range. i.e. any node that ended in the 'Y' range will + // be adjusted to have their end at the end of the 'Z' range. + if (element.end >= changeRangeOldEnd) { + // Element ends after the change range. Always adjust the end pos. + element.end += delta; + } + else { + // Element ends in the change range. The element will keep its position if + // possible. Or Move backward to the new-end if it's in the 'Y' range. + element.end = Math.min(element.end, changeRangeNewEnd); + } + ts.Debug.assert(element.pos <= element.end); + if (element.parent) { + ts.Debug.assert(element.pos >= element.parent.pos); + ts.Debug.assert(element.end <= element.parent.end); + } + } + function checkNodePositions(node, aggressiveChecks) { + if (aggressiveChecks) { + var pos_2 = node.pos; + var visitNode_1 = function (child) { + ts.Debug.assert(child.pos >= pos_2); + pos_2 = child.end; + }; + if (ts.hasJSDocNodes(node)) { + for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { + var jsDocComment = _a[_i]; + visitNode_1(jsDocComment); + } + } + forEachChild(node, visitNode_1); + ts.Debug.assert(pos_2 <= node.end); + } + } + function updateTokenPositionsAndMarkElements(sourceFile, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta, oldText, newText, aggressiveChecks) { + visitNode(sourceFile); + return; + function visitNode(child) { + ts.Debug.assert(child.pos <= child.end); + if (child.pos > changeRangeOldEnd) { + // Node is entirely past the change range. We need to move both its pos and + // end, forward or backward appropriately. + moveElementEntirelyPastChangeRange(child, /*isArray*/ false, delta, oldText, newText, aggressiveChecks); + return; + } + // Check if the element intersects the change range. If it does, then it is not + // reusable. Also, we'll need to recurse to see what constituent portions we may + // be able to use. + var fullEnd = child.end; + if (fullEnd >= changeStart) { + child.intersectsChange = true; + child._children = undefined; + // Adjust the pos or end (or both) of the intersecting element accordingly. + adjustIntersectingElement(child, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta); + forEachChild(child, visitNode, visitArray); + if (ts.hasJSDocNodes(child)) { + for (var _i = 0, _a = child.jsDoc; _i < _a.length; _i++) { + var jsDocComment = _a[_i]; + visitNode(jsDocComment); + } + } + checkNodePositions(child, aggressiveChecks); + return; + } + // Otherwise, the node is entirely before the change range. No need to do anything with it. + ts.Debug.assert(fullEnd < changeStart); + } + function visitArray(array) { + ts.Debug.assert(array.pos <= array.end); + if (array.pos > changeRangeOldEnd) { + // Array is entirely after the change range. We need to move it, and move any of + // its children. + moveElementEntirelyPastChangeRange(array, /*isArray*/ true, delta, oldText, newText, aggressiveChecks); + return; + } + // Check if the element intersects the change range. If it does, then it is not + // reusable. Also, we'll need to recurse to see what constituent portions we may + // be able to use. + var fullEnd = array.end; + if (fullEnd >= changeStart) { + array.intersectsChange = true; + array._children = undefined; + // Adjust the pos or end (or both) of the intersecting array accordingly. + adjustIntersectingElement(array, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta); + for (var _i = 0, array_9 = array; _i < array_9.length; _i++) { + var node = array_9[_i]; + visitNode(node); + } + return; + } + // Otherwise, the array is entirely before the change range. No need to do anything with it. + ts.Debug.assert(fullEnd < changeStart); + } + } + function extendToAffectedRange(sourceFile, changeRange) { + // Consider the following code: + // void foo() { /; } + // + // If the text changes with an insertion of / just before the semicolon then we end up with: + // void foo() { //; } + // + // If we were to just use the changeRange a is, then we would not rescan the { token + // (as it does not intersect the actual original change range). Because an edit may + // change the token touching it, we actually need to look back *at least* one token so + // that the prior token sees that change. + var maxLookahead = 1; + var start = changeRange.span.start; + // the first iteration aligns us with the change start. subsequent iteration move us to + // the left by maxLookahead tokens. We only need to do this as long as we're not at the + // start of the tree. + for (var i = 0; start > 0 && i <= maxLookahead; i++) { + var nearestNode = findNearestNodeStartingBeforeOrAtPosition(sourceFile, start); + ts.Debug.assert(nearestNode.pos <= start); + var position = nearestNode.pos; + start = Math.max(0, position - 1); + } + var finalSpan = ts.createTextSpanFromBounds(start, ts.textSpanEnd(changeRange.span)); + var finalLength = changeRange.newLength + (changeRange.span.start - start); + return ts.createTextChangeRange(finalSpan, finalLength); + } + function findNearestNodeStartingBeforeOrAtPosition(sourceFile, position) { + var bestResult = sourceFile; + var lastNodeEntirelyBeforePosition; + forEachChild(sourceFile, visit); + if (lastNodeEntirelyBeforePosition) { + var lastChildOfLastEntireNodeBeforePosition = getLastDescendant(lastNodeEntirelyBeforePosition); + if (lastChildOfLastEntireNodeBeforePosition.pos > bestResult.pos) { + bestResult = lastChildOfLastEntireNodeBeforePosition; + } + } + return bestResult; + function getLastDescendant(node) { + while (true) { + var lastChild = ts.getLastChild(node); + if (lastChild) { + node = lastChild; + } + else { + return node; + } + } + } + function visit(child) { + if (ts.nodeIsMissing(child)) { + // Missing nodes are effectively invisible to us. We never even consider them + // When trying to find the nearest node before us. + return; + } + // If the child intersects this position, then this node is currently the nearest + // node that starts before the position. + if (child.pos <= position) { + if (child.pos >= bestResult.pos) { + // This node starts before the position, and is closer to the position than + // the previous best node we found. It is now the new best node. + bestResult = child; + } + // Now, the node may overlap the position, or it may end entirely before the + // position. If it overlaps with the position, then either it, or one of its + // children must be the nearest node before the position. So we can just + // recurse into this child to see if we can find something better. + if (position < child.end) { + // The nearest node is either this child, or one of the children inside + // of it. We've already marked this child as the best so far. Recurse + // in case one of the children is better. + forEachChild(child, visit); + // Once we look at the children of this node, then there's no need to + // continue any further. + return true; + } + else { + ts.Debug.assert(child.end <= position); + // The child ends entirely before this position. Say you have the following + // (where $ is the position) + // + // ? $ : <...> <...> + // + // We would want to find the nearest preceding node in "complex expr 2". + // To support that, we keep track of this node, and once we're done searching + // for a best node, we recurse down this node to see if we can find a good + // result in it. + // + // This approach allows us to quickly skip over nodes that are entirely + // before the position, while still allowing us to find any nodes in the + // last one that might be what we want. + lastNodeEntirelyBeforePosition = child; + } + } + else { + ts.Debug.assert(child.pos > position); + // We're now at a node that is entirely past the position we're searching for. + // This node (and all following nodes) could never contribute to the result, + // so just skip them by returning 'true' here. + return true; + } + } + } + function checkChangeRange(sourceFile, newText, textChangeRange, aggressiveChecks) { + var oldText = sourceFile.text; + if (textChangeRange) { + ts.Debug.assert((oldText.length - textChangeRange.span.length + textChangeRange.newLength) === newText.length); + if (aggressiveChecks || ts.Debug.shouldAssert(3 /* VeryAggressive */)) { + var oldTextPrefix = oldText.substr(0, textChangeRange.span.start); + var newTextPrefix = newText.substr(0, textChangeRange.span.start); + ts.Debug.assert(oldTextPrefix === newTextPrefix); + var oldTextSuffix = oldText.substring(ts.textSpanEnd(textChangeRange.span), oldText.length); + var newTextSuffix = newText.substring(ts.textSpanEnd(ts.textChangeRangeNewSpan(textChangeRange)), newText.length); + ts.Debug.assert(oldTextSuffix === newTextSuffix); + } + } + } + function createSyntaxCursor(sourceFile) { + var currentArray = sourceFile.statements; + var currentArrayIndex = 0; + ts.Debug.assert(currentArrayIndex < currentArray.length); + var current = currentArray[currentArrayIndex]; + var lastQueriedPosition = -1 /* Value */; + return { + currentNode: function (position) { + // Only compute the current node if the position is different than the last time + // we were asked. The parser commonly asks for the node at the same position + // twice. Once to know if can read an appropriate list element at a certain point, + // and then to actually read and consume the node. + if (position !== lastQueriedPosition) { + // Much of the time the parser will need the very next node in the array that + // we just returned a node from.So just simply check for that case and move + // forward in the array instead of searching for the node again. + if (current && current.end === position && currentArrayIndex < (currentArray.length - 1)) { + currentArrayIndex++; + current = currentArray[currentArrayIndex]; + } + // If we don't have a node, or the node we have isn't in the right position, + // then try to find a viable node at the position requested. + if (!current || current.pos !== position) { + findHighestListElementThatStartsAtPosition(position); + } + } + // Cache this query so that we don't do any extra work if the parser calls back + // into us. Note: this is very common as the parser will make pairs of calls like + // 'isListElement -> parseListElement'. If we were unable to find a node when + // called with 'isListElement', we don't want to redo the work when parseListElement + // is called immediately after. + lastQueriedPosition = position; + // Either we don'd have a node, or we have a node at the position being asked for. + ts.Debug.assert(!current || current.pos === position); + return current; + } + }; + // Finds the highest element in the tree we can find that starts at the provided position. + // The element must be a direct child of some node list in the tree. This way after we + // return it, we can easily return its next sibling in the list. + function findHighestListElementThatStartsAtPosition(position) { + // Clear out any cached state about the last node we found. + currentArray = undefined; + currentArrayIndex = -1 /* Value */; + current = undefined; + // Recurse into the source file to find the highest node at this position. + forEachChild(sourceFile, visitNode, visitArray); + return; + function visitNode(node) { + if (position >= node.pos && position < node.end) { + // Position was within this node. Keep searching deeper to find the node. + forEachChild(node, visitNode, visitArray); + // don't proceed any further in the search. + return true; + } + // position wasn't in this node, have to keep searching. + return false; + } + function visitArray(array) { + if (position >= array.pos && position < array.end) { + // position was in this array. Search through this array to see if we find a + // viable element. + for (var i = 0; i < array.length; i++) { + var child = array[i]; + if (child) { + if (child.pos === position) { + // Found the right node. We're done. + currentArray = array; + currentArrayIndex = i; + current = child; + return true; + } + else { + if (child.pos < position && position < child.end) { + // Position in somewhere within this child. Search in it and + // stop searching in this array. + forEachChild(child, visitNode, visitArray); + return true; + } + } + } + } + } + // position wasn't in this array, have to keep searching. + return false; + } + } + } + var InvalidPosition; + (function (InvalidPosition) { + InvalidPosition[InvalidPosition["Value"] = -1] = "Value"; + })(InvalidPosition || (InvalidPosition = {})); + })(IncrementalParser || (IncrementalParser = {})); + /** @internal */ + function isDeclarationFileName(fileName) { + return ts.fileExtensionIs(fileName, ".d.ts" /* Dts */); + } + ts.isDeclarationFileName = isDeclarationFileName; + /*@internal*/ + function processCommentPragmas(context, sourceText) { + var triviaScanner = ts.createScanner(context.languageVersion, /*skipTrivia*/ false, 0 /* Standard */, sourceText); + var pragmas = []; + // Keep scanning all the leading trivia in the file until we get to something that + // isn't trivia. Any single line comment will be analyzed to see if it is a + // reference comment. + while (true) { + var kind = triviaScanner.scan(); + if (!ts.isTrivia(kind)) { + break; + } + var range = { + kind: triviaScanner.getToken(), + pos: triviaScanner.getTokenPos(), + end: triviaScanner.getTextPos(), + }; + var comment = sourceText.substring(range.pos, range.end); + extractPragmas(pragmas, range, comment); + } + context.pragmas = ts.createMap(); + for (var _i = 0, pragmas_1 = pragmas; _i < pragmas_1.length; _i++) { + var pragma = pragmas_1[_i]; + if (context.pragmas.has(pragma.name)) { // TODO: GH#18217 + var currentValue = context.pragmas.get(pragma.name); + if (currentValue instanceof Array) { + currentValue.push(pragma.args); + } + else { + context.pragmas.set(pragma.name, [currentValue, pragma.args]); + } + continue; + } + context.pragmas.set(pragma.name, pragma.args); + } + } + ts.processCommentPragmas = processCommentPragmas; + /*@internal*/ + function processPragmasIntoFields(context, reportDiagnostic) { + context.checkJsDirective = undefined; + context.referencedFiles = []; + context.typeReferenceDirectives = []; + context.libReferenceDirectives = []; + context.amdDependencies = []; + context.hasNoDefaultLib = false; + context.pragmas.forEach(function (entryOrList, key) { + // TODO: The below should be strongly type-guarded and not need casts/explicit annotations, since entryOrList is related to + // key and key is constrained to a union; but it's not (see GH#21483 for at least partial fix) :( + switch (key) { + case "reference": { + var referencedFiles_1 = context.referencedFiles; + var typeReferenceDirectives_1 = context.typeReferenceDirectives; + var libReferenceDirectives_1 = context.libReferenceDirectives; + ts.forEach(ts.toArray(entryOrList), function (arg) { + // TODO: GH#18217 + if (arg.arguments["no-default-lib"]) { + context.hasNoDefaultLib = true; + } + else if (arg.arguments.types) { + typeReferenceDirectives_1.push({ pos: arg.arguments.types.pos, end: arg.arguments.types.end, fileName: arg.arguments.types.value }); + } + else if (arg.arguments.lib) { + libReferenceDirectives_1.push({ pos: arg.arguments.lib.pos, end: arg.arguments.lib.end, fileName: arg.arguments.lib.value }); + } + else if (arg.arguments.path) { + referencedFiles_1.push({ pos: arg.arguments.path.pos, end: arg.arguments.path.end, fileName: arg.arguments.path.value }); + } + else { + reportDiagnostic(arg.range.pos, arg.range.end - arg.range.pos, ts.Diagnostics.Invalid_reference_directive_syntax); + } + }); + break; + } + case "amd-dependency": { + context.amdDependencies = ts.map(ts.toArray(entryOrList), function (x) { return ({ name: x.arguments.name, path: x.arguments.path }); }); // TODO: GH#18217 + break; + } + case "amd-module": { + if (entryOrList instanceof Array) { + for (var _i = 0, entryOrList_1 = entryOrList; _i < entryOrList_1.length; _i++) { + var entry = entryOrList_1[_i]; + if (context.moduleName) { + // TODO: It's probably fine to issue this diagnostic on all instances of the pragma + reportDiagnostic(entry.range.pos, entry.range.end - entry.range.pos, ts.Diagnostics.An_AMD_module_cannot_have_multiple_name_assignments); + } + context.moduleName = entry.arguments.name; + } + } + else { + context.moduleName = entryOrList.arguments.name; + } + break; + } + case "ts-nocheck": + case "ts-check": { + // _last_ of either nocheck or check in a file is the "winner" + ts.forEach(ts.toArray(entryOrList), function (entry) { + if (!context.checkJsDirective || entry.range.pos > context.checkJsDirective.pos) { // TODO: GH#18217 + context.checkJsDirective = { + enabled: key === "ts-check", + end: entry.range.end, + pos: entry.range.pos + }; + } + }); + break; + } + case "jsx": return; // Accessed directly + default: ts.Debug.fail("Unhandled pragma kind"); // Can this be made into an assertNever in the future? + } + }); + } + ts.processPragmasIntoFields = processPragmasIntoFields; + var namedArgRegExCache = ts.createMap(); + function getNamedArgRegEx(name) { + if (namedArgRegExCache.has(name)) { + return namedArgRegExCache.get(name); + } + var result = new RegExp("(\\s" + name + "\\s*=\\s*)('|\")(.+?)\\2", "im"); + namedArgRegExCache.set(name, result); + return result; + } + var tripleSlashXMLCommentStartRegEx = /^\/\/\/\s*<(\S+)\s.*?\/>/im; + var singleLinePragmaRegEx = /^\/\/\/?\s*@(\S+)\s*(.*)\s*$/im; + function extractPragmas(pragmas, range, text) { + var tripleSlash = range.kind === 2 /* SingleLineCommentTrivia */ && tripleSlashXMLCommentStartRegEx.exec(text); + if (tripleSlash) { + var name = tripleSlash[1].toLowerCase(); // Technically unsafe cast, but we do it so the below check to make it safe typechecks + var pragma = ts.commentPragmas[name]; + if (!pragma || !(pragma.kind & 1 /* TripleSlashXML */)) { + return; + } + if (pragma.args) { + var argument = {}; + for (var _i = 0, _a = pragma.args; _i < _a.length; _i++) { + var arg = _a[_i]; + var matcher = getNamedArgRegEx(arg.name); + var matchResult = matcher.exec(text); + if (!matchResult && !arg.optional) { + return; // Missing required argument, don't parse + } + else if (matchResult) { + if (arg.captureSpan) { + var startPos = range.pos + matchResult.index + matchResult[1].length + matchResult[2].length; + argument[arg.name] = { + value: matchResult[3], + pos: startPos, + end: startPos + matchResult[3].length + }; + } + else { + argument[arg.name] = matchResult[3]; + } + } + } + pragmas.push({ name: name, args: { arguments: argument, range: range } }); + } + else { + pragmas.push({ name: name, args: { arguments: {}, range: range } }); + } + return; + } + var singleLine = range.kind === 2 /* SingleLineCommentTrivia */ && singleLinePragmaRegEx.exec(text); + if (singleLine) { + return addPragmaForMatch(pragmas, range, 2 /* SingleLine */, singleLine); + } + if (range.kind === 3 /* MultiLineCommentTrivia */) { + var multiLinePragmaRegEx = /\s*@(\S+)\s*(.*)\s*$/gim; // Defined inline since it uses the "g" flag, which keeps a persistent index (for iterating) + var multiLineMatch = void 0; + while (multiLineMatch = multiLinePragmaRegEx.exec(text)) { + addPragmaForMatch(pragmas, range, 4 /* MultiLine */, multiLineMatch); + } + } + } + function addPragmaForMatch(pragmas, range, kind, match) { + if (!match) + return; + var name = match[1].toLowerCase(); // Technically unsafe cast, but we do it so they below check to make it safe typechecks + var pragma = ts.commentPragmas[name]; + if (!pragma || !(pragma.kind & kind)) { + return; + } + var args = match[2]; // Split on spaces and match up positionally with definition + var argument = getNamedPragmaArguments(pragma, args); + if (argument === "fail") + return; // Missing required argument, fail to parse it + pragmas.push({ name: name, args: { arguments: argument, range: range } }); + return; + } + function getNamedPragmaArguments(pragma, text) { + if (!text) + return {}; + if (!pragma.args) + return {}; + var args = text.split(/\s+/); + var argMap = {}; + for (var i = 0; i < pragma.args.length; i++) { + var argument = pragma.args[i]; + if (!args[i] && !argument.optional) { + return "fail"; + } + if (argument.captureSpan) { + return ts.Debug.fail("Capture spans not yet implemented for non-xml pragmas"); + } + argMap[argument.name] = args[i]; + } + return argMap; + } + /** @internal */ + function tagNamesAreEquivalent(lhs, rhs) { + if (lhs.kind !== rhs.kind) { + return false; + } + if (lhs.kind === 72 /* Identifier */) { + return lhs.escapedText === rhs.escapedText; + } + if (lhs.kind === 100 /* ThisKeyword */) { + return true; + } + // If we are at this statement then we must have PropertyAccessExpression and because tag name in Jsx element can only + // take forms of JsxTagNameExpression which includes an identifier, "this" expression, or another propertyAccessExpression + // it is safe to case the expression property as such. See parseJsxElementName for how we parse tag name in Jsx element + return lhs.name.escapedText === rhs.name.escapedText && + tagNamesAreEquivalent(lhs.expression, rhs.expression); + } + ts.tagNamesAreEquivalent = tagNamesAreEquivalent; +})(ts || (ts = {})); +var ts; +(function (ts) { + /* @internal */ + ts.compileOnSaveCommandLineOption = { name: "compileOnSave", type: "boolean" }; + // NOTE: The order here is important to default lib ordering as entries will have the same + // order in the generated program (see `getDefaultLibPriority` in program.ts). This + // order also affects overload resolution when a type declared in one lib is + // augmented in another lib. + var libEntries = [ + // JavaScript only + ["es5", "lib.es5.d.ts"], + ["es6", "lib.es2015.d.ts"], + ["es2015", "lib.es2015.d.ts"], + ["es7", "lib.es2016.d.ts"], + ["es2016", "lib.es2016.d.ts"], + ["es2017", "lib.es2017.d.ts"], + ["es2018", "lib.es2018.d.ts"], + ["esnext", "lib.esnext.d.ts"], + // Host only + ["dom", "lib.dom.d.ts"], + ["dom.iterable", "lib.dom.iterable.d.ts"], + ["webworker", "lib.webworker.d.ts"], + ["webworker.importscripts", "lib.webworker.importscripts.d.ts"], + ["scripthost", "lib.scripthost.d.ts"], + // ES2015 Or ESNext By-feature options + ["es2015.core", "lib.es2015.core.d.ts"], + ["es2015.collection", "lib.es2015.collection.d.ts"], + ["es2015.generator", "lib.es2015.generator.d.ts"], + ["es2015.iterable", "lib.es2015.iterable.d.ts"], + ["es2015.promise", "lib.es2015.promise.d.ts"], + ["es2015.proxy", "lib.es2015.proxy.d.ts"], + ["es2015.reflect", "lib.es2015.reflect.d.ts"], + ["es2015.symbol", "lib.es2015.symbol.d.ts"], + ["es2015.symbol.wellknown", "lib.es2015.symbol.wellknown.d.ts"], + ["es2016.array.include", "lib.es2016.array.include.d.ts"], + ["es2017.object", "lib.es2017.object.d.ts"], + ["es2017.sharedmemory", "lib.es2017.sharedmemory.d.ts"], + ["es2017.string", "lib.es2017.string.d.ts"], + ["es2017.intl", "lib.es2017.intl.d.ts"], + ["es2017.typedarrays", "lib.es2017.typedarrays.d.ts"], + ["es2018.intl", "lib.es2018.intl.d.ts"], + ["es2018.promise", "lib.es2018.promise.d.ts"], + ["es2018.regexp", "lib.es2018.regexp.d.ts"], + ["esnext.array", "lib.esnext.array.d.ts"], + ["esnext.symbol", "lib.esnext.symbol.d.ts"], + ["esnext.asynciterable", "lib.esnext.asynciterable.d.ts"], + ["esnext.intl", "lib.esnext.intl.d.ts"], + ["esnext.bigint", "lib.esnext.bigint.d.ts"] + ]; + /** + * An array of supported "lib" reference file names used to determine the order for inclusion + * when referenced, as well as for spelling suggestions. This ensures the correct ordering for + * overload resolution when a type declared in one lib is extended by another. + */ + /* @internal */ + ts.libs = libEntries.map(function (entry) { return entry[0]; }); + /** + * A map of lib names to lib files. This map is used both for parsing the "lib" command line + * option as well as for resolving lib reference directives. + */ + /* @internal */ + ts.libMap = ts.createMapFromEntries(libEntries); + /* @internal */ + ts.commonOptionsWithBuild = [ + { + name: "help", + shortName: "h", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Print_this_message, + }, + { + name: "help", + shortName: "?", + type: "boolean" + }, + { + name: "watch", + shortName: "w", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Watch_input_files, + }, + { + name: "preserveWatchOutput", + type: "boolean", + showInSimplifiedHelpView: false, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen, + }, + { + name: "listFiles", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Print_names_of_files_part_of_the_compilation + }, + { + name: "listEmittedFiles", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Print_names_of_generated_files_part_of_the_compilation + }, + { + name: "pretty", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Stylize_errors_and_messages_using_color_and_context_experimental + }, + { + name: "traceResolution", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Enable_tracing_of_the_name_resolution_process + }, + { + name: "diagnostics", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Show_diagnostic_information + }, + { + name: "extendedDiagnostics", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Show_verbose_diagnostic_information + }, + ]; + /* @internal */ + ts.optionDeclarations = ts.commonOptionsWithBuild.concat([ + { + name: "all", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Show_all_compiler_options, + }, + { + name: "version", + shortName: "v", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Print_the_compiler_s_version, + }, + { + name: "init", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file, + }, + { + name: "project", + shortName: "p", + type: "string", + isFilePath: true, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Command_line_Options, + paramType: ts.Diagnostics.FILE_OR_DIRECTORY, + description: ts.Diagnostics.Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json, + }, + { + name: "build", + type: "boolean", + shortName: "b", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Build_one_or_more_projects_and_their_dependencies_if_out_of_date + }, + { + name: "showConfig", + type: "boolean", + category: ts.Diagnostics.Command_line_Options, + isCommandLineOnly: true, + description: ts.Diagnostics.Print_the_final_configuration_instead_of_building + }, + // Basic + { + name: "target", + shortName: "t", + type: ts.createMapFromTemplate({ + es3: 0 /* ES3 */, + es5: 1 /* ES5 */, + es6: 2 /* ES2015 */, + es2015: 2 /* ES2015 */, + es2016: 3 /* ES2016 */, + es2017: 4 /* ES2017 */, + es2018: 5 /* ES2018 */, + esnext: 6 /* ESNext */, + }), + affectsSourceFile: true, + affectsModuleResolution: true, + paramType: ts.Diagnostics.VERSION, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_or_ESNEXT, + }, + { + name: "module", + shortName: "m", + type: ts.createMapFromTemplate({ + none: ts.ModuleKind.None, + commonjs: ts.ModuleKind.CommonJS, + amd: ts.ModuleKind.AMD, + system: ts.ModuleKind.System, + umd: ts.ModuleKind.UMD, + es6: ts.ModuleKind.ES2015, + es2015: ts.ModuleKind.ES2015, + esnext: ts.ModuleKind.ESNext + }), + affectsModuleResolution: true, + paramType: ts.Diagnostics.KIND, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext, + }, + { + name: "lib", + type: "list", + element: { + name: "lib", + type: ts.libMap + }, + affectsModuleResolution: true, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Specify_library_files_to_be_included_in_the_compilation + }, + { + name: "allowJs", + type: "boolean", + affectsModuleResolution: true, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Allow_javascript_files_to_be_compiled + }, + { + name: "checkJs", + type: "boolean", + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Report_errors_in_js_files + }, + { + name: "jsx", + type: ts.createMapFromTemplate({ + "preserve": 1 /* Preserve */, + "react-native": 3 /* ReactNative */, + "react": 2 /* React */ + }), + affectsSourceFile: true, + paramType: ts.Diagnostics.KIND, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Specify_JSX_code_generation_Colon_preserve_react_native_or_react, + }, + { + name: "declaration", + shortName: "d", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Generates_corresponding_d_ts_file, + }, + { + name: "declarationMap", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Generates_a_sourcemap_for_each_corresponding_d_ts_file, + }, + { + name: "emitDeclarationOnly", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Only_emit_d_ts_declaration_files, + }, + { + name: "sourceMap", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Generates_corresponding_map_file, + }, + { + name: "outFile", + type: "string", + isFilePath: true, + paramType: ts.Diagnostics.FILE, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Concatenate_and_emit_output_to_single_file, + }, + { + name: "outDir", + type: "string", + isFilePath: true, + paramType: ts.Diagnostics.DIRECTORY, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Redirect_output_structure_to_the_directory, + }, + { + name: "rootDir", + type: "string", + isFilePath: true, + paramType: ts.Diagnostics.LOCATION, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir, + }, + { + name: "composite", + type: "boolean", + isTSConfigOnly: true, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Enable_project_compilation, + }, + { + name: "removeComments", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Do_not_emit_comments_to_output, + }, + { + name: "noEmit", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Do_not_emit_outputs, + }, + { + name: "importHelpers", + type: "boolean", + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Import_emit_helpers_from_tslib + }, + { + name: "downlevelIteration", + type: "boolean", + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Provide_full_support_for_iterables_in_for_of_spread_and_destructuring_when_targeting_ES5_or_ES3 + }, + { + name: "isolatedModules", + type: "boolean", + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule + }, + // Strict Type Checks + { + name: "strict", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Strict_Type_Checking_Options, + description: ts.Diagnostics.Enable_all_strict_type_checking_options + }, + { + name: "noImplicitAny", + type: "boolean", + affectsSemanticDiagnostics: true, + strictFlag: true, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Strict_Type_Checking_Options, + description: ts.Diagnostics.Raise_error_on_expressions_and_declarations_with_an_implied_any_type + }, + { + name: "strictNullChecks", + type: "boolean", + affectsSemanticDiagnostics: true, + strictFlag: true, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Strict_Type_Checking_Options, + description: ts.Diagnostics.Enable_strict_null_checks + }, + { + name: "strictFunctionTypes", + type: "boolean", + affectsSemanticDiagnostics: true, + strictFlag: true, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Strict_Type_Checking_Options, + description: ts.Diagnostics.Enable_strict_checking_of_function_types + }, + { + name: "strictBindCallApply", + type: "boolean", + strictFlag: true, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Strict_Type_Checking_Options, + description: ts.Diagnostics.Enable_strict_bind_call_and_apply_methods_on_functions + }, + { + name: "strictPropertyInitialization", + type: "boolean", + affectsSemanticDiagnostics: true, + strictFlag: true, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Strict_Type_Checking_Options, + description: ts.Diagnostics.Enable_strict_checking_of_property_initialization_in_classes + }, + { + name: "noImplicitThis", + type: "boolean", + affectsSemanticDiagnostics: true, + strictFlag: true, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Strict_Type_Checking_Options, + description: ts.Diagnostics.Raise_error_on_this_expressions_with_an_implied_any_type, + }, + { + name: "alwaysStrict", + type: "boolean", + affectsSourceFile: true, + strictFlag: true, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Strict_Type_Checking_Options, + description: ts.Diagnostics.Parse_in_strict_mode_and_emit_use_strict_for_each_source_file + }, + // Additional Checks + { + name: "noUnusedLocals", + type: "boolean", + affectsSemanticDiagnostics: true, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Additional_Checks, + description: ts.Diagnostics.Report_errors_on_unused_locals, + }, + { + name: "noUnusedParameters", + type: "boolean", + affectsSemanticDiagnostics: true, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Additional_Checks, + description: ts.Diagnostics.Report_errors_on_unused_parameters, + }, + { + name: "noImplicitReturns", + type: "boolean", + affectsSemanticDiagnostics: true, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Additional_Checks, + description: ts.Diagnostics.Report_error_when_not_all_code_paths_in_function_return_a_value + }, + { + name: "noFallthroughCasesInSwitch", + type: "boolean", + affectsBindDiagnostics: true, + affectsSemanticDiagnostics: true, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Additional_Checks, + description: ts.Diagnostics.Report_errors_for_fallthrough_cases_in_switch_statement + }, + // Module Resolution + { + name: "moduleResolution", + type: ts.createMapFromTemplate({ + node: ts.ModuleResolutionKind.NodeJs, + classic: ts.ModuleResolutionKind.Classic, + }), + affectsModuleResolution: true, + paramType: ts.Diagnostics.STRATEGY, + category: ts.Diagnostics.Module_Resolution_Options, + description: ts.Diagnostics.Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6, + }, + { + name: "baseUrl", + type: "string", + affectsModuleResolution: true, + isFilePath: true, + category: ts.Diagnostics.Module_Resolution_Options, + description: ts.Diagnostics.Base_directory_to_resolve_non_absolute_module_names + }, + { + // this option can only be specified in tsconfig.json + // use type = object to copy the value as-is + name: "paths", + type: "object", + affectsModuleResolution: true, + isTSConfigOnly: true, + category: ts.Diagnostics.Module_Resolution_Options, + description: ts.Diagnostics.A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl + }, + { + // this option can only be specified in tsconfig.json + // use type = object to copy the value as-is + name: "rootDirs", + type: "list", + isTSConfigOnly: true, + element: { + name: "rootDirs", + type: "string", + isFilePath: true + }, + affectsModuleResolution: true, + category: ts.Diagnostics.Module_Resolution_Options, + description: ts.Diagnostics.List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime + }, + { + name: "typeRoots", + type: "list", + element: { + name: "typeRoots", + type: "string", + isFilePath: true + }, + affectsModuleResolution: true, + category: ts.Diagnostics.Module_Resolution_Options, + description: ts.Diagnostics.List_of_folders_to_include_type_definitions_from + }, + { + name: "types", + type: "list", + element: { + name: "types", + type: "string" + }, + affectsModuleResolution: true, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Module_Resolution_Options, + description: ts.Diagnostics.Type_declaration_files_to_be_included_in_compilation + }, + { + name: "allowSyntheticDefaultImports", + type: "boolean", + affectsSemanticDiagnostics: true, + category: ts.Diagnostics.Module_Resolution_Options, + description: ts.Diagnostics.Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking + }, + { + name: "esModuleInterop", + type: "boolean", + affectsSemanticDiagnostics: true, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Module_Resolution_Options, + description: ts.Diagnostics.Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for_all_imports_Implies_allowSyntheticDefaultImports + }, + { + name: "preserveSymlinks", + type: "boolean", + category: ts.Diagnostics.Module_Resolution_Options, + description: ts.Diagnostics.Do_not_resolve_the_real_path_of_symlinks, + }, + // Source Maps + { + name: "sourceRoot", + type: "string", + paramType: ts.Diagnostics.LOCATION, + category: ts.Diagnostics.Source_Map_Options, + description: ts.Diagnostics.Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations, + }, + { + name: "mapRoot", + type: "string", + paramType: ts.Diagnostics.LOCATION, + category: ts.Diagnostics.Source_Map_Options, + description: ts.Diagnostics.Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations, + }, + { + name: "inlineSourceMap", + type: "boolean", + category: ts.Diagnostics.Source_Map_Options, + description: ts.Diagnostics.Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file + }, + { + name: "inlineSources", + type: "boolean", + category: ts.Diagnostics.Source_Map_Options, + description: ts.Diagnostics.Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap_to_be_set + }, + // Experimental + { + name: "experimentalDecorators", + type: "boolean", + category: ts.Diagnostics.Experimental_Options, + description: ts.Diagnostics.Enables_experimental_support_for_ES7_decorators + }, + { + name: "emitDecoratorMetadata", + type: "boolean", + category: ts.Diagnostics.Experimental_Options, + description: ts.Diagnostics.Enables_experimental_support_for_emitting_type_metadata_for_decorators + }, + // Advanced + { + name: "jsxFactory", + type: "string", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h + }, + { + name: "resolveJsonModule", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Include_modules_imported_with_json_extension + }, + { + name: "out", + type: "string", + isFilePath: false, + // for correct behaviour, please use outFile + category: ts.Diagnostics.Advanced_Options, + paramType: ts.Diagnostics.FILE, + description: ts.Diagnostics.Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file, + }, + { + name: "reactNamespace", + type: "string", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react_JSX_emit + }, + { + name: "skipDefaultLibCheck", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files + }, + { + name: "charset", + type: "string", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.The_character_set_of_the_input_files + }, + { + name: "emitBOM", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files + }, + { + name: "locale", + type: "string", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.The_locale_used_when_displaying_messages_to_the_user_e_g_en_us + }, + { + name: "newLine", + type: ts.createMapFromTemplate({ + crlf: 0 /* CarriageReturnLineFeed */, + lf: 1 /* LineFeed */ + }), + paramType: ts.Diagnostics.NEWLINE, + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix, + }, + { + name: "noErrorTruncation", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Do_not_truncate_error_messages + }, + { + name: "noLib", + type: "boolean", + affectsModuleResolution: true, + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Do_not_include_the_default_library_file_lib_d_ts + }, + { + name: "noResolve", + type: "boolean", + affectsModuleResolution: true, + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files + }, + { + name: "stripInternal", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Do_not_emit_declarations_for_code_that_has_an_internal_annotation, + }, + { + name: "disableSizeLimit", + type: "boolean", + affectsSourceFile: true, + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Disable_size_limitations_on_JavaScript_projects + }, + { + name: "noImplicitUseStrict", + type: "boolean", + affectsSemanticDiagnostics: true, + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Do_not_emit_use_strict_directives_in_module_output + }, + { + name: "noEmitHelpers", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Do_not_generate_custom_helper_functions_like_extends_in_compiled_output + }, + { + name: "noEmitOnError", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Do_not_emit_outputs_if_any_errors_were_reported, + }, + { + name: "preserveConstEnums", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Do_not_erase_const_enum_declarations_in_generated_code + }, + { + name: "declarationDir", + type: "string", + isFilePath: true, + paramType: ts.Diagnostics.DIRECTORY, + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Output_directory_for_generated_declaration_files + }, + { + name: "skipLibCheck", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Skip_type_checking_of_declaration_files, + }, + { + name: "allowUnusedLabels", + type: "boolean", + affectsBindDiagnostics: true, + affectsSemanticDiagnostics: true, + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Do_not_report_errors_on_unused_labels + }, + { + name: "allowUnreachableCode", + type: "boolean", + affectsBindDiagnostics: true, + affectsSemanticDiagnostics: true, + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Do_not_report_errors_on_unreachable_code + }, + { + name: "suppressExcessPropertyErrors", + type: "boolean", + affectsSemanticDiagnostics: true, + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Suppress_excess_property_checks_for_object_literals, + }, + { + name: "suppressImplicitAnyIndexErrors", + type: "boolean", + affectsSemanticDiagnostics: true, + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures, + }, + { + name: "forceConsistentCasingInFileNames", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Disallow_inconsistently_cased_references_to_the_same_file + }, + { + name: "maxNodeModuleJsDepth", + type: "number", + affectsModuleResolution: true, + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files + }, + { + name: "noStrictGenericChecks", + type: "boolean", + affectsSemanticDiagnostics: true, + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Disable_strict_checking_of_generic_signatures_in_function_types, + }, + { + name: "keyofStringsOnly", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols, + }, + { + // A list of plugins to load in the language service + name: "plugins", + type: "list", + isTSConfigOnly: true, + element: { + name: "plugin", + type: "object" + }, + description: ts.Diagnostics.List_of_language_service_plugins + } + ]); + /* @internal */ + ts.semanticDiagnosticsOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsSemanticDiagnostics; }); + /* @internal */ + ts.moduleResolutionOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsModuleResolution; }); + /* @internal */ + ts.sourceFileAffectingCompilerOptions = ts.optionDeclarations.filter(function (option) { + return !!option.affectsSourceFile || !!option.affectsModuleResolution || !!option.affectsBindDiagnostics; + }); + /* @internal */ + ts.buildOpts = ts.commonOptionsWithBuild.concat([ + { + name: "verbose", + shortName: "v", + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Enable_verbose_logging, + type: "boolean" + }, + { + name: "dry", + shortName: "d", + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Show_what_would_be_built_or_deleted_if_specified_with_clean, + type: "boolean" + }, + { + name: "force", + shortName: "f", + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Build_all_projects_including_those_that_appear_to_be_up_to_date, + type: "boolean" + }, + { + name: "clean", + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Delete_the_outputs_of_all_projects, + type: "boolean" + } + ]); + /* @internal */ + ts.typeAcquisitionDeclarations = [ + { + /* @deprecated typingOptions.enableAutoDiscovery + * Use typeAcquisition.enable instead. + */ + name: "enableAutoDiscovery", + type: "boolean", + }, + { + name: "enable", + type: "boolean", + }, + { + name: "include", + type: "list", + element: { + name: "include", + type: "string" + } + }, + { + name: "exclude", + type: "list", + element: { + name: "exclude", + type: "string" + } + } + ]; + /* @internal */ + ts.defaultInitCompilerOptions = { + module: ts.ModuleKind.CommonJS, + target: 1 /* ES5 */, + strict: true, + esModuleInterop: true + }; + var optionNameMapCache; + /* @internal */ + function convertEnableAutoDiscoveryToEnable(typeAcquisition) { + // Convert deprecated typingOptions.enableAutoDiscovery to typeAcquisition.enable + if (typeAcquisition && typeAcquisition.enableAutoDiscovery !== undefined && typeAcquisition.enable === undefined) { + return { + enable: typeAcquisition.enableAutoDiscovery, + include: typeAcquisition.include || [], + exclude: typeAcquisition.exclude || [] + }; + } + return typeAcquisition; + } + ts.convertEnableAutoDiscoveryToEnable = convertEnableAutoDiscoveryToEnable; + function getOptionNameMap() { + return optionNameMapCache || (optionNameMapCache = createOptionNameMap(ts.optionDeclarations)); + } + /*@internal*/ + function createOptionNameMap(optionDeclarations) { + var optionNameMap = ts.createMap(); + var shortOptionNames = ts.createMap(); + ts.forEach(optionDeclarations, function (option) { + optionNameMap.set(option.name.toLowerCase(), option); + if (option.shortName) { + shortOptionNames.set(option.shortName, option.name); + } + }); + return { optionNameMap: optionNameMap, shortOptionNames: shortOptionNames }; + } + ts.createOptionNameMap = createOptionNameMap; + /* @internal */ + function createCompilerDiagnosticForInvalidCustomType(opt) { + return createDiagnosticForInvalidCustomType(opt, ts.createCompilerDiagnostic); + } + ts.createCompilerDiagnosticForInvalidCustomType = createCompilerDiagnosticForInvalidCustomType; + function createDiagnosticForInvalidCustomType(opt, createDiagnostic) { + var namesOfType = ts.arrayFrom(opt.type.keys()).map(function (key) { return "'" + key + "'"; }).join(", "); + return createDiagnostic(ts.Diagnostics.Argument_for_0_option_must_be_Colon_1, "--" + opt.name, namesOfType); + } + /* @internal */ + function parseCustomTypeOption(opt, value, errors) { + return convertJsonOptionOfCustomType(opt, trimString(value || ""), errors); + } + ts.parseCustomTypeOption = parseCustomTypeOption; + /* @internal */ + function parseListTypeOption(opt, value, errors) { + if (value === void 0) { value = ""; } + value = trimString(value); + if (ts.startsWith(value, "-")) { + return undefined; + } + if (value === "") { + return []; + } + var values = value.split(","); + switch (opt.element.type) { + case "number": + return ts.map(values, parseInt); + case "string": + return ts.map(values, function (v) { return v || ""; }); + default: + return ts.mapDefined(values, function (v) { return parseCustomTypeOption(opt.element, v, errors); }); + } + } + ts.parseListTypeOption = parseListTypeOption; + function parseCommandLineWorker(getOptionNameMap, _a, commandLine, readFile) { + var unknownOptionDiagnostic = _a[0], optionTypeMismatchDiagnostic = _a[1]; + var options = {}; + var fileNames = []; + var errors = []; + parseStrings(commandLine); + return { + options: options, + fileNames: fileNames, + errors: errors + }; + function parseStrings(args) { + var i = 0; + while (i < args.length) { + var s = args[i]; + i++; + if (s.charCodeAt(0) === 64 /* at */) { + parseResponseFile(s.slice(1)); + } + else if (s.charCodeAt(0) === 45 /* minus */) { + var opt = getOptionDeclarationFromName(getOptionNameMap, s.slice(s.charCodeAt(1) === 45 /* minus */ ? 2 : 1), /*allowShort*/ true); + if (opt) { + if (opt.isTSConfigOnly) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_can_only_be_specified_in_tsconfig_json_file, opt.name)); + } + else { + // Check to see if no argument was provided (e.g. "--locale" is the last command-line argument). + if (!args[i] && opt.type !== "boolean") { + errors.push(ts.createCompilerDiagnostic(optionTypeMismatchDiagnostic, opt.name)); + } + switch (opt.type) { + case "number": + options[opt.name] = parseInt(args[i]); + i++; + break; + case "boolean": + // boolean flag has optional value true, false, others + var optValue = args[i]; + options[opt.name] = optValue !== "false"; + // consume next argument as boolean flag value + if (optValue === "false" || optValue === "true") { + i++; + } + break; + case "string": + options[opt.name] = args[i] || ""; + i++; + break; + case "list": + var result = parseListTypeOption(opt, args[i], errors); + options[opt.name] = result || []; + if (result) { + i++; + } + break; + // If not a primitive, the possible types are specified in what is effectively a map of options. + default: + options[opt.name] = parseCustomTypeOption(opt, args[i], errors); + i++; + break; + } + } + } + else { + errors.push(ts.createCompilerDiagnostic(unknownOptionDiagnostic, s)); + } + } + else { + fileNames.push(s); + } + } + } + function parseResponseFile(fileName) { + var text = readFile ? readFile(fileName) : ts.sys.readFile(fileName); + if (!text) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_not_found, fileName)); + return; + } + var args = []; + var pos = 0; + while (true) { + while (pos < text.length && text.charCodeAt(pos) <= 32 /* space */) + pos++; + if (pos >= text.length) + break; + var start = pos; + if (text.charCodeAt(start) === 34 /* doubleQuote */) { + pos++; + while (pos < text.length && text.charCodeAt(pos) !== 34 /* doubleQuote */) + pos++; + if (pos < text.length) { + args.push(text.substring(start + 1, pos)); + pos++; + } + else { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unterminated_quoted_string_in_response_file_0, fileName)); + } + } + else { + while (text.charCodeAt(pos) > 32 /* space */) + pos++; + args.push(text.substring(start, pos)); + } + } + parseStrings(args); + } + } + function parseCommandLine(commandLine, readFile) { + return parseCommandLineWorker(getOptionNameMap, [ + ts.Diagnostics.Unknown_compiler_option_0, + ts.Diagnostics.Compiler_option_0_expects_an_argument + ], commandLine, readFile); + } + ts.parseCommandLine = parseCommandLine; + /** @internal */ + function getOptionFromName(optionName, allowShort) { + return getOptionDeclarationFromName(getOptionNameMap, optionName, allowShort); + } + ts.getOptionFromName = getOptionFromName; + function getOptionDeclarationFromName(getOptionNameMap, optionName, allowShort) { + if (allowShort === void 0) { allowShort = false; } + optionName = optionName.toLowerCase(); + var _a = getOptionNameMap(), optionNameMap = _a.optionNameMap, shortOptionNames = _a.shortOptionNames; + // Try to translate short option names to their full equivalents. + if (allowShort) { + var short = shortOptionNames.get(optionName); + if (short !== undefined) { + optionName = short; + } + } + return optionNameMap.get(optionName); + } + /*@internal*/ + function parseBuildCommand(args) { + var buildOptionNameMap; + var returnBuildOptionNameMap = function () { return (buildOptionNameMap || (buildOptionNameMap = createOptionNameMap(ts.buildOpts))); }; + var _a = parseCommandLineWorker(returnBuildOptionNameMap, [ + ts.Diagnostics.Unknown_build_option_0, + ts.Diagnostics.Build_option_0_requires_a_value_of_type_1 + ], args), options = _a.options, projects = _a.fileNames, errors = _a.errors; + var buildOptions = options; + if (projects.length === 0) { + // tsc -b invoked with no extra arguments; act as if invoked with "tsc -b ." + projects.push("."); + } + // Nonsensical combinations + if (buildOptions.clean && buildOptions.force) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "force")); + } + if (buildOptions.clean && buildOptions.verbose) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "verbose")); + } + if (buildOptions.clean && buildOptions.watch) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "watch")); + } + if (buildOptions.watch && buildOptions.dry) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "watch", "dry")); + } + return { buildOptions: buildOptions, projects: projects, errors: errors }; + } + ts.parseBuildCommand = parseBuildCommand; + function getDiagnosticText(_message) { + var _args = []; + for (var _i = 1; _i < arguments.length; _i++) { + _args[_i - 1] = arguments[_i]; + } + var diagnostic = ts.createCompilerDiagnostic.apply(undefined, arguments); + return diagnostic.messageText; + } + /* @internal */ + function printVersion() { + ts.sys.write(getDiagnosticText(ts.Diagnostics.Version_0, ts.version) + ts.sys.newLine); + } + ts.printVersion = printVersion; + /* @internal */ + function printHelp(optionsList, syntaxPrefix) { + if (syntaxPrefix === void 0) { syntaxPrefix = ""; } + var output = []; + // We want to align our "syntax" and "examples" commands to a certain margin. + var syntaxLength = getDiagnosticText(ts.Diagnostics.Syntax_Colon_0, "").length; + var examplesLength = getDiagnosticText(ts.Diagnostics.Examples_Colon_0, "").length; + var marginLength = Math.max(syntaxLength, examplesLength); + // Build up the syntactic skeleton. + var syntax = makePadding(marginLength - syntaxLength); + syntax += "tsc " + syntaxPrefix + "[" + getDiagnosticText(ts.Diagnostics.options) + "] [" + getDiagnosticText(ts.Diagnostics.file) + "...]"; + output.push(getDiagnosticText(ts.Diagnostics.Syntax_Colon_0, syntax)); + output.push(ts.sys.newLine + ts.sys.newLine); + // Build up the list of examples. + var padding = makePadding(marginLength); + output.push(getDiagnosticText(ts.Diagnostics.Examples_Colon_0, makePadding(marginLength - examplesLength) + "tsc hello.ts") + ts.sys.newLine); + output.push(padding + "tsc --outFile file.js file.ts" + ts.sys.newLine); + output.push(padding + "tsc @args.txt" + ts.sys.newLine); + output.push(padding + "tsc --build tsconfig.json" + ts.sys.newLine); + output.push(ts.sys.newLine); + output.push(getDiagnosticText(ts.Diagnostics.Options_Colon) + ts.sys.newLine); + // We want our descriptions to align at the same column in our output, + // so we keep track of the longest option usage string. + marginLength = 0; + var usageColumn = []; // Things like "-d, --declaration" go in here. + var descriptionColumn = []; + var optionsDescriptionMap = ts.createMap(); // Map between option.description and list of option.type if it is a kind + for (var _i = 0, optionsList_1 = optionsList; _i < optionsList_1.length; _i++) { + var option = optionsList_1[_i]; + // If an option lacks a description, + // it is not officially supported. + if (!option.description) { + continue; + } + var usageText_1 = " "; + if (option.shortName) { + usageText_1 += "-" + option.shortName; + usageText_1 += getParamType(option); + usageText_1 += ", "; + } + usageText_1 += "--" + option.name; + usageText_1 += getParamType(option); + usageColumn.push(usageText_1); + var description = void 0; + if (option.name === "lib") { + description = getDiagnosticText(option.description); + var element = option.element; + var typeMap = element.type; + optionsDescriptionMap.set(description, ts.arrayFrom(typeMap.keys()).map(function (key) { return "'" + key + "'"; })); + } + else { + description = getDiagnosticText(option.description); + } + descriptionColumn.push(description); + // Set the new margin for the description column if necessary. + marginLength = Math.max(usageText_1.length, marginLength); + } + // Special case that can't fit in the loop. + var usageText = " @<" + getDiagnosticText(ts.Diagnostics.file) + ">"; + usageColumn.push(usageText); + descriptionColumn.push(getDiagnosticText(ts.Diagnostics.Insert_command_line_options_and_files_from_a_file)); + marginLength = Math.max(usageText.length, marginLength); + // Print out each row, aligning all the descriptions on the same column. + for (var i = 0; i < usageColumn.length; i++) { + var usage = usageColumn[i]; + var description = descriptionColumn[i]; + var kindsList = optionsDescriptionMap.get(description); + output.push(usage + makePadding(marginLength - usage.length + 2) + description + ts.sys.newLine); + if (kindsList) { + output.push(makePadding(marginLength + 4)); + for (var _a = 0, kindsList_1 = kindsList; _a < kindsList_1.length; _a++) { + var kind = kindsList_1[_a]; + output.push(kind + " "); + } + output.push(ts.sys.newLine); + } + } + for (var _b = 0, output_1 = output; _b < output_1.length; _b++) { + var line = output_1[_b]; + ts.sys.write(line); + } + return; + function getParamType(option) { + if (option.paramType !== undefined) { + return " " + getDiagnosticText(option.paramType); + } + return ""; + } + function makePadding(paddingLength) { + return Array(paddingLength + 1).join(" "); + } + } + ts.printHelp = printHelp; + /** + * Reads the config file, reports errors if any and exits if the config file cannot be found + */ + function getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host) { + var configFileText; + try { + configFileText = host.readFile(configFileName); + } + catch (e) { + var error = ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, configFileName, e.message); + host.onUnRecoverableConfigFileDiagnostic(error); + return undefined; + } + if (!configFileText) { + var error = ts.createCompilerDiagnostic(ts.Diagnostics.File_0_not_found, configFileName); + host.onUnRecoverableConfigFileDiagnostic(error); + return undefined; + } + var result = ts.parseJsonText(configFileName, configFileText); + var cwd = host.getCurrentDirectory(); + result.path = ts.toPath(configFileName, cwd, ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames)); + result.resolvedPath = result.path; + result.originalFileName = result.fileName; + return parseJsonSourceFileConfigFileContent(result, host, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), cwd), optionsToExtend, ts.getNormalizedAbsolutePath(configFileName, cwd)); + } + ts.getParsedCommandLineOfConfigFile = getParsedCommandLineOfConfigFile; + /** + * Read tsconfig.json file + * @param fileName The path to the config file + */ + function readConfigFile(fileName, readFile) { + var textOrDiagnostic = tryReadFile(fileName, readFile); + return ts.isString(textOrDiagnostic) ? parseConfigFileTextToJson(fileName, textOrDiagnostic) : { config: {}, error: textOrDiagnostic }; + } + ts.readConfigFile = readConfigFile; + /** + * Parse the text of the tsconfig.json file + * @param fileName The path to the config file + * @param jsonText The text of the config file + */ + function parseConfigFileTextToJson(fileName, jsonText) { + var jsonSourceFile = ts.parseJsonText(fileName, jsonText); + return { + config: convertToObject(jsonSourceFile, jsonSourceFile.parseDiagnostics), + error: jsonSourceFile.parseDiagnostics.length ? jsonSourceFile.parseDiagnostics[0] : undefined + }; + } + ts.parseConfigFileTextToJson = parseConfigFileTextToJson; + /** + * Read tsconfig.json file + * @param fileName The path to the config file + */ + function readJsonConfigFile(fileName, readFile) { + var textOrDiagnostic = tryReadFile(fileName, readFile); + return ts.isString(textOrDiagnostic) ? ts.parseJsonText(fileName, textOrDiagnostic) : { parseDiagnostics: [textOrDiagnostic] }; + } + ts.readJsonConfigFile = readJsonConfigFile; + function tryReadFile(fileName, readFile) { + var text; + try { + text = readFile(fileName); + } + catch (e) { + return ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, e.message); + } + return text === undefined ? ts.createCompilerDiagnostic(ts.Diagnostics.The_specified_path_does_not_exist_Colon_0, fileName) : text; + } + function commandLineOptionsToMap(options) { + return ts.arrayToMap(options, function (option) { return option.name; }); + } + var _tsconfigRootOptions; + function getTsconfigRootOptionsMap() { + if (_tsconfigRootOptions === undefined) { + _tsconfigRootOptions = { + name: undefined, + type: "object", + elementOptions: commandLineOptionsToMap([ + { + name: "compilerOptions", + type: "object", + elementOptions: commandLineOptionsToMap(ts.optionDeclarations), + extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_compiler_option_0 + }, + { + name: "typingOptions", + type: "object", + elementOptions: commandLineOptionsToMap(ts.typeAcquisitionDeclarations), + extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_type_acquisition_option_0 + }, + { + name: "typeAcquisition", + type: "object", + elementOptions: commandLineOptionsToMap(ts.typeAcquisitionDeclarations), + extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_type_acquisition_option_0 + }, + { + name: "extends", + type: "string" + }, + { + name: "references", + type: "list", + element: { + name: "references", + type: "object" + } + }, + { + name: "files", + type: "list", + element: { + name: "files", + type: "string" + } + }, + { + name: "include", + type: "list", + element: { + name: "include", + type: "string" + } + }, + { + name: "exclude", + type: "list", + element: { + name: "exclude", + type: "string" + } + }, + ts.compileOnSaveCommandLineOption + ]) + }; + } + return _tsconfigRootOptions; + } + /** + * Convert the json syntax tree into the json value + */ + function convertToObject(sourceFile, errors) { + return convertToObjectWorker(sourceFile, errors, /*returnValue*/ true, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined); + } + ts.convertToObject = convertToObject; + /** + * Convert the json syntax tree into the json value and report errors + * This returns the json value (apart from checking errors) only if returnValue provided is true. + * Otherwise it just checks the errors and returns undefined + */ + /*@internal*/ + function convertToObjectWorker(sourceFile, errors, returnValue, knownRootOptions, jsonConversionNotifier) { + if (!sourceFile.statements.length) { + return returnValue ? {} : undefined; + } + return convertPropertyValueToJson(sourceFile.statements[0].expression, knownRootOptions); + function isRootOptionMap(knownOptions) { + return knownRootOptions && knownRootOptions.elementOptions === knownOptions; + } + function convertObjectLiteralExpressionToJson(node, knownOptions, extraKeyDiagnosticMessage, parentOption) { + var result = returnValue ? {} : undefined; + for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { + var element = _a[_i]; + if (element.kind !== 275 /* PropertyAssignment */) { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element, ts.Diagnostics.Property_assignment_expected)); + continue; + } + if (element.questionToken) { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.questionToken, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, "?")); + } + if (!isDoubleQuotedString(element.name)) { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, ts.Diagnostics.String_literal_with_double_quotes_expected)); + } + var textOfKey = ts.getTextOfPropertyName(element.name); + var keyText = textOfKey && ts.unescapeLeadingUnderscores(textOfKey); + var option = keyText && knownOptions ? knownOptions.get(keyText) : undefined; + if (keyText && extraKeyDiagnosticMessage && !option) { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, extraKeyDiagnosticMessage, keyText)); + } + var value = convertPropertyValueToJson(element.initializer, option); + if (typeof keyText !== "undefined") { + if (returnValue) { + result[keyText] = value; + } + // Notify key value set, if user asked for it + if (jsonConversionNotifier && + // Current callbacks are only on known parent option or if we are setting values in the root + (parentOption || isRootOptionMap(knownOptions))) { + var isValidOptionValue = isCompilerOptionsValue(option, value); + if (parentOption) { + if (isValidOptionValue) { + // Notify option set in the parent if its a valid option value + jsonConversionNotifier.onSetValidOptionKeyValueInParent(parentOption, option, value); + } + } + else if (isRootOptionMap(knownOptions)) { + if (isValidOptionValue) { + // Notify about the valid root key value being set + jsonConversionNotifier.onSetValidOptionKeyValueInRoot(keyText, element.name, value, element.initializer); + } + else if (!option) { + // Notify about the unknown root key value being set + jsonConversionNotifier.onSetUnknownOptionKeyValueInRoot(keyText, element.name, value, element.initializer); + } + } + } + } + } + return result; + } + function convertArrayLiteralExpressionToJson(elements, elementOption) { + if (!returnValue) { + return elements.forEach(function (element) { return convertPropertyValueToJson(element, elementOption); }); + } + // Filter out invalid values + return ts.filter(elements.map(function (element) { return convertPropertyValueToJson(element, elementOption); }), function (v) { return v !== undefined; }); + } + function convertPropertyValueToJson(valueExpression, option) { + switch (valueExpression.kind) { + case 102 /* TrueKeyword */: + reportInvalidOptionValue(option && option.type !== "boolean"); + return true; + case 87 /* FalseKeyword */: + reportInvalidOptionValue(option && option.type !== "boolean"); + return false; + case 96 /* NullKeyword */: + reportInvalidOptionValue(option && option.name === "extends"); // "extends" is the only option we don't allow null/undefined for + return null; // tslint:disable-line:no-null-keyword + case 10 /* StringLiteral */: + if (!isDoubleQuotedString(valueExpression)) { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, ts.Diagnostics.String_literal_with_double_quotes_expected)); + } + reportInvalidOptionValue(option && (ts.isString(option.type) && option.type !== "string")); + var text = valueExpression.text; + if (option && !ts.isString(option.type)) { + var customOption = option; + // Validate custom option type + if (!customOption.type.has(text.toLowerCase())) { + errors.push(createDiagnosticForInvalidCustomType(customOption, function (message, arg0, arg1) { return ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, message, arg0, arg1); })); + } + } + return text; + case 8 /* NumericLiteral */: + reportInvalidOptionValue(option && option.type !== "number"); + return Number(valueExpression.text); + case 202 /* PrefixUnaryExpression */: + if (valueExpression.operator !== 39 /* MinusToken */ || valueExpression.operand.kind !== 8 /* NumericLiteral */) { + break; // not valid JSON syntax + } + reportInvalidOptionValue(option && option.type !== "number"); + return -Number(valueExpression.operand.text); + case 188 /* ObjectLiteralExpression */: + reportInvalidOptionValue(option && option.type !== "object"); + var objectLiteralExpression = valueExpression; + // Currently having element option declaration in the tsconfig with type "object" + // determines if it needs onSetValidOptionKeyValueInParent callback or not + // At moment there are only "compilerOptions", "typeAcquisition" and "typingOptions" + // that satifies it and need it to modify options set in them (for normalizing file paths) + // vs what we set in the json + // If need arises, we can modify this interface and callbacks as needed + if (option) { + var _a = option, elementOptions = _a.elementOptions, extraKeyDiagnosticMessage = _a.extraKeyDiagnosticMessage, optionName = _a.name; + return convertObjectLiteralExpressionToJson(objectLiteralExpression, elementOptions, extraKeyDiagnosticMessage, optionName); + } + else { + return convertObjectLiteralExpressionToJson(objectLiteralExpression, /* knownOptions*/ undefined, + /*extraKeyDiagnosticMessage */ undefined, /*parentOption*/ undefined); + } + case 187 /* ArrayLiteralExpression */: + reportInvalidOptionValue(option && option.type !== "list"); + return convertArrayLiteralExpressionToJson(valueExpression.elements, option && option.element); + } + // Not in expected format + if (option) { + reportInvalidOptionValue(/*isError*/ true); + } + else { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, ts.Diagnostics.Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_literal)); + } + return undefined; + function reportInvalidOptionValue(isError) { + if (isError) { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, option.name, getCompilerOptionValueTypeString(option))); + } + } + } + function isDoubleQuotedString(node) { + return ts.isStringLiteral(node) && ts.isStringDoubleQuoted(node, sourceFile); + } + } + ts.convertToObjectWorker = convertToObjectWorker; + function getCompilerOptionValueTypeString(option) { + return option.type === "list" ? + "Array" : + ts.isString(option.type) ? option.type : "string"; + } + function isCompilerOptionsValue(option, value) { + if (option) { + if (isNullOrUndefined(value)) + return true; // All options are undefinable/nullable + if (option.type === "list") { + return ts.isArray(value); + } + var expectedType = ts.isString(option.type) ? option.type : "string"; + return typeof value === expectedType; + } + return false; + } + /** + * Generate an uncommented, complete tsconfig for use with "--showConfig" + * @param configParseResult options to be generated into tsconfig.json + * @param configFileName name of the parsed config file - output paths will be generated relative to this + * @param host provides current directory and case sensitivity services + */ + /** @internal */ + function convertToTSConfig(configParseResult, configFileName, host) { + var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); + var files = ts.map(ts.filter(configParseResult.fileNames, (!configParseResult.configFileSpecs || !configParseResult.configFileSpecs.validatedIncludeSpecs) ? function (_) { return true; } : matchesSpecs(configFileName, configParseResult.configFileSpecs.validatedIncludeSpecs, configParseResult.configFileSpecs.validatedExcludeSpecs)), function (f) { return ts.getRelativePathFromFile(ts.getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), ts.getNormalizedAbsolutePath(f, host.getCurrentDirectory()), getCanonicalFileName); }); + var optionMap = serializeCompilerOptions(configParseResult.options, { configFilePath: ts.getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), useCaseSensitiveFileNames: host.useCaseSensitiveFileNames }); + var config = __assign({ compilerOptions: __assign({}, ts.arrayFrom(optionMap.entries()).reduce(function (prev, cur) { + var _a; + return (__assign({}, prev, (_a = {}, _a[cur[0]] = cur[1], _a))); + }, {}), { showConfig: undefined, configFile: undefined, configFilePath: undefined, help: undefined, init: undefined, listFiles: undefined, listEmittedFiles: undefined, project: undefined }), references: ts.map(configParseResult.projectReferences, function (r) { return (__assign({}, r, { path: r.originalPath, originalPath: undefined })); }), files: ts.length(files) ? files : undefined }, (configParseResult.configFileSpecs ? { + include: filterSameAsDefaultInclude(configParseResult.configFileSpecs.validatedIncludeSpecs), + exclude: configParseResult.configFileSpecs.validatedExcludeSpecs + } : {}), { compilerOnSave: !!configParseResult.compileOnSave ? true : undefined }); + return config; + } + ts.convertToTSConfig = convertToTSConfig; + function filterSameAsDefaultInclude(specs) { + if (!ts.length(specs)) + return undefined; + if (ts.length(specs) !== 1) + return specs; + if (specs[0] === "**/*") + return undefined; + return specs; + } + function matchesSpecs(path, includeSpecs, excludeSpecs) { + if (!includeSpecs) + return function (_) { return true; }; + var patterns = ts.getFileMatcherPatterns(path, excludeSpecs, includeSpecs, ts.sys.useCaseSensitiveFileNames, ts.sys.getCurrentDirectory()); + var excludeRe = patterns.excludePattern && ts.getRegexFromPattern(patterns.excludePattern, ts.sys.useCaseSensitiveFileNames); + var includeRe = patterns.includeFilePattern && ts.getRegexFromPattern(patterns.includeFilePattern, ts.sys.useCaseSensitiveFileNames); + if (includeRe) { + if (excludeRe) { + return function (path) { return !(includeRe.test(path) && !excludeRe.test(path)); }; + } + return function (path) { return !includeRe.test(path); }; + } + if (excludeRe) { + return function (path) { return excludeRe.test(path); }; + } + return function (_) { return true; }; + } + function getCustomTypeMapOfCommandLineOption(optionDefinition) { + if (optionDefinition.type === "string" || optionDefinition.type === "number" || optionDefinition.type === "boolean") { + // this is of a type CommandLineOptionOfPrimitiveType + return undefined; + } + else if (optionDefinition.type === "list") { + return getCustomTypeMapOfCommandLineOption(optionDefinition.element); + } + else { + return optionDefinition.type; + } + } + function getNameOfCompilerOptionValue(value, customTypeMap) { + // There is a typeMap associated with this command-line option so use it to map value back to its name + return ts.forEachEntry(customTypeMap, function (mapValue, key) { + if (mapValue === value) { + return key; + } + }); + } + function serializeCompilerOptions(options, pathOptions) { + var result = ts.createMap(); + var optionsNameMap = getOptionNameMap().optionNameMap; + var getCanonicalFileName = pathOptions && ts.createGetCanonicalFileName(pathOptions.useCaseSensitiveFileNames); + var _loop_3 = function (name) { + if (ts.hasProperty(options, name)) { + // tsconfig only options cannot be specified via command line, + // so we can assume that only types that can appear here string | number | boolean + if (optionsNameMap.has(name) && optionsNameMap.get(name).category === ts.Diagnostics.Command_line_Options) { + return "continue"; + } + var value = options[name]; + var optionDefinition = optionsNameMap.get(name.toLowerCase()); + if (optionDefinition) { + var customTypeMap_1 = getCustomTypeMapOfCommandLineOption(optionDefinition); + if (!customTypeMap_1) { + // There is no map associated with this compiler option then use the value as-is + // This is the case if the value is expect to be string, number, boolean or list of string + if (pathOptions && optionDefinition.isFilePath) { + result.set(name, ts.getRelativePathFromFile(pathOptions.configFilePath, ts.getNormalizedAbsolutePath(value, ts.getDirectoryPath(pathOptions.configFilePath)), getCanonicalFileName)); + } + else { + result.set(name, value); + } + } + else { + if (optionDefinition.type === "list") { + result.set(name, value.map(function (element) { return getNameOfCompilerOptionValue(element, customTypeMap_1); })); // TODO: GH#18217 + } + else { + // There is a typeMap associated with this command-line option so use it to map value back to its name + result.set(name, getNameOfCompilerOptionValue(value, customTypeMap_1)); + } + } + } + } + }; + for (var name in options) { + _loop_3(name); + } + return result; + } + /** + * Generate tsconfig configuration when running command line "--init" + * @param options commandlineOptions to be generated into tsconfig.json + * @param fileNames array of filenames to be generated into tsconfig.json + */ + /* @internal */ + function generateTSConfig(options, fileNames, newLine) { + var compilerOptions = ts.extend(options, ts.defaultInitCompilerOptions); + var compilerOptionsMap = serializeCompilerOptions(compilerOptions); + return writeConfigurations(); + function getDefaultValueForOption(option) { + switch (option.type) { + case "number": + return 1; + case "boolean": + return true; + case "string": + return option.isFilePath ? "./" : ""; + case "list": + return []; + case "object": + return {}; + default: + return option.type.keys().next().value; + } + } + function makePadding(paddingLength) { + return Array(paddingLength + 1).join(" "); + } + function isAllowedOption(_a) { + var category = _a.category, name = _a.name; + // Skip options which do not have a category or have category `Command_line_Options` + // Exclude all possible `Advanced_Options` in tsconfig.json which were NOT defined in command line + return category !== undefined + && category !== ts.Diagnostics.Command_line_Options + && (category !== ts.Diagnostics.Advanced_Options || compilerOptionsMap.has(name)); + } + function writeConfigurations() { + // Filter applicable options to place in the file + var categorizedOptions = ts.createMultiMap(); + for (var _i = 0, optionDeclarations_1 = ts.optionDeclarations; _i < optionDeclarations_1.length; _i++) { + var option = optionDeclarations_1[_i]; + var category = option.category; + if (isAllowedOption(option)) { + categorizedOptions.add(ts.getLocaleSpecificMessage(category), option); + } + } + // Serialize all options and their descriptions + var marginLength = 0; + var seenKnownKeys = 0; + var nameColumn = []; + var descriptionColumn = []; + categorizedOptions.forEach(function (options, category) { + if (nameColumn.length !== 0) { + nameColumn.push(""); + descriptionColumn.push(""); + } + nameColumn.push("/* " + category + " */"); + descriptionColumn.push(""); + for (var _i = 0, options_1 = options; _i < options_1.length; _i++) { + var option = options_1[_i]; + var optionName = void 0; + if (compilerOptionsMap.has(option.name)) { + optionName = "\"" + option.name + "\": " + JSON.stringify(compilerOptionsMap.get(option.name)) + ((seenKnownKeys += 1) === compilerOptionsMap.size ? "" : ","); + } + else { + optionName = "// \"" + option.name + "\": " + JSON.stringify(getDefaultValueForOption(option)) + ","; + } + nameColumn.push(optionName); + descriptionColumn.push("/* " + (option.description && ts.getLocaleSpecificMessage(option.description) || option.name) + " */"); + marginLength = Math.max(optionName.length, marginLength); + } + }); + // Write the output + var tab = makePadding(2); + var result = []; + result.push("{"); + result.push(tab + "\"compilerOptions\": {"); + // Print out each row, aligning all the descriptions on the same column. + for (var i = 0; i < nameColumn.length; i++) { + var optionName = nameColumn[i]; + var description = descriptionColumn[i]; + result.push(optionName && "" + tab + tab + optionName + (description && (makePadding(marginLength - optionName.length + 2) + description))); + } + if (fileNames.length) { + result.push(tab + "},"); + result.push(tab + "\"files\": ["); + for (var i = 0; i < fileNames.length; i++) { + result.push("" + tab + tab + JSON.stringify(fileNames[i]) + (i === fileNames.length - 1 ? "" : ",")); + } + result.push(tab + "]"); + } + else { + result.push(tab + "}"); + } + result.push("}"); + return result.join(newLine); + } + } + ts.generateTSConfig = generateTSConfig; + /** + * Parse the contents of a config file (tsconfig.json). + * @param json The contents of the config file to parse + * @param host Instance of ParseConfigHost used to enumerate files in folder. + * @param basePath A root directory to resolve relative path entries in the config + * file to. e.g. outDir + */ + function parseJsonConfigFileContent(json, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions) { + return parseJsonConfigFileContentWorker(json, /*sourceFile*/ undefined, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions); + } + ts.parseJsonConfigFileContent = parseJsonConfigFileContent; + /** + * Parse the contents of a config file (tsconfig.json). + * @param jsonNode The contents of the config file to parse + * @param host Instance of ParseConfigHost used to enumerate files in folder. + * @param basePath A root directory to resolve relative path entries in the config + * file to. e.g. outDir + */ + function parseJsonSourceFileConfigFileContent(sourceFile, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions) { + return parseJsonConfigFileContentWorker(/*json*/ undefined, sourceFile, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions); + } + ts.parseJsonSourceFileConfigFileContent = parseJsonSourceFileConfigFileContent; + /*@internal*/ + function setConfigFileInOptions(options, configFile) { + if (configFile) { + Object.defineProperty(options, "configFile", { enumerable: false, writable: false, value: configFile }); + } + } + ts.setConfigFileInOptions = setConfigFileInOptions; + function isNullOrUndefined(x) { + // tslint:disable-next-line:no-null-keyword + return x === undefined || x === null; + } + function directoryOfCombinedPath(fileName, basePath) { + // Use the `getNormalizedAbsolutePath` function to avoid canonicalizing the path, as it must remain noncanonical + // until consistient casing errors are reported + return ts.getDirectoryPath(ts.getNormalizedAbsolutePath(fileName, basePath)); + } + /** + * Parse the contents of a config file from json or json source file (tsconfig.json). + * @param json The contents of the config file to parse + * @param sourceFile sourceFile corresponding to the Json + * @param host Instance of ParseConfigHost used to enumerate files in folder. + * @param basePath A root directory to resolve relative path entries in the config + * file to. e.g. outDir + * @param resolutionStack Only present for backwards-compatibility. Should be empty. + */ + function parseJsonConfigFileContentWorker(json, sourceFile, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions) { + if (existingOptions === void 0) { existingOptions = {}; } + if (resolutionStack === void 0) { resolutionStack = []; } + if (extraFileExtensions === void 0) { extraFileExtensions = []; } + ts.Debug.assert((json === undefined && sourceFile !== undefined) || (json !== undefined && sourceFile === undefined)); + var errors = []; + var parsedConfig = parseConfig(json, sourceFile, host, basePath, configFileName, resolutionStack, errors); + var raw = parsedConfig.raw; + var options = ts.extend(existingOptions, parsedConfig.options || {}); + options.configFilePath = configFileName && ts.normalizeSlashes(configFileName); + setConfigFileInOptions(options, sourceFile); + var projectReferences; + var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories, spec = _a.spec; + return { + options: options, + fileNames: fileNames, + projectReferences: projectReferences, + typeAcquisition: parsedConfig.typeAcquisition || getDefaultTypeAcquisition(), + raw: raw, + errors: errors, + wildcardDirectories: wildcardDirectories, + compileOnSave: !!raw.compileOnSave, + configFileSpecs: spec + }; + function getFileNames() { + var filesSpecs; + if (ts.hasProperty(raw, "files") && !isNullOrUndefined(raw.files)) { + if (ts.isArray(raw.files)) { + filesSpecs = raw.files; + var hasReferences = ts.hasProperty(raw, "references") && !isNullOrUndefined(raw.references); + var hasZeroOrNoReferences = !hasReferences || raw.references.length === 0; + var hasExtends = ts.hasProperty(raw, "extends"); + if (filesSpecs.length === 0 && hasZeroOrNoReferences && !hasExtends) { + if (sourceFile) { + var fileName = configFileName || "tsconfig.json"; + var diagnosticMessage = ts.Diagnostics.The_files_list_in_config_file_0_is_empty; + var nodeValue = ts.firstDefined(ts.getTsConfigPropArray(sourceFile, "files"), function (property) { return property.initializer; }); + var error = nodeValue + ? ts.createDiagnosticForNodeInSourceFile(sourceFile, nodeValue, diagnosticMessage, fileName) + : ts.createCompilerDiagnostic(diagnosticMessage, fileName); + errors.push(error); + } + else { + createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json"); + } + } + } + else { + createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "files", "Array"); + } + } + var includeSpecs; + if (ts.hasProperty(raw, "include") && !isNullOrUndefined(raw.include)) { + if (ts.isArray(raw.include)) { + includeSpecs = raw.include; + } + else { + createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "include", "Array"); + } + } + var excludeSpecs; + if (ts.hasProperty(raw, "exclude") && !isNullOrUndefined(raw.exclude)) { + if (ts.isArray(raw.exclude)) { + excludeSpecs = raw.exclude; + } + else { + createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "exclude", "Array"); + } + } + else if (raw.compilerOptions) { + var outDir = raw.compilerOptions.outDir; + var declarationDir = raw.compilerOptions.declarationDir; + if (outDir || declarationDir) { + excludeSpecs = [outDir, declarationDir].filter(function (d) { return !!d; }); + } + } + if (filesSpecs === undefined && includeSpecs === undefined) { + includeSpecs = ["**/*"]; + } + var result = matchFileNames(filesSpecs, includeSpecs, excludeSpecs, configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath, options, host, errors, extraFileExtensions, sourceFile); + if (shouldReportNoInputFiles(result, canJsonReportNoInutFiles(raw), resolutionStack)) { + errors.push(getErrorForNoInputFiles(result.spec, configFileName)); + } + if (ts.hasProperty(raw, "references") && !isNullOrUndefined(raw.references)) { + if (ts.isArray(raw.references)) { + for (var _i = 0, _a = raw.references; _i < _a.length; _i++) { + var ref = _a[_i]; + if (typeof ref.path !== "string") { + createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "reference.path", "string"); + } + else { + (projectReferences || (projectReferences = [])).push({ + path: ts.getNormalizedAbsolutePath(ref.path, basePath), + originalPath: ref.path, + prepend: ref.prepend, + circular: ref.circular + }); + } + } + } + else { + createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "references", "Array"); + } + } + return result; + } + function createCompilerDiagnosticOnlyIfJson(message, arg0, arg1) { + if (!sourceFile) { + errors.push(ts.createCompilerDiagnostic(message, arg0, arg1)); + } + } + } + function isErrorNoInputFiles(error) { + return error.code === ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2.code; + } + function getErrorForNoInputFiles(_a, configFileName) { + var includeSpecs = _a.includeSpecs, excludeSpecs = _a.excludeSpecs; + return ts.createCompilerDiagnostic(ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2, configFileName || "tsconfig.json", JSON.stringify(includeSpecs || []), JSON.stringify(excludeSpecs || [])); + } + function shouldReportNoInputFiles(result, canJsonReportNoInutFiles, resolutionStack) { + return result.fileNames.length === 0 && canJsonReportNoInutFiles && (!resolutionStack || resolutionStack.length === 0); + } + /*@internal*/ + function canJsonReportNoInutFiles(raw) { + return !ts.hasProperty(raw, "files") && !ts.hasProperty(raw, "references"); + } + ts.canJsonReportNoInutFiles = canJsonReportNoInutFiles; + /*@internal*/ + function updateErrorForNoInputFiles(result, configFileName, configFileSpecs, configParseDiagnostics, canJsonReportNoInutFiles) { + var existingErrors = configParseDiagnostics.length; + if (shouldReportNoInputFiles(result, canJsonReportNoInutFiles)) { + configParseDiagnostics.push(getErrorForNoInputFiles(configFileSpecs, configFileName)); + } + else { + ts.filterMutate(configParseDiagnostics, function (error) { return !isErrorNoInputFiles(error); }); + } + return existingErrors !== configParseDiagnostics.length; + } + ts.updateErrorForNoInputFiles = updateErrorForNoInputFiles; + function isSuccessfulParsedTsconfig(value) { + return !!value.options; + } + /** + * This *just* extracts options/include/exclude/files out of a config file. + * It does *not* resolve the included files. + */ + function parseConfig(json, sourceFile, host, basePath, configFileName, resolutionStack, errors) { + basePath = ts.normalizeSlashes(basePath); + var resolvedPath = ts.getNormalizedAbsolutePath(configFileName || "", basePath); + if (resolutionStack.indexOf(resolvedPath) >= 0) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Circularity_detected_while_resolving_configuration_Colon_0, resolutionStack.concat([resolvedPath]).join(" -> "))); + return { raw: json || convertToObject(sourceFile, errors) }; + } + var ownConfig = json ? + parseOwnConfigOfJson(json, host, basePath, configFileName, errors) : + parseOwnConfigOfJsonSourceFile(sourceFile, host, basePath, configFileName, errors); + if (ownConfig.extendedConfigPath) { + // copy the resolution stack so it is never reused between branches in potential diamond-problem scenarios. + resolutionStack = resolutionStack.concat([resolvedPath]); + var extendedConfig = getExtendedConfig(sourceFile, ownConfig.extendedConfigPath, host, basePath, resolutionStack, errors); + if (extendedConfig && isSuccessfulParsedTsconfig(extendedConfig)) { + var baseRaw_1 = extendedConfig.raw; + var raw_1 = ownConfig.raw; + var setPropertyInRawIfNotUndefined = function (propertyName) { + var value = raw_1[propertyName] || baseRaw_1[propertyName]; + if (value) { + raw_1[propertyName] = value; + } + }; + setPropertyInRawIfNotUndefined("include"); + setPropertyInRawIfNotUndefined("exclude"); + setPropertyInRawIfNotUndefined("files"); + if (raw_1.compileOnSave === undefined) { + raw_1.compileOnSave = baseRaw_1.compileOnSave; + } + ownConfig.options = ts.assign({}, extendedConfig.options, ownConfig.options); + // TODO extend type typeAcquisition + } + } + return ownConfig; + } + function parseOwnConfigOfJson(json, host, basePath, configFileName, errors) { + if (ts.hasProperty(json, "excludes")) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude)); + } + var options = convertCompilerOptionsFromJsonWorker(json.compilerOptions, basePath, errors, configFileName); + // typingOptions has been deprecated and is only supported for backward compatibility purposes. + // It should be removed in future releases - use typeAcquisition instead. + var typeAcquisition = convertTypeAcquisitionFromJsonWorker(json.typeAcquisition || json.typingOptions, basePath, errors, configFileName); + json.compileOnSave = convertCompileOnSaveOptionFromJson(json, basePath, errors); + var extendedConfigPath; + if (json.extends) { + if (!ts.isString(json.extends)) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "extends", "string")); + } + else { + var newBase = configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath; + extendedConfigPath = getExtendsConfigPath(json.extends, host, newBase, errors, ts.createCompilerDiagnostic); + } + } + return { raw: json, options: options, typeAcquisition: typeAcquisition, extendedConfigPath: extendedConfigPath }; + } + function parseOwnConfigOfJsonSourceFile(sourceFile, host, basePath, configFileName, errors) { + var options = getDefaultCompilerOptions(configFileName); + var typeAcquisition, typingOptionstypeAcquisition; + var extendedConfigPath; + var optionsIterator = { + onSetValidOptionKeyValueInParent: function (parentOption, option, value) { + ts.Debug.assert(parentOption === "compilerOptions" || parentOption === "typeAcquisition" || parentOption === "typingOptions"); + var currentOption = parentOption === "compilerOptions" ? + options : + parentOption === "typeAcquisition" ? + (typeAcquisition || (typeAcquisition = getDefaultTypeAcquisition(configFileName))) : + (typingOptionstypeAcquisition || (typingOptionstypeAcquisition = getDefaultTypeAcquisition(configFileName))); + currentOption[option.name] = normalizeOptionValue(option, basePath, value); + }, + onSetValidOptionKeyValueInRoot: function (key, _keyNode, value, valueNode) { + switch (key) { + case "extends": + var newBase = configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath; + extendedConfigPath = getExtendsConfigPath(value, host, newBase, errors, function (message, arg0) { + return ts.createDiagnosticForNodeInSourceFile(sourceFile, valueNode, message, arg0); + }); + return; + } + }, + onSetUnknownOptionKeyValueInRoot: function (key, keyNode, _value, _valueNode) { + if (key === "excludes") { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, keyNode, ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude)); + } + } + }; + var json = convertToObjectWorker(sourceFile, errors, /*returnValue*/ true, getTsconfigRootOptionsMap(), optionsIterator); + if (!typeAcquisition) { + if (typingOptionstypeAcquisition) { + typeAcquisition = (typingOptionstypeAcquisition.enableAutoDiscovery !== undefined) ? + { + enable: typingOptionstypeAcquisition.enableAutoDiscovery, + include: typingOptionstypeAcquisition.include, + exclude: typingOptionstypeAcquisition.exclude + } : + typingOptionstypeAcquisition; + } + else { + typeAcquisition = getDefaultTypeAcquisition(configFileName); + } + } + return { raw: json, options: options, typeAcquisition: typeAcquisition, extendedConfigPath: extendedConfigPath }; + } + function getExtendsConfigPath(extendedConfig, host, basePath, errors, createDiagnostic) { + extendedConfig = ts.normalizeSlashes(extendedConfig); + if (ts.isRootedDiskPath(extendedConfig) || ts.startsWith(extendedConfig, "./") || ts.startsWith(extendedConfig, "../")) { + var extendedConfigPath = ts.getNormalizedAbsolutePath(extendedConfig, basePath); + if (!host.fileExists(extendedConfigPath) && !ts.endsWith(extendedConfigPath, ".json" /* Json */)) { + extendedConfigPath = extendedConfigPath + ".json"; + if (!host.fileExists(extendedConfigPath)) { + errors.push(createDiagnostic(ts.Diagnostics.File_0_does_not_exist, extendedConfig)); + return undefined; + } + } + return extendedConfigPath; + } + // If the path isn't a rooted or relative path, resolve like a module + var resolved = ts.nodeModuleNameResolver(extendedConfig, ts.combinePaths(basePath, "tsconfig.json"), { moduleResolution: ts.ModuleResolutionKind.NodeJs }, host, /*cache*/ undefined, /*projectRefs*/ undefined, /*lookupConfig*/ true); + if (resolved.resolvedModule) { + return resolved.resolvedModule.resolvedFileName; + } + errors.push(createDiagnostic(ts.Diagnostics.File_0_does_not_exist, extendedConfig)); + return undefined; + } + function getExtendedConfig(sourceFile, extendedConfigPath, host, basePath, resolutionStack, errors) { + var _a; + var extendedResult = readJsonConfigFile(extendedConfigPath, function (path) { return host.readFile(path); }); + if (sourceFile) { + sourceFile.extendedSourceFiles = [extendedResult.fileName]; + } + if (extendedResult.parseDiagnostics.length) { + errors.push.apply(errors, extendedResult.parseDiagnostics); + return undefined; + } + var extendedDirname = ts.getDirectoryPath(extendedConfigPath); + var extendedConfig = parseConfig(/*json*/ undefined, extendedResult, host, extendedDirname, ts.getBaseFileName(extendedConfigPath), resolutionStack, errors); + if (sourceFile && extendedResult.extendedSourceFiles) { + (_a = sourceFile.extendedSourceFiles).push.apply(_a, extendedResult.extendedSourceFiles); + } + if (isSuccessfulParsedTsconfig(extendedConfig)) { + // Update the paths to reflect base path + var relativeDifference_1 = ts.convertToRelativePath(extendedDirname, basePath, ts.identity); + var updatePath_1 = function (path) { return ts.isRootedDiskPath(path) ? path : ts.combinePaths(relativeDifference_1, path); }; + var mapPropertiesInRawIfNotUndefined = function (propertyName) { + if (raw_2[propertyName]) { + raw_2[propertyName] = ts.map(raw_2[propertyName], updatePath_1); + } + }; + var raw_2 = extendedConfig.raw; + mapPropertiesInRawIfNotUndefined("include"); + mapPropertiesInRawIfNotUndefined("exclude"); + mapPropertiesInRawIfNotUndefined("files"); + } + return extendedConfig; + } + function convertCompileOnSaveOptionFromJson(jsonOption, basePath, errors) { + if (!ts.hasProperty(jsonOption, ts.compileOnSaveCommandLineOption.name)) { + return false; + } + var result = convertJsonOption(ts.compileOnSaveCommandLineOption, jsonOption.compileOnSave, basePath, errors); + return typeof result === "boolean" && result; + } + function convertCompilerOptionsFromJson(jsonOptions, basePath, configFileName) { + var errors = []; + var options = convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName); + return { options: options, errors: errors }; + } + ts.convertCompilerOptionsFromJson = convertCompilerOptionsFromJson; + function convertTypeAcquisitionFromJson(jsonOptions, basePath, configFileName) { + var errors = []; + var options = convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName); + return { options: options, errors: errors }; + } + ts.convertTypeAcquisitionFromJson = convertTypeAcquisitionFromJson; + function getDefaultCompilerOptions(configFileName) { + var options = configFileName && ts.getBaseFileName(configFileName) === "jsconfig.json" + ? { allowJs: true, maxNodeModuleJsDepth: 2, allowSyntheticDefaultImports: true, skipLibCheck: true, noEmit: true } + : {}; + return options; + } + function convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName) { + var options = getDefaultCompilerOptions(configFileName); + convertOptionsFromJson(ts.optionDeclarations, jsonOptions, basePath, options, ts.Diagnostics.Unknown_compiler_option_0, errors); + if (configFileName) { + options.configFilePath = ts.normalizeSlashes(configFileName); + } + return options; + } + function getDefaultTypeAcquisition(configFileName) { + return { enable: !!configFileName && ts.getBaseFileName(configFileName) === "jsconfig.json", include: [], exclude: [] }; + } + function convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName) { + var options = getDefaultTypeAcquisition(configFileName); + var typeAcquisition = convertEnableAutoDiscoveryToEnable(jsonOptions); + convertOptionsFromJson(ts.typeAcquisitionDeclarations, typeAcquisition, basePath, options, ts.Diagnostics.Unknown_type_acquisition_option_0, errors); + return options; + } + function convertOptionsFromJson(optionDeclarations, jsonOptions, basePath, defaultOptions, diagnosticMessage, errors) { + if (!jsonOptions) { + return; + } + var optionNameMap = commandLineOptionsToMap(optionDeclarations); + for (var id in jsonOptions) { + var opt = optionNameMap.get(id); + if (opt) { + defaultOptions[opt.name] = convertJsonOption(opt, jsonOptions[id], basePath, errors); + } + else { + errors.push(ts.createCompilerDiagnostic(diagnosticMessage, id)); + } + } + } + function convertJsonOption(opt, value, basePath, errors) { + if (isCompilerOptionsValue(opt, value)) { + var optType = opt.type; + if (optType === "list" && ts.isArray(value)) { + return convertJsonOptionOfListType(opt, value, basePath, errors); + } + else if (!ts.isString(optType)) { + return convertJsonOptionOfCustomType(opt, value, errors); + } + return normalizeNonListOptionValue(opt, basePath, value); + } + else { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, opt.name, getCompilerOptionValueTypeString(opt))); + } + } + function normalizeOptionValue(option, basePath, value) { + if (isNullOrUndefined(value)) + return undefined; + if (option.type === "list") { + var listOption_1 = option; + if (listOption_1.element.isFilePath || !ts.isString(listOption_1.element.type)) { + return ts.filter(ts.map(value, function (v) { return normalizeOptionValue(listOption_1.element, basePath, v); }), function (v) { return !!v; }); + } + return value; + } + else if (!ts.isString(option.type)) { + return option.type.get(ts.isString(value) ? value.toLowerCase() : value); + } + return normalizeNonListOptionValue(option, basePath, value); + } + function normalizeNonListOptionValue(option, basePath, value) { + if (option.isFilePath) { + value = ts.normalizePath(ts.combinePaths(basePath, value)); + if (value === "") { + value = "."; + } + } + return value; + } + function convertJsonOptionOfCustomType(opt, value, errors) { + if (isNullOrUndefined(value)) + return undefined; + var key = value.toLowerCase(); + var val = opt.type.get(key); + if (val !== undefined) { + return val; + } + else { + errors.push(createCompilerDiagnosticForInvalidCustomType(opt)); + } + } + function convertJsonOptionOfListType(option, values, basePath, errors) { + return ts.filter(ts.map(values, function (v) { return convertJsonOption(option.element, v, basePath, errors); }), function (v) { return !!v; }); + } + function trimString(s) { + return typeof s.trim === "function" ? s.trim() : s.replace(/^[\s]+|[\s]+$/g, ""); + } + /** + * Tests for a path that ends in a recursive directory wildcard. + * Matches **, \**, **\, and \**\, but not a**b. + * + * NOTE: used \ in place of / above to avoid issues with multiline comments. + * + * Breakdown: + * (^|\/) # matches either the beginning of the string or a directory separator. + * \*\* # matches the recursive directory wildcard "**". + * \/?$ # matches an optional trailing directory separator at the end of the string. + */ + var invalidTrailingRecursionPattern = /(^|\/)\*\*\/?$/; + /** + * Tests for a path where .. appears after a recursive directory wildcard. + * Matches **\..\*, **\a\..\*, and **\.., but not ..\**\* + * + * NOTE: used \ in place of / above to avoid issues with multiline comments. + * + * Breakdown: + * (^|\/) # matches either the beginning of the string or a directory separator. + * \*\*\/ # matches a recursive directory wildcard "**" followed by a directory separator. + * (.*\/)? # optionally matches any number of characters followed by a directory separator. + * \.\. # matches a parent directory path component ".." + * ($|\/) # matches either the end of the string or a directory separator. + */ + var invalidDotDotAfterRecursiveWildcardPattern = /(^|\/)\*\*\/(.*\/)?\.\.($|\/)/; + /** + * Tests for a path containing a wildcard character in a directory component of the path. + * Matches \*\, \?\, and \a*b\, but not \a\ or \a\*. + * + * NOTE: used \ in place of / above to avoid issues with multiline comments. + * + * Breakdown: + * \/ # matches a directory separator. + * [^/]*? # matches any number of characters excluding directory separators (non-greedy). + * [*?] # matches either a wildcard character (* or ?) + * [^/]* # matches any number of characters excluding directory separators (greedy). + * \/ # matches a directory separator. + */ + var watchRecursivePattern = /\/[^/]*?[*?][^/]*\//; + /** + * Matches the portion of a wildcard path that does not contain wildcards. + * Matches \a of \a\*, or \a\b\c of \a\b\c\?\d. + * + * NOTE: used \ in place of / above to avoid issues with multiline comments. + * + * Breakdown: + * ^ # matches the beginning of the string + * [^*?]* # matches any number of non-wildcard characters + * (?=\/[^/]*[*?]) # lookahead that matches a directory separator followed by + * # a path component that contains at least one wildcard character (* or ?). + */ + var wildcardDirectoryPattern = /^[^*?]*(?=\/[^/]*[*?])/; + /** + * Expands an array of file specifications. + * + * @param filesSpecs The literal file names to include. + * @param includeSpecs The wildcard file specifications to include. + * @param excludeSpecs The wildcard file specifications to exclude. + * @param basePath The base path for any relative file specifications. + * @param options Compiler options. + * @param host The host used to resolve files and directories. + * @param errors An array for diagnostic reporting. + */ + function matchFileNames(filesSpecs, includeSpecs, excludeSpecs, basePath, options, host, errors, extraFileExtensions, jsonSourceFile) { + basePath = ts.normalizePath(basePath); + var validatedIncludeSpecs, validatedExcludeSpecs; + // The exclude spec list is converted into a regular expression, which allows us to quickly + // test whether a file or directory should be excluded before recursively traversing the + // file system. + if (includeSpecs) { + validatedIncludeSpecs = validateSpecs(includeSpecs, errors, /*allowTrailingRecursion*/ false, jsonSourceFile, "include"); + } + if (excludeSpecs) { + validatedExcludeSpecs = validateSpecs(excludeSpecs, errors, /*allowTrailingRecursion*/ true, jsonSourceFile, "exclude"); + } + // Wildcard directories (provided as part of a wildcard path) are stored in a + // file map that marks whether it was a regular wildcard match (with a `*` or `?` token), + // or a recursive directory. This information is used by filesystem watchers to monitor for + // new entries in these paths. + var wildcardDirectories = getWildcardDirectories(validatedIncludeSpecs, validatedExcludeSpecs, basePath, host.useCaseSensitiveFileNames); + var spec = { filesSpecs: filesSpecs, includeSpecs: includeSpecs, excludeSpecs: excludeSpecs, validatedIncludeSpecs: validatedIncludeSpecs, validatedExcludeSpecs: validatedExcludeSpecs, wildcardDirectories: wildcardDirectories }; + return getFileNamesFromConfigSpecs(spec, basePath, options, host, extraFileExtensions); + } + /** + * Gets the file names from the provided config file specs that contain, files, include, exclude and + * other properties needed to resolve the file names + * @param spec The config file specs extracted with file names to include, wildcards to include/exclude and other details + * @param basePath The base path for any relative file specifications. + * @param options Compiler options. + * @param host The host used to resolve files and directories. + * @param extraFileExtensions optionaly file extra file extension information from host + */ + /* @internal */ + function getFileNamesFromConfigSpecs(spec, basePath, options, host, extraFileExtensions) { + if (extraFileExtensions === void 0) { extraFileExtensions = []; } + basePath = ts.normalizePath(basePath); + var keyMapper = host.useCaseSensitiveFileNames ? ts.identity : ts.toLowerCase; + // Literal file names (provided via the "files" array in tsconfig.json) are stored in a + // file map with a possibly case insensitive key. We use this map later when when including + // wildcard paths. + var literalFileMap = ts.createMap(); + // Wildcard paths (provided via the "includes" array in tsconfig.json) are stored in a + // file map with a possibly case insensitive key. We use this map to store paths matched + // via wildcard, and to handle extension priority. + var wildcardFileMap = ts.createMap(); + // Wildcard paths of json files (provided via the "includes" array in tsconfig.json) are stored in a + // file map with a possibly case insensitive key. We use this map to store paths matched + // via wildcard of *.json kind + var wildCardJsonFileMap = ts.createMap(); + var filesSpecs = spec.filesSpecs, validatedIncludeSpecs = spec.validatedIncludeSpecs, validatedExcludeSpecs = spec.validatedExcludeSpecs, wildcardDirectories = spec.wildcardDirectories; + // Rather than requery this for each file and filespec, we query the supported extensions + // once and store it on the expansion context. + var supportedExtensions = ts.getSupportedExtensions(options, extraFileExtensions); + var supportedExtensionsWithJsonIfResolveJsonModule = ts.getSuppoertedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions); + // Literal files are always included verbatim. An "include" or "exclude" specification cannot + // remove a literal file. + if (filesSpecs) { + for (var _i = 0, filesSpecs_1 = filesSpecs; _i < filesSpecs_1.length; _i++) { + var fileName = filesSpecs_1[_i]; + var file = ts.getNormalizedAbsolutePath(fileName, basePath); + literalFileMap.set(keyMapper(file), file); + } + } + var jsonOnlyIncludeRegexes; + if (validatedIncludeSpecs && validatedIncludeSpecs.length > 0) { + var _loop_4 = function (file) { + if (ts.fileExtensionIs(file, ".json" /* Json */)) { + // Valid only if *.json specified + if (!jsonOnlyIncludeRegexes) { + var includes = validatedIncludeSpecs.filter(function (s) { return ts.endsWith(s, ".json" /* Json */); }); + var includeFilePatterns = ts.map(ts.getRegularExpressionsForWildcards(includes, basePath, "files"), function (pattern) { return "^" + pattern + "$"; }); + jsonOnlyIncludeRegexes = includeFilePatterns ? includeFilePatterns.map(function (pattern) { return ts.getRegexFromPattern(pattern, host.useCaseSensitiveFileNames); }) : ts.emptyArray; + } + var includeIndex = ts.findIndex(jsonOnlyIncludeRegexes, function (re) { return re.test(file); }); + if (includeIndex !== -1) { + var key_1 = keyMapper(file); + if (!literalFileMap.has(key_1) && !wildCardJsonFileMap.has(key_1)) { + wildCardJsonFileMap.set(key_1, file); + } + } + return "continue"; + } + // If we have already included a literal or wildcard path with a + // higher priority extension, we should skip this file. + // + // This handles cases where we may encounter both .ts and + // .d.ts (or .js if "allowJs" is enabled) in the same + // directory when they are compilation outputs. + if (hasFileWithHigherPriorityExtension(file, literalFileMap, wildcardFileMap, supportedExtensions, keyMapper)) { + return "continue"; + } + // We may have included a wildcard path with a lower priority + // extension due to the user-defined order of entries in the + // "include" array. If there is a lower priority extension in the + // same directory, we should remove it. + removeWildcardFilesWithLowerPriorityExtension(file, wildcardFileMap, supportedExtensions, keyMapper); + var key = keyMapper(file); + if (!literalFileMap.has(key) && !wildcardFileMap.has(key)) { + wildcardFileMap.set(key, file); + } + }; + for (var _a = 0, _b = host.readDirectory(basePath, supportedExtensionsWithJsonIfResolveJsonModule, validatedExcludeSpecs, validatedIncludeSpecs, /*depth*/ undefined); _a < _b.length; _a++) { + var file = _b[_a]; + _loop_4(file); + } + } + var literalFiles = ts.arrayFrom(literalFileMap.values()); + var wildcardFiles = ts.arrayFrom(wildcardFileMap.values()); + return { + fileNames: literalFiles.concat(wildcardFiles, ts.arrayFrom(wildCardJsonFileMap.values())), + wildcardDirectories: wildcardDirectories, + spec: spec + }; + } + ts.getFileNamesFromConfigSpecs = getFileNamesFromConfigSpecs; + function validateSpecs(specs, errors, allowTrailingRecursion, jsonSourceFile, specKey) { + return specs.filter(function (spec) { + var diag = specToDiagnostic(spec, allowTrailingRecursion); + if (diag !== undefined) { + errors.push(createDiagnostic(diag, spec)); + } + return diag === undefined; + }); + function createDiagnostic(message, spec) { + var element = ts.getTsConfigPropArrayElementValue(jsonSourceFile, specKey, spec); + return element ? + ts.createDiagnosticForNodeInSourceFile(jsonSourceFile, element, message, spec) : + ts.createCompilerDiagnostic(message, spec); + } + } + function specToDiagnostic(spec, allowTrailingRecursion) { + if (!allowTrailingRecursion && invalidTrailingRecursionPattern.test(spec)) { + return ts.Diagnostics.File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0; + } + else if (invalidDotDotAfterRecursiveWildcardPattern.test(spec)) { + return ts.Diagnostics.File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0; + } + } + /** + * Gets directories in a set of include patterns that should be watched for changes. + */ + function getWildcardDirectories(include, exclude, path, useCaseSensitiveFileNames) { + // We watch a directory recursively if it contains a wildcard anywhere in a directory segment + // of the pattern: + // + // /a/b/**/d - Watch /a/b recursively to catch changes to any d in any subfolder recursively + // /a/b/*/d - Watch /a/b recursively to catch any d in any immediate subfolder, even if a new subfolder is added + // /a/b - Watch /a/b recursively to catch changes to anything in any recursive subfoler + // + // We watch a directory without recursion if it contains a wildcard in the file segment of + // the pattern: + // + // /a/b/* - Watch /a/b directly to catch any new file + // /a/b/a?z - Watch /a/b directly to catch any new file matching a?z + var rawExcludeRegex = ts.getRegularExpressionForWildcard(exclude, path, "exclude"); + var excludeRegex = rawExcludeRegex && new RegExp(rawExcludeRegex, useCaseSensitiveFileNames ? "" : "i"); + var wildcardDirectories = {}; + if (include !== undefined) { + var recursiveKeys = []; + for (var _i = 0, include_1 = include; _i < include_1.length; _i++) { + var file = include_1[_i]; + var spec = ts.normalizePath(ts.combinePaths(path, file)); + if (excludeRegex && excludeRegex.test(spec)) { + continue; + } + var match = getWildcardDirectoryFromSpec(spec, useCaseSensitiveFileNames); + if (match) { + var key = match.key, flags = match.flags; + var existingFlags = wildcardDirectories[key]; + if (existingFlags === undefined || existingFlags < flags) { + wildcardDirectories[key] = flags; + if (flags === 1 /* Recursive */) { + recursiveKeys.push(key); + } + } + } + } + // Remove any subpaths under an existing recursively watched directory. + for (var key in wildcardDirectories) { + if (ts.hasProperty(wildcardDirectories, key)) { + for (var _a = 0, recursiveKeys_1 = recursiveKeys; _a < recursiveKeys_1.length; _a++) { + var recursiveKey = recursiveKeys_1[_a]; + if (key !== recursiveKey && ts.containsPath(recursiveKey, key, path, !useCaseSensitiveFileNames)) { + delete wildcardDirectories[key]; + } + } + } + } + } + return wildcardDirectories; + } + function getWildcardDirectoryFromSpec(spec, useCaseSensitiveFileNames) { + var match = wildcardDirectoryPattern.exec(spec); + if (match) { + return { + key: useCaseSensitiveFileNames ? match[0] : match[0].toLowerCase(), + flags: watchRecursivePattern.test(spec) ? 1 /* Recursive */ : 0 /* None */ + }; + } + if (ts.isImplicitGlob(spec)) { + return { key: spec, flags: 1 /* Recursive */ }; + } + return undefined; + } + /** + * Determines whether a literal or wildcard file has already been included that has a higher + * extension priority. + * + * @param file The path to the file. + * @param extensionPriority The priority of the extension. + * @param context The expansion context. + */ + function hasFileWithHigherPriorityExtension(file, literalFiles, wildcardFiles, extensions, keyMapper) { + var extensionPriority = ts.getExtensionPriority(file, extensions); + var adjustedExtensionPriority = ts.adjustExtensionPriority(extensionPriority, extensions); + for (var i = 0 /* Highest */; i < adjustedExtensionPriority; i++) { + var higherPriorityExtension = extensions[i]; + var higherPriorityPath = keyMapper(ts.changeExtension(file, higherPriorityExtension)); + if (literalFiles.has(higherPriorityPath) || wildcardFiles.has(higherPriorityPath)) { + return true; + } + } + return false; + } + /** + * Removes files included via wildcard expansion with a lower extension priority that have + * already been included. + * + * @param file The path to the file. + * @param extensionPriority The priority of the extension. + * @param context The expansion context. + */ + function removeWildcardFilesWithLowerPriorityExtension(file, wildcardFiles, extensions, keyMapper) { + var extensionPriority = ts.getExtensionPriority(file, extensions); + var nextExtensionPriority = ts.getNextLowestExtensionPriority(extensionPriority, extensions); + for (var i = nextExtensionPriority; i < extensions.length; i++) { + var lowerPriorityExtension = extensions[i]; + var lowerPriorityPath = keyMapper(ts.changeExtension(file, lowerPriorityExtension)); + wildcardFiles.delete(lowerPriorityPath); + } + } + /** + * Produces a cleaned version of compiler options with personally identifying info (aka, paths) removed. + * Also converts enum values back to strings. + */ + /* @internal */ + function convertCompilerOptionsForTelemetry(opts) { + var out = {}; + for (var key in opts) { + if (opts.hasOwnProperty(key)) { + var type = getOptionFromName(key); + if (type !== undefined) { // Ignore unknown options + out[key] = getOptionValueWithEmptyStrings(opts[key], type); + } + } + } + return out; + } + ts.convertCompilerOptionsForTelemetry = convertCompilerOptionsForTelemetry; + function getOptionValueWithEmptyStrings(value, option) { + switch (option.type) { + case "object": // "paths". Can't get any useful information from the value since we blank out strings, so just return "". + return ""; + case "string": // Could be any arbitrary string -- use empty string instead. + return ""; + case "number": // Allow numbers, but be sure to check it's actually a number. + return typeof value === "number" ? value : ""; + case "boolean": + return typeof value === "boolean" ? value : ""; + case "list": + var elementType_1 = option.element; + return ts.isArray(value) ? value.map(function (v) { return getOptionValueWithEmptyStrings(v, elementType_1); }) : ""; + default: + return ts.forEachEntry(option.type, function (optionEnumValue, optionStringValue) { + if (optionEnumValue === value) { + return optionStringValue; + } + }); // TODO: GH#18217 + } + } +})(ts || (ts = {})); +var ts; +(function (ts) { + function trace(host) { + host.trace(ts.formatMessage.apply(undefined, arguments)); + } + ts.trace = trace; + /* @internal */ + function isTraceEnabled(compilerOptions, host) { + return !!compilerOptions.traceResolution && host.trace !== undefined; + } + ts.isTraceEnabled = isTraceEnabled; + function withPackageId(packageId, r) { + return r && { path: r.path, extension: r.ext, packageId: packageId }; + } + function noPackageId(r) { + return withPackageId(/*packageId*/ undefined, r); + } + function removeIgnoredPackageId(r) { + if (r) { + ts.Debug.assert(r.packageId === undefined); + return { path: r.path, ext: r.extension }; + } + } + /** + * Kinds of file that we are currently looking for. + * Typically there is one pass with Extensions.TypeScript, then a second pass with Extensions.JavaScript. + */ + var Extensions; + (function (Extensions) { + Extensions[Extensions["TypeScript"] = 0] = "TypeScript"; + Extensions[Extensions["JavaScript"] = 1] = "JavaScript"; + Extensions[Extensions["Json"] = 2] = "Json"; + Extensions[Extensions["TSConfig"] = 3] = "TSConfig"; + Extensions[Extensions["DtsOnly"] = 4] = "DtsOnly"; /** Only '.d.ts' */ + })(Extensions || (Extensions = {})); + /** Used with `Extensions.DtsOnly` to extract the path from TypeScript results. */ + function resolvedTypeScriptOnly(resolved) { + if (!resolved) { + return undefined; + } + ts.Debug.assert(ts.extensionIsTS(resolved.extension)); + return { fileName: resolved.path, packageId: resolved.packageId }; + } + function createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations) { + return { + resolvedModule: resolved && { resolvedFileName: resolved.path, originalPath: resolved.originalPath === true ? undefined : resolved.originalPath, extension: resolved.extension, isExternalLibraryImport: isExternalLibraryImport, packageId: resolved.packageId }, + failedLookupLocations: failedLookupLocations + }; + } + function readPackageJsonField(jsonContent, fieldName, typeOfTag, state) { + if (!ts.hasProperty(jsonContent, fieldName)) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_does_not_have_a_0_field, fieldName); + } + return; + } + var value = jsonContent[fieldName]; + if (typeof value !== typeOfTag || value === null) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_1_got_2, fieldName, typeOfTag, value === null ? "null" : typeof value); + } + return; + } + return value; + } + function readPackageJsonPathField(jsonContent, fieldName, baseDirectory, state) { + var fileName = readPackageJsonField(jsonContent, fieldName, "string", state); + if (fileName === undefined) + return; + var path = ts.normalizePath(ts.combinePaths(baseDirectory, fileName)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, fileName, path); + } + return path; + } + function readPackageJsonTypesFields(jsonContent, baseDirectory, state) { + return readPackageJsonPathField(jsonContent, "typings", baseDirectory, state) + || readPackageJsonPathField(jsonContent, "types", baseDirectory, state); + } + function readPackageJsonTSConfigField(jsonContent, baseDirectory, state) { + return readPackageJsonPathField(jsonContent, "tsconfig", baseDirectory, state); + } + function readPackageJsonMainField(jsonContent, baseDirectory, state) { + return readPackageJsonPathField(jsonContent, "main", baseDirectory, state); + } + function readPackageJsonTypesVersionsField(jsonContent, state) { + var typesVersions = readPackageJsonField(jsonContent, "typesVersions", "object", state); + if (typesVersions === undefined) + return; + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_field_with_version_specific_path_mappings); + } + return typesVersions; + } + function readPackageJsonTypesVersionPaths(jsonContent, state) { + var typesVersions = readPackageJsonTypesVersionsField(jsonContent, state); + if (typesVersions === undefined) + return; + if (state.traceEnabled) { + for (var key in typesVersions) { + if (ts.hasProperty(typesVersions, key) && !ts.VersionRange.tryParse(key)) { + trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range, key); + } + } + } + var result = getPackageJsonTypesVersionsPaths(typesVersions); + if (!result) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_does_not_have_a_typesVersions_entry_that_matches_version_0, ts.versionMajorMinor); + } + return; + } + var bestVersionKey = result.version, bestVersionPaths = result.paths; + if (typeof bestVersionPaths !== "object") { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_1_got_2, "typesVersions['" + bestVersionKey + "']", "object", typeof bestVersionPaths); + } + return; + } + return result; + } + var typeScriptVersion; + /* @internal */ + function getPackageJsonTypesVersionsPaths(typesVersions) { + if (!typeScriptVersion) + typeScriptVersion = new ts.Version(ts.version); + for (var key in typesVersions) { + if (!ts.hasProperty(typesVersions, key)) + continue; + var keyRange = ts.VersionRange.tryParse(key); + if (keyRange === undefined) { + continue; + } + // return the first entry whose range matches the current compiler version. + if (keyRange.test(typeScriptVersion)) { + return { version: key, paths: typesVersions[key] }; + } + } + } + ts.getPackageJsonTypesVersionsPaths = getPackageJsonTypesVersionsPaths; + function getEffectiveTypeRoots(options, host) { + if (options.typeRoots) { + return options.typeRoots; + } + var currentDirectory; + if (options.configFilePath) { + currentDirectory = ts.getDirectoryPath(options.configFilePath); + } + else if (host.getCurrentDirectory) { + currentDirectory = host.getCurrentDirectory(); + } + if (currentDirectory !== undefined) { + return getDefaultTypeRoots(currentDirectory, host); + } + } + ts.getEffectiveTypeRoots = getEffectiveTypeRoots; + /** + * Returns the path to every node_modules/@types directory from some ancestor directory. + * Returns undefined if there are none. + */ + function getDefaultTypeRoots(currentDirectory, host) { + if (!host.directoryExists) { + return [ts.combinePaths(currentDirectory, nodeModulesAtTypes)]; + // And if it doesn't exist, tough. + } + var typeRoots; + ts.forEachAncestorDirectory(ts.normalizePath(currentDirectory), function (directory) { + var atTypes = ts.combinePaths(directory, nodeModulesAtTypes); + if (host.directoryExists(atTypes)) { + (typeRoots || (typeRoots = [])).push(atTypes); + } + return undefined; + }); + return typeRoots; + } + var nodeModulesAtTypes = ts.combinePaths("node_modules", "@types"); + /** + * @param {string | undefined} containingFile - file that contains type reference directive, can be undefined if containing file is unknown. + * This is possible in case if resolution is performed for directives specified via 'types' parameter. In this case initial path for secondary lookups + * is assumed to be the same as root directory of the project. + */ + function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host, redirectedReference) { + var traceEnabled = isTraceEnabled(options, host); + if (redirectedReference) { + options = redirectedReference.commandLine.options; + } + var failedLookupLocations = []; + var moduleResolutionState = { compilerOptions: options, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; + var typeRoots = getEffectiveTypeRoots(options, host); + if (traceEnabled) { + if (containingFile === undefined) { + if (typeRoots === undefined) { + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set, typeReferenceDirectiveName); + } + else { + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1, typeReferenceDirectiveName, typeRoots); + } + } + else { + if (typeRoots === undefined) { + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set, typeReferenceDirectiveName, containingFile); + } + else { + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_2, typeReferenceDirectiveName, containingFile, typeRoots); + } + } + if (redirectedReference) { + trace(host, ts.Diagnostics.Using_compiler_options_of_project_reference_redirect_0, redirectedReference.sourceFile.fileName); + } + } + var resolved = primaryLookup(); + var primary = true; + if (!resolved) { + resolved = secondaryLookup(); + primary = false; + } + var resolvedTypeReferenceDirective; + if (resolved) { + var fileName = resolved.fileName, packageId = resolved.packageId; + var resolvedFileName = options.preserveSymlinks ? fileName : realPath(fileName, host, traceEnabled); + if (traceEnabled) { + trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFileName, primary); + } + resolvedTypeReferenceDirective = { primary: primary, resolvedFileName: resolvedFileName, packageId: packageId, isExternalLibraryImport: pathContainsNodeModules(fileName) }; + } + return { resolvedTypeReferenceDirective: resolvedTypeReferenceDirective, failedLookupLocations: failedLookupLocations }; + function primaryLookup() { + // Check primary library paths + if (typeRoots && typeRoots.length) { + if (traceEnabled) { + trace(host, ts.Diagnostics.Resolving_with_primary_search_path_0, typeRoots.join(", ")); + } + return ts.firstDefined(typeRoots, function (typeRoot) { + var candidate = ts.combinePaths(typeRoot, typeReferenceDirectiveName); + var candidateDirectory = ts.getDirectoryPath(candidate); + var directoryExists = ts.directoryProbablyExists(candidateDirectory, host); + if (!directoryExists && traceEnabled) { + trace(host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, candidateDirectory); + } + return resolvedTypeScriptOnly(loadNodeModuleFromDirectory(Extensions.DtsOnly, candidate, !directoryExists, moduleResolutionState)); + }); + } + else { + if (traceEnabled) { + trace(host, ts.Diagnostics.Root_directory_cannot_be_determined_skipping_primary_search_paths); + } + } + } + function secondaryLookup() { + var initialLocationForSecondaryLookup = containingFile && ts.getDirectoryPath(containingFile); + if (initialLocationForSecondaryLookup !== undefined) { + // check secondary locations + if (traceEnabled) { + trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup); + } + var result = void 0; + if (!ts.isExternalModuleNameRelative(typeReferenceDirectiveName)) { + var searchResult = loadModuleFromNearestNodeModulesDirectory(Extensions.DtsOnly, typeReferenceDirectiveName, initialLocationForSecondaryLookup, moduleResolutionState, /*cache*/ undefined, /*redirectedReference*/ undefined); + result = searchResult && searchResult.value; + } + else { + var candidate = ts.normalizePathAndParts(ts.combinePaths(initialLocationForSecondaryLookup, typeReferenceDirectiveName)).path; + result = nodeLoadModuleByRelativeName(Extensions.DtsOnly, candidate, /*onlyRecordFailures*/ false, moduleResolutionState, /*considerPackageJson*/ true); + } + var resolvedFile = resolvedTypeScriptOnly(result); + if (!resolvedFile && traceEnabled) { + trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName); + } + return resolvedFile; + } + else { + if (traceEnabled) { + trace(host, ts.Diagnostics.Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder); + } + } + } + } + ts.resolveTypeReferenceDirective = resolveTypeReferenceDirective; + /** + * Given a set of options, returns the set of type directive names + * that should be included for this program automatically. + * This list could either come from the config file, + * or from enumerating the types root + initial secondary types lookup location. + * More type directives might appear in the program later as a result of loading actual source files; + * this list is only the set of defaults that are implicitly included. + */ + function getAutomaticTypeDirectiveNames(options, host) { + // Use explicit type list from tsconfig.json + if (options.types) { + return options.types; + } + // Walk the primary type lookup locations + var result = []; + if (host.directoryExists && host.getDirectories) { + var typeRoots = getEffectiveTypeRoots(options, host); + if (typeRoots) { + for (var _i = 0, typeRoots_1 = typeRoots; _i < typeRoots_1.length; _i++) { + var root = typeRoots_1[_i]; + if (host.directoryExists(root)) { + for (var _a = 0, _b = host.getDirectories(root); _a < _b.length; _a++) { + var typeDirectivePath = _b[_a]; + var normalized = ts.normalizePath(typeDirectivePath); + var packageJsonPath = ts.combinePaths(root, normalized, "package.json"); + // `types-publisher` sometimes creates packages with `"typings": null` for packages that don't provide their own types. + // See `createNotNeededPackageJSON` in the types-publisher` repo. + // tslint:disable-next-line:no-null-keyword + var isNotNeededPackage = host.fileExists(packageJsonPath) && ts.readJson(packageJsonPath, host).typings === null; + if (!isNotNeededPackage) { + var baseFileName = ts.getBaseFileName(normalized); + // At this stage, skip results with leading dot. + if (baseFileName.charCodeAt(0) !== 46 /* dot */) { + // Return just the type directive names + result.push(baseFileName); + } + } + } + } + } + } + } + return result; + } + ts.getAutomaticTypeDirectiveNames = getAutomaticTypeDirectiveNames; + function createModuleResolutionCache(currentDirectory, getCanonicalFileName) { + return createModuleResolutionCacheWithMaps(createCacheWithRedirects(), createCacheWithRedirects(), currentDirectory, getCanonicalFileName); + } + ts.createModuleResolutionCache = createModuleResolutionCache; + /*@internal*/ + function createCacheWithRedirects() { + var ownMap = ts.createMap(); + var redirectsMap = ts.createMap(); + return { + ownMap: ownMap, + redirectsMap: redirectsMap, + getOrCreateMapOfCacheRedirects: getOrCreateMapOfCacheRedirects, + clear: clear + }; + function getOrCreateMapOfCacheRedirects(redirectedReference) { + if (!redirectedReference) { + return ownMap; + } + var path = redirectedReference.sourceFile.path; + var redirects = redirectsMap.get(path); + if (!redirects) { + redirects = ts.createMap(); + redirectsMap.set(path, redirects); + } + return redirects; + } + function clear() { + ownMap.clear(); + redirectsMap.clear(); + } + } + ts.createCacheWithRedirects = createCacheWithRedirects; + /*@internal*/ + function createModuleResolutionCacheWithMaps(directoryToModuleNameMap, moduleNameToDirectoryMap, currentDirectory, getCanonicalFileName) { + return { getOrCreateCacheForDirectory: getOrCreateCacheForDirectory, getOrCreateCacheForModuleName: getOrCreateCacheForModuleName }; + function getOrCreateCacheForDirectory(directoryName, redirectedReference) { + var path = ts.toPath(directoryName, currentDirectory, getCanonicalFileName); + return getOrCreateCache(directoryToModuleNameMap, redirectedReference, path, ts.createMap); + } + function getOrCreateCacheForModuleName(nonRelativeModuleName, redirectedReference) { + ts.Debug.assert(!ts.isExternalModuleNameRelative(nonRelativeModuleName)); + return getOrCreateCache(moduleNameToDirectoryMap, redirectedReference, nonRelativeModuleName, createPerModuleNameCache); + } + function getOrCreateCache(cacheWithRedirects, redirectedReference, key, create) { + var cache = cacheWithRedirects.getOrCreateMapOfCacheRedirects(redirectedReference); + var result = cache.get(key); + if (!result) { + result = create(); + cache.set(key, result); + } + return result; + } + function createPerModuleNameCache() { + var directoryPathMap = ts.createMap(); + return { get: get, set: set }; + function get(directory) { + return directoryPathMap.get(ts.toPath(directory, currentDirectory, getCanonicalFileName)); + } + /** + * At first this function add entry directory -> module resolution result to the table. + * Then it computes the set of parent folders for 'directory' that should have the same module resolution result + * and for every parent folder in set it adds entry: parent -> module resolution. . + * Lets say we first directory name: /a/b/c/d/e and resolution result is: /a/b/bar.ts. + * Set of parent folders that should have the same result will be: + * [ + * /a/b/c/d, /a/b/c, /a/b + * ] + * this means that request for module resolution from file in any of these folder will be immediately found in cache. + */ + function set(directory, result) { + var path = ts.toPath(directory, currentDirectory, getCanonicalFileName); + // if entry is already in cache do nothing + if (directoryPathMap.has(path)) { + return; + } + directoryPathMap.set(path, result); + var resolvedFileName = result.resolvedModule && + (result.resolvedModule.originalPath || result.resolvedModule.resolvedFileName); + // find common prefix between directory and resolved file name + // this common prefix should be the shortest path that has the same resolution + // directory: /a/b/c/d/e + // resolvedFileName: /a/b/foo.d.ts + // commonPrefix: /a/b + // for failed lookups cache the result for every directory up to root + var commonPrefix = resolvedFileName && getCommonPrefix(path, resolvedFileName); + var current = path; + while (current !== commonPrefix) { + var parent = ts.getDirectoryPath(current); + if (parent === current || directoryPathMap.has(parent)) { + break; + } + directoryPathMap.set(parent, result); + current = parent; + } + } + function getCommonPrefix(directory, resolution) { + var resolutionDirectory = ts.toPath(ts.getDirectoryPath(resolution), currentDirectory, getCanonicalFileName); + // find first position where directory and resolution differs + var i = 0; + var limit = Math.min(directory.length, resolutionDirectory.length); + while (i < limit && directory.charCodeAt(i) === resolutionDirectory.charCodeAt(i)) { + i++; + } + if (i === directory.length && (resolutionDirectory.length === i || resolutionDirectory[i] === ts.directorySeparator)) { + return directory; + } + var rootLength = ts.getRootLength(directory); + if (i < rootLength) { + return undefined; + } + var sep = directory.lastIndexOf(ts.directorySeparator, i - 1); + if (sep === -1) { + return undefined; + } + return directory.substr(0, Math.max(sep, rootLength)); + } + } + } + ts.createModuleResolutionCacheWithMaps = createModuleResolutionCacheWithMaps; + function resolveModuleNameFromCache(moduleName, containingFile, cache) { + var containingDirectory = ts.getDirectoryPath(containingFile); + var perFolderCache = cache && cache.getOrCreateCacheForDirectory(containingDirectory); + return perFolderCache && perFolderCache.get(moduleName); + } + ts.resolveModuleNameFromCache = resolveModuleNameFromCache; + function resolveModuleName(moduleName, containingFile, compilerOptions, host, cache, redirectedReference) { + var traceEnabled = isTraceEnabled(compilerOptions, host); + if (redirectedReference) { + compilerOptions = redirectedReference.commandLine.options; + } + if (traceEnabled) { + trace(host, ts.Diagnostics.Resolving_module_0_from_1, moduleName, containingFile); + if (redirectedReference) { + trace(host, ts.Diagnostics.Using_compiler_options_of_project_reference_redirect_0, redirectedReference.sourceFile.fileName); + } + } + var containingDirectory = ts.getDirectoryPath(containingFile); + var perFolderCache = cache && cache.getOrCreateCacheForDirectory(containingDirectory, redirectedReference); + var result = perFolderCache && perFolderCache.get(moduleName); + if (result) { + if (traceEnabled) { + trace(host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory); + } + } + else { + var moduleResolution = compilerOptions.moduleResolution; + if (moduleResolution === undefined) { + moduleResolution = ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS ? ts.ModuleResolutionKind.NodeJs : ts.ModuleResolutionKind.Classic; + if (traceEnabled) { + trace(host, ts.Diagnostics.Module_resolution_kind_is_not_specified_using_0, ts.ModuleResolutionKind[moduleResolution]); + } + } + else { + if (traceEnabled) { + trace(host, ts.Diagnostics.Explicitly_specified_module_resolution_kind_Colon_0, ts.ModuleResolutionKind[moduleResolution]); + } + } + switch (moduleResolution) { + case ts.ModuleResolutionKind.NodeJs: + result = nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference); + break; + case ts.ModuleResolutionKind.Classic: + result = classicNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference); + break; + default: + return ts.Debug.fail("Unexpected moduleResolution: " + moduleResolution); + } + if (perFolderCache) { + perFolderCache.set(moduleName, result); + if (!ts.isExternalModuleNameRelative(moduleName)) { + // put result in per-module name cache + cache.getOrCreateCacheForModuleName(moduleName, redirectedReference).set(containingDirectory, result); + } + } + } + if (traceEnabled) { + if (result.resolvedModule) { + trace(host, ts.Diagnostics.Module_name_0_was_successfully_resolved_to_1, moduleName, result.resolvedModule.resolvedFileName); + } + else { + trace(host, ts.Diagnostics.Module_name_0_was_not_resolved, moduleName); + } + } + return result; + } + ts.resolveModuleName = resolveModuleName; + /** + * Any module resolution kind can be augmented with optional settings: 'baseUrl', 'paths' and 'rootDirs' - they are used to + * mitigate differences between design time structure of the project and its runtime counterpart so the same import name + * can be resolved successfully by TypeScript compiler and runtime module loader. + * If these settings are set then loading procedure will try to use them to resolve module name and it can of failure it will + * fallback to standard resolution routine. + * + * - baseUrl - this setting controls how non-relative module names are resolved. If this setting is specified then non-relative + * names will be resolved relative to baseUrl: i.e. if baseUrl is '/a/b' then candidate location to resolve module name 'c/d' will + * be '/a/b/c/d' + * - paths - this setting can only be used when baseUrl is specified. allows to tune how non-relative module names + * will be resolved based on the content of the module name. + * Structure of 'paths' compiler options + * 'paths': { + * pattern-1: [...substitutions], + * pattern-2: [...substitutions], + * ... + * pattern-n: [...substitutions] + * } + * Pattern here is a string that can contain zero or one '*' character. During module resolution module name will be matched against + * all patterns in the list. Matching for patterns that don't contain '*' means that module name must be equal to pattern respecting the case. + * If pattern contains '*' then to match pattern "*" module name must start with the and end with . + * denotes part of the module name between and . + * If module name can be matches with multiple patterns then pattern with the longest prefix will be picked. + * After selecting pattern we'll use list of substitutions to get candidate locations of the module and the try to load module + * from the candidate location. + * Substitution is a string that can contain zero or one '*'. To get candidate location from substitution we'll pick every + * substitution in the list and replace '*' with string. If candidate location is not rooted it + * will be converted to absolute using baseUrl. + * For example: + * baseUrl: /a/b/c + * "paths": { + * // match all module names + * "*": [ + * "*", // use matched name as is, + * // will be looked as /a/b/c/ + * + * "folder1/*" // substitution will convert matched name to 'folder1/', + * // since it is not rooted then final candidate location will be /a/b/c/folder1/ + * ], + * // match module names that start with 'components/' + * "components/*": [ "/root/components/*" ] // substitution will convert /components/folder1/ to '/root/components/folder1/', + * // it is rooted so it will be final candidate location + * } + * + * 'rootDirs' allows the project to be spreaded across multiple locations and resolve modules with relative names as if + * they were in the same location. For example lets say there are two files + * '/local/src/content/file1.ts' + * '/shared/components/contracts/src/content/protocols/file2.ts' + * After bundling content of '/shared/components/contracts/src' will be merged with '/local/src' so + * if file1 has the following import 'import {x} from "./protocols/file2"' it will be resolved successfully in runtime. + * 'rootDirs' provides the way to tell compiler that in order to get the whole project it should behave as if content of all + * root dirs were merged together. + * I.e. for the example above 'rootDirs' will have two entries: [ '/local/src', '/shared/components/contracts/src' ]. + * Compiler will first convert './protocols/file2' into absolute path relative to the location of containing file: + * '/local/src/content/protocols/file2' and try to load it - failure. + * Then it will search 'rootDirs' looking for a longest matching prefix of this absolute path and if such prefix is found - absolute path will + * be converted to a path relative to found rootDir entry './content/protocols/file2' (*). As a last step compiler will check all remaining + * entries in 'rootDirs', use them to build absolute path out of (*) and try to resolve module from this location. + */ + function tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, state) { + var resolved = tryLoadModuleUsingPathsIfEligible(extensions, moduleName, loader, state); + if (resolved) + return resolved.value; + if (!ts.isExternalModuleNameRelative(moduleName)) { + return tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, state); + } + else { + return tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, state); + } + } + function tryLoadModuleUsingPathsIfEligible(extensions, moduleName, loader, state) { + var _a = state.compilerOptions, baseUrl = _a.baseUrl, paths = _a.paths; + if (baseUrl && paths && !ts.pathIsRelative(moduleName)) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, baseUrl, moduleName); + trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName); + } + return tryLoadModuleUsingPaths(extensions, moduleName, baseUrl, paths, loader, /*onlyRecordFailures*/ false, state); + } + } + function tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, state) { + if (!state.compilerOptions.rootDirs) { + return undefined; + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0, moduleName); + } + var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); + var matchedRootDir; + var matchedNormalizedPrefix; + for (var _i = 0, _a = state.compilerOptions.rootDirs; _i < _a.length; _i++) { + var rootDir = _a[_i]; + // rootDirs are expected to be absolute + // in case of tsconfig.json this will happen automatically - compiler will expand relative names + // using location of tsconfig.json as base location + var normalizedRoot = ts.normalizePath(rootDir); + if (!ts.endsWith(normalizedRoot, ts.directorySeparator)) { + normalizedRoot += ts.directorySeparator; + } + var isLongestMatchingPrefix = ts.startsWith(candidate, normalizedRoot) && + (matchedNormalizedPrefix === undefined || matchedNormalizedPrefix.length < normalizedRoot.length); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Checking_if_0_is_the_longest_matching_prefix_for_1_2, normalizedRoot, candidate, isLongestMatchingPrefix); + } + if (isLongestMatchingPrefix) { + matchedNormalizedPrefix = normalizedRoot; + matchedRootDir = rootDir; + } + } + if (matchedNormalizedPrefix) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Longest_matching_prefix_for_0_is_1, candidate, matchedNormalizedPrefix); + } + var suffix = candidate.substr(matchedNormalizedPrefix.length); + // first - try to load from a initial location + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, matchedNormalizedPrefix, candidate); + } + var resolvedFileName = loader(extensions, candidate, !ts.directoryProbablyExists(containingDirectory, state.host), state); + if (resolvedFileName) { + return resolvedFileName; + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Trying_other_entries_in_rootDirs); + } + // then try to resolve using remaining entries in rootDirs + for (var _b = 0, _c = state.compilerOptions.rootDirs; _b < _c.length; _b++) { + var rootDir = _c[_b]; + if (rootDir === matchedRootDir) { + // skip the initially matched entry + continue; + } + var candidate_1 = ts.combinePaths(ts.normalizePath(rootDir), suffix); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, rootDir, candidate_1); + } + var baseDirectory = ts.getDirectoryPath(candidate_1); + var resolvedFileName_1 = loader(extensions, candidate_1, !ts.directoryProbablyExists(baseDirectory, state.host), state); + if (resolvedFileName_1) { + return resolvedFileName_1; + } + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Module_resolution_using_rootDirs_has_failed); + } + } + return undefined; + } + function tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, state) { + var baseUrl = state.compilerOptions.baseUrl; + if (!baseUrl) { + return undefined; + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, baseUrl, moduleName); + } + var candidate = ts.normalizePath(ts.combinePaths(baseUrl, moduleName)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, baseUrl, candidate); + } + return loader(extensions, candidate, !ts.directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); + } + /** + * Expose resolution logic to allow us to use Node module resolution logic from arbitrary locations. + * No way to do this with `require()`: https://github.com/nodejs/node/issues/5963 + * Throws an error if the module can't be resolved. + */ + /* @internal */ + function resolveJSModule(moduleName, initialDir, host) { + var _a = tryResolveJSModuleWorker(moduleName, initialDir, host), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; + if (!resolvedModule) { + throw new Error("Could not resolve JS module '" + moduleName + "' starting at '" + initialDir + "'. Looked in: " + failedLookupLocations.join(", ")); + } + return resolvedModule.resolvedFileName; + } + ts.resolveJSModule = resolveJSModule; + /* @internal */ + function tryResolveJSModule(moduleName, initialDir, host) { + var resolvedModule = tryResolveJSModuleWorker(moduleName, initialDir, host).resolvedModule; + return resolvedModule && resolvedModule.resolvedFileName; + } + ts.tryResolveJSModule = tryResolveJSModule; + var jsOnlyExtensions = [Extensions.JavaScript]; + var tsExtensions = [Extensions.TypeScript, Extensions.JavaScript]; + var tsPlusJsonExtensions = tsExtensions.concat([Extensions.Json]); + var tsconfigExtensions = [Extensions.TSConfig]; + function tryResolveJSModuleWorker(moduleName, initialDir, host) { + return nodeModuleNameResolverWorker(moduleName, initialDir, { moduleResolution: ts.ModuleResolutionKind.NodeJs, allowJs: true }, host, /*cache*/ undefined, jsOnlyExtensions, /*redirectedReferences*/ undefined); + } + function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference, lookupConfig) { + return nodeModuleNameResolverWorker(moduleName, ts.getDirectoryPath(containingFile), compilerOptions, host, cache, lookupConfig ? tsconfigExtensions : (compilerOptions.resolveJsonModule ? tsPlusJsonExtensions : tsExtensions), redirectedReference); + } + ts.nodeModuleNameResolver = nodeModuleNameResolver; + function nodeModuleNameResolverWorker(moduleName, containingDirectory, compilerOptions, host, cache, extensions, redirectedReference) { + var traceEnabled = isTraceEnabled(compilerOptions, host); + var failedLookupLocations = []; + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; + var result = ts.forEach(extensions, function (ext) { return tryResolve(ext); }); + if (result && result.value) { + var _a = result.value, resolved = _a.resolved, isExternalLibraryImport = _a.isExternalLibraryImport; + return createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations); + } + return { resolvedModule: undefined, failedLookupLocations: failedLookupLocations }; + function tryResolve(extensions) { + var loader = function (extensions, candidate, onlyRecordFailures, state) { return nodeLoadModuleByRelativeName(extensions, candidate, onlyRecordFailures, state, /*considerPackageJson*/ true); }; + var resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, state); + if (resolved) { + return toSearchResult({ resolved: resolved, isExternalLibraryImport: pathContainsNodeModules(resolved.path) }); + } + if (!ts.isExternalModuleNameRelative(moduleName)) { + if (traceEnabled) { + trace(host, ts.Diagnostics.Loading_module_0_from_node_modules_folder_target_file_type_1, moduleName, Extensions[extensions]); + } + var resolved_1 = loadModuleFromNearestNodeModulesDirectory(extensions, moduleName, containingDirectory, state, cache, redirectedReference); + if (!resolved_1) + return undefined; + var resolvedValue = resolved_1.value; + if (!compilerOptions.preserveSymlinks && resolvedValue && !resolvedValue.originalPath) { + var path = realPath(resolvedValue.path, host, traceEnabled); + var originalPath = path === resolvedValue.path ? undefined : resolvedValue.path; + resolvedValue = __assign({}, resolvedValue, { path: path, originalPath: originalPath }); + } + // For node_modules lookups, get the real path so that multiple accesses to an `npm link`-ed module do not create duplicate files. + return { value: resolvedValue && { resolved: resolvedValue, isExternalLibraryImport: true } }; + } + else { + var _a = ts.normalizePathAndParts(ts.combinePaths(containingDirectory, moduleName)), candidate = _a.path, parts = _a.parts; + var resolved_2 = nodeLoadModuleByRelativeName(extensions, candidate, /*onlyRecordFailures*/ false, state, /*considerPackageJson*/ true); + // Treat explicit "node_modules" import as an external library import. + return resolved_2 && toSearchResult({ resolved: resolved_2, isExternalLibraryImport: ts.contains(parts, "node_modules") }); + } + } + } + function realPath(path, host, traceEnabled) { + if (!host.realpath) { + return path; + } + var real = ts.normalizePath(host.realpath(path)); + if (traceEnabled) { + trace(host, ts.Diagnostics.Resolving_real_path_for_0_result_1, path, real); + } + ts.Debug.assert(host.fileExists(real), path + " linked to nonexistent file " + real); // tslint:disable-line + return real; + } + function nodeLoadModuleByRelativeName(extensions, candidate, onlyRecordFailures, state, considerPackageJson) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1, candidate, Extensions[extensions]); + } + if (!ts.hasTrailingDirectorySeparator(candidate)) { + if (!onlyRecordFailures) { + var parentOfCandidate = ts.getDirectoryPath(candidate); + if (!ts.directoryProbablyExists(parentOfCandidate, state.host)) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, parentOfCandidate); + } + onlyRecordFailures = true; + } + } + var resolvedFromFile = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state); + if (resolvedFromFile) { + var nm = considerPackageJson ? parseNodeModuleFromPath(resolvedFromFile) : undefined; + var packageInfo = nm && getPackageJsonInfo(nm.packageDirectory, nm.subModuleName, /*onlyRecordFailures*/ false, state); + var packageId = packageInfo && packageInfo.packageId; + return withPackageId(packageId, resolvedFromFile); + } + } + if (!onlyRecordFailures) { + var candidateExists = ts.directoryProbablyExists(candidate, state.host); + if (!candidateExists) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, candidate); + } + onlyRecordFailures = true; + } + } + return loadNodeModuleFromDirectory(extensions, candidate, onlyRecordFailures, state, considerPackageJson); + } + /*@internal*/ + ts.nodeModulesPathPart = "/node_modules/"; + /*@internal*/ + function pathContainsNodeModules(path) { + return ts.stringContains(path, ts.nodeModulesPathPart); + } + ts.pathContainsNodeModules = pathContainsNodeModules; + /** + * This will be called on the successfully resolved path from `loadModuleFromFile`. + * (Not neeeded for `loadModuleFromNodeModules` as that looks up the `package.json` as part of resolution.) + * + * packageDirectory is the directory of the package itself. + * subModuleName is the path within the package. + * For `blah/node_modules/foo/index.d.ts` this is { packageDirectory: "foo", subModuleName: "index.d.ts" }. (Part before "/node_modules/" is ignored.) + * For `/node_modules/foo/bar.d.ts` this is { packageDirectory: "foo", subModuleName": "bar/index.d.ts" }. + * For `/node_modules/@types/foo/bar/index.d.ts` this is { packageDirectory: "@types/foo", subModuleName: "bar/index.d.ts" }. + * For `/node_modules/foo/bar/index.d.ts` this is { packageDirectory: "foo", subModuleName": "bar/index.d.ts" }. + */ + function parseNodeModuleFromPath(resolved) { + var path = ts.normalizePath(resolved.path); + var idx = path.lastIndexOf(ts.nodeModulesPathPart); + if (idx === -1) { + return undefined; + } + var indexAfterNodeModules = idx + ts.nodeModulesPathPart.length; + var indexAfterPackageName = moveToNextDirectorySeparatorIfAvailable(path, indexAfterNodeModules); + if (path.charCodeAt(indexAfterNodeModules) === 64 /* at */) { + indexAfterPackageName = moveToNextDirectorySeparatorIfAvailable(path, indexAfterPackageName); + } + var packageDirectory = path.slice(0, indexAfterPackageName); + var subModuleName = ts.removeExtension(path.slice(indexAfterPackageName + 1), resolved.ext) + ".d.ts" /* Dts */; + return { packageDirectory: packageDirectory, subModuleName: subModuleName }; + } + function moveToNextDirectorySeparatorIfAvailable(path, prevSeparatorIndex) { + var nextSeparatorIndex = path.indexOf(ts.directorySeparator, prevSeparatorIndex + 1); + return nextSeparatorIndex === -1 ? prevSeparatorIndex : nextSeparatorIndex; + } + function addExtensionAndIndex(path) { + if (path === "") { + return "index.d.ts"; + } + if (ts.endsWith(path, ".d.ts")) { + return path; + } + if (path === "index" || ts.endsWith(path, "/index")) { + return path + ".d.ts"; + } + return path + "/index.d.ts"; + } + function loadModuleFromFileNoPackageId(extensions, candidate, onlyRecordFailures, state) { + return noPackageId(loadModuleFromFile(extensions, candidate, onlyRecordFailures, state)); + } + /** + * @param {boolean} onlyRecordFailures - if true then function won't try to actually load files but instead record all attempts as failures. This flag is necessary + * in cases when we know upfront that all load attempts will fail (because containing folder does not exists) however we still need to record all failed lookup locations. + */ + function loadModuleFromFile(extensions, candidate, onlyRecordFailures, state) { + if (extensions === Extensions.Json || extensions === Extensions.TSConfig) { + var extensionLess = ts.tryRemoveExtension(candidate, ".json" /* Json */); + return (extensionLess === undefined && extensions === Extensions.Json) ? undefined : tryAddingExtensions(extensionLess || candidate, extensions, onlyRecordFailures, state); + } + // First, try adding an extension. An import of "foo" could be matched by a file "foo.ts", or "foo.js" by "foo.js.ts" + var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, onlyRecordFailures, state); + if (resolvedByAddingExtension) { + return resolvedByAddingExtension; + } + // If that didn't work, try stripping a ".js" or ".jsx" extension and replacing it with a TypeScript one; + // e.g. "./foo.js" can be matched by "./foo.ts" or "./foo.d.ts" + if (ts.hasJSFileExtension(candidate)) { + var extensionless = ts.removeFileExtension(candidate); + if (state.traceEnabled) { + var extension = candidate.substring(extensionless.length); + trace(state.host, ts.Diagnostics.File_name_0_has_a_1_extension_stripping_it, candidate, extension); + } + return tryAddingExtensions(extensionless, extensions, onlyRecordFailures, state); + } + } + /** Try to return an existing file that adds one of the `extensions` to `candidate`. */ + function tryAddingExtensions(candidate, extensions, onlyRecordFailures, state) { + if (!onlyRecordFailures) { + // check if containing folder exists - if it doesn't then just record failures for all supported extensions without disk probing + var directory = ts.getDirectoryPath(candidate); + if (directory) { + onlyRecordFailures = !ts.directoryProbablyExists(directory, state.host); + } + } + switch (extensions) { + case Extensions.DtsOnly: + return tryExtension(".d.ts" /* Dts */); + case Extensions.TypeScript: + return tryExtension(".ts" /* Ts */) || tryExtension(".tsx" /* Tsx */) || tryExtension(".d.ts" /* Dts */); + case Extensions.JavaScript: + return tryExtension(".js" /* Js */) || tryExtension(".jsx" /* Jsx */); + case Extensions.TSConfig: + case Extensions.Json: + return tryExtension(".json" /* Json */); + } + function tryExtension(ext) { + var path = tryFile(candidate + ext, onlyRecordFailures, state); + return path === undefined ? undefined : { path: path, ext: ext }; + } + } + /** Return the file if it exists. */ + function tryFile(fileName, onlyRecordFailures, state) { + if (!onlyRecordFailures) { + if (state.host.fileExists(fileName)) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_exist_use_it_as_a_name_resolution_result, fileName); + } + return fileName; + } + else { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_does_not_exist, fileName); + } + } + } + state.failedLookupLocations.push(fileName); + return undefined; + } + function loadNodeModuleFromDirectory(extensions, candidate, onlyRecordFailures, state, considerPackageJson) { + if (considerPackageJson === void 0) { considerPackageJson = true; } + var packageInfo = considerPackageJson ? getPackageJsonInfo(candidate, "", onlyRecordFailures, state) : undefined; + var packageId = packageInfo && packageInfo.packageId; + var packageJsonContent = packageInfo && packageInfo.packageJsonContent; + var versionPaths = packageJsonContent && readPackageJsonTypesVersionPaths(packageJsonContent, state); + return withPackageId(packageId, loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths)); + } + function getPackageJsonInfo(packageDirectory, subModuleName, onlyRecordFailures, state) { + var host = state.host, traceEnabled = state.traceEnabled; + var directoryExists = !onlyRecordFailures && ts.directoryProbablyExists(packageDirectory, host); + var packageJsonPath = ts.combinePaths(packageDirectory, "package.json"); + if (directoryExists && host.fileExists(packageJsonPath)) { + var packageJsonContent = ts.readJson(packageJsonPath, host); + if (subModuleName === "") { // looking up the root - need to handle types/typings/main redirects for subModuleName + var path = readPackageJsonTypesFields(packageJsonContent, packageDirectory, state); + if (typeof path === "string") { + subModuleName = addExtensionAndIndex(path.substring(packageDirectory.length + 1)); + } + else { + var jsPath = readPackageJsonMainField(packageJsonContent, packageDirectory, state); + if (typeof jsPath === "string" && jsPath.length > packageDirectory.length) { + var potentialSubModule_1 = jsPath.substring(packageDirectory.length + 1); + subModuleName = (ts.forEach(ts.supportedJSExtensions, function (extension) { + return ts.tryRemoveExtension(potentialSubModule_1, extension); + }) || potentialSubModule_1) + ".d.ts" /* Dts */; + } + else { + subModuleName = "index.d.ts"; + } + } + } + if (!ts.endsWith(subModuleName, ".d.ts" /* Dts */)) { + subModuleName = addExtensionAndIndex(subModuleName); + } + var versionPaths = readPackageJsonTypesVersionPaths(packageJsonContent, state); + var packageId = typeof packageJsonContent.name === "string" && typeof packageJsonContent.version === "string" + ? { name: packageJsonContent.name, subModuleName: subModuleName, version: packageJsonContent.version } + : undefined; + if (traceEnabled) { + if (packageId) { + trace(host, ts.Diagnostics.Found_package_json_at_0_Package_ID_is_1, packageJsonPath, ts.packageIdToString(packageId)); + } + else { + trace(host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); + } + } + return { packageJsonContent: packageJsonContent, packageId: packageId, versionPaths: versionPaths }; + } + else { + if (directoryExists && traceEnabled) { + trace(host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath); + } + // record package json as one of failed lookup locations - in the future if this file will appear it will invalidate resolution results + state.failedLookupLocations.push(packageJsonPath); + } + } + function loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, jsonContent, versionPaths) { + var packageFile; + if (jsonContent) { + switch (extensions) { + case Extensions.JavaScript: + case Extensions.Json: + packageFile = readPackageJsonMainField(jsonContent, candidate, state); + break; + case Extensions.TypeScript: + // When resolving typescript modules, try resolving using main field as well + packageFile = readPackageJsonTypesFields(jsonContent, candidate, state) || readPackageJsonMainField(jsonContent, candidate, state); + break; + case Extensions.DtsOnly: + packageFile = readPackageJsonTypesFields(jsonContent, candidate, state); + break; + case Extensions.TSConfig: + packageFile = readPackageJsonTSConfigField(jsonContent, candidate, state); + break; + default: + return ts.Debug.assertNever(extensions); + } + } + var loader = function (extensions, candidate, onlyRecordFailures, state) { + var fromFile = tryFile(candidate, onlyRecordFailures, state); + if (fromFile) { + var resolved = resolvedIfExtensionMatches(extensions, fromFile); + if (resolved) { + return noPackageId(resolved); + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_has_an_unsupported_extension_so_skipping_it, fromFile); + } + } + // Even if extensions is DtsOnly, we can still look up a .ts file as a result of package.json "types" + var nextExtensions = extensions === Extensions.DtsOnly ? Extensions.TypeScript : extensions; + // Don't do package.json lookup recursively, because Node.js' package lookup doesn't. + return nodeLoadModuleByRelativeName(nextExtensions, candidate, onlyRecordFailures, state, /*considerPackageJson*/ false); + }; + var onlyRecordFailuresForPackageFile = packageFile ? !ts.directoryProbablyExists(ts.getDirectoryPath(packageFile), state.host) : undefined; + var onlyRecordFailuresForIndex = onlyRecordFailures || !ts.directoryProbablyExists(candidate, state.host); + var indexPath = ts.combinePaths(candidate, extensions === Extensions.TSConfig ? "tsconfig" : "index"); + if (versionPaths && (!packageFile || ts.containsPath(candidate, packageFile))) { + var moduleName = ts.getRelativePathFromDirectory(candidate, packageFile || indexPath, /*ignoreCase*/ false); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2, versionPaths.version, ts.version, moduleName); + } + var result = tryLoadModuleUsingPaths(extensions, moduleName, candidate, versionPaths.paths, loader, onlyRecordFailuresForPackageFile || onlyRecordFailuresForIndex, state); + if (result) { + return removeIgnoredPackageId(result.value); + } + } + // It won't have a `packageId` set, because we disabled `considerPackageJson`. + var packageFileResult = packageFile && removeIgnoredPackageId(loader(extensions, packageFile, onlyRecordFailuresForPackageFile, state)); + if (packageFileResult) + return packageFileResult; + return loadModuleFromFile(extensions, indexPath, onlyRecordFailuresForIndex, state); + } + /** Resolve from an arbitrarily specified file. Return `undefined` if it has an unsupported extension. */ + function resolvedIfExtensionMatches(extensions, path) { + var ext = ts.tryGetExtensionFromPath(path); + return ext !== undefined && extensionIsOk(extensions, ext) ? { path: path, ext: ext } : undefined; + } + /** True if `extension` is one of the supported `extensions`. */ + function extensionIsOk(extensions, extension) { + switch (extensions) { + case Extensions.JavaScript: + return extension === ".js" /* Js */ || extension === ".jsx" /* Jsx */; + case Extensions.TSConfig: + case Extensions.Json: + return extension === ".json" /* Json */; + case Extensions.TypeScript: + return extension === ".ts" /* Ts */ || extension === ".tsx" /* Tsx */ || extension === ".d.ts" /* Dts */; + case Extensions.DtsOnly: + return extension === ".d.ts" /* Dts */; + } + } + /* @internal */ + function parsePackageName(moduleName) { + var idx = moduleName.indexOf(ts.directorySeparator); + if (moduleName[0] === "@") { + idx = moduleName.indexOf(ts.directorySeparator, idx + 1); + } + return idx === -1 ? { packageName: moduleName, rest: "" } : { packageName: moduleName.slice(0, idx), rest: moduleName.slice(idx + 1) }; + } + ts.parsePackageName = parsePackageName; + function loadModuleFromNearestNodeModulesDirectory(extensions, moduleName, directory, state, cache, redirectedReference) { + return loadModuleFromNearestNodeModulesDirectoryWorker(extensions, moduleName, directory, state, /*typesScopeOnly*/ false, cache, redirectedReference); + } + function loadModuleFromNearestNodeModulesDirectoryTypesScope(moduleName, directory, state) { + // Extensions parameter here doesn't actually matter, because typesOnly ensures we're just doing @types lookup, which is always DtsOnly. + return loadModuleFromNearestNodeModulesDirectoryWorker(Extensions.DtsOnly, moduleName, directory, state, /*typesScopeOnly*/ true, /*cache*/ undefined, /*redirectedReference*/ undefined); + } + function loadModuleFromNearestNodeModulesDirectoryWorker(extensions, moduleName, directory, state, typesScopeOnly, cache, redirectedReference) { + var perModuleNameCache = cache && cache.getOrCreateCacheForModuleName(moduleName, redirectedReference); + return ts.forEachAncestorDirectory(ts.normalizeSlashes(directory), function (ancestorDirectory) { + if (ts.getBaseFileName(ancestorDirectory) !== "node_modules") { + var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, ancestorDirectory, state); + if (resolutionFromCache) { + return resolutionFromCache; + } + return toSearchResult(loadModuleFromImmediateNodeModulesDirectory(extensions, moduleName, ancestorDirectory, state, typesScopeOnly)); + } + }); + } + function loadModuleFromImmediateNodeModulesDirectory(extensions, moduleName, directory, state, typesScopeOnly) { + var nodeModulesFolder = ts.combinePaths(directory, "node_modules"); + var nodeModulesFolderExists = ts.directoryProbablyExists(nodeModulesFolder, state.host); + if (!nodeModulesFolderExists && state.traceEnabled) { + trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, nodeModulesFolder); + } + var packageResult = typesScopeOnly ? undefined : loadModuleFromSpecificNodeModulesDirectory(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, state); + if (packageResult) { + return packageResult; + } + if (extensions === Extensions.TypeScript || extensions === Extensions.DtsOnly) { + var nodeModulesAtTypes_1 = ts.combinePaths(nodeModulesFolder, "@types"); + var nodeModulesAtTypesExists = nodeModulesFolderExists; + if (nodeModulesFolderExists && !ts.directoryProbablyExists(nodeModulesAtTypes_1, state.host)) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, nodeModulesAtTypes_1); + } + nodeModulesAtTypesExists = false; + } + return loadModuleFromSpecificNodeModulesDirectory(Extensions.DtsOnly, mangleScopedPackageNameWithTrace(moduleName, state), nodeModulesAtTypes_1, nodeModulesAtTypesExists, state); + } + } + function loadModuleFromSpecificNodeModulesDirectory(extensions, moduleName, nodeModulesDirectory, nodeModulesDirectoryExists, state) { + var candidate = ts.normalizePath(ts.combinePaths(nodeModulesDirectory, moduleName)); + // First look for a nested package.json, as in `node_modules/foo/bar/package.json`. + var packageJsonContent; + var packageId; + var versionPaths; + var packageInfo = getPackageJsonInfo(candidate, "", !nodeModulesDirectoryExists, state); + if (packageInfo) { + (packageJsonContent = packageInfo.packageJsonContent, packageId = packageInfo.packageId, versionPaths = packageInfo.versionPaths); + var fromFile = loadModuleFromFile(extensions, candidate, !nodeModulesDirectoryExists, state); + if (fromFile) { + return noPackageId(fromFile); + } + var fromDirectory = loadNodeModuleFromDirectoryWorker(extensions, candidate, !nodeModulesDirectoryExists, state, packageJsonContent, versionPaths); + return withPackageId(packageId, fromDirectory); + } + var loader = function (extensions, candidate, onlyRecordFailures, state) { + var pathAndExtension = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state) || + loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths); + return withPackageId(packageId, pathAndExtension); + }; + var _a = parsePackageName(moduleName), packageName = _a.packageName, rest = _a.rest; + if (rest !== "") { // If "rest" is empty, we just did this search above. + var packageDirectory = ts.combinePaths(nodeModulesDirectory, packageName); + // Don't use a "types" or "main" from here because we're not loading the root, but a subdirectory -- just here for the packageId and path mappings. + var packageInfo_1 = getPackageJsonInfo(packageDirectory, rest, !nodeModulesDirectoryExists, state); + if (packageInfo_1) + (packageId = packageInfo_1.packageId, versionPaths = packageInfo_1.versionPaths); + if (versionPaths) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2, versionPaths.version, ts.version, rest); + } + var packageDirectoryExists = nodeModulesDirectoryExists && ts.directoryProbablyExists(packageDirectory, state.host); + var fromPaths = tryLoadModuleUsingPaths(extensions, rest, packageDirectory, versionPaths.paths, loader, !packageDirectoryExists, state); + if (fromPaths) { + return fromPaths.value; + } + } + } + return loader(extensions, candidate, !nodeModulesDirectoryExists, state); + } + function tryLoadModuleUsingPaths(extensions, moduleName, baseDirectory, paths, loader, onlyRecordFailures, state) { + var matchedPattern = ts.matchPatternOrExact(ts.getOwnKeys(paths), moduleName); + if (matchedPattern) { + var matchedStar_1 = ts.isString(matchedPattern) ? undefined : ts.matchedText(matchedPattern, moduleName); + var matchedPatternText = ts.isString(matchedPattern) ? matchedPattern : ts.patternText(matchedPattern); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText); + } + var resolved = ts.forEach(paths[matchedPatternText], function (subst) { + var path = matchedStar_1 ? subst.replace("*", matchedStar_1) : subst; + var candidate = ts.normalizePath(ts.combinePaths(baseDirectory, path)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path); + } + // A path mapping may have an extension, in contrast to an import, which should omit it. + var extension = ts.tryGetExtensionFromPath(candidate); + if (extension !== undefined) { + var path_1 = tryFile(candidate, onlyRecordFailures, state); + if (path_1 !== undefined) { + return noPackageId({ path: path_1, ext: extension }); + } + } + return loader(extensions, candidate, onlyRecordFailures || !ts.directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); + }); + return { value: resolved }; + } + } + /** Double underscores are used in DefinitelyTyped to delimit scoped packages. */ + var mangledScopedPackageSeparator = "__"; + /** For a scoped package, we must look in `@types/foo__bar` instead of `@types/@foo/bar`. */ + function mangleScopedPackageNameWithTrace(packageName, state) { + var mangled = mangleScopedPackageName(packageName); + if (state.traceEnabled && mangled !== packageName) { + trace(state.host, ts.Diagnostics.Scoped_package_detected_looking_in_0, mangled); + } + return mangled; + } + /* @internal */ + function getTypesPackageName(packageName) { + return "@types/" + mangleScopedPackageName(packageName); + } + ts.getTypesPackageName = getTypesPackageName; + /* @internal */ + function mangleScopedPackageName(packageName) { + if (ts.startsWith(packageName, "@")) { + var replaceSlash = packageName.replace(ts.directorySeparator, mangledScopedPackageSeparator); + if (replaceSlash !== packageName) { + return replaceSlash.slice(1); // Take off the "@" + } + } + return packageName; + } + ts.mangleScopedPackageName = mangleScopedPackageName; + /* @internal */ + function getPackageNameFromTypesPackageName(mangledName) { + var withoutAtTypePrefix = ts.removePrefix(mangledName, "@types/"); + if (withoutAtTypePrefix !== mangledName) { + return unmangleScopedPackageName(withoutAtTypePrefix); + } + return mangledName; + } + ts.getPackageNameFromTypesPackageName = getPackageNameFromTypesPackageName; + /* @internal */ + function unmangleScopedPackageName(typesPackageName) { + return ts.stringContains(typesPackageName, mangledScopedPackageSeparator) ? + "@" + typesPackageName.replace(mangledScopedPackageSeparator, ts.directorySeparator) : + typesPackageName; + } + ts.unmangleScopedPackageName = unmangleScopedPackageName; + function tryFindNonRelativeModuleNameInCache(cache, moduleName, containingDirectory, state) { + var _a; + var result = cache && cache.get(containingDirectory); + if (result) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory); + } + (_a = state.failedLookupLocations).push.apply(_a, result.failedLookupLocations); + return { value: result.resolvedModule && { path: result.resolvedModule.resolvedFileName, originalPath: result.resolvedModule.originalPath || true, extension: result.resolvedModule.extension, packageId: result.resolvedModule.packageId } }; + } + } + function classicNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference) { + var traceEnabled = isTraceEnabled(compilerOptions, host); + var failedLookupLocations = []; + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; + var containingDirectory = ts.getDirectoryPath(containingFile); + var resolved = tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript); + // No originalPath because classic resolution doesn't resolve realPath + return createResolvedModuleWithFailedLookupLocations(resolved && resolved.value, /*isExternalLibraryImport*/ false, failedLookupLocations); + function tryResolve(extensions) { + var resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFileNoPackageId, state); + if (resolvedUsingSettings) { + return { value: resolvedUsingSettings }; + } + if (!ts.isExternalModuleNameRelative(moduleName)) { + var perModuleNameCache_1 = cache && cache.getOrCreateCacheForModuleName(moduleName, redirectedReference); + // Climb up parent directories looking for a module. + var resolved_3 = ts.forEachAncestorDirectory(containingDirectory, function (directory) { + var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache_1, moduleName, directory, state); + if (resolutionFromCache) { + return resolutionFromCache; + } + var searchName = ts.normalizePath(ts.combinePaths(directory, moduleName)); + return toSearchResult(loadModuleFromFileNoPackageId(extensions, searchName, /*onlyRecordFailures*/ false, state)); + }); + if (resolved_3) { + return resolved_3; + } + if (extensions === Extensions.TypeScript) { + // If we didn't find the file normally, look it up in @types. + return loadModuleFromNearestNodeModulesDirectoryTypesScope(moduleName, containingDirectory, state); + } + } + else { + var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); + return toSearchResult(loadModuleFromFileNoPackageId(extensions, candidate, /*onlyRecordFailures*/ false, state)); + } + } + } + ts.classicNameResolver = classicNameResolver; + /** + * LSHost may load a module from a global cache of typings. + * This is the minumum code needed to expose that functionality; the rest is in LSHost. + */ + /* @internal */ + function loadModuleFromGlobalCache(moduleName, projectName, compilerOptions, host, globalCache) { + var traceEnabled = isTraceEnabled(compilerOptions, host); + if (traceEnabled) { + trace(host, ts.Diagnostics.Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2, projectName, moduleName, globalCache); + } + var failedLookupLocations = []; + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; + var resolved = loadModuleFromImmediateNodeModulesDirectory(Extensions.DtsOnly, moduleName, globalCache, state, /*typesScopeOnly*/ false); + return createResolvedModuleWithFailedLookupLocations(resolved, /*isExternalLibraryImport*/ true, failedLookupLocations); + } + ts.loadModuleFromGlobalCache = loadModuleFromGlobalCache; + /** + * Wraps value to SearchResult. + * @returns undefined if value is undefined or { value } otherwise + */ + function toSearchResult(value) { + return value !== undefined ? { value: value } : undefined; + } +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var ModuleInstanceState; + (function (ModuleInstanceState) { + ModuleInstanceState[ModuleInstanceState["NonInstantiated"] = 0] = "NonInstantiated"; + ModuleInstanceState[ModuleInstanceState["Instantiated"] = 1] = "Instantiated"; + ModuleInstanceState[ModuleInstanceState["ConstEnumOnly"] = 2] = "ConstEnumOnly"; + })(ModuleInstanceState = ts.ModuleInstanceState || (ts.ModuleInstanceState = {})); + function getModuleInstanceState(node) { + return node.body ? getModuleInstanceStateWorker(node.body) : 1 /* Instantiated */; + } + ts.getModuleInstanceState = getModuleInstanceState; + function getModuleInstanceStateWorker(node) { + // A module is uninstantiated if it contains only + switch (node.kind) { + // 1. interface declarations, type alias declarations + case 241 /* InterfaceDeclaration */: + case 242 /* TypeAliasDeclaration */: + return 0 /* NonInstantiated */; + // 2. const enum declarations + case 243 /* EnumDeclaration */: + if (ts.isEnumConst(node)) { + return 2 /* ConstEnumOnly */; + } + break; + // 3. non-exported import declarations + case 249 /* ImportDeclaration */: + case 248 /* ImportEqualsDeclaration */: + if (!(ts.hasModifier(node, 1 /* Export */))) { + return 0 /* NonInstantiated */; + } + break; + // 4. other uninstantiated module declarations. + case 245 /* ModuleBlock */: { + var state_1 = 0 /* NonInstantiated */; + ts.forEachChild(node, function (n) { + var childState = getModuleInstanceStateWorker(n); + switch (childState) { + case 0 /* NonInstantiated */: + // child is non-instantiated - continue searching + return; + case 2 /* ConstEnumOnly */: + // child is const enum only - record state and continue searching + state_1 = 2 /* ConstEnumOnly */; + return; + case 1 /* Instantiated */: + // child is instantiated - record state and stop + state_1 = 1 /* Instantiated */; + return true; + default: + ts.Debug.assertNever(childState); + } + }); + return state_1; + } + case 244 /* ModuleDeclaration */: + return getModuleInstanceState(node); + case 72 /* Identifier */: + // Only jsdoc typedef definition can exist in jsdoc namespace, and it should + // be considered the same as type alias + if (node.isInJSDocNamespace) { + return 0 /* NonInstantiated */; + } + } + return 1 /* Instantiated */; + } + var ContainerFlags; + (function (ContainerFlags) { + // The current node is not a container, and no container manipulation should happen before + // recursing into it. + ContainerFlags[ContainerFlags["None"] = 0] = "None"; + // The current node is a container. It should be set as the current container (and block- + // container) before recursing into it. The current node does not have locals. Examples: + // + // Classes, ObjectLiterals, TypeLiterals, Interfaces... + ContainerFlags[ContainerFlags["IsContainer"] = 1] = "IsContainer"; + // The current node is a block-scoped-container. It should be set as the current block- + // container before recursing into it. Examples: + // + // Blocks (when not parented by functions), Catch clauses, For/For-in/For-of statements... + ContainerFlags[ContainerFlags["IsBlockScopedContainer"] = 2] = "IsBlockScopedContainer"; + // The current node is the container of a control flow path. The current control flow should + // be saved and restored, and a new control flow initialized within the container. + ContainerFlags[ContainerFlags["IsControlFlowContainer"] = 4] = "IsControlFlowContainer"; + ContainerFlags[ContainerFlags["IsFunctionLike"] = 8] = "IsFunctionLike"; + ContainerFlags[ContainerFlags["IsFunctionExpression"] = 16] = "IsFunctionExpression"; + ContainerFlags[ContainerFlags["HasLocals"] = 32] = "HasLocals"; + ContainerFlags[ContainerFlags["IsInterface"] = 64] = "IsInterface"; + ContainerFlags[ContainerFlags["IsObjectLiteralOrClassExpressionMethod"] = 128] = "IsObjectLiteralOrClassExpressionMethod"; + })(ContainerFlags || (ContainerFlags = {})); + var binder = createBinder(); + function bindSourceFile(file, options) { + ts.performance.mark("beforeBind"); + binder(file, options); + ts.performance.mark("afterBind"); + ts.performance.measure("Bind", "beforeBind", "afterBind"); + } + ts.bindSourceFile = bindSourceFile; + function createBinder() { + var file; + var options; + var languageVersion; + var parent; + var container; + var thisParentContainer; // Container one level up + var blockScopeContainer; + var lastContainer; + var delayedTypeAliases; + var seenThisKeyword; + // state used by control flow analysis + var currentFlow; + var currentBreakTarget; + var currentContinueTarget; + var currentReturnTarget; + var currentTrueTarget; + var currentFalseTarget; + var preSwitchCaseFlow; + var activeLabels; + var hasExplicitReturn; + // state used for emit helpers + var emitFlags; + // If this file is an external module, then it is automatically in strict-mode according to + // ES6. If it is not an external module, then we'll determine if it is in strict mode or + // not depending on if we see "use strict" in certain places or if we hit a class/namespace + // or if compiler options contain alwaysStrict. + var inStrictMode; + var symbolCount = 0; + var Symbol; // tslint:disable-line variable-name + var classifiableNames; + var unreachableFlow = { flags: 1 /* Unreachable */ }; + var reportedUnreachableFlow = { flags: 1 /* Unreachable */ }; + // state used to aggregate transform flags during bind. + var subtreeTransformFlags = 0 /* None */; + var skipTransformFlagAggregation; + /** + * Inside the binder, we may create a diagnostic for an as-yet unbound node (with potentially no parent pointers, implying no accessible source file) + * If so, the node _must_ be in the current file (as that's the only way anything could have traversed to it to yield it as the error node) + * This version of `createDiagnosticForNode` uses the binder's context to account for this, and always yields correct diagnostics even in these situations. + */ + function createDiagnosticForNode(node, message, arg0, arg1, arg2) { + return ts.createDiagnosticForNodeInSourceFile(ts.getSourceFileOfNode(node) || file, node, message, arg0, arg1, arg2); + } + function bindSourceFile(f, opts) { + file = f; + options = opts; + languageVersion = ts.getEmitScriptTarget(options); + inStrictMode = bindInStrictMode(file, opts); + classifiableNames = ts.createUnderscoreEscapedMap(); + symbolCount = 0; + skipTransformFlagAggregation = file.isDeclarationFile; + Symbol = ts.objectAllocator.getSymbolConstructor(); + if (!file.locals) { + bind(file); + file.symbolCount = symbolCount; + file.classifiableNames = classifiableNames; + delayedBindJSDocTypedefTag(); + } + file = undefined; + options = undefined; + languageVersion = undefined; + parent = undefined; + container = undefined; + thisParentContainer = undefined; + blockScopeContainer = undefined; + lastContainer = undefined; + delayedTypeAliases = undefined; + seenThisKeyword = false; + currentFlow = undefined; + currentBreakTarget = undefined; + currentContinueTarget = undefined; + currentReturnTarget = undefined; + currentTrueTarget = undefined; + currentFalseTarget = undefined; + activeLabels = undefined; + hasExplicitReturn = false; + emitFlags = 0 /* None */; + subtreeTransformFlags = 0 /* None */; + } + return bindSourceFile; + function bindInStrictMode(file, opts) { + if (ts.getStrictOptionValue(opts, "alwaysStrict") && !file.isDeclarationFile) { + // bind in strict mode source files with alwaysStrict option + return true; + } + else { + return !!file.externalModuleIndicator; + } + } + function createSymbol(flags, name) { + symbolCount++; + return new Symbol(flags, name); + } + function addDeclarationToSymbol(symbol, node, symbolFlags) { + symbol.flags |= symbolFlags; + node.symbol = symbol; + symbol.declarations = ts.append(symbol.declarations, node); + if (symbolFlags & (32 /* Class */ | 384 /* Enum */ | 1536 /* Module */ | 3 /* Variable */) && !symbol.exports) { + symbol.exports = ts.createSymbolTable(); + } + if (symbolFlags & (32 /* Class */ | 64 /* Interface */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && !symbol.members) { + symbol.members = ts.createSymbolTable(); + } + if (symbolFlags & 67220415 /* Value */) { + setValueDeclaration(symbol, node); + } + } + function setValueDeclaration(symbol, node) { + var valueDeclaration = symbol.valueDeclaration; + if (!valueDeclaration || + (ts.isAssignmentDeclaration(valueDeclaration) && !ts.isAssignmentDeclaration(node)) || + (valueDeclaration.kind !== node.kind && ts.isEffectiveModuleDeclaration(valueDeclaration))) { + // other kinds of value declarations take precedence over modules and assignment declarations + symbol.valueDeclaration = node; + } + } + // Should not be called on a declaration with a computed property name, + // unless it is a well known Symbol. + function getDeclarationName(node) { + if (node.kind === 254 /* ExportAssignment */) { + return node.isExportEquals ? "export=" /* ExportEquals */ : "default" /* Default */; + } + var name = ts.getNameOfDeclaration(node); + if (name) { + if (ts.isAmbientModule(node)) { + var moduleName = ts.getTextOfIdentifierOrLiteral(name); + return (ts.isGlobalScopeAugmentation(node) ? "__global" : "\"" + moduleName + "\""); + } + if (name.kind === 149 /* ComputedPropertyName */) { + var nameExpression = name.expression; + // treat computed property names where expression is string/numeric literal as just string/numeric literal + if (ts.isStringOrNumericLiteralLike(nameExpression)) { + return ts.escapeLeadingUnderscores(nameExpression.text); + } + ts.Debug.assert(ts.isWellKnownSymbolSyntactically(nameExpression)); + return ts.getPropertyNameForKnownSymbolName(ts.idText(nameExpression.name)); + } + return ts.isPropertyNameLiteral(name) ? ts.getEscapedTextOfIdentifierOrLiteral(name) : undefined; + } + switch (node.kind) { + case 157 /* Constructor */: + return "__constructor" /* Constructor */; + case 165 /* FunctionType */: + case 160 /* CallSignature */: + case 293 /* JSDocSignature */: + return "__call" /* Call */; + case 166 /* ConstructorType */: + case 161 /* ConstructSignature */: + return "__new" /* New */; + case 162 /* IndexSignature */: + return "__index" /* Index */; + case 255 /* ExportDeclaration */: + return "__export" /* ExportStar */; + case 279 /* SourceFile */: + // json file should behave as + // module.exports = ... + return "export=" /* ExportEquals */; + case 204 /* BinaryExpression */: + if (ts.getAssignmentDeclarationKind(node) === 2 /* ModuleExports */) { + // module.exports = ... + return "export=" /* ExportEquals */; + } + ts.Debug.fail("Unknown binary declaration kind"); + break; + case 289 /* JSDocFunctionType */: + return (ts.isJSDocConstructSignature(node) ? "__new" /* New */ : "__call" /* Call */); + case 151 /* Parameter */: + // Parameters with names are handled at the top of this function. Parameters + // without names can only come from JSDocFunctionTypes. + ts.Debug.assert(node.parent.kind === 289 /* JSDocFunctionType */, "Impossible parameter parent kind", function () { return "parent is: " + (ts.SyntaxKind ? ts.SyntaxKind[node.parent.kind] : node.parent.kind) + ", expected JSDocFunctionType"; }); + var functionType = node.parent; + var index = functionType.parameters.indexOf(node); + return "arg" + index; + } + } + function getDisplayName(node) { + return ts.isNamedDeclaration(node) ? ts.declarationNameToString(node.name) : ts.unescapeLeadingUnderscores(ts.Debug.assertDefined(getDeclarationName(node))); + } + /** + * Declares a Symbol for the node and adds it to symbols. Reports errors for conflicting identifier names. + * @param symbolTable - The symbol table which node will be added to. + * @param parent - node's parent declaration. + * @param node - The declaration to be added to the symbol table + * @param includes - The SymbolFlags that node has in addition to its declaration type (eg: export, ambient, etc.) + * @param excludes - The flags which node cannot be declared alongside in a symbol table. Used to report forbidden declarations. + */ + function declareSymbol(symbolTable, parent, node, includes, excludes, isReplaceableByMethod) { + ts.Debug.assert(!ts.hasDynamicName(node)); + var isDefaultExport = ts.hasModifier(node, 512 /* Default */); + // The exported symbol for an export default function/class node is always named "default" + var name = isDefaultExport && parent ? "default" /* Default */ : getDeclarationName(node); + var symbol; + if (name === undefined) { + symbol = createSymbol(0 /* None */, "__missing" /* Missing */); + } + else { + // Check and see if the symbol table already has a symbol with this name. If not, + // create a new symbol with this name and add it to the table. Note that we don't + // give the new symbol any flags *yet*. This ensures that it will not conflict + // with the 'excludes' flags we pass in. + // + // If we do get an existing symbol, see if it conflicts with the new symbol we're + // creating. For example, a 'var' symbol and a 'class' symbol will conflict within + // the same symbol table. If we have a conflict, report the issue on each + // declaration we have for this symbol, and then create a new symbol for this + // declaration. + // + // Note that when properties declared in Javascript constructors + // (marked by isReplaceableByMethod) conflict with another symbol, the property loses. + // Always. This allows the common Javascript pattern of overwriting a prototype method + // with an bound instance method of the same type: `this.method = this.method.bind(this)` + // + // If we created a new symbol, either because we didn't have a symbol with this name + // in the symbol table, or we conflicted with an existing symbol, then just add this + // node as the sole declaration of the new symbol. + // + // Otherwise, we'll be merging into a compatible existing symbol (for example when + // you have multiple 'vars' with the same name in the same container). In this case + // just add this node into the declarations list of the symbol. + symbol = symbolTable.get(name); + if (includes & 2885600 /* Classifiable */) { + classifiableNames.set(name, true); + } + if (!symbol) { + symbolTable.set(name, symbol = createSymbol(0 /* None */, name)); + if (isReplaceableByMethod) + symbol.isReplaceableByMethod = true; + } + else if (isReplaceableByMethod && !symbol.isReplaceableByMethod) { + // A symbol already exists, so don't add this as a declaration. + return symbol; + } + else if (symbol.flags & excludes) { + if (symbol.isReplaceableByMethod) { + // Javascript constructor-declared symbols can be discarded in favor of + // prototype symbols like methods. + symbolTable.set(name, symbol = createSymbol(0 /* None */, name)); + } + else if (!(includes & 3 /* Variable */ && symbol.flags & 67108864 /* Assignment */)) { + // Assignment declarations are allowed to merge with variables, no matter what other flags they have. + if (ts.isNamedDeclaration(node)) { + node.name.parent = node; + } + // Report errors every position with duplicate declaration + // Report errors on previous encountered declarations + var message_1 = symbol.flags & 2 /* BlockScopedVariable */ + ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 + : ts.Diagnostics.Duplicate_identifier_0; + var messageNeedsName_1 = true; + if (symbol.flags & 384 /* Enum */ || includes & 384 /* Enum */) { + message_1 = ts.Diagnostics.Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations; + messageNeedsName_1 = false; + } + if (symbol.declarations && symbol.declarations.length) { + // If the current node is a default export of some sort, then check if + // there are any other default exports that we need to error on. + // We'll know whether we have other default exports depending on if `symbol` already has a declaration list set. + if (isDefaultExport) { + message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; + messageNeedsName_1 = false; + } + else { + // This is to properly report an error in the case "export default { }" is after export default of class declaration or function declaration. + // Error on multiple export default in the following case: + // 1. multiple export default of class declaration or function declaration by checking NodeFlags.Default + // 2. multiple export default of export assignment. This one doesn't have NodeFlags.Default on (as export default doesn't considered as modifiers) + if (symbol.declarations && symbol.declarations.length && + (node.kind === 254 /* ExportAssignment */ && !node.isExportEquals)) { + message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; + messageNeedsName_1 = false; + } + } + } + var addError = function (decl) { + file.bindDiagnostics.push(createDiagnosticForNode(ts.getNameOfDeclaration(decl) || decl, message_1, messageNeedsName_1 ? getDisplayName(decl) : undefined)); + }; + ts.forEach(symbol.declarations, addError); + addError(node); + symbol = createSymbol(0 /* None */, name); + } + } + } + addDeclarationToSymbol(symbol, node, includes); + if (symbol.parent) { + ts.Debug.assert(symbol.parent === parent, "Existing symbol parent should match new one"); + } + else { + symbol.parent = parent; + } + return symbol; + } + function declareModuleMember(node, symbolFlags, symbolExcludes) { + var hasExportModifier = ts.getCombinedModifierFlags(node) & 1 /* Export */; + if (symbolFlags & 2097152 /* Alias */) { + if (node.kind === 257 /* ExportSpecifier */ || (node.kind === 248 /* ImportEqualsDeclaration */ && hasExportModifier)) { + return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); + } + else { + return declareSymbol(container.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes); + } + } + else { + // Exported module members are given 2 symbols: A local symbol that is classified with an ExportValue flag, + // and an associated export symbol with all the correct flags set on it. There are 2 main reasons: + // + // 1. We treat locals and exports of the same name as mutually exclusive within a container. + // That means the binder will issue a Duplicate Identifier error if you mix locals and exports + // with the same name in the same container. + // TODO: Make this a more specific error and decouple it from the exclusion logic. + // 2. When we checkIdentifier in the checker, we set its resolved symbol to the local symbol, + // but return the export symbol (by calling getExportSymbolOfValueSymbolIfExported). That way + // when the emitter comes back to it, it knows not to qualify the name if it was found in a containing scope. + // NOTE: Nested ambient modules always should go to to 'locals' table to prevent their automatic merge + // during global merging in the checker. Why? The only case when ambient module is permitted inside another module is module augmentation + // and this case is specially handled. Module augmentations should only be merged with original module definition + // and should never be merged directly with other augmentation, and the latter case would be possible if automatic merge is allowed. + if (ts.isJSDocTypeAlias(node)) + ts.Debug.assert(ts.isInJSFile(node)); // We shouldn't add symbols for JSDoc nodes if not in a JS file. + if ((!ts.isAmbientModule(node) && (hasExportModifier || container.flags & 32 /* ExportContext */)) || ts.isJSDocTypeAlias(node)) { + if (ts.hasModifier(node, 512 /* Default */) && !getDeclarationName(node)) { + return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); // No local symbol for an unnamed default! + } + var exportKind = symbolFlags & 67220415 /* Value */ ? 1048576 /* ExportValue */ : 0; + var local = declareSymbol(container.locals, /*parent*/ undefined, node, exportKind, symbolExcludes); + local.exportSymbol = declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); + node.localSymbol = local; + return local; + } + else { + return declareSymbol(container.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes); + } + } + } + // All container nodes are kept on a linked list in declaration order. This list is used by + // the getLocalNameOfContainer function in the type checker to validate that the local name + // used for a container is unique. + function bindContainer(node, containerFlags) { + // Before we recurse into a node's children, we first save the existing parent, container + // and block-container. Then after we pop out of processing the children, we restore + // these saved values. + var saveContainer = container; + var saveThisParentContainer = thisParentContainer; + var savedBlockScopeContainer = blockScopeContainer; + // Depending on what kind of node this is, we may have to adjust the current container + // and block-container. If the current node is a container, then it is automatically + // considered the current block-container as well. Also, for containers that we know + // may contain locals, we eagerly initialize the .locals field. We do this because + // it's highly likely that the .locals will be needed to place some child in (for example, + // a parameter, or variable declaration). + // + // However, we do not proactively create the .locals for block-containers because it's + // totally normal and common for block-containers to never actually have a block-scoped + // variable in them. We don't want to end up allocating an object for every 'block' we + // run into when most of them won't be necessary. + // + // Finally, if this is a block-container, then we clear out any existing .locals object + // it may contain within it. This happens in incremental scenarios. Because we can be + // reusing a node from a previous compilation, that node may have had 'locals' created + // for it. We must clear this so we don't accidentally move any stale data forward from + // a previous compilation. + if (containerFlags & 1 /* IsContainer */) { + if (node.kind !== 197 /* ArrowFunction */) { + thisParentContainer = container; + } + container = blockScopeContainer = node; + if (containerFlags & 32 /* HasLocals */) { + container.locals = ts.createSymbolTable(); + } + addToContainerChain(container); + } + else if (containerFlags & 2 /* IsBlockScopedContainer */) { + blockScopeContainer = node; + blockScopeContainer.locals = undefined; + } + if (containerFlags & 4 /* IsControlFlowContainer */) { + var saveCurrentFlow = currentFlow; + var saveBreakTarget = currentBreakTarget; + var saveContinueTarget = currentContinueTarget; + var saveReturnTarget = currentReturnTarget; + var saveActiveLabels = activeLabels; + var saveHasExplicitReturn = hasExplicitReturn; + var isIIFE = containerFlags & 16 /* IsFunctionExpression */ && !ts.hasModifier(node, 256 /* Async */) && + !node.asteriskToken && !!ts.getImmediatelyInvokedFunctionExpression(node); + // A non-async, non-generator IIFE is considered part of the containing control flow. Return statements behave + // similarly to break statements that exit to a label just past the statement body. + if (!isIIFE) { + currentFlow = { flags: 2 /* Start */ }; + if (containerFlags & (16 /* IsFunctionExpression */ | 128 /* IsObjectLiteralOrClassExpressionMethod */)) { + currentFlow.container = node; + } + } + // We create a return control flow graph for IIFEs and constructors. For constructors + // we use the return control flow graph in strict property intialization checks. + currentReturnTarget = isIIFE || node.kind === 157 /* Constructor */ ? createBranchLabel() : undefined; + currentBreakTarget = undefined; + currentContinueTarget = undefined; + activeLabels = undefined; + hasExplicitReturn = false; + bindChildren(node); + // Reset all reachability check related flags on node (for incremental scenarios) + node.flags &= ~1408 /* ReachabilityAndEmitFlags */; + if (!(currentFlow.flags & 1 /* Unreachable */) && containerFlags & 8 /* IsFunctionLike */ && ts.nodeIsPresent(node.body)) { + node.flags |= 128 /* HasImplicitReturn */; + if (hasExplicitReturn) + node.flags |= 256 /* HasExplicitReturn */; + } + if (node.kind === 279 /* SourceFile */) { + node.flags |= emitFlags; + } + if (currentReturnTarget) { + addAntecedent(currentReturnTarget, currentFlow); + currentFlow = finishFlowLabel(currentReturnTarget); + if (node.kind === 157 /* Constructor */) { + node.returnFlowNode = currentFlow; + } + } + if (!isIIFE) { + currentFlow = saveCurrentFlow; + } + currentBreakTarget = saveBreakTarget; + currentContinueTarget = saveContinueTarget; + currentReturnTarget = saveReturnTarget; + activeLabels = saveActiveLabels; + hasExplicitReturn = saveHasExplicitReturn; + } + else if (containerFlags & 64 /* IsInterface */) { + seenThisKeyword = false; + bindChildren(node); + node.flags = seenThisKeyword ? node.flags | 64 /* ContainsThis */ : node.flags & ~64 /* ContainsThis */; + } + else { + bindChildren(node); + } + container = saveContainer; + thisParentContainer = saveThisParentContainer; + blockScopeContainer = savedBlockScopeContainer; + } + function bindChildren(node) { + if (skipTransformFlagAggregation) { + bindChildrenWorker(node); + } + else if (node.transformFlags & 536870912 /* HasComputedFlags */) { + skipTransformFlagAggregation = true; + bindChildrenWorker(node); + skipTransformFlagAggregation = false; + subtreeTransformFlags |= node.transformFlags & ~getTransformFlagsSubtreeExclusions(node.kind); + } + else { + var savedSubtreeTransformFlags = subtreeTransformFlags; + subtreeTransformFlags = 0; + bindChildrenWorker(node); + subtreeTransformFlags = savedSubtreeTransformFlags | computeTransformFlagsForNode(node, subtreeTransformFlags); + } + } + function bindEachFunctionsFirst(nodes) { + bindEach(nodes, function (n) { return n.kind === 239 /* FunctionDeclaration */ ? bind(n) : undefined; }); + bindEach(nodes, function (n) { return n.kind !== 239 /* FunctionDeclaration */ ? bind(n) : undefined; }); + } + function bindEach(nodes, bindFunction) { + if (bindFunction === void 0) { bindFunction = bind; } + if (nodes === undefined) { + return; + } + if (skipTransformFlagAggregation) { + ts.forEach(nodes, bindFunction); + } + else { + var savedSubtreeTransformFlags = subtreeTransformFlags; + subtreeTransformFlags = 0 /* None */; + var nodeArrayFlags = 0 /* None */; + for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) { + var node = nodes_2[_i]; + bindFunction(node); + nodeArrayFlags |= node.transformFlags & ~536870912 /* HasComputedFlags */; + } + nodes.transformFlags = nodeArrayFlags | 536870912 /* HasComputedFlags */; + subtreeTransformFlags |= savedSubtreeTransformFlags; + } + } + function bindEachChild(node) { + ts.forEachChild(node, bind, bindEach); + } + function bindChildrenWorker(node) { + if (checkUnreachable(node)) { + bindEachChild(node); + bindJSDoc(node); + return; + } + switch (node.kind) { + case 224 /* WhileStatement */: + bindWhileStatement(node); + break; + case 223 /* DoStatement */: + bindDoStatement(node); + break; + case 225 /* ForStatement */: + bindForStatement(node); + break; + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + bindForInOrForOfStatement(node); + break; + case 222 /* IfStatement */: + bindIfStatement(node); + break; + case 230 /* ReturnStatement */: + case 234 /* ThrowStatement */: + bindReturnOrThrow(node); + break; + case 229 /* BreakStatement */: + case 228 /* ContinueStatement */: + bindBreakOrContinueStatement(node); + break; + case 235 /* TryStatement */: + bindTryStatement(node); + break; + case 232 /* SwitchStatement */: + bindSwitchStatement(node); + break; + case 246 /* CaseBlock */: + bindCaseBlock(node); + break; + case 271 /* CaseClause */: + bindCaseClause(node); + break; + case 233 /* LabeledStatement */: + bindLabeledStatement(node); + break; + case 202 /* PrefixUnaryExpression */: + bindPrefixUnaryExpressionFlow(node); + break; + case 203 /* PostfixUnaryExpression */: + bindPostfixUnaryExpressionFlow(node); + break; + case 204 /* BinaryExpression */: + bindBinaryExpressionFlow(node); + break; + case 198 /* DeleteExpression */: + bindDeleteExpressionFlow(node); + break; + case 205 /* ConditionalExpression */: + bindConditionalExpressionFlow(node); + break; + case 237 /* VariableDeclaration */: + bindVariableDeclarationFlow(node); + break; + case 191 /* CallExpression */: + bindCallExpressionFlow(node); + break; + case 304 /* JSDocTypedefTag */: + case 297 /* JSDocCallbackTag */: + bindJSDocTypeAlias(node); + break; + // In source files and blocks, bind functions first to match hoisting that occurs at runtime + case 279 /* SourceFile */: { + bindEachFunctionsFirst(node.statements); + bind(node.endOfFileToken); + break; + } + case 218 /* Block */: + case 245 /* ModuleBlock */: + bindEachFunctionsFirst(node.statements); + break; + default: + bindEachChild(node); + break; + } + bindJSDoc(node); + } + function isNarrowingExpression(expr) { + switch (expr.kind) { + case 72 /* Identifier */: + case 100 /* ThisKeyword */: + case 189 /* PropertyAccessExpression */: + case 190 /* ElementAccessExpression */: + return isNarrowableReference(expr); + case 191 /* CallExpression */: + return hasNarrowableArgument(expr); + case 195 /* ParenthesizedExpression */: + return isNarrowingExpression(expr.expression); + case 204 /* BinaryExpression */: + return isNarrowingBinaryExpression(expr); + case 202 /* PrefixUnaryExpression */: + return expr.operator === 52 /* ExclamationToken */ && isNarrowingExpression(expr.operand); + case 199 /* TypeOfExpression */: + return isNarrowingExpression(expr.expression); + } + return false; + } + function isNarrowableReference(expr) { + return expr.kind === 72 /* Identifier */ || expr.kind === 100 /* ThisKeyword */ || expr.kind === 98 /* SuperKeyword */ || + ts.isPropertyAccessExpression(expr) && isNarrowableReference(expr.expression) || + ts.isElementAccessExpression(expr) && expr.argumentExpression && + (ts.isStringLiteral(expr.argumentExpression) || ts.isNumericLiteral(expr.argumentExpression)) && + isNarrowableReference(expr.expression); + } + function hasNarrowableArgument(expr) { + if (expr.arguments) { + for (var _i = 0, _a = expr.arguments; _i < _a.length; _i++) { + var argument = _a[_i]; + if (isNarrowableReference(argument)) { + return true; + } + } + } + if (expr.expression.kind === 189 /* PropertyAccessExpression */ && + isNarrowableReference(expr.expression.expression)) { + return true; + } + return false; + } + function isNarrowingTypeofOperands(expr1, expr2) { + return ts.isTypeOfExpression(expr1) && isNarrowableOperand(expr1.expression) && ts.isStringLiteralLike(expr2); + } + function isNarrowableInOperands(left, right) { + return ts.isStringLiteralLike(left) && isNarrowingExpression(right); + } + function isNarrowingBinaryExpression(expr) { + switch (expr.operatorToken.kind) { + case 59 /* EqualsToken */: + return isNarrowableReference(expr.left); + case 33 /* EqualsEqualsToken */: + case 34 /* ExclamationEqualsToken */: + case 35 /* EqualsEqualsEqualsToken */: + case 36 /* ExclamationEqualsEqualsToken */: + return isNarrowableOperand(expr.left) || isNarrowableOperand(expr.right) || + isNarrowingTypeofOperands(expr.right, expr.left) || isNarrowingTypeofOperands(expr.left, expr.right); + case 94 /* InstanceOfKeyword */: + return isNarrowableOperand(expr.left); + case 93 /* InKeyword */: + return isNarrowableInOperands(expr.left, expr.right); + case 27 /* CommaToken */: + return isNarrowingExpression(expr.right); + } + return false; + } + function isNarrowableOperand(expr) { + switch (expr.kind) { + case 195 /* ParenthesizedExpression */: + return isNarrowableOperand(expr.expression); + case 204 /* BinaryExpression */: + switch (expr.operatorToken.kind) { + case 59 /* EqualsToken */: + return isNarrowableOperand(expr.left); + case 27 /* CommaToken */: + return isNarrowableOperand(expr.right); + } + } + return isNarrowableReference(expr); + } + function createBranchLabel() { + return { + flags: 4 /* BranchLabel */, + antecedents: undefined + }; + } + function createLoopLabel() { + return { + flags: 8 /* LoopLabel */, + antecedents: undefined + }; + } + function setFlowNodeReferenced(flow) { + // On first reference we set the Referenced flag, thereafter we set the Shared flag + flow.flags |= flow.flags & 512 /* Referenced */ ? 1024 /* Shared */ : 512 /* Referenced */; + } + function addAntecedent(label, antecedent) { + if (!(antecedent.flags & 1 /* Unreachable */) && !ts.contains(label.antecedents, antecedent)) { + (label.antecedents || (label.antecedents = [])).push(antecedent); + setFlowNodeReferenced(antecedent); + } + } + function createFlowCondition(flags, antecedent, expression) { + if (antecedent.flags & 1 /* Unreachable */) { + return antecedent; + } + if (!expression) { + return flags & 32 /* TrueCondition */ ? antecedent : unreachableFlow; + } + if (expression.kind === 102 /* TrueKeyword */ && flags & 64 /* FalseCondition */ || + expression.kind === 87 /* FalseKeyword */ && flags & 32 /* TrueCondition */) { + return unreachableFlow; + } + if (!isNarrowingExpression(expression)) { + return antecedent; + } + setFlowNodeReferenced(antecedent); + return { flags: flags, expression: expression, antecedent: antecedent }; + } + function createFlowSwitchClause(antecedent, switchStatement, clauseStart, clauseEnd) { + if (!isNarrowingExpression(switchStatement.expression)) { + return antecedent; + } + setFlowNodeReferenced(antecedent); + return { flags: 128 /* SwitchClause */, switchStatement: switchStatement, clauseStart: clauseStart, clauseEnd: clauseEnd, antecedent: antecedent }; + } + function createFlowAssignment(antecedent, node) { + setFlowNodeReferenced(antecedent); + return { flags: 16 /* Assignment */, antecedent: antecedent, node: node }; + } + function createFlowArrayMutation(antecedent, node) { + setFlowNodeReferenced(antecedent); + var res = { flags: 256 /* ArrayMutation */, antecedent: antecedent, node: node }; + return res; + } + function finishFlowLabel(flow) { + var antecedents = flow.antecedents; + if (!antecedents) { + return unreachableFlow; + } + if (antecedents.length === 1) { + return antecedents[0]; + } + return flow; + } + function isStatementCondition(node) { + var parent = node.parent; + switch (parent.kind) { + case 222 /* IfStatement */: + case 224 /* WhileStatement */: + case 223 /* DoStatement */: + return parent.expression === node; + case 225 /* ForStatement */: + case 205 /* ConditionalExpression */: + return parent.condition === node; + } + return false; + } + function isLogicalExpression(node) { + while (true) { + if (node.kind === 195 /* ParenthesizedExpression */) { + node = node.expression; + } + else if (node.kind === 202 /* PrefixUnaryExpression */ && node.operator === 52 /* ExclamationToken */) { + node = node.operand; + } + else { + return node.kind === 204 /* BinaryExpression */ && (node.operatorToken.kind === 54 /* AmpersandAmpersandToken */ || + node.operatorToken.kind === 55 /* BarBarToken */); + } + } + } + function isTopLevelLogicalExpression(node) { + while (node.parent.kind === 195 /* ParenthesizedExpression */ || + node.parent.kind === 202 /* PrefixUnaryExpression */ && + node.parent.operator === 52 /* ExclamationToken */) { + node = node.parent; + } + return !isStatementCondition(node) && !isLogicalExpression(node.parent); + } + function bindCondition(node, trueTarget, falseTarget) { + var saveTrueTarget = currentTrueTarget; + var saveFalseTarget = currentFalseTarget; + currentTrueTarget = trueTarget; + currentFalseTarget = falseTarget; + bind(node); + currentTrueTarget = saveTrueTarget; + currentFalseTarget = saveFalseTarget; + if (!node || !isLogicalExpression(node)) { + addAntecedent(trueTarget, createFlowCondition(32 /* TrueCondition */, currentFlow, node)); + addAntecedent(falseTarget, createFlowCondition(64 /* FalseCondition */, currentFlow, node)); + } + } + function bindIterativeStatement(node, breakTarget, continueTarget) { + var saveBreakTarget = currentBreakTarget; + var saveContinueTarget = currentContinueTarget; + currentBreakTarget = breakTarget; + currentContinueTarget = continueTarget; + bind(node); + currentBreakTarget = saveBreakTarget; + currentContinueTarget = saveContinueTarget; + } + function bindWhileStatement(node) { + var preWhileLabel = createLoopLabel(); + var preBodyLabel = createBranchLabel(); + var postWhileLabel = createBranchLabel(); + addAntecedent(preWhileLabel, currentFlow); + currentFlow = preWhileLabel; + bindCondition(node.expression, preBodyLabel, postWhileLabel); + currentFlow = finishFlowLabel(preBodyLabel); + bindIterativeStatement(node.statement, postWhileLabel, preWhileLabel); + addAntecedent(preWhileLabel, currentFlow); + currentFlow = finishFlowLabel(postWhileLabel); + } + function bindDoStatement(node) { + var preDoLabel = createLoopLabel(); + var enclosingLabeledStatement = node.parent.kind === 233 /* LabeledStatement */ + ? ts.lastOrUndefined(activeLabels) + : undefined; + // if do statement is wrapped in labeled statement then target labels for break/continue with or without + // label should be the same + var preConditionLabel = enclosingLabeledStatement ? enclosingLabeledStatement.continueTarget : createBranchLabel(); + var postDoLabel = enclosingLabeledStatement ? enclosingLabeledStatement.breakTarget : createBranchLabel(); + addAntecedent(preDoLabel, currentFlow); + currentFlow = preDoLabel; + bindIterativeStatement(node.statement, postDoLabel, preConditionLabel); + addAntecedent(preConditionLabel, currentFlow); + currentFlow = finishFlowLabel(preConditionLabel); + bindCondition(node.expression, preDoLabel, postDoLabel); + currentFlow = finishFlowLabel(postDoLabel); + } + function bindForStatement(node) { + var preLoopLabel = createLoopLabel(); + var preBodyLabel = createBranchLabel(); + var postLoopLabel = createBranchLabel(); + bind(node.initializer); + addAntecedent(preLoopLabel, currentFlow); + currentFlow = preLoopLabel; + bindCondition(node.condition, preBodyLabel, postLoopLabel); + currentFlow = finishFlowLabel(preBodyLabel); + bindIterativeStatement(node.statement, postLoopLabel, preLoopLabel); + bind(node.incrementor); + addAntecedent(preLoopLabel, currentFlow); + currentFlow = finishFlowLabel(postLoopLabel); + } + function bindForInOrForOfStatement(node) { + var preLoopLabel = createLoopLabel(); + var postLoopLabel = createBranchLabel(); + addAntecedent(preLoopLabel, currentFlow); + currentFlow = preLoopLabel; + if (node.kind === 227 /* ForOfStatement */) { + bind(node.awaitModifier); + } + bind(node.expression); + addAntecedent(postLoopLabel, currentFlow); + bind(node.initializer); + if (node.initializer.kind !== 238 /* VariableDeclarationList */) { + bindAssignmentTargetFlow(node.initializer); + } + bindIterativeStatement(node.statement, postLoopLabel, preLoopLabel); + addAntecedent(preLoopLabel, currentFlow); + currentFlow = finishFlowLabel(postLoopLabel); + } + function bindIfStatement(node) { + var thenLabel = createBranchLabel(); + var elseLabel = createBranchLabel(); + var postIfLabel = createBranchLabel(); + bindCondition(node.expression, thenLabel, elseLabel); + currentFlow = finishFlowLabel(thenLabel); + bind(node.thenStatement); + addAntecedent(postIfLabel, currentFlow); + currentFlow = finishFlowLabel(elseLabel); + bind(node.elseStatement); + addAntecedent(postIfLabel, currentFlow); + currentFlow = finishFlowLabel(postIfLabel); + } + function bindReturnOrThrow(node) { + bind(node.expression); + if (node.kind === 230 /* ReturnStatement */) { + hasExplicitReturn = true; + if (currentReturnTarget) { + addAntecedent(currentReturnTarget, currentFlow); + } + } + currentFlow = unreachableFlow; + } + function findActiveLabel(name) { + if (activeLabels) { + for (var _i = 0, activeLabels_1 = activeLabels; _i < activeLabels_1.length; _i++) { + var label = activeLabels_1[_i]; + if (label.name === name) { + return label; + } + } + } + return undefined; + } + function bindBreakOrContinueFlow(node, breakTarget, continueTarget) { + var flowLabel = node.kind === 229 /* BreakStatement */ ? breakTarget : continueTarget; + if (flowLabel) { + addAntecedent(flowLabel, currentFlow); + currentFlow = unreachableFlow; + } + } + function bindBreakOrContinueStatement(node) { + bind(node.label); + if (node.label) { + var activeLabel = findActiveLabel(node.label.escapedText); + if (activeLabel) { + activeLabel.referenced = true; + bindBreakOrContinueFlow(node, activeLabel.breakTarget, activeLabel.continueTarget); + } + } + else { + bindBreakOrContinueFlow(node, currentBreakTarget, currentContinueTarget); + } + } + function bindTryStatement(node) { + var preFinallyLabel = createBranchLabel(); + var preTryFlow = currentFlow; + // TODO: Every statement in try block is potentially an exit point! + bind(node.tryBlock); + addAntecedent(preFinallyLabel, currentFlow); + var flowAfterTry = currentFlow; + var flowAfterCatch = unreachableFlow; + if (node.catchClause) { + currentFlow = preTryFlow; + bind(node.catchClause); + addAntecedent(preFinallyLabel, currentFlow); + flowAfterCatch = currentFlow; + } + if (node.finallyBlock) { + // in finally flow is combined from pre-try/flow from try/flow from catch + // pre-flow is necessary to make sure that finally is reachable even if finally flows in both try and finally blocks are unreachable + // also for finally blocks we inject two extra edges into the flow graph. + // first -> edge that connects pre-try flow with the label at the beginning of the finally block, it has lock associated with it + // second -> edge that represents post-finally flow. + // these edges are used in following scenario: + // let a; (1) + // try { a = someOperation(); (2)} + // finally { (3) console.log(a) } (4) + // (5) a + // flow graph for this case looks roughly like this (arrows show ): + // (1-pre-try-flow) <--.. <-- (2-post-try-flow) + // ^ ^ + // |*****(3-pre-finally-label) -----| + // ^ + // |-- ... <-- (4-post-finally-label) <--- (5) + // In case when we walk the flow starting from inside the finally block we want to take edge '*****' into account + // since it ensures that finally is always reachable. However when we start outside the finally block and go through label (5) + // then edge '*****' should be discarded because label 4 is only reachable if post-finally label-4 is reachable + // Simply speaking code inside finally block is treated as reachable as pre-try-flow + // since we conservatively assume that any line in try block can throw or return in which case we'll enter finally. + // However code after finally is reachable only if control flow was not abrupted in try/catch or finally blocks - it should be composed from + // final flows of these blocks without taking pre-try flow into account. + // + // extra edges that we inject allows to control this behavior + // if when walking the flow we step on post-finally edge - we can mark matching pre-finally edge as locked so it will be skipped. + var preFinallyFlow = { flags: 2048 /* PreFinally */, antecedent: preTryFlow, lock: {} }; + addAntecedent(preFinallyLabel, preFinallyFlow); + currentFlow = finishFlowLabel(preFinallyLabel); + bind(node.finallyBlock); + // if flow after finally is unreachable - keep it + // otherwise check if flows after try and after catch are unreachable + // if yes - convert current flow to unreachable + // i.e. + // try { return "1" } finally { console.log(1); } + // console.log(2); // this line should be unreachable even if flow falls out of finally block + if (!(currentFlow.flags & 1 /* Unreachable */)) { + if ((flowAfterTry.flags & 1 /* Unreachable */) && (flowAfterCatch.flags & 1 /* Unreachable */)) { + currentFlow = flowAfterTry === reportedUnreachableFlow || flowAfterCatch === reportedUnreachableFlow + ? reportedUnreachableFlow + : unreachableFlow; + } + } + if (!(currentFlow.flags & 1 /* Unreachable */)) { + var afterFinallyFlow = { flags: 4096 /* AfterFinally */, antecedent: currentFlow }; + preFinallyFlow.lock = afterFinallyFlow; + currentFlow = afterFinallyFlow; + } + } + else { + currentFlow = finishFlowLabel(preFinallyLabel); + } + } + function bindSwitchStatement(node) { + var postSwitchLabel = createBranchLabel(); + bind(node.expression); + var saveBreakTarget = currentBreakTarget; + var savePreSwitchCaseFlow = preSwitchCaseFlow; + currentBreakTarget = postSwitchLabel; + preSwitchCaseFlow = currentFlow; + bind(node.caseBlock); + addAntecedent(postSwitchLabel, currentFlow); + var hasDefault = ts.forEach(node.caseBlock.clauses, function (c) { return c.kind === 272 /* DefaultClause */; }); + // We mark a switch statement as possibly exhaustive if it has no default clause and if all + // case clauses have unreachable end points (e.g. they all return). + node.possiblyExhaustive = !hasDefault && !postSwitchLabel.antecedents; + if (!hasDefault) { + addAntecedent(postSwitchLabel, createFlowSwitchClause(preSwitchCaseFlow, node, 0, 0)); + } + currentBreakTarget = saveBreakTarget; + preSwitchCaseFlow = savePreSwitchCaseFlow; + currentFlow = finishFlowLabel(postSwitchLabel); + } + function bindCaseBlock(node) { + var savedSubtreeTransformFlags = subtreeTransformFlags; + subtreeTransformFlags = 0; + var clauses = node.clauses; + var fallthroughFlow = unreachableFlow; + for (var i = 0; i < clauses.length; i++) { + var clauseStart = i; + while (!clauses[i].statements.length && i + 1 < clauses.length) { + bind(clauses[i]); + i++; + } + var preCaseLabel = createBranchLabel(); + addAntecedent(preCaseLabel, createFlowSwitchClause(preSwitchCaseFlow, node.parent, clauseStart, i + 1)); + addAntecedent(preCaseLabel, fallthroughFlow); + currentFlow = finishFlowLabel(preCaseLabel); + var clause = clauses[i]; + bind(clause); + fallthroughFlow = currentFlow; + if (!(currentFlow.flags & 1 /* Unreachable */) && i !== clauses.length - 1 && options.noFallthroughCasesInSwitch) { + errorOnFirstToken(clause, ts.Diagnostics.Fallthrough_case_in_switch); + } + } + clauses.transformFlags = subtreeTransformFlags | 536870912 /* HasComputedFlags */; + subtreeTransformFlags |= savedSubtreeTransformFlags; + } + function bindCaseClause(node) { + var saveCurrentFlow = currentFlow; + currentFlow = preSwitchCaseFlow; + bind(node.expression); + currentFlow = saveCurrentFlow; + bindEach(node.statements); + } + function pushActiveLabel(name, breakTarget, continueTarget) { + var activeLabel = { + name: name, + breakTarget: breakTarget, + continueTarget: continueTarget, + referenced: false + }; + (activeLabels || (activeLabels = [])).push(activeLabel); + return activeLabel; + } + function popActiveLabel() { + activeLabels.pop(); + } + function bindLabeledStatement(node) { + var preStatementLabel = createLoopLabel(); + var postStatementLabel = createBranchLabel(); + bind(node.label); + addAntecedent(preStatementLabel, currentFlow); + var activeLabel = pushActiveLabel(node.label.escapedText, postStatementLabel, preStatementLabel); + bind(node.statement); + popActiveLabel(); + if (!activeLabel.referenced && !options.allowUnusedLabels) { + errorOrSuggestionOnNode(ts.unusedLabelIsError(options), node.label, ts.Diagnostics.Unused_label); + } + if (!node.statement || node.statement.kind !== 223 /* DoStatement */) { + // do statement sets current flow inside bindDoStatement + addAntecedent(postStatementLabel, currentFlow); + currentFlow = finishFlowLabel(postStatementLabel); + } + } + function bindDestructuringTargetFlow(node) { + if (node.kind === 204 /* BinaryExpression */ && node.operatorToken.kind === 59 /* EqualsToken */) { + bindAssignmentTargetFlow(node.left); + } + else { + bindAssignmentTargetFlow(node); + } + } + function bindAssignmentTargetFlow(node) { + if (isNarrowableReference(node)) { + currentFlow = createFlowAssignment(currentFlow, node); + } + else if (node.kind === 187 /* ArrayLiteralExpression */) { + for (var _i = 0, _a = node.elements; _i < _a.length; _i++) { + var e = _a[_i]; + if (e.kind === 208 /* SpreadElement */) { + bindAssignmentTargetFlow(e.expression); + } + else { + bindDestructuringTargetFlow(e); + } + } + } + else if (node.kind === 188 /* ObjectLiteralExpression */) { + for (var _b = 0, _c = node.properties; _b < _c.length; _b++) { + var p = _c[_b]; + if (p.kind === 275 /* PropertyAssignment */) { + bindDestructuringTargetFlow(p.initializer); + } + else if (p.kind === 276 /* ShorthandPropertyAssignment */) { + bindAssignmentTargetFlow(p.name); + } + else if (p.kind === 277 /* SpreadAssignment */) { + bindAssignmentTargetFlow(p.expression); + } + } + } + } + function bindLogicalExpression(node, trueTarget, falseTarget) { + var preRightLabel = createBranchLabel(); + if (node.operatorToken.kind === 54 /* AmpersandAmpersandToken */) { + bindCondition(node.left, preRightLabel, falseTarget); + } + else { + bindCondition(node.left, trueTarget, preRightLabel); + } + currentFlow = finishFlowLabel(preRightLabel); + bind(node.operatorToken); + bindCondition(node.right, trueTarget, falseTarget); + } + function bindPrefixUnaryExpressionFlow(node) { + if (node.operator === 52 /* ExclamationToken */) { + var saveTrueTarget = currentTrueTarget; + currentTrueTarget = currentFalseTarget; + currentFalseTarget = saveTrueTarget; + bindEachChild(node); + currentFalseTarget = currentTrueTarget; + currentTrueTarget = saveTrueTarget; + } + else { + bindEachChild(node); + if (node.operator === 44 /* PlusPlusToken */ || node.operator === 45 /* MinusMinusToken */) { + bindAssignmentTargetFlow(node.operand); + } + } + } + function bindPostfixUnaryExpressionFlow(node) { + bindEachChild(node); + if (node.operator === 44 /* PlusPlusToken */ || node.operator === 45 /* MinusMinusToken */) { + bindAssignmentTargetFlow(node.operand); + } + } + function bindBinaryExpressionFlow(node) { + var operator = node.operatorToken.kind; + if (operator === 54 /* AmpersandAmpersandToken */ || operator === 55 /* BarBarToken */) { + if (isTopLevelLogicalExpression(node)) { + var postExpressionLabel = createBranchLabel(); + bindLogicalExpression(node, postExpressionLabel, postExpressionLabel); + currentFlow = finishFlowLabel(postExpressionLabel); + } + else { + bindLogicalExpression(node, currentTrueTarget, currentFalseTarget); + } + } + else { + bindEachChild(node); + if (ts.isAssignmentOperator(operator) && !ts.isAssignmentTarget(node)) { + bindAssignmentTargetFlow(node.left); + if (operator === 59 /* EqualsToken */ && node.left.kind === 190 /* ElementAccessExpression */) { + var elementAccess = node.left; + if (isNarrowableOperand(elementAccess.expression)) { + currentFlow = createFlowArrayMutation(currentFlow, node); + } + } + } + } + } + function bindDeleteExpressionFlow(node) { + bindEachChild(node); + if (node.expression.kind === 189 /* PropertyAccessExpression */) { + bindAssignmentTargetFlow(node.expression); + } + } + function bindConditionalExpressionFlow(node) { + var trueLabel = createBranchLabel(); + var falseLabel = createBranchLabel(); + var postExpressionLabel = createBranchLabel(); + bindCondition(node.condition, trueLabel, falseLabel); + currentFlow = finishFlowLabel(trueLabel); + bind(node.questionToken); + bind(node.whenTrue); + addAntecedent(postExpressionLabel, currentFlow); + currentFlow = finishFlowLabel(falseLabel); + bind(node.colonToken); + bind(node.whenFalse); + addAntecedent(postExpressionLabel, currentFlow); + currentFlow = finishFlowLabel(postExpressionLabel); + } + function bindInitializedVariableFlow(node) { + var name = !ts.isOmittedExpression(node) ? node.name : undefined; + if (ts.isBindingPattern(name)) { + for (var _i = 0, _a = name.elements; _i < _a.length; _i++) { + var child = _a[_i]; + bindInitializedVariableFlow(child); + } + } + else { + currentFlow = createFlowAssignment(currentFlow, node); + } + } + function bindVariableDeclarationFlow(node) { + bindEachChild(node); + if (node.initializer || ts.isForInOrOfStatement(node.parent.parent)) { + bindInitializedVariableFlow(node); + } + } + function bindJSDocTypeAlias(node) { + node.tagName.parent = node; + if (node.fullName) { + setParentPointers(node, node.fullName); + } + } + function bindCallExpressionFlow(node) { + // If the target of the call expression is a function expression or arrow function we have + // an immediately invoked function expression (IIFE). Initialize the flowNode property to + // the current control flow (which includes evaluation of the IIFE arguments). + var expr = node.expression; + while (expr.kind === 195 /* ParenthesizedExpression */) { + expr = expr.expression; + } + if (expr.kind === 196 /* FunctionExpression */ || expr.kind === 197 /* ArrowFunction */) { + bindEach(node.typeArguments); + bindEach(node.arguments); + bind(node.expression); + } + else { + bindEachChild(node); + } + if (node.expression.kind === 189 /* PropertyAccessExpression */) { + var propertyAccess = node.expression; + if (isNarrowableOperand(propertyAccess.expression) && ts.isPushOrUnshiftIdentifier(propertyAccess.name)) { + currentFlow = createFlowArrayMutation(currentFlow, node); + } + } + } + function getContainerFlags(node) { + switch (node.kind) { + case 209 /* ClassExpression */: + case 240 /* ClassDeclaration */: + case 243 /* EnumDeclaration */: + case 188 /* ObjectLiteralExpression */: + case 168 /* TypeLiteral */: + case 292 /* JSDocTypeLiteral */: + case 268 /* JsxAttributes */: + return 1 /* IsContainer */; + case 241 /* InterfaceDeclaration */: + return 1 /* IsContainer */ | 64 /* IsInterface */; + case 244 /* ModuleDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 181 /* MappedType */: + return 1 /* IsContainer */ | 32 /* HasLocals */; + case 279 /* SourceFile */: + return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */; + case 156 /* MethodDeclaration */: + if (ts.isObjectLiteralOrClassExpressionMethod(node)) { + return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */ | 128 /* IsObjectLiteralOrClassExpressionMethod */; + } + // falls through + case 157 /* Constructor */: + case 239 /* FunctionDeclaration */: + case 155 /* MethodSignature */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 160 /* CallSignature */: + case 293 /* JSDocSignature */: + case 289 /* JSDocFunctionType */: + case 165 /* FunctionType */: + case 161 /* ConstructSignature */: + case 162 /* IndexSignature */: + case 166 /* ConstructorType */: + return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */; + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */ | 16 /* IsFunctionExpression */; + case 245 /* ModuleBlock */: + return 4 /* IsControlFlowContainer */; + case 154 /* PropertyDeclaration */: + return node.initializer ? 4 /* IsControlFlowContainer */ : 0; + case 274 /* CatchClause */: + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + case 246 /* CaseBlock */: + return 2 /* IsBlockScopedContainer */; + case 218 /* Block */: + // do not treat blocks directly inside a function as a block-scoped-container. + // Locals that reside in this block should go to the function locals. Otherwise 'x' + // would not appear to be a redeclaration of a block scoped local in the following + // example: + // + // function foo() { + // var x; + // let x; + // } + // + // If we placed 'var x' into the function locals and 'let x' into the locals of + // the block, then there would be no collision. + // + // By not creating a new block-scoped-container here, we ensure that both 'var x' + // and 'let x' go into the Function-container's locals, and we do get a collision + // conflict. + return ts.isFunctionLike(node.parent) ? 0 /* None */ : 2 /* IsBlockScopedContainer */; + } + return 0 /* None */; + } + function addToContainerChain(next) { + if (lastContainer) { + lastContainer.nextContainer = next; + } + lastContainer = next; + } + function declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes) { + switch (container.kind) { + // Modules, source files, and classes need specialized handling for how their + // members are declared (for example, a member of a class will go into a specific + // symbol table depending on if it is static or not). We defer to specialized + // handlers to take care of declaring these child members. + case 244 /* ModuleDeclaration */: + return declareModuleMember(node, symbolFlags, symbolExcludes); + case 279 /* SourceFile */: + return declareSourceFileMember(node, symbolFlags, symbolExcludes); + case 209 /* ClassExpression */: + case 240 /* ClassDeclaration */: + return declareClassMember(node, symbolFlags, symbolExcludes); + case 243 /* EnumDeclaration */: + return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); + case 168 /* TypeLiteral */: + case 292 /* JSDocTypeLiteral */: + case 188 /* ObjectLiteralExpression */: + case 241 /* InterfaceDeclaration */: + case 268 /* JsxAttributes */: + // Interface/Object-types always have their children added to the 'members' of + // their container. They are only accessible through an instance of their + // container, and are never in scope otherwise (even inside the body of the + // object / type / interface declaring them). An exception is type parameters, + // which are in scope without qualification (similar to 'locals'). + return declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes); + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 293 /* JSDocSignature */: + case 162 /* IndexSignature */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 289 /* JSDocFunctionType */: + case 304 /* JSDocTypedefTag */: + case 297 /* JSDocCallbackTag */: + case 242 /* TypeAliasDeclaration */: + case 181 /* MappedType */: + // All the children of these container types are never visible through another + // symbol (i.e. through another symbol's 'exports' or 'members'). Instead, + // they're only accessed 'lexically' (i.e. from code that exists underneath + // their container in the tree). To accomplish this, we simply add their declared + // symbol to the 'locals' of the container. These symbols can then be found as + // the type checker walks up the containers, checking them for matching names. + return declareSymbol(container.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes); + } + } + function declareClassMember(node, symbolFlags, symbolExcludes) { + return ts.hasModifier(node, 32 /* Static */) + ? declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes) + : declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes); + } + function declareSourceFileMember(node, symbolFlags, symbolExcludes) { + return ts.isExternalModule(file) + ? declareModuleMember(node, symbolFlags, symbolExcludes) + : declareSymbol(file.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes); + } + function hasExportDeclarations(node) { + var body = node.kind === 279 /* SourceFile */ ? node : node.body; + if (body && (body.kind === 279 /* SourceFile */ || body.kind === 245 /* ModuleBlock */)) { + for (var _i = 0, _a = body.statements; _i < _a.length; _i++) { + var stat = _a[_i]; + if (stat.kind === 255 /* ExportDeclaration */ || stat.kind === 254 /* ExportAssignment */) { + return true; + } + } + } + return false; + } + function setExportContextFlag(node) { + // A declaration source file or ambient module declaration that contains no export declarations (but possibly regular + // declarations with export modifiers) is an export context in which declarations are implicitly exported. + if (node.flags & 4194304 /* Ambient */ && !hasExportDeclarations(node)) { + node.flags |= 32 /* ExportContext */; + } + else { + node.flags &= ~32 /* ExportContext */; + } + } + function bindModuleDeclaration(node) { + setExportContextFlag(node); + if (ts.isAmbientModule(node)) { + if (ts.hasModifier(node, 1 /* Export */)) { + errorOnFirstToken(node, ts.Diagnostics.export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always_visible); + } + if (ts.isModuleAugmentationExternal(node)) { + declareModuleSymbol(node); + } + else { + var pattern = void 0; + if (node.name.kind === 10 /* StringLiteral */) { + var text = node.name.text; + if (ts.hasZeroOrOneAsteriskCharacter(text)) { + pattern = ts.tryParsePattern(text); + } + else { + errorOnFirstToken(node.name, ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, text); + } + } + var symbol = declareSymbolAndAddToSymbolTable(node, 512 /* ValueModule */, 110735 /* ValueModuleExcludes */); + file.patternAmbientModules = ts.append(file.patternAmbientModules, pattern && { pattern: pattern, symbol: symbol }); + } + } + else { + var state = declareModuleSymbol(node); + if (state !== 0 /* NonInstantiated */) { + var symbol = node.symbol; + // if module was already merged with some function, class or non-const enum, treat it as non-const-enum-only + symbol.constEnumOnlyModule = (!(symbol.flags & (16 /* Function */ | 32 /* Class */ | 256 /* RegularEnum */))) + // Current must be `const enum` only + && state === 2 /* ConstEnumOnly */ + // Can't have been set to 'false' in a previous merged symbol. ('undefined' OK) + && symbol.constEnumOnlyModule !== false; + } + } + } + function declareModuleSymbol(node) { + var state = getModuleInstanceState(node); + var instantiated = state !== 0 /* NonInstantiated */; + declareSymbolAndAddToSymbolTable(node, instantiated ? 512 /* ValueModule */ : 1024 /* NamespaceModule */, instantiated ? 110735 /* ValueModuleExcludes */ : 0 /* NamespaceModuleExcludes */); + return state; + } + function bindFunctionOrConstructorType(node) { + // For a given function symbol "<...>(...) => T" we want to generate a symbol identical + // to the one we would get for: { <...>(...): T } + // + // We do that by making an anonymous type literal symbol, and then setting the function + // symbol as its sole member. To the rest of the system, this symbol will be indistinguishable + // from an actual type literal symbol you would have gotten had you used the long form. + var symbol = createSymbol(131072 /* Signature */, getDeclarationName(node)); // TODO: GH#18217 + addDeclarationToSymbol(symbol, node, 131072 /* Signature */); + var typeLiteralSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */); + addDeclarationToSymbol(typeLiteralSymbol, node, 2048 /* TypeLiteral */); + typeLiteralSymbol.members = ts.createSymbolTable(); + typeLiteralSymbol.members.set(symbol.escapedName, symbol); + } + function bindObjectLiteralExpression(node) { + var ElementKind; + (function (ElementKind) { + ElementKind[ElementKind["Property"] = 1] = "Property"; + ElementKind[ElementKind["Accessor"] = 2] = "Accessor"; + })(ElementKind || (ElementKind = {})); + if (inStrictMode) { + var seen = ts.createUnderscoreEscapedMap(); + for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { + var prop = _a[_i]; + if (prop.kind === 277 /* SpreadAssignment */ || prop.name.kind !== 72 /* Identifier */) { + continue; + } + var identifier = prop.name; + // ECMA-262 11.1.5 Object Initializer + // If previous is not undefined then throw a SyntaxError exception if any of the following conditions are true + // a.This production is contained in strict code and IsDataDescriptor(previous) is true and + // IsDataDescriptor(propId.descriptor) is true. + // b.IsDataDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true. + // c.IsAccessorDescriptor(previous) is true and IsDataDescriptor(propId.descriptor) is true. + // d.IsAccessorDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true + // and either both previous and propId.descriptor have[[Get]] fields or both previous and propId.descriptor have[[Set]] fields + var currentKind = prop.kind === 275 /* PropertyAssignment */ || prop.kind === 276 /* ShorthandPropertyAssignment */ || prop.kind === 156 /* MethodDeclaration */ + ? 1 /* Property */ + : 2 /* Accessor */; + var existingKind = seen.get(identifier.escapedText); + if (!existingKind) { + seen.set(identifier.escapedText, currentKind); + continue; + } + if (currentKind === 1 /* Property */ && existingKind === 1 /* Property */) { + var span = ts.getErrorSpanForNode(file, identifier); + file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, ts.Diagnostics.An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode)); + } + } + } + return bindAnonymousDeclaration(node, 4096 /* ObjectLiteral */, "__object" /* Object */); + } + function bindJsxAttributes(node) { + return bindAnonymousDeclaration(node, 4096 /* ObjectLiteral */, "__jsxAttributes" /* JSXAttributes */); + } + function bindJsxAttribute(node, symbolFlags, symbolExcludes) { + return declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes); + } + function bindAnonymousDeclaration(node, symbolFlags, name) { + var symbol = createSymbol(symbolFlags, name); + if (symbolFlags & (8 /* EnumMember */ | 106500 /* ClassMember */)) { + symbol.parent = container.symbol; + } + addDeclarationToSymbol(symbol, node, symbolFlags); + return symbol; + } + function bindBlockScopedDeclaration(node, symbolFlags, symbolExcludes) { + switch (blockScopeContainer.kind) { + case 244 /* ModuleDeclaration */: + declareModuleMember(node, symbolFlags, symbolExcludes); + break; + case 279 /* SourceFile */: + if (ts.isExternalOrCommonJsModule(container)) { + declareModuleMember(node, symbolFlags, symbolExcludes); + break; + } + // falls through + default: + if (!blockScopeContainer.locals) { + blockScopeContainer.locals = ts.createSymbolTable(); + addToContainerChain(blockScopeContainer); + } + declareSymbol(blockScopeContainer.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes); + } + } + function delayedBindJSDocTypedefTag() { + if (!delayedTypeAliases) { + return; + } + var saveContainer = container; + var saveLastContainer = lastContainer; + var saveBlockScopeContainer = blockScopeContainer; + var saveParent = parent; + var saveCurrentFlow = currentFlow; + for (var _i = 0, delayedTypeAliases_1 = delayedTypeAliases; _i < delayedTypeAliases_1.length; _i++) { + var typeAlias = delayedTypeAliases_1[_i]; + var host = ts.getJSDocHost(typeAlias); + container = ts.findAncestor(host.parent, function (n) { return !!(getContainerFlags(n) & 1 /* IsContainer */); }) || file; + blockScopeContainer = ts.getEnclosingBlockScopeContainer(host) || file; + currentFlow = { flags: 2 /* Start */ }; + parent = typeAlias; + bind(typeAlias.typeExpression); + if (!typeAlias.fullName || typeAlias.fullName.kind === 72 /* Identifier */) { + parent = typeAlias.parent; + bindBlockScopedDeclaration(typeAlias, 524288 /* TypeAlias */, 67897832 /* TypeAliasExcludes */); + } + else { + bind(typeAlias.fullName); + } + } + container = saveContainer; + lastContainer = saveLastContainer; + blockScopeContainer = saveBlockScopeContainer; + parent = saveParent; + currentFlow = saveCurrentFlow; + } + // The binder visits every node in the syntax tree so it is a convenient place to perform a single localized + // check for reserved words used as identifiers in strict mode code. + function checkStrictModeIdentifier(node) { + if (inStrictMode && + node.originalKeywordKind >= 109 /* FirstFutureReservedWord */ && + node.originalKeywordKind <= 117 /* LastFutureReservedWord */ && + !ts.isIdentifierName(node) && + !(node.flags & 4194304 /* Ambient */)) { + // Report error only if there are no parse errors in file + if (!file.parseDiagnostics.length) { + file.bindDiagnostics.push(createDiagnosticForNode(node, getStrictModeIdentifierMessage(node), ts.declarationNameToString(node))); + } + } + } + function getStrictModeIdentifierMessage(node) { + // Provide specialized messages to help the user understand why we think they're in + // strict mode. + if (ts.getContainingClass(node)) { + return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode; + } + if (file.externalModuleIndicator) { + return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode; + } + return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode; + } + function checkStrictModeBinaryExpression(node) { + if (inStrictMode && ts.isLeftHandSideExpression(node.left) && ts.isAssignmentOperator(node.operatorToken.kind)) { + // ECMA 262 (Annex C) The identifier eval or arguments may not appear as the LeftHandSideExpression of an + // Assignment operator(11.13) or of a PostfixExpression(11.3) + checkStrictModeEvalOrArguments(node, node.left); + } + } + function checkStrictModeCatchClause(node) { + // It is a SyntaxError if a TryStatement with a Catch occurs within strict code and the Identifier of the + // Catch production is eval or arguments + if (inStrictMode && node.variableDeclaration) { + checkStrictModeEvalOrArguments(node, node.variableDeclaration.name); + } + } + function checkStrictModeDeleteExpression(node) { + // Grammar checking + if (inStrictMode && node.expression.kind === 72 /* Identifier */) { + // When a delete operator occurs within strict mode code, a SyntaxError is thrown if its + // UnaryExpression is a direct reference to a variable, function argument, or function name + var span = ts.getErrorSpanForNode(file, node.expression); + file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, ts.Diagnostics.delete_cannot_be_called_on_an_identifier_in_strict_mode)); + } + } + function isEvalOrArgumentsIdentifier(node) { + return ts.isIdentifier(node) && (node.escapedText === "eval" || node.escapedText === "arguments"); + } + function checkStrictModeEvalOrArguments(contextNode, name) { + if (name && name.kind === 72 /* Identifier */) { + var identifier = name; + if (isEvalOrArgumentsIdentifier(identifier)) { + // We check first if the name is inside class declaration or class expression; if so give explicit message + // otherwise report generic error message. + var span = ts.getErrorSpanForNode(file, name); + file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, getStrictModeEvalOrArgumentsMessage(contextNode), ts.idText(identifier))); + } + } + } + function getStrictModeEvalOrArgumentsMessage(node) { + // Provide specialized messages to help the user understand why we think they're in + // strict mode. + if (ts.getContainingClass(node)) { + return ts.Diagnostics.Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode; + } + if (file.externalModuleIndicator) { + return ts.Diagnostics.Invalid_use_of_0_Modules_are_automatically_in_strict_mode; + } + return ts.Diagnostics.Invalid_use_of_0_in_strict_mode; + } + function checkStrictModeFunctionName(node) { + if (inStrictMode) { + // It is a SyntaxError if the identifier eval or arguments appears within a FormalParameterList of a strict mode FunctionDeclaration or FunctionExpression (13.1)) + checkStrictModeEvalOrArguments(node, node.name); + } + } + function getStrictModeBlockScopeFunctionDeclarationMessage(node) { + // Provide specialized messages to help the user understand why we think they're in + // strict mode. + if (ts.getContainingClass(node)) { + return ts.Diagnostics.Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_definitions_are_automatically_in_strict_mode; + } + if (file.externalModuleIndicator) { + return ts.Diagnostics.Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_are_automatically_in_strict_mode; + } + return ts.Diagnostics.Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5; + } + function checkStrictModeFunctionDeclaration(node) { + if (languageVersion < 2 /* ES2015 */) { + // Report error if function is not top level function declaration + if (blockScopeContainer.kind !== 279 /* SourceFile */ && + blockScopeContainer.kind !== 244 /* ModuleDeclaration */ && + !ts.isFunctionLike(blockScopeContainer)) { + // We check first if the name is inside class declaration or class expression; if so give explicit message + // otherwise report generic error message. + var errorSpan = ts.getErrorSpanForNode(file, node); + file.bindDiagnostics.push(ts.createFileDiagnostic(file, errorSpan.start, errorSpan.length, getStrictModeBlockScopeFunctionDeclarationMessage(node))); + } + } + } + function checkStrictModeNumericLiteral(node) { + if (inStrictMode && node.numericLiteralFlags & 32 /* Octal */) { + file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Octal_literals_are_not_allowed_in_strict_mode)); + } + } + function checkStrictModePostfixUnaryExpression(node) { + // Grammar checking + // The identifier eval or arguments may not appear as the LeftHandSideExpression of an + // Assignment operator(11.13) or of a PostfixExpression(11.3) or as the UnaryExpression + // operated upon by a Prefix Increment(11.4.4) or a Prefix Decrement(11.4.5) operator. + if (inStrictMode) { + checkStrictModeEvalOrArguments(node, node.operand); + } + } + function checkStrictModePrefixUnaryExpression(node) { + // Grammar checking + if (inStrictMode) { + if (node.operator === 44 /* PlusPlusToken */ || node.operator === 45 /* MinusMinusToken */) { + checkStrictModeEvalOrArguments(node, node.operand); + } + } + } + function checkStrictModeWithStatement(node) { + // Grammar checking for withStatement + if (inStrictMode) { + errorOnFirstToken(node, ts.Diagnostics.with_statements_are_not_allowed_in_strict_mode); + } + } + function checkStrictModeLabeledStatement(node) { + // Grammar checking for labeledStatement + if (inStrictMode && options.target >= 2 /* ES2015 */) { + if (ts.isDeclarationStatement(node.statement) || ts.isVariableStatement(node.statement)) { + errorOnFirstToken(node.label, ts.Diagnostics.A_label_is_not_allowed_here); + } + } + } + function errorOnFirstToken(node, message, arg0, arg1, arg2) { + var span = ts.getSpanOfTokenAtPosition(file, node.pos); + file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, message, arg0, arg1, arg2)); + } + function errorOrSuggestionOnNode(isError, node, message) { + errorOrSuggestionOnRange(isError, node, node, message); + } + function errorOrSuggestionOnRange(isError, startNode, endNode, message) { + addErrorOrSuggestionDiagnostic(isError, { pos: ts.getTokenPosOfNode(startNode, file), end: endNode.end }, message); + } + function addErrorOrSuggestionDiagnostic(isError, range, message) { + var diag = ts.createFileDiagnostic(file, range.pos, range.end - range.pos, message); + if (isError) { + file.bindDiagnostics.push(diag); + } + else { + file.bindSuggestionDiagnostics = ts.append(file.bindSuggestionDiagnostics, __assign({}, diag, { category: ts.DiagnosticCategory.Suggestion })); + } + } + function bind(node) { + if (!node) { + return; + } + node.parent = parent; + var saveInStrictMode = inStrictMode; + // Even though in the AST the jsdoc @typedef node belongs to the current node, + // its symbol might be in the same scope with the current node's symbol. Consider: + // + // /** @typedef {string | number} MyType */ + // function foo(); + // + // Here the current node is "foo", which is a container, but the scope of "MyType" should + // not be inside "foo". Therefore we always bind @typedef before bind the parent node, + // and skip binding this tag later when binding all the other jsdoc tags. + // First we bind declaration nodes to a symbol if possible. We'll both create a symbol + // and then potentially add the symbol to an appropriate symbol table. Possible + // destination symbol tables are: + // + // 1) The 'exports' table of the current container's symbol. + // 2) The 'members' table of the current container's symbol. + // 3) The 'locals' table of the current container. + // + // However, not all symbols will end up in any of these tables. 'Anonymous' symbols + // (like TypeLiterals for example) will not be put in any table. + bindWorker(node); + // Then we recurse into the children of the node to bind them as well. For certain + // symbols we do specialized work when we recurse. For example, we'll keep track of + // the current 'container' node when it changes. This helps us know which symbol table + // a local should go into for example. Since terminal nodes are known not to have + // children, as an optimization we don't process those. + if (node.kind > 147 /* LastToken */) { + var saveParent = parent; + parent = node; + var containerFlags = getContainerFlags(node); + if (containerFlags === 0 /* None */) { + bindChildren(node); + } + else { + bindContainer(node, containerFlags); + } + parent = saveParent; + } + else if (!skipTransformFlagAggregation && (node.transformFlags & 536870912 /* HasComputedFlags */) === 0) { + subtreeTransformFlags |= computeTransformFlagsForNode(node, 0); + var saveParent = parent; + if (node.kind === 1 /* EndOfFileToken */) + parent = node; + bindJSDoc(node); + parent = saveParent; + } + inStrictMode = saveInStrictMode; + } + function bindJSDoc(node) { + if (ts.hasJSDocNodes(node)) { + if (ts.isInJSFile(node)) { + for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { + var j = _a[_i]; + bind(j); + } + } + else { + for (var _b = 0, _c = node.jsDoc; _b < _c.length; _b++) { + var j = _c[_b]; + setParentPointers(node, j); + } + } + } + } + function updateStrictModeStatementList(statements) { + if (!inStrictMode) { + for (var _i = 0, statements_1 = statements; _i < statements_1.length; _i++) { + var statement = statements_1[_i]; + if (!ts.isPrologueDirective(statement)) { + return; + } + if (isUseStrictPrologueDirective(statement)) { + inStrictMode = true; + return; + } + } + } + } + /// Should be called only on prologue directives (isPrologueDirective(node) should be true) + function isUseStrictPrologueDirective(node) { + var nodeText = ts.getSourceTextOfNodeFromSourceFile(file, node.expression); + // Note: the node text must be exactly "use strict" or 'use strict'. It is not ok for the + // string to contain unicode escapes (as per ES5). + return nodeText === '"use strict"' || nodeText === "'use strict'"; + } + function bindWorker(node) { + switch (node.kind) { + /* Strict mode checks */ + case 72 /* Identifier */: + // for typedef type names with namespaces, bind the new jsdoc type symbol here + // because it requires all containing namespaces to be in effect, namely the + // current "blockScopeContainer" needs to be set to its immediate namespace parent. + if (node.isInJSDocNamespace) { + var parentNode = node.parent; + while (parentNode && !ts.isJSDocTypeAlias(parentNode)) { + parentNode = parentNode.parent; + } + bindBlockScopedDeclaration(parentNode, 524288 /* TypeAlias */, 67897832 /* TypeAliasExcludes */); + break; + } + // falls through + case 100 /* ThisKeyword */: + if (currentFlow && (ts.isExpression(node) || parent.kind === 276 /* ShorthandPropertyAssignment */)) { + node.flowNode = currentFlow; + } + return checkStrictModeIdentifier(node); + case 189 /* PropertyAccessExpression */: + case 190 /* ElementAccessExpression */: + if (currentFlow && isNarrowableReference(node)) { + node.flowNode = currentFlow; + } + if (ts.isSpecialPropertyDeclaration(node)) { + bindSpecialPropertyDeclaration(node); + } + if (ts.isInJSFile(node) && + file.commonJsModuleIndicator && + ts.isModuleExportsPropertyAccessExpression(node) && + !lookupSymbolForNameWorker(blockScopeContainer, "module")) { + declareSymbol(file.locals, /*parent*/ undefined, node.expression, 1 /* FunctionScopedVariable */ | 134217728 /* ModuleExports */, 67220414 /* FunctionScopedVariableExcludes */); + } + break; + case 204 /* BinaryExpression */: + var specialKind = ts.getAssignmentDeclarationKind(node); + switch (specialKind) { + case 1 /* ExportsProperty */: + bindExportsPropertyAssignment(node); + break; + case 2 /* ModuleExports */: + bindModuleExportsAssignment(node); + break; + case 3 /* PrototypeProperty */: + bindPrototypePropertyAssignment(node.left, node); + break; + case 6 /* Prototype */: + bindPrototypeAssignment(node); + break; + case 4 /* ThisProperty */: + bindThisPropertyAssignment(node); + break; + case 5 /* Property */: + bindSpecialPropertyAssignment(node); + break; + case 0 /* None */: + // Nothing to do + break; + default: + ts.Debug.fail("Unknown binary expression special property assignment kind"); + } + return checkStrictModeBinaryExpression(node); + case 274 /* CatchClause */: + return checkStrictModeCatchClause(node); + case 198 /* DeleteExpression */: + return checkStrictModeDeleteExpression(node); + case 8 /* NumericLiteral */: + return checkStrictModeNumericLiteral(node); + case 203 /* PostfixUnaryExpression */: + return checkStrictModePostfixUnaryExpression(node); + case 202 /* PrefixUnaryExpression */: + return checkStrictModePrefixUnaryExpression(node); + case 231 /* WithStatement */: + return checkStrictModeWithStatement(node); + case 233 /* LabeledStatement */: + return checkStrictModeLabeledStatement(node); + case 178 /* ThisType */: + seenThisKeyword = true; + return; + case 163 /* TypePredicate */: + break; // Binding the children will handle everything + case 150 /* TypeParameter */: + return bindTypeParameter(node); + case 151 /* Parameter */: + return bindParameter(node); + case 237 /* VariableDeclaration */: + return bindVariableDeclarationOrBindingElement(node); + case 186 /* BindingElement */: + node.flowNode = currentFlow; + return bindVariableDeclarationOrBindingElement(node); + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + return bindPropertyWorker(node); + case 275 /* PropertyAssignment */: + case 276 /* ShorthandPropertyAssignment */: + return bindPropertyOrMethodOrAccessor(node, 4 /* Property */, 0 /* PropertyExcludes */); + case 278 /* EnumMember */: + return bindPropertyOrMethodOrAccessor(node, 8 /* EnumMember */, 68008959 /* EnumMemberExcludes */); + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 162 /* IndexSignature */: + return declareSymbolAndAddToSymbolTable(node, 131072 /* Signature */, 0 /* None */); + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + // If this is an ObjectLiteralExpression method, then it sits in the same space + // as other properties in the object literal. So we use SymbolFlags.PropertyExcludes + // so that it will conflict with any other object literal members with the same + // name. + return bindPropertyOrMethodOrAccessor(node, 8192 /* Method */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), ts.isObjectLiteralMethod(node) ? 0 /* PropertyExcludes */ : 67212223 /* MethodExcludes */); + case 239 /* FunctionDeclaration */: + return bindFunctionDeclaration(node); + case 157 /* Constructor */: + return declareSymbolAndAddToSymbolTable(node, 16384 /* Constructor */, /*symbolExcludes:*/ 0 /* None */); + case 158 /* GetAccessor */: + return bindPropertyOrMethodOrAccessor(node, 32768 /* GetAccessor */, 67154879 /* GetAccessorExcludes */); + case 159 /* SetAccessor */: + return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 67187647 /* SetAccessorExcludes */); + case 165 /* FunctionType */: + case 289 /* JSDocFunctionType */: + case 293 /* JSDocSignature */: + case 166 /* ConstructorType */: + return bindFunctionOrConstructorType(node); + case 168 /* TypeLiteral */: + case 292 /* JSDocTypeLiteral */: + case 181 /* MappedType */: + return bindAnonymousTypeWorker(node); + case 188 /* ObjectLiteralExpression */: + return bindObjectLiteralExpression(node); + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + return bindFunctionExpression(node); + case 191 /* CallExpression */: + var assignmentKind = ts.getAssignmentDeclarationKind(node); + switch (assignmentKind) { + case 7 /* ObjectDefinePropertyValue */: + return bindObjectDefinePropertyAssignment(node); + case 8 /* ObjectDefinePropertyExports */: + return bindObjectDefinePropertyExport(node); + case 9 /* ObjectDefinePrototypeProperty */: + return bindObjectDefinePrototypeProperty(node); + case 0 /* None */: + break; // Nothing to do + default: + return ts.Debug.fail("Unknown call expression assignment declaration kind"); + } + if (ts.isInJSFile(node)) { + bindCallExpression(node); + } + break; + // Members of classes, interfaces, and modules + case 209 /* ClassExpression */: + case 240 /* ClassDeclaration */: + // All classes are automatically in strict mode in ES6. + inStrictMode = true; + return bindClassLikeDeclaration(node); + case 241 /* InterfaceDeclaration */: + return bindBlockScopedDeclaration(node, 64 /* Interface */, 67897736 /* InterfaceExcludes */); + case 242 /* TypeAliasDeclaration */: + return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 67897832 /* TypeAliasExcludes */); + case 243 /* EnumDeclaration */: + return bindEnumDeclaration(node); + case 244 /* ModuleDeclaration */: + return bindModuleDeclaration(node); + // Jsx-attributes + case 268 /* JsxAttributes */: + return bindJsxAttributes(node); + case 267 /* JsxAttribute */: + return bindJsxAttribute(node, 4 /* Property */, 0 /* PropertyExcludes */); + // Imports and exports + case 248 /* ImportEqualsDeclaration */: + case 251 /* NamespaceImport */: + case 253 /* ImportSpecifier */: + case 257 /* ExportSpecifier */: + return declareSymbolAndAddToSymbolTable(node, 2097152 /* Alias */, 2097152 /* AliasExcludes */); + case 247 /* NamespaceExportDeclaration */: + return bindNamespaceExportDeclaration(node); + case 250 /* ImportClause */: + return bindImportClause(node); + case 255 /* ExportDeclaration */: + return bindExportDeclaration(node); + case 254 /* ExportAssignment */: + return bindExportAssignment(node); + case 279 /* SourceFile */: + updateStrictModeStatementList(node.statements); + return bindSourceFileIfExternalModule(); + case 218 /* Block */: + if (!ts.isFunctionLike(node.parent)) { + return; + } + // falls through + case 245 /* ModuleBlock */: + return updateStrictModeStatementList(node.statements); + case 299 /* JSDocParameterTag */: + if (node.parent.kind === 293 /* JSDocSignature */) { + return bindParameter(node); + } + if (node.parent.kind !== 292 /* JSDocTypeLiteral */) { + break; + } + // falls through + case 305 /* JSDocPropertyTag */: + var propTag = node; + var flags = propTag.isBracketed || propTag.typeExpression && propTag.typeExpression.type.kind === 288 /* JSDocOptionalType */ ? + 4 /* Property */ | 16777216 /* Optional */ : + 4 /* Property */; + return declareSymbolAndAddToSymbolTable(propTag, flags, 0 /* PropertyExcludes */); + case 304 /* JSDocTypedefTag */: + case 297 /* JSDocCallbackTag */: + return (delayedTypeAliases || (delayedTypeAliases = [])).push(node); + } + } + function bindPropertyWorker(node) { + return bindPropertyOrMethodOrAccessor(node, 4 /* Property */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), 0 /* PropertyExcludes */); + } + function bindAnonymousTypeWorker(node) { + return bindAnonymousDeclaration(node, 2048 /* TypeLiteral */, "__type" /* Type */); + } + function bindSourceFileIfExternalModule() { + setExportContextFlag(file); + if (ts.isExternalModule(file)) { + bindSourceFileAsExternalModule(); + } + else if (ts.isJsonSourceFile(file)) { + bindSourceFileAsExternalModule(); + // Create symbol equivalent for the module.exports = {} + var originalSymbol = file.symbol; + declareSymbol(file.symbol.exports, file.symbol, file, 4 /* Property */, 67108863 /* All */); + file.symbol = originalSymbol; + } + } + function bindSourceFileAsExternalModule() { + bindAnonymousDeclaration(file, 512 /* ValueModule */, "\"" + ts.removeFileExtension(file.fileName) + "\""); + } + function bindExportAssignment(node) { + if (!container.symbol || !container.symbol.exports) { + // Export assignment in some sort of block construct + bindAnonymousDeclaration(node, 2097152 /* Alias */, getDeclarationName(node)); + } + else { + var flags = ts.exportAssignmentIsAlias(node) + // An export default clause with an EntityNameExpression or a class expression exports all meanings of that identifier or expression; + ? 2097152 /* Alias */ + // An export default clause with any other expression exports a value + : 4 /* Property */; + // If there is an `export default x;` alias declaration, can't `export default` anything else. + // (In contrast, you can still have `export default function f() {}` and `export default interface I {}`.) + var symbol = declareSymbol(container.symbol.exports, container.symbol, node, flags, 67108863 /* All */); + if (node.isExportEquals) { + // Will be an error later, since the module already has other exports. Just make sure this has a valueDeclaration set. + setValueDeclaration(symbol, node); + } + } + } + function bindNamespaceExportDeclaration(node) { + if (node.modifiers && node.modifiers.length) { + file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Modifiers_cannot_appear_here)); + } + var diag = !ts.isSourceFile(node.parent) ? ts.Diagnostics.Global_module_exports_may_only_appear_at_top_level + : !ts.isExternalModule(node.parent) ? ts.Diagnostics.Global_module_exports_may_only_appear_in_module_files + : !node.parent.isDeclarationFile ? ts.Diagnostics.Global_module_exports_may_only_appear_in_declaration_files + : undefined; + if (diag) { + file.bindDiagnostics.push(createDiagnosticForNode(node, diag)); + } + else { + file.symbol.globalExports = file.symbol.globalExports || ts.createSymbolTable(); + declareSymbol(file.symbol.globalExports, file.symbol, node, 2097152 /* Alias */, 2097152 /* AliasExcludes */); + } + } + function bindExportDeclaration(node) { + if (!container.symbol || !container.symbol.exports) { + // Export * in some sort of block construct + bindAnonymousDeclaration(node, 8388608 /* ExportStar */, getDeclarationName(node)); + } + else if (!node.exportClause) { + // All export * declarations are collected in an __export symbol + declareSymbol(container.symbol.exports, container.symbol, node, 8388608 /* ExportStar */, 0 /* None */); + } + } + function bindImportClause(node) { + if (node.name) { + declareSymbolAndAddToSymbolTable(node, 2097152 /* Alias */, 2097152 /* AliasExcludes */); + } + } + function setCommonJsModuleIndicator(node) { + if (file.externalModuleIndicator) { + return false; + } + if (!file.commonJsModuleIndicator) { + file.commonJsModuleIndicator = node; + bindSourceFileAsExternalModule(); + } + return true; + } + function bindObjectDefinePropertyExport(node) { + if (!setCommonJsModuleIndicator(node)) { + return; + } + var symbol = forEachIdentifierInEntityName(node.arguments[0], /*parent*/ undefined, function (id, symbol) { + if (symbol) { + addDeclarationToSymbol(symbol, id, 1536 /* Module */ | 67108864 /* Assignment */); + } + return symbol; + }); + if (symbol) { + var flags = 4 /* Property */ | 1048576 /* ExportValue */; + declareSymbol(symbol.exports, symbol, node, flags, 0 /* None */); + } + } + function bindExportsPropertyAssignment(node) { + // When we create a property via 'exports.foo = bar', the 'exports.foo' property access + // expression is the declaration + if (!setCommonJsModuleIndicator(node)) { + return; + } + var lhs = node.left; + var symbol = forEachIdentifierInEntityName(lhs.expression, /*parent*/ undefined, function (id, symbol) { + if (symbol) { + addDeclarationToSymbol(symbol, id, 1536 /* Module */ | 67108864 /* Assignment */); + } + return symbol; + }); + if (symbol) { + var flags = ts.isClassExpression(node.right) ? + 4 /* Property */ | 1048576 /* ExportValue */ | 32 /* Class */ : + 4 /* Property */ | 1048576 /* ExportValue */; + declareSymbol(symbol.exports, symbol, lhs, flags, 0 /* None */); + } + } + function bindModuleExportsAssignment(node) { + // A common practice in node modules is to set 'export = module.exports = {}', this ensures that 'exports' + // is still pointing to 'module.exports'. + // We do not want to consider this as 'export=' since a module can have only one of these. + // Similarly we do not want to treat 'module.exports = exports' as an 'export='. + if (!setCommonJsModuleIndicator(node)) { + return; + } + var assignedExpression = ts.getRightMostAssignedExpression(node.right); + if (ts.isEmptyObjectLiteral(assignedExpression) || container === file && isExportsOrModuleExportsOrAlias(file, assignedExpression)) { + return; + } + // 'module.exports = expr' assignment + var flags = ts.exportAssignmentIsAlias(node) + ? 2097152 /* Alias */ + : 4 /* Property */ | 1048576 /* ExportValue */ | 512 /* ValueModule */; + declareSymbol(file.symbol.exports, file.symbol, node, flags | 67108864 /* Assignment */, 0 /* None */); + } + function bindThisPropertyAssignment(node) { + ts.Debug.assert(ts.isInJSFile(node)); + var thisContainer = ts.getThisContainer(node, /*includeArrowFunctions*/ false); + switch (thisContainer.kind) { + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + var constructorSymbol = thisContainer.symbol; + // For `f.prototype.m = function() { this.x = 0; }`, `this.x = 0` should modify `f`'s members, not the function expression. + if (ts.isBinaryExpression(thisContainer.parent) && thisContainer.parent.operatorToken.kind === 59 /* EqualsToken */) { + var l = thisContainer.parent.left; + if (ts.isPropertyAccessEntityNameExpression(l) && ts.isPrototypeAccess(l.expression)) { + constructorSymbol = lookupSymbolForPropertyAccess(l.expression.expression, thisParentContainer); + } + } + if (constructorSymbol) { + // Declare a 'member' if the container is an ES5 class or ES6 constructor + constructorSymbol.members = constructorSymbol.members || ts.createSymbolTable(); + // It's acceptable for multiple 'this' assignments of the same identifier to occur + declareSymbol(constructorSymbol.members, constructorSymbol, node, 4 /* Property */, 0 /* PropertyExcludes */ & ~4 /* Property */); + } + break; + case 157 /* Constructor */: + case 154 /* PropertyDeclaration */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + // this.foo assignment in a JavaScript class + // Bind this property to the containing class + var containingClass = thisContainer.parent; + var symbolTable = ts.hasModifier(thisContainer, 32 /* Static */) ? containingClass.symbol.exports : containingClass.symbol.members; + declareSymbol(symbolTable, containingClass.symbol, node, 4 /* Property */, 0 /* None */, /*isReplaceableByMethod*/ true); + break; + case 279 /* SourceFile */: + // this.foo assignment in a source file + // Do not bind. It would be nice to support this someday though. + break; + default: + ts.Debug.fail(ts.Debug.showSyntaxKind(thisContainer)); + } + } + function bindSpecialPropertyDeclaration(node) { + if (node.expression.kind === 100 /* ThisKeyword */) { + bindThisPropertyAssignment(node); + } + else if (ts.isPropertyAccessEntityNameExpression(node) && node.parent.parent.kind === 279 /* SourceFile */) { + if (ts.isPrototypeAccess(node.expression)) { + bindPrototypePropertyAssignment(node, node.parent); + } + else { + bindStaticPropertyAssignment(node); + } + } + } + /** For `x.prototype = { p, ... }`, declare members p,... if `x` is function/class/{}, or not declared. */ + function bindPrototypeAssignment(node) { + node.left.parent = node; + node.right.parent = node; + var lhs = node.left; + bindPropertyAssignment(lhs.expression, lhs, /*isPrototypeProperty*/ false); + } + function bindObjectDefinePrototypeProperty(node) { + var namespaceSymbol = lookupSymbolForPropertyAccess(node.arguments[0].expression); + bindPotentiallyNewExpandoMemberToNamespace(node, namespaceSymbol, /*isPrototypeProperty*/ true); + } + /** + * For `x.prototype.y = z`, declare a member `y` on `x` if `x` is a function or class, or not declared. + * Note that jsdoc preceding an ExpressionStatement like `x.prototype.y;` is also treated as a declaration. + */ + function bindPrototypePropertyAssignment(lhs, parent) { + // Look up the function in the local scope, since prototype assignments should + // follow the function declaration + var classPrototype = lhs.expression; + var constructorFunction = classPrototype.expression; + // Fix up parent pointers since we're going to use these nodes before we bind into them + lhs.parent = parent; + constructorFunction.parent = classPrototype; + classPrototype.parent = lhs; + bindPropertyAssignment(constructorFunction, lhs, /*isPrototypeProperty*/ true); + } + function bindObjectDefinePropertyAssignment(node) { + var namespaceSymbol = lookupSymbolForPropertyAccess(node.arguments[0]); + var isToplevel = node.parent.parent.kind === 279 /* SourceFile */; + namespaceSymbol = bindPotentiallyMissingNamespaces(namespaceSymbol, node.arguments[0], isToplevel, /*isPrototypeProperty*/ false); + bindPotentiallyNewExpandoMemberToNamespace(node, namespaceSymbol, /*isPrototypeProperty*/ false); + } + function bindSpecialPropertyAssignment(node) { + var lhs = node.left; + // Class declarations in Typescript do not allow property declarations + var parentSymbol = lookupSymbolForPropertyAccess(lhs.expression); + if (!ts.isInJSFile(node) && !ts.isFunctionSymbol(parentSymbol)) { + return; + } + // Fix up parent pointers since we're going to use these nodes before we bind into them + node.left.parent = node; + node.right.parent = node; + if (ts.isIdentifier(lhs.expression) && container === file && isNameOfExportsOrModuleExportsAliasDeclaration(file, lhs.expression)) { + // This can be an alias for the 'exports' or 'module.exports' names, e.g. + // var util = module.exports; + // util.property = function ... + bindExportsPropertyAssignment(node); + } + else { + bindStaticPropertyAssignment(lhs); + } + } + /** + * For nodes like `x.y = z`, declare a member 'y' on 'x' if x is a function (or IIFE) or class or {}, or not declared. + * Also works for expression statements preceded by JSDoc, like / ** @type number * / x.y; + */ + function bindStaticPropertyAssignment(node) { + node.expression.parent = node; + bindPropertyAssignment(node.expression, node, /*isPrototypeProperty*/ false); + } + function bindPotentiallyMissingNamespaces(namespaceSymbol, entityName, isToplevel, isPrototypeProperty) { + if (isToplevel && !isPrototypeProperty && (!namespaceSymbol || !(namespaceSymbol.flags & 1920 /* Namespace */))) { + // make symbols or add declarations for intermediate containers + var flags_1 = 1536 /* Module */ | 67108864 /* Assignment */; + var excludeFlags_1 = 110735 /* ValueModuleExcludes */ & ~67108864 /* Assignment */; + namespaceSymbol = forEachIdentifierInEntityName(entityName, namespaceSymbol, function (id, symbol, parent) { + if (symbol) { + addDeclarationToSymbol(symbol, id, flags_1); + return symbol; + } + else { + var table = parent ? parent.exports : + file.jsGlobalAugmentations || (file.jsGlobalAugmentations = ts.createSymbolTable()); + return declareSymbol(table, parent, id, flags_1, excludeFlags_1); + } + }); + } + return namespaceSymbol; + } + function bindPotentiallyNewExpandoMemberToNamespace(declaration, namespaceSymbol, isPrototypeProperty) { + if (!namespaceSymbol || !isExpandoSymbol(namespaceSymbol)) { + return; + } + // Set up the members collection if it doesn't exist already + var symbolTable = isPrototypeProperty ? + (namespaceSymbol.members || (namespaceSymbol.members = ts.createSymbolTable())) : + (namespaceSymbol.exports || (namespaceSymbol.exports = ts.createSymbolTable())); + var isMethod = ts.isFunctionLikeDeclaration(ts.getAssignedExpandoInitializer(declaration)); + var includes = isMethod ? 8192 /* Method */ : 4 /* Property */; + var excludes = isMethod ? 67212223 /* MethodExcludes */ : 0 /* PropertyExcludes */; + declareSymbol(symbolTable, namespaceSymbol, declaration, includes | 67108864 /* Assignment */, excludes & ~67108864 /* Assignment */); + } + function bindPropertyAssignment(name, propertyAccess, isPrototypeProperty) { + var namespaceSymbol = lookupSymbolForPropertyAccess(name); + var isToplevel = ts.isBinaryExpression(propertyAccess.parent) + ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 279 /* SourceFile */ + : propertyAccess.parent.parent.kind === 279 /* SourceFile */; + namespaceSymbol = bindPotentiallyMissingNamespaces(namespaceSymbol, propertyAccess.expression, isToplevel, isPrototypeProperty); + bindPotentiallyNewExpandoMemberToNamespace(propertyAccess, namespaceSymbol, isPrototypeProperty); + } + /** + * Javascript expando values are: + * - Functions + * - classes + * - namespaces + * - variables initialized with function expressions + * - with class expressions + * - with empty object literals + * - with non-empty object literals if assigned to the prototype property + */ + function isExpandoSymbol(symbol) { + if (symbol.flags & (16 /* Function */ | 32 /* Class */ | 1024 /* NamespaceModule */)) { + return true; + } + var node = symbol.valueDeclaration; + if (node && ts.isCallExpression(node)) { + return !!ts.getAssignedExpandoInitializer(node); + } + var init = !node ? undefined : + ts.isVariableDeclaration(node) ? node.initializer : + ts.isBinaryExpression(node) ? node.right : + ts.isPropertyAccessExpression(node) && ts.isBinaryExpression(node.parent) ? node.parent.right : + undefined; + init = init && ts.getRightMostAssignedExpression(init); + if (init) { + var isPrototypeAssignment = ts.isPrototypeAccess(ts.isVariableDeclaration(node) ? node.name : ts.isBinaryExpression(node) ? node.left : node); + return !!ts.getExpandoInitializer(ts.isBinaryExpression(init) && init.operatorToken.kind === 55 /* BarBarToken */ ? init.right : init, isPrototypeAssignment); + } + return false; + } + function getParentOfBinaryExpression(expr) { + while (ts.isBinaryExpression(expr.parent)) { + expr = expr.parent; + } + return expr.parent; + } + function lookupSymbolForPropertyAccess(node, lookupContainer) { + if (lookupContainer === void 0) { lookupContainer = container; } + if (ts.isIdentifier(node)) { + return lookupSymbolForNameWorker(lookupContainer, node.escapedText); + } + else { + var symbol = lookupSymbolForPropertyAccess(node.expression); + return symbol && symbol.exports && symbol.exports.get(node.name.escapedText); + } + } + function forEachIdentifierInEntityName(e, parent, action) { + if (isExportsOrModuleExportsOrAlias(file, e)) { + return file.symbol; + } + else if (ts.isIdentifier(e)) { + return action(e, lookupSymbolForPropertyAccess(e), parent); + } + else { + var s = forEachIdentifierInEntityName(e.expression, parent, action); + if (!s || !s.exports) + return ts.Debug.fail(); + return action(e.name, s.exports.get(e.name.escapedText), s); + } + } + function bindCallExpression(node) { + // We're only inspecting call expressions to detect CommonJS modules, so we can skip + // this check if we've already seen the module indicator + if (!file.commonJsModuleIndicator && ts.isRequireCall(node, /*checkArgumentIsStringLiteralLike*/ false)) { + setCommonJsModuleIndicator(node); + } + } + function bindClassLikeDeclaration(node) { + if (node.kind === 240 /* ClassDeclaration */) { + bindBlockScopedDeclaration(node, 32 /* Class */, 68008383 /* ClassExcludes */); + } + else { + var bindingName = node.name ? node.name.escapedText : "__class" /* Class */; + bindAnonymousDeclaration(node, 32 /* Class */, bindingName); + // Add name of class expression into the map for semantic classifier + if (node.name) { + classifiableNames.set(node.name.escapedText, true); + } + } + var symbol = node.symbol; + // TypeScript 1.0 spec (April 2014): 8.4 + // Every class automatically contains a static property member named 'prototype', the + // type of which is an instantiation of the class type with type Any supplied as a type + // argument for each type parameter. It is an error to explicitly declare a static + // property member with the name 'prototype'. + // + // Note: we check for this here because this class may be merging into a module. The + // module might have an exported variable called 'prototype'. We can't allow that as + // that would clash with the built-in 'prototype' for the class. + var prototypeSymbol = createSymbol(4 /* Property */ | 4194304 /* Prototype */, "prototype"); + var symbolExport = symbol.exports.get(prototypeSymbol.escapedName); + if (symbolExport) { + if (node.name) { + node.name.parent = node; + } + file.bindDiagnostics.push(createDiagnosticForNode(symbolExport.declarations[0], ts.Diagnostics.Duplicate_identifier_0, ts.symbolName(prototypeSymbol))); + } + symbol.exports.set(prototypeSymbol.escapedName, prototypeSymbol); + prototypeSymbol.parent = symbol; + } + function bindEnumDeclaration(node) { + return ts.isEnumConst(node) + ? bindBlockScopedDeclaration(node, 128 /* ConstEnum */, 68008831 /* ConstEnumExcludes */) + : bindBlockScopedDeclaration(node, 256 /* RegularEnum */, 68008191 /* RegularEnumExcludes */); + } + function bindVariableDeclarationOrBindingElement(node) { + if (inStrictMode) { + checkStrictModeEvalOrArguments(node, node.name); + } + if (!ts.isBindingPattern(node.name)) { + var isEnum = ts.isInJSFile(node) && !!ts.getJSDocEnumTag(node); + var enumFlags = (isEnum ? 256 /* RegularEnum */ : 0 /* None */); + var enumExcludes = (isEnum ? 68008191 /* RegularEnumExcludes */ : 0 /* None */); + if (ts.isBlockOrCatchScoped(node)) { + bindBlockScopedDeclaration(node, 2 /* BlockScopedVariable */ | enumFlags, 67220415 /* BlockScopedVariableExcludes */ | enumExcludes); + } + else if (ts.isParameterDeclaration(node)) { + // It is safe to walk up parent chain to find whether the node is a destructuring parameter declaration + // because its parent chain has already been set up, since parents are set before descending into children. + // + // If node is a binding element in parameter declaration, we need to use ParameterExcludes. + // Using ParameterExcludes flag allows the compiler to report an error on duplicate identifiers in Parameter Declaration + // For example: + // function foo([a,a]) {} // Duplicate Identifier error + // function bar(a,a) {} // Duplicate Identifier error, parameter declaration in this case is handled in bindParameter + // // which correctly set excluded symbols + declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67220415 /* ParameterExcludes */); + } + else { + declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */ | enumFlags, 67220414 /* FunctionScopedVariableExcludes */ | enumExcludes); + } + } + } + function bindParameter(node) { + if (node.kind === 299 /* JSDocParameterTag */ && container.kind !== 293 /* JSDocSignature */) { + return; + } + if (inStrictMode && !(node.flags & 4194304 /* Ambient */)) { + // It is a SyntaxError if the identifier eval or arguments appears within a FormalParameterList of a + // strict mode FunctionLikeDeclaration or FunctionExpression(13.1) + checkStrictModeEvalOrArguments(node, node.name); + } + if (ts.isBindingPattern(node.name)) { + bindAnonymousDeclaration(node, 1 /* FunctionScopedVariable */, "__" + node.parent.parameters.indexOf(node)); + } + else { + declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67220415 /* ParameterExcludes */); + } + // If this is a property-parameter, then also declare the property symbol into the + // containing class. + if (ts.isParameterPropertyDeclaration(node)) { + var classDeclaration = node.parent.parent; + declareSymbol(classDeclaration.symbol.members, classDeclaration.symbol, node, 4 /* Property */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), 0 /* PropertyExcludes */); + } + } + function bindFunctionDeclaration(node) { + if (!file.isDeclarationFile && !(node.flags & 4194304 /* Ambient */)) { + if (ts.isAsyncFunction(node)) { + emitFlags |= 1024 /* HasAsyncFunctions */; + } + } + checkStrictModeFunctionName(node); + if (inStrictMode) { + checkStrictModeFunctionDeclaration(node); + bindBlockScopedDeclaration(node, 16 /* Function */, 67219887 /* FunctionExcludes */); + } + else { + declareSymbolAndAddToSymbolTable(node, 16 /* Function */, 67219887 /* FunctionExcludes */); + } + } + function bindFunctionExpression(node) { + if (!file.isDeclarationFile && !(node.flags & 4194304 /* Ambient */)) { + if (ts.isAsyncFunction(node)) { + emitFlags |= 1024 /* HasAsyncFunctions */; + } + } + if (currentFlow) { + node.flowNode = currentFlow; + } + checkStrictModeFunctionName(node); + var bindingName = node.name ? node.name.escapedText : "__function" /* Function */; + return bindAnonymousDeclaration(node, 16 /* Function */, bindingName); + } + function bindPropertyOrMethodOrAccessor(node, symbolFlags, symbolExcludes) { + if (!file.isDeclarationFile && !(node.flags & 4194304 /* Ambient */) && ts.isAsyncFunction(node)) { + emitFlags |= 1024 /* HasAsyncFunctions */; + } + if (currentFlow && ts.isObjectLiteralOrClassExpressionMethod(node)) { + node.flowNode = currentFlow; + } + return ts.hasDynamicName(node) + ? bindAnonymousDeclaration(node, symbolFlags, "__computed" /* Computed */) + : declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes); + } + function getInferTypeContainer(node) { + var extendsType = ts.findAncestor(node, function (n) { return n.parent && ts.isConditionalTypeNode(n.parent) && n.parent.extendsType === n; }); + return extendsType && extendsType.parent; + } + function bindTypeParameter(node) { + if (ts.isJSDocTemplateTag(node.parent)) { + var container_1 = ts.find(node.parent.parent.tags, ts.isJSDocTypeAlias) || ts.getHostSignatureFromJSDoc(node.parent); // TODO: GH#18217 + if (container_1) { + if (!container_1.locals) { + container_1.locals = ts.createSymbolTable(); + } + declareSymbol(container_1.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 67635688 /* TypeParameterExcludes */); + } + else { + declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 67635688 /* TypeParameterExcludes */); + } + } + else if (node.parent.kind === 176 /* InferType */) { + var container_2 = getInferTypeContainer(node.parent); + if (container_2) { + if (!container_2.locals) { + container_2.locals = ts.createSymbolTable(); + } + declareSymbol(container_2.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 67635688 /* TypeParameterExcludes */); + } + else { + bindAnonymousDeclaration(node, 262144 /* TypeParameter */, getDeclarationName(node)); // TODO: GH#18217 + } + } + else { + declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 67635688 /* TypeParameterExcludes */); + } + } + // reachability checks + function shouldReportErrorOnModuleDeclaration(node) { + var instanceState = getModuleInstanceState(node); + return instanceState === 1 /* Instantiated */ || (instanceState === 2 /* ConstEnumOnly */ && !!options.preserveConstEnums); + } + function checkUnreachable(node) { + if (!(currentFlow.flags & 1 /* Unreachable */)) { + return false; + } + if (currentFlow === unreachableFlow) { + var reportError = + // report error on all statements except empty ones + (ts.isStatementButNotDeclaration(node) && node.kind !== 220 /* EmptyStatement */) || + // report error on class declarations + node.kind === 240 /* ClassDeclaration */ || + // report error on instantiated modules or const-enums only modules if preserveConstEnums is set + (node.kind === 244 /* ModuleDeclaration */ && shouldReportErrorOnModuleDeclaration(node)); + if (reportError) { + currentFlow = reportedUnreachableFlow; + if (!options.allowUnreachableCode) { + // unreachable code is reported if + // - user has explicitly asked about it AND + // - statement is in not ambient context (statements in ambient context is already an error + // so we should not report extras) AND + // - node is not variable statement OR + // - node is block scoped variable statement OR + // - node is not block scoped variable statement and at least one variable declaration has initializer + // Rationale: we don't want to report errors on non-initialized var's since they are hoisted + // On the other side we do want to report errors on non-initialized 'lets' because of TDZ + var isError_1 = ts.unreachableCodeIsError(options) && + !(node.flags & 4194304 /* Ambient */) && + (!ts.isVariableStatement(node) || + !!(ts.getCombinedNodeFlags(node.declarationList) & 3 /* BlockScoped */) || + node.declarationList.declarations.some(function (d) { return !!d.initializer; })); + eachUnreachableRange(node, function (start, end) { return errorOrSuggestionOnRange(isError_1, start, end, ts.Diagnostics.Unreachable_code_detected); }); + } + } + } + return true; + } + } + function eachUnreachableRange(node, cb) { + if (ts.isStatement(node) && isExecutableStatement(node) && ts.isBlock(node.parent)) { + var statements = node.parent.statements; + var slice_1 = ts.sliceAfter(statements, node); + ts.getRangesWhere(slice_1, isExecutableStatement, function (start, afterEnd) { return cb(slice_1[start], slice_1[afterEnd - 1]); }); + } + else { + cb(node, node); + } + } + // As opposed to a pure declaration like an `interface` + function isExecutableStatement(s) { + // Don't remove statements that can validly be used before they appear. + return !ts.isFunctionDeclaration(s) && !isPurelyTypeDeclaration(s) && !ts.isEnumDeclaration(s) && + // `var x;` may declare a variable used above + !(ts.isVariableStatement(s) && !(ts.getCombinedNodeFlags(s) & (1 /* Let */ | 2 /* Const */)) && s.declarationList.declarations.some(function (d) { return !d.initializer; })); + } + function isPurelyTypeDeclaration(s) { + switch (s.kind) { + case 241 /* InterfaceDeclaration */: + case 242 /* TypeAliasDeclaration */: + return true; + case 244 /* ModuleDeclaration */: + return getModuleInstanceState(s) !== 1 /* Instantiated */; + case 243 /* EnumDeclaration */: + return ts.hasModifier(s, 2048 /* Const */); + default: + return false; + } + } + function isExportsOrModuleExportsOrAlias(sourceFile, node) { + return ts.isExportsIdentifier(node) || + ts.isModuleExportsPropertyAccessExpression(node) || + ts.isIdentifier(node) && isNameOfExportsOrModuleExportsAliasDeclaration(sourceFile, node); + } + ts.isExportsOrModuleExportsOrAlias = isExportsOrModuleExportsOrAlias; + function isNameOfExportsOrModuleExportsAliasDeclaration(sourceFile, node) { + var symbol = lookupSymbolForNameWorker(sourceFile, node.escapedText); + return !!symbol && !!symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && + !!symbol.valueDeclaration.initializer && isExportsOrModuleExportsOrAliasOrAssignment(sourceFile, symbol.valueDeclaration.initializer); + } + function isExportsOrModuleExportsOrAliasOrAssignment(sourceFile, node) { + return isExportsOrModuleExportsOrAlias(sourceFile, node) || + (ts.isAssignmentExpression(node, /*excludeCompoundAssignment*/ true) && (isExportsOrModuleExportsOrAliasOrAssignment(sourceFile, node.left) || isExportsOrModuleExportsOrAliasOrAssignment(sourceFile, node.right))); + } + function lookupSymbolForNameWorker(container, name) { + var local = container.locals && container.locals.get(name); + if (local) { + return local.exportSymbol || local; + } + if (ts.isSourceFile(container) && container.jsGlobalAugmentations && container.jsGlobalAugmentations.has(name)) { + return container.jsGlobalAugmentations.get(name); + } + return container.symbol && container.symbol.exports && container.symbol.exports.get(name); + } + /** + * Computes the transform flags for a node, given the transform flags of its subtree + * + * @param node The node to analyze + * @param subtreeFlags Transform flags computed for this node's subtree + */ + function computeTransformFlagsForNode(node, subtreeFlags) { + var kind = node.kind; + switch (kind) { + case 191 /* CallExpression */: + return computeCallExpression(node, subtreeFlags); + case 192 /* NewExpression */: + return computeNewExpression(node, subtreeFlags); + case 244 /* ModuleDeclaration */: + return computeModuleDeclaration(node, subtreeFlags); + case 195 /* ParenthesizedExpression */: + return computeParenthesizedExpression(node, subtreeFlags); + case 204 /* BinaryExpression */: + return computeBinaryExpression(node, subtreeFlags); + case 221 /* ExpressionStatement */: + return computeExpressionStatement(node, subtreeFlags); + case 151 /* Parameter */: + return computeParameter(node, subtreeFlags); + case 197 /* ArrowFunction */: + return computeArrowFunction(node, subtreeFlags); + case 196 /* FunctionExpression */: + return computeFunctionExpression(node, subtreeFlags); + case 239 /* FunctionDeclaration */: + return computeFunctionDeclaration(node, subtreeFlags); + case 237 /* VariableDeclaration */: + return computeVariableDeclaration(node, subtreeFlags); + case 238 /* VariableDeclarationList */: + return computeVariableDeclarationList(node, subtreeFlags); + case 219 /* VariableStatement */: + return computeVariableStatement(node, subtreeFlags); + case 233 /* LabeledStatement */: + return computeLabeledStatement(node, subtreeFlags); + case 240 /* ClassDeclaration */: + return computeClassDeclaration(node, subtreeFlags); + case 209 /* ClassExpression */: + return computeClassExpression(node, subtreeFlags); + case 273 /* HeritageClause */: + return computeHeritageClause(node, subtreeFlags); + case 274 /* CatchClause */: + return computeCatchClause(node, subtreeFlags); + case 211 /* ExpressionWithTypeArguments */: + return computeExpressionWithTypeArguments(node, subtreeFlags); + case 157 /* Constructor */: + return computeConstructor(node, subtreeFlags); + case 154 /* PropertyDeclaration */: + return computePropertyDeclaration(node, subtreeFlags); + case 156 /* MethodDeclaration */: + return computeMethod(node, subtreeFlags); + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + return computeAccessor(node, subtreeFlags); + case 248 /* ImportEqualsDeclaration */: + return computeImportEquals(node, subtreeFlags); + case 189 /* PropertyAccessExpression */: + return computePropertyAccess(node, subtreeFlags); + case 190 /* ElementAccessExpression */: + return computeElementAccess(node, subtreeFlags); + default: + return computeOther(node, kind, subtreeFlags); + } + } + ts.computeTransformFlagsForNode = computeTransformFlagsForNode; + function computeCallExpression(node, subtreeFlags) { + var transformFlags = subtreeFlags; + var expression = node.expression; + if (node.typeArguments) { + transformFlags |= 3 /* AssertTypeScript */; + } + if (subtreeFlags & 131072 /* ContainsRestOrSpread */ + || (expression.transformFlags & (33554432 /* Super */ | 67108864 /* ContainsSuper */))) { + // If the this node contains a SpreadExpression, or is a super call, then it is an ES6 + // node. + transformFlags |= 192 /* AssertES2015 */; + // super property or element accesses could be inside lambdas, etc, and need a captured `this`, + // while super keyword for super calls (indicated by TransformFlags.Super) does not (since it can only be top-level in a constructor) + if (expression.transformFlags & 67108864 /* ContainsSuper */) { + transformFlags |= 8192 /* ContainsLexicalThis */; + } + } + if (expression.kind === 92 /* ImportKeyword */) { + transformFlags |= 16777216 /* ContainsDynamicImport */; + // A dynamic 'import()' call that contains a lexical 'this' will + // require a captured 'this' when emitting down-level. + if (subtreeFlags & 8192 /* ContainsLexicalThis */) { + transformFlags |= 16384 /* ContainsCapturedLexicalThis */; + } + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~637666625 /* ArrayLiteralOrCallOrNewExcludes */; + } + function computeNewExpression(node, subtreeFlags) { + var transformFlags = subtreeFlags; + if (node.typeArguments) { + transformFlags |= 3 /* AssertTypeScript */; + } + if (subtreeFlags & 131072 /* ContainsRestOrSpread */) { + // If the this node contains a SpreadElementExpression then it is an ES6 + // node. + transformFlags |= 192 /* AssertES2015 */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~637666625 /* ArrayLiteralOrCallOrNewExcludes */; + } + function computeBinaryExpression(node, subtreeFlags) { + var transformFlags = subtreeFlags; + var operatorTokenKind = node.operatorToken.kind; + var leftKind = node.left.kind; + if (operatorTokenKind === 59 /* EqualsToken */ && leftKind === 188 /* ObjectLiteralExpression */) { + // Destructuring object assignments with are ES2015 syntax + // and possibly ESNext if they contain rest + transformFlags |= 8 /* AssertESNext */ | 192 /* AssertES2015 */ | 3072 /* AssertDestructuringAssignment */; + } + else if (operatorTokenKind === 59 /* EqualsToken */ && leftKind === 187 /* ArrayLiteralExpression */) { + // Destructuring assignments are ES2015 syntax. + transformFlags |= 192 /* AssertES2015 */ | 3072 /* AssertDestructuringAssignment */; + } + else if (operatorTokenKind === 41 /* AsteriskAsteriskToken */ + || operatorTokenKind === 63 /* AsteriskAsteriskEqualsToken */) { + // Exponentiation is ES2016 syntax. + transformFlags |= 32 /* AssertES2016 */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~637535553 /* NodeExcludes */; + } + function computeParameter(node, subtreeFlags) { + var transformFlags = subtreeFlags; + var name = node.name; + var initializer = node.initializer; + var dotDotDotToken = node.dotDotDotToken; + // The '?' token, type annotations, decorators, and 'this' parameters are TypeSCript + // syntax. + if (node.questionToken + || node.type + || (subtreeFlags & 4096 /* ContainsTypeScriptClassSyntax */ && ts.some(node.decorators)) + || ts.isThisIdentifier(name)) { + transformFlags |= 3 /* AssertTypeScript */; + } + // If a parameter has an accessibility modifier, then it is TypeScript syntax. + if (ts.hasModifier(node, 92 /* ParameterPropertyModifier */)) { + transformFlags |= 3 /* AssertTypeScript */ | 4096 /* ContainsTypeScriptClassSyntax */; + } + // parameters with object rest destructuring are ES Next syntax + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { + transformFlags |= 8 /* AssertESNext */; + } + // If a parameter has an initializer, a binding pattern or a dotDotDot token, then + // it is ES6 syntax and its container must emit default value assignments or parameter destructuring downlevel. + if (subtreeFlags & 2097152 /* ContainsBindingPattern */ || initializer || dotDotDotToken) { + transformFlags |= 192 /* AssertES2015 */ | 65536 /* ContainsDefaultValueAssignments */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~637535553 /* ParameterExcludes */; + } + function computeParenthesizedExpression(node, subtreeFlags) { + var transformFlags = subtreeFlags; + var expression = node.expression; + var expressionKind = expression.kind; + var expressionTransformFlags = expression.transformFlags; + // If the node is synthesized, it means the emitter put the parentheses there, + // not the user. If we didn't want them, the emitter would not have put them + // there. + if (expressionKind === 212 /* AsExpression */ + || expressionKind === 194 /* TypeAssertionExpression */) { + transformFlags |= 3 /* AssertTypeScript */; + } + // If the expression of a ParenthesizedExpression is a destructuring assignment, + // then the ParenthesizedExpression is a destructuring assignment. + if (expressionTransformFlags & 1024 /* DestructuringAssignment */) { + transformFlags |= 1024 /* DestructuringAssignment */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~536872257 /* OuterExpressionExcludes */; + } + function computeClassDeclaration(node, subtreeFlags) { + var transformFlags; + if (ts.hasModifier(node, 2 /* Ambient */)) { + // An ambient declaration is TypeScript syntax. + transformFlags = 3 /* AssertTypeScript */; + } + else { + // A ClassDeclaration is ES6 syntax. + transformFlags = subtreeFlags | 192 /* AssertES2015 */; + // A class with a parameter property assignment, property initializer, computed property name, or decorator is + // TypeScript syntax. + // An exported declaration may be TypeScript syntax, but is handled by the visitor + // for a namespace declaration. + if ((subtreeFlags & 4096 /* ContainsTypeScriptClassSyntax */) + || node.typeParameters) { + transformFlags |= 3 /* AssertTypeScript */; + } + if (subtreeFlags & 32768 /* ContainsLexicalThisInComputedPropertyName */) { + // A computed property name containing `this` might need to be rewritten, + // so propagate the ContainsLexicalThis flag upward. + transformFlags |= 8192 /* ContainsLexicalThis */; + } + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~638121281 /* ClassExcludes */; + } + function computeClassExpression(node, subtreeFlags) { + // A ClassExpression is ES6 syntax. + var transformFlags = subtreeFlags | 192 /* AssertES2015 */; + // A class with a parameter property assignment, property initializer, or decorator is + // TypeScript syntax. + if (subtreeFlags & 4096 /* ContainsTypeScriptClassSyntax */ + || node.typeParameters) { + transformFlags |= 3 /* AssertTypeScript */; + } + if (subtreeFlags & 32768 /* ContainsLexicalThisInComputedPropertyName */) { + // A computed property name containing `this` might need to be rewritten, + // so propagate the ContainsLexicalThis flag upward. + transformFlags |= 8192 /* ContainsLexicalThis */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~638121281 /* ClassExcludes */; + } + function computeHeritageClause(node, subtreeFlags) { + var transformFlags = subtreeFlags; + switch (node.token) { + case 86 /* ExtendsKeyword */: + // An `extends` HeritageClause is ES6 syntax. + transformFlags |= 192 /* AssertES2015 */; + break; + case 109 /* ImplementsKeyword */: + // An `implements` HeritageClause is TypeScript syntax. + transformFlags |= 3 /* AssertTypeScript */; + break; + default: + ts.Debug.fail("Unexpected token for heritage clause"); + break; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~637535553 /* NodeExcludes */; + } + function computeCatchClause(node, subtreeFlags) { + var transformFlags = subtreeFlags; + if (!node.variableDeclaration) { + transformFlags |= 8 /* AssertESNext */; + } + else if (ts.isBindingPattern(node.variableDeclaration.name)) { + transformFlags |= 192 /* AssertES2015 */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~637797697 /* CatchClauseExcludes */; + } + function computeExpressionWithTypeArguments(node, subtreeFlags) { + // An ExpressionWithTypeArguments is ES6 syntax, as it is used in the + // extends clause of a class. + var transformFlags = subtreeFlags | 192 /* AssertES2015 */; + // If an ExpressionWithTypeArguments contains type arguments, then it + // is TypeScript syntax. + if (node.typeArguments) { + transformFlags |= 3 /* AssertTypeScript */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~637535553 /* NodeExcludes */; + } + function computeConstructor(node, subtreeFlags) { + var transformFlags = subtreeFlags; + // TypeScript-specific modifiers and overloads are TypeScript syntax + if (ts.hasModifier(node, 2270 /* TypeScriptModifier */) + || !node.body) { + transformFlags |= 3 /* AssertTypeScript */; + } + // function declarations with object rest destructuring are ES Next syntax + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { + transformFlags |= 8 /* AssertESNext */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~653616449 /* ConstructorExcludes */; + } + function computeMethod(node, subtreeFlags) { + // A MethodDeclaration is ES6 syntax. + var transformFlags = subtreeFlags | 192 /* AssertES2015 */; + // Decorators, TypeScript-specific modifiers, type parameters, type annotations, and + // overloads are TypeScript syntax. + if (node.decorators + || ts.hasModifier(node, 2270 /* TypeScriptModifier */) + || node.typeParameters + || node.type + || (node.name && ts.isComputedPropertyName(node.name)) // While computed method names aren't typescript, the TS transform must visit them to emit property declarations correctly + || !node.body) { + transformFlags |= 3 /* AssertTypeScript */; + } + // function declarations with object rest destructuring are ES Next syntax + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { + transformFlags |= 8 /* AssertESNext */; + } + // An async method declaration is ES2017 syntax. + if (ts.hasModifier(node, 256 /* Async */)) { + transformFlags |= node.asteriskToken ? 8 /* AssertESNext */ : 16 /* AssertES2017 */; + } + if (node.asteriskToken) { + transformFlags |= 768 /* AssertGenerator */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~653616449 /* MethodOrAccessorExcludes */; + } + function computeAccessor(node, subtreeFlags) { + var transformFlags = subtreeFlags; + // Decorators, TypeScript-specific modifiers, type annotations, and overloads are + // TypeScript syntax. + if (node.decorators + || ts.hasModifier(node, 2270 /* TypeScriptModifier */) + || node.type + || (node.name && ts.isComputedPropertyName(node.name)) // While computed accessor names aren't typescript, the TS transform must visit them to emit property declarations correctly + || !node.body) { + transformFlags |= 3 /* AssertTypeScript */; + } + // function declarations with object rest destructuring are ES Next syntax + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { + transformFlags |= 8 /* AssertESNext */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~653616449 /* MethodOrAccessorExcludes */; + } + function computePropertyDeclaration(node, subtreeFlags) { + // A PropertyDeclaration is TypeScript syntax. + var transformFlags = subtreeFlags | 3 /* AssertTypeScript */; + // If the PropertyDeclaration has an initializer or a computed name, we need to inform its ancestor + // so that it handle the transformation. + if (node.initializer || ts.isComputedPropertyName(node.name)) { + transformFlags |= 4096 /* ContainsTypeScriptClassSyntax */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~637535553 /* NodeExcludes */; + } + function computeFunctionDeclaration(node, subtreeFlags) { + var transformFlags; + var modifierFlags = ts.getModifierFlags(node); + var body = node.body; + if (!body || (modifierFlags & 2 /* Ambient */)) { + // An ambient declaration is TypeScript syntax. + // A FunctionDeclaration without a body is an overload and is TypeScript syntax. + transformFlags = 3 /* AssertTypeScript */; + } + else { + transformFlags = subtreeFlags | 8388608 /* ContainsHoistedDeclarationOrCompletion */; + // TypeScript-specific modifiers, type parameters, and type annotations are TypeScript + // syntax. + if (modifierFlags & 2270 /* TypeScriptModifier */ + || node.typeParameters + || node.type) { + transformFlags |= 3 /* AssertTypeScript */; + } + // An async function declaration is ES2017 syntax. + if (modifierFlags & 256 /* Async */) { + transformFlags |= node.asteriskToken ? 8 /* AssertESNext */ : 16 /* AssertES2017 */; + } + // function declarations with object rest destructuring are ES Next syntax + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { + transformFlags |= 8 /* AssertESNext */; + } + // If a FunctionDeclaration's subtree has marked the container as needing to capture the + // lexical this, or the function contains parameters with initializers, then this node is + // ES6 syntax. + if (subtreeFlags & 81920 /* ES2015FunctionSyntaxMask */) { + transformFlags |= 192 /* AssertES2015 */; + } + // If a FunctionDeclaration is generator function and is the body of a + // transformed async function, then this node can be transformed to a + // down-level generator. + // Currently we do not support transforming any other generator fucntions + // down level. + if (node.asteriskToken) { + transformFlags |= 768 /* AssertGenerator */; + } + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~653620545 /* FunctionExcludes */; + } + function computeFunctionExpression(node, subtreeFlags) { + var transformFlags = subtreeFlags; + // TypeScript-specific modifiers, type parameters, and type annotations are TypeScript + // syntax. + if (ts.hasModifier(node, 2270 /* TypeScriptModifier */) + || node.typeParameters + || node.type) { + transformFlags |= 3 /* AssertTypeScript */; + } + // An async function expression is ES2017 syntax. + if (ts.hasModifier(node, 256 /* Async */)) { + transformFlags |= node.asteriskToken ? 8 /* AssertESNext */ : 16 /* AssertES2017 */; + } + // function expressions with object rest destructuring are ES Next syntax + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { + transformFlags |= 8 /* AssertESNext */; + } + // If a FunctionExpression's subtree has marked the container as needing to capture the + // lexical this, or the function contains parameters with initializers, then this node is + // ES6 syntax. + if (subtreeFlags & 81920 /* ES2015FunctionSyntaxMask */) { + transformFlags |= 192 /* AssertES2015 */; + } + // If a FunctionExpression is generator function and is the body of a + // transformed async function, then this node can be transformed to a + // down-level generator. + if (node.asteriskToken) { + transformFlags |= 768 /* AssertGenerator */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~653620545 /* FunctionExcludes */; + } + function computeArrowFunction(node, subtreeFlags) { + // An ArrowFunction is ES6 syntax, and excludes markers that should not escape the scope of an ArrowFunction. + var transformFlags = subtreeFlags | 192 /* AssertES2015 */; + // TypeScript-specific modifiers, type parameters, and type annotations are TypeScript + // syntax. + if (ts.hasModifier(node, 2270 /* TypeScriptModifier */) + || node.typeParameters + || node.type) { + transformFlags |= 3 /* AssertTypeScript */; + } + // An async arrow function is ES2017 syntax. + if (ts.hasModifier(node, 256 /* Async */)) { + transformFlags |= 16 /* AssertES2017 */; + } + // arrow functions with object rest destructuring are ES Next syntax + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { + transformFlags |= 8 /* AssertESNext */; + } + // If an ArrowFunction contains a lexical this, its container must capture the lexical this. + if (subtreeFlags & 8192 /* ContainsLexicalThis */) { + transformFlags |= 16384 /* ContainsCapturedLexicalThis */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~653604161 /* ArrowFunctionExcludes */; + } + function computePropertyAccess(node, subtreeFlags) { + var transformFlags = subtreeFlags; + // If a PropertyAccessExpression starts with a super keyword, then it is + // ES6 syntax, and requires a lexical `this` binding. + if (transformFlags & 33554432 /* Super */) { + transformFlags ^= 33554432 /* Super */; + // super inside of an async function requires hoisting the super access (ES2017). + // same for super inside of an async generator, which is ESNext. + transformFlags |= 67108864 /* ContainsSuper */ | 16 /* ContainsES2017 */ | 8 /* ContainsESNext */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~570426689 /* PropertyAccessExcludes */; + } + function computeElementAccess(node, subtreeFlags) { + var transformFlags = subtreeFlags; + var expression = node.expression; + var expressionFlags = expression.transformFlags; // We do not want to aggregate flags from the argument expression for super/this capturing + // If an ElementAccessExpression starts with a super keyword, then it is + // ES6 syntax, and requires a lexical `this` binding. + if (expressionFlags & 33554432 /* Super */) { + transformFlags &= ~33554432 /* Super */; + // super inside of an async function requires hoisting the super access (ES2017). + // same for super inside of an async generator, which is ESNext. + transformFlags |= 67108864 /* ContainsSuper */ | 16 /* ContainsES2017 */ | 8 /* ContainsESNext */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~570426689 /* PropertyAccessExcludes */; + } + function computeVariableDeclaration(node, subtreeFlags) { + var transformFlags = subtreeFlags; + transformFlags |= 192 /* AssertES2015 */ | 2097152 /* ContainsBindingPattern */; + // A VariableDeclaration containing ObjectRest is ESNext syntax + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { + transformFlags |= 8 /* AssertESNext */; + } + // Type annotations are TypeScript syntax. + if (node.type) { + transformFlags |= 3 /* AssertTypeScript */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~637535553 /* NodeExcludes */; + } + function computeVariableStatement(node, subtreeFlags) { + var transformFlags; + var declarationListTransformFlags = node.declarationList.transformFlags; + // An ambient declaration is TypeScript syntax. + if (ts.hasModifier(node, 2 /* Ambient */)) { + transformFlags = 3 /* AssertTypeScript */; + } + else { + transformFlags = subtreeFlags; + if (declarationListTransformFlags & 2097152 /* ContainsBindingPattern */) { + transformFlags |= 192 /* AssertES2015 */; + } + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~637535553 /* NodeExcludes */; + } + function computeLabeledStatement(node, subtreeFlags) { + var transformFlags = subtreeFlags; + // A labeled statement containing a block scoped binding *may* need to be transformed from ES6. + if (subtreeFlags & 1048576 /* ContainsBlockScopedBinding */ + && ts.isIterationStatement(node, /*lookInLabeledStatements*/ true)) { + transformFlags |= 192 /* AssertES2015 */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~637535553 /* NodeExcludes */; + } + function computeImportEquals(node, subtreeFlags) { + var transformFlags = subtreeFlags; + // An ImportEqualsDeclaration with a namespace reference is TypeScript. + if (!ts.isExternalModuleImportEqualsDeclaration(node)) { + transformFlags |= 3 /* AssertTypeScript */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~637535553 /* NodeExcludes */; + } + function computeExpressionStatement(node, subtreeFlags) { + var transformFlags = subtreeFlags; + // If the expression of an expression statement is a destructuring assignment, + // then we treat the statement as ES6 so that we can indicate that we do not + // need to hold on to the right-hand side. + if (node.expression.transformFlags & 1024 /* DestructuringAssignment */) { + transformFlags |= 192 /* AssertES2015 */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~637535553 /* NodeExcludes */; + } + function computeModuleDeclaration(node, subtreeFlags) { + var transformFlags = 3 /* AssertTypeScript */; + var modifierFlags = ts.getModifierFlags(node); + if ((modifierFlags & 2 /* Ambient */) === 0) { + transformFlags |= subtreeFlags; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~647001409 /* ModuleExcludes */; + } + function computeVariableDeclarationList(node, subtreeFlags) { + var transformFlags = subtreeFlags | 8388608 /* ContainsHoistedDeclarationOrCompletion */; + if (subtreeFlags & 2097152 /* ContainsBindingPattern */) { + transformFlags |= 192 /* AssertES2015 */; + } + // If a VariableDeclarationList is `let` or `const`, then it is ES6 syntax. + if (node.flags & 3 /* BlockScoped */) { + transformFlags |= 192 /* AssertES2015 */ | 1048576 /* ContainsBlockScopedBinding */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~639894849 /* VariableDeclarationListExcludes */; + } + function computeOther(node, kind, subtreeFlags) { + // Mark transformations needed for each node + var transformFlags = subtreeFlags; + var excludeFlags = 637535553 /* NodeExcludes */; + switch (kind) { + case 121 /* AsyncKeyword */: + case 201 /* AwaitExpression */: + // async/await is ES2017 syntax, but may be ESNext syntax (for async generators) + transformFlags |= 8 /* AssertESNext */ | 16 /* AssertES2017 */; + break; + case 194 /* TypeAssertionExpression */: + case 212 /* AsExpression */: + case 308 /* PartiallyEmittedExpression */: + // These nodes are TypeScript syntax. + transformFlags |= 3 /* AssertTypeScript */; + excludeFlags = 536872257 /* OuterExpressionExcludes */; + break; + case 115 /* PublicKeyword */: + case 113 /* PrivateKeyword */: + case 114 /* ProtectedKeyword */: + case 118 /* AbstractKeyword */: + case 125 /* DeclareKeyword */: + case 77 /* ConstKeyword */: + case 243 /* EnumDeclaration */: + case 278 /* EnumMember */: + case 213 /* NonNullExpression */: + case 133 /* ReadonlyKeyword */: + // These nodes are TypeScript syntax. + transformFlags |= 3 /* AssertTypeScript */; + break; + case 260 /* JsxElement */: + case 261 /* JsxSelfClosingElement */: + case 262 /* JsxOpeningElement */: + case 11 /* JsxText */: + case 263 /* JsxClosingElement */: + case 264 /* JsxFragment */: + case 265 /* JsxOpeningFragment */: + case 266 /* JsxClosingFragment */: + case 267 /* JsxAttribute */: + case 268 /* JsxAttributes */: + case 269 /* JsxSpreadAttribute */: + case 270 /* JsxExpression */: + // These nodes are Jsx syntax. + transformFlags |= 4 /* AssertJsx */; + break; + case 14 /* NoSubstitutionTemplateLiteral */: + case 15 /* TemplateHead */: + case 16 /* TemplateMiddle */: + case 17 /* TemplateTail */: + case 206 /* TemplateExpression */: + case 193 /* TaggedTemplateExpression */: + case 276 /* ShorthandPropertyAssignment */: + case 116 /* StaticKeyword */: + case 214 /* MetaProperty */: + // These nodes are ES6 syntax. + transformFlags |= 192 /* AssertES2015 */; + break; + case 10 /* StringLiteral */: + if (node.hasExtendedUnicodeEscape) { + transformFlags |= 192 /* AssertES2015 */; + } + break; + case 8 /* NumericLiteral */: + if (node.numericLiteralFlags & 384 /* BinaryOrOctalSpecifier */) { + transformFlags |= 192 /* AssertES2015 */; + } + break; + case 9 /* BigIntLiteral */: + transformFlags |= 8 /* AssertESNext */; + break; + case 227 /* ForOfStatement */: + // This node is either ES2015 syntax or ES2017 syntax (if it is a for-await-of). + if (node.awaitModifier) { + transformFlags |= 8 /* AssertESNext */; + } + transformFlags |= 192 /* AssertES2015 */; + break; + case 207 /* YieldExpression */: + // This node is either ES2015 syntax (in a generator) or ES2017 syntax (in an async + // generator). + transformFlags |= 8 /* AssertESNext */ | 192 /* AssertES2015 */ | 4194304 /* ContainsYield */; + break; + case 120 /* AnyKeyword */: + case 135 /* NumberKeyword */: + case 146 /* BigIntKeyword */: + case 132 /* NeverKeyword */: + case 136 /* ObjectKeyword */: + case 138 /* StringKeyword */: + case 123 /* BooleanKeyword */: + case 139 /* SymbolKeyword */: + case 106 /* VoidKeyword */: + case 150 /* TypeParameter */: + case 153 /* PropertySignature */: + case 155 /* MethodSignature */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 162 /* IndexSignature */: + case 163 /* TypePredicate */: + case 164 /* TypeReference */: + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + case 167 /* TypeQuery */: + case 168 /* TypeLiteral */: + case 169 /* ArrayType */: + case 170 /* TupleType */: + case 171 /* OptionalType */: + case 172 /* RestType */: + case 173 /* UnionType */: + case 174 /* IntersectionType */: + case 175 /* ConditionalType */: + case 176 /* InferType */: + case 177 /* ParenthesizedType */: + case 241 /* InterfaceDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 178 /* ThisType */: + case 179 /* TypeOperator */: + case 180 /* IndexedAccessType */: + case 181 /* MappedType */: + case 182 /* LiteralType */: + case 247 /* NamespaceExportDeclaration */: + // Types and signatures are TypeScript syntax, and exclude all other facts. + transformFlags = 3 /* AssertTypeScript */; + excludeFlags = -3 /* TypeExcludes */; + break; + case 149 /* ComputedPropertyName */: + // Even though computed property names are ES6, we don't treat them as such. + // This is so that they can flow through PropertyName transforms unaffected. + // Instead, we mark the container as ES6, so that it can properly handle the transform. + transformFlags |= 524288 /* ContainsComputedPropertyName */; + if (subtreeFlags & 8192 /* ContainsLexicalThis */) { + // A computed method name like `[this.getName()](x: string) { ... }` needs to + // distinguish itself from the normal case of a method body containing `this`: + // `this` inside a method doesn't need to be rewritten (the method provides `this`), + // whereas `this` inside a computed name *might* need to be rewritten if the class/object + // is inside an arrow function: + // `_this = this; () => class K { [_this.getName()]() { ... } }` + // To make this distinction, use ContainsLexicalThisInComputedPropertyName + // instead of ContainsLexicalThis for computed property names + transformFlags |= 32768 /* ContainsLexicalThisInComputedPropertyName */; + } + break; + case 208 /* SpreadElement */: + transformFlags |= 192 /* AssertES2015 */ | 131072 /* ContainsRestOrSpread */; + break; + case 277 /* SpreadAssignment */: + transformFlags |= 8 /* AssertESNext */ | 262144 /* ContainsObjectRestOrSpread */; + break; + case 98 /* SuperKeyword */: + // This node is ES6 syntax. + transformFlags |= 192 /* AssertES2015 */ | 33554432 /* Super */; + excludeFlags = 536872257 /* OuterExpressionExcludes */; // must be set to persist `Super` + break; + case 100 /* ThisKeyword */: + // Mark this node and its ancestors as containing a lexical `this` keyword. + transformFlags |= 8192 /* ContainsLexicalThis */; + break; + case 184 /* ObjectBindingPattern */: + transformFlags |= 192 /* AssertES2015 */ | 2097152 /* ContainsBindingPattern */; + if (subtreeFlags & 131072 /* ContainsRestOrSpread */) { + transformFlags |= 8 /* AssertESNext */ | 262144 /* ContainsObjectRestOrSpread */; + } + excludeFlags = 637666625 /* BindingPatternExcludes */; + break; + case 185 /* ArrayBindingPattern */: + transformFlags |= 192 /* AssertES2015 */ | 2097152 /* ContainsBindingPattern */; + excludeFlags = 637666625 /* BindingPatternExcludes */; + break; + case 186 /* BindingElement */: + transformFlags |= 192 /* AssertES2015 */; + if (node.dotDotDotToken) { + transformFlags |= 131072 /* ContainsRestOrSpread */; + } + break; + case 152 /* Decorator */: + // This node is TypeScript syntax, and marks its container as also being TypeScript syntax. + transformFlags |= 3 /* AssertTypeScript */ | 4096 /* ContainsTypeScriptClassSyntax */; + break; + case 188 /* ObjectLiteralExpression */: + excludeFlags = 638358849 /* ObjectLiteralExcludes */; + if (subtreeFlags & 524288 /* ContainsComputedPropertyName */) { + // If an ObjectLiteralExpression contains a ComputedPropertyName, then it + // is an ES6 node. + transformFlags |= 192 /* AssertES2015 */; + } + if (subtreeFlags & 32768 /* ContainsLexicalThisInComputedPropertyName */) { + // A computed property name containing `this` might need to be rewritten, + // so propagate the ContainsLexicalThis flag upward. + transformFlags |= 8192 /* ContainsLexicalThis */; + } + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { + // If an ObjectLiteralExpression contains a spread element, then it + // is an ES next node. + transformFlags |= 8 /* AssertESNext */; + } + break; + case 187 /* ArrayLiteralExpression */: + case 192 /* NewExpression */: + excludeFlags = 637666625 /* ArrayLiteralOrCallOrNewExcludes */; + if (subtreeFlags & 131072 /* ContainsRestOrSpread */) { + // If the this node contains a SpreadExpression, then it is an ES6 + // node. + transformFlags |= 192 /* AssertES2015 */; + } + break; + case 223 /* DoStatement */: + case 224 /* WhileStatement */: + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + // A loop containing a block scoped binding *may* need to be transformed from ES6. + if (subtreeFlags & 1048576 /* ContainsBlockScopedBinding */) { + transformFlags |= 192 /* AssertES2015 */; + } + break; + case 279 /* SourceFile */: + if (subtreeFlags & 16384 /* ContainsCapturedLexicalThis */) { + transformFlags |= 192 /* AssertES2015 */; + } + break; + case 230 /* ReturnStatement */: + // Return statements may require an `await` in ESNext. + transformFlags |= 8388608 /* ContainsHoistedDeclarationOrCompletion */ | 8 /* AssertESNext */; + break; + case 228 /* ContinueStatement */: + case 229 /* BreakStatement */: + transformFlags |= 8388608 /* ContainsHoistedDeclarationOrCompletion */; + break; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~excludeFlags; + } + /** + * Gets the transform flags to exclude when unioning the transform flags of a subtree. + * + * NOTE: This needs to be kept up-to-date with the exclusions used in `computeTransformFlagsForNode`. + * For performance reasons, `computeTransformFlagsForNode` uses local constant values rather + * than calling this function. + */ + function getTransformFlagsSubtreeExclusions(kind) { + if (kind >= 163 /* FirstTypeNode */ && kind <= 183 /* LastTypeNode */) { + return -3 /* TypeExcludes */; + } + switch (kind) { + case 191 /* CallExpression */: + case 192 /* NewExpression */: + case 187 /* ArrayLiteralExpression */: + return 637666625 /* ArrayLiteralOrCallOrNewExcludes */; + case 244 /* ModuleDeclaration */: + return 647001409 /* ModuleExcludes */; + case 151 /* Parameter */: + return 637535553 /* ParameterExcludes */; + case 197 /* ArrowFunction */: + return 653604161 /* ArrowFunctionExcludes */; + case 196 /* FunctionExpression */: + case 239 /* FunctionDeclaration */: + return 653620545 /* FunctionExcludes */; + case 238 /* VariableDeclarationList */: + return 639894849 /* VariableDeclarationListExcludes */; + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + return 638121281 /* ClassExcludes */; + case 157 /* Constructor */: + return 653616449 /* ConstructorExcludes */; + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + return 653616449 /* MethodOrAccessorExcludes */; + case 120 /* AnyKeyword */: + case 135 /* NumberKeyword */: + case 146 /* BigIntKeyword */: + case 132 /* NeverKeyword */: + case 138 /* StringKeyword */: + case 136 /* ObjectKeyword */: + case 123 /* BooleanKeyword */: + case 139 /* SymbolKeyword */: + case 106 /* VoidKeyword */: + case 150 /* TypeParameter */: + case 153 /* PropertySignature */: + case 155 /* MethodSignature */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 162 /* IndexSignature */: + case 241 /* InterfaceDeclaration */: + case 242 /* TypeAliasDeclaration */: + return -3 /* TypeExcludes */; + case 188 /* ObjectLiteralExpression */: + return 638358849 /* ObjectLiteralExcludes */; + case 274 /* CatchClause */: + return 637797697 /* CatchClauseExcludes */; + case 184 /* ObjectBindingPattern */: + case 185 /* ArrayBindingPattern */: + return 637666625 /* BindingPatternExcludes */; + case 194 /* TypeAssertionExpression */: + case 212 /* AsExpression */: + case 308 /* PartiallyEmittedExpression */: + case 195 /* ParenthesizedExpression */: + case 98 /* SuperKeyword */: + return 536872257 /* OuterExpressionExcludes */; + case 189 /* PropertyAccessExpression */: + case 190 /* ElementAccessExpression */: + return 570426689 /* PropertyAccessExcludes */; + default: + return 637535553 /* NodeExcludes */; + } + } + ts.getTransformFlagsSubtreeExclusions = getTransformFlagsSubtreeExclusions; + /** + * "Binds" JSDoc nodes in TypeScript code. + * Since we will never create symbols for JSDoc, we just set parent pointers instead. + */ + function setParentPointers(parent, child) { + child.parent = parent; + ts.forEachChild(child, function (grandchild) { return setParentPointers(child, grandchild); }); + } +})(ts || (ts = {})); +/** @internal */ +var ts; +(function (ts) { + function createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintOfTypeParameter, getFirstIdentifier) { + return getSymbolWalker; + function getSymbolWalker(accept) { + if (accept === void 0) { accept = function () { return true; }; } + var visitedTypes = []; // Sparse array from id to type + var visitedSymbols = []; // Sparse array from id to symbol + return { + walkType: function (type) { + try { + visitType(type); + return { visitedTypes: ts.getOwnValues(visitedTypes), visitedSymbols: ts.getOwnValues(visitedSymbols) }; + } + finally { + ts.clear(visitedTypes); + ts.clear(visitedSymbols); + } + }, + walkSymbol: function (symbol) { + try { + visitSymbol(symbol); + return { visitedTypes: ts.getOwnValues(visitedTypes), visitedSymbols: ts.getOwnValues(visitedSymbols) }; + } + finally { + ts.clear(visitedTypes); + ts.clear(visitedSymbols); + } + }, + }; + function visitType(type) { + if (!type) { + return; + } + if (visitedTypes[type.id]) { + return; + } + visitedTypes[type.id] = type; + // Reuse visitSymbol to visit the type's symbol, + // but be sure to bail on recuring into the type if accept declines the symbol. + var shouldBail = visitSymbol(type.symbol); + if (shouldBail) + return; + // Visit the type's related types, if any + if (type.flags & 524288 /* Object */) { + var objectType = type; + var objectFlags = objectType.objectFlags; + if (objectFlags & 4 /* Reference */) { + visitTypeReference(type); + } + if (objectFlags & 32 /* Mapped */) { + visitMappedType(type); + } + if (objectFlags & (1 /* Class */ | 2 /* Interface */)) { + visitInterfaceType(type); + } + if (objectFlags & (8 /* Tuple */ | 16 /* Anonymous */)) { + visitObjectType(objectType); + } + } + if (type.flags & 262144 /* TypeParameter */) { + visitTypeParameter(type); + } + if (type.flags & 3145728 /* UnionOrIntersection */) { + visitUnionOrIntersectionType(type); + } + if (type.flags & 4194304 /* Index */) { + visitIndexType(type); + } + if (type.flags & 8388608 /* IndexedAccess */) { + visitIndexedAccessType(type); + } + } + function visitTypeReference(type) { + visitType(type.target); + ts.forEach(type.typeArguments, visitType); + } + function visitTypeParameter(type) { + visitType(getConstraintOfTypeParameter(type)); + } + function visitUnionOrIntersectionType(type) { + ts.forEach(type.types, visitType); + } + function visitIndexType(type) { + visitType(type.type); + } + function visitIndexedAccessType(type) { + visitType(type.objectType); + visitType(type.indexType); + visitType(type.constraint); + } + function visitMappedType(type) { + visitType(type.typeParameter); + visitType(type.constraintType); + visitType(type.templateType); + visitType(type.modifiersType); + } + function visitSignature(signature) { + var typePredicate = getTypePredicateOfSignature(signature); + if (typePredicate) { + visitType(typePredicate.type); + } + ts.forEach(signature.typeParameters, visitType); + for (var _i = 0, _a = signature.parameters; _i < _a.length; _i++) { + var parameter = _a[_i]; + visitSymbol(parameter); + } + visitType(getRestTypeOfSignature(signature)); + visitType(getReturnTypeOfSignature(signature)); + } + function visitInterfaceType(interfaceT) { + visitObjectType(interfaceT); + ts.forEach(interfaceT.typeParameters, visitType); + ts.forEach(getBaseTypes(interfaceT), visitType); + visitType(interfaceT.thisType); + } + function visitObjectType(type) { + var stringIndexType = getIndexTypeOfStructuredType(type, 0 /* String */); + visitType(stringIndexType); + var numberIndexType = getIndexTypeOfStructuredType(type, 1 /* Number */); + visitType(numberIndexType); + // The two checks above *should* have already resolved the type (if needed), so this should be cached + var resolved = resolveStructuredTypeMembers(type); + for (var _i = 0, _a = resolved.callSignatures; _i < _a.length; _i++) { + var signature = _a[_i]; + visitSignature(signature); + } + for (var _b = 0, _c = resolved.constructSignatures; _b < _c.length; _b++) { + var signature = _c[_b]; + visitSignature(signature); + } + for (var _d = 0, _e = resolved.properties; _d < _e.length; _d++) { + var p = _e[_d]; + visitSymbol(p); + } + } + function visitSymbol(symbol) { + if (!symbol) { + return false; + } + var symbolId = ts.getSymbolId(symbol); + if (visitedSymbols[symbolId]) { + return false; + } + visitedSymbols[symbolId] = symbol; + if (!accept(symbol)) { + return true; + } + var t = getTypeOfSymbol(symbol); + visitType(t); // Should handle members on classes and such + if (symbol.exports) { + symbol.exports.forEach(visitSymbol); + } + ts.forEach(symbol.declarations, function (d) { + // Type queries are too far resolved when we just visit the symbol's type + // (their type resolved directly to the member deeply referenced) + // So to get the intervening symbols, we need to check if there's a type + // query node on any of the symbol's declarations and get symbols there + if (d.type && d.type.kind === 167 /* TypeQuery */) { + var query = d.type; + var entity = getResolvedSymbol(getFirstIdentifier(query.exprName)); + visitSymbol(entity); + } + }); + return false; + } + } + } + ts.createGetSymbolWalker = createGetSymbolWalker; +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var ambientModuleSymbolRegex = /^".+"$/; + var nextSymbolId = 1; + var nextNodeId = 1; + var nextMergeId = 1; + var nextFlowId = 1; + function getNodeId(node) { + if (!node.id) { + node.id = nextNodeId; + nextNodeId++; + } + return node.id; + } + ts.getNodeId = getNodeId; + function getSymbolId(symbol) { + if (!symbol.id) { + symbol.id = nextSymbolId; + nextSymbolId++; + } + return symbol.id; + } + ts.getSymbolId = getSymbolId; + function isInstantiatedModule(node, preserveConstEnums) { + var moduleState = ts.getModuleInstanceState(node); + return moduleState === 1 /* Instantiated */ || + (preserveConstEnums && moduleState === 2 /* ConstEnumOnly */); + } + ts.isInstantiatedModule = isInstantiatedModule; + function createTypeChecker(host, produceDiagnostics) { + var getPackagesSet = ts.memoize(function () { + var set = ts.createMap(); + host.getSourceFiles().forEach(function (sf) { + if (!sf.resolvedModules) + return; + ts.forEachEntry(sf.resolvedModules, function (r) { + if (r && r.packageId) + set.set(r.packageId.name, true); + }); + }); + return set; + }); + // Cancellation that controls whether or not we can cancel in the middle of type checking. + // In general cancelling is *not* safe for the type checker. We might be in the middle of + // computing something, and we will leave our internals in an inconsistent state. Callers + // who set the cancellation token should catch if a cancellation exception occurs, and + // should throw away and create a new TypeChecker. + // + // Currently we only support setting the cancellation token when getting diagnostics. This + // is because diagnostics can be quite expensive, and we want to allow hosts to bail out if + // they no longer need the information (for example, if the user started editing again). + var cancellationToken; + var requestedExternalEmitHelpers; + var externalHelpersModule; + // tslint:disable variable-name + var Symbol = ts.objectAllocator.getSymbolConstructor(); + var Type = ts.objectAllocator.getTypeConstructor(); + var Signature = ts.objectAllocator.getSignatureConstructor(); + // tslint:enable variable-name + var typeCount = 0; + var symbolCount = 0; + var enumCount = 0; + var instantiationDepth = 0; + var constraintDepth = 0; + var emptySymbols = ts.createSymbolTable(); + var identityMapper = ts.identity; + var compilerOptions = host.getCompilerOptions(); + var languageVersion = ts.getEmitScriptTarget(compilerOptions); + var moduleKind = ts.getEmitModuleKind(compilerOptions); + var allowSyntheticDefaultImports = ts.getAllowSyntheticDefaultImports(compilerOptions); + var strictNullChecks = ts.getStrictOptionValue(compilerOptions, "strictNullChecks"); + var strictFunctionTypes = ts.getStrictOptionValue(compilerOptions, "strictFunctionTypes"); + var strictBindCallApply = ts.getStrictOptionValue(compilerOptions, "strictBindCallApply"); + var strictPropertyInitialization = ts.getStrictOptionValue(compilerOptions, "strictPropertyInitialization"); + var noImplicitAny = ts.getStrictOptionValue(compilerOptions, "noImplicitAny"); + var noImplicitThis = ts.getStrictOptionValue(compilerOptions, "noImplicitThis"); + var keyofStringsOnly = !!compilerOptions.keyofStringsOnly; + var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 32768 /* FreshLiteral */; + var emitResolver = createResolver(); + var nodeBuilder = createNodeBuilder(); + var undefinedSymbol = createSymbol(4 /* Property */, "undefined"); + undefinedSymbol.declarations = []; + var argumentsSymbol = createSymbol(4 /* Property */, "arguments"); + var requireSymbol = createSymbol(4 /* Property */, "require"); + /** This will be set during calls to `getResolvedSignature` where services determines an apparent number of arguments greater than what is actually provided. */ + var apparentArgumentCount; + // for public members that accept a Node or one of its subtypes, we must guard against + // synthetic nodes created during transformations by calling `getParseTreeNode`. + // for most of these, we perform the guard only on `checker` to avoid any possible + // extra cost of calling `getParseTreeNode` when calling these functions from inside the + // checker. + var checker = { + getNodeCount: function () { return ts.sum(host.getSourceFiles(), "nodeCount"); }, + getIdentifierCount: function () { return ts.sum(host.getSourceFiles(), "identifierCount"); }, + getSymbolCount: function () { return ts.sum(host.getSourceFiles(), "symbolCount") + symbolCount; }, + getTypeCount: function () { return typeCount; }, + isUndefinedSymbol: function (symbol) { return symbol === undefinedSymbol; }, + isArgumentsSymbol: function (symbol) { return symbol === argumentsSymbol; }, + isUnknownSymbol: function (symbol) { return symbol === unknownSymbol; }, + getMergedSymbol: getMergedSymbol, + getDiagnostics: getDiagnostics, + getGlobalDiagnostics: getGlobalDiagnostics, + getTypeOfSymbolAtLocation: function (symbol, location) { + location = ts.getParseTreeNode(location); + return location ? getTypeOfSymbolAtLocation(symbol, location) : errorType; + }, + getSymbolsOfParameterPropertyDeclaration: function (parameterIn, parameterName) { + var parameter = ts.getParseTreeNode(parameterIn, ts.isParameter); + if (parameter === undefined) + return ts.Debug.fail("Cannot get symbols of a synthetic parameter that cannot be resolved to a parse-tree node."); + return getSymbolsOfParameterPropertyDeclaration(parameter, ts.escapeLeadingUnderscores(parameterName)); + }, + getDeclaredTypeOfSymbol: getDeclaredTypeOfSymbol, + getPropertiesOfType: getPropertiesOfType, + getPropertyOfType: function (type, name) { return getPropertyOfType(type, ts.escapeLeadingUnderscores(name)); }, + getTypeOfPropertyOfType: function (type, name) { return getTypeOfPropertyOfType(type, ts.escapeLeadingUnderscores(name)); }, + getIndexInfoOfType: getIndexInfoOfType, + getSignaturesOfType: getSignaturesOfType, + getIndexTypeOfType: getIndexTypeOfType, + getBaseTypes: getBaseTypes, + getBaseTypeOfLiteralType: getBaseTypeOfLiteralType, + getWidenedType: getWidenedType, + getTypeFromTypeNode: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isTypeNode); + return node ? getTypeFromTypeNode(node) : errorType; + }, + getParameterType: getTypeAtPosition, + getPromisedTypeOfPromise: getPromisedTypeOfPromise, + getReturnTypeOfSignature: getReturnTypeOfSignature, + getNullableType: getNullableType, + getNonNullableType: getNonNullableType, + typeToTypeNode: nodeBuilder.typeToTypeNode, + indexInfoToIndexSignatureDeclaration: nodeBuilder.indexInfoToIndexSignatureDeclaration, + signatureToSignatureDeclaration: nodeBuilder.signatureToSignatureDeclaration, + symbolToEntityName: nodeBuilder.symbolToEntityName, + symbolToExpression: nodeBuilder.symbolToExpression, + symbolToTypeParameterDeclarations: nodeBuilder.symbolToTypeParameterDeclarations, + symbolToParameterDeclaration: nodeBuilder.symbolToParameterDeclaration, + typeParameterToDeclaration: nodeBuilder.typeParameterToDeclaration, + getSymbolsInScope: function (location, meaning) { + location = ts.getParseTreeNode(location); + return location ? getSymbolsInScope(location, meaning) : []; + }, + getSymbolAtLocation: function (node) { + node = ts.getParseTreeNode(node); + return node ? getSymbolAtLocation(node) : undefined; + }, + getShorthandAssignmentValueSymbol: function (node) { + node = ts.getParseTreeNode(node); + return node ? getShorthandAssignmentValueSymbol(node) : undefined; + }, + getExportSpecifierLocalTargetSymbol: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isExportSpecifier); + return node ? getExportSpecifierLocalTargetSymbol(node) : undefined; + }, + getExportSymbolOfSymbol: function (symbol) { + return getMergedSymbol(symbol.exportSymbol || symbol); + }, + getTypeAtLocation: function (node) { + node = ts.getParseTreeNode(node); + return node ? getTypeOfNode(node) : errorType; + }, + getPropertySymbolOfDestructuringAssignment: function (locationIn) { + var location = ts.getParseTreeNode(locationIn, ts.isIdentifier); + return location ? getPropertySymbolOfDestructuringAssignment(location) : undefined; + }, + signatureToString: function (signature, enclosingDeclaration, flags, kind) { + return signatureToString(signature, ts.getParseTreeNode(enclosingDeclaration), flags, kind); + }, + typeToString: function (type, enclosingDeclaration, flags) { + return typeToString(type, ts.getParseTreeNode(enclosingDeclaration), flags); + }, + symbolToString: function (symbol, enclosingDeclaration, meaning, flags) { + return symbolToString(symbol, ts.getParseTreeNode(enclosingDeclaration), meaning, flags); + }, + typePredicateToString: function (predicate, enclosingDeclaration, flags) { + return typePredicateToString(predicate, ts.getParseTreeNode(enclosingDeclaration), flags); + }, + writeSignature: function (signature, enclosingDeclaration, flags, kind, writer) { + return signatureToString(signature, ts.getParseTreeNode(enclosingDeclaration), flags, kind, writer); + }, + writeType: function (type, enclosingDeclaration, flags, writer) { + return typeToString(type, ts.getParseTreeNode(enclosingDeclaration), flags, writer); + }, + writeSymbol: function (symbol, enclosingDeclaration, meaning, flags, writer) { + return symbolToString(symbol, ts.getParseTreeNode(enclosingDeclaration), meaning, flags, writer); + }, + writeTypePredicate: function (predicate, enclosingDeclaration, flags, writer) { + return typePredicateToString(predicate, ts.getParseTreeNode(enclosingDeclaration), flags, writer); + }, + getAugmentedPropertiesOfType: getAugmentedPropertiesOfType, + getRootSymbols: getRootSymbols, + getContextualType: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isExpression); + return node ? getContextualType(node) : undefined; + }, + getContextualTypeForObjectLiteralElement: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isObjectLiteralElementLike); + return node ? getContextualTypeForObjectLiteralElement(node) : undefined; + }, + getContextualTypeForArgumentAtIndex: function (nodeIn, argIndex) { + var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression); + return node && getContextualTypeForArgumentAtIndex(node, argIndex); + }, + getContextualTypeForJsxAttribute: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isJsxAttributeLike); + return node && getContextualTypeForJsxAttribute(node); + }, + isContextSensitive: isContextSensitive, + getFullyQualifiedName: getFullyQualifiedName, + getResolvedSignature: function (node, candidatesOutArray, agumentCount) { + return getResolvedSignatureWorker(node, candidatesOutArray, agumentCount, /*isForSignatureHelp*/ false); + }, + getResolvedSignatureForSignatureHelp: function (node, candidatesOutArray, agumentCount) { + return getResolvedSignatureWorker(node, candidatesOutArray, agumentCount, /*isForSignatureHelp*/ true); + }, + getConstantValue: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, canHaveConstantValue); + return node ? getConstantValue(node) : undefined; + }, + isValidPropertyAccess: function (nodeIn, propertyName) { + var node = ts.getParseTreeNode(nodeIn, ts.isPropertyAccessOrQualifiedNameOrImportTypeNode); + return !!node && isValidPropertyAccess(node, ts.escapeLeadingUnderscores(propertyName)); + }, + isValidPropertyAccessForCompletions: function (nodeIn, type, property) { + var node = ts.getParseTreeNode(nodeIn, ts.isPropertyAccessExpression); + return !!node && isValidPropertyAccessForCompletions(node, type, property); + }, + getSignatureFromDeclaration: function (declarationIn) { + var declaration = ts.getParseTreeNode(declarationIn, ts.isFunctionLike); + return declaration ? getSignatureFromDeclaration(declaration) : undefined; + }, + isImplementationOfOverload: function (node) { + var parsed = ts.getParseTreeNode(node, ts.isFunctionLike); + return parsed ? isImplementationOfOverload(parsed) : undefined; + }, + getImmediateAliasedSymbol: getImmediateAliasedSymbol, + getAliasedSymbol: resolveAlias, + getEmitResolver: getEmitResolver, + getExportsOfModule: getExportsOfModuleAsArray, + getExportsAndPropertiesOfModule: getExportsAndPropertiesOfModule, + getSymbolWalker: ts.createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintOfTypeParameter, getFirstIdentifier), + getAmbientModules: getAmbientModules, + getJsxIntrinsicTagNamesAt: getJsxIntrinsicTagNamesAt, + isOptionalParameter: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isParameter); + return node ? isOptionalParameter(node) : false; + }, + tryGetMemberInModuleExports: function (name, symbol) { return tryGetMemberInModuleExports(ts.escapeLeadingUnderscores(name), symbol); }, + tryGetMemberInModuleExportsAndProperties: function (name, symbol) { return tryGetMemberInModuleExportsAndProperties(ts.escapeLeadingUnderscores(name), symbol); }, + tryFindAmbientModuleWithoutAugmentations: function (moduleName) { + // we deliberately exclude augmentations + // since we are only interested in declarations of the module itself + return tryFindAmbientModule(moduleName, /*withAugmentations*/ false); + }, + getApparentType: getApparentType, + getUnionType: getUnionType, + createAnonymousType: createAnonymousType, + createSignature: createSignature, + createSymbol: createSymbol, + createIndexInfo: createIndexInfo, + getAnyType: function () { return anyType; }, + getStringType: function () { return stringType; }, + getNumberType: function () { return numberType; }, + createPromiseType: createPromiseType, + createArrayType: createArrayType, + getElementTypeOfArrayType: getElementTypeOfArrayType, + getBooleanType: function () { return booleanType; }, + getFalseType: function (fresh) { return fresh ? falseType : regularFalseType; }, + getTrueType: function (fresh) { return fresh ? trueType : regularTrueType; }, + getVoidType: function () { return voidType; }, + getUndefinedType: function () { return undefinedType; }, + getNullType: function () { return nullType; }, + getESSymbolType: function () { return esSymbolType; }, + getNeverType: function () { return neverType; }, + isSymbolAccessible: isSymbolAccessible, + getObjectFlags: ts.getObjectFlags, + isArrayLikeType: isArrayLikeType, + isTypeInvalidDueToUnionDiscriminant: isTypeInvalidDueToUnionDiscriminant, + getAllPossiblePropertiesOfTypes: getAllPossiblePropertiesOfTypes, + getSuggestionForNonexistentProperty: function (node, type) { return getSuggestionForNonexistentProperty(node, type); }, + getSuggestionForNonexistentSymbol: function (location, name, meaning) { return getSuggestionForNonexistentSymbol(location, ts.escapeLeadingUnderscores(name), meaning); }, + getSuggestionForNonexistentExport: function (node, target) { return getSuggestionForNonexistentExport(node, target); }, + getBaseConstraintOfType: getBaseConstraintOfType, + getDefaultFromTypeParameter: function (type) { return type && type.flags & 262144 /* TypeParameter */ ? getDefaultFromTypeParameter(type) : undefined; }, + resolveName: function (name, location, meaning, excludeGlobals) { + return resolveName(location, ts.escapeLeadingUnderscores(name), meaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false, excludeGlobals); + }, + getJsxNamespace: function (n) { return ts.unescapeLeadingUnderscores(getJsxNamespace(n)); }, + getAccessibleSymbolChain: getAccessibleSymbolChain, + getTypePredicateOfSignature: getTypePredicateOfSignature, + resolveExternalModuleSymbol: resolveExternalModuleSymbol, + tryGetThisTypeAt: function (node) { + node = ts.getParseTreeNode(node); + return node && tryGetThisTypeAt(node); + }, + getTypeArgumentConstraint: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isTypeNode); + return node && getTypeArgumentConstraint(node); + }, + getSuggestionDiagnostics: function (file, ct) { + if (ts.skipTypeChecking(file, compilerOptions)) { + return ts.emptyArray; + } + var diagnostics; + try { + // Record the cancellation token so it can be checked later on during checkSourceElement. + // Do this in a finally block so we can ensure that it gets reset back to nothing after + // this call is done. + cancellationToken = ct; + // Ensure file is type checked + checkSourceFile(file); + ts.Debug.assert(!!(getNodeLinks(file).flags & 1 /* TypeChecked */)); + diagnostics = ts.addRange(diagnostics, suggestionDiagnostics.get(file.fileName)); + if (!file.isDeclarationFile && (!unusedIsError(0 /* Local */) || !unusedIsError(1 /* Parameter */))) { + addUnusedDiagnostics(); + } + return diagnostics || ts.emptyArray; + } + finally { + cancellationToken = undefined; + } + function addUnusedDiagnostics() { + checkUnusedIdentifiers(getPotentiallyUnusedIdentifiers(file), function (containingNode, kind, diag) { + if (!ts.containsParseError(containingNode) && !unusedIsError(kind)) { + (diagnostics || (diagnostics = [])).push(__assign({}, diag, { category: ts.DiagnosticCategory.Suggestion })); + } + }); + } + }, + runWithCancellationToken: function (token, callback) { + try { + cancellationToken = token; + return callback(checker); + } + finally { + cancellationToken = undefined; + } + }, + getLocalTypeParametersOfClassOrInterfaceOrTypeAlias: getLocalTypeParametersOfClassOrInterfaceOrTypeAlias, + }; + function getResolvedSignatureWorker(nodeIn, candidatesOutArray, argumentCount, isForSignatureHelp) { + var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression); + apparentArgumentCount = argumentCount; + var res = node ? getResolvedSignature(node, candidatesOutArray, isForSignatureHelp) : undefined; + apparentArgumentCount = undefined; + return res; + } + var tupleTypes = ts.createMap(); + var unionTypes = ts.createMap(); + var intersectionTypes = ts.createMap(); + var literalTypes = ts.createMap(); + var indexedAccessTypes = ts.createMap(); + var evolvingArrayTypes = []; + var undefinedProperties = ts.createMap(); + var unknownSymbol = createSymbol(4 /* Property */, "unknown"); + var resolvingSymbol = createSymbol(0, "__resolving__" /* Resolving */); + var anyType = createIntrinsicType(1 /* Any */, "any"); + var autoType = createIntrinsicType(1 /* Any */, "any"); + var wildcardType = createIntrinsicType(1 /* Any */, "any"); + var errorType = createIntrinsicType(1 /* Any */, "error"); + var unknownType = createIntrinsicType(2 /* Unknown */, "unknown"); + var undefinedType = createIntrinsicType(32768 /* Undefined */, "undefined"); + var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(32768 /* Undefined */ | 134217728 /* ContainsWideningType */, "undefined"); + var nullType = createIntrinsicType(65536 /* Null */, "null"); + var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(65536 /* Null */ | 134217728 /* ContainsWideningType */, "null"); + var stringType = createIntrinsicType(4 /* String */, "string"); + var numberType = createIntrinsicType(8 /* Number */, "number"); + var bigintType = createIntrinsicType(64 /* BigInt */, "bigint"); + var falseType = createIntrinsicType(512 /* BooleanLiteral */, "false"); + var regularFalseType = createIntrinsicType(512 /* BooleanLiteral */, "false"); + var trueType = createIntrinsicType(512 /* BooleanLiteral */, "true"); + var regularTrueType = createIntrinsicType(512 /* BooleanLiteral */, "true"); + trueType.regularType = regularTrueType; + trueType.freshType = trueType; + regularTrueType.regularType = regularTrueType; + regularTrueType.freshType = trueType; + falseType.regularType = regularFalseType; + falseType.freshType = falseType; + regularFalseType.regularType = regularFalseType; + regularFalseType.freshType = falseType; + var booleanType = createBooleanType([regularFalseType, regularTrueType]); + // Also mark all combinations of fresh/regular booleans as "Boolean" so they print as `boolean` instead of `true | false` + // (The union is cached, so simply doing the marking here is sufficient) + createBooleanType([regularFalseType, trueType]); + createBooleanType([falseType, regularTrueType]); + createBooleanType([falseType, trueType]); + var esSymbolType = createIntrinsicType(4096 /* ESSymbol */, "symbol"); + var voidType = createIntrinsicType(16384 /* Void */, "void"); + var neverType = createIntrinsicType(131072 /* Never */, "never"); + var silentNeverType = createIntrinsicType(131072 /* Never */, "never"); + var implicitNeverType = createIntrinsicType(131072 /* Never */, "never"); + var nonPrimitiveType = createIntrinsicType(67108864 /* NonPrimitive */, "object"); + var stringNumberSymbolType = getUnionType([stringType, numberType, esSymbolType]); + var keyofConstraintType = keyofStringsOnly ? stringType : stringNumberSymbolType; + var numberOrBigIntType = getUnionType([numberType, bigintType]); + var emptyObjectType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + var emptyJsxObjectType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + emptyJsxObjectType.objectFlags |= 4096 /* JsxAttributes */; + var emptyTypeLiteralSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */); + emptyTypeLiteralSymbol.members = ts.createSymbolTable(); + var emptyTypeLiteralType = createAnonymousType(emptyTypeLiteralSymbol, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + var emptyGenericType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + emptyGenericType.instantiations = ts.createMap(); + var anyFunctionType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + // The anyFunctionType contains the anyFunctionType by definition. The flag is further propagated + // in getPropagatingFlagsOfTypes, and it is checked in inferFromTypes. + anyFunctionType.flags |= 536870912 /* ContainsAnyFunctionType */; + var noConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + var circularConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + var resolvingDefaultType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + var markerSuperType = createType(262144 /* TypeParameter */); + var markerSubType = createType(262144 /* TypeParameter */); + markerSubType.constraint = markerSuperType; + var markerOtherType = createType(262144 /* TypeParameter */); + var noTypePredicate = createIdentifierTypePredicate("<>", 0, anyType); + var anySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + var unknownSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, errorType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + var resolvingSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + var silentNeverSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, silentNeverType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + var enumNumberIndexInfo = createIndexInfo(stringType, /*isReadonly*/ true); + var globals = ts.createSymbolTable(); + /** Key is "/path/to/a.ts|/path/to/b.ts". */ + var amalgamatedDuplicates; + var reverseMappedCache = ts.createMap(); + var ambientModulesCache; + /** + * List of every ambient module with a "*" wildcard. + * Unlike other ambient modules, these can't be stored in `globals` because symbol tables only deal with exact matches. + * This is only used if there is no exact match. + */ + var patternAmbientModules; + var globalObjectType; + var globalFunctionType; + var globalCallableFunctionType; + var globalNewableFunctionType; + var globalArrayType; + var globalReadonlyArrayType; + var globalStringType; + var globalNumberType; + var globalBooleanType; + var globalRegExpType; + var globalThisType; + var anyArrayType; + var autoArrayType; + var anyReadonlyArrayType; + var deferredGlobalNonNullableTypeAlias; + // The library files are only loaded when the feature is used. + // This allows users to just specify library files they want to used through --lib + // and they will not get an error from not having unrelated library files + var deferredGlobalESSymbolConstructorSymbol; + var deferredGlobalESSymbolType; + var deferredGlobalTypedPropertyDescriptorType; + var deferredGlobalPromiseType; + var deferredGlobalPromiseLikeType; + var deferredGlobalPromiseConstructorSymbol; + var deferredGlobalPromiseConstructorLikeType; + var deferredGlobalIterableType; + var deferredGlobalIteratorType; + var deferredGlobalIterableIteratorType; + var deferredGlobalAsyncIterableType; + var deferredGlobalAsyncIteratorType; + var deferredGlobalAsyncIterableIteratorType; + var deferredGlobalTemplateStringsArrayType; + var deferredGlobalImportMetaType; + var deferredGlobalExtractSymbol; + var deferredGlobalExcludeSymbol; + var deferredGlobalPickSymbol; + var deferredGlobalBigIntType; + var allPotentiallyUnusedIdentifiers = ts.createMap(); // key is file name + var flowLoopStart = 0; + var flowLoopCount = 0; + var sharedFlowCount = 0; + var flowAnalysisDisabled = false; + var emptyStringType = getLiteralType(""); + var zeroType = getLiteralType(0); + var zeroBigIntType = getLiteralType({ negative: false, base10Value: "0" }); + var resolutionTargets = []; + var resolutionResults = []; + var resolutionPropertyNames = []; + var suggestionCount = 0; + var maximumSuggestionCount = 10; + var mergedSymbols = []; + var symbolLinks = []; + var nodeLinks = []; + var flowLoopCaches = []; + var flowLoopNodes = []; + var flowLoopKeys = []; + var flowLoopTypes = []; + var sharedFlowNodes = []; + var sharedFlowTypes = []; + var potentialThisCollisions = []; + var potentialNewTargetCollisions = []; + var awaitedTypeStack = []; + var diagnostics = ts.createDiagnosticCollection(); + // Suggestion diagnostics must have a file. Keyed by source file name. + var suggestionDiagnostics = ts.createMultiMap(); + var TypeFacts; + (function (TypeFacts) { + TypeFacts[TypeFacts["None"] = 0] = "None"; + TypeFacts[TypeFacts["TypeofEQString"] = 1] = "TypeofEQString"; + TypeFacts[TypeFacts["TypeofEQNumber"] = 2] = "TypeofEQNumber"; + TypeFacts[TypeFacts["TypeofEQBigInt"] = 4] = "TypeofEQBigInt"; + TypeFacts[TypeFacts["TypeofEQBoolean"] = 8] = "TypeofEQBoolean"; + TypeFacts[TypeFacts["TypeofEQSymbol"] = 16] = "TypeofEQSymbol"; + TypeFacts[TypeFacts["TypeofEQObject"] = 32] = "TypeofEQObject"; + TypeFacts[TypeFacts["TypeofEQFunction"] = 64] = "TypeofEQFunction"; + TypeFacts[TypeFacts["TypeofEQHostObject"] = 128] = "TypeofEQHostObject"; + TypeFacts[TypeFacts["TypeofNEString"] = 256] = "TypeofNEString"; + TypeFacts[TypeFacts["TypeofNENumber"] = 512] = "TypeofNENumber"; + TypeFacts[TypeFacts["TypeofNEBigInt"] = 1024] = "TypeofNEBigInt"; + TypeFacts[TypeFacts["TypeofNEBoolean"] = 2048] = "TypeofNEBoolean"; + TypeFacts[TypeFacts["TypeofNESymbol"] = 4096] = "TypeofNESymbol"; + TypeFacts[TypeFacts["TypeofNEObject"] = 8192] = "TypeofNEObject"; + TypeFacts[TypeFacts["TypeofNEFunction"] = 16384] = "TypeofNEFunction"; + TypeFacts[TypeFacts["TypeofNEHostObject"] = 32768] = "TypeofNEHostObject"; + TypeFacts[TypeFacts["EQUndefined"] = 65536] = "EQUndefined"; + TypeFacts[TypeFacts["EQNull"] = 131072] = "EQNull"; + TypeFacts[TypeFacts["EQUndefinedOrNull"] = 262144] = "EQUndefinedOrNull"; + TypeFacts[TypeFacts["NEUndefined"] = 524288] = "NEUndefined"; + TypeFacts[TypeFacts["NENull"] = 1048576] = "NENull"; + TypeFacts[TypeFacts["NEUndefinedOrNull"] = 2097152] = "NEUndefinedOrNull"; + TypeFacts[TypeFacts["Truthy"] = 4194304] = "Truthy"; + TypeFacts[TypeFacts["Falsy"] = 8388608] = "Falsy"; + TypeFacts[TypeFacts["All"] = 16777215] = "All"; + // The following members encode facts about particular kinds of types for use in the getTypeFacts function. + // The presence of a particular fact means that the given test is true for some (and possibly all) values + // of that kind of type. + TypeFacts[TypeFacts["BaseStringStrictFacts"] = 3735041] = "BaseStringStrictFacts"; + TypeFacts[TypeFacts["BaseStringFacts"] = 12582401] = "BaseStringFacts"; + TypeFacts[TypeFacts["StringStrictFacts"] = 16317953] = "StringStrictFacts"; + TypeFacts[TypeFacts["StringFacts"] = 16776705] = "StringFacts"; + TypeFacts[TypeFacts["EmptyStringStrictFacts"] = 12123649] = "EmptyStringStrictFacts"; + TypeFacts[TypeFacts["EmptyStringFacts"] = 12582401] = "EmptyStringFacts"; + TypeFacts[TypeFacts["NonEmptyStringStrictFacts"] = 7929345] = "NonEmptyStringStrictFacts"; + TypeFacts[TypeFacts["NonEmptyStringFacts"] = 16776705] = "NonEmptyStringFacts"; + TypeFacts[TypeFacts["BaseNumberStrictFacts"] = 3734786] = "BaseNumberStrictFacts"; + TypeFacts[TypeFacts["BaseNumberFacts"] = 12582146] = "BaseNumberFacts"; + TypeFacts[TypeFacts["NumberStrictFacts"] = 16317698] = "NumberStrictFacts"; + TypeFacts[TypeFacts["NumberFacts"] = 16776450] = "NumberFacts"; + TypeFacts[TypeFacts["ZeroNumberStrictFacts"] = 12123394] = "ZeroNumberStrictFacts"; + TypeFacts[TypeFacts["ZeroNumberFacts"] = 12582146] = "ZeroNumberFacts"; + TypeFacts[TypeFacts["NonZeroNumberStrictFacts"] = 7929090] = "NonZeroNumberStrictFacts"; + TypeFacts[TypeFacts["NonZeroNumberFacts"] = 16776450] = "NonZeroNumberFacts"; + TypeFacts[TypeFacts["BaseBigIntStrictFacts"] = 3734276] = "BaseBigIntStrictFacts"; + TypeFacts[TypeFacts["BaseBigIntFacts"] = 12581636] = "BaseBigIntFacts"; + TypeFacts[TypeFacts["BigIntStrictFacts"] = 16317188] = "BigIntStrictFacts"; + TypeFacts[TypeFacts["BigIntFacts"] = 16775940] = "BigIntFacts"; + TypeFacts[TypeFacts["ZeroBigIntStrictFacts"] = 12122884] = "ZeroBigIntStrictFacts"; + TypeFacts[TypeFacts["ZeroBigIntFacts"] = 12581636] = "ZeroBigIntFacts"; + TypeFacts[TypeFacts["NonZeroBigIntStrictFacts"] = 7928580] = "NonZeroBigIntStrictFacts"; + TypeFacts[TypeFacts["NonZeroBigIntFacts"] = 16775940] = "NonZeroBigIntFacts"; + TypeFacts[TypeFacts["BaseBooleanStrictFacts"] = 3733256] = "BaseBooleanStrictFacts"; + TypeFacts[TypeFacts["BaseBooleanFacts"] = 12580616] = "BaseBooleanFacts"; + TypeFacts[TypeFacts["BooleanStrictFacts"] = 16316168] = "BooleanStrictFacts"; + TypeFacts[TypeFacts["BooleanFacts"] = 16774920] = "BooleanFacts"; + TypeFacts[TypeFacts["FalseStrictFacts"] = 12121864] = "FalseStrictFacts"; + TypeFacts[TypeFacts["FalseFacts"] = 12580616] = "FalseFacts"; + TypeFacts[TypeFacts["TrueStrictFacts"] = 7927560] = "TrueStrictFacts"; + TypeFacts[TypeFacts["TrueFacts"] = 16774920] = "TrueFacts"; + TypeFacts[TypeFacts["SymbolStrictFacts"] = 7925520] = "SymbolStrictFacts"; + TypeFacts[TypeFacts["SymbolFacts"] = 16772880] = "SymbolFacts"; + TypeFacts[TypeFacts["ObjectStrictFacts"] = 7888800] = "ObjectStrictFacts"; + TypeFacts[TypeFacts["ObjectFacts"] = 16736160] = "ObjectFacts"; + TypeFacts[TypeFacts["FunctionStrictFacts"] = 7880640] = "FunctionStrictFacts"; + TypeFacts[TypeFacts["FunctionFacts"] = 16728000] = "FunctionFacts"; + TypeFacts[TypeFacts["UndefinedFacts"] = 9830144] = "UndefinedFacts"; + TypeFacts[TypeFacts["NullFacts"] = 9363232] = "NullFacts"; + TypeFacts[TypeFacts["EmptyObjectStrictFacts"] = 16318463] = "EmptyObjectStrictFacts"; + TypeFacts[TypeFacts["EmptyObjectFacts"] = 16777215] = "EmptyObjectFacts"; + })(TypeFacts || (TypeFacts = {})); + var typeofEQFacts = ts.createMapFromTemplate({ + string: 1 /* TypeofEQString */, + number: 2 /* TypeofEQNumber */, + bigint: 4 /* TypeofEQBigInt */, + boolean: 8 /* TypeofEQBoolean */, + symbol: 16 /* TypeofEQSymbol */, + undefined: 65536 /* EQUndefined */, + object: 32 /* TypeofEQObject */, + function: 64 /* TypeofEQFunction */ + }); + var typeofNEFacts = ts.createMapFromTemplate({ + string: 256 /* TypeofNEString */, + number: 512 /* TypeofNENumber */, + bigint: 1024 /* TypeofNEBigInt */, + boolean: 2048 /* TypeofNEBoolean */, + symbol: 4096 /* TypeofNESymbol */, + undefined: 524288 /* NEUndefined */, + object: 8192 /* TypeofNEObject */, + function: 16384 /* TypeofNEFunction */ + }); + var typeofTypesByName = ts.createMapFromTemplate({ + string: stringType, + number: numberType, + bigint: bigintType, + boolean: booleanType, + symbol: esSymbolType, + undefined: undefinedType + }); + var typeofType = createTypeofType(); + var _jsxNamespace; + var _jsxFactoryEntity; + var subtypeRelation = ts.createMap(); + var assignableRelation = ts.createMap(); + var definitelyAssignableRelation = ts.createMap(); + var comparableRelation = ts.createMap(); + var identityRelation = ts.createMap(); + var enumRelation = ts.createMap(); + var TypeSystemPropertyName; + (function (TypeSystemPropertyName) { + TypeSystemPropertyName[TypeSystemPropertyName["Type"] = 0] = "Type"; + TypeSystemPropertyName[TypeSystemPropertyName["ResolvedBaseConstructorType"] = 1] = "ResolvedBaseConstructorType"; + TypeSystemPropertyName[TypeSystemPropertyName["DeclaredType"] = 2] = "DeclaredType"; + TypeSystemPropertyName[TypeSystemPropertyName["ResolvedReturnType"] = 3] = "ResolvedReturnType"; + TypeSystemPropertyName[TypeSystemPropertyName["ImmediateBaseConstraint"] = 4] = "ImmediateBaseConstraint"; + TypeSystemPropertyName[TypeSystemPropertyName["EnumTagType"] = 5] = "EnumTagType"; + TypeSystemPropertyName[TypeSystemPropertyName["JSDocTypeReference"] = 6] = "JSDocTypeReference"; + })(TypeSystemPropertyName || (TypeSystemPropertyName = {})); + var CheckMode; + (function (CheckMode) { + CheckMode[CheckMode["Normal"] = 0] = "Normal"; + CheckMode[CheckMode["SkipContextSensitive"] = 1] = "SkipContextSensitive"; + CheckMode[CheckMode["Inferential"] = 2] = "Inferential"; + CheckMode[CheckMode["Contextual"] = 3] = "Contextual"; + })(CheckMode || (CheckMode = {})); + var CallbackCheck; + (function (CallbackCheck) { + CallbackCheck[CallbackCheck["None"] = 0] = "None"; + CallbackCheck[CallbackCheck["Bivariant"] = 1] = "Bivariant"; + CallbackCheck[CallbackCheck["Strict"] = 2] = "Strict"; + })(CallbackCheck || (CallbackCheck = {})); + var MappedTypeModifiers; + (function (MappedTypeModifiers) { + MappedTypeModifiers[MappedTypeModifiers["IncludeReadonly"] = 1] = "IncludeReadonly"; + MappedTypeModifiers[MappedTypeModifiers["ExcludeReadonly"] = 2] = "ExcludeReadonly"; + MappedTypeModifiers[MappedTypeModifiers["IncludeOptional"] = 4] = "IncludeOptional"; + MappedTypeModifiers[MappedTypeModifiers["ExcludeOptional"] = 8] = "ExcludeOptional"; + })(MappedTypeModifiers || (MappedTypeModifiers = {})); + var ExpandingFlags; + (function (ExpandingFlags) { + ExpandingFlags[ExpandingFlags["None"] = 0] = "None"; + ExpandingFlags[ExpandingFlags["Source"] = 1] = "Source"; + ExpandingFlags[ExpandingFlags["Target"] = 2] = "Target"; + ExpandingFlags[ExpandingFlags["Both"] = 3] = "Both"; + })(ExpandingFlags || (ExpandingFlags = {})); + var MembersOrExportsResolutionKind; + (function (MembersOrExportsResolutionKind) { + MembersOrExportsResolutionKind["resolvedExports"] = "resolvedExports"; + MembersOrExportsResolutionKind["resolvedMembers"] = "resolvedMembers"; + })(MembersOrExportsResolutionKind || (MembersOrExportsResolutionKind = {})); + var UnusedKind; + (function (UnusedKind) { + UnusedKind[UnusedKind["Local"] = 0] = "Local"; + UnusedKind[UnusedKind["Parameter"] = 1] = "Parameter"; + })(UnusedKind || (UnusedKind = {})); + var builtinGlobals = ts.createSymbolTable(); + builtinGlobals.set(undefinedSymbol.escapedName, undefinedSymbol); + var isNotOverloadAndNotAccessor = ts.and(isNotOverload, isNotAccessor); + initializeTypeChecker(); + return checker; + function getJsxNamespace(location) { + if (location) { + var file = ts.getSourceFileOfNode(location); + if (file) { + if (file.localJsxNamespace) { + return file.localJsxNamespace; + } + var jsxPragma = file.pragmas.get("jsx"); + if (jsxPragma) { + var chosenpragma = ts.isArray(jsxPragma) ? jsxPragma[0] : jsxPragma; // TODO: GH#18217 + file.localJsxFactory = ts.parseIsolatedEntityName(chosenpragma.arguments.factory, languageVersion); + if (file.localJsxFactory) { + return file.localJsxNamespace = getFirstIdentifier(file.localJsxFactory).escapedText; + } + } + } + } + if (!_jsxNamespace) { + _jsxNamespace = "React"; + if (compilerOptions.jsxFactory) { + _jsxFactoryEntity = ts.parseIsolatedEntityName(compilerOptions.jsxFactory, languageVersion); + if (_jsxFactoryEntity) { + _jsxNamespace = getFirstIdentifier(_jsxFactoryEntity).escapedText; + } + } + else if (compilerOptions.reactNamespace) { + _jsxNamespace = ts.escapeLeadingUnderscores(compilerOptions.reactNamespace); + } + } + return _jsxNamespace; + } + function getEmitResolver(sourceFile, cancellationToken) { + // Ensure we have all the type information in place for this file so that all the + // emitter questions of this resolver will return the right information. + getDiagnostics(sourceFile, cancellationToken); + return emitResolver; + } + function lookupOrIssueError(location, message, arg0, arg1, arg2, arg3) { + var diagnostic = location + ? ts.createDiagnosticForNode(location, message, arg0, arg1, arg2, arg3) + : ts.createCompilerDiagnostic(message, arg0, arg1, arg2, arg3); + var existing = diagnostics.lookup(diagnostic); + if (existing) { + return existing; + } + else { + diagnostics.add(diagnostic); + return diagnostic; + } + } + function addRelatedInfo(diagnostic) { + var relatedInformation = []; + for (var _i = 1; _i < arguments.length; _i++) { + relatedInformation[_i - 1] = arguments[_i]; + } + var _a; + if (!diagnostic.relatedInformation) { + diagnostic.relatedInformation = []; + } + (_a = diagnostic.relatedInformation).push.apply(_a, relatedInformation); + return diagnostic; + } + function error(location, message, arg0, arg1, arg2, arg3) { + var diagnostic = location + ? ts.createDiagnosticForNode(location, message, arg0, arg1, arg2, arg3) + : ts.createCompilerDiagnostic(message, arg0, arg1, arg2, arg3); + diagnostics.add(diagnostic); + return diagnostic; + } + function addErrorOrSuggestion(isError, diagnostic) { + if (isError) { + diagnostics.add(diagnostic); + } + else { + suggestionDiagnostics.add(diagnostic.file.fileName, __assign({}, diagnostic, { category: ts.DiagnosticCategory.Suggestion })); + } + } + function errorOrSuggestion(isError, location, message, arg0, arg1, arg2, arg3) { + addErrorOrSuggestion(isError, "message" in message ? ts.createDiagnosticForNode(location, message, arg0, arg1, arg2, arg3) : ts.createDiagnosticForNodeFromMessageChain(location, message)); + } + function createSymbol(flags, name, checkFlags) { + symbolCount++; + var symbol = (new Symbol(flags | 33554432 /* Transient */, name)); + symbol.checkFlags = checkFlags || 0; + return symbol; + } + function isTransientSymbol(symbol) { + return (symbol.flags & 33554432 /* Transient */) !== 0; + } + function getExcludedSymbolFlags(flags) { + var result = 0; + if (flags & 2 /* BlockScopedVariable */) + result |= 67220415 /* BlockScopedVariableExcludes */; + if (flags & 1 /* FunctionScopedVariable */) + result |= 67220414 /* FunctionScopedVariableExcludes */; + if (flags & 4 /* Property */) + result |= 0 /* PropertyExcludes */; + if (flags & 8 /* EnumMember */) + result |= 68008959 /* EnumMemberExcludes */; + if (flags & 16 /* Function */) + result |= 67219887 /* FunctionExcludes */; + if (flags & 32 /* Class */) + result |= 68008383 /* ClassExcludes */; + if (flags & 64 /* Interface */) + result |= 67897736 /* InterfaceExcludes */; + if (flags & 256 /* RegularEnum */) + result |= 68008191 /* RegularEnumExcludes */; + if (flags & 128 /* ConstEnum */) + result |= 68008831 /* ConstEnumExcludes */; + if (flags & 512 /* ValueModule */) + result |= 110735 /* ValueModuleExcludes */; + if (flags & 8192 /* Method */) + result |= 67212223 /* MethodExcludes */; + if (flags & 32768 /* GetAccessor */) + result |= 67154879 /* GetAccessorExcludes */; + if (flags & 65536 /* SetAccessor */) + result |= 67187647 /* SetAccessorExcludes */; + if (flags & 262144 /* TypeParameter */) + result |= 67635688 /* TypeParameterExcludes */; + if (flags & 524288 /* TypeAlias */) + result |= 67897832 /* TypeAliasExcludes */; + if (flags & 2097152 /* Alias */) + result |= 2097152 /* AliasExcludes */; + return result; + } + function recordMergedSymbol(target, source) { + if (!source.mergeId) { + source.mergeId = nextMergeId; + nextMergeId++; + } + mergedSymbols[source.mergeId] = target; + } + function cloneSymbol(symbol) { + var result = createSymbol(symbol.flags, symbol.escapedName); + result.declarations = symbol.declarations ? symbol.declarations.slice() : []; + result.parent = symbol.parent; + if (symbol.valueDeclaration) + result.valueDeclaration = symbol.valueDeclaration; + if (symbol.constEnumOnlyModule) + result.constEnumOnlyModule = true; + if (symbol.members) + result.members = ts.cloneMap(symbol.members); + if (symbol.exports) + result.exports = ts.cloneMap(symbol.exports); + recordMergedSymbol(result, symbol); + return result; + } + /** + * Note: if target is transient, then it is mutable, and mergeSymbol with both mutate and return it. + * If target is not transient, mergeSymbol will produce a transient clone, mutate that and return it. + */ + function mergeSymbol(target, source) { + if (!(target.flags & getExcludedSymbolFlags(source.flags)) || + (source.flags | target.flags) & 67108864 /* Assignment */) { + ts.Debug.assert(source !== target); + if (!(target.flags & 33554432 /* Transient */)) { + var resolvedTarget = resolveSymbol(target); + if (resolvedTarget === unknownSymbol) { + return source; + } + target = cloneSymbol(resolvedTarget); + } + // Javascript static-property-assignment declarations always merge, even though they are also values + if (source.flags & 512 /* ValueModule */ && target.flags & 512 /* ValueModule */ && target.constEnumOnlyModule && !source.constEnumOnlyModule) { + // reset flag when merging instantiated module into value module that has only const enums + target.constEnumOnlyModule = false; + } + target.flags |= source.flags; + if (source.valueDeclaration && + (!target.valueDeclaration || + ts.isAssignmentDeclaration(target.valueDeclaration) && !ts.isAssignmentDeclaration(source.valueDeclaration) || + ts.isEffectiveModuleDeclaration(target.valueDeclaration) && !ts.isEffectiveModuleDeclaration(source.valueDeclaration))) { + // other kinds of value declarations take precedence over modules and assignment declarations + target.valueDeclaration = source.valueDeclaration; + } + ts.addRange(target.declarations, source.declarations); + if (source.members) { + if (!target.members) + target.members = ts.createSymbolTable(); + mergeSymbolTable(target.members, source.members); + } + if (source.exports) { + if (!target.exports) + target.exports = ts.createSymbolTable(); + mergeSymbolTable(target.exports, source.exports); + } + recordMergedSymbol(target, source); + } + else if (target.flags & 1024 /* NamespaceModule */) { + error(ts.getNameOfDeclaration(source.declarations[0]), ts.Diagnostics.Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity, symbolToString(target)); + } + else { // error + var isEitherEnum = !!(target.flags & 384 /* Enum */ || source.flags & 384 /* Enum */); + var isEitherBlockScoped_1 = !!(target.flags & 2 /* BlockScopedVariable */ || source.flags & 2 /* BlockScopedVariable */); + var message = isEitherEnum + ? ts.Diagnostics.Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations + : isEitherBlockScoped_1 + ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 + : ts.Diagnostics.Duplicate_identifier_0; + var sourceSymbolFile = source.declarations && ts.getSourceFileOfNode(source.declarations[0]); + var targetSymbolFile = target.declarations && ts.getSourceFileOfNode(target.declarations[0]); + var symbolName_1 = symbolToString(source); + // Collect top-level duplicate identifier errors into one mapping, so we can then merge their diagnostics if there are a bunch + if (sourceSymbolFile && targetSymbolFile && amalgamatedDuplicates && !isEitherEnum && sourceSymbolFile !== targetSymbolFile) { + var firstFile_1 = ts.comparePaths(sourceSymbolFile.path, targetSymbolFile.path) === -1 /* LessThan */ ? sourceSymbolFile : targetSymbolFile; + var secondFile_1 = firstFile_1 === sourceSymbolFile ? targetSymbolFile : sourceSymbolFile; + var filesDuplicates = ts.getOrUpdate(amalgamatedDuplicates, firstFile_1.path + "|" + secondFile_1.path, function () { + return ({ firstFile: firstFile_1, secondFile: secondFile_1, conflictingSymbols: ts.createMap() }); + }); + var conflictingSymbolInfo = ts.getOrUpdate(filesDuplicates.conflictingSymbols, symbolName_1, function () { + return ({ isBlockScoped: isEitherBlockScoped_1, firstFileLocations: [], secondFileLocations: [] }); + }); + addDuplicateLocations(conflictingSymbolInfo.firstFileLocations, source); + addDuplicateLocations(conflictingSymbolInfo.secondFileLocations, target); + } + else { + addDuplicateDeclarationErrorsForSymbols(source, message, symbolName_1, target); + addDuplicateDeclarationErrorsForSymbols(target, message, symbolName_1, source); + } + } + return target; + function addDuplicateLocations(locs, symbol) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + ts.pushIfUnique(locs, (ts.getExpandoInitializer(decl, /*isPrototypeAssignment*/ false) ? ts.getNameOfExpando(decl) : ts.getNameOfDeclaration(decl)) || decl); + } + } + } + function addDuplicateDeclarationErrorsForSymbols(target, message, symbolName, source) { + ts.forEach(target.declarations, function (node) { + var errorNode = (ts.getExpandoInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getNameOfExpando(node) : ts.getNameOfDeclaration(node)) || node; + addDuplicateDeclarationError(errorNode, message, symbolName, source.declarations); + }); + } + function addDuplicateDeclarationError(errorNode, message, symbolName, relatedNodes) { + var err = lookupOrIssueError(errorNode, message, symbolName); + for (var _i = 0, _a = relatedNodes || ts.emptyArray; _i < _a.length; _i++) { + var relatedNode = _a[_i]; + err.relatedInformation = err.relatedInformation || []; + if (ts.length(err.relatedInformation) >= 5) + continue; + addRelatedInfo(err, !ts.length(err.relatedInformation) ? ts.createDiagnosticForNode(relatedNode, ts.Diagnostics._0_was_also_declared_here, symbolName) : ts.createDiagnosticForNode(relatedNode, ts.Diagnostics.and_here)); + } + } + function combineSymbolTables(first, second) { + if (!ts.hasEntries(first)) + return second; + if (!ts.hasEntries(second)) + return first; + var combined = ts.createSymbolTable(); + mergeSymbolTable(combined, first); + mergeSymbolTable(combined, second); + return combined; + } + function mergeSymbolTable(target, source) { + source.forEach(function (sourceSymbol, id) { + var targetSymbol = target.get(id); + target.set(id, targetSymbol ? mergeSymbol(targetSymbol, sourceSymbol) : sourceSymbol); + }); + } + function mergeModuleAugmentation(moduleName) { + var moduleAugmentation = moduleName.parent; + if (moduleAugmentation.symbol.declarations[0] !== moduleAugmentation) { + // this is a combined symbol for multiple augmentations within the same file. + // its symbol already has accumulated information for all declarations + // so we need to add it just once - do the work only for first declaration + ts.Debug.assert(moduleAugmentation.symbol.declarations.length > 1); + return; + } + if (ts.isGlobalScopeAugmentation(moduleAugmentation)) { + mergeSymbolTable(globals, moduleAugmentation.symbol.exports); + } + else { + // find a module that about to be augmented + // do not validate names of augmentations that are defined in ambient context + var moduleNotFoundError = !(moduleName.parent.parent.flags & 4194304 /* Ambient */) + ? ts.Diagnostics.Invalid_module_name_in_augmentation_module_0_cannot_be_found + : undefined; + var mainModule = resolveExternalModuleNameWorker(moduleName, moduleName, moduleNotFoundError, /*isForAugmentation*/ true); + if (!mainModule) { + return; + } + // obtain item referenced by 'export=' + mainModule = resolveExternalModuleSymbol(mainModule); + if (mainModule.flags & 1920 /* Namespace */) { + mainModule = mergeSymbol(mainModule, moduleAugmentation.symbol); + } + else { + // moduleName will be a StringLiteral since this is not `declare global`. + error(moduleName, ts.Diagnostics.Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity, moduleName.text); + } + } + } + function addToSymbolTable(target, source, message) { + source.forEach(function (sourceSymbol, id) { + var targetSymbol = target.get(id); + if (targetSymbol) { + // Error on redeclarations + ts.forEach(targetSymbol.declarations, addDeclarationDiagnostic(ts.unescapeLeadingUnderscores(id), message)); + } + else { + target.set(id, sourceSymbol); + } + }); + function addDeclarationDiagnostic(id, message) { + return function (declaration) { return diagnostics.add(ts.createDiagnosticForNode(declaration, message, id)); }; + } + } + function getSymbolLinks(symbol) { + if (symbol.flags & 33554432 /* Transient */) + return symbol; + var id = getSymbolId(symbol); + return symbolLinks[id] || (symbolLinks[id] = {}); + } + function getNodeLinks(node) { + var nodeId = getNodeId(node); + return nodeLinks[nodeId] || (nodeLinks[nodeId] = { flags: 0 }); + } + function isGlobalSourceFile(node) { + return node.kind === 279 /* SourceFile */ && !ts.isExternalOrCommonJsModule(node); + } + function getSymbol(symbols, name, meaning) { + if (meaning) { + var symbol = symbols.get(name); + if (symbol) { + ts.Debug.assert((ts.getCheckFlags(symbol) & 1 /* Instantiated */) === 0, "Should never get an instantiated symbol here."); + if (symbol.flags & meaning) { + return symbol; + } + if (symbol.flags & 2097152 /* Alias */) { + var target = resolveAlias(symbol); + // Unknown symbol means an error occurred in alias resolution, treat it as positive answer to avoid cascading errors + if (target === unknownSymbol || target.flags & meaning) { + return symbol; + } + } + } + } + // return undefined if we can't find a symbol. + } + /** + * Get symbols that represent parameter-property-declaration as parameter and as property declaration + * @param parameter a parameterDeclaration node + * @param parameterName a name of the parameter to get the symbols for. + * @return a tuple of two symbols + */ + function getSymbolsOfParameterPropertyDeclaration(parameter, parameterName) { + var constructorDeclaration = parameter.parent; + var classDeclaration = parameter.parent.parent; + var parameterSymbol = getSymbol(constructorDeclaration.locals, parameterName, 67220415 /* Value */); + var propertySymbol = getSymbol(getMembersOfSymbol(classDeclaration.symbol), parameterName, 67220415 /* Value */); + if (parameterSymbol && propertySymbol) { + return [parameterSymbol, propertySymbol]; + } + return ts.Debug.fail("There should exist two symbols, one as property declaration and one as parameter declaration"); + } + function isBlockScopedNameDeclaredBeforeUse(declaration, usage) { + var declarationFile = ts.getSourceFileOfNode(declaration); + var useFile = ts.getSourceFileOfNode(usage); + if (declarationFile !== useFile) { + if ((moduleKind && (declarationFile.externalModuleIndicator || useFile.externalModuleIndicator)) || + (!compilerOptions.outFile && !compilerOptions.out) || + isInTypeQuery(usage) || + declaration.flags & 4194304 /* Ambient */) { + // nodes are in different files and order cannot be determined + return true; + } + // declaration is after usage + // can be legal if usage is deferred (i.e. inside function or in initializer of instance property) + if (isUsedInFunctionOrInstanceProperty(usage, declaration)) { + return true; + } + var sourceFiles = host.getSourceFiles(); + return sourceFiles.indexOf(declarationFile) <= sourceFiles.indexOf(useFile); + } + if (declaration.pos <= usage.pos) { + // declaration is before usage + if (declaration.kind === 186 /* BindingElement */) { + // still might be illegal if declaration and usage are both binding elements (eg var [a = b, b = b] = [1, 2]) + var errorBindingElement = ts.getAncestor(usage, 186 /* BindingElement */); + if (errorBindingElement) { + return ts.findAncestor(errorBindingElement, ts.isBindingElement) !== ts.findAncestor(declaration, ts.isBindingElement) || + declaration.pos < errorBindingElement.pos; + } + // or it might be illegal if usage happens before parent variable is declared (eg var [a] = a) + return isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 237 /* VariableDeclaration */), usage); + } + else if (declaration.kind === 237 /* VariableDeclaration */) { + // still might be illegal if usage is in the initializer of the variable declaration (eg var a = a) + return !isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage); + } + else if (ts.isClassDeclaration(declaration)) { + // still might be illegal if the usage is within a computed property name in the class (eg class A { static p = "a"; [A.p]() {} }) + return !ts.findAncestor(usage, function (n) { return ts.isComputedPropertyName(n) && n.parent.parent === declaration; }); + } + return true; + } + // declaration is after usage, but it can still be legal if usage is deferred: + // 1. inside an export specifier + // 2. inside a function + // 3. inside an instance property initializer, a reference to a non-instance property + // 4. inside a static property initializer, a reference to a static method in the same class + // 5. inside a TS export= declaration (since we will move the export statement during emit to avoid TDZ) + // or if usage is in a type context: + // 1. inside a type query (typeof in type position) + // 2. inside a jsdoc comment + if (usage.parent.kind === 257 /* ExportSpecifier */ || (usage.parent.kind === 254 /* ExportAssignment */ && usage.parent.isExportEquals)) { + // export specifiers do not use the variable, they only make it available for use + return true; + } + // When resolving symbols for exports, the `usage` location passed in can be the export site directly + if (usage.kind === 254 /* ExportAssignment */ && usage.isExportEquals) { + return true; + } + var container = ts.getEnclosingBlockScopeContainer(declaration); + return !!(usage.flags & 2097152 /* JSDoc */) || isInTypeQuery(usage) || isUsedInFunctionOrInstanceProperty(usage, declaration, container); + function isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage) { + var container = ts.getEnclosingBlockScopeContainer(declaration); + switch (declaration.parent.parent.kind) { + case 219 /* VariableStatement */: + case 225 /* ForStatement */: + case 227 /* ForOfStatement */: + // variable statement/for/for-of statement case, + // use site should not be inside variable declaration (initializer of declaration or binding element) + if (isSameScopeDescendentOf(usage, declaration, container)) { + return true; + } + break; + } + // ForIn/ForOf case - use site should not be used in expression part + var grandparent = declaration.parent.parent; + return ts.isForInOrOfStatement(grandparent) && isSameScopeDescendentOf(usage, grandparent.expression, container); + } + function isUsedInFunctionOrInstanceProperty(usage, declaration, container) { + return !!ts.findAncestor(usage, function (current) { + if (current === container) { + return "quit"; + } + if (ts.isFunctionLike(current)) { + return true; + } + var initializerOfProperty = current.parent && + current.parent.kind === 154 /* PropertyDeclaration */ && + current.parent.initializer === current; + if (initializerOfProperty) { + if (ts.hasModifier(current.parent, 32 /* Static */)) { + if (declaration.kind === 156 /* MethodDeclaration */) { + return true; + } + } + else { + var isDeclarationInstanceProperty = declaration.kind === 154 /* PropertyDeclaration */ && !ts.hasModifier(declaration, 32 /* Static */); + if (!isDeclarationInstanceProperty || ts.getContainingClass(usage) !== ts.getContainingClass(declaration)) { + return true; + } + } + } + return false; + }); + } + } + /** + * Resolve a given name for a given meaning at a given location. An error is reported if the name was not found and + * the nameNotFoundMessage argument is not undefined. Returns the resolved symbol, or undefined if no symbol with + * the given name can be found. + * + * @param isUse If true, this will count towards --noUnusedLocals / --noUnusedParameters. + */ + function resolveName(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, suggestedNameNotFoundMessage) { + if (excludeGlobals === void 0) { excludeGlobals = false; } + return resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, getSymbol, suggestedNameNotFoundMessage); + } + function resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, lookup, suggestedNameNotFoundMessage) { + var originalLocation = location; // needed for did-you-mean error reporting, which gathers candidates starting from the original location + var result; + var lastLocation; + var lastSelfReferenceLocation; + var propertyWithInvalidInitializer; + var errorLocation = location; + var grandparent; + var isInExternalModule = false; + loop: while (location) { + // Locals of a source file are not in scope (because they get merged into the global symbol table) + if (location.locals && !isGlobalSourceFile(location)) { + if (result = lookup(location.locals, name, meaning)) { + var useResult = true; + if (ts.isFunctionLike(location) && lastLocation && lastLocation !== location.body) { + // symbol lookup restrictions for function-like declarations + // - Type parameters of a function are in scope in the entire function declaration, including the parameter + // list and return type. However, local types are only in scope in the function body. + // - parameters are only in the scope of function body + // This restriction does not apply to JSDoc comment types because they are parented + // at a higher level than type parameters would normally be + if (meaning & result.flags & 67897832 /* Type */ && lastLocation.kind !== 291 /* JSDocComment */) { + useResult = result.flags & 262144 /* TypeParameter */ + // type parameters are visible in parameter list, return type and type parameter list + ? lastLocation === location.type || + lastLocation.kind === 151 /* Parameter */ || + lastLocation.kind === 150 /* TypeParameter */ + // local types not visible outside the function body + : false; + } + if (meaning & result.flags & 3 /* Variable */) { + // expression inside parameter will lookup as normal variable scope when targeting es2015+ + var functionLocation = location; + if (compilerOptions.target && compilerOptions.target >= 2 /* ES2015 */ && ts.isParameter(lastLocation) && + functionLocation.body && result.valueDeclaration.pos >= functionLocation.body.pos && result.valueDeclaration.end <= functionLocation.body.end) { + useResult = false; + } + else if (result.flags & 1 /* FunctionScopedVariable */) { + // parameters are visible only inside function body, parameter list and return type + // technically for parameter list case here we might mix parameters and variables declared in function, + // however it is detected separately when checking initializers of parameters + // to make sure that they reference no variables declared after them. + useResult = + lastLocation.kind === 151 /* Parameter */ || + (lastLocation === location.type && + !!ts.findAncestor(result.valueDeclaration, ts.isParameter)); + } + } + } + else if (location.kind === 175 /* ConditionalType */) { + // A type parameter declared using 'infer T' in a conditional type is visible only in + // the true branch of the conditional type. + useResult = lastLocation === location.trueType; + } + if (useResult) { + break loop; + } + else { + result = undefined; + } + } + } + switch (location.kind) { + case 279 /* SourceFile */: + if (!ts.isExternalOrCommonJsModule(location)) + break; + isInExternalModule = true; + // falls through + case 244 /* ModuleDeclaration */: + var moduleExports = getSymbolOfNode(location).exports; + if (location.kind === 279 /* SourceFile */ || ts.isAmbientModule(location)) { + // It's an external module. First see if the module has an export default and if the local + // name of that export default matches. + if (result = moduleExports.get("default" /* Default */)) { + var localSymbol = ts.getLocalSymbolForExportDefault(result); + if (localSymbol && (result.flags & meaning) && localSymbol.escapedName === name) { + break loop; + } + result = undefined; + } + // Because of module/namespace merging, a module's exports are in scope, + // yet we never want to treat an export specifier as putting a member in scope. + // Therefore, if the name we find is purely an export specifier, it is not actually considered in scope. + // Two things to note about this: + // 1. We have to check this without calling getSymbol. The problem with calling getSymbol + // on an export specifier is that it might find the export specifier itself, and try to + // resolve it as an alias. This will cause the checker to consider the export specifier + // a circular alias reference when it might not be. + // 2. We check === SymbolFlags.Alias in order to check that the symbol is *purely* + // an alias. If we used &, we'd be throwing out symbols that have non alias aspects, + // which is not the desired behavior. + var moduleExport = moduleExports.get(name); + if (moduleExport && + moduleExport.flags === 2097152 /* Alias */ && + ts.getDeclarationOfKind(moduleExport, 257 /* ExportSpecifier */)) { + break; + } + } + // ES6 exports are also visible locally (except for 'default'), but commonjs exports are not (except typedefs) + if (name !== "default" /* Default */ && (result = lookup(moduleExports, name, meaning & 2623475 /* ModuleMember */))) { + if (ts.isSourceFile(location) && location.commonJsModuleIndicator && !result.declarations.some(ts.isJSDocTypeAlias)) { + result = undefined; + } + else { + break loop; + } + } + break; + case 243 /* EnumDeclaration */: + if (result = lookup(getSymbolOfNode(location).exports, name, meaning & 8 /* EnumMember */)) { + break loop; + } + break; + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + // TypeScript 1.0 spec (April 2014): 8.4.1 + // Initializer expressions for instance member variables are evaluated in the scope + // of the class constructor body but are not permitted to reference parameters or + // local variables of the constructor. This effectively means that entities from outer scopes + // by the same name as a constructor parameter or local variable are inaccessible + // in initializer expressions for instance member variables. + if (ts.isClassLike(location.parent) && !ts.hasModifier(location, 32 /* Static */)) { + var ctor = findConstructorDeclaration(location.parent); + if (ctor && ctor.locals) { + if (lookup(ctor.locals, name, meaning & 67220415 /* Value */)) { + // Remember the property node, it will be used later to report appropriate error + propertyWithInvalidInitializer = location; + } + } + } + break; + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 241 /* InterfaceDeclaration */: + // The below is used to lookup type parameters within a class or interface, as they are added to the class/interface locals + // These can never be latebound, so the symbol's raw members are sufficient. `getMembersOfNode` cannot be used, as it would + // trigger resolving late-bound names, which we may already be in the process of doing while we're here! + if (result = lookup(getSymbolOfNode(location).members || emptySymbols, name, meaning & 67897832 /* Type */)) { + if (!isTypeParameterSymbolDeclaredInContainer(result, location)) { + // ignore type parameters not declared in this container + result = undefined; + break; + } + if (lastLocation && ts.hasModifier(lastLocation, 32 /* Static */)) { + // TypeScript 1.0 spec (April 2014): 3.4.1 + // The scope of a type parameter extends over the entire declaration with which the type + // parameter list is associated, with the exception of static member declarations in classes. + error(errorLocation, ts.Diagnostics.Static_members_cannot_reference_class_type_parameters); + return undefined; + } + break loop; + } + if (location.kind === 209 /* ClassExpression */ && meaning & 32 /* Class */) { + var className = location.name; + if (className && name === className.escapedText) { + result = location.symbol; + break loop; + } + } + break; + case 211 /* ExpressionWithTypeArguments */: + // The type parameters of a class are not in scope in the base class expression. + if (lastLocation === location.expression && location.parent.token === 86 /* ExtendsKeyword */) { + var container = location.parent.parent; + if (ts.isClassLike(container) && (result = lookup(getSymbolOfNode(container).members, name, meaning & 67897832 /* Type */))) { + if (nameNotFoundMessage) { + error(errorLocation, ts.Diagnostics.Base_class_expressions_cannot_reference_class_type_parameters); + } + return undefined; + } + } + break; + // It is not legal to reference a class's own type parameters from a computed property name that + // belongs to the class. For example: + // + // function foo() { return '' } + // class C { // <-- Class's own type parameter T + // [foo()]() { } // <-- Reference to T from class's own computed property + // } + // + case 149 /* ComputedPropertyName */: + grandparent = location.parent.parent; + if (ts.isClassLike(grandparent) || grandparent.kind === 241 /* InterfaceDeclaration */) { + // A reference to this grandparent's type parameters would be an error + if (result = lookup(getSymbolOfNode(grandparent).members, name, meaning & 67897832 /* Type */)) { + error(errorLocation, ts.Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type); + return undefined; + } + } + break; + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 239 /* FunctionDeclaration */: + case 197 /* ArrowFunction */: + if (meaning & 3 /* Variable */ && name === "arguments") { + result = argumentsSymbol; + break loop; + } + break; + case 196 /* FunctionExpression */: + if (meaning & 3 /* Variable */ && name === "arguments") { + result = argumentsSymbol; + break loop; + } + if (meaning & 16 /* Function */) { + var functionName = location.name; + if (functionName && name === functionName.escapedText) { + result = location.symbol; + break loop; + } + } + break; + case 152 /* Decorator */: + // Decorators are resolved at the class declaration. Resolving at the parameter + // or member would result in looking up locals in the method. + // + // function y() {} + // class C { + // method(@y x, y) {} // <-- decorator y should be resolved at the class declaration, not the parameter. + // } + // + if (location.parent && location.parent.kind === 151 /* Parameter */) { + location = location.parent; + } + // + // function y() {} + // class C { + // @y method(x, y) {} // <-- decorator y should be resolved at the class declaration, not the method. + // } + // + if (location.parent && ts.isClassElement(location.parent)) { + location = location.parent; + } + break; + case 304 /* JSDocTypedefTag */: + case 297 /* JSDocCallbackTag */: + // js type aliases do not resolve names from their host, so skip past it + location = ts.getJSDocHost(location); + break; + } + if (isSelfReferenceLocation(location)) { + lastSelfReferenceLocation = location; + } + lastLocation = location; + location = location.parent; + } + // We just climbed up parents looking for the name, meaning that we started in a descendant node of `lastLocation`. + // If `result === lastSelfReferenceLocation.symbol`, that means that we are somewhere inside `lastSelfReferenceLocation` looking up a name, and resolving to `lastLocation` itself. + // That means that this is a self-reference of `lastLocation`, and shouldn't count this when considering whether `lastLocation` is used. + if (isUse && result && (!lastSelfReferenceLocation || result !== lastSelfReferenceLocation.symbol)) { + result.isReferenced |= meaning; + } + if (!result) { + if (lastLocation) { + ts.Debug.assert(lastLocation.kind === 279 /* SourceFile */); + if (lastLocation.commonJsModuleIndicator && name === "exports" && meaning & lastLocation.symbol.flags) { + return lastLocation.symbol; + } + } + if (!excludeGlobals) { + result = lookup(globals, name, meaning); + } + } + if (!result) { + if (originalLocation && ts.isInJSFile(originalLocation) && originalLocation.parent) { + if (ts.isRequireCall(originalLocation.parent, /*checkArgumentIsStringLiteralLike*/ false)) { + return requireSymbol; + } + } + } + if (!result) { + if (nameNotFoundMessage) { + if (!errorLocation || + !checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) && // TODO: GH#18217 + !checkAndReportErrorForExtendingInterface(errorLocation) && + !checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) && + !checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) && + !checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning)) { + var suggestion = void 0; + if (suggestedNameNotFoundMessage && suggestionCount < maximumSuggestionCount) { + suggestion = getSuggestedSymbolForNonexistentSymbol(originalLocation, name, meaning); + if (suggestion) { + var suggestionName = symbolToString(suggestion); + var diagnostic = error(errorLocation, suggestedNameNotFoundMessage, diagnosticName(nameArg), suggestionName); + if (suggestion.valueDeclaration) { + addRelatedInfo(diagnostic, ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestionName)); + } + } + } + if (!suggestion) { + error(errorLocation, nameNotFoundMessage, diagnosticName(nameArg)); + } + suggestionCount++; + } + } + return undefined; + } + // Perform extra checks only if error reporting was requested + if (nameNotFoundMessage) { + if (propertyWithInvalidInitializer) { + // We have a match, but the reference occurred within a property initializer and the identifier also binds + // to a local variable in the constructor where the code will be emitted. + var propertyName = propertyWithInvalidInitializer.name; + error(errorLocation, ts.Diagnostics.Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor, ts.declarationNameToString(propertyName), diagnosticName(nameArg)); + return undefined; + } + // Only check for block-scoped variable if we have an error location and are looking for the + // name with variable meaning + // For example, + // declare module foo { + // interface bar {} + // } + // const foo/*1*/: foo/*2*/.bar; + // The foo at /*1*/ and /*2*/ will share same symbol with two meanings: + // block-scoped variable and namespace module. However, only when we + // try to resolve name in /*1*/ which is used in variable position, + // we want to check for block-scoped + if (errorLocation && + (meaning & 2 /* BlockScopedVariable */ || + ((meaning & 32 /* Class */ || meaning & 384 /* Enum */) && (meaning & 67220415 /* Value */) === 67220415 /* Value */))) { + var exportOrLocalSymbol = getExportSymbolOfValueSymbolIfExported(result); + if (exportOrLocalSymbol.flags & 2 /* BlockScopedVariable */ || exportOrLocalSymbol.flags & 32 /* Class */ || exportOrLocalSymbol.flags & 384 /* Enum */) { + checkResolvedBlockScopedVariable(exportOrLocalSymbol, errorLocation); + } + } + // If we're in an external module, we can't reference value symbols created from UMD export declarations + if (result && isInExternalModule && (meaning & 67220415 /* Value */) === 67220415 /* Value */ && !(originalLocation.flags & 2097152 /* JSDoc */)) { + if (ts.some(result.declarations, function (d) { return ts.isNamespaceExportDeclaration(d) || ts.isSourceFile(d) && !!d.symbol.globalExports; })) { + error(errorLocation, ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead, ts.unescapeLeadingUnderscores(name)); // TODO: GH#18217 + } + } + } + return result; + } + function isSelfReferenceLocation(node) { + switch (node.kind) { + case 239 /* FunctionDeclaration */: + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + case 243 /* EnumDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 244 /* ModuleDeclaration */: // For `namespace N { N; }` + return true; + default: + return false; + } + } + function diagnosticName(nameArg) { + return ts.isString(nameArg) ? ts.unescapeLeadingUnderscores(nameArg) : ts.declarationNameToString(nameArg); + } + function isTypeParameterSymbolDeclaredInContainer(symbol, container) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + if (decl.kind === 150 /* TypeParameter */) { + var parent = ts.isJSDocTemplateTag(decl.parent) ? ts.getJSDocHost(decl.parent) : decl.parent; + if (parent === container) { + return !(ts.isJSDocTemplateTag(decl.parent) && ts.find(decl.parent.parent.tags, ts.isJSDocTypeAlias)); // TODO: GH#18217 + } + } + } + return false; + } + function checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) { + if (!ts.isIdentifier(errorLocation) || errorLocation.escapedText !== name || isTypeReferenceIdentifier(errorLocation) || isInTypeQuery(errorLocation)) { + return false; + } + var container = ts.getThisContainer(errorLocation, /*includeArrowFunctions*/ false); + var location = container; + while (location) { + if (ts.isClassLike(location.parent)) { + var classSymbol = getSymbolOfNode(location.parent); + if (!classSymbol) { + break; + } + // Check to see if a static member exists. + var constructorType = getTypeOfSymbol(classSymbol); + if (getPropertyOfType(constructorType, name)) { + error(errorLocation, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_static_member_1_0, diagnosticName(nameArg), symbolToString(classSymbol)); + return true; + } + // No static member is present. + // Check if we're in an instance method and look for a relevant instance member. + if (location === container && !ts.hasModifier(location, 32 /* Static */)) { + var instanceType = getDeclaredTypeOfSymbol(classSymbol).thisType; // TODO: GH#18217 + if (getPropertyOfType(instanceType, name)) { + error(errorLocation, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0, diagnosticName(nameArg)); + return true; + } + } + } + location = location.parent; + } + return false; + } + function checkAndReportErrorForExtendingInterface(errorLocation) { + var expression = getEntityNameForExtendingInterface(errorLocation); + if (expression && resolveEntityName(expression, 64 /* Interface */, /*ignoreErrors*/ true)) { + error(errorLocation, ts.Diagnostics.Cannot_extend_an_interface_0_Did_you_mean_implements, ts.getTextOfNode(expression)); + return true; + } + return false; + } + /** + * Climbs up parents to an ExpressionWithTypeArguments, and returns its expression, + * but returns undefined if that expression is not an EntityNameExpression. + */ + function getEntityNameForExtendingInterface(node) { + switch (node.kind) { + case 72 /* Identifier */: + case 189 /* PropertyAccessExpression */: + return node.parent ? getEntityNameForExtendingInterface(node.parent) : undefined; + case 211 /* ExpressionWithTypeArguments */: + if (ts.isEntityNameExpression(node.expression)) { + return node.expression; + } + // falls through + default: + return undefined; + } + } + function checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) { + var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJSFile(errorLocation) ? 67220415 /* Value */ : 0); + if (meaning === namespaceMeaning) { + var symbol = resolveSymbol(resolveName(errorLocation, name, 67897832 /* Type */ & ~namespaceMeaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + var parent = errorLocation.parent; + if (symbol) { + if (ts.isQualifiedName(parent)) { + ts.Debug.assert(parent.left === errorLocation, "Should only be resolving left side of qualified name as a namespace"); + var propName = parent.right.escapedText; + var propType = getPropertyOfType(getDeclaredTypeOfSymbol(symbol), propName); + if (propType) { + error(parent, ts.Diagnostics.Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_property_1_in_0_with_0_1, ts.unescapeLeadingUnderscores(name), ts.unescapeLeadingUnderscores(propName)); + return true; + } + } + error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here, ts.unescapeLeadingUnderscores(name)); + return true; + } + } + return false; + } + function checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) { + if (meaning & (67220415 /* Value */ & ~1024 /* NamespaceModule */)) { + if (name === "any" || name === "string" || name === "number" || name === "boolean" || name === "never") { + error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, ts.unescapeLeadingUnderscores(name)); + return true; + } + var symbol = resolveSymbol(resolveName(errorLocation, name, 67897832 /* Type */ & ~67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + if (symbol && !(symbol.flags & 1024 /* NamespaceModule */)) { + var message = (name === "Promise" || name === "Symbol") + ? ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later + : ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here; + error(errorLocation, message, ts.unescapeLeadingUnderscores(name)); + return true; + } + } + return false; + } + function checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) { + if (meaning & (67220415 /* Value */ & ~1024 /* NamespaceModule */ & ~67897832 /* Type */)) { + var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 /* NamespaceModule */ & ~67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + if (symbol) { + error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_value, ts.unescapeLeadingUnderscores(name)); + return true; + } + } + else if (meaning & (67897832 /* Type */ & ~1024 /* NamespaceModule */ & ~67220415 /* Value */)) { + var symbol = resolveSymbol(resolveName(errorLocation, name, (512 /* ValueModule */ | 1024 /* NamespaceModule */) & ~67897832 /* Type */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + if (symbol) { + error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_type, ts.unescapeLeadingUnderscores(name)); + return true; + } + } + return false; + } + function checkResolvedBlockScopedVariable(result, errorLocation) { + ts.Debug.assert(!!(result.flags & 2 /* BlockScopedVariable */ || result.flags & 32 /* Class */ || result.flags & 384 /* Enum */)); + // Block-scoped variables cannot be used before their definition + var declaration = ts.find(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) || ts.isClassLike(d) || (d.kind === 243 /* EnumDeclaration */) || ts.isInJSFile(d) && !!ts.getJSDocEnumTag(d); }); + if (declaration === undefined) + return ts.Debug.fail("Declaration to checkResolvedBlockScopedVariable is undefined"); + if (!(declaration.flags & 4194304 /* Ambient */) && !isBlockScopedNameDeclaredBeforeUse(declaration, errorLocation)) { + var diagnosticMessage = void 0; + var declarationName = ts.declarationNameToString(ts.getNameOfDeclaration(declaration)); + if (result.flags & 2 /* BlockScopedVariable */) { + diagnosticMessage = error(errorLocation, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, declarationName); + } + else if (result.flags & 32 /* Class */) { + diagnosticMessage = error(errorLocation, ts.Diagnostics.Class_0_used_before_its_declaration, declarationName); + } + else if (result.flags & 256 /* RegularEnum */) { + diagnosticMessage = error(errorLocation, ts.Diagnostics.Enum_0_used_before_its_declaration, declarationName); + } + else { + ts.Debug.assert(!!(result.flags & 128 /* ConstEnum */)); + if (compilerOptions.preserveConstEnums) { + diagnosticMessage = error(errorLocation, ts.Diagnostics.Class_0_used_before_its_declaration, declarationName); + } + } + if (diagnosticMessage) { + addRelatedInfo(diagnosticMessage, ts.createDiagnosticForNode(declaration, ts.Diagnostics._0_is_declared_here, declarationName)); + } + } + } + /* Starting from 'initial' node walk up the parent chain until 'stopAt' node is reached. + * If at any point current node is equal to 'parent' node - return true. + * Return false if 'stopAt' node is reached or isFunctionLike(current) === true. + */ + function isSameScopeDescendentOf(initial, parent, stopAt) { + return !!parent && !!ts.findAncestor(initial, function (n) { return n === stopAt || ts.isFunctionLike(n) ? "quit" : n === parent; }); + } + function getAnyImportSyntax(node) { + switch (node.kind) { + case 248 /* ImportEqualsDeclaration */: + return node; + case 250 /* ImportClause */: + return node.parent; + case 251 /* NamespaceImport */: + return node.parent.parent; + case 253 /* ImportSpecifier */: + return node.parent.parent.parent; + default: + return undefined; + } + } + function getDeclarationOfAliasSymbol(symbol) { + return ts.find(symbol.declarations, ts.isAliasSymbolDeclaration); + } + function getTargetOfImportEqualsDeclaration(node, dontResolveAlias) { + if (node.moduleReference.kind === 259 /* ExternalModuleReference */) { + return resolveExternalModuleSymbol(resolveExternalModuleName(node, ts.getExternalModuleImportEqualsDeclarationExpression(node))); + } + return getSymbolOfPartOfRightHandSideOfImportEquals(node.moduleReference, dontResolveAlias); + } + function resolveExportByName(moduleSymbol, name, dontResolveAlias) { + var exportValue = moduleSymbol.exports.get("export=" /* ExportEquals */); + return exportValue + ? getPropertyOfType(getTypeOfSymbol(exportValue), name) + : resolveSymbol(moduleSymbol.exports.get(name), dontResolveAlias); + } + function isSyntacticDefault(node) { + return ((ts.isExportAssignment(node) && !node.isExportEquals) || ts.hasModifier(node, 512 /* Default */) || ts.isExportSpecifier(node)); + } + function canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias) { + if (!allowSyntheticDefaultImports) { + return false; + } + // Declaration files (and ambient modules) + if (!file || file.isDeclarationFile) { + // Definitely cannot have a synthetic default if they have a syntactic default member specified + var defaultExportSymbol = resolveExportByName(moduleSymbol, "default" /* Default */, /*dontResolveAlias*/ true); // Dont resolve alias because we want the immediately exported symbol's declaration + if (defaultExportSymbol && ts.some(defaultExportSymbol.declarations, isSyntacticDefault)) { + return false; + } + // It _might_ still be incorrect to assume there is no __esModule marker on the import at runtime, even if there is no `default` member + // So we check a bit more, + if (resolveExportByName(moduleSymbol, ts.escapeLeadingUnderscores("__esModule"), dontResolveAlias)) { + // If there is an `__esModule` specified in the declaration (meaning someone explicitly added it or wrote it in their code), + // it definitely is a module and does not have a synthetic default + return false; + } + // There are _many_ declaration files not written with esmodules in mind that still get compiled into a format with __esModule set + // Meaning there may be no default at runtime - however to be on the permissive side, we allow access to a synthetic default member + // as there is no marker to indicate if the accompanying JS has `__esModule` or not, or is even native esm + return true; + } + // TypeScript files never have a synthetic default (as they are always emitted with an __esModule marker) _unless_ they contain an export= statement + if (!ts.isSourceFileJS(file)) { + return hasExportAssignmentSymbol(moduleSymbol); + } + // JS files have a synthetic default if they do not contain ES2015+ module syntax (export = is not valid in js) _and_ do not have an __esModule marker + return !file.externalModuleIndicator && !resolveExportByName(moduleSymbol, ts.escapeLeadingUnderscores("__esModule"), dontResolveAlias); + } + function getTargetOfImportClause(node, dontResolveAlias) { + var moduleSymbol = resolveExternalModuleName(node, node.parent.moduleSpecifier); + if (moduleSymbol) { + var exportDefaultSymbol = void 0; + if (ts.isShorthandAmbientModuleSymbol(moduleSymbol)) { + exportDefaultSymbol = moduleSymbol; + } + else { + exportDefaultSymbol = resolveExportByName(moduleSymbol, "default" /* Default */, dontResolveAlias); + } + var file = ts.find(moduleSymbol.declarations, ts.isSourceFile); + var hasSyntheticDefault = canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias); + if (!exportDefaultSymbol && !hasSyntheticDefault) { + error(node.name, ts.Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol)); + } + else if (hasSyntheticDefault) { + // per emit behavior, a synthetic default overrides a "real" .default member if `__esModule` is not present + return resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias); + } + return exportDefaultSymbol; + } + } + function getTargetOfNamespaceImport(node, dontResolveAlias) { + var moduleSpecifier = node.parent.parent.moduleSpecifier; + return resolveESModuleSymbol(resolveExternalModuleName(node, moduleSpecifier), moduleSpecifier, dontResolveAlias); + } + // This function creates a synthetic symbol that combines the value side of one symbol with the + // type/namespace side of another symbol. Consider this example: + // + // declare module graphics { + // interface Point { + // x: number; + // y: number; + // } + // } + // declare var graphics: { + // Point: new (x: number, y: number) => graphics.Point; + // } + // declare module "graphics" { + // export = graphics; + // } + // + // An 'import { Point } from "graphics"' needs to create a symbol that combines the value side 'Point' + // property with the type/namespace side interface 'Point'. + function combineValueAndTypeSymbols(valueSymbol, typeSymbol) { + if (valueSymbol === unknownSymbol && typeSymbol === unknownSymbol) { + return unknownSymbol; + } + if (valueSymbol.flags & (67897832 /* Type */ | 1920 /* Namespace */)) { + return valueSymbol; + } + var result = createSymbol(valueSymbol.flags | typeSymbol.flags, valueSymbol.escapedName); + result.declarations = ts.deduplicate(ts.concatenate(valueSymbol.declarations, typeSymbol.declarations), ts.equateValues); + result.parent = valueSymbol.parent || typeSymbol.parent; + if (valueSymbol.valueDeclaration) + result.valueDeclaration = valueSymbol.valueDeclaration; + if (typeSymbol.members) + result.members = typeSymbol.members; + if (valueSymbol.exports) + result.exports = valueSymbol.exports; + return result; + } + function getExportOfModule(symbol, name, dontResolveAlias) { + if (symbol.flags & 1536 /* Module */) { + return resolveSymbol(getExportsOfSymbol(symbol).get(name), dontResolveAlias); + } + } + function getPropertyOfVariable(symbol, name) { + if (symbol.flags & 3 /* Variable */) { + var typeAnnotation = symbol.valueDeclaration.type; + if (typeAnnotation) { + return resolveSymbol(getPropertyOfType(getTypeFromTypeNode(typeAnnotation), name)); + } + } + } + function getExternalModuleMember(node, specifier, dontResolveAlias) { + if (dontResolveAlias === void 0) { dontResolveAlias = false; } + var moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier); // TODO: GH#18217 + var targetSymbol = resolveESModuleSymbol(moduleSymbol, node.moduleSpecifier, dontResolveAlias); + if (targetSymbol) { + var name = specifier.propertyName || specifier.name; + if (name.escapedText) { + if (ts.isShorthandAmbientModuleSymbol(moduleSymbol)) { + return moduleSymbol; + } + var symbolFromVariable = void 0; + // First check if module was specified with "export=". If so, get the member from the resolved type + if (moduleSymbol && moduleSymbol.exports && moduleSymbol.exports.get("export=" /* ExportEquals */)) { + symbolFromVariable = getPropertyOfType(getTypeOfSymbol(targetSymbol), name.escapedText); + } + else { + symbolFromVariable = getPropertyOfVariable(targetSymbol, name.escapedText); + } + // if symbolFromVariable is export - get its final target + symbolFromVariable = resolveSymbol(symbolFromVariable, dontResolveAlias); + var symbolFromModule = getExportOfModule(targetSymbol, name.escapedText, dontResolveAlias); + // If the export member we're looking for is default, and there is no real default but allowSyntheticDefaultImports is on, return the entire module as the default + if (!symbolFromModule && allowSyntheticDefaultImports && name.escapedText === "default" /* Default */) { + symbolFromModule = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias); + } + var symbol = symbolFromModule && symbolFromVariable && symbolFromModule !== symbolFromVariable ? + combineValueAndTypeSymbols(symbolFromVariable, symbolFromModule) : + symbolFromModule || symbolFromVariable; + if (!symbol) { + var moduleName = getFullyQualifiedName(moduleSymbol, node); + var declarationName = ts.declarationNameToString(name); + var suggestion = getSuggestedSymbolForNonexistentModule(name, targetSymbol); + if (suggestion !== undefined) { + var suggestionName = symbolToString(suggestion); + var diagnostic = error(name, ts.Diagnostics.Module_0_has_no_exported_member_1_Did_you_mean_2, moduleName, declarationName, suggestionName); + if (suggestion.valueDeclaration) { + addRelatedInfo(diagnostic, ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestionName)); + } + } + else { + error(name, ts.Diagnostics.Module_0_has_no_exported_member_1, moduleName, declarationName); + } + } + return symbol; + } + } + } + function getTargetOfImportSpecifier(node, dontResolveAlias) { + return getExternalModuleMember(node.parent.parent.parent, node, dontResolveAlias); + } + function getTargetOfNamespaceExportDeclaration(node, dontResolveAlias) { + return resolveExternalModuleSymbol(node.parent.symbol, dontResolveAlias); + } + function getTargetOfExportSpecifier(node, meaning, dontResolveAlias) { + return node.parent.parent.moduleSpecifier ? + getExternalModuleMember(node.parent.parent, node, dontResolveAlias) : + resolveEntityName(node.propertyName || node.name, meaning, /*ignoreErrors*/ false, dontResolveAlias); + } + function getTargetOfExportAssignment(node, dontResolveAlias) { + var expression = (ts.isExportAssignment(node) ? node.expression : node.right); + if (ts.isClassExpression(expression)) { + return checkExpression(expression).symbol; + } + var aliasLike = resolveEntityName(expression, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ true, dontResolveAlias); + if (aliasLike) { + return aliasLike; + } + checkExpression(expression); + return getNodeLinks(expression).resolvedSymbol; + } + function getTargetOfAliasDeclaration(node, dontRecursivelyResolve) { + if (dontRecursivelyResolve === void 0) { dontRecursivelyResolve = false; } + switch (node.kind) { + case 248 /* ImportEqualsDeclaration */: + return getTargetOfImportEqualsDeclaration(node, dontRecursivelyResolve); + case 250 /* ImportClause */: + return getTargetOfImportClause(node, dontRecursivelyResolve); + case 251 /* NamespaceImport */: + return getTargetOfNamespaceImport(node, dontRecursivelyResolve); + case 253 /* ImportSpecifier */: + return getTargetOfImportSpecifier(node, dontRecursivelyResolve); + case 257 /* ExportSpecifier */: + return getTargetOfExportSpecifier(node, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */, dontRecursivelyResolve); + case 254 /* ExportAssignment */: + case 204 /* BinaryExpression */: + return getTargetOfExportAssignment(node, dontRecursivelyResolve); + case 247 /* NamespaceExportDeclaration */: + return getTargetOfNamespaceExportDeclaration(node, dontRecursivelyResolve); + default: + return ts.Debug.fail(); + } + } + /** + * Indicates that a symbol is an alias that does not merge with a local declaration. + * OR Is a JSContainer which may merge an alias with a local declaration + */ + function isNonLocalAlias(symbol, excludes) { + if (excludes === void 0) { excludes = 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */; } + if (!symbol) + return false; + return (symbol.flags & (2097152 /* Alias */ | excludes)) === 2097152 /* Alias */ || !!(symbol.flags & 2097152 /* Alias */ && symbol.flags & 67108864 /* Assignment */); + } + function resolveSymbol(symbol, dontResolveAlias) { + return !dontResolveAlias && isNonLocalAlias(symbol) ? resolveAlias(symbol) : symbol; + } + function resolveAlias(symbol) { + ts.Debug.assert((symbol.flags & 2097152 /* Alias */) !== 0, "Should only get Alias here."); + var links = getSymbolLinks(symbol); + if (!links.target) { + links.target = resolvingSymbol; + var node = getDeclarationOfAliasSymbol(symbol); + if (!node) + return ts.Debug.fail(); + var target = getTargetOfAliasDeclaration(node); + if (links.target === resolvingSymbol) { + links.target = target || unknownSymbol; + } + else { + error(node, ts.Diagnostics.Circular_definition_of_import_alias_0, symbolToString(symbol)); + } + } + else if (links.target === resolvingSymbol) { + links.target = unknownSymbol; + } + return links.target; + } + function markExportAsReferenced(node) { + var symbol = getSymbolOfNode(node); + var target = resolveAlias(symbol); + if (target) { + var markAlias = target === unknownSymbol || + ((target.flags & 67220415 /* Value */) && !isConstEnumOrConstEnumOnlyModule(target)); + if (markAlias) { + markAliasSymbolAsReferenced(symbol); + } + } + } + // When an alias symbol is referenced, we need to mark the entity it references as referenced and in turn repeat that until + // we reach a non-alias or an exported entity (which is always considered referenced). We do this by checking the target of + // the alias as an expression (which recursively takes us back here if the target references another alias). + function markAliasSymbolAsReferenced(symbol) { + var links = getSymbolLinks(symbol); + if (!links.referenced) { + links.referenced = true; + var node = getDeclarationOfAliasSymbol(symbol); + if (!node) + return ts.Debug.fail(); + if (node.kind === 254 /* ExportAssignment */) { + // export default + checkExpressionCached(node.expression); + } + else if (node.kind === 257 /* ExportSpecifier */) { + // export { } or export { as foo } + checkExpressionCached(node.propertyName || node.name); + } + else if (ts.isInternalModuleImportEqualsDeclaration(node)) { + // import foo = + checkExpressionCached(node.moduleReference); + } + } + } + // This function is only for imports with entity names + function getSymbolOfPartOfRightHandSideOfImportEquals(entityName, dontResolveAlias) { + // There are three things we might try to look for. In the following examples, + // the search term is enclosed in |...|: + // + // import a = |b|; // Namespace + // import a = |b.c|; // Value, type, namespace + // import a = |b.c|.d; // Namespace + if (entityName.kind === 72 /* Identifier */ && ts.isRightSideOfQualifiedNameOrPropertyAccess(entityName)) { + entityName = entityName.parent; + } + // Check for case 1 and 3 in the above example + if (entityName.kind === 72 /* Identifier */ || entityName.parent.kind === 148 /* QualifiedName */) { + return resolveEntityName(entityName, 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); + } + else { + // Case 2 in above example + // entityName.kind could be a QualifiedName or a Missing identifier + ts.Debug.assert(entityName.parent.kind === 248 /* ImportEqualsDeclaration */); + return resolveEntityName(entityName, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); + } + } + function getFullyQualifiedName(symbol, containingLocation) { + return symbol.parent ? getFullyQualifiedName(symbol.parent, containingLocation) + "." + symbolToString(symbol) : symbolToString(symbol, containingLocation, /*meaning*/ undefined, 16 /* DoNotIncludeSymbolChain */ | 4 /* AllowAnyNodeKind */); + } + /** + * Resolves a qualified name and any involved aliases. + */ + function resolveEntityName(name, meaning, ignoreErrors, dontResolveAlias, location) { + if (ts.nodeIsMissing(name)) { + return undefined; + } + var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJSFile(name) ? meaning & 67220415 /* Value */ : 0); + var symbol; + if (name.kind === 72 /* Identifier */) { + var message = meaning === namespaceMeaning ? ts.Diagnostics.Cannot_find_namespace_0 : getCannotFindNameDiagnosticForName(getFirstIdentifier(name).escapedText); + var symbolFromJSPrototype = ts.isInJSFile(name) ? resolveEntityNameFromAssignmentDeclaration(name, meaning) : undefined; + symbol = resolveName(location || name, name.escapedText, meaning, ignoreErrors || symbolFromJSPrototype ? undefined : message, name, /*isUse*/ true); + if (!symbol) { + return symbolFromJSPrototype; + } + } + else if (name.kind === 148 /* QualifiedName */ || name.kind === 189 /* PropertyAccessExpression */) { + var left = name.kind === 148 /* QualifiedName */ ? name.left : name.expression; + var right = name.kind === 148 /* QualifiedName */ ? name.right : name.name; + var namespace = resolveEntityName(left, namespaceMeaning, ignoreErrors, /*dontResolveAlias*/ false, location); + if (!namespace || ts.nodeIsMissing(right)) { + return undefined; + } + else if (namespace === unknownSymbol) { + return namespace; + } + if (ts.isInJSFile(name)) { + if (namespace.valueDeclaration && + ts.isVariableDeclaration(namespace.valueDeclaration) && + namespace.valueDeclaration.initializer && + isCommonJsRequire(namespace.valueDeclaration.initializer)) { + var moduleName = namespace.valueDeclaration.initializer.arguments[0]; + var moduleSym = resolveExternalModuleName(moduleName, moduleName); + if (moduleSym) { + var resolvedModuleSymbol = resolveExternalModuleSymbol(moduleSym); + if (resolvedModuleSymbol) { + namespace = resolvedModuleSymbol; + } + } + } + } + symbol = getSymbol(getExportsOfSymbol(namespace), right.escapedText, meaning); + if (!symbol) { + if (!ignoreErrors) { + error(right, ts.Diagnostics.Namespace_0_has_no_exported_member_1, getFullyQualifiedName(namespace), ts.declarationNameToString(right)); + } + return undefined; + } + } + else { + throw ts.Debug.assertNever(name, "Unknown entity name kind."); + } + ts.Debug.assert((ts.getCheckFlags(symbol) & 1 /* Instantiated */) === 0, "Should never get an instantiated symbol here."); + return (symbol.flags & meaning) || dontResolveAlias ? symbol : resolveAlias(symbol); + } + /** + * 1. For prototype-property methods like `A.prototype.m = function () ...`, try to resolve names in the scope of `A` too. + * Note that prototype-property assignment to locations outside the current file (eg globals) doesn't work, so + * name resolution won't work either. + * 2. For property assignments like `{ x: function f () { } }`, try to resolve names in the scope of `f` too. + */ + function resolveEntityNameFromAssignmentDeclaration(name, meaning) { + if (isJSDocTypeReference(name.parent)) { + var secondaryLocation = getAssignmentDeclarationLocation(name.parent); + if (secondaryLocation) { + return resolveName(secondaryLocation, name.escapedText, meaning, /*nameNotFoundMessage*/ undefined, name, /*isUse*/ true); + } + } + } + function getAssignmentDeclarationLocation(node) { + var typeAlias = ts.findAncestor(node, function (node) { return !(ts.isJSDocNode(node) || node.flags & 2097152 /* JSDoc */) ? "quit" : ts.isJSDocTypeAlias(node); }); + if (typeAlias) { + return; + } + var host = ts.getJSDocHost(node); + if (ts.isExpressionStatement(host) && + ts.isBinaryExpression(host.expression) && + ts.getAssignmentDeclarationKind(host.expression) === 3 /* PrototypeProperty */) { + // X.prototype.m = /** @param {K} p */ function () { } <-- look for K on X's declaration + var symbol = getSymbolOfNode(host.expression.left); + if (symbol) { + return getDeclarationOfJSPrototypeContainer(symbol); + } + } + if ((ts.isObjectLiteralMethod(host) || ts.isPropertyAssignment(host)) && + ts.isBinaryExpression(host.parent.parent) && + ts.getAssignmentDeclarationKind(host.parent.parent) === 6 /* Prototype */) { + // X.prototype = { /** @param {K} p */m() { } } <-- look for K on X's declaration + var symbol = getSymbolOfNode(host.parent.parent.left); + if (symbol) { + return getDeclarationOfJSPrototypeContainer(symbol); + } + } + var sig = ts.getHostSignatureFromJSDocHost(host); + if (sig) { + var symbol = getSymbolOfNode(sig); + return symbol && symbol.valueDeclaration; + } + } + function getDeclarationOfJSPrototypeContainer(symbol) { + var decl = symbol.parent.valueDeclaration; + if (!decl) { + return undefined; + } + var initializer = ts.isAssignmentDeclaration(decl) ? ts.getAssignedExpandoInitializer(decl) : + ts.hasOnlyExpressionInitializer(decl) ? ts.getDeclaredExpandoInitializer(decl) : + undefined; + return initializer || decl; + } + function resolveExternalModuleName(location, moduleReferenceExpression, ignoreErrors) { + return resolveExternalModuleNameWorker(location, moduleReferenceExpression, ignoreErrors ? undefined : ts.Diagnostics.Cannot_find_module_0); + } + function resolveExternalModuleNameWorker(location, moduleReferenceExpression, moduleNotFoundError, isForAugmentation) { + if (isForAugmentation === void 0) { isForAugmentation = false; } + return ts.isStringLiteralLike(moduleReferenceExpression) + ? resolveExternalModule(location, moduleReferenceExpression.text, moduleNotFoundError, moduleReferenceExpression, isForAugmentation) + : undefined; + } + function resolveExternalModule(location, moduleReference, moduleNotFoundError, errorNode, isForAugmentation) { + if (isForAugmentation === void 0) { isForAugmentation = false; } + if (moduleReference === undefined) { + return; + } + if (ts.startsWith(moduleReference, "@types/")) { + var diag = ts.Diagnostics.Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1; + var withoutAtTypePrefix = ts.removePrefix(moduleReference, "@types/"); + error(errorNode, diag, withoutAtTypePrefix, moduleReference); + } + var ambientModule = tryFindAmbientModule(moduleReference, /*withAugmentations*/ true); + if (ambientModule) { + return ambientModule; + } + var currentSourceFile = ts.getSourceFileOfNode(location); + var resolvedModule = ts.getResolvedModule(currentSourceFile, moduleReference); // TODO: GH#18217 + var resolutionDiagnostic = resolvedModule && ts.getResolutionDiagnostic(compilerOptions, resolvedModule); + var sourceFile = resolvedModule && !resolutionDiagnostic && host.getSourceFile(resolvedModule.resolvedFileName); + if (sourceFile) { + if (sourceFile.symbol) { + if (resolvedModule.isExternalLibraryImport && !ts.resolutionExtensionIsTSOrJson(resolvedModule.extension)) { + errorOnImplicitAnyModule(/*isError*/ false, errorNode, resolvedModule, moduleReference); + } + // merged symbol is module declaration symbol combined with all augmentations + return getMergedSymbol(sourceFile.symbol); + } + if (moduleNotFoundError) { + // report errors only if it was requested + error(errorNode, ts.Diagnostics.File_0_is_not_a_module, sourceFile.fileName); + } + return undefined; + } + if (patternAmbientModules) { + var pattern = ts.findBestPatternMatch(patternAmbientModules, function (_) { return _.pattern; }, moduleReference); + if (pattern) { + return getMergedSymbol(pattern.symbol); + } + } + // May be an untyped module. If so, ignore resolutionDiagnostic. + if (resolvedModule && !ts.resolutionExtensionIsTSOrJson(resolvedModule.extension) && resolutionDiagnostic === undefined || resolutionDiagnostic === ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type) { + if (isForAugmentation) { + var diag = ts.Diagnostics.Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented; + error(errorNode, diag, moduleReference, resolvedModule.resolvedFileName); + } + else { + errorOnImplicitAnyModule(/*isError*/ noImplicitAny && !!moduleNotFoundError, errorNode, resolvedModule, moduleReference); + } + // Failed imports and untyped modules are both treated in an untyped manner; only difference is whether we give a diagnostic first. + return undefined; + } + if (moduleNotFoundError) { + // For relative paths, see if this was possibly a projectReference redirect + if (ts.pathIsRelative(moduleReference)) { + var sourceFile_1 = ts.getSourceFileOfNode(location); + var redirects = sourceFile_1.redirectedReferences; + if (redirects) { + var normalizedTargetPath = ts.getNormalizedAbsolutePath(moduleReference, ts.getDirectoryPath(sourceFile_1.fileName)); + for (var _i = 0, _a = [".ts" /* Ts */, ".tsx" /* Tsx */]; _i < _a.length; _i++) { + var ext = _a[_i]; + var probePath = normalizedTargetPath + ext; + if (redirects.indexOf(probePath) >= 0) { + error(errorNode, ts.Diagnostics.Output_file_0_has_not_been_built_from_source_file_1, moduleReference, probePath); + return undefined; + } + } + } + } + if (resolutionDiagnostic) { + error(errorNode, resolutionDiagnostic, moduleReference, resolvedModule.resolvedFileName); + } + else { + var tsExtension = ts.tryExtractTSExtension(moduleReference); + if (tsExtension) { + var diag = ts.Diagnostics.An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead; + error(errorNode, diag, tsExtension, ts.removeExtension(moduleReference, tsExtension)); + } + else if (!compilerOptions.resolveJsonModule && + ts.fileExtensionIs(moduleReference, ".json" /* Json */) && + ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs && + ts.hasJsonModuleEmitEnabled(compilerOptions)) { + error(errorNode, ts.Diagnostics.Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension, moduleReference); + } + else { + error(errorNode, moduleNotFoundError, moduleReference); + } + } + } + return undefined; + } + function errorOnImplicitAnyModule(isError, errorNode, _a, moduleReference) { + var packageId = _a.packageId, resolvedFileName = _a.resolvedFileName; + var errorInfo = !ts.isExternalModuleNameRelative(moduleReference) && packageId + ? typesPackageExists(packageId.name) + ? ts.chainDiagnosticMessages( + /*details*/ undefined, ts.Diagnostics.If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1, packageId.name, ts.mangleScopedPackageName(packageId.name)) + : ts.chainDiagnosticMessages( + /*details*/ undefined, ts.Diagnostics.Try_npm_install_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, moduleReference, ts.mangleScopedPackageName(packageId.name)) + : undefined; + errorOrSuggestion(isError, errorNode, ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type, moduleReference, resolvedFileName)); + } + function typesPackageExists(packageName) { + return getPackagesSet().has(ts.getTypesPackageName(packageName)); + } + function resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) { + if (moduleSymbol) { + var exportEquals = resolveSymbol(moduleSymbol.exports.get("export=" /* ExportEquals */), dontResolveAlias); + var exported = getCommonJsExportEquals(exportEquals, moduleSymbol); + return getMergedSymbol(exported) || moduleSymbol; + } + return undefined; + } + function getCommonJsExportEquals(exported, moduleSymbol) { + if (!exported || exported === unknownSymbol || exported === moduleSymbol || moduleSymbol.exports.size === 1 || exported.flags & 2097152 /* Alias */) { + return exported; + } + var merged = cloneSymbol(exported); + if (merged.exports === undefined) { + merged.flags = merged.flags | 512 /* ValueModule */; + merged.exports = ts.createSymbolTable(); + } + moduleSymbol.exports.forEach(function (s, name) { + if (name === "export=" /* ExportEquals */) + return; + merged.exports.set(name, merged.exports.has(name) ? mergeSymbol(merged.exports.get(name), s) : s); + }); + return merged; + } + // An external module with an 'export =' declaration may be referenced as an ES6 module provided the 'export =' + // references a symbol that is at least declared as a module or a variable. The target of the 'export =' may + // combine other declarations with the module or variable (e.g. a class/module, function/module, interface/variable). + function resolveESModuleSymbol(moduleSymbol, referencingLocation, dontResolveAlias) { + var symbol = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias); + if (!dontResolveAlias && symbol) { + if (!(symbol.flags & (1536 /* Module */ | 3 /* Variable */)) && !ts.getDeclarationOfKind(symbol, 279 /* SourceFile */)) { + error(referencingLocation, ts.Diagnostics.Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct, symbolToString(moduleSymbol)); + return symbol; + } + if (compilerOptions.esModuleInterop) { + var referenceParent = referencingLocation.parent; + if ((ts.isImportDeclaration(referenceParent) && ts.getNamespaceDeclarationNode(referenceParent)) || + ts.isImportCall(referenceParent)) { + var type = getTypeOfSymbol(symbol); + var sigs = getSignaturesOfStructuredType(type, 0 /* Call */); + if (!sigs || !sigs.length) { + sigs = getSignaturesOfStructuredType(type, 1 /* Construct */); + } + if (sigs && sigs.length) { + var moduleType = getTypeWithSyntheticDefaultImportType(type, symbol, moduleSymbol); + // Create a new symbol which has the module's type less the call and construct signatures + var result = createSymbol(symbol.flags, symbol.escapedName); + result.declarations = symbol.declarations ? symbol.declarations.slice() : []; + result.parent = symbol.parent; + result.target = symbol; + result.originatingImport = referenceParent; + if (symbol.valueDeclaration) + result.valueDeclaration = symbol.valueDeclaration; + if (symbol.constEnumOnlyModule) + result.constEnumOnlyModule = true; + if (symbol.members) + result.members = ts.cloneMap(symbol.members); + if (symbol.exports) + result.exports = ts.cloneMap(symbol.exports); + var resolvedModuleType = resolveStructuredTypeMembers(moduleType); // Should already be resolved from the signature checks above + result.type = createAnonymousType(result, resolvedModuleType.members, ts.emptyArray, ts.emptyArray, resolvedModuleType.stringIndexInfo, resolvedModuleType.numberIndexInfo); + return result; + } + } + } + } + return symbol; + } + function hasExportAssignmentSymbol(moduleSymbol) { + return moduleSymbol.exports.get("export=" /* ExportEquals */) !== undefined; + } + function getExportsOfModuleAsArray(moduleSymbol) { + return symbolsToArray(getExportsOfModule(moduleSymbol)); + } + function getExportsAndPropertiesOfModule(moduleSymbol) { + var exports = getExportsOfModuleAsArray(moduleSymbol); + var exportEquals = resolveExternalModuleSymbol(moduleSymbol); + if (exportEquals !== moduleSymbol) { + ts.addRange(exports, getPropertiesOfType(getTypeOfSymbol(exportEquals))); + } + return exports; + } + function tryGetMemberInModuleExports(memberName, moduleSymbol) { + var symbolTable = getExportsOfModule(moduleSymbol); + if (symbolTable) { + return symbolTable.get(memberName); + } + } + function tryGetMemberInModuleExportsAndProperties(memberName, moduleSymbol) { + var symbol = tryGetMemberInModuleExports(memberName, moduleSymbol); + if (symbol) { + return symbol; + } + var exportEquals = resolveExternalModuleSymbol(moduleSymbol); + if (exportEquals === moduleSymbol) { + return undefined; + } + var type = getTypeOfSymbol(exportEquals); + return type.flags & 131068 /* Primitive */ ? undefined : getPropertyOfType(type, memberName); + } + function getExportsOfSymbol(symbol) { + return symbol.flags & 32 /* Class */ ? getResolvedMembersOrExportsOfSymbol(symbol, "resolvedExports" /* resolvedExports */) : + symbol.flags & 1536 /* Module */ ? getExportsOfModule(symbol) : + symbol.exports || emptySymbols; + } + function getExportsOfModule(moduleSymbol) { + var links = getSymbolLinks(moduleSymbol); + return links.resolvedExports || (links.resolvedExports = getExportsOfModuleWorker(moduleSymbol)); + } + /** + * Extends one symbol table with another while collecting information on name collisions for error message generation into the `lookupTable` argument + * Not passing `lookupTable` and `exportNode` disables this collection, and just extends the tables + */ + function extendExportSymbols(target, source, lookupTable, exportNode) { + if (!source) + return; + source.forEach(function (sourceSymbol, id) { + if (id === "default" /* Default */) + return; + var targetSymbol = target.get(id); + if (!targetSymbol) { + target.set(id, sourceSymbol); + if (lookupTable && exportNode) { + lookupTable.set(id, { + specifierText: ts.getTextOfNode(exportNode.moduleSpecifier) + }); + } + } + else if (lookupTable && exportNode && targetSymbol && resolveSymbol(targetSymbol) !== resolveSymbol(sourceSymbol)) { + var collisionTracker = lookupTable.get(id); + if (!collisionTracker.exportsWithDuplicate) { + collisionTracker.exportsWithDuplicate = [exportNode]; + } + else { + collisionTracker.exportsWithDuplicate.push(exportNode); + } + } + }); + } + function getExportsOfModuleWorker(moduleSymbol) { + var visitedSymbols = []; + // A module defined by an 'export=' consists of one export that needs to be resolved + moduleSymbol = resolveExternalModuleSymbol(moduleSymbol); + return visit(moduleSymbol) || emptySymbols; + // The ES6 spec permits export * declarations in a module to circularly reference the module itself. For example, + // module 'a' can 'export * from "b"' and 'b' can 'export * from "a"' without error. + function visit(symbol) { + if (!(symbol && symbol.exports && ts.pushIfUnique(visitedSymbols, symbol))) { + return; + } + var symbols = ts.cloneMap(symbol.exports); + // All export * declarations are collected in an __export symbol by the binder + var exportStars = symbol.exports.get("__export" /* ExportStar */); + if (exportStars) { + var nestedSymbols = ts.createSymbolTable(); + var lookupTable_1 = ts.createMap(); + for (var _i = 0, _a = exportStars.declarations; _i < _a.length; _i++) { + var node = _a[_i]; + var resolvedModule = resolveExternalModuleName(node, node.moduleSpecifier); + var exportedSymbols = visit(resolvedModule); + extendExportSymbols(nestedSymbols, exportedSymbols, lookupTable_1, node); + } + lookupTable_1.forEach(function (_a, id) { + var exportsWithDuplicate = _a.exportsWithDuplicate; + // It's not an error if the file with multiple `export *`s with duplicate names exports a member with that name itself + if (id === "export=" || !(exportsWithDuplicate && exportsWithDuplicate.length) || symbols.has(id)) { + return; + } + for (var _i = 0, exportsWithDuplicate_1 = exportsWithDuplicate; _i < exportsWithDuplicate_1.length; _i++) { + var node = exportsWithDuplicate_1[_i]; + diagnostics.add(ts.createDiagnosticForNode(node, ts.Diagnostics.Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambiguity, lookupTable_1.get(id).specifierText, ts.unescapeLeadingUnderscores(id))); + } + }); + extendExportSymbols(symbols, nestedSymbols); + } + return symbols; + } + } + function getMergedSymbol(symbol) { + var merged; + return symbol && symbol.mergeId && (merged = mergedSymbols[symbol.mergeId]) ? merged : symbol; + } + function getSymbolOfNode(node) { + return getMergedSymbol(node.symbol && getLateBoundSymbol(node.symbol)); + } + function getParentOfSymbol(symbol) { + return getMergedSymbol(symbol.parent && getLateBoundSymbol(symbol.parent)); + } + function getAlternativeContainingModules(symbol, enclosingDeclaration) { + var containingFile = ts.getSourceFileOfNode(enclosingDeclaration); + var id = "" + getNodeId(containingFile); + var links = getSymbolLinks(symbol); + var results; + if (links.extendedContainersByFile && (results = links.extendedContainersByFile.get(id))) { + return results; + } + if (containingFile && containingFile.imports) { + // Try to make an import using an import already in the enclosing file, if possible + for (var _i = 0, _a = containingFile.imports; _i < _a.length; _i++) { + var importRef = _a[_i]; + if (ts.nodeIsSynthesized(importRef)) + continue; // Synthetic names can't be resolved by `resolveExternalModuleName` - they'll cause a debug assert if they error + var resolvedModule = resolveExternalModuleName(enclosingDeclaration, importRef, /*ignoreErrors*/ true); + if (!resolvedModule) + continue; + var ref = getAliasForSymbolInContainer(resolvedModule, symbol); + if (!ref) + continue; + results = ts.append(results, resolvedModule); + } + if (ts.length(results)) { + (links.extendedContainersByFile || (links.extendedContainersByFile = ts.createMap())).set(id, results); + return results; + } + } + if (links.extendedContainers) { + return links.extendedContainers; + } + // No results from files already being imported by this file - expand search (expensive, but not location-specific, so cached) + var otherFiles = host.getSourceFiles(); + for (var _b = 0, otherFiles_1 = otherFiles; _b < otherFiles_1.length; _b++) { + var file = otherFiles_1[_b]; + if (!ts.isExternalModule(file)) + continue; + var sym = getSymbolOfNode(file); + var ref = getAliasForSymbolInContainer(sym, symbol); + if (!ref) + continue; + results = ts.append(results, sym); + } + return links.extendedContainers = results || ts.emptyArray; + } + /** + * Attempts to find the symbol corresponding to the container a symbol is in - usually this + * is just its' `.parent`, but for locals, this value is `undefined` + */ + function getContainersOfSymbol(symbol, enclosingDeclaration) { + var container = getParentOfSymbol(symbol); + if (container) { + var additionalContainers = ts.mapDefined(container.declarations, fileSymbolIfFileSymbolExportEqualsContainer); + var reexportContainers = enclosingDeclaration && getAlternativeContainingModules(symbol, enclosingDeclaration); + if (enclosingDeclaration && getAccessibleSymbolChain(container, enclosingDeclaration, 1920 /* Namespace */, /*externalOnly*/ false)) { + return ts.concatenate(ts.concatenate([container], additionalContainers), reexportContainers); // This order expresses a preference for the real container if it is in scope + } + var res = ts.append(additionalContainers, container); + return ts.concatenate(res, reexportContainers); + } + var candidates = ts.mapDefined(symbol.declarations, function (d) { return !ts.isAmbientModule(d) && d.parent && hasNonGlobalAugmentationExternalModuleSymbol(d.parent) ? getSymbolOfNode(d.parent) : undefined; }); + if (!ts.length(candidates)) { + return undefined; + } + return ts.mapDefined(candidates, function (candidate) { return getAliasForSymbolInContainer(candidate, symbol) ? candidate : undefined; }); + function fileSymbolIfFileSymbolExportEqualsContainer(d) { + var fileSymbol = getExternalModuleContainer(d); + var exported = fileSymbol && fileSymbol.exports && fileSymbol.exports.get("export=" /* ExportEquals */); + return resolveSymbol(exported) === resolveSymbol(container) ? fileSymbol : undefined; + } + } + function getAliasForSymbolInContainer(container, symbol) { + if (container === getParentOfSymbol(symbol)) { + // fast path, `symbol` is either already the alias or isn't aliased + return symbol; + } + var exports = getExportsOfSymbol(container); + var quick = exports.get(symbol.escapedName); + if (quick && symbolRefersToTarget(quick)) { + return quick; + } + return ts.forEachEntry(exports, function (exported) { + if (symbolRefersToTarget(exported)) { + return exported; + } + }); + function symbolRefersToTarget(s) { + if (s === symbol || resolveSymbol(s) === symbol || resolveSymbol(s) === resolveSymbol(symbol)) { + return s; + } + } + } + function getExportSymbolOfValueSymbolIfExported(symbol) { + return getMergedSymbol(symbol && (symbol.flags & 1048576 /* ExportValue */) !== 0 ? symbol.exportSymbol : symbol); + } + function symbolIsValue(symbol) { + return !!(symbol.flags & 67220415 /* Value */ || symbol.flags & 2097152 /* Alias */ && resolveAlias(symbol).flags & 67220415 /* Value */); + } + function findConstructorDeclaration(node) { + var members = node.members; + for (var _i = 0, members_2 = members; _i < members_2.length; _i++) { + var member = members_2[_i]; + if (member.kind === 157 /* Constructor */ && ts.nodeIsPresent(member.body)) { + return member; + } + } + } + function createType(flags) { + var result = new Type(checker, flags); + typeCount++; + result.id = typeCount; + return result; + } + function createIntrinsicType(kind, intrinsicName) { + var type = createType(kind); + type.intrinsicName = intrinsicName; + return type; + } + function createBooleanType(trueFalseTypes) { + var type = getUnionType(trueFalseTypes); + type.flags |= 16 /* Boolean */; + type.intrinsicName = "boolean"; + return type; + } + function createObjectType(objectFlags, symbol) { + var type = createType(524288 /* Object */); + type.objectFlags = objectFlags; + type.symbol = symbol; + type.members = undefined; + type.properties = undefined; + type.callSignatures = undefined; + type.constructSignatures = undefined; + type.stringIndexInfo = undefined; + type.numberIndexInfo = undefined; + return type; + } + function createTypeofType() { + return getUnionType(ts.arrayFrom(typeofEQFacts.keys(), getLiteralType)); + } + // A reserved member name starts with two underscores, but the third character cannot be an underscore + // or the @ symbol. A third underscore indicates an escaped form of an identifer that started + // with at least two underscores. The @ character indicates that the name is denoted by a well known ES + // Symbol instance. + function isReservedMemberName(name) { + return name.charCodeAt(0) === 95 /* _ */ && + name.charCodeAt(1) === 95 /* _ */ && + name.charCodeAt(2) !== 95 /* _ */ && + name.charCodeAt(2) !== 64 /* at */; + } + function getNamedMembers(members) { + var result; + members.forEach(function (symbol, id) { + if (!isReservedMemberName(id) && symbolIsValue(symbol)) { + (result || (result = [])).push(symbol); + } + }); + return result || ts.emptyArray; + } + function setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo) { + type.members = members; + type.properties = members === emptySymbols ? ts.emptyArray : getNamedMembers(members); + type.callSignatures = callSignatures; + type.constructSignatures = constructSignatures; + type.stringIndexInfo = stringIndexInfo; + type.numberIndexInfo = numberIndexInfo; + return type; + } + function createAnonymousType(symbol, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo) { + return setStructuredTypeMembers(createObjectType(16 /* Anonymous */, symbol), members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + } + function forEachSymbolTableInScope(enclosingDeclaration, callback) { + var result; + for (var location = enclosingDeclaration; location; location = location.parent) { + // Locals of a source file are not in scope (because they get merged into the global symbol table) + if (location.locals && !isGlobalSourceFile(location)) { + if (result = callback(location.locals)) { + return result; + } + } + switch (location.kind) { + case 279 /* SourceFile */: + if (!ts.isExternalOrCommonJsModule(location)) { + break; + } + // falls through + case 244 /* ModuleDeclaration */: + if (result = callback(getSymbolOfNode(location).exports)) { + return result; + } + break; + } + } + return callback(globals); + } + function getQualifiedLeftMeaning(rightMeaning) { + // If we are looking in value space, the parent meaning is value, other wise it is namespace + return rightMeaning === 67220415 /* Value */ ? 67220415 /* Value */ : 1920 /* Namespace */; + } + function getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, useOnlyExternalAliasing, visitedSymbolTablesMap) { + if (visitedSymbolTablesMap === void 0) { visitedSymbolTablesMap = ts.createMap(); } + if (!(symbol && !isPropertyOrMethodDeclarationSymbol(symbol))) { + return undefined; + } + var id = "" + getSymbolId(symbol); + var visitedSymbolTables = visitedSymbolTablesMap.get(id); + if (!visitedSymbolTables) { + visitedSymbolTablesMap.set(id, visitedSymbolTables = []); + } + return forEachSymbolTableInScope(enclosingDeclaration, getAccessibleSymbolChainFromSymbolTable); + /** + * @param {ignoreQualification} boolean Set when a symbol is being looked for through the exports of another symbol (meaning we have a route to qualify it already) + */ + function getAccessibleSymbolChainFromSymbolTable(symbols, ignoreQualification) { + if (!ts.pushIfUnique(visitedSymbolTables, symbols)) { + return undefined; + } + var result = trySymbolTable(symbols, ignoreQualification); + visitedSymbolTables.pop(); + return result; + } + function canQualifySymbol(symbolFromSymbolTable, meaning) { + // If the symbol is equivalent and doesn't need further qualification, this symbol is accessible + return !needsQualification(symbolFromSymbolTable, enclosingDeclaration, meaning) || + // If symbol needs qualification, make sure that parent is accessible, if it is then this symbol is accessible too + !!getAccessibleSymbolChain(symbolFromSymbolTable.parent, enclosingDeclaration, getQualifiedLeftMeaning(meaning), useOnlyExternalAliasing, visitedSymbolTablesMap); + } + function isAccessible(symbolFromSymbolTable, resolvedAliasSymbol, ignoreQualification) { + return symbol === (resolvedAliasSymbol || symbolFromSymbolTable) && + // if the symbolFromSymbolTable is not external module (it could be if it was determined as ambient external module and would be in globals table) + // and if symbolFromSymbolTable or alias resolution matches the symbol, + // check the symbol can be qualified, it is only then this symbol is accessible + !ts.some(symbolFromSymbolTable.declarations, hasNonGlobalAugmentationExternalModuleSymbol) && + (ignoreQualification || canQualifySymbol(symbolFromSymbolTable, meaning)); + } + function trySymbolTable(symbols, ignoreQualification) { + // If symbol is directly available by its name in the symbol table + if (isAccessible(symbols.get(symbol.escapedName), /*resolvedAliasSymbol*/ undefined, ignoreQualification)) { + return [symbol]; + } + // Check if symbol is any of the alias + return ts.forEachEntry(symbols, function (symbolFromSymbolTable) { + if (symbolFromSymbolTable.flags & 2097152 /* Alias */ + && symbolFromSymbolTable.escapedName !== "export=" /* ExportEquals */ + && symbolFromSymbolTable.escapedName !== "default" /* Default */ + && !(ts.isUMDExportSymbol(symbolFromSymbolTable) && enclosingDeclaration && ts.isExternalModule(ts.getSourceFileOfNode(enclosingDeclaration))) + // If `!useOnlyExternalAliasing`, we can use any type of alias to get the name + && (!useOnlyExternalAliasing || ts.some(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration)) + // While exports are generally considered to be in scope, export-specifier declared symbols are _not_ + // See similar comment in `resolveName` for details + && (ignoreQualification || !ts.getDeclarationOfKind(symbolFromSymbolTable, 257 /* ExportSpecifier */))) { + var resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable); + if (isAccessible(symbolFromSymbolTable, resolvedImportedSymbol, ignoreQualification)) { + return [symbolFromSymbolTable]; + } + // Look in the exported members, if we can find accessibleSymbolChain, symbol is accessible using this chain + // but only if the symbolFromSymbolTable can be qualified + var candidateTable = getExportsOfSymbol(resolvedImportedSymbol); + var accessibleSymbolsFromExports = candidateTable && getAccessibleSymbolChainFromSymbolTable(candidateTable, /*ignoreQualification*/ true); + if (accessibleSymbolsFromExports && canQualifySymbol(symbolFromSymbolTable, getQualifiedLeftMeaning(meaning))) { + return [symbolFromSymbolTable].concat(accessibleSymbolsFromExports); + } + } + if (symbolFromSymbolTable.escapedName === symbol.escapedName && symbolFromSymbolTable.exportSymbol) { + if (isAccessible(getMergedSymbol(symbolFromSymbolTable.exportSymbol), /*aliasSymbol*/ undefined, ignoreQualification)) { + return [symbol]; + } + } + }); + } + } + function needsQualification(symbol, enclosingDeclaration, meaning) { + var qualify = false; + forEachSymbolTableInScope(enclosingDeclaration, function (symbolTable) { + // If symbol of this name is not available in the symbol table we are ok + var symbolFromSymbolTable = getMergedSymbol(symbolTable.get(symbol.escapedName)); + if (!symbolFromSymbolTable) { + // Continue to the next symbol table + return false; + } + // If the symbol with this name is present it should refer to the symbol + if (symbolFromSymbolTable === symbol) { + // No need to qualify + return true; + } + // Qualify if the symbol from symbol table has same meaning as expected + symbolFromSymbolTable = (symbolFromSymbolTable.flags & 2097152 /* Alias */ && !ts.getDeclarationOfKind(symbolFromSymbolTable, 257 /* ExportSpecifier */)) ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable; + if (symbolFromSymbolTable.flags & meaning) { + qualify = true; + return true; + } + // Continue to the next symbol table + return false; + }); + return qualify; + } + function isPropertyOrMethodDeclarationSymbol(symbol) { + if (symbol.declarations && symbol.declarations.length) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + switch (declaration.kind) { + case 154 /* PropertyDeclaration */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + continue; + default: + return false; + } + } + return true; + } + return false; + } + function isTypeSymbolAccessible(typeSymbol, enclosingDeclaration) { + var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67897832 /* Type */, /*shouldComputeAliasesToMakeVisible*/ false); + return access.accessibility === 0 /* Accessible */; + } + function isValueSymbolAccessible(typeSymbol, enclosingDeclaration) { + var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67220415 /* Value */, /*shouldComputeAliasesToMakeVisible*/ false); + return access.accessibility === 0 /* Accessible */; + } + function isAnySymbolAccessible(symbols, enclosingDeclaration, initialSymbol, meaning, shouldComputeAliasesToMakeVisible) { + if (!ts.length(symbols)) + return; + var hadAccessibleChain; + for (var _i = 0, _a = symbols; _i < _a.length; _i++) { + var symbol = _a[_i]; + // Symbol is accessible if it by itself is accessible + var accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, /*useOnlyExternalAliasing*/ false); + if (accessibleSymbolChain) { + hadAccessibleChain = symbol; + var hasAccessibleDeclarations = hasVisibleDeclarations(accessibleSymbolChain[0], shouldComputeAliasesToMakeVisible); + if (hasAccessibleDeclarations) { + return hasAccessibleDeclarations; + } + } + else { + if (ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { + // Any meaning of a module symbol is always accessible via an `import` type + return { + accessibility: 0 /* Accessible */ + }; + } + } + // If we haven't got the accessible symbol, it doesn't mean the symbol is actually inaccessible. + // It could be a qualified symbol and hence verify the path + // e.g.: + // module m { + // export class c { + // } + // } + // const x: typeof m.c + // In the above example when we start with checking if typeof m.c symbol is accessible, + // we are going to see if c can be accessed in scope directly. + // But it can't, hence the accessible is going to be undefined, but that doesn't mean m.c is inaccessible + // It is accessible if the parent m is accessible because then m.c can be accessed through qualification + var containers = getContainersOfSymbol(symbol, enclosingDeclaration); + // If we're trying to reference some object literal in, eg `var a = { x: 1 }`, the symbol for the literal, `__object`, is distinct + // from the symbol of the declaration it is being assigned to. Since we can use the declaration to refer to the literal, however, + // we'd like to make that connection here - potentially causing us to paint the declararation's visibiility, and therefore the literal. + var firstDecl = ts.first(symbol.declarations); + if (!ts.length(containers) && meaning & 67220415 /* Value */ && firstDecl && ts.isObjectLiteralExpression(firstDecl)) { + if (firstDecl.parent && ts.isVariableDeclaration(firstDecl.parent) && firstDecl === firstDecl.parent.initializer) { + containers = [getSymbolOfNode(firstDecl.parent)]; + } + } + var parentResult = isAnySymbolAccessible(containers, enclosingDeclaration, initialSymbol, initialSymbol === symbol ? getQualifiedLeftMeaning(meaning) : meaning, shouldComputeAliasesToMakeVisible); + if (parentResult) { + return parentResult; + } + } + if (hadAccessibleChain) { + return { + accessibility: 1 /* NotAccessible */, + errorSymbolName: symbolToString(initialSymbol, enclosingDeclaration, meaning), + errorModuleName: hadAccessibleChain !== initialSymbol ? symbolToString(hadAccessibleChain, enclosingDeclaration, 1920 /* Namespace */) : undefined, + }; + } + } + /** + * Check if the given symbol in given enclosing declaration is accessible and mark all associated alias to be visible if requested + * + * @param symbol a Symbol to check if accessible + * @param enclosingDeclaration a Node containing reference to the symbol + * @param meaning a SymbolFlags to check if such meaning of the symbol is accessible + * @param shouldComputeAliasToMakeVisible a boolean value to indicate whether to return aliases to be mark visible in case the symbol is accessible + */ + function isSymbolAccessible(symbol, enclosingDeclaration, meaning, shouldComputeAliasesToMakeVisible) { + if (symbol && enclosingDeclaration) { + var result = isAnySymbolAccessible([symbol], enclosingDeclaration, symbol, meaning, shouldComputeAliasesToMakeVisible); + if (result) { + return result; + } + // This could be a symbol that is not exported in the external module + // or it could be a symbol from different external module that is not aliased and hence cannot be named + var symbolExternalModule = ts.forEach(symbol.declarations, getExternalModuleContainer); + if (symbolExternalModule) { + var enclosingExternalModule = getExternalModuleContainer(enclosingDeclaration); + if (symbolExternalModule !== enclosingExternalModule) { + // name from different external module that is not visible + return { + accessibility: 2 /* CannotBeNamed */, + errorSymbolName: symbolToString(symbol, enclosingDeclaration, meaning), + errorModuleName: symbolToString(symbolExternalModule) + }; + } + } + // Just a local name that is not accessible + return { + accessibility: 1 /* NotAccessible */, + errorSymbolName: symbolToString(symbol, enclosingDeclaration, meaning), + }; + } + return { accessibility: 0 /* Accessible */ }; + } + function getExternalModuleContainer(declaration) { + var node = ts.findAncestor(declaration, hasExternalModuleSymbol); + return node && getSymbolOfNode(node); + } + function hasExternalModuleSymbol(declaration) { + return ts.isAmbientModule(declaration) || (declaration.kind === 279 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration)); + } + function hasNonGlobalAugmentationExternalModuleSymbol(declaration) { + return ts.isModuleWithStringLiteralName(declaration) || (declaration.kind === 279 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration)); + } + function hasVisibleDeclarations(symbol, shouldComputeAliasToMakeVisible) { + var aliasesToMakeVisible; + if (!ts.every(symbol.declarations, getIsDeclarationVisible)) { + return undefined; + } + return { accessibility: 0 /* Accessible */, aliasesToMakeVisible: aliasesToMakeVisible }; + function getIsDeclarationVisible(declaration) { + if (!isDeclarationVisible(declaration)) { + // Mark the unexported alias as visible if its parent is visible + // because these kind of aliases can be used to name types in declaration file + var anyImportSyntax = getAnyImportSyntax(declaration); + if (anyImportSyntax && + !ts.hasModifier(anyImportSyntax, 1 /* Export */) && // import clause without export + isDeclarationVisible(anyImportSyntax.parent)) { + return addVisibleAlias(declaration, anyImportSyntax); + } + else if (ts.isVariableDeclaration(declaration) && ts.isVariableStatement(declaration.parent.parent) && + !ts.hasModifier(declaration.parent.parent, 1 /* Export */) && // unexported variable statement + isDeclarationVisible(declaration.parent.parent.parent)) { + return addVisibleAlias(declaration, declaration.parent.parent); + } + else if (ts.isLateVisibilityPaintedStatement(declaration) // unexported top-level statement + && !ts.hasModifier(declaration, 1 /* Export */) + && isDeclarationVisible(declaration.parent)) { + return addVisibleAlias(declaration, declaration); + } + // Declaration is not visible + return false; + } + return true; + } + function addVisibleAlias(declaration, aliasingStatement) { + // In function "buildTypeDisplay" where we decide whether to write type-alias or serialize types, + // we want to just check if type- alias is accessible or not but we don't care about emitting those alias at that time + // since we will do the emitting later in trackSymbol. + if (shouldComputeAliasToMakeVisible) { + getNodeLinks(declaration).isVisible = true; + aliasesToMakeVisible = ts.appendIfUnique(aliasesToMakeVisible, aliasingStatement); + } + return true; + } + } + function isEntityNameVisible(entityName, enclosingDeclaration) { + // get symbol of the first identifier of the entityName + var meaning; + if (entityName.parent.kind === 167 /* TypeQuery */ || + ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent) || + entityName.parent.kind === 149 /* ComputedPropertyName */) { + // Typeof value + meaning = 67220415 /* Value */ | 1048576 /* ExportValue */; + } + else if (entityName.kind === 148 /* QualifiedName */ || entityName.kind === 189 /* PropertyAccessExpression */ || + entityName.parent.kind === 248 /* ImportEqualsDeclaration */) { + // Left identifier from type reference or TypeAlias + // Entity name of the import declaration + meaning = 1920 /* Namespace */; + } + else { + // Type Reference or TypeAlias entity = Identifier + meaning = 67897832 /* Type */; + } + var firstIdentifier = getFirstIdentifier(entityName); + var symbol = resolveName(enclosingDeclaration, firstIdentifier.escapedText, meaning, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); + // Verify if the symbol is accessible + return (symbol && hasVisibleDeclarations(symbol, /*shouldComputeAliasToMakeVisible*/ true)) || { + accessibility: 1 /* NotAccessible */, + errorSymbolName: ts.getTextOfNode(firstIdentifier), + errorNode: firstIdentifier + }; + } + function symbolToString(symbol, enclosingDeclaration, meaning, flags, writer) { + if (flags === void 0) { flags = 4 /* AllowAnyNodeKind */; } + var nodeFlags = 70221824 /* IgnoreErrors */; + if (flags & 2 /* UseOnlyExternalAliasing */) { + nodeFlags |= 128 /* UseOnlyExternalAliasing */; + } + if (flags & 1 /* WriteTypeParametersOrArguments */) { + nodeFlags |= 512 /* WriteTypeParametersInQualifiedName */; + } + if (flags & 8 /* UseAliasDefinedOutsideCurrentScope */) { + nodeFlags |= 16384 /* UseAliasDefinedOutsideCurrentScope */; + } + if (flags & 16 /* DoNotIncludeSymbolChain */) { + nodeFlags |= 134217728 /* DoNotIncludeSymbolChain */; + } + var builder = flags & 4 /* AllowAnyNodeKind */ ? nodeBuilder.symbolToExpression : nodeBuilder.symbolToEntityName; + return writer ? symbolToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(symbolToStringWorker); + function symbolToStringWorker(writer) { + var entity = builder(symbol, meaning, enclosingDeclaration, nodeFlags); // TODO: GH#18217 + var printer = ts.createPrinter({ removeComments: true }); + var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); + printer.writeNode(4 /* Unspecified */, entity, /*sourceFile*/ sourceFile, writer); + return writer; + } + } + function signatureToString(signature, enclosingDeclaration, flags, kind, writer) { + if (flags === void 0) { flags = 0 /* None */; } + return writer ? signatureToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(signatureToStringWorker); + function signatureToStringWorker(writer) { + var sigOutput; + if (flags & 262144 /* WriteArrowStyleSignature */) { + sigOutput = kind === 1 /* Construct */ ? 166 /* ConstructorType */ : 165 /* FunctionType */; + } + else { + sigOutput = kind === 1 /* Construct */ ? 161 /* ConstructSignature */ : 160 /* CallSignature */; + } + var sig = nodeBuilder.signatureToSignatureDeclaration(signature, sigOutput, enclosingDeclaration, toNodeBuilderFlags(flags) | 70221824 /* IgnoreErrors */ | 512 /* WriteTypeParametersInQualifiedName */); + var printer = ts.createPrinter({ removeComments: true, omitTrailingSemicolon: true }); + var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); + printer.writeNode(4 /* Unspecified */, sig, /*sourceFile*/ sourceFile, ts.getTrailingSemicolonOmittingWriter(writer)); // TODO: GH#18217 + return writer; + } + } + function typeToString(type, enclosingDeclaration, flags, writer) { + if (flags === void 0) { flags = 1048576 /* AllowUniqueESSymbolType */ | 16384 /* UseAliasDefinedOutsideCurrentScope */; } + if (writer === void 0) { writer = ts.createTextWriter(""); } + var noTruncation = compilerOptions.noErrorTruncation || flags & 1 /* NoTruncation */; + var typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, toNodeBuilderFlags(flags) | 70221824 /* IgnoreErrors */ | (noTruncation ? 1 /* NoTruncation */ : 0), writer); + if (typeNode === undefined) + return ts.Debug.fail("should always get typenode"); + var options = { removeComments: true }; + var printer = ts.createPrinter(options); + var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); + printer.writeNode(4 /* Unspecified */, typeNode, /*sourceFile*/ sourceFile, writer); + var result = writer.getText(); + var maxLength = noTruncation ? undefined : ts.defaultMaximumTruncationLength * 2; + if (maxLength && result && result.length >= maxLength) { + return result.substr(0, maxLength - "...".length) + "..."; + } + return result; + } + function toNodeBuilderFlags(flags) { + if (flags === void 0) { flags = 0 /* None */; } + return flags & 9469291 /* NodeBuilderFlagsMask */; + } + function createNodeBuilder() { + return { + typeToTypeNode: function (type, enclosingDeclaration, flags, tracker) { + return withContext(enclosingDeclaration, flags, tracker, function (context) { return typeToTypeNodeHelper(type, context); }); + }, + indexInfoToIndexSignatureDeclaration: function (indexInfo, kind, enclosingDeclaration, flags, tracker) { + return withContext(enclosingDeclaration, flags, tracker, function (context) { return indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind, context); }); + }, + signatureToSignatureDeclaration: function (signature, kind, enclosingDeclaration, flags, tracker) { + return withContext(enclosingDeclaration, flags, tracker, function (context) { return signatureToSignatureDeclarationHelper(signature, kind, context); }); + }, + symbolToEntityName: function (symbol, meaning, enclosingDeclaration, flags, tracker) { + return withContext(enclosingDeclaration, flags, tracker, function (context) { return symbolToName(symbol, context, meaning, /*expectsIdentifier*/ false); }); + }, + symbolToExpression: function (symbol, meaning, enclosingDeclaration, flags, tracker) { + return withContext(enclosingDeclaration, flags, tracker, function (context) { return symbolToExpression(symbol, context, meaning); }); + }, + symbolToTypeParameterDeclarations: function (symbol, enclosingDeclaration, flags, tracker) { + return withContext(enclosingDeclaration, flags, tracker, function (context) { return typeParametersToTypeParameterDeclarations(symbol, context); }); + }, + symbolToParameterDeclaration: function (symbol, enclosingDeclaration, flags, tracker) { + return withContext(enclosingDeclaration, flags, tracker, function (context) { return symbolToParameterDeclaration(symbol, context); }); + }, + typeParameterToDeclaration: function (parameter, enclosingDeclaration, flags, tracker) { + return withContext(enclosingDeclaration, flags, tracker, function (context) { return typeParameterToDeclaration(parameter, context); }); + }, + }; + function withContext(enclosingDeclaration, flags, tracker, cb) { + ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8 /* Synthesized */) === 0); + var context = { + enclosingDeclaration: enclosingDeclaration, + flags: flags || 0 /* None */, + // If no full tracker is provided, fake up a dummy one with a basic limited-functionality moduleResolverHost + tracker: tracker && tracker.trackSymbol ? tracker : { trackSymbol: ts.noop, moduleResolverHost: flags & 134217728 /* DoNotIncludeSymbolChain */ ? { + getCommonSourceDirectory: host.getCommonSourceDirectory ? function () { return host.getCommonSourceDirectory(); } : function () { return ""; }, + getSourceFiles: function () { return host.getSourceFiles(); }, + getCurrentDirectory: host.getCurrentDirectory && (function () { return host.getCurrentDirectory(); }) + } : undefined }, + encounteredError: false, + visitedTypes: undefined, + symbolDepth: undefined, + inferTypeParameters: undefined, + approximateLength: 0 + }; + var resultingNode = cb(context); + return context.encounteredError ? undefined : resultingNode; + } + function checkTruncationLength(context) { + if (context.truncating) + return context.truncating; + return context.truncating = !(context.flags & 1 /* NoTruncation */) && context.approximateLength > ts.defaultMaximumTruncationLength; + } + function typeToTypeNodeHelper(type, context) { + if (cancellationToken && cancellationToken.throwIfCancellationRequested) { + cancellationToken.throwIfCancellationRequested(); + } + var inTypeAlias = context.flags & 8388608 /* InTypeAlias */; + context.flags &= ~8388608 /* InTypeAlias */; + if (!type) { + context.encounteredError = true; + return undefined; // TODO: GH#18217 + } + if (type.flags & 1 /* Any */) { + context.approximateLength += 3; + return ts.createKeywordTypeNode(120 /* AnyKeyword */); + } + if (type.flags & 2 /* Unknown */) { + return ts.createKeywordTypeNode(143 /* UnknownKeyword */); + } + if (type.flags & 4 /* String */) { + context.approximateLength += 6; + return ts.createKeywordTypeNode(138 /* StringKeyword */); + } + if (type.flags & 8 /* Number */) { + context.approximateLength += 6; + return ts.createKeywordTypeNode(135 /* NumberKeyword */); + } + if (type.flags & 64 /* BigInt */) { + context.approximateLength += 6; + return ts.createKeywordTypeNode(146 /* BigIntKeyword */); + } + if (type.flags & 16 /* Boolean */) { + context.approximateLength += 7; + return ts.createKeywordTypeNode(123 /* BooleanKeyword */); + } + if (type.flags & 1024 /* EnumLiteral */ && !(type.flags & 1048576 /* Union */)) { + var parentSymbol = getParentOfSymbol(type.symbol); + var parentName = symbolToTypeNode(parentSymbol, context, 67897832 /* Type */); + var enumLiteralName = getDeclaredTypeOfSymbol(parentSymbol) === type + ? parentName + : appendReferenceToType(parentName, ts.createTypeReferenceNode(ts.symbolName(type.symbol), /*typeArguments*/ undefined)); + return enumLiteralName; + } + if (type.flags & 1056 /* EnumLike */) { + return symbolToTypeNode(type.symbol, context, 67897832 /* Type */); + } + if (type.flags & 128 /* StringLiteral */) { + context.approximateLength += (type.value.length + 2); + return ts.createLiteralTypeNode(ts.setEmitFlags(ts.createLiteral(type.value), 16777216 /* NoAsciiEscaping */)); + } + if (type.flags & 256 /* NumberLiteral */) { + context.approximateLength += (("" + type.value).length); + return ts.createLiteralTypeNode((ts.createLiteral(type.value))); + } + if (type.flags & 2048 /* BigIntLiteral */) { + context.approximateLength += (ts.pseudoBigIntToString(type.value).length) + 1; + return ts.createLiteralTypeNode((ts.createLiteral(type.value))); + } + if (type.flags & 512 /* BooleanLiteral */) { + context.approximateLength += type.intrinsicName.length; + return type.intrinsicName === "true" ? ts.createTrue() : ts.createFalse(); + } + if (type.flags & 8192 /* UniqueESSymbol */) { + if (!(context.flags & 1048576 /* AllowUniqueESSymbolType */)) { + if (isValueSymbolAccessible(type.symbol, context.enclosingDeclaration)) { + context.approximateLength += 6; + return symbolToTypeNode(type.symbol, context, 67220415 /* Value */); + } + if (context.tracker.reportInaccessibleUniqueSymbolError) { + context.tracker.reportInaccessibleUniqueSymbolError(); + } + } + context.approximateLength += 13; + return ts.createTypeOperatorNode(142 /* UniqueKeyword */, ts.createKeywordTypeNode(139 /* SymbolKeyword */)); + } + if (type.flags & 16384 /* Void */) { + context.approximateLength += 4; + return ts.createKeywordTypeNode(106 /* VoidKeyword */); + } + if (type.flags & 32768 /* Undefined */) { + context.approximateLength += 9; + return ts.createKeywordTypeNode(141 /* UndefinedKeyword */); + } + if (type.flags & 65536 /* Null */) { + context.approximateLength += 4; + return ts.createKeywordTypeNode(96 /* NullKeyword */); + } + if (type.flags & 131072 /* Never */) { + context.approximateLength += 5; + return ts.createKeywordTypeNode(132 /* NeverKeyword */); + } + if (type.flags & 4096 /* ESSymbol */) { + context.approximateLength += 6; + return ts.createKeywordTypeNode(139 /* SymbolKeyword */); + } + if (type.flags & 67108864 /* NonPrimitive */) { + context.approximateLength += 6; + return ts.createKeywordTypeNode(136 /* ObjectKeyword */); + } + if (type.flags & 262144 /* TypeParameter */ && type.isThisType) { + if (context.flags & 4194304 /* InObjectTypeLiteral */) { + if (!context.encounteredError && !(context.flags & 32768 /* AllowThisInObjectLiteral */)) { + context.encounteredError = true; + } + if (context.tracker.reportInaccessibleThisError) { + context.tracker.reportInaccessibleThisError(); + } + } + context.approximateLength += 4; + return ts.createThis(); + } + var objectFlags = ts.getObjectFlags(type); + if (objectFlags & 4 /* Reference */) { + ts.Debug.assert(!!(type.flags & 524288 /* Object */)); + return typeReferenceToTypeNode(type); + } + if (type.flags & 262144 /* TypeParameter */ || objectFlags & 3 /* ClassOrInterface */) { + if (type.flags & 262144 /* TypeParameter */ && ts.contains(context.inferTypeParameters, type)) { + context.approximateLength += (ts.symbolName(type.symbol).length + 6); + return ts.createInferTypeNode(typeParameterToDeclarationWithConstraint(type, context, /*constraintNode*/ undefined)); + } + if (context.flags & 4 /* GenerateNamesForShadowedTypeParams */ && + type.flags & 262144 /* TypeParameter */ && + ts.length(type.symbol.declarations) && + ts.isTypeParameterDeclaration(type.symbol.declarations[0]) && + typeParameterShadowsNameInScope(type, context) && + !isTypeSymbolAccessible(type.symbol, context.enclosingDeclaration)) { + var name = type.symbol.declarations[0].name; + context.approximateLength += ts.idText(name).length; + return ts.createTypeReferenceNode(ts.getGeneratedNameForNode(name, 16 /* Optimistic */ | 8 /* ReservedInNestedScopes */), /*typeArguments*/ undefined); + } + // Ignore constraint/default when creating a usage (as opposed to declaration) of a type parameter. + return type.symbol + ? symbolToTypeNode(type.symbol, context, 67897832 /* Type */) + : ts.createTypeReferenceNode(ts.createIdentifier("?"), /*typeArguments*/ undefined); + } + if (!inTypeAlias && type.aliasSymbol && (context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */ || isTypeSymbolAccessible(type.aliasSymbol, context.enclosingDeclaration))) { + var typeArgumentNodes = mapToTypeNodes(type.aliasTypeArguments, context); + if (isReservedMemberName(type.aliasSymbol.escapedName) && !(type.aliasSymbol.flags & 32 /* Class */)) + return ts.createTypeReferenceNode(ts.createIdentifier(""), typeArgumentNodes); + return symbolToTypeNode(type.aliasSymbol, context, 67897832 /* Type */, typeArgumentNodes); + } + if (type.flags & (1048576 /* Union */ | 2097152 /* Intersection */)) { + var types = type.flags & 1048576 /* Union */ ? formatUnionTypes(type.types) : type.types; + if (ts.length(types) === 1) { + return typeToTypeNodeHelper(types[0], context); + } + var typeNodes = mapToTypeNodes(types, context, /*isBareList*/ true); + if (typeNodes && typeNodes.length > 0) { + var unionOrIntersectionTypeNode = ts.createUnionOrIntersectionTypeNode(type.flags & 1048576 /* Union */ ? 173 /* UnionType */ : 174 /* IntersectionType */, typeNodes); + return unionOrIntersectionTypeNode; + } + else { + if (!context.encounteredError && !(context.flags & 262144 /* AllowEmptyUnionOrIntersection */)) { + context.encounteredError = true; + } + return undefined; // TODO: GH#18217 + } + } + if (objectFlags & (16 /* Anonymous */ | 32 /* Mapped */)) { + ts.Debug.assert(!!(type.flags & 524288 /* Object */)); + // The type is an object literal type. + return createAnonymousTypeNode(type); + } + if (type.flags & 4194304 /* Index */) { + var indexedType = type.type; + context.approximateLength += 6; + var indexTypeNode = typeToTypeNodeHelper(indexedType, context); + return ts.createTypeOperatorNode(indexTypeNode); + } + if (type.flags & 8388608 /* IndexedAccess */) { + var objectTypeNode = typeToTypeNodeHelper(type.objectType, context); + var indexTypeNode = typeToTypeNodeHelper(type.indexType, context); + context.approximateLength += 2; + return ts.createIndexedAccessTypeNode(objectTypeNode, indexTypeNode); + } + if (type.flags & 16777216 /* Conditional */) { + var checkTypeNode = typeToTypeNodeHelper(type.checkType, context); + var saveInferTypeParameters = context.inferTypeParameters; + context.inferTypeParameters = type.root.inferTypeParameters; + var extendsTypeNode = typeToTypeNodeHelper(type.extendsType, context); + context.inferTypeParameters = saveInferTypeParameters; + var trueTypeNode = typeToTypeNodeHelper(getTrueTypeFromConditionalType(type), context); + var falseTypeNode = typeToTypeNodeHelper(getFalseTypeFromConditionalType(type), context); + context.approximateLength += 15; + return ts.createConditionalTypeNode(checkTypeNode, extendsTypeNode, trueTypeNode, falseTypeNode); + } + if (type.flags & 33554432 /* Substitution */) { + return typeToTypeNodeHelper(type.typeVariable, context); + } + return ts.Debug.fail("Should be unreachable."); + function createMappedTypeNodeFromType(type) { + ts.Debug.assert(!!(type.flags & 524288 /* Object */)); + var readonlyToken = type.declaration.readonlyToken ? ts.createToken(type.declaration.readonlyToken.kind) : undefined; + var questionToken = type.declaration.questionToken ? ts.createToken(type.declaration.questionToken.kind) : undefined; + var appropriateConstraintTypeNode; + if (isMappedTypeWithKeyofConstraintDeclaration(type)) { + // We have a { [P in keyof T]: X } + // We do this to ensure we retain the toplevel keyof-ness of the type which may be lost due to keyof distribution during `getConstraintTypeFromMappedType` + appropriateConstraintTypeNode = ts.createTypeOperatorNode(typeToTypeNodeHelper(getModifiersTypeFromMappedType(type), context)); + } + else { + appropriateConstraintTypeNode = typeToTypeNodeHelper(getConstraintTypeFromMappedType(type), context); + } + var typeParameterNode = typeParameterToDeclarationWithConstraint(getTypeParameterFromMappedType(type), context, appropriateConstraintTypeNode); + var templateTypeNode = typeToTypeNodeHelper(getTemplateTypeFromMappedType(type), context); + var mappedTypeNode = ts.createMappedTypeNode(readonlyToken, typeParameterNode, questionToken, templateTypeNode); + context.approximateLength += 10; + return ts.setEmitFlags(mappedTypeNode, 1 /* SingleLine */); + } + function createAnonymousTypeNode(type) { + var typeId = "" + type.id; + var symbol = type.symbol; + var id; + if (symbol) { + var isConstructorObject = ts.getObjectFlags(type) & 16 /* Anonymous */ && type.symbol && type.symbol.flags & 32 /* Class */; + id = (isConstructorObject ? "+" : "") + getSymbolId(symbol); + if (isJSConstructor(symbol.valueDeclaration)) { + // Instance and static types share the same symbol; only add 'typeof' for the static side. + var isInstanceType = type === getInferredClassType(symbol) ? 67897832 /* Type */ : 67220415 /* Value */; + return symbolToTypeNode(symbol, context, isInstanceType); + } + // Always use 'typeof T' for type of class, enum, and module objects + else if (symbol.flags & 32 /* Class */ && !getBaseTypeVariableOfClass(symbol) && !(symbol.valueDeclaration.kind === 209 /* ClassExpression */ && context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */) || + symbol.flags & (384 /* Enum */ | 512 /* ValueModule */) || + shouldWriteTypeOfFunctionSymbol()) { + return symbolToTypeNode(symbol, context, 67220415 /* Value */); + } + else if (context.visitedTypes && context.visitedTypes.has(typeId)) { + // If type is an anonymous type literal in a type alias declaration, use type alias name + var typeAlias = getTypeAliasForTypeLiteral(type); + if (typeAlias) { + // The specified symbol flags need to be reinterpreted as type flags + return symbolToTypeNode(typeAlias, context, 67897832 /* Type */); + } + else { + return createElidedInformationPlaceholder(context); + } + } + else { + // Since instantiations of the same anonymous type have the same symbol, tracking symbols instead + // of types allows us to catch circular references to instantiations of the same anonymous type + if (!context.visitedTypes) { + context.visitedTypes = ts.createMap(); + } + if (!context.symbolDepth) { + context.symbolDepth = ts.createMap(); + } + var depth = context.symbolDepth.get(id) || 0; + if (depth > 10) { + return createElidedInformationPlaceholder(context); + } + context.symbolDepth.set(id, depth + 1); + context.visitedTypes.set(typeId, true); + var result = createTypeNodeFromObjectType(type); + context.visitedTypes.delete(typeId); + context.symbolDepth.set(id, depth); + return result; + } + } + else { + // Anonymous types without a symbol are never circular. + return createTypeNodeFromObjectType(type); + } + function shouldWriteTypeOfFunctionSymbol() { + var isStaticMethodSymbol = !!(symbol.flags & 8192 /* Method */) && // typeof static method + ts.some(symbol.declarations, function (declaration) { return ts.hasModifier(declaration, 32 /* Static */); }); + var isNonLocalFunctionSymbol = !!(symbol.flags & 16 /* Function */) && + (symbol.parent || // is exported function symbol + ts.forEach(symbol.declarations, function (declaration) { + return declaration.parent.kind === 279 /* SourceFile */ || declaration.parent.kind === 245 /* ModuleBlock */; + })); + if (isStaticMethodSymbol || isNonLocalFunctionSymbol) { + // typeof is allowed only for static/non local functions + return (!!(context.flags & 4096 /* UseTypeOfFunction */) || (context.visitedTypes && context.visitedTypes.has(typeId))) && // it is type of the symbol uses itself recursively + (!(context.flags & 8 /* UseStructuralFallback */) || isValueSymbolAccessible(symbol, context.enclosingDeclaration)); // TODO: GH#18217 // And the build is going to succeed without visibility error or there is no structural fallback allowed + } + } + } + function createTypeNodeFromObjectType(type) { + if (isGenericMappedType(type)) { + return createMappedTypeNodeFromType(type); + } + var resolved = resolveStructuredTypeMembers(type); + if (!resolved.properties.length && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { + if (!resolved.callSignatures.length && !resolved.constructSignatures.length) { + context.approximateLength += 2; + return ts.setEmitFlags(ts.createTypeLiteralNode(/*members*/ undefined), 1 /* SingleLine */); + } + if (resolved.callSignatures.length === 1 && !resolved.constructSignatures.length) { + var signature = resolved.callSignatures[0]; + var signatureNode = signatureToSignatureDeclarationHelper(signature, 165 /* FunctionType */, context); + return signatureNode; + } + if (resolved.constructSignatures.length === 1 && !resolved.callSignatures.length) { + var signature = resolved.constructSignatures[0]; + var signatureNode = signatureToSignatureDeclarationHelper(signature, 166 /* ConstructorType */, context); + return signatureNode; + } + } + var savedFlags = context.flags; + context.flags |= 4194304 /* InObjectTypeLiteral */; + var members = createTypeNodesFromResolvedType(resolved); + context.flags = savedFlags; + var typeLiteralNode = ts.createTypeLiteralNode(members); + context.approximateLength += 2; + return ts.setEmitFlags(typeLiteralNode, (context.flags & 1024 /* MultilineObjectLiterals */) ? 0 : 1 /* SingleLine */); + } + function typeReferenceToTypeNode(type) { + var typeArguments = type.typeArguments || ts.emptyArray; + if (type.target === globalArrayType) { + if (context.flags & 2 /* WriteArrayAsGenericType */) { + var typeArgumentNode = typeToTypeNodeHelper(typeArguments[0], context); + return ts.createTypeReferenceNode("Array", [typeArgumentNode]); + } + var elementType = typeToTypeNodeHelper(typeArguments[0], context); + return ts.createArrayTypeNode(elementType); + } + else if (type.target.objectFlags & 8 /* Tuple */) { + if (typeArguments.length > 0) { + var arity = getTypeReferenceArity(type); + var tupleConstituentNodes = mapToTypeNodes(typeArguments.slice(0, arity), context); + var hasRestElement = type.target.hasRestElement; + if (tupleConstituentNodes) { + for (var i = type.target.minLength; i < Math.min(arity, tupleConstituentNodes.length); i++) { + tupleConstituentNodes[i] = hasRestElement && i === arity - 1 ? + ts.createRestTypeNode(ts.createArrayTypeNode(tupleConstituentNodes[i])) : + ts.createOptionalTypeNode(tupleConstituentNodes[i]); + } + return ts.createTupleTypeNode(tupleConstituentNodes); + } + } + if (context.encounteredError || (context.flags & 524288 /* AllowEmptyTuple */)) { + return ts.createTupleTypeNode([]); + } + context.encounteredError = true; + return undefined; // TODO: GH#18217 + } + else if (context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */ && + type.symbol.valueDeclaration && + ts.isClassLike(type.symbol.valueDeclaration) && + !isValueSymbolAccessible(type.symbol, context.enclosingDeclaration)) { + return createAnonymousTypeNode(type); + } + else { + var outerTypeParameters = type.target.outerTypeParameters; + var i = 0; + var resultType = void 0; + if (outerTypeParameters) { + var length_1 = outerTypeParameters.length; + while (i < length_1) { + // Find group of type arguments for type parameters with the same declaring container. + var start = i; + var parent = getParentSymbolOfTypeParameter(outerTypeParameters[i]); + do { + i++; + } while (i < length_1 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent); + // When type parameters are their own type arguments for the whole group (i.e. we have + // the default outer type arguments), we don't show the group. + if (!ts.rangeEquals(outerTypeParameters, typeArguments, start, i)) { + var typeArgumentSlice = mapToTypeNodes(typeArguments.slice(start, i), context); + var flags_2 = context.flags; + context.flags |= 16 /* ForbidIndexedAccessSymbolReferences */; + var ref = symbolToTypeNode(parent, context, 67897832 /* Type */, typeArgumentSlice); + context.flags = flags_2; + resultType = !resultType ? ref : appendReferenceToType(resultType, ref); + } + } + } + var typeArgumentNodes = void 0; + if (typeArguments.length > 0) { + var typeParameterCount = (type.target.typeParameters || ts.emptyArray).length; + typeArgumentNodes = mapToTypeNodes(typeArguments.slice(i, typeParameterCount), context); + } + var flags = context.flags; + context.flags |= 16 /* ForbidIndexedAccessSymbolReferences */; + var finalRef = symbolToTypeNode(type.symbol, context, 67897832 /* Type */, typeArgumentNodes); + context.flags = flags; + return !resultType ? finalRef : appendReferenceToType(resultType, finalRef); + } + } + function appendReferenceToType(root, ref) { + if (ts.isImportTypeNode(root)) { + // first shift type arguments + var innerParams = root.typeArguments; + if (root.qualifier) { + (ts.isIdentifier(root.qualifier) ? root.qualifier : root.qualifier.right).typeArguments = innerParams; + } + root.typeArguments = ref.typeArguments; + // then move qualifiers + var ids = getAccessStack(ref); + for (var _i = 0, ids_1 = ids; _i < ids_1.length; _i++) { + var id = ids_1[_i]; + root.qualifier = root.qualifier ? ts.createQualifiedName(root.qualifier, id) : id; + } + return root; + } + else { + // first shift type arguments + var innerParams = root.typeArguments; + (ts.isIdentifier(root.typeName) ? root.typeName : root.typeName.right).typeArguments = innerParams; + root.typeArguments = ref.typeArguments; + // then move qualifiers + var ids = getAccessStack(ref); + for (var _a = 0, ids_2 = ids; _a < ids_2.length; _a++) { + var id = ids_2[_a]; + root.typeName = ts.createQualifiedName(root.typeName, id); + } + return root; + } + } + function getAccessStack(ref) { + var state = ref.typeName; + var ids = []; + while (!ts.isIdentifier(state)) { + ids.unshift(state.right); + state = state.left; + } + ids.unshift(state); + return ids; + } + function createTypeNodesFromResolvedType(resolvedType) { + if (checkTruncationLength(context)) { + return [ts.createPropertySignature(/*modifiers*/ undefined, "...", /*questionToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined)]; + } + var typeElements = []; + for (var _i = 0, _a = resolvedType.callSignatures; _i < _a.length; _i++) { + var signature = _a[_i]; + typeElements.push(signatureToSignatureDeclarationHelper(signature, 160 /* CallSignature */, context)); + } + for (var _b = 0, _c = resolvedType.constructSignatures; _b < _c.length; _b++) { + var signature = _c[_b]; + typeElements.push(signatureToSignatureDeclarationHelper(signature, 161 /* ConstructSignature */, context)); + } + if (resolvedType.stringIndexInfo) { + var indexSignature = void 0; + if (resolvedType.objectFlags & 2048 /* ReverseMapped */) { + indexSignature = indexInfoToIndexSignatureDeclarationHelper(createIndexInfo(anyType, resolvedType.stringIndexInfo.isReadonly, resolvedType.stringIndexInfo.declaration), 0 /* String */, context); + indexSignature.type = createElidedInformationPlaceholder(context); + } + else { + indexSignature = indexInfoToIndexSignatureDeclarationHelper(resolvedType.stringIndexInfo, 0 /* String */, context); + } + typeElements.push(indexSignature); + } + if (resolvedType.numberIndexInfo) { + typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.numberIndexInfo, 1 /* Number */, context)); + } + var properties = resolvedType.properties; + if (!properties) { + return typeElements; + } + var i = 0; + for (var _d = 0, properties_1 = properties; _d < properties_1.length; _d++) { + var propertySymbol = properties_1[_d]; + i++; + if (context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */) { + if (propertySymbol.flags & 4194304 /* Prototype */) { + continue; + } + if (ts.getDeclarationModifierFlagsFromSymbol(propertySymbol) & (8 /* Private */ | 16 /* Protected */) && context.tracker.reportPrivateInBaseOfClassExpression) { + context.tracker.reportPrivateInBaseOfClassExpression(ts.unescapeLeadingUnderscores(propertySymbol.escapedName)); + } + } + if (checkTruncationLength(context) && (i + 2 < properties.length - 1)) { + typeElements.push(ts.createPropertySignature(/*modifiers*/ undefined, "... " + (properties.length - i) + " more ...", /*questionToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined)); + addPropertyToElementList(properties[properties.length - 1], context, typeElements); + break; + } + addPropertyToElementList(propertySymbol, context, typeElements); + } + return typeElements.length ? typeElements : undefined; + } + } + function createElidedInformationPlaceholder(context) { + context.approximateLength += 3; + if (!(context.flags & 1 /* NoTruncation */)) { + return ts.createTypeReferenceNode(ts.createIdentifier("..."), /*typeArguments*/ undefined); + } + return ts.createKeywordTypeNode(120 /* AnyKeyword */); + } + function addPropertyToElementList(propertySymbol, context, typeElements) { + var propertyIsReverseMapped = !!(ts.getCheckFlags(propertySymbol) & 2048 /* ReverseMapped */); + var propertyType = propertyIsReverseMapped && context.flags & 33554432 /* InReverseMappedType */ ? + anyType : getTypeOfSymbol(propertySymbol); + var saveEnclosingDeclaration = context.enclosingDeclaration; + context.enclosingDeclaration = undefined; + if (context.tracker.trackSymbol && ts.getCheckFlags(propertySymbol) & 1024 /* Late */) { + var decl = ts.first(propertySymbol.declarations); + if (hasLateBindableName(decl)) { + trackComputedName(decl.name, saveEnclosingDeclaration, context); + } + } + var propertyName = symbolToName(propertySymbol, context, 67220415 /* Value */, /*expectsIdentifier*/ true); + context.approximateLength += (ts.symbolName(propertySymbol).length + 1); + context.enclosingDeclaration = saveEnclosingDeclaration; + var optionalToken = propertySymbol.flags & 16777216 /* Optional */ ? ts.createToken(56 /* QuestionToken */) : undefined; + if (propertySymbol.flags & (16 /* Function */ | 8192 /* Method */) && !getPropertiesOfObjectType(propertyType).length) { + var signatures = getSignaturesOfType(propertyType, 0 /* Call */); + for (var _i = 0, signatures_1 = signatures; _i < signatures_1.length; _i++) { + var signature = signatures_1[_i]; + var methodDeclaration = signatureToSignatureDeclarationHelper(signature, 155 /* MethodSignature */, context); + methodDeclaration.name = propertyName; + methodDeclaration.questionToken = optionalToken; + if (propertySymbol.valueDeclaration) { + // Copy comments to node for declaration emit + ts.setCommentRange(methodDeclaration, propertySymbol.valueDeclaration); + } + typeElements.push(methodDeclaration); + } + } + else { + var savedFlags = context.flags; + context.flags |= propertyIsReverseMapped ? 33554432 /* InReverseMappedType */ : 0; + var propertyTypeNode = void 0; + if (propertyIsReverseMapped && !!(savedFlags & 33554432 /* InReverseMappedType */)) { + propertyTypeNode = createElidedInformationPlaceholder(context); + } + else { + propertyTypeNode = propertyType ? typeToTypeNodeHelper(propertyType, context) : ts.createKeywordTypeNode(120 /* AnyKeyword */); + } + context.flags = savedFlags; + var modifiers = isReadonlySymbol(propertySymbol) ? [ts.createToken(133 /* ReadonlyKeyword */)] : undefined; + if (modifiers) { + context.approximateLength += 9; + } + var propertySignature = ts.createPropertySignature(modifiers, propertyName, optionalToken, propertyTypeNode, + /*initializer*/ undefined); + if (propertySymbol.valueDeclaration) { + // Copy comments to node for declaration emit + ts.setCommentRange(propertySignature, propertySymbol.valueDeclaration); + } + typeElements.push(propertySignature); + } + } + function mapToTypeNodes(types, context, isBareList) { + if (ts.some(types)) { + if (checkTruncationLength(context)) { + if (!isBareList) { + return [ts.createTypeReferenceNode("...", /*typeArguments*/ undefined)]; + } + else if (types.length > 2) { + return [ + typeToTypeNodeHelper(types[0], context), + ts.createTypeReferenceNode("... " + (types.length - 2) + " more ...", /*typeArguments*/ undefined), + typeToTypeNodeHelper(types[types.length - 1], context) + ]; + } + } + var result = []; + var i = 0; + for (var _i = 0, types_1 = types; _i < types_1.length; _i++) { + var type = types_1[_i]; + i++; + if (checkTruncationLength(context) && (i + 2 < types.length - 1)) { + result.push(ts.createTypeReferenceNode("... " + (types.length - i) + " more ...", /*typeArguments*/ undefined)); + var typeNode_1 = typeToTypeNodeHelper(types[types.length - 1], context); + if (typeNode_1) { + result.push(typeNode_1); + } + break; + } + context.approximateLength += 2; // Account for whitespace + separator + var typeNode = typeToTypeNodeHelper(type, context); + if (typeNode) { + result.push(typeNode); + } + } + return result; + } + } + function indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind, context) { + var name = ts.getNameFromIndexInfo(indexInfo) || "x"; + var indexerTypeNode = ts.createKeywordTypeNode(kind === 0 /* String */ ? 138 /* StringKeyword */ : 135 /* NumberKeyword */); + var indexingParameter = ts.createParameter( + /*decorators*/ undefined, + /*modifiers*/ undefined, + /*dotDotDotToken*/ undefined, name, + /*questionToken*/ undefined, indexerTypeNode, + /*initializer*/ undefined); + var typeNode = typeToTypeNodeHelper(indexInfo.type || anyType, context); + if (!indexInfo.type && !(context.flags & 2097152 /* AllowEmptyIndexInfoType */)) { + context.encounteredError = true; + } + context.approximateLength += (name.length + 4); + return ts.createIndexSignature( + /*decorators*/ undefined, indexInfo.isReadonly ? [ts.createToken(133 /* ReadonlyKeyword */)] : undefined, [indexingParameter], typeNode); + } + function signatureToSignatureDeclarationHelper(signature, kind, context) { + var typeParameters; + var typeArguments; + if (context.flags & 32 /* WriteTypeArgumentsOfSignature */ && signature.target && signature.mapper && signature.target.typeParameters) { + typeArguments = signature.target.typeParameters.map(function (parameter) { return typeToTypeNodeHelper(instantiateType(parameter, signature.mapper), context); }); + } + else { + typeParameters = signature.typeParameters && signature.typeParameters.map(function (parameter) { return typeParameterToDeclaration(parameter, context); }); + } + var parameters = getExpandedParameters(signature).map(function (parameter) { return symbolToParameterDeclaration(parameter, context, kind === 157 /* Constructor */); }); + if (signature.thisParameter) { + var thisParameter = symbolToParameterDeclaration(signature.thisParameter, context); + parameters.unshift(thisParameter); + } + var returnTypeNode; + var typePredicate = getTypePredicateOfSignature(signature); + if (typePredicate) { + var parameterName = typePredicate.kind === 1 /* Identifier */ ? + ts.setEmitFlags(ts.createIdentifier(typePredicate.parameterName), 16777216 /* NoAsciiEscaping */) : + ts.createThisTypeNode(); + var typeNode = typeToTypeNodeHelper(typePredicate.type, context); + returnTypeNode = ts.createTypePredicateNode(parameterName, typeNode); + } + else { + var returnType = getReturnTypeOfSignature(signature); + returnTypeNode = returnType && typeToTypeNodeHelper(returnType, context); + } + if (context.flags & 256 /* SuppressAnyReturnType */) { + if (returnTypeNode && returnTypeNode.kind === 120 /* AnyKeyword */) { + returnTypeNode = undefined; + } + } + else if (!returnTypeNode) { + returnTypeNode = ts.createKeywordTypeNode(120 /* AnyKeyword */); + } + context.approximateLength += 3; // Usually a signature contributes a few more characters than this, but 3 is the minimum + return ts.createSignatureDeclaration(kind, typeParameters, parameters, returnTypeNode, typeArguments); + } + function typeParameterShadowsNameInScope(type, context) { + return !!resolveName(context.enclosingDeclaration, type.symbol.escapedName, 67897832 /* Type */, /*nameNotFoundArg*/ undefined, type.symbol.escapedName, /*isUse*/ false); + } + function typeParameterToDeclarationWithConstraint(type, context, constraintNode) { + var savedContextFlags = context.flags; + context.flags &= ~512 /* WriteTypeParametersInQualifiedName */; // Avoids potential infinite loop when building for a claimspace with a generic + var shouldUseGeneratedName = context.flags & 4 /* GenerateNamesForShadowedTypeParams */ && + type.symbol.declarations[0] && + ts.isTypeParameterDeclaration(type.symbol.declarations[0]) && + typeParameterShadowsNameInScope(type, context); + var name = shouldUseGeneratedName + ? ts.getGeneratedNameForNode(type.symbol.declarations[0].name, 16 /* Optimistic */ | 8 /* ReservedInNestedScopes */) + : symbolToName(type.symbol, context, 67897832 /* Type */, /*expectsIdentifier*/ true); + var defaultParameter = getDefaultFromTypeParameter(type); + var defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter, context); + context.flags = savedContextFlags; + return ts.createTypeParameterDeclaration(name, constraintNode, defaultParameterNode); + } + function typeParameterToDeclaration(type, context, constraint) { + if (constraint === void 0) { constraint = getConstraintOfTypeParameter(type); } + var constraintNode = constraint && typeToTypeNodeHelper(constraint, context); + return typeParameterToDeclarationWithConstraint(type, context, constraintNode); + } + function symbolToParameterDeclaration(parameterSymbol, context, preserveModifierFlags) { + var parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 151 /* Parameter */); + if (!parameterDeclaration && !isTransientSymbol(parameterSymbol)) { + parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 299 /* JSDocParameterTag */); + } + var parameterType = getTypeOfSymbol(parameterSymbol); + if (parameterDeclaration && isRequiredInitializedParameter(parameterDeclaration)) { + parameterType = getOptionalType(parameterType); + } + var parameterTypeNode = typeToTypeNodeHelper(parameterType, context); + var modifiers = !(context.flags & 8192 /* OmitParameterModifiers */) && preserveModifierFlags && parameterDeclaration && parameterDeclaration.modifiers ? parameterDeclaration.modifiers.map(ts.getSynthesizedClone) : undefined; + var isRest = parameterDeclaration && ts.isRestParameter(parameterDeclaration) || ts.getCheckFlags(parameterSymbol) & 8192 /* RestParameter */; + var dotDotDotToken = isRest ? ts.createToken(25 /* DotDotDotToken */) : undefined; + var name = parameterDeclaration + ? parameterDeclaration.name ? + parameterDeclaration.name.kind === 72 /* Identifier */ ? ts.setEmitFlags(ts.getSynthesizedClone(parameterDeclaration.name), 16777216 /* NoAsciiEscaping */) : + parameterDeclaration.name.kind === 148 /* QualifiedName */ ? ts.setEmitFlags(ts.getSynthesizedClone(parameterDeclaration.name.right), 16777216 /* NoAsciiEscaping */) : + cloneBindingName(parameterDeclaration.name) : + ts.symbolName(parameterSymbol) + : ts.symbolName(parameterSymbol); + var isOptional = parameterDeclaration && isOptionalParameter(parameterDeclaration) || ts.getCheckFlags(parameterSymbol) & 4096 /* OptionalParameter */; + var questionToken = isOptional ? ts.createToken(56 /* QuestionToken */) : undefined; + var parameterNode = ts.createParameter( + /*decorators*/ undefined, modifiers, dotDotDotToken, name, questionToken, parameterTypeNode, + /*initializer*/ undefined); + context.approximateLength += ts.symbolName(parameterSymbol).length + 3; + return parameterNode; + function cloneBindingName(node) { + return elideInitializerAndSetEmitFlags(node); + function elideInitializerAndSetEmitFlags(node) { + if (context.tracker.trackSymbol && ts.isComputedPropertyName(node) && isLateBindableName(node)) { + trackComputedName(node, context.enclosingDeclaration, context); + } + var visited = ts.visitEachChild(node, elideInitializerAndSetEmitFlags, ts.nullTransformationContext, /*nodesVisitor*/ undefined, elideInitializerAndSetEmitFlags); + var clone = ts.nodeIsSynthesized(visited) ? visited : ts.getSynthesizedClone(visited); + if (clone.kind === 186 /* BindingElement */) { + clone.initializer = undefined; + } + return ts.setEmitFlags(clone, 1 /* SingleLine */ | 16777216 /* NoAsciiEscaping */); + } + } + } + function trackComputedName(node, enclosingDeclaration, context) { + if (!context.tracker.trackSymbol) + return; + // get symbol of the first identifier of the entityName + var firstIdentifier = getFirstIdentifier(node.expression); + var name = resolveName(firstIdentifier, firstIdentifier.escapedText, 67220415 /* Value */ | 1048576 /* ExportValue */, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); + if (name) { + context.tracker.trackSymbol(name, enclosingDeclaration, 67220415 /* Value */); + } + } + function lookupSymbolChain(symbol, context, meaning, yieldModuleSymbol) { + context.tracker.trackSymbol(symbol, context.enclosingDeclaration, meaning); // TODO: GH#18217 + // Try to get qualified name if the symbol is not a type parameter and there is an enclosing declaration. + var chain; + var isTypeParameter = symbol.flags & 262144 /* TypeParameter */; + if (!isTypeParameter && (context.enclosingDeclaration || context.flags & 64 /* UseFullyQualifiedType */) && !(context.flags & 134217728 /* DoNotIncludeSymbolChain */)) { + chain = ts.Debug.assertDefined(getSymbolChain(symbol, meaning, /*endOfChain*/ true)); + ts.Debug.assert(chain && chain.length > 0); + } + else { + chain = [symbol]; + } + return chain; + /** @param endOfChain Set to false for recursive calls; non-recursive calls should always output something. */ + function getSymbolChain(symbol, meaning, endOfChain) { + var accessibleSymbolChain = getAccessibleSymbolChain(symbol, context.enclosingDeclaration, meaning, !!(context.flags & 128 /* UseOnlyExternalAliasing */)); + var parentSpecifiers; + if (!accessibleSymbolChain || + needsQualification(accessibleSymbolChain[0], context.enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) { + // Go up and add our parent. + var parents_1 = getContainersOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol, context.enclosingDeclaration); + if (ts.length(parents_1)) { + parentSpecifiers = parents_1.map(function (symbol) { + return ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol) + ? getSpecifierForModuleSymbol(symbol, context) + : undefined; + }); + var indices = parents_1.map(function (_, i) { return i; }); + indices.sort(sortByBestName); + var sortedParents = indices.map(function (i) { return parents_1[i]; }); + for (var _i = 0, sortedParents_1 = sortedParents; _i < sortedParents_1.length; _i++) { + var parent = sortedParents_1[_i]; + var parentChain = getSymbolChain(parent, getQualifiedLeftMeaning(meaning), /*endOfChain*/ false); + if (parentChain) { + accessibleSymbolChain = parentChain.concat(accessibleSymbolChain || [getAliasForSymbolInContainer(parent, symbol) || symbol]); + break; + } + } + } + } + if (accessibleSymbolChain) { + return accessibleSymbolChain; + } + if ( + // If this is the last part of outputting the symbol, always output. The cases apply only to parent symbols. + endOfChain || + // If a parent symbol is an anonymous type, don't write it. + !(symbol.flags & (2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */))) { + // If a parent symbol is an external module, don't write it. (We prefer just `x` vs `"foo/bar".x`.) + if (!endOfChain && !yieldModuleSymbol && !!ts.forEach(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { + return; + } + return [symbol]; + } + function sortByBestName(a, b) { + var specifierA = parentSpecifiers[a]; + var specifierB = parentSpecifiers[b]; + if (specifierA && specifierB) { + var isBRelative = ts.pathIsRelative(specifierB); + if (ts.pathIsRelative(specifierA) === isBRelative) { + // Both relative or both non-relative, sort by number of parts + return ts.moduleSpecifiers.countPathComponents(specifierA) - ts.moduleSpecifiers.countPathComponents(specifierB); + } + if (isBRelative) { + // A is non-relative, B is relative: prefer A + return -1; + } + // A is relative, B is non-relative: prefer B + return 1; + } + return 0; + } + } + } + function typeParametersToTypeParameterDeclarations(symbol, context) { + var typeParameterNodes; + var targetSymbol = getTargetSymbol(symbol); + if (targetSymbol.flags & (32 /* Class */ | 64 /* Interface */ | 524288 /* TypeAlias */)) { + typeParameterNodes = ts.createNodeArray(ts.map(getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol), function (tp) { return typeParameterToDeclaration(tp, context); })); + } + return typeParameterNodes; + } + function lookupTypeParameterNodes(chain, index, context) { + ts.Debug.assert(chain && 0 <= index && index < chain.length); + var symbol = chain[index]; + var typeParameterNodes; + if (context.flags & 512 /* WriteTypeParametersInQualifiedName */ && index < (chain.length - 1)) { + var parentSymbol = symbol; + var nextSymbol = chain[index + 1]; + if (ts.getCheckFlags(nextSymbol) & 1 /* Instantiated */) { + var params = getTypeParametersOfClassOrInterface(parentSymbol.flags & 2097152 /* Alias */ ? resolveAlias(parentSymbol) : parentSymbol); + typeParameterNodes = mapToTypeNodes(ts.map(params, nextSymbol.mapper), context); + } + else { + typeParameterNodes = typeParametersToTypeParameterDeclarations(symbol, context); + } + } + return typeParameterNodes; + } + /** + * Given A[B][C][D], finds A[B] + */ + function getTopmostIndexedAccessType(top) { + if (ts.isIndexedAccessTypeNode(top.objectType)) { + return getTopmostIndexedAccessType(top.objectType); + } + return top; + } + function getSpecifierForModuleSymbol(symbol, context) { + var file = ts.getDeclarationOfKind(symbol, 279 /* SourceFile */); + if (file && file.moduleName !== undefined) { + // Use the amd name if it is available + return file.moduleName; + } + if (!file) { + if (context.tracker.trackReferencedAmbientModule) { + var ambientDecls = ts.filter(symbol.declarations, ts.isAmbientModule); + if (ts.length(ambientDecls)) { + for (var _i = 0, ambientDecls_1 = ambientDecls; _i < ambientDecls_1.length; _i++) { + var decl = ambientDecls_1[_i]; + context.tracker.trackReferencedAmbientModule(decl, symbol); + } + } + } + if (ambientModuleSymbolRegex.test(symbol.escapedName)) { + return symbol.escapedName.substring(1, symbol.escapedName.length - 1); + } + } + if (!context.enclosingDeclaration || !context.tracker.moduleResolverHost) { + // If there's no context declaration, we can't lookup a non-ambient specifier, so we just use the symbol name + if (ambientModuleSymbolRegex.test(symbol.escapedName)) { + return symbol.escapedName.substring(1, symbol.escapedName.length - 1); + } + return ts.getSourceFileOfNode(ts.getNonAugmentationDeclaration(symbol)).fileName; // A resolver may not be provided for baselines and errors - in those cases we use the fileName in full + } + var contextFile = ts.getSourceFileOfNode(ts.getOriginalNode(context.enclosingDeclaration)); + var links = getSymbolLinks(symbol); + var specifier = links.specifierCache && links.specifierCache.get(contextFile.path); + if (!specifier) { + var isBundle_1 = (compilerOptions.out || compilerOptions.outFile); + // For declaration bundles, we need to generate absolute paths relative to the common source dir for imports, + // just like how the declaration emitter does for the ambient module declarations - we can easily accomplish this + // using the `baseUrl` compiler option (which we would otherwise never use in declaration emit) and a non-relative + // specifier preference + var moduleResolverHost = context.tracker.moduleResolverHost; + var specifierCompilerOptions = isBundle_1 ? __assign({}, compilerOptions, { baseUrl: moduleResolverHost.getCommonSourceDirectory() }) : compilerOptions; + specifier = ts.first(ts.moduleSpecifiers.getModuleSpecifiers(symbol, specifierCompilerOptions, contextFile, moduleResolverHost, host.getSourceFiles(), { importModuleSpecifierPreference: isBundle_1 ? "non-relative" : "relative" }, host.redirectTargetsMap)); + links.specifierCache = links.specifierCache || ts.createMap(); + links.specifierCache.set(contextFile.path, specifier); + } + return specifier; + } + function symbolToTypeNode(symbol, context, meaning, overrideTypeArguments) { + var chain = lookupSymbolChain(symbol, context, meaning, !(context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */)); // If we're using aliases outside the current scope, dont bother with the module + var isTypeOf = meaning === 67220415 /* Value */; + if (ts.some(chain[0].declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { + // module is root, must use `ImportTypeNode` + var nonRootParts = chain.length > 1 ? createAccessFromSymbolChain(chain, chain.length - 1, 1) : undefined; + var typeParameterNodes = overrideTypeArguments || lookupTypeParameterNodes(chain, 0, context); + var specifier = getSpecifierForModuleSymbol(chain[0], context); + if (!(context.flags & 67108864 /* AllowNodeModulesRelativePaths */) && ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs && specifier.indexOf("/node_modules/") >= 0) { + // If ultimately we can only name the symbol with a reference that dives into a `node_modules` folder, we should error + // since declaration files with these kinds of references are liable to fail when published :( + context.encounteredError = true; + if (context.tracker.reportLikelyUnsafeImportRequiredError) { + context.tracker.reportLikelyUnsafeImportRequiredError(specifier); + } + } + var lit = ts.createLiteralTypeNode(ts.createLiteral(specifier)); + if (context.tracker.trackExternalModuleSymbolOfImportTypeNode) + context.tracker.trackExternalModuleSymbolOfImportTypeNode(chain[0]); + context.approximateLength += specifier.length + 10; // specifier + import("") + if (!nonRootParts || ts.isEntityName(nonRootParts)) { + if (nonRootParts) { + var lastId = ts.isIdentifier(nonRootParts) ? nonRootParts : nonRootParts.right; + lastId.typeArguments = undefined; + } + return ts.createImportTypeNode(lit, nonRootParts, typeParameterNodes, isTypeOf); + } + else { + var splitNode = getTopmostIndexedAccessType(nonRootParts); + var qualifier = splitNode.objectType.typeName; + return ts.createIndexedAccessTypeNode(ts.createImportTypeNode(lit, qualifier, typeParameterNodes, isTypeOf), splitNode.indexType); + } + } + var entityName = createAccessFromSymbolChain(chain, chain.length - 1, 0); + if (ts.isIndexedAccessTypeNode(entityName)) { + return entityName; // Indexed accesses can never be `typeof` + } + if (isTypeOf) { + return ts.createTypeQueryNode(entityName); + } + else { + var lastId = ts.isIdentifier(entityName) ? entityName : entityName.right; + var lastTypeArgs = lastId.typeArguments; + lastId.typeArguments = undefined; + return ts.createTypeReferenceNode(entityName, lastTypeArgs); + } + function createAccessFromSymbolChain(chain, index, stopper) { + var typeParameterNodes = index === (chain.length - 1) ? overrideTypeArguments : lookupTypeParameterNodes(chain, index, context); + var symbol = chain[index]; + if (index === 0) { + context.flags |= 16777216 /* InInitialEntityName */; + } + var symbolName = getNameOfSymbolAsWritten(symbol, context); + context.approximateLength += symbolName.length + 1; + if (index === 0) { + context.flags ^= 16777216 /* InInitialEntityName */; + } + var parent = chain[index - 1]; + if (!(context.flags & 16 /* ForbidIndexedAccessSymbolReferences */) && parent && getMembersOfSymbol(parent) && getMembersOfSymbol(parent).get(symbol.escapedName) === symbol) { + // Should use an indexed access + var LHS = createAccessFromSymbolChain(chain, index - 1, stopper); + if (ts.isIndexedAccessTypeNode(LHS)) { + return ts.createIndexedAccessTypeNode(LHS, ts.createLiteralTypeNode(ts.createLiteral(symbolName))); + } + else { + return ts.createIndexedAccessTypeNode(ts.createTypeReferenceNode(LHS, typeParameterNodes), ts.createLiteralTypeNode(ts.createLiteral(symbolName))); + } + } + var identifier = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216 /* NoAsciiEscaping */); + identifier.symbol = symbol; + if (index > stopper) { + var LHS = createAccessFromSymbolChain(chain, index - 1, stopper); + if (!ts.isEntityName(LHS)) { + return ts.Debug.fail("Impossible construct - an export of an indexed access cannot be reachable"); + } + return ts.createQualifiedName(LHS, identifier); + } + return identifier; + } + } + function symbolToName(symbol, context, meaning, expectsIdentifier) { + var chain = lookupSymbolChain(symbol, context, meaning); + if (expectsIdentifier && chain.length !== 1 + && !context.encounteredError + && !(context.flags & 65536 /* AllowQualifedNameInPlaceOfIdentifier */)) { + context.encounteredError = true; + } + return createEntityNameFromSymbolChain(chain, chain.length - 1); + function createEntityNameFromSymbolChain(chain, index) { + var typeParameterNodes = lookupTypeParameterNodes(chain, index, context); + var symbol = chain[index]; + if (index === 0) { + context.flags |= 16777216 /* InInitialEntityName */; + } + var symbolName = getNameOfSymbolAsWritten(symbol, context); + if (index === 0) { + context.flags ^= 16777216 /* InInitialEntityName */; + } + var identifier = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216 /* NoAsciiEscaping */); + identifier.symbol = symbol; + return index > 0 ? ts.createQualifiedName(createEntityNameFromSymbolChain(chain, index - 1), identifier) : identifier; + } + } + function symbolToExpression(symbol, context, meaning) { + var chain = lookupSymbolChain(symbol, context, meaning); + return createExpressionFromSymbolChain(chain, chain.length - 1); + function createExpressionFromSymbolChain(chain, index) { + var typeParameterNodes = lookupTypeParameterNodes(chain, index, context); + var symbol = chain[index]; + if (ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { + return ts.createLiteral(getSpecifierForModuleSymbol(symbol, context)); + } + if (index === 0) { + context.flags |= 16777216 /* InInitialEntityName */; + } + var symbolName = getNameOfSymbolAsWritten(symbol, context); + if (index === 0) { + context.flags ^= 16777216 /* InInitialEntityName */; + } + var firstChar = symbolName.charCodeAt(0); + var canUsePropertyAccess = ts.isIdentifierStart(firstChar, languageVersion); + if (index === 0 || canUsePropertyAccess) { + var identifier = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216 /* NoAsciiEscaping */); + identifier.symbol = symbol; + return index > 0 ? ts.createPropertyAccess(createExpressionFromSymbolChain(chain, index - 1), identifier) : identifier; + } + else { + if (firstChar === 91 /* openBracket */) { + symbolName = symbolName.substring(1, symbolName.length - 1); + firstChar = symbolName.charCodeAt(0); + } + var expression = void 0; + if (ts.isSingleOrDoubleQuote(firstChar)) { + expression = ts.createLiteral(symbolName.substring(1, symbolName.length - 1).replace(/\\./g, function (s) { return s.substring(1); })); + expression.singleQuote = firstChar === 39 /* singleQuote */; + } + else if (("" + +symbolName) === symbolName) { + expression = ts.createLiteral(+symbolName); + } + if (!expression) { + expression = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216 /* NoAsciiEscaping */); + expression.symbol = symbol; + } + return ts.createElementAccess(createExpressionFromSymbolChain(chain, index - 1), expression); + } + } + } + } + function typePredicateToString(typePredicate, enclosingDeclaration, flags, writer) { + if (flags === void 0) { flags = 16384 /* UseAliasDefinedOutsideCurrentScope */; } + return writer ? typePredicateToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(typePredicateToStringWorker); + function typePredicateToStringWorker(writer) { + var predicate = ts.createTypePredicateNode(typePredicate.kind === 1 /* Identifier */ ? ts.createIdentifier(typePredicate.parameterName) : ts.createThisTypeNode(), nodeBuilder.typeToTypeNode(typePredicate.type, enclosingDeclaration, toNodeBuilderFlags(flags) | 70221824 /* IgnoreErrors */ | 512 /* WriteTypeParametersInQualifiedName */)); + var printer = ts.createPrinter({ removeComments: true }); + var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); + printer.writeNode(4 /* Unspecified */, predicate, /*sourceFile*/ sourceFile, writer); + return writer; + } + } + function formatUnionTypes(types) { + var result = []; + var flags = 0; + for (var i = 0; i < types.length; i++) { + var t = types[i]; + flags |= t.flags; + if (!(t.flags & 98304 /* Nullable */)) { + if (t.flags & (512 /* BooleanLiteral */ | 1024 /* EnumLiteral */)) { + var baseType = t.flags & 512 /* BooleanLiteral */ ? booleanType : getBaseTypeOfEnumLiteralType(t); + if (baseType.flags & 1048576 /* Union */) { + var count = baseType.types.length; + if (i + count <= types.length && getRegularTypeOfLiteralType(types[i + count - 1]) === getRegularTypeOfLiteralType(baseType.types[count - 1])) { + result.push(baseType); + i += count - 1; + continue; + } + } + } + result.push(t); + } + } + if (flags & 65536 /* Null */) + result.push(nullType); + if (flags & 32768 /* Undefined */) + result.push(undefinedType); + return result || types; + } + function visibilityToString(flags) { + if (flags === 8 /* Private */) { + return "private"; + } + if (flags === 16 /* Protected */) { + return "protected"; + } + return "public"; + } + function getTypeAliasForTypeLiteral(type) { + if (type.symbol && type.symbol.flags & 2048 /* TypeLiteral */) { + var node = ts.findAncestor(type.symbol.declarations[0].parent, function (n) { return n.kind !== 177 /* ParenthesizedType */; }); + if (node.kind === 242 /* TypeAliasDeclaration */) { + return getSymbolOfNode(node); + } + } + return undefined; + } + function isTopLevelInExternalModuleAugmentation(node) { + return node && node.parent && + node.parent.kind === 245 /* ModuleBlock */ && + ts.isExternalModuleAugmentation(node.parent.parent); + } + function isDefaultBindingContext(location) { + return location.kind === 279 /* SourceFile */ || ts.isAmbientModule(location); + } + /** + * Gets a human-readable name for a symbol. + * Should *not* be used for the right-hand side of a `.` -- use `symbolName(symbol)` for that instead. + * + * Unlike `symbolName(symbol)`, this will include quotes if the name is from a string literal. + * It will also use a representation of a number as written instead of a decimal form, e.g. `0o11` instead of `9`. + */ + function getNameOfSymbolAsWritten(symbol, context) { + if (context && symbol.escapedName === "default" /* Default */ && !(context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */) && + // If it's not the first part of an entity name, it must print as `default` + (!(context.flags & 16777216 /* InInitialEntityName */) || + // if the symbol is synthesized, it will only be referenced externally it must print as `default` + !symbol.declarations || + // if not in the same binding context (source file, module declaration), it must print as `default` + (context.enclosingDeclaration && ts.findAncestor(symbol.declarations[0], isDefaultBindingContext) !== ts.findAncestor(context.enclosingDeclaration, isDefaultBindingContext)))) { + return "default"; + } + if (symbol.declarations && symbol.declarations.length) { + var declaration = symbol.declarations[0]; + var name = ts.getNameOfDeclaration(declaration); + if (name) { + if (ts.isCallExpression(declaration) && ts.isBindableObjectDefinePropertyCall(declaration)) { + return ts.symbolName(symbol); + } + return ts.declarationNameToString(name); + } + if (declaration.parent && declaration.parent.kind === 237 /* VariableDeclaration */) { + return ts.declarationNameToString(declaration.parent.name); + } + switch (declaration.kind) { + case 209 /* ClassExpression */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + if (context && !context.encounteredError && !(context.flags & 131072 /* AllowAnonymousIdentifier */)) { + context.encounteredError = true; + } + return declaration.kind === 209 /* ClassExpression */ ? "(Anonymous class)" : "(Anonymous function)"; + } + } + var nameType = symbol.nameType; + if (nameType) { + if (nameType.flags & 128 /* StringLiteral */ && !ts.isIdentifierText(nameType.value, compilerOptions.target)) { + return "\"" + ts.escapeString(nameType.value, 34 /* doubleQuote */) + "\""; + } + if (nameType && nameType.flags & 8192 /* UniqueESSymbol */) { + return "[" + getNameOfSymbolAsWritten(nameType.symbol, context) + "]"; + } + } + return ts.symbolName(symbol); + } + function isDeclarationVisible(node) { + if (node) { + var links = getNodeLinks(node); + if (links.isVisible === undefined) { + links.isVisible = !!determineIfDeclarationIsVisible(); + } + return links.isVisible; + } + return false; + function determineIfDeclarationIsVisible() { + switch (node.kind) { + case 297 /* JSDocCallbackTag */: + case 304 /* JSDocTypedefTag */: + // Top-level jsdoc type aliases are considered exported + // First parent is comment node, second is hosting declaration or token; we only care about those tokens or declarations whose parent is a source file + return !!(node.parent && node.parent.parent && node.parent.parent.parent && ts.isSourceFile(node.parent.parent.parent)); + case 186 /* BindingElement */: + return isDeclarationVisible(node.parent.parent); + case 237 /* VariableDeclaration */: + if (ts.isBindingPattern(node.name) && + !node.name.elements.length) { + // If the binding pattern is empty, this variable declaration is not visible + return false; + } + // falls through + case 244 /* ModuleDeclaration */: + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 239 /* FunctionDeclaration */: + case 243 /* EnumDeclaration */: + case 248 /* ImportEqualsDeclaration */: + // external module augmentation is always visible + if (ts.isExternalModuleAugmentation(node)) { + return true; + } + var parent = getDeclarationContainer(node); + // If the node is not exported or it is not ambient module element (except import declaration) + if (!(ts.getCombinedModifierFlags(node) & 1 /* Export */) && + !(node.kind !== 248 /* ImportEqualsDeclaration */ && parent.kind !== 279 /* SourceFile */ && parent.flags & 4194304 /* Ambient */)) { + return isGlobalSourceFile(parent); + } + // Exported members/ambient module elements (exception import declaration) are visible if parent is visible + return isDeclarationVisible(parent); + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + if (ts.hasModifier(node, 8 /* Private */ | 16 /* Protected */)) { + // Private/protected properties/methods are not visible + return false; + } + // Public properties/methods are visible if its parents are visible, so: + // falls through + case 157 /* Constructor */: + case 161 /* ConstructSignature */: + case 160 /* CallSignature */: + case 162 /* IndexSignature */: + case 151 /* Parameter */: + case 245 /* ModuleBlock */: + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + case 168 /* TypeLiteral */: + case 164 /* TypeReference */: + case 169 /* ArrayType */: + case 170 /* TupleType */: + case 173 /* UnionType */: + case 174 /* IntersectionType */: + case 177 /* ParenthesizedType */: + return isDeclarationVisible(node.parent); + // Default binding, import specifier and namespace import is visible + // only on demand so by default it is not visible + case 250 /* ImportClause */: + case 251 /* NamespaceImport */: + case 253 /* ImportSpecifier */: + return false; + // Type parameters are always visible + case 150 /* TypeParameter */: + // Source file and namespace export are always visible + case 279 /* SourceFile */: + case 247 /* NamespaceExportDeclaration */: + return true; + // Export assignments do not create name bindings outside the module + case 254 /* ExportAssignment */: + return false; + default: + return false; + } + } + } + function collectLinkedAliases(node, setVisibility) { + var exportSymbol; + if (node.parent && node.parent.kind === 254 /* ExportAssignment */) { + exportSymbol = resolveName(node, node.escapedText, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, node, /*isUse*/ false); + } + else if (node.parent.kind === 257 /* ExportSpecifier */) { + exportSymbol = getTargetOfExportSpecifier(node.parent, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); + } + var result; + if (exportSymbol) { + buildVisibleNodeList(exportSymbol.declarations); + } + return result; + function buildVisibleNodeList(declarations) { + ts.forEach(declarations, function (declaration) { + var resultNode = getAnyImportSyntax(declaration) || declaration; + if (setVisibility) { + getNodeLinks(declaration).isVisible = true; + } + else { + result = result || []; + ts.pushIfUnique(result, resultNode); + } + if (ts.isInternalModuleImportEqualsDeclaration(declaration)) { + // Add the referenced top container visible + var internalModuleReference = declaration.moduleReference; + var firstIdentifier = getFirstIdentifier(internalModuleReference); + var importSymbol = resolveName(declaration, firstIdentifier.escapedText, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */, undefined, undefined, /*isUse*/ false); + if (importSymbol) { + buildVisibleNodeList(importSymbol.declarations); + } + } + }); + } + } + /** + * Push an entry on the type resolution stack. If an entry with the given target and the given property name + * is already on the stack, and no entries in between already have a type, then a circularity has occurred. + * In this case, the result values of the existing entry and all entries pushed after it are changed to false, + * and the value false is returned. Otherwise, the new entry is just pushed onto the stack, and true is returned. + * In order to see if the same query has already been done before, the target object and the propertyName both + * must match the one passed in. + * + * @param target The symbol, type, or signature whose type is being queried + * @param propertyName The property name that should be used to query the target for its type + */ + function pushTypeResolution(target, propertyName) { + var resolutionCycleStartIndex = findResolutionCycleStartIndex(target, propertyName); + if (resolutionCycleStartIndex >= 0) { + // A cycle was found + var length_2 = resolutionTargets.length; + for (var i = resolutionCycleStartIndex; i < length_2; i++) { + resolutionResults[i] = false; + } + return false; + } + resolutionTargets.push(target); + resolutionResults.push(/*items*/ true); + resolutionPropertyNames.push(propertyName); + return true; + } + function findResolutionCycleStartIndex(target, propertyName) { + for (var i = resolutionTargets.length - 1; i >= 0; i--) { + if (hasType(resolutionTargets[i], resolutionPropertyNames[i])) { + return -1; + } + if (resolutionTargets[i] === target && resolutionPropertyNames[i] === propertyName) { + return i; + } + } + return -1; + } + function hasType(target, propertyName) { + switch (propertyName) { + case 0 /* Type */: + return !!getSymbolLinks(target).type; + case 5 /* EnumTagType */: + return !!(getNodeLinks(target).resolvedEnumType); + case 2 /* DeclaredType */: + return !!getSymbolLinks(target).declaredType; + case 1 /* ResolvedBaseConstructorType */: + return !!target.resolvedBaseConstructorType; + case 3 /* ResolvedReturnType */: + return !!target.resolvedReturnType; + case 4 /* ImmediateBaseConstraint */: + return !!target.immediateBaseConstraint; + case 6 /* JSDocTypeReference */: + return !!getSymbolLinks(target).resolvedJSDocType; + } + return ts.Debug.assertNever(propertyName); + } + // Pop an entry from the type resolution stack and return its associated result value. The result value will + // be true if no circularities were detected, or false if a circularity was found. + function popTypeResolution() { + resolutionTargets.pop(); + resolutionPropertyNames.pop(); + return resolutionResults.pop(); + } + function getDeclarationContainer(node) { + return ts.findAncestor(ts.getRootDeclaration(node), function (node) { + switch (node.kind) { + case 237 /* VariableDeclaration */: + case 238 /* VariableDeclarationList */: + case 253 /* ImportSpecifier */: + case 252 /* NamedImports */: + case 251 /* NamespaceImport */: + case 250 /* ImportClause */: + return false; + default: + return true; + } + }).parent; + } + function getTypeOfPrototypeProperty(prototype) { + // TypeScript 1.0 spec (April 2014): 8.4 + // Every class automatically contains a static property member named 'prototype', + // the type of which is an instantiation of the class type with type Any supplied as a type argument for each type parameter. + // It is an error to explicitly declare a static property member with the name 'prototype'. + var classType = getDeclaredTypeOfSymbol(getParentOfSymbol(prototype)); + return classType.typeParameters ? createTypeReference(classType, ts.map(classType.typeParameters, function (_) { return anyType; })) : classType; + } + // Return the type of the given property in the given type, or undefined if no such property exists + function getTypeOfPropertyOfType(type, name) { + var prop = getPropertyOfType(type, name); + return prop ? getTypeOfSymbol(prop) : undefined; + } + function isTypeAny(type) { + return type && (type.flags & 1 /* Any */) !== 0; + } + // Return the type of a binding element parent. We check SymbolLinks first to see if a type has been + // assigned by contextual typing. + function getTypeForBindingElementParent(node) { + var symbol = getSymbolOfNode(node); + return symbol && getSymbolLinks(symbol).type || getTypeForVariableLikeDeclaration(node, /*includeOptionality*/ false); + } + function isComputedNonLiteralName(name) { + return name.kind === 149 /* ComputedPropertyName */ && !ts.isStringOrNumericLiteralLike(name.expression); + } + function getRestType(source, properties, symbol) { + source = filterType(source, function (t) { return !(t.flags & 98304 /* Nullable */); }); + if (source.flags & 131072 /* Never */) { + return emptyObjectType; + } + if (source.flags & 1048576 /* Union */) { + return mapType(source, function (t) { return getRestType(t, properties, symbol); }); + } + var omitKeyType = getUnionType(ts.map(properties, getLiteralTypeFromPropertyName)); + if (isGenericObjectType(source) || isGenericIndexType(omitKeyType)) { + if (omitKeyType.flags & 131072 /* Never */) { + return source; + } + var pickTypeAlias = getGlobalPickSymbol(); + var excludeTypeAlias = getGlobalExcludeSymbol(); + if (!pickTypeAlias || !excludeTypeAlias) { + return errorType; + } + var pickKeys = getTypeAliasInstantiation(excludeTypeAlias, [getIndexType(source), omitKeyType]); + return getTypeAliasInstantiation(pickTypeAlias, [source, pickKeys]); + } + var members = ts.createSymbolTable(); + for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) { + var prop = _a[_i]; + if (!isTypeAssignableTo(getLiteralTypeFromProperty(prop, 8576 /* StringOrNumberLiteralOrUnique */), omitKeyType) + && !(ts.getDeclarationModifierFlagsFromSymbol(prop) & (8 /* Private */ | 16 /* Protected */)) + && isSpreadableProperty(prop)) { + members.set(prop.escapedName, getSpreadSymbol(prop)); + } + } + var stringIndexInfo = getIndexInfoOfType(source, 0 /* String */); + var numberIndexInfo = getIndexInfoOfType(source, 1 /* Number */); + return createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); + } + /** Return the inferred type for a binding element */ + function getTypeForBindingElement(declaration) { + var pattern = declaration.parent; + var parentType = getTypeForBindingElementParent(pattern.parent); + // If parent has the unknown (error) type, then so does this binding element + if (parentType === errorType) { + return errorType; + } + // If no type was specified or inferred for parent, + // infer from the initializer of the binding element if one is present. + // Otherwise, go with the undefined type of the parent. + if (!parentType) { + return declaration.initializer ? checkDeclarationInitializer(declaration) : parentType; + } + if (isTypeAny(parentType)) { + return parentType; + } + // Relax null check on ambient destructuring parameters, since the parameters have no implementation and are just documentation + if (strictNullChecks && declaration.flags & 4194304 /* Ambient */ && ts.isParameterDeclaration(declaration)) { + parentType = getNonNullableType(parentType); + } + var type; + if (pattern.kind === 184 /* ObjectBindingPattern */) { + if (declaration.dotDotDotToken) { + if (parentType.flags & 2 /* Unknown */ || !isValidSpreadType(parentType)) { + error(declaration, ts.Diagnostics.Rest_types_may_only_be_created_from_object_types); + return errorType; + } + var literalMembers = []; + for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (!element.dotDotDotToken) { + literalMembers.push(element.propertyName || element.name); + } + } + type = getRestType(parentType, literalMembers, declaration.symbol); + } + else { + // Use explicitly specified property name ({ p: xxx } form), or otherwise the implied name ({ p } form) + var name = declaration.propertyName || declaration.name; + var exprType = getLiteralTypeFromPropertyName(name); + var declaredType = checkIndexedAccessIndexType(getIndexedAccessType(parentType, exprType, name), name); + type = getFlowTypeOfReference(declaration, getConstraintForLocation(declaredType, declaration.name)); + } + } + else { + // This elementType will be used if the specific property corresponding to this index is not + // present (aka the tuple element property). This call also checks that the parentType is in + // fact an iterable or array (depending on target language). + var elementType = checkIteratedTypeOrElementType(parentType, pattern, /*allowStringInput*/ false, /*allowAsyncIterables*/ false); + var index_1 = pattern.elements.indexOf(declaration); + if (declaration.dotDotDotToken) { + // If the parent is a tuple type, the rest element has a tuple type of the + // remaining tuple element types. Otherwise, the rest element has an array type with same + // element type as the parent type. + type = everyType(parentType, isTupleType) ? + mapType(parentType, function (t) { return sliceTupleType(t, index_1); }) : + createArrayType(elementType); + } + else { + // Use specific property type when parent is a tuple or numeric index type when parent is an array + var index_2 = pattern.elements.indexOf(declaration); + type = everyType(parentType, isTupleLikeType) ? + getTupleElementType(parentType, index_2) || declaration.initializer && checkDeclarationInitializer(declaration) : + elementType; + if (!type) { + if (isTupleType(parentType)) { + error(declaration, ts.Diagnostics.Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2, typeToString(parentType), getTypeReferenceArity(parentType), pattern.elements.length); + } + else { + error(declaration, ts.Diagnostics.Type_0_has_no_property_1, typeToString(parentType), "" + index_2); + } + return errorType; + } + } + } + // In strict null checking mode, if a default value of a non-undefined type is specified, remove + // undefined from the final type. + if (strictNullChecks && declaration.initializer && !(getFalsyFlags(checkDeclarationInitializer(declaration)) & 32768 /* Undefined */)) { + type = getTypeWithFacts(type, 524288 /* NEUndefined */); + } + return declaration.initializer && !ts.getEffectiveTypeAnnotationNode(ts.walkUpBindingElementsAndPatterns(declaration)) ? + getUnionType([type, checkDeclarationInitializer(declaration)], 2 /* Subtype */) : + type; + } + function getTypeForDeclarationFromJSDocComment(declaration) { + var jsdocType = ts.getJSDocType(declaration); + if (jsdocType) { + return getTypeFromTypeNode(jsdocType); + } + return undefined; + } + function isNullOrUndefined(node) { + var expr = ts.skipParentheses(node); + return expr.kind === 96 /* NullKeyword */ || expr.kind === 72 /* Identifier */ && getResolvedSymbol(expr) === undefinedSymbol; + } + function isEmptyArrayLiteral(node) { + var expr = ts.skipParentheses(node); + return expr.kind === 187 /* ArrayLiteralExpression */ && expr.elements.length === 0; + } + function addOptionality(type, optional) { + if (optional === void 0) { optional = true; } + return strictNullChecks && optional ? getOptionalType(type) : type; + } + // Return the inferred type for a variable, parameter, or property declaration + function getTypeForVariableLikeDeclaration(declaration, includeOptionality) { + // A variable declared in a for..in statement is of type string, or of type keyof T when the + // right hand expression is of a type parameter type. + if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 226 /* ForInStatement */) { + var indexType = getIndexType(getNonNullableTypeIfNeeded(checkExpression(declaration.parent.parent.expression))); + return indexType.flags & (262144 /* TypeParameter */ | 4194304 /* Index */) ? getExtractStringType(indexType) : stringType; + } + if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 227 /* ForOfStatement */) { + // checkRightHandSideOfForOf will return undefined if the for-of expression type was + // missing properties/signatures required to get its iteratedType (like + // [Symbol.iterator] or next). This may be because we accessed properties from anyType, + // or it may have led to an error inside getElementTypeOfIterable. + var forOfStatement = declaration.parent.parent; + return checkRightHandSideOfForOf(forOfStatement.expression, forOfStatement.awaitModifier) || anyType; + } + if (ts.isBindingPattern(declaration.parent)) { + return getTypeForBindingElement(declaration); + } + var isOptional = includeOptionality && (ts.isParameter(declaration) && isJSDocOptionalParameter(declaration) + || !ts.isBindingElement(declaration) && !ts.isVariableDeclaration(declaration) && !!declaration.questionToken); + // Use type from type annotation if one is present + var declaredType = tryGetTypeFromEffectiveTypeNode(declaration); + if (declaredType) { + return addOptionality(declaredType, isOptional); + } + if ((noImplicitAny || ts.isInJSFile(declaration)) && + declaration.kind === 237 /* VariableDeclaration */ && !ts.isBindingPattern(declaration.name) && + !(ts.getCombinedModifierFlags(declaration) & 1 /* Export */) && !(declaration.flags & 4194304 /* Ambient */)) { + // If --noImplicitAny is on or the declaration is in a Javascript file, + // use control flow tracked 'any' type for non-ambient, non-exported var or let variables with no + // initializer or a 'null' or 'undefined' initializer. + if (!(ts.getCombinedNodeFlags(declaration) & 2 /* Const */) && (!declaration.initializer || isNullOrUndefined(declaration.initializer))) { + return autoType; + } + // Use control flow tracked 'any[]' type for non-ambient, non-exported variables with an empty array + // literal initializer. + if (declaration.initializer && isEmptyArrayLiteral(declaration.initializer)) { + return autoArrayType; + } + } + if (declaration.kind === 151 /* Parameter */) { + var func = declaration.parent; + // For a parameter of a set accessor, use the type of the get accessor if one is present + if (func.kind === 159 /* SetAccessor */ && !hasNonBindableDynamicName(func)) { + var getter = ts.getDeclarationOfKind(getSymbolOfNode(declaration.parent), 158 /* GetAccessor */); + if (getter) { + var getterSignature = getSignatureFromDeclaration(getter); + var thisParameter = getAccessorThisParameter(func); + if (thisParameter && declaration === thisParameter) { + // Use the type from the *getter* + ts.Debug.assert(!thisParameter.type); + return getTypeOfSymbol(getterSignature.thisParameter); + } + return getReturnTypeOfSignature(getterSignature); + } + } + if (ts.isInJSFile(declaration)) { + var typeTag = ts.getJSDocType(func); + if (typeTag && ts.isFunctionTypeNode(typeTag)) { + return getTypeAtPosition(getSignatureFromDeclaration(typeTag), func.parameters.indexOf(declaration)); + } + } + // Use contextual parameter type if one is available + var type = declaration.symbol.escapedName === "this" /* This */ ? getContextualThisParameterType(func) : getContextuallyTypedParameterType(declaration); + if (type) { + return addOptionality(type, isOptional); + } + } + else if (ts.isInJSFile(declaration)) { + var containerObjectType = getJSContainerObjectType(declaration, getSymbolOfNode(declaration), ts.getDeclaredExpandoInitializer(declaration)); + if (containerObjectType) { + return containerObjectType; + } + } + // Use the type of the initializer expression if one is present + if (declaration.initializer) { + var type = checkDeclarationInitializer(declaration); + return addOptionality(type, isOptional); + } + if (ts.isJsxAttribute(declaration)) { + // if JSX attribute doesn't have initializer, by default the attribute will have boolean value of true. + // I.e is sugar for + return trueType; + } + // If the declaration specifies a binding pattern, use the type implied by the binding pattern + if (ts.isBindingPattern(declaration.name)) { + return getTypeFromBindingPattern(declaration.name, /*includePatternInType*/ false, /*reportErrors*/ true); + } + // No type specified and nothing can be inferred + return undefined; + } + function getWidenedTypeFromAssignmentDeclaration(symbol, resolvedSymbol) { + // function/class/{} initializers are themselves containers, so they won't merge in the same way as other initializers + var container = ts.getAssignedExpandoInitializer(symbol.valueDeclaration); + if (container) { + var tag = ts.getJSDocTypeTag(container); + if (tag && tag.typeExpression) { + return getTypeFromTypeNode(tag.typeExpression); + } + var containerObjectType = getJSContainerObjectType(symbol.valueDeclaration, symbol, container); + return containerObjectType || getWidenedLiteralType(checkExpressionCached(container)); + } + var definedInConstructor = false; + var definedInMethod = false; + var jsdocType; + var types; + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + var expression = (ts.isBinaryExpression(declaration) || ts.isCallExpression(declaration)) ? declaration : + ts.isPropertyAccessExpression(declaration) ? ts.isBinaryExpression(declaration.parent) ? declaration.parent : declaration : + undefined; + if (!expression) { + return errorType; + } + var kind = ts.isPropertyAccessExpression(expression) ? ts.getAssignmentDeclarationPropertyAccessKind(expression) : ts.getAssignmentDeclarationKind(expression); + if (kind === 4 /* ThisProperty */) { + if (isDeclarationInConstructor(expression)) { + definedInConstructor = true; + } + else { + definedInMethod = true; + } + } + if (!ts.isCallExpression(expression)) { + jsdocType = getJSDocTypeFromAssignmentDeclaration(jsdocType, expression, symbol, declaration); + } + if (!jsdocType) { + (types || (types = [])).push((ts.isBinaryExpression(expression) || ts.isCallExpression(expression)) ? getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) : neverType); + } + } + var type = jsdocType; + if (!type) { + var constructorTypes = definedInConstructor ? getConstructorDefinedThisAssignmentTypes(types, symbol.declarations) : undefined; + // use only the constructor types unless they were only assigned null | undefined (including widening variants) + if (definedInMethod) { + var propType = getTypeOfAssignmentDeclarationPropertyOfBaseType(symbol); + if (propType) { + (constructorTypes || (constructorTypes = [])).push(propType); + definedInConstructor = true; + } + } + var sourceTypes = ts.some(constructorTypes, function (t) { return !!(t.flags & ~(98304 /* Nullable */ | 134217728 /* ContainsWideningType */)); }) ? constructorTypes : types; // TODO: GH#18217 + type = getUnionType(sourceTypes, 2 /* Subtype */); + } + var widened = getWidenedType(addOptionality(type, definedInMethod && !definedInConstructor)); + if (filterType(widened, function (t) { return !!(t.flags & ~98304 /* Nullable */); }) === neverType) { + reportImplicitAny(symbol.valueDeclaration, anyType); + return anyType; + } + return widened; + } + function getJSContainerObjectType(decl, symbol, init) { + if (!ts.isInJSFile(decl) || !init || !ts.isObjectLiteralExpression(init) || init.properties.length) { + return undefined; + } + var exports = ts.createSymbolTable(); + while (ts.isBinaryExpression(decl) || ts.isPropertyAccessExpression(decl)) { + var s_1 = getSymbolOfNode(decl); + if (s_1 && ts.hasEntries(s_1.exports)) { + mergeSymbolTable(exports, s_1.exports); + } + decl = ts.isBinaryExpression(decl) ? decl.parent : decl.parent.parent; + } + var s = getSymbolOfNode(decl); + if (s && ts.hasEntries(s.exports)) { + mergeSymbolTable(exports, s.exports); + } + var type = createAnonymousType(symbol, exports, ts.emptyArray, ts.emptyArray, undefined, undefined); + type.objectFlags |= 16384 /* JSLiteral */; + return type; + } + function getJSDocTypeFromAssignmentDeclaration(declaredType, expression, _symbol, declaration) { + var typeNode = ts.getJSDocType(expression.parent); + if (typeNode) { + var type = getWidenedType(getTypeFromTypeNode(typeNode)); + if (!declaredType) { + return type; + } + else if (declaredType !== errorType && type !== errorType && !isTypeIdenticalTo(declaredType, type)) { + errorNextVariableOrPropertyDeclarationMustHaveSameType(declaredType, declaration, type); + } + } + return declaredType; + } + /** If we don't have an explicit JSDoc type, get the type from the initializer. */ + function getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) { + if (ts.isCallExpression(expression)) { + if (resolvedSymbol) { + return getTypeOfSymbol(resolvedSymbol); // This shouldn't happen except under some hopefully forbidden merges of export assignments and object define assignments + } + var objectLitType = checkExpressionCached(expression.arguments[2]); + var valueType = getTypeOfPropertyOfType(objectLitType, "value"); + if (valueType) { + return valueType; + } + var getFunc = getTypeOfPropertyOfType(objectLitType, "get"); + if (getFunc) { + var getSig = getSingleCallSignature(getFunc); + if (getSig) { + return getReturnTypeOfSignature(getSig); + } + } + var setFunc = getTypeOfPropertyOfType(objectLitType, "set"); + if (setFunc) { + var setSig = getSingleCallSignature(setFunc); + if (setSig) { + return getTypeOfFirstParameterOfSignature(setSig); + } + } + return anyType; + } + var type = resolvedSymbol ? getTypeOfSymbol(resolvedSymbol) : getWidenedLiteralType(checkExpressionCached(expression.right)); + if (type.flags & 524288 /* Object */ && + kind === 2 /* ModuleExports */ && + symbol.escapedName === "export=" /* ExportEquals */) { + var exportedType_1 = resolveStructuredTypeMembers(type); + var members_3 = ts.createSymbolTable(); + ts.copyEntries(exportedType_1.members, members_3); + if (resolvedSymbol && !resolvedSymbol.exports) { + resolvedSymbol.exports = ts.createSymbolTable(); + } + (resolvedSymbol || symbol).exports.forEach(function (s, name) { + if (members_3.has(name)) { + var exportedMember = exportedType_1.members.get(name); + var union = createSymbol(s.flags | exportedMember.flags, name); + union.type = getUnionType([getTypeOfSymbol(s), getTypeOfSymbol(exportedMember)]); + members_3.set(name, union); + } + else { + members_3.set(name, s); + } + }); + var result = createAnonymousType(exportedType_1.symbol, members_3, exportedType_1.callSignatures, exportedType_1.constructSignatures, exportedType_1.stringIndexInfo, exportedType_1.numberIndexInfo); + result.objectFlags |= (ts.getObjectFlags(type) & 16384 /* JSLiteral */); // Propagate JSLiteral flag + return result; + } + if (isEmptyArrayLiteralType(type)) { + reportImplicitAny(expression, anyArrayType); + return anyArrayType; + } + return type; + } + function isDeclarationInConstructor(expression) { + var thisContainer = ts.getThisContainer(expression, /*includeArrowFunctions*/ false); + // Properties defined in a constructor (or base constructor, or javascript constructor function) don't get undefined added. + // Function expressions that are assigned to the prototype count as methods. + return thisContainer.kind === 157 /* Constructor */ || + thisContainer.kind === 239 /* FunctionDeclaration */ || + (thisContainer.kind === 196 /* FunctionExpression */ && !ts.isPrototypePropertyAssignment(thisContainer.parent)); + } + function getConstructorDefinedThisAssignmentTypes(types, declarations) { + ts.Debug.assert(types.length === declarations.length); + return types.filter(function (_, i) { + var declaration = declarations[i]; + var expression = ts.isBinaryExpression(declaration) ? declaration : + ts.isBinaryExpression(declaration.parent) ? declaration.parent : undefined; + return expression && isDeclarationInConstructor(expression); + }); + } + /** check for definition in base class if any declaration is in a class */ + function getTypeOfAssignmentDeclarationPropertyOfBaseType(property) { + var parentDeclaration = ts.forEach(property.declarations, function (d) { + var parent = ts.getThisContainer(d, /*includeArrowFunctions*/ false).parent; + return ts.isClassLike(parent) && parent; + }); + if (parentDeclaration) { + var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(parentDeclaration)); + var baseClassType = classType && getBaseTypes(classType)[0]; + if (baseClassType) { + return getTypeOfPropertyOfType(baseClassType, property.escapedName); + } + } + } + // Return the type implied by a binding pattern element. This is the type of the initializer of the element if + // one is present. Otherwise, if the element is itself a binding pattern, it is the type implied by the binding + // pattern. Otherwise, it is the type any. + function getTypeFromBindingElement(element, includePatternInType, reportErrors) { + if (element.initializer) { + return addOptionality(checkDeclarationInitializer(element)); + } + if (ts.isBindingPattern(element.name)) { + return getTypeFromBindingPattern(element.name, includePatternInType, reportErrors); + } + if (reportErrors && !declarationBelongsToPrivateAmbientMember(element)) { + reportImplicitAny(element, anyType); + } + return anyType; + } + // Return the type implied by an object binding pattern + function getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) { + var members = ts.createSymbolTable(); + var stringIndexInfo; + var objectFlags = 128 /* ObjectLiteral */; + ts.forEach(pattern.elements, function (e) { + var name = e.propertyName || e.name; + if (isComputedNonLiteralName(name)) { + // do not include computed properties in the implied type + objectFlags |= 512 /* ObjectLiteralPatternWithComputedProperties */; + return; + } + if (e.dotDotDotToken) { + stringIndexInfo = createIndexInfo(anyType, /*isReadonly*/ false); + return; + } + var text = ts.getTextOfPropertyName(name); + var flags = 4 /* Property */ | (e.initializer ? 16777216 /* Optional */ : 0); + var symbol = createSymbol(flags, text); + symbol.type = getTypeFromBindingElement(e, includePatternInType, reportErrors); + symbol.bindingElement = e; + members.set(symbol.escapedName, symbol); + }); + var result = createAnonymousType(undefined, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, undefined); + result.flags |= 268435456 /* ContainsObjectLiteral */; + result.objectFlags |= objectFlags; + if (includePatternInType) { + result.pattern = pattern; + } + return result; + } + // Return the type implied by an array binding pattern + function getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors) { + var elements = pattern.elements; + var lastElement = ts.lastOrUndefined(elements); + var hasRestElement = !!(lastElement && lastElement.kind === 186 /* BindingElement */ && lastElement.dotDotDotToken); + if (elements.length === 0 || elements.length === 1 && hasRestElement) { + return languageVersion >= 2 /* ES2015 */ ? createIterableType(anyType) : anyArrayType; + } + var elementTypes = ts.map(elements, function (e) { return ts.isOmittedExpression(e) ? anyType : getTypeFromBindingElement(e, includePatternInType, reportErrors); }); + var minLength = ts.findLastIndex(elements, function (e) { return !ts.isOmittedExpression(e) && !hasDefaultValue(e); }, elements.length - (hasRestElement ? 2 : 1)) + 1; + var result = createTupleType(elementTypes, minLength, hasRestElement); + if (includePatternInType) { + result = cloneTypeReference(result); + result.pattern = pattern; + } + return result; + } + // Return the type implied by a binding pattern. This is the type implied purely by the binding pattern itself + // and without regard to its context (i.e. without regard any type annotation or initializer associated with the + // declaration in which the binding pattern is contained). For example, the implied type of [x, y] is [any, any] + // and the implied type of { x, y: z = 1 } is { x: any; y: number; }. The type implied by a binding pattern is + // used as the contextual type of an initializer associated with the binding pattern. Also, for a destructuring + // parameter with no type annotation or initializer, the type implied by the binding pattern becomes the type of + // the parameter. + function getTypeFromBindingPattern(pattern, includePatternInType, reportErrors) { + if (includePatternInType === void 0) { includePatternInType = false; } + if (reportErrors === void 0) { reportErrors = false; } + return pattern.kind === 184 /* ObjectBindingPattern */ + ? getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) + : getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors); + } + // Return the type associated with a variable, parameter, or property declaration. In the simple case this is the type + // specified in a type annotation or inferred from an initializer. However, in the case of a destructuring declaration it + // is a bit more involved. For example: + // + // var [x, s = ""] = [1, "one"]; + // + // Here, the array literal [1, "one"] is contextually typed by the type [any, string], which is the implied type of the + // binding pattern [x, s = ""]. Because the contextual type is a tuple type, the resulting type of [1, "one"] is the + // tuple type [number, string]. Thus, the type inferred for 'x' is number and the type inferred for 's' is string. + function getWidenedTypeForVariableLikeDeclaration(declaration, reportErrors) { + return widenTypeForVariableLikeDeclaration(getTypeForVariableLikeDeclaration(declaration, /*includeOptionality*/ true), declaration, reportErrors); + } + function widenTypeForVariableLikeDeclaration(type, declaration, reportErrors) { + if (type) { + if (reportErrors) { + reportErrorsFromWidening(declaration, type); + } + // always widen a 'unique symbol' type if the type was created for a different declaration. + if (type.flags & 8192 /* UniqueESSymbol */ && (ts.isBindingElement(declaration) || !declaration.type) && type.symbol !== getSymbolOfNode(declaration)) { + type = esSymbolType; + } + return getWidenedType(type); + } + // Rest parameters default to type any[], other parameters default to type any + type = ts.isParameter(declaration) && declaration.dotDotDotToken ? anyArrayType : anyType; + // Report implicit any errors unless this is a private property within an ambient declaration + if (reportErrors) { + if (!declarationBelongsToPrivateAmbientMember(declaration)) { + reportImplicitAny(declaration, type); + } + } + return type; + } + function declarationBelongsToPrivateAmbientMember(declaration) { + var root = ts.getRootDeclaration(declaration); + var memberDeclaration = root.kind === 151 /* Parameter */ ? root.parent : root; + return isPrivateWithinAmbient(memberDeclaration); + } + function tryGetTypeFromEffectiveTypeNode(declaration) { + var typeNode = ts.getEffectiveTypeAnnotationNode(declaration); + if (typeNode) { + return getTypeFromTypeNode(typeNode); + } + } + function getTypeOfVariableOrParameterOrProperty(symbol) { + var links = getSymbolLinks(symbol); + return links.type || (links.type = getTypeOfVariableOrParameterOrPropertyWorker(symbol)); + } + function getTypeOfVariableOrParameterOrPropertyWorker(symbol) { + // Handle prototype property + if (symbol.flags & 4194304 /* Prototype */) { + return getTypeOfPrototypeProperty(symbol); + } + // CommonsJS require and module both have type any. + if (symbol === requireSymbol) { + return anyType; + } + if (symbol.flags & 134217728 /* ModuleExports */) { + var fileSymbol = getSymbolOfNode(ts.getSourceFileOfNode(symbol.valueDeclaration)); + var members = ts.createSymbolTable(); + members.set("exports", fileSymbol); + return createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, undefined, undefined); + } + // Handle catch clause variables + var declaration = symbol.valueDeclaration; + if (ts.isCatchClauseVariableDeclarationOrBindingElement(declaration)) { + return anyType; + } + // Handle export default expressions + if (ts.isSourceFile(declaration)) { + var jsonSourceFile = ts.cast(declaration, ts.isJsonSourceFile); + if (!jsonSourceFile.statements.length) { + return emptyObjectType; + } + var type_1 = getWidenedLiteralType(checkExpression(jsonSourceFile.statements[0].expression)); + if (type_1.flags & 524288 /* Object */) { + return getRegularTypeOfObjectLiteral(type_1); + } + return type_1; + } + if (declaration.kind === 254 /* ExportAssignment */) { + return widenTypeForVariableLikeDeclaration(checkExpressionCached(declaration.expression), declaration); + } + // Handle variable, parameter or property + if (!pushTypeResolution(symbol, 0 /* Type */)) { + return errorType; + } + var type; + if (ts.isInJSFile(declaration) && + (ts.isCallExpression(declaration) || ts.isBinaryExpression(declaration) || ts.isPropertyAccessExpression(declaration) && ts.isBinaryExpression(declaration.parent))) { + type = getWidenedTypeFromAssignmentDeclaration(symbol); + } + else if (ts.isJSDocPropertyLikeTag(declaration) + || ts.isPropertyAccessExpression(declaration) + || ts.isIdentifier(declaration) + || ts.isClassDeclaration(declaration) + || ts.isFunctionDeclaration(declaration) + || (ts.isMethodDeclaration(declaration) && !ts.isObjectLiteralMethod(declaration)) + || ts.isMethodSignature(declaration)) { + // Symbol is property of some kind that is merged with something - should use `getTypeOfFuncClassEnumModule` and not `getTypeOfVariableOrParameterOrProperty` + if (symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 384 /* Enum */ | 512 /* ValueModule */)) { + return getTypeOfFuncClassEnumModule(symbol); + } + type = ts.isBinaryExpression(declaration.parent) ? + getWidenedTypeFromAssignmentDeclaration(symbol) : + tryGetTypeFromEffectiveTypeNode(declaration) || anyType; + } + else if (ts.isPropertyAssignment(declaration)) { + type = tryGetTypeFromEffectiveTypeNode(declaration) || checkPropertyAssignment(declaration); + } + else if (ts.isJsxAttribute(declaration)) { + type = tryGetTypeFromEffectiveTypeNode(declaration) || checkJsxAttribute(declaration); + } + else if (ts.isShorthandPropertyAssignment(declaration)) { + type = tryGetTypeFromEffectiveTypeNode(declaration) || checkExpressionForMutableLocation(declaration.name, 0 /* Normal */); + } + else if (ts.isObjectLiteralMethod(declaration)) { + type = tryGetTypeFromEffectiveTypeNode(declaration) || checkObjectLiteralMethod(declaration, 0 /* Normal */); + } + else if (ts.isParameter(declaration) + || ts.isPropertyDeclaration(declaration) + || ts.isPropertySignature(declaration) + || ts.isVariableDeclaration(declaration) + || ts.isBindingElement(declaration)) { + type = getWidenedTypeForVariableLikeDeclaration(declaration, /*includeOptionality*/ true); + } + // getTypeOfSymbol dispatches some JS merges incorrectly because their symbol flags are not mutually exclusive. + // Re-dispatch based on valueDeclaration.kind instead. + else if (ts.isEnumDeclaration(declaration)) { + type = getTypeOfFuncClassEnumModule(symbol); + } + else if (ts.isEnumMember(declaration)) { + type = getTypeOfEnumMember(symbol); + } + else { + return ts.Debug.fail("Unhandled declaration kind! " + ts.Debug.showSyntaxKind(declaration) + " for " + ts.Debug.showSymbol(symbol)); + } + if (!popTypeResolution()) { + type = reportCircularityError(symbol); + } + return type; + } + function getAnnotatedAccessorTypeNode(accessor) { + if (accessor) { + if (accessor.kind === 158 /* GetAccessor */) { + var getterTypeAnnotation = ts.getEffectiveReturnTypeNode(accessor); + return getterTypeAnnotation; + } + else { + var setterTypeAnnotation = ts.getEffectiveSetAccessorTypeAnnotationNode(accessor); + return setterTypeAnnotation; + } + } + return undefined; + } + function getAnnotatedAccessorType(accessor) { + var node = getAnnotatedAccessorTypeNode(accessor); + return node && getTypeFromTypeNode(node); + } + function getAnnotatedAccessorThisParameter(accessor) { + var parameter = getAccessorThisParameter(accessor); + return parameter && parameter.symbol; + } + function getThisTypeOfDeclaration(declaration) { + return getThisTypeOfSignature(getSignatureFromDeclaration(declaration)); + } + function getTypeOfAccessors(symbol) { + var links = getSymbolLinks(symbol); + return links.type || (links.type = getTypeOfAccessorsWorker(symbol)); + } + function getTypeOfAccessorsWorker(symbol) { + var getter = ts.getDeclarationOfKind(symbol, 158 /* GetAccessor */); + var setter = ts.getDeclarationOfKind(symbol, 159 /* SetAccessor */); + if (getter && ts.isInJSFile(getter)) { + var jsDocType = getTypeForDeclarationFromJSDocComment(getter); + if (jsDocType) { + return jsDocType; + } + } + if (!pushTypeResolution(symbol, 0 /* Type */)) { + return errorType; + } + var type; + // First try to see if the user specified a return type on the get-accessor. + var getterReturnType = getAnnotatedAccessorType(getter); + if (getterReturnType) { + type = getterReturnType; + } + else { + // If the user didn't specify a return type, try to use the set-accessor's parameter type. + var setterParameterType = getAnnotatedAccessorType(setter); + if (setterParameterType) { + type = setterParameterType; + } + else { + // If there are no specified types, try to infer it from the body of the get accessor if it exists. + if (getter && getter.body) { + type = getReturnTypeFromBody(getter); + } + // Otherwise, fall back to 'any'. + else { + if (setter) { + errorOrSuggestion(noImplicitAny, setter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation, symbolToString(symbol)); + } + else { + ts.Debug.assert(!!getter, "there must existed getter as we are current checking either setter or getter in this function"); + errorOrSuggestion(noImplicitAny, getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); + } + type = anyType; + } + } + } + if (!popTypeResolution()) { + type = anyType; + if (noImplicitAny) { + var getter_1 = ts.getDeclarationOfKind(symbol, 158 /* GetAccessor */); + error(getter_1, ts.Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, symbolToString(symbol)); + } + } + return type; + } + function getBaseTypeVariableOfClass(symbol) { + var baseConstructorType = getBaseConstructorTypeOfClass(getDeclaredTypeOfClassOrInterface(symbol)); + return baseConstructorType.flags & 8650752 /* TypeVariable */ ? baseConstructorType : undefined; + } + function getTypeOfFuncClassEnumModule(symbol) { + var links = getSymbolLinks(symbol); + var originalLinks = links; + if (!links.type) { + var jsDeclaration = ts.getDeclarationOfExpando(symbol.valueDeclaration); + if (jsDeclaration) { + var jsSymbol = getSymbolOfNode(jsDeclaration); + if (jsSymbol && (ts.hasEntries(jsSymbol.exports) || ts.hasEntries(jsSymbol.members))) { + symbol = cloneSymbol(symbol); + // note:we overwrite links because we just cloned the symbol + links = symbol; + if (ts.hasEntries(jsSymbol.exports)) { + symbol.exports = symbol.exports || ts.createSymbolTable(); + mergeSymbolTable(symbol.exports, jsSymbol.exports); + } + if (ts.hasEntries(jsSymbol.members)) { + symbol.members = symbol.members || ts.createSymbolTable(); + mergeSymbolTable(symbol.members, jsSymbol.members); + } + } + } + originalLinks.type = links.type = getTypeOfFuncClassEnumModuleWorker(symbol); + } + return links.type; + } + function getTypeOfFuncClassEnumModuleWorker(symbol) { + var declaration = symbol.valueDeclaration; + if (symbol.flags & 1536 /* Module */ && ts.isShorthandAmbientModuleSymbol(symbol)) { + return anyType; + } + else if (declaration.kind === 204 /* BinaryExpression */ || + declaration.kind === 189 /* PropertyAccessExpression */ && declaration.parent.kind === 204 /* BinaryExpression */) { + return getWidenedTypeFromAssignmentDeclaration(symbol); + } + else if (symbol.flags & 512 /* ValueModule */ && declaration && ts.isSourceFile(declaration) && declaration.commonJsModuleIndicator) { + var resolvedModule = resolveExternalModuleSymbol(symbol); + if (resolvedModule !== symbol) { + if (!pushTypeResolution(symbol, 0 /* Type */)) { + return errorType; + } + var exportEquals = getMergedSymbol(symbol.exports.get("export=" /* ExportEquals */)); + var type_2 = getWidenedTypeFromAssignmentDeclaration(exportEquals, exportEquals === resolvedModule ? undefined : resolvedModule); + if (!popTypeResolution()) { + return reportCircularityError(symbol); + } + return type_2; + } + } + var type = createObjectType(16 /* Anonymous */, symbol); + if (symbol.flags & 32 /* Class */) { + var baseTypeVariable = getBaseTypeVariableOfClass(symbol); + return baseTypeVariable ? getIntersectionType([type, baseTypeVariable]) : type; + } + else { + return strictNullChecks && symbol.flags & 16777216 /* Optional */ ? getOptionalType(type) : type; + } + } + function getTypeOfEnumMember(symbol) { + var links = getSymbolLinks(symbol); + return links.type || (links.type = getDeclaredTypeOfEnumMember(symbol)); + } + function getTypeOfAlias(symbol) { + var links = getSymbolLinks(symbol); + if (!links.type) { + var targetSymbol = resolveAlias(symbol); + // It only makes sense to get the type of a value symbol. If the result of resolving + // the alias is not a value, then it has no type. To get the type associated with a + // type symbol, call getDeclaredTypeOfSymbol. + // This check is important because without it, a call to getTypeOfSymbol could end + // up recursively calling getTypeOfAlias, causing a stack overflow. + links.type = targetSymbol.flags & 67220415 /* Value */ + ? getTypeOfSymbol(targetSymbol) + : errorType; + } + return links.type; + } + function getTypeOfInstantiatedSymbol(symbol) { + var links = getSymbolLinks(symbol); + if (!links.type) { + if (!pushTypeResolution(symbol, 0 /* Type */)) { + return links.type = errorType; + } + var type = instantiateType(getTypeOfSymbol(links.target), links.mapper); + if (!popTypeResolution()) { + type = reportCircularityError(symbol); + } + links.type = type; + } + return links.type; + } + function reportCircularityError(symbol) { + // Check if variable has type annotation that circularly references the variable itself + if (ts.getEffectiveTypeAnnotationNode(symbol.valueDeclaration)) { + error(symbol.valueDeclaration, ts.Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_type_annotation, symbolToString(symbol)); + return errorType; + } + // Otherwise variable has initializer that circularly references the variable itself + if (noImplicitAny) { + error(symbol.valueDeclaration, ts.Diagnostics._0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer, symbolToString(symbol)); + } + return anyType; + } + function getTypeOfSymbol(symbol) { + if (ts.getCheckFlags(symbol) & 1 /* Instantiated */) { + return getTypeOfInstantiatedSymbol(symbol); + } + if (ts.getCheckFlags(symbol) & 2048 /* ReverseMapped */) { + return getTypeOfReverseMappedSymbol(symbol); + } + if (symbol.flags & (3 /* Variable */ | 4 /* Property */)) { + return getTypeOfVariableOrParameterOrProperty(symbol); + } + if (symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 384 /* Enum */ | 512 /* ValueModule */)) { + return getTypeOfFuncClassEnumModule(symbol); + } + if (symbol.flags & 8 /* EnumMember */) { + return getTypeOfEnumMember(symbol); + } + if (symbol.flags & 98304 /* Accessor */) { + return getTypeOfAccessors(symbol); + } + if (symbol.flags & 2097152 /* Alias */) { + return getTypeOfAlias(symbol); + } + return errorType; + } + function isReferenceToType(type, target) { + return type !== undefined + && target !== undefined + && (ts.getObjectFlags(type) & 4 /* Reference */) !== 0 + && type.target === target; + } + function getTargetType(type) { + return ts.getObjectFlags(type) & 4 /* Reference */ ? type.target : type; + } + // TODO: GH#18217 If `checkBase` is undefined, we should not call this because this will always return false. + function hasBaseType(type, checkBase) { + return check(type); + function check(type) { + if (ts.getObjectFlags(type) & (3 /* ClassOrInterface */ | 4 /* Reference */)) { + var target = getTargetType(type); + return target === checkBase || ts.some(getBaseTypes(target), check); + } + else if (type.flags & 2097152 /* Intersection */) { + return ts.some(type.types, check); + } + return false; + } + } + // Appends the type parameters given by a list of declarations to a set of type parameters and returns the resulting set. + // The function allocates a new array if the input type parameter set is undefined, but otherwise it modifies the set + // in-place and returns the same array. + function appendTypeParameters(typeParameters, declarations) { + for (var _i = 0, declarations_2 = declarations; _i < declarations_2.length; _i++) { + var declaration = declarations_2[_i]; + typeParameters = ts.appendIfUnique(typeParameters, getDeclaredTypeOfTypeParameter(getSymbolOfNode(declaration))); + } + return typeParameters; + } + // Return the outer type parameters of a node or undefined if the node has no outer type parameters. + function getOuterTypeParameters(node, includeThisTypes) { + while (true) { + node = node.parent; // TODO: GH#18217 Use SourceFile kind check instead + if (!node) { + return undefined; + } + switch (node.kind) { + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 241 /* InterfaceDeclaration */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 155 /* MethodSignature */: + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + case 289 /* JSDocFunctionType */: + case 239 /* FunctionDeclaration */: + case 156 /* MethodDeclaration */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 242 /* TypeAliasDeclaration */: + case 303 /* JSDocTemplateTag */: + case 304 /* JSDocTypedefTag */: + case 297 /* JSDocCallbackTag */: + case 181 /* MappedType */: + case 175 /* ConditionalType */: + var outerTypeParameters = getOuterTypeParameters(node, includeThisTypes); + if (node.kind === 181 /* MappedType */) { + return ts.append(outerTypeParameters, getDeclaredTypeOfTypeParameter(getSymbolOfNode(node.typeParameter))); + } + else if (node.kind === 175 /* ConditionalType */) { + return ts.concatenate(outerTypeParameters, getInferTypeParameters(node)); + } + var outerAndOwnTypeParameters = appendTypeParameters(outerTypeParameters, ts.getEffectiveTypeParameterDeclarations(node)); + var thisType = includeThisTypes && + (node.kind === 240 /* ClassDeclaration */ || node.kind === 209 /* ClassExpression */ || node.kind === 241 /* InterfaceDeclaration */) && + getDeclaredTypeOfClassOrInterface(getSymbolOfNode(node)).thisType; + return thisType ? ts.append(outerAndOwnTypeParameters, thisType) : outerAndOwnTypeParameters; + } + } + } + // The outer type parameters are those defined by enclosing generic classes, methods, or functions. + function getOuterTypeParametersOfClassOrInterface(symbol) { + var declaration = symbol.flags & 32 /* Class */ ? symbol.valueDeclaration : ts.getDeclarationOfKind(symbol, 241 /* InterfaceDeclaration */); + return getOuterTypeParameters(declaration); + } + // The local type parameters are the combined set of type parameters from all declarations of the class, + // interface, or type alias. + function getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) { + var result; + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var node = _a[_i]; + if (node.kind === 241 /* InterfaceDeclaration */ || + node.kind === 240 /* ClassDeclaration */ || + node.kind === 209 /* ClassExpression */ || + ts.isTypeAlias(node)) { + var declaration = node; + result = appendTypeParameters(result, ts.getEffectiveTypeParameterDeclarations(declaration)); + } + } + return result; + } + // The full set of type parameters for a generic class or interface type consists of its outer type parameters plus + // its locally declared type parameters. + function getTypeParametersOfClassOrInterface(symbol) { + return ts.concatenate(getOuterTypeParametersOfClassOrInterface(symbol), getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol)); + } + // A type is a mixin constructor if it has a single construct signature taking no type parameters and a single + // rest parameter of type any[]. + function isMixinConstructorType(type) { + var signatures = getSignaturesOfType(type, 1 /* Construct */); + if (signatures.length === 1) { + var s = signatures[0]; + return !s.typeParameters && s.parameters.length === 1 && s.hasRestParameter && getTypeOfParameter(s.parameters[0]) === anyArrayType; + } + return false; + } + function isConstructorType(type) { + if (isValidBaseType(type) && getSignaturesOfType(type, 1 /* Construct */).length > 0) { + return true; + } + if (type.flags & 8650752 /* TypeVariable */) { + var constraint = getBaseConstraintOfType(type); + return !!constraint && isValidBaseType(constraint) && isMixinConstructorType(constraint); + } + return isJSConstructorType(type); + } + function getBaseTypeNodeOfClass(type) { + return ts.getEffectiveBaseTypeNode(type.symbol.valueDeclaration); + } + function getConstructorsForTypeArguments(type, typeArgumentNodes, location) { + var typeArgCount = ts.length(typeArgumentNodes); + var isJavascript = ts.isInJSFile(location); + return ts.filter(getSignaturesOfType(type, 1 /* Construct */), function (sig) { return (isJavascript || typeArgCount >= getMinTypeArgumentCount(sig.typeParameters)) && typeArgCount <= ts.length(sig.typeParameters); }); + } + function getInstantiatedConstructorsForTypeArguments(type, typeArgumentNodes, location) { + var signatures = getConstructorsForTypeArguments(type, typeArgumentNodes, location); + var typeArguments = ts.map(typeArgumentNodes, getTypeFromTypeNode); + return ts.sameMap(signatures, function (sig) { return ts.some(sig.typeParameters) ? getSignatureInstantiation(sig, typeArguments, ts.isInJSFile(location)) : sig; }); + } + /** + * The base constructor of a class can resolve to + * * undefinedType if the class has no extends clause, + * * unknownType if an error occurred during resolution of the extends expression, + * * nullType if the extends expression is the null value, + * * anyType if the extends expression has type any, or + * * an object type with at least one construct signature. + */ + function getBaseConstructorTypeOfClass(type) { + if (!type.resolvedBaseConstructorType) { + var decl = type.symbol.valueDeclaration; + var extended = ts.getEffectiveBaseTypeNode(decl); + var baseTypeNode = getBaseTypeNodeOfClass(type); + if (!baseTypeNode) { + return type.resolvedBaseConstructorType = undefinedType; + } + if (!pushTypeResolution(type, 1 /* ResolvedBaseConstructorType */)) { + return errorType; + } + var baseConstructorType = checkExpression(baseTypeNode.expression); + if (extended && baseTypeNode !== extended) { + ts.Debug.assert(!extended.typeArguments); // Because this is in a JS file, and baseTypeNode is in an @extends tag + checkExpression(extended.expression); + } + if (baseConstructorType.flags & (524288 /* Object */ | 2097152 /* Intersection */)) { + // Resolving the members of a class requires us to resolve the base class of that class. + // We force resolution here such that we catch circularities now. + resolveStructuredTypeMembers(baseConstructorType); + } + if (!popTypeResolution()) { + error(type.symbol.valueDeclaration, ts.Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_base_expression, symbolToString(type.symbol)); + return type.resolvedBaseConstructorType = errorType; + } + if (!(baseConstructorType.flags & 1 /* Any */) && baseConstructorType !== nullWideningType && !isConstructorType(baseConstructorType)) { + var err = error(baseTypeNode.expression, ts.Diagnostics.Type_0_is_not_a_constructor_function_type, typeToString(baseConstructorType)); + if (baseConstructorType.flags & 262144 /* TypeParameter */) { + var constraint = getConstraintFromTypeParameter(baseConstructorType); + var ctorReturn = unknownType; + if (constraint) { + var ctorSig = getSignaturesOfType(constraint, 1 /* Construct */); + if (ctorSig[0]) { + ctorReturn = getReturnTypeOfSignature(ctorSig[0]); + } + } + addRelatedInfo(err, ts.createDiagnosticForNode(baseConstructorType.symbol.declarations[0], ts.Diagnostics.Did_you_mean_for_0_to_be_constrained_to_type_new_args_Colon_any_1, symbolToString(baseConstructorType.symbol), typeToString(ctorReturn))); + } + return type.resolvedBaseConstructorType = errorType; + } + type.resolvedBaseConstructorType = baseConstructorType; + } + return type.resolvedBaseConstructorType; + } + function getBaseTypes(type) { + if (!type.resolvedBaseTypes) { + if (type.objectFlags & 8 /* Tuple */) { + type.resolvedBaseTypes = [createArrayType(getUnionType(type.typeParameters || ts.emptyArray))]; + } + else if (type.symbol.flags & (32 /* Class */ | 64 /* Interface */)) { + if (type.symbol.flags & 32 /* Class */) { + resolveBaseTypesOfClass(type); + } + if (type.symbol.flags & 64 /* Interface */) { + resolveBaseTypesOfInterface(type); + } + } + else { + ts.Debug.fail("type must be class or interface"); + } + } + return type.resolvedBaseTypes; + } + function resolveBaseTypesOfClass(type) { + type.resolvedBaseTypes = ts.resolvingEmptyArray; + var baseConstructorType = getApparentType(getBaseConstructorTypeOfClass(type)); + if (!(baseConstructorType.flags & (524288 /* Object */ | 2097152 /* Intersection */ | 1 /* Any */))) { + return type.resolvedBaseTypes = ts.emptyArray; + } + var baseTypeNode = getBaseTypeNodeOfClass(type); + var typeArgs = typeArgumentsFromTypeReferenceNode(baseTypeNode); + var baseType; + var originalBaseType = isJSConstructorType(baseConstructorType) ? baseConstructorType : + baseConstructorType.symbol ? getDeclaredTypeOfSymbol(baseConstructorType.symbol) : + undefined; + if (baseConstructorType.symbol && baseConstructorType.symbol.flags & 32 /* Class */ && + areAllOuterTypeParametersApplied(originalBaseType)) { + // When base constructor type is a class with no captured type arguments we know that the constructors all have the same type parameters as the + // class and all return the instance type of the class. There is no need for further checks and we can apply the + // type arguments in the same manner as a type reference to get the same error reporting experience. + baseType = getTypeFromClassOrInterfaceReference(baseTypeNode, baseConstructorType.symbol, typeArgs); + } + else if (baseConstructorType.flags & 1 /* Any */) { + baseType = baseConstructorType; + } + else if (isJSConstructorType(baseConstructorType)) { + baseType = !baseTypeNode.typeArguments && getJSClassType(baseConstructorType.symbol) || anyType; + } + else { + // The class derives from a "class-like" constructor function, check that we have at least one construct signature + // with a matching number of type parameters and use the return type of the first instantiated signature. Elsewhere + // we check that all instantiated signatures return the same type. + var constructors = getInstantiatedConstructorsForTypeArguments(baseConstructorType, baseTypeNode.typeArguments, baseTypeNode); + if (!constructors.length) { + error(baseTypeNode.expression, ts.Diagnostics.No_base_constructor_has_the_specified_number_of_type_arguments); + return type.resolvedBaseTypes = ts.emptyArray; + } + baseType = getReturnTypeOfSignature(constructors[0]); + } + if (baseType === errorType) { + return type.resolvedBaseTypes = ts.emptyArray; + } + if (!isValidBaseType(baseType)) { + error(baseTypeNode.expression, ts.Diagnostics.Base_constructor_return_type_0_is_not_an_object_type_or_intersection_of_object_types_with_statically_known_members, typeToString(baseType)); + return type.resolvedBaseTypes = ts.emptyArray; + } + if (type === baseType || hasBaseType(baseType, type)) { + error(type.symbol.valueDeclaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, /*enclosingDeclaration*/ undefined, 2 /* WriteArrayAsGenericType */)); + return type.resolvedBaseTypes = ts.emptyArray; + } + if (type.resolvedBaseTypes === ts.resolvingEmptyArray) { + // Circular reference, likely through instantiation of default parameters + // (otherwise there'd be an error from hasBaseType) - this is fine, but `.members` should be reset + // as `getIndexedAccessType` via `instantiateType` via `getTypeFromClassOrInterfaceReference` forces a + // partial instantiation of the members without the base types fully resolved + type.members = undefined; + } + return type.resolvedBaseTypes = [baseType]; + } + function areAllOuterTypeParametersApplied(type) { + // An unapplied type parameter has its symbol still the same as the matching argument symbol. + // Since parameters are applied outer-to-inner, only the last outer parameter needs to be checked. + var outerTypeParameters = type.outerTypeParameters; + if (outerTypeParameters) { + var last_1 = outerTypeParameters.length - 1; + var typeArguments = type.typeArguments; + return outerTypeParameters[last_1].symbol !== typeArguments[last_1].symbol; + } + return true; + } + // A valid base type is `any`, any non-generic object type or intersection of non-generic + // object types. + function isValidBaseType(type) { + return !!(type.flags & (524288 /* Object */ | 67108864 /* NonPrimitive */ | 1 /* Any */)) && !isGenericMappedType(type) || + !!(type.flags & 2097152 /* Intersection */) && ts.every(type.types, isValidBaseType); + } + function resolveBaseTypesOfInterface(type) { + type.resolvedBaseTypes = type.resolvedBaseTypes || ts.emptyArray; + for (var _i = 0, _a = type.symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (declaration.kind === 241 /* InterfaceDeclaration */ && ts.getInterfaceBaseTypeNodes(declaration)) { + for (var _b = 0, _c = ts.getInterfaceBaseTypeNodes(declaration); _b < _c.length; _b++) { + var node = _c[_b]; + var baseType = getTypeFromTypeNode(node); + if (baseType !== errorType) { + if (isValidBaseType(baseType)) { + if (type !== baseType && !hasBaseType(baseType, type)) { + if (type.resolvedBaseTypes === ts.emptyArray) { + type.resolvedBaseTypes = [baseType]; + } + else { + type.resolvedBaseTypes.push(baseType); + } + } + else { + error(declaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, /*enclosingDeclaration*/ undefined, 2 /* WriteArrayAsGenericType */)); + } + } + else { + error(node, ts.Diagnostics.An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_members); + } + } + } + } + } + } + /** + * Returns true if the interface given by the symbol is free of "this" references. + * + * Specifically, the result is true if the interface itself contains no references + * to "this" in its body, if all base types are interfaces, + * and if none of the base interfaces have a "this" type. + */ + function isThislessInterface(symbol) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (declaration.kind === 241 /* InterfaceDeclaration */) { + if (declaration.flags & 64 /* ContainsThis */) { + return false; + } + var baseTypeNodes = ts.getInterfaceBaseTypeNodes(declaration); + if (baseTypeNodes) { + for (var _b = 0, baseTypeNodes_1 = baseTypeNodes; _b < baseTypeNodes_1.length; _b++) { + var node = baseTypeNodes_1[_b]; + if (ts.isEntityNameExpression(node.expression)) { + var baseSymbol = resolveEntityName(node.expression, 67897832 /* Type */, /*ignoreErrors*/ true); + if (!baseSymbol || !(baseSymbol.flags & 64 /* Interface */) || getDeclaredTypeOfClassOrInterface(baseSymbol).thisType) { + return false; + } + } + } + } + } + } + return true; + } + function getDeclaredTypeOfClassOrInterface(symbol) { + var links = getSymbolLinks(symbol); + if (!links.declaredType) { + var kind = symbol.flags & 32 /* Class */ ? 1 /* Class */ : 2 /* Interface */; + var type = links.declaredType = createObjectType(kind, symbol); + var outerTypeParameters = getOuterTypeParametersOfClassOrInterface(symbol); + var localTypeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); + // A class or interface is generic if it has type parameters or a "this" type. We always give classes a "this" type + // because it is not feasible to analyze all members to determine if the "this" type escapes the class (in particular, + // property types inferred from initializers and method return types inferred from return statements are very hard + // to exhaustively analyze). We give interfaces a "this" type if we can't definitely determine that they are free of + // "this" references. + if (outerTypeParameters || localTypeParameters || kind === 1 /* Class */ || !isThislessInterface(symbol)) { + type.objectFlags |= 4 /* Reference */; + type.typeParameters = ts.concatenate(outerTypeParameters, localTypeParameters); + type.outerTypeParameters = outerTypeParameters; + type.localTypeParameters = localTypeParameters; + type.instantiations = ts.createMap(); + type.instantiations.set(getTypeListId(type.typeParameters), type); + type.target = type; + type.typeArguments = type.typeParameters; + type.thisType = createType(262144 /* TypeParameter */); + type.thisType.isThisType = true; + type.thisType.symbol = symbol; + type.thisType.constraint = type; + } + } + return links.declaredType; + } + function getDeclaredTypeOfTypeAlias(symbol) { + var links = getSymbolLinks(symbol); + if (!links.declaredType) { + // Note that we use the links object as the target here because the symbol object is used as the unique + // identity for resolution of the 'type' property in SymbolLinks. + if (!pushTypeResolution(symbol, 2 /* DeclaredType */)) { + return errorType; + } + var declaration = ts.find(symbol.declarations, function (d) { + return ts.isJSDocTypeAlias(d) || d.kind === 242 /* TypeAliasDeclaration */; + }); + var typeNode = ts.isJSDocTypeAlias(declaration) ? declaration.typeExpression : declaration.type; + // If typeNode is missing, we will error in checkJSDocTypedefTag. + var type = typeNode ? getTypeFromTypeNode(typeNode) : errorType; + if (popTypeResolution()) { + var typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); + if (typeParameters) { + // Initialize the instantiation cache for generic type aliases. The declared type corresponds to + // an instantiation of the type alias with the type parameters supplied as type arguments. + links.typeParameters = typeParameters; + links.instantiations = ts.createMap(); + links.instantiations.set(getTypeListId(typeParameters), type); + } + } + else { + type = errorType; + error(declaration.name, ts.Diagnostics.Type_alias_0_circularly_references_itself, symbolToString(symbol)); + } + links.declaredType = type; + } + return links.declaredType; + } + function isStringConcatExpression(expr) { + if (expr.kind === 10 /* StringLiteral */) { + return true; + } + else if (expr.kind === 204 /* BinaryExpression */) { + return isStringConcatExpression(expr.left) && isStringConcatExpression(expr.right); + } + return false; + } + function isLiteralEnumMember(member) { + var expr = member.initializer; + if (!expr) { + return !(member.flags & 4194304 /* Ambient */); + } + switch (expr.kind) { + case 10 /* StringLiteral */: + case 8 /* NumericLiteral */: + return true; + case 202 /* PrefixUnaryExpression */: + return expr.operator === 39 /* MinusToken */ && + expr.operand.kind === 8 /* NumericLiteral */; + case 72 /* Identifier */: + return ts.nodeIsMissing(expr) || !!getSymbolOfNode(member.parent).exports.get(expr.escapedText); + case 204 /* BinaryExpression */: + return isStringConcatExpression(expr); + default: + return false; + } + } + function getEnumKind(symbol) { + var links = getSymbolLinks(symbol); + if (links.enumKind !== undefined) { + return links.enumKind; + } + var hasNonLiteralMember = false; + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (declaration.kind === 243 /* EnumDeclaration */) { + for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { + var member = _c[_b]; + if (member.initializer && member.initializer.kind === 10 /* StringLiteral */) { + return links.enumKind = 1 /* Literal */; + } + if (!isLiteralEnumMember(member)) { + hasNonLiteralMember = true; + } + } + } + } + return links.enumKind = hasNonLiteralMember ? 0 /* Numeric */ : 1 /* Literal */; + } + function getBaseTypeOfEnumLiteralType(type) { + return type.flags & 1024 /* EnumLiteral */ && !(type.flags & 1048576 /* Union */) ? getDeclaredTypeOfSymbol(getParentOfSymbol(type.symbol)) : type; + } + function getDeclaredTypeOfEnum(symbol) { + var links = getSymbolLinks(symbol); + if (links.declaredType) { + return links.declaredType; + } + if (getEnumKind(symbol) === 1 /* Literal */) { + enumCount++; + var memberTypeList = []; + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (declaration.kind === 243 /* EnumDeclaration */) { + for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { + var member = _c[_b]; + var memberType = getFreshTypeOfLiteralType(getLiteralType(getEnumMemberValue(member), enumCount, getSymbolOfNode(member))); // TODO: GH#18217 + getSymbolLinks(getSymbolOfNode(member)).declaredType = memberType; + memberTypeList.push(getRegularTypeOfLiteralType(memberType)); + } + } + } + if (memberTypeList.length) { + var enumType_1 = getUnionType(memberTypeList, 1 /* Literal */, symbol, /*aliasTypeArguments*/ undefined); + if (enumType_1.flags & 1048576 /* Union */) { + enumType_1.flags |= 1024 /* EnumLiteral */; + enumType_1.symbol = symbol; + } + return links.declaredType = enumType_1; + } + } + var enumType = createType(32 /* Enum */); + enumType.symbol = symbol; + return links.declaredType = enumType; + } + function getDeclaredTypeOfEnumMember(symbol) { + var links = getSymbolLinks(symbol); + if (!links.declaredType) { + var enumType = getDeclaredTypeOfEnum(getParentOfSymbol(symbol)); + if (!links.declaredType) { + links.declaredType = enumType; + } + } + return links.declaredType; + } + function getDeclaredTypeOfTypeParameter(symbol) { + var links = getSymbolLinks(symbol); + if (!links.declaredType) { + var type = createType(262144 /* TypeParameter */); + type.symbol = symbol; + links.declaredType = type; + } + return links.declaredType; + } + function getDeclaredTypeOfAlias(symbol) { + var links = getSymbolLinks(symbol); + if (!links.declaredType) { + links.declaredType = getDeclaredTypeOfSymbol(resolveAlias(symbol)); + } + return links.declaredType; + } + function getDeclaredTypeOfSymbol(symbol) { + return tryGetDeclaredTypeOfSymbol(symbol) || errorType; + } + function tryGetDeclaredTypeOfSymbol(symbol) { + if (symbol.flags & (32 /* Class */ | 64 /* Interface */)) { + return getDeclaredTypeOfClassOrInterface(symbol); + } + if (symbol.flags & 524288 /* TypeAlias */) { + return getDeclaredTypeOfTypeAlias(symbol); + } + if (symbol.flags & 262144 /* TypeParameter */) { + return getDeclaredTypeOfTypeParameter(symbol); + } + if (symbol.flags & 384 /* Enum */) { + return getDeclaredTypeOfEnum(symbol); + } + if (symbol.flags & 8 /* EnumMember */) { + return getDeclaredTypeOfEnumMember(symbol); + } + if (symbol.flags & 2097152 /* Alias */) { + return getDeclaredTypeOfAlias(symbol); + } + return undefined; + } + /** + * A type is free of this references if it's the any, string, number, boolean, symbol, or void keyword, a string + * literal type, an array with an element type that is free of this references, or a type reference that is + * free of this references. + */ + function isThislessType(node) { + switch (node.kind) { + case 120 /* AnyKeyword */: + case 143 /* UnknownKeyword */: + case 138 /* StringKeyword */: + case 135 /* NumberKeyword */: + case 146 /* BigIntKeyword */: + case 123 /* BooleanKeyword */: + case 139 /* SymbolKeyword */: + case 136 /* ObjectKeyword */: + case 106 /* VoidKeyword */: + case 141 /* UndefinedKeyword */: + case 96 /* NullKeyword */: + case 132 /* NeverKeyword */: + case 182 /* LiteralType */: + return true; + case 169 /* ArrayType */: + return isThislessType(node.elementType); + case 164 /* TypeReference */: + return !node.typeArguments || node.typeArguments.every(isThislessType); + } + return false; + } + /** A type parameter is thisless if its contraint is thisless, or if it has no constraint. */ + function isThislessTypeParameter(node) { + var constraint = ts.getEffectiveConstraintOfTypeParameter(node); + return !constraint || isThislessType(constraint); + } + /** + * A variable-like declaration is free of this references if it has a type annotation + * that is thisless, or if it has no type annotation and no initializer (and is thus of type any). + */ + function isThislessVariableLikeDeclaration(node) { + var typeNode = ts.getEffectiveTypeAnnotationNode(node); + return typeNode ? isThislessType(typeNode) : !ts.hasInitializer(node); + } + /** + * A function-like declaration is considered free of `this` references if it has a return type + * annotation that is free of this references and if each parameter is thisless and if + * each type parameter (if present) is thisless. + */ + function isThislessFunctionLikeDeclaration(node) { + var returnType = ts.getEffectiveReturnTypeNode(node); + var typeParameters = ts.getEffectiveTypeParameterDeclarations(node); + return (node.kind === 157 /* Constructor */ || (!!returnType && isThislessType(returnType))) && + node.parameters.every(isThislessVariableLikeDeclaration) && + typeParameters.every(isThislessTypeParameter); + } + /** + * Returns true if the class or interface member given by the symbol is free of "this" references. The + * function may return false for symbols that are actually free of "this" references because it is not + * feasible to perform a complete analysis in all cases. In particular, property members with types + * inferred from their initializers and function members with inferred return types are conservatively + * assumed not to be free of "this" references. + */ + function isThisless(symbol) { + if (symbol.declarations && symbol.declarations.length === 1) { + var declaration = symbol.declarations[0]; + if (declaration) { + switch (declaration.kind) { + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + return isThislessVariableLikeDeclaration(declaration); + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 157 /* Constructor */: + return isThislessFunctionLikeDeclaration(declaration); + } + } + } + return false; + } + // The mappingThisOnly flag indicates that the only type parameter being mapped is "this". When the flag is true, + // we check symbols to see if we can quickly conclude they are free of "this" references, thus needing no instantiation. + function createInstantiatedSymbolTable(symbols, mapper, mappingThisOnly) { + var result = ts.createSymbolTable(); + for (var _i = 0, symbols_2 = symbols; _i < symbols_2.length; _i++) { + var symbol = symbols_2[_i]; + result.set(symbol.escapedName, mappingThisOnly && isThisless(symbol) ? symbol : instantiateSymbol(symbol, mapper)); + } + return result; + } + function addInheritedMembers(symbols, baseSymbols) { + for (var _i = 0, baseSymbols_1 = baseSymbols; _i < baseSymbols_1.length; _i++) { + var s = baseSymbols_1[_i]; + if (!symbols.has(s.escapedName)) { + symbols.set(s.escapedName, s); + } + } + } + function resolveDeclaredMembers(type) { + if (!type.declaredProperties) { + var symbol = type.symbol; + var members = getMembersOfSymbol(symbol); + type.declaredProperties = getNamedMembers(members); + // Start with signatures at empty array in case of recursive types + type.declaredCallSignatures = ts.emptyArray; + type.declaredConstructSignatures = ts.emptyArray; + type.declaredCallSignatures = getSignaturesOfSymbol(members.get("__call" /* Call */)); + type.declaredConstructSignatures = getSignaturesOfSymbol(members.get("__new" /* New */)); + type.declaredStringIndexInfo = getIndexInfoOfSymbol(symbol, 0 /* String */); + type.declaredNumberIndexInfo = getIndexInfoOfSymbol(symbol, 1 /* Number */); + } + return type; + } + /** + * Indicates whether a type can be used as a late-bound name. + */ + function isTypeUsableAsLateBoundName(type) { + return !!(type.flags & 8576 /* StringOrNumberLiteralOrUnique */); + } + /** + * Indicates whether a declaration name is definitely late-bindable. + * A declaration name is only late-bindable if: + * - It is a `ComputedPropertyName`. + * - Its expression is an `Identifier` or either a `PropertyAccessExpression` an + * `ElementAccessExpression` consisting only of these same three types of nodes. + * - The type of its expression is a string or numeric literal type, or is a `unique symbol` type. + */ + function isLateBindableName(node) { + return ts.isComputedPropertyName(node) + && ts.isEntityNameExpression(node.expression) + && isTypeUsableAsLateBoundName(checkComputedPropertyName(node)); + } + function isLateBoundName(name) { + return name.charCodeAt(0) === 95 /* _ */ && + name.charCodeAt(1) === 95 /* _ */ && + name.charCodeAt(2) === 64 /* at */; + } + /** + * Indicates whether a declaration has a late-bindable dynamic name. + */ + function hasLateBindableName(node) { + var name = ts.getNameOfDeclaration(node); + return !!name && isLateBindableName(name); + } + /** + * Indicates whether a declaration has a dynamic name that cannot be late-bound. + */ + function hasNonBindableDynamicName(node) { + return ts.hasDynamicName(node) && !hasLateBindableName(node); + } + /** + * Indicates whether a declaration name is a dynamic name that cannot be late-bound. + */ + function isNonBindableDynamicName(node) { + return ts.isDynamicName(node) && !isLateBindableName(node); + } + /** + * Gets the symbolic name for a late-bound member from its type. + */ + function getLateBoundNameFromType(type) { + if (type.flags & 8192 /* UniqueESSymbol */) { + return "__@" + type.symbol.escapedName + "@" + getSymbolId(type.symbol); + } + if (type.flags & (128 /* StringLiteral */ | 256 /* NumberLiteral */)) { + return ts.escapeLeadingUnderscores("" + type.value); + } + return ts.Debug.fail(); + } + /** + * Adds a declaration to a late-bound dynamic member. This performs the same function for + * late-bound members that `addDeclarationToSymbol` in binder.ts performs for early-bound + * members. + */ + function addDeclarationToLateBoundSymbol(symbol, member, symbolFlags) { + ts.Debug.assert(!!(ts.getCheckFlags(symbol) & 1024 /* Late */), "Expected a late-bound symbol."); + symbol.flags |= symbolFlags; + getSymbolLinks(member.symbol).lateSymbol = symbol; + if (!symbol.declarations) { + symbol.declarations = [member]; + } + else { + symbol.declarations.push(member); + } + if (symbolFlags & 67220415 /* Value */) { + if (!symbol.valueDeclaration || symbol.valueDeclaration.kind !== member.kind) { + symbol.valueDeclaration = member; + } + } + } + /** + * Performs late-binding of a dynamic member. This performs the same function for + * late-bound members that `declareSymbol` in binder.ts performs for early-bound + * members. + * + * If a symbol is a dynamic name from a computed property, we perform an additional "late" + * binding phase to attempt to resolve the name for the symbol from the type of the computed + * property's expression. If the type of the expression is a string-literal, numeric-literal, + * or unique symbol type, we can use that type as the name of the symbol. + * + * For example, given: + * + * const x = Symbol(); + * + * interface I { + * [x]: number; + * } + * + * The binder gives the property `[x]: number` a special symbol with the name "__computed". + * In the late-binding phase we can type-check the expression `x` and see that it has a + * unique symbol type which we can then use as the name of the member. This allows users + * to define custom symbols that can be used in the members of an object type. + * + * @param parent The containing symbol for the member. + * @param earlySymbols The early-bound symbols of the parent. + * @param lateSymbols The late-bound symbols of the parent. + * @param decl The member to bind. + */ + function lateBindMember(parent, earlySymbols, lateSymbols, decl) { + ts.Debug.assert(!!decl.symbol, "The member is expected to have a symbol."); + var links = getNodeLinks(decl); + if (!links.resolvedSymbol) { + // In the event we attempt to resolve the late-bound name of this member recursively, + // fall back to the early-bound name of this member. + links.resolvedSymbol = decl.symbol; + var type = checkComputedPropertyName(decl.name); + if (isTypeUsableAsLateBoundName(type)) { + var memberName = getLateBoundNameFromType(type); + var symbolFlags = decl.symbol.flags; + // Get or add a late-bound symbol for the member. This allows us to merge late-bound accessor declarations. + var lateSymbol = lateSymbols.get(memberName); + if (!lateSymbol) + lateSymbols.set(memberName, lateSymbol = createSymbol(0 /* None */, memberName, 1024 /* Late */)); + // Report an error if a late-bound member has the same name as an early-bound member, + // or if we have another early-bound symbol declaration with the same name and + // conflicting flags. + var earlySymbol = earlySymbols && earlySymbols.get(memberName); + if (lateSymbol.flags & getExcludedSymbolFlags(symbolFlags) || earlySymbol) { + // If we have an existing early-bound member, combine its declarations so that we can + // report an error at each declaration. + var declarations = earlySymbol ? ts.concatenate(earlySymbol.declarations, lateSymbol.declarations) : lateSymbol.declarations; + var name_2 = ts.declarationNameToString(decl.name); + ts.forEach(declarations, function (declaration) { return error(ts.getNameOfDeclaration(declaration) || declaration, ts.Diagnostics.Duplicate_declaration_0, name_2); }); + error(decl.name || decl, ts.Diagnostics.Duplicate_declaration_0, name_2); + lateSymbol = createSymbol(0 /* None */, memberName, 1024 /* Late */); + } + lateSymbol.nameType = type; + addDeclarationToLateBoundSymbol(lateSymbol, decl, symbolFlags); + if (lateSymbol.parent) { + ts.Debug.assert(lateSymbol.parent === parent, "Existing symbol parent should match new one"); + } + else { + lateSymbol.parent = parent; + } + return links.resolvedSymbol = lateSymbol; + } + } + return links.resolvedSymbol; + } + function getResolvedMembersOrExportsOfSymbol(symbol, resolutionKind) { + var links = getSymbolLinks(symbol); + if (!links[resolutionKind]) { + var isStatic = resolutionKind === "resolvedExports" /* resolvedExports */; + var earlySymbols = !isStatic ? symbol.members : + symbol.flags & 1536 /* Module */ ? getExportsOfModuleWorker(symbol) : + symbol.exports; + // In the event we recursively resolve the members/exports of the symbol, we + // set the initial value of resolvedMembers/resolvedExports to the early-bound + // members/exports of the symbol. + links[resolutionKind] = earlySymbols || emptySymbols; + // fill in any as-yet-unresolved late-bound members. + var lateSymbols = ts.createSymbolTable(); + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + var members = ts.getMembersOfDeclaration(decl); + if (members) { + for (var _b = 0, members_4 = members; _b < members_4.length; _b++) { + var member = members_4[_b]; + if (isStatic === ts.hasStaticModifier(member) && hasLateBindableName(member)) { + lateBindMember(symbol, earlySymbols, lateSymbols, member); + } + } + } + } + links[resolutionKind] = combineSymbolTables(earlySymbols, lateSymbols) || emptySymbols; + } + return links[resolutionKind]; + } + /** + * Gets a SymbolTable containing both the early- and late-bound members of a symbol. + * + * For a description of late-binding, see `lateBindMember`. + */ + function getMembersOfSymbol(symbol) { + return symbol.flags & 6240 /* LateBindingContainer */ + ? getResolvedMembersOrExportsOfSymbol(symbol, "resolvedMembers" /* resolvedMembers */) + : symbol.members || emptySymbols; + } + /** + * If a symbol is the dynamic name of the member of an object type, get the late-bound + * symbol of the member. + * + * For a description of late-binding, see `lateBindMember`. + */ + function getLateBoundSymbol(symbol) { + if (symbol.flags & 106500 /* ClassMember */ && symbol.escapedName === "__computed" /* Computed */) { + var links = getSymbolLinks(symbol); + if (!links.lateSymbol && ts.some(symbol.declarations, hasLateBindableName)) { + // force late binding of members/exports. This will set the late-bound symbol + if (ts.some(symbol.declarations, ts.hasStaticModifier)) { + getExportsOfSymbol(symbol.parent); + } + else { + getMembersOfSymbol(symbol.parent); + } + } + return links.lateSymbol || (links.lateSymbol = symbol); + } + return symbol; + } + function getTypeWithThisArgument(type, thisArgument, needApparentType) { + if (ts.getObjectFlags(type) & 4 /* Reference */) { + var target = type.target; + var typeArguments = type.typeArguments; + if (ts.length(target.typeParameters) === ts.length(typeArguments)) { + var ref = createTypeReference(target, ts.concatenate(typeArguments, [thisArgument || target.thisType])); + return needApparentType ? getApparentType(ref) : ref; + } + } + else if (type.flags & 2097152 /* Intersection */) { + return getIntersectionType(ts.map(type.types, function (t) { return getTypeWithThisArgument(t, thisArgument, needApparentType); })); + } + return needApparentType ? getApparentType(type) : type; + } + function resolveObjectTypeMembers(type, source, typeParameters, typeArguments) { + var mapper; + var members; + var callSignatures; + var constructSignatures; + var stringIndexInfo; + var numberIndexInfo; + if (ts.rangeEquals(typeParameters, typeArguments, 0, typeParameters.length)) { + mapper = identityMapper; + members = source.symbol ? getMembersOfSymbol(source.symbol) : ts.createSymbolTable(source.declaredProperties); + callSignatures = source.declaredCallSignatures; + constructSignatures = source.declaredConstructSignatures; + stringIndexInfo = source.declaredStringIndexInfo; + numberIndexInfo = source.declaredNumberIndexInfo; + } + else { + mapper = createTypeMapper(typeParameters, typeArguments); + members = createInstantiatedSymbolTable(source.declaredProperties, mapper, /*mappingThisOnly*/ typeParameters.length === 1); + callSignatures = instantiateSignatures(source.declaredCallSignatures, mapper); + constructSignatures = instantiateSignatures(source.declaredConstructSignatures, mapper); + stringIndexInfo = instantiateIndexInfo(source.declaredStringIndexInfo, mapper); + numberIndexInfo = instantiateIndexInfo(source.declaredNumberIndexInfo, mapper); + } + var baseTypes = getBaseTypes(source); + if (baseTypes.length) { + if (source.symbol && members === getMembersOfSymbol(source.symbol)) { + members = ts.createSymbolTable(source.declaredProperties); + } + setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + var thisArgument = ts.lastOrUndefined(typeArguments); + for (var _i = 0, baseTypes_1 = baseTypes; _i < baseTypes_1.length; _i++) { + var baseType = baseTypes_1[_i]; + var instantiatedBaseType = thisArgument ? getTypeWithThisArgument(instantiateType(baseType, mapper), thisArgument) : baseType; + addInheritedMembers(members, getPropertiesOfType(instantiatedBaseType)); + callSignatures = ts.concatenate(callSignatures, getSignaturesOfType(instantiatedBaseType, 0 /* Call */)); + constructSignatures = ts.concatenate(constructSignatures, getSignaturesOfType(instantiatedBaseType, 1 /* Construct */)); + if (!stringIndexInfo) { + stringIndexInfo = instantiatedBaseType === anyType ? + createIndexInfo(anyType, /*isReadonly*/ false) : + getIndexInfoOfType(instantiatedBaseType, 0 /* String */); + } + numberIndexInfo = numberIndexInfo || getIndexInfoOfType(instantiatedBaseType, 1 /* Number */); + } + } + setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + } + function resolveClassOrInterfaceMembers(type) { + resolveObjectTypeMembers(type, resolveDeclaredMembers(type), ts.emptyArray, ts.emptyArray); + } + function resolveTypeReferenceMembers(type) { + var source = resolveDeclaredMembers(type.target); + var typeParameters = ts.concatenate(source.typeParameters, [source.thisType]); + var typeArguments = type.typeArguments && type.typeArguments.length === typeParameters.length ? + type.typeArguments : ts.concatenate(type.typeArguments, [type]); + resolveObjectTypeMembers(type, source, typeParameters, typeArguments); + } + function createSignature(declaration, typeParameters, thisParameter, parameters, resolvedReturnType, resolvedTypePredicate, minArgumentCount, hasRestParameter, hasLiteralTypes) { + var sig = new Signature(checker); + sig.declaration = declaration; + sig.typeParameters = typeParameters; + sig.parameters = parameters; + sig.thisParameter = thisParameter; + sig.resolvedReturnType = resolvedReturnType; + sig.resolvedTypePredicate = resolvedTypePredicate; + sig.minArgumentCount = minArgumentCount; + sig.hasRestParameter = hasRestParameter; + sig.hasLiteralTypes = hasLiteralTypes; + sig.target = undefined; + sig.mapper = undefined; + return sig; + } + function cloneSignature(sig) { + return createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, /*resolvedReturnType*/ undefined, + /*resolvedTypePredicate*/ undefined, sig.minArgumentCount, sig.hasRestParameter, sig.hasLiteralTypes); + } + function getExpandedParameters(sig) { + if (sig.hasRestParameter) { + var restIndex_1 = sig.parameters.length - 1; + var restParameter = sig.parameters[restIndex_1]; + var restType = getTypeOfSymbol(restParameter); + if (isTupleType(restType)) { + var elementTypes = restType.typeArguments || ts.emptyArray; + var minLength_1 = restType.target.minLength; + var tupleRestIndex_1 = restType.target.hasRestElement ? elementTypes.length - 1 : -1; + var restParams = ts.map(elementTypes, function (t, i) { + var name = getParameterNameAtPosition(sig, restIndex_1 + i); + var checkFlags = i === tupleRestIndex_1 ? 8192 /* RestParameter */ : + i >= minLength_1 ? 4096 /* OptionalParameter */ : 0; + var symbol = createSymbol(1 /* FunctionScopedVariable */, name, checkFlags); + symbol.type = i === tupleRestIndex_1 ? createArrayType(t) : t; + return symbol; + }); + return ts.concatenate(sig.parameters.slice(0, restIndex_1), restParams); + } + } + return sig.parameters; + } + function getDefaultConstructSignatures(classType) { + var baseConstructorType = getBaseConstructorTypeOfClass(classType); + var baseSignatures = getSignaturesOfType(baseConstructorType, 1 /* Construct */); + if (baseSignatures.length === 0) { + return [createSignature(undefined, classType.localTypeParameters, undefined, ts.emptyArray, classType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false)]; // TODO: GH#18217 + } + var baseTypeNode = getBaseTypeNodeOfClass(classType); + var isJavaScript = ts.isInJSFile(baseTypeNode); + var typeArguments = typeArgumentsFromTypeReferenceNode(baseTypeNode); + var typeArgCount = ts.length(typeArguments); + var result = []; + for (var _i = 0, baseSignatures_1 = baseSignatures; _i < baseSignatures_1.length; _i++) { + var baseSig = baseSignatures_1[_i]; + var minTypeArgumentCount = getMinTypeArgumentCount(baseSig.typeParameters); + var typeParamCount = ts.length(baseSig.typeParameters); + if (isJavaScript || typeArgCount >= minTypeArgumentCount && typeArgCount <= typeParamCount) { + var sig = typeParamCount ? createSignatureInstantiation(baseSig, fillMissingTypeArguments(typeArguments, baseSig.typeParameters, minTypeArgumentCount, isJavaScript)) : cloneSignature(baseSig); + sig.typeParameters = classType.localTypeParameters; + sig.resolvedReturnType = classType; + result.push(sig); + } + } + return result; + } + function findMatchingSignature(signatureList, signature, partialMatch, ignoreThisTypes, ignoreReturnTypes) { + for (var _i = 0, signatureList_1 = signatureList; _i < signatureList_1.length; _i++) { + var s = signatureList_1[_i]; + if (compareSignaturesIdentical(s, signature, partialMatch, ignoreThisTypes, ignoreReturnTypes, partialMatch ? compareTypesSubtypeOf : compareTypesIdentical)) { + return s; + } + } + } + function findMatchingSignatures(signatureLists, signature, listIndex) { + if (signature.typeParameters) { + // We require an exact match for generic signatures, so we only return signatures from the first + // signature list and only if they have exact matches in the other signature lists. + if (listIndex > 0) { + return undefined; + } + for (var i = 1; i < signatureLists.length; i++) { + if (!findMatchingSignature(signatureLists[i], signature, /*partialMatch*/ false, /*ignoreThisTypes*/ false, /*ignoreReturnTypes*/ false)) { + return undefined; + } + } + return [signature]; + } + var result; + for (var i = 0; i < signatureLists.length; i++) { + // Allow matching non-generic signatures to have excess parameters and different return types + var match = i === listIndex ? signature : findMatchingSignature(signatureLists[i], signature, /*partialMatch*/ true, /*ignoreThisTypes*/ true, /*ignoreReturnTypes*/ true); + if (!match) { + return undefined; + } + result = ts.appendIfUnique(result, match); + } + return result; + } + // The signatures of a union type are those signatures that are present in each of the constituent types. + // Generic signatures must match exactly, but non-generic signatures are allowed to have extra optional + // parameters and may differ in return types. When signatures differ in return types, the resulting return + // type is the union of the constituent return types. + function getUnionSignatures(signatureLists) { + var result; + for (var i = 0; i < signatureLists.length; i++) { + for (var _i = 0, _a = signatureLists[i]; _i < _a.length; _i++) { + var signature = _a[_i]; + // Only process signatures with parameter lists that aren't already in the result list + if (!result || !findMatchingSignature(result, signature, /*partialMatch*/ false, /*ignoreThisTypes*/ true, /*ignoreReturnTypes*/ true)) { + var unionSignatures = findMatchingSignatures(signatureLists, signature, i); + if (unionSignatures) { + var s = signature; + // Union the result types when more than one signature matches + if (unionSignatures.length > 1) { + var thisParameter = signature.thisParameter; + if (ts.forEach(unionSignatures, function (sig) { return sig.thisParameter; })) { + // TODO: GH#18217 We tested that *some* has thisParameter and now act as if *all* do + var thisType = getUnionType(ts.map(unionSignatures, function (sig) { return sig.thisParameter ? getTypeOfSymbol(sig.thisParameter) : anyType; }), 2 /* Subtype */); + thisParameter = createSymbolWithType(signature.thisParameter, thisType); + } + s = cloneSignature(signature); + s.thisParameter = thisParameter; + s.unionSignatures = unionSignatures; + } + (result || (result = [])).push(s); + } + } + } + } + return result || ts.emptyArray; + } + function getUnionIndexInfo(types, kind) { + var indexTypes = []; + var isAnyReadonly = false; + for (var _i = 0, types_2 = types; _i < types_2.length; _i++) { + var type = types_2[_i]; + var indexInfo = getIndexInfoOfType(type, kind); + if (!indexInfo) { + return undefined; + } + indexTypes.push(indexInfo.type); + isAnyReadonly = isAnyReadonly || indexInfo.isReadonly; + } + return createIndexInfo(getUnionType(indexTypes, 2 /* Subtype */), isAnyReadonly); + } + function resolveUnionTypeMembers(type) { + // The members and properties collections are empty for union types. To get all properties of a union + // type use getPropertiesOfType (only the language service uses this). + var callSignatures = getUnionSignatures(ts.map(type.types, function (t) { return getSignaturesOfType(t, 0 /* Call */); })); + var constructSignatures = getUnionSignatures(ts.map(type.types, function (t) { return getSignaturesOfType(t, 1 /* Construct */); })); + var stringIndexInfo = getUnionIndexInfo(type.types, 0 /* String */); + var numberIndexInfo = getUnionIndexInfo(type.types, 1 /* Number */); + setStructuredTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + } + function intersectTypes(type1, type2) { + return !type1 ? type2 : !type2 ? type1 : getIntersectionType([type1, type2]); + } + function intersectIndexInfos(info1, info2) { + return !info1 ? info2 : !info2 ? info1 : createIndexInfo(getIntersectionType([info1.type, info2.type]), info1.isReadonly && info2.isReadonly); + } + function unionSpreadIndexInfos(info1, info2) { + return info1 && info2 && createIndexInfo(getUnionType([info1.type, info2.type]), info1.isReadonly || info2.isReadonly); + } + function includeMixinType(type, types, index) { + var mixedTypes = []; + for (var i = 0; i < types.length; i++) { + if (i === index) { + mixedTypes.push(type); + } + else if (isMixinConstructorType(types[i])) { + mixedTypes.push(getReturnTypeOfSignature(getSignaturesOfType(types[i], 1 /* Construct */)[0])); + } + } + return getIntersectionType(mixedTypes); + } + function resolveIntersectionTypeMembers(type) { + // The members and properties collections are empty for intersection types. To get all properties of an + // intersection type use getPropertiesOfType (only the language service uses this). + var callSignatures = ts.emptyArray; + var constructSignatures = ts.emptyArray; + var stringIndexInfo; + var numberIndexInfo; + var types = type.types; + var mixinCount = ts.countWhere(types, isMixinConstructorType); + var _loop_5 = function (i) { + var t = type.types[i]; + // When an intersection type contains mixin constructor types, the construct signatures from + // those types are discarded and their return types are mixed into the return types of all + // other construct signatures in the intersection type. For example, the intersection type + // '{ new(...args: any[]) => A } & { new(s: string) => B }' has a single construct signature + // 'new(s: string) => A & B'. + if (mixinCount === 0 || mixinCount === types.length && i === 0 || !isMixinConstructorType(t)) { + var signatures = getSignaturesOfType(t, 1 /* Construct */); + if (signatures.length && mixinCount > 0) { + signatures = ts.map(signatures, function (s) { + var clone = cloneSignature(s); + clone.resolvedReturnType = includeMixinType(getReturnTypeOfSignature(s), types, i); + return clone; + }); + } + constructSignatures = ts.concatenate(constructSignatures, signatures); + } + callSignatures = ts.concatenate(callSignatures, getSignaturesOfType(t, 0 /* Call */)); + stringIndexInfo = intersectIndexInfos(stringIndexInfo, getIndexInfoOfType(t, 0 /* String */)); + numberIndexInfo = intersectIndexInfos(numberIndexInfo, getIndexInfoOfType(t, 1 /* Number */)); + }; + for (var i = 0; i < types.length; i++) { + _loop_5(i); + } + setStructuredTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + } + /** + * Converts an AnonymousType to a ResolvedType. + */ + function resolveAnonymousTypeMembers(type) { + var symbol = type.symbol; + if (type.target) { + setStructuredTypeMembers(type, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + var members = createInstantiatedSymbolTable(getPropertiesOfObjectType(type.target), type.mapper, /*mappingThisOnly*/ false); + var callSignatures = instantiateSignatures(getSignaturesOfType(type.target, 0 /* Call */), type.mapper); + var constructSignatures = instantiateSignatures(getSignaturesOfType(type.target, 1 /* Construct */), type.mapper); + var stringIndexInfo = instantiateIndexInfo(getIndexInfoOfType(type.target, 0 /* String */), type.mapper); + var numberIndexInfo = instantiateIndexInfo(getIndexInfoOfType(type.target, 1 /* Number */), type.mapper); + setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + } + else if (symbol.flags & 2048 /* TypeLiteral */) { + setStructuredTypeMembers(type, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + var members = getMembersOfSymbol(symbol); + var callSignatures = getSignaturesOfSymbol(members.get("__call" /* Call */)); + var constructSignatures = getSignaturesOfSymbol(members.get("__new" /* New */)); + var stringIndexInfo = getIndexInfoOfSymbol(symbol, 0 /* String */); + var numberIndexInfo = getIndexInfoOfSymbol(symbol, 1 /* Number */); + setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + } + else { + // Combinations of function, class, enum and module + var members = emptySymbols; + var stringIndexInfo = void 0; + if (symbol.exports) { + members = getExportsOfSymbol(symbol); + } + setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, undefined, undefined); + if (symbol.flags & 32 /* Class */) { + var classType = getDeclaredTypeOfClassOrInterface(symbol); + var baseConstructorType = getBaseConstructorTypeOfClass(classType); + if (baseConstructorType.flags & (524288 /* Object */ | 2097152 /* Intersection */ | 8650752 /* TypeVariable */)) { + members = ts.createSymbolTable(getNamedMembers(members)); + addInheritedMembers(members, getPropertiesOfType(baseConstructorType)); + } + else if (baseConstructorType === anyType) { + stringIndexInfo = createIndexInfo(anyType, /*isReadonly*/ false); + } + } + var numberIndexInfo = symbol.flags & 384 /* Enum */ ? enumNumberIndexInfo : undefined; + setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); + // We resolve the members before computing the signatures because a signature may use + // typeof with a qualified name expression that circularly references the type we are + // in the process of resolving (see issue #6072). The temporarily empty signature list + // will never be observed because a qualified name can't reference signatures. + if (symbol.flags & (16 /* Function */ | 8192 /* Method */)) { + type.callSignatures = getSignaturesOfSymbol(symbol); + type.constructSignatures = ts.filter(type.callSignatures, function (sig) { return isJSConstructor(sig.declaration); }); + } + // And likewise for construct signatures for classes + if (symbol.flags & 32 /* Class */) { + var classType = getDeclaredTypeOfClassOrInterface(symbol); + var constructSignatures = getSignaturesOfSymbol(symbol.members.get("__constructor" /* Constructor */)); + if (!constructSignatures.length) { + constructSignatures = getDefaultConstructSignatures(classType); + } + type.constructSignatures = constructSignatures; + } + } + } + function resolveReverseMappedTypeMembers(type) { + var indexInfo = getIndexInfoOfType(type.source, 0 /* String */); + var modifiers = getMappedTypeModifiers(type.mappedType); + var readonlyMask = modifiers & 1 /* IncludeReadonly */ ? false : true; + var optionalMask = modifiers & 4 /* IncludeOptional */ ? 0 : 16777216 /* Optional */; + var stringIndexInfo = indexInfo && createIndexInfo(inferReverseMappedType(indexInfo.type, type.mappedType, type.constraintType), readonlyMask && indexInfo.isReadonly); + var members = ts.createSymbolTable(); + for (var _i = 0, _a = getPropertiesOfType(type.source); _i < _a.length; _i++) { + var prop = _a[_i]; + var checkFlags = 2048 /* ReverseMapped */ | (readonlyMask && isReadonlySymbol(prop) ? 8 /* Readonly */ : 0); + var inferredProp = createSymbol(4 /* Property */ | prop.flags & optionalMask, prop.escapedName, checkFlags); + inferredProp.declarations = prop.declarations; + inferredProp.nameType = prop.nameType; + inferredProp.propertyType = getTypeOfSymbol(prop); + inferredProp.mappedType = type.mappedType; + inferredProp.constraintType = type.constraintType; + members.set(prop.escapedName, inferredProp); + } + setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, undefined); + } + /** Resolve the members of a mapped type { [P in K]: T } */ + function resolveMappedTypeMembers(type) { + var members = ts.createSymbolTable(); + var stringIndexInfo; + var numberIndexInfo; + // Resolve upfront such that recursive references see an empty object type. + setStructuredTypeMembers(type, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + // In { [P in K]: T }, we refer to P as the type parameter type, K as the constraint type, + // and T as the template type. + var typeParameter = getTypeParameterFromMappedType(type); + var constraintType = getConstraintTypeFromMappedType(type); + var templateType = getTemplateTypeFromMappedType(type.target || type); + var modifiersType = getApparentType(getModifiersTypeFromMappedType(type)); // The 'T' in 'keyof T' + var templateModifiers = getMappedTypeModifiers(type); + var include = keyofStringsOnly ? 128 /* StringLiteral */ : 8576 /* StringOrNumberLiteralOrUnique */; + if (isMappedTypeWithKeyofConstraintDeclaration(type)) { + // We have a { [P in keyof T]: X } + for (var _i = 0, _a = getPropertiesOfType(modifiersType); _i < _a.length; _i++) { + var prop = _a[_i]; + addMemberForKeyType(getLiteralTypeFromProperty(prop, include)); + } + if (modifiersType.flags & 1 /* Any */ || getIndexInfoOfType(modifiersType, 0 /* String */)) { + addMemberForKeyType(stringType); + } + if (!keyofStringsOnly && getIndexInfoOfType(modifiersType, 1 /* Number */)) { + addMemberForKeyType(numberType); + } + } + else { + // If the key type is a 'keyof X', obtain 'keyof C' where C is the base constraint of X. + // Then iterate over the constituents of the key type. + var iterationType = constraintType.flags & 4194304 /* Index */ ? getIndexType(getApparentType(constraintType.type)) : constraintType; + forEachType(iterationType, addMemberForKeyType); + } + setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); + function addMemberForKeyType(t) { + // Create a mapper from T to the current iteration type constituent. Then, if the + // mapped type is itself an instantiated type, combine the iteration mapper with the + // instantiation mapper. + var templateMapper = combineTypeMappers(type.mapper, createTypeMapper([typeParameter], [t])); + var propType = instantiateType(templateType, templateMapper); + // If the current iteration type constituent is a string literal type, create a property. + // Otherwise, for type string create a string index signature. + if (t.flags & 8576 /* StringOrNumberLiteralOrUnique */) { + var propName = getLateBoundNameFromType(t); + var modifiersProp = getPropertyOfType(modifiersType, propName); + var isOptional = !!(templateModifiers & 4 /* IncludeOptional */ || + !(templateModifiers & 8 /* ExcludeOptional */) && modifiersProp && modifiersProp.flags & 16777216 /* Optional */); + var isReadonly = !!(templateModifiers & 1 /* IncludeReadonly */ || + !(templateModifiers & 2 /* ExcludeReadonly */) && modifiersProp && isReadonlySymbol(modifiersProp)); + var prop = createSymbol(4 /* Property */ | (isOptional ? 16777216 /* Optional */ : 0), propName, isReadonly ? 8 /* Readonly */ : 0); + // When creating an optional property in strictNullChecks mode, if 'undefined' isn't assignable to the + // type, we include 'undefined' in the type. Similarly, when creating a non-optional property in strictNullChecks + // mode, if the underlying property is optional we remove 'undefined' from the type. + prop.type = strictNullChecks && isOptional && !isTypeAssignableTo(undefinedType, propType) ? getOptionalType(propType) : + strictNullChecks && !isOptional && modifiersProp && modifiersProp.flags & 16777216 /* Optional */ ? getTypeWithFacts(propType, 524288 /* NEUndefined */) : + propType; + if (modifiersProp) { + prop.syntheticOrigin = modifiersProp; + prop.declarations = modifiersProp.declarations; + } + prop.nameType = t; + members.set(propName, prop); + } + else if (t.flags & (1 /* Any */ | 4 /* String */)) { + stringIndexInfo = createIndexInfo(propType, !!(templateModifiers & 1 /* IncludeReadonly */)); + } + else if (t.flags & 8 /* Number */) { + numberIndexInfo = createIndexInfo(propType, !!(templateModifiers & 1 /* IncludeReadonly */)); + } + } + } + function getTypeParameterFromMappedType(type) { + return type.typeParameter || + (type.typeParameter = getDeclaredTypeOfTypeParameter(getSymbolOfNode(type.declaration.typeParameter))); + } + function getConstraintTypeFromMappedType(type) { + return type.constraintType || + (type.constraintType = getConstraintOfTypeParameter(getTypeParameterFromMappedType(type)) || errorType); + } + function getTemplateTypeFromMappedType(type) { + return type.templateType || + (type.templateType = type.declaration.type ? + instantiateType(addOptionality(getTypeFromTypeNode(type.declaration.type), !!(getMappedTypeModifiers(type) & 4 /* IncludeOptional */)), type.mapper || identityMapper) : + errorType); + } + function getConstraintDeclarationForMappedType(type) { + return ts.getEffectiveConstraintOfTypeParameter(type.declaration.typeParameter); + } + function isMappedTypeWithKeyofConstraintDeclaration(type) { + var constraintDeclaration = getConstraintDeclarationForMappedType(type); // TODO: GH#18217 + return constraintDeclaration.kind === 179 /* TypeOperator */ && + constraintDeclaration.operator === 129 /* KeyOfKeyword */; + } + function getModifiersTypeFromMappedType(type) { + if (!type.modifiersType) { + if (isMappedTypeWithKeyofConstraintDeclaration(type)) { + // If the constraint declaration is a 'keyof T' node, the modifiers type is T. We check + // AST nodes here because, when T is a non-generic type, the logic below eagerly resolves + // 'keyof T' to a literal union type and we can't recover T from that type. + type.modifiersType = instantiateType(getTypeFromTypeNode(getConstraintDeclarationForMappedType(type).type), type.mapper || identityMapper); + } + else { + // Otherwise, get the declared constraint type, and if the constraint type is a type parameter, + // get the constraint of that type parameter. If the resulting type is an indexed type 'keyof T', + // the modifiers type is T. Otherwise, the modifiers type is {}. + var declaredType = getTypeFromMappedTypeNode(type.declaration); + var constraint = getConstraintTypeFromMappedType(declaredType); + var extendedConstraint = constraint && constraint.flags & 262144 /* TypeParameter */ ? getConstraintOfTypeParameter(constraint) : constraint; + type.modifiersType = extendedConstraint && extendedConstraint.flags & 4194304 /* Index */ ? instantiateType(extendedConstraint.type, type.mapper || identityMapper) : emptyObjectType; + } + } + return type.modifiersType; + } + function getMappedTypeModifiers(type) { + var declaration = type.declaration; + return (declaration.readonlyToken ? declaration.readonlyToken.kind === 39 /* MinusToken */ ? 2 /* ExcludeReadonly */ : 1 /* IncludeReadonly */ : 0) | + (declaration.questionToken ? declaration.questionToken.kind === 39 /* MinusToken */ ? 8 /* ExcludeOptional */ : 4 /* IncludeOptional */ : 0); + } + function getMappedTypeOptionality(type) { + var modifiers = getMappedTypeModifiers(type); + return modifiers & 8 /* ExcludeOptional */ ? -1 : modifiers & 4 /* IncludeOptional */ ? 1 : 0; + } + function getCombinedMappedTypeOptionality(type) { + var optionality = getMappedTypeOptionality(type); + var modifiersType = getModifiersTypeFromMappedType(type); + return optionality || (isGenericMappedType(modifiersType) ? getMappedTypeOptionality(modifiersType) : 0); + } + function isPartialMappedType(type) { + return !!(ts.getObjectFlags(type) & 32 /* Mapped */ && getMappedTypeModifiers(type) & 4 /* IncludeOptional */); + } + function isGenericMappedType(type) { + return !!(ts.getObjectFlags(type) & 32 /* Mapped */) && isGenericIndexType(getConstraintTypeFromMappedType(type)); + } + function resolveStructuredTypeMembers(type) { + if (!type.members) { + if (type.flags & 524288 /* Object */) { + if (type.objectFlags & 4 /* Reference */) { + resolveTypeReferenceMembers(type); + } + else if (type.objectFlags & 3 /* ClassOrInterface */) { + resolveClassOrInterfaceMembers(type); + } + else if (type.objectFlags & 2048 /* ReverseMapped */) { + resolveReverseMappedTypeMembers(type); + } + else if (type.objectFlags & 16 /* Anonymous */) { + resolveAnonymousTypeMembers(type); + } + else if (type.objectFlags & 32 /* Mapped */) { + resolveMappedTypeMembers(type); + } + } + else if (type.flags & 1048576 /* Union */) { + resolveUnionTypeMembers(type); + } + else if (type.flags & 2097152 /* Intersection */) { + resolveIntersectionTypeMembers(type); + } + } + return type; + } + /** Return properties of an object type or an empty array for other types */ + function getPropertiesOfObjectType(type) { + if (type.flags & 524288 /* Object */) { + return resolveStructuredTypeMembers(type).properties; + } + return ts.emptyArray; + } + /** If the given type is an object type and that type has a property by the given name, + * return the symbol for that property. Otherwise return undefined. + */ + function getPropertyOfObjectType(type, name) { + if (type.flags & 524288 /* Object */) { + var resolved = resolveStructuredTypeMembers(type); + var symbol = resolved.members.get(name); + if (symbol && symbolIsValue(symbol)) { + return symbol; + } + } + } + function getPropertiesOfUnionOrIntersectionType(type) { + if (!type.resolvedProperties) { + var members = ts.createSymbolTable(); + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var current = _a[_i]; + for (var _b = 0, _c = getPropertiesOfType(current); _b < _c.length; _b++) { + var prop = _c[_b]; + if (!members.has(prop.escapedName)) { + var combinedProp = getPropertyOfUnionOrIntersectionType(type, prop.escapedName); + if (combinedProp) { + members.set(prop.escapedName, combinedProp); + } + } + } + // The properties of a union type are those that are present in all constituent types, so + // we only need to check the properties of the first type + if (type.flags & 1048576 /* Union */) { + break; + } + } + type.resolvedProperties = getNamedMembers(members); + } + return type.resolvedProperties; + } + function getPropertiesOfType(type) { + type = getApparentType(type); + return type.flags & 3145728 /* UnionOrIntersection */ ? + getPropertiesOfUnionOrIntersectionType(type) : + getPropertiesOfObjectType(type); + } + function isTypeInvalidDueToUnionDiscriminant(contextualType, obj) { + var list = obj.properties; + return list.some(function (property) { + var name = property.name && ts.getTextOfPropertyName(property.name); + var expected = name === undefined ? undefined : getTypeOfPropertyOfType(contextualType, name); + return !!expected && typeIsLiteralType(expected) && !isTypeIdenticalTo(getTypeOfNode(property), expected); + }); + } + function getAllPossiblePropertiesOfTypes(types) { + var unionType = getUnionType(types); + if (!(unionType.flags & 1048576 /* Union */)) { + return getAugmentedPropertiesOfType(unionType); + } + var props = ts.createSymbolTable(); + for (var _i = 0, types_3 = types; _i < types_3.length; _i++) { + var memberType = types_3[_i]; + for (var _a = 0, _b = getAugmentedPropertiesOfType(memberType); _a < _b.length; _a++) { + var escapedName = _b[_a].escapedName; + if (!props.has(escapedName)) { + var prop = createUnionOrIntersectionProperty(unionType, escapedName); + // May be undefined if the property is private + if (prop) + props.set(escapedName, prop); + } + } + } + return ts.arrayFrom(props.values()); + } + function getConstraintOfType(type) { + return type.flags & 262144 /* TypeParameter */ ? getConstraintOfTypeParameter(type) : + type.flags & 8388608 /* IndexedAccess */ ? getConstraintOfIndexedAccess(type) : + type.flags & 16777216 /* Conditional */ ? getConstraintOfConditionalType(type) : + getBaseConstraintOfType(type); + } + function getConstraintOfTypeParameter(typeParameter) { + return hasNonCircularBaseConstraint(typeParameter) ? getConstraintFromTypeParameter(typeParameter) : undefined; + } + function getConstraintOfIndexedAccess(type) { + var objectType = getConstraintOfType(type.objectType) || type.objectType; + if (objectType !== type.objectType) { + var constraint = getIndexedAccessType(objectType, type.indexType, /*accessNode*/ undefined, errorType); + if (constraint && constraint !== errorType) { + return constraint; + } + } + var baseConstraint = getBaseConstraintOfType(type); + return baseConstraint && baseConstraint !== type ? baseConstraint : undefined; + } + function getDefaultConstraintOfConditionalType(type) { + if (!type.resolvedDefaultConstraint) { + var rootTrueType = type.root.trueType; + var rootTrueConstraint = !(rootTrueType.flags & 33554432 /* Substitution */) + ? rootTrueType + : (rootTrueType.substitute).flags & 3 /* AnyOrUnknown */ + ? rootTrueType.typeVariable + : getIntersectionType([rootTrueType.substitute, rootTrueType.typeVariable]); + type.resolvedDefaultConstraint = getUnionType([instantiateType(rootTrueConstraint, type.combinedMapper || type.mapper), getFalseTypeFromConditionalType(type)]); + } + return type.resolvedDefaultConstraint; + } + function getConstraintOfDistributiveConditionalType(type) { + // Check if we have a conditional type of the form 'T extends U ? X : Y', where T is a constrained + // type parameter. If so, create an instantiation of the conditional type where T is replaced + // with its constraint. We do this because if the constraint is a union type it will be distributed + // over the conditional type and possibly reduced. For example, 'T extends undefined ? never : T' + // removes 'undefined' from T. + if (type.root.isDistributive) { + var simplified = getSimplifiedType(type.checkType); + var constraint = simplified === type.checkType ? getConstraintOfType(simplified) : simplified; + if (constraint) { + var mapper = makeUnaryTypeMapper(type.root.checkType, constraint); + var instantiated = getConditionalTypeInstantiation(type, combineTypeMappers(mapper, type.mapper)); + if (!(instantiated.flags & 131072 /* Never */)) { + return instantiated; + } + } + } + return undefined; + } + function getConstraintOfConditionalType(type) { + return getConstraintOfDistributiveConditionalType(type) || getDefaultConstraintOfConditionalType(type); + } + function getUnionConstraintOfIntersection(type, targetIsUnion) { + var constraints; + var hasDisjointDomainType = false; + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (t.flags & 63176704 /* Instantiable */) { + // We keep following constraints as long as we have an instantiable type that is known + // not to be circular or infinite (hence we stop on index access types). + var constraint = getConstraintOfType(t); + while (constraint && constraint.flags & (262144 /* TypeParameter */ | 4194304 /* Index */ | 16777216 /* Conditional */)) { + constraint = getConstraintOfType(constraint); + } + if (constraint) { + // A constraint that isn't a union type implies that the final type would be a non-union + // type as well. Since non-union constraints are of no interest, we can exit here. + if (!(constraint.flags & 1048576 /* Union */)) { + return undefined; + } + constraints = ts.append(constraints, constraint); + } + } + else if (t.flags & 67238908 /* DisjointDomains */) { + hasDisjointDomainType = true; + } + } + // If the target is a union type or if we are intersecting with types belonging to one of the + // disjoint domans, we may end up producing a constraint that hasn't been examined before. + if (constraints && (targetIsUnion || hasDisjointDomainType)) { + if (hasDisjointDomainType) { + // We add any types belong to one of the disjoint domans because they might cause the final + // intersection operation to reduce the union constraints. + for (var _b = 0, _c = type.types; _b < _c.length; _b++) { + var t = _c[_b]; + if (t.flags & 67238908 /* DisjointDomains */) { + constraints = ts.append(constraints, t); + } + } + } + return getIntersectionType(constraints); + } + return undefined; + } + function getBaseConstraintOfType(type) { + if (type.flags & (58982400 /* InstantiableNonPrimitive */ | 3145728 /* UnionOrIntersection */)) { + var constraint = getResolvedBaseConstraint(type); + return constraint !== noConstraintType && constraint !== circularConstraintType ? constraint : undefined; + } + return type.flags & 4194304 /* Index */ ? keyofConstraintType : undefined; + } + /** + * This is similar to `getBaseConstraintOfType` except it returns the input type if there's no base constraint, instead of `undefined` + * It also doesn't map indexes to `string`, as where this is used this would be unneeded (and likely undesirable) + */ + function getBaseConstraintOrType(type) { + return getBaseConstraintOfType(type) || type; + } + function hasNonCircularBaseConstraint(type) { + return getResolvedBaseConstraint(type) !== circularConstraintType; + } + /** + * Return the resolved base constraint of a type variable. The noConstraintType singleton is returned if the + * type variable has no constraint, and the circularConstraintType singleton is returned if the constraint + * circularly references the type variable. + */ + function getResolvedBaseConstraint(type) { + var nonTerminating = false; + return type.resolvedBaseConstraint || + (type.resolvedBaseConstraint = getTypeWithThisArgument(getImmediateBaseConstraint(type), type)); + function getImmediateBaseConstraint(t) { + if (!t.immediateBaseConstraint) { + if (!pushTypeResolution(t, 4 /* ImmediateBaseConstraint */)) { + return circularConstraintType; + } + if (constraintDepth === 50) { + // We have reached 50 recursive invocations of getImmediateBaseConstraint and there is a + // very high likelyhood we're dealing with an infinite generic type that perpetually generates + // new type identities as we descend into it. We stop the recursion here and mark this type + // and the outer types as having circular constraints. + nonTerminating = true; + return t.immediateBaseConstraint = noConstraintType; + } + constraintDepth++; + var result = computeBaseConstraint(getSimplifiedType(t)); + constraintDepth--; + if (!popTypeResolution() || nonTerminating) { + result = circularConstraintType; + } + t.immediateBaseConstraint = result || noConstraintType; + } + return t.immediateBaseConstraint; + } + function getBaseConstraint(t) { + var c = getImmediateBaseConstraint(t); + return c !== noConstraintType && c !== circularConstraintType ? c : undefined; + } + function computeBaseConstraint(t) { + if (t.flags & 262144 /* TypeParameter */) { + var constraint = getConstraintFromTypeParameter(t); + return t.isThisType || !constraint ? + constraint : + getBaseConstraint(constraint); + } + if (t.flags & 3145728 /* UnionOrIntersection */) { + var types = t.types; + var baseTypes = []; + for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { + var type_3 = types_4[_i]; + var baseType = getBaseConstraint(type_3); + if (baseType) { + baseTypes.push(baseType); + } + } + return t.flags & 1048576 /* Union */ && baseTypes.length === types.length ? getUnionType(baseTypes) : + t.flags & 2097152 /* Intersection */ && baseTypes.length ? getIntersectionType(baseTypes) : + undefined; + } + if (t.flags & 4194304 /* Index */) { + return keyofConstraintType; + } + if (t.flags & 8388608 /* IndexedAccess */) { + var baseObjectType = getBaseConstraint(t.objectType); + var baseIndexType = getBaseConstraint(t.indexType); + var baseIndexedAccess = baseObjectType && baseIndexType ? getIndexedAccessType(baseObjectType, baseIndexType, /*accessNode*/ undefined, errorType) : undefined; + return baseIndexedAccess && baseIndexedAccess !== errorType ? getBaseConstraint(baseIndexedAccess) : undefined; + } + if (t.flags & 16777216 /* Conditional */) { + var constraint = getConstraintOfConditionalType(t); + return constraint && getBaseConstraint(constraint); + } + if (t.flags & 33554432 /* Substitution */) { + return getBaseConstraint(t.substitute); + } + return t; + } + } + function getApparentTypeOfIntersectionType(type) { + return type.resolvedApparentType || (type.resolvedApparentType = getTypeWithThisArgument(type, type, /*apparentType*/ true)); + } + function getResolvedTypeParameterDefault(typeParameter) { + if (!typeParameter.default) { + if (typeParameter.target) { + var targetDefault = getResolvedTypeParameterDefault(typeParameter.target); + typeParameter.default = targetDefault ? instantiateType(targetDefault, typeParameter.mapper) : noConstraintType; + } + else { + // To block recursion, set the initial value to the resolvingDefaultType. + typeParameter.default = resolvingDefaultType; + var defaultDeclaration = typeParameter.symbol && ts.forEach(typeParameter.symbol.declarations, function (decl) { return ts.isTypeParameterDeclaration(decl) && decl.default; }); + var defaultType = defaultDeclaration ? getTypeFromTypeNode(defaultDeclaration) : noConstraintType; + if (typeParameter.default === resolvingDefaultType) { + // If we have not been called recursively, set the correct default type. + typeParameter.default = defaultType; + } + } + } + else if (typeParameter.default === resolvingDefaultType) { + // If we are called recursively for this type parameter, mark the default as circular. + typeParameter.default = circularConstraintType; + } + return typeParameter.default; + } + /** + * Gets the default type for a type parameter. + * + * If the type parameter is the result of an instantiation, this gets the instantiated + * default type of its target. If the type parameter has no default type or the default is + * circular, `undefined` is returned. + */ + function getDefaultFromTypeParameter(typeParameter) { + var defaultType = getResolvedTypeParameterDefault(typeParameter); + return defaultType !== noConstraintType && defaultType !== circularConstraintType ? defaultType : undefined; + } + function hasNonCircularTypeParameterDefault(typeParameter) { + return getResolvedTypeParameterDefault(typeParameter) !== circularConstraintType; + } + /** + * Indicates whether the declaration of a typeParameter has a default type. + */ + function hasTypeParameterDefault(typeParameter) { + return !!(typeParameter.symbol && ts.forEach(typeParameter.symbol.declarations, function (decl) { return ts.isTypeParameterDeclaration(decl) && decl.default; })); + } + function getApparentTypeOfMappedType(type) { + return type.resolvedApparentType || (type.resolvedApparentType = getResolvedApparentTypeOfMappedType(type)); + } + function getResolvedApparentTypeOfMappedType(type) { + var typeVariable = getHomomorphicTypeVariable(type); + if (typeVariable) { + var constraint = getConstraintOfTypeParameter(typeVariable); + if (constraint && (isArrayType(constraint) || isReadonlyArrayType(constraint) || isTupleType(constraint))) { + var mapper = makeUnaryTypeMapper(typeVariable, constraint); + return instantiateType(type, combineTypeMappers(mapper, type.mapper)); + } + } + return type; + } + /** + * For a type parameter, return the base constraint of the type parameter. For the string, number, + * boolean, and symbol primitive types, return the corresponding object types. Otherwise return the + * type itself. Note that the apparent type of a union type is the union type itself. + */ + function getApparentType(type) { + var t = type.flags & 63176704 /* Instantiable */ ? getBaseConstraintOfType(type) || emptyObjectType : type; + return ts.getObjectFlags(t) & 32 /* Mapped */ ? getApparentTypeOfMappedType(t) : + t.flags & 2097152 /* Intersection */ ? getApparentTypeOfIntersectionType(t) : + t.flags & 132 /* StringLike */ ? globalStringType : + t.flags & 296 /* NumberLike */ ? globalNumberType : + t.flags & 2112 /* BigIntLike */ ? getGlobalBigIntType(/*reportErrors*/ languageVersion >= 6 /* ESNext */) : + t.flags & 528 /* BooleanLike */ ? globalBooleanType : + t.flags & 12288 /* ESSymbolLike */ ? getGlobalESSymbolType(/*reportErrors*/ languageVersion >= 2 /* ES2015 */) : + t.flags & 67108864 /* NonPrimitive */ ? emptyObjectType : + t.flags & 4194304 /* Index */ ? keyofConstraintType : + t; + } + function createUnionOrIntersectionProperty(containingType, name) { + var props; + var indexTypes; + var isUnion = containingType.flags & 1048576 /* Union */; + var excludeModifiers = isUnion ? 24 /* NonPublicAccessibilityModifier */ : 0; + // Flags we want to propagate to the result if they exist in all source symbols + var commonFlags = isUnion ? 0 /* None */ : 16777216 /* Optional */; + var syntheticFlag = 4 /* SyntheticMethod */; + var checkFlags = 0; + for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) { + var current = _a[_i]; + var type = getApparentType(current); + if (type !== errorType) { + var prop = getPropertyOfType(type, name); + var modifiers = prop ? ts.getDeclarationModifierFlagsFromSymbol(prop) : 0; + if (prop && !(modifiers & excludeModifiers)) { + commonFlags &= prop.flags; + props = ts.appendIfUnique(props, prop); + checkFlags |= (isReadonlySymbol(prop) ? 8 /* Readonly */ : 0) | + (!(modifiers & 24 /* NonPublicAccessibilityModifier */) ? 64 /* ContainsPublic */ : 0) | + (modifiers & 16 /* Protected */ ? 128 /* ContainsProtected */ : 0) | + (modifiers & 8 /* Private */ ? 256 /* ContainsPrivate */ : 0) | + (modifiers & 32 /* Static */ ? 512 /* ContainsStatic */ : 0); + if (!isPrototypeProperty(prop)) { + syntheticFlag = 2 /* SyntheticProperty */; + } + } + else if (isUnion) { + var indexInfo = !isLateBoundName(name) && (isNumericLiteralName(name) && getIndexInfoOfType(type, 1 /* Number */) || getIndexInfoOfType(type, 0 /* String */)); + if (indexInfo) { + checkFlags |= indexInfo.isReadonly ? 8 /* Readonly */ : 0; + indexTypes = ts.append(indexTypes, isTupleType(type) ? getRestTypeOfTupleType(type) || undefinedType : indexInfo.type); + } + else { + checkFlags |= 16 /* Partial */; + } + } + } + } + if (!props) { + return undefined; + } + if (props.length === 1 && !(checkFlags & 16 /* Partial */) && !indexTypes) { + return props[0]; + } + var declarations; + var commonType; + var nameType; + var propTypes = []; + var first = true; + var commonValueDeclaration; + var hasNonUniformValueDeclaration = false; + for (var _b = 0, props_1 = props; _b < props_1.length; _b++) { + var prop = props_1[_b]; + if (!commonValueDeclaration) { + commonValueDeclaration = prop.valueDeclaration; + } + else if (prop.valueDeclaration !== commonValueDeclaration) { + hasNonUniformValueDeclaration = true; + } + declarations = ts.addRange(declarations, prop.declarations); + var type = getTypeOfSymbol(prop); + if (first) { + commonType = type; + nameType = prop.nameType; + first = false; + } + else { + if (type !== commonType) { + checkFlags |= 32 /* HasNonUniformType */; + } + } + propTypes.push(type); + } + ts.addRange(propTypes, indexTypes); + var result = createSymbol(4 /* Property */ | commonFlags, name, syntheticFlag | checkFlags); + result.containingType = containingType; + if (!hasNonUniformValueDeclaration && commonValueDeclaration) { + result.valueDeclaration = commonValueDeclaration; + } + result.declarations = declarations; + result.nameType = nameType; + result.type = isUnion ? getUnionType(propTypes) : getIntersectionType(propTypes); + return result; + } + // Return the symbol for a given property in a union or intersection type, or undefined if the property + // does not exist in any constituent type. Note that the returned property may only be present in some + // constituents, in which case the isPartial flag is set when the containing type is union type. We need + // these partial properties when identifying discriminant properties, but otherwise they are filtered out + // and do not appear to be present in the union type. + function getUnionOrIntersectionProperty(type, name) { + var properties = type.propertyCache || (type.propertyCache = ts.createSymbolTable()); + var property = properties.get(name); + if (!property) { + property = createUnionOrIntersectionProperty(type, name); + if (property) { + properties.set(name, property); + } + } + return property; + } + function getPropertyOfUnionOrIntersectionType(type, name) { + var property = getUnionOrIntersectionProperty(type, name); + // We need to filter out partial properties in union types + return property && !(ts.getCheckFlags(property) & 16 /* Partial */) ? property : undefined; + } + /** + * Return the symbol for the property with the given name in the given type. Creates synthetic union properties when + * necessary, maps primitive types and type parameters are to their apparent types, and augments with properties from + * Object and Function as appropriate. + * + * @param type a type to look up property from + * @param name a name of property to look up in a given type + */ + function getPropertyOfType(type, name) { + type = getApparentType(type); + if (type.flags & 524288 /* Object */) { + var resolved = resolveStructuredTypeMembers(type); + var symbol = resolved.members.get(name); + if (symbol && symbolIsValue(symbol)) { + return symbol; + } + var functionType = resolved === anyFunctionType ? globalFunctionType : + resolved.callSignatures.length ? globalCallableFunctionType : + resolved.constructSignatures.length ? globalNewableFunctionType : + undefined; + if (functionType) { + var symbol_1 = getPropertyOfObjectType(functionType, name); + if (symbol_1) { + return symbol_1; + } + } + return getPropertyOfObjectType(globalObjectType, name); + } + if (type.flags & 3145728 /* UnionOrIntersection */) { + return getPropertyOfUnionOrIntersectionType(type, name); + } + return undefined; + } + function getSignaturesOfStructuredType(type, kind) { + if (type.flags & 3670016 /* StructuredType */) { + var resolved = resolveStructuredTypeMembers(type); + return kind === 0 /* Call */ ? resolved.callSignatures : resolved.constructSignatures; + } + return ts.emptyArray; + } + /** + * Return the signatures of the given kind in the given type. Creates synthetic union signatures when necessary and + * maps primitive types and type parameters are to their apparent types. + */ + function getSignaturesOfType(type, kind) { + return getSignaturesOfStructuredType(getApparentType(type), kind); + } + function getIndexInfoOfStructuredType(type, kind) { + if (type.flags & 3670016 /* StructuredType */) { + var resolved = resolveStructuredTypeMembers(type); + return kind === 0 /* String */ ? resolved.stringIndexInfo : resolved.numberIndexInfo; + } + } + function getIndexTypeOfStructuredType(type, kind) { + var info = getIndexInfoOfStructuredType(type, kind); + return info && info.type; + } + // Return the indexing info of the given kind in the given type. Creates synthetic union index types when necessary and + // maps primitive types and type parameters are to their apparent types. + function getIndexInfoOfType(type, kind) { + return getIndexInfoOfStructuredType(getApparentType(type), kind); + } + // Return the index type of the given kind in the given type. Creates synthetic union index types when necessary and + // maps primitive types and type parameters are to their apparent types. + function getIndexTypeOfType(type, kind) { + return getIndexTypeOfStructuredType(getApparentType(type), kind); + } + function getImplicitIndexTypeOfType(type, kind) { + if (isObjectTypeWithInferableIndex(type)) { + var propTypes = []; + for (var _i = 0, _a = getPropertiesOfType(type); _i < _a.length; _i++) { + var prop = _a[_i]; + if (kind === 0 /* String */ || isNumericLiteralName(prop.escapedName)) { + propTypes.push(getTypeOfSymbol(prop)); + } + } + if (propTypes.length) { + return getUnionType(propTypes, 2 /* Subtype */); + } + } + return undefined; + } + // Return list of type parameters with duplicates removed (duplicate identifier errors are generated in the actual + // type checking functions). + function getTypeParametersFromDeclaration(declaration) { + var result; + for (var _i = 0, _a = ts.getEffectiveTypeParameterDeclarations(declaration); _i < _a.length; _i++) { + var node = _a[_i]; + result = ts.appendIfUnique(result, getDeclaredTypeOfTypeParameter(node.symbol)); + } + return result; + } + function symbolsToArray(symbols) { + var result = []; + symbols.forEach(function (symbol, id) { + if (!isReservedMemberName(id)) { + result.push(symbol); + } + }); + return result; + } + function isJSDocOptionalParameter(node) { + return ts.isInJSFile(node) && ( + // node.type should only be a JSDocOptionalType when node is a parameter of a JSDocFunctionType + node.type && node.type.kind === 288 /* JSDocOptionalType */ + || ts.getJSDocParameterTags(node).some(function (_a) { + var isBracketed = _a.isBracketed, typeExpression = _a.typeExpression; + return isBracketed || !!typeExpression && typeExpression.type.kind === 288 /* JSDocOptionalType */; + })); + } + function tryFindAmbientModule(moduleName, withAugmentations) { + if (ts.isExternalModuleNameRelative(moduleName)) { + return undefined; + } + var symbol = getSymbol(globals, '"' + moduleName + '"', 512 /* ValueModule */); + // merged symbol is module declaration symbol combined with all augmentations + return symbol && withAugmentations ? getMergedSymbol(symbol) : symbol; + } + function isOptionalParameter(node) { + if (ts.hasQuestionToken(node) || isOptionalJSDocParameterTag(node) || isJSDocOptionalParameter(node)) { + return true; + } + if (node.initializer) { + var signature = getSignatureFromDeclaration(node.parent); + var parameterIndex = node.parent.parameters.indexOf(node); + ts.Debug.assert(parameterIndex >= 0); + return parameterIndex >= getMinArgumentCount(signature); + } + var iife = ts.getImmediatelyInvokedFunctionExpression(node.parent); + if (iife) { + return !node.type && + !node.dotDotDotToken && + node.parent.parameters.indexOf(node) >= iife.arguments.length; + } + return false; + } + function isOptionalJSDocParameterTag(node) { + if (!ts.isJSDocParameterTag(node)) { + return false; + } + var isBracketed = node.isBracketed, typeExpression = node.typeExpression; + return isBracketed || !!typeExpression && typeExpression.type.kind === 288 /* JSDocOptionalType */; + } + function createIdentifierTypePredicate(parameterName, parameterIndex, type) { + return { kind: 1 /* Identifier */, parameterName: parameterName, parameterIndex: parameterIndex, type: type }; + } + function createThisTypePredicate(type) { + return { kind: 0 /* This */, type: type }; + } + /** + * Gets the minimum number of type arguments needed to satisfy all non-optional type + * parameters. + */ + function getMinTypeArgumentCount(typeParameters) { + var minTypeArgumentCount = 0; + if (typeParameters) { + for (var i = 0; i < typeParameters.length; i++) { + if (!hasTypeParameterDefault(typeParameters[i])) { + minTypeArgumentCount = i + 1; + } + } + } + return minTypeArgumentCount; + } + function fillMissingTypeArguments(typeArguments, typeParameters, minTypeArgumentCount, isJavaScriptImplicitAny) { + var numTypeParameters = ts.length(typeParameters); + if (!numTypeParameters) { + return []; + } + var numTypeArguments = ts.length(typeArguments); + if (isJavaScriptImplicitAny || (numTypeArguments >= minTypeArgumentCount && numTypeArguments <= numTypeParameters)) { + var result = typeArguments ? typeArguments.slice() : []; + // Map an unsatisfied type parameter with a default type. + // If a type parameter does not have a default type, or if the default type + // is a forward reference, the empty object type is used. + var baseDefaultType_1 = getDefaultTypeArgumentType(isJavaScriptImplicitAny); + var circularityMapper = createTypeMapper(typeParameters, ts.map(typeParameters, function () { return baseDefaultType_1; })); + for (var i = numTypeArguments; i < numTypeParameters; i++) { + result[i] = instantiateType(getConstraintFromTypeParameter(typeParameters[i]) || baseDefaultType_1, circularityMapper); + } + for (var i = numTypeArguments; i < numTypeParameters; i++) { + var mapper = createTypeMapper(typeParameters, result); + var defaultType = getDefaultFromTypeParameter(typeParameters[i]); + if (isJavaScriptImplicitAny && defaultType && isTypeIdenticalTo(defaultType, emptyObjectType)) { + defaultType = anyType; + } + result[i] = defaultType ? instantiateType(defaultType, mapper) : baseDefaultType_1; + } + result.length = typeParameters.length; + return result; + } + return typeArguments && typeArguments.slice(); + } + function getSignatureFromDeclaration(declaration) { + var links = getNodeLinks(declaration); + if (!links.resolvedSignature) { + var parameters = []; + var hasLiteralTypes = false; + var minArgumentCount = 0; + var thisParameter = void 0; + var hasThisParameter = false; + var iife = ts.getImmediatelyInvokedFunctionExpression(declaration); + var isJSConstructSignature = ts.isJSDocConstructSignature(declaration); + var isUntypedSignatureInJSFile = !iife && + ts.isInJSFile(declaration) && + ts.isValueSignatureDeclaration(declaration) && + !ts.hasJSDocParameterTags(declaration) && + !ts.getJSDocType(declaration); + // If this is a JSDoc construct signature, then skip the first parameter in the + // parameter list. The first parameter represents the return type of the construct + // signature. + for (var i = isJSConstructSignature ? 1 : 0; i < declaration.parameters.length; i++) { + var param = declaration.parameters[i]; + var paramSymbol = param.symbol; + var type = ts.isJSDocParameterTag(param) ? (param.typeExpression && param.typeExpression.type) : param.type; + // Include parameter symbol instead of property symbol in the signature + if (paramSymbol && !!(paramSymbol.flags & 4 /* Property */) && !ts.isBindingPattern(param.name)) { + var resolvedSymbol = resolveName(param, paramSymbol.escapedName, 67220415 /* Value */, undefined, undefined, /*isUse*/ false); + paramSymbol = resolvedSymbol; + } + if (i === 0 && paramSymbol.escapedName === "this" /* This */) { + hasThisParameter = true; + thisParameter = param.symbol; + } + else { + parameters.push(paramSymbol); + } + if (type && type.kind === 182 /* LiteralType */) { + hasLiteralTypes = true; + } + // Record a new minimum argument count if this is not an optional parameter + var isOptionalParameter_1 = isOptionalJSDocParameterTag(param) || + param.initializer || param.questionToken || param.dotDotDotToken || + iife && parameters.length > iife.arguments.length && !type || + isUntypedSignatureInJSFile || + isJSDocOptionalParameter(param); + if (!isOptionalParameter_1) { + minArgumentCount = parameters.length; + } + } + // If only one accessor includes a this-type annotation, the other behaves as if it had the same type annotation + if ((declaration.kind === 158 /* GetAccessor */ || declaration.kind === 159 /* SetAccessor */) && + !hasNonBindableDynamicName(declaration) && + (!hasThisParameter || !thisParameter)) { + var otherKind = declaration.kind === 158 /* GetAccessor */ ? 159 /* SetAccessor */ : 158 /* GetAccessor */; + var other = ts.getDeclarationOfKind(getSymbolOfNode(declaration), otherKind); + if (other) { + thisParameter = getAnnotatedAccessorThisParameter(other); + } + } + var classType = declaration.kind === 157 /* Constructor */ ? + getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)) + : undefined; + var typeParameters = classType ? classType.localTypeParameters : getTypeParametersFromDeclaration(declaration); + var hasRestLikeParameter = ts.hasRestParameter(declaration) || ts.isInJSFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters); + links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, + /*resolvedReturnType*/ undefined, /*resolvedTypePredicate*/ undefined, minArgumentCount, hasRestLikeParameter, hasLiteralTypes); + } + return links.resolvedSignature; + } + /** + * A JS function gets a synthetic rest parameter if it references `arguments` AND: + * 1. It has no parameters but at least one `@param` with a type that starts with `...` + * OR + * 2. It has at least one parameter, and the last parameter has a matching `@param` with a type that starts with `...` + */ + function maybeAddJsSyntheticRestParameter(declaration, parameters) { + if (ts.isJSDocSignature(declaration) || !containsArgumentsReference(declaration)) { + return false; + } + var lastParam = ts.lastOrUndefined(declaration.parameters); + var lastParamTags = lastParam ? ts.getJSDocParameterTags(lastParam) : ts.getJSDocTags(declaration).filter(ts.isJSDocParameterTag); + var lastParamVariadicType = ts.firstDefined(lastParamTags, function (p) { + return p.typeExpression && ts.isJSDocVariadicType(p.typeExpression.type) ? p.typeExpression.type : undefined; + }); + var syntheticArgsSymbol = createSymbol(3 /* Variable */, "args", 8192 /* RestParameter */); + syntheticArgsSymbol.type = lastParamVariadicType ? createArrayType(getTypeFromTypeNode(lastParamVariadicType.type)) : anyArrayType; + if (lastParamVariadicType) { + // Replace the last parameter with a rest parameter. + parameters.pop(); + } + parameters.push(syntheticArgsSymbol); + return true; + } + function getSignatureOfTypeTag(node) { + var typeTag = ts.isInJSFile(node) ? ts.getJSDocTypeTag(node) : undefined; + var signature = typeTag && typeTag.typeExpression && getSingleCallSignature(getTypeFromTypeNode(typeTag.typeExpression)); + return signature && getErasedSignature(signature); + } + function getReturnTypeOfTypeTag(node) { + var signature = getSignatureOfTypeTag(node); + return signature && getReturnTypeOfSignature(signature); + } + function containsArgumentsReference(declaration) { + var links = getNodeLinks(declaration); + if (links.containsArgumentsReference === undefined) { + if (links.flags & 8192 /* CaptureArguments */) { + links.containsArgumentsReference = true; + } + else { + links.containsArgumentsReference = traverse(declaration.body); + } + } + return links.containsArgumentsReference; + function traverse(node) { + if (!node) + return false; + switch (node.kind) { + case 72 /* Identifier */: + return node.escapedText === "arguments" && ts.isExpressionNode(node); + case 154 /* PropertyDeclaration */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + return node.name.kind === 149 /* ComputedPropertyName */ + && traverse(node.name); + default: + return !ts.nodeStartsNewLexicalEnvironment(node) && !ts.isPartOfTypeNode(node) && !!ts.forEachChild(node, traverse); + } + } + } + function getSignaturesOfSymbol(symbol) { + if (!symbol) + return ts.emptyArray; + var result = []; + for (var i = 0; i < symbol.declarations.length; i++) { + var decl = symbol.declarations[i]; + if (!ts.isFunctionLike(decl)) + continue; + // Don't include signature if node is the implementation of an overloaded function. A node is considered + // an implementation node if it has a body and the previous node is of the same kind and immediately + // precedes the implementation node (i.e. has the same parent and ends where the implementation starts). + if (i > 0 && decl.body) { + var previous = symbol.declarations[i - 1]; + if (decl.parent === previous.parent && decl.kind === previous.kind && decl.pos === previous.end) { + continue; + } + } + result.push(getSignatureFromDeclaration(decl)); + } + return result; + } + function resolveExternalModuleTypeByLiteral(name) { + var moduleSym = resolveExternalModuleName(name, name); + if (moduleSym) { + var resolvedModuleSymbol = resolveExternalModuleSymbol(moduleSym); + if (resolvedModuleSymbol) { + return getTypeOfSymbol(resolvedModuleSymbol); + } + } + return anyType; + } + function getThisTypeOfSignature(signature) { + if (signature.thisParameter) { + return getTypeOfSymbol(signature.thisParameter); + } + } + function signatureHasTypePredicate(signature) { + return getTypePredicateOfSignature(signature) !== undefined; + } + function getTypePredicateOfSignature(signature) { + if (!signature.resolvedTypePredicate) { + if (signature.target) { + var targetTypePredicate = getTypePredicateOfSignature(signature.target); + signature.resolvedTypePredicate = targetTypePredicate ? instantiateTypePredicate(targetTypePredicate, signature.mapper) : noTypePredicate; + } + else if (signature.unionSignatures) { + signature.resolvedTypePredicate = getUnionTypePredicate(signature.unionSignatures) || noTypePredicate; + } + else { + var type = signature.declaration && ts.getEffectiveReturnTypeNode(signature.declaration); + var jsdocPredicate = void 0; + if (!type && ts.isInJSFile(signature.declaration)) { + var jsdocSignature = getSignatureOfTypeTag(signature.declaration); + if (jsdocSignature && signature !== jsdocSignature) { + jsdocPredicate = getTypePredicateOfSignature(jsdocSignature); + } + } + signature.resolvedTypePredicate = type && ts.isTypePredicateNode(type) ? + createTypePredicateFromTypePredicateNode(type, signature.declaration) : + jsdocPredicate || noTypePredicate; + } + ts.Debug.assert(!!signature.resolvedTypePredicate); + } + return signature.resolvedTypePredicate === noTypePredicate ? undefined : signature.resolvedTypePredicate; + } + function createTypePredicateFromTypePredicateNode(node, func) { + var parameterName = node.parameterName; + var type = getTypeFromTypeNode(node.type); + if (parameterName.kind === 72 /* Identifier */) { + return createIdentifierTypePredicate(parameterName.escapedText, getTypePredicateParameterIndex(func.parameters, parameterName), type); + } + else { + return createThisTypePredicate(type); + } + } + function getTypePredicateParameterIndex(parameterList, parameter) { + for (var i = 0; i < parameterList.length; i++) { + var param = parameterList[i]; + if (param.name.kind === 72 /* Identifier */ && param.name.escapedText === parameter.escapedText) { + return i; + } + } + return -1; + } + function getReturnTypeOfSignature(signature) { + if (!signature.resolvedReturnType) { + if (!pushTypeResolution(signature, 3 /* ResolvedReturnType */)) { + return errorType; + } + var type = signature.target ? instantiateType(getReturnTypeOfSignature(signature.target), signature.mapper) : + signature.unionSignatures ? getUnionType(ts.map(signature.unionSignatures, getReturnTypeOfSignature), 2 /* Subtype */) : + getReturnTypeFromAnnotation(signature.declaration) || + isJSConstructor(signature.declaration) && getJSClassType(getSymbolOfNode(signature.declaration)) || + (ts.nodeIsMissing(signature.declaration.body) ? anyType : getReturnTypeFromBody(signature.declaration)); + if (!popTypeResolution()) { + if (signature.declaration) { + var typeNode = ts.getEffectiveReturnTypeNode(signature.declaration); + if (typeNode) { + error(typeNode, ts.Diagnostics.Return_type_annotation_circularly_references_itself); + } + else if (noImplicitAny) { + var declaration = signature.declaration; + var name = ts.getNameOfDeclaration(declaration); + if (name) { + error(name, ts.Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, ts.declarationNameToString(name)); + } + else { + error(declaration, ts.Diagnostics.Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions); + } + } + } + type = anyType; + } + signature.resolvedReturnType = type; + } + return signature.resolvedReturnType; + } + function getReturnTypeFromAnnotation(declaration) { + if (declaration.kind === 157 /* Constructor */) { + return getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)); + } + if (ts.isJSDocConstructSignature(declaration)) { + return getTypeFromTypeNode(declaration.parameters[0].type); // TODO: GH#18217 + } + var typeNode = ts.getEffectiveReturnTypeNode(declaration); + if (typeNode) { + return getTypeFromTypeNode(typeNode); + } + if (declaration.kind === 158 /* GetAccessor */ && !hasNonBindableDynamicName(declaration)) { + var jsDocType = ts.isInJSFile(declaration) && getTypeForDeclarationFromJSDocComment(declaration); + if (jsDocType) { + return jsDocType; + } + var setter = ts.getDeclarationOfKind(getSymbolOfNode(declaration), 159 /* SetAccessor */); + var setterType = getAnnotatedAccessorType(setter); + if (setterType) { + return setterType; + } + } + return getReturnTypeOfTypeTag(declaration); + } + function isResolvingReturnTypeOfSignature(signature) { + return !signature.resolvedReturnType && findResolutionCycleStartIndex(signature, 3 /* ResolvedReturnType */) >= 0; + } + function getRestTypeOfSignature(signature) { + return tryGetRestTypeOfSignature(signature) || anyType; + } + function tryGetRestTypeOfSignature(signature) { + if (signature.hasRestParameter) { + var sigRestType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); + var restType = isTupleType(sigRestType) ? getRestTypeOfTupleType(sigRestType) : sigRestType; + return restType && getIndexTypeOfType(restType, 1 /* Number */); + } + return undefined; + } + function getSignatureInstantiation(signature, typeArguments, isJavascript) { + return getSignatureInstantiationWithoutFillingInTypeArguments(signature, fillMissingTypeArguments(typeArguments, signature.typeParameters, getMinTypeArgumentCount(signature.typeParameters), isJavascript)); + } + function getSignatureInstantiationWithoutFillingInTypeArguments(signature, typeArguments) { + var instantiations = signature.instantiations || (signature.instantiations = ts.createMap()); + var id = getTypeListId(typeArguments); + var instantiation = instantiations.get(id); + if (!instantiation) { + instantiations.set(id, instantiation = createSignatureInstantiation(signature, typeArguments)); + } + return instantiation; + } + function createSignatureInstantiation(signature, typeArguments) { + return instantiateSignature(signature, createSignatureTypeMapper(signature, typeArguments), /*eraseTypeParameters*/ true); + } + function createSignatureTypeMapper(signature, typeArguments) { + return createTypeMapper(signature.typeParameters, typeArguments); + } + function getErasedSignature(signature) { + return signature.typeParameters ? + signature.erasedSignatureCache || (signature.erasedSignatureCache = createErasedSignature(signature)) : + signature; + } + function createErasedSignature(signature) { + // Create an instantiation of the signature where all type arguments are the any type. + return instantiateSignature(signature, createTypeEraser(signature.typeParameters), /*eraseTypeParameters*/ true); + } + function getCanonicalSignature(signature) { + return signature.typeParameters ? + signature.canonicalSignatureCache || (signature.canonicalSignatureCache = createCanonicalSignature(signature)) : + signature; + } + function createCanonicalSignature(signature) { + // Create an instantiation of the signature where each unconstrained type parameter is replaced with + // its original. When a generic class or interface is instantiated, each generic method in the class or + // interface is instantiated with a fresh set of cloned type parameters (which we need to handle scenarios + // where different generations of the same type parameter are in scope). This leads to a lot of new type + // identities, and potentially a lot of work comparing those identities, so here we create an instantiation + // that uses the original type identities for all unconstrained type parameters. + return getSignatureInstantiation(signature, ts.map(signature.typeParameters, function (tp) { return tp.target && !getConstraintOfTypeParameter(tp.target) ? tp.target : tp; }), ts.isInJSFile(signature.declaration)); + } + function getBaseSignature(signature) { + var typeParameters = signature.typeParameters; + if (typeParameters) { + var typeEraser_1 = createTypeEraser(typeParameters); + var baseConstraints = ts.map(typeParameters, function (tp) { return instantiateType(getBaseConstraintOfType(tp), typeEraser_1) || emptyObjectType; }); + return instantiateSignature(signature, createTypeMapper(typeParameters, baseConstraints), /*eraseTypeParameters*/ true); + } + return signature; + } + function getOrCreateTypeFromSignature(signature) { + // There are two ways to declare a construct signature, one is by declaring a class constructor + // using the constructor keyword, and the other is declaring a bare construct signature in an + // object type literal or interface (using the new keyword). Each way of declaring a constructor + // will result in a different declaration kind. + if (!signature.isolatedSignatureType) { + var isConstructor = signature.declaration.kind === 157 /* Constructor */ || signature.declaration.kind === 161 /* ConstructSignature */; // TODO: GH#18217 + var type = createObjectType(16 /* Anonymous */); + type.members = emptySymbols; + type.properties = ts.emptyArray; + type.callSignatures = !isConstructor ? [signature] : ts.emptyArray; + type.constructSignatures = isConstructor ? [signature] : ts.emptyArray; + signature.isolatedSignatureType = type; + } + return signature.isolatedSignatureType; + } + function getIndexSymbol(symbol) { + return symbol.members.get("__index" /* Index */); + } + function getIndexDeclarationOfSymbol(symbol, kind) { + var syntaxKind = kind === 1 /* Number */ ? 135 /* NumberKeyword */ : 138 /* StringKeyword */; + var indexSymbol = getIndexSymbol(symbol); + if (indexSymbol) { + for (var _i = 0, _a = indexSymbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + var node = ts.cast(decl, ts.isIndexSignatureDeclaration); + if (node.parameters.length === 1) { + var parameter = node.parameters[0]; + if (parameter.type && parameter.type.kind === syntaxKind) { + return node; + } + } + } + } + return undefined; + } + function createIndexInfo(type, isReadonly, declaration) { + return { type: type, isReadonly: isReadonly, declaration: declaration }; + } + function getIndexInfoOfSymbol(symbol, kind) { + var declaration = getIndexDeclarationOfSymbol(symbol, kind); + if (declaration) { + return createIndexInfo(declaration.type ? getTypeFromTypeNode(declaration.type) : anyType, ts.hasModifier(declaration, 64 /* Readonly */), declaration); + } + return undefined; + } + function getConstraintDeclaration(type) { + var decl = type.symbol && ts.getDeclarationOfKind(type.symbol, 150 /* TypeParameter */); + return decl && ts.getEffectiveConstraintOfTypeParameter(decl); + } + function getInferredTypeParameterConstraint(typeParameter) { + var inferences; + if (typeParameter.symbol) { + for (var _i = 0, _a = typeParameter.symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (declaration.parent.kind === 176 /* InferType */) { + // When an 'infer T' declaration is immediately contained in a type reference node + // (such as 'Foo'), T's constraint is inferred from the constraint of the + // corresponding type parameter in 'Foo'. When multiple 'infer T' declarations are + // present, we form an intersection of the inferred constraint types. + var grandParent = declaration.parent.parent; + if (grandParent.kind === 164 /* TypeReference */) { + var typeReference = grandParent; + var typeParameters = getTypeParametersForTypeReference(typeReference); + if (typeParameters) { + var index = typeReference.typeArguments.indexOf(declaration.parent); + if (index < typeParameters.length) { + var declaredConstraint = getConstraintOfTypeParameter(typeParameters[index]); + if (declaredConstraint) { + // Type parameter constraints can reference other type parameters so + // constraints need to be instantiated. If instantiation produces the + // type parameter itself, we discard that inference. For example, in + // type Foo = [T, U]; + // type Bar = T extends Foo ? Foo : T; + // the instantiated constraint for U is X, so we discard that inference. + var mapper = createTypeMapper(typeParameters, getEffectiveTypeArguments(typeReference, typeParameters)); + var constraint = instantiateType(declaredConstraint, mapper); + if (constraint !== typeParameter) { + inferences = ts.append(inferences, constraint); + } + } + } + } + } + // When an 'infer T' declaration is immediately contained in a rest parameter + // declaration, we infer an 'unknown[]' constraint. + else if (grandParent.kind === 151 /* Parameter */ && grandParent.dotDotDotToken) { + inferences = ts.append(inferences, createArrayType(unknownType)); + } + } + } + } + return inferences && getIntersectionType(inferences); + } + /** This is a worker function. Use getConstraintOfTypeParameter which guards against circular constraints. */ + function getConstraintFromTypeParameter(typeParameter) { + if (!typeParameter.constraint) { + if (typeParameter.target) { + var targetConstraint = getConstraintOfTypeParameter(typeParameter.target); + typeParameter.constraint = targetConstraint ? instantiateType(targetConstraint, typeParameter.mapper) : noConstraintType; + } + else { + var constraintDeclaration = getConstraintDeclaration(typeParameter); + typeParameter.constraint = constraintDeclaration ? getTypeFromTypeNode(constraintDeclaration) : + getInferredTypeParameterConstraint(typeParameter) || noConstraintType; + } + } + return typeParameter.constraint === noConstraintType ? undefined : typeParameter.constraint; + } + function getParentSymbolOfTypeParameter(typeParameter) { + var tp = ts.getDeclarationOfKind(typeParameter.symbol, 150 /* TypeParameter */); + var host = ts.isJSDocTemplateTag(tp.parent) ? ts.getHostSignatureFromJSDoc(tp.parent) : tp.parent; + return host && getSymbolOfNode(host); + } + function getTypeListId(types) { + var result = ""; + if (types) { + var length_3 = types.length; + var i = 0; + while (i < length_3) { + var startId = types[i].id; + var count = 1; + while (i + count < length_3 && types[i + count].id === startId + count) { + count++; + } + if (result.length) { + result += ","; + } + result += startId; + if (count > 1) { + result += ":" + count; + } + i += count; + } + } + return result; + } + // This function is used to propagate certain flags when creating new object type references and union types. + // It is only necessary to do so if a constituent type might be the undefined type, the null type, the type + // of an object literal or the anyFunctionType. This is because there are operations in the type checker + // that care about the presence of such types at arbitrary depth in a containing type. + function getPropagatingFlagsOfTypes(types, excludeKinds) { + var result = 0; + for (var _i = 0, types_5 = types; _i < types_5.length; _i++) { + var type = types_5[_i]; + if (!(type.flags & excludeKinds)) { + result |= type.flags; + } + } + return result & 939524096 /* PropagatingFlags */; + } + function createTypeReference(target, typeArguments) { + var id = getTypeListId(typeArguments); + var type = target.instantiations.get(id); + if (!type) { + type = createObjectType(4 /* Reference */, target.symbol); + target.instantiations.set(id, type); + type.flags |= typeArguments ? getPropagatingFlagsOfTypes(typeArguments, /*excludeKinds*/ 0) : 0; + type.target = target; + type.typeArguments = typeArguments; + } + return type; + } + function cloneTypeReference(source) { + var type = createType(source.flags); + type.symbol = source.symbol; + type.objectFlags = source.objectFlags; + type.target = source.target; + type.typeArguments = source.typeArguments; + return type; + } + function getTypeReferenceArity(type) { + return ts.length(type.target.typeParameters); + } + /** + * Get type from type-reference that reference to class or interface + */ + function getTypeFromClassOrInterfaceReference(node, symbol, typeArgs) { + var type = getDeclaredTypeOfSymbol(getMergedSymbol(symbol)); + var typeParameters = type.localTypeParameters; + if (typeParameters) { + var numTypeArguments = ts.length(node.typeArguments); + var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters); + var isJs = ts.isInJSFile(node); + var isJsImplicitAny = !noImplicitAny && isJs; + if (!isJsImplicitAny && (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length)) { + var missingAugmentsTag = isJs && ts.isExpressionWithTypeArguments(node) && !ts.isJSDocAugmentsTag(node.parent); + var diag = minTypeArgumentCount === typeParameters.length + ? missingAugmentsTag + ? ts.Diagnostics.Expected_0_type_arguments_provide_these_with_an_extends_tag + : ts.Diagnostics.Generic_type_0_requires_1_type_argument_s + : missingAugmentsTag + ? ts.Diagnostics.Expected_0_1_type_arguments_provide_these_with_an_extends_tag + : ts.Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments; + var typeStr = typeToString(type, /*enclosingDeclaration*/ undefined, 2 /* WriteArrayAsGenericType */); + error(node, diag, typeStr, minTypeArgumentCount, typeParameters.length); + if (!isJs) { + // TODO: Adopt same permissive behavior in TS as in JS to reduce follow-on editing experience failures (requires editing fillMissingTypeArguments) + return errorType; + } + } + // In a type reference, the outer type parameters of the referenced class or interface are automatically + // supplied as type arguments and the type reference only specifies arguments for the local type parameters + // of the class or interface. + var typeArguments = ts.concatenate(type.outerTypeParameters, fillMissingTypeArguments(typeArgs, typeParameters, minTypeArgumentCount, isJs)); + return createTypeReference(type, typeArguments); + } + return checkNoTypeArguments(node, symbol) ? type : errorType; + } + function getTypeAliasInstantiation(symbol, typeArguments) { + var type = getDeclaredTypeOfSymbol(symbol); + var links = getSymbolLinks(symbol); + var typeParameters = links.typeParameters; + var id = getTypeListId(typeArguments); + var instantiation = links.instantiations.get(id); + if (!instantiation) { + links.instantiations.set(id, instantiation = instantiateType(type, createTypeMapper(typeParameters, fillMissingTypeArguments(typeArguments, typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJSFile(symbol.valueDeclaration))))); + } + return instantiation; + } + /** + * Get type from reference to type alias. When a type alias is generic, the declared type of the type alias may include + * references to the type parameters of the alias. We replace those with the actual type arguments by instantiating the + * declared type. Instantiations are cached using the type identities of the type arguments as the key. + */ + function getTypeFromTypeAliasReference(node, symbol, typeArguments) { + var type = getDeclaredTypeOfSymbol(symbol); + var typeParameters = getSymbolLinks(symbol).typeParameters; + if (typeParameters) { + var numTypeArguments = ts.length(node.typeArguments); + var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters); + if (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length) { + error(node, minTypeArgumentCount === typeParameters.length + ? ts.Diagnostics.Generic_type_0_requires_1_type_argument_s + : ts.Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments, symbolToString(symbol), minTypeArgumentCount, typeParameters.length); + return errorType; + } + return getTypeAliasInstantiation(symbol, typeArguments); + } + return checkNoTypeArguments(node, symbol) ? type : errorType; + } + function getTypeReferenceName(node) { + switch (node.kind) { + case 164 /* TypeReference */: + return node.typeName; + case 211 /* ExpressionWithTypeArguments */: + // We only support expressions that are simple qualified names. For other + // expressions this produces undefined. + var expr = node.expression; + if (ts.isEntityNameExpression(expr)) { + return expr; + } + // fall through; + } + return undefined; + } + function resolveTypeReferenceName(typeReferenceName, meaning) { + if (!typeReferenceName) { + return unknownSymbol; + } + return resolveEntityName(typeReferenceName, meaning) || unknownSymbol; + } + function getTypeReferenceType(node, symbol) { + var typeArguments = typeArgumentsFromTypeReferenceNode(node); // Do unconditionally so we mark type arguments as referenced. + if (symbol === unknownSymbol) { + return errorType; + } + var type = getTypeReferenceTypeWorker(node, symbol, typeArguments); + if (type) { + return type; + } + // JS enums are 'string' or 'number', not an enum type. + var enumTag = ts.isInJSFile(node) && symbol.valueDeclaration && ts.getJSDocEnumTag(symbol.valueDeclaration); + if (enumTag) { + var links = getNodeLinks(enumTag); + if (!pushTypeResolution(enumTag, 5 /* EnumTagType */)) { + return errorType; + } + var type_4 = enumTag.typeExpression ? getTypeFromTypeNode(enumTag.typeExpression) : errorType; + if (!popTypeResolution()) { + type_4 = errorType; + error(node, ts.Diagnostics.Enum_type_0_circularly_references_itself, symbolToString(symbol)); + } + return (links.resolvedEnumType = type_4); + } + // Get type from reference to named type that cannot be generic (enum or type parameter) + var res = tryGetDeclaredTypeOfSymbol(symbol); + if (res) { + return checkNoTypeArguments(node, symbol) ? + res.flags & 262144 /* TypeParameter */ ? getConstrainedTypeVariable(res, node) : getRegularTypeOfLiteralType(res) : + errorType; + } + if (!(symbol.flags & 67220415 /* Value */ && isJSDocTypeReference(node))) { + return errorType; + } + var jsdocType = getJSDocTypeReference(node, symbol, typeArguments); + if (jsdocType) { + return jsdocType; + } + // Resolve the type reference as a Type for the purpose of reporting errors. + resolveTypeReferenceName(getTypeReferenceName(node), 67897832 /* Type */); + return getTypeOfSymbol(symbol); + } + /** + * A jsdoc TypeReference may have resolved to a value (as opposed to a type). If + * the symbol is a constructor function, return the inferred class type; otherwise, + * the type of this reference is just the type of the value we resolved to. + */ + function getJSDocTypeReference(node, symbol, typeArguments) { + if (!pushTypeResolution(symbol, 6 /* JSDocTypeReference */)) { + return errorType; + } + var assignedType = getAssignedClassType(symbol); + var valueType = getTypeOfSymbol(symbol); + var referenceType = valueType.symbol && valueType.symbol !== symbol && !isInferredClassType(valueType) && getTypeReferenceTypeWorker(node, valueType.symbol, typeArguments); + if (!popTypeResolution()) { + getSymbolLinks(symbol).resolvedJSDocType = errorType; + error(node, ts.Diagnostics.JSDoc_type_0_circularly_references_itself, symbolToString(symbol)); + return errorType; + } + if (referenceType || assignedType) { + // TODO: GH#18217 (should the `|| assignedType` be at a lower precedence?) + var type = (referenceType && assignedType ? getIntersectionType([assignedType, referenceType]) : referenceType || assignedType); + return getSymbolLinks(symbol).resolvedJSDocType = type; + } + } + function getTypeReferenceTypeWorker(node, symbol, typeArguments) { + if (symbol.flags & (32 /* Class */ | 64 /* Interface */)) { + if (symbol.valueDeclaration && ts.isBinaryExpression(symbol.valueDeclaration.parent)) { + var jsdocType = getJSDocTypeReference(node, symbol, typeArguments); + if (jsdocType) { + return jsdocType; + } + } + return getTypeFromClassOrInterfaceReference(node, symbol, typeArguments); + } + if (symbol.flags & 524288 /* TypeAlias */) { + return getTypeFromTypeAliasReference(node, symbol, typeArguments); + } + if (symbol.flags & 16 /* Function */ && + isJSDocTypeReference(node) && + (symbol.members || ts.getJSDocClassTag(symbol.valueDeclaration))) { + return getInferredClassType(symbol); + } + } + function getSubstitutionType(typeVariable, substitute) { + var result = createType(33554432 /* Substitution */); + result.typeVariable = typeVariable; + result.substitute = substitute; + return result; + } + function isUnaryTupleTypeNode(node) { + return node.kind === 170 /* TupleType */ && node.elementTypes.length === 1; + } + function getImpliedConstraint(typeVariable, checkNode, extendsNode) { + return isUnaryTupleTypeNode(checkNode) && isUnaryTupleTypeNode(extendsNode) ? getImpliedConstraint(typeVariable, checkNode.elementTypes[0], extendsNode.elementTypes[0]) : + getActualTypeVariable(getTypeFromTypeNode(checkNode)) === typeVariable ? getTypeFromTypeNode(extendsNode) : + undefined; + } + function getConstrainedTypeVariable(typeVariable, node) { + var constraints; + while (node && !ts.isStatement(node) && node.kind !== 291 /* JSDocComment */) { + var parent = node.parent; + if (parent.kind === 175 /* ConditionalType */ && node === parent.trueType) { + var constraint = getImpliedConstraint(typeVariable, parent.checkType, parent.extendsType); + if (constraint) { + constraints = ts.append(constraints, constraint); + } + } + node = parent; + } + return constraints ? getSubstitutionType(typeVariable, getIntersectionType(ts.append(constraints, typeVariable))) : typeVariable; + } + function isJSDocTypeReference(node) { + return !!(node.flags & 2097152 /* JSDoc */) && (node.kind === 164 /* TypeReference */ || node.kind === 183 /* ImportType */); + } + function checkNoTypeArguments(node, symbol) { + if (node.typeArguments) { + error(node, ts.Diagnostics.Type_0_is_not_generic, symbol ? symbolToString(symbol) : node.typeName ? ts.declarationNameToString(node.typeName) : "(anonymous)"); + return false; + } + return true; + } + function getIntendedTypeFromJSDocTypeReference(node) { + if (ts.isIdentifier(node.typeName)) { + var typeArgs = node.typeArguments; + switch (node.typeName.escapedText) { + case "String": + checkNoTypeArguments(node); + return stringType; + case "Number": + checkNoTypeArguments(node); + return numberType; + case "Boolean": + checkNoTypeArguments(node); + return booleanType; + case "Void": + checkNoTypeArguments(node); + return voidType; + case "Undefined": + checkNoTypeArguments(node); + return undefinedType; + case "Null": + checkNoTypeArguments(node); + return nullType; + case "Function": + case "function": + checkNoTypeArguments(node); + return globalFunctionType; + case "Array": + case "array": + return !typeArgs || !typeArgs.length ? anyArrayType : undefined; + case "Promise": + case "promise": + return !typeArgs || !typeArgs.length ? createPromiseType(anyType) : undefined; + case "Object": + if (typeArgs && typeArgs.length === 2) { + if (ts.isJSDocIndexSignature(node)) { + var indexed = getTypeFromTypeNode(typeArgs[0]); + var target = getTypeFromTypeNode(typeArgs[1]); + var index = createIndexInfo(target, /*isReadonly*/ false); + return createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, indexed === stringType ? index : undefined, indexed === numberType ? index : undefined); + } + return anyType; + } + checkNoTypeArguments(node); + return anyType; + } + } + } + function getTypeFromJSDocNullableTypeNode(node) { + var type = getTypeFromTypeNode(node.type); + return strictNullChecks ? getNullableType(type, 65536 /* Null */) : type; + } + function getTypeFromTypeReference(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + var symbol = void 0; + var type = void 0; + var meaning = 67897832 /* Type */; + if (isJSDocTypeReference(node)) { + type = getIntendedTypeFromJSDocTypeReference(node); + meaning |= 67220415 /* Value */; + } + if (!type) { + symbol = resolveTypeReferenceName(getTypeReferenceName(node), meaning); + type = getTypeReferenceType(node, symbol); + } + // Cache both the resolved symbol and the resolved type. The resolved symbol is needed when we check the + // type reference in checkTypeReferenceNode. + links.resolvedSymbol = symbol; + links.resolvedType = type; + } + return links.resolvedType; + } + function typeArgumentsFromTypeReferenceNode(node) { + return ts.map(node.typeArguments, getTypeFromTypeNode); + } + function getTypeFromTypeQueryNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + // TypeScript 1.0 spec (April 2014): 3.6.3 + // The expression is processed as an identifier expression (section 4.3) + // or property access expression(section 4.10), + // the widened type(section 3.9) of which becomes the result. + links.resolvedType = getRegularTypeOfLiteralType(getWidenedType(checkExpression(node.exprName))); + } + return links.resolvedType; + } + function getTypeOfGlobalSymbol(symbol, arity) { + function getTypeDeclaration(symbol) { + var declarations = symbol.declarations; + for (var _i = 0, declarations_3 = declarations; _i < declarations_3.length; _i++) { + var declaration = declarations_3[_i]; + switch (declaration.kind) { + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + case 243 /* EnumDeclaration */: + return declaration; + } + } + } + if (!symbol) { + return arity ? emptyGenericType : emptyObjectType; + } + var type = getDeclaredTypeOfSymbol(symbol); + if (!(type.flags & 524288 /* Object */)) { + error(getTypeDeclaration(symbol), ts.Diagnostics.Global_type_0_must_be_a_class_or_interface_type, ts.symbolName(symbol)); + return arity ? emptyGenericType : emptyObjectType; + } + if (ts.length(type.typeParameters) !== arity) { + error(getTypeDeclaration(symbol), ts.Diagnostics.Global_type_0_must_have_1_type_parameter_s, ts.symbolName(symbol), arity); + return arity ? emptyGenericType : emptyObjectType; + } + return type; + } + function getGlobalValueSymbol(name, reportErrors) { + return getGlobalSymbol(name, 67220415 /* Value */, reportErrors ? ts.Diagnostics.Cannot_find_global_value_0 : undefined); + } + function getGlobalTypeSymbol(name, reportErrors) { + return getGlobalSymbol(name, 67897832 /* Type */, reportErrors ? ts.Diagnostics.Cannot_find_global_type_0 : undefined); + } + function getGlobalSymbol(name, meaning, diagnostic) { + // Don't track references for global symbols anyway, so value if `isReference` is arbitrary + return resolveName(undefined, name, meaning, diagnostic, name, /*isUse*/ false); + } + function getGlobalType(name, arity, reportErrors) { + var symbol = getGlobalTypeSymbol(name, reportErrors); + return symbol || reportErrors ? getTypeOfGlobalSymbol(symbol, arity) : undefined; + } + function getGlobalTypedPropertyDescriptorType() { + return deferredGlobalTypedPropertyDescriptorType || (deferredGlobalTypedPropertyDescriptorType = getGlobalType("TypedPropertyDescriptor", /*arity*/ 1, /*reportErrors*/ true)) || emptyGenericType; + } + function getGlobalTemplateStringsArrayType() { + return deferredGlobalTemplateStringsArrayType || (deferredGlobalTemplateStringsArrayType = getGlobalType("TemplateStringsArray", /*arity*/ 0, /*reportErrors*/ true)) || emptyObjectType; + } + function getGlobalImportMetaType() { + return deferredGlobalImportMetaType || (deferredGlobalImportMetaType = getGlobalType("ImportMeta", /*arity*/ 0, /*reportErrors*/ true)) || emptyObjectType; + } + function getGlobalESSymbolConstructorSymbol(reportErrors) { + return deferredGlobalESSymbolConstructorSymbol || (deferredGlobalESSymbolConstructorSymbol = getGlobalValueSymbol("Symbol", reportErrors)); + } + function getGlobalESSymbolType(reportErrors) { + return deferredGlobalESSymbolType || (deferredGlobalESSymbolType = getGlobalType("Symbol", /*arity*/ 0, reportErrors)) || emptyObjectType; + } + function getGlobalPromiseType(reportErrors) { + return deferredGlobalPromiseType || (deferredGlobalPromiseType = getGlobalType("Promise", /*arity*/ 1, reportErrors)) || emptyGenericType; + } + function getGlobalPromiseLikeType(reportErrors) { + return deferredGlobalPromiseLikeType || (deferredGlobalPromiseLikeType = getGlobalType("PromiseLike", /*arity*/ 1, reportErrors)) || emptyGenericType; + } + function getGlobalPromiseConstructorSymbol(reportErrors) { + return deferredGlobalPromiseConstructorSymbol || (deferredGlobalPromiseConstructorSymbol = getGlobalValueSymbol("Promise", reportErrors)); + } + function getGlobalPromiseConstructorLikeType(reportErrors) { + return deferredGlobalPromiseConstructorLikeType || (deferredGlobalPromiseConstructorLikeType = getGlobalType("PromiseConstructorLike", /*arity*/ 0, reportErrors)) || emptyObjectType; + } + function getGlobalAsyncIterableType(reportErrors) { + return deferredGlobalAsyncIterableType || (deferredGlobalAsyncIterableType = getGlobalType("AsyncIterable", /*arity*/ 1, reportErrors)) || emptyGenericType; + } + function getGlobalAsyncIteratorType(reportErrors) { + return deferredGlobalAsyncIteratorType || (deferredGlobalAsyncIteratorType = getGlobalType("AsyncIterator", /*arity*/ 1, reportErrors)) || emptyGenericType; + } + function getGlobalAsyncIterableIteratorType(reportErrors) { + return deferredGlobalAsyncIterableIteratorType || (deferredGlobalAsyncIterableIteratorType = getGlobalType("AsyncIterableIterator", /*arity*/ 1, reportErrors)) || emptyGenericType; + } + function getGlobalIterableType(reportErrors) { + return deferredGlobalIterableType || (deferredGlobalIterableType = getGlobalType("Iterable", /*arity*/ 1, reportErrors)) || emptyGenericType; + } + function getGlobalIteratorType(reportErrors) { + return deferredGlobalIteratorType || (deferredGlobalIteratorType = getGlobalType("Iterator", /*arity*/ 1, reportErrors)) || emptyGenericType; + } + function getGlobalIterableIteratorType(reportErrors) { + return deferredGlobalIterableIteratorType || (deferredGlobalIterableIteratorType = getGlobalType("IterableIterator", /*arity*/ 1, reportErrors)) || emptyGenericType; + } + function getGlobalTypeOrUndefined(name, arity) { + if (arity === void 0) { arity = 0; } + var symbol = getGlobalSymbol(name, 67897832 /* Type */, /*diagnostic*/ undefined); + return symbol && getTypeOfGlobalSymbol(symbol, arity); + } + function getGlobalExtractSymbol() { + return deferredGlobalExtractSymbol || (deferredGlobalExtractSymbol = getGlobalSymbol("Extract", 524288 /* TypeAlias */, ts.Diagnostics.Cannot_find_global_type_0)); // TODO: GH#18217 + } + function getGlobalExcludeSymbol() { + return deferredGlobalExcludeSymbol || (deferredGlobalExcludeSymbol = getGlobalSymbol("Exclude", 524288 /* TypeAlias */, ts.Diagnostics.Cannot_find_global_type_0)); // TODO: GH#18217 + } + function getGlobalPickSymbol() { + return deferredGlobalPickSymbol || (deferredGlobalPickSymbol = getGlobalSymbol("Pick", 524288 /* TypeAlias */, ts.Diagnostics.Cannot_find_global_type_0)); // TODO: GH#18217 + } + function getGlobalBigIntType(reportErrors) { + return deferredGlobalBigIntType || (deferredGlobalBigIntType = getGlobalType("BigInt", /*arity*/ 0, reportErrors)) || emptyObjectType; + } + /** + * Instantiates a global type that is generic with some element type, and returns that instantiation. + */ + function createTypeFromGenericGlobalType(genericGlobalType, typeArguments) { + return genericGlobalType !== emptyGenericType ? createTypeReference(genericGlobalType, typeArguments) : emptyObjectType; + } + function createTypedPropertyDescriptorType(propertyType) { + return createTypeFromGenericGlobalType(getGlobalTypedPropertyDescriptorType(), [propertyType]); + } + function createAsyncIterableType(iteratedType) { + return createTypeFromGenericGlobalType(getGlobalAsyncIterableType(/*reportErrors*/ true), [iteratedType]); + } + function createAsyncIterableIteratorType(iteratedType) { + return createTypeFromGenericGlobalType(getGlobalAsyncIterableIteratorType(/*reportErrors*/ true), [iteratedType]); + } + function createIterableType(iteratedType) { + return createTypeFromGenericGlobalType(getGlobalIterableType(/*reportErrors*/ true), [iteratedType]); + } + function createIterableIteratorType(iteratedType) { + return createTypeFromGenericGlobalType(getGlobalIterableIteratorType(/*reportErrors*/ true), [iteratedType]); + } + function createArrayType(elementType) { + return createTypeFromGenericGlobalType(globalArrayType, [elementType]); + } + function createReadonlyArrayType(elementType) { + return createTypeFromGenericGlobalType(globalReadonlyArrayType, [elementType]); + } + function getTypeFromArrayTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + links.resolvedType = createArrayType(getTypeFromTypeNode(node.elementType)); + } + return links.resolvedType; + } + // We represent tuple types as type references to synthesized generic interface types created by + // this function. The types are of the form: + // + // interface Tuple extends Array { 0: T0, 1: T1, 2: T2, ... } + // + // Note that the generic type created by this function has no symbol associated with it. The same + // is true for each of the synthesized type parameters. + function createTupleTypeOfArity(arity, minLength, hasRestElement, associatedNames) { + var typeParameters; + var properties = []; + var maxLength = hasRestElement ? arity - 1 : arity; + if (arity) { + typeParameters = new Array(arity); + for (var i = 0; i < arity; i++) { + var typeParameter = typeParameters[i] = createType(262144 /* TypeParameter */); + if (i < maxLength) { + var property = createSymbol(4 /* Property */ | (i >= minLength ? 16777216 /* Optional */ : 0), "" + i); + property.type = typeParameter; + properties.push(property); + } + } + } + var literalTypes = []; + for (var i = minLength; i <= maxLength; i++) + literalTypes.push(getLiteralType(i)); + var lengthSymbol = createSymbol(4 /* Property */, "length"); + lengthSymbol.type = hasRestElement ? numberType : getUnionType(literalTypes); + properties.push(lengthSymbol); + var type = createObjectType(8 /* Tuple */ | 4 /* Reference */); + type.typeParameters = typeParameters; + type.outerTypeParameters = undefined; + type.localTypeParameters = typeParameters; + type.instantiations = ts.createMap(); + type.instantiations.set(getTypeListId(type.typeParameters), type); + type.target = type; + type.typeArguments = type.typeParameters; + type.thisType = createType(262144 /* TypeParameter */); + type.thisType.isThisType = true; + type.thisType.constraint = type; + type.declaredProperties = properties; + type.declaredCallSignatures = ts.emptyArray; + type.declaredConstructSignatures = ts.emptyArray; + type.declaredStringIndexInfo = undefined; + type.declaredNumberIndexInfo = undefined; + type.minLength = minLength; + type.hasRestElement = hasRestElement; + type.associatedNames = associatedNames; + return type; + } + function getTupleTypeOfArity(arity, minLength, hasRestElement, associatedNames) { + var key = arity + (hasRestElement ? "+" : ",") + minLength + (associatedNames && associatedNames.length ? "," + associatedNames.join(",") : ""); + var type = tupleTypes.get(key); + if (!type) { + tupleTypes.set(key, type = createTupleTypeOfArity(arity, minLength, hasRestElement, associatedNames)); + } + return type; + } + function createTupleType(elementTypes, minLength, hasRestElement, associatedNames) { + if (minLength === void 0) { minLength = elementTypes.length; } + if (hasRestElement === void 0) { hasRestElement = false; } + var arity = elementTypes.length; + if (arity === 1 && hasRestElement) { + return createArrayType(elementTypes[0]); + } + var tupleType = getTupleTypeOfArity(arity, minLength, arity > 0 && hasRestElement, associatedNames); + return elementTypes.length ? createTypeReference(tupleType, elementTypes) : tupleType; + } + function getTypeFromTupleTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + var lastElement = ts.lastOrUndefined(node.elementTypes); + var restElement_1 = lastElement && lastElement.kind === 172 /* RestType */ ? lastElement : undefined; + var minLength = ts.findLastIndex(node.elementTypes, function (n) { return n.kind !== 171 /* OptionalType */ && n !== restElement_1; }) + 1; + var elementTypes = ts.map(node.elementTypes, function (n) { + var type = getTypeFromTypeNode(n); + return n === restElement_1 && getIndexTypeOfType(type, 1 /* Number */) || type; + }); + links.resolvedType = createTupleType(elementTypes, minLength, !!restElement_1); + } + return links.resolvedType; + } + function sliceTupleType(type, index) { + var tuple = type.target; + if (tuple.hasRestElement) { + // don't slice off rest element + index = Math.min(index, getTypeReferenceArity(type) - 1); + } + return createTupleType((type.typeArguments || ts.emptyArray).slice(index), Math.max(0, tuple.minLength - index), tuple.hasRestElement, tuple.associatedNames && tuple.associatedNames.slice(index)); + } + function getTypeFromOptionalTypeNode(node) { + var type = getTypeFromTypeNode(node.type); + return strictNullChecks ? getOptionalType(type) : type; + } + function getTypeId(type) { + return type.id; + } + function containsType(types, type) { + return ts.binarySearch(types, type, getTypeId, ts.compareValues) >= 0; + } + function insertType(types, type) { + var index = ts.binarySearch(types, type, getTypeId, ts.compareValues); + if (index < 0) { + types.splice(~index, 0, type); + return true; + } + return false; + } + // Return true if the given intersection type contains + // more than one unit type or, + // an object type and a nullable type (null or undefined), or + // a string-like type and a type known to be non-string-like, or + // a number-like type and a type known to be non-number-like, or + // a symbol-like type and a type known to be non-symbol-like, or + // a void-like type and a type known to be non-void-like, or + // a non-primitive type and a type known to be primitive. + function isEmptyIntersectionType(type) { + var combined = 0; + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (t.flags & 109440 /* Unit */ && combined & 109440 /* Unit */) { + return true; + } + combined |= t.flags; + if (combined & 98304 /* Nullable */ && combined & (524288 /* Object */ | 67108864 /* NonPrimitive */) || + combined & 67108864 /* NonPrimitive */ && combined & (67238908 /* DisjointDomains */ & ~67108864 /* NonPrimitive */) || + combined & 132 /* StringLike */ && combined & (67238908 /* DisjointDomains */ & ~132 /* StringLike */) || + combined & 296 /* NumberLike */ && combined & (67238908 /* DisjointDomains */ & ~296 /* NumberLike */) || + combined & 2112 /* BigIntLike */ && combined & (67238908 /* DisjointDomains */ & ~2112 /* BigIntLike */) || + combined & 12288 /* ESSymbolLike */ && combined & (67238908 /* DisjointDomains */ & ~12288 /* ESSymbolLike */) || + combined & 49152 /* VoidLike */ && combined & (67238908 /* DisjointDomains */ & ~49152 /* VoidLike */)) { + return true; + } + } + return false; + } + function addTypeToUnion(typeSet, includes, type) { + var flags = type.flags; + if (flags & 1048576 /* Union */) { + return addTypesToUnion(typeSet, includes, type.types); + } + // We ignore 'never' types in unions. Likewise, we ignore intersections of unit types as they are + // another form of 'never' (in that they have an empty value domain). We could in theory turn + // intersections of unit types into 'never' upon construction, but deferring the reduction makes it + // easier to reason about their origin. + if (!(flags & 131072 /* Never */ || flags & 2097152 /* Intersection */ && isEmptyIntersectionType(type))) { + includes |= flags & ~939524096 /* ConstructionFlags */; + if (type === wildcardType) + includes |= 268435456 /* Wildcard */; + if (!strictNullChecks && flags & 98304 /* Nullable */) { + if (!(flags & 134217728 /* ContainsWideningType */)) + includes |= 134217728 /* NonWideningType */; + } + else { + var len = typeSet.length; + var index = len && type.id > typeSet[len - 1].id ? ~len : ts.binarySearch(typeSet, type, getTypeId, ts.compareValues); + if (index < 0) { + typeSet.splice(~index, 0, type); + } + } + } + return includes; + } + // Add the given types to the given type set. Order is preserved, duplicates are removed, + // and nested types of the given kind are flattened into the set. + function addTypesToUnion(typeSet, includes, types) { + for (var _i = 0, types_6 = types; _i < types_6.length; _i++) { + var type = types_6[_i]; + includes = addTypeToUnion(typeSet, includes, type); + } + return includes; + } + function isSubtypeOfAny(source, targets) { + for (var _i = 0, targets_1 = targets; _i < targets_1.length; _i++) { + var target = targets_1[_i]; + if (source !== target && isTypeSubtypeOf(source, target) && (!(ts.getObjectFlags(getTargetType(source)) & 1 /* Class */) || + !(ts.getObjectFlags(getTargetType(target)) & 1 /* Class */) || + isTypeDerivedFrom(source, target))) { + return true; + } + } + return false; + } + function isSetOfLiteralsFromSameEnum(types) { + var first = types[0]; + if (first.flags & 1024 /* EnumLiteral */) { + var firstEnum = getParentOfSymbol(first.symbol); + for (var i = 1; i < types.length; i++) { + var other = types[i]; + if (!(other.flags & 1024 /* EnumLiteral */) || (firstEnum !== getParentOfSymbol(other.symbol))) { + return false; + } + } + return true; + } + return false; + } + function removeSubtypes(types) { + if (types.length === 0 || isSetOfLiteralsFromSameEnum(types)) { + return; + } + var i = types.length; + while (i > 0) { + i--; + if (isSubtypeOfAny(types[i], types)) { + ts.orderedRemoveItemAt(types, i); + } + } + } + function removeRedundantLiteralTypes(types, includes) { + var i = types.length; + while (i > 0) { + i--; + var t = types[i]; + var remove = t.flags & 128 /* StringLiteral */ && includes & 4 /* String */ || + t.flags & 256 /* NumberLiteral */ && includes & 8 /* Number */ || + t.flags & 2048 /* BigIntLiteral */ && includes & 64 /* BigInt */ || + t.flags & 8192 /* UniqueESSymbol */ && includes & 4096 /* ESSymbol */ || + isFreshLiteralType(t) && containsType(types, t.regularType); + if (remove) { + ts.orderedRemoveItemAt(types, i); + } + } + } + // We sort and deduplicate the constituent types based on object identity. If the subtypeReduction + // flag is specified we also reduce the constituent type set to only include types that aren't subtypes + // of other types. Subtype reduction is expensive for large union types and is possible only when union + // types are known not to circularly reference themselves (as is the case with union types created by + // expression constructs such as array literals and the || and ?: operators). Named types can + // circularly reference themselves and therefore cannot be subtype reduced during their declaration. + // For example, "type Item = string | (() => Item" is a named type that circularly references itself. + function getUnionType(types, unionReduction, aliasSymbol, aliasTypeArguments) { + if (unionReduction === void 0) { unionReduction = 1 /* Literal */; } + if (types.length === 0) { + return neverType; + } + if (types.length === 1) { + return types[0]; + } + var typeSet = []; + var includes = addTypesToUnion(typeSet, 0, types); + if (unionReduction !== 0 /* None */) { + if (includes & 3 /* AnyOrUnknown */) { + return includes & 1 /* Any */ ? includes & 268435456 /* Wildcard */ ? wildcardType : anyType : unknownType; + } + switch (unionReduction) { + case 1 /* Literal */: + if (includes & 8576 /* StringOrNumberLiteralOrUnique */ | 512 /* BooleanLiteral */) { + removeRedundantLiteralTypes(typeSet, includes); + } + break; + case 2 /* Subtype */: + removeSubtypes(typeSet); + break; + } + if (typeSet.length === 0) { + return includes & 65536 /* Null */ ? includes & 134217728 /* NonWideningType */ ? nullType : nullWideningType : + includes & 32768 /* Undefined */ ? includes & 134217728 /* NonWideningType */ ? undefinedType : undefinedWideningType : + neverType; + } + } + return getUnionTypeFromSortedList(typeSet, !(includes & 66994211 /* NotPrimitiveUnion */), aliasSymbol, aliasTypeArguments); + } + function getUnionTypePredicate(signatures) { + var first; + var types = []; + for (var _i = 0, signatures_2 = signatures; _i < signatures_2.length; _i++) { + var sig = signatures_2[_i]; + var pred = getTypePredicateOfSignature(sig); + if (!pred) { + continue; + } + if (first) { + if (!typePredicateKindsMatch(first, pred)) { + // No common type predicate. + return undefined; + } + } + else { + first = pred; + } + types.push(pred.type); + } + if (!first) { + // No union signatures had a type predicate. + return undefined; + } + var unionType = getUnionType(types); + return ts.isIdentifierTypePredicate(first) + ? createIdentifierTypePredicate(first.parameterName, first.parameterIndex, unionType) + : createThisTypePredicate(unionType); + } + function typePredicateKindsMatch(a, b) { + return ts.isIdentifierTypePredicate(a) + ? ts.isIdentifierTypePredicate(b) && a.parameterIndex === b.parameterIndex + : !ts.isIdentifierTypePredicate(b); + } + // This function assumes the constituent type list is sorted and deduplicated. + function getUnionTypeFromSortedList(types, primitiveTypesOnly, aliasSymbol, aliasTypeArguments) { + if (types.length === 0) { + return neverType; + } + if (types.length === 1) { + return types[0]; + } + var id = getTypeListId(types); + var type = unionTypes.get(id); + if (!type) { + var propagatedFlags = getPropagatingFlagsOfTypes(types, /*excludeKinds*/ 98304 /* Nullable */); + type = createType(1048576 /* Union */ | propagatedFlags); + unionTypes.set(id, type); + type.types = types; + type.primitiveTypesOnly = primitiveTypesOnly; + /* + Note: This is the alias symbol (or lack thereof) that we see when we first encounter this union type. + For aliases of identical unions, eg `type T = A | B; type U = A | B`, the symbol of the first alias encountered is the aliasSymbol. + (In the language service, the order may depend on the order in which a user takes actions, such as hovering over symbols.) + It's important that we create equivalent union types only once, so that's an unfortunate side effect. + */ + type.aliasSymbol = aliasSymbol; + type.aliasTypeArguments = aliasTypeArguments; + } + return type; + } + function getTypeFromUnionTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + var aliasSymbol = getAliasSymbolForTypeNode(node); + links.resolvedType = getUnionType(ts.map(node.types, getTypeFromTypeNode), 1 /* Literal */, aliasSymbol, getTypeArgumentsForAliasSymbol(aliasSymbol)); + } + return links.resolvedType; + } + function addTypeToIntersection(typeSet, includes, type) { + var flags = type.flags; + if (flags & 2097152 /* Intersection */) { + return addTypesToIntersection(typeSet, includes, type.types); + } + if (isEmptyAnonymousObjectType(type)) { + if (!(includes & 536870912 /* EmptyObject */)) { + includes |= 536870912 /* EmptyObject */; + typeSet.push(type); + } + } + else { + includes |= flags & ~939524096 /* ConstructionFlags */; + if (flags & 3 /* AnyOrUnknown */) { + if (type === wildcardType) + includes |= 268435456 /* Wildcard */; + } + else if ((strictNullChecks || !(flags & 98304 /* Nullable */)) && !ts.contains(typeSet, type)) { + typeSet.push(type); + } + } + return includes; + } + // Add the given types to the given type set. Order is preserved, freshness is removed from literal + // types, duplicates are removed, and nested types of the given kind are flattened into the set. + function addTypesToIntersection(typeSet, includes, types) { + for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { + var type = types_7[_i]; + includes = addTypeToIntersection(typeSet, includes, getRegularTypeOfLiteralType(type)); + } + return includes; + } + function removeRedundantPrimitiveTypes(types, includes) { + var i = types.length; + while (i > 0) { + i--; + var t = types[i]; + var remove = t.flags & 4 /* String */ && includes & 128 /* StringLiteral */ || + t.flags & 8 /* Number */ && includes & 256 /* NumberLiteral */ || + t.flags & 64 /* BigInt */ && includes & 2048 /* BigIntLiteral */ || + t.flags & 4096 /* ESSymbol */ && includes & 8192 /* UniqueESSymbol */; + if (remove) { + ts.orderedRemoveItemAt(types, i); + } + } + } + // Check that the given type has a match in every union. A given type is matched by + // an identical type, and a literal type is additionally matched by its corresponding + // primitive type. + function eachUnionContains(unionTypes, type) { + for (var _i = 0, unionTypes_1 = unionTypes; _i < unionTypes_1.length; _i++) { + var u = unionTypes_1[_i]; + if (!containsType(u.types, type)) { + var primitive = type.flags & 128 /* StringLiteral */ ? stringType : + type.flags & 256 /* NumberLiteral */ ? numberType : + type.flags & 2048 /* BigIntLiteral */ ? bigintType : + type.flags & 8192 /* UniqueESSymbol */ ? esSymbolType : + undefined; + if (!primitive || !containsType(u.types, primitive)) { + return false; + } + } + } + return true; + } + // If the given list of types contains more than one union of primitive types, replace the + // first with a union containing an intersection of those primitive types, then remove the + // other unions and return true. Otherwise, do nothing and return false. + function intersectUnionsOfPrimitiveTypes(types) { + var unionTypes; + var index = ts.findIndex(types, function (t) { return !!(t.flags & 1048576 /* Union */) && t.primitiveTypesOnly; }); + if (index < 0) { + return false; + } + var i = index + 1; + // Remove all but the first union of primitive types and collect them in + // the unionTypes array. + while (i < types.length) { + var t = types[i]; + if (t.flags & 1048576 /* Union */ && t.primitiveTypesOnly) { + (unionTypes || (unionTypes = [types[index]])).push(t); + ts.orderedRemoveItemAt(types, i); + } + else { + i++; + } + } + // Return false if there was only one union of primitive types + if (!unionTypes) { + return false; + } + // We have more than one union of primitive types, now intersect them. For each + // type in each union we check if the type is matched in every union and if so + // we include it in the result. + var checked = []; + var result = []; + for (var _i = 0, unionTypes_2 = unionTypes; _i < unionTypes_2.length; _i++) { + var u = unionTypes_2[_i]; + for (var _a = 0, _b = u.types; _a < _b.length; _a++) { + var t = _b[_a]; + if (insertType(checked, t)) { + if (eachUnionContains(unionTypes, t)) { + insertType(result, t); + } + } + } + } + // Finally replace the first union with the result + types[index] = getUnionTypeFromSortedList(result, /*primitiveTypesOnly*/ true); + return true; + } + // We normalize combinations of intersection and union types based on the distributive property of the '&' + // operator. Specifically, because X & (A | B) is equivalent to X & A | X & B, we can transform intersection + // types with union type constituents into equivalent union types with intersection type constituents and + // effectively ensure that union types are always at the top level in type representations. + // + // We do not perform structural deduplication on intersection types. Intersection types are created only by the & + // type operator and we can't reduce those because we want to support recursive intersection types. For example, + // a type alias of the form "type List = T & { next: List }" cannot be reduced during its declaration. + // Also, unlike union types, the order of the constituent types is preserved in order that overload resolution + // for intersections of types with signatures can be deterministic. + function getIntersectionType(types, aliasSymbol, aliasTypeArguments) { + var typeSet = []; + var includes = addTypesToIntersection(typeSet, 0, types); + if (includes & 131072 /* Never */) { + return neverType; + } + if (includes & 1 /* Any */) { + return includes & 268435456 /* Wildcard */ ? wildcardType : anyType; + } + if (!strictNullChecks && includes & 98304 /* Nullable */) { + return includes & 32768 /* Undefined */ ? undefinedType : nullType; + } + if (includes & 4 /* String */ && includes & 128 /* StringLiteral */ || + includes & 8 /* Number */ && includes & 256 /* NumberLiteral */ || + includes & 64 /* BigInt */ && includes & 2048 /* BigIntLiteral */ || + includes & 4096 /* ESSymbol */ && includes & 8192 /* UniqueESSymbol */) { + removeRedundantPrimitiveTypes(typeSet, includes); + } + if (includes & 536870912 /* EmptyObject */ && includes & 524288 /* Object */) { + ts.orderedRemoveItemAt(typeSet, ts.findIndex(typeSet, isEmptyAnonymousObjectType)); + } + if (typeSet.length === 0) { + return unknownType; + } + if (typeSet.length === 1) { + return typeSet[0]; + } + if (includes & 1048576 /* Union */) { + if (intersectUnionsOfPrimitiveTypes(typeSet)) { + // When the intersection creates a reduced set (which might mean that *all* union types have + // disappeared), we restart the operation to get a new set of combined flags. Once we have + // reduced we'll never reduce again, so this occurs at most once. + return getIntersectionType(typeSet, aliasSymbol, aliasTypeArguments); + } + // We are attempting to construct a type of the form X & (A | B) & Y. Transform this into a type of + // the form X & A & Y | X & B & Y and recursively reduce until no union type constituents remain. + var unionIndex_1 = ts.findIndex(typeSet, function (t) { return (t.flags & 1048576 /* Union */) !== 0; }); + var unionType = typeSet[unionIndex_1]; + return getUnionType(ts.map(unionType.types, function (t) { return getIntersectionType(ts.replaceElement(typeSet, unionIndex_1, t)); }), 1 /* Literal */, aliasSymbol, aliasTypeArguments); + } + var id = getTypeListId(typeSet); + var type = intersectionTypes.get(id); + if (!type) { + var propagatedFlags = getPropagatingFlagsOfTypes(typeSet, /*excludeKinds*/ 98304 /* Nullable */); + type = createType(2097152 /* Intersection */ | propagatedFlags); + intersectionTypes.set(id, type); + type.types = typeSet; + type.aliasSymbol = aliasSymbol; // See comment in `getUnionTypeFromSortedList`. + type.aliasTypeArguments = aliasTypeArguments; + } + return type; + } + function getTypeFromIntersectionTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + var aliasSymbol = getAliasSymbolForTypeNode(node); + links.resolvedType = getIntersectionType(ts.map(node.types, getTypeFromTypeNode), aliasSymbol, getTypeArgumentsForAliasSymbol(aliasSymbol)); + } + return links.resolvedType; + } + function createIndexType(type, stringsOnly) { + var result = createType(4194304 /* Index */); + result.type = type; + result.stringsOnly = stringsOnly; + return result; + } + function getIndexTypeForGenericType(type, stringsOnly) { + return stringsOnly ? + type.resolvedStringIndexType || (type.resolvedStringIndexType = createIndexType(type, /*stringsOnly*/ true)) : + type.resolvedIndexType || (type.resolvedIndexType = createIndexType(type, /*stringsOnly*/ false)); + } + function getLiteralTypeFromPropertyName(name) { + return ts.isIdentifier(name) ? getLiteralType(ts.unescapeLeadingUnderscores(name.escapedText)) : + getRegularTypeOfLiteralType(ts.isComputedPropertyName(name) ? checkComputedPropertyName(name) : checkExpression(name)); + } + function getBigIntLiteralType(node) { + return getLiteralType({ + negative: false, + base10Value: ts.parsePseudoBigInt(node.text) + }); + } + function getLiteralTypeFromProperty(prop, include) { + if (!(ts.getDeclarationModifierFlagsFromSymbol(prop) & 24 /* NonPublicAccessibilityModifier */)) { + var type = getLateBoundSymbol(prop).nameType; + if (!type && !ts.isKnownSymbol(prop)) { + if (prop.escapedName === "default" /* Default */) { + type = getLiteralType("default"); + } + else { + var name = prop.valueDeclaration && ts.getNameOfDeclaration(prop.valueDeclaration); + type = name && getLiteralTypeFromPropertyName(name) || getLiteralType(ts.symbolName(prop)); + } + } + if (type && type.flags & include) { + return type; + } + } + return neverType; + } + function getLiteralTypeFromProperties(type, include) { + return getUnionType(ts.map(getPropertiesOfType(type), function (t) { return getLiteralTypeFromProperty(t, include); })); + } + function getNonEnumNumberIndexInfo(type) { + var numberIndexInfo = getIndexInfoOfType(type, 1 /* Number */); + return numberIndexInfo !== enumNumberIndexInfo ? numberIndexInfo : undefined; + } + function getIndexType(type, stringsOnly) { + if (stringsOnly === void 0) { stringsOnly = keyofStringsOnly; } + return type.flags & 1048576 /* Union */ ? getIntersectionType(ts.map(type.types, function (t) { return getIndexType(t, stringsOnly); })) : + type.flags & 2097152 /* Intersection */ ? getUnionType(ts.map(type.types, function (t) { return getIndexType(t, stringsOnly); })) : + maybeTypeOfKind(type, 58982400 /* InstantiableNonPrimitive */) ? getIndexTypeForGenericType(type, stringsOnly) : + ts.getObjectFlags(type) & 32 /* Mapped */ ? getConstraintTypeFromMappedType(type) : + type === wildcardType ? wildcardType : + type.flags & 1 /* Any */ ? keyofConstraintType : + stringsOnly ? getIndexInfoOfType(type, 0 /* String */) ? stringType : getLiteralTypeFromProperties(type, 128 /* StringLiteral */) : + getIndexInfoOfType(type, 0 /* String */) ? getUnionType([stringType, numberType, getLiteralTypeFromProperties(type, 8192 /* UniqueESSymbol */)]) : + getNonEnumNumberIndexInfo(type) ? getUnionType([numberType, getLiteralTypeFromProperties(type, 128 /* StringLiteral */ | 8192 /* UniqueESSymbol */)]) : + getLiteralTypeFromProperties(type, 8576 /* StringOrNumberLiteralOrUnique */); + } + function getExtractStringType(type) { + if (keyofStringsOnly) { + return type; + } + var extractTypeAlias = getGlobalExtractSymbol(); + return extractTypeAlias ? getTypeAliasInstantiation(extractTypeAlias, [type, stringType]) : stringType; + } + function getIndexTypeOrString(type) { + var indexType = getExtractStringType(getIndexType(type)); + return indexType.flags & 131072 /* Never */ ? stringType : indexType; + } + function getTypeFromTypeOperatorNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + switch (node.operator) { + case 129 /* KeyOfKeyword */: + links.resolvedType = getIndexType(getTypeFromTypeNode(node.type)); + break; + case 142 /* UniqueKeyword */: + links.resolvedType = node.type.kind === 139 /* SymbolKeyword */ + ? getESSymbolLikeTypeForNode(ts.walkUpParenthesizedTypes(node.parent)) + : errorType; + break; + } + } + return links.resolvedType; // TODO: GH#18217 + } + function createIndexedAccessType(objectType, indexType) { + var type = createType(8388608 /* IndexedAccess */); + type.objectType = objectType; + type.indexType = indexType; + return type; + } + /** + * Returns if a type is or consists of a JSLiteral object type + * In addition to objects which are directly literals, + * * unions where every element is a jsliteral + * * intersections where at least one element is a jsliteral + * * and instantiable types constrained to a jsliteral + * Should all count as literals and not print errors on access or assignment of possibly existing properties. + * This mirrors the behavior of the index signature propagation, to which this behaves similarly (but doesn't affect assignability or inference). + */ + function isJSLiteralType(type) { + if (noImplicitAny) { + return false; // Flag is meaningless under `noImplicitAny` mode + } + if (ts.getObjectFlags(type) & 16384 /* JSLiteral */) { + return true; + } + if (type.flags & 1048576 /* Union */) { + return ts.every(type.types, isJSLiteralType); + } + if (type.flags & 2097152 /* Intersection */) { + return ts.some(type.types, isJSLiteralType); + } + if (type.flags & 63176704 /* Instantiable */) { + return isJSLiteralType(getResolvedBaseConstraint(type)); + } + return false; + } + function getPropertyTypeForIndexType(objectType, indexType, accessNode, cacheSymbol, missingType) { + var accessExpression = accessNode && accessNode.kind === 190 /* ElementAccessExpression */ ? accessNode : undefined; + var propName = isTypeUsableAsLateBoundName(indexType) + ? getLateBoundNameFromType(indexType) + : accessExpression && checkThatExpressionIsProperSymbolReference(accessExpression.argumentExpression, indexType, /*reportError*/ false) + ? ts.getPropertyNameForKnownSymbolName(ts.idText(accessExpression.argumentExpression.name)) + : accessNode && ts.isPropertyName(accessNode) + // late bound names are handled in the first branch, so here we only need to handle normal names + ? ts.getPropertyNameForPropertyNameNode(accessNode) + : undefined; + if (propName !== undefined) { + var prop = getPropertyOfType(objectType, propName); + if (prop) { + if (accessExpression) { + markPropertyAsReferenced(prop, accessExpression, /*isThisAccess*/ accessExpression.expression.kind === 100 /* ThisKeyword */); + if (ts.isAssignmentTarget(accessExpression) && (isReferenceToReadonlyEntity(accessExpression, prop) || isReferenceThroughNamespaceImport(accessExpression))) { + error(accessExpression.argumentExpression, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, symbolToString(prop)); + return missingType; + } + if (cacheSymbol) { + getNodeLinks(accessNode).resolvedSymbol = prop; + } + } + var propType = getTypeOfSymbol(prop); + return accessExpression && ts.getAssignmentTargetKind(accessExpression) !== 1 /* Definite */ ? + getFlowTypeOfReference(accessExpression, propType) : + propType; + } + if (everyType(objectType, isTupleType) && isNumericLiteralName(propName) && +propName >= 0) { + if (accessNode && everyType(objectType, function (t) { return !t.target.hasRestElement; })) { + var indexNode = getIndexNodeForAccessExpression(accessNode); + error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(propName), typeToString(objectType)); + } + return mapType(objectType, function (t) { return getRestTypeOfTupleType(t) || undefinedType; }); + } + } + if (!(indexType.flags & 98304 /* Nullable */) && isTypeAssignableToKind(indexType, 132 /* StringLike */ | 296 /* NumberLike */ | 12288 /* ESSymbolLike */)) { + if (objectType.flags & (1 /* Any */ | 131072 /* Never */)) { + return objectType; + } + var indexInfo = isTypeAssignableToKind(indexType, 296 /* NumberLike */) && getIndexInfoOfType(objectType, 1 /* Number */) || + getIndexInfoOfType(objectType, 0 /* String */) || + undefined; + if (indexInfo) { + if (accessNode && !isTypeAssignableToKind(indexType, 4 /* String */ | 8 /* Number */)) { + var indexNode = getIndexNodeForAccessExpression(accessNode); + error(indexNode, ts.Diagnostics.Type_0_cannot_be_used_as_an_index_type, typeToString(indexType)); + } + else if (accessExpression && indexInfo.isReadonly && (ts.isAssignmentTarget(accessExpression) || ts.isDeleteTarget(accessExpression))) { + error(accessExpression, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(objectType)); + } + return indexInfo.type; + } + if (indexType.flags & 131072 /* Never */) { + return neverType; + } + if (isJSLiteralType(objectType)) { + return anyType; + } + if (accessExpression && !isConstEnumObjectType(objectType)) { + if (noImplicitAny && !compilerOptions.suppressImplicitAnyIndexErrors) { + if (propName !== undefined && typeHasStaticProperty(propName, objectType)) { + error(accessExpression, ts.Diagnostics.Property_0_is_a_static_member_of_type_1, propName, typeToString(objectType)); + } + else if (getIndexTypeOfType(objectType, 1 /* Number */)) { + error(accessExpression.argumentExpression, ts.Diagnostics.Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number); + } + else { + var suggestion = void 0; + if (propName !== undefined && (suggestion = getSuggestionForNonexistentProperty(propName, objectType))) { + if (suggestion !== undefined) { + error(accessExpression.argumentExpression, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2, propName, typeToString(objectType), suggestion); + } + } + else { + error(accessExpression, ts.Diagnostics.Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature, typeToString(objectType)); + } + } + } + return missingType; + } + } + if (isJSLiteralType(objectType)) { + return anyType; + } + if (accessNode) { + var indexNode = getIndexNodeForAccessExpression(accessNode); + if (indexType.flags & (128 /* StringLiteral */ | 256 /* NumberLiteral */)) { + error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, "" + indexType.value, typeToString(objectType)); + } + else if (indexType.flags & (4 /* String */ | 8 /* Number */)) { + error(indexNode, ts.Diagnostics.Type_0_has_no_matching_index_signature_for_type_1, typeToString(objectType), typeToString(indexType)); + } + else { + error(indexNode, ts.Diagnostics.Type_0_cannot_be_used_as_an_index_type, typeToString(indexType)); + } + } + if (isTypeAny(indexType)) { + return indexType; + } + return missingType; + } + function getIndexNodeForAccessExpression(accessNode) { + return accessNode.kind === 190 /* ElementAccessExpression */ + ? accessNode.argumentExpression + : accessNode.kind === 180 /* IndexedAccessType */ + ? accessNode.indexType + : accessNode.kind === 149 /* ComputedPropertyName */ + ? accessNode.expression + : accessNode; + } + function isGenericObjectType(type) { + return maybeTypeOfKind(type, 58982400 /* InstantiableNonPrimitive */ | 134217728 /* GenericMappedType */); + } + function isGenericIndexType(type) { + return maybeTypeOfKind(type, 58982400 /* InstantiableNonPrimitive */ | 4194304 /* Index */); + } + function getSimplifiedType(type) { + return type.flags & 8388608 /* IndexedAccess */ ? getSimplifiedIndexedAccessType(type) : type; + } + function distributeIndexOverObjectType(objectType, indexType) { + // (T | U)[K] -> T[K] | U[K] + if (objectType.flags & 1048576 /* Union */) { + return mapType(objectType, function (t) { return getSimplifiedType(getIndexedAccessType(t, indexType)); }); + } + // (T & U)[K] -> T[K] & U[K] + if (objectType.flags & 2097152 /* Intersection */) { + return getIntersectionType(ts.map(objectType.types, function (t) { return getSimplifiedType(getIndexedAccessType(t, indexType)); })); + } + } + // Transform an indexed access to a simpler form, if possible. Return the simpler form, or return + // the type itself if no transformation is possible. + function getSimplifiedIndexedAccessType(type) { + if (type.simplified) { + return type.simplified === circularConstraintType ? type : type.simplified; + } + type.simplified = circularConstraintType; + // We recursively simplify the object type as it may in turn be an indexed access type. For example, with + // '{ [P in T]: { [Q in U]: number } }[T][U]' we want to first simplify the inner indexed access type. + var objectType = getSimplifiedType(type.objectType); + var indexType = getSimplifiedType(type.indexType); + // T[A | B] -> T[A] | T[B] + if (indexType.flags & 1048576 /* Union */) { + return type.simplified = mapType(indexType, function (t) { return getSimplifiedType(getIndexedAccessType(objectType, t)); }); + } + // Only do the inner distributions if the index can no longer be instantiated to cause index distribution again + if (!(indexType.flags & 63176704 /* Instantiable */)) { + var simplified = distributeIndexOverObjectType(objectType, indexType); + if (simplified) { + return type.simplified = simplified; + } + } + // So ultimately: + // ((A & B) | C)[K1 | K2] -> ((A & B) | C)[K1] | ((A & B) | C)[K2] -> (A & B)[K1] | C[K1] | (A & B)[K2] | C[K2] -> (A[K1] & B[K1]) | C[K1] | (A[K2] & B[K2]) | C[K2] + // If the object type is a mapped type { [P in K]: E }, where K is generic, instantiate E using a mapper + // that substitutes the index type for P. For example, for an index access { [P in K]: Box }[X], we + // construct the type Box. We do not further simplify the result because mapped types can be recursive + // and we might never terminate. + if (isGenericMappedType(objectType)) { + return type.simplified = substituteIndexedMappedType(objectType, type); + } + if (objectType.flags & 262144 /* TypeParameter */) { + var constraint = getConstraintOfTypeParameter(objectType); + if (constraint && isGenericMappedType(constraint)) { + return type.simplified = substituteIndexedMappedType(constraint, type); + } + } + return type.simplified = type; + } + function substituteIndexedMappedType(objectType, type) { + var mapper = createTypeMapper([getTypeParameterFromMappedType(objectType)], [type.indexType]); + var templateMapper = combineTypeMappers(objectType.mapper, mapper); + return instantiateType(getTemplateTypeFromMappedType(objectType), templateMapper); + } + function getIndexedAccessType(objectType, indexType, accessNode, missingType) { + if (missingType === void 0) { missingType = accessNode ? errorType : unknownType; } + if (objectType === wildcardType || indexType === wildcardType) { + return wildcardType; + } + // If the index type is generic, or if the object type is generic and doesn't originate in an expression, + // we are performing a higher-order index access where we cannot meaningfully access the properties of the + // object type. Note that for a generic T and a non-generic K, we eagerly resolve T[K] if it originates in + // an expression. This is to preserve backwards compatibility. For example, an element access 'this["foo"]' + // has always been resolved eagerly using the constraint type of 'this' at the given location. + if (isGenericIndexType(indexType) || !(accessNode && accessNode.kind !== 180 /* IndexedAccessType */) && isGenericObjectType(objectType)) { + if (objectType.flags & 3 /* AnyOrUnknown */) { + return objectType; + } + // Defer the operation by creating an indexed access type. + var id = objectType.id + "," + indexType.id; + var type = indexedAccessTypes.get(id); + if (!type) { + indexedAccessTypes.set(id, type = createIndexedAccessType(objectType, indexType)); + } + return type; + } + // In the following we resolve T[K] to the type of the property in T selected by K. + // We treat boolean as different from other unions to improve errors; + // skipping straight to getPropertyTypeForIndexType gives errors with 'boolean' instead of 'true'. + var apparentObjectType = getApparentType(objectType); + if (indexType.flags & 1048576 /* Union */ && !(indexType.flags & 16 /* Boolean */)) { + var propTypes = []; + var wasMissingProp = false; + for (var _i = 0, _a = indexType.types; _i < _a.length; _i++) { + var t = _a[_i]; + var propType = getPropertyTypeForIndexType(apparentObjectType, t, accessNode, /*cacheSymbol*/ false, missingType); + if (propType === missingType) { + if (!accessNode) { + // If there's no error node, we can immeditely stop, since error reporting is off + return missingType; + } + else { + // Otherwise we set a flag and return at the end of the loop so we still mark all errors + wasMissingProp = true; + } + } + propTypes.push(propType); + } + if (wasMissingProp) { + return missingType; + } + return getUnionType(propTypes); + } + return getPropertyTypeForIndexType(apparentObjectType, indexType, accessNode, /*cacheSymbol*/ true, missingType); + } + function getTypeFromIndexedAccessTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + var objectType = getTypeFromTypeNode(node.objectType); + var indexType = getTypeFromTypeNode(node.indexType); + var resolved = getIndexedAccessType(objectType, indexType, node); + links.resolvedType = resolved.flags & 8388608 /* IndexedAccess */ && + resolved.objectType === objectType && + resolved.indexType === indexType ? + getConstrainedTypeVariable(resolved, node) : resolved; + } + return links.resolvedType; + } + function getTypeFromMappedTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + var type = createObjectType(32 /* Mapped */, node.symbol); + type.declaration = node; + type.aliasSymbol = getAliasSymbolForTypeNode(node); + type.aliasTypeArguments = getTypeArgumentsForAliasSymbol(type.aliasSymbol); + links.resolvedType = type; + // Eagerly resolve the constraint type which forces an error if the constraint type circularly + // references itself through one or more type aliases. + getConstraintTypeFromMappedType(type); + } + return links.resolvedType; + } + function getActualTypeVariable(type) { + return type.flags & 33554432 /* Substitution */ ? type.typeVariable : type; + } + function getConditionalType(root, mapper) { + var checkType = instantiateType(root.checkType, mapper); + var extendsType = instantiateType(root.extendsType, mapper); + if (checkType === wildcardType || extendsType === wildcardType) { + return wildcardType; + } + // If this is a distributive conditional type and the check type is generic we need to defer + // resolution of the conditional type such that a later instantiation will properly distribute + // over union types. + var isDeferred = root.isDistributive && maybeTypeOfKind(checkType, 63176704 /* Instantiable */); + var combinedMapper; + if (root.inferTypeParameters) { + var context = createInferenceContext(root.inferTypeParameters, /*signature*/ undefined, 0 /* None */); + if (!isDeferred) { + // We don't want inferences from constraints as they may cause us to eagerly resolve the + // conditional type instead of deferring resolution. Also, we always want strict function + // types rules (i.e. proper contravariance) for inferences. + inferTypes(context.inferences, checkType, extendsType, 32 /* NoConstraints */ | 64 /* AlwaysStrict */); + } + combinedMapper = combineTypeMappers(mapper, context); + } + if (!isDeferred) { + if (extendsType.flags & 3 /* AnyOrUnknown */) { + return instantiateType(root.trueType, mapper); + } + // Return union of trueType and falseType for 'any' since it matches anything + if (checkType.flags & 1 /* Any */) { + return getUnionType([instantiateType(root.trueType, combinedMapper || mapper), instantiateType(root.falseType, mapper)]); + } + // Instantiate the extends type including inferences for 'infer T' type parameters + var inferredExtendsType = combinedMapper ? instantiateType(root.extendsType, combinedMapper) : extendsType; + // Return falseType for a definitely false extends check. We check an instantations of the two + // types with type parameters mapped to the wildcard type, the most permissive instantiations + // possible (the wildcard type is assignable to and from all types). If those are not related, + // then no instatiations will be and we can just return the false branch type. + if (!isTypeAssignableTo(getWildcardInstantiation(checkType), getWildcardInstantiation(inferredExtendsType))) { + return instantiateType(root.falseType, mapper); + } + // Return trueType for a definitely true extends check. The definitely assignable relation excludes + // type variable constraints from consideration. Without the definitely assignable relation, the type + // type Foo = T extends { x: string } ? string : number + // would immediately resolve to 'string' instead of being deferred. + if (checkTypeRelatedTo(checkType, inferredExtendsType, definitelyAssignableRelation, /*errorNode*/ undefined)) { + return instantiateType(root.trueType, combinedMapper || mapper); + } + } + // Return a deferred type for a check that is neither definitely true nor definitely false + var erasedCheckType = getActualTypeVariable(checkType); + var result = createType(16777216 /* Conditional */); + result.root = root; + result.checkType = erasedCheckType; + result.extendsType = extendsType; + result.mapper = mapper; + result.combinedMapper = combinedMapper; + result.aliasSymbol = root.aliasSymbol; + result.aliasTypeArguments = instantiateTypes(root.aliasTypeArguments, mapper); // TODO: GH#18217 + return result; + } + function getTrueTypeFromConditionalType(type) { + return type.resolvedTrueType || (type.resolvedTrueType = instantiateType(type.root.trueType, type.mapper)); + } + function getFalseTypeFromConditionalType(type) { + return type.resolvedFalseType || (type.resolvedFalseType = instantiateType(type.root.falseType, type.mapper)); + } + function getInferTypeParameters(node) { + var result; + if (node.locals) { + node.locals.forEach(function (symbol) { + if (symbol.flags & 262144 /* TypeParameter */) { + result = ts.append(result, getDeclaredTypeOfSymbol(symbol)); + } + }); + } + return result; + } + function isPossiblyReferencedInConditionalType(tp, node) { + if (isTypeParameterPossiblyReferenced(tp, node)) { + return true; + } + while (node) { + if (node.kind === 175 /* ConditionalType */) { + if (isTypeParameterPossiblyReferenced(tp, node.extendsType)) { + return true; + } + } + node = node.parent; + } + return false; + } + function getTypeFromConditionalTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + var checkType = getTypeFromTypeNode(node.checkType); + var aliasSymbol = getAliasSymbolForTypeNode(node); + var aliasTypeArguments = getTypeArgumentsForAliasSymbol(aliasSymbol); + var allOuterTypeParameters = getOuterTypeParameters(node, /*includeThisTypes*/ true); + var outerTypeParameters = aliasTypeArguments ? allOuterTypeParameters : ts.filter(allOuterTypeParameters, function (tp) { return isPossiblyReferencedInConditionalType(tp, node); }); + var root = { + node: node, + checkType: checkType, + extendsType: getTypeFromTypeNode(node.extendsType), + trueType: getTypeFromTypeNode(node.trueType), + falseType: getTypeFromTypeNode(node.falseType), + isDistributive: !!(checkType.flags & 262144 /* TypeParameter */), + inferTypeParameters: getInferTypeParameters(node), + outerTypeParameters: outerTypeParameters, + instantiations: undefined, + aliasSymbol: aliasSymbol, + aliasTypeArguments: aliasTypeArguments + }; + links.resolvedType = getConditionalType(root, /*mapper*/ undefined); + if (outerTypeParameters) { + root.instantiations = ts.createMap(); + root.instantiations.set(getTypeListId(outerTypeParameters), links.resolvedType); + } + } + return links.resolvedType; + } + function getTypeFromInferTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + links.resolvedType = getDeclaredTypeOfTypeParameter(getSymbolOfNode(node.typeParameter)); + } + return links.resolvedType; + } + function getIdentifierChain(node) { + if (ts.isIdentifier(node)) { + return [node]; + } + else { + return ts.append(getIdentifierChain(node.left), node.right); + } + } + function getTypeFromImportTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + if (node.isTypeOf && node.typeArguments) { // Only the non-typeof form can make use of type arguments + error(node, ts.Diagnostics.Type_arguments_cannot_be_used_here); + links.resolvedSymbol = unknownSymbol; + return links.resolvedType = errorType; + } + if (!ts.isLiteralImportTypeNode(node)) { + error(node.argument, ts.Diagnostics.String_literal_expected); + links.resolvedSymbol = unknownSymbol; + return links.resolvedType = errorType; + } + var targetMeaning = node.isTypeOf ? 67220415 /* Value */ : node.flags & 2097152 /* JSDoc */ ? 67220415 /* Value */ | 67897832 /* Type */ : 67897832 /* Type */; + // TODO: Future work: support unions/generics/whatever via a deferred import-type + var innerModuleSymbol = resolveExternalModuleName(node, node.argument.literal); + if (!innerModuleSymbol) { + links.resolvedSymbol = unknownSymbol; + return links.resolvedType = errorType; + } + var moduleSymbol = resolveExternalModuleSymbol(innerModuleSymbol, /*dontResolveAlias*/ false); + if (!ts.nodeIsMissing(node.qualifier)) { + var nameStack = getIdentifierChain(node.qualifier); + var currentNamespace = moduleSymbol; + var current = void 0; + while (current = nameStack.shift()) { + var meaning = nameStack.length ? 1920 /* Namespace */ : targetMeaning; + var next = getSymbol(getExportsOfSymbol(getMergedSymbol(resolveSymbol(currentNamespace))), current.escapedText, meaning); + if (!next) { + error(current, ts.Diagnostics.Namespace_0_has_no_exported_member_1, getFullyQualifiedName(currentNamespace), ts.declarationNameToString(current)); + return links.resolvedType = errorType; + } + getNodeLinks(current).resolvedSymbol = next; + getNodeLinks(current.parent).resolvedSymbol = next; + currentNamespace = next; + } + resolveImportSymbolType(node, links, currentNamespace, targetMeaning); + } + else { + if (moduleSymbol.flags & targetMeaning) { + resolveImportSymbolType(node, links, moduleSymbol, targetMeaning); + } + else { + var errorMessage = targetMeaning === 67220415 /* Value */ + ? ts.Diagnostics.Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here + : ts.Diagnostics.Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0; + error(node, errorMessage, node.argument.literal.text); + links.resolvedSymbol = unknownSymbol; + links.resolvedType = errorType; + } + } + } + return links.resolvedType; // TODO: GH#18217 + } + function resolveImportSymbolType(node, links, symbol, meaning) { + var resolvedSymbol = resolveSymbol(symbol); + links.resolvedSymbol = resolvedSymbol; + if (meaning === 67220415 /* Value */) { + return links.resolvedType = getTypeOfSymbol(symbol); // intentionally doesn't use resolved symbol so type is cached as expected on the alias + } + else { + return links.resolvedType = getTypeReferenceType(node, resolvedSymbol); // getTypeReferenceType doesn't handle aliases - it must get the resolved symbol + } + } + function getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + // Deferred resolution of members is handled by resolveObjectTypeMembers + var aliasSymbol = getAliasSymbolForTypeNode(node); + if (getMembersOfSymbol(node.symbol).size === 0 && !aliasSymbol) { + links.resolvedType = emptyTypeLiteralType; + } + else { + var type = createObjectType(16 /* Anonymous */, node.symbol); + type.aliasSymbol = aliasSymbol; + type.aliasTypeArguments = getTypeArgumentsForAliasSymbol(aliasSymbol); + if (ts.isJSDocTypeLiteral(node) && node.isArrayType) { + type = createArrayType(type); + } + links.resolvedType = type; + } + } + return links.resolvedType; + } + function getAliasSymbolForTypeNode(node) { + return ts.isTypeAlias(node.parent) ? getSymbolOfNode(node.parent) : undefined; + } + function getTypeArgumentsForAliasSymbol(symbol) { + return symbol ? getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) : undefined; + } + function isNonGenericObjectType(type) { + return !!(type.flags & 524288 /* Object */) && !isGenericMappedType(type); + } + /** + * Since the source of spread types are object literals, which are not binary, + * this function should be called in a left folding style, with left = previous result of getSpreadType + * and right = the new element to be spread. + */ + function getSpreadType(left, right, symbol, typeFlags, objectFlags) { + if (left.flags & 1 /* Any */ || right.flags & 1 /* Any */) { + return anyType; + } + if (left.flags & 2 /* Unknown */ || right.flags & 2 /* Unknown */) { + return unknownType; + } + if (left.flags & 131072 /* Never */) { + return right; + } + if (right.flags & 131072 /* Never */) { + return left; + } + if (left.flags & 1048576 /* Union */) { + return mapType(left, function (t) { return getSpreadType(t, right, symbol, typeFlags, objectFlags); }); + } + if (right.flags & 1048576 /* Union */) { + return mapType(right, function (t) { return getSpreadType(left, t, symbol, typeFlags, objectFlags); }); + } + if (right.flags & (528 /* BooleanLike */ | 296 /* NumberLike */ | 2112 /* BigIntLike */ | 132 /* StringLike */ | 1056 /* EnumLike */ | 67108864 /* NonPrimitive */ | 4194304 /* Index */)) { + return left; + } + if (isGenericObjectType(left) || isGenericObjectType(right)) { + if (isEmptyObjectType(left)) { + return right; + } + // When the left type is an intersection, we may need to merge the last constituent of the + // intersection with the right type. For example when the left type is 'T & { a: string }' + // and the right type is '{ b: string }' we produce 'T & { a: string, b: string }'. + if (left.flags & 2097152 /* Intersection */) { + var types = left.types; + var lastLeft = types[types.length - 1]; + if (isNonGenericObjectType(lastLeft) && isNonGenericObjectType(right)) { + return getIntersectionType(ts.concatenate(types.slice(0, types.length - 1), [getSpreadType(lastLeft, right, symbol, typeFlags, objectFlags)])); + } + } + return getIntersectionType([left, right]); + } + var members = ts.createSymbolTable(); + var skippedPrivateMembers = ts.createUnderscoreEscapedMap(); + var stringIndexInfo; + var numberIndexInfo; + if (left === emptyObjectType) { + // for the first spread element, left === emptyObjectType, so take the right's string indexer + stringIndexInfo = getIndexInfoOfType(right, 0 /* String */); + numberIndexInfo = getIndexInfoOfType(right, 1 /* Number */); + } + else { + stringIndexInfo = unionSpreadIndexInfos(getIndexInfoOfType(left, 0 /* String */), getIndexInfoOfType(right, 0 /* String */)); + numberIndexInfo = unionSpreadIndexInfos(getIndexInfoOfType(left, 1 /* Number */), getIndexInfoOfType(right, 1 /* Number */)); + } + for (var _i = 0, _a = getPropertiesOfType(right); _i < _a.length; _i++) { + var rightProp = _a[_i]; + if (ts.getDeclarationModifierFlagsFromSymbol(rightProp) & (8 /* Private */ | 16 /* Protected */)) { + skippedPrivateMembers.set(rightProp.escapedName, true); + } + else if (isSpreadableProperty(rightProp)) { + members.set(rightProp.escapedName, getSpreadSymbol(rightProp)); + } + } + for (var _b = 0, _c = getPropertiesOfType(left); _b < _c.length; _b++) { + var leftProp = _c[_b]; + if (skippedPrivateMembers.has(leftProp.escapedName) || !isSpreadableProperty(leftProp)) { + continue; + } + if (members.has(leftProp.escapedName)) { + var rightProp = members.get(leftProp.escapedName); + var rightType = getTypeOfSymbol(rightProp); + if (rightProp.flags & 16777216 /* Optional */) { + var declarations = ts.concatenate(leftProp.declarations, rightProp.declarations); + var flags = 4 /* Property */ | (leftProp.flags & 16777216 /* Optional */); + var result = createSymbol(flags, leftProp.escapedName); + result.type = getUnionType([getTypeOfSymbol(leftProp), getTypeWithFacts(rightType, 524288 /* NEUndefined */)]); + result.leftSpread = leftProp; + result.rightSpread = rightProp; + result.declarations = declarations; + result.nameType = leftProp.nameType; + members.set(leftProp.escapedName, result); + } + } + else { + members.set(leftProp.escapedName, getSpreadSymbol(leftProp)); + } + } + var spread = createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, getNonReadonlyIndexSignature(stringIndexInfo), getNonReadonlyIndexSignature(numberIndexInfo)); + spread.flags |= 268435456 /* ContainsObjectLiteral */ | typeFlags; + spread.objectFlags |= 128 /* ObjectLiteral */ | 1024 /* ContainsSpread */ | objectFlags; + return spread; + } + /** We approximate own properties as non-methods plus methods that are inside the object literal */ + function isSpreadableProperty(prop) { + return !(prop.flags & (8192 /* Method */ | 32768 /* GetAccessor */ | 65536 /* SetAccessor */)) || + !prop.declarations.some(function (decl) { return ts.isClassLike(decl.parent); }); + } + function getSpreadSymbol(prop) { + var isReadonly = isReadonlySymbol(prop); + var isSetonlyAccessor = prop.flags & 65536 /* SetAccessor */ && !(prop.flags & 32768 /* GetAccessor */); + if (!isReadonly && !isSetonlyAccessor) { + return prop; + } + var flags = 4 /* Property */ | (prop.flags & 16777216 /* Optional */); + var result = createSymbol(flags, prop.escapedName); + result.type = isSetonlyAccessor ? undefinedType : getTypeOfSymbol(prop); + result.declarations = prop.declarations; + result.nameType = prop.nameType; + result.syntheticOrigin = prop; + return result; + } + function getNonReadonlyIndexSignature(index) { + if (index && index.isReadonly) { + return createIndexInfo(index.type, /*isReadonly*/ false, index.declaration); + } + return index; + } + function createLiteralType(flags, value, symbol) { + var type = createType(flags); + type.symbol = symbol; + type.value = value; + return type; + } + function getFreshTypeOfLiteralType(type) { + if (type.flags & 2944 /* Literal */) { + if (!type.freshType) { + var freshType = createLiteralType(type.flags, type.value, type.symbol); + freshType.regularType = type; + freshType.freshType = freshType; + type.freshType = freshType; + } + return type.freshType; + } + return type; + } + function getRegularTypeOfLiteralType(type) { + return type.flags & 2944 /* Literal */ ? type.regularType : + type.flags & 1048576 /* Union */ ? getUnionType(ts.sameMap(type.types, getRegularTypeOfLiteralType)) : + type; + } + function isFreshLiteralType(type) { + return !!(type.flags & 2944 /* Literal */) && type.freshType === type; + } + function getLiteralType(value, enumId, symbol) { + // We store all literal types in a single map with keys of the form '#NNN' and '@SSS', + // where NNN is the text representation of a numeric literal and SSS are the characters + // of a string literal. For literal enum members we use 'EEE#NNN' and 'EEE@SSS', where + // EEE is a unique id for the containing enum type. + var qualifier = typeof value === "number" ? "#" : typeof value === "string" ? "@" : "n"; + var key = (enumId ? enumId : "") + qualifier + (typeof value === "object" ? ts.pseudoBigIntToString(value) : value); + var type = literalTypes.get(key); + if (!type) { + var flags = (typeof value === "number" ? 256 /* NumberLiteral */ : + typeof value === "string" ? 128 /* StringLiteral */ : 2048 /* BigIntLiteral */) | + (enumId ? 1024 /* EnumLiteral */ : 0); + literalTypes.set(key, type = createLiteralType(flags, value, symbol)); + type.regularType = type; + } + return type; + } + function getTypeFromLiteralTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + links.resolvedType = getRegularTypeOfLiteralType(checkExpression(node.literal)); + } + return links.resolvedType; + } + function createUniqueESSymbolType(symbol) { + var type = createType(8192 /* UniqueESSymbol */); + type.symbol = symbol; + return type; + } + function getESSymbolLikeTypeForNode(node) { + if (ts.isValidESSymbolDeclaration(node)) { + var symbol = getSymbolOfNode(node); + var links = getSymbolLinks(symbol); + return links.uniqueESSymbolType || (links.uniqueESSymbolType = createUniqueESSymbolType(symbol)); + } + return esSymbolType; + } + function getThisType(node) { + var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); + var parent = container && container.parent; + if (parent && (ts.isClassLike(parent) || parent.kind === 241 /* InterfaceDeclaration */)) { + if (!ts.hasModifier(container, 32 /* Static */) && + (container.kind !== 157 /* Constructor */ || ts.isNodeDescendantOf(node, container.body))) { + return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(parent)).thisType; + } + } + error(node, ts.Diagnostics.A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface); + return errorType; + } + function getTypeFromThisTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + links.resolvedType = getThisType(node); + } + return links.resolvedType; + } + function getTypeFromTypeNode(node) { + switch (node.kind) { + case 120 /* AnyKeyword */: + case 284 /* JSDocAllType */: + case 285 /* JSDocUnknownType */: + return anyType; + case 143 /* UnknownKeyword */: + return unknownType; + case 138 /* StringKeyword */: + return stringType; + case 135 /* NumberKeyword */: + return numberType; + case 146 /* BigIntKeyword */: + return bigintType; + case 123 /* BooleanKeyword */: + return booleanType; + case 139 /* SymbolKeyword */: + return esSymbolType; + case 106 /* VoidKeyword */: + return voidType; + case 141 /* UndefinedKeyword */: + return undefinedType; + case 96 /* NullKeyword */: + return nullType; + case 132 /* NeverKeyword */: + return neverType; + case 136 /* ObjectKeyword */: + return node.flags & 65536 /* JavaScriptFile */ ? anyType : nonPrimitiveType; + case 178 /* ThisType */: + case 100 /* ThisKeyword */: + return getTypeFromThisTypeNode(node); + case 182 /* LiteralType */: + return getTypeFromLiteralTypeNode(node); + case 164 /* TypeReference */: + return getTypeFromTypeReference(node); + case 163 /* TypePredicate */: + return booleanType; + case 211 /* ExpressionWithTypeArguments */: + return getTypeFromTypeReference(node); + case 167 /* TypeQuery */: + return getTypeFromTypeQueryNode(node); + case 169 /* ArrayType */: + return getTypeFromArrayTypeNode(node); + case 170 /* TupleType */: + return getTypeFromTupleTypeNode(node); + case 171 /* OptionalType */: + return getTypeFromOptionalTypeNode(node); + case 173 /* UnionType */: + return getTypeFromUnionTypeNode(node); + case 174 /* IntersectionType */: + return getTypeFromIntersectionTypeNode(node); + case 286 /* JSDocNullableType */: + return getTypeFromJSDocNullableTypeNode(node); + case 288 /* JSDocOptionalType */: + return addOptionality(getTypeFromTypeNode(node.type)); + case 177 /* ParenthesizedType */: + case 172 /* RestType */: + case 287 /* JSDocNonNullableType */: + case 283 /* JSDocTypeExpression */: + return getTypeFromTypeNode(node.type); + case 290 /* JSDocVariadicType */: + return getTypeFromJSDocVariadicType(node); + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + case 168 /* TypeLiteral */: + case 292 /* JSDocTypeLiteral */: + case 289 /* JSDocFunctionType */: + case 293 /* JSDocSignature */: + return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node); + case 179 /* TypeOperator */: + return getTypeFromTypeOperatorNode(node); + case 180 /* IndexedAccessType */: + return getTypeFromIndexedAccessTypeNode(node); + case 181 /* MappedType */: + return getTypeFromMappedTypeNode(node); + case 175 /* ConditionalType */: + return getTypeFromConditionalTypeNode(node); + case 176 /* InferType */: + return getTypeFromInferTypeNode(node); + case 183 /* ImportType */: + return getTypeFromImportTypeNode(node); + // This function assumes that an identifier or qualified name is a type expression + // Callers should first ensure this by calling isTypeNode + case 72 /* Identifier */: + case 148 /* QualifiedName */: + var symbol = getSymbolAtLocation(node); + return symbol ? getDeclaredTypeOfSymbol(symbol) : errorType; + default: + return errorType; + } + } + function instantiateList(items, mapper, instantiator) { + if (items && items.length) { + for (var i = 0; i < items.length; i++) { + var item = items[i]; + var mapped = instantiator(item, mapper); + if (item !== mapped) { + var result = i === 0 ? [] : items.slice(0, i); + result.push(mapped); + for (i++; i < items.length; i++) { + result.push(instantiator(items[i], mapper)); + } + return result; + } + } + } + return items; + } + function instantiateTypes(types, mapper) { + return instantiateList(types, mapper, instantiateType); + } + function instantiateSignatures(signatures, mapper) { + return instantiateList(signatures, mapper, instantiateSignature); + } + function makeUnaryTypeMapper(source, target) { + return function (t) { return t === source ? target : t; }; + } + function makeBinaryTypeMapper(source1, target1, source2, target2) { + return function (t) { return t === source1 ? target1 : t === source2 ? target2 : t; }; + } + function makeArrayTypeMapper(sources, targets) { + return function (t) { + for (var i = 0; i < sources.length; i++) { + if (t === sources[i]) { + return targets ? targets[i] : anyType; + } + } + return t; + }; + } + function createTypeMapper(sources, targets) { + ts.Debug.assert(targets === undefined || sources.length === targets.length); + return sources.length === 1 ? makeUnaryTypeMapper(sources[0], targets ? targets[0] : anyType) : + sources.length === 2 ? makeBinaryTypeMapper(sources[0], targets ? targets[0] : anyType, sources[1], targets ? targets[1] : anyType) : + makeArrayTypeMapper(sources, targets); + } + function createTypeEraser(sources) { + return createTypeMapper(sources, /*targets*/ undefined); + } + /** + * Maps forward-references to later types parameters to the empty object type. + * This is used during inference when instantiating type parameter defaults. + */ + function createBackreferenceMapper(typeParameters, index) { + return function (t) { return typeParameters.indexOf(t) >= index ? emptyObjectType : t; }; + } + function isInferenceContext(mapper) { + return !!mapper.typeParameters; + } + function cloneTypeMapper(mapper) { + return mapper && isInferenceContext(mapper) ? + createInferenceContext(mapper.typeParameters, mapper.signature, mapper.flags | 1 /* NoDefault */, mapper.compareTypes, mapper.inferences) : + mapper; + } + function combineTypeMappers(mapper1, mapper2) { + if (!mapper1) + return mapper2; + if (!mapper2) + return mapper1; + return function (t) { return instantiateType(mapper1(t), mapper2); }; + } + function createReplacementMapper(source, target, baseMapper) { + return function (t) { return t === source ? target : baseMapper(t); }; + } + function wildcardMapper(type) { + return type.flags & 262144 /* TypeParameter */ ? wildcardType : type; + } + function cloneTypeParameter(typeParameter) { + var result = createType(262144 /* TypeParameter */); + result.symbol = typeParameter.symbol; + result.target = typeParameter; + return result; + } + function instantiateTypePredicate(predicate, mapper) { + if (ts.isIdentifierTypePredicate(predicate)) { + return { + kind: 1 /* Identifier */, + parameterName: predicate.parameterName, + parameterIndex: predicate.parameterIndex, + type: instantiateType(predicate.type, mapper) + }; + } + else { + return { + kind: 0 /* This */, + type: instantiateType(predicate.type, mapper) + }; + } + } + function instantiateSignature(signature, mapper, eraseTypeParameters) { + var freshTypeParameters; + if (signature.typeParameters && !eraseTypeParameters) { + // First create a fresh set of type parameters, then include a mapping from the old to the + // new type parameters in the mapper function. Finally store this mapper in the new type + // parameters such that we can use it when instantiating constraints. + freshTypeParameters = ts.map(signature.typeParameters, cloneTypeParameter); + mapper = combineTypeMappers(createTypeMapper(signature.typeParameters, freshTypeParameters), mapper); + for (var _i = 0, freshTypeParameters_1 = freshTypeParameters; _i < freshTypeParameters_1.length; _i++) { + var tp = freshTypeParameters_1[_i]; + tp.mapper = mapper; + } + } + // Don't compute resolvedReturnType and resolvedTypePredicate now, + // because using `mapper` now could trigger inferences to become fixed. (See `createInferenceContext`.) + // See GH#17600. + var result = createSignature(signature.declaration, freshTypeParameters, signature.thisParameter && instantiateSymbol(signature.thisParameter, mapper), instantiateList(signature.parameters, mapper, instantiateSymbol), + /*resolvedReturnType*/ undefined, + /*resolvedTypePredicate*/ undefined, signature.minArgumentCount, signature.hasRestParameter, signature.hasLiteralTypes); + result.target = signature; + result.mapper = mapper; + return result; + } + function instantiateSymbol(symbol, mapper) { + var links = getSymbolLinks(symbol); + if (links.type && !maybeTypeOfKind(links.type, 524288 /* Object */ | 63176704 /* Instantiable */)) { + // If the type of the symbol is already resolved, and if that type could not possibly + // be affected by instantiation, simply return the symbol itself. + return symbol; + } + if (ts.getCheckFlags(symbol) & 1 /* Instantiated */) { + // If symbol being instantiated is itself a instantiation, fetch the original target and combine the + // type mappers. This ensures that original type identities are properly preserved and that aliases + // always reference a non-aliases. + symbol = links.target; + mapper = combineTypeMappers(links.mapper, mapper); + } + // Keep the flags from the symbol we're instantiating. Mark that is instantiated, and + // also transient so that we can just store data on it directly. + var result = createSymbol(symbol.flags, symbol.escapedName, 1 /* Instantiated */ | ts.getCheckFlags(symbol) & (1024 /* Late */ | 4096 /* OptionalParameter */ | 8192 /* RestParameter */)); + result.declarations = symbol.declarations; + result.parent = symbol.parent; + result.target = symbol; + result.mapper = mapper; + if (symbol.valueDeclaration) { + result.valueDeclaration = symbol.valueDeclaration; + } + if (symbol.nameType) { + result.nameType = symbol.nameType; + } + return result; + } + function getAnonymousTypeInstantiation(type, mapper) { + var target = type.objectFlags & 64 /* Instantiated */ ? type.target : type; + var symbol = target.symbol; + var links = getSymbolLinks(symbol); + var typeParameters = links.outerTypeParameters; + if (!typeParameters) { + // The first time an anonymous type is instantiated we compute and store a list of the type + // parameters that are in scope (and therefore potentially referenced). For type literals that + // aren't the right hand side of a generic type alias declaration we optimize by reducing the + // set of type parameters to those that are possibly referenced in the literal. + var declaration_1 = symbol.declarations[0]; + if (ts.isInJSFile(declaration_1)) { + var paramTag = ts.findAncestor(declaration_1, ts.isJSDocParameterTag); + if (paramTag) { + var paramSymbol = ts.getParameterSymbolFromJSDoc(paramTag); + if (paramSymbol) { + declaration_1 = paramSymbol.valueDeclaration; + } + } + } + var outerTypeParameters = getOuterTypeParameters(declaration_1, /*includeThisTypes*/ true); + if (isJSConstructor(declaration_1)) { + var templateTagParameters = getTypeParametersFromDeclaration(declaration_1); + outerTypeParameters = ts.addRange(outerTypeParameters, templateTagParameters); + } + typeParameters = outerTypeParameters || ts.emptyArray; + typeParameters = symbol.flags & 2048 /* TypeLiteral */ && !target.aliasTypeArguments ? + ts.filter(typeParameters, function (tp) { return isTypeParameterPossiblyReferenced(tp, declaration_1); }) : + typeParameters; + links.outerTypeParameters = typeParameters; + if (typeParameters.length) { + links.instantiations = ts.createMap(); + links.instantiations.set(getTypeListId(typeParameters), target); + } + } + if (typeParameters.length) { + // We are instantiating an anonymous type that has one or more type parameters in scope. Apply the + // mapper to the type parameters to produce the effective list of type arguments, and compute the + // instantiation cache key from the type IDs of the type arguments. + var combinedMapper = type.objectFlags & 64 /* Instantiated */ ? combineTypeMappers(type.mapper, mapper) : mapper; + var typeArguments = ts.map(typeParameters, combinedMapper); + var id = getTypeListId(typeArguments); + var result = links.instantiations.get(id); + if (!result) { + var newMapper = createTypeMapper(typeParameters, typeArguments); + result = target.objectFlags & 32 /* Mapped */ ? instantiateMappedType(target, newMapper) : instantiateAnonymousType(target, newMapper); + links.instantiations.set(id, result); + } + return result; + } + return type; + } + function maybeTypeParameterReference(node) { + return !(node.kind === 148 /* QualifiedName */ || + node.parent.kind === 164 /* TypeReference */ && node.parent.typeArguments && node === node.parent.typeName); + } + function isTypeParameterPossiblyReferenced(tp, node) { + // If the type parameter doesn't have exactly one declaration, if there are invening statement blocks + // between the node and the type parameter declaration, if the node contains actual references to the + // type parameter, or if the node contains type queries, we consider the type parameter possibly referenced. + if (tp.symbol && tp.symbol.declarations && tp.symbol.declarations.length === 1) { + var container_3 = tp.symbol.declarations[0].parent; + if (ts.findAncestor(node, function (n) { return n.kind === 218 /* Block */ ? "quit" : n === container_3; })) { + return !!ts.forEachChild(node, containsReference); + } + } + return true; + function containsReference(node) { + switch (node.kind) { + case 178 /* ThisType */: + return !!tp.isThisType; + case 72 /* Identifier */: + return !tp.isThisType && ts.isPartOfTypeNode(node) && maybeTypeParameterReference(node) && + getTypeFromTypeNode(node) === tp; + case 167 /* TypeQuery */: + return true; + } + return !!ts.forEachChild(node, containsReference); + } + } + function getHomomorphicTypeVariable(type) { + var constraintType = getConstraintTypeFromMappedType(type); + if (constraintType.flags & 4194304 /* Index */) { + var typeVariable = constraintType.type; + if (typeVariable.flags & 262144 /* TypeParameter */) { + return typeVariable; + } + } + return undefined; + } + function instantiateMappedType(type, mapper) { + // For a homomorphic mapped type { [P in keyof T]: X }, where T is some type variable, the mapping + // operation depends on T as follows: + // * If T is a primitive type no mapping is performed and the result is simply T. + // * If T is a union type we distribute the mapped type over the union. + // * If T is an array we map to an array where the element type has been transformed. + // * If T is a tuple we map to a tuple where the element types have been transformed. + // * Otherwise we map to an object type where the type of each property has been transformed. + // For example, when T is instantiated to a union type A | B, we produce { [P in keyof A]: X } | + // { [P in keyof B]: X }, and when when T is instantiated to a union type A | undefined, we produce + // { [P in keyof A]: X } | undefined. + var typeVariable = getHomomorphicTypeVariable(type); + if (typeVariable) { + var mappedTypeVariable = instantiateType(typeVariable, mapper); + if (typeVariable !== mappedTypeVariable) { + // If we are already in the process of creating an instantiation of this mapped type, + // return the error type. This situation only arises if we are instantiating the mapped + // type for an array or tuple type, as we then need to eagerly resolve the (possibly + // circular) element type(s). + if (type.instantiating) { + return errorType; + } + type.instantiating = true; + var result = mapType(mappedTypeVariable, function (t) { + if (t.flags & (3 /* AnyOrUnknown */ | 58982400 /* InstantiableNonPrimitive */ | 524288 /* Object */ | 2097152 /* Intersection */) && t !== wildcardType) { + var replacementMapper = createReplacementMapper(typeVariable, t, mapper); + return isArrayType(t) ? createArrayType(instantiateMappedTypeTemplate(type, numberType, /*isOptional*/ true, replacementMapper)) : + isReadonlyArrayType(t) ? createReadonlyArrayType(instantiateMappedTypeTemplate(type, numberType, /*isOptional*/ true, replacementMapper)) : + isTupleType(t) ? instantiateMappedTupleType(t, type, replacementMapper) : + instantiateAnonymousType(type, replacementMapper); + } + return t; + }); + type.instantiating = false; + return result; + } + } + return instantiateAnonymousType(type, mapper); + } + function instantiateMappedTupleType(tupleType, mappedType, mapper) { + var minLength = tupleType.target.minLength; + var elementTypes = ts.map(tupleType.typeArguments || ts.emptyArray, function (_, i) { + return instantiateMappedTypeTemplate(mappedType, getLiteralType("" + i), i >= minLength, mapper); + }); + var modifiers = getMappedTypeModifiers(mappedType); + var newMinLength = modifiers & 4 /* IncludeOptional */ ? 0 : + modifiers & 8 /* ExcludeOptional */ ? getTypeReferenceArity(tupleType) - (tupleType.target.hasRestElement ? 1 : 0) : + minLength; + return createTupleType(elementTypes, newMinLength, tupleType.target.hasRestElement, tupleType.target.associatedNames); + } + function instantiateMappedTypeTemplate(type, key, isOptional, mapper) { + var templateMapper = combineTypeMappers(mapper, createTypeMapper([getTypeParameterFromMappedType(type)], [key])); + var propType = instantiateType(getTemplateTypeFromMappedType(type.target || type), templateMapper); + var modifiers = getMappedTypeModifiers(type); + return strictNullChecks && modifiers & 4 /* IncludeOptional */ && !isTypeAssignableTo(undefinedType, propType) ? getOptionalType(propType) : + strictNullChecks && modifiers & 8 /* ExcludeOptional */ && isOptional ? getTypeWithFacts(propType, 524288 /* NEUndefined */) : + propType; + } + function instantiateAnonymousType(type, mapper) { + var result = createObjectType(type.objectFlags | 64 /* Instantiated */, type.symbol); + if (type.objectFlags & 32 /* Mapped */) { + result.declaration = type.declaration; + // C.f. instantiateSignature + var origTypeParameter = getTypeParameterFromMappedType(type); + var freshTypeParameter = cloneTypeParameter(origTypeParameter); + result.typeParameter = freshTypeParameter; + mapper = combineTypeMappers(makeUnaryTypeMapper(origTypeParameter, freshTypeParameter), mapper); + freshTypeParameter.mapper = mapper; + } + result.target = type; + result.mapper = mapper; + result.aliasSymbol = type.aliasSymbol; + result.aliasTypeArguments = instantiateTypes(type.aliasTypeArguments, mapper); + return result; + } + function getConditionalTypeInstantiation(type, mapper) { + var root = type.root; + if (root.outerTypeParameters) { + // We are instantiating a conditional type that has one or more type parameters in scope. Apply the + // mapper to the type parameters to produce the effective list of type arguments, and compute the + // instantiation cache key from the type IDs of the type arguments. + var typeArguments = ts.map(root.outerTypeParameters, mapper); + var id = getTypeListId(typeArguments); + var result = root.instantiations.get(id); + if (!result) { + var newMapper = createTypeMapper(root.outerTypeParameters, typeArguments); + result = instantiateConditionalType(root, newMapper); + root.instantiations.set(id, result); + } + return result; + } + return type; + } + function instantiateConditionalType(root, mapper) { + // Check if we have a conditional type where the check type is a naked type parameter. If so, + // the conditional type is distributive over union types and when T is instantiated to a union + // type A | B, we produce (A extends U ? X : Y) | (B extends U ? X : Y). + if (root.isDistributive) { + var checkType_1 = root.checkType; + var instantiatedType = mapper(checkType_1); + if (checkType_1 !== instantiatedType && instantiatedType.flags & (1048576 /* Union */ | 131072 /* Never */)) { + return mapType(instantiatedType, function (t) { return getConditionalType(root, createReplacementMapper(checkType_1, t, mapper)); }); + } + } + return getConditionalType(root, mapper); + } + function instantiateType(type, mapper) { + if (!type || !mapper || mapper === identityMapper) { + return type; + } + if (instantiationDepth === 50) { + // We have reached 50 recursive type instantiations and there is a very high likelyhood we're dealing + // with a combination of infinite generic types that perpetually generate new type identities. We stop + // the recursion here by yielding the error type. + return errorType; + } + instantiationDepth++; + var result = instantiateTypeWorker(type, mapper); + instantiationDepth--; + return result; + } + function instantiateTypeWorker(type, mapper) { + var flags = type.flags; + if (flags & 262144 /* TypeParameter */) { + return mapper(type); + } + if (flags & 524288 /* Object */) { + var objectFlags = type.objectFlags; + if (objectFlags & 16 /* Anonymous */) { + // If the anonymous type originates in a declaration of a function, method, class, or + // interface, in an object type literal, or in an object literal expression, we may need + // to instantiate the type because it might reference a type parameter. + return type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && type.symbol.declarations ? + getAnonymousTypeInstantiation(type, mapper) : type; + } + if (objectFlags & 32 /* Mapped */) { + return getAnonymousTypeInstantiation(type, mapper); + } + if (objectFlags & 4 /* Reference */) { + var typeArguments = type.typeArguments; + var newTypeArguments = instantiateTypes(typeArguments, mapper); + return newTypeArguments !== typeArguments ? createTypeReference(type.target, newTypeArguments) : type; + } + return type; + } + if (flags & 1048576 /* Union */ && !(flags & 131068 /* Primitive */)) { + var types = type.types; + var newTypes = instantiateTypes(types, mapper); + return newTypes !== types ? getUnionType(newTypes, 1 /* Literal */, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type; + } + if (flags & 2097152 /* Intersection */) { + var types = type.types; + var newTypes = instantiateTypes(types, mapper); + return newTypes !== types ? getIntersectionType(newTypes, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type; + } + if (flags & 4194304 /* Index */) { + return getIndexType(instantiateType(type.type, mapper)); + } + if (flags & 8388608 /* IndexedAccess */) { + return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper)); + } + if (flags & 16777216 /* Conditional */) { + return getConditionalTypeInstantiation(type, combineTypeMappers(type.mapper, mapper)); + } + if (flags & 33554432 /* Substitution */) { + return instantiateType(type.typeVariable, mapper); + } + return type; + } + function getWildcardInstantiation(type) { + return type.flags & (131068 /* Primitive */ | 3 /* AnyOrUnknown */ | 131072 /* Never */) ? type : + type.wildcardInstantiation || (type.wildcardInstantiation = instantiateType(type, wildcardMapper)); + } + function instantiateIndexInfo(info, mapper) { + return info && createIndexInfo(instantiateType(info.type, mapper), info.isReadonly, info.declaration); + } + // Returns true if the given expression contains (at any level of nesting) a function or arrow expression + // that is subject to contextual typing. + function isContextSensitive(node) { + ts.Debug.assert(node.kind !== 156 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + switch (node.kind) { + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 156 /* MethodDeclaration */: + return isContextSensitiveFunctionLikeDeclaration(node); + case 188 /* ObjectLiteralExpression */: + return ts.some(node.properties, isContextSensitive); + case 187 /* ArrayLiteralExpression */: + return ts.some(node.elements, isContextSensitive); + case 205 /* ConditionalExpression */: + return isContextSensitive(node.whenTrue) || + isContextSensitive(node.whenFalse); + case 204 /* BinaryExpression */: + return node.operatorToken.kind === 55 /* BarBarToken */ && + (isContextSensitive(node.left) || isContextSensitive(node.right)); + case 275 /* PropertyAssignment */: + return isContextSensitive(node.initializer); + case 195 /* ParenthesizedExpression */: + return isContextSensitive(node.expression); + case 268 /* JsxAttributes */: + return ts.some(node.properties, isContextSensitive) || ts.isJsxOpeningElement(node.parent) && ts.some(node.parent.parent.children, isContextSensitive); + case 267 /* JsxAttribute */: { + // If there is no initializer, JSX attribute has a boolean value of true which is not context sensitive. + var initializer = node.initializer; + return !!initializer && isContextSensitive(initializer); + } + case 270 /* JsxExpression */: { + // It is possible to that node.expression is undefined (e.g
      ) + var expression = node.expression; + return !!expression && isContextSensitive(expression); + } + } + return false; + } + function isContextSensitiveFunctionLikeDeclaration(node) { + // Functions with type parameters are not context sensitive. + if (node.typeParameters) { + return false; + } + // Functions with any parameters that lack type annotations are context sensitive. + if (ts.some(node.parameters, function (p) { return !ts.getEffectiveTypeAnnotationNode(p); })) { + return true; + } + if (node.kind !== 197 /* ArrowFunction */) { + // If the first parameter is not an explicit 'this' parameter, then the function has + // an implicit 'this' parameter which is subject to contextual typing. + var parameter = ts.firstOrUndefined(node.parameters); + if (!(parameter && ts.parameterIsThisKeyword(parameter))) { + return true; + } + } + return hasContextSensitiveReturnExpression(node); + } + function hasContextSensitiveReturnExpression(node) { + // TODO(anhans): A block should be context-sensitive if it has a context-sensitive return value. + var body = node.body; + return body.kind === 218 /* Block */ ? false : isContextSensitive(body); + } + function isContextSensitiveFunctionOrObjectLiteralMethod(func) { + return (ts.isInJSFile(func) && ts.isFunctionDeclaration(func) || isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && + isContextSensitiveFunctionLikeDeclaration(func); + } + function getTypeWithoutSignatures(type) { + if (type.flags & 524288 /* Object */) { + var resolved = resolveStructuredTypeMembers(type); + if (resolved.constructSignatures.length || resolved.callSignatures.length) { + var result = createObjectType(16 /* Anonymous */, type.symbol); + result.members = resolved.members; + result.properties = resolved.properties; + result.callSignatures = ts.emptyArray; + result.constructSignatures = ts.emptyArray; + return result; + } + } + else if (type.flags & 2097152 /* Intersection */) { + return getIntersectionType(ts.map(type.types, getTypeWithoutSignatures)); + } + return type; + } + // TYPE CHECKING + function isTypeIdenticalTo(source, target) { + return isTypeRelatedTo(source, target, identityRelation); + } + function compareTypesIdentical(source, target) { + return isTypeRelatedTo(source, target, identityRelation) ? -1 /* True */ : 0 /* False */; + } + function compareTypesAssignable(source, target) { + return isTypeRelatedTo(source, target, assignableRelation) ? -1 /* True */ : 0 /* False */; + } + function compareTypesSubtypeOf(source, target) { + return isTypeRelatedTo(source, target, subtypeRelation) ? -1 /* True */ : 0 /* False */; + } + function isTypeSubtypeOf(source, target) { + return isTypeRelatedTo(source, target, subtypeRelation); + } + function isTypeAssignableTo(source, target) { + return isTypeRelatedTo(source, target, assignableRelation); + } + // An object type S is considered to be derived from an object type T if + // S is a union type and every constituent of S is derived from T, + // T is a union type and S is derived from at least one constituent of T, or + // S is a type variable with a base constraint that is derived from T, + // T is one of the global types Object and Function and S is a subtype of T, or + // T occurs directly or indirectly in an 'extends' clause of S. + // Note that this check ignores type parameters and only considers the + // inheritance hierarchy. + function isTypeDerivedFrom(source, target) { + return source.flags & 1048576 /* Union */ ? ts.every(source.types, function (t) { return isTypeDerivedFrom(t, target); }) : + target.flags & 1048576 /* Union */ ? ts.some(target.types, function (t) { return isTypeDerivedFrom(source, t); }) : + source.flags & 58982400 /* InstantiableNonPrimitive */ ? isTypeDerivedFrom(getBaseConstraintOfType(source) || emptyObjectType, target) : + target === globalObjectType ? !!(source.flags & (524288 /* Object */ | 67108864 /* NonPrimitive */)) : + target === globalFunctionType ? !!(source.flags & 524288 /* Object */) && isFunctionObjectType(source) : + hasBaseType(source, getTargetType(target)); + } + /** + * This is *not* a bi-directional relationship. + * If one needs to check both directions for comparability, use a second call to this function or 'checkTypeComparableTo'. + * + * A type S is comparable to a type T if some (but not necessarily all) of the possible values of S are also possible values of T. + * It is used to check following cases: + * - the types of the left and right sides of equality/inequality operators (`===`, `!==`, `==`, `!=`). + * - the types of `case` clause expressions and their respective `switch` expressions. + * - the type of an expression in a type assertion with the type being asserted. + */ + function isTypeComparableTo(source, target) { + return isTypeRelatedTo(source, target, comparableRelation); + } + function areTypesComparable(type1, type2) { + return isTypeComparableTo(type1, type2) || isTypeComparableTo(type2, type1); + } + function checkTypeAssignableTo(source, target, errorNode, headMessage, containingMessageChain, errorOutputObject) { + return checkTypeRelatedTo(source, target, assignableRelation, errorNode, headMessage, containingMessageChain, errorOutputObject); + } + /** + * Like `checkTypeAssignableTo`, but if it would issue an error, instead performs structural comparisons of the types using the given expression node to + * attempt to issue more specific errors on, for example, specific object literal properties or tuple members. + */ + function checkTypeAssignableToAndOptionallyElaborate(source, target, errorNode, expr, headMessage, containingMessageChain) { + return checkTypeRelatedToAndOptionallyElaborate(source, target, assignableRelation, errorNode, expr, headMessage, containingMessageChain); + } + function checkTypeRelatedToAndOptionallyElaborate(source, target, relation, errorNode, expr, headMessage, containingMessageChain) { + if (isTypeRelatedTo(source, target, relation)) + return true; + if (!errorNode || !elaborateError(expr, source, target, relation, headMessage)) { + return checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain); + } + return false; + } + function isOrHasGenericConditional(type) { + return !!(type.flags & 16777216 /* Conditional */ || (type.flags & 2097152 /* Intersection */ && ts.some(type.types, isOrHasGenericConditional))); + } + function elaborateError(node, source, target, relation, headMessage) { + if (!node || isOrHasGenericConditional(target)) + return false; + if (!checkTypeRelatedTo(source, target, relation, /*errorNode*/ undefined) && elaborateDidYouMeanToCallOrConstruct(node, source, target, relation, headMessage)) { + return true; + } + switch (node.kind) { + case 270 /* JsxExpression */: + case 195 /* ParenthesizedExpression */: + return elaborateError(node.expression, source, target, relation, headMessage); + case 204 /* BinaryExpression */: + switch (node.operatorToken.kind) { + case 59 /* EqualsToken */: + case 27 /* CommaToken */: + return elaborateError(node.right, source, target, relation, headMessage); + } + break; + case 188 /* ObjectLiteralExpression */: + return elaborateObjectLiteral(node, source, target, relation); + case 187 /* ArrayLiteralExpression */: + return elaborateArrayLiteral(node, source, target, relation); + case 268 /* JsxAttributes */: + return elaborateJsxAttributes(node, source, target, relation); + case 197 /* ArrowFunction */: + return elaborateArrowFunction(node, source, target, relation); + } + return false; + } + function elaborateDidYouMeanToCallOrConstruct(node, source, target, relation, headMessage) { + var callSignatures = getSignaturesOfType(source, 0 /* Call */); + var constructSignatures = getSignaturesOfType(source, 1 /* Construct */); + for (var _i = 0, _a = [constructSignatures, callSignatures]; _i < _a.length; _i++) { + var signatures = _a[_i]; + if (ts.some(signatures, function (s) { + var returnType = getReturnTypeOfSignature(s); + return !(returnType.flags & (1 /* Any */ | 131072 /* Never */)) && checkTypeRelatedTo(returnType, target, relation, /*errorNode*/ undefined); + })) { + var resultObj = {}; + checkTypeAssignableTo(source, target, node, headMessage, /*containingChain*/ undefined, resultObj); + var diagnostic = resultObj.error; + addRelatedInfo(diagnostic, ts.createDiagnosticForNode(node, signatures === constructSignatures ? ts.Diagnostics.Did_you_mean_to_use_new_with_this_expression : ts.Diagnostics.Did_you_mean_to_call_this_expression)); + return true; + } + } + return false; + } + function elaborateArrowFunction(node, source, target, relation) { + // Don't elaborate blocks + if (ts.isBlock(node.body)) { + return false; + } + // Or functions with annotated parameter types + if (ts.some(node.parameters, ts.hasType)) { + return false; + } + var sourceSig = getSingleCallSignature(source); + if (!sourceSig) { + return false; + } + var targetSignatures = getSignaturesOfType(target, 0 /* Call */); + if (!ts.length(targetSignatures)) { + return false; + } + var returnExpression = node.body; + var sourceReturn = getReturnTypeOfSignature(sourceSig); + var targetReturn = getUnionType(ts.map(targetSignatures, getReturnTypeOfSignature)); + if (!checkTypeRelatedTo(sourceReturn, targetReturn, relation, /*errorNode*/ undefined)) { + var elaborated = returnExpression && elaborateError(returnExpression, sourceReturn, targetReturn, relation, /*headMessage*/ undefined); + if (elaborated) { + return elaborated; + } + var resultObj = {}; + checkTypeRelatedTo(sourceReturn, targetReturn, relation, returnExpression, /*message*/ undefined, /*chain*/ undefined, resultObj); + if (resultObj.error) { + if (target.symbol && ts.length(target.symbol.declarations)) { + addRelatedInfo(resultObj.error, ts.createDiagnosticForNode(target.symbol.declarations[0], ts.Diagnostics.The_expected_type_comes_from_the_return_type_of_this_signature)); + } + return true; + } + } + return false; + } + /** + * For every element returned from the iterator, checks that element to issue an error on a property of that element's type + * If that element would issue an error, we first attempt to dive into that element's inner expression and issue a more specific error by recuring into `elaborateError` + * Otherwise, we issue an error on _every_ element which fail the assignability check + */ + function elaborateElementwise(iterator, source, target, relation) { + // Assignability failure - check each prop individually, and if that fails, fall back on the bad error span + var reportedError = false; + for (var status = iterator.next(); !status.done; status = iterator.next()) { + var _a = status.value, prop = _a.errorNode, next = _a.innerExpression, nameType = _a.nameType, errorMessage = _a.errorMessage; + var targetPropType = getIndexedAccessType(target, nameType, /*accessNode*/ undefined, errorType); + if (targetPropType === errorType || targetPropType.flags & 8388608 /* IndexedAccess */) + continue; // Don't elaborate on indexes on generic variables + var sourcePropType = getIndexedAccessType(source, nameType, /*accessNode*/ undefined, errorType); + if (sourcePropType !== errorType && targetPropType !== errorType && !checkTypeRelatedTo(sourcePropType, targetPropType, relation, /*errorNode*/ undefined)) { + var elaborated = next && elaborateError(next, sourcePropType, targetPropType, relation, /*headMessage*/ undefined); + if (elaborated) { + reportedError = true; + } + else { + // Issue error on the prop itself, since the prop couldn't elaborate the error + var resultObj = {}; + // Use the expression type, if available + var specificSource = next ? checkExpressionForMutableLocation(next, 0 /* Normal */, sourcePropType) : sourcePropType; + var result = checkTypeRelatedTo(specificSource, targetPropType, relation, prop, errorMessage, /*containingChain*/ undefined, resultObj); + if (result && specificSource !== sourcePropType) { + // If for whatever reason the expression type doesn't yield an error, make sure we still issue an error on the sourcePropType + checkTypeRelatedTo(sourcePropType, targetPropType, relation, prop, errorMessage, /*containingChain*/ undefined, resultObj); + } + if (resultObj.error) { + var reportedDiag = resultObj.error; + var propertyName = isTypeUsableAsLateBoundName(nameType) ? getLateBoundNameFromType(nameType) : undefined; + var targetProp = propertyName !== undefined ? getPropertyOfType(target, propertyName) : undefined; + var issuedElaboration = false; + if (!targetProp) { + var indexInfo = isTypeAssignableToKind(nameType, 296 /* NumberLike */) && getIndexInfoOfType(target, 1 /* Number */) || + getIndexInfoOfType(target, 0 /* String */) || + undefined; + if (indexInfo && indexInfo.declaration && !ts.getSourceFileOfNode(indexInfo.declaration).hasNoDefaultLib) { + issuedElaboration = true; + addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(indexInfo.declaration, ts.Diagnostics.The_expected_type_comes_from_this_index_signature)); + } + } + if (!issuedElaboration && (targetProp && ts.length(targetProp.declarations) || target.symbol && ts.length(target.symbol.declarations))) { + var targetNode = targetProp && ts.length(targetProp.declarations) ? targetProp.declarations[0] : target.symbol.declarations[0]; + if (!ts.getSourceFileOfNode(targetNode).hasNoDefaultLib) { + addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(targetNode, ts.Diagnostics.The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1, propertyName && !(nameType.flags & 8192 /* UniqueESSymbol */) ? ts.unescapeLeadingUnderscores(propertyName) : typeToString(nameType), typeToString(target))); + } + } + } + reportedError = true; + } + } + } + return reportedError; + } + function generateJsxAttributes(node) { + var _i, _a, prop; + return __generator(this, function (_b) { + switch (_b.label) { + case 0: + if (!ts.length(node.properties)) + return [2 /*return*/]; + _i = 0, _a = node.properties; + _b.label = 1; + case 1: + if (!(_i < _a.length)) return [3 /*break*/, 4]; + prop = _a[_i]; + if (ts.isJsxSpreadAttribute(prop)) + return [3 /*break*/, 3]; + return [4 /*yield*/, { errorNode: prop.name, innerExpression: prop.initializer, nameType: getLiteralType(ts.idText(prop.name)) }]; + case 2: + _b.sent(); + _b.label = 3; + case 3: + _i++; + return [3 /*break*/, 1]; + case 4: return [2 /*return*/]; + } + }); + } + function elaborateJsxAttributes(node, source, target, relation) { + return elaborateElementwise(generateJsxAttributes(node), source, target, relation); + } + function generateLimitedTupleElements(node, target) { + var len, i, elem, nameType; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + len = ts.length(node.elements); + if (!len) + return [2 /*return*/]; + i = 0; + _a.label = 1; + case 1: + if (!(i < len)) return [3 /*break*/, 4]; + // Skip elements which do not exist in the target - a length error on the tuple overall is likely better than an error on a mismatched index signature + if (isTupleLikeType(target) && !getPropertyOfType(target, ("" + i))) + return [3 /*break*/, 3]; + elem = node.elements[i]; + if (ts.isOmittedExpression(elem)) + return [3 /*break*/, 3]; + nameType = getLiteralType(i); + return [4 /*yield*/, { errorNode: elem, innerExpression: elem, nameType: nameType }]; + case 2: + _a.sent(); + _a.label = 3; + case 3: + i++; + return [3 /*break*/, 1]; + case 4: return [2 /*return*/]; + } + }); + } + function elaborateArrayLiteral(node, source, target, relation) { + if (isTupleLikeType(source)) { + return elaborateElementwise(generateLimitedTupleElements(node, target), source, target, relation); + } + // recreate a tuple from the elements, if possible + var tupleizedType = checkArrayLiteral(node, 3 /* Contextual */, /*forceTuple*/ true); + if (isTupleLikeType(tupleizedType)) { + return elaborateElementwise(generateLimitedTupleElements(node, target), tupleizedType, target, relation); + } + return false; + } + function generateObjectLiteralElements(node) { + var _i, _a, prop, type, _b; + return __generator(this, function (_c) { + switch (_c.label) { + case 0: + if (!ts.length(node.properties)) + return [2 /*return*/]; + _i = 0, _a = node.properties; + _c.label = 1; + case 1: + if (!(_i < _a.length)) return [3 /*break*/, 8]; + prop = _a[_i]; + if (ts.isSpreadAssignment(prop)) + return [3 /*break*/, 7]; + type = getLiteralTypeFromProperty(getSymbolOfNode(prop), 8576 /* StringOrNumberLiteralOrUnique */); + if (!type || (type.flags & 131072 /* Never */)) { + return [3 /*break*/, 7]; + } + _b = prop.kind; + switch (_b) { + case 159 /* SetAccessor */: return [3 /*break*/, 2]; + case 158 /* GetAccessor */: return [3 /*break*/, 2]; + case 156 /* MethodDeclaration */: return [3 /*break*/, 2]; + case 276 /* ShorthandPropertyAssignment */: return [3 /*break*/, 2]; + case 275 /* PropertyAssignment */: return [3 /*break*/, 4]; + } + return [3 /*break*/, 6]; + case 2: return [4 /*yield*/, { errorNode: prop.name, innerExpression: undefined, nameType: type }]; + case 3: + _c.sent(); + return [3 /*break*/, 7]; + case 4: return [4 /*yield*/, { errorNode: prop.name, innerExpression: prop.initializer, nameType: type, errorMessage: isComputedNonLiteralName(prop.name) ? ts.Diagnostics.Type_of_computed_property_s_value_is_0_which_is_not_assignable_to_type_1 : undefined }]; + case 5: + _c.sent(); + return [3 /*break*/, 7]; + case 6: + ts.Debug.assertNever(prop); + _c.label = 7; + case 7: + _i++; + return [3 /*break*/, 1]; + case 8: return [2 /*return*/]; + } + }); + } + function elaborateObjectLiteral(node, source, target, relation) { + return elaborateElementwise(generateObjectLiteralElements(node), source, target, relation); + } + /** + * This is *not* a bi-directional relationship. + * If one needs to check both directions for comparability, use a second call to this function or 'isTypeComparableTo'. + */ + function checkTypeComparableTo(source, target, errorNode, headMessage, containingMessageChain) { + return checkTypeRelatedTo(source, target, comparableRelation, errorNode, headMessage, containingMessageChain); + } + function isSignatureAssignableTo(source, target, ignoreReturnTypes) { + return compareSignaturesRelated(source, target, 0 /* None */, ignoreReturnTypes, /*reportErrors*/ false, + /*errorReporter*/ undefined, compareTypesAssignable) !== 0 /* False */; + } + /** + * See signatureRelatedTo, compareSignaturesIdentical + */ + function compareSignaturesRelated(source, target, callbackCheck, ignoreReturnTypes, reportErrors, errorReporter, compareTypes) { + // TODO (drosen): De-duplicate code between related functions. + if (source === target) { + return -1 /* True */; + } + var targetCount = getParameterCount(target); + if (!hasEffectiveRestParameter(target) && getMinArgumentCount(source) > targetCount) { + return 0 /* False */; + } + if (source.typeParameters && source.typeParameters !== target.typeParameters) { + target = getCanonicalSignature(target); + source = instantiateSignatureInContextOf(source, target, /*contextualMapper*/ undefined, compareTypes); + } + var sourceCount = getParameterCount(source); + var sourceRestType = getNonArrayRestType(source); + var targetRestType = getNonArrayRestType(target); + if (sourceRestType && targetRestType && sourceCount !== targetCount) { + // We're not able to relate misaligned complex rest parameters + return 0 /* False */; + } + var kind = target.declaration ? target.declaration.kind : 0 /* Unknown */; + var strictVariance = !callbackCheck && strictFunctionTypes && kind !== 156 /* MethodDeclaration */ && + kind !== 155 /* MethodSignature */ && kind !== 157 /* Constructor */; + var result = -1 /* True */; + var sourceThisType = getThisTypeOfSignature(source); + if (sourceThisType && sourceThisType !== voidType) { + var targetThisType = getThisTypeOfSignature(target); + if (targetThisType) { + // void sources are assignable to anything. + var related = !strictVariance && compareTypes(sourceThisType, targetThisType, /*reportErrors*/ false) + || compareTypes(targetThisType, sourceThisType, reportErrors); + if (!related) { + if (reportErrors) { + errorReporter(ts.Diagnostics.The_this_types_of_each_signature_are_incompatible); + } + return 0 /* False */; + } + result &= related; + } + } + var paramCount = sourceRestType || targetRestType ? Math.min(sourceCount, targetCount) : Math.max(sourceCount, targetCount); + var restIndex = sourceRestType || targetRestType ? paramCount - 1 : -1; + for (var i = 0; i < paramCount; i++) { + var sourceType = i === restIndex ? getRestTypeAtPosition(source, i) : getTypeAtPosition(source, i); + var targetType = i === restIndex ? getRestTypeAtPosition(target, i) : getTypeAtPosition(target, i); + // In order to ensure that any generic type Foo is at least co-variant with respect to T no matter + // how Foo uses T, we need to relate parameters bi-variantly (given that parameters are input positions, + // they naturally relate only contra-variantly). However, if the source and target parameters both have + // function types with a single call signature, we know we are relating two callback parameters. In + // that case it is sufficient to only relate the parameters of the signatures co-variantly because, + // similar to return values, callback parameters are output positions. This means that a Promise, + // where T is used only in callback parameter positions, will be co-variant (as opposed to bi-variant) + // with respect to T. + var sourceSig = callbackCheck ? undefined : getSingleCallSignature(getNonNullableType(sourceType)); + var targetSig = callbackCheck ? undefined : getSingleCallSignature(getNonNullableType(targetType)); + var callbacks = sourceSig && targetSig && !signatureHasTypePredicate(sourceSig) && !signatureHasTypePredicate(targetSig) && + (getFalsyFlags(sourceType) & 98304 /* Nullable */) === (getFalsyFlags(targetType) & 98304 /* Nullable */); + var related = callbacks ? + // TODO: GH#18217 It will work if they're both `undefined`, but not if only one is + compareSignaturesRelated(targetSig, sourceSig, strictVariance ? 2 /* Strict */ : 1 /* Bivariant */, /*ignoreReturnTypes*/ false, reportErrors, errorReporter, compareTypes) : + !callbackCheck && !strictVariance && compareTypes(sourceType, targetType, /*reportErrors*/ false) || compareTypes(targetType, sourceType, reportErrors); + if (!related) { + if (reportErrors) { + errorReporter(ts.Diagnostics.Types_of_parameters_0_and_1_are_incompatible, ts.unescapeLeadingUnderscores(getParameterNameAtPosition(source, i)), ts.unescapeLeadingUnderscores(getParameterNameAtPosition(target, i))); + } + return 0 /* False */; + } + result &= related; + } + if (!ignoreReturnTypes) { + var targetReturnType = (target.declaration && isJSConstructor(target.declaration)) ? + getJSClassType(target.declaration.symbol) : getReturnTypeOfSignature(target); + if (targetReturnType === voidType) { + return result; + } + var sourceReturnType = (source.declaration && isJSConstructor(source.declaration)) ? + getJSClassType(source.declaration.symbol) : getReturnTypeOfSignature(source); + // The following block preserves behavior forbidding boolean returning functions from being assignable to type guard returning functions + var targetTypePredicate = getTypePredicateOfSignature(target); + if (targetTypePredicate) { + var sourceTypePredicate = getTypePredicateOfSignature(source); + if (sourceTypePredicate) { + result &= compareTypePredicateRelatedTo(sourceTypePredicate, targetTypePredicate, source.declaration, target.declaration, reportErrors, errorReporter, compareTypes); // TODO: GH#18217 + } + else if (ts.isIdentifierTypePredicate(targetTypePredicate)) { + if (reportErrors) { + errorReporter(ts.Diagnostics.Signature_0_must_be_a_type_predicate, signatureToString(source)); + } + return 0 /* False */; + } + } + else { + // When relating callback signatures, we still need to relate return types bi-variantly as otherwise + // the containing type wouldn't be co-variant. For example, interface Foo { add(cb: () => T): void } + // wouldn't be co-variant for T without this rule. + result &= callbackCheck === 1 /* Bivariant */ && compareTypes(targetReturnType, sourceReturnType, /*reportErrors*/ false) || + compareTypes(sourceReturnType, targetReturnType, reportErrors); + } + } + return result; + } + function compareTypePredicateRelatedTo(source, target, sourceDeclaration, targetDeclaration, reportErrors, errorReporter, compareTypes) { + if (source.kind !== target.kind) { + if (reportErrors) { + errorReporter(ts.Diagnostics.A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard); + errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target)); + } + return 0 /* False */; + } + if (source.kind === 1 /* Identifier */) { + var targetPredicate = target; + var sourceIndex = source.parameterIndex - (ts.getThisParameter(sourceDeclaration) ? 1 : 0); + var targetIndex = targetPredicate.parameterIndex - (ts.getThisParameter(targetDeclaration) ? 1 : 0); + if (sourceIndex !== targetIndex) { + if (reportErrors) { + errorReporter(ts.Diagnostics.Parameter_0_is_not_in_the_same_position_as_parameter_1, source.parameterName, targetPredicate.parameterName); + errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target)); + } + return 0 /* False */; + } + } + var related = compareTypes(source.type, target.type, reportErrors); + if (related === 0 /* False */ && reportErrors) { + errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target)); + } + return related; + } + function isImplementationCompatibleWithOverload(implementation, overload) { + var erasedSource = getErasedSignature(implementation); + var erasedTarget = getErasedSignature(overload); + // First see if the return types are compatible in either direction. + var sourceReturnType = getReturnTypeOfSignature(erasedSource); + var targetReturnType = getReturnTypeOfSignature(erasedTarget); + if (targetReturnType === voidType + || isTypeRelatedTo(targetReturnType, sourceReturnType, assignableRelation) + || isTypeRelatedTo(sourceReturnType, targetReturnType, assignableRelation)) { + return isSignatureAssignableTo(erasedSource, erasedTarget, /*ignoreReturnTypes*/ true); + } + return false; + } + function isEmptyResolvedType(t) { + return t.properties.length === 0 && + t.callSignatures.length === 0 && + t.constructSignatures.length === 0 && + !t.stringIndexInfo && + !t.numberIndexInfo; + } + function isEmptyObjectType(type) { + return type.flags & 524288 /* Object */ ? isEmptyResolvedType(resolveStructuredTypeMembers(type)) : + type.flags & 67108864 /* NonPrimitive */ ? true : + type.flags & 1048576 /* Union */ ? ts.some(type.types, isEmptyObjectType) : + type.flags & 2097152 /* Intersection */ ? ts.every(type.types, isEmptyObjectType) : + false; + } + function isEmptyAnonymousObjectType(type) { + return !!(ts.getObjectFlags(type) & 16 /* Anonymous */) && isEmptyObjectType(type); + } + function isEnumTypeRelatedTo(sourceSymbol, targetSymbol, errorReporter) { + if (sourceSymbol === targetSymbol) { + return true; + } + var id = getSymbolId(sourceSymbol) + "," + getSymbolId(targetSymbol); + var relation = enumRelation.get(id); + if (relation !== undefined && !(relation === 2 /* Failed */ && errorReporter)) { + return relation === 1 /* Succeeded */; + } + if (sourceSymbol.escapedName !== targetSymbol.escapedName || !(sourceSymbol.flags & 256 /* RegularEnum */) || !(targetSymbol.flags & 256 /* RegularEnum */)) { + enumRelation.set(id, 3 /* FailedAndReported */); + return false; + } + var targetEnumType = getTypeOfSymbol(targetSymbol); + for (var _i = 0, _a = getPropertiesOfType(getTypeOfSymbol(sourceSymbol)); _i < _a.length; _i++) { + var property = _a[_i]; + if (property.flags & 8 /* EnumMember */) { + var targetProperty = getPropertyOfType(targetEnumType, property.escapedName); + if (!targetProperty || !(targetProperty.flags & 8 /* EnumMember */)) { + if (errorReporter) { + errorReporter(ts.Diagnostics.Property_0_is_missing_in_type_1, ts.symbolName(property), typeToString(getDeclaredTypeOfSymbol(targetSymbol), /*enclosingDeclaration*/ undefined, 64 /* UseFullyQualifiedType */)); + enumRelation.set(id, 3 /* FailedAndReported */); + } + else { + enumRelation.set(id, 2 /* Failed */); + } + return false; + } + } + } + enumRelation.set(id, 1 /* Succeeded */); + return true; + } + function isSimpleTypeRelatedTo(source, target, relation, errorReporter) { + var s = source.flags; + var t = target.flags; + if (t & 3 /* AnyOrUnknown */ || s & 131072 /* Never */ || source === wildcardType) + return true; + if (t & 131072 /* Never */) + return false; + if (s & 132 /* StringLike */ && t & 4 /* String */) + return true; + if (s & 128 /* StringLiteral */ && s & 1024 /* EnumLiteral */ && + t & 128 /* StringLiteral */ && !(t & 1024 /* EnumLiteral */) && + source.value === target.value) + return true; + if (s & 296 /* NumberLike */ && t & 8 /* Number */) + return true; + if (s & 256 /* NumberLiteral */ && s & 1024 /* EnumLiteral */ && + t & 256 /* NumberLiteral */ && !(t & 1024 /* EnumLiteral */) && + source.value === target.value) + return true; + if (s & 2112 /* BigIntLike */ && t & 64 /* BigInt */) + return true; + if (s & 528 /* BooleanLike */ && t & 16 /* Boolean */) + return true; + if (s & 12288 /* ESSymbolLike */ && t & 4096 /* ESSymbol */) + return true; + if (s & 32 /* Enum */ && t & 32 /* Enum */ && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) + return true; + if (s & 1024 /* EnumLiteral */ && t & 1024 /* EnumLiteral */) { + if (s & 1048576 /* Union */ && t & 1048576 /* Union */ && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) + return true; + if (s & 2944 /* Literal */ && t & 2944 /* Literal */ && + source.value === target.value && + isEnumTypeRelatedTo(getParentOfSymbol(source.symbol), getParentOfSymbol(target.symbol), errorReporter)) + return true; + } + if (s & 32768 /* Undefined */ && (!strictNullChecks || t & (32768 /* Undefined */ | 16384 /* Void */))) + return true; + if (s & 65536 /* Null */ && (!strictNullChecks || t & 65536 /* Null */)) + return true; + if (s & 524288 /* Object */ && t & 67108864 /* NonPrimitive */) + return true; + if (s & 8192 /* UniqueESSymbol */ || t & 8192 /* UniqueESSymbol */) + return false; + if (relation === assignableRelation || relation === definitelyAssignableRelation || relation === comparableRelation) { + if (s & 1 /* Any */) + return true; + // Type number or any numeric literal type is assignable to any numeric enum type or any + // numeric enum literal type. This rule exists for backwards compatibility reasons because + // bit-flag enum types sometimes look like literal enum types with numeric literal values. + if (s & (8 /* Number */ | 256 /* NumberLiteral */) && !(s & 1024 /* EnumLiteral */) && (t & 32 /* Enum */ || t & 256 /* NumberLiteral */ && t & 1024 /* EnumLiteral */)) + return true; + } + return false; + } + function isTypeRelatedTo(source, target, relation) { + if (isFreshLiteralType(source)) { + source = source.regularType; + } + if (isFreshLiteralType(target)) { + target = target.regularType; + } + if (source === target || + relation === comparableRelation && !(target.flags & 131072 /* Never */) && isSimpleTypeRelatedTo(target, source, relation) || + relation !== identityRelation && isSimpleTypeRelatedTo(source, target, relation)) { + return true; + } + if (source.flags & 524288 /* Object */ && target.flags & 524288 /* Object */) { + var related = relation.get(getRelationKey(source, target, relation)); + if (related !== undefined) { + return related === 1 /* Succeeded */; + } + } + if (source.flags & 66846720 /* StructuredOrInstantiable */ || target.flags & 66846720 /* StructuredOrInstantiable */) { + return checkTypeRelatedTo(source, target, relation, /*errorNode*/ undefined); + } + return false; + } + function isIgnoredJsxProperty(source, sourceProp, targetMemberType) { + return ts.getObjectFlags(source) & 4096 /* JsxAttributes */ && !(isUnhyphenatedJsxName(sourceProp.escapedName) || targetMemberType); + } + /** + * Checks if 'source' is related to 'target' (e.g.: is a assignable to). + * @param source The left-hand-side of the relation. + * @param target The right-hand-side of the relation. + * @param relation The relation considered. One of 'identityRelation', 'subtypeRelation', 'assignableRelation', or 'comparableRelation'. + * Used as both to determine which checks are performed and as a cache of previously computed results. + * @param errorNode The suggested node upon which all errors will be reported, if defined. This may or may not be the actual node used. + * @param headMessage If the error chain should be prepended by a head message, then headMessage will be used. + * @param containingMessageChain A chain of errors to prepend any new errors found. + */ + function checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain, errorOutputContainer) { + var errorInfo; + var relatedInfo; + var maybeKeys; + var sourceStack; + var targetStack; + var maybeCount = 0; + var depth = 0; + var expandingFlags = 0 /* None */; + var overflow = false; + var suppressNextError = false; + ts.Debug.assert(relation !== identityRelation || !errorNode, "no error reporting in identity checking"); + var result = isRelatedTo(source, target, /*reportErrors*/ !!errorNode, headMessage); + if (overflow) { + error(errorNode, ts.Diagnostics.Excessive_stack_depth_comparing_types_0_and_1, typeToString(source), typeToString(target)); + } + else if (errorInfo) { + if (containingMessageChain) { + var chain_1 = containingMessageChain(); + if (chain_1) { + errorInfo = ts.concatenateDiagnosticMessageChains(chain_1, errorInfo); + } + } + var relatedInformation = void 0; + // Check if we should issue an extra diagnostic to produce a quickfix for a slightly incorrect import statement + if (headMessage && errorNode && !result && source.symbol) { + var links = getSymbolLinks(source.symbol); + if (links.originatingImport && !ts.isImportCall(links.originatingImport)) { + var helpfulRetry = checkTypeRelatedTo(getTypeOfSymbol(links.target), target, relation, /*errorNode*/ undefined); + if (helpfulRetry) { + // Likely an incorrect import. Issue a helpful diagnostic to produce a quickfix to change the import + var diag_1 = ts.createDiagnosticForNode(links.originatingImport, ts.Diagnostics.Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_Consider_using_a_default_import_or_import_require_here_instead); + relatedInformation = ts.append(relatedInformation, diag_1); // Cause the error to appear with the error that triggered it + } + } + } + var diag = ts.createDiagnosticForNodeFromMessageChain(errorNode, errorInfo, relatedInformation); + if (relatedInfo) { + addRelatedInfo.apply(void 0, [diag].concat(relatedInfo)); + } + if (errorOutputContainer) { + errorOutputContainer.error = diag; + } + diagnostics.add(diag); // TODO: GH#18217 + } + return result !== 0 /* False */; + function reportError(message, arg0, arg1, arg2, arg3) { + ts.Debug.assert(!!errorNode); + errorInfo = ts.chainDiagnosticMessages(errorInfo, message, arg0, arg1, arg2, arg3); + } + function associateRelatedInfo(info) { + ts.Debug.assert(!!errorInfo); + if (!relatedInfo) { + relatedInfo = [info]; + } + else { + relatedInfo.push(info); + } + } + function reportRelationError(message, source, target) { + var sourceType = typeToString(source); + var targetType = typeToString(target); + if (sourceType === targetType) { + sourceType = typeToString(source, /*enclosingDeclaration*/ undefined, 64 /* UseFullyQualifiedType */); + targetType = typeToString(target, /*enclosingDeclaration*/ undefined, 64 /* UseFullyQualifiedType */); + } + if (!message) { + if (relation === comparableRelation) { + message = ts.Diagnostics.Type_0_is_not_comparable_to_type_1; + } + else if (sourceType === targetType) { + message = ts.Diagnostics.Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated; + } + else { + message = ts.Diagnostics.Type_0_is_not_assignable_to_type_1; + } + } + reportError(message, sourceType, targetType); + } + function tryElaborateErrorsForPrimitivesAndObjects(source, target) { + var sourceType = typeToString(source); + var targetType = typeToString(target); + if ((globalStringType === source && stringType === target) || + (globalNumberType === source && numberType === target) || + (globalBooleanType === source && booleanType === target) || + (getGlobalESSymbolType(/*reportErrors*/ false) === source && esSymbolType === target)) { + reportError(ts.Diagnostics._0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible, targetType, sourceType); + } + } + function isUnionOrIntersectionTypeWithoutNullableConstituents(type) { + if (!(type.flags & 3145728 /* UnionOrIntersection */)) { + return false; + } + // at this point we know that this is union or intersection type possibly with nullable constituents. + // check if we still will have compound type if we ignore nullable components. + var seenNonNullable = false; + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (t.flags & 98304 /* Nullable */) { + continue; + } + if (seenNonNullable) { + return true; + } + seenNonNullable = true; + } + return false; + } + /** + * Compare two types and return + * * Ternary.True if they are related with no assumptions, + * * Ternary.Maybe if they are related with assumptions of other relationships, or + * * Ternary.False if they are not related. + */ + function isRelatedTo(source, target, reportErrors, headMessage, isApparentIntersectionConstituent) { + if (reportErrors === void 0) { reportErrors = false; } + if (isFreshLiteralType(source)) { + source = source.regularType; + } + if (isFreshLiteralType(target)) { + target = target.regularType; + } + if (source.flags & 33554432 /* Substitution */) { + source = relation === definitelyAssignableRelation ? source.typeVariable : source.substitute; + } + if (target.flags & 33554432 /* Substitution */) { + target = target.typeVariable; + } + if (source.flags & 8388608 /* IndexedAccess */) { + source = getSimplifiedType(source); + } + if (target.flags & 8388608 /* IndexedAccess */) { + target = getSimplifiedType(target); + } + // Try to see if we're relating something like `Foo` -> `Bar | null | undefined`. + // If so, reporting the `null` and `undefined` in the type is hardly useful. + // First, see if we're even relating an object type to a union. + // Then see if the target is stripped down to a single non-union type. + // Note + // * We actually want to remove null and undefined naively here (rather than using getNonNullableType), + // since we don't want to end up with a worse error like "`Foo` is not assignable to `NonNullable`" + // when dealing with generics. + // * We also don't deal with primitive source types, since we already halt elaboration below. + if (target.flags & 1048576 /* Union */ && source.flags & 524288 /* Object */ && + target.types.length <= 3 && maybeTypeOfKind(target, 98304 /* Nullable */)) { + var nullStrippedTarget = extractTypesOfKind(target, ~98304 /* Nullable */); + if (!(nullStrippedTarget.flags & (1048576 /* Union */ | 131072 /* Never */))) { + target = nullStrippedTarget; + } + } + // both types are the same - covers 'they are the same primitive type or both are Any' or the same type parameter cases + if (source === target) + return -1 /* True */; + if (relation === identityRelation) { + return isIdenticalTo(source, target); + } + if (relation === comparableRelation && !(target.flags & 131072 /* Never */) && isSimpleTypeRelatedTo(target, source, relation) || + isSimpleTypeRelatedTo(source, target, relation, reportErrors ? reportError : undefined)) + return -1 /* True */; + var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096 /* JsxAttributes */); + if (isObjectLiteralType(source) && ts.getObjectFlags(source) & 32768 /* FreshLiteral */) { + var discriminantType = target.flags & 1048576 /* Union */ ? findMatchingDiscriminantType(source, target) : undefined; + if (hasExcessProperties(source, target, discriminantType, reportErrors)) { + if (reportErrors) { + reportRelationError(headMessage, source, target); + } + return 0 /* False */; + } + // Above we check for excess properties with respect to the entire target type. When union + // and intersection types are further deconstructed on the target side, we don't want to + // make the check again (as it might fail for a partial target type). Therefore we obtain + // the regular source type and proceed with that. + if (isUnionOrIntersectionTypeWithoutNullableConstituents(target) && !discriminantType) { + source = getRegularTypeOfObjectLiteral(source); + } + } + if (relation !== comparableRelation && !isApparentIntersectionConstituent && + source.flags & (131068 /* Primitive */ | 524288 /* Object */ | 2097152 /* Intersection */) && source !== globalObjectType && + target.flags & (524288 /* Object */ | 2097152 /* Intersection */) && isWeakType(target) && + (getPropertiesOfType(source).length > 0 || typeHasCallOrConstructSignatures(source)) && + !hasCommonProperties(source, target, isComparingJsxAttributes)) { + if (reportErrors) { + var calls = getSignaturesOfType(source, 0 /* Call */); + var constructs = getSignaturesOfType(source, 1 /* Construct */); + if (calls.length > 0 && isRelatedTo(getReturnTypeOfSignature(calls[0]), target, /*reportErrors*/ false) || + constructs.length > 0 && isRelatedTo(getReturnTypeOfSignature(constructs[0]), target, /*reportErrors*/ false)) { + reportError(ts.Diagnostics.Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it, typeToString(source), typeToString(target)); + } + else { + reportError(ts.Diagnostics.Type_0_has_no_properties_in_common_with_type_1, typeToString(source), typeToString(target)); + } + } + return 0 /* False */; + } + var result = 0 /* False */; + var saveErrorInfo = errorInfo; + var isIntersectionConstituent = !!isApparentIntersectionConstituent; + // Note that these checks are specifically ordered to produce correct results. In particular, + // we need to deconstruct unions before intersections (because unions are always at the top), + // and we need to handle "each" relations before "some" relations for the same kind of type. + if (source.flags & 1048576 /* Union */) { + result = relation === comparableRelation ? + someTypeRelatedToType(source, target, reportErrors && !(source.flags & 131068 /* Primitive */)) : + eachTypeRelatedToType(source, target, reportErrors && !(source.flags & 131068 /* Primitive */)); + } + else { + if (target.flags & 1048576 /* Union */) { + result = typeRelatedToSomeType(source, target, reportErrors && !(source.flags & 131068 /* Primitive */) && !(target.flags & 131068 /* Primitive */)); + } + else if (target.flags & 2097152 /* Intersection */) { + isIntersectionConstituent = true; // set here to affect the following trio of checks + result = typeRelatedToEachType(source, target, reportErrors); + } + else if (source.flags & 2097152 /* Intersection */) { + // Check to see if any constituents of the intersection are immediately related to the target. + // + // Don't report errors though. Checking whether a constituent is related to the source is not actually + // useful and leads to some confusing error messages. Instead it is better to let the below checks + // take care of this, or to not elaborate at all. For instance, + // + // - For an object type (such as 'C = A & B'), users are usually more interested in structural errors. + // + // - For a union type (such as '(A | B) = (C & D)'), it's better to hold onto the whole intersection + // than to report that 'D' is not assignable to 'A' or 'B'. + // + // - For a primitive type or type parameter (such as 'number = A & B') there is no point in + // breaking the intersection apart. + result = someTypeRelatedToType(source, target, /*reportErrors*/ false); + } + if (!result && (source.flags & 66846720 /* StructuredOrInstantiable */ || target.flags & 66846720 /* StructuredOrInstantiable */)) { + if (result = recursiveTypeRelatedTo(source, target, reportErrors, isIntersectionConstituent)) { + errorInfo = saveErrorInfo; + } + } + } + if (!result && source.flags & 2097152 /* Intersection */) { + // The combined constraint of an intersection type is the intersection of the constraints of + // the constituents. When an intersection type contains instantiable types with union type + // constraints, there are situations where we need to examine the combined constraint. One is + // when the target is a union type. Another is when the intersection contains types belonging + // to one of the disjoint domains. For example, given type variables T and U, each with the + // constraint 'string | number', the combined constraint of 'T & U' is 'string | number' and + // we need to check this constraint against a union on the target side. Also, given a type + // variable V constrained to 'string | number', 'V & number' has a combined constraint of + // 'string & number | number & number' which reduces to just 'number'. + var constraint = getUnionConstraintOfIntersection(source, !!(target.flags & 1048576 /* Union */)); + if (constraint) { + if (result = isRelatedTo(constraint, target, reportErrors, /*headMessage*/ undefined, isIntersectionConstituent)) { + errorInfo = saveErrorInfo; + } + } + } + if (!result && reportErrors) { + var maybeSuppress = suppressNextError; + suppressNextError = false; + if (source.flags & 524288 /* Object */ && target.flags & 131068 /* Primitive */) { + tryElaborateErrorsForPrimitivesAndObjects(source, target); + } + else if (source.symbol && source.flags & 524288 /* Object */ && globalObjectType === source) { + reportError(ts.Diagnostics.The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead); + } + else if (isComparingJsxAttributes && target.flags & 2097152 /* Intersection */) { + var targetTypes = target.types; + var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes, errorNode); + var intrinsicClassAttributes = getJsxType(JsxNames.IntrinsicClassAttributes, errorNode); + if (intrinsicAttributes !== errorType && intrinsicClassAttributes !== errorType && + (ts.contains(targetTypes, intrinsicAttributes) || ts.contains(targetTypes, intrinsicClassAttributes))) { + // do not report top error + return result; + } + } + if (!headMessage && maybeSuppress) { + // Used by, eg, missing property checking to replace the top-level message with a more informative one + return result; + } + reportRelationError(headMessage, source, target); + } + return result; + } + function isIdenticalTo(source, target) { + var result; + var flags = source.flags & target.flags; + if (flags & 524288 /* Object */ || flags & 8388608 /* IndexedAccess */ || flags & 16777216 /* Conditional */ || flags & 4194304 /* Index */ || flags & 33554432 /* Substitution */) { + return recursiveTypeRelatedTo(source, target, /*reportErrors*/ false, /*isIntersectionConstituent*/ false); + } + if (flags & (1048576 /* Union */ | 2097152 /* Intersection */)) { + if (result = eachTypeRelatedToSomeType(source, target)) { + if (result &= eachTypeRelatedToSomeType(target, source)) { + return result; + } + } + } + return 0 /* False */; + } + function hasExcessProperties(source, target, discriminant, reportErrors) { + if (!noImplicitAny && ts.getObjectFlags(target) & 16384 /* JSLiteral */) { + return false; // Disable excess property checks on JS literals to simulate having an implicit "index signature" - but only outside of noImplicitAny + } + if (maybeTypeOfKind(target, 524288 /* Object */) && !(ts.getObjectFlags(target) & 512 /* ObjectLiteralPatternWithComputedProperties */)) { + var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096 /* JsxAttributes */); + if ((relation === assignableRelation || relation === definitelyAssignableRelation || relation === comparableRelation) && + (isTypeSubsetOf(globalObjectType, target) || (!isComparingJsxAttributes && isEmptyObjectType(target)))) { + return false; + } + if (discriminant) { + // check excess properties against discriminant type only, not the entire union + return hasExcessProperties(source, discriminant, /*discriminant*/ undefined, reportErrors); + } + var _loop_6 = function (prop) { + if (shouldCheckAsExcessProperty(prop, source.symbol) && !isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { + if (reportErrors) { + // We know *exactly* where things went wrong when comparing the types. + // Use this property as the error node as this will be more helpful in + // reasoning about what went wrong. + if (!errorNode) + return { value: ts.Debug.fail() }; + if (ts.isJsxAttributes(errorNode) || ts.isJsxOpeningLikeElement(errorNode) || ts.isJsxOpeningLikeElement(errorNode.parent)) { + // JsxAttributes has an object-literal flag and undergo same type-assignablity check as normal object-literal. + // However, using an object-literal error message will be very confusing to the users so we give different a message. + // TODO: Spelling suggestions for excess jsx attributes (needs new diagnostic messages) + reportError(ts.Diagnostics.Property_0_does_not_exist_on_type_1, symbolToString(prop), typeToString(target)); + } + else { + // use the property's value declaration if the property is assigned inside the literal itself + var objectLiteralDeclaration_1 = source.symbol && ts.firstOrUndefined(source.symbol.declarations); + var suggestion = void 0; + if (prop.valueDeclaration && ts.findAncestor(prop.valueDeclaration, function (d) { return d === objectLiteralDeclaration_1; })) { + var propDeclaration = prop.valueDeclaration; + ts.Debug.assertNode(propDeclaration, ts.isObjectLiteralElementLike); + errorNode = propDeclaration; + var name = propDeclaration.name; + if (ts.isIdentifier(name)) { + suggestion = getSuggestionForNonexistentProperty(name, target); + } + } + if (suggestion !== undefined) { + reportError(ts.Diagnostics.Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_write_2, symbolToString(prop), typeToString(target), suggestion); + } + else { + reportError(ts.Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(prop), typeToString(target)); + } + } + } + return { value: true }; + } + }; + for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) { + var prop = _a[_i]; + var state_2 = _loop_6(prop); + if (typeof state_2 === "object") + return state_2.value; + } + } + return false; + } + function shouldCheckAsExcessProperty(prop, container) { + return prop.valueDeclaration && container.valueDeclaration && prop.valueDeclaration.parent === container.valueDeclaration; + } + function eachTypeRelatedToSomeType(source, target) { + var result = -1 /* True */; + var sourceTypes = source.types; + for (var _i = 0, sourceTypes_1 = sourceTypes; _i < sourceTypes_1.length; _i++) { + var sourceType = sourceTypes_1[_i]; + var related = typeRelatedToSomeType(sourceType, target, /*reportErrors*/ false); + if (!related) { + return 0 /* False */; + } + result &= related; + } + return result; + } + function typeRelatedToSomeType(source, target, reportErrors) { + var targetTypes = target.types; + if (target.flags & 1048576 /* Union */ && containsType(targetTypes, source)) { + return -1 /* True */; + } + for (var _i = 0, targetTypes_1 = targetTypes; _i < targetTypes_1.length; _i++) { + var type = targetTypes_1[_i]; + var related = isRelatedTo(source, type, /*reportErrors*/ false); + if (related) { + return related; + } + } + if (reportErrors) { + var bestMatchingType = findMatchingDiscriminantType(source, target) || + findMatchingTypeReferenceOrTypeAliasReference(source, target) || + findBestTypeForObjectLiteral(source, target) || + findBestTypeForInvokable(source, target) || + findMostOverlappyType(source, target); + isRelatedTo(source, bestMatchingType || targetTypes[targetTypes.length - 1], /*reportErrors*/ true); + } + return 0 /* False */; + } + function findMatchingTypeReferenceOrTypeAliasReference(source, unionTarget) { + var sourceObjectFlags = ts.getObjectFlags(source); + if (sourceObjectFlags & (4 /* Reference */ | 16 /* Anonymous */) && unionTarget.flags & 1048576 /* Union */) { + return ts.find(unionTarget.types, function (target) { + if (target.flags & 524288 /* Object */) { + var overlapObjFlags = sourceObjectFlags & ts.getObjectFlags(target); + if (overlapObjFlags & 4 /* Reference */) { + return source.target === target.target; + } + if (overlapObjFlags & 16 /* Anonymous */) { + return !!source.aliasSymbol && source.aliasSymbol === target.aliasSymbol; + } + } + return false; + }); + } + } + function findBestTypeForObjectLiteral(source, unionTarget) { + if (ts.getObjectFlags(source) & 128 /* ObjectLiteral */ && forEachType(unionTarget, isArrayLikeType)) { + return ts.find(unionTarget.types, function (t) { return !isArrayLikeType(t); }); + } + } + function findBestTypeForInvokable(source, unionTarget) { + var signatureKind = 0 /* Call */; + var hasSignatures = getSignaturesOfType(source, signatureKind).length > 0 || + (signatureKind = 1 /* Construct */, getSignaturesOfType(source, signatureKind).length > 0); + if (hasSignatures) { + return ts.find(unionTarget.types, function (t) { return getSignaturesOfType(t, signatureKind).length > 0; }); + } + } + function findMostOverlappyType(source, unionTarget) { + var bestMatch; + var matchingCount = 0; + for (var _i = 0, _a = unionTarget.types; _i < _a.length; _i++) { + var target_1 = _a[_i]; + var overlap = getIntersectionType([getIndexType(source), getIndexType(target_1)]); + if (overlap.flags & 4194304 /* Index */) { + // perfect overlap of keys + bestMatch = target_1; + matchingCount = Infinity; + } + else if (overlap.flags & 1048576 /* Union */) { + // Some subset overlap if we have only string literals. + // If we have a union of index types, it seems likely that we + // needed to elaborate between two generic mapped types anyway. + var len = ts.length(overlap.types); + if (len >= matchingCount) { + bestMatch = target_1; + matchingCount = len; + } + } + else if (!(overlap.flags & 131072 /* Never */) && 1 >= matchingCount) { + bestMatch = target_1; + matchingCount = 1; + } + } + return bestMatch; + } + // Keep this up-to-date with the same logic within `getApparentTypeOfContextualType`, since they should behave similarly + function findMatchingDiscriminantType(source, target) { + if (target.flags & 1048576 /* Union */) { + var sourceProperties = getPropertiesOfObjectType(source); + if (sourceProperties) { + var sourcePropertiesFiltered = findDiscriminantProperties(sourceProperties, target); + if (sourcePropertiesFiltered) { + return discriminateTypeByDiscriminableItems(target, ts.map(sourcePropertiesFiltered, function (p) { return [function () { return getTypeOfSymbol(p); }, p.escapedName]; }), isRelatedTo); + } + } + } + return undefined; + } + function typeRelatedToEachType(source, target, reportErrors) { + var result = -1 /* True */; + var targetTypes = target.types; + for (var _i = 0, targetTypes_2 = targetTypes; _i < targetTypes_2.length; _i++) { + var targetType = targetTypes_2[_i]; + var related = isRelatedTo(source, targetType, reportErrors, /*headMessage*/ undefined, /*isIntersectionConstituent*/ true); + if (!related) { + return 0 /* False */; + } + result &= related; + } + return result; + } + function someTypeRelatedToType(source, target, reportErrors) { + var sourceTypes = source.types; + if (source.flags & 1048576 /* Union */ && containsType(sourceTypes, target)) { + return -1 /* True */; + } + var len = sourceTypes.length; + for (var i = 0; i < len; i++) { + var related = isRelatedTo(sourceTypes[i], target, reportErrors && i === len - 1); + if (related) { + return related; + } + } + return 0 /* False */; + } + function eachTypeRelatedToType(source, target, reportErrors) { + var result = -1 /* True */; + var sourceTypes = source.types; + for (var _i = 0, sourceTypes_2 = sourceTypes; _i < sourceTypes_2.length; _i++) { + var sourceType = sourceTypes_2[_i]; + var related = isRelatedTo(sourceType, target, reportErrors); + if (!related) { + return 0 /* False */; + } + result &= related; + } + return result; + } + function typeArgumentsRelatedTo(sources, targets, variances, reportErrors) { + if (sources === void 0) { sources = ts.emptyArray; } + if (targets === void 0) { targets = ts.emptyArray; } + if (variances === void 0) { variances = ts.emptyArray; } + if (sources.length !== targets.length && relation === identityRelation) { + return 0 /* False */; + } + var length = sources.length <= targets.length ? sources.length : targets.length; + var result = -1 /* True */; + for (var i = 0; i < length; i++) { + // When variance information isn't available we default to covariance. This happens + // in the process of computing variance information for recursive types and when + // comparing 'this' type arguments. + var variance = i < variances.length ? variances[i] : 1 /* Covariant */; + // We ignore arguments for independent type parameters (because they're never witnessed). + if (variance !== 4 /* Independent */) { + var s = sources[i]; + var t = targets[i]; + var related = -1 /* True */; + if (variance === 1 /* Covariant */) { + related = isRelatedTo(s, t, reportErrors); + } + else if (variance === 2 /* Contravariant */) { + related = isRelatedTo(t, s, reportErrors); + } + else if (variance === 3 /* Bivariant */) { + // In the bivariant case we first compare contravariantly without reporting + // errors. Then, if that doesn't succeed, we compare covariantly with error + // reporting. Thus, error elaboration will be based on the the covariant check, + // which is generally easier to reason about. + related = isRelatedTo(t, s, /*reportErrors*/ false); + if (!related) { + related = isRelatedTo(s, t, reportErrors); + } + } + else { + // In the invariant case we first compare covariantly, and only when that + // succeeds do we proceed to compare contravariantly. Thus, error elaboration + // will typically be based on the covariant check. + related = isRelatedTo(s, t, reportErrors); + if (related) { + related &= isRelatedTo(t, s, reportErrors); + } + } + if (!related) { + return 0 /* False */; + } + result &= related; + } + } + return result; + } + // Determine if possibly recursive types are related. First, check if the result is already available in the global cache. + // Second, check if we have already started a comparison of the given two types in which case we assume the result to be true. + // Third, check if both types are part of deeply nested chains of generic type instantiations and if so assume the types are + // equal and infinitely expanding. Fourth, if we have reached a depth of 100 nested comparisons, assume we have runaway recursion + // and issue an error. Otherwise, actually compare the structure of the two types. + function recursiveTypeRelatedTo(source, target, reportErrors, isIntersectionConstituent) { + if (overflow) { + return 0 /* False */; + } + var id = getRelationKey(source, target, relation); + var related = relation.get(id); + if (related !== undefined) { + if (reportErrors && related === 2 /* Failed */) { + // We are elaborating errors and the cached result is an unreported failure. The result will be reported + // as a failure, and should be updated as a reported failure by the bottom of this function. + } + else { + return related === 1 /* Succeeded */ ? -1 /* True */ : 0 /* False */; + } + } + if (!maybeKeys) { + maybeKeys = []; + sourceStack = []; + targetStack = []; + } + else { + for (var i = 0; i < maybeCount; i++) { + // If source and target are already being compared, consider them related with assumptions + if (id === maybeKeys[i]) { + return 1 /* Maybe */; + } + } + if (depth === 100) { + overflow = true; + return 0 /* False */; + } + } + var maybeStart = maybeCount; + maybeKeys[maybeCount] = id; + maybeCount++; + sourceStack[depth] = source; + targetStack[depth] = target; + depth++; + var saveExpandingFlags = expandingFlags; + if (!(expandingFlags & 1 /* Source */) && isDeeplyNestedType(source, sourceStack, depth)) + expandingFlags |= 1 /* Source */; + if (!(expandingFlags & 2 /* Target */) && isDeeplyNestedType(target, targetStack, depth)) + expandingFlags |= 2 /* Target */; + var result = expandingFlags !== 3 /* Both */ ? structuredTypeRelatedTo(source, target, reportErrors, isIntersectionConstituent) : 1 /* Maybe */; + expandingFlags = saveExpandingFlags; + depth--; + if (result) { + if (result === -1 /* True */ || depth === 0) { + // If result is definitely true, record all maybe keys as having succeeded + for (var i = maybeStart; i < maybeCount; i++) { + relation.set(maybeKeys[i], 1 /* Succeeded */); + } + maybeCount = maybeStart; + } + } + else { + // A false result goes straight into global cache (when something is false under + // assumptions it will also be false without assumptions) + relation.set(id, reportErrors ? 3 /* FailedAndReported */ : 2 /* Failed */); + maybeCount = maybeStart; + } + return result; + } + function getConstraintForRelation(type) { + return relation === definitelyAssignableRelation ? undefined : getConstraintOfType(type); + } + function structuredTypeRelatedTo(source, target, reportErrors, isIntersectionConstituent) { + var flags = source.flags & target.flags; + if (relation === identityRelation && !(flags & 524288 /* Object */)) { + if (flags & 4194304 /* Index */) { + return isRelatedTo(source.type, target.type, /*reportErrors*/ false); + } + var result_2 = 0 /* False */; + if (flags & 8388608 /* IndexedAccess */) { + if (result_2 = isRelatedTo(source.objectType, target.objectType, /*reportErrors*/ false)) { + if (result_2 &= isRelatedTo(source.indexType, target.indexType, /*reportErrors*/ false)) { + return result_2; + } + } + } + if (flags & 16777216 /* Conditional */) { + if (source.root.isDistributive === target.root.isDistributive) { + if (result_2 = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) { + if (result_2 &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) { + if (result_2 &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), /*reportErrors*/ false)) { + if (result_2 &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), /*reportErrors*/ false)) { + return result_2; + } + } + } + } + } + } + if (flags & 33554432 /* Substitution */) { + return isRelatedTo(source.substitute, target.substitute, /*reportErrors*/ false); + } + return 0 /* False */; + } + var result; + var originalErrorInfo; + var saveErrorInfo = errorInfo; + // We limit alias variance probing to only object and conditional types since their alias behavior + // is more predictable than other, interned types, which may or may not have an alias depending on + // the order in which things were checked. + if (source.flags & (524288 /* Object */ | 16777216 /* Conditional */) && source.aliasSymbol && + source.aliasTypeArguments && source.aliasSymbol === target.aliasSymbol && + !(source.aliasTypeArgumentsContainsMarker || target.aliasTypeArgumentsContainsMarker)) { + var variances = getAliasVariances(source.aliasSymbol); + if (result = typeArgumentsRelatedTo(source.aliasTypeArguments, target.aliasTypeArguments, variances, reportErrors)) { + return result; + } + originalErrorInfo = errorInfo; + errorInfo = saveErrorInfo; + } + if (target.flags & 262144 /* TypeParameter */) { + // A source type { [P in Q]: X } is related to a target type T if keyof T is related to Q and X is related to T[Q]. + if (ts.getObjectFlags(source) & 32 /* Mapped */ && isRelatedTo(getIndexType(target), getConstraintTypeFromMappedType(source))) { + if (!(getMappedTypeModifiers(source) & 4 /* IncludeOptional */)) { + var templateType = getTemplateTypeFromMappedType(source); + var indexedAccessType = getIndexedAccessType(target, getTypeParameterFromMappedType(source)); + if (result = isRelatedTo(templateType, indexedAccessType, reportErrors)) { + return result; + } + } + } + } + else if (target.flags & 4194304 /* Index */) { + // A keyof S is related to a keyof T if T is related to S. + if (source.flags & 4194304 /* Index */) { + if (result = isRelatedTo(target.type, source.type, /*reportErrors*/ false)) { + return result; + } + } + // A type S is assignable to keyof T if S is assignable to keyof C, where C is the + // simplified form of T or, if T doesn't simplify, the constraint of T. + if (relation !== definitelyAssignableRelation) { + var simplified = getSimplifiedType(target.type); + var constraint = simplified !== target.type ? simplified : getConstraintOfType(target.type); + if (constraint) { + // We require Ternary.True here such that circular constraints don't cause + // false positives. For example, given 'T extends { [K in keyof T]: string }', + // 'keyof T' has itself as its constraint and produces a Ternary.Maybe when + // related to other types. + if (isRelatedTo(source, getIndexType(constraint, target.stringsOnly), reportErrors) === -1 /* True */) { + return -1 /* True */; + } + } + } + } + else if (target.flags & 8388608 /* IndexedAccess */) { + // A type S is related to a type T[K], where T and K aren't both type variables, if S is related to C, + // where C is the base constraint of T[K] + if (relation !== identityRelation && !(isGenericObjectType(target.objectType) && isGenericIndexType(target.indexType))) { + var constraint = getBaseConstraintOfType(target); + if (constraint && constraint !== target) { + if (result = isRelatedTo(source, constraint, reportErrors)) { + return result; + } + } + } + } + else if (isGenericMappedType(target)) { + // A source type T is related to a target type { [P in X]: T[P] } + var template = getTemplateTypeFromMappedType(target); + var modifiers = getMappedTypeModifiers(target); + if (!(modifiers & 8 /* ExcludeOptional */)) { + if (template.flags & 8388608 /* IndexedAccess */ && template.objectType === source && + template.indexType === getTypeParameterFromMappedType(target)) { + return -1 /* True */; + } + // A source type T is related to a target type { [P in Q]: X } if Q is related to keyof T and T[Q] is related to X. + if (!isGenericMappedType(source) && isRelatedTo(getConstraintTypeFromMappedType(target), getIndexType(source))) { + var indexedAccessType = getIndexedAccessType(source, getTypeParameterFromMappedType(target)); + var templateType = getTemplateTypeFromMappedType(target); + if (result = isRelatedTo(indexedAccessType, templateType, reportErrors)) { + return result; + } + } + originalErrorInfo = errorInfo; + errorInfo = saveErrorInfo; + } + } + if (source.flags & 8650752 /* TypeVariable */) { + if (source.flags & 8388608 /* IndexedAccess */ && target.flags & 8388608 /* IndexedAccess */) { + // A type S[K] is related to a type T[J] if S is related to T and K is related to J. + if (result = isRelatedTo(source.objectType, target.objectType, reportErrors)) { + result &= isRelatedTo(source.indexType, target.indexType, reportErrors); + } + if (result) { + errorInfo = saveErrorInfo; + return result; + } + } + var constraint = getConstraintForRelation(source); + if (!constraint || (source.flags & 262144 /* TypeParameter */ && constraint.flags & 3 /* AnyOrUnknown */)) { + // A type variable with no constraint is not related to the non-primitive object type. + if (result = isRelatedTo(emptyObjectType, extractTypesOfKind(target, ~67108864 /* NonPrimitive */))) { + errorInfo = saveErrorInfo; + return result; + } + } + // hi-speed no-this-instantiation check (less accurate, but avoids costly `this`-instantiation when the constraint will suffice), see #28231 for report on why this is needed + else if (result = isRelatedTo(constraint, target, /*reportErrors*/ false, /*headMessage*/ undefined, isIntersectionConstituent)) { + errorInfo = saveErrorInfo; + return result; + } + // slower, fuller, this-instantiated check (necessary when comparing raw `this` types from base classes), see `subclassWithPolymorphicThisIsAssignable.ts` test for example + else if (result = isRelatedTo(getTypeWithThisArgument(constraint, source), target, reportErrors, /*headMessage*/ undefined, isIntersectionConstituent)) { + errorInfo = saveErrorInfo; + return result; + } + } + else if (source.flags & 4194304 /* Index */) { + if (result = isRelatedTo(keyofConstraintType, target, reportErrors)) { + errorInfo = saveErrorInfo; + return result; + } + } + else if (source.flags & 16777216 /* Conditional */) { + if (target.flags & 16777216 /* Conditional */) { + // Two conditional types 'T1 extends U1 ? X1 : Y1' and 'T2 extends U2 ? X2 : Y2' are related if + // one of T1 and T2 is related to the other, U1 and U2 are identical types, X1 is related to X2, + // and Y1 is related to Y2. + if (isTypeIdenticalTo(source.extendsType, target.extendsType) && + (isRelatedTo(source.checkType, target.checkType) || isRelatedTo(target.checkType, source.checkType))) { + if (result = isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), reportErrors)) { + result &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), reportErrors); + } + if (result) { + errorInfo = saveErrorInfo; + return result; + } + } + } + else if (relation !== definitelyAssignableRelation) { + var distributiveConstraint = getConstraintOfDistributiveConditionalType(source); + if (distributiveConstraint) { + if (result = isRelatedTo(distributiveConstraint, target, reportErrors)) { + errorInfo = saveErrorInfo; + return result; + } + } + var defaultConstraint = getDefaultConstraintOfConditionalType(source); + if (defaultConstraint) { + if (result = isRelatedTo(defaultConstraint, target, reportErrors)) { + errorInfo = saveErrorInfo; + return result; + } + } + } + } + else { + // An empty object type is related to any mapped type that includes a '?' modifier. + if (isPartialMappedType(target) && !isGenericMappedType(source) && isEmptyObjectType(source)) { + return -1 /* True */; + } + if (isGenericMappedType(target)) { + if (isGenericMappedType(source)) { + if (result = mappedTypeRelatedTo(source, target, reportErrors)) { + errorInfo = saveErrorInfo; + return result; + } + } + return 0 /* False */; + } + if (relation === definitelyAssignableRelation && isGenericMappedType(source)) { + return 0 /* False */; + } + var sourceIsPrimitive = !!(source.flags & 131068 /* Primitive */); + if (relation !== identityRelation) { + source = getApparentType(source); + } + if (ts.getObjectFlags(source) & 4 /* Reference */ && ts.getObjectFlags(target) & 4 /* Reference */ && source.target === target.target && + !(ts.getObjectFlags(source) & 8192 /* MarkerType */ || ts.getObjectFlags(target) & 8192 /* MarkerType */)) { + // We have type references to the same generic type, and the type references are not marker + // type references (which are intended by be compared structurally). Obtain the variance + // information for the type parameters and relate the type arguments accordingly. + var variances = getVariances(source.target); + if (result = typeArgumentsRelatedTo(source.typeArguments, target.typeArguments, variances, reportErrors)) { + return result; + } + // The type arguments did not relate appropriately, but it may be because we have no variance + // information (in which case typeArgumentsRelatedTo defaulted to covariance for all type + // arguments). It might also be the case that the target type has a 'void' type argument for + // a covariant type parameter that is only used in return positions within the generic type + // (in which case any type argument is permitted on the source side). In those cases we proceed + // with a structural comparison. Otherwise, we know for certain the instantiations aren't + // related and we can return here. + if (variances !== ts.emptyArray && !hasCovariantVoidArgument(target, variances)) { + // In some cases generic types that are covariant in regular type checking mode become + // invariant in --strictFunctionTypes mode because one or more type parameters are used in + // both co- and contravariant positions. In order to make it easier to diagnose *why* such + // types are invariant, if any of the type parameters are invariant we reset the reported + // errors and instead force a structural comparison (which will include elaborations that + // reveal the reason). + if (!(reportErrors && ts.some(variances, function (v) { return v === 0 /* Invariant */; }))) { + return 0 /* False */; + } + // We remember the original error information so we can restore it in case the structural + // comparison unexpectedly succeeds. This can happen when the structural comparison result + // is a Ternary.Maybe for example caused by the recursion depth limiter. + originalErrorInfo = errorInfo; + errorInfo = saveErrorInfo; + } + } + else if (isTupleType(source) && (isArrayType(target) || isReadonlyArrayType(target)) || isArrayType(source) && isReadonlyArrayType(target)) { + return isRelatedTo(getIndexTypeOfType(source, 1 /* Number */) || anyType, getIndexTypeOfType(target, 1 /* Number */) || anyType, reportErrors); + } + // Even if relationship doesn't hold for unions, intersections, or generic type references, + // it may hold in a structural comparison. + // In a check of the form X = A & B, we will have previously checked if A relates to X or B relates + // to X. Failing both of those we want to check if the aggregation of A and B's members structurally + // relates to X. Thus, we include intersection types on the source side here. + if (source.flags & (524288 /* Object */ | 2097152 /* Intersection */) && target.flags & 524288 /* Object */) { + // Report structural errors only if we haven't reported any errors yet + var reportStructuralErrors = reportErrors && errorInfo === saveErrorInfo && !sourceIsPrimitive; + result = propertiesRelatedTo(source, target, reportStructuralErrors); + if (result) { + result &= signaturesRelatedTo(source, target, 0 /* Call */, reportStructuralErrors); + if (result) { + result &= signaturesRelatedTo(source, target, 1 /* Construct */, reportStructuralErrors); + if (result) { + result &= indexTypesRelatedTo(source, target, 0 /* String */, sourceIsPrimitive, reportStructuralErrors); + if (result) { + result &= indexTypesRelatedTo(source, target, 1 /* Number */, sourceIsPrimitive, reportStructuralErrors); + } + } + } + } + if (result) { + if (!originalErrorInfo) { + errorInfo = saveErrorInfo; + return result; + } + errorInfo = originalErrorInfo; + } + } + } + return 0 /* False */; + } + // A type [P in S]: X is related to a type [Q in T]: Y if T is related to S and X' is + // related to Y, where X' is an instantiation of X in which P is replaced with Q. Notice + // that S and T are contra-variant whereas X and Y are co-variant. + function mappedTypeRelatedTo(source, target, reportErrors) { + var modifiersRelated = relation === comparableRelation || (relation === identityRelation ? getMappedTypeModifiers(source) === getMappedTypeModifiers(target) : + getCombinedMappedTypeOptionality(source) <= getCombinedMappedTypeOptionality(target)); + if (modifiersRelated) { + var result_3; + if (result_3 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) { + var mapper = createTypeMapper([getTypeParameterFromMappedType(source)], [getTypeParameterFromMappedType(target)]); + return result_3 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); + } + } + return 0 /* False */; + } + function propertiesRelatedTo(source, target, reportErrors) { + if (relation === identityRelation) { + return propertiesIdenticalTo(source, target); + } + var requireOptionalProperties = relation === subtypeRelation && !isObjectLiteralType(source) && !isEmptyArrayLiteralType(source) && !isTupleType(source); + var unmatchedProperty = getUnmatchedProperty(source, target, requireOptionalProperties); + if (unmatchedProperty) { + if (reportErrors) { + var props = ts.arrayFrom(getUnmatchedProperties(source, target, requireOptionalProperties)); + if (!headMessage || (headMessage.code !== ts.Diagnostics.Class_0_incorrectly_implements_interface_1.code && + headMessage.code !== ts.Diagnostics.Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass.code)) { + suppressNextError = true; // Retain top-level error for interface implementing issues, otherwise omit it + } + if (props.length === 1) { + var propName = symbolToString(unmatchedProperty); + reportError(ts.Diagnostics.Property_0_is_missing_in_type_1_but_required_in_type_2, propName, typeToString(source), typeToString(target)); + if (ts.length(unmatchedProperty.declarations)) { + associateRelatedInfo(ts.createDiagnosticForNode(unmatchedProperty.declarations[0], ts.Diagnostics._0_is_declared_here, propName)); + } + } + else if (props.length > 5) { // arbitrary cutoff for too-long list form + reportError(ts.Diagnostics.Type_0_is_missing_the_following_properties_from_type_1_Colon_2_and_3_more, typeToString(source), typeToString(target), ts.map(props.slice(0, 4), function (p) { return symbolToString(p); }).join(", "), props.length - 4); + } + else { + reportError(ts.Diagnostics.Type_0_is_missing_the_following_properties_from_type_1_Colon_2, typeToString(source), typeToString(target), ts.map(props, function (p) { return symbolToString(p); }).join(", ")); + } + } + return 0 /* False */; + } + if (isObjectLiteralType(target)) { + for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) { + var sourceProp = _a[_i]; + if (!getPropertyOfObjectType(target, sourceProp.escapedName)) { + var sourceType = getTypeOfSymbol(sourceProp); + if (!(sourceType === undefinedType || sourceType === undefinedWideningType)) { + if (reportErrors) { + reportError(ts.Diagnostics.Property_0_does_not_exist_on_type_1, symbolToString(sourceProp), typeToString(target)); + } + return 0 /* False */; + } + } + } + } + var result = -1 /* True */; + if (isTupleType(target)) { + var targetRestType = getRestTypeOfTupleType(target); + if (targetRestType) { + if (!isTupleType(source)) { + return 0 /* False */; + } + var sourceRestType = getRestTypeOfTupleType(source); + if (sourceRestType && !isRelatedTo(sourceRestType, targetRestType, reportErrors)) { + if (reportErrors) { + reportError(ts.Diagnostics.Rest_signatures_are_incompatible); + } + return 0 /* False */; + } + var targetCount = getTypeReferenceArity(target) - 1; + var sourceCount = getTypeReferenceArity(source) - (sourceRestType ? 1 : 0); + for (var i = targetCount; i < sourceCount; i++) { + var related = isRelatedTo(source.typeArguments[i], targetRestType, reportErrors); + if (!related) { + if (reportErrors) { + reportError(ts.Diagnostics.Property_0_is_incompatible_with_rest_element_type, "" + i); + } + return 0 /* False */; + } + result &= related; + } + } + } + var properties = getPropertiesOfObjectType(target); + for (var _b = 0, properties_2 = properties; _b < properties_2.length; _b++) { + var targetProp = properties_2[_b]; + if (!(targetProp.flags & 4194304 /* Prototype */)) { + var sourceProp = getPropertyOfType(source, targetProp.escapedName); + if (sourceProp && sourceProp !== targetProp) { + if (isIgnoredJsxProperty(source, sourceProp, getTypeOfSymbol(targetProp))) { + continue; + } + var sourcePropFlags = ts.getDeclarationModifierFlagsFromSymbol(sourceProp); + var targetPropFlags = ts.getDeclarationModifierFlagsFromSymbol(targetProp); + if (sourcePropFlags & 8 /* Private */ || targetPropFlags & 8 /* Private */) { + var hasDifferingDeclarations = sourceProp.valueDeclaration !== targetProp.valueDeclaration; + if (ts.getCheckFlags(sourceProp) & 256 /* ContainsPrivate */ && hasDifferingDeclarations) { + if (reportErrors) { + reportError(ts.Diagnostics.Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1, symbolToString(sourceProp), typeToString(source)); + } + return 0 /* False */; + } + if (hasDifferingDeclarations) { + if (reportErrors) { + if (sourcePropFlags & 8 /* Private */ && targetPropFlags & 8 /* Private */) { + reportError(ts.Diagnostics.Types_have_separate_declarations_of_a_private_property_0, symbolToString(targetProp)); + } + else { + reportError(ts.Diagnostics.Property_0_is_private_in_type_1_but_not_in_type_2, symbolToString(targetProp), typeToString(sourcePropFlags & 8 /* Private */ ? source : target), typeToString(sourcePropFlags & 8 /* Private */ ? target : source)); + } + } + return 0 /* False */; + } + } + else if (targetPropFlags & 16 /* Protected */) { + if (!isValidOverrideOf(sourceProp, targetProp)) { + if (reportErrors) { + reportError(ts.Diagnostics.Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2, symbolToString(targetProp), typeToString(getDeclaringClass(sourceProp) || source), typeToString(getDeclaringClass(targetProp) || target)); + } + return 0 /* False */; + } + } + else if (sourcePropFlags & 16 /* Protected */) { + if (reportErrors) { + reportError(ts.Diagnostics.Property_0_is_protected_in_type_1_but_public_in_type_2, symbolToString(targetProp), typeToString(source), typeToString(target)); + } + return 0 /* False */; + } + var related = isRelatedTo(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp), reportErrors); + if (!related) { + if (reportErrors) { + reportError(ts.Diagnostics.Types_of_property_0_are_incompatible, symbolToString(targetProp)); + } + return 0 /* False */; + } + result &= related; + // When checking for comparability, be more lenient with optional properties. + if (relation !== comparableRelation && sourceProp.flags & 16777216 /* Optional */ && !(targetProp.flags & 16777216 /* Optional */)) { + // TypeScript 1.0 spec (April 2014): 3.8.3 + // S is a subtype of a type T, and T is a supertype of S if ... + // S' and T are object types and, for each member M in T.. + // M is a property and S' contains a property N where + // if M is a required property, N is also a required property + // (M - property in T) + // (N - property in S) + if (reportErrors) { + reportError(ts.Diagnostics.Property_0_is_optional_in_type_1_but_required_in_type_2, symbolToString(targetProp), typeToString(source), typeToString(target)); + } + return 0 /* False */; + } + } + } + } + return result; + } + function propertiesIdenticalTo(source, target) { + if (!(source.flags & 524288 /* Object */ && target.flags & 524288 /* Object */)) { + return 0 /* False */; + } + var sourceProperties = getPropertiesOfObjectType(source); + var targetProperties = getPropertiesOfObjectType(target); + if (sourceProperties.length !== targetProperties.length) { + return 0 /* False */; + } + var result = -1 /* True */; + for (var _i = 0, sourceProperties_1 = sourceProperties; _i < sourceProperties_1.length; _i++) { + var sourceProp = sourceProperties_1[_i]; + var targetProp = getPropertyOfObjectType(target, sourceProp.escapedName); + if (!targetProp) { + return 0 /* False */; + } + var related = compareProperties(sourceProp, targetProp, isRelatedTo); + if (!related) { + return 0 /* False */; + } + result &= related; + } + return result; + } + function signaturesRelatedTo(source, target, kind, reportErrors) { + if (relation === identityRelation) { + return signaturesIdenticalTo(source, target, kind); + } + if (target === anyFunctionType || source === anyFunctionType) { + return -1 /* True */; + } + var sourceIsJSConstructor = source.symbol && isJSConstructor(source.symbol.valueDeclaration); + var targetIsJSConstructor = target.symbol && isJSConstructor(target.symbol.valueDeclaration); + var sourceSignatures = getSignaturesOfType(source, (sourceIsJSConstructor && kind === 1 /* Construct */) ? + 0 /* Call */ : kind); + var targetSignatures = getSignaturesOfType(target, (targetIsJSConstructor && kind === 1 /* Construct */) ? + 0 /* Call */ : kind); + if (kind === 1 /* Construct */ && sourceSignatures.length && targetSignatures.length) { + if (ts.isAbstractConstructorType(source) && !ts.isAbstractConstructorType(target)) { + // An abstract constructor type is not assignable to a non-abstract constructor type + // as it would otherwise be possible to new an abstract class. Note that the assignability + // check we perform for an extends clause excludes construct signatures from the target, + // so this check never proceeds. + if (reportErrors) { + reportError(ts.Diagnostics.Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type); + } + return 0 /* False */; + } + if (!constructorVisibilitiesAreCompatible(sourceSignatures[0], targetSignatures[0], reportErrors)) { + return 0 /* False */; + } + } + var result = -1 /* True */; + var saveErrorInfo = errorInfo; + if (ts.getObjectFlags(source) & 64 /* Instantiated */ && ts.getObjectFlags(target) & 64 /* Instantiated */ && source.symbol === target.symbol) { + // We have instantiations of the same anonymous type (which typically will be the type of a + // method). Simply do a pairwise comparison of the signatures in the two signature lists instead + // of the much more expensive N * M comparison matrix we explore below. We erase type parameters + // as they are known to always be the same. + for (var i = 0; i < targetSignatures.length; i++) { + var related = signatureRelatedTo(sourceSignatures[i], targetSignatures[i], /*erase*/ true, reportErrors); + if (!related) { + return 0 /* False */; + } + result &= related; + } + } + else if (sourceSignatures.length === 1 && targetSignatures.length === 1) { + // For simple functions (functions with a single signature) we only erase type parameters for + // the comparable relation. Otherwise, if the source signature is generic, we instantiate it + // in the context of the target signature before checking the relationship. Ideally we'd do + // this regardless of the number of signatures, but the potential costs are prohibitive due + // to the quadratic nature of the logic below. + var eraseGenerics = relation === comparableRelation || !!compilerOptions.noStrictGenericChecks; + result = signatureRelatedTo(sourceSignatures[0], targetSignatures[0], eraseGenerics, reportErrors); + } + else { + outer: for (var _i = 0, targetSignatures_1 = targetSignatures; _i < targetSignatures_1.length; _i++) { + var t = targetSignatures_1[_i]; + // Only elaborate errors from the first failure + var shouldElaborateErrors = reportErrors; + for (var _a = 0, sourceSignatures_1 = sourceSignatures; _a < sourceSignatures_1.length; _a++) { + var s = sourceSignatures_1[_a]; + var related = signatureRelatedTo(s, t, /*erase*/ true, shouldElaborateErrors); + if (related) { + result &= related; + errorInfo = saveErrorInfo; + continue outer; + } + shouldElaborateErrors = false; + } + if (shouldElaborateErrors) { + reportError(ts.Diagnostics.Type_0_provides_no_match_for_the_signature_1, typeToString(source), signatureToString(t, /*enclosingDeclaration*/ undefined, /*flags*/ undefined, kind)); + } + return 0 /* False */; + } + } + return result; + } + /** + * See signatureAssignableTo, compareSignaturesIdentical + */ + function signatureRelatedTo(source, target, erase, reportErrors) { + return compareSignaturesRelated(erase ? getErasedSignature(source) : source, erase ? getErasedSignature(target) : target, 0 /* None */, /*ignoreReturnTypes*/ false, reportErrors, reportError, isRelatedTo); + } + function signaturesIdenticalTo(source, target, kind) { + var sourceSignatures = getSignaturesOfType(source, kind); + var targetSignatures = getSignaturesOfType(target, kind); + if (sourceSignatures.length !== targetSignatures.length) { + return 0 /* False */; + } + var result = -1 /* True */; + for (var i = 0; i < sourceSignatures.length; i++) { + var related = compareSignaturesIdentical(sourceSignatures[i], targetSignatures[i], /*partialMatch*/ false, /*ignoreThisTypes*/ false, /*ignoreReturnTypes*/ false, isRelatedTo); + if (!related) { + return 0 /* False */; + } + result &= related; + } + return result; + } + function eachPropertyRelatedTo(source, target, kind, reportErrors) { + var result = -1 /* True */; + for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) { + var prop = _a[_i]; + if (isIgnoredJsxProperty(source, prop, /*targetMemberType*/ undefined)) { + continue; + } + // Skip over symbol-named members + if (prop.nameType && prop.nameType.flags & 8192 /* UniqueESSymbol */) { + continue; + } + if (kind === 0 /* String */ || isNumericLiteralName(prop.escapedName)) { + var related = isRelatedTo(getTypeOfSymbol(prop), target, reportErrors); + if (!related) { + if (reportErrors) { + reportError(ts.Diagnostics.Property_0_is_incompatible_with_index_signature, symbolToString(prop)); + } + return 0 /* False */; + } + result &= related; + } + } + return result; + } + function indexInfoRelatedTo(sourceInfo, targetInfo, reportErrors) { + var related = isRelatedTo(sourceInfo.type, targetInfo.type, reportErrors); + if (!related && reportErrors) { + reportError(ts.Diagnostics.Index_signatures_are_incompatible); + } + return related; + } + function indexTypesRelatedTo(source, target, kind, sourceIsPrimitive, reportErrors) { + if (relation === identityRelation) { + return indexTypesIdenticalTo(source, target, kind); + } + var targetInfo = getIndexInfoOfType(target, kind); + if (!targetInfo || targetInfo.type.flags & 3 /* AnyOrUnknown */ && !sourceIsPrimitive) { + // Index signature of type any permits assignment from everything but primitives + return -1 /* True */; + } + var sourceInfo = getIndexInfoOfType(source, kind) || + kind === 1 /* Number */ && getIndexInfoOfType(source, 0 /* String */); + if (sourceInfo) { + return indexInfoRelatedTo(sourceInfo, targetInfo, reportErrors); + } + if (isGenericMappedType(source)) { + // A generic mapped type { [P in K]: T } is related to an index signature { [x: string]: U } + // if T is related to U. + return (kind === 0 /* String */ && isRelatedTo(getTemplateTypeFromMappedType(source), targetInfo.type, reportErrors)); // TODO: GH#18217 + } + if (isObjectTypeWithInferableIndex(source)) { + var related = -1 /* True */; + if (kind === 0 /* String */) { + var sourceNumberInfo = getIndexInfoOfType(source, 1 /* Number */); + if (sourceNumberInfo) { + related = indexInfoRelatedTo(sourceNumberInfo, targetInfo, reportErrors); + } + } + if (related) { + related &= eachPropertyRelatedTo(source, targetInfo.type, kind, reportErrors); + } + return related; + } + if (reportErrors) { + reportError(ts.Diagnostics.Index_signature_is_missing_in_type_0, typeToString(source)); + } + return 0 /* False */; + } + function indexTypesIdenticalTo(source, target, indexKind) { + var targetInfo = getIndexInfoOfType(target, indexKind); + var sourceInfo = getIndexInfoOfType(source, indexKind); + if (!sourceInfo && !targetInfo) { + return -1 /* True */; + } + if (sourceInfo && targetInfo && sourceInfo.isReadonly === targetInfo.isReadonly) { + return isRelatedTo(sourceInfo.type, targetInfo.type); + } + return 0 /* False */; + } + function constructorVisibilitiesAreCompatible(sourceSignature, targetSignature, reportErrors) { + if (!sourceSignature.declaration || !targetSignature.declaration) { + return true; + } + var sourceAccessibility = ts.getSelectedModifierFlags(sourceSignature.declaration, 24 /* NonPublicAccessibilityModifier */); + var targetAccessibility = ts.getSelectedModifierFlags(targetSignature.declaration, 24 /* NonPublicAccessibilityModifier */); + // A public, protected and private signature is assignable to a private signature. + if (targetAccessibility === 8 /* Private */) { + return true; + } + // A public and protected signature is assignable to a protected signature. + if (targetAccessibility === 16 /* Protected */ && sourceAccessibility !== 8 /* Private */) { + return true; + } + // Only a public signature is assignable to public signature. + if (targetAccessibility !== 16 /* Protected */ && !sourceAccessibility) { + return true; + } + if (reportErrors) { + reportError(ts.Diagnostics.Cannot_assign_a_0_constructor_type_to_a_1_constructor_type, visibilityToString(sourceAccessibility), visibilityToString(targetAccessibility)); + } + return false; + } + } + function discriminateTypeByDiscriminableItems(target, discriminators, related, defaultValue) { + var match; + for (var _i = 0, discriminators_1 = discriminators; _i < discriminators_1.length; _i++) { + var _a = discriminators_1[_i], getDiscriminatingType = _a[0], propertyName = _a[1]; + for (var _b = 0, _c = target.types; _b < _c.length; _b++) { + var type = _c[_b]; + var targetType = getTypeOfPropertyOfType(type, propertyName); + if (targetType && related(getDiscriminatingType(), targetType)) { + if (match) { + if (type === match) + continue; // Finding multiple fields which discriminate to the same type is fine + return defaultValue; + } + match = type; + } + } + } + return match || defaultValue; + } + /** + * A type is 'weak' if it is an object type with at least one optional property + * and no required properties, call/construct signatures or index signatures + */ + function isWeakType(type) { + if (type.flags & 524288 /* Object */) { + var resolved = resolveStructuredTypeMembers(type); + return resolved.callSignatures.length === 0 && resolved.constructSignatures.length === 0 && + !resolved.stringIndexInfo && !resolved.numberIndexInfo && + resolved.properties.length > 0 && + ts.every(resolved.properties, function (p) { return !!(p.flags & 16777216 /* Optional */); }); + } + if (type.flags & 2097152 /* Intersection */) { + return ts.every(type.types, isWeakType); + } + return false; + } + function hasCommonProperties(source, target, isComparingJsxAttributes) { + for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) { + var prop = _a[_i]; + if (isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { + return true; + } + } + return false; + } + // Return a type reference where the source type parameter is replaced with the target marker + // type, and flag the result as a marker type reference. + function getMarkerTypeReference(type, source, target) { + var result = createTypeReference(type, ts.map(type.typeParameters, function (t) { return t === source ? target : t; })); + result.objectFlags |= 8192 /* MarkerType */; + return result; + } + function getAliasVariances(symbol) { + var links = getSymbolLinks(symbol); + return getVariancesWorker(links.typeParameters, links, function (_links, param, marker) { + var type = getTypeAliasInstantiation(symbol, instantiateTypes(links.typeParameters, makeUnaryTypeMapper(param, marker))); + type.aliasTypeArgumentsContainsMarker = true; + return type; + }); + } + // Return an array containing the variance of each type parameter. The variance is effectively + // a digest of the type comparisons that occur for each type argument when instantiations of the + // generic type are structurally compared. We infer the variance information by comparing + // instantiations of the generic type for type arguments with known relations. The function + // returns the emptyArray singleton if we're not in strictFunctionTypes mode or if the function + // has been invoked recursively for the given generic type. + function getVariancesWorker(typeParameters, cache, createMarkerType) { + if (typeParameters === void 0) { typeParameters = ts.emptyArray; } + var variances = cache.variances; + if (!variances) { + // The emptyArray singleton is used to signal a recursive invocation. + cache.variances = ts.emptyArray; + variances = []; + for (var _i = 0, typeParameters_1 = typeParameters; _i < typeParameters_1.length; _i++) { + var tp = typeParameters_1[_i]; + // We first compare instantiations where the type parameter is replaced with + // marker types that have a known subtype relationship. From this we can infer + // invariance, covariance, contravariance or bivariance. + var typeWithSuper = createMarkerType(cache, tp, markerSuperType); + var typeWithSub = createMarkerType(cache, tp, markerSubType); + var variance = (isTypeAssignableTo(typeWithSub, typeWithSuper) ? 1 /* Covariant */ : 0) | + (isTypeAssignableTo(typeWithSuper, typeWithSub) ? 2 /* Contravariant */ : 0); + // If the instantiations appear to be related bivariantly it may be because the + // type parameter is independent (i.e. it isn't witnessed anywhere in the generic + // type). To determine this we compare instantiations where the type parameter is + // replaced with marker types that are known to be unrelated. + if (variance === 3 /* Bivariant */ && isTypeAssignableTo(createMarkerType(cache, tp, markerOtherType), typeWithSuper)) { + variance = 4 /* Independent */; + } + variances.push(variance); + } + cache.variances = variances; + } + return variances; + } + function getVariances(type) { + if (!strictFunctionTypes) { + return ts.emptyArray; + } + if (type === globalArrayType || type === globalReadonlyArrayType) { + // Arrays are known to be covariant, no need to spend time computing this (emptyArray implies covariance for all parameters) + return ts.emptyArray; + } + return getVariancesWorker(type.typeParameters, type, getMarkerTypeReference); + } + // Return true if the given type reference has a 'void' type argument for a covariant type parameter. + // See comment at call in recursiveTypeRelatedTo for when this case matters. + function hasCovariantVoidArgument(type, variances) { + for (var i = 0; i < variances.length; i++) { + if (variances[i] === 1 /* Covariant */ && type.typeArguments[i].flags & 16384 /* Void */) { + return true; + } + } + return false; + } + function isUnconstrainedTypeParameter(type) { + return type.flags & 262144 /* TypeParameter */ && !getConstraintOfTypeParameter(type); + } + function isTypeReferenceWithGenericArguments(type) { + return !!(ts.getObjectFlags(type) & 4 /* Reference */) && ts.some(type.typeArguments, function (t) { return isUnconstrainedTypeParameter(t) || isTypeReferenceWithGenericArguments(t); }); + } + /** + * getTypeReferenceId(A) returns "111=0-12=1" + * where A.id=111 and number.id=12 + */ + function getTypeReferenceId(type, typeParameters, depth) { + if (depth === void 0) { depth = 0; } + var result = "" + type.target.id; + for (var _i = 0, _a = type.typeArguments; _i < _a.length; _i++) { + var t = _a[_i]; + if (isUnconstrainedTypeParameter(t)) { + var index = typeParameters.indexOf(t); + if (index < 0) { + index = typeParameters.length; + typeParameters.push(t); + } + result += "=" + index; + } + else if (depth < 4 && isTypeReferenceWithGenericArguments(t)) { + result += "<" + getTypeReferenceId(t, typeParameters, depth + 1) + ">"; + } + else { + result += "-" + t.id; + } + } + return result; + } + /** + * To improve caching, the relation key for two generic types uses the target's id plus ids of the type parameters. + * For other cases, the types ids are used. + */ + function getRelationKey(source, target, relation) { + if (relation === identityRelation && source.id > target.id) { + var temp = source; + source = target; + target = temp; + } + if (isTypeReferenceWithGenericArguments(source) && isTypeReferenceWithGenericArguments(target)) { + var typeParameters = []; + return getTypeReferenceId(source, typeParameters) + "," + getTypeReferenceId(target, typeParameters); + } + return source.id + "," + target.id; + } + // Invoke the callback for each underlying property symbol of the given symbol and return the first + // value that isn't undefined. + function forEachProperty(prop, callback) { + if (ts.getCheckFlags(prop) & 6 /* Synthetic */) { + for (var _i = 0, _a = prop.containingType.types; _i < _a.length; _i++) { + var t = _a[_i]; + var p = getPropertyOfType(t, prop.escapedName); + var result = p && forEachProperty(p, callback); + if (result) { + return result; + } + } + return undefined; + } + return callback(prop); + } + // Return the declaring class type of a property or undefined if property not declared in class + function getDeclaringClass(prop) { + return prop.parent && prop.parent.flags & 32 /* Class */ ? getDeclaredTypeOfSymbol(getParentOfSymbol(prop)) : undefined; + } + // Return true if some underlying source property is declared in a class that derives + // from the given base class. + function isPropertyInClassDerivedFrom(prop, baseClass) { + return forEachProperty(prop, function (sp) { + var sourceClass = getDeclaringClass(sp); + return sourceClass ? hasBaseType(sourceClass, baseClass) : false; + }); + } + // Return true if source property is a valid override of protected parts of target property. + function isValidOverrideOf(sourceProp, targetProp) { + return !forEachProperty(targetProp, function (tp) { return ts.getDeclarationModifierFlagsFromSymbol(tp) & 16 /* Protected */ ? + !isPropertyInClassDerivedFrom(sourceProp, getDeclaringClass(tp)) : false; }); + } + // Return true if the given class derives from each of the declaring classes of the protected + // constituents of the given property. + function isClassDerivedFromDeclaringClasses(checkClass, prop) { + return forEachProperty(prop, function (p) { return ts.getDeclarationModifierFlagsFromSymbol(p) & 16 /* Protected */ ? + !hasBaseType(checkClass, getDeclaringClass(p)) : false; }) ? undefined : checkClass; + } + // Return true if the given type is deeply nested. We consider this to be the case when structural type comparisons + // for 5 or more occurrences or instantiations of the type have been recorded on the given stack. It is possible, + // though highly unlikely, for this test to be true in a situation where a chain of instantiations is not infinitely + // expanding. Effectively, we will generate a false positive when two types are structurally equal to at least 5 + // levels, but unequal at some level beyond that. + function isDeeplyNestedType(type, stack, depth) { + // We track all object types that have an associated symbol (representing the origin of the type) + if (depth >= 5 && type.flags & 524288 /* Object */) { + var symbol = type.symbol; + if (symbol) { + var count = 0; + for (var i = 0; i < depth; i++) { + var t = stack[i]; + if (t.flags & 524288 /* Object */ && t.symbol === symbol) { + count++; + if (count >= 5) + return true; + } + } + } + } + return false; + } + function isPropertyIdenticalTo(sourceProp, targetProp) { + return compareProperties(sourceProp, targetProp, compareTypesIdentical) !== 0 /* False */; + } + function compareProperties(sourceProp, targetProp, compareTypes) { + // Two members are considered identical when + // - they are public properties with identical names, optionality, and types, + // - they are private or protected properties originating in the same declaration and having identical types + if (sourceProp === targetProp) { + return -1 /* True */; + } + var sourcePropAccessibility = ts.getDeclarationModifierFlagsFromSymbol(sourceProp) & 24 /* NonPublicAccessibilityModifier */; + var targetPropAccessibility = ts.getDeclarationModifierFlagsFromSymbol(targetProp) & 24 /* NonPublicAccessibilityModifier */; + if (sourcePropAccessibility !== targetPropAccessibility) { + return 0 /* False */; + } + if (sourcePropAccessibility) { + if (getTargetSymbol(sourceProp) !== getTargetSymbol(targetProp)) { + return 0 /* False */; + } + } + else { + if ((sourceProp.flags & 16777216 /* Optional */) !== (targetProp.flags & 16777216 /* Optional */)) { + return 0 /* False */; + } + } + if (isReadonlySymbol(sourceProp) !== isReadonlySymbol(targetProp)) { + return 0 /* False */; + } + return compareTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); + } + function isMatchingSignature(source, target, partialMatch) { + var sourceParameterCount = getParameterCount(source); + var targetParameterCount = getParameterCount(target); + var sourceMinArgumentCount = getMinArgumentCount(source); + var targetMinArgumentCount = getMinArgumentCount(target); + var sourceHasRestParameter = hasEffectiveRestParameter(source); + var targetHasRestParameter = hasEffectiveRestParameter(target); + // A source signature matches a target signature if the two signatures have the same number of required, + // optional, and rest parameters. + if (sourceParameterCount === targetParameterCount && + sourceMinArgumentCount === targetMinArgumentCount && + sourceHasRestParameter === targetHasRestParameter) { + return true; + } + // A source signature partially matches a target signature if the target signature has no fewer required + // parameters + if (partialMatch && sourceMinArgumentCount <= targetMinArgumentCount) { + return true; + } + return false; + } + /** + * See signatureRelatedTo, compareSignaturesIdentical + */ + function compareSignaturesIdentical(source, target, partialMatch, ignoreThisTypes, ignoreReturnTypes, compareTypes) { + // TODO (drosen): De-duplicate code between related functions. + if (source === target) { + return -1 /* True */; + } + if (!(isMatchingSignature(source, target, partialMatch))) { + return 0 /* False */; + } + // Check that the two signatures have the same number of type parameters. We might consider + // also checking that any type parameter constraints match, but that would require instantiating + // the constraints with a common set of type arguments to get relatable entities in places where + // type parameters occur in the constraints. The complexity of doing that doesn't seem worthwhile, + // particularly as we're comparing erased versions of the signatures below. + if (ts.length(source.typeParameters) !== ts.length(target.typeParameters)) { + return 0 /* False */; + } + // Spec 1.0 Section 3.8.3 & 3.8.4: + // M and N (the signatures) are instantiated using type Any as the type argument for all type parameters declared by M and N + source = getErasedSignature(source); + target = getErasedSignature(target); + var result = -1 /* True */; + if (!ignoreThisTypes) { + var sourceThisType = getThisTypeOfSignature(source); + if (sourceThisType) { + var targetThisType = getThisTypeOfSignature(target); + if (targetThisType) { + var related = compareTypes(sourceThisType, targetThisType); + if (!related) { + return 0 /* False */; + } + result &= related; + } + } + } + var targetLen = getParameterCount(target); + for (var i = 0; i < targetLen; i++) { + var s = getTypeAtPosition(source, i); + var t = getTypeAtPosition(target, i); + var related = compareTypes(t, s); + if (!related) { + return 0 /* False */; + } + result &= related; + } + if (!ignoreReturnTypes) { + var sourceTypePredicate = getTypePredicateOfSignature(source); + var targetTypePredicate = getTypePredicateOfSignature(target); + result &= sourceTypePredicate !== undefined || targetTypePredicate !== undefined + ? compareTypePredicatesIdentical(sourceTypePredicate, targetTypePredicate, compareTypes) + // If they're both type predicates their return types will both be `boolean`, so no need to compare those. + : compareTypes(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target)); + } + return result; + } + function compareTypePredicatesIdentical(source, target, compareTypes) { + return source === undefined || target === undefined || !typePredicateKindsMatch(source, target) ? 0 /* False */ : compareTypes(source.type, target.type); + } + function literalTypesWithSameBaseType(types) { + var commonBaseType; + for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { + var t = types_8[_i]; + var baseType = getBaseTypeOfLiteralType(t); + if (!commonBaseType) { + commonBaseType = baseType; + } + if (baseType === t || baseType !== commonBaseType) { + return false; + } + } + return true; + } + // When the candidate types are all literal types with the same base type, return a union + // of those literal types. Otherwise, return the leftmost type for which no type to the + // right is a supertype. + function getSupertypeOrUnion(types) { + return literalTypesWithSameBaseType(types) ? + getUnionType(types) : + ts.reduceLeft(types, function (s, t) { return isTypeSubtypeOf(s, t) ? t : s; }); + } + function getCommonSupertype(types) { + if (!strictNullChecks) { + return getSupertypeOrUnion(types); + } + var primaryTypes = ts.filter(types, function (t) { return !(t.flags & 98304 /* Nullable */); }); + return primaryTypes.length ? + getNullableType(getSupertypeOrUnion(primaryTypes), getFalsyFlagsOfTypes(types) & 98304 /* Nullable */) : + getUnionType(types, 2 /* Subtype */); + } + // Return the leftmost type for which no type to the right is a subtype. + function getCommonSubtype(types) { + return ts.reduceLeft(types, function (s, t) { return isTypeSubtypeOf(t, s) ? t : s; }); + } + function isArrayType(type) { + return !!(ts.getObjectFlags(type) & 4 /* Reference */) && type.target === globalArrayType; + } + function isReadonlyArrayType(type) { + return !!(ts.getObjectFlags(type) & 4 /* Reference */) && type.target === globalReadonlyArrayType; + } + function getElementTypeOfArrayType(type) { + return isArrayType(type) && type.typeArguments ? type.typeArguments[0] : undefined; + } + function isArrayLikeType(type) { + // A type is array-like if it is a reference to the global Array or global ReadonlyArray type, + // or if it is not the undefined or null type and if it is assignable to ReadonlyArray + return ts.getObjectFlags(type) & 4 /* Reference */ && (type.target === globalArrayType || type.target === globalReadonlyArrayType) || + !(type.flags & 98304 /* Nullable */) && isTypeAssignableTo(type, anyReadonlyArrayType); + } + function isEmptyArrayLiteralType(type) { + var elementType = isArrayType(type) ? type.typeArguments[0] : undefined; + return elementType === undefinedWideningType || elementType === implicitNeverType; + } + function isTupleLikeType(type) { + return isTupleType(type) || !!getPropertyOfType(type, "0"); + } + function getTupleElementType(type, index) { + var propType = getTypeOfPropertyOfType(type, "" + index); + if (propType) { + return propType; + } + if (everyType(type, isTupleType) && !everyType(type, function (t) { return !t.target.hasRestElement; })) { + return mapType(type, function (t) { return getRestTypeOfTupleType(t) || undefinedType; }); + } + return undefined; + } + function isNeitherUnitTypeNorNever(type) { + return !(type.flags & (109440 /* Unit */ | 131072 /* Never */)); + } + function isUnitType(type) { + return !!(type.flags & 109440 /* Unit */); + } + function isLiteralType(type) { + return type.flags & 16 /* Boolean */ ? true : + type.flags & 1048576 /* Union */ ? type.flags & 1024 /* EnumLiteral */ ? true : ts.every(type.types, isUnitType) : + isUnitType(type); + } + function getBaseTypeOfLiteralType(type) { + return type.flags & 1024 /* EnumLiteral */ ? getBaseTypeOfEnumLiteralType(type) : + type.flags & 128 /* StringLiteral */ ? stringType : + type.flags & 256 /* NumberLiteral */ ? numberType : + type.flags & 2048 /* BigIntLiteral */ ? bigintType : + type.flags & 512 /* BooleanLiteral */ ? booleanType : + type.flags & 1048576 /* Union */ ? getUnionType(ts.sameMap(type.types, getBaseTypeOfLiteralType)) : + type; + } + function getWidenedLiteralType(type) { + return type.flags & 1024 /* EnumLiteral */ && isFreshLiteralType(type) ? getBaseTypeOfEnumLiteralType(type) : + type.flags & 128 /* StringLiteral */ && isFreshLiteralType(type) ? stringType : + type.flags & 256 /* NumberLiteral */ && isFreshLiteralType(type) ? numberType : + type.flags & 2048 /* BigIntLiteral */ && isFreshLiteralType(type) ? bigintType : + type.flags & 512 /* BooleanLiteral */ && isFreshLiteralType(type) ? booleanType : + type.flags & 1048576 /* Union */ ? getUnionType(ts.sameMap(type.types, getWidenedLiteralType)) : + type; + } + function getWidenedUniqueESSymbolType(type) { + return type.flags & 8192 /* UniqueESSymbol */ ? esSymbolType : + type.flags & 1048576 /* Union */ ? getUnionType(ts.sameMap(type.types, getWidenedUniqueESSymbolType)) : + type; + } + function getWidenedLiteralLikeTypeForContextualType(type, contextualType) { + if (!isLiteralOfContextualType(type, contextualType)) { + type = getWidenedUniqueESSymbolType(getWidenedLiteralType(type)); + } + return type; + } + /** + * Check if a Type was written as a tuple type literal. + * Prefer using isTupleLikeType() unless the use of `elementTypes` is required. + */ + function isTupleType(type) { + return !!(ts.getObjectFlags(type) & 4 /* Reference */ && type.target.objectFlags & 8 /* Tuple */); + } + function getRestTypeOfTupleType(type) { + return type.target.hasRestElement ? type.typeArguments[type.target.typeParameters.length - 1] : undefined; + } + function getRestArrayTypeOfTupleType(type) { + var restType = getRestTypeOfTupleType(type); + return restType && createArrayType(restType); + } + function getLengthOfTupleType(type) { + return getTypeReferenceArity(type) - (type.target.hasRestElement ? 1 : 0); + } + function isZeroBigInt(_a) { + var value = _a.value; + return value.base10Value === "0"; + } + function getFalsyFlagsOfTypes(types) { + var result = 0; + for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { + var t = types_9[_i]; + result |= getFalsyFlags(t); + } + return result; + } + // Returns the String, Number, Boolean, StringLiteral, NumberLiteral, BooleanLiteral, Void, Undefined, or Null + // flags for the string, number, boolean, "", 0, false, void, undefined, or null types respectively. Returns + // no flags for all other types (including non-falsy literal types). + function getFalsyFlags(type) { + return type.flags & 1048576 /* Union */ ? getFalsyFlagsOfTypes(type.types) : + type.flags & 128 /* StringLiteral */ ? type.value === "" ? 128 /* StringLiteral */ : 0 : + type.flags & 256 /* NumberLiteral */ ? type.value === 0 ? 256 /* NumberLiteral */ : 0 : + type.flags & 2048 /* BigIntLiteral */ ? isZeroBigInt(type) ? 2048 /* BigIntLiteral */ : 0 : + type.flags & 512 /* BooleanLiteral */ ? (type === falseType || type === regularFalseType) ? 512 /* BooleanLiteral */ : 0 : + type.flags & 117724 /* PossiblyFalsy */; + } + function removeDefinitelyFalsyTypes(type) { + return getFalsyFlags(type) & 117632 /* DefinitelyFalsy */ ? + filterType(type, function (t) { return !(getFalsyFlags(t) & 117632 /* DefinitelyFalsy */); }) : + type; + } + function extractDefinitelyFalsyTypes(type) { + return mapType(type, getDefinitelyFalsyPartOfType); + } + function getDefinitelyFalsyPartOfType(type) { + return type.flags & 4 /* String */ ? emptyStringType : + type.flags & 8 /* Number */ ? zeroType : + type.flags & 64 /* BigInt */ ? zeroBigIntType : + type === regularFalseType || + type === falseType || + type.flags & (16384 /* Void */ | 32768 /* Undefined */ | 65536 /* Null */) || + type.flags & 128 /* StringLiteral */ && type.value === "" || + type.flags & 256 /* NumberLiteral */ && type.value === 0 || + type.flags & 2048 /* BigIntLiteral */ && isZeroBigInt(type) ? type : + neverType; + } + /** + * Add undefined or null or both to a type if they are missing. + * @param type - type to add undefined and/or null to if not present + * @param flags - Either TypeFlags.Undefined or TypeFlags.Null, or both + */ + function getNullableType(type, flags) { + var missing = (flags & ~type.flags) & (32768 /* Undefined */ | 65536 /* Null */); + return missing === 0 ? type : + missing === 32768 /* Undefined */ ? getUnionType([type, undefinedType]) : + missing === 65536 /* Null */ ? getUnionType([type, nullType]) : + getUnionType([type, undefinedType, nullType]); + } + function getOptionalType(type) { + ts.Debug.assert(strictNullChecks); + return type.flags & 32768 /* Undefined */ ? type : getUnionType([type, undefinedType]); + } + function getGlobalNonNullableTypeInstantiation(type) { + if (!deferredGlobalNonNullableTypeAlias) { + deferredGlobalNonNullableTypeAlias = getGlobalSymbol("NonNullable", 524288 /* TypeAlias */, /*diagnostic*/ undefined) || unknownSymbol; + } + // Use NonNullable global type alias if available to improve quick info/declaration emit + if (deferredGlobalNonNullableTypeAlias !== unknownSymbol) { + return getTypeAliasInstantiation(deferredGlobalNonNullableTypeAlias, [type]); + } + return getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */); // Type alias unavailable, fall back to non-higher-order behavior + } + function getNonNullableType(type) { + return strictNullChecks ? getGlobalNonNullableTypeInstantiation(type) : type; + } + /** + * Return true if type was inferred from an object literal, written as an object type literal, or is the shape of a module + * with no call or construct signatures. + */ + function isObjectTypeWithInferableIndex(type) { + return type.symbol && (type.symbol.flags & (4096 /* ObjectLiteral */ | 2048 /* TypeLiteral */ | 512 /* ValueModule */)) !== 0 && + !typeHasCallOrConstructSignatures(type); + } + function createSymbolWithType(source, type) { + var symbol = createSymbol(source.flags, source.escapedName); + symbol.declarations = source.declarations; + symbol.parent = source.parent; + symbol.type = type; + symbol.target = source; + if (source.valueDeclaration) { + symbol.valueDeclaration = source.valueDeclaration; + } + if (source.nameType) { + symbol.nameType = source.nameType; + } + return symbol; + } + function transformTypeOfMembers(type, f) { + var members = ts.createSymbolTable(); + for (var _i = 0, _a = getPropertiesOfObjectType(type); _i < _a.length; _i++) { + var property = _a[_i]; + var original = getTypeOfSymbol(property); + var updated = f(original); + members.set(property.escapedName, updated === original ? property : createSymbolWithType(property, updated)); + } + return members; + } + /** + * If the the provided object literal is subject to the excess properties check, + * create a new that is exempt. Recursively mark object literal members as exempt. + * Leave signatures alone since they are not subject to the check. + */ + function getRegularTypeOfObjectLiteral(type) { + if (!(isObjectLiteralType(type) && ts.getObjectFlags(type) & 32768 /* FreshLiteral */)) { + return type; + } + var regularType = type.regularType; + if (regularType) { + return regularType; + } + var resolved = type; + var members = transformTypeOfMembers(type, getRegularTypeOfObjectLiteral); + var regularNew = createAnonymousType(resolved.symbol, members, resolved.callSignatures, resolved.constructSignatures, resolved.stringIndexInfo, resolved.numberIndexInfo); + regularNew.flags = resolved.flags; + regularNew.objectFlags |= 128 /* ObjectLiteral */ | (ts.getObjectFlags(resolved) & 16384 /* JSLiteral */); + type.regularType = regularNew; + return regularNew; + } + function createWideningContext(parent, propertyName, siblings) { + return { parent: parent, propertyName: propertyName, siblings: siblings, resolvedProperties: undefined }; + } + function getSiblingsOfContext(context) { + if (!context.siblings) { + var siblings_1 = []; + for (var _i = 0, _a = getSiblingsOfContext(context.parent); _i < _a.length; _i++) { + var type = _a[_i]; + if (isObjectLiteralType(type)) { + var prop = getPropertyOfObjectType(type, context.propertyName); + if (prop) { + forEachType(getTypeOfSymbol(prop), function (t) { + siblings_1.push(t); + }); + } + } + } + context.siblings = siblings_1; + } + return context.siblings; + } + function getPropertiesOfContext(context) { + if (!context.resolvedProperties) { + var names = ts.createMap(); + for (var _i = 0, _a = getSiblingsOfContext(context); _i < _a.length; _i++) { + var t = _a[_i]; + if (isObjectLiteralType(t) && !(ts.getObjectFlags(t) & 1024 /* ContainsSpread */)) { + for (var _b = 0, _c = getPropertiesOfType(t); _b < _c.length; _b++) { + var prop = _c[_b]; + names.set(prop.escapedName, prop); + } + } + } + context.resolvedProperties = ts.arrayFrom(names.values()); + } + return context.resolvedProperties; + } + function getWidenedProperty(prop, context) { + if (!(prop.flags & 4 /* Property */)) { + // Since get accessors already widen their return value there is no need to + // widen accessor based properties here. + return prop; + } + var original = getTypeOfSymbol(prop); + var propContext = context && createWideningContext(context, prop.escapedName, /*siblings*/ undefined); + var widened = getWidenedTypeWithContext(original, propContext); + return widened === original ? prop : createSymbolWithType(prop, widened); + } + function getUndefinedProperty(prop) { + var cached = undefinedProperties.get(prop.escapedName); + if (cached) { + return cached; + } + var result = createSymbolWithType(prop, undefinedType); + result.flags |= 16777216 /* Optional */; + undefinedProperties.set(prop.escapedName, result); + return result; + } + function getWidenedTypeOfObjectLiteral(type, context) { + var members = ts.createSymbolTable(); + for (var _i = 0, _a = getPropertiesOfObjectType(type); _i < _a.length; _i++) { + var prop = _a[_i]; + members.set(prop.escapedName, getWidenedProperty(prop, context)); + } + if (context) { + for (var _b = 0, _c = getPropertiesOfContext(context); _b < _c.length; _b++) { + var prop = _c[_b]; + if (!members.has(prop.escapedName)) { + members.set(prop.escapedName, getUndefinedProperty(prop)); + } + } + } + var stringIndexInfo = getIndexInfoOfType(type, 0 /* String */); + var numberIndexInfo = getIndexInfoOfType(type, 1 /* Number */); + var result = createAnonymousType(type.symbol, members, ts.emptyArray, ts.emptyArray, stringIndexInfo && createIndexInfo(getWidenedType(stringIndexInfo.type), stringIndexInfo.isReadonly), numberIndexInfo && createIndexInfo(getWidenedType(numberIndexInfo.type), numberIndexInfo.isReadonly)); + result.objectFlags |= (ts.getObjectFlags(type) & 16384 /* JSLiteral */); // Retain js literal flag through widening + return result; + } + function getWidenedType(type) { + return getWidenedTypeWithContext(type, /*context*/ undefined); + } + function getWidenedTypeWithContext(type, context) { + if (type.flags & 402653184 /* RequiresWidening */) { + if (type.flags & 98304 /* Nullable */) { + return anyType; + } + if (isObjectLiteralType(type)) { + return getWidenedTypeOfObjectLiteral(type, context); + } + if (type.flags & 1048576 /* Union */) { + var unionContext_1 = context || createWideningContext(/*parent*/ undefined, /*propertyName*/ undefined, type.types); + var widenedTypes = ts.sameMap(type.types, function (t) { return t.flags & 98304 /* Nullable */ ? t : getWidenedTypeWithContext(t, unionContext_1); }); + // Widening an empty object literal transitions from a highly restrictive type to + // a highly inclusive one. For that reason we perform subtype reduction here if the + // union includes empty object types (e.g. reducing {} | string to just {}). + return getUnionType(widenedTypes, ts.some(widenedTypes, isEmptyObjectType) ? 2 /* Subtype */ : 1 /* Literal */); + } + if (isArrayType(type) || isTupleType(type)) { + return createTypeReference(type.target, ts.sameMap(type.typeArguments, getWidenedType)); + } + } + return type; + } + /** + * Reports implicit any errors that occur as a result of widening 'null' and 'undefined' + * to 'any'. A call to reportWideningErrorsInType is normally accompanied by a call to + * getWidenedType. But in some cases getWidenedType is called without reporting errors + * (type argument inference is an example). + * + * The return value indicates whether an error was in fact reported. The particular circumstances + * are on a best effort basis. Currently, if the null or undefined that causes widening is inside + * an object literal property (arbitrarily deeply), this function reports an error. If no error is + * reported, reportImplicitAnyError is a suitable fallback to report a general error. + */ + function reportWideningErrorsInType(type) { + var errorReported = false; + if (type.flags & 134217728 /* ContainsWideningType */) { + if (type.flags & 1048576 /* Union */) { + if (ts.some(type.types, isEmptyObjectType)) { + errorReported = true; + } + else { + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (reportWideningErrorsInType(t)) { + errorReported = true; + } + } + } + } + if (isArrayType(type) || isTupleType(type)) { + for (var _b = 0, _c = type.typeArguments; _b < _c.length; _b++) { + var t = _c[_b]; + if (reportWideningErrorsInType(t)) { + errorReported = true; + } + } + } + if (isObjectLiteralType(type)) { + for (var _d = 0, _e = getPropertiesOfObjectType(type); _d < _e.length; _d++) { + var p = _e[_d]; + var t = getTypeOfSymbol(p); + if (t.flags & 134217728 /* ContainsWideningType */) { + if (!reportWideningErrorsInType(t)) { + error(p.valueDeclaration, ts.Diagnostics.Object_literal_s_property_0_implicitly_has_an_1_type, symbolToString(p), typeToString(getWidenedType(t))); + } + errorReported = true; + } + } + } + } + return errorReported; + } + function reportImplicitAny(declaration, type) { + var typeAsString = typeToString(getWidenedType(type)); + if (ts.isInJSFile(declaration) && !ts.isCheckJsEnabledForFile(ts.getSourceFileOfNode(declaration), compilerOptions)) { + // Only report implicit any errors/suggestions in TS and ts-check JS files + return; + } + var diagnostic; + switch (declaration.kind) { + case 204 /* BinaryExpression */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + diagnostic = noImplicitAny ? ts.Diagnostics.Member_0_implicitly_has_an_1_type : ts.Diagnostics.Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage; + break; + case 151 /* Parameter */: + var param = declaration; + if (ts.isIdentifier(param.name) && + (ts.isCallSignatureDeclaration(param.parent) || ts.isMethodSignature(param.parent) || ts.isFunctionTypeNode(param.parent)) && + param.parent.parameters.indexOf(param) > -1 && + (resolveName(param, param.name.escapedText, 67897832 /* Type */, undefined, param.name.escapedText, /*isUse*/ true) || + param.name.originalKeywordKind && ts.isTypeNodeKind(param.name.originalKeywordKind))) { + var newName = "arg" + param.parent.parameters.indexOf(param); + errorOrSuggestion(noImplicitAny, declaration, ts.Diagnostics.Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1, newName, ts.declarationNameToString(param.name)); + return; + } + diagnostic = declaration.dotDotDotToken ? + noImplicitAny ? ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type : ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage : + noImplicitAny ? ts.Diagnostics.Parameter_0_implicitly_has_an_1_type : ts.Diagnostics.Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage; + break; + case 186 /* BindingElement */: + diagnostic = ts.Diagnostics.Binding_element_0_implicitly_has_an_1_type; + break; + case 289 /* JSDocFunctionType */: + error(declaration, ts.Diagnostics.Function_type_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString); + return; + case 239 /* FunctionDeclaration */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + if (noImplicitAny && !declaration.name) { + error(declaration, ts.Diagnostics.Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString); + return; + } + diagnostic = noImplicitAny ? ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type : ts.Diagnostics._0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage; + break; + case 181 /* MappedType */: + if (noImplicitAny) { + error(declaration, ts.Diagnostics.Mapped_object_type_implicitly_has_an_any_template_type); + } + return; + default: + diagnostic = noImplicitAny ? ts.Diagnostics.Variable_0_implicitly_has_an_1_type : ts.Diagnostics.Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage; + } + errorOrSuggestion(noImplicitAny, declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString); + } + function reportErrorsFromWidening(declaration, type) { + if (produceDiagnostics && noImplicitAny && type.flags & 134217728 /* ContainsWideningType */) { + // Report implicit any error within type if possible, otherwise report error on declaration + if (!reportWideningErrorsInType(type)) { + reportImplicitAny(declaration, type); + } + } + } + function forEachMatchingParameterType(source, target, callback) { + var sourceCount = getParameterCount(source); + var targetCount = getParameterCount(target); + var sourceRestType = getEffectiveRestType(source); + var targetRestType = getEffectiveRestType(target); + var targetNonRestCount = targetRestType ? targetCount - 1 : targetCount; + var paramCount = sourceRestType ? targetNonRestCount : Math.min(sourceCount, targetNonRestCount); + var sourceThisType = getThisTypeOfSignature(source); + if (sourceThisType) { + var targetThisType = getThisTypeOfSignature(target); + if (targetThisType) { + callback(sourceThisType, targetThisType); + } + } + for (var i = 0; i < paramCount; i++) { + callback(getTypeAtPosition(source, i), getTypeAtPosition(target, i)); + } + if (targetRestType) { + callback(getRestTypeAtPosition(source, paramCount), targetRestType); + } + } + function createInferenceContext(typeParameters, signature, flags, compareTypes, baseInferences) { + var inferences = baseInferences ? baseInferences.map(cloneInferenceInfo) : typeParameters.map(createInferenceInfo); + var context = mapper; + context.typeParameters = typeParameters; + context.signature = signature; + context.inferences = inferences; + context.flags = flags; + context.compareTypes = compareTypes || compareTypesAssignable; + return context; + function mapper(t) { + for (var i = 0; i < inferences.length; i++) { + if (t === inferences[i].typeParameter) { + inferences[i].isFixed = true; + return getInferredType(context, i); + } + } + return t; + } + } + function createInferenceInfo(typeParameter) { + return { + typeParameter: typeParameter, + candidates: undefined, + contraCandidates: undefined, + inferredType: undefined, + priority: undefined, + topLevel: true, + isFixed: false + }; + } + function cloneInferenceInfo(inference) { + return { + typeParameter: inference.typeParameter, + candidates: inference.candidates && inference.candidates.slice(), + contraCandidates: inference.contraCandidates && inference.contraCandidates.slice(), + inferredType: inference.inferredType, + priority: inference.priority, + topLevel: inference.topLevel, + isFixed: inference.isFixed + }; + } + // Return true if the given type could possibly reference a type parameter for which + // we perform type inference (i.e. a type parameter of a generic function). We cache + // results for union and intersection types for performance reasons. + function couldContainTypeVariables(type) { + var objectFlags = ts.getObjectFlags(type); + return !!(type.flags & 63176704 /* Instantiable */ || + objectFlags & 4 /* Reference */ && ts.forEach(type.typeArguments, couldContainTypeVariables) || + objectFlags & 16 /* Anonymous */ && type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 2048 /* TypeLiteral */ | 32 /* Class */) || + objectFlags & 32 /* Mapped */ || + type.flags & 3145728 /* UnionOrIntersection */ && couldUnionOrIntersectionContainTypeVariables(type)); + } + function couldUnionOrIntersectionContainTypeVariables(type) { + if (type.couldContainTypeVariables === undefined) { + type.couldContainTypeVariables = ts.some(type.types, couldContainTypeVariables); + } + return type.couldContainTypeVariables; + } + function isTypeParameterAtTopLevel(type, typeParameter) { + return type === typeParameter || !!(type.flags & 3145728 /* UnionOrIntersection */) && ts.some(type.types, function (t) { return isTypeParameterAtTopLevel(t, typeParameter); }); + } + /** Create an object with properties named in the string literal type. Every property has type `any` */ + function createEmptyObjectTypeFromStringLiteral(type) { + var members = ts.createSymbolTable(); + forEachType(type, function (t) { + if (!(t.flags & 128 /* StringLiteral */)) { + return; + } + var name = ts.escapeLeadingUnderscores(t.value); + var literalProp = createSymbol(4 /* Property */, name); + literalProp.type = anyType; + if (t.symbol) { + literalProp.declarations = t.symbol.declarations; + literalProp.valueDeclaration = t.symbol.valueDeclaration; + } + members.set(name, literalProp); + }); + var indexInfo = type.flags & 4 /* String */ ? createIndexInfo(emptyObjectType, /*isReadonly*/ false) : undefined; + return createAnonymousType(undefined, members, ts.emptyArray, ts.emptyArray, indexInfo, undefined); + } + /** + * Infer a suitable input type for a homomorphic mapped type { [P in keyof T]: X }. We construct + * an object type with the same set of properties as the source type, where the type of each + * property is computed by inferring from the source property type to X for the type + * variable T[P] (i.e. we treat the type T[P] as the type variable we're inferring for). + */ + function inferTypeForHomomorphicMappedType(source, target, constraint) { + var key = source.id + "," + target.id + "," + constraint.id; + if (reverseMappedCache.has(key)) { + return reverseMappedCache.get(key); + } + reverseMappedCache.set(key, undefined); + var type = createReverseMappedType(source, target, constraint); + reverseMappedCache.set(key, type); + return type; + } + function createReverseMappedType(source, target, constraint) { + var properties = getPropertiesOfType(source); + if (properties.length === 0 && !getIndexInfoOfType(source, 0 /* String */)) { + return undefined; + } + // If any property contains context sensitive functions that have been skipped, the source type + // is incomplete and we can't infer a meaningful input type. + for (var _i = 0, properties_3 = properties; _i < properties_3.length; _i++) { + var prop = properties_3[_i]; + if (getTypeOfSymbol(prop).flags & 536870912 /* ContainsAnyFunctionType */) { + return undefined; + } + } + // For arrays and tuples we infer new arrays and tuples where the reverse mapping has been + // applied to the element type(s). + if (isArrayType(source)) { + return createArrayType(inferReverseMappedType(source.typeArguments[0], target, constraint)); + } + if (isReadonlyArrayType(source)) { + return createReadonlyArrayType(inferReverseMappedType(source.typeArguments[0], target, constraint)); + } + if (isTupleType(source)) { + var elementTypes = ts.map(source.typeArguments || ts.emptyArray, function (t) { return inferReverseMappedType(t, target, constraint); }); + var minLength = getMappedTypeModifiers(target) & 4 /* IncludeOptional */ ? + getTypeReferenceArity(source) - (source.target.hasRestElement ? 1 : 0) : source.target.minLength; + return createTupleType(elementTypes, minLength, source.target.hasRestElement, source.target.associatedNames); + } + // For all other object types we infer a new object type where the reverse mapping has been + // applied to the type of each property. + var reversed = createObjectType(2048 /* ReverseMapped */ | 16 /* Anonymous */, /*symbol*/ undefined); + reversed.source = source; + reversed.mappedType = target; + reversed.constraintType = constraint; + return reversed; + } + function getTypeOfReverseMappedSymbol(symbol) { + return inferReverseMappedType(symbol.propertyType, symbol.mappedType, symbol.constraintType); + } + function inferReverseMappedType(sourceType, target, constraint) { + var typeParameter = getIndexedAccessType(constraint.type, getTypeParameterFromMappedType(target)); + var templateType = getTemplateTypeFromMappedType(target); + var inference = createInferenceInfo(typeParameter); + inferTypes([inference], sourceType, templateType); + return getTypeFromInference(inference); + } + function getUnmatchedProperties(source, target, requireOptionalProperties) { + var properties, _i, properties_4, targetProp, sourceProp; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + properties = target.flags & 2097152 /* Intersection */ ? getPropertiesOfUnionOrIntersectionType(target) : getPropertiesOfObjectType(target); + _i = 0, properties_4 = properties; + _a.label = 1; + case 1: + if (!(_i < properties_4.length)) return [3 /*break*/, 4]; + targetProp = properties_4[_i]; + if (!(requireOptionalProperties || !(targetProp.flags & 16777216 /* Optional */))) return [3 /*break*/, 3]; + sourceProp = getPropertyOfType(source, targetProp.escapedName); + if (!!sourceProp) return [3 /*break*/, 3]; + return [4 /*yield*/, targetProp]; + case 2: + _a.sent(); + _a.label = 3; + case 3: + _i++; + return [3 /*break*/, 1]; + case 4: return [2 /*return*/]; + } + }); + } + function getUnmatchedProperty(source, target, requireOptionalProperties) { + return getUnmatchedProperties(source, target, requireOptionalProperties).next().value; + } + function tupleTypesDefinitelyUnrelated(source, target) { + return target.target.minLength > source.target.minLength || + !getRestTypeOfTupleType(target) && (!!getRestTypeOfTupleType(source) || getLengthOfTupleType(target) < getLengthOfTupleType(source)); + } + function typesDefinitelyUnrelated(source, target) { + // Two tuple types with incompatible arities are definitely unrelated. + // Two object types that each have a property that is unmatched in the other are definitely unrelated. + return isTupleType(source) && isTupleType(target) && tupleTypesDefinitelyUnrelated(source, target) || + !!getUnmatchedProperty(source, target, /*requireOptionalProperties*/ false) && !!getUnmatchedProperty(target, source, /*requireOptionalProperties*/ false); + } + function getTypeFromInference(inference) { + return inference.candidates ? getUnionType(inference.candidates, 2 /* Subtype */) : + inference.contraCandidates ? getIntersectionType(inference.contraCandidates) : + emptyObjectType; + } + function inferTypes(inferences, originalSource, originalTarget, priority) { + if (priority === void 0) { priority = 0; } + var symbolStack; + var visited; + var contravariant = false; + var bivariant = false; + var propagationType; + var allowComplexConstraintInference = true; + inferFromTypes(originalSource, originalTarget); + function inferFromTypes(source, target) { + if (!couldContainTypeVariables(target)) { + return; + } + if (source === wildcardType) { + // We are inferring from an 'any' type. We want to infer this type for every type parameter + // referenced in the target type, so we record it as the propagation type and infer from the + // target to itself. Then, as we find candidates we substitute the propagation type. + var savePropagationType = propagationType; + propagationType = source; + inferFromTypes(target, target); + propagationType = savePropagationType; + return; + } + if (source.aliasSymbol && source.aliasTypeArguments && source.aliasSymbol === target.aliasSymbol) { + // Source and target are types originating in the same generic type alias declaration. + // Simply infer from source type arguments to target type arguments. + var sourceTypes = source.aliasTypeArguments; + var targetTypes = target.aliasTypeArguments; + for (var i = 0; i < sourceTypes.length; i++) { + inferFromTypes(sourceTypes[i], targetTypes[i]); + } + return; + } + if (source.flags & 1048576 /* Union */ && target.flags & 1048576 /* Union */ && !(source.flags & 1024 /* EnumLiteral */ && target.flags & 1024 /* EnumLiteral */) || + source.flags & 2097152 /* Intersection */ && target.flags & 2097152 /* Intersection */) { + // Source and target are both unions or both intersections. If source and target + // are the same type, just relate each constituent type to itself. + if (source === target) { + for (var _i = 0, _a = source.types; _i < _a.length; _i++) { + var t = _a[_i]; + inferFromTypes(t, t); + } + return; + } + // Find each source constituent type that has an identically matching target constituent + // type, and for each such type infer from the type to itself. When inferring from a + // type to itself we effectively find all type parameter occurrences within that type + // and infer themselves as their type arguments. We have special handling for numeric + // and string literals because the number and string types are not represented as unions + // of all their possible values. + var matchingTypes = void 0; + for (var _b = 0, _c = source.types; _b < _c.length; _b++) { + var t = _c[_b]; + if (typeIdenticalToSomeType(t, target.types)) { + (matchingTypes || (matchingTypes = [])).push(t); + inferFromTypes(t, t); + } + else if (t.flags & (256 /* NumberLiteral */ | 128 /* StringLiteral */)) { + var b = getBaseTypeOfLiteralType(t); + if (typeIdenticalToSomeType(b, target.types)) { + (matchingTypes || (matchingTypes = [])).push(t, b); + } + } + } + // Next, to improve the quality of inferences, reduce the source and target types by + // removing the identically matched constituents. For example, when inferring from + // 'string | string[]' to 'string | T' we reduce the types to 'string[]' and 'T'. + if (matchingTypes) { + source = removeTypesFromUnionOrIntersection(source, matchingTypes); + target = removeTypesFromUnionOrIntersection(target, matchingTypes); + } + } + if (target.flags & 8650752 /* TypeVariable */) { + // If target is a type parameter, make an inference, unless the source type contains + // the anyFunctionType (the wildcard type that's used to avoid contextually typing functions). + // Because the anyFunctionType is internal, it should not be exposed to the user by adding + // it as an inference candidate. Hopefully, a better candidate will come along that does + // not contain anyFunctionType when we come back to this argument for its second round + // of inference. Also, we exclude inferences for silentNeverType (which is used as a wildcard + // when constructing types from type parameters that had no inference candidates). + if (source.flags & 536870912 /* ContainsAnyFunctionType */ || source === silentNeverType || (priority & 8 /* ReturnType */ && (source === autoType || source === autoArrayType))) { + return; + } + var inference = getInferenceInfoForType(target); + if (inference) { + if (!inference.isFixed) { + if (inference.priority === undefined || priority < inference.priority) { + inference.candidates = undefined; + inference.contraCandidates = undefined; + inference.priority = priority; + } + if (priority === inference.priority) { + var candidate = propagationType || source; + // We make contravariant inferences only if we are in a pure contravariant position, + // i.e. only if we have not descended into a bivariant position. + if (contravariant && !bivariant) { + inference.contraCandidates = ts.appendIfUnique(inference.contraCandidates, candidate); + } + else { + inference.candidates = ts.appendIfUnique(inference.candidates, candidate); + } + } + if (!(priority & 8 /* ReturnType */) && target.flags & 262144 /* TypeParameter */ && !isTypeParameterAtTopLevel(originalTarget, target)) { + inference.topLevel = false; + } + } + return; + } + else { + // Infer to the simplified version of an indexed access, if possible, to (hopefully) expose more bare type parameters to the inference engine + var simplified = getSimplifiedType(target); + if (simplified !== target) { + inferFromTypesOnce(source, simplified); + } + else if (target.flags & 8388608 /* IndexedAccess */) { + var indexType = getSimplifiedType(target.indexType); + // Generally simplifications of instantiable indexes are avoided to keep relationship checking correct, however if our target is an access, we can consider + // that key of that access to be "instantiated", since we're looking to find the infernce goal in any way we can. + if (indexType.flags & 63176704 /* Instantiable */) { + var simplified_1 = distributeIndexOverObjectType(getSimplifiedType(target.objectType), indexType); + if (simplified_1 && simplified_1 !== target) { + inferFromTypesOnce(source, simplified_1); + } + } + } + } + } + if (ts.getObjectFlags(source) & 4 /* Reference */ && ts.getObjectFlags(target) & 4 /* Reference */ && source.target === target.target) { + // If source and target are references to the same generic type, infer from type arguments + var sourceTypes = source.typeArguments || ts.emptyArray; + var targetTypes = target.typeArguments || ts.emptyArray; + var count = sourceTypes.length < targetTypes.length ? sourceTypes.length : targetTypes.length; + var variances = getVariances(source.target); + for (var i = 0; i < count; i++) { + if (i < variances.length && variances[i] === 2 /* Contravariant */) { + inferFromContravariantTypes(sourceTypes[i], targetTypes[i]); + } + else { + inferFromTypes(sourceTypes[i], targetTypes[i]); + } + } + } + else if (source.flags & 4194304 /* Index */ && target.flags & 4194304 /* Index */) { + contravariant = !contravariant; + inferFromTypes(source.type, target.type); + contravariant = !contravariant; + } + else if ((isLiteralType(source) || source.flags & 4 /* String */) && target.flags & 4194304 /* Index */) { + var empty = createEmptyObjectTypeFromStringLiteral(source); + contravariant = !contravariant; + var savePriority = priority; + priority |= 16 /* LiteralKeyof */; + inferFromTypes(empty, target.type); + priority = savePriority; + contravariant = !contravariant; + } + else if (source.flags & 8388608 /* IndexedAccess */ && target.flags & 8388608 /* IndexedAccess */) { + inferFromTypes(source.objectType, target.objectType); + inferFromTypes(source.indexType, target.indexType); + } + else if (source.flags & 16777216 /* Conditional */ && target.flags & 16777216 /* Conditional */) { + inferFromTypes(source.checkType, target.checkType); + inferFromTypes(source.extendsType, target.extendsType); + inferFromTypes(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target)); + inferFromTypes(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target)); + } + else if (target.flags & 16777216 /* Conditional */) { + inferFromTypes(source, getUnionType([getTrueTypeFromConditionalType(target), getFalseTypeFromConditionalType(target)])); + } + else if (target.flags & 3145728 /* UnionOrIntersection */) { + var targetTypes = target.types; + var typeVariableCount = 0; + var typeVariable = void 0; + // First infer to each type in union or intersection that isn't a type variable + for (var _d = 0, targetTypes_3 = targetTypes; _d < targetTypes_3.length; _d++) { + var t = targetTypes_3[_d]; + if (getInferenceInfoForType(t)) { + typeVariable = t; + typeVariableCount++; + } + else { + inferFromTypes(source, t); + } + } + // Next, if target containings a single naked type variable, make a secondary inference to that type + // variable. This gives meaningful results for union types in co-variant positions and intersection + // types in contra-variant positions (such as callback parameters). + if (typeVariableCount === 1) { + var savePriority = priority; + priority |= 1 /* NakedTypeVariable */; + inferFromTypes(source, typeVariable); + priority = savePriority; + } + } + else if (source.flags & 1048576 /* Union */) { + // Source is a union or intersection type, infer from each constituent type + var sourceTypes = source.types; + for (var _e = 0, sourceTypes_3 = sourceTypes; _e < sourceTypes_3.length; _e++) { + var sourceType = sourceTypes_3[_e]; + inferFromTypes(sourceType, target); + } + } + else { + if (!(priority & 32 /* NoConstraints */ && source.flags & (2097152 /* Intersection */ | 63176704 /* Instantiable */))) { + var apparentSource = getApparentType(source); + // getApparentType can return _any_ type, since an indexed access or conditional may simplify to any other type. + // If that occurs and it doesn't simplify to an object or intersection, we'll need to restart `inferFromTypes` + // with the simplified source. + if (apparentSource !== source && allowComplexConstraintInference && !(apparentSource.flags & (524288 /* Object */ | 2097152 /* Intersection */))) { + // TODO: The `allowComplexConstraintInference` flag is a hack! This forbids inference from complex constraints within constraints! + // This isn't required algorithmically, but rather is used to lower the memory burden caused by performing inference + // that is _too good_ in projects with complicated constraints (eg, fp-ts). In such cases, if we did not limit ourselves + // here, we might produce more valid inferences for types, causing us to do more checks and perform more instantiations + // (in addition to the extra stack depth here) which, in turn, can push the already close process over its limit. + // TL;DR: If we ever become generally more memory efficienct (or our resource budget ever increases), we should just + // remove this `allowComplexConstraintInference` flag. + allowComplexConstraintInference = false; + return inferFromTypes(apparentSource, target); + } + source = apparentSource; + } + if (source.flags & (524288 /* Object */ | 2097152 /* Intersection */)) { + var key = source.id + "," + target.id; + if (visited && visited.get(key)) { + return; + } + (visited || (visited = ts.createMap())).set(key, true); + // If we are already processing another target type with the same associated symbol (such as + // an instantiation of the same generic type), we do not explore this target as it would yield + // no further inferences. We exclude the static side of classes from this check since it shares + // its symbol with the instance side which would lead to false positives. + var isNonConstructorObject = target.flags & 524288 /* Object */ && + !(ts.getObjectFlags(target) & 16 /* Anonymous */ && target.symbol && target.symbol.flags & 32 /* Class */); + var symbol = isNonConstructorObject ? target.symbol : undefined; + if (symbol) { + if (ts.contains(symbolStack, symbol)) { + return; + } + (symbolStack || (symbolStack = [])).push(symbol); + inferFromObjectTypes(source, target); + symbolStack.pop(); + } + else { + inferFromObjectTypes(source, target); + } + } + } + function inferFromTypesOnce(source, target) { + var key = source.id + "," + target.id; + if (!visited || !visited.get(key)) { + (visited || (visited = ts.createMap())).set(key, true); + inferFromTypes(source, target); + } + } + } + function inferFromContravariantTypes(source, target) { + if (strictFunctionTypes || priority & 64 /* AlwaysStrict */) { + contravariant = !contravariant; + inferFromTypes(source, target); + contravariant = !contravariant; + } + else { + inferFromTypes(source, target); + } + } + function getInferenceInfoForType(type) { + if (type.flags & 8650752 /* TypeVariable */) { + for (var _i = 0, inferences_1 = inferences; _i < inferences_1.length; _i++) { + var inference = inferences_1[_i]; + if (type === inference.typeParameter) { + return inference; + } + } + } + return undefined; + } + function inferFromMappedTypeConstraint(source, target, constraintType) { + if (constraintType.flags & 1048576 /* Union */) { + var result = false; + for (var _i = 0, _a = constraintType.types; _i < _a.length; _i++) { + var type = _a[_i]; + result = inferFromMappedTypeConstraint(source, target, type) || result; + } + return result; + } + if (constraintType.flags & 4194304 /* Index */) { + // We're inferring from some source type S to a homomorphic mapped type { [P in keyof T]: X }, + // where T is a type variable. Use inferTypeForHomomorphicMappedType to infer a suitable source + // type and then make a secondary inference from that type to T. We make a secondary inference + // such that direct inferences to T get priority over inferences to Partial, for example. + var inference = getInferenceInfoForType(constraintType.type); + if (inference && !inference.isFixed) { + var inferredType = inferTypeForHomomorphicMappedType(source, target, constraintType); + if (inferredType) { + var savePriority = priority; + priority |= 2 /* HomomorphicMappedType */; + inferFromTypes(inferredType, inference.typeParameter); + priority = savePriority; + } + } + return true; + } + if (constraintType.flags & 262144 /* TypeParameter */) { + // We're inferring from some source type S to a mapped type { [P in T]: X }, where T is a type + // parameter. Infer from 'keyof S' to T and infer from a union of each property type in S to X. + var savePriority = priority; + priority |= 4 /* MappedTypeConstraint */; + inferFromTypes(getIndexType(source), constraintType); + priority = savePriority; + inferFromTypes(getUnionType(ts.map(getPropertiesOfType(source), getTypeOfSymbol)), getTemplateTypeFromMappedType(target)); + return true; + } + return false; + } + function inferFromObjectTypes(source, target) { + if (isGenericMappedType(source) && isGenericMappedType(target)) { + // The source and target types are generic types { [P in S]: X } and { [P in T]: Y }, so we infer + // from S to T and from X to Y. + inferFromTypes(getConstraintTypeFromMappedType(source), getConstraintTypeFromMappedType(target)); + inferFromTypes(getTemplateTypeFromMappedType(source), getTemplateTypeFromMappedType(target)); + } + if (ts.getObjectFlags(target) & 32 /* Mapped */) { + var constraintType = getConstraintTypeFromMappedType(target); + if (inferFromMappedTypeConstraint(source, target, constraintType)) { + return; + } + } + // Infer from the members of source and target only if the two types are possibly related + if (!typesDefinitelyUnrelated(source, target)) { + inferFromProperties(source, target); + inferFromSignatures(source, target, 0 /* Call */); + inferFromSignatures(source, target, 1 /* Construct */); + inferFromIndexTypes(source, target); + } + } + function inferFromProperties(source, target) { + if (isTupleType(source)) { + if (isTupleType(target)) { + var sourceLength = getLengthOfTupleType(source); + var targetLength = getLengthOfTupleType(target); + var sourceRestType = getRestTypeOfTupleType(source); + var targetRestType = getRestTypeOfTupleType(target); + var fixedLength = targetLength < sourceLength || sourceRestType ? targetLength : sourceLength; + for (var i = 0; i < fixedLength; i++) { + inferFromTypes(i < sourceLength ? source.typeArguments[i] : sourceRestType, target.typeArguments[i]); + } + if (targetRestType) { + var types = fixedLength < sourceLength ? source.typeArguments.slice(fixedLength, sourceLength) : []; + if (sourceRestType) { + types.push(sourceRestType); + } + if (types.length) { + inferFromTypes(getUnionType(types), targetRestType); + } + } + return; + } + if (isArrayType(target)) { + inferFromIndexTypes(source, target); + return; + } + } + var properties = getPropertiesOfObjectType(target); + for (var _i = 0, properties_5 = properties; _i < properties_5.length; _i++) { + var targetProp = properties_5[_i]; + var sourceProp = getPropertyOfType(source, targetProp.escapedName); + if (sourceProp) { + inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); + } + } + } + function inferFromSignatures(source, target, kind) { + var sourceSignatures = getSignaturesOfType(source, kind); + var targetSignatures = getSignaturesOfType(target, kind); + var sourceLen = sourceSignatures.length; + var targetLen = targetSignatures.length; + var len = sourceLen < targetLen ? sourceLen : targetLen; + var skipParameters = !!(source.flags & 536870912 /* ContainsAnyFunctionType */); + for (var i = 0; i < len; i++) { + inferFromSignature(getBaseSignature(sourceSignatures[sourceLen - len + i]), getBaseSignature(targetSignatures[targetLen - len + i]), skipParameters); + } + } + function inferFromSignature(source, target, skipParameters) { + if (!skipParameters) { + var saveBivariant = bivariant; + var kind = target.declaration ? target.declaration.kind : 0 /* Unknown */; + // Once we descend into a bivariant signature we remain bivariant for all nested inferences + bivariant = bivariant || kind === 156 /* MethodDeclaration */ || kind === 155 /* MethodSignature */ || kind === 157 /* Constructor */; + forEachMatchingParameterType(source, target, inferFromContravariantTypes); + bivariant = saveBivariant; + } + var sourceTypePredicate = getTypePredicateOfSignature(source); + var targetTypePredicate = getTypePredicateOfSignature(target); + if (sourceTypePredicate && targetTypePredicate && sourceTypePredicate.kind === targetTypePredicate.kind) { + inferFromTypes(sourceTypePredicate.type, targetTypePredicate.type); + } + else { + inferFromTypes(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target)); + } + } + function inferFromIndexTypes(source, target) { + var targetStringIndexType = getIndexTypeOfType(target, 0 /* String */); + if (targetStringIndexType) { + var sourceIndexType = getIndexTypeOfType(source, 0 /* String */) || + getImplicitIndexTypeOfType(source, 0 /* String */); + if (sourceIndexType) { + inferFromTypes(sourceIndexType, targetStringIndexType); + } + } + var targetNumberIndexType = getIndexTypeOfType(target, 1 /* Number */); + if (targetNumberIndexType) { + var sourceIndexType = getIndexTypeOfType(source, 1 /* Number */) || + getIndexTypeOfType(source, 0 /* String */) || + getImplicitIndexTypeOfType(source, 1 /* Number */); + if (sourceIndexType) { + inferFromTypes(sourceIndexType, targetNumberIndexType); + } + } + } + } + function typeIdenticalToSomeType(type, types) { + for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { + var t = types_10[_i]; + if (isTypeIdenticalTo(t, type)) { + return true; + } + } + return false; + } + /** + * Return a new union or intersection type computed by removing a given set of types + * from a given union or intersection type. + */ + function removeTypesFromUnionOrIntersection(type, typesToRemove) { + var reducedTypes = []; + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (!typeIdenticalToSomeType(t, typesToRemove)) { + reducedTypes.push(t); + } + } + return type.flags & 1048576 /* Union */ ? getUnionType(reducedTypes) : getIntersectionType(reducedTypes); + } + function hasPrimitiveConstraint(type) { + var constraint = getConstraintOfTypeParameter(type); + return !!constraint && maybeTypeOfKind(constraint.flags & 16777216 /* Conditional */ ? getDefaultConstraintOfConditionalType(constraint) : constraint, 131068 /* Primitive */ | 4194304 /* Index */); + } + function isObjectLiteralType(type) { + return !!(ts.getObjectFlags(type) & 128 /* ObjectLiteral */); + } + function widenObjectLiteralCandidates(candidates) { + if (candidates.length > 1) { + var objectLiterals = ts.filter(candidates, isObjectLiteralType); + if (objectLiterals.length) { + var objectLiteralsType = getWidenedType(getUnionType(objectLiterals, 2 /* Subtype */)); + return ts.concatenate(ts.filter(candidates, function (t) { return !isObjectLiteralType(t); }), [objectLiteralsType]); + } + } + return candidates; + } + function getContravariantInference(inference) { + return inference.priority & 28 /* PriorityImpliesCombination */ ? getIntersectionType(inference.contraCandidates) : getCommonSubtype(inference.contraCandidates); + } + function getCovariantInference(inference, signature) { + // Extract all object literal types and replace them with a single widened and normalized type. + var candidates = widenObjectLiteralCandidates(inference.candidates); + // We widen inferred literal types if + // all inferences were made to top-level occurrences of the type parameter, and + // the type parameter has no constraint or its constraint includes no primitive or literal types, and + // the type parameter was fixed during inference or does not occur at top-level in the return type. + var primitiveConstraint = hasPrimitiveConstraint(inference.typeParameter); + var widenLiteralTypes = !primitiveConstraint && inference.topLevel && + (inference.isFixed || !isTypeParameterAtTopLevel(getReturnTypeOfSignature(signature), inference.typeParameter)); + var baseCandidates = primitiveConstraint ? ts.sameMap(candidates, getRegularTypeOfLiteralType) : + widenLiteralTypes ? ts.sameMap(candidates, getWidenedLiteralType) : + candidates; + // If all inferences were made from a position that implies a combined result, infer a union type. + // Otherwise, infer a common supertype. + var unwidenedType = inference.priority & 28 /* PriorityImpliesCombination */ ? + getUnionType(baseCandidates, 2 /* Subtype */) : + getCommonSupertype(baseCandidates); + return getWidenedType(unwidenedType); + } + function getInferredType(context, index) { + var inference = context.inferences[index]; + var inferredType = inference.inferredType; + if (!inferredType) { + var signature = context.signature; + if (signature) { + var inferredCovariantType = inference.candidates ? getCovariantInference(inference, signature) : undefined; + if (inference.contraCandidates) { + var inferredContravariantType = getContravariantInference(inference); + // If we have both co- and contra-variant inferences, we prefer the contra-variant inference + // unless the co-variant inference is a subtype and not 'never'. + inferredType = inferredCovariantType && !(inferredCovariantType.flags & 131072 /* Never */) && + isTypeSubtypeOf(inferredCovariantType, inferredContravariantType) ? + inferredCovariantType : inferredContravariantType; + } + else if (inferredCovariantType) { + inferredType = inferredCovariantType; + } + else if (context.flags & 1 /* NoDefault */) { + // We use silentNeverType as the wildcard that signals no inferences. + inferredType = silentNeverType; + } + else { + // Infer either the default or the empty object type when no inferences were + // made. It is important to remember that in this case, inference still + // succeeds, meaning there is no error for not having inference candidates. An + // inference error only occurs when there are *conflicting* candidates, i.e. + // candidates with no common supertype. + var defaultType = getDefaultFromTypeParameter(inference.typeParameter); + if (defaultType) { + // Instantiate the default type. Any forward reference to a type + // parameter should be instantiated to the empty object type. + inferredType = instantiateType(defaultType, combineTypeMappers(createBackreferenceMapper(context.signature.typeParameters, index), context)); + } + else { + inferredType = getDefaultTypeArgumentType(!!(context.flags & 2 /* AnyDefault */)); + } + } + } + else { + inferredType = getTypeFromInference(inference); + } + inference.inferredType = inferredType; + var constraint = getConstraintOfTypeParameter(inference.typeParameter); + if (constraint) { + var instantiatedConstraint = instantiateType(constraint, context); + if (!context.compareTypes(inferredType, getTypeWithThisArgument(instantiatedConstraint, inferredType))) { + inference.inferredType = inferredType = instantiatedConstraint; + } + } + } + return inferredType; + } + function getDefaultTypeArgumentType(isInJavaScriptFile) { + return isInJavaScriptFile ? anyType : emptyObjectType; + } + function getInferredTypes(context) { + var result = []; + for (var i = 0; i < context.inferences.length; i++) { + result.push(getInferredType(context, i)); + } + return result; + } + // EXPRESSION TYPE CHECKING + function getCannotFindNameDiagnosticForName(name) { + switch (name) { + case "document": + case "console": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom; + case "$": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_and_then_add_jquery_to_the_types_field_in_your_tsconfig; + case "describe": + case "suite": + case "it": + case "test": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha_and_then_add_jest_or_mocha_to_the_types_field_in_your_tsconfig; + case "process": + case "require": + case "Buffer": + case "module": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_and_then_add_node_to_the_types_field_in_your_tsconfig; + case "Map": + case "Set": + case "Promise": + case "Symbol": + case "WeakMap": + case "WeakSet": + case "Iterator": + case "AsyncIterator": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later; + default: return ts.Diagnostics.Cannot_find_name_0; + } + } + function getResolvedSymbol(node) { + var links = getNodeLinks(node); + if (!links.resolvedSymbol) { + links.resolvedSymbol = !ts.nodeIsMissing(node) && + resolveName(node, node.escapedText, 67220415 /* Value */ | 1048576 /* ExportValue */, getCannotFindNameDiagnosticForName(node.escapedText), node, !ts.isWriteOnlyAccess(node), + /*excludeGlobals*/ false, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1) || unknownSymbol; + } + return links.resolvedSymbol; + } + function isInTypeQuery(node) { + // TypeScript 1.0 spec (April 2014): 3.6.3 + // A type query consists of the keyword typeof followed by an expression. + // The expression is restricted to a single identifier or a sequence of identifiers separated by periods + return !!ts.findAncestor(node, function (n) { return n.kind === 167 /* TypeQuery */ ? true : n.kind === 72 /* Identifier */ || n.kind === 148 /* QualifiedName */ ? false : "quit"; }); + } + // Return the flow cache key for a "dotted name" (i.e. a sequence of identifiers + // separated by dots). The key consists of the id of the symbol referenced by the + // leftmost identifier followed by zero or more property names separated by dots. + // The result is undefined if the reference isn't a dotted name. We prefix nodes + // occurring in an apparent type position with '@' because the control flow type + // of such nodes may be based on the apparent type instead of the declared type. + function getFlowCacheKey(node) { + if (node.kind === 72 /* Identifier */) { + var symbol = getResolvedSymbol(node); + return symbol !== unknownSymbol ? (isConstraintPosition(node) ? "@" : "") + getSymbolId(symbol) : undefined; + } + if (node.kind === 100 /* ThisKeyword */) { + return "0"; + } + if (node.kind === 189 /* PropertyAccessExpression */) { + var key = getFlowCacheKey(node.expression); + return key && key + "." + ts.idText(node.name); + } + if (node.kind === 186 /* BindingElement */) { + var container = node.parent.parent; + var key = container.kind === 186 /* BindingElement */ ? getFlowCacheKey(container) : (container.initializer && getFlowCacheKey(container.initializer)); + var text = getBindingElementNameText(node); + var result = key && text && (key + "." + text); + return result; + } + return undefined; + } + function getBindingElementNameText(element) { + var parent = element.parent; + if (parent.kind === 184 /* ObjectBindingPattern */) { + var name = element.propertyName || element.name; + switch (name.kind) { + case 72 /* Identifier */: + return ts.idText(name); + case 149 /* ComputedPropertyName */: + return ts.isStringOrNumericLiteralLike(name.expression) ? name.expression.text : undefined; + case 10 /* StringLiteral */: + case 8 /* NumericLiteral */: + return name.text; + default: + // Per types, array and object binding patterns remain, however they should never be present if propertyName is not defined + ts.Debug.fail("Unexpected name kind for binding element name"); + } + } + else { + return "" + parent.elements.indexOf(element); + } + } + function isMatchingReference(source, target) { + switch (source.kind) { + case 72 /* Identifier */: + return target.kind === 72 /* Identifier */ && getResolvedSymbol(source) === getResolvedSymbol(target) || + (target.kind === 237 /* VariableDeclaration */ || target.kind === 186 /* BindingElement */) && + getExportSymbolOfValueSymbolIfExported(getResolvedSymbol(source)) === getSymbolOfNode(target); + case 100 /* ThisKeyword */: + return target.kind === 100 /* ThisKeyword */; + case 98 /* SuperKeyword */: + return target.kind === 98 /* SuperKeyword */; + case 189 /* PropertyAccessExpression */: + case 190 /* ElementAccessExpression */: + return (ts.isPropertyAccessExpression(target) || ts.isElementAccessExpression(target)) && + getAccessedPropertyName(source) === getAccessedPropertyName(target) && + isMatchingReference(source.expression, target.expression); + case 186 /* BindingElement */: + if (target.kind !== 189 /* PropertyAccessExpression */) + return false; + var t = target; + if (t.name.escapedText !== getBindingElementNameText(source)) + return false; + if (source.parent.parent.kind === 186 /* BindingElement */ && isMatchingReference(source.parent.parent, t.expression)) { + return true; + } + if (source.parent.parent.kind === 237 /* VariableDeclaration */) { + var maybeId = source.parent.parent.initializer; + return !!maybeId && isMatchingReference(maybeId, t.expression); + } + } + return false; + } + function getAccessedPropertyName(access) { + return ts.isPropertyAccessExpression(access) ? access.name.escapedText : + ts.isStringLiteral(access.argumentExpression) || ts.isNumericLiteral(access.argumentExpression) ? ts.escapeLeadingUnderscores(access.argumentExpression.text) : + undefined; + } + function containsMatchingReference(source, target) { + while (source.kind === 189 /* PropertyAccessExpression */) { + source = source.expression; + if (isMatchingReference(source, target)) { + return true; + } + } + return false; + } + // Return true if target is a property access xxx.yyy, source is a property access xxx.zzz, the declared + // type of xxx is a union type, and yyy is a property that is possibly a discriminant. We consider a property + // a possible discriminant if its type differs in the constituents of containing union type, and if every + // choice is a unit type or a union of unit types. + function containsMatchingReferenceDiscriminant(source, target) { + return target.kind === 189 /* PropertyAccessExpression */ && + containsMatchingReference(source, target.expression) && + isDiscriminantProperty(getDeclaredTypeOfReference(target.expression), target.name.escapedText); + } + function getDeclaredTypeOfReference(expr) { + if (expr.kind === 72 /* Identifier */) { + return getTypeOfSymbol(getResolvedSymbol(expr)); + } + if (expr.kind === 189 /* PropertyAccessExpression */) { + var type = getDeclaredTypeOfReference(expr.expression); + return type && getTypeOfPropertyOfType(type, expr.name.escapedText); + } + return undefined; + } + function isDiscriminantType(type) { + if (type.flags & 1048576 /* Union */) { + if (type.flags & (16 /* Boolean */ | 1024 /* EnumLiteral */)) { + return true; + } + var combined = 0; + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var t = _a[_i]; + combined |= t.flags; + } + if (combined & 109440 /* Unit */ && !(combined & 63176704 /* Instantiable */)) { + return true; + } + } + return false; + } + function isDiscriminantProperty(type, name) { + if (type && type.flags & 1048576 /* Union */) { + var prop = getUnionOrIntersectionProperty(type, name); + if (prop && ts.getCheckFlags(prop) & 2 /* SyntheticProperty */) { + if (prop.isDiscriminantProperty === undefined) { + prop.isDiscriminantProperty = !!(prop.checkFlags & 32 /* HasNonUniformType */) && isDiscriminantType(getTypeOfSymbol(prop)); + } + return !!prop.isDiscriminantProperty; + } + } + return false; + } + function hasNarrowableDeclaredType(expr) { + var type = getDeclaredTypeOfReference(expr); + return !!(type && type.flags & 1048576 /* Union */); + } + function findDiscriminantProperties(sourceProperties, target) { + var result; + for (var _i = 0, sourceProperties_2 = sourceProperties; _i < sourceProperties_2.length; _i++) { + var sourceProperty = sourceProperties_2[_i]; + if (isDiscriminantProperty(target, sourceProperty.escapedName)) { + if (result) { + result.push(sourceProperty); + continue; + } + result = [sourceProperty]; + } + } + return result; + } + function isOrContainsMatchingReference(source, target) { + return isMatchingReference(source, target) || containsMatchingReference(source, target); + } + function hasMatchingArgument(callExpression, reference) { + if (callExpression.arguments) { + for (var _i = 0, _a = callExpression.arguments; _i < _a.length; _i++) { + var argument = _a[_i]; + if (isOrContainsMatchingReference(reference, argument)) { + return true; + } + } + } + if (callExpression.expression.kind === 189 /* PropertyAccessExpression */ && + isOrContainsMatchingReference(reference, callExpression.expression.expression)) { + return true; + } + return false; + } + function getFlowNodeId(flow) { + if (!flow.id) { + flow.id = nextFlowId; + nextFlowId++; + } + return flow.id; + } + function typeMaybeAssignableTo(source, target) { + if (!(source.flags & 1048576 /* Union */)) { + return isTypeAssignableTo(source, target); + } + for (var _i = 0, _a = source.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (isTypeAssignableTo(t, target)) { + return true; + } + } + return false; + } + // Remove those constituent types of declaredType to which no constituent type of assignedType is assignable. + // For example, when a variable of type number | string | boolean is assigned a value of type number | boolean, + // we remove type string. + function getAssignmentReducedType(declaredType, assignedType) { + if (declaredType !== assignedType) { + if (assignedType.flags & 131072 /* Never */) { + return assignedType; + } + var reducedType = filterType(declaredType, function (t) { return typeMaybeAssignableTo(assignedType, t); }); + if (assignedType.flags & 512 /* BooleanLiteral */ && isFreshLiteralType(assignedType)) { + reducedType = mapType(reducedType, getFreshTypeOfLiteralType); // Ensure that if the assignment is a fresh type, that we narrow to fresh types + } + // Our crude heuristic produces an invalid result in some cases: see GH#26130. + // For now, when that happens, we give up and don't narrow at all. (This also + // means we'll never narrow for erroneous assignments where the assigned type + // is not assignable to the declared type.) + if (isTypeAssignableTo(assignedType, reducedType)) { + return reducedType; + } + } + return declaredType; + } + function getTypeFactsOfTypes(types) { + var result = 0 /* None */; + for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { + var t = types_11[_i]; + result |= getTypeFacts(t); + } + return result; + } + function isFunctionObjectType(type) { + // We do a quick check for a "bind" property before performing the more expensive subtype + // check. This gives us a quicker out in the common case where an object type is not a function. + var resolved = resolveStructuredTypeMembers(type); + return !!(resolved.callSignatures.length || resolved.constructSignatures.length || + resolved.members.get("bind") && isTypeSubtypeOf(type, globalFunctionType)); + } + function getTypeFacts(type) { + var flags = type.flags; + if (flags & 4 /* String */) { + return strictNullChecks ? 16317953 /* StringStrictFacts */ : 16776705 /* StringFacts */; + } + if (flags & 128 /* StringLiteral */) { + var isEmpty = type.value === ""; + return strictNullChecks ? + isEmpty ? 12123649 /* EmptyStringStrictFacts */ : 7929345 /* NonEmptyStringStrictFacts */ : + isEmpty ? 12582401 /* EmptyStringFacts */ : 16776705 /* NonEmptyStringFacts */; + } + if (flags & (8 /* Number */ | 32 /* Enum */)) { + return strictNullChecks ? 16317698 /* NumberStrictFacts */ : 16776450 /* NumberFacts */; + } + if (flags & 256 /* NumberLiteral */) { + var isZero = type.value === 0; + return strictNullChecks ? + isZero ? 12123394 /* ZeroNumberStrictFacts */ : 7929090 /* NonZeroNumberStrictFacts */ : + isZero ? 12582146 /* ZeroNumberFacts */ : 16776450 /* NonZeroNumberFacts */; + } + if (flags & 64 /* BigInt */) { + return strictNullChecks ? 16317188 /* BigIntStrictFacts */ : 16775940 /* BigIntFacts */; + } + if (flags & 2048 /* BigIntLiteral */) { + var isZero = isZeroBigInt(type); + return strictNullChecks ? + isZero ? 12122884 /* ZeroBigIntStrictFacts */ : 7928580 /* NonZeroBigIntStrictFacts */ : + isZero ? 12581636 /* ZeroBigIntFacts */ : 16775940 /* NonZeroBigIntFacts */; + } + if (flags & 16 /* Boolean */) { + return strictNullChecks ? 16316168 /* BooleanStrictFacts */ : 16774920 /* BooleanFacts */; + } + if (flags & 528 /* BooleanLike */) { + return strictNullChecks ? + (type === falseType || type === regularFalseType) ? 12121864 /* FalseStrictFacts */ : 7927560 /* TrueStrictFacts */ : + (type === falseType || type === regularFalseType) ? 12580616 /* FalseFacts */ : 16774920 /* TrueFacts */; + } + if (flags & 524288 /* Object */) { + return ts.getObjectFlags(type) & 16 /* Anonymous */ && isEmptyObjectType(type) ? + strictNullChecks ? 16318463 /* EmptyObjectStrictFacts */ : 16777215 /* EmptyObjectFacts */ : + isFunctionObjectType(type) ? + strictNullChecks ? 7880640 /* FunctionStrictFacts */ : 16728000 /* FunctionFacts */ : + strictNullChecks ? 7888800 /* ObjectStrictFacts */ : 16736160 /* ObjectFacts */; + } + if (flags & (16384 /* Void */ | 32768 /* Undefined */)) { + return 9830144 /* UndefinedFacts */; + } + if (flags & 65536 /* Null */) { + return 9363232 /* NullFacts */; + } + if (flags & 12288 /* ESSymbolLike */) { + return strictNullChecks ? 7925520 /* SymbolStrictFacts */ : 16772880 /* SymbolFacts */; + } + if (flags & 67108864 /* NonPrimitive */) { + return strictNullChecks ? 7888800 /* ObjectStrictFacts */ : 16736160 /* ObjectFacts */; + } + if (flags & 63176704 /* Instantiable */) { + return getTypeFacts(getBaseConstraintOfType(type) || emptyObjectType); + } + if (flags & 3145728 /* UnionOrIntersection */) { + return getTypeFactsOfTypes(type.types); + } + return 16777215 /* All */; + } + function getTypeWithFacts(type, include) { + return filterType(type, function (t) { return (getTypeFacts(t) & include) !== 0; }); + } + function getTypeWithDefault(type, defaultExpression) { + if (defaultExpression) { + var defaultType = getTypeOfExpression(defaultExpression); + return getUnionType([getTypeWithFacts(type, 524288 /* NEUndefined */), defaultType]); + } + return type; + } + function getTypeOfDestructuredProperty(type, name) { + var text = ts.getTextOfPropertyName(name); + return getConstraintForLocation(getTypeOfPropertyOfType(type, text), name) || + isNumericLiteralName(text) && getIndexTypeOfType(type, 1 /* Number */) || + getIndexTypeOfType(type, 0 /* String */) || + errorType; + } + function getTypeOfDestructuredArrayElement(type, index) { + return everyType(type, isTupleLikeType) && getTupleElementType(type, index) || + checkIteratedTypeOrElementType(type, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterables*/ false) || + errorType; + } + function getTypeOfDestructuredSpreadExpression(type) { + return createArrayType(checkIteratedTypeOrElementType(type, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterables*/ false) || errorType); + } + function getAssignedTypeOfBinaryExpression(node) { + var isDestructuringDefaultAssignment = node.parent.kind === 187 /* ArrayLiteralExpression */ && isDestructuringAssignmentTarget(node.parent) || + node.parent.kind === 275 /* PropertyAssignment */ && isDestructuringAssignmentTarget(node.parent.parent); + return isDestructuringDefaultAssignment ? + getTypeWithDefault(getAssignedType(node), node.right) : + getTypeOfExpression(node.right); + } + function isDestructuringAssignmentTarget(parent) { + return parent.parent.kind === 204 /* BinaryExpression */ && parent.parent.left === parent || + parent.parent.kind === 227 /* ForOfStatement */ && parent.parent.initializer === parent; + } + function getAssignedTypeOfArrayLiteralElement(node, element) { + return getTypeOfDestructuredArrayElement(getAssignedType(node), node.elements.indexOf(element)); + } + function getAssignedTypeOfSpreadExpression(node) { + return getTypeOfDestructuredSpreadExpression(getAssignedType(node.parent)); + } + function getAssignedTypeOfPropertyAssignment(node) { + return getTypeOfDestructuredProperty(getAssignedType(node.parent), node.name); + } + function getAssignedTypeOfShorthandPropertyAssignment(node) { + return getTypeWithDefault(getAssignedTypeOfPropertyAssignment(node), node.objectAssignmentInitializer); + } + function getAssignedType(node) { + var parent = node.parent; + switch (parent.kind) { + case 226 /* ForInStatement */: + return stringType; + case 227 /* ForOfStatement */: + return checkRightHandSideOfForOf(parent.expression, parent.awaitModifier) || errorType; + case 204 /* BinaryExpression */: + return getAssignedTypeOfBinaryExpression(parent); + case 198 /* DeleteExpression */: + return undefinedType; + case 187 /* ArrayLiteralExpression */: + return getAssignedTypeOfArrayLiteralElement(parent, node); + case 208 /* SpreadElement */: + return getAssignedTypeOfSpreadExpression(parent); + case 275 /* PropertyAssignment */: + return getAssignedTypeOfPropertyAssignment(parent); + case 276 /* ShorthandPropertyAssignment */: + return getAssignedTypeOfShorthandPropertyAssignment(parent); + } + return errorType; + } + function getInitialTypeOfBindingElement(node) { + var pattern = node.parent; + var parentType = getInitialType(pattern.parent); + var type = pattern.kind === 184 /* ObjectBindingPattern */ ? + getTypeOfDestructuredProperty(parentType, node.propertyName || node.name) : + !node.dotDotDotToken ? + getTypeOfDestructuredArrayElement(parentType, pattern.elements.indexOf(node)) : + getTypeOfDestructuredSpreadExpression(parentType); + return getTypeWithDefault(type, node.initializer); + } + function getTypeOfInitializer(node) { + // Return the cached type if one is available. If the type of the variable was inferred + // from its initializer, we'll already have cached the type. Otherwise we compute it now + // without caching such that transient types are reflected. + var links = getNodeLinks(node); + return links.resolvedType || getTypeOfExpression(node); + } + function getInitialTypeOfVariableDeclaration(node) { + if (node.initializer) { + return getTypeOfInitializer(node.initializer); + } + if (node.parent.parent.kind === 226 /* ForInStatement */) { + return stringType; + } + if (node.parent.parent.kind === 227 /* ForOfStatement */) { + return checkRightHandSideOfForOf(node.parent.parent.expression, node.parent.parent.awaitModifier) || errorType; + } + return errorType; + } + function getInitialType(node) { + return node.kind === 237 /* VariableDeclaration */ ? + getInitialTypeOfVariableDeclaration(node) : + getInitialTypeOfBindingElement(node); + } + function getInitialOrAssignedType(node, reference) { + return getConstraintForLocation(node.kind === 237 /* VariableDeclaration */ || node.kind === 186 /* BindingElement */ ? + getInitialType(node) : + getAssignedType(node), reference); + } + function isEmptyArrayAssignment(node) { + return node.kind === 237 /* VariableDeclaration */ && node.initializer && + isEmptyArrayLiteral(node.initializer) || + node.kind !== 186 /* BindingElement */ && node.parent.kind === 204 /* BinaryExpression */ && + isEmptyArrayLiteral(node.parent.right); + } + function getReferenceCandidate(node) { + switch (node.kind) { + case 195 /* ParenthesizedExpression */: + return getReferenceCandidate(node.expression); + case 204 /* BinaryExpression */: + switch (node.operatorToken.kind) { + case 59 /* EqualsToken */: + return getReferenceCandidate(node.left); + case 27 /* CommaToken */: + return getReferenceCandidate(node.right); + } + } + return node; + } + function getReferenceRoot(node) { + var parent = node.parent; + return parent.kind === 195 /* ParenthesizedExpression */ || + parent.kind === 204 /* BinaryExpression */ && parent.operatorToken.kind === 59 /* EqualsToken */ && parent.left === node || + parent.kind === 204 /* BinaryExpression */ && parent.operatorToken.kind === 27 /* CommaToken */ && parent.right === node ? + getReferenceRoot(parent) : node; + } + function getTypeOfSwitchClause(clause) { + if (clause.kind === 271 /* CaseClause */) { + return getRegularTypeOfLiteralType(getTypeOfExpression(clause.expression)); + } + return neverType; + } + function getSwitchClauseTypes(switchStatement) { + var links = getNodeLinks(switchStatement); + if (!links.switchTypes) { + links.switchTypes = []; + for (var _i = 0, _a = switchStatement.caseBlock.clauses; _i < _a.length; _i++) { + var clause = _a[_i]; + links.switchTypes.push(getTypeOfSwitchClause(clause)); + } + } + return links.switchTypes; + } + // Get the types from all cases in a switch on `typeof`. An + // `undefined` element denotes an explicit `default` clause. + function getSwitchClauseTypeOfWitnesses(switchStatement) { + var witnesses = []; + for (var _i = 0, _a = switchStatement.caseBlock.clauses; _i < _a.length; _i++) { + var clause = _a[_i]; + if (clause.kind === 271 /* CaseClause */) { + if (clause.expression.kind === 10 /* StringLiteral */) { + witnesses.push(clause.expression.text); + continue; + } + return ts.emptyArray; + } + witnesses.push(/*explicitDefaultStatement*/ undefined); + } + return witnesses; + } + function eachTypeContainedIn(source, types) { + return source.flags & 1048576 /* Union */ ? !ts.forEach(source.types, function (t) { return !ts.contains(types, t); }) : ts.contains(types, source); + } + function isTypeSubsetOf(source, target) { + return source === target || target.flags & 1048576 /* Union */ && isTypeSubsetOfUnion(source, target); + } + function isTypeSubsetOfUnion(source, target) { + if (source.flags & 1048576 /* Union */) { + for (var _i = 0, _a = source.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (!containsType(target.types, t)) { + return false; + } + } + return true; + } + if (source.flags & 1024 /* EnumLiteral */ && getBaseTypeOfEnumLiteralType(source) === target) { + return true; + } + return containsType(target.types, source); + } + function forEachType(type, f) { + return type.flags & 1048576 /* Union */ ? ts.forEach(type.types, f) : f(type); + } + function everyType(type, f) { + return type.flags & 1048576 /* Union */ ? ts.every(type.types, f) : f(type); + } + function filterType(type, f) { + if (type.flags & 1048576 /* Union */) { + var types = type.types; + var filtered = ts.filter(types, f); + return filtered === types ? type : getUnionTypeFromSortedList(filtered, type.primitiveTypesOnly); + } + return f(type) ? type : neverType; + } + function mapType(type, mapper, noReductions) { + if (type.flags & 131072 /* Never */) { + return type; + } + if (!(type.flags & 1048576 /* Union */)) { + return mapper(type); + } + var types = type.types; + var mappedType; + var mappedTypes; + for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { + var current = types_12[_i]; + var t = mapper(current); + if (t) { + if (!mappedType) { + mappedType = t; + } + else if (!mappedTypes) { + mappedTypes = [mappedType, t]; + } + else { + mappedTypes.push(t); + } + } + } + return mappedTypes ? getUnionType(mappedTypes, noReductions ? 0 /* None */ : 1 /* Literal */) : mappedType; + } + function extractTypesOfKind(type, kind) { + return filterType(type, function (t) { return (t.flags & kind) !== 0; }); + } + // Return a new type in which occurrences of the string and number primitive types in + // typeWithPrimitives have been replaced with occurrences of string literals and numeric + // literals in typeWithLiterals, respectively. + function replacePrimitivesWithLiterals(typeWithPrimitives, typeWithLiterals) { + if (isTypeSubsetOf(stringType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 128 /* StringLiteral */) || + isTypeSubsetOf(numberType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 256 /* NumberLiteral */) || + isTypeSubsetOf(bigintType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 2048 /* BigIntLiteral */)) { + return mapType(typeWithPrimitives, function (t) { + return t.flags & 4 /* String */ ? extractTypesOfKind(typeWithLiterals, 4 /* String */ | 128 /* StringLiteral */) : + t.flags & 8 /* Number */ ? extractTypesOfKind(typeWithLiterals, 8 /* Number */ | 256 /* NumberLiteral */) : + t.flags & 64 /* BigInt */ ? extractTypesOfKind(typeWithLiterals, 64 /* BigInt */ | 2048 /* BigIntLiteral */) : + t; + }); + } + return typeWithPrimitives; + } + function isIncomplete(flowType) { + return flowType.flags === 0; + } + function getTypeFromFlowType(flowType) { + return flowType.flags === 0 ? flowType.type : flowType; + } + function createFlowType(type, incomplete) { + return incomplete ? { flags: 0, type: type } : type; + } + // An evolving array type tracks the element types that have so far been seen in an + // 'x.push(value)' or 'x[n] = value' operation along the control flow graph. Evolving + // array types are ultimately converted into manifest array types (using getFinalArrayType) + // and never escape the getFlowTypeOfReference function. + function createEvolvingArrayType(elementType) { + var result = createObjectType(256 /* EvolvingArray */); + result.elementType = elementType; + return result; + } + function getEvolvingArrayType(elementType) { + return evolvingArrayTypes[elementType.id] || (evolvingArrayTypes[elementType.id] = createEvolvingArrayType(elementType)); + } + // When adding evolving array element types we do not perform subtype reduction. Instead, + // we defer subtype reduction until the evolving array type is finalized into a manifest + // array type. + function addEvolvingArrayElementType(evolvingArrayType, node) { + var elementType = getBaseTypeOfLiteralType(getContextFreeTypeOfExpression(node)); + return isTypeSubsetOf(elementType, evolvingArrayType.elementType) ? evolvingArrayType : getEvolvingArrayType(getUnionType([evolvingArrayType.elementType, elementType])); + } + function createFinalArrayType(elementType) { + return elementType.flags & 131072 /* Never */ ? + autoArrayType : + createArrayType(elementType.flags & 1048576 /* Union */ ? + getUnionType(elementType.types, 2 /* Subtype */) : + elementType); + } + // We perform subtype reduction upon obtaining the final array type from an evolving array type. + function getFinalArrayType(evolvingArrayType) { + return evolvingArrayType.finalArrayType || (evolvingArrayType.finalArrayType = createFinalArrayType(evolvingArrayType.elementType)); + } + function finalizeEvolvingArrayType(type) { + return ts.getObjectFlags(type) & 256 /* EvolvingArray */ ? getFinalArrayType(type) : type; + } + function getElementTypeOfEvolvingArrayType(type) { + return ts.getObjectFlags(type) & 256 /* EvolvingArray */ ? type.elementType : neverType; + } + function isEvolvingArrayTypeList(types) { + var hasEvolvingArrayType = false; + for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { + var t = types_13[_i]; + if (!(t.flags & 131072 /* Never */)) { + if (!(ts.getObjectFlags(t) & 256 /* EvolvingArray */)) { + return false; + } + hasEvolvingArrayType = true; + } + } + return hasEvolvingArrayType; + } + // At flow control branch or loop junctions, if the type along every antecedent code path + // is an evolving array type, we construct a combined evolving array type. Otherwise we + // finalize all evolving array types. + function getUnionOrEvolvingArrayType(types, subtypeReduction) { + return isEvolvingArrayTypeList(types) ? + getEvolvingArrayType(getUnionType(ts.map(types, getElementTypeOfEvolvingArrayType))) : + getUnionType(ts.sameMap(types, finalizeEvolvingArrayType), subtypeReduction); + } + // Return true if the given node is 'x' in an 'x.length', x.push(value)', 'x.unshift(value)' or + // 'x[n] = value' operation, where 'n' is an expression of type any, undefined, or a number-like type. + function isEvolvingArrayOperationTarget(node) { + var root = getReferenceRoot(node); + var parent = root.parent; + var isLengthPushOrUnshift = parent.kind === 189 /* PropertyAccessExpression */ && (parent.name.escapedText === "length" || + parent.parent.kind === 191 /* CallExpression */ && ts.isPushOrUnshiftIdentifier(parent.name)); + var isElementAssignment = parent.kind === 190 /* ElementAccessExpression */ && + parent.expression === root && + parent.parent.kind === 204 /* BinaryExpression */ && + parent.parent.operatorToken.kind === 59 /* EqualsToken */ && + parent.parent.left === parent && + !ts.isAssignmentTarget(parent.parent) && + isTypeAssignableToKind(getTypeOfExpression(parent.argumentExpression), 296 /* NumberLike */); + return isLengthPushOrUnshift || isElementAssignment; + } + function maybeTypePredicateCall(node) { + var links = getNodeLinks(node); + if (links.maybeTypePredicate === undefined) { + links.maybeTypePredicate = getMaybeTypePredicate(node); + } + return links.maybeTypePredicate; + } + function getMaybeTypePredicate(node) { + if (node.expression.kind !== 98 /* SuperKeyword */) { + var funcType = checkNonNullExpression(node.expression); + if (funcType !== silentNeverType) { + var apparentType = getApparentType(funcType); + return apparentType !== errorType && ts.some(getSignaturesOfType(apparentType, 0 /* Call */), signatureHasTypePredicate); + } + } + return false; + } + function reportFlowControlError(node) { + var block = ts.findAncestor(node, ts.isFunctionOrModuleBlock); + var sourceFile = ts.getSourceFileOfNode(node); + var span = ts.getSpanOfTokenAtPosition(sourceFile, block.statements.pos); + diagnostics.add(ts.createFileDiagnostic(sourceFile, span.start, span.length, ts.Diagnostics.The_containing_function_or_module_body_is_too_large_for_control_flow_analysis)); + } + function getFlowTypeOfReference(reference, declaredType, initialType, flowContainer, couldBeUninitialized) { + if (initialType === void 0) { initialType = declaredType; } + var key; + var flowDepth = 0; + if (flowAnalysisDisabled) { + return errorType; + } + if (!reference.flowNode || !couldBeUninitialized && !(declaredType.flags & 133970943 /* Narrowable */)) { + return declaredType; + } + var sharedFlowStart = sharedFlowCount; + var evolvedType = getTypeFromFlowType(getTypeAtFlowNode(reference.flowNode)); + sharedFlowCount = sharedFlowStart; + // When the reference is 'x' in an 'x.length', 'x.push(value)', 'x.unshift(value)' or x[n] = value' operation, + // we give type 'any[]' to 'x' instead of using the type determined by control flow analysis such that operations + // on empty arrays are possible without implicit any errors and new element types can be inferred without + // type mismatch errors. + var resultType = ts.getObjectFlags(evolvedType) & 256 /* EvolvingArray */ && isEvolvingArrayOperationTarget(reference) ? autoArrayType : finalizeEvolvingArrayType(evolvedType); + if (reference.parent && reference.parent.kind === 213 /* NonNullExpression */ && getTypeWithFacts(resultType, 2097152 /* NEUndefinedOrNull */).flags & 131072 /* Never */) { + return declaredType; + } + return resultType; + function getTypeAtFlowNode(flow) { + if (flowDepth === 2000) { + // We have made 2000 recursive invocations. To avoid overflowing the call stack we report an error + // and disable further control flow analysis in the containing function or module body. + flowAnalysisDisabled = true; + reportFlowControlError(reference); + return errorType; + } + flowDepth++; + while (true) { + var flags = flow.flags; + if (flags & 1024 /* Shared */) { + // We cache results of flow type resolution for shared nodes that were previously visited in + // the same getFlowTypeOfReference invocation. A node is considered shared when it is the + // antecedent of more than one node. + for (var i = sharedFlowStart; i < sharedFlowCount; i++) { + if (sharedFlowNodes[i] === flow) { + flowDepth--; + return sharedFlowTypes[i]; + } + } + } + var type = void 0; + if (flags & 4096 /* AfterFinally */) { + // block flow edge: finally -> pre-try (for larger explanation check comment in binder.ts - bindTryStatement + flow.locked = true; + type = getTypeAtFlowNode(flow.antecedent); + flow.locked = false; + } + else if (flags & 2048 /* PreFinally */) { + // locked pre-finally flows are filtered out in getTypeAtFlowBranchLabel + // so here just redirect to antecedent + flow = flow.antecedent; + continue; + } + else if (flags & 16 /* Assignment */) { + type = getTypeAtFlowAssignment(flow); + if (!type) { + flow = flow.antecedent; + continue; + } + } + else if (flags & 96 /* Condition */) { + type = getTypeAtFlowCondition(flow); + } + else if (flags & 128 /* SwitchClause */) { + type = getTypeAtSwitchClause(flow); + } + else if (flags & 12 /* Label */) { + if (flow.antecedents.length === 1) { + flow = flow.antecedents[0]; + continue; + } + type = flags & 4 /* BranchLabel */ ? + getTypeAtFlowBranchLabel(flow) : + getTypeAtFlowLoopLabel(flow); + } + else if (flags & 256 /* ArrayMutation */) { + type = getTypeAtFlowArrayMutation(flow); + if (!type) { + flow = flow.antecedent; + continue; + } + } + else if (flags & 2 /* Start */) { + // Check if we should continue with the control flow of the containing function. + var container = flow.container; + if (container && container !== flowContainer && + reference.kind !== 189 /* PropertyAccessExpression */ && + reference.kind !== 190 /* ElementAccessExpression */ && + reference.kind !== 100 /* ThisKeyword */) { + flow = container.flowNode; + continue; + } + // At the top of the flow we have the initial type. + type = initialType; + } + else { + // Unreachable code errors are reported in the binding phase. Here we + // simply return the non-auto declared type to reduce follow-on errors. + type = convertAutoToAny(declaredType); + } + if (flags & 1024 /* Shared */) { + // Record visited node and the associated type in the cache. + sharedFlowNodes[sharedFlowCount] = flow; + sharedFlowTypes[sharedFlowCount] = type; + sharedFlowCount++; + } + flowDepth--; + return type; + } + } + function getTypeAtFlowAssignment(flow) { + var node = flow.node; + // Assignments only narrow the computed type if the declared type is a union type. Thus, we + // only need to evaluate the assigned type if the declared type is a union type. + if (isMatchingReference(reference, node)) { + if (ts.getAssignmentTargetKind(node) === 2 /* Compound */) { + var flowType = getTypeAtFlowNode(flow.antecedent); + return createFlowType(getBaseTypeOfLiteralType(getTypeFromFlowType(flowType)), isIncomplete(flowType)); + } + if (declaredType === autoType || declaredType === autoArrayType) { + if (isEmptyArrayAssignment(node)) { + return getEvolvingArrayType(neverType); + } + var assignedType = getBaseTypeOfLiteralType(getInitialOrAssignedType(node, reference)); + return isTypeAssignableTo(assignedType, declaredType) ? assignedType : anyArrayType; + } + if (declaredType.flags & 1048576 /* Union */) { + return getAssignmentReducedType(declaredType, getInitialOrAssignedType(node, reference)); + } + return declaredType; + } + // We didn't have a direct match. However, if the reference is a dotted name, this + // may be an assignment to a left hand part of the reference. For example, for a + // reference 'x.y.z', we may be at an assignment to 'x.y' or 'x'. In that case, + // return the declared type. + if (containsMatchingReference(reference, node)) { + // A matching dotted name might also be an expando property on a function *expression*, + // in which case we continue control flow analysis back to the function's declaration + if (ts.isVariableDeclaration(node) && (ts.isInJSFile(node) || ts.isVarConst(node))) { + var init = ts.getDeclaredExpandoInitializer(node); + if (init && (init.kind === 196 /* FunctionExpression */ || init.kind === 197 /* ArrowFunction */)) { + return getTypeAtFlowNode(flow.antecedent); + } + } + return declaredType; + } + // for (const _ in ref) acts as a nonnull on ref + if (ts.isVariableDeclaration(node) && node.parent.parent.kind === 226 /* ForInStatement */ && isMatchingReference(reference, node.parent.parent.expression)) { + return getNonNullableTypeIfNeeded(getTypeFromFlowType(getTypeAtFlowNode(flow.antecedent))); + } + // Assignment doesn't affect reference + return undefined; + } + function getTypeAtFlowArrayMutation(flow) { + if (declaredType === autoType || declaredType === autoArrayType) { + var node = flow.node; + var expr = node.kind === 191 /* CallExpression */ ? + node.expression.expression : + node.left.expression; + if (isMatchingReference(reference, getReferenceCandidate(expr))) { + var flowType = getTypeAtFlowNode(flow.antecedent); + var type = getTypeFromFlowType(flowType); + if (ts.getObjectFlags(type) & 256 /* EvolvingArray */) { + var evolvedType_1 = type; + if (node.kind === 191 /* CallExpression */) { + for (var _i = 0, _a = node.arguments; _i < _a.length; _i++) { + var arg = _a[_i]; + evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, arg); + } + } + else { + // We must get the context free expression type so as to not recur in an uncached fashion on the LHS (which causes exponential blowup in compile time) + var indexType = getContextFreeTypeOfExpression(node.left.argumentExpression); + if (isTypeAssignableToKind(indexType, 296 /* NumberLike */)) { + evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, node.right); + } + } + return evolvedType_1 === type ? flowType : createFlowType(evolvedType_1, isIncomplete(flowType)); + } + return flowType; + } + } + return undefined; + } + function getTypeAtFlowCondition(flow) { + var flowType = getTypeAtFlowNode(flow.antecedent); + var type = getTypeFromFlowType(flowType); + if (type.flags & 131072 /* Never */) { + return flowType; + } + // If we have an antecedent type (meaning we're reachable in some way), we first + // attempt to narrow the antecedent type. If that produces the never type, and if + // the antecedent type is incomplete (i.e. a transient type in a loop), then we + // take the type guard as an indication that control *could* reach here once we + // have the complete type. We proceed by switching to the silent never type which + // doesn't report errors when operators are applied to it. Note that this is the + // *only* place a silent never type is ever generated. + var assumeTrue = (flow.flags & 32 /* TrueCondition */) !== 0; + var nonEvolvingType = finalizeEvolvingArrayType(type); + var narrowedType = narrowType(nonEvolvingType, flow.expression, assumeTrue); + if (narrowedType === nonEvolvingType) { + return flowType; + } + var incomplete = isIncomplete(flowType); + var resultType = incomplete && narrowedType.flags & 131072 /* Never */ ? silentNeverType : narrowedType; + return createFlowType(resultType, incomplete); + } + function getTypeAtSwitchClause(flow) { + var expr = flow.switchStatement.expression; + if (containsMatchingReferenceDiscriminant(reference, expr)) { + return declaredType; + } + var flowType = getTypeAtFlowNode(flow.antecedent); + var type = getTypeFromFlowType(flowType); + if (isMatchingReference(reference, expr)) { + type = narrowTypeBySwitchOnDiscriminant(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); + } + else if (isMatchingReferenceDiscriminant(expr, type)) { + type = narrowTypeByDiscriminant(type, expr, function (t) { return narrowTypeBySwitchOnDiscriminant(t, flow.switchStatement, flow.clauseStart, flow.clauseEnd); }); + } + else if (expr.kind === 199 /* TypeOfExpression */ && isMatchingReference(reference, expr.expression)) { + type = narrowBySwitchOnTypeOf(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); + } + return createFlowType(type, isIncomplete(flowType)); + } + function getTypeAtFlowBranchLabel(flow) { + var antecedentTypes = []; + var subtypeReduction = false; + var seenIncomplete = false; + for (var _i = 0, _a = flow.antecedents; _i < _a.length; _i++) { + var antecedent = _a[_i]; + if (antecedent.flags & 2048 /* PreFinally */ && antecedent.lock.locked) { + // if flow correspond to branch from pre-try to finally and this branch is locked - this means that + // we initially have started following the flow outside the finally block. + // in this case we should ignore this branch. + continue; + } + var flowType = getTypeAtFlowNode(antecedent); + var type = getTypeFromFlowType(flowType); + // If the type at a particular antecedent path is the declared type and the + // reference is known to always be assigned (i.e. when declared and initial types + // are the same), there is no reason to process more antecedents since the only + // possible outcome is subtypes that will be removed in the final union type anyway. + if (type === declaredType && declaredType === initialType) { + return type; + } + ts.pushIfUnique(antecedentTypes, type); + // If an antecedent type is not a subset of the declared type, we need to perform + // subtype reduction. This happens when a "foreign" type is injected into the control + // flow using the instanceof operator or a user defined type predicate. + if (!isTypeSubsetOf(type, declaredType)) { + subtypeReduction = true; + } + if (isIncomplete(flowType)) { + seenIncomplete = true; + } + } + return createFlowType(getUnionOrEvolvingArrayType(antecedentTypes, subtypeReduction ? 2 /* Subtype */ : 1 /* Literal */), seenIncomplete); + } + function getTypeAtFlowLoopLabel(flow) { + // If we have previously computed the control flow type for the reference at + // this flow loop junction, return the cached type. + var id = getFlowNodeId(flow); + var cache = flowLoopCaches[id] || (flowLoopCaches[id] = ts.createMap()); + if (!key) { + key = getFlowCacheKey(reference); + // No cache key is generated when binding patterns are in unnarrowable situations + if (!key) { + return declaredType; + } + } + var cached = cache.get(key); + if (cached) { + return cached; + } + // If this flow loop junction and reference are already being processed, return + // the union of the types computed for each branch so far, marked as incomplete. + // It is possible to see an empty array in cases where loops are nested and the + // back edge of the outer loop reaches an inner loop that is already being analyzed. + // In such cases we restart the analysis of the inner loop, which will then see + // a non-empty in-process array for the outer loop and eventually terminate because + // the first antecedent of a loop junction is always the non-looping control flow + // path that leads to the top. + for (var i = flowLoopStart; i < flowLoopCount; i++) { + if (flowLoopNodes[i] === flow && flowLoopKeys[i] === key && flowLoopTypes[i].length) { + return createFlowType(getUnionOrEvolvingArrayType(flowLoopTypes[i], 1 /* Literal */), /*incomplete*/ true); + } + } + // Add the flow loop junction and reference to the in-process stack and analyze + // each antecedent code path. + var antecedentTypes = []; + var subtypeReduction = false; + var firstAntecedentType; + flowLoopNodes[flowLoopCount] = flow; + flowLoopKeys[flowLoopCount] = key; + flowLoopTypes[flowLoopCount] = antecedentTypes; + for (var _i = 0, _a = flow.antecedents; _i < _a.length; _i++) { + var antecedent = _a[_i]; + flowLoopCount++; + var flowType = getTypeAtFlowNode(antecedent); + flowLoopCount--; + if (!firstAntecedentType) { + firstAntecedentType = flowType; + } + var type = getTypeFromFlowType(flowType); + // If we see a value appear in the cache it is a sign that control flow analysis + // was restarted and completed by checkExpressionCached. We can simply pick up + // the resulting type and bail out. + var cached_1 = cache.get(key); + if (cached_1) { + return cached_1; + } + ts.pushIfUnique(antecedentTypes, type); + // If an antecedent type is not a subset of the declared type, we need to perform + // subtype reduction. This happens when a "foreign" type is injected into the control + // flow using the instanceof operator or a user defined type predicate. + if (!isTypeSubsetOf(type, declaredType)) { + subtypeReduction = true; + } + // If the type at a particular antecedent path is the declared type there is no + // reason to process more antecedents since the only possible outcome is subtypes + // that will be removed in the final union type anyway. + if (type === declaredType) { + break; + } + } + // The result is incomplete if the first antecedent (the non-looping control flow path) + // is incomplete. + var result = getUnionOrEvolvingArrayType(antecedentTypes, subtypeReduction ? 2 /* Subtype */ : 1 /* Literal */); + if (isIncomplete(firstAntecedentType)) { + return createFlowType(result, /*incomplete*/ true); + } + cache.set(key, result); + return result; + } + function isMatchingReferenceDiscriminant(expr, computedType) { + if (!(computedType.flags & 1048576 /* Union */) || + expr.kind !== 189 /* PropertyAccessExpression */ && expr.kind !== 190 /* ElementAccessExpression */) { + return false; + } + var access = expr; + var name = getAccessedPropertyName(access); + if (!name) { + return false; + } + return isMatchingReference(reference, access.expression) && isDiscriminantProperty(computedType, name); + } + function narrowTypeByDiscriminant(type, access, narrowType) { + var propName = getAccessedPropertyName(access); + if (!propName) { + return type; + } + var propType = getTypeOfPropertyOfType(type, propName); + var narrowedPropType = propType && narrowType(propType); + return propType === narrowedPropType ? type : filterType(type, function (t) { return isTypeComparableTo(getTypeOfPropertyOfType(t, propName), narrowedPropType); }); + } + function narrowTypeByTruthiness(type, expr, assumeTrue) { + if (isMatchingReference(reference, expr)) { + return getTypeWithFacts(type, assumeTrue ? 4194304 /* Truthy */ : 8388608 /* Falsy */); + } + if (isMatchingReferenceDiscriminant(expr, declaredType)) { + return narrowTypeByDiscriminant(type, expr, function (t) { return getTypeWithFacts(t, assumeTrue ? 4194304 /* Truthy */ : 8388608 /* Falsy */); }); + } + if (containsMatchingReferenceDiscriminant(reference, expr)) { + return declaredType; + } + return type; + } + function isTypePresencePossible(type, propName, assumeTrue) { + if (getIndexInfoOfType(type, 0 /* String */)) { + return true; + } + var prop = getPropertyOfType(type, propName); + if (prop) { + return prop.flags & 16777216 /* Optional */ ? true : assumeTrue; + } + return !assumeTrue; + } + function narrowByInKeyword(type, literal, assumeTrue) { + if ((type.flags & (1048576 /* Union */ | 524288 /* Object */)) || (type.flags & 262144 /* TypeParameter */ && type.isThisType)) { + var propName_1 = ts.escapeLeadingUnderscores(literal.text); + return filterType(type, function (t) { return isTypePresencePossible(t, propName_1, assumeTrue); }); + } + return type; + } + function narrowTypeByBinaryExpression(type, expr, assumeTrue) { + switch (expr.operatorToken.kind) { + case 59 /* EqualsToken */: + return narrowTypeByTruthiness(type, expr.left, assumeTrue); + case 33 /* EqualsEqualsToken */: + case 34 /* ExclamationEqualsToken */: + case 35 /* EqualsEqualsEqualsToken */: + case 36 /* ExclamationEqualsEqualsToken */: + var operator_1 = expr.operatorToken.kind; + var left_1 = getReferenceCandidate(expr.left); + var right_1 = getReferenceCandidate(expr.right); + if (left_1.kind === 199 /* TypeOfExpression */ && ts.isStringLiteralLike(right_1)) { + return narrowTypeByTypeof(type, left_1, operator_1, right_1, assumeTrue); + } + if (right_1.kind === 199 /* TypeOfExpression */ && ts.isStringLiteralLike(left_1)) { + return narrowTypeByTypeof(type, right_1, operator_1, left_1, assumeTrue); + } + if (isMatchingReference(reference, left_1)) { + return narrowTypeByEquality(type, operator_1, right_1, assumeTrue); + } + if (isMatchingReference(reference, right_1)) { + return narrowTypeByEquality(type, operator_1, left_1, assumeTrue); + } + if (isMatchingReferenceDiscriminant(left_1, declaredType)) { + return narrowTypeByDiscriminant(type, left_1, function (t) { return narrowTypeByEquality(t, operator_1, right_1, assumeTrue); }); + } + if (isMatchingReferenceDiscriminant(right_1, declaredType)) { + return narrowTypeByDiscriminant(type, right_1, function (t) { return narrowTypeByEquality(t, operator_1, left_1, assumeTrue); }); + } + if (containsMatchingReferenceDiscriminant(reference, left_1) || containsMatchingReferenceDiscriminant(reference, right_1)) { + return declaredType; + } + break; + case 94 /* InstanceOfKeyword */: + return narrowTypeByInstanceof(type, expr, assumeTrue); + case 93 /* InKeyword */: + var target = getReferenceCandidate(expr.right); + if (ts.isStringLiteralLike(expr.left) && isMatchingReference(reference, target)) { + return narrowByInKeyword(type, expr.left, assumeTrue); + } + break; + case 27 /* CommaToken */: + return narrowType(type, expr.right, assumeTrue); + } + return type; + } + function narrowTypeByEquality(type, operator, value, assumeTrue) { + if (type.flags & 1 /* Any */) { + return type; + } + if (operator === 34 /* ExclamationEqualsToken */ || operator === 36 /* ExclamationEqualsEqualsToken */) { + assumeTrue = !assumeTrue; + } + var valueType = getTypeOfExpression(value); + if (valueType.flags & 98304 /* Nullable */) { + if (!strictNullChecks) { + return type; + } + var doubleEquals = operator === 33 /* EqualsEqualsToken */ || operator === 34 /* ExclamationEqualsToken */; + var facts = doubleEquals ? + assumeTrue ? 262144 /* EQUndefinedOrNull */ : 2097152 /* NEUndefinedOrNull */ : + valueType.flags & 65536 /* Null */ ? + assumeTrue ? 131072 /* EQNull */ : 1048576 /* NENull */ : + assumeTrue ? 65536 /* EQUndefined */ : 524288 /* NEUndefined */; + return getTypeWithFacts(type, facts); + } + if (type.flags & 67637251 /* NotUnionOrUnit */) { + return type; + } + if (assumeTrue) { + var narrowedType = filterType(type, function (t) { return areTypesComparable(t, valueType); }); + return narrowedType.flags & 131072 /* Never */ ? type : replacePrimitivesWithLiterals(narrowedType, valueType); + } + if (isUnitType(valueType)) { + var regularType_1 = getRegularTypeOfLiteralType(valueType); + return filterType(type, function (t) { return getRegularTypeOfLiteralType(t) !== regularType_1; }); + } + return type; + } + function narrowTypeByTypeof(type, typeOfExpr, operator, literal, assumeTrue) { + // We have '==', '!=', '====', or !==' operator with 'typeof xxx' and string literal operands + var target = getReferenceCandidate(typeOfExpr.expression); + if (!isMatchingReference(reference, target)) { + // For a reference of the form 'x.y', where 'x' has a narrowable declared type, a + // 'typeof x === ...' type guard resets the narrowed type of 'y' to its declared type. + if (containsMatchingReference(reference, target) && hasNarrowableDeclaredType(target)) { + return declaredType; + } + return type; + } + if (operator === 34 /* ExclamationEqualsToken */ || operator === 36 /* ExclamationEqualsEqualsToken */) { + assumeTrue = !assumeTrue; + } + if (type.flags & 1 /* Any */ && literal.text === "function") { + return type; + } + var facts = assumeTrue ? + typeofEQFacts.get(literal.text) || 128 /* TypeofEQHostObject */ : + typeofNEFacts.get(literal.text) || 32768 /* TypeofNEHostObject */; + return getTypeWithFacts(assumeTrue ? mapType(type, narrowTypeForTypeof) : type, facts); + function narrowTypeForTypeof(type) { + if (type.flags & 2 /* Unknown */ && literal.text === "object") { + return getUnionType([nonPrimitiveType, nullType]); + } + // We narrow a non-union type to an exact primitive type if the non-union type + // is a supertype of that primitive type. For example, type 'any' can be narrowed + // to one of the primitive types. + var targetType = literal.text === "function" ? globalFunctionType : typeofTypesByName.get(literal.text); + if (targetType) { + if (isTypeSubtypeOf(type, targetType)) { + return type; + } + if (isTypeSubtypeOf(targetType, type)) { + return targetType; + } + if (type.flags & 63176704 /* Instantiable */) { + var constraint = getBaseConstraintOfType(type) || anyType; + if (isTypeSubtypeOf(targetType, constraint)) { + return getIntersectionType([type, targetType]); + } + } + } + return type; + } + } + function narrowTypeBySwitchOnDiscriminant(type, switchStatement, clauseStart, clauseEnd) { + // We only narrow if all case expressions specify values with unit types + var switchTypes = getSwitchClauseTypes(switchStatement); + if (!switchTypes.length) { + return type; + } + var clauseTypes = switchTypes.slice(clauseStart, clauseEnd); + var hasDefaultClause = clauseStart === clauseEnd || ts.contains(clauseTypes, neverType); + var discriminantType = getUnionType(clauseTypes); + var caseType = discriminantType.flags & 131072 /* Never */ ? neverType : + replacePrimitivesWithLiterals(filterType(type, function (t) { return areTypesComparable(discriminantType, t); }), discriminantType); + if (!hasDefaultClause) { + return caseType; + } + var defaultType = filterType(type, function (t) { return !(isUnitType(t) && ts.contains(switchTypes, getRegularTypeOfLiteralType(t))); }); + return caseType.flags & 131072 /* Never */ ? defaultType : getUnionType([caseType, defaultType]); + } + function getImpliedTypeFromTypeofCase(type, text) { + switch (text) { + case "function": + return type.flags & 1 /* Any */ ? type : globalFunctionType; + case "object": + return type.flags & 2 /* Unknown */ ? getUnionType([nonPrimitiveType, nullType]) : type; + default: + return typeofTypesByName.get(text) || type; + } + } + function narrowTypeForTypeofSwitch(candidate) { + return function (type) { + if (isTypeSubtypeOf(candidate, type)) { + return candidate; + } + if (type.flags & 63176704 /* Instantiable */) { + var constraint = getBaseConstraintOfType(type) || anyType; + if (isTypeSubtypeOf(candidate, constraint)) { + return getIntersectionType([type, candidate]); + } + } + return type; + }; + } + function narrowBySwitchOnTypeOf(type, switchStatement, clauseStart, clauseEnd) { + var switchWitnesses = getSwitchClauseTypeOfWitnesses(switchStatement); + if (!switchWitnesses.length) { + return type; + } + // Equal start and end denotes implicit fallthrough; undefined marks explicit default clause + var defaultCaseLocation = ts.findIndex(switchWitnesses, function (elem) { return elem === undefined; }); + var hasDefaultClause = clauseStart === clauseEnd || (defaultCaseLocation >= clauseStart && defaultCaseLocation < clauseEnd); + var clauseWitnesses; + var switchFacts; + if (defaultCaseLocation > -1) { + // We no longer need the undefined denoting an + // explicit default case. Remove the undefined and + // fix-up clauseStart and clauseEnd. This means + // that we don't have to worry about undefined + // in the witness array. + var witnesses = switchWitnesses.filter(function (witness) { return witness !== undefined; }); + // The adjusted clause start and end after removing the `default` statement. + var fixedClauseStart = defaultCaseLocation < clauseStart ? clauseStart - 1 : clauseStart; + var fixedClauseEnd = defaultCaseLocation < clauseEnd ? clauseEnd - 1 : clauseEnd; + clauseWitnesses = witnesses.slice(fixedClauseStart, fixedClauseEnd); + switchFacts = getFactsFromTypeofSwitch(fixedClauseStart, fixedClauseEnd, witnesses, hasDefaultClause); + } + else { + clauseWitnesses = switchWitnesses.slice(clauseStart, clauseEnd); + switchFacts = getFactsFromTypeofSwitch(clauseStart, clauseEnd, switchWitnesses, hasDefaultClause); + } + if (hasDefaultClause) { + return filterType(type, function (t) { return (getTypeFacts(t) & switchFacts) === switchFacts; }); + } + /* + The implied type is the raw type suggested by a + value being caught in this clause. + + When the clause contains a default case we ignore + the implied type and try to narrow using any facts + we can learn: see `switchFacts`. + + Example: + switch (typeof x) { + case 'number': + case 'string': break; + default: break; + case 'number': + case 'boolean': break + } + + In the first clause (case `number` and `string`) the + implied type is number | string. + + In the default clause we de not compute an implied type. + + In the third clause (case `number` and `boolean`) + the naive implied type is number | boolean, however + we use the type facts to narrow the implied type to + boolean. We know that number cannot be selected + because it is caught in the first clause. + */ + var impliedType = getTypeWithFacts(getUnionType(clauseWitnesses.map(function (text) { return getImpliedTypeFromTypeofCase(type, text); })), switchFacts); + if (impliedType.flags & 1048576 /* Union */) { + impliedType = getAssignmentReducedType(impliedType, getBaseConstraintOrType(type)); + } + return getTypeWithFacts(mapType(type, narrowTypeForTypeofSwitch(impliedType)), switchFacts); + } + function narrowTypeByInstanceof(type, expr, assumeTrue) { + var left = getReferenceCandidate(expr.left); + if (!isMatchingReference(reference, left)) { + // For a reference of the form 'x.y', where 'x' has a narrowable declared type, an + // 'x instanceof T' type guard resets the narrowed type of 'y' to its declared type. + if (containsMatchingReference(reference, left) && hasNarrowableDeclaredType(left)) { + return declaredType; + } + return type; + } + // Check that right operand is a function type with a prototype property + var rightType = getTypeOfExpression(expr.right); + if (!isTypeDerivedFrom(rightType, globalFunctionType)) { + return type; + } + var targetType; + var prototypeProperty = getPropertyOfType(rightType, "prototype"); + if (prototypeProperty) { + // Target type is type of the prototype property + var prototypePropertyType = getTypeOfSymbol(prototypeProperty); + if (!isTypeAny(prototypePropertyType)) { + targetType = prototypePropertyType; + } + } + // Don't narrow from 'any' if the target type is exactly 'Object' or 'Function' + if (isTypeAny(type) && (targetType === globalObjectType || targetType === globalFunctionType)) { + return type; + } + if (!targetType) { + var constructSignatures = getSignaturesOfType(rightType, 1 /* Construct */); + targetType = constructSignatures.length ? + getUnionType(ts.map(constructSignatures, function (signature) { return getReturnTypeOfSignature(getErasedSignature(signature)); })) : + emptyObjectType; + } + return getNarrowedType(type, targetType, assumeTrue, isTypeDerivedFrom); + } + function getNarrowedType(type, candidate, assumeTrue, isRelated) { + if (!assumeTrue) { + return filterType(type, function (t) { return !isRelated(t, candidate); }); + } + // If the current type is a union type, remove all constituents that couldn't be instances of + // the candidate type. If one or more constituents remain, return a union of those. + if (type.flags & 1048576 /* Union */) { + var assignableType = filterType(type, function (t) { return isRelated(t, candidate); }); + if (!(assignableType.flags & 131072 /* Never */)) { + return assignableType; + } + } + // If the candidate type is a subtype of the target type, narrow to the candidate type. + // Otherwise, if the target type is assignable to the candidate type, keep the target type. + // Otherwise, if the candidate type is assignable to the target type, narrow to the candidate + // type. Otherwise, the types are completely unrelated, so narrow to an intersection of the + // two types. + return isTypeSubtypeOf(candidate, type) ? candidate : + isTypeAssignableTo(type, candidate) ? type : + isTypeAssignableTo(candidate, type) ? candidate : + getIntersectionType([type, candidate]); + } + function narrowTypeByTypePredicate(type, callExpression, assumeTrue) { + if (!hasMatchingArgument(callExpression, reference) || !maybeTypePredicateCall(callExpression)) { + return type; + } + var signature = getResolvedSignature(callExpression); + var predicate = getTypePredicateOfSignature(signature); + if (!predicate) { + return type; + } + // Don't narrow from 'any' if the predicate type is exactly 'Object' or 'Function' + if (isTypeAny(type) && (predicate.type === globalObjectType || predicate.type === globalFunctionType)) { + return type; + } + if (ts.isIdentifierTypePredicate(predicate)) { + var predicateArgument = callExpression.arguments[predicate.parameterIndex - (signature.thisParameter ? 1 : 0)]; + if (predicateArgument) { + if (isMatchingReference(reference, predicateArgument)) { + return getNarrowedType(type, predicate.type, assumeTrue, isTypeSubtypeOf); + } + if (containsMatchingReference(reference, predicateArgument)) { + return declaredType; + } + } + } + else { + var invokedExpression = ts.skipParentheses(callExpression.expression); + if (invokedExpression.kind === 190 /* ElementAccessExpression */ || invokedExpression.kind === 189 /* PropertyAccessExpression */) { + var accessExpression = invokedExpression; + var possibleReference = ts.skipParentheses(accessExpression.expression); + if (isMatchingReference(reference, possibleReference)) { + return getNarrowedType(type, predicate.type, assumeTrue, isTypeSubtypeOf); + } + if (containsMatchingReference(reference, possibleReference)) { + return declaredType; + } + } + } + return type; + } + // Narrow the given type based on the given expression having the assumed boolean value. The returned type + // will be a subtype or the same type as the argument. + function narrowType(type, expr, assumeTrue) { + switch (expr.kind) { + case 72 /* Identifier */: + case 100 /* ThisKeyword */: + case 98 /* SuperKeyword */: + case 189 /* PropertyAccessExpression */: + case 190 /* ElementAccessExpression */: + return narrowTypeByTruthiness(type, expr, assumeTrue); + case 191 /* CallExpression */: + return narrowTypeByTypePredicate(type, expr, assumeTrue); + case 195 /* ParenthesizedExpression */: + return narrowType(type, expr.expression, assumeTrue); + case 204 /* BinaryExpression */: + return narrowTypeByBinaryExpression(type, expr, assumeTrue); + case 202 /* PrefixUnaryExpression */: + if (expr.operator === 52 /* ExclamationToken */) { + return narrowType(type, expr.operand, !assumeTrue); + } + break; + } + return type; + } + } + function getTypeOfSymbolAtLocation(symbol, location) { + symbol = symbol.exportSymbol || symbol; + // If we have an identifier or a property access at the given location, if the location is + // an dotted name expression, and if the location is not an assignment target, obtain the type + // of the expression (which will reflect control flow analysis). If the expression indeed + // resolved to the given symbol, return the narrowed type. + if (location.kind === 72 /* Identifier */) { + if (ts.isRightSideOfQualifiedNameOrPropertyAccess(location)) { + location = location.parent; + } + if (ts.isExpressionNode(location) && !ts.isAssignmentTarget(location)) { + var type = getTypeOfExpression(location); + if (getExportSymbolOfValueSymbolIfExported(getNodeLinks(location).resolvedSymbol) === symbol) { + return type; + } + } + } + // The location isn't a reference to the given symbol, meaning we're being asked + // a hypothetical question of what type the symbol would have if there was a reference + // to it at the given location. Since we have no control flow information for the + // hypothetical reference (control flow information is created and attached by the + // binder), we simply return the declared type of the symbol. + return getTypeOfSymbol(symbol); + } + function getControlFlowContainer(node) { + return ts.findAncestor(node.parent, function (node) { + return ts.isFunctionLike(node) && !ts.getImmediatelyInvokedFunctionExpression(node) || + node.kind === 245 /* ModuleBlock */ || + node.kind === 279 /* SourceFile */ || + node.kind === 154 /* PropertyDeclaration */; + }); + } + // Check if a parameter is assigned anywhere within its declaring function. + function isParameterAssigned(symbol) { + var func = ts.getRootDeclaration(symbol.valueDeclaration).parent; + var links = getNodeLinks(func); + if (!(links.flags & 8388608 /* AssignmentsMarked */)) { + links.flags |= 8388608 /* AssignmentsMarked */; + if (!hasParentWithAssignmentsMarked(func)) { + markParameterAssignments(func); + } + } + return symbol.isAssigned || false; + } + function hasParentWithAssignmentsMarked(node) { + return !!ts.findAncestor(node.parent, function (node) { return ts.isFunctionLike(node) && !!(getNodeLinks(node).flags & 8388608 /* AssignmentsMarked */); }); + } + function markParameterAssignments(node) { + if (node.kind === 72 /* Identifier */) { + if (ts.isAssignmentTarget(node)) { + var symbol = getResolvedSymbol(node); + if (symbol.valueDeclaration && ts.getRootDeclaration(symbol.valueDeclaration).kind === 151 /* Parameter */) { + symbol.isAssigned = true; + } + } + } + else { + ts.forEachChild(node, markParameterAssignments); + } + } + function isConstVariable(symbol) { + return symbol.flags & 3 /* Variable */ && (getDeclarationNodeFlagsFromSymbol(symbol) & 2 /* Const */) !== 0 && getTypeOfSymbol(symbol) !== autoArrayType; + } + /** remove undefined from the annotated type of a parameter when there is an initializer (that doesn't include undefined) */ + function removeOptionalityFromDeclaredType(declaredType, declaration) { + var annotationIncludesUndefined = strictNullChecks && + declaration.kind === 151 /* Parameter */ && + declaration.initializer && + getFalsyFlags(declaredType) & 32768 /* Undefined */ && + !(getFalsyFlags(checkExpression(declaration.initializer)) & 32768 /* Undefined */); + return annotationIncludesUndefined ? getTypeWithFacts(declaredType, 524288 /* NEUndefined */) : declaredType; + } + function isConstraintPosition(node) { + var parent = node.parent; + return parent.kind === 189 /* PropertyAccessExpression */ || + parent.kind === 191 /* CallExpression */ && parent.expression === node || + parent.kind === 190 /* ElementAccessExpression */ && parent.expression === node || + parent.kind === 186 /* BindingElement */ && parent.name === node && !!parent.initializer; + } + function typeHasNullableConstraint(type) { + return type.flags & 58982400 /* InstantiableNonPrimitive */ && maybeTypeOfKind(getBaseConstraintOfType(type) || emptyObjectType, 98304 /* Nullable */); + } + function getConstraintForLocation(type, node) { + // When a node is the left hand expression of a property access, element access, or call expression, + // and the type of the node includes type variables with constraints that are nullable, we fetch the + // apparent type of the node *before* performing control flow analysis such that narrowings apply to + // the constraint type. + if (type && isConstraintPosition(node) && forEachType(type, typeHasNullableConstraint)) { + return mapType(getWidenedType(type), getBaseConstraintOrType); + } + return type; + } + function markAliasReferenced(symbol, location) { + if (isNonLocalAlias(symbol, /*excludes*/ 67220415 /* Value */) && !isInTypeQuery(location) && !isConstEnumOrConstEnumOnlyModule(resolveAlias(symbol))) { + markAliasSymbolAsReferenced(symbol); + } + } + function checkIdentifier(node) { + var symbol = getResolvedSymbol(node); + if (symbol === unknownSymbol) { + return errorType; + } + // As noted in ECMAScript 6 language spec, arrow functions never have an arguments objects. + // Although in down-level emit of arrow function, we emit it using function expression which means that + // arguments objects will be bound to the inner object; emitting arrow function natively in ES6, arguments objects + // will be bound to non-arrow function that contain this arrow function. This results in inconsistent behavior. + // To avoid that we will give an error to users if they use arguments objects in arrow function so that they + // can explicitly bound arguments objects + if (symbol === argumentsSymbol) { + var container = ts.getContainingFunction(node); + if (languageVersion < 2 /* ES2015 */) { + if (container.kind === 197 /* ArrowFunction */) { + error(node, ts.Diagnostics.The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_standard_function_expression); + } + else if (ts.hasModifier(container, 256 /* Async */)) { + error(node, ts.Diagnostics.The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_using_a_standard_function_or_method); + } + } + getNodeLinks(container).flags |= 8192 /* CaptureArguments */; + return getTypeOfSymbol(symbol); + } + // We should only mark aliases as referenced if there isn't a local value declaration + // for the symbol. Also, don't mark any property access expression LHS - checkPropertyAccessExpression will handle that + if (!(node.parent && ts.isPropertyAccessExpression(node.parent) && node.parent.expression === node)) { + markAliasReferenced(symbol, node); + } + var localOrExportSymbol = getExportSymbolOfValueSymbolIfExported(symbol); + var declaration = localOrExportSymbol.valueDeclaration; + if (localOrExportSymbol.flags & 32 /* Class */) { + // Due to the emit for class decorators, any reference to the class from inside of the class body + // must instead be rewritten to point to a temporary variable to avoid issues with the double-bind + // behavior of class names in ES6. + if (declaration.kind === 240 /* ClassDeclaration */ + && ts.nodeIsDecorated(declaration)) { + var container = ts.getContainingClass(node); + while (container !== undefined) { + if (container === declaration && container.name !== node) { + getNodeLinks(declaration).flags |= 16777216 /* ClassWithConstructorReference */; + getNodeLinks(node).flags |= 33554432 /* ConstructorReferenceInClass */; + break; + } + container = ts.getContainingClass(container); + } + } + else if (declaration.kind === 209 /* ClassExpression */) { + // When we emit a class expression with static members that contain a reference + // to the constructor in the initializer, we will need to substitute that + // binding with an alias as the class name is not in scope. + var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); + while (container.kind !== 279 /* SourceFile */) { + if (container.parent === declaration) { + if (container.kind === 154 /* PropertyDeclaration */ && ts.hasModifier(container, 32 /* Static */)) { + getNodeLinks(declaration).flags |= 16777216 /* ClassWithConstructorReference */; + getNodeLinks(node).flags |= 33554432 /* ConstructorReferenceInClass */; + } + break; + } + container = ts.getThisContainer(container, /*includeArrowFunctions*/ false); + } + } + } + checkNestedBlockScopedBinding(node, symbol); + var type = getConstraintForLocation(getTypeOfSymbol(localOrExportSymbol), node); + var assignmentKind = ts.getAssignmentTargetKind(node); + if (assignmentKind) { + if (!(localOrExportSymbol.flags & 3 /* Variable */) && + !(ts.isInJSFile(node) && localOrExportSymbol.flags & 512 /* ValueModule */)) { + error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_not_a_variable, symbolToString(symbol)); + return errorType; + } + if (isReadonlySymbol(localOrExportSymbol)) { + if (localOrExportSymbol.flags & 3 /* Variable */) { + error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant, symbolToString(symbol)); + } + else { + error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, symbolToString(symbol)); + } + return errorType; + } + } + var isAlias = localOrExportSymbol.flags & 2097152 /* Alias */; + // We only narrow variables and parameters occurring in a non-assignment position. For all other + // entities we simply return the declared type. + if (localOrExportSymbol.flags & 3 /* Variable */) { + if (assignmentKind === 1 /* Definite */) { + return type; + } + } + else if (isAlias) { + declaration = ts.find(symbol.declarations, isSomeImportDeclaration); + } + else { + return type; + } + if (!declaration) { + return type; + } + // The declaration container is the innermost function that encloses the declaration of the variable + // or parameter. The flow container is the innermost function starting with which we analyze the control + // flow graph to determine the control flow based type. + var isParameter = ts.getRootDeclaration(declaration).kind === 151 /* Parameter */; + var declarationContainer = getControlFlowContainer(declaration); + var flowContainer = getControlFlowContainer(node); + var isOuterVariable = flowContainer !== declarationContainer; + var isSpreadDestructuringAssignmentTarget = node.parent && node.parent.parent && ts.isSpreadAssignment(node.parent) && isDestructuringAssignmentTarget(node.parent.parent); + var isModuleExports = symbol.flags & 134217728 /* ModuleExports */; + // When the control flow originates in a function expression or arrow function and we are referencing + // a const variable or parameter from an outer function, we extend the origin of the control flow + // analysis to include the immediately enclosing function. + while (flowContainer !== declarationContainer && (flowContainer.kind === 196 /* FunctionExpression */ || + flowContainer.kind === 197 /* ArrowFunction */ || ts.isObjectLiteralOrClassExpressionMethod(flowContainer)) && + (isConstVariable(localOrExportSymbol) || isParameter && !isParameterAssigned(localOrExportSymbol))) { + flowContainer = getControlFlowContainer(flowContainer); + } + // We only look for uninitialized variables in strict null checking mode, and only when we can analyze + // the entire control flow graph from the variable's declaration (i.e. when the flow container and + // declaration container are the same). + var assumeInitialized = isParameter || isAlias || isOuterVariable || isSpreadDestructuringAssignmentTarget || isModuleExports || + type !== autoType && type !== autoArrayType && (!strictNullChecks || (type.flags & 3 /* AnyOrUnknown */) !== 0 || + isInTypeQuery(node) || node.parent.kind === 257 /* ExportSpecifier */) || + node.parent.kind === 213 /* NonNullExpression */ || + declaration.kind === 237 /* VariableDeclaration */ && declaration.exclamationToken || + declaration.flags & 4194304 /* Ambient */; + var initialType = assumeInitialized ? (isParameter ? removeOptionalityFromDeclaredType(type, declaration) : type) : + type === autoType || type === autoArrayType ? undefinedType : + getOptionalType(type); + var flowType = getFlowTypeOfReference(node, type, initialType, flowContainer, !assumeInitialized); + // A variable is considered uninitialized when it is possible to analyze the entire control flow graph + // from declaration to use, and when the variable's declared type doesn't include undefined but the + // control flow based type does include undefined. + if (!isEvolvingArrayOperationTarget(node) && (type === autoType || type === autoArrayType)) { + if (flowType === autoType || flowType === autoArrayType) { + if (noImplicitAny) { + error(ts.getNameOfDeclaration(declaration), ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined, symbolToString(symbol), typeToString(flowType)); + error(node, ts.Diagnostics.Variable_0_implicitly_has_an_1_type, symbolToString(symbol), typeToString(flowType)); + } + return convertAutoToAny(flowType); + } + } + else if (!assumeInitialized && !(getFalsyFlags(type) & 32768 /* Undefined */) && getFalsyFlags(flowType) & 32768 /* Undefined */) { + error(node, ts.Diagnostics.Variable_0_is_used_before_being_assigned, symbolToString(symbol)); + // Return the declared type to reduce follow-on errors + return type; + } + return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType; + } + function isInsideFunction(node, threshold) { + return !!ts.findAncestor(node, function (n) { return n === threshold ? "quit" : ts.isFunctionLike(n); }); + } + function getPartOfForStatementContainingNode(node, container) { + return ts.findAncestor(node, function (n) { return n === container ? "quit" : n === container.initializer || n === container.condition || n === container.incrementor || n === container.statement; }); + } + function checkNestedBlockScopedBinding(node, symbol) { + if (languageVersion >= 2 /* ES2015 */ || + (symbol.flags & (2 /* BlockScopedVariable */ | 32 /* Class */)) === 0 || + symbol.valueDeclaration.parent.kind === 274 /* CatchClause */) { + return; + } + // 1. walk from the use site up to the declaration and check + // if there is anything function like between declaration and use-site (is binding/class is captured in function). + // 2. walk from the declaration up to the boundary of lexical environment and check + // if there is an iteration statement in between declaration and boundary (is binding/class declared inside iteration statement) + var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); + var usedInFunction = isInsideFunction(node.parent, container); + var current = container; + var containedInIterationStatement = false; + while (current && !ts.nodeStartsNewLexicalEnvironment(current)) { + if (ts.isIterationStatement(current, /*lookInLabeledStatements*/ false)) { + containedInIterationStatement = true; + break; + } + current = current.parent; + } + if (containedInIterationStatement) { + if (usedInFunction) { + // mark iteration statement as containing block-scoped binding captured in some function + var capturesBlockScopeBindingInLoopBody = true; + if (ts.isForStatement(container) && + ts.getAncestor(symbol.valueDeclaration, 238 /* VariableDeclarationList */).parent === container) { + var part = getPartOfForStatementContainingNode(node.parent, container); + if (part) { + var links = getNodeLinks(part); + links.flags |= 131072 /* ContainsCapturedBlockScopeBinding */; + var capturedBindings = links.capturedBlockScopeBindings || (links.capturedBlockScopeBindings = []); + ts.pushIfUnique(capturedBindings, symbol); + if (part === container.initializer) { + capturesBlockScopeBindingInLoopBody = false; // Initializer is outside of loop body + } + } + } + if (capturesBlockScopeBindingInLoopBody) { + getNodeLinks(current).flags |= 65536 /* LoopWithCapturedBlockScopedBinding */; + } + } + // mark variables that are declared in loop initializer and reassigned inside the body of ForStatement. + // if body of ForStatement will be converted to function then we'll need a extra machinery to propagate reassigned values back. + if (container.kind === 225 /* ForStatement */ && + ts.getAncestor(symbol.valueDeclaration, 238 /* VariableDeclarationList */).parent === container && + isAssignedInBodyOfForStatement(node, container)) { + getNodeLinks(symbol.valueDeclaration).flags |= 4194304 /* NeedsLoopOutParameter */; + } + // set 'declared inside loop' bit on the block-scoped binding + getNodeLinks(symbol.valueDeclaration).flags |= 524288 /* BlockScopedBindingInLoop */; + } + if (usedInFunction) { + getNodeLinks(symbol.valueDeclaration).flags |= 262144 /* CapturedBlockScopedBinding */; + } + } + function isBindingCapturedByNode(node, decl) { + var links = getNodeLinks(node); + return !!links && ts.contains(links.capturedBlockScopeBindings, getSymbolOfNode(decl)); + } + function isAssignedInBodyOfForStatement(node, container) { + // skip parenthesized nodes + var current = node; + while (current.parent.kind === 195 /* ParenthesizedExpression */) { + current = current.parent; + } + // check if node is used as LHS in some assignment expression + var isAssigned = false; + if (ts.isAssignmentTarget(current)) { + isAssigned = true; + } + else if ((current.parent.kind === 202 /* PrefixUnaryExpression */ || current.parent.kind === 203 /* PostfixUnaryExpression */)) { + var expr = current.parent; + isAssigned = expr.operator === 44 /* PlusPlusToken */ || expr.operator === 45 /* MinusMinusToken */; + } + if (!isAssigned) { + return false; + } + // at this point we know that node is the target of assignment + // now check that modification happens inside the statement part of the ForStatement + return !!ts.findAncestor(current, function (n) { return n === container ? "quit" : n === container.statement; }); + } + function captureLexicalThis(node, container) { + getNodeLinks(node).flags |= 2 /* LexicalThis */; + if (container.kind === 154 /* PropertyDeclaration */ || container.kind === 157 /* Constructor */) { + var classNode = container.parent; + getNodeLinks(classNode).flags |= 4 /* CaptureThis */; + } + else { + getNodeLinks(container).flags |= 4 /* CaptureThis */; + } + } + function findFirstSuperCall(n) { + if (ts.isSuperCall(n)) { + return n; + } + else if (ts.isFunctionLike(n)) { + return undefined; + } + return ts.forEachChild(n, findFirstSuperCall); + } + /** + * Return a cached result if super-statement is already found. + * Otherwise, find a super statement in a given constructor function and cache the result in the node-links of the constructor + * + * @param constructor constructor-function to look for super statement + */ + function getSuperCallInConstructor(constructor) { + var links = getNodeLinks(constructor); + // Only trying to find super-call if we haven't yet tried to find one. Once we try, we will record the result + if (links.hasSuperCall === undefined) { + links.superCall = findFirstSuperCall(constructor.body); + links.hasSuperCall = links.superCall ? true : false; + } + return links.superCall; + } + /** + * Check if the given class-declaration extends null then return true. + * Otherwise, return false + * @param classDecl a class declaration to check if it extends null + */ + function classDeclarationExtendsNull(classDecl) { + var classSymbol = getSymbolOfNode(classDecl); + var classInstanceType = getDeclaredTypeOfSymbol(classSymbol); + var baseConstructorType = getBaseConstructorTypeOfClass(classInstanceType); + return baseConstructorType === nullWideningType; + } + function checkThisBeforeSuper(node, container, diagnosticMessage) { + var containingClassDecl = container.parent; + var baseTypeNode = ts.getEffectiveBaseTypeNode(containingClassDecl); + // If a containing class does not have extends clause or the class extends null + // skip checking whether super statement is called before "this" accessing. + if (baseTypeNode && !classDeclarationExtendsNull(containingClassDecl)) { + var superCall = getSuperCallInConstructor(container); + // We should give an error in the following cases: + // - No super-call + // - "this" is accessing before super-call. + // i.e super(this) + // this.x; super(); + // We want to make sure that super-call is done before accessing "this" so that + // "this" is not accessed as a parameter of the super-call. + if (!superCall || superCall.end > node.pos) { + // In ES6, super inside constructor of class-declaration has to precede "this" accessing + error(node, diagnosticMessage); + } + } + } + function checkThisExpression(node) { + // Stop at the first arrow function so that we can + // tell whether 'this' needs to be captured. + var container = ts.getThisContainer(node, /* includeArrowFunctions */ true); + var capturedByArrowFunction = false; + if (container.kind === 157 /* Constructor */) { + checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class); + } + // Now skip arrow functions to get the "real" owner of 'this'. + if (container.kind === 197 /* ArrowFunction */) { + container = ts.getThisContainer(container, /* includeArrowFunctions */ false); + capturedByArrowFunction = true; + } + switch (container.kind) { + case 244 /* ModuleDeclaration */: + error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_module_or_namespace_body); + // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks + break; + case 243 /* EnumDeclaration */: + error(node, ts.Diagnostics.this_cannot_be_referenced_in_current_location); + // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks + break; + case 157 /* Constructor */: + if (isInConstructorArgumentInitializer(node, container)) { + error(node, ts.Diagnostics.this_cannot_be_referenced_in_constructor_arguments); + // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks + } + break; + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + if (ts.hasModifier(container, 32 /* Static */)) { + error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_static_property_initializer); + // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks + } + break; + case 149 /* ComputedPropertyName */: + error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_computed_property_name); + break; + } + // When targeting es6, mark that we'll need to capture `this` in its lexically bound scope. + if (capturedByArrowFunction && languageVersion < 2 /* ES2015 */) { + captureLexicalThis(node, container); + } + var type = tryGetThisTypeAt(node, container); + if (!type && noImplicitThis) { + // With noImplicitThis, functions may not reference 'this' if it has type 'any' + var diag = error(node, capturedByArrowFunction && container.kind === 279 /* SourceFile */ ? + ts.Diagnostics.The_containing_arrow_function_captures_the_global_value_of_this_which_implicitly_has_type_any : + ts.Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation); + if (!ts.isSourceFile(container)) { + var outsideThis = tryGetThisTypeAt(container); + if (outsideThis) { + addRelatedInfo(diag, ts.createDiagnosticForNode(container, ts.Diagnostics.An_outer_value_of_this_is_shadowed_by_this_container)); + } + } + } + return type || anyType; + } + function tryGetThisTypeAt(node, container) { + if (container === void 0) { container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); } + var isInJS = ts.isInJSFile(node); + if (ts.isFunctionLike(container) && + (!isInParameterInitializerBeforeContainingFunction(node) || ts.getThisParameter(container))) { + // Note: a parameter initializer should refer to class-this unless function-this is explicitly annotated. + // If this is a function in a JS file, it might be a class method. + var className = getClassNameFromPrototypeMethod(container); + if (isInJS && className) { + var classSymbol = checkExpression(className).symbol; + if (classSymbol && classSymbol.members && (classSymbol.flags & 16 /* Function */)) { + var classType = getJSClassType(classSymbol); + if (classType) { + return getFlowTypeOfReference(node, classType); + } + } + } + // Check if it's a constructor definition, can be either a variable decl or function decl + // i.e. + // * /** @constructor */ function [name]() { ... } + // * /** @constructor */ var x = function() { ... } + else if (isInJS && + (container.kind === 196 /* FunctionExpression */ || container.kind === 239 /* FunctionDeclaration */) && + ts.getJSDocClassTag(container)) { + var classType = getJSClassType(container.symbol); + if (classType) { + return getFlowTypeOfReference(node, classType); + } + } + var thisType = getThisTypeOfDeclaration(container) || getContextualThisParameterType(container); + if (thisType) { + return getFlowTypeOfReference(node, thisType); + } + } + if (ts.isClassLike(container.parent)) { + var symbol = getSymbolOfNode(container.parent); + var type = ts.hasModifier(container, 32 /* Static */) ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol).thisType; + return getFlowTypeOfReference(node, type); + } + if (isInJS) { + var type = getTypeForThisExpressionFromJSDoc(container); + if (type && type !== errorType) { + return getFlowTypeOfReference(node, type); + } + } + } + function getClassNameFromPrototypeMethod(container) { + // Check if it's the RHS of a x.prototype.y = function [name]() { .... } + if (container.kind === 196 /* FunctionExpression */ && + ts.isBinaryExpression(container.parent) && + ts.getAssignmentDeclarationKind(container.parent) === 3 /* PrototypeProperty */) { + // Get the 'x' of 'x.prototype.y = container' + return container.parent // x.prototype.y = container + .left // x.prototype.y + .expression // x.prototype + .expression; // x + } + // x.prototype = { method() { } } + else if (container.kind === 156 /* MethodDeclaration */ && + container.parent.kind === 188 /* ObjectLiteralExpression */ && + ts.isBinaryExpression(container.parent.parent) && + ts.getAssignmentDeclarationKind(container.parent.parent) === 6 /* Prototype */) { + return container.parent.parent.left.expression; + } + // x.prototype = { method: function() { } } + else if (container.kind === 196 /* FunctionExpression */ && + container.parent.kind === 275 /* PropertyAssignment */ && + container.parent.parent.kind === 188 /* ObjectLiteralExpression */ && + ts.isBinaryExpression(container.parent.parent.parent) && + ts.getAssignmentDeclarationKind(container.parent.parent.parent) === 6 /* Prototype */) { + return container.parent.parent.parent.left.expression; + } + // Object.defineProperty(x, "method", { value: function() { } }); + // Object.defineProperty(x, "method", { set: (x: () => void) => void }); + // Object.defineProperty(x, "method", { get: () => function() { }) }); + else if (container.kind === 196 /* FunctionExpression */ && + ts.isPropertyAssignment(container.parent) && + ts.isIdentifier(container.parent.name) && + (container.parent.name.escapedText === "value" || container.parent.name.escapedText === "get" || container.parent.name.escapedText === "set") && + ts.isObjectLiteralExpression(container.parent.parent) && + ts.isCallExpression(container.parent.parent.parent) && + container.parent.parent.parent.arguments[2] === container.parent.parent && + ts.getAssignmentDeclarationKind(container.parent.parent.parent) === 9 /* ObjectDefinePrototypeProperty */) { + return container.parent.parent.parent.arguments[0].expression; + } + // Object.defineProperty(x, "method", { value() { } }); + // Object.defineProperty(x, "method", { set(x: () => void) {} }); + // Object.defineProperty(x, "method", { get() { return () => {} } }); + else if (ts.isMethodDeclaration(container) && + ts.isIdentifier(container.name) && + (container.name.escapedText === "value" || container.name.escapedText === "get" || container.name.escapedText === "set") && + ts.isObjectLiteralExpression(container.parent) && + ts.isCallExpression(container.parent.parent) && + container.parent.parent.arguments[2] === container.parent && + ts.getAssignmentDeclarationKind(container.parent.parent) === 9 /* ObjectDefinePrototypeProperty */) { + return container.parent.parent.arguments[0].expression; + } + } + function getTypeForThisExpressionFromJSDoc(node) { + var jsdocType = ts.getJSDocType(node); + if (jsdocType && jsdocType.kind === 289 /* JSDocFunctionType */) { + var jsDocFunctionType = jsdocType; + if (jsDocFunctionType.parameters.length > 0 && + jsDocFunctionType.parameters[0].name && + jsDocFunctionType.parameters[0].name.escapedText === "this" /* This */) { + return getTypeFromTypeNode(jsDocFunctionType.parameters[0].type); + } + } + var thisTag = ts.getJSDocThisTag(node); + if (thisTag && thisTag.typeExpression) { + return getTypeFromTypeNode(thisTag.typeExpression); + } + } + function isInConstructorArgumentInitializer(node, constructorDecl) { + return !!ts.findAncestor(node, function (n) { return n === constructorDecl ? "quit" : n.kind === 151 /* Parameter */; }); + } + function checkSuperExpression(node) { + var isCallExpression = node.parent.kind === 191 /* CallExpression */ && node.parent.expression === node; + var container = ts.getSuperContainer(node, /*stopOnFunctions*/ true); + var needToCaptureLexicalThis = false; + // adjust the container reference in case if super is used inside arrow functions with arbitrarily deep nesting + if (!isCallExpression) { + while (container && container.kind === 197 /* ArrowFunction */) { + container = ts.getSuperContainer(container, /*stopOnFunctions*/ true); + needToCaptureLexicalThis = languageVersion < 2 /* ES2015 */; + } + } + var canUseSuperExpression = isLegalUsageOfSuperExpression(container); + var nodeCheckFlag = 0; + if (!canUseSuperExpression) { + // issue more specific error if super is used in computed property name + // class A { foo() { return "1" }} + // class B { + // [super.foo()]() {} + // } + var current = ts.findAncestor(node, function (n) { return n === container ? "quit" : n.kind === 149 /* ComputedPropertyName */; }); + if (current && current.kind === 149 /* ComputedPropertyName */) { + error(node, ts.Diagnostics.super_cannot_be_referenced_in_a_computed_property_name); + } + else if (isCallExpression) { + error(node, ts.Diagnostics.Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors); + } + else if (!container || !container.parent || !(ts.isClassLike(container.parent) || container.parent.kind === 188 /* ObjectLiteralExpression */)) { + error(node, ts.Diagnostics.super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions); + } + else { + error(node, ts.Diagnostics.super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_derived_class); + } + return errorType; + } + if (!isCallExpression && container.kind === 157 /* Constructor */) { + checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class); + } + if (ts.hasModifier(container, 32 /* Static */) || isCallExpression) { + nodeCheckFlag = 512 /* SuperStatic */; + } + else { + nodeCheckFlag = 256 /* SuperInstance */; + } + getNodeLinks(node).flags |= nodeCheckFlag; + // Due to how we emit async functions, we need to specialize the emit for an async method that contains a `super` reference. + // This is due to the fact that we emit the body of an async function inside of a generator function. As generator + // functions cannot reference `super`, we emit a helper inside of the method body, but outside of the generator. This helper + // uses an arrow function, which is permitted to reference `super`. + // + // There are two primary ways we can access `super` from within an async method. The first is getting the value of a property + // or indexed access on super, either as part of a right-hand-side expression or call expression. The second is when setting the value + // of a property or indexed access, either as part of an assignment expression or destructuring assignment. + // + // The simplest case is reading a value, in which case we will emit something like the following: + // + // // ts + // ... + // async asyncMethod() { + // let x = await super.asyncMethod(); + // return x; + // } + // ... + // + // // js + // ... + // asyncMethod() { + // const _super = Object.create(null, { + // asyncMethod: { get: () => super.asyncMethod }, + // }); + // return __awaiter(this, arguments, Promise, function *() { + // let x = yield _super.asyncMethod.call(this); + // return x; + // }); + // } + // ... + // + // The more complex case is when we wish to assign a value, especially as part of a destructuring assignment. As both cases + // are legal in ES6, but also likely less frequent, we only emit setters if there is an assignment: + // + // // ts + // ... + // async asyncMethod(ar: Promise) { + // [super.a, super.b] = await ar; + // } + // ... + // + // // js + // ... + // asyncMethod(ar) { + // const _super = Object.create(null, { + // a: { get: () => super.a, set: (v) => super.a = v }, + // b: { get: () => super.b, set: (v) => super.b = v } + // }; + // return __awaiter(this, arguments, Promise, function *() { + // [_super.a, _super.b] = yield ar; + // }); + // } + // ... + // + // Creating an object that has getter and setters instead of just an accessor function is required for destructuring assignments + // as a call expression cannot be used as the target of a destructuring assignment while a property access can. + // + // For element access expressions (`super[x]`), we emit a generic helper that forwards the element access in both situations. + if (container.kind === 156 /* MethodDeclaration */ && ts.hasModifier(container, 256 /* Async */)) { + if (ts.isSuperProperty(node.parent) && ts.isAssignmentTarget(node.parent)) { + getNodeLinks(container).flags |= 4096 /* AsyncMethodWithSuperBinding */; + } + else { + getNodeLinks(container).flags |= 2048 /* AsyncMethodWithSuper */; + } + } + if (needToCaptureLexicalThis) { + // call expressions are allowed only in constructors so they should always capture correct 'this' + // super property access expressions can also appear in arrow functions - + // in this case they should also use correct lexical this + captureLexicalThis(node.parent, container); + } + if (container.parent.kind === 188 /* ObjectLiteralExpression */) { + if (languageVersion < 2 /* ES2015 */) { + error(node, ts.Diagnostics.super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_higher); + return errorType; + } + else { + // for object literal assume that type of 'super' is 'any' + return anyType; + } + } + // at this point the only legal case for parent is ClassLikeDeclaration + var classLikeDeclaration = container.parent; + if (!ts.getEffectiveBaseTypeNode(classLikeDeclaration)) { + error(node, ts.Diagnostics.super_can_only_be_referenced_in_a_derived_class); + return errorType; + } + var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(classLikeDeclaration)); + var baseClassType = classType && getBaseTypes(classType)[0]; + if (!baseClassType) { + return errorType; + } + if (container.kind === 157 /* Constructor */ && isInConstructorArgumentInitializer(node, container)) { + // issue custom error message for super property access in constructor arguments (to be aligned with old compiler) + error(node, ts.Diagnostics.super_cannot_be_referenced_in_constructor_arguments); + return errorType; + } + return nodeCheckFlag === 512 /* SuperStatic */ + ? getBaseConstructorTypeOfClass(classType) + : getTypeWithThisArgument(baseClassType, classType.thisType); + function isLegalUsageOfSuperExpression(container) { + if (!container) { + return false; + } + if (isCallExpression) { + // TS 1.0 SPEC (April 2014): 4.8.1 + // Super calls are only permitted in constructors of derived classes + return container.kind === 157 /* Constructor */; + } + else { + // TS 1.0 SPEC (April 2014) + // 'super' property access is allowed + // - In a constructor, instance member function, instance member accessor, or instance member variable initializer where this references a derived class instance + // - In a static member function or static member accessor + // topmost container must be something that is directly nested in the class declaration\object literal expression + if (ts.isClassLike(container.parent) || container.parent.kind === 188 /* ObjectLiteralExpression */) { + if (ts.hasModifier(container, 32 /* Static */)) { + return container.kind === 156 /* MethodDeclaration */ || + container.kind === 155 /* MethodSignature */ || + container.kind === 158 /* GetAccessor */ || + container.kind === 159 /* SetAccessor */; + } + else { + return container.kind === 156 /* MethodDeclaration */ || + container.kind === 155 /* MethodSignature */ || + container.kind === 158 /* GetAccessor */ || + container.kind === 159 /* SetAccessor */ || + container.kind === 154 /* PropertyDeclaration */ || + container.kind === 153 /* PropertySignature */ || + container.kind === 157 /* Constructor */; + } + } + } + return false; + } + } + function getContainingObjectLiteral(func) { + return (func.kind === 156 /* MethodDeclaration */ || + func.kind === 158 /* GetAccessor */ || + func.kind === 159 /* SetAccessor */) && func.parent.kind === 188 /* ObjectLiteralExpression */ ? func.parent : + func.kind === 196 /* FunctionExpression */ && func.parent.kind === 275 /* PropertyAssignment */ ? func.parent.parent : + undefined; + } + function getThisTypeArgument(type) { + return ts.getObjectFlags(type) & 4 /* Reference */ && type.target === globalThisType ? type.typeArguments[0] : undefined; + } + function getThisTypeFromContextualType(type) { + return mapType(type, function (t) { + return t.flags & 2097152 /* Intersection */ ? ts.forEach(t.types, getThisTypeArgument) : getThisTypeArgument(t); + }); + } + function getContextualThisParameterType(func) { + if (func.kind === 197 /* ArrowFunction */) { + return undefined; + } + if (isContextSensitiveFunctionOrObjectLiteralMethod(func)) { + var contextualSignature = getContextualSignature(func); + if (contextualSignature) { + var thisParameter = contextualSignature.thisParameter; + if (thisParameter) { + return getTypeOfSymbol(thisParameter); + } + } + } + var inJs = ts.isInJSFile(func); + if (noImplicitThis || inJs) { + var containingLiteral = getContainingObjectLiteral(func); + if (containingLiteral) { + // We have an object literal method. Check if the containing object literal has a contextual type + // that includes a ThisType. If so, T is the contextual type for 'this'. We continue looking in + // any directly enclosing object literals. + var contextualType = getApparentTypeOfContextualType(containingLiteral); + var literal = containingLiteral; + var type = contextualType; + while (type) { + var thisType = getThisTypeFromContextualType(type); + if (thisType) { + return instantiateType(thisType, getContextualMapper(containingLiteral)); + } + if (literal.parent.kind !== 275 /* PropertyAssignment */) { + break; + } + literal = literal.parent.parent; + type = getApparentTypeOfContextualType(literal); + } + // There was no contextual ThisType for the containing object literal, so the contextual type + // for 'this' is the non-null form of the contextual type for the containing object literal or + // the type of the object literal itself. + return contextualType ? getNonNullableType(contextualType) : checkExpressionCached(containingLiteral); + } + // In an assignment of the form 'obj.xxx = function(...)' or 'obj[xxx] = function(...)', the + // contextual type for 'this' is 'obj'. + var parent = func.parent; + if (parent.kind === 204 /* BinaryExpression */ && parent.operatorToken.kind === 59 /* EqualsToken */) { + var target = parent.left; + if (target.kind === 189 /* PropertyAccessExpression */ || target.kind === 190 /* ElementAccessExpression */) { + var expression = target.expression; + // Don't contextually type `this` as `exports` in `exports.Point = function(x, y) { this.x = x; this.y = y; }` + if (inJs && ts.isIdentifier(expression)) { + var sourceFile = ts.getSourceFileOfNode(parent); + if (sourceFile.commonJsModuleIndicator && getResolvedSymbol(expression) === sourceFile.symbol) { + return undefined; + } + } + return checkExpressionCached(expression); + } + } + } + return undefined; + } + // Return contextual type of parameter or undefined if no contextual type is available + function getContextuallyTypedParameterType(parameter) { + var func = parameter.parent; + if (!isContextSensitiveFunctionOrObjectLiteralMethod(func)) { + return undefined; + } + var iife = ts.getImmediatelyInvokedFunctionExpression(func); + if (iife && iife.arguments) { + var args = getEffectiveCallArguments(iife); + var indexOfParameter = func.parameters.indexOf(parameter); + if (parameter.dotDotDotToken) { + return getSpreadArgumentType(args, indexOfParameter, args.length, anyType, /*context*/ undefined); + } + var links = getNodeLinks(iife); + var cached = links.resolvedSignature; + links.resolvedSignature = anySignature; + var type = indexOfParameter < args.length ? + getWidenedLiteralType(checkExpression(args[indexOfParameter])) : + parameter.initializer ? undefined : undefinedWideningType; + links.resolvedSignature = cached; + return type; + } + var contextualSignature = getContextualSignature(func); + if (contextualSignature) { + var index = func.parameters.indexOf(parameter) - (ts.getThisParameter(func) ? 1 : 0); + return parameter.dotDotDotToken && ts.lastOrUndefined(func.parameters) === parameter ? + getRestTypeAtPosition(contextualSignature, index) : + tryGetTypeAtPosition(contextualSignature, index); + } + } + // In a variable, parameter or property declaration with a type annotation, + // the contextual type of an initializer expression is the type of the variable, parameter or property. + // Otherwise, in a parameter declaration of a contextually typed function expression, + // the contextual type of an initializer expression is the contextual type of the parameter. + // Otherwise, in a variable or parameter declaration with a binding pattern name, + // the contextual type of an initializer expression is the type implied by the binding pattern. + // Otherwise, in a binding pattern inside a variable or parameter declaration, + // the contextual type of an initializer expression is the type annotation of the containing declaration, if present. + function getContextualTypeForInitializerExpression(node) { + var declaration = node.parent; + if (ts.hasInitializer(declaration) && node === declaration.initializer) { + var typeNode = ts.getEffectiveTypeAnnotationNode(declaration); + if (typeNode) { + return getTypeFromTypeNode(typeNode); + } + if (declaration.kind === 151 /* Parameter */) { + var type = getContextuallyTypedParameterType(declaration); + if (type) { + return type; + } + } + if (ts.isBindingPattern(declaration.name)) { + return getTypeFromBindingPattern(declaration.name, /*includePatternInType*/ true, /*reportErrors*/ false); + } + if (ts.isBindingPattern(declaration.parent)) { + var parentDeclaration = declaration.parent.parent; + var name = declaration.propertyName || declaration.name; + if (parentDeclaration.kind !== 186 /* BindingElement */) { + var parentTypeNode = ts.getEffectiveTypeAnnotationNode(parentDeclaration); + if (parentTypeNode && !ts.isBindingPattern(name)) { + var text = ts.getTextOfPropertyName(name); + if (text) { + return getTypeOfPropertyOfType(getTypeFromTypeNode(parentTypeNode), text); + } + } + } + } + } + return undefined; + } + function getContextualTypeForReturnExpression(node) { + var func = ts.getContainingFunction(node); + if (func) { + var functionFlags = ts.getFunctionFlags(func); + if (functionFlags & 1 /* Generator */) { // AsyncGenerator function or Generator function + return undefined; + } + var contextualReturnType = getContextualReturnType(func); + if (contextualReturnType) { + if (functionFlags & 2 /* Async */) { // Async function + var contextualAwaitedType = getAwaitedTypeOfPromise(contextualReturnType); + return contextualAwaitedType && getUnionType([contextualAwaitedType, createPromiseLikeType(contextualAwaitedType)]); + } + return contextualReturnType; // Regular function + } + } + return undefined; + } + function getContextualTypeForAwaitOperand(node) { + var contextualType = getContextualType(node); + if (contextualType) { + var contextualAwaitedType = getAwaitedType(contextualType); + return contextualAwaitedType && getUnionType([contextualAwaitedType, createPromiseLikeType(contextualAwaitedType)]); + } + return undefined; + } + function getContextualTypeForYieldOperand(node) { + var func = ts.getContainingFunction(node); + if (func) { + var functionFlags = ts.getFunctionFlags(func); + var contextualReturnType = getContextualReturnType(func); + if (contextualReturnType) { + return node.asteriskToken + ? contextualReturnType + : getIteratedTypeOfGenerator(contextualReturnType, (functionFlags & 2 /* Async */) !== 0); + } + } + return undefined; + } + function isInParameterInitializerBeforeContainingFunction(node) { + var inBindingInitializer = false; + while (node.parent && !ts.isFunctionLike(node.parent)) { + if (ts.isParameter(node.parent) && (inBindingInitializer || node.parent.initializer === node)) { + return true; + } + if (ts.isBindingElement(node.parent) && node.parent.initializer === node) { + inBindingInitializer = true; + } + node = node.parent; + } + return false; + } + function getContextualReturnType(functionDecl) { + // If the containing function has a return type annotation, is a constructor, or is a get accessor whose + // corresponding set accessor has a type annotation, return statements in the function are contextually typed + var returnType = getReturnTypeFromAnnotation(functionDecl); + if (returnType) { + return returnType; + } + // Otherwise, if the containing function is contextually typed by a function type with exactly one call signature + // and that call signature is non-generic, return statements are contextually typed by the return type of the signature + var signature = getContextualSignatureForFunctionLikeDeclaration(functionDecl); + if (signature && !isResolvingReturnTypeOfSignature(signature)) { + return getReturnTypeOfSignature(signature); + } + return undefined; + } + // In a typed function call, an argument or substitution expression is contextually typed by the type of the corresponding parameter. + function getContextualTypeForArgument(callTarget, arg) { + var args = getEffectiveCallArguments(callTarget); + var argIndex = args.indexOf(arg); // -1 for e.g. the expression of a CallExpression, or the tag of a TaggedTemplateExpression + return argIndex === -1 ? undefined : getContextualTypeForArgumentAtIndex(callTarget, argIndex); + } + function getContextualTypeForArgumentAtIndex(callTarget, argIndex) { + // If we're already in the process of resolving the given signature, don't resolve again as + // that could cause infinite recursion. Instead, return anySignature. + var signature = getNodeLinks(callTarget).resolvedSignature === resolvingSignature ? resolvingSignature : getResolvedSignature(callTarget); + if (ts.isJsxOpeningLikeElement(callTarget) && argIndex === 0) { + return getEffectiveFirstArgumentForJsxSignature(signature, callTarget); + } + return getTypeAtPosition(signature, argIndex); + } + function getContextualTypeForSubstitutionExpression(template, substitutionExpression) { + if (template.parent.kind === 193 /* TaggedTemplateExpression */) { + return getContextualTypeForArgument(template.parent, substitutionExpression); + } + return undefined; + } + function getContextualTypeForBinaryOperand(node) { + var binaryExpression = node.parent; + var left = binaryExpression.left, operatorToken = binaryExpression.operatorToken, right = binaryExpression.right; + switch (operatorToken.kind) { + case 59 /* EqualsToken */: + if (node !== right) { + return undefined; + } + var contextSensitive = getIsContextSensitiveAssignmentOrContextType(binaryExpression); + if (!contextSensitive) { + return undefined; + } + return contextSensitive === true ? getTypeOfExpression(left) : contextSensitive; + case 55 /* BarBarToken */: + // When an || expression has a contextual type, the operands are contextually typed by that type. When an || + // expression has no contextual type, the right operand is contextually typed by the type of the left operand, + // except for the special case of Javascript declarations of the form `namespace.prop = namespace.prop || {}` + var type = getContextualType(binaryExpression); + return !type && node === right && !ts.isDefaultedExpandoInitializer(binaryExpression) ? + getTypeOfExpression(left) : type; + case 54 /* AmpersandAmpersandToken */: + case 27 /* CommaToken */: + return node === right ? getContextualType(binaryExpression) : undefined; + default: + return undefined; + } + } + // In an assignment expression, the right operand is contextually typed by the type of the left operand. + // Don't do this for assignment declarations unless there is a type tag on the assignment, to avoid circularity from checking the right operand. + function getIsContextSensitiveAssignmentOrContextType(binaryExpression) { + var kind = ts.getAssignmentDeclarationKind(binaryExpression); + switch (kind) { + case 0 /* None */: + return true; + case 5 /* Property */: + case 1 /* ExportsProperty */: + case 6 /* Prototype */: + case 3 /* PrototypeProperty */: + // If `binaryExpression.left` was assigned a symbol, then this is a new declaration; otherwise it is an assignment to an existing declaration. + // See `bindStaticPropertyAssignment` in `binder.ts`. + if (!binaryExpression.left.symbol) { + return true; + } + else { + var decl = binaryExpression.left.symbol.valueDeclaration; + if (!decl) { + return false; + } + var lhs = binaryExpression.left; + var overallAnnotation = ts.getEffectiveTypeAnnotationNode(decl); + if (overallAnnotation) { + return getTypeFromTypeNode(overallAnnotation); + } + else if (ts.isIdentifier(lhs.expression)) { + var id = lhs.expression; + var parentSymbol = resolveName(id, id.escapedText, 67220415 /* Value */, undefined, id.escapedText, /*isUse*/ true); + if (parentSymbol) { + var annotated = ts.getEffectiveTypeAnnotationNode(parentSymbol.valueDeclaration); + if (annotated) { + var type = getTypeOfPropertyOfContextualType(getTypeFromTypeNode(annotated), lhs.name.escapedText); + return type || false; + } + return false; + } + } + return !ts.isInJSFile(decl); + } + case 2 /* ModuleExports */: + case 4 /* ThisProperty */: + if (!binaryExpression.symbol) + return true; + if (binaryExpression.symbol.valueDeclaration) { + var annotated = ts.getEffectiveTypeAnnotationNode(binaryExpression.symbol.valueDeclaration); + if (annotated) { + var type = getTypeFromTypeNode(annotated); + if (type) { + return type; + } + } + } + if (kind === 2 /* ModuleExports */) + return false; + var thisAccess = binaryExpression.left; + if (!ts.isObjectLiteralMethod(ts.getThisContainer(thisAccess.expression, /*includeArrowFunctions*/ false))) { + return false; + } + var thisType = checkThisExpression(thisAccess.expression); + return thisType && getTypeOfPropertyOfContextualType(thisType, thisAccess.name.escapedText) || false; + case 7 /* ObjectDefinePropertyValue */: + case 8 /* ObjectDefinePropertyExports */: + case 9 /* ObjectDefinePrototypeProperty */: + return ts.Debug.fail("Does not apply"); + default: + return ts.Debug.assertNever(kind); + } + } + function getTypeOfPropertyOfContextualType(type, name) { + return mapType(type, function (t) { + if (t.flags & 3670016 /* StructuredType */) { + var prop = getPropertyOfType(t, name); + if (prop) { + return getTypeOfSymbol(prop); + } + if (isTupleType(t)) { + var restType = getRestTypeOfTupleType(t); + if (restType && isNumericLiteralName(name) && +name >= 0) { + return restType; + } + } + return isNumericLiteralName(name) && getIndexTypeOfContextualType(t, 1 /* Number */) || + getIndexTypeOfContextualType(t, 0 /* String */); + } + return undefined; + }, /*noReductions*/ true); + } + function getIndexTypeOfContextualType(type, kind) { + return mapType(type, function (t) { return getIndexTypeOfStructuredType(t, kind); }, /*noReductions*/ true); + } + // In an object literal contextually typed by a type T, the contextual type of a property assignment is the type of + // the matching property in T, if one exists. Otherwise, it is the type of the numeric index signature in T, if one + // exists. Otherwise, it is the type of the string index signature in T, if one exists. + function getContextualTypeForObjectLiteralMethod(node) { + ts.Debug.assert(ts.isObjectLiteralMethod(node)); + if (node.flags & 8388608 /* InWithStatement */) { + // We cannot answer semantic questions within a with block, do not proceed any further + return undefined; + } + return getContextualTypeForObjectLiteralElement(node); + } + function getContextualTypeForObjectLiteralElement(element) { + var objectLiteral = element.parent; + var type = getApparentTypeOfContextualType(objectLiteral); + if (type) { + if (!hasNonBindableDynamicName(element)) { + // For a (non-symbol) computed property, there is no reason to look up the name + // in the type. It will just be "__computed", which does not appear in any + // SymbolTable. + var symbolName_2 = getSymbolOfNode(element).escapedName; + var propertyType = getTypeOfPropertyOfContextualType(type, symbolName_2); + if (propertyType) { + return propertyType; + } + } + return isNumericName(element.name) && getIndexTypeOfContextualType(type, 1 /* Number */) || + getIndexTypeOfContextualType(type, 0 /* String */); + } + return undefined; + } + // In an array literal contextually typed by a type T, the contextual type of an element expression at index N is + // the type of the property with the numeric name N in T, if one exists. Otherwise, if T has a numeric index signature, + // it is the type of the numeric index signature in T. Otherwise, in ES6 and higher, the contextual type is the iterated + // type of T. + function getContextualTypeForElementExpression(arrayContextualType, index) { + return arrayContextualType && (getTypeOfPropertyOfContextualType(arrayContextualType, "" + index) + || getIteratedTypeOrElementType(arrayContextualType, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterables*/ false, /*checkAssignability*/ false)); + } + // In a contextually typed conditional expression, the true/false expressions are contextually typed by the same type. + function getContextualTypeForConditionalOperand(node) { + var conditional = node.parent; + return node === conditional.whenTrue || node === conditional.whenFalse ? getContextualType(conditional) : undefined; + } + function getContextualTypeForChildJsxExpression(node) { + var attributesType = getApparentTypeOfContextualType(node.openingElement.tagName); + // JSX expression is in children of JSX Element, we will look for an "children" atttribute (we get the name from JSX.ElementAttributesProperty) + var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(node)); + return attributesType && !isTypeAny(attributesType) && jsxChildrenPropertyName && jsxChildrenPropertyName !== "" ? getTypeOfPropertyOfContextualType(attributesType, jsxChildrenPropertyName) : undefined; + } + function getContextualTypeForJsxExpression(node) { + var exprParent = node.parent; + return ts.isJsxAttributeLike(exprParent) + ? getContextualType(node) + : ts.isJsxElement(exprParent) + ? getContextualTypeForChildJsxExpression(exprParent) + : undefined; + } + function getContextualTypeForJsxAttribute(attribute) { + // When we trying to resolve JsxOpeningLikeElement as a stateless function element, we will already give its attributes a contextual type + // which is a type of the parameter of the signature we are trying out. + // If there is no contextual type (e.g. we are trying to resolve stateful component), get attributes type from resolving element's tagName + if (ts.isJsxAttribute(attribute)) { + var attributesType = getApparentTypeOfContextualType(attribute.parent); + if (!attributesType || isTypeAny(attributesType)) { + return undefined; + } + return getTypeOfPropertyOfContextualType(attributesType, attribute.name.escapedText); + } + else { + return getContextualType(attribute.parent); + } + } + // Return true if the given expression is possibly a discriminant value. We limit the kinds of + // expressions we check to those that don't depend on their contextual type in order not to cause + // recursive (and possibly infinite) invocations of getContextualType. + function isPossiblyDiscriminantValue(node) { + switch (node.kind) { + case 10 /* StringLiteral */: + case 8 /* NumericLiteral */: + case 9 /* BigIntLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: + case 102 /* TrueKeyword */: + case 87 /* FalseKeyword */: + case 96 /* NullKeyword */: + case 72 /* Identifier */: + case 141 /* UndefinedKeyword */: + return true; + case 189 /* PropertyAccessExpression */: + case 195 /* ParenthesizedExpression */: + return isPossiblyDiscriminantValue(node.expression); + case 270 /* JsxExpression */: + return !node.expression || isPossiblyDiscriminantValue(node.expression); + } + return false; + } + function discriminateContextualTypeByObjectMembers(node, contextualType) { + return discriminateTypeByDiscriminableItems(contextualType, ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 275 /* PropertyAssignment */ && isPossiblyDiscriminantValue(p.initializer) && isDiscriminantProperty(contextualType, p.symbol.escapedName); }), function (prop) { return [function () { return checkExpression(prop.initializer); }, prop.symbol.escapedName]; }), isTypeAssignableTo, contextualType); + } + function discriminateContextualTypeByJSXAttributes(node, contextualType) { + return discriminateTypeByDiscriminableItems(contextualType, ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 267 /* JsxAttribute */ && isDiscriminantProperty(contextualType, p.symbol.escapedName) && (!p.initializer || isPossiblyDiscriminantValue(p.initializer)); }), function (prop) { return [!prop.initializer ? (function () { return trueType; }) : (function () { return checkExpression(prop.initializer); }), prop.symbol.escapedName]; }), isTypeAssignableTo, contextualType); + } + // Return the contextual type for a given expression node. During overload resolution, a contextual type may temporarily + // be "pushed" onto a node using the contextualType property. + function getApparentTypeOfContextualType(node) { + var contextualType = getContextualType(node); + contextualType = contextualType && mapType(contextualType, getApparentType); + if (contextualType && contextualType.flags & 1048576 /* Union */) { + if (ts.isObjectLiteralExpression(node)) { + return discriminateContextualTypeByObjectMembers(node, contextualType); + } + else if (ts.isJsxAttributes(node)) { + return discriminateContextualTypeByJSXAttributes(node, contextualType); + } + } + return contextualType; + } + /** + * Woah! Do you really want to use this function? + * + * Unless you're trying to get the *non-apparent* type for a + * value-literal type or you're authoring relevant portions of this algorithm, + * you probably meant to use 'getApparentTypeOfContextualType'. + * Otherwise this may not be very useful. + * + * In cases where you *are* working on this function, you should understand + * when it is appropriate to use 'getContextualType' and 'getApparentTypeOfContextualType'. + * + * - Use 'getContextualType' when you are simply going to propagate the result to the expression. + * - Use 'getApparentTypeOfContextualType' when you're going to need the members of the type. + * + * @param node the expression whose contextual type will be returned. + * @returns the contextual type of an expression. + */ + function getContextualType(node) { + if (node.flags & 8388608 /* InWithStatement */) { + // We cannot answer semantic questions within a with block, do not proceed any further + return undefined; + } + if (node.contextualType) { + return node.contextualType; + } + var parent = node.parent; + switch (parent.kind) { + case 237 /* VariableDeclaration */: + case 151 /* Parameter */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 186 /* BindingElement */: + return getContextualTypeForInitializerExpression(node); + case 197 /* ArrowFunction */: + case 230 /* ReturnStatement */: + return getContextualTypeForReturnExpression(node); + case 207 /* YieldExpression */: + return getContextualTypeForYieldOperand(parent); + case 201 /* AwaitExpression */: + return getContextualTypeForAwaitOperand(parent); + case 191 /* CallExpression */: + case 192 /* NewExpression */: + return getContextualTypeForArgument(parent, node); + case 194 /* TypeAssertionExpression */: + case 212 /* AsExpression */: + return getTypeFromTypeNode(parent.type); + case 204 /* BinaryExpression */: + return getContextualTypeForBinaryOperand(node); + case 275 /* PropertyAssignment */: + case 276 /* ShorthandPropertyAssignment */: + return getContextualTypeForObjectLiteralElement(parent); + case 277 /* SpreadAssignment */: + return getApparentTypeOfContextualType(parent.parent); + case 187 /* ArrayLiteralExpression */: { + var arrayLiteral = parent; + var type = getApparentTypeOfContextualType(arrayLiteral); + return getContextualTypeForElementExpression(type, ts.indexOfNode(arrayLiteral.elements, node)); + } + case 205 /* ConditionalExpression */: + return getContextualTypeForConditionalOperand(node); + case 216 /* TemplateSpan */: + ts.Debug.assert(parent.parent.kind === 206 /* TemplateExpression */); + return getContextualTypeForSubstitutionExpression(parent.parent, node); + case 195 /* ParenthesizedExpression */: { + // Like in `checkParenthesizedExpression`, an `/** @type {xyz} */` comment before a parenthesized expression acts as a type cast. + var tag = ts.isInJSFile(parent) ? ts.getJSDocTypeTag(parent) : undefined; + return tag ? getTypeFromTypeNode(tag.typeExpression.type) : getContextualType(parent); + } + case 270 /* JsxExpression */: + return getContextualTypeForJsxExpression(parent); + case 267 /* JsxAttribute */: + case 269 /* JsxSpreadAttribute */: + return getContextualTypeForJsxAttribute(parent); + case 262 /* JsxOpeningElement */: + case 261 /* JsxSelfClosingElement */: + return getContextualJsxElementAttributesType(parent); + } + return undefined; + } + function getContextualMapper(node) { + var ancestor = ts.findAncestor(node, function (n) { return !!n.contextualMapper; }); + return ancestor ? ancestor.contextualMapper : identityMapper; + } + function getContextualJsxElementAttributesType(node) { + if (ts.isJsxOpeningElement(node) && node.parent.contextualType) { + // Contextually applied type is moved from attributes up to the outer jsx attributes so when walking up from the children they get hit + // _However_ to hit them from the _attributes_ we must look for them here; otherwise we'll used the declared type + // (as below) instead! + return node.parent.contextualType; + } + return getContextualTypeForArgumentAtIndex(node, 0); + } + function getEffectiveFirstArgumentForJsxSignature(signature, node) { + return getJsxReferenceKind(node) !== 0 /* Component */ ? getJsxPropsTypeFromCallSignature(signature, node) : getJsxPropsTypeFromClassType(signature, node); + } + function getJsxPropsTypeFromCallSignature(sig, context) { + var propsType = getTypeOfFirstParameterOfSignatureWithFallback(sig, emptyObjectType); + propsType = getJsxManagedAttributesFromLocatedAttributes(context, getJsxNamespaceAt(context), propsType); + var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes, context); + if (intrinsicAttribs !== errorType) { + propsType = intersectTypes(intrinsicAttribs, propsType); + } + return propsType; + } + function getJsxPropsTypeForSignatureFromMember(sig, forcedLookupLocation) { + var instanceType = getReturnTypeOfSignature(sig); + return isTypeAny(instanceType) ? instanceType : getTypeOfPropertyOfType(instanceType, forcedLookupLocation); + } + function getStaticTypeOfReferencedJsxConstructor(context) { + if (isJsxIntrinsicIdentifier(context.tagName)) { + var result = getIntrinsicAttributesTypeFromJsxOpeningLikeElement(context); + var fakeSignature = createSignatureForJSXIntrinsic(context, result); + return getOrCreateTypeFromSignature(fakeSignature); + } + var tagType = checkExpressionCached(context.tagName); + if (tagType.flags & 128 /* StringLiteral */) { + var result = getIntrinsicAttributesTypeFromStringLiteralType(tagType, context); + if (!result) { + return errorType; + } + var fakeSignature = createSignatureForJSXIntrinsic(context, result); + return getOrCreateTypeFromSignature(fakeSignature); + } + return tagType; + } + function getJsxManagedAttributesFromLocatedAttributes(context, ns, attributesType) { + var managedSym = getJsxLibraryManagedAttributes(ns); + if (managedSym) { + var declaredManagedType = getDeclaredTypeOfSymbol(managedSym); + var ctorType = getStaticTypeOfReferencedJsxConstructor(context); + if (ts.length(declaredManagedType.typeParameters) >= 2) { + var args = fillMissingTypeArguments([ctorType, attributesType], declaredManagedType.typeParameters, 2, ts.isInJSFile(context)); + return createTypeReference(declaredManagedType, args); + } + else if (ts.length(declaredManagedType.aliasTypeArguments) >= 2) { + var args = fillMissingTypeArguments([ctorType, attributesType], declaredManagedType.aliasTypeArguments, 2, ts.isInJSFile(context)); + return getTypeAliasInstantiation(declaredManagedType.aliasSymbol, args); + } + } + return attributesType; + } + function getJsxPropsTypeFromClassType(sig, context) { + var ns = getJsxNamespaceAt(context); + var forcedLookupLocation = getJsxElementPropertiesName(ns); + var attributesType = forcedLookupLocation === undefined + // If there is no type ElementAttributesProperty, return the type of the first parameter of the signature, which should be the props type + ? getTypeOfFirstParameterOfSignatureWithFallback(sig, emptyObjectType) + : forcedLookupLocation === "" + // If there is no e.g. 'props' member in ElementAttributesProperty, use the element class type instead + ? getReturnTypeOfSignature(sig) + // Otherwise get the type of the property on the signature return type + : getJsxPropsTypeForSignatureFromMember(sig, forcedLookupLocation); + if (!attributesType) { + // There is no property named 'props' on this instance type + if (!!forcedLookupLocation && !!ts.length(context.attributes.properties)) { + error(context, ts.Diagnostics.JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property, ts.unescapeLeadingUnderscores(forcedLookupLocation)); + } + return emptyObjectType; + } + attributesType = getJsxManagedAttributesFromLocatedAttributes(context, ns, attributesType); + if (isTypeAny(attributesType)) { + // Props is of type 'any' or unknown + return attributesType; + } + else { + // Normal case -- add in IntrinsicClassElements and IntrinsicElements + var apparentAttributesType = attributesType; + var intrinsicClassAttribs = getJsxType(JsxNames.IntrinsicClassAttributes, context); + if (intrinsicClassAttribs !== errorType) { + var typeParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(intrinsicClassAttribs.symbol); + var hostClassType = getReturnTypeOfSignature(sig); + apparentAttributesType = intersectTypes(typeParams + ? createTypeReference(intrinsicClassAttribs, fillMissingTypeArguments([hostClassType], typeParams, getMinTypeArgumentCount(typeParams), ts.isInJSFile(context))) + : intrinsicClassAttribs, apparentAttributesType); + } + var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes, context); + if (intrinsicAttribs !== errorType) { + apparentAttributesType = intersectTypes(intrinsicAttribs, apparentAttributesType); + } + return apparentAttributesType; + } + } + // If the given type is an object or union type with a single signature, and if that signature has at + // least as many parameters as the given function, return the signature. Otherwise return undefined. + function getContextualCallSignature(type, node) { + var signatures = getSignaturesOfType(type, 0 /* Call */); + if (signatures.length === 1) { + var signature = signatures[0]; + if (!isAritySmaller(signature, node)) { + return signature; + } + } + } + /** If the contextual signature has fewer parameters than the function expression, do not use it */ + function isAritySmaller(signature, target) { + var targetParameterCount = 0; + for (; targetParameterCount < target.parameters.length; targetParameterCount++) { + var param = target.parameters[targetParameterCount]; + if (param.initializer || param.questionToken || param.dotDotDotToken || isJSDocOptionalParameter(param)) { + break; + } + } + if (target.parameters.length && ts.parameterIsThisKeyword(target.parameters[0])) { + targetParameterCount--; + } + return !hasEffectiveRestParameter(signature) && getParameterCount(signature) < targetParameterCount; + } + function isFunctionExpressionOrArrowFunction(node) { + return node.kind === 196 /* FunctionExpression */ || node.kind === 197 /* ArrowFunction */; + } + function getContextualSignatureForFunctionLikeDeclaration(node) { + // Only function expressions, arrow functions, and object literal methods are contextually typed. + return isFunctionExpressionOrArrowFunction(node) || ts.isObjectLiteralMethod(node) + ? getContextualSignature(node) + : undefined; + } + function getContextualTypeForFunctionLikeDeclaration(node) { + return ts.isObjectLiteralMethod(node) ? + getContextualTypeForObjectLiteralMethod(node) : + getApparentTypeOfContextualType(node); + } + // Return the contextual signature for a given expression node. A contextual type provides a + // contextual signature if it has a single call signature and if that call signature is non-generic. + // If the contextual type is a union type, get the signature from each type possible and if they are + // all identical ignoring their return type, the result is same signature but with return type as + // union type of return types from these signatures + function getContextualSignature(node) { + ts.Debug.assert(node.kind !== 156 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + var typeTagSignature = getSignatureOfTypeTag(node); + if (typeTagSignature) { + return typeTagSignature; + } + var type = getContextualTypeForFunctionLikeDeclaration(node); + if (!type) { + return undefined; + } + if (!(type.flags & 1048576 /* Union */)) { + return getContextualCallSignature(type, node); + } + var signatureList; + var types = type.types; + for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { + var current = types_14[_i]; + var signature = getContextualCallSignature(current, node); + if (signature) { + if (!signatureList) { + // This signature will contribute to contextual union signature + signatureList = [signature]; + } + else if (!compareSignaturesIdentical(signatureList[0], signature, /*partialMatch*/ false, /*ignoreThisTypes*/ true, /*ignoreReturnTypes*/ true, compareTypesIdentical)) { + // Signatures aren't identical, do not use + return undefined; + } + else { + // Use this signature for contextual union signature + signatureList.push(signature); + } + } + } + // Result is union of signatures collected (return type is union of return types of this signature set) + var result; + if (signatureList) { + result = cloneSignature(signatureList[0]); + result.unionSignatures = signatureList; + } + return result; + } + function checkSpreadExpression(node, checkMode) { + if (languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) { + checkExternalEmitHelpers(node, 1536 /* SpreadIncludes */); + } + var arrayOrIterableType = checkExpression(node.expression, checkMode); + return checkIteratedTypeOrElementType(arrayOrIterableType, node.expression, /*allowStringInput*/ false, /*allowAsyncIterables*/ false); + } + function hasDefaultValue(node) { + return (node.kind === 186 /* BindingElement */ && !!node.initializer) || + (node.kind === 204 /* BinaryExpression */ && node.operatorToken.kind === 59 /* EqualsToken */); + } + function checkArrayLiteral(node, checkMode, forceTuple) { + var elements = node.elements; + var elementCount = elements.length; + var hasNonEndingSpreadElement = false; + var elementTypes = []; + var inDestructuringPattern = ts.isAssignmentTarget(node); + var contextualType = getApparentTypeOfContextualType(node); + for (var index = 0; index < elementCount; index++) { + var e = elements[index]; + if (inDestructuringPattern && e.kind === 208 /* SpreadElement */) { + // Given the following situation: + // var c: {}; + // [...c] = ["", 0]; + // + // c is represented in the tree as a spread element in an array literal. + // But c really functions as a rest element, and its purpose is to provide + // a contextual type for the right hand side of the assignment. Therefore, + // instead of calling checkExpression on "...c", which will give an error + // if c is not iterable/array-like, we need to act as if we are trying to + // get the contextual element type from it. So we do something similar to + // getContextualTypeForElementExpression, which will crucially not error + // if there is no index type / iterated type. + var restArrayType = checkExpression(e.expression, checkMode, forceTuple); + var restElementType = getIndexTypeOfType(restArrayType, 1 /* Number */) || + getIteratedTypeOrElementType(restArrayType, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterables*/ false, /*checkAssignability*/ false); + if (restElementType) { + elementTypes.push(restElementType); + } + } + else { + var elementContextualType = getContextualTypeForElementExpression(contextualType, index); + var type = checkExpressionForMutableLocation(e, checkMode, elementContextualType, forceTuple); + elementTypes.push(type); + } + if (index < elementCount - 1 && e.kind === 208 /* SpreadElement */) { + hasNonEndingSpreadElement = true; + } + } + if (!hasNonEndingSpreadElement) { + var hasRestElement = elementCount > 0 && elements[elementCount - 1].kind === 208 /* SpreadElement */; + var minLength = elementCount - (hasRestElement ? 1 : 0); + // If array literal is actually a destructuring pattern, mark it as an implied type. We do this such + // that we get the same behavior for "var [x, y] = []" and "[x, y] = []". + var tupleResult = void 0; + if (inDestructuringPattern && minLength > 0) { + var type = cloneTypeReference(createTupleType(elementTypes, minLength, hasRestElement)); + type.pattern = node; + return type; + } + else if (tupleResult = getArrayLiteralTupleTypeIfApplicable(elementTypes, contextualType, hasRestElement, elementCount)) { + return tupleResult; + } + else if (forceTuple) { + return createTupleType(elementTypes, minLength, hasRestElement); + } + } + return getArrayLiteralType(elementTypes, 2 /* Subtype */); + } + function getArrayLiteralTupleTypeIfApplicable(elementTypes, contextualType, hasRestElement, elementCount) { + if (elementCount === void 0) { elementCount = elementTypes.length; } + // Infer a tuple type when the contextual type is or contains a tuple-like type + if (contextualType && forEachType(contextualType, isTupleLikeType)) { + var minLength = elementCount - (hasRestElement ? 1 : 0); + var pattern = contextualType.pattern; + // If array literal is contextually typed by a binding pattern or an assignment pattern, pad the resulting + // tuple type with the corresponding binding or assignment element types to make the lengths equal. + if (!hasRestElement && pattern && (pattern.kind === 185 /* ArrayBindingPattern */ || pattern.kind === 187 /* ArrayLiteralExpression */)) { + var patternElements = pattern.elements; + for (var i = elementCount; i < patternElements.length; i++) { + var e = patternElements[i]; + if (hasDefaultValue(e)) { + elementTypes.push(contextualType.typeArguments[i]); + } + else if (i < patternElements.length - 1 || !(e.kind === 186 /* BindingElement */ && e.dotDotDotToken || e.kind === 208 /* SpreadElement */)) { + if (e.kind !== 210 /* OmittedExpression */) { + error(e, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); + } + elementTypes.push(strictNullChecks ? implicitNeverType : undefinedWideningType); + } + } + } + return createTupleType(elementTypes, minLength, hasRestElement); + } + } + function getArrayLiteralType(elementTypes, unionReduction) { + if (unionReduction === void 0) { unionReduction = 1 /* Literal */; } + return createArrayType(elementTypes.length ? + getUnionType(elementTypes, unionReduction) : + strictNullChecks ? implicitNeverType : undefinedWideningType); + } + function isNumericName(name) { + switch (name.kind) { + case 149 /* ComputedPropertyName */: + return isNumericComputedName(name); + case 72 /* Identifier */: + return isNumericLiteralName(name.escapedText); + case 8 /* NumericLiteral */: + case 10 /* StringLiteral */: + return isNumericLiteralName(name.text); + default: + return false; + } + } + function isNumericComputedName(name) { + // It seems odd to consider an expression of type Any to result in a numeric name, + // but this behavior is consistent with checkIndexedAccess + return isTypeAssignableToKind(checkComputedPropertyName(name), 296 /* NumberLike */); + } + function isInfinityOrNaNString(name) { + return name === "Infinity" || name === "-Infinity" || name === "NaN"; + } + function isNumericLiteralName(name) { + // The intent of numeric names is that + // - they are names with text in a numeric form, and that + // - setting properties/indexing with them is always equivalent to doing so with the numeric literal 'numLit', + // acquired by applying the abstract 'ToNumber' operation on the name's text. + // + // The subtlety is in the latter portion, as we cannot reliably say that anything that looks like a numeric literal is a numeric name. + // In fact, it is the case that the text of the name must be equal to 'ToString(numLit)' for this to hold. + // + // Consider the property name '"0xF00D"'. When one indexes with '0xF00D', they are actually indexing with the value of 'ToString(0xF00D)' + // according to the ECMAScript specification, so it is actually as if the user indexed with the string '"61453"'. + // Thus, the text of all numeric literals equivalent to '61543' such as '0xF00D', '0xf00D', '0170015', etc. are not valid numeric names + // because their 'ToString' representation is not equal to their original text. + // This is motivated by ECMA-262 sections 9.3.1, 9.8.1, 11.1.5, and 11.2.1. + // + // Here, we test whether 'ToString(ToNumber(name))' is exactly equal to 'name'. + // The '+' prefix operator is equivalent here to applying the abstract ToNumber operation. + // Applying the 'toString()' method on a number gives us the abstract ToString operation on a number. + // + // Note that this accepts the values 'Infinity', '-Infinity', and 'NaN', and that this is intentional. + // This is desired behavior, because when indexing with them as numeric entities, you are indexing + // with the strings '"Infinity"', '"-Infinity"', and '"NaN"' respectively. + return (+name).toString() === name; + } + function checkComputedPropertyName(node) { + var links = getNodeLinks(node.expression); + if (!links.resolvedType) { + links.resolvedType = checkExpression(node.expression); + // This will allow types number, string, symbol or any. It will also allow enums, the unknown + // type, and any union of these types (like string | number). + if (links.resolvedType.flags & 98304 /* Nullable */ || + !isTypeAssignableToKind(links.resolvedType, 132 /* StringLike */ | 296 /* NumberLike */ | 12288 /* ESSymbolLike */) && + !isTypeAssignableTo(links.resolvedType, stringNumberSymbolType)) { + error(node, ts.Diagnostics.A_computed_property_name_must_be_of_type_string_number_symbol_or_any); + } + else { + checkThatExpressionIsProperSymbolReference(node.expression, links.resolvedType, /*reportError*/ true); + } + } + return links.resolvedType; + } + function getObjectLiteralIndexInfo(propertyNodes, offset, properties, kind) { + var propTypes = []; + for (var i = 0; i < properties.length; i++) { + if (kind === 0 /* String */ || isNumericName(propertyNodes[i + offset].name)) { + propTypes.push(getTypeOfSymbol(properties[i])); + } + } + var unionType = propTypes.length ? getUnionType(propTypes, 2 /* Subtype */) : undefinedType; + return createIndexInfo(unionType, /*isReadonly*/ false); + } + function getImmediateAliasedSymbol(symbol) { + ts.Debug.assert((symbol.flags & 2097152 /* Alias */) !== 0, "Should only get Alias here."); + var links = getSymbolLinks(symbol); + if (!links.immediateTarget) { + var node = getDeclarationOfAliasSymbol(symbol); + if (!node) + return ts.Debug.fail(); + links.immediateTarget = getTargetOfAliasDeclaration(node, /*dontRecursivelyResolve*/ true); + } + return links.immediateTarget; + } + function checkObjectLiteral(node, checkMode) { + var inDestructuringPattern = ts.isAssignmentTarget(node); + // Grammar checking + checkGrammarObjectLiteralExpression(node, inDestructuringPattern); + var propertiesTable; + var propertiesArray = []; + var spread = emptyObjectType; + var propagatedFlags = 0; + var contextualType = getApparentTypeOfContextualType(node); + var contextualTypeHasPattern = contextualType && contextualType.pattern && + (contextualType.pattern.kind === 184 /* ObjectBindingPattern */ || contextualType.pattern.kind === 188 /* ObjectLiteralExpression */); + var isInJavascript = ts.isInJSFile(node) && !ts.isInJsonFile(node); + var enumTag = ts.getJSDocEnumTag(node); + var isJSObjectLiteral = !contextualType && isInJavascript && !enumTag; + var typeFlags = 0; + var patternWithComputedProperties = false; + var hasComputedStringProperty = false; + var hasComputedNumberProperty = false; + propertiesTable = ts.createSymbolTable(); + var offset = 0; + for (var i = 0; i < node.properties.length; i++) { + var memberDecl = node.properties[i]; + var member = getSymbolOfNode(memberDecl); + var computedNameType = memberDecl.name && memberDecl.name.kind === 149 /* ComputedPropertyName */ && !ts.isWellKnownSymbolSyntactically(memberDecl.name.expression) ? + checkComputedPropertyName(memberDecl.name) : undefined; + if (memberDecl.kind === 275 /* PropertyAssignment */ || + memberDecl.kind === 276 /* ShorthandPropertyAssignment */ || + ts.isObjectLiteralMethod(memberDecl)) { + var type = memberDecl.kind === 275 /* PropertyAssignment */ ? checkPropertyAssignment(memberDecl, checkMode) : + memberDecl.kind === 276 /* ShorthandPropertyAssignment */ ? checkExpressionForMutableLocation(memberDecl.name, checkMode) : + checkObjectLiteralMethod(memberDecl, checkMode); + if (isInJavascript) { + var jsDocType = getTypeForDeclarationFromJSDocComment(memberDecl); + if (jsDocType) { + checkTypeAssignableTo(type, jsDocType, memberDecl); + type = jsDocType; + } + else if (enumTag && enumTag.typeExpression) { + checkTypeAssignableTo(type, getTypeFromTypeNode(enumTag.typeExpression), memberDecl); + } + } + typeFlags |= type.flags; + var nameType = computedNameType && computedNameType.flags & 8576 /* StringOrNumberLiteralOrUnique */ ? + computedNameType : undefined; + var prop = nameType ? + createSymbol(4 /* Property */ | member.flags, getLateBoundNameFromType(nameType), 1024 /* Late */) : + createSymbol(4 /* Property */ | member.flags, member.escapedName); + if (nameType) { + prop.nameType = nameType; + } + if (inDestructuringPattern) { + // If object literal is an assignment pattern and if the assignment pattern specifies a default value + // for the property, make the property optional. + var isOptional = (memberDecl.kind === 275 /* PropertyAssignment */ && hasDefaultValue(memberDecl.initializer)) || + (memberDecl.kind === 276 /* ShorthandPropertyAssignment */ && memberDecl.objectAssignmentInitializer); + if (isOptional) { + prop.flags |= 16777216 /* Optional */; + } + } + else if (contextualTypeHasPattern && !(ts.getObjectFlags(contextualType) & 512 /* ObjectLiteralPatternWithComputedProperties */)) { + // If object literal is contextually typed by the implied type of a binding pattern, and if the + // binding pattern specifies a default value for the property, make the property optional. + var impliedProp = getPropertyOfType(contextualType, member.escapedName); + if (impliedProp) { + prop.flags |= impliedProp.flags & 16777216 /* Optional */; + } + else if (!compilerOptions.suppressExcessPropertyErrors && !getIndexInfoOfType(contextualType, 0 /* String */)) { + error(memberDecl.name, ts.Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(member), typeToString(contextualType)); + } + } + prop.declarations = member.declarations; + prop.parent = member.parent; + if (member.valueDeclaration) { + prop.valueDeclaration = member.valueDeclaration; + } + prop.type = type; + prop.target = member; + member = prop; + } + else if (memberDecl.kind === 277 /* SpreadAssignment */) { + if (languageVersion < 2 /* ES2015 */) { + checkExternalEmitHelpers(memberDecl, 2 /* Assign */); + } + if (propertiesArray.length > 0) { + spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, propagatedFlags, 32768 /* FreshLiteral */); + propertiesArray = []; + propertiesTable = ts.createSymbolTable(); + hasComputedStringProperty = false; + hasComputedNumberProperty = false; + typeFlags = 0; + } + var type = checkExpression(memberDecl.expression); + if (!isValidSpreadType(type)) { + error(memberDecl, ts.Diagnostics.Spread_types_may_only_be_created_from_object_types); + return errorType; + } + spread = getSpreadType(spread, type, node.symbol, propagatedFlags, 32768 /* FreshLiteral */); + offset = i + 1; + continue; + } + else { + // TypeScript 1.0 spec (April 2014) + // A get accessor declaration is processed in the same manner as + // an ordinary function declaration(section 6.1) with no parameters. + // A set accessor declaration is processed in the same manner + // as an ordinary function declaration with a single parameter and a Void return type. + ts.Debug.assert(memberDecl.kind === 158 /* GetAccessor */ || memberDecl.kind === 159 /* SetAccessor */); + checkNodeDeferred(memberDecl); + } + if (computedNameType && !(computedNameType.flags & 8576 /* StringOrNumberLiteralOrUnique */)) { + if (isTypeAssignableTo(computedNameType, stringNumberSymbolType)) { + if (isTypeAssignableTo(computedNameType, numberType)) { + hasComputedNumberProperty = true; + } + else { + hasComputedStringProperty = true; + } + if (inDestructuringPattern) { + patternWithComputedProperties = true; + } + } + } + else { + propertiesTable.set(member.escapedName, member); + } + propertiesArray.push(member); + } + // If object literal is contextually typed by the implied type of a binding pattern, augment the result + // type with those properties for which the binding pattern specifies a default value. + if (contextualTypeHasPattern) { + for (var _i = 0, _a = getPropertiesOfType(contextualType); _i < _a.length; _i++) { + var prop = _a[_i]; + if (!propertiesTable.get(prop.escapedName) && !(spread && getPropertyOfType(spread, prop.escapedName))) { + if (!(prop.flags & 16777216 /* Optional */)) { + error(prop.valueDeclaration || prop.bindingElement, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); + } + propertiesTable.set(prop.escapedName, prop); + propertiesArray.push(prop); + } + } + } + if (spread !== emptyObjectType) { + if (propertiesArray.length > 0) { + spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, propagatedFlags, 32768 /* FreshLiteral */); + } + return spread; + } + return createObjectLiteralType(); + function createObjectLiteralType() { + var stringIndexInfo = hasComputedStringProperty ? getObjectLiteralIndexInfo(node.properties, offset, propertiesArray, 0 /* String */) : undefined; + var numberIndexInfo = hasComputedNumberProperty ? getObjectLiteralIndexInfo(node.properties, offset, propertiesArray, 1 /* Number */) : undefined; + var result = createAnonymousType(node.symbol, propertiesTable, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); + result.flags |= 268435456 /* ContainsObjectLiteral */ | typeFlags & 939524096 /* PropagatingFlags */; + result.objectFlags |= 128 /* ObjectLiteral */ | freshObjectLiteralFlag; + if (isJSObjectLiteral) { + result.objectFlags |= 16384 /* JSLiteral */; + } + if (patternWithComputedProperties) { + result.objectFlags |= 512 /* ObjectLiteralPatternWithComputedProperties */; + } + if (inDestructuringPattern) { + result.pattern = node; + } + propagatedFlags |= result.flags & 939524096 /* PropagatingFlags */; + return result; + } + } + function isValidSpreadType(type) { + return !!(type.flags & (3 /* AnyOrUnknown */ | 67108864 /* NonPrimitive */ | 524288 /* Object */ | 58982400 /* InstantiableNonPrimitive */) || + getFalsyFlags(type) & 117632 /* DefinitelyFalsy */ && isValidSpreadType(removeDefinitelyFalsyTypes(type)) || + type.flags & 3145728 /* UnionOrIntersection */ && ts.every(type.types, isValidSpreadType)); + } + function checkJsxSelfClosingElementDeferred(node) { + checkJsxOpeningLikeElementOrOpeningFragment(node); + } + function checkJsxSelfClosingElement(node, _checkMode) { + checkNodeDeferred(node); + return getJsxElementTypeAt(node) || anyType; + } + function checkJsxElementDeferred(node) { + // Check attributes + checkJsxOpeningLikeElementOrOpeningFragment(node.openingElement); + // Perform resolution on the closing tag so that rename/go to definition/etc work + if (isJsxIntrinsicIdentifier(node.closingElement.tagName)) { + getIntrinsicTagSymbol(node.closingElement); + } + else { + checkExpression(node.closingElement.tagName); + } + checkJsxChildren(node); + } + function checkJsxElement(node, _checkMode) { + checkNodeDeferred(node); + return getJsxElementTypeAt(node) || anyType; + } + function checkJsxFragment(node) { + checkJsxOpeningLikeElementOrOpeningFragment(node.openingFragment); + if (compilerOptions.jsx === 2 /* React */ && (compilerOptions.jsxFactory || ts.getSourceFileOfNode(node).pragmas.has("jsx"))) { + error(node, compilerOptions.jsxFactory + ? ts.Diagnostics.JSX_fragment_is_not_supported_when_using_jsxFactory + : ts.Diagnostics.JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma); + } + checkJsxChildren(node); + return getJsxElementTypeAt(node) || anyType; + } + /** + * Returns true iff the JSX element name would be a valid JS identifier, ignoring restrictions about keywords not being identifiers + */ + function isUnhyphenatedJsxName(name) { + // - is the only character supported in JSX attribute names that isn't valid in JavaScript identifiers + return !ts.stringContains(name, "-"); + } + /** + * Returns true iff React would emit this tag name as a string rather than an identifier or qualified name + */ + function isJsxIntrinsicIdentifier(tagName) { + return tagName.kind === 72 /* Identifier */ && ts.isIntrinsicJsxName(tagName.escapedText); + } + function checkJsxAttribute(node, checkMode) { + return node.initializer + ? checkExpressionForMutableLocation(node.initializer, checkMode) + : trueType; // is sugar for + } + /** + * Get attributes type of the JSX opening-like element. The result is from resolving "attributes" property of the opening-like element. + * + * @param openingLikeElement a JSX opening-like element + * @param filter a function to remove attributes that will not participate in checking whether attributes are assignable + * @return an anonymous type (similar to the one returned by checkObjectLiteral) in which its properties are attributes property. + * @remarks Because this function calls getSpreadType, it needs to use the same checks as checkObjectLiteral, + * which also calls getSpreadType. + */ + function createJsxAttributesTypeFromAttributesProperty(openingLikeElement, checkMode) { + var attributes = openingLikeElement.attributes; + var attributesTable = ts.createSymbolTable(); + var spread = emptyJsxObjectType; + var hasSpreadAnyType = false; + var typeToIntersect; + var explicitlySpecifyChildrenAttribute = false; + var typeFlags = 0; + var objectFlags = 4096 /* JsxAttributes */; + var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(openingLikeElement)); + for (var _i = 0, _a = attributes.properties; _i < _a.length; _i++) { + var attributeDecl = _a[_i]; + var member = attributeDecl.symbol; + if (ts.isJsxAttribute(attributeDecl)) { + var exprType = checkJsxAttribute(attributeDecl, checkMode); + typeFlags |= exprType.flags & 939524096 /* PropagatingFlags */; + var attributeSymbol = createSymbol(4 /* Property */ | 33554432 /* Transient */ | member.flags, member.escapedName); + attributeSymbol.declarations = member.declarations; + attributeSymbol.parent = member.parent; + if (member.valueDeclaration) { + attributeSymbol.valueDeclaration = member.valueDeclaration; + } + attributeSymbol.type = exprType; + attributeSymbol.target = member; + attributesTable.set(attributeSymbol.escapedName, attributeSymbol); + if (attributeDecl.name.escapedText === jsxChildrenPropertyName) { + explicitlySpecifyChildrenAttribute = true; + } + } + else { + ts.Debug.assert(attributeDecl.kind === 269 /* JsxSpreadAttribute */); + if (attributesTable.size > 0) { + spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, typeFlags, objectFlags); + attributesTable = ts.createSymbolTable(); + } + var exprType = checkExpressionCached(attributeDecl.expression, checkMode); + if (isTypeAny(exprType)) { + hasSpreadAnyType = true; + } + if (isValidSpreadType(exprType)) { + spread = getSpreadType(spread, exprType, attributes.symbol, typeFlags, objectFlags); + } + else { + typeToIntersect = typeToIntersect ? getIntersectionType([typeToIntersect, exprType]) : exprType; + } + } + } + if (!hasSpreadAnyType) { + if (attributesTable.size > 0) { + spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, typeFlags, objectFlags); + } + } + // Handle children attribute + var parent = openingLikeElement.parent.kind === 260 /* JsxElement */ ? openingLikeElement.parent : undefined; + // We have to check that openingElement of the parent is the one we are visiting as this may not be true for selfClosingElement + if (parent && parent.openingElement === openingLikeElement && parent.children.length > 0) { + var childrenTypes = checkJsxChildren(parent, checkMode); + if (!hasSpreadAnyType && jsxChildrenPropertyName && jsxChildrenPropertyName !== "") { + // Error if there is a attribute named "children" explicitly specified and children element. + // This is because children element will overwrite the value from attributes. + // Note: we will not warn "children" attribute overwritten if "children" attribute is specified in object spread. + if (explicitlySpecifyChildrenAttribute) { + error(attributes, ts.Diagnostics._0_are_specified_twice_The_attribute_named_0_will_be_overwritten, ts.unescapeLeadingUnderscores(jsxChildrenPropertyName)); + } + var contextualType = getApparentTypeOfContextualType(openingLikeElement.attributes); + var childrenContextualType = contextualType && getTypeOfPropertyOfContextualType(contextualType, jsxChildrenPropertyName); + // If there are children in the body of JSX element, create dummy attribute "children" with the union of children types so that it will pass the attribute checking process + var childrenPropSymbol = createSymbol(4 /* Property */ | 33554432 /* Transient */, jsxChildrenPropertyName); + childrenPropSymbol.type = childrenTypes.length === 1 ? + childrenTypes[0] : + (getArrayLiteralTupleTypeIfApplicable(childrenTypes, childrenContextualType, /*hasRestElement*/ false) || createArrayType(getUnionType(childrenTypes))); + var childPropMap = ts.createSymbolTable(); + childPropMap.set(jsxChildrenPropertyName, childrenPropSymbol); + spread = getSpreadType(spread, createAnonymousType(attributes.symbol, childPropMap, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined), attributes.symbol, typeFlags, objectFlags); + } + } + if (hasSpreadAnyType) { + return anyType; + } + if (typeToIntersect && spread !== emptyJsxObjectType) { + return getIntersectionType([typeToIntersect, spread]); + } + return typeToIntersect || (spread === emptyJsxObjectType ? createJsxAttributesType() : spread); + /** + * Create anonymous type from given attributes symbol table. + * @param symbol a symbol of JsxAttributes containing attributes corresponding to attributesTable + * @param attributesTable a symbol table of attributes property + */ + function createJsxAttributesType() { + objectFlags |= freshObjectLiteralFlag; + var result = createAnonymousType(attributes.symbol, attributesTable, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined); + result.flags |= 268435456 /* ContainsObjectLiteral */ | typeFlags; + result.objectFlags |= 128 /* ObjectLiteral */ | objectFlags; + return result; + } + } + function checkJsxChildren(node, checkMode) { + var childrenTypes = []; + for (var _i = 0, _a = node.children; _i < _a.length; _i++) { + var child = _a[_i]; + // In React, JSX text that contains only whitespaces will be ignored so we don't want to type-check that + // because then type of children property will have constituent of string type. + if (child.kind === 11 /* JsxText */) { + if (!child.containsOnlyWhiteSpaces) { + childrenTypes.push(stringType); + } + } + else { + childrenTypes.push(checkExpressionForMutableLocation(child, checkMode)); + } + } + return childrenTypes; + } + /** + * Check attributes property of opening-like element. This function is called during chooseOverload to get call signature of a JSX opening-like element. + * (See "checkApplicableSignatureForJsxOpeningLikeElement" for how the function is used) + * @param node a JSXAttributes to be resolved of its type + */ + function checkJsxAttributes(node, checkMode) { + return createJsxAttributesTypeFromAttributesProperty(node.parent, checkMode); + } + function getJsxType(name, location) { + var namespace = getJsxNamespaceAt(location); + var exports = namespace && getExportsOfSymbol(namespace); + var typeSymbol = exports && getSymbol(exports, name, 67897832 /* Type */); + return typeSymbol ? getDeclaredTypeOfSymbol(typeSymbol) : errorType; + } + /** + * Looks up an intrinsic tag name and returns a symbol that either points to an intrinsic + * property (in which case nodeLinks.jsxFlags will be IntrinsicNamedElement) or an intrinsic + * string index signature (in which case nodeLinks.jsxFlags will be IntrinsicIndexedElement). + * May also return unknownSymbol if both of these lookups fail. + */ + function getIntrinsicTagSymbol(node) { + var links = getNodeLinks(node); + if (!links.resolvedSymbol) { + var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements, node); + if (intrinsicElementsType !== errorType) { + // Property case + if (!ts.isIdentifier(node.tagName)) + return ts.Debug.fail(); + var intrinsicProp = getPropertyOfType(intrinsicElementsType, node.tagName.escapedText); + if (intrinsicProp) { + links.jsxFlags |= 1 /* IntrinsicNamedElement */; + return links.resolvedSymbol = intrinsicProp; + } + // Intrinsic string indexer case + var indexSignatureType = getIndexTypeOfType(intrinsicElementsType, 0 /* String */); + if (indexSignatureType) { + links.jsxFlags |= 2 /* IntrinsicIndexedElement */; + return links.resolvedSymbol = intrinsicElementsType.symbol; + } + // Wasn't found + error(node, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.idText(node.tagName), "JSX." + JsxNames.IntrinsicElements); + return links.resolvedSymbol = unknownSymbol; + } + else { + if (noImplicitAny) { + error(node, ts.Diagnostics.JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists, ts.unescapeLeadingUnderscores(JsxNames.IntrinsicElements)); + } + return links.resolvedSymbol = unknownSymbol; + } + } + return links.resolvedSymbol; + } + function getJsxNamespaceAt(location) { + var links = location && getNodeLinks(location); + if (links && links.jsxNamespace) { + return links.jsxNamespace; + } + if (!links || links.jsxNamespace !== false) { + var namespaceName = getJsxNamespace(location); + var resolvedNamespace = resolveName(location, namespaceName, 1920 /* Namespace */, /*diagnosticMessage*/ undefined, namespaceName, /*isUse*/ false); + if (resolvedNamespace) { + var candidate = getSymbol(getExportsOfSymbol(resolveSymbol(resolvedNamespace)), JsxNames.JSX, 1920 /* Namespace */); + if (candidate) { + if (links) { + links.jsxNamespace = candidate; + } + return candidate; + } + if (links) { + links.jsxNamespace = false; + } + } + } + // JSX global fallback + return getGlobalSymbol(JsxNames.JSX, 1920 /* Namespace */, /*diagnosticMessage*/ undefined); // TODO: GH#18217 + } + /** + * Look into JSX namespace and then look for container with matching name as nameOfAttribPropContainer. + * Get a single property from that container if existed. Report an error if there are more than one property. + * + * @param nameOfAttribPropContainer a string of value JsxNames.ElementAttributesPropertyNameContainer or JsxNames.ElementChildrenAttributeNameContainer + * if other string is given or the container doesn't exist, return undefined. + */ + function getNameFromJsxElementAttributesContainer(nameOfAttribPropContainer, jsxNamespace) { + // JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute [symbol] + var jsxElementAttribPropInterfaceSym = jsxNamespace && getSymbol(jsxNamespace.exports, nameOfAttribPropContainer, 67897832 /* Type */); + // JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute [type] + var jsxElementAttribPropInterfaceType = jsxElementAttribPropInterfaceSym && getDeclaredTypeOfSymbol(jsxElementAttribPropInterfaceSym); + // The properties of JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute + var propertiesOfJsxElementAttribPropInterface = jsxElementAttribPropInterfaceType && getPropertiesOfType(jsxElementAttribPropInterfaceType); + if (propertiesOfJsxElementAttribPropInterface) { + // Element Attributes has zero properties, so the element attributes type will be the class instance type + if (propertiesOfJsxElementAttribPropInterface.length === 0) { + return ""; + } + // Element Attributes has one property, so the element attributes type will be the type of the corresponding + // property of the class instance type + else if (propertiesOfJsxElementAttribPropInterface.length === 1) { + return propertiesOfJsxElementAttribPropInterface[0].escapedName; + } + else if (propertiesOfJsxElementAttribPropInterface.length > 1) { + // More than one property on ElementAttributesProperty is an error + error(jsxElementAttribPropInterfaceSym.declarations[0], ts.Diagnostics.The_global_type_JSX_0_may_not_have_more_than_one_property, ts.unescapeLeadingUnderscores(nameOfAttribPropContainer)); + } + } + return undefined; + } + function getJsxLibraryManagedAttributes(jsxNamespace) { + // JSX.LibraryManagedAttributes [symbol] + return jsxNamespace && getSymbol(jsxNamespace.exports, JsxNames.LibraryManagedAttributes, 67897832 /* Type */); + } + /// e.g. "props" for React.d.ts, + /// or 'undefined' if ElementAttributesProperty doesn't exist (which means all + /// non-intrinsic elements' attributes type is 'any'), + /// or '' if it has 0 properties (which means every + /// non-intrinsic elements' attributes type is the element instance type) + function getJsxElementPropertiesName(jsxNamespace) { + return getNameFromJsxElementAttributesContainer(JsxNames.ElementAttributesPropertyNameContainer, jsxNamespace); + } + function getJsxElementChildrenPropertyName(jsxNamespace) { + return getNameFromJsxElementAttributesContainer(JsxNames.ElementChildrenAttributeNameContainer, jsxNamespace); + } + function getUninstantiatedJsxSignaturesOfType(elementType, caller) { + if (elementType.flags & 4 /* String */) { + return [anySignature]; + } + else if (elementType.flags & 128 /* StringLiteral */) { + var intrinsicType = getIntrinsicAttributesTypeFromStringLiteralType(elementType, caller); + if (!intrinsicType) { + error(caller, ts.Diagnostics.Property_0_does_not_exist_on_type_1, elementType.value, "JSX." + JsxNames.IntrinsicElements); + return ts.emptyArray; + } + else { + var fakeSignature = createSignatureForJSXIntrinsic(caller, intrinsicType); + return [fakeSignature]; + } + } + var apparentElemType = getApparentType(elementType); + // Resolve the signatures, preferring constructor + var signatures = getSignaturesOfType(apparentElemType, 1 /* Construct */); + if (signatures.length === 0) { + // No construct signatures, try call signatures + signatures = getSignaturesOfType(apparentElemType, 0 /* Call */); + } + if (signatures.length === 0 && apparentElemType.flags & 1048576 /* Union */) { + // If each member has some combination of new/call signatures; make a union signature list for those + signatures = getUnionSignatures(ts.map(apparentElemType.types, function (t) { return getUninstantiatedJsxSignaturesOfType(t, caller); })); + } + return signatures; + } + function getIntrinsicAttributesTypeFromStringLiteralType(type, location) { + // If the elemType is a stringLiteral type, we can then provide a check to make sure that the string literal type is one of the Jsx intrinsic element type + // For example: + // var CustomTag: "h1" = "h1"; + // Hello World + var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements, location); + if (intrinsicElementsType !== errorType) { + var stringLiteralTypeName = type.value; + var intrinsicProp = getPropertyOfType(intrinsicElementsType, ts.escapeLeadingUnderscores(stringLiteralTypeName)); + if (intrinsicProp) { + return getTypeOfSymbol(intrinsicProp); + } + var indexSignatureType = getIndexTypeOfType(intrinsicElementsType, 0 /* String */); + if (indexSignatureType) { + return indexSignatureType; + } + return undefined; + } + // If we need to report an error, we already done so here. So just return any to prevent any more error downstream + return anyType; + } + function checkJsxReturnAssignableToAppropriateBound(refKind, elemInstanceType, openingLikeElement) { + if (refKind === 1 /* Function */) { + var sfcReturnConstraint = getJsxStatelessElementTypeAt(openingLikeElement); + if (sfcReturnConstraint) { + checkTypeRelatedTo(elemInstanceType, sfcReturnConstraint, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); + } + } + else if (refKind === 0 /* Component */) { + var classConstraint = getJsxElementClassTypeAt(openingLikeElement); + if (classConstraint) { + // Issue an error if this return type isn't assignable to JSX.ElementClass or JSX.Element, failing that + checkTypeRelatedTo(elemInstanceType, classConstraint, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); + } + } + else { // Mixed + var sfcReturnConstraint = getJsxStatelessElementTypeAt(openingLikeElement); + var classConstraint = getJsxElementClassTypeAt(openingLikeElement); + if (!sfcReturnConstraint || !classConstraint) { + return; + } + var combined = getUnionType([sfcReturnConstraint, classConstraint]); + checkTypeRelatedTo(elemInstanceType, combined, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); + } + } + /** + * Get attributes type of the given intrinsic opening-like Jsx element by resolving the tag name. + * The function is intended to be called from a function which has checked that the opening element is an intrinsic element. + * @param node an intrinsic JSX opening-like element + */ + function getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node) { + ts.Debug.assert(isJsxIntrinsicIdentifier(node.tagName)); + var links = getNodeLinks(node); + if (!links.resolvedJsxElementAttributesType) { + var symbol = getIntrinsicTagSymbol(node); + if (links.jsxFlags & 1 /* IntrinsicNamedElement */) { + return links.resolvedJsxElementAttributesType = getTypeOfSymbol(symbol); + } + else if (links.jsxFlags & 2 /* IntrinsicIndexedElement */) { + return links.resolvedJsxElementAttributesType = getIndexInfoOfSymbol(symbol, 0 /* String */).type; + } + else { + return links.resolvedJsxElementAttributesType = errorType; + } + } + return links.resolvedJsxElementAttributesType; + } + function getJsxElementClassTypeAt(location) { + var type = getJsxType(JsxNames.ElementClass, location); + if (type === errorType) + return undefined; + return type; + } + function getJsxElementTypeAt(location) { + return getJsxType(JsxNames.Element, location); + } + function getJsxStatelessElementTypeAt(location) { + var jsxElementType = getJsxElementTypeAt(location); + if (jsxElementType) { + return getUnionType([jsxElementType, nullType]); + } + } + /** + * Returns all the properties of the Jsx.IntrinsicElements interface + */ + function getJsxIntrinsicTagNamesAt(location) { + var intrinsics = getJsxType(JsxNames.IntrinsicElements, location); + return intrinsics ? getPropertiesOfType(intrinsics) : ts.emptyArray; + } + function checkJsxPreconditions(errorNode) { + // Preconditions for using JSX + if ((compilerOptions.jsx || 0 /* None */) === 0 /* None */) { + error(errorNode, ts.Diagnostics.Cannot_use_JSX_unless_the_jsx_flag_is_provided); + } + if (getJsxElementTypeAt(errorNode) === undefined) { + if (noImplicitAny) { + error(errorNode, ts.Diagnostics.JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist); + } + } + } + function checkJsxOpeningLikeElementOrOpeningFragment(node) { + var isNodeOpeningLikeElement = ts.isJsxOpeningLikeElement(node); + if (isNodeOpeningLikeElement) { + checkGrammarJsxElement(node); + } + checkJsxPreconditions(node); + // The reactNamespace/jsxFactory's root symbol should be marked as 'used' so we don't incorrectly elide its import. + // And if there is no reactNamespace/jsxFactory's symbol in scope when targeting React emit, we should issue an error. + var reactRefErr = diagnostics && compilerOptions.jsx === 2 /* React */ ? ts.Diagnostics.Cannot_find_name_0 : undefined; + var reactNamespace = getJsxNamespace(node); + var reactLocation = isNodeOpeningLikeElement ? node.tagName : node; + var reactSym = resolveName(reactLocation, reactNamespace, 67220415 /* Value */, reactRefErr, reactNamespace, /*isUse*/ true); + if (reactSym) { + // Mark local symbol as referenced here because it might not have been marked + // if jsx emit was not react as there wont be error being emitted + reactSym.isReferenced = 67108863 /* All */; + // If react symbol is alias, mark it as refereced + if (reactSym.flags & 2097152 /* Alias */ && !isConstEnumOrConstEnumOnlyModule(resolveAlias(reactSym))) { + markAliasSymbolAsReferenced(reactSym); + } + } + if (isNodeOpeningLikeElement) { + var sig = getResolvedSignature(node); + checkJsxReturnAssignableToAppropriateBound(getJsxReferenceKind(node), getReturnTypeOfSignature(sig), node); + } + } + /** + * Check if a property with the given name is known anywhere in the given type. In an object type, a property + * is considered known if + * 1. the object type is empty and the check is for assignability, or + * 2. if the object type has index signatures, or + * 3. if the property is actually declared in the object type + * (this means that 'toString', for example, is not usually a known property). + * 4. In a union or intersection type, + * a property is considered known if it is known in any constituent type. + * @param targetType a type to search a given name in + * @param name a property name to search + * @param isComparingJsxAttributes a boolean flag indicating whether we are searching in JsxAttributesType + */ + function isKnownProperty(targetType, name, isComparingJsxAttributes) { + if (targetType.flags & 524288 /* Object */) { + var resolved = resolveStructuredTypeMembers(targetType); + if (resolved.stringIndexInfo || + resolved.numberIndexInfo && isNumericLiteralName(name) || + getPropertyOfObjectType(targetType, name) || + isComparingJsxAttributes && !isUnhyphenatedJsxName(name)) { + // For JSXAttributes, if the attribute has a hyphenated name, consider that the attribute to be known. + return true; + } + } + else if (targetType.flags & 3145728 /* UnionOrIntersection */) { + for (var _i = 0, _a = targetType.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (isKnownProperty(t, name, isComparingJsxAttributes)) { + return true; + } + } + } + else if (targetType.flags & 16777216 /* Conditional */) { + return isKnownProperty(targetType.root.trueType, name, isComparingJsxAttributes) || + isKnownProperty(targetType.root.falseType, name, isComparingJsxAttributes); + } + return false; + } + function checkJsxExpression(node, checkMode) { + if (node.expression) { + var type = checkExpression(node.expression, checkMode); + if (node.dotDotDotToken && type !== anyType && !isArrayType(type)) { + error(node, ts.Diagnostics.JSX_spread_child_must_be_an_array_type); + } + return type; + } + else { + return errorType; + } + } + function getDeclarationNodeFlagsFromSymbol(s) { + return s.valueDeclaration ? ts.getCombinedNodeFlags(s.valueDeclaration) : 0; + } + /** + * Return whether this symbol is a member of a prototype somewhere + * Note that this is not tracked well within the compiler, so the answer may be incorrect. + */ + function isPrototypeProperty(symbol) { + if (symbol.flags & 8192 /* Method */ || ts.getCheckFlags(symbol) & 4 /* SyntheticMethod */) { + return true; + } + if (ts.isInJSFile(symbol.valueDeclaration)) { + var parent = symbol.valueDeclaration.parent; + return parent && ts.isBinaryExpression(parent) && + ts.getAssignmentDeclarationKind(parent) === 3 /* PrototypeProperty */; + } + } + /** + * Check whether the requested property access is valid. + * Returns true if node is a valid property access, and false otherwise. + * @param node The node to be checked. + * @param isSuper True if the access is from `super.`. + * @param type The type of the object whose property is being accessed. (Not the type of the property.) + * @param prop The symbol for the property being accessed. + */ + function checkPropertyAccessibility(node, isSuper, type, prop) { + var flags = ts.getDeclarationModifierFlagsFromSymbol(prop); + var errorNode = node.kind === 148 /* QualifiedName */ ? node.right : node.kind === 183 /* ImportType */ ? node : node.name; + if (ts.getCheckFlags(prop) & 256 /* ContainsPrivate */) { + // Synthetic property with private constituent property + error(errorNode, ts.Diagnostics.Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1, symbolToString(prop), typeToString(type)); + return false; + } + if (isSuper) { + // TS 1.0 spec (April 2014): 4.8.2 + // - In a constructor, instance member function, instance member accessor, or + // instance member variable initializer where this references a derived class instance, + // a super property access is permitted and must specify a public instance member function of the base class. + // - In a static member function or static member accessor + // where this references the constructor function object of a derived class, + // a super property access is permitted and must specify a public static member function of the base class. + if (languageVersion < 2 /* ES2015 */) { + if (symbolHasNonMethodDeclaration(prop)) { + error(errorNode, ts.Diagnostics.Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword); + return false; + } + } + if (flags & 128 /* Abstract */) { + // A method cannot be accessed in a super property access if the method is abstract. + // This error could mask a private property access error. But, a member + // cannot simultaneously be private and abstract, so this will trigger an + // additional error elsewhere. + error(errorNode, ts.Diagnostics.Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression, symbolToString(prop), typeToString(getDeclaringClass(prop))); + return false; + } + } + // Referencing abstract properties within their own constructors is not allowed + if ((flags & 128 /* Abstract */) && ts.isThisProperty(node) && symbolHasNonMethodDeclaration(prop)) { + var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop)); + if (declaringClassDeclaration && isNodeUsedDuringClassInitialization(node)) { + error(errorNode, ts.Diagnostics.Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor, symbolToString(prop), ts.getTextOfIdentifierOrLiteral(declaringClassDeclaration.name)); // TODO: GH#18217 + return false; + } + } + // Public properties are otherwise accessible. + if (!(flags & 24 /* NonPublicAccessibilityModifier */)) { + return true; + } + // Property is known to be private or protected at this point + // Private property is accessible if the property is within the declaring class + if (flags & 8 /* Private */) { + var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop)); + if (!isNodeWithinClass(node, declaringClassDeclaration)) { + error(errorNode, ts.Diagnostics.Property_0_is_private_and_only_accessible_within_class_1, symbolToString(prop), typeToString(getDeclaringClass(prop))); + return false; + } + return true; + } + // Property is known to be protected at this point + // All protected properties of a supertype are accessible in a super access + if (isSuper) { + return true; + } + // Find the first enclosing class that has the declaring classes of the protected constituents + // of the property as base classes + var enclosingClass = forEachEnclosingClass(node, function (enclosingDeclaration) { + var enclosingClass = getDeclaredTypeOfSymbol(getSymbolOfNode(enclosingDeclaration)); + return isClassDerivedFromDeclaringClasses(enclosingClass, prop) ? enclosingClass : undefined; + }); + // A protected property is accessible if the property is within the declaring class or classes derived from it + if (!enclosingClass) { + // allow PropertyAccessibility if context is in function with this parameter + // static member access is disallow + var thisParameter = void 0; + if (flags & 32 /* Static */ || !(thisParameter = getThisParameterFromNodeContext(node)) || !thisParameter.type) { + error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses, symbolToString(prop), typeToString(getDeclaringClass(prop) || type)); + return false; + } + var thisType = getTypeFromTypeNode(thisParameter.type); + enclosingClass = ((thisType.flags & 262144 /* TypeParameter */) ? getConstraintOfTypeParameter(thisType) : thisType); + } + // No further restrictions for static properties + if (flags & 32 /* Static */) { + return true; + } + if (type.flags & 262144 /* TypeParameter */) { + // get the original type -- represented as the type constraint of the 'this' type + type = type.isThisType ? getConstraintOfTypeParameter(type) : getBaseConstraintOfType(type); // TODO: GH#18217 Use a different variable that's allowed to be undefined + } + if (!type || !hasBaseType(type, enclosingClass)) { + error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1, symbolToString(prop), typeToString(enclosingClass)); + return false; + } + return true; + } + function getThisParameterFromNodeContext(node) { + var thisContainer = ts.getThisContainer(node, /* includeArrowFunctions */ false); + return thisContainer && ts.isFunctionLike(thisContainer) ? ts.getThisParameter(thisContainer) : undefined; + } + function symbolHasNonMethodDeclaration(symbol) { + return !!forEachProperty(symbol, function (prop) { return !(prop.flags & 8192 /* Method */); }); + } + function checkNonNullExpression(node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic) { + return checkNonNullType(checkExpression(node), node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic); + } + function getNonNullableTypeIfNeeded(type) { + var kind = (strictNullChecks ? getFalsyFlags(type) : type.flags) & 98304 /* Nullable */; + if (kind) { + return getNonNullableType(type); + } + return type; + } + function checkNonNullType(type, node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic) { + if (type.flags & 2 /* Unknown */) { + error(node, ts.Diagnostics.Object_is_of_type_unknown); + return errorType; + } + var kind = (strictNullChecks ? getFalsyFlags(type) : type.flags) & 98304 /* Nullable */; + if (kind) { + error(node, kind & 32768 /* Undefined */ ? kind & 65536 /* Null */ ? + (nullOrUndefinedDiagnostic || ts.Diagnostics.Object_is_possibly_null_or_undefined) : + (undefinedDiagnostic || ts.Diagnostics.Object_is_possibly_undefined) : + (nullDiagnostic || ts.Diagnostics.Object_is_possibly_null)); + var t = getNonNullableType(type); + return t.flags & (98304 /* Nullable */ | 131072 /* Never */) ? errorType : t; + } + return type; + } + function checkPropertyAccessExpression(node) { + return checkPropertyAccessExpressionOrQualifiedName(node, node.expression, node.name); + } + function checkQualifiedName(node) { + return checkPropertyAccessExpressionOrQualifiedName(node, node.left, node.right); + } + function checkPropertyAccessExpressionOrQualifiedName(node, left, right) { + var propType; + var leftType = checkNonNullExpression(left); + var parentSymbol = getNodeLinks(left).resolvedSymbol; + var apparentType = getApparentType(getWidenedType(leftType)); + if (isTypeAny(apparentType) || apparentType === silentNeverType) { + if (ts.isIdentifier(left) && parentSymbol) { + markAliasReferenced(parentSymbol, node); + } + return apparentType; + } + var assignmentKind = ts.getAssignmentTargetKind(node); + var prop = getPropertyOfType(apparentType, right.escapedText); + if (ts.isIdentifier(left) && parentSymbol && !(prop && isConstEnumOrConstEnumOnlyModule(prop))) { + markAliasReferenced(parentSymbol, node); + } + if (!prop) { + var indexInfo = getIndexInfoOfType(apparentType, 0 /* String */); + if (!(indexInfo && indexInfo.type)) { + if (isJSLiteralType(leftType)) { + return anyType; + } + if (right.escapedText && !checkAndReportErrorForExtendingInterface(node)) { + reportNonexistentProperty(right, leftType.flags & 262144 /* TypeParameter */ && leftType.isThisType ? apparentType : leftType); + } + return errorType; + } + if (indexInfo.isReadonly && (ts.isAssignmentTarget(node) || ts.isDeleteTarget(node))) { + error(node, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(apparentType)); + } + propType = indexInfo.type; + } + else { + checkPropertyNotUsedBeforeDeclaration(prop, node, right); + markPropertyAsReferenced(prop, node, left.kind === 100 /* ThisKeyword */); + getNodeLinks(node).resolvedSymbol = prop; + checkPropertyAccessibility(node, left.kind === 98 /* SuperKeyword */, apparentType, prop); + if (assignmentKind) { + if (isReferenceToReadonlyEntity(node, prop) || isReferenceThroughNamespaceImport(node)) { + error(right, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, ts.idText(right)); + return errorType; + } + } + propType = getConstraintForLocation(getTypeOfSymbol(prop), node); + } + // Only compute control flow type if this is a property access expression that isn't an + // assignment target, and the referenced property was declared as a variable, property, + // accessor, or optional method. + if (node.kind !== 189 /* PropertyAccessExpression */ || + assignmentKind === 1 /* Definite */ || + prop && !(prop.flags & (3 /* Variable */ | 4 /* Property */ | 98304 /* Accessor */)) && !(prop.flags & 8192 /* Method */ && propType.flags & 1048576 /* Union */)) { + return propType; + } + // If strict null checks and strict property initialization checks are enabled, if we have + // a this.xxx property access, if the property is an instance property without an initializer, + // and if we are in a constructor of the same class as the property declaration, assume that + // the property is uninitialized at the top of the control flow. + var assumeUninitialized = false; + if (strictNullChecks && strictPropertyInitialization && left.kind === 100 /* ThisKeyword */) { + var declaration = prop && prop.valueDeclaration; + if (declaration && isInstancePropertyWithoutInitializer(declaration)) { + var flowContainer = getControlFlowContainer(node); + if (flowContainer.kind === 157 /* Constructor */ && flowContainer.parent === declaration.parent) { + assumeUninitialized = true; + } + } + } + else if (strictNullChecks && prop && prop.valueDeclaration && + ts.isPropertyAccessExpression(prop.valueDeclaration) && + ts.getAssignmentDeclarationPropertyAccessKind(prop.valueDeclaration) && + getControlFlowContainer(node) === getControlFlowContainer(prop.valueDeclaration)) { + assumeUninitialized = true; + } + var flowType = getFlowTypeOfReference(node, propType, assumeUninitialized ? getOptionalType(propType) : propType); + if (assumeUninitialized && !(getFalsyFlags(propType) & 32768 /* Undefined */) && getFalsyFlags(flowType) & 32768 /* Undefined */) { + error(right, ts.Diagnostics.Property_0_is_used_before_being_assigned, symbolToString(prop)); // TODO: GH#18217 + // Return the declared type to reduce follow-on errors + return propType; + } + return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType; + } + function checkPropertyNotUsedBeforeDeclaration(prop, node, right) { + var valueDeclaration = prop.valueDeclaration; + if (!valueDeclaration) { + return; + } + var diagnosticMessage; + var declarationName = ts.idText(right); + if (isInPropertyInitializer(node) && + !isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right) + && !isPropertyDeclaredInAncestorClass(prop)) { + diagnosticMessage = error(right, ts.Diagnostics.Property_0_is_used_before_its_initialization, declarationName); + } + else if (valueDeclaration.kind === 240 /* ClassDeclaration */ && + node.parent.kind !== 164 /* TypeReference */ && + !(valueDeclaration.flags & 4194304 /* Ambient */) && + !isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right)) { + diagnosticMessage = error(right, ts.Diagnostics.Class_0_used_before_its_declaration, declarationName); + } + if (diagnosticMessage) { + addRelatedInfo(diagnosticMessage, ts.createDiagnosticForNode(valueDeclaration, ts.Diagnostics._0_is_declared_here, declarationName)); + } + } + function isInPropertyInitializer(node) { + return !!ts.findAncestor(node, function (node) { + switch (node.kind) { + case 154 /* PropertyDeclaration */: + return true; + case 275 /* PropertyAssignment */: + // We might be in `a = { b: this.b }`, so keep looking. See `tests/cases/compiler/useBeforeDeclaration_propertyAssignment.ts`. + return false; + default: + return ts.isExpressionNode(node) ? false : "quit"; + } + }); + } + /** + * It's possible that "prop.valueDeclaration" is a local declaration, but the property was also declared in a superclass. + * In that case we won't consider it used before its declaration, because it gets its value from the superclass' declaration. + */ + function isPropertyDeclaredInAncestorClass(prop) { + if (!(prop.parent.flags & 32 /* Class */)) { + return false; + } + var classType = getTypeOfSymbol(prop.parent); + while (true) { + classType = classType.symbol && getSuperClass(classType); + if (!classType) { + return false; + } + var superProperty = getPropertyOfType(classType, prop.escapedName); + if (superProperty && superProperty.valueDeclaration) { + return true; + } + } + } + function getSuperClass(classType) { + var x = getBaseTypes(classType); + if (x.length === 0) { + return undefined; + } + return getIntersectionType(x); + } + function reportNonexistentProperty(propNode, containingType) { + var errorInfo; + var relatedInfo; + if (containingType.flags & 1048576 /* Union */ && !(containingType.flags & 131068 /* Primitive */)) { + for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) { + var subtype = _a[_i]; + if (!getPropertyOfType(subtype, propNode.escapedText)) { + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(subtype)); + break; + } + } + } + if (typeHasStaticProperty(propNode.escapedText, containingType)) { + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_is_a_static_member_of_type_1, ts.declarationNameToString(propNode), typeToString(containingType)); + } + else { + var promisedType = getPromisedTypeOfPromise(containingType); + if (promisedType && getPropertyOfType(promisedType, propNode.escapedText)) { + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_forget_to_use_await, ts.declarationNameToString(propNode), typeToString(containingType)); + } + else { + var suggestion = getSuggestedSymbolForNonexistentProperty(propNode, containingType); + if (suggestion !== undefined) { + var suggestedName = ts.symbolName(suggestion); + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2, ts.declarationNameToString(propNode), typeToString(containingType), suggestedName); + relatedInfo = suggestion.valueDeclaration && ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestedName); + } + else { + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(containingType)); + } + } + } + var resultDiagnostic = ts.createDiagnosticForNodeFromMessageChain(propNode, errorInfo); + if (relatedInfo) { + addRelatedInfo(resultDiagnostic, relatedInfo); + } + diagnostics.add(resultDiagnostic); + } + function typeHasStaticProperty(propName, containingType) { + var prop = containingType.symbol && getPropertyOfType(getTypeOfSymbol(containingType.symbol), propName); + return prop !== undefined && prop.valueDeclaration && ts.hasModifier(prop.valueDeclaration, 32 /* Static */); + } + function getSuggestedSymbolForNonexistentProperty(name, containingType) { + return getSpellingSuggestionForName(ts.isString(name) ? name : ts.idText(name), getPropertiesOfType(containingType), 67220415 /* Value */); + } + function getSuggestionForNonexistentProperty(name, containingType) { + var suggestion = getSuggestedSymbolForNonexistentProperty(name, containingType); + return suggestion && ts.symbolName(suggestion); + } + function getSuggestedSymbolForNonexistentSymbol(location, outerName, meaning) { + ts.Debug.assert(outerName !== undefined, "outername should always be defined"); + var result = resolveNameHelper(location, outerName, meaning, /*nameNotFoundMessage*/ undefined, outerName, /*isUse*/ false, /*excludeGlobals*/ false, function (symbols, name, meaning) { + ts.Debug.assertEqual(outerName, name, "name should equal outerName"); + var symbol = getSymbol(symbols, name, meaning); + // Sometimes the symbol is found when location is a return type of a function: `typeof x` and `x` is declared in the body of the function + // So the table *contains* `x` but `x` isn't actually in scope. + // However, resolveNameHelper will continue and call this callback again, so we'll eventually get a correct suggestion. + return symbol || getSpellingSuggestionForName(ts.unescapeLeadingUnderscores(name), ts.arrayFrom(symbols.values()), meaning); + }); + return result; + } + function getSuggestionForNonexistentSymbol(location, outerName, meaning) { + var symbolResult = getSuggestedSymbolForNonexistentSymbol(location, outerName, meaning); + return symbolResult && ts.symbolName(symbolResult); + } + function getSuggestedSymbolForNonexistentModule(name, targetModule) { + return targetModule.exports && getSpellingSuggestionForName(ts.idText(name), getExportsOfModuleAsArray(targetModule), 2623475 /* ModuleMember */); + } + function getSuggestionForNonexistentExport(name, targetModule) { + var suggestion = getSuggestedSymbolForNonexistentModule(name, targetModule); + return suggestion && ts.symbolName(suggestion); + } + /** + * Given a name and a list of symbols whose names are *not* equal to the name, return a spelling suggestion if there is one that is close enough. + * Names less than length 3 only check for case-insensitive equality, not levenshtein distance. + * + * If there is a candidate that's the same except for case, return that. + * If there is a candidate that's within one edit of the name, return that. + * Otherwise, return the candidate with the smallest Levenshtein distance, + * except for candidates: + * * With no name + * * Whose meaning doesn't match the `meaning` parameter. + * * Whose length differs from the target name by more than 0.34 of the length of the name. + * * Whose levenshtein distance is more than 0.4 of the length of the name + * (0.4 allows 1 substitution/transposition for every 5 characters, + * and 1 insertion/deletion at 3 characters) + */ + function getSpellingSuggestionForName(name, symbols, meaning) { + return ts.getSpellingSuggestion(name, symbols, getCandidateName); + function getCandidateName(candidate) { + var candidateName = ts.symbolName(candidate); + return !ts.startsWith(candidateName, "\"") && candidate.flags & meaning ? candidateName : undefined; + } + } + function markPropertyAsReferenced(prop, nodeForCheckWriteOnly, isThisAccess) { + if (!prop || !(prop.flags & 106500 /* ClassMember */) || !prop.valueDeclaration || !ts.hasModifier(prop.valueDeclaration, 8 /* Private */)) { + return; + } + if (nodeForCheckWriteOnly && ts.isWriteOnlyAccess(nodeForCheckWriteOnly) && !(prop.flags & 65536 /* SetAccessor */ && !(prop.flags & 32768 /* GetAccessor */))) { + return; + } + if (isThisAccess) { + // Find any FunctionLikeDeclaration because those create a new 'this' binding. But this should only matter for methods (or getters/setters). + var containingMethod = ts.findAncestor(nodeForCheckWriteOnly, ts.isFunctionLikeDeclaration); + if (containingMethod && containingMethod.symbol === prop) { + return; + } + } + (ts.getCheckFlags(prop) & 1 /* Instantiated */ ? getSymbolLinks(prop).target : prop).isReferenced = 67108863 /* All */; + } + function isValidPropertyAccess(node, propertyName) { + switch (node.kind) { + case 189 /* PropertyAccessExpression */: + return isValidPropertyAccessWithType(node, node.expression.kind === 98 /* SuperKeyword */, propertyName, getWidenedType(checkExpression(node.expression))); + case 148 /* QualifiedName */: + return isValidPropertyAccessWithType(node, /*isSuper*/ false, propertyName, getWidenedType(checkExpression(node.left))); + case 183 /* ImportType */: + return isValidPropertyAccessWithType(node, /*isSuper*/ false, propertyName, getTypeFromTypeNode(node)); + } + } + function isValidPropertyAccessForCompletions(node, type, property) { + return isValidPropertyAccessWithType(node, node.kind !== 183 /* ImportType */ && node.expression.kind === 98 /* SuperKeyword */, property.escapedName, type) + && (!(property.flags & 8192 /* Method */) || isValidMethodAccess(property, type)); + } + function isValidMethodAccess(method, actualThisType) { + var propType = getTypeOfPropertyOfType(actualThisType, method.escapedName); + var signatures = getSignaturesOfType(getNonNullableType(propType), 0 /* Call */); + ts.Debug.assert(signatures.length !== 0); + return signatures.some(function (sig) { + var signatureThisType = getThisTypeOfSignature(sig); + return !signatureThisType || isTypeAssignableTo(actualThisType, getInstantiatedSignatureThisType(sig, signatureThisType, actualThisType)); + }); + } + function getInstantiatedSignatureThisType(sig, signatureThisType, actualThisType) { + if (!sig.typeParameters) { + return signatureThisType; + } + var context = createInferenceContext(sig.typeParameters, sig, 0 /* None */); + inferTypes(context.inferences, actualThisType, signatureThisType); + return instantiateType(signatureThisType, createSignatureTypeMapper(sig, getInferredTypes(context))); + } + function isValidPropertyAccessWithType(node, isSuper, propertyName, type) { + if (type === errorType || isTypeAny(type)) { + return true; + } + var prop = getPropertyOfType(type, propertyName); + return prop ? checkPropertyAccessibility(node, isSuper, type, prop) + // In js files properties of unions are allowed in completion + : ts.isInJSFile(node) && (type.flags & 1048576 /* Union */) !== 0 && type.types.some(function (elementType) { return isValidPropertyAccessWithType(node, isSuper, propertyName, elementType); }); + } + /** + * Return the symbol of the for-in variable declared or referenced by the given for-in statement. + */ + function getForInVariableSymbol(node) { + var initializer = node.initializer; + if (initializer.kind === 238 /* VariableDeclarationList */) { + var variable = initializer.declarations[0]; + if (variable && !ts.isBindingPattern(variable.name)) { + return getSymbolOfNode(variable); + } + } + else if (initializer.kind === 72 /* Identifier */) { + return getResolvedSymbol(initializer); + } + return undefined; + } + /** + * Return true if the given type is considered to have numeric property names. + */ + function hasNumericPropertyNames(type) { + return getIndexTypeOfType(type, 1 /* Number */) && !getIndexTypeOfType(type, 0 /* String */); + } + /** + * Return true if given node is an expression consisting of an identifier (possibly parenthesized) + * that references a for-in variable for an object with numeric property names. + */ + function isForInVariableForNumericPropertyNames(expr) { + var e = ts.skipParentheses(expr); + if (e.kind === 72 /* Identifier */) { + var symbol = getResolvedSymbol(e); + if (symbol.flags & 3 /* Variable */) { + var child = expr; + var node = expr.parent; + while (node) { + if (node.kind === 226 /* ForInStatement */ && + child === node.statement && + getForInVariableSymbol(node) === symbol && + hasNumericPropertyNames(getTypeOfExpression(node.expression))) { + return true; + } + child = node; + node = node.parent; + } + } + } + return false; + } + function checkIndexedAccess(node) { + var objectType = checkNonNullExpression(node.expression); + var indexExpression = node.argumentExpression; + if (!indexExpression) { + var sourceFile = ts.getSourceFileOfNode(node); + if (node.parent.kind === 192 /* NewExpression */ && node.parent.expression === node) { + var start = ts.skipTrivia(sourceFile.text, node.expression.end); + var end = node.end; + grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead); + } + else { + var start = node.end - "]".length; + var end = node.end; + grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.Expression_expected); + } + return errorType; + } + var indexType = checkExpression(indexExpression); + if (objectType === errorType || objectType === silentNeverType) { + return objectType; + } + if (isConstEnumObjectType(objectType) && indexExpression.kind !== 10 /* StringLiteral */) { + error(indexExpression, ts.Diagnostics.A_const_enum_member_can_only_be_accessed_using_a_string_literal); + return errorType; + } + return checkIndexedAccessIndexType(getIndexedAccessType(objectType, isForInVariableForNumericPropertyNames(indexExpression) ? numberType : indexType, node), node); + } + function checkThatExpressionIsProperSymbolReference(expression, expressionType, reportError) { + if (expressionType === errorType) { + // There is already an error, so no need to report one. + return false; + } + if (!ts.isWellKnownSymbolSyntactically(expression)) { + return false; + } + // Make sure the property type is the primitive symbol type + if ((expressionType.flags & 12288 /* ESSymbolLike */) === 0) { + if (reportError) { + error(expression, ts.Diagnostics.A_computed_property_name_of_the_form_0_must_be_of_type_symbol, ts.getTextOfNode(expression)); + } + return false; + } + // The name is Symbol., so make sure Symbol actually resolves to the + // global Symbol object + var leftHandSide = expression.expression; + var leftHandSideSymbol = getResolvedSymbol(leftHandSide); + if (!leftHandSideSymbol) { + return false; + } + var globalESSymbol = getGlobalESSymbolConstructorSymbol(/*reportErrors*/ true); + if (!globalESSymbol) { + // Already errored when we tried to look up the symbol + return false; + } + if (leftHandSideSymbol !== globalESSymbol) { + if (reportError) { + error(leftHandSide, ts.Diagnostics.Symbol_reference_does_not_refer_to_the_global_Symbol_constructor_object); + } + return false; + } + return true; + } + function callLikeExpressionMayHaveTypeArguments(node) { + return ts.isCallOrNewExpression(node) || ts.isTaggedTemplateExpression(node) || ts.isJsxOpeningLikeElement(node); + } + function resolveUntypedCall(node) { + if (callLikeExpressionMayHaveTypeArguments(node)) { + // Check type arguments even though we will give an error that untyped calls may not accept type arguments. + // This gets us diagnostics for the type arguments and marks them as referenced. + ts.forEach(node.typeArguments, checkSourceElement); + } + if (node.kind === 193 /* TaggedTemplateExpression */) { + checkExpression(node.template); + } + else if (ts.isJsxOpeningLikeElement(node)) { + checkExpression(node.attributes); + } + else if (node.kind !== 152 /* Decorator */) { + ts.forEach(node.arguments, function (argument) { + checkExpression(argument); + }); + } + return anySignature; + } + function resolveErrorCall(node) { + resolveUntypedCall(node); + return unknownSignature; + } + // Re-order candidate signatures into the result array. Assumes the result array to be empty. + // The candidate list orders groups in reverse, but within a group signatures are kept in declaration order + // A nit here is that we reorder only signatures that belong to the same symbol, + // so order how inherited signatures are processed is still preserved. + // interface A { (x: string): void } + // interface B extends A { (x: 'foo'): string } + // const b: B; + // b('foo') // <- here overloads should be processed as [(x:'foo'): string, (x: string): void] + function reorderCandidates(signatures, result) { + var lastParent; + var lastSymbol; + var cutoffIndex = 0; + var index; + var specializedIndex = -1; + var spliceIndex; + ts.Debug.assert(!result.length); + for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { + var signature = signatures_3[_i]; + var symbol = signature.declaration && getSymbolOfNode(signature.declaration); + var parent = signature.declaration && signature.declaration.parent; + if (!lastSymbol || symbol === lastSymbol) { + if (lastParent && parent === lastParent) { + index = index + 1; + } + else { + lastParent = parent; + index = cutoffIndex; + } + } + else { + // current declaration belongs to a different symbol + // set cutoffIndex so re-orderings in the future won't change result set from 0 to cutoffIndex + index = cutoffIndex = result.length; + lastParent = parent; + } + lastSymbol = symbol; + // specialized signatures always need to be placed before non-specialized signatures regardless + // of the cutoff position; see GH#1133 + if (signature.hasLiteralTypes) { + specializedIndex++; + spliceIndex = specializedIndex; + // The cutoff index always needs to be greater than or equal to the specialized signature index + // in order to prevent non-specialized signatures from being added before a specialized + // signature. + cutoffIndex++; + } + else { + spliceIndex = index; + } + result.splice(spliceIndex, 0, signature); + } + } + function isSpreadArgument(arg) { + return !!arg && (arg.kind === 208 /* SpreadElement */ || arg.kind === 215 /* SyntheticExpression */ && arg.isSpread); + } + function getSpreadArgumentIndex(args) { + return ts.findIndex(args, isSpreadArgument); + } + function acceptsVoid(t) { + return !!(t.flags & 16384 /* Void */); + } + function hasCorrectArity(node, args, signature, signatureHelpTrailingComma) { + if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; } + var argCount; + var callIsIncomplete = false; // In incomplete call we want to be lenient when we have too few arguments + var effectiveParameterCount = getParameterCount(signature); + var effectiveMinimumArguments = getMinArgumentCount(signature); + if (node.kind === 193 /* TaggedTemplateExpression */) { + argCount = args.length; + if (node.template.kind === 206 /* TemplateExpression */) { + // If a tagged template expression lacks a tail literal, the call is incomplete. + // Specifically, a template only can end in a TemplateTail or a Missing literal. + var lastSpan = ts.last(node.template.templateSpans); // we should always have at least one span. + callIsIncomplete = ts.nodeIsMissing(lastSpan.literal) || !!lastSpan.literal.isUnterminated; + } + else { + // If the template didn't end in a backtick, or its beginning occurred right prior to EOF, + // then this might actually turn out to be a TemplateHead in the future; + // so we consider the call to be incomplete. + var templateLiteral = node.template; + ts.Debug.assert(templateLiteral.kind === 14 /* NoSubstitutionTemplateLiteral */); + callIsIncomplete = !!templateLiteral.isUnterminated; + } + } + else if (node.kind === 152 /* Decorator */) { + argCount = getDecoratorArgumentCount(node, signature); + } + else if (ts.isJsxOpeningLikeElement(node)) { + callIsIncomplete = node.attributes.end === node.end; + if (callIsIncomplete) { + return true; + } + argCount = effectiveMinimumArguments === 0 ? args.length : 1; + effectiveParameterCount = args.length === 0 ? effectiveParameterCount : 1; // class may have argumentless ctor functions - still resolve ctor and compare vs props member type + effectiveMinimumArguments = Math.min(effectiveMinimumArguments, 1); // sfc may specify context argument - handled by framework and not typechecked + } + else { + if (!node.arguments) { + // This only happens when we have something of the form: 'new C' + ts.Debug.assert(node.kind === 192 /* NewExpression */); + return getMinArgumentCount(signature) === 0; + } + argCount = signatureHelpTrailingComma ? args.length + 1 : args.length; + // If we are missing the close parenthesis, the call is incomplete. + callIsIncomplete = node.arguments.end === node.end; + // If a spread argument is present, check that it corresponds to a rest parameter or at least that it's in the valid range. + var spreadArgIndex = getSpreadArgumentIndex(args); + if (spreadArgIndex >= 0) { + return spreadArgIndex >= getMinArgumentCount(signature) && (hasEffectiveRestParameter(signature) || spreadArgIndex < getParameterCount(signature)); + } + } + // Too many arguments implies incorrect arity. + if (!hasEffectiveRestParameter(signature) && argCount > effectiveParameterCount) { + return false; + } + // If the call is incomplete, we should skip the lower bound check. + // JSX signatures can have extra parameters provided by the library which we don't check + if (callIsIncomplete || argCount >= effectiveMinimumArguments) { + return true; + } + for (var i = argCount; i < effectiveMinimumArguments; i++) { + var type = getTypeAtPosition(signature, i); + if (filterType(type, acceptsVoid).flags & 131072 /* Never */) { + return false; + } + } + return true; + } + function hasCorrectTypeArgumentArity(signature, typeArguments) { + // If the user supplied type arguments, but the number of type arguments does not match + // the declared number of type parameters, the call has an incorrect arity. + var numTypeParameters = ts.length(signature.typeParameters); + var minTypeArgumentCount = getMinTypeArgumentCount(signature.typeParameters); + return !typeArguments || + (typeArguments.length >= minTypeArgumentCount && typeArguments.length <= numTypeParameters); + } + // If type has a single call signature and no other members, return that signature. Otherwise, return undefined. + function getSingleCallSignature(type) { + if (type.flags & 524288 /* Object */) { + var resolved = resolveStructuredTypeMembers(type); + if (resolved.callSignatures.length === 1 && resolved.constructSignatures.length === 0 && + resolved.properties.length === 0 && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { + return resolved.callSignatures[0]; + } + } + return undefined; + } + // Instantiate a generic signature in the context of a non-generic signature (section 3.8.5 in TypeScript spec) + function instantiateSignatureInContextOf(signature, contextualSignature, contextualMapper, compareTypes) { + var context = createInferenceContext(signature.typeParameters, signature, 0 /* None */, compareTypes); + var sourceSignature = contextualMapper ? instantiateSignature(contextualSignature, contextualMapper) : contextualSignature; + forEachMatchingParameterType(sourceSignature, signature, function (source, target) { + // Type parameters from outer context referenced by source type are fixed by instantiation of the source type + inferTypes(context.inferences, source, target); + }); + if (!contextualMapper) { + inferTypes(context.inferences, getReturnTypeOfSignature(contextualSignature), getReturnTypeOfSignature(signature), 8 /* ReturnType */); + } + return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJSFile(contextualSignature.declaration)); + } + function inferJsxTypeArguments(node, signature, excludeArgument, context) { + var paramType = getEffectiveFirstArgumentForJsxSignature(signature, node); + var checkAttrType = checkExpressionWithContextualType(node.attributes, paramType, excludeArgument && excludeArgument[0] !== undefined ? identityMapper : context); + inferTypes(context.inferences, checkAttrType, paramType); + return getInferredTypes(context); + } + function inferTypeArguments(node, signature, args, excludeArgument, context) { + // Clear out all the inference results from the last time inferTypeArguments was called on this context + for (var _i = 0, _a = context.inferences; _i < _a.length; _i++) { + var inference = _a[_i]; + // As an optimization, we don't have to clear (and later recompute) inferred types + // for type parameters that have already been fixed on the previous call to inferTypeArguments. + // It would be just as correct to reset all of them. But then we'd be repeating the same work + // for the type parameters that were fixed, namely the work done by getInferredType. + if (!inference.isFixed) { + inference.inferredType = undefined; + } + } + if (ts.isJsxOpeningLikeElement(node)) { + return inferJsxTypeArguments(node, signature, excludeArgument, context); + } + // If a contextual type is available, infer from that type to the return type of the call expression. For + // example, given a 'function wrap(cb: (x: T) => U): (x: T) => U' and a call expression + // 'let f: (x: string) => number = wrap(s => s.length)', we infer from the declared type of 'f' to the + // return type of 'wrap'. + if (node.kind !== 152 /* Decorator */) { + var contextualType = getContextualType(node); + if (contextualType) { + // We clone the contextual mapper to avoid disturbing a resolution in progress for an + // outer call expression. Effectively we just want a snapshot of whatever has been + // inferred for any outer call expression so far. + var instantiatedType = instantiateType(contextualType, cloneTypeMapper(getContextualMapper(node))); + // If the contextual type is a generic function type with a single call signature, we + // instantiate the type with its own type parameters and type arguments. This ensures that + // the type parameters are not erased to type any during type inference such that they can + // be inferred as actual types from the contextual type. For example: + // declare function arrayMap(f: (x: T) => U): (a: T[]) => U[]; + // const boxElements: (a: A[]) => { value: A }[] = arrayMap(value => ({ value })); + // Above, the type of the 'value' parameter is inferred to be 'A'. + var contextualSignature = getSingleCallSignature(instantiatedType); + var inferenceSourceType = contextualSignature && contextualSignature.typeParameters ? + getOrCreateTypeFromSignature(getSignatureInstantiationWithoutFillingInTypeArguments(contextualSignature, contextualSignature.typeParameters)) : + instantiatedType; + var inferenceTargetType = getReturnTypeOfSignature(signature); + // Inferences made from return types have lower priority than all other inferences. + inferTypes(context.inferences, inferenceSourceType, inferenceTargetType, 8 /* ReturnType */); + } + } + var thisType = getThisTypeOfSignature(signature); + if (thisType) { + var thisArgumentNode = getThisArgumentOfCall(node); + var thisArgumentType = thisArgumentNode ? checkExpression(thisArgumentNode) : voidType; + inferTypes(context.inferences, thisArgumentType, thisType); + } + var restType = getNonArrayRestType(signature); + var argCount = restType ? Math.min(getParameterCount(signature) - 1, args.length) : args.length; + for (var i = 0; i < argCount; i++) { + var arg = args[i]; + if (arg.kind !== 210 /* OmittedExpression */) { + var paramType = getTypeAtPosition(signature, i); + // For context sensitive arguments we pass the identityMapper, which is a signal to treat all + // context sensitive function expressions as wildcards + var mapper = excludeArgument && excludeArgument[i] !== undefined ? identityMapper : context; + var argType = checkExpressionWithContextualType(arg, paramType, mapper); + inferTypes(context.inferences, argType, paramType); + } + } + if (restType) { + var spreadType = getSpreadArgumentType(args, argCount, args.length, restType, context); + inferTypes(context.inferences, spreadType, restType); + } + return getInferredTypes(context); + } + function getArrayifiedType(type) { + if (forEachType(type, function (t) { return !(t.flags & (1 /* Any */ | 63176704 /* Instantiable */) || isArrayType(t) || isTupleType(t)); })) { + return createArrayType(getIndexTypeOfType(type, 1 /* Number */) || errorType); + } + return type; + } + function getSpreadArgumentType(args, index, argCount, restType, context) { + if (index >= argCount - 1) { + var arg = args[argCount - 1]; + if (isSpreadArgument(arg)) { + // We are inferring from a spread expression in the last argument position, i.e. both the parameter + // and the argument are ...x forms. + return arg.kind === 215 /* SyntheticExpression */ ? + createArrayType(arg.type) : + getArrayifiedType(checkExpressionWithContextualType(arg.expression, restType, context)); + } + } + var contextualType = getIndexTypeOfType(restType, 1 /* Number */) || anyType; + var hasPrimitiveContextualType = maybeTypeOfKind(contextualType, 131068 /* Primitive */ | 4194304 /* Index */); + var types = []; + var spreadIndex = -1; + for (var i = index; i < argCount; i++) { + var argType = checkExpressionWithContextualType(args[i], contextualType, context); + if (spreadIndex < 0 && isSpreadArgument(args[i])) { + spreadIndex = i - index; + } + types.push(hasPrimitiveContextualType ? getRegularTypeOfLiteralType(argType) : getWidenedLiteralType(argType)); + } + return spreadIndex < 0 ? + createTupleType(types) : + createTupleType(ts.append(types.slice(0, spreadIndex), getUnionType(types.slice(spreadIndex))), spreadIndex, /*hasRestElement*/ true); + } + function checkTypeArguments(signature, typeArgumentNodes, reportErrors, headMessage) { + var isJavascript = ts.isInJSFile(signature.declaration); + var typeParameters = signature.typeParameters; + var typeArgumentTypes = fillMissingTypeArguments(ts.map(typeArgumentNodes, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), isJavascript); + var mapper; + for (var i = 0; i < typeArgumentNodes.length; i++) { + ts.Debug.assert(typeParameters[i] !== undefined, "Should not call checkTypeArguments with too many type arguments"); + var constraint = getConstraintOfTypeParameter(typeParameters[i]); + if (constraint) { + var errorInfo = reportErrors && headMessage ? (function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); }) : undefined; + var typeArgumentHeadMessage = headMessage || ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1; + if (!mapper) { + mapper = createTypeMapper(typeParameters, typeArgumentTypes); + } + var typeArgument = typeArgumentTypes[i]; + if (!checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), reportErrors ? typeArgumentNodes[i] : undefined, typeArgumentHeadMessage, errorInfo)) { + return undefined; + } + } + } + return typeArgumentTypes; + } + function getJsxReferenceKind(node) { + if (isJsxIntrinsicIdentifier(node.tagName)) { + return 2 /* Mixed */; + } + var tagType = getApparentType(checkExpression(node.tagName)); + if (ts.length(getSignaturesOfType(tagType, 1 /* Construct */))) { + return 0 /* Component */; + } + if (ts.length(getSignaturesOfType(tagType, 0 /* Call */))) { + return 1 /* Function */; + } + return 2 /* Mixed */; + } + /** + * Check if the given signature can possibly be a signature called by the JSX opening-like element. + * @param node a JSX opening-like element we are trying to figure its call signature + * @param signature a candidate signature we are trying whether it is a call signature + * @param relation a relationship to check parameter and argument type + * @param excludeArgument + */ + function checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation, excludeArgument, reportErrors) { + // Stateless function components can have maximum of three arguments: "props", "context", and "updater". + // However "context" and "updater" are implicit and can't be specify by users. Only the first parameter, props, + // can be specified by users through attributes property. + var paramType = getEffectiveFirstArgumentForJsxSignature(signature, node); + var attributesType = checkExpressionWithContextualType(node.attributes, paramType, excludeArgument && excludeArgument[0] ? identityMapper : undefined); + return checkTypeRelatedToAndOptionallyElaborate(attributesType, paramType, relation, reportErrors ? node.tagName : undefined, node.attributes); + } + function checkApplicableSignature(node, args, signature, relation, excludeArgument, reportErrors) { + if (ts.isJsxOpeningLikeElement(node)) { + return checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation, excludeArgument, reportErrors); + } + var thisType = getThisTypeOfSignature(signature); + if (thisType && thisType !== voidType && node.kind !== 192 /* NewExpression */) { + // If the called expression is not of the form `x.f` or `x["f"]`, then sourceType = voidType + // If the signature's 'this' type is voidType, then the check is skipped -- anything is compatible. + // If the expression is a new expression, then the check is skipped. + var thisArgumentNode = getThisArgumentOfCall(node); + var thisArgumentType = thisArgumentNode ? checkExpression(thisArgumentNode) : voidType; + var errorNode = reportErrors ? (thisArgumentNode || node) : undefined; + var headMessage_1 = ts.Diagnostics.The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1; + if (!checkTypeRelatedTo(thisArgumentType, thisType, relation, errorNode, headMessage_1)) { + return false; + } + } + var headMessage = ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1; + var restType = getNonArrayRestType(signature); + var argCount = restType ? Math.min(getParameterCount(signature) - 1, args.length) : args.length; + for (var i = 0; i < argCount; i++) { + var arg = args[i]; + if (arg.kind !== 210 /* OmittedExpression */) { + var paramType = getTypeAtPosition(signature, i); + var argType = checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); + // If one or more arguments are still excluded (as indicated by a non-null excludeArgument parameter), + // we obtain the regular type of any object literal arguments because we may not have inferred complete + // parameter types yet and therefore excess property checks may yield false positives (see #17041). + var checkArgType = excludeArgument ? getRegularTypeOfObjectLiteral(argType) : argType; + if (!checkTypeRelatedToAndOptionallyElaborate(checkArgType, paramType, relation, reportErrors ? arg : undefined, arg, headMessage)) { + return false; + } + } + } + if (restType) { + var spreadType = getSpreadArgumentType(args, argCount, args.length, restType, /*context*/ undefined); + var errorNode = reportErrors ? argCount < args.length ? args[argCount] : node : undefined; + return checkTypeRelatedTo(spreadType, restType, relation, errorNode, headMessage); + } + return true; + } + /** + * Returns the this argument in calls like x.f(...) and x[f](...). Undefined otherwise. + */ + function getThisArgumentOfCall(node) { + if (node.kind === 191 /* CallExpression */) { + var callee = ts.skipOuterExpressions(node.expression); + if (callee.kind === 189 /* PropertyAccessExpression */ || callee.kind === 190 /* ElementAccessExpression */) { + return callee.expression; + } + } + } + function createSyntheticExpression(parent, type, isSpread) { + var result = ts.createNode(215 /* SyntheticExpression */, parent.pos, parent.end); + result.parent = parent; + result.type = type; + result.isSpread = isSpread || false; + return result; + } + /** + * Returns the effective arguments for an expression that works like a function invocation. + */ + function getEffectiveCallArguments(node) { + if (node.kind === 193 /* TaggedTemplateExpression */) { + var template = node.template; + var args_4 = [createSyntheticExpression(template, getGlobalTemplateStringsArrayType())]; + if (template.kind === 206 /* TemplateExpression */) { + ts.forEach(template.templateSpans, function (span) { + args_4.push(span.expression); + }); + } + return args_4; + } + if (node.kind === 152 /* Decorator */) { + return getEffectiveDecoratorArguments(node); + } + if (ts.isJsxOpeningLikeElement(node)) { + return node.attributes.properties.length > 0 || (ts.isJsxOpeningElement(node) && node.parent.children.length > 0) ? [node.attributes] : ts.emptyArray; + } + var args = node.arguments || ts.emptyArray; + var length = args.length; + if (length && isSpreadArgument(args[length - 1]) && getSpreadArgumentIndex(args) === length - 1) { + // We have a spread argument in the last position and no other spread arguments. If the type + // of the argument is a tuple type, spread the tuple elements into the argument list. We can + // call checkExpressionCached because spread expressions never have a contextual type. + var spreadArgument_1 = args[length - 1]; + var type = checkExpressionCached(spreadArgument_1.expression); + if (isTupleType(type)) { + var typeArguments = type.typeArguments || ts.emptyArray; + var restIndex_2 = type.target.hasRestElement ? typeArguments.length - 1 : -1; + var syntheticArgs = ts.map(typeArguments, function (t, i) { return createSyntheticExpression(spreadArgument_1, t, /*isSpread*/ i === restIndex_2); }); + return ts.concatenate(args.slice(0, length - 1), syntheticArgs); + } + } + return args; + } + /** + * Returns the synthetic argument list for a decorator invocation. + */ + function getEffectiveDecoratorArguments(node) { + var parent = node.parent; + var expr = node.expression; + switch (parent.kind) { + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + // For a class decorator, the `target` is the type of the class (e.g. the + // "static" or "constructor" side of the class). + return [ + createSyntheticExpression(expr, getTypeOfSymbol(getSymbolOfNode(parent))) + ]; + case 151 /* Parameter */: + // A parameter declaration decorator will have three arguments (see + // `ParameterDecorator` in core.d.ts). + var func = parent.parent; + return [ + createSyntheticExpression(expr, parent.parent.kind === 157 /* Constructor */ ? getTypeOfSymbol(getSymbolOfNode(func)) : errorType), + createSyntheticExpression(expr, anyType), + createSyntheticExpression(expr, numberType) + ]; + case 154 /* PropertyDeclaration */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + // A method or accessor declaration decorator will have two or three arguments (see + // `PropertyDecorator` and `MethodDecorator` in core.d.ts). If we are emitting decorators + // for ES3, we will only pass two arguments. + var hasPropDesc = parent.kind !== 154 /* PropertyDeclaration */ && languageVersion !== 0 /* ES3 */; + return [ + createSyntheticExpression(expr, getParentTypeOfClassElement(parent)), + createSyntheticExpression(expr, getClassElementPropertyKeyType(parent)), + createSyntheticExpression(expr, hasPropDesc ? createTypedPropertyDescriptorType(getTypeOfNode(parent)) : anyType) + ]; + } + return ts.Debug.fail(); + } + /** + * Returns the argument count for a decorator node that works like a function invocation. + */ + function getDecoratorArgumentCount(node, signature) { + switch (node.parent.kind) { + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + return 1; + case 154 /* PropertyDeclaration */: + return 2; + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + // For ES3 or decorators with only two parameters we supply only two arguments + return languageVersion === 0 /* ES3 */ || signature.parameters.length <= 2 ? 2 : 3; + case 151 /* Parameter */: + return 3; + default: + return ts.Debug.fail(); + } + } + function getArgumentArityError(node, signatures, args) { + var min = Number.POSITIVE_INFINITY; + var max = Number.NEGATIVE_INFINITY; + var belowArgCount = Number.NEGATIVE_INFINITY; + var aboveArgCount = Number.POSITIVE_INFINITY; + var argCount = args.length; + var closestSignature; + for (var _i = 0, signatures_4 = signatures; _i < signatures_4.length; _i++) { + var sig = signatures_4[_i]; + var minCount = getMinArgumentCount(sig); + var maxCount = getParameterCount(sig); + if (minCount < argCount && minCount > belowArgCount) + belowArgCount = minCount; + if (argCount < maxCount && maxCount < aboveArgCount) + aboveArgCount = maxCount; + if (minCount < min) { + min = minCount; + closestSignature = sig; + } + max = Math.max(max, maxCount); + } + var hasRestParameter = ts.some(signatures, hasEffectiveRestParameter); + var paramRange = hasRestParameter ? min : + min < max ? min + "-" + max : + min; + var hasSpreadArgument = getSpreadArgumentIndex(args) > -1; + if (argCount <= max && hasSpreadArgument) { + argCount--; + } + var related; + if (closestSignature && getMinArgumentCount(closestSignature) > argCount && closestSignature.declaration) { + var paramDecl = closestSignature.declaration.parameters[closestSignature.thisParameter ? argCount + 1 : argCount]; + if (paramDecl) { + related = ts.createDiagnosticForNode(paramDecl, ts.isBindingPattern(paramDecl.name) ? ts.Diagnostics.An_argument_matching_this_binding_pattern_was_not_provided : ts.Diagnostics.An_argument_for_0_was_not_provided, !paramDecl.name ? argCount : !ts.isBindingPattern(paramDecl.name) ? ts.idText(getFirstIdentifier(paramDecl.name)) : undefined); + } + } + if (hasRestParameter || hasSpreadArgument) { + var error_1 = hasRestParameter && hasSpreadArgument ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1_or_more : + hasRestParameter ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1 : + ts.Diagnostics.Expected_0_arguments_but_got_1_or_more; + var diagnostic_1 = ts.createDiagnosticForNode(node, error_1, paramRange, argCount); + return related ? addRelatedInfo(diagnostic_1, related) : diagnostic_1; + } + if (min < argCount && argCount < max) { + return ts.createDiagnosticForNode(node, ts.Diagnostics.No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments, argCount, belowArgCount, aboveArgCount); + } + var diagnostic = ts.createDiagnosticForNode(node, ts.Diagnostics.Expected_0_arguments_but_got_1, paramRange, argCount); + return related ? addRelatedInfo(diagnostic, related) : diagnostic; + } + function getTypeArgumentArityError(node, signatures, typeArguments) { + var min = Infinity; + var max = -Infinity; + for (var _i = 0, signatures_5 = signatures; _i < signatures_5.length; _i++) { + var sig = signatures_5[_i]; + min = Math.min(min, getMinTypeArgumentCount(sig.typeParameters)); + max = Math.max(max, ts.length(sig.typeParameters)); + } + var paramCount = min === max ? min : min + "-" + max; + return ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), typeArguments, ts.Diagnostics.Expected_0_type_arguments_but_got_1, paramCount, typeArguments.length); + } + function resolveCall(node, signatures, candidatesOutArray, isForSignatureHelp, fallbackError) { + var isTaggedTemplate = node.kind === 193 /* TaggedTemplateExpression */; + var isDecorator = node.kind === 152 /* Decorator */; + var isJsxOpeningOrSelfClosingElement = ts.isJsxOpeningLikeElement(node); + var reportErrors = !candidatesOutArray; + var typeArguments; + if (!isDecorator) { + typeArguments = node.typeArguments; + // We already perform checking on the type arguments on the class declaration itself. + if (isTaggedTemplate || isJsxOpeningOrSelfClosingElement || node.expression.kind !== 98 /* SuperKeyword */) { + ts.forEach(typeArguments, checkSourceElement); + } + } + var candidates = candidatesOutArray || []; + // reorderCandidates fills up the candidates array directly + reorderCandidates(signatures, candidates); + if (!candidates.length) { + if (reportErrors) { + diagnostics.add(ts.createDiagnosticForNode(node, ts.Diagnostics.Call_target_does_not_contain_any_signatures)); + } + return resolveErrorCall(node); + } + var args = getEffectiveCallArguments(node); + // The excludeArgument array contains true for each context sensitive argument (an argument + // is context sensitive it is susceptible to a one-time permanent contextual typing). + // + // The idea is that we will perform type argument inference & assignability checking once + // without using the susceptible parameters that are functions, and once more for those + // parameters, contextually typing each as we go along. + // + // For a tagged template, then the first argument be 'undefined' if necessary because it + // represents a TemplateStringsArray. + // + // For a decorator, no arguments are susceptible to contextual typing due to the fact + // decorators are applied to a declaration by the emitter, and not to an expression. + var isSingleNonGenericCandidate = candidates.length === 1 && !candidates[0].typeParameters; + var excludeArgument = !isDecorator && !isSingleNonGenericCandidate ? getExcludeArgument(args) : undefined; + // The following variables are captured and modified by calls to chooseOverload. + // If overload resolution or type argument inference fails, we want to report the + // best error possible. The best error is one which says that an argument was not + // assignable to a parameter. This implies that everything else about the overload + // was fine. So if there is any overload that is only incorrect because of an + // argument, we will report an error on that one. + // + // function foo(s: string): void; + // function foo(n: number): void; // Report argument error on this overload + // function foo(): void; + // foo(true); + // + // If none of the overloads even made it that far, there are two possibilities. + // There was a problem with type arguments for some overload, in which case + // report an error on that. Or none of the overloads even had correct arity, + // in which case give an arity error. + // + // function foo(x: T): void; // Report type argument error + // function foo(): void; + // foo(0); + // + var candidateForArgumentError; + var candidateForArgumentArityError; + var candidateForTypeArgumentError; + var result; + // If we are in signature help, a trailing comma indicates that we intend to provide another argument, + // so we will only accept overloads with arity at least 1 higher than the current number of provided arguments. + var signatureHelpTrailingComma = isForSignatureHelp && node.kind === 191 /* CallExpression */ && node.arguments.hasTrailingComma; + // Section 4.12.1: + // if the candidate list contains one or more signatures for which the type of each argument + // expression is a subtype of each corresponding parameter type, the return type of the first + // of those signatures becomes the return type of the function call. + // Otherwise, the return type of the first signature in the candidate list becomes the return + // type of the function call. + // + // Whether the call is an error is determined by assignability of the arguments. The subtype pass + // is just important for choosing the best signature. So in the case where there is only one + // signature, the subtype pass is useless. So skipping it is an optimization. + if (candidates.length > 1) { + result = chooseOverload(candidates, subtypeRelation, signatureHelpTrailingComma); + } + if (!result) { + result = chooseOverload(candidates, assignableRelation, signatureHelpTrailingComma); + } + if (result) { + return result; + } + // No signatures were applicable. Now report errors based on the last applicable signature with + // no arguments excluded from assignability checks. + // If candidate is undefined, it means that no candidates had a suitable arity. In that case, + // skip the checkApplicableSignature check. + if (reportErrors) { + if (candidateForArgumentError) { + // excludeArgument is undefined, in this case also equivalent to [undefined, undefined, ...] + // The importance of excludeArgument is to prevent us from typing function expression parameters + // in arguments too early. If possible, we'd like to only type them once we know the correct + // overload. However, this matters for the case where the call is correct. When the call is + // an error, we don't need to exclude any arguments, although it would cause no harm to do so. + checkApplicableSignature(node, args, candidateForArgumentError, assignableRelation, /*excludeArgument*/ undefined, /*reportErrors*/ true); + } + else if (candidateForArgumentArityError) { + diagnostics.add(getArgumentArityError(node, [candidateForArgumentArityError], args)); + } + else if (candidateForTypeArgumentError) { + checkTypeArguments(candidateForTypeArgumentError, node.typeArguments, /*reportErrors*/ true, fallbackError); + } + else { + var signaturesWithCorrectTypeArgumentArity = ts.filter(signatures, function (s) { return hasCorrectTypeArgumentArity(s, typeArguments); }); + if (signaturesWithCorrectTypeArgumentArity.length === 0) { + diagnostics.add(getTypeArgumentArityError(node, signatures, typeArguments)); + } + else if (!isDecorator) { + diagnostics.add(getArgumentArityError(node, signaturesWithCorrectTypeArgumentArity, args)); + } + else if (fallbackError) { + diagnostics.add(ts.createDiagnosticForNode(node, fallbackError)); + } + } + } + return produceDiagnostics || !args ? resolveErrorCall(node) : getCandidateForOverloadFailure(node, candidates, args, !!candidatesOutArray); + function chooseOverload(candidates, relation, signatureHelpTrailingComma) { + if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; } + candidateForArgumentError = undefined; + candidateForArgumentArityError = undefined; + candidateForTypeArgumentError = undefined; + if (isSingleNonGenericCandidate) { + var candidate = candidates[0]; + if (typeArguments || !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) { + return undefined; + } + if (!checkApplicableSignature(node, args, candidate, relation, excludeArgument, /*reportErrors*/ false)) { + candidateForArgumentError = candidate; + return undefined; + } + return candidate; + } + for (var candidateIndex = 0; candidateIndex < candidates.length; candidateIndex++) { + var candidate = candidates[candidateIndex]; + if (!hasCorrectTypeArgumentArity(candidate, typeArguments) || !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) { + continue; + } + var checkCandidate = void 0; + var inferenceContext = void 0; + if (candidate.typeParameters) { + var typeArgumentTypes = void 0; + if (typeArguments) { + typeArgumentTypes = checkTypeArguments(candidate, typeArguments, /*reportErrors*/ false); + if (!typeArgumentTypes) { + candidateForTypeArgumentError = candidate; + continue; + } + } + else { + inferenceContext = createInferenceContext(candidate.typeParameters, candidate, /*flags*/ ts.isInJSFile(node) ? 2 /* AnyDefault */ : 0 /* None */); + typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); + } + checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration)); + // If the original signature has a generic rest type, instantiation may produce a + // signature with different arity and we need to perform another arity check. + if (getNonArrayRestType(candidate) && !hasCorrectArity(node, args, checkCandidate, signatureHelpTrailingComma)) { + candidateForArgumentArityError = checkCandidate; + continue; + } + } + else { + checkCandidate = candidate; + } + if (!checkApplicableSignature(node, args, checkCandidate, relation, excludeArgument, /*reportErrors*/ false)) { + // Give preference to error candidates that have no rest parameters (as they are more specific) + if (!candidateForArgumentError || getEffectiveRestType(candidateForArgumentError) || !getEffectiveRestType(checkCandidate)) { + candidateForArgumentError = checkCandidate; + } + continue; + } + if (excludeArgument) { + // If one or more context sensitive arguments were excluded, we start including + // them now (and keeping do so for any subsequent candidates) and perform a second + // round of type inference and applicability checking for this particular candidate. + excludeArgument = undefined; + if (inferenceContext) { + var typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); + checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration)); + } + if (!checkApplicableSignature(node, args, checkCandidate, relation, excludeArgument, /*reportErrors*/ false)) { + // Give preference to error candidates that have no rest parameters (as they are more specific) + if (!candidateForArgumentError || getEffectiveRestType(candidateForArgumentError) || !getEffectiveRestType(checkCandidate)) { + candidateForArgumentError = checkCandidate; + } + continue; + } + } + candidates[candidateIndex] = checkCandidate; + return checkCandidate; + } + return undefined; + } + } + function getExcludeArgument(args) { + var excludeArgument; + // We do not need to call `getEffectiveArgumentCount` here as it only + // applies when calculating the number of arguments for a decorator. + for (var i = 0; i < args.length; i++) { + if (isContextSensitive(args[i])) { + if (!excludeArgument) { + excludeArgument = new Array(args.length); + } + excludeArgument[i] = true; + } + } + return excludeArgument; + } + // No signature was applicable. We have already reported the errors for the invalid signature. + // If this is a type resolution session, e.g. Language Service, try to get better information than anySignature. + function getCandidateForOverloadFailure(node, candidates, args, hasCandidatesOutArray) { + ts.Debug.assert(candidates.length > 0); // Else should not have called this. + // Normally we will combine overloads. Skip this if they have type parameters since that's hard to combine. + // Don't do this if there is a `candidatesOutArray`, + // because then we want the chosen best candidate to be one of the overloads, not a combination. + return hasCandidatesOutArray || candidates.length === 1 || candidates.some(function (c) { return !!c.typeParameters; }) + ? pickLongestCandidateSignature(node, candidates, args) + : createUnionOfSignaturesForOverloadFailure(candidates); + } + function createUnionOfSignaturesForOverloadFailure(candidates) { + var thisParameters = ts.mapDefined(candidates, function (c) { return c.thisParameter; }); + var thisParameter; + if (thisParameters.length) { + thisParameter = createCombinedSymbolFromTypes(thisParameters, thisParameters.map(getTypeOfParameter)); + } + var _a = ts.minAndMax(candidates, getNumNonRestParameters), minArgumentCount = _a.min, maxNonRestParam = _a.max; + var parameters = []; + var _loop_7 = function (i) { + var symbols = ts.mapDefined(candidates, function (_a) { + var parameters = _a.parameters, hasRestParameter = _a.hasRestParameter; + return hasRestParameter ? + i < parameters.length - 1 ? parameters[i] : ts.last(parameters) : + i < parameters.length ? parameters[i] : undefined; + }); + ts.Debug.assert(symbols.length !== 0); + parameters.push(createCombinedSymbolFromTypes(symbols, ts.mapDefined(candidates, function (candidate) { return tryGetTypeAtPosition(candidate, i); }))); + }; + for (var i = 0; i < maxNonRestParam; i++) { + _loop_7(i); + } + var restParameterSymbols = ts.mapDefined(candidates, function (c) { return c.hasRestParameter ? ts.last(c.parameters) : undefined; }); + var hasRestParameter = restParameterSymbols.length !== 0; + if (hasRestParameter) { + var type = createArrayType(getUnionType(ts.mapDefined(candidates, tryGetRestTypeOfSignature), 2 /* Subtype */)); + parameters.push(createCombinedSymbolForOverloadFailure(restParameterSymbols, type)); + } + return createSignature(candidates[0].declaration, + /*typeParameters*/ undefined, // Before calling this we tested for `!candidates.some(c => !!c.typeParameters)`. + thisParameter, parameters, + /*resolvedReturnType*/ getIntersectionType(candidates.map(getReturnTypeOfSignature)), + /*typePredicate*/ undefined, minArgumentCount, hasRestParameter, + /*hasLiteralTypes*/ candidates.some(function (c) { return c.hasLiteralTypes; })); + } + function getNumNonRestParameters(signature) { + var numParams = signature.parameters.length; + return signature.hasRestParameter ? numParams - 1 : numParams; + } + function createCombinedSymbolFromTypes(sources, types) { + return createCombinedSymbolForOverloadFailure(sources, getUnionType(types, 2 /* Subtype */)); + } + function createCombinedSymbolForOverloadFailure(sources, type) { + // This function is currently only used for erroneous overloads, so it's good enough to just use the first source. + return createSymbolWithType(ts.first(sources), type); + } + function pickLongestCandidateSignature(node, candidates, args) { + // Pick the longest signature. This way we can get a contextual type for cases like: + // declare function f(a: { xa: number; xb: number; }, b: number); + // f({ | + // Also, use explicitly-supplied type arguments if they are provided, so we can get a contextual signature in cases like: + // declare function f(k: keyof T); + // f(" + var bestIndex = getLongestCandidateIndex(candidates, apparentArgumentCount === undefined ? args.length : apparentArgumentCount); + var candidate = candidates[bestIndex]; + var typeParameters = candidate.typeParameters; + if (!typeParameters) { + return candidate; + } + var typeArgumentNodes = callLikeExpressionMayHaveTypeArguments(node) ? node.typeArguments : undefined; + var instantiated = typeArgumentNodes + ? createSignatureInstantiation(candidate, getTypeArgumentsFromNodes(typeArgumentNodes, typeParameters, ts.isInJSFile(node))) + : inferSignatureInstantiationForOverloadFailure(node, typeParameters, candidate, args); + candidates[bestIndex] = instantiated; + return instantiated; + } + function getTypeArgumentsFromNodes(typeArgumentNodes, typeParameters, isJs) { + var typeArguments = typeArgumentNodes.map(getTypeOfNode); + while (typeArguments.length > typeParameters.length) { + typeArguments.pop(); + } + while (typeArguments.length < typeParameters.length) { + typeArguments.push(getConstraintOfTypeParameter(typeParameters[typeArguments.length]) || getDefaultTypeArgumentType(isJs)); + } + return typeArguments; + } + function inferSignatureInstantiationForOverloadFailure(node, typeParameters, candidate, args) { + var inferenceContext = createInferenceContext(typeParameters, candidate, /*flags*/ ts.isInJSFile(node) ? 2 /* AnyDefault */ : 0 /* None */); + var typeArgumentTypes = inferTypeArguments(node, candidate, args, getExcludeArgument(args), inferenceContext); + return createSignatureInstantiation(candidate, typeArgumentTypes); + } + function getLongestCandidateIndex(candidates, argsCount) { + var maxParamsIndex = -1; + var maxParams = -1; + for (var i = 0; i < candidates.length; i++) { + var candidate = candidates[i]; + var paramCount = getParameterCount(candidate); + if (hasEffectiveRestParameter(candidate) || paramCount >= argsCount) { + return i; + } + if (paramCount > maxParams) { + maxParams = paramCount; + maxParamsIndex = i; + } + } + return maxParamsIndex; + } + function resolveCallExpression(node, candidatesOutArray, isForSignatureHelp) { + if (node.expression.kind === 98 /* SuperKeyword */) { + var superType = checkSuperExpression(node.expression); + if (isTypeAny(superType)) { + for (var _i = 0, _a = node.arguments; _i < _a.length; _i++) { + var arg = _a[_i]; + checkExpression(arg); // Still visit arguments so they get marked for visibility, etc + } + return anySignature; + } + if (superType !== errorType) { + // In super call, the candidate signatures are the matching arity signatures of the base constructor function instantiated + // with the type arguments specified in the extends clause. + var baseTypeNode = ts.getEffectiveBaseTypeNode(ts.getContainingClass(node)); + if (baseTypeNode) { + var baseConstructors = getInstantiatedConstructorsForTypeArguments(superType, baseTypeNode.typeArguments, baseTypeNode); + return resolveCall(node, baseConstructors, candidatesOutArray, isForSignatureHelp); + } + } + return resolveUntypedCall(node); + } + var funcType = checkNonNullExpression(node.expression, ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_null, ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_undefined, ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_null_or_undefined); + if (funcType === silentNeverType) { + return silentNeverSignature; + } + var apparentType = getApparentType(funcType); + if (apparentType === errorType) { + // Another error has already been reported + return resolveErrorCall(node); + } + // Technically, this signatures list may be incomplete. We are taking the apparent type, + // but we are not including call signatures that may have been added to the Object or + // Function interface, since they have none by default. This is a bit of a leap of faith + // that the user will not add any. + var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */); + var numConstructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */).length; + // TS 1.0 Spec: 4.12 + // In an untyped function call no TypeArgs are permitted, Args can be any argument list, no contextual + // types are provided for the argument expressions, and the result is always of type Any. + if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, numConstructSignatures)) { + // The unknownType indicates that an error already occurred (and was reported). No + // need to report another error in this case. + if (funcType !== errorType && node.typeArguments) { + error(node, ts.Diagnostics.Untyped_function_calls_may_not_accept_type_arguments); + } + return resolveUntypedCall(node); + } + // If FuncExpr's apparent type(section 3.8.1) is a function type, the call is a typed function call. + // TypeScript employs overload resolution in typed function calls in order to support functions + // with multiple call signatures. + if (!callSignatures.length) { + if (numConstructSignatures) { + error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType)); + } + else { + var relatedInformation = void 0; + if (node.arguments.length === 1) { + var text = ts.getSourceFileOfNode(node).text; + if (ts.isLineBreak(text.charCodeAt(ts.skipTrivia(text, node.expression.end, /* stopAfterLineBreak */ true) - 1))) { + relatedInformation = ts.createDiagnosticForNode(node.expression, ts.Diagnostics.It_is_highly_likely_that_you_are_missing_a_semicolon); + } + } + invocationError(node, apparentType, 0 /* Call */, relatedInformation); + } + return resolveErrorCall(node); + } + // If the function is explicitly marked with `@class`, then it must be constructed. + if (callSignatures.some(function (sig) { return ts.isInJSFile(sig.declaration) && !!ts.getJSDocClassTag(sig.declaration); })) { + error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType)); + return resolveErrorCall(node); + } + return resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp); + } + /** + * TS 1.0 spec: 4.12 + * If FuncExpr is of type Any, or of an object type that has no call or construct signatures + * but is a subtype of the Function interface, the call is an untyped function call. + */ + function isUntypedFunctionCall(funcType, apparentFuncType, numCallSignatures, numConstructSignatures) { + // We exclude union types because we may have a union of function types that happen to have no common signatures. + return isTypeAny(funcType) || isTypeAny(apparentFuncType) && funcType.flags & 262144 /* TypeParameter */ || + !numCallSignatures && !numConstructSignatures && !(apparentFuncType.flags & (1048576 /* Union */ | 131072 /* Never */)) && isTypeAssignableTo(funcType, globalFunctionType); + } + function resolveNewExpression(node, candidatesOutArray, isForSignatureHelp) { + if (node.arguments && languageVersion < 1 /* ES5 */) { + var spreadIndex = getSpreadArgumentIndex(node.arguments); + if (spreadIndex >= 0) { + error(node.arguments[spreadIndex], ts.Diagnostics.Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher); + } + } + var expressionType = checkNonNullExpression(node.expression); + if (expressionType === silentNeverType) { + return silentNeverSignature; + } + // If expressionType's apparent type(section 3.8.1) is an object type with one or + // more construct signatures, the expression is processed in the same manner as a + // function call, but using the construct signatures as the initial set of candidate + // signatures for overload resolution. The result type of the function call becomes + // the result type of the operation. + expressionType = getApparentType(expressionType); + if (expressionType === errorType) { + // Another error has already been reported + return resolveErrorCall(node); + } + // TS 1.0 spec: 4.11 + // If expressionType is of type Any, Args can be any argument + // list and the result of the operation is of type Any. + if (isTypeAny(expressionType)) { + if (node.typeArguments) { + error(node, ts.Diagnostics.Untyped_function_calls_may_not_accept_type_arguments); + } + return resolveUntypedCall(node); + } + // Technically, this signatures list may be incomplete. We are taking the apparent type, + // but we are not including construct signatures that may have been added to the Object or + // Function interface, since they have none by default. This is a bit of a leap of faith + // that the user will not add any. + var constructSignatures = getSignaturesOfType(expressionType, 1 /* Construct */); + if (constructSignatures.length) { + if (!isConstructorAccessible(node, constructSignatures[0])) { + return resolveErrorCall(node); + } + // If the expression is a class of abstract type, then it cannot be instantiated. + // Note, only class declarations can be declared abstract. + // In the case of a merged class-module or class-interface declaration, + // only the class declaration node will have the Abstract flag set. + var valueDecl = expressionType.symbol && ts.getClassLikeDeclarationOfSymbol(expressionType.symbol); + if (valueDecl && ts.hasModifier(valueDecl, 128 /* Abstract */)) { + error(node, ts.Diagnostics.Cannot_create_an_instance_of_an_abstract_class); + return resolveErrorCall(node); + } + return resolveCall(node, constructSignatures, candidatesOutArray, isForSignatureHelp); + } + // If expressionType's apparent type is an object type with no construct signatures but + // one or more call signatures, the expression is processed as a function call. A compile-time + // error occurs if the result of the function call is not Void. The type of the result of the + // operation is Any. It is an error to have a Void this type. + var callSignatures = getSignaturesOfType(expressionType, 0 /* Call */); + if (callSignatures.length) { + var signature = resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp); + if (!noImplicitAny) { + if (signature.declaration && !isJSConstructor(signature.declaration) && getReturnTypeOfSignature(signature) !== voidType) { + error(node, ts.Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword); + } + if (getThisTypeOfSignature(signature) === voidType) { + error(node, ts.Diagnostics.A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void); + } + } + return signature; + } + invocationError(node, expressionType, 1 /* Construct */); + return resolveErrorCall(node); + } + function typeHasProtectedAccessibleBase(target, type) { + var baseTypes = getBaseTypes(type); + if (!ts.length(baseTypes)) { + return false; + } + var firstBase = baseTypes[0]; + if (firstBase.flags & 2097152 /* Intersection */) { + var types = firstBase.types; + var mixinCount = ts.countWhere(types, isMixinConstructorType); + var i = 0; + for (var _i = 0, _a = firstBase.types; _i < _a.length; _i++) { + var intersectionMember = _a[_i]; + i++; + // We want to ignore mixin ctors + if (mixinCount === 0 || mixinCount === types.length && i === 0 || !isMixinConstructorType(intersectionMember)) { + if (ts.getObjectFlags(intersectionMember) & (1 /* Class */ | 2 /* Interface */)) { + if (intersectionMember.symbol === target) { + return true; + } + if (typeHasProtectedAccessibleBase(target, intersectionMember)) { + return true; + } + } + } + } + return false; + } + if (firstBase.symbol === target) { + return true; + } + return typeHasProtectedAccessibleBase(target, firstBase); + } + function isConstructorAccessible(node, signature) { + if (!signature || !signature.declaration) { + return true; + } + var declaration = signature.declaration; + var modifiers = ts.getSelectedModifierFlags(declaration, 24 /* NonPublicAccessibilityModifier */); + // Public constructor is accessible. + if (!modifiers) { + return true; + } + var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(declaration.parent.symbol); + var declaringClass = getDeclaredTypeOfSymbol(declaration.parent.symbol); + // A private or protected constructor can only be instantiated within its own class (or a subclass, for protected) + if (!isNodeWithinClass(node, declaringClassDeclaration)) { + var containingClass = ts.getContainingClass(node); + if (containingClass && modifiers & 16 /* Protected */) { + var containingType = getTypeOfNode(containingClass); + if (typeHasProtectedAccessibleBase(declaration.parent.symbol, containingType)) { + return true; + } + } + if (modifiers & 8 /* Private */) { + error(node, ts.Diagnostics.Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration, typeToString(declaringClass)); + } + if (modifiers & 16 /* Protected */) { + error(node, ts.Diagnostics.Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration, typeToString(declaringClass)); + } + return false; + } + return true; + } + function invocationError(node, apparentType, kind, relatedInformation) { + var diagnostic = error(node, (kind === 0 /* Call */ ? + ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures : + ts.Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature), typeToString(apparentType)); + invocationErrorRecovery(apparentType, kind, relatedInformation ? addRelatedInfo(diagnostic, relatedInformation) : diagnostic); + } + function invocationErrorRecovery(apparentType, kind, diagnostic) { + if (!apparentType.symbol) { + return; + } + var importNode = getSymbolLinks(apparentType.symbol).originatingImport; + // Create a diagnostic on the originating import if possible onto which we can attach a quickfix + // An import call expression cannot be rewritten into another form to correct the error - the only solution is to use `.default` at the use-site + if (importNode && !ts.isImportCall(importNode)) { + var sigs = getSignaturesOfType(getTypeOfSymbol(getSymbolLinks(apparentType.symbol).target), kind); + if (!sigs || !sigs.length) + return; + addRelatedInfo(diagnostic, ts.createDiagnosticForNode(importNode, ts.Diagnostics.Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_Consider_using_a_default_import_or_import_require_here_instead)); + } + } + function resolveTaggedTemplateExpression(node, candidatesOutArray, isForSignatureHelp) { + var tagType = checkExpression(node.tag); + var apparentType = getApparentType(tagType); + if (apparentType === errorType) { + // Another error has already been reported + return resolveErrorCall(node); + } + var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */); + var numConstructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */).length; + if (isUntypedFunctionCall(tagType, apparentType, callSignatures.length, numConstructSignatures)) { + return resolveUntypedCall(node); + } + if (!callSignatures.length) { + invocationError(node, apparentType, 0 /* Call */); + return resolveErrorCall(node); + } + return resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp); + } + /** + * Gets the localized diagnostic head message to use for errors when resolving a decorator as a call expression. + */ + function getDiagnosticHeadMessageForDecoratorResolution(node) { + switch (node.parent.kind) { + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + return ts.Diagnostics.Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression; + case 151 /* Parameter */: + return ts.Diagnostics.Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression; + case 154 /* PropertyDeclaration */: + return ts.Diagnostics.Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression; + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + return ts.Diagnostics.Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression; + default: + return ts.Debug.fail(); + } + } + /** + * Resolves a decorator as if it were a call expression. + */ + function resolveDecorator(node, candidatesOutArray, isForSignatureHelp) { + var funcType = checkExpression(node.expression); + var apparentType = getApparentType(funcType); + if (apparentType === errorType) { + return resolveErrorCall(node); + } + var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */); + var numConstructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */).length; + if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, numConstructSignatures)) { + return resolveUntypedCall(node); + } + if (isPotentiallyUncalledDecorator(node, callSignatures)) { + var nodeStr = ts.getTextOfNode(node.expression, /*includeTrivia*/ false); + error(node, ts.Diagnostics._0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write_0, nodeStr); + return resolveErrorCall(node); + } + var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); + if (!callSignatures.length) { + var errorInfo = ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures, typeToString(apparentType)); + errorInfo = ts.chainDiagnosticMessages(errorInfo, headMessage); + var diag = ts.createDiagnosticForNodeFromMessageChain(node, errorInfo); + diagnostics.add(diag); + invocationErrorRecovery(apparentType, 0 /* Call */, diag); + return resolveErrorCall(node); + } + return resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp, headMessage); + } + function createSignatureForJSXIntrinsic(node, result) { + var namespace = getJsxNamespaceAt(node); + var exports = namespace && getExportsOfSymbol(namespace); + // We fake up a SFC signature for each intrinsic, however a more specific per-element signature drawn from the JSX declaration + // file would probably be preferable. + var typeSymbol = exports && getSymbol(exports, JsxNames.Element, 67897832 /* Type */); + var returnNode = typeSymbol && nodeBuilder.symbolToEntityName(typeSymbol, 67897832 /* Type */, node); + var declaration = ts.createFunctionTypeNode(/*typeParameters*/ undefined, [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotdotdot*/ undefined, "props", /*questionMark*/ undefined, nodeBuilder.typeToTypeNode(result, node))], returnNode ? ts.createTypeReferenceNode(returnNode, /*typeArguments*/ undefined) : ts.createKeywordTypeNode(120 /* AnyKeyword */)); + var parameterSymbol = createSymbol(1 /* FunctionScopedVariable */, "props"); + parameterSymbol.type = result; + return createSignature(declaration, + /*typeParameters*/ undefined, + /*thisParameter*/ undefined, [parameterSymbol], typeSymbol ? getDeclaredTypeOfSymbol(typeSymbol) : errorType, + /*returnTypePredicate*/ undefined, 1, + /*hasRestparameter*/ false, + /*hasLiteralTypes*/ false); + } + function resolveJsxOpeningLikeElement(node, candidatesOutArray, isForSignatureHelp) { + if (isJsxIntrinsicIdentifier(node.tagName)) { + var result = getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node); + var fakeSignature = createSignatureForJSXIntrinsic(node, result); + checkTypeAssignableToAndOptionallyElaborate(checkExpressionWithContextualType(node.attributes, getEffectiveFirstArgumentForJsxSignature(fakeSignature, node), /*mapper*/ undefined), result, node.tagName, node.attributes); + return fakeSignature; + } + var exprTypes = checkExpression(node.tagName); + var apparentType = getApparentType(exprTypes); + if (apparentType === errorType) { + return resolveErrorCall(node); + } + var signatures = getUninstantiatedJsxSignaturesOfType(exprTypes, node); + if (isUntypedFunctionCall(exprTypes, apparentType, signatures.length, /*constructSignatures*/ 0)) { + return resolveUntypedCall(node); + } + if (signatures.length === 0) { + // We found no signatures at all, which is an error + error(node.tagName, ts.Diagnostics.JSX_element_type_0_does_not_have_any_construct_or_call_signatures, ts.getTextOfNode(node.tagName)); + return resolveErrorCall(node); + } + return resolveCall(node, signatures, candidatesOutArray, isForSignatureHelp); + } + /** + * Sometimes, we have a decorator that could accept zero arguments, + * but is receiving too many arguments as part of the decorator invocation. + * In those cases, a user may have meant to *call* the expression before using it as a decorator. + */ + function isPotentiallyUncalledDecorator(decorator, signatures) { + return signatures.length && ts.every(signatures, function (signature) { + return signature.minArgumentCount === 0 && + !signature.hasRestParameter && + signature.parameters.length < getDecoratorArgumentCount(decorator, signature); + }); + } + function resolveSignature(node, candidatesOutArray, isForSignatureHelp) { + switch (node.kind) { + case 191 /* CallExpression */: + return resolveCallExpression(node, candidatesOutArray, isForSignatureHelp); + case 192 /* NewExpression */: + return resolveNewExpression(node, candidatesOutArray, isForSignatureHelp); + case 193 /* TaggedTemplateExpression */: + return resolveTaggedTemplateExpression(node, candidatesOutArray, isForSignatureHelp); + case 152 /* Decorator */: + return resolveDecorator(node, candidatesOutArray, isForSignatureHelp); + case 262 /* JsxOpeningElement */: + case 261 /* JsxSelfClosingElement */: + return resolveJsxOpeningLikeElement(node, candidatesOutArray, isForSignatureHelp); + } + throw ts.Debug.assertNever(node, "Branch in 'resolveSignature' should be unreachable."); + } + /** + * Resolve a signature of a given call-like expression. + * @param node a call-like expression to try resolve a signature for + * @param candidatesOutArray an array of signature to be filled in by the function. It is passed by signature help in the language service; + * the function will fill it up with appropriate candidate signatures + * @return a signature of the call-like expression or undefined if one can't be found + */ + function getResolvedSignature(node, candidatesOutArray, isForSignatureHelp) { + if (isForSignatureHelp === void 0) { isForSignatureHelp = false; } + var links = getNodeLinks(node); + // If getResolvedSignature has already been called, we will have cached the resolvedSignature. + // However, it is possible that either candidatesOutArray was not passed in the first time, + // or that a different candidatesOutArray was passed in. Therefore, we need to redo the work + // to correctly fill the candidatesOutArray. + var cached = links.resolvedSignature; + if (cached && cached !== resolvingSignature && !candidatesOutArray) { + return cached; + } + links.resolvedSignature = resolvingSignature; + var result = resolveSignature(node, candidatesOutArray, isForSignatureHelp); + // If signature resolution originated in control flow type analysis (for example to compute the + // assigned type in a flow assignment) we don't cache the result as it may be based on temporary + // types from the control flow analysis. + links.resolvedSignature = flowLoopStart === flowLoopCount ? result : cached; + return result; + } + /** + * Indicates whether a declaration can be treated as a constructor in a JavaScript + * file. + */ + function isJSConstructor(node) { + if (!node || !ts.isInJSFile(node)) { + return false; + } + var func = ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node) ? node : + ts.isVariableDeclaration(node) && node.initializer && ts.isFunctionExpression(node.initializer) ? node.initializer : + undefined; + if (func) { + // If the node has a @class tag, treat it like a constructor. + if (ts.getJSDocClassTag(node)) + return true; + // If the symbol of the node has members, treat it like a constructor. + var symbol = getSymbolOfNode(func); + return !!symbol && symbol.members !== undefined; + } + return false; + } + function isJSConstructorType(type) { + if (type.flags & 524288 /* Object */) { + var resolved = resolveStructuredTypeMembers(type); + return resolved.callSignatures.length === 1 && isJSConstructor(resolved.callSignatures[0].declaration); + } + return false; + } + function getJSClassType(symbol) { + var inferred; + if (isJSConstructor(symbol.valueDeclaration)) { + inferred = getInferredClassType(symbol); + } + var assigned = getAssignedClassType(symbol); + var valueType = getTypeOfSymbol(symbol); + if (valueType.symbol && !isInferredClassType(valueType) && isJSConstructor(valueType.symbol.valueDeclaration)) { + inferred = getInferredClassType(valueType.symbol); + } + return assigned && inferred ? + getIntersectionType([inferred, assigned]) : + assigned || inferred; + } + function getAssignedClassType(symbol) { + var decl = symbol.valueDeclaration; + var assignmentSymbol = decl && decl.parent && + (ts.isFunctionDeclaration(decl) && getSymbolOfNode(decl) || + ts.isBinaryExpression(decl.parent) && getSymbolOfNode(decl.parent.left) || + ts.isVariableDeclaration(decl.parent) && getSymbolOfNode(decl.parent)); + var prototype = assignmentSymbol && assignmentSymbol.exports && assignmentSymbol.exports.get("prototype"); + var init = prototype && prototype.valueDeclaration && getAssignedJSPrototype(prototype.valueDeclaration); + return init ? checkExpression(init) : undefined; + } + function getAssignedJSPrototype(node) { + if (!node.parent) { + return false; + } + var parent = node.parent; + while (parent && parent.kind === 189 /* PropertyAccessExpression */) { + parent = parent.parent; + } + if (parent && ts.isBinaryExpression(parent) && ts.isPrototypeAccess(parent.left) && parent.operatorToken.kind === 59 /* EqualsToken */) { + var right = ts.getInitializerOfBinaryExpression(parent); + return ts.isObjectLiteralExpression(right) && right; + } + } + function getInferredClassType(symbol) { + var links = getSymbolLinks(symbol); + if (!links.inferredClassType) { + links.inferredClassType = createAnonymousType(symbol, getMembersOfSymbol(symbol) || emptySymbols, ts.emptyArray, ts.emptyArray, /*stringIndexType*/ undefined, /*numberIndexType*/ undefined); + } + return links.inferredClassType; + } + function isInferredClassType(type) { + return type.symbol + && ts.getObjectFlags(type) & 16 /* Anonymous */ + && getSymbolLinks(type.symbol).inferredClassType === type; + } + /** + * Syntactically and semantically checks a call or new expression. + * @param node The call/new expression to be checked. + * @returns On success, the expression's signature's return type. On failure, anyType. + */ + function checkCallExpression(node) { + if (!checkGrammarTypeArguments(node, node.typeArguments)) + checkGrammarArguments(node.arguments); + var signature = getResolvedSignature(node); + if (node.expression.kind === 98 /* SuperKeyword */) { + return voidType; + } + if (node.kind === 192 /* NewExpression */) { + var declaration = signature.declaration; + if (declaration && + declaration.kind !== 157 /* Constructor */ && + declaration.kind !== 161 /* ConstructSignature */ && + declaration.kind !== 166 /* ConstructorType */ && + !ts.isJSDocConstructSignature(declaration)) { + // When resolved signature is a call signature (and not a construct signature) the result type is any, unless + // the declaring function had members created through 'x.prototype.y = expr' or 'this.y = expr' psuedodeclarations + // in a JS file + // Note:JS inferred classes might come from a variable declaration instead of a function declaration. + // In this case, using getResolvedSymbol directly is required to avoid losing the members from the declaration. + var funcSymbol = checkExpression(node.expression).symbol; + if (!funcSymbol && node.expression.kind === 72 /* Identifier */) { + funcSymbol = getResolvedSymbol(node.expression); + } + var type = funcSymbol && getJSClassType(funcSymbol); + if (type) { + return signature.target ? instantiateType(type, signature.mapper) : type; + } + if (noImplicitAny) { + error(node, ts.Diagnostics.new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type); + } + return anyType; + } + } + // In JavaScript files, calls to any identifier 'require' are treated as external module imports + if (ts.isInJSFile(node) && isCommonJsRequire(node)) { + return resolveExternalModuleTypeByLiteral(node.arguments[0]); + } + var returnType = getReturnTypeOfSignature(signature); + // Treat any call to the global 'Symbol' function that is part of a const variable or readonly property + // as a fresh unique symbol literal type. + if (returnType.flags & 12288 /* ESSymbolLike */ && isSymbolOrSymbolForCall(node)) { + return getESSymbolLikeTypeForNode(ts.walkUpParenthesizedExpressions(node.parent)); + } + var jsAssignmentType; + if (ts.isInJSFile(node)) { + var decl = ts.getDeclarationOfExpando(node); + if (decl) { + var jsSymbol = getSymbolOfNode(decl); + if (jsSymbol && ts.hasEntries(jsSymbol.exports)) { + jsAssignmentType = createAnonymousType(jsSymbol, jsSymbol.exports, ts.emptyArray, ts.emptyArray, undefined, undefined); + jsAssignmentType.objectFlags |= 16384 /* JSLiteral */; + } + } + } + return jsAssignmentType ? getIntersectionType([returnType, jsAssignmentType]) : returnType; + } + function isSymbolOrSymbolForCall(node) { + if (!ts.isCallExpression(node)) + return false; + var left = node.expression; + if (ts.isPropertyAccessExpression(left) && left.name.escapedText === "for") { + left = left.expression; + } + if (!ts.isIdentifier(left) || left.escapedText !== "Symbol") { + return false; + } + // make sure `Symbol` is the global symbol + var globalESSymbol = getGlobalESSymbolConstructorSymbol(/*reportErrors*/ false); + if (!globalESSymbol) { + return false; + } + return globalESSymbol === resolveName(left, "Symbol", 67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); + } + function checkImportCallExpression(node) { + // Check grammar of dynamic import + if (!checkGrammarArguments(node.arguments)) + checkGrammarImportCallExpression(node); + if (node.arguments.length === 0) { + return createPromiseReturnType(node, anyType); + } + var specifier = node.arguments[0]; + var specifierType = checkExpressionCached(specifier); + // Even though multiple arguments is grammatically incorrect, type-check extra arguments for completion + for (var i = 1; i < node.arguments.length; ++i) { + checkExpressionCached(node.arguments[i]); + } + if (specifierType.flags & 32768 /* Undefined */ || specifierType.flags & 65536 /* Null */ || !isTypeAssignableTo(specifierType, stringType)) { + error(specifier, ts.Diagnostics.Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0, typeToString(specifierType)); + } + // resolveExternalModuleName will return undefined if the moduleReferenceExpression is not a string literal + var moduleSymbol = resolveExternalModuleName(node, specifier); + if (moduleSymbol) { + var esModuleSymbol = resolveESModuleSymbol(moduleSymbol, specifier, /*dontRecursivelyResolve*/ true); + if (esModuleSymbol) { + return createPromiseReturnType(node, getTypeWithSyntheticDefaultImportType(getTypeOfSymbol(esModuleSymbol), esModuleSymbol, moduleSymbol)); + } + } + return createPromiseReturnType(node, anyType); + } + function getTypeWithSyntheticDefaultImportType(type, symbol, originalSymbol) { + if (allowSyntheticDefaultImports && type && type !== errorType) { + var synthType = type; + if (!synthType.syntheticType) { + var file = ts.find(originalSymbol.declarations, ts.isSourceFile); + var hasSyntheticDefault = canHaveSyntheticDefault(file, originalSymbol, /*dontResolveAlias*/ false); + if (hasSyntheticDefault) { + var memberTable = ts.createSymbolTable(); + var newSymbol = createSymbol(2097152 /* Alias */, "default" /* Default */); + newSymbol.nameType = getLiteralType("default"); + newSymbol.target = resolveSymbol(symbol); + memberTable.set("default" /* Default */, newSymbol); + var anonymousSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */); + var defaultContainingObject = createAnonymousType(anonymousSymbol, memberTable, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined); + anonymousSymbol.type = defaultContainingObject; + synthType.syntheticType = isValidSpreadType(type) ? getSpreadType(type, defaultContainingObject, anonymousSymbol, /*typeFLags*/ 0, /*objectFlags*/ 0) : defaultContainingObject; + } + else { + synthType.syntheticType = type; + } + } + return synthType.syntheticType; + } + return type; + } + function isCommonJsRequire(node) { + if (!ts.isRequireCall(node, /*checkArgumentIsStringLiteralLike*/ true)) { + return false; + } + // Make sure require is not a local function + if (!ts.isIdentifier(node.expression)) + return ts.Debug.fail(); + var resolvedRequire = resolveName(node.expression, node.expression.escapedText, 67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); // TODO: GH#18217 + if (resolvedRequire === requireSymbol) { + return true; + } + // project includes symbol named 'require' - make sure that it is ambient and local non-alias + if (resolvedRequire.flags & 2097152 /* Alias */) { + return false; + } + var targetDeclarationKind = resolvedRequire.flags & 16 /* Function */ + ? 239 /* FunctionDeclaration */ + : resolvedRequire.flags & 3 /* Variable */ + ? 237 /* VariableDeclaration */ + : 0 /* Unknown */; + if (targetDeclarationKind !== 0 /* Unknown */) { + var decl = ts.getDeclarationOfKind(resolvedRequire, targetDeclarationKind); + // function/variable declaration should be ambient + return !!decl && !!(decl.flags & 4194304 /* Ambient */); + } + return false; + } + function checkTaggedTemplateExpression(node) { + checkGrammarTypeArguments(node, node.typeArguments); + if (languageVersion < 2 /* ES2015 */) { + checkExternalEmitHelpers(node, 65536 /* MakeTemplateObject */); + } + return getReturnTypeOfSignature(getResolvedSignature(node)); + } + function checkAssertion(node) { + return checkAssertionWorker(node, node.type, node.expression); + } + function checkAssertionWorker(errNode, type, expression, checkMode) { + var exprType = getRegularTypeOfObjectLiteral(getBaseTypeOfLiteralType(checkExpression(expression, checkMode))); + checkSourceElement(type); + var targetType = getTypeFromTypeNode(type); + if (produceDiagnostics && targetType !== errorType) { + var widenedType = getWidenedType(exprType); + if (!isTypeComparableTo(targetType, widenedType)) { + checkTypeComparableTo(exprType, targetType, errNode, ts.Diagnostics.Conversion_of_type_0_to_type_1_may_be_a_mistake_because_neither_type_sufficiently_overlaps_with_the_other_If_this_was_intentional_convert_the_expression_to_unknown_first); + } + } + return targetType; + } + function checkNonNullAssertion(node) { + return getNonNullableType(checkExpression(node.expression)); + } + function checkMetaProperty(node) { + checkGrammarMetaProperty(node); + if (node.keywordToken === 95 /* NewKeyword */) { + return checkNewTargetMetaProperty(node); + } + if (node.keywordToken === 92 /* ImportKeyword */) { + return checkImportMetaProperty(node); + } + return ts.Debug.assertNever(node.keywordToken); + } + function checkNewTargetMetaProperty(node) { + var container = ts.getNewTargetContainer(node); + if (!container) { + error(node, ts.Diagnostics.Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constructor, "new.target"); + return errorType; + } + else if (container.kind === 157 /* Constructor */) { + var symbol = getSymbolOfNode(container.parent); + return getTypeOfSymbol(symbol); + } + else { + var symbol = getSymbolOfNode(container); + return getTypeOfSymbol(symbol); + } + } + function checkImportMetaProperty(node) { + if (languageVersion < 6 /* ESNext */ || moduleKind < ts.ModuleKind.ESNext) { + error(node, ts.Diagnostics.The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_options); + } + var file = ts.getSourceFileOfNode(node); + ts.Debug.assert(!!(file.flags & 1048576 /* PossiblyContainsImportMeta */), "Containing file is missing import meta node flag."); + ts.Debug.assert(!!file.externalModuleIndicator, "Containing file should be a module."); + return node.name.escapedText === "meta" ? getGlobalImportMetaType() : errorType; + } + function getTypeOfParameter(symbol) { + var type = getTypeOfSymbol(symbol); + if (strictNullChecks) { + var declaration = symbol.valueDeclaration; + if (declaration && ts.hasInitializer(declaration)) { + return getOptionalType(type); + } + } + return type; + } + function getParameterNameAtPosition(signature, pos) { + var paramCount = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); + if (pos < paramCount) { + return signature.parameters[pos].escapedName; + } + var restParameter = signature.parameters[paramCount] || unknownSymbol; + var restType = getTypeOfSymbol(restParameter); + if (isTupleType(restType)) { + var associatedNames = restType.target.associatedNames; + var index = pos - paramCount; + return associatedNames ? associatedNames[index] : restParameter.escapedName + "_" + index; + } + return restParameter.escapedName; + } + function getTypeAtPosition(signature, pos) { + return tryGetTypeAtPosition(signature, pos) || anyType; + } + function tryGetTypeAtPosition(signature, pos) { + var paramCount = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); + if (pos < paramCount) { + return getTypeOfParameter(signature.parameters[pos]); + } + if (signature.hasRestParameter) { + var restType = getTypeOfSymbol(signature.parameters[paramCount]); + if (isTupleType(restType)) { + if (pos - paramCount < getLengthOfTupleType(restType)) { + return restType.typeArguments[pos - paramCount]; + } + return getRestTypeOfTupleType(restType); + } + return getIndexTypeOfType(restType, 1 /* Number */); + } + return undefined; + } + function getRestTypeAtPosition(source, pos) { + var paramCount = getParameterCount(source); + var restType = getEffectiveRestType(source); + if (restType && pos === paramCount - 1) { + return restType; + } + var start = restType ? Math.min(pos, paramCount - 1) : pos; + var types = []; + var names = []; + for (var i = start; i < paramCount; i++) { + types.push(getTypeAtPosition(source, i)); + names.push(getParameterNameAtPosition(source, i)); + } + var minArgumentCount = getMinArgumentCount(source); + var minLength = minArgumentCount < start ? 0 : minArgumentCount - start; + return createTupleType(types, minLength, !!restType, names); + } + function getParameterCount(signature) { + var length = signature.parameters.length; + if (signature.hasRestParameter) { + var restType = getTypeOfSymbol(signature.parameters[length - 1]); + if (isTupleType(restType)) { + return length + (restType.typeArguments || ts.emptyArray).length - 1; + } + } + return length; + } + function getMinArgumentCount(signature) { + if (signature.hasRestParameter) { + var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); + if (isTupleType(restType)) { + var minLength = restType.target.minLength; + if (minLength > 0) { + return signature.parameters.length - 1 + minLength; + } + } + } + return signature.minArgumentCount; + } + function hasEffectiveRestParameter(signature) { + if (signature.hasRestParameter) { + var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); + return !isTupleType(restType) || restType.target.hasRestElement; + } + return false; + } + function getEffectiveRestType(signature) { + if (signature.hasRestParameter) { + var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); + return isTupleType(restType) ? getRestArrayTypeOfTupleType(restType) : restType; + } + return undefined; + } + function getNonArrayRestType(signature) { + var restType = getEffectiveRestType(signature); + return restType && !isArrayType(restType) && !isTypeAny(restType) ? restType : undefined; + } + function getTypeOfFirstParameterOfSignature(signature) { + return getTypeOfFirstParameterOfSignatureWithFallback(signature, neverType); + } + function getTypeOfFirstParameterOfSignatureWithFallback(signature, fallbackType) { + return signature.parameters.length > 0 ? getTypeAtPosition(signature, 0) : fallbackType; + } + function inferFromAnnotatedParameters(signature, context, mapper) { + var len = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); + for (var i = 0; i < len; i++) { + var declaration = signature.parameters[i].valueDeclaration; + if (declaration.type) { + var typeNode = ts.getEffectiveTypeAnnotationNode(declaration); + if (typeNode) { + inferTypes(mapper.inferences, getTypeFromTypeNode(typeNode), getTypeAtPosition(context, i)); + } + } + } + } + function assignContextualParameterTypes(signature, context) { + signature.typeParameters = context.typeParameters; + if (context.thisParameter) { + var parameter = signature.thisParameter; + if (!parameter || parameter.valueDeclaration && !parameter.valueDeclaration.type) { + if (!parameter) { + signature.thisParameter = createSymbolWithType(context.thisParameter, /*type*/ undefined); + } + assignTypeToParameterAndFixTypeParameters(signature.thisParameter, getTypeOfSymbol(context.thisParameter)); + } + } + var len = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); + for (var i = 0; i < len; i++) { + var parameter = signature.parameters[i]; + if (!ts.getEffectiveTypeAnnotationNode(parameter.valueDeclaration)) { + var contextualParameterType = getTypeAtPosition(context, i); + assignTypeToParameterAndFixTypeParameters(parameter, contextualParameterType); + } + } + if (signature.hasRestParameter) { + // parameter might be a transient symbol generated by use of `arguments` in the function body. + var parameter = ts.last(signature.parameters); + if (isTransientSymbol(parameter) || !ts.getEffectiveTypeAnnotationNode(parameter.valueDeclaration)) { + var contextualParameterType = getRestTypeAtPosition(context, len); + assignTypeToParameterAndFixTypeParameters(parameter, contextualParameterType); + } + } + } + // When contextual typing assigns a type to a parameter that contains a binding pattern, we also need to push + // the destructured type into the contained binding elements. + function assignBindingElementTypes(pattern) { + for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (!ts.isOmittedExpression(element)) { + if (element.name.kind === 72 /* Identifier */) { + getSymbolLinks(getSymbolOfNode(element)).type = getTypeForBindingElement(element); + } + else { + assignBindingElementTypes(element.name); + } + } + } + } + function assignTypeToParameterAndFixTypeParameters(parameter, contextualType) { + var links = getSymbolLinks(parameter); + if (!links.type) { + links.type = contextualType; + var decl = parameter.valueDeclaration; + if (decl.name.kind !== 72 /* Identifier */) { + // if inference didn't come up with anything but {}, fall back to the binding pattern if present. + if (links.type === emptyObjectType) { + links.type = getTypeFromBindingPattern(decl.name); + } + assignBindingElementTypes(decl.name); + } + } + } + function createPromiseType(promisedType) { + // creates a `Promise` type where `T` is the promisedType argument + var globalPromiseType = getGlobalPromiseType(/*reportErrors*/ true); + if (globalPromiseType !== emptyGenericType) { + // if the promised type is itself a promise, get the underlying type; otherwise, fallback to the promised type + promisedType = getAwaitedType(promisedType) || emptyObjectType; + return createTypeReference(globalPromiseType, [promisedType]); + } + return emptyObjectType; + } + function createPromiseLikeType(promisedType) { + // creates a `PromiseLike` type where `T` is the promisedType argument + var globalPromiseLikeType = getGlobalPromiseLikeType(/*reportErrors*/ true); + if (globalPromiseLikeType !== emptyGenericType) { + // if the promised type is itself a promise, get the underlying type; otherwise, fallback to the promised type + promisedType = getAwaitedType(promisedType) || emptyObjectType; + return createTypeReference(globalPromiseLikeType, [promisedType]); + } + return emptyObjectType; + } + function createPromiseReturnType(func, promisedType) { + var promiseType = createPromiseType(promisedType); + if (promiseType === emptyObjectType) { + error(func, ts.isImportCall(func) ? + ts.Diagnostics.A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option : + ts.Diagnostics.An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option); + return errorType; + } + else if (!getGlobalPromiseConstructorSymbol(/*reportErrors*/ true)) { + error(func, ts.isImportCall(func) ? + ts.Diagnostics.A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option : + ts.Diagnostics.An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option); + } + return promiseType; + } + function getReturnTypeFromBody(func, checkMode) { + if (!func.body) { + return errorType; + } + var functionFlags = ts.getFunctionFlags(func); + var type; + if (func.body.kind !== 218 /* Block */) { + type = checkExpressionCached(func.body, checkMode); + if (functionFlags & 2 /* Async */) { + // From within an async function you can return either a non-promise value or a promise. Any + // Promise/A+ compatible implementation will always assimilate any foreign promise, so the + // return type of the body should be unwrapped to its awaited type, which we will wrap in + // the native Promise type later in this function. + type = checkAwaitedType(type, /*errorNode*/ func, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); + } + } + else { + var types = checkAndAggregateReturnExpressionTypes(func, checkMode); + if (functionFlags & 1 /* Generator */) { // Generator or AsyncGenerator function + types = ts.concatenate(checkAndAggregateYieldOperandTypes(func, checkMode), types); + if (!types || types.length === 0) { + var iterableIteratorAny = functionFlags & 2 /* Async */ + ? createAsyncIterableIteratorType(anyType) // AsyncGenerator function + : createIterableIteratorType(anyType); // Generator function + if (noImplicitAny) { + error(func.asteriskToken, ts.Diagnostics.Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_type, typeToString(iterableIteratorAny)); + } + return iterableIteratorAny; + } + } + else { + if (!types) { + // For an async function, the return type will not be never, but rather a Promise for never. + return functionFlags & 2 /* Async */ + ? createPromiseReturnType(func, neverType) // Async function + : neverType; // Normal function + } + if (types.length === 0) { + // For an async function, the return type will not be void, but rather a Promise for void. + return functionFlags & 2 /* Async */ + ? createPromiseReturnType(func, voidType) // Async function + : voidType; // Normal function + } + } + // Return a union of the return expression types. + type = getUnionType(types, 2 /* Subtype */); + } + var contextualSignature = getContextualSignatureForFunctionLikeDeclaration(func); + if (!contextualSignature) { + reportErrorsFromWidening(func, type); + } + if (isUnitType(type)) { + var contextualType = !contextualSignature ? undefined : + contextualSignature === getSignatureFromDeclaration(func) ? type : + getReturnTypeOfSignature(contextualSignature); + if (contextualType) { + switch (functionFlags & 3 /* AsyncGenerator */) { + case 3 /* AsyncGenerator */: + contextualType = getIteratedTypeOfGenerator(contextualType, /*isAsyncGenerator*/ true); + break; + case 1 /* Generator */: + contextualType = getIteratedTypeOfGenerator(contextualType, /*isAsyncGenerator*/ false); + break; + case 2 /* Async */: + contextualType = getPromisedTypeOfPromise(contextualType); + break; + } + } + type = getWidenedLiteralLikeTypeForContextualType(type, contextualType); + } + var widenedType = getWidenedType(type); + switch (functionFlags & 3 /* AsyncGenerator */) { + case 3 /* AsyncGenerator */: + return createAsyncIterableIteratorType(widenedType); + case 1 /* Generator */: + return createIterableIteratorType(widenedType); + case 2 /* Async */: + // From within an async function you can return either a non-promise value or a promise. Any + // Promise/A+ compatible implementation will always assimilate any foreign promise, so the + // return type of the body is awaited type of the body, wrapped in a native Promise type. + return createPromiseType(widenedType); + default: + return widenedType; + } + } + function checkAndAggregateYieldOperandTypes(func, checkMode) { + var aggregatedTypes = []; + var isAsync = (ts.getFunctionFlags(func) & 2 /* Async */) !== 0; + ts.forEachYieldExpression(func.body, function (yieldExpression) { + ts.pushIfUnique(aggregatedTypes, getYieldedTypeOfYieldExpression(yieldExpression, isAsync, checkMode)); + }); + return aggregatedTypes; + } + function getYieldedTypeOfYieldExpression(node, isAsync, checkMode) { + var errorNode = node.expression || node; + var expressionType = node.expression ? checkExpression(node.expression, checkMode) : undefinedWideningType; + // A `yield*` expression effectively yields everything that its operand yields + var yieldedType = node.asteriskToken ? checkIteratedTypeOrElementType(expressionType, errorNode, /*allowStringInput*/ false, isAsync) : expressionType; + return !isAsync ? yieldedType : getAwaitedType(yieldedType, errorNode, node.asteriskToken + ? ts.Diagnostics.Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member + : ts.Diagnostics.Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); + } + /** + * Collect the TypeFacts learned from a typeof switch with + * total clauses `witnesses`, and the active clause ranging + * from `start` to `end`. Parameter `hasDefault` denotes + * whether the active clause contains a default clause. + */ + function getFactsFromTypeofSwitch(start, end, witnesses, hasDefault) { + var facts = 0 /* None */; + // When in the default we only collect inequality facts + // because default is 'in theory' a set of infinite + // equalities. + if (hasDefault) { + // Value is not equal to any types after the active clause. + for (var i = end; i < witnesses.length; i++) { + facts |= typeofNEFacts.get(witnesses[i]) || 32768 /* TypeofNEHostObject */; + } + // Remove inequalities for types that appear in the + // active clause because they appear before other + // types collected so far. + for (var i = start; i < end; i++) { + facts &= ~(typeofNEFacts.get(witnesses[i]) || 0); + } + // Add inequalities for types before the active clause unconditionally. + for (var i = 0; i < start; i++) { + facts |= typeofNEFacts.get(witnesses[i]) || 32768 /* TypeofNEHostObject */; + } + } + // When in an active clause without default the set of + // equalities is finite. + else { + // Add equalities for all types in the active clause. + for (var i = start; i < end; i++) { + facts |= typeofEQFacts.get(witnesses[i]) || 128 /* TypeofEQHostObject */; + } + // Remove equalities for types that appear before the + // active clause. + for (var i = 0; i < start; i++) { + facts &= ~(typeofEQFacts.get(witnesses[i]) || 0); + } + } + return facts; + } + function isExhaustiveSwitchStatement(node) { + if (!node.possiblyExhaustive) { + return false; + } + if (node.expression.kind === 199 /* TypeOfExpression */) { + var operandType = getTypeOfExpression(node.expression.expression); + // This cast is safe because the switch is possibly exhaustive and does not contain a default case, so there can be no undefined. + var witnesses = getSwitchClauseTypeOfWitnesses(node); + // notEqualFacts states that the type of the switched value is not equal to every type in the switch. + var notEqualFacts_1 = getFactsFromTypeofSwitch(0, 0, witnesses, /*hasDefault*/ true); + var type_5 = getBaseConstraintOfType(operandType) || operandType; + return !!(filterType(type_5, function (t) { return (getTypeFacts(t) & notEqualFacts_1) === notEqualFacts_1; }).flags & 131072 /* Never */); + } + var type = getTypeOfExpression(node.expression); + if (!isLiteralType(type)) { + return false; + } + var switchTypes = getSwitchClauseTypes(node); + if (!switchTypes.length || ts.some(switchTypes, isNeitherUnitTypeNorNever)) { + return false; + } + return eachTypeContainedIn(mapType(type, getRegularTypeOfLiteralType), switchTypes); + } + function functionHasImplicitReturn(func) { + if (!(func.flags & 128 /* HasImplicitReturn */)) { + return false; + } + if (ts.some(func.body.statements, function (statement) { return statement.kind === 232 /* SwitchStatement */ && isExhaustiveSwitchStatement(statement); })) { + return false; + } + return true; + } + /** NOTE: Return value of `[]` means a different thing than `undefined`. `[]` means func returns `void`, `undefined` means it returns `never`. */ + function checkAndAggregateReturnExpressionTypes(func, checkMode) { + var functionFlags = ts.getFunctionFlags(func); + var aggregatedTypes = []; + var hasReturnWithNoExpression = functionHasImplicitReturn(func); + var hasReturnOfTypeNever = false; + ts.forEachReturnStatement(func.body, function (returnStatement) { + var expr = returnStatement.expression; + if (expr) { + var type = checkExpressionCached(expr, checkMode); + if (functionFlags & 2 /* Async */) { + // From within an async function you can return either a non-promise value or a promise. Any + // Promise/A+ compatible implementation will always assimilate any foreign promise, so the + // return type of the body should be unwrapped to its awaited type, which should be wrapped in + // the native Promise type by the caller. + type = checkAwaitedType(type, func, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); + } + if (type.flags & 131072 /* Never */) { + hasReturnOfTypeNever = true; + } + ts.pushIfUnique(aggregatedTypes, type); + } + else { + hasReturnWithNoExpression = true; + } + }); + if (aggregatedTypes.length === 0 && !hasReturnWithNoExpression && (hasReturnOfTypeNever || mayReturnNever(func))) { + return undefined; + } + if (strictNullChecks && aggregatedTypes.length && hasReturnWithNoExpression && + !(isJSConstructor(func) && aggregatedTypes.some(function (t) { return t.symbol === func.symbol; }))) { + // Javascript "callable constructors", containing eg `if (!(this instanceof A)) return new A()` should not add undefined + ts.pushIfUnique(aggregatedTypes, undefinedType); + } + return aggregatedTypes; + } + function mayReturnNever(func) { + switch (func.kind) { + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + return true; + case 156 /* MethodDeclaration */: + return func.parent.kind === 188 /* ObjectLiteralExpression */; + default: + return false; + } + } + /** + * TypeScript Specification 1.0 (6.3) - July 2014 + * An explicitly typed function whose return type isn't the Void type, + * the Any type, or a union type containing the Void or Any type as a constituent + * must have at least one return statement somewhere in its body. + * An exception to this rule is if the function implementation consists of a single 'throw' statement. + * + * @param returnType - return type of the function, can be undefined if return type is not explicitly specified + */ + function checkAllCodePathsInNonVoidFunctionReturnOrThrow(func, returnType) { + if (!produceDiagnostics) { + return; + } + // Functions with with an explicitly specified 'void' or 'any' return type don't need any return expressions. + if (returnType && maybeTypeOfKind(returnType, 1 /* Any */ | 16384 /* Void */)) { + return; + } + // If all we have is a function signature, or an arrow function with an expression body, then there is nothing to check. + // also if HasImplicitReturn flag is not set this means that all codepaths in function body end with return or throw + if (func.kind === 155 /* MethodSignature */ || ts.nodeIsMissing(func.body) || func.body.kind !== 218 /* Block */ || !functionHasImplicitReturn(func)) { + return; + } + var hasExplicitReturn = func.flags & 256 /* HasExplicitReturn */; + if (returnType && returnType.flags & 131072 /* Never */) { + error(ts.getEffectiveReturnTypeNode(func), ts.Diagnostics.A_function_returning_never_cannot_have_a_reachable_end_point); + } + else if (returnType && !hasExplicitReturn) { + // minimal check: function has syntactic return type annotation and no explicit return statements in the body + // this function does not conform to the specification. + // NOTE: having returnType !== undefined is a precondition for entering this branch so func.type will always be present + error(ts.getEffectiveReturnTypeNode(func), ts.Diagnostics.A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value); + } + else if (returnType && strictNullChecks && !isTypeAssignableTo(undefinedType, returnType)) { + error(ts.getEffectiveReturnTypeNode(func), ts.Diagnostics.Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined); + } + else if (compilerOptions.noImplicitReturns) { + if (!returnType) { + // If return type annotation is omitted check if function has any explicit return statements. + // If it does not have any - its inferred return type is void - don't do any checks. + // Otherwise get inferred return type from function body and report error only if it is not void / anytype + if (!hasExplicitReturn) { + return; + } + var inferredReturnType = getReturnTypeOfSignature(getSignatureFromDeclaration(func)); + if (isUnwrappedReturnTypeVoidOrAny(func, inferredReturnType)) { + return; + } + } + error(ts.getEffectiveReturnTypeNode(func) || func, ts.Diagnostics.Not_all_code_paths_return_a_value); + } + } + function checkFunctionExpressionOrObjectLiteralMethod(node, checkMode) { + ts.Debug.assert(node.kind !== 156 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + checkNodeDeferred(node); + // The identityMapper object is used to indicate that function expressions are wildcards + if (checkMode === 1 /* SkipContextSensitive */ && isContextSensitive(node)) { + // Skip parameters, return signature with return type that retains noncontextual parts so inferences can still be drawn in an early stage + if (!ts.getEffectiveReturnTypeNode(node) && hasContextSensitiveReturnExpression(node)) { + var links_1 = getNodeLinks(node); + if (links_1.contextFreeType) { + return links_1.contextFreeType; + } + var returnType = getReturnTypeFromBody(node, checkMode); + var returnOnlySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, returnType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + var returnOnlyType = createAnonymousType(node.symbol, emptySymbols, [returnOnlySignature], ts.emptyArray, undefined, undefined); + returnOnlyType.flags |= 536870912 /* ContainsAnyFunctionType */; + return links_1.contextFreeType = returnOnlyType; + } + return anyFunctionType; + } + // Grammar checking + var hasGrammarError = checkGrammarFunctionLikeDeclaration(node); + if (!hasGrammarError && node.kind === 196 /* FunctionExpression */) { + checkGrammarForGenerator(node); + } + var links = getNodeLinks(node); + var type = getTypeOfSymbol(getMergedSymbol(node.symbol)); + if (isTypeAny(type)) { + return type; + } + // Check if function expression is contextually typed and assign parameter types if so. + if (!(links.flags & 1024 /* ContextChecked */)) { + var contextualSignature = getContextualSignature(node); + // If a type check is started at a function expression that is an argument of a function call, obtaining the + // contextual type may recursively get back to here during overload resolution of the call. If so, we will have + // already assigned contextual types. + if (!(links.flags & 1024 /* ContextChecked */)) { + links.flags |= 1024 /* ContextChecked */; + if (contextualSignature) { + var signature = getSignaturesOfType(type, 0 /* Call */)[0]; + if (isContextSensitive(node)) { + var contextualMapper = getContextualMapper(node); + if (checkMode === 2 /* Inferential */) { + inferFromAnnotatedParameters(signature, contextualSignature, contextualMapper); + } + var instantiatedContextualSignature = contextualMapper === identityMapper ? + contextualSignature : instantiateSignature(contextualSignature, contextualMapper); + assignContextualParameterTypes(signature, instantiatedContextualSignature); + } + if (!getReturnTypeFromAnnotation(node) && !signature.resolvedReturnType) { + var returnType = getReturnTypeFromBody(node, checkMode); + if (!signature.resolvedReturnType) { + signature.resolvedReturnType = returnType; + } + } + } + checkSignatureDeclaration(node); + } + } + return type; + } + function getReturnOrPromisedType(node, functionFlags) { + var type = getReturnTypeFromAnnotation(node); + return type && ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */) ? + getAwaitedType(type) || errorType : type; + } + function checkFunctionExpressionOrObjectLiteralMethodDeferred(node) { + ts.Debug.assert(node.kind !== 156 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + var functionFlags = ts.getFunctionFlags(node); + var returnOrPromisedType = getReturnOrPromisedType(node, functionFlags); + if ((functionFlags & 1 /* Generator */) === 0) { // Async function or normal function + // return is not necessary in the body of generators + checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnOrPromisedType); + } + if (node.body) { + if (!ts.getEffectiveReturnTypeNode(node)) { + // There are some checks that are only performed in getReturnTypeFromBody, that may produce errors + // we need. An example is the noImplicitAny errors resulting from widening the return expression + // of a function. Because checking of function expression bodies is deferred, there was never an + // appropriate time to do this during the main walk of the file (see the comment at the top of + // checkFunctionExpressionBodies). So it must be done now. + getReturnTypeOfSignature(getSignatureFromDeclaration(node)); + } + if (node.body.kind === 218 /* Block */) { + checkSourceElement(node.body); + } + else { + // From within an async function you can return either a non-promise value or a promise. Any + // Promise/A+ compatible implementation will always assimilate any foreign promise, so we + // should not be checking assignability of a promise to the return type. Instead, we need to + // check assignability of the awaited type of the expression body against the promised type of + // its return type annotation. + var exprType = checkExpression(node.body); + if (returnOrPromisedType) { + if ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */) { // Async function + var awaitedType = checkAwaitedType(exprType, node.body, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); + checkTypeAssignableToAndOptionallyElaborate(awaitedType, returnOrPromisedType, node.body, node.body); + } + else { // Normal function + checkTypeAssignableToAndOptionallyElaborate(exprType, returnOrPromisedType, node.body, node.body); + } + } + } + } + } + function checkArithmeticOperandType(operand, type, diagnostic) { + if (!isTypeAssignableTo(type, numberOrBigIntType)) { + error(operand, diagnostic); + return false; + } + return true; + } + function isReadonlyAssignmentDeclaration(d) { + if (!ts.isCallExpression(d)) { + return false; + } + if (!ts.isBindableObjectDefinePropertyCall(d)) { + return false; + } + var objectLitType = checkExpressionCached(d.arguments[2]); + var valueType = getTypeOfPropertyOfType(objectLitType, "value"); + if (valueType) { + var writableProp = getPropertyOfType(objectLitType, "writable"); + var writableType = writableProp && getTypeOfSymbol(writableProp); + if (!writableType || writableType === falseType || writableType === regularFalseType) { + return true; + } + // We include this definition whereupon we walk back and check the type at the declaration because + // The usual definition of `Object.defineProperty` will _not_ cause literal types to be preserved in the + // argument types, should the type be contextualized by the call itself. + if (writableProp && writableProp.valueDeclaration && ts.isPropertyAssignment(writableProp.valueDeclaration)) { + var initializer = writableProp.valueDeclaration.initializer; + var rawOriginalType = checkExpression(initializer); + if (rawOriginalType === falseType || rawOriginalType === regularFalseType) { + return true; + } + } + return false; + } + var setProp = getPropertyOfType(objectLitType, "set"); + return !setProp; + } + function isReadonlySymbol(symbol) { + // The following symbols are considered read-only: + // Properties with a 'readonly' modifier + // Variables declared with 'const' + // Get accessors without matching set accessors + // Enum members + // Object.defineProperty assignments with writable false or no setter + // Unions and intersections of the above (unions and intersections eagerly set isReadonly on creation) + return !!(ts.getCheckFlags(symbol) & 8 /* Readonly */ || + symbol.flags & 4 /* Property */ && ts.getDeclarationModifierFlagsFromSymbol(symbol) & 64 /* Readonly */ || + symbol.flags & 3 /* Variable */ && getDeclarationNodeFlagsFromSymbol(symbol) & 2 /* Const */ || + symbol.flags & 98304 /* Accessor */ && !(symbol.flags & 65536 /* SetAccessor */) || + symbol.flags & 8 /* EnumMember */ || + ts.some(symbol.declarations, isReadonlyAssignmentDeclaration)); + } + function isReferenceToReadonlyEntity(expr, symbol) { + if (isReadonlySymbol(symbol)) { + // Allow assignments to readonly properties within constructors of the same class declaration. + if (symbol.flags & 4 /* Property */ && + (expr.kind === 189 /* PropertyAccessExpression */ || expr.kind === 190 /* ElementAccessExpression */) && + expr.expression.kind === 100 /* ThisKeyword */) { + // Look for if this is the constructor for the class that `symbol` is a property of. + var func = ts.getContainingFunction(expr); + if (!(func && func.kind === 157 /* Constructor */)) { + return true; + } + // If func.parent is a class and symbol is a (readonly) property of that class, or + // if func is a constructor and symbol is a (readonly) parameter property declared in it, + // then symbol is writeable here. + return !symbol.valueDeclaration || !(func.parent === symbol.valueDeclaration.parent || func === symbol.valueDeclaration.parent); + } + return true; + } + return false; + } + function isReferenceThroughNamespaceImport(expr) { + if (expr.kind === 189 /* PropertyAccessExpression */ || expr.kind === 190 /* ElementAccessExpression */) { + var node = ts.skipParentheses(expr.expression); + if (node.kind === 72 /* Identifier */) { + var symbol = getNodeLinks(node).resolvedSymbol; + if (symbol.flags & 2097152 /* Alias */) { + var declaration = getDeclarationOfAliasSymbol(symbol); + return !!declaration && declaration.kind === 251 /* NamespaceImport */; + } + } + } + return false; + } + function checkReferenceExpression(expr, invalidReferenceMessage) { + // References are combinations of identifiers, parentheses, and property accesses. + var node = ts.skipOuterExpressions(expr, 2 /* Assertions */ | 1 /* Parentheses */); + if (node.kind !== 72 /* Identifier */ && node.kind !== 189 /* PropertyAccessExpression */ && node.kind !== 190 /* ElementAccessExpression */) { + error(expr, invalidReferenceMessage); + return false; + } + return true; + } + function checkDeleteExpression(node) { + checkExpression(node.expression); + var expr = ts.skipParentheses(node.expression); + if (expr.kind !== 189 /* PropertyAccessExpression */ && expr.kind !== 190 /* ElementAccessExpression */) { + error(expr, ts.Diagnostics.The_operand_of_a_delete_operator_must_be_a_property_reference); + return booleanType; + } + var links = getNodeLinks(expr); + var symbol = getExportSymbolOfValueSymbolIfExported(links.resolvedSymbol); + if (symbol && isReadonlySymbol(symbol)) { + error(expr, ts.Diagnostics.The_operand_of_a_delete_operator_cannot_be_a_read_only_property); + } + return booleanType; + } + function checkTypeOfExpression(node) { + checkExpression(node.expression); + return typeofType; + } + function checkVoidExpression(node) { + checkExpression(node.expression); + return undefinedWideningType; + } + function checkAwaitExpression(node) { + // Grammar checking + if (produceDiagnostics) { + if (!(node.flags & 16384 /* AwaitContext */)) { + grammarErrorOnFirstToken(node, ts.Diagnostics.await_expression_is_only_allowed_within_an_async_function); + } + if (isInParameterInitializerBeforeContainingFunction(node)) { + error(node, ts.Diagnostics.await_expressions_cannot_be_used_in_a_parameter_initializer); + } + } + var operandType = checkExpression(node.expression); + return checkAwaitedType(operandType, node, ts.Diagnostics.Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); + } + function checkPrefixUnaryExpression(node) { + var operandType = checkExpression(node.operand); + if (operandType === silentNeverType) { + return silentNeverType; + } + switch (node.operand.kind) { + case 8 /* NumericLiteral */: + switch (node.operator) { + case 39 /* MinusToken */: + return getFreshTypeOfLiteralType(getLiteralType(-node.operand.text)); + case 38 /* PlusToken */: + return getFreshTypeOfLiteralType(getLiteralType(+node.operand.text)); + } + break; + case 9 /* BigIntLiteral */: + if (node.operator === 39 /* MinusToken */) { + return getFreshTypeOfLiteralType(getLiteralType({ + negative: true, + base10Value: ts.parsePseudoBigInt(node.operand.text) + })); + } + } + switch (node.operator) { + case 38 /* PlusToken */: + case 39 /* MinusToken */: + case 53 /* TildeToken */: + checkNonNullType(operandType, node.operand); + if (maybeTypeOfKind(operandType, 12288 /* ESSymbolLike */)) { + error(node.operand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(node.operator)); + } + if (node.operator === 38 /* PlusToken */) { + if (maybeTypeOfKind(operandType, 2112 /* BigIntLike */)) { + error(node.operand, ts.Diagnostics.Operator_0_cannot_be_applied_to_type_1, ts.tokenToString(node.operator), typeToString(operandType)); + } + return numberType; + } + return getUnaryResultType(operandType); + case 52 /* ExclamationToken */: + checkTruthinessExpression(node.operand); + var facts = getTypeFacts(operandType) & (4194304 /* Truthy */ | 8388608 /* Falsy */); + return facts === 4194304 /* Truthy */ ? falseType : + facts === 8388608 /* Falsy */ ? trueType : + booleanType; + case 44 /* PlusPlusToken */: + case 45 /* MinusMinusToken */: + var ok = checkArithmeticOperandType(node.operand, checkNonNullType(operandType, node.operand), ts.Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_bigint_or_an_enum_type); + if (ok) { + // run check only if former checks succeeded to avoid reporting cascading errors + checkReferenceExpression(node.operand, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access); + } + return getUnaryResultType(operandType); + } + return errorType; + } + function checkPostfixUnaryExpression(node) { + var operandType = checkExpression(node.operand); + if (operandType === silentNeverType) { + return silentNeverType; + } + var ok = checkArithmeticOperandType(node.operand, checkNonNullType(operandType, node.operand), ts.Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_bigint_or_an_enum_type); + if (ok) { + // run check only if former checks succeeded to avoid reporting cascading errors + checkReferenceExpression(node.operand, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access); + } + return getUnaryResultType(operandType); + } + function getUnaryResultType(operandType) { + if (maybeTypeOfKind(operandType, 2112 /* BigIntLike */)) { + return isTypeAssignableToKind(operandType, 3 /* AnyOrUnknown */) || maybeTypeOfKind(operandType, 296 /* NumberLike */) + ? numberOrBigIntType + : bigintType; + } + // If it's not a bigint type, implicit coercion will result in a number + return numberType; + } + // Return true if type might be of the given kind. A union or intersection type might be of a given + // kind if at least one constituent type is of the given kind. + function maybeTypeOfKind(type, kind) { + if (type.flags & kind & ~134217728 /* GenericMappedType */ || kind & 134217728 /* GenericMappedType */ && isGenericMappedType(type)) { + return true; + } + if (type.flags & 3145728 /* UnionOrIntersection */) { + var types = type.types; + for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { + var t = types_15[_i]; + if (maybeTypeOfKind(t, kind)) { + return true; + } + } + } + return false; + } + function isTypeAssignableToKind(source, kind, strict) { + if (source.flags & kind) { + return true; + } + if (strict && source.flags & (3 /* AnyOrUnknown */ | 16384 /* Void */ | 32768 /* Undefined */ | 65536 /* Null */)) { + return false; + } + return !!(kind & 296 /* NumberLike */) && isTypeAssignableTo(source, numberType) || + !!(kind & 2112 /* BigIntLike */) && isTypeAssignableTo(source, bigintType) || + !!(kind & 132 /* StringLike */) && isTypeAssignableTo(source, stringType) || + !!(kind & 528 /* BooleanLike */) && isTypeAssignableTo(source, booleanType) || + !!(kind & 16384 /* Void */) && isTypeAssignableTo(source, voidType) || + !!(kind & 131072 /* Never */) && isTypeAssignableTo(source, neverType) || + !!(kind & 65536 /* Null */) && isTypeAssignableTo(source, nullType) || + !!(kind & 32768 /* Undefined */) && isTypeAssignableTo(source, undefinedType) || + !!(kind & 4096 /* ESSymbol */) && isTypeAssignableTo(source, esSymbolType) || + !!(kind & 67108864 /* NonPrimitive */) && isTypeAssignableTo(source, nonPrimitiveType); + } + function allTypesAssignableToKind(source, kind, strict) { + return source.flags & 1048576 /* Union */ ? + ts.every(source.types, function (subType) { return allTypesAssignableToKind(subType, kind, strict); }) : + isTypeAssignableToKind(source, kind, strict); + } + function isConstEnumObjectType(type) { + return !!(ts.getObjectFlags(type) & 16 /* Anonymous */) && !!type.symbol && isConstEnumSymbol(type.symbol); + } + function isConstEnumSymbol(symbol) { + return (symbol.flags & 128 /* ConstEnum */) !== 0; + } + function checkInstanceOfExpression(left, right, leftType, rightType) { + if (leftType === silentNeverType || rightType === silentNeverType) { + return silentNeverType; + } + // TypeScript 1.0 spec (April 2014): 4.15.4 + // The instanceof operator requires the left operand to be of type Any, an object type, or a type parameter type, + // and the right operand to be of type Any, a subtype of the 'Function' interface type, or have a call or construct signature. + // The result is always of the Boolean primitive type. + // NOTE: do not raise error if leftType is unknown as related error was already reported + if (!isTypeAny(leftType) && + allTypesAssignableToKind(leftType, 131068 /* Primitive */)) { + error(left, ts.Diagnostics.The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter); + } + // NOTE: do not raise error if right is unknown as related error was already reported + if (!(isTypeAny(rightType) || typeHasCallOrConstructSignatures(rightType) || isTypeSubtypeOf(rightType, globalFunctionType))) { + error(right, ts.Diagnostics.The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_Function_interface_type); + } + return booleanType; + } + function checkInExpression(left, right, leftType, rightType) { + if (leftType === silentNeverType || rightType === silentNeverType) { + return silentNeverType; + } + leftType = checkNonNullType(leftType, left); + rightType = checkNonNullType(rightType, right); + // TypeScript 1.0 spec (April 2014): 4.15.5 + // The in operator requires the left operand to be of type Any, the String primitive type, or the Number primitive type, + // and the right operand to be of type Any, an object type, or a type parameter type. + // The result is always of the Boolean primitive type. + if (!(isTypeComparableTo(leftType, stringType) || isTypeAssignableToKind(leftType, 296 /* NumberLike */ | 12288 /* ESSymbolLike */))) { + error(left, ts.Diagnostics.The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol); + } + if (!isTypeAssignableToKind(rightType, 67108864 /* NonPrimitive */ | 58982400 /* InstantiableNonPrimitive */)) { + error(right, ts.Diagnostics.The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter); + } + return booleanType; + } + function checkObjectLiteralAssignment(node, sourceType, rightIsThis) { + var properties = node.properties; + if (strictNullChecks && properties.length === 0) { + return checkNonNullType(sourceType, node); + } + for (var _i = 0, properties_6 = properties; _i < properties_6.length; _i++) { + var p = properties_6[_i]; + checkObjectLiteralDestructuringPropertyAssignment(sourceType, p, properties, rightIsThis); + } + return sourceType; + } + /** Note: If property cannot be a SpreadAssignment, then allProperties does not need to be provided */ + function checkObjectLiteralDestructuringPropertyAssignment(objectLiteralType, property, allProperties, rightIsThis) { + if (rightIsThis === void 0) { rightIsThis = false; } + if (property.kind === 275 /* PropertyAssignment */ || property.kind === 276 /* ShorthandPropertyAssignment */) { + var name = property.name; + if (name.kind === 149 /* ComputedPropertyName */) { + checkComputedPropertyName(name); + } + if (isComputedNonLiteralName(name)) { + return undefined; + } + var type = getTypeOfObjectLiteralDestructuringProperty(objectLiteralType, name, property, rightIsThis); + if (type) { + // non-shorthand property assignments should always have initializers + return checkDestructuringAssignment(property.kind === 276 /* ShorthandPropertyAssignment */ ? property : property.initializer, type); + } + else { + error(name, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(objectLiteralType), ts.declarationNameToString(name)); + } + } + else if (property.kind === 277 /* SpreadAssignment */) { + if (languageVersion < 6 /* ESNext */) { + checkExternalEmitHelpers(property, 4 /* Rest */); + } + var nonRestNames = []; + if (allProperties) { + for (var i = 0; i < allProperties.length - 1; i++) { + nonRestNames.push(allProperties[i].name); + } + } + var type = getRestType(objectLiteralType, nonRestNames, objectLiteralType.symbol); + checkGrammarForDisallowedTrailingComma(allProperties, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma); + return checkDestructuringAssignment(property.expression, type); + } + else { + error(property, ts.Diagnostics.Property_assignment_expected); + } + } + function getTypeOfObjectLiteralDestructuringProperty(objectLiteralType, name, property, rightIsThis) { + if (isTypeAny(objectLiteralType)) { + return objectLiteralType; + } + var type; + var text = ts.getTextOfPropertyName(name); + if (text) { // TODO: GH#26379 + var prop = getPropertyOfType(objectLiteralType, text); + if (prop) { + markPropertyAsReferenced(prop, property, rightIsThis); + checkPropertyAccessibility(property, /*isSuper*/ false, objectLiteralType, prop); + type = getTypeOfSymbol(prop); + } + type = type || (isNumericLiteralName(text) ? getIndexTypeOfType(objectLiteralType, 1 /* Number */) : undefined); + } + return type || getIndexTypeOfType(objectLiteralType, 0 /* String */); + } + function checkArrayLiteralAssignment(node, sourceType, checkMode) { + var elements = node.elements; + if (languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) { + checkExternalEmitHelpers(node, 512 /* Read */); + } + // This elementType will be used if the specific property corresponding to this index is not + // present (aka the tuple element property). This call also checks that the parentType is in + // fact an iterable or array (depending on target language). + var elementType = checkIteratedTypeOrElementType(sourceType, node, /*allowStringInput*/ false, /*allowAsyncIterables*/ false) || errorType; + for (var i = 0; i < elements.length; i++) { + checkArrayLiteralDestructuringElementAssignment(node, sourceType, i, elementType, checkMode); + } + return sourceType; + } + function checkArrayLiteralDestructuringElementAssignment(node, sourceType, elementIndex, elementType, checkMode) { + var elements = node.elements; + var element = elements[elementIndex]; + if (element.kind !== 210 /* OmittedExpression */) { + if (element.kind !== 208 /* SpreadElement */) { + var propName = "" + elementIndex; + var type = isTypeAny(sourceType) ? sourceType : + everyType(sourceType, isTupleLikeType) ? getTupleElementType(sourceType, elementIndex) : + elementType; + if (type) { + return checkDestructuringAssignment(element, type, checkMode); + } + // We still need to check element expression here because we may need to set appropriate flag on the expression + // such as NodeCheckFlags.LexicalThis on "this"expression. + checkExpression(element); + if (isTupleType(sourceType)) { + error(element, ts.Diagnostics.Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2, typeToString(sourceType), getTypeReferenceArity(sourceType), elements.length); + } + else { + error(element, ts.Diagnostics.Type_0_has_no_property_1, typeToString(sourceType), propName); + } + } + else { + if (elementIndex < elements.length - 1) { + error(element, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern); + } + else { + var restExpression = element.expression; + if (restExpression.kind === 204 /* BinaryExpression */ && restExpression.operatorToken.kind === 59 /* EqualsToken */) { + error(restExpression.operatorToken, ts.Diagnostics.A_rest_element_cannot_have_an_initializer); + } + else { + checkGrammarForDisallowedTrailingComma(node.elements, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma); + var type = everyType(sourceType, isTupleType) ? + mapType(sourceType, function (t) { return sliceTupleType(t, elementIndex); }) : + createArrayType(elementType); + return checkDestructuringAssignment(restExpression, type, checkMode); + } + } + } + } + return undefined; + } + function checkDestructuringAssignment(exprOrAssignment, sourceType, checkMode, rightIsThis) { + var target; + if (exprOrAssignment.kind === 276 /* ShorthandPropertyAssignment */) { + var prop = exprOrAssignment; + if (prop.objectAssignmentInitializer) { + // In strict null checking mode, if a default value of a non-undefined type is specified, remove + // undefined from the final type. + if (strictNullChecks && + !(getFalsyFlags(checkExpression(prop.objectAssignmentInitializer)) & 32768 /* Undefined */)) { + sourceType = getTypeWithFacts(sourceType, 524288 /* NEUndefined */); + } + checkBinaryLikeExpression(prop.name, prop.equalsToken, prop.objectAssignmentInitializer, checkMode); + } + target = exprOrAssignment.name; + } + else { + target = exprOrAssignment; + } + if (target.kind === 204 /* BinaryExpression */ && target.operatorToken.kind === 59 /* EqualsToken */) { + checkBinaryExpression(target, checkMode); + target = target.left; + } + if (target.kind === 188 /* ObjectLiteralExpression */) { + return checkObjectLiteralAssignment(target, sourceType, rightIsThis); + } + if (target.kind === 187 /* ArrayLiteralExpression */) { + return checkArrayLiteralAssignment(target, sourceType, checkMode); + } + return checkReferenceAssignment(target, sourceType, checkMode); + } + function checkReferenceAssignment(target, sourceType, checkMode) { + var targetType = checkExpression(target, checkMode); + var error = target.parent.kind === 277 /* SpreadAssignment */ ? + ts.Diagnostics.The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access : + ts.Diagnostics.The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access; + if (checkReferenceExpression(target, error)) { + checkTypeAssignableToAndOptionallyElaborate(sourceType, targetType, target, target); + } + return sourceType; + } + /** + * This is a *shallow* check: An expression is side-effect-free if the + * evaluation of the expression *itself* cannot produce side effects. + * For example, x++ / 3 is side-effect free because the / operator + * does not have side effects. + * The intent is to "smell test" an expression for correctness in positions where + * its value is discarded (e.g. the left side of the comma operator). + */ + function isSideEffectFree(node) { + node = ts.skipParentheses(node); + switch (node.kind) { + case 72 /* Identifier */: + case 10 /* StringLiteral */: + case 13 /* RegularExpressionLiteral */: + case 193 /* TaggedTemplateExpression */: + case 206 /* TemplateExpression */: + case 14 /* NoSubstitutionTemplateLiteral */: + case 8 /* NumericLiteral */: + case 9 /* BigIntLiteral */: + case 102 /* TrueKeyword */: + case 87 /* FalseKeyword */: + case 96 /* NullKeyword */: + case 141 /* UndefinedKeyword */: + case 196 /* FunctionExpression */: + case 209 /* ClassExpression */: + case 197 /* ArrowFunction */: + case 187 /* ArrayLiteralExpression */: + case 188 /* ObjectLiteralExpression */: + case 199 /* TypeOfExpression */: + case 213 /* NonNullExpression */: + case 261 /* JsxSelfClosingElement */: + case 260 /* JsxElement */: + return true; + case 205 /* ConditionalExpression */: + return isSideEffectFree(node.whenTrue) && + isSideEffectFree(node.whenFalse); + case 204 /* BinaryExpression */: + if (ts.isAssignmentOperator(node.operatorToken.kind)) { + return false; + } + return isSideEffectFree(node.left) && + isSideEffectFree(node.right); + case 202 /* PrefixUnaryExpression */: + case 203 /* PostfixUnaryExpression */: + // Unary operators ~, !, +, and - have no side effects. + // The rest do. + switch (node.operator) { + case 52 /* ExclamationToken */: + case 38 /* PlusToken */: + case 39 /* MinusToken */: + case 53 /* TildeToken */: + return true; + } + return false; + // Some forms listed here for clarity + case 200 /* VoidExpression */: // Explicit opt-out + case 194 /* TypeAssertionExpression */: // Not SEF, but can produce useful type warnings + case 212 /* AsExpression */: // Not SEF, but can produce useful type warnings + default: + return false; + } + } + function isTypeEqualityComparableTo(source, target) { + return (target.flags & 98304 /* Nullable */) !== 0 || isTypeComparableTo(source, target); + } + function checkBinaryExpression(node, checkMode) { + if (ts.isInJSFile(node) && ts.getAssignedExpandoInitializer(node)) { + return checkExpression(node.right, checkMode); + } + return checkBinaryLikeExpression(node.left, node.operatorToken, node.right, checkMode, node); + } + function checkBinaryLikeExpression(left, operatorToken, right, checkMode, errorNode) { + var operator = operatorToken.kind; + if (operator === 59 /* EqualsToken */ && (left.kind === 188 /* ObjectLiteralExpression */ || left.kind === 187 /* ArrayLiteralExpression */)) { + return checkDestructuringAssignment(left, checkExpression(right, checkMode), checkMode, right.kind === 100 /* ThisKeyword */); + } + var leftType; + if (operator === 54 /* AmpersandAmpersandToken */ || operator === 55 /* BarBarToken */) { + leftType = checkTruthinessExpression(left, checkMode); + } + else { + leftType = checkExpression(left, checkMode); + } + var rightType = checkExpression(right, checkMode); + switch (operator) { + case 40 /* AsteriskToken */: + case 41 /* AsteriskAsteriskToken */: + case 62 /* AsteriskEqualsToken */: + case 63 /* AsteriskAsteriskEqualsToken */: + case 42 /* SlashToken */: + case 64 /* SlashEqualsToken */: + case 43 /* PercentToken */: + case 65 /* PercentEqualsToken */: + case 39 /* MinusToken */: + case 61 /* MinusEqualsToken */: + case 46 /* LessThanLessThanToken */: + case 66 /* LessThanLessThanEqualsToken */: + case 47 /* GreaterThanGreaterThanToken */: + case 67 /* GreaterThanGreaterThanEqualsToken */: + case 48 /* GreaterThanGreaterThanGreaterThanToken */: + case 68 /* GreaterThanGreaterThanGreaterThanEqualsToken */: + case 50 /* BarToken */: + case 70 /* BarEqualsToken */: + case 51 /* CaretToken */: + case 71 /* CaretEqualsToken */: + case 49 /* AmpersandToken */: + case 69 /* AmpersandEqualsToken */: + if (leftType === silentNeverType || rightType === silentNeverType) { + return silentNeverType; + } + leftType = checkNonNullType(leftType, left); + rightType = checkNonNullType(rightType, right); + var suggestedOperator = void 0; + // if a user tries to apply a bitwise operator to 2 boolean operands + // try and return them a helpful suggestion + if ((leftType.flags & 528 /* BooleanLike */) && + (rightType.flags & 528 /* BooleanLike */) && + (suggestedOperator = getSuggestedBooleanOperator(operatorToken.kind)) !== undefined) { + error(errorNode || operatorToken, ts.Diagnostics.The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead, ts.tokenToString(operatorToken.kind), ts.tokenToString(suggestedOperator)); + return numberType; + } + else { + // otherwise just check each operand separately and report errors as normal + var leftOk = checkArithmeticOperandType(left, leftType, ts.Diagnostics.The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type); + var rightOk = checkArithmeticOperandType(right, rightType, ts.Diagnostics.The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type); + var resultType_1; + // If both are any or unknown, allow operation; assume it will resolve to number + if ((isTypeAssignableToKind(leftType, 3 /* AnyOrUnknown */) && isTypeAssignableToKind(rightType, 3 /* AnyOrUnknown */)) || + // Or, if neither could be bigint, implicit coercion results in a number result + !(maybeTypeOfKind(leftType, 2112 /* BigIntLike */) || maybeTypeOfKind(rightType, 2112 /* BigIntLike */))) { + resultType_1 = numberType; + } + // At least one is assignable to bigint, so both should be only assignable to bigint + else if (isTypeAssignableToKind(leftType, 2112 /* BigIntLike */) && isTypeAssignableToKind(rightType, 2112 /* BigIntLike */)) { + switch (operator) { + case 48 /* GreaterThanGreaterThanGreaterThanToken */: + case 68 /* GreaterThanGreaterThanGreaterThanEqualsToken */: + reportOperatorError(); + } + resultType_1 = bigintType; + } + else { + reportOperatorError(); + resultType_1 = errorType; + } + if (leftOk && rightOk) { + checkAssignmentOperator(resultType_1); + } + return resultType_1; + } + case 38 /* PlusToken */: + case 60 /* PlusEqualsToken */: + if (leftType === silentNeverType || rightType === silentNeverType) { + return silentNeverType; + } + if (!isTypeAssignableToKind(leftType, 132 /* StringLike */) && !isTypeAssignableToKind(rightType, 132 /* StringLike */)) { + leftType = checkNonNullType(leftType, left); + rightType = checkNonNullType(rightType, right); + } + var resultType = void 0; + if (isTypeAssignableToKind(leftType, 296 /* NumberLike */, /*strict*/ true) && isTypeAssignableToKind(rightType, 296 /* NumberLike */, /*strict*/ true)) { + // Operands of an enum type are treated as having the primitive type Number. + // If both operands are of the Number primitive type, the result is of the Number primitive type. + resultType = numberType; + } + else if (isTypeAssignableToKind(leftType, 2112 /* BigIntLike */, /*strict*/ true) && isTypeAssignableToKind(rightType, 2112 /* BigIntLike */, /*strict*/ true)) { + // If both operands are of the BigInt primitive type, the result is of the BigInt primitive type. + resultType = bigintType; + } + else if (isTypeAssignableToKind(leftType, 132 /* StringLike */, /*strict*/ true) || isTypeAssignableToKind(rightType, 132 /* StringLike */, /*strict*/ true)) { + // If one or both operands are of the String primitive type, the result is of the String primitive type. + resultType = stringType; + } + else if (isTypeAny(leftType) || isTypeAny(rightType)) { + // Otherwise, the result is of type Any. + // NOTE: unknown type here denotes error type. Old compiler treated this case as any type so do we. + resultType = leftType === errorType || rightType === errorType ? errorType : anyType; + } + // Symbols are not allowed at all in arithmetic expressions + if (resultType && !checkForDisallowedESSymbolOperand(operator)) { + return resultType; + } + if (!resultType) { + reportOperatorError(); + return anyType; + } + if (operator === 60 /* PlusEqualsToken */) { + checkAssignmentOperator(resultType); + } + return resultType; + case 28 /* LessThanToken */: + case 30 /* GreaterThanToken */: + case 31 /* LessThanEqualsToken */: + case 32 /* GreaterThanEqualsToken */: + if (checkForDisallowedESSymbolOperand(operator)) { + leftType = getBaseTypeOfLiteralType(checkNonNullType(leftType, left)); + rightType = getBaseTypeOfLiteralType(checkNonNullType(rightType, right)); + if (!(isTypeComparableTo(leftType, rightType) || isTypeComparableTo(rightType, leftType) || + (isTypeAssignableTo(leftType, numberOrBigIntType) && isTypeAssignableTo(rightType, numberOrBigIntType)))) { + reportOperatorError(); + } + } + return booleanType; + case 33 /* EqualsEqualsToken */: + case 34 /* ExclamationEqualsToken */: + case 35 /* EqualsEqualsEqualsToken */: + case 36 /* ExclamationEqualsEqualsToken */: + var leftIsLiteral = isLiteralType(leftType); + var rightIsLiteral = isLiteralType(rightType); + if (!leftIsLiteral || !rightIsLiteral) { + leftType = leftIsLiteral ? getBaseTypeOfLiteralType(leftType) : leftType; + rightType = rightIsLiteral ? getBaseTypeOfLiteralType(rightType) : rightType; + } + if (!isTypeEqualityComparableTo(leftType, rightType) && !isTypeEqualityComparableTo(rightType, leftType)) { + reportOperatorError(); + } + return booleanType; + case 94 /* InstanceOfKeyword */: + return checkInstanceOfExpression(left, right, leftType, rightType); + case 93 /* InKeyword */: + return checkInExpression(left, right, leftType, rightType); + case 54 /* AmpersandAmpersandToken */: + return getTypeFacts(leftType) & 4194304 /* Truthy */ ? + getUnionType([extractDefinitelyFalsyTypes(strictNullChecks ? leftType : getBaseTypeOfLiteralType(rightType)), rightType]) : + leftType; + case 55 /* BarBarToken */: + return getTypeFacts(leftType) & 8388608 /* Falsy */ ? + getUnionType([removeDefinitelyFalsyTypes(leftType), rightType], 2 /* Subtype */) : + leftType; + case 59 /* EqualsToken */: + var declKind = ts.isBinaryExpression(left.parent) ? ts.getAssignmentDeclarationKind(left.parent) : 0 /* None */; + checkAssignmentDeclaration(declKind, rightType); + if (isAssignmentDeclaration(declKind)) { + if (!(rightType.flags & 524288 /* Object */) || + declKind !== 2 /* ModuleExports */ && + declKind !== 6 /* Prototype */ && + !isEmptyObjectType(rightType) && + !isFunctionObjectType(rightType) && + !(ts.getObjectFlags(rightType) & 1 /* Class */)) { + // don't check assignability of module.exports=, C.prototype=, or expando types because they will necessarily be incomplete + checkAssignmentOperator(rightType); + } + return leftType; + } + else { + checkAssignmentOperator(rightType); + return getRegularTypeOfObjectLiteral(rightType); + } + case 27 /* CommaToken */: + if (!compilerOptions.allowUnreachableCode && isSideEffectFree(left) && !isEvalNode(right)) { + error(left, ts.Diagnostics.Left_side_of_comma_operator_is_unused_and_has_no_side_effects); + } + return rightType; + default: + return ts.Debug.fail(); + } + function checkAssignmentDeclaration(kind, rightType) { + if (kind === 2 /* ModuleExports */) { + for (var _i = 0, _a = getPropertiesOfObjectType(rightType); _i < _a.length; _i++) { + var prop = _a[_i]; + var propType = getTypeOfSymbol(prop); + if (propType.symbol && propType.symbol.flags & 32 /* Class */) { + var name = prop.escapedName; + var symbol = resolveName(prop.valueDeclaration, name, 67897832 /* Type */, undefined, name, /*isUse*/ false); + if (symbol && symbol.declarations.some(ts.isJSDocTypedefTag)) { + grammarErrorOnNode(symbol.declarations[0], ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name)); + return grammarErrorOnNode(prop.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name)); + } + } + } + } + } + function isEvalNode(node) { + return node.kind === 72 /* Identifier */ && node.escapedText === "eval"; + } + // Return true if there was no error, false if there was an error. + function checkForDisallowedESSymbolOperand(operator) { + var offendingSymbolOperand = maybeTypeOfKind(leftType, 12288 /* ESSymbolLike */) ? left : + maybeTypeOfKind(rightType, 12288 /* ESSymbolLike */) ? right : + undefined; + if (offendingSymbolOperand) { + error(offendingSymbolOperand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(operator)); + return false; + } + return true; + } + function getSuggestedBooleanOperator(operator) { + switch (operator) { + case 50 /* BarToken */: + case 70 /* BarEqualsToken */: + return 55 /* BarBarToken */; + case 51 /* CaretToken */: + case 71 /* CaretEqualsToken */: + return 36 /* ExclamationEqualsEqualsToken */; + case 49 /* AmpersandToken */: + case 69 /* AmpersandEqualsToken */: + return 54 /* AmpersandAmpersandToken */; + default: + return undefined; + } + } + function checkAssignmentOperator(valueType) { + if (produceDiagnostics && ts.isAssignmentOperator(operator)) { + // TypeScript 1.0 spec (April 2014): 4.17 + // An assignment of the form + // VarExpr = ValueExpr + // requires VarExpr to be classified as a reference + // A compound assignment furthermore requires VarExpr to be classified as a reference (section 4.1) + // and the type of the non-compound operation to be assignable to the type of VarExpr. + if (checkReferenceExpression(left, ts.Diagnostics.The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access) + && (!ts.isIdentifier(left) || ts.unescapeLeadingUnderscores(left.escapedText) !== "exports")) { + // to avoid cascading errors check assignability only if 'isReference' check succeeded and no errors were reported + checkTypeAssignableToAndOptionallyElaborate(valueType, leftType, left, right); + } + } + } + function isAssignmentDeclaration(kind) { + switch (kind) { + case 2 /* ModuleExports */: + return true; + case 1 /* ExportsProperty */: + case 5 /* Property */: + case 6 /* Prototype */: + case 3 /* PrototypeProperty */: + case 4 /* ThisProperty */: + var symbol = getSymbolOfNode(left); + var init = ts.getAssignedExpandoInitializer(right); + return init && ts.isObjectLiteralExpression(init) && + symbol && ts.hasEntries(symbol.exports); + default: + return false; + } + } + function reportOperatorError() { + var leftStr = typeToString(leftType); + var rightStr = typeToString(rightType); + var errNode = errorNode || operatorToken; + if (!tryGiveBetterPrimaryError(errNode, leftStr, rightStr)) { + error(errNode, ts.Diagnostics.Operator_0_cannot_be_applied_to_types_1_and_2, ts.tokenToString(operatorToken.kind), leftStr, rightStr); + } + } + function tryGiveBetterPrimaryError(errNode, leftStr, rightStr) { + switch (operatorToken.kind) { + case 35 /* EqualsEqualsEqualsToken */: + case 33 /* EqualsEqualsToken */: + return error(errNode, ts.Diagnostics.This_condition_will_always_return_0_since_the_types_1_and_2_have_no_overlap, "false", leftStr, rightStr); + case 36 /* ExclamationEqualsEqualsToken */: + case 34 /* ExclamationEqualsToken */: + return error(errNode, ts.Diagnostics.This_condition_will_always_return_0_since_the_types_1_and_2_have_no_overlap, "true", leftStr, rightStr); + } + return undefined; + } + } + function isYieldExpressionInClass(node) { + var current = node; + var parent = node.parent; + while (parent) { + if (ts.isFunctionLike(parent) && current === parent.body) { + return false; + } + else if (ts.isClassLike(current)) { + return true; + } + current = parent; + parent = parent.parent; + } + return false; + } + function checkYieldExpression(node) { + // Grammar checking + if (produceDiagnostics) { + if (!(node.flags & 4096 /* YieldContext */) || isYieldExpressionInClass(node)) { + grammarErrorOnFirstToken(node, ts.Diagnostics.A_yield_expression_is_only_allowed_in_a_generator_body); + } + if (isInParameterInitializerBeforeContainingFunction(node)) { + error(node, ts.Diagnostics.yield_expressions_cannot_be_used_in_a_parameter_initializer); + } + } + var func = ts.getContainingFunction(node); + if (!func) + return anyType; + var functionFlags = ts.getFunctionFlags(func); + if (!(functionFlags & 1 /* Generator */)) { + // If the user's code is syntactically correct, the func should always have a star. After all, we are in a yield context. + return anyType; + } + if (node.asteriskToken) { + // Async generator functions prior to ESNext require the __await, __asyncDelegator, + // and __asyncValues helpers + if ((functionFlags & 3 /* AsyncGenerator */) === 3 /* AsyncGenerator */ && + languageVersion < 6 /* ESNext */) { + checkExternalEmitHelpers(node, 26624 /* AsyncDelegatorIncludes */); + } + // Generator functions prior to ES2015 require the __values helper + if ((functionFlags & 3 /* AsyncGenerator */) === 1 /* Generator */ && + languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) { + checkExternalEmitHelpers(node, 256 /* Values */); + } + } + var isAsync = (functionFlags & 2 /* Async */) !== 0; + var yieldedType = getYieldedTypeOfYieldExpression(node, isAsync); // TODO: GH#18217 + // There is no point in doing an assignability check if the function + // has no explicit return type because the return type is directly computed + // from the yield expressions. + var returnType = getReturnTypeFromAnnotation(func); + if (returnType) { + var signatureElementType = getIteratedTypeOfGenerator(returnType, isAsync) || anyType; + checkTypeAssignableToAndOptionallyElaborate(yieldedType, signatureElementType, node.expression || node, node.expression); + } + // Both yield and yield* expressions have type 'any' + return anyType; + } + function checkConditionalExpression(node, checkMode) { + checkTruthinessExpression(node.condition); + var type1 = checkExpression(node.whenTrue, checkMode); + var type2 = checkExpression(node.whenFalse, checkMode); + return getUnionType([type1, type2], 2 /* Subtype */); + } + function checkTemplateExpression(node) { + // We just want to check each expressions, but we are unconcerned with + // the type of each expression, as any value may be coerced into a string. + // It is worth asking whether this is what we really want though. + // A place where we actually *are* concerned with the expressions' types are + // in tagged templates. + ts.forEach(node.templateSpans, function (templateSpan) { + if (maybeTypeOfKind(checkExpression(templateSpan.expression), 12288 /* ESSymbolLike */)) { + error(templateSpan.expression, ts.Diagnostics.Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_in_String); + } + }); + return stringType; + } + function getContextNode(node) { + if (node.kind === 268 /* JsxAttributes */ && !ts.isJsxSelfClosingElement(node.parent)) { + return node.parent.parent; // Needs to be the root JsxElement, so it encompasses the attributes _and_ the children (which are essentially part of the attributes) + } + return node; + } + function checkExpressionWithContextualType(node, contextualType, contextualMapper) { + var context = getContextNode(node); + var saveContextualType = context.contextualType; + var saveContextualMapper = context.contextualMapper; + context.contextualType = contextualType; + context.contextualMapper = contextualMapper; + var checkMode = contextualMapper === identityMapper ? 1 /* SkipContextSensitive */ : + contextualMapper ? 2 /* Inferential */ : 3 /* Contextual */; + var result = checkExpression(node, checkMode); + context.contextualType = saveContextualType; + context.contextualMapper = saveContextualMapper; + return result; + } + function checkExpressionCached(node, checkMode) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + if (checkMode) { + return checkExpression(node, checkMode); + } + // When computing a type that we're going to cache, we need to ignore any ongoing control flow + // analysis because variables may have transient types in indeterminable states. Moving flowLoopStart + // to the top of the stack ensures all transient types are computed from a known point. + var saveFlowLoopStart = flowLoopStart; + flowLoopStart = flowLoopCount; + links.resolvedType = checkExpression(node, checkMode); + flowLoopStart = saveFlowLoopStart; + } + return links.resolvedType; + } + function isTypeAssertion(node) { + node = ts.skipParentheses(node); + return node.kind === 194 /* TypeAssertionExpression */ || node.kind === 212 /* AsExpression */; + } + function checkDeclarationInitializer(declaration) { + var initializer = ts.getEffectiveInitializer(declaration); + var type = getTypeOfExpression(initializer, /*cache*/ true); + var widened = ts.getCombinedNodeFlags(declaration) & 2 /* Const */ || + ts.isDeclarationReadonly(declaration) || + isTypeAssertion(initializer) ? type : getWidenedLiteralType(type); + if (ts.isInJSFile(declaration)) { + if (widened.flags & 98304 /* Nullable */) { + reportImplicitAny(declaration, anyType); + return anyType; + } + else if (isEmptyArrayLiteralType(widened)) { + reportImplicitAny(declaration, anyArrayType); + return anyArrayType; + } + } + return widened; + } + function isLiteralOfContextualType(candidateType, contextualType) { + if (contextualType) { + if (contextualType.flags & 3145728 /* UnionOrIntersection */) { + var types = contextualType.types; + return ts.some(types, function (t) { return isLiteralOfContextualType(candidateType, t); }); + } + if (contextualType.flags & 58982400 /* InstantiableNonPrimitive */) { + // If the contextual type is a type variable constrained to a primitive type, consider + // this a literal context for literals of that primitive type. For example, given a + // type parameter 'T extends string', infer string literal types for T. + var constraint = getBaseConstraintOfType(contextualType) || emptyObjectType; + return maybeTypeOfKind(constraint, 4 /* String */) && maybeTypeOfKind(candidateType, 128 /* StringLiteral */) || + maybeTypeOfKind(constraint, 8 /* Number */) && maybeTypeOfKind(candidateType, 256 /* NumberLiteral */) || + maybeTypeOfKind(constraint, 64 /* BigInt */) && maybeTypeOfKind(candidateType, 2048 /* BigIntLiteral */) || + maybeTypeOfKind(constraint, 4096 /* ESSymbol */) && maybeTypeOfKind(candidateType, 8192 /* UniqueESSymbol */) || + isLiteralOfContextualType(candidateType, constraint); + } + // If the contextual type is a literal of a particular primitive type, we consider this a + // literal context for all literals of that primitive type. + return !!(contextualType.flags & (128 /* StringLiteral */ | 4194304 /* Index */) && maybeTypeOfKind(candidateType, 128 /* StringLiteral */) || + contextualType.flags & 256 /* NumberLiteral */ && maybeTypeOfKind(candidateType, 256 /* NumberLiteral */) || + contextualType.flags & 2048 /* BigIntLiteral */ && maybeTypeOfKind(candidateType, 2048 /* BigIntLiteral */) || + contextualType.flags & 512 /* BooleanLiteral */ && maybeTypeOfKind(candidateType, 512 /* BooleanLiteral */) || + contextualType.flags & 8192 /* UniqueESSymbol */ && maybeTypeOfKind(candidateType, 8192 /* UniqueESSymbol */)); + } + return false; + } + function checkExpressionForMutableLocation(node, checkMode, contextualType, forceTuple) { + if (arguments.length === 2) { + contextualType = getContextualType(node); + } + var type = checkExpression(node, checkMode, forceTuple); + return isTypeAssertion(node) ? type : + getWidenedLiteralLikeTypeForContextualType(type, contextualType); + } + function checkPropertyAssignment(node, checkMode) { + // Do not use hasDynamicName here, because that returns false for well known symbols. + // We want to perform checkComputedPropertyName for all computed properties, including + // well known symbols. + if (node.name.kind === 149 /* ComputedPropertyName */) { + checkComputedPropertyName(node.name); + } + return checkExpressionForMutableLocation(node.initializer, checkMode); + } + function checkObjectLiteralMethod(node, checkMode) { + // Grammar checking + checkGrammarMethod(node); + // Do not use hasDynamicName here, because that returns false for well known symbols. + // We want to perform checkComputedPropertyName for all computed properties, including + // well known symbols. + if (node.name.kind === 149 /* ComputedPropertyName */) { + checkComputedPropertyName(node.name); + } + var uninstantiatedType = checkFunctionExpressionOrObjectLiteralMethod(node, checkMode); + return instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode); + } + function instantiateTypeWithSingleGenericCallSignature(node, type, checkMode) { + if (checkMode === 2 /* Inferential */) { + var signature = getSingleCallSignature(type); + if (signature && signature.typeParameters) { + var contextualType = getApparentTypeOfContextualType(node); + if (contextualType) { + var contextualSignature = getSingleCallSignature(getNonNullableType(contextualType)); + if (contextualSignature && !contextualSignature.typeParameters) { + return getOrCreateTypeFromSignature(instantiateSignatureInContextOf(signature, contextualSignature, getContextualMapper(node))); + } + } + } + } + return type; + } + /** + * Returns the type of an expression. Unlike checkExpression, this function is simply concerned + * with computing the type and may not fully check all contained sub-expressions for errors. + * A cache argument of true indicates that if the function performs a full type check, it is ok + * to cache the result. + */ + function getTypeOfExpression(node, cache) { + var expr = ts.skipParentheses(node); + // Optimize for the common case of a call to a function with a single non-generic call + // signature where we can just fetch the return type without checking the arguments. + if (expr.kind === 191 /* CallExpression */ && expr.expression.kind !== 98 /* SuperKeyword */ && !ts.isRequireCall(expr, /*checkArgumentIsStringLiteralLike*/ true) && !isSymbolOrSymbolForCall(expr)) { + var funcType = checkNonNullExpression(expr.expression); + var signature = getSingleCallSignature(funcType); + if (signature && !signature.typeParameters) { + return getReturnTypeOfSignature(signature); + } + } + else if (expr.kind === 194 /* TypeAssertionExpression */ || expr.kind === 212 /* AsExpression */) { + return getTypeFromTypeNode(expr.type); + } + // Otherwise simply call checkExpression. Ideally, the entire family of checkXXX functions + // should have a parameter that indicates whether full error checking is required such that + // we can perform the optimizations locally. + return cache ? checkExpressionCached(node) : checkExpression(node); + } + /** + * Returns the type of an expression. Unlike checkExpression, this function is simply concerned + * with computing the type and may not fully check all contained sub-expressions for errors. + * It is intended for uses where you know there is no contextual type, + * and requesting the contextual type might cause a circularity or other bad behaviour. + * It sets the contextual type of the node to any before calling getTypeOfExpression. + */ + function getContextFreeTypeOfExpression(node) { + var links = getNodeLinks(node); + if (links.contextFreeType) { + return links.contextFreeType; + } + var saveContextualType = node.contextualType; + node.contextualType = anyType; + var type = links.contextFreeType = checkExpression(node, 1 /* SkipContextSensitive */); + node.contextualType = saveContextualType; + return type; + } + // Checks an expression and returns its type. The contextualMapper parameter serves two purposes: When + // contextualMapper is not undefined and not equal to the identityMapper function object it indicates that the + // expression is being inferentially typed (section 4.15.2 in spec) and provides the type mapper to use in + // conjunction with the generic contextual type. When contextualMapper is equal to the identityMapper function + // object, it serves as an indicator that all contained function and arrow expressions should be considered to + // have the wildcard function type; this form of type check is used during overload resolution to exclude + // contextually typed function and arrow expressions in the initial phase. + function checkExpression(node, checkMode, forceTuple) { + var type; + if (node.kind === 148 /* QualifiedName */) { + type = checkQualifiedName(node); + } + else { + var uninstantiatedType = checkExpressionWorker(node, checkMode, forceTuple); + type = instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode); + } + if (isConstEnumObjectType(type)) { + // enum object type for const enums are only permitted in: + // - 'left' in property access + // - 'object' in indexed access + // - target in rhs of import statement + var ok = (node.parent.kind === 189 /* PropertyAccessExpression */ && node.parent.expression === node) || + (node.parent.kind === 190 /* ElementAccessExpression */ && node.parent.expression === node) || + ((node.kind === 72 /* Identifier */ || node.kind === 148 /* QualifiedName */) && isInRightSideOfImportOrExportAssignment(node) || + (node.parent.kind === 167 /* TypeQuery */ && node.parent.exprName === node)); + if (!ok) { + error(node, ts.Diagnostics.const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment_or_type_query); + } + } + return type; + } + function checkParenthesizedExpression(node, checkMode) { + var tag = ts.isInJSFile(node) ? ts.getJSDocTypeTag(node) : undefined; + if (tag) { + return checkAssertionWorker(tag, tag.typeExpression.type, node.expression, checkMode); + } + return checkExpression(node.expression, checkMode); + } + function checkExpressionWorker(node, checkMode, forceTuple) { + switch (node.kind) { + case 72 /* Identifier */: + return checkIdentifier(node); + case 100 /* ThisKeyword */: + return checkThisExpression(node); + case 98 /* SuperKeyword */: + return checkSuperExpression(node); + case 96 /* NullKeyword */: + return nullWideningType; + case 14 /* NoSubstitutionTemplateLiteral */: + case 10 /* StringLiteral */: + return getFreshTypeOfLiteralType(getLiteralType(node.text)); + case 8 /* NumericLiteral */: + checkGrammarNumericLiteral(node); + return getFreshTypeOfLiteralType(getLiteralType(+node.text)); + case 9 /* BigIntLiteral */: + checkGrammarBigIntLiteral(node); + return getFreshTypeOfLiteralType(getBigIntLiteralType(node)); + case 102 /* TrueKeyword */: + return trueType; + case 87 /* FalseKeyword */: + return falseType; + case 206 /* TemplateExpression */: + return checkTemplateExpression(node); + case 13 /* RegularExpressionLiteral */: + return globalRegExpType; + case 187 /* ArrayLiteralExpression */: + return checkArrayLiteral(node, checkMode, forceTuple); + case 188 /* ObjectLiteralExpression */: + return checkObjectLiteral(node, checkMode); + case 189 /* PropertyAccessExpression */: + return checkPropertyAccessExpression(node); + case 190 /* ElementAccessExpression */: + return checkIndexedAccess(node); + case 191 /* CallExpression */: + if (node.expression.kind === 92 /* ImportKeyword */) { + return checkImportCallExpression(node); + } + /* falls through */ + case 192 /* NewExpression */: + return checkCallExpression(node); + case 193 /* TaggedTemplateExpression */: + return checkTaggedTemplateExpression(node); + case 195 /* ParenthesizedExpression */: + return checkParenthesizedExpression(node, checkMode); + case 209 /* ClassExpression */: + return checkClassExpression(node); + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + return checkFunctionExpressionOrObjectLiteralMethod(node, checkMode); + case 199 /* TypeOfExpression */: + return checkTypeOfExpression(node); + case 194 /* TypeAssertionExpression */: + case 212 /* AsExpression */: + return checkAssertion(node); + case 213 /* NonNullExpression */: + return checkNonNullAssertion(node); + case 214 /* MetaProperty */: + return checkMetaProperty(node); + case 198 /* DeleteExpression */: + return checkDeleteExpression(node); + case 200 /* VoidExpression */: + return checkVoidExpression(node); + case 201 /* AwaitExpression */: + return checkAwaitExpression(node); + case 202 /* PrefixUnaryExpression */: + return checkPrefixUnaryExpression(node); + case 203 /* PostfixUnaryExpression */: + return checkPostfixUnaryExpression(node); + case 204 /* BinaryExpression */: + return checkBinaryExpression(node, checkMode); + case 205 /* ConditionalExpression */: + return checkConditionalExpression(node, checkMode); + case 208 /* SpreadElement */: + return checkSpreadExpression(node, checkMode); + case 210 /* OmittedExpression */: + return undefinedWideningType; + case 207 /* YieldExpression */: + return checkYieldExpression(node); + case 215 /* SyntheticExpression */: + return node.type; + case 270 /* JsxExpression */: + return checkJsxExpression(node, checkMode); + case 260 /* JsxElement */: + return checkJsxElement(node, checkMode); + case 261 /* JsxSelfClosingElement */: + return checkJsxSelfClosingElement(node, checkMode); + case 264 /* JsxFragment */: + return checkJsxFragment(node); + case 268 /* JsxAttributes */: + return checkJsxAttributes(node, checkMode); + case 262 /* JsxOpeningElement */: + ts.Debug.fail("Shouldn't ever directly check a JsxOpeningElement"); + } + return errorType; + } + // DECLARATION AND STATEMENT TYPE CHECKING + function checkTypeParameter(node) { + // Grammar Checking + if (node.expression) { + grammarErrorOnFirstToken(node.expression, ts.Diagnostics.Type_expected); + } + checkSourceElement(node.constraint); + checkSourceElement(node.default); + var typeParameter = getDeclaredTypeOfTypeParameter(getSymbolOfNode(node)); + if (!hasNonCircularBaseConstraint(typeParameter)) { + error(ts.getEffectiveConstraintOfTypeParameter(node), ts.Diagnostics.Type_parameter_0_has_a_circular_constraint, typeToString(typeParameter)); + } + if (!hasNonCircularTypeParameterDefault(typeParameter)) { + error(node.default, ts.Diagnostics.Type_parameter_0_has_a_circular_default, typeToString(typeParameter)); + } + var constraintType = getConstraintOfTypeParameter(typeParameter); + var defaultType = getDefaultFromTypeParameter(typeParameter); + if (constraintType && defaultType) { + checkTypeAssignableTo(defaultType, getTypeWithThisArgument(constraintType, defaultType), node.default, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); + } + if (produceDiagnostics) { + checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_parameter_name_cannot_be_0); + } + } + function checkParameter(node) { + // Grammar checking + // It is a SyntaxError if the Identifier "eval" or the Identifier "arguments" occurs as the + // Identifier in a PropertySetParameterList of a PropertyAssignment that is contained in strict code + // or if its FunctionBody is strict code(11.1.5). + checkGrammarDecoratorsAndModifiers(node); + checkVariableLikeDeclaration(node); + var func = ts.getContainingFunction(node); + if (ts.hasModifier(node, 92 /* ParameterPropertyModifier */)) { + if (!(func.kind === 157 /* Constructor */ && ts.nodeIsPresent(func.body))) { + error(node, ts.Diagnostics.A_parameter_property_is_only_allowed_in_a_constructor_implementation); + } + } + if (node.questionToken && ts.isBindingPattern(node.name) && func.body) { + error(node, ts.Diagnostics.A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature); + } + if (node.name && ts.isIdentifier(node.name) && (node.name.escapedText === "this" || node.name.escapedText === "new")) { + if (func.parameters.indexOf(node) !== 0) { + error(node, ts.Diagnostics.A_0_parameter_must_be_the_first_parameter, node.name.escapedText); + } + if (func.kind === 157 /* Constructor */ || func.kind === 161 /* ConstructSignature */ || func.kind === 166 /* ConstructorType */) { + error(node, ts.Diagnostics.A_constructor_cannot_have_a_this_parameter); + } + if (func.kind === 197 /* ArrowFunction */) { + error(node, ts.Diagnostics.An_arrow_function_cannot_have_a_this_parameter); + } + } + // Only check rest parameter type if it's not a binding pattern. Since binding patterns are + // not allowed in a rest parameter, we already have an error from checkGrammarParameterList. + if (node.dotDotDotToken && !ts.isBindingPattern(node.name) && !isTypeAssignableTo(getTypeOfSymbol(node.symbol), anyArrayType)) { + error(node, ts.Diagnostics.A_rest_parameter_must_be_of_an_array_type); + } + } + function checkTypePredicate(node) { + var parent = getTypePredicateParent(node); + if (!parent) { + // The parent must not be valid. + error(node, ts.Diagnostics.A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods); + return; + } + var typePredicate = getTypePredicateOfSignature(getSignatureFromDeclaration(parent)); + if (!typePredicate) { + return; + } + checkSourceElement(node.type); + var parameterName = node.parameterName; + if (ts.isThisTypePredicate(typePredicate)) { + getTypeFromThisTypeNode(parameterName); + } + else { + if (typePredicate.parameterIndex >= 0) { + if (parent.parameters[typePredicate.parameterIndex].dotDotDotToken) { + error(parameterName, ts.Diagnostics.A_type_predicate_cannot_reference_a_rest_parameter); + } + else { + var leadingError = function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type); }; + checkTypeAssignableTo(typePredicate.type, getTypeOfNode(parent.parameters[typePredicate.parameterIndex]), node.type, + /*headMessage*/ undefined, leadingError); + } + } + else if (parameterName) { + var hasReportedError = false; + for (var _i = 0, _a = parent.parameters; _i < _a.length; _i++) { + var name = _a[_i].name; + if (ts.isBindingPattern(name) && + checkIfTypePredicateVariableIsDeclaredInBindingPattern(name, parameterName, typePredicate.parameterName)) { + hasReportedError = true; + break; + } + } + if (!hasReportedError) { + error(node.parameterName, ts.Diagnostics.Cannot_find_parameter_0, typePredicate.parameterName); + } + } + } + } + function getTypePredicateParent(node) { + switch (node.parent.kind) { + case 197 /* ArrowFunction */: + case 160 /* CallSignature */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 165 /* FunctionType */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + var parent = node.parent; + if (node === parent.type) { + return parent; + } + } + } + function checkIfTypePredicateVariableIsDeclaredInBindingPattern(pattern, predicateVariableNode, predicateVariableName) { + for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (ts.isOmittedExpression(element)) { + continue; + } + var name = element.name; + if (name.kind === 72 /* Identifier */ && name.escapedText === predicateVariableName) { + error(predicateVariableNode, ts.Diagnostics.A_type_predicate_cannot_reference_element_0_in_a_binding_pattern, predicateVariableName); + return true; + } + else if (name.kind === 185 /* ArrayBindingPattern */ || name.kind === 184 /* ObjectBindingPattern */) { + if (checkIfTypePredicateVariableIsDeclaredInBindingPattern(name, predicateVariableNode, predicateVariableName)) { + return true; + } + } + } + } + function checkSignatureDeclaration(node) { + // Grammar checking + if (node.kind === 162 /* IndexSignature */) { + checkGrammarIndexSignature(node); + } + // TODO (yuisu): Remove this check in else-if when SyntaxKind.Construct is moved and ambient context is handled + else if (node.kind === 165 /* FunctionType */ || node.kind === 239 /* FunctionDeclaration */ || node.kind === 166 /* ConstructorType */ || + node.kind === 160 /* CallSignature */ || node.kind === 157 /* Constructor */ || + node.kind === 161 /* ConstructSignature */) { + checkGrammarFunctionLikeDeclaration(node); + } + var functionFlags = ts.getFunctionFlags(node); + if (!(functionFlags & 4 /* Invalid */)) { + // Async generators prior to ESNext require the __await and __asyncGenerator helpers + if ((functionFlags & 3 /* AsyncGenerator */) === 3 /* AsyncGenerator */ && languageVersion < 6 /* ESNext */) { + checkExternalEmitHelpers(node, 6144 /* AsyncGeneratorIncludes */); + } + // Async functions prior to ES2017 require the __awaiter helper + if ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */ && languageVersion < 4 /* ES2017 */) { + checkExternalEmitHelpers(node, 64 /* Awaiter */); + } + // Generator functions, Async functions, and Async Generator functions prior to + // ES2015 require the __generator helper + if ((functionFlags & 3 /* AsyncGenerator */) !== 0 /* Normal */ && languageVersion < 2 /* ES2015 */) { + checkExternalEmitHelpers(node, 128 /* Generator */); + } + } + checkTypeParameters(node.typeParameters); + ts.forEach(node.parameters, checkParameter); + // TODO(rbuckton): Should we start checking JSDoc types? + if (node.type) { + checkSourceElement(node.type); + } + if (produceDiagnostics) { + checkCollisionWithArgumentsInGeneratedCode(node); + var returnTypeNode = ts.getEffectiveReturnTypeNode(node); + if (noImplicitAny && !returnTypeNode) { + switch (node.kind) { + case 161 /* ConstructSignature */: + error(node, ts.Diagnostics.Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type); + break; + case 160 /* CallSignature */: + error(node, ts.Diagnostics.Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type); + break; + } + } + if (returnTypeNode) { + var functionFlags_1 = ts.getFunctionFlags(node); + if ((functionFlags_1 & (4 /* Invalid */ | 1 /* Generator */)) === 1 /* Generator */) { + var returnType = getTypeFromTypeNode(returnTypeNode); + if (returnType === voidType) { + error(returnTypeNode, ts.Diagnostics.A_generator_cannot_have_a_void_type_annotation); + } + else { + var generatorElementType = getIteratedTypeOfGenerator(returnType, (functionFlags_1 & 2 /* Async */) !== 0) || anyType; + var iterableIteratorInstantiation = functionFlags_1 & 2 /* Async */ + ? createAsyncIterableIteratorType(generatorElementType) // AsyncGenerator function + : createIterableIteratorType(generatorElementType); // Generator function + // Naively, one could check that IterableIterator is assignable to the return type annotation. + // However, that would not catch the error in the following case. + // + // interface BadGenerator extends Iterable, Iterator { } + // function* g(): BadGenerator { } // Iterable and Iterator have different types! + // + checkTypeAssignableTo(iterableIteratorInstantiation, returnType, returnTypeNode); + } + } + else if ((functionFlags_1 & 3 /* AsyncGenerator */) === 2 /* Async */) { + checkAsyncFunctionReturnType(node, returnTypeNode); + } + } + if (node.kind !== 162 /* IndexSignature */ && node.kind !== 289 /* JSDocFunctionType */) { + registerForUnusedIdentifiersCheck(node); + } + } + } + function checkClassForDuplicateDeclarations(node) { + var Declaration; + (function (Declaration) { + Declaration[Declaration["Getter"] = 1] = "Getter"; + Declaration[Declaration["Setter"] = 2] = "Setter"; + Declaration[Declaration["Method"] = 4] = "Method"; + Declaration[Declaration["Property"] = 3] = "Property"; + })(Declaration || (Declaration = {})); + var instanceNames = ts.createUnderscoreEscapedMap(); + var staticNames = ts.createUnderscoreEscapedMap(); + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + if (member.kind === 157 /* Constructor */) { + for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { + var param = _c[_b]; + if (ts.isParameterPropertyDeclaration(param) && !ts.isBindingPattern(param.name)) { + addName(instanceNames, param.name, param.name.escapedText, 3 /* Property */); + } + } + } + else { + var isStatic = ts.hasModifier(member, 32 /* Static */); + var names = isStatic ? staticNames : instanceNames; + var name = member.name; + var memberName = name && ts.getPropertyNameForPropertyNameNode(name); + if (name && memberName) { + switch (member.kind) { + case 158 /* GetAccessor */: + addName(names, name, memberName, 1 /* Getter */); + break; + case 159 /* SetAccessor */: + addName(names, name, memberName, 2 /* Setter */); + break; + case 154 /* PropertyDeclaration */: + addName(names, name, memberName, 3 /* Property */); + break; + case 156 /* MethodDeclaration */: + addName(names, name, memberName, 4 /* Method */); + break; + } + } + } + } + function addName(names, location, name, meaning) { + var prev = names.get(name); + if (prev) { + if (prev & 4 /* Method */) { + if (meaning !== 4 /* Method */) { + error(location, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(location)); + } + } + else if (prev & meaning) { + error(location, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(location)); + } + else { + names.set(name, prev | meaning); + } + } + else { + names.set(name, meaning); + } + } + } + /** + * Static members being set on a constructor function may conflict with built-in properties + * of Function. Esp. in ECMAScript 5 there are non-configurable and non-writable + * built-in properties. This check issues a transpile error when a class has a static + * member with the same name as a non-writable built-in property. + * + * @see http://www.ecma-international.org/ecma-262/5.1/#sec-15.3.3 + * @see http://www.ecma-international.org/ecma-262/5.1/#sec-15.3.5 + * @see http://www.ecma-international.org/ecma-262/6.0/#sec-properties-of-the-function-constructor + * @see http://www.ecma-international.org/ecma-262/6.0/#sec-function-instances + */ + function checkClassForStaticPropertyNameConflicts(node) { + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + var memberNameNode = member.name; + var isStatic = ts.hasModifier(member, 32 /* Static */); + if (isStatic && memberNameNode) { + var memberName = ts.getPropertyNameForPropertyNameNode(memberNameNode); + switch (memberName) { + case "name": + case "length": + case "caller": + case "arguments": + case "prototype": + var message = ts.Diagnostics.Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1; + var className = getNameOfSymbolAsWritten(getSymbolOfNode(node)); + error(memberNameNode, message, memberName, className); + break; + } + } + } + } + function checkObjectTypeForDuplicateDeclarations(node) { + var names = ts.createMap(); + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + if (member.kind === 153 /* PropertySignature */) { + var memberName = void 0; + var name = member.name; + switch (name.kind) { + case 10 /* StringLiteral */: + case 8 /* NumericLiteral */: + memberName = name.text; + break; + case 72 /* Identifier */: + memberName = ts.idText(name); + break; + default: + continue; + } + if (names.get(memberName)) { + error(ts.getNameOfDeclaration(member.symbol.valueDeclaration), ts.Diagnostics.Duplicate_identifier_0, memberName); + error(member.name, ts.Diagnostics.Duplicate_identifier_0, memberName); + } + else { + names.set(memberName, true); + } + } + } + } + function checkTypeForDuplicateIndexSignatures(node) { + if (node.kind === 241 /* InterfaceDeclaration */) { + var nodeSymbol = getSymbolOfNode(node); + // in case of merging interface declaration it is possible that we'll enter this check procedure several times for every declaration + // to prevent this run check only for the first declaration of a given kind + if (nodeSymbol.declarations.length > 0 && nodeSymbol.declarations[0] !== node) { + return; + } + } + // TypeScript 1.0 spec (April 2014) + // 3.7.4: An object type can contain at most one string index signature and one numeric index signature. + // 8.5: A class declaration can have at most one string index member declaration and one numeric index member declaration + var indexSymbol = getIndexSymbol(getSymbolOfNode(node)); + if (indexSymbol) { + var seenNumericIndexer = false; + var seenStringIndexer = false; + for (var _i = 0, _a = indexSymbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + var declaration = decl; + if (declaration.parameters.length === 1 && declaration.parameters[0].type) { + switch (declaration.parameters[0].type.kind) { + case 138 /* StringKeyword */: + if (!seenStringIndexer) { + seenStringIndexer = true; + } + else { + error(declaration, ts.Diagnostics.Duplicate_string_index_signature); + } + break; + case 135 /* NumberKeyword */: + if (!seenNumericIndexer) { + seenNumericIndexer = true; + } + else { + error(declaration, ts.Diagnostics.Duplicate_number_index_signature); + } + break; + } + } + } + } + } + function checkPropertyDeclaration(node) { + // Grammar checking + if (!checkGrammarDecoratorsAndModifiers(node) && !checkGrammarProperty(node)) + checkGrammarComputedPropertyName(node.name); + checkVariableLikeDeclaration(node); + } + function checkMethodDeclaration(node) { + // Grammar checking + if (!checkGrammarMethod(node)) + checkGrammarComputedPropertyName(node.name); + // Grammar checking for modifiers is done inside the function checkGrammarFunctionLikeDeclaration + checkFunctionOrMethodDeclaration(node); + // Abstract methods cannot have an implementation. + // Extra checks are to avoid reporting multiple errors relating to the "abstractness" of the node. + if (ts.hasModifier(node, 128 /* Abstract */) && node.kind === 156 /* MethodDeclaration */ && node.body) { + error(node, ts.Diagnostics.Method_0_cannot_have_an_implementation_because_it_is_marked_abstract, ts.declarationNameToString(node.name)); + } + } + function checkConstructorDeclaration(node) { + // Grammar check on signature of constructor and modifier of the constructor is done in checkSignatureDeclaration function. + checkSignatureDeclaration(node); + // Grammar check for checking only related to constructorDeclaration + if (!checkGrammarConstructorTypeParameters(node)) + checkGrammarConstructorTypeAnnotation(node); + checkSourceElement(node.body); + var symbol = getSymbolOfNode(node); + var firstDeclaration = ts.getDeclarationOfKind(symbol, node.kind); + // Only type check the symbol once + if (node === firstDeclaration) { + checkFunctionOrConstructorSymbol(symbol); + } + // exit early in the case of signature - super checks are not relevant to them + if (ts.nodeIsMissing(node.body)) { + return; + } + if (!produceDiagnostics) { + return; + } + function isInstancePropertyWithInitializer(n) { + return n.kind === 154 /* PropertyDeclaration */ && + !ts.hasModifier(n, 32 /* Static */) && + !!n.initializer; + } + // TS 1.0 spec (April 2014): 8.3.2 + // Constructors of classes with no extends clause may not contain super calls, whereas + // constructors of derived classes must contain at least one super call somewhere in their function body. + var containingClassDecl = node.parent; + if (ts.getEffectiveBaseTypeNode(containingClassDecl)) { + captureLexicalThis(node.parent, containingClassDecl); + var classExtendsNull = classDeclarationExtendsNull(containingClassDecl); + var superCall = getSuperCallInConstructor(node); + if (superCall) { + if (classExtendsNull) { + error(superCall, ts.Diagnostics.A_constructor_cannot_contain_a_super_call_when_its_class_extends_null); + } + // The first statement in the body of a constructor (excluding prologue directives) must be a super call + // if both of the following are true: + // - The containing class is a derived class. + // - The constructor declares parameter properties + // or the containing class declares instance member variables with initializers. + var superCallShouldBeFirst = ts.some(node.parent.members, isInstancePropertyWithInitializer) || + ts.some(node.parameters, function (p) { return ts.hasModifier(p, 92 /* ParameterPropertyModifier */); }); + // Skip past any prologue directives to find the first statement + // to ensure that it was a super call. + if (superCallShouldBeFirst) { + var statements = node.body.statements; + var superCallStatement = void 0; + for (var _i = 0, statements_2 = statements; _i < statements_2.length; _i++) { + var statement = statements_2[_i]; + if (statement.kind === 221 /* ExpressionStatement */ && ts.isSuperCall(statement.expression)) { + superCallStatement = statement; + break; + } + if (!ts.isPrologueDirective(statement)) { + break; + } + } + if (!superCallStatement) { + error(node, ts.Diagnostics.A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_properties_or_has_parameter_properties); + } + } + } + else if (!classExtendsNull) { + error(node, ts.Diagnostics.Constructors_for_derived_classes_must_contain_a_super_call); + } + } + } + function checkAccessorDeclaration(node) { + if (produceDiagnostics) { + // Grammar checking accessors + if (!checkGrammarFunctionLikeDeclaration(node) && !checkGrammarAccessor(node)) + checkGrammarComputedPropertyName(node.name); + checkDecorators(node); + checkSignatureDeclaration(node); + if (node.kind === 158 /* GetAccessor */) { + if (!(node.flags & 4194304 /* Ambient */) && ts.nodeIsPresent(node.body) && (node.flags & 128 /* HasImplicitReturn */)) { + if (!(node.flags & 256 /* HasExplicitReturn */)) { + error(node.name, ts.Diagnostics.A_get_accessor_must_return_a_value); + } + } + } + // Do not use hasDynamicName here, because that returns false for well known symbols. + // We want to perform checkComputedPropertyName for all computed properties, including + // well known symbols. + if (node.name.kind === 149 /* ComputedPropertyName */) { + checkComputedPropertyName(node.name); + } + if (!hasNonBindableDynamicName(node)) { + // TypeScript 1.0 spec (April 2014): 8.4.3 + // Accessors for the same member name must specify the same accessibility. + var otherKind = node.kind === 158 /* GetAccessor */ ? 159 /* SetAccessor */ : 158 /* GetAccessor */; + var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(node), otherKind); + if (otherAccessor) { + var nodeFlags = ts.getModifierFlags(node); + var otherFlags = ts.getModifierFlags(otherAccessor); + if ((nodeFlags & 28 /* AccessibilityModifier */) !== (otherFlags & 28 /* AccessibilityModifier */)) { + error(node.name, ts.Diagnostics.Getter_and_setter_accessors_do_not_agree_in_visibility); + } + if ((nodeFlags & 128 /* Abstract */) !== (otherFlags & 128 /* Abstract */)) { + error(node.name, ts.Diagnostics.Accessors_must_both_be_abstract_or_non_abstract); + } + // TypeScript 1.0 spec (April 2014): 4.5 + // If both accessors include type annotations, the specified types must be identical. + checkAccessorDeclarationTypesIdentical(node, otherAccessor, getAnnotatedAccessorType, ts.Diagnostics.get_and_set_accessor_must_have_the_same_type); + checkAccessorDeclarationTypesIdentical(node, otherAccessor, getThisTypeOfDeclaration, ts.Diagnostics.get_and_set_accessor_must_have_the_same_this_type); + } + } + var returnType = getTypeOfAccessors(getSymbolOfNode(node)); + if (node.kind === 158 /* GetAccessor */) { + checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnType); + } + } + checkSourceElement(node.body); + } + function checkAccessorDeclarationTypesIdentical(first, second, getAnnotatedType, message) { + var firstType = getAnnotatedType(first); + var secondType = getAnnotatedType(second); + if (firstType && secondType && !isTypeIdenticalTo(firstType, secondType)) { + error(first, message); + } + } + function checkMissingDeclaration(node) { + checkDecorators(node); + } + function getEffectiveTypeArguments(node, typeParameters) { + return fillMissingTypeArguments(ts.map(node.typeArguments, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJSFile(node)); + } + function checkTypeArgumentConstraints(node, typeParameters) { + var typeArguments; + var mapper; + var result = true; + for (var i = 0; i < typeParameters.length; i++) { + var constraint = getConstraintOfTypeParameter(typeParameters[i]); + if (constraint) { + if (!typeArguments) { + typeArguments = getEffectiveTypeArguments(node, typeParameters); + mapper = createTypeMapper(typeParameters, typeArguments); + } + result = result && checkTypeAssignableTo(typeArguments[i], instantiateType(constraint, mapper), node.typeArguments[i], ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); + } + } + return result; + } + function getTypeParametersForTypeReference(node) { + var type = getTypeFromTypeReference(node); + if (type !== errorType) { + var symbol = getNodeLinks(node).resolvedSymbol; + if (symbol) { + return symbol.flags & 524288 /* TypeAlias */ && getSymbolLinks(symbol).typeParameters || + (ts.getObjectFlags(type) & 4 /* Reference */ ? type.target.localTypeParameters : undefined); + } + } + return undefined; + } + function checkTypeReferenceNode(node) { + checkGrammarTypeArguments(node, node.typeArguments); + if (node.kind === 164 /* TypeReference */ && node.typeName.jsdocDotPos !== undefined && !ts.isInJSFile(node) && !ts.isInJSDoc(node)) { + grammarErrorAtPos(node, node.typeName.jsdocDotPos, 1, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments); + } + var type = getTypeFromTypeReference(node); + if (type !== errorType) { + if (node.typeArguments) { + // Do type argument local checks only if referenced type is successfully resolved + ts.forEach(node.typeArguments, checkSourceElement); + if (produceDiagnostics) { + var typeParameters = getTypeParametersForTypeReference(node); + if (typeParameters) { + checkTypeArgumentConstraints(node, typeParameters); + } + } + } + if (type.flags & 32 /* Enum */ && getNodeLinks(node).resolvedSymbol.flags & 8 /* EnumMember */) { + error(node, ts.Diagnostics.Enum_type_0_has_members_with_initializers_that_are_not_literals, typeToString(type)); + } + } + } + function getTypeArgumentConstraint(node) { + var typeReferenceNode = ts.tryCast(node.parent, ts.isTypeReferenceType); + if (!typeReferenceNode) + return undefined; + var typeParameters = getTypeParametersForTypeReference(typeReferenceNode); // TODO: GH#18217 + var constraint = getConstraintOfTypeParameter(typeParameters[typeReferenceNode.typeArguments.indexOf(node)]); + return constraint && instantiateType(constraint, createTypeMapper(typeParameters, getEffectiveTypeArguments(typeReferenceNode, typeParameters))); + } + function checkTypeQuery(node) { + getTypeFromTypeQueryNode(node); + } + function checkTypeLiteral(node) { + ts.forEach(node.members, checkSourceElement); + if (produceDiagnostics) { + var type = getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node); + checkIndexConstraints(type); + checkTypeForDuplicateIndexSignatures(node); + checkObjectTypeForDuplicateDeclarations(node); + } + } + function checkArrayType(node) { + checkSourceElement(node.elementType); + } + function checkTupleType(node) { + var elementTypes = node.elementTypes; + var seenOptionalElement = false; + for (var i = 0; i < elementTypes.length; i++) { + var e = elementTypes[i]; + if (e.kind === 172 /* RestType */) { + if (i !== elementTypes.length - 1) { + grammarErrorOnNode(e, ts.Diagnostics.A_rest_element_must_be_last_in_a_tuple_type); + break; + } + if (!isArrayType(getTypeFromTypeNode(e))) { + error(e, ts.Diagnostics.A_rest_element_type_must_be_an_array_type); + } + } + else if (e.kind === 171 /* OptionalType */) { + seenOptionalElement = true; + } + else if (seenOptionalElement) { + grammarErrorOnNode(e, ts.Diagnostics.A_required_element_cannot_follow_an_optional_element); + break; + } + } + checkGrammarForDisallowedTrailingComma(node.elementTypes); + ts.forEach(node.elementTypes, checkSourceElement); + } + function checkUnionOrIntersectionType(node) { + ts.forEach(node.types, checkSourceElement); + } + function checkIndexedAccessIndexType(type, accessNode) { + if (!(type.flags & 8388608 /* IndexedAccess */)) { + return type; + } + // Check if the index type is assignable to 'keyof T' for the object type. + var objectType = type.objectType; + var indexType = type.indexType; + if (isTypeAssignableTo(indexType, getIndexType(objectType, /*stringsOnly*/ false))) { + if (accessNode.kind === 190 /* ElementAccessExpression */ && ts.isAssignmentTarget(accessNode) && + ts.getObjectFlags(objectType) & 32 /* Mapped */ && getMappedTypeModifiers(objectType) & 1 /* IncludeReadonly */) { + error(accessNode, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(objectType)); + } + return type; + } + // Check if we're indexing with a numeric type and if either object or index types + // is a generic type with a constraint that has a numeric index signature. + if (getIndexInfoOfType(getApparentType(objectType), 1 /* Number */) && isTypeAssignableToKind(indexType, 296 /* NumberLike */)) { + return type; + } + error(accessNode, ts.Diagnostics.Type_0_cannot_be_used_to_index_type_1, typeToString(indexType), typeToString(objectType)); + return type; + } + function checkIndexedAccessType(node) { + checkSourceElement(node.objectType); + checkSourceElement(node.indexType); + checkIndexedAccessIndexType(getTypeFromIndexedAccessTypeNode(node), node); + } + function checkMappedType(node) { + checkSourceElement(node.typeParameter); + checkSourceElement(node.type); + if (!node.type) { + reportImplicitAny(node, anyType); + } + var type = getTypeFromMappedTypeNode(node); + var constraintType = getConstraintTypeFromMappedType(type); + checkTypeAssignableTo(constraintType, keyofConstraintType, ts.getEffectiveConstraintOfTypeParameter(node.typeParameter)); + } + function checkThisType(node) { + getTypeFromThisTypeNode(node); + } + function checkTypeOperator(node) { + checkGrammarTypeOperatorNode(node); + checkSourceElement(node.type); + } + function checkConditionalType(node) { + ts.forEachChild(node, checkSourceElement); + } + function checkInferType(node) { + if (!ts.findAncestor(node, function (n) { return n.parent && n.parent.kind === 175 /* ConditionalType */ && n.parent.extendsType === n; })) { + grammarErrorOnNode(node, ts.Diagnostics.infer_declarations_are_only_permitted_in_the_extends_clause_of_a_conditional_type); + } + checkSourceElement(node.typeParameter); + registerForUnusedIdentifiersCheck(node); + } + function checkImportType(node) { + checkSourceElement(node.argument); + getTypeFromTypeNode(node); + } + function isPrivateWithinAmbient(node) { + return ts.hasModifier(node, 8 /* Private */) && !!(node.flags & 4194304 /* Ambient */); + } + function getEffectiveDeclarationFlags(n, flagsToCheck) { + var flags = ts.getCombinedModifierFlags(n); + // children of classes (even ambient classes) should not be marked as ambient or export + // because those flags have no useful semantics there. + if (n.parent.kind !== 241 /* InterfaceDeclaration */ && + n.parent.kind !== 240 /* ClassDeclaration */ && + n.parent.kind !== 209 /* ClassExpression */ && + n.flags & 4194304 /* Ambient */) { + if (!(flags & 2 /* Ambient */) && !(ts.isModuleBlock(n.parent) && ts.isModuleDeclaration(n.parent.parent) && ts.isGlobalScopeAugmentation(n.parent.parent))) { + // It is nested in an ambient context, which means it is automatically exported + flags |= 1 /* Export */; + } + flags |= 2 /* Ambient */; + } + return flags & flagsToCheck; + } + function checkFunctionOrConstructorSymbol(symbol) { + if (!produceDiagnostics) { + return; + } + function getCanonicalOverload(overloads, implementation) { + // Consider the canonical set of flags to be the flags of the bodyDeclaration or the first declaration + // Error on all deviations from this canonical set of flags + // The caveat is that if some overloads are defined in lib.d.ts, we don't want to + // report the errors on those. To achieve this, we will say that the implementation is + // the canonical signature only if it is in the same container as the first overload + var implementationSharesContainerWithFirstOverload = implementation !== undefined && implementation.parent === overloads[0].parent; + return implementationSharesContainerWithFirstOverload ? implementation : overloads[0]; + } + function checkFlagAgreementBetweenOverloads(overloads, implementation, flagsToCheck, someOverloadFlags, allOverloadFlags) { + // Error if some overloads have a flag that is not shared by all overloads. To find the + // deviations, we XOR someOverloadFlags with allOverloadFlags + var someButNotAllOverloadFlags = someOverloadFlags ^ allOverloadFlags; + if (someButNotAllOverloadFlags !== 0) { + var canonicalFlags_1 = getEffectiveDeclarationFlags(getCanonicalOverload(overloads, implementation), flagsToCheck); + ts.forEach(overloads, function (o) { + var deviation = getEffectiveDeclarationFlags(o, flagsToCheck) ^ canonicalFlags_1; + if (deviation & 1 /* Export */) { + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_exported_or_non_exported); + } + else if (deviation & 2 /* Ambient */) { + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_ambient_or_non_ambient); + } + else if (deviation & (8 /* Private */ | 16 /* Protected */)) { + error(ts.getNameOfDeclaration(o) || o, ts.Diagnostics.Overload_signatures_must_all_be_public_private_or_protected); + } + else if (deviation & 128 /* Abstract */) { + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_abstract_or_non_abstract); + } + }); + } + } + function checkQuestionTokenAgreementBetweenOverloads(overloads, implementation, someHaveQuestionToken, allHaveQuestionToken) { + if (someHaveQuestionToken !== allHaveQuestionToken) { + var canonicalHasQuestionToken_1 = ts.hasQuestionToken(getCanonicalOverload(overloads, implementation)); + ts.forEach(overloads, function (o) { + var deviation = ts.hasQuestionToken(o) !== canonicalHasQuestionToken_1; + if (deviation) { + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_optional_or_required); + } + }); + } + } + var flagsToCheck = 1 /* Export */ | 2 /* Ambient */ | 8 /* Private */ | 16 /* Protected */ | 128 /* Abstract */; + var someNodeFlags = 0 /* None */; + var allNodeFlags = flagsToCheck; + var someHaveQuestionToken = false; + var allHaveQuestionToken = true; + var hasOverloads = false; + var bodyDeclaration; + var lastSeenNonAmbientDeclaration; + var previousDeclaration; + var declarations = symbol.declarations; + var isConstructor = (symbol.flags & 16384 /* Constructor */) !== 0; + function reportImplementationExpectedError(node) { + if (node.name && ts.nodeIsMissing(node.name)) { + return; + } + var seen = false; + var subsequentNode = ts.forEachChild(node.parent, function (c) { + if (seen) { + return c; + } + else { + seen = c === node; + } + }); + // We may be here because of some extra nodes between overloads that could not be parsed into a valid node. + // In this case the subsequent node is not really consecutive (.pos !== node.end), and we must ignore it here. + if (subsequentNode && subsequentNode.pos === node.end) { + if (subsequentNode.kind === node.kind) { + var errorNode_1 = subsequentNode.name || subsequentNode; + // TODO: GH#17345: These are methods, so handle computed name case. (`Always allowing computed property names is *not* the correct behavior!) + var subsequentName = subsequentNode.name; + if (node.name && subsequentName && + (ts.isComputedPropertyName(node.name) && ts.isComputedPropertyName(subsequentName) || + !ts.isComputedPropertyName(node.name) && !ts.isComputedPropertyName(subsequentName) && ts.getEscapedTextOfIdentifierOrLiteral(node.name) === ts.getEscapedTextOfIdentifierOrLiteral(subsequentName))) { + var reportError = (node.kind === 156 /* MethodDeclaration */ || node.kind === 155 /* MethodSignature */) && + ts.hasModifier(node, 32 /* Static */) !== ts.hasModifier(subsequentNode, 32 /* Static */); + // we can get here in two cases + // 1. mixed static and instance class members + // 2. something with the same name was defined before the set of overloads that prevents them from merging + // here we'll report error only for the first case since for second we should already report error in binder + if (reportError) { + var diagnostic = ts.hasModifier(node, 32 /* Static */) ? ts.Diagnostics.Function_overload_must_be_static : ts.Diagnostics.Function_overload_must_not_be_static; + error(errorNode_1, diagnostic); + } + return; + } + else if (ts.nodeIsPresent(subsequentNode.body)) { + error(errorNode_1, ts.Diagnostics.Function_implementation_name_must_be_0, ts.declarationNameToString(node.name)); + return; + } + } + } + var errorNode = node.name || node; + if (isConstructor) { + error(errorNode, ts.Diagnostics.Constructor_implementation_is_missing); + } + else { + // Report different errors regarding non-consecutive blocks of declarations depending on whether + // the node in question is abstract. + if (ts.hasModifier(node, 128 /* Abstract */)) { + error(errorNode, ts.Diagnostics.All_declarations_of_an_abstract_method_must_be_consecutive); + } + else { + error(errorNode, ts.Diagnostics.Function_implementation_is_missing_or_not_immediately_following_the_declaration); + } + } + } + var duplicateFunctionDeclaration = false; + var multipleConstructorImplementation = false; + for (var _i = 0, declarations_4 = declarations; _i < declarations_4.length; _i++) { + var current = declarations_4[_i]; + var node = current; + var inAmbientContext = node.flags & 4194304 /* Ambient */; + var inAmbientContextOrInterface = node.parent.kind === 241 /* InterfaceDeclaration */ || node.parent.kind === 168 /* TypeLiteral */ || inAmbientContext; + if (inAmbientContextOrInterface) { + // check if declarations are consecutive only if they are non-ambient + // 1. ambient declarations can be interleaved + // i.e. this is legal + // declare function foo(); + // declare function bar(); + // declare function foo(); + // 2. mixing ambient and non-ambient declarations is a separate error that will be reported - do not want to report an extra one + previousDeclaration = undefined; + } + if (node.kind === 239 /* FunctionDeclaration */ || node.kind === 156 /* MethodDeclaration */ || node.kind === 155 /* MethodSignature */ || node.kind === 157 /* Constructor */) { + var currentNodeFlags = getEffectiveDeclarationFlags(node, flagsToCheck); + someNodeFlags |= currentNodeFlags; + allNodeFlags &= currentNodeFlags; + someHaveQuestionToken = someHaveQuestionToken || ts.hasQuestionToken(node); + allHaveQuestionToken = allHaveQuestionToken && ts.hasQuestionToken(node); + if (ts.nodeIsPresent(node.body) && bodyDeclaration) { + if (isConstructor) { + multipleConstructorImplementation = true; + } + else { + duplicateFunctionDeclaration = true; + } + } + else if (previousDeclaration && previousDeclaration.parent === node.parent && previousDeclaration.end !== node.pos) { + reportImplementationExpectedError(previousDeclaration); + } + if (ts.nodeIsPresent(node.body)) { + if (!bodyDeclaration) { + bodyDeclaration = node; + } + } + else { + hasOverloads = true; + } + previousDeclaration = node; + if (!inAmbientContextOrInterface) { + lastSeenNonAmbientDeclaration = node; + } + } + } + if (multipleConstructorImplementation) { + ts.forEach(declarations, function (declaration) { + error(declaration, ts.Diagnostics.Multiple_constructor_implementations_are_not_allowed); + }); + } + if (duplicateFunctionDeclaration) { + ts.forEach(declarations, function (declaration) { + error(ts.getNameOfDeclaration(declaration), ts.Diagnostics.Duplicate_function_implementation); + }); + } + // Abstract methods can't have an implementation -- in particular, they don't need one. + if (lastSeenNonAmbientDeclaration && !lastSeenNonAmbientDeclaration.body && + !ts.hasModifier(lastSeenNonAmbientDeclaration, 128 /* Abstract */) && !lastSeenNonAmbientDeclaration.questionToken) { + reportImplementationExpectedError(lastSeenNonAmbientDeclaration); + } + if (hasOverloads) { + checkFlagAgreementBetweenOverloads(declarations, bodyDeclaration, flagsToCheck, someNodeFlags, allNodeFlags); + checkQuestionTokenAgreementBetweenOverloads(declarations, bodyDeclaration, someHaveQuestionToken, allHaveQuestionToken); + if (bodyDeclaration) { + var signatures = getSignaturesOfSymbol(symbol); + var bodySignature = getSignatureFromDeclaration(bodyDeclaration); + for (var _a = 0, signatures_6 = signatures; _a < signatures_6.length; _a++) { + var signature = signatures_6[_a]; + if (!isImplementationCompatibleWithOverload(bodySignature, signature)) { + error(signature.declaration, ts.Diagnostics.Overload_signature_is_not_compatible_with_function_implementation); + break; + } + } + } + } + } + var DeclarationSpaces; + (function (DeclarationSpaces) { + DeclarationSpaces[DeclarationSpaces["None"] = 0] = "None"; + DeclarationSpaces[DeclarationSpaces["ExportValue"] = 1] = "ExportValue"; + DeclarationSpaces[DeclarationSpaces["ExportType"] = 2] = "ExportType"; + DeclarationSpaces[DeclarationSpaces["ExportNamespace"] = 4] = "ExportNamespace"; + })(DeclarationSpaces || (DeclarationSpaces = {})); + function checkExportsOnMergedDeclarations(node) { + if (!produceDiagnostics) { + return; + } + // if localSymbol is defined on node then node itself is exported - check is required + var symbol = node.localSymbol; + if (!symbol) { + // local symbol is undefined => this declaration is non-exported. + // however symbol might contain other declarations that are exported + symbol = getSymbolOfNode(node); + if (!symbol.exportSymbol) { + // this is a pure local symbol (all declarations are non-exported) - no need to check anything + return; + } + } + // run the check only for the first declaration in the list + if (ts.getDeclarationOfKind(symbol, node.kind) !== node) { + return; + } + var exportedDeclarationSpaces = 0 /* None */; + var nonExportedDeclarationSpaces = 0 /* None */; + var defaultExportedDeclarationSpaces = 0 /* None */; + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var d = _a[_i]; + var declarationSpaces = getDeclarationSpaces(d); + var effectiveDeclarationFlags = getEffectiveDeclarationFlags(d, 1 /* Export */ | 512 /* Default */); + if (effectiveDeclarationFlags & 1 /* Export */) { + if (effectiveDeclarationFlags & 512 /* Default */) { + defaultExportedDeclarationSpaces |= declarationSpaces; + } + else { + exportedDeclarationSpaces |= declarationSpaces; + } + } + else { + nonExportedDeclarationSpaces |= declarationSpaces; + } + } + // Spaces for anything not declared a 'default export'. + var nonDefaultExportedDeclarationSpaces = exportedDeclarationSpaces | nonExportedDeclarationSpaces; + var commonDeclarationSpacesForExportsAndLocals = exportedDeclarationSpaces & nonExportedDeclarationSpaces; + var commonDeclarationSpacesForDefaultAndNonDefault = defaultExportedDeclarationSpaces & nonDefaultExportedDeclarationSpaces; + if (commonDeclarationSpacesForExportsAndLocals || commonDeclarationSpacesForDefaultAndNonDefault) { + // declaration spaces for exported and non-exported declarations intersect + for (var _b = 0, _c = symbol.declarations; _b < _c.length; _b++) { + var d = _c[_b]; + var declarationSpaces = getDeclarationSpaces(d); + var name = ts.getNameOfDeclaration(d); + // Only error on the declarations that contributed to the intersecting spaces. + if (declarationSpaces & commonDeclarationSpacesForDefaultAndNonDefault) { + error(name, ts.Diagnostics.Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead, ts.declarationNameToString(name)); + } + else if (declarationSpaces & commonDeclarationSpacesForExportsAndLocals) { + error(name, ts.Diagnostics.Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local, ts.declarationNameToString(name)); + } + } + } + function getDeclarationSpaces(decl) { + var d = decl; + switch (d.kind) { + case 241 /* InterfaceDeclaration */: + case 242 /* TypeAliasDeclaration */: + // A jsdoc typedef and callback are, by definition, type aliases + case 304 /* JSDocTypedefTag */: + case 297 /* JSDocCallbackTag */: + return 2 /* ExportType */; + case 244 /* ModuleDeclaration */: + return ts.isAmbientModule(d) || ts.getModuleInstanceState(d) !== 0 /* NonInstantiated */ + ? 4 /* ExportNamespace */ | 1 /* ExportValue */ + : 4 /* ExportNamespace */; + case 240 /* ClassDeclaration */: + case 243 /* EnumDeclaration */: + return 2 /* ExportType */ | 1 /* ExportValue */; + case 279 /* SourceFile */: + return 2 /* ExportType */ | 1 /* ExportValue */ | 4 /* ExportNamespace */; + case 254 /* ExportAssignment */: + // Export assigned entity name expressions act as aliases and should fall through, otherwise they export values + if (!ts.isEntityNameExpression(d.expression)) { + return 1 /* ExportValue */; + } + d = d.expression; + /* falls through */ + // The below options all declare an Alias, which is allowed to merge with other values within the importing module + case 248 /* ImportEqualsDeclaration */: + case 251 /* NamespaceImport */: + case 250 /* ImportClause */: + var result_4 = 0 /* None */; + var target = resolveAlias(getSymbolOfNode(d)); + ts.forEach(target.declarations, function (d) { result_4 |= getDeclarationSpaces(d); }); + return result_4; + case 237 /* VariableDeclaration */: + case 186 /* BindingElement */: + case 239 /* FunctionDeclaration */: + case 253 /* ImportSpecifier */: // https://github.com/Microsoft/TypeScript/pull/7591 + return 1 /* ExportValue */; + default: + return ts.Debug.fail(ts.Debug.showSyntaxKind(d)); + } + } + } + function getAwaitedTypeOfPromise(type, errorNode, diagnosticMessage) { + var promisedType = getPromisedTypeOfPromise(type, errorNode); + return promisedType && getAwaitedType(promisedType, errorNode, diagnosticMessage); + } + /** + * Gets the "promised type" of a promise. + * @param type The type of the promise. + * @remarks The "promised type" of a type is the type of the "value" parameter of the "onfulfilled" callback. + */ + function getPromisedTypeOfPromise(promise, errorNode) { + // + // { // promise + // then( // thenFunction + // onfulfilled: ( // onfulfilledParameterType + // value: T // valueParameterType + // ) => any + // ): any; + // } + // + if (isTypeAny(promise)) { + return undefined; + } + var typeAsPromise = promise; + if (typeAsPromise.promisedTypeOfPromise) { + return typeAsPromise.promisedTypeOfPromise; + } + if (isReferenceToType(promise, getGlobalPromiseType(/*reportErrors*/ false))) { + return typeAsPromise.promisedTypeOfPromise = promise.typeArguments[0]; + } + var thenFunction = getTypeOfPropertyOfType(promise, "then"); // TODO: GH#18217 + if (isTypeAny(thenFunction)) { + return undefined; + } + var thenSignatures = thenFunction ? getSignaturesOfType(thenFunction, 0 /* Call */) : ts.emptyArray; + if (thenSignatures.length === 0) { + if (errorNode) { + error(errorNode, ts.Diagnostics.A_promise_must_have_a_then_method); + } + return undefined; + } + var onfulfilledParameterType = getTypeWithFacts(getUnionType(ts.map(thenSignatures, getTypeOfFirstParameterOfSignature)), 2097152 /* NEUndefinedOrNull */); + if (isTypeAny(onfulfilledParameterType)) { + return undefined; + } + var onfulfilledParameterSignatures = getSignaturesOfType(onfulfilledParameterType, 0 /* Call */); + if (onfulfilledParameterSignatures.length === 0) { + if (errorNode) { + error(errorNode, ts.Diagnostics.The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback); + } + return undefined; + } + return typeAsPromise.promisedTypeOfPromise = getUnionType(ts.map(onfulfilledParameterSignatures, getTypeOfFirstParameterOfSignature), 2 /* Subtype */); + } + /** + * Gets the "awaited type" of a type. + * @param type The type to await. + * @remarks The "awaited type" of an expression is its "promised type" if the expression is a + * Promise-like type; otherwise, it is the type of the expression. This is used to reflect + * The runtime behavior of the `await` keyword. + */ + function checkAwaitedType(type, errorNode, diagnosticMessage) { + return getAwaitedType(type, errorNode, diagnosticMessage) || errorType; + } + function getAwaitedType(type, errorNode, diagnosticMessage) { + var typeAsAwaitable = type; + if (typeAsAwaitable.awaitedTypeOfType) { + return typeAsAwaitable.awaitedTypeOfType; + } + if (isTypeAny(type)) { + return typeAsAwaitable.awaitedTypeOfType = type; + } + if (type.flags & 1048576 /* Union */) { + var types = void 0; + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var constituentType = _a[_i]; + types = ts.append(types, getAwaitedType(constituentType, errorNode, diagnosticMessage)); + } + if (!types) { + return undefined; + } + return typeAsAwaitable.awaitedTypeOfType = getUnionType(types); + } + var promisedType = getPromisedTypeOfPromise(type); + if (promisedType) { + if (type.id === promisedType.id || awaitedTypeStack.indexOf(promisedType.id) >= 0) { + // Verify that we don't have a bad actor in the form of a promise whose + // promised type is the same as the promise type, or a mutually recursive + // promise. If so, we return undefined as we cannot guess the shape. If this + // were the actual case in the JavaScript, this Promise would never resolve. + // + // An example of a bad actor with a singly-recursive promise type might + // be: + // + // interface BadPromise { + // then( + // onfulfilled: (value: BadPromise) => any, + // onrejected: (error: any) => any): BadPromise; + // } + // The above interface will pass the PromiseLike check, and return a + // promised type of `BadPromise`. Since this is a self reference, we + // don't want to keep recursing ad infinitum. + // + // An example of a bad actor in the form of a mutually-recursive + // promise type might be: + // + // interface BadPromiseA { + // then( + // onfulfilled: (value: BadPromiseB) => any, + // onrejected: (error: any) => any): BadPromiseB; + // } + // + // interface BadPromiseB { + // then( + // onfulfilled: (value: BadPromiseA) => any, + // onrejected: (error: any) => any): BadPromiseA; + // } + // + if (errorNode) { + error(errorNode, ts.Diagnostics.Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method); + } + return undefined; + } + // Keep track of the type we're about to unwrap to avoid bad recursive promise types. + // See the comments above for more information. + awaitedTypeStack.push(type.id); + var awaitedType = getAwaitedType(promisedType, errorNode, diagnosticMessage); + awaitedTypeStack.pop(); + if (!awaitedType) { + return undefined; + } + return typeAsAwaitable.awaitedTypeOfType = awaitedType; + } + // The type was not a promise, so it could not be unwrapped any further. + // As long as the type does not have a callable "then" property, it is + // safe to return the type; otherwise, an error will be reported in + // the call to getNonThenableType and we will return undefined. + // + // An example of a non-promise "thenable" might be: + // + // await { then(): void {} } + // + // The "thenable" does not match the minimal definition for a promise. When + // a Promise/A+-compatible or ES6 promise tries to adopt this value, the promise + // will never settle. We treat this as an error to help flag an early indicator + // of a runtime problem. If the user wants to return this value from an async + // function, they would need to wrap it in some other value. If they want it to + // be treated as a promise, they can cast to . + var thenFunction = getTypeOfPropertyOfType(type, "then"); + if (thenFunction && getSignaturesOfType(thenFunction, 0 /* Call */).length > 0) { + if (errorNode) { + if (!diagnosticMessage) + return ts.Debug.fail(); + error(errorNode, diagnosticMessage); + } + return undefined; + } + return typeAsAwaitable.awaitedTypeOfType = type; + } + /** + * Checks the return type of an async function to ensure it is a compatible + * Promise implementation. + * + * This checks that an async function has a valid Promise-compatible return type. + * An async function has a valid Promise-compatible return type if the resolved value + * of the return type has a construct signature that takes in an `initializer` function + * that in turn supplies a `resolve` function as one of its arguments and results in an + * object with a callable `then` signature. + * + * @param node The signature to check + */ + function checkAsyncFunctionReturnType(node, returnTypeNode) { + // As part of our emit for an async function, we will need to emit the entity name of + // the return type annotation as an expression. To meet the necessary runtime semantics + // for __awaiter, we must also check that the type of the declaration (e.g. the static + // side or "constructor" of the promise type) is compatible `PromiseConstructorLike`. + // + // An example might be (from lib.es6.d.ts): + // + // interface Promise { ... } + // interface PromiseConstructor { + // new (...): Promise; + // } + // declare var Promise: PromiseConstructor; + // + // When an async function declares a return type annotation of `Promise`, we + // need to get the type of the `Promise` variable declaration above, which would + // be `PromiseConstructor`. + // + // The same case applies to a class: + // + // declare class Promise { + // constructor(...); + // then(...): Promise; + // } + // + var returnType = getTypeFromTypeNode(returnTypeNode); + if (languageVersion >= 2 /* ES2015 */) { + if (returnType === errorType) { + return; + } + var globalPromiseType = getGlobalPromiseType(/*reportErrors*/ true); + if (globalPromiseType !== emptyGenericType && !isReferenceToType(returnType, globalPromiseType)) { + // The promise type was not a valid type reference to the global promise type, so we + // report an error and return the unknown type. + error(returnTypeNode, ts.Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type); + return; + } + } + else { + // Always mark the type node as referenced if it points to a value + markTypeNodeAsReferenced(returnTypeNode); + if (returnType === errorType) { + return; + } + var promiseConstructorName = ts.getEntityNameFromTypeNode(returnTypeNode); + if (promiseConstructorName === undefined) { + error(returnTypeNode, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, typeToString(returnType)); + return; + } + var promiseConstructorSymbol = resolveEntityName(promiseConstructorName, 67220415 /* Value */, /*ignoreErrors*/ true); + var promiseConstructorType = promiseConstructorSymbol ? getTypeOfSymbol(promiseConstructorSymbol) : errorType; + if (promiseConstructorType === errorType) { + if (promiseConstructorName.kind === 72 /* Identifier */ && promiseConstructorName.escapedText === "Promise" && getTargetType(returnType) === getGlobalPromiseType(/*reportErrors*/ false)) { + error(returnTypeNode, ts.Diagnostics.An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option); + } + else { + error(returnTypeNode, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, ts.entityNameToString(promiseConstructorName)); + } + return; + } + var globalPromiseConstructorLikeType = getGlobalPromiseConstructorLikeType(/*reportErrors*/ true); + if (globalPromiseConstructorLikeType === emptyObjectType) { + // If we couldn't resolve the global PromiseConstructorLike type we cannot verify + // compatibility with __awaiter. + error(returnTypeNode, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, ts.entityNameToString(promiseConstructorName)); + return; + } + if (!checkTypeAssignableTo(promiseConstructorType, globalPromiseConstructorLikeType, returnTypeNode, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value)) { + return; + } + // Verify there is no local declaration that could collide with the promise constructor. + var rootName = promiseConstructorName && getFirstIdentifier(promiseConstructorName); + var collidingSymbol = getSymbol(node.locals, rootName.escapedText, 67220415 /* Value */); + if (collidingSymbol) { + error(collidingSymbol.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, ts.idText(rootName), ts.entityNameToString(promiseConstructorName)); + return; + } + } + checkAwaitedType(returnType, node, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); + } + /** Check a decorator */ + function checkDecorator(node) { + var signature = getResolvedSignature(node); + var returnType = getReturnTypeOfSignature(signature); + if (returnType.flags & 1 /* Any */) { + return; + } + var expectedReturnType; + var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); + var errorInfo; + switch (node.parent.kind) { + case 240 /* ClassDeclaration */: + var classSymbol = getSymbolOfNode(node.parent); + var classConstructorType = getTypeOfSymbol(classSymbol); + expectedReturnType = getUnionType([classConstructorType, voidType]); + break; + case 151 /* Parameter */: + expectedReturnType = voidType; + errorInfo = ts.chainDiagnosticMessages( + /*details*/ undefined, ts.Diagnostics.The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any); + break; + case 154 /* PropertyDeclaration */: + expectedReturnType = voidType; + errorInfo = ts.chainDiagnosticMessages( + /*details*/ undefined, ts.Diagnostics.The_return_type_of_a_property_decorator_function_must_be_either_void_or_any); + break; + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + var methodType = getTypeOfNode(node.parent); + var descriptorType = createTypedPropertyDescriptorType(methodType); + expectedReturnType = getUnionType([descriptorType, voidType]); + break; + default: + return ts.Debug.fail(); + } + checkTypeAssignableTo(returnType, expectedReturnType, node, headMessage, function () { return errorInfo; }); + } + /** + * If a TypeNode can be resolved to a value symbol imported from an external module, it is + * marked as referenced to prevent import elision. + */ + function markTypeNodeAsReferenced(node) { + markEntityNameOrEntityExpressionAsReference(node && ts.getEntityNameFromTypeNode(node)); + } + function markEntityNameOrEntityExpressionAsReference(typeName) { + if (!typeName) + return; + var rootName = getFirstIdentifier(typeName); + var meaning = (typeName.kind === 72 /* Identifier */ ? 67897832 /* Type */ : 1920 /* Namespace */) | 2097152 /* Alias */; + var rootSymbol = resolveName(rootName, rootName.escapedText, meaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isRefernce*/ true); + if (rootSymbol + && rootSymbol.flags & 2097152 /* Alias */ + && symbolIsValue(rootSymbol) + && !isConstEnumOrConstEnumOnlyModule(resolveAlias(rootSymbol))) { + markAliasSymbolAsReferenced(rootSymbol); + } + } + /** + * This function marks the type used for metadata decorator as referenced if it is import + * from external module. + * This is different from markTypeNodeAsReferenced because it tries to simplify type nodes in + * union and intersection type + * @param node + */ + function markDecoratorMedataDataTypeNodeAsReferenced(node) { + var entityName = getEntityNameForDecoratorMetadata(node); + if (entityName && ts.isEntityName(entityName)) { + markEntityNameOrEntityExpressionAsReference(entityName); + } + } + function getEntityNameForDecoratorMetadata(node) { + if (node) { + switch (node.kind) { + case 174 /* IntersectionType */: + case 173 /* UnionType */: + return getEntityNameForDecoratorMetadataFromTypeList(node.types); + case 175 /* ConditionalType */: + return getEntityNameForDecoratorMetadataFromTypeList([node.trueType, node.falseType]); + case 177 /* ParenthesizedType */: + return getEntityNameForDecoratorMetadata(node.type); + case 164 /* TypeReference */: + return node.typeName; + } + } + } + function getEntityNameForDecoratorMetadataFromTypeList(types) { + var commonEntityName; + for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { + var typeNode = types_16[_i]; + while (typeNode.kind === 177 /* ParenthesizedType */) { + typeNode = typeNode.type; // Skip parens if need be + } + if (typeNode.kind === 132 /* NeverKeyword */) { + continue; // Always elide `never` from the union/intersection if possible + } + if (!strictNullChecks && (typeNode.kind === 96 /* NullKeyword */ || typeNode.kind === 141 /* UndefinedKeyword */)) { + continue; // Elide null and undefined from unions for metadata, just like what we did prior to the implementation of strict null checks + } + var individualEntityName = getEntityNameForDecoratorMetadata(typeNode); + if (!individualEntityName) { + // Individual is something like string number + // So it would be serialized to either that type or object + // Safe to return here + return undefined; + } + if (commonEntityName) { + // Note this is in sync with the transformation that happens for type node. + // Keep this in sync with serializeUnionOrIntersectionType + // Verify if they refer to same entity and is identifier + // return undefined if they dont match because we would emit object + if (!ts.isIdentifier(commonEntityName) || + !ts.isIdentifier(individualEntityName) || + commonEntityName.escapedText !== individualEntityName.escapedText) { + return undefined; + } + } + else { + commonEntityName = individualEntityName; + } + } + return commonEntityName; + } + function getParameterTypeNodeForDecoratorCheck(node) { + var typeNode = ts.getEffectiveTypeAnnotationNode(node); + return ts.isRestParameter(node) ? ts.getRestParameterElementType(typeNode) : typeNode; + } + /** Check the decorators of a node */ + function checkDecorators(node) { + if (!node.decorators) { + return; + } + // skip this check for nodes that cannot have decorators. These should have already had an error reported by + // checkGrammarDecorators. + if (!ts.nodeCanBeDecorated(node, node.parent, node.parent.parent)) { + return; + } + if (!compilerOptions.experimentalDecorators) { + error(node, ts.Diagnostics.Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_to_remove_this_warning); + } + var firstDecorator = node.decorators[0]; + checkExternalEmitHelpers(firstDecorator, 8 /* Decorate */); + if (node.kind === 151 /* Parameter */) { + checkExternalEmitHelpers(firstDecorator, 32 /* Param */); + } + if (compilerOptions.emitDecoratorMetadata) { + checkExternalEmitHelpers(firstDecorator, 16 /* Metadata */); + // we only need to perform these checks if we are emitting serialized type metadata for the target of a decorator. + switch (node.kind) { + case 240 /* ClassDeclaration */: + var constructor = ts.getFirstConstructorWithBody(node); + if (constructor) { + for (var _i = 0, _a = constructor.parameters; _i < _a.length; _i++) { + var parameter = _a[_i]; + markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); + } + } + break; + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + var otherKind = node.kind === 158 /* GetAccessor */ ? 159 /* SetAccessor */ : 158 /* GetAccessor */; + var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(node), otherKind); + markDecoratorMedataDataTypeNodeAsReferenced(getAnnotatedAccessorTypeNode(node) || otherAccessor && getAnnotatedAccessorTypeNode(otherAccessor)); + break; + case 156 /* MethodDeclaration */: + for (var _b = 0, _c = node.parameters; _b < _c.length; _b++) { + var parameter = _c[_b]; + markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); + } + markDecoratorMedataDataTypeNodeAsReferenced(ts.getEffectiveReturnTypeNode(node)); + break; + case 154 /* PropertyDeclaration */: + markDecoratorMedataDataTypeNodeAsReferenced(ts.getEffectiveTypeAnnotationNode(node)); + break; + case 151 /* Parameter */: + markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(node)); + var containingSignature = node.parent; + for (var _d = 0, _e = containingSignature.parameters; _d < _e.length; _d++) { + var parameter = _e[_d]; + markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); + } + break; + } + } + ts.forEach(node.decorators, checkDecorator); + } + function checkFunctionDeclaration(node) { + if (produceDiagnostics) { + checkFunctionOrMethodDeclaration(node); + checkGrammarForGenerator(node); + checkCollisionWithRequireExportsInGeneratedCode(node, node.name); + checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); + } + } + function checkJSDocTypeAliasTag(node) { + if (!node.typeExpression) { + // If the node had `@property` tags, `typeExpression` would have been set to the first property tag. + error(node.name, ts.Diagnostics.JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags); + } + if (node.name) { + checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_alias_name_cannot_be_0); + } + checkSourceElement(node.typeExpression); + } + function checkJSDocTemplateTag(node) { + checkSourceElement(node.constraint); + for (var _i = 0, _a = node.typeParameters; _i < _a.length; _i++) { + var tp = _a[_i]; + checkSourceElement(tp); + } + } + function checkJSDocTypeTag(node) { + checkSourceElement(node.typeExpression); + } + function checkJSDocParameterTag(node) { + checkSourceElement(node.typeExpression); + if (!ts.getParameterSymbolFromJSDoc(node)) { + var decl = ts.getHostSignatureFromJSDoc(node); + // don't issue an error for invalid hosts -- just functions -- + // and give a better error message when the host function mentions `arguments` + // but the tag doesn't have an array type + if (decl) { + var i = ts.getJSDocTags(decl).filter(ts.isJSDocParameterTag).indexOf(node); + if (i > -1 && i < decl.parameters.length && ts.isBindingPattern(decl.parameters[i].name)) { + return; + } + if (!containsArgumentsReference(decl)) { + error(node.name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name, ts.idText(node.name.kind === 148 /* QualifiedName */ ? node.name.right : node.name)); + } + else if (ts.findLast(ts.getJSDocTags(decl), ts.isJSDocParameterTag) === node && + node.typeExpression && node.typeExpression.type && + !isArrayType(getTypeFromTypeNode(node.typeExpression.type))) { + error(node.name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_had_an_array_type, ts.idText(node.name.kind === 148 /* QualifiedName */ ? node.name.right : node.name)); + } + } + } + } + function checkJSDocFunctionType(node) { + if (produceDiagnostics && !node.type && !ts.isJSDocConstructSignature(node)) { + reportImplicitAny(node, anyType); + } + checkSignatureDeclaration(node); + } + function checkJSDocAugmentsTag(node) { + var classLike = ts.getJSDocHost(node); + if (!ts.isClassDeclaration(classLike) && !ts.isClassExpression(classLike)) { + error(classLike, ts.Diagnostics.JSDoc_0_is_not_attached_to_a_class, ts.idText(node.tagName)); + return; + } + var augmentsTags = ts.getJSDocTags(classLike).filter(ts.isJSDocAugmentsTag); + ts.Debug.assert(augmentsTags.length > 0); + if (augmentsTags.length > 1) { + error(augmentsTags[1], ts.Diagnostics.Class_declarations_cannot_have_more_than_one_augments_or_extends_tag); + } + var name = getIdentifierFromEntityNameExpression(node.class.expression); + var extend = ts.getClassExtendsHeritageElement(classLike); + if (extend) { + var className = getIdentifierFromEntityNameExpression(extend.expression); + if (className && name.escapedText !== className.escapedText) { + error(name, ts.Diagnostics.JSDoc_0_1_does_not_match_the_extends_2_clause, ts.idText(node.tagName), ts.idText(name), ts.idText(className)); + } + } + } + function getIdentifierFromEntityNameExpression(node) { + switch (node.kind) { + case 72 /* Identifier */: + return node; + case 189 /* PropertyAccessExpression */: + return node.name; + default: + return undefined; + } + } + function checkFunctionOrMethodDeclaration(node) { + checkDecorators(node); + checkSignatureDeclaration(node); + var functionFlags = ts.getFunctionFlags(node); + // Do not use hasDynamicName here, because that returns false for well known symbols. + // We want to perform checkComputedPropertyName for all computed properties, including + // well known symbols. + if (node.name && node.name.kind === 149 /* ComputedPropertyName */) { + // This check will account for methods in class/interface declarations, + // as well as accessors in classes/object literals + checkComputedPropertyName(node.name); + } + if (!hasNonBindableDynamicName(node)) { + // first we want to check the local symbol that contain this declaration + // - if node.localSymbol !== undefined - this is current declaration is exported and localSymbol points to the local symbol + // - if node.localSymbol === undefined - this node is non-exported so we can just pick the result of getSymbolOfNode + var symbol = getSymbolOfNode(node); + var localSymbol = node.localSymbol || symbol; + // Since the javascript won't do semantic analysis like typescript, + // if the javascript file comes before the typescript file and both contain same name functions, + // checkFunctionOrConstructorSymbol wouldn't be called if we didnt ignore javascript function. + var firstDeclaration = ts.find(localSymbol.declarations, + // Get first non javascript function declaration + function (declaration) { return declaration.kind === node.kind && !(declaration.flags & 65536 /* JavaScriptFile */); }); + // Only type check the symbol once + if (node === firstDeclaration) { + checkFunctionOrConstructorSymbol(localSymbol); + } + if (symbol.parent) { + // run check once for the first declaration + if (ts.getDeclarationOfKind(symbol, node.kind) === node) { + // run check on export symbol to check that modifiers agree across all exported declarations + checkFunctionOrConstructorSymbol(symbol); + } + } + } + var body = node.kind === 155 /* MethodSignature */ ? undefined : node.body; + checkSourceElement(body); + if ((functionFlags & 1 /* Generator */) === 0) { // Async function or normal function + var returnOrPromisedType = getReturnOrPromisedType(node, functionFlags); + checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnOrPromisedType); + } + if (produceDiagnostics && !ts.getEffectiveReturnTypeNode(node)) { + // Report an implicit any error if there is no body, no explicit return type, and node is not a private method + // in an ambient context + if (ts.nodeIsMissing(body) && !isPrivateWithinAmbient(node)) { + reportImplicitAny(node, anyType); + } + if (functionFlags & 1 /* Generator */ && ts.nodeIsPresent(body)) { + // A generator with a body and no type annotation can still cause errors. It can error if the + // yielded values have no common supertype, or it can give an implicit any error if it has no + // yielded values. The only way to trigger these errors is to try checking its return type. + getReturnTypeOfSignature(getSignatureFromDeclaration(node)); + } + } + // A js function declaration can have a @type tag instead of a return type node, but that type must have a call signature + if (ts.isInJSFile(node)) { + var typeTag = ts.getJSDocTypeTag(node); + if (typeTag && typeTag.typeExpression && !getContextualCallSignature(getTypeFromTypeNode(typeTag.typeExpression), node)) { + error(typeTag, ts.Diagnostics.The_type_of_a_function_declaration_must_match_the_function_s_signature); + } + } + } + function registerForUnusedIdentifiersCheck(node) { + // May be in a call such as getTypeOfNode that happened to call this. But potentiallyUnusedIdentifiers is only defined in the scope of `checkSourceFile`. + if (produceDiagnostics && !(node.flags & 4194304 /* Ambient */)) { + var sourceFile = ts.getSourceFileOfNode(node); + var potentiallyUnusedIdentifiers = allPotentiallyUnusedIdentifiers.get(sourceFile.path); + if (!potentiallyUnusedIdentifiers) { + potentiallyUnusedIdentifiers = []; + allPotentiallyUnusedIdentifiers.set(sourceFile.path, potentiallyUnusedIdentifiers); + } + // TODO: GH#22580 + // Debug.assert(addToSeen(seenPotentiallyUnusedIdentifiers, getNodeId(node)), "Adding potentially-unused identifier twice"); + potentiallyUnusedIdentifiers.push(node); + } + } + function checkUnusedIdentifiers(potentiallyUnusedIdentifiers, addDiagnostic) { + for (var _i = 0, potentiallyUnusedIdentifiers_1 = potentiallyUnusedIdentifiers; _i < potentiallyUnusedIdentifiers_1.length; _i++) { + var node = potentiallyUnusedIdentifiers_1[_i]; + switch (node.kind) { + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + checkUnusedClassMembers(node, addDiagnostic); + checkUnusedTypeParameters(node, addDiagnostic); + break; + case 279 /* SourceFile */: + case 244 /* ModuleDeclaration */: + case 218 /* Block */: + case 246 /* CaseBlock */: + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + checkUnusedLocalsAndParameters(node, addDiagnostic); + break; + case 157 /* Constructor */: + case 196 /* FunctionExpression */: + case 239 /* FunctionDeclaration */: + case 197 /* ArrowFunction */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + if (node.body) { // Don't report unused parameters in overloads + checkUnusedLocalsAndParameters(node, addDiagnostic); + } + checkUnusedTypeParameters(node, addDiagnostic); + break; + case 155 /* MethodSignature */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + case 242 /* TypeAliasDeclaration */: + case 241 /* InterfaceDeclaration */: + checkUnusedTypeParameters(node, addDiagnostic); + break; + case 176 /* InferType */: + checkUnusedInferTypeParameter(node, addDiagnostic); + break; + default: + ts.Debug.assertNever(node, "Node should not have been registered for unused identifiers check"); + } + } + } + function errorUnusedLocal(declaration, name, addDiagnostic) { + var node = ts.getNameOfDeclaration(declaration) || declaration; + var message = isTypeDeclaration(declaration) ? ts.Diagnostics._0_is_declared_but_never_used : ts.Diagnostics._0_is_declared_but_its_value_is_never_read; + addDiagnostic(declaration, 0 /* Local */, ts.createDiagnosticForNode(node, message, name)); + } + function isIdentifierThatStartsWithUnderscore(node) { + return ts.isIdentifier(node) && ts.idText(node).charCodeAt(0) === 95 /* _ */; + } + function checkUnusedClassMembers(node, addDiagnostic) { + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + switch (member.kind) { + case 156 /* MethodDeclaration */: + case 154 /* PropertyDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + if (member.kind === 159 /* SetAccessor */ && member.symbol.flags & 32768 /* GetAccessor */) { + // Already would have reported an error on the getter. + break; + } + var symbol = getSymbolOfNode(member); + if (!symbol.isReferenced && ts.hasModifier(member, 8 /* Private */)) { + addDiagnostic(member, 0 /* Local */, ts.createDiagnosticForNode(member.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, symbolToString(symbol))); + } + break; + case 157 /* Constructor */: + for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { + var parameter = _c[_b]; + if (!parameter.symbol.isReferenced && ts.hasModifier(parameter, 8 /* Private */)) { + addDiagnostic(parameter, 0 /* Local */, ts.createDiagnosticForNode(parameter.name, ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read, ts.symbolName(parameter.symbol))); + } + } + break; + case 162 /* IndexSignature */: + case 217 /* SemicolonClassElement */: + // Can't be private + break; + default: + ts.Debug.fail(); + } + } + } + function checkUnusedInferTypeParameter(node, addDiagnostic) { + var typeParameter = node.typeParameter; + if (isTypeParameterUnused(typeParameter)) { + addDiagnostic(node, 1 /* Parameter */, ts.createDiagnosticForNode(node, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(typeParameter.name))); + } + } + function checkUnusedTypeParameters(node, addDiagnostic) { + // Only report errors on the last declaration for the type parameter container; + // this ensures that all uses have been accounted for. + if (ts.last(getSymbolOfNode(node).declarations) !== node) + return; + var typeParameters = ts.getEffectiveTypeParameterDeclarations(node); + var seenParentsWithEveryUnused = new ts.NodeSet(); + for (var _i = 0, typeParameters_2 = typeParameters; _i < typeParameters_2.length; _i++) { + var typeParameter = typeParameters_2[_i]; + if (!isTypeParameterUnused(typeParameter)) + continue; + var name = ts.idText(typeParameter.name); + var parent = typeParameter.parent; + if (parent.kind !== 176 /* InferType */ && parent.typeParameters.every(isTypeParameterUnused)) { + if (seenParentsWithEveryUnused.tryAdd(parent)) { + var range = ts.isJSDocTemplateTag(parent) + // Whole @template tag + ? ts.rangeOfNode(parent) + // Include the `<>` in the error message + : ts.rangeOfTypeParameters(parent.typeParameters); + var only = typeParameters.length === 1; + var message = only ? ts.Diagnostics._0_is_declared_but_its_value_is_never_read : ts.Diagnostics.All_type_parameters_are_unused; + var arg0 = only ? name : undefined; + addDiagnostic(typeParameter, 1 /* Parameter */, ts.createFileDiagnostic(ts.getSourceFileOfNode(parent), range.pos, range.end - range.pos, message, arg0)); + } + } + else { + addDiagnostic(typeParameter, 1 /* Parameter */, ts.createDiagnosticForNode(typeParameter, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, name)); + } + } + } + function isTypeParameterUnused(typeParameter) { + return !(getMergedSymbol(typeParameter.symbol).isReferenced & 262144 /* TypeParameter */) && !isIdentifierThatStartsWithUnderscore(typeParameter.name); + } + function addToGroup(map, key, value, getKey) { + var keyString = String(getKey(key)); + var group = map.get(keyString); + if (group) { + group[1].push(value); + } + else { + map.set(keyString, [key, [value]]); + } + } + function tryGetRootParameterDeclaration(node) { + return ts.tryCast(ts.getRootDeclaration(node), ts.isParameter); + } + function checkUnusedLocalsAndParameters(nodeWithLocals, addDiagnostic) { + if (nodeWithLocals.flags & 4194304 /* Ambient */) + return; + // Ideally we could use the ImportClause directly as a key, but must wait until we have full ES6 maps. So must store key along with value. + var unusedImports = ts.createMap(); + var unusedDestructures = ts.createMap(); + var unusedVariables = ts.createMap(); + nodeWithLocals.locals.forEach(function (local) { + // If it's purely a type parameter, ignore, will be checked in `checkUnusedTypeParameters`. + // If it's a type parameter merged with a parameter, check if the parameter-side is used. + if (local.flags & 262144 /* TypeParameter */ ? !(local.flags & 3 /* Variable */ && !(local.isReferenced & 3 /* Variable */)) : local.isReferenced || local.exportSymbol) { + return; + } + for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (ts.isAmbientModule(declaration) || + (ts.isVariableDeclaration(declaration) && ts.isForInOrOfStatement(declaration.parent.parent) || isImportedDeclaration(declaration)) && isIdentifierThatStartsWithUnderscore(declaration.name)) { + continue; + } + if (isImportedDeclaration(declaration)) { + addToGroup(unusedImports, importClauseFromImported(declaration), declaration, getNodeId); + } + else if (ts.isBindingElement(declaration) && ts.isObjectBindingPattern(declaration.parent)) { + // In `{ a, ...b }, `a` is considered used since it removes a property from `b`. `b` may still be unused though. + var lastElement = ts.last(declaration.parent.elements); + if (declaration === lastElement || !ts.last(declaration.parent.elements).dotDotDotToken) { + addToGroup(unusedDestructures, declaration.parent, declaration, getNodeId); + } + } + else if (ts.isVariableDeclaration(declaration)) { + addToGroup(unusedVariables, declaration.parent, declaration, getNodeId); + } + else { + var parameter = local.valueDeclaration && tryGetRootParameterDeclaration(local.valueDeclaration); + var name = local.valueDeclaration && ts.getNameOfDeclaration(local.valueDeclaration); + if (parameter && name) { + if (!ts.isParameterPropertyDeclaration(parameter) && !ts.parameterIsThisKeyword(parameter) && !isIdentifierThatStartsWithUnderscore(name)) { + addDiagnostic(parameter, 1 /* Parameter */, ts.createDiagnosticForNode(name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.symbolName(local))); + } + } + else { + errorUnusedLocal(declaration, ts.symbolName(local), addDiagnostic); + } + } + } + }); + unusedImports.forEach(function (_a) { + var importClause = _a[0], unuseds = _a[1]; + var importDecl = importClause.parent; + var nDeclarations = (importClause.name ? 1 : 0) + + (importClause.namedBindings ? + (importClause.namedBindings.kind === 251 /* NamespaceImport */ ? 1 : importClause.namedBindings.elements.length) + : 0); + if (nDeclarations === unuseds.length) { + addDiagnostic(importDecl, 0 /* Local */, unuseds.length === 1 + ? ts.createDiagnosticForNode(importDecl, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(ts.first(unuseds).name)) + : ts.createDiagnosticForNode(importDecl, ts.Diagnostics.All_imports_in_import_declaration_are_unused)); + } + else { + for (var _i = 0, unuseds_1 = unuseds; _i < unuseds_1.length; _i++) { + var unused = unuseds_1[_i]; + errorUnusedLocal(unused, ts.idText(unused.name), addDiagnostic); + } + } + }); + unusedDestructures.forEach(function (_a) { + var bindingPattern = _a[0], bindingElements = _a[1]; + var kind = tryGetRootParameterDeclaration(bindingPattern.parent) ? 1 /* Parameter */ : 0 /* Local */; + if (bindingPattern.elements.length === bindingElements.length) { + if (bindingElements.length === 1 && bindingPattern.parent.kind === 237 /* VariableDeclaration */ && bindingPattern.parent.parent.kind === 238 /* VariableDeclarationList */) { + addToGroup(unusedVariables, bindingPattern.parent.parent, bindingPattern.parent, getNodeId); + } + else { + addDiagnostic(bindingPattern, kind, bindingElements.length === 1 + ? ts.createDiagnosticForNode(bindingPattern, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(ts.first(bindingElements).name)) + : ts.createDiagnosticForNode(bindingPattern, ts.Diagnostics.All_destructured_elements_are_unused)); + } + } + else { + for (var _i = 0, bindingElements_1 = bindingElements; _i < bindingElements_1.length; _i++) { + var e = bindingElements_1[_i]; + addDiagnostic(e, kind, ts.createDiagnosticForNode(e, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(e.name))); + } + } + }); + unusedVariables.forEach(function (_a) { + var declarationList = _a[0], declarations = _a[1]; + if (declarationList.declarations.length === declarations.length) { + addDiagnostic(declarationList, 0 /* Local */, declarations.length === 1 + ? ts.createDiagnosticForNode(ts.first(declarations).name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(ts.first(declarations).name)) + : ts.createDiagnosticForNode(declarationList.parent.kind === 219 /* VariableStatement */ ? declarationList.parent : declarationList, ts.Diagnostics.All_variables_are_unused)); + } + else { + for (var _i = 0, declarations_5 = declarations; _i < declarations_5.length; _i++) { + var decl = declarations_5[_i]; + addDiagnostic(decl, 0 /* Local */, ts.createDiagnosticForNode(decl, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(decl.name))); + } + } + }); + } + function bindingNameText(name) { + switch (name.kind) { + case 72 /* Identifier */: + return ts.idText(name); + case 185 /* ArrayBindingPattern */: + case 184 /* ObjectBindingPattern */: + return bindingNameText(ts.cast(ts.first(name.elements), ts.isBindingElement).name); + default: + return ts.Debug.assertNever(name); + } + } + function isImportedDeclaration(node) { + return node.kind === 250 /* ImportClause */ || node.kind === 253 /* ImportSpecifier */ || node.kind === 251 /* NamespaceImport */; + } + function importClauseFromImported(decl) { + return decl.kind === 250 /* ImportClause */ ? decl : decl.kind === 251 /* NamespaceImport */ ? decl.parent : decl.parent.parent; + } + function checkBlock(node) { + // Grammar checking for SyntaxKind.Block + if (node.kind === 218 /* Block */) { + checkGrammarStatementInAmbientContext(node); + } + if (ts.isFunctionOrModuleBlock(node)) { + var saveFlowAnalysisDisabled = flowAnalysisDisabled; + ts.forEach(node.statements, checkSourceElement); + flowAnalysisDisabled = saveFlowAnalysisDisabled; + } + else { + ts.forEach(node.statements, checkSourceElement); + } + if (node.locals) { + registerForUnusedIdentifiersCheck(node); + } + } + function checkCollisionWithArgumentsInGeneratedCode(node) { + // no rest parameters \ declaration context \ overload - no codegen impact + if (languageVersion >= 2 /* ES2015 */ || compilerOptions.noEmit || !ts.hasRestParameter(node) || node.flags & 4194304 /* Ambient */ || ts.nodeIsMissing(node.body)) { + return; + } + ts.forEach(node.parameters, function (p) { + if (p.name && !ts.isBindingPattern(p.name) && p.name.escapedText === argumentsSymbol.escapedName) { + error(p, ts.Diagnostics.Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters); + } + }); + } + function needCollisionCheckForIdentifier(node, identifier, name) { + if (!(identifier && identifier.escapedText === name)) { + return false; + } + if (node.kind === 154 /* PropertyDeclaration */ || + node.kind === 153 /* PropertySignature */ || + node.kind === 156 /* MethodDeclaration */ || + node.kind === 155 /* MethodSignature */ || + node.kind === 158 /* GetAccessor */ || + node.kind === 159 /* SetAccessor */) { + // it is ok to have member named '_super' or '_this' - member access is always qualified + return false; + } + if (node.flags & 4194304 /* Ambient */) { + // ambient context - no codegen impact + return false; + } + var root = ts.getRootDeclaration(node); + if (root.kind === 151 /* Parameter */ && ts.nodeIsMissing(root.parent.body)) { + // just an overload - no codegen impact + return false; + } + return true; + } + // this function will run after checking the source file so 'CaptureThis' is correct for all nodes + function checkIfThisIsCapturedInEnclosingScope(node) { + ts.findAncestor(node, function (current) { + if (getNodeCheckFlags(current) & 4 /* CaptureThis */) { + var isDeclaration_1 = node.kind !== 72 /* Identifier */; + if (isDeclaration_1) { + error(ts.getNameOfDeclaration(node), ts.Diagnostics.Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference); + } + else { + error(node, ts.Diagnostics.Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference); + } + return true; + } + return false; + }); + } + function checkIfNewTargetIsCapturedInEnclosingScope(node) { + ts.findAncestor(node, function (current) { + if (getNodeCheckFlags(current) & 8 /* CaptureNewTarget */) { + var isDeclaration_2 = node.kind !== 72 /* Identifier */; + if (isDeclaration_2) { + error(ts.getNameOfDeclaration(node), ts.Diagnostics.Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference); + } + else { + error(node, ts.Diagnostics.Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta_property_reference); + } + return true; + } + return false; + }); + } + function checkCollisionWithRequireExportsInGeneratedCode(node, name) { + // No need to check for require or exports for ES6 modules and later + if (moduleKind >= ts.ModuleKind.ES2015 || compilerOptions.noEmit) { + return; + } + if (!needCollisionCheckForIdentifier(node, name, "require") && !needCollisionCheckForIdentifier(node, name, "exports")) { + return; + } + // Uninstantiated modules shouldnt do this check + if (ts.isModuleDeclaration(node) && ts.getModuleInstanceState(node) !== 1 /* Instantiated */) { + return; + } + // In case of variable declaration, node.parent is variable statement so look at the variable statement's parent + var parent = getDeclarationContainer(node); + if (parent.kind === 279 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent)) { + // If the declaration happens to be in external module, report error that require and exports are reserved keywords + error(name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module, ts.declarationNameToString(name), ts.declarationNameToString(name)); + } + } + function checkCollisionWithGlobalPromiseInGeneratedCode(node, name) { + if (languageVersion >= 4 /* ES2017 */ || compilerOptions.noEmit || !needCollisionCheckForIdentifier(node, name, "Promise")) { + return; + } + // Uninstantiated modules shouldnt do this check + if (ts.isModuleDeclaration(node) && ts.getModuleInstanceState(node) !== 1 /* Instantiated */) { + return; + } + // In case of variable declaration, node.parent is variable statement so look at the variable statement's parent + var parent = getDeclarationContainer(node); + if (parent.kind === 279 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent) && parent.flags & 1024 /* HasAsyncFunctions */) { + // If the declaration happens to be in external module, report error that Promise is a reserved identifier. + error(name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_functions, ts.declarationNameToString(name), ts.declarationNameToString(name)); + } + } + function checkVarDeclaredNamesNotShadowed(node) { + // - ScriptBody : StatementList + // It is a Syntax Error if any element of the LexicallyDeclaredNames of StatementList + // also occurs in the VarDeclaredNames of StatementList. + // - Block : { StatementList } + // It is a Syntax Error if any element of the LexicallyDeclaredNames of StatementList + // also occurs in the VarDeclaredNames of StatementList. + // Variable declarations are hoisted to the top of their function scope. They can shadow + // block scoped declarations, which bind tighter. this will not be flagged as duplicate definition + // by the binder as the declaration scope is different. + // A non-initialized declaration is a no-op as the block declaration will resolve before the var + // declaration. the problem is if the declaration has an initializer. this will act as a write to the + // block declared value. this is fine for let, but not const. + // Only consider declarations with initializers, uninitialized const declarations will not + // step on a let/const variable. + // Do not consider const and const declarations, as duplicate block-scoped declarations + // are handled by the binder. + // We are only looking for const declarations that step on let\const declarations from a + // different scope. e.g.: + // { + // const x = 0; // localDeclarationSymbol obtained after name resolution will correspond to this declaration + // const x = 0; // symbol for this declaration will be 'symbol' + // } + // skip block-scoped variables and parameters + if ((ts.getCombinedNodeFlags(node) & 3 /* BlockScoped */) !== 0 || ts.isParameterDeclaration(node)) { + return; + } + // skip variable declarations that don't have initializers + // NOTE: in ES6 spec initializer is required in variable declarations where name is binding pattern + // so we'll always treat binding elements as initialized + if (node.kind === 237 /* VariableDeclaration */ && !node.initializer) { + return; + } + var symbol = getSymbolOfNode(node); + if (symbol.flags & 1 /* FunctionScopedVariable */) { + if (!ts.isIdentifier(node.name)) + return ts.Debug.fail(); + var localDeclarationSymbol = resolveName(node, node.name.escapedText, 3 /* Variable */, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); + if (localDeclarationSymbol && + localDeclarationSymbol !== symbol && + localDeclarationSymbol.flags & 2 /* BlockScopedVariable */) { + if (getDeclarationNodeFlagsFromSymbol(localDeclarationSymbol) & 3 /* BlockScoped */) { + var varDeclList = ts.getAncestor(localDeclarationSymbol.valueDeclaration, 238 /* VariableDeclarationList */); + var container = varDeclList.parent.kind === 219 /* VariableStatement */ && varDeclList.parent.parent + ? varDeclList.parent.parent + : undefined; + // names of block-scoped and function scoped variables can collide only + // if block scoped variable is defined in the function\module\source file scope (because of variable hoisting) + var namesShareScope = container && + (container.kind === 218 /* Block */ && ts.isFunctionLike(container.parent) || + container.kind === 245 /* ModuleBlock */ || + container.kind === 244 /* ModuleDeclaration */ || + container.kind === 279 /* SourceFile */); + // here we know that function scoped variable is shadowed by block scoped one + // if they are defined in the same scope - binder has already reported redeclaration error + // otherwise if variable has an initializer - show error that initialization will fail + // since LHS will be block scoped name instead of function scoped + if (!namesShareScope) { + var name = symbolToString(localDeclarationSymbol); + error(node, ts.Diagnostics.Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1, name, name); + } + } + } + } + } + // Check that a parameter initializer contains no references to parameters declared to the right of itself + function checkParameterInitializer(node) { + if (ts.getRootDeclaration(node).kind !== 151 /* Parameter */) { + return; + } + var func = ts.getContainingFunction(node); + visit(node.initializer); + function visit(n) { + if (ts.isTypeNode(n) || ts.isDeclarationName(n)) { + // do not dive in types + // skip declaration names (i.e. in object literal expressions) + return; + } + if (n.kind === 189 /* PropertyAccessExpression */) { + // skip property names in property access expression + return visit(n.expression); + } + else if (n.kind === 72 /* Identifier */) { + // check FunctionLikeDeclaration.locals (stores parameters\function local variable) + // if it contains entry with a specified name + var symbol = resolveName(n, n.escapedText, 67220415 /* Value */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); + if (!symbol || symbol === unknownSymbol || !symbol.valueDeclaration) { + return; + } + if (symbol.valueDeclaration === node) { + error(n, ts.Diagnostics.Parameter_0_cannot_be_referenced_in_its_initializer, ts.declarationNameToString(node.name)); + return; + } + // locals map for function contain both parameters and function locals + // so we need to do a bit of extra work to check if reference is legal + var enclosingContainer = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); + if (enclosingContainer === func) { + if (symbol.valueDeclaration.kind === 151 /* Parameter */ || + symbol.valueDeclaration.kind === 186 /* BindingElement */) { + // it is ok to reference parameter in initializer if either + // - parameter is located strictly on the left of current parameter declaration + if (symbol.valueDeclaration.pos < node.pos) { + return; + } + // - parameter is wrapped in function-like entity + if (ts.findAncestor(n, function (current) { + if (current === node.initializer) { + return "quit"; + } + return ts.isFunctionLike(current.parent) || + // computed property names/initializers in instance property declaration of class like entities + // are executed in constructor and thus deferred + (current.parent.kind === 154 /* PropertyDeclaration */ && + !(ts.hasModifier(current.parent, 32 /* Static */)) && + ts.isClassLike(current.parent.parent)); + })) { + return; + } + // fall through to report error + } + error(n, ts.Diagnostics.Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it, ts.declarationNameToString(node.name), ts.declarationNameToString(n)); + } + } + else { + return ts.forEachChild(n, visit); + } + } + } + function convertAutoToAny(type) { + return type === autoType ? anyType : type === autoArrayType ? anyArrayType : type; + } + // Check variable, parameter, or property declaration + function checkVariableLikeDeclaration(node) { + checkDecorators(node); + if (!ts.isBindingElement(node)) { + checkSourceElement(node.type); + } + // JSDoc `function(string, string): string` syntax results in parameters with no name + if (!node.name) { + return; + } + // For a computed property, just check the initializer and exit + // Do not use hasDynamicName here, because that returns false for well known symbols. + // We want to perform checkComputedPropertyName for all computed properties, including + // well known symbols. + if (node.name.kind === 149 /* ComputedPropertyName */) { + checkComputedPropertyName(node.name); + if (node.initializer) { + checkExpressionCached(node.initializer); + } + } + if (node.kind === 186 /* BindingElement */) { + if (node.parent.kind === 184 /* ObjectBindingPattern */ && languageVersion < 6 /* ESNext */) { + checkExternalEmitHelpers(node, 4 /* Rest */); + } + // check computed properties inside property names of binding elements + if (node.propertyName && node.propertyName.kind === 149 /* ComputedPropertyName */) { + checkComputedPropertyName(node.propertyName); + } + // check private/protected variable access + var parent = node.parent.parent; + var parentType = getTypeForBindingElementParent(parent); + var name = node.propertyName || node.name; + if (!ts.isBindingPattern(name)) { + var nameText = ts.getTextOfPropertyName(name); + if (nameText) { + var property = getPropertyOfType(parentType, nameText); // TODO: GH#18217 + if (property) { + markPropertyAsReferenced(property, /*nodeForCheckWriteOnly*/ undefined, /*isThisAccess*/ false); // A destructuring is never a write-only reference. + checkPropertyAccessibility(parent, !!parent.initializer && parent.initializer.kind === 98 /* SuperKeyword */, parentType, property); + } + } + } + } + // For a binding pattern, check contained binding elements + if (ts.isBindingPattern(node.name)) { + if (node.name.kind === 185 /* ArrayBindingPattern */ && languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) { + checkExternalEmitHelpers(node, 512 /* Read */); + } + ts.forEach(node.name.elements, checkSourceElement); + } + // For a parameter declaration with an initializer, error and exit if the containing function doesn't have a body + if (node.initializer && ts.getRootDeclaration(node).kind === 151 /* Parameter */ && ts.nodeIsMissing(ts.getContainingFunction(node).body)) { + error(node, ts.Diagnostics.A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation); + return; + } + // For a binding pattern, validate the initializer and exit + if (ts.isBindingPattern(node.name)) { + // Don't validate for-in initializer as it is already an error + if (node.initializer && node.parent.parent.kind !== 226 /* ForInStatement */) { + var initializerType = checkExpressionCached(node.initializer); + if (strictNullChecks && node.name.elements.length === 0) { + checkNonNullType(initializerType, node); + } + else { + checkTypeAssignableToAndOptionallyElaborate(initializerType, getWidenedTypeForVariableLikeDeclaration(node), node, node.initializer); + } + checkParameterInitializer(node); + } + return; + } + var symbol = getSymbolOfNode(node); + var type = convertAutoToAny(getTypeOfSymbol(symbol)); + if (node === symbol.valueDeclaration) { + // Node is the primary declaration of the symbol, just validate the initializer + // Don't validate for-in initializer as it is already an error + var initializer = ts.getEffectiveInitializer(node); + if (initializer) { + var isJSObjectLiteralInitializer = ts.isInJSFile(node) && + ts.isObjectLiteralExpression(initializer) && + (initializer.properties.length === 0 || ts.isPrototypeAccess(node.name)) && + ts.hasEntries(symbol.exports); + if (!isJSObjectLiteralInitializer && node.parent.parent.kind !== 226 /* ForInStatement */) { + checkTypeAssignableToAndOptionallyElaborate(checkExpressionCached(initializer), type, node, initializer, /*headMessage*/ undefined); + checkParameterInitializer(node); + } + } + if (symbol.declarations.length > 1) { + if (ts.some(symbol.declarations, function (d) { return d !== node && ts.isVariableLike(d) && !areDeclarationFlagsIdentical(d, node); })) { + error(node.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); + } + } + } + else { + // Node is a secondary declaration, check that type is identical to primary declaration and check that + // initializer is consistent with type associated with the node + var declarationType = convertAutoToAny(getWidenedTypeForVariableLikeDeclaration(node)); + if (type !== errorType && declarationType !== errorType && + !isTypeIdenticalTo(type, declarationType) && + !(symbol.flags & 67108864 /* Assignment */)) { + errorNextVariableOrPropertyDeclarationMustHaveSameType(type, node, declarationType); + } + if (node.initializer) { + checkTypeAssignableToAndOptionallyElaborate(checkExpressionCached(node.initializer), declarationType, node, node.initializer, /*headMessage*/ undefined); + } + if (!areDeclarationFlagsIdentical(node, symbol.valueDeclaration)) { + error(node.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); + } + } + if (node.kind !== 154 /* PropertyDeclaration */ && node.kind !== 153 /* PropertySignature */) { + // We know we don't have a binding pattern or computed name here + checkExportsOnMergedDeclarations(node); + if (node.kind === 237 /* VariableDeclaration */ || node.kind === 186 /* BindingElement */) { + checkVarDeclaredNamesNotShadowed(node); + } + checkCollisionWithRequireExportsInGeneratedCode(node, node.name); + checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); + } + } + function errorNextVariableOrPropertyDeclarationMustHaveSameType(firstType, nextDeclaration, nextType) { + var nextDeclarationName = ts.getNameOfDeclaration(nextDeclaration); + var message = nextDeclaration.kind === 154 /* PropertyDeclaration */ || nextDeclaration.kind === 153 /* PropertySignature */ + ? ts.Diagnostics.Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_type_2 + : ts.Diagnostics.Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2; + error(nextDeclarationName, message, ts.declarationNameToString(nextDeclarationName), typeToString(firstType), typeToString(nextType)); + } + function areDeclarationFlagsIdentical(left, right) { + if ((left.kind === 151 /* Parameter */ && right.kind === 237 /* VariableDeclaration */) || + (left.kind === 237 /* VariableDeclaration */ && right.kind === 151 /* Parameter */)) { + // Differences in optionality between parameters and variables are allowed. + return true; + } + if (ts.hasQuestionToken(left) !== ts.hasQuestionToken(right)) { + return false; + } + var interestingFlags = 8 /* Private */ | + 16 /* Protected */ | + 256 /* Async */ | + 128 /* Abstract */ | + 64 /* Readonly */ | + 32 /* Static */; + return ts.getSelectedModifierFlags(left, interestingFlags) === ts.getSelectedModifierFlags(right, interestingFlags); + } + function checkVariableDeclaration(node) { + checkGrammarVariableDeclaration(node); + return checkVariableLikeDeclaration(node); + } + function checkBindingElement(node) { + checkGrammarBindingElement(node); + return checkVariableLikeDeclaration(node); + } + function checkVariableStatement(node) { + // Grammar checking + if (!checkGrammarDecoratorsAndModifiers(node) && !checkGrammarVariableDeclarationList(node.declarationList)) + checkGrammarForDisallowedLetOrConstStatement(node); + ts.forEach(node.declarationList.declarations, checkSourceElement); + } + function checkExpressionStatement(node) { + // Grammar checking + checkGrammarStatementInAmbientContext(node); + checkExpression(node.expression); + } + function checkIfStatement(node) { + // Grammar checking + checkGrammarStatementInAmbientContext(node); + checkTruthinessExpression(node.expression); + checkSourceElement(node.thenStatement); + if (node.thenStatement.kind === 220 /* EmptyStatement */) { + error(node.thenStatement, ts.Diagnostics.The_body_of_an_if_statement_cannot_be_the_empty_statement); + } + checkSourceElement(node.elseStatement); + } + function checkDoStatement(node) { + // Grammar checking + checkGrammarStatementInAmbientContext(node); + checkSourceElement(node.statement); + checkTruthinessExpression(node.expression); + } + function checkWhileStatement(node) { + // Grammar checking + checkGrammarStatementInAmbientContext(node); + checkTruthinessExpression(node.expression); + checkSourceElement(node.statement); + } + function checkTruthinessExpression(node, checkMode) { + var type = checkExpression(node, checkMode); + if (type.flags & 16384 /* Void */) { + error(node, ts.Diagnostics.An_expression_of_type_void_cannot_be_tested_for_truthiness); + } + return type; + } + function checkForStatement(node) { + // Grammar checking + if (!checkGrammarStatementInAmbientContext(node)) { + if (node.initializer && node.initializer.kind === 238 /* VariableDeclarationList */) { + checkGrammarVariableDeclarationList(node.initializer); + } + } + if (node.initializer) { + if (node.initializer.kind === 238 /* VariableDeclarationList */) { + ts.forEach(node.initializer.declarations, checkVariableDeclaration); + } + else { + checkExpression(node.initializer); + } + } + if (node.condition) + checkTruthinessExpression(node.condition); + if (node.incrementor) + checkExpression(node.incrementor); + checkSourceElement(node.statement); + if (node.locals) { + registerForUnusedIdentifiersCheck(node); + } + } + function checkForOfStatement(node) { + checkGrammarForInOrForOfStatement(node); + if (node.awaitModifier) { + var functionFlags = ts.getFunctionFlags(ts.getContainingFunction(node)); + if ((functionFlags & (4 /* Invalid */ | 2 /* Async */)) === 2 /* Async */ && languageVersion < 6 /* ESNext */) { + // for..await..of in an async function or async generator function prior to ESNext requires the __asyncValues helper + checkExternalEmitHelpers(node, 16384 /* ForAwaitOfIncludes */); + } + } + else if (compilerOptions.downlevelIteration && languageVersion < 2 /* ES2015 */) { + // for..of prior to ES2015 requires the __values helper when downlevelIteration is enabled + checkExternalEmitHelpers(node, 256 /* ForOfIncludes */); + } + // Check the LHS and RHS + // If the LHS is a declaration, just check it as a variable declaration, which will in turn check the RHS + // via checkRightHandSideOfForOf. + // If the LHS is an expression, check the LHS, as a destructuring assignment or as a reference. + // Then check that the RHS is assignable to it. + if (node.initializer.kind === 238 /* VariableDeclarationList */) { + checkForInOrForOfVariableDeclaration(node); + } + else { + var varExpr = node.initializer; + var iteratedType = checkRightHandSideOfForOf(node.expression, node.awaitModifier); + // There may be a destructuring assignment on the left side + if (varExpr.kind === 187 /* ArrayLiteralExpression */ || varExpr.kind === 188 /* ObjectLiteralExpression */) { + // iteratedType may be undefined. In this case, we still want to check the structure of + // varExpr, in particular making sure it's a valid LeftHandSideExpression. But we'd like + // to short circuit the type relation checking as much as possible, so we pass the unknownType. + checkDestructuringAssignment(varExpr, iteratedType || errorType); + } + else { + var leftType = checkExpression(varExpr); + checkReferenceExpression(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access); + // iteratedType will be undefined if the rightType was missing properties/signatures + // required to get its iteratedType (like [Symbol.iterator] or next). This may be + // because we accessed properties from anyType, or it may have led to an error inside + // getElementTypeOfIterable. + if (iteratedType) { + checkTypeAssignableToAndOptionallyElaborate(iteratedType, leftType, varExpr, node.expression); + } + } + } + checkSourceElement(node.statement); + if (node.locals) { + registerForUnusedIdentifiersCheck(node); + } + } + function checkForInStatement(node) { + // Grammar checking + checkGrammarForInOrForOfStatement(node); + var rightType = getNonNullableTypeIfNeeded(checkExpression(node.expression)); + // TypeScript 1.0 spec (April 2014): 5.4 + // In a 'for-in' statement of the form + // for (let VarDecl in Expr) Statement + // VarDecl must be a variable declaration without a type annotation that declares a variable of type Any, + // and Expr must be an expression of type Any, an object type, or a type parameter type. + if (node.initializer.kind === 238 /* VariableDeclarationList */) { + var variable = node.initializer.declarations[0]; + if (variable && ts.isBindingPattern(variable.name)) { + error(variable.name, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern); + } + checkForInOrForOfVariableDeclaration(node); + } + else { + // In a 'for-in' statement of the form + // for (Var in Expr) Statement + // Var must be an expression classified as a reference of type Any or the String primitive type, + // and Expr must be an expression of type Any, an object type, or a type parameter type. + var varExpr = node.initializer; + var leftType = checkExpression(varExpr); + if (varExpr.kind === 187 /* ArrayLiteralExpression */ || varExpr.kind === 188 /* ObjectLiteralExpression */) { + error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern); + } + else if (!isTypeAssignableTo(getIndexTypeOrString(rightType), leftType)) { + error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any); + } + else { + // run check only former check succeeded to avoid cascading errors + checkReferenceExpression(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access); + } + } + // unknownType is returned i.e. if node.expression is identifier whose name cannot be resolved + // in this case error about missing name is already reported - do not report extra one + if (rightType === neverType || !isTypeAssignableToKind(rightType, 67108864 /* NonPrimitive */ | 58982400 /* InstantiableNonPrimitive */)) { + error(node.expression, ts.Diagnostics.The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_but_here_has_type_0, typeToString(rightType)); + } + checkSourceElement(node.statement); + if (node.locals) { + registerForUnusedIdentifiersCheck(node); + } + } + function checkForInOrForOfVariableDeclaration(iterationStatement) { + var variableDeclarationList = iterationStatement.initializer; + // checkGrammarForInOrForOfStatement will check that there is exactly one declaration. + if (variableDeclarationList.declarations.length >= 1) { + var decl = variableDeclarationList.declarations[0]; + checkVariableDeclaration(decl); + } + } + function checkRightHandSideOfForOf(rhsExpression, awaitModifier) { + var expressionType = checkNonNullExpression(rhsExpression); + return checkIteratedTypeOrElementType(expressionType, rhsExpression, /*allowStringInput*/ true, awaitModifier !== undefined); + } + function checkIteratedTypeOrElementType(inputType, errorNode, allowStringInput, allowAsyncIterables) { + if (isTypeAny(inputType)) { + return inputType; + } + return getIteratedTypeOrElementType(inputType, errorNode, allowStringInput, allowAsyncIterables, /*checkAssignability*/ true) || anyType; + } + /** + * When consuming an iterable type in a for..of, spread, or iterator destructuring assignment + * we want to get the iterated type of an iterable for ES2015 or later, or the iterated type + * of a iterable (if defined globally) or element type of an array like for ES2015 or earlier. + */ + function getIteratedTypeOrElementType(inputType, errorNode, allowStringInput, allowAsyncIterables, checkAssignability) { + if (inputType === neverType) { + reportTypeNotIterableError(errorNode, inputType, allowAsyncIterables); // TODO: GH#18217 + return undefined; + } + var uplevelIteration = languageVersion >= 2 /* ES2015 */; + var downlevelIteration = !uplevelIteration && compilerOptions.downlevelIteration; + // Get the iterated type of an `Iterable` or `IterableIterator` only in ES2015 + // or higher, when inside of an async generator or for-await-if, or when + // downlevelIteration is requested. + if (uplevelIteration || downlevelIteration || allowAsyncIterables) { + // We only report errors for an invalid iterable type in ES2015 or higher. + var iteratedType = getIteratedTypeOfIterable(inputType, uplevelIteration ? errorNode : undefined, allowAsyncIterables, /*allowSyncIterables*/ true, checkAssignability); + if (iteratedType || uplevelIteration) { + return iteratedType; + } + } + var arrayType = inputType; + var reportedError = false; + var hasStringConstituent = false; + // If strings are permitted, remove any string-like constituents from the array type. + // This allows us to find other non-string element types from an array unioned with + // a string. + if (allowStringInput) { + if (arrayType.flags & 1048576 /* Union */) { + // After we remove all types that are StringLike, we will know if there was a string constituent + // based on whether the result of filter is a new array. + var arrayTypes = inputType.types; + var filteredTypes = ts.filter(arrayTypes, function (t) { return !(t.flags & 132 /* StringLike */); }); + if (filteredTypes !== arrayTypes) { + arrayType = getUnionType(filteredTypes, 2 /* Subtype */); + } + } + else if (arrayType.flags & 132 /* StringLike */) { + arrayType = neverType; + } + hasStringConstituent = arrayType !== inputType; + if (hasStringConstituent) { + if (languageVersion < 1 /* ES5 */) { + if (errorNode) { + error(errorNode, ts.Diagnostics.Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher); + reportedError = true; + } + } + // Now that we've removed all the StringLike types, if no constituents remain, then the entire + // arrayOrStringType was a string. + if (arrayType.flags & 131072 /* Never */) { + return stringType; + } + } + } + if (!isArrayLikeType(arrayType)) { + if (errorNode && !reportedError) { + // Which error we report depends on whether we allow strings or if there was a + // string constituent. For example, if the input type is number | string, we + // want to say that number is not an array type. But if the input was just + // number and string input is allowed, we want to say that number is not an + // array type or a string type. + var isIterable = !!getIteratedTypeOfIterable(inputType, /* errorNode */ undefined, allowAsyncIterables, /*allowSyncIterables*/ true, checkAssignability); + var diagnostic = !allowStringInput || hasStringConstituent + ? downlevelIteration + ? ts.Diagnostics.Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator + : isIterable + ? ts.Diagnostics.Type_0_is_not_an_array_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators + : ts.Diagnostics.Type_0_is_not_an_array_type + : downlevelIteration + ? ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator + : isIterable + ? ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators + : ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type; + error(errorNode, diagnostic, typeToString(arrayType)); + } + return hasStringConstituent ? stringType : undefined; + } + var arrayElementType = getIndexTypeOfType(arrayType, 1 /* Number */); + if (hasStringConstituent && arrayElementType) { + // This is just an optimization for the case where arrayOrStringType is string | string[] + if (arrayElementType.flags & 132 /* StringLike */) { + return stringType; + } + return getUnionType([arrayElementType, stringType], 2 /* Subtype */); + } + return arrayElementType; + } + /** + * We want to treat type as an iterable, and get the type it is an iterable of. The iterable + * must have the following structure (annotated with the names of the variables below): + * + * { // iterable + * [Symbol.iterator]: { // iteratorMethod + * (): Iterator + * } + * } + * + * For an async iterable, we expect the following structure: + * + * { // iterable + * [Symbol.asyncIterator]: { // iteratorMethod + * (): AsyncIterator + * } + * } + * + * T is the type we are after. At every level that involves analyzing return types + * of signatures, we union the return types of all the signatures. + * + * Another thing to note is that at any step of this process, we could run into a dead end, + * meaning either the property is missing, or we run into the anyType. If either of these things + * happens, we return undefined to signal that we could not find the iterated type. If a property + * is missing, and the previous step did not result in 'any', then we also give an error if the + * caller requested it. Then the caller can decide what to do in the case where there is no iterated + * type. This is different from returning anyType, because that would signify that we have matched the + * whole pattern and that T (above) is 'any'. + * + * For a **for-of** statement, `yield*` (in a normal generator), spread, array + * destructuring, or normal generator we will only ever look for a `[Symbol.iterator]()` + * method. + * + * For an async generator we will only ever look at the `[Symbol.asyncIterator]()` method. + * + * For a **for-await-of** statement or a `yield*` in an async generator we will look for + * the `[Symbol.asyncIterator]()` method first, and then the `[Symbol.iterator]()` method. + */ + function getIteratedTypeOfIterable(type, errorNode, allowAsyncIterables, allowSyncIterables, checkAssignability) { + if (isTypeAny(type)) { + return undefined; + } + return mapType(type, getIteratedType); + function getIteratedType(type) { + var typeAsIterable = type; + if (allowAsyncIterables) { + if (typeAsIterable.iteratedTypeOfAsyncIterable) { + return typeAsIterable.iteratedTypeOfAsyncIterable; + } + // As an optimization, if the type is an instantiation of the global `AsyncIterable` + // or the global `AsyncIterableIterator` then just grab its type argument. + if (isReferenceToType(type, getGlobalAsyncIterableType(/*reportErrors*/ false)) || + isReferenceToType(type, getGlobalAsyncIterableIteratorType(/*reportErrors*/ false))) { + return typeAsIterable.iteratedTypeOfAsyncIterable = type.typeArguments[0]; + } + } + if (allowSyncIterables) { + if (typeAsIterable.iteratedTypeOfIterable) { + return allowAsyncIterables + ? typeAsIterable.iteratedTypeOfAsyncIterable = getAwaitedType(typeAsIterable.iteratedTypeOfIterable) + : typeAsIterable.iteratedTypeOfIterable; + } + // As an optimization, if the type is an instantiation of the global `Iterable` or + // `IterableIterator` then just grab its type argument. + if (isReferenceToType(type, getGlobalIterableType(/*reportErrors*/ false)) || + isReferenceToType(type, getGlobalIterableIteratorType(/*reportErrors*/ false))) { + return allowAsyncIterables + ? typeAsIterable.iteratedTypeOfAsyncIterable = getAwaitedType(type.typeArguments[0]) + : typeAsIterable.iteratedTypeOfIterable = type.typeArguments[0]; + } + } + var asyncMethodType = allowAsyncIterables && getTypeOfPropertyOfType(type, ts.getPropertyNameForKnownSymbolName("asyncIterator")); + var methodType = asyncMethodType || (allowSyncIterables ? getTypeOfPropertyOfType(type, ts.getPropertyNameForKnownSymbolName("iterator")) : undefined); + if (isTypeAny(methodType)) { + return undefined; + } + var signatures = methodType ? getSignaturesOfType(methodType, 0 /* Call */) : undefined; + if (!ts.some(signatures)) { + if (errorNode) { + // only report on the first error + reportTypeNotIterableError(errorNode, type, allowAsyncIterables); + errorNode = undefined; + } + return undefined; + } + var returnType = getUnionType(ts.map(signatures, getReturnTypeOfSignature), 2 /* Subtype */); + var iteratedType = getIteratedTypeOfIterator(returnType, errorNode, /*isAsyncIterator*/ !!asyncMethodType); + if (checkAssignability && errorNode && iteratedType) { + // If `checkAssignability` was specified, we were called from + // `checkIteratedTypeOrElementType`. As such, we need to validate that + // the type passed in is actually an Iterable. + checkTypeAssignableTo(type, asyncMethodType + ? createAsyncIterableType(iteratedType) + : createIterableType(iteratedType), errorNode); + } + if (iteratedType) { + return allowAsyncIterables + ? typeAsIterable.iteratedTypeOfAsyncIterable = asyncMethodType ? iteratedType : getAwaitedType(iteratedType) + : typeAsIterable.iteratedTypeOfIterable = iteratedType; + } + } + } + function reportTypeNotIterableError(errorNode, type, allowAsyncIterables) { + error(errorNode, allowAsyncIterables + ? ts.Diagnostics.Type_0_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator + : ts.Diagnostics.Type_0_must_have_a_Symbol_iterator_method_that_returns_an_iterator, typeToString(type)); + } + /** + * This function has very similar logic as getIteratedTypeOfIterable, except that it operates on + * Iterators instead of Iterables. Here is the structure: + * + * { // iterator + * next: { // nextMethod + * (): { // nextResult + * value: T // nextValue + * } + * } + * } + * + * For an async iterator, we expect the following structure: + * + * { // iterator + * next: { // nextMethod + * (): PromiseLike<{ // nextResult + * value: T // nextValue + * }> + * } + * } + */ + function getIteratedTypeOfIterator(type, errorNode, isAsyncIterator) { + if (isTypeAny(type)) { + return undefined; + } + var typeAsIterator = type; + if (isAsyncIterator ? typeAsIterator.iteratedTypeOfAsyncIterator : typeAsIterator.iteratedTypeOfIterator) { + return isAsyncIterator ? typeAsIterator.iteratedTypeOfAsyncIterator : typeAsIterator.iteratedTypeOfIterator; + } + // As an optimization, if the type is an instantiation of the global `Iterator` (for + // a non-async iterator) or the global `AsyncIterator` (for an async-iterator) then + // just grab its type argument. + var getIteratorType = isAsyncIterator ? getGlobalAsyncIteratorType : getGlobalIteratorType; + if (isReferenceToType(type, getIteratorType(/*reportErrors*/ false))) { + return isAsyncIterator + ? typeAsIterator.iteratedTypeOfAsyncIterator = type.typeArguments[0] + : typeAsIterator.iteratedTypeOfIterator = type.typeArguments[0]; + } + // Both async and non-async iterators must have a `next` method. + var nextMethod = getTypeOfPropertyOfType(type, "next"); + if (isTypeAny(nextMethod)) { + return undefined; + } + var nextMethodSignatures = nextMethod ? getSignaturesOfType(nextMethod, 0 /* Call */) : ts.emptyArray; + if (nextMethodSignatures.length === 0) { + if (errorNode) { + error(errorNode, isAsyncIterator + ? ts.Diagnostics.An_async_iterator_must_have_a_next_method + : ts.Diagnostics.An_iterator_must_have_a_next_method); + } + return undefined; + } + var nextResult = getUnionType(ts.map(nextMethodSignatures, getReturnTypeOfSignature), 2 /* Subtype */); + if (isTypeAny(nextResult)) { + return undefined; + } + // For an async iterator, we must get the awaited type of the return type. + if (isAsyncIterator) { + nextResult = getAwaitedTypeOfPromise(nextResult, errorNode, ts.Diagnostics.The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property); + if (isTypeAny(nextResult)) { + return undefined; + } + } + var nextValue = nextResult && getTypeOfPropertyOfType(nextResult, "value"); + if (!nextValue) { + if (errorNode) { + error(errorNode, isAsyncIterator + ? ts.Diagnostics.The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property + : ts.Diagnostics.The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property); + } + return undefined; + } + return isAsyncIterator + ? typeAsIterator.iteratedTypeOfAsyncIterator = nextValue + : typeAsIterator.iteratedTypeOfIterator = nextValue; + } + /** + * A generator may have a return type of `Iterator`, `Iterable`, or + * `IterableIterator`. An async generator may have a return type of `AsyncIterator`, + * `AsyncIterable`, or `AsyncIterableIterator`. This function can be used to extract + * the iterated type from this return type for contextual typing and verifying signatures. + */ + function getIteratedTypeOfGenerator(returnType, isAsyncGenerator) { + if (isTypeAny(returnType)) { + return undefined; + } + return getIteratedTypeOfIterable(returnType, /*errorNode*/ undefined, /*allowAsyncIterables*/ isAsyncGenerator, /*allowSyncIterables*/ !isAsyncGenerator, /*checkAssignability*/ false) + || getIteratedTypeOfIterator(returnType, /*errorNode*/ undefined, isAsyncGenerator); + } + function checkBreakOrContinueStatement(node) { + // Grammar checking + if (!checkGrammarStatementInAmbientContext(node)) + checkGrammarBreakOrContinueStatement(node); + // TODO: Check that target label is valid + } + function isUnwrappedReturnTypeVoidOrAny(func, returnType) { + var unwrappedReturnType = (ts.getFunctionFlags(func) & 3 /* AsyncGenerator */) === 2 /* Async */ + ? getPromisedTypeOfPromise(returnType) // Async function + : returnType; // AsyncGenerator function, Generator function, or normal function + return !!unwrappedReturnType && maybeTypeOfKind(unwrappedReturnType, 16384 /* Void */ | 3 /* AnyOrUnknown */); + } + function checkReturnStatement(node) { + // Grammar checking + if (checkGrammarStatementInAmbientContext(node)) { + return; + } + var func = ts.getContainingFunction(node); + if (!func) { + grammarErrorOnFirstToken(node, ts.Diagnostics.A_return_statement_can_only_be_used_within_a_function_body); + return; + } + var signature = getSignatureFromDeclaration(func); + var returnType = getReturnTypeOfSignature(signature); + var functionFlags = ts.getFunctionFlags(func); + var isGenerator = functionFlags & 1 /* Generator */; + if (strictNullChecks || node.expression || returnType.flags & 131072 /* Never */) { + var exprType = node.expression ? checkExpressionCached(node.expression) : undefinedType; + if (isGenerator) { // AsyncGenerator function or Generator function + // A generator does not need its return expressions checked against its return type. + // Instead, the yield expressions are checked against the element type. + // TODO: Check return types of generators when return type tracking is added + // for generators. + return; + } + else if (func.kind === 159 /* SetAccessor */) { + if (node.expression) { + error(node, ts.Diagnostics.Setters_cannot_return_a_value); + } + } + else if (func.kind === 157 /* Constructor */) { + if (node.expression && !checkTypeAssignableToAndOptionallyElaborate(exprType, returnType, node, node.expression)) { + error(node, ts.Diagnostics.Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class); + } + } + else if (getReturnTypeFromAnnotation(func)) { + if (functionFlags & 2 /* Async */) { // Async function + var promisedType = getPromisedTypeOfPromise(returnType); + var awaitedType = checkAwaitedType(exprType, node, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); + if (promisedType) { + // If the function has a return type, but promisedType is + // undefined, an error will be reported in checkAsyncFunctionReturnType + // so we don't need to report one here. + checkTypeAssignableTo(awaitedType, promisedType, node); + } + } + else { + checkTypeAssignableToAndOptionallyElaborate(exprType, returnType, node, node.expression); + } + } + } + else if (func.kind !== 157 /* Constructor */ && compilerOptions.noImplicitReturns && !isUnwrappedReturnTypeVoidOrAny(func, returnType) && !isGenerator) { + // The function has a return type, but the return statement doesn't have an expression. + error(node, ts.Diagnostics.Not_all_code_paths_return_a_value); + } + } + function checkWithStatement(node) { + // Grammar checking for withStatement + if (!checkGrammarStatementInAmbientContext(node)) { + if (node.flags & 16384 /* AwaitContext */) { + grammarErrorOnFirstToken(node, ts.Diagnostics.with_statements_are_not_allowed_in_an_async_function_block); + } + } + checkExpression(node.expression); + var sourceFile = ts.getSourceFileOfNode(node); + if (!hasParseDiagnostics(sourceFile)) { + var start = ts.getSpanOfTokenAtPosition(sourceFile, node.pos).start; + var end = node.statement.pos; + grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any); + } + } + function checkSwitchStatement(node) { + // Grammar checking + checkGrammarStatementInAmbientContext(node); + var firstDefaultClause; + var hasDuplicateDefaultClause = false; + var expressionType = checkExpression(node.expression); + var expressionIsLiteral = isLiteralType(expressionType); + ts.forEach(node.caseBlock.clauses, function (clause) { + // Grammar check for duplicate default clauses, skip if we already report duplicate default clause + if (clause.kind === 272 /* DefaultClause */ && !hasDuplicateDefaultClause) { + if (firstDefaultClause === undefined) { + firstDefaultClause = clause; + } + else { + var sourceFile = ts.getSourceFileOfNode(node); + var start = ts.skipTrivia(sourceFile.text, clause.pos); + var end = clause.statements.length > 0 ? clause.statements[0].pos : clause.end; + grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.A_default_clause_cannot_appear_more_than_once_in_a_switch_statement); + hasDuplicateDefaultClause = true; + } + } + if (produceDiagnostics && clause.kind === 271 /* CaseClause */) { + // TypeScript 1.0 spec (April 2014): 5.9 + // In a 'switch' statement, each 'case' expression must be of a type that is comparable + // to or from the type of the 'switch' expression. + var caseType = checkExpression(clause.expression); + var caseIsLiteral = isLiteralType(caseType); + var comparedExpressionType = expressionType; + if (!caseIsLiteral || !expressionIsLiteral) { + caseType = caseIsLiteral ? getBaseTypeOfLiteralType(caseType) : caseType; + comparedExpressionType = getBaseTypeOfLiteralType(expressionType); + } + if (!isTypeEqualityComparableTo(comparedExpressionType, caseType)) { + // expressionType is not comparable to caseType, try the reversed check and report errors if it fails + checkTypeComparableTo(caseType, comparedExpressionType, clause.expression, /*headMessage*/ undefined); + } + } + ts.forEach(clause.statements, checkSourceElement); + }); + if (node.caseBlock.locals) { + registerForUnusedIdentifiersCheck(node.caseBlock); + } + } + function checkLabeledStatement(node) { + // Grammar checking + if (!checkGrammarStatementInAmbientContext(node)) { + ts.findAncestor(node.parent, function (current) { + if (ts.isFunctionLike(current)) { + return "quit"; + } + if (current.kind === 233 /* LabeledStatement */ && current.label.escapedText === node.label.escapedText) { + grammarErrorOnNode(node.label, ts.Diagnostics.Duplicate_label_0, ts.getTextOfNode(node.label)); + return true; + } + return false; + }); + } + // ensure that label is unique + checkSourceElement(node.statement); + } + function checkThrowStatement(node) { + // Grammar checking + if (!checkGrammarStatementInAmbientContext(node)) { + if (node.expression === undefined) { + grammarErrorAfterFirstToken(node, ts.Diagnostics.Line_break_not_permitted_here); + } + } + if (node.expression) { + checkExpression(node.expression); + } + } + function checkTryStatement(node) { + // Grammar checking + checkGrammarStatementInAmbientContext(node); + checkBlock(node.tryBlock); + var catchClause = node.catchClause; + if (catchClause) { + // Grammar checking + if (catchClause.variableDeclaration) { + if (catchClause.variableDeclaration.type) { + grammarErrorOnFirstToken(catchClause.variableDeclaration.type, ts.Diagnostics.Catch_clause_variable_cannot_have_a_type_annotation); + } + else if (catchClause.variableDeclaration.initializer) { + grammarErrorOnFirstToken(catchClause.variableDeclaration.initializer, ts.Diagnostics.Catch_clause_variable_cannot_have_an_initializer); + } + else { + var blockLocals_1 = catchClause.block.locals; + if (blockLocals_1) { + ts.forEachKey(catchClause.locals, function (caughtName) { + var blockLocal = blockLocals_1.get(caughtName); + if (blockLocal && (blockLocal.flags & 2 /* BlockScopedVariable */) !== 0) { + grammarErrorOnNode(blockLocal.valueDeclaration, ts.Diagnostics.Cannot_redeclare_identifier_0_in_catch_clause, caughtName); + } + }); + } + } + } + checkBlock(catchClause.block); + } + if (node.finallyBlock) { + checkBlock(node.finallyBlock); + } + } + function checkIndexConstraints(type) { + var declaredNumberIndexer = getIndexDeclarationOfSymbol(type.symbol, 1 /* Number */); + var declaredStringIndexer = getIndexDeclarationOfSymbol(type.symbol, 0 /* String */); + var stringIndexType = getIndexTypeOfType(type, 0 /* String */); + var numberIndexType = getIndexTypeOfType(type, 1 /* Number */); + if (stringIndexType || numberIndexType) { + ts.forEach(getPropertiesOfObjectType(type), function (prop) { + var propType = getTypeOfSymbol(prop); + checkIndexConstraintForProperty(prop, propType, type, declaredStringIndexer, stringIndexType, 0 /* String */); + checkIndexConstraintForProperty(prop, propType, type, declaredNumberIndexer, numberIndexType, 1 /* Number */); + }); + var classDeclaration = type.symbol.valueDeclaration; + if (ts.getObjectFlags(type) & 1 /* Class */ && ts.isClassLike(classDeclaration)) { + for (var _i = 0, _a = classDeclaration.members; _i < _a.length; _i++) { + var member = _a[_i]; + // Only process instance properties with computed names here. + // Static properties cannot be in conflict with indexers, + // and properties with literal names were already checked. + if (!ts.hasModifier(member, 32 /* Static */) && hasNonBindableDynamicName(member)) { + var symbol = getSymbolOfNode(member); + var propType = getTypeOfSymbol(symbol); + checkIndexConstraintForProperty(symbol, propType, type, declaredStringIndexer, stringIndexType, 0 /* String */); + checkIndexConstraintForProperty(symbol, propType, type, declaredNumberIndexer, numberIndexType, 1 /* Number */); + } + } + } + } + var errorNode; + if (stringIndexType && numberIndexType) { + errorNode = declaredNumberIndexer || declaredStringIndexer; + // condition 'errorNode === undefined' may appear if types does not declare nor string neither number indexer + if (!errorNode && (ts.getObjectFlags(type) & 2 /* Interface */)) { + var someBaseTypeHasBothIndexers = ts.forEach(getBaseTypes(type), function (base) { return getIndexTypeOfType(base, 0 /* String */) && getIndexTypeOfType(base, 1 /* Number */); }); + errorNode = someBaseTypeHasBothIndexers ? undefined : type.symbol.declarations[0]; + } + } + if (errorNode && !isTypeAssignableTo(numberIndexType, stringIndexType)) { // TODO: GH#18217 + error(errorNode, ts.Diagnostics.Numeric_index_type_0_is_not_assignable_to_string_index_type_1, typeToString(numberIndexType), typeToString(stringIndexType)); + } + function checkIndexConstraintForProperty(prop, propertyType, containingType, indexDeclaration, indexType, indexKind) { + // ESSymbol properties apply to neither string nor numeric indexers. + if (!indexType || ts.isKnownSymbol(prop)) { + return; + } + var propDeclaration = prop.valueDeclaration; + var name = propDeclaration && ts.getNameOfDeclaration(propDeclaration); + // index is numeric and property name is not valid numeric literal + if (indexKind === 1 /* Number */ && !(name ? isNumericName(name) : isNumericLiteralName(prop.escapedName))) { + return; + } + // perform property check if property or indexer is declared in 'type' + // this allows us to rule out cases when both property and indexer are inherited from the base class + var errorNode; + if (propDeclaration && name && + (propDeclaration.kind === 204 /* BinaryExpression */ || + name.kind === 149 /* ComputedPropertyName */ || + prop.parent === containingType.symbol)) { + errorNode = propDeclaration; + } + else if (indexDeclaration) { + errorNode = indexDeclaration; + } + else if (ts.getObjectFlags(containingType) & 2 /* Interface */) { + // for interfaces property and indexer might be inherited from different bases + // check if any base class already has both property and indexer. + // check should be performed only if 'type' is the first type that brings property\indexer together + var someBaseClassHasBothPropertyAndIndexer = ts.forEach(getBaseTypes(containingType), function (base) { return getPropertyOfObjectType(base, prop.escapedName) && getIndexTypeOfType(base, indexKind); }); + errorNode = someBaseClassHasBothPropertyAndIndexer ? undefined : containingType.symbol.declarations[0]; + } + if (errorNode && !isTypeAssignableTo(propertyType, indexType)) { + var errorMessage = indexKind === 0 /* String */ + ? ts.Diagnostics.Property_0_of_type_1_is_not_assignable_to_string_index_type_2 + : ts.Diagnostics.Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2; + error(errorNode, errorMessage, symbolToString(prop), typeToString(propertyType), typeToString(indexType)); + } + } + } + function checkTypeNameIsReserved(name, message) { + // TS 1.0 spec (April 2014): 3.6.1 + // The predefined type keywords are reserved and cannot be used as names of user defined types. + switch (name.escapedText) { + case "any": + case "unknown": + case "number": + case "bigint": + case "boolean": + case "string": + case "symbol": + case "void": + case "object": + error(name, message, name.escapedText); + } + } + /** + * The name cannot be used as 'Object' of user defined types with special target. + */ + function checkClassNameCollisionWithObject(name) { + if (languageVersion === 1 /* ES5 */ && name.escapedText === "Object" + && moduleKind !== ts.ModuleKind.ES2015 && moduleKind !== ts.ModuleKind.ESNext) { + error(name, ts.Diagnostics.Class_name_cannot_be_Object_when_targeting_ES5_with_module_0, ts.ModuleKind[moduleKind]); // https://github.com/Microsoft/TypeScript/issues/17494 + } + } + /** + * Check each type parameter and check that type parameters have no duplicate type parameter declarations + */ + function checkTypeParameters(typeParameterDeclarations) { + if (typeParameterDeclarations) { + var seenDefault = false; + for (var i = 0; i < typeParameterDeclarations.length; i++) { + var node = typeParameterDeclarations[i]; + checkTypeParameter(node); + if (produceDiagnostics) { + if (node.default) { + seenDefault = true; + } + else if (seenDefault) { + error(node, ts.Diagnostics.Required_type_parameters_may_not_follow_optional_type_parameters); + } + for (var j = 0; j < i; j++) { + if (typeParameterDeclarations[j].symbol === node.symbol) { + error(node.name, ts.Diagnostics.Duplicate_identifier_0, ts.declarationNameToString(node.name)); + } + } + } + } + } + } + /** Check that type parameter lists are identical across multiple declarations */ + function checkTypeParameterListsIdentical(symbol) { + if (symbol.declarations.length === 1) { + return; + } + var links = getSymbolLinks(symbol); + if (!links.typeParametersChecked) { + links.typeParametersChecked = true; + var declarations = getClassOrInterfaceDeclarationsOfSymbol(symbol); + if (declarations.length <= 1) { + return; + } + var type = getDeclaredTypeOfSymbol(symbol); + if (!areTypeParametersIdentical(declarations, type.localTypeParameters)) { + // Report an error on every conflicting declaration. + var name = symbolToString(symbol); + for (var _i = 0, declarations_6 = declarations; _i < declarations_6.length; _i++) { + var declaration = declarations_6[_i]; + error(declaration.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_type_parameters, name); + } + } + } + } + function areTypeParametersIdentical(declarations, targetParameters) { + var maxTypeArgumentCount = ts.length(targetParameters); + var minTypeArgumentCount = getMinTypeArgumentCount(targetParameters); + for (var _i = 0, declarations_7 = declarations; _i < declarations_7.length; _i++) { + var declaration = declarations_7[_i]; + // If this declaration has too few or too many type parameters, we report an error + var sourceParameters = ts.getEffectiveTypeParameterDeclarations(declaration); + var numTypeParameters = sourceParameters.length; + if (numTypeParameters < minTypeArgumentCount || numTypeParameters > maxTypeArgumentCount) { + return false; + } + for (var i = 0; i < numTypeParameters; i++) { + var source = sourceParameters[i]; + var target = targetParameters[i]; + // If the type parameter node does not have the same as the resolved type + // parameter at this position, we report an error. + if (source.name.escapedText !== target.symbol.escapedName) { + return false; + } + // If the type parameter node does not have an identical constraint as the resolved + // type parameter at this position, we report an error. + var constraint = ts.getEffectiveConstraintOfTypeParameter(source); + var sourceConstraint = constraint && getTypeFromTypeNode(constraint); + var targetConstraint = getConstraintOfTypeParameter(target); + if (sourceConstraint) { + // relax check if later interface augmentation has no constraint + if (!targetConstraint || !isTypeIdenticalTo(sourceConstraint, targetConstraint)) { + return false; + } + } + // If the type parameter node has a default and it is not identical to the default + // for the type parameter at this position, we report an error. + var sourceDefault = source.default && getTypeFromTypeNode(source.default); + var targetDefault = getDefaultFromTypeParameter(target); + if (sourceDefault && targetDefault && !isTypeIdenticalTo(sourceDefault, targetDefault)) { + return false; + } + } + } + return true; + } + function checkClassExpression(node) { + checkClassLikeDeclaration(node); + checkNodeDeferred(node); + return getTypeOfSymbol(getSymbolOfNode(node)); + } + function checkClassExpressionDeferred(node) { + ts.forEach(node.members, checkSourceElement); + registerForUnusedIdentifiersCheck(node); + } + function checkClassDeclaration(node) { + if (!node.name && !ts.hasModifier(node, 512 /* Default */)) { + grammarErrorOnFirstToken(node, ts.Diagnostics.A_class_declaration_without_the_default_modifier_must_have_a_name); + } + checkClassLikeDeclaration(node); + ts.forEach(node.members, checkSourceElement); + registerForUnusedIdentifiersCheck(node); + } + function checkClassLikeDeclaration(node) { + checkGrammarClassLikeDeclaration(node); + checkDecorators(node); + if (node.name) { + checkTypeNameIsReserved(node.name, ts.Diagnostics.Class_name_cannot_be_0); + checkCollisionWithRequireExportsInGeneratedCode(node, node.name); + checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); + if (!(node.flags & 4194304 /* Ambient */)) { + checkClassNameCollisionWithObject(node.name); + } + } + checkTypeParameters(ts.getEffectiveTypeParameterDeclarations(node)); + checkExportsOnMergedDeclarations(node); + var symbol = getSymbolOfNode(node); + var type = getDeclaredTypeOfSymbol(symbol); + var typeWithThis = getTypeWithThisArgument(type); + var staticType = getTypeOfSymbol(symbol); + checkTypeParameterListsIdentical(symbol); + checkClassForDuplicateDeclarations(node); + // Only check for reserved static identifiers on non-ambient context. + if (!(node.flags & 4194304 /* Ambient */)) { + checkClassForStaticPropertyNameConflicts(node); + } + var baseTypeNode = ts.getEffectiveBaseTypeNode(node); + if (baseTypeNode) { + if (languageVersion < 2 /* ES2015 */) { + checkExternalEmitHelpers(baseTypeNode.parent, 1 /* Extends */); + } + var baseTypes = getBaseTypes(type); + if (baseTypes.length && produceDiagnostics) { + var baseType_1 = baseTypes[0]; + var baseConstructorType = getBaseConstructorTypeOfClass(type); + var staticBaseType = getApparentType(baseConstructorType); + checkBaseTypeAccessibility(staticBaseType, baseTypeNode); + checkSourceElement(baseTypeNode.expression); + var extendsNode = ts.getClassExtendsHeritageElement(node); + if (extendsNode && extendsNode !== baseTypeNode) { + checkExpression(extendsNode.expression); + } + if (ts.some(baseTypeNode.typeArguments)) { + ts.forEach(baseTypeNode.typeArguments, checkSourceElement); + for (var _i = 0, _a = getConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments, baseTypeNode); _i < _a.length; _i++) { + var constructor = _a[_i]; + if (!checkTypeArgumentConstraints(baseTypeNode, constructor.typeParameters)) { + break; + } + } + } + var baseWithThis = getTypeWithThisArgument(baseType_1, type.thisType); + if (!checkTypeAssignableTo(typeWithThis, baseWithThis, /*errorNode*/ undefined)) { + issueMemberSpecificError(node, typeWithThis, baseWithThis, ts.Diagnostics.Class_0_incorrectly_extends_base_class_1); + } + else { + // Report static side error only when instance type is assignable + checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, ts.Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1); + } + if (baseConstructorType.flags & 8650752 /* TypeVariable */ && !isMixinConstructorType(staticType)) { + error(node.name || node, ts.Diagnostics.A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any); + } + if (!(staticBaseType.symbol && staticBaseType.symbol.flags & 32 /* Class */) && !(baseConstructorType.flags & 8650752 /* TypeVariable */)) { + // When the static base type is a "class-like" constructor function (but not actually a class), we verify + // that all instantiated base constructor signatures return the same type. We can simply compare the type + // references (as opposed to checking the structure of the types) because elsewhere we have already checked + // that the base type is a class or interface type (and not, for example, an anonymous object type). + // (Javascript constructor functions have this property trivially true since their return type is ignored.) + var constructors = getInstantiatedConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments, baseTypeNode); + if (ts.forEach(constructors, function (sig) { return !isJSConstructor(sig.declaration) && getReturnTypeOfSignature(sig) !== baseType_1; })) { + error(baseTypeNode.expression, ts.Diagnostics.Base_constructors_must_all_have_the_same_return_type); + } + } + checkKindsOfPropertyMemberOverrides(type, baseType_1); + } + } + var implementedTypeNodes = ts.getClassImplementsHeritageClauseElements(node); + if (implementedTypeNodes) { + for (var _b = 0, implementedTypeNodes_1 = implementedTypeNodes; _b < implementedTypeNodes_1.length; _b++) { + var typeRefNode = implementedTypeNodes_1[_b]; + if (!ts.isEntityNameExpression(typeRefNode.expression)) { + error(typeRefNode.expression, ts.Diagnostics.A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments); + } + checkTypeReferenceNode(typeRefNode); + if (produceDiagnostics) { + var t = getTypeFromTypeNode(typeRefNode); + if (t !== errorType) { + if (isValidBaseType(t)) { + var genericDiag = t.symbol && t.symbol.flags & 32 /* Class */ ? + ts.Diagnostics.Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass : + ts.Diagnostics.Class_0_incorrectly_implements_interface_1; + var baseWithThis = getTypeWithThisArgument(t, type.thisType); + if (!checkTypeAssignableTo(typeWithThis, baseWithThis, /*errorNode*/ undefined)) { + issueMemberSpecificError(node, typeWithThis, baseWithThis, genericDiag); + } + } + else { + error(typeRefNode, ts.Diagnostics.A_class_can_only_implement_an_object_type_or_intersection_of_object_types_with_statically_known_members); + } + } + } + } + } + if (produceDiagnostics) { + checkIndexConstraints(type); + checkTypeForDuplicateIndexSignatures(node); + checkPropertyInitialization(node); + } + } + function issueMemberSpecificError(node, typeWithThis, baseWithThis, broadDiag) { + // iterate over all implemented properties and issue errors on each one which isn't compatible, rather than the class as a whole, if possible + var issuedMemberError = false; + var _loop_8 = function (member) { + if (ts.hasStaticModifier(member)) { + return "continue"; + } + var declaredProp = member.name && getSymbolAtLocation(member.name) || getSymbolAtLocation(member); + if (declaredProp) { + var prop = getPropertyOfType(typeWithThis, declaredProp.escapedName); + var baseProp = getPropertyOfType(baseWithThis, declaredProp.escapedName); + if (prop && baseProp) { + var rootChain = function () { return ts.chainDiagnosticMessages( + /*details*/ undefined, ts.Diagnostics.Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2, symbolToString(declaredProp), typeToString(typeWithThis), typeToString(baseWithThis)); }; + if (!checkTypeAssignableTo(getTypeOfSymbol(prop), getTypeOfSymbol(baseProp), member.name || member, /*message*/ undefined, rootChain)) { + issuedMemberError = true; + } + } + } + }; + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + _loop_8(member); + } + if (!issuedMemberError) { + // check again with diagnostics to generate a less-specific error + checkTypeAssignableTo(typeWithThis, baseWithThis, node.name || node, broadDiag); + } + } + function checkBaseTypeAccessibility(type, node) { + var signatures = getSignaturesOfType(type, 1 /* Construct */); + if (signatures.length) { + var declaration = signatures[0].declaration; + if (declaration && ts.hasModifier(declaration, 8 /* Private */)) { + var typeClassDeclaration = ts.getClassLikeDeclarationOfSymbol(type.symbol); + if (!isNodeWithinClass(node, typeClassDeclaration)) { + error(node, ts.Diagnostics.Cannot_extend_a_class_0_Class_constructor_is_marked_as_private, getFullyQualifiedName(type.symbol)); + } + } + } + } + function getTargetSymbol(s) { + // if symbol is instantiated its flags are not copied from the 'target' + // so we'll need to get back original 'target' symbol to work with correct set of flags + return ts.getCheckFlags(s) & 1 /* Instantiated */ ? s.target : s; + } + function getClassOrInterfaceDeclarationsOfSymbol(symbol) { + return ts.filter(symbol.declarations, function (d) { + return d.kind === 240 /* ClassDeclaration */ || d.kind === 241 /* InterfaceDeclaration */; + }); + } + function checkKindsOfPropertyMemberOverrides(type, baseType) { + // TypeScript 1.0 spec (April 2014): 8.2.3 + // A derived class inherits all members from its base class it doesn't override. + // Inheritance means that a derived class implicitly contains all non - overridden members of the base class. + // Both public and private property members are inherited, but only public property members can be overridden. + // A property member in a derived class is said to override a property member in a base class + // when the derived class property member has the same name and kind(instance or static) + // as the base class property member. + // The type of an overriding property member must be assignable(section 3.8.4) + // to the type of the overridden property member, or otherwise a compile - time error occurs. + // Base class instance member functions can be overridden by derived class instance member functions, + // but not by other kinds of members. + // Base class instance member variables and accessors can be overridden by + // derived class instance member variables and accessors, but not by other kinds of members. + // NOTE: assignability is checked in checkClassDeclaration + var baseProperties = getPropertiesOfType(baseType); + for (var _i = 0, baseProperties_1 = baseProperties; _i < baseProperties_1.length; _i++) { + var baseProperty = baseProperties_1[_i]; + var base = getTargetSymbol(baseProperty); + if (base.flags & 4194304 /* Prototype */) { + continue; + } + var derived = getTargetSymbol(getPropertyOfObjectType(type, base.escapedName)); // TODO: GH#18217 + var baseDeclarationFlags = ts.getDeclarationModifierFlagsFromSymbol(base); + ts.Debug.assert(!!derived, "derived should point to something, even if it is the base class' declaration."); + if (derived) { + // In order to resolve whether the inherited method was overridden in the base class or not, + // we compare the Symbols obtained. Since getTargetSymbol returns the symbol on the *uninstantiated* + // type declaration, derived and base resolve to the same symbol even in the case of generic classes. + if (derived === base) { + // derived class inherits base without override/redeclaration + var derivedClassDecl = ts.getClassLikeDeclarationOfSymbol(type.symbol); + // It is an error to inherit an abstract member without implementing it or being declared abstract. + // If there is no declaration for the derived class (as in the case of class expressions), + // then the class cannot be declared abstract. + if (baseDeclarationFlags & 128 /* Abstract */ && (!derivedClassDecl || !ts.hasModifier(derivedClassDecl, 128 /* Abstract */))) { + if (derivedClassDecl.kind === 209 /* ClassExpression */) { + error(derivedClassDecl, ts.Diagnostics.Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1, symbolToString(baseProperty), typeToString(baseType)); + } + else { + error(derivedClassDecl, ts.Diagnostics.Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2, typeToString(type), symbolToString(baseProperty), typeToString(baseType)); + } + } + } + else { + // derived overrides base. + var derivedDeclarationFlags = ts.getDeclarationModifierFlagsFromSymbol(derived); + if (baseDeclarationFlags & 8 /* Private */ || derivedDeclarationFlags & 8 /* Private */) { + // either base or derived property is private - not override, skip it + continue; + } + if (isPrototypeProperty(base) || base.flags & 98308 /* PropertyOrAccessor */ && derived.flags & 98308 /* PropertyOrAccessor */) { + // method is overridden with method or property/accessor is overridden with property/accessor - correct case + continue; + } + var errorMessage = void 0; + if (isPrototypeProperty(base)) { + if (derived.flags & 98304 /* Accessor */) { + errorMessage = ts.Diagnostics.Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor; + } + else { + errorMessage = ts.Diagnostics.Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_property; + } + } + else if (base.flags & 98304 /* Accessor */) { + errorMessage = ts.Diagnostics.Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function; + } + else { + errorMessage = ts.Diagnostics.Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_function; + } + error(ts.getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage, typeToString(baseType), symbolToString(base), typeToString(type)); + } + } + } + } + function checkInheritedPropertiesAreIdentical(type, typeNode) { + var baseTypes = getBaseTypes(type); + if (baseTypes.length < 2) { + return true; + } + var seen = ts.createUnderscoreEscapedMap(); + ts.forEach(resolveDeclaredMembers(type).declaredProperties, function (p) { seen.set(p.escapedName, { prop: p, containingType: type }); }); + var ok = true; + for (var _i = 0, baseTypes_2 = baseTypes; _i < baseTypes_2.length; _i++) { + var base = baseTypes_2[_i]; + var properties = getPropertiesOfType(getTypeWithThisArgument(base, type.thisType)); + for (var _a = 0, properties_7 = properties; _a < properties_7.length; _a++) { + var prop = properties_7[_a]; + var existing = seen.get(prop.escapedName); + if (!existing) { + seen.set(prop.escapedName, { prop: prop, containingType: base }); + } + else { + var isInheritedProperty = existing.containingType !== type; + if (isInheritedProperty && !isPropertyIdenticalTo(existing.prop, prop)) { + ok = false; + var typeName1 = typeToString(existing.containingType); + var typeName2 = typeToString(base); + var errorInfo = ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Named_property_0_of_types_1_and_2_are_not_identical, symbolToString(prop), typeName1, typeName2); + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Interface_0_cannot_simultaneously_extend_types_1_and_2, typeToString(type), typeName1, typeName2); + diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(typeNode, errorInfo)); + } + } + } + } + return ok; + } + function checkPropertyInitialization(node) { + if (!strictNullChecks || !strictPropertyInitialization || node.flags & 4194304 /* Ambient */) { + return; + } + var constructor = findConstructorDeclaration(node); + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + if (isInstancePropertyWithoutInitializer(member)) { + var propName = member.name; + if (ts.isIdentifier(propName)) { + var type = getTypeOfSymbol(getSymbolOfNode(member)); + if (!(type.flags & 3 /* AnyOrUnknown */ || getFalsyFlags(type) & 32768 /* Undefined */)) { + if (!constructor || !isPropertyInitializedInConstructor(propName, type, constructor)) { + error(member.name, ts.Diagnostics.Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor, ts.declarationNameToString(propName)); + } + } + } + } + } + } + function isInstancePropertyWithoutInitializer(node) { + return node.kind === 154 /* PropertyDeclaration */ && + !ts.hasModifier(node, 32 /* Static */ | 128 /* Abstract */) && + !node.exclamationToken && + !node.initializer; + } + function isPropertyInitializedInConstructor(propName, propType, constructor) { + var reference = ts.createPropertyAccess(ts.createThis(), propName); + reference.expression.parent = reference; + reference.parent = constructor; + reference.flowNode = constructor.returnFlowNode; + var flowType = getFlowTypeOfReference(reference, propType, getOptionalType(propType)); + return !(getFalsyFlags(flowType) & 32768 /* Undefined */); + } + function checkInterfaceDeclaration(node) { + // Grammar checking + if (!checkGrammarDecoratorsAndModifiers(node)) + checkGrammarInterfaceDeclaration(node); + checkTypeParameters(node.typeParameters); + if (produceDiagnostics) { + checkTypeNameIsReserved(node.name, ts.Diagnostics.Interface_name_cannot_be_0); + checkExportsOnMergedDeclarations(node); + var symbol = getSymbolOfNode(node); + checkTypeParameterListsIdentical(symbol); + // Only check this symbol once + var firstInterfaceDecl = ts.getDeclarationOfKind(symbol, 241 /* InterfaceDeclaration */); + if (node === firstInterfaceDecl) { + var type = getDeclaredTypeOfSymbol(symbol); + var typeWithThis = getTypeWithThisArgument(type); + // run subsequent checks only if first set succeeded + if (checkInheritedPropertiesAreIdentical(type, node.name)) { + for (var _i = 0, _a = getBaseTypes(type); _i < _a.length; _i++) { + var baseType = _a[_i]; + checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(baseType, type.thisType), node.name, ts.Diagnostics.Interface_0_incorrectly_extends_interface_1); + } + checkIndexConstraints(type); + } + } + checkObjectTypeForDuplicateDeclarations(node); + } + ts.forEach(ts.getInterfaceBaseTypeNodes(node), function (heritageElement) { + if (!ts.isEntityNameExpression(heritageElement.expression)) { + error(heritageElement.expression, ts.Diagnostics.An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments); + } + checkTypeReferenceNode(heritageElement); + }); + ts.forEach(node.members, checkSourceElement); + if (produceDiagnostics) { + checkTypeForDuplicateIndexSignatures(node); + registerForUnusedIdentifiersCheck(node); + } + } + function checkTypeAliasDeclaration(node) { + // Grammar checking + checkGrammarDecoratorsAndModifiers(node); + checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_alias_name_cannot_be_0); + checkTypeParameters(node.typeParameters); + checkSourceElement(node.type); + registerForUnusedIdentifiersCheck(node); + } + function computeEnumMemberValues(node) { + var nodeLinks = getNodeLinks(node); + if (!(nodeLinks.flags & 16384 /* EnumValuesComputed */)) { + nodeLinks.flags |= 16384 /* EnumValuesComputed */; + var autoValue = 0; + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + var value = computeMemberValue(member, autoValue); + getNodeLinks(member).enumMemberValue = value; + autoValue = typeof value === "number" ? value + 1 : undefined; + } + } + } + function computeMemberValue(member, autoValue) { + if (isComputedNonLiteralName(member.name)) { + error(member.name, ts.Diagnostics.Computed_property_names_are_not_allowed_in_enums); + } + else { + var text = ts.getTextOfPropertyName(member.name); + if (isNumericLiteralName(text) && !isInfinityOrNaNString(text)) { + error(member.name, ts.Diagnostics.An_enum_member_cannot_have_a_numeric_name); + } + } + if (member.initializer) { + return computeConstantValue(member); + } + // In ambient enum declarations that specify no const modifier, enum member declarations that omit + // a value are considered computed members (as opposed to having auto-incremented values). + if (member.parent.flags & 4194304 /* Ambient */ && !ts.isEnumConst(member.parent)) { + return undefined; + } + // If the member declaration specifies no value, the member is considered a constant enum member. + // If the member is the first member in the enum declaration, it is assigned the value zero. + // Otherwise, it is assigned the value of the immediately preceding member plus one, and an error + // occurs if the immediately preceding member is not a constant enum member. + if (autoValue !== undefined) { + return autoValue; + } + error(member.name, ts.Diagnostics.Enum_member_must_have_initializer); + return undefined; + } + function computeConstantValue(member) { + var enumKind = getEnumKind(getSymbolOfNode(member.parent)); + var isConstEnum = ts.isEnumConst(member.parent); + var initializer = member.initializer; + var value = enumKind === 1 /* Literal */ && !isLiteralEnumMember(member) ? undefined : evaluate(initializer); + if (value !== undefined) { + if (isConstEnum && typeof value === "number" && !isFinite(value)) { + error(initializer, isNaN(value) ? + ts.Diagnostics.const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN : + ts.Diagnostics.const_enum_member_initializer_was_evaluated_to_a_non_finite_value); + } + } + else if (enumKind === 1 /* Literal */) { + error(initializer, ts.Diagnostics.Computed_values_are_not_permitted_in_an_enum_with_string_valued_members); + return 0; + } + else if (isConstEnum) { + error(initializer, ts.Diagnostics.In_const_enum_declarations_member_initializer_must_be_constant_expression); + } + else if (member.parent.flags & 4194304 /* Ambient */) { + error(initializer, ts.Diagnostics.In_ambient_enum_declarations_member_initializer_must_be_constant_expression); + } + else { + // Only here do we need to check that the initializer is assignable to the enum type. + checkTypeAssignableTo(checkExpression(initializer), getDeclaredTypeOfSymbol(getSymbolOfNode(member.parent)), initializer, /*headMessage*/ undefined); + } + return value; + function evaluate(expr) { + switch (expr.kind) { + case 202 /* PrefixUnaryExpression */: + var value_2 = evaluate(expr.operand); + if (typeof value_2 === "number") { + switch (expr.operator) { + case 38 /* PlusToken */: return value_2; + case 39 /* MinusToken */: return -value_2; + case 53 /* TildeToken */: return ~value_2; + } + } + break; + case 204 /* BinaryExpression */: + var left = evaluate(expr.left); + var right = evaluate(expr.right); + if (typeof left === "number" && typeof right === "number") { + switch (expr.operatorToken.kind) { + case 50 /* BarToken */: return left | right; + case 49 /* AmpersandToken */: return left & right; + case 47 /* GreaterThanGreaterThanToken */: return left >> right; + case 48 /* GreaterThanGreaterThanGreaterThanToken */: return left >>> right; + case 46 /* LessThanLessThanToken */: return left << right; + case 51 /* CaretToken */: return left ^ right; + case 40 /* AsteriskToken */: return left * right; + case 42 /* SlashToken */: return left / right; + case 38 /* PlusToken */: return left + right; + case 39 /* MinusToken */: return left - right; + case 43 /* PercentToken */: return left % right; + case 41 /* AsteriskAsteriskToken */: return Math.pow(left, right); + } + } + else if (typeof left === "string" && typeof right === "string" && expr.operatorToken.kind === 38 /* PlusToken */) { + return left + right; + } + break; + case 10 /* StringLiteral */: + return expr.text; + case 8 /* NumericLiteral */: + checkGrammarNumericLiteral(expr); + return +expr.text; + case 195 /* ParenthesizedExpression */: + return evaluate(expr.expression); + case 72 /* Identifier */: + var identifier = expr; + if (isInfinityOrNaNString(identifier.escapedText)) { + return +(identifier.escapedText); + } + return ts.nodeIsMissing(expr) ? 0 : evaluateEnumMember(expr, getSymbolOfNode(member.parent), identifier.escapedText); + case 190 /* ElementAccessExpression */: + case 189 /* PropertyAccessExpression */: + var ex = expr; + if (isConstantMemberAccess(ex)) { + var type = getTypeOfExpression(ex.expression); + if (type.symbol && type.symbol.flags & 384 /* Enum */) { + var name = void 0; + if (ex.kind === 189 /* PropertyAccessExpression */) { + name = ex.name.escapedText; + } + else { + var argument = ex.argumentExpression; + ts.Debug.assert(ts.isLiteralExpression(argument)); + name = ts.escapeLeadingUnderscores(argument.text); + } + return evaluateEnumMember(expr, type.symbol, name); + } + } + break; + } + return undefined; + } + function evaluateEnumMember(expr, enumSymbol, name) { + var memberSymbol = enumSymbol.exports.get(name); + if (memberSymbol) { + var declaration = memberSymbol.valueDeclaration; + if (declaration !== member) { + if (isBlockScopedNameDeclaredBeforeUse(declaration, member)) { + return getEnumMemberValue(declaration); + } + error(expr, ts.Diagnostics.A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums); + return 0; + } + } + return undefined; + } + } + function isConstantMemberAccess(node) { + return node.kind === 72 /* Identifier */ || + node.kind === 189 /* PropertyAccessExpression */ && isConstantMemberAccess(node.expression) || + node.kind === 190 /* ElementAccessExpression */ && isConstantMemberAccess(node.expression) && + node.argumentExpression.kind === 10 /* StringLiteral */; + } + function checkEnumDeclaration(node) { + if (!produceDiagnostics) { + return; + } + // Grammar checking + checkGrammarDecoratorsAndModifiers(node); + checkTypeNameIsReserved(node.name, ts.Diagnostics.Enum_name_cannot_be_0); + checkCollisionWithRequireExportsInGeneratedCode(node, node.name); + checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); + checkExportsOnMergedDeclarations(node); + computeEnumMemberValues(node); + var enumIsConst = ts.isEnumConst(node); + if (compilerOptions.isolatedModules && enumIsConst && node.flags & 4194304 /* Ambient */) { + error(node.name, ts.Diagnostics.Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided); + } + // Spec 2014 - Section 9.3: + // It isn't possible for one enum declaration to continue the automatic numbering sequence of another, + // and when an enum type has multiple declarations, only one declaration is permitted to omit a value + // for the first member. + // + // Only perform this check once per symbol + var enumSymbol = getSymbolOfNode(node); + var firstDeclaration = ts.getDeclarationOfKind(enumSymbol, node.kind); + if (node === firstDeclaration) { + if (enumSymbol.declarations.length > 1) { + // check that const is placed\omitted on all enum declarations + ts.forEach(enumSymbol.declarations, function (decl) { + if (ts.isEnumDeclaration(decl) && ts.isEnumConst(decl) !== enumIsConst) { + error(ts.getNameOfDeclaration(decl), ts.Diagnostics.Enum_declarations_must_all_be_const_or_non_const); + } + }); + } + var seenEnumMissingInitialInitializer_1 = false; + ts.forEach(enumSymbol.declarations, function (declaration) { + // return true if we hit a violation of the rule, false otherwise + if (declaration.kind !== 243 /* EnumDeclaration */) { + return false; + } + var enumDeclaration = declaration; + if (!enumDeclaration.members.length) { + return false; + } + var firstEnumMember = enumDeclaration.members[0]; + if (!firstEnumMember.initializer) { + if (seenEnumMissingInitialInitializer_1) { + error(firstEnumMember.name, ts.Diagnostics.In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enum_element); + } + else { + seenEnumMissingInitialInitializer_1 = true; + } + } + }); + } + } + function getFirstNonAmbientClassOrFunctionDeclaration(symbol) { + var declarations = symbol.declarations; + for (var _i = 0, declarations_8 = declarations; _i < declarations_8.length; _i++) { + var declaration = declarations_8[_i]; + if ((declaration.kind === 240 /* ClassDeclaration */ || + (declaration.kind === 239 /* FunctionDeclaration */ && ts.nodeIsPresent(declaration.body))) && + !(declaration.flags & 4194304 /* Ambient */)) { + return declaration; + } + } + return undefined; + } + function inSameLexicalScope(node1, node2) { + var container1 = ts.getEnclosingBlockScopeContainer(node1); + var container2 = ts.getEnclosingBlockScopeContainer(node2); + if (isGlobalSourceFile(container1)) { + return isGlobalSourceFile(container2); + } + else if (isGlobalSourceFile(container2)) { + return false; + } + else { + return container1 === container2; + } + } + function checkModuleDeclaration(node) { + if (produceDiagnostics) { + // Grammar checking + var isGlobalAugmentation = ts.isGlobalScopeAugmentation(node); + var inAmbientContext = node.flags & 4194304 /* Ambient */; + if (isGlobalAugmentation && !inAmbientContext) { + error(node.name, ts.Diagnostics.Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambient_context); + } + var isAmbientExternalModule = ts.isAmbientModule(node); + var contextErrorMessage = isAmbientExternalModule + ? ts.Diagnostics.An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file + : ts.Diagnostics.A_namespace_declaration_is_only_allowed_in_a_namespace_or_module; + if (checkGrammarModuleElementContext(node, contextErrorMessage)) { + // If we hit a module declaration in an illegal context, just bail out to avoid cascading errors. + return; + } + if (!checkGrammarDecoratorsAndModifiers(node)) { + if (!inAmbientContext && node.name.kind === 10 /* StringLiteral */) { + grammarErrorOnNode(node.name, ts.Diagnostics.Only_ambient_modules_can_use_quoted_names); + } + } + if (ts.isIdentifier(node.name)) { + checkCollisionWithRequireExportsInGeneratedCode(node, node.name); + checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); + } + checkExportsOnMergedDeclarations(node); + var symbol = getSymbolOfNode(node); + // The following checks only apply on a non-ambient instantiated module declaration. + if (symbol.flags & 512 /* ValueModule */ + && symbol.declarations.length > 1 + && !inAmbientContext + && isInstantiatedModule(node, !!compilerOptions.preserveConstEnums || !!compilerOptions.isolatedModules)) { + var firstNonAmbientClassOrFunc = getFirstNonAmbientClassOrFunctionDeclaration(symbol); + if (firstNonAmbientClassOrFunc) { + if (ts.getSourceFileOfNode(node) !== ts.getSourceFileOfNode(firstNonAmbientClassOrFunc)) { + error(node.name, ts.Diagnostics.A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merged); + } + else if (node.pos < firstNonAmbientClassOrFunc.pos) { + error(node.name, ts.Diagnostics.A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged); + } + } + // if the module merges with a class declaration in the same lexical scope, + // we need to track this to ensure the correct emit. + var mergedClass = ts.getDeclarationOfKind(symbol, 240 /* ClassDeclaration */); + if (mergedClass && + inSameLexicalScope(node, mergedClass)) { + getNodeLinks(node).flags |= 32768 /* LexicalModuleMergesWithClass */; + } + } + if (isAmbientExternalModule) { + if (ts.isExternalModuleAugmentation(node)) { + // body of the augmentation should be checked for consistency only if augmentation was applied to its target (either global scope or module) + // otherwise we'll be swamped in cascading errors. + // We can detect if augmentation was applied using following rules: + // - augmentation for a global scope is always applied + // - augmentation for some external module is applied if symbol for augmentation is merged (it was combined with target module). + var checkBody = isGlobalAugmentation || (getSymbolOfNode(node).flags & 33554432 /* Transient */); + if (checkBody && node.body) { + for (var _i = 0, _a = node.body.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + checkModuleAugmentationElement(statement, isGlobalAugmentation); + } + } + } + else if (isGlobalSourceFile(node.parent)) { + if (isGlobalAugmentation) { + error(node.name, ts.Diagnostics.Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_declarations); + } + else if (ts.isExternalModuleNameRelative(ts.getTextOfIdentifierOrLiteral(node.name))) { + error(node.name, ts.Diagnostics.Ambient_module_declaration_cannot_specify_relative_module_name); + } + } + else { + if (isGlobalAugmentation) { + error(node.name, ts.Diagnostics.Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_declarations); + } + else { + // Node is not an augmentation and is not located on the script level. + // This means that this is declaration of ambient module that is located in other module or namespace which is prohibited. + error(node.name, ts.Diagnostics.Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces); + } + } + } + } + if (node.body) { + checkSourceElement(node.body); + if (!ts.isGlobalScopeAugmentation(node)) { + registerForUnusedIdentifiersCheck(node); + } + } + } + function checkModuleAugmentationElement(node, isGlobalAugmentation) { + switch (node.kind) { + case 219 /* VariableStatement */: + // error each individual name in variable statement instead of marking the entire variable statement + for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + checkModuleAugmentationElement(decl, isGlobalAugmentation); + } + break; + case 254 /* ExportAssignment */: + case 255 /* ExportDeclaration */: + grammarErrorOnFirstToken(node, ts.Diagnostics.Exports_and_export_assignments_are_not_permitted_in_module_augmentations); + break; + case 248 /* ImportEqualsDeclaration */: + case 249 /* ImportDeclaration */: + grammarErrorOnFirstToken(node, ts.Diagnostics.Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_module); + break; + case 186 /* BindingElement */: + case 237 /* VariableDeclaration */: + var name = node.name; + if (ts.isBindingPattern(name)) { + for (var _b = 0, _c = name.elements; _b < _c.length; _b++) { + var el = _c[_b]; + // mark individual names in binding pattern + checkModuleAugmentationElement(el, isGlobalAugmentation); + } + break; + } + // falls through + case 240 /* ClassDeclaration */: + case 243 /* EnumDeclaration */: + case 239 /* FunctionDeclaration */: + case 241 /* InterfaceDeclaration */: + case 244 /* ModuleDeclaration */: + case 242 /* TypeAliasDeclaration */: + if (isGlobalAugmentation) { + return; + } + var symbol = getSymbolOfNode(node); + if (symbol) { + // module augmentations cannot introduce new names on the top level scope of the module + // this is done it two steps + // 1. quick check - if symbol for node is not merged - this is local symbol to this augmentation - report error + // 2. main check - report error if value declaration of the parent symbol is module augmentation) + var reportError = !(symbol.flags & 33554432 /* Transient */); + if (!reportError) { + // symbol should not originate in augmentation + reportError = !!symbol.parent && ts.isExternalModuleAugmentation(symbol.parent.declarations[0]); + } + } + break; + } + } + function getFirstIdentifier(node) { + switch (node.kind) { + case 72 /* Identifier */: + return node; + case 148 /* QualifiedName */: + do { + node = node.left; + } while (node.kind !== 72 /* Identifier */); + return node; + case 189 /* PropertyAccessExpression */: + do { + node = node.expression; + } while (node.kind !== 72 /* Identifier */); + return node; + } + } + function checkExternalImportOrExportDeclaration(node) { + var moduleName = ts.getExternalModuleName(node); + if (!moduleName || ts.nodeIsMissing(moduleName)) { + // Should be a parse error. + return false; + } + if (!ts.isStringLiteral(moduleName)) { + error(moduleName, ts.Diagnostics.String_literal_expected); + return false; + } + var inAmbientExternalModule = node.parent.kind === 245 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent); + if (node.parent.kind !== 279 /* SourceFile */ && !inAmbientExternalModule) { + error(moduleName, node.kind === 255 /* ExportDeclaration */ ? + ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace : + ts.Diagnostics.Import_declarations_in_a_namespace_cannot_reference_a_module); + return false; + } + if (inAmbientExternalModule && ts.isExternalModuleNameRelative(moduleName.text)) { + // we have already reported errors on top level imports\exports in external module augmentations in checkModuleDeclaration + // no need to do this again. + if (!isTopLevelInExternalModuleAugmentation(node)) { + // TypeScript 1.0 spec (April 2013): 12.1.6 + // An ExternalImportDeclaration in an AmbientExternalModuleDeclaration may reference + // other external modules only through top - level external module names. + // Relative external module names are not permitted. + error(node, ts.Diagnostics.Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relative_module_name); + return false; + } + } + return true; + } + function checkAliasSymbol(node) { + var symbol = getSymbolOfNode(node); + var target = resolveAlias(symbol); + if (target !== unknownSymbol) { + // For external modules symbol represent local symbol for an alias. + // This local symbol will merge any other local declarations (excluding other aliases) + // and symbol.flags will contains combined representation for all merged declaration. + // Based on symbol.flags we can compute a set of excluded meanings (meaning that resolved alias should not have, + // otherwise it will conflict with some local declaration). Note that in addition to normal flags we include matching SymbolFlags.Export* + // in order to prevent collisions with declarations that were exported from the current module (they still contribute to local names). + var excludedMeanings = (symbol.flags & (67220415 /* Value */ | 1048576 /* ExportValue */) ? 67220415 /* Value */ : 0) | + (symbol.flags & 67897832 /* Type */ ? 67897832 /* Type */ : 0) | + (symbol.flags & 1920 /* Namespace */ ? 1920 /* Namespace */ : 0); + if (target.flags & excludedMeanings) { + var message = node.kind === 257 /* ExportSpecifier */ ? + ts.Diagnostics.Export_declaration_conflicts_with_exported_declaration_of_0 : + ts.Diagnostics.Import_declaration_conflicts_with_local_declaration_of_0; + error(node, message, symbolToString(symbol)); + } + // Don't allow to re-export something with no value side when `--isolatedModules` is set. + if (compilerOptions.isolatedModules + && node.kind === 257 /* ExportSpecifier */ + && !(target.flags & 67220415 /* Value */) + && !(node.flags & 4194304 /* Ambient */)) { + error(node, ts.Diagnostics.Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided); + } + } + } + function checkImportBinding(node) { + checkCollisionWithRequireExportsInGeneratedCode(node, node.name); + checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); + checkAliasSymbol(node); + } + function checkImportDeclaration(node) { + if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_import_declaration_can_only_be_used_in_a_namespace_or_module)) { + // If we hit an import declaration in an illegal context, just bail out to avoid cascading errors. + return; + } + if (!checkGrammarDecoratorsAndModifiers(node) && ts.hasModifiers(node)) { + grammarErrorOnFirstToken(node, ts.Diagnostics.An_import_declaration_cannot_have_modifiers); + } + if (checkExternalImportOrExportDeclaration(node)) { + var importClause = node.importClause; + if (importClause) { + if (importClause.name) { + checkImportBinding(importClause); + } + if (importClause.namedBindings) { + if (importClause.namedBindings.kind === 251 /* NamespaceImport */) { + checkImportBinding(importClause.namedBindings); + } + else { + var moduleExisted = resolveExternalModuleName(node, node.moduleSpecifier); + if (moduleExisted) { + ts.forEach(importClause.namedBindings.elements, checkImportBinding); + } + } + } + } + } + } + function checkImportEqualsDeclaration(node) { + if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_import_declaration_can_only_be_used_in_a_namespace_or_module)) { + // If we hit an import declaration in an illegal context, just bail out to avoid cascading errors. + return; + } + checkGrammarDecoratorsAndModifiers(node); + if (ts.isInternalModuleImportEqualsDeclaration(node) || checkExternalImportOrExportDeclaration(node)) { + checkImportBinding(node); + if (ts.hasModifier(node, 1 /* Export */)) { + markExportAsReferenced(node); + } + if (node.moduleReference.kind !== 259 /* ExternalModuleReference */) { + var target = resolveAlias(getSymbolOfNode(node)); + if (target !== unknownSymbol) { + if (target.flags & 67220415 /* Value */) { + // Target is a value symbol, check that it is not hidden by a local declaration with the same name + var moduleName = getFirstIdentifier(node.moduleReference); + if (!(resolveEntityName(moduleName, 67220415 /* Value */ | 1920 /* Namespace */).flags & 1920 /* Namespace */)) { + error(moduleName, ts.Diagnostics.Module_0_is_hidden_by_a_local_declaration_with_the_same_name, ts.declarationNameToString(moduleName)); + } + } + if (target.flags & 67897832 /* Type */) { + checkTypeNameIsReserved(node.name, ts.Diagnostics.Import_name_cannot_be_0); + } + } + } + else { + if (moduleKind >= ts.ModuleKind.ES2015 && !(node.flags & 4194304 /* Ambient */)) { + // Import equals declaration is deprecated in es6 or above + grammarErrorOnNode(node, ts.Diagnostics.Import_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_import_Asterisk_as_ns_from_mod_import_a_from_mod_import_d_from_mod_or_another_module_format_instead); + } + } + } + } + function checkExportDeclaration(node) { + if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_export_declaration_can_only_be_used_in_a_module)) { + // If we hit an export in an illegal context, just bail out to avoid cascading errors. + return; + } + if (!checkGrammarDecoratorsAndModifiers(node) && ts.hasModifiers(node)) { + grammarErrorOnFirstToken(node, ts.Diagnostics.An_export_declaration_cannot_have_modifiers); + } + if (!node.moduleSpecifier || checkExternalImportOrExportDeclaration(node)) { + if (node.exportClause) { + // export { x, y } + // export { x, y } from "foo" + ts.forEach(node.exportClause.elements, checkExportSpecifier); + var inAmbientExternalModule = node.parent.kind === 245 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent); + var inAmbientNamespaceDeclaration = !inAmbientExternalModule && node.parent.kind === 245 /* ModuleBlock */ && + !node.moduleSpecifier && node.flags & 4194304 /* Ambient */; + if (node.parent.kind !== 279 /* SourceFile */ && !inAmbientExternalModule && !inAmbientNamespaceDeclaration) { + error(node, ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace); + } + } + else { + // export * from "foo" + var moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier); + if (moduleSymbol && hasExportAssignmentSymbol(moduleSymbol)) { + error(node.moduleSpecifier, ts.Diagnostics.Module_0_uses_export_and_cannot_be_used_with_export_Asterisk, symbolToString(moduleSymbol)); + } + if (moduleKind !== ts.ModuleKind.System && moduleKind !== ts.ModuleKind.ES2015 && moduleKind !== ts.ModuleKind.ESNext) { + checkExternalEmitHelpers(node, 32768 /* ExportStar */); + } + } + } + } + function checkGrammarModuleElementContext(node, errorMessage) { + var isInAppropriateContext = node.parent.kind === 279 /* SourceFile */ || node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 244 /* ModuleDeclaration */; + if (!isInAppropriateContext) { + grammarErrorOnFirstToken(node, errorMessage); + } + return !isInAppropriateContext; + } + function checkExportSpecifier(node) { + checkAliasSymbol(node); + if (ts.getEmitDeclarations(compilerOptions)) { + collectLinkedAliases(node.propertyName || node.name, /*setVisibility*/ true); + } + if (!node.parent.parent.moduleSpecifier) { + var exportedName = node.propertyName || node.name; + // find immediate value referenced by exported name (SymbolFlags.Alias is set so we don't chase down aliases) + var symbol = resolveName(exportedName, exportedName.escapedText, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, + /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); + if (symbol && (symbol === undefinedSymbol || isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { + error(exportedName, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, ts.idText(exportedName)); + } + else { + markExportAsReferenced(node); + } + } + } + function checkExportAssignment(node) { + if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_export_assignment_can_only_be_used_in_a_module)) { + // If we hit an export assignment in an illegal context, just bail out to avoid cascading errors. + return; + } + var container = node.parent.kind === 279 /* SourceFile */ ? node.parent : node.parent.parent; + if (container.kind === 244 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) { + if (node.isExportEquals) { + error(node, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_namespace); + } + else { + error(node, ts.Diagnostics.A_default_export_can_only_be_used_in_an_ECMAScript_style_module); + } + return; + } + // Grammar checking + if (!checkGrammarDecoratorsAndModifiers(node) && ts.hasModifiers(node)) { + grammarErrorOnFirstToken(node, ts.Diagnostics.An_export_assignment_cannot_have_modifiers); + } + if (node.expression.kind === 72 /* Identifier */) { + markExportAsReferenced(node); + if (ts.getEmitDeclarations(compilerOptions)) { + collectLinkedAliases(node.expression, /*setVisibility*/ true); + } + } + else { + checkExpressionCached(node.expression); + } + checkExternalModuleExports(container); + if ((node.flags & 4194304 /* Ambient */) && !ts.isEntityNameExpression(node.expression)) { + grammarErrorOnNode(node.expression, ts.Diagnostics.The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context); + } + if (node.isExportEquals && !(node.flags & 4194304 /* Ambient */)) { + if (moduleKind >= ts.ModuleKind.ES2015) { + // export assignment is not supported in es6 modules + grammarErrorOnNode(node, ts.Diagnostics.Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or_another_module_format_instead); + } + else if (moduleKind === ts.ModuleKind.System) { + // system modules does not support export assignment + grammarErrorOnNode(node, ts.Diagnostics.Export_assignment_is_not_supported_when_module_flag_is_system); + } + } + } + function hasExportedMembers(moduleSymbol) { + return ts.forEachEntry(moduleSymbol.exports, function (_, id) { return id !== "export="; }); + } + function checkExternalModuleExports(node) { + var moduleSymbol = getSymbolOfNode(node); + var links = getSymbolLinks(moduleSymbol); + if (!links.exportsChecked) { + var exportEqualsSymbol = moduleSymbol.exports.get("export="); + if (exportEqualsSymbol && hasExportedMembers(moduleSymbol)) { + var declaration = getDeclarationOfAliasSymbol(exportEqualsSymbol) || exportEqualsSymbol.valueDeclaration; + if (!isTopLevelInExternalModuleAugmentation(declaration) && !ts.isInJSFile(declaration)) { + error(declaration, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements); + } + } + // Checks for export * conflicts + var exports_1 = getExportsOfModule(moduleSymbol); + if (exports_1) { + exports_1.forEach(function (_a, id) { + var declarations = _a.declarations, flags = _a.flags; + if (id === "__export") { + return; + } + // ECMA262: 15.2.1.1 It is a Syntax Error if the ExportedNames of ModuleItemList contains any duplicate entries. + // (TS Exceptions: namespaces, function overloads, enums, and interfaces) + if (flags & (1920 /* Namespace */ | 64 /* Interface */ | 384 /* Enum */)) { + return; + } + var exportedDeclarationsCount = ts.countWhere(declarations, isNotOverloadAndNotAccessor); + if (flags & 524288 /* TypeAlias */ && exportedDeclarationsCount <= 2) { + // it is legal to merge type alias with other values + // so count should be either 1 (just type alias) or 2 (type alias + merged value) + return; + } + if (exportedDeclarationsCount > 1) { + for (var _i = 0, declarations_9 = declarations; _i < declarations_9.length; _i++) { + var declaration = declarations_9[_i]; + if (isNotOverload(declaration)) { + diagnostics.add(ts.createDiagnosticForNode(declaration, ts.Diagnostics.Cannot_redeclare_exported_variable_0, ts.unescapeLeadingUnderscores(id))); + } + } + } + }); + } + links.exportsChecked = true; + } + } + function isNotAccessor(declaration) { + // Accessors check for their own matching duplicates, and in contexts where they are valid, there are already duplicate identifier checks + return !ts.isAccessor(declaration); + } + function isNotOverload(declaration) { + return (declaration.kind !== 239 /* FunctionDeclaration */ && declaration.kind !== 156 /* MethodDeclaration */) || + !!declaration.body; + } + function checkSourceElement(node) { + if (!node) { + return; + } + if (ts.isInJSFile(node)) { + ts.forEach(node.jsDoc, function (_a) { + var tags = _a.tags; + return ts.forEach(tags, checkSourceElement); + }); + } + var kind = node.kind; + if (cancellationToken) { + // Only bother checking on a few construct kinds. We don't want to be excessively + // hitting the cancellation token on every node we check. + switch (kind) { + case 244 /* ModuleDeclaration */: + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + case 239 /* FunctionDeclaration */: + cancellationToken.throwIfCancellationRequested(); + } + } + switch (kind) { + case 150 /* TypeParameter */: + return checkTypeParameter(node); + case 151 /* Parameter */: + return checkParameter(node); + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + return checkPropertyDeclaration(node); + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 162 /* IndexSignature */: + return checkSignatureDeclaration(node); + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + return checkMethodDeclaration(node); + case 157 /* Constructor */: + return checkConstructorDeclaration(node); + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + return checkAccessorDeclaration(node); + case 164 /* TypeReference */: + return checkTypeReferenceNode(node); + case 163 /* TypePredicate */: + return checkTypePredicate(node); + case 167 /* TypeQuery */: + return checkTypeQuery(node); + case 168 /* TypeLiteral */: + return checkTypeLiteral(node); + case 169 /* ArrayType */: + return checkArrayType(node); + case 170 /* TupleType */: + return checkTupleType(node); + case 173 /* UnionType */: + case 174 /* IntersectionType */: + return checkUnionOrIntersectionType(node); + case 177 /* ParenthesizedType */: + case 171 /* OptionalType */: + case 172 /* RestType */: + return checkSourceElement(node.type); + case 178 /* ThisType */: + return checkThisType(node); + case 179 /* TypeOperator */: + return checkTypeOperator(node); + case 175 /* ConditionalType */: + return checkConditionalType(node); + case 176 /* InferType */: + return checkInferType(node); + case 183 /* ImportType */: + return checkImportType(node); + case 295 /* JSDocAugmentsTag */: + return checkJSDocAugmentsTag(node); + case 304 /* JSDocTypedefTag */: + case 297 /* JSDocCallbackTag */: + return checkJSDocTypeAliasTag(node); + case 303 /* JSDocTemplateTag */: + return checkJSDocTemplateTag(node); + case 302 /* JSDocTypeTag */: + return checkJSDocTypeTag(node); + case 299 /* JSDocParameterTag */: + return checkJSDocParameterTag(node); + case 289 /* JSDocFunctionType */: + checkJSDocFunctionType(node); + // falls through + case 287 /* JSDocNonNullableType */: + case 286 /* JSDocNullableType */: + case 284 /* JSDocAllType */: + case 285 /* JSDocUnknownType */: + case 292 /* JSDocTypeLiteral */: + checkJSDocTypeIsInJsFile(node); + ts.forEachChild(node, checkSourceElement); + return; + case 290 /* JSDocVariadicType */: + checkJSDocVariadicType(node); + return; + case 283 /* JSDocTypeExpression */: + return checkSourceElement(node.type); + case 180 /* IndexedAccessType */: + return checkIndexedAccessType(node); + case 181 /* MappedType */: + return checkMappedType(node); + case 239 /* FunctionDeclaration */: + return checkFunctionDeclaration(node); + case 218 /* Block */: + case 245 /* ModuleBlock */: + return checkBlock(node); + case 219 /* VariableStatement */: + return checkVariableStatement(node); + case 221 /* ExpressionStatement */: + return checkExpressionStatement(node); + case 222 /* IfStatement */: + return checkIfStatement(node); + case 223 /* DoStatement */: + return checkDoStatement(node); + case 224 /* WhileStatement */: + return checkWhileStatement(node); + case 225 /* ForStatement */: + return checkForStatement(node); + case 226 /* ForInStatement */: + return checkForInStatement(node); + case 227 /* ForOfStatement */: + return checkForOfStatement(node); + case 228 /* ContinueStatement */: + case 229 /* BreakStatement */: + return checkBreakOrContinueStatement(node); + case 230 /* ReturnStatement */: + return checkReturnStatement(node); + case 231 /* WithStatement */: + return checkWithStatement(node); + case 232 /* SwitchStatement */: + return checkSwitchStatement(node); + case 233 /* LabeledStatement */: + return checkLabeledStatement(node); + case 234 /* ThrowStatement */: + return checkThrowStatement(node); + case 235 /* TryStatement */: + return checkTryStatement(node); + case 237 /* VariableDeclaration */: + return checkVariableDeclaration(node); + case 186 /* BindingElement */: + return checkBindingElement(node); + case 240 /* ClassDeclaration */: + return checkClassDeclaration(node); + case 241 /* InterfaceDeclaration */: + return checkInterfaceDeclaration(node); + case 242 /* TypeAliasDeclaration */: + return checkTypeAliasDeclaration(node); + case 243 /* EnumDeclaration */: + return checkEnumDeclaration(node); + case 244 /* ModuleDeclaration */: + return checkModuleDeclaration(node); + case 249 /* ImportDeclaration */: + return checkImportDeclaration(node); + case 248 /* ImportEqualsDeclaration */: + return checkImportEqualsDeclaration(node); + case 255 /* ExportDeclaration */: + return checkExportDeclaration(node); + case 254 /* ExportAssignment */: + return checkExportAssignment(node); + case 220 /* EmptyStatement */: + case 236 /* DebuggerStatement */: + checkGrammarStatementInAmbientContext(node); + return; + case 258 /* MissingDeclaration */: + return checkMissingDeclaration(node); + } + } + function checkJSDocTypeIsInJsFile(node) { + if (!ts.isInJSFile(node)) { + grammarErrorOnNode(node, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments); + } + } + function checkJSDocVariadicType(node) { + checkJSDocTypeIsInJsFile(node); + checkSourceElement(node.type); + // Only legal location is in the *last* parameter tag or last parameter of a JSDoc function. + var parent = node.parent; + if (ts.isParameter(parent) && ts.isJSDocFunctionType(parent.parent)) { + if (ts.last(parent.parent.parameters) !== parent) { + error(node, ts.Diagnostics.A_rest_parameter_must_be_last_in_a_parameter_list); + } + return; + } + if (!ts.isJSDocTypeExpression(parent)) { + error(node, ts.Diagnostics.JSDoc_may_only_appear_in_the_last_parameter_of_a_signature); + } + var paramTag = node.parent.parent; + if (!ts.isJSDocParameterTag(paramTag)) { + error(node, ts.Diagnostics.JSDoc_may_only_appear_in_the_last_parameter_of_a_signature); + return; + } + var param = ts.getParameterSymbolFromJSDoc(paramTag); + if (!param) { + // We will error in `checkJSDocParameterTag`. + return; + } + var host = ts.getHostSignatureFromJSDoc(paramTag); + if (!host || ts.last(host.parameters).symbol !== param) { + error(node, ts.Diagnostics.A_rest_parameter_must_be_last_in_a_parameter_list); + } + } + function getTypeFromJSDocVariadicType(node) { + var type = getTypeFromTypeNode(node.type); + var parent = node.parent; + var paramTag = node.parent.parent; + if (ts.isJSDocTypeExpression(node.parent) && ts.isJSDocParameterTag(paramTag)) { + // Else we will add a diagnostic, see `checkJSDocVariadicType`. + var host_1 = ts.getHostSignatureFromJSDoc(paramTag); + if (host_1) { + /* + Only return an array type if the corresponding parameter is marked as a rest parameter, or if there are no parameters. + So in the following situation we will not create an array type: + /** @param {...number} a * / + function f(a) {} + Because `a` will just be of type `number | undefined`. A synthetic `...args` will also be added, which *will* get an array type. + */ + var lastParamDeclaration = ts.lastOrUndefined(host_1.parameters); + var symbol = ts.getParameterSymbolFromJSDoc(paramTag); + if (!lastParamDeclaration || + symbol && lastParamDeclaration.symbol === symbol && ts.isRestParameter(lastParamDeclaration)) { + return createArrayType(type); + } + } + } + if (ts.isParameter(parent) && ts.isJSDocFunctionType(parent.parent)) { + return createArrayType(type); + } + return addOptionality(type); + } + // Function and class expression bodies are checked after all statements in the enclosing body. This is + // to ensure constructs like the following are permitted: + // const foo = function () { + // const s = foo(); + // return "hello"; + // } + // Here, performing a full type check of the body of the function expression whilst in the process of + // determining the type of foo would cause foo to be given type any because of the recursive reference. + // Delaying the type check of the body ensures foo has been assigned a type. + function checkNodeDeferred(node) { + var enclosingFile = ts.getSourceFileOfNode(node); + var links = getNodeLinks(enclosingFile); + if (!(links.flags & 1 /* TypeChecked */)) { + links.deferredNodes = links.deferredNodes || ts.createMap(); + var id = "" + getNodeId(node); + links.deferredNodes.set(id, node); + } + } + function checkDeferredNodes(context) { + var links = getNodeLinks(context); + if (!links.deferredNodes) { + return; + } + links.deferredNodes.forEach(function (node) { + switch (node.kind) { + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + checkFunctionExpressionOrObjectLiteralMethodDeferred(node); + break; + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + checkAccessorDeclaration(node); + break; + case 209 /* ClassExpression */: + checkClassExpressionDeferred(node); + break; + case 261 /* JsxSelfClosingElement */: + checkJsxSelfClosingElementDeferred(node); + break; + case 260 /* JsxElement */: + checkJsxElementDeferred(node); + break; + } + }); + } + function checkSourceFile(node) { + ts.performance.mark("beforeCheck"); + checkSourceFileWorker(node); + ts.performance.mark("afterCheck"); + ts.performance.measure("Check", "beforeCheck", "afterCheck"); + } + function unusedIsError(kind) { + switch (kind) { + case 0 /* Local */: + return !!compilerOptions.noUnusedLocals; + case 1 /* Parameter */: + return !!compilerOptions.noUnusedParameters; + default: + return ts.Debug.assertNever(kind); + } + } + function getPotentiallyUnusedIdentifiers(sourceFile) { + return allPotentiallyUnusedIdentifiers.get(sourceFile.path) || ts.emptyArray; + } + // Fully type check a source file and collect the relevant diagnostics. + function checkSourceFileWorker(node) { + var links = getNodeLinks(node); + if (!(links.flags & 1 /* TypeChecked */)) { + if (ts.skipTypeChecking(node, compilerOptions)) { + return; + } + // Grammar checking + checkGrammarSourceFile(node); + ts.clear(potentialThisCollisions); + ts.clear(potentialNewTargetCollisions); + ts.forEach(node.statements, checkSourceElement); + checkSourceElement(node.endOfFileToken); + checkDeferredNodes(node); + if (ts.isExternalOrCommonJsModule(node)) { + registerForUnusedIdentifiersCheck(node); + } + if (!node.isDeclarationFile && (compilerOptions.noUnusedLocals || compilerOptions.noUnusedParameters)) { + checkUnusedIdentifiers(getPotentiallyUnusedIdentifiers(node), function (containingNode, kind, diag) { + if (!ts.containsParseError(containingNode) && unusedIsError(kind)) { + diagnostics.add(diag); + } + }); + } + if (ts.isExternalOrCommonJsModule(node)) { + checkExternalModuleExports(node); + } + if (potentialThisCollisions.length) { + ts.forEach(potentialThisCollisions, checkIfThisIsCapturedInEnclosingScope); + ts.clear(potentialThisCollisions); + } + if (potentialNewTargetCollisions.length) { + ts.forEach(potentialNewTargetCollisions, checkIfNewTargetIsCapturedInEnclosingScope); + ts.clear(potentialNewTargetCollisions); + } + links.flags |= 1 /* TypeChecked */; + } + } + function getDiagnostics(sourceFile, ct) { + try { + // Record the cancellation token so it can be checked later on during checkSourceElement. + // Do this in a finally block so we can ensure that it gets reset back to nothing after + // this call is done. + cancellationToken = ct; + return getDiagnosticsWorker(sourceFile); + } + finally { + cancellationToken = undefined; + } + } + function getDiagnosticsWorker(sourceFile) { + throwIfNonDiagnosticsProducing(); + if (sourceFile) { + // Some global diagnostics are deferred until they are needed and + // may not be reported in the firt call to getGlobalDiagnostics. + // We should catch these changes and report them. + var previousGlobalDiagnostics = diagnostics.getGlobalDiagnostics(); + var previousGlobalDiagnosticsSize = previousGlobalDiagnostics.length; + checkSourceFile(sourceFile); + var semanticDiagnostics = diagnostics.getDiagnostics(sourceFile.fileName); + var currentGlobalDiagnostics = diagnostics.getGlobalDiagnostics(); + if (currentGlobalDiagnostics !== previousGlobalDiagnostics) { + // If the arrays are not the same reference, new diagnostics were added. + var deferredGlobalDiagnostics = ts.relativeComplement(previousGlobalDiagnostics, currentGlobalDiagnostics, ts.compareDiagnostics); + return ts.concatenate(deferredGlobalDiagnostics, semanticDiagnostics); + } + else if (previousGlobalDiagnosticsSize === 0 && currentGlobalDiagnostics.length > 0) { + // If the arrays are the same reference, but the length has changed, a single + // new diagnostic was added as DiagnosticCollection attempts to reuse the + // same array. + return ts.concatenate(currentGlobalDiagnostics, semanticDiagnostics); + } + return semanticDiagnostics; + } + // Global diagnostics are always added when a file is not provided to + // getDiagnostics + ts.forEach(host.getSourceFiles(), checkSourceFile); + return diagnostics.getDiagnostics(); + } + function getGlobalDiagnostics() { + throwIfNonDiagnosticsProducing(); + return diagnostics.getGlobalDiagnostics(); + } + function throwIfNonDiagnosticsProducing() { + if (!produceDiagnostics) { + throw new Error("Trying to get diagnostics from a type checker that does not produce them."); + } + } + // Language service support + function getSymbolsInScope(location, meaning) { + if (location.flags & 8388608 /* InWithStatement */) { + // We cannot answer semantic questions within a with block, do not proceed any further + return []; + } + var symbols = ts.createSymbolTable(); + var isStatic = false; + populateSymbols(); + symbols.delete("this" /* This */); // Not a symbol, a keyword + return symbolsToArray(symbols); + function populateSymbols() { + while (location) { + if (location.locals && !isGlobalSourceFile(location)) { + copySymbols(location.locals, meaning); + } + switch (location.kind) { + case 279 /* SourceFile */: + if (!ts.isExternalOrCommonJsModule(location)) + break; + // falls through + case 244 /* ModuleDeclaration */: + copySymbols(getSymbolOfNode(location).exports, meaning & 2623475 /* ModuleMember */); + break; + case 243 /* EnumDeclaration */: + copySymbols(getSymbolOfNode(location).exports, meaning & 8 /* EnumMember */); + break; + case 209 /* ClassExpression */: + var className = location.name; + if (className) { + copySymbol(location.symbol, meaning); + } + // falls through + // this fall-through is necessary because we would like to handle + // type parameter inside class expression similar to how we handle it in classDeclaration and interface Declaration + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + // If we didn't come from static member of class or interface, + // add the type parameters into the symbol table + // (type parameters of classDeclaration/classExpression and interface are in member property of the symbol. + // Note: that the memberFlags come from previous iteration. + if (!isStatic) { + copySymbols(getMembersOfSymbol(getSymbolOfNode(location)), meaning & 67897832 /* Type */); + } + break; + case 196 /* FunctionExpression */: + var funcName = location.name; + if (funcName) { + copySymbol(location.symbol, meaning); + } + break; + } + if (ts.introducesArgumentsExoticObject(location)) { + copySymbol(argumentsSymbol, meaning); + } + isStatic = ts.hasModifier(location, 32 /* Static */); + location = location.parent; + } + copySymbols(globals, meaning); + } + /** + * Copy the given symbol into symbol tables if the symbol has the given meaning + * and it doesn't already existed in the symbol table + * @param key a key for storing in symbol table; if undefined, use symbol.name + * @param symbol the symbol to be added into symbol table + * @param meaning meaning of symbol to filter by before adding to symbol table + */ + function copySymbol(symbol, meaning) { + if (ts.getCombinedLocalAndExportSymbolFlags(symbol) & meaning) { + var id = symbol.escapedName; + // We will copy all symbol regardless of its reserved name because + // symbolsToArray will check whether the key is a reserved name and + // it will not copy symbol with reserved name to the array + if (!symbols.has(id)) { + symbols.set(id, symbol); + } + } + } + function copySymbols(source, meaning) { + if (meaning) { + source.forEach(function (symbol) { + copySymbol(symbol, meaning); + }); + } + } + } + function isTypeDeclarationName(name) { + return name.kind === 72 /* Identifier */ && + isTypeDeclaration(name.parent) && + name.parent.name === name; + } + function isTypeDeclaration(node) { + switch (node.kind) { + case 150 /* TypeParameter */: + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 243 /* EnumDeclaration */: + return true; + default: + return false; + } + } + // True if the given identifier is part of a type reference + function isTypeReferenceIdentifier(node) { + while (node.parent.kind === 148 /* QualifiedName */) { + node = node.parent; + } + return node.parent.kind === 164 /* TypeReference */; + } + function isHeritageClauseElementIdentifier(node) { + while (node.parent.kind === 189 /* PropertyAccessExpression */) { + node = node.parent; + } + return node.parent.kind === 211 /* ExpressionWithTypeArguments */; + } + function forEachEnclosingClass(node, callback) { + var result; + while (true) { + node = ts.getContainingClass(node); + if (!node) + break; + if (result = callback(node)) + break; + } + return result; + } + function isNodeUsedDuringClassInitialization(node) { + return !!ts.findAncestor(node, function (element) { + if (ts.isConstructorDeclaration(element) && ts.nodeIsPresent(element.body) || ts.isPropertyDeclaration(element)) { + return true; + } + else if (ts.isClassLike(element) || ts.isFunctionLikeDeclaration(element)) { + return "quit"; + } + return false; + }); + } + function isNodeWithinClass(node, classDeclaration) { + return !!forEachEnclosingClass(node, function (n) { return n === classDeclaration; }); + } + function getLeftSideOfImportEqualsOrExportAssignment(nodeOnRightSide) { + while (nodeOnRightSide.parent.kind === 148 /* QualifiedName */) { + nodeOnRightSide = nodeOnRightSide.parent; + } + if (nodeOnRightSide.parent.kind === 248 /* ImportEqualsDeclaration */) { + return nodeOnRightSide.parent.moduleReference === nodeOnRightSide ? nodeOnRightSide.parent : undefined; + } + if (nodeOnRightSide.parent.kind === 254 /* ExportAssignment */) { + return nodeOnRightSide.parent.expression === nodeOnRightSide ? nodeOnRightSide.parent : undefined; + } + return undefined; + } + function isInRightSideOfImportOrExportAssignment(node) { + return getLeftSideOfImportEqualsOrExportAssignment(node) !== undefined; + } + function getSpecialPropertyAssignmentSymbolFromEntityName(entityName) { + var specialPropertyAssignmentKind = ts.getAssignmentDeclarationKind(entityName.parent.parent); + switch (specialPropertyAssignmentKind) { + case 1 /* ExportsProperty */: + case 3 /* PrototypeProperty */: + return getSymbolOfNode(entityName.parent); + case 4 /* ThisProperty */: + case 2 /* ModuleExports */: + case 5 /* Property */: + return getSymbolOfNode(entityName.parent.parent); + } + } + function isImportTypeQualifierPart(node) { + var parent = node.parent; + while (ts.isQualifiedName(parent)) { + node = parent; + parent = parent.parent; + } + if (parent && parent.kind === 183 /* ImportType */ && parent.qualifier === node) { + return parent; + } + return undefined; + } + function getSymbolOfEntityNameOrPropertyAccessExpression(entityName) { + if (ts.isDeclarationName(entityName)) { + return getSymbolOfNode(entityName.parent); + } + if (ts.isInJSFile(entityName) && + entityName.parent.kind === 189 /* PropertyAccessExpression */ && + entityName.parent === entityName.parent.parent.left) { + // Check if this is a special property assignment + var specialPropertyAssignmentSymbol = getSpecialPropertyAssignmentSymbolFromEntityName(entityName); + if (specialPropertyAssignmentSymbol) { + return specialPropertyAssignmentSymbol; + } + } + if (entityName.parent.kind === 254 /* ExportAssignment */ && ts.isEntityNameExpression(entityName)) { + // Even an entity name expression that doesn't resolve as an entityname may still typecheck as a property access expression + var success = resolveEntityName(entityName, + /*all meanings*/ 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*ignoreErrors*/ true); + if (success && success !== unknownSymbol) { + return success; + } + } + else if (!ts.isPropertyAccessExpression(entityName) && isInRightSideOfImportOrExportAssignment(entityName)) { + // Since we already checked for ExportAssignment, this really could only be an Import + var importEqualsDeclaration = ts.getAncestor(entityName, 248 /* ImportEqualsDeclaration */); + ts.Debug.assert(importEqualsDeclaration !== undefined); + return getSymbolOfPartOfRightHandSideOfImportEquals(entityName, /*dontResolveAlias*/ true); + } + if (!ts.isPropertyAccessExpression(entityName)) { + var possibleImportNode = isImportTypeQualifierPart(entityName); + if (possibleImportNode) { + getTypeFromTypeNode(possibleImportNode); + var sym = getNodeLinks(entityName).resolvedSymbol; + return sym === unknownSymbol ? undefined : sym; + } + } + while (ts.isRightSideOfQualifiedNameOrPropertyAccess(entityName)) { + entityName = entityName.parent; + } + if (isHeritageClauseElementIdentifier(entityName)) { + var meaning = 0 /* None */; + // In an interface or class, we're definitely interested in a type. + if (entityName.parent.kind === 211 /* ExpressionWithTypeArguments */) { + meaning = 67897832 /* Type */; + // In a class 'extends' clause we are also looking for a value. + if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent)) { + meaning |= 67220415 /* Value */; + } + } + else { + meaning = 1920 /* Namespace */; + } + meaning |= 2097152 /* Alias */; + var entityNameSymbol = ts.isEntityNameExpression(entityName) ? resolveEntityName(entityName, meaning) : undefined; + if (entityNameSymbol) { + return entityNameSymbol; + } + } + if (entityName.parent.kind === 299 /* JSDocParameterTag */) { + return ts.getParameterSymbolFromJSDoc(entityName.parent); + } + if (entityName.parent.kind === 150 /* TypeParameter */ && entityName.parent.parent.kind === 303 /* JSDocTemplateTag */) { + ts.Debug.assert(!ts.isInJSFile(entityName)); // Otherwise `isDeclarationName` would have been true. + var typeParameter = ts.getTypeParameterFromJsDoc(entityName.parent); + return typeParameter && typeParameter.symbol; + } + if (ts.isExpressionNode(entityName)) { + if (ts.nodeIsMissing(entityName)) { + // Missing entity name. + return undefined; + } + if (entityName.kind === 72 /* Identifier */) { + if (ts.isJSXTagName(entityName) && isJsxIntrinsicIdentifier(entityName)) { + var symbol = getIntrinsicTagSymbol(entityName.parent); + return symbol === unknownSymbol ? undefined : symbol; + } + return resolveEntityName(entityName, 67220415 /* Value */, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); + } + else if (entityName.kind === 189 /* PropertyAccessExpression */ || entityName.kind === 148 /* QualifiedName */) { + var links = getNodeLinks(entityName); + if (links.resolvedSymbol) { + return links.resolvedSymbol; + } + if (entityName.kind === 189 /* PropertyAccessExpression */) { + checkPropertyAccessExpression(entityName); + } + else { + checkQualifiedName(entityName); + } + return links.resolvedSymbol; + } + } + else if (isTypeReferenceIdentifier(entityName)) { + var meaning = entityName.parent.kind === 164 /* TypeReference */ ? 67897832 /* Type */ : 1920 /* Namespace */; + return resolveEntityName(entityName, meaning, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); + } + if (entityName.parent.kind === 163 /* TypePredicate */) { + return resolveEntityName(entityName, /*meaning*/ 1 /* FunctionScopedVariable */); + } + // Do we want to return undefined here? + return undefined; + } + function getSymbolAtLocation(node) { + if (node.kind === 279 /* SourceFile */) { + return ts.isExternalModule(node) ? getMergedSymbol(node.symbol) : undefined; + } + var parent = node.parent; + var grandParent = parent.parent; + if (node.flags & 8388608 /* InWithStatement */) { + // We cannot answer semantic questions within a with block, do not proceed any further + return undefined; + } + if (isDeclarationNameOrImportPropertyName(node)) { + // This is a declaration, call getSymbolOfNode + var parentSymbol = getSymbolOfNode(parent); + return ts.isImportOrExportSpecifier(node.parent) && node.parent.propertyName === node + ? getImmediateAliasedSymbol(parentSymbol) + : parentSymbol; + } + else if (ts.isLiteralComputedPropertyDeclarationName(node)) { + return getSymbolOfNode(parent.parent); + } + if (node.kind === 72 /* Identifier */) { + if (isInRightSideOfImportOrExportAssignment(node)) { + return getSymbolOfEntityNameOrPropertyAccessExpression(node); + } + else if (parent.kind === 186 /* BindingElement */ && + grandParent.kind === 184 /* ObjectBindingPattern */ && + node === parent.propertyName) { + var typeOfPattern = getTypeOfNode(grandParent); + var propertyDeclaration = getPropertyOfType(typeOfPattern, node.escapedText); + if (propertyDeclaration) { + return propertyDeclaration; + } + } + } + switch (node.kind) { + case 72 /* Identifier */: + case 189 /* PropertyAccessExpression */: + case 148 /* QualifiedName */: + return getSymbolOfEntityNameOrPropertyAccessExpression(node); + case 100 /* ThisKeyword */: + var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); + if (ts.isFunctionLike(container)) { + var sig = getSignatureFromDeclaration(container); + if (sig.thisParameter) { + return sig.thisParameter; + } + } + if (ts.isInExpressionContext(node)) { + return checkExpression(node).symbol; + } + // falls through + case 178 /* ThisType */: + return getTypeFromThisTypeNode(node).symbol; + case 98 /* SuperKeyword */: + return checkExpression(node).symbol; + case 124 /* ConstructorKeyword */: + // constructor keyword for an overload, should take us to the definition if it exist + var constructorDeclaration = node.parent; + if (constructorDeclaration && constructorDeclaration.kind === 157 /* Constructor */) { + return constructorDeclaration.parent.symbol; + } + return undefined; + case 10 /* StringLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: + // 1). import x = require("./mo/*gotToDefinitionHere*/d") + // 2). External module name in an import declaration + // 3). Dynamic import call or require in javascript + // 4). type A = import("./f/*gotToDefinitionHere*/oo") + if ((ts.isExternalModuleImportEqualsDeclaration(node.parent.parent) && ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node) || + ((node.parent.kind === 249 /* ImportDeclaration */ || node.parent.kind === 255 /* ExportDeclaration */) && node.parent.moduleSpecifier === node) || + ((ts.isInJSFile(node) && ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteralLike*/ false)) || ts.isImportCall(node.parent)) || + (ts.isLiteralTypeNode(node.parent) && ts.isLiteralImportTypeNode(node.parent.parent) && node.parent.parent.argument === node.parent)) { + return resolveExternalModuleName(node, node); + } + if (ts.isCallExpression(parent) && ts.isBindableObjectDefinePropertyCall(parent) && parent.arguments[1] === node) { + return getSymbolOfNode(parent); + } + // falls through + case 8 /* NumericLiteral */: + // index access + var objectType = ts.isElementAccessExpression(parent) + ? parent.argumentExpression === node ? getTypeOfExpression(parent.expression) : undefined + : ts.isLiteralTypeNode(parent) && ts.isIndexedAccessTypeNode(grandParent) + ? getTypeFromTypeNode(grandParent.objectType) + : undefined; + return objectType && getPropertyOfType(objectType, ts.escapeLeadingUnderscores(node.text)); + case 80 /* DefaultKeyword */: + case 90 /* FunctionKeyword */: + case 37 /* EqualsGreaterThanToken */: + case 76 /* ClassKeyword */: + return getSymbolOfNode(node.parent); + case 183 /* ImportType */: + return ts.isLiteralImportTypeNode(node) ? getSymbolAtLocation(node.argument.literal) : undefined; + case 85 /* ExportKeyword */: + return ts.isExportAssignment(node.parent) ? ts.Debug.assertDefined(node.parent.symbol) : undefined; + default: + return undefined; + } + } + function getShorthandAssignmentValueSymbol(location) { + if (location && location.kind === 276 /* ShorthandPropertyAssignment */) { + return resolveEntityName(location.name, 67220415 /* Value */ | 2097152 /* Alias */); + } + return undefined; + } + /** Returns the target of an export specifier without following aliases */ + function getExportSpecifierLocalTargetSymbol(node) { + return node.parent.parent.moduleSpecifier ? + getExternalModuleMember(node.parent.parent, node) : + resolveEntityName(node.propertyName || node.name, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); + } + function getTypeOfNode(node) { + if (node.flags & 8388608 /* InWithStatement */) { + // We cannot answer semantic questions within a with block, do not proceed any further + return errorType; + } + var classDecl = ts.tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node); + var classType = classDecl && getDeclaredTypeOfClassOrInterface(getSymbolOfNode(classDecl.class)); + if (ts.isPartOfTypeNode(node)) { + var typeFromTypeNode = getTypeFromTypeNode(node); + return classType ? getTypeWithThisArgument(typeFromTypeNode, classType.thisType) : typeFromTypeNode; + } + if (ts.isExpressionNode(node)) { + return getRegularTypeOfExpression(node); + } + if (classType && !classDecl.isImplements) { + // A SyntaxKind.ExpressionWithTypeArguments is considered a type node, except when it occurs in the + // extends clause of a class. We handle that case here. + var baseType = ts.firstOrUndefined(getBaseTypes(classType)); + return baseType ? getTypeWithThisArgument(baseType, classType.thisType) : errorType; + } + if (isTypeDeclaration(node)) { + // In this case, we call getSymbolOfNode instead of getSymbolAtLocation because it is a declaration + var symbol = getSymbolOfNode(node); + return getDeclaredTypeOfSymbol(symbol); + } + if (isTypeDeclarationName(node)) { + var symbol = getSymbolAtLocation(node); + return symbol ? getDeclaredTypeOfSymbol(symbol) : errorType; + } + if (ts.isDeclaration(node)) { + // In this case, we call getSymbolOfNode instead of getSymbolAtLocation because it is a declaration + var symbol = getSymbolOfNode(node); + return getTypeOfSymbol(symbol); + } + if (isDeclarationNameOrImportPropertyName(node)) { + var symbol = getSymbolAtLocation(node); + return symbol ? getTypeOfSymbol(symbol) : errorType; + } + if (ts.isBindingPattern(node)) { + return getTypeForVariableLikeDeclaration(node.parent, /*includeOptionality*/ true) || errorType; + } + if (isInRightSideOfImportOrExportAssignment(node)) { + var symbol = getSymbolAtLocation(node); + if (symbol) { + var declaredType = getDeclaredTypeOfSymbol(symbol); + return declaredType !== errorType ? declaredType : getTypeOfSymbol(symbol); + } + } + return errorType; + } + // Gets the type of object literal or array literal of destructuring assignment. + // { a } from + // for ( { a } of elems) { + // } + // [ a ] from + // [a] = [ some array ...] + function getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr) { + ts.Debug.assert(expr.kind === 188 /* ObjectLiteralExpression */ || expr.kind === 187 /* ArrayLiteralExpression */); + // If this is from "for of" + // for ( { a } of elems) { + // } + if (expr.parent.kind === 227 /* ForOfStatement */) { + var iteratedType = checkRightHandSideOfForOf(expr.parent.expression, expr.parent.awaitModifier); + return checkDestructuringAssignment(expr, iteratedType || errorType); + } + // If this is from "for" initializer + // for ({a } = elems[0];.....) { } + if (expr.parent.kind === 204 /* BinaryExpression */) { + var iteratedType = getTypeOfExpression(expr.parent.right); + return checkDestructuringAssignment(expr, iteratedType || errorType); + } + // If this is from nested object binding pattern + // for ({ skills: { primary, secondary } } = multiRobot, i = 0; i < 1; i++) { + if (expr.parent.kind === 275 /* PropertyAssignment */) { + var typeOfParentObjectLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr.parent.parent); + return checkObjectLiteralDestructuringPropertyAssignment(typeOfParentObjectLiteral || errorType, expr.parent); // TODO: GH#18217 + } + // Array literal assignment - array destructuring pattern + ts.Debug.assert(expr.parent.kind === 187 /* ArrayLiteralExpression */); + // [{ property1: p1, property2 }] = elems; + var typeOfArrayLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr.parent); + var elementType = checkIteratedTypeOrElementType(typeOfArrayLiteral || errorType, expr.parent, /*allowStringInput*/ false, /*allowAsyncIterables*/ false) || errorType; + return checkArrayLiteralDestructuringElementAssignment(expr.parent, typeOfArrayLiteral, expr.parent.elements.indexOf(expr), elementType || errorType); // TODO: GH#18217 + } + // Gets the property symbol corresponding to the property in destructuring assignment + // 'property1' from + // for ( { property1: a } of elems) { + // } + // 'property1' at location 'a' from: + // [a] = [ property1, property2 ] + function getPropertySymbolOfDestructuringAssignment(location) { + // Get the type of the object or array literal and then look for property of given name in the type + var typeOfObjectLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(location.parent.parent); + return typeOfObjectLiteral && getPropertyOfType(typeOfObjectLiteral, location.escapedText); + } + function getRegularTypeOfExpression(expr) { + if (ts.isRightSideOfQualifiedNameOrPropertyAccess(expr)) { + expr = expr.parent; + } + return getRegularTypeOfLiteralType(getTypeOfExpression(expr)); + } + /** + * Gets either the static or instance type of a class element, based on + * whether the element is declared as "static". + */ + function getParentTypeOfClassElement(node) { + var classSymbol = getSymbolOfNode(node.parent); + return ts.hasModifier(node, 32 /* Static */) + ? getTypeOfSymbol(classSymbol) + : getDeclaredTypeOfSymbol(classSymbol); + } + function getClassElementPropertyKeyType(element) { + var name = element.name; + switch (name.kind) { + case 72 /* Identifier */: + return getLiteralType(ts.idText(name)); + case 8 /* NumericLiteral */: + case 10 /* StringLiteral */: + return getLiteralType(name.text); + case 149 /* ComputedPropertyName */: + var nameType = checkComputedPropertyName(name); + return isTypeAssignableToKind(nameType, 12288 /* ESSymbolLike */) ? nameType : stringType; + default: + ts.Debug.fail("Unsupported property name."); + return errorType; + } + } + // Return the list of properties of the given type, augmented with properties from Function + // if the type has call or construct signatures + function getAugmentedPropertiesOfType(type) { + type = getApparentType(type); + var propsByName = ts.createSymbolTable(getPropertiesOfType(type)); + var functionType = getSignaturesOfType(type, 0 /* Call */).length ? globalCallableFunctionType : + getSignaturesOfType(type, 1 /* Construct */).length ? globalNewableFunctionType : + undefined; + if (functionType) { + ts.forEach(getPropertiesOfType(functionType), function (p) { + if (!propsByName.has(p.escapedName)) { + propsByName.set(p.escapedName, p); + } + }); + } + return getNamedMembers(propsByName); + } + function typeHasCallOrConstructSignatures(type) { + return ts.typeHasCallOrConstructSignatures(type, checker); + } + function getRootSymbols(symbol) { + var roots = getImmediateRootSymbols(symbol); + return roots ? ts.flatMap(roots, getRootSymbols) : [symbol]; + } + function getImmediateRootSymbols(symbol) { + if (ts.getCheckFlags(symbol) & 6 /* Synthetic */) { + return ts.mapDefined(getSymbolLinks(symbol).containingType.types, function (type) { return getPropertyOfType(type, symbol.escapedName); }); + } + else if (symbol.flags & 33554432 /* Transient */) { + var _a = symbol, leftSpread = _a.leftSpread, rightSpread = _a.rightSpread, syntheticOrigin = _a.syntheticOrigin; + return leftSpread ? [leftSpread, rightSpread] + : syntheticOrigin ? [syntheticOrigin] + : ts.singleElementArray(tryGetAliasTarget(symbol)); + } + return undefined; + } + function tryGetAliasTarget(symbol) { + var target; + var next = symbol; + while (next = getSymbolLinks(next).target) { + target = next; + } + return target; + } + // Emitter support + function isArgumentsLocalBinding(nodeIn) { + if (!ts.isGeneratedIdentifier(nodeIn)) { + var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier); + if (node) { + var isPropertyName_1 = node.parent.kind === 189 /* PropertyAccessExpression */ && node.parent.name === node; + return !isPropertyName_1 && getReferencedValueSymbol(node) === argumentsSymbol; + } + } + return false; + } + function moduleExportsSomeValue(moduleReferenceExpression) { + var moduleSymbol = resolveExternalModuleName(moduleReferenceExpression.parent, moduleReferenceExpression); + if (!moduleSymbol || ts.isShorthandAmbientModuleSymbol(moduleSymbol)) { + // If the module is not found or is shorthand, assume that it may export a value. + return true; + } + var hasExportAssignment = hasExportAssignmentSymbol(moduleSymbol); + // if module has export assignment then 'resolveExternalModuleSymbol' will return resolved symbol for export assignment + // otherwise it will return moduleSymbol itself + moduleSymbol = resolveExternalModuleSymbol(moduleSymbol); + var symbolLinks = getSymbolLinks(moduleSymbol); + if (symbolLinks.exportsSomeValue === undefined) { + // for export assignments - check if resolved symbol for RHS is itself a value + // otherwise - check if at least one export is value + symbolLinks.exportsSomeValue = hasExportAssignment + ? !!(moduleSymbol.flags & 67220415 /* Value */) + : ts.forEachEntry(getExportsOfModule(moduleSymbol), isValue); + } + return symbolLinks.exportsSomeValue; + function isValue(s) { + s = resolveSymbol(s); + return s && !!(s.flags & 67220415 /* Value */); + } + } + function isNameOfModuleOrEnumDeclaration(node) { + return ts.isModuleOrEnumDeclaration(node.parent) && node === node.parent.name; + } + // When resolved as an expression identifier, if the given node references an exported entity, return the declaration + // node of the exported entity's container. Otherwise, return undefined. + function getReferencedExportContainer(nodeIn, prefixLocals) { + var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier); + if (node) { + // When resolving the export container for the name of a module or enum + // declaration, we need to start resolution at the declaration's container. + // Otherwise, we could incorrectly resolve the export container as the + // declaration if it contains an exported member with the same name. + var symbol = getReferencedValueSymbol(node, /*startInDeclarationContainer*/ isNameOfModuleOrEnumDeclaration(node)); + if (symbol) { + if (symbol.flags & 1048576 /* ExportValue */) { + // If we reference an exported entity within the same module declaration, then whether + // we prefix depends on the kind of entity. SymbolFlags.ExportHasLocal encompasses all the + // kinds that we do NOT prefix. + var exportSymbol = getMergedSymbol(symbol.exportSymbol); + if (!prefixLocals && exportSymbol.flags & 944 /* ExportHasLocal */ && !(exportSymbol.flags & 3 /* Variable */)) { + return undefined; + } + symbol = exportSymbol; + } + var parentSymbol_1 = getParentOfSymbol(symbol); + if (parentSymbol_1) { + if (parentSymbol_1.flags & 512 /* ValueModule */ && parentSymbol_1.valueDeclaration.kind === 279 /* SourceFile */) { + var symbolFile = parentSymbol_1.valueDeclaration; + var referenceFile = ts.getSourceFileOfNode(node); + // If `node` accesses an export and that export isn't in the same file, then symbol is a namespace export, so return undefined. + var symbolIsUmdExport = symbolFile !== referenceFile; + return symbolIsUmdExport ? undefined : symbolFile; + } + return ts.findAncestor(node.parent, function (n) { return ts.isModuleOrEnumDeclaration(n) && getSymbolOfNode(n) === parentSymbol_1; }); + } + } + } + } + // When resolved as an expression identifier, if the given node references an import, return the declaration of + // that import. Otherwise, return undefined. + function getReferencedImportDeclaration(nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier); + if (node) { + var symbol = getReferencedValueSymbol(node); + // We should only get the declaration of an alias if there isn't a local value + // declaration for the symbol + if (isNonLocalAlias(symbol, /*excludes*/ 67220415 /* Value */)) { + return getDeclarationOfAliasSymbol(symbol); + } + } + return undefined; + } + function isSymbolOfDeclarationWithCollidingName(symbol) { + if (symbol.flags & 418 /* BlockScoped */) { + var links = getSymbolLinks(symbol); + if (links.isDeclarationWithCollidingName === undefined) { + var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); + if (ts.isStatementWithLocals(container)) { + var nodeLinks_1 = getNodeLinks(symbol.valueDeclaration); + if (resolveName(container.parent, symbol.escapedName, 67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)) { + // redeclaration - always should be renamed + links.isDeclarationWithCollidingName = true; + } + else if (nodeLinks_1.flags & 262144 /* CapturedBlockScopedBinding */) { + // binding is captured in the function + // should be renamed if: + // - binding is not top level - top level bindings never collide with anything + // AND + // - binding is not declared in loop, should be renamed to avoid name reuse across siblings + // let a, b + // { let x = 1; a = () => x; } + // { let x = 100; b = () => x; } + // console.log(a()); // should print '1' + // console.log(b()); // should print '100' + // OR + // - binding is declared inside loop but not in inside initializer of iteration statement or directly inside loop body + // * variables from initializer are passed to rewritten loop body as parameters so they are not captured directly + // * variables that are declared immediately in loop body will become top level variable after loop is rewritten and thus + // they will not collide with anything + var isDeclaredInLoop = nodeLinks_1.flags & 524288 /* BlockScopedBindingInLoop */; + var inLoopInitializer = ts.isIterationStatement(container, /*lookInLabeledStatements*/ false); + var inLoopBodyBlock = container.kind === 218 /* Block */ && ts.isIterationStatement(container.parent, /*lookInLabeledStatements*/ false); + links.isDeclarationWithCollidingName = !ts.isBlockScopedContainerTopLevel(container) && (!isDeclaredInLoop || (!inLoopInitializer && !inLoopBodyBlock)); + } + else { + links.isDeclarationWithCollidingName = false; + } + } + } + return links.isDeclarationWithCollidingName; + } + return false; + } + // When resolved as an expression identifier, if the given node references a nested block scoped entity with + // a name that either hides an existing name or might hide it when compiled downlevel, + // return the declaration of that entity. Otherwise, return undefined. + function getReferencedDeclarationWithCollidingName(nodeIn) { + if (!ts.isGeneratedIdentifier(nodeIn)) { + var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier); + if (node) { + var symbol = getReferencedValueSymbol(node); + if (symbol && isSymbolOfDeclarationWithCollidingName(symbol)) { + return symbol.valueDeclaration; + } + } + } + return undefined; + } + // Return true if the given node is a declaration of a nested block scoped entity with a name that either hides an + // existing name or might hide a name when compiled downlevel + function isDeclarationWithCollidingName(nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isDeclaration); + if (node) { + var symbol = getSymbolOfNode(node); + if (symbol) { + return isSymbolOfDeclarationWithCollidingName(symbol); + } + } + return false; + } + function isValueAliasDeclaration(node) { + switch (node.kind) { + case 248 /* ImportEqualsDeclaration */: + case 250 /* ImportClause */: + case 251 /* NamespaceImport */: + case 253 /* ImportSpecifier */: + case 257 /* ExportSpecifier */: + return isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol); + case 255 /* ExportDeclaration */: + var exportClause = node.exportClause; + return !!exportClause && ts.some(exportClause.elements, isValueAliasDeclaration); + case 254 /* ExportAssignment */: + return node.expression + && node.expression.kind === 72 /* Identifier */ + ? isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol) + : true; + } + return false; + } + function isTopLevelValueImportEqualsWithEntityName(nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isImportEqualsDeclaration); + if (node === undefined || node.parent.kind !== 279 /* SourceFile */ || !ts.isInternalModuleImportEqualsDeclaration(node)) { + // parent is not source file or it is not reference to internal module + return false; + } + var isValue = isAliasResolvedToValue(getSymbolOfNode(node)); + return isValue && node.moduleReference && !ts.nodeIsMissing(node.moduleReference); + } + function isAliasResolvedToValue(symbol) { + var target = resolveAlias(symbol); + if (target === unknownSymbol) { + return true; + } + // const enums and modules that contain only const enums are not considered values from the emit perspective + // unless 'preserveConstEnums' option is set to true + return !!(target.flags & 67220415 /* Value */) && + (compilerOptions.preserveConstEnums || !isConstEnumOrConstEnumOnlyModule(target)); + } + function isConstEnumOrConstEnumOnlyModule(s) { + return isConstEnumSymbol(s) || !!s.constEnumOnlyModule; + } + function isReferencedAliasDeclaration(node, checkChildren) { + if (ts.isAliasSymbolDeclaration(node)) { + var symbol = getSymbolOfNode(node); + if (symbol && getSymbolLinks(symbol).referenced) { + return true; + } + var target = getSymbolLinks(symbol).target; // TODO: GH#18217 + if (target && ts.getModifierFlags(node) & 1 /* Export */ && + target.flags & 67220415 /* Value */ && (compilerOptions.preserveConstEnums || !isConstEnumOrConstEnumOnlyModule(target))) { + // An `export import ... =` of a value symbol is always considered referenced + return true; + } + } + if (checkChildren) { + return !!ts.forEachChild(node, function (node) { return isReferencedAliasDeclaration(node, checkChildren); }); + } + return false; + } + function isImplementationOfOverload(node) { + if (ts.nodeIsPresent(node.body)) { + if (ts.isGetAccessor(node) || ts.isSetAccessor(node)) + return false; // Get or set accessors can never be overload implementations, but can have up to 2 signatures + var symbol = getSymbolOfNode(node); + var signaturesOfSymbol = getSignaturesOfSymbol(symbol); + // If this function body corresponds to function with multiple signature, it is implementation of overload + // e.g.: function foo(a: string): string; + // function foo(a: number): number; + // function foo(a: any) { // This is implementation of the overloads + // return a; + // } + return signaturesOfSymbol.length > 1 || + // If there is single signature for the symbol, it is overload if that signature isn't coming from the node + // e.g.: function foo(a: string): string; + // function foo(a: any) { // This is implementation of the overloads + // return a; + // } + (signaturesOfSymbol.length === 1 && signaturesOfSymbol[0].declaration !== node); + } + return false; + } + function isRequiredInitializedParameter(parameter) { + return !!strictNullChecks && + !isOptionalParameter(parameter) && + !ts.isJSDocParameterTag(parameter) && + !!parameter.initializer && + !ts.hasModifier(parameter, 92 /* ParameterPropertyModifier */); + } + function isOptionalUninitializedParameterProperty(parameter) { + return strictNullChecks && + isOptionalParameter(parameter) && + !parameter.initializer && + ts.hasModifier(parameter, 92 /* ParameterPropertyModifier */); + } + function isExpandoFunctionDeclaration(node) { + var declaration = ts.getParseTreeNode(node, ts.isFunctionDeclaration); + if (!declaration) { + return false; + } + var symbol = getSymbolOfNode(declaration); + if (!symbol || !(symbol.flags & 16 /* Function */)) { + return false; + } + return !!ts.forEachEntry(getExportsOfSymbol(symbol), function (p) { return p.flags & 67220415 /* Value */ && ts.isPropertyAccessExpression(p.valueDeclaration); }); + } + function getPropertiesOfContainerFunction(node) { + var declaration = ts.getParseTreeNode(node, ts.isFunctionDeclaration); + if (!declaration) { + return ts.emptyArray; + } + var symbol = getSymbolOfNode(declaration); + return symbol && getPropertiesOfType(getTypeOfSymbol(symbol)) || ts.emptyArray; + } + function getNodeCheckFlags(node) { + return getNodeLinks(node).flags || 0; + } + function getEnumMemberValue(node) { + computeEnumMemberValues(node.parent); + return getNodeLinks(node).enumMemberValue; + } + function canHaveConstantValue(node) { + switch (node.kind) { + case 278 /* EnumMember */: + case 189 /* PropertyAccessExpression */: + case 190 /* ElementAccessExpression */: + return true; + } + return false; + } + function getConstantValue(node) { + if (node.kind === 278 /* EnumMember */) { + return getEnumMemberValue(node); + } + var symbol = getNodeLinks(node).resolvedSymbol; + if (symbol && (symbol.flags & 8 /* EnumMember */)) { + // inline property\index accesses only for const enums + var member = symbol.valueDeclaration; + if (ts.isEnumConst(member.parent)) { + return getEnumMemberValue(member); + } + } + return undefined; + } + function isFunctionType(type) { + return !!(type.flags & 524288 /* Object */) && getSignaturesOfType(type, 0 /* Call */).length > 0; + } + function getTypeReferenceSerializationKind(typeNameIn, location) { + // ensure both `typeName` and `location` are parse tree nodes. + var typeName = ts.getParseTreeNode(typeNameIn, ts.isEntityName); + if (!typeName) + return ts.TypeReferenceSerializationKind.Unknown; + if (location) { + location = ts.getParseTreeNode(location); + if (!location) + return ts.TypeReferenceSerializationKind.Unknown; + } + // Resolve the symbol as a value to ensure the type can be reached at runtime during emit. + var valueSymbol = resolveEntityName(typeName, 67220415 /* Value */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location); + // Resolve the symbol as a type so that we can provide a more useful hint for the type serializer. + var typeSymbol = resolveEntityName(typeName, 67897832 /* Type */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location); + if (valueSymbol && valueSymbol === typeSymbol) { + var globalPromiseSymbol = getGlobalPromiseConstructorSymbol(/*reportErrors*/ false); + if (globalPromiseSymbol && valueSymbol === globalPromiseSymbol) { + return ts.TypeReferenceSerializationKind.Promise; + } + var constructorType = getTypeOfSymbol(valueSymbol); + if (constructorType && isConstructorType(constructorType)) { + return ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue; + } + } + // We might not be able to resolve type symbol so use unknown type in that case (eg error case) + if (!typeSymbol) { + return ts.TypeReferenceSerializationKind.Unknown; + } + var type = getDeclaredTypeOfSymbol(typeSymbol); + if (type === errorType) { + return ts.TypeReferenceSerializationKind.Unknown; + } + else if (type.flags & 3 /* AnyOrUnknown */) { + return ts.TypeReferenceSerializationKind.ObjectType; + } + else if (isTypeAssignableToKind(type, 16384 /* Void */ | 98304 /* Nullable */ | 131072 /* Never */)) { + return ts.TypeReferenceSerializationKind.VoidNullableOrNeverType; + } + else if (isTypeAssignableToKind(type, 528 /* BooleanLike */)) { + return ts.TypeReferenceSerializationKind.BooleanType; + } + else if (isTypeAssignableToKind(type, 296 /* NumberLike */)) { + return ts.TypeReferenceSerializationKind.NumberLikeType; + } + else if (isTypeAssignableToKind(type, 2112 /* BigIntLike */)) { + return ts.TypeReferenceSerializationKind.BigIntLikeType; + } + else if (isTypeAssignableToKind(type, 132 /* StringLike */)) { + return ts.TypeReferenceSerializationKind.StringLikeType; + } + else if (isTupleType(type)) { + return ts.TypeReferenceSerializationKind.ArrayLikeType; + } + else if (isTypeAssignableToKind(type, 12288 /* ESSymbolLike */)) { + return ts.TypeReferenceSerializationKind.ESSymbolType; + } + else if (isFunctionType(type)) { + return ts.TypeReferenceSerializationKind.TypeWithCallSignature; + } + else if (isArrayType(type)) { + return ts.TypeReferenceSerializationKind.ArrayLikeType; + } + else { + return ts.TypeReferenceSerializationKind.ObjectType; + } + } + function createTypeOfDeclaration(declarationIn, enclosingDeclaration, flags, tracker, addUndefined) { + var declaration = ts.getParseTreeNode(declarationIn, ts.isVariableLikeOrAccessor); + if (!declaration) { + return ts.createToken(120 /* AnyKeyword */); + } + // Get type of the symbol if this is the valid symbol otherwise get type at location + var symbol = getSymbolOfNode(declaration); + var type = symbol && !(symbol.flags & (2048 /* TypeLiteral */ | 131072 /* Signature */)) + ? getWidenedLiteralType(getTypeOfSymbol(symbol)) + : errorType; + if (type.flags & 8192 /* UniqueESSymbol */ && + type.symbol === symbol) { + flags |= 1048576 /* AllowUniqueESSymbolType */; + } + if (addUndefined) { + type = getOptionalType(type); + } + return nodeBuilder.typeToTypeNode(type, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, tracker); + } + function createReturnTypeOfSignatureDeclaration(signatureDeclarationIn, enclosingDeclaration, flags, tracker) { + var signatureDeclaration = ts.getParseTreeNode(signatureDeclarationIn, ts.isFunctionLike); + if (!signatureDeclaration) { + return ts.createToken(120 /* AnyKeyword */); + } + var signature = getSignatureFromDeclaration(signatureDeclaration); + return nodeBuilder.typeToTypeNode(getReturnTypeOfSignature(signature), enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, tracker); + } + function createTypeOfExpression(exprIn, enclosingDeclaration, flags, tracker) { + var expr = ts.getParseTreeNode(exprIn, ts.isExpression); + if (!expr) { + return ts.createToken(120 /* AnyKeyword */); + } + var type = getWidenedType(getRegularTypeOfExpression(expr)); + return nodeBuilder.typeToTypeNode(type, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, tracker); + } + function hasGlobalName(name) { + return globals.has(ts.escapeLeadingUnderscores(name)); + } + function getReferencedValueSymbol(reference, startInDeclarationContainer) { + var resolvedSymbol = getNodeLinks(reference).resolvedSymbol; + if (resolvedSymbol) { + return resolvedSymbol; + } + var location = reference; + if (startInDeclarationContainer) { + // When resolving the name of a declaration as a value, we need to start resolution + // at a point outside of the declaration. + var parent = reference.parent; + if (ts.isDeclaration(parent) && reference === parent.name) { + location = getDeclarationContainer(parent); + } + } + return resolveName(location, reference.escapedText, 67220415 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */, /*nodeNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); + } + function getReferencedValueDeclaration(referenceIn) { + if (!ts.isGeneratedIdentifier(referenceIn)) { + var reference = ts.getParseTreeNode(referenceIn, ts.isIdentifier); + if (reference) { + var symbol = getReferencedValueSymbol(reference); + if (symbol) { + return getExportSymbolOfValueSymbolIfExported(symbol).valueDeclaration; + } + } + } + return undefined; + } + function isLiteralConstDeclaration(node) { + if (ts.isDeclarationReadonly(node) || ts.isVariableDeclaration(node) && ts.isVarConst(node)) { + return isFreshLiteralType(getTypeOfSymbol(getSymbolOfNode(node))); + } + return false; + } + function literalTypeToNode(type, enclosing, tracker) { + var enumResult = type.flags & 1024 /* EnumLiteral */ ? nodeBuilder.symbolToExpression(type.symbol, 67220415 /* Value */, enclosing, /*flags*/ undefined, tracker) + : type === trueType ? ts.createTrue() : type === falseType && ts.createFalse(); + return enumResult || ts.createLiteral(type.value); + } + function createLiteralConstValue(node, tracker) { + var type = getTypeOfSymbol(getSymbolOfNode(node)); + return literalTypeToNode(type, node, tracker); + } + function createResolver() { + // this variable and functions that use it are deliberately moved here from the outer scope + // to avoid scope pollution + var resolvedTypeReferenceDirectives = host.getResolvedTypeReferenceDirectives(); + var fileToDirective; + if (resolvedTypeReferenceDirectives) { + // populate reverse mapping: file path -> type reference directive that was resolved to this file + fileToDirective = ts.createMap(); + resolvedTypeReferenceDirectives.forEach(function (resolvedDirective, key) { + if (!resolvedDirective || !resolvedDirective.resolvedFileName) { + return; + } + var file = host.getSourceFile(resolvedDirective.resolvedFileName); + fileToDirective.set(file.path, key); + }); + } + return { + getReferencedExportContainer: getReferencedExportContainer, + getReferencedImportDeclaration: getReferencedImportDeclaration, + getReferencedDeclarationWithCollidingName: getReferencedDeclarationWithCollidingName, + isDeclarationWithCollidingName: isDeclarationWithCollidingName, + isValueAliasDeclaration: function (node) { + node = ts.getParseTreeNode(node); + // Synthesized nodes are always treated like values. + return node ? isValueAliasDeclaration(node) : true; + }, + hasGlobalName: hasGlobalName, + isReferencedAliasDeclaration: function (node, checkChildren) { + node = ts.getParseTreeNode(node); + // Synthesized nodes are always treated as referenced. + return node ? isReferencedAliasDeclaration(node, checkChildren) : true; + }, + getNodeCheckFlags: function (node) { + node = ts.getParseTreeNode(node); + return node ? getNodeCheckFlags(node) : 0; + }, + isTopLevelValueImportEqualsWithEntityName: isTopLevelValueImportEqualsWithEntityName, + isDeclarationVisible: isDeclarationVisible, + isImplementationOfOverload: isImplementationOfOverload, + isRequiredInitializedParameter: isRequiredInitializedParameter, + isOptionalUninitializedParameterProperty: isOptionalUninitializedParameterProperty, + isExpandoFunctionDeclaration: isExpandoFunctionDeclaration, + getPropertiesOfContainerFunction: getPropertiesOfContainerFunction, + createTypeOfDeclaration: createTypeOfDeclaration, + createReturnTypeOfSignatureDeclaration: createReturnTypeOfSignatureDeclaration, + createTypeOfExpression: createTypeOfExpression, + createLiteralConstValue: createLiteralConstValue, + isSymbolAccessible: isSymbolAccessible, + isEntityNameVisible: isEntityNameVisible, + getConstantValue: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, canHaveConstantValue); + return node ? getConstantValue(node) : undefined; + }, + collectLinkedAliases: collectLinkedAliases, + getReferencedValueDeclaration: getReferencedValueDeclaration, + getTypeReferenceSerializationKind: getTypeReferenceSerializationKind, + isOptionalParameter: isOptionalParameter, + moduleExportsSomeValue: moduleExportsSomeValue, + isArgumentsLocalBinding: isArgumentsLocalBinding, + getExternalModuleFileFromDeclaration: getExternalModuleFileFromDeclaration, + getTypeReferenceDirectivesForEntityName: getTypeReferenceDirectivesForEntityName, + getTypeReferenceDirectivesForSymbol: getTypeReferenceDirectivesForSymbol, + isLiteralConstDeclaration: isLiteralConstDeclaration, + isLateBound: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isDeclaration); + var symbol = node && getSymbolOfNode(node); + return !!(symbol && ts.getCheckFlags(symbol) & 1024 /* Late */); + }, + getJsxFactoryEntity: function (location) { return location ? (getJsxNamespace(location), (ts.getSourceFileOfNode(location).localJsxFactory || _jsxFactoryEntity)) : _jsxFactoryEntity; }, + getAllAccessorDeclarations: function (accessor) { + accessor = ts.getParseTreeNode(accessor, ts.isGetOrSetAccessorDeclaration); // TODO: GH#18217 + var otherKind = accessor.kind === 159 /* SetAccessor */ ? 158 /* GetAccessor */ : 159 /* SetAccessor */; + var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(accessor), otherKind); + var firstAccessor = otherAccessor && (otherAccessor.pos < accessor.pos) ? otherAccessor : accessor; + var secondAccessor = otherAccessor && (otherAccessor.pos < accessor.pos) ? accessor : otherAccessor; + var setAccessor = accessor.kind === 159 /* SetAccessor */ ? accessor : otherAccessor; + var getAccessor = accessor.kind === 158 /* GetAccessor */ ? accessor : otherAccessor; + return { + firstAccessor: firstAccessor, + secondAccessor: secondAccessor, + setAccessor: setAccessor, + getAccessor: getAccessor + }; + }, + getSymbolOfExternalModuleSpecifier: function (moduleName) { return resolveExternalModuleNameWorker(moduleName, moduleName, /*moduleNotFoundError*/ undefined); }, + isBindingCapturedByNode: function (node, decl) { + var parseNode = ts.getParseTreeNode(node); + var parseDecl = ts.getParseTreeNode(decl); + return !!parseNode && !!parseDecl && (ts.isVariableDeclaration(parseDecl) || ts.isBindingElement(parseDecl)) && isBindingCapturedByNode(parseNode, parseDecl); + } + }; + function isInHeritageClause(node) { + return node.parent && node.parent.kind === 211 /* ExpressionWithTypeArguments */ && node.parent.parent && node.parent.parent.kind === 273 /* HeritageClause */; + } + // defined here to avoid outer scope pollution + function getTypeReferenceDirectivesForEntityName(node) { + // program does not have any files with type reference directives - bail out + if (!fileToDirective) { + return undefined; + } + // property access can only be used as values, or types when within an expression with type arguments inside a heritage clause + // qualified names can only be used as types\namespaces + // identifiers are treated as values only if they appear in type queries + var meaning = 67897832 /* Type */ | 1920 /* Namespace */; + if ((node.kind === 72 /* Identifier */ && isInTypeQuery(node)) || (node.kind === 189 /* PropertyAccessExpression */ && !isInHeritageClause(node))) { + meaning = 67220415 /* Value */ | 1048576 /* ExportValue */; + } + var symbol = resolveEntityName(node, meaning, /*ignoreErrors*/ true); + return symbol && symbol !== unknownSymbol ? getTypeReferenceDirectivesForSymbol(symbol, meaning) : undefined; + } + // defined here to avoid outer scope pollution + function getTypeReferenceDirectivesForSymbol(symbol, meaning) { + // program does not have any files with type reference directives - bail out + if (!fileToDirective) { + return undefined; + } + if (!isSymbolFromTypeDeclarationFile(symbol)) { + return undefined; + } + // check what declarations in the symbol can contribute to the target meaning + var typeReferenceDirectives; + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + // check meaning of the local symbol to see if declaration needs to be analyzed further + if (decl.symbol && decl.symbol.flags & meaning) { + var file = ts.getSourceFileOfNode(decl); + var typeReferenceDirective = fileToDirective.get(file.path); + if (typeReferenceDirective) { + (typeReferenceDirectives || (typeReferenceDirectives = [])).push(typeReferenceDirective); + } + else { + // found at least one entry that does not originate from type reference directive + return undefined; + } + } + } + return typeReferenceDirectives; + } + function isSymbolFromTypeDeclarationFile(symbol) { + // bail out if symbol does not have associated declarations (i.e. this is transient symbol created for property in binding pattern) + if (!symbol.declarations) { + return false; + } + // walk the parent chain for symbols to make sure that top level parent symbol is in the global scope + // external modules cannot define or contribute to type declaration files + var current = symbol; + while (true) { + var parent = getParentOfSymbol(current); + if (parent) { + current = parent; + } + else { + break; + } + } + if (current.valueDeclaration && current.valueDeclaration.kind === 279 /* SourceFile */ && current.flags & 512 /* ValueModule */) { + return false; + } + // check that at least one declaration of top level symbol originates from type declaration file + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + var file = ts.getSourceFileOfNode(decl); + if (fileToDirective.has(file.path)) { + return true; + } + } + return false; + } + } + function getExternalModuleFileFromDeclaration(declaration) { + var specifier = declaration.kind === 244 /* ModuleDeclaration */ ? ts.tryCast(declaration.name, ts.isStringLiteral) : ts.getExternalModuleName(declaration); + var moduleSymbol = resolveExternalModuleNameWorker(specifier, specifier, /*moduleNotFoundError*/ undefined); // TODO: GH#18217 + if (!moduleSymbol) { + return undefined; + } + return ts.getDeclarationOfKind(moduleSymbol, 279 /* SourceFile */); + } + function initializeTypeChecker() { + // Bind all source files and propagate errors + for (var _i = 0, _a = host.getSourceFiles(); _i < _a.length; _i++) { + var file = _a[_i]; + ts.bindSourceFile(file, compilerOptions); + } + amalgamatedDuplicates = ts.createMap(); + // Initialize global symbol table + var augmentations; + for (var _b = 0, _c = host.getSourceFiles(); _b < _c.length; _b++) { + var file = _c[_b]; + if (file.redirectInfo) { + continue; + } + if (!ts.isExternalOrCommonJsModule(file)) { + mergeSymbolTable(globals, file.locals); + } + if (file.jsGlobalAugmentations) { + mergeSymbolTable(globals, file.jsGlobalAugmentations); + } + if (file.patternAmbientModules && file.patternAmbientModules.length) { + patternAmbientModules = ts.concatenate(patternAmbientModules, file.patternAmbientModules); + } + if (file.moduleAugmentations.length) { + (augmentations || (augmentations = [])).push(file.moduleAugmentations); + } + if (file.symbol && file.symbol.globalExports) { + // Merge in UMD exports with first-in-wins semantics (see #9771) + var source = file.symbol.globalExports; + source.forEach(function (sourceSymbol, id) { + if (!globals.has(id)) { + globals.set(id, sourceSymbol); + } + }); + } + } + // We do global augmentations separately from module augmentations (and before creating global types) because they + // 1. Affect global types. We won't have the correct global types until global augmentations are merged. Also, + // 2. Module augmentation instantiation requires creating the type of a module, which, in turn, can require + // checking for an export or property on the module (if export=) which, in turn, can fall back to the + // apparent type of the module - either globalObjectType or globalFunctionType - which wouldn't exist if we + // did module augmentations prior to finalizing the global types. + if (augmentations) { + // merge _global_ module augmentations. + // this needs to be done after global symbol table is initialized to make sure that all ambient modules are indexed + for (var _d = 0, augmentations_1 = augmentations; _d < augmentations_1.length; _d++) { + var list = augmentations_1[_d]; + for (var _e = 0, list_1 = list; _e < list_1.length; _e++) { + var augmentation = list_1[_e]; + if (!ts.isGlobalScopeAugmentation(augmentation.parent)) + continue; + mergeModuleAugmentation(augmentation); + } + } + } + // Setup global builtins + addToSymbolTable(globals, builtinGlobals, ts.Diagnostics.Declaration_name_conflicts_with_built_in_global_identifier_0); + getSymbolLinks(undefinedSymbol).type = undefinedWideningType; + getSymbolLinks(argumentsSymbol).type = getGlobalType("IArguments", /*arity*/ 0, /*reportErrors*/ true); + getSymbolLinks(unknownSymbol).type = errorType; + // Initialize special types + globalArrayType = getGlobalType("Array", /*arity*/ 1, /*reportErrors*/ true); + globalObjectType = getGlobalType("Object", /*arity*/ 0, /*reportErrors*/ true); + globalFunctionType = getGlobalType("Function", /*arity*/ 0, /*reportErrors*/ true); + globalCallableFunctionType = strictBindCallApply && getGlobalType("CallableFunction", /*arity*/ 0, /*reportErrors*/ true) || globalFunctionType; + globalNewableFunctionType = strictBindCallApply && getGlobalType("NewableFunction", /*arity*/ 0, /*reportErrors*/ true) || globalFunctionType; + globalStringType = getGlobalType("String", /*arity*/ 0, /*reportErrors*/ true); + globalNumberType = getGlobalType("Number", /*arity*/ 0, /*reportErrors*/ true); + globalBooleanType = getGlobalType("Boolean", /*arity*/ 0, /*reportErrors*/ true); + globalRegExpType = getGlobalType("RegExp", /*arity*/ 0, /*reportErrors*/ true); + anyArrayType = createArrayType(anyType); + autoArrayType = createArrayType(autoType); + if (autoArrayType === emptyObjectType) { + // autoArrayType is used as a marker, so even if global Array type is not defined, it needs to be a unique type + autoArrayType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + } + globalReadonlyArrayType = getGlobalTypeOrUndefined("ReadonlyArray", /*arity*/ 1); + anyReadonlyArrayType = globalReadonlyArrayType ? createTypeFromGenericGlobalType(globalReadonlyArrayType, [anyType]) : anyArrayType; + globalThisType = getGlobalTypeOrUndefined("ThisType", /*arity*/ 1); + if (augmentations) { + // merge _nonglobal_ module augmentations. + // this needs to be done after global symbol table is initialized to make sure that all ambient modules are indexed + for (var _f = 0, augmentations_2 = augmentations; _f < augmentations_2.length; _f++) { + var list = augmentations_2[_f]; + for (var _g = 0, list_2 = list; _g < list_2.length; _g++) { + var augmentation = list_2[_g]; + if (ts.isGlobalScopeAugmentation(augmentation.parent)) + continue; + mergeModuleAugmentation(augmentation); + } + } + } + amalgamatedDuplicates.forEach(function (_a) { + var firstFile = _a.firstFile, secondFile = _a.secondFile, conflictingSymbols = _a.conflictingSymbols; + // If not many things conflict, issue individual errors + if (conflictingSymbols.size < 8) { + conflictingSymbols.forEach(function (_a, symbolName) { + var isBlockScoped = _a.isBlockScoped, firstFileLocations = _a.firstFileLocations, secondFileLocations = _a.secondFileLocations; + var message = isBlockScoped ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 : ts.Diagnostics.Duplicate_identifier_0; + for (var _i = 0, firstFileLocations_1 = firstFileLocations; _i < firstFileLocations_1.length; _i++) { + var node = firstFileLocations_1[_i]; + addDuplicateDeclarationError(node, message, symbolName, secondFileLocations); + } + for (var _b = 0, secondFileLocations_1 = secondFileLocations; _b < secondFileLocations_1.length; _b++) { + var node = secondFileLocations_1[_b]; + addDuplicateDeclarationError(node, message, symbolName, firstFileLocations); + } + }); + } + else { + // Otherwise issue top-level error since the files appear very identical in terms of what they contain + var list = ts.arrayFrom(conflictingSymbols.keys()).join(", "); + diagnostics.add(addRelatedInfo(ts.createDiagnosticForNode(firstFile, ts.Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list), ts.createDiagnosticForNode(secondFile, ts.Diagnostics.Conflicts_are_in_this_file))); + diagnostics.add(addRelatedInfo(ts.createDiagnosticForNode(secondFile, ts.Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list), ts.createDiagnosticForNode(firstFile, ts.Diagnostics.Conflicts_are_in_this_file))); + } + }); + amalgamatedDuplicates = undefined; + } + function checkExternalEmitHelpers(location, helpers) { + if ((requestedExternalEmitHelpers & helpers) !== helpers && compilerOptions.importHelpers) { + var sourceFile = ts.getSourceFileOfNode(location); + if (ts.isEffectiveExternalModule(sourceFile, compilerOptions) && !(location.flags & 4194304 /* Ambient */)) { + var helpersModule = resolveHelpersModule(sourceFile, location); + if (helpersModule !== unknownSymbol) { + var uncheckedHelpers = helpers & ~requestedExternalEmitHelpers; + for (var helper = 1 /* FirstEmitHelper */; helper <= 65536 /* LastEmitHelper */; helper <<= 1) { + if (uncheckedHelpers & helper) { + var name = getHelperName(helper); + var symbol = getSymbol(helpersModule.exports, ts.escapeLeadingUnderscores(name), 67220415 /* Value */); + if (!symbol) { + error(location, ts.Diagnostics.This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1, ts.externalHelpersModuleNameText, name); + } + } + } + } + requestedExternalEmitHelpers |= helpers; + } + } + } + function getHelperName(helper) { + switch (helper) { + case 1 /* Extends */: return "__extends"; + case 2 /* Assign */: return "__assign"; + case 4 /* Rest */: return "__rest"; + case 8 /* Decorate */: return "__decorate"; + case 16 /* Metadata */: return "__metadata"; + case 32 /* Param */: return "__param"; + case 64 /* Awaiter */: return "__awaiter"; + case 128 /* Generator */: return "__generator"; + case 256 /* Values */: return "__values"; + case 512 /* Read */: return "__read"; + case 1024 /* Spread */: return "__spread"; + case 2048 /* Await */: return "__await"; + case 4096 /* AsyncGenerator */: return "__asyncGenerator"; + case 8192 /* AsyncDelegator */: return "__asyncDelegator"; + case 16384 /* AsyncValues */: return "__asyncValues"; + case 32768 /* ExportStar */: return "__exportStar"; + case 65536 /* MakeTemplateObject */: return "__makeTemplateObject"; + default: return ts.Debug.fail("Unrecognized helper"); + } + } + function resolveHelpersModule(node, errorNode) { + if (!externalHelpersModule) { + externalHelpersModule = resolveExternalModule(node, ts.externalHelpersModuleNameText, ts.Diagnostics.This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found, errorNode) || unknownSymbol; + } + return externalHelpersModule; + } + // GRAMMAR CHECKING + function checkGrammarDecoratorsAndModifiers(node) { + return checkGrammarDecorators(node) || checkGrammarModifiers(node); + } + function checkGrammarDecorators(node) { + if (!node.decorators) { + return false; + } + if (!ts.nodeCanBeDecorated(node, node.parent, node.parent.parent)) { + if (node.kind === 156 /* MethodDeclaration */ && !ts.nodeIsPresent(node.body)) { + return grammarErrorOnFirstToken(node, ts.Diagnostics.A_decorator_can_only_decorate_a_method_implementation_not_an_overload); + } + else { + return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_are_not_valid_here); + } + } + else if (node.kind === 158 /* GetAccessor */ || node.kind === 159 /* SetAccessor */) { + var accessors = ts.getAllAccessorDeclarations(node.parent.members, node); + if (accessors.firstAccessor.decorators && node === accessors.secondAccessor) { + return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name); + } + } + return false; + } + function checkGrammarModifiers(node) { + var quickResult = reportObviousModifierErrors(node); + if (quickResult !== undefined) { + return quickResult; + } + var lastStatic, lastDeclare, lastAsync, lastReadonly; + var flags = 0 /* None */; + for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) { + var modifier = _a[_i]; + if (modifier.kind !== 133 /* ReadonlyKeyword */) { + if (node.kind === 153 /* PropertySignature */ || node.kind === 155 /* MethodSignature */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_type_member, ts.tokenToString(modifier.kind)); + } + if (node.kind === 162 /* IndexSignature */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_an_index_signature, ts.tokenToString(modifier.kind)); + } + } + switch (modifier.kind) { + case 77 /* ConstKeyword */: + if (node.kind !== 243 /* EnumDeclaration */) { + return grammarErrorOnNode(node, ts.Diagnostics.A_class_member_cannot_have_the_0_keyword, ts.tokenToString(77 /* ConstKeyword */)); + } + break; + case 115 /* PublicKeyword */: + case 114 /* ProtectedKeyword */: + case 113 /* PrivateKeyword */: + var text = visibilityToString(ts.modifierToFlag(modifier.kind)); + if (flags & 28 /* AccessibilityModifier */) { + return grammarErrorOnNode(modifier, ts.Diagnostics.Accessibility_modifier_already_seen); + } + else if (flags & 32 /* Static */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "static"); + } + else if (flags & 64 /* Readonly */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "readonly"); + } + else if (flags & 256 /* Async */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "async"); + } + else if (node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 279 /* SourceFile */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, text); + } + else if (flags & 128 /* Abstract */) { + if (modifier.kind === 113 /* PrivateKeyword */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, text, "abstract"); + } + else { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "abstract"); + } + } + flags |= ts.modifierToFlag(modifier.kind); + break; + case 116 /* StaticKeyword */: + if (flags & 32 /* Static */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "static"); + } + else if (flags & 64 /* Readonly */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "readonly"); + } + else if (flags & 256 /* Async */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "async"); + } + else if (node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 279 /* SourceFile */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, "static"); + } + else if (node.kind === 151 /* Parameter */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "static"); + } + else if (flags & 128 /* Abstract */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "abstract"); + } + flags |= 32 /* Static */; + lastStatic = modifier; + break; + case 133 /* ReadonlyKeyword */: + if (flags & 64 /* Readonly */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "readonly"); + } + else if (node.kind !== 154 /* PropertyDeclaration */ && node.kind !== 153 /* PropertySignature */ && node.kind !== 162 /* IndexSignature */ && node.kind !== 151 /* Parameter */) { + // If node.kind === SyntaxKind.Parameter, checkParameter report an error if it's not a parameter property. + return grammarErrorOnNode(modifier, ts.Diagnostics.readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature); + } + flags |= 64 /* Readonly */; + lastReadonly = modifier; + break; + case 85 /* ExportKeyword */: + if (flags & 1 /* Export */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "export"); + } + else if (flags & 2 /* Ambient */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "declare"); + } + else if (flags & 128 /* Abstract */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "abstract"); + } + else if (flags & 256 /* Async */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "async"); + } + else if (node.parent.kind === 240 /* ClassDeclaration */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_class_element, "export"); + } + else if (node.kind === 151 /* Parameter */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "export"); + } + flags |= 1 /* Export */; + break; + case 80 /* DefaultKeyword */: + var container = node.parent.kind === 279 /* SourceFile */ ? node.parent : node.parent.parent; + if (container.kind === 244 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) { + return grammarErrorOnNode(modifier, ts.Diagnostics.A_default_export_can_only_be_used_in_an_ECMAScript_style_module); + } + flags |= 512 /* Default */; + break; + case 125 /* DeclareKeyword */: + if (flags & 2 /* Ambient */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "declare"); + } + else if (flags & 256 /* Async */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async"); + } + else if (node.parent.kind === 240 /* ClassDeclaration */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_class_element, "declare"); + } + else if (node.kind === 151 /* Parameter */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "declare"); + } + else if ((node.parent.flags & 4194304 /* Ambient */) && node.parent.kind === 245 /* ModuleBlock */) { + return grammarErrorOnNode(modifier, ts.Diagnostics.A_declare_modifier_cannot_be_used_in_an_already_ambient_context); + } + flags |= 2 /* Ambient */; + lastDeclare = modifier; + break; + case 118 /* AbstractKeyword */: + if (flags & 128 /* Abstract */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "abstract"); + } + if (node.kind !== 240 /* ClassDeclaration */) { + if (node.kind !== 156 /* MethodDeclaration */ && + node.kind !== 154 /* PropertyDeclaration */ && + node.kind !== 158 /* GetAccessor */ && + node.kind !== 159 /* SetAccessor */) { + return grammarErrorOnNode(modifier, ts.Diagnostics.abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration); + } + if (!(node.parent.kind === 240 /* ClassDeclaration */ && ts.hasModifier(node.parent, 128 /* Abstract */))) { + return grammarErrorOnNode(modifier, ts.Diagnostics.Abstract_methods_can_only_appear_within_an_abstract_class); + } + if (flags & 32 /* Static */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "abstract"); + } + if (flags & 8 /* Private */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "private", "abstract"); + } + } + flags |= 128 /* Abstract */; + break; + case 121 /* AsyncKeyword */: + if (flags & 256 /* Async */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "async"); + } + else if (flags & 2 /* Ambient */ || node.parent.flags & 4194304 /* Ambient */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async"); + } + else if (node.kind === 151 /* Parameter */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "async"); + } + flags |= 256 /* Async */; + lastAsync = modifier; + break; + } + } + if (node.kind === 157 /* Constructor */) { + if (flags & 32 /* Static */) { + return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "static"); + } + if (flags & 128 /* Abstract */) { + return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "abstract"); // TODO: GH#18217 + } + else if (flags & 256 /* Async */) { + return grammarErrorOnNode(lastAsync, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "async"); + } + else if (flags & 64 /* Readonly */) { + return grammarErrorOnNode(lastReadonly, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "readonly"); + } + return false; + } + else if ((node.kind === 249 /* ImportDeclaration */ || node.kind === 248 /* ImportEqualsDeclaration */) && flags & 2 /* Ambient */) { + return grammarErrorOnNode(lastDeclare, ts.Diagnostics.A_0_modifier_cannot_be_used_with_an_import_declaration, "declare"); + } + else if (node.kind === 151 /* Parameter */ && (flags & 92 /* ParameterPropertyModifier */) && ts.isBindingPattern(node.name)) { + return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_may_not_be_declared_using_a_binding_pattern); + } + else if (node.kind === 151 /* Parameter */ && (flags & 92 /* ParameterPropertyModifier */) && node.dotDotDotToken) { + return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_cannot_be_declared_using_a_rest_parameter); + } + if (flags & 256 /* Async */) { + return checkGrammarAsyncModifier(node, lastAsync); + } + return false; + } + /** + * true | false: Early return this value from checkGrammarModifiers. + * undefined: Need to do full checking on the modifiers. + */ + function reportObviousModifierErrors(node) { + return !node.modifiers + ? false + : shouldReportBadModifier(node) + ? grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here) + : undefined; + } + function shouldReportBadModifier(node) { + switch (node.kind) { + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 157 /* Constructor */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 162 /* IndexSignature */: + case 244 /* ModuleDeclaration */: + case 249 /* ImportDeclaration */: + case 248 /* ImportEqualsDeclaration */: + case 255 /* ExportDeclaration */: + case 254 /* ExportAssignment */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 151 /* Parameter */: + return false; + default: + if (node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 279 /* SourceFile */) { + return false; + } + switch (node.kind) { + case 239 /* FunctionDeclaration */: + return nodeHasAnyModifiersExcept(node, 121 /* AsyncKeyword */); + case 240 /* ClassDeclaration */: + return nodeHasAnyModifiersExcept(node, 118 /* AbstractKeyword */); + case 241 /* InterfaceDeclaration */: + case 219 /* VariableStatement */: + case 242 /* TypeAliasDeclaration */: + return true; + case 243 /* EnumDeclaration */: + return nodeHasAnyModifiersExcept(node, 77 /* ConstKeyword */); + default: + ts.Debug.fail(); + return false; + } + } + } + function nodeHasAnyModifiersExcept(node, allowedModifier) { + return node.modifiers.length > 1 || node.modifiers[0].kind !== allowedModifier; + } + function checkGrammarAsyncModifier(node, asyncModifier) { + switch (node.kind) { + case 156 /* MethodDeclaration */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + return false; + } + return grammarErrorOnNode(asyncModifier, ts.Diagnostics._0_modifier_cannot_be_used_here, "async"); + } + function checkGrammarForDisallowedTrailingComma(list, diag) { + if (diag === void 0) { diag = ts.Diagnostics.Trailing_comma_not_allowed; } + if (list && list.hasTrailingComma) { + return grammarErrorAtPos(list[0], list.end - ",".length, ",".length, diag); + } + return false; + } + function checkGrammarTypeParameterList(typeParameters, file) { + if (typeParameters && typeParameters.length === 0) { + var start = typeParameters.pos - "<".length; + var end = ts.skipTrivia(file.text, typeParameters.end) + ">".length; + return grammarErrorAtPos(file, start, end - start, ts.Diagnostics.Type_parameter_list_cannot_be_empty); + } + return false; + } + function checkGrammarParameterList(parameters) { + var seenOptionalParameter = false; + var parameterCount = parameters.length; + for (var i = 0; i < parameterCount; i++) { + var parameter = parameters[i]; + if (parameter.dotDotDotToken) { + if (i !== (parameterCount - 1)) { + return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.A_rest_parameter_must_be_last_in_a_parameter_list); + } + if (!(parameter.flags & 4194304 /* Ambient */)) { // Allow `...foo,` in ambient declarations; see GH#23070 + checkGrammarForDisallowedTrailingComma(parameters, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma); + } + if (ts.isBindingPattern(parameter.name)) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.A_rest_element_cannot_contain_a_binding_pattern); + } + if (parameter.questionToken) { + return grammarErrorOnNode(parameter.questionToken, ts.Diagnostics.A_rest_parameter_cannot_be_optional); + } + if (parameter.initializer) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.A_rest_parameter_cannot_have_an_initializer); + } + } + else if (parameter.questionToken) { + seenOptionalParameter = true; + if (parameter.initializer) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.Parameter_cannot_have_question_mark_and_initializer); + } + } + else if (seenOptionalParameter && !parameter.initializer) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.A_required_parameter_cannot_follow_an_optional_parameter); + } + } + } + function getNonSimpleParameters(parameters) { + return ts.filter(parameters, function (parameter) { return !!parameter.initializer || ts.isBindingPattern(parameter.name) || ts.isRestParameter(parameter); }); + } + function checkGrammarForUseStrictSimpleParameterList(node) { + if (languageVersion >= 3 /* ES2016 */) { + var useStrictDirective_1 = node.body && ts.isBlock(node.body) && ts.findUseStrictPrologue(node.body.statements); + if (useStrictDirective_1) { + var nonSimpleParameters = getNonSimpleParameters(node.parameters); + if (ts.length(nonSimpleParameters)) { + ts.forEach(nonSimpleParameters, function (parameter) { + addRelatedInfo(error(parameter, ts.Diagnostics.This_parameter_is_not_allowed_with_use_strict_directive), ts.createDiagnosticForNode(useStrictDirective_1, ts.Diagnostics.use_strict_directive_used_here)); + }); + var diagnostics_1 = nonSimpleParameters.map(function (parameter, index) { return (index === 0 ? ts.createDiagnosticForNode(parameter, ts.Diagnostics.Non_simple_parameter_declared_here) : ts.createDiagnosticForNode(parameter, ts.Diagnostics.and_here)); }); + addRelatedInfo.apply(void 0, [error(useStrictDirective_1, ts.Diagnostics.use_strict_directive_cannot_be_used_with_non_simple_parameter_list)].concat(diagnostics_1)); + return true; + } + } + } + return false; + } + function checkGrammarFunctionLikeDeclaration(node) { + // Prevent cascading error by short-circuit + var file = ts.getSourceFileOfNode(node); + return checkGrammarDecoratorsAndModifiers(node) || checkGrammarTypeParameterList(node.typeParameters, file) || + checkGrammarParameterList(node.parameters) || checkGrammarArrowFunction(node, file) || + (ts.isFunctionLikeDeclaration(node) && checkGrammarForUseStrictSimpleParameterList(node)); + } + function checkGrammarClassLikeDeclaration(node) { + var file = ts.getSourceFileOfNode(node); + return checkGrammarClassDeclarationHeritageClauses(node) || checkGrammarTypeParameterList(node.typeParameters, file); + } + function checkGrammarArrowFunction(node, file) { + if (!ts.isArrowFunction(node)) { + return false; + } + var equalsGreaterThanToken = node.equalsGreaterThanToken; + var startLine = ts.getLineAndCharacterOfPosition(file, equalsGreaterThanToken.pos).line; + var endLine = ts.getLineAndCharacterOfPosition(file, equalsGreaterThanToken.end).line; + return startLine !== endLine && grammarErrorOnNode(equalsGreaterThanToken, ts.Diagnostics.Line_terminator_not_permitted_before_arrow); + } + function checkGrammarIndexSignatureParameters(node) { + var parameter = node.parameters[0]; + if (node.parameters.length !== 1) { + if (parameter) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_must_have_exactly_one_parameter); + } + else { + return grammarErrorOnNode(node, ts.Diagnostics.An_index_signature_must_have_exactly_one_parameter); + } + } + if (parameter.dotDotDotToken) { + return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.An_index_signature_cannot_have_a_rest_parameter); + } + if (ts.hasModifiers(parameter)) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_cannot_have_an_accessibility_modifier); + } + if (parameter.questionToken) { + return grammarErrorOnNode(parameter.questionToken, ts.Diagnostics.An_index_signature_parameter_cannot_have_a_question_mark); + } + if (parameter.initializer) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_cannot_have_an_initializer); + } + if (!parameter.type) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_must_have_a_type_annotation); + } + if (parameter.type.kind !== 138 /* StringKeyword */ && parameter.type.kind !== 135 /* NumberKeyword */) { + var type = getTypeFromTypeNode(parameter.type); + if (type.flags & 4 /* String */ || type.flags & 8 /* Number */) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead, ts.getTextOfNode(parameter.name), typeToString(type), typeToString(getTypeFromTypeNode(node.type))); + } + if (type.flags & 1048576 /* Union */ && allTypesAssignableToKind(type, 128 /* StringLiteral */, /*strict*/ true)) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead); + } + return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_must_be_string_or_number); + } + if (!node.type) { + return grammarErrorOnNode(node, ts.Diagnostics.An_index_signature_must_have_a_type_annotation); + } + return false; + } + function checkGrammarIndexSignature(node) { + // Prevent cascading error by short-circuit + return checkGrammarDecoratorsAndModifiers(node) || checkGrammarIndexSignatureParameters(node); + } + function checkGrammarForAtLeastOneTypeArgument(node, typeArguments) { + if (typeArguments && typeArguments.length === 0) { + var sourceFile = ts.getSourceFileOfNode(node); + var start = typeArguments.pos - "<".length; + var end = ts.skipTrivia(sourceFile.text, typeArguments.end) + ">".length; + return grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.Type_argument_list_cannot_be_empty); + } + return false; + } + function checkGrammarTypeArguments(node, typeArguments) { + return checkGrammarForDisallowedTrailingComma(typeArguments) || + checkGrammarForAtLeastOneTypeArgument(node, typeArguments); + } + function checkGrammarForOmittedArgument(args) { + if (args) { + for (var _i = 0, args_5 = args; _i < args_5.length; _i++) { + var arg = args_5[_i]; + if (arg.kind === 210 /* OmittedExpression */) { + return grammarErrorAtPos(arg, arg.pos, 0, ts.Diagnostics.Argument_expression_expected); + } + } + } + return false; + } + function checkGrammarArguments(args) { + return checkGrammarForOmittedArgument(args); + } + function checkGrammarHeritageClause(node) { + var types = node.types; + if (checkGrammarForDisallowedTrailingComma(types)) { + return true; + } + if (types && types.length === 0) { + var listType = ts.tokenToString(node.token); + return grammarErrorAtPos(node, types.pos, 0, ts.Diagnostics._0_list_cannot_be_empty, listType); + } + return ts.some(types, checkGrammarExpressionWithTypeArguments); + } + function checkGrammarExpressionWithTypeArguments(node) { + return checkGrammarTypeArguments(node, node.typeArguments); + } + function checkGrammarClassDeclarationHeritageClauses(node) { + var seenExtendsClause = false; + var seenImplementsClause = false; + if (!checkGrammarDecoratorsAndModifiers(node) && node.heritageClauses) { + for (var _i = 0, _a = node.heritageClauses; _i < _a.length; _i++) { + var heritageClause = _a[_i]; + if (heritageClause.token === 86 /* ExtendsKeyword */) { + if (seenExtendsClause) { + return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.extends_clause_already_seen); + } + if (seenImplementsClause) { + return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.extends_clause_must_precede_implements_clause); + } + if (heritageClause.types.length > 1) { + return grammarErrorOnFirstToken(heritageClause.types[1], ts.Diagnostics.Classes_can_only_extend_a_single_class); + } + seenExtendsClause = true; + } + else { + ts.Debug.assert(heritageClause.token === 109 /* ImplementsKeyword */); + if (seenImplementsClause) { + return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.implements_clause_already_seen); + } + seenImplementsClause = true; + } + // Grammar checking heritageClause inside class declaration + checkGrammarHeritageClause(heritageClause); + } + } + } + function checkGrammarInterfaceDeclaration(node) { + var seenExtendsClause = false; + if (node.heritageClauses) { + for (var _i = 0, _a = node.heritageClauses; _i < _a.length; _i++) { + var heritageClause = _a[_i]; + if (heritageClause.token === 86 /* ExtendsKeyword */) { + if (seenExtendsClause) { + return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.extends_clause_already_seen); + } + seenExtendsClause = true; + } + else { + ts.Debug.assert(heritageClause.token === 109 /* ImplementsKeyword */); + return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.Interface_declaration_cannot_have_implements_clause); + } + // Grammar checking heritageClause inside class declaration + checkGrammarHeritageClause(heritageClause); + } + } + return false; + } + function checkGrammarComputedPropertyName(node) { + // If node is not a computedPropertyName, just skip the grammar checking + if (node.kind !== 149 /* ComputedPropertyName */) { + return false; + } + var computedPropertyName = node; + if (computedPropertyName.expression.kind === 204 /* BinaryExpression */ && computedPropertyName.expression.operatorToken.kind === 27 /* CommaToken */) { + return grammarErrorOnNode(computedPropertyName.expression, ts.Diagnostics.A_comma_expression_is_not_allowed_in_a_computed_property_name); + } + return false; + } + function checkGrammarForGenerator(node) { + if (node.asteriskToken) { + ts.Debug.assert(node.kind === 239 /* FunctionDeclaration */ || + node.kind === 196 /* FunctionExpression */ || + node.kind === 156 /* MethodDeclaration */); + if (node.flags & 4194304 /* Ambient */) { + return grammarErrorOnNode(node.asteriskToken, ts.Diagnostics.Generators_are_not_allowed_in_an_ambient_context); + } + if (!node.body) { + return grammarErrorOnNode(node.asteriskToken, ts.Diagnostics.An_overload_signature_cannot_be_declared_as_a_generator); + } + } + } + function checkGrammarForInvalidQuestionMark(questionToken, message) { + return !!questionToken && grammarErrorOnNode(questionToken, message); + } + function checkGrammarForInvalidExclamationToken(exclamationToken, message) { + return !!exclamationToken && grammarErrorOnNode(exclamationToken, message); + } + function checkGrammarObjectLiteralExpression(node, inDestructuring) { + var Flags; + (function (Flags) { + Flags[Flags["Property"] = 1] = "Property"; + Flags[Flags["GetAccessor"] = 2] = "GetAccessor"; + Flags[Flags["SetAccessor"] = 4] = "SetAccessor"; + Flags[Flags["GetOrSetAccessor"] = 6] = "GetOrSetAccessor"; + })(Flags || (Flags = {})); + var seen = ts.createUnderscoreEscapedMap(); + for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { + var prop = _a[_i]; + if (prop.kind === 277 /* SpreadAssignment */) { + continue; + } + var name = prop.name; + if (name.kind === 149 /* ComputedPropertyName */) { + // If the name is not a ComputedPropertyName, the grammar checking will skip it + checkGrammarComputedPropertyName(name); + } + if (prop.kind === 276 /* ShorthandPropertyAssignment */ && !inDestructuring && prop.objectAssignmentInitializer) { + // having objectAssignmentInitializer is only valid in ObjectAssignmentPattern + // outside of destructuring it is a syntax error + return grammarErrorOnNode(prop.equalsToken, ts.Diagnostics.can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment); + } + // Modifiers are never allowed on properties except for 'async' on a method declaration + if (prop.modifiers) { + for (var _b = 0, _c = prop.modifiers; _b < _c.length; _b++) { // TODO: GH#19955 + var mod = _c[_b]; + if (mod.kind !== 121 /* AsyncKeyword */ || prop.kind !== 156 /* MethodDeclaration */) { + grammarErrorOnNode(mod, ts.Diagnostics._0_modifier_cannot_be_used_here, ts.getTextOfNode(mod)); + } + } + } + // ECMA-262 11.1.5 Object Initializer + // If previous is not undefined then throw a SyntaxError exception if any of the following conditions are true + // a.This production is contained in strict code and IsDataDescriptor(previous) is true and + // IsDataDescriptor(propId.descriptor) is true. + // b.IsDataDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true. + // c.IsAccessorDescriptor(previous) is true and IsDataDescriptor(propId.descriptor) is true. + // d.IsAccessorDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true + // and either both previous and propId.descriptor have[[Get]] fields or both previous and propId.descriptor have[[Set]] fields + var currentKind = void 0; + switch (prop.kind) { + case 276 /* ShorthandPropertyAssignment */: + checkGrammarForInvalidExclamationToken(prop.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context); + /* tslint:disable:no-switch-case-fall-through */ + case 275 /* PropertyAssignment */: + // Grammar checking for computedPropertyName and shorthandPropertyAssignment + checkGrammarForInvalidQuestionMark(prop.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional); + if (name.kind === 8 /* NumericLiteral */) { + checkGrammarNumericLiteral(name); + } + // falls through + case 156 /* MethodDeclaration */: + currentKind = 1 /* Property */; + break; + case 158 /* GetAccessor */: + currentKind = 2 /* GetAccessor */; + break; + case 159 /* SetAccessor */: + currentKind = 4 /* SetAccessor */; + break; + default: + throw ts.Debug.assertNever(prop, "Unexpected syntax kind:" + prop.kind); + } + var effectiveName = ts.getPropertyNameForPropertyNameNode(name); + if (effectiveName === undefined) { + continue; + } + var existingKind = seen.get(effectiveName); + if (!existingKind) { + seen.set(effectiveName, currentKind); + } + else { + if (currentKind === 1 /* Property */ && existingKind === 1 /* Property */) { + grammarErrorOnNode(name, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(name)); + } + else if ((currentKind & 6 /* GetOrSetAccessor */) && (existingKind & 6 /* GetOrSetAccessor */)) { + if (existingKind !== 6 /* GetOrSetAccessor */ && currentKind !== existingKind) { + seen.set(effectiveName, currentKind | existingKind); + } + else { + return grammarErrorOnNode(name, ts.Diagnostics.An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name); + } + } + else { + return grammarErrorOnNode(name, ts.Diagnostics.An_object_literal_cannot_have_property_and_accessor_with_the_same_name); + } + } + } + } + function checkGrammarJsxElement(node) { + checkGrammarTypeArguments(node, node.typeArguments); + var seen = ts.createUnderscoreEscapedMap(); + for (var _i = 0, _a = node.attributes.properties; _i < _a.length; _i++) { + var attr = _a[_i]; + if (attr.kind === 269 /* JsxSpreadAttribute */) { + continue; + } + var name = attr.name, initializer = attr.initializer; + if (!seen.get(name.escapedText)) { + seen.set(name.escapedText, true); + } + else { + return grammarErrorOnNode(name, ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name); + } + if (initializer && initializer.kind === 270 /* JsxExpression */ && !initializer.expression) { + return grammarErrorOnNode(initializer, ts.Diagnostics.JSX_attributes_must_only_be_assigned_a_non_empty_expression); + } + } + } + function checkGrammarForInOrForOfStatement(forInOrOfStatement) { + if (checkGrammarStatementInAmbientContext(forInOrOfStatement)) { + return true; + } + if (forInOrOfStatement.kind === 227 /* ForOfStatement */ && forInOrOfStatement.awaitModifier) { + if ((forInOrOfStatement.flags & 16384 /* AwaitContext */) === 0 /* None */) { + return grammarErrorOnNode(forInOrOfStatement.awaitModifier, ts.Diagnostics.A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator); + } + } + if (forInOrOfStatement.initializer.kind === 238 /* VariableDeclarationList */) { + var variableList = forInOrOfStatement.initializer; + if (!checkGrammarVariableDeclarationList(variableList)) { + var declarations = variableList.declarations; + // declarations.length can be zero if there is an error in variable declaration in for-of or for-in + // See http://www.ecma-international.org/ecma-262/6.0/#sec-for-in-and-for-of-statements for details + // For example: + // var let = 10; + // for (let of [1,2,3]) {} // this is invalid ES6 syntax + // for (let in [1,2,3]) {} // this is invalid ES6 syntax + // We will then want to skip on grammar checking on variableList declaration + if (!declarations.length) { + return false; + } + if (declarations.length > 1) { + var diagnostic = forInOrOfStatement.kind === 226 /* ForInStatement */ + ? ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement + : ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement; + return grammarErrorOnFirstToken(variableList.declarations[1], diagnostic); + } + var firstDeclaration = declarations[0]; + if (firstDeclaration.initializer) { + var diagnostic = forInOrOfStatement.kind === 226 /* ForInStatement */ + ? ts.Diagnostics.The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer + : ts.Diagnostics.The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer; + return grammarErrorOnNode(firstDeclaration.name, diagnostic); + } + if (firstDeclaration.type) { + var diagnostic = forInOrOfStatement.kind === 226 /* ForInStatement */ + ? ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation + : ts.Diagnostics.The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation; + return grammarErrorOnNode(firstDeclaration, diagnostic); + } + } + } + return false; + } + function checkGrammarAccessor(accessor) { + var kind = accessor.kind; + if (languageVersion < 1 /* ES5 */) { + return grammarErrorOnNode(accessor.name, ts.Diagnostics.Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher); + } + else if (accessor.flags & 4194304 /* Ambient */) { + return grammarErrorOnNode(accessor.name, ts.Diagnostics.An_accessor_cannot_be_declared_in_an_ambient_context); + } + else if (accessor.body === undefined && !ts.hasModifier(accessor, 128 /* Abstract */)) { + return grammarErrorAtPos(accessor, accessor.end - 1, ";".length, ts.Diagnostics._0_expected, "{"); + } + else if (accessor.body && ts.hasModifier(accessor, 128 /* Abstract */)) { + return grammarErrorOnNode(accessor, ts.Diagnostics.An_abstract_accessor_cannot_have_an_implementation); + } + else if (accessor.typeParameters) { + return grammarErrorOnNode(accessor.name, ts.Diagnostics.An_accessor_cannot_have_type_parameters); + } + else if (!doesAccessorHaveCorrectParameterCount(accessor)) { + return grammarErrorOnNode(accessor.name, kind === 158 /* GetAccessor */ ? + ts.Diagnostics.A_get_accessor_cannot_have_parameters : + ts.Diagnostics.A_set_accessor_must_have_exactly_one_parameter); + } + else if (kind === 159 /* SetAccessor */) { + if (accessor.type) { + return grammarErrorOnNode(accessor.name, ts.Diagnostics.A_set_accessor_cannot_have_a_return_type_annotation); + } + else { + var parameter = accessor.parameters[0]; + if (parameter.dotDotDotToken) { + return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.A_set_accessor_cannot_have_rest_parameter); + } + else if (parameter.questionToken) { + return grammarErrorOnNode(parameter.questionToken, ts.Diagnostics.A_set_accessor_cannot_have_an_optional_parameter); + } + else if (parameter.initializer) { + return grammarErrorOnNode(accessor.name, ts.Diagnostics.A_set_accessor_parameter_cannot_have_an_initializer); + } + } + } + return false; + } + /** Does the accessor have the right number of parameters? + * A get accessor has no parameters or a single `this` parameter. + * A set accessor has one parameter or a `this` parameter and one more parameter. + */ + function doesAccessorHaveCorrectParameterCount(accessor) { + return getAccessorThisParameter(accessor) || accessor.parameters.length === (accessor.kind === 158 /* GetAccessor */ ? 0 : 1); + } + function getAccessorThisParameter(accessor) { + if (accessor.parameters.length === (accessor.kind === 158 /* GetAccessor */ ? 1 : 2)) { + return ts.getThisParameter(accessor); + } + } + function checkGrammarTypeOperatorNode(node) { + if (node.operator === 142 /* UniqueKeyword */) { + if (node.type.kind !== 139 /* SymbolKeyword */) { + return grammarErrorOnNode(node.type, ts.Diagnostics._0_expected, ts.tokenToString(139 /* SymbolKeyword */)); + } + var parent = ts.walkUpParenthesizedTypes(node.parent); + switch (parent.kind) { + case 237 /* VariableDeclaration */: + var decl = parent; + if (decl.name.kind !== 72 /* Identifier */) { + return grammarErrorOnNode(node, ts.Diagnostics.unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name); + } + if (!ts.isVariableDeclarationInVariableStatement(decl)) { + return grammarErrorOnNode(node, ts.Diagnostics.unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement); + } + if (!(decl.parent.flags & 2 /* Const */)) { + return grammarErrorOnNode(parent.name, ts.Diagnostics.A_variable_whose_type_is_a_unique_symbol_type_must_be_const); + } + break; + case 154 /* PropertyDeclaration */: + if (!ts.hasModifier(parent, 32 /* Static */) || + !ts.hasModifier(parent, 64 /* Readonly */)) { + return grammarErrorOnNode(parent.name, ts.Diagnostics.A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly); + } + break; + case 153 /* PropertySignature */: + if (!ts.hasModifier(parent, 64 /* Readonly */)) { + return grammarErrorOnNode(parent.name, ts.Diagnostics.A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly); + } + break; + default: + return grammarErrorOnNode(node, ts.Diagnostics.unique_symbol_types_are_not_allowed_here); + } + } + } + function checkGrammarForInvalidDynamicName(node, message) { + if (isNonBindableDynamicName(node)) { + return grammarErrorOnNode(node, message); + } + } + function checkGrammarMethod(node) { + if (checkGrammarFunctionLikeDeclaration(node)) { + return true; + } + if (node.kind === 156 /* MethodDeclaration */) { + if (node.parent.kind === 188 /* ObjectLiteralExpression */) { + // We only disallow modifier on a method declaration if it is a property of object-literal-expression + if (node.modifiers && !(node.modifiers.length === 1 && ts.first(node.modifiers).kind === 121 /* AsyncKeyword */)) { + return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); + } + else if (checkGrammarForInvalidQuestionMark(node.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional)) { + return true; + } + else if (checkGrammarForInvalidExclamationToken(node.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context)) { + return true; + } + else if (node.body === undefined) { + return grammarErrorAtPos(node, node.end - 1, ";".length, ts.Diagnostics._0_expected, "{"); + } + } + if (checkGrammarForGenerator(node)) { + return true; + } + } + if (ts.isClassLike(node.parent)) { + // Technically, computed properties in ambient contexts is disallowed + // for property declarations and accessors too, not just methods. + // However, property declarations disallow computed names in general, + // and accessors are not allowed in ambient contexts in general, + // so this error only really matters for methods. + if (node.flags & 4194304 /* Ambient */) { + return checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type); + } + else if (node.kind === 156 /* MethodDeclaration */ && !node.body) { + return checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type); + } + } + else if (node.parent.kind === 241 /* InterfaceDeclaration */) { + return checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type); + } + else if (node.parent.kind === 168 /* TypeLiteral */) { + return checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type); + } + } + function checkGrammarBreakOrContinueStatement(node) { + var current = node; + while (current) { + if (ts.isFunctionLike(current)) { + return grammarErrorOnNode(node, ts.Diagnostics.Jump_target_cannot_cross_function_boundary); + } + switch (current.kind) { + case 233 /* LabeledStatement */: + if (node.label && current.label.escapedText === node.label.escapedText) { + // found matching label - verify that label usage is correct + // continue can only target labels that are on iteration statements + var isMisplacedContinueLabel = node.kind === 228 /* ContinueStatement */ + && !ts.isIterationStatement(current.statement, /*lookInLabeledStatement*/ true); + if (isMisplacedContinueLabel) { + return grammarErrorOnNode(node, ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement); + } + return false; + } + break; + case 232 /* SwitchStatement */: + if (node.kind === 229 /* BreakStatement */ && !node.label) { + // unlabeled break within switch statement - ok + return false; + } + break; + default: + if (ts.isIterationStatement(current, /*lookInLabeledStatement*/ false) && !node.label) { + // unlabeled break or continue within iteration statement - ok + return false; + } + break; + } + current = current.parent; + } + if (node.label) { + var message = node.kind === 229 /* BreakStatement */ + ? ts.Diagnostics.A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement + : ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement; + return grammarErrorOnNode(node, message); + } + else { + var message = node.kind === 229 /* BreakStatement */ + ? ts.Diagnostics.A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement + : ts.Diagnostics.A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement; + return grammarErrorOnNode(node, message); + } + } + function checkGrammarBindingElement(node) { + if (node.dotDotDotToken) { + var elements = node.parent.elements; + if (node !== ts.last(elements)) { + return grammarErrorOnNode(node, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern); + } + checkGrammarForDisallowedTrailingComma(elements, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma); + if (node.propertyName) { + return grammarErrorOnNode(node.name, ts.Diagnostics.A_rest_element_cannot_have_a_property_name); + } + if (node.initializer) { + // Error on equals token which immediately precedes the initializer + return grammarErrorAtPos(node, node.initializer.pos - 1, 1, ts.Diagnostics.A_rest_element_cannot_have_an_initializer); + } + } + } + function isStringOrNumberLiteralExpression(expr) { + return expr.kind === 10 /* StringLiteral */ || expr.kind === 8 /* NumericLiteral */ || + expr.kind === 202 /* PrefixUnaryExpression */ && expr.operator === 39 /* MinusToken */ && + expr.operand.kind === 8 /* NumericLiteral */; + } + function isBigIntLiteralExpression(expr) { + return expr.kind === 9 /* BigIntLiteral */ || + expr.kind === 202 /* PrefixUnaryExpression */ && expr.operator === 39 /* MinusToken */ && + expr.operand.kind === 9 /* BigIntLiteral */; + } + function isSimpleLiteralEnumReference(expr) { + if ((ts.isPropertyAccessExpression(expr) || (ts.isElementAccessExpression(expr) && isStringOrNumberLiteralExpression(expr.argumentExpression))) && + ts.isEntityNameExpression(expr.expression)) + return !!(checkExpressionCached(expr).flags & 1024 /* EnumLiteral */); + } + function checkAmbientInitializer(node) { + var initializer = node.initializer; + if (initializer) { + var isInvalidInitializer = !(isStringOrNumberLiteralExpression(initializer) || + isSimpleLiteralEnumReference(initializer) || + initializer.kind === 102 /* TrueKeyword */ || initializer.kind === 87 /* FalseKeyword */ || + isBigIntLiteralExpression(initializer)); + var isConstOrReadonly = ts.isDeclarationReadonly(node) || ts.isVariableDeclaration(node) && ts.isVarConst(node); + if (isConstOrReadonly && !node.type) { + if (isInvalidInitializer) { + return grammarErrorOnNode(initializer, ts.Diagnostics.A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_reference); + } + } + else { + return grammarErrorOnNode(initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); + } + if (!isConstOrReadonly || isInvalidInitializer) { + return grammarErrorOnNode(initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); + } + } + } + function checkGrammarVariableDeclaration(node) { + if (node.parent.parent.kind !== 226 /* ForInStatement */ && node.parent.parent.kind !== 227 /* ForOfStatement */) { + if (node.flags & 4194304 /* Ambient */) { + checkAmbientInitializer(node); + } + else if (!node.initializer) { + if (ts.isBindingPattern(node.name) && !ts.isBindingPattern(node.parent)) { + return grammarErrorOnNode(node, ts.Diagnostics.A_destructuring_declaration_must_have_an_initializer); + } + if (ts.isVarConst(node)) { + return grammarErrorOnNode(node, ts.Diagnostics.const_declarations_must_be_initialized); + } + } + } + if (node.exclamationToken && (node.parent.parent.kind !== 219 /* VariableStatement */ || !node.type || node.initializer || node.flags & 4194304 /* Ambient */)) { + return grammarErrorOnNode(node.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context); + } + if (compilerOptions.module !== ts.ModuleKind.ES2015 && compilerOptions.module !== ts.ModuleKind.ESNext && compilerOptions.module !== ts.ModuleKind.System && !compilerOptions.noEmit && + !(node.parent.parent.flags & 4194304 /* Ambient */) && ts.hasModifier(node.parent.parent, 1 /* Export */)) { + checkESModuleMarker(node.name); + } + var checkLetConstNames = (ts.isLet(node) || ts.isVarConst(node)); + // 1. LexicalDeclaration : LetOrConst BindingList ; + // It is a Syntax Error if the BoundNames of BindingList contains "let". + // 2. ForDeclaration: ForDeclaration : LetOrConst ForBinding + // It is a Syntax Error if the BoundNames of ForDeclaration contains "let". + // It is a SyntaxError if a VariableDeclaration or VariableDeclarationNoIn occurs within strict code + // and its Identifier is eval or arguments + return checkLetConstNames && checkGrammarNameInLetOrConstDeclarations(node.name); + } + function checkESModuleMarker(name) { + if (name.kind === 72 /* Identifier */) { + if (ts.idText(name) === "__esModule") { + return grammarErrorOnNode(name, ts.Diagnostics.Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules); + } + } + else { + var elements = name.elements; + for (var _i = 0, elements_1 = elements; _i < elements_1.length; _i++) { + var element = elements_1[_i]; + if (!ts.isOmittedExpression(element)) { + return checkESModuleMarker(element.name); + } + } + } + return false; + } + function checkGrammarNameInLetOrConstDeclarations(name) { + if (name.kind === 72 /* Identifier */) { + if (name.originalKeywordKind === 111 /* LetKeyword */) { + return grammarErrorOnNode(name, ts.Diagnostics.let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations); + } + } + else { + var elements = name.elements; + for (var _i = 0, elements_2 = elements; _i < elements_2.length; _i++) { + var element = elements_2[_i]; + if (!ts.isOmittedExpression(element)) { + checkGrammarNameInLetOrConstDeclarations(element.name); + } + } + } + return false; + } + function checkGrammarVariableDeclarationList(declarationList) { + var declarations = declarationList.declarations; + if (checkGrammarForDisallowedTrailingComma(declarationList.declarations)) { + return true; + } + if (!declarationList.declarations.length) { + return grammarErrorAtPos(declarationList, declarations.pos, declarations.end - declarations.pos, ts.Diagnostics.Variable_declaration_list_cannot_be_empty); + } + return false; + } + function allowLetAndConstDeclarations(parent) { + switch (parent.kind) { + case 222 /* IfStatement */: + case 223 /* DoStatement */: + case 224 /* WhileStatement */: + case 231 /* WithStatement */: + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + return false; + case 233 /* LabeledStatement */: + return allowLetAndConstDeclarations(parent.parent); + } + return true; + } + function checkGrammarForDisallowedLetOrConstStatement(node) { + if (!allowLetAndConstDeclarations(node.parent)) { + if (ts.isLet(node.declarationList)) { + return grammarErrorOnNode(node, ts.Diagnostics.let_declarations_can_only_be_declared_inside_a_block); + } + else if (ts.isVarConst(node.declarationList)) { + return grammarErrorOnNode(node, ts.Diagnostics.const_declarations_can_only_be_declared_inside_a_block); + } + } + } + function checkGrammarMetaProperty(node) { + var escapedText = node.name.escapedText; + switch (node.keywordToken) { + case 95 /* NewKeyword */: + if (escapedText !== "target") { + return grammarErrorOnNode(node.name, ts.Diagnostics._0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2, node.name.escapedText, ts.tokenToString(node.keywordToken), "target"); + } + break; + case 92 /* ImportKeyword */: + if (escapedText !== "meta") { + return grammarErrorOnNode(node.name, ts.Diagnostics._0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2, node.name.escapedText, ts.tokenToString(node.keywordToken), "meta"); + } + break; + } + } + function hasParseDiagnostics(sourceFile) { + return sourceFile.parseDiagnostics.length > 0; + } + function grammarErrorOnFirstToken(node, message, arg0, arg1, arg2) { + var sourceFile = ts.getSourceFileOfNode(node); + if (!hasParseDiagnostics(sourceFile)) { + var span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos); + diagnostics.add(ts.createFileDiagnostic(sourceFile, span.start, span.length, message, arg0, arg1, arg2)); + return true; + } + return false; + } + function grammarErrorAtPos(nodeForSourceFile, start, length, message, arg0, arg1, arg2) { + var sourceFile = ts.getSourceFileOfNode(nodeForSourceFile); + if (!hasParseDiagnostics(sourceFile)) { + diagnostics.add(ts.createFileDiagnostic(sourceFile, start, length, message, arg0, arg1, arg2)); + return true; + } + return false; + } + function grammarErrorOnNode(node, message, arg0, arg1, arg2) { + var sourceFile = ts.getSourceFileOfNode(node); + if (!hasParseDiagnostics(sourceFile)) { + diagnostics.add(ts.createDiagnosticForNode(node, message, arg0, arg1, arg2)); + return true; + } + return false; + } + function checkGrammarConstructorTypeParameters(node) { + var jsdocTypeParameters = ts.isInJSFile(node) ? ts.getJSDocTypeParameterDeclarations(node) : undefined; + var range = node.typeParameters || jsdocTypeParameters && ts.firstOrUndefined(jsdocTypeParameters); + if (range) { + var pos = range.pos === range.end ? range.pos : ts.skipTrivia(ts.getSourceFileOfNode(node).text, range.pos); + return grammarErrorAtPos(node, pos, range.end - pos, ts.Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration); + } + } + function checkGrammarConstructorTypeAnnotation(node) { + var type = ts.getEffectiveReturnTypeNode(node); + if (type) { + return grammarErrorOnNode(type, ts.Diagnostics.Type_annotation_cannot_appear_on_a_constructor_declaration); + } + } + function checkGrammarProperty(node) { + if (ts.isClassLike(node.parent)) { + if (checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_class_property_declaration_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type)) { + return true; + } + } + else if (node.parent.kind === 241 /* InterfaceDeclaration */) { + if (checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type)) { + return true; + } + if (node.initializer) { + return grammarErrorOnNode(node.initializer, ts.Diagnostics.An_interface_property_cannot_have_an_initializer); + } + } + else if (node.parent.kind === 168 /* TypeLiteral */) { + if (checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type)) { + return true; + } + if (node.initializer) { + return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_type_literal_property_cannot_have_an_initializer); + } + } + if (node.flags & 4194304 /* Ambient */) { + checkAmbientInitializer(node); + } + if (ts.isPropertyDeclaration(node) && node.exclamationToken && (!ts.isClassLike(node.parent) || !node.type || node.initializer || + node.flags & 4194304 /* Ambient */ || ts.hasModifier(node, 32 /* Static */ | 128 /* Abstract */))) { + return grammarErrorOnNode(node.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context); + } + } + function checkGrammarTopLevelElementForRequiredDeclareModifier(node) { + // A declare modifier is required for any top level .d.ts declaration except export=, export default, export as namespace + // interfaces and imports categories: + // + // DeclarationElement: + // ExportAssignment + // export_opt InterfaceDeclaration + // export_opt TypeAliasDeclaration + // export_opt ImportDeclaration + // export_opt ExternalImportDeclaration + // export_opt AmbientDeclaration + // + // TODO: The spec needs to be amended to reflect this grammar. + if (node.kind === 241 /* InterfaceDeclaration */ || + node.kind === 242 /* TypeAliasDeclaration */ || + node.kind === 249 /* ImportDeclaration */ || + node.kind === 248 /* ImportEqualsDeclaration */ || + node.kind === 255 /* ExportDeclaration */ || + node.kind === 254 /* ExportAssignment */ || + node.kind === 247 /* NamespaceExportDeclaration */ || + ts.hasModifier(node, 2 /* Ambient */ | 1 /* Export */ | 512 /* Default */)) { + return false; + } + return grammarErrorOnFirstToken(node, ts.Diagnostics.A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file); + } + function checkGrammarTopLevelElementsForRequiredDeclareModifier(file) { + for (var _i = 0, _a = file.statements; _i < _a.length; _i++) { + var decl = _a[_i]; + if (ts.isDeclaration(decl) || decl.kind === 219 /* VariableStatement */) { + if (checkGrammarTopLevelElementForRequiredDeclareModifier(decl)) { + return true; + } + } + } + return false; + } + function checkGrammarSourceFile(node) { + return !!(node.flags & 4194304 /* Ambient */) && checkGrammarTopLevelElementsForRequiredDeclareModifier(node); + } + function checkGrammarStatementInAmbientContext(node) { + if (node.flags & 4194304 /* Ambient */) { + // An accessors is already reported about the ambient context + if (ts.isAccessor(node.parent)) { + return getNodeLinks(node).hasReportedStatementInAmbientContext = true; + } + // Find containing block which is either Block, ModuleBlock, SourceFile + var links = getNodeLinks(node); + if (!links.hasReportedStatementInAmbientContext && ts.isFunctionLike(node.parent)) { + return getNodeLinks(node).hasReportedStatementInAmbientContext = grammarErrorOnFirstToken(node, ts.Diagnostics.An_implementation_cannot_be_declared_in_ambient_contexts); + } + // We are either parented by another statement, or some sort of block. + // If we're in a block, we only want to really report an error once + // to prevent noisiness. So use a bit on the block to indicate if + // this has already been reported, and don't report if it has. + // + if (node.parent.kind === 218 /* Block */ || node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 279 /* SourceFile */) { + var links_2 = getNodeLinks(node.parent); + // Check if the containing block ever report this error + if (!links_2.hasReportedStatementInAmbientContext) { + return links_2.hasReportedStatementInAmbientContext = grammarErrorOnFirstToken(node, ts.Diagnostics.Statements_are_not_allowed_in_ambient_contexts); + } + } + else { + // We must be parented by a statement. If so, there's no need + // to report the error as our parent will have already done it. + // Debug.assert(isStatement(node.parent)); + } + } + return false; + } + function checkGrammarNumericLiteral(node) { + // Grammar checking + if (node.numericLiteralFlags & 32 /* Octal */) { + var diagnosticMessage = void 0; + if (languageVersion >= 1 /* ES5 */) { + diagnosticMessage = ts.Diagnostics.Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0; + } + else if (ts.isChildOfNodeWithKind(node, 182 /* LiteralType */)) { + diagnosticMessage = ts.Diagnostics.Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0; + } + else if (ts.isChildOfNodeWithKind(node, 278 /* EnumMember */)) { + diagnosticMessage = ts.Diagnostics.Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0; + } + if (diagnosticMessage) { + var withMinus = ts.isPrefixUnaryExpression(node.parent) && node.parent.operator === 39 /* MinusToken */; + var literal = (withMinus ? "-" : "") + "0o" + node.text; + return grammarErrorOnNode(withMinus ? node.parent : node, diagnosticMessage, literal); + } + } + return false; + } + function checkGrammarBigIntLiteral(node) { + var literalType = ts.isLiteralTypeNode(node.parent) || + ts.isPrefixUnaryExpression(node.parent) && ts.isLiteralTypeNode(node.parent.parent); + if (!literalType) { + if (languageVersion < 6 /* ESNext */) { + if (grammarErrorOnNode(node, ts.Diagnostics.BigInt_literals_are_not_available_when_targeting_lower_than_ESNext)) { + return true; + } + } + } + return false; + } + function grammarErrorAfterFirstToken(node, message, arg0, arg1, arg2) { + var sourceFile = ts.getSourceFileOfNode(node); + if (!hasParseDiagnostics(sourceFile)) { + var span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos); + diagnostics.add(ts.createFileDiagnostic(sourceFile, ts.textSpanEnd(span), /*length*/ 0, message, arg0, arg1, arg2)); + return true; + } + return false; + } + function getAmbientModules() { + if (!ambientModulesCache) { + ambientModulesCache = []; + globals.forEach(function (global, sym) { + // No need to `unescapeLeadingUnderscores`, an escaped symbol is never an ambient module. + if (ambientModuleSymbolRegex.test(sym)) { + ambientModulesCache.push(global); + } + }); + } + return ambientModulesCache; + } + function checkGrammarImportCallExpression(node) { + if (moduleKind === ts.ModuleKind.ES2015) { + return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext); + } + if (node.typeArguments) { + return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_import_cannot_have_type_arguments); + } + var nodeArguments = node.arguments; + if (nodeArguments.length !== 1) { + return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_import_must_have_one_specifier_as_an_argument); + } + // see: parseArgumentOrArrayLiteralElement...we use this function which parse arguments of callExpression to parse specifier for dynamic import. + // parseArgumentOrArrayLiteralElement allows spread element to be in an argument list which is not allowed as specifier in dynamic import. + if (ts.isSpreadElement(nodeArguments[0])) { + return grammarErrorOnNode(nodeArguments[0], ts.Diagnostics.Specifier_of_dynamic_import_cannot_be_spread_element); + } + return false; + } + } + ts.createTypeChecker = createTypeChecker; + /** Like 'isDeclarationName', but returns true for LHS of `import { x as y }` or `export { x as y }`. */ + function isDeclarationNameOrImportPropertyName(name) { + switch (name.parent.kind) { + case 253 /* ImportSpecifier */: + case 257 /* ExportSpecifier */: + return ts.isIdentifier(name); + default: + return ts.isDeclarationName(name); + } + } + function isSomeImportDeclaration(decl) { + switch (decl.kind) { + case 250 /* ImportClause */: // For default import + case 248 /* ImportEqualsDeclaration */: + case 251 /* NamespaceImport */: + case 253 /* ImportSpecifier */: // For rename import `x as y` + return true; + case 72 /* Identifier */: + // For regular import, `decl` is an Identifier under the ImportSpecifier. + return decl.parent.kind === 253 /* ImportSpecifier */; + default: + return false; + } + } + var JsxNames; + (function (JsxNames) { + // tslint:disable variable-name + JsxNames.JSX = "JSX"; + JsxNames.IntrinsicElements = "IntrinsicElements"; + JsxNames.ElementClass = "ElementClass"; + JsxNames.ElementAttributesPropertyNameContainer = "ElementAttributesProperty"; // TODO: Deprecate and remove support + JsxNames.ElementChildrenAttributeNameContainer = "ElementChildrenAttribute"; + JsxNames.Element = "Element"; + JsxNames.IntrinsicAttributes = "IntrinsicAttributes"; + JsxNames.IntrinsicClassAttributes = "IntrinsicClassAttributes"; + JsxNames.LibraryManagedAttributes = "LibraryManagedAttributes"; + // tslint:enable variable-name + })(JsxNames || (JsxNames = {})); + function typeIsLiteralType(type) { + return !!(type.flags & 2944 /* Literal */); + } +})(ts || (ts = {})); +var ts; +(function (ts) { + function createSynthesizedNode(kind) { + var node = ts.createNode(kind, -1, -1); + node.flags |= 8 /* Synthesized */; + return node; + } + /* @internal */ + function updateNode(updated, original) { + if (updated !== original) { + setOriginalNode(updated, original); + setTextRange(updated, original); + ts.aggregateTransformFlags(updated); + } + return updated; + } + ts.updateNode = updateNode; + /** + * Make `elements` into a `NodeArray`. If `elements` is `undefined`, returns an empty `NodeArray`. + */ + function createNodeArray(elements, hasTrailingComma) { + if (!elements || elements === ts.emptyArray) { + elements = []; + } + else if (ts.isNodeArray(elements)) { + return elements; + } + var array = elements; + array.pos = -1; + array.end = -1; + array.hasTrailingComma = hasTrailingComma; + return array; + } + ts.createNodeArray = createNodeArray; + /** + * Creates a shallow, memberwise clone of a node with no source map location. + */ + /* @internal */ + function getSynthesizedClone(node) { + // We don't use "clone" from core.ts here, as we need to preserve the prototype chain of + // the original node. We also need to exclude specific properties and only include own- + // properties (to skip members already defined on the shared prototype). + if (node === undefined) { + return node; + } + var clone = createSynthesizedNode(node.kind); + clone.flags |= node.flags; + setOriginalNode(clone, node); + for (var key in node) { + if (clone.hasOwnProperty(key) || !node.hasOwnProperty(key)) { + continue; + } + clone[key] = node[key]; + } + return clone; + } + ts.getSynthesizedClone = getSynthesizedClone; + function createLiteral(value, isSingleQuote) { + if (typeof value === "number") { + return createNumericLiteral(value + ""); + } + if (typeof value === "object" && "base10Value" in value) { // PseudoBigInt + return createBigIntLiteral(ts.pseudoBigIntToString(value) + "n"); + } + if (typeof value === "boolean") { + return value ? createTrue() : createFalse(); + } + if (ts.isString(value)) { + var res = createStringLiteral(value); + if (isSingleQuote) + res.singleQuote = true; + return res; + } + return createLiteralFromNode(value); + } + ts.createLiteral = createLiteral; + function createNumericLiteral(value) { + var node = createSynthesizedNode(8 /* NumericLiteral */); + node.text = value; + node.numericLiteralFlags = 0; + return node; + } + ts.createNumericLiteral = createNumericLiteral; + function createBigIntLiteral(value) { + var node = createSynthesizedNode(9 /* BigIntLiteral */); + node.text = value; + return node; + } + ts.createBigIntLiteral = createBigIntLiteral; + function createStringLiteral(text) { + var node = createSynthesizedNode(10 /* StringLiteral */); + node.text = text; + return node; + } + ts.createStringLiteral = createStringLiteral; + function createRegularExpressionLiteral(text) { + var node = createSynthesizedNode(13 /* RegularExpressionLiteral */); + node.text = text; + return node; + } + ts.createRegularExpressionLiteral = createRegularExpressionLiteral; + function createLiteralFromNode(sourceNode) { + var node = createStringLiteral(ts.getTextOfIdentifierOrLiteral(sourceNode)); + node.textSourceNode = sourceNode; + return node; + } + function createIdentifier(text, typeArguments) { + var node = createSynthesizedNode(72 /* Identifier */); + node.escapedText = ts.escapeLeadingUnderscores(text); + node.originalKeywordKind = text ? ts.stringToToken(text) : 0 /* Unknown */; + node.autoGenerateFlags = 0 /* None */; + node.autoGenerateId = 0; + if (typeArguments) { + node.typeArguments = createNodeArray(typeArguments); + } + return node; + } + ts.createIdentifier = createIdentifier; + function updateIdentifier(node, typeArguments) { + return node.typeArguments !== typeArguments + ? updateNode(createIdentifier(ts.idText(node), typeArguments), node) + : node; + } + ts.updateIdentifier = updateIdentifier; + var nextAutoGenerateId = 0; + function createTempVariable(recordTempVariable, reservedInNestedScopes) { + var name = createIdentifier(""); + name.autoGenerateFlags = 1 /* Auto */; + name.autoGenerateId = nextAutoGenerateId; + nextAutoGenerateId++; + if (recordTempVariable) { + recordTempVariable(name); + } + if (reservedInNestedScopes) { + name.autoGenerateFlags |= 8 /* ReservedInNestedScopes */; + } + return name; + } + ts.createTempVariable = createTempVariable; + /** Create a unique temporary variable for use in a loop. */ + function createLoopVariable() { + var name = createIdentifier(""); + name.autoGenerateFlags = 2 /* Loop */; + name.autoGenerateId = nextAutoGenerateId; + nextAutoGenerateId++; + return name; + } + ts.createLoopVariable = createLoopVariable; + /** Create a unique name based on the supplied text. */ + function createUniqueName(text) { + var name = createIdentifier(text); + name.autoGenerateFlags = 3 /* Unique */; + name.autoGenerateId = nextAutoGenerateId; + nextAutoGenerateId++; + return name; + } + ts.createUniqueName = createUniqueName; + function createOptimisticUniqueName(text) { + var name = createIdentifier(text); + name.autoGenerateFlags = 3 /* Unique */ | 16 /* Optimistic */; + name.autoGenerateId = nextAutoGenerateId; + nextAutoGenerateId++; + return name; + } + ts.createOptimisticUniqueName = createOptimisticUniqueName; + /** Create a unique name based on the supplied text. This does not consider names injected by the transformer. */ + function createFileLevelUniqueName(text) { + var name = createOptimisticUniqueName(text); + name.autoGenerateFlags |= 32 /* FileLevel */; + return name; + } + ts.createFileLevelUniqueName = createFileLevelUniqueName; + function getGeneratedNameForNode(node, flags) { + var name = createIdentifier(node && ts.isIdentifier(node) ? ts.idText(node) : ""); + name.autoGenerateFlags = 4 /* Node */ | flags; + name.autoGenerateId = nextAutoGenerateId; + name.original = node; + nextAutoGenerateId++; + return name; + } + ts.getGeneratedNameForNode = getGeneratedNameForNode; + // Punctuation + function createToken(token) { + return createSynthesizedNode(token); + } + ts.createToken = createToken; + // Reserved words + function createSuper() { + return createSynthesizedNode(98 /* SuperKeyword */); + } + ts.createSuper = createSuper; + function createThis() { + return createSynthesizedNode(100 /* ThisKeyword */); + } + ts.createThis = createThis; + function createNull() { + return createSynthesizedNode(96 /* NullKeyword */); + } + ts.createNull = createNull; + function createTrue() { + return createSynthesizedNode(102 /* TrueKeyword */); + } + ts.createTrue = createTrue; + function createFalse() { + return createSynthesizedNode(87 /* FalseKeyword */); + } + ts.createFalse = createFalse; + // Modifiers + function createModifier(kind) { + return createToken(kind); + } + ts.createModifier = createModifier; + function createModifiersFromModifierFlags(flags) { + var result = []; + if (flags & 1 /* Export */) { + result.push(createModifier(85 /* ExportKeyword */)); + } + if (flags & 2 /* Ambient */) { + result.push(createModifier(125 /* DeclareKeyword */)); + } + if (flags & 512 /* Default */) { + result.push(createModifier(80 /* DefaultKeyword */)); + } + if (flags & 2048 /* Const */) { + result.push(createModifier(77 /* ConstKeyword */)); + } + if (flags & 4 /* Public */) { + result.push(createModifier(115 /* PublicKeyword */)); + } + if (flags & 8 /* Private */) { + result.push(createModifier(113 /* PrivateKeyword */)); + } + if (flags & 16 /* Protected */) { + result.push(createModifier(114 /* ProtectedKeyword */)); + } + if (flags & 128 /* Abstract */) { + result.push(createModifier(118 /* AbstractKeyword */)); + } + if (flags & 32 /* Static */) { + result.push(createModifier(116 /* StaticKeyword */)); + } + if (flags & 64 /* Readonly */) { + result.push(createModifier(133 /* ReadonlyKeyword */)); + } + if (flags & 256 /* Async */) { + result.push(createModifier(121 /* AsyncKeyword */)); + } + return result; + } + ts.createModifiersFromModifierFlags = createModifiersFromModifierFlags; + // Names + function createQualifiedName(left, right) { + var node = createSynthesizedNode(148 /* QualifiedName */); + node.left = left; + node.right = asName(right); + return node; + } + ts.createQualifiedName = createQualifiedName; + function updateQualifiedName(node, left, right) { + return node.left !== left + || node.right !== right + ? updateNode(createQualifiedName(left, right), node) + : node; + } + ts.updateQualifiedName = updateQualifiedName; + function parenthesizeForComputedName(expression) { + return ts.isCommaSequence(expression) + ? createParen(expression) + : expression; + } + function createComputedPropertyName(expression) { + var node = createSynthesizedNode(149 /* ComputedPropertyName */); + node.expression = parenthesizeForComputedName(expression); + return node; + } + ts.createComputedPropertyName = createComputedPropertyName; + function updateComputedPropertyName(node, expression) { + return node.expression !== expression + ? updateNode(createComputedPropertyName(expression), node) + : node; + } + ts.updateComputedPropertyName = updateComputedPropertyName; + // Signature elements + function createTypeParameterDeclaration(name, constraint, defaultType) { + var node = createSynthesizedNode(150 /* TypeParameter */); + node.name = asName(name); + node.constraint = constraint; + node.default = defaultType; + return node; + } + ts.createTypeParameterDeclaration = createTypeParameterDeclaration; + function updateTypeParameterDeclaration(node, name, constraint, defaultType) { + return node.name !== name + || node.constraint !== constraint + || node.default !== defaultType + ? updateNode(createTypeParameterDeclaration(name, constraint, defaultType), node) + : node; + } + ts.updateTypeParameterDeclaration = updateTypeParameterDeclaration; + function createParameter(decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer) { + var node = createSynthesizedNode(151 /* Parameter */); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.dotDotDotToken = dotDotDotToken; + node.name = asName(name); + node.questionToken = questionToken; + node.type = type; + node.initializer = initializer ? ts.parenthesizeExpressionForList(initializer) : undefined; + return node; + } + ts.createParameter = createParameter; + function updateParameter(node, decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.dotDotDotToken !== dotDotDotToken + || node.name !== name + || node.questionToken !== questionToken + || node.type !== type + || node.initializer !== initializer + ? updateNode(createParameter(decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer), node) + : node; + } + ts.updateParameter = updateParameter; + function createDecorator(expression) { + var node = createSynthesizedNode(152 /* Decorator */); + node.expression = ts.parenthesizeForAccess(expression); + return node; + } + ts.createDecorator = createDecorator; + function updateDecorator(node, expression) { + return node.expression !== expression + ? updateNode(createDecorator(expression), node) + : node; + } + ts.updateDecorator = updateDecorator; + // Type Elements + function createPropertySignature(modifiers, name, questionToken, type, initializer) { + var node = createSynthesizedNode(153 /* PropertySignature */); + node.modifiers = asNodeArray(modifiers); + node.name = asName(name); + node.questionToken = questionToken; + node.type = type; + node.initializer = initializer; + return node; + } + ts.createPropertySignature = createPropertySignature; + function updatePropertySignature(node, modifiers, name, questionToken, type, initializer) { + return node.modifiers !== modifiers + || node.name !== name + || node.questionToken !== questionToken + || node.type !== type + || node.initializer !== initializer + ? updateNode(createPropertySignature(modifiers, name, questionToken, type, initializer), node) + : node; + } + ts.updatePropertySignature = updatePropertySignature; + function createProperty(decorators, modifiers, name, questionOrExclamationToken, type, initializer) { + var node = createSynthesizedNode(154 /* PropertyDeclaration */); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.name = asName(name); + node.questionToken = questionOrExclamationToken !== undefined && questionOrExclamationToken.kind === 56 /* QuestionToken */ ? questionOrExclamationToken : undefined; + node.exclamationToken = questionOrExclamationToken !== undefined && questionOrExclamationToken.kind === 52 /* ExclamationToken */ ? questionOrExclamationToken : undefined; + node.type = type; + node.initializer = initializer; + return node; + } + ts.createProperty = createProperty; + function updateProperty(node, decorators, modifiers, name, questionOrExclamationToken, type, initializer) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.name !== name + || node.questionToken !== (questionOrExclamationToken !== undefined && questionOrExclamationToken.kind === 56 /* QuestionToken */ ? questionOrExclamationToken : undefined) + || node.exclamationToken !== (questionOrExclamationToken !== undefined && questionOrExclamationToken.kind === 52 /* ExclamationToken */ ? questionOrExclamationToken : undefined) + || node.type !== type + || node.initializer !== initializer + ? updateNode(createProperty(decorators, modifiers, name, questionOrExclamationToken, type, initializer), node) + : node; + } + ts.updateProperty = updateProperty; + function createMethodSignature(typeParameters, parameters, type, name, questionToken) { + var node = createSignatureDeclaration(155 /* MethodSignature */, typeParameters, parameters, type); + node.name = asName(name); + node.questionToken = questionToken; + return node; + } + ts.createMethodSignature = createMethodSignature; + function updateMethodSignature(node, typeParameters, parameters, type, name, questionToken) { + return node.typeParameters !== typeParameters + || node.parameters !== parameters + || node.type !== type + || node.name !== name + || node.questionToken !== questionToken + ? updateNode(createMethodSignature(typeParameters, parameters, type, name, questionToken), node) + : node; + } + ts.updateMethodSignature = updateMethodSignature; + function createMethod(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { + var node = createSynthesizedNode(156 /* MethodDeclaration */); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.asteriskToken = asteriskToken; + node.name = asName(name); + node.questionToken = questionToken; + node.typeParameters = asNodeArray(typeParameters); + node.parameters = createNodeArray(parameters); + node.type = type; + node.body = body; + return node; + } + ts.createMethod = createMethod; + function updateMethod(node, decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.asteriskToken !== asteriskToken + || node.name !== name + || node.questionToken !== questionToken + || node.typeParameters !== typeParameters + || node.parameters !== parameters + || node.type !== type + || node.body !== body + ? updateNode(createMethod(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body), node) + : node; + } + ts.updateMethod = updateMethod; + function createConstructor(decorators, modifiers, parameters, body) { + var node = createSynthesizedNode(157 /* Constructor */); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.typeParameters = undefined; + node.parameters = createNodeArray(parameters); + node.type = undefined; + node.body = body; + return node; + } + ts.createConstructor = createConstructor; + function updateConstructor(node, decorators, modifiers, parameters, body) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.parameters !== parameters + || node.body !== body + ? updateNode(createConstructor(decorators, modifiers, parameters, body), node) + : node; + } + ts.updateConstructor = updateConstructor; + function createGetAccessor(decorators, modifiers, name, parameters, type, body) { + var node = createSynthesizedNode(158 /* GetAccessor */); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.name = asName(name); + node.typeParameters = undefined; + node.parameters = createNodeArray(parameters); + node.type = type; + node.body = body; + return node; + } + ts.createGetAccessor = createGetAccessor; + function updateGetAccessor(node, decorators, modifiers, name, parameters, type, body) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.name !== name + || node.parameters !== parameters + || node.type !== type + || node.body !== body + ? updateNode(createGetAccessor(decorators, modifiers, name, parameters, type, body), node) + : node; + } + ts.updateGetAccessor = updateGetAccessor; + function createSetAccessor(decorators, modifiers, name, parameters, body) { + var node = createSynthesizedNode(159 /* SetAccessor */); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.name = asName(name); + node.typeParameters = undefined; + node.parameters = createNodeArray(parameters); + node.body = body; + return node; + } + ts.createSetAccessor = createSetAccessor; + function updateSetAccessor(node, decorators, modifiers, name, parameters, body) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.name !== name + || node.parameters !== parameters + || node.body !== body + ? updateNode(createSetAccessor(decorators, modifiers, name, parameters, body), node) + : node; + } + ts.updateSetAccessor = updateSetAccessor; + function createCallSignature(typeParameters, parameters, type) { + return createSignatureDeclaration(160 /* CallSignature */, typeParameters, parameters, type); + } + ts.createCallSignature = createCallSignature; + function updateCallSignature(node, typeParameters, parameters, type) { + return updateSignatureDeclaration(node, typeParameters, parameters, type); + } + ts.updateCallSignature = updateCallSignature; + function createConstructSignature(typeParameters, parameters, type) { + return createSignatureDeclaration(161 /* ConstructSignature */, typeParameters, parameters, type); + } + ts.createConstructSignature = createConstructSignature; + function updateConstructSignature(node, typeParameters, parameters, type) { + return updateSignatureDeclaration(node, typeParameters, parameters, type); + } + ts.updateConstructSignature = updateConstructSignature; + function createIndexSignature(decorators, modifiers, parameters, type) { + var node = createSynthesizedNode(162 /* IndexSignature */); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.parameters = createNodeArray(parameters); + node.type = type; + return node; + } + ts.createIndexSignature = createIndexSignature; + function updateIndexSignature(node, decorators, modifiers, parameters, type) { + return node.parameters !== parameters + || node.type !== type + || node.decorators !== decorators + || node.modifiers !== modifiers + ? updateNode(createIndexSignature(decorators, modifiers, parameters, type), node) + : node; + } + ts.updateIndexSignature = updateIndexSignature; + /* @internal */ + function createSignatureDeclaration(kind, typeParameters, parameters, type, typeArguments) { + var node = createSynthesizedNode(kind); + node.typeParameters = asNodeArray(typeParameters); + node.parameters = asNodeArray(parameters); + node.type = type; + node.typeArguments = asNodeArray(typeArguments); + return node; + } + ts.createSignatureDeclaration = createSignatureDeclaration; + function updateSignatureDeclaration(node, typeParameters, parameters, type) { + return node.typeParameters !== typeParameters + || node.parameters !== parameters + || node.type !== type + ? updateNode(createSignatureDeclaration(node.kind, typeParameters, parameters, type), node) + : node; + } + // Types + function createKeywordTypeNode(kind) { + return createSynthesizedNode(kind); + } + ts.createKeywordTypeNode = createKeywordTypeNode; + function createTypePredicateNode(parameterName, type) { + var node = createSynthesizedNode(163 /* TypePredicate */); + node.parameterName = asName(parameterName); + node.type = type; + return node; + } + ts.createTypePredicateNode = createTypePredicateNode; + function updateTypePredicateNode(node, parameterName, type) { + return node.parameterName !== parameterName + || node.type !== type + ? updateNode(createTypePredicateNode(parameterName, type), node) + : node; + } + ts.updateTypePredicateNode = updateTypePredicateNode; + function createTypeReferenceNode(typeName, typeArguments) { + var node = createSynthesizedNode(164 /* TypeReference */); + node.typeName = asName(typeName); + node.typeArguments = typeArguments && ts.parenthesizeTypeParameters(typeArguments); + return node; + } + ts.createTypeReferenceNode = createTypeReferenceNode; + function updateTypeReferenceNode(node, typeName, typeArguments) { + return node.typeName !== typeName + || node.typeArguments !== typeArguments + ? updateNode(createTypeReferenceNode(typeName, typeArguments), node) + : node; + } + ts.updateTypeReferenceNode = updateTypeReferenceNode; + function createFunctionTypeNode(typeParameters, parameters, type) { + return createSignatureDeclaration(165 /* FunctionType */, typeParameters, parameters, type); + } + ts.createFunctionTypeNode = createFunctionTypeNode; + function updateFunctionTypeNode(node, typeParameters, parameters, type) { + return updateSignatureDeclaration(node, typeParameters, parameters, type); + } + ts.updateFunctionTypeNode = updateFunctionTypeNode; + function createConstructorTypeNode(typeParameters, parameters, type) { + return createSignatureDeclaration(166 /* ConstructorType */, typeParameters, parameters, type); + } + ts.createConstructorTypeNode = createConstructorTypeNode; + function updateConstructorTypeNode(node, typeParameters, parameters, type) { + return updateSignatureDeclaration(node, typeParameters, parameters, type); + } + ts.updateConstructorTypeNode = updateConstructorTypeNode; + function createTypeQueryNode(exprName) { + var node = createSynthesizedNode(167 /* TypeQuery */); + node.exprName = exprName; + return node; + } + ts.createTypeQueryNode = createTypeQueryNode; + function updateTypeQueryNode(node, exprName) { + return node.exprName !== exprName + ? updateNode(createTypeQueryNode(exprName), node) + : node; + } + ts.updateTypeQueryNode = updateTypeQueryNode; + function createTypeLiteralNode(members) { + var node = createSynthesizedNode(168 /* TypeLiteral */); + node.members = createNodeArray(members); + return node; + } + ts.createTypeLiteralNode = createTypeLiteralNode; + function updateTypeLiteralNode(node, members) { + return node.members !== members + ? updateNode(createTypeLiteralNode(members), node) + : node; + } + ts.updateTypeLiteralNode = updateTypeLiteralNode; + function createArrayTypeNode(elementType) { + var node = createSynthesizedNode(169 /* ArrayType */); + node.elementType = ts.parenthesizeArrayTypeMember(elementType); + return node; + } + ts.createArrayTypeNode = createArrayTypeNode; + function updateArrayTypeNode(node, elementType) { + return node.elementType !== elementType + ? updateNode(createArrayTypeNode(elementType), node) + : node; + } + ts.updateArrayTypeNode = updateArrayTypeNode; + function createTupleTypeNode(elementTypes) { + var node = createSynthesizedNode(170 /* TupleType */); + node.elementTypes = createNodeArray(elementTypes); + return node; + } + ts.createTupleTypeNode = createTupleTypeNode; + function updateTupleTypeNode(node, elementTypes) { + return node.elementTypes !== elementTypes + ? updateNode(createTupleTypeNode(elementTypes), node) + : node; + } + ts.updateTupleTypeNode = updateTupleTypeNode; + function createOptionalTypeNode(type) { + var node = createSynthesizedNode(171 /* OptionalType */); + node.type = ts.parenthesizeArrayTypeMember(type); + return node; + } + ts.createOptionalTypeNode = createOptionalTypeNode; + function updateOptionalTypeNode(node, type) { + return node.type !== type + ? updateNode(createOptionalTypeNode(type), node) + : node; + } + ts.updateOptionalTypeNode = updateOptionalTypeNode; + function createRestTypeNode(type) { + var node = createSynthesizedNode(172 /* RestType */); + node.type = type; + return node; + } + ts.createRestTypeNode = createRestTypeNode; + function updateRestTypeNode(node, type) { + return node.type !== type + ? updateNode(createRestTypeNode(type), node) + : node; + } + ts.updateRestTypeNode = updateRestTypeNode; + function createUnionTypeNode(types) { + return createUnionOrIntersectionTypeNode(173 /* UnionType */, types); + } + ts.createUnionTypeNode = createUnionTypeNode; + function updateUnionTypeNode(node, types) { + return updateUnionOrIntersectionTypeNode(node, types); + } + ts.updateUnionTypeNode = updateUnionTypeNode; + function createIntersectionTypeNode(types) { + return createUnionOrIntersectionTypeNode(174 /* IntersectionType */, types); + } + ts.createIntersectionTypeNode = createIntersectionTypeNode; + function updateIntersectionTypeNode(node, types) { + return updateUnionOrIntersectionTypeNode(node, types); + } + ts.updateIntersectionTypeNode = updateIntersectionTypeNode; + function createUnionOrIntersectionTypeNode(kind, types) { + var node = createSynthesizedNode(kind); + node.types = ts.parenthesizeElementTypeMembers(types); + return node; + } + ts.createUnionOrIntersectionTypeNode = createUnionOrIntersectionTypeNode; + function updateUnionOrIntersectionTypeNode(node, types) { + return node.types !== types + ? updateNode(createUnionOrIntersectionTypeNode(node.kind, types), node) + : node; + } + function createConditionalTypeNode(checkType, extendsType, trueType, falseType) { + var node = createSynthesizedNode(175 /* ConditionalType */); + node.checkType = ts.parenthesizeConditionalTypeMember(checkType); + node.extendsType = ts.parenthesizeConditionalTypeMember(extendsType); + node.trueType = trueType; + node.falseType = falseType; + return node; + } + ts.createConditionalTypeNode = createConditionalTypeNode; + function updateConditionalTypeNode(node, checkType, extendsType, trueType, falseType) { + return node.checkType !== checkType + || node.extendsType !== extendsType + || node.trueType !== trueType + || node.falseType !== falseType + ? updateNode(createConditionalTypeNode(checkType, extendsType, trueType, falseType), node) + : node; + } + ts.updateConditionalTypeNode = updateConditionalTypeNode; + function createInferTypeNode(typeParameter) { + var node = createSynthesizedNode(176 /* InferType */); + node.typeParameter = typeParameter; + return node; + } + ts.createInferTypeNode = createInferTypeNode; + function updateInferTypeNode(node, typeParameter) { + return node.typeParameter !== typeParameter + ? updateNode(createInferTypeNode(typeParameter), node) + : node; + } + ts.updateInferTypeNode = updateInferTypeNode; + function createImportTypeNode(argument, qualifier, typeArguments, isTypeOf) { + var node = createSynthesizedNode(183 /* ImportType */); + node.argument = argument; + node.qualifier = qualifier; + node.typeArguments = asNodeArray(typeArguments); + node.isTypeOf = isTypeOf; + return node; + } + ts.createImportTypeNode = createImportTypeNode; + function updateImportTypeNode(node, argument, qualifier, typeArguments, isTypeOf) { + return node.argument !== argument + || node.qualifier !== qualifier + || node.typeArguments !== typeArguments + || node.isTypeOf !== isTypeOf + ? updateNode(createImportTypeNode(argument, qualifier, typeArguments, isTypeOf), node) + : node; + } + ts.updateImportTypeNode = updateImportTypeNode; + function createParenthesizedType(type) { + var node = createSynthesizedNode(177 /* ParenthesizedType */); + node.type = type; + return node; + } + ts.createParenthesizedType = createParenthesizedType; + function updateParenthesizedType(node, type) { + return node.type !== type + ? updateNode(createParenthesizedType(type), node) + : node; + } + ts.updateParenthesizedType = updateParenthesizedType; + function createThisTypeNode() { + return createSynthesizedNode(178 /* ThisType */); + } + ts.createThisTypeNode = createThisTypeNode; + function createTypeOperatorNode(operatorOrType, type) { + var node = createSynthesizedNode(179 /* TypeOperator */); + node.operator = typeof operatorOrType === "number" ? operatorOrType : 129 /* KeyOfKeyword */; + node.type = ts.parenthesizeElementTypeMember(typeof operatorOrType === "number" ? type : operatorOrType); + return node; + } + ts.createTypeOperatorNode = createTypeOperatorNode; + function updateTypeOperatorNode(node, type) { + return node.type !== type ? updateNode(createTypeOperatorNode(node.operator, type), node) : node; + } + ts.updateTypeOperatorNode = updateTypeOperatorNode; + function createIndexedAccessTypeNode(objectType, indexType) { + var node = createSynthesizedNode(180 /* IndexedAccessType */); + node.objectType = ts.parenthesizeElementTypeMember(objectType); + node.indexType = indexType; + return node; + } + ts.createIndexedAccessTypeNode = createIndexedAccessTypeNode; + function updateIndexedAccessTypeNode(node, objectType, indexType) { + return node.objectType !== objectType + || node.indexType !== indexType + ? updateNode(createIndexedAccessTypeNode(objectType, indexType), node) + : node; + } + ts.updateIndexedAccessTypeNode = updateIndexedAccessTypeNode; + function createMappedTypeNode(readonlyToken, typeParameter, questionToken, type) { + var node = createSynthesizedNode(181 /* MappedType */); + node.readonlyToken = readonlyToken; + node.typeParameter = typeParameter; + node.questionToken = questionToken; + node.type = type; + return node; + } + ts.createMappedTypeNode = createMappedTypeNode; + function updateMappedTypeNode(node, readonlyToken, typeParameter, questionToken, type) { + return node.readonlyToken !== readonlyToken + || node.typeParameter !== typeParameter + || node.questionToken !== questionToken + || node.type !== type + ? updateNode(createMappedTypeNode(readonlyToken, typeParameter, questionToken, type), node) + : node; + } + ts.updateMappedTypeNode = updateMappedTypeNode; + function createLiteralTypeNode(literal) { + var node = createSynthesizedNode(182 /* LiteralType */); + node.literal = literal; + return node; + } + ts.createLiteralTypeNode = createLiteralTypeNode; + function updateLiteralTypeNode(node, literal) { + return node.literal !== literal + ? updateNode(createLiteralTypeNode(literal), node) + : node; + } + ts.updateLiteralTypeNode = updateLiteralTypeNode; + // Binding Patterns + function createObjectBindingPattern(elements) { + var node = createSynthesizedNode(184 /* ObjectBindingPattern */); + node.elements = createNodeArray(elements); + return node; + } + ts.createObjectBindingPattern = createObjectBindingPattern; + function updateObjectBindingPattern(node, elements) { + return node.elements !== elements + ? updateNode(createObjectBindingPattern(elements), node) + : node; + } + ts.updateObjectBindingPattern = updateObjectBindingPattern; + function createArrayBindingPattern(elements) { + var node = createSynthesizedNode(185 /* ArrayBindingPattern */); + node.elements = createNodeArray(elements); + return node; + } + ts.createArrayBindingPattern = createArrayBindingPattern; + function updateArrayBindingPattern(node, elements) { + return node.elements !== elements + ? updateNode(createArrayBindingPattern(elements), node) + : node; + } + ts.updateArrayBindingPattern = updateArrayBindingPattern; + function createBindingElement(dotDotDotToken, propertyName, name, initializer) { + var node = createSynthesizedNode(186 /* BindingElement */); + node.dotDotDotToken = dotDotDotToken; + node.propertyName = asName(propertyName); + node.name = asName(name); + node.initializer = initializer; + return node; + } + ts.createBindingElement = createBindingElement; + function updateBindingElement(node, dotDotDotToken, propertyName, name, initializer) { + return node.propertyName !== propertyName + || node.dotDotDotToken !== dotDotDotToken + || node.name !== name + || node.initializer !== initializer + ? updateNode(createBindingElement(dotDotDotToken, propertyName, name, initializer), node) + : node; + } + ts.updateBindingElement = updateBindingElement; + // Expression + function createArrayLiteral(elements, multiLine) { + var node = createSynthesizedNode(187 /* ArrayLiteralExpression */); + node.elements = ts.parenthesizeListElements(createNodeArray(elements)); + if (multiLine) + node.multiLine = true; + return node; + } + ts.createArrayLiteral = createArrayLiteral; + function updateArrayLiteral(node, elements) { + return node.elements !== elements + ? updateNode(createArrayLiteral(elements, node.multiLine), node) + : node; + } + ts.updateArrayLiteral = updateArrayLiteral; + function createObjectLiteral(properties, multiLine) { + var node = createSynthesizedNode(188 /* ObjectLiteralExpression */); + node.properties = createNodeArray(properties); + if (multiLine) + node.multiLine = true; + return node; + } + ts.createObjectLiteral = createObjectLiteral; + function updateObjectLiteral(node, properties) { + return node.properties !== properties + ? updateNode(createObjectLiteral(properties, node.multiLine), node) + : node; + } + ts.updateObjectLiteral = updateObjectLiteral; + function createPropertyAccess(expression, name) { + var node = createSynthesizedNode(189 /* PropertyAccessExpression */); + node.expression = ts.parenthesizeForAccess(expression); + node.name = asName(name); // TODO: GH#18217 + setEmitFlags(node, 131072 /* NoIndentation */); + return node; + } + ts.createPropertyAccess = createPropertyAccess; + function updatePropertyAccess(node, expression, name) { + // Because we are updating existed propertyAccess we want to inherit its emitFlags + // instead of using the default from createPropertyAccess + return node.expression !== expression + || node.name !== name + ? updateNode(setEmitFlags(createPropertyAccess(expression, name), ts.getEmitFlags(node)), node) + : node; + } + ts.updatePropertyAccess = updatePropertyAccess; + function createElementAccess(expression, index) { + var node = createSynthesizedNode(190 /* ElementAccessExpression */); + node.expression = ts.parenthesizeForAccess(expression); + node.argumentExpression = asExpression(index); + return node; + } + ts.createElementAccess = createElementAccess; + function updateElementAccess(node, expression, argumentExpression) { + return node.expression !== expression + || node.argumentExpression !== argumentExpression + ? updateNode(createElementAccess(expression, argumentExpression), node) + : node; + } + ts.updateElementAccess = updateElementAccess; + function createCall(expression, typeArguments, argumentsArray) { + var node = createSynthesizedNode(191 /* CallExpression */); + node.expression = ts.parenthesizeForAccess(expression); + node.typeArguments = asNodeArray(typeArguments); + node.arguments = ts.parenthesizeListElements(createNodeArray(argumentsArray)); + return node; + } + ts.createCall = createCall; + function updateCall(node, expression, typeArguments, argumentsArray) { + return node.expression !== expression + || node.typeArguments !== typeArguments + || node.arguments !== argumentsArray + ? updateNode(createCall(expression, typeArguments, argumentsArray), node) + : node; + } + ts.updateCall = updateCall; + function createNew(expression, typeArguments, argumentsArray) { + var node = createSynthesizedNode(192 /* NewExpression */); + node.expression = ts.parenthesizeForNew(expression); + node.typeArguments = asNodeArray(typeArguments); + node.arguments = argumentsArray ? ts.parenthesizeListElements(createNodeArray(argumentsArray)) : undefined; + return node; + } + ts.createNew = createNew; + function updateNew(node, expression, typeArguments, argumentsArray) { + return node.expression !== expression + || node.typeArguments !== typeArguments + || node.arguments !== argumentsArray + ? updateNode(createNew(expression, typeArguments, argumentsArray), node) + : node; + } + ts.updateNew = updateNew; + function createTaggedTemplate(tag, typeArgumentsOrTemplate, template) { + var node = createSynthesizedNode(193 /* TaggedTemplateExpression */); + node.tag = ts.parenthesizeForAccess(tag); + if (template) { + node.typeArguments = asNodeArray(typeArgumentsOrTemplate); + node.template = template; + } + else { + node.typeArguments = undefined; + node.template = typeArgumentsOrTemplate; + } + return node; + } + ts.createTaggedTemplate = createTaggedTemplate; + function updateTaggedTemplate(node, tag, typeArgumentsOrTemplate, template) { + return node.tag !== tag + || (template + ? node.typeArguments !== typeArgumentsOrTemplate || node.template !== template + : node.typeArguments !== undefined || node.template !== typeArgumentsOrTemplate) + ? updateNode(createTaggedTemplate(tag, typeArgumentsOrTemplate, template), node) + : node; + } + ts.updateTaggedTemplate = updateTaggedTemplate; + function createTypeAssertion(type, expression) { + var node = createSynthesizedNode(194 /* TypeAssertionExpression */); + node.type = type; + node.expression = ts.parenthesizePrefixOperand(expression); + return node; + } + ts.createTypeAssertion = createTypeAssertion; + function updateTypeAssertion(node, type, expression) { + return node.type !== type + || node.expression !== expression + ? updateNode(createTypeAssertion(type, expression), node) + : node; + } + ts.updateTypeAssertion = updateTypeAssertion; + function createParen(expression) { + var node = createSynthesizedNode(195 /* ParenthesizedExpression */); + node.expression = expression; + return node; + } + ts.createParen = createParen; + function updateParen(node, expression) { + return node.expression !== expression + ? updateNode(createParen(expression), node) + : node; + } + ts.updateParen = updateParen; + function createFunctionExpression(modifiers, asteriskToken, name, typeParameters, parameters, type, body) { + var node = createSynthesizedNode(196 /* FunctionExpression */); + node.modifiers = asNodeArray(modifiers); + node.asteriskToken = asteriskToken; + node.name = asName(name); + node.typeParameters = asNodeArray(typeParameters); + node.parameters = createNodeArray(parameters); + node.type = type; + node.body = body; + return node; + } + ts.createFunctionExpression = createFunctionExpression; + function updateFunctionExpression(node, modifiers, asteriskToken, name, typeParameters, parameters, type, body) { + return node.name !== name + || node.modifiers !== modifiers + || node.asteriskToken !== asteriskToken + || node.typeParameters !== typeParameters + || node.parameters !== parameters + || node.type !== type + || node.body !== body + ? updateNode(createFunctionExpression(modifiers, asteriskToken, name, typeParameters, parameters, type, body), node) + : node; + } + ts.updateFunctionExpression = updateFunctionExpression; + function createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body) { + var node = createSynthesizedNode(197 /* ArrowFunction */); + node.modifiers = asNodeArray(modifiers); + node.typeParameters = asNodeArray(typeParameters); + node.parameters = createNodeArray(parameters); + node.type = type; + node.equalsGreaterThanToken = equalsGreaterThanToken || createToken(37 /* EqualsGreaterThanToken */); + node.body = ts.parenthesizeConciseBody(body); + return node; + } + ts.createArrowFunction = createArrowFunction; + function updateArrowFunction(node, modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body) { + return node.modifiers !== modifiers + || node.typeParameters !== typeParameters + || node.parameters !== parameters + || node.type !== type + || node.equalsGreaterThanToken !== equalsGreaterThanToken + || node.body !== body + ? updateNode(createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body), node) + : node; + } + ts.updateArrowFunction = updateArrowFunction; + function createDelete(expression) { + var node = createSynthesizedNode(198 /* DeleteExpression */); + node.expression = ts.parenthesizePrefixOperand(expression); + return node; + } + ts.createDelete = createDelete; + function updateDelete(node, expression) { + return node.expression !== expression + ? updateNode(createDelete(expression), node) + : node; + } + ts.updateDelete = updateDelete; + function createTypeOf(expression) { + var node = createSynthesizedNode(199 /* TypeOfExpression */); + node.expression = ts.parenthesizePrefixOperand(expression); + return node; + } + ts.createTypeOf = createTypeOf; + function updateTypeOf(node, expression) { + return node.expression !== expression + ? updateNode(createTypeOf(expression), node) + : node; + } + ts.updateTypeOf = updateTypeOf; + function createVoid(expression) { + var node = createSynthesizedNode(200 /* VoidExpression */); + node.expression = ts.parenthesizePrefixOperand(expression); + return node; + } + ts.createVoid = createVoid; + function updateVoid(node, expression) { + return node.expression !== expression + ? updateNode(createVoid(expression), node) + : node; + } + ts.updateVoid = updateVoid; + function createAwait(expression) { + var node = createSynthesizedNode(201 /* AwaitExpression */); + node.expression = ts.parenthesizePrefixOperand(expression); + return node; + } + ts.createAwait = createAwait; + function updateAwait(node, expression) { + return node.expression !== expression + ? updateNode(createAwait(expression), node) + : node; + } + ts.updateAwait = updateAwait; + function createPrefix(operator, operand) { + var node = createSynthesizedNode(202 /* PrefixUnaryExpression */); + node.operator = operator; + node.operand = ts.parenthesizePrefixOperand(operand); + return node; + } + ts.createPrefix = createPrefix; + function updatePrefix(node, operand) { + return node.operand !== operand + ? updateNode(createPrefix(node.operator, operand), node) + : node; + } + ts.updatePrefix = updatePrefix; + function createPostfix(operand, operator) { + var node = createSynthesizedNode(203 /* PostfixUnaryExpression */); + node.operand = ts.parenthesizePostfixOperand(operand); + node.operator = operator; + return node; + } + ts.createPostfix = createPostfix; + function updatePostfix(node, operand) { + return node.operand !== operand + ? updateNode(createPostfix(operand, node.operator), node) + : node; + } + ts.updatePostfix = updatePostfix; + function createBinary(left, operator, right) { + var node = createSynthesizedNode(204 /* BinaryExpression */); + var operatorToken = asToken(operator); + var operatorKind = operatorToken.kind; + node.left = ts.parenthesizeBinaryOperand(operatorKind, left, /*isLeftSideOfBinary*/ true, /*leftOperand*/ undefined); + node.operatorToken = operatorToken; + node.right = ts.parenthesizeBinaryOperand(operatorKind, right, /*isLeftSideOfBinary*/ false, node.left); + return node; + } + ts.createBinary = createBinary; + function updateBinary(node, left, right, operator) { + return node.left !== left + || node.right !== right + ? updateNode(createBinary(left, operator || node.operatorToken, right), node) + : node; + } + ts.updateBinary = updateBinary; + function createConditional(condition, questionTokenOrWhenTrue, whenTrueOrWhenFalse, colonToken, whenFalse) { + var node = createSynthesizedNode(205 /* ConditionalExpression */); + node.condition = ts.parenthesizeForConditionalHead(condition); + node.questionToken = whenFalse ? questionTokenOrWhenTrue : createToken(56 /* QuestionToken */); + node.whenTrue = ts.parenthesizeSubexpressionOfConditionalExpression(whenFalse ? whenTrueOrWhenFalse : questionTokenOrWhenTrue); + node.colonToken = whenFalse ? colonToken : createToken(57 /* ColonToken */); + node.whenFalse = ts.parenthesizeSubexpressionOfConditionalExpression(whenFalse ? whenFalse : whenTrueOrWhenFalse); + return node; + } + ts.createConditional = createConditional; + function updateConditional(node, condition, questionToken, whenTrue, colonToken, whenFalse) { + return node.condition !== condition + || node.questionToken !== questionToken + || node.whenTrue !== whenTrue + || node.colonToken !== colonToken + || node.whenFalse !== whenFalse + ? updateNode(createConditional(condition, questionToken, whenTrue, colonToken, whenFalse), node) + : node; + } + ts.updateConditional = updateConditional; + function createTemplateExpression(head, templateSpans) { + var node = createSynthesizedNode(206 /* TemplateExpression */); + node.head = head; + node.templateSpans = createNodeArray(templateSpans); + return node; + } + ts.createTemplateExpression = createTemplateExpression; + function updateTemplateExpression(node, head, templateSpans) { + return node.head !== head + || node.templateSpans !== templateSpans + ? updateNode(createTemplateExpression(head, templateSpans), node) + : node; + } + ts.updateTemplateExpression = updateTemplateExpression; + function createTemplateHead(text) { + var node = createSynthesizedNode(15 /* TemplateHead */); + node.text = text; + return node; + } + ts.createTemplateHead = createTemplateHead; + function createTemplateMiddle(text) { + var node = createSynthesizedNode(16 /* TemplateMiddle */); + node.text = text; + return node; + } + ts.createTemplateMiddle = createTemplateMiddle; + function createTemplateTail(text) { + var node = createSynthesizedNode(17 /* TemplateTail */); + node.text = text; + return node; + } + ts.createTemplateTail = createTemplateTail; + function createNoSubstitutionTemplateLiteral(text) { + var node = createSynthesizedNode(14 /* NoSubstitutionTemplateLiteral */); + node.text = text; + return node; + } + ts.createNoSubstitutionTemplateLiteral = createNoSubstitutionTemplateLiteral; + function createYield(asteriskTokenOrExpression, expression) { + var node = createSynthesizedNode(207 /* YieldExpression */); + node.asteriskToken = asteriskTokenOrExpression && asteriskTokenOrExpression.kind === 40 /* AsteriskToken */ ? asteriskTokenOrExpression : undefined; + node.expression = asteriskTokenOrExpression && asteriskTokenOrExpression.kind !== 40 /* AsteriskToken */ ? asteriskTokenOrExpression : expression; + return node; + } + ts.createYield = createYield; + function updateYield(node, asteriskToken, expression) { + return node.expression !== expression + || node.asteriskToken !== asteriskToken + ? updateNode(createYield(asteriskToken, expression), node) + : node; + } + ts.updateYield = updateYield; + function createSpread(expression) { + var node = createSynthesizedNode(208 /* SpreadElement */); + node.expression = ts.parenthesizeExpressionForList(expression); + return node; + } + ts.createSpread = createSpread; + function updateSpread(node, expression) { + return node.expression !== expression + ? updateNode(createSpread(expression), node) + : node; + } + ts.updateSpread = updateSpread; + function createClassExpression(modifiers, name, typeParameters, heritageClauses, members) { + var node = createSynthesizedNode(209 /* ClassExpression */); + node.decorators = undefined; + node.modifiers = asNodeArray(modifiers); + node.name = asName(name); + node.typeParameters = asNodeArray(typeParameters); + node.heritageClauses = asNodeArray(heritageClauses); + node.members = createNodeArray(members); + return node; + } + ts.createClassExpression = createClassExpression; + function updateClassExpression(node, modifiers, name, typeParameters, heritageClauses, members) { + return node.modifiers !== modifiers + || node.name !== name + || node.typeParameters !== typeParameters + || node.heritageClauses !== heritageClauses + || node.members !== members + ? updateNode(createClassExpression(modifiers, name, typeParameters, heritageClauses, members), node) + : node; + } + ts.updateClassExpression = updateClassExpression; + function createOmittedExpression() { + return createSynthesizedNode(210 /* OmittedExpression */); + } + ts.createOmittedExpression = createOmittedExpression; + function createExpressionWithTypeArguments(typeArguments, expression) { + var node = createSynthesizedNode(211 /* ExpressionWithTypeArguments */); + node.expression = ts.parenthesizeForAccess(expression); + node.typeArguments = asNodeArray(typeArguments); + return node; + } + ts.createExpressionWithTypeArguments = createExpressionWithTypeArguments; + function updateExpressionWithTypeArguments(node, typeArguments, expression) { + return node.typeArguments !== typeArguments + || node.expression !== expression + ? updateNode(createExpressionWithTypeArguments(typeArguments, expression), node) + : node; + } + ts.updateExpressionWithTypeArguments = updateExpressionWithTypeArguments; + function createAsExpression(expression, type) { + var node = createSynthesizedNode(212 /* AsExpression */); + node.expression = expression; + node.type = type; + return node; + } + ts.createAsExpression = createAsExpression; + function updateAsExpression(node, expression, type) { + return node.expression !== expression + || node.type !== type + ? updateNode(createAsExpression(expression, type), node) + : node; + } + ts.updateAsExpression = updateAsExpression; + function createNonNullExpression(expression) { + var node = createSynthesizedNode(213 /* NonNullExpression */); + node.expression = ts.parenthesizeForAccess(expression); + return node; + } + ts.createNonNullExpression = createNonNullExpression; + function updateNonNullExpression(node, expression) { + return node.expression !== expression + ? updateNode(createNonNullExpression(expression), node) + : node; + } + ts.updateNonNullExpression = updateNonNullExpression; + function createMetaProperty(keywordToken, name) { + var node = createSynthesizedNode(214 /* MetaProperty */); + node.keywordToken = keywordToken; + node.name = name; + return node; + } + ts.createMetaProperty = createMetaProperty; + function updateMetaProperty(node, name) { + return node.name !== name + ? updateNode(createMetaProperty(node.keywordToken, name), node) + : node; + } + ts.updateMetaProperty = updateMetaProperty; + // Misc + function createTemplateSpan(expression, literal) { + var node = createSynthesizedNode(216 /* TemplateSpan */); + node.expression = expression; + node.literal = literal; + return node; + } + ts.createTemplateSpan = createTemplateSpan; + function updateTemplateSpan(node, expression, literal) { + return node.expression !== expression + || node.literal !== literal + ? updateNode(createTemplateSpan(expression, literal), node) + : node; + } + ts.updateTemplateSpan = updateTemplateSpan; + function createSemicolonClassElement() { + return createSynthesizedNode(217 /* SemicolonClassElement */); + } + ts.createSemicolonClassElement = createSemicolonClassElement; + // Element + function createBlock(statements, multiLine) { + var block = createSynthesizedNode(218 /* Block */); + block.statements = createNodeArray(statements); + if (multiLine) + block.multiLine = multiLine; + return block; + } + ts.createBlock = createBlock; + function updateBlock(node, statements) { + return node.statements !== statements + ? updateNode(createBlock(statements, node.multiLine), node) + : node; + } + ts.updateBlock = updateBlock; + function createVariableStatement(modifiers, declarationList) { + var node = createSynthesizedNode(219 /* VariableStatement */); + node.decorators = undefined; + node.modifiers = asNodeArray(modifiers); + node.declarationList = ts.isArray(declarationList) ? createVariableDeclarationList(declarationList) : declarationList; + return node; + } + ts.createVariableStatement = createVariableStatement; + function updateVariableStatement(node, modifiers, declarationList) { + return node.modifiers !== modifiers + || node.declarationList !== declarationList + ? updateNode(createVariableStatement(modifiers, declarationList), node) + : node; + } + ts.updateVariableStatement = updateVariableStatement; + function createEmptyStatement() { + return createSynthesizedNode(220 /* EmptyStatement */); + } + ts.createEmptyStatement = createEmptyStatement; + function createExpressionStatement(expression) { + var node = createSynthesizedNode(221 /* ExpressionStatement */); + node.expression = ts.parenthesizeExpressionForExpressionStatement(expression); + return node; + } + ts.createExpressionStatement = createExpressionStatement; + function updateExpressionStatement(node, expression) { + return node.expression !== expression + ? updateNode(createExpressionStatement(expression), node) + : node; + } + ts.updateExpressionStatement = updateExpressionStatement; + /** @deprecated Use `createExpressionStatement` instead. */ + ts.createStatement = createExpressionStatement; + /** @deprecated Use `updateExpressionStatement` instead. */ + ts.updateStatement = updateExpressionStatement; + function createIf(expression, thenStatement, elseStatement) { + var node = createSynthesizedNode(222 /* IfStatement */); + node.expression = expression; + node.thenStatement = thenStatement; + node.elseStatement = elseStatement; + return node; + } + ts.createIf = createIf; + function updateIf(node, expression, thenStatement, elseStatement) { + return node.expression !== expression + || node.thenStatement !== thenStatement + || node.elseStatement !== elseStatement + ? updateNode(createIf(expression, thenStatement, elseStatement), node) + : node; + } + ts.updateIf = updateIf; + function createDo(statement, expression) { + var node = createSynthesizedNode(223 /* DoStatement */); + node.statement = statement; + node.expression = expression; + return node; + } + ts.createDo = createDo; + function updateDo(node, statement, expression) { + return node.statement !== statement + || node.expression !== expression + ? updateNode(createDo(statement, expression), node) + : node; + } + ts.updateDo = updateDo; + function createWhile(expression, statement) { + var node = createSynthesizedNode(224 /* WhileStatement */); + node.expression = expression; + node.statement = statement; + return node; + } + ts.createWhile = createWhile; + function updateWhile(node, expression, statement) { + return node.expression !== expression + || node.statement !== statement + ? updateNode(createWhile(expression, statement), node) + : node; + } + ts.updateWhile = updateWhile; + function createFor(initializer, condition, incrementor, statement) { + var node = createSynthesizedNode(225 /* ForStatement */); + node.initializer = initializer; + node.condition = condition; + node.incrementor = incrementor; + node.statement = statement; + return node; + } + ts.createFor = createFor; + function updateFor(node, initializer, condition, incrementor, statement) { + return node.initializer !== initializer + || node.condition !== condition + || node.incrementor !== incrementor + || node.statement !== statement + ? updateNode(createFor(initializer, condition, incrementor, statement), node) + : node; + } + ts.updateFor = updateFor; + function createForIn(initializer, expression, statement) { + var node = createSynthesizedNode(226 /* ForInStatement */); + node.initializer = initializer; + node.expression = expression; + node.statement = statement; + return node; + } + ts.createForIn = createForIn; + function updateForIn(node, initializer, expression, statement) { + return node.initializer !== initializer + || node.expression !== expression + || node.statement !== statement + ? updateNode(createForIn(initializer, expression, statement), node) + : node; + } + ts.updateForIn = updateForIn; + function createForOf(awaitModifier, initializer, expression, statement) { + var node = createSynthesizedNode(227 /* ForOfStatement */); + node.awaitModifier = awaitModifier; + node.initializer = initializer; + node.expression = expression; + node.statement = statement; + return node; + } + ts.createForOf = createForOf; + function updateForOf(node, awaitModifier, initializer, expression, statement) { + return node.awaitModifier !== awaitModifier + || node.initializer !== initializer + || node.expression !== expression + || node.statement !== statement + ? updateNode(createForOf(awaitModifier, initializer, expression, statement), node) + : node; + } + ts.updateForOf = updateForOf; + function createContinue(label) { + var node = createSynthesizedNode(228 /* ContinueStatement */); + node.label = asName(label); + return node; + } + ts.createContinue = createContinue; + function updateContinue(node, label) { + return node.label !== label + ? updateNode(createContinue(label), node) + : node; + } + ts.updateContinue = updateContinue; + function createBreak(label) { + var node = createSynthesizedNode(229 /* BreakStatement */); + node.label = asName(label); + return node; + } + ts.createBreak = createBreak; + function updateBreak(node, label) { + return node.label !== label + ? updateNode(createBreak(label), node) + : node; + } + ts.updateBreak = updateBreak; + function createReturn(expression) { + var node = createSynthesizedNode(230 /* ReturnStatement */); + node.expression = expression; + return node; + } + ts.createReturn = createReturn; + function updateReturn(node, expression) { + return node.expression !== expression + ? updateNode(createReturn(expression), node) + : node; + } + ts.updateReturn = updateReturn; + function createWith(expression, statement) { + var node = createSynthesizedNode(231 /* WithStatement */); + node.expression = expression; + node.statement = statement; + return node; + } + ts.createWith = createWith; + function updateWith(node, expression, statement) { + return node.expression !== expression + || node.statement !== statement + ? updateNode(createWith(expression, statement), node) + : node; + } + ts.updateWith = updateWith; + function createSwitch(expression, caseBlock) { + var node = createSynthesizedNode(232 /* SwitchStatement */); + node.expression = ts.parenthesizeExpressionForList(expression); + node.caseBlock = caseBlock; + return node; + } + ts.createSwitch = createSwitch; + function updateSwitch(node, expression, caseBlock) { + return node.expression !== expression + || node.caseBlock !== caseBlock + ? updateNode(createSwitch(expression, caseBlock), node) + : node; + } + ts.updateSwitch = updateSwitch; + function createLabel(label, statement) { + var node = createSynthesizedNode(233 /* LabeledStatement */); + node.label = asName(label); + node.statement = statement; + return node; + } + ts.createLabel = createLabel; + function updateLabel(node, label, statement) { + return node.label !== label + || node.statement !== statement + ? updateNode(createLabel(label, statement), node) + : node; + } + ts.updateLabel = updateLabel; + function createThrow(expression) { + var node = createSynthesizedNode(234 /* ThrowStatement */); + node.expression = expression; + return node; + } + ts.createThrow = createThrow; + function updateThrow(node, expression) { + return node.expression !== expression + ? updateNode(createThrow(expression), node) + : node; + } + ts.updateThrow = updateThrow; + function createTry(tryBlock, catchClause, finallyBlock) { + var node = createSynthesizedNode(235 /* TryStatement */); + node.tryBlock = tryBlock; + node.catchClause = catchClause; + node.finallyBlock = finallyBlock; + return node; + } + ts.createTry = createTry; + function updateTry(node, tryBlock, catchClause, finallyBlock) { + return node.tryBlock !== tryBlock + || node.catchClause !== catchClause + || node.finallyBlock !== finallyBlock + ? updateNode(createTry(tryBlock, catchClause, finallyBlock), node) + : node; + } + ts.updateTry = updateTry; + function createDebuggerStatement() { + return createSynthesizedNode(236 /* DebuggerStatement */); + } + ts.createDebuggerStatement = createDebuggerStatement; + function createVariableDeclaration(name, type, initializer) { + var node = createSynthesizedNode(237 /* VariableDeclaration */); + node.name = asName(name); + node.type = type; + node.initializer = initializer !== undefined ? ts.parenthesizeExpressionForList(initializer) : undefined; + return node; + } + ts.createVariableDeclaration = createVariableDeclaration; + function updateVariableDeclaration(node, name, type, initializer) { + return node.name !== name + || node.type !== type + || node.initializer !== initializer + ? updateNode(createVariableDeclaration(name, type, initializer), node) + : node; + } + ts.updateVariableDeclaration = updateVariableDeclaration; + function createVariableDeclarationList(declarations, flags) { + if (flags === void 0) { flags = 0 /* None */; } + var node = createSynthesizedNode(238 /* VariableDeclarationList */); + node.flags |= flags & 3 /* BlockScoped */; + node.declarations = createNodeArray(declarations); + return node; + } + ts.createVariableDeclarationList = createVariableDeclarationList; + function updateVariableDeclarationList(node, declarations) { + return node.declarations !== declarations + ? updateNode(createVariableDeclarationList(declarations, node.flags), node) + : node; + } + ts.updateVariableDeclarationList = updateVariableDeclarationList; + function createFunctionDeclaration(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body) { + var node = createSynthesizedNode(239 /* FunctionDeclaration */); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.asteriskToken = asteriskToken; + node.name = asName(name); + node.typeParameters = asNodeArray(typeParameters); + node.parameters = createNodeArray(parameters); + node.type = type; + node.body = body; + return node; + } + ts.createFunctionDeclaration = createFunctionDeclaration; + function updateFunctionDeclaration(node, decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.asteriskToken !== asteriskToken + || node.name !== name + || node.typeParameters !== typeParameters + || node.parameters !== parameters + || node.type !== type + || node.body !== body + ? updateNode(createFunctionDeclaration(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body), node) + : node; + } + ts.updateFunctionDeclaration = updateFunctionDeclaration; + function createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) { + var node = createSynthesizedNode(240 /* ClassDeclaration */); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.name = asName(name); + node.typeParameters = asNodeArray(typeParameters); + node.heritageClauses = asNodeArray(heritageClauses); + node.members = createNodeArray(members); + return node; + } + ts.createClassDeclaration = createClassDeclaration; + function updateClassDeclaration(node, decorators, modifiers, name, typeParameters, heritageClauses, members) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.name !== name + || node.typeParameters !== typeParameters + || node.heritageClauses !== heritageClauses + || node.members !== members + ? updateNode(createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members), node) + : node; + } + ts.updateClassDeclaration = updateClassDeclaration; + function createInterfaceDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) { + var node = createSynthesizedNode(241 /* InterfaceDeclaration */); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.name = asName(name); + node.typeParameters = asNodeArray(typeParameters); + node.heritageClauses = asNodeArray(heritageClauses); + node.members = createNodeArray(members); + return node; + } + ts.createInterfaceDeclaration = createInterfaceDeclaration; + function updateInterfaceDeclaration(node, decorators, modifiers, name, typeParameters, heritageClauses, members) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.name !== name + || node.typeParameters !== typeParameters + || node.heritageClauses !== heritageClauses + || node.members !== members + ? updateNode(createInterfaceDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members), node) + : node; + } + ts.updateInterfaceDeclaration = updateInterfaceDeclaration; + function createTypeAliasDeclaration(decorators, modifiers, name, typeParameters, type) { + var node = createSynthesizedNode(242 /* TypeAliasDeclaration */); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.name = asName(name); + node.typeParameters = asNodeArray(typeParameters); + node.type = type; + return node; + } + ts.createTypeAliasDeclaration = createTypeAliasDeclaration; + function updateTypeAliasDeclaration(node, decorators, modifiers, name, typeParameters, type) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.name !== name + || node.typeParameters !== typeParameters + || node.type !== type + ? updateNode(createTypeAliasDeclaration(decorators, modifiers, name, typeParameters, type), node) + : node; + } + ts.updateTypeAliasDeclaration = updateTypeAliasDeclaration; + function createEnumDeclaration(decorators, modifiers, name, members) { + var node = createSynthesizedNode(243 /* EnumDeclaration */); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.name = asName(name); + node.members = createNodeArray(members); + return node; + } + ts.createEnumDeclaration = createEnumDeclaration; + function updateEnumDeclaration(node, decorators, modifiers, name, members) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.name !== name + || node.members !== members + ? updateNode(createEnumDeclaration(decorators, modifiers, name, members), node) + : node; + } + ts.updateEnumDeclaration = updateEnumDeclaration; + function createModuleDeclaration(decorators, modifiers, name, body, flags) { + if (flags === void 0) { flags = 0 /* None */; } + var node = createSynthesizedNode(244 /* ModuleDeclaration */); + node.flags |= flags & (16 /* Namespace */ | 4 /* NestedNamespace */ | 512 /* GlobalAugmentation */); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.name = name; + node.body = body; + return node; + } + ts.createModuleDeclaration = createModuleDeclaration; + function updateModuleDeclaration(node, decorators, modifiers, name, body) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.name !== name + || node.body !== body + ? updateNode(createModuleDeclaration(decorators, modifiers, name, body, node.flags), node) + : node; + } + ts.updateModuleDeclaration = updateModuleDeclaration; + function createModuleBlock(statements) { + var node = createSynthesizedNode(245 /* ModuleBlock */); + node.statements = createNodeArray(statements); + return node; + } + ts.createModuleBlock = createModuleBlock; + function updateModuleBlock(node, statements) { + return node.statements !== statements + ? updateNode(createModuleBlock(statements), node) + : node; + } + ts.updateModuleBlock = updateModuleBlock; + function createCaseBlock(clauses) { + var node = createSynthesizedNode(246 /* CaseBlock */); + node.clauses = createNodeArray(clauses); + return node; + } + ts.createCaseBlock = createCaseBlock; + function updateCaseBlock(node, clauses) { + return node.clauses !== clauses + ? updateNode(createCaseBlock(clauses), node) + : node; + } + ts.updateCaseBlock = updateCaseBlock; + function createNamespaceExportDeclaration(name) { + var node = createSynthesizedNode(247 /* NamespaceExportDeclaration */); + node.name = asName(name); + return node; + } + ts.createNamespaceExportDeclaration = createNamespaceExportDeclaration; + function updateNamespaceExportDeclaration(node, name) { + return node.name !== name + ? updateNode(createNamespaceExportDeclaration(name), node) + : node; + } + ts.updateNamespaceExportDeclaration = updateNamespaceExportDeclaration; + function createImportEqualsDeclaration(decorators, modifiers, name, moduleReference) { + var node = createSynthesizedNode(248 /* ImportEqualsDeclaration */); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.name = asName(name); + node.moduleReference = moduleReference; + return node; + } + ts.createImportEqualsDeclaration = createImportEqualsDeclaration; + function updateImportEqualsDeclaration(node, decorators, modifiers, name, moduleReference) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.name !== name + || node.moduleReference !== moduleReference + ? updateNode(createImportEqualsDeclaration(decorators, modifiers, name, moduleReference), node) + : node; + } + ts.updateImportEqualsDeclaration = updateImportEqualsDeclaration; + function createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier) { + var node = createSynthesizedNode(249 /* ImportDeclaration */); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.importClause = importClause; + node.moduleSpecifier = moduleSpecifier; + return node; + } + ts.createImportDeclaration = createImportDeclaration; + function updateImportDeclaration(node, decorators, modifiers, importClause, moduleSpecifier) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.importClause !== importClause + || node.moduleSpecifier !== moduleSpecifier + ? updateNode(createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier), node) + : node; + } + ts.updateImportDeclaration = updateImportDeclaration; + function createImportClause(name, namedBindings) { + var node = createSynthesizedNode(250 /* ImportClause */); + node.name = name; + node.namedBindings = namedBindings; + return node; + } + ts.createImportClause = createImportClause; + function updateImportClause(node, name, namedBindings) { + return node.name !== name + || node.namedBindings !== namedBindings + ? updateNode(createImportClause(name, namedBindings), node) + : node; + } + ts.updateImportClause = updateImportClause; + function createNamespaceImport(name) { + var node = createSynthesizedNode(251 /* NamespaceImport */); + node.name = name; + return node; + } + ts.createNamespaceImport = createNamespaceImport; + function updateNamespaceImport(node, name) { + return node.name !== name + ? updateNode(createNamespaceImport(name), node) + : node; + } + ts.updateNamespaceImport = updateNamespaceImport; + function createNamedImports(elements) { + var node = createSynthesizedNode(252 /* NamedImports */); + node.elements = createNodeArray(elements); + return node; + } + ts.createNamedImports = createNamedImports; + function updateNamedImports(node, elements) { + return node.elements !== elements + ? updateNode(createNamedImports(elements), node) + : node; + } + ts.updateNamedImports = updateNamedImports; + function createImportSpecifier(propertyName, name) { + var node = createSynthesizedNode(253 /* ImportSpecifier */); + node.propertyName = propertyName; + node.name = name; + return node; + } + ts.createImportSpecifier = createImportSpecifier; + function updateImportSpecifier(node, propertyName, name) { + return node.propertyName !== propertyName + || node.name !== name + ? updateNode(createImportSpecifier(propertyName, name), node) + : node; + } + ts.updateImportSpecifier = updateImportSpecifier; + function createExportAssignment(decorators, modifiers, isExportEquals, expression) { + var node = createSynthesizedNode(254 /* ExportAssignment */); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.isExportEquals = isExportEquals; + node.expression = isExportEquals ? ts.parenthesizeBinaryOperand(59 /* EqualsToken */, expression, /*isLeftSideOfBinary*/ false, /*leftOperand*/ undefined) : ts.parenthesizeDefaultExpression(expression); + return node; + } + ts.createExportAssignment = createExportAssignment; + function updateExportAssignment(node, decorators, modifiers, expression) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.expression !== expression + ? updateNode(createExportAssignment(decorators, modifiers, node.isExportEquals, expression), node) + : node; + } + ts.updateExportAssignment = updateExportAssignment; + function createExportDeclaration(decorators, modifiers, exportClause, moduleSpecifier) { + var node = createSynthesizedNode(255 /* ExportDeclaration */); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.exportClause = exportClause; + node.moduleSpecifier = moduleSpecifier; + return node; + } + ts.createExportDeclaration = createExportDeclaration; + function updateExportDeclaration(node, decorators, modifiers, exportClause, moduleSpecifier) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.exportClause !== exportClause + || node.moduleSpecifier !== moduleSpecifier + ? updateNode(createExportDeclaration(decorators, modifiers, exportClause, moduleSpecifier), node) + : node; + } + ts.updateExportDeclaration = updateExportDeclaration; + function createNamedExports(elements) { + var node = createSynthesizedNode(256 /* NamedExports */); + node.elements = createNodeArray(elements); + return node; + } + ts.createNamedExports = createNamedExports; + function updateNamedExports(node, elements) { + return node.elements !== elements + ? updateNode(createNamedExports(elements), node) + : node; + } + ts.updateNamedExports = updateNamedExports; + function createExportSpecifier(propertyName, name) { + var node = createSynthesizedNode(257 /* ExportSpecifier */); + node.propertyName = asName(propertyName); + node.name = asName(name); + return node; + } + ts.createExportSpecifier = createExportSpecifier; + function updateExportSpecifier(node, propertyName, name) { + return node.propertyName !== propertyName + || node.name !== name + ? updateNode(createExportSpecifier(propertyName, name), node) + : node; + } + ts.updateExportSpecifier = updateExportSpecifier; + // Module references + function createExternalModuleReference(expression) { + var node = createSynthesizedNode(259 /* ExternalModuleReference */); + node.expression = expression; + return node; + } + ts.createExternalModuleReference = createExternalModuleReference; + function updateExternalModuleReference(node, expression) { + return node.expression !== expression + ? updateNode(createExternalModuleReference(expression), node) + : node; + } + ts.updateExternalModuleReference = updateExternalModuleReference; + // JSDoc + /* @internal */ + function createJSDocTypeExpression(type) { + var node = createSynthesizedNode(283 /* JSDocTypeExpression */); + node.type = type; + return node; + } + ts.createJSDocTypeExpression = createJSDocTypeExpression; + /* @internal */ + function createJSDocTypeTag(typeExpression, comment) { + var tag = createJSDocTag(302 /* JSDocTypeTag */, "type"); + tag.typeExpression = typeExpression; + tag.comment = comment; + return tag; + } + ts.createJSDocTypeTag = createJSDocTypeTag; + /* @internal */ + function createJSDocReturnTag(typeExpression, comment) { + var tag = createJSDocTag(300 /* JSDocReturnTag */, "returns"); + tag.typeExpression = typeExpression; + tag.comment = comment; + return tag; + } + ts.createJSDocReturnTag = createJSDocReturnTag; + /* @internal */ + function createJSDocParamTag(name, isBracketed, typeExpression, comment) { + var tag = createJSDocTag(299 /* JSDocParameterTag */, "param"); + tag.typeExpression = typeExpression; + tag.name = name; + tag.isBracketed = isBracketed; + tag.comment = comment; + return tag; + } + ts.createJSDocParamTag = createJSDocParamTag; + /* @internal */ + function createJSDocComment(comment, tags) { + var node = createSynthesizedNode(291 /* JSDocComment */); + node.comment = comment; + node.tags = tags; + return node; + } + ts.createJSDocComment = createJSDocComment; + /* @internal */ + function createJSDocTag(kind, tagName) { + var node = createSynthesizedNode(kind); + node.tagName = createIdentifier(tagName); + return node; + } + // JSX + function createJsxElement(openingElement, children, closingElement) { + var node = createSynthesizedNode(260 /* JsxElement */); + node.openingElement = openingElement; + node.children = createNodeArray(children); + node.closingElement = closingElement; + return node; + } + ts.createJsxElement = createJsxElement; + function updateJsxElement(node, openingElement, children, closingElement) { + return node.openingElement !== openingElement + || node.children !== children + || node.closingElement !== closingElement + ? updateNode(createJsxElement(openingElement, children, closingElement), node) + : node; + } + ts.updateJsxElement = updateJsxElement; + function createJsxSelfClosingElement(tagName, typeArguments, attributes) { + var node = createSynthesizedNode(261 /* JsxSelfClosingElement */); + node.tagName = tagName; + node.typeArguments = asNodeArray(typeArguments); + node.attributes = attributes; + return node; + } + ts.createJsxSelfClosingElement = createJsxSelfClosingElement; + function updateJsxSelfClosingElement(node, tagName, typeArguments, attributes) { + return node.tagName !== tagName + || node.typeArguments !== typeArguments + || node.attributes !== attributes + ? updateNode(createJsxSelfClosingElement(tagName, typeArguments, attributes), node) + : node; + } + ts.updateJsxSelfClosingElement = updateJsxSelfClosingElement; + function createJsxOpeningElement(tagName, typeArguments, attributes) { + var node = createSynthesizedNode(262 /* JsxOpeningElement */); + node.tagName = tagName; + node.typeArguments = asNodeArray(typeArguments); + node.attributes = attributes; + return node; + } + ts.createJsxOpeningElement = createJsxOpeningElement; + function updateJsxOpeningElement(node, tagName, typeArguments, attributes) { + return node.tagName !== tagName + || node.typeArguments !== typeArguments + || node.attributes !== attributes + ? updateNode(createJsxOpeningElement(tagName, typeArguments, attributes), node) + : node; + } + ts.updateJsxOpeningElement = updateJsxOpeningElement; + function createJsxClosingElement(tagName) { + var node = createSynthesizedNode(263 /* JsxClosingElement */); + node.tagName = tagName; + return node; + } + ts.createJsxClosingElement = createJsxClosingElement; + function updateJsxClosingElement(node, tagName) { + return node.tagName !== tagName + ? updateNode(createJsxClosingElement(tagName), node) + : node; + } + ts.updateJsxClosingElement = updateJsxClosingElement; + function createJsxFragment(openingFragment, children, closingFragment) { + var node = createSynthesizedNode(264 /* JsxFragment */); + node.openingFragment = openingFragment; + node.children = createNodeArray(children); + node.closingFragment = closingFragment; + return node; + } + ts.createJsxFragment = createJsxFragment; + function updateJsxFragment(node, openingFragment, children, closingFragment) { + return node.openingFragment !== openingFragment + || node.children !== children + || node.closingFragment !== closingFragment + ? updateNode(createJsxFragment(openingFragment, children, closingFragment), node) + : node; + } + ts.updateJsxFragment = updateJsxFragment; + function createJsxAttribute(name, initializer) { + var node = createSynthesizedNode(267 /* JsxAttribute */); + node.name = name; + node.initializer = initializer; + return node; + } + ts.createJsxAttribute = createJsxAttribute; + function updateJsxAttribute(node, name, initializer) { + return node.name !== name + || node.initializer !== initializer + ? updateNode(createJsxAttribute(name, initializer), node) + : node; + } + ts.updateJsxAttribute = updateJsxAttribute; + function createJsxAttributes(properties) { + var node = createSynthesizedNode(268 /* JsxAttributes */); + node.properties = createNodeArray(properties); + return node; + } + ts.createJsxAttributes = createJsxAttributes; + function updateJsxAttributes(node, properties) { + return node.properties !== properties + ? updateNode(createJsxAttributes(properties), node) + : node; + } + ts.updateJsxAttributes = updateJsxAttributes; + function createJsxSpreadAttribute(expression) { + var node = createSynthesizedNode(269 /* JsxSpreadAttribute */); + node.expression = expression; + return node; + } + ts.createJsxSpreadAttribute = createJsxSpreadAttribute; + function updateJsxSpreadAttribute(node, expression) { + return node.expression !== expression + ? updateNode(createJsxSpreadAttribute(expression), node) + : node; + } + ts.updateJsxSpreadAttribute = updateJsxSpreadAttribute; + function createJsxExpression(dotDotDotToken, expression) { + var node = createSynthesizedNode(270 /* JsxExpression */); + node.dotDotDotToken = dotDotDotToken; + node.expression = expression; + return node; + } + ts.createJsxExpression = createJsxExpression; + function updateJsxExpression(node, expression) { + return node.expression !== expression + ? updateNode(createJsxExpression(node.dotDotDotToken, expression), node) + : node; + } + ts.updateJsxExpression = updateJsxExpression; + // Clauses + function createCaseClause(expression, statements) { + var node = createSynthesizedNode(271 /* CaseClause */); + node.expression = ts.parenthesizeExpressionForList(expression); + node.statements = createNodeArray(statements); + return node; + } + ts.createCaseClause = createCaseClause; + function updateCaseClause(node, expression, statements) { + return node.expression !== expression + || node.statements !== statements + ? updateNode(createCaseClause(expression, statements), node) + : node; + } + ts.updateCaseClause = updateCaseClause; + function createDefaultClause(statements) { + var node = createSynthesizedNode(272 /* DefaultClause */); + node.statements = createNodeArray(statements); + return node; + } + ts.createDefaultClause = createDefaultClause; + function updateDefaultClause(node, statements) { + return node.statements !== statements + ? updateNode(createDefaultClause(statements), node) + : node; + } + ts.updateDefaultClause = updateDefaultClause; + function createHeritageClause(token, types) { + var node = createSynthesizedNode(273 /* HeritageClause */); + node.token = token; + node.types = createNodeArray(types); + return node; + } + ts.createHeritageClause = createHeritageClause; + function updateHeritageClause(node, types) { + return node.types !== types + ? updateNode(createHeritageClause(node.token, types), node) + : node; + } + ts.updateHeritageClause = updateHeritageClause; + function createCatchClause(variableDeclaration, block) { + var node = createSynthesizedNode(274 /* CatchClause */); + node.variableDeclaration = ts.isString(variableDeclaration) ? createVariableDeclaration(variableDeclaration) : variableDeclaration; + node.block = block; + return node; + } + ts.createCatchClause = createCatchClause; + function updateCatchClause(node, variableDeclaration, block) { + return node.variableDeclaration !== variableDeclaration + || node.block !== block + ? updateNode(createCatchClause(variableDeclaration, block), node) + : node; + } + ts.updateCatchClause = updateCatchClause; + // Property assignments + function createPropertyAssignment(name, initializer) { + var node = createSynthesizedNode(275 /* PropertyAssignment */); + node.name = asName(name); + node.questionToken = undefined; + node.initializer = ts.parenthesizeExpressionForList(initializer); + return node; + } + ts.createPropertyAssignment = createPropertyAssignment; + function updatePropertyAssignment(node, name, initializer) { + return node.name !== name + || node.initializer !== initializer + ? updateNode(createPropertyAssignment(name, initializer), node) + : node; + } + ts.updatePropertyAssignment = updatePropertyAssignment; + function createShorthandPropertyAssignment(name, objectAssignmentInitializer) { + var node = createSynthesizedNode(276 /* ShorthandPropertyAssignment */); + node.name = asName(name); + node.objectAssignmentInitializer = objectAssignmentInitializer !== undefined ? ts.parenthesizeExpressionForList(objectAssignmentInitializer) : undefined; + return node; + } + ts.createShorthandPropertyAssignment = createShorthandPropertyAssignment; + function updateShorthandPropertyAssignment(node, name, objectAssignmentInitializer) { + return node.name !== name + || node.objectAssignmentInitializer !== objectAssignmentInitializer + ? updateNode(createShorthandPropertyAssignment(name, objectAssignmentInitializer), node) + : node; + } + ts.updateShorthandPropertyAssignment = updateShorthandPropertyAssignment; + function createSpreadAssignment(expression) { + var node = createSynthesizedNode(277 /* SpreadAssignment */); + node.expression = expression !== undefined ? ts.parenthesizeExpressionForList(expression) : undefined; // TODO: GH#18217 + return node; + } + ts.createSpreadAssignment = createSpreadAssignment; + function updateSpreadAssignment(node, expression) { + return node.expression !== expression + ? updateNode(createSpreadAssignment(expression), node) + : node; + } + ts.updateSpreadAssignment = updateSpreadAssignment; + // Enum + function createEnumMember(name, initializer) { + var node = createSynthesizedNode(278 /* EnumMember */); + node.name = asName(name); + node.initializer = initializer && ts.parenthesizeExpressionForList(initializer); + return node; + } + ts.createEnumMember = createEnumMember; + function updateEnumMember(node, name, initializer) { + return node.name !== name + || node.initializer !== initializer + ? updateNode(createEnumMember(name, initializer), node) + : node; + } + ts.updateEnumMember = updateEnumMember; + // Top-level nodes + function updateSourceFileNode(node, statements, isDeclarationFile, referencedFiles, typeReferences, hasNoDefaultLib, libReferences) { + if (node.statements !== statements || + (isDeclarationFile !== undefined && node.isDeclarationFile !== isDeclarationFile) || + (referencedFiles !== undefined && node.referencedFiles !== referencedFiles) || + (typeReferences !== undefined && node.typeReferenceDirectives !== typeReferences) || + (libReferences !== undefined && node.libReferenceDirectives !== libReferences) || + (hasNoDefaultLib !== undefined && node.hasNoDefaultLib !== hasNoDefaultLib)) { + var updated = createSynthesizedNode(279 /* SourceFile */); + updated.flags |= node.flags; + updated.statements = createNodeArray(statements); + updated.endOfFileToken = node.endOfFileToken; + updated.fileName = node.fileName; + updated.path = node.path; + updated.text = node.text; + updated.isDeclarationFile = isDeclarationFile === undefined ? node.isDeclarationFile : isDeclarationFile; + updated.referencedFiles = referencedFiles === undefined ? node.referencedFiles : referencedFiles; + updated.typeReferenceDirectives = typeReferences === undefined ? node.typeReferenceDirectives : typeReferences; + updated.hasNoDefaultLib = hasNoDefaultLib === undefined ? node.hasNoDefaultLib : hasNoDefaultLib; + updated.libReferenceDirectives = libReferences === undefined ? node.libReferenceDirectives : libReferences; + if (node.amdDependencies !== undefined) + updated.amdDependencies = node.amdDependencies; + if (node.moduleName !== undefined) + updated.moduleName = node.moduleName; + if (node.languageVariant !== undefined) + updated.languageVariant = node.languageVariant; + if (node.renamedDependencies !== undefined) + updated.renamedDependencies = node.renamedDependencies; + if (node.languageVersion !== undefined) + updated.languageVersion = node.languageVersion; + if (node.scriptKind !== undefined) + updated.scriptKind = node.scriptKind; + if (node.externalModuleIndicator !== undefined) + updated.externalModuleIndicator = node.externalModuleIndicator; + if (node.commonJsModuleIndicator !== undefined) + updated.commonJsModuleIndicator = node.commonJsModuleIndicator; + if (node.identifiers !== undefined) + updated.identifiers = node.identifiers; + if (node.nodeCount !== undefined) + updated.nodeCount = node.nodeCount; + if (node.identifierCount !== undefined) + updated.identifierCount = node.identifierCount; + if (node.symbolCount !== undefined) + updated.symbolCount = node.symbolCount; + if (node.parseDiagnostics !== undefined) + updated.parseDiagnostics = node.parseDiagnostics; + if (node.bindDiagnostics !== undefined) + updated.bindDiagnostics = node.bindDiagnostics; + if (node.bindSuggestionDiagnostics !== undefined) + updated.bindSuggestionDiagnostics = node.bindSuggestionDiagnostics; + if (node.lineMap !== undefined) + updated.lineMap = node.lineMap; + if (node.classifiableNames !== undefined) + updated.classifiableNames = node.classifiableNames; + if (node.resolvedModules !== undefined) + updated.resolvedModules = node.resolvedModules; + if (node.resolvedTypeReferenceDirectiveNames !== undefined) + updated.resolvedTypeReferenceDirectiveNames = node.resolvedTypeReferenceDirectiveNames; + if (node.imports !== undefined) + updated.imports = node.imports; + if (node.moduleAugmentations !== undefined) + updated.moduleAugmentations = node.moduleAugmentations; + if (node.pragmas !== undefined) + updated.pragmas = node.pragmas; + if (node.localJsxFactory !== undefined) + updated.localJsxFactory = node.localJsxFactory; + if (node.localJsxNamespace !== undefined) + updated.localJsxNamespace = node.localJsxNamespace; + return updateNode(updated, node); + } + return node; + } + ts.updateSourceFileNode = updateSourceFileNode; + /** + * Creates a shallow, memberwise clone of a node for mutation. + */ + function getMutableClone(node) { + var clone = getSynthesizedClone(node); + clone.pos = node.pos; + clone.end = node.end; + clone.parent = node.parent; + return clone; + } + ts.getMutableClone = getMutableClone; + // Transformation nodes + /** + * Creates a synthetic statement to act as a placeholder for a not-emitted statement in + * order to preserve comments. + * + * @param original The original statement. + */ + function createNotEmittedStatement(original) { + var node = createSynthesizedNode(307 /* NotEmittedStatement */); + node.original = original; + setTextRange(node, original); + return node; + } + ts.createNotEmittedStatement = createNotEmittedStatement; + /** + * Creates a synthetic element to act as a placeholder for the end of an emitted declaration in + * order to properly emit exports. + */ + /* @internal */ + function createEndOfDeclarationMarker(original) { + var node = createSynthesizedNode(311 /* EndOfDeclarationMarker */); + node.emitNode = {}; + node.original = original; + return node; + } + ts.createEndOfDeclarationMarker = createEndOfDeclarationMarker; + /** + * Creates a synthetic element to act as a placeholder for the beginning of a merged declaration in + * order to properly emit exports. + */ + /* @internal */ + function createMergeDeclarationMarker(original) { + var node = createSynthesizedNode(310 /* MergeDeclarationMarker */); + node.emitNode = {}; + node.original = original; + return node; + } + ts.createMergeDeclarationMarker = createMergeDeclarationMarker; + /** + * Creates a synthetic expression to act as a placeholder for a not-emitted expression in + * order to preserve comments or sourcemap positions. + * + * @param expression The inner expression to emit. + * @param original The original outer expression. + * @param location The location for the expression. Defaults to the positions from "original" if provided. + */ + function createPartiallyEmittedExpression(expression, original) { + var node = createSynthesizedNode(308 /* PartiallyEmittedExpression */); + node.expression = expression; + node.original = original; + setTextRange(node, original); + return node; + } + ts.createPartiallyEmittedExpression = createPartiallyEmittedExpression; + function updatePartiallyEmittedExpression(node, expression) { + if (node.expression !== expression) { + return updateNode(createPartiallyEmittedExpression(expression, node.original), node); + } + return node; + } + ts.updatePartiallyEmittedExpression = updatePartiallyEmittedExpression; + function flattenCommaElements(node) { + if (ts.nodeIsSynthesized(node) && !ts.isParseTreeNode(node) && !node.original && !node.emitNode && !node.id) { + if (node.kind === 309 /* CommaListExpression */) { + return node.elements; + } + if (ts.isBinaryExpression(node) && node.operatorToken.kind === 27 /* CommaToken */) { + return [node.left, node.right]; + } + } + return node; + } + function createCommaList(elements) { + var node = createSynthesizedNode(309 /* CommaListExpression */); + node.elements = createNodeArray(ts.sameFlatMap(elements, flattenCommaElements)); + return node; + } + ts.createCommaList = createCommaList; + function updateCommaList(node, elements) { + return node.elements !== elements + ? updateNode(createCommaList(elements), node) + : node; + } + ts.updateCommaList = updateCommaList; + function createBundle(sourceFiles, prepends) { + if (prepends === void 0) { prepends = ts.emptyArray; } + var node = ts.createNode(280 /* Bundle */); + node.prepends = prepends; + node.sourceFiles = sourceFiles; + return node; + } + ts.createBundle = createBundle; + function createUnparsedSourceFile(text, mapPath, map) { + var node = ts.createNode(281 /* UnparsedSource */); + node.text = text; + node.sourceMapPath = mapPath; + node.sourceMapText = map; + return node; + } + ts.createUnparsedSourceFile = createUnparsedSourceFile; + function createInputFiles(javascript, declaration, javascriptMapPath, javascriptMapText, declarationMapPath, declarationMapText) { + var node = ts.createNode(282 /* InputFiles */); + node.javascriptText = javascript; + node.javascriptMapPath = javascriptMapPath; + node.javascriptMapText = javascriptMapText; + node.declarationText = declaration; + node.declarationMapPath = declarationMapPath; + node.declarationMapText = declarationMapText; + return node; + } + ts.createInputFiles = createInputFiles; + function updateBundle(node, sourceFiles, prepends) { + if (prepends === void 0) { prepends = ts.emptyArray; } + if (node.sourceFiles !== sourceFiles || node.prepends !== prepends) { + return createBundle(sourceFiles, prepends); + } + return node; + } + ts.updateBundle = updateBundle; + function createImmediatelyInvokedFunctionExpression(statements, param, paramValue) { + return createCall(createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, + /*parameters*/ param ? [param] : [], + /*type*/ undefined, createBlock(statements, /*multiLine*/ true)), + /*typeArguments*/ undefined, + /*argumentsArray*/ paramValue ? [paramValue] : []); + } + ts.createImmediatelyInvokedFunctionExpression = createImmediatelyInvokedFunctionExpression; + function createImmediatelyInvokedArrowFunction(statements, param, paramValue) { + return createCall(createArrowFunction( + /*modifiers*/ undefined, + /*typeParameters*/ undefined, + /*parameters*/ param ? [param] : [], + /*type*/ undefined, + /*equalsGreaterThanToken*/ undefined, createBlock(statements, /*multiLine*/ true)), + /*typeArguments*/ undefined, + /*argumentsArray*/ paramValue ? [paramValue] : []); + } + ts.createImmediatelyInvokedArrowFunction = createImmediatelyInvokedArrowFunction; + function createComma(left, right) { + return createBinary(left, 27 /* CommaToken */, right); + } + ts.createComma = createComma; + function createLessThan(left, right) { + return createBinary(left, 28 /* LessThanToken */, right); + } + ts.createLessThan = createLessThan; + function createAssignment(left, right) { + return createBinary(left, 59 /* EqualsToken */, right); + } + ts.createAssignment = createAssignment; + function createStrictEquality(left, right) { + return createBinary(left, 35 /* EqualsEqualsEqualsToken */, right); + } + ts.createStrictEquality = createStrictEquality; + function createStrictInequality(left, right) { + return createBinary(left, 36 /* ExclamationEqualsEqualsToken */, right); + } + ts.createStrictInequality = createStrictInequality; + function createAdd(left, right) { + return createBinary(left, 38 /* PlusToken */, right); + } + ts.createAdd = createAdd; + function createSubtract(left, right) { + return createBinary(left, 39 /* MinusToken */, right); + } + ts.createSubtract = createSubtract; + function createPostfixIncrement(operand) { + return createPostfix(operand, 44 /* PlusPlusToken */); + } + ts.createPostfixIncrement = createPostfixIncrement; + function createLogicalAnd(left, right) { + return createBinary(left, 54 /* AmpersandAmpersandToken */, right); + } + ts.createLogicalAnd = createLogicalAnd; + function createLogicalOr(left, right) { + return createBinary(left, 55 /* BarBarToken */, right); + } + ts.createLogicalOr = createLogicalOr; + function createLogicalNot(operand) { + return createPrefix(52 /* ExclamationToken */, operand); + } + ts.createLogicalNot = createLogicalNot; + function createVoidZero() { + return createVoid(createLiteral(0)); + } + ts.createVoidZero = createVoidZero; + function createExportDefault(expression) { + return createExportAssignment(/*decorators*/ undefined, /*modifiers*/ undefined, /*isExportEquals*/ false, expression); + } + ts.createExportDefault = createExportDefault; + function createExternalModuleExport(exportName) { + return createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, createNamedExports([createExportSpecifier(/*propertyName*/ undefined, exportName)])); + } + ts.createExternalModuleExport = createExternalModuleExport; + // Utilities + function asName(name) { + return ts.isString(name) ? createIdentifier(name) : name; + } + function asExpression(value) { + return ts.isString(value) || typeof value === "number" ? createLiteral(value) : value; + } + function asNodeArray(array) { + return array ? createNodeArray(array) : undefined; + } + function asToken(value) { + return typeof value === "number" ? createToken(value) : value; + } + /** + * Clears any EmitNode entries from parse-tree nodes. + * @param sourceFile A source file. + */ + function disposeEmitNodes(sourceFile) { + // During transformation we may need to annotate a parse tree node with transient + // transformation properties. As parse tree nodes live longer than transformation + // nodes, we need to make sure we reclaim any memory allocated for custom ranges + // from these nodes to ensure we do not hold onto entire subtrees just for position + // information. We also need to reset these nodes to a pre-transformation state + // for incremental parsing scenarios so that we do not impact later emit. + sourceFile = ts.getSourceFileOfNode(ts.getParseTreeNode(sourceFile)); + var emitNode = sourceFile && sourceFile.emitNode; + var annotatedNodes = emitNode && emitNode.annotatedNodes; + if (annotatedNodes) { + for (var _i = 0, annotatedNodes_1 = annotatedNodes; _i < annotatedNodes_1.length; _i++) { + var node = annotatedNodes_1[_i]; + node.emitNode = undefined; + } + } + } + ts.disposeEmitNodes = disposeEmitNodes; + /** + * Associates a node with the current transformation, initializing + * various transient transformation properties. + */ + /* @internal */ + function getOrCreateEmitNode(node) { + if (!node.emitNode) { + if (ts.isParseTreeNode(node)) { + // To avoid holding onto transformation artifacts, we keep track of any + // parse tree node we are annotating. This allows us to clean them up after + // all transformations have completed. + if (node.kind === 279 /* SourceFile */) { + return node.emitNode = { annotatedNodes: [node] }; + } + var sourceFile = ts.getSourceFileOfNode(node); + getOrCreateEmitNode(sourceFile).annotatedNodes.push(node); + } + node.emitNode = {}; + } + return node.emitNode; + } + ts.getOrCreateEmitNode = getOrCreateEmitNode; + function setTextRange(range, location) { + if (location) { + range.pos = location.pos; + range.end = location.end; + } + return range; + } + ts.setTextRange = setTextRange; + /** + * Sets flags that control emit behavior of a node. + */ + function setEmitFlags(node, emitFlags) { + getOrCreateEmitNode(node).flags = emitFlags; + return node; + } + ts.setEmitFlags = setEmitFlags; + /** + * Sets flags that control emit behavior of a node. + */ + /* @internal */ + function addEmitFlags(node, emitFlags) { + var emitNode = getOrCreateEmitNode(node); + emitNode.flags = emitNode.flags | emitFlags; + return node; + } + ts.addEmitFlags = addEmitFlags; + /** + * Gets a custom text range to use when emitting source maps. + */ + function getSourceMapRange(node) { + var emitNode = node.emitNode; + return (emitNode && emitNode.sourceMapRange) || node; + } + ts.getSourceMapRange = getSourceMapRange; + /** + * Sets a custom text range to use when emitting source maps. + */ + function setSourceMapRange(node, range) { + getOrCreateEmitNode(node).sourceMapRange = range; + return node; + } + ts.setSourceMapRange = setSourceMapRange; + // tslint:disable-next-line variable-name + var SourceMapSource; + /** + * Create an external source map source file reference + */ + function createSourceMapSource(fileName, text, skipTrivia) { + return new (SourceMapSource || (SourceMapSource = ts.objectAllocator.getSourceMapSourceConstructor()))(fileName, text, skipTrivia); + } + ts.createSourceMapSource = createSourceMapSource; + /** + * Gets the TextRange to use for source maps for a token of a node. + */ + function getTokenSourceMapRange(node, token) { + var emitNode = node.emitNode; + var tokenSourceMapRanges = emitNode && emitNode.tokenSourceMapRanges; + return tokenSourceMapRanges && tokenSourceMapRanges[token]; + } + ts.getTokenSourceMapRange = getTokenSourceMapRange; + /** + * Sets the TextRange to use for source maps for a token of a node. + */ + function setTokenSourceMapRange(node, token, range) { + var emitNode = getOrCreateEmitNode(node); + var tokenSourceMapRanges = emitNode.tokenSourceMapRanges || (emitNode.tokenSourceMapRanges = []); + tokenSourceMapRanges[token] = range; + return node; + } + ts.setTokenSourceMapRange = setTokenSourceMapRange; + /** + * Gets a custom text range to use when emitting comments. + */ + /*@internal*/ + function getStartsOnNewLine(node) { + var emitNode = node.emitNode; + return emitNode && emitNode.startsOnNewLine; + } + ts.getStartsOnNewLine = getStartsOnNewLine; + /** + * Sets a custom text range to use when emitting comments. + */ + /*@internal*/ + function setStartsOnNewLine(node, newLine) { + getOrCreateEmitNode(node).startsOnNewLine = newLine; + return node; + } + ts.setStartsOnNewLine = setStartsOnNewLine; + /** + * Gets a custom text range to use when emitting comments. + */ + function getCommentRange(node) { + var emitNode = node.emitNode; + return (emitNode && emitNode.commentRange) || node; + } + ts.getCommentRange = getCommentRange; + /** + * Sets a custom text range to use when emitting comments. + */ + function setCommentRange(node, range) { + getOrCreateEmitNode(node).commentRange = range; + return node; + } + ts.setCommentRange = setCommentRange; + function getSyntheticLeadingComments(node) { + var emitNode = node.emitNode; + return emitNode && emitNode.leadingComments; + } + ts.getSyntheticLeadingComments = getSyntheticLeadingComments; + function setSyntheticLeadingComments(node, comments) { + getOrCreateEmitNode(node).leadingComments = comments; + return node; + } + ts.setSyntheticLeadingComments = setSyntheticLeadingComments; + function addSyntheticLeadingComment(node, kind, text, hasTrailingNewLine) { + return setSyntheticLeadingComments(node, ts.append(getSyntheticLeadingComments(node), { kind: kind, pos: -1, end: -1, hasTrailingNewLine: hasTrailingNewLine, text: text })); + } + ts.addSyntheticLeadingComment = addSyntheticLeadingComment; + function getSyntheticTrailingComments(node) { + var emitNode = node.emitNode; + return emitNode && emitNode.trailingComments; + } + ts.getSyntheticTrailingComments = getSyntheticTrailingComments; + function setSyntheticTrailingComments(node, comments) { + getOrCreateEmitNode(node).trailingComments = comments; + return node; + } + ts.setSyntheticTrailingComments = setSyntheticTrailingComments; + function addSyntheticTrailingComment(node, kind, text, hasTrailingNewLine) { + return setSyntheticTrailingComments(node, ts.append(getSyntheticTrailingComments(node), { kind: kind, pos: -1, end: -1, hasTrailingNewLine: hasTrailingNewLine, text: text })); + } + ts.addSyntheticTrailingComment = addSyntheticTrailingComment; + function moveSyntheticComments(node, original) { + setSyntheticLeadingComments(node, getSyntheticLeadingComments(original)); + setSyntheticTrailingComments(node, getSyntheticTrailingComments(original)); + var emit = getOrCreateEmitNode(original); + emit.leadingComments = undefined; + emit.trailingComments = undefined; + return node; + } + ts.moveSyntheticComments = moveSyntheticComments; + /** + * Gets the constant value to emit for an expression. + */ + function getConstantValue(node) { + var emitNode = node.emitNode; + return emitNode && emitNode.constantValue; + } + ts.getConstantValue = getConstantValue; + /** + * Sets the constant value to emit for an expression. + */ + function setConstantValue(node, value) { + var emitNode = getOrCreateEmitNode(node); + emitNode.constantValue = value; + return node; + } + ts.setConstantValue = setConstantValue; + /** + * Adds an EmitHelper to a node. + */ + function addEmitHelper(node, helper) { + var emitNode = getOrCreateEmitNode(node); + emitNode.helpers = ts.append(emitNode.helpers, helper); + return node; + } + ts.addEmitHelper = addEmitHelper; + /** + * Add EmitHelpers to a node. + */ + function addEmitHelpers(node, helpers) { + if (ts.some(helpers)) { + var emitNode = getOrCreateEmitNode(node); + for (var _i = 0, helpers_1 = helpers; _i < helpers_1.length; _i++) { + var helper = helpers_1[_i]; + emitNode.helpers = ts.appendIfUnique(emitNode.helpers, helper); + } + } + return node; + } + ts.addEmitHelpers = addEmitHelpers; + /** + * Removes an EmitHelper from a node. + */ + function removeEmitHelper(node, helper) { + var emitNode = node.emitNode; + if (emitNode) { + var helpers = emitNode.helpers; + if (helpers) { + return ts.orderedRemoveItem(helpers, helper); + } + } + return false; + } + ts.removeEmitHelper = removeEmitHelper; + /** + * Gets the EmitHelpers of a node. + */ + function getEmitHelpers(node) { + var emitNode = node.emitNode; + return emitNode && emitNode.helpers; + } + ts.getEmitHelpers = getEmitHelpers; + /** + * Moves matching emit helpers from a source node to a target node. + */ + function moveEmitHelpers(source, target, predicate) { + var sourceEmitNode = source.emitNode; + var sourceEmitHelpers = sourceEmitNode && sourceEmitNode.helpers; + if (!ts.some(sourceEmitHelpers)) + return; + var targetEmitNode = getOrCreateEmitNode(target); + var helpersRemoved = 0; + for (var i = 0; i < sourceEmitHelpers.length; i++) { + var helper = sourceEmitHelpers[i]; + if (predicate(helper)) { + helpersRemoved++; + targetEmitNode.helpers = ts.appendIfUnique(targetEmitNode.helpers, helper); + } + else if (helpersRemoved > 0) { + sourceEmitHelpers[i - helpersRemoved] = helper; + } + } + if (helpersRemoved > 0) { + sourceEmitHelpers.length -= helpersRemoved; + } + } + ts.moveEmitHelpers = moveEmitHelpers; + /* @internal */ + function compareEmitHelpers(x, y) { + if (x === y) + return 0 /* EqualTo */; + if (x.priority === y.priority) + return 0 /* EqualTo */; + if (x.priority === undefined) + return 1 /* GreaterThan */; + if (y.priority === undefined) + return -1 /* LessThan */; + return ts.compareValues(x.priority, y.priority); + } + ts.compareEmitHelpers = compareEmitHelpers; + function setOriginalNode(node, original) { + node.original = original; + if (original) { + var emitNode = original.emitNode; + if (emitNode) + node.emitNode = mergeEmitNode(emitNode, node.emitNode); + } + return node; + } + ts.setOriginalNode = setOriginalNode; + function mergeEmitNode(sourceEmitNode, destEmitNode) { + var flags = sourceEmitNode.flags, leadingComments = sourceEmitNode.leadingComments, trailingComments = sourceEmitNode.trailingComments, commentRange = sourceEmitNode.commentRange, sourceMapRange = sourceEmitNode.sourceMapRange, tokenSourceMapRanges = sourceEmitNode.tokenSourceMapRanges, constantValue = sourceEmitNode.constantValue, helpers = sourceEmitNode.helpers, startsOnNewLine = sourceEmitNode.startsOnNewLine; + if (!destEmitNode) + destEmitNode = {}; + // We are using `.slice()` here in case `destEmitNode.leadingComments` is pushed to later. + if (leadingComments) + destEmitNode.leadingComments = ts.addRange(leadingComments.slice(), destEmitNode.leadingComments); + if (trailingComments) + destEmitNode.trailingComments = ts.addRange(trailingComments.slice(), destEmitNode.trailingComments); + if (flags) + destEmitNode.flags = flags; + if (commentRange) + destEmitNode.commentRange = commentRange; + if (sourceMapRange) + destEmitNode.sourceMapRange = sourceMapRange; + if (tokenSourceMapRanges) + destEmitNode.tokenSourceMapRanges = mergeTokenSourceMapRanges(tokenSourceMapRanges, destEmitNode.tokenSourceMapRanges); + if (constantValue !== undefined) + destEmitNode.constantValue = constantValue; + if (helpers) + destEmitNode.helpers = ts.addRange(destEmitNode.helpers, helpers); + if (startsOnNewLine !== undefined) + destEmitNode.startsOnNewLine = startsOnNewLine; + return destEmitNode; + } + function mergeTokenSourceMapRanges(sourceRanges, destRanges) { + if (!destRanges) + destRanges = []; + for (var key in sourceRanges) { + destRanges[key] = sourceRanges[key]; + } + return destRanges; + } +})(ts || (ts = {})); +/* @internal */ +(function (ts) { + ts.nullTransformationContext = { + enableEmitNotification: ts.noop, + enableSubstitution: ts.noop, + endLexicalEnvironment: function () { return undefined; }, + getCompilerOptions: ts.notImplemented, + getEmitHost: ts.notImplemented, + getEmitResolver: ts.notImplemented, + hoistFunctionDeclaration: ts.noop, + hoistVariableDeclaration: ts.noop, + isEmitNotificationEnabled: ts.notImplemented, + isSubstitutionEnabled: ts.notImplemented, + onEmitNode: ts.noop, + onSubstituteNode: ts.notImplemented, + readEmitHelpers: ts.notImplemented, + requestEmitHelper: ts.noop, + resumeLexicalEnvironment: ts.noop, + startLexicalEnvironment: ts.noop, + suspendLexicalEnvironment: ts.noop, + addDiagnostic: ts.noop, + }; + function createTypeCheck(value, tag) { + return tag === "undefined" + ? ts.createStrictEquality(value, ts.createVoidZero()) + : ts.createStrictEquality(ts.createTypeOf(value), ts.createLiteral(tag)); + } + ts.createTypeCheck = createTypeCheck; + function createMemberAccessForPropertyName(target, memberName, location) { + if (ts.isComputedPropertyName(memberName)) { + return ts.setTextRange(ts.createElementAccess(target, memberName.expression), location); + } + else { + var expression = ts.setTextRange(ts.isIdentifier(memberName) + ? ts.createPropertyAccess(target, memberName) + : ts.createElementAccess(target, memberName), memberName); + ts.getOrCreateEmitNode(expression).flags |= 64 /* NoNestedSourceMaps */; + return expression; + } + } + ts.createMemberAccessForPropertyName = createMemberAccessForPropertyName; + function createFunctionCall(func, thisArg, argumentsList, location) { + return ts.setTextRange(ts.createCall(ts.createPropertyAccess(func, "call"), + /*typeArguments*/ undefined, [ + thisArg + ].concat(argumentsList)), location); + } + ts.createFunctionCall = createFunctionCall; + function createFunctionApply(func, thisArg, argumentsExpression, location) { + return ts.setTextRange(ts.createCall(ts.createPropertyAccess(func, "apply"), + /*typeArguments*/ undefined, [ + thisArg, + argumentsExpression + ]), location); + } + ts.createFunctionApply = createFunctionApply; + function createArraySlice(array, start) { + var argumentsList = []; + if (start !== undefined) { + argumentsList.push(typeof start === "number" ? ts.createLiteral(start) : start); + } + return ts.createCall(ts.createPropertyAccess(array, "slice"), /*typeArguments*/ undefined, argumentsList); + } + ts.createArraySlice = createArraySlice; + function createArrayConcat(array, values) { + return ts.createCall(ts.createPropertyAccess(array, "concat"), + /*typeArguments*/ undefined, values); + } + ts.createArrayConcat = createArrayConcat; + function createMathPow(left, right, location) { + return ts.setTextRange(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Math"), "pow"), + /*typeArguments*/ undefined, [left, right]), location); + } + ts.createMathPow = createMathPow; + function createReactNamespace(reactNamespace, parent) { + // To ensure the emit resolver can properly resolve the namespace, we need to + // treat this identifier as if it were a source tree node by clearing the `Synthesized` + // flag and setting a parent node. + var react = ts.createIdentifier(reactNamespace || "React"); + react.flags &= ~8 /* Synthesized */; + // Set the parent that is in parse tree + // this makes sure that parent chain is intact for checker to traverse complete scope tree + react.parent = ts.getParseTreeNode(parent); + return react; + } + function createJsxFactoryExpressionFromEntityName(jsxFactory, parent) { + if (ts.isQualifiedName(jsxFactory)) { + var left = createJsxFactoryExpressionFromEntityName(jsxFactory.left, parent); + var right = ts.createIdentifier(ts.idText(jsxFactory.right)); + right.escapedText = jsxFactory.right.escapedText; + return ts.createPropertyAccess(left, right); + } + else { + return createReactNamespace(ts.idText(jsxFactory), parent); + } + } + function createJsxFactoryExpression(jsxFactoryEntity, reactNamespace, parent) { + return jsxFactoryEntity ? + createJsxFactoryExpressionFromEntityName(jsxFactoryEntity, parent) : + ts.createPropertyAccess(createReactNamespace(reactNamespace, parent), "createElement"); + } + function createExpressionForJsxElement(jsxFactoryEntity, reactNamespace, tagName, props, children, parentElement, location) { + var argumentsList = [tagName]; + if (props) { + argumentsList.push(props); + } + if (children && children.length > 0) { + if (!props) { + argumentsList.push(ts.createNull()); + } + if (children.length > 1) { + for (var _i = 0, children_1 = children; _i < children_1.length; _i++) { + var child = children_1[_i]; + startOnNewLine(child); + argumentsList.push(child); + } + } + else { + argumentsList.push(children[0]); + } + } + return ts.setTextRange(ts.createCall(createJsxFactoryExpression(jsxFactoryEntity, reactNamespace, parentElement), + /*typeArguments*/ undefined, argumentsList), location); + } + ts.createExpressionForJsxElement = createExpressionForJsxElement; + function createExpressionForJsxFragment(jsxFactoryEntity, reactNamespace, children, parentElement, location) { + var tagName = ts.createPropertyAccess(createReactNamespace(reactNamespace, parentElement), "Fragment"); + var argumentsList = [tagName]; + argumentsList.push(ts.createNull()); + if (children && children.length > 0) { + if (children.length > 1) { + for (var _i = 0, children_2 = children; _i < children_2.length; _i++) { + var child = children_2[_i]; + startOnNewLine(child); + argumentsList.push(child); + } + } + else { + argumentsList.push(children[0]); + } + } + return ts.setTextRange(ts.createCall(createJsxFactoryExpression(jsxFactoryEntity, reactNamespace, parentElement), + /*typeArguments*/ undefined, argumentsList), location); + } + ts.createExpressionForJsxFragment = createExpressionForJsxFragment; + // Helpers + function getHelperName(name) { + return ts.setEmitFlags(ts.createIdentifier(name), 4096 /* HelperName */ | 2 /* AdviseOnEmitNode */); + } + ts.getHelperName = getHelperName; + var valuesHelper = { + name: "typescript:values", + scoped: false, + text: "\n var __values = (this && this.__values) || function (o) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator], i = 0;\n if (m) return m.call(o);\n return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n };" + }; + function createValuesHelper(context, expression, location) { + context.requestEmitHelper(valuesHelper); + return ts.setTextRange(ts.createCall(getHelperName("__values"), + /*typeArguments*/ undefined, [expression]), location); + } + ts.createValuesHelper = createValuesHelper; + var readHelper = { + name: "typescript:read", + scoped: false, + text: "\n var __read = (this && this.__read) || function (o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m) return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n }\n catch (error) { e = { error: error }; }\n finally {\n try {\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\n }\n finally { if (e) throw e.error; }\n }\n return ar;\n };" + }; + function createReadHelper(context, iteratorRecord, count, location) { + context.requestEmitHelper(readHelper); + return ts.setTextRange(ts.createCall(getHelperName("__read"), + /*typeArguments*/ undefined, count !== undefined + ? [iteratorRecord, ts.createLiteral(count)] + : [iteratorRecord]), location); + } + ts.createReadHelper = createReadHelper; + var spreadHelper = { + name: "typescript:spread", + scoped: false, + text: "\n var __spread = (this && this.__spread) || function () {\n for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i]));\n return ar;\n };" + }; + function createSpreadHelper(context, argumentList, location) { + context.requestEmitHelper(readHelper); + context.requestEmitHelper(spreadHelper); + return ts.setTextRange(ts.createCall(getHelperName("__spread"), + /*typeArguments*/ undefined, argumentList), location); + } + ts.createSpreadHelper = createSpreadHelper; + // Utilities + function createForOfBindingStatement(node, boundValue) { + if (ts.isVariableDeclarationList(node)) { + var firstDeclaration = ts.first(node.declarations); + var updatedDeclaration = ts.updateVariableDeclaration(firstDeclaration, firstDeclaration.name, + /*typeNode*/ undefined, boundValue); + return ts.setTextRange(ts.createVariableStatement( + /*modifiers*/ undefined, ts.updateVariableDeclarationList(node, [updatedDeclaration])), + /*location*/ node); + } + else { + var updatedExpression = ts.setTextRange(ts.createAssignment(node, boundValue), /*location*/ node); + return ts.setTextRange(ts.createStatement(updatedExpression), /*location*/ node); + } + } + ts.createForOfBindingStatement = createForOfBindingStatement; + function insertLeadingStatement(dest, source) { + if (ts.isBlock(dest)) { + return ts.updateBlock(dest, ts.setTextRange(ts.createNodeArray([source].concat(dest.statements)), dest.statements)); + } + else { + return ts.createBlock(ts.createNodeArray([dest, source]), /*multiLine*/ true); + } + } + ts.insertLeadingStatement = insertLeadingStatement; + function restoreEnclosingLabel(node, outermostLabeledStatement, afterRestoreLabelCallback) { + if (!outermostLabeledStatement) { + return node; + } + var updated = ts.updateLabel(outermostLabeledStatement, outermostLabeledStatement.label, outermostLabeledStatement.statement.kind === 233 /* LabeledStatement */ + ? restoreEnclosingLabel(node, outermostLabeledStatement.statement) + : node); + if (afterRestoreLabelCallback) { + afterRestoreLabelCallback(outermostLabeledStatement); + } + return updated; + } + ts.restoreEnclosingLabel = restoreEnclosingLabel; + function shouldBeCapturedInTempVariable(node, cacheIdentifiers) { + var target = ts.skipParentheses(node); + switch (target.kind) { + case 72 /* Identifier */: + return cacheIdentifiers; + case 100 /* ThisKeyword */: + case 8 /* NumericLiteral */: + case 9 /* BigIntLiteral */: + case 10 /* StringLiteral */: + return false; + case 187 /* ArrayLiteralExpression */: + var elements = target.elements; + if (elements.length === 0) { + return false; + } + return true; + case 188 /* ObjectLiteralExpression */: + return target.properties.length > 0; + default: + return true; + } + } + function createCallBinding(expression, recordTempVariable, languageVersion, cacheIdentifiers) { + if (cacheIdentifiers === void 0) { cacheIdentifiers = false; } + var callee = skipOuterExpressions(expression, 7 /* All */); + var thisArg; + var target; + if (ts.isSuperProperty(callee)) { + thisArg = ts.createThis(); + target = callee; + } + else if (callee.kind === 98 /* SuperKeyword */) { + thisArg = ts.createThis(); + target = languageVersion < 2 /* ES2015 */ + ? ts.setTextRange(ts.createIdentifier("_super"), callee) + : callee; + } + else if (ts.getEmitFlags(callee) & 4096 /* HelperName */) { + thisArg = ts.createVoidZero(); + target = parenthesizeForAccess(callee); + } + else { + switch (callee.kind) { + case 189 /* PropertyAccessExpression */: { + if (shouldBeCapturedInTempVariable(callee.expression, cacheIdentifiers)) { + // for `a.b()` target is `(_a = a).b` and thisArg is `_a` + thisArg = ts.createTempVariable(recordTempVariable); + target = ts.createPropertyAccess(ts.setTextRange(ts.createAssignment(thisArg, callee.expression), callee.expression), callee.name); + ts.setTextRange(target, callee); + } + else { + thisArg = callee.expression; + target = callee; + } + break; + } + case 190 /* ElementAccessExpression */: { + if (shouldBeCapturedInTempVariable(callee.expression, cacheIdentifiers)) { + // for `a[b]()` target is `(_a = a)[b]` and thisArg is `_a` + thisArg = ts.createTempVariable(recordTempVariable); + target = ts.createElementAccess(ts.setTextRange(ts.createAssignment(thisArg, callee.expression), callee.expression), callee.argumentExpression); + ts.setTextRange(target, callee); + } + else { + thisArg = callee.expression; + target = callee; + } + break; + } + default: { + // for `a()` target is `a` and thisArg is `void 0` + thisArg = ts.createVoidZero(); + target = parenthesizeForAccess(expression); + break; + } + } + } + return { target: target, thisArg: thisArg }; + } + ts.createCallBinding = createCallBinding; + function inlineExpressions(expressions) { + // Avoid deeply nested comma expressions as traversing them during emit can result in "Maximum call + // stack size exceeded" errors. + return expressions.length > 10 + ? ts.createCommaList(expressions) + : ts.reduceLeft(expressions, ts.createComma); + } + ts.inlineExpressions = inlineExpressions; + function createExpressionFromEntityName(node) { + if (ts.isQualifiedName(node)) { + var left = createExpressionFromEntityName(node.left); + var right = ts.getMutableClone(node.right); + return ts.setTextRange(ts.createPropertyAccess(left, right), node); + } + else { + return ts.getMutableClone(node); + } + } + ts.createExpressionFromEntityName = createExpressionFromEntityName; + function createExpressionForPropertyName(memberName) { + if (ts.isIdentifier(memberName)) { + return ts.createLiteral(memberName); + } + else if (ts.isComputedPropertyName(memberName)) { + return ts.getMutableClone(memberName.expression); + } + else { + return ts.getMutableClone(memberName); + } + } + ts.createExpressionForPropertyName = createExpressionForPropertyName; + function createExpressionForObjectLiteralElementLike(node, property, receiver) { + switch (property.kind) { + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + return createExpressionForAccessorDeclaration(node.properties, property, receiver, !!node.multiLine); + case 275 /* PropertyAssignment */: + return createExpressionForPropertyAssignment(property, receiver); + case 276 /* ShorthandPropertyAssignment */: + return createExpressionForShorthandPropertyAssignment(property, receiver); + case 156 /* MethodDeclaration */: + return createExpressionForMethodDeclaration(property, receiver); + } + } + ts.createExpressionForObjectLiteralElementLike = createExpressionForObjectLiteralElementLike; + function createExpressionForAccessorDeclaration(properties, property, receiver, multiLine) { + var _a = ts.getAllAccessorDeclarations(properties, property), firstAccessor = _a.firstAccessor, getAccessor = _a.getAccessor, setAccessor = _a.setAccessor; + if (property === firstAccessor) { + var properties_8 = []; + if (getAccessor) { + var getterFunction = ts.createFunctionExpression(getAccessor.modifiers, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, getAccessor.parameters, + /*type*/ undefined, getAccessor.body // TODO: GH#18217 + ); + ts.setTextRange(getterFunction, getAccessor); + ts.setOriginalNode(getterFunction, getAccessor); + var getter = ts.createPropertyAssignment("get", getterFunction); + properties_8.push(getter); + } + if (setAccessor) { + var setterFunction = ts.createFunctionExpression(setAccessor.modifiers, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, setAccessor.parameters, + /*type*/ undefined, setAccessor.body // TODO: GH#18217 + ); + ts.setTextRange(setterFunction, setAccessor); + ts.setOriginalNode(setterFunction, setAccessor); + var setter = ts.createPropertyAssignment("set", setterFunction); + properties_8.push(setter); + } + properties_8.push(ts.createPropertyAssignment("enumerable", ts.createTrue())); + properties_8.push(ts.createPropertyAssignment("configurable", ts.createTrue())); + var expression = ts.setTextRange(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"), + /*typeArguments*/ undefined, [ + receiver, + createExpressionForPropertyName(property.name), + ts.createObjectLiteral(properties_8, multiLine) + ]), + /*location*/ firstAccessor); + return ts.aggregateTransformFlags(expression); + } + return undefined; + } + function createExpressionForPropertyAssignment(property, receiver) { + return ts.aggregateTransformFlags(ts.setOriginalNode(ts.setTextRange(ts.createAssignment(createMemberAccessForPropertyName(receiver, property.name, /*location*/ property.name), property.initializer), property), property)); + } + function createExpressionForShorthandPropertyAssignment(property, receiver) { + return ts.aggregateTransformFlags(ts.setOriginalNode(ts.setTextRange(ts.createAssignment(createMemberAccessForPropertyName(receiver, property.name, /*location*/ property.name), ts.getSynthesizedClone(property.name)), + /*location*/ property), + /*original*/ property)); + } + function createExpressionForMethodDeclaration(method, receiver) { + return ts.aggregateTransformFlags(ts.setOriginalNode(ts.setTextRange(ts.createAssignment(createMemberAccessForPropertyName(receiver, method.name, /*location*/ method.name), ts.setOriginalNode(ts.setTextRange(ts.createFunctionExpression(method.modifiers, method.asteriskToken, + /*name*/ undefined, + /*typeParameters*/ undefined, method.parameters, + /*type*/ undefined, method.body // TODO: GH#18217 + ), + /*location*/ method), + /*original*/ method)), + /*location*/ method), + /*original*/ method)); + } + /** + * Gets the internal name of a declaration. This is primarily used for declarations that can be + * referred to by name in the body of an ES5 class function body. An internal name will *never* + * be prefixed with an module or namespace export modifier like "exports." when emitted as an + * expression. An internal name will also *never* be renamed due to a collision with a block + * scoped variable. + * + * @param node The declaration. + * @param allowComments A value indicating whether comments may be emitted for the name. + * @param allowSourceMaps A value indicating whether source maps may be emitted for the name. + */ + function getInternalName(node, allowComments, allowSourceMaps) { + return getName(node, allowComments, allowSourceMaps, 16384 /* LocalName */ | 32768 /* InternalName */); + } + ts.getInternalName = getInternalName; + /** + * Gets whether an identifier should only be referred to by its internal name. + */ + function isInternalName(node) { + return (ts.getEmitFlags(node) & 32768 /* InternalName */) !== 0; + } + ts.isInternalName = isInternalName; + /** + * Gets the local name of a declaration. This is primarily used for declarations that can be + * referred to by name in the declaration's immediate scope (classes, enums, namespaces). A + * local name will *never* be prefixed with an module or namespace export modifier like + * "exports." when emitted as an expression. + * + * @param node The declaration. + * @param allowComments A value indicating whether comments may be emitted for the name. + * @param allowSourceMaps A value indicating whether source maps may be emitted for the name. + */ + function getLocalName(node, allowComments, allowSourceMaps) { + return getName(node, allowComments, allowSourceMaps, 16384 /* LocalName */); + } + ts.getLocalName = getLocalName; + /** + * Gets whether an identifier should only be referred to by its local name. + */ + function isLocalName(node) { + return (ts.getEmitFlags(node) & 16384 /* LocalName */) !== 0; + } + ts.isLocalName = isLocalName; + /** + * Gets the export name of a declaration. This is primarily used for declarations that can be + * referred to by name in the declaration's immediate scope (classes, enums, namespaces). An + * export name will *always* be prefixed with an module or namespace export modifier like + * `"exports."` when emitted as an expression if the name points to an exported symbol. + * + * @param node The declaration. + * @param allowComments A value indicating whether comments may be emitted for the name. + * @param allowSourceMaps A value indicating whether source maps may be emitted for the name. + */ + function getExportName(node, allowComments, allowSourceMaps) { + return getName(node, allowComments, allowSourceMaps, 8192 /* ExportName */); + } + ts.getExportName = getExportName; + /** + * Gets whether an identifier should only be referred to by its export representation if the + * name points to an exported symbol. + */ + function isExportName(node) { + return (ts.getEmitFlags(node) & 8192 /* ExportName */) !== 0; + } + ts.isExportName = isExportName; + /** + * Gets the name of a declaration for use in declarations. + * + * @param node The declaration. + * @param allowComments A value indicating whether comments may be emitted for the name. + * @param allowSourceMaps A value indicating whether source maps may be emitted for the name. + */ + function getDeclarationName(node, allowComments, allowSourceMaps) { + return getName(node, allowComments, allowSourceMaps); + } + ts.getDeclarationName = getDeclarationName; + function getName(node, allowComments, allowSourceMaps, emitFlags) { + if (emitFlags === void 0) { emitFlags = 0; } + var nodeName = ts.getNameOfDeclaration(node); + if (nodeName && ts.isIdentifier(nodeName) && !ts.isGeneratedIdentifier(nodeName)) { + var name = ts.getMutableClone(nodeName); + emitFlags |= ts.getEmitFlags(nodeName); + if (!allowSourceMaps) + emitFlags |= 48 /* NoSourceMap */; + if (!allowComments) + emitFlags |= 1536 /* NoComments */; + if (emitFlags) + ts.setEmitFlags(name, emitFlags); + return name; + } + return ts.getGeneratedNameForNode(node); + } + /** + * Gets the exported name of a declaration for use in expressions. + * + * An exported name will *always* be prefixed with an module or namespace export modifier like + * "exports." if the name points to an exported symbol. + * + * @param ns The namespace identifier. + * @param node The declaration. + * @param allowComments A value indicating whether comments may be emitted for the name. + * @param allowSourceMaps A value indicating whether source maps may be emitted for the name. + */ + function getExternalModuleOrNamespaceExportName(ns, node, allowComments, allowSourceMaps) { + if (ns && ts.hasModifier(node, 1 /* Export */)) { + return getNamespaceMemberName(ns, getName(node), allowComments, allowSourceMaps); + } + return getExportName(node, allowComments, allowSourceMaps); + } + ts.getExternalModuleOrNamespaceExportName = getExternalModuleOrNamespaceExportName; + /** + * Gets a namespace-qualified name for use in expressions. + * + * @param ns The namespace identifier. + * @param name The name. + * @param allowComments A value indicating whether comments may be emitted for the name. + * @param allowSourceMaps A value indicating whether source maps may be emitted for the name. + */ + function getNamespaceMemberName(ns, name, allowComments, allowSourceMaps) { + var qualifiedName = ts.createPropertyAccess(ns, ts.nodeIsSynthesized(name) ? name : ts.getSynthesizedClone(name)); + ts.setTextRange(qualifiedName, name); + var emitFlags = 0; + if (!allowSourceMaps) + emitFlags |= 48 /* NoSourceMap */; + if (!allowComments) + emitFlags |= 1536 /* NoComments */; + if (emitFlags) + ts.setEmitFlags(qualifiedName, emitFlags); + return qualifiedName; + } + ts.getNamespaceMemberName = getNamespaceMemberName; + function convertToFunctionBody(node, multiLine) { + return ts.isBlock(node) ? node : ts.setTextRange(ts.createBlock([ts.setTextRange(ts.createReturn(node), node)], multiLine), node); + } + ts.convertToFunctionBody = convertToFunctionBody; + function convertFunctionDeclarationToExpression(node) { + if (!node.body) + return ts.Debug.fail(); + var updated = ts.createFunctionExpression(node.modifiers, node.asteriskToken, node.name, node.typeParameters, node.parameters, node.type, node.body); + ts.setOriginalNode(updated, node); + ts.setTextRange(updated, node); + if (ts.getStartsOnNewLine(node)) { + ts.setStartsOnNewLine(updated, /*newLine*/ true); + } + ts.aggregateTransformFlags(updated); + return updated; + } + ts.convertFunctionDeclarationToExpression = convertFunctionDeclarationToExpression; + function isUseStrictPrologue(node) { + return ts.isStringLiteral(node.expression) && node.expression.text === "use strict"; + } + /** + * Add any necessary prologue-directives into target statement-array. + * The function needs to be called during each transformation step. + * This function needs to be called whenever we transform the statement + * list of a source file, namespace, or function-like body. + * + * @param target: result statements array + * @param source: origin statements array + * @param ensureUseStrict: boolean determining whether the function need to add prologue-directives + * @param visitor: Optional callback used to visit any custom prologue directives. + */ + function addPrologue(target, source, ensureUseStrict, visitor) { + var offset = addStandardPrologue(target, source, ensureUseStrict); + return addCustomPrologue(target, source, offset, visitor); + } + ts.addPrologue = addPrologue; + /** + * Add just the standard (string-expression) prologue-directives into target statement-array. + * The function needs to be called during each transformation step. + * This function needs to be called whenever we transform the statement + * list of a source file, namespace, or function-like body. + */ + function addStandardPrologue(target, source, ensureUseStrict) { + ts.Debug.assert(target.length === 0, "Prologue directives should be at the first statement in the target statements array"); + var foundUseStrict = false; + var statementOffset = 0; + var numStatements = source.length; + while (statementOffset < numStatements) { + var statement = source[statementOffset]; + if (ts.isPrologueDirective(statement)) { + if (isUseStrictPrologue(statement)) { + foundUseStrict = true; + } + target.push(statement); + } + else { + break; + } + statementOffset++; + } + if (ensureUseStrict && !foundUseStrict) { + target.push(startOnNewLine(ts.createStatement(ts.createLiteral("use strict")))); + } + return statementOffset; + } + ts.addStandardPrologue = addStandardPrologue; + function addCustomPrologue(target, source, statementOffset, visitor) { + var numStatements = source.length; + while (statementOffset !== undefined && statementOffset < numStatements) { + var statement = source[statementOffset]; + if (ts.getEmitFlags(statement) & 1048576 /* CustomPrologue */) { + ts.append(target, visitor ? ts.visitNode(statement, visitor, ts.isStatement) : statement); + } + else { + break; + } + statementOffset++; + } + return statementOffset; + } + ts.addCustomPrologue = addCustomPrologue; + function findUseStrictPrologue(statements) { + for (var _i = 0, statements_3 = statements; _i < statements_3.length; _i++) { + var statement = statements_3[_i]; + if (ts.isPrologueDirective(statement)) { + if (isUseStrictPrologue(statement)) { + return statement; + } + } + else { + break; + } + } + return undefined; + } + ts.findUseStrictPrologue = findUseStrictPrologue; + function startsWithUseStrict(statements) { + var firstStatement = ts.firstOrUndefined(statements); + return firstStatement !== undefined + && ts.isPrologueDirective(firstStatement) + && isUseStrictPrologue(firstStatement); + } + ts.startsWithUseStrict = startsWithUseStrict; + /** + * Ensures "use strict" directive is added + * + * @param statements An array of statements + */ + function ensureUseStrict(statements) { + var foundUseStrict = findUseStrictPrologue(statements); + if (!foundUseStrict) { + return ts.setTextRange(ts.createNodeArray([ + startOnNewLine(ts.createStatement(ts.createLiteral("use strict"))) + ].concat(statements)), statements); + } + return statements; + } + ts.ensureUseStrict = ensureUseStrict; + /** + * Wraps the operand to a BinaryExpression in parentheses if they are needed to preserve the intended + * order of operations. + * + * @param binaryOperator The operator for the BinaryExpression. + * @param operand The operand for the BinaryExpression. + * @param isLeftSideOfBinary A value indicating whether the operand is the left side of the + * BinaryExpression. + */ + function parenthesizeBinaryOperand(binaryOperator, operand, isLeftSideOfBinary, leftOperand) { + var skipped = ts.skipPartiallyEmittedExpressions(operand); + // If the resulting expression is already parenthesized, we do not need to do any further processing. + if (skipped.kind === 195 /* ParenthesizedExpression */) { + return operand; + } + return binaryOperandNeedsParentheses(binaryOperator, operand, isLeftSideOfBinary, leftOperand) + ? ts.createParen(operand) + : operand; + } + ts.parenthesizeBinaryOperand = parenthesizeBinaryOperand; + /** + * Determines whether the operand to a BinaryExpression needs to be parenthesized. + * + * @param binaryOperator The operator for the BinaryExpression. + * @param operand The operand for the BinaryExpression. + * @param isLeftSideOfBinary A value indicating whether the operand is the left side of the + * BinaryExpression. + */ + function binaryOperandNeedsParentheses(binaryOperator, operand, isLeftSideOfBinary, leftOperand) { + // If the operand has lower precedence, then it needs to be parenthesized to preserve the + // intent of the expression. For example, if the operand is `a + b` and the operator is + // `*`, then we need to parenthesize the operand to preserve the intended order of + // operations: `(a + b) * x`. + // + // If the operand has higher precedence, then it does not need to be parenthesized. For + // example, if the operand is `a * b` and the operator is `+`, then we do not need to + // parenthesize to preserve the intended order of operations: `a * b + x`. + // + // If the operand has the same precedence, then we need to check the associativity of + // the operator based on whether this is the left or right operand of the expression. + // + // For example, if `a / d` is on the right of operator `*`, we need to parenthesize + // to preserve the intended order of operations: `x * (a / d)` + // + // If `a ** d` is on the left of operator `**`, we need to parenthesize to preserve + // the intended order of operations: `(a ** b) ** c` + var binaryOperatorPrecedence = ts.getOperatorPrecedence(204 /* BinaryExpression */, binaryOperator); + var binaryOperatorAssociativity = ts.getOperatorAssociativity(204 /* BinaryExpression */, binaryOperator); + var emittedOperand = ts.skipPartiallyEmittedExpressions(operand); + if (!isLeftSideOfBinary && operand.kind === 197 /* ArrowFunction */ && binaryOperatorPrecedence > 4) { + // We need to parenthesize arrow functions on the right side to avoid it being + // parsed as parenthesized expression: `a && (() => {})` + return true; + } + var operandPrecedence = ts.getExpressionPrecedence(emittedOperand); + switch (ts.compareValues(operandPrecedence, binaryOperatorPrecedence)) { + case -1 /* LessThan */: + // If the operand is the right side of a right-associative binary operation + // and is a yield expression, then we do not need parentheses. + if (!isLeftSideOfBinary + && binaryOperatorAssociativity === 1 /* Right */ + && operand.kind === 207 /* YieldExpression */) { + return false; + } + return true; + case 1 /* GreaterThan */: + return false; + case 0 /* EqualTo */: + if (isLeftSideOfBinary) { + // No need to parenthesize the left operand when the binary operator is + // left associative: + // (a*b)/x -> a*b/x + // (a**b)/x -> a**b/x + // + // Parentheses are needed for the left operand when the binary operator is + // right associative: + // (a/b)**x -> (a/b)**x + // (a**b)**x -> (a**b)**x + return binaryOperatorAssociativity === 1 /* Right */; + } + else { + if (ts.isBinaryExpression(emittedOperand) + && emittedOperand.operatorToken.kind === binaryOperator) { + // No need to parenthesize the right operand when the binary operator and + // operand are the same and one of the following: + // x*(a*b) => x*a*b + // x|(a|b) => x|a|b + // x&(a&b) => x&a&b + // x^(a^b) => x^a^b + if (operatorHasAssociativeProperty(binaryOperator)) { + return false; + } + // No need to parenthesize the right operand when the binary operator + // is plus (+) if both the left and right operands consist solely of either + // literals of the same kind or binary plus (+) expressions for literals of + // the same kind (recursively). + // "a"+(1+2) => "a"+(1+2) + // "a"+("b"+"c") => "a"+"b"+"c" + if (binaryOperator === 38 /* PlusToken */) { + var leftKind = leftOperand ? getLiteralKindOfBinaryPlusOperand(leftOperand) : 0 /* Unknown */; + if (ts.isLiteralKind(leftKind) && leftKind === getLiteralKindOfBinaryPlusOperand(emittedOperand)) { + return false; + } + } + } + // No need to parenthesize the right operand when the operand is right + // associative: + // x/(a**b) -> x/a**b + // x**(a**b) -> x**a**b + // + // Parentheses are needed for the right operand when the operand is left + // associative: + // x/(a*b) -> x/(a*b) + // x**(a/b) -> x**(a/b) + var operandAssociativity = ts.getExpressionAssociativity(emittedOperand); + return operandAssociativity === 0 /* Left */; + } + } + } + /** + * Determines whether a binary operator is mathematically associative. + * + * @param binaryOperator The binary operator. + */ + function operatorHasAssociativeProperty(binaryOperator) { + // The following operators are associative in JavaScript: + // (a*b)*c -> a*(b*c) -> a*b*c + // (a|b)|c -> a|(b|c) -> a|b|c + // (a&b)&c -> a&(b&c) -> a&b&c + // (a^b)^c -> a^(b^c) -> a^b^c + // + // While addition is associative in mathematics, JavaScript's `+` is not + // guaranteed to be associative as it is overloaded with string concatenation. + return binaryOperator === 40 /* AsteriskToken */ + || binaryOperator === 50 /* BarToken */ + || binaryOperator === 49 /* AmpersandToken */ + || binaryOperator === 51 /* CaretToken */; + } + /** + * This function determines whether an expression consists of a homogeneous set of + * literal expressions or binary plus expressions that all share the same literal kind. + * It is used to determine whether the right-hand operand of a binary plus expression can be + * emitted without parentheses. + */ + function getLiteralKindOfBinaryPlusOperand(node) { + node = ts.skipPartiallyEmittedExpressions(node); + if (ts.isLiteralKind(node.kind)) { + return node.kind; + } + if (node.kind === 204 /* BinaryExpression */ && node.operatorToken.kind === 38 /* PlusToken */) { + if (node.cachedLiteralKind !== undefined) { + return node.cachedLiteralKind; + } + var leftKind = getLiteralKindOfBinaryPlusOperand(node.left); + var literalKind = ts.isLiteralKind(leftKind) + && leftKind === getLiteralKindOfBinaryPlusOperand(node.right) + ? leftKind + : 0 /* Unknown */; + node.cachedLiteralKind = literalKind; + return literalKind; + } + return 0 /* Unknown */; + } + function parenthesizeForConditionalHead(condition) { + var conditionalPrecedence = ts.getOperatorPrecedence(205 /* ConditionalExpression */, 56 /* QuestionToken */); + var emittedCondition = ts.skipPartiallyEmittedExpressions(condition); + var conditionPrecedence = ts.getExpressionPrecedence(emittedCondition); + if (ts.compareValues(conditionPrecedence, conditionalPrecedence) === -1 /* LessThan */) { + return ts.createParen(condition); + } + return condition; + } + ts.parenthesizeForConditionalHead = parenthesizeForConditionalHead; + function parenthesizeSubexpressionOfConditionalExpression(e) { + // per ES grammar both 'whenTrue' and 'whenFalse' parts of conditional expression are assignment expressions + // so in case when comma expression is introduced as a part of previous transformations + // if should be wrapped in parens since comma operator has the lowest precedence + var emittedExpression = ts.skipPartiallyEmittedExpressions(e); + return isCommaSequence(emittedExpression) + ? ts.createParen(e) + : e; + } + ts.parenthesizeSubexpressionOfConditionalExpression = parenthesizeSubexpressionOfConditionalExpression; + /** + * [Per the spec](https://tc39.github.io/ecma262/#prod-ExportDeclaration), `export default` accepts _AssigmentExpression_ but + * has a lookahead restriction for `function`, `async function`, and `class`. + * + * Basically, that means we need to parenthesize in the following cases: + * + * - BinaryExpression of CommaToken + * - CommaList (synthetic list of multiple comma expressions) + * - FunctionExpression + * - ClassExpression + */ + function parenthesizeDefaultExpression(e) { + var check = ts.skipPartiallyEmittedExpressions(e); + var needsParens = isCommaSequence(check); + if (!needsParens) { + switch (getLeftmostExpression(check, /*stopAtCallExpression*/ false).kind) { + case 209 /* ClassExpression */: + case 196 /* FunctionExpression */: + needsParens = true; + } + } + return needsParens ? ts.createParen(e) : e; + } + ts.parenthesizeDefaultExpression = parenthesizeDefaultExpression; + /** + * Wraps an expression in parentheses if it is needed in order to use the expression + * as the expression of a NewExpression node. + * + * @param expression The Expression node. + */ + function parenthesizeForNew(expression) { + var leftmostExpr = getLeftmostExpression(expression, /*stopAtCallExpressions*/ true); + switch (leftmostExpr.kind) { + case 191 /* CallExpression */: + return ts.createParen(expression); + case 192 /* NewExpression */: + return !leftmostExpr.arguments + ? ts.createParen(expression) + : expression; + } + return parenthesizeForAccess(expression); + } + ts.parenthesizeForNew = parenthesizeForNew; + /** + * Wraps an expression in parentheses if it is needed in order to use the expression for + * property or element access. + * + * @param expr The expression node. + */ + function parenthesizeForAccess(expression) { + // isLeftHandSideExpression is almost the correct criterion for when it is not necessary + // to parenthesize the expression before a dot. The known exception is: + // + // NewExpression: + // new C.x -> not the same as (new C).x + // + var emittedExpression = ts.skipPartiallyEmittedExpressions(expression); + if (ts.isLeftHandSideExpression(emittedExpression) + && (emittedExpression.kind !== 192 /* NewExpression */ || emittedExpression.arguments)) { + return expression; + } + return ts.setTextRange(ts.createParen(expression), expression); + } + ts.parenthesizeForAccess = parenthesizeForAccess; + function parenthesizePostfixOperand(operand) { + return ts.isLeftHandSideExpression(operand) + ? operand + : ts.setTextRange(ts.createParen(operand), operand); + } + ts.parenthesizePostfixOperand = parenthesizePostfixOperand; + function parenthesizePrefixOperand(operand) { + return ts.isUnaryExpression(operand) + ? operand + : ts.setTextRange(ts.createParen(operand), operand); + } + ts.parenthesizePrefixOperand = parenthesizePrefixOperand; + function parenthesizeListElements(elements) { + var result; + for (var i = 0; i < elements.length; i++) { + var element = parenthesizeExpressionForList(elements[i]); + if (result !== undefined || element !== elements[i]) { + if (result === undefined) { + result = elements.slice(0, i); + } + result.push(element); + } + } + if (result !== undefined) { + return ts.setTextRange(ts.createNodeArray(result, elements.hasTrailingComma), elements); + } + return elements; + } + ts.parenthesizeListElements = parenthesizeListElements; + function parenthesizeExpressionForList(expression) { + var emittedExpression = ts.skipPartiallyEmittedExpressions(expression); + var expressionPrecedence = ts.getExpressionPrecedence(emittedExpression); + var commaPrecedence = ts.getOperatorPrecedence(204 /* BinaryExpression */, 27 /* CommaToken */); + return expressionPrecedence > commaPrecedence + ? expression + : ts.setTextRange(ts.createParen(expression), expression); + } + ts.parenthesizeExpressionForList = parenthesizeExpressionForList; + function parenthesizeExpressionForExpressionStatement(expression) { + var emittedExpression = ts.skipPartiallyEmittedExpressions(expression); + if (ts.isCallExpression(emittedExpression)) { + var callee = emittedExpression.expression; + var kind = ts.skipPartiallyEmittedExpressions(callee).kind; + if (kind === 196 /* FunctionExpression */ || kind === 197 /* ArrowFunction */) { + var mutableCall = ts.getMutableClone(emittedExpression); + mutableCall.expression = ts.setTextRange(ts.createParen(callee), callee); + return recreateOuterExpressions(expression, mutableCall, 4 /* PartiallyEmittedExpressions */); + } + } + var leftmostExpressionKind = getLeftmostExpression(emittedExpression, /*stopAtCallExpressions*/ false).kind; + if (leftmostExpressionKind === 188 /* ObjectLiteralExpression */ || leftmostExpressionKind === 196 /* FunctionExpression */) { + return ts.setTextRange(ts.createParen(expression), expression); + } + return expression; + } + ts.parenthesizeExpressionForExpressionStatement = parenthesizeExpressionForExpressionStatement; + function parenthesizeConditionalTypeMember(member) { + return member.kind === 175 /* ConditionalType */ ? ts.createParenthesizedType(member) : member; + } + ts.parenthesizeConditionalTypeMember = parenthesizeConditionalTypeMember; + function parenthesizeElementTypeMember(member) { + switch (member.kind) { + case 173 /* UnionType */: + case 174 /* IntersectionType */: + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + return ts.createParenthesizedType(member); + } + return parenthesizeConditionalTypeMember(member); + } + ts.parenthesizeElementTypeMember = parenthesizeElementTypeMember; + function parenthesizeArrayTypeMember(member) { + switch (member.kind) { + case 167 /* TypeQuery */: + case 179 /* TypeOperator */: + case 176 /* InferType */: + return ts.createParenthesizedType(member); + } + return parenthesizeElementTypeMember(member); + } + ts.parenthesizeArrayTypeMember = parenthesizeArrayTypeMember; + function parenthesizeElementTypeMembers(members) { + return ts.createNodeArray(ts.sameMap(members, parenthesizeElementTypeMember)); + } + ts.parenthesizeElementTypeMembers = parenthesizeElementTypeMembers; + function parenthesizeTypeParameters(typeParameters) { + if (ts.some(typeParameters)) { + var params = []; + for (var i = 0; i < typeParameters.length; ++i) { + var entry = typeParameters[i]; + params.push(i === 0 && ts.isFunctionOrConstructorTypeNode(entry) && entry.typeParameters ? + ts.createParenthesizedType(entry) : + entry); + } + return ts.createNodeArray(params); + } + } + ts.parenthesizeTypeParameters = parenthesizeTypeParameters; + function getLeftmostExpression(node, stopAtCallExpressions) { + while (true) { + switch (node.kind) { + case 203 /* PostfixUnaryExpression */: + node = node.operand; + continue; + case 204 /* BinaryExpression */: + node = node.left; + continue; + case 205 /* ConditionalExpression */: + node = node.condition; + continue; + case 193 /* TaggedTemplateExpression */: + node = node.tag; + continue; + case 191 /* CallExpression */: + if (stopAtCallExpressions) { + return node; + } + // falls through + case 212 /* AsExpression */: + case 190 /* ElementAccessExpression */: + case 189 /* PropertyAccessExpression */: + case 213 /* NonNullExpression */: + case 308 /* PartiallyEmittedExpression */: + node = node.expression; + continue; + } + return node; + } + } + function parenthesizeConciseBody(body) { + if (!ts.isBlock(body) && (isCommaSequence(body) || getLeftmostExpression(body, /*stopAtCallExpressions*/ false).kind === 188 /* ObjectLiteralExpression */)) { + return ts.setTextRange(ts.createParen(body), body); + } + return body; + } + ts.parenthesizeConciseBody = parenthesizeConciseBody; + function isCommaSequence(node) { + return node.kind === 204 /* BinaryExpression */ && node.operatorToken.kind === 27 /* CommaToken */ || + node.kind === 309 /* CommaListExpression */; + } + ts.isCommaSequence = isCommaSequence; + var OuterExpressionKinds; + (function (OuterExpressionKinds) { + OuterExpressionKinds[OuterExpressionKinds["Parentheses"] = 1] = "Parentheses"; + OuterExpressionKinds[OuterExpressionKinds["Assertions"] = 2] = "Assertions"; + OuterExpressionKinds[OuterExpressionKinds["PartiallyEmittedExpressions"] = 4] = "PartiallyEmittedExpressions"; + OuterExpressionKinds[OuterExpressionKinds["All"] = 7] = "All"; + })(OuterExpressionKinds = ts.OuterExpressionKinds || (ts.OuterExpressionKinds = {})); + function isOuterExpression(node, kinds) { + if (kinds === void 0) { kinds = 7 /* All */; } + switch (node.kind) { + case 195 /* ParenthesizedExpression */: + return (kinds & 1 /* Parentheses */) !== 0; + case 194 /* TypeAssertionExpression */: + case 212 /* AsExpression */: + case 213 /* NonNullExpression */: + return (kinds & 2 /* Assertions */) !== 0; + case 308 /* PartiallyEmittedExpression */: + return (kinds & 4 /* PartiallyEmittedExpressions */) !== 0; + } + return false; + } + ts.isOuterExpression = isOuterExpression; + function skipOuterExpressions(node, kinds) { + if (kinds === void 0) { kinds = 7 /* All */; } + var previousNode; + do { + previousNode = node; + if (kinds & 1 /* Parentheses */) { + node = ts.skipParentheses(node); + } + if (kinds & 2 /* Assertions */) { + node = skipAssertions(node); + } + if (kinds & 4 /* PartiallyEmittedExpressions */) { + node = ts.skipPartiallyEmittedExpressions(node); + } + } while (previousNode !== node); + return node; + } + ts.skipOuterExpressions = skipOuterExpressions; + function skipAssertions(node) { + while (ts.isAssertionExpression(node) || node.kind === 213 /* NonNullExpression */) { + node = node.expression; + } + return node; + } + ts.skipAssertions = skipAssertions; + function updateOuterExpression(outerExpression, expression) { + switch (outerExpression.kind) { + case 195 /* ParenthesizedExpression */: return ts.updateParen(outerExpression, expression); + case 194 /* TypeAssertionExpression */: return ts.updateTypeAssertion(outerExpression, outerExpression.type, expression); + case 212 /* AsExpression */: return ts.updateAsExpression(outerExpression, expression, outerExpression.type); + case 213 /* NonNullExpression */: return ts.updateNonNullExpression(outerExpression, expression); + case 308 /* PartiallyEmittedExpression */: return ts.updatePartiallyEmittedExpression(outerExpression, expression); + } + } + /** + * Determines whether a node is a parenthesized expression that can be ignored when recreating outer expressions. + * + * A parenthesized expression can be ignored when all of the following are true: + * + * - It's `pos` and `end` are not -1 + * - It does not have a custom source map range + * - It does not have a custom comment range + * - It does not have synthetic leading or trailing comments + * + * If an outermost parenthesized expression is ignored, but the containing expression requires a parentheses around + * the expression to maintain precedence, a new parenthesized expression should be created automatically when + * the containing expression is created/updated. + */ + function isIgnorableParen(node) { + return node.kind === 195 /* ParenthesizedExpression */ + && ts.nodeIsSynthesized(node) + && ts.nodeIsSynthesized(ts.getSourceMapRange(node)) + && ts.nodeIsSynthesized(ts.getCommentRange(node)) + && !ts.some(ts.getSyntheticLeadingComments(node)) + && !ts.some(ts.getSyntheticTrailingComments(node)); + } + function recreateOuterExpressions(outerExpression, innerExpression, kinds) { + if (kinds === void 0) { kinds = 7 /* All */; } + if (outerExpression && isOuterExpression(outerExpression, kinds) && !isIgnorableParen(outerExpression)) { + return updateOuterExpression(outerExpression, recreateOuterExpressions(outerExpression.expression, innerExpression)); + } + return innerExpression; + } + ts.recreateOuterExpressions = recreateOuterExpressions; + function startOnNewLine(node) { + return ts.setStartsOnNewLine(node, /*newLine*/ true); + } + ts.startOnNewLine = startOnNewLine; + function getExternalHelpersModuleName(node) { + var parseNode = ts.getOriginalNode(node, ts.isSourceFile); + var emitNode = parseNode && parseNode.emitNode; + return emitNode && emitNode.externalHelpersModuleName; + } + ts.getExternalHelpersModuleName = getExternalHelpersModuleName; + function getOrCreateExternalHelpersModuleNameIfNeeded(node, compilerOptions, hasExportStarsToExportValues, hasImportStarOrImportDefault) { + if (compilerOptions.importHelpers && ts.isEffectiveExternalModule(node, compilerOptions)) { + var externalHelpersModuleName = getExternalHelpersModuleName(node); + if (externalHelpersModuleName) { + return externalHelpersModuleName; + } + var moduleKind = ts.getEmitModuleKind(compilerOptions); + var create = (hasExportStarsToExportValues || (compilerOptions.esModuleInterop && hasImportStarOrImportDefault)) + && moduleKind !== ts.ModuleKind.System + && moduleKind !== ts.ModuleKind.ES2015 + && moduleKind !== ts.ModuleKind.ESNext; + if (!create) { + var helpers = ts.getEmitHelpers(node); + if (helpers) { + for (var _i = 0, helpers_2 = helpers; _i < helpers_2.length; _i++) { + var helper = helpers_2[_i]; + if (!helper.scoped) { + create = true; + break; + } + } + } + } + if (create) { + var parseNode = ts.getOriginalNode(node, ts.isSourceFile); + var emitNode = ts.getOrCreateEmitNode(parseNode); + return emitNode.externalHelpersModuleName || (emitNode.externalHelpersModuleName = ts.createUniqueName(ts.externalHelpersModuleNameText)); + } + } + } + ts.getOrCreateExternalHelpersModuleNameIfNeeded = getOrCreateExternalHelpersModuleNameIfNeeded; + /** + * Get the name of that target module from an import or export declaration + */ + function getLocalNameForExternalImport(node, sourceFile) { + var namespaceDeclaration = ts.getNamespaceDeclarationNode(node); + if (namespaceDeclaration && !ts.isDefaultImport(node)) { + var name = namespaceDeclaration.name; + return ts.isGeneratedIdentifier(name) ? name : ts.createIdentifier(ts.getSourceTextOfNodeFromSourceFile(sourceFile, name) || ts.idText(name)); + } + if (node.kind === 249 /* ImportDeclaration */ && node.importClause) { + return ts.getGeneratedNameForNode(node); + } + if (node.kind === 255 /* ExportDeclaration */ && node.moduleSpecifier) { + return ts.getGeneratedNameForNode(node); + } + return undefined; + } + ts.getLocalNameForExternalImport = getLocalNameForExternalImport; + /** + * Get the name of a target module from an import/export declaration as should be written in the emitted output. + * The emitted output name can be different from the input if: + * 1. The module has a /// + * 2. --out or --outFile is used, making the name relative to the rootDir + * 3- The containing SourceFile has an entry in renamedDependencies for the import as requested by some module loaders (e.g. System). + * Otherwise, a new StringLiteral node representing the module name will be returned. + */ + function getExternalModuleNameLiteral(importNode, sourceFile, host, resolver, compilerOptions) { + var moduleName = ts.getExternalModuleName(importNode); // TODO: GH#18217 + if (moduleName.kind === 10 /* StringLiteral */) { + return tryGetModuleNameFromDeclaration(importNode, host, resolver, compilerOptions) + || tryRenameExternalModule(moduleName, sourceFile) + || ts.getSynthesizedClone(moduleName); + } + return undefined; + } + ts.getExternalModuleNameLiteral = getExternalModuleNameLiteral; + /** + * Some bundlers (SystemJS builder) sometimes want to rename dependencies. + * Here we check if alternative name was provided for a given moduleName and return it if possible. + */ + function tryRenameExternalModule(moduleName, sourceFile) { + var rename = sourceFile.renamedDependencies && sourceFile.renamedDependencies.get(moduleName.text); + return rename && ts.createLiteral(rename); + } + /** + * Get the name of a module as should be written in the emitted output. + * The emitted output name can be different from the input if: + * 1. The module has a /// + * 2. --out or --outFile is used, making the name relative to the rootDir + * Otherwise, a new StringLiteral node representing the module name will be returned. + */ + function tryGetModuleNameFromFile(file, host, options) { + if (!file) { + return undefined; + } + if (file.moduleName) { + return ts.createLiteral(file.moduleName); + } + if (!file.isDeclarationFile && (options.out || options.outFile)) { + return ts.createLiteral(ts.getExternalModuleNameFromPath(host, file.fileName)); + } + return undefined; + } + ts.tryGetModuleNameFromFile = tryGetModuleNameFromFile; + function tryGetModuleNameFromDeclaration(declaration, host, resolver, compilerOptions) { + return tryGetModuleNameFromFile(resolver.getExternalModuleFileFromDeclaration(declaration), host, compilerOptions); + } + /** + * Gets the initializer of an BindingOrAssignmentElement. + */ + function getInitializerOfBindingOrAssignmentElement(bindingElement) { + if (ts.isDeclarationBindingElement(bindingElement)) { + // `1` in `let { a = 1 } = ...` + // `1` in `let { a: b = 1 } = ...` + // `1` in `let { a: {b} = 1 } = ...` + // `1` in `let { a: [b] = 1 } = ...` + // `1` in `let [a = 1] = ...` + // `1` in `let [{a} = 1] = ...` + // `1` in `let [[a] = 1] = ...` + return bindingElement.initializer; + } + if (ts.isPropertyAssignment(bindingElement)) { + // `1` in `({ a: b = 1 } = ...)` + // `1` in `({ a: {b} = 1 } = ...)` + // `1` in `({ a: [b] = 1 } = ...)` + var initializer = bindingElement.initializer; + return ts.isAssignmentExpression(initializer, /*excludeCompoundAssignment*/ true) + ? initializer.right + : undefined; + } + if (ts.isShorthandPropertyAssignment(bindingElement)) { + // `1` in `({ a = 1 } = ...)` + return bindingElement.objectAssignmentInitializer; + } + if (ts.isAssignmentExpression(bindingElement, /*excludeCompoundAssignment*/ true)) { + // `1` in `[a = 1] = ...` + // `1` in `[{a} = 1] = ...` + // `1` in `[[a] = 1] = ...` + return bindingElement.right; + } + if (ts.isSpreadElement(bindingElement)) { + // Recovery consistent with existing emit. + return getInitializerOfBindingOrAssignmentElement(bindingElement.expression); + } + } + ts.getInitializerOfBindingOrAssignmentElement = getInitializerOfBindingOrAssignmentElement; + /** + * Gets the name of an BindingOrAssignmentElement. + */ + function getTargetOfBindingOrAssignmentElement(bindingElement) { + if (ts.isDeclarationBindingElement(bindingElement)) { + // `a` in `let { a } = ...` + // `a` in `let { a = 1 } = ...` + // `b` in `let { a: b } = ...` + // `b` in `let { a: b = 1 } = ...` + // `a` in `let { ...a } = ...` + // `{b}` in `let { a: {b} } = ...` + // `{b}` in `let { a: {b} = 1 } = ...` + // `[b]` in `let { a: [b] } = ...` + // `[b]` in `let { a: [b] = 1 } = ...` + // `a` in `let [a] = ...` + // `a` in `let [a = 1] = ...` + // `a` in `let [...a] = ...` + // `{a}` in `let [{a}] = ...` + // `{a}` in `let [{a} = 1] = ...` + // `[a]` in `let [[a]] = ...` + // `[a]` in `let [[a] = 1] = ...` + return bindingElement.name; + } + if (ts.isObjectLiteralElementLike(bindingElement)) { + switch (bindingElement.kind) { + case 275 /* PropertyAssignment */: + // `b` in `({ a: b } = ...)` + // `b` in `({ a: b = 1 } = ...)` + // `{b}` in `({ a: {b} } = ...)` + // `{b}` in `({ a: {b} = 1 } = ...)` + // `[b]` in `({ a: [b] } = ...)` + // `[b]` in `({ a: [b] = 1 } = ...)` + // `b.c` in `({ a: b.c } = ...)` + // `b.c` in `({ a: b.c = 1 } = ...)` + // `b[0]` in `({ a: b[0] } = ...)` + // `b[0]` in `({ a: b[0] = 1 } = ...)` + return getTargetOfBindingOrAssignmentElement(bindingElement.initializer); + case 276 /* ShorthandPropertyAssignment */: + // `a` in `({ a } = ...)` + // `a` in `({ a = 1 } = ...)` + return bindingElement.name; + case 277 /* SpreadAssignment */: + // `a` in `({ ...a } = ...)` + return getTargetOfBindingOrAssignmentElement(bindingElement.expression); + } + // no target + return undefined; + } + if (ts.isAssignmentExpression(bindingElement, /*excludeCompoundAssignment*/ true)) { + // `a` in `[a = 1] = ...` + // `{a}` in `[{a} = 1] = ...` + // `[a]` in `[[a] = 1] = ...` + // `a.b` in `[a.b = 1] = ...` + // `a[0]` in `[a[0] = 1] = ...` + return getTargetOfBindingOrAssignmentElement(bindingElement.left); + } + if (ts.isSpreadElement(bindingElement)) { + // `a` in `[...a] = ...` + return getTargetOfBindingOrAssignmentElement(bindingElement.expression); + } + // `a` in `[a] = ...` + // `{a}` in `[{a}] = ...` + // `[a]` in `[[a]] = ...` + // `a.b` in `[a.b] = ...` + // `a[0]` in `[a[0]] = ...` + return bindingElement; + } + ts.getTargetOfBindingOrAssignmentElement = getTargetOfBindingOrAssignmentElement; + /** + * Determines whether an BindingOrAssignmentElement is a rest element. + */ + function getRestIndicatorOfBindingOrAssignmentElement(bindingElement) { + switch (bindingElement.kind) { + case 151 /* Parameter */: + case 186 /* BindingElement */: + // `...` in `let [...a] = ...` + return bindingElement.dotDotDotToken; + case 208 /* SpreadElement */: + case 277 /* SpreadAssignment */: + // `...` in `[...a] = ...` + return bindingElement; + } + return undefined; + } + ts.getRestIndicatorOfBindingOrAssignmentElement = getRestIndicatorOfBindingOrAssignmentElement; + /** + * Gets the property name of a BindingOrAssignmentElement + */ + function getPropertyNameOfBindingOrAssignmentElement(bindingElement) { + switch (bindingElement.kind) { + case 186 /* BindingElement */: + // `a` in `let { a: b } = ...` + // `[a]` in `let { [a]: b } = ...` + // `"a"` in `let { "a": b } = ...` + // `1` in `let { 1: b } = ...` + if (bindingElement.propertyName) { + var propertyName = bindingElement.propertyName; + return ts.isComputedPropertyName(propertyName) && isStringOrNumericLiteral(propertyName.expression) + ? propertyName.expression + : propertyName; + } + break; + case 275 /* PropertyAssignment */: + // `a` in `({ a: b } = ...)` + // `[a]` in `({ [a]: b } = ...)` + // `"a"` in `({ "a": b } = ...)` + // `1` in `({ 1: b } = ...)` + if (bindingElement.name) { + var propertyName = bindingElement.name; + return ts.isComputedPropertyName(propertyName) && isStringOrNumericLiteral(propertyName.expression) + ? propertyName.expression + : propertyName; + } + break; + case 277 /* SpreadAssignment */: + // `a` in `({ ...a } = ...)` + return bindingElement.name; + } + var target = getTargetOfBindingOrAssignmentElement(bindingElement); + if (target && ts.isPropertyName(target)) { + return ts.isComputedPropertyName(target) && isStringOrNumericLiteral(target.expression) + ? target.expression + : target; + } + ts.Debug.fail("Invalid property name for binding element."); + } + ts.getPropertyNameOfBindingOrAssignmentElement = getPropertyNameOfBindingOrAssignmentElement; + function isStringOrNumericLiteral(node) { + var kind = node.kind; + return kind === 10 /* StringLiteral */ + || kind === 8 /* NumericLiteral */; + } + /** + * Gets the elements of a BindingOrAssignmentPattern + */ + function getElementsOfBindingOrAssignmentPattern(name) { + switch (name.kind) { + case 184 /* ObjectBindingPattern */: + case 185 /* ArrayBindingPattern */: + case 187 /* ArrayLiteralExpression */: + // `a` in `{a}` + // `a` in `[a]` + return name.elements; + case 188 /* ObjectLiteralExpression */: + // `a` in `{a}` + return name.properties; + } + } + ts.getElementsOfBindingOrAssignmentPattern = getElementsOfBindingOrAssignmentPattern; + function convertToArrayAssignmentElement(element) { + if (ts.isBindingElement(element)) { + if (element.dotDotDotToken) { + ts.Debug.assertNode(element.name, ts.isIdentifier); + return ts.setOriginalNode(ts.setTextRange(ts.createSpread(element.name), element), element); + } + var expression = convertToAssignmentElementTarget(element.name); + return element.initializer + ? ts.setOriginalNode(ts.setTextRange(ts.createAssignment(expression, element.initializer), element), element) + : expression; + } + ts.Debug.assertNode(element, ts.isExpression); + return element; + } + ts.convertToArrayAssignmentElement = convertToArrayAssignmentElement; + function convertToObjectAssignmentElement(element) { + if (ts.isBindingElement(element)) { + if (element.dotDotDotToken) { + ts.Debug.assertNode(element.name, ts.isIdentifier); + return ts.setOriginalNode(ts.setTextRange(ts.createSpreadAssignment(element.name), element), element); + } + if (element.propertyName) { + var expression = convertToAssignmentElementTarget(element.name); + return ts.setOriginalNode(ts.setTextRange(ts.createPropertyAssignment(element.propertyName, element.initializer ? ts.createAssignment(expression, element.initializer) : expression), element), element); + } + ts.Debug.assertNode(element.name, ts.isIdentifier); + return ts.setOriginalNode(ts.setTextRange(ts.createShorthandPropertyAssignment(element.name, element.initializer), element), element); + } + ts.Debug.assertNode(element, ts.isObjectLiteralElementLike); + return element; + } + ts.convertToObjectAssignmentElement = convertToObjectAssignmentElement; + function convertToAssignmentPattern(node) { + switch (node.kind) { + case 185 /* ArrayBindingPattern */: + case 187 /* ArrayLiteralExpression */: + return convertToArrayAssignmentPattern(node); + case 184 /* ObjectBindingPattern */: + case 188 /* ObjectLiteralExpression */: + return convertToObjectAssignmentPattern(node); + } + } + ts.convertToAssignmentPattern = convertToAssignmentPattern; + function convertToObjectAssignmentPattern(node) { + if (ts.isObjectBindingPattern(node)) { + return ts.setOriginalNode(ts.setTextRange(ts.createObjectLiteral(ts.map(node.elements, convertToObjectAssignmentElement)), node), node); + } + ts.Debug.assertNode(node, ts.isObjectLiteralExpression); + return node; + } + ts.convertToObjectAssignmentPattern = convertToObjectAssignmentPattern; + function convertToArrayAssignmentPattern(node) { + if (ts.isArrayBindingPattern(node)) { + return ts.setOriginalNode(ts.setTextRange(ts.createArrayLiteral(ts.map(node.elements, convertToArrayAssignmentElement)), node), node); + } + ts.Debug.assertNode(node, ts.isArrayLiteralExpression); + return node; + } + ts.convertToArrayAssignmentPattern = convertToArrayAssignmentPattern; + function convertToAssignmentElementTarget(node) { + if (ts.isBindingPattern(node)) { + return convertToAssignmentPattern(node); + } + ts.Debug.assertNode(node, ts.isExpression); + return node; + } + ts.convertToAssignmentElementTarget = convertToAssignmentElementTarget; +})(ts || (ts = {})); +var ts; +(function (ts) { + var isTypeNodeOrTypeParameterDeclaration = ts.or(ts.isTypeNode, ts.isTypeParameterDeclaration); + function visitNode(node, visitor, test, lift) { + if (node === undefined || visitor === undefined) { + return node; + } + ts.aggregateTransformFlags(node); + var visited = visitor(node); + if (visited === node) { + return node; + } + var visitedNode; + if (visited === undefined) { + return undefined; + } + else if (ts.isArray(visited)) { + visitedNode = (lift || extractSingleNode)(visited); + } + else { + visitedNode = visited; + } + ts.Debug.assertNode(visitedNode, test); + ts.aggregateTransformFlags(visitedNode); + return visitedNode; + } + ts.visitNode = visitNode; + /** + * Visits a NodeArray using the supplied visitor, possibly returning a new NodeArray in its place. + * + * @param nodes The NodeArray to visit. + * @param visitor The callback used to visit a Node. + * @param test A node test to execute for each node. + * @param start An optional value indicating the starting offset at which to start visiting. + * @param count An optional value indicating the maximum number of nodes to visit. + */ + function visitNodes(nodes, visitor, test, start, count) { + if (nodes === undefined || visitor === undefined) { + return nodes; + } + var updated; + // Ensure start and count have valid values + var length = nodes.length; + if (start === undefined || start < 0) { + start = 0; + } + if (count === undefined || count > length - start) { + count = length - start; + } + if (start > 0 || count < length) { + // If we are not visiting all of the original nodes, we must always create a new array. + // Since this is a fragment of a node array, we do not copy over the previous location + // and will only copy over `hasTrailingComma` if we are including the last element. + updated = ts.createNodeArray([], /*hasTrailingComma*/ nodes.hasTrailingComma && start + count === length); + } + // Visit each original node. + for (var i = 0; i < count; i++) { + var node = nodes[i + start]; + ts.aggregateTransformFlags(node); + var visited = node !== undefined ? visitor(node) : undefined; + if (updated !== undefined || visited === undefined || visited !== node) { + if (updated === undefined) { + // Ensure we have a copy of `nodes`, up to the current index. + updated = ts.createNodeArray(nodes.slice(0, i), nodes.hasTrailingComma); + ts.setTextRange(updated, nodes); + } + if (visited) { + if (ts.isArray(visited)) { + for (var _i = 0, visited_1 = visited; _i < visited_1.length; _i++) { + var visitedNode = visited_1[_i]; + ts.Debug.assertNode(visitedNode, test); + ts.aggregateTransformFlags(visitedNode); + updated.push(visitedNode); + } + } + else { + ts.Debug.assertNode(visited, test); + ts.aggregateTransformFlags(visited); + updated.push(visited); + } + } + } + } + return updated || nodes; + } + ts.visitNodes = visitNodes; + /** + * Starts a new lexical environment and visits a statement list, ending the lexical environment + * and merging hoisted declarations upon completion. + */ + function visitLexicalEnvironment(statements, visitor, context, start, ensureUseStrict) { + context.startLexicalEnvironment(); + statements = visitNodes(statements, visitor, ts.isStatement, start); + if (ensureUseStrict && !ts.startsWithUseStrict(statements)) { + statements = ts.setTextRange(ts.createNodeArray([ts.createExpressionStatement(ts.createLiteral("use strict"))].concat(statements)), statements); + } + var declarations = context.endLexicalEnvironment(); + return ts.setTextRange(ts.createNodeArray(ts.concatenate(declarations, statements)), statements); + } + ts.visitLexicalEnvironment = visitLexicalEnvironment; + /** + * Starts a new lexical environment and visits a parameter list, suspending the lexical + * environment upon completion. + */ + function visitParameterList(nodes, visitor, context, nodesVisitor) { + if (nodesVisitor === void 0) { nodesVisitor = visitNodes; } + context.startLexicalEnvironment(); + var updated = nodesVisitor(nodes, visitor, ts.isParameterDeclaration); + context.suspendLexicalEnvironment(); + return updated; + } + ts.visitParameterList = visitParameterList; + function visitFunctionBody(node, visitor, context) { + context.resumeLexicalEnvironment(); + var updated = visitNode(node, visitor, ts.isConciseBody); + var declarations = context.endLexicalEnvironment(); + if (ts.some(declarations)) { + var block = ts.convertToFunctionBody(updated); + var statements = ts.mergeLexicalEnvironment(block.statements, declarations); + return ts.updateBlock(block, statements); + } + return updated; + } + ts.visitFunctionBody = visitFunctionBody; + function visitEachChild(node, visitor, context, nodesVisitor, tokenVisitor) { + if (nodesVisitor === void 0) { nodesVisitor = visitNodes; } + if (node === undefined) { + return undefined; + } + var kind = node.kind; + // No need to visit nodes with no children. + if ((kind > 0 /* FirstToken */ && kind <= 147 /* LastToken */) || kind === 178 /* ThisType */) { + return node; + } + switch (kind) { + // Names + case 72 /* Identifier */: + return ts.updateIdentifier(node, nodesVisitor(node.typeArguments, visitor, isTypeNodeOrTypeParameterDeclaration)); + case 148 /* QualifiedName */: + return ts.updateQualifiedName(node, visitNode(node.left, visitor, ts.isEntityName), visitNode(node.right, visitor, ts.isIdentifier)); + case 149 /* ComputedPropertyName */: + return ts.updateComputedPropertyName(node, visitNode(node.expression, visitor, ts.isExpression)); + // Signature elements + case 150 /* TypeParameter */: + return ts.updateTypeParameterDeclaration(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.constraint, visitor, ts.isTypeNode), visitNode(node.default, visitor, ts.isTypeNode)); + case 151 /* Parameter */: + return ts.updateParameter(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.dotDotDotToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isBindingName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); + case 152 /* Decorator */: + return ts.updateDecorator(node, visitNode(node.expression, visitor, ts.isExpression)); + // Type elements + case 153 /* PropertySignature */: + return ts.updatePropertySignature(node, nodesVisitor(node.modifiers, visitor, ts.isToken), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); + case 154 /* PropertyDeclaration */: + return ts.updateProperty(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); + case 155 /* MethodSignature */: + return ts.updateMethodSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken)); + case 156 /* MethodDeclaration */: + return ts.updateMethod(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); + case 157 /* Constructor */: + return ts.updateConstructor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context)); + case 158 /* GetAccessor */: + return ts.updateGetAccessor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); + case 159 /* SetAccessor */: + return ts.updateSetAccessor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context)); + case 160 /* CallSignature */: + return ts.updateCallSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); + case 161 /* ConstructSignature */: + return ts.updateConstructSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); + case 162 /* IndexSignature */: + return ts.updateIndexSignature(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); + // Types + case 163 /* TypePredicate */: + return ts.updateTypePredicateNode(node, visitNode(node.parameterName, visitor), visitNode(node.type, visitor, ts.isTypeNode)); + case 164 /* TypeReference */: + return ts.updateTypeReferenceNode(node, visitNode(node.typeName, visitor, ts.isEntityName), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode)); + case 165 /* FunctionType */: + return ts.updateFunctionTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); + case 166 /* ConstructorType */: + return ts.updateConstructorTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); + case 167 /* TypeQuery */: + return ts.updateTypeQueryNode(node, visitNode(node.exprName, visitor, ts.isEntityName)); + case 168 /* TypeLiteral */: + return ts.updateTypeLiteralNode(node, nodesVisitor(node.members, visitor, ts.isTypeElement)); + case 169 /* ArrayType */: + return ts.updateArrayTypeNode(node, visitNode(node.elementType, visitor, ts.isTypeNode)); + case 170 /* TupleType */: + return ts.updateTupleTypeNode(node, nodesVisitor(node.elementTypes, visitor, ts.isTypeNode)); + case 171 /* OptionalType */: + return ts.updateOptionalTypeNode(node, visitNode(node.type, visitor, ts.isTypeNode)); + case 172 /* RestType */: + return ts.updateRestTypeNode(node, visitNode(node.type, visitor, ts.isTypeNode)); + case 173 /* UnionType */: + return ts.updateUnionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode)); + case 174 /* IntersectionType */: + return ts.updateIntersectionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode)); + case 175 /* ConditionalType */: + return ts.updateConditionalTypeNode(node, visitNode(node.checkType, visitor, ts.isTypeNode), visitNode(node.extendsType, visitor, ts.isTypeNode), visitNode(node.trueType, visitor, ts.isTypeNode), visitNode(node.falseType, visitor, ts.isTypeNode)); + case 176 /* InferType */: + return ts.updateInferTypeNode(node, visitNode(node.typeParameter, visitor, ts.isTypeParameterDeclaration)); + case 183 /* ImportType */: + return ts.updateImportTypeNode(node, visitNode(node.argument, visitor, ts.isTypeNode), visitNode(node.qualifier, visitor, ts.isEntityName), visitNodes(node.typeArguments, visitor, ts.isTypeNode), node.isTypeOf); + case 177 /* ParenthesizedType */: + return ts.updateParenthesizedType(node, visitNode(node.type, visitor, ts.isTypeNode)); + case 179 /* TypeOperator */: + return ts.updateTypeOperatorNode(node, visitNode(node.type, visitor, ts.isTypeNode)); + case 180 /* IndexedAccessType */: + return ts.updateIndexedAccessTypeNode(node, visitNode(node.objectType, visitor, ts.isTypeNode), visitNode(node.indexType, visitor, ts.isTypeNode)); + case 181 /* MappedType */: + return ts.updateMappedTypeNode(node, visitNode(node.readonlyToken, tokenVisitor, ts.isToken), visitNode(node.typeParameter, visitor, ts.isTypeParameterDeclaration), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode)); + case 182 /* LiteralType */: + return ts.updateLiteralTypeNode(node, visitNode(node.literal, visitor, ts.isExpression)); + // Binding patterns + case 184 /* ObjectBindingPattern */: + return ts.updateObjectBindingPattern(node, nodesVisitor(node.elements, visitor, ts.isBindingElement)); + case 185 /* ArrayBindingPattern */: + return ts.updateArrayBindingPattern(node, nodesVisitor(node.elements, visitor, ts.isArrayBindingElement)); + case 186 /* BindingElement */: + return ts.updateBindingElement(node, visitNode(node.dotDotDotToken, tokenVisitor, ts.isToken), visitNode(node.propertyName, visitor, ts.isPropertyName), visitNode(node.name, visitor, ts.isBindingName), visitNode(node.initializer, visitor, ts.isExpression)); + // Expression + case 187 /* ArrayLiteralExpression */: + return ts.updateArrayLiteral(node, nodesVisitor(node.elements, visitor, ts.isExpression)); + case 188 /* ObjectLiteralExpression */: + return ts.updateObjectLiteral(node, nodesVisitor(node.properties, visitor, ts.isObjectLiteralElementLike)); + case 189 /* PropertyAccessExpression */: + return ts.updatePropertyAccess(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.name, visitor, ts.isIdentifier)); + case 190 /* ElementAccessExpression */: + return ts.updateElementAccess(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.argumentExpression, visitor, ts.isExpression)); + case 191 /* CallExpression */: + return ts.updateCall(node, visitNode(node.expression, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression)); + case 192 /* NewExpression */: + return ts.updateNew(node, visitNode(node.expression, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression)); + case 193 /* TaggedTemplateExpression */: + return ts.updateTaggedTemplate(node, visitNode(node.tag, visitor, ts.isExpression), visitNodes(node.typeArguments, visitor, ts.isExpression), visitNode(node.template, visitor, ts.isTemplateLiteral)); + case 194 /* TypeAssertionExpression */: + return ts.updateTypeAssertion(node, visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.expression, visitor, ts.isExpression)); + case 195 /* ParenthesizedExpression */: + return ts.updateParen(node, visitNode(node.expression, visitor, ts.isExpression)); + case 196 /* FunctionExpression */: + return ts.updateFunctionExpression(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); + case 197 /* ArrowFunction */: + return ts.updateArrowFunction(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.equalsGreaterThanToken, visitor, ts.isToken), visitFunctionBody(node.body, visitor, context)); + case 198 /* DeleteExpression */: + return ts.updateDelete(node, visitNode(node.expression, visitor, ts.isExpression)); + case 199 /* TypeOfExpression */: + return ts.updateTypeOf(node, visitNode(node.expression, visitor, ts.isExpression)); + case 200 /* VoidExpression */: + return ts.updateVoid(node, visitNode(node.expression, visitor, ts.isExpression)); + case 201 /* AwaitExpression */: + return ts.updateAwait(node, visitNode(node.expression, visitor, ts.isExpression)); + case 202 /* PrefixUnaryExpression */: + return ts.updatePrefix(node, visitNode(node.operand, visitor, ts.isExpression)); + case 203 /* PostfixUnaryExpression */: + return ts.updatePostfix(node, visitNode(node.operand, visitor, ts.isExpression)); + case 204 /* BinaryExpression */: + return ts.updateBinary(node, visitNode(node.left, visitor, ts.isExpression), visitNode(node.right, visitor, ts.isExpression), visitNode(node.operatorToken, visitor, ts.isToken)); + case 205 /* ConditionalExpression */: + return ts.updateConditional(node, visitNode(node.condition, visitor, ts.isExpression), visitNode(node.questionToken, visitor, ts.isToken), visitNode(node.whenTrue, visitor, ts.isExpression), visitNode(node.colonToken, visitor, ts.isToken), visitNode(node.whenFalse, visitor, ts.isExpression)); + case 206 /* TemplateExpression */: + return ts.updateTemplateExpression(node, visitNode(node.head, visitor, ts.isTemplateHead), nodesVisitor(node.templateSpans, visitor, ts.isTemplateSpan)); + case 207 /* YieldExpression */: + return ts.updateYield(node, visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.expression, visitor, ts.isExpression)); + case 208 /* SpreadElement */: + return ts.updateSpread(node, visitNode(node.expression, visitor, ts.isExpression)); + case 209 /* ClassExpression */: + return ts.updateClassExpression(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement)); + case 211 /* ExpressionWithTypeArguments */: + return ts.updateExpressionWithTypeArguments(node, nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), visitNode(node.expression, visitor, ts.isExpression)); + case 212 /* AsExpression */: + return ts.updateAsExpression(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.type, visitor, ts.isTypeNode)); + case 213 /* NonNullExpression */: + return ts.updateNonNullExpression(node, visitNode(node.expression, visitor, ts.isExpression)); + case 214 /* MetaProperty */: + return ts.updateMetaProperty(node, visitNode(node.name, visitor, ts.isIdentifier)); + // Misc + case 216 /* TemplateSpan */: + return ts.updateTemplateSpan(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.literal, visitor, ts.isTemplateMiddleOrTemplateTail)); + // Element + case 218 /* Block */: + return ts.updateBlock(node, nodesVisitor(node.statements, visitor, ts.isStatement)); + case 219 /* VariableStatement */: + return ts.updateVariableStatement(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.declarationList, visitor, ts.isVariableDeclarationList)); + case 221 /* ExpressionStatement */: + return ts.updateExpressionStatement(node, visitNode(node.expression, visitor, ts.isExpression)); + case 222 /* IfStatement */: + return ts.updateIf(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.thenStatement, visitor, ts.isStatement, ts.liftToBlock), visitNode(node.elseStatement, visitor, ts.isStatement, ts.liftToBlock)); + case 223 /* DoStatement */: + return ts.updateDo(node, visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock), visitNode(node.expression, visitor, ts.isExpression)); + case 224 /* WhileStatement */: + return ts.updateWhile(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); + case 225 /* ForStatement */: + return ts.updateFor(node, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.condition, visitor, ts.isExpression), visitNode(node.incrementor, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); + case 226 /* ForInStatement */: + return ts.updateForIn(node, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); + case 227 /* ForOfStatement */: + return ts.updateForOf(node, visitNode(node.awaitModifier, visitor, ts.isToken), visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); + case 228 /* ContinueStatement */: + return ts.updateContinue(node, visitNode(node.label, visitor, ts.isIdentifier)); + case 229 /* BreakStatement */: + return ts.updateBreak(node, visitNode(node.label, visitor, ts.isIdentifier)); + case 230 /* ReturnStatement */: + return ts.updateReturn(node, visitNode(node.expression, visitor, ts.isExpression)); + case 231 /* WithStatement */: + return ts.updateWith(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); + case 232 /* SwitchStatement */: + return ts.updateSwitch(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.caseBlock, visitor, ts.isCaseBlock)); + case 233 /* LabeledStatement */: + return ts.updateLabel(node, visitNode(node.label, visitor, ts.isIdentifier), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); + case 234 /* ThrowStatement */: + return ts.updateThrow(node, visitNode(node.expression, visitor, ts.isExpression)); + case 235 /* TryStatement */: + return ts.updateTry(node, visitNode(node.tryBlock, visitor, ts.isBlock), visitNode(node.catchClause, visitor, ts.isCatchClause), visitNode(node.finallyBlock, visitor, ts.isBlock)); + case 237 /* VariableDeclaration */: + return ts.updateVariableDeclaration(node, visitNode(node.name, visitor, ts.isBindingName), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); + case 238 /* VariableDeclarationList */: + return ts.updateVariableDeclarationList(node, nodesVisitor(node.declarations, visitor, ts.isVariableDeclaration)); + case 239 /* FunctionDeclaration */: + return ts.updateFunctionDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); + case 240 /* ClassDeclaration */: + return ts.updateClassDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement)); + case 241 /* InterfaceDeclaration */: + return ts.updateInterfaceDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isTypeElement)); + case 242 /* TypeAliasDeclaration */: + return ts.updateTypeAliasDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); + case 243 /* EnumDeclaration */: + return ts.updateEnumDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.members, visitor, ts.isEnumMember)); + case 244 /* ModuleDeclaration */: + return ts.updateModuleDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.body, visitor, ts.isModuleBody)); + case 245 /* ModuleBlock */: + return ts.updateModuleBlock(node, nodesVisitor(node.statements, visitor, ts.isStatement)); + case 246 /* CaseBlock */: + return ts.updateCaseBlock(node, nodesVisitor(node.clauses, visitor, ts.isCaseOrDefaultClause)); + case 247 /* NamespaceExportDeclaration */: + return ts.updateNamespaceExportDeclaration(node, visitNode(node.name, visitor, ts.isIdentifier)); + case 248 /* ImportEqualsDeclaration */: + return ts.updateImportEqualsDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.moduleReference, visitor, ts.isModuleReference)); + case 249 /* ImportDeclaration */: + return ts.updateImportDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.importClause, visitor, ts.isImportClause), visitNode(node.moduleSpecifier, visitor, ts.isExpression)); + case 250 /* ImportClause */: + return ts.updateImportClause(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.namedBindings, visitor, ts.isNamedImportBindings)); + case 251 /* NamespaceImport */: + return ts.updateNamespaceImport(node, visitNode(node.name, visitor, ts.isIdentifier)); + case 252 /* NamedImports */: + return ts.updateNamedImports(node, nodesVisitor(node.elements, visitor, ts.isImportSpecifier)); + case 253 /* ImportSpecifier */: + return ts.updateImportSpecifier(node, visitNode(node.propertyName, visitor, ts.isIdentifier), visitNode(node.name, visitor, ts.isIdentifier)); + case 254 /* ExportAssignment */: + return ts.updateExportAssignment(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.expression, visitor, ts.isExpression)); + case 255 /* ExportDeclaration */: + return ts.updateExportDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.exportClause, visitor, ts.isNamedExports), visitNode(node.moduleSpecifier, visitor, ts.isExpression)); + case 256 /* NamedExports */: + return ts.updateNamedExports(node, nodesVisitor(node.elements, visitor, ts.isExportSpecifier)); + case 257 /* ExportSpecifier */: + return ts.updateExportSpecifier(node, visitNode(node.propertyName, visitor, ts.isIdentifier), visitNode(node.name, visitor, ts.isIdentifier)); + // Module references + case 259 /* ExternalModuleReference */: + return ts.updateExternalModuleReference(node, visitNode(node.expression, visitor, ts.isExpression)); + // JSX + case 260 /* JsxElement */: + return ts.updateJsxElement(node, visitNode(node.openingElement, visitor, ts.isJsxOpeningElement), nodesVisitor(node.children, visitor, ts.isJsxChild), visitNode(node.closingElement, visitor, ts.isJsxClosingElement)); + case 261 /* JsxSelfClosingElement */: + return ts.updateJsxSelfClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), visitNode(node.attributes, visitor, ts.isJsxAttributes)); + case 262 /* JsxOpeningElement */: + return ts.updateJsxOpeningElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), visitNode(node.attributes, visitor, ts.isJsxAttributes)); + case 263 /* JsxClosingElement */: + return ts.updateJsxClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression)); + case 264 /* JsxFragment */: + return ts.updateJsxFragment(node, visitNode(node.openingFragment, visitor, ts.isJsxOpeningFragment), nodesVisitor(node.children, visitor, ts.isJsxChild), visitNode(node.closingFragment, visitor, ts.isJsxClosingFragment)); + case 267 /* JsxAttribute */: + return ts.updateJsxAttribute(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.initializer, visitor, ts.isStringLiteralOrJsxExpression)); + case 268 /* JsxAttributes */: + return ts.updateJsxAttributes(node, nodesVisitor(node.properties, visitor, ts.isJsxAttributeLike)); + case 269 /* JsxSpreadAttribute */: + return ts.updateJsxSpreadAttribute(node, visitNode(node.expression, visitor, ts.isExpression)); + case 270 /* JsxExpression */: + return ts.updateJsxExpression(node, visitNode(node.expression, visitor, ts.isExpression)); + // Clauses + case 271 /* CaseClause */: + return ts.updateCaseClause(node, visitNode(node.expression, visitor, ts.isExpression), nodesVisitor(node.statements, visitor, ts.isStatement)); + case 272 /* DefaultClause */: + return ts.updateDefaultClause(node, nodesVisitor(node.statements, visitor, ts.isStatement)); + case 273 /* HeritageClause */: + return ts.updateHeritageClause(node, nodesVisitor(node.types, visitor, ts.isExpressionWithTypeArguments)); + case 274 /* CatchClause */: + return ts.updateCatchClause(node, visitNode(node.variableDeclaration, visitor, ts.isVariableDeclaration), visitNode(node.block, visitor, ts.isBlock)); + // Property assignments + case 275 /* PropertyAssignment */: + return ts.updatePropertyAssignment(node, visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.initializer, visitor, ts.isExpression)); + case 276 /* ShorthandPropertyAssignment */: + return ts.updateShorthandPropertyAssignment(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.objectAssignmentInitializer, visitor, ts.isExpression)); + case 277 /* SpreadAssignment */: + return ts.updateSpreadAssignment(node, visitNode(node.expression, visitor, ts.isExpression)); + // Enum + case 278 /* EnumMember */: + return ts.updateEnumMember(node, visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.initializer, visitor, ts.isExpression)); + // Top-level nodes + case 279 /* SourceFile */: + return ts.updateSourceFileNode(node, visitLexicalEnvironment(node.statements, visitor, context)); + // Transformation nodes + case 308 /* PartiallyEmittedExpression */: + return ts.updatePartiallyEmittedExpression(node, visitNode(node.expression, visitor, ts.isExpression)); + case 309 /* CommaListExpression */: + return ts.updateCommaList(node, nodesVisitor(node.elements, visitor, ts.isExpression)); + default: + // No need to visit nodes with no children. + return node; + } + } + ts.visitEachChild = visitEachChild; + /** + * Extracts the single node from a NodeArray. + * + * @param nodes The NodeArray. + */ + function extractSingleNode(nodes) { + ts.Debug.assert(nodes.length <= 1, "Too many nodes written to output."); + return ts.singleOrUndefined(nodes); + } +})(ts || (ts = {})); +/* @internal */ +(function (ts) { + function reduceNode(node, f, initial) { + return node ? f(initial, node) : initial; + } + function reduceNodeArray(nodes, f, initial) { + return nodes ? f(initial, nodes) : initial; + } + /** + * Similar to `reduceLeft`, performs a reduction against each child of a node. + * NOTE: Unlike `forEachChild`, this does *not* visit every node. + * + * @param node The node containing the children to reduce. + * @param initial The initial value to supply to the reduction. + * @param f The callback function + */ + function reduceEachChild(node, initial, cbNode, cbNodeArray) { + if (node === undefined) { + return initial; + } + var reduceNodes = cbNodeArray ? reduceNodeArray : ts.reduceLeft; + var cbNodes = cbNodeArray || cbNode; + var kind = node.kind; + // No need to visit nodes with no children. + if ((kind > 0 /* FirstToken */ && kind <= 147 /* LastToken */)) { + return initial; + } + // We do not yet support types. + if ((kind >= 163 /* TypePredicate */ && kind <= 182 /* LiteralType */)) { + return initial; + } + var result = initial; + switch (node.kind) { + // Leaf nodes + case 217 /* SemicolonClassElement */: + case 220 /* EmptyStatement */: + case 210 /* OmittedExpression */: + case 236 /* DebuggerStatement */: + case 307 /* NotEmittedStatement */: + // No need to visit nodes with no children. + break; + // Names + case 148 /* QualifiedName */: + result = reduceNode(node.left, cbNode, result); + result = reduceNode(node.right, cbNode, result); + break; + case 149 /* ComputedPropertyName */: + result = reduceNode(node.expression, cbNode, result); + break; + // Signature elements + case 151 /* Parameter */: + result = reduceNodes(node.decorators, cbNodes, result); + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.type, cbNode, result); + result = reduceNode(node.initializer, cbNode, result); + break; + case 152 /* Decorator */: + result = reduceNode(node.expression, cbNode, result); + break; + // Type member + case 153 /* PropertySignature */: + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.questionToken, cbNode, result); + result = reduceNode(node.type, cbNode, result); + result = reduceNode(node.initializer, cbNode, result); + break; + case 154 /* PropertyDeclaration */: + result = reduceNodes(node.decorators, cbNodes, result); + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.type, cbNode, result); + result = reduceNode(node.initializer, cbNode, result); + break; + case 156 /* MethodDeclaration */: + result = reduceNodes(node.decorators, cbNodes, result); + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNodes(node.typeParameters, cbNodes, result); + result = reduceNodes(node.parameters, cbNodes, result); + result = reduceNode(node.type, cbNode, result); + result = reduceNode(node.body, cbNode, result); + break; + case 157 /* Constructor */: + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNodes(node.parameters, cbNodes, result); + result = reduceNode(node.body, cbNode, result); + break; + case 158 /* GetAccessor */: + result = reduceNodes(node.decorators, cbNodes, result); + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNodes(node.parameters, cbNodes, result); + result = reduceNode(node.type, cbNode, result); + result = reduceNode(node.body, cbNode, result); + break; + case 159 /* SetAccessor */: + result = reduceNodes(node.decorators, cbNodes, result); + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNodes(node.parameters, cbNodes, result); + result = reduceNode(node.body, cbNode, result); + break; + // Binding patterns + case 184 /* ObjectBindingPattern */: + case 185 /* ArrayBindingPattern */: + result = reduceNodes(node.elements, cbNodes, result); + break; + case 186 /* BindingElement */: + result = reduceNode(node.propertyName, cbNode, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.initializer, cbNode, result); + break; + // Expression + case 187 /* ArrayLiteralExpression */: + result = reduceNodes(node.elements, cbNodes, result); + break; + case 188 /* ObjectLiteralExpression */: + result = reduceNodes(node.properties, cbNodes, result); + break; + case 189 /* PropertyAccessExpression */: + result = reduceNode(node.expression, cbNode, result); + result = reduceNode(node.name, cbNode, result); + break; + case 190 /* ElementAccessExpression */: + result = reduceNode(node.expression, cbNode, result); + result = reduceNode(node.argumentExpression, cbNode, result); + break; + case 191 /* CallExpression */: + result = reduceNode(node.expression, cbNode, result); + result = reduceNodes(node.typeArguments, cbNodes, result); + result = reduceNodes(node.arguments, cbNodes, result); + break; + case 192 /* NewExpression */: + result = reduceNode(node.expression, cbNode, result); + result = reduceNodes(node.typeArguments, cbNodes, result); + result = reduceNodes(node.arguments, cbNodes, result); + break; + case 193 /* TaggedTemplateExpression */: + result = reduceNode(node.tag, cbNode, result); + result = reduceNodes(node.typeArguments, cbNodes, result); + result = reduceNode(node.template, cbNode, result); + break; + case 194 /* TypeAssertionExpression */: + result = reduceNode(node.type, cbNode, result); + result = reduceNode(node.expression, cbNode, result); + break; + case 196 /* FunctionExpression */: + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNodes(node.typeParameters, cbNodes, result); + result = reduceNodes(node.parameters, cbNodes, result); + result = reduceNode(node.type, cbNode, result); + result = reduceNode(node.body, cbNode, result); + break; + case 197 /* ArrowFunction */: + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNodes(node.typeParameters, cbNodes, result); + result = reduceNodes(node.parameters, cbNodes, result); + result = reduceNode(node.type, cbNode, result); + result = reduceNode(node.body, cbNode, result); + break; + case 195 /* ParenthesizedExpression */: + case 198 /* DeleteExpression */: + case 199 /* TypeOfExpression */: + case 200 /* VoidExpression */: + case 201 /* AwaitExpression */: + case 207 /* YieldExpression */: + case 208 /* SpreadElement */: + case 213 /* NonNullExpression */: + result = reduceNode(node.expression, cbNode, result); + break; + case 202 /* PrefixUnaryExpression */: + case 203 /* PostfixUnaryExpression */: + result = reduceNode(node.operand, cbNode, result); + break; + case 204 /* BinaryExpression */: + result = reduceNode(node.left, cbNode, result); + result = reduceNode(node.right, cbNode, result); + break; + case 205 /* ConditionalExpression */: + result = reduceNode(node.condition, cbNode, result); + result = reduceNode(node.whenTrue, cbNode, result); + result = reduceNode(node.whenFalse, cbNode, result); + break; + case 206 /* TemplateExpression */: + result = reduceNode(node.head, cbNode, result); + result = reduceNodes(node.templateSpans, cbNodes, result); + break; + case 209 /* ClassExpression */: + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNodes(node.typeParameters, cbNodes, result); + result = reduceNodes(node.heritageClauses, cbNodes, result); + result = reduceNodes(node.members, cbNodes, result); + break; + case 211 /* ExpressionWithTypeArguments */: + result = reduceNode(node.expression, cbNode, result); + result = reduceNodes(node.typeArguments, cbNodes, result); + break; + case 212 /* AsExpression */: + result = reduceNode(node.expression, cbNode, result); + result = reduceNode(node.type, cbNode, result); + break; + // Misc + case 216 /* TemplateSpan */: + result = reduceNode(node.expression, cbNode, result); + result = reduceNode(node.literal, cbNode, result); + break; + // Element + case 218 /* Block */: + result = reduceNodes(node.statements, cbNodes, result); + break; + case 219 /* VariableStatement */: + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.declarationList, cbNode, result); + break; + case 221 /* ExpressionStatement */: + result = reduceNode(node.expression, cbNode, result); + break; + case 222 /* IfStatement */: + result = reduceNode(node.expression, cbNode, result); + result = reduceNode(node.thenStatement, cbNode, result); + result = reduceNode(node.elseStatement, cbNode, result); + break; + case 223 /* DoStatement */: + result = reduceNode(node.statement, cbNode, result); + result = reduceNode(node.expression, cbNode, result); + break; + case 224 /* WhileStatement */: + case 231 /* WithStatement */: + result = reduceNode(node.expression, cbNode, result); + result = reduceNode(node.statement, cbNode, result); + break; + case 225 /* ForStatement */: + result = reduceNode(node.initializer, cbNode, result); + result = reduceNode(node.condition, cbNode, result); + result = reduceNode(node.incrementor, cbNode, result); + result = reduceNode(node.statement, cbNode, result); + break; + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + result = reduceNode(node.initializer, cbNode, result); + result = reduceNode(node.expression, cbNode, result); + result = reduceNode(node.statement, cbNode, result); + break; + case 230 /* ReturnStatement */: + case 234 /* ThrowStatement */: + result = reduceNode(node.expression, cbNode, result); + break; + case 232 /* SwitchStatement */: + result = reduceNode(node.expression, cbNode, result); + result = reduceNode(node.caseBlock, cbNode, result); + break; + case 233 /* LabeledStatement */: + result = reduceNode(node.label, cbNode, result); + result = reduceNode(node.statement, cbNode, result); + break; + case 235 /* TryStatement */: + result = reduceNode(node.tryBlock, cbNode, result); + result = reduceNode(node.catchClause, cbNode, result); + result = reduceNode(node.finallyBlock, cbNode, result); + break; + case 237 /* VariableDeclaration */: + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.type, cbNode, result); + result = reduceNode(node.initializer, cbNode, result); + break; + case 238 /* VariableDeclarationList */: + result = reduceNodes(node.declarations, cbNodes, result); + break; + case 239 /* FunctionDeclaration */: + result = reduceNodes(node.decorators, cbNodes, result); + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNodes(node.typeParameters, cbNodes, result); + result = reduceNodes(node.parameters, cbNodes, result); + result = reduceNode(node.type, cbNode, result); + result = reduceNode(node.body, cbNode, result); + break; + case 240 /* ClassDeclaration */: + result = reduceNodes(node.decorators, cbNodes, result); + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNodes(node.typeParameters, cbNodes, result); + result = reduceNodes(node.heritageClauses, cbNodes, result); + result = reduceNodes(node.members, cbNodes, result); + break; + case 243 /* EnumDeclaration */: + result = reduceNodes(node.decorators, cbNodes, result); + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNodes(node.members, cbNodes, result); + break; + case 244 /* ModuleDeclaration */: + result = reduceNodes(node.decorators, cbNodes, result); + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.body, cbNode, result); + break; + case 245 /* ModuleBlock */: + result = reduceNodes(node.statements, cbNodes, result); + break; + case 246 /* CaseBlock */: + result = reduceNodes(node.clauses, cbNodes, result); + break; + case 248 /* ImportEqualsDeclaration */: + result = reduceNodes(node.decorators, cbNodes, result); + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.moduleReference, cbNode, result); + break; + case 249 /* ImportDeclaration */: + result = reduceNodes(node.decorators, cbNodes, result); + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.importClause, cbNode, result); + result = reduceNode(node.moduleSpecifier, cbNode, result); + break; + case 250 /* ImportClause */: + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.namedBindings, cbNode, result); + break; + case 251 /* NamespaceImport */: + result = reduceNode(node.name, cbNode, result); + break; + case 252 /* NamedImports */: + case 256 /* NamedExports */: + result = reduceNodes(node.elements, cbNodes, result); + break; + case 253 /* ImportSpecifier */: + case 257 /* ExportSpecifier */: + result = reduceNode(node.propertyName, cbNode, result); + result = reduceNode(node.name, cbNode, result); + break; + case 254 /* ExportAssignment */: + result = ts.reduceLeft(node.decorators, cbNode, result); + result = ts.reduceLeft(node.modifiers, cbNode, result); + result = reduceNode(node.expression, cbNode, result); + break; + case 255 /* ExportDeclaration */: + result = ts.reduceLeft(node.decorators, cbNode, result); + result = ts.reduceLeft(node.modifiers, cbNode, result); + result = reduceNode(node.exportClause, cbNode, result); + result = reduceNode(node.moduleSpecifier, cbNode, result); + break; + // Module references + case 259 /* ExternalModuleReference */: + result = reduceNode(node.expression, cbNode, result); + break; + // JSX + case 260 /* JsxElement */: + result = reduceNode(node.openingElement, cbNode, result); + result = ts.reduceLeft(node.children, cbNode, result); + result = reduceNode(node.closingElement, cbNode, result); + break; + case 264 /* JsxFragment */: + result = reduceNode(node.openingFragment, cbNode, result); + result = ts.reduceLeft(node.children, cbNode, result); + result = reduceNode(node.closingFragment, cbNode, result); + break; + case 261 /* JsxSelfClosingElement */: + case 262 /* JsxOpeningElement */: + result = reduceNode(node.tagName, cbNode, result); + result = reduceNodes(node.typeArguments, cbNode, result); + result = reduceNode(node.attributes, cbNode, result); + break; + case 268 /* JsxAttributes */: + result = reduceNodes(node.properties, cbNodes, result); + break; + case 263 /* JsxClosingElement */: + result = reduceNode(node.tagName, cbNode, result); + break; + case 267 /* JsxAttribute */: + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.initializer, cbNode, result); + break; + case 269 /* JsxSpreadAttribute */: + result = reduceNode(node.expression, cbNode, result); + break; + case 270 /* JsxExpression */: + result = reduceNode(node.expression, cbNode, result); + break; + // Clauses + case 271 /* CaseClause */: + result = reduceNode(node.expression, cbNode, result); + // falls through + case 272 /* DefaultClause */: + result = reduceNodes(node.statements, cbNodes, result); + break; + case 273 /* HeritageClause */: + result = reduceNodes(node.types, cbNodes, result); + break; + case 274 /* CatchClause */: + result = reduceNode(node.variableDeclaration, cbNode, result); + result = reduceNode(node.block, cbNode, result); + break; + // Property assignments + case 275 /* PropertyAssignment */: + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.initializer, cbNode, result); + break; + case 276 /* ShorthandPropertyAssignment */: + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.objectAssignmentInitializer, cbNode, result); + break; + case 277 /* SpreadAssignment */: + result = reduceNode(node.expression, cbNode, result); + break; + // Enum + case 278 /* EnumMember */: + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.initializer, cbNode, result); + break; + // Top-level nodes + case 279 /* SourceFile */: + result = reduceNodes(node.statements, cbNodes, result); + break; + // Transformation nodes + case 308 /* PartiallyEmittedExpression */: + result = reduceNode(node.expression, cbNode, result); + break; + case 309 /* CommaListExpression */: + result = reduceNodes(node.elements, cbNodes, result); + break; + default: + break; + } + return result; + } + ts.reduceEachChild = reduceEachChild; + function mergeLexicalEnvironment(statements, declarations) { + if (!ts.some(declarations)) { + return statements; + } + return ts.isNodeArray(statements) + ? ts.setTextRange(ts.createNodeArray(ts.addStatementsAfterPrologue(statements.slice(), declarations)), statements) + : ts.addStatementsAfterPrologue(statements, declarations); + } + ts.mergeLexicalEnvironment = mergeLexicalEnvironment; + /** + * Lifts a NodeArray containing only Statement nodes to a block. + * + * @param nodes The NodeArray. + */ + function liftToBlock(nodes) { + Debug.assert(ts.every(nodes, ts.isStatement), "Cannot lift nodes to a Block."); + return ts.singleOrUndefined(nodes) || ts.createBlock(nodes); + } + ts.liftToBlock = liftToBlock; + /** + * Aggregates the TransformFlags for a Node and its subtree. + */ + function aggregateTransformFlags(node) { + aggregateTransformFlagsForNode(node); + return node; + } + ts.aggregateTransformFlags = aggregateTransformFlags; + /** + * Aggregates the TransformFlags for a Node and its subtree. The flags for the subtree are + * computed first, then the transform flags for the current node are computed from the subtree + * flags and the state of the current node. Finally, the transform flags of the node are + * returned, excluding any flags that should not be included in its parent node's subtree + * flags. + */ + function aggregateTransformFlagsForNode(node) { + if (node === undefined) { + return 0 /* None */; + } + if (node.transformFlags & 536870912 /* HasComputedFlags */) { + return node.transformFlags & ~ts.getTransformFlagsSubtreeExclusions(node.kind); + } + var subtreeFlags = aggregateTransformFlagsForSubtree(node); + return ts.computeTransformFlagsForNode(node, subtreeFlags); + } + function aggregateTransformFlagsForNodeArray(nodes) { + if (nodes === undefined) { + return 0 /* None */; + } + var subtreeFlags = 0 /* None */; + var nodeArrayFlags = 0 /* None */; + for (var _i = 0, nodes_3 = nodes; _i < nodes_3.length; _i++) { + var node = nodes_3[_i]; + subtreeFlags |= aggregateTransformFlagsForNode(node); + nodeArrayFlags |= node.transformFlags & ~536870912 /* HasComputedFlags */; + } + nodes.transformFlags = nodeArrayFlags | 536870912 /* HasComputedFlags */; + return subtreeFlags; + } + /** + * Aggregates the transform flags for the subtree of a node. + */ + function aggregateTransformFlagsForSubtree(node) { + // We do not transform ambient declarations or types, so there is no need to + // recursively aggregate transform flags. + if (ts.hasModifier(node, 2 /* Ambient */) || (ts.isTypeNode(node) && node.kind !== 211 /* ExpressionWithTypeArguments */)) { + return 0 /* None */; + } + // Aggregate the transform flags of each child. + return reduceEachChild(node, 0 /* None */, aggregateTransformFlagsForChildNode, aggregateTransformFlagsForChildNodes); + } + /** + * Aggregates the TransformFlags of a child node with the TransformFlags of its + * siblings. + */ + function aggregateTransformFlagsForChildNode(transformFlags, node) { + return transformFlags | aggregateTransformFlagsForNode(node); + } + function aggregateTransformFlagsForChildNodes(transformFlags, nodes) { + return transformFlags | aggregateTransformFlagsForNodeArray(nodes); + } + var Debug; + (function (Debug) { + var isDebugInfoEnabled = false; + function failBadSyntaxKind(node, message) { + return Debug.fail((message || "Unexpected node.") + "\r\nNode " + ts.formatSyntaxKind(node.kind) + " was unexpected.", failBadSyntaxKind); + } + Debug.failBadSyntaxKind = failBadSyntaxKind; + Debug.assertEachNode = Debug.shouldAssert(1 /* Normal */) + ? function (nodes, test, message) { return Debug.assert(test === undefined || ts.every(nodes, test), message || "Unexpected node.", function () { return "Node array did not pass test '" + Debug.getFunctionName(test) + "'."; }, Debug.assertEachNode); } + : ts.noop; + Debug.assertNode = Debug.shouldAssert(1 /* Normal */) + ? function (node, test, message) { return Debug.assert(test === undefined || test(node), message || "Unexpected node.", function () { return "Node " + ts.formatSyntaxKind(node.kind) + " did not pass test '" + Debug.getFunctionName(test) + "'."; }, Debug.assertNode); } + : ts.noop; + Debug.assertOptionalNode = Debug.shouldAssert(1 /* Normal */) + ? function (node, test, message) { return Debug.assert(test === undefined || node === undefined || test(node), message || "Unexpected node.", function () { return "Node " + ts.formatSyntaxKind(node.kind) + " did not pass test '" + Debug.getFunctionName(test) + "'."; }, Debug.assertOptionalNode); } + : ts.noop; + Debug.assertOptionalToken = Debug.shouldAssert(1 /* Normal */) + ? function (node, kind, message) { return Debug.assert(kind === undefined || node === undefined || node.kind === kind, message || "Unexpected node.", function () { return "Node " + ts.formatSyntaxKind(node.kind) + " was not a '" + ts.formatSyntaxKind(kind) + "' token."; }, Debug.assertOptionalToken); } + : ts.noop; + Debug.assertMissingNode = Debug.shouldAssert(1 /* Normal */) + ? function (node, message) { return Debug.assert(node === undefined, message || "Unexpected node.", function () { return "Node " + ts.formatSyntaxKind(node.kind) + " was unexpected'."; }, Debug.assertMissingNode); } + : ts.noop; + /** + * Injects debug information into frequently used types. + */ + function enableDebugInfo() { + if (isDebugInfoEnabled) + return; + // Add additional properties in debug mode to assist with debugging. + Object.defineProperties(ts.objectAllocator.getSymbolConstructor().prototype, { + __debugFlags: { get: function () { return ts.formatSymbolFlags(this.flags); } } + }); + Object.defineProperties(ts.objectAllocator.getTypeConstructor().prototype, { + __debugFlags: { get: function () { return ts.formatTypeFlags(this.flags); } }, + __debugObjectFlags: { get: function () { return this.flags & 524288 /* Object */ ? ts.formatObjectFlags(this.objectFlags) : ""; } }, + __debugTypeToString: { value: function () { return this.checker.typeToString(this); } }, + }); + var nodeConstructors = [ + ts.objectAllocator.getNodeConstructor(), + ts.objectAllocator.getIdentifierConstructor(), + ts.objectAllocator.getTokenConstructor(), + ts.objectAllocator.getSourceFileConstructor() + ]; + for (var _i = 0, nodeConstructors_1 = nodeConstructors; _i < nodeConstructors_1.length; _i++) { + var ctor = nodeConstructors_1[_i]; + if (!ctor.prototype.hasOwnProperty("__debugKind")) { + Object.defineProperties(ctor.prototype, { + __debugKind: { get: function () { return ts.formatSyntaxKind(this.kind); } }, + __debugModifierFlags: { get: function () { return ts.formatModifierFlags(ts.getModifierFlagsNoCache(this)); } }, + __debugTransformFlags: { get: function () { return ts.formatTransformFlags(this.transformFlags); } }, + __debugEmitFlags: { get: function () { return ts.formatEmitFlags(ts.getEmitFlags(this)); } }, + __debugGetText: { + value: function (includeTrivia) { + if (ts.nodeIsSynthesized(this)) + return ""; + var parseNode = ts.getParseTreeNode(this); + var sourceFile = parseNode && ts.getSourceFileOfNode(parseNode); + return sourceFile ? ts.getSourceTextOfNodeFromSourceFile(sourceFile, parseNode, includeTrivia) : ""; + } + } + }); + } + } + isDebugInfoEnabled = true; + } + Debug.enableDebugInfo = enableDebugInfo; + })(Debug = ts.Debug || (ts.Debug = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + function createSourceMapGenerator(host, file, sourceRoot, sourcesDirectoryPath, generatorOptions) { + var _a = generatorOptions.extendedDiagnostics + ? ts.performance.createTimer("Source Map", "beforeSourcemap", "afterSourcemap") + : ts.performance.nullTimer, enter = _a.enter, exit = _a.exit; + // Current source map file and its index in the sources list + var rawSources = []; + var sources = []; + var sourceToSourceIndexMap = ts.createMap(); + var sourcesContent; + var names = []; + var nameToNameIndexMap; + var mappings = ""; + // Last recorded and encoded mappings + var lastGeneratedLine = 0; + var lastGeneratedCharacter = 0; + var lastSourceIndex = 0; + var lastSourceLine = 0; + var lastSourceCharacter = 0; + var lastNameIndex = 0; + var hasLast = false; + var pendingGeneratedLine = 0; + var pendingGeneratedCharacter = 0; + var pendingSourceIndex = 0; + var pendingSourceLine = 0; + var pendingSourceCharacter = 0; + var pendingNameIndex = 0; + var hasPending = false; + var hasPendingSource = false; + var hasPendingName = false; + return { + getSources: function () { return rawSources; }, + addSource: addSource, + setSourceContent: setSourceContent, + addName: addName, + addMapping: addMapping, + appendSourceMap: appendSourceMap, + toJSON: toJSON, + toString: function () { return JSON.stringify(toJSON()); } + }; + function addSource(fileName) { + enter(); + var source = ts.getRelativePathToDirectoryOrUrl(sourcesDirectoryPath, fileName, host.getCurrentDirectory(), host.getCanonicalFileName, + /*isAbsolutePathAnUrl*/ true); + var sourceIndex = sourceToSourceIndexMap.get(source); + if (sourceIndex === undefined) { + sourceIndex = sources.length; + sources.push(source); + rawSources.push(fileName); + sourceToSourceIndexMap.set(source, sourceIndex); + } + exit(); + return sourceIndex; + } + function setSourceContent(sourceIndex, content) { + enter(); + if (content !== null) { + if (!sourcesContent) + sourcesContent = []; + while (sourcesContent.length < sourceIndex) { + // tslint:disable-next-line:no-null-keyword boolean-trivia + sourcesContent.push(null); + } + sourcesContent[sourceIndex] = content; + } + exit(); + } + function addName(name) { + enter(); + if (!nameToNameIndexMap) + nameToNameIndexMap = ts.createMap(); + var nameIndex = nameToNameIndexMap.get(name); + if (nameIndex === undefined) { + nameIndex = names.length; + names.push(name); + nameToNameIndexMap.set(name, nameIndex); + } + exit(); + return nameIndex; + } + function isNewGeneratedPosition(generatedLine, generatedCharacter) { + return !hasPending + || pendingGeneratedLine !== generatedLine + || pendingGeneratedCharacter !== generatedCharacter; + } + function isBacktrackingSourcePosition(sourceIndex, sourceLine, sourceCharacter) { + return sourceIndex !== undefined + && sourceLine !== undefined + && sourceCharacter !== undefined + && pendingSourceIndex === sourceIndex + && (pendingSourceLine > sourceLine + || pendingSourceLine === sourceLine && pendingSourceCharacter > sourceCharacter); + } + function addMapping(generatedLine, generatedCharacter, sourceIndex, sourceLine, sourceCharacter, nameIndex) { + ts.Debug.assert(generatedLine >= pendingGeneratedLine, "generatedLine cannot backtrack"); + ts.Debug.assert(generatedCharacter >= 0, "generatedCharacter cannot be negative"); + ts.Debug.assert(sourceIndex === undefined || sourceIndex >= 0, "sourceIndex cannot be negative"); + ts.Debug.assert(sourceLine === undefined || sourceLine >= 0, "sourceLine cannot be negative"); + ts.Debug.assert(sourceCharacter === undefined || sourceCharacter >= 0, "sourceCharacter cannot be negative"); + enter(); + // If this location wasn't recorded or the location in source is going backwards, record the mapping + if (isNewGeneratedPosition(generatedLine, generatedCharacter) || + isBacktrackingSourcePosition(sourceIndex, sourceLine, sourceCharacter)) { + commitPendingMapping(); + pendingGeneratedLine = generatedLine; + pendingGeneratedCharacter = generatedCharacter; + hasPendingSource = false; + hasPendingName = false; + hasPending = true; + } + if (sourceIndex !== undefined && sourceLine !== undefined && sourceCharacter !== undefined) { + pendingSourceIndex = sourceIndex; + pendingSourceLine = sourceLine; + pendingSourceCharacter = sourceCharacter; + hasPendingSource = true; + if (nameIndex !== undefined) { + pendingNameIndex = nameIndex; + hasPendingName = true; + } + } + exit(); + } + function appendSourceMap(generatedLine, generatedCharacter, map, sourceMapPath) { + var _a; + ts.Debug.assert(generatedLine >= pendingGeneratedLine, "generatedLine cannot backtrack"); + ts.Debug.assert(generatedCharacter >= 0, "generatedCharacter cannot be negative"); + enter(); + // First, decode the old component sourcemap + var sourceIndexToNewSourceIndexMap = []; + var nameIndexToNewNameIndexMap; + var mappingIterator = decodeMappings(map.mappings); + for (var _b = mappingIterator.next(), raw = _b.value, done = _b.done; !done; _a = mappingIterator.next(), raw = _a.value, done = _a.done, _a) { + // Then reencode all the updated mappings into the overall map + var newSourceIndex = void 0; + var newSourceLine = void 0; + var newSourceCharacter = void 0; + var newNameIndex = void 0; + if (raw.sourceIndex !== undefined) { + newSourceIndex = sourceIndexToNewSourceIndexMap[raw.sourceIndex]; + if (newSourceIndex === undefined) { + // Apply offsets to each position and fixup source entries + var rawPath = map.sources[raw.sourceIndex]; + var relativePath = map.sourceRoot ? ts.combinePaths(map.sourceRoot, rawPath) : rawPath; + var combinedPath = ts.combinePaths(ts.getDirectoryPath(sourceMapPath), relativePath); + sourceIndexToNewSourceIndexMap[raw.sourceIndex] = newSourceIndex = addSource(combinedPath); + if (map.sourcesContent && typeof map.sourcesContent[raw.sourceIndex] === "string") { + setSourceContent(newSourceIndex, map.sourcesContent[raw.sourceIndex]); + } + } + newSourceLine = raw.sourceLine; + newSourceCharacter = raw.sourceCharacter; + if (map.names && raw.nameIndex !== undefined) { + if (!nameIndexToNewNameIndexMap) + nameIndexToNewNameIndexMap = []; + newNameIndex = nameIndexToNewNameIndexMap[raw.nameIndex]; + if (newNameIndex === undefined) { + nameIndexToNewNameIndexMap[raw.nameIndex] = newNameIndex = addName(map.names[raw.nameIndex]); + } + } + } + var newGeneratedLine = raw.generatedLine + generatedLine; + var newGeneratedCharacter = raw.generatedLine === 0 ? raw.generatedCharacter + generatedCharacter : raw.generatedCharacter; + addMapping(newGeneratedLine, newGeneratedCharacter, newSourceIndex, newSourceLine, newSourceCharacter, newNameIndex); + } + exit(); + } + function shouldCommitMapping() { + return !hasLast + || lastGeneratedLine !== pendingGeneratedLine + || lastGeneratedCharacter !== pendingGeneratedCharacter + || lastSourceIndex !== pendingSourceIndex + || lastSourceLine !== pendingSourceLine + || lastSourceCharacter !== pendingSourceCharacter + || lastNameIndex !== pendingNameIndex; + } + function commitPendingMapping() { + if (!hasPending || !shouldCommitMapping()) { + return; + } + enter(); + // Line/Comma delimiters + if (lastGeneratedLine < pendingGeneratedLine) { + // Emit line delimiters + do { + mappings += ";"; + lastGeneratedLine++; + lastGeneratedCharacter = 0; + } while (lastGeneratedLine < pendingGeneratedLine); + } + else { + ts.Debug.assertEqual(lastGeneratedLine, pendingGeneratedLine, "generatedLine cannot backtrack"); + // Emit comma to separate the entry + if (hasLast) { + mappings += ","; + } + } + // 1. Relative generated character + mappings += base64VLQFormatEncode(pendingGeneratedCharacter - lastGeneratedCharacter); + lastGeneratedCharacter = pendingGeneratedCharacter; + if (hasPendingSource) { + // 2. Relative sourceIndex + mappings += base64VLQFormatEncode(pendingSourceIndex - lastSourceIndex); + lastSourceIndex = pendingSourceIndex; + // 3. Relative source line + mappings += base64VLQFormatEncode(pendingSourceLine - lastSourceLine); + lastSourceLine = pendingSourceLine; + // 4. Relative source character + mappings += base64VLQFormatEncode(pendingSourceCharacter - lastSourceCharacter); + lastSourceCharacter = pendingSourceCharacter; + if (hasPendingName) { + // 5. Relative nameIndex + mappings += base64VLQFormatEncode(pendingNameIndex - lastNameIndex); + lastNameIndex = pendingNameIndex; + } + } + hasLast = true; + exit(); + } + function toJSON() { + commitPendingMapping(); + return { + version: 3, + file: file, + sourceRoot: sourceRoot, + sources: sources, + names: names, + mappings: mappings, + sourcesContent: sourcesContent, + }; + } + } + ts.createSourceMapGenerator = createSourceMapGenerator; + // Sometimes tools can see the following line as a source mapping url comment, so we mangle it a bit (the [M]) + var sourceMapCommentRegExp = /^\/\/[@#] source[M]appingURL=(.+)\s*$/; + var whitespaceOrMapCommentRegExp = /^\s*(\/\/[@#] .*)?$/; + /** + * Tries to find the sourceMappingURL comment at the end of a file. + * @param text The source text of the file. + * @param lineStarts The line starts of the file. + */ + function tryGetSourceMappingURL(text, lineStarts) { + if (lineStarts === void 0) { lineStarts = ts.computeLineStarts(text); } + for (var index = lineStarts.length - 1; index >= 0; index--) { + var line = text.substring(lineStarts[index], lineStarts[index + 1]); + var comment = sourceMapCommentRegExp.exec(line); + if (comment) { + return comment[1]; + } + // If we see a non-whitespace/map comment-like line, break, to avoid scanning up the entire file + else if (!line.match(whitespaceOrMapCommentRegExp)) { + break; + } + } + } + ts.tryGetSourceMappingURL = tryGetSourceMappingURL; + function isStringOrNull(x) { + // tslint:disable-next-line:no-null-keyword + return typeof x === "string" || x === null; + } + function isRawSourceMap(x) { + // tslint:disable-next-line:no-null-keyword + return x !== null + && typeof x === "object" + && x.version === 3 + && typeof x.file === "string" + && typeof x.mappings === "string" + && ts.isArray(x.sources) && ts.every(x.sources, ts.isString) + && (x.sourceRoot === undefined || x.sourceRoot === null || typeof x.sourceRoot === "string") + && (x.sourcesContent === undefined || x.sourcesContent === null || ts.isArray(x.sourcesContent) && ts.every(x.sourcesContent, isStringOrNull)) + && (x.names === undefined || x.names === null || ts.isArray(x.names) && ts.every(x.names, ts.isString)); + } + ts.isRawSourceMap = isRawSourceMap; + function tryParseRawSourceMap(text) { + try { + var parsed = JSON.parse(text); + if (isRawSourceMap(parsed)) { + return parsed; + } + } + catch (_a) { + // empty + } + return undefined; + } + ts.tryParseRawSourceMap = tryParseRawSourceMap; + function decodeMappings(mappings) { + var done = false; + var pos = 0; + var generatedLine = 0; + var generatedCharacter = 0; + var sourceIndex = 0; + var sourceLine = 0; + var sourceCharacter = 0; + var nameIndex = 0; + var error; + return { + get pos() { return pos; }, + get error() { return error; }, + get state() { return captureMapping(/*hasSource*/ true, /*hasName*/ true); }, + next: function () { + while (!done && pos < mappings.length) { + var ch = mappings.charCodeAt(pos); + if (ch === 59 /* semicolon */) { + // new line + generatedLine++; + generatedCharacter = 0; + pos++; + continue; + } + if (ch === 44 /* comma */) { + // Next entry is on same line - no action needed + pos++; + continue; + } + var hasSource = false; + var hasName = false; + generatedCharacter += base64VLQFormatDecode(); + if (hasReportedError()) + return stopIterating(); + if (generatedCharacter < 0) + return setErrorAndStopIterating("Invalid generatedCharacter found"); + if (!isSourceMappingSegmentEnd()) { + hasSource = true; + sourceIndex += base64VLQFormatDecode(); + if (hasReportedError()) + return stopIterating(); + if (sourceIndex < 0) + return setErrorAndStopIterating("Invalid sourceIndex found"); + if (isSourceMappingSegmentEnd()) + return setErrorAndStopIterating("Unsupported Format: No entries after sourceIndex"); + sourceLine += base64VLQFormatDecode(); + if (hasReportedError()) + return stopIterating(); + if (sourceLine < 0) + return setErrorAndStopIterating("Invalid sourceLine found"); + if (isSourceMappingSegmentEnd()) + return setErrorAndStopIterating("Unsupported Format: No entries after sourceLine"); + sourceCharacter += base64VLQFormatDecode(); + if (hasReportedError()) + return stopIterating(); + if (sourceCharacter < 0) + return setErrorAndStopIterating("Invalid sourceCharacter found"); + if (!isSourceMappingSegmentEnd()) { + hasName = true; + nameIndex += base64VLQFormatDecode(); + if (hasReportedError()) + return stopIterating(); + if (nameIndex < 0) + return setErrorAndStopIterating("Invalid nameIndex found"); + if (!isSourceMappingSegmentEnd()) + return setErrorAndStopIterating("Unsupported Error Format: Entries after nameIndex"); + } + } + return { value: captureMapping(hasSource, hasName), done: done }; + } + return stopIterating(); + } + }; + function captureMapping(hasSource, hasName) { + return { + generatedLine: generatedLine, + generatedCharacter: generatedCharacter, + sourceIndex: hasSource ? sourceIndex : undefined, + sourceLine: hasSource ? sourceLine : undefined, + sourceCharacter: hasSource ? sourceCharacter : undefined, + nameIndex: hasName ? nameIndex : undefined + }; + } + function stopIterating() { + done = true; + return { value: undefined, done: true }; + } + function setError(message) { + if (error === undefined) { + error = message; + } + } + function setErrorAndStopIterating(message) { + setError(message); + return stopIterating(); + } + function hasReportedError() { + return error !== undefined; + } + function isSourceMappingSegmentEnd() { + return (pos === mappings.length || + mappings.charCodeAt(pos) === 44 /* comma */ || + mappings.charCodeAt(pos) === 59 /* semicolon */); + } + function base64VLQFormatDecode() { + var moreDigits = true; + var shiftCount = 0; + var value = 0; + for (; moreDigits; pos++) { + if (pos >= mappings.length) + return setError("Error in decoding base64VLQFormatDecode, past the mapping string"), -1; + // 6 digit number + var currentByte = base64FormatDecode(mappings.charCodeAt(pos)); + if (currentByte === -1) + return setError("Invalid character in VLQ"), -1; + // If msb is set, we still have more bits to continue + moreDigits = (currentByte & 32) !== 0; + // least significant 5 bits are the next msbs in the final value. + value = value | ((currentByte & 31) << shiftCount); + shiftCount += 5; + } + // Least significant bit if 1 represents negative and rest of the msb is actual absolute value + if ((value & 1) === 0) { + // + number + value = value >> 1; + } + else { + // - number + value = value >> 1; + value = -value; + } + return value; + } + } + ts.decodeMappings = decodeMappings; + function sameMapping(left, right) { + return left === right + || left.generatedLine === right.generatedLine + && left.generatedCharacter === right.generatedCharacter + && left.sourceIndex === right.sourceIndex + && left.sourceLine === right.sourceLine + && left.sourceCharacter === right.sourceCharacter + && left.nameIndex === right.nameIndex; + } + ts.sameMapping = sameMapping; + function isSourceMapping(mapping) { + return mapping.sourceIndex !== undefined + && mapping.sourceLine !== undefined + && mapping.sourceCharacter !== undefined; + } + ts.isSourceMapping = isSourceMapping; + function base64FormatEncode(value) { + return value >= 0 && value < 26 ? 65 /* A */ + value : + value >= 26 && value < 52 ? 97 /* a */ + value - 26 : + value >= 52 && value < 62 ? 48 /* _0 */ + value - 52 : + value === 62 ? 43 /* plus */ : + value === 63 ? 47 /* slash */ : + ts.Debug.fail(value + ": not a base64 value"); + } + function base64FormatDecode(ch) { + return ch >= 65 /* A */ && ch <= 90 /* Z */ ? ch - 65 /* A */ : + ch >= 97 /* a */ && ch <= 122 /* z */ ? ch - 97 /* a */ + 26 : + ch >= 48 /* _0 */ && ch <= 57 /* _9 */ ? ch - 48 /* _0 */ + 52 : + ch === 43 /* plus */ ? 62 : + ch === 47 /* slash */ ? 63 : + -1; + } + function base64VLQFormatEncode(inValue) { + // Add a new least significant bit that has the sign of the value. + // if negative number the least significant bit that gets added to the number has value 1 + // else least significant bit value that gets added is 0 + // eg. -1 changes to binary : 01 [1] => 3 + // +1 changes to binary : 01 [0] => 2 + if (inValue < 0) { + inValue = ((-inValue) << 1) + 1; + } + else { + inValue = inValue << 1; + } + // Encode 5 bits at a time starting from least significant bits + var encodedStr = ""; + do { + var currentDigit = inValue & 31; // 11111 + inValue = inValue >> 5; + if (inValue > 0) { + // There are still more digits to decode, set the msb (6th bit) + currentDigit = currentDigit | 32; + } + encodedStr = encodedStr + String.fromCharCode(base64FormatEncode(currentDigit)); + } while (inValue > 0); + return encodedStr; + } + function isSourceMappedPosition(value) { + return value.sourceIndex !== undefined + && value.sourcePosition !== undefined; + } + function sameMappedPosition(left, right) { + return left.generatedPosition === right.generatedPosition + && left.sourceIndex === right.sourceIndex + && left.sourcePosition === right.sourcePosition; + } + function compareSourcePositions(left, right) { + return ts.compareValues(left.sourceIndex, right.sourceIndex); + } + function compareGeneratedPositions(left, right) { + return ts.compareValues(left.generatedPosition, right.generatedPosition); + } + function getSourcePositionOfMapping(value) { + return value.sourcePosition; + } + function getGeneratedPositionOfMapping(value) { + return value.generatedPosition; + } + function createDocumentPositionMapper(host, map, mapPath) { + var mapDirectory = ts.getDirectoryPath(mapPath); + var sourceRoot = map.sourceRoot ? ts.getNormalizedAbsolutePath(map.sourceRoot, mapDirectory) : mapDirectory; + var generatedAbsoluteFilePath = ts.getNormalizedAbsolutePath(map.file, mapDirectory); + var generatedCanonicalFilePath = host.getCanonicalFileName(generatedAbsoluteFilePath); + var generatedFile = host.getSourceFileLike(generatedCanonicalFilePath); + var sourceFileAbsolutePaths = map.sources.map(function (source) { return ts.getNormalizedAbsolutePath(source, sourceRoot); }); + var sourceFileCanonicalPaths = sourceFileAbsolutePaths.map(function (source) { return host.getCanonicalFileName(source); }); + var sourceToSourceIndexMap = ts.createMapFromEntries(sourceFileCanonicalPaths.map(function (source, i) { return [source, i]; })); + var decodedMappings; + var generatedMappings; + var sourceMappings; + return { + getSourcePosition: getSourcePosition, + getGeneratedPosition: getGeneratedPosition + }; + function processMapping(mapping) { + var generatedPosition = generatedFile !== undefined + ? ts.getPositionOfLineAndCharacterWithEdits(generatedFile, mapping.generatedLine, mapping.generatedCharacter) + : -1; + var source; + var sourcePosition; + if (isSourceMapping(mapping)) { + var sourceFilePath = sourceFileCanonicalPaths[mapping.sourceIndex]; + var sourceFile = host.getSourceFileLike(sourceFilePath); + source = map.sources[mapping.sourceIndex]; + sourcePosition = sourceFile !== undefined + ? ts.getPositionOfLineAndCharacterWithEdits(sourceFile, mapping.sourceLine, mapping.sourceCharacter) + : -1; + } + return { + generatedPosition: generatedPosition, + source: source, + sourceIndex: mapping.sourceIndex, + sourcePosition: sourcePosition, + nameIndex: mapping.nameIndex + }; + } + function getDecodedMappings() { + if (decodedMappings === undefined) { + var decoder = decodeMappings(map.mappings); + var mappings = ts.arrayFrom(decoder, processMapping); + if (decoder.error !== undefined) { + if (host.log) { + host.log("Encountered error while decoding sourcemap: " + decoder.error); + } + decodedMappings = ts.emptyArray; + } + else { + decodedMappings = mappings; + } + } + return decodedMappings; + } + function getSourceMappings(sourceIndex) { + if (sourceMappings === undefined) { + var lists = []; + for (var _i = 0, _a = getDecodedMappings(); _i < _a.length; _i++) { + var mapping = _a[_i]; + if (!isSourceMappedPosition(mapping)) + continue; + var list = lists[mapping.sourceIndex]; + if (!list) + lists[mapping.sourceIndex] = list = []; + list.push(mapping); + } + sourceMappings = lists.map(function (list) { return ts.sortAndDeduplicate(list, compareSourcePositions, sameMappedPosition); }); + } + return sourceMappings[sourceIndex]; + } + function getGeneratedMappings() { + if (generatedMappings === undefined) { + var list = []; + for (var _i = 0, _a = getDecodedMappings(); _i < _a.length; _i++) { + var mapping = _a[_i]; + list.push(mapping); + } + generatedMappings = ts.sortAndDeduplicate(list, compareGeneratedPositions, sameMappedPosition); + } + return generatedMappings; + } + function getGeneratedPosition(loc) { + var sourceIndex = sourceToSourceIndexMap.get(host.getCanonicalFileName(loc.fileName)); + if (sourceIndex === undefined) + return loc; + var sourceMappings = getSourceMappings(sourceIndex); + if (!ts.some(sourceMappings)) + return loc; + var targetIndex = ts.binarySearchKey(sourceMappings, loc.pos, getSourcePositionOfMapping, ts.compareValues); + if (targetIndex < 0) { + // if no exact match, closest is 2's complement of result + targetIndex = ~targetIndex; + } + var mapping = sourceMappings[targetIndex]; + if (mapping === undefined || mapping.sourceIndex !== sourceIndex) { + return loc; + } + return { fileName: generatedAbsoluteFilePath, pos: mapping.generatedPosition }; // Closest pos + } + function getSourcePosition(loc) { + var generatedMappings = getGeneratedMappings(); + if (!ts.some(generatedMappings)) + return loc; + var targetIndex = ts.binarySearchKey(generatedMappings, loc.pos, getGeneratedPositionOfMapping, ts.compareValues); + if (targetIndex < 0) { + // if no exact match, closest is 2's complement of result + targetIndex = ~targetIndex; + } + var mapping = generatedMappings[targetIndex]; + if (mapping === undefined || !isSourceMappedPosition(mapping)) { + return loc; + } + return { fileName: sourceFileAbsolutePaths[mapping.sourceIndex], pos: mapping.sourcePosition }; // Closest pos + } + } + ts.createDocumentPositionMapper = createDocumentPositionMapper; + ts.identitySourceMapConsumer = { + getSourcePosition: ts.identity, + getGeneratedPosition: ts.identity + }; +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + function getOriginalNodeId(node) { + node = ts.getOriginalNode(node); + return node ? ts.getNodeId(node) : 0; + } + ts.getOriginalNodeId = getOriginalNodeId; + function containsDefaultReference(node) { + if (!node) + return false; + if (!ts.isNamedImports(node)) + return false; + return ts.some(node.elements, isNamedDefaultReference); + } + function isNamedDefaultReference(e) { + return e.propertyName !== undefined && e.propertyName.escapedText === "default" /* Default */; + } + function chainBundle(transformSourceFile) { + return transformSourceFileOrBundle; + function transformSourceFileOrBundle(node) { + return node.kind === 279 /* SourceFile */ ? transformSourceFile(node) : transformBundle(node); + } + function transformBundle(node) { + return ts.createBundle(ts.map(node.sourceFiles, transformSourceFile), node.prepends); + } + } + ts.chainBundle = chainBundle; + function getImportNeedsImportStarHelper(node) { + if (!!ts.getNamespaceDeclarationNode(node)) { + return true; + } + var bindings = node.importClause && node.importClause.namedBindings; + if (!bindings) { + return false; + } + if (!ts.isNamedImports(bindings)) + return false; + var defaultRefCount = 0; + for (var _i = 0, _a = bindings.elements; _i < _a.length; _i++) { + var binding = _a[_i]; + if (isNamedDefaultReference(binding)) { + defaultRefCount++; + } + } + // Import star is required if there's default named refs mixed with non-default refs, or if theres non-default refs and it has a default import + return (defaultRefCount > 0 && defaultRefCount !== bindings.elements.length) || (!!(bindings.elements.length - defaultRefCount) && ts.isDefaultImport(node)); + } + ts.getImportNeedsImportStarHelper = getImportNeedsImportStarHelper; + function getImportNeedsImportDefaultHelper(node) { + // Import default is needed if there's a default import or a default ref and no other refs (meaning an import star helper wasn't requested) + return !getImportNeedsImportStarHelper(node) && (ts.isDefaultImport(node) || (!!node.importClause && ts.isNamedImports(node.importClause.namedBindings) && containsDefaultReference(node.importClause.namedBindings))); // TODO: GH#18217 + } + ts.getImportNeedsImportDefaultHelper = getImportNeedsImportDefaultHelper; + function collectExternalModuleInfo(sourceFile, resolver, compilerOptions) { + var externalImports = []; + var exportSpecifiers = ts.createMultiMap(); + var exportedBindings = []; + var uniqueExports = ts.createMap(); + var exportedNames; + var hasExportDefault = false; + var exportEquals; + var hasExportStarsToExportValues = false; + var hasImportStarOrImportDefault = false; + for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { + var node = _a[_i]; + switch (node.kind) { + case 249 /* ImportDeclaration */: + // import "mod" + // import x from "mod" + // import * as x from "mod" + // import { x, y } from "mod" + externalImports.push(node); + hasImportStarOrImportDefault = hasImportStarOrImportDefault || getImportNeedsImportStarHelper(node) || getImportNeedsImportDefaultHelper(node); + break; + case 248 /* ImportEqualsDeclaration */: + if (node.moduleReference.kind === 259 /* ExternalModuleReference */) { + // import x = require("mod") + externalImports.push(node); + } + break; + case 255 /* ExportDeclaration */: + if (node.moduleSpecifier) { + if (!node.exportClause) { + // export * from "mod" + externalImports.push(node); + hasExportStarsToExportValues = true; + } + else { + // export { x, y } from "mod" + externalImports.push(node); + } + } + else { + // export { x, y } + for (var _b = 0, _c = node.exportClause.elements; _b < _c.length; _b++) { + var specifier = _c[_b]; + if (!uniqueExports.get(ts.idText(specifier.name))) { + var name = specifier.propertyName || specifier.name; + exportSpecifiers.add(ts.idText(name), specifier); + var decl = resolver.getReferencedImportDeclaration(name) + || resolver.getReferencedValueDeclaration(name); + if (decl) { + multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(decl), specifier.name); + } + uniqueExports.set(ts.idText(specifier.name), true); + exportedNames = ts.append(exportedNames, specifier.name); + } + } + } + break; + case 254 /* ExportAssignment */: + if (node.isExportEquals && !exportEquals) { + // export = x + exportEquals = node; + } + break; + case 219 /* VariableStatement */: + if (ts.hasModifier(node, 1 /* Export */)) { + for (var _d = 0, _e = node.declarationList.declarations; _d < _e.length; _d++) { + var decl = _e[_d]; + exportedNames = collectExportedVariableInfo(decl, uniqueExports, exportedNames); + } + } + break; + case 239 /* FunctionDeclaration */: + if (ts.hasModifier(node, 1 /* Export */)) { + if (ts.hasModifier(node, 512 /* Default */)) { + // export default function() { } + if (!hasExportDefault) { + multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), ts.getDeclarationName(node)); + hasExportDefault = true; + } + } + else { + // export function x() { } + var name = node.name; + if (!uniqueExports.get(ts.idText(name))) { + multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), name); + uniqueExports.set(ts.idText(name), true); + exportedNames = ts.append(exportedNames, name); + } + } + } + break; + case 240 /* ClassDeclaration */: + if (ts.hasModifier(node, 1 /* Export */)) { + if (ts.hasModifier(node, 512 /* Default */)) { + // export default class { } + if (!hasExportDefault) { + multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), ts.getDeclarationName(node)); + hasExportDefault = true; + } + } + else { + // export class x { } + var name = node.name; + if (name && !uniqueExports.get(ts.idText(name))) { + multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), name); + uniqueExports.set(ts.idText(name), true); + exportedNames = ts.append(exportedNames, name); + } + } + } + break; + } + } + var externalHelpersModuleName = ts.getOrCreateExternalHelpersModuleNameIfNeeded(sourceFile, compilerOptions, hasExportStarsToExportValues, hasImportStarOrImportDefault); + var externalHelpersImportDeclaration = externalHelpersModuleName && ts.createImportDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(externalHelpersModuleName)), ts.createLiteral(ts.externalHelpersModuleNameText)); + if (externalHelpersImportDeclaration) { + ts.addEmitFlags(externalHelpersImportDeclaration, 67108864 /* NeverApplyImportHelper */); + externalImports.unshift(externalHelpersImportDeclaration); + } + return { externalImports: externalImports, exportSpecifiers: exportSpecifiers, exportEquals: exportEquals, hasExportStarsToExportValues: hasExportStarsToExportValues, exportedBindings: exportedBindings, exportedNames: exportedNames, externalHelpersImportDeclaration: externalHelpersImportDeclaration }; + } + ts.collectExternalModuleInfo = collectExternalModuleInfo; + function collectExportedVariableInfo(decl, uniqueExports, exportedNames) { + if (ts.isBindingPattern(decl.name)) { + for (var _i = 0, _a = decl.name.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (!ts.isOmittedExpression(element)) { + exportedNames = collectExportedVariableInfo(element, uniqueExports, exportedNames); + } + } + } + else if (!ts.isGeneratedIdentifier(decl.name)) { + var text = ts.idText(decl.name); + if (!uniqueExports.get(text)) { + uniqueExports.set(text, true); + exportedNames = ts.append(exportedNames, decl.name); + } + } + return exportedNames; + } + /** Use a sparse array as a multi-map. */ + function multiMapSparseArrayAdd(map, key, value) { + var values = map[key]; + if (values) { + values.push(value); + } + else { + map[key] = values = [value]; + } + return values; + } + /** + * Used in the module transformer to check if an expression is reasonably without sideeffect, + * and thus better to copy into multiple places rather than to cache in a temporary variable + * - this is mostly subjective beyond the requirement that the expression not be sideeffecting + */ + function isSimpleCopiableExpression(expression) { + return ts.isStringLiteralLike(expression) || + expression.kind === 8 /* NumericLiteral */ || + ts.isKeyword(expression.kind) || + ts.isIdentifier(expression); + } + ts.isSimpleCopiableExpression = isSimpleCopiableExpression; + /** + * @param input Template string input strings + * @param args Names which need to be made file-level unique + */ + function helperString(input) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + return function (uniqueName) { + var result = ""; + for (var i = 0; i < args.length; i++) { + result += input[i]; + result += uniqueName(args[i]); + } + result += input[input.length - 1]; + return result; + }; + } + ts.helperString = helperString; +})(ts || (ts = {})); +/*@internal*/ +var ts; +(function (ts) { + var FlattenLevel; + (function (FlattenLevel) { + FlattenLevel[FlattenLevel["All"] = 0] = "All"; + FlattenLevel[FlattenLevel["ObjectRest"] = 1] = "ObjectRest"; + })(FlattenLevel = ts.FlattenLevel || (ts.FlattenLevel = {})); + /** + * Flattens a DestructuringAssignment or a VariableDeclaration to an expression. + * + * @param node The node to flatten. + * @param visitor An optional visitor used to visit initializers. + * @param context The transformation context. + * @param level Indicates the extent to which flattening should occur. + * @param needsValue An optional value indicating whether the value from the right-hand-side of + * the destructuring assignment is needed as part of a larger expression. + * @param createAssignmentCallback An optional callback used to create the assignment expression. + */ + function flattenDestructuringAssignment(node, visitor, context, level, needsValue, createAssignmentCallback) { + var location = node; + var value; + if (ts.isDestructuringAssignment(node)) { + value = node.right; + while (ts.isEmptyArrayLiteral(node.left) || ts.isEmptyObjectLiteral(node.left)) { + if (ts.isDestructuringAssignment(value)) { + location = node = value; + value = node.right; + } + else { + return ts.visitNode(value, visitor, ts.isExpression); + } + } + } + var expressions; + var flattenContext = { + context: context, + level: level, + downlevelIteration: !!context.getCompilerOptions().downlevelIteration, + hoistTempVariables: true, + emitExpression: emitExpression, + emitBindingOrAssignment: emitBindingOrAssignment, + createArrayBindingOrAssignmentPattern: makeArrayAssignmentPattern, + createObjectBindingOrAssignmentPattern: makeObjectAssignmentPattern, + createArrayBindingOrAssignmentElement: makeAssignmentElement, + visitor: visitor + }; + if (value) { + value = ts.visitNode(value, visitor, ts.isExpression); + if (ts.isIdentifier(value) && bindingOrAssignmentElementAssignsToName(node, value.escapedText)) { + // If the right-hand value of the assignment is also an assignment target then + // we need to cache the right-hand value. + value = ensureIdentifier(flattenContext, value, /*reuseIdentifierExpressions*/ false, location); + } + else if (needsValue) { + // If the right-hand value of the destructuring assignment needs to be preserved (as + // is the case when the destructuring assignment is part of a larger expression), + // then we need to cache the right-hand value. + // + // The source map location for the assignment should point to the entire binary + // expression. + value = ensureIdentifier(flattenContext, value, /*reuseIdentifierExpressions*/ true, location); + } + else if (ts.nodeIsSynthesized(node)) { + // Generally, the source map location for a destructuring assignment is the root + // expression. + // + // However, if the root expression is synthesized (as in the case + // of the initializer when transforming a ForOfStatement), then the source map + // location should point to the right-hand value of the expression. + location = value; + } + } + flattenBindingOrAssignmentElement(flattenContext, node, value, location, /*skipInitializer*/ ts.isDestructuringAssignment(node)); + if (value && needsValue) { + if (!ts.some(expressions)) { + return value; + } + expressions.push(value); + } + return ts.aggregateTransformFlags(ts.inlineExpressions(expressions)) || ts.createOmittedExpression(); + function emitExpression(expression) { + // NOTE: this completely disables source maps, but aligns with the behavior of + // `emitAssignment` in the old emitter. + ts.setEmitFlags(expression, 64 /* NoNestedSourceMaps */); + ts.aggregateTransformFlags(expression); + expressions = ts.append(expressions, expression); + } + function emitBindingOrAssignment(target, value, location, original) { + ts.Debug.assertNode(target, createAssignmentCallback ? ts.isIdentifier : ts.isExpression); + var expression = createAssignmentCallback + ? createAssignmentCallback(target, value, location) + : ts.setTextRange(ts.createAssignment(ts.visitNode(target, visitor, ts.isExpression), value), location); + expression.original = original; + emitExpression(expression); + } + } + ts.flattenDestructuringAssignment = flattenDestructuringAssignment; + function bindingOrAssignmentElementAssignsToName(element, escapedName) { + var target = ts.getTargetOfBindingOrAssignmentElement(element); // TODO: GH#18217 + if (ts.isBindingOrAssignmentPattern(target)) { + return bindingOrAssignmentPatternAssignsToName(target, escapedName); + } + else if (ts.isIdentifier(target)) { + return target.escapedText === escapedName; + } + return false; + } + function bindingOrAssignmentPatternAssignsToName(pattern, escapedName) { + var elements = ts.getElementsOfBindingOrAssignmentPattern(pattern); + for (var _i = 0, elements_3 = elements; _i < elements_3.length; _i++) { + var element = elements_3[_i]; + if (bindingOrAssignmentElementAssignsToName(element, escapedName)) { + return true; + } + } + return false; + } + /** + * Flattens a VariableDeclaration or ParameterDeclaration to one or more variable declarations. + * + * @param node The node to flatten. + * @param visitor An optional visitor used to visit initializers. + * @param context The transformation context. + * @param boundValue The value bound to the declaration. + * @param skipInitializer A value indicating whether to ignore the initializer of `node`. + * @param hoistTempVariables Indicates whether temporary variables should not be recorded in-line. + * @param level Indicates the extent to which flattening should occur. + */ + function flattenDestructuringBinding(node, visitor, context, level, rval, hoistTempVariables, skipInitializer) { + if (hoistTempVariables === void 0) { hoistTempVariables = false; } + var pendingExpressions; + var pendingDeclarations = []; + var declarations = []; + var flattenContext = { + context: context, + level: level, + downlevelIteration: !!context.getCompilerOptions().downlevelIteration, + hoistTempVariables: hoistTempVariables, + emitExpression: emitExpression, + emitBindingOrAssignment: emitBindingOrAssignment, + createArrayBindingOrAssignmentPattern: makeArrayBindingPattern, + createObjectBindingOrAssignmentPattern: makeObjectBindingPattern, + createArrayBindingOrAssignmentElement: makeBindingElement, + visitor: visitor + }; + if (ts.isVariableDeclaration(node)) { + var initializer = ts.getInitializerOfBindingOrAssignmentElement(node); + if (initializer && ts.isIdentifier(initializer) && bindingOrAssignmentElementAssignsToName(node, initializer.escapedText)) { + // If the right-hand value of the assignment is also an assignment target then + // we need to cache the right-hand value. + initializer = ensureIdentifier(flattenContext, initializer, /*reuseIdentifierExpressions*/ false, initializer); + node = ts.updateVariableDeclaration(node, node.name, node.type, initializer); + } + } + flattenBindingOrAssignmentElement(flattenContext, node, rval, node, skipInitializer); + if (pendingExpressions) { + var temp = ts.createTempVariable(/*recordTempVariable*/ undefined); + if (hoistTempVariables) { + var value = ts.inlineExpressions(pendingExpressions); + pendingExpressions = undefined; + emitBindingOrAssignment(temp, value, /*location*/ undefined, /*original*/ undefined); + } + else { + context.hoistVariableDeclaration(temp); + var pendingDeclaration = ts.last(pendingDeclarations); + pendingDeclaration.pendingExpressions = ts.append(pendingDeclaration.pendingExpressions, ts.createAssignment(temp, pendingDeclaration.value)); + ts.addRange(pendingDeclaration.pendingExpressions, pendingExpressions); + pendingDeclaration.value = temp; + } + } + for (var _i = 0, pendingDeclarations_1 = pendingDeclarations; _i < pendingDeclarations_1.length; _i++) { + var _a = pendingDeclarations_1[_i], pendingExpressions_1 = _a.pendingExpressions, name = _a.name, value = _a.value, location = _a.location, original = _a.original; + var variable = ts.createVariableDeclaration(name, + /*type*/ undefined, pendingExpressions_1 ? ts.inlineExpressions(ts.append(pendingExpressions_1, value)) : value); + variable.original = original; + ts.setTextRange(variable, location); + if (ts.isIdentifier(name)) { + ts.setEmitFlags(variable, 64 /* NoNestedSourceMaps */); + } + ts.aggregateTransformFlags(variable); + declarations.push(variable); + } + return declarations; + function emitExpression(value) { + pendingExpressions = ts.append(pendingExpressions, value); + } + function emitBindingOrAssignment(target, value, location, original) { + ts.Debug.assertNode(target, ts.isBindingName); + if (pendingExpressions) { + value = ts.inlineExpressions(ts.append(pendingExpressions, value)); + pendingExpressions = undefined; + } + pendingDeclarations.push({ pendingExpressions: pendingExpressions, name: target, value: value, location: location, original: original }); + } + } + ts.flattenDestructuringBinding = flattenDestructuringBinding; + /** + * Flattens a BindingOrAssignmentElement into zero or more bindings or assignments. + * + * @param flattenContext Options used to control flattening. + * @param element The element to flatten. + * @param value The current RHS value to assign to the element. + * @param location The location to use for source maps and comments. + * @param skipInitializer An optional value indicating whether to include the initializer + * for the element. + */ + function flattenBindingOrAssignmentElement(flattenContext, element, value, location, skipInitializer) { + if (!skipInitializer) { + var initializer = ts.visitNode(ts.getInitializerOfBindingOrAssignmentElement(element), flattenContext.visitor, ts.isExpression); + if (initializer) { + // Combine value and initializer + value = value ? createDefaultValueCheck(flattenContext, value, initializer, location) : initializer; + } + else if (!value) { + // Use 'void 0' in absence of value and initializer + value = ts.createVoidZero(); + } + } + var bindingTarget = ts.getTargetOfBindingOrAssignmentElement(element); // TODO: GH#18217 + if (ts.isObjectBindingOrAssignmentPattern(bindingTarget)) { + flattenObjectBindingOrAssignmentPattern(flattenContext, element, bindingTarget, value, location); + } + else if (ts.isArrayBindingOrAssignmentPattern(bindingTarget)) { + flattenArrayBindingOrAssignmentPattern(flattenContext, element, bindingTarget, value, location); + } + else { + flattenContext.emitBindingOrAssignment(bindingTarget, value, location, /*original*/ element); // TODO: GH#18217 + } + } + /** + * Flattens an ObjectBindingOrAssignmentPattern into zero or more bindings or assignments. + * + * @param flattenContext Options used to control flattening. + * @param parent The parent element of the pattern. + * @param pattern The ObjectBindingOrAssignmentPattern to flatten. + * @param value The current RHS value to assign to the element. + * @param location The location to use for source maps and comments. + */ + function flattenObjectBindingOrAssignmentPattern(flattenContext, parent, pattern, value, location) { + var elements = ts.getElementsOfBindingOrAssignmentPattern(pattern); + var numElements = elements.length; + if (numElements !== 1) { + // For anything other than a single-element destructuring we need to generate a temporary + // to ensure value is evaluated exactly once. Additionally, if we have zero elements + // we need to emit *something* to ensure that in case a 'var' keyword was already emitted, + // so in that case, we'll intentionally create that temporary. + var reuseIdentifierExpressions = !ts.isDeclarationBindingElement(parent) || numElements !== 0; + value = ensureIdentifier(flattenContext, value, reuseIdentifierExpressions, location); + } + var bindingElements; + var computedTempVariables; + for (var i = 0; i < numElements; i++) { + var element = elements[i]; + if (!ts.getRestIndicatorOfBindingOrAssignmentElement(element)) { + var propertyName = ts.getPropertyNameOfBindingOrAssignmentElement(element); + if (flattenContext.level >= 1 /* ObjectRest */ + && !(element.transformFlags & (131072 /* ContainsRestOrSpread */ | 262144 /* ContainsObjectRestOrSpread */)) + && !(ts.getTargetOfBindingOrAssignmentElement(element).transformFlags & (131072 /* ContainsRestOrSpread */ | 262144 /* ContainsObjectRestOrSpread */)) + && !ts.isComputedPropertyName(propertyName)) { + bindingElements = ts.append(bindingElements, element); + } + else { + if (bindingElements) { + flattenContext.emitBindingOrAssignment(flattenContext.createObjectBindingOrAssignmentPattern(bindingElements), value, location, pattern); + bindingElements = undefined; + } + var rhsValue = createDestructuringPropertyAccess(flattenContext, value, propertyName); + if (ts.isComputedPropertyName(propertyName)) { + computedTempVariables = ts.append(computedTempVariables, rhsValue.argumentExpression); + } + flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, /*location*/ element); + } + } + else if (i === numElements - 1) { + if (bindingElements) { + flattenContext.emitBindingOrAssignment(flattenContext.createObjectBindingOrAssignmentPattern(bindingElements), value, location, pattern); + bindingElements = undefined; + } + var rhsValue = createRestCall(flattenContext.context, value, elements, computedTempVariables, pattern); // TODO: GH#18217 + flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, element); + } + } + if (bindingElements) { + flattenContext.emitBindingOrAssignment(flattenContext.createObjectBindingOrAssignmentPattern(bindingElements), value, location, pattern); + } + } + /** + * Flattens an ArrayBindingOrAssignmentPattern into zero or more bindings or assignments. + * + * @param flattenContext Options used to control flattening. + * @param parent The parent element of the pattern. + * @param pattern The ArrayBindingOrAssignmentPattern to flatten. + * @param value The current RHS value to assign to the element. + * @param location The location to use for source maps and comments. + */ + function flattenArrayBindingOrAssignmentPattern(flattenContext, parent, pattern, value, location) { + var elements = ts.getElementsOfBindingOrAssignmentPattern(pattern); + var numElements = elements.length; + if (flattenContext.level < 1 /* ObjectRest */ && flattenContext.downlevelIteration) { + // Read the elements of the iterable into an array + value = ensureIdentifier(flattenContext, ts.createReadHelper(flattenContext.context, value, numElements > 0 && ts.getRestIndicatorOfBindingOrAssignmentElement(elements[numElements - 1]) + ? undefined + : numElements, location), + /*reuseIdentifierExpressions*/ false, location); + } + else if (numElements !== 1 && (flattenContext.level < 1 /* ObjectRest */ || numElements === 0) + || ts.every(elements, ts.isOmittedExpression)) { + // For anything other than a single-element destructuring we need to generate a temporary + // to ensure value is evaluated exactly once. Additionally, if we have zero elements + // we need to emit *something* to ensure that in case a 'var' keyword was already emitted, + // so in that case, we'll intentionally create that temporary. + // Or all the elements of the binding pattern are omitted expression such as "var [,] = [1,2]", + // then we will create temporary variable. + var reuseIdentifierExpressions = !ts.isDeclarationBindingElement(parent) || numElements !== 0; + value = ensureIdentifier(flattenContext, value, reuseIdentifierExpressions, location); + } + var bindingElements; + var restContainingElements; + for (var i = 0; i < numElements; i++) { + var element = elements[i]; + if (flattenContext.level >= 1 /* ObjectRest */) { + // If an array pattern contains an ObjectRest, we must cache the result so that we + // can perform the ObjectRest destructuring in a different declaration + if (element.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { + var temp = ts.createTempVariable(/*recordTempVariable*/ undefined); + if (flattenContext.hoistTempVariables) { + flattenContext.context.hoistVariableDeclaration(temp); + } + restContainingElements = ts.append(restContainingElements, [temp, element]); + bindingElements = ts.append(bindingElements, flattenContext.createArrayBindingOrAssignmentElement(temp)); + } + else { + bindingElements = ts.append(bindingElements, element); + } + } + else if (ts.isOmittedExpression(element)) { + continue; + } + else if (!ts.getRestIndicatorOfBindingOrAssignmentElement(element)) { + var rhsValue = ts.createElementAccess(value, i); + flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, /*location*/ element); + } + else if (i === numElements - 1) { + var rhsValue = ts.createArraySlice(value, i); + flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, /*location*/ element); + } + } + if (bindingElements) { + flattenContext.emitBindingOrAssignment(flattenContext.createArrayBindingOrAssignmentPattern(bindingElements), value, location, pattern); + } + if (restContainingElements) { + for (var _i = 0, restContainingElements_1 = restContainingElements; _i < restContainingElements_1.length; _i++) { + var _a = restContainingElements_1[_i], id = _a[0], element = _a[1]; + flattenBindingOrAssignmentElement(flattenContext, element, id, element); + } + } + } + /** + * Creates an expression used to provide a default value if a value is `undefined` at runtime. + * + * @param flattenContext Options used to control flattening. + * @param value The RHS value to test. + * @param defaultValue The default value to use if `value` is `undefined` at runtime. + * @param location The location to use for source maps and comments. + */ + function createDefaultValueCheck(flattenContext, value, defaultValue, location) { + value = ensureIdentifier(flattenContext, value, /*reuseIdentifierExpressions*/ true, location); + return ts.createConditional(ts.createTypeCheck(value, "undefined"), defaultValue, value); + } + /** + * Creates either a PropertyAccessExpression or an ElementAccessExpression for the + * right-hand side of a transformed destructuring assignment. + * + * @link https://tc39.github.io/ecma262/#sec-runtime-semantics-keyeddestructuringassignmentevaluation + * + * @param flattenContext Options used to control flattening. + * @param value The RHS value that is the source of the property. + * @param propertyName The destructuring property name. + */ + function createDestructuringPropertyAccess(flattenContext, value, propertyName) { + if (ts.isComputedPropertyName(propertyName)) { + var argumentExpression = ensureIdentifier(flattenContext, ts.visitNode(propertyName.expression, flattenContext.visitor), /*reuseIdentifierExpressions*/ false, /*location*/ propertyName); + return ts.createElementAccess(value, argumentExpression); + } + else if (ts.isStringOrNumericLiteralLike(propertyName)) { + var argumentExpression = ts.getSynthesizedClone(propertyName); + argumentExpression.text = argumentExpression.text; + return ts.createElementAccess(value, argumentExpression); + } + else { + var name = ts.createIdentifier(ts.idText(propertyName)); + return ts.createPropertyAccess(value, name); + } + } + /** + * Ensures that there exists a declared identifier whose value holds the given expression. + * This function is useful to ensure that the expression's value can be read from in subsequent expressions. + * Unless 'reuseIdentifierExpressions' is false, 'value' will be returned if it is just an identifier. + * + * @param flattenContext Options used to control flattening. + * @param value the expression whose value needs to be bound. + * @param reuseIdentifierExpressions true if identifier expressions can simply be returned; + * false if it is necessary to always emit an identifier. + * @param location The location to use for source maps and comments. + */ + function ensureIdentifier(flattenContext, value, reuseIdentifierExpressions, location) { + if (ts.isIdentifier(value) && reuseIdentifierExpressions) { + return value; + } + else { + var temp = ts.createTempVariable(/*recordTempVariable*/ undefined); + if (flattenContext.hoistTempVariables) { + flattenContext.context.hoistVariableDeclaration(temp); + flattenContext.emitExpression(ts.setTextRange(ts.createAssignment(temp, value), location)); + } + else { + flattenContext.emitBindingOrAssignment(temp, value, location, /*original*/ undefined); + } + return temp; + } + } + function makeArrayBindingPattern(elements) { + ts.Debug.assertEachNode(elements, ts.isArrayBindingElement); + return ts.createArrayBindingPattern(elements); + } + function makeArrayAssignmentPattern(elements) { + return ts.createArrayLiteral(ts.map(elements, ts.convertToArrayAssignmentElement)); + } + function makeObjectBindingPattern(elements) { + ts.Debug.assertEachNode(elements, ts.isBindingElement); + return ts.createObjectBindingPattern(elements); + } + function makeObjectAssignmentPattern(elements) { + return ts.createObjectLiteral(ts.map(elements, ts.convertToObjectAssignmentElement)); + } + function makeBindingElement(name) { + return ts.createBindingElement(/*dotDotDotToken*/ undefined, /*propertyName*/ undefined, name); + } + function makeAssignmentElement(name) { + return name; + } + var restHelper = { + name: "typescript:rest", + scoped: false, + text: "\n var __rest = (this && this.__rest) || function (s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) if (e.indexOf(p[i]) < 0)\n t[p[i]] = s[p[i]];\n return t;\n };" + }; + /** Given value: o, propName: p, pattern: { a, b, ...p } from the original statement + * `{ a, b, ...p } = o`, create `p = __rest(o, ["a", "b"]);` + */ + function createRestCall(context, value, elements, computedTempVariables, location) { + context.requestEmitHelper(restHelper); + var propertyNames = []; + var computedTempVariableOffset = 0; + for (var i = 0; i < elements.length - 1; i++) { + var propertyName = ts.getPropertyNameOfBindingOrAssignmentElement(elements[i]); + if (propertyName) { + if (ts.isComputedPropertyName(propertyName)) { + var temp = computedTempVariables[computedTempVariableOffset]; + computedTempVariableOffset++; + // typeof _tmp === "symbol" ? _tmp : _tmp + "" + propertyNames.push(ts.createConditional(ts.createTypeCheck(temp, "symbol"), temp, ts.createAdd(temp, ts.createLiteral("")))); + } + else { + propertyNames.push(ts.createLiteral(propertyName)); + } + } + } + return ts.createCall(ts.getHelperName("__rest"), + /*typeArguments*/ undefined, [ + value, + ts.setTextRange(ts.createArrayLiteral(propertyNames), location) + ]); + } +})(ts || (ts = {})); +/*@internal*/ +var ts; +(function (ts) { + /** + * Indicates whether to emit type metadata in the new format. + */ + var USE_NEW_TYPE_METADATA_FORMAT = false; + var TypeScriptSubstitutionFlags; + (function (TypeScriptSubstitutionFlags) { + /** Enables substitutions for decorated classes. */ + TypeScriptSubstitutionFlags[TypeScriptSubstitutionFlags["ClassAliases"] = 1] = "ClassAliases"; + /** Enables substitutions for namespace exports. */ + TypeScriptSubstitutionFlags[TypeScriptSubstitutionFlags["NamespaceExports"] = 2] = "NamespaceExports"; + /* Enables substitutions for unqualified enum members */ + TypeScriptSubstitutionFlags[TypeScriptSubstitutionFlags["NonQualifiedEnumMembers"] = 8] = "NonQualifiedEnumMembers"; + })(TypeScriptSubstitutionFlags || (TypeScriptSubstitutionFlags = {})); + var ClassFacts; + (function (ClassFacts) { + ClassFacts[ClassFacts["None"] = 0] = "None"; + ClassFacts[ClassFacts["HasStaticInitializedProperties"] = 1] = "HasStaticInitializedProperties"; + ClassFacts[ClassFacts["HasConstructorDecorators"] = 2] = "HasConstructorDecorators"; + ClassFacts[ClassFacts["HasMemberDecorators"] = 4] = "HasMemberDecorators"; + ClassFacts[ClassFacts["IsExportOfNamespace"] = 8] = "IsExportOfNamespace"; + ClassFacts[ClassFacts["IsNamedExternalExport"] = 16] = "IsNamedExternalExport"; + ClassFacts[ClassFacts["IsDefaultExternalExport"] = 32] = "IsDefaultExternalExport"; + ClassFacts[ClassFacts["IsDerivedClass"] = 64] = "IsDerivedClass"; + ClassFacts[ClassFacts["UseImmediatelyInvokedFunctionExpression"] = 128] = "UseImmediatelyInvokedFunctionExpression"; + ClassFacts[ClassFacts["HasAnyDecorators"] = 6] = "HasAnyDecorators"; + ClassFacts[ClassFacts["NeedsName"] = 5] = "NeedsName"; + ClassFacts[ClassFacts["MayNeedImmediatelyInvokedFunctionExpression"] = 7] = "MayNeedImmediatelyInvokedFunctionExpression"; + ClassFacts[ClassFacts["IsExported"] = 56] = "IsExported"; + })(ClassFacts || (ClassFacts = {})); + function transformTypeScript(context) { + var startLexicalEnvironment = context.startLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; + var resolver = context.getEmitResolver(); + var compilerOptions = context.getCompilerOptions(); + var strictNullChecks = ts.getStrictOptionValue(compilerOptions, "strictNullChecks"); + var languageVersion = ts.getEmitScriptTarget(compilerOptions); + var moduleKind = ts.getEmitModuleKind(compilerOptions); + // Save the previous transformation hooks. + var previousOnEmitNode = context.onEmitNode; + var previousOnSubstituteNode = context.onSubstituteNode; + // Set new transformation hooks. + context.onEmitNode = onEmitNode; + context.onSubstituteNode = onSubstituteNode; + // Enable substitution for property/element access to emit const enum values. + context.enableSubstitution(189 /* PropertyAccessExpression */); + context.enableSubstitution(190 /* ElementAccessExpression */); + // These variables contain state that changes as we descend into the tree. + var currentSourceFile; + var currentNamespace; + var currentNamespaceContainerName; + var currentLexicalScope; + var currentNameScope; + var currentScopeFirstDeclarationsOfName; + /** + * Keeps track of whether expression substitution has been enabled for specific edge cases. + * They are persisted between each SourceFile transformation and should not be reset. + */ + var enabledSubstitutions; + /** + * A map that keeps track of aliases created for classes with decorators to avoid issues + * with the double-binding behavior of classes. + */ + var classAliases; + /** + * Keeps track of whether we are within any containing namespaces when performing + * just-in-time substitution while printing an expression identifier. + */ + var applicableSubstitutions; + /** + * Tracks what computed name expressions originating from elided names must be inlined + * at the next execution site, in document order + */ + var pendingExpressions; + return transformSourceFileOrBundle; + function transformSourceFileOrBundle(node) { + if (node.kind === 280 /* Bundle */) { + return transformBundle(node); + } + return transformSourceFile(node); + } + function transformBundle(node) { + return ts.createBundle(node.sourceFiles.map(transformSourceFile), ts.mapDefined(node.prepends, function (prepend) { + if (prepend.kind === 282 /* InputFiles */) { + return ts.createUnparsedSourceFile(prepend.javascriptText, prepend.javascriptMapPath, prepend.javascriptMapText); + } + return prepend; + })); + } + /** + * Transform TypeScript-specific syntax in a SourceFile. + * + * @param node A SourceFile node. + */ + function transformSourceFile(node) { + if (node.isDeclarationFile) { + return node; + } + currentSourceFile = node; + var visited = saveStateAndInvoke(node, visitSourceFile); + ts.addEmitHelpers(visited, context.readEmitHelpers()); + currentSourceFile = undefined; + return visited; + } + /** + * Visits a node, saving and restoring state variables on the stack. + * + * @param node The node to visit. + */ + function saveStateAndInvoke(node, f) { + // Save state + var savedCurrentScope = currentLexicalScope; + var savedCurrentNameScope = currentNameScope; + var savedCurrentScopeFirstDeclarationsOfName = currentScopeFirstDeclarationsOfName; + // Handle state changes before visiting a node. + onBeforeVisitNode(node); + var visited = f(node); + // Restore state + if (currentLexicalScope !== savedCurrentScope) { + currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName; + } + currentLexicalScope = savedCurrentScope; + currentNameScope = savedCurrentNameScope; + return visited; + } + /** + * Performs actions that should always occur immediately before visiting a node. + * + * @param node The node to visit. + */ + function onBeforeVisitNode(node) { + switch (node.kind) { + case 279 /* SourceFile */: + case 246 /* CaseBlock */: + case 245 /* ModuleBlock */: + case 218 /* Block */: + currentLexicalScope = node; + currentNameScope = undefined; + currentScopeFirstDeclarationsOfName = undefined; + break; + case 240 /* ClassDeclaration */: + case 239 /* FunctionDeclaration */: + if (ts.hasModifier(node, 2 /* Ambient */)) { + break; + } + // Record these declarations provided that they have a name. + if (node.name) { + recordEmittedDeclarationInScope(node); + } + else { + // These nodes should always have names unless they are default-exports; + // however, class declaration parsing allows for undefined names, so syntactically invalid + // programs may also have an undefined name. + ts.Debug.assert(node.kind === 240 /* ClassDeclaration */ || ts.hasModifier(node, 512 /* Default */)); + } + if (ts.isClassDeclaration(node)) { + // XXX: should probably also cover interfaces and type aliases that can have type variables? + currentNameScope = node; + } + break; + } + } + /** + * General-purpose node visitor. + * + * @param node The node to visit. + */ + function visitor(node) { + return saveStateAndInvoke(node, visitorWorker); + } + /** + * Visits and possibly transforms any node. + * + * @param node The node to visit. + */ + function visitorWorker(node) { + if (node.transformFlags & 1 /* TypeScript */) { + // This node is explicitly marked as TypeScript, so we should transform the node. + return visitTypeScript(node); + } + else if (node.transformFlags & 2 /* ContainsTypeScript */) { + // This node contains TypeScript, so we should visit its children. + return ts.visitEachChild(node, visitor, context); + } + return node; + } + /** + * Specialized visitor that visits the immediate children of a SourceFile. + * + * @param node The node to visit. + */ + function sourceElementVisitor(node) { + return saveStateAndInvoke(node, sourceElementVisitorWorker); + } + /** + * Specialized visitor that visits the immediate children of a SourceFile. + * + * @param node The node to visit. + */ + function sourceElementVisitorWorker(node) { + switch (node.kind) { + case 249 /* ImportDeclaration */: + case 248 /* ImportEqualsDeclaration */: + case 254 /* ExportAssignment */: + case 255 /* ExportDeclaration */: + return visitEllidableStatement(node); + default: + return visitorWorker(node); + } + } + function visitEllidableStatement(node) { + var parsed = ts.getParseTreeNode(node); + if (parsed !== node) { + // If the node has been transformed by a `before` transformer, perform no ellision on it + // As the type information we would attempt to lookup to perform ellision is potentially unavailable for the synthesized nodes + // We do not reuse `visitorWorker`, as the ellidable statement syntax kinds are technically unrecognized by the switch-case in `visitTypeScript`, + // and will trigger debug failures when debug verbosity is turned up + if (node.transformFlags & 2 /* ContainsTypeScript */) { + // This node contains TypeScript, so we should visit its children. + return ts.visitEachChild(node, visitor, context); + } + // Otherwise, we can just return the node + return node; + } + switch (node.kind) { + case 249 /* ImportDeclaration */: + return visitImportDeclaration(node); + case 248 /* ImportEqualsDeclaration */: + return visitImportEqualsDeclaration(node); + case 254 /* ExportAssignment */: + return visitExportAssignment(node); + case 255 /* ExportDeclaration */: + return visitExportDeclaration(node); + default: + ts.Debug.fail("Unhandled ellided statement"); + } + } + /** + * Specialized visitor that visits the immediate children of a namespace. + * + * @param node The node to visit. + */ + function namespaceElementVisitor(node) { + return saveStateAndInvoke(node, namespaceElementVisitorWorker); + } + /** + * Specialized visitor that visits the immediate children of a namespace. + * + * @param node The node to visit. + */ + function namespaceElementVisitorWorker(node) { + if (node.kind === 255 /* ExportDeclaration */ || + node.kind === 249 /* ImportDeclaration */ || + node.kind === 250 /* ImportClause */ || + (node.kind === 248 /* ImportEqualsDeclaration */ && + node.moduleReference.kind === 259 /* ExternalModuleReference */)) { + // do not emit ES6 imports and exports since they are illegal inside a namespace + return undefined; + } + else if (node.transformFlags & 1 /* TypeScript */ || ts.hasModifier(node, 1 /* Export */)) { + // This node is explicitly marked as TypeScript, or is exported at the namespace + // level, so we should transform the node. + return visitTypeScript(node); + } + else if (node.transformFlags & 2 /* ContainsTypeScript */) { + // This node contains TypeScript, so we should visit its children. + return ts.visitEachChild(node, visitor, context); + } + return node; + } + /** + * Specialized visitor that visits the immediate children of a class with TypeScript syntax. + * + * @param node The node to visit. + */ + function classElementVisitor(node) { + return saveStateAndInvoke(node, classElementVisitorWorker); + } + /** + * Specialized visitor that visits the immediate children of a class with TypeScript syntax. + * + * @param node The node to visit. + */ + function classElementVisitorWorker(node) { + switch (node.kind) { + case 157 /* Constructor */: + // TypeScript constructors are transformed in `visitClassDeclaration`. + // We elide them here as `visitorWorker` checks transform flags, which could + // erronously include an ES6 constructor without TypeScript syntax. + return undefined; + case 154 /* PropertyDeclaration */: + case 162 /* IndexSignature */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 156 /* MethodDeclaration */: + // Fallback to the default visit behavior. + return visitorWorker(node); + case 217 /* SemicolonClassElement */: + return node; + default: + return ts.Debug.failBadSyntaxKind(node); + } + } + function modifierVisitor(node) { + if (ts.modifierToFlag(node.kind) & 2270 /* TypeScriptModifier */) { + return undefined; + } + else if (currentNamespace && node.kind === 85 /* ExportKeyword */) { + return undefined; + } + return node; + } + /** + * Branching visitor, visits a TypeScript syntax node. + * + * @param node The node to visit. + */ + function visitTypeScript(node) { + if (ts.hasModifier(node, 2 /* Ambient */) && ts.isStatement(node)) { + // TypeScript ambient declarations are elided, but some comments may be preserved. + // See the implementation of `getLeadingComments` in comments.ts for more details. + return ts.createNotEmittedStatement(node); + } + switch (node.kind) { + case 85 /* ExportKeyword */: + case 80 /* DefaultKeyword */: + // ES6 export and default modifiers are elided when inside a namespace. + return currentNamespace ? undefined : node; + case 115 /* PublicKeyword */: + case 113 /* PrivateKeyword */: + case 114 /* ProtectedKeyword */: + case 118 /* AbstractKeyword */: + case 77 /* ConstKeyword */: + case 125 /* DeclareKeyword */: + case 133 /* ReadonlyKeyword */: + // TypeScript accessibility and readonly modifiers are elided. + case 169 /* ArrayType */: + case 170 /* TupleType */: + case 171 /* OptionalType */: + case 172 /* RestType */: + case 168 /* TypeLiteral */: + case 163 /* TypePredicate */: + case 150 /* TypeParameter */: + case 120 /* AnyKeyword */: + case 143 /* UnknownKeyword */: + case 123 /* BooleanKeyword */: + case 138 /* StringKeyword */: + case 135 /* NumberKeyword */: + case 132 /* NeverKeyword */: + case 106 /* VoidKeyword */: + case 139 /* SymbolKeyword */: + case 166 /* ConstructorType */: + case 165 /* FunctionType */: + case 167 /* TypeQuery */: + case 164 /* TypeReference */: + case 173 /* UnionType */: + case 174 /* IntersectionType */: + case 175 /* ConditionalType */: + case 177 /* ParenthesizedType */: + case 178 /* ThisType */: + case 179 /* TypeOperator */: + case 180 /* IndexedAccessType */: + case 181 /* MappedType */: + case 182 /* LiteralType */: + // TypeScript type nodes are elided. + case 162 /* IndexSignature */: + // TypeScript index signatures are elided. + case 152 /* Decorator */: + // TypeScript decorators are elided. They will be emitted as part of visitClassDeclaration. + case 242 /* TypeAliasDeclaration */: + // TypeScript type-only declarations are elided. + return undefined; + case 154 /* PropertyDeclaration */: + // TypeScript property declarations are elided. However their names are still visited, and can potentially be retained if they could have sideeffects + return visitPropertyDeclaration(node); + case 247 /* NamespaceExportDeclaration */: + // TypeScript namespace export declarations are elided. + return undefined; + case 157 /* Constructor */: + return visitConstructor(node); + case 241 /* InterfaceDeclaration */: + // TypeScript interfaces are elided, but some comments may be preserved. + // See the implementation of `getLeadingComments` in comments.ts for more details. + return ts.createNotEmittedStatement(node); + case 240 /* ClassDeclaration */: + // This is a class declaration with TypeScript syntax extensions. + // + // TypeScript class syntax extensions include: + // - decorators + // - optional `implements` heritage clause + // - parameter property assignments in the constructor + // - property declarations + // - index signatures + // - method overload signatures + return visitClassDeclaration(node); + case 209 /* ClassExpression */: + // This is a class expression with TypeScript syntax extensions. + // + // TypeScript class syntax extensions include: + // - decorators + // - optional `implements` heritage clause + // - parameter property assignments in the constructor + // - property declarations + // - index signatures + // - method overload signatures + return visitClassExpression(node); + case 273 /* HeritageClause */: + // This is a heritage clause with TypeScript syntax extensions. + // + // TypeScript heritage clause extensions include: + // - `implements` clause + return visitHeritageClause(node); + case 211 /* ExpressionWithTypeArguments */: + // TypeScript supports type arguments on an expression in an `extends` heritage clause. + return visitExpressionWithTypeArguments(node); + case 156 /* MethodDeclaration */: + // TypeScript method declarations may have decorators, modifiers + // or type annotations. + return visitMethodDeclaration(node); + case 158 /* GetAccessor */: + // Get Accessors can have TypeScript modifiers, decorators, and type annotations. + return visitGetAccessor(node); + case 159 /* SetAccessor */: + // Set Accessors can have TypeScript modifiers and type annotations. + return visitSetAccessor(node); + case 239 /* FunctionDeclaration */: + // Typescript function declarations can have modifiers, decorators, and type annotations. + return visitFunctionDeclaration(node); + case 196 /* FunctionExpression */: + // TypeScript function expressions can have modifiers and type annotations. + return visitFunctionExpression(node); + case 197 /* ArrowFunction */: + // TypeScript arrow functions can have modifiers and type annotations. + return visitArrowFunction(node); + case 151 /* Parameter */: + // This is a parameter declaration with TypeScript syntax extensions. + // + // TypeScript parameter declaration syntax extensions include: + // - decorators + // - accessibility modifiers + // - the question mark (?) token for optional parameters + // - type annotations + // - this parameters + return visitParameter(node); + case 195 /* ParenthesizedExpression */: + // ParenthesizedExpressions are TypeScript if their expression is a + // TypeAssertion or AsExpression + return visitParenthesizedExpression(node); + case 194 /* TypeAssertionExpression */: + case 212 /* AsExpression */: + // TypeScript type assertions are removed, but their subtrees are preserved. + return visitAssertionExpression(node); + case 191 /* CallExpression */: + return visitCallExpression(node); + case 192 /* NewExpression */: + return visitNewExpression(node); + case 193 /* TaggedTemplateExpression */: + return visitTaggedTemplateExpression(node); + case 213 /* NonNullExpression */: + // TypeScript non-null expressions are removed, but their subtrees are preserved. + return visitNonNullExpression(node); + case 243 /* EnumDeclaration */: + // TypeScript enum declarations do not exist in ES6 and must be rewritten. + return visitEnumDeclaration(node); + case 219 /* VariableStatement */: + // TypeScript namespace exports for variable statements must be transformed. + return visitVariableStatement(node); + case 237 /* VariableDeclaration */: + return visitVariableDeclaration(node); + case 244 /* ModuleDeclaration */: + // TypeScript namespace declarations must be transformed. + return visitModuleDeclaration(node); + case 248 /* ImportEqualsDeclaration */: + // TypeScript namespace or external module import. + return visitImportEqualsDeclaration(node); + default: + return ts.Debug.failBadSyntaxKind(node); + } + } + function visitSourceFile(node) { + var alwaysStrict = ts.getStrictOptionValue(compilerOptions, "alwaysStrict") && + !(ts.isExternalModule(node) && moduleKind >= ts.ModuleKind.ES2015) && + !ts.isJsonSourceFile(node); + return ts.updateSourceFileNode(node, ts.visitLexicalEnvironment(node.statements, sourceElementVisitor, context, /*start*/ 0, alwaysStrict)); + } + /** + * Tests whether we should emit a __decorate call for a class declaration. + */ + function shouldEmitDecorateCallForClass(node) { + if (node.decorators && node.decorators.length > 0) { + return true; + } + var constructor = ts.getFirstConstructorWithBody(node); + if (constructor) { + return ts.forEach(constructor.parameters, shouldEmitDecorateCallForParameter); + } + return false; + } + /** + * Tests whether we should emit a __decorate call for a parameter declaration. + */ + function shouldEmitDecorateCallForParameter(parameter) { + return parameter.decorators !== undefined && parameter.decorators.length > 0; + } + function getClassFacts(node, staticProperties) { + var facts = 0 /* None */; + if (ts.some(staticProperties)) + facts |= 1 /* HasStaticInitializedProperties */; + var extendsClauseElement = ts.getEffectiveBaseTypeNode(node); + if (extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 96 /* NullKeyword */) + facts |= 64 /* IsDerivedClass */; + if (shouldEmitDecorateCallForClass(node)) + facts |= 2 /* HasConstructorDecorators */; + if (ts.childIsDecorated(node)) + facts |= 4 /* HasMemberDecorators */; + if (isExportOfNamespace(node)) + facts |= 8 /* IsExportOfNamespace */; + else if (isDefaultExternalModuleExport(node)) + facts |= 32 /* IsDefaultExternalExport */; + else if (isNamedExternalModuleExport(node)) + facts |= 16 /* IsNamedExternalExport */; + if (languageVersion <= 1 /* ES5 */ && (facts & 7 /* MayNeedImmediatelyInvokedFunctionExpression */)) + facts |= 128 /* UseImmediatelyInvokedFunctionExpression */; + return facts; + } + /** + * Transforms a class declaration with TypeScript syntax into compatible ES6. + * + * This function will only be called when one of the following conditions are met: + * - The class has decorators. + * - The class has property declarations with initializers. + * - The class contains a constructor that contains parameters with accessibility modifiers. + * - The class is an export in a TypeScript namespace. + * + * @param node The node to transform. + */ + function visitClassDeclaration(node) { + var savedPendingExpressions = pendingExpressions; + pendingExpressions = undefined; + var staticProperties = getInitializedProperties(node, /*isStatic*/ true); + var facts = getClassFacts(node, staticProperties); + if (facts & 128 /* UseImmediatelyInvokedFunctionExpression */) { + context.startLexicalEnvironment(); + } + var name = node.name || (facts & 5 /* NeedsName */ ? ts.getGeneratedNameForNode(node) : undefined); + var classStatement = facts & 2 /* HasConstructorDecorators */ + ? createClassDeclarationHeadWithDecorators(node, name, facts) + : createClassDeclarationHeadWithoutDecorators(node, name, facts); + var statements = [classStatement]; + // Write any pending expressions from elided or moved computed property names + if (ts.some(pendingExpressions)) { + statements.push(ts.createExpressionStatement(ts.inlineExpressions(pendingExpressions))); + } + pendingExpressions = savedPendingExpressions; + // Emit static property assignment. Because classDeclaration is lexically evaluated, + // it is safe to emit static property assignment after classDeclaration + // From ES6 specification: + // HasLexicalDeclaration (N) : Determines if the argument identifier has a binding in this environment record that was created using + // a lexical declaration such as a LexicalDeclaration or a ClassDeclaration. + if (facts & 1 /* HasStaticInitializedProperties */) { + addInitializedPropertyStatements(statements, staticProperties, facts & 128 /* UseImmediatelyInvokedFunctionExpression */ ? ts.getInternalName(node) : ts.getLocalName(node)); + } + // Write any decorators of the node. + addClassElementDecorationStatements(statements, node, /*isStatic*/ false); + addClassElementDecorationStatements(statements, node, /*isStatic*/ true); + addConstructorDecorationStatement(statements, node); + if (facts & 128 /* UseImmediatelyInvokedFunctionExpression */) { + // When we emit a TypeScript class down to ES5, we must wrap it in an IIFE so that the + // 'es2015' transformer can properly nest static initializers and decorators. The result + // looks something like: + // + // var C = function () { + // class C { + // } + // C.static_prop = 1; + // return C; + // }(); + // + var closingBraceLocation = ts.createTokenRange(ts.skipTrivia(currentSourceFile.text, node.members.end), 19 /* CloseBraceToken */); + var localName = ts.getInternalName(node); + // The following partially-emitted expression exists purely to align our sourcemap + // emit with the original emitter. + var outer = ts.createPartiallyEmittedExpression(localName); + outer.end = closingBraceLocation.end; + ts.setEmitFlags(outer, 1536 /* NoComments */); + var statement = ts.createReturn(outer); + statement.pos = closingBraceLocation.pos; + ts.setEmitFlags(statement, 1536 /* NoComments */ | 384 /* NoTokenSourceMaps */); + statements.push(statement); + ts.addStatementsAfterPrologue(statements, context.endLexicalEnvironment()); + var iife = ts.createImmediatelyInvokedArrowFunction(statements); + ts.setEmitFlags(iife, 33554432 /* TypeScriptClassWrapper */); + var varStatement = ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ false), + /*type*/ undefined, iife) + ])); + ts.setOriginalNode(varStatement, node); + ts.setCommentRange(varStatement, node); + ts.setSourceMapRange(varStatement, ts.moveRangePastDecorators(node)); + ts.startOnNewLine(varStatement); + statements = [varStatement]; + } + // If the class is exported as part of a TypeScript namespace, emit the namespace export. + // Otherwise, if the class was exported at the top level and was decorated, emit an export + // declaration or export default for the class. + if (facts & 8 /* IsExportOfNamespace */) { + addExportMemberAssignment(statements, node); + } + else if (facts & 128 /* UseImmediatelyInvokedFunctionExpression */ || facts & 2 /* HasConstructorDecorators */) { + if (facts & 32 /* IsDefaultExternalExport */) { + statements.push(ts.createExportDefault(ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true))); + } + else if (facts & 16 /* IsNamedExternalExport */) { + statements.push(ts.createExternalModuleExport(ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true))); + } + } + if (statements.length > 1) { + // Add a DeclarationMarker as a marker for the end of the declaration + statements.push(ts.createEndOfDeclarationMarker(node)); + ts.setEmitFlags(classStatement, ts.getEmitFlags(classStatement) | 4194304 /* HasEndOfDeclarationMarker */); + } + return ts.singleOrMany(statements); + } + /** + * Transforms a non-decorated class declaration and appends the resulting statements. + * + * @param node A ClassDeclaration node. + * @param name The name of the class. + * @param facts Precomputed facts about the class. + */ + function createClassDeclarationHeadWithoutDecorators(node, name, facts) { + // ${modifiers} class ${name} ${heritageClauses} { + // ${members} + // } + // we do not emit modifiers on the declaration if we are emitting an IIFE + var modifiers = !(facts & 128 /* UseImmediatelyInvokedFunctionExpression */) + ? ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier) + : undefined; + var classDeclaration = ts.createClassDeclaration( + /*decorators*/ undefined, modifiers, name, + /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node, (facts & 64 /* IsDerivedClass */) !== 0)); + // To better align with the old emitter, we should not emit a trailing source map + // entry if the class has static properties. + var emitFlags = ts.getEmitFlags(node); + if (facts & 1 /* HasStaticInitializedProperties */) { + emitFlags |= 32 /* NoTrailingSourceMap */; + } + ts.setTextRange(classDeclaration, node); + ts.setOriginalNode(classDeclaration, node); + ts.setEmitFlags(classDeclaration, emitFlags); + return classDeclaration; + } + /** + * Transforms a decorated class declaration and appends the resulting statements. If + * the class requires an alias to avoid issues with double-binding, the alias is returned. + */ + function createClassDeclarationHeadWithDecorators(node, name, facts) { + // When we emit an ES6 class that has a class decorator, we must tailor the + // emit to certain specific cases. + // + // In the simplest case, we emit the class declaration as a let declaration, and + // evaluate decorators after the close of the class body: + // + // [Example 1] + // --------------------------------------------------------------------- + // TypeScript | Javascript + // --------------------------------------------------------------------- + // @dec | let C = class C { + // class C { | } + // } | C = __decorate([dec], C); + // --------------------------------------------------------------------- + // @dec | let C = class C { + // export class C { | } + // } | C = __decorate([dec], C); + // | export { C }; + // --------------------------------------------------------------------- + // + // If a class declaration contains a reference to itself *inside* of the class body, + // this introduces two bindings to the class: One outside of the class body, and one + // inside of the class body. If we apply decorators as in [Example 1] above, there + // is the possibility that the decorator `dec` will return a new value for the + // constructor, which would result in the binding inside of the class no longer + // pointing to the same reference as the binding outside of the class. + // + // As a result, we must instead rewrite all references to the class *inside* of the + // class body to instead point to a local temporary alias for the class: + // + // [Example 2] + // --------------------------------------------------------------------- + // TypeScript | Javascript + // --------------------------------------------------------------------- + // @dec | let C = C_1 = class C { + // class C { | static x() { return C_1.y; } + // static x() { return C.y; } | } + // static y = 1; | C.y = 1; + // } | C = C_1 = __decorate([dec], C); + // | var C_1; + // --------------------------------------------------------------------- + // @dec | let C = class C { + // export class C { | static x() { return C_1.y; } + // static x() { return C.y; } | } + // static y = 1; | C.y = 1; + // } | C = C_1 = __decorate([dec], C); + // | export { C }; + // | var C_1; + // --------------------------------------------------------------------- + // + // If a class declaration is the default export of a module, we instead emit + // the export after the decorated declaration: + // + // [Example 3] + // --------------------------------------------------------------------- + // TypeScript | Javascript + // --------------------------------------------------------------------- + // @dec | let default_1 = class { + // export default class { | } + // } | default_1 = __decorate([dec], default_1); + // | export default default_1; + // --------------------------------------------------------------------- + // @dec | let C = class C { + // export default class C { | } + // } | C = __decorate([dec], C); + // | export default C; + // --------------------------------------------------------------------- + // + // If the class declaration is the default export and a reference to itself + // inside of the class body, we must emit both an alias for the class *and* + // move the export after the declaration: + // + // [Example 4] + // --------------------------------------------------------------------- + // TypeScript | Javascript + // --------------------------------------------------------------------- + // @dec | let C = class C { + // export default class C { | static x() { return C_1.y; } + // static x() { return C.y; } | } + // static y = 1; | C.y = 1; + // } | C = C_1 = __decorate([dec], C); + // | export default C; + // | var C_1; + // --------------------------------------------------------------------- + // + var location = ts.moveRangePastDecorators(node); + var classAlias = getClassAliasIfNeeded(node); + var declName = ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true); + // ... = class ${name} ${heritageClauses} { + // ${members} + // } + var heritageClauses = ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause); + var members = transformClassMembers(node, (facts & 64 /* IsDerivedClass */) !== 0); + var classExpression = ts.createClassExpression(/*modifiers*/ undefined, name, /*typeParameters*/ undefined, heritageClauses, members); + ts.setOriginalNode(classExpression, node); + ts.setTextRange(classExpression, location); + // let ${name} = ${classExpression} where name is either declaredName if the class doesn't contain self-reference + // or decoratedClassAlias if the class contain self-reference. + var statement = ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(declName, + /*type*/ undefined, classAlias ? ts.createAssignment(classAlias, classExpression) : classExpression) + ], 1 /* Let */)); + ts.setOriginalNode(statement, node); + ts.setTextRange(statement, location); + ts.setCommentRange(statement, node); + return statement; + } + /** + * Transforms a class expression with TypeScript syntax into compatible ES6. + * + * This function will only be called when one of the following conditions are met: + * - The class has property declarations with initializers. + * - The class contains a constructor that contains parameters with accessibility modifiers. + * + * @param node The node to transform. + */ + function visitClassExpression(node) { + var savedPendingExpressions = pendingExpressions; + pendingExpressions = undefined; + var staticProperties = getInitializedProperties(node, /*isStatic*/ true); + var heritageClauses = ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause); + var members = transformClassMembers(node, ts.some(heritageClauses, function (c) { return c.token === 86 /* ExtendsKeyword */; })); + var classExpression = ts.createClassExpression( + /*modifiers*/ undefined, node.name, + /*typeParameters*/ undefined, heritageClauses, members); + ts.setOriginalNode(classExpression, node); + ts.setTextRange(classExpression, node); + if (ts.some(staticProperties) || ts.some(pendingExpressions)) { + var expressions = []; + var isClassWithConstructorReference = resolver.getNodeCheckFlags(node) & 16777216 /* ClassWithConstructorReference */; + var temp = ts.createTempVariable(hoistVariableDeclaration, !!isClassWithConstructorReference); + if (isClassWithConstructorReference) { + // record an alias as the class name is not in scope for statics. + enableSubstitutionForClassAliases(); + var alias = ts.getSynthesizedClone(temp); + alias.autoGenerateFlags &= ~8 /* ReservedInNestedScopes */; + classAliases[ts.getOriginalNodeId(node)] = alias; + } + // To preserve the behavior of the old emitter, we explicitly indent + // the body of a class with static initializers. + ts.setEmitFlags(classExpression, 65536 /* Indented */ | ts.getEmitFlags(classExpression)); + expressions.push(ts.startOnNewLine(ts.createAssignment(temp, classExpression))); + // Add any pending expressions leftover from elided or relocated computed property names + ts.addRange(expressions, ts.map(pendingExpressions, ts.startOnNewLine)); + pendingExpressions = savedPendingExpressions; + ts.addRange(expressions, generateInitializedPropertyExpressions(staticProperties, temp)); + expressions.push(ts.startOnNewLine(temp)); + return ts.inlineExpressions(expressions); + } + pendingExpressions = savedPendingExpressions; + return classExpression; + } + /** + * Transforms the members of a class. + * + * @param node The current class. + * @param isDerivedClass A value indicating whether the class has an extends clause that does not extend 'null'. + */ + function transformClassMembers(node, isDerivedClass) { + var members = []; + var constructor = transformConstructor(node, isDerivedClass); + if (constructor) { + members.push(constructor); + } + ts.addRange(members, ts.visitNodes(node.members, classElementVisitor, ts.isClassElement)); + return ts.setTextRange(ts.createNodeArray(members), /*location*/ node.members); + } + /** + * Transforms (or creates) a constructor for a class. + * + * @param node The current class. + * @param isDerivedClass A value indicating whether the class has an extends clause that does not extend 'null'. + */ + function transformConstructor(node, isDerivedClass) { + // Check if we have property assignment inside class declaration. + // If there is a property assignment, we need to emit constructor whether users define it or not + // If there is no property assignment, we can omit constructor if users do not define it + var constructor = ts.getFirstConstructorWithBody(node); + var hasInstancePropertyWithInitializer = ts.forEach(node.members, isInstanceInitializedProperty); + var hasParameterPropertyAssignments = constructor && + constructor.transformFlags & 4096 /* ContainsTypeScriptClassSyntax */ && + ts.forEach(constructor.parameters, isParameterWithPropertyAssignment); + // If the class does not contain nodes that require a synthesized constructor, + // accept the current constructor if it exists. + if (!hasInstancePropertyWithInitializer && !hasParameterPropertyAssignments) { + return ts.visitEachChild(constructor, visitor, context); + } + var parameters = transformConstructorParameters(constructor); + var body = transformConstructorBody(node, constructor, isDerivedClass); + // constructor(${parameters}) { + // ${body} + // } + return ts.startOnNewLine(ts.setOriginalNode(ts.setTextRange(ts.createConstructor( + /*decorators*/ undefined, + /*modifiers*/ undefined, parameters, body), constructor || node), constructor)); + } + /** + * Transforms (or creates) the parameters for the constructor of a class with + * parameter property assignments or instance property initializers. + * + * @param constructor The constructor declaration. + */ + function transformConstructorParameters(constructor) { + // The ES2015 spec specifies in 14.5.14. Runtime Semantics: ClassDefinitionEvaluation: + // If constructor is empty, then + // If ClassHeritag_eopt is present and protoParent is not null, then + // Let constructor be the result of parsing the source text + // constructor(...args) { super (...args);} + // using the syntactic grammar with the goal symbol MethodDefinition[~Yield]. + // Else, + // Let constructor be the result of parsing the source text + // constructor( ){ } + // using the syntactic grammar with the goal symbol MethodDefinition[~Yield]. + // + // While we could emit the '...args' rest parameter, certain later tools in the pipeline might + // downlevel the '...args' portion less efficiently by naively copying the contents of 'arguments' to an array. + // Instead, we'll avoid using a rest parameter and spread into the super call as + // 'super(...arguments)' instead of 'super(...args)', as you can see in "transformConstructorBody". + return ts.visitParameterList(constructor && constructor.parameters, visitor, context) + || []; + } + /** + * Transforms (or creates) a constructor body for a class with parameter property + * assignments or instance property initializers. + * + * @param node The current class. + * @param constructor The current class constructor. + * @param isDerivedClass A value indicating whether the class has an extends clause that does not extend 'null'. + */ + function transformConstructorBody(node, constructor, isDerivedClass) { + var statements = []; + var indexOfFirstStatement = 0; + resumeLexicalEnvironment(); + if (constructor) { + indexOfFirstStatement = addPrologueDirectivesAndInitialSuperCall(constructor, statements); + // Add parameters with property assignments. Transforms this: + // + // constructor (public x, public y) { + // } + // + // Into this: + // + // constructor (x, y) { + // this.x = x; + // this.y = y; + // } + // + var propertyAssignments = getParametersWithPropertyAssignments(constructor); + ts.addRange(statements, ts.map(propertyAssignments, transformParameterWithPropertyAssignment)); + } + else if (isDerivedClass) { + // Add a synthetic `super` call: + // + // super(...arguments); + // + statements.push(ts.createExpressionStatement(ts.createCall(ts.createSuper(), + /*typeArguments*/ undefined, [ts.createSpread(ts.createIdentifier("arguments"))]))); + } + // Add the property initializers. Transforms this: + // + // public x = 1; + // + // Into this: + // + // constructor() { + // this.x = 1; + // } + // + var properties = getInitializedProperties(node, /*isStatic*/ false); + addInitializedPropertyStatements(statements, properties, ts.createThis()); + if (constructor) { + // The class already had a constructor, so we should add the existing statements, skipping the initial super call. + ts.addRange(statements, ts.visitNodes(constructor.body.statements, visitor, ts.isStatement, indexOfFirstStatement)); + } + // End the lexical environment. + statements = ts.mergeLexicalEnvironment(statements, endLexicalEnvironment()); + return ts.setTextRange(ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), + /*location*/ constructor ? constructor.body.statements : node.members), + /*multiLine*/ true), + /*location*/ constructor ? constructor.body : undefined); + } + /** + * Adds super call and preceding prologue directives into the list of statements. + * + * @param ctor The constructor node. + * @returns index of the statement that follows super call + */ + function addPrologueDirectivesAndInitialSuperCall(ctor, result) { + if (ctor.body) { + var statements = ctor.body.statements; + // add prologue directives to the list (if any) + var index = ts.addPrologue(result, statements, /*ensureUseStrict*/ false, visitor); + if (index === statements.length) { + // list contains nothing but prologue directives (or empty) - exit + return index; + } + var statement = statements[index]; + if (statement.kind === 221 /* ExpressionStatement */ && ts.isSuperCall(statement.expression)) { + result.push(ts.visitNode(statement, visitor, ts.isStatement)); + return index + 1; + } + return index; + } + return 0; + } + /** + * Gets all parameters of a constructor that should be transformed into property assignments. + * + * @param node The constructor node. + */ + function getParametersWithPropertyAssignments(node) { + return ts.filter(node.parameters, isParameterWithPropertyAssignment); + } + /** + * Determines whether a parameter should be transformed into a property assignment. + * + * @param parameter The parameter node. + */ + function isParameterWithPropertyAssignment(parameter) { + return ts.hasModifier(parameter, 92 /* ParameterPropertyModifier */) + && ts.isIdentifier(parameter.name); + } + /** + * Transforms a parameter into a property assignment statement. + * + * @param node The parameter declaration. + */ + function transformParameterWithPropertyAssignment(node) { + ts.Debug.assert(ts.isIdentifier(node.name)); + var name = node.name; + var propertyName = ts.getMutableClone(name); + ts.setEmitFlags(propertyName, 1536 /* NoComments */ | 48 /* NoSourceMap */); + var localName = ts.getMutableClone(name); + ts.setEmitFlags(localName, 1536 /* NoComments */); + return ts.startOnNewLine(ts.setEmitFlags(ts.setTextRange(ts.createExpressionStatement(ts.createAssignment(ts.setTextRange(ts.createPropertyAccess(ts.createThis(), propertyName), node.name), localName)), ts.moveRangePos(node, -1)), 1536 /* NoComments */)); + } + /** + * Gets all property declarations with initializers on either the static or instance side of a class. + * + * @param node The class node. + * @param isStatic A value indicating whether to get properties from the static or instance side of the class. + */ + function getInitializedProperties(node, isStatic) { + return ts.filter(node.members, isStatic ? isStaticInitializedProperty : isInstanceInitializedProperty); + } + /** + * Gets a value indicating whether a class element is a static property declaration with an initializer. + * + * @param member The class element node. + */ + function isStaticInitializedProperty(member) { + return isInitializedProperty(member, /*isStatic*/ true); + } + /** + * Gets a value indicating whether a class element is an instance property declaration with an initializer. + * + * @param member The class element node. + */ + function isInstanceInitializedProperty(member) { + return isInitializedProperty(member, /*isStatic*/ false); + } + /** + * Gets a value indicating whether a class element is either a static or an instance property declaration with an initializer. + * + * @param member The class element node. + * @param isStatic A value indicating whether the member should be a static or instance member. + */ + function isInitializedProperty(member, isStatic) { + return member.kind === 154 /* PropertyDeclaration */ + && isStatic === ts.hasModifier(member, 32 /* Static */) + && member.initializer !== undefined; + } + /** + * Generates assignment statements for property initializers. + * + * @param properties An array of property declarations to transform. + * @param receiver The receiver on which each property should be assigned. + */ + function addInitializedPropertyStatements(statements, properties, receiver) { + for (var _i = 0, properties_9 = properties; _i < properties_9.length; _i++) { + var property = properties_9[_i]; + var statement = ts.createExpressionStatement(transformInitializedProperty(property, receiver)); + ts.setSourceMapRange(statement, ts.moveRangePastModifiers(property)); + ts.setCommentRange(statement, property); + ts.setOriginalNode(statement, property); + statements.push(statement); + } + } + /** + * Generates assignment expressions for property initializers. + * + * @param properties An array of property declarations to transform. + * @param receiver The receiver on which each property should be assigned. + */ + function generateInitializedPropertyExpressions(properties, receiver) { + var expressions = []; + for (var _i = 0, properties_10 = properties; _i < properties_10.length; _i++) { + var property = properties_10[_i]; + var expression = transformInitializedProperty(property, receiver); + ts.startOnNewLine(expression); + ts.setSourceMapRange(expression, ts.moveRangePastModifiers(property)); + ts.setCommentRange(expression, property); + ts.setOriginalNode(expression, property); + expressions.push(expression); + } + return expressions; + } + /** + * Transforms a property initializer into an assignment statement. + * + * @param property The property declaration. + * @param receiver The object receiving the property assignment. + */ + function transformInitializedProperty(property, receiver) { + // We generate a name here in order to reuse the value cached by the relocated computed name expression (which uses the same generated name) + var propertyName = ts.isComputedPropertyName(property.name) && !isSimpleInlineableExpression(property.name.expression) + ? ts.updateComputedPropertyName(property.name, ts.getGeneratedNameForNode(property.name)) + : property.name; + var initializer = ts.visitNode(property.initializer, visitor, ts.isExpression); + var memberAccess = ts.createMemberAccessForPropertyName(receiver, propertyName, /*location*/ propertyName); + return ts.createAssignment(memberAccess, initializer); + } + /** + * Gets either the static or instance members of a class that are decorated, or have + * parameters that are decorated. + * + * @param node The class containing the member. + * @param isStatic A value indicating whether to retrieve static or instance members of + * the class. + */ + function getDecoratedClassElements(node, isStatic) { + return ts.filter(node.members, isStatic ? function (m) { return isStaticDecoratedClassElement(m, node); } : function (m) { return isInstanceDecoratedClassElement(m, node); }); + } + /** + * Determines whether a class member is a static member of a class that is decorated, or + * has parameters that are decorated. + * + * @param member The class member. + */ + function isStaticDecoratedClassElement(member, parent) { + return isDecoratedClassElement(member, /*isStatic*/ true, parent); + } + /** + * Determines whether a class member is an instance member of a class that is decorated, + * or has parameters that are decorated. + * + * @param member The class member. + */ + function isInstanceDecoratedClassElement(member, parent) { + return isDecoratedClassElement(member, /*isStatic*/ false, parent); + } + /** + * Determines whether a class member is either a static or an instance member of a class + * that is decorated, or has parameters that are decorated. + * + * @param member The class member. + */ + function isDecoratedClassElement(member, isStatic, parent) { + return ts.nodeOrChildIsDecorated(member, parent) + && isStatic === ts.hasModifier(member, 32 /* Static */); + } + /** + * Gets an array of arrays of decorators for the parameters of a function-like node. + * The offset into the result array should correspond to the offset of the parameter. + * + * @param node The function-like node. + */ + function getDecoratorsOfParameters(node) { + var decorators; + if (node) { + var parameters = node.parameters; + for (var i = 0; i < parameters.length; i++) { + var parameter = parameters[i]; + if (decorators || parameter.decorators) { + if (!decorators) { + decorators = new Array(parameters.length); + } + decorators[i] = parameter.decorators; + } + } + } + return decorators; + } + /** + * Gets an AllDecorators object containing the decorators for the class and the decorators for the + * parameters of the constructor of the class. + * + * @param node The class node. + */ + function getAllDecoratorsOfConstructor(node) { + var decorators = node.decorators; + var parameters = getDecoratorsOfParameters(ts.getFirstConstructorWithBody(node)); + if (!decorators && !parameters) { + return undefined; + } + return { + decorators: decorators, + parameters: parameters + }; + } + /** + * Gets an AllDecorators object containing the decorators for the member and its parameters. + * + * @param node The class node that contains the member. + * @param member The class member. + */ + function getAllDecoratorsOfClassElement(node, member) { + switch (member.kind) { + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + return getAllDecoratorsOfAccessors(node, member); + case 156 /* MethodDeclaration */: + return getAllDecoratorsOfMethod(member); + case 154 /* PropertyDeclaration */: + return getAllDecoratorsOfProperty(member); + default: + return undefined; + } + } + /** + * Gets an AllDecorators object containing the decorators for the accessor and its parameters. + * + * @param node The class node that contains the accessor. + * @param accessor The class accessor member. + */ + function getAllDecoratorsOfAccessors(node, accessor) { + if (!accessor.body) { + return undefined; + } + var _a = ts.getAllAccessorDeclarations(node.members, accessor), firstAccessor = _a.firstAccessor, secondAccessor = _a.secondAccessor, setAccessor = _a.setAccessor; + var firstAccessorWithDecorators = firstAccessor.decorators ? firstAccessor : secondAccessor && secondAccessor.decorators ? secondAccessor : undefined; + if (!firstAccessorWithDecorators || accessor !== firstAccessorWithDecorators) { + return undefined; + } + var decorators = firstAccessorWithDecorators.decorators; + var parameters = getDecoratorsOfParameters(setAccessor); + if (!decorators && !parameters) { + return undefined; + } + return { decorators: decorators, parameters: parameters }; + } + /** + * Gets an AllDecorators object containing the decorators for the method and its parameters. + * + * @param method The class method member. + */ + function getAllDecoratorsOfMethod(method) { + if (!method.body) { + return undefined; + } + var decorators = method.decorators; + var parameters = getDecoratorsOfParameters(method); + if (!decorators && !parameters) { + return undefined; + } + return { decorators: decorators, parameters: parameters }; + } + /** + * Gets an AllDecorators object containing the decorators for the property. + * + * @param property The class property member. + */ + function getAllDecoratorsOfProperty(property) { + var decorators = property.decorators; + if (!decorators) { + return undefined; + } + return { decorators: decorators }; + } + /** + * Transforms all of the decorators for a declaration into an array of expressions. + * + * @param node The declaration node. + * @param allDecorators An object containing all of the decorators for the declaration. + */ + function transformAllDecoratorsOfDeclaration(node, container, allDecorators) { + if (!allDecorators) { + return undefined; + } + var decoratorExpressions = []; + ts.addRange(decoratorExpressions, ts.map(allDecorators.decorators, transformDecorator)); + ts.addRange(decoratorExpressions, ts.flatMap(allDecorators.parameters, transformDecoratorsOfParameter)); + addTypeMetadata(node, container, decoratorExpressions); + return decoratorExpressions; + } + /** + * Generates statements used to apply decorators to either the static or instance members + * of a class. + * + * @param node The class node. + * @param isStatic A value indicating whether to generate statements for static or + * instance members. + */ + function addClassElementDecorationStatements(statements, node, isStatic) { + ts.addRange(statements, ts.map(generateClassElementDecorationExpressions(node, isStatic), expressionToStatement)); + } + /** + * Generates expressions used to apply decorators to either the static or instance members + * of a class. + * + * @param node The class node. + * @param isStatic A value indicating whether to generate expressions for static or + * instance members. + */ + function generateClassElementDecorationExpressions(node, isStatic) { + var members = getDecoratedClassElements(node, isStatic); + var expressions; + for (var _i = 0, members_5 = members; _i < members_5.length; _i++) { + var member = members_5[_i]; + var expression = generateClassElementDecorationExpression(node, member); + if (expression) { + if (!expressions) { + expressions = [expression]; + } + else { + expressions.push(expression); + } + } + } + return expressions; + } + /** + * Generates an expression used to evaluate class element decorators at runtime. + * + * @param node The class node that contains the member. + * @param member The class member. + */ + function generateClassElementDecorationExpression(node, member) { + var allDecorators = getAllDecoratorsOfClassElement(node, member); + var decoratorExpressions = transformAllDecoratorsOfDeclaration(member, node, allDecorators); + if (!decoratorExpressions) { + return undefined; + } + // Emit the call to __decorate. Given the following: + // + // class C { + // @dec method(@dec2 x) {} + // @dec get accessor() {} + // @dec prop; + // } + // + // The emit for a method is: + // + // __decorate([ + // dec, + // __param(0, dec2), + // __metadata("design:type", Function), + // __metadata("design:paramtypes", [Object]), + // __metadata("design:returntype", void 0) + // ], C.prototype, "method", null); + // + // The emit for an accessor is: + // + // __decorate([ + // dec + // ], C.prototype, "accessor", null); + // + // The emit for a property is: + // + // __decorate([ + // dec + // ], C.prototype, "prop"); + // + var prefix = getClassMemberPrefix(node, member); + var memberName = getExpressionForPropertyName(member, /*generateNameForComputedPropertyName*/ true); + var descriptor = languageVersion > 0 /* ES3 */ + ? member.kind === 154 /* PropertyDeclaration */ + // We emit `void 0` here to indicate to `__decorate` that it can invoke `Object.defineProperty` directly, but that it + // should not invoke `Object.getOwnPropertyDescriptor`. + ? ts.createVoidZero() + // We emit `null` here to indicate to `__decorate` that it can invoke `Object.getOwnPropertyDescriptor` directly. + // We have this extra argument here so that we can inject an explicit property descriptor at a later date. + : ts.createNull() + : undefined; + var helper = createDecorateHelper(context, decoratorExpressions, prefix, memberName, descriptor, ts.moveRangePastDecorators(member)); + ts.setEmitFlags(helper, 1536 /* NoComments */); + return helper; + } + /** + * Generates a __decorate helper call for a class constructor. + * + * @param node The class node. + */ + function addConstructorDecorationStatement(statements, node) { + var expression = generateConstructorDecorationExpression(node); + if (expression) { + statements.push(ts.setOriginalNode(ts.createExpressionStatement(expression), node)); + } + } + /** + * Generates a __decorate helper call for a class constructor. + * + * @param node The class node. + */ + function generateConstructorDecorationExpression(node) { + var allDecorators = getAllDecoratorsOfConstructor(node); + var decoratorExpressions = transformAllDecoratorsOfDeclaration(node, node, allDecorators); + if (!decoratorExpressions) { + return undefined; + } + var classAlias = classAliases && classAliases[ts.getOriginalNodeId(node)]; + var localName = ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true); + var decorate = createDecorateHelper(context, decoratorExpressions, localName); + var expression = ts.createAssignment(localName, classAlias ? ts.createAssignment(classAlias, decorate) : decorate); + ts.setEmitFlags(expression, 1536 /* NoComments */); + ts.setSourceMapRange(expression, ts.moveRangePastDecorators(node)); + return expression; + } + /** + * Transforms a decorator into an expression. + * + * @param decorator The decorator node. + */ + function transformDecorator(decorator) { + return ts.visitNode(decorator.expression, visitor, ts.isExpression); + } + /** + * Transforms the decorators of a parameter. + * + * @param decorators The decorators for the parameter at the provided offset. + * @param parameterOffset The offset of the parameter. + */ + function transformDecoratorsOfParameter(decorators, parameterOffset) { + var expressions; + if (decorators) { + expressions = []; + for (var _i = 0, decorators_1 = decorators; _i < decorators_1.length; _i++) { + var decorator = decorators_1[_i]; + var helper = createParamHelper(context, transformDecorator(decorator), parameterOffset, + /*location*/ decorator.expression); + ts.setEmitFlags(helper, 1536 /* NoComments */); + expressions.push(helper); + } + } + return expressions; + } + /** + * Adds optional type metadata for a declaration. + * + * @param node The declaration node. + * @param decoratorExpressions The destination array to which to add new decorator expressions. + */ + function addTypeMetadata(node, container, decoratorExpressions) { + if (USE_NEW_TYPE_METADATA_FORMAT) { + addNewTypeMetadata(node, container, decoratorExpressions); + } + else { + addOldTypeMetadata(node, container, decoratorExpressions); + } + } + function addOldTypeMetadata(node, container, decoratorExpressions) { + if (compilerOptions.emitDecoratorMetadata) { + if (shouldAddTypeMetadata(node)) { + decoratorExpressions.push(createMetadataHelper(context, "design:type", serializeTypeOfNode(node))); + } + if (shouldAddParamTypesMetadata(node)) { + decoratorExpressions.push(createMetadataHelper(context, "design:paramtypes", serializeParameterTypesOfNode(node, container))); + } + if (shouldAddReturnTypeMetadata(node)) { + decoratorExpressions.push(createMetadataHelper(context, "design:returntype", serializeReturnTypeOfNode(node))); + } + } + } + function addNewTypeMetadata(node, container, decoratorExpressions) { + if (compilerOptions.emitDecoratorMetadata) { + var properties = void 0; + if (shouldAddTypeMetadata(node)) { + (properties || (properties = [])).push(ts.createPropertyAssignment("type", ts.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, ts.createToken(37 /* EqualsGreaterThanToken */), serializeTypeOfNode(node)))); + } + if (shouldAddParamTypesMetadata(node)) { + (properties || (properties = [])).push(ts.createPropertyAssignment("paramTypes", ts.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, ts.createToken(37 /* EqualsGreaterThanToken */), serializeParameterTypesOfNode(node, container)))); + } + if (shouldAddReturnTypeMetadata(node)) { + (properties || (properties = [])).push(ts.createPropertyAssignment("returnType", ts.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, ts.createToken(37 /* EqualsGreaterThanToken */), serializeReturnTypeOfNode(node)))); + } + if (properties) { + decoratorExpressions.push(createMetadataHelper(context, "design:typeinfo", ts.createObjectLiteral(properties, /*multiLine*/ true))); + } + } + } + /** + * Determines whether to emit the "design:type" metadata based on the node's kind. + * The caller should have already tested whether the node has decorators and whether the + * emitDecoratorMetadata compiler option is set. + * + * @param node The node to test. + */ + function shouldAddTypeMetadata(node) { + var kind = node.kind; + return kind === 156 /* MethodDeclaration */ + || kind === 158 /* GetAccessor */ + || kind === 159 /* SetAccessor */ + || kind === 154 /* PropertyDeclaration */; + } + /** + * Determines whether to emit the "design:returntype" metadata based on the node's kind. + * The caller should have already tested whether the node has decorators and whether the + * emitDecoratorMetadata compiler option is set. + * + * @param node The node to test. + */ + function shouldAddReturnTypeMetadata(node) { + return node.kind === 156 /* MethodDeclaration */; + } + /** + * Determines whether to emit the "design:paramtypes" metadata based on the node's kind. + * The caller should have already tested whether the node has decorators and whether the + * emitDecoratorMetadata compiler option is set. + * + * @param node The node to test. + */ + function shouldAddParamTypesMetadata(node) { + switch (node.kind) { + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + return ts.getFirstConstructorWithBody(node) !== undefined; + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + return true; + } + return false; + } + function getAccessorTypeNode(node) { + var accessors = resolver.getAllAccessorDeclarations(node); + return accessors.setAccessor && ts.getSetAccessorTypeAnnotationNode(accessors.setAccessor) + || accessors.getAccessor && ts.getEffectiveReturnTypeNode(accessors.getAccessor); + } + /** + * Serializes the type of a node for use with decorator type metadata. + * + * @param node The node that should have its type serialized. + */ + function serializeTypeOfNode(node) { + switch (node.kind) { + case 154 /* PropertyDeclaration */: + case 151 /* Parameter */: + return serializeTypeNode(node.type); + case 159 /* SetAccessor */: + case 158 /* GetAccessor */: + return serializeTypeNode(getAccessorTypeNode(node)); + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 156 /* MethodDeclaration */: + return ts.createIdentifier("Function"); + default: + return ts.createVoidZero(); + } + } + /** + * Serializes the types of the parameters of a node for use with decorator type metadata. + * + * @param node The node that should have its parameter types serialized. + */ + function serializeParameterTypesOfNode(node, container) { + var valueDeclaration = ts.isClassLike(node) + ? ts.getFirstConstructorWithBody(node) + : ts.isFunctionLike(node) && ts.nodeIsPresent(node.body) + ? node + : undefined; + var expressions = []; + if (valueDeclaration) { + var parameters = getParametersOfDecoratedDeclaration(valueDeclaration, container); + var numParameters = parameters.length; + for (var i = 0; i < numParameters; i++) { + var parameter = parameters[i]; + if (i === 0 && ts.isIdentifier(parameter.name) && parameter.name.escapedText === "this") { + continue; + } + if (parameter.dotDotDotToken) { + expressions.push(serializeTypeNode(ts.getRestParameterElementType(parameter.type))); + } + else { + expressions.push(serializeTypeOfNode(parameter)); + } + } + } + return ts.createArrayLiteral(expressions); + } + function getParametersOfDecoratedDeclaration(node, container) { + if (container && node.kind === 158 /* GetAccessor */) { + var setAccessor = ts.getAllAccessorDeclarations(container.members, node).setAccessor; + if (setAccessor) { + return setAccessor.parameters; + } + } + return node.parameters; + } + /** + * Serializes the return type of a node for use with decorator type metadata. + * + * @param node The node that should have its return type serialized. + */ + function serializeReturnTypeOfNode(node) { + if (ts.isFunctionLike(node) && node.type) { + return serializeTypeNode(node.type); + } + else if (ts.isAsyncFunction(node)) { + return ts.createIdentifier("Promise"); + } + return ts.createVoidZero(); + } + /** + * Serializes a type node for use with decorator type metadata. + * + * Types are serialized in the following fashion: + * - Void types point to "undefined" (e.g. "void 0") + * - Function and Constructor types point to the global "Function" constructor. + * - Interface types with a call or construct signature types point to the global + * "Function" constructor. + * - Array and Tuple types point to the global "Array" constructor. + * - Type predicates and booleans point to the global "Boolean" constructor. + * - String literal types and strings point to the global "String" constructor. + * - Enum and number types point to the global "Number" constructor. + * - Symbol types point to the global "Symbol" constructor. + * - Type references to classes (or class-like variables) point to the constructor for the class. + * - Anything else points to the global "Object" constructor. + * + * @param node The type node to serialize. + */ + function serializeTypeNode(node) { + if (node === undefined) { + return ts.createIdentifier("Object"); + } + switch (node.kind) { + case 106 /* VoidKeyword */: + case 141 /* UndefinedKeyword */: + case 96 /* NullKeyword */: + case 132 /* NeverKeyword */: + return ts.createVoidZero(); + case 177 /* ParenthesizedType */: + return serializeTypeNode(node.type); + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + return ts.createIdentifier("Function"); + case 169 /* ArrayType */: + case 170 /* TupleType */: + return ts.createIdentifier("Array"); + case 163 /* TypePredicate */: + case 123 /* BooleanKeyword */: + return ts.createIdentifier("Boolean"); + case 138 /* StringKeyword */: + return ts.createIdentifier("String"); + case 136 /* ObjectKeyword */: + return ts.createIdentifier("Object"); + case 182 /* LiteralType */: + switch (node.literal.kind) { + case 10 /* StringLiteral */: + return ts.createIdentifier("String"); + case 8 /* NumericLiteral */: + return ts.createIdentifier("Number"); + case 9 /* BigIntLiteral */: + return getGlobalBigIntNameWithFallback(); + case 102 /* TrueKeyword */: + case 87 /* FalseKeyword */: + return ts.createIdentifier("Boolean"); + default: + return ts.Debug.failBadSyntaxKind(node.literal); + } + case 135 /* NumberKeyword */: + return ts.createIdentifier("Number"); + case 146 /* BigIntKeyword */: + return getGlobalBigIntNameWithFallback(); + case 139 /* SymbolKeyword */: + return languageVersion < 2 /* ES2015 */ + ? getGlobalSymbolNameWithFallback() + : ts.createIdentifier("Symbol"); + case 164 /* TypeReference */: + return serializeTypeReferenceNode(node); + case 174 /* IntersectionType */: + case 173 /* UnionType */: + return serializeTypeList(node.types); + case 175 /* ConditionalType */: + return serializeTypeList([node.trueType, node.falseType]); + case 167 /* TypeQuery */: + case 179 /* TypeOperator */: + case 180 /* IndexedAccessType */: + case 181 /* MappedType */: + case 168 /* TypeLiteral */: + case 120 /* AnyKeyword */: + case 143 /* UnknownKeyword */: + case 178 /* ThisType */: + case 183 /* ImportType */: + break; + default: + return ts.Debug.failBadSyntaxKind(node); + } + return ts.createIdentifier("Object"); + } + function serializeTypeList(types) { + // Note when updating logic here also update getEntityNameForDecoratorMetadata + // so that aliases can be marked as referenced + var serializedUnion; + for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { + var typeNode = types_17[_i]; + while (typeNode.kind === 177 /* ParenthesizedType */) { + typeNode = typeNode.type; // Skip parens if need be + } + if (typeNode.kind === 132 /* NeverKeyword */) { + continue; // Always elide `never` from the union/intersection if possible + } + if (!strictNullChecks && (typeNode.kind === 96 /* NullKeyword */ || typeNode.kind === 141 /* UndefinedKeyword */)) { + continue; // Elide null and undefined from unions for metadata, just like what we did prior to the implementation of strict null checks + } + var serializedIndividual = serializeTypeNode(typeNode); + if (ts.isIdentifier(serializedIndividual) && serializedIndividual.escapedText === "Object") { + // One of the individual is global object, return immediately + return serializedIndividual; + } + // If there exists union that is not void 0 expression, check if the the common type is identifier. + // anything more complex and we will just default to Object + else if (serializedUnion) { + // Different types + if (!ts.isIdentifier(serializedUnion) || + !ts.isIdentifier(serializedIndividual) || + serializedUnion.escapedText !== serializedIndividual.escapedText) { + return ts.createIdentifier("Object"); + } + } + else { + // Initialize the union type + serializedUnion = serializedIndividual; + } + } + // If we were able to find common type, use it + return serializedUnion || ts.createVoidZero(); // Fallback is only hit if all union constituients are null/undefined/never + } + /** + * Serializes a TypeReferenceNode to an appropriate JS constructor value for use with + * decorator type metadata. + * + * @param node The type reference node. + */ + function serializeTypeReferenceNode(node) { + var kind = resolver.getTypeReferenceSerializationKind(node.typeName, currentNameScope || currentLexicalScope); + switch (kind) { + case ts.TypeReferenceSerializationKind.Unknown: + // From conditional type type reference that cannot be resolved is Similar to any or unknown + if (ts.findAncestor(node, function (n) { return n.parent && ts.isConditionalTypeNode(n.parent) && (n.parent.trueType === n || n.parent.falseType === n); })) { + return ts.createIdentifier("Object"); + } + var serialized = serializeEntityNameAsExpressionFallback(node.typeName); + var temp = ts.createTempVariable(hoistVariableDeclaration); + return ts.createConditional(ts.createTypeCheck(ts.createAssignment(temp, serialized), "function"), temp, ts.createIdentifier("Object")); + case ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue: + return serializeEntityNameAsExpression(node.typeName); + case ts.TypeReferenceSerializationKind.VoidNullableOrNeverType: + return ts.createVoidZero(); + case ts.TypeReferenceSerializationKind.BigIntLikeType: + return getGlobalBigIntNameWithFallback(); + case ts.TypeReferenceSerializationKind.BooleanType: + return ts.createIdentifier("Boolean"); + case ts.TypeReferenceSerializationKind.NumberLikeType: + return ts.createIdentifier("Number"); + case ts.TypeReferenceSerializationKind.StringLikeType: + return ts.createIdentifier("String"); + case ts.TypeReferenceSerializationKind.ArrayLikeType: + return ts.createIdentifier("Array"); + case ts.TypeReferenceSerializationKind.ESSymbolType: + return languageVersion < 2 /* ES2015 */ + ? getGlobalSymbolNameWithFallback() + : ts.createIdentifier("Symbol"); + case ts.TypeReferenceSerializationKind.TypeWithCallSignature: + return ts.createIdentifier("Function"); + case ts.TypeReferenceSerializationKind.Promise: + return ts.createIdentifier("Promise"); + case ts.TypeReferenceSerializationKind.ObjectType: + return ts.createIdentifier("Object"); + default: + return ts.Debug.assertNever(kind); + } + } + function createCheckedValue(left, right) { + return ts.createLogicalAnd(ts.createStrictInequality(ts.createTypeOf(left), ts.createLiteral("undefined")), right); + } + /** + * Serializes an entity name which may not exist at runtime, but whose access shouldn't throw + * + * @param node The entity name to serialize. + */ + function serializeEntityNameAsExpressionFallback(node) { + if (node.kind === 72 /* Identifier */) { + // A -> typeof A !== undefined && A + var copied = serializeEntityNameAsExpression(node); + return createCheckedValue(copied, copied); + } + if (node.left.kind === 72 /* Identifier */) { + // A.B -> typeof A !== undefined && A.B + return createCheckedValue(serializeEntityNameAsExpression(node.left), serializeEntityNameAsExpression(node)); + } + // A.B.C -> typeof A !== undefined && (_a = A.B) !== void 0 && _a.C + var left = serializeEntityNameAsExpressionFallback(node.left); + var temp = ts.createTempVariable(hoistVariableDeclaration); + return ts.createLogicalAnd(ts.createLogicalAnd(left.left, ts.createStrictInequality(ts.createAssignment(temp, left.right), ts.createVoidZero())), ts.createPropertyAccess(temp, node.right)); + } + /** + * Serializes an entity name as an expression for decorator type metadata. + * + * @param node The entity name to serialize. + */ + function serializeEntityNameAsExpression(node) { + switch (node.kind) { + case 72 /* Identifier */: + // Create a clone of the name with a new parent, and treat it as if it were + // a source tree node for the purposes of the checker. + var name = ts.getMutableClone(node); + name.flags &= ~8 /* Synthesized */; + name.original = undefined; + name.parent = ts.getParseTreeNode(currentLexicalScope); // ensure the parent is set to a parse tree node. + return name; + case 148 /* QualifiedName */: + return serializeQualifiedNameAsExpression(node); + } + } + /** + * Serializes an qualified name as an expression for decorator type metadata. + * + * @param node The qualified name to serialize. + * @param useFallback A value indicating whether to use logical operators to test for the + * qualified name at runtime. + */ + function serializeQualifiedNameAsExpression(node) { + return ts.createPropertyAccess(serializeEntityNameAsExpression(node.left), node.right); + } + /** + * Gets an expression that points to the global "Symbol" constructor at runtime if it is + * available. + */ + function getGlobalSymbolNameWithFallback() { + return ts.createConditional(ts.createTypeCheck(ts.createIdentifier("Symbol"), "function"), ts.createIdentifier("Symbol"), ts.createIdentifier("Object")); + } + /** + * Gets an expression that points to the global "BigInt" constructor at runtime if it is + * available. + */ + function getGlobalBigIntNameWithFallback() { + return languageVersion < 6 /* ESNext */ + ? ts.createConditional(ts.createTypeCheck(ts.createIdentifier("BigInt"), "function"), ts.createIdentifier("BigInt"), ts.createIdentifier("Object")) + : ts.createIdentifier("BigInt"); + } + /** + * A simple inlinable expression is an expression which can be copied into multiple locations + * without risk of repeating any sideeffects and whose value could not possibly change between + * any such locations + */ + function isSimpleInlineableExpression(expression) { + return !ts.isIdentifier(expression) && ts.isSimpleCopiableExpression(expression) || + ts.isWellKnownSymbolSyntactically(expression); + } + /** + * Gets an expression that represents a property name. For a computed property, a + * name is generated for the node. + * + * @param member The member whose name should be converted into an expression. + */ + function getExpressionForPropertyName(member, generateNameForComputedPropertyName) { + var name = member.name; + if (ts.isComputedPropertyName(name)) { + return generateNameForComputedPropertyName && !isSimpleInlineableExpression(name.expression) + ? ts.getGeneratedNameForNode(name) + : name.expression; + } + else if (ts.isIdentifier(name)) { + return ts.createLiteral(ts.idText(name)); + } + else { + return ts.getSynthesizedClone(name); + } + } + /** + * If the name is a computed property, this function transforms it, then either returns an expression which caches the + * value of the result or the expression itself if the value is either unused or safe to inline into multiple locations + * @param shouldHoist Does the expression need to be reused? (ie, for an initializer or a decorator) + * @param omitSimple Should expressions with no observable side-effects be elided? (ie, the expression is not hoisted for a decorator or initializer and is a literal) + */ + function getPropertyNameExpressionIfNeeded(name, shouldHoist, omitSimple) { + if (ts.isComputedPropertyName(name)) { + var expression = ts.visitNode(name.expression, visitor, ts.isExpression); + var innerExpression = ts.skipPartiallyEmittedExpressions(expression); + var inlinable = isSimpleInlineableExpression(innerExpression); + if (!inlinable && shouldHoist) { + var generatedName = ts.getGeneratedNameForNode(name); + hoistVariableDeclaration(generatedName); + return ts.createAssignment(generatedName, expression); + } + return (omitSimple && (inlinable || ts.isIdentifier(innerExpression))) ? undefined : expression; + } + } + /** + * Visits the property name of a class element, for use when emitting property + * initializers. For a computed property on a node with decorators, a temporary + * value is stored for later use. + * + * @param member The member whose name should be visited. + */ + function visitPropertyNameOfClassElement(member) { + var name = member.name; + var expr = getPropertyNameExpressionIfNeeded(name, ts.some(member.decorators), /*omitSimple*/ false); + if (expr) { // expr only exists if `name` is a computed property name + // Inline any pending expressions from previous elided or relocated computed property name expressions in order to preserve execution order + if (ts.some(pendingExpressions)) { + expr = ts.inlineExpressions(pendingExpressions.concat([expr])); + pendingExpressions.length = 0; + } + return ts.updateComputedPropertyName(name, expr); + } + else { + return name; + } + } + /** + * Transforms a HeritageClause with TypeScript syntax. + * + * This function will only be called when one of the following conditions are met: + * - The node is a non-`extends` heritage clause that should be elided. + * - The node is an `extends` heritage clause that should be visited, but only allow a single type. + * + * @param node The HeritageClause to transform. + */ + function visitHeritageClause(node) { + if (node.token === 86 /* ExtendsKeyword */) { + var types = ts.visitNodes(node.types, visitor, ts.isExpressionWithTypeArguments, 0, 1); + return ts.setTextRange(ts.createHeritageClause(86 /* ExtendsKeyword */, types), node); + } + return undefined; + } + /** + * Transforms an ExpressionWithTypeArguments with TypeScript syntax. + * + * This function will only be called when one of the following conditions are met: + * - The node contains type arguments that should be elided. + * + * @param node The ExpressionWithTypeArguments to transform. + */ + function visitExpressionWithTypeArguments(node) { + return ts.updateExpressionWithTypeArguments(node, + /*typeArguments*/ undefined, ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression)); + } + /** + * Determines whether to emit a function-like declaration. We should not emit the + * declaration if it does not have a body. + * + * @param node The declaration node. + */ + function shouldEmitFunctionLikeDeclaration(node) { + return !ts.nodeIsMissing(node.body); + } + function visitPropertyDeclaration(node) { + var expr = getPropertyNameExpressionIfNeeded(node.name, ts.some(node.decorators) || !!node.initializer, /*omitSimple*/ true); + if (expr && !isSimpleInlineableExpression(expr)) { + (pendingExpressions || (pendingExpressions = [])).push(expr); + } + return undefined; + } + function visitConstructor(node) { + if (!shouldEmitFunctionLikeDeclaration(node)) { + return undefined; + } + return ts.updateConstructor(node, ts.visitNodes(node.decorators, visitor, ts.isDecorator), ts.visitNodes(node.modifiers, visitor, ts.isModifier), ts.visitParameterList(node.parameters, visitor, context), ts.visitFunctionBody(node.body, visitor, context)); + } + /** + * Visits a method declaration of a class. + * + * This function will be called when one of the following conditions are met: + * - The node is an overload + * - The node is marked as abstract, public, private, protected, or readonly + * - The node has a computed property name + * + * @param node The method node. + */ + function visitMethodDeclaration(node) { + if (!shouldEmitFunctionLikeDeclaration(node)) { + return undefined; + } + var updated = ts.updateMethod(node, + /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, visitPropertyNameOfClassElement(node), + /*questionToken*/ undefined, + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context)); + if (updated !== node) { + // While we emit the source map for the node after skipping decorators and modifiers, + // we need to emit the comments for the original range. + ts.setCommentRange(updated, node); + ts.setSourceMapRange(updated, ts.moveRangePastDecorators(node)); + } + return updated; + } + /** + * Determines whether to emit an accessor declaration. We should not emit the + * declaration if it does not have a body and is abstract. + * + * @param node The declaration node. + */ + function shouldEmitAccessorDeclaration(node) { + return !(ts.nodeIsMissing(node.body) && ts.hasModifier(node, 128 /* Abstract */)); + } + /** + * Visits a get accessor declaration of a class. + * + * This function will be called when one of the following conditions are met: + * - The node is marked as abstract, public, private, or protected + * - The node has a computed property name + * + * @param node The get accessor node. + */ + function visitGetAccessor(node) { + if (!shouldEmitAccessorDeclaration(node)) { + return undefined; + } + var updated = ts.updateGetAccessor(node, + /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), visitPropertyNameOfClassElement(node), ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context) || ts.createBlock([])); + if (updated !== node) { + // While we emit the source map for the node after skipping decorators and modifiers, + // we need to emit the comments for the original range. + ts.setCommentRange(updated, node); + ts.setSourceMapRange(updated, ts.moveRangePastDecorators(node)); + } + return updated; + } + /** + * Visits a set accessor declaration of a class. + * + * This function will be called when one of the following conditions are met: + * - The node is marked as abstract, public, private, or protected + * - The node has a computed property name + * + * @param node The set accessor node. + */ + function visitSetAccessor(node) { + if (!shouldEmitAccessorDeclaration(node)) { + return undefined; + } + var updated = ts.updateSetAccessor(node, + /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), visitPropertyNameOfClassElement(node), ts.visitParameterList(node.parameters, visitor, context), ts.visitFunctionBody(node.body, visitor, context) || ts.createBlock([])); + if (updated !== node) { + // While we emit the source map for the node after skipping decorators and modifiers, + // we need to emit the comments for the original range. + ts.setCommentRange(updated, node); + ts.setSourceMapRange(updated, ts.moveRangePastDecorators(node)); + } + return updated; + } + /** + * Visits a function declaration. + * + * This function will be called when one of the following conditions are met: + * - The node is an overload + * - The node is exported from a TypeScript namespace + * - The node has decorators + * + * @param node The function node. + */ + function visitFunctionDeclaration(node) { + if (!shouldEmitFunctionLikeDeclaration(node)) { + return ts.createNotEmittedStatement(node); + } + var updated = ts.updateFunctionDeclaration(node, + /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, node.name, + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context) || ts.createBlock([])); + if (isExportOfNamespace(node)) { + var statements = [updated]; + addExportMemberAssignment(statements, node); + return statements; + } + return updated; + } + /** + * Visits a function expression node. + * + * This function will be called when one of the following conditions are met: + * - The node has type annotations + * + * @param node The function expression node. + */ + function visitFunctionExpression(node) { + if (!shouldEmitFunctionLikeDeclaration(node)) { + return ts.createOmittedExpression(); + } + var updated = ts.updateFunctionExpression(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, node.name, + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context) || ts.createBlock([])); + return updated; + } + /** + * @remarks + * This function will be called when one of the following conditions are met: + * - The node has type annotations + */ + function visitArrowFunction(node) { + var updated = ts.updateArrowFunction(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, node.equalsGreaterThanToken, ts.visitFunctionBody(node.body, visitor, context)); + return updated; + } + /** + * Visits a parameter declaration node. + * + * This function will be called when one of the following conditions are met: + * - The node has an accessibility modifier. + * - The node has a questionToken. + * - The node's kind is ThisKeyword. + * + * @param node The parameter declaration node. + */ + function visitParameter(node) { + if (ts.parameterIsThisKeyword(node)) { + return undefined; + } + var parameter = ts.createParameter( + /*decorators*/ undefined, + /*modifiers*/ undefined, node.dotDotDotToken, ts.visitNode(node.name, visitor, ts.isBindingName), + /*questionToken*/ undefined, + /*type*/ undefined, ts.visitNode(node.initializer, visitor, ts.isExpression)); + // While we emit the source map for the node after skipping decorators and modifiers, + // we need to emit the comments for the original range. + ts.setOriginalNode(parameter, node); + ts.setTextRange(parameter, ts.moveRangePastModifiers(node)); + ts.setCommentRange(parameter, node); + ts.setSourceMapRange(parameter, ts.moveRangePastModifiers(node)); + ts.setEmitFlags(parameter.name, 32 /* NoTrailingSourceMap */); + return parameter; + } + /** + * Visits a variable statement in a namespace. + * + * This function will be called when one of the following conditions are met: + * - The node is exported from a TypeScript namespace. + */ + function visitVariableStatement(node) { + if (isExportOfNamespace(node)) { + var variables = ts.getInitializedVariables(node.declarationList); + if (variables.length === 0) { + // elide statement if there are no initialized variables. + return undefined; + } + return ts.setTextRange(ts.createExpressionStatement(ts.inlineExpressions(ts.map(variables, transformInitializedVariable))), node); + } + else { + return ts.visitEachChild(node, visitor, context); + } + } + function transformInitializedVariable(node) { + var name = node.name; + if (ts.isBindingPattern(name)) { + return ts.flattenDestructuringAssignment(node, visitor, context, 0 /* All */, + /*needsValue*/ false, createNamespaceExportExpression); + } + else { + return ts.setTextRange(ts.createAssignment(getNamespaceMemberNameWithSourceMapsAndWithoutComments(name), ts.visitNode(node.initializer, visitor, ts.isExpression)), + /*location*/ node); + } + } + function visitVariableDeclaration(node) { + return ts.updateVariableDeclaration(node, ts.visitNode(node.name, visitor, ts.isBindingName), + /*type*/ undefined, ts.visitNode(node.initializer, visitor, ts.isExpression)); + } + /** + * Visits a parenthesized expression that contains either a type assertion or an `as` + * expression. + * + * @param node The parenthesized expression node. + */ + function visitParenthesizedExpression(node) { + var innerExpression = ts.skipOuterExpressions(node.expression, ~2 /* Assertions */); + if (ts.isAssertionExpression(innerExpression)) { + // Make sure we consider all nested cast expressions, e.g.: + // (-A).x; + var expression = ts.visitNode(node.expression, visitor, ts.isExpression); + // We have an expression of the form: (SubExpr). Emitting this as (SubExpr) + // is really not desirable. We would like to emit the subexpression as-is. Omitting + // the parentheses, however, could cause change in the semantics of the generated + // code if the casted expression has a lower precedence than the rest of the + // expression. + // + // To preserve comments, we return a "PartiallyEmittedExpression" here which will + // preserve the position information of the original expression. + // + // Due to the auto-parenthesization rules used by the visitor and factory functions + // we can safely elide the parentheses here, as a new synthetic + // ParenthesizedExpression will be inserted if we remove parentheses too + // aggressively. + // HOWEVER - if there are leading comments on the expression itself, to handle ASI + // correctly for return and throw, we must keep the parenthesis + if (ts.length(ts.getLeadingCommentRangesOfNode(expression, currentSourceFile))) { + return ts.updateParen(node, expression); + } + return ts.createPartiallyEmittedExpression(expression, node); + } + return ts.visitEachChild(node, visitor, context); + } + function visitAssertionExpression(node) { + var expression = ts.visitNode(node.expression, visitor, ts.isExpression); + return ts.createPartiallyEmittedExpression(expression, node); + } + function visitNonNullExpression(node) { + var expression = ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression); + return ts.createPartiallyEmittedExpression(expression, node); + } + function visitCallExpression(node) { + return ts.updateCall(node, ts.visitNode(node.expression, visitor, ts.isExpression), + /*typeArguments*/ undefined, ts.visitNodes(node.arguments, visitor, ts.isExpression)); + } + function visitNewExpression(node) { + return ts.updateNew(node, ts.visitNode(node.expression, visitor, ts.isExpression), + /*typeArguments*/ undefined, ts.visitNodes(node.arguments, visitor, ts.isExpression)); + } + function visitTaggedTemplateExpression(node) { + return ts.updateTaggedTemplate(node, ts.visitNode(node.tag, visitor, ts.isExpression), + /*typeArguments*/ undefined, ts.visitNode(node.template, visitor, ts.isExpression)); + } + /** + * Determines whether to emit an enum declaration. + * + * @param node The enum declaration node. + */ + function shouldEmitEnumDeclaration(node) { + return !ts.isEnumConst(node) + || compilerOptions.preserveConstEnums + || compilerOptions.isolatedModules; + } + /** + * Visits an enum declaration. + * + * This function will be called any time a TypeScript enum is encountered. + * + * @param node The enum declaration node. + */ + function visitEnumDeclaration(node) { + if (!shouldEmitEnumDeclaration(node)) { + return undefined; + } + var statements = []; + // We request to be advised when the printer is about to print this node. This allows + // us to set up the correct state for later substitutions. + var emitFlags = 2 /* AdviseOnEmitNode */; + // If needed, we should emit a variable declaration for the enum. If we emit + // a leading variable declaration, we should not emit leading comments for the + // enum body. + var varAdded = addVarForEnumOrModuleDeclaration(statements, node); + if (varAdded) { + // We should still emit the comments if we are emitting a system module. + if (moduleKind !== ts.ModuleKind.System || currentLexicalScope !== currentSourceFile) { + emitFlags |= 512 /* NoLeadingComments */; + } + } + // `parameterName` is the declaration name used inside of the enum. + var parameterName = getNamespaceParameterName(node); + // `containerName` is the expression used inside of the enum for assignments. + var containerName = getNamespaceContainerName(node); + // `exportName` is the expression used within this node's container for any exported references. + var exportName = ts.hasModifier(node, 1 /* Export */) + ? ts.getExternalModuleOrNamespaceExportName(currentNamespaceContainerName, node, /*allowComments*/ false, /*allowSourceMaps*/ true) + : ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true); + // x || (x = {}) + // exports.x || (exports.x = {}) + var moduleArg = ts.createLogicalOr(exportName, ts.createAssignment(exportName, ts.createObjectLiteral())); + if (hasNamespaceQualifiedExportName(node)) { + // `localName` is the expression used within this node's containing scope for any local references. + var localName = ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true); + // x = (exports.x || (exports.x = {})) + moduleArg = ts.createAssignment(localName, moduleArg); + } + // (function (x) { + // x[x["y"] = 0] = "y"; + // ... + // })(x || (x = {})); + var enumStatement = ts.createExpressionStatement(ts.createCall(ts.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, parameterName)], + /*type*/ undefined, transformEnumBody(node, containerName)), + /*typeArguments*/ undefined, [moduleArg])); + ts.setOriginalNode(enumStatement, node); + if (varAdded) { + // If a variable was added, synthetic comments are emitted on it, not on the moduleStatement. + ts.setSyntheticLeadingComments(enumStatement, undefined); + ts.setSyntheticTrailingComments(enumStatement, undefined); + } + ts.setTextRange(enumStatement, node); + ts.addEmitFlags(enumStatement, emitFlags); + statements.push(enumStatement); + // Add a DeclarationMarker for the enum to preserve trailing comments and mark + // the end of the declaration. + statements.push(ts.createEndOfDeclarationMarker(node)); + return statements; + } + /** + * Transforms the body of an enum declaration. + * + * @param node The enum declaration node. + */ + function transformEnumBody(node, localName) { + var savedCurrentNamespaceLocalName = currentNamespaceContainerName; + currentNamespaceContainerName = localName; + var statements = []; + startLexicalEnvironment(); + var members = ts.map(node.members, transformEnumMember); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + ts.addRange(statements, members); + currentNamespaceContainerName = savedCurrentNamespaceLocalName; + return ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), /*location*/ node.members), + /*multiLine*/ true); + } + /** + * Transforms an enum member into a statement. + * + * @param member The enum member node. + */ + function transformEnumMember(member) { + // enums don't support computed properties + // we pass false as 'generateNameForComputedPropertyName' for a backward compatibility purposes + // old emitter always generate 'expression' part of the name as-is. + var name = getExpressionForPropertyName(member, /*generateNameForComputedPropertyName*/ false); + var valueExpression = transformEnumMemberDeclarationValue(member); + var innerAssignment = ts.createAssignment(ts.createElementAccess(currentNamespaceContainerName, name), valueExpression); + var outerAssignment = valueExpression.kind === 10 /* StringLiteral */ ? + innerAssignment : + ts.createAssignment(ts.createElementAccess(currentNamespaceContainerName, innerAssignment), name); + return ts.setTextRange(ts.createExpressionStatement(ts.setTextRange(outerAssignment, member)), member); + } + /** + * Transforms the value of an enum member. + * + * @param member The enum member node. + */ + function transformEnumMemberDeclarationValue(member) { + var value = resolver.getConstantValue(member); + if (value !== undefined) { + return ts.createLiteral(value); + } + else { + enableSubstitutionForNonQualifiedEnumMembers(); + if (member.initializer) { + return ts.visitNode(member.initializer, visitor, ts.isExpression); + } + else { + return ts.createVoidZero(); + } + } + } + /** + * Determines whether to elide a module declaration. + * + * @param node The module declaration node. + */ + function shouldEmitModuleDeclaration(node) { + return ts.isInstantiatedModule(node, !!compilerOptions.preserveConstEnums || !!compilerOptions.isolatedModules); + } + /** + * Determines whether an exported declaration will have a qualified export name (e.g. `f.x` + * or `exports.x`). + */ + function hasNamespaceQualifiedExportName(node) { + return isExportOfNamespace(node) + || (isExternalModuleExport(node) + && moduleKind !== ts.ModuleKind.ES2015 + && moduleKind !== ts.ModuleKind.ESNext + && moduleKind !== ts.ModuleKind.System); + } + /** + * Records that a declaration was emitted in the current scope, if it was the first + * declaration for the provided symbol. + */ + function recordEmittedDeclarationInScope(node) { + if (!currentScopeFirstDeclarationsOfName) { + currentScopeFirstDeclarationsOfName = ts.createUnderscoreEscapedMap(); + } + var name = declaredNameInScope(node); + if (!currentScopeFirstDeclarationsOfName.has(name)) { + currentScopeFirstDeclarationsOfName.set(name, node); + } + } + /** + * Determines whether a declaration is the first declaration with + * the same name emitted in the current scope. + */ + function isFirstEmittedDeclarationInScope(node) { + if (currentScopeFirstDeclarationsOfName) { + var name = declaredNameInScope(node); + return currentScopeFirstDeclarationsOfName.get(name) === node; + } + return true; + } + function declaredNameInScope(node) { + ts.Debug.assertNode(node.name, ts.isIdentifier); + return node.name.escapedText; + } + /** + * Adds a leading VariableStatement for a enum or module declaration. + */ + function addVarForEnumOrModuleDeclaration(statements, node) { + // Emit a variable statement for the module. We emit top-level enums as a `var` + // declaration to avoid static errors in global scripts scripts due to redeclaration. + // enums in any other scope are emitted as a `let` declaration. + var statement = ts.createVariableStatement(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.createVariableDeclarationList([ + ts.createVariableDeclaration(ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true)) + ], currentLexicalScope.kind === 279 /* SourceFile */ ? 0 /* None */ : 1 /* Let */)); + ts.setOriginalNode(statement, node); + recordEmittedDeclarationInScope(node); + if (isFirstEmittedDeclarationInScope(node)) { + // Adjust the source map emit to match the old emitter. + if (node.kind === 243 /* EnumDeclaration */) { + ts.setSourceMapRange(statement.declarationList, node); + } + else { + ts.setSourceMapRange(statement, node); + } + // Trailing comments for module declaration should be emitted after the function closure + // instead of the variable statement: + // + // /** Module comment*/ + // module m1 { + // function foo4Export() { + // } + // } // trailing comment module + // + // Should emit: + // + // /** Module comment*/ + // var m1; + // (function (m1) { + // function foo4Export() { + // } + // })(m1 || (m1 = {})); // trailing comment module + // + ts.setCommentRange(statement, node); + ts.addEmitFlags(statement, 1024 /* NoTrailingComments */ | 4194304 /* HasEndOfDeclarationMarker */); + statements.push(statement); + return true; + } + else { + // For an EnumDeclaration or ModuleDeclaration that merges with a preceeding + // declaration we do not emit a leading variable declaration. To preserve the + // begin/end semantics of the declararation and to properly handle exports + // we wrap the leading variable declaration in a `MergeDeclarationMarker`. + var mergeMarker = ts.createMergeDeclarationMarker(statement); + ts.setEmitFlags(mergeMarker, 1536 /* NoComments */ | 4194304 /* HasEndOfDeclarationMarker */); + statements.push(mergeMarker); + return false; + } + } + /** + * Visits a module declaration node. + * + * This function will be called any time a TypeScript namespace (ModuleDeclaration) is encountered. + * + * @param node The module declaration node. + */ + function visitModuleDeclaration(node) { + if (!shouldEmitModuleDeclaration(node)) { + return ts.createNotEmittedStatement(node); + } + ts.Debug.assertNode(node.name, ts.isIdentifier, "A TypeScript namespace should have an Identifier name."); + enableSubstitutionForNamespaceExports(); + var statements = []; + // We request to be advised when the printer is about to print this node. This allows + // us to set up the correct state for later substitutions. + var emitFlags = 2 /* AdviseOnEmitNode */; + // If needed, we should emit a variable declaration for the module. If we emit + // a leading variable declaration, we should not emit leading comments for the + // module body. + var varAdded = addVarForEnumOrModuleDeclaration(statements, node); + if (varAdded) { + // We should still emit the comments if we are emitting a system module. + if (moduleKind !== ts.ModuleKind.System || currentLexicalScope !== currentSourceFile) { + emitFlags |= 512 /* NoLeadingComments */; + } + } + // `parameterName` is the declaration name used inside of the namespace. + var parameterName = getNamespaceParameterName(node); + // `containerName` is the expression used inside of the namespace for exports. + var containerName = getNamespaceContainerName(node); + // `exportName` is the expression used within this node's container for any exported references. + var exportName = ts.hasModifier(node, 1 /* Export */) + ? ts.getExternalModuleOrNamespaceExportName(currentNamespaceContainerName, node, /*allowComments*/ false, /*allowSourceMaps*/ true) + : ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true); + // x || (x = {}) + // exports.x || (exports.x = {}) + var moduleArg = ts.createLogicalOr(exportName, ts.createAssignment(exportName, ts.createObjectLiteral())); + if (hasNamespaceQualifiedExportName(node)) { + // `localName` is the expression used within this node's containing scope for any local references. + var localName = ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true); + // x = (exports.x || (exports.x = {})) + moduleArg = ts.createAssignment(localName, moduleArg); + } + // (function (x_1) { + // x_1.y = ...; + // })(x || (x = {})); + var moduleStatement = ts.createExpressionStatement(ts.createCall(ts.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, parameterName)], + /*type*/ undefined, transformModuleBody(node, containerName)), + /*typeArguments*/ undefined, [moduleArg])); + ts.setOriginalNode(moduleStatement, node); + if (varAdded) { + // If a variable was added, synthetic comments are emitted on it, not on the moduleStatement. + ts.setSyntheticLeadingComments(moduleStatement, undefined); + ts.setSyntheticTrailingComments(moduleStatement, undefined); + } + ts.setTextRange(moduleStatement, node); + ts.addEmitFlags(moduleStatement, emitFlags); + statements.push(moduleStatement); + // Add a DeclarationMarker for the namespace to preserve trailing comments and mark + // the end of the declaration. + statements.push(ts.createEndOfDeclarationMarker(node)); + return statements; + } + /** + * Transforms the body of a module declaration. + * + * @param node The module declaration node. + */ + function transformModuleBody(node, namespaceLocalName) { + var savedCurrentNamespaceContainerName = currentNamespaceContainerName; + var savedCurrentNamespace = currentNamespace; + var savedCurrentScopeFirstDeclarationsOfName = currentScopeFirstDeclarationsOfName; + currentNamespaceContainerName = namespaceLocalName; + currentNamespace = node; + currentScopeFirstDeclarationsOfName = undefined; + var statements = []; + startLexicalEnvironment(); + var statementsLocation; + var blockLocation; + var body = node.body; + if (body.kind === 245 /* ModuleBlock */) { + saveStateAndInvoke(body, function (body) { return ts.addRange(statements, ts.visitNodes(body.statements, namespaceElementVisitor, ts.isStatement)); }); + statementsLocation = body.statements; + blockLocation = body; + } + else { + var result = visitModuleDeclaration(body); + if (result) { + if (ts.isArray(result)) { + ts.addRange(statements, result); + } + else { + statements.push(result); + } + } + var moduleBlock = getInnerMostModuleDeclarationFromDottedModule(node).body; + statementsLocation = ts.moveRangePos(moduleBlock.statements, -1); + } + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + currentNamespaceContainerName = savedCurrentNamespaceContainerName; + currentNamespace = savedCurrentNamespace; + currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName; + var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), + /*location*/ statementsLocation), + /*multiLine*/ true); + ts.setTextRange(block, blockLocation); + // namespace hello.hi.world { + // function foo() {} + // + // // TODO, blah + // } + // + // should be emitted as + // + // var hello; + // (function (hello) { + // var hi; + // (function (hi) { + // var world; + // (function (world) { + // function foo() { } + // // TODO, blah + // })(world = hi.world || (hi.world = {})); + // })(hi = hello.hi || (hello.hi = {})); + // })(hello || (hello = {})); + // We only want to emit comment on the namespace which contains block body itself, not the containing namespaces. + if (body.kind !== 245 /* ModuleBlock */) { + ts.setEmitFlags(block, ts.getEmitFlags(block) | 1536 /* NoComments */); + } + return block; + } + function getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration) { + if (moduleDeclaration.body.kind === 244 /* ModuleDeclaration */) { + var recursiveInnerModule = getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration.body); + return recursiveInnerModule || moduleDeclaration.body; + } + } + /** + * Visits an import declaration, eliding it if it is not referenced. + * + * @param node The import declaration node. + */ + function visitImportDeclaration(node) { + if (!node.importClause) { + // Do not elide a side-effect only import declaration. + // import "foo"; + return node; + } + // Elide the declaration if the import clause was elided. + var importClause = ts.visitNode(node.importClause, visitImportClause, ts.isImportClause); + return importClause + ? ts.updateImportDeclaration(node, + /*decorators*/ undefined, + /*modifiers*/ undefined, importClause, node.moduleSpecifier) + : undefined; + } + /** + * Visits an import clause, eliding it if it is not referenced. + * + * @param node The import clause node. + */ + function visitImportClause(node) { + // Elide the import clause if we elide both its name and its named bindings. + var name = resolver.isReferencedAliasDeclaration(node) ? node.name : undefined; + var namedBindings = ts.visitNode(node.namedBindings, visitNamedImportBindings, ts.isNamedImportBindings); + return (name || namedBindings) ? ts.updateImportClause(node, name, namedBindings) : undefined; + } + /** + * Visits named import bindings, eliding it if it is not referenced. + * + * @param node The named import bindings node. + */ + function visitNamedImportBindings(node) { + if (node.kind === 251 /* NamespaceImport */) { + // Elide a namespace import if it is not referenced. + return resolver.isReferencedAliasDeclaration(node) ? node : undefined; + } + else { + // Elide named imports if all of its import specifiers are elided. + var elements = ts.visitNodes(node.elements, visitImportSpecifier, ts.isImportSpecifier); + return ts.some(elements) ? ts.updateNamedImports(node, elements) : undefined; + } + } + /** + * Visits an import specifier, eliding it if it is not referenced. + * + * @param node The import specifier node. + */ + function visitImportSpecifier(node) { + // Elide an import specifier if it is not referenced. + return resolver.isReferencedAliasDeclaration(node) ? node : undefined; + } + /** + * Visits an export assignment, eliding it if it does not contain a clause that resolves + * to a value. + * + * @param node The export assignment node. + */ + function visitExportAssignment(node) { + // Elide the export assignment if it does not reference a value. + return resolver.isValueAliasDeclaration(node) + ? ts.visitEachChild(node, visitor, context) + : undefined; + } + /** + * Visits an export declaration, eliding it if it does not contain a clause that resolves + * to a value. + * + * @param node The export declaration node. + */ + function visitExportDeclaration(node) { + if (!node.exportClause) { + // Elide a star export if the module it references does not export a value. + return compilerOptions.isolatedModules || resolver.moduleExportsSomeValue(node.moduleSpecifier) ? node : undefined; + } + if (!resolver.isValueAliasDeclaration(node)) { + // Elide the export declaration if it does not export a value. + return undefined; + } + // Elide the export declaration if all of its named exports are elided. + var exportClause = ts.visitNode(node.exportClause, visitNamedExports, ts.isNamedExports); + return exportClause + ? ts.updateExportDeclaration(node, + /*decorators*/ undefined, + /*modifiers*/ undefined, exportClause, node.moduleSpecifier) + : undefined; + } + /** + * Visits named exports, eliding it if it does not contain an export specifier that + * resolves to a value. + * + * @param node The named exports node. + */ + function visitNamedExports(node) { + // Elide the named exports if all of its export specifiers were elided. + var elements = ts.visitNodes(node.elements, visitExportSpecifier, ts.isExportSpecifier); + return ts.some(elements) ? ts.updateNamedExports(node, elements) : undefined; + } + /** + * Visits an export specifier, eliding it if it does not resolve to a value. + * + * @param node The export specifier node. + */ + function visitExportSpecifier(node) { + // Elide an export specifier if it does not reference a value. + return resolver.isValueAliasDeclaration(node) ? node : undefined; + } + /** + * Determines whether to emit an import equals declaration. + * + * @param node The import equals declaration node. + */ + function shouldEmitImportEqualsDeclaration(node) { + // preserve old compiler's behavior: emit 'var' for import declaration (even if we do not consider them referenced) when + // - current file is not external module + // - import declaration is top level and target is value imported by entity name + return resolver.isReferencedAliasDeclaration(node) + || (!ts.isExternalModule(currentSourceFile) + && resolver.isTopLevelValueImportEqualsWithEntityName(node)); + } + /** + * Visits an import equals declaration. + * + * @param node The import equals declaration node. + */ + function visitImportEqualsDeclaration(node) { + if (ts.isExternalModuleImportEqualsDeclaration(node)) { + // Elide external module `import=` if it is not referenced. + return resolver.isReferencedAliasDeclaration(node) + ? ts.visitEachChild(node, visitor, context) + : undefined; + } + if (!shouldEmitImportEqualsDeclaration(node)) { + return undefined; + } + var moduleReference = ts.createExpressionFromEntityName(node.moduleReference); + ts.setEmitFlags(moduleReference, 1536 /* NoComments */ | 2048 /* NoNestedComments */); + if (isNamedExternalModuleExport(node) || !isExportOfNamespace(node)) { + // export var ${name} = ${moduleReference}; + // var ${name} = ${moduleReference}; + return ts.setOriginalNode(ts.setTextRange(ts.createVariableStatement(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.createVariableDeclarationList([ + ts.setOriginalNode(ts.createVariableDeclaration(node.name, + /*type*/ undefined, moduleReference), node) + ])), node), node); + } + else { + // exports.${name} = ${moduleReference}; + return ts.setOriginalNode(createNamespaceExport(node.name, moduleReference, node), node); + } + } + /** + * Gets a value indicating whether the node is exported from a namespace. + * + * @param node The node to test. + */ + function isExportOfNamespace(node) { + return currentNamespace !== undefined && ts.hasModifier(node, 1 /* Export */); + } + /** + * Gets a value indicating whether the node is exported from an external module. + * + * @param node The node to test. + */ + function isExternalModuleExport(node) { + return currentNamespace === undefined && ts.hasModifier(node, 1 /* Export */); + } + /** + * Gets a value indicating whether the node is a named export from an external module. + * + * @param node The node to test. + */ + function isNamedExternalModuleExport(node) { + return isExternalModuleExport(node) + && !ts.hasModifier(node, 512 /* Default */); + } + /** + * Gets a value indicating whether the node is the default export of an external module. + * + * @param node The node to test. + */ + function isDefaultExternalModuleExport(node) { + return isExternalModuleExport(node) + && ts.hasModifier(node, 512 /* Default */); + } + /** + * Creates a statement for the provided expression. This is used in calls to `map`. + */ + function expressionToStatement(expression) { + return ts.createExpressionStatement(expression); + } + function addExportMemberAssignment(statements, node) { + var expression = ts.createAssignment(ts.getExternalModuleOrNamespaceExportName(currentNamespaceContainerName, node, /*allowComments*/ false, /*allowSourceMaps*/ true), ts.getLocalName(node)); + ts.setSourceMapRange(expression, ts.createRange(node.name ? node.name.pos : node.pos, node.end)); + var statement = ts.createExpressionStatement(expression); + ts.setSourceMapRange(statement, ts.createRange(-1, node.end)); + statements.push(statement); + } + function createNamespaceExport(exportName, exportValue, location) { + return ts.setTextRange(ts.createExpressionStatement(ts.createAssignment(ts.getNamespaceMemberName(currentNamespaceContainerName, exportName, /*allowComments*/ false, /*allowSourceMaps*/ true), exportValue)), location); + } + function createNamespaceExportExpression(exportName, exportValue, location) { + return ts.setTextRange(ts.createAssignment(getNamespaceMemberNameWithSourceMapsAndWithoutComments(exportName), exportValue), location); + } + function getNamespaceMemberNameWithSourceMapsAndWithoutComments(name) { + return ts.getNamespaceMemberName(currentNamespaceContainerName, name, /*allowComments*/ false, /*allowSourceMaps*/ true); + } + /** + * Gets the declaration name used inside of a namespace or enum. + */ + function getNamespaceParameterName(node) { + var name = ts.getGeneratedNameForNode(node); + ts.setSourceMapRange(name, node.name); + return name; + } + /** + * Gets the expression used to refer to a namespace or enum within the body + * of its declaration. + */ + function getNamespaceContainerName(node) { + return ts.getGeneratedNameForNode(node); + } + /** + * Gets a local alias for a class declaration if it is a decorated class with an internal + * reference to the static side of the class. This is necessary to avoid issues with + * double-binding semantics for the class name. + */ + function getClassAliasIfNeeded(node) { + if (resolver.getNodeCheckFlags(node) & 16777216 /* ClassWithConstructorReference */) { + enableSubstitutionForClassAliases(); + var classAlias = ts.createUniqueName(node.name && !ts.isGeneratedIdentifier(node.name) ? ts.idText(node.name) : "default"); + classAliases[ts.getOriginalNodeId(node)] = classAlias; + hoistVariableDeclaration(classAlias); + return classAlias; + } + } + function getClassPrototype(node) { + return ts.createPropertyAccess(ts.getDeclarationName(node), "prototype"); + } + function getClassMemberPrefix(node, member) { + return ts.hasModifier(member, 32 /* Static */) + ? ts.getDeclarationName(node) + : getClassPrototype(node); + } + function enableSubstitutionForNonQualifiedEnumMembers() { + if ((enabledSubstitutions & 8 /* NonQualifiedEnumMembers */) === 0) { + enabledSubstitutions |= 8 /* NonQualifiedEnumMembers */; + context.enableSubstitution(72 /* Identifier */); + } + } + function enableSubstitutionForClassAliases() { + if ((enabledSubstitutions & 1 /* ClassAliases */) === 0) { + enabledSubstitutions |= 1 /* ClassAliases */; + // We need to enable substitutions for identifiers. This allows us to + // substitute class names inside of a class declaration. + context.enableSubstitution(72 /* Identifier */); + // Keep track of class aliases. + classAliases = []; + } + } + function enableSubstitutionForNamespaceExports() { + if ((enabledSubstitutions & 2 /* NamespaceExports */) === 0) { + enabledSubstitutions |= 2 /* NamespaceExports */; + // We need to enable substitutions for identifiers and shorthand property assignments. This allows us to + // substitute the names of exported members of a namespace. + context.enableSubstitution(72 /* Identifier */); + context.enableSubstitution(276 /* ShorthandPropertyAssignment */); + // We need to be notified when entering and exiting namespaces. + context.enableEmitNotification(244 /* ModuleDeclaration */); + } + } + function isTransformedModuleDeclaration(node) { + return ts.getOriginalNode(node).kind === 244 /* ModuleDeclaration */; + } + function isTransformedEnumDeclaration(node) { + return ts.getOriginalNode(node).kind === 243 /* EnumDeclaration */; + } + /** + * Hook for node emit. + * + * @param hint A hint as to the intended usage of the node. + * @param node The node to emit. + * @param emit A callback used to emit the node in the printer. + */ + function onEmitNode(hint, node, emitCallback) { + var savedApplicableSubstitutions = applicableSubstitutions; + var savedCurrentSourceFile = currentSourceFile; + if (ts.isSourceFile(node)) { + currentSourceFile = node; + } + if (enabledSubstitutions & 2 /* NamespaceExports */ && isTransformedModuleDeclaration(node)) { + applicableSubstitutions |= 2 /* NamespaceExports */; + } + if (enabledSubstitutions & 8 /* NonQualifiedEnumMembers */ && isTransformedEnumDeclaration(node)) { + applicableSubstitutions |= 8 /* NonQualifiedEnumMembers */; + } + previousOnEmitNode(hint, node, emitCallback); + applicableSubstitutions = savedApplicableSubstitutions; + currentSourceFile = savedCurrentSourceFile; + } + /** + * Hooks node substitutions. + * + * @param hint A hint as to the intended usage of the node. + * @param node The node to substitute. + */ + function onSubstituteNode(hint, node) { + node = previousOnSubstituteNode(hint, node); + if (hint === 1 /* Expression */) { + return substituteExpression(node); + } + else if (ts.isShorthandPropertyAssignment(node)) { + return substituteShorthandPropertyAssignment(node); + } + return node; + } + function substituteShorthandPropertyAssignment(node) { + if (enabledSubstitutions & 2 /* NamespaceExports */) { + var name = node.name; + var exportedName = trySubstituteNamespaceExportedName(name); + if (exportedName) { + // A shorthand property with an assignment initializer is probably part of a + // destructuring assignment + if (node.objectAssignmentInitializer) { + var initializer = ts.createAssignment(exportedName, node.objectAssignmentInitializer); + return ts.setTextRange(ts.createPropertyAssignment(name, initializer), node); + } + return ts.setTextRange(ts.createPropertyAssignment(name, exportedName), node); + } + } + return node; + } + function substituteExpression(node) { + switch (node.kind) { + case 72 /* Identifier */: + return substituteExpressionIdentifier(node); + case 189 /* PropertyAccessExpression */: + return substitutePropertyAccessExpression(node); + case 190 /* ElementAccessExpression */: + return substituteElementAccessExpression(node); + } + return node; + } + function substituteExpressionIdentifier(node) { + return trySubstituteClassAlias(node) + || trySubstituteNamespaceExportedName(node) + || node; + } + function trySubstituteClassAlias(node) { + if (enabledSubstitutions & 1 /* ClassAliases */) { + if (resolver.getNodeCheckFlags(node) & 33554432 /* ConstructorReferenceInClass */) { + // Due to the emit for class decorators, any reference to the class from inside of the class body + // must instead be rewritten to point to a temporary variable to avoid issues with the double-bind + // behavior of class names in ES6. + // Also, when emitting statics for class expressions, we must substitute a class alias for + // constructor references in static property initializers. + var declaration = resolver.getReferencedValueDeclaration(node); + if (declaration) { + var classAlias = classAliases[declaration.id]; // TODO: GH#18217 + if (classAlias) { + var clone_1 = ts.getSynthesizedClone(classAlias); + ts.setSourceMapRange(clone_1, node); + ts.setCommentRange(clone_1, node); + return clone_1; + } + } + } + } + return undefined; + } + function trySubstituteNamespaceExportedName(node) { + // If this is explicitly a local name, do not substitute. + if (enabledSubstitutions & applicableSubstitutions && !ts.isGeneratedIdentifier(node) && !ts.isLocalName(node)) { + // If we are nested within a namespace declaration, we may need to qualifiy + // an identifier that is exported from a merged namespace. + var container = resolver.getReferencedExportContainer(node, /*prefixLocals*/ false); + if (container && container.kind !== 279 /* SourceFile */) { + var substitute = (applicableSubstitutions & 2 /* NamespaceExports */ && container.kind === 244 /* ModuleDeclaration */) || + (applicableSubstitutions & 8 /* NonQualifiedEnumMembers */ && container.kind === 243 /* EnumDeclaration */); + if (substitute) { + return ts.setTextRange(ts.createPropertyAccess(ts.getGeneratedNameForNode(container), node), + /*location*/ node); + } + } + } + return undefined; + } + function substitutePropertyAccessExpression(node) { + return substituteConstantValue(node); + } + function substituteElementAccessExpression(node) { + return substituteConstantValue(node); + } + function substituteConstantValue(node) { + var constantValue = tryGetConstEnumValue(node); + if (constantValue !== undefined) { + // track the constant value on the node for the printer in needsDotDotForPropertyAccess + ts.setConstantValue(node, constantValue); + var substitute = ts.createLiteral(constantValue); + if (!compilerOptions.removeComments) { + var propertyName = ts.isPropertyAccessExpression(node) + ? ts.declarationNameToString(node.name) + : ts.getTextOfNode(node.argumentExpression); + ts.addSyntheticTrailingComment(substitute, 3 /* MultiLineCommentTrivia */, " " + propertyName + " "); + } + return substitute; + } + return node; + } + function tryGetConstEnumValue(node) { + if (compilerOptions.isolatedModules) { + return undefined; + } + return ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node) ? resolver.getConstantValue(node) : undefined; + } + } + ts.transformTypeScript = transformTypeScript; + function createDecorateHelper(context, decoratorExpressions, target, memberName, descriptor, location) { + var argumentsArray = []; + argumentsArray.push(ts.createArrayLiteral(decoratorExpressions, /*multiLine*/ true)); + argumentsArray.push(target); + if (memberName) { + argumentsArray.push(memberName); + if (descriptor) { + argumentsArray.push(descriptor); + } + } + context.requestEmitHelper(decorateHelper); + return ts.setTextRange(ts.createCall(ts.getHelperName("__decorate"), + /*typeArguments*/ undefined, argumentsArray), location); + } + var decorateHelper = { + name: "typescript:decorate", + scoped: false, + priority: 2, + text: "\n var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n };" + }; + function createMetadataHelper(context, metadataKey, metadataValue) { + context.requestEmitHelper(metadataHelper); + return ts.createCall(ts.getHelperName("__metadata"), + /*typeArguments*/ undefined, [ + ts.createLiteral(metadataKey), + metadataValue + ]); + } + var metadataHelper = { + name: "typescript:metadata", + scoped: false, + priority: 3, + text: "\n var __metadata = (this && this.__metadata) || function (k, v) {\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(k, v);\n };" + }; + function createParamHelper(context, expression, parameterOffset, location) { + context.requestEmitHelper(paramHelper); + return ts.setTextRange(ts.createCall(ts.getHelperName("__param"), + /*typeArguments*/ undefined, [ + ts.createLiteral(parameterOffset), + expression + ]), location); + } + var paramHelper = { + name: "typescript:param", + scoped: false, + priority: 4, + text: "\n var __param = (this && this.__param) || function (paramIndex, decorator) {\n return function (target, key) { decorator(target, key, paramIndex); }\n };" + }; +})(ts || (ts = {})); +/*@internal*/ +var ts; +(function (ts) { + var ES2017SubstitutionFlags; + (function (ES2017SubstitutionFlags) { + /** Enables substitutions for async methods with `super` calls. */ + ES2017SubstitutionFlags[ES2017SubstitutionFlags["AsyncMethodsWithSuper"] = 1] = "AsyncMethodsWithSuper"; + })(ES2017SubstitutionFlags || (ES2017SubstitutionFlags = {})); + function transformES2017(context) { + var resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; + var resolver = context.getEmitResolver(); + var compilerOptions = context.getCompilerOptions(); + var languageVersion = ts.getEmitScriptTarget(compilerOptions); + /** + * Keeps track of whether expression substitution has been enabled for specific edge cases. + * They are persisted between each SourceFile transformation and should not be reset. + */ + var enabledSubstitutions; + /** + * This keeps track of containers where `super` is valid, for use with + * just-in-time substitution for `super` expressions inside of async methods. + */ + var enclosingSuperContainerFlags = 0; + var enclosingFunctionParameterNames; + /** + * Keeps track of property names accessed on super (`super.x`) within async functions. + */ + var capturedSuperProperties; + /** Whether the async function contains an element access on super (`super[x]`). */ + var hasSuperElementAccess; + /** A set of node IDs for generated super accessors (variable statements). */ + var substitutedSuperAccessors = []; + // Save the previous transformation hooks. + var previousOnEmitNode = context.onEmitNode; + var previousOnSubstituteNode = context.onSubstituteNode; + // Set new transformation hooks. + context.onEmitNode = onEmitNode; + context.onSubstituteNode = onSubstituteNode; + return ts.chainBundle(transformSourceFile); + function transformSourceFile(node) { + if (node.isDeclarationFile) { + return node; + } + var visited = ts.visitEachChild(node, visitor, context); + ts.addEmitHelpers(visited, context.readEmitHelpers()); + return visited; + } + function visitor(node) { + if ((node.transformFlags & 16 /* ContainsES2017 */) === 0) { + return node; + } + switch (node.kind) { + case 121 /* AsyncKeyword */: + // ES2017 async modifier should be elided for targets < ES2017 + return undefined; + case 201 /* AwaitExpression */: + return visitAwaitExpression(node); + case 156 /* MethodDeclaration */: + return visitMethodDeclaration(node); + case 239 /* FunctionDeclaration */: + return visitFunctionDeclaration(node); + case 196 /* FunctionExpression */: + return visitFunctionExpression(node); + case 197 /* ArrowFunction */: + return visitArrowFunction(node); + case 189 /* PropertyAccessExpression */: + if (capturedSuperProperties && ts.isPropertyAccessExpression(node) && node.expression.kind === 98 /* SuperKeyword */) { + capturedSuperProperties.set(node.name.escapedText, true); + } + return ts.visitEachChild(node, visitor, context); + case 190 /* ElementAccessExpression */: + if (capturedSuperProperties && node.expression.kind === 98 /* SuperKeyword */) { + hasSuperElementAccess = true; + } + return ts.visitEachChild(node, visitor, context); + default: + return ts.visitEachChild(node, visitor, context); + } + } + function asyncBodyVisitor(node) { + if (ts.isNodeWithPossibleHoistedDeclaration(node)) { + switch (node.kind) { + case 219 /* VariableStatement */: + return visitVariableStatementInAsyncBody(node); + case 225 /* ForStatement */: + return visitForStatementInAsyncBody(node); + case 226 /* ForInStatement */: + return visitForInStatementInAsyncBody(node); + case 227 /* ForOfStatement */: + return visitForOfStatementInAsyncBody(node); + case 274 /* CatchClause */: + return visitCatchClauseInAsyncBody(node); + case 218 /* Block */: + case 232 /* SwitchStatement */: + case 246 /* CaseBlock */: + case 271 /* CaseClause */: + case 272 /* DefaultClause */: + case 235 /* TryStatement */: + case 223 /* DoStatement */: + case 224 /* WhileStatement */: + case 222 /* IfStatement */: + case 231 /* WithStatement */: + case 233 /* LabeledStatement */: + return ts.visitEachChild(node, asyncBodyVisitor, context); + default: + return ts.Debug.assertNever(node, "Unhandled node."); + } + } + return visitor(node); + } + function visitCatchClauseInAsyncBody(node) { + var catchClauseNames = ts.createUnderscoreEscapedMap(); + recordDeclarationName(node.variableDeclaration, catchClauseNames); // TODO: GH#18217 + // names declared in a catch variable are block scoped + var catchClauseUnshadowedNames; + catchClauseNames.forEach(function (_, escapedName) { + if (enclosingFunctionParameterNames.has(escapedName)) { + if (!catchClauseUnshadowedNames) { + catchClauseUnshadowedNames = ts.cloneMap(enclosingFunctionParameterNames); + } + catchClauseUnshadowedNames.delete(escapedName); + } + }); + if (catchClauseUnshadowedNames) { + var savedEnclosingFunctionParameterNames = enclosingFunctionParameterNames; + enclosingFunctionParameterNames = catchClauseUnshadowedNames; + var result = ts.visitEachChild(node, asyncBodyVisitor, context); + enclosingFunctionParameterNames = savedEnclosingFunctionParameterNames; + return result; + } + else { + return ts.visitEachChild(node, asyncBodyVisitor, context); + } + } + function visitVariableStatementInAsyncBody(node) { + if (isVariableDeclarationListWithCollidingName(node.declarationList)) { + var expression = visitVariableDeclarationListWithCollidingNames(node.declarationList, /*hasReceiver*/ false); + return expression ? ts.createExpressionStatement(expression) : undefined; + } + return ts.visitEachChild(node, visitor, context); + } + function visitForInStatementInAsyncBody(node) { + return ts.updateForIn(node, isVariableDeclarationListWithCollidingName(node.initializer) + ? visitVariableDeclarationListWithCollidingNames(node.initializer, /*hasReceiver*/ true) + : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitNode(node.statement, asyncBodyVisitor, ts.isStatement, ts.liftToBlock)); + } + function visitForOfStatementInAsyncBody(node) { + return ts.updateForOf(node, ts.visitNode(node.awaitModifier, visitor, ts.isToken), isVariableDeclarationListWithCollidingName(node.initializer) + ? visitVariableDeclarationListWithCollidingNames(node.initializer, /*hasReceiver*/ true) + : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitNode(node.statement, asyncBodyVisitor, ts.isStatement, ts.liftToBlock)); + } + function visitForStatementInAsyncBody(node) { + var initializer = node.initializer; // TODO: GH#18217 + return ts.updateFor(node, isVariableDeclarationListWithCollidingName(initializer) + ? visitVariableDeclarationListWithCollidingNames(initializer, /*hasReceiver*/ false) + : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.condition, visitor, ts.isExpression), ts.visitNode(node.incrementor, visitor, ts.isExpression), ts.visitNode(node.statement, asyncBodyVisitor, ts.isStatement, ts.liftToBlock)); + } + /** + * Visits an AwaitExpression node. + * + * This function will be called any time a ES2017 await expression is encountered. + * + * @param node The node to visit. + */ + function visitAwaitExpression(node) { + return ts.setOriginalNode(ts.setTextRange(ts.createYield( + /*asteriskToken*/ undefined, ts.visitNode(node.expression, visitor, ts.isExpression)), node), node); + } + /** + * Visits a MethodDeclaration node. + * + * This function will be called when one of the following conditions are met: + * - The node is marked as async + * + * @param node The node to visit. + */ + function visitMethodDeclaration(node) { + return ts.updateMethod(node, + /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, node.name, + /*questionToken*/ undefined, + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, ts.getFunctionFlags(node) & 2 /* Async */ + ? transformAsyncFunctionBody(node) + : ts.visitFunctionBody(node.body, visitor, context)); + } + /** + * Visits a FunctionDeclaration node. + * + * This function will be called when one of the following conditions are met: + * - The node is marked async + * + * @param node The node to visit. + */ + function visitFunctionDeclaration(node) { + return ts.updateFunctionDeclaration(node, + /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, node.name, + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, ts.getFunctionFlags(node) & 2 /* Async */ + ? transformAsyncFunctionBody(node) + : ts.visitFunctionBody(node.body, visitor, context)); + } + /** + * Visits a FunctionExpression node. + * + * This function will be called when one of the following conditions are met: + * - The node is marked async + * + * @param node The node to visit. + */ + function visitFunctionExpression(node) { + return ts.updateFunctionExpression(node, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, node.name, + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, ts.getFunctionFlags(node) & 2 /* Async */ + ? transformAsyncFunctionBody(node) + : ts.visitFunctionBody(node.body, visitor, context)); + } + /** + * Visits an ArrowFunction. + * + * This function will be called when one of the following conditions are met: + * - The node is marked async + * + * @param node The node to visit. + */ + function visitArrowFunction(node) { + return ts.updateArrowFunction(node, ts.visitNodes(node.modifiers, visitor, ts.isModifier), + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, node.equalsGreaterThanToken, ts.getFunctionFlags(node) & 2 /* Async */ + ? transformAsyncFunctionBody(node) + : ts.visitFunctionBody(node.body, visitor, context)); + } + function recordDeclarationName(_a, names) { + var name = _a.name; + if (ts.isIdentifier(name)) { + names.set(name.escapedText, true); + } + else { + for (var _i = 0, _b = name.elements; _i < _b.length; _i++) { + var element = _b[_i]; + if (!ts.isOmittedExpression(element)) { + recordDeclarationName(element, names); + } + } + } + } + function isVariableDeclarationListWithCollidingName(node) { + return !!node + && ts.isVariableDeclarationList(node) + && !(node.flags & 3 /* BlockScoped */) + && node.declarations.some(collidesWithParameterName); + } + function visitVariableDeclarationListWithCollidingNames(node, hasReceiver) { + hoistVariableDeclarationList(node); + var variables = ts.getInitializedVariables(node); + if (variables.length === 0) { + if (hasReceiver) { + return ts.visitNode(ts.convertToAssignmentElementTarget(node.declarations[0].name), visitor, ts.isExpression); + } + return undefined; + } + return ts.inlineExpressions(ts.map(variables, transformInitializedVariable)); + } + function hoistVariableDeclarationList(node) { + ts.forEach(node.declarations, hoistVariable); + } + function hoistVariable(_a) { + var name = _a.name; + if (ts.isIdentifier(name)) { + hoistVariableDeclaration(name); + } + else { + for (var _i = 0, _b = name.elements; _i < _b.length; _i++) { + var element = _b[_i]; + if (!ts.isOmittedExpression(element)) { + hoistVariable(element); + } + } + } + } + function transformInitializedVariable(node) { + var converted = ts.setSourceMapRange(ts.createAssignment(ts.convertToAssignmentElementTarget(node.name), node.initializer), node); + return ts.visitNode(converted, visitor, ts.isExpression); + } + function collidesWithParameterName(_a) { + var name = _a.name; + if (ts.isIdentifier(name)) { + return enclosingFunctionParameterNames.has(name.escapedText); + } + else { + for (var _i = 0, _b = name.elements; _i < _b.length; _i++) { + var element = _b[_i]; + if (!ts.isOmittedExpression(element) && collidesWithParameterName(element)) { + return true; + } + } + } + return false; + } + function transformAsyncFunctionBody(node) { + resumeLexicalEnvironment(); + var original = ts.getOriginalNode(node, ts.isFunctionLike); + var nodeType = original.type; + var promiseConstructor = languageVersion < 2 /* ES2015 */ ? getPromiseConstructor(nodeType) : undefined; + var isArrowFunction = node.kind === 197 /* ArrowFunction */; + var hasLexicalArguments = (resolver.getNodeCheckFlags(node) & 8192 /* CaptureArguments */) !== 0; + // An async function is emit as an outer function that calls an inner + // generator function. To preserve lexical bindings, we pass the current + // `this` and `arguments` objects to `__awaiter`. The generator function + // passed to `__awaiter` is executed inside of the callback to the + // promise constructor. + var savedEnclosingFunctionParameterNames = enclosingFunctionParameterNames; + enclosingFunctionParameterNames = ts.createUnderscoreEscapedMap(); + for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { + var parameter = _a[_i]; + recordDeclarationName(parameter, enclosingFunctionParameterNames); + } + var savedCapturedSuperProperties = capturedSuperProperties; + var savedHasSuperElementAccess = hasSuperElementAccess; + capturedSuperProperties = ts.createUnderscoreEscapedMap(); + hasSuperElementAccess = false; + var result; + if (!isArrowFunction) { + var statements = []; + var statementOffset = ts.addPrologue(statements, node.body.statements, /*ensureUseStrict*/ false, visitor); + statements.push(ts.createReturn(createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, transformAsyncFunctionBodyWorker(node.body, statementOffset)))); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + // Minor optimization, emit `_super` helper to capture `super` access in an arrow. + // This step isn't needed if we eventually transform this to ES5. + var emitSuperHelpers = languageVersion >= 2 /* ES2015 */ && resolver.getNodeCheckFlags(node) & (4096 /* AsyncMethodWithSuperBinding */ | 2048 /* AsyncMethodWithSuper */); + if (emitSuperHelpers) { + enableSubstitutionForAsyncMethodsWithSuper(); + var variableStatement = createSuperAccessVariableStatement(resolver, node, capturedSuperProperties); + substitutedSuperAccessors[ts.getNodeId(variableStatement)] = true; + ts.addStatementsAfterPrologue(statements, [variableStatement]); + } + var block = ts.createBlock(statements, /*multiLine*/ true); + ts.setTextRange(block, node.body); + if (emitSuperHelpers && hasSuperElementAccess) { + // Emit helpers for super element access expressions (`super[x]`). + if (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) { + ts.addEmitHelper(block, ts.advancedAsyncSuperHelper); + } + else if (resolver.getNodeCheckFlags(node) & 2048 /* AsyncMethodWithSuper */) { + ts.addEmitHelper(block, ts.asyncSuperHelper); + } + } + result = block; + } + else { + var expression = createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, transformAsyncFunctionBodyWorker(node.body)); + var declarations = endLexicalEnvironment(); + if (ts.some(declarations)) { + var block = ts.convertToFunctionBody(expression); + result = ts.updateBlock(block, ts.setTextRange(ts.createNodeArray(ts.concatenate(declarations, block.statements)), block.statements)); + } + else { + result = expression; + } + } + enclosingFunctionParameterNames = savedEnclosingFunctionParameterNames; + capturedSuperProperties = savedCapturedSuperProperties; + hasSuperElementAccess = savedHasSuperElementAccess; + return result; + } + function transformAsyncFunctionBodyWorker(body, start) { + if (ts.isBlock(body)) { + return ts.updateBlock(body, ts.visitNodes(body.statements, asyncBodyVisitor, ts.isStatement, start)); + } + else { + return ts.convertToFunctionBody(ts.visitNode(body, asyncBodyVisitor, ts.isConciseBody)); + } + } + function getPromiseConstructor(type) { + var typeName = type && ts.getEntityNameFromTypeNode(type); + if (typeName && ts.isEntityName(typeName)) { + var serializationKind = resolver.getTypeReferenceSerializationKind(typeName); + if (serializationKind === ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue + || serializationKind === ts.TypeReferenceSerializationKind.Unknown) { + return typeName; + } + } + return undefined; + } + function enableSubstitutionForAsyncMethodsWithSuper() { + if ((enabledSubstitutions & 1 /* AsyncMethodsWithSuper */) === 0) { + enabledSubstitutions |= 1 /* AsyncMethodsWithSuper */; + // We need to enable substitutions for call, property access, and element access + // if we need to rewrite super calls. + context.enableSubstitution(191 /* CallExpression */); + context.enableSubstitution(189 /* PropertyAccessExpression */); + context.enableSubstitution(190 /* ElementAccessExpression */); + // We need to be notified when entering and exiting declarations that bind super. + context.enableEmitNotification(240 /* ClassDeclaration */); + context.enableEmitNotification(156 /* MethodDeclaration */); + context.enableEmitNotification(158 /* GetAccessor */); + context.enableEmitNotification(159 /* SetAccessor */); + context.enableEmitNotification(157 /* Constructor */); + // We need to be notified when entering the generated accessor arrow functions. + context.enableEmitNotification(219 /* VariableStatement */); + } + } + /** + * Hook for node emit. + * + * @param hint A hint as to the intended usage of the node. + * @param node The node to emit. + * @param emit A callback used to emit the node in the printer. + */ + function onEmitNode(hint, node, emitCallback) { + // If we need to support substitutions for `super` in an async method, + // we should track it here. + if (enabledSubstitutions & 1 /* AsyncMethodsWithSuper */ && isSuperContainer(node)) { + var superContainerFlags = resolver.getNodeCheckFlags(node) & (2048 /* AsyncMethodWithSuper */ | 4096 /* AsyncMethodWithSuperBinding */); + if (superContainerFlags !== enclosingSuperContainerFlags) { + var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags; + enclosingSuperContainerFlags = superContainerFlags; + previousOnEmitNode(hint, node, emitCallback); + enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags; + return; + } + } + // Disable substitution in the generated super accessor itself. + else if (enabledSubstitutions && substitutedSuperAccessors[ts.getNodeId(node)]) { + var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags; + enclosingSuperContainerFlags = 0; + previousOnEmitNode(hint, node, emitCallback); + enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags; + return; + } + previousOnEmitNode(hint, node, emitCallback); + } + /** + * Hooks node substitutions. + * + * @param hint A hint as to the intended usage of the node. + * @param node The node to substitute. + */ + function onSubstituteNode(hint, node) { + node = previousOnSubstituteNode(hint, node); + if (hint === 1 /* Expression */ && enclosingSuperContainerFlags) { + return substituteExpression(node); + } + return node; + } + function substituteExpression(node) { + switch (node.kind) { + case 189 /* PropertyAccessExpression */: + return substitutePropertyAccessExpression(node); + case 190 /* ElementAccessExpression */: + return substituteElementAccessExpression(node); + case 191 /* CallExpression */: + return substituteCallExpression(node); + } + return node; + } + function substitutePropertyAccessExpression(node) { + if (node.expression.kind === 98 /* SuperKeyword */) { + return ts.setTextRange(ts.createPropertyAccess(ts.createFileLevelUniqueName("_super"), node.name), node); + } + return node; + } + function substituteElementAccessExpression(node) { + if (node.expression.kind === 98 /* SuperKeyword */) { + return createSuperElementAccessInAsyncMethod(node.argumentExpression, node); + } + return node; + } + function substituteCallExpression(node) { + var expression = node.expression; + if (ts.isSuperProperty(expression)) { + var argumentExpression = ts.isPropertyAccessExpression(expression) + ? substitutePropertyAccessExpression(expression) + : substituteElementAccessExpression(expression); + return ts.createCall(ts.createPropertyAccess(argumentExpression, "call"), + /*typeArguments*/ undefined, [ + ts.createThis() + ].concat(node.arguments)); + } + return node; + } + function isSuperContainer(node) { + var kind = node.kind; + return kind === 240 /* ClassDeclaration */ + || kind === 157 /* Constructor */ + || kind === 156 /* MethodDeclaration */ + || kind === 158 /* GetAccessor */ + || kind === 159 /* SetAccessor */; + } + function createSuperElementAccessInAsyncMethod(argumentExpression, location) { + if (enclosingSuperContainerFlags & 4096 /* AsyncMethodWithSuperBinding */) { + return ts.setTextRange(ts.createPropertyAccess(ts.createCall(ts.createFileLevelUniqueName("_superIndex"), + /*typeArguments*/ undefined, [argumentExpression]), "value"), location); + } + else { + return ts.setTextRange(ts.createCall(ts.createFileLevelUniqueName("_superIndex"), + /*typeArguments*/ undefined, [argumentExpression]), location); + } + } + } + ts.transformES2017 = transformES2017; + /** Creates a variable named `_super` with accessor properties for the given property names. */ + function createSuperAccessVariableStatement(resolver, node, names) { + // Create a variable declaration with a getter/setter (if binding) definition for each name: + // const _super = Object.create(null, { x: { get: () => super.x, set: (v) => super.x = v }, ... }); + var hasBinding = (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) !== 0; + var accessors = []; + names.forEach(function (_, key) { + var name = ts.unescapeLeadingUnderscores(key); + var getterAndSetter = []; + getterAndSetter.push(ts.createPropertyAssignment("get", ts.createArrowFunction( + /* modifiers */ undefined, + /* typeParameters */ undefined, + /* parameters */ [], + /* type */ undefined, + /* equalsGreaterThanToken */ undefined, ts.createPropertyAccess(ts.createSuper(), name)))); + if (hasBinding) { + getterAndSetter.push(ts.createPropertyAssignment("set", ts.createArrowFunction( + /* modifiers */ undefined, + /* typeParameters */ undefined, + /* parameters */ [ + ts.createParameter( + /* decorators */ undefined, + /* modifiers */ undefined, + /* dotDotDotToken */ undefined, "v", + /* questionToken */ undefined, + /* type */ undefined, + /* initializer */ undefined) + ], + /* type */ undefined, + /* equalsGreaterThanToken */ undefined, ts.createAssignment(ts.createPropertyAccess(ts.createSuper(), name), ts.createIdentifier("v"))))); + } + accessors.push(ts.createPropertyAssignment(name, ts.createObjectLiteral(getterAndSetter))); + }); + return ts.createVariableStatement( + /* modifiers */ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(ts.createFileLevelUniqueName("_super"), + /* type */ undefined, ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "create"), + /* typeArguments */ undefined, [ + ts.createNull(), + ts.createObjectLiteral(accessors, /* multiline */ true) + ])) + ], 2 /* Const */)); + } + ts.createSuperAccessVariableStatement = createSuperAccessVariableStatement; + var awaiterHelper = { + name: "typescript:awaiter", + scoped: false, + priority: 5, + text: "\n var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n };" + }; + function createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, body) { + context.requestEmitHelper(awaiterHelper); + var generatorFunc = ts.createFunctionExpression( + /*modifiers*/ undefined, ts.createToken(40 /* AsteriskToken */), + /*name*/ undefined, + /*typeParameters*/ undefined, + /*parameters*/ [], + /*type*/ undefined, body); + // Mark this node as originally an async function + (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 262144 /* AsyncFunctionBody */ | 524288 /* ReuseTempVariableScope */; + return ts.createCall(ts.getHelperName("__awaiter"), + /*typeArguments*/ undefined, [ + ts.createThis(), + hasLexicalArguments ? ts.createIdentifier("arguments") : ts.createVoidZero(), + promiseConstructor ? ts.createExpressionFromEntityName(promiseConstructor) : ts.createVoidZero(), + generatorFunc + ]); + } + ts.asyncSuperHelper = { + name: "typescript:async-super", + scoped: true, + text: ts.helperString(__makeTemplateObject(["\n const ", " = name => super[name];"], ["\n const ", " = name => super[name];"]), "_superIndex") + }; + ts.advancedAsyncSuperHelper = { + name: "typescript:advanced-async-super", + scoped: true, + text: ts.helperString(__makeTemplateObject(["\n const ", " = (function (geti, seti) {\n const cache = Object.create(null);\n return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } });\n })(name => super[name], (name, value) => super[name] = value);"], ["\n const ", " = (function (geti, seti) {\n const cache = Object.create(null);\n return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } });\n })(name => super[name], (name, value) => super[name] = value);"]), "_superIndex") + }; +})(ts || (ts = {})); +/*@internal*/ +var ts; +(function (ts) { + var ESNextSubstitutionFlags; + (function (ESNextSubstitutionFlags) { + /** Enables substitutions for async methods with `super` calls. */ + ESNextSubstitutionFlags[ESNextSubstitutionFlags["AsyncMethodsWithSuper"] = 1] = "AsyncMethodsWithSuper"; + })(ESNextSubstitutionFlags || (ESNextSubstitutionFlags = {})); + function transformESNext(context) { + var resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; + var resolver = context.getEmitResolver(); + var compilerOptions = context.getCompilerOptions(); + var languageVersion = ts.getEmitScriptTarget(compilerOptions); + var previousOnEmitNode = context.onEmitNode; + context.onEmitNode = onEmitNode; + var previousOnSubstituteNode = context.onSubstituteNode; + context.onSubstituteNode = onSubstituteNode; + var enabledSubstitutions; + var enclosingFunctionFlags; + var enclosingSuperContainerFlags = 0; + /** Keeps track of property names accessed on super (`super.x`) within async functions. */ + var capturedSuperProperties; + /** Whether the async function contains an element access on super (`super[x]`). */ + var hasSuperElementAccess; + /** A set of node IDs for generated super accessors. */ + var substitutedSuperAccessors = []; + return ts.chainBundle(transformSourceFile); + function transformSourceFile(node) { + if (node.isDeclarationFile) { + return node; + } + var visited = ts.visitEachChild(node, visitor, context); + ts.addEmitHelpers(visited, context.readEmitHelpers()); + return visited; + } + function visitor(node) { + return visitorWorker(node, /*noDestructuringValue*/ false); + } + function visitorNoDestructuringValue(node) { + return visitorWorker(node, /*noDestructuringValue*/ true); + } + function visitorNoAsyncModifier(node) { + if (node.kind === 121 /* AsyncKeyword */) { + return undefined; + } + return node; + } + function visitorWorker(node, noDestructuringValue) { + if ((node.transformFlags & 8 /* ContainsESNext */) === 0) { + return node; + } + switch (node.kind) { + case 201 /* AwaitExpression */: + return visitAwaitExpression(node); + case 207 /* YieldExpression */: + return visitYieldExpression(node); + case 230 /* ReturnStatement */: + return visitReturnStatement(node); + case 233 /* LabeledStatement */: + return visitLabeledStatement(node); + case 188 /* ObjectLiteralExpression */: + return visitObjectLiteralExpression(node); + case 204 /* BinaryExpression */: + return visitBinaryExpression(node, noDestructuringValue); + case 237 /* VariableDeclaration */: + return visitVariableDeclaration(node); + case 227 /* ForOfStatement */: + return visitForOfStatement(node, /*outermostLabeledStatement*/ undefined); + case 225 /* ForStatement */: + return visitForStatement(node); + case 200 /* VoidExpression */: + return visitVoidExpression(node); + case 157 /* Constructor */: + return visitConstructorDeclaration(node); + case 156 /* MethodDeclaration */: + return visitMethodDeclaration(node); + case 158 /* GetAccessor */: + return visitGetAccessorDeclaration(node); + case 159 /* SetAccessor */: + return visitSetAccessorDeclaration(node); + case 239 /* FunctionDeclaration */: + return visitFunctionDeclaration(node); + case 196 /* FunctionExpression */: + return visitFunctionExpression(node); + case 197 /* ArrowFunction */: + return visitArrowFunction(node); + case 151 /* Parameter */: + return visitParameter(node); + case 221 /* ExpressionStatement */: + return visitExpressionStatement(node); + case 195 /* ParenthesizedExpression */: + return visitParenthesizedExpression(node, noDestructuringValue); + case 274 /* CatchClause */: + return visitCatchClause(node); + case 189 /* PropertyAccessExpression */: + if (capturedSuperProperties && ts.isPropertyAccessExpression(node) && node.expression.kind === 98 /* SuperKeyword */) { + capturedSuperProperties.set(node.name.escapedText, true); + } + return ts.visitEachChild(node, visitor, context); + case 190 /* ElementAccessExpression */: + if (capturedSuperProperties && node.expression.kind === 98 /* SuperKeyword */) { + hasSuperElementAccess = true; + } + return ts.visitEachChild(node, visitor, context); + default: + return ts.visitEachChild(node, visitor, context); + } + } + function visitAwaitExpression(node) { + if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */) { + return ts.setOriginalNode(ts.setTextRange(ts.createYield(createAwaitHelper(context, ts.visitNode(node.expression, visitor, ts.isExpression))), + /*location*/ node), node); + } + return ts.visitEachChild(node, visitor, context); + } + function visitYieldExpression(node) { + if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */) { + if (node.asteriskToken) { + var expression = ts.visitNode(node.expression, visitor, ts.isExpression); + return ts.setOriginalNode(ts.setTextRange(ts.createYield(createAwaitHelper(context, ts.updateYield(node, node.asteriskToken, createAsyncDelegatorHelper(context, createAsyncValuesHelper(context, expression, expression), expression)))), node), node); + } + return ts.setOriginalNode(ts.setTextRange(ts.createYield(createDownlevelAwait(node.expression + ? ts.visitNode(node.expression, visitor, ts.isExpression) + : ts.createVoidZero())), node), node); + } + return ts.visitEachChild(node, visitor, context); + } + function visitReturnStatement(node) { + if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */) { + return ts.updateReturn(node, createDownlevelAwait(node.expression ? ts.visitNode(node.expression, visitor, ts.isExpression) : ts.createVoidZero())); + } + return ts.visitEachChild(node, visitor, context); + } + function visitLabeledStatement(node) { + if (enclosingFunctionFlags & 2 /* Async */) { + var statement = ts.unwrapInnermostStatementOfLabel(node); + if (statement.kind === 227 /* ForOfStatement */ && statement.awaitModifier) { + return visitForOfStatement(statement, node); + } + return ts.restoreEnclosingLabel(ts.visitEachChild(statement, visitor, context), node); + } + return ts.visitEachChild(node, visitor, context); + } + function chunkObjectLiteralElements(elements) { + var chunkObject; + var objects = []; + for (var _i = 0, elements_4 = elements; _i < elements_4.length; _i++) { + var e = elements_4[_i]; + if (e.kind === 277 /* SpreadAssignment */) { + if (chunkObject) { + objects.push(ts.createObjectLiteral(chunkObject)); + chunkObject = undefined; + } + var target = e.expression; + objects.push(ts.visitNode(target, visitor, ts.isExpression)); + } + else { + chunkObject = ts.append(chunkObject, e.kind === 275 /* PropertyAssignment */ + ? ts.createPropertyAssignment(e.name, ts.visitNode(e.initializer, visitor, ts.isExpression)) + : ts.visitNode(e, visitor, ts.isObjectLiteralElementLike)); + } + } + if (chunkObject) { + objects.push(ts.createObjectLiteral(chunkObject)); + } + return objects; + } + function visitObjectLiteralExpression(node) { + if (node.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { + // spread elements emit like so: + // non-spread elements are chunked together into object literals, and then all are passed to __assign: + // { a, ...o, b } => __assign({a}, o, {b}); + // If the first element is a spread element, then the first argument to __assign is {}: + // { ...o, a, b, ...o2 } => __assign({}, o, {a, b}, o2) + var objects = chunkObjectLiteralElements(node.properties); + if (objects.length && objects[0].kind !== 188 /* ObjectLiteralExpression */) { + objects.unshift(ts.createObjectLiteral()); + } + return createAssignHelper(context, objects); + } + return ts.visitEachChild(node, visitor, context); + } + function visitExpressionStatement(node) { + return ts.visitEachChild(node, visitorNoDestructuringValue, context); + } + function visitParenthesizedExpression(node, noDestructuringValue) { + return ts.visitEachChild(node, noDestructuringValue ? visitorNoDestructuringValue : visitor, context); + } + function visitCatchClause(node) { + if (!node.variableDeclaration) { + return ts.updateCatchClause(node, ts.createVariableDeclaration(ts.createTempVariable(/*recordTempVariable*/ undefined)), ts.visitNode(node.block, visitor, ts.isBlock)); + } + return ts.visitEachChild(node, visitor, context); + } + /** + * Visits a BinaryExpression that contains a destructuring assignment. + * + * @param node A BinaryExpression node. + */ + function visitBinaryExpression(node, noDestructuringValue) { + if (ts.isDestructuringAssignment(node) && node.left.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { + return ts.flattenDestructuringAssignment(node, visitor, context, 1 /* ObjectRest */, !noDestructuringValue); + } + else if (node.operatorToken.kind === 27 /* CommaToken */) { + return ts.updateBinary(node, ts.visitNode(node.left, visitorNoDestructuringValue, ts.isExpression), ts.visitNode(node.right, noDestructuringValue ? visitorNoDestructuringValue : visitor, ts.isExpression)); + } + return ts.visitEachChild(node, visitor, context); + } + /** + * Visits a VariableDeclaration node with a binding pattern. + * + * @param node A VariableDeclaration node. + */ + function visitVariableDeclaration(node) { + // If we are here it is because the name contains a binding pattern with a rest somewhere in it. + if (ts.isBindingPattern(node.name) && node.name.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { + return ts.flattenDestructuringBinding(node, visitor, context, 1 /* ObjectRest */); + } + return ts.visitEachChild(node, visitor, context); + } + function visitForStatement(node) { + return ts.updateFor(node, ts.visitNode(node.initializer, visitorNoDestructuringValue, ts.isForInitializer), ts.visitNode(node.condition, visitor, ts.isExpression), ts.visitNode(node.incrementor, visitor, ts.isExpression), ts.visitNode(node.statement, visitor, ts.isStatement)); + } + function visitVoidExpression(node) { + return ts.visitEachChild(node, visitorNoDestructuringValue, context); + } + /** + * Visits a ForOfStatement and converts it into a ES2015-compatible ForOfStatement. + * + * @param node A ForOfStatement. + */ + function visitForOfStatement(node, outermostLabeledStatement) { + if (node.initializer.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { + node = transformForOfStatementWithObjectRest(node); + } + if (node.awaitModifier) { + return transformForAwaitOfStatement(node, outermostLabeledStatement); + } + else { + return ts.restoreEnclosingLabel(ts.visitEachChild(node, visitor, context), outermostLabeledStatement); + } + } + function transformForOfStatementWithObjectRest(node) { + var initializerWithoutParens = ts.skipParentheses(node.initializer); + if (ts.isVariableDeclarationList(initializerWithoutParens) || ts.isAssignmentPattern(initializerWithoutParens)) { + var bodyLocation = void 0; + var statementsLocation = void 0; + var temp = ts.createTempVariable(/*recordTempVariable*/ undefined); + var statements = [ts.createForOfBindingStatement(initializerWithoutParens, temp)]; + if (ts.isBlock(node.statement)) { + ts.addRange(statements, node.statement.statements); + bodyLocation = node.statement; + statementsLocation = node.statement.statements; + } + else if (node.statement) { + ts.append(statements, node.statement); + bodyLocation = node.statement; + statementsLocation = node.statement; + } + return ts.updateForOf(node, node.awaitModifier, ts.setTextRange(ts.createVariableDeclarationList([ + ts.setTextRange(ts.createVariableDeclaration(temp), node.initializer) + ], 1 /* Let */), node.initializer), node.expression, ts.setTextRange(ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), statementsLocation), + /*multiLine*/ true), bodyLocation)); + } + return node; + } + function convertForOfStatementHead(node, boundValue) { + var binding = ts.createForOfBindingStatement(node.initializer, boundValue); + var bodyLocation; + var statementsLocation; + var statements = [ts.visitNode(binding, visitor, ts.isStatement)]; + var statement = ts.visitNode(node.statement, visitor, ts.isStatement); + if (ts.isBlock(statement)) { + ts.addRange(statements, statement.statements); + bodyLocation = statement; + statementsLocation = statement.statements; + } + else { + statements.push(statement); + } + return ts.setEmitFlags(ts.setTextRange(ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), statementsLocation), + /*multiLine*/ true), bodyLocation), 48 /* NoSourceMap */ | 384 /* NoTokenSourceMaps */); + } + function createDownlevelAwait(expression) { + return enclosingFunctionFlags & 1 /* Generator */ + ? ts.createYield(/*asteriskToken*/ undefined, createAwaitHelper(context, expression)) + : ts.createAwait(expression); + } + function transformForAwaitOfStatement(node, outermostLabeledStatement) { + var expression = ts.visitNode(node.expression, visitor, ts.isExpression); + var iterator = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(expression) : ts.createTempVariable(/*recordTempVariable*/ undefined); + var result = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(iterator) : ts.createTempVariable(/*recordTempVariable*/ undefined); + var errorRecord = ts.createUniqueName("e"); + var catchVariable = ts.getGeneratedNameForNode(errorRecord); + var returnMethod = ts.createTempVariable(/*recordTempVariable*/ undefined); + var callValues = createAsyncValuesHelper(context, expression, /*location*/ node.expression); + var callNext = ts.createCall(ts.createPropertyAccess(iterator, "next"), /*typeArguments*/ undefined, []); + var getDone = ts.createPropertyAccess(result, "done"); + var getValue = ts.createPropertyAccess(result, "value"); + var callReturn = ts.createFunctionCall(returnMethod, iterator, []); + hoistVariableDeclaration(errorRecord); + hoistVariableDeclaration(returnMethod); + var forStatement = ts.setEmitFlags(ts.setTextRange(ts.createFor( + /*initializer*/ ts.setEmitFlags(ts.setTextRange(ts.createVariableDeclarationList([ + ts.setTextRange(ts.createVariableDeclaration(iterator, /*type*/ undefined, callValues), node.expression), + ts.createVariableDeclaration(result) + ]), node.expression), 2097152 /* NoHoisting */), + /*condition*/ ts.createComma(ts.createAssignment(result, createDownlevelAwait(callNext)), ts.createLogicalNot(getDone)), + /*incrementor*/ undefined, + /*statement*/ convertForOfStatementHead(node, getValue)), + /*location*/ node), 256 /* NoTokenTrailingSourceMaps */); + return ts.createTry(ts.createBlock([ + ts.restoreEnclosingLabel(forStatement, outermostLabeledStatement) + ]), ts.createCatchClause(ts.createVariableDeclaration(catchVariable), ts.setEmitFlags(ts.createBlock([ + ts.createExpressionStatement(ts.createAssignment(errorRecord, ts.createObjectLiteral([ + ts.createPropertyAssignment("error", catchVariable) + ]))) + ]), 1 /* SingleLine */)), ts.createBlock([ + ts.createTry( + /*tryBlock*/ ts.createBlock([ + ts.setEmitFlags(ts.createIf(ts.createLogicalAnd(ts.createLogicalAnd(result, ts.createLogicalNot(getDone)), ts.createAssignment(returnMethod, ts.createPropertyAccess(iterator, "return"))), ts.createExpressionStatement(createDownlevelAwait(callReturn))), 1 /* SingleLine */) + ]), + /*catchClause*/ undefined, + /*finallyBlock*/ ts.setEmitFlags(ts.createBlock([ + ts.setEmitFlags(ts.createIf(errorRecord, ts.createThrow(ts.createPropertyAccess(errorRecord, "error"))), 1 /* SingleLine */) + ]), 1 /* SingleLine */)) + ])); + } + function visitParameter(node) { + if (node.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { + // Binding patterns are converted into a generated name and are + // evaluated inside the function body. + return ts.updateParameter(node, + /*decorators*/ undefined, + /*modifiers*/ undefined, node.dotDotDotToken, ts.getGeneratedNameForNode(node), + /*questionToken*/ undefined, + /*type*/ undefined, ts.visitNode(node.initializer, visitor, ts.isExpression)); + } + return ts.visitEachChild(node, visitor, context); + } + function visitConstructorDeclaration(node) { + var savedEnclosingFunctionFlags = enclosingFunctionFlags; + enclosingFunctionFlags = 0 /* Normal */; + var updated = ts.updateConstructor(node, + /*decorators*/ undefined, node.modifiers, ts.visitParameterList(node.parameters, visitor, context), transformFunctionBody(node)); + enclosingFunctionFlags = savedEnclosingFunctionFlags; + return updated; + } + function visitGetAccessorDeclaration(node) { + var savedEnclosingFunctionFlags = enclosingFunctionFlags; + enclosingFunctionFlags = 0 /* Normal */; + var updated = ts.updateGetAccessor(node, + /*decorators*/ undefined, node.modifiers, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, transformFunctionBody(node)); + enclosingFunctionFlags = savedEnclosingFunctionFlags; + return updated; + } + function visitSetAccessorDeclaration(node) { + var savedEnclosingFunctionFlags = enclosingFunctionFlags; + enclosingFunctionFlags = 0 /* Normal */; + var updated = ts.updateSetAccessor(node, + /*decorators*/ undefined, node.modifiers, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitParameterList(node.parameters, visitor, context), transformFunctionBody(node)); + enclosingFunctionFlags = savedEnclosingFunctionFlags; + return updated; + } + function visitMethodDeclaration(node) { + var savedEnclosingFunctionFlags = enclosingFunctionFlags; + enclosingFunctionFlags = ts.getFunctionFlags(node); + var updated = ts.updateMethod(node, + /*decorators*/ undefined, enclosingFunctionFlags & 1 /* Generator */ + ? ts.visitNodes(node.modifiers, visitorNoAsyncModifier, ts.isModifier) + : node.modifiers, enclosingFunctionFlags & 2 /* Async */ + ? undefined + : node.asteriskToken, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitNode(/*questionToken*/ undefined, visitor, ts.isToken), + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */ + ? transformAsyncGeneratorFunctionBody(node) + : transformFunctionBody(node)); + enclosingFunctionFlags = savedEnclosingFunctionFlags; + return updated; + } + function visitFunctionDeclaration(node) { + var savedEnclosingFunctionFlags = enclosingFunctionFlags; + enclosingFunctionFlags = ts.getFunctionFlags(node); + var updated = ts.updateFunctionDeclaration(node, + /*decorators*/ undefined, enclosingFunctionFlags & 1 /* Generator */ + ? ts.visitNodes(node.modifiers, visitorNoAsyncModifier, ts.isModifier) + : node.modifiers, enclosingFunctionFlags & 2 /* Async */ + ? undefined + : node.asteriskToken, node.name, + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */ + ? transformAsyncGeneratorFunctionBody(node) + : transformFunctionBody(node)); + enclosingFunctionFlags = savedEnclosingFunctionFlags; + return updated; + } + function visitArrowFunction(node) { + var savedEnclosingFunctionFlags = enclosingFunctionFlags; + enclosingFunctionFlags = ts.getFunctionFlags(node); + var updated = ts.updateArrowFunction(node, node.modifiers, + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, node.equalsGreaterThanToken, transformFunctionBody(node)); + enclosingFunctionFlags = savedEnclosingFunctionFlags; + return updated; + } + function visitFunctionExpression(node) { + var savedEnclosingFunctionFlags = enclosingFunctionFlags; + enclosingFunctionFlags = ts.getFunctionFlags(node); + var updated = ts.updateFunctionExpression(node, enclosingFunctionFlags & 1 /* Generator */ + ? ts.visitNodes(node.modifiers, visitorNoAsyncModifier, ts.isModifier) + : node.modifiers, enclosingFunctionFlags & 2 /* Async */ + ? undefined + : node.asteriskToken, node.name, + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */ + ? transformAsyncGeneratorFunctionBody(node) + : transformFunctionBody(node)); + enclosingFunctionFlags = savedEnclosingFunctionFlags; + return updated; + } + function transformAsyncGeneratorFunctionBody(node) { + resumeLexicalEnvironment(); + var statements = []; + var statementOffset = ts.addPrologue(statements, node.body.statements, /*ensureUseStrict*/ false, visitor); + appendObjectRestAssignmentsIfNeeded(statements, node); + var savedCapturedSuperProperties = capturedSuperProperties; + var savedHasSuperElementAccess = hasSuperElementAccess; + capturedSuperProperties = ts.createUnderscoreEscapedMap(); + hasSuperElementAccess = false; + var returnStatement = ts.createReturn(createAsyncGeneratorHelper(context, ts.createFunctionExpression( + /*modifiers*/ undefined, ts.createToken(40 /* AsteriskToken */), node.name && ts.getGeneratedNameForNode(node.name), + /*typeParameters*/ undefined, + /*parameters*/ [], + /*type*/ undefined, ts.updateBlock(node.body, ts.visitLexicalEnvironment(node.body.statements, visitor, context, statementOffset))))); + // Minor optimization, emit `_super` helper to capture `super` access in an arrow. + // This step isn't needed if we eventually transform this to ES5. + var emitSuperHelpers = languageVersion >= 2 /* ES2015 */ && resolver.getNodeCheckFlags(node) & (4096 /* AsyncMethodWithSuperBinding */ | 2048 /* AsyncMethodWithSuper */); + if (emitSuperHelpers) { + enableSubstitutionForAsyncMethodsWithSuper(); + var variableStatement = ts.createSuperAccessVariableStatement(resolver, node, capturedSuperProperties); + substitutedSuperAccessors[ts.getNodeId(variableStatement)] = true; + ts.addStatementsAfterPrologue(statements, [variableStatement]); + } + statements.push(returnStatement); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + var block = ts.updateBlock(node.body, statements); + if (emitSuperHelpers && hasSuperElementAccess) { + if (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) { + ts.addEmitHelper(block, ts.advancedAsyncSuperHelper); + } + else if (resolver.getNodeCheckFlags(node) & 2048 /* AsyncMethodWithSuper */) { + ts.addEmitHelper(block, ts.asyncSuperHelper); + } + } + capturedSuperProperties = savedCapturedSuperProperties; + hasSuperElementAccess = savedHasSuperElementAccess; + return block; + } + function transformFunctionBody(node) { + resumeLexicalEnvironment(); + var statementOffset = 0; + var statements = []; + var body = ts.visitNode(node.body, visitor, ts.isConciseBody); + if (ts.isBlock(body)) { + statementOffset = ts.addPrologue(statements, body.statements, /*ensureUseStrict*/ false, visitor); + } + ts.addRange(statements, appendObjectRestAssignmentsIfNeeded(/*statements*/ undefined, node)); + var leadingStatements = endLexicalEnvironment(); + if (statementOffset > 0 || ts.some(statements) || ts.some(leadingStatements)) { + var block = ts.convertToFunctionBody(body, /*multiLine*/ true); + ts.addStatementsAfterPrologue(statements, leadingStatements); + ts.addRange(statements, block.statements.slice(statementOffset)); + return ts.updateBlock(block, ts.setTextRange(ts.createNodeArray(statements), block.statements)); + } + return body; + } + function appendObjectRestAssignmentsIfNeeded(statements, node) { + for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { + var parameter = _a[_i]; + if (parameter.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { + var temp = ts.getGeneratedNameForNode(parameter); + var declarations = ts.flattenDestructuringBinding(parameter, visitor, context, 1 /* ObjectRest */, temp, + /*doNotRecordTempVariablesInLine*/ false, + /*skipInitializer*/ true); + if (ts.some(declarations)) { + var statement = ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList(declarations)); + ts.setEmitFlags(statement, 1048576 /* CustomPrologue */); + statements = ts.append(statements, statement); + } + } + } + return statements; + } + function enableSubstitutionForAsyncMethodsWithSuper() { + if ((enabledSubstitutions & 1 /* AsyncMethodsWithSuper */) === 0) { + enabledSubstitutions |= 1 /* AsyncMethodsWithSuper */; + // We need to enable substitutions for call, property access, and element access + // if we need to rewrite super calls. + context.enableSubstitution(191 /* CallExpression */); + context.enableSubstitution(189 /* PropertyAccessExpression */); + context.enableSubstitution(190 /* ElementAccessExpression */); + // We need to be notified when entering and exiting declarations that bind super. + context.enableEmitNotification(240 /* ClassDeclaration */); + context.enableEmitNotification(156 /* MethodDeclaration */); + context.enableEmitNotification(158 /* GetAccessor */); + context.enableEmitNotification(159 /* SetAccessor */); + context.enableEmitNotification(157 /* Constructor */); + // We need to be notified when entering the generated accessor arrow functions. + context.enableEmitNotification(219 /* VariableStatement */); + } + } + /** + * Called by the printer just before a node is printed. + * + * @param hint A hint as to the intended usage of the node. + * @param node The node to be printed. + * @param emitCallback The callback used to emit the node. + */ + function onEmitNode(hint, node, emitCallback) { + // If we need to support substitutions for `super` in an async method, + // we should track it here. + if (enabledSubstitutions & 1 /* AsyncMethodsWithSuper */ && isSuperContainer(node)) { + var superContainerFlags = resolver.getNodeCheckFlags(node) & (2048 /* AsyncMethodWithSuper */ | 4096 /* AsyncMethodWithSuperBinding */); + if (superContainerFlags !== enclosingSuperContainerFlags) { + var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags; + enclosingSuperContainerFlags = superContainerFlags; + previousOnEmitNode(hint, node, emitCallback); + enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags; + return; + } + } + // Disable substitution in the generated super accessor itself. + else if (enabledSubstitutions && substitutedSuperAccessors[ts.getNodeId(node)]) { + var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags; + enclosingSuperContainerFlags = 0; + previousOnEmitNode(hint, node, emitCallback); + enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags; + return; + } + previousOnEmitNode(hint, node, emitCallback); + } + /** + * Hooks node substitutions. + * + * @param hint The context for the emitter. + * @param node The node to substitute. + */ + function onSubstituteNode(hint, node) { + node = previousOnSubstituteNode(hint, node); + if (hint === 1 /* Expression */ && enclosingSuperContainerFlags) { + return substituteExpression(node); + } + return node; + } + function substituteExpression(node) { + switch (node.kind) { + case 189 /* PropertyAccessExpression */: + return substitutePropertyAccessExpression(node); + case 190 /* ElementAccessExpression */: + return substituteElementAccessExpression(node); + case 191 /* CallExpression */: + return substituteCallExpression(node); + } + return node; + } + function substitutePropertyAccessExpression(node) { + if (node.expression.kind === 98 /* SuperKeyword */) { + return ts.setTextRange(ts.createPropertyAccess(ts.createFileLevelUniqueName("_super"), node.name), node); + } + return node; + } + function substituteElementAccessExpression(node) { + if (node.expression.kind === 98 /* SuperKeyword */) { + return createSuperElementAccessInAsyncMethod(node.argumentExpression, node); + } + return node; + } + function substituteCallExpression(node) { + var expression = node.expression; + if (ts.isSuperProperty(expression)) { + var argumentExpression = ts.isPropertyAccessExpression(expression) + ? substitutePropertyAccessExpression(expression) + : substituteElementAccessExpression(expression); + return ts.createCall(ts.createPropertyAccess(argumentExpression, "call"), + /*typeArguments*/ undefined, [ + ts.createThis() + ].concat(node.arguments)); + } + return node; + } + function isSuperContainer(node) { + var kind = node.kind; + return kind === 240 /* ClassDeclaration */ + || kind === 157 /* Constructor */ + || kind === 156 /* MethodDeclaration */ + || kind === 158 /* GetAccessor */ + || kind === 159 /* SetAccessor */; + } + function createSuperElementAccessInAsyncMethod(argumentExpression, location) { + if (enclosingSuperContainerFlags & 4096 /* AsyncMethodWithSuperBinding */) { + return ts.setTextRange(ts.createPropertyAccess(ts.createCall(ts.createIdentifier("_superIndex"), + /*typeArguments*/ undefined, [argumentExpression]), "value"), location); + } + else { + return ts.setTextRange(ts.createCall(ts.createIdentifier("_superIndex"), + /*typeArguments*/ undefined, [argumentExpression]), location); + } + } + } + ts.transformESNext = transformESNext; + var assignHelper = { + name: "typescript:assign", + scoped: false, + priority: 1, + text: "\n var __assign = (this && this.__assign) || function () {\n __assign = Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n };\n return __assign.apply(this, arguments);\n };" + }; + function createAssignHelper(context, attributesSegments) { + if (context.getCompilerOptions().target >= 2 /* ES2015 */) { + return ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "assign"), + /*typeArguments*/ undefined, attributesSegments); + } + context.requestEmitHelper(assignHelper); + return ts.createCall(ts.getHelperName("__assign"), + /*typeArguments*/ undefined, attributesSegments); + } + ts.createAssignHelper = createAssignHelper; + var awaitHelper = { + name: "typescript:await", + scoped: false, + text: "\n var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }" + }; + function createAwaitHelper(context, expression) { + context.requestEmitHelper(awaitHelper); + return ts.createCall(ts.getHelperName("__await"), /*typeArguments*/ undefined, [expression]); + } + var asyncGeneratorHelper = { + name: "typescript:asyncGenerator", + scoped: false, + text: "\n var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\n function fulfill(value) { resume(\"next\", value); }\n function reject(value) { resume(\"throw\", value); }\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\n };" + }; + function createAsyncGeneratorHelper(context, generatorFunc) { + context.requestEmitHelper(awaitHelper); + context.requestEmitHelper(asyncGeneratorHelper); + // Mark this node as originally an async function + (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 262144 /* AsyncFunctionBody */; + return ts.createCall(ts.getHelperName("__asyncGenerator"), + /*typeArguments*/ undefined, [ + ts.createThis(), + ts.createIdentifier("arguments"), + generatorFunc + ]); + } + var asyncDelegator = { + name: "typescript:asyncDelegator", + scoped: false, + text: "\n var __asyncDelegator = (this && this.__asyncDelegator) || function (o) {\n var i, p;\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; } : f; }\n };" + }; + function createAsyncDelegatorHelper(context, expression, location) { + context.requestEmitHelper(awaitHelper); + context.requestEmitHelper(asyncDelegator); + return ts.setTextRange(ts.createCall(ts.getHelperName("__asyncDelegator"), + /*typeArguments*/ undefined, [expression]), location); + } + var asyncValues = { + name: "typescript:asyncValues", + scoped: false, + text: "\n var __asyncValues = (this && this.__asyncValues) || function (o) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var m = o[Symbol.asyncIterator], i;\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\n };" + }; + function createAsyncValuesHelper(context, expression, location) { + context.requestEmitHelper(asyncValues); + return ts.setTextRange(ts.createCall(ts.getHelperName("__asyncValues"), + /*typeArguments*/ undefined, [expression]), location); + } +})(ts || (ts = {})); +/*@internal*/ +var ts; +(function (ts) { + function transformJsx(context) { + var compilerOptions = context.getCompilerOptions(); + var currentSourceFile; + return ts.chainBundle(transformSourceFile); + /** + * Transform JSX-specific syntax in a SourceFile. + * + * @param node A SourceFile node. + */ + function transformSourceFile(node) { + if (node.isDeclarationFile) { + return node; + } + currentSourceFile = node; + var visited = ts.visitEachChild(node, visitor, context); + ts.addEmitHelpers(visited, context.readEmitHelpers()); + return visited; + } + function visitor(node) { + if (node.transformFlags & 4 /* ContainsJsx */) { + return visitorWorker(node); + } + else { + return node; + } + } + function visitorWorker(node) { + switch (node.kind) { + case 260 /* JsxElement */: + return visitJsxElement(node, /*isChild*/ false); + case 261 /* JsxSelfClosingElement */: + return visitJsxSelfClosingElement(node, /*isChild*/ false); + case 264 /* JsxFragment */: + return visitJsxFragment(node, /*isChild*/ false); + case 270 /* JsxExpression */: + return visitJsxExpression(node); + default: + return ts.visitEachChild(node, visitor, context); + } + } + function transformJsxChildToExpression(node) { + switch (node.kind) { + case 11 /* JsxText */: + return visitJsxText(node); + case 270 /* JsxExpression */: + return visitJsxExpression(node); + case 260 /* JsxElement */: + return visitJsxElement(node, /*isChild*/ true); + case 261 /* JsxSelfClosingElement */: + return visitJsxSelfClosingElement(node, /*isChild*/ true); + case 264 /* JsxFragment */: + return visitJsxFragment(node, /*isChild*/ true); + default: + return ts.Debug.failBadSyntaxKind(node); + } + } + function visitJsxElement(node, isChild) { + return visitJsxOpeningLikeElement(node.openingElement, node.children, isChild, /*location*/ node); + } + function visitJsxSelfClosingElement(node, isChild) { + return visitJsxOpeningLikeElement(node, /*children*/ undefined, isChild, /*location*/ node); + } + function visitJsxFragment(node, isChild) { + return visitJsxOpeningFragment(node.openingFragment, node.children, isChild, /*location*/ node); + } + function visitJsxOpeningLikeElement(node, children, isChild, location) { + var tagName = getTagName(node); + var objectProperties; + var attrs = node.attributes.properties; + if (attrs.length === 0) { + // When there are no attributes, React wants "null" + objectProperties = ts.createNull(); + } + else { + // Map spans of JsxAttribute nodes into object literals and spans + // of JsxSpreadAttribute nodes into expressions. + var segments = ts.flatten(ts.spanMap(attrs, ts.isJsxSpreadAttribute, function (attrs, isSpread) { return isSpread + ? ts.map(attrs, transformJsxSpreadAttributeToExpression) + : ts.createObjectLiteral(ts.map(attrs, transformJsxAttributeToObjectLiteralElement)); })); + if (ts.isJsxSpreadAttribute(attrs[0])) { + // We must always emit at least one object literal before a spread + // argument. + segments.unshift(ts.createObjectLiteral()); + } + // Either emit one big object literal (no spread attribs), or + // a call to the __assign helper. + objectProperties = ts.singleOrUndefined(segments); + if (!objectProperties) { + objectProperties = ts.createAssignHelper(context, segments); + } + } + var element = ts.createExpressionForJsxElement(context.getEmitResolver().getJsxFactoryEntity(currentSourceFile), compilerOptions.reactNamespace, // TODO: GH#18217 + tagName, objectProperties, ts.mapDefined(children, transformJsxChildToExpression), node, location); + if (isChild) { + ts.startOnNewLine(element); + } + return element; + } + function visitJsxOpeningFragment(node, children, isChild, location) { + var element = ts.createExpressionForJsxFragment(context.getEmitResolver().getJsxFactoryEntity(currentSourceFile), compilerOptions.reactNamespace, // TODO: GH#18217 + ts.mapDefined(children, transformJsxChildToExpression), node, location); + if (isChild) { + ts.startOnNewLine(element); + } + return element; + } + function transformJsxSpreadAttributeToExpression(node) { + return ts.visitNode(node.expression, visitor, ts.isExpression); + } + function transformJsxAttributeToObjectLiteralElement(node) { + var name = getAttributeName(node); + var expression = transformJsxAttributeInitializer(node.initializer); + return ts.createPropertyAssignment(name, expression); + } + function transformJsxAttributeInitializer(node) { + if (node === undefined) { + return ts.createTrue(); + } + else if (node.kind === 10 /* StringLiteral */) { + // Always recreate the literal to escape any escape sequences or newlines which may be in the original jsx string and which + // Need to be escaped to be handled correctly in a normal string + var literal = ts.createLiteral(tryDecodeEntities(node.text) || node.text); + literal.singleQuote = node.singleQuote !== undefined ? node.singleQuote : !ts.isStringDoubleQuoted(node, currentSourceFile); + return ts.setTextRange(literal, node); + } + else if (node.kind === 270 /* JsxExpression */) { + if (node.expression === undefined) { + return ts.createTrue(); + } + return visitJsxExpression(node); + } + else { + return ts.Debug.failBadSyntaxKind(node); + } + } + function visitJsxText(node) { + var fixed = fixupWhitespaceAndDecodeEntities(ts.getTextOfNode(node, /*includeTrivia*/ true)); + return fixed === undefined ? undefined : ts.createLiteral(fixed); + } + /** + * JSX trims whitespace at the end and beginning of lines, except that the + * start/end of a tag is considered a start/end of a line only if that line is + * on the same line as the closing tag. See examples in + * tests/cases/conformance/jsx/tsxReactEmitWhitespace.tsx + * See also https://www.w3.org/TR/html4/struct/text.html#h-9.1 and https://www.w3.org/TR/CSS2/text.html#white-space-model + * + * An equivalent algorithm would be: + * - If there is only one line, return it. + * - If there is only whitespace (but multiple lines), return `undefined`. + * - Split the text into lines. + * - 'trimRight' the first line, 'trimLeft' the last line, 'trim' middle lines. + * - Decode entities on each line (individually). + * - Remove empty lines and join the rest with " ". + */ + function fixupWhitespaceAndDecodeEntities(text) { + var acc; + // First non-whitespace character on this line. + var firstNonWhitespace = 0; + // Last non-whitespace character on this line. + var lastNonWhitespace = -1; + // These initial values are special because the first line is: + // firstNonWhitespace = 0 to indicate that we want leading whitsepace, + // but lastNonWhitespace = -1 as a special flag to indicate that we *don't* include the line if it's all whitespace. + for (var i = 0; i < text.length; i++) { + var c = text.charCodeAt(i); + if (ts.isLineBreak(c)) { + // If we've seen any non-whitespace characters on this line, add the 'trim' of the line. + // (lastNonWhitespace === -1 is a special flag to detect whether the first line is all whitespace.) + if (firstNonWhitespace !== -1 && lastNonWhitespace !== -1) { + acc = addLineOfJsxText(acc, text.substr(firstNonWhitespace, lastNonWhitespace - firstNonWhitespace + 1)); + } + // Reset firstNonWhitespace for the next line. + // Don't bother to reset lastNonWhitespace because we ignore it if firstNonWhitespace = -1. + firstNonWhitespace = -1; + } + else if (!ts.isWhiteSpaceSingleLine(c)) { + lastNonWhitespace = i; + if (firstNonWhitespace === -1) { + firstNonWhitespace = i; + } + } + } + return firstNonWhitespace !== -1 + // Last line had a non-whitespace character. Emit the 'trimLeft', meaning keep trailing whitespace. + ? addLineOfJsxText(acc, text.substr(firstNonWhitespace)) + // Last line was all whitespace, so ignore it + : acc; + } + function addLineOfJsxText(acc, trimmedLine) { + // We do not escape the string here as that is handled by the printer + // when it emits the literal. We do, however, need to decode JSX entities. + var decoded = decodeEntities(trimmedLine); + return acc === undefined ? decoded : acc + " " + decoded; + } + /** + * Replace entities like " ", "{", and "�" with the characters they encode. + * See https://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references + */ + function decodeEntities(text) { + return text.replace(/&((#((\d+)|x([\da-fA-F]+)))|(\w+));/g, function (match, _all, _number, _digits, decimal, hex, word) { + if (decimal) { + return String.fromCharCode(parseInt(decimal, 10)); + } + else if (hex) { + return String.fromCharCode(parseInt(hex, 16)); + } + else { + var ch = entities.get(word); + // If this is not a valid entity, then just use `match` (replace it with itself, i.e. don't replace) + return ch ? String.fromCharCode(ch) : match; + } + }); + } + /** Like `decodeEntities` but returns `undefined` if there were no entities to decode. */ + function tryDecodeEntities(text) { + var decoded = decodeEntities(text); + return decoded === text ? undefined : decoded; + } + function getTagName(node) { + if (node.kind === 260 /* JsxElement */) { + return getTagName(node.openingElement); + } + else { + var name = node.tagName; + if (ts.isIdentifier(name) && ts.isIntrinsicJsxName(name.escapedText)) { + return ts.createLiteral(ts.idText(name)); + } + else { + return ts.createExpressionFromEntityName(name); + } + } + } + /** + * Emit an attribute name, which is quoted if it needs to be quoted. Because + * these emit into an object literal property name, we don't need to be worried + * about keywords, just non-identifier characters + */ + function getAttributeName(node) { + var name = node.name; + var text = ts.idText(name); + if (/^[A-Za-z_]\w*$/.test(text)) { + return name; + } + else { + return ts.createLiteral(text); + } + } + function visitJsxExpression(node) { + return ts.visitNode(node.expression, visitor, ts.isExpression); + } + } + ts.transformJsx = transformJsx; + var entities = ts.createMapFromTemplate({ + quot: 0x0022, + amp: 0x0026, + apos: 0x0027, + lt: 0x003C, + gt: 0x003E, + nbsp: 0x00A0, + iexcl: 0x00A1, + cent: 0x00A2, + pound: 0x00A3, + curren: 0x00A4, + yen: 0x00A5, + brvbar: 0x00A6, + sect: 0x00A7, + uml: 0x00A8, + copy: 0x00A9, + ordf: 0x00AA, + laquo: 0x00AB, + not: 0x00AC, + shy: 0x00AD, + reg: 0x00AE, + macr: 0x00AF, + deg: 0x00B0, + plusmn: 0x00B1, + sup2: 0x00B2, + sup3: 0x00B3, + acute: 0x00B4, + micro: 0x00B5, + para: 0x00B6, + middot: 0x00B7, + cedil: 0x00B8, + sup1: 0x00B9, + ordm: 0x00BA, + raquo: 0x00BB, + frac14: 0x00BC, + frac12: 0x00BD, + frac34: 0x00BE, + iquest: 0x00BF, + Agrave: 0x00C0, + Aacute: 0x00C1, + Acirc: 0x00C2, + Atilde: 0x00C3, + Auml: 0x00C4, + Aring: 0x00C5, + AElig: 0x00C6, + Ccedil: 0x00C7, + Egrave: 0x00C8, + Eacute: 0x00C9, + Ecirc: 0x00CA, + Euml: 0x00CB, + Igrave: 0x00CC, + Iacute: 0x00CD, + Icirc: 0x00CE, + Iuml: 0x00CF, + ETH: 0x00D0, + Ntilde: 0x00D1, + Ograve: 0x00D2, + Oacute: 0x00D3, + Ocirc: 0x00D4, + Otilde: 0x00D5, + Ouml: 0x00D6, + times: 0x00D7, + Oslash: 0x00D8, + Ugrave: 0x00D9, + Uacute: 0x00DA, + Ucirc: 0x00DB, + Uuml: 0x00DC, + Yacute: 0x00DD, + THORN: 0x00DE, + szlig: 0x00DF, + agrave: 0x00E0, + aacute: 0x00E1, + acirc: 0x00E2, + atilde: 0x00E3, + auml: 0x00E4, + aring: 0x00E5, + aelig: 0x00E6, + ccedil: 0x00E7, + egrave: 0x00E8, + eacute: 0x00E9, + ecirc: 0x00EA, + euml: 0x00EB, + igrave: 0x00EC, + iacute: 0x00ED, + icirc: 0x00EE, + iuml: 0x00EF, + eth: 0x00F0, + ntilde: 0x00F1, + ograve: 0x00F2, + oacute: 0x00F3, + ocirc: 0x00F4, + otilde: 0x00F5, + ouml: 0x00F6, + divide: 0x00F7, + oslash: 0x00F8, + ugrave: 0x00F9, + uacute: 0x00FA, + ucirc: 0x00FB, + uuml: 0x00FC, + yacute: 0x00FD, + thorn: 0x00FE, + yuml: 0x00FF, + OElig: 0x0152, + oelig: 0x0153, + Scaron: 0x0160, + scaron: 0x0161, + Yuml: 0x0178, + fnof: 0x0192, + circ: 0x02C6, + tilde: 0x02DC, + Alpha: 0x0391, + Beta: 0x0392, + Gamma: 0x0393, + Delta: 0x0394, + Epsilon: 0x0395, + Zeta: 0x0396, + Eta: 0x0397, + Theta: 0x0398, + Iota: 0x0399, + Kappa: 0x039A, + Lambda: 0x039B, + Mu: 0x039C, + Nu: 0x039D, + Xi: 0x039E, + Omicron: 0x039F, + Pi: 0x03A0, + Rho: 0x03A1, + Sigma: 0x03A3, + Tau: 0x03A4, + Upsilon: 0x03A5, + Phi: 0x03A6, + Chi: 0x03A7, + Psi: 0x03A8, + Omega: 0x03A9, + alpha: 0x03B1, + beta: 0x03B2, + gamma: 0x03B3, + delta: 0x03B4, + epsilon: 0x03B5, + zeta: 0x03B6, + eta: 0x03B7, + theta: 0x03B8, + iota: 0x03B9, + kappa: 0x03BA, + lambda: 0x03BB, + mu: 0x03BC, + nu: 0x03BD, + xi: 0x03BE, + omicron: 0x03BF, + pi: 0x03C0, + rho: 0x03C1, + sigmaf: 0x03C2, + sigma: 0x03C3, + tau: 0x03C4, + upsilon: 0x03C5, + phi: 0x03C6, + chi: 0x03C7, + psi: 0x03C8, + omega: 0x03C9, + thetasym: 0x03D1, + upsih: 0x03D2, + piv: 0x03D6, + ensp: 0x2002, + emsp: 0x2003, + thinsp: 0x2009, + zwnj: 0x200C, + zwj: 0x200D, + lrm: 0x200E, + rlm: 0x200F, + ndash: 0x2013, + mdash: 0x2014, + lsquo: 0x2018, + rsquo: 0x2019, + sbquo: 0x201A, + ldquo: 0x201C, + rdquo: 0x201D, + bdquo: 0x201E, + dagger: 0x2020, + Dagger: 0x2021, + bull: 0x2022, + hellip: 0x2026, + permil: 0x2030, + prime: 0x2032, + Prime: 0x2033, + lsaquo: 0x2039, + rsaquo: 0x203A, + oline: 0x203E, + frasl: 0x2044, + euro: 0x20AC, + image: 0x2111, + weierp: 0x2118, + real: 0x211C, + trade: 0x2122, + alefsym: 0x2135, + larr: 0x2190, + uarr: 0x2191, + rarr: 0x2192, + darr: 0x2193, + harr: 0x2194, + crarr: 0x21B5, + lArr: 0x21D0, + uArr: 0x21D1, + rArr: 0x21D2, + dArr: 0x21D3, + hArr: 0x21D4, + forall: 0x2200, + part: 0x2202, + exist: 0x2203, + empty: 0x2205, + nabla: 0x2207, + isin: 0x2208, + notin: 0x2209, + ni: 0x220B, + prod: 0x220F, + sum: 0x2211, + minus: 0x2212, + lowast: 0x2217, + radic: 0x221A, + prop: 0x221D, + infin: 0x221E, + ang: 0x2220, + and: 0x2227, + or: 0x2228, + cap: 0x2229, + cup: 0x222A, + int: 0x222B, + there4: 0x2234, + sim: 0x223C, + cong: 0x2245, + asymp: 0x2248, + ne: 0x2260, + equiv: 0x2261, + le: 0x2264, + ge: 0x2265, + sub: 0x2282, + sup: 0x2283, + nsub: 0x2284, + sube: 0x2286, + supe: 0x2287, + oplus: 0x2295, + otimes: 0x2297, + perp: 0x22A5, + sdot: 0x22C5, + lceil: 0x2308, + rceil: 0x2309, + lfloor: 0x230A, + rfloor: 0x230B, + lang: 0x2329, + rang: 0x232A, + loz: 0x25CA, + spades: 0x2660, + clubs: 0x2663, + hearts: 0x2665, + diams: 0x2666 + }); +})(ts || (ts = {})); +/*@internal*/ +var ts; +(function (ts) { + function transformES2016(context) { + var hoistVariableDeclaration = context.hoistVariableDeclaration; + return ts.chainBundle(transformSourceFile); + function transformSourceFile(node) { + if (node.isDeclarationFile) { + return node; + } + return ts.visitEachChild(node, visitor, context); + } + function visitor(node) { + if ((node.transformFlags & 32 /* ContainsES2016 */) === 0) { + return node; + } + switch (node.kind) { + case 204 /* BinaryExpression */: + return visitBinaryExpression(node); + default: + return ts.visitEachChild(node, visitor, context); + } + } + function visitBinaryExpression(node) { + switch (node.operatorToken.kind) { + case 63 /* AsteriskAsteriskEqualsToken */: + return visitExponentiationAssignmentExpression(node); + case 41 /* AsteriskAsteriskToken */: + return visitExponentiationExpression(node); + default: + return ts.visitEachChild(node, visitor, context); + } + } + function visitExponentiationAssignmentExpression(node) { + var target; + var value; + var left = ts.visitNode(node.left, visitor, ts.isExpression); + var right = ts.visitNode(node.right, visitor, ts.isExpression); + if (ts.isElementAccessExpression(left)) { + // Transforms `a[x] **= b` into `(_a = a)[_x = x] = Math.pow(_a[_x], b)` + var expressionTemp = ts.createTempVariable(hoistVariableDeclaration); + var argumentExpressionTemp = ts.createTempVariable(hoistVariableDeclaration); + target = ts.setTextRange(ts.createElementAccess(ts.setTextRange(ts.createAssignment(expressionTemp, left.expression), left.expression), ts.setTextRange(ts.createAssignment(argumentExpressionTemp, left.argumentExpression), left.argumentExpression)), left); + value = ts.setTextRange(ts.createElementAccess(expressionTemp, argumentExpressionTemp), left); + } + else if (ts.isPropertyAccessExpression(left)) { + // Transforms `a.x **= b` into `(_a = a).x = Math.pow(_a.x, b)` + var expressionTemp = ts.createTempVariable(hoistVariableDeclaration); + target = ts.setTextRange(ts.createPropertyAccess(ts.setTextRange(ts.createAssignment(expressionTemp, left.expression), left.expression), left.name), left); + value = ts.setTextRange(ts.createPropertyAccess(expressionTemp, left.name), left); + } + else { + // Transforms `a **= b` into `a = Math.pow(a, b)` + target = left; + value = left; + } + return ts.setTextRange(ts.createAssignment(target, ts.createMathPow(value, right, /*location*/ node)), node); + } + function visitExponentiationExpression(node) { + // Transforms `a ** b` into `Math.pow(a, b)` + var left = ts.visitNode(node.left, visitor, ts.isExpression); + var right = ts.visitNode(node.right, visitor, ts.isExpression); + return ts.createMathPow(left, right, /*location*/ node); + } + } + ts.transformES2016 = transformES2016; +})(ts || (ts = {})); +/*@internal*/ +var ts; +(function (ts) { + var ES2015SubstitutionFlags; + (function (ES2015SubstitutionFlags) { + /** Enables substitutions for captured `this` */ + ES2015SubstitutionFlags[ES2015SubstitutionFlags["CapturedThis"] = 1] = "CapturedThis"; + /** Enables substitutions for block-scoped bindings. */ + ES2015SubstitutionFlags[ES2015SubstitutionFlags["BlockScopedBindings"] = 2] = "BlockScopedBindings"; + })(ES2015SubstitutionFlags || (ES2015SubstitutionFlags = {})); + var LoopOutParameterFlags; + (function (LoopOutParameterFlags) { + LoopOutParameterFlags[LoopOutParameterFlags["Body"] = 1] = "Body"; + LoopOutParameterFlags[LoopOutParameterFlags["Initializer"] = 2] = "Initializer"; + })(LoopOutParameterFlags || (LoopOutParameterFlags = {})); + var CopyDirection; + (function (CopyDirection) { + CopyDirection[CopyDirection["ToOriginal"] = 0] = "ToOriginal"; + CopyDirection[CopyDirection["ToOutParameter"] = 1] = "ToOutParameter"; + })(CopyDirection || (CopyDirection = {})); + var Jump; + (function (Jump) { + Jump[Jump["Break"] = 2] = "Break"; + Jump[Jump["Continue"] = 4] = "Continue"; + Jump[Jump["Return"] = 8] = "Return"; + })(Jump || (Jump = {})); + var SuperCaptureResult; + (function (SuperCaptureResult) { + /** + * A capture may have been added for calls to 'super', but + * the caller should emit subsequent statements normally. + */ + SuperCaptureResult[SuperCaptureResult["NoReplacement"] = 0] = "NoReplacement"; + /** + * A call to 'super()' got replaced with a capturing statement like: + * + * var _this = _super.call(...) || this; + * + * Callers should skip the current statement. + */ + SuperCaptureResult[SuperCaptureResult["ReplaceSuperCapture"] = 1] = "ReplaceSuperCapture"; + /** + * A call to 'super()' got replaced with a capturing statement like: + * + * return _super.call(...) || this; + * + * Callers should skip the current statement and avoid any returns of '_this'. + */ + SuperCaptureResult[SuperCaptureResult["ReplaceWithReturn"] = 2] = "ReplaceWithReturn"; + })(SuperCaptureResult || (SuperCaptureResult = {})); + // Facts we track as we traverse the tree + var HierarchyFacts; + (function (HierarchyFacts) { + HierarchyFacts[HierarchyFacts["None"] = 0] = "None"; + // + // Ancestor facts + // + HierarchyFacts[HierarchyFacts["Function"] = 1] = "Function"; + HierarchyFacts[HierarchyFacts["ArrowFunction"] = 2] = "ArrowFunction"; + HierarchyFacts[HierarchyFacts["AsyncFunctionBody"] = 4] = "AsyncFunctionBody"; + HierarchyFacts[HierarchyFacts["NonStaticClassElement"] = 8] = "NonStaticClassElement"; + HierarchyFacts[HierarchyFacts["CapturesThis"] = 16] = "CapturesThis"; + HierarchyFacts[HierarchyFacts["ExportedVariableStatement"] = 32] = "ExportedVariableStatement"; + HierarchyFacts[HierarchyFacts["TopLevel"] = 64] = "TopLevel"; + HierarchyFacts[HierarchyFacts["Block"] = 128] = "Block"; + HierarchyFacts[HierarchyFacts["IterationStatement"] = 256] = "IterationStatement"; + HierarchyFacts[HierarchyFacts["IterationStatementBlock"] = 512] = "IterationStatementBlock"; + HierarchyFacts[HierarchyFacts["ForStatement"] = 1024] = "ForStatement"; + HierarchyFacts[HierarchyFacts["ForInOrForOfStatement"] = 2048] = "ForInOrForOfStatement"; + HierarchyFacts[HierarchyFacts["ConstructorWithCapturedSuper"] = 4096] = "ConstructorWithCapturedSuper"; + HierarchyFacts[HierarchyFacts["ComputedPropertyName"] = 8192] = "ComputedPropertyName"; + // NOTE: do not add more ancestor flags without also updating AncestorFactsMask below. + // + // Ancestor masks + // + HierarchyFacts[HierarchyFacts["AncestorFactsMask"] = 16383] = "AncestorFactsMask"; + // We are always in *some* kind of block scope, but only specific block-scope containers are + // top-level or Blocks. + HierarchyFacts[HierarchyFacts["BlockScopeIncludes"] = 0] = "BlockScopeIncludes"; + HierarchyFacts[HierarchyFacts["BlockScopeExcludes"] = 4032] = "BlockScopeExcludes"; + // A source file is a top-level block scope. + HierarchyFacts[HierarchyFacts["SourceFileIncludes"] = 64] = "SourceFileIncludes"; + HierarchyFacts[HierarchyFacts["SourceFileExcludes"] = 3968] = "SourceFileExcludes"; + // Functions, methods, and accessors are both new lexical scopes and new block scopes. + HierarchyFacts[HierarchyFacts["FunctionIncludes"] = 65] = "FunctionIncludes"; + HierarchyFacts[HierarchyFacts["FunctionExcludes"] = 16286] = "FunctionExcludes"; + HierarchyFacts[HierarchyFacts["AsyncFunctionBodyIncludes"] = 69] = "AsyncFunctionBodyIncludes"; + HierarchyFacts[HierarchyFacts["AsyncFunctionBodyExcludes"] = 16278] = "AsyncFunctionBodyExcludes"; + // Arrow functions are lexically scoped to their container, but are new block scopes. + HierarchyFacts[HierarchyFacts["ArrowFunctionIncludes"] = 66] = "ArrowFunctionIncludes"; + HierarchyFacts[HierarchyFacts["ArrowFunctionExcludes"] = 16256] = "ArrowFunctionExcludes"; + // Constructors are both new lexical scopes and new block scopes. Constructors are also + // always considered non-static members of a class. + HierarchyFacts[HierarchyFacts["ConstructorIncludes"] = 73] = "ConstructorIncludes"; + HierarchyFacts[HierarchyFacts["ConstructorExcludes"] = 16278] = "ConstructorExcludes"; + // 'do' and 'while' statements are not block scopes. We track that the subtree is contained + // within an IterationStatement to indicate whether the embedded statement is an + // IterationStatementBlock. + HierarchyFacts[HierarchyFacts["DoOrWhileStatementIncludes"] = 256] = "DoOrWhileStatementIncludes"; + HierarchyFacts[HierarchyFacts["DoOrWhileStatementExcludes"] = 0] = "DoOrWhileStatementExcludes"; + // 'for' statements are new block scopes and have special handling for 'let' declarations. + HierarchyFacts[HierarchyFacts["ForStatementIncludes"] = 1280] = "ForStatementIncludes"; + HierarchyFacts[HierarchyFacts["ForStatementExcludes"] = 3008] = "ForStatementExcludes"; + // 'for-in' and 'for-of' statements are new block scopes and have special handling for + // 'let' declarations. + HierarchyFacts[HierarchyFacts["ForInOrForOfStatementIncludes"] = 2304] = "ForInOrForOfStatementIncludes"; + HierarchyFacts[HierarchyFacts["ForInOrForOfStatementExcludes"] = 1984] = "ForInOrForOfStatementExcludes"; + // Blocks (other than function bodies) are new block scopes. + HierarchyFacts[HierarchyFacts["BlockIncludes"] = 128] = "BlockIncludes"; + HierarchyFacts[HierarchyFacts["BlockExcludes"] = 3904] = "BlockExcludes"; + HierarchyFacts[HierarchyFacts["IterationStatementBlockIncludes"] = 512] = "IterationStatementBlockIncludes"; + HierarchyFacts[HierarchyFacts["IterationStatementBlockExcludes"] = 4032] = "IterationStatementBlockExcludes"; + // Computed property names track subtree flags differently than their containing members. + HierarchyFacts[HierarchyFacts["ComputedPropertyNameIncludes"] = 8192] = "ComputedPropertyNameIncludes"; + HierarchyFacts[HierarchyFacts["ComputedPropertyNameExcludes"] = 0] = "ComputedPropertyNameExcludes"; + // + // Subtree facts + // + HierarchyFacts[HierarchyFacts["NewTarget"] = 16384] = "NewTarget"; + HierarchyFacts[HierarchyFacts["NewTargetInComputedPropertyName"] = 32768] = "NewTargetInComputedPropertyName"; + // + // Subtree masks + // + HierarchyFacts[HierarchyFacts["SubtreeFactsMask"] = -16384] = "SubtreeFactsMask"; + HierarchyFacts[HierarchyFacts["PropagateNewTargetMask"] = 49152] = "PropagateNewTargetMask"; + })(HierarchyFacts || (HierarchyFacts = {})); + function transformES2015(context) { + var startLexicalEnvironment = context.startLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; + var compilerOptions = context.getCompilerOptions(); + var resolver = context.getEmitResolver(); + var previousOnSubstituteNode = context.onSubstituteNode; + var previousOnEmitNode = context.onEmitNode; + context.onEmitNode = onEmitNode; + context.onSubstituteNode = onSubstituteNode; + var currentSourceFile; + var currentText; + var hierarchyFacts; + var taggedTemplateStringDeclarations; + function recordTaggedTemplateString(temp) { + taggedTemplateStringDeclarations = ts.append(taggedTemplateStringDeclarations, ts.createVariableDeclaration(temp)); + } + /** + * Used to track if we are emitting body of the converted loop + */ + var convertedLoopState; + /** + * Keeps track of whether substitutions have been enabled for specific cases. + * They are persisted between each SourceFile transformation and should not + * be reset. + */ + var enabledSubstitutions; + return ts.chainBundle(transformSourceFile); + function transformSourceFile(node) { + if (node.isDeclarationFile) { + return node; + } + currentSourceFile = node; + currentText = node.text; + var visited = visitSourceFile(node); + ts.addEmitHelpers(visited, context.readEmitHelpers()); + currentSourceFile = undefined; + currentText = undefined; + taggedTemplateStringDeclarations = undefined; + hierarchyFacts = 0 /* None */; + return visited; + } + /** + * Sets the `HierarchyFacts` for this node prior to visiting this node's subtree, returning the facts set prior to modification. + * @param excludeFacts The existing `HierarchyFacts` to reset before visiting the subtree. + * @param includeFacts The new `HierarchyFacts` to set before visiting the subtree. + */ + function enterSubtree(excludeFacts, includeFacts) { + var ancestorFacts = hierarchyFacts; + hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & 16383 /* AncestorFactsMask */; + return ancestorFacts; + } + /** + * Restores the `HierarchyFacts` for this node's ancestor after visiting this node's + * subtree, propagating specific facts from the subtree. + * @param ancestorFacts The `HierarchyFacts` of the ancestor to restore after visiting the subtree. + * @param excludeFacts The existing `HierarchyFacts` of the subtree that should not be propagated. + * @param includeFacts The new `HierarchyFacts` of the subtree that should be propagated. + */ + function exitSubtree(ancestorFacts, excludeFacts, includeFacts) { + hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & -16384 /* SubtreeFactsMask */ | ancestorFacts; + } + function isReturnVoidStatementInConstructorWithCapturedSuper(node) { + return (hierarchyFacts & 4096 /* ConstructorWithCapturedSuper */) !== 0 + && node.kind === 230 /* ReturnStatement */ + && !node.expression; + } + function shouldVisitNode(node) { + return (node.transformFlags & 128 /* ContainsES2015 */) !== 0 + || convertedLoopState !== undefined + || (hierarchyFacts & 4096 /* ConstructorWithCapturedSuper */ && (ts.isStatement(node) || (node.kind === 218 /* Block */))) + || (ts.isIterationStatement(node, /*lookInLabeledStatements*/ false) && shouldConvertIterationStatement(node)) + || (ts.getEmitFlags(node) & 33554432 /* TypeScriptClassWrapper */) !== 0; + } + function visitor(node) { + if (shouldVisitNode(node)) { + return visitJavaScript(node); + } + else { + return node; + } + } + function functionBodyVisitor(node) { + if (shouldVisitNode(node)) { + return visitBlock(node, /*isFunctionBody*/ true); + } + return node; + } + function callExpressionVisitor(node) { + if (node.kind === 98 /* SuperKeyword */) { + return visitSuperKeyword(/*isExpressionOfCall*/ true); + } + return visitor(node); + } + function visitJavaScript(node) { + switch (node.kind) { + case 116 /* StaticKeyword */: + return undefined; // elide static keyword + case 240 /* ClassDeclaration */: + return visitClassDeclaration(node); + case 209 /* ClassExpression */: + return visitClassExpression(node); + case 151 /* Parameter */: + return visitParameter(node); + case 239 /* FunctionDeclaration */: + return visitFunctionDeclaration(node); + case 197 /* ArrowFunction */: + return visitArrowFunction(node); + case 196 /* FunctionExpression */: + return visitFunctionExpression(node); + case 237 /* VariableDeclaration */: + return visitVariableDeclaration(node); + case 72 /* Identifier */: + return visitIdentifier(node); + case 238 /* VariableDeclarationList */: + return visitVariableDeclarationList(node); + case 232 /* SwitchStatement */: + return visitSwitchStatement(node); + case 246 /* CaseBlock */: + return visitCaseBlock(node); + case 218 /* Block */: + return visitBlock(node, /*isFunctionBody*/ false); + case 229 /* BreakStatement */: + case 228 /* ContinueStatement */: + return visitBreakOrContinueStatement(node); + case 233 /* LabeledStatement */: + return visitLabeledStatement(node); + case 223 /* DoStatement */: + case 224 /* WhileStatement */: + return visitDoOrWhileStatement(node, /*outermostLabeledStatement*/ undefined); + case 225 /* ForStatement */: + return visitForStatement(node, /*outermostLabeledStatement*/ undefined); + case 226 /* ForInStatement */: + return visitForInStatement(node, /*outermostLabeledStatement*/ undefined); + case 227 /* ForOfStatement */: + return visitForOfStatement(node, /*outermostLabeledStatement*/ undefined); + case 221 /* ExpressionStatement */: + return visitExpressionStatement(node); + case 188 /* ObjectLiteralExpression */: + return visitObjectLiteralExpression(node); + case 274 /* CatchClause */: + return visitCatchClause(node); + case 276 /* ShorthandPropertyAssignment */: + return visitShorthandPropertyAssignment(node); + case 149 /* ComputedPropertyName */: + return visitComputedPropertyName(node); + case 187 /* ArrayLiteralExpression */: + return visitArrayLiteralExpression(node); + case 191 /* CallExpression */: + return visitCallExpression(node); + case 192 /* NewExpression */: + return visitNewExpression(node); + case 195 /* ParenthesizedExpression */: + return visitParenthesizedExpression(node, /*needsDestructuringValue*/ true); + case 204 /* BinaryExpression */: + return visitBinaryExpression(node, /*needsDestructuringValue*/ true); + case 14 /* NoSubstitutionTemplateLiteral */: + case 15 /* TemplateHead */: + case 16 /* TemplateMiddle */: + case 17 /* TemplateTail */: + return visitTemplateLiteral(node); + case 10 /* StringLiteral */: + return visitStringLiteral(node); + case 8 /* NumericLiteral */: + return visitNumericLiteral(node); + case 193 /* TaggedTemplateExpression */: + return visitTaggedTemplateExpression(node); + case 206 /* TemplateExpression */: + return visitTemplateExpression(node); + case 207 /* YieldExpression */: + return visitYieldExpression(node); + case 208 /* SpreadElement */: + return visitSpreadElement(node); + case 98 /* SuperKeyword */: + return visitSuperKeyword(/*isExpressionOfCall*/ false); + case 100 /* ThisKeyword */: + return visitThisKeyword(node); + case 214 /* MetaProperty */: + return visitMetaProperty(node); + case 156 /* MethodDeclaration */: + return visitMethodDeclaration(node); + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + return visitAccessorDeclaration(node); + case 219 /* VariableStatement */: + return visitVariableStatement(node); + case 230 /* ReturnStatement */: + return visitReturnStatement(node); + default: + return ts.visitEachChild(node, visitor, context); + } + } + function visitSourceFile(node) { + var ancestorFacts = enterSubtree(3968 /* SourceFileExcludes */, 64 /* SourceFileIncludes */); + var statements = []; + startLexicalEnvironment(); + var statementOffset = ts.addStandardPrologue(statements, node.statements, /*ensureUseStrict*/ false); + addCaptureThisForNodeIfNeeded(statements, node); + statementOffset = ts.addCustomPrologue(statements, node.statements, statementOffset, visitor); + ts.addRange(statements, ts.visitNodes(node.statements, visitor, ts.isStatement, statementOffset)); + if (taggedTemplateStringDeclarations) { + statements.push(ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList(taggedTemplateStringDeclarations))); + } + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */); + return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements)); + } + function visitSwitchStatement(node) { + if (convertedLoopState !== undefined) { + var savedAllowedNonLabeledJumps = convertedLoopState.allowedNonLabeledJumps; + // for switch statement allow only non-labeled break + convertedLoopState.allowedNonLabeledJumps |= 2 /* Break */; + var result = ts.visitEachChild(node, visitor, context); + convertedLoopState.allowedNonLabeledJumps = savedAllowedNonLabeledJumps; + return result; + } + return ts.visitEachChild(node, visitor, context); + } + function visitCaseBlock(node) { + var ancestorFacts = enterSubtree(4032 /* BlockScopeExcludes */, 0 /* BlockScopeIncludes */); + var updated = ts.visitEachChild(node, visitor, context); + exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */); + return updated; + } + function returnCapturedThis(node) { + return ts.setOriginalNode(ts.createReturn(ts.createFileLevelUniqueName("_this")), node); + } + function visitReturnStatement(node) { + if (convertedLoopState) { + convertedLoopState.nonLocalJumps |= 8 /* Return */; + if (isReturnVoidStatementInConstructorWithCapturedSuper(node)) { + node = returnCapturedThis(node); + } + return ts.createReturn(ts.createObjectLiteral([ + ts.createPropertyAssignment(ts.createIdentifier("value"), node.expression + ? ts.visitNode(node.expression, visitor, ts.isExpression) + : ts.createVoidZero()) + ])); + } + else if (isReturnVoidStatementInConstructorWithCapturedSuper(node)) { + return returnCapturedThis(node); + } + return ts.visitEachChild(node, visitor, context); + } + function visitThisKeyword(node) { + if (convertedLoopState) { + if (hierarchyFacts & 2 /* ArrowFunction */) { + // if the enclosing function is an ArrowFunction then we use the captured 'this' keyword. + convertedLoopState.containsLexicalThis = true; + return node; + } + return convertedLoopState.thisName || (convertedLoopState.thisName = ts.createUniqueName("this")); + } + return node; + } + function visitIdentifier(node) { + if (!convertedLoopState) { + return node; + } + if (ts.isGeneratedIdentifier(node)) { + return node; + } + if (node.escapedText !== "arguments" || !resolver.isArgumentsLocalBinding(node)) { + return node; + } + return convertedLoopState.argumentsName || (convertedLoopState.argumentsName = ts.createUniqueName("arguments")); + } + function visitBreakOrContinueStatement(node) { + if (convertedLoopState) { + // check if we can emit break/continue as is + // it is possible if either + // - break/continue is labeled and label is located inside the converted loop + // - break/continue is non-labeled and located in non-converted loop/switch statement + var jump = node.kind === 229 /* BreakStatement */ ? 2 /* Break */ : 4 /* Continue */; + var canUseBreakOrContinue = (node.label && convertedLoopState.labels && convertedLoopState.labels.get(ts.idText(node.label))) || + (!node.label && (convertedLoopState.allowedNonLabeledJumps & jump)); + if (!canUseBreakOrContinue) { + var labelMarker = void 0; + var label = node.label; + if (!label) { + if (node.kind === 229 /* BreakStatement */) { + convertedLoopState.nonLocalJumps |= 2 /* Break */; + labelMarker = "break"; + } + else { + convertedLoopState.nonLocalJumps |= 4 /* Continue */; + // note: return value is emitted only to simplify debugging, call to converted loop body does not do any dispatching on it. + labelMarker = "continue"; + } + } + else { + if (node.kind === 229 /* BreakStatement */) { + labelMarker = "break-" + label.escapedText; + setLabeledJump(convertedLoopState, /*isBreak*/ true, ts.idText(label), labelMarker); + } + else { + labelMarker = "continue-" + label.escapedText; + setLabeledJump(convertedLoopState, /*isBreak*/ false, ts.idText(label), labelMarker); + } + } + var returnExpression = ts.createLiteral(labelMarker); + if (convertedLoopState.loopOutParameters.length) { + var outParams = convertedLoopState.loopOutParameters; + var expr = void 0; + for (var i = 0; i < outParams.length; i++) { + var copyExpr = copyOutParameter(outParams[i], 1 /* ToOutParameter */); + if (i === 0) { + expr = copyExpr; + } + else { + expr = ts.createBinary(expr, 27 /* CommaToken */, copyExpr); + } + } + returnExpression = ts.createBinary(expr, 27 /* CommaToken */, returnExpression); + } + return ts.createReturn(returnExpression); + } + } + return ts.visitEachChild(node, visitor, context); + } + /** + * Visits a ClassDeclaration and transforms it into a variable statement. + * + * @param node A ClassDeclaration node. + */ + function visitClassDeclaration(node) { + // [source] + // class C { } + // + // [output] + // var C = (function () { + // function C() { + // } + // return C; + // }()); + var variable = ts.createVariableDeclaration(ts.getLocalName(node, /*allowComments*/ true), + /*type*/ undefined, transformClassLikeDeclarationToExpression(node)); + ts.setOriginalNode(variable, node); + var statements = []; + var statement = ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([variable])); + ts.setOriginalNode(statement, node); + ts.setTextRange(statement, node); + ts.startOnNewLine(statement); + statements.push(statement); + // Add an `export default` statement for default exports (for `--target es5 --module es6`) + if (ts.hasModifier(node, 1 /* Export */)) { + var exportStatement = ts.hasModifier(node, 512 /* Default */) + ? ts.createExportDefault(ts.getLocalName(node)) + : ts.createExternalModuleExport(ts.getLocalName(node)); + ts.setOriginalNode(exportStatement, statement); + statements.push(exportStatement); + } + var emitFlags = ts.getEmitFlags(node); + if ((emitFlags & 4194304 /* HasEndOfDeclarationMarker */) === 0) { + // Add a DeclarationMarker as a marker for the end of the declaration + statements.push(ts.createEndOfDeclarationMarker(node)); + ts.setEmitFlags(statement, emitFlags | 4194304 /* HasEndOfDeclarationMarker */); + } + return ts.singleOrMany(statements); + } + /** + * Visits a ClassExpression and transforms it into an expression. + * + * @param node A ClassExpression node. + */ + function visitClassExpression(node) { + // [source] + // C = class { } + // + // [output] + // C = (function () { + // function class_1() { + // } + // return class_1; + // }()) + return transformClassLikeDeclarationToExpression(node); + } + /** + * Transforms a ClassExpression or ClassDeclaration into an expression. + * + * @param node A ClassExpression or ClassDeclaration node. + */ + function transformClassLikeDeclarationToExpression(node) { + // [source] + // class C extends D { + // constructor() {} + // method() {} + // get prop() {} + // set prop(v) {} + // } + // + // [output] + // (function (_super) { + // __extends(C, _super); + // function C() { + // } + // C.prototype.method = function () {} + // Object.defineProperty(C.prototype, "prop", { + // get: function() {}, + // set: function() {}, + // enumerable: true, + // configurable: true + // }); + // return C; + // }(D)) + if (node.name) { + enableSubstitutionsForBlockScopedBindings(); + } + var extendsClauseElement = ts.getEffectiveBaseTypeNode(node); + var classFunction = ts.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, extendsClauseElement ? [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, ts.createFileLevelUniqueName("_super"))] : [], + /*type*/ undefined, transformClassBody(node, extendsClauseElement)); + // To preserve the behavior of the old emitter, we explicitly indent + // the body of the function here if it was requested in an earlier + // transformation. + ts.setEmitFlags(classFunction, (ts.getEmitFlags(node) & 65536 /* Indented */) | 524288 /* ReuseTempVariableScope */); + // "inner" and "outer" below are added purely to preserve source map locations from + // the old emitter + var inner = ts.createPartiallyEmittedExpression(classFunction); + inner.end = node.end; + ts.setEmitFlags(inner, 1536 /* NoComments */); + var outer = ts.createPartiallyEmittedExpression(inner); + outer.end = ts.skipTrivia(currentText, node.pos); + ts.setEmitFlags(outer, 1536 /* NoComments */); + var result = ts.createParen(ts.createCall(outer, + /*typeArguments*/ undefined, extendsClauseElement + ? [ts.visitNode(extendsClauseElement.expression, visitor, ts.isExpression)] + : [])); + ts.addSyntheticLeadingComment(result, 3 /* MultiLineCommentTrivia */, "* @class "); + return result; + } + /** + * Transforms a ClassExpression or ClassDeclaration into a function body. + * + * @param node A ClassExpression or ClassDeclaration node. + * @param extendsClauseElement The expression for the class `extends` clause. + */ + function transformClassBody(node, extendsClauseElement) { + var statements = []; + startLexicalEnvironment(); + addExtendsHelperIfNeeded(statements, node, extendsClauseElement); + addConstructor(statements, node, extendsClauseElement); + addClassMembers(statements, node); + // Create a synthetic text range for the return statement. + var closingBraceLocation = ts.createTokenRange(ts.skipTrivia(currentText, node.members.end), 19 /* CloseBraceToken */); + var localName = ts.getInternalName(node); + // The following partially-emitted expression exists purely to align our sourcemap + // emit with the original emitter. + var outer = ts.createPartiallyEmittedExpression(localName); + outer.end = closingBraceLocation.end; + ts.setEmitFlags(outer, 1536 /* NoComments */); + var statement = ts.createReturn(outer); + statement.pos = closingBraceLocation.pos; + ts.setEmitFlags(statement, 1536 /* NoComments */ | 384 /* NoTokenSourceMaps */); + statements.push(statement); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), /*location*/ node.members), /*multiLine*/ true); + ts.setEmitFlags(block, 1536 /* NoComments */); + return block; + } + /** + * Adds a call to the `__extends` helper if needed for a class. + * + * @param statements The statements of the class body function. + * @param node The ClassExpression or ClassDeclaration node. + * @param extendsClauseElement The expression for the class `extends` clause. + */ + function addExtendsHelperIfNeeded(statements, node, extendsClauseElement) { + if (extendsClauseElement) { + statements.push(ts.setTextRange(ts.createExpressionStatement(createExtendsHelper(context, ts.getInternalName(node))), + /*location*/ extendsClauseElement)); + } + } + /** + * Adds the constructor of the class to a class body function. + * + * @param statements The statements of the class body function. + * @param node The ClassExpression or ClassDeclaration node. + * @param extendsClauseElement The expression for the class `extends` clause. + */ + function addConstructor(statements, node, extendsClauseElement) { + var savedConvertedLoopState = convertedLoopState; + convertedLoopState = undefined; + var ancestorFacts = enterSubtree(16278 /* ConstructorExcludes */, 73 /* ConstructorIncludes */); + var constructor = ts.getFirstConstructorWithBody(node); + var hasSynthesizedSuper = hasSynthesizedDefaultSuperCall(constructor, extendsClauseElement !== undefined); + var constructorFunction = ts.createFunctionDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, ts.getInternalName(node), + /*typeParameters*/ undefined, transformConstructorParameters(constructor, hasSynthesizedSuper), + /*type*/ undefined, transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper)); + ts.setTextRange(constructorFunction, constructor || node); + if (extendsClauseElement) { + ts.setEmitFlags(constructorFunction, 8 /* CapturesThis */); + } + statements.push(constructorFunction); + exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, 0 /* None */); + convertedLoopState = savedConvertedLoopState; + } + /** + * Transforms the parameters of the constructor declaration of a class. + * + * @param constructor The constructor for the class. + * @param hasSynthesizedSuper A value indicating whether the constructor starts with a + * synthesized `super` call. + */ + function transformConstructorParameters(constructor, hasSynthesizedSuper) { + // If the TypeScript transformer needed to synthesize a constructor for property + // initializers, it would have also added a synthetic `...args` parameter and + // `super` call. + // If this is the case, we do not include the synthetic `...args` parameter and + // will instead use the `arguments` object in ES5/3. + return ts.visitParameterList(constructor && !hasSynthesizedSuper ? constructor.parameters : undefined, visitor, context) + || []; + } + /** + * Transforms the body of a constructor declaration of a class. + * + * @param constructor The constructor for the class. + * @param node The node which contains the constructor. + * @param extendsClauseElement The expression for the class `extends` clause. + * @param hasSynthesizedSuper A value indicating whether the constructor starts with a + * synthesized `super` call. + */ + function transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper) { + var statements = []; + resumeLexicalEnvironment(); + var statementOffset = -1; + if (hasSynthesizedSuper) { + // If a super call has already been synthesized, + // we're going to assume that we should just transform everything after that. + // The assumption is that no prior step in the pipeline has added any prologue directives. + statementOffset = 0; + } + else if (constructor) { + statementOffset = ts.addStandardPrologue(statements, constructor.body.statements, /*ensureUseStrict*/ false); + } + if (constructor) { + addDefaultValueAssignmentsIfNeeded(statements, constructor); + addRestParameterIfNeeded(statements, constructor, hasSynthesizedSuper); + if (!hasSynthesizedSuper) { + // If no super call has been synthesized, emit custom prologue directives. + statementOffset = ts.addCustomPrologue(statements, constructor.body.statements, statementOffset, visitor); + } + ts.Debug.assert(statementOffset >= 0, "statementOffset not initialized correctly!"); + } + // determine whether the class is known syntactically to be a derived class (e.g. a + // class that extends a value that is not syntactically known to be `null`). + var isDerivedClass = !!extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 96 /* NullKeyword */; + var superCaptureStatus = declareOrCaptureOrReturnThisForConstructorIfNeeded(statements, constructor, isDerivedClass, hasSynthesizedSuper, statementOffset); + // The last statement expression was replaced. Skip it. + if (superCaptureStatus === 1 /* ReplaceSuperCapture */ || superCaptureStatus === 2 /* ReplaceWithReturn */) { + statementOffset++; + } + if (constructor) { + if (superCaptureStatus === 1 /* ReplaceSuperCapture */) { + hierarchyFacts |= 4096 /* ConstructorWithCapturedSuper */; + } + ts.addRange(statements, ts.visitNodes(constructor.body.statements, visitor, ts.isStatement, /*start*/ statementOffset)); + } + // Return `_this` unless we're sure enough that it would be pointless to add a return statement. + // If there's a constructor that we can tell returns in enough places, then we *do not* want to add a return. + if (isDerivedClass + && superCaptureStatus !== 2 /* ReplaceWithReturn */ + && !(constructor && isSufficientlyCoveredByReturnStatements(constructor.body))) { + statements.push(ts.createReturn(ts.createFileLevelUniqueName("_this"))); + } + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + if (constructor) { + prependCaptureNewTargetIfNeeded(statements, constructor, /*copyOnWrite*/ false); + } + var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), + /*location*/ constructor ? constructor.body.statements : node.members), + /*multiLine*/ true); + ts.setTextRange(block, constructor ? constructor.body : node); + if (!constructor) { + ts.setEmitFlags(block, 1536 /* NoComments */); + } + return block; + } + /** + * We want to try to avoid emitting a return statement in certain cases if a user already returned something. + * It would generate obviously dead code, so we'll try to make things a little bit prettier + * by doing a minimal check on whether some common patterns always explicitly return. + */ + function isSufficientlyCoveredByReturnStatements(statement) { + // A return statement is considered covered. + if (statement.kind === 230 /* ReturnStatement */) { + return true; + } + // An if-statement with two covered branches is covered. + else if (statement.kind === 222 /* IfStatement */) { + var ifStatement = statement; + if (ifStatement.elseStatement) { + return isSufficientlyCoveredByReturnStatements(ifStatement.thenStatement) && + isSufficientlyCoveredByReturnStatements(ifStatement.elseStatement); + } + } + // A block is covered if it has a last statement which is covered. + else if (statement.kind === 218 /* Block */) { + var lastStatement = ts.lastOrUndefined(statement.statements); + if (lastStatement && isSufficientlyCoveredByReturnStatements(lastStatement)) { + return true; + } + } + return false; + } + /** + * Declares a `_this` variable for derived classes and for when arrow functions capture `this`. + * + * @returns The new statement offset into the `statements` array. + */ + function declareOrCaptureOrReturnThisForConstructorIfNeeded(statements, ctor, isDerivedClass, hasSynthesizedSuper, statementOffset) { + // If this isn't a derived class, just capture 'this' for arrow functions if necessary. + if (!isDerivedClass) { + if (ctor) { + addCaptureThisForNodeIfNeeded(statements, ctor); + } + return 0 /* NoReplacement */; + } + // We must be here because the user didn't write a constructor + // but we needed to call 'super(...args)' anyway as per 14.5.14 of the ES2016 spec. + // If that's the case we can just immediately return the result of a 'super()' call. + if (!ctor) { + statements.push(ts.createReturn(createDefaultSuperCallOrThis())); + return 2 /* ReplaceWithReturn */; + } + // The constructor exists, but it and the 'super()' call it contains were generated + // for something like property initializers. + // Create a captured '_this' variable and assume it will subsequently be used. + if (hasSynthesizedSuper) { + captureThisForNode(statements, ctor, createDefaultSuperCallOrThis()); + enableSubstitutionsForCapturedThis(); + return 1 /* ReplaceSuperCapture */; + } + // Most of the time, a 'super' call will be the first real statement in a constructor body. + // In these cases, we'd like to transform these into a *single* statement instead of a declaration + // followed by an assignment statement for '_this'. For instance, if we emitted without an initializer, + // we'd get: + // + // var _this; + // _this = _super.call(...) || this; + // + // instead of + // + // var _this = _super.call(...) || this; + // + // Additionally, if the 'super()' call is the last statement, we should just avoid capturing + // entirely and immediately return the result like so: + // + // return _super.call(...) || this; + // + var firstStatement; + var superCallExpression; + var ctorStatements = ctor.body.statements; + if (statementOffset < ctorStatements.length) { + firstStatement = ctorStatements[statementOffset]; + if (firstStatement.kind === 221 /* ExpressionStatement */ && ts.isSuperCall(firstStatement.expression)) { + superCallExpression = visitImmediateSuperCallInBody(firstStatement.expression); + } + } + // Return the result if we have an immediate super() call on the last statement, + // but only if the constructor itself doesn't use 'this' elsewhere. + if (superCallExpression + && statementOffset === ctorStatements.length - 1 + && !(ctor.transformFlags & (8192 /* ContainsLexicalThis */ | 16384 /* ContainsCapturedLexicalThis */))) { + var returnStatement = ts.createReturn(superCallExpression); + if (superCallExpression.kind !== 204 /* BinaryExpression */ + || superCallExpression.left.kind !== 191 /* CallExpression */) { + ts.Debug.fail("Assumed generated super call would have form 'super.call(...) || this'."); + } + // Shift comments from the original super call to the return statement. + ts.setCommentRange(returnStatement, ts.getCommentRange(ts.setEmitFlags(superCallExpression.left, 1536 /* NoComments */))); + statements.push(returnStatement); + return 2 /* ReplaceWithReturn */; + } + // Perform the capture. + captureThisForNode(statements, ctor, superCallExpression || createActualThis()); + // If we're actually replacing the original statement, we need to signal this to the caller. + if (superCallExpression) { + return 1 /* ReplaceSuperCapture */; + } + return 0 /* NoReplacement */; + } + function createActualThis() { + return ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */); + } + function createDefaultSuperCallOrThis() { + return ts.createLogicalOr(ts.createLogicalAnd(ts.createStrictInequality(ts.createFileLevelUniqueName("_super"), ts.createNull()), ts.createFunctionApply(ts.createFileLevelUniqueName("_super"), createActualThis(), ts.createIdentifier("arguments"))), createActualThis()); + } + /** + * Visits a parameter declaration. + * + * @param node A ParameterDeclaration node. + */ + function visitParameter(node) { + if (node.dotDotDotToken) { + // rest parameters are elided + return undefined; + } + else if (ts.isBindingPattern(node.name)) { + // Binding patterns are converted into a generated name and are + // evaluated inside the function body. + return ts.setOriginalNode(ts.setTextRange(ts.createParameter( + /*decorators*/ undefined, + /*modifiers*/ undefined, + /*dotDotDotToken*/ undefined, ts.getGeneratedNameForNode(node), + /*questionToken*/ undefined, + /*type*/ undefined, + /*initializer*/ undefined), + /*location*/ node), + /*original*/ node); + } + else if (node.initializer) { + // Initializers are elided + return ts.setOriginalNode(ts.setTextRange(ts.createParameter( + /*decorators*/ undefined, + /*modifiers*/ undefined, + /*dotDotDotToken*/ undefined, node.name, + /*questionToken*/ undefined, + /*type*/ undefined, + /*initializer*/ undefined), + /*location*/ node), + /*original*/ node); + } + else { + return node; + } + } + /** + * Gets a value indicating whether we need to add default value assignments for a + * function-like node. + * + * @param node A function-like node. + */ + function shouldAddDefaultValueAssignments(node) { + return (node.transformFlags & 65536 /* ContainsDefaultValueAssignments */) !== 0; + } + /** + * Adds statements to the body of a function-like node if it contains parameters with + * binding patterns or initializers. + * + * @param statements The statements for the new function body. + * @param node A function-like node. + */ + function addDefaultValueAssignmentsIfNeeded(statements, node) { + if (!shouldAddDefaultValueAssignments(node)) { + return; + } + for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { + var parameter = _a[_i]; + var name = parameter.name, initializer = parameter.initializer, dotDotDotToken = parameter.dotDotDotToken; + // A rest parameter cannot have a binding pattern or an initializer, + // so let's just ignore it. + if (dotDotDotToken) { + continue; + } + if (ts.isBindingPattern(name)) { + addDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer); + } + else if (initializer) { + addDefaultValueAssignmentForInitializer(statements, parameter, name, initializer); + } + } + } + /** + * Adds statements to the body of a function-like node for parameters with binding patterns + * + * @param statements The statements for the new function body. + * @param parameter The parameter for the function. + * @param name The name of the parameter. + * @param initializer The initializer for the parameter. + */ + function addDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer) { + var temp = ts.getGeneratedNameForNode(parameter); + // In cases where a binding pattern is simply '[]' or '{}', + // we usually don't want to emit a var declaration; however, in the presence + // of an initializer, we must emit that expression to preserve side effects. + if (name.elements.length > 0) { + statements.push(ts.setEmitFlags(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList(ts.flattenDestructuringBinding(parameter, visitor, context, 0 /* All */, temp))), 1048576 /* CustomPrologue */)); + } + else if (initializer) { + statements.push(ts.setEmitFlags(ts.createExpressionStatement(ts.createAssignment(temp, ts.visitNode(initializer, visitor, ts.isExpression))), 1048576 /* CustomPrologue */)); + } + } + /** + * Adds statements to the body of a function-like node for parameters with initializers. + * + * @param statements The statements for the new function body. + * @param parameter The parameter for the function. + * @param name The name of the parameter. + * @param initializer The initializer for the parameter. + */ + function addDefaultValueAssignmentForInitializer(statements, parameter, name, initializer) { + initializer = ts.visitNode(initializer, visitor, ts.isExpression); + var statement = ts.createIf(ts.createTypeCheck(ts.getSynthesizedClone(name), "undefined"), ts.setEmitFlags(ts.setTextRange(ts.createBlock([ + ts.createExpressionStatement(ts.setEmitFlags(ts.setTextRange(ts.createAssignment(ts.setEmitFlags(ts.getMutableClone(name), 48 /* NoSourceMap */), ts.setEmitFlags(initializer, 48 /* NoSourceMap */ | ts.getEmitFlags(initializer) | 1536 /* NoComments */)), parameter), 1536 /* NoComments */)) + ]), parameter), 1 /* SingleLine */ | 32 /* NoTrailingSourceMap */ | 384 /* NoTokenSourceMaps */ | 1536 /* NoComments */)); + ts.startOnNewLine(statement); + ts.setTextRange(statement, parameter); + ts.setEmitFlags(statement, 384 /* NoTokenSourceMaps */ | 32 /* NoTrailingSourceMap */ | 1048576 /* CustomPrologue */ | 1536 /* NoComments */); + statements.push(statement); + } + /** + * Gets a value indicating whether we need to add statements to handle a rest parameter. + * + * @param node A ParameterDeclaration node. + * @param inConstructorWithSynthesizedSuper A value indicating whether the parameter is + * part of a constructor declaration with a + * synthesized call to `super` + */ + function shouldAddRestParameter(node, inConstructorWithSynthesizedSuper) { + return node && node.dotDotDotToken && node.name.kind === 72 /* Identifier */ && !inConstructorWithSynthesizedSuper; + } + /** + * Adds statements to the body of a function-like node if it contains a rest parameter. + * + * @param statements The statements for the new function body. + * @param node A function-like node. + * @param inConstructorWithSynthesizedSuper A value indicating whether the parameter is + * part of a constructor declaration with a + * synthesized call to `super` + */ + function addRestParameterIfNeeded(statements, node, inConstructorWithSynthesizedSuper) { + var parameter = ts.lastOrUndefined(node.parameters); + if (!shouldAddRestParameter(parameter, inConstructorWithSynthesizedSuper)) { + return; + } + // `declarationName` is the name of the local declaration for the parameter. + var declarationName = ts.getMutableClone(parameter.name); + ts.setEmitFlags(declarationName, 48 /* NoSourceMap */); + // `expressionName` is the name of the parameter used in expressions. + var expressionName = ts.getSynthesizedClone(parameter.name); + var restIndex = node.parameters.length - 1; + var temp = ts.createLoopVariable(); + // var param = []; + statements.push(ts.setEmitFlags(ts.setTextRange(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(declarationName, + /*type*/ undefined, ts.createArrayLiteral([])) + ])), + /*location*/ parameter), 1048576 /* CustomPrologue */)); + // for (var _i = restIndex; _i < arguments.length; _i++) { + // param[_i - restIndex] = arguments[_i]; + // } + var forStatement = ts.createFor(ts.setTextRange(ts.createVariableDeclarationList([ + ts.createVariableDeclaration(temp, /*type*/ undefined, ts.createLiteral(restIndex)) + ]), parameter), ts.setTextRange(ts.createLessThan(temp, ts.createPropertyAccess(ts.createIdentifier("arguments"), "length")), parameter), ts.setTextRange(ts.createPostfixIncrement(temp), parameter), ts.createBlock([ + ts.startOnNewLine(ts.setTextRange(ts.createExpressionStatement(ts.createAssignment(ts.createElementAccess(expressionName, restIndex === 0 + ? temp + : ts.createSubtract(temp, ts.createLiteral(restIndex))), ts.createElementAccess(ts.createIdentifier("arguments"), temp))), + /*location*/ parameter)) + ])); + ts.setEmitFlags(forStatement, 1048576 /* CustomPrologue */); + ts.startOnNewLine(forStatement); + statements.push(forStatement); + } + /** + * Adds a statement to capture the `this` of a function declaration if it is needed. + * + * @param statements The statements for the new function body. + * @param node A node. + */ + function addCaptureThisForNodeIfNeeded(statements, node) { + if (node.transformFlags & 16384 /* ContainsCapturedLexicalThis */ && node.kind !== 197 /* ArrowFunction */) { + captureThisForNode(statements, node, ts.createThis()); + } + } + function captureThisForNode(statements, node, initializer) { + enableSubstitutionsForCapturedThis(); + var captureThisStatement = ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(ts.createFileLevelUniqueName("_this"), + /*type*/ undefined, initializer) + ])); + ts.setEmitFlags(captureThisStatement, 1536 /* NoComments */ | 1048576 /* CustomPrologue */); + ts.setSourceMapRange(captureThisStatement, node); + statements.push(captureThisStatement); + } + function prependCaptureNewTargetIfNeeded(statements, node, copyOnWrite) { + if (hierarchyFacts & 16384 /* NewTarget */) { + var newTarget = void 0; + switch (node.kind) { + case 197 /* ArrowFunction */: + return statements; + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + // Methods and accessors cannot be constructors, so 'new.target' will + // always return 'undefined'. + newTarget = ts.createVoidZero(); + break; + case 157 /* Constructor */: + // Class constructors can only be called with `new`, so `this.constructor` + // should be relatively safe to use. + newTarget = ts.createPropertyAccess(ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */), "constructor"); + break; + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + // Functions can be called or constructed, and may have a `this` due to + // being a member or when calling an imported function via `other_1.f()`. + newTarget = ts.createConditional(ts.createLogicalAnd(ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */), ts.createBinary(ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */), 94 /* InstanceOfKeyword */, ts.getLocalName(node))), ts.createPropertyAccess(ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */), "constructor"), ts.createVoidZero()); + break; + default: + return ts.Debug.failBadSyntaxKind(node); + } + var captureNewTargetStatement = ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(ts.createFileLevelUniqueName("_newTarget"), + /*type*/ undefined, newTarget) + ])); + if (copyOnWrite) { + return [captureNewTargetStatement].concat(statements); + } + statements.unshift(captureNewTargetStatement); + } + return statements; + } + /** + * Adds statements to the class body function for a class to define the members of the + * class. + * + * @param statements The statements for the class body function. + * @param node The ClassExpression or ClassDeclaration node. + */ + function addClassMembers(statements, node) { + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + switch (member.kind) { + case 217 /* SemicolonClassElement */: + statements.push(transformSemicolonClassElementToStatement(member)); + break; + case 156 /* MethodDeclaration */: + statements.push(transformClassMethodDeclarationToStatement(getClassMemberPrefix(node, member), member, node)); + break; + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + var accessors = ts.getAllAccessorDeclarations(node.members, member); + if (member === accessors.firstAccessor) { + statements.push(transformAccessorsToStatement(getClassMemberPrefix(node, member), accessors, node)); + } + break; + case 157 /* Constructor */: + // Constructors are handled in visitClassExpression/visitClassDeclaration + break; + default: + ts.Debug.failBadSyntaxKind(node); + break; + } + } + } + /** + * Transforms a SemicolonClassElement into a statement for a class body function. + * + * @param member The SemicolonClassElement node. + */ + function transformSemicolonClassElementToStatement(member) { + return ts.setTextRange(ts.createEmptyStatement(), member); + } + /** + * Transforms a MethodDeclaration into a statement for a class body function. + * + * @param receiver The receiver for the member. + * @param member The MethodDeclaration node. + */ + function transformClassMethodDeclarationToStatement(receiver, member, container) { + var ancestorFacts = enterSubtree(0 /* None */, 0 /* None */); + var commentRange = ts.getCommentRange(member); + var sourceMapRange = ts.getSourceMapRange(member); + var memberName = ts.createMemberAccessForPropertyName(receiver, ts.visitNode(member.name, visitor, ts.isPropertyName), /*location*/ member.name); + var memberFunction = transformFunctionLikeToExpression(member, /*location*/ member, /*name*/ undefined, container); + ts.setEmitFlags(memberFunction, 1536 /* NoComments */); + ts.setSourceMapRange(memberFunction, sourceMapRange); + var statement = ts.setTextRange(ts.createExpressionStatement(ts.createAssignment(memberName, memberFunction)), + /*location*/ member); + ts.setOriginalNode(statement, member); + ts.setCommentRange(statement, commentRange); + // The location for the statement is used to emit comments only. + // No source map should be emitted for this statement to align with the + // old emitter. + ts.setEmitFlags(statement, 48 /* NoSourceMap */); + exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, hierarchyFacts & 49152 /* PropagateNewTargetMask */ ? 16384 /* NewTarget */ : 0 /* None */); + return statement; + } + /** + * Transforms a set of related of get/set accessors into a statement for a class body function. + * + * @param receiver The receiver for the member. + * @param accessors The set of related get/set accessors. + */ + function transformAccessorsToStatement(receiver, accessors, container) { + var statement = ts.createExpressionStatement(transformAccessorsToExpression(receiver, accessors, container, /*startsOnNewLine*/ false)); + // The location for the statement is used to emit source maps only. + // No comments should be emitted for this statement to align with the + // old emitter. + ts.setEmitFlags(statement, 1536 /* NoComments */); + ts.setSourceMapRange(statement, ts.getSourceMapRange(accessors.firstAccessor)); + return statement; + } + /** + * Transforms a set of related get/set accessors into an expression for either a class + * body function or an ObjectLiteralExpression with computed properties. + * + * @param receiver The receiver for the member. + */ + function transformAccessorsToExpression(receiver, _a, container, startsOnNewLine) { + var firstAccessor = _a.firstAccessor, getAccessor = _a.getAccessor, setAccessor = _a.setAccessor; + var ancestorFacts = enterSubtree(0 /* None */, 0 /* None */); + // To align with source maps in the old emitter, the receiver and property name + // arguments are both mapped contiguously to the accessor name. + var target = ts.getMutableClone(receiver); + ts.setEmitFlags(target, 1536 /* NoComments */ | 32 /* NoTrailingSourceMap */); + ts.setSourceMapRange(target, firstAccessor.name); // TODO: GH#18217 + var propertyName = ts.createExpressionForPropertyName(ts.visitNode(firstAccessor.name, visitor, ts.isPropertyName)); + ts.setEmitFlags(propertyName, 1536 /* NoComments */ | 16 /* NoLeadingSourceMap */); + ts.setSourceMapRange(propertyName, firstAccessor.name); + var properties = []; + if (getAccessor) { + var getterFunction = transformFunctionLikeToExpression(getAccessor, /*location*/ undefined, /*name*/ undefined, container); + ts.setSourceMapRange(getterFunction, ts.getSourceMapRange(getAccessor)); + ts.setEmitFlags(getterFunction, 512 /* NoLeadingComments */); + var getter = ts.createPropertyAssignment("get", getterFunction); + ts.setCommentRange(getter, ts.getCommentRange(getAccessor)); + properties.push(getter); + } + if (setAccessor) { + var setterFunction = transformFunctionLikeToExpression(setAccessor, /*location*/ undefined, /*name*/ undefined, container); + ts.setSourceMapRange(setterFunction, ts.getSourceMapRange(setAccessor)); + ts.setEmitFlags(setterFunction, 512 /* NoLeadingComments */); + var setter = ts.createPropertyAssignment("set", setterFunction); + ts.setCommentRange(setter, ts.getCommentRange(setAccessor)); + properties.push(setter); + } + properties.push(ts.createPropertyAssignment("enumerable", ts.createTrue()), ts.createPropertyAssignment("configurable", ts.createTrue())); + var call = ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"), + /*typeArguments*/ undefined, [ + target, + propertyName, + ts.createObjectLiteral(properties, /*multiLine*/ true) + ]); + if (startsOnNewLine) { + ts.startOnNewLine(call); + } + exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, hierarchyFacts & 49152 /* PropagateNewTargetMask */ ? 16384 /* NewTarget */ : 0 /* None */); + return call; + } + /** + * Visits an ArrowFunction and transforms it into a FunctionExpression. + * + * @param node An ArrowFunction node. + */ + function visitArrowFunction(node) { + if (node.transformFlags & 8192 /* ContainsLexicalThis */) { + enableSubstitutionsForCapturedThis(); + } + var savedConvertedLoopState = convertedLoopState; + convertedLoopState = undefined; + var ancestorFacts = enterSubtree(16256 /* ArrowFunctionExcludes */, 66 /* ArrowFunctionIncludes */); + var func = ts.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, transformFunctionBody(node)); + ts.setTextRange(func, node); + ts.setOriginalNode(func, node); + ts.setEmitFlags(func, 8 /* CapturesThis */); + exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */); + convertedLoopState = savedConvertedLoopState; + return func; + } + /** + * Visits a FunctionExpression node. + * + * @param node a FunctionExpression node. + */ + function visitFunctionExpression(node) { + var ancestorFacts = ts.getEmitFlags(node) & 262144 /* AsyncFunctionBody */ + ? enterSubtree(16278 /* AsyncFunctionBodyExcludes */, 69 /* AsyncFunctionBodyIncludes */) + : enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */); + var savedConvertedLoopState = convertedLoopState; + convertedLoopState = undefined; + var parameters = ts.visitParameterList(node.parameters, visitor, context); + var body = node.transformFlags & 64 /* ES2015 */ + ? transformFunctionBody(node) + : visitFunctionBodyDownLevel(node); + var name = hierarchyFacts & 16384 /* NewTarget */ + ? ts.getLocalName(node) + : node.name; + exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, 0 /* None */); + convertedLoopState = savedConvertedLoopState; + return ts.updateFunctionExpression(node, + /*modifiers*/ undefined, node.asteriskToken, name, + /*typeParameters*/ undefined, parameters, + /*type*/ undefined, body); + } + /** + * Visits a FunctionDeclaration node. + * + * @param node a FunctionDeclaration node. + */ + function visitFunctionDeclaration(node) { + var savedConvertedLoopState = convertedLoopState; + convertedLoopState = undefined; + var ancestorFacts = enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */); + var parameters = ts.visitParameterList(node.parameters, visitor, context); + var body = node.transformFlags & 64 /* ES2015 */ + ? transformFunctionBody(node) + : visitFunctionBodyDownLevel(node); + var name = hierarchyFacts & 16384 /* NewTarget */ + ? ts.getLocalName(node) + : node.name; + exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, 0 /* None */); + convertedLoopState = savedConvertedLoopState; + return ts.updateFunctionDeclaration(node, + /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, name, + /*typeParameters*/ undefined, parameters, + /*type*/ undefined, body); + } + /** + * Transforms a function-like node into a FunctionExpression. + * + * @param node The function-like node to transform. + * @param location The source-map location for the new FunctionExpression. + * @param name The name of the new FunctionExpression. + */ + function transformFunctionLikeToExpression(node, location, name, container) { + var savedConvertedLoopState = convertedLoopState; + convertedLoopState = undefined; + var ancestorFacts = container && ts.isClassLike(container) && !ts.hasModifier(node, 32 /* Static */) + ? enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */ | 8 /* NonStaticClassElement */) + : enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */); + var parameters = ts.visitParameterList(node.parameters, visitor, context); + var body = transformFunctionBody(node); + if (hierarchyFacts & 16384 /* NewTarget */ && !name && (node.kind === 239 /* FunctionDeclaration */ || node.kind === 196 /* FunctionExpression */)) { + name = ts.getGeneratedNameForNode(node); + } + exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, 0 /* None */); + convertedLoopState = savedConvertedLoopState; + return ts.setOriginalNode(ts.setTextRange(ts.createFunctionExpression( + /*modifiers*/ undefined, node.asteriskToken, name, + /*typeParameters*/ undefined, parameters, + /*type*/ undefined, body), location), + /*original*/ node); + } + /** + * Transforms the body of a function-like node. + * + * @param node A function-like node. + */ + function transformFunctionBody(node) { + var multiLine = false; // indicates whether the block *must* be emitted as multiple lines + var singleLine = false; // indicates whether the block *may* be emitted as a single line + var statementsLocation; + var closeBraceLocation; + var leadingStatements = []; + var statements = []; + var body = node.body; + var statementOffset; + resumeLexicalEnvironment(); + if (ts.isBlock(body)) { + // ensureUseStrict is false because no new prologue-directive should be added. + // addStandardPrologue will put already-existing directives at the beginning of the target statement-array + statementOffset = ts.addStandardPrologue(leadingStatements, body.statements, /*ensureUseStrict*/ false); + } + addCaptureThisForNodeIfNeeded(leadingStatements, node); + addDefaultValueAssignmentsIfNeeded(leadingStatements, node); + addRestParameterIfNeeded(leadingStatements, node, /*inConstructorWithSynthesizedSuper*/ false); + if (ts.isBlock(body)) { + // addCustomPrologue puts already-existing directives at the beginning of the target statement-array + statementOffset = ts.addCustomPrologue(leadingStatements, body.statements, statementOffset, visitor); + statementsLocation = body.statements; + ts.addRange(statements, ts.visitNodes(body.statements, visitor, ts.isStatement, statementOffset)); + // If the original body was a multi-line block, this must be a multi-line block. + if (!multiLine && body.multiLine) { + multiLine = true; + } + } + else { + ts.Debug.assert(node.kind === 197 /* ArrowFunction */); + // To align with the old emitter, we use a synthetic end position on the location + // for the statement list we synthesize when we down-level an arrow function with + // an expression function body. This prevents both comments and source maps from + // being emitted for the end position only. + statementsLocation = ts.moveRangeEnd(body, -1); + var equalsGreaterThanToken = node.equalsGreaterThanToken; + if (!ts.nodeIsSynthesized(equalsGreaterThanToken) && !ts.nodeIsSynthesized(body)) { + if (ts.rangeEndIsOnSameLineAsRangeStart(equalsGreaterThanToken, body, currentSourceFile)) { + singleLine = true; + } + else { + multiLine = true; + } + } + var expression = ts.visitNode(body, visitor, ts.isExpression); + var returnStatement = ts.createReturn(expression); + ts.setTextRange(returnStatement, body); + ts.moveSyntheticComments(returnStatement, body); + ts.setEmitFlags(returnStatement, 384 /* NoTokenSourceMaps */ | 32 /* NoTrailingSourceMap */ | 1024 /* NoTrailingComments */); + statements.push(returnStatement); + // To align with the source map emit for the old emitter, we set a custom + // source map location for the close brace. + closeBraceLocation = body; + } + var lexicalEnvironment = context.endLexicalEnvironment(); + ts.addStatementsAfterPrologue(statements, lexicalEnvironment); + prependCaptureNewTargetIfNeeded(statements, node, /*copyOnWrite*/ false); + // If we added any final generated statements, this must be a multi-line block + if (ts.some(leadingStatements) || ts.some(lexicalEnvironment)) { + multiLine = true; + } + var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(leadingStatements.concat(statements)), statementsLocation), multiLine); + ts.setTextRange(block, node.body); + if (!multiLine && singleLine) { + ts.setEmitFlags(block, 1 /* SingleLine */); + } + if (closeBraceLocation) { + ts.setTokenSourceMapRange(block, 19 /* CloseBraceToken */, closeBraceLocation); + } + ts.setOriginalNode(block, node.body); + return block; + } + function visitFunctionBodyDownLevel(node) { + var updated = ts.visitFunctionBody(node.body, functionBodyVisitor, context); + return ts.updateBlock(updated, ts.setTextRange(ts.createNodeArray(prependCaptureNewTargetIfNeeded(updated.statements, node, /*copyOnWrite*/ true)), + /*location*/ updated.statements)); + } + function visitBlock(node, isFunctionBody) { + if (isFunctionBody) { + // A function body is not a block scope. + return ts.visitEachChild(node, visitor, context); + } + var ancestorFacts = hierarchyFacts & 256 /* IterationStatement */ + ? enterSubtree(4032 /* IterationStatementBlockExcludes */, 512 /* IterationStatementBlockIncludes */) + : enterSubtree(3904 /* BlockExcludes */, 128 /* BlockIncludes */); + var updated = ts.visitEachChild(node, visitor, context); + exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */); + return updated; + } + /** + * Visits an ExpressionStatement that contains a destructuring assignment. + * + * @param node An ExpressionStatement node. + */ + function visitExpressionStatement(node) { + // If we are here it is most likely because our expression is a destructuring assignment. + switch (node.expression.kind) { + case 195 /* ParenthesizedExpression */: + return ts.updateExpressionStatement(node, visitParenthesizedExpression(node.expression, /*needsDestructuringValue*/ false)); + case 204 /* BinaryExpression */: + return ts.updateExpressionStatement(node, visitBinaryExpression(node.expression, /*needsDestructuringValue*/ false)); + } + return ts.visitEachChild(node, visitor, context); + } + /** + * Visits a ParenthesizedExpression that may contain a destructuring assignment. + * + * @param node A ParenthesizedExpression node. + * @param needsDestructuringValue A value indicating whether we need to hold onto the rhs + * of a destructuring assignment. + */ + function visitParenthesizedExpression(node, needsDestructuringValue) { + // If we are here it is most likely because our expression is a destructuring assignment. + if (!needsDestructuringValue) { + // By default we always emit the RHS at the end of a flattened destructuring + // expression. If we are in a state where we do not need the destructuring value, + // we pass that information along to the children that care about it. + switch (node.expression.kind) { + case 195 /* ParenthesizedExpression */: + return ts.updateParen(node, visitParenthesizedExpression(node.expression, /*needsDestructuringValue*/ false)); + case 204 /* BinaryExpression */: + return ts.updateParen(node, visitBinaryExpression(node.expression, /*needsDestructuringValue*/ false)); + } + } + return ts.visitEachChild(node, visitor, context); + } + /** + * Visits a BinaryExpression that contains a destructuring assignment. + * + * @param node A BinaryExpression node. + * @param needsDestructuringValue A value indicating whether we need to hold onto the rhs + * of a destructuring assignment. + */ + function visitBinaryExpression(node, needsDestructuringValue) { + // If we are here it is because this is a destructuring assignment. + if (ts.isDestructuringAssignment(node)) { + return ts.flattenDestructuringAssignment(node, visitor, context, 0 /* All */, needsDestructuringValue); + } + return ts.visitEachChild(node, visitor, context); + } + function visitVariableStatement(node) { + var ancestorFacts = enterSubtree(0 /* None */, ts.hasModifier(node, 1 /* Export */) ? 32 /* ExportedVariableStatement */ : 0 /* None */); + var updated; + if (convertedLoopState && (node.declarationList.flags & 3 /* BlockScoped */) === 0) { + // we are inside a converted loop - hoist variable declarations + var assignments = void 0; + for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + hoistVariableDeclarationDeclaredInConvertedLoop(convertedLoopState, decl); + if (decl.initializer) { + var assignment = void 0; + if (ts.isBindingPattern(decl.name)) { + assignment = ts.flattenDestructuringAssignment(decl, visitor, context, 0 /* All */); + } + else { + assignment = ts.createBinary(decl.name, 59 /* EqualsToken */, ts.visitNode(decl.initializer, visitor, ts.isExpression)); + ts.setTextRange(assignment, decl); + } + assignments = ts.append(assignments, assignment); + } + } + if (assignments) { + updated = ts.setTextRange(ts.createExpressionStatement(ts.inlineExpressions(assignments)), node); + } + else { + // none of declarations has initializer - the entire variable statement can be deleted + updated = undefined; + } + } + else { + updated = ts.visitEachChild(node, visitor, context); + } + exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */); + return updated; + } + /** + * Visits a VariableDeclarationList that is block scoped (e.g. `let` or `const`). + * + * @param node A VariableDeclarationList node. + */ + function visitVariableDeclarationList(node) { + if (node.transformFlags & 64 /* ES2015 */) { + if (node.flags & 3 /* BlockScoped */) { + enableSubstitutionsForBlockScopedBindings(); + } + var declarations = ts.flatMap(node.declarations, node.flags & 1 /* Let */ + ? visitVariableDeclarationInLetDeclarationList + : visitVariableDeclaration); + var declarationList = ts.createVariableDeclarationList(declarations); + ts.setOriginalNode(declarationList, node); + ts.setTextRange(declarationList, node); + ts.setCommentRange(declarationList, node); + // If the first or last declaration is a binding pattern, we need to modify + // the source map range for the declaration list. + if (node.transformFlags & 2097152 /* ContainsBindingPattern */ + && (ts.isBindingPattern(node.declarations[0].name) || ts.isBindingPattern(ts.last(node.declarations).name))) { + ts.setSourceMapRange(declarationList, getRangeUnion(declarations)); + } + return declarationList; + } + return ts.visitEachChild(node, visitor, context); + } + function getRangeUnion(declarations) { + // declarations may not be sorted by position. + // pos should be the minimum* position over all nodes (that's not -1), end should be the maximum end over all nodes. + var pos = -1, end = -1; + for (var _i = 0, declarations_10 = declarations; _i < declarations_10.length; _i++) { + var node = declarations_10[_i]; + pos = pos === -1 ? node.pos : node.pos === -1 ? pos : Math.min(pos, node.pos); + end = Math.max(end, node.end); + } + return ts.createRange(pos, end); + } + /** + * Gets a value indicating whether we should emit an explicit initializer for a variable + * declaration in a `let` declaration list. + * + * @param node A VariableDeclaration node. + */ + function shouldEmitExplicitInitializerForLetDeclaration(node) { + // Nested let bindings might need to be initialized explicitly to preserve + // ES6 semantic: + // + // { let x = 1; } + // { let x; } // x here should be undefined. not 1 + // + // Top level bindings never collide with anything and thus don't require + // explicit initialization. As for nested let bindings there are two cases: + // + // - Nested let bindings that were not renamed definitely should be + // initialized explicitly: + // + // { let x = 1; } + // { let x; if (some-condition) { x = 1}; if (x) { /*1*/ } } + // + // Without explicit initialization code in /*1*/ can be executed even if + // some-condition is evaluated to false. + // + // - Renaming introduces fresh name that should not collide with any + // existing names, however renamed bindings sometimes also should be + // explicitly initialized. One particular case: non-captured binding + // declared inside loop body (but not in loop initializer): + // + // let x; + // for (;;) { + // let x; + // } + // + // In downlevel codegen inner 'x' will be renamed so it won't collide + // with outer 'x' however it will should be reset on every iteration as + // if it was declared anew. + // + // * Why non-captured binding? + // - Because if loop contains block scoped binding captured in some + // function then loop body will be rewritten to have a fresh scope + // on every iteration so everything will just work. + // + // * Why loop initializer is excluded? + // - Since we've introduced a fresh name it already will be undefined. + var flags = resolver.getNodeCheckFlags(node); + var isCapturedInFunction = flags & 262144 /* CapturedBlockScopedBinding */; + var isDeclaredInLoop = flags & 524288 /* BlockScopedBindingInLoop */; + var emittedAsTopLevel = (hierarchyFacts & 64 /* TopLevel */) !== 0 + || (isCapturedInFunction + && isDeclaredInLoop + && (hierarchyFacts & 512 /* IterationStatementBlock */) !== 0); + var emitExplicitInitializer = !emittedAsTopLevel + && (hierarchyFacts & 2048 /* ForInOrForOfStatement */) === 0 + && (!resolver.isDeclarationWithCollidingName(node) + || (isDeclaredInLoop + && !isCapturedInFunction + && (hierarchyFacts & (1024 /* ForStatement */ | 2048 /* ForInOrForOfStatement */)) === 0)); + return emitExplicitInitializer; + } + /** + * Visits a VariableDeclaration in a `let` declaration list. + * + * @param node A VariableDeclaration node. + */ + function visitVariableDeclarationInLetDeclarationList(node) { + // For binding pattern names that lack initializers there is no point to emit + // explicit initializer since downlevel codegen for destructuring will fail + // in the absence of initializer so all binding elements will say uninitialized + var name = node.name; + if (ts.isBindingPattern(name)) { + return visitVariableDeclaration(node); + } + if (!node.initializer && shouldEmitExplicitInitializerForLetDeclaration(node)) { + var clone_2 = ts.getMutableClone(node); + clone_2.initializer = ts.createVoidZero(); + return clone_2; + } + return ts.visitEachChild(node, visitor, context); + } + /** + * Visits a VariableDeclaration node with a binding pattern. + * + * @param node A VariableDeclaration node. + */ + function visitVariableDeclaration(node) { + var ancestorFacts = enterSubtree(32 /* ExportedVariableStatement */, 0 /* None */); + var updated; + if (ts.isBindingPattern(node.name)) { + updated = ts.flattenDestructuringBinding(node, visitor, context, 0 /* All */, + /*value*/ undefined, (ancestorFacts & 32 /* ExportedVariableStatement */) !== 0); + } + else { + updated = ts.visitEachChild(node, visitor, context); + } + exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */); + return updated; + } + function recordLabel(node) { + convertedLoopState.labels.set(ts.idText(node.label), true); + } + function resetLabel(node) { + convertedLoopState.labels.set(ts.idText(node.label), false); + } + function visitLabeledStatement(node) { + if (convertedLoopState && !convertedLoopState.labels) { + convertedLoopState.labels = ts.createMap(); + } + var statement = ts.unwrapInnermostStatementOfLabel(node, convertedLoopState && recordLabel); + return ts.isIterationStatement(statement, /*lookInLabeledStatements*/ false) + ? visitIterationStatement(statement, /*outermostLabeledStatement*/ node) + : ts.restoreEnclosingLabel(ts.visitNode(statement, visitor, ts.isStatement, ts.liftToBlock), node, convertedLoopState && resetLabel); + } + function visitIterationStatement(node, outermostLabeledStatement) { + switch (node.kind) { + case 223 /* DoStatement */: + case 224 /* WhileStatement */: + return visitDoOrWhileStatement(node, outermostLabeledStatement); + case 225 /* ForStatement */: + return visitForStatement(node, outermostLabeledStatement); + case 226 /* ForInStatement */: + return visitForInStatement(node, outermostLabeledStatement); + case 227 /* ForOfStatement */: + return visitForOfStatement(node, outermostLabeledStatement); + } + } + function visitIterationStatementWithFacts(excludeFacts, includeFacts, node, outermostLabeledStatement, convert) { + var ancestorFacts = enterSubtree(excludeFacts, includeFacts); + var updated = convertIterationStatementBodyIfNecessary(node, outermostLabeledStatement, convert); + exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */); + return updated; + } + function visitDoOrWhileStatement(node, outermostLabeledStatement) { + return visitIterationStatementWithFacts(0 /* DoOrWhileStatementExcludes */, 256 /* DoOrWhileStatementIncludes */, node, outermostLabeledStatement); + } + function visitForStatement(node, outermostLabeledStatement) { + return visitIterationStatementWithFacts(3008 /* ForStatementExcludes */, 1280 /* ForStatementIncludes */, node, outermostLabeledStatement); + } + function visitForInStatement(node, outermostLabeledStatement) { + return visitIterationStatementWithFacts(1984 /* ForInOrForOfStatementExcludes */, 2304 /* ForInOrForOfStatementIncludes */, node, outermostLabeledStatement); + } + function visitForOfStatement(node, outermostLabeledStatement) { + return visitIterationStatementWithFacts(1984 /* ForInOrForOfStatementExcludes */, 2304 /* ForInOrForOfStatementIncludes */, node, outermostLabeledStatement, compilerOptions.downlevelIteration ? convertForOfStatementForIterable : convertForOfStatementForArray); + } + function convertForOfStatementHead(node, boundValue, convertedLoopBodyStatements) { + var statements = []; + var initializer = node.initializer; + if (ts.isVariableDeclarationList(initializer)) { + if (node.initializer.flags & 3 /* BlockScoped */) { + enableSubstitutionsForBlockScopedBindings(); + } + var firstOriginalDeclaration = ts.firstOrUndefined(initializer.declarations); + if (firstOriginalDeclaration && ts.isBindingPattern(firstOriginalDeclaration.name)) { + // This works whether the declaration is a var, let, or const. + // It will use rhsIterationValue _a[_i] as the initializer. + var declarations = ts.flattenDestructuringBinding(firstOriginalDeclaration, visitor, context, 0 /* All */, boundValue); + var declarationList = ts.setTextRange(ts.createVariableDeclarationList(declarations), node.initializer); + ts.setOriginalNode(declarationList, node.initializer); + // Adjust the source map range for the first declaration to align with the old + // emitter. + ts.setSourceMapRange(declarationList, ts.createRange(declarations[0].pos, ts.last(declarations).end)); + statements.push(ts.createVariableStatement( + /*modifiers*/ undefined, declarationList)); + } + else { + // The following call does not include the initializer, so we have + // to emit it separately. + statements.push(ts.setTextRange(ts.createVariableStatement( + /*modifiers*/ undefined, ts.setOriginalNode(ts.setTextRange(ts.createVariableDeclarationList([ + ts.createVariableDeclaration(firstOriginalDeclaration ? firstOriginalDeclaration.name : ts.createTempVariable(/*recordTempVariable*/ undefined), + /*type*/ undefined, boundValue) + ]), ts.moveRangePos(initializer, -1)), initializer)), ts.moveRangeEnd(initializer, -1))); + } + } + else { + // Initializer is an expression. Emit the expression in the body, so that it's + // evaluated on every iteration. + var assignment = ts.createAssignment(initializer, boundValue); + if (ts.isDestructuringAssignment(assignment)) { + ts.aggregateTransformFlags(assignment); + statements.push(ts.createExpressionStatement(visitBinaryExpression(assignment, /*needsDestructuringValue*/ false))); + } + else { + assignment.end = initializer.end; + statements.push(ts.setTextRange(ts.createExpressionStatement(ts.visitNode(assignment, visitor, ts.isExpression)), ts.moveRangeEnd(initializer, -1))); + } + } + if (convertedLoopBodyStatements) { + return createSyntheticBlockForConvertedStatements(ts.addRange(statements, convertedLoopBodyStatements)); + } + else { + var statement = ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock); + if (ts.isBlock(statement)) { + return ts.updateBlock(statement, ts.setTextRange(ts.createNodeArray(ts.concatenate(statements, statement.statements)), statement.statements)); + } + else { + statements.push(statement); + return createSyntheticBlockForConvertedStatements(statements); + } + } + } + function createSyntheticBlockForConvertedStatements(statements) { + return ts.setEmitFlags(ts.createBlock(ts.createNodeArray(statements), + /*multiLine*/ true), 48 /* NoSourceMap */ | 384 /* NoTokenSourceMaps */); + } + function convertForOfStatementForArray(node, outermostLabeledStatement, convertedLoopBodyStatements) { + // The following ES6 code: + // + // for (let v of expr) { } + // + // should be emitted as + // + // for (var _i = 0, _a = expr; _i < _a.length; _i++) { + // var v = _a[_i]; + // } + // + // where _a and _i are temps emitted to capture the RHS and the counter, + // respectively. + // When the left hand side is an expression instead of a let declaration, + // the "let v" is not emitted. + // When the left hand side is a let/const, the v is renamed if there is + // another v in scope. + // Note that all assignments to the LHS are emitted in the body, including + // all destructuring. + // Note also that because an extra statement is needed to assign to the LHS, + // for-of bodies are always emitted as blocks. + var expression = ts.visitNode(node.expression, visitor, ts.isExpression); + // In the case where the user wrote an identifier as the RHS, like this: + // + // for (let v of arr) { } + // + // we don't want to emit a temporary variable for the RHS, just use it directly. + var counter = ts.createLoopVariable(); + var rhsReference = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(expression) : ts.createTempVariable(/*recordTempVariable*/ undefined); + // The old emitter does not emit source maps for the expression + ts.setEmitFlags(expression, 48 /* NoSourceMap */ | ts.getEmitFlags(expression)); + var forStatement = ts.setTextRange(ts.createFor( + /*initializer*/ ts.setEmitFlags(ts.setTextRange(ts.createVariableDeclarationList([ + ts.setTextRange(ts.createVariableDeclaration(counter, /*type*/ undefined, ts.createLiteral(0)), ts.moveRangePos(node.expression, -1)), + ts.setTextRange(ts.createVariableDeclaration(rhsReference, /*type*/ undefined, expression), node.expression) + ]), node.expression), 2097152 /* NoHoisting */), + /*condition*/ ts.setTextRange(ts.createLessThan(counter, ts.createPropertyAccess(rhsReference, "length")), node.expression), + /*incrementor*/ ts.setTextRange(ts.createPostfixIncrement(counter), node.expression), + /*statement*/ convertForOfStatementHead(node, ts.createElementAccess(rhsReference, counter), convertedLoopBodyStatements)), + /*location*/ node); + // Disable trailing source maps for the OpenParenToken to align source map emit with the old emitter. + ts.setEmitFlags(forStatement, 256 /* NoTokenTrailingSourceMaps */); + ts.setTextRange(forStatement, node); + return ts.restoreEnclosingLabel(forStatement, outermostLabeledStatement, convertedLoopState && resetLabel); + } + function convertForOfStatementForIterable(node, outermostLabeledStatement, convertedLoopBodyStatements) { + var expression = ts.visitNode(node.expression, visitor, ts.isExpression); + var iterator = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(expression) : ts.createTempVariable(/*recordTempVariable*/ undefined); + var result = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(iterator) : ts.createTempVariable(/*recordTempVariable*/ undefined); + var errorRecord = ts.createUniqueName("e"); + var catchVariable = ts.getGeneratedNameForNode(errorRecord); + var returnMethod = ts.createTempVariable(/*recordTempVariable*/ undefined); + var values = ts.createValuesHelper(context, expression, node.expression); + var next = ts.createCall(ts.createPropertyAccess(iterator, "next"), /*typeArguments*/ undefined, []); + hoistVariableDeclaration(errorRecord); + hoistVariableDeclaration(returnMethod); + var forStatement = ts.setEmitFlags(ts.setTextRange(ts.createFor( + /*initializer*/ ts.setEmitFlags(ts.setTextRange(ts.createVariableDeclarationList([ + ts.setTextRange(ts.createVariableDeclaration(iterator, /*type*/ undefined, values), node.expression), + ts.createVariableDeclaration(result, /*type*/ undefined, next) + ]), node.expression), 2097152 /* NoHoisting */), + /*condition*/ ts.createLogicalNot(ts.createPropertyAccess(result, "done")), + /*incrementor*/ ts.createAssignment(result, next), + /*statement*/ convertForOfStatementHead(node, ts.createPropertyAccess(result, "value"), convertedLoopBodyStatements)), + /*location*/ node), 256 /* NoTokenTrailingSourceMaps */); + return ts.createTry(ts.createBlock([ + ts.restoreEnclosingLabel(forStatement, outermostLabeledStatement, convertedLoopState && resetLabel) + ]), ts.createCatchClause(ts.createVariableDeclaration(catchVariable), ts.setEmitFlags(ts.createBlock([ + ts.createExpressionStatement(ts.createAssignment(errorRecord, ts.createObjectLiteral([ + ts.createPropertyAssignment("error", catchVariable) + ]))) + ]), 1 /* SingleLine */)), ts.createBlock([ + ts.createTry( + /*tryBlock*/ ts.createBlock([ + ts.setEmitFlags(ts.createIf(ts.createLogicalAnd(ts.createLogicalAnd(result, ts.createLogicalNot(ts.createPropertyAccess(result, "done"))), ts.createAssignment(returnMethod, ts.createPropertyAccess(iterator, "return"))), ts.createExpressionStatement(ts.createFunctionCall(returnMethod, iterator, []))), 1 /* SingleLine */), + ]), + /*catchClause*/ undefined, + /*finallyBlock*/ ts.setEmitFlags(ts.createBlock([ + ts.setEmitFlags(ts.createIf(errorRecord, ts.createThrow(ts.createPropertyAccess(errorRecord, "error"))), 1 /* SingleLine */) + ]), 1 /* SingleLine */)) + ])); + } + /** + * Visits an ObjectLiteralExpression with computed property names. + * + * @param node An ObjectLiteralExpression node. + */ + function visitObjectLiteralExpression(node) { + // We are here because a ComputedPropertyName was used somewhere in the expression. + var properties = node.properties; + var numProperties = properties.length; + // Find the first computed property. + // Everything until that point can be emitted as part of the initial object literal. + var numInitialProperties = numProperties; + var numInitialPropertiesWithoutYield = numProperties; + for (var i = 0; i < numProperties; i++) { + var property = properties[i]; + if ((property.transformFlags & 4194304 /* ContainsYield */ && hierarchyFacts & 4 /* AsyncFunctionBody */) + && i < numInitialPropertiesWithoutYield) { + numInitialPropertiesWithoutYield = i; + } + if (property.name.kind === 149 /* ComputedPropertyName */) { + numInitialProperties = i; + break; + } + } + if (numInitialProperties !== numProperties) { + if (numInitialPropertiesWithoutYield < numInitialProperties) { + numInitialProperties = numInitialPropertiesWithoutYield; + } + // For computed properties, we need to create a unique handle to the object + // literal so we can modify it without risking internal assignments tainting the object. + var temp = ts.createTempVariable(hoistVariableDeclaration); + // Write out the first non-computed properties, then emit the rest through indexing on the temp variable. + var expressions = []; + var assignment = ts.createAssignment(temp, ts.setEmitFlags(ts.createObjectLiteral(ts.visitNodes(properties, visitor, ts.isObjectLiteralElementLike, 0, numInitialProperties), node.multiLine), 65536 /* Indented */)); + if (node.multiLine) { + ts.startOnNewLine(assignment); + } + expressions.push(assignment); + addObjectLiteralMembers(expressions, node, temp, numInitialProperties); + // We need to clone the temporary identifier so that we can write it on a + // new line + expressions.push(node.multiLine ? ts.startOnNewLine(ts.getMutableClone(temp)) : temp); + return ts.inlineExpressions(expressions); + } + return ts.visitEachChild(node, visitor, context); + } + function shouldConvertPartOfIterationStatement(node) { + return (resolver.getNodeCheckFlags(node) & 131072 /* ContainsCapturedBlockScopeBinding */) !== 0; + } + function shouldConvertInitializerOfForStatement(node) { + return ts.isForStatement(node) && !!node.initializer && shouldConvertPartOfIterationStatement(node.initializer); + } + function shouldConvertConditionOfForStatement(node) { + return ts.isForStatement(node) && !!node.condition && shouldConvertPartOfIterationStatement(node.condition); + } + function shouldConvertIncrementorOfForStatement(node) { + return ts.isForStatement(node) && !!node.incrementor && shouldConvertPartOfIterationStatement(node.incrementor); + } + function shouldConvertIterationStatement(node) { + return shouldConvertBodyOfIterationStatement(node) + || shouldConvertInitializerOfForStatement(node); + } + function shouldConvertBodyOfIterationStatement(node) { + return (resolver.getNodeCheckFlags(node) & 65536 /* LoopWithCapturedBlockScopedBinding */) !== 0; + } + /** + * Records constituents of name for the given variable to be hoisted in the outer scope. + */ + function hoistVariableDeclarationDeclaredInConvertedLoop(state, node) { + if (!state.hoistedLocalVariables) { + state.hoistedLocalVariables = []; + } + visit(node.name); + function visit(node) { + if (node.kind === 72 /* Identifier */) { + state.hoistedLocalVariables.push(node); + } + else { + for (var _i = 0, _a = node.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (!ts.isOmittedExpression(element)) { + visit(element.name); + } + } + } + } + } + function convertIterationStatementBodyIfNecessary(node, outermostLabeledStatement, convert) { + if (!shouldConvertIterationStatement(node)) { + var saveAllowedNonLabeledJumps = void 0; + if (convertedLoopState) { + // we get here if we are trying to emit normal loop loop inside converted loop + // set allowedNonLabeledJumps to Break | Continue to mark that break\continue inside the loop should be emitted as is + saveAllowedNonLabeledJumps = convertedLoopState.allowedNonLabeledJumps; + convertedLoopState.allowedNonLabeledJumps = 2 /* Break */ | 4 /* Continue */; + } + var result = convert + ? convert(node, outermostLabeledStatement, /*convertedLoopBodyStatements*/ undefined) + : ts.restoreEnclosingLabel(ts.visitEachChild(node, visitor, context), outermostLabeledStatement, convertedLoopState && resetLabel); + if (convertedLoopState) { + convertedLoopState.allowedNonLabeledJumps = saveAllowedNonLabeledJumps; + } + return result; + } + var currentState = createConvertedLoopState(node); + var statements = []; + var outerConvertedLoopState = convertedLoopState; + convertedLoopState = currentState; + var initializerFunction = shouldConvertInitializerOfForStatement(node) ? createFunctionForInitializerOfForStatement(node, currentState) : undefined; + var bodyFunction = shouldConvertBodyOfIterationStatement(node) ? createFunctionForBodyOfIterationStatement(node, currentState, outerConvertedLoopState) : undefined; + convertedLoopState = outerConvertedLoopState; + if (initializerFunction) + statements.push(initializerFunction.functionDeclaration); + if (bodyFunction) + statements.push(bodyFunction.functionDeclaration); + addExtraDeclarationsForConvertedLoop(statements, currentState, outerConvertedLoopState); + if (initializerFunction) { + statements.push(generateCallToConvertedLoopInitializer(initializerFunction.functionName, initializerFunction.containsYield)); + } + var loop; + if (bodyFunction) { + if (convert) { + loop = convert(node, outermostLabeledStatement, bodyFunction.part); + } + else { + var clone_3 = convertIterationStatementCore(node, initializerFunction, ts.createBlock(bodyFunction.part, /*multiLine*/ true)); + ts.aggregateTransformFlags(clone_3); + loop = ts.restoreEnclosingLabel(clone_3, outermostLabeledStatement, convertedLoopState && resetLabel); + } + } + else { + var clone_4 = convertIterationStatementCore(node, initializerFunction, ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); + ts.aggregateTransformFlags(clone_4); + loop = ts.restoreEnclosingLabel(clone_4, outermostLabeledStatement, convertedLoopState && resetLabel); + } + statements.push(loop); + return statements; + } + function convertIterationStatementCore(node, initializerFunction, convertedLoopBody) { + switch (node.kind) { + case 225 /* ForStatement */: return convertForStatement(node, initializerFunction, convertedLoopBody); + case 226 /* ForInStatement */: return convertForInStatement(node, convertedLoopBody); + case 227 /* ForOfStatement */: return convertForOfStatement(node, convertedLoopBody); + case 223 /* DoStatement */: return convertDoStatement(node, convertedLoopBody); + case 224 /* WhileStatement */: return convertWhileStatement(node, convertedLoopBody); + default: return ts.Debug.failBadSyntaxKind(node, "IterationStatement expected"); + } + } + function convertForStatement(node, initializerFunction, convertedLoopBody) { + var shouldConvertCondition = node.condition && shouldConvertPartOfIterationStatement(node.condition); + var shouldConvertIncrementor = shouldConvertCondition || node.incrementor && shouldConvertPartOfIterationStatement(node.incrementor); + return ts.updateFor(node, ts.visitNode(initializerFunction ? initializerFunction.part : node.initializer, visitor, ts.isForInitializer), ts.visitNode(shouldConvertCondition ? undefined : node.condition, visitor, ts.isExpression), ts.visitNode(shouldConvertIncrementor ? undefined : node.incrementor, visitor, ts.isExpression), convertedLoopBody); + } + function convertForOfStatement(node, convertedLoopBody) { + return ts.updateForOf(node, + /*awaitModifier*/ undefined, ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), convertedLoopBody); + } + function convertForInStatement(node, convertedLoopBody) { + return ts.updateForIn(node, ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), convertedLoopBody); + } + function convertDoStatement(node, convertedLoopBody) { + return ts.updateDo(node, convertedLoopBody, ts.visitNode(node.expression, visitor, ts.isExpression)); + } + function convertWhileStatement(node, convertedLoopBody) { + return ts.updateWhile(node, ts.visitNode(node.expression, visitor, ts.isExpression), convertedLoopBody); + } + function createConvertedLoopState(node) { + var loopInitializer; + switch (node.kind) { + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + var initializer = node.initializer; + if (initializer && initializer.kind === 238 /* VariableDeclarationList */) { + loopInitializer = initializer; + } + break; + } + // variables that will be passed to the loop as parameters + var loopParameters = []; + // variables declared in the loop initializer that will be changed inside the loop + var loopOutParameters = []; + if (loopInitializer && (ts.getCombinedNodeFlags(loopInitializer) & 3 /* BlockScoped */)) { + var hasCapturedBindingsInForInitializer = shouldConvertInitializerOfForStatement(node); + for (var _i = 0, _a = loopInitializer.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + processLoopVariableDeclaration(node, decl, loopParameters, loopOutParameters, hasCapturedBindingsInForInitializer); + } + } + var currentState = { loopParameters: loopParameters, loopOutParameters: loopOutParameters }; + if (convertedLoopState) { + // convertedOuterLoopState !== undefined means that this converted loop is nested in another converted loop. + // if outer converted loop has already accumulated some state - pass it through + if (convertedLoopState.argumentsName) { + // outer loop has already used 'arguments' so we've already have some name to alias it + // use the same name in all nested loops + currentState.argumentsName = convertedLoopState.argumentsName; + } + if (convertedLoopState.thisName) { + // outer loop has already used 'this' so we've already have some name to alias it + // use the same name in all nested loops + currentState.thisName = convertedLoopState.thisName; + } + if (convertedLoopState.hoistedLocalVariables) { + // we've already collected some non-block scoped variable declarations in enclosing loop + // use the same storage in nested loop + currentState.hoistedLocalVariables = convertedLoopState.hoistedLocalVariables; + } + } + return currentState; + } + function addExtraDeclarationsForConvertedLoop(statements, state, outerState) { + var extraVariableDeclarations; + // propagate state from the inner loop to the outer loop if necessary + if (state.argumentsName) { + // if alias for arguments is set + if (outerState) { + // pass it to outer converted loop + outerState.argumentsName = state.argumentsName; + } + else { + // this is top level converted loop and we need to create an alias for 'arguments' object + (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(state.argumentsName, + /*type*/ undefined, ts.createIdentifier("arguments"))); + } + } + if (state.thisName) { + // if alias for this is set + if (outerState) { + // pass it to outer converted loop + outerState.thisName = state.thisName; + } + else { + // this is top level converted loop so we need to create an alias for 'this' here + // NOTE: + // if converted loops were all nested in arrow function then we'll always emit '_this' so convertedLoopState.thisName will not be set. + // If it is set this means that all nested loops are not nested in arrow function and it is safe to capture 'this'. + (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(state.thisName, + /*type*/ undefined, ts.createIdentifier("this"))); + } + } + if (state.hoistedLocalVariables) { + // if hoistedLocalVariables !== undefined this means that we've possibly collected some variable declarations to be hoisted later + if (outerState) { + // pass them to outer converted loop + outerState.hoistedLocalVariables = state.hoistedLocalVariables; + } + else { + if (!extraVariableDeclarations) { + extraVariableDeclarations = []; + } + // hoist collected variable declarations + for (var _i = 0, _a = state.hoistedLocalVariables; _i < _a.length; _i++) { + var identifier = _a[_i]; + extraVariableDeclarations.push(ts.createVariableDeclaration(identifier)); + } + } + } + // add extra variables to hold out parameters if necessary + if (state.loopOutParameters.length) { + if (!extraVariableDeclarations) { + extraVariableDeclarations = []; + } + for (var _b = 0, _c = state.loopOutParameters; _b < _c.length; _b++) { + var outParam = _c[_b]; + extraVariableDeclarations.push(ts.createVariableDeclaration(outParam.outParamName)); + } + } + if (state.conditionVariable) { + if (!extraVariableDeclarations) { + extraVariableDeclarations = []; + } + extraVariableDeclarations.push(ts.createVariableDeclaration(state.conditionVariable, /*type*/ undefined, ts.createFalse())); + } + // create variable statement to hold all introduced variable declarations + if (extraVariableDeclarations) { + statements.push(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList(extraVariableDeclarations))); + } + } + function createOutVariable(p) { + return ts.createVariableDeclaration(p.originalName, /*type*/ undefined, p.outParamName); + } + /** + * Creates a `_loop_init` function for a `ForStatement` with a block-scoped initializer + * that is captured in a closure inside of the initializer. The `_loop_init` function is + * used to preserve the per-iteration environment semantics of + * [13.7.4.8 RS: ForBodyEvaluation](https://tc39.github.io/ecma262/#sec-forbodyevaluation). + */ + function createFunctionForInitializerOfForStatement(node, currentState) { + var functionName = ts.createUniqueName("_loop_init"); + var containsYield = (node.initializer.transformFlags & 4194304 /* ContainsYield */) !== 0; + var emitFlags = 0 /* None */; + if (currentState.containsLexicalThis) + emitFlags |= 8 /* CapturesThis */; + if (containsYield && hierarchyFacts & 4 /* AsyncFunctionBody */) + emitFlags |= 262144 /* AsyncFunctionBody */; + var statements = []; + statements.push(ts.createVariableStatement(/*modifiers*/ undefined, node.initializer)); + copyOutParameters(currentState.loopOutParameters, 2 /* Initializer */, 1 /* ToOutParameter */, statements); + // This transforms the following ES2015 syntax: + // + // for (let i = (setImmediate(() => console.log(i)), 0); i < 2; i++) { + // // loop body + // } + // + // Into the following ES5 syntax: + // + // var _loop_init_1 = function () { + // var i = (setImmediate(() => console.log(i)), 0); + // out_i_1 = i; + // }; + // var out_i_1; + // _loop_init_1(); + // for (var i = out_i_1; i < 2; i++) { + // // loop body + // } + // + // Which prevents mutations to `i` in the per-iteration environment of the body + // from affecting the initial value for `i` outside of the per-iteration environment. + var functionDeclaration = ts.createVariableStatement( + /*modifiers*/ undefined, ts.setEmitFlags(ts.createVariableDeclarationList([ + ts.createVariableDeclaration(functionName, + /*type*/ undefined, ts.setEmitFlags(ts.createFunctionExpression( + /*modifiers*/ undefined, containsYield ? ts.createToken(40 /* AsteriskToken */) : undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, + /*parameters*/ undefined, + /*type*/ undefined, ts.visitNode(ts.createBlock(statements, /*multiLine*/ true), visitor, ts.isBlock)), emitFlags)) + ]), 2097152 /* NoHoisting */)); + var part = ts.createVariableDeclarationList(ts.map(currentState.loopOutParameters, createOutVariable)); + return { functionName: functionName, containsYield: containsYield, functionDeclaration: functionDeclaration, part: part }; + } + /** + * Creates a `_loop` function for an `IterationStatement` with a block-scoped initializer + * that is captured in a closure inside of the loop body. The `_loop` function is used to + * preserve the per-iteration environment semantics of + * [13.7.4.8 RS: ForBodyEvaluation](https://tc39.github.io/ecma262/#sec-forbodyevaluation). + */ + function createFunctionForBodyOfIterationStatement(node, currentState, outerState) { + var functionName = ts.createUniqueName("_loop"); + startLexicalEnvironment(); + var statement = ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock); + var lexicalEnvironment = endLexicalEnvironment(); + var statements = []; + if (shouldConvertConditionOfForStatement(node) || shouldConvertIncrementorOfForStatement(node)) { + // If a block-scoped variable declared in the initializer of `node` is captured in + // the condition or incrementor, we must move the condition and incrementor into + // the body of the for loop. + // + // This transforms the following ES2015 syntax: + // + // for (let i = 0; setImmediate(() => console.log(i)), i < 2; setImmediate(() => console.log(i)), i++) { + // // loop body + // } + // + // Into the following ES5 syntax: + // + // var _loop_1 = function (i) { + // if (inc_1) + // setImmediate(() => console.log(i)), i++; + // else + // inc_1 = true; + // if (!(setImmediate(() => console.log(i)), i < 2)) + // return out_i_1 = i, "break"; + // // loop body + // out_i_1 = i; + // } + // var out_i_1, inc_1 = false; + // for (var i = 0;;) { + // var state_1 = _loop_1(i); + // i = out_i_1; + // if (state_1 === "break") + // break; + // } + // + // Which prevents mutations to `i` in the per-iteration environment of the body + // from affecting the value of `i` in the previous per-iteration environment. + // + // Note that the incrementor of a `for` loop is evaluated in a *new* per-iteration + // environment that is carried over to the next iteration of the loop. As a result, + // we must indicate whether this is the first evaluation of the loop body so that + // we only evaluate the incrementor on subsequent evaluations. + currentState.conditionVariable = ts.createUniqueName("inc"); + statements.push(ts.createIf(currentState.conditionVariable, ts.createStatement(ts.visitNode(node.incrementor, visitor, ts.isExpression)), ts.createStatement(ts.createAssignment(currentState.conditionVariable, ts.createTrue())))); + if (shouldConvertConditionOfForStatement(node)) { + statements.push(ts.createIf(ts.createPrefix(52 /* ExclamationToken */, ts.visitNode(node.condition, visitor, ts.isExpression)), ts.visitNode(ts.createBreak(), visitor, ts.isStatement))); + } + } + if (ts.isBlock(statement)) { + ts.addRange(statements, statement.statements); + } + else { + statements.push(statement); + } + copyOutParameters(currentState.loopOutParameters, 1 /* Body */, 1 /* ToOutParameter */, statements); + ts.addStatementsAfterPrologue(statements, lexicalEnvironment); + var loopBody = ts.createBlock(statements, /*multiLine*/ true); + if (ts.isBlock(statement)) + ts.setOriginalNode(loopBody, statement); + var containsYield = (node.statement.transformFlags & 4194304 /* ContainsYield */) !== 0; + var emitFlags = 0; + if (currentState.containsLexicalThis) + emitFlags |= 8 /* CapturesThis */; + if (containsYield && (hierarchyFacts & 4 /* AsyncFunctionBody */) !== 0) + emitFlags |= 262144 /* AsyncFunctionBody */; + // This transforms the following ES2015 syntax (in addition to other variations): + // + // for (let i = 0; i < 2; i++) { + // setImmediate(() => console.log(i)); + // } + // + // Into the following ES5 syntax: + // + // var _loop_1 = function (i) { + // setImmediate(() => console.log(i)); + // }; + // for (var i = 0; i < 2; i++) { + // _loop_1(i); + // } + var functionDeclaration = ts.createVariableStatement( + /*modifiers*/ undefined, ts.setEmitFlags(ts.createVariableDeclarationList([ + ts.createVariableDeclaration(functionName, + /*type*/ undefined, ts.setEmitFlags(ts.createFunctionExpression( + /*modifiers*/ undefined, containsYield ? ts.createToken(40 /* AsteriskToken */) : undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, currentState.loopParameters, + /*type*/ undefined, loopBody), emitFlags)) + ]), 2097152 /* NoHoisting */)); + var part = generateCallToConvertedLoop(functionName, currentState, outerState, containsYield); + return { functionName: functionName, containsYield: containsYield, functionDeclaration: functionDeclaration, part: part }; + } + function copyOutParameter(outParam, copyDirection) { + var source = copyDirection === 0 /* ToOriginal */ ? outParam.outParamName : outParam.originalName; + var target = copyDirection === 0 /* ToOriginal */ ? outParam.originalName : outParam.outParamName; + return ts.createBinary(target, 59 /* EqualsToken */, source); + } + function copyOutParameters(outParams, partFlags, copyDirection, statements) { + for (var _i = 0, outParams_1 = outParams; _i < outParams_1.length; _i++) { + var outParam = outParams_1[_i]; + if (outParam.flags & partFlags) { + statements.push(ts.createExpressionStatement(copyOutParameter(outParam, copyDirection))); + } + } + } + function generateCallToConvertedLoopInitializer(initFunctionExpressionName, containsYield) { + var call = ts.createCall(initFunctionExpressionName, /*typeArguments*/ undefined, []); + var callResult = containsYield + ? ts.createYield(ts.createToken(40 /* AsteriskToken */), ts.setEmitFlags(call, 8388608 /* Iterator */)) + : call; + return ts.createStatement(callResult); + } + function generateCallToConvertedLoop(loopFunctionExpressionName, state, outerState, containsYield) { + var statements = []; + // loop is considered simple if it does not have any return statements or break\continue that transfer control outside of the loop + // simple loops are emitted as just 'loop()'; + // NOTE: if loop uses only 'continue' it still will be emitted as simple loop + var isSimpleLoop = !(state.nonLocalJumps & ~4 /* Continue */) && + !state.labeledNonLocalBreaks && + !state.labeledNonLocalContinues; + var call = ts.createCall(loopFunctionExpressionName, /*typeArguments*/ undefined, ts.map(state.loopParameters, function (p) { return p.name; })); + var callResult = containsYield + ? ts.createYield(ts.createToken(40 /* AsteriskToken */), ts.setEmitFlags(call, 8388608 /* Iterator */)) + : call; + if (isSimpleLoop) { + statements.push(ts.createExpressionStatement(callResult)); + copyOutParameters(state.loopOutParameters, 1 /* Body */, 0 /* ToOriginal */, statements); + } + else { + var loopResultName = ts.createUniqueName("state"); + var stateVariable = ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(loopResultName, /*type*/ undefined, callResult)])); + statements.push(stateVariable); + copyOutParameters(state.loopOutParameters, 1 /* Body */, 0 /* ToOriginal */, statements); + if (state.nonLocalJumps & 8 /* Return */) { + var returnStatement = void 0; + if (outerState) { + outerState.nonLocalJumps |= 8 /* Return */; + returnStatement = ts.createReturn(loopResultName); + } + else { + returnStatement = ts.createReturn(ts.createPropertyAccess(loopResultName, "value")); + } + statements.push(ts.createIf(ts.createBinary(ts.createTypeOf(loopResultName), 35 /* EqualsEqualsEqualsToken */, ts.createLiteral("object")), returnStatement)); + } + if (state.nonLocalJumps & 2 /* Break */) { + statements.push(ts.createIf(ts.createBinary(loopResultName, 35 /* EqualsEqualsEqualsToken */, ts.createLiteral("break")), ts.createBreak())); + } + if (state.labeledNonLocalBreaks || state.labeledNonLocalContinues) { + var caseClauses = []; + processLabeledJumps(state.labeledNonLocalBreaks, /*isBreak*/ true, loopResultName, outerState, caseClauses); + processLabeledJumps(state.labeledNonLocalContinues, /*isBreak*/ false, loopResultName, outerState, caseClauses); + statements.push(ts.createSwitch(loopResultName, ts.createCaseBlock(caseClauses))); + } + } + return statements; + } + function setLabeledJump(state, isBreak, labelText, labelMarker) { + if (isBreak) { + if (!state.labeledNonLocalBreaks) { + state.labeledNonLocalBreaks = ts.createMap(); + } + state.labeledNonLocalBreaks.set(labelText, labelMarker); + } + else { + if (!state.labeledNonLocalContinues) { + state.labeledNonLocalContinues = ts.createMap(); + } + state.labeledNonLocalContinues.set(labelText, labelMarker); + } + } + function processLabeledJumps(table, isBreak, loopResultName, outerLoop, caseClauses) { + if (!table) { + return; + } + table.forEach(function (labelMarker, labelText) { + var statements = []; + // if there are no outer converted loop or outer label in question is located inside outer converted loop + // then emit labeled break\continue + // otherwise propagate pair 'label -> marker' to outer converted loop and emit 'return labelMarker' so outer loop can later decide what to do + if (!outerLoop || (outerLoop.labels && outerLoop.labels.get(labelText))) { + var label = ts.createIdentifier(labelText); + statements.push(isBreak ? ts.createBreak(label) : ts.createContinue(label)); + } + else { + setLabeledJump(outerLoop, isBreak, labelText, labelMarker); + statements.push(ts.createReturn(loopResultName)); + } + caseClauses.push(ts.createCaseClause(ts.createLiteral(labelMarker), statements)); + }); + } + function processLoopVariableDeclaration(container, decl, loopParameters, loopOutParameters, hasCapturedBindingsInForInitializer) { + var name = decl.name; + if (ts.isBindingPattern(name)) { + for (var _i = 0, _a = name.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (!ts.isOmittedExpression(element)) { + processLoopVariableDeclaration(container, element, loopParameters, loopOutParameters, hasCapturedBindingsInForInitializer); + } + } + } + else { + loopParameters.push(ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, name)); + var checkFlags = resolver.getNodeCheckFlags(decl); + if (checkFlags & 4194304 /* NeedsLoopOutParameter */ || hasCapturedBindingsInForInitializer) { + var outParamName = ts.createUniqueName("out_" + ts.idText(name)); + var flags = 0; + if (checkFlags & 4194304 /* NeedsLoopOutParameter */) { + flags |= 1 /* Body */; + } + if (ts.isForStatement(container) && container.initializer && resolver.isBindingCapturedByNode(container.initializer, decl)) { + flags |= 2 /* Initializer */; + } + loopOutParameters.push({ flags: flags, originalName: name, outParamName: outParamName }); + } + } + } + /** + * Adds the members of an object literal to an array of expressions. + * + * @param expressions An array of expressions. + * @param node An ObjectLiteralExpression node. + * @param receiver The receiver for members of the ObjectLiteralExpression. + * @param numInitialNonComputedProperties The number of initial properties without + * computed property names. + */ + function addObjectLiteralMembers(expressions, node, receiver, start) { + var properties = node.properties; + var numProperties = properties.length; + for (var i = start; i < numProperties; i++) { + var property = properties[i]; + switch (property.kind) { + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + var accessors = ts.getAllAccessorDeclarations(node.properties, property); + if (property === accessors.firstAccessor) { + expressions.push(transformAccessorsToExpression(receiver, accessors, node, !!node.multiLine)); + } + break; + case 156 /* MethodDeclaration */: + expressions.push(transformObjectLiteralMethodDeclarationToExpression(property, receiver, node, node.multiLine)); + break; + case 275 /* PropertyAssignment */: + expressions.push(transformPropertyAssignmentToExpression(property, receiver, node.multiLine)); + break; + case 276 /* ShorthandPropertyAssignment */: + expressions.push(transformShorthandPropertyAssignmentToExpression(property, receiver, node.multiLine)); + break; + default: + ts.Debug.failBadSyntaxKind(node); + break; + } + } + } + /** + * Transforms a PropertyAssignment node into an expression. + * + * @param node The ObjectLiteralExpression that contains the PropertyAssignment. + * @param property The PropertyAssignment node. + * @param receiver The receiver for the assignment. + */ + function transformPropertyAssignmentToExpression(property, receiver, startsOnNewLine) { + var expression = ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(property.name, visitor, ts.isPropertyName)), ts.visitNode(property.initializer, visitor, ts.isExpression)); + ts.setTextRange(expression, property); + if (startsOnNewLine) { + ts.startOnNewLine(expression); + } + return expression; + } + /** + * Transforms a ShorthandPropertyAssignment node into an expression. + * + * @param node The ObjectLiteralExpression that contains the ShorthandPropertyAssignment. + * @param property The ShorthandPropertyAssignment node. + * @param receiver The receiver for the assignment. + */ + function transformShorthandPropertyAssignmentToExpression(property, receiver, startsOnNewLine) { + var expression = ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(property.name, visitor, ts.isPropertyName)), ts.getSynthesizedClone(property.name)); + ts.setTextRange(expression, property); + if (startsOnNewLine) { + ts.startOnNewLine(expression); + } + return expression; + } + /** + * Transforms a MethodDeclaration of an ObjectLiteralExpression into an expression. + * + * @param node The ObjectLiteralExpression that contains the MethodDeclaration. + * @param method The MethodDeclaration node. + * @param receiver The receiver for the assignment. + */ + function transformObjectLiteralMethodDeclarationToExpression(method, receiver, container, startsOnNewLine) { + var ancestorFacts = enterSubtree(0 /* None */, 0 /* None */); + var expression = ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(method.name, visitor, ts.isPropertyName)), transformFunctionLikeToExpression(method, /*location*/ method, /*name*/ undefined, container)); + ts.setTextRange(expression, method); + if (startsOnNewLine) { + ts.startOnNewLine(expression); + } + exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, hierarchyFacts & 49152 /* PropagateNewTargetMask */ ? 16384 /* NewTarget */ : 0 /* None */); + return expression; + } + function visitCatchClause(node) { + var ancestorFacts = enterSubtree(4032 /* BlockScopeExcludes */, 0 /* BlockScopeIncludes */); + var updated; + ts.Debug.assert(!!node.variableDeclaration, "Catch clause variable should always be present when downleveling ES2015."); + if (ts.isBindingPattern(node.variableDeclaration.name)) { + var temp = ts.createTempVariable(/*recordTempVariable*/ undefined); + var newVariableDeclaration = ts.createVariableDeclaration(temp); + ts.setTextRange(newVariableDeclaration, node.variableDeclaration); + var vars = ts.flattenDestructuringBinding(node.variableDeclaration, visitor, context, 0 /* All */, temp); + var list = ts.createVariableDeclarationList(vars); + ts.setTextRange(list, node.variableDeclaration); + var destructure = ts.createVariableStatement(/*modifiers*/ undefined, list); + updated = ts.updateCatchClause(node, newVariableDeclaration, addStatementToStartOfBlock(node.block, destructure)); + } + else { + updated = ts.visitEachChild(node, visitor, context); + } + exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */); + return updated; + } + function addStatementToStartOfBlock(block, statement) { + var transformedStatements = ts.visitNodes(block.statements, visitor, ts.isStatement); + return ts.updateBlock(block, [statement].concat(transformedStatements)); + } + /** + * Visits a MethodDeclaration of an ObjectLiteralExpression and transforms it into a + * PropertyAssignment. + * + * @param node A MethodDeclaration node. + */ + function visitMethodDeclaration(node) { + // We should only get here for methods on an object literal with regular identifier names. + // Methods on classes are handled in visitClassDeclaration/visitClassExpression. + // Methods with computed property names are handled in visitObjectLiteralExpression. + ts.Debug.assert(!ts.isComputedPropertyName(node.name)); + var functionExpression = transformFunctionLikeToExpression(node, /*location*/ ts.moveRangePos(node, -1), /*name*/ undefined, /*container*/ undefined); + ts.setEmitFlags(functionExpression, 512 /* NoLeadingComments */ | ts.getEmitFlags(functionExpression)); + return ts.setTextRange(ts.createPropertyAssignment(node.name, functionExpression), + /*location*/ node); + } + /** + * Visits an AccessorDeclaration of an ObjectLiteralExpression. + * + * @param node An AccessorDeclaration node. + */ + function visitAccessorDeclaration(node) { + ts.Debug.assert(!ts.isComputedPropertyName(node.name)); + var savedConvertedLoopState = convertedLoopState; + convertedLoopState = undefined; + var ancestorFacts = enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */); + var updated; + var parameters = ts.visitParameterList(node.parameters, visitor, context); + var body = node.transformFlags & (16384 /* ContainsCapturedLexicalThis */ | 128 /* ContainsES2015 */) + ? transformFunctionBody(node) + : visitFunctionBodyDownLevel(node); + if (node.kind === 158 /* GetAccessor */) { + updated = ts.updateGetAccessor(node, node.decorators, node.modifiers, node.name, parameters, node.type, body); + } + else { + updated = ts.updateSetAccessor(node, node.decorators, node.modifiers, node.name, parameters, body); + } + exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, 0 /* None */); + convertedLoopState = savedConvertedLoopState; + return updated; + } + /** + * Visits a ShorthandPropertyAssignment and transforms it into a PropertyAssignment. + * + * @param node A ShorthandPropertyAssignment node. + */ + function visitShorthandPropertyAssignment(node) { + return ts.setTextRange(ts.createPropertyAssignment(node.name, ts.getSynthesizedClone(node.name)), + /*location*/ node); + } + function visitComputedPropertyName(node) { + var ancestorFacts = enterSubtree(0 /* ComputedPropertyNameExcludes */, 8192 /* ComputedPropertyNameIncludes */); + var updated = ts.visitEachChild(node, visitor, context); + exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, hierarchyFacts & 49152 /* PropagateNewTargetMask */ ? 32768 /* NewTargetInComputedPropertyName */ : 0 /* None */); + return updated; + } + /** + * Visits a YieldExpression node. + * + * @param node A YieldExpression node. + */ + function visitYieldExpression(node) { + // `yield` expressions are transformed using the generators transformer. + return ts.visitEachChild(node, visitor, context); + } + /** + * Visits an ArrayLiteralExpression that contains a spread element. + * + * @param node An ArrayLiteralExpression node. + */ + function visitArrayLiteralExpression(node) { + if (node.transformFlags & 64 /* ES2015 */) { + // We are here because we contain a SpreadElementExpression. + return transformAndSpreadElements(node.elements, /*needsUniqueCopy*/ true, !!node.multiLine, /*hasTrailingComma*/ !!node.elements.hasTrailingComma); + } + return ts.visitEachChild(node, visitor, context); + } + /** + * Visits a CallExpression that contains either a spread element or `super`. + * + * @param node a CallExpression. + */ + function visitCallExpression(node) { + if (ts.getEmitFlags(node) & 33554432 /* TypeScriptClassWrapper */) { + return visitTypeScriptClassWrapper(node); + } + if (node.transformFlags & 64 /* ES2015 */) { + return visitCallExpressionWithPotentialCapturedThisAssignment(node, /*assignToCapturedThis*/ true); + } + return ts.updateCall(node, ts.visitNode(node.expression, callExpressionVisitor, ts.isExpression), + /*typeArguments*/ undefined, ts.visitNodes(node.arguments, visitor, ts.isExpression)); + } + function visitTypeScriptClassWrapper(node) { + // This is a call to a class wrapper function (an IIFE) created by the 'ts' transformer. + // The wrapper has a form similar to: + // + // (function() { + // class C { // 1 + // } + // C.x = 1; // 2 + // return C; + // }()) + // + // When we transform the class, we end up with something like this: + // + // (function () { + // var C = (function () { // 3 + // function C() { + // } + // return C; // 4 + // }()); + // C.x = 1; + // return C; + // }()) + // + // We want to simplify the two nested IIFEs to end up with something like this: + // + // (function () { + // function C() { + // } + // C.x = 1; + // return C; + // }()) + // We skip any outer expressions in a number of places to get to the innermost + // expression, but we will restore them later to preserve comments and source maps. + var body = ts.cast(ts.cast(ts.skipOuterExpressions(node.expression), ts.isArrowFunction).body, ts.isBlock); + // The class statements are the statements generated by visiting the first statement with initializer of the + // body (1), while all other statements are added to remainingStatements (2) + var isVariableStatementWithInitializer = function (stmt) { return ts.isVariableStatement(stmt) && !!ts.first(stmt.declarationList.declarations).initializer; }; + var bodyStatements = ts.visitNodes(body.statements, visitor, ts.isStatement); + var classStatements = ts.filter(bodyStatements, isVariableStatementWithInitializer); + var remainingStatements = ts.filter(bodyStatements, function (stmt) { return !isVariableStatementWithInitializer(stmt); }); + var varStatement = ts.cast(ts.first(classStatements), ts.isVariableStatement); + // We know there is only one variable declaration here as we verified this in an + // earlier call to isTypeScriptClassWrapper + var variable = varStatement.declarationList.declarations[0]; + var initializer = ts.skipOuterExpressions(variable.initializer); + // Under certain conditions, the 'ts' transformer may introduce a class alias, which + // we see as an assignment, for example: + // + // (function () { + // var C_1; + // var C = C_1 = (function () { + // function C() { + // } + // C.x = function () { return C_1; } + // return C; + // }()); + // C = C_1 = __decorate([dec], C); + // return C; + // }()) + // + var aliasAssignment = ts.tryCast(initializer, ts.isAssignmentExpression); + // The underlying call (3) is another IIFE that may contain a '_super' argument. + var call = ts.cast(aliasAssignment ? ts.skipOuterExpressions(aliasAssignment.right) : initializer, ts.isCallExpression); + var func = ts.cast(ts.skipOuterExpressions(call.expression), ts.isFunctionExpression); + var funcStatements = func.body.statements; + var classBodyStart = 0; + var classBodyEnd = -1; + var statements = []; + if (aliasAssignment) { + // If we have a class alias assignment, we need to move it to the down-level constructor + // function we generated for the class. + var extendsCall = ts.tryCast(funcStatements[classBodyStart], ts.isExpressionStatement); + if (extendsCall) { + statements.push(extendsCall); + classBodyStart++; + } + // The next statement is the function declaration. + statements.push(funcStatements[classBodyStart]); + classBodyStart++; + // Add the class alias following the declaration. + statements.push(ts.createExpressionStatement(ts.createAssignment(aliasAssignment.left, ts.cast(variable.name, ts.isIdentifier)))); + } + // Find the trailing 'return' statement (4) + while (!ts.isReturnStatement(ts.elementAt(funcStatements, classBodyEnd))) { + classBodyEnd--; + } + // When we extract the statements of the inner IIFE, we exclude the 'return' statement (4) + // as we already have one that has been introduced by the 'ts' transformer. + ts.addRange(statements, funcStatements, classBodyStart, classBodyEnd); + if (classBodyEnd < -1) { + // If there were any hoisted declarations following the return statement, we should + // append them. + ts.addRange(statements, funcStatements, classBodyEnd + 1); + } + // Add the remaining statements of the outer wrapper. + ts.addRange(statements, remainingStatements); + // The 'es2015' class transform may add an end-of-declaration marker. If so we will add it + // after the remaining statements from the 'ts' transformer. + ts.addRange(statements, classStatements, /*start*/ 1); + // Recreate any outer parentheses or partially-emitted expressions to preserve source map + // and comment locations. + return ts.recreateOuterExpressions(node.expression, ts.recreateOuterExpressions(variable.initializer, ts.recreateOuterExpressions(aliasAssignment && aliasAssignment.right, ts.updateCall(call, ts.recreateOuterExpressions(call.expression, ts.updateFunctionExpression(func, + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, func.parameters, + /*type*/ undefined, ts.updateBlock(func.body, statements))), + /*typeArguments*/ undefined, call.arguments)))); + } + function visitImmediateSuperCallInBody(node) { + return visitCallExpressionWithPotentialCapturedThisAssignment(node, /*assignToCapturedThis*/ false); + } + function visitCallExpressionWithPotentialCapturedThisAssignment(node, assignToCapturedThis) { + // We are here either because SuperKeyword was used somewhere in the expression, or + // because we contain a SpreadElementExpression. + if (node.transformFlags & 131072 /* ContainsRestOrSpread */ || + node.expression.kind === 98 /* SuperKeyword */ || + ts.isSuperProperty(ts.skipOuterExpressions(node.expression))) { + var _a = ts.createCallBinding(node.expression, hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg; + if (node.expression.kind === 98 /* SuperKeyword */) { + ts.setEmitFlags(thisArg, 4 /* NoSubstitution */); + } + var resultingCall = void 0; + if (node.transformFlags & 131072 /* ContainsRestOrSpread */) { + // [source] + // f(...a, b) + // x.m(...a, b) + // super(...a, b) + // super.m(...a, b) // in static + // super.m(...a, b) // in instance + // + // [output] + // f.apply(void 0, a.concat([b])) + // (_a = x).m.apply(_a, a.concat([b])) + // _super.apply(this, a.concat([b])) + // _super.m.apply(this, a.concat([b])) + // _super.prototype.m.apply(this, a.concat([b])) + resultingCall = ts.createFunctionApply(ts.visitNode(target, callExpressionVisitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), transformAndSpreadElements(node.arguments, /*needsUniqueCopy*/ false, /*multiLine*/ false, /*hasTrailingComma*/ false)); + } + else { + // [source] + // super(a) + // super.m(a) // in static + // super.m(a) // in instance + // + // [output] + // _super.call(this, a) + // _super.m.call(this, a) + // _super.prototype.m.call(this, a) + resultingCall = ts.createFunctionCall(ts.visitNode(target, callExpressionVisitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), ts.visitNodes(node.arguments, visitor, ts.isExpression), + /*location*/ node); + } + if (node.expression.kind === 98 /* SuperKeyword */) { + var actualThis = ts.createThis(); + ts.setEmitFlags(actualThis, 4 /* NoSubstitution */); + var initializer = ts.createLogicalOr(resultingCall, actualThis); + resultingCall = assignToCapturedThis + ? ts.createAssignment(ts.createFileLevelUniqueName("_this"), initializer) + : initializer; + } + return ts.setOriginalNode(resultingCall, node); + } + return ts.visitEachChild(node, visitor, context); + } + /** + * Visits a NewExpression that contains a spread element. + * + * @param node A NewExpression node. + */ + function visitNewExpression(node) { + if (node.transformFlags & 131072 /* ContainsRestOrSpread */) { + // We are here because we contain a SpreadElementExpression. + // [source] + // new C(...a) + // + // [output] + // new ((_a = C).bind.apply(_a, [void 0].concat(a)))() + var _a = ts.createCallBinding(ts.createPropertyAccess(node.expression, "bind"), hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg; + return ts.createNew(ts.createFunctionApply(ts.visitNode(target, visitor, ts.isExpression), thisArg, transformAndSpreadElements(ts.createNodeArray([ts.createVoidZero()].concat(node.arguments)), /*needsUniqueCopy*/ false, /*multiLine*/ false, /*hasTrailingComma*/ false)), + /*typeArguments*/ undefined, []); + } + return ts.visitEachChild(node, visitor, context); + } + /** + * Transforms an array of Expression nodes that contains a SpreadExpression. + * + * @param elements The array of Expression nodes. + * @param needsUniqueCopy A value indicating whether to ensure that the result is a fresh array. + * @param multiLine A value indicating whether the result should be emitted on multiple lines. + */ + function transformAndSpreadElements(elements, needsUniqueCopy, multiLine, hasTrailingComma) { + // [source] + // [a, ...b, c] + // + // [output] + // [a].concat(b, [c]) + // Map spans of spread expressions into their expressions and spans of other + // expressions into an array literal. + var numElements = elements.length; + var segments = ts.flatten(ts.spanMap(elements, partitionSpread, function (partition, visitPartition, _start, end) { + return visitPartition(partition, multiLine, hasTrailingComma && end === numElements); + })); + if (compilerOptions.downlevelIteration) { + if (segments.length === 1) { + var firstSegment = segments[0]; + if (ts.isCallExpression(firstSegment) + && ts.isIdentifier(firstSegment.expression) + && (ts.getEmitFlags(firstSegment.expression) & 4096 /* HelperName */) + && firstSegment.expression.escapedText === "___spread") { + return segments[0]; + } + } + return ts.createSpreadHelper(context, segments); + } + else { + if (segments.length === 1) { + var firstElement = elements[0]; + return needsUniqueCopy && ts.isSpreadElement(firstElement) && firstElement.expression.kind !== 187 /* ArrayLiteralExpression */ + ? ts.createArraySlice(segments[0]) + : segments[0]; + } + // Rewrite using the pattern .concat(, , ...) + return ts.createArrayConcat(segments.shift(), segments); + } + } + function partitionSpread(node) { + return ts.isSpreadElement(node) + ? visitSpanOfSpreads + : visitSpanOfNonSpreads; + } + function visitSpanOfSpreads(chunk) { + return ts.map(chunk, visitExpressionOfSpread); + } + function visitSpanOfNonSpreads(chunk, multiLine, hasTrailingComma) { + return ts.createArrayLiteral(ts.visitNodes(ts.createNodeArray(chunk, hasTrailingComma), visitor, ts.isExpression), multiLine); + } + function visitSpreadElement(node) { + return ts.visitNode(node.expression, visitor, ts.isExpression); + } + /** + * Transforms the expression of a SpreadExpression node. + * + * @param node A SpreadExpression node. + */ + function visitExpressionOfSpread(node) { + return ts.visitNode(node.expression, visitor, ts.isExpression); + } + /** + * Visits a template literal. + * + * @param node A template literal. + */ + function visitTemplateLiteral(node) { + return ts.setTextRange(ts.createLiteral(node.text), node); + } + /** + * Visits a string literal with an extended unicode escape. + * + * @param node A string literal. + */ + function visitStringLiteral(node) { + if (node.hasExtendedUnicodeEscape) { + return ts.setTextRange(ts.createLiteral(node.text), node); + } + return node; + } + /** + * Visits a binary or octal (ES6) numeric literal. + * + * @param node A string literal. + */ + function visitNumericLiteral(node) { + if (node.numericLiteralFlags & 384 /* BinaryOrOctalSpecifier */) { + return ts.setTextRange(ts.createNumericLiteral(node.text), node); + } + return node; + } + /** + * Visits a TaggedTemplateExpression node. + * + * @param node A TaggedTemplateExpression node. + */ + function visitTaggedTemplateExpression(node) { + // Visit the tag expression + var tag = ts.visitNode(node.tag, visitor, ts.isExpression); + // Build up the template arguments and the raw and cooked strings for the template. + // We start out with 'undefined' for the first argument and revisit later + // to avoid walking over the template string twice and shifting all our arguments over after the fact. + var templateArguments = [undefined]; + var cookedStrings = []; + var rawStrings = []; + var template = node.template; + if (ts.isNoSubstitutionTemplateLiteral(template)) { + cookedStrings.push(ts.createLiteral(template.text)); + rawStrings.push(getRawLiteral(template)); + } + else { + cookedStrings.push(ts.createLiteral(template.head.text)); + rawStrings.push(getRawLiteral(template.head)); + for (var _i = 0, _a = template.templateSpans; _i < _a.length; _i++) { + var templateSpan = _a[_i]; + cookedStrings.push(ts.createLiteral(templateSpan.literal.text)); + rawStrings.push(getRawLiteral(templateSpan.literal)); + templateArguments.push(ts.visitNode(templateSpan.expression, visitor, ts.isExpression)); + } + } + var helperCall = createTemplateObjectHelper(context, ts.createArrayLiteral(cookedStrings), ts.createArrayLiteral(rawStrings)); + // Create a variable to cache the template object if we're in a module. + // Do not do this in the global scope, as any variable we currently generate could conflict with + // variables from outside of the current compilation. In the future, we can revisit this behavior. + if (ts.isExternalModule(currentSourceFile)) { + var tempVar = ts.createUniqueName("templateObject"); + recordTaggedTemplateString(tempVar); + templateArguments[0] = ts.createLogicalOr(tempVar, ts.createAssignment(tempVar, helperCall)); + } + else { + templateArguments[0] = helperCall; + } + return ts.createCall(tag, /*typeArguments*/ undefined, templateArguments); + } + /** + * Creates an ES5 compatible literal from an ES6 template literal. + * + * @param node The ES6 template literal. + */ + function getRawLiteral(node) { + // Find original source text, since we need to emit the raw strings of the tagged template. + // The raw strings contain the (escaped) strings of what the user wrote. + // Examples: `\n` is converted to "\\n", a template string with a newline to "\n". + var text = ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node); + // text contains the original source, it will also contain quotes ("`"), dolar signs and braces ("${" and "}"), + // thus we need to remove those characters. + // First template piece starts with "`", others with "}" + // Last template piece ends with "`", others with "${" + var isLast = node.kind === 14 /* NoSubstitutionTemplateLiteral */ || node.kind === 17 /* TemplateTail */; + text = text.substring(1, text.length - (isLast ? 1 : 2)); + // Newline normalization: + // ES6 Spec 11.8.6.1 - Static Semantics of TV's and TRV's + // and LineTerminatorSequences are normalized to for both TV and TRV. + text = text.replace(/\r\n?/g, "\n"); + return ts.setTextRange(ts.createLiteral(text), node); + } + /** + * Visits a TemplateExpression node. + * + * @param node A TemplateExpression node. + */ + function visitTemplateExpression(node) { + var expressions = []; + addTemplateHead(expressions, node); + addTemplateSpans(expressions, node); + // createAdd will check if each expression binds less closely than binary '+'. + // If it does, it wraps the expression in parentheses. Otherwise, something like + // `abc${ 1 << 2 }` + // becomes + // "abc" + 1 << 2 + "" + // which is really + // ("abc" + 1) << (2 + "") + // rather than + // "abc" + (1 << 2) + "" + var expression = ts.reduceLeft(expressions, ts.createAdd); + if (ts.nodeIsSynthesized(expression)) { + expression.pos = node.pos; + expression.end = node.end; + } + return expression; + } + /** + * Gets a value indicating whether we need to include the head of a TemplateExpression. + * + * @param node A TemplateExpression node. + */ + function shouldAddTemplateHead(node) { + // If this expression has an empty head literal and the first template span has a non-empty + // literal, then emitting the empty head literal is not necessary. + // `${ foo } and ${ bar }` + // can be emitted as + // foo + " and " + bar + // This is because it is only required that one of the first two operands in the emit + // output must be a string literal, so that the other operand and all following operands + // are forced into strings. + // + // If the first template span has an empty literal, then the head must still be emitted. + // `${ foo }${ bar }` + // must still be emitted as + // "" + foo + bar + // There is always atleast one templateSpan in this code path, since + // NoSubstitutionTemplateLiterals are directly emitted via emitLiteral() + ts.Debug.assert(node.templateSpans.length !== 0); + return node.head.text.length !== 0 || node.templateSpans[0].literal.text.length === 0; + } + /** + * Adds the head of a TemplateExpression to an array of expressions. + * + * @param expressions An array of expressions. + * @param node A TemplateExpression node. + */ + function addTemplateHead(expressions, node) { + if (!shouldAddTemplateHead(node)) { + return; + } + expressions.push(ts.createLiteral(node.head.text)); + } + /** + * Visits and adds the template spans of a TemplateExpression to an array of expressions. + * + * @param expressions An array of expressions. + * @param node A TemplateExpression node. + */ + function addTemplateSpans(expressions, node) { + for (var _i = 0, _a = node.templateSpans; _i < _a.length; _i++) { + var span = _a[_i]; + expressions.push(ts.visitNode(span.expression, visitor, ts.isExpression)); + // Only emit if the literal is non-empty. + // The binary '+' operator is left-associative, so the first string concatenation + // with the head will force the result up to this point to be a string. + // Emitting a '+ ""' has no semantic effect for middles and tails. + if (span.literal.text.length !== 0) { + expressions.push(ts.createLiteral(span.literal.text)); + } + } + } + /** + * Visits the `super` keyword + */ + function visitSuperKeyword(isExpressionOfCall) { + return hierarchyFacts & 8 /* NonStaticClassElement */ + && !isExpressionOfCall + ? ts.createPropertyAccess(ts.createFileLevelUniqueName("_super"), "prototype") + : ts.createFileLevelUniqueName("_super"); + } + function visitMetaProperty(node) { + if (node.keywordToken === 95 /* NewKeyword */ && node.name.escapedText === "target") { + if (hierarchyFacts & 8192 /* ComputedPropertyName */) { + hierarchyFacts |= 32768 /* NewTargetInComputedPropertyName */; + } + else { + hierarchyFacts |= 16384 /* NewTarget */; + } + return ts.createFileLevelUniqueName("_newTarget"); + } + return node; + } + /** + * Called by the printer just before a node is printed. + * + * @param hint A hint as to the intended usage of the node. + * @param node The node to be printed. + * @param emitCallback The callback used to emit the node. + */ + function onEmitNode(hint, node, emitCallback) { + if (enabledSubstitutions & 1 /* CapturedThis */ && ts.isFunctionLike(node)) { + // If we are tracking a captured `this`, keep track of the enclosing function. + var ancestorFacts = enterSubtree(16286 /* FunctionExcludes */, ts.getEmitFlags(node) & 8 /* CapturesThis */ + ? 65 /* FunctionIncludes */ | 16 /* CapturesThis */ + : 65 /* FunctionIncludes */); + previousOnEmitNode(hint, node, emitCallback); + exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */); + return; + } + previousOnEmitNode(hint, node, emitCallback); + } + /** + * Enables a more costly code path for substitutions when we determine a source file + * contains block-scoped bindings (e.g. `let` or `const`). + */ + function enableSubstitutionsForBlockScopedBindings() { + if ((enabledSubstitutions & 2 /* BlockScopedBindings */) === 0) { + enabledSubstitutions |= 2 /* BlockScopedBindings */; + context.enableSubstitution(72 /* Identifier */); + } + } + /** + * Enables a more costly code path for substitutions when we determine a source file + * contains a captured `this`. + */ + function enableSubstitutionsForCapturedThis() { + if ((enabledSubstitutions & 1 /* CapturedThis */) === 0) { + enabledSubstitutions |= 1 /* CapturedThis */; + context.enableSubstitution(100 /* ThisKeyword */); + context.enableEmitNotification(157 /* Constructor */); + context.enableEmitNotification(156 /* MethodDeclaration */); + context.enableEmitNotification(158 /* GetAccessor */); + context.enableEmitNotification(159 /* SetAccessor */); + context.enableEmitNotification(197 /* ArrowFunction */); + context.enableEmitNotification(196 /* FunctionExpression */); + context.enableEmitNotification(239 /* FunctionDeclaration */); + } + } + /** + * Hooks node substitutions. + * + * @param hint The context for the emitter. + * @param node The node to substitute. + */ + function onSubstituteNode(hint, node) { + node = previousOnSubstituteNode(hint, node); + if (hint === 1 /* Expression */) { + return substituteExpression(node); + } + if (ts.isIdentifier(node)) { + return substituteIdentifier(node); + } + return node; + } + /** + * Hooks substitutions for non-expression identifiers. + */ + function substituteIdentifier(node) { + // Only substitute the identifier if we have enabled substitutions for block-scoped + // bindings. + if (enabledSubstitutions & 2 /* BlockScopedBindings */ && !ts.isInternalName(node)) { + var original = ts.getParseTreeNode(node, ts.isIdentifier); + if (original && isNameOfDeclarationWithCollidingName(original)) { + return ts.setTextRange(ts.getGeneratedNameForNode(original), node); + } + } + return node; + } + /** + * Determines whether a name is the name of a declaration with a colliding name. + * NOTE: This function expects to be called with an original source tree node. + * + * @param node An original source tree node. + */ + function isNameOfDeclarationWithCollidingName(node) { + switch (node.parent.kind) { + case 186 /* BindingElement */: + case 240 /* ClassDeclaration */: + case 243 /* EnumDeclaration */: + case 237 /* VariableDeclaration */: + return node.parent.name === node + && resolver.isDeclarationWithCollidingName(node.parent); + } + return false; + } + /** + * Substitutes an expression. + * + * @param node An Expression node. + */ + function substituteExpression(node) { + switch (node.kind) { + case 72 /* Identifier */: + return substituteExpressionIdentifier(node); + case 100 /* ThisKeyword */: + return substituteThisKeyword(node); + } + return node; + } + /** + * Substitutes an expression identifier. + * + * @param node An Identifier node. + */ + function substituteExpressionIdentifier(node) { + if (enabledSubstitutions & 2 /* BlockScopedBindings */ && !ts.isInternalName(node)) { + var declaration = resolver.getReferencedDeclarationWithCollidingName(node); + if (declaration && !(ts.isClassLike(declaration) && isPartOfClassBody(declaration, node))) { + return ts.setTextRange(ts.getGeneratedNameForNode(ts.getNameOfDeclaration(declaration)), node); + } + } + return node; + } + function isPartOfClassBody(declaration, node) { + var currentNode = ts.getParseTreeNode(node); + if (!currentNode || currentNode === declaration || currentNode.end <= declaration.pos || currentNode.pos >= declaration.end) { + // if the node has no correlation to a parse tree node, its definitely not + // part of the body. + // if the node is outside of the document range of the declaration, its + // definitely not part of the body. + return false; + } + var blockScope = ts.getEnclosingBlockScopeContainer(declaration); + while (currentNode) { + if (currentNode === blockScope || currentNode === declaration) { + // if we are in the enclosing block scope of the declaration, we are definitely + // not inside the class body. + return false; + } + if (ts.isClassElement(currentNode) && currentNode.parent === declaration) { + return true; + } + currentNode = currentNode.parent; + } + return false; + } + /** + * Substitutes `this` when contained within an arrow function. + * + * @param node The ThisKeyword node. + */ + function substituteThisKeyword(node) { + if (enabledSubstitutions & 1 /* CapturedThis */ + && hierarchyFacts & 16 /* CapturesThis */) { + return ts.setTextRange(ts.createFileLevelUniqueName("_this"), node); + } + return node; + } + function getClassMemberPrefix(node, member) { + return ts.hasModifier(member, 32 /* Static */) + ? ts.getInternalName(node) + : ts.createPropertyAccess(ts.getInternalName(node), "prototype"); + } + function hasSynthesizedDefaultSuperCall(constructor, hasExtendsClause) { + if (!constructor || !hasExtendsClause) { + return false; + } + if (ts.some(constructor.parameters)) { + return false; + } + var statement = ts.firstOrUndefined(constructor.body.statements); + if (!statement || !ts.nodeIsSynthesized(statement) || statement.kind !== 221 /* ExpressionStatement */) { + return false; + } + var statementExpression = statement.expression; + if (!ts.nodeIsSynthesized(statementExpression) || statementExpression.kind !== 191 /* CallExpression */) { + return false; + } + var callTarget = statementExpression.expression; + if (!ts.nodeIsSynthesized(callTarget) || callTarget.kind !== 98 /* SuperKeyword */) { + return false; + } + var callArgument = ts.singleOrUndefined(statementExpression.arguments); + if (!callArgument || !ts.nodeIsSynthesized(callArgument) || callArgument.kind !== 208 /* SpreadElement */) { + return false; + } + var expression = callArgument.expression; + return ts.isIdentifier(expression) && expression.escapedText === "arguments"; + } + } + ts.transformES2015 = transformES2015; + function createExtendsHelper(context, name) { + context.requestEmitHelper(extendsHelper); + return ts.createCall(ts.getHelperName("__extends"), + /*typeArguments*/ undefined, [ + name, + ts.createFileLevelUniqueName("_super") + ]); + } + function createTemplateObjectHelper(context, cooked, raw) { + context.requestEmitHelper(templateObjectHelper); + return ts.createCall(ts.getHelperName("__makeTemplateObject"), + /*typeArguments*/ undefined, [ + cooked, + raw + ]); + } + var extendsHelper = { + name: "typescript:extends", + scoped: false, + priority: 0, + text: "\n var __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return extendStatics(d, b);\n };\n\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n })();" + }; + var templateObjectHelper = { + name: "typescript:makeTemplateObject", + scoped: false, + priority: 0, + text: "\n var __makeTemplateObject = (this && this.__makeTemplateObject) || function (cooked, raw) {\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\n return cooked;\n };" + }; +})(ts || (ts = {})); +/*@internal*/ +var ts; +(function (ts) { + /** + * Transforms ES5 syntax into ES3 syntax. + * + * @param context Context and state information for the transformation. + */ + function transformES5(context) { + var compilerOptions = context.getCompilerOptions(); + // enable emit notification only if using --jsx preserve or react-native + var previousOnEmitNode; + var noSubstitution; + if (compilerOptions.jsx === 1 /* Preserve */ || compilerOptions.jsx === 3 /* ReactNative */) { + previousOnEmitNode = context.onEmitNode; + context.onEmitNode = onEmitNode; + context.enableEmitNotification(262 /* JsxOpeningElement */); + context.enableEmitNotification(263 /* JsxClosingElement */); + context.enableEmitNotification(261 /* JsxSelfClosingElement */); + noSubstitution = []; + } + var previousOnSubstituteNode = context.onSubstituteNode; + context.onSubstituteNode = onSubstituteNode; + context.enableSubstitution(189 /* PropertyAccessExpression */); + context.enableSubstitution(275 /* PropertyAssignment */); + return ts.chainBundle(transformSourceFile); + /** + * Transforms an ES5 source file to ES3. + * + * @param node A SourceFile + */ + function transformSourceFile(node) { + return node; + } + /** + * Called by the printer just before a node is printed. + * + * @param hint A hint as to the intended usage of the node. + * @param node The node to emit. + * @param emitCallback A callback used to emit the node. + */ + function onEmitNode(hint, node, emitCallback) { + switch (node.kind) { + case 262 /* JsxOpeningElement */: + case 263 /* JsxClosingElement */: + case 261 /* JsxSelfClosingElement */: + var tagName = node.tagName; + noSubstitution[ts.getOriginalNodeId(tagName)] = true; + break; + } + previousOnEmitNode(hint, node, emitCallback); + } + /** + * Hooks node substitutions. + * + * @param hint A hint as to the intended usage of the node. + * @param node The node to substitute. + */ + function onSubstituteNode(hint, node) { + if (node.id && noSubstitution && noSubstitution[node.id]) { + return previousOnSubstituteNode(hint, node); + } + node = previousOnSubstituteNode(hint, node); + if (ts.isPropertyAccessExpression(node)) { + return substitutePropertyAccessExpression(node); + } + else if (ts.isPropertyAssignment(node)) { + return substitutePropertyAssignment(node); + } + return node; + } + /** + * Substitutes a PropertyAccessExpression whose name is a reserved word. + * + * @param node A PropertyAccessExpression + */ + function substitutePropertyAccessExpression(node) { + var literalName = trySubstituteReservedName(node.name); + if (literalName) { + return ts.setTextRange(ts.createElementAccess(node.expression, literalName), node); + } + return node; + } + /** + * Substitutes a PropertyAssignment whose name is a reserved word. + * + * @param node A PropertyAssignment + */ + function substitutePropertyAssignment(node) { + var literalName = ts.isIdentifier(node.name) && trySubstituteReservedName(node.name); + if (literalName) { + return ts.updatePropertyAssignment(node, literalName, node.initializer); + } + return node; + } + /** + * If an identifier name is a reserved word, returns a string literal for the name. + * + * @param name An Identifier + */ + function trySubstituteReservedName(name) { + var token = name.originalKeywordKind || (ts.nodeIsSynthesized(name) ? ts.stringToToken(ts.idText(name)) : undefined); + if (token !== undefined && token >= 73 /* FirstReservedWord */ && token <= 108 /* LastReservedWord */) { + return ts.setTextRange(ts.createLiteral(name), name); + } + return undefined; + } + } + ts.transformES5 = transformES5; +})(ts || (ts = {})); +// Transforms generator functions into a compatible ES5 representation with similar runtime +// semantics. This is accomplished by first transforming the body of each generator +// function into an intermediate representation that is the compiled into a JavaScript +// switch statement. +// +// Many functions in this transformer will contain comments indicating the expected +// intermediate representation. For illustrative purposes, the following intermediate +// language is used to define this intermediate representation: +// +// .nop - Performs no operation. +// .local NAME, ... - Define local variable declarations. +// .mark LABEL - Mark the location of a label. +// .br LABEL - Jump to a label. If jumping out of a protected +// region, all .finally blocks are executed. +// .brtrue LABEL, (x) - Jump to a label IIF the expression `x` is truthy. +// If jumping out of a protected region, all .finally +// blocks are executed. +// .brfalse LABEL, (x) - Jump to a label IIF the expression `x` is falsey. +// If jumping out of a protected region, all .finally +// blocks are executed. +// .yield (x) - Yield the value of the optional expression `x`. +// Resume at the next label. +// .yieldstar (x) - Delegate yield to the value of the optional +// expression `x`. Resume at the next label. +// NOTE: `x` must be an Iterator, not an Iterable. +// .loop CONTINUE, BREAK - Marks the beginning of a loop. Any "continue" or +// "break" abrupt completions jump to the CONTINUE or +// BREAK labels, respectively. +// .endloop - Marks the end of a loop. +// .with (x) - Marks the beginning of a WithStatement block, using +// the supplied expression. +// .endwith - Marks the end of a WithStatement. +// .switch - Marks the beginning of a SwitchStatement. +// .endswitch - Marks the end of a SwitchStatement. +// .labeled NAME - Marks the beginning of a LabeledStatement with the +// supplied name. +// .endlabeled - Marks the end of a LabeledStatement. +// .try TRY, CATCH, FINALLY, END - Marks the beginning of a protected region, and the +// labels for each block. +// .catch (x) - Marks the beginning of a catch block. +// .finally - Marks the beginning of a finally block. +// .endfinally - Marks the end of a finally block. +// .endtry - Marks the end of a protected region. +// .throw (x) - Throws the value of the expression `x`. +// .return (x) - Returns the value of the expression `x`. +// +// In addition, the illustrative intermediate representation introduces some special +// variables: +// +// %sent% - Either returns the next value sent to the generator, +// returns the result of a delegated yield, or throws +// the exception sent to the generator. +// %error% - Returns the value of the current exception in a +// catch block. +// +// This intermediate representation is then compiled into JavaScript syntax. The resulting +// compilation output looks something like the following: +// +// function f() { +// var /*locals*/; +// /*functions*/ +// return __generator(function (state) { +// switch (state.label) { +// /*cases per label*/ +// } +// }); +// } +// +// Each of the above instructions corresponds to JavaScript emit similar to the following: +// +// .local NAME | var NAME; +// -------------------------------|---------------------------------------------- +// .mark LABEL | case LABEL: +// -------------------------------|---------------------------------------------- +// .br LABEL | return [3 /*break*/, LABEL]; +// -------------------------------|---------------------------------------------- +// .brtrue LABEL, (x) | if (x) return [3 /*break*/, LABEL]; +// -------------------------------|---------------------------------------------- +// .brfalse LABEL, (x) | if (!(x)) return [3, /*break*/, LABEL]; +// -------------------------------|---------------------------------------------- +// .yield (x) | return [4 /*yield*/, x]; +// .mark RESUME | case RESUME: +// a = %sent%; | a = state.sent(); +// -------------------------------|---------------------------------------------- +// .yieldstar (x) | return [5 /*yield**/, x]; +// .mark RESUME | case RESUME: +// a = %sent%; | a = state.sent(); +// -------------------------------|---------------------------------------------- +// .with (_a) | with (_a) { +// a(); | a(); +// | } +// | state.label = LABEL; +// .mark LABEL | case LABEL: +// | with (_a) { +// b(); | b(); +// | } +// .endwith | +// -------------------------------|---------------------------------------------- +// | case 0: +// | state.trys = []; +// | ... +// .try TRY, CATCH, FINALLY, END | +// .mark TRY | case TRY: +// | state.trys.push([TRY, CATCH, FINALLY, END]); +// .nop | +// a(); | a(); +// .br END | return [3 /*break*/, END]; +// .catch (e) | +// .mark CATCH | case CATCH: +// | e = state.sent(); +// b(); | b(); +// .br END | return [3 /*break*/, END]; +// .finally | +// .mark FINALLY | case FINALLY: +// c(); | c(); +// .endfinally | return [7 /*endfinally*/]; +// .endtry | +// .mark END | case END: +/*@internal*/ +var ts; +(function (ts) { + var OpCode; + (function (OpCode) { + OpCode[OpCode["Nop"] = 0] = "Nop"; + OpCode[OpCode["Statement"] = 1] = "Statement"; + OpCode[OpCode["Assign"] = 2] = "Assign"; + OpCode[OpCode["Break"] = 3] = "Break"; + OpCode[OpCode["BreakWhenTrue"] = 4] = "BreakWhenTrue"; + OpCode[OpCode["BreakWhenFalse"] = 5] = "BreakWhenFalse"; + OpCode[OpCode["Yield"] = 6] = "Yield"; + OpCode[OpCode["YieldStar"] = 7] = "YieldStar"; + OpCode[OpCode["Return"] = 8] = "Return"; + OpCode[OpCode["Throw"] = 9] = "Throw"; + OpCode[OpCode["Endfinally"] = 10] = "Endfinally"; // Marks the end of a `finally` block + })(OpCode || (OpCode = {})); + // whether a generated code block is opening or closing at the current operation for a FunctionBuilder + var BlockAction; + (function (BlockAction) { + BlockAction[BlockAction["Open"] = 0] = "Open"; + BlockAction[BlockAction["Close"] = 1] = "Close"; + })(BlockAction || (BlockAction = {})); + // the kind for a generated code block in a FunctionBuilder + var CodeBlockKind; + (function (CodeBlockKind) { + CodeBlockKind[CodeBlockKind["Exception"] = 0] = "Exception"; + CodeBlockKind[CodeBlockKind["With"] = 1] = "With"; + CodeBlockKind[CodeBlockKind["Switch"] = 2] = "Switch"; + CodeBlockKind[CodeBlockKind["Loop"] = 3] = "Loop"; + CodeBlockKind[CodeBlockKind["Labeled"] = 4] = "Labeled"; + })(CodeBlockKind || (CodeBlockKind = {})); + // the state for a generated code exception block + var ExceptionBlockState; + (function (ExceptionBlockState) { + ExceptionBlockState[ExceptionBlockState["Try"] = 0] = "Try"; + ExceptionBlockState[ExceptionBlockState["Catch"] = 1] = "Catch"; + ExceptionBlockState[ExceptionBlockState["Finally"] = 2] = "Finally"; + ExceptionBlockState[ExceptionBlockState["Done"] = 3] = "Done"; + })(ExceptionBlockState || (ExceptionBlockState = {})); + // NOTE: changes to this enum should be reflected in the __generator helper. + var Instruction; + (function (Instruction) { + Instruction[Instruction["Next"] = 0] = "Next"; + Instruction[Instruction["Throw"] = 1] = "Throw"; + Instruction[Instruction["Return"] = 2] = "Return"; + Instruction[Instruction["Break"] = 3] = "Break"; + Instruction[Instruction["Yield"] = 4] = "Yield"; + Instruction[Instruction["YieldStar"] = 5] = "YieldStar"; + Instruction[Instruction["Catch"] = 6] = "Catch"; + Instruction[Instruction["Endfinally"] = 7] = "Endfinally"; + })(Instruction || (Instruction = {})); + function getInstructionName(instruction) { + switch (instruction) { + case 2 /* Return */: return "return"; + case 3 /* Break */: return "break"; + case 4 /* Yield */: return "yield"; + case 5 /* YieldStar */: return "yield*"; + case 7 /* Endfinally */: return "endfinally"; + default: return undefined; // TODO: GH#18217 + } + } + function transformGenerators(context) { + var resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistFunctionDeclaration = context.hoistFunctionDeclaration, hoistVariableDeclaration = context.hoistVariableDeclaration; + var compilerOptions = context.getCompilerOptions(); + var languageVersion = ts.getEmitScriptTarget(compilerOptions); + var resolver = context.getEmitResolver(); + var previousOnSubstituteNode = context.onSubstituteNode; + context.onSubstituteNode = onSubstituteNode; + var renamedCatchVariables; + var renamedCatchVariableDeclarations; + var inGeneratorFunctionBody; + var inStatementContainingYield; + // The following three arrays store information about generated code blocks. + // All three arrays are correlated by their index. This approach is used over allocating + // objects to store the same information to avoid GC overhead. + // + var blocks; // Information about the code block + var blockOffsets; // The operation offset at which a code block begins or ends + var blockActions; // Whether the code block is opened or closed + var blockStack; // A stack of currently open code blocks + // Labels are used to mark locations in the code that can be the target of a Break (jump) + // operation. These are translated into case clauses in a switch statement. + // The following two arrays are correlated by their index. This approach is used over + // allocating objects to store the same information to avoid GC overhead. + // + var labelOffsets; // The operation offset at which the label is defined. + var labelExpressions; // The NumericLiteral nodes bound to each label. + var nextLabelId = 1; // The next label id to use. + // Operations store information about generated code for the function body. This + // Includes things like statements, assignments, breaks (jumps), and yields. + // The following three arrays are correlated by their index. This approach is used over + // allocating objects to store the same information to avoid GC overhead. + // + var operations; // The operation to perform. + var operationArguments; // The arguments to the operation. + var operationLocations; // The source map location for the operation. + var state; // The name of the state object used by the generator at runtime. + // The following variables store information used by the `build` function: + // + var blockIndex = 0; // The index of the current block. + var labelNumber = 0; // The current label number. + var labelNumbers; + var lastOperationWasAbrupt; // Indicates whether the last operation was abrupt (break/continue). + var lastOperationWasCompletion; // Indicates whether the last operation was a completion (return/throw). + var clauses; // The case clauses generated for labels. + var statements; // The statements for the current label. + var exceptionBlockStack; // A stack of containing exception blocks. + var currentExceptionBlock; // The current exception block. + var withBlockStack; // A stack containing `with` blocks. + return ts.chainBundle(transformSourceFile); + function transformSourceFile(node) { + if (node.isDeclarationFile || (node.transformFlags & 512 /* ContainsGenerator */) === 0) { + return node; + } + var visited = ts.visitEachChild(node, visitor, context); + ts.addEmitHelpers(visited, context.readEmitHelpers()); + return visited; + } + /** + * Visits a node. + * + * @param node The node to visit. + */ + function visitor(node) { + var transformFlags = node.transformFlags; + if (inStatementContainingYield) { + return visitJavaScriptInStatementContainingYield(node); + } + else if (inGeneratorFunctionBody) { + return visitJavaScriptInGeneratorFunctionBody(node); + } + else if (transformFlags & 256 /* Generator */) { + return visitGenerator(node); + } + else if (transformFlags & 512 /* ContainsGenerator */) { + return ts.visitEachChild(node, visitor, context); + } + else { + return node; + } + } + /** + * Visits a node that is contained within a statement that contains yield. + * + * @param node The node to visit. + */ + function visitJavaScriptInStatementContainingYield(node) { + switch (node.kind) { + case 223 /* DoStatement */: + return visitDoStatement(node); + case 224 /* WhileStatement */: + return visitWhileStatement(node); + case 232 /* SwitchStatement */: + return visitSwitchStatement(node); + case 233 /* LabeledStatement */: + return visitLabeledStatement(node); + default: + return visitJavaScriptInGeneratorFunctionBody(node); + } + } + /** + * Visits a node that is contained within a generator function. + * + * @param node The node to visit. + */ + function visitJavaScriptInGeneratorFunctionBody(node) { + switch (node.kind) { + case 239 /* FunctionDeclaration */: + return visitFunctionDeclaration(node); + case 196 /* FunctionExpression */: + return visitFunctionExpression(node); + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + return visitAccessorDeclaration(node); + case 219 /* VariableStatement */: + return visitVariableStatement(node); + case 225 /* ForStatement */: + return visitForStatement(node); + case 226 /* ForInStatement */: + return visitForInStatement(node); + case 229 /* BreakStatement */: + return visitBreakStatement(node); + case 228 /* ContinueStatement */: + return visitContinueStatement(node); + case 230 /* ReturnStatement */: + return visitReturnStatement(node); + default: + if (node.transformFlags & 4194304 /* ContainsYield */) { + return visitJavaScriptContainingYield(node); + } + else if (node.transformFlags & (512 /* ContainsGenerator */ | 8388608 /* ContainsHoistedDeclarationOrCompletion */)) { + return ts.visitEachChild(node, visitor, context); + } + else { + return node; + } + } + } + /** + * Visits a node that contains a YieldExpression. + * + * @param node The node to visit. + */ + function visitJavaScriptContainingYield(node) { + switch (node.kind) { + case 204 /* BinaryExpression */: + return visitBinaryExpression(node); + case 205 /* ConditionalExpression */: + return visitConditionalExpression(node); + case 207 /* YieldExpression */: + return visitYieldExpression(node); + case 187 /* ArrayLiteralExpression */: + return visitArrayLiteralExpression(node); + case 188 /* ObjectLiteralExpression */: + return visitObjectLiteralExpression(node); + case 190 /* ElementAccessExpression */: + return visitElementAccessExpression(node); + case 191 /* CallExpression */: + return visitCallExpression(node); + case 192 /* NewExpression */: + return visitNewExpression(node); + default: + return ts.visitEachChild(node, visitor, context); + } + } + /** + * Visits a generator function. + * + * @param node The node to visit. + */ + function visitGenerator(node) { + switch (node.kind) { + case 239 /* FunctionDeclaration */: + return visitFunctionDeclaration(node); + case 196 /* FunctionExpression */: + return visitFunctionExpression(node); + default: + return ts.Debug.failBadSyntaxKind(node); + } + } + /** + * Visits a function declaration. + * + * This will be called when one of the following conditions are met: + * - The function declaration is a generator function. + * - The function declaration is contained within the body of a generator function. + * + * @param node The node to visit. + */ + function visitFunctionDeclaration(node) { + // Currently, we only support generators that were originally async functions. + if (node.asteriskToken) { + node = ts.setOriginalNode(ts.setTextRange(ts.createFunctionDeclaration( + /*decorators*/ undefined, node.modifiers, + /*asteriskToken*/ undefined, node.name, + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, transformGeneratorFunctionBody(node.body)), + /*location*/ node), node); + } + else { + var savedInGeneratorFunctionBody = inGeneratorFunctionBody; + var savedInStatementContainingYield = inStatementContainingYield; + inGeneratorFunctionBody = false; + inStatementContainingYield = false; + node = ts.visitEachChild(node, visitor, context); + inGeneratorFunctionBody = savedInGeneratorFunctionBody; + inStatementContainingYield = savedInStatementContainingYield; + } + if (inGeneratorFunctionBody) { + // Function declarations in a generator function body are hoisted + // to the top of the lexical scope and elided from the current statement. + hoistFunctionDeclaration(node); + return undefined; + } + else { + return node; + } + } + /** + * Visits a function expression. + * + * This will be called when one of the following conditions are met: + * - The function expression is a generator function. + * - The function expression is contained within the body of a generator function. + * + * @param node The node to visit. + */ + function visitFunctionExpression(node) { + // Currently, we only support generators that were originally async functions. + if (node.asteriskToken) { + node = ts.setOriginalNode(ts.setTextRange(ts.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, node.name, + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, transformGeneratorFunctionBody(node.body)), + /*location*/ node), node); + } + else { + var savedInGeneratorFunctionBody = inGeneratorFunctionBody; + var savedInStatementContainingYield = inStatementContainingYield; + inGeneratorFunctionBody = false; + inStatementContainingYield = false; + node = ts.visitEachChild(node, visitor, context); + inGeneratorFunctionBody = savedInGeneratorFunctionBody; + inStatementContainingYield = savedInStatementContainingYield; + } + return node; + } + /** + * Visits a get or set accessor declaration. + * + * This will be called when one of the following conditions are met: + * - The accessor is contained within the body of a generator function. + * + * @param node The node to visit. + */ + function visitAccessorDeclaration(node) { + var savedInGeneratorFunctionBody = inGeneratorFunctionBody; + var savedInStatementContainingYield = inStatementContainingYield; + inGeneratorFunctionBody = false; + inStatementContainingYield = false; + node = ts.visitEachChild(node, visitor, context); + inGeneratorFunctionBody = savedInGeneratorFunctionBody; + inStatementContainingYield = savedInStatementContainingYield; + return node; + } + /** + * Transforms the body of a generator function declaration. + * + * @param node The function body to transform. + */ + function transformGeneratorFunctionBody(body) { + // Save existing generator state + var statements = []; + var savedInGeneratorFunctionBody = inGeneratorFunctionBody; + var savedInStatementContainingYield = inStatementContainingYield; + var savedBlocks = blocks; + var savedBlockOffsets = blockOffsets; + var savedBlockActions = blockActions; + var savedBlockStack = blockStack; + var savedLabelOffsets = labelOffsets; + var savedLabelExpressions = labelExpressions; + var savedNextLabelId = nextLabelId; + var savedOperations = operations; + var savedOperationArguments = operationArguments; + var savedOperationLocations = operationLocations; + var savedState = state; + // Initialize generator state + inGeneratorFunctionBody = true; + inStatementContainingYield = false; + blocks = undefined; + blockOffsets = undefined; + blockActions = undefined; + blockStack = undefined; + labelOffsets = undefined; + labelExpressions = undefined; + nextLabelId = 1; + operations = undefined; + operationArguments = undefined; + operationLocations = undefined; + state = ts.createTempVariable(/*recordTempVariable*/ undefined); + // Build the generator + resumeLexicalEnvironment(); + var statementOffset = ts.addPrologue(statements, body.statements, /*ensureUseStrict*/ false, visitor); + transformAndEmitStatements(body.statements, statementOffset); + var buildResult = build(); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + statements.push(ts.createReturn(buildResult)); + // Restore previous generator state + inGeneratorFunctionBody = savedInGeneratorFunctionBody; + inStatementContainingYield = savedInStatementContainingYield; + blocks = savedBlocks; + blockOffsets = savedBlockOffsets; + blockActions = savedBlockActions; + blockStack = savedBlockStack; + labelOffsets = savedLabelOffsets; + labelExpressions = savedLabelExpressions; + nextLabelId = savedNextLabelId; + operations = savedOperations; + operationArguments = savedOperationArguments; + operationLocations = savedOperationLocations; + state = savedState; + return ts.setTextRange(ts.createBlock(statements, body.multiLine), body); + } + /** + * Visits a variable statement. + * + * This will be called when one of the following conditions are met: + * - The variable statement is contained within the body of a generator function. + * + * @param node The node to visit. + */ + function visitVariableStatement(node) { + if (node.transformFlags & 4194304 /* ContainsYield */) { + transformAndEmitVariableDeclarationList(node.declarationList); + return undefined; + } + else { + // Do not hoist custom prologues. + if (ts.getEmitFlags(node) & 1048576 /* CustomPrologue */) { + return node; + } + for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { + var variable = _a[_i]; + hoistVariableDeclaration(variable.name); + } + var variables = ts.getInitializedVariables(node.declarationList); + if (variables.length === 0) { + return undefined; + } + return ts.setSourceMapRange(ts.createExpressionStatement(ts.inlineExpressions(ts.map(variables, transformInitializedVariable))), node); + } + } + /** + * Visits a binary expression. + * + * This will be called when one of the following conditions are met: + * - The node contains a YieldExpression. + * + * @param node The node to visit. + */ + function visitBinaryExpression(node) { + var assoc = ts.getExpressionAssociativity(node); + switch (assoc) { + case 0 /* Left */: + return visitLeftAssociativeBinaryExpression(node); + case 1 /* Right */: + return visitRightAssociativeBinaryExpression(node); + default: + return ts.Debug.assertNever(assoc); + } + } + function isCompoundAssignment(kind) { + return kind >= 60 /* FirstCompoundAssignment */ + && kind <= 71 /* LastCompoundAssignment */; + } + function getOperatorForCompoundAssignment(kind) { + switch (kind) { + case 60 /* PlusEqualsToken */: return 38 /* PlusToken */; + case 61 /* MinusEqualsToken */: return 39 /* MinusToken */; + case 62 /* AsteriskEqualsToken */: return 40 /* AsteriskToken */; + case 63 /* AsteriskAsteriskEqualsToken */: return 41 /* AsteriskAsteriskToken */; + case 64 /* SlashEqualsToken */: return 42 /* SlashToken */; + case 65 /* PercentEqualsToken */: return 43 /* PercentToken */; + case 66 /* LessThanLessThanEqualsToken */: return 46 /* LessThanLessThanToken */; + case 67 /* GreaterThanGreaterThanEqualsToken */: return 47 /* GreaterThanGreaterThanToken */; + case 68 /* GreaterThanGreaterThanGreaterThanEqualsToken */: return 48 /* GreaterThanGreaterThanGreaterThanToken */; + case 69 /* AmpersandEqualsToken */: return 49 /* AmpersandToken */; + case 70 /* BarEqualsToken */: return 50 /* BarToken */; + case 71 /* CaretEqualsToken */: return 51 /* CaretToken */; + } + } + /** + * Visits a right-associative binary expression containing `yield`. + * + * @param node The node to visit. + */ + function visitRightAssociativeBinaryExpression(node) { + var left = node.left, right = node.right; + if (containsYield(right)) { + var target = void 0; + switch (left.kind) { + case 189 /* PropertyAccessExpression */: + // [source] + // a.b = yield; + // + // [intermediate] + // .local _a + // _a = a; + // .yield resumeLabel + // .mark resumeLabel + // _a.b = %sent%; + target = ts.updatePropertyAccess(left, cacheExpression(ts.visitNode(left.expression, visitor, ts.isLeftHandSideExpression)), left.name); + break; + case 190 /* ElementAccessExpression */: + // [source] + // a[b] = yield; + // + // [intermediate] + // .local _a, _b + // _a = a; + // _b = b; + // .yield resumeLabel + // .mark resumeLabel + // _a[_b] = %sent%; + target = ts.updateElementAccess(left, cacheExpression(ts.visitNode(left.expression, visitor, ts.isLeftHandSideExpression)), cacheExpression(ts.visitNode(left.argumentExpression, visitor, ts.isExpression))); + break; + default: + target = ts.visitNode(left, visitor, ts.isExpression); + break; + } + var operator = node.operatorToken.kind; + if (isCompoundAssignment(operator)) { + return ts.setTextRange(ts.createAssignment(target, ts.setTextRange(ts.createBinary(cacheExpression(target), getOperatorForCompoundAssignment(operator), ts.visitNode(right, visitor, ts.isExpression)), node)), node); + } + else { + return ts.updateBinary(node, target, ts.visitNode(right, visitor, ts.isExpression)); + } + } + return ts.visitEachChild(node, visitor, context); + } + function visitLeftAssociativeBinaryExpression(node) { + if (containsYield(node.right)) { + if (ts.isLogicalOperator(node.operatorToken.kind)) { + return visitLogicalBinaryExpression(node); + } + else if (node.operatorToken.kind === 27 /* CommaToken */) { + return visitCommaExpression(node); + } + // [source] + // a() + (yield) + c() + // + // [intermediate] + // .local _a + // _a = a(); + // .yield resumeLabel + // _a + %sent% + c() + var clone_5 = ts.getMutableClone(node); + clone_5.left = cacheExpression(ts.visitNode(node.left, visitor, ts.isExpression)); + clone_5.right = ts.visitNode(node.right, visitor, ts.isExpression); + return clone_5; + } + return ts.visitEachChild(node, visitor, context); + } + /** + * Visits a logical binary expression containing `yield`. + * + * @param node A node to visit. + */ + function visitLogicalBinaryExpression(node) { + // Logical binary expressions (`&&` and `||`) are shortcutting expressions and need + // to be transformed as such: + // + // [source] + // x = a() && yield; + // + // [intermediate] + // .local _a + // _a = a(); + // .brfalse resultLabel, (_a) + // .yield resumeLabel + // .mark resumeLabel + // _a = %sent%; + // .mark resultLabel + // x = _a; + // + // [source] + // x = a() || yield; + // + // [intermediate] + // .local _a + // _a = a(); + // .brtrue resultLabel, (_a) + // .yield resumeLabel + // .mark resumeLabel + // _a = %sent%; + // .mark resultLabel + // x = _a; + var resultLabel = defineLabel(); + var resultLocal = declareLocal(); + emitAssignment(resultLocal, ts.visitNode(node.left, visitor, ts.isExpression), /*location*/ node.left); + if (node.operatorToken.kind === 54 /* AmpersandAmpersandToken */) { + // Logical `&&` shortcuts when the left-hand operand is falsey. + emitBreakWhenFalse(resultLabel, resultLocal, /*location*/ node.left); + } + else { + // Logical `||` shortcuts when the left-hand operand is truthy. + emitBreakWhenTrue(resultLabel, resultLocal, /*location*/ node.left); + } + emitAssignment(resultLocal, ts.visitNode(node.right, visitor, ts.isExpression), /*location*/ node.right); + markLabel(resultLabel); + return resultLocal; + } + /** + * Visits a comma expression containing `yield`. + * + * @param node The node to visit. + */ + function visitCommaExpression(node) { + // [source] + // x = a(), yield, b(); + // + // [intermediate] + // a(); + // .yield resumeLabel + // .mark resumeLabel + // x = %sent%, b(); + var pendingExpressions = []; + visit(node.left); + visit(node.right); + return ts.inlineExpressions(pendingExpressions); + function visit(node) { + if (ts.isBinaryExpression(node) && node.operatorToken.kind === 27 /* CommaToken */) { + visit(node.left); + visit(node.right); + } + else { + if (containsYield(node) && pendingExpressions.length > 0) { + emitWorker(1 /* Statement */, [ts.createExpressionStatement(ts.inlineExpressions(pendingExpressions))]); + pendingExpressions = []; + } + pendingExpressions.push(ts.visitNode(node, visitor, ts.isExpression)); + } + } + } + /** + * Visits a conditional expression containing `yield`. + * + * @param node The node to visit. + */ + function visitConditionalExpression(node) { + // [source] + // x = a() ? yield : b(); + // + // [intermediate] + // .local _a + // .brfalse whenFalseLabel, (a()) + // .yield resumeLabel + // .mark resumeLabel + // _a = %sent%; + // .br resultLabel + // .mark whenFalseLabel + // _a = b(); + // .mark resultLabel + // x = _a; + // We only need to perform a specific transformation if a `yield` expression exists + // in either the `whenTrue` or `whenFalse` branches. + // A `yield` in the condition will be handled by the normal visitor. + if (containsYield(node.whenTrue) || containsYield(node.whenFalse)) { + var whenFalseLabel = defineLabel(); + var resultLabel = defineLabel(); + var resultLocal = declareLocal(); + emitBreakWhenFalse(whenFalseLabel, ts.visitNode(node.condition, visitor, ts.isExpression), /*location*/ node.condition); + emitAssignment(resultLocal, ts.visitNode(node.whenTrue, visitor, ts.isExpression), /*location*/ node.whenTrue); + emitBreak(resultLabel); + markLabel(whenFalseLabel); + emitAssignment(resultLocal, ts.visitNode(node.whenFalse, visitor, ts.isExpression), /*location*/ node.whenFalse); + markLabel(resultLabel); + return resultLocal; + } + return ts.visitEachChild(node, visitor, context); + } + /** + * Visits a `yield` expression. + * + * @param node The node to visit. + */ + function visitYieldExpression(node) { + // [source] + // x = yield a(); + // + // [intermediate] + // .yield resumeLabel, (a()) + // .mark resumeLabel + // x = %sent%; + var resumeLabel = defineLabel(); + var expression = ts.visitNode(node.expression, visitor, ts.isExpression); + if (node.asteriskToken) { + var iterator = (ts.getEmitFlags(node.expression) & 8388608 /* Iterator */) === 0 + ? ts.createValuesHelper(context, expression, /*location*/ node) + : expression; + emitYieldStar(iterator, /*location*/ node); + } + else { + emitYield(expression, /*location*/ node); + } + markLabel(resumeLabel); + return createGeneratorResume(/*location*/ node); + } + /** + * Visits an ArrayLiteralExpression that contains a YieldExpression. + * + * @param node The node to visit. + */ + function visitArrayLiteralExpression(node) { + return visitElements(node.elements, /*leadingElement*/ undefined, /*location*/ undefined, node.multiLine); + } + /** + * Visits an array of expressions containing one or more YieldExpression nodes + * and returns an expression for the resulting value. + * + * @param elements The elements to visit. + * @param multiLine Whether array literals created should be emitted on multiple lines. + */ + function visitElements(elements, leadingElement, location, multiLine) { + // [source] + // ar = [1, yield, 2]; + // + // [intermediate] + // .local _a + // _a = [1]; + // .yield resumeLabel + // .mark resumeLabel + // ar = _a.concat([%sent%, 2]); + var numInitialElements = countInitialNodesWithoutYield(elements); + var temp; + if (numInitialElements > 0) { + temp = declareLocal(); + var initialElements = ts.visitNodes(elements, visitor, ts.isExpression, 0, numInitialElements); + emitAssignment(temp, ts.createArrayLiteral(leadingElement + ? [leadingElement].concat(initialElements) : initialElements)); + leadingElement = undefined; + } + var expressions = ts.reduceLeft(elements, reduceElement, [], numInitialElements); + return temp + ? ts.createArrayConcat(temp, [ts.createArrayLiteral(expressions, multiLine)]) + : ts.setTextRange(ts.createArrayLiteral(leadingElement ? [leadingElement].concat(expressions) : expressions, multiLine), location); + function reduceElement(expressions, element) { + if (containsYield(element) && expressions.length > 0) { + var hasAssignedTemp = temp !== undefined; + if (!temp) { + temp = declareLocal(); + } + emitAssignment(temp, hasAssignedTemp + ? ts.createArrayConcat(temp, [ts.createArrayLiteral(expressions, multiLine)]) + : ts.createArrayLiteral(leadingElement ? [leadingElement].concat(expressions) : expressions, multiLine)); + leadingElement = undefined; + expressions = []; + } + expressions.push(ts.visitNode(element, visitor, ts.isExpression)); + return expressions; + } + } + function visitObjectLiteralExpression(node) { + // [source] + // o = { + // a: 1, + // b: yield, + // c: 2 + // }; + // + // [intermediate] + // .local _a + // _a = { + // a: 1 + // }; + // .yield resumeLabel + // .mark resumeLabel + // o = (_a.b = %sent%, + // _a.c = 2, + // _a); + var properties = node.properties; + var multiLine = node.multiLine; + var numInitialProperties = countInitialNodesWithoutYield(properties); + var temp = declareLocal(); + emitAssignment(temp, ts.createObjectLiteral(ts.visitNodes(properties, visitor, ts.isObjectLiteralElementLike, 0, numInitialProperties), multiLine)); + var expressions = ts.reduceLeft(properties, reduceProperty, [], numInitialProperties); + expressions.push(multiLine ? ts.startOnNewLine(ts.getMutableClone(temp)) : temp); + return ts.inlineExpressions(expressions); + function reduceProperty(expressions, property) { + if (containsYield(property) && expressions.length > 0) { + emitStatement(ts.createExpressionStatement(ts.inlineExpressions(expressions))); + expressions = []; + } + var expression = ts.createExpressionForObjectLiteralElementLike(node, property, temp); + var visited = ts.visitNode(expression, visitor, ts.isExpression); + if (visited) { + if (multiLine) { + ts.startOnNewLine(visited); + } + expressions.push(visited); + } + return expressions; + } + } + /** + * Visits an ElementAccessExpression that contains a YieldExpression. + * + * @param node The node to visit. + */ + function visitElementAccessExpression(node) { + if (containsYield(node.argumentExpression)) { + // [source] + // a = x[yield]; + // + // [intermediate] + // .local _a + // _a = x; + // .yield resumeLabel + // .mark resumeLabel + // a = _a[%sent%] + var clone_6 = ts.getMutableClone(node); + clone_6.expression = cacheExpression(ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression)); + clone_6.argumentExpression = ts.visitNode(node.argumentExpression, visitor, ts.isExpression); + return clone_6; + } + return ts.visitEachChild(node, visitor, context); + } + function visitCallExpression(node) { + if (!ts.isImportCall(node) && ts.forEach(node.arguments, containsYield)) { + // [source] + // a.b(1, yield, 2); + // + // [intermediate] + // .local _a, _b, _c + // _b = (_a = a).b; + // _c = [1]; + // .yield resumeLabel + // .mark resumeLabel + // _b.apply(_a, _c.concat([%sent%, 2])); + var _a = ts.createCallBinding(node.expression, hoistVariableDeclaration, languageVersion, /*cacheIdentifiers*/ true), target = _a.target, thisArg = _a.thisArg; + return ts.setOriginalNode(ts.createFunctionApply(cacheExpression(ts.visitNode(target, visitor, ts.isLeftHandSideExpression)), thisArg, visitElements(node.arguments), + /*location*/ node), node); + } + return ts.visitEachChild(node, visitor, context); + } + function visitNewExpression(node) { + if (ts.forEach(node.arguments, containsYield)) { + // [source] + // new a.b(1, yield, 2); + // + // [intermediate] + // .local _a, _b, _c + // _b = (_a = a.b).bind; + // _c = [1]; + // .yield resumeLabel + // .mark resumeLabel + // new (_b.apply(_a, _c.concat([%sent%, 2]))); + var _a = ts.createCallBinding(ts.createPropertyAccess(node.expression, "bind"), hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg; + return ts.setOriginalNode(ts.setTextRange(ts.createNew(ts.createFunctionApply(cacheExpression(ts.visitNode(target, visitor, ts.isExpression)), thisArg, visitElements(node.arguments, + /*leadingElement*/ ts.createVoidZero())), + /*typeArguments*/ undefined, []), node), node); + } + return ts.visitEachChild(node, visitor, context); + } + function transformAndEmitStatements(statements, start) { + if (start === void 0) { start = 0; } + var numStatements = statements.length; + for (var i = start; i < numStatements; i++) { + transformAndEmitStatement(statements[i]); + } + } + function transformAndEmitEmbeddedStatement(node) { + if (ts.isBlock(node)) { + transformAndEmitStatements(node.statements); + } + else { + transformAndEmitStatement(node); + } + } + function transformAndEmitStatement(node) { + var savedInStatementContainingYield = inStatementContainingYield; + if (!inStatementContainingYield) { + inStatementContainingYield = containsYield(node); + } + transformAndEmitStatementWorker(node); + inStatementContainingYield = savedInStatementContainingYield; + } + function transformAndEmitStatementWorker(node) { + switch (node.kind) { + case 218 /* Block */: + return transformAndEmitBlock(node); + case 221 /* ExpressionStatement */: + return transformAndEmitExpressionStatement(node); + case 222 /* IfStatement */: + return transformAndEmitIfStatement(node); + case 223 /* DoStatement */: + return transformAndEmitDoStatement(node); + case 224 /* WhileStatement */: + return transformAndEmitWhileStatement(node); + case 225 /* ForStatement */: + return transformAndEmitForStatement(node); + case 226 /* ForInStatement */: + return transformAndEmitForInStatement(node); + case 228 /* ContinueStatement */: + return transformAndEmitContinueStatement(node); + case 229 /* BreakStatement */: + return transformAndEmitBreakStatement(node); + case 230 /* ReturnStatement */: + return transformAndEmitReturnStatement(node); + case 231 /* WithStatement */: + return transformAndEmitWithStatement(node); + case 232 /* SwitchStatement */: + return transformAndEmitSwitchStatement(node); + case 233 /* LabeledStatement */: + return transformAndEmitLabeledStatement(node); + case 234 /* ThrowStatement */: + return transformAndEmitThrowStatement(node); + case 235 /* TryStatement */: + return transformAndEmitTryStatement(node); + default: + return emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + } + function transformAndEmitBlock(node) { + if (containsYield(node)) { + transformAndEmitStatements(node.statements); + } + else { + emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + } + function transformAndEmitExpressionStatement(node) { + emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + function transformAndEmitVariableDeclarationList(node) { + for (var _i = 0, _a = node.declarations; _i < _a.length; _i++) { + var variable = _a[_i]; + var name = ts.getSynthesizedClone(variable.name); + ts.setCommentRange(name, variable.name); + hoistVariableDeclaration(name); + } + var variables = ts.getInitializedVariables(node); + var numVariables = variables.length; + var variablesWritten = 0; + var pendingExpressions = []; + while (variablesWritten < numVariables) { + for (var i = variablesWritten; i < numVariables; i++) { + var variable = variables[i]; + if (containsYield(variable.initializer) && pendingExpressions.length > 0) { + break; + } + pendingExpressions.push(transformInitializedVariable(variable)); + } + if (pendingExpressions.length) { + emitStatement(ts.createExpressionStatement(ts.inlineExpressions(pendingExpressions))); + variablesWritten += pendingExpressions.length; + pendingExpressions = []; + } + } + return undefined; + } + function transformInitializedVariable(node) { + return ts.setSourceMapRange(ts.createAssignment(ts.setSourceMapRange(ts.getSynthesizedClone(node.name), node.name), ts.visitNode(node.initializer, visitor, ts.isExpression)), node); + } + function transformAndEmitIfStatement(node) { + if (containsYield(node)) { + // [source] + // if (x) + // /*thenStatement*/ + // else + // /*elseStatement*/ + // + // [intermediate] + // .brfalse elseLabel, (x) + // /*thenStatement*/ + // .br endLabel + // .mark elseLabel + // /*elseStatement*/ + // .mark endLabel + if (containsYield(node.thenStatement) || containsYield(node.elseStatement)) { + var endLabel = defineLabel(); + var elseLabel = node.elseStatement ? defineLabel() : undefined; + emitBreakWhenFalse(node.elseStatement ? elseLabel : endLabel, ts.visitNode(node.expression, visitor, ts.isExpression), /*location*/ node.expression); + transformAndEmitEmbeddedStatement(node.thenStatement); + if (node.elseStatement) { + emitBreak(endLabel); + markLabel(elseLabel); + transformAndEmitEmbeddedStatement(node.elseStatement); + } + markLabel(endLabel); + } + else { + emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + } + else { + emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + } + function transformAndEmitDoStatement(node) { + if (containsYield(node)) { + // [source] + // do { + // /*body*/ + // } + // while (i < 10); + // + // [intermediate] + // .loop conditionLabel, endLabel + // .mark loopLabel + // /*body*/ + // .mark conditionLabel + // .brtrue loopLabel, (i < 10) + // .endloop + // .mark endLabel + var conditionLabel = defineLabel(); + var loopLabel = defineLabel(); + beginLoopBlock(/*continueLabel*/ conditionLabel); + markLabel(loopLabel); + transformAndEmitEmbeddedStatement(node.statement); + markLabel(conditionLabel); + emitBreakWhenTrue(loopLabel, ts.visitNode(node.expression, visitor, ts.isExpression)); + endLoopBlock(); + } + else { + emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + } + function visitDoStatement(node) { + if (inStatementContainingYield) { + beginScriptLoopBlock(); + node = ts.visitEachChild(node, visitor, context); + endLoopBlock(); + return node; + } + else { + return ts.visitEachChild(node, visitor, context); + } + } + function transformAndEmitWhileStatement(node) { + if (containsYield(node)) { + // [source] + // while (i < 10) { + // /*body*/ + // } + // + // [intermediate] + // .loop loopLabel, endLabel + // .mark loopLabel + // .brfalse endLabel, (i < 10) + // /*body*/ + // .br loopLabel + // .endloop + // .mark endLabel + var loopLabel = defineLabel(); + var endLabel = beginLoopBlock(loopLabel); + markLabel(loopLabel); + emitBreakWhenFalse(endLabel, ts.visitNode(node.expression, visitor, ts.isExpression)); + transformAndEmitEmbeddedStatement(node.statement); + emitBreak(loopLabel); + endLoopBlock(); + } + else { + emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + } + function visitWhileStatement(node) { + if (inStatementContainingYield) { + beginScriptLoopBlock(); + node = ts.visitEachChild(node, visitor, context); + endLoopBlock(); + return node; + } + else { + return ts.visitEachChild(node, visitor, context); + } + } + function transformAndEmitForStatement(node) { + if (containsYield(node)) { + // [source] + // for (var i = 0; i < 10; i++) { + // /*body*/ + // } + // + // [intermediate] + // .local i + // i = 0; + // .loop incrementLabel, endLoopLabel + // .mark conditionLabel + // .brfalse endLoopLabel, (i < 10) + // /*body*/ + // .mark incrementLabel + // i++; + // .br conditionLabel + // .endloop + // .mark endLoopLabel + var conditionLabel = defineLabel(); + var incrementLabel = defineLabel(); + var endLabel = beginLoopBlock(incrementLabel); + if (node.initializer) { + var initializer = node.initializer; + if (ts.isVariableDeclarationList(initializer)) { + transformAndEmitVariableDeclarationList(initializer); + } + else { + emitStatement(ts.setTextRange(ts.createExpressionStatement(ts.visitNode(initializer, visitor, ts.isExpression)), initializer)); + } + } + markLabel(conditionLabel); + if (node.condition) { + emitBreakWhenFalse(endLabel, ts.visitNode(node.condition, visitor, ts.isExpression)); + } + transformAndEmitEmbeddedStatement(node.statement); + markLabel(incrementLabel); + if (node.incrementor) { + emitStatement(ts.setTextRange(ts.createExpressionStatement(ts.visitNode(node.incrementor, visitor, ts.isExpression)), node.incrementor)); + } + emitBreak(conditionLabel); + endLoopBlock(); + } + else { + emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + } + function visitForStatement(node) { + if (inStatementContainingYield) { + beginScriptLoopBlock(); + } + var initializer = node.initializer; + if (initializer && ts.isVariableDeclarationList(initializer)) { + for (var _i = 0, _a = initializer.declarations; _i < _a.length; _i++) { + var variable = _a[_i]; + hoistVariableDeclaration(variable.name); + } + var variables = ts.getInitializedVariables(initializer); + node = ts.updateFor(node, variables.length > 0 + ? ts.inlineExpressions(ts.map(variables, transformInitializedVariable)) + : undefined, ts.visitNode(node.condition, visitor, ts.isExpression), ts.visitNode(node.incrementor, visitor, ts.isExpression), ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); + } + else { + node = ts.visitEachChild(node, visitor, context); + } + if (inStatementContainingYield) { + endLoopBlock(); + } + return node; + } + function transformAndEmitForInStatement(node) { + // TODO(rbuckton): Source map locations + if (containsYield(node)) { + // [source] + // for (var p in o) { + // /*body*/ + // } + // + // [intermediate] + // .local _a, _b, _i + // _a = []; + // for (_b in o) _a.push(_b); + // _i = 0; + // .loop incrementLabel, endLoopLabel + // .mark conditionLabel + // .brfalse endLoopLabel, (_i < _a.length) + // p = _a[_i]; + // /*body*/ + // .mark incrementLabel + // _b++; + // .br conditionLabel + // .endloop + // .mark endLoopLabel + var keysArray = declareLocal(); // _a + var key = declareLocal(); // _b + var keysIndex = ts.createLoopVariable(); // _i + var initializer = node.initializer; + hoistVariableDeclaration(keysIndex); + emitAssignment(keysArray, ts.createArrayLiteral()); + emitStatement(ts.createForIn(key, ts.visitNode(node.expression, visitor, ts.isExpression), ts.createExpressionStatement(ts.createCall(ts.createPropertyAccess(keysArray, "push"), + /*typeArguments*/ undefined, [key])))); + emitAssignment(keysIndex, ts.createLiteral(0)); + var conditionLabel = defineLabel(); + var incrementLabel = defineLabel(); + var endLabel = beginLoopBlock(incrementLabel); + markLabel(conditionLabel); + emitBreakWhenFalse(endLabel, ts.createLessThan(keysIndex, ts.createPropertyAccess(keysArray, "length"))); + var variable = void 0; + if (ts.isVariableDeclarationList(initializer)) { + for (var _i = 0, _a = initializer.declarations; _i < _a.length; _i++) { + var variable_1 = _a[_i]; + hoistVariableDeclaration(variable_1.name); + } + variable = ts.getSynthesizedClone(initializer.declarations[0].name); + } + else { + variable = ts.visitNode(initializer, visitor, ts.isExpression); + ts.Debug.assert(ts.isLeftHandSideExpression(variable)); + } + emitAssignment(variable, ts.createElementAccess(keysArray, keysIndex)); + transformAndEmitEmbeddedStatement(node.statement); + markLabel(incrementLabel); + emitStatement(ts.createExpressionStatement(ts.createPostfixIncrement(keysIndex))); + emitBreak(conditionLabel); + endLoopBlock(); + } + else { + emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + } + function visitForInStatement(node) { + // [source] + // for (var x in a) { + // /*body*/ + // } + // + // [intermediate] + // .local x + // .loop + // for (x in a) { + // /*body*/ + // } + // .endloop + if (inStatementContainingYield) { + beginScriptLoopBlock(); + } + var initializer = node.initializer; + if (ts.isVariableDeclarationList(initializer)) { + for (var _i = 0, _a = initializer.declarations; _i < _a.length; _i++) { + var variable = _a[_i]; + hoistVariableDeclaration(variable.name); + } + node = ts.updateForIn(node, initializer.declarations[0].name, ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); + } + else { + node = ts.visitEachChild(node, visitor, context); + } + if (inStatementContainingYield) { + endLoopBlock(); + } + return node; + } + function transformAndEmitContinueStatement(node) { + var label = findContinueTarget(node.label ? ts.idText(node.label) : undefined); + if (label > 0) { + emitBreak(label, /*location*/ node); + } + else { + // invalid continue without a containing loop. Leave the node as is, per #17875. + emitStatement(node); + } + } + function visitContinueStatement(node) { + if (inStatementContainingYield) { + var label = findContinueTarget(node.label && ts.idText(node.label)); + if (label > 0) { + return createInlineBreak(label, /*location*/ node); + } + } + return ts.visitEachChild(node, visitor, context); + } + function transformAndEmitBreakStatement(node) { + var label = findBreakTarget(node.label ? ts.idText(node.label) : undefined); + if (label > 0) { + emitBreak(label, /*location*/ node); + } + else { + // invalid break without a containing loop, switch, or labeled statement. Leave the node as is, per #17875. + emitStatement(node); + } + } + function visitBreakStatement(node) { + if (inStatementContainingYield) { + var label = findBreakTarget(node.label && ts.idText(node.label)); + if (label > 0) { + return createInlineBreak(label, /*location*/ node); + } + } + return ts.visitEachChild(node, visitor, context); + } + function transformAndEmitReturnStatement(node) { + emitReturn(ts.visitNode(node.expression, visitor, ts.isExpression), + /*location*/ node); + } + function visitReturnStatement(node) { + return createInlineReturn(ts.visitNode(node.expression, visitor, ts.isExpression), + /*location*/ node); + } + function transformAndEmitWithStatement(node) { + if (containsYield(node)) { + // [source] + // with (x) { + // /*body*/ + // } + // + // [intermediate] + // .with (x) + // /*body*/ + // .endwith + beginWithBlock(cacheExpression(ts.visitNode(node.expression, visitor, ts.isExpression))); + transformAndEmitEmbeddedStatement(node.statement); + endWithBlock(); + } + else { + emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + } + function transformAndEmitSwitchStatement(node) { + if (containsYield(node.caseBlock)) { + // [source] + // switch (x) { + // case a: + // /*caseStatements*/ + // case b: + // /*caseStatements*/ + // default: + // /*defaultStatements*/ + // } + // + // [intermediate] + // .local _a + // .switch endLabel + // _a = x; + // switch (_a) { + // case a: + // .br clauseLabels[0] + // } + // switch (_a) { + // case b: + // .br clauseLabels[1] + // } + // .br clauseLabels[2] + // .mark clauseLabels[0] + // /*caseStatements*/ + // .mark clauseLabels[1] + // /*caseStatements*/ + // .mark clauseLabels[2] + // /*caseStatements*/ + // .endswitch + // .mark endLabel + var caseBlock = node.caseBlock; + var numClauses = caseBlock.clauses.length; + var endLabel = beginSwitchBlock(); + var expression = cacheExpression(ts.visitNode(node.expression, visitor, ts.isExpression)); + // Create labels for each clause and find the index of the first default clause. + var clauseLabels = []; + var defaultClauseIndex = -1; + for (var i = 0; i < numClauses; i++) { + var clause = caseBlock.clauses[i]; + clauseLabels.push(defineLabel()); + if (clause.kind === 272 /* DefaultClause */ && defaultClauseIndex === -1) { + defaultClauseIndex = i; + } + } + // Emit switch statements for each run of case clauses either from the first case + // clause or the next case clause with a `yield` in its expression, up to the next + // case clause with a `yield` in its expression. + var clausesWritten = 0; + var pendingClauses = []; + while (clausesWritten < numClauses) { + var defaultClausesSkipped = 0; + for (var i = clausesWritten; i < numClauses; i++) { + var clause = caseBlock.clauses[i]; + if (clause.kind === 271 /* CaseClause */) { + if (containsYield(clause.expression) && pendingClauses.length > 0) { + break; + } + pendingClauses.push(ts.createCaseClause(ts.visitNode(clause.expression, visitor, ts.isExpression), [ + createInlineBreak(clauseLabels[i], /*location*/ clause.expression) + ])); + } + else { + defaultClausesSkipped++; + } + } + if (pendingClauses.length) { + emitStatement(ts.createSwitch(expression, ts.createCaseBlock(pendingClauses))); + clausesWritten += pendingClauses.length; + pendingClauses = []; + } + if (defaultClausesSkipped > 0) { + clausesWritten += defaultClausesSkipped; + defaultClausesSkipped = 0; + } + } + if (defaultClauseIndex >= 0) { + emitBreak(clauseLabels[defaultClauseIndex]); + } + else { + emitBreak(endLabel); + } + for (var i = 0; i < numClauses; i++) { + markLabel(clauseLabels[i]); + transformAndEmitStatements(caseBlock.clauses[i].statements); + } + endSwitchBlock(); + } + else { + emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + } + function visitSwitchStatement(node) { + if (inStatementContainingYield) { + beginScriptSwitchBlock(); + } + node = ts.visitEachChild(node, visitor, context); + if (inStatementContainingYield) { + endSwitchBlock(); + } + return node; + } + function transformAndEmitLabeledStatement(node) { + if (containsYield(node)) { + // [source] + // x: { + // /*body*/ + // } + // + // [intermediate] + // .labeled "x", endLabel + // /*body*/ + // .endlabeled + // .mark endLabel + beginLabeledBlock(ts.idText(node.label)); + transformAndEmitEmbeddedStatement(node.statement); + endLabeledBlock(); + } + else { + emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + } + function visitLabeledStatement(node) { + if (inStatementContainingYield) { + beginScriptLabeledBlock(ts.idText(node.label)); + } + node = ts.visitEachChild(node, visitor, context); + if (inStatementContainingYield) { + endLabeledBlock(); + } + return node; + } + function transformAndEmitThrowStatement(node) { + emitThrow(ts.visitNode(node.expression, visitor, ts.isExpression), + /*location*/ node); + } + function transformAndEmitTryStatement(node) { + if (containsYield(node)) { + // [source] + // try { + // /*tryBlock*/ + // } + // catch (e) { + // /*catchBlock*/ + // } + // finally { + // /*finallyBlock*/ + // } + // + // [intermediate] + // .local _a + // .try tryLabel, catchLabel, finallyLabel, endLabel + // .mark tryLabel + // .nop + // /*tryBlock*/ + // .br endLabel + // .catch + // .mark catchLabel + // _a = %error%; + // /*catchBlock*/ + // .br endLabel + // .finally + // .mark finallyLabel + // /*finallyBlock*/ + // .endfinally + // .endtry + // .mark endLabel + beginExceptionBlock(); + transformAndEmitEmbeddedStatement(node.tryBlock); + if (node.catchClause) { + beginCatchBlock(node.catchClause.variableDeclaration); // TODO: GH#18217 + transformAndEmitEmbeddedStatement(node.catchClause.block); + } + if (node.finallyBlock) { + beginFinallyBlock(); + transformAndEmitEmbeddedStatement(node.finallyBlock); + } + endExceptionBlock(); + } + else { + emitStatement(ts.visitEachChild(node, visitor, context)); + } + } + function containsYield(node) { + return !!node && (node.transformFlags & 4194304 /* ContainsYield */) !== 0; + } + function countInitialNodesWithoutYield(nodes) { + var numNodes = nodes.length; + for (var i = 0; i < numNodes; i++) { + if (containsYield(nodes[i])) { + return i; + } + } + return -1; + } + function onSubstituteNode(hint, node) { + node = previousOnSubstituteNode(hint, node); + if (hint === 1 /* Expression */) { + return substituteExpression(node); + } + return node; + } + function substituteExpression(node) { + if (ts.isIdentifier(node)) { + return substituteExpressionIdentifier(node); + } + return node; + } + function substituteExpressionIdentifier(node) { + if (!ts.isGeneratedIdentifier(node) && renamedCatchVariables && renamedCatchVariables.has(ts.idText(node))) { + var original = ts.getOriginalNode(node); + if (ts.isIdentifier(original) && original.parent) { + var declaration = resolver.getReferencedValueDeclaration(original); + if (declaration) { + var name = renamedCatchVariableDeclarations[ts.getOriginalNodeId(declaration)]; + if (name) { + var clone_7 = ts.getMutableClone(name); + ts.setSourceMapRange(clone_7, node); + ts.setCommentRange(clone_7, node); + return clone_7; + } + } + } + } + return node; + } + function cacheExpression(node) { + var temp; + if (ts.isGeneratedIdentifier(node) || ts.getEmitFlags(node) & 4096 /* HelperName */) { + return node; + } + temp = ts.createTempVariable(hoistVariableDeclaration); + emitAssignment(temp, node, /*location*/ node); + return temp; + } + function declareLocal(name) { + var temp = name + ? ts.createUniqueName(name) + : ts.createTempVariable(/*recordTempVariable*/ undefined); + hoistVariableDeclaration(temp); + return temp; + } + /** + * Defines a label, uses as the target of a Break operation. + */ + function defineLabel() { + if (!labelOffsets) { + labelOffsets = []; + } + var label = nextLabelId; + nextLabelId++; + labelOffsets[label] = -1; + return label; + } + /** + * Marks the current operation with the specified label. + */ + function markLabel(label) { + ts.Debug.assert(labelOffsets !== undefined, "No labels were defined."); + labelOffsets[label] = operations ? operations.length : 0; + } + /** + * Begins a block operation (With, Break/Continue, Try/Catch/Finally) + * + * @param block Information about the block. + */ + function beginBlock(block) { + if (!blocks) { + blocks = []; + blockActions = []; + blockOffsets = []; + blockStack = []; + } + var index = blockActions.length; + blockActions[index] = 0 /* Open */; + blockOffsets[index] = operations ? operations.length : 0; + blocks[index] = block; + blockStack.push(block); + return index; + } + /** + * Ends the current block operation. + */ + function endBlock() { + var block = peekBlock(); + if (block === undefined) + return ts.Debug.fail("beginBlock was never called."); + var index = blockActions.length; + blockActions[index] = 1 /* Close */; + blockOffsets[index] = operations ? operations.length : 0; + blocks[index] = block; + blockStack.pop(); + return block; + } + /** + * Gets the current open block. + */ + function peekBlock() { + return ts.lastOrUndefined(blockStack); + } + /** + * Gets the kind of the current open block. + */ + function peekBlockKind() { + var block = peekBlock(); + return block && block.kind; + } + /** + * Begins a code block for a generated `with` statement. + * + * @param expression An identifier representing expression for the `with` block. + */ + function beginWithBlock(expression) { + var startLabel = defineLabel(); + var endLabel = defineLabel(); + markLabel(startLabel); + beginBlock({ + kind: 1 /* With */, + expression: expression, + startLabel: startLabel, + endLabel: endLabel + }); + } + /** + * Ends a code block for a generated `with` statement. + */ + function endWithBlock() { + ts.Debug.assert(peekBlockKind() === 1 /* With */); + var block = endBlock(); + markLabel(block.endLabel); + } + /** + * Begins a code block for a generated `try` statement. + */ + function beginExceptionBlock() { + var startLabel = defineLabel(); + var endLabel = defineLabel(); + markLabel(startLabel); + beginBlock({ + kind: 0 /* Exception */, + state: 0 /* Try */, + startLabel: startLabel, + endLabel: endLabel + }); + emitNop(); + return endLabel; + } + /** + * Enters the `catch` clause of a generated `try` statement. + * + * @param variable The catch variable. + */ + function beginCatchBlock(variable) { + ts.Debug.assert(peekBlockKind() === 0 /* Exception */); + // generated identifiers should already be unique within a file + var name; + if (ts.isGeneratedIdentifier(variable.name)) { + name = variable.name; + hoistVariableDeclaration(variable.name); + } + else { + var text = ts.idText(variable.name); + name = declareLocal(text); + if (!renamedCatchVariables) { + renamedCatchVariables = ts.createMap(); + renamedCatchVariableDeclarations = []; + context.enableSubstitution(72 /* Identifier */); + } + renamedCatchVariables.set(text, true); + renamedCatchVariableDeclarations[ts.getOriginalNodeId(variable)] = name; + } + var exception = peekBlock(); + ts.Debug.assert(exception.state < 1 /* Catch */); + var endLabel = exception.endLabel; + emitBreak(endLabel); + var catchLabel = defineLabel(); + markLabel(catchLabel); + exception.state = 1 /* Catch */; + exception.catchVariable = name; + exception.catchLabel = catchLabel; + emitAssignment(name, ts.createCall(ts.createPropertyAccess(state, "sent"), /*typeArguments*/ undefined, [])); + emitNop(); + } + /** + * Enters the `finally` block of a generated `try` statement. + */ + function beginFinallyBlock() { + ts.Debug.assert(peekBlockKind() === 0 /* Exception */); + var exception = peekBlock(); + ts.Debug.assert(exception.state < 2 /* Finally */); + var endLabel = exception.endLabel; + emitBreak(endLabel); + var finallyLabel = defineLabel(); + markLabel(finallyLabel); + exception.state = 2 /* Finally */; + exception.finallyLabel = finallyLabel; + } + /** + * Ends the code block for a generated `try` statement. + */ + function endExceptionBlock() { + ts.Debug.assert(peekBlockKind() === 0 /* Exception */); + var exception = endBlock(); + var state = exception.state; + if (state < 2 /* Finally */) { + emitBreak(exception.endLabel); + } + else { + emitEndfinally(); + } + markLabel(exception.endLabel); + emitNop(); + exception.state = 3 /* Done */; + } + /** + * Begins a code block that supports `break` or `continue` statements that are defined in + * the source tree and not from generated code. + * + * @param labelText Names from containing labeled statements. + */ + function beginScriptLoopBlock() { + beginBlock({ + kind: 3 /* Loop */, + isScript: true, + breakLabel: -1, + continueLabel: -1 + }); + } + /** + * Begins a code block that supports `break` or `continue` statements that are defined in + * generated code. Returns a label used to mark the operation to which to jump when a + * `break` statement targets this block. + * + * @param continueLabel A Label used to mark the operation to which to jump when a + * `continue` statement targets this block. + */ + function beginLoopBlock(continueLabel) { + var breakLabel = defineLabel(); + beginBlock({ + kind: 3 /* Loop */, + isScript: false, + breakLabel: breakLabel, + continueLabel: continueLabel, + }); + return breakLabel; + } + /** + * Ends a code block that supports `break` or `continue` statements that are defined in + * generated code or in the source tree. + */ + function endLoopBlock() { + ts.Debug.assert(peekBlockKind() === 3 /* Loop */); + var block = endBlock(); + var breakLabel = block.breakLabel; + if (!block.isScript) { + markLabel(breakLabel); + } + } + /** + * Begins a code block that supports `break` statements that are defined in the source + * tree and not from generated code. + * + */ + function beginScriptSwitchBlock() { + beginBlock({ + kind: 2 /* Switch */, + isScript: true, + breakLabel: -1 + }); + } + /** + * Begins a code block that supports `break` statements that are defined in generated code. + * Returns a label used to mark the operation to which to jump when a `break` statement + * targets this block. + */ + function beginSwitchBlock() { + var breakLabel = defineLabel(); + beginBlock({ + kind: 2 /* Switch */, + isScript: false, + breakLabel: breakLabel, + }); + return breakLabel; + } + /** + * Ends a code block that supports `break` statements that are defined in generated code. + */ + function endSwitchBlock() { + ts.Debug.assert(peekBlockKind() === 2 /* Switch */); + var block = endBlock(); + var breakLabel = block.breakLabel; + if (!block.isScript) { + markLabel(breakLabel); + } + } + function beginScriptLabeledBlock(labelText) { + beginBlock({ + kind: 4 /* Labeled */, + isScript: true, + labelText: labelText, + breakLabel: -1 + }); + } + function beginLabeledBlock(labelText) { + var breakLabel = defineLabel(); + beginBlock({ + kind: 4 /* Labeled */, + isScript: false, + labelText: labelText, + breakLabel: breakLabel + }); + } + function endLabeledBlock() { + ts.Debug.assert(peekBlockKind() === 4 /* Labeled */); + var block = endBlock(); + if (!block.isScript) { + markLabel(block.breakLabel); + } + } + /** + * Indicates whether the provided block supports `break` statements. + * + * @param block A code block. + */ + function supportsUnlabeledBreak(block) { + return block.kind === 2 /* Switch */ + || block.kind === 3 /* Loop */; + } + /** + * Indicates whether the provided block supports `break` statements with labels. + * + * @param block A code block. + */ + function supportsLabeledBreakOrContinue(block) { + return block.kind === 4 /* Labeled */; + } + /** + * Indicates whether the provided block supports `continue` statements. + * + * @param block A code block. + */ + function supportsUnlabeledContinue(block) { + return block.kind === 3 /* Loop */; + } + function hasImmediateContainingLabeledBlock(labelText, start) { + for (var j = start; j >= 0; j--) { + var containingBlock = blockStack[j]; + if (supportsLabeledBreakOrContinue(containingBlock)) { + if (containingBlock.labelText === labelText) { + return true; + } + } + else { + break; + } + } + return false; + } + /** + * Finds the label that is the target for a `break` statement. + * + * @param labelText An optional name of a containing labeled statement. + */ + function findBreakTarget(labelText) { + if (blockStack) { + if (labelText) { + for (var i = blockStack.length - 1; i >= 0; i--) { + var block = blockStack[i]; + if (supportsLabeledBreakOrContinue(block) && block.labelText === labelText) { + return block.breakLabel; + } + else if (supportsUnlabeledBreak(block) && hasImmediateContainingLabeledBlock(labelText, i - 1)) { + return block.breakLabel; + } + } + } + else { + for (var i = blockStack.length - 1; i >= 0; i--) { + var block = blockStack[i]; + if (supportsUnlabeledBreak(block)) { + return block.breakLabel; + } + } + } + } + return 0; + } + /** + * Finds the label that is the target for a `continue` statement. + * + * @param labelText An optional name of a containing labeled statement. + */ + function findContinueTarget(labelText) { + if (blockStack) { + if (labelText) { + for (var i = blockStack.length - 1; i >= 0; i--) { + var block = blockStack[i]; + if (supportsUnlabeledContinue(block) && hasImmediateContainingLabeledBlock(labelText, i - 1)) { + return block.continueLabel; + } + } + } + else { + for (var i = blockStack.length - 1; i >= 0; i--) { + var block = blockStack[i]; + if (supportsUnlabeledContinue(block)) { + return block.continueLabel; + } + } + } + } + return 0; + } + /** + * Creates an expression that can be used to indicate the value for a label. + * + * @param label A label. + */ + function createLabel(label) { + if (label !== undefined && label > 0) { + if (labelExpressions === undefined) { + labelExpressions = []; + } + var expression = ts.createLiteral(-1); + if (labelExpressions[label] === undefined) { + labelExpressions[label] = [expression]; + } + else { + labelExpressions[label].push(expression); + } + return expression; + } + return ts.createOmittedExpression(); + } + /** + * Creates a numeric literal for the provided instruction. + */ + function createInstruction(instruction) { + var literal = ts.createLiteral(instruction); + ts.addSyntheticTrailingComment(literal, 3 /* MultiLineCommentTrivia */, getInstructionName(instruction)); + return literal; + } + /** + * Creates a statement that can be used indicate a Break operation to the provided label. + * + * @param label A label. + * @param location An optional source map location for the statement. + */ + function createInlineBreak(label, location) { + ts.Debug.assertLessThan(0, label, "Invalid label"); + return ts.setTextRange(ts.createReturn(ts.createArrayLiteral([ + createInstruction(3 /* Break */), + createLabel(label) + ])), location); + } + /** + * Creates a statement that can be used indicate a Return operation. + * + * @param expression The expression for the return statement. + * @param location An optional source map location for the statement. + */ + function createInlineReturn(expression, location) { + return ts.setTextRange(ts.createReturn(ts.createArrayLiteral(expression + ? [createInstruction(2 /* Return */), expression] + : [createInstruction(2 /* Return */)])), location); + } + /** + * Creates an expression that can be used to resume from a Yield operation. + */ + function createGeneratorResume(location) { + return ts.setTextRange(ts.createCall(ts.createPropertyAccess(state, "sent"), + /*typeArguments*/ undefined, []), location); + } + /** + * Emits an empty instruction. + */ + function emitNop() { + emitWorker(0 /* Nop */); + } + /** + * Emits a Statement. + * + * @param node A statement. + */ + function emitStatement(node) { + if (node) { + emitWorker(1 /* Statement */, [node]); + } + else { + emitNop(); + } + } + /** + * Emits an Assignment operation. + * + * @param left The left-hand side of the assignment. + * @param right The right-hand side of the assignment. + * @param location An optional source map location for the assignment. + */ + function emitAssignment(left, right, location) { + emitWorker(2 /* Assign */, [left, right], location); + } + /** + * Emits a Break operation to the specified label. + * + * @param label A label. + * @param location An optional source map location for the assignment. + */ + function emitBreak(label, location) { + emitWorker(3 /* Break */, [label], location); + } + /** + * Emits a Break operation to the specified label when a condition evaluates to a truthy + * value at runtime. + * + * @param label A label. + * @param condition The condition. + * @param location An optional source map location for the assignment. + */ + function emitBreakWhenTrue(label, condition, location) { + emitWorker(4 /* BreakWhenTrue */, [label, condition], location); + } + /** + * Emits a Break to the specified label when a condition evaluates to a falsey value at + * runtime. + * + * @param label A label. + * @param condition The condition. + * @param location An optional source map location for the assignment. + */ + function emitBreakWhenFalse(label, condition, location) { + emitWorker(5 /* BreakWhenFalse */, [label, condition], location); + } + /** + * Emits a YieldStar operation for the provided expression. + * + * @param expression An optional value for the yield operation. + * @param location An optional source map location for the assignment. + */ + function emitYieldStar(expression, location) { + emitWorker(7 /* YieldStar */, [expression], location); + } + /** + * Emits a Yield operation for the provided expression. + * + * @param expression An optional value for the yield operation. + * @param location An optional source map location for the assignment. + */ + function emitYield(expression, location) { + emitWorker(6 /* Yield */, [expression], location); + } + /** + * Emits a Return operation for the provided expression. + * + * @param expression An optional value for the operation. + * @param location An optional source map location for the assignment. + */ + function emitReturn(expression, location) { + emitWorker(8 /* Return */, [expression], location); + } + /** + * Emits a Throw operation for the provided expression. + * + * @param expression A value for the operation. + * @param location An optional source map location for the assignment. + */ + function emitThrow(expression, location) { + emitWorker(9 /* Throw */, [expression], location); + } + /** + * Emits an Endfinally operation. This is used to handle `finally` block semantics. + */ + function emitEndfinally() { + emitWorker(10 /* Endfinally */); + } + /** + * Emits an operation. + * + * @param code The OpCode for the operation. + * @param args The optional arguments for the operation. + */ + function emitWorker(code, args, location) { + if (operations === undefined) { + operations = []; + operationArguments = []; + operationLocations = []; + } + if (labelOffsets === undefined) { + // mark entry point + markLabel(defineLabel()); + } + var operationIndex = operations.length; + operations[operationIndex] = code; + operationArguments[operationIndex] = args; + operationLocations[operationIndex] = location; + } + /** + * Builds the generator function body. + */ + function build() { + blockIndex = 0; + labelNumber = 0; + labelNumbers = undefined; + lastOperationWasAbrupt = false; + lastOperationWasCompletion = false; + clauses = undefined; + statements = undefined; + exceptionBlockStack = undefined; + currentExceptionBlock = undefined; + withBlockStack = undefined; + var buildResult = buildStatements(); + return createGeneratorHelper(context, ts.setEmitFlags(ts.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, state)], + /*type*/ undefined, ts.createBlock(buildResult, + /*multiLine*/ buildResult.length > 0)), 524288 /* ReuseTempVariableScope */)); + } + /** + * Builds the statements for the generator function body. + */ + function buildStatements() { + if (operations) { + for (var operationIndex = 0; operationIndex < operations.length; operationIndex++) { + writeOperation(operationIndex); + } + flushFinalLabel(operations.length); + } + else { + flushFinalLabel(0); + } + if (clauses) { + var labelExpression = ts.createPropertyAccess(state, "label"); + var switchStatement = ts.createSwitch(labelExpression, ts.createCaseBlock(clauses)); + return [ts.startOnNewLine(switchStatement)]; + } + if (statements) { + return statements; + } + return []; + } + /** + * Flush the current label and advance to a new label. + */ + function flushLabel() { + if (!statements) { + return; + } + appendLabel(/*markLabelEnd*/ !lastOperationWasAbrupt); + lastOperationWasAbrupt = false; + lastOperationWasCompletion = false; + labelNumber++; + } + /** + * Flush the final label of the generator function body. + */ + function flushFinalLabel(operationIndex) { + if (isFinalLabelReachable(operationIndex)) { + tryEnterLabel(operationIndex); + withBlockStack = undefined; + writeReturn(/*expression*/ undefined, /*operationLocation*/ undefined); + } + if (statements && clauses) { + appendLabel(/*markLabelEnd*/ false); + } + updateLabelExpressions(); + } + /** + * Tests whether the final label of the generator function body + * is reachable by user code. + */ + function isFinalLabelReachable(operationIndex) { + // if the last operation was *not* a completion (return/throw) then + // the final label is reachable. + if (!lastOperationWasCompletion) { + return true; + } + // if there are no labels defined or referenced, then the final label is + // not reachable. + if (!labelOffsets || !labelExpressions) { + return false; + } + // if the label for this offset is referenced, then the final label + // is reachable. + for (var label = 0; label < labelOffsets.length; label++) { + if (labelOffsets[label] === operationIndex && labelExpressions[label]) { + return true; + } + } + return false; + } + /** + * Appends a case clause for the last label and sets the new label. + * + * @param markLabelEnd Indicates that the transition between labels was a fall-through + * from a previous case clause and the change in labels should be + * reflected on the `state` object. + */ + function appendLabel(markLabelEnd) { + if (!clauses) { + clauses = []; + } + if (statements) { + if (withBlockStack) { + // The previous label was nested inside one or more `with` blocks, so we + // surround the statements in generated `with` blocks to create the same environment. + for (var i = withBlockStack.length - 1; i >= 0; i--) { + var withBlock = withBlockStack[i]; + statements = [ts.createWith(withBlock.expression, ts.createBlock(statements))]; + } + } + if (currentExceptionBlock) { + // The previous label was nested inside of an exception block, so we must + // indicate entry into a protected region by pushing the label numbers + // for each block in the protected region. + var startLabel = currentExceptionBlock.startLabel, catchLabel = currentExceptionBlock.catchLabel, finallyLabel = currentExceptionBlock.finallyLabel, endLabel = currentExceptionBlock.endLabel; + statements.unshift(ts.createExpressionStatement(ts.createCall(ts.createPropertyAccess(ts.createPropertyAccess(state, "trys"), "push"), + /*typeArguments*/ undefined, [ + ts.createArrayLiteral([ + createLabel(startLabel), + createLabel(catchLabel), + createLabel(finallyLabel), + createLabel(endLabel) + ]) + ]))); + currentExceptionBlock = undefined; + } + if (markLabelEnd) { + // The case clause for the last label falls through to this label, so we + // add an assignment statement to reflect the change in labels. + statements.push(ts.createExpressionStatement(ts.createAssignment(ts.createPropertyAccess(state, "label"), ts.createLiteral(labelNumber + 1)))); + } + } + clauses.push(ts.createCaseClause(ts.createLiteral(labelNumber), statements || [])); + statements = undefined; + } + /** + * Tries to enter into a new label at the current operation index. + */ + function tryEnterLabel(operationIndex) { + if (!labelOffsets) { + return; + } + for (var label = 0; label < labelOffsets.length; label++) { + if (labelOffsets[label] === operationIndex) { + flushLabel(); + if (labelNumbers === undefined) { + labelNumbers = []; + } + if (labelNumbers[labelNumber] === undefined) { + labelNumbers[labelNumber] = [label]; + } + else { + labelNumbers[labelNumber].push(label); + } + } + } + } + /** + * Updates literal expressions for labels with actual label numbers. + */ + function updateLabelExpressions() { + if (labelExpressions !== undefined && labelNumbers !== undefined) { + for (var labelNumber_1 = 0; labelNumber_1 < labelNumbers.length; labelNumber_1++) { + var labels = labelNumbers[labelNumber_1]; + if (labels !== undefined) { + for (var _i = 0, labels_1 = labels; _i < labels_1.length; _i++) { + var label = labels_1[_i]; + var expressions = labelExpressions[label]; + if (expressions !== undefined) { + for (var _a = 0, expressions_1 = expressions; _a < expressions_1.length; _a++) { + var expression = expressions_1[_a]; + expression.text = String(labelNumber_1); + } + } + } + } + } + } + } + /** + * Tries to enter or leave a code block. + */ + function tryEnterOrLeaveBlock(operationIndex) { + if (blocks) { + for (; blockIndex < blockActions.length && blockOffsets[blockIndex] <= operationIndex; blockIndex++) { + var block = blocks[blockIndex]; + var blockAction = blockActions[blockIndex]; + switch (block.kind) { + case 0 /* Exception */: + if (blockAction === 0 /* Open */) { + if (!exceptionBlockStack) { + exceptionBlockStack = []; + } + if (!statements) { + statements = []; + } + exceptionBlockStack.push(currentExceptionBlock); + currentExceptionBlock = block; + } + else if (blockAction === 1 /* Close */) { + currentExceptionBlock = exceptionBlockStack.pop(); + } + break; + case 1 /* With */: + if (blockAction === 0 /* Open */) { + if (!withBlockStack) { + withBlockStack = []; + } + withBlockStack.push(block); + } + else if (blockAction === 1 /* Close */) { + withBlockStack.pop(); + } + break; + // default: do nothing + } + } + } + } + /** + * Writes an operation as a statement to the current label's statement list. + * + * @param operation The OpCode of the operation + */ + function writeOperation(operationIndex) { + tryEnterLabel(operationIndex); + tryEnterOrLeaveBlock(operationIndex); + // early termination, nothing else to process in this label + if (lastOperationWasAbrupt) { + return; + } + lastOperationWasAbrupt = false; + lastOperationWasCompletion = false; + var opcode = operations[operationIndex]; + if (opcode === 0 /* Nop */) { + return; + } + else if (opcode === 10 /* Endfinally */) { + return writeEndfinally(); + } + var args = operationArguments[operationIndex]; + if (opcode === 1 /* Statement */) { + return writeStatement(args[0]); + } + var location = operationLocations[operationIndex]; + switch (opcode) { + case 2 /* Assign */: + return writeAssign(args[0], args[1], location); + case 3 /* Break */: + return writeBreak(args[0], location); + case 4 /* BreakWhenTrue */: + return writeBreakWhenTrue(args[0], args[1], location); + case 5 /* BreakWhenFalse */: + return writeBreakWhenFalse(args[0], args[1], location); + case 6 /* Yield */: + return writeYield(args[0], location); + case 7 /* YieldStar */: + return writeYieldStar(args[0], location); + case 8 /* Return */: + return writeReturn(args[0], location); + case 9 /* Throw */: + return writeThrow(args[0], location); + } + } + /** + * Writes a statement to the current label's statement list. + * + * @param statement A statement to write. + */ + function writeStatement(statement) { + if (statement) { + if (!statements) { + statements = [statement]; + } + else { + statements.push(statement); + } + } + } + /** + * Writes an Assign operation to the current label's statement list. + * + * @param left The left-hand side of the assignment. + * @param right The right-hand side of the assignment. + * @param operationLocation The source map location for the operation. + */ + function writeAssign(left, right, operationLocation) { + writeStatement(ts.setTextRange(ts.createExpressionStatement(ts.createAssignment(left, right)), operationLocation)); + } + /** + * Writes a Throw operation to the current label's statement list. + * + * @param expression The value to throw. + * @param operationLocation The source map location for the operation. + */ + function writeThrow(expression, operationLocation) { + lastOperationWasAbrupt = true; + lastOperationWasCompletion = true; + writeStatement(ts.setTextRange(ts.createThrow(expression), operationLocation)); + } + /** + * Writes a Return operation to the current label's statement list. + * + * @param expression The value to return. + * @param operationLocation The source map location for the operation. + */ + function writeReturn(expression, operationLocation) { + lastOperationWasAbrupt = true; + lastOperationWasCompletion = true; + writeStatement(ts.setEmitFlags(ts.setTextRange(ts.createReturn(ts.createArrayLiteral(expression + ? [createInstruction(2 /* Return */), expression] + : [createInstruction(2 /* Return */)])), operationLocation), 384 /* NoTokenSourceMaps */)); + } + /** + * Writes a Break operation to the current label's statement list. + * + * @param label The label for the Break. + * @param operationLocation The source map location for the operation. + */ + function writeBreak(label, operationLocation) { + lastOperationWasAbrupt = true; + writeStatement(ts.setEmitFlags(ts.setTextRange(ts.createReturn(ts.createArrayLiteral([ + createInstruction(3 /* Break */), + createLabel(label) + ])), operationLocation), 384 /* NoTokenSourceMaps */)); + } + /** + * Writes a BreakWhenTrue operation to the current label's statement list. + * + * @param label The label for the Break. + * @param condition The condition for the Break. + * @param operationLocation The source map location for the operation. + */ + function writeBreakWhenTrue(label, condition, operationLocation) { + writeStatement(ts.setEmitFlags(ts.createIf(condition, ts.setEmitFlags(ts.setTextRange(ts.createReturn(ts.createArrayLiteral([ + createInstruction(3 /* Break */), + createLabel(label) + ])), operationLocation), 384 /* NoTokenSourceMaps */)), 1 /* SingleLine */)); + } + /** + * Writes a BreakWhenFalse operation to the current label's statement list. + * + * @param label The label for the Break. + * @param condition The condition for the Break. + * @param operationLocation The source map location for the operation. + */ + function writeBreakWhenFalse(label, condition, operationLocation) { + writeStatement(ts.setEmitFlags(ts.createIf(ts.createLogicalNot(condition), ts.setEmitFlags(ts.setTextRange(ts.createReturn(ts.createArrayLiteral([ + createInstruction(3 /* Break */), + createLabel(label) + ])), operationLocation), 384 /* NoTokenSourceMaps */)), 1 /* SingleLine */)); + } + /** + * Writes a Yield operation to the current label's statement list. + * + * @param expression The expression to yield. + * @param operationLocation The source map location for the operation. + */ + function writeYield(expression, operationLocation) { + lastOperationWasAbrupt = true; + writeStatement(ts.setEmitFlags(ts.setTextRange(ts.createReturn(ts.createArrayLiteral(expression + ? [createInstruction(4 /* Yield */), expression] + : [createInstruction(4 /* Yield */)])), operationLocation), 384 /* NoTokenSourceMaps */)); + } + /** + * Writes a YieldStar instruction to the current label's statement list. + * + * @param expression The expression to yield. + * @param operationLocation The source map location for the operation. + */ + function writeYieldStar(expression, operationLocation) { + lastOperationWasAbrupt = true; + writeStatement(ts.setEmitFlags(ts.setTextRange(ts.createReturn(ts.createArrayLiteral([ + createInstruction(5 /* YieldStar */), + expression + ])), operationLocation), 384 /* NoTokenSourceMaps */)); + } + /** + * Writes an Endfinally instruction to the current label's statement list. + */ + function writeEndfinally() { + lastOperationWasAbrupt = true; + writeStatement(ts.createReturn(ts.createArrayLiteral([ + createInstruction(7 /* Endfinally */) + ]))); + } + } + ts.transformGenerators = transformGenerators; + function createGeneratorHelper(context, body) { + context.requestEmitHelper(generatorHelper); + return ts.createCall(ts.getHelperName("__generator"), + /*typeArguments*/ undefined, [ts.createThis(), body]); + } + // The __generator helper is used by down-level transformations to emulate the runtime + // semantics of an ES2015 generator function. When called, this helper returns an + // object that implements the Iterator protocol, in that it has `next`, `return`, and + // `throw` methods that step through the generator when invoked. + // + // parameters: + // @param thisArg The value to use as the `this` binding for the transformed generator body. + // @param body A function that acts as the transformed generator body. + // + // variables: + // _ Persistent state for the generator that is shared between the helper and the + // generator body. The state object has the following members: + // sent() - A method that returns or throws the current completion value. + // label - The next point at which to resume evaluation of the generator body. + // trys - A stack of protected regions (try/catch/finally blocks). + // ops - A stack of pending instructions when inside of a finally block. + // f A value indicating whether the generator is executing. + // y An iterator to delegate for a yield*. + // t A temporary variable that holds one of the following values (note that these + // cases do not overlap): + // - The completion value when resuming from a `yield` or `yield*`. + // - The error value for a catch block. + // - The current protected region (array of try/catch/finally/end labels). + // - The verb (`next`, `throw`, or `return` method) to delegate to the expression + // of a `yield*`. + // - The result of evaluating the verb delegated to the expression of a `yield*`. + // + // functions: + // verb(n) Creates a bound callback to the `step` function for opcode `n`. + // step(op) Evaluates opcodes in a generator body until execution is suspended or + // completed. + // + // The __generator helper understands a limited set of instructions: + // 0: next(value?) - Start or resume the generator with the specified value. + // 1: throw(error) - Resume the generator with an exception. If the generator is + // suspended inside of one or more protected regions, evaluates + // any intervening finally blocks between the current label and + // the nearest catch block or function boundary. If uncaught, the + // exception is thrown to the caller. + // 2: return(value?) - Resume the generator as if with a return. If the generator is + // suspended inside of one or more protected regions, evaluates any + // intervening finally blocks. + // 3: break(label) - Jump to the specified label. If the label is outside of the + // current protected region, evaluates any intervening finally + // blocks. + // 4: yield(value?) - Yield execution to the caller with an optional value. When + // resumed, the generator will continue at the next label. + // 5: yield*(value) - Delegates evaluation to the supplied iterator. When + // delegation completes, the generator will continue at the next + // label. + // 6: catch(error) - Handles an exception thrown from within the generator body. If + // the current label is inside of one or more protected regions, + // evaluates any intervening finally blocks between the current + // label and the nearest catch block or function boundary. If + // uncaught, the exception is thrown to the caller. + // 7: endfinally - Ends a finally block, resuming the last instruction prior to + // entering a finally block. + // + // For examples of how these are used, see the comments in ./transformers/generators.ts + var generatorHelper = { + name: "typescript:generator", + scoped: false, + priority: 6, + text: "\n var __generator = (this && this.__generator) || function (thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (_) try {\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [op[0] & 2, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n };" + }; +})(ts || (ts = {})); +/*@internal*/ +var ts; +(function (ts) { + function transformModule(context) { + function getTransformModuleDelegate(moduleKind) { + switch (moduleKind) { + case ts.ModuleKind.AMD: return transformAMDModule; + case ts.ModuleKind.UMD: return transformUMDModule; + default: return transformCommonJSModule; + } + } + var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; + var compilerOptions = context.getCompilerOptions(); + var resolver = context.getEmitResolver(); + var host = context.getEmitHost(); + var languageVersion = ts.getEmitScriptTarget(compilerOptions); + var moduleKind = ts.getEmitModuleKind(compilerOptions); + var previousOnSubstituteNode = context.onSubstituteNode; + var previousOnEmitNode = context.onEmitNode; + context.onSubstituteNode = onSubstituteNode; + context.onEmitNode = onEmitNode; + context.enableSubstitution(72 /* Identifier */); // Substitutes expression identifiers with imported/exported symbols. + context.enableSubstitution(204 /* BinaryExpression */); // Substitutes assignments to exported symbols. + context.enableSubstitution(202 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols. + context.enableSubstitution(203 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols. + context.enableSubstitution(276 /* ShorthandPropertyAssignment */); // Substitutes shorthand property assignments for imported/exported symbols. + context.enableEmitNotification(279 /* SourceFile */); // Restore state when substituting nodes in a file. + var moduleInfoMap = []; // The ExternalModuleInfo for each file. + var deferredExports = []; // Exports to defer until an EndOfDeclarationMarker is found. + var currentSourceFile; // The current file. + var currentModuleInfo; // The ExternalModuleInfo for the current file. + var noSubstitution; // Set of nodes for which substitution rules should be ignored. + var needUMDDynamicImportHelper; + return ts.chainBundle(transformSourceFile); + /** + * Transforms the module aspects of a SourceFile. + * + * @param node The SourceFile node. + */ + function transformSourceFile(node) { + if (node.isDeclarationFile || + !(ts.isEffectiveExternalModule(node, compilerOptions) || + node.transformFlags & 16777216 /* ContainsDynamicImport */ || + (ts.isJsonSourceFile(node) && ts.hasJsonModuleEmitEnabled(compilerOptions) && (compilerOptions.out || compilerOptions.outFile)))) { + return node; + } + currentSourceFile = node; + currentModuleInfo = ts.collectExternalModuleInfo(node, resolver, compilerOptions); + moduleInfoMap[ts.getOriginalNodeId(node)] = currentModuleInfo; + // Perform the transformation. + var transformModule = getTransformModuleDelegate(moduleKind); + var updated = transformModule(node); + currentSourceFile = undefined; + currentModuleInfo = undefined; + needUMDDynamicImportHelper = false; + return ts.aggregateTransformFlags(updated); + } + function shouldEmitUnderscoreUnderscoreESModule() { + if (!currentModuleInfo.exportEquals && ts.isExternalModule(currentSourceFile)) { + return true; + } + return false; + } + /** + * Transforms a SourceFile into a CommonJS module. + * + * @param node The SourceFile node. + */ + function transformCommonJSModule(node) { + startLexicalEnvironment(); + var statements = []; + var ensureUseStrict = ts.getStrictOptionValue(compilerOptions, "alwaysStrict") || (!compilerOptions.noImplicitUseStrict && ts.isExternalModule(currentSourceFile)); + var statementOffset = ts.addPrologue(statements, node.statements, ensureUseStrict, sourceElementVisitor); + if (shouldEmitUnderscoreUnderscoreESModule()) { + ts.append(statements, createUnderscoreUnderscoreESModule()); + } + ts.append(statements, ts.visitNode(currentModuleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement)); + ts.addRange(statements, ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset)); + addExportEqualsIfNeeded(statements, /*emitAsReturn*/ false); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + var updated = ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements)); + if (currentModuleInfo.hasExportStarsToExportValues && !compilerOptions.importHelpers) { + // If we have any `export * from ...` declarations + // we need to inform the emitter to add the __export helper. + ts.addEmitHelper(updated, exportStarHelper); + } + ts.addEmitHelpers(updated, context.readEmitHelpers()); + return updated; + } + /** + * Transforms a SourceFile into an AMD module. + * + * @param node The SourceFile node. + */ + function transformAMDModule(node) { + var define = ts.createIdentifier("define"); + var moduleName = ts.tryGetModuleNameFromFile(node, host, compilerOptions); + var jsonSourceFile = ts.isJsonSourceFile(node) && node; + // An AMD define function has the following shape: + // + // define(id?, dependencies?, factory); + // + // This has the shape of the following: + // + // define(name, ["module1", "module2"], function (module1Alias) { ... } + // + // The location of the alias in the parameter list in the factory function needs to + // match the position of the module name in the dependency list. + // + // To ensure this is true in cases of modules with no aliases, e.g.: + // + // import "module" + // + // or + // + // /// + // + // we need to add modules without alias names to the end of the dependencies list + var _a = collectAsynchronousDependencies(node, /*includeNonAmdDependencies*/ true), aliasedModuleNames = _a.aliasedModuleNames, unaliasedModuleNames = _a.unaliasedModuleNames, importAliasNames = _a.importAliasNames; + // Create an updated SourceFile: + // + // define(moduleName?, ["module1", "module2"], function ... + var updated = ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray([ + ts.createExpressionStatement(ts.createCall(define, + /*typeArguments*/ undefined, (moduleName ? [moduleName] : []).concat([ + // Add the dependency array argument: + // + // ["require", "exports", module1", "module2", ...] + ts.createArrayLiteral(jsonSourceFile ? ts.emptyArray : [ + ts.createLiteral("require"), + ts.createLiteral("exports") + ].concat(aliasedModuleNames, unaliasedModuleNames)), + // Add the module body function argument: + // + // function (require, exports, module1, module2) ... + jsonSourceFile ? + jsonSourceFile.statements.length ? jsonSourceFile.statements[0].expression : ts.createObjectLiteral() : + ts.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, [ + ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "require"), + ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "exports") + ].concat(importAliasNames), + /*type*/ undefined, transformAsynchronousModuleBody(node)) + ]))) + ]), + /*location*/ node.statements)); + ts.addEmitHelpers(updated, context.readEmitHelpers()); + return updated; + } + /** + * Transforms a SourceFile into a UMD module. + * + * @param node The SourceFile node. + */ + function transformUMDModule(node) { + var _a = collectAsynchronousDependencies(node, /*includeNonAmdDependencies*/ false), aliasedModuleNames = _a.aliasedModuleNames, unaliasedModuleNames = _a.unaliasedModuleNames, importAliasNames = _a.importAliasNames; + var moduleName = ts.tryGetModuleNameFromFile(node, host, compilerOptions); + var umdHeader = ts.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "factory")], + /*type*/ undefined, ts.setTextRange(ts.createBlock([ + ts.createIf(ts.createLogicalAnd(ts.createTypeCheck(ts.createIdentifier("module"), "object"), ts.createTypeCheck(ts.createPropertyAccess(ts.createIdentifier("module"), "exports"), "object")), ts.createBlock([ + ts.createVariableStatement( + /*modifiers*/ undefined, [ + ts.createVariableDeclaration("v", + /*type*/ undefined, ts.createCall(ts.createIdentifier("factory"), + /*typeArguments*/ undefined, [ + ts.createIdentifier("require"), + ts.createIdentifier("exports") + ])) + ]), + ts.setEmitFlags(ts.createIf(ts.createStrictInequality(ts.createIdentifier("v"), ts.createIdentifier("undefined")), ts.createExpressionStatement(ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier("module"), "exports"), ts.createIdentifier("v")))), 1 /* SingleLine */) + ]), ts.createIf(ts.createLogicalAnd(ts.createTypeCheck(ts.createIdentifier("define"), "function"), ts.createPropertyAccess(ts.createIdentifier("define"), "amd")), ts.createBlock([ + ts.createExpressionStatement(ts.createCall(ts.createIdentifier("define"), + /*typeArguments*/ undefined, (moduleName ? [moduleName] : []).concat([ + ts.createArrayLiteral([ + ts.createLiteral("require"), + ts.createLiteral("exports") + ].concat(aliasedModuleNames, unaliasedModuleNames)), + ts.createIdentifier("factory") + ]))) + ]))) + ], + /*multiLine*/ true), + /*location*/ undefined)); + // Create an updated SourceFile: + // + // (function (factory) { + // if (typeof module === "object" && typeof module.exports === "object") { + // var v = factory(require, exports); + // if (v !== undefined) module.exports = v; + // } + // else if (typeof define === 'function' && define.amd) { + // define(["require", "exports"], factory); + // } + // })(function ...) + var updated = ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray([ + ts.createExpressionStatement(ts.createCall(umdHeader, + /*typeArguments*/ undefined, [ + // Add the module body function argument: + // + // function (require, exports) ... + ts.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, [ + ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "require"), + ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "exports") + ].concat(importAliasNames), + /*type*/ undefined, transformAsynchronousModuleBody(node)) + ])) + ]), + /*location*/ node.statements)); + ts.addEmitHelpers(updated, context.readEmitHelpers()); + return updated; + } + /** + * Collect the additional asynchronous dependencies for the module. + * + * @param node The source file. + * @param includeNonAmdDependencies A value indicating whether to include non-AMD dependencies. + */ + function collectAsynchronousDependencies(node, includeNonAmdDependencies) { + // names of modules with corresponding parameter in the factory function + var aliasedModuleNames = []; + // names of modules with no corresponding parameters in factory function + var unaliasedModuleNames = []; + // names of the parameters in the factory function; these + // parameters need to match the indexes of the corresponding + // module names in aliasedModuleNames. + var importAliasNames = []; + // Fill in amd-dependency tags + for (var _i = 0, _a = node.amdDependencies; _i < _a.length; _i++) { + var amdDependency = _a[_i]; + if (amdDependency.name) { + aliasedModuleNames.push(ts.createLiteral(amdDependency.path)); + importAliasNames.push(ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, amdDependency.name)); + } + else { + unaliasedModuleNames.push(ts.createLiteral(amdDependency.path)); + } + } + for (var _b = 0, _c = currentModuleInfo.externalImports; _b < _c.length; _b++) { + var importNode = _c[_b]; + // Find the name of the external module + var externalModuleName = ts.getExternalModuleNameLiteral(importNode, currentSourceFile, host, resolver, compilerOptions); + // Find the name of the module alias, if there is one + var importAliasName = ts.getLocalNameForExternalImport(importNode, currentSourceFile); + // It is possible that externalModuleName is undefined if it is not string literal. + // This can happen in the invalid import syntax. + // E.g : "import * from alias from 'someLib';" + if (externalModuleName) { + if (includeNonAmdDependencies && importAliasName) { + // Set emitFlags on the name of the classDeclaration + // This is so that when printer will not substitute the identifier + ts.setEmitFlags(importAliasName, 4 /* NoSubstitution */); + aliasedModuleNames.push(externalModuleName); + importAliasNames.push(ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, importAliasName)); + } + else { + unaliasedModuleNames.push(externalModuleName); + } + } + } + return { aliasedModuleNames: aliasedModuleNames, unaliasedModuleNames: unaliasedModuleNames, importAliasNames: importAliasNames }; + } + function getAMDImportExpressionForImport(node) { + if (ts.isImportEqualsDeclaration(node) || ts.isExportDeclaration(node) || !ts.getExternalModuleNameLiteral(node, currentSourceFile, host, resolver, compilerOptions)) { + return undefined; + } + var name = ts.getLocalNameForExternalImport(node, currentSourceFile); // TODO: GH#18217 + var expr = getHelperExpressionForImport(node, name); + if (expr === name) { + return undefined; + } + return ts.createExpressionStatement(ts.createAssignment(name, expr)); + } + /** + * Transforms a SourceFile into an AMD or UMD module body. + * + * @param node The SourceFile node. + */ + function transformAsynchronousModuleBody(node) { + startLexicalEnvironment(); + var statements = []; + var statementOffset = ts.addPrologue(statements, node.statements, /*ensureUseStrict*/ !compilerOptions.noImplicitUseStrict, sourceElementVisitor); + if (shouldEmitUnderscoreUnderscoreESModule()) { + ts.append(statements, createUnderscoreUnderscoreESModule()); + } + // Visit each statement of the module body. + ts.append(statements, ts.visitNode(currentModuleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement)); + if (moduleKind === ts.ModuleKind.AMD) { + ts.addRange(statements, ts.mapDefined(currentModuleInfo.externalImports, getAMDImportExpressionForImport)); + } + ts.addRange(statements, ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset)); + // Append the 'export =' statement if provided. + addExportEqualsIfNeeded(statements, /*emitAsReturn*/ true); + // End the lexical environment for the module body + // and merge any new lexical declarations. + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + var body = ts.createBlock(statements, /*multiLine*/ true); + if (currentModuleInfo.hasExportStarsToExportValues && !compilerOptions.importHelpers) { + // If we have any `export * from ...` declarations + // we need to inform the emitter to add the __export helper. + ts.addEmitHelper(body, exportStarHelper); + } + if (needUMDDynamicImportHelper) { + ts.addEmitHelper(body, dynamicImportUMDHelper); + } + return body; + } + /** + * Adds the down-level representation of `export=` to the statement list if one exists + * in the source file. + * + * @param statements The Statement list to modify. + * @param emitAsReturn A value indicating whether to emit the `export=` statement as a + * return statement. + */ + function addExportEqualsIfNeeded(statements, emitAsReturn) { + if (currentModuleInfo.exportEquals) { + var expressionResult = ts.visitNode(currentModuleInfo.exportEquals.expression, moduleExpressionElementVisitor); + if (expressionResult) { + if (emitAsReturn) { + var statement = ts.createReturn(expressionResult); + ts.setTextRange(statement, currentModuleInfo.exportEquals); + ts.setEmitFlags(statement, 384 /* NoTokenSourceMaps */ | 1536 /* NoComments */); + statements.push(statement); + } + else { + var statement = ts.createExpressionStatement(ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier("module"), "exports"), expressionResult)); + ts.setTextRange(statement, currentModuleInfo.exportEquals); + ts.setEmitFlags(statement, 1536 /* NoComments */); + statements.push(statement); + } + } + } + } + // + // Top-Level Source Element Visitors + // + /** + * Visits a node at the top level of the source file. + * + * @param node The node to visit. + */ + function sourceElementVisitor(node) { + switch (node.kind) { + case 249 /* ImportDeclaration */: + return visitImportDeclaration(node); + case 248 /* ImportEqualsDeclaration */: + return visitImportEqualsDeclaration(node); + case 255 /* ExportDeclaration */: + return visitExportDeclaration(node); + case 254 /* ExportAssignment */: + return visitExportAssignment(node); + case 219 /* VariableStatement */: + return visitVariableStatement(node); + case 239 /* FunctionDeclaration */: + return visitFunctionDeclaration(node); + case 240 /* ClassDeclaration */: + return visitClassDeclaration(node); + case 310 /* MergeDeclarationMarker */: + return visitMergeDeclarationMarker(node); + case 311 /* EndOfDeclarationMarker */: + return visitEndOfDeclarationMarker(node); + default: + return ts.visitEachChild(node, moduleExpressionElementVisitor, context); + } + } + function moduleExpressionElementVisitor(node) { + // This visitor does not need to descend into the tree if there is no dynamic import or destructuring assignment, + // as export/import statements are only transformed at the top level of a file. + if (!(node.transformFlags & 16777216 /* ContainsDynamicImport */) && !(node.transformFlags & 2048 /* ContainsDestructuringAssignment */)) { + return node; + } + if (ts.isImportCall(node)) { + return visitImportCallExpression(node); + } + else if (node.transformFlags & 1024 /* DestructuringAssignment */ && ts.isBinaryExpression(node)) { + return visitDestructuringAssignment(node); + } + else { + return ts.visitEachChild(node, moduleExpressionElementVisitor, context); + } + } + function destructuringNeedsFlattening(node) { + if (ts.isObjectLiteralExpression(node)) { + for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { + var elem = _a[_i]; + switch (elem.kind) { + case 275 /* PropertyAssignment */: + if (destructuringNeedsFlattening(elem.initializer)) { + return true; + } + break; + case 276 /* ShorthandPropertyAssignment */: + if (destructuringNeedsFlattening(elem.name)) { + return true; + } + break; + case 277 /* SpreadAssignment */: + if (destructuringNeedsFlattening(elem.expression)) { + return true; + } + break; + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + return false; + default: ts.Debug.assertNever(elem, "Unhandled object member kind"); + } + } + } + else if (ts.isArrayLiteralExpression(node)) { + for (var _b = 0, _c = node.elements; _b < _c.length; _b++) { + var elem = _c[_b]; + if (ts.isSpreadElement(elem)) { + if (destructuringNeedsFlattening(elem.expression)) { + return true; + } + } + else if (destructuringNeedsFlattening(elem)) { + return true; + } + } + } + else if (ts.isIdentifier(node)) { + return ts.length(getExports(node)) > (ts.isExportName(node) ? 1 : 0); + } + return false; + } + function visitDestructuringAssignment(node) { + if (destructuringNeedsFlattening(node.left)) { + return ts.flattenDestructuringAssignment(node, moduleExpressionElementVisitor, context, 0 /* All */, /*needsValue*/ false, createAllExportExpressions); + } + return ts.visitEachChild(node, moduleExpressionElementVisitor, context); + } + function visitImportCallExpression(node) { + var argument = ts.visitNode(ts.firstOrUndefined(node.arguments), moduleExpressionElementVisitor); + var containsLexicalThis = !!(node.transformFlags & 8192 /* ContainsLexicalThis */); + switch (compilerOptions.module) { + case ts.ModuleKind.AMD: + return createImportCallExpressionAMD(argument, containsLexicalThis); + case ts.ModuleKind.UMD: + return createImportCallExpressionUMD(argument, containsLexicalThis); + case ts.ModuleKind.CommonJS: + default: + return createImportCallExpressionCommonJS(argument, containsLexicalThis); + } + } + function createImportCallExpressionUMD(arg, containsLexicalThis) { + // (function (factory) { + // ... (regular UMD) + // } + // })(function (require, exports, useSyncRequire) { + // "use strict"; + // Object.defineProperty(exports, "__esModule", { value: true }); + // var __syncRequire = typeof module === "object" && typeof module.exports === "object"; + // var __resolved = new Promise(function (resolve) { resolve(); }); + // ..... + // __syncRequire + // ? __resolved.then(function () { return require(x); }) /*CommonJs Require*/ + // : new Promise(function (_a, _b) { require([x], _a, _b); }); /*Amd Require*/ + // }); + needUMDDynamicImportHelper = true; + if (ts.isSimpleCopiableExpression(arg)) { + var argClone = ts.isGeneratedIdentifier(arg) ? arg : ts.isStringLiteral(arg) ? ts.createLiteral(arg) : ts.setEmitFlags(ts.setTextRange(ts.getSynthesizedClone(arg), arg), 1536 /* NoComments */); + return ts.createConditional( + /*condition*/ ts.createIdentifier("__syncRequire"), + /*whenTrue*/ createImportCallExpressionCommonJS(arg, containsLexicalThis), + /*whenFalse*/ createImportCallExpressionAMD(argClone, containsLexicalThis)); + } + else { + var temp = ts.createTempVariable(hoistVariableDeclaration); + return ts.createComma(ts.createAssignment(temp, arg), ts.createConditional( + /*condition*/ ts.createIdentifier("__syncRequire"), + /*whenTrue*/ createImportCallExpressionCommonJS(temp, containsLexicalThis), + /*whenFalse*/ createImportCallExpressionAMD(temp, containsLexicalThis))); + } + } + function createImportCallExpressionAMD(arg, containsLexicalThis) { + // improt("./blah") + // emit as + // define(["require", "exports", "blah"], function (require, exports) { + // ... + // new Promise(function (_a, _b) { require([x], _a, _b); }); /*Amd Require*/ + // }); + var resolve = ts.createUniqueName("resolve"); + var reject = ts.createUniqueName("reject"); + var parameters = [ + ts.createParameter(/*decorator*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, /*name*/ resolve), + ts.createParameter(/*decorator*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, /*name*/ reject) + ]; + var body = ts.createBlock([ + ts.createExpressionStatement(ts.createCall(ts.createIdentifier("require"), + /*typeArguments*/ undefined, [ts.createArrayLiteral([arg || ts.createOmittedExpression()]), resolve, reject])) + ]); + var func; + if (languageVersion >= 2 /* ES2015 */) { + func = ts.createArrowFunction( + /*modifiers*/ undefined, + /*typeParameters*/ undefined, parameters, + /*type*/ undefined, + /*equalsGreaterThanToken*/ undefined, body); + } + else { + func = ts.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, parameters, + /*type*/ undefined, body); + // if there is a lexical 'this' in the import call arguments, ensure we indicate + // that this new function expression indicates it captures 'this' so that the + // es2015 transformer will properly substitute 'this' with '_this'. + if (containsLexicalThis) { + ts.setEmitFlags(func, 8 /* CapturesThis */); + } + } + var promise = ts.createNew(ts.createIdentifier("Promise"), /*typeArguments*/ undefined, [func]); + if (compilerOptions.esModuleInterop) { + context.requestEmitHelper(importStarHelper); + return ts.createCall(ts.createPropertyAccess(promise, ts.createIdentifier("then")), /*typeArguments*/ undefined, [ts.getHelperName("__importStar")]); + } + return promise; + } + function createImportCallExpressionCommonJS(arg, containsLexicalThis) { + // import("./blah") + // emit as + // Promise.resolve().then(function () { return require(x); }) /*CommonJs Require*/ + // We have to wrap require in then callback so that require is done in asynchronously + // if we simply do require in resolve callback in Promise constructor. We will execute the loading immediately + var promiseResolveCall = ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Promise"), "resolve"), /*typeArguments*/ undefined, /*argumentsArray*/ []); + var requireCall = ts.createCall(ts.createIdentifier("require"), /*typeArguments*/ undefined, arg ? [arg] : []); + if (compilerOptions.esModuleInterop) { + context.requestEmitHelper(importStarHelper); + requireCall = ts.createCall(ts.getHelperName("__importStar"), /*typeArguments*/ undefined, [requireCall]); + } + var func; + if (languageVersion >= 2 /* ES2015 */) { + func = ts.createArrowFunction( + /*modifiers*/ undefined, + /*typeParameters*/ undefined, + /*parameters*/ [], + /*type*/ undefined, + /*equalsGreaterThanToken*/ undefined, requireCall); + } + else { + func = ts.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, + /*parameters*/ [], + /*type*/ undefined, ts.createBlock([ts.createReturn(requireCall)])); + // if there is a lexical 'this' in the import call arguments, ensure we indicate + // that this new function expression indicates it captures 'this' so that the + // es2015 transformer will properly substitute 'this' with '_this'. + if (containsLexicalThis) { + ts.setEmitFlags(func, 8 /* CapturesThis */); + } + } + return ts.createCall(ts.createPropertyAccess(promiseResolveCall, "then"), /*typeArguments*/ undefined, [func]); + } + function getHelperExpressionForImport(node, innerExpr) { + if (!compilerOptions.esModuleInterop || ts.getEmitFlags(node) & 67108864 /* NeverApplyImportHelper */) { + return innerExpr; + } + if (ts.getImportNeedsImportStarHelper(node)) { + context.requestEmitHelper(importStarHelper); + return ts.createCall(ts.getHelperName("__importStar"), /*typeArguments*/ undefined, [innerExpr]); + } + if (ts.getImportNeedsImportDefaultHelper(node)) { + context.requestEmitHelper(importDefaultHelper); + return ts.createCall(ts.getHelperName("__importDefault"), /*typeArguments*/ undefined, [innerExpr]); + } + return innerExpr; + } + /** + * Visits an ImportDeclaration node. + * + * @param node The node to visit. + */ + function visitImportDeclaration(node) { + var statements; + var namespaceDeclaration = ts.getNamespaceDeclarationNode(node); + if (moduleKind !== ts.ModuleKind.AMD) { + if (!node.importClause) { + // import "mod"; + return ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(createRequireCall(node)), node), node); + } + else { + var variables = []; + if (namespaceDeclaration && !ts.isDefaultImport(node)) { + // import * as n from "mod"; + variables.push(ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name), + /*type*/ undefined, getHelperExpressionForImport(node, createRequireCall(node)))); + } + else { + // import d from "mod"; + // import { x, y } from "mod"; + // import d, { x, y } from "mod"; + // import d, * as n from "mod"; + variables.push(ts.createVariableDeclaration(ts.getGeneratedNameForNode(node), + /*type*/ undefined, getHelperExpressionForImport(node, createRequireCall(node)))); + if (namespaceDeclaration && ts.isDefaultImport(node)) { + variables.push(ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name), + /*type*/ undefined, ts.getGeneratedNameForNode(node))); + } + } + statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList(variables, languageVersion >= 2 /* ES2015 */ ? 2 /* Const */ : 0 /* None */)), + /*location*/ node), + /*original*/ node)); + } + } + else if (namespaceDeclaration && ts.isDefaultImport(node)) { + // import d, * as n from "mod"; + statements = ts.append(statements, ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ + ts.setOriginalNode(ts.setTextRange(ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name), + /*type*/ undefined, ts.getGeneratedNameForNode(node)), + /*location*/ node), + /*original*/ node) + ], languageVersion >= 2 /* ES2015 */ ? 2 /* Const */ : 0 /* None */))); + } + if (hasAssociatedEndOfDeclarationMarker(node)) { + // Defer exports until we encounter an EndOfDeclarationMarker node + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportsOfImportDeclaration(deferredExports[id], node); + } + else { + statements = appendExportsOfImportDeclaration(statements, node); + } + return ts.singleOrMany(statements); + } + /** + * Creates a `require()` call to import an external module. + * + * @param importNode The declararation to import. + */ + function createRequireCall(importNode) { + var moduleName = ts.getExternalModuleNameLiteral(importNode, currentSourceFile, host, resolver, compilerOptions); + var args = []; + if (moduleName) { + args.push(moduleName); + } + return ts.createCall(ts.createIdentifier("require"), /*typeArguments*/ undefined, args); + } + /** + * Visits an ImportEqualsDeclaration node. + * + * @param node The node to visit. + */ + function visitImportEqualsDeclaration(node) { + ts.Debug.assert(ts.isExternalModuleImportEqualsDeclaration(node), "import= for internal module references should be handled in an earlier transformer."); + var statements; + if (moduleKind !== ts.ModuleKind.AMD) { + if (ts.hasModifier(node, 1 /* Export */)) { + statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(createExportExpression(node.name, createRequireCall(node))), node), node)); + } + else { + statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(ts.getSynthesizedClone(node.name), + /*type*/ undefined, createRequireCall(node)) + ], + /*flags*/ languageVersion >= 2 /* ES2015 */ ? 2 /* Const */ : 0 /* None */)), node), node)); + } + } + else { + if (ts.hasModifier(node, 1 /* Export */)) { + statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(createExportExpression(ts.getExportName(node), ts.getLocalName(node))), node), node)); + } + } + if (hasAssociatedEndOfDeclarationMarker(node)) { + // Defer exports until we encounter an EndOfDeclarationMarker node + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportsOfImportEqualsDeclaration(deferredExports[id], node); + } + else { + statements = appendExportsOfImportEqualsDeclaration(statements, node); + } + return ts.singleOrMany(statements); + } + /** + * Visits an ExportDeclaration node. + * + * @param The node to visit. + */ + function visitExportDeclaration(node) { + if (!node.moduleSpecifier) { + // Elide export declarations with no module specifier as they are handled + // elsewhere. + return undefined; + } + var generatedName = ts.getGeneratedNameForNode(node); + if (node.exportClause) { + var statements = []; + // export { x, y } from "mod"; + if (moduleKind !== ts.ModuleKind.AMD) { + statements.push(ts.setOriginalNode(ts.setTextRange(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(generatedName, + /*type*/ undefined, createRequireCall(node)) + ])), + /*location*/ node), + /* original */ node)); + } + for (var _i = 0, _a = node.exportClause.elements; _i < _a.length; _i++) { + var specifier = _a[_i]; + var exportedValue = ts.createPropertyAccess(generatedName, specifier.propertyName || specifier.name); + statements.push(ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(createExportExpression(ts.getExportName(specifier), exportedValue)), specifier), specifier)); + } + return ts.singleOrMany(statements); + } + else { + // export * from "mod"; + return ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(createExportStarHelper(context, moduleKind !== ts.ModuleKind.AMD ? createRequireCall(node) : generatedName)), node), node); + } + } + /** + * Visits an ExportAssignment node. + * + * @param node The node to visit. + */ + function visitExportAssignment(node) { + if (node.isExportEquals) { + return undefined; + } + var statements; + var original = node.original; + if (original && hasAssociatedEndOfDeclarationMarker(original)) { + // Defer exports until we encounter an EndOfDeclarationMarker node + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportStatement(deferredExports[id], ts.createIdentifier("default"), ts.visitNode(node.expression, moduleExpressionElementVisitor), /*location*/ node, /*allowComments*/ true); + } + else { + statements = appendExportStatement(statements, ts.createIdentifier("default"), ts.visitNode(node.expression, moduleExpressionElementVisitor), /*location*/ node, /*allowComments*/ true); + } + return ts.singleOrMany(statements); + } + /** + * Visits a FunctionDeclaration node. + * + * @param node The node to visit. + */ + function visitFunctionDeclaration(node) { + var statements; + if (ts.hasModifier(node, 1 /* Export */)) { + statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createFunctionDeclaration( + /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, ts.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true), + /*typeParameters*/ undefined, ts.visitNodes(node.parameters, moduleExpressionElementVisitor), + /*type*/ undefined, ts.visitEachChild(node.body, moduleExpressionElementVisitor, context)), + /*location*/ node), + /*original*/ node)); + } + else { + statements = ts.append(statements, ts.visitEachChild(node, moduleExpressionElementVisitor, context)); + } + if (hasAssociatedEndOfDeclarationMarker(node)) { + // Defer exports until we encounter an EndOfDeclarationMarker node + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node); + } + else { + statements = appendExportsOfHoistedDeclaration(statements, node); + } + return ts.singleOrMany(statements); + } + /** + * Visits a ClassDeclaration node. + * + * @param node The node to visit. + */ + function visitClassDeclaration(node) { + var statements; + if (ts.hasModifier(node, 1 /* Export */)) { + statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createClassDeclaration( + /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true), + /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, moduleExpressionElementVisitor), ts.visitNodes(node.members, moduleExpressionElementVisitor)), node), node)); + } + else { + statements = ts.append(statements, ts.visitEachChild(node, moduleExpressionElementVisitor, context)); + } + if (hasAssociatedEndOfDeclarationMarker(node)) { + // Defer exports until we encounter an EndOfDeclarationMarker node + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node); + } + else { + statements = appendExportsOfHoistedDeclaration(statements, node); + } + return ts.singleOrMany(statements); + } + /** + * Visits a VariableStatement node. + * + * @param node The node to visit. + */ + function visitVariableStatement(node) { + var statements; + var variables; + var expressions; + if (ts.hasModifier(node, 1 /* Export */)) { + var modifiers = void 0; + // If we're exporting these variables, then these just become assignments to 'exports.x'. + // We only want to emit assignments for variables with initializers. + for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { + var variable = _a[_i]; + if (ts.isIdentifier(variable.name) && ts.isLocalName(variable.name)) { + if (!modifiers) { + modifiers = ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier); + } + variables = ts.append(variables, variable); + } + else if (variable.initializer) { + expressions = ts.append(expressions, transformInitializedVariable(variable)); + } + } + if (variables) { + statements = ts.append(statements, ts.updateVariableStatement(node, modifiers, ts.updateVariableDeclarationList(node.declarationList, variables))); + } + if (expressions) { + statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(ts.inlineExpressions(expressions)), node), node)); + } + } + else { + statements = ts.append(statements, ts.visitEachChild(node, moduleExpressionElementVisitor, context)); + } + if (hasAssociatedEndOfDeclarationMarker(node)) { + // Defer exports until we encounter an EndOfDeclarationMarker node + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node); + } + else { + statements = appendExportsOfVariableStatement(statements, node); + } + return ts.singleOrMany(statements); + } + function createAllExportExpressions(name, value, location) { + var exportedNames = getExports(name); + if (exportedNames) { + // For each additional export of the declaration, apply an export assignment. + var expression = ts.isExportName(name) ? value : ts.createAssignment(name, value); + for (var _i = 0, exportedNames_1 = exportedNames; _i < exportedNames_1.length; _i++) { + var exportName = exportedNames_1[_i]; + // Mark the node to prevent triggering substitution. + ts.setEmitFlags(expression, 4 /* NoSubstitution */); + expression = createExportExpression(exportName, expression, /*location*/ location); + } + return expression; + } + return ts.createAssignment(name, value); + } + /** + * Transforms an exported variable with an initializer into an expression. + * + * @param node The node to transform. + */ + function transformInitializedVariable(node) { + if (ts.isBindingPattern(node.name)) { + return ts.flattenDestructuringAssignment(ts.visitNode(node, moduleExpressionElementVisitor), + /*visitor*/ undefined, context, 0 /* All */, + /*needsValue*/ false, createAllExportExpressions); + } + else { + return ts.createAssignment(ts.setTextRange(ts.createPropertyAccess(ts.createIdentifier("exports"), node.name), + /*location*/ node.name), ts.visitNode(node.initializer, moduleExpressionElementVisitor)); + } + } + /** + * Visits a MergeDeclarationMarker used as a placeholder for the beginning of a merged + * and transformed declaration. + * + * @param node The node to visit. + */ + function visitMergeDeclarationMarker(node) { + // For an EnumDeclaration or ModuleDeclaration that merges with a preceeding + // declaration we do not emit a leading variable declaration. To preserve the + // begin/end semantics of the declararation and to properly handle exports + // we wrapped the leading variable declaration in a `MergeDeclarationMarker`. + // + // To balance the declaration, add the exports of the elided variable + // statement. + if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 219 /* VariableStatement */) { + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node.original); + } + return node; + } + /** + * Determines whether a node has an associated EndOfDeclarationMarker. + * + * @param node The node to test. + */ + function hasAssociatedEndOfDeclarationMarker(node) { + return (ts.getEmitFlags(node) & 4194304 /* HasEndOfDeclarationMarker */) !== 0; + } + /** + * Visits a DeclarationMarker used as a placeholder for the end of a transformed + * declaration. + * + * @param node The node to visit. + */ + function visitEndOfDeclarationMarker(node) { + // For some transformations we emit an `EndOfDeclarationMarker` to mark the actual + // end of the transformed declaration. We use this marker to emit any deferred exports + // of the declaration. + var id = ts.getOriginalNodeId(node); + var statements = deferredExports[id]; + if (statements) { + delete deferredExports[id]; + return ts.append(statements, node); + } + return node; + } + /** + * Appends the exports of an ImportDeclaration to a statement list, returning the + * statement list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param decl The declaration whose exports are to be recorded. + */ + function appendExportsOfImportDeclaration(statements, decl) { + if (currentModuleInfo.exportEquals) { + return statements; + } + var importClause = decl.importClause; + if (!importClause) { + return statements; + } + if (importClause.name) { + statements = appendExportsOfDeclaration(statements, importClause); + } + var namedBindings = importClause.namedBindings; + if (namedBindings) { + switch (namedBindings.kind) { + case 251 /* NamespaceImport */: + statements = appendExportsOfDeclaration(statements, namedBindings); + break; + case 252 /* NamedImports */: + for (var _i = 0, _a = namedBindings.elements; _i < _a.length; _i++) { + var importBinding = _a[_i]; + statements = appendExportsOfDeclaration(statements, importBinding); + } + break; + } + } + return statements; + } + /** + * Appends the exports of an ImportEqualsDeclaration to a statement list, returning the + * statement list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param decl The declaration whose exports are to be recorded. + */ + function appendExportsOfImportEqualsDeclaration(statements, decl) { + if (currentModuleInfo.exportEquals) { + return statements; + } + return appendExportsOfDeclaration(statements, decl); + } + /** + * Appends the exports of a VariableStatement to a statement list, returning the statement + * list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param node The VariableStatement whose exports are to be recorded. + */ + function appendExportsOfVariableStatement(statements, node) { + if (currentModuleInfo.exportEquals) { + return statements; + } + for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + statements = appendExportsOfBindingElement(statements, decl); + } + return statements; + } + /** + * Appends the exports of a VariableDeclaration or BindingElement to a statement list, + * returning the statement list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param decl The declaration whose exports are to be recorded. + */ + function appendExportsOfBindingElement(statements, decl) { + if (currentModuleInfo.exportEquals) { + return statements; + } + if (ts.isBindingPattern(decl.name)) { + for (var _i = 0, _a = decl.name.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (!ts.isOmittedExpression(element)) { + statements = appendExportsOfBindingElement(statements, element); + } + } + } + else if (!ts.isGeneratedIdentifier(decl.name)) { + statements = appendExportsOfDeclaration(statements, decl); + } + return statements; + } + /** + * Appends the exports of a ClassDeclaration or FunctionDeclaration to a statement list, + * returning the statement list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param decl The declaration whose exports are to be recorded. + */ + function appendExportsOfHoistedDeclaration(statements, decl) { + if (currentModuleInfo.exportEquals) { + return statements; + } + if (ts.hasModifier(decl, 1 /* Export */)) { + var exportName = ts.hasModifier(decl, 512 /* Default */) ? ts.createIdentifier("default") : ts.getDeclarationName(decl); + statements = appendExportStatement(statements, exportName, ts.getLocalName(decl), /*location*/ decl); + } + if (decl.name) { + statements = appendExportsOfDeclaration(statements, decl); + } + return statements; + } + /** + * Appends the exports of a declaration to a statement list, returning the statement list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param decl The declaration to export. + */ + function appendExportsOfDeclaration(statements, decl) { + var name = ts.getDeclarationName(decl); + var exportSpecifiers = currentModuleInfo.exportSpecifiers.get(ts.idText(name)); + if (exportSpecifiers) { + for (var _i = 0, exportSpecifiers_1 = exportSpecifiers; _i < exportSpecifiers_1.length; _i++) { + var exportSpecifier = exportSpecifiers_1[_i]; + statements = appendExportStatement(statements, exportSpecifier.name, name, /*location*/ exportSpecifier.name); + } + } + return statements; + } + /** + * Appends the down-level representation of an export to a statement list, returning the + * statement list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param exportName The name of the export. + * @param expression The expression to export. + * @param location The location to use for source maps and comments for the export. + * @param allowComments Whether to allow comments on the export. + */ + function appendExportStatement(statements, exportName, expression, location, allowComments) { + statements = ts.append(statements, createExportStatement(exportName, expression, location, allowComments)); + return statements; + } + function createUnderscoreUnderscoreESModule() { + var statement; + if (languageVersion === 0 /* ES3 */) { + statement = ts.createExpressionStatement(createExportExpression(ts.createIdentifier("__esModule"), ts.createLiteral(/*value*/ true))); + } + else { + statement = ts.createExpressionStatement(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"), + /*typeArguments*/ undefined, [ + ts.createIdentifier("exports"), + ts.createLiteral("__esModule"), + ts.createObjectLiteral([ + ts.createPropertyAssignment("value", ts.createLiteral(/*value*/ true)) + ]) + ])); + } + ts.setEmitFlags(statement, 1048576 /* CustomPrologue */); + return statement; + } + /** + * Creates a call to the current file's export function to export a value. + * + * @param name The bound name of the export. + * @param value The exported value. + * @param location The location to use for source maps and comments for the export. + * @param allowComments An optional value indicating whether to emit comments for the statement. + */ + function createExportStatement(name, value, location, allowComments) { + var statement = ts.setTextRange(ts.createExpressionStatement(createExportExpression(name, value)), location); + ts.startOnNewLine(statement); + if (!allowComments) { + ts.setEmitFlags(statement, 1536 /* NoComments */); + } + return statement; + } + /** + * Creates a call to the current file's export function to export a value. + * + * @param name The bound name of the export. + * @param value The exported value. + * @param location The location to use for source maps and comments for the export. + */ + function createExportExpression(name, value, location) { + return ts.setTextRange(ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier("exports"), ts.getSynthesizedClone(name)), value), location); + } + // + // Modifier Visitors + // + /** + * Visit nodes to elide module-specific modifiers. + * + * @param node The node to visit. + */ + function modifierVisitor(node) { + // Elide module-specific modifiers. + switch (node.kind) { + case 85 /* ExportKeyword */: + case 80 /* DefaultKeyword */: + return undefined; + } + return node; + } + // + // Emit Notification + // + /** + * Hook for node emit notifications. + * + * @param hint A hint as to the intended usage of the node. + * @param node The node to emit. + * @param emit A callback used to emit the node in the printer. + */ + function onEmitNode(hint, node, emitCallback) { + if (node.kind === 279 /* SourceFile */) { + currentSourceFile = node; + currentModuleInfo = moduleInfoMap[ts.getOriginalNodeId(currentSourceFile)]; + noSubstitution = []; + previousOnEmitNode(hint, node, emitCallback); + currentSourceFile = undefined; + currentModuleInfo = undefined; + noSubstitution = undefined; + } + else { + previousOnEmitNode(hint, node, emitCallback); + } + } + // + // Substitutions + // + /** + * Hooks node substitutions. + * + * @param hint A hint as to the intended usage of the node. + * @param node The node to substitute. + */ + function onSubstituteNode(hint, node) { + node = previousOnSubstituteNode(hint, node); + if (node.id && noSubstitution[node.id]) { + return node; + } + if (hint === 1 /* Expression */) { + return substituteExpression(node); + } + else if (ts.isShorthandPropertyAssignment(node)) { + return substituteShorthandPropertyAssignment(node); + } + return node; + } + /** + * Substitution for a ShorthandPropertyAssignment whose declaration name is an imported + * or exported symbol. + * + * @param node The node to substitute. + */ + function substituteShorthandPropertyAssignment(node) { + var name = node.name; + var exportedOrImportedName = substituteExpressionIdentifier(name); + if (exportedOrImportedName !== name) { + // A shorthand property with an assignment initializer is probably part of a + // destructuring assignment + if (node.objectAssignmentInitializer) { + var initializer = ts.createAssignment(exportedOrImportedName, node.objectAssignmentInitializer); + return ts.setTextRange(ts.createPropertyAssignment(name, initializer), node); + } + return ts.setTextRange(ts.createPropertyAssignment(name, exportedOrImportedName), node); + } + return node; + } + /** + * Substitution for an Expression that may contain an imported or exported symbol. + * + * @param node The node to substitute. + */ + function substituteExpression(node) { + switch (node.kind) { + case 72 /* Identifier */: + return substituteExpressionIdentifier(node); + case 204 /* BinaryExpression */: + return substituteBinaryExpression(node); + case 203 /* PostfixUnaryExpression */: + case 202 /* PrefixUnaryExpression */: + return substituteUnaryExpression(node); + } + return node; + } + /** + * Substitution for an Identifier expression that may contain an imported or exported + * symbol. + * + * @param node The node to substitute. + */ + function substituteExpressionIdentifier(node) { + if (ts.getEmitFlags(node) & 4096 /* HelperName */) { + var externalHelpersModuleName = ts.getExternalHelpersModuleName(currentSourceFile); + if (externalHelpersModuleName) { + return ts.createPropertyAccess(externalHelpersModuleName, node); + } + return node; + } + if (!ts.isGeneratedIdentifier(node) && !ts.isLocalName(node)) { + var exportContainer = resolver.getReferencedExportContainer(node, ts.isExportName(node)); + if (exportContainer && exportContainer.kind === 279 /* SourceFile */) { + return ts.setTextRange(ts.createPropertyAccess(ts.createIdentifier("exports"), ts.getSynthesizedClone(node)), + /*location*/ node); + } + var importDeclaration = resolver.getReferencedImportDeclaration(node); + if (importDeclaration) { + if (ts.isImportClause(importDeclaration)) { + return ts.setTextRange(ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent), ts.createIdentifier("default")), + /*location*/ node); + } + else if (ts.isImportSpecifier(importDeclaration)) { + var name = importDeclaration.propertyName || importDeclaration.name; + return ts.setTextRange(ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent.parent.parent), ts.getSynthesizedClone(name)), + /*location*/ node); + } + } + } + return node; + } + /** + * Substitution for a BinaryExpression that may contain an imported or exported symbol. + * + * @param node The node to substitute. + */ + function substituteBinaryExpression(node) { + // When we see an assignment expression whose left-hand side is an exported symbol, + // we should ensure all exports of that symbol are updated with the correct value. + // + // - We do not substitute generated identifiers for any reason. + // - We do not substitute identifiers tagged with the LocalName flag. + // - We do not substitute identifiers that were originally the name of an enum or + // namespace due to how they are transformed in TypeScript. + // - We only substitute identifiers that are exported at the top level. + if (ts.isAssignmentOperator(node.operatorToken.kind) + && ts.isIdentifier(node.left) + && !ts.isGeneratedIdentifier(node.left) + && !ts.isLocalName(node.left) + && !ts.isDeclarationNameOfEnumOrNamespace(node.left)) { + var exportedNames = getExports(node.left); + if (exportedNames) { + // For each additional export of the declaration, apply an export assignment. + var expression = node; + for (var _i = 0, exportedNames_2 = exportedNames; _i < exportedNames_2.length; _i++) { + var exportName = exportedNames_2[_i]; + // Mark the node to prevent triggering this rule again. + noSubstitution[ts.getNodeId(expression)] = true; + expression = createExportExpression(exportName, expression, /*location*/ node); + } + return expression; + } + } + return node; + } + /** + * Substitution for a UnaryExpression that may contain an imported or exported symbol. + * + * @param node The node to substitute. + */ + function substituteUnaryExpression(node) { + // When we see a prefix or postfix increment expression whose operand is an exported + // symbol, we should ensure all exports of that symbol are updated with the correct + // value. + // + // - We do not substitute generated identifiers for any reason. + // - We do not substitute identifiers tagged with the LocalName flag. + // - We do not substitute identifiers that were originally the name of an enum or + // namespace due to how they are transformed in TypeScript. + // - We only substitute identifiers that are exported at the top level. + if ((node.operator === 44 /* PlusPlusToken */ || node.operator === 45 /* MinusMinusToken */) + && ts.isIdentifier(node.operand) + && !ts.isGeneratedIdentifier(node.operand) + && !ts.isLocalName(node.operand) + && !ts.isDeclarationNameOfEnumOrNamespace(node.operand)) { + var exportedNames = getExports(node.operand); + if (exportedNames) { + var expression = node.kind === 203 /* PostfixUnaryExpression */ + ? ts.setTextRange(ts.createBinary(node.operand, ts.createToken(node.operator === 44 /* PlusPlusToken */ ? 60 /* PlusEqualsToken */ : 61 /* MinusEqualsToken */), ts.createLiteral(1)), + /*location*/ node) + : node; + for (var _i = 0, exportedNames_3 = exportedNames; _i < exportedNames_3.length; _i++) { + var exportName = exportedNames_3[_i]; + // Mark the node to prevent triggering this rule again. + noSubstitution[ts.getNodeId(expression)] = true; + expression = createExportExpression(exportName, expression); + } + return expression; + } + } + return node; + } + /** + * Gets the additional exports of a name. + * + * @param name The name. + */ + function getExports(name) { + if (!ts.isGeneratedIdentifier(name)) { + var valueDeclaration = resolver.getReferencedImportDeclaration(name) + || resolver.getReferencedValueDeclaration(name); + if (valueDeclaration) { + return currentModuleInfo + && currentModuleInfo.exportedBindings[ts.getOriginalNodeId(valueDeclaration)]; + } + } + } + } + ts.transformModule = transformModule; + // emit output for the __export helper function + var exportStarHelper = { + name: "typescript:export-star", + scoped: true, + text: "\n function __export(m) {\n for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\n }" + }; + function createExportStarHelper(context, module) { + var compilerOptions = context.getCompilerOptions(); + return compilerOptions.importHelpers + ? ts.createCall(ts.getHelperName("__exportStar"), /*typeArguments*/ undefined, [module, ts.createIdentifier("exports")]) + : ts.createCall(ts.createIdentifier("__export"), /*typeArguments*/ undefined, [module]); + } + // emit helper for dynamic import + var dynamicImportUMDHelper = { + name: "typescript:dynamicimport-sync-require", + scoped: true, + text: "\n var __syncRequire = typeof module === \"object\" && typeof module.exports === \"object\";" + }; + // emit helper for `import * as Name from "foo"` + var importStarHelper = { + name: "typescript:commonjsimportstar", + scoped: false, + text: "\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];\n result[\"default\"] = mod;\n return result;\n};" + }; + // emit helper for `import Name from "foo"` + var importDefaultHelper = { + name: "typescript:commonjsimportdefault", + scoped: false, + text: "\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};" + }; +})(ts || (ts = {})); +/*@internal*/ +var ts; +(function (ts) { + function transformSystemModule(context) { + var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; + var compilerOptions = context.getCompilerOptions(); + var resolver = context.getEmitResolver(); + var host = context.getEmitHost(); + var previousOnSubstituteNode = context.onSubstituteNode; + var previousOnEmitNode = context.onEmitNode; + context.onSubstituteNode = onSubstituteNode; + context.onEmitNode = onEmitNode; + context.enableSubstitution(72 /* Identifier */); // Substitutes expression identifiers for imported symbols. + context.enableSubstitution(276 /* ShorthandPropertyAssignment */); // Substitutes expression identifiers for imported symbols + context.enableSubstitution(204 /* BinaryExpression */); // Substitutes assignments to exported symbols. + context.enableSubstitution(202 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols. + context.enableSubstitution(203 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols. + context.enableEmitNotification(279 /* SourceFile */); // Restore state when substituting nodes in a file. + var moduleInfoMap = []; // The ExternalModuleInfo for each file. + var deferredExports = []; // Exports to defer until an EndOfDeclarationMarker is found. + var exportFunctionsMap = []; // The export function associated with a source file. + var noSubstitutionMap = []; // Set of nodes for which substitution rules should be ignored for each file. + var currentSourceFile; // The current file. + var moduleInfo; // ExternalModuleInfo for the current file. + var exportFunction; // The export function for the current file. + var contextObject; // The context object for the current file. + var hoistedStatements; + var enclosingBlockScopedContainer; + var noSubstitution; // Set of nodes for which substitution rules should be ignored. + return ts.chainBundle(transformSourceFile); + /** + * Transforms the module aspects of a SourceFile. + * + * @param node The SourceFile node. + */ + function transformSourceFile(node) { + if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 16777216 /* ContainsDynamicImport */)) { + return node; + } + var id = ts.getOriginalNodeId(node); + currentSourceFile = node; + enclosingBlockScopedContainer = node; + // System modules have the following shape: + // + // System.register(['dep-1', ... 'dep-n'], function(exports) {/* module body function */}) + // + // The parameter 'exports' here is a callback '(name: string, value: T) => T' that + // is used to publish exported values. 'exports' returns its 'value' argument so in + // most cases expressions that mutate exported values can be rewritten as: + // + // expr -> exports('name', expr) + // + // The only exception in this rule is postfix unary operators, + // see comment to 'substitutePostfixUnaryExpression' for more details + // Collect information about the external module and dependency groups. + moduleInfo = moduleInfoMap[id] = ts.collectExternalModuleInfo(node, resolver, compilerOptions); + // Make sure that the name of the 'exports' function does not conflict with + // existing identifiers. + exportFunction = ts.createUniqueName("exports"); + exportFunctionsMap[id] = exportFunction; + contextObject = ts.createUniqueName("context"); + // Add the body of the module. + var dependencyGroups = collectDependencyGroups(moduleInfo.externalImports); + var moduleBodyBlock = createSystemModuleBody(node, dependencyGroups); + var moduleBodyFunction = ts.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, [ + ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, exportFunction), + ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, contextObject) + ], + /*type*/ undefined, moduleBodyBlock); + // Write the call to `System.register` + // Clear the emit-helpers flag for later passes since we'll have already used it in the module body + // So the helper will be emit at the correct position instead of at the top of the source-file + var moduleName = ts.tryGetModuleNameFromFile(node, host, compilerOptions); + var dependencies = ts.createArrayLiteral(ts.map(dependencyGroups, function (dependencyGroup) { return dependencyGroup.name; })); + var updated = ts.setEmitFlags(ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray([ + ts.createExpressionStatement(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("System"), "register"), + /*typeArguments*/ undefined, moduleName + ? [moduleName, dependencies, moduleBodyFunction] + : [dependencies, moduleBodyFunction])) + ]), node.statements)), 1024 /* NoTrailingComments */); + if (!(compilerOptions.outFile || compilerOptions.out)) { + ts.moveEmitHelpers(updated, moduleBodyBlock, function (helper) { return !helper.scoped; }); + } + if (noSubstitution) { + noSubstitutionMap[id] = noSubstitution; + noSubstitution = undefined; + } + currentSourceFile = undefined; + moduleInfo = undefined; + exportFunction = undefined; + contextObject = undefined; + hoistedStatements = undefined; + enclosingBlockScopedContainer = undefined; + return ts.aggregateTransformFlags(updated); + } + /** + * Collects the dependency groups for this files imports. + * + * @param externalImports The imports for the file. + */ + function collectDependencyGroups(externalImports) { + var groupIndices = ts.createMap(); + var dependencyGroups = []; + for (var _i = 0, externalImports_1 = externalImports; _i < externalImports_1.length; _i++) { + var externalImport = externalImports_1[_i]; + var externalModuleName = ts.getExternalModuleNameLiteral(externalImport, currentSourceFile, host, resolver, compilerOptions); + if (externalModuleName) { + var text = externalModuleName.text; + var groupIndex = groupIndices.get(text); + if (groupIndex !== undefined) { + // deduplicate/group entries in dependency list by the dependency name + dependencyGroups[groupIndex].externalImports.push(externalImport); + } + else { + groupIndices.set(text, dependencyGroups.length); + dependencyGroups.push({ + name: externalModuleName, + externalImports: [externalImport] + }); + } + } + } + return dependencyGroups; + } + /** + * Adds the statements for the module body function for the source file. + * + * @param node The source file for the module. + * @param dependencyGroups The grouped dependencies of the module. + */ + function createSystemModuleBody(node, dependencyGroups) { + // Shape of the body in system modules: + // + // function (exports) { + // + // + // + // return { + // setters: [ + // + // ], + // execute: function() { + // + // } + // } + // + // } + // + // i.e: + // + // import {x} from 'file1' + // var y = 1; + // export function foo() { return y + x(); } + // console.log(y); + // + // Will be transformed to: + // + // function(exports) { + // function foo() { return y + file_1.x(); } + // exports("foo", foo); + // var file_1, y; + // return { + // setters: [ + // function(v) { file_1 = v } + // ], + // execute(): function() { + // y = 1; + // console.log(y); + // } + // }; + // } + var statements = []; + // We start a new lexical environment in this function body, but *not* in the + // body of the execute function. This allows us to emit temporary declarations + // only in the outer module body and not in the inner one. + startLexicalEnvironment(); + // Add any prologue directives. + var ensureUseStrict = ts.getStrictOptionValue(compilerOptions, "alwaysStrict") || (!compilerOptions.noImplicitUseStrict && ts.isExternalModule(currentSourceFile)); + var statementOffset = ts.addPrologue(statements, node.statements, ensureUseStrict, sourceElementVisitor); + // var __moduleName = context_1 && context_1.id; + statements.push(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration("__moduleName", + /*type*/ undefined, ts.createLogicalAnd(contextObject, ts.createPropertyAccess(contextObject, "id"))) + ]))); + // Visit the synthetic external helpers import declaration if present + ts.visitNode(moduleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement); + // Visit the statements of the source file, emitting any transformations into + // the `executeStatements` array. We do this *before* we fill the `setters` array + // as we both emit transformations as well as aggregate some data used when creating + // setters. This allows us to reduce the number of times we need to loop through the + // statements of the source file. + var executeStatements = ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset); + // Emit early exports for function declarations. + ts.addRange(statements, hoistedStatements); + // We emit hoisted variables early to align roughly with our previous emit output. + // Two key differences in this approach are: + // - Temporary variables will appear at the top rather than at the bottom of the file + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + var exportStarFunction = addExportStarIfNeeded(statements); // TODO: GH#18217 + var moduleObject = ts.createObjectLiteral([ + ts.createPropertyAssignment("setters", createSettersArray(exportStarFunction, dependencyGroups)), + ts.createPropertyAssignment("execute", ts.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, + /*parameters*/ [], + /*type*/ undefined, ts.createBlock(executeStatements, /*multiLine*/ true))) + ]); + moduleObject.multiLine = true; + statements.push(ts.createReturn(moduleObject)); + return ts.createBlock(statements, /*multiLine*/ true); + } + /** + * Adds an exportStar function to a statement list if it is needed for the file. + * + * @param statements A statement list. + */ + function addExportStarIfNeeded(statements) { + if (!moduleInfo.hasExportStarsToExportValues) { + return; + } + // when resolving exports local exported entries/indirect exported entries in the module + // should always win over entries with similar names that were added via star exports + // to support this we store names of local/indirect exported entries in a set. + // this set is used to filter names brought by star expors. + // local names set should only be added if we have anything exported + if (!moduleInfo.exportedNames && moduleInfo.exportSpecifiers.size === 0) { + // no exported declarations (export var ...) or export specifiers (export {x}) + // check if we have any non star export declarations. + var hasExportDeclarationWithExportClause = false; + for (var _i = 0, _a = moduleInfo.externalImports; _i < _a.length; _i++) { + var externalImport = _a[_i]; + if (externalImport.kind === 255 /* ExportDeclaration */ && externalImport.exportClause) { + hasExportDeclarationWithExportClause = true; + break; + } + } + if (!hasExportDeclarationWithExportClause) { + // we still need to emit exportStar helper + var exportStarFunction_1 = createExportStarFunction(/*localNames*/ undefined); + statements.push(exportStarFunction_1); + return exportStarFunction_1.name; + } + } + var exportedNames = []; + if (moduleInfo.exportedNames) { + for (var _b = 0, _c = moduleInfo.exportedNames; _b < _c.length; _b++) { + var exportedLocalName = _c[_b]; + if (exportedLocalName.escapedText === "default") { + continue; + } + // write name of exported declaration, i.e 'export var x...' + exportedNames.push(ts.createPropertyAssignment(ts.createLiteral(exportedLocalName), ts.createTrue())); + } + } + for (var _d = 0, _e = moduleInfo.externalImports; _d < _e.length; _d++) { + var externalImport = _e[_d]; + if (externalImport.kind !== 255 /* ExportDeclaration */) { + continue; + } + if (!externalImport.exportClause) { + // export * from ... + continue; + } + for (var _f = 0, _g = externalImport.exportClause.elements; _f < _g.length; _f++) { + var element = _g[_f]; + // write name of indirectly exported entry, i.e. 'export {x} from ...' + exportedNames.push(ts.createPropertyAssignment(ts.createLiteral(ts.idText(element.name || element.propertyName)), ts.createTrue())); + } + } + var exportedNamesStorageRef = ts.createUniqueName("exportedNames"); + statements.push(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(exportedNamesStorageRef, + /*type*/ undefined, ts.createObjectLiteral(exportedNames, /*multiline*/ true)) + ]))); + var exportStarFunction = createExportStarFunction(exportedNamesStorageRef); + statements.push(exportStarFunction); + return exportStarFunction.name; + } + /** + * Creates an exportStar function for the file, with an optional set of excluded local + * names. + * + * @param localNames An optional reference to an object containing a set of excluded local + * names. + */ + function createExportStarFunction(localNames) { + var exportStarFunction = ts.createUniqueName("exportStar"); + var m = ts.createIdentifier("m"); + var n = ts.createIdentifier("n"); + var exports = ts.createIdentifier("exports"); + var condition = ts.createStrictInequality(n, ts.createLiteral("default")); + if (localNames) { + condition = ts.createLogicalAnd(condition, ts.createLogicalNot(ts.createCall(ts.createPropertyAccess(localNames, "hasOwnProperty"), + /*typeArguments*/ undefined, [n]))); + } + return ts.createFunctionDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, exportStarFunction, + /*typeParameters*/ undefined, [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, m)], + /*type*/ undefined, ts.createBlock([ + ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(exports, + /*type*/ undefined, ts.createObjectLiteral([])) + ])), + ts.createForIn(ts.createVariableDeclarationList([ + ts.createVariableDeclaration(n, /*type*/ undefined) + ]), m, ts.createBlock([ + ts.setEmitFlags(ts.createIf(condition, ts.createExpressionStatement(ts.createAssignment(ts.createElementAccess(exports, n), ts.createElementAccess(m, n)))), 1 /* SingleLine */) + ])), + ts.createExpressionStatement(ts.createCall(exportFunction, + /*typeArguments*/ undefined, [exports])) + ], /*multiline*/ true)); + } + /** + * Creates an array setter callbacks for each dependency group. + * + * @param exportStarFunction A reference to an exportStarFunction for the file. + * @param dependencyGroups An array of grouped dependencies. + */ + function createSettersArray(exportStarFunction, dependencyGroups) { + var setters = []; + for (var _i = 0, dependencyGroups_1 = dependencyGroups; _i < dependencyGroups_1.length; _i++) { + var group_1 = dependencyGroups_1[_i]; + // derive a unique name for parameter from the first named entry in the group + var localName = ts.forEach(group_1.externalImports, function (i) { return ts.getLocalNameForExternalImport(i, currentSourceFile); }); + var parameterName = localName ? ts.getGeneratedNameForNode(localName) : ts.createUniqueName(""); + var statements = []; + for (var _a = 0, _b = group_1.externalImports; _a < _b.length; _a++) { + var entry = _b[_a]; + var importVariableName = ts.getLocalNameForExternalImport(entry, currentSourceFile); // TODO: GH#18217 + switch (entry.kind) { + case 249 /* ImportDeclaration */: + if (!entry.importClause) { + // 'import "..."' case + // module is imported only for side-effects, no emit required + break; + } + // falls through + case 248 /* ImportEqualsDeclaration */: + ts.Debug.assert(importVariableName !== undefined); + // save import into the local + statements.push(ts.createExpressionStatement(ts.createAssignment(importVariableName, parameterName))); + break; + case 255 /* ExportDeclaration */: + ts.Debug.assert(importVariableName !== undefined); + if (entry.exportClause) { + // export {a, b as c} from 'foo' + // + // emit as: + // + // exports_({ + // "a": _["a"], + // "c": _["b"] + // }); + var properties = []; + for (var _c = 0, _d = entry.exportClause.elements; _c < _d.length; _c++) { + var e = _d[_c]; + properties.push(ts.createPropertyAssignment(ts.createLiteral(ts.idText(e.name)), ts.createElementAccess(parameterName, ts.createLiteral(ts.idText(e.propertyName || e.name))))); + } + statements.push(ts.createExpressionStatement(ts.createCall(exportFunction, + /*typeArguments*/ undefined, [ts.createObjectLiteral(properties, /*multiline*/ true)]))); + } + else { + // export * from 'foo' + // + // emit as: + // + // exportStar(foo_1_1); + statements.push(ts.createExpressionStatement(ts.createCall(exportStarFunction, + /*typeArguments*/ undefined, [parameterName]))); + } + break; + } + } + setters.push(ts.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, parameterName)], + /*type*/ undefined, ts.createBlock(statements, /*multiLine*/ true))); + } + return ts.createArrayLiteral(setters, /*multiLine*/ true); + } + // + // Top-level Source Element Visitors + // + /** + * Visit source elements at the top-level of a module. + * + * @param node The node to visit. + */ + function sourceElementVisitor(node) { + switch (node.kind) { + case 249 /* ImportDeclaration */: + return visitImportDeclaration(node); + case 248 /* ImportEqualsDeclaration */: + return visitImportEqualsDeclaration(node); + case 255 /* ExportDeclaration */: + // ExportDeclarations are elided as they are handled via + // `appendExportsOfDeclaration`. + return undefined; + case 254 /* ExportAssignment */: + return visitExportAssignment(node); + default: + return nestedElementVisitor(node); + } + } + /** + * Visits an ImportDeclaration node. + * + * @param node The node to visit. + */ + function visitImportDeclaration(node) { + var statements; + if (node.importClause) { + hoistVariableDeclaration(ts.getLocalNameForExternalImport(node, currentSourceFile)); // TODO: GH#18217 + } + if (hasAssociatedEndOfDeclarationMarker(node)) { + // Defer exports until we encounter an EndOfDeclarationMarker node + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportsOfImportDeclaration(deferredExports[id], node); + } + else { + statements = appendExportsOfImportDeclaration(statements, node); + } + return ts.singleOrMany(statements); + } + /** + * Visits an ImportEqualsDeclaration node. + * + * @param node The node to visit. + */ + function visitImportEqualsDeclaration(node) { + ts.Debug.assert(ts.isExternalModuleImportEqualsDeclaration(node), "import= for internal module references should be handled in an earlier transformer."); + var statements; + hoistVariableDeclaration(ts.getLocalNameForExternalImport(node, currentSourceFile)); // TODO: GH#18217 + if (hasAssociatedEndOfDeclarationMarker(node)) { + // Defer exports until we encounter an EndOfDeclarationMarker node + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportsOfImportEqualsDeclaration(deferredExports[id], node); + } + else { + statements = appendExportsOfImportEqualsDeclaration(statements, node); + } + return ts.singleOrMany(statements); + } + /** + * Visits an ExportAssignment node. + * + * @param node The node to visit. + */ + function visitExportAssignment(node) { + if (node.isExportEquals) { + // Elide `export=` as it is illegal in a SystemJS module. + return undefined; + } + var expression = ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression); + var original = node.original; + if (original && hasAssociatedEndOfDeclarationMarker(original)) { + // Defer exports until we encounter an EndOfDeclarationMarker node + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportStatement(deferredExports[id], ts.createIdentifier("default"), expression, /*allowComments*/ true); + } + else { + return createExportStatement(ts.createIdentifier("default"), expression, /*allowComments*/ true); + } + } + /** + * Visits a FunctionDeclaration, hoisting it to the outer module body function. + * + * @param node The node to visit. + */ + function visitFunctionDeclaration(node) { + if (ts.hasModifier(node, 1 /* Export */)) { + hoistedStatements = ts.append(hoistedStatements, ts.updateFunctionDeclaration(node, node.decorators, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, ts.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true), + /*typeParameters*/ undefined, ts.visitNodes(node.parameters, destructuringAndImportCallVisitor, ts.isParameterDeclaration), + /*type*/ undefined, ts.visitNode(node.body, destructuringAndImportCallVisitor, ts.isBlock))); + } + else { + hoistedStatements = ts.append(hoistedStatements, ts.visitEachChild(node, destructuringAndImportCallVisitor, context)); + } + if (hasAssociatedEndOfDeclarationMarker(node)) { + // Defer exports until we encounter an EndOfDeclarationMarker node + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node); + } + else { + hoistedStatements = appendExportsOfHoistedDeclaration(hoistedStatements, node); + } + return undefined; + } + /** + * Visits a ClassDeclaration, hoisting its name to the outer module body function. + * + * @param node The node to visit. + */ + function visitClassDeclaration(node) { + var statements; + // Hoist the name of the class declaration to the outer module body function. + var name = ts.getLocalName(node); + hoistVariableDeclaration(name); + // Rewrite the class declaration into an assignment of a class expression. + statements = ts.append(statements, ts.setTextRange(ts.createExpressionStatement(ts.createAssignment(name, ts.setTextRange(ts.createClassExpression( + /*modifiers*/ undefined, node.name, + /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, destructuringAndImportCallVisitor, ts.isHeritageClause), ts.visitNodes(node.members, destructuringAndImportCallVisitor, ts.isClassElement)), node))), node)); + if (hasAssociatedEndOfDeclarationMarker(node)) { + // Defer exports until we encounter an EndOfDeclarationMarker node + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node); + } + else { + statements = appendExportsOfHoistedDeclaration(statements, node); + } + return ts.singleOrMany(statements); + } + /** + * Visits a variable statement, hoisting declared names to the top-level module body. + * Each declaration is rewritten into an assignment expression. + * + * @param node The node to visit. + */ + function visitVariableStatement(node) { + if (!shouldHoistVariableDeclarationList(node.declarationList)) { + return ts.visitNode(node, destructuringAndImportCallVisitor, ts.isStatement); + } + var expressions; + var isExportedDeclaration = ts.hasModifier(node, 1 /* Export */); + var isMarkedDeclaration = hasAssociatedEndOfDeclarationMarker(node); + for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { + var variable = _a[_i]; + if (variable.initializer) { + expressions = ts.append(expressions, transformInitializedVariable(variable, isExportedDeclaration && !isMarkedDeclaration)); + } + else { + hoistBindingElement(variable); + } + } + var statements; + if (expressions) { + statements = ts.append(statements, ts.setTextRange(ts.createExpressionStatement(ts.inlineExpressions(expressions)), node)); + } + if (isMarkedDeclaration) { + // Defer exports until we encounter an EndOfDeclarationMarker node + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node, isExportedDeclaration); + } + else { + statements = appendExportsOfVariableStatement(statements, node, /*exportSelf*/ false); + } + return ts.singleOrMany(statements); + } + /** + * Hoists the declared names of a VariableDeclaration or BindingElement. + * + * @param node The declaration to hoist. + */ + function hoistBindingElement(node) { + if (ts.isBindingPattern(node.name)) { + for (var _i = 0, _a = node.name.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (!ts.isOmittedExpression(element)) { + hoistBindingElement(element); + } + } + } + else { + hoistVariableDeclaration(ts.getSynthesizedClone(node.name)); + } + } + /** + * Determines whether a VariableDeclarationList should be hoisted. + * + * @param node The node to test. + */ + function shouldHoistVariableDeclarationList(node) { + // hoist only non-block scoped declarations or block scoped declarations parented by source file + return (ts.getEmitFlags(node) & 2097152 /* NoHoisting */) === 0 + && (enclosingBlockScopedContainer.kind === 279 /* SourceFile */ + || (ts.getOriginalNode(node).flags & 3 /* BlockScoped */) === 0); + } + /** + * Transform an initialized variable declaration into an expression. + * + * @param node The node to transform. + * @param isExportedDeclaration A value indicating whether the variable is exported. + */ + function transformInitializedVariable(node, isExportedDeclaration) { + var createAssignment = isExportedDeclaration ? createExportedVariableAssignment : createNonExportedVariableAssignment; + return ts.isBindingPattern(node.name) + ? ts.flattenDestructuringAssignment(node, destructuringAndImportCallVisitor, context, 0 /* All */, + /*needsValue*/ false, createAssignment) + : node.initializer ? createAssignment(node.name, ts.visitNode(node.initializer, destructuringAndImportCallVisitor, ts.isExpression)) : node.name; + } + /** + * Creates an assignment expression for an exported variable declaration. + * + * @param name The name of the variable. + * @param value The value of the variable's initializer. + * @param location The source map location for the assignment. + */ + function createExportedVariableAssignment(name, value, location) { + return createVariableAssignment(name, value, location, /*isExportedDeclaration*/ true); + } + /** + * Creates an assignment expression for a non-exported variable declaration. + * + * @param name The name of the variable. + * @param value The value of the variable's initializer. + * @param location The source map location for the assignment. + */ + function createNonExportedVariableAssignment(name, value, location) { + return createVariableAssignment(name, value, location, /*isExportedDeclaration*/ false); + } + /** + * Creates an assignment expression for a variable declaration. + * + * @param name The name of the variable. + * @param value The value of the variable's initializer. + * @param location The source map location for the assignment. + * @param isExportedDeclaration A value indicating whether the variable is exported. + */ + function createVariableAssignment(name, value, location, isExportedDeclaration) { + hoistVariableDeclaration(ts.getSynthesizedClone(name)); + return isExportedDeclaration + ? createExportExpression(name, preventSubstitution(ts.setTextRange(ts.createAssignment(name, value), location))) + : preventSubstitution(ts.setTextRange(ts.createAssignment(name, value), location)); + } + /** + * Visits a MergeDeclarationMarker used as a placeholder for the beginning of a merged + * and transformed declaration. + * + * @param node The node to visit. + */ + function visitMergeDeclarationMarker(node) { + // For an EnumDeclaration or ModuleDeclaration that merges with a preceeding + // declaration we do not emit a leading variable declaration. To preserve the + // begin/end semantics of the declararation and to properly handle exports + // we wrapped the leading variable declaration in a `MergeDeclarationMarker`. + // + // To balance the declaration, we defer the exports of the elided variable + // statement until we visit this declaration's `EndOfDeclarationMarker`. + if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 219 /* VariableStatement */) { + var id = ts.getOriginalNodeId(node); + var isExportedDeclaration = ts.hasModifier(node.original, 1 /* Export */); + deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node.original, isExportedDeclaration); + } + return node; + } + /** + * Determines whether a node has an associated EndOfDeclarationMarker. + * + * @param node The node to test. + */ + function hasAssociatedEndOfDeclarationMarker(node) { + return (ts.getEmitFlags(node) & 4194304 /* HasEndOfDeclarationMarker */) !== 0; + } + /** + * Visits a DeclarationMarker used as a placeholder for the end of a transformed + * declaration. + * + * @param node The node to visit. + */ + function visitEndOfDeclarationMarker(node) { + // For some transformations we emit an `EndOfDeclarationMarker` to mark the actual + // end of the transformed declaration. We use this marker to emit any deferred exports + // of the declaration. + var id = ts.getOriginalNodeId(node); + var statements = deferredExports[id]; + if (statements) { + delete deferredExports[id]; + return ts.append(statements, node); + } + else { + var original = ts.getOriginalNode(node); + if (ts.isModuleOrEnumDeclaration(original)) { + return ts.append(appendExportsOfDeclaration(statements, original), node); + } + } + return node; + } + /** + * Appends the exports of an ImportDeclaration to a statement list, returning the + * statement list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param decl The declaration whose exports are to be recorded. + */ + function appendExportsOfImportDeclaration(statements, decl) { + if (moduleInfo.exportEquals) { + return statements; + } + var importClause = decl.importClause; + if (!importClause) { + return statements; + } + if (importClause.name) { + statements = appendExportsOfDeclaration(statements, importClause); + } + var namedBindings = importClause.namedBindings; + if (namedBindings) { + switch (namedBindings.kind) { + case 251 /* NamespaceImport */: + statements = appendExportsOfDeclaration(statements, namedBindings); + break; + case 252 /* NamedImports */: + for (var _i = 0, _a = namedBindings.elements; _i < _a.length; _i++) { + var importBinding = _a[_i]; + statements = appendExportsOfDeclaration(statements, importBinding); + } + break; + } + } + return statements; + } + /** + * Appends the export of an ImportEqualsDeclaration to a statement list, returning the + * statement list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param decl The declaration whose exports are to be recorded. + */ + function appendExportsOfImportEqualsDeclaration(statements, decl) { + if (moduleInfo.exportEquals) { + return statements; + } + return appendExportsOfDeclaration(statements, decl); + } + /** + * Appends the exports of a VariableStatement to a statement list, returning the statement + * list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param node The VariableStatement whose exports are to be recorded. + * @param exportSelf A value indicating whether to also export each VariableDeclaration of + * `nodes` declaration list. + */ + function appendExportsOfVariableStatement(statements, node, exportSelf) { + if (moduleInfo.exportEquals) { + return statements; + } + for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + if (decl.initializer || exportSelf) { + statements = appendExportsOfBindingElement(statements, decl, exportSelf); + } + } + return statements; + } + /** + * Appends the exports of a VariableDeclaration or BindingElement to a statement list, + * returning the statement list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param decl The declaration whose exports are to be recorded. + * @param exportSelf A value indicating whether to also export the declaration itself. + */ + function appendExportsOfBindingElement(statements, decl, exportSelf) { + if (moduleInfo.exportEquals) { + return statements; + } + if (ts.isBindingPattern(decl.name)) { + for (var _i = 0, _a = decl.name.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (!ts.isOmittedExpression(element)) { + statements = appendExportsOfBindingElement(statements, element, exportSelf); + } + } + } + else if (!ts.isGeneratedIdentifier(decl.name)) { + var excludeName = void 0; + if (exportSelf) { + statements = appendExportStatement(statements, decl.name, ts.getLocalName(decl)); + excludeName = ts.idText(decl.name); + } + statements = appendExportsOfDeclaration(statements, decl, excludeName); + } + return statements; + } + /** + * Appends the exports of a ClassDeclaration or FunctionDeclaration to a statement list, + * returning the statement list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param decl The declaration whose exports are to be recorded. + */ + function appendExportsOfHoistedDeclaration(statements, decl) { + if (moduleInfo.exportEquals) { + return statements; + } + var excludeName; + if (ts.hasModifier(decl, 1 /* Export */)) { + var exportName = ts.hasModifier(decl, 512 /* Default */) ? ts.createLiteral("default") : decl.name; + statements = appendExportStatement(statements, exportName, ts.getLocalName(decl)); + excludeName = ts.getTextOfIdentifierOrLiteral(exportName); + } + if (decl.name) { + statements = appendExportsOfDeclaration(statements, decl, excludeName); + } + return statements; + } + /** + * Appends the exports of a declaration to a statement list, returning the statement list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param decl The declaration to export. + * @param excludeName An optional name to exclude from exports. + */ + function appendExportsOfDeclaration(statements, decl, excludeName) { + if (moduleInfo.exportEquals) { + return statements; + } + var name = ts.getDeclarationName(decl); + var exportSpecifiers = moduleInfo.exportSpecifiers.get(ts.idText(name)); + if (exportSpecifiers) { + for (var _i = 0, exportSpecifiers_2 = exportSpecifiers; _i < exportSpecifiers_2.length; _i++) { + var exportSpecifier = exportSpecifiers_2[_i]; + if (exportSpecifier.name.escapedText !== excludeName) { + statements = appendExportStatement(statements, exportSpecifier.name, name); + } + } + } + return statements; + } + /** + * Appends the down-level representation of an export to a statement list, returning the + * statement list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param exportName The name of the export. + * @param expression The expression to export. + * @param allowComments Whether to allow comments on the export. + */ + function appendExportStatement(statements, exportName, expression, allowComments) { + statements = ts.append(statements, createExportStatement(exportName, expression, allowComments)); + return statements; + } + /** + * Creates a call to the current file's export function to export a value. + * + * @param name The bound name of the export. + * @param value The exported value. + * @param allowComments An optional value indicating whether to emit comments for the statement. + */ + function createExportStatement(name, value, allowComments) { + var statement = ts.createExpressionStatement(createExportExpression(name, value)); + ts.startOnNewLine(statement); + if (!allowComments) { + ts.setEmitFlags(statement, 1536 /* NoComments */); + } + return statement; + } + /** + * Creates a call to the current file's export function to export a value. + * + * @param name The bound name of the export. + * @param value The exported value. + */ + function createExportExpression(name, value) { + var exportName = ts.isIdentifier(name) ? ts.createLiteral(name) : name; + ts.setEmitFlags(value, ts.getEmitFlags(value) | 1536 /* NoComments */); + return ts.setCommentRange(ts.createCall(exportFunction, /*typeArguments*/ undefined, [exportName, value]), value); + } + // + // Top-Level or Nested Source Element Visitors + // + /** + * Visit nested elements at the top-level of a module. + * + * @param node The node to visit. + */ + function nestedElementVisitor(node) { + switch (node.kind) { + case 219 /* VariableStatement */: + return visitVariableStatement(node); + case 239 /* FunctionDeclaration */: + return visitFunctionDeclaration(node); + case 240 /* ClassDeclaration */: + return visitClassDeclaration(node); + case 225 /* ForStatement */: + return visitForStatement(node); + case 226 /* ForInStatement */: + return visitForInStatement(node); + case 227 /* ForOfStatement */: + return visitForOfStatement(node); + case 223 /* DoStatement */: + return visitDoStatement(node); + case 224 /* WhileStatement */: + return visitWhileStatement(node); + case 233 /* LabeledStatement */: + return visitLabeledStatement(node); + case 231 /* WithStatement */: + return visitWithStatement(node); + case 232 /* SwitchStatement */: + return visitSwitchStatement(node); + case 246 /* CaseBlock */: + return visitCaseBlock(node); + case 271 /* CaseClause */: + return visitCaseClause(node); + case 272 /* DefaultClause */: + return visitDefaultClause(node); + case 235 /* TryStatement */: + return visitTryStatement(node); + case 274 /* CatchClause */: + return visitCatchClause(node); + case 218 /* Block */: + return visitBlock(node); + case 310 /* MergeDeclarationMarker */: + return visitMergeDeclarationMarker(node); + case 311 /* EndOfDeclarationMarker */: + return visitEndOfDeclarationMarker(node); + default: + return destructuringAndImportCallVisitor(node); + } + } + /** + * Visits the body of a ForStatement to hoist declarations. + * + * @param node The node to visit. + */ + function visitForStatement(node) { + var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; + enclosingBlockScopedContainer = node; + node = ts.updateFor(node, node.initializer && visitForInitializer(node.initializer), ts.visitNode(node.condition, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.incrementor, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement)); + enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; + return node; + } + /** + * Visits the body of a ForInStatement to hoist declarations. + * + * @param node The node to visit. + */ + function visitForInStatement(node) { + var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; + enclosingBlockScopedContainer = node; + node = ts.updateForIn(node, visitForInitializer(node.initializer), ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock)); + enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; + return node; + } + /** + * Visits the body of a ForOfStatement to hoist declarations. + * + * @param node The node to visit. + */ + function visitForOfStatement(node) { + var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; + enclosingBlockScopedContainer = node; + node = ts.updateForOf(node, node.awaitModifier, visitForInitializer(node.initializer), ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock)); + enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; + return node; + } + /** + * Determines whether to hoist the initializer of a ForStatement, ForInStatement, or + * ForOfStatement. + * + * @param node The node to test. + */ + function shouldHoistForInitializer(node) { + return ts.isVariableDeclarationList(node) + && shouldHoistVariableDeclarationList(node); + } + /** + * Visits the initializer of a ForStatement, ForInStatement, or ForOfStatement + * + * @param node The node to visit. + */ + function visitForInitializer(node) { + if (shouldHoistForInitializer(node)) { + var expressions = void 0; + for (var _i = 0, _a = node.declarations; _i < _a.length; _i++) { + var variable = _a[_i]; + expressions = ts.append(expressions, transformInitializedVariable(variable, /*isExportedDeclaration*/ false)); + if (!variable.initializer) { + hoistBindingElement(variable); + } + } + return expressions ? ts.inlineExpressions(expressions) : ts.createOmittedExpression(); + } + else { + return ts.visitEachChild(node, nestedElementVisitor, context); + } + } + /** + * Visits the body of a DoStatement to hoist declarations. + * + * @param node The node to visit. + */ + function visitDoStatement(node) { + return ts.updateDo(node, ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock), ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression)); + } + /** + * Visits the body of a WhileStatement to hoist declarations. + * + * @param node The node to visit. + */ + function visitWhileStatement(node) { + return ts.updateWhile(node, ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock)); + } + /** + * Visits the body of a LabeledStatement to hoist declarations. + * + * @param node The node to visit. + */ + function visitLabeledStatement(node) { + return ts.updateLabel(node, node.label, ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock)); + } + /** + * Visits the body of a WithStatement to hoist declarations. + * + * @param node The node to visit. + */ + function visitWithStatement(node) { + return ts.updateWith(node, ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock)); + } + /** + * Visits the body of a SwitchStatement to hoist declarations. + * + * @param node The node to visit. + */ + function visitSwitchStatement(node) { + return ts.updateSwitch(node, ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.caseBlock, nestedElementVisitor, ts.isCaseBlock)); + } + /** + * Visits the body of a CaseBlock to hoist declarations. + * + * @param node The node to visit. + */ + function visitCaseBlock(node) { + var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; + enclosingBlockScopedContainer = node; + node = ts.updateCaseBlock(node, ts.visitNodes(node.clauses, nestedElementVisitor, ts.isCaseOrDefaultClause)); + enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; + return node; + } + /** + * Visits the body of a CaseClause to hoist declarations. + * + * @param node The node to visit. + */ + function visitCaseClause(node) { + return ts.updateCaseClause(node, ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNodes(node.statements, nestedElementVisitor, ts.isStatement)); + } + /** + * Visits the body of a DefaultClause to hoist declarations. + * + * @param node The node to visit. + */ + function visitDefaultClause(node) { + return ts.visitEachChild(node, nestedElementVisitor, context); + } + /** + * Visits the body of a TryStatement to hoist declarations. + * + * @param node The node to visit. + */ + function visitTryStatement(node) { + return ts.visitEachChild(node, nestedElementVisitor, context); + } + /** + * Visits the body of a CatchClause to hoist declarations. + * + * @param node The node to visit. + */ + function visitCatchClause(node) { + var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; + enclosingBlockScopedContainer = node; + node = ts.updateCatchClause(node, node.variableDeclaration, ts.visitNode(node.block, nestedElementVisitor, ts.isBlock)); + enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; + return node; + } + /** + * Visits the body of a Block to hoist declarations. + * + * @param node The node to visit. + */ + function visitBlock(node) { + var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; + enclosingBlockScopedContainer = node; + node = ts.visitEachChild(node, nestedElementVisitor, context); + enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; + return node; + } + // + // Destructuring Assignment Visitors + // + /** + * Visit nodes to flatten destructuring assignments to exported symbols. + * + * @param node The node to visit. + */ + function destructuringAndImportCallVisitor(node) { + if (node.transformFlags & 1024 /* DestructuringAssignment */ + && node.kind === 204 /* BinaryExpression */) { + return visitDestructuringAssignment(node); + } + else if (ts.isImportCall(node)) { + return visitImportCallExpression(node); + } + else if ((node.transformFlags & 2048 /* ContainsDestructuringAssignment */) || (node.transformFlags & 16777216 /* ContainsDynamicImport */)) { + return ts.visitEachChild(node, destructuringAndImportCallVisitor, context); + } + else { + return node; + } + } + function visitImportCallExpression(node) { + // import("./blah") + // emit as + // System.register([], function (_export, _context) { + // return { + // setters: [], + // execute: () => { + // _context.import('./blah'); + // } + // }; + // }); + return ts.createCall(ts.createPropertyAccess(contextObject, ts.createIdentifier("import")), + /*typeArguments*/ undefined, ts.some(node.arguments) ? [ts.visitNode(node.arguments[0], destructuringAndImportCallVisitor)] : []); + } + /** + * Visits a DestructuringAssignment to flatten destructuring to exported symbols. + * + * @param node The node to visit. + */ + function visitDestructuringAssignment(node) { + if (hasExportedReferenceInDestructuringTarget(node.left)) { + return ts.flattenDestructuringAssignment(node, destructuringAndImportCallVisitor, context, 0 /* All */, + /*needsValue*/ true); + } + return ts.visitEachChild(node, destructuringAndImportCallVisitor, context); + } + /** + * Determines whether the target of a destructuring assigment refers to an exported symbol. + * + * @param node The destructuring target. + */ + function hasExportedReferenceInDestructuringTarget(node) { + if (ts.isAssignmentExpression(node, /*excludeCompoundAssignment*/ true)) { + return hasExportedReferenceInDestructuringTarget(node.left); + } + else if (ts.isSpreadElement(node)) { + return hasExportedReferenceInDestructuringTarget(node.expression); + } + else if (ts.isObjectLiteralExpression(node)) { + return ts.some(node.properties, hasExportedReferenceInDestructuringTarget); + } + else if (ts.isArrayLiteralExpression(node)) { + return ts.some(node.elements, hasExportedReferenceInDestructuringTarget); + } + else if (ts.isShorthandPropertyAssignment(node)) { + return hasExportedReferenceInDestructuringTarget(node.name); + } + else if (ts.isPropertyAssignment(node)) { + return hasExportedReferenceInDestructuringTarget(node.initializer); + } + else if (ts.isIdentifier(node)) { + var container = resolver.getReferencedExportContainer(node); + return container !== undefined && container.kind === 279 /* SourceFile */; + } + else { + return false; + } + } + // + // Modifier Visitors + // + /** + * Visit nodes to elide module-specific modifiers. + * + * @param node The node to visit. + */ + function modifierVisitor(node) { + switch (node.kind) { + case 85 /* ExportKeyword */: + case 80 /* DefaultKeyword */: + return undefined; + } + return node; + } + // + // Emit Notification + // + /** + * Hook for node emit notifications. + * + * @param hint A hint as to the intended usage of the node. + * @param node The node to emit. + * @param emitCallback A callback used to emit the node in the printer. + */ + function onEmitNode(hint, node, emitCallback) { + if (node.kind === 279 /* SourceFile */) { + var id = ts.getOriginalNodeId(node); + currentSourceFile = node; + moduleInfo = moduleInfoMap[id]; + exportFunction = exportFunctionsMap[id]; + noSubstitution = noSubstitutionMap[id]; + if (noSubstitution) { + delete noSubstitutionMap[id]; + } + previousOnEmitNode(hint, node, emitCallback); + currentSourceFile = undefined; + moduleInfo = undefined; + exportFunction = undefined; + noSubstitution = undefined; + } + else { + previousOnEmitNode(hint, node, emitCallback); + } + } + // + // Substitutions + // + /** + * Hooks node substitutions. + * + * @param hint A hint as to the intended usage of the node. + * @param node The node to substitute. + */ + function onSubstituteNode(hint, node) { + node = previousOnSubstituteNode(hint, node); + if (isSubstitutionPrevented(node)) { + return node; + } + if (hint === 1 /* Expression */) { + return substituteExpression(node); + } + else if (hint === 4 /* Unspecified */) { + return substituteUnspecified(node); + } + return node; + } + /** + * Substitute the node, if necessary. + * + * @param node The node to substitute. + */ + function substituteUnspecified(node) { + switch (node.kind) { + case 276 /* ShorthandPropertyAssignment */: + return substituteShorthandPropertyAssignment(node); + } + return node; + } + /** + * Substitution for a ShorthandPropertyAssignment whose name that may contain an imported or exported symbol. + * + * @param node The node to substitute. + */ + function substituteShorthandPropertyAssignment(node) { + var name = node.name; + if (!ts.isGeneratedIdentifier(name) && !ts.isLocalName(name)) { + var importDeclaration = resolver.getReferencedImportDeclaration(name); + if (importDeclaration) { + if (ts.isImportClause(importDeclaration)) { + return ts.setTextRange(ts.createPropertyAssignment(ts.getSynthesizedClone(name), ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent), ts.createIdentifier("default"))), + /*location*/ node); + } + else if (ts.isImportSpecifier(importDeclaration)) { + return ts.setTextRange(ts.createPropertyAssignment(ts.getSynthesizedClone(name), ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent.parent.parent), ts.getSynthesizedClone(importDeclaration.propertyName || importDeclaration.name))), + /*location*/ node); + } + } + } + return node; + } + /** + * Substitute the expression, if necessary. + * + * @param node The node to substitute. + */ + function substituteExpression(node) { + switch (node.kind) { + case 72 /* Identifier */: + return substituteExpressionIdentifier(node); + case 204 /* BinaryExpression */: + return substituteBinaryExpression(node); + case 202 /* PrefixUnaryExpression */: + case 203 /* PostfixUnaryExpression */: + return substituteUnaryExpression(node); + } + return node; + } + /** + * Substitution for an Identifier expression that may contain an imported or exported symbol. + * + * @param node The node to substitute. + */ + function substituteExpressionIdentifier(node) { + if (ts.getEmitFlags(node) & 4096 /* HelperName */) { + var externalHelpersModuleName = ts.getExternalHelpersModuleName(currentSourceFile); + if (externalHelpersModuleName) { + return ts.createPropertyAccess(externalHelpersModuleName, node); + } + return node; + } + // When we see an identifier in an expression position that + // points to an imported symbol, we should substitute a qualified + // reference to the imported symbol if one is needed. + // + // - We do not substitute generated identifiers for any reason. + // - We do not substitute identifiers tagged with the LocalName flag. + if (!ts.isGeneratedIdentifier(node) && !ts.isLocalName(node)) { + var importDeclaration = resolver.getReferencedImportDeclaration(node); + if (importDeclaration) { + if (ts.isImportClause(importDeclaration)) { + return ts.setTextRange(ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent), ts.createIdentifier("default")), + /*location*/ node); + } + else if (ts.isImportSpecifier(importDeclaration)) { + return ts.setTextRange(ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent.parent.parent), ts.getSynthesizedClone(importDeclaration.propertyName || importDeclaration.name)), + /*location*/ node); + } + } + } + return node; + } + /** + * Substitution for a BinaryExpression that may contain an imported or exported symbol. + * + * @param node The node to substitute. + */ + function substituteBinaryExpression(node) { + // When we see an assignment expression whose left-hand side is an exported symbol, + // we should ensure all exports of that symbol are updated with the correct value. + // + // - We do not substitute generated identifiers for any reason. + // - We do not substitute identifiers tagged with the LocalName flag. + // - We do not substitute identifiers that were originally the name of an enum or + // namespace due to how they are transformed in TypeScript. + // - We only substitute identifiers that are exported at the top level. + if (ts.isAssignmentOperator(node.operatorToken.kind) + && ts.isIdentifier(node.left) + && !ts.isGeneratedIdentifier(node.left) + && !ts.isLocalName(node.left) + && !ts.isDeclarationNameOfEnumOrNamespace(node.left)) { + var exportedNames = getExports(node.left); + if (exportedNames) { + // For each additional export of the declaration, apply an export assignment. + var expression = node; + for (var _i = 0, exportedNames_4 = exportedNames; _i < exportedNames_4.length; _i++) { + var exportName = exportedNames_4[_i]; + expression = createExportExpression(exportName, preventSubstitution(expression)); + } + return expression; + } + } + return node; + } + /** + * Substitution for a UnaryExpression that may contain an imported or exported symbol. + * + * @param node The node to substitute. + */ + function substituteUnaryExpression(node) { + // When we see a prefix or postfix increment expression whose operand is an exported + // symbol, we should ensure all exports of that symbol are updated with the correct + // value. + // + // - We do not substitute generated identifiers for any reason. + // - We do not substitute identifiers tagged with the LocalName flag. + // - We do not substitute identifiers that were originally the name of an enum or + // namespace due to how they are transformed in TypeScript. + // - We only substitute identifiers that are exported at the top level. + if ((node.operator === 44 /* PlusPlusToken */ || node.operator === 45 /* MinusMinusToken */) + && ts.isIdentifier(node.operand) + && !ts.isGeneratedIdentifier(node.operand) + && !ts.isLocalName(node.operand) + && !ts.isDeclarationNameOfEnumOrNamespace(node.operand)) { + var exportedNames = getExports(node.operand); + if (exportedNames) { + var expression = node.kind === 203 /* PostfixUnaryExpression */ + ? ts.setTextRange(ts.createPrefix(node.operator, node.operand), node) + : node; + for (var _i = 0, exportedNames_5 = exportedNames; _i < exportedNames_5.length; _i++) { + var exportName = exportedNames_5[_i]; + expression = createExportExpression(exportName, preventSubstitution(expression)); + } + if (node.kind === 203 /* PostfixUnaryExpression */) { + expression = node.operator === 44 /* PlusPlusToken */ + ? ts.createSubtract(preventSubstitution(expression), ts.createLiteral(1)) + : ts.createAdd(preventSubstitution(expression), ts.createLiteral(1)); + } + return expression; + } + } + return node; + } + /** + * Gets the exports of a name. + * + * @param name The name. + */ + function getExports(name) { + var exportedNames; + if (!ts.isGeneratedIdentifier(name)) { + var valueDeclaration = resolver.getReferencedImportDeclaration(name) + || resolver.getReferencedValueDeclaration(name); + if (valueDeclaration) { + var exportContainer = resolver.getReferencedExportContainer(name, /*prefixLocals*/ false); + if (exportContainer && exportContainer.kind === 279 /* SourceFile */) { + exportedNames = ts.append(exportedNames, ts.getDeclarationName(valueDeclaration)); + } + exportedNames = ts.addRange(exportedNames, moduleInfo && moduleInfo.exportedBindings[ts.getOriginalNodeId(valueDeclaration)]); + } + } + return exportedNames; + } + /** + * Prevent substitution of a node for this transformer. + * + * @param node The node which should not be substituted. + */ + function preventSubstitution(node) { + if (noSubstitution === undefined) + noSubstitution = []; + noSubstitution[ts.getNodeId(node)] = true; + return node; + } + /** + * Determines whether a node should not be substituted. + * + * @param node The node to test. + */ + function isSubstitutionPrevented(node) { + return noSubstitution && node.id && noSubstitution[node.id]; + } + } + ts.transformSystemModule = transformSystemModule; +})(ts || (ts = {})); +/*@internal*/ +var ts; +(function (ts) { + function transformES2015Module(context) { + var compilerOptions = context.getCompilerOptions(); + var previousOnEmitNode = context.onEmitNode; + var previousOnSubstituteNode = context.onSubstituteNode; + context.onEmitNode = onEmitNode; + context.onSubstituteNode = onSubstituteNode; + context.enableEmitNotification(279 /* SourceFile */); + context.enableSubstitution(72 /* Identifier */); + var currentSourceFile; + return ts.chainBundle(transformSourceFile); + function transformSourceFile(node) { + if (node.isDeclarationFile) { + return node; + } + if (ts.isExternalModule(node) || compilerOptions.isolatedModules) { + var externalHelpersModuleName = ts.getOrCreateExternalHelpersModuleNameIfNeeded(node, compilerOptions); + if (externalHelpersModuleName) { + var statements = []; + var statementOffset = ts.addPrologue(statements, node.statements); + var tslibImport = ts.createImportDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(externalHelpersModuleName)), ts.createLiteral(ts.externalHelpersModuleNameText)); + ts.addEmitFlags(tslibImport, 67108864 /* NeverApplyImportHelper */); + ts.append(statements, tslibImport); + ts.addRange(statements, ts.visitNodes(node.statements, visitor, ts.isStatement, statementOffset)); + return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements)); + } + else { + return ts.visitEachChild(node, visitor, context); + } + } + return node; + } + function visitor(node) { + switch (node.kind) { + case 248 /* ImportEqualsDeclaration */: + // Elide `import=` as it is not legal with --module ES6 + return undefined; + case 254 /* ExportAssignment */: + return visitExportAssignment(node); + } + return node; + } + function visitExportAssignment(node) { + // Elide `export=` as it is not legal with --module ES6 + return node.isExportEquals ? undefined : node; + } + // + // Emit Notification + // + /** + * Hook for node emit. + * + * @param hint A hint as to the intended usage of the node. + * @param node The node to emit. + * @param emit A callback used to emit the node in the printer. + */ + function onEmitNode(hint, node, emitCallback) { + if (ts.isSourceFile(node)) { + currentSourceFile = node; + previousOnEmitNode(hint, node, emitCallback); + currentSourceFile = undefined; + } + else { + previousOnEmitNode(hint, node, emitCallback); + } + } + // + // Substitutions + // + /** + * Hooks node substitutions. + * + * @param hint A hint as to the intended usage of the node. + * @param node The node to substitute. + */ + function onSubstituteNode(hint, node) { + node = previousOnSubstituteNode(hint, node); + if (ts.isIdentifier(node) && hint === 1 /* Expression */) { + return substituteExpressionIdentifier(node); + } + return node; + } + function substituteExpressionIdentifier(node) { + if (ts.getEmitFlags(node) & 4096 /* HelperName */) { + var externalHelpersModuleName = ts.getExternalHelpersModuleName(currentSourceFile); + if (externalHelpersModuleName) { + return ts.createPropertyAccess(externalHelpersModuleName, node); + } + } + return node; + } + } + ts.transformES2015Module = transformES2015Module; +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + function canProduceDiagnostics(node) { + return ts.isVariableDeclaration(node) || + ts.isPropertyDeclaration(node) || + ts.isPropertySignature(node) || + ts.isBindingElement(node) || + ts.isSetAccessor(node) || + ts.isGetAccessor(node) || + ts.isConstructSignatureDeclaration(node) || + ts.isCallSignatureDeclaration(node) || + ts.isMethodDeclaration(node) || + ts.isMethodSignature(node) || + ts.isFunctionDeclaration(node) || + ts.isParameter(node) || + ts.isTypeParameterDeclaration(node) || + ts.isExpressionWithTypeArguments(node) || + ts.isImportEqualsDeclaration(node) || + ts.isTypeAliasDeclaration(node) || + ts.isConstructorDeclaration(node) || + ts.isIndexSignatureDeclaration(node); + } + ts.canProduceDiagnostics = canProduceDiagnostics; + function createGetSymbolAccessibilityDiagnosticForNodeName(node) { + if (ts.isSetAccessor(node) || ts.isGetAccessor(node)) { + return getAccessorNameVisibilityError; + } + else if (ts.isMethodSignature(node) || ts.isMethodDeclaration(node)) { + return getMethodNameVisibilityError; + } + else { + return createGetSymbolAccessibilityDiagnosticForNode(node); + } + function getAccessorNameVisibilityError(symbolAccessibilityResult) { + var diagnosticMessage = getAccessorNameVisibilityDiagnosticMessage(symbolAccessibilityResult); + return diagnosticMessage !== undefined ? { + diagnosticMessage: diagnosticMessage, + errorNode: node, + typeName: node.name + } : undefined; + } + function getAccessorNameVisibilityDiagnosticMessage(symbolAccessibilityResult) { + if (ts.hasModifier(node, 32 /* Static */)) { + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1; + } + else if (node.parent.kind === 240 /* ClassDeclaration */) { + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_private_name_1; + } + else { + return symbolAccessibilityResult.errorModuleName ? + ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_private_name_1; + } + } + function getMethodNameVisibilityError(symbolAccessibilityResult) { + var diagnosticMessage = getMethodNameVisibilityDiagnosticMessage(symbolAccessibilityResult); + return diagnosticMessage !== undefined ? { + diagnosticMessage: diagnosticMessage, + errorNode: node, + typeName: node.name + } : undefined; + } + function getMethodNameVisibilityDiagnosticMessage(symbolAccessibilityResult) { + if (ts.hasModifier(node, 32 /* Static */)) { + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_private_name_1; + } + else if (node.parent.kind === 240 /* ClassDeclaration */) { + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Public_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Public_method_0_of_exported_class_has_or_is_using_private_name_1; + } + else { + return symbolAccessibilityResult.errorModuleName ? + ts.Diagnostics.Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Method_0_of_exported_interface_has_or_is_using_private_name_1; + } + } + } + ts.createGetSymbolAccessibilityDiagnosticForNodeName = createGetSymbolAccessibilityDiagnosticForNodeName; + function createGetSymbolAccessibilityDiagnosticForNode(node) { + if (ts.isVariableDeclaration(node) || ts.isPropertyDeclaration(node) || ts.isPropertySignature(node) || ts.isBindingElement(node) || ts.isConstructorDeclaration(node)) { + return getVariableDeclarationTypeVisibilityError; + } + else if (ts.isSetAccessor(node) || ts.isGetAccessor(node)) { + return getAccessorDeclarationTypeVisibilityError; + } + else if (ts.isConstructSignatureDeclaration(node) || ts.isCallSignatureDeclaration(node) || ts.isMethodDeclaration(node) || ts.isMethodSignature(node) || ts.isFunctionDeclaration(node) || ts.isIndexSignatureDeclaration(node)) { + return getReturnTypeVisibilityError; + } + else if (ts.isParameter(node)) { + if (ts.isParameterPropertyDeclaration(node) && ts.hasModifier(node.parent, 8 /* Private */)) { + return getVariableDeclarationTypeVisibilityError; + } + return getParameterDeclarationTypeVisibilityError; + } + else if (ts.isTypeParameterDeclaration(node)) { + return getTypeParameterConstraintVisibilityError; + } + else if (ts.isExpressionWithTypeArguments(node)) { + return getHeritageClauseVisibilityError; + } + else if (ts.isImportEqualsDeclaration(node)) { + return getImportEntityNameVisibilityError; + } + else if (ts.isTypeAliasDeclaration(node)) { + return getTypeAliasDeclarationVisibilityError; + } + else { + return ts.Debug.assertNever(node, "Attempted to set a declaration diagnostic context for unhandled node kind: " + ts.SyntaxKind[node.kind]); + } + function getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) { + if (node.kind === 237 /* VariableDeclaration */ || node.kind === 186 /* BindingElement */) { + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Exported_variable_0_has_or_is_using_private_name_1; + } + // This check is to ensure we don't report error on constructor parameter property as that error would be reported during parameter emit + // The only exception here is if the constructor was marked as private. we are not emitting the constructor parameters at all. + else if (node.kind === 154 /* PropertyDeclaration */ || node.kind === 153 /* PropertySignature */ || + (node.kind === 151 /* Parameter */ && ts.hasModifier(node.parent, 8 /* Private */))) { + // TODO(jfreeman): Deal with computed properties in error reporting. + if (ts.hasModifier(node, 32 /* Static */)) { + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1; + } + else if (node.parent.kind === 240 /* ClassDeclaration */ || node.kind === 151 /* Parameter */) { + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_private_name_1; + } + else { + // Interfaces cannot have types that cannot be named + return symbolAccessibilityResult.errorModuleName ? + ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_private_name_1; + } + } + } + function getVariableDeclarationTypeVisibilityError(symbolAccessibilityResult) { + var diagnosticMessage = getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult); + return diagnosticMessage !== undefined ? { + diagnosticMessage: diagnosticMessage, + errorNode: node, + typeName: node.name + } : undefined; + } + function getAccessorDeclarationTypeVisibilityError(symbolAccessibilityResult) { + var diagnosticMessage; + if (node.kind === 159 /* SetAccessor */) { + // Getters can infer the return type from the returned expression, but setters cannot, so the + // "_from_external_module_1_but_cannot_be_named" case cannot occur. + if (ts.hasModifier(node, 32 /* Static */)) { + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + ts.Diagnostics.Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1; + } + else { + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + ts.Diagnostics.Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_private_name_1; + } + } + else { + if (ts.hasModifier(node, 32 /* Static */)) { + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_private_name_1; + } + else { + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Return_type_of_public_getter_0_from_exported_class_has_or_is_using_private_name_1; + } + } + return { + diagnosticMessage: diagnosticMessage, + errorNode: node.name, + typeName: node.name + }; + } + function getReturnTypeVisibilityError(symbolAccessibilityResult) { + var diagnosticMessage; + switch (node.kind) { + case 161 /* ConstructSignature */: + // Interfaces cannot have return types that cannot be named + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + ts.Diagnostics.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : + ts.Diagnostics.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0; + break; + case 160 /* CallSignature */: + // Interfaces cannot have return types that cannot be named + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + ts.Diagnostics.Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : + ts.Diagnostics.Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0; + break; + case 162 /* IndexSignature */: + // Interfaces cannot have return types that cannot be named + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + ts.Diagnostics.Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : + ts.Diagnostics.Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0; + break; + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + if (ts.hasModifier(node, 32 /* Static */)) { + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : + ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1 : + ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0; + } + else if (node.parent.kind === 240 /* ClassDeclaration */) { + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : + ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1 : + ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0; + } + else { + // Interfaces cannot have return types that cannot be named + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + ts.Diagnostics.Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : + ts.Diagnostics.Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0; + } + break; + case 239 /* FunctionDeclaration */: + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : + ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1 : + ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_private_name_0; + break; + default: + return ts.Debug.fail("This is unknown kind for signature: " + node.kind); + } + return { + diagnosticMessage: diagnosticMessage, + errorNode: node.name || node + }; + } + function getParameterDeclarationTypeVisibilityError(symbolAccessibilityResult) { + var diagnosticMessage = getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult); + return diagnosticMessage !== undefined ? { + diagnosticMessage: diagnosticMessage, + errorNode: node, + typeName: node.name + } : undefined; + } + function getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) { + switch (node.parent.kind) { + case 157 /* Constructor */: + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1; + case 161 /* ConstructSignature */: + case 166 /* ConstructorType */: + // Interfaces cannot have parameter types that cannot be named + return symbolAccessibilityResult.errorModuleName ? + ts.Diagnostics.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1; + case 160 /* CallSignature */: + // Interfaces cannot have parameter types that cannot be named + return symbolAccessibilityResult.errorModuleName ? + ts.Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1; + case 162 /* IndexSignature */: + // Interfaces cannot have parameter types that cannot be named + return symbolAccessibilityResult.errorModuleName ? + ts.Diagnostics.Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1; + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + if (ts.hasModifier(node.parent, 32 /* Static */)) { + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1; + } + else if (node.parent.parent.kind === 240 /* ClassDeclaration */) { + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1; + } + else { + // Interfaces cannot have parameter types that cannot be named + return symbolAccessibilityResult.errorModuleName ? + ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1; + } + case 239 /* FunctionDeclaration */: + case 165 /* FunctionType */: + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_private_name_1; + default: + return ts.Debug.fail("Unknown parent for parameter: " + ts.SyntaxKind[node.parent.kind]); + } + } + function getTypeParameterConstraintVisibilityError() { + // Type parameter constraints are named by user so we should always be able to name it + var diagnosticMessage; + switch (node.parent.kind) { + case 240 /* ClassDeclaration */: + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_class_has_or_is_using_private_name_1; + break; + case 241 /* InterfaceDeclaration */: + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1; + break; + case 161 /* ConstructSignature */: + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1; + break; + case 160 /* CallSignature */: + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1; + break; + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + if (ts.hasModifier(node.parent, 32 /* Static */)) { + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1; + } + else if (node.parent.parent.kind === 240 /* ClassDeclaration */) { + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1; + } + else { + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1; + } + break; + case 239 /* FunctionDeclaration */: + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_function_has_or_is_using_private_name_1; + break; + case 242 /* TypeAliasDeclaration */: + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1; + break; + default: + return ts.Debug.fail("This is unknown parent for type parameter: " + node.parent.kind); + } + return { + diagnosticMessage: diagnosticMessage, + errorNode: node, + typeName: node.name + }; + } + function getHeritageClauseVisibilityError() { + var diagnosticMessage; + // Heritage clause is written by user so it can always be named + if (node.parent.parent.kind === 240 /* ClassDeclaration */) { + // Class or Interface implemented/extended is inaccessible + diagnosticMessage = ts.isHeritageClause(node.parent) && node.parent.token === 109 /* ImplementsKeyword */ ? + ts.Diagnostics.Implements_clause_of_exported_class_0_has_or_is_using_private_name_1 : + ts.Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1; + } + else { + // interface is inaccessible + diagnosticMessage = ts.Diagnostics.extends_clause_of_exported_interface_0_has_or_is_using_private_name_1; + } + return { + diagnosticMessage: diagnosticMessage, + errorNode: node, + typeName: ts.getNameOfDeclaration(node.parent.parent) + }; + } + function getImportEntityNameVisibilityError() { + return { + diagnosticMessage: ts.Diagnostics.Import_declaration_0_is_using_private_name_1, + errorNode: node, + typeName: node.name + }; + } + function getTypeAliasDeclarationVisibilityError() { + return { + diagnosticMessage: ts.Diagnostics.Exported_type_alias_0_has_or_is_using_private_name_1, + errorNode: node.type, + typeName: node.name + }; + } + } + ts.createGetSymbolAccessibilityDiagnosticForNode = createGetSymbolAccessibilityDiagnosticForNode; +})(ts || (ts = {})); +/*@internal*/ +var ts; +(function (ts) { + function getDeclarationDiagnostics(host, resolver, file) { + if (file && ts.isSourceFileJS(file)) { + return []; // No declaration diagnostics for js for now + } + var compilerOptions = host.getCompilerOptions(); + var result = ts.transformNodes(resolver, host, compilerOptions, file ? [file] : ts.filter(host.getSourceFiles(), ts.isSourceFileNotJS), [transformDeclarations], /*allowDtsFiles*/ false); + return result.diagnostics; + } + ts.getDeclarationDiagnostics = getDeclarationDiagnostics; + var declarationEmitNodeBuilderFlags = 1024 /* MultilineObjectLiterals */ | + 2048 /* WriteClassExpressionAsTypeLiteral */ | + 4096 /* UseTypeOfFunction */ | + 8 /* UseStructuralFallback */ | + 524288 /* AllowEmptyTuple */ | + 4 /* GenerateNamesForShadowedTypeParams */ | + 1 /* NoTruncation */; + /** + * Transforms a ts file into a .d.ts file + * This process requires type information, which is retrieved through the emit resolver. Because of this, + * in many places this transformer assumes it will be operating on parse tree nodes directly. + * This means that _no transforms should be allowed to occur before this one_. + */ + function transformDeclarations(context) { + var throwDiagnostic = function () { return ts.Debug.fail("Diagnostic emitted without context"); }; + var getSymbolAccessibilityDiagnostic = throwDiagnostic; + var needsDeclare = true; + var isBundledEmit = false; + var resultHasExternalModuleIndicator = false; + var needsScopeFixMarker = false; + var resultHasScopeMarker = false; + var enclosingDeclaration; + var necessaryTypeReferences; + var lateMarkedStatements; + var lateStatementReplacementMap; + var suppressNewDiagnosticContexts; + var exportedModulesFromDeclarationEmit; + var host = context.getEmitHost(); + var symbolTracker = { + trackSymbol: trackSymbol, + reportInaccessibleThisError: reportInaccessibleThisError, + reportInaccessibleUniqueSymbolError: reportInaccessibleUniqueSymbolError, + reportPrivateInBaseOfClassExpression: reportPrivateInBaseOfClassExpression, + reportLikelyUnsafeImportRequiredError: reportLikelyUnsafeImportRequiredError, + moduleResolverHost: host, + trackReferencedAmbientModule: trackReferencedAmbientModule, + trackExternalModuleSymbolOfImportTypeNode: trackExternalModuleSymbolOfImportTypeNode + }; + var errorNameNode; + var currentSourceFile; + var refs; + var libs; + var resolver = context.getEmitResolver(); + var options = context.getCompilerOptions(); + var newLine = ts.getNewLineCharacter(options); + var noResolve = options.noResolve, stripInternal = options.stripInternal; + return transformRoot; + function recordTypeReferenceDirectivesIfNecessary(typeReferenceDirectives) { + if (!typeReferenceDirectives) { + return; + } + necessaryTypeReferences = necessaryTypeReferences || ts.createMap(); + for (var _i = 0, typeReferenceDirectives_2 = typeReferenceDirectives; _i < typeReferenceDirectives_2.length; _i++) { + var ref = typeReferenceDirectives_2[_i]; + necessaryTypeReferences.set(ref, true); + } + } + function trackReferencedAmbientModule(node, symbol) { + // If it is visible via `// `, then we should just use that + var directives = resolver.getTypeReferenceDirectivesForSymbol(symbol, 67108863 /* All */); + if (ts.length(directives)) { + return recordTypeReferenceDirectivesIfNecessary(directives); + } + // Otherwise we should emit a path-based reference + var container = ts.getSourceFileOfNode(node); + refs.set("" + ts.getOriginalNodeId(container), container); + } + function handleSymbolAccessibilityError(symbolAccessibilityResult) { + if (symbolAccessibilityResult.accessibility === 0 /* Accessible */) { + // Add aliases back onto the possible imports list if they're not there so we can try them again with updated visibility info + if (symbolAccessibilityResult && symbolAccessibilityResult.aliasesToMakeVisible) { + if (!lateMarkedStatements) { + lateMarkedStatements = symbolAccessibilityResult.aliasesToMakeVisible; + } + else { + for (var _i = 0, _a = symbolAccessibilityResult.aliasesToMakeVisible; _i < _a.length; _i++) { + var ref = _a[_i]; + ts.pushIfUnique(lateMarkedStatements, ref); + } + } + } + // TODO: Do all these accessibility checks inside/after the first pass in the checker when declarations are enabled, if possible + } + else { + // Report error + var errorInfo = getSymbolAccessibilityDiagnostic(symbolAccessibilityResult); + if (errorInfo) { + if (errorInfo.typeName) { + context.addDiagnostic(ts.createDiagnosticForNode(symbolAccessibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, ts.getTextOfNode(errorInfo.typeName), symbolAccessibilityResult.errorSymbolName, symbolAccessibilityResult.errorModuleName)); + } + else { + context.addDiagnostic(ts.createDiagnosticForNode(symbolAccessibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, symbolAccessibilityResult.errorSymbolName, symbolAccessibilityResult.errorModuleName)); + } + } + } + } + function trackExternalModuleSymbolOfImportTypeNode(symbol) { + if (!isBundledEmit) { + (exportedModulesFromDeclarationEmit || (exportedModulesFromDeclarationEmit = [])).push(symbol); + } + } + function trackSymbol(symbol, enclosingDeclaration, meaning) { + if (symbol.flags & 262144 /* TypeParameter */) + return; + handleSymbolAccessibilityError(resolver.isSymbolAccessible(symbol, enclosingDeclaration, meaning, /*shouldComputeAliasesToMakeVisible*/ true)); + recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForSymbol(symbol, meaning)); + } + function reportPrivateInBaseOfClassExpression(propertyName) { + if (errorNameNode) { + context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.Property_0_of_exported_class_expression_may_not_be_private_or_protected, propertyName)); + } + } + function reportInaccessibleUniqueSymbolError() { + if (errorNameNode) { + context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary, ts.declarationNameToString(errorNameNode), "unique symbol")); + } + } + function reportInaccessibleThisError() { + if (errorNameNode) { + context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary, ts.declarationNameToString(errorNameNode), "this")); + } + } + function reportLikelyUnsafeImportRequiredError(specifier) { + if (errorNameNode) { + context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_annotation_is_necessary, ts.declarationNameToString(errorNameNode), specifier)); + } + } + function transformRoot(node) { + if (node.kind === 279 /* SourceFile */ && (node.isDeclarationFile || ts.isSourceFileJS(node))) { + return node; + } + if (node.kind === 280 /* Bundle */) { + isBundledEmit = true; + refs = ts.createMap(); + libs = ts.createMap(); + var hasNoDefaultLib_1 = false; + var bundle = ts.createBundle(ts.map(node.sourceFiles, function (sourceFile) { + if (sourceFile.isDeclarationFile || ts.isSourceFileJS(sourceFile)) + return undefined; // Omit declaration files from bundle results, too // TODO: GH#18217 + hasNoDefaultLib_1 = hasNoDefaultLib_1 || sourceFile.hasNoDefaultLib; + currentSourceFile = sourceFile; + enclosingDeclaration = sourceFile; + lateMarkedStatements = undefined; + suppressNewDiagnosticContexts = false; + lateStatementReplacementMap = ts.createMap(); + getSymbolAccessibilityDiagnostic = throwDiagnostic; + needsScopeFixMarker = false; + resultHasScopeMarker = false; + collectReferences(sourceFile, refs); + collectLibs(sourceFile, libs); + if (ts.isExternalModule(sourceFile)) { + resultHasExternalModuleIndicator = false; // unused in external module bundle emit (all external modules are within module blocks, therefore are known to be modules) + needsDeclare = false; + var statements_4 = ts.visitNodes(sourceFile.statements, visitDeclarationStatements); + var newFile = ts.updateSourceFileNode(sourceFile, [ts.createModuleDeclaration([], [ts.createModifier(125 /* DeclareKeyword */)], ts.createLiteral(ts.getResolvedExternalModuleName(context.getEmitHost(), sourceFile)), ts.createModuleBlock(ts.setTextRange(ts.createNodeArray(transformAndReplaceLatePaintedStatements(statements_4)), sourceFile.statements)))], /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false, /*libReferences*/ []); + return newFile; + } + needsDeclare = true; + var updated = ts.visitNodes(sourceFile.statements, visitDeclarationStatements); + return ts.updateSourceFileNode(sourceFile, transformAndReplaceLatePaintedStatements(updated), /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false, /*libReferences*/ []); + }), ts.mapDefined(node.prepends, function (prepend) { + if (prepend.kind === 282 /* InputFiles */) { + return ts.createUnparsedSourceFile(prepend.declarationText, prepend.declarationMapPath, prepend.declarationMapText); + } + })); + bundle.syntheticFileReferences = []; + bundle.syntheticTypeReferences = getFileReferencesForUsedTypeReferences(); + bundle.syntheticLibReferences = getLibReferences(); + bundle.hasNoDefaultLib = hasNoDefaultLib_1; + var outputFilePath_1 = ts.getDirectoryPath(ts.normalizeSlashes(ts.getOutputPathsFor(node, host, /*forceDtsPaths*/ true).declarationFilePath)); + var referenceVisitor_1 = mapReferencesIntoArray(bundle.syntheticFileReferences, outputFilePath_1); + refs.forEach(referenceVisitor_1); + return bundle; + } + // Single source file + needsDeclare = true; + needsScopeFixMarker = false; + resultHasScopeMarker = false; + enclosingDeclaration = node; + currentSourceFile = node; + getSymbolAccessibilityDiagnostic = throwDiagnostic; + isBundledEmit = false; + resultHasExternalModuleIndicator = false; + suppressNewDiagnosticContexts = false; + lateMarkedStatements = undefined; + lateStatementReplacementMap = ts.createMap(); + necessaryTypeReferences = undefined; + refs = collectReferences(currentSourceFile, ts.createMap()); + libs = collectLibs(currentSourceFile, ts.createMap()); + var references = []; + var outputFilePath = ts.getDirectoryPath(ts.normalizeSlashes(ts.getOutputPathsFor(node, host, /*forceDtsPaths*/ true).declarationFilePath)); + var referenceVisitor = mapReferencesIntoArray(references, outputFilePath); + var statements = ts.visitNodes(node.statements, visitDeclarationStatements); + var combinedStatements = ts.setTextRange(ts.createNodeArray(transformAndReplaceLatePaintedStatements(statements)), node.statements); + refs.forEach(referenceVisitor); + var emittedImports = ts.filter(combinedStatements, ts.isAnyImportSyntax); + if (ts.isExternalModule(node) && (!resultHasExternalModuleIndicator || (needsScopeFixMarker && !resultHasScopeMarker))) { + combinedStatements = ts.setTextRange(ts.createNodeArray(combinedStatements.concat([ts.createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createNamedExports([]), /*moduleSpecifier*/ undefined)])), combinedStatements); + } + var updated = ts.updateSourceFileNode(node, combinedStatements, /*isDeclarationFile*/ true, references, getFileReferencesForUsedTypeReferences(), node.hasNoDefaultLib, getLibReferences()); + updated.exportedModulesFromDeclarationEmit = exportedModulesFromDeclarationEmit; + return updated; + function getLibReferences() { + return ts.map(ts.arrayFrom(libs.keys()), function (lib) { return ({ fileName: lib, pos: -1, end: -1 }); }); + } + function getFileReferencesForUsedTypeReferences() { + return necessaryTypeReferences ? ts.mapDefined(ts.arrayFrom(necessaryTypeReferences.keys()), getFileReferenceForTypeName) : []; + } + function getFileReferenceForTypeName(typeName) { + // Elide type references for which we have imports + if (emittedImports) { + for (var _i = 0, emittedImports_1 = emittedImports; _i < emittedImports_1.length; _i++) { + var importStatement = emittedImports_1[_i]; + if (ts.isImportEqualsDeclaration(importStatement) && ts.isExternalModuleReference(importStatement.moduleReference)) { + var expr = importStatement.moduleReference.expression; + if (ts.isStringLiteralLike(expr) && expr.text === typeName) { + return undefined; + } + } + else if (ts.isImportDeclaration(importStatement) && ts.isStringLiteral(importStatement.moduleSpecifier) && importStatement.moduleSpecifier.text === typeName) { + return undefined; + } + } + } + return { fileName: typeName, pos: -1, end: -1 }; + } + function mapReferencesIntoArray(references, outputFilePath) { + return function (file) { + var declFileName; + if (file.isDeclarationFile) { // Neither decl files or js should have their refs changed + declFileName = file.fileName; + } + else { + if (isBundledEmit && ts.contains(node.sourceFiles, file)) + return; // Omit references to files which are being merged + var paths = ts.getOutputPathsFor(file, host, /*forceDtsPaths*/ true); + declFileName = paths.declarationFilePath || paths.jsFilePath || file.fileName; + } + if (declFileName) { + var fileName = ts.getRelativePathToDirectoryOrUrl(outputFilePath, declFileName, host.getCurrentDirectory(), host.getCanonicalFileName, + /*isAbsolutePathAnUrl*/ false); + if (ts.startsWith(fileName, "./") && ts.hasExtension(fileName)) { + fileName = fileName.substring(2); + } + // omit references to files from node_modules (npm may disambiguate module + // references when installing this package, making the path is unreliable). + if (ts.startsWith(fileName, "node_modules/") || fileName.indexOf("/node_modules/") !== -1) { + return; + } + references.push({ pos: -1, end: -1, fileName: fileName }); + } + }; + } + } + function collectReferences(sourceFile, ret) { + if (noResolve || ts.isSourceFileJS(sourceFile)) + return ret; + ts.forEach(sourceFile.referencedFiles, function (f) { + var elem = ts.tryResolveScriptReference(host, sourceFile, f); + if (elem) { + ret.set("" + ts.getOriginalNodeId(elem), elem); + } + }); + return ret; + } + function collectLibs(sourceFile, ret) { + ts.forEach(sourceFile.libReferenceDirectives, function (ref) { + var lib = host.getLibFileFromReference(ref); + if (lib) { + ret.set(ref.fileName.toLocaleLowerCase(), true); + } + }); + return ret; + } + function filterBindingPatternInitializers(name) { + if (name.kind === 72 /* Identifier */) { + return name; + } + else { + if (name.kind === 185 /* ArrayBindingPattern */) { + return ts.updateArrayBindingPattern(name, ts.visitNodes(name.elements, visitBindingElement)); + } + else { + return ts.updateObjectBindingPattern(name, ts.visitNodes(name.elements, visitBindingElement)); + } + } + function visitBindingElement(elem) { + if (elem.kind === 210 /* OmittedExpression */) { + return elem; + } + return ts.updateBindingElement(elem, elem.dotDotDotToken, elem.propertyName, filterBindingPatternInitializers(elem.name), shouldPrintWithInitializer(elem) ? elem.initializer : undefined); + } + } + function ensureParameter(p, modifierMask) { + var oldDiag; + if (!suppressNewDiagnosticContexts) { + oldDiag = getSymbolAccessibilityDiagnostic; + getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(p); + } + var newParam = ts.updateParameter(p, + /*decorators*/ undefined, maskModifiers(p, modifierMask), p.dotDotDotToken, filterBindingPatternInitializers(p.name), resolver.isOptionalParameter(p) ? (p.questionToken || ts.createToken(56 /* QuestionToken */)) : undefined, ensureType(p, p.type, /*ignorePrivate*/ true), // Ignore private param props, since this type is going straight back into a param + ensureNoInitializer(p)); + if (!suppressNewDiagnosticContexts) { + getSymbolAccessibilityDiagnostic = oldDiag; + } + return newParam; + } + function shouldPrintWithInitializer(node) { + return canHaveLiteralInitializer(node) && resolver.isLiteralConstDeclaration(ts.getParseTreeNode(node)); // TODO: Make safe + } + function ensureNoInitializer(node) { + if (shouldPrintWithInitializer(node)) { + return resolver.createLiteralConstValue(ts.getParseTreeNode(node), symbolTracker); // TODO: Make safe + } + return undefined; + } + function ensureType(node, type, ignorePrivate) { + if (!ignorePrivate && ts.hasModifier(node, 8 /* Private */)) { + // Private nodes emit no types (except private parameter properties, whose parameter types are actually visible) + return; + } + if (shouldPrintWithInitializer(node)) { + // Literal const declarations will have an initializer ensured rather than a type + return; + } + var shouldUseResolverType = node.kind === 151 /* Parameter */ && + (resolver.isRequiredInitializedParameter(node) || + resolver.isOptionalUninitializedParameterProperty(node)); + if (type && !shouldUseResolverType) { + return ts.visitNode(type, visitDeclarationSubtree); + } + if (!ts.getParseTreeNode(node)) { + return type ? ts.visitNode(type, visitDeclarationSubtree) : ts.createKeywordTypeNode(120 /* AnyKeyword */); + } + if (node.kind === 159 /* SetAccessor */) { + // Set accessors with no associated type node (from it's param or get accessor return) are `any` since they are never contextually typed right now + // (The inferred type here will be void, but the old declaration emitter printed `any`, so this replicates that) + return ts.createKeywordTypeNode(120 /* AnyKeyword */); + } + errorNameNode = node.name; + var oldDiag; + if (!suppressNewDiagnosticContexts) { + oldDiag = getSymbolAccessibilityDiagnostic; + getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(node); + } + if (node.kind === 237 /* VariableDeclaration */ || node.kind === 186 /* BindingElement */) { + return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker)); + } + if (node.kind === 151 /* Parameter */ + || node.kind === 154 /* PropertyDeclaration */ + || node.kind === 153 /* PropertySignature */) { + if (!node.initializer) + return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker, shouldUseResolverType)); + return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker, shouldUseResolverType) || resolver.createTypeOfExpression(node.initializer, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker)); + } + return cleanup(resolver.createReturnTypeOfSignatureDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker)); + function cleanup(returnValue) { + errorNameNode = undefined; + if (!suppressNewDiagnosticContexts) { + getSymbolAccessibilityDiagnostic = oldDiag; + } + return returnValue || ts.createKeywordTypeNode(120 /* AnyKeyword */); + } + } + function isDeclarationAndNotVisible(node) { + node = ts.getParseTreeNode(node); + switch (node.kind) { + case 239 /* FunctionDeclaration */: + case 244 /* ModuleDeclaration */: + case 241 /* InterfaceDeclaration */: + case 240 /* ClassDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 243 /* EnumDeclaration */: + return !resolver.isDeclarationVisible(node); + // The following should be doing their own visibility checks based on filtering their members + case 237 /* VariableDeclaration */: + return !getBindingNameVisible(node); + case 248 /* ImportEqualsDeclaration */: + case 249 /* ImportDeclaration */: + case 255 /* ExportDeclaration */: + case 254 /* ExportAssignment */: + return false; + } + return false; + } + function getBindingNameVisible(elem) { + if (ts.isOmittedExpression(elem)) { + return false; + } + if (ts.isBindingPattern(elem.name)) { + // If any child binding pattern element has been marked visible (usually by collect linked aliases), then this is visible + return ts.some(elem.name.elements, getBindingNameVisible); + } + else { + return resolver.isDeclarationVisible(elem); + } + } + function updateParamsList(node, params, modifierMask) { + if (ts.hasModifier(node, 8 /* Private */)) { + return undefined; // TODO: GH#18217 + } + var newParams = ts.map(params, function (p) { return ensureParameter(p, modifierMask); }); + if (!newParams) { + return undefined; // TODO: GH#18217 + } + return ts.createNodeArray(newParams, params.hasTrailingComma); + } + function ensureTypeParams(node, params) { + return ts.hasModifier(node, 8 /* Private */) ? undefined : ts.visitNodes(params, visitDeclarationSubtree); + } + function isEnclosingDeclaration(node) { + return ts.isSourceFile(node) + || ts.isTypeAliasDeclaration(node) + || ts.isModuleDeclaration(node) + || ts.isClassDeclaration(node) + || ts.isInterfaceDeclaration(node) + || ts.isFunctionLike(node) + || ts.isIndexSignatureDeclaration(node) + || ts.isMappedTypeNode(node); + } + function checkEntityNameVisibility(entityName, enclosingDeclaration) { + var visibilityResult = resolver.isEntityNameVisible(entityName, enclosingDeclaration); + handleSymbolAccessibilityError(visibilityResult); + recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForEntityName(entityName)); + } + function preserveJsDoc(updated, original) { + if (ts.hasJSDocNodes(updated) && ts.hasJSDocNodes(original)) { + updated.jsDoc = original.jsDoc; + } + return ts.setCommentRange(updated, ts.getCommentRange(original)); + } + function rewriteModuleSpecifier(parent, input) { + if (!input) + return undefined; // TODO: GH#18217 + resultHasExternalModuleIndicator = resultHasExternalModuleIndicator || (parent.kind !== 244 /* ModuleDeclaration */ && parent.kind !== 183 /* ImportType */); + if (ts.isStringLiteralLike(input)) { + if (isBundledEmit) { + var newName = ts.getExternalModuleNameFromDeclaration(context.getEmitHost(), resolver, parent); + if (newName) { + return ts.createLiteral(newName); + } + } + else { + var symbol = resolver.getSymbolOfExternalModuleSpecifier(input); + if (symbol) { + (exportedModulesFromDeclarationEmit || (exportedModulesFromDeclarationEmit = [])).push(symbol); + } + } + } + return input; + } + function transformImportEqualsDeclaration(decl) { + if (!resolver.isDeclarationVisible(decl)) + return; + if (decl.moduleReference.kind === 259 /* ExternalModuleReference */) { + // Rewrite external module names if necessary + var specifier = ts.getExternalModuleImportEqualsDeclarationExpression(decl); + return ts.updateImportEqualsDeclaration(decl, + /*decorators*/ undefined, decl.modifiers, decl.name, ts.updateExternalModuleReference(decl.moduleReference, rewriteModuleSpecifier(decl, specifier))); + } + else { + var oldDiag = getSymbolAccessibilityDiagnostic; + getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(decl); + checkEntityNameVisibility(decl.moduleReference, enclosingDeclaration); + getSymbolAccessibilityDiagnostic = oldDiag; + return decl; + } + } + function transformImportDeclaration(decl) { + if (!decl.importClause) { + // import "mod" - possibly needed for side effects? (global interface patches, module augmentations, etc) + return ts.updateImportDeclaration(decl, + /*decorators*/ undefined, decl.modifiers, decl.importClause, rewriteModuleSpecifier(decl, decl.moduleSpecifier)); + } + // The `importClause` visibility corresponds to the default's visibility. + var visibleDefaultBinding = decl.importClause && decl.importClause.name && resolver.isDeclarationVisible(decl.importClause) ? decl.importClause.name : undefined; + if (!decl.importClause.namedBindings) { + // No named bindings (either namespace or list), meaning the import is just default or should be elided + return visibleDefaultBinding && ts.updateImportDeclaration(decl, /*decorators*/ undefined, decl.modifiers, ts.updateImportClause(decl.importClause, visibleDefaultBinding, + /*namedBindings*/ undefined), rewriteModuleSpecifier(decl, decl.moduleSpecifier)); + } + if (decl.importClause.namedBindings.kind === 251 /* NamespaceImport */) { + // Namespace import (optionally with visible default) + var namedBindings = resolver.isDeclarationVisible(decl.importClause.namedBindings) ? decl.importClause.namedBindings : /*namedBindings*/ undefined; + return visibleDefaultBinding || namedBindings ? ts.updateImportDeclaration(decl, /*decorators*/ undefined, decl.modifiers, ts.updateImportClause(decl.importClause, visibleDefaultBinding, namedBindings), rewriteModuleSpecifier(decl, decl.moduleSpecifier)) : undefined; + } + // Named imports (optionally with visible default) + var bindingList = ts.mapDefined(decl.importClause.namedBindings.elements, function (b) { return resolver.isDeclarationVisible(b) ? b : undefined; }); + if ((bindingList && bindingList.length) || visibleDefaultBinding) { + return ts.updateImportDeclaration(decl, + /*decorators*/ undefined, decl.modifiers, ts.updateImportClause(decl.importClause, visibleDefaultBinding, bindingList && bindingList.length ? ts.updateNamedImports(decl.importClause.namedBindings, bindingList) : undefined), rewriteModuleSpecifier(decl, decl.moduleSpecifier)); + } + // Nothing visible + } + function transformAndReplaceLatePaintedStatements(statements) { + // This is a `while` loop because `handleSymbolAccessibilityError` can see additional import aliases marked as visible during + // error handling which must now be included in the output and themselves checked for errors. + // For example: + // ``` + // module A { + // export module Q {} + // import B = Q; + // import C = B; + // export import D = C; + // } + // ``` + // In such a scenario, only Q and D are initially visible, but we don't consider imports as private names - instead we say they if they are referenced they must + // be recorded. So while checking D's visibility we mark C as visible, then we must check C which in turn marks B, completing the chain of + // dependent imports and allowing a valid declaration file output. Today, this dependent alias marking only happens for internal import aliases. + while (ts.length(lateMarkedStatements)) { + var i = lateMarkedStatements.shift(); + if (!ts.isLateVisibilityPaintedStatement(i)) { + return ts.Debug.fail("Late replaced statement was found which is not handled by the declaration transformer!: " + (ts.SyntaxKind ? ts.SyntaxKind[i.kind] : i.kind)); + } + var result = transformTopLevelDeclaration(i, /*privateDeclaration*/ true); + lateStatementReplacementMap.set("" + ts.getOriginalNodeId(i), result); + } + // And lastly, we need to get the final form of all those indetermine import declarations from before and add them to the output list + // (and remove them from the set to examine for outter declarations) + return ts.visitNodes(statements, visitLateVisibilityMarkedStatements); + function visitLateVisibilityMarkedStatements(statement) { + if (ts.isLateVisibilityPaintedStatement(statement)) { + var key = "" + ts.getOriginalNodeId(statement); + if (lateStatementReplacementMap.has(key)) { + var result = lateStatementReplacementMap.get(key); + lateStatementReplacementMap.delete(key); + if (result && ts.isSourceFile(statement.parent)) { + if (ts.isArray(result) ? ts.some(result, needsScopeMarker) : needsScopeMarker(result)) { + // Top-level declarations in .d.ts files are always considered exported even without a modifier unless there's an export assignment or specifier + needsScopeFixMarker = true; + } + if (ts.isArray(result) ? ts.some(result, isExternalModuleIndicator) : isExternalModuleIndicator(result)) { + resultHasExternalModuleIndicator = true; + } + } + return result; + } + } + return statement; + } + } + function isExternalModuleIndicator(result) { + // Exported top-level member indicates moduleness + return ts.isAnyImportOrReExport(result) || ts.isExportAssignment(result) || ts.hasModifier(result, 1 /* Export */); + } + function needsScopeMarker(result) { + return !ts.isAnyImportOrReExport(result) && !ts.isExportAssignment(result) && !ts.hasModifier(result, 1 /* Export */) && !ts.isAmbientModule(result); + } + function visitDeclarationSubtree(input) { + if (shouldStripInternal(input)) + return; + if (ts.isDeclaration(input)) { + if (isDeclarationAndNotVisible(input)) + return; + if (ts.hasDynamicName(input) && !resolver.isLateBound(ts.getParseTreeNode(input))) { + return; + } + } + // Elide implementation signatures from overload sets + if (ts.isFunctionLike(input) && resolver.isImplementationOfOverload(input)) + return; + // Elide semicolon class statements + if (ts.isSemicolonClassElement(input)) + return; + var previousEnclosingDeclaration; + if (isEnclosingDeclaration(input)) { + previousEnclosingDeclaration = enclosingDeclaration; + enclosingDeclaration = input; + } + var oldDiag = getSymbolAccessibilityDiagnostic; + // Emit methods which are private as properties with no type information + if (ts.isMethodDeclaration(input) || ts.isMethodSignature(input)) { + if (ts.hasModifier(input, 8 /* Private */)) { + if (input.symbol && input.symbol.declarations && input.symbol.declarations[0] !== input) + return; // Elide all but the first overload + return cleanup(ts.createProperty(/*decorators*/ undefined, ensureModifiers(input), input.name, /*questionToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined)); + } + } + var canProdiceDiagnostic = ts.canProduceDiagnostics(input); + if (canProdiceDiagnostic && !suppressNewDiagnosticContexts) { + getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(input); + } + if (ts.isTypeQueryNode(input)) { + checkEntityNameVisibility(input.exprName, enclosingDeclaration); + } + var oldWithinObjectLiteralType = suppressNewDiagnosticContexts; + var shouldEnterSuppressNewDiagnosticsContextContext = ((input.kind === 168 /* TypeLiteral */ || input.kind === 181 /* MappedType */) && input.parent.kind !== 242 /* TypeAliasDeclaration */); + if (shouldEnterSuppressNewDiagnosticsContextContext) { + // We stop making new diagnostic contexts within object literal types. Unless it's an object type on the RHS of a type alias declaration. Then we do. + suppressNewDiagnosticContexts = true; + } + if (isProcessedComponent(input)) { + switch (input.kind) { + case 211 /* ExpressionWithTypeArguments */: { + if ((ts.isEntityName(input.expression) || ts.isEntityNameExpression(input.expression))) { + checkEntityNameVisibility(input.expression, enclosingDeclaration); + } + var node = ts.visitEachChild(input, visitDeclarationSubtree, context); + return cleanup(ts.updateExpressionWithTypeArguments(node, ts.parenthesizeTypeParameters(node.typeArguments), node.expression)); + } + case 164 /* TypeReference */: { + checkEntityNameVisibility(input.typeName, enclosingDeclaration); + var node = ts.visitEachChild(input, visitDeclarationSubtree, context); + return cleanup(ts.updateTypeReferenceNode(node, node.typeName, ts.parenthesizeTypeParameters(node.typeArguments))); + } + case 161 /* ConstructSignature */: + return cleanup(ts.updateConstructSignature(input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type))); + case 157 /* Constructor */: { + var isPrivate = ts.hasModifier(input, 8 /* Private */); + // A constructor declaration may not have a type annotation + var ctor = ts.createSignatureDeclaration(157 /* Constructor */, isPrivate ? undefined : ensureTypeParams(input, input.typeParameters), + // TODO: GH#18217 + isPrivate ? undefined : updateParamsList(input, input.parameters, 0 /* None */), + /*type*/ undefined); + ctor.modifiers = ts.createNodeArray(ensureModifiers(input)); + return cleanup(ctor); + } + case 156 /* MethodDeclaration */: { + var sig = ts.createSignatureDeclaration(155 /* MethodSignature */, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type)); + sig.name = input.name; + sig.modifiers = ts.createNodeArray(ensureModifiers(input)); + sig.questionToken = input.questionToken; + return cleanup(sig); + } + case 158 /* GetAccessor */: { + var newNode = ensureAccessor(input); + return cleanup(newNode); + } + case 159 /* SetAccessor */: { + var newNode = ensureAccessor(input); + return cleanup(newNode); + } + case 154 /* PropertyDeclaration */: + return cleanup(ts.updateProperty(input, + /*decorators*/ undefined, ensureModifiers(input), input.name, input.questionToken, !ts.hasModifier(input, 8 /* Private */) ? ensureType(input, input.type) : undefined, ensureNoInitializer(input))); + case 153 /* PropertySignature */: + return cleanup(ts.updatePropertySignature(input, ensureModifiers(input), input.name, input.questionToken, !ts.hasModifier(input, 8 /* Private */) ? ensureType(input, input.type) : undefined, ensureNoInitializer(input))); + case 155 /* MethodSignature */: { + return cleanup(ts.updateMethodSignature(input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type), input.name, input.questionToken)); + } + case 160 /* CallSignature */: { + return cleanup(ts.updateCallSignature(input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type))); + } + case 162 /* IndexSignature */: { + return cleanup(ts.updateIndexSignature(input, + /*decorators*/ undefined, ensureModifiers(input), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree) || ts.createKeywordTypeNode(120 /* AnyKeyword */))); + } + case 237 /* VariableDeclaration */: { + if (ts.isBindingPattern(input.name)) { + return recreateBindingPattern(input.name); + } + shouldEnterSuppressNewDiagnosticsContextContext = true; + suppressNewDiagnosticContexts = true; // Variable declaration types also suppress new diagnostic contexts, provided the contexts wouldn't be made for binding pattern types + return cleanup(ts.updateVariableDeclaration(input, input.name, ensureType(input, input.type), ensureNoInitializer(input))); + } + case 150 /* TypeParameter */: { + if (isPrivateMethodTypeParameter(input) && (input.default || input.constraint)) { + return cleanup(ts.updateTypeParameterDeclaration(input, input.name, /*constraint*/ undefined, /*defaultType*/ undefined)); + } + return cleanup(ts.visitEachChild(input, visitDeclarationSubtree, context)); + } + case 175 /* ConditionalType */: { + // We have to process conditional types in a special way because for visibility purposes we need to push a new enclosingDeclaration + // just for the `infer` types in the true branch. It's an implicit declaration scope that only applies to _part_ of the type. + var checkType = ts.visitNode(input.checkType, visitDeclarationSubtree); + var extendsType = ts.visitNode(input.extendsType, visitDeclarationSubtree); + var oldEnclosingDecl = enclosingDeclaration; + enclosingDeclaration = input.trueType; + var trueType = ts.visitNode(input.trueType, visitDeclarationSubtree); + enclosingDeclaration = oldEnclosingDecl; + var falseType = ts.visitNode(input.falseType, visitDeclarationSubtree); + return cleanup(ts.updateConditionalTypeNode(input, checkType, extendsType, trueType, falseType)); + } + case 165 /* FunctionType */: { + return cleanup(ts.updateFunctionTypeNode(input, ts.visitNodes(input.typeParameters, visitDeclarationSubtree), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree))); + } + case 166 /* ConstructorType */: { + return cleanup(ts.updateConstructorTypeNode(input, ts.visitNodes(input.typeParameters, visitDeclarationSubtree), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree))); + } + case 183 /* ImportType */: { + if (!ts.isLiteralImportTypeNode(input)) + return cleanup(input); + return cleanup(ts.updateImportTypeNode(input, ts.updateLiteralTypeNode(input.argument, rewriteModuleSpecifier(input, input.argument.literal)), input.qualifier, ts.visitNodes(input.typeArguments, visitDeclarationSubtree, ts.isTypeNode), input.isTypeOf)); + } + default: ts.Debug.assertNever(input, "Attempted to process unhandled node kind: " + ts.SyntaxKind[input.kind]); + } + } + return cleanup(ts.visitEachChild(input, visitDeclarationSubtree, context)); + function cleanup(returnValue) { + if (returnValue && canProdiceDiagnostic && ts.hasDynamicName(input)) { + checkName(input); + } + if (isEnclosingDeclaration(input)) { + enclosingDeclaration = previousEnclosingDeclaration; + } + if (canProdiceDiagnostic && !suppressNewDiagnosticContexts) { + getSymbolAccessibilityDiagnostic = oldDiag; + } + if (shouldEnterSuppressNewDiagnosticsContextContext) { + suppressNewDiagnosticContexts = oldWithinObjectLiteralType; + } + if (returnValue === input) { + return returnValue; + } + return returnValue && ts.setOriginalNode(preserveJsDoc(returnValue, input), input); + } + } + function isPrivateMethodTypeParameter(node) { + return node.parent.kind === 156 /* MethodDeclaration */ && ts.hasModifier(node.parent, 8 /* Private */); + } + function visitDeclarationStatements(input) { + if (!isPreservedDeclarationStatement(input)) { + // return undefined for unmatched kinds to omit them from the tree + return; + } + if (shouldStripInternal(input)) + return; + switch (input.kind) { + case 255 /* ExportDeclaration */: { + if (ts.isSourceFile(input.parent)) { + resultHasExternalModuleIndicator = true; + resultHasScopeMarker = true; + } + // Always visible if the parent node isn't dropped for being not visible + // Rewrite external module names if necessary + return ts.updateExportDeclaration(input, /*decorators*/ undefined, input.modifiers, input.exportClause, rewriteModuleSpecifier(input, input.moduleSpecifier)); + } + case 254 /* ExportAssignment */: { + // Always visible if the parent node isn't dropped for being not visible + if (ts.isSourceFile(input.parent)) { + resultHasExternalModuleIndicator = true; + resultHasScopeMarker = true; + } + if (input.expression.kind === 72 /* Identifier */) { + return input; + } + else { + var newId = ts.createOptimisticUniqueName("_default"); + getSymbolAccessibilityDiagnostic = function () { return ({ + diagnosticMessage: ts.Diagnostics.Default_export_of_the_module_has_or_is_using_private_name_0, + errorNode: input + }); }; + var varDecl = ts.createVariableDeclaration(newId, resolver.createTypeOfExpression(input.expression, input, declarationEmitNodeBuilderFlags, symbolTracker), /*initializer*/ undefined); + var statement = ts.createVariableStatement(needsDeclare ? [ts.createModifier(125 /* DeclareKeyword */)] : [], ts.createVariableDeclarationList([varDecl], 2 /* Const */)); + return [statement, ts.updateExportAssignment(input, input.decorators, input.modifiers, newId)]; + } + } + } + var result = transformTopLevelDeclaration(input); + // Don't actually transform yet; just leave as original node - will be elided/swapped by late pass + lateStatementReplacementMap.set("" + ts.getOriginalNodeId(input), result); + return input; + } + function transformTopLevelDeclaration(input, isPrivate) { + if (shouldStripInternal(input)) + return; + switch (input.kind) { + case 248 /* ImportEqualsDeclaration */: { + return transformImportEqualsDeclaration(input); + } + case 249 /* ImportDeclaration */: { + return transformImportDeclaration(input); + } + } + if (ts.isDeclaration(input) && isDeclarationAndNotVisible(input)) + return; + // Elide implementation signatures from overload sets + if (ts.isFunctionLike(input) && resolver.isImplementationOfOverload(input)) + return; + var previousEnclosingDeclaration; + if (isEnclosingDeclaration(input)) { + previousEnclosingDeclaration = enclosingDeclaration; + enclosingDeclaration = input; + } + var canProdiceDiagnostic = ts.canProduceDiagnostics(input); + var oldDiag = getSymbolAccessibilityDiagnostic; + if (canProdiceDiagnostic) { + getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(input); + } + var previousNeedsDeclare = needsDeclare; + switch (input.kind) { + case 242 /* TypeAliasDeclaration */: // Type aliases get `declare`d if need be (for legacy support), but that's all + return cleanup(ts.updateTypeAliasDeclaration(input, + /*decorators*/ undefined, ensureModifiers(input, isPrivate), input.name, ts.visitNodes(input.typeParameters, visitDeclarationSubtree, ts.isTypeParameterDeclaration), ts.visitNode(input.type, visitDeclarationSubtree, ts.isTypeNode))); + case 241 /* InterfaceDeclaration */: { + return cleanup(ts.updateInterfaceDeclaration(input, + /*decorators*/ undefined, ensureModifiers(input, isPrivate), input.name, ensureTypeParams(input, input.typeParameters), transformHeritageClauses(input.heritageClauses), ts.visitNodes(input.members, visitDeclarationSubtree))); + } + case 239 /* FunctionDeclaration */: { + // Generators lose their generator-ness, excepting their return type + var clean = cleanup(ts.updateFunctionDeclaration(input, + /*decorators*/ undefined, ensureModifiers(input, isPrivate), + /*asteriskToken*/ undefined, input.name, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type), + /*body*/ undefined)); + if (clean && resolver.isExpandoFunctionDeclaration(input)) { + var declarations = ts.mapDefined(resolver.getPropertiesOfContainerFunction(input), function (p) { + if (!ts.isPropertyAccessExpression(p.valueDeclaration)) { + return undefined; + } + var type = resolver.createTypeOfDeclaration(p.valueDeclaration, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker); + var varDecl = ts.createVariableDeclaration(ts.unescapeLeadingUnderscores(p.escapedName), type, /*initializer*/ undefined); + return ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([varDecl])); + }); + var namespaceDecl = ts.createModuleDeclaration(/*decorators*/ undefined, ensureModifiers(input, isPrivate), input.name, ts.createModuleBlock(declarations), 16 /* Namespace */); + return [clean, namespaceDecl]; + } + else { + return clean; + } + } + case 244 /* ModuleDeclaration */: { + needsDeclare = false; + var inner = input.body; + if (inner && inner.kind === 245 /* ModuleBlock */) { + var statements = ts.visitNodes(inner.statements, visitDeclarationStatements); + var body = ts.updateModuleBlock(inner, transformAndReplaceLatePaintedStatements(statements)); + needsDeclare = previousNeedsDeclare; + var mods = ensureModifiers(input, isPrivate); + return cleanup(ts.updateModuleDeclaration(input, + /*decorators*/ undefined, mods, ts.isExternalModuleAugmentation(input) ? rewriteModuleSpecifier(input, input.name) : input.name, body)); + } + else { + needsDeclare = previousNeedsDeclare; + var mods = ensureModifiers(input, isPrivate); + needsDeclare = false; + ts.visitNode(inner, visitDeclarationStatements); + // eagerly transform nested namespaces (the nesting doesn't need any elision or painting done) + var id = "" + ts.getOriginalNodeId(inner); // TODO: GH#18217 + var body = lateStatementReplacementMap.get(id); + lateStatementReplacementMap.delete(id); + return cleanup(ts.updateModuleDeclaration(input, + /*decorators*/ undefined, mods, input.name, body)); + } + } + case 240 /* ClassDeclaration */: { + var modifiers = ts.createNodeArray(ensureModifiers(input, isPrivate)); + var typeParameters = ensureTypeParams(input, input.typeParameters); + var ctor = ts.getFirstConstructorWithBody(input); + var parameterProperties = void 0; + if (ctor) { + var oldDiag_1 = getSymbolAccessibilityDiagnostic; + parameterProperties = ts.compact(ts.flatMap(ctor.parameters, function (param) { + if (!ts.hasModifier(param, 92 /* ParameterPropertyModifier */)) + return; + getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(param); + if (param.name.kind === 72 /* Identifier */) { + return preserveJsDoc(ts.createProperty( + /*decorators*/ undefined, ensureModifiers(param), param.name, param.questionToken, ensureType(param, param.type), ensureNoInitializer(param)), param); + } + else { + // Pattern - this is currently an error, but we emit declarations for it somewhat correctly + return walkBindingPattern(param.name); + } + function walkBindingPattern(pattern) { + var elems; + for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) { + var elem = _a[_i]; + if (ts.isOmittedExpression(elem)) + continue; + if (ts.isBindingPattern(elem.name)) { + elems = ts.concatenate(elems, walkBindingPattern(elem.name)); + } + elems = elems || []; + elems.push(ts.createProperty( + /*decorators*/ undefined, ensureModifiers(param), elem.name, + /*questionToken*/ undefined, ensureType(elem, /*type*/ undefined), + /*initializer*/ undefined)); + } + return elems; + } + })); + getSymbolAccessibilityDiagnostic = oldDiag_1; + } + var members = ts.createNodeArray(ts.concatenate(parameterProperties, ts.visitNodes(input.members, visitDeclarationSubtree))); + var extendsClause_1 = ts.getEffectiveBaseTypeNode(input); + if (extendsClause_1 && !ts.isEntityNameExpression(extendsClause_1.expression) && extendsClause_1.expression.kind !== 96 /* NullKeyword */) { + // We must add a temporary declaration for the extends clause expression + var newId_1 = ts.createOptimisticUniqueName(ts.unescapeLeadingUnderscores(input.name.escapedText) + "_base"); // TODO: GH#18217 + getSymbolAccessibilityDiagnostic = function () { return ({ + diagnosticMessage: ts.Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1, + errorNode: extendsClause_1, + typeName: input.name + }); }; + var varDecl = ts.createVariableDeclaration(newId_1, resolver.createTypeOfExpression(extendsClause_1.expression, input, declarationEmitNodeBuilderFlags, symbolTracker), /*initializer*/ undefined); + var statement = ts.createVariableStatement(needsDeclare ? [ts.createModifier(125 /* DeclareKeyword */)] : [], ts.createVariableDeclarationList([varDecl], 2 /* Const */)); + var heritageClauses = ts.createNodeArray(ts.map(input.heritageClauses, function (clause) { + if (clause.token === 86 /* ExtendsKeyword */) { + var oldDiag_2 = getSymbolAccessibilityDiagnostic; + getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(clause.types[0]); + var newClause = ts.updateHeritageClause(clause, ts.map(clause.types, function (t) { return ts.updateExpressionWithTypeArguments(t, ts.visitNodes(t.typeArguments, visitDeclarationSubtree), newId_1); })); + getSymbolAccessibilityDiagnostic = oldDiag_2; + return newClause; + } + return ts.updateHeritageClause(clause, ts.visitNodes(ts.createNodeArray(ts.filter(clause.types, function (t) { return ts.isEntityNameExpression(t.expression) || t.expression.kind === 96 /* NullKeyword */; })), visitDeclarationSubtree)); + })); + return [statement, cleanup(ts.updateClassDeclaration(input, + /*decorators*/ undefined, modifiers, input.name, typeParameters, heritageClauses, members))]; // TODO: GH#18217 + } + else { + var heritageClauses = transformHeritageClauses(input.heritageClauses); + return cleanup(ts.updateClassDeclaration(input, + /*decorators*/ undefined, modifiers, input.name, typeParameters, heritageClauses, members)); + } + } + case 219 /* VariableStatement */: { + return cleanup(transformVariableStatement(input, isPrivate)); + } + case 243 /* EnumDeclaration */: { + return cleanup(ts.updateEnumDeclaration(input, /*decorators*/ undefined, ts.createNodeArray(ensureModifiers(input, isPrivate)), input.name, ts.createNodeArray(ts.mapDefined(input.members, function (m) { + if (shouldStripInternal(m)) + return; + // Rewrite enum values to their constants, if available + var constValue = resolver.getConstantValue(m); + return preserveJsDoc(ts.updateEnumMember(m, m.name, constValue !== undefined ? ts.createLiteral(constValue) : undefined), m); + })))); + } + } + // Anything left unhandled is an error, so this should be unreachable + return ts.Debug.assertNever(input, "Unhandled top-level node in declaration emit: " + ts.SyntaxKind[input.kind]); + function cleanup(node) { + if (isEnclosingDeclaration(input)) { + enclosingDeclaration = previousEnclosingDeclaration; + } + if (canProdiceDiagnostic) { + getSymbolAccessibilityDiagnostic = oldDiag; + } + if (input.kind === 244 /* ModuleDeclaration */) { + needsDeclare = previousNeedsDeclare; + } + if (node === input) { + return node; + } + return node && ts.setOriginalNode(preserveJsDoc(node, input), input); + } + } + function transformVariableStatement(input, privateDeclaration) { + if (!ts.forEach(input.declarationList.declarations, getBindingNameVisible)) + return; + var nodes = ts.visitNodes(input.declarationList.declarations, visitDeclarationSubtree); + if (!ts.length(nodes)) + return; + return ts.updateVariableStatement(input, ts.createNodeArray(ensureModifiers(input, privateDeclaration)), ts.updateVariableDeclarationList(input.declarationList, nodes)); + } + function recreateBindingPattern(d) { + return ts.flatten(ts.mapDefined(d.elements, function (e) { return recreateBindingElement(e); })); + } + function recreateBindingElement(e) { + if (e.kind === 210 /* OmittedExpression */) { + return; + } + if (e.name) { + if (!getBindingNameVisible(e)) + return; + if (ts.isBindingPattern(e.name)) { + return recreateBindingPattern(e.name); + } + else { + return ts.createVariableDeclaration(e.name, ensureType(e, /*type*/ undefined), /*initializer*/ undefined); + } + } + } + function checkName(node) { + var oldDiag; + if (!suppressNewDiagnosticContexts) { + oldDiag = getSymbolAccessibilityDiagnostic; + getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNodeName(node); + } + errorNameNode = node.name; + ts.Debug.assert(resolver.isLateBound(ts.getParseTreeNode(node))); // Should only be called with dynamic names + var decl = node; + var entityName = decl.name.expression; + checkEntityNameVisibility(entityName, enclosingDeclaration); + if (!suppressNewDiagnosticContexts) { + getSymbolAccessibilityDiagnostic = oldDiag; + } + errorNameNode = undefined; + } + function hasInternalAnnotation(range) { + var comment = currentSourceFile.text.substring(range.pos, range.end); + return ts.stringContains(comment, "@internal"); + } + function shouldStripInternal(node) { + if (stripInternal && node) { + var leadingCommentRanges = ts.getLeadingCommentRangesOfNode(ts.getParseTreeNode(node), currentSourceFile); + if (ts.forEach(leadingCommentRanges, hasInternalAnnotation)) { + return true; + } + } + return false; + } + function isScopeMarker(node) { + return ts.isExportAssignment(node) || ts.isExportDeclaration(node); + } + function hasScopeMarker(node) { + if (ts.isModuleBlock(node)) { + return ts.some(node.statements, isScopeMarker); + } + return false; + } + function ensureModifiers(node, privateDeclaration) { + var currentFlags = ts.getModifierFlags(node); + var newFlags = ensureModifierFlags(node, privateDeclaration); + if (currentFlags === newFlags) { + return node.modifiers; + } + return ts.createModifiersFromModifierFlags(newFlags); + } + function ensureModifierFlags(node, privateDeclaration) { + var mask = 3071 /* All */ ^ (4 /* Public */ | 256 /* Async */); // No async modifiers in declaration files + var additions = (needsDeclare && !isAlwaysType(node)) ? 2 /* Ambient */ : 0 /* None */; + var parentIsFile = node.parent.kind === 279 /* SourceFile */; + if (!parentIsFile || (isBundledEmit && parentIsFile && ts.isExternalModule(node.parent))) { + mask ^= ((privateDeclaration || (isBundledEmit && parentIsFile) || hasScopeMarker(node.parent) ? 0 : 1 /* Export */) | 2 /* Ambient */); + additions = 0 /* None */; + } + return maskModifierFlags(node, mask, additions); + } + function ensureAccessor(node) { + var accessors = resolver.getAllAccessorDeclarations(node); + if (node.kind !== accessors.firstAccessor.kind) { + return; + } + var accessorType = getTypeAnnotationFromAccessor(node); + if (!accessorType && accessors.secondAccessor) { + accessorType = getTypeAnnotationFromAccessor(accessors.secondAccessor); + // If we end up pulling the type from the second accessor, we also need to change the diagnostic context to get the expected error message + getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(accessors.secondAccessor); + } + var prop = ts.createProperty(/*decorators*/ undefined, maskModifiers(node, /*mask*/ undefined, (!accessors.setAccessor) ? 64 /* Readonly */ : 0 /* None */), node.name, node.questionToken, ensureType(node, accessorType), /*initializer*/ undefined); + var leadingsSyntheticCommentRanges = accessors.secondAccessor && ts.getLeadingCommentRangesOfNode(accessors.secondAccessor, currentSourceFile); + if (leadingsSyntheticCommentRanges) { + var _loop_9 = function (range) { + if (range.kind === 3 /* MultiLineCommentTrivia */) { + var text = currentSourceFile.text.slice(range.pos + 2, range.end - 2); + var lines = text.split(/\r\n?|\n/g); + if (lines.length > 1) { + var lastLines = lines.slice(1); + var indentation_1 = ts.guessIndentation(lastLines); + text = [lines[0]].concat(ts.map(lastLines, function (l) { return l.slice(indentation_1); })).join(newLine); + } + ts.addSyntheticLeadingComment(prop, range.kind, text, range.hasTrailingNewLine); + } + }; + for (var _i = 0, leadingsSyntheticCommentRanges_1 = leadingsSyntheticCommentRanges; _i < leadingsSyntheticCommentRanges_1.length; _i++) { + var range = leadingsSyntheticCommentRanges_1[_i]; + _loop_9(range); + } + } + return prop; + } + function transformHeritageClauses(nodes) { + return ts.createNodeArray(ts.filter(ts.map(nodes, function (clause) { return ts.updateHeritageClause(clause, ts.visitNodes(ts.createNodeArray(ts.filter(clause.types, function (t) { + return ts.isEntityNameExpression(t.expression) || (clause.token === 86 /* ExtendsKeyword */ && t.expression.kind === 96 /* NullKeyword */); + })), visitDeclarationSubtree)); }), function (clause) { return clause.types && !!clause.types.length; })); + } + } + ts.transformDeclarations = transformDeclarations; + function isAlwaysType(node) { + if (node.kind === 241 /* InterfaceDeclaration */) { + return true; + } + return false; + } + // Elide "public" modifier, as it is the default + function maskModifiers(node, modifierMask, modifierAdditions) { + return ts.createModifiersFromModifierFlags(maskModifierFlags(node, modifierMask, modifierAdditions)); + } + function maskModifierFlags(node, modifierMask, modifierAdditions) { + if (modifierMask === void 0) { modifierMask = 3071 /* All */ ^ 4 /* Public */; } + if (modifierAdditions === void 0) { modifierAdditions = 0 /* None */; } + var flags = (ts.getModifierFlags(node) & modifierMask) | modifierAdditions; + if (flags & 512 /* Default */ && !(flags & 1 /* Export */)) { + // A non-exported default is a nonsequitor - we usually try to remove all export modifiers + // from statements in ambient declarations; but a default export must retain its export modifier to be syntactically valid + flags ^= 1 /* Export */; + } + if (flags & 512 /* Default */ && flags & 2 /* Ambient */) { + flags ^= 2 /* Ambient */; // `declare` is never required alongside `default` (and would be an error if printed) + } + return flags; + } + function getTypeAnnotationFromAccessor(accessor) { + if (accessor) { + return accessor.kind === 158 /* GetAccessor */ + ? accessor.type // Getter - return type + : accessor.parameters.length > 0 + ? accessor.parameters[0].type // Setter parameter type + : undefined; + } + } + function canHaveLiteralInitializer(node) { + switch (node.kind) { + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + return !ts.hasModifier(node, 8 /* Private */); + case 151 /* Parameter */: + case 237 /* VariableDeclaration */: + return true; + } + return false; + } + function isPreservedDeclarationStatement(node) { + switch (node.kind) { + case 239 /* FunctionDeclaration */: + case 244 /* ModuleDeclaration */: + case 248 /* ImportEqualsDeclaration */: + case 241 /* InterfaceDeclaration */: + case 240 /* ClassDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 243 /* EnumDeclaration */: + case 219 /* VariableStatement */: + case 249 /* ImportDeclaration */: + case 255 /* ExportDeclaration */: + case 254 /* ExportAssignment */: + return true; + } + return false; + } + function isProcessedComponent(node) { + switch (node.kind) { + case 161 /* ConstructSignature */: + case 157 /* Constructor */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 155 /* MethodSignature */: + case 160 /* CallSignature */: + case 162 /* IndexSignature */: + case 237 /* VariableDeclaration */: + case 150 /* TypeParameter */: + case 211 /* ExpressionWithTypeArguments */: + case 164 /* TypeReference */: + case 175 /* ConditionalType */: + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + case 183 /* ImportType */: + return true; + } + return false; + } +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + function getModuleTransformer(moduleKind) { + switch (moduleKind) { + case ts.ModuleKind.ESNext: + case ts.ModuleKind.ES2015: + return ts.transformES2015Module; + case ts.ModuleKind.System: + return ts.transformSystemModule; + default: + return ts.transformModule; + } + } + var TransformationState; + (function (TransformationState) { + TransformationState[TransformationState["Uninitialized"] = 0] = "Uninitialized"; + TransformationState[TransformationState["Initialized"] = 1] = "Initialized"; + TransformationState[TransformationState["Completed"] = 2] = "Completed"; + TransformationState[TransformationState["Disposed"] = 3] = "Disposed"; + })(TransformationState || (TransformationState = {})); + var SyntaxKindFeatureFlags; + (function (SyntaxKindFeatureFlags) { + SyntaxKindFeatureFlags[SyntaxKindFeatureFlags["Substitution"] = 1] = "Substitution"; + SyntaxKindFeatureFlags[SyntaxKindFeatureFlags["EmitNotifications"] = 2] = "EmitNotifications"; + })(SyntaxKindFeatureFlags || (SyntaxKindFeatureFlags = {})); + function getTransformers(compilerOptions, customTransformers) { + var jsx = compilerOptions.jsx; + var languageVersion = ts.getEmitScriptTarget(compilerOptions); + var moduleKind = ts.getEmitModuleKind(compilerOptions); + var transformers = []; + ts.addRange(transformers, customTransformers && customTransformers.before); + transformers.push(ts.transformTypeScript); + if (jsx === 2 /* React */) { + transformers.push(ts.transformJsx); + } + if (languageVersion < 6 /* ESNext */) { + transformers.push(ts.transformESNext); + } + if (languageVersion < 4 /* ES2017 */) { + transformers.push(ts.transformES2017); + } + if (languageVersion < 3 /* ES2016 */) { + transformers.push(ts.transformES2016); + } + if (languageVersion < 2 /* ES2015 */) { + transformers.push(ts.transformES2015); + transformers.push(ts.transformGenerators); + } + transformers.push(getModuleTransformer(moduleKind)); + // The ES5 transformer is last so that it can substitute expressions like `exports.default` + // for ES3. + if (languageVersion < 1 /* ES5 */) { + transformers.push(ts.transformES5); + } + ts.addRange(transformers, customTransformers && customTransformers.after); + return transformers; + } + ts.getTransformers = getTransformers; + function noEmitSubstitution(_hint, node) { + return node; + } + ts.noEmitSubstitution = noEmitSubstitution; + function noEmitNotification(hint, node, callback) { + callback(hint, node); + } + ts.noEmitNotification = noEmitNotification; + /** + * Transforms an array of SourceFiles by passing them through each transformer. + * + * @param resolver The emit resolver provided by the checker. + * @param host The emit host object used to interact with the file system. + * @param options Compiler options to surface in the `TransformationContext`. + * @param nodes An array of nodes to transform. + * @param transforms An array of `TransformerFactory` callbacks. + * @param allowDtsFiles A value indicating whether to allow the transformation of .d.ts files. + */ + function transformNodes(resolver, host, options, nodes, transformers, allowDtsFiles) { + var enabledSyntaxKindFeatures = new Array(312 /* Count */); + var lexicalEnvironmentVariableDeclarations; + var lexicalEnvironmentFunctionDeclarations; + var lexicalEnvironmentVariableDeclarationsStack = []; + var lexicalEnvironmentFunctionDeclarationsStack = []; + var lexicalEnvironmentStackOffset = 0; + var lexicalEnvironmentSuspended = false; + var emitHelpers; + var onSubstituteNode = noEmitSubstitution; + var onEmitNode = noEmitNotification; + var state = 0 /* Uninitialized */; + var diagnostics = []; + // The transformation context is provided to each transformer as part of transformer + // initialization. + var context = { + getCompilerOptions: function () { return options; }, + getEmitResolver: function () { return resolver; }, + getEmitHost: function () { return host; }, + startLexicalEnvironment: startLexicalEnvironment, + suspendLexicalEnvironment: suspendLexicalEnvironment, + resumeLexicalEnvironment: resumeLexicalEnvironment, + endLexicalEnvironment: endLexicalEnvironment, + hoistVariableDeclaration: hoistVariableDeclaration, + hoistFunctionDeclaration: hoistFunctionDeclaration, + requestEmitHelper: requestEmitHelper, + readEmitHelpers: readEmitHelpers, + enableSubstitution: enableSubstitution, + enableEmitNotification: enableEmitNotification, + isSubstitutionEnabled: isSubstitutionEnabled, + isEmitNotificationEnabled: isEmitNotificationEnabled, + get onSubstituteNode() { return onSubstituteNode; }, + set onSubstituteNode(value) { + ts.Debug.assert(state < 1 /* Initialized */, "Cannot modify transformation hooks after initialization has completed."); + ts.Debug.assert(value !== undefined, "Value must not be 'undefined'"); + onSubstituteNode = value; + }, + get onEmitNode() { return onEmitNode; }, + set onEmitNode(value) { + ts.Debug.assert(state < 1 /* Initialized */, "Cannot modify transformation hooks after initialization has completed."); + ts.Debug.assert(value !== undefined, "Value must not be 'undefined'"); + onEmitNode = value; + }, + addDiagnostic: function (diag) { + diagnostics.push(diag); + } + }; + // Ensure the parse tree is clean before applying transformations + for (var _i = 0, nodes_4 = nodes; _i < nodes_4.length; _i++) { + var node = nodes_4[_i]; + ts.disposeEmitNodes(ts.getSourceFileOfNode(ts.getParseTreeNode(node))); + } + ts.performance.mark("beforeTransform"); + // Chain together and initialize each transformer. + var transformation = ts.chain.apply(void 0, transformers)(context); + // prevent modification of transformation hooks. + state = 1 /* Initialized */; + // Transform each node. + var transformed = ts.map(nodes, allowDtsFiles ? transformation : transformRoot); + // prevent modification of the lexical environment. + state = 2 /* Completed */; + ts.performance.mark("afterTransform"); + ts.performance.measure("transformTime", "beforeTransform", "afterTransform"); + return { + transformed: transformed, + substituteNode: substituteNode, + emitNodeWithNotification: emitNodeWithNotification, + dispose: dispose, + diagnostics: diagnostics + }; + function transformRoot(node) { + return node && (!ts.isSourceFile(node) || !node.isDeclarationFile) ? transformation(node) : node; + } + /** + * Enables expression substitutions in the pretty printer for the provided SyntaxKind. + */ + function enableSubstitution(kind) { + ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the transformation context after transformation has completed."); + enabledSyntaxKindFeatures[kind] |= 1 /* Substitution */; + } + /** + * Determines whether expression substitutions are enabled for the provided node. + */ + function isSubstitutionEnabled(node) { + return (enabledSyntaxKindFeatures[node.kind] & 1 /* Substitution */) !== 0 + && (ts.getEmitFlags(node) & 4 /* NoSubstitution */) === 0; + } + /** + * Emits a node with possible substitution. + * + * @param hint A hint as to the intended usage of the node. + * @param node The node to emit. + * @param emitCallback The callback used to emit the node or its substitute. + */ + function substituteNode(hint, node) { + ts.Debug.assert(state < 3 /* Disposed */, "Cannot substitute a node after the result is disposed."); + return node && isSubstitutionEnabled(node) && onSubstituteNode(hint, node) || node; + } + /** + * Enables before/after emit notifications in the pretty printer for the provided SyntaxKind. + */ + function enableEmitNotification(kind) { + ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the transformation context after transformation has completed."); + enabledSyntaxKindFeatures[kind] |= 2 /* EmitNotifications */; + } + /** + * Determines whether before/after emit notifications should be raised in the pretty + * printer when it emits a node. + */ + function isEmitNotificationEnabled(node) { + return (enabledSyntaxKindFeatures[node.kind] & 2 /* EmitNotifications */) !== 0 + || (ts.getEmitFlags(node) & 2 /* AdviseOnEmitNode */) !== 0; + } + /** + * Emits a node with possible emit notification. + * + * @param hint A hint as to the intended usage of the node. + * @param node The node to emit. + * @param emitCallback The callback used to emit the node. + */ + function emitNodeWithNotification(hint, node, emitCallback) { + ts.Debug.assert(state < 3 /* Disposed */, "Cannot invoke TransformationResult callbacks after the result is disposed."); + if (node) { + if (isEmitNotificationEnabled(node)) { + onEmitNode(hint, node, emitCallback); + } + else { + emitCallback(hint, node); + } + } + } + /** + * Records a hoisted variable declaration for the provided name within a lexical environment. + */ + function hoistVariableDeclaration(name) { + ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization."); + ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed."); + var decl = ts.setEmitFlags(ts.createVariableDeclaration(name), 64 /* NoNestedSourceMaps */); + if (!lexicalEnvironmentVariableDeclarations) { + lexicalEnvironmentVariableDeclarations = [decl]; + } + else { + lexicalEnvironmentVariableDeclarations.push(decl); + } + } + /** + * Records a hoisted function declaration within a lexical environment. + */ + function hoistFunctionDeclaration(func) { + ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization."); + ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed."); + if (!lexicalEnvironmentFunctionDeclarations) { + lexicalEnvironmentFunctionDeclarations = [func]; + } + else { + lexicalEnvironmentFunctionDeclarations.push(func); + } + } + /** + * Starts a new lexical environment. Any existing hoisted variable or function declarations + * are pushed onto a stack, and the related storage variables are reset. + */ + function startLexicalEnvironment() { + ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization."); + ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed."); + ts.Debug.assert(!lexicalEnvironmentSuspended, "Lexical environment is suspended."); + // Save the current lexical environment. Rather than resizing the array we adjust the + // stack size variable. This allows us to reuse existing array slots we've + // already allocated between transformations to avoid allocation and GC overhead during + // transformation. + lexicalEnvironmentVariableDeclarationsStack[lexicalEnvironmentStackOffset] = lexicalEnvironmentVariableDeclarations; + lexicalEnvironmentFunctionDeclarationsStack[lexicalEnvironmentStackOffset] = lexicalEnvironmentFunctionDeclarations; + lexicalEnvironmentStackOffset++; + lexicalEnvironmentVariableDeclarations = undefined; + lexicalEnvironmentFunctionDeclarations = undefined; + } + /** Suspends the current lexical environment, usually after visiting a parameter list. */ + function suspendLexicalEnvironment() { + ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization."); + ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed."); + ts.Debug.assert(!lexicalEnvironmentSuspended, "Lexical environment is already suspended."); + lexicalEnvironmentSuspended = true; + } + /** Resumes a suspended lexical environment, usually before visiting a function body. */ + function resumeLexicalEnvironment() { + ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization."); + ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed."); + ts.Debug.assert(lexicalEnvironmentSuspended, "Lexical environment is not suspended."); + lexicalEnvironmentSuspended = false; + } + /** + * Ends a lexical environment. The previous set of hoisted declarations are restored and + * any hoisted declarations added in this environment are returned. + */ + function endLexicalEnvironment() { + ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization."); + ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed."); + ts.Debug.assert(!lexicalEnvironmentSuspended, "Lexical environment is suspended."); + var statements; + if (lexicalEnvironmentVariableDeclarations || lexicalEnvironmentFunctionDeclarations) { + if (lexicalEnvironmentFunctionDeclarations) { + statements = lexicalEnvironmentFunctionDeclarations.slice(); + } + if (lexicalEnvironmentVariableDeclarations) { + var statement = ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList(lexicalEnvironmentVariableDeclarations)); + if (!statements) { + statements = [statement]; + } + else { + statements.push(statement); + } + } + } + // Restore the previous lexical environment. + lexicalEnvironmentStackOffset--; + lexicalEnvironmentVariableDeclarations = lexicalEnvironmentVariableDeclarationsStack[lexicalEnvironmentStackOffset]; + lexicalEnvironmentFunctionDeclarations = lexicalEnvironmentFunctionDeclarationsStack[lexicalEnvironmentStackOffset]; + if (lexicalEnvironmentStackOffset === 0) { + lexicalEnvironmentVariableDeclarationsStack = []; + lexicalEnvironmentFunctionDeclarationsStack = []; + } + return statements; + } + function requestEmitHelper(helper) { + ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the transformation context during initialization."); + ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the transformation context after transformation has completed."); + ts.Debug.assert(!helper.scoped, "Cannot request a scoped emit helper."); + emitHelpers = ts.append(emitHelpers, helper); + } + function readEmitHelpers() { + ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the transformation context during initialization."); + ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the transformation context after transformation has completed."); + var helpers = emitHelpers; + emitHelpers = undefined; + return helpers; + } + function dispose() { + if (state < 3 /* Disposed */) { + // Clean up emit nodes on parse tree + for (var _i = 0, nodes_5 = nodes; _i < nodes_5.length; _i++) { + var node = nodes_5[_i]; + ts.disposeEmitNodes(ts.getSourceFileOfNode(ts.getParseTreeNode(node))); + } + // Release references to external entries for GC purposes. + lexicalEnvironmentVariableDeclarations = undefined; + lexicalEnvironmentVariableDeclarationsStack = undefined; + lexicalEnvironmentFunctionDeclarations = undefined; + lexicalEnvironmentFunctionDeclarationsStack = undefined; + onSubstituteNode = undefined; + onEmitNode = undefined; + emitHelpers = undefined; + // Prevent further use of the transformation result. + state = 3 /* Disposed */; + } + } + } + ts.transformNodes = transformNodes; +})(ts || (ts = {})); +var ts; +(function (ts) { + var infoExtension = ".tsbundleinfo"; + var brackets = createBracketsMap(); + var syntheticParent = { pos: -1, end: -1 }; + /*@internal*/ + /** + * Iterates over the source files that are expected to have an emit output. + * + * @param host An EmitHost. + * @param action The action to execute. + * @param sourceFilesOrTargetSourceFile + * If an array, the full list of source files to emit. + * Else, calls `getSourceFilesToEmit` with the (optional) target source file to determine the list of source files to emit. + */ + function forEachEmittedFile(host, action, sourceFilesOrTargetSourceFile, emitOnlyDtsFiles) { + if (emitOnlyDtsFiles === void 0) { emitOnlyDtsFiles = false; } + var sourceFiles = ts.isArray(sourceFilesOrTargetSourceFile) ? sourceFilesOrTargetSourceFile : ts.getSourceFilesToEmit(host, sourceFilesOrTargetSourceFile); + var options = host.getCompilerOptions(); + if (options.outFile || options.out) { + if (sourceFiles.length) { + var bundle = ts.createBundle(sourceFiles, host.getPrependNodes()); + var result = action(getOutputPathsFor(bundle, host, emitOnlyDtsFiles), bundle); + if (result) { + return result; + } + } + } + else { + for (var _a = 0, sourceFiles_1 = sourceFiles; _a < sourceFiles_1.length; _a++) { + var sourceFile = sourceFiles_1[_a]; + var result = action(getOutputPathsFor(sourceFile, host, emitOnlyDtsFiles), sourceFile); + if (result) { + return result; + } + } + } + } + ts.forEachEmittedFile = forEachEmittedFile; + /*@internal*/ + function getOutputPathsFor(sourceFile, host, forceDtsPaths) { + var options = host.getCompilerOptions(); + if (sourceFile.kind === 280 /* Bundle */) { + var outPath = options.outFile || options.out; + var jsFilePath = options.emitDeclarationOnly ? undefined : outPath; + var sourceMapFilePath = jsFilePath && getSourceMapFilePath(jsFilePath, options); + var declarationFilePath = (forceDtsPaths || ts.getEmitDeclarations(options)) ? ts.removeFileExtension(outPath) + ".d.ts" /* Dts */ : undefined; + var declarationMapPath = declarationFilePath && ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; + var bundleInfoPath = options.references && jsFilePath ? (ts.removeFileExtension(jsFilePath) + infoExtension) : undefined; + return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, bundleInfoPath: bundleInfoPath }; + } + else { + var ownOutputFilePath = ts.getOwnEmitOutputFilePath(sourceFile.fileName, host, getOutputExtension(sourceFile, options)); + // If json file emits to the same location skip writing it, if emitDeclarationOnly skip writing it + var isJsonEmittedToSameLocation = ts.isJsonSourceFile(sourceFile) && + ts.comparePaths(sourceFile.fileName, ownOutputFilePath, host.getCurrentDirectory(), !host.useCaseSensitiveFileNames()) === 0 /* EqualTo */; + var jsFilePath = options.emitDeclarationOnly || isJsonEmittedToSameLocation ? undefined : ownOutputFilePath; + var sourceMapFilePath = !jsFilePath || ts.isJsonSourceFile(sourceFile) ? undefined : getSourceMapFilePath(jsFilePath, options); + // For legacy reasons (ie, we have baselines capturing the behavior), js files don't report a .d.ts output path - this would only matter if `declaration` and `allowJs` were both on, which is currently an error + var isJs = ts.isSourceFileJS(sourceFile); + var declarationFilePath = ((forceDtsPaths || ts.getEmitDeclarations(options)) && !isJs) ? ts.getDeclarationEmitOutputFilePath(sourceFile.fileName, host) : undefined; + var declarationMapPath = declarationFilePath && ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; + return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, bundleInfoPath: undefined }; + } + } + ts.getOutputPathsFor = getOutputPathsFor; + function getSourceMapFilePath(jsFilePath, options) { + return (options.sourceMap && !options.inlineSourceMap) ? jsFilePath + ".map" : undefined; + } + function createDefaultBundleInfo() { + return { + originalOffset: -1, + totalLength: -1 + }; + } + // JavaScript files are always LanguageVariant.JSX, as JSX syntax is allowed in .js files also. + // So for JavaScript files, '.jsx' is only emitted if the input was '.jsx', and JsxEmit.Preserve. + // For TypeScript, the only time to emit with a '.jsx' extension, is on JSX input, and JsxEmit.Preserve + /* @internal */ + function getOutputExtension(sourceFile, options) { + if (ts.isJsonSourceFile(sourceFile)) { + return ".json" /* Json */; + } + if (options.jsx === 1 /* Preserve */) { + if (ts.isSourceFileJS(sourceFile)) { + if (ts.fileExtensionIs(sourceFile.fileName, ".jsx" /* Jsx */)) { + return ".jsx" /* Jsx */; + } + } + else if (sourceFile.languageVariant === 1 /* JSX */) { + // TypeScript source file preserving JSX syntax + return ".jsx" /* Jsx */; + } + } + return ".js" /* Js */; + } + ts.getOutputExtension = getOutputExtension; + /*@internal*/ + // targetSourceFile is when users only want one file in entire project to be emitted. This is used in compileOnSave feature + function emitFiles(resolver, host, targetSourceFile, emitOnlyDtsFiles, transformers, declarationTransformers) { + var compilerOptions = host.getCompilerOptions(); + var sourceMapDataList = (compilerOptions.sourceMap || compilerOptions.inlineSourceMap || ts.getAreDeclarationMapsEnabled(compilerOptions)) ? [] : undefined; + var emittedFilesList = compilerOptions.listEmittedFiles ? [] : undefined; + var emitterDiagnostics = ts.createDiagnosticCollection(); + var newLine = ts.getNewLineCharacter(compilerOptions, function () { return host.getNewLine(); }); + var writer = ts.createTextWriter(newLine); + var _a = ts.performance.createTimer("printTime", "beforePrint", "afterPrint"), enter = _a.enter, exit = _a.exit; + var bundleInfo = createDefaultBundleInfo(); + var emitSkipped = false; + var exportedModulesFromDeclarationEmit; + // Emit each output file + enter(); + forEachEmittedFile(host, emitSourceFileOrBundle, ts.getSourceFilesToEmit(host, targetSourceFile), emitOnlyDtsFiles); + exit(); + return { + emitSkipped: emitSkipped, + diagnostics: emitterDiagnostics.getDiagnostics(), + emittedFiles: emittedFilesList, + sourceMaps: sourceMapDataList, + exportedModulesFromDeclarationEmit: exportedModulesFromDeclarationEmit + }; + function emitSourceFileOrBundle(_a, sourceFileOrBundle) { + var jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, bundleInfoPath = _a.bundleInfoPath; + emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, bundleInfoPath); + emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath); + if (!emitSkipped && emittedFilesList) { + if (!emitOnlyDtsFiles) { + if (jsFilePath) { + emittedFilesList.push(jsFilePath); + } + if (sourceMapFilePath) { + emittedFilesList.push(sourceMapFilePath); + } + if (bundleInfoPath) { + emittedFilesList.push(bundleInfoPath); + } + } + if (declarationFilePath) { + emittedFilesList.push(declarationFilePath); + } + if (declarationMapPath) { + emittedFilesList.push(declarationMapPath); + } + } + } + function emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, bundleInfoPath) { + if (emitOnlyDtsFiles || !jsFilePath) { + return; + } + // Make sure not to write js file and source map file if any of them cannot be written + if ((jsFilePath && host.isEmitBlocked(jsFilePath)) || compilerOptions.noEmit) { + emitSkipped = true; + return; + } + // Transform the source files + var transform = ts.transformNodes(resolver, host, compilerOptions, [sourceFileOrBundle], transformers, /*allowDtsFiles*/ false); + var printerOptions = { + removeComments: compilerOptions.removeComments, + newLine: compilerOptions.newLine, + noEmitHelpers: compilerOptions.noEmitHelpers, + module: compilerOptions.module, + target: compilerOptions.target, + sourceMap: compilerOptions.sourceMap, + inlineSourceMap: compilerOptions.inlineSourceMap, + inlineSources: compilerOptions.inlineSources, + extendedDiagnostics: compilerOptions.extendedDiagnostics, + }; + // Create a printer to print the nodes + var printer = createPrinter(printerOptions, { + // resolver hooks + hasGlobalName: resolver.hasGlobalName, + // transform hooks + onEmitNode: transform.emitNodeWithNotification, + substituteNode: transform.substituteNode, + }); + ts.Debug.assert(transform.transformed.length === 1, "Should only see one output from the transform"); + printSourceFileOrBundle(jsFilePath, sourceMapFilePath, transform.transformed[0], bundleInfoPath, printer, compilerOptions); + // Clean up emit nodes on parse tree + transform.dispose(); + } + function emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath) { + if (!(declarationFilePath && !ts.isInJSFile(sourceFileOrBundle))) { + return; + } + var sourceFiles = ts.isSourceFile(sourceFileOrBundle) ? [sourceFileOrBundle] : sourceFileOrBundle.sourceFiles; + // Setup and perform the transformation to retrieve declarations from the input files + var nonJsFiles = ts.filter(sourceFiles, ts.isSourceFileNotJS); + var inputListOrBundle = (compilerOptions.outFile || compilerOptions.out) ? [ts.createBundle(nonJsFiles, !ts.isSourceFile(sourceFileOrBundle) ? sourceFileOrBundle.prepends : undefined)] : nonJsFiles; + if (emitOnlyDtsFiles && !ts.getEmitDeclarations(compilerOptions)) { + // Checker wont collect the linked aliases since thats only done when declaration is enabled. + // Do that here when emitting only dts files + nonJsFiles.forEach(collectLinkedAliases); + } + var declarationTransform = ts.transformNodes(resolver, host, compilerOptions, inputListOrBundle, ts.concatenate([ts.transformDeclarations], declarationTransformers), /*allowDtsFiles*/ false); + if (ts.length(declarationTransform.diagnostics)) { + for (var _a = 0, _b = declarationTransform.diagnostics; _a < _b.length; _a++) { + var diagnostic = _b[_a]; + emitterDiagnostics.add(diagnostic); + } + } + var printerOptions = { + removeComments: compilerOptions.removeComments, + newLine: compilerOptions.newLine, + noEmitHelpers: true, + module: compilerOptions.module, + target: compilerOptions.target, + sourceMap: compilerOptions.sourceMap, + inlineSourceMap: compilerOptions.inlineSourceMap, + extendedDiagnostics: compilerOptions.extendedDiagnostics, + onlyPrintJsDocStyle: true, + }; + var declarationPrinter = createPrinter(printerOptions, { + // resolver hooks + hasGlobalName: resolver.hasGlobalName, + // transform hooks + onEmitNode: declarationTransform.emitNodeWithNotification, + substituteNode: declarationTransform.substituteNode, + }); + var declBlocked = (!!declarationTransform.diagnostics && !!declarationTransform.diagnostics.length) || !!host.isEmitBlocked(declarationFilePath) || !!compilerOptions.noEmit; + emitSkipped = emitSkipped || declBlocked; + if (!declBlocked || emitOnlyDtsFiles) { + ts.Debug.assert(declarationTransform.transformed.length === 1, "Should only see one output from the decl transform"); + printSourceFileOrBundle(declarationFilePath, declarationMapPath, declarationTransform.transformed[0], /* bundleInfopath*/ undefined, declarationPrinter, { + sourceMap: compilerOptions.declarationMap, + sourceRoot: compilerOptions.sourceRoot, + mapRoot: compilerOptions.mapRoot, + extendedDiagnostics: compilerOptions.extendedDiagnostics, + }); + if (emitOnlyDtsFiles && declarationTransform.transformed[0].kind === 279 /* SourceFile */) { + var sourceFile = declarationTransform.transformed[0]; + exportedModulesFromDeclarationEmit = sourceFile.exportedModulesFromDeclarationEmit; + } + } + declarationTransform.dispose(); + } + function collectLinkedAliases(node) { + if (ts.isExportAssignment(node)) { + if (node.expression.kind === 72 /* Identifier */) { + resolver.collectLinkedAliases(node.expression, /*setVisibility*/ true); + } + return; + } + else if (ts.isExportSpecifier(node)) { + resolver.collectLinkedAliases(node.propertyName || node.name, /*setVisibility*/ true); + return; + } + ts.forEachChild(node, collectLinkedAliases); + } + function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle, bundleInfoPath, printer, mapOptions) { + var bundle = sourceFileOrBundle.kind === 280 /* Bundle */ ? sourceFileOrBundle : undefined; + var sourceFile = sourceFileOrBundle.kind === 279 /* SourceFile */ ? sourceFileOrBundle : undefined; + var sourceFiles = bundle ? bundle.sourceFiles : [sourceFile]; + var sourceMapGenerator; + if (shouldEmitSourceMaps(mapOptions, sourceFileOrBundle)) { + sourceMapGenerator = ts.createSourceMapGenerator(host, ts.getBaseFileName(ts.normalizeSlashes(jsFilePath)), getSourceRoot(mapOptions), getSourceMapDirectory(mapOptions, jsFilePath, sourceFile), mapOptions); + } + if (bundle) { + printer.writeBundle(bundle, bundleInfo, writer, sourceMapGenerator); + } + else { + printer.writeFile(sourceFile, writer, sourceMapGenerator); + } + if (sourceMapGenerator) { + if (sourceMapDataList) { + sourceMapDataList.push({ + inputSourceFileNames: sourceMapGenerator.getSources(), + sourceMap: sourceMapGenerator.toJSON() + }); + } + var sourceMappingURL = getSourceMappingURL(mapOptions, sourceMapGenerator, jsFilePath, sourceMapFilePath, sourceFile); + if (sourceMappingURL) { + if (!writer.isAtStartOfLine()) + writer.rawWrite(newLine); + writer.writeComment("//# " + "sourceMappingURL" + "=" + sourceMappingURL); // Tools can sometimes see this line as a source mapping url comment + } + // Write the source map + if (sourceMapFilePath) { + var sourceMap = sourceMapGenerator.toString(); + ts.writeFile(host, emitterDiagnostics, sourceMapFilePath, sourceMap, /*writeByteOrderMark*/ false, sourceFiles); + } + } + else { + writer.writeLine(); + } + // Write the output file + ts.writeFile(host, emitterDiagnostics, jsFilePath, writer.getText(), !!compilerOptions.emitBOM, sourceFiles); + // Write bundled offset information if applicable + if (bundleInfoPath) { + bundleInfo.totalLength = writer.getTextPos(); + ts.writeFile(host, emitterDiagnostics, bundleInfoPath, JSON.stringify(bundleInfo, undefined, 2), /*writeByteOrderMark*/ false); + } + // Reset state + writer.clear(); + bundleInfo = createDefaultBundleInfo(); + } + function shouldEmitSourceMaps(mapOptions, sourceFileOrBundle) { + return (mapOptions.sourceMap || mapOptions.inlineSourceMap) + && (sourceFileOrBundle.kind !== 279 /* SourceFile */ || !ts.fileExtensionIs(sourceFileOrBundle.fileName, ".json" /* Json */)); + } + function getSourceRoot(mapOptions) { + // Normalize source root and make sure it has trailing "/" so that it can be used to combine paths with the + // relative paths of the sources list in the sourcemap + var sourceRoot = ts.normalizeSlashes(mapOptions.sourceRoot || ""); + return sourceRoot ? ts.ensureTrailingDirectorySeparator(sourceRoot) : sourceRoot; + } + function getSourceMapDirectory(mapOptions, filePath, sourceFile) { + if (mapOptions.sourceRoot) + return host.getCommonSourceDirectory(); + if (mapOptions.mapRoot) { + var sourceMapDir = ts.normalizeSlashes(mapOptions.mapRoot); + if (sourceFile) { + // For modules or multiple emit files the mapRoot will have directory structure like the sources + // So if src\a.ts and src\lib\b.ts are compiled together user would be moving the maps into mapRoot\a.js.map and mapRoot\lib\b.js.map + sourceMapDir = ts.getDirectoryPath(ts.getSourceFilePathInNewDir(sourceFile.fileName, host, sourceMapDir)); + } + if (ts.getRootLength(sourceMapDir) === 0) { + // The relative paths are relative to the common directory + sourceMapDir = ts.combinePaths(host.getCommonSourceDirectory(), sourceMapDir); + } + return sourceMapDir; + } + return ts.getDirectoryPath(ts.normalizePath(filePath)); + } + function getSourceMappingURL(mapOptions, sourceMapGenerator, filePath, sourceMapFilePath, sourceFile) { + if (mapOptions.inlineSourceMap) { + // Encode the sourceMap into the sourceMap url + var sourceMapText = sourceMapGenerator.toString(); + var base64SourceMapText = ts.base64encode(ts.sys, sourceMapText); + return "data:application/json;base64," + base64SourceMapText; + } + var sourceMapFile = ts.getBaseFileName(ts.normalizeSlashes(ts.Debug.assertDefined(sourceMapFilePath))); + if (mapOptions.mapRoot) { + var sourceMapDir = ts.normalizeSlashes(mapOptions.mapRoot); + if (sourceFile) { + // For modules or multiple emit files the mapRoot will have directory structure like the sources + // So if src\a.ts and src\lib\b.ts are compiled together user would be moving the maps into mapRoot\a.js.map and mapRoot\lib\b.js.map + sourceMapDir = ts.getDirectoryPath(ts.getSourceFilePathInNewDir(sourceFile.fileName, host, sourceMapDir)); + } + if (ts.getRootLength(sourceMapDir) === 0) { + // The relative paths are relative to the common directory + sourceMapDir = ts.combinePaths(host.getCommonSourceDirectory(), sourceMapDir); + return ts.getRelativePathToDirectoryOrUrl(ts.getDirectoryPath(ts.normalizePath(filePath)), // get the relative sourceMapDir path based on jsFilePath + ts.combinePaths(sourceMapDir, sourceMapFile), // this is where user expects to see sourceMap + host.getCurrentDirectory(), host.getCanonicalFileName, + /*isAbsolutePathAnUrl*/ true); + } + else { + return ts.combinePaths(sourceMapDir, sourceMapFile); + } + } + return sourceMapFile; + } + } + ts.emitFiles = emitFiles; + var PipelinePhase; + (function (PipelinePhase) { + PipelinePhase[PipelinePhase["Notification"] = 0] = "Notification"; + PipelinePhase[PipelinePhase["Substitution"] = 1] = "Substitution"; + PipelinePhase[PipelinePhase["Comments"] = 2] = "Comments"; + PipelinePhase[PipelinePhase["SourceMaps"] = 3] = "SourceMaps"; + PipelinePhase[PipelinePhase["Emit"] = 4] = "Emit"; + })(PipelinePhase || (PipelinePhase = {})); + function createPrinter(printerOptions, handlers) { + if (printerOptions === void 0) { printerOptions = {}; } + if (handlers === void 0) { handlers = {}; } + var hasGlobalName = handlers.hasGlobalName, _a = handlers.onEmitNode, onEmitNode = _a === void 0 ? ts.noEmitNotification : _a, _b = handlers.substituteNode, substituteNode = _b === void 0 ? ts.noEmitSubstitution : _b, onBeforeEmitNodeArray = handlers.onBeforeEmitNodeArray, onAfterEmitNodeArray = handlers.onAfterEmitNodeArray, onBeforeEmitToken = handlers.onBeforeEmitToken, onAfterEmitToken = handlers.onAfterEmitToken; + var extendedDiagnostics = !!printerOptions.extendedDiagnostics; + var newLine = ts.getNewLineCharacter(printerOptions); + var moduleKind = ts.getEmitModuleKind(printerOptions); + var bundledHelpers = ts.createMap(); + var currentSourceFile; + var nodeIdToGeneratedName; // Map of generated names for specific nodes. + var autoGeneratedIdToGeneratedName; // Map of generated names for temp and loop variables. + var generatedNames; // Set of names generated by the NameGenerator. + var tempFlagsStack; // Stack of enclosing name generation scopes. + var tempFlags; // TempFlags for the current name generation scope. + var reservedNamesStack; // Stack of TempFlags reserved in enclosing name generation scopes. + var reservedNames; // TempFlags to reserve in nested name generation scopes. + var writer; + var ownWriter; // Reusable `EmitTextWriter` for basic printing. + var write = writeBase; + var isOwnFileEmit; + // Source Maps + var sourceMapsDisabled = true; + var sourceMapGenerator; + var sourceMapSource; + var sourceMapSourceIndex = -1; + // Comments + var containerPos = -1; + var containerEnd = -1; + var declarationListContainerEnd = -1; + var currentLineMap; + var detachedCommentsInfo; + var hasWrittenComment = false; + var commentsDisabled = !!printerOptions.removeComments; + var _c = ts.performance.createTimerIf(extendedDiagnostics, "commentTime", "beforeComment", "afterComment"), enterComment = _c.enter, exitComment = _c.exit; + reset(); + return { + // public API + printNode: printNode, + printList: printList, + printFile: printFile, + printBundle: printBundle, + // internal API + writeNode: writeNode, + writeList: writeList, + writeFile: writeFile, + writeBundle: writeBundle + }; + function printNode(hint, node, sourceFile) { + switch (hint) { + case 0 /* SourceFile */: + ts.Debug.assert(ts.isSourceFile(node), "Expected a SourceFile node."); + break; + case 2 /* IdentifierName */: + ts.Debug.assert(ts.isIdentifier(node), "Expected an Identifier node."); + break; + case 1 /* Expression */: + ts.Debug.assert(ts.isExpression(node), "Expected an Expression node."); + break; + } + switch (node.kind) { + case 279 /* SourceFile */: return printFile(node); + case 280 /* Bundle */: return printBundle(node); + case 281 /* UnparsedSource */: return printUnparsedSource(node); + } + writeNode(hint, node, sourceFile, beginPrint()); + return endPrint(); + } + function printList(format, nodes, sourceFile) { + writeList(format, nodes, sourceFile, beginPrint()); + return endPrint(); + } + function printBundle(bundle) { + writeBundle(bundle, /*bundleInfo*/ undefined, beginPrint(), /*sourceMapEmitter*/ undefined); + return endPrint(); + } + function printFile(sourceFile) { + writeFile(sourceFile, beginPrint(), /*sourceMapEmitter*/ undefined); + return endPrint(); + } + function printUnparsedSource(unparsed) { + writeUnparsedSource(unparsed, beginPrint()); + return endPrint(); + } + function writeNode(hint, node, sourceFile, output) { + var previousWriter = writer; + setWriter(output, /*_sourceMapGenerator*/ undefined); + print(hint, node, sourceFile); + reset(); + writer = previousWriter; + } + function writeList(format, nodes, sourceFile, output) { + var previousWriter = writer; + setWriter(output, /*_sourceMapGenerator*/ undefined); + if (sourceFile) { + setSourceFile(sourceFile); + } + emitList(syntheticParent, nodes, format); + reset(); + writer = previousWriter; + } + function writeBundle(bundle, bundleInfo, output, sourceMapGenerator) { + isOwnFileEmit = false; + var previousWriter = writer; + setWriter(output, sourceMapGenerator); + emitShebangIfNeeded(bundle); + emitPrologueDirectivesIfNeeded(bundle); + emitHelpers(bundle); + emitSyntheticTripleSlashReferencesIfNeeded(bundle); + for (var _a = 0, _b = bundle.prepends; _a < _b.length; _a++) { + var prepend = _b[_a]; + writeLine(); + print(4 /* Unspecified */, prepend, /*sourceFile*/ undefined); + } + if (bundleInfo) { + bundleInfo.originalOffset = writer.getTextPos(); + } + for (var _c = 0, _d = bundle.sourceFiles; _c < _d.length; _c++) { + var sourceFile = _d[_c]; + print(0 /* SourceFile */, sourceFile, sourceFile); + } + reset(); + writer = previousWriter; + } + function writeUnparsedSource(unparsed, output) { + var previousWriter = writer; + setWriter(output, /*_sourceMapGenerator*/ undefined); + print(4 /* Unspecified */, unparsed, /*sourceFile*/ undefined); + reset(); + writer = previousWriter; + } + function writeFile(sourceFile, output, sourceMapGenerator) { + isOwnFileEmit = true; + var previousWriter = writer; + setWriter(output, sourceMapGenerator); + emitShebangIfNeeded(sourceFile); + emitPrologueDirectivesIfNeeded(sourceFile); + print(0 /* SourceFile */, sourceFile, sourceFile); + reset(); + writer = previousWriter; + } + function beginPrint() { + return ownWriter || (ownWriter = ts.createTextWriter(newLine)); + } + function endPrint() { + var text = ownWriter.getText(); + ownWriter.clear(); + return text; + } + function print(hint, node, sourceFile) { + if (sourceFile) { + setSourceFile(sourceFile); + } + var pipelinePhase = getPipelinePhase(0 /* Notification */, node); + pipelinePhase(hint, node); + } + function setSourceFile(sourceFile) { + currentSourceFile = sourceFile; + currentLineMap = undefined; + detachedCommentsInfo = undefined; + if (sourceFile) { + setSourceMapSource(sourceFile); + } + } + function setWriter(_writer, _sourceMapGenerator) { + if (_writer && printerOptions.omitTrailingSemicolon) { + _writer = ts.getTrailingSemicolonOmittingWriter(_writer); + } + writer = _writer; // TODO: GH#18217 + sourceMapGenerator = _sourceMapGenerator; + sourceMapsDisabled = !writer || !sourceMapGenerator; + } + function reset() { + nodeIdToGeneratedName = []; + autoGeneratedIdToGeneratedName = []; + generatedNames = ts.createMap(); + tempFlagsStack = []; + tempFlags = 0 /* Auto */; + reservedNamesStack = []; + currentSourceFile = undefined; + currentLineMap = undefined; + detachedCommentsInfo = undefined; + setWriter(/*output*/ undefined, /*_sourceMapGenerator*/ undefined); + } + function getCurrentLineMap() { + return currentLineMap || (currentLineMap = ts.getLineStarts(currentSourceFile)); + } + function emit(node) { + if (node === undefined) + return; + var pipelinePhase = getPipelinePhase(0 /* Notification */, node); + pipelinePhase(4 /* Unspecified */, node); + } + function emitIdentifierName(node) { + if (node === undefined) + return; + var pipelinePhase = getPipelinePhase(0 /* Notification */, node); + pipelinePhase(2 /* IdentifierName */, node); + } + function emitExpression(node) { + if (node === undefined) + return; + var pipelinePhase = getPipelinePhase(0 /* Notification */, node); + pipelinePhase(1 /* Expression */, node); + } + function getPipelinePhase(phase, node) { + switch (phase) { + case 0 /* Notification */: + if (onEmitNode !== ts.noEmitNotification) { + return pipelineEmitWithNotification; + } + // falls through + case 1 /* Substitution */: + if (substituteNode !== ts.noEmitSubstitution) { + return pipelineEmitWithSubstitution; + } + // falls through + case 2 /* Comments */: + if (!commentsDisabled && node.kind !== 279 /* SourceFile */) { + return pipelineEmitWithComments; + } + // falls through + case 3 /* SourceMaps */: + if (!sourceMapsDisabled && node.kind !== 279 /* SourceFile */ && !ts.isInJsonFile(node)) { + return pipelineEmitWithSourceMap; + } + // falls through + case 4 /* Emit */: + return pipelineEmitWithHint; + default: + return ts.Debug.assertNever(phase); + } + } + function getNextPipelinePhase(currentPhase, node) { + return getPipelinePhase(currentPhase + 1, node); + } + function pipelineEmitWithNotification(hint, node) { + var pipelinePhase = getNextPipelinePhase(0 /* Notification */, node); + onEmitNode(hint, node, pipelinePhase); + } + function pipelineEmitWithHint(hint, node) { + if (hint === 0 /* SourceFile */) + return emitSourceFile(ts.cast(node, ts.isSourceFile)); + if (hint === 2 /* IdentifierName */) + return emitIdentifier(ts.cast(node, ts.isIdentifier)); + if (hint === 3 /* MappedTypeParameter */) + return emitMappedTypeParameter(ts.cast(node, ts.isTypeParameterDeclaration)); + if (hint === 5 /* EmbeddedStatement */) { + ts.Debug.assertNode(node, ts.isEmptyStatement); + return emitEmptyStatement(/*isEmbeddedStatement*/ true); + } + if (hint === 4 /* Unspecified */) { + if (ts.isKeyword(node.kind)) + return writeTokenNode(node, writeKeyword); + switch (node.kind) { + // Pseudo-literals + case 15 /* TemplateHead */: + case 16 /* TemplateMiddle */: + case 17 /* TemplateTail */: + return emitLiteral(node); + case 281 /* UnparsedSource */: + return emitUnparsedSource(node); + // Identifiers + case 72 /* Identifier */: + return emitIdentifier(node); + // Parse tree nodes + // Names + case 148 /* QualifiedName */: + return emitQualifiedName(node); + case 149 /* ComputedPropertyName */: + return emitComputedPropertyName(node); + // Signature elements + case 150 /* TypeParameter */: + return emitTypeParameter(node); + case 151 /* Parameter */: + return emitParameter(node); + case 152 /* Decorator */: + return emitDecorator(node); + // Type members + case 153 /* PropertySignature */: + return emitPropertySignature(node); + case 154 /* PropertyDeclaration */: + return emitPropertyDeclaration(node); + case 155 /* MethodSignature */: + return emitMethodSignature(node); + case 156 /* MethodDeclaration */: + return emitMethodDeclaration(node); + case 157 /* Constructor */: + return emitConstructor(node); + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + return emitAccessorDeclaration(node); + case 160 /* CallSignature */: + return emitCallSignature(node); + case 161 /* ConstructSignature */: + return emitConstructSignature(node); + case 162 /* IndexSignature */: + return emitIndexSignature(node); + // Types + case 163 /* TypePredicate */: + return emitTypePredicate(node); + case 164 /* TypeReference */: + return emitTypeReference(node); + case 165 /* FunctionType */: + return emitFunctionType(node); + case 289 /* JSDocFunctionType */: + return emitJSDocFunctionType(node); + case 166 /* ConstructorType */: + return emitConstructorType(node); + case 167 /* TypeQuery */: + return emitTypeQuery(node); + case 168 /* TypeLiteral */: + return emitTypeLiteral(node); + case 169 /* ArrayType */: + return emitArrayType(node); + case 170 /* TupleType */: + return emitTupleType(node); + case 171 /* OptionalType */: + return emitOptionalType(node); + case 173 /* UnionType */: + return emitUnionType(node); + case 174 /* IntersectionType */: + return emitIntersectionType(node); + case 175 /* ConditionalType */: + return emitConditionalType(node); + case 176 /* InferType */: + return emitInferType(node); + case 177 /* ParenthesizedType */: + return emitParenthesizedType(node); + case 211 /* ExpressionWithTypeArguments */: + return emitExpressionWithTypeArguments(node); + case 178 /* ThisType */: + return emitThisType(); + case 179 /* TypeOperator */: + return emitTypeOperator(node); + case 180 /* IndexedAccessType */: + return emitIndexedAccessType(node); + case 181 /* MappedType */: + return emitMappedType(node); + case 182 /* LiteralType */: + return emitLiteralType(node); + case 183 /* ImportType */: + return emitImportTypeNode(node); + case 284 /* JSDocAllType */: + writePunctuation("*"); + return; + case 285 /* JSDocUnknownType */: + writePunctuation("?"); + return; + case 286 /* JSDocNullableType */: + return emitJSDocNullableType(node); + case 287 /* JSDocNonNullableType */: + return emitJSDocNonNullableType(node); + case 288 /* JSDocOptionalType */: + return emitJSDocOptionalType(node); + case 172 /* RestType */: + case 290 /* JSDocVariadicType */: + return emitRestOrJSDocVariadicType(node); + // Binding patterns + case 184 /* ObjectBindingPattern */: + return emitObjectBindingPattern(node); + case 185 /* ArrayBindingPattern */: + return emitArrayBindingPattern(node); + case 186 /* BindingElement */: + return emitBindingElement(node); + // Misc + case 216 /* TemplateSpan */: + return emitTemplateSpan(node); + case 217 /* SemicolonClassElement */: + return emitSemicolonClassElement(); + // Statements + case 218 /* Block */: + return emitBlock(node); + case 219 /* VariableStatement */: + return emitVariableStatement(node); + case 220 /* EmptyStatement */: + return emitEmptyStatement(/*isEmbeddedStatement*/ false); + case 221 /* ExpressionStatement */: + return emitExpressionStatement(node); + case 222 /* IfStatement */: + return emitIfStatement(node); + case 223 /* DoStatement */: + return emitDoStatement(node); + case 224 /* WhileStatement */: + return emitWhileStatement(node); + case 225 /* ForStatement */: + return emitForStatement(node); + case 226 /* ForInStatement */: + return emitForInStatement(node); + case 227 /* ForOfStatement */: + return emitForOfStatement(node); + case 228 /* ContinueStatement */: + return emitContinueStatement(node); + case 229 /* BreakStatement */: + return emitBreakStatement(node); + case 230 /* ReturnStatement */: + return emitReturnStatement(node); + case 231 /* WithStatement */: + return emitWithStatement(node); + case 232 /* SwitchStatement */: + return emitSwitchStatement(node); + case 233 /* LabeledStatement */: + return emitLabeledStatement(node); + case 234 /* ThrowStatement */: + return emitThrowStatement(node); + case 235 /* TryStatement */: + return emitTryStatement(node); + case 236 /* DebuggerStatement */: + return emitDebuggerStatement(node); + // Declarations + case 237 /* VariableDeclaration */: + return emitVariableDeclaration(node); + case 238 /* VariableDeclarationList */: + return emitVariableDeclarationList(node); + case 239 /* FunctionDeclaration */: + return emitFunctionDeclaration(node); + case 240 /* ClassDeclaration */: + return emitClassDeclaration(node); + case 241 /* InterfaceDeclaration */: + return emitInterfaceDeclaration(node); + case 242 /* TypeAliasDeclaration */: + return emitTypeAliasDeclaration(node); + case 243 /* EnumDeclaration */: + return emitEnumDeclaration(node); + case 244 /* ModuleDeclaration */: + return emitModuleDeclaration(node); + case 245 /* ModuleBlock */: + return emitModuleBlock(node); + case 246 /* CaseBlock */: + return emitCaseBlock(node); + case 247 /* NamespaceExportDeclaration */: + return emitNamespaceExportDeclaration(node); + case 248 /* ImportEqualsDeclaration */: + return emitImportEqualsDeclaration(node); + case 249 /* ImportDeclaration */: + return emitImportDeclaration(node); + case 250 /* ImportClause */: + return emitImportClause(node); + case 251 /* NamespaceImport */: + return emitNamespaceImport(node); + case 252 /* NamedImports */: + return emitNamedImports(node); + case 253 /* ImportSpecifier */: + return emitImportSpecifier(node); + case 254 /* ExportAssignment */: + return emitExportAssignment(node); + case 255 /* ExportDeclaration */: + return emitExportDeclaration(node); + case 256 /* NamedExports */: + return emitNamedExports(node); + case 257 /* ExportSpecifier */: + return emitExportSpecifier(node); + case 258 /* MissingDeclaration */: + return; + // Module references + case 259 /* ExternalModuleReference */: + return emitExternalModuleReference(node); + // JSX (non-expression) + case 11 /* JsxText */: + return emitJsxText(node); + case 262 /* JsxOpeningElement */: + case 265 /* JsxOpeningFragment */: + return emitJsxOpeningElementOrFragment(node); + case 263 /* JsxClosingElement */: + case 266 /* JsxClosingFragment */: + return emitJsxClosingElementOrFragment(node); + case 267 /* JsxAttribute */: + return emitJsxAttribute(node); + case 268 /* JsxAttributes */: + return emitJsxAttributes(node); + case 269 /* JsxSpreadAttribute */: + return emitJsxSpreadAttribute(node); + case 270 /* JsxExpression */: + return emitJsxExpression(node); + // Clauses + case 271 /* CaseClause */: + return emitCaseClause(node); + case 272 /* DefaultClause */: + return emitDefaultClause(node); + case 273 /* HeritageClause */: + return emitHeritageClause(node); + case 274 /* CatchClause */: + return emitCatchClause(node); + // Property assignments + case 275 /* PropertyAssignment */: + return emitPropertyAssignment(node); + case 276 /* ShorthandPropertyAssignment */: + return emitShorthandPropertyAssignment(node); + case 277 /* SpreadAssignment */: + return emitSpreadAssignment(node); + // Enum + case 278 /* EnumMember */: + return emitEnumMember(node); + // JSDoc nodes (only used in codefixes currently) + case 299 /* JSDocParameterTag */: + case 305 /* JSDocPropertyTag */: + return emitJSDocPropertyLikeTag(node); + case 300 /* JSDocReturnTag */: + case 302 /* JSDocTypeTag */: + case 301 /* JSDocThisTag */: + case 298 /* JSDocEnumTag */: + return emitJSDocSimpleTypedTag(node); + case 295 /* JSDocAugmentsTag */: + return emitJSDocAugmentsTag(node); + case 303 /* JSDocTemplateTag */: + return emitJSDocTemplateTag(node); + case 304 /* JSDocTypedefTag */: + return emitJSDocTypedefTag(node); + case 297 /* JSDocCallbackTag */: + return emitJSDocCallbackTag(node); + case 293 /* JSDocSignature */: + return emitJSDocSignature(node); + case 292 /* JSDocTypeLiteral */: + return emitJSDocTypeLiteral(node); + case 296 /* JSDocClassTag */: + case 294 /* JSDocTag */: + return emitJSDocSimpleTag(node); + case 291 /* JSDocComment */: + return emitJSDoc(node); + // Transformation nodes (ignored) + } + if (ts.isExpression(node)) { + hint = 1 /* Expression */; + if (substituteNode !== ts.noEmitSubstitution) { + node = substituteNode(hint, node); + } + } + else if (ts.isToken(node)) { + return writeTokenNode(node, writePunctuation); + } + } + if (hint === 1 /* Expression */) { + switch (node.kind) { + // Literals + case 8 /* NumericLiteral */: + case 9 /* BigIntLiteral */: + return emitNumericOrBigIntLiteral(node); + case 10 /* StringLiteral */: + case 13 /* RegularExpressionLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: + return emitLiteral(node); + // Identifiers + case 72 /* Identifier */: + return emitIdentifier(node); + // Reserved words + case 87 /* FalseKeyword */: + case 96 /* NullKeyword */: + case 98 /* SuperKeyword */: + case 102 /* TrueKeyword */: + case 100 /* ThisKeyword */: + case 92 /* ImportKeyword */: + writeTokenNode(node, writeKeyword); + return; + // Expressions + case 187 /* ArrayLiteralExpression */: + return emitArrayLiteralExpression(node); + case 188 /* ObjectLiteralExpression */: + return emitObjectLiteralExpression(node); + case 189 /* PropertyAccessExpression */: + return emitPropertyAccessExpression(node); + case 190 /* ElementAccessExpression */: + return emitElementAccessExpression(node); + case 191 /* CallExpression */: + return emitCallExpression(node); + case 192 /* NewExpression */: + return emitNewExpression(node); + case 193 /* TaggedTemplateExpression */: + return emitTaggedTemplateExpression(node); + case 194 /* TypeAssertionExpression */: + return emitTypeAssertionExpression(node); + case 195 /* ParenthesizedExpression */: + return emitParenthesizedExpression(node); + case 196 /* FunctionExpression */: + return emitFunctionExpression(node); + case 197 /* ArrowFunction */: + return emitArrowFunction(node); + case 198 /* DeleteExpression */: + return emitDeleteExpression(node); + case 199 /* TypeOfExpression */: + return emitTypeOfExpression(node); + case 200 /* VoidExpression */: + return emitVoidExpression(node); + case 201 /* AwaitExpression */: + return emitAwaitExpression(node); + case 202 /* PrefixUnaryExpression */: + return emitPrefixUnaryExpression(node); + case 203 /* PostfixUnaryExpression */: + return emitPostfixUnaryExpression(node); + case 204 /* BinaryExpression */: + return emitBinaryExpression(node); + case 205 /* ConditionalExpression */: + return emitConditionalExpression(node); + case 206 /* TemplateExpression */: + return emitTemplateExpression(node); + case 207 /* YieldExpression */: + return emitYieldExpression(node); + case 208 /* SpreadElement */: + return emitSpreadExpression(node); + case 209 /* ClassExpression */: + return emitClassExpression(node); + case 210 /* OmittedExpression */: + return; + case 212 /* AsExpression */: + return emitAsExpression(node); + case 213 /* NonNullExpression */: + return emitNonNullExpression(node); + case 214 /* MetaProperty */: + return emitMetaProperty(node); + // JSX + case 260 /* JsxElement */: + return emitJsxElement(node); + case 261 /* JsxSelfClosingElement */: + return emitJsxSelfClosingElement(node); + case 264 /* JsxFragment */: + return emitJsxFragment(node); + // Transformation nodes + case 308 /* PartiallyEmittedExpression */: + return emitPartiallyEmittedExpression(node); + case 309 /* CommaListExpression */: + return emitCommaList(node); + } + } + } + function emitMappedTypeParameter(node) { + emit(node.name); + writeSpace(); + writeKeyword("in"); + writeSpace(); + emit(node.constraint); + } + function pipelineEmitWithSubstitution(hint, node) { + var pipelinePhase = getNextPipelinePhase(1 /* Substitution */, node); + pipelinePhase(hint, substituteNode(hint, node)); + } + function emitHelpers(node) { + var helpersEmitted = false; + var bundle = node.kind === 280 /* Bundle */ ? node : undefined; + if (bundle && moduleKind === ts.ModuleKind.None) { + return; + } + var numNodes = bundle ? bundle.sourceFiles.length : 1; + for (var i = 0; i < numNodes; i++) { + var currentNode = bundle ? bundle.sourceFiles[i] : node; + var sourceFile = ts.isSourceFile(currentNode) ? currentNode : currentSourceFile; + var shouldSkip = printerOptions.noEmitHelpers || ts.getExternalHelpersModuleName(sourceFile) !== undefined; + var shouldBundle = ts.isSourceFile(currentNode) && !isOwnFileEmit; + var helpers = ts.getEmitHelpers(currentNode); + if (helpers) { + for (var _a = 0, _b = ts.stableSort(helpers, ts.compareEmitHelpers); _a < _b.length; _a++) { + var helper = _b[_a]; + if (!helper.scoped) { + // Skip the helper if it can be skipped and the noEmitHelpers compiler + // option is set, or if it can be imported and the importHelpers compiler + // option is set. + if (shouldSkip) + continue; + // Skip the helper if it can be bundled but hasn't already been emitted and we + // are emitting a bundled module. + if (shouldBundle) { + if (bundledHelpers.get(helper.name)) { + continue; + } + bundledHelpers.set(helper.name, true); + } + } + else if (bundle) { + // Skip the helper if it is scoped and we are emitting bundled helpers + continue; + } + if (typeof helper.text === "string") { + writeLines(helper.text); + } + else { + writeLines(helper.text(makeFileLevelOptimisticUniqueName)); + } + helpersEmitted = true; + } + } + } + return helpersEmitted; + } + // + // Literals/Pseudo-literals + // + // SyntaxKind.NumericLiteral + // SyntaxKind.BigIntLiteral + function emitNumericOrBigIntLiteral(node) { + emitLiteral(node); + } + // SyntaxKind.StringLiteral + // SyntaxKind.RegularExpressionLiteral + // SyntaxKind.NoSubstitutionTemplateLiteral + // SyntaxKind.TemplateHead + // SyntaxKind.TemplateMiddle + // SyntaxKind.TemplateTail + function emitLiteral(node) { + var text = getLiteralTextOfNode(node, printerOptions.neverAsciiEscape); + if ((printerOptions.sourceMap || printerOptions.inlineSourceMap) + && (node.kind === 10 /* StringLiteral */ || ts.isTemplateLiteralKind(node.kind))) { + writeLiteral(text); + } + else { + // Quick info expects all literals to be called with writeStringLiteral, as there's no specific type for numberLiterals + writeStringLiteral(text); + } + } + // SyntaxKind.UnparsedSource + function emitUnparsedSource(unparsed) { + writer.rawWrite(unparsed.text); + } + // + // Identifiers + // + function emitIdentifier(node) { + var writeText = node.symbol ? writeSymbol : write; + writeText(getTextOfNode(node, /*includeTrivia*/ false), node.symbol); + emitList(node, node.typeArguments, 53776 /* TypeParameters */); // Call emitList directly since it could be an array of TypeParameterDeclarations _or_ type arguments + } + // + // Names + // + function emitQualifiedName(node) { + emitEntityName(node.left); + writePunctuation("."); + emit(node.right); + } + function emitEntityName(node) { + if (node.kind === 72 /* Identifier */) { + emitExpression(node); + } + else { + emit(node); + } + } + function emitComputedPropertyName(node) { + writePunctuation("["); + emitExpression(node.expression); + writePunctuation("]"); + } + // + // Signature elements + // + function emitTypeParameter(node) { + emit(node.name); + if (node.constraint) { + writeSpace(); + writeKeyword("extends"); + writeSpace(); + emit(node.constraint); + } + if (node.default) { + writeSpace(); + writeOperator("="); + writeSpace(); + emit(node.default); + } + } + function emitParameter(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + emit(node.dotDotDotToken); + emitNodeWithWriter(node.name, writeParameter); + emit(node.questionToken); + if (node.parent && node.parent.kind === 289 /* JSDocFunctionType */ && !node.name) { + emit(node.type); + } + else { + emitTypeAnnotation(node.type); + } + // The comment position has to fallback to any present node within the parameterdeclaration because as it turns out, the parser can make parameter declarations with _just_ an initializer. + emitInitializer(node.initializer, node.type ? node.type.end : node.questionToken ? node.questionToken.end : node.name ? node.name.end : node.modifiers ? node.modifiers.end : node.decorators ? node.decorators.end : node.pos, node); + } + function emitDecorator(decorator) { + writePunctuation("@"); + emitExpression(decorator.expression); + } + // + // Type members + // + function emitPropertySignature(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + emitNodeWithWriter(node.name, writeProperty); + emit(node.questionToken); + emitTypeAnnotation(node.type); + writeTrailingSemicolon(); + } + function emitPropertyDeclaration(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + emit(node.name); + emit(node.questionToken); + emit(node.exclamationToken); + emitTypeAnnotation(node.type); + emitInitializer(node.initializer, node.type ? node.type.end : node.questionToken ? node.questionToken.end : node.name.end, node); + writeTrailingSemicolon(); + } + function emitMethodSignature(node) { + pushNameGenerationScope(node); + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + emit(node.name); + emit(node.questionToken); + emitTypeParameters(node, node.typeParameters); + emitParameters(node, node.parameters); + emitTypeAnnotation(node.type); + writeTrailingSemicolon(); + popNameGenerationScope(node); + } + function emitMethodDeclaration(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + emit(node.asteriskToken); + emit(node.name); + emit(node.questionToken); + emitSignatureAndBody(node, emitSignatureHead); + } + function emitConstructor(node) { + emitModifiers(node, node.modifiers); + writeKeyword("constructor"); + emitSignatureAndBody(node, emitSignatureHead); + } + function emitAccessorDeclaration(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + writeKeyword(node.kind === 158 /* GetAccessor */ ? "get" : "set"); + writeSpace(); + emit(node.name); + emitSignatureAndBody(node, emitSignatureHead); + } + function emitCallSignature(node) { + pushNameGenerationScope(node); + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + emitTypeParameters(node, node.typeParameters); + emitParameters(node, node.parameters); + emitTypeAnnotation(node.type); + writeTrailingSemicolon(); + popNameGenerationScope(node); + } + function emitConstructSignature(node) { + pushNameGenerationScope(node); + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + writeKeyword("new"); + writeSpace(); + emitTypeParameters(node, node.typeParameters); + emitParameters(node, node.parameters); + emitTypeAnnotation(node.type); + writeTrailingSemicolon(); + popNameGenerationScope(node); + } + function emitIndexSignature(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + emitParametersForIndexSignature(node, node.parameters); + emitTypeAnnotation(node.type); + writeTrailingSemicolon(); + } + function emitSemicolonClassElement() { + writeTrailingSemicolon(); + } + // + // Types + // + function emitTypePredicate(node) { + emit(node.parameterName); + writeSpace(); + writeKeyword("is"); + writeSpace(); + emit(node.type); + } + function emitTypeReference(node) { + emit(node.typeName); + emitTypeArguments(node, node.typeArguments); + } + function emitFunctionType(node) { + pushNameGenerationScope(node); + emitTypeParameters(node, node.typeParameters); + emitParametersForArrow(node, node.parameters); + writeSpace(); + writePunctuation("=>"); + writeSpace(); + emit(node.type); + popNameGenerationScope(node); + } + function emitJSDocFunctionType(node) { + writeKeyword("function"); + emitParameters(node, node.parameters); + writePunctuation(":"); + emit(node.type); + } + function emitJSDocNullableType(node) { + writePunctuation("?"); + emit(node.type); + } + function emitJSDocNonNullableType(node) { + writePunctuation("!"); + emit(node.type); + } + function emitJSDocOptionalType(node) { + emit(node.type); + writePunctuation("="); + } + function emitConstructorType(node) { + pushNameGenerationScope(node); + writeKeyword("new"); + writeSpace(); + emitTypeParameters(node, node.typeParameters); + emitParameters(node, node.parameters); + writeSpace(); + writePunctuation("=>"); + writeSpace(); + emit(node.type); + popNameGenerationScope(node); + } + function emitTypeQuery(node) { + writeKeyword("typeof"); + writeSpace(); + emit(node.exprName); + } + function emitTypeLiteral(node) { + writePunctuation("{"); + var flags = ts.getEmitFlags(node) & 1 /* SingleLine */ ? 768 /* SingleLineTypeLiteralMembers */ : 32897 /* MultiLineTypeLiteralMembers */; + emitList(node, node.members, flags | 524288 /* NoSpaceIfEmpty */); + writePunctuation("}"); + } + function emitArrayType(node) { + emit(node.elementType); + writePunctuation("["); + writePunctuation("]"); + } + function emitRestOrJSDocVariadicType(node) { + writePunctuation("..."); + emit(node.type); + } + function emitTupleType(node) { + writePunctuation("["); + emitList(node, node.elementTypes, 528 /* TupleTypeElements */); + writePunctuation("]"); + } + function emitOptionalType(node) { + emit(node.type); + writePunctuation("?"); + } + function emitUnionType(node) { + emitList(node, node.types, 516 /* UnionTypeConstituents */); + } + function emitIntersectionType(node) { + emitList(node, node.types, 520 /* IntersectionTypeConstituents */); + } + function emitConditionalType(node) { + emit(node.checkType); + writeSpace(); + writeKeyword("extends"); + writeSpace(); + emit(node.extendsType); + writeSpace(); + writePunctuation("?"); + writeSpace(); + emit(node.trueType); + writeSpace(); + writePunctuation(":"); + writeSpace(); + emit(node.falseType); + } + function emitInferType(node) { + writeKeyword("infer"); + writeSpace(); + emit(node.typeParameter); + } + function emitParenthesizedType(node) { + writePunctuation("("); + emit(node.type); + writePunctuation(")"); + } + function emitThisType() { + writeKeyword("this"); + } + function emitTypeOperator(node) { + writeTokenText(node.operator, writeKeyword); + writeSpace(); + emit(node.type); + } + function emitIndexedAccessType(node) { + emit(node.objectType); + writePunctuation("["); + emit(node.indexType); + writePunctuation("]"); + } + function emitMappedType(node) { + var emitFlags = ts.getEmitFlags(node); + writePunctuation("{"); + if (emitFlags & 1 /* SingleLine */) { + writeSpace(); + } + else { + writeLine(); + increaseIndent(); + } + if (node.readonlyToken) { + emit(node.readonlyToken); + if (node.readonlyToken.kind !== 133 /* ReadonlyKeyword */) { + writeKeyword("readonly"); + } + writeSpace(); + } + writePunctuation("["); + var pipelinePhase = getPipelinePhase(0 /* Notification */, node.typeParameter); + pipelinePhase(3 /* MappedTypeParameter */, node.typeParameter); + writePunctuation("]"); + if (node.questionToken) { + emit(node.questionToken); + if (node.questionToken.kind !== 56 /* QuestionToken */) { + writePunctuation("?"); + } + } + writePunctuation(":"); + writeSpace(); + emit(node.type); + writeTrailingSemicolon(); + if (emitFlags & 1 /* SingleLine */) { + writeSpace(); + } + else { + writeLine(); + decreaseIndent(); + } + writePunctuation("}"); + } + function emitLiteralType(node) { + emitExpression(node.literal); + } + function emitImportTypeNode(node) { + if (node.isTypeOf) { + writeKeyword("typeof"); + writeSpace(); + } + writeKeyword("import"); + writePunctuation("("); + emit(node.argument); + writePunctuation(")"); + if (node.qualifier) { + writePunctuation("."); + emit(node.qualifier); + } + emitTypeArguments(node, node.typeArguments); + } + // + // Binding patterns + // + function emitObjectBindingPattern(node) { + writePunctuation("{"); + emitList(node, node.elements, 525136 /* ObjectBindingPatternElements */); + writePunctuation("}"); + } + function emitArrayBindingPattern(node) { + writePunctuation("["); + emitList(node, node.elements, 524880 /* ArrayBindingPatternElements */); + writePunctuation("]"); + } + function emitBindingElement(node) { + emit(node.dotDotDotToken); + if (node.propertyName) { + emit(node.propertyName); + writePunctuation(":"); + writeSpace(); + } + emit(node.name); + emitInitializer(node.initializer, node.name.end, node); + } + // + // Expressions + // + function emitArrayLiteralExpression(node) { + var elements = node.elements; + var preferNewLine = node.multiLine ? 65536 /* PreferNewLine */ : 0 /* None */; + emitExpressionList(node, elements, 8914 /* ArrayLiteralExpressionElements */ | preferNewLine); + } + function emitObjectLiteralExpression(node) { + ts.forEach(node.properties, generateMemberNames); + var indentedFlag = ts.getEmitFlags(node) & 65536 /* Indented */; + if (indentedFlag) { + increaseIndent(); + } + var preferNewLine = node.multiLine ? 65536 /* PreferNewLine */ : 0 /* None */; + var allowTrailingComma = currentSourceFile.languageVersion >= 1 /* ES5 */ && !ts.isJsonSourceFile(currentSourceFile) ? 64 /* AllowTrailingComma */ : 0 /* None */; + emitList(node, node.properties, 526226 /* ObjectLiteralExpressionProperties */ | allowTrailingComma | preferNewLine); + if (indentedFlag) { + decreaseIndent(); + } + } + function emitPropertyAccessExpression(node) { + var indentBeforeDot = false; + var indentAfterDot = false; + if (!(ts.getEmitFlags(node) & 131072 /* NoIndentation */)) { + var dotRangeStart = node.expression.end; + var dotRangeEnd = ts.skipTrivia(currentSourceFile.text, node.expression.end) + 1; + var dotToken = ts.createToken(24 /* DotToken */); + dotToken.pos = dotRangeStart; + dotToken.end = dotRangeEnd; + indentBeforeDot = needsIndentation(node, node.expression, dotToken); + indentAfterDot = needsIndentation(node, dotToken, node.name); + } + emitExpression(node.expression); + increaseIndentIf(indentBeforeDot, /*writeSpaceIfNotIndenting*/ false); + var shouldEmitDotDot = !indentBeforeDot && needsDotDotForPropertyAccess(node.expression); + if (shouldEmitDotDot) { + writePunctuation("."); + } + emitTokenWithComment(24 /* DotToken */, node.expression.end, writePunctuation, node); + increaseIndentIf(indentAfterDot, /*writeSpaceIfNotIndenting*/ false); + emit(node.name); + decreaseIndentIf(indentBeforeDot, indentAfterDot); + } + // 1..toString is a valid property access, emit a dot after the literal + // Also emit a dot if expression is a integer const enum value - it will appear in generated code as numeric literal + function needsDotDotForPropertyAccess(expression) { + expression = ts.skipPartiallyEmittedExpressions(expression); + if (ts.isNumericLiteral(expression)) { + // check if numeric literal is a decimal literal that was originally written with a dot + var text = getLiteralTextOfNode(expression, /*neverAsciiEscape*/ true); + return !expression.numericLiteralFlags + && !ts.stringContains(text, ts.tokenToString(24 /* DotToken */)); + } + else if (ts.isPropertyAccessExpression(expression) || ts.isElementAccessExpression(expression)) { + // check if constant enum value is integer + var constantValue = ts.getConstantValue(expression); + // isFinite handles cases when constantValue is undefined + return typeof constantValue === "number" && isFinite(constantValue) + && Math.floor(constantValue) === constantValue + && printerOptions.removeComments; + } + } + function emitElementAccessExpression(node) { + emitExpression(node.expression); + emitTokenWithComment(22 /* OpenBracketToken */, node.expression.end, writePunctuation, node); + emitExpression(node.argumentExpression); + emitTokenWithComment(23 /* CloseBracketToken */, node.argumentExpression.end, writePunctuation, node); + } + function emitCallExpression(node) { + emitExpression(node.expression); + emitTypeArguments(node, node.typeArguments); + emitExpressionList(node, node.arguments, 2576 /* CallExpressionArguments */); + } + function emitNewExpression(node) { + emitTokenWithComment(95 /* NewKeyword */, node.pos, writeKeyword, node); + writeSpace(); + emitExpression(node.expression); + emitTypeArguments(node, node.typeArguments); + emitExpressionList(node, node.arguments, 18960 /* NewExpressionArguments */); + } + function emitTaggedTemplateExpression(node) { + emitExpression(node.tag); + emitTypeArguments(node, node.typeArguments); + writeSpace(); + emitExpression(node.template); + } + function emitTypeAssertionExpression(node) { + writePunctuation("<"); + emit(node.type); + writePunctuation(">"); + emitExpression(node.expression); + } + function emitParenthesizedExpression(node) { + var openParenPos = emitTokenWithComment(20 /* OpenParenToken */, node.pos, writePunctuation, node); + emitExpression(node.expression); + emitTokenWithComment(21 /* CloseParenToken */, node.expression ? node.expression.end : openParenPos, writePunctuation, node); + } + function emitFunctionExpression(node) { + generateNameIfNeeded(node.name); + emitFunctionDeclarationOrExpression(node); + } + function emitArrowFunction(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + emitSignatureAndBody(node, emitArrowFunctionHead); + } + function emitArrowFunctionHead(node) { + emitTypeParameters(node, node.typeParameters); + emitParametersForArrow(node, node.parameters); + emitTypeAnnotation(node.type); + writeSpace(); + emit(node.equalsGreaterThanToken); + } + function emitDeleteExpression(node) { + emitTokenWithComment(81 /* DeleteKeyword */, node.pos, writeKeyword, node); + writeSpace(); + emitExpression(node.expression); + } + function emitTypeOfExpression(node) { + emitTokenWithComment(104 /* TypeOfKeyword */, node.pos, writeKeyword, node); + writeSpace(); + emitExpression(node.expression); + } + function emitVoidExpression(node) { + emitTokenWithComment(106 /* VoidKeyword */, node.pos, writeKeyword, node); + writeSpace(); + emitExpression(node.expression); + } + function emitAwaitExpression(node) { + emitTokenWithComment(122 /* AwaitKeyword */, node.pos, writeKeyword, node); + writeSpace(); + emitExpression(node.expression); + } + function emitPrefixUnaryExpression(node) { + writeTokenText(node.operator, writeOperator); + if (shouldEmitWhitespaceBeforeOperand(node)) { + writeSpace(); + } + emitExpression(node.operand); + } + function shouldEmitWhitespaceBeforeOperand(node) { + // In some cases, we need to emit a space between the operator and the operand. One obvious case + // is when the operator is an identifier, like delete or typeof. We also need to do this for plus + // and minus expressions in certain cases. Specifically, consider the following two cases (parens + // are just for clarity of exposition, and not part of the source code): + // + // (+(+1)) + // (+(++1)) + // + // We need to emit a space in both cases. In the first case, the absence of a space will make + // the resulting expression a prefix increment operation. And in the second, it will make the resulting + // expression a prefix increment whose operand is a plus expression - (++(+x)) + // The same is true of minus of course. + var operand = node.operand; + return operand.kind === 202 /* PrefixUnaryExpression */ + && ((node.operator === 38 /* PlusToken */ && (operand.operator === 38 /* PlusToken */ || operand.operator === 44 /* PlusPlusToken */)) + || (node.operator === 39 /* MinusToken */ && (operand.operator === 39 /* MinusToken */ || operand.operator === 45 /* MinusMinusToken */))); + } + function emitPostfixUnaryExpression(node) { + emitExpression(node.operand); + writeTokenText(node.operator, writeOperator); + } + function emitBinaryExpression(node) { + var isCommaOperator = node.operatorToken.kind !== 27 /* CommaToken */; + var indentBeforeOperator = needsIndentation(node, node.left, node.operatorToken); + var indentAfterOperator = needsIndentation(node, node.operatorToken, node.right); + emitExpression(node.left); + increaseIndentIf(indentBeforeOperator, isCommaOperator); + emitLeadingCommentsOfPosition(node.operatorToken.pos); + writeTokenNode(node.operatorToken, node.operatorToken.kind === 93 /* InKeyword */ ? writeKeyword : writeOperator); + emitTrailingCommentsOfPosition(node.operatorToken.end, /*prefixSpace*/ true); // Binary operators should have a space before the comment starts + increaseIndentIf(indentAfterOperator, /*writeSpaceIfNotIndenting*/ true); + emitExpression(node.right); + decreaseIndentIf(indentBeforeOperator, indentAfterOperator); + } + function emitConditionalExpression(node) { + var indentBeforeQuestion = needsIndentation(node, node.condition, node.questionToken); + var indentAfterQuestion = needsIndentation(node, node.questionToken, node.whenTrue); + var indentBeforeColon = needsIndentation(node, node.whenTrue, node.colonToken); + var indentAfterColon = needsIndentation(node, node.colonToken, node.whenFalse); + emitExpression(node.condition); + increaseIndentIf(indentBeforeQuestion, /*writeSpaceIfNotIndenting*/ true); + emit(node.questionToken); + increaseIndentIf(indentAfterQuestion, /*writeSpaceIfNotIndenting*/ true); + emitExpression(node.whenTrue); + decreaseIndentIf(indentBeforeQuestion, indentAfterQuestion); + increaseIndentIf(indentBeforeColon, /*writeSpaceIfNotIndenting*/ true); + emit(node.colonToken); + increaseIndentIf(indentAfterColon, /*writeSpaceIfNotIndenting*/ true); + emitExpression(node.whenFalse); + decreaseIndentIf(indentBeforeColon, indentAfterColon); + } + function emitTemplateExpression(node) { + emit(node.head); + emitList(node, node.templateSpans, 262144 /* TemplateExpressionSpans */); + } + function emitYieldExpression(node) { + emitTokenWithComment(117 /* YieldKeyword */, node.pos, writeKeyword, node); + emit(node.asteriskToken); + emitExpressionWithLeadingSpace(node.expression); + } + function emitSpreadExpression(node) { + emitTokenWithComment(25 /* DotDotDotToken */, node.pos, writePunctuation, node); + emitExpression(node.expression); + } + function emitClassExpression(node) { + generateNameIfNeeded(node.name); + emitClassDeclarationOrExpression(node); + } + function emitExpressionWithTypeArguments(node) { + emitExpression(node.expression); + emitTypeArguments(node, node.typeArguments); + } + function emitAsExpression(node) { + emitExpression(node.expression); + if (node.type) { + writeSpace(); + writeKeyword("as"); + writeSpace(); + emit(node.type); + } + } + function emitNonNullExpression(node) { + emitExpression(node.expression); + writeOperator("!"); + } + function emitMetaProperty(node) { + writeToken(node.keywordToken, node.pos, writePunctuation); + writePunctuation("."); + emit(node.name); + } + // + // Misc + // + function emitTemplateSpan(node) { + emitExpression(node.expression); + emit(node.literal); + } + // + // Statements + // + function emitBlock(node) { + emitBlockStatements(node, /*forceSingleLine*/ !node.multiLine && isEmptyBlock(node)); + } + function emitBlockStatements(node, forceSingleLine) { + emitTokenWithComment(18 /* OpenBraceToken */, node.pos, writePunctuation, /*contextNode*/ node); + var format = forceSingleLine || ts.getEmitFlags(node) & 1 /* SingleLine */ ? 768 /* SingleLineBlockStatements */ : 129 /* MultiLineBlockStatements */; + emitList(node, node.statements, format); + emitTokenWithComment(19 /* CloseBraceToken */, node.statements.end, writePunctuation, /*contextNode*/ node, /*indentLeading*/ !!(format & 1 /* MultiLine */)); + } + function emitVariableStatement(node) { + emitModifiers(node, node.modifiers); + emit(node.declarationList); + writeTrailingSemicolon(); + } + function emitEmptyStatement(isEmbeddedStatement) { + // While most trailing semicolons are possibly insignificant, an embedded "empty" + // statement is significant and cannot be elided by a trailing-semicolon-omitting writer. + if (isEmbeddedStatement) { + writePunctuation(";"); + } + else { + writeTrailingSemicolon(); + } + } + function emitExpressionStatement(node) { + emitExpression(node.expression); + // Emit semicolon in non json files + // or if json file that created synthesized expression(eg.define expression statement when --out and amd code generation) + if (!ts.isJsonSourceFile(currentSourceFile) || ts.nodeIsSynthesized(node.expression)) { + writeTrailingSemicolon(); + } + } + function emitIfStatement(node) { + var openParenPos = emitTokenWithComment(91 /* IfKeyword */, node.pos, writeKeyword, node); + writeSpace(); + emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node); + emitExpression(node.expression); + emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node); + emitEmbeddedStatement(node, node.thenStatement); + if (node.elseStatement) { + writeLineOrSpace(node); + emitTokenWithComment(83 /* ElseKeyword */, node.thenStatement.end, writeKeyword, node); + if (node.elseStatement.kind === 222 /* IfStatement */) { + writeSpace(); + emit(node.elseStatement); + } + else { + emitEmbeddedStatement(node, node.elseStatement); + } + } + } + function emitWhileClause(node, startPos) { + var openParenPos = emitTokenWithComment(107 /* WhileKeyword */, startPos, writeKeyword, node); + writeSpace(); + emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node); + emitExpression(node.expression); + emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node); + } + function emitDoStatement(node) { + emitTokenWithComment(82 /* DoKeyword */, node.pos, writeKeyword, node); + emitEmbeddedStatement(node, node.statement); + if (ts.isBlock(node.statement)) { + writeSpace(); + } + else { + writeLineOrSpace(node); + } + emitWhileClause(node, node.statement.end); + writePunctuation(";"); + } + function emitWhileStatement(node) { + emitWhileClause(node, node.pos); + emitEmbeddedStatement(node, node.statement); + } + function emitForStatement(node) { + var openParenPos = emitTokenWithComment(89 /* ForKeyword */, node.pos, writeKeyword, node); + writeSpace(); + var pos = emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, /*contextNode*/ node); + emitForBinding(node.initializer); + pos = emitTokenWithComment(26 /* SemicolonToken */, node.initializer ? node.initializer.end : pos, writePunctuation, node); + emitExpressionWithLeadingSpace(node.condition); + pos = emitTokenWithComment(26 /* SemicolonToken */, node.condition ? node.condition.end : pos, writePunctuation, node); + emitExpressionWithLeadingSpace(node.incrementor); + emitTokenWithComment(21 /* CloseParenToken */, node.incrementor ? node.incrementor.end : pos, writePunctuation, node); + emitEmbeddedStatement(node, node.statement); + } + function emitForInStatement(node) { + var openParenPos = emitTokenWithComment(89 /* ForKeyword */, node.pos, writeKeyword, node); + writeSpace(); + emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node); + emitForBinding(node.initializer); + writeSpace(); + emitTokenWithComment(93 /* InKeyword */, node.initializer.end, writeKeyword, node); + writeSpace(); + emitExpression(node.expression); + emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node); + emitEmbeddedStatement(node, node.statement); + } + function emitForOfStatement(node) { + var openParenPos = emitTokenWithComment(89 /* ForKeyword */, node.pos, writeKeyword, node); + writeSpace(); + emitWithTrailingSpace(node.awaitModifier); + emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node); + emitForBinding(node.initializer); + writeSpace(); + emitTokenWithComment(147 /* OfKeyword */, node.initializer.end, writeKeyword, node); + writeSpace(); + emitExpression(node.expression); + emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node); + emitEmbeddedStatement(node, node.statement); + } + function emitForBinding(node) { + if (node !== undefined) { + if (node.kind === 238 /* VariableDeclarationList */) { + emit(node); + } + else { + emitExpression(node); + } + } + } + function emitContinueStatement(node) { + emitTokenWithComment(78 /* ContinueKeyword */, node.pos, writeKeyword, node); + emitWithLeadingSpace(node.label); + writeTrailingSemicolon(); + } + function emitBreakStatement(node) { + emitTokenWithComment(73 /* BreakKeyword */, node.pos, writeKeyword, node); + emitWithLeadingSpace(node.label); + writeTrailingSemicolon(); + } + function emitTokenWithComment(token, pos, writer, contextNode, indentLeading) { + var node = ts.getParseTreeNode(contextNode); + var isSimilarNode = node && node.kind === contextNode.kind; + var startPos = pos; + if (isSimilarNode) { + pos = ts.skipTrivia(currentSourceFile.text, pos); + } + if (emitLeadingCommentsOfPosition && isSimilarNode && contextNode.pos !== startPos) { + var needsIndent = indentLeading && !ts.positionsAreOnSameLine(startPos, pos, currentSourceFile); + if (needsIndent) { + increaseIndent(); + } + emitLeadingCommentsOfPosition(startPos); + if (needsIndent) { + decreaseIndent(); + } + } + pos = writeTokenText(token, writer, pos); + if (emitTrailingCommentsOfPosition && isSimilarNode && contextNode.end !== pos) { + emitTrailingCommentsOfPosition(pos, /*prefixSpace*/ true); + } + return pos; + } + function emitReturnStatement(node) { + emitTokenWithComment(97 /* ReturnKeyword */, node.pos, writeKeyword, /*contextNode*/ node); + emitExpressionWithLeadingSpace(node.expression); + writeTrailingSemicolon(); + } + function emitWithStatement(node) { + var openParenPos = emitTokenWithComment(108 /* WithKeyword */, node.pos, writeKeyword, node); + writeSpace(); + emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node); + emitExpression(node.expression); + emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node); + emitEmbeddedStatement(node, node.statement); + } + function emitSwitchStatement(node) { + var openParenPos = emitTokenWithComment(99 /* SwitchKeyword */, node.pos, writeKeyword, node); + writeSpace(); + emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node); + emitExpression(node.expression); + emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node); + writeSpace(); + emit(node.caseBlock); + } + function emitLabeledStatement(node) { + emit(node.label); + emitTokenWithComment(57 /* ColonToken */, node.label.end, writePunctuation, node); + writeSpace(); + emit(node.statement); + } + function emitThrowStatement(node) { + emitTokenWithComment(101 /* ThrowKeyword */, node.pos, writeKeyword, node); + emitExpressionWithLeadingSpace(node.expression); + writeTrailingSemicolon(); + } + function emitTryStatement(node) { + emitTokenWithComment(103 /* TryKeyword */, node.pos, writeKeyword, node); + writeSpace(); + emit(node.tryBlock); + if (node.catchClause) { + writeLineOrSpace(node); + emit(node.catchClause); + } + if (node.finallyBlock) { + writeLineOrSpace(node); + emitTokenWithComment(88 /* FinallyKeyword */, (node.catchClause || node.tryBlock).end, writeKeyword, node); + writeSpace(); + emit(node.finallyBlock); + } + } + function emitDebuggerStatement(node) { + writeToken(79 /* DebuggerKeyword */, node.pos, writeKeyword); + writeTrailingSemicolon(); + } + // + // Declarations + // + function emitVariableDeclaration(node) { + emit(node.name); + emitTypeAnnotation(node.type); + emitInitializer(node.initializer, node.type ? node.type.end : node.name.end, node); + } + function emitVariableDeclarationList(node) { + writeKeyword(ts.isLet(node) ? "let" : ts.isVarConst(node) ? "const" : "var"); + writeSpace(); + emitList(node, node.declarations, 528 /* VariableDeclarationList */); + } + function emitFunctionDeclaration(node) { + emitFunctionDeclarationOrExpression(node); + } + function emitFunctionDeclarationOrExpression(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + writeKeyword("function"); + emit(node.asteriskToken); + writeSpace(); + emitIdentifierName(node.name); // TODO: GH#18217 + emitSignatureAndBody(node, emitSignatureHead); + } + function emitBlockCallback(_hint, body) { + emitBlockFunctionBody(body); + } + function emitSignatureAndBody(node, emitSignatureHead) { + var body = node.body; + if (body) { + if (ts.isBlock(body)) { + var indentedFlag = ts.getEmitFlags(node) & 65536 /* Indented */; + if (indentedFlag) { + increaseIndent(); + } + pushNameGenerationScope(node); + ts.forEach(node.parameters, generateNames); + generateNames(node.body); + emitSignatureHead(node); + if (onEmitNode) { + onEmitNode(4 /* Unspecified */, body, emitBlockCallback); + } + else { + emitBlockFunctionBody(body); + } + popNameGenerationScope(node); + if (indentedFlag) { + decreaseIndent(); + } + } + else { + emitSignatureHead(node); + writeSpace(); + emitExpression(body); + } + } + else { + emitSignatureHead(node); + writeTrailingSemicolon(); + } + } + function emitSignatureHead(node) { + emitTypeParameters(node, node.typeParameters); + emitParameters(node, node.parameters); + emitTypeAnnotation(node.type); + } + function shouldEmitBlockFunctionBodyOnSingleLine(body) { + // We must emit a function body as a single-line body in the following case: + // * The body has NodeEmitFlags.SingleLine specified. + // We must emit a function body as a multi-line body in the following cases: + // * The body is explicitly marked as multi-line. + // * A non-synthesized body's start and end position are on different lines. + // * Any statement in the body starts on a new line. + if (ts.getEmitFlags(body) & 1 /* SingleLine */) { + return true; + } + if (body.multiLine) { + return false; + } + if (!ts.nodeIsSynthesized(body) && !ts.rangeIsOnSingleLine(body, currentSourceFile)) { + return false; + } + if (shouldWriteLeadingLineTerminator(body, body.statements, 2 /* PreserveLines */) + || shouldWriteClosingLineTerminator(body, body.statements, 2 /* PreserveLines */)) { + return false; + } + var previousStatement; + for (var _a = 0, _b = body.statements; _a < _b.length; _a++) { + var statement = _b[_a]; + if (shouldWriteSeparatingLineTerminator(previousStatement, statement, 2 /* PreserveLines */)) { + return false; + } + previousStatement = statement; + } + return true; + } + function emitBlockFunctionBody(body) { + writeSpace(); + writePunctuation("{"); + increaseIndent(); + var emitBlockFunctionBody = shouldEmitBlockFunctionBodyOnSingleLine(body) + ? emitBlockFunctionBodyOnSingleLine + : emitBlockFunctionBodyWorker; + if (emitBodyWithDetachedComments) { + emitBodyWithDetachedComments(body, body.statements, emitBlockFunctionBody); + } + else { + emitBlockFunctionBody(body); + } + decreaseIndent(); + writeToken(19 /* CloseBraceToken */, body.statements.end, writePunctuation, body); + } + function emitBlockFunctionBodyOnSingleLine(body) { + emitBlockFunctionBodyWorker(body, /*emitBlockFunctionBodyOnSingleLine*/ true); + } + function emitBlockFunctionBodyWorker(body, emitBlockFunctionBodyOnSingleLine) { + // Emit all the prologue directives (like "use strict"). + var statementOffset = emitPrologueDirectives(body.statements, /*startWithNewLine*/ true); + var pos = writer.getTextPos(); + emitHelpers(body); + if (statementOffset === 0 && pos === writer.getTextPos() && emitBlockFunctionBodyOnSingleLine) { + decreaseIndent(); + emitList(body, body.statements, 768 /* SingleLineFunctionBodyStatements */); + increaseIndent(); + } + else { + emitList(body, body.statements, 1 /* MultiLineFunctionBodyStatements */, statementOffset); + } + } + function emitClassDeclaration(node) { + emitClassDeclarationOrExpression(node); + } + function emitClassDeclarationOrExpression(node) { + ts.forEach(node.members, generateMemberNames); + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + writeKeyword("class"); + if (node.name) { + writeSpace(); + emitIdentifierName(node.name); + } + var indentedFlag = ts.getEmitFlags(node) & 65536 /* Indented */; + if (indentedFlag) { + increaseIndent(); + } + emitTypeParameters(node, node.typeParameters); + emitList(node, node.heritageClauses, 0 /* ClassHeritageClauses */); + writeSpace(); + writePunctuation("{"); + emitList(node, node.members, 129 /* ClassMembers */); + writePunctuation("}"); + if (indentedFlag) { + decreaseIndent(); + } + } + function emitInterfaceDeclaration(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + writeKeyword("interface"); + writeSpace(); + emit(node.name); + emitTypeParameters(node, node.typeParameters); + emitList(node, node.heritageClauses, 512 /* HeritageClauses */); + writeSpace(); + writePunctuation("{"); + emitList(node, node.members, 129 /* InterfaceMembers */); + writePunctuation("}"); + } + function emitTypeAliasDeclaration(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + writeKeyword("type"); + writeSpace(); + emit(node.name); + emitTypeParameters(node, node.typeParameters); + writeSpace(); + writePunctuation("="); + writeSpace(); + emit(node.type); + writeTrailingSemicolon(); + } + function emitEnumDeclaration(node) { + emitModifiers(node, node.modifiers); + writeKeyword("enum"); + writeSpace(); + emit(node.name); + writeSpace(); + writePunctuation("{"); + emitList(node, node.members, 145 /* EnumMembers */); + writePunctuation("}"); + } + function emitModuleDeclaration(node) { + emitModifiers(node, node.modifiers); + if (~node.flags & 512 /* GlobalAugmentation */) { + writeKeyword(node.flags & 16 /* Namespace */ ? "namespace" : "module"); + writeSpace(); + } + emit(node.name); + var body = node.body; + if (!body) + return writeTrailingSemicolon(); + while (body.kind === 244 /* ModuleDeclaration */) { + writePunctuation("."); + emit(body.name); + body = body.body; + } + writeSpace(); + emit(body); + } + function emitModuleBlock(node) { + pushNameGenerationScope(node); + ts.forEach(node.statements, generateNames); + emitBlockStatements(node, /*forceSingleLine*/ isEmptyBlock(node)); + popNameGenerationScope(node); + } + function emitCaseBlock(node) { + emitTokenWithComment(18 /* OpenBraceToken */, node.pos, writePunctuation, node); + emitList(node, node.clauses, 129 /* CaseBlockClauses */); + emitTokenWithComment(19 /* CloseBraceToken */, node.clauses.end, writePunctuation, node, /*indentLeading*/ true); + } + function emitImportEqualsDeclaration(node) { + emitModifiers(node, node.modifiers); + emitTokenWithComment(92 /* ImportKeyword */, node.modifiers ? node.modifiers.end : node.pos, writeKeyword, node); + writeSpace(); + emit(node.name); + writeSpace(); + emitTokenWithComment(59 /* EqualsToken */, node.name.end, writePunctuation, node); + writeSpace(); + emitModuleReference(node.moduleReference); + writeTrailingSemicolon(); + } + function emitModuleReference(node) { + if (node.kind === 72 /* Identifier */) { + emitExpression(node); + } + else { + emit(node); + } + } + function emitImportDeclaration(node) { + emitModifiers(node, node.modifiers); + emitTokenWithComment(92 /* ImportKeyword */, node.modifiers ? node.modifiers.end : node.pos, writeKeyword, node); + writeSpace(); + if (node.importClause) { + emit(node.importClause); + writeSpace(); + emitTokenWithComment(144 /* FromKeyword */, node.importClause.end, writeKeyword, node); + writeSpace(); + } + emitExpression(node.moduleSpecifier); + writeTrailingSemicolon(); + } + function emitImportClause(node) { + emit(node.name); + if (node.name && node.namedBindings) { + emitTokenWithComment(27 /* CommaToken */, node.name.end, writePunctuation, node); + writeSpace(); + } + emit(node.namedBindings); + } + function emitNamespaceImport(node) { + var asPos = emitTokenWithComment(40 /* AsteriskToken */, node.pos, writePunctuation, node); + writeSpace(); + emitTokenWithComment(119 /* AsKeyword */, asPos, writeKeyword, node); + writeSpace(); + emit(node.name); + } + function emitNamedImports(node) { + emitNamedImportsOrExports(node); + } + function emitImportSpecifier(node) { + emitImportOrExportSpecifier(node); + } + function emitExportAssignment(node) { + var nextPos = emitTokenWithComment(85 /* ExportKeyword */, node.pos, writeKeyword, node); + writeSpace(); + if (node.isExportEquals) { + emitTokenWithComment(59 /* EqualsToken */, nextPos, writeOperator, node); + } + else { + emitTokenWithComment(80 /* DefaultKeyword */, nextPos, writeKeyword, node); + } + writeSpace(); + emitExpression(node.expression); + writeTrailingSemicolon(); + } + function emitExportDeclaration(node) { + var nextPos = emitTokenWithComment(85 /* ExportKeyword */, node.pos, writeKeyword, node); + writeSpace(); + if (node.exportClause) { + emit(node.exportClause); + } + else { + nextPos = emitTokenWithComment(40 /* AsteriskToken */, nextPos, writePunctuation, node); + } + if (node.moduleSpecifier) { + writeSpace(); + var fromPos = node.exportClause ? node.exportClause.end : nextPos; + emitTokenWithComment(144 /* FromKeyword */, fromPos, writeKeyword, node); + writeSpace(); + emitExpression(node.moduleSpecifier); + } + writeTrailingSemicolon(); + } + function emitNamespaceExportDeclaration(node) { + var nextPos = emitTokenWithComment(85 /* ExportKeyword */, node.pos, writeKeyword, node); + writeSpace(); + nextPos = emitTokenWithComment(119 /* AsKeyword */, nextPos, writeKeyword, node); + writeSpace(); + nextPos = emitTokenWithComment(131 /* NamespaceKeyword */, nextPos, writeKeyword, node); + writeSpace(); + emit(node.name); + writeTrailingSemicolon(); + } + function emitNamedExports(node) { + emitNamedImportsOrExports(node); + } + function emitExportSpecifier(node) { + emitImportOrExportSpecifier(node); + } + function emitNamedImportsOrExports(node) { + writePunctuation("{"); + emitList(node, node.elements, 525136 /* NamedImportsOrExportsElements */); + writePunctuation("}"); + } + function emitImportOrExportSpecifier(node) { + if (node.propertyName) { + emit(node.propertyName); + writeSpace(); + emitTokenWithComment(119 /* AsKeyword */, node.propertyName.end, writeKeyword, node); + writeSpace(); + } + emit(node.name); + } + // + // Module references + // + function emitExternalModuleReference(node) { + writeKeyword("require"); + writePunctuation("("); + emitExpression(node.expression); + writePunctuation(")"); + } + // + // JSX + // + function emitJsxElement(node) { + emit(node.openingElement); + emitList(node, node.children, 262144 /* JsxElementOrFragmentChildren */); + emit(node.closingElement); + } + function emitJsxSelfClosingElement(node) { + writePunctuation("<"); + emitJsxTagName(node.tagName); + writeSpace(); + emit(node.attributes); + writePunctuation("/>"); + } + function emitJsxFragment(node) { + emit(node.openingFragment); + emitList(node, node.children, 262144 /* JsxElementOrFragmentChildren */); + emit(node.closingFragment); + } + function emitJsxOpeningElementOrFragment(node) { + writePunctuation("<"); + if (ts.isJsxOpeningElement(node)) { + emitJsxTagName(node.tagName); + if (node.attributes.properties && node.attributes.properties.length > 0) { + writeSpace(); + } + emit(node.attributes); + } + writePunctuation(">"); + } + function emitJsxText(node) { + writer.writeLiteral(getTextOfNode(node, /*includeTrivia*/ true)); + } + function emitJsxClosingElementOrFragment(node) { + writePunctuation(""); + } + function emitJsxAttributes(node) { + emitList(node, node.properties, 262656 /* JsxElementAttributes */); + } + function emitJsxAttribute(node) { + emit(node.name); + emitNodeWithPrefix("=", writePunctuation, node.initializer, emit); // TODO: GH#18217 + } + function emitJsxSpreadAttribute(node) { + writePunctuation("{..."); + emitExpression(node.expression); + writePunctuation("}"); + } + function emitJsxExpression(node) { + if (node.expression) { + writePunctuation("{"); + emit(node.dotDotDotToken); + emitExpression(node.expression); + writePunctuation("}"); + } + } + function emitJsxTagName(node) { + if (node.kind === 72 /* Identifier */) { + emitExpression(node); + } + else { + emit(node); + } + } + // + // Clauses + // + function emitCaseClause(node) { + emitTokenWithComment(74 /* CaseKeyword */, node.pos, writeKeyword, node); + writeSpace(); + emitExpression(node.expression); + emitCaseOrDefaultClauseRest(node, node.statements, node.expression.end); + } + function emitDefaultClause(node) { + var pos = emitTokenWithComment(80 /* DefaultKeyword */, node.pos, writeKeyword, node); + emitCaseOrDefaultClauseRest(node, node.statements, pos); + } + function emitCaseOrDefaultClauseRest(parentNode, statements, colonPos) { + var emitAsSingleStatement = statements.length === 1 && + ( + // treat synthesized nodes as located on the same line for emit purposes + ts.nodeIsSynthesized(parentNode) || + ts.nodeIsSynthesized(statements[0]) || + ts.rangeStartPositionsAreOnSameLine(parentNode, statements[0], currentSourceFile)); + var format = 163969 /* CaseOrDefaultClauseStatements */; + if (emitAsSingleStatement) { + writeToken(57 /* ColonToken */, colonPos, writePunctuation, parentNode); + writeSpace(); + format &= ~(1 /* MultiLine */ | 128 /* Indented */); + } + else { + emitTokenWithComment(57 /* ColonToken */, colonPos, writePunctuation, parentNode); + } + emitList(parentNode, statements, format); + } + function emitHeritageClause(node) { + writeSpace(); + writeTokenText(node.token, writeKeyword); + writeSpace(); + emitList(node, node.types, 528 /* HeritageClauseTypes */); + } + function emitCatchClause(node) { + var openParenPos = emitTokenWithComment(75 /* CatchKeyword */, node.pos, writeKeyword, node); + writeSpace(); + if (node.variableDeclaration) { + emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node); + emit(node.variableDeclaration); + emitTokenWithComment(21 /* CloseParenToken */, node.variableDeclaration.end, writePunctuation, node); + writeSpace(); + } + emit(node.block); + } + // + // Property assignments + // + function emitPropertyAssignment(node) { + emit(node.name); + writePunctuation(":"); + writeSpace(); + // This is to ensure that we emit comment in the following case: + // For example: + // obj = { + // id: /*comment1*/ ()=>void + // } + // "comment1" is not considered to be leading comment for node.initializer + // but rather a trailing comment on the previous node. + var initializer = node.initializer; + if (emitTrailingCommentsOfPosition && (ts.getEmitFlags(initializer) & 512 /* NoLeadingComments */) === 0) { + var commentRange = ts.getCommentRange(initializer); + emitTrailingCommentsOfPosition(commentRange.pos); + } + emitExpression(initializer); + } + function emitShorthandPropertyAssignment(node) { + emit(node.name); + if (node.objectAssignmentInitializer) { + writeSpace(); + writePunctuation("="); + writeSpace(); + emitExpression(node.objectAssignmentInitializer); + } + } + function emitSpreadAssignment(node) { + if (node.expression) { + emitTokenWithComment(25 /* DotDotDotToken */, node.pos, writePunctuation, node); + emitExpression(node.expression); + } + } + // + // Enum + // + function emitEnumMember(node) { + emit(node.name); + emitInitializer(node.initializer, node.name.end, node); + } + // + // JSDoc + // + function emitJSDoc(node) { + write("/**"); + if (node.comment) { + var lines = node.comment.split(/\r\n?|\n/g); + for (var _a = 0, lines_2 = lines; _a < lines_2.length; _a++) { + var line = lines_2[_a]; + writeLine(); + writeSpace(); + writePunctuation("*"); + writeSpace(); + write(line); + } + } + if (node.tags) { + if (node.tags.length === 1 && node.tags[0].kind === 302 /* JSDocTypeTag */ && !node.comment) { + writeSpace(); + emit(node.tags[0]); + } + else { + emitList(node, node.tags, 33 /* JSDocComment */); + } + } + writeSpace(); + write("*/"); + } + function emitJSDocSimpleTypedTag(tag) { + emitJSDocTagName(tag.tagName); + emitJSDocTypeExpression(tag.typeExpression); + emitJSDocComment(tag.comment); + } + function emitJSDocAugmentsTag(tag) { + emitJSDocTagName(tag.tagName); + writeSpace(); + writePunctuation("{"); + emit(tag.class); + writePunctuation("}"); + emitJSDocComment(tag.comment); + } + function emitJSDocTemplateTag(tag) { + emitJSDocTagName(tag.tagName); + emitJSDocTypeExpression(tag.constraint); + writeSpace(); + emitList(tag, tag.typeParameters, 528 /* CommaListElements */); + emitJSDocComment(tag.comment); + } + function emitJSDocTypedefTag(tag) { + emitJSDocTagName(tag.tagName); + if (tag.typeExpression) { + if (tag.typeExpression.kind === 283 /* JSDocTypeExpression */) { + emitJSDocTypeExpression(tag.typeExpression); + } + else { + writeSpace(); + writePunctuation("{"); + write("Object"); + if (tag.typeExpression.isArrayType) { + writePunctuation("["); + writePunctuation("]"); + } + writePunctuation("}"); + } + } + if (tag.fullName) { + writeSpace(); + emit(tag.fullName); + } + emitJSDocComment(tag.comment); + if (tag.typeExpression && tag.typeExpression.kind === 292 /* JSDocTypeLiteral */) { + emitJSDocTypeLiteral(tag.typeExpression); + } + } + function emitJSDocCallbackTag(tag) { + emitJSDocTagName(tag.tagName); + if (tag.name) { + writeSpace(); + emit(tag.name); + } + emitJSDocComment(tag.comment); + emitJSDocSignature(tag.typeExpression); + } + function emitJSDocSimpleTag(tag) { + emitJSDocTagName(tag.tagName); + emitJSDocComment(tag.comment); + } + function emitJSDocTypeLiteral(lit) { + emitList(lit, ts.createNodeArray(lit.jsDocPropertyTags), 33 /* JSDocComment */); + } + function emitJSDocSignature(sig) { + if (sig.typeParameters) { + emitList(sig, ts.createNodeArray(sig.typeParameters), 33 /* JSDocComment */); + } + if (sig.parameters) { + emitList(sig, ts.createNodeArray(sig.parameters), 33 /* JSDocComment */); + } + if (sig.type) { + writeLine(); + writeSpace(); + writePunctuation("*"); + writeSpace(); + emit(sig.type); + } + } + function emitJSDocPropertyLikeTag(param) { + emitJSDocTagName(param.tagName); + emitJSDocTypeExpression(param.typeExpression); + writeSpace(); + if (param.isBracketed) { + writePunctuation("["); + } + emit(param.name); + if (param.isBracketed) { + writePunctuation("]"); + } + emitJSDocComment(param.comment); + } + function emitJSDocTagName(tagName) { + writePunctuation("@"); + emit(tagName); + } + function emitJSDocComment(comment) { + if (comment) { + writeSpace(); + write(comment); + } + } + function emitJSDocTypeExpression(typeExpression) { + if (typeExpression) { + writeSpace(); + writePunctuation("{"); + emit(typeExpression.type); + writePunctuation("}"); + } + } + // + // Top-level nodes + // + function emitSourceFile(node) { + writeLine(); + var statements = node.statements; + if (emitBodyWithDetachedComments) { + // Emit detached comment if there are no prologue directives or if the first node is synthesized. + // The synthesized node will have no leading comment so some comments may be missed. + var shouldEmitDetachedComment = statements.length === 0 || + !ts.isPrologueDirective(statements[0]) || + ts.nodeIsSynthesized(statements[0]); + if (shouldEmitDetachedComment) { + emitBodyWithDetachedComments(node, statements, emitSourceFileWorker); + return; + } + } + emitSourceFileWorker(node); + } + function emitSyntheticTripleSlashReferencesIfNeeded(node) { + emitTripleSlashDirectives(!!node.hasNoDefaultLib, node.syntheticFileReferences || [], node.syntheticTypeReferences || [], node.syntheticLibReferences || []); + } + function emitTripleSlashDirectivesIfNeeded(node) { + if (node.isDeclarationFile) + emitTripleSlashDirectives(node.hasNoDefaultLib, node.referencedFiles, node.typeReferenceDirectives, node.libReferenceDirectives); + } + function emitTripleSlashDirectives(hasNoDefaultLib, files, types, libs) { + if (hasNoDefaultLib) { + writeComment("/// "); + writeLine(); + } + if (currentSourceFile && currentSourceFile.moduleName) { + writeComment("/// "); + writeLine(); + } + if (currentSourceFile && currentSourceFile.amdDependencies) { + for (var _a = 0, _b = currentSourceFile.amdDependencies; _a < _b.length; _a++) { + var dep = _b[_a]; + if (dep.name) { + writeComment("/// "); + } + else { + writeComment("/// "); + } + writeLine(); + } + } + for (var _c = 0, files_1 = files; _c < files_1.length; _c++) { + var directive = files_1[_c]; + writeComment("/// "); + writeLine(); + } + for (var _d = 0, types_18 = types; _d < types_18.length; _d++) { + var directive = types_18[_d]; + writeComment("/// "); + writeLine(); + } + for (var _e = 0, libs_1 = libs; _e < libs_1.length; _e++) { + var directive = libs_1[_e]; + writeComment("/// "); + writeLine(); + } + } + function emitSourceFileWorker(node) { + var statements = node.statements; + pushNameGenerationScope(node); + ts.forEach(node.statements, generateNames); + emitHelpers(node); + var index = ts.findIndex(statements, function (statement) { return !ts.isPrologueDirective(statement); }); + emitTripleSlashDirectivesIfNeeded(node); + emitList(node, statements, 1 /* MultiLine */, index === -1 ? statements.length : index); + popNameGenerationScope(node); + } + // Transformation nodes + function emitPartiallyEmittedExpression(node) { + emitExpression(node.expression); + } + function emitCommaList(node) { + emitExpressionList(node, node.elements, 528 /* CommaListElements */); + } + /** + * Emits any prologue directives at the start of a Statement list, returning the + * number of prologue directives written to the output. + */ + function emitPrologueDirectives(statements, startWithNewLine, seenPrologueDirectives) { + for (var i = 0; i < statements.length; i++) { + var statement = statements[i]; + if (ts.isPrologueDirective(statement)) { + var shouldEmitPrologueDirective = seenPrologueDirectives ? !seenPrologueDirectives.has(statement.expression.text) : true; + if (shouldEmitPrologueDirective) { + if (startWithNewLine || i > 0) { + writeLine(); + } + emit(statement); + if (seenPrologueDirectives) { + seenPrologueDirectives.set(statement.expression.text, true); + } + } + } + else { + // return index of the first non prologue directive + return i; + } + } + return statements.length; + } + function emitPrologueDirectivesIfNeeded(sourceFileOrBundle) { + if (ts.isSourceFile(sourceFileOrBundle)) { + setSourceFile(sourceFileOrBundle); + emitPrologueDirectives(sourceFileOrBundle.statements); + } + else { + var seenPrologueDirectives = ts.createMap(); + for (var _a = 0, _b = sourceFileOrBundle.sourceFiles; _a < _b.length; _a++) { + var sourceFile = _b[_a]; + setSourceFile(sourceFile); + emitPrologueDirectives(sourceFile.statements, /*startWithNewLine*/ true, seenPrologueDirectives); + } + setSourceFile(undefined); + } + } + function emitShebangIfNeeded(sourceFileOrBundle) { + if (ts.isSourceFile(sourceFileOrBundle)) { + var shebang = ts.getShebang(sourceFileOrBundle.text); + if (shebang) { + writeComment(shebang); + writeLine(); + return true; + } + } + else { + for (var _a = 0, _b = sourceFileOrBundle.sourceFiles; _a < _b.length; _a++) { + var sourceFile = _b[_a]; + // Emit only the first encountered shebang + if (emitShebangIfNeeded(sourceFile)) { + break; + } + } + } + } + // + // Helpers + // + function emitNodeWithWriter(node, writer) { + if (!node) + return; + var savedWrite = write; + write = writer; + emit(node); + write = savedWrite; + } + function emitModifiers(node, modifiers) { + if (modifiers && modifiers.length) { + emitList(node, modifiers, 262656 /* Modifiers */); + writeSpace(); + } + } + function emitTypeAnnotation(node) { + if (node) { + writePunctuation(":"); + writeSpace(); + emit(node); + } + } + function emitInitializer(node, equalCommentStartPos, container) { + if (node) { + writeSpace(); + emitTokenWithComment(59 /* EqualsToken */, equalCommentStartPos, writeOperator, container); + writeSpace(); + emitExpression(node); + } + } + function emitNodeWithPrefix(prefix, prefixWriter, node, emit) { + if (node) { + prefixWriter(prefix); + emit(node); + } + } + function emitWithLeadingSpace(node) { + if (node) { + writeSpace(); + emit(node); + } + } + function emitExpressionWithLeadingSpace(node) { + if (node) { + writeSpace(); + emitExpression(node); + } + } + function emitWithTrailingSpace(node) { + if (node) { + emit(node); + writeSpace(); + } + } + function emitEmbeddedStatement(parent, node) { + if (ts.isBlock(node) || ts.getEmitFlags(parent) & 1 /* SingleLine */) { + writeSpace(); + emit(node); + } + else { + writeLine(); + increaseIndent(); + if (ts.isEmptyStatement(node)) { + var pipelinePhase = getPipelinePhase(0 /* Notification */, node); + pipelinePhase(5 /* EmbeddedStatement */, node); + } + else { + emit(node); + } + decreaseIndent(); + } + } + function emitDecorators(parentNode, decorators) { + emitList(parentNode, decorators, 49153 /* Decorators */); + } + function emitTypeArguments(parentNode, typeArguments) { + emitList(parentNode, typeArguments, 53776 /* TypeArguments */); + } + function emitTypeParameters(parentNode, typeParameters) { + if (ts.isFunctionLike(parentNode) && parentNode.typeArguments) { // Quick info uses type arguments in place of type parameters on instantiated signatures + return emitTypeArguments(parentNode, parentNode.typeArguments); + } + emitList(parentNode, typeParameters, 53776 /* TypeParameters */); + } + function emitParameters(parentNode, parameters) { + emitList(parentNode, parameters, 2576 /* Parameters */); + } + function canEmitSimpleArrowHead(parentNode, parameters) { + var parameter = ts.singleOrUndefined(parameters); + return parameter + && parameter.pos === parentNode.pos // may not have parsed tokens between parent and parameter + && ts.isArrowFunction(parentNode) // only arrow functions may have simple arrow head + && !parentNode.type // arrow function may not have return type annotation + && !ts.some(parentNode.decorators) // parent may not have decorators + && !ts.some(parentNode.modifiers) // parent may not have modifiers + && !ts.some(parentNode.typeParameters) // parent may not have type parameters + && !ts.some(parameter.decorators) // parameter may not have decorators + && !ts.some(parameter.modifiers) // parameter may not have modifiers + && !parameter.dotDotDotToken // parameter may not be rest + && !parameter.questionToken // parameter may not be optional + && !parameter.type // parameter may not have a type annotation + && !parameter.initializer // parameter may not have an initializer + && ts.isIdentifier(parameter.name); // parameter name must be identifier + } + function emitParametersForArrow(parentNode, parameters) { + if (canEmitSimpleArrowHead(parentNode, parameters)) { + emitList(parentNode, parameters, 2576 /* Parameters */ & ~2048 /* Parenthesis */); + } + else { + emitParameters(parentNode, parameters); + } + } + function emitParametersForIndexSignature(parentNode, parameters) { + emitList(parentNode, parameters, 8848 /* IndexSignatureParameters */); + } + function emitList(parentNode, children, format, start, count) { + emitNodeList(emit, parentNode, children, format, start, count); + } + function emitExpressionList(parentNode, children, format, start, count) { + emitNodeList(emitExpression, parentNode, children, format, start, count); // TODO: GH#18217 + } + function writeDelimiter(format) { + switch (format & 60 /* DelimitersMask */) { + case 0 /* None */: + break; + case 16 /* CommaDelimited */: + writePunctuation(","); + break; + case 4 /* BarDelimited */: + writeSpace(); + writePunctuation("|"); + break; + case 32 /* AsteriskDelimited */: + writeSpace(); + writePunctuation("*"); + writeSpace(); + break; + case 8 /* AmpersandDelimited */: + writeSpace(); + writePunctuation("&"); + break; + } + } + function emitNodeList(emit, parentNode, children, format, start, count) { + if (start === void 0) { start = 0; } + if (count === void 0) { count = children ? children.length - start : 0; } + var isUndefined = children === undefined; + if (isUndefined && format & 16384 /* OptionalIfUndefined */) { + return; + } + var isEmpty = children === undefined || start >= children.length || count === 0; + if (isEmpty && format & 32768 /* OptionalIfEmpty */) { + if (onBeforeEmitNodeArray) { + onBeforeEmitNodeArray(children); + } + if (onAfterEmitNodeArray) { + onAfterEmitNodeArray(children); + } + return; + } + if (format & 15360 /* BracketsMask */) { + writePunctuation(getOpeningBracket(format)); + if (isEmpty && !isUndefined) { + // TODO: GH#18217 + emitTrailingCommentsOfPosition(children.pos, /*prefixSpace*/ true); // Emit comments within empty bracketed lists + } + } + if (onBeforeEmitNodeArray) { + onBeforeEmitNodeArray(children); + } + if (isEmpty) { + // Write a line terminator if the parent node was multi-line + if (format & 1 /* MultiLine */) { + writeLine(); + } + else if (format & 256 /* SpaceBetweenBraces */ && !(format & 524288 /* NoSpaceIfEmpty */)) { + writeSpace(); + } + } + else { + // Write the opening line terminator or leading whitespace. + var mayEmitInterveningComments = (format & 262144 /* NoInterveningComments */) === 0; + var shouldEmitInterveningComments = mayEmitInterveningComments; + if (shouldWriteLeadingLineTerminator(parentNode, children, format)) { // TODO: GH#18217 + writeLine(); + shouldEmitInterveningComments = false; + } + else if (format & 256 /* SpaceBetweenBraces */) { + writeSpace(); + } + // Increase the indent, if requested. + if (format & 128 /* Indented */) { + increaseIndent(); + } + // Emit each child. + var previousSibling = void 0; + var shouldDecreaseIndentAfterEmit = false; + for (var i = 0; i < count; i++) { + var child = children[start + i]; + // Write the delimiter if this is not the first node. + if (format & 32 /* AsteriskDelimited */) { + // always write JSDoc in the format "\n *" + writeLine(); + writeDelimiter(format); + } + else if (previousSibling) { + // i.e + // function commentedParameters( + // /* Parameter a */ + // a + // /* End of parameter a */ -> this comment isn't considered to be trailing comment of parameter "a" due to newline + // , + if (format & 60 /* DelimitersMask */ && previousSibling.end !== parentNode.end) { + emitLeadingCommentsOfPosition(previousSibling.end); + } + writeDelimiter(format); + // Write either a line terminator or whitespace to separate the elements. + if (shouldWriteSeparatingLineTerminator(previousSibling, child, format)) { + // If a synthesized node in a single-line list starts on a new + // line, we should increase the indent. + if ((format & (3 /* LinesMask */ | 128 /* Indented */)) === 0 /* SingleLine */) { + increaseIndent(); + shouldDecreaseIndentAfterEmit = true; + } + writeLine(); + shouldEmitInterveningComments = false; + } + else if (previousSibling && format & 512 /* SpaceBetweenSiblings */) { + writeSpace(); + } + } + // Emit this child. + if (shouldEmitInterveningComments) { + if (emitTrailingCommentsOfPosition) { + var commentRange = ts.getCommentRange(child); + emitTrailingCommentsOfPosition(commentRange.pos); + } + } + else { + shouldEmitInterveningComments = mayEmitInterveningComments; + } + emit(child); + if (shouldDecreaseIndentAfterEmit) { + decreaseIndent(); + shouldDecreaseIndentAfterEmit = false; + } + previousSibling = child; + } + // Write a trailing comma, if requested. + var hasTrailingComma = (format & 64 /* AllowTrailingComma */) && children.hasTrailingComma; + if (format & 16 /* CommaDelimited */ && hasTrailingComma) { + writePunctuation(","); + } + // Emit any trailing comment of the last element in the list + // i.e + // var array = [... + // 2 + // /* end of element 2 */ + // ]; + if (previousSibling && format & 60 /* DelimitersMask */ && previousSibling.end !== parentNode.end && !(ts.getEmitFlags(previousSibling) & 1024 /* NoTrailingComments */)) { + emitLeadingCommentsOfPosition(previousSibling.end); + } + // Decrease the indent, if requested. + if (format & 128 /* Indented */) { + decreaseIndent(); + } + // Write the closing line terminator or closing whitespace. + if (shouldWriteClosingLineTerminator(parentNode, children, format)) { + writeLine(); + } + else if (format & 256 /* SpaceBetweenBraces */) { + writeSpace(); + } + } + if (onAfterEmitNodeArray) { + onAfterEmitNodeArray(children); + } + if (format & 15360 /* BracketsMask */) { + if (isEmpty && !isUndefined) { + // TODO: GH#18217 + emitLeadingCommentsOfPosition(children.end); // Emit leading comments within empty lists + } + writePunctuation(getClosingBracket(format)); + } + } + // Writers + function writeLiteral(s) { + writer.writeLiteral(s); + } + function writeStringLiteral(s) { + writer.writeStringLiteral(s); + } + function writeBase(s) { + writer.write(s); + } + function writeSymbol(s, sym) { + writer.writeSymbol(s, sym); + } + function writePunctuation(s) { + writer.writePunctuation(s); + } + function writeTrailingSemicolon() { + writer.writeTrailingSemicolon(";"); + } + function writeKeyword(s) { + writer.writeKeyword(s); + } + function writeOperator(s) { + writer.writeOperator(s); + } + function writeParameter(s) { + writer.writeParameter(s); + } + function writeComment(s) { + writer.writeComment(s); + } + function writeSpace() { + writer.writeSpace(" "); + } + function writeProperty(s) { + writer.writeProperty(s); + } + function writeLine() { + writer.writeLine(); + } + function increaseIndent() { + writer.increaseIndent(); + } + function decreaseIndent() { + writer.decreaseIndent(); + } + function writeToken(token, pos, writer, contextNode) { + return !sourceMapsDisabled + ? emitTokenWithSourceMap(contextNode, token, writer, pos, writeTokenText) + : writeTokenText(token, writer, pos); + } + function writeTokenNode(node, writer) { + if (onBeforeEmitToken) { + onBeforeEmitToken(node); + } + writer(ts.tokenToString(node.kind)); + if (onAfterEmitToken) { + onAfterEmitToken(node); + } + } + function writeTokenText(token, writer, pos) { + var tokenString = ts.tokenToString(token); + writer(tokenString); + return pos < 0 ? pos : pos + tokenString.length; + } + function writeLineOrSpace(node) { + if (ts.getEmitFlags(node) & 1 /* SingleLine */) { + writeSpace(); + } + else { + writeLine(); + } + } + function writeLines(text) { + var lines = text.split(/\r\n?|\n/g); + var indentation = ts.guessIndentation(lines); + for (var _a = 0, lines_3 = lines; _a < lines_3.length; _a++) { + var lineText = lines_3[_a]; + var line = indentation ? lineText.slice(indentation) : lineText; + if (line.length) { + writeLine(); + write(line); + writer.rawWrite(newLine); + } + } + } + function increaseIndentIf(value, writeSpaceIfNotIndenting) { + if (value) { + increaseIndent(); + writeLine(); + } + else if (writeSpaceIfNotIndenting) { + writeSpace(); + } + } + // Helper function to decrease the indent if we previously indented. Allows multiple + // previous indent values to be considered at a time. This also allows caller to just + // call this once, passing in all their appropriate indent values, instead of needing + // to call this helper function multiple times. + function decreaseIndentIf(value1, value2) { + if (value1) { + decreaseIndent(); + } + if (value2) { + decreaseIndent(); + } + } + function shouldWriteLeadingLineTerminator(parentNode, children, format) { + if (format & 1 /* MultiLine */) { + return true; + } + if (format & 2 /* PreserveLines */) { + if (format & 65536 /* PreferNewLine */) { + return true; + } + var firstChild = children[0]; + if (firstChild === undefined) { + return !ts.rangeIsOnSingleLine(parentNode, currentSourceFile); + } + else if (ts.positionIsSynthesized(parentNode.pos) || ts.nodeIsSynthesized(firstChild)) { + return synthesizedNodeStartsOnNewLine(firstChild, format); + } + else { + return !ts.rangeStartPositionsAreOnSameLine(parentNode, firstChild, currentSourceFile); + } + } + else { + return false; + } + } + function shouldWriteSeparatingLineTerminator(previousNode, nextNode, format) { + if (format & 1 /* MultiLine */) { + return true; + } + else if (format & 2 /* PreserveLines */) { + if (previousNode === undefined || nextNode === undefined) { + return false; + } + else if (ts.nodeIsSynthesized(previousNode) || ts.nodeIsSynthesized(nextNode)) { + return synthesizedNodeStartsOnNewLine(previousNode, format) || synthesizedNodeStartsOnNewLine(nextNode, format); + } + else { + return !ts.rangeEndIsOnSameLineAsRangeStart(previousNode, nextNode, currentSourceFile); + } + } + else { + return ts.getStartsOnNewLine(nextNode); + } + } + function shouldWriteClosingLineTerminator(parentNode, children, format) { + if (format & 1 /* MultiLine */) { + return (format & 131072 /* NoTrailingNewLine */) === 0; + } + else if (format & 2 /* PreserveLines */) { + if (format & 65536 /* PreferNewLine */) { + return true; + } + var lastChild = ts.lastOrUndefined(children); + if (lastChild === undefined) { + return !ts.rangeIsOnSingleLine(parentNode, currentSourceFile); + } + else if (ts.positionIsSynthesized(parentNode.pos) || ts.nodeIsSynthesized(lastChild)) { + return synthesizedNodeStartsOnNewLine(lastChild, format); + } + else { + return !ts.rangeEndPositionsAreOnSameLine(parentNode, lastChild, currentSourceFile); + } + } + else { + return false; + } + } + function synthesizedNodeStartsOnNewLine(node, format) { + if (ts.nodeIsSynthesized(node)) { + var startsOnNewLine = ts.getStartsOnNewLine(node); + if (startsOnNewLine === undefined) { + return (format & 65536 /* PreferNewLine */) !== 0; + } + return startsOnNewLine; + } + return (format & 65536 /* PreferNewLine */) !== 0; + } + function needsIndentation(parent, node1, node2) { + parent = skipSynthesizedParentheses(parent); + node1 = skipSynthesizedParentheses(node1); + node2 = skipSynthesizedParentheses(node2); + // Always use a newline for synthesized code if the synthesizer desires it. + if (ts.getStartsOnNewLine(node2)) { + return true; + } + return !ts.nodeIsSynthesized(parent) + && !ts.nodeIsSynthesized(node1) + && !ts.nodeIsSynthesized(node2) + && !ts.rangeEndIsOnSameLineAsRangeStart(node1, node2, currentSourceFile); + } + function isEmptyBlock(block) { + return block.statements.length === 0 + && ts.rangeEndIsOnSameLineAsRangeStart(block, block, currentSourceFile); + } + function skipSynthesizedParentheses(node) { + while (node.kind === 195 /* ParenthesizedExpression */ && ts.nodeIsSynthesized(node)) { + node = node.expression; + } + return node; + } + function getTextOfNode(node, includeTrivia) { + if (ts.isGeneratedIdentifier(node)) { + return generateName(node); + } + else if (ts.isIdentifier(node) && (ts.nodeIsSynthesized(node) || !node.parent || !currentSourceFile || (node.parent && currentSourceFile && ts.getSourceFileOfNode(node) !== ts.getOriginalNode(currentSourceFile)))) { + return ts.idText(node); + } + else if (node.kind === 10 /* StringLiteral */ && node.textSourceNode) { + return getTextOfNode(node.textSourceNode, includeTrivia); + } + else if (ts.isLiteralExpression(node) && (ts.nodeIsSynthesized(node) || !node.parent)) { + return node.text; + } + return ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node, includeTrivia); + } + function getLiteralTextOfNode(node, neverAsciiEscape) { + if (node.kind === 10 /* StringLiteral */ && node.textSourceNode) { + var textSourceNode = node.textSourceNode; + if (ts.isIdentifier(textSourceNode)) { + return neverAsciiEscape || (ts.getEmitFlags(node) & 16777216 /* NoAsciiEscaping */) ? + "\"" + ts.escapeString(getTextOfNode(textSourceNode)) + "\"" : + "\"" + ts.escapeNonAsciiString(getTextOfNode(textSourceNode)) + "\""; + } + else { + return getLiteralTextOfNode(textSourceNode, neverAsciiEscape); + } + } + return ts.getLiteralText(node, currentSourceFile, neverAsciiEscape); + } + /** + * Push a new name generation scope. + */ + function pushNameGenerationScope(node) { + if (node && ts.getEmitFlags(node) & 524288 /* ReuseTempVariableScope */) { + return; + } + tempFlagsStack.push(tempFlags); + tempFlags = 0; + reservedNamesStack.push(reservedNames); + } + /** + * Pop the current name generation scope. + */ + function popNameGenerationScope(node) { + if (node && ts.getEmitFlags(node) & 524288 /* ReuseTempVariableScope */) { + return; + } + tempFlags = tempFlagsStack.pop(); + reservedNames = reservedNamesStack.pop(); + } + function reserveNameInNestedScopes(name) { + if (!reservedNames || reservedNames === ts.lastOrUndefined(reservedNamesStack)) { + reservedNames = ts.createMap(); + } + reservedNames.set(name, true); + } + function generateNames(node) { + if (!node) + return; + switch (node.kind) { + case 218 /* Block */: + ts.forEach(node.statements, generateNames); + break; + case 233 /* LabeledStatement */: + case 231 /* WithStatement */: + case 223 /* DoStatement */: + case 224 /* WhileStatement */: + generateNames(node.statement); + break; + case 222 /* IfStatement */: + generateNames(node.thenStatement); + generateNames(node.elseStatement); + break; + case 225 /* ForStatement */: + case 227 /* ForOfStatement */: + case 226 /* ForInStatement */: + generateNames(node.initializer); + generateNames(node.statement); + break; + case 232 /* SwitchStatement */: + generateNames(node.caseBlock); + break; + case 246 /* CaseBlock */: + ts.forEach(node.clauses, generateNames); + break; + case 271 /* CaseClause */: + case 272 /* DefaultClause */: + ts.forEach(node.statements, generateNames); + break; + case 235 /* TryStatement */: + generateNames(node.tryBlock); + generateNames(node.catchClause); + generateNames(node.finallyBlock); + break; + case 274 /* CatchClause */: + generateNames(node.variableDeclaration); + generateNames(node.block); + break; + case 219 /* VariableStatement */: + generateNames(node.declarationList); + break; + case 238 /* VariableDeclarationList */: + ts.forEach(node.declarations, generateNames); + break; + case 237 /* VariableDeclaration */: + case 151 /* Parameter */: + case 186 /* BindingElement */: + case 240 /* ClassDeclaration */: + generateNameIfNeeded(node.name); + break; + case 239 /* FunctionDeclaration */: + generateNameIfNeeded(node.name); + if (ts.getEmitFlags(node) & 524288 /* ReuseTempVariableScope */) { + ts.forEach(node.parameters, generateNames); + generateNames(node.body); + } + break; + case 184 /* ObjectBindingPattern */: + case 185 /* ArrayBindingPattern */: + ts.forEach(node.elements, generateNames); + break; + case 249 /* ImportDeclaration */: + generateNames(node.importClause); + break; + case 250 /* ImportClause */: + generateNameIfNeeded(node.name); + generateNames(node.namedBindings); + break; + case 251 /* NamespaceImport */: + generateNameIfNeeded(node.name); + break; + case 252 /* NamedImports */: + ts.forEach(node.elements, generateNames); + break; + case 253 /* ImportSpecifier */: + generateNameIfNeeded(node.propertyName || node.name); + break; + } + } + function generateMemberNames(node) { + if (!node) + return; + switch (node.kind) { + case 275 /* PropertyAssignment */: + case 276 /* ShorthandPropertyAssignment */: + case 154 /* PropertyDeclaration */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + generateNameIfNeeded(node.name); + break; + } + } + function generateNameIfNeeded(name) { + if (name) { + if (ts.isGeneratedIdentifier(name)) { + generateName(name); + } + else if (ts.isBindingPattern(name)) { + generateNames(name); + } + } + } + /** + * Generate the text for a generated identifier. + */ + function generateName(name) { + if ((name.autoGenerateFlags & 7 /* KindMask */) === 4 /* Node */) { + // Node names generate unique names based on their original node + // and are cached based on that node's id. + return generateNameCached(getNodeForGeneratedName(name), name.autoGenerateFlags); + } + else { + // Auto, Loop, and Unique names are cached based on their unique + // autoGenerateId. + var autoGenerateId = name.autoGenerateId; + return autoGeneratedIdToGeneratedName[autoGenerateId] || (autoGeneratedIdToGeneratedName[autoGenerateId] = makeName(name)); + } + } + function generateNameCached(node, flags) { + var nodeId = ts.getNodeId(node); + return nodeIdToGeneratedName[nodeId] || (nodeIdToGeneratedName[nodeId] = generateNameForNode(node, flags)); + } + /** + * Returns a value indicating whether a name is unique globally, within the current file, + * or within the NameGenerator. + */ + function isUniqueName(name) { + return isFileLevelUniqueName(name) + && !generatedNames.has(name) + && !(reservedNames && reservedNames.has(name)); + } + /** + * Returns a value indicating whether a name is unique globally or within the current file. + */ + function isFileLevelUniqueName(name) { + return currentSourceFile ? ts.isFileLevelUniqueName(currentSourceFile, name, hasGlobalName) : true; + } + /** + * Returns a value indicating whether a name is unique within a container. + */ + function isUniqueLocalName(name, container) { + for (var node = container; ts.isNodeDescendantOf(node, container); node = node.nextContainer) { + if (node.locals) { + var local = node.locals.get(ts.escapeLeadingUnderscores(name)); + // We conservatively include alias symbols to cover cases where they're emitted as locals + if (local && local.flags & (67220415 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */)) { + return false; + } + } + } + return true; + } + /** + * Return the next available name in the pattern _a ... _z, _0, _1, ... + * TempFlags._i or TempFlags._n may be used to express a preference for that dedicated name. + * Note that names generated by makeTempVariableName and makeUniqueName will never conflict. + */ + function makeTempVariableName(flags, reservedInNestedScopes) { + if (flags && !(tempFlags & flags)) { + var name = flags === 268435456 /* _i */ ? "_i" : "_n"; + if (isUniqueName(name)) { + tempFlags |= flags; + if (reservedInNestedScopes) { + reserveNameInNestedScopes(name); + } + return name; + } + } + while (true) { + var count = tempFlags & 268435455 /* CountMask */; + tempFlags++; + // Skip over 'i' and 'n' + if (count !== 8 && count !== 13) { + var name = count < 26 + ? "_" + String.fromCharCode(97 /* a */ + count) + : "_" + (count - 26); + if (isUniqueName(name)) { + if (reservedInNestedScopes) { + reserveNameInNestedScopes(name); + } + return name; + } + } + } + } + /** + * Generate a name that is unique within the current file and doesn't conflict with any names + * in global scope. The name is formed by adding an '_n' suffix to the specified base name, + * where n is a positive integer. Note that names generated by makeTempVariableName and + * makeUniqueName are guaranteed to never conflict. + * If `optimistic` is set, the first instance will use 'baseName' verbatim instead of 'baseName_1' + */ + function makeUniqueName(baseName, checkFn, optimistic, scoped) { + if (checkFn === void 0) { checkFn = isUniqueName; } + if (optimistic) { + if (checkFn(baseName)) { + if (scoped) { + reserveNameInNestedScopes(baseName); + } + else { + generatedNames.set(baseName, true); + } + return baseName; + } + } + // Find the first unique 'name_n', where n is a positive number + if (baseName.charCodeAt(baseName.length - 1) !== 95 /* _ */) { + baseName += "_"; + } + var i = 1; + while (true) { + var generatedName = baseName + i; + if (checkFn(generatedName)) { + if (scoped) { + reserveNameInNestedScopes(generatedName); + } + else { + generatedNames.set(generatedName, true); + } + return generatedName; + } + i++; + } + } + function makeFileLevelOptimisticUniqueName(name) { + return makeUniqueName(name, isFileLevelUniqueName, /*optimistic*/ true); + } + /** + * Generates a unique name for a ModuleDeclaration or EnumDeclaration. + */ + function generateNameForModuleOrEnum(node) { + var name = getTextOfNode(node.name); + // Use module/enum name itself if it is unique, otherwise make a unique variation + return isUniqueLocalName(name, node) ? name : makeUniqueName(name); + } + /** + * Generates a unique name for an ImportDeclaration or ExportDeclaration. + */ + function generateNameForImportOrExportDeclaration(node) { + var expr = ts.getExternalModuleName(node); // TODO: GH#18217 + var baseName = ts.isStringLiteral(expr) ? + ts.makeIdentifierFromModuleName(expr.text) : "module"; + return makeUniqueName(baseName); + } + /** + * Generates a unique name for a default export. + */ + function generateNameForExportDefault() { + return makeUniqueName("default"); + } + /** + * Generates a unique name for a class expression. + */ + function generateNameForClassExpression() { + return makeUniqueName("class"); + } + function generateNameForMethodOrAccessor(node) { + if (ts.isIdentifier(node.name)) { + return generateNameCached(node.name); + } + return makeTempVariableName(0 /* Auto */); + } + /** + * Generates a unique name from a node. + */ + function generateNameForNode(node, flags) { + switch (node.kind) { + case 72 /* Identifier */: + return makeUniqueName(getTextOfNode(node), isUniqueName, !!(flags & 16 /* Optimistic */), !!(flags & 8 /* ReservedInNestedScopes */)); + case 244 /* ModuleDeclaration */: + case 243 /* EnumDeclaration */: + return generateNameForModuleOrEnum(node); + case 249 /* ImportDeclaration */: + case 255 /* ExportDeclaration */: + return generateNameForImportOrExportDeclaration(node); + case 239 /* FunctionDeclaration */: + case 240 /* ClassDeclaration */: + case 254 /* ExportAssignment */: + return generateNameForExportDefault(); + case 209 /* ClassExpression */: + return generateNameForClassExpression(); + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + return generateNameForMethodOrAccessor(node); + default: + return makeTempVariableName(0 /* Auto */); + } + } + /** + * Generates a unique identifier for a node. + */ + function makeName(name) { + switch (name.autoGenerateFlags & 7 /* KindMask */) { + case 1 /* Auto */: + return makeTempVariableName(0 /* Auto */, !!(name.autoGenerateFlags & 8 /* ReservedInNestedScopes */)); + case 2 /* Loop */: + return makeTempVariableName(268435456 /* _i */, !!(name.autoGenerateFlags & 8 /* ReservedInNestedScopes */)); + case 3 /* Unique */: + return makeUniqueName(ts.idText(name), (name.autoGenerateFlags & 32 /* FileLevel */) ? isFileLevelUniqueName : isUniqueName, !!(name.autoGenerateFlags & 16 /* Optimistic */), !!(name.autoGenerateFlags & 8 /* ReservedInNestedScopes */)); + } + return ts.Debug.fail("Unsupported GeneratedIdentifierKind."); + } + /** + * Gets the node from which a name should be generated. + */ + function getNodeForGeneratedName(name) { + var autoGenerateId = name.autoGenerateId; + var node = name; + var original = node.original; + while (original) { + node = original; + // if "node" is a different generated name (having a different + // "autoGenerateId"), use it and stop traversing. + if (ts.isIdentifier(node) + && !!(node.autoGenerateFlags & 4 /* Node */) + && node.autoGenerateId !== autoGenerateId) { + break; + } + original = node.original; + } + // otherwise, return the original node for the source; + return node; + } + // Comments + function pipelineEmitWithComments(hint, node) { + enterComment(); + hasWrittenComment = false; + var emitFlags = ts.getEmitFlags(node); + var _a = ts.getCommentRange(node), pos = _a.pos, end = _a.end; + var isEmittedNode = node.kind !== 307 /* NotEmittedStatement */; + // We have to explicitly check that the node is JsxText because if the compilerOptions.jsx is "preserve" we will not do any transformation. + // It is expensive to walk entire tree just to set one kind of node to have no comments. + var skipLeadingComments = pos < 0 || (emitFlags & 512 /* NoLeadingComments */) !== 0 || node.kind === 11 /* JsxText */; + var skipTrailingComments = end < 0 || (emitFlags & 1024 /* NoTrailingComments */) !== 0 || node.kind === 11 /* JsxText */; + // Save current container state on the stack. + var savedContainerPos = containerPos; + var savedContainerEnd = containerEnd; + var savedDeclarationListContainerEnd = declarationListContainerEnd; + if ((pos > 0 || end > 0) && pos !== end) { + // Emit leading comments if the position is not synthesized and the node + // has not opted out from emitting leading comments. + if (!skipLeadingComments) { + emitLeadingComments(pos, isEmittedNode); + } + if (!skipLeadingComments || (pos >= 0 && (emitFlags & 512 /* NoLeadingComments */) !== 0)) { + // Advance the container position if comments get emitted or if they've been disabled explicitly using NoLeadingComments. + containerPos = pos; + } + if (!skipTrailingComments || (end >= 0 && (emitFlags & 1024 /* NoTrailingComments */) !== 0)) { + // As above. + containerEnd = end; + // To avoid invalid comment emit in a down-level binding pattern, we + // keep track of the last declaration list container's end + if (node.kind === 238 /* VariableDeclarationList */) { + declarationListContainerEnd = end; + } + } + } + ts.forEach(ts.getSyntheticLeadingComments(node), emitLeadingSynthesizedComment); + exitComment(); + var pipelinePhase = getNextPipelinePhase(2 /* Comments */, node); + if (emitFlags & 2048 /* NoNestedComments */) { + commentsDisabled = true; + pipelinePhase(hint, node); + commentsDisabled = false; + } + else { + pipelinePhase(hint, node); + } + enterComment(); + ts.forEach(ts.getSyntheticTrailingComments(node), emitTrailingSynthesizedComment); + if ((pos > 0 || end > 0) && pos !== end) { + // Restore previous container state. + containerPos = savedContainerPos; + containerEnd = savedContainerEnd; + declarationListContainerEnd = savedDeclarationListContainerEnd; + // Emit trailing comments if the position is not synthesized and the node + // has not opted out from emitting leading comments and is an emitted node. + if (!skipTrailingComments && isEmittedNode) { + emitTrailingComments(end); + } + } + exitComment(); + } + function emitLeadingSynthesizedComment(comment) { + if (comment.kind === 2 /* SingleLineCommentTrivia */) { + writer.writeLine(); + } + writeSynthesizedComment(comment); + if (comment.hasTrailingNewLine || comment.kind === 2 /* SingleLineCommentTrivia */) { + writer.writeLine(); + } + else { + writer.writeSpace(" "); + } + } + function emitTrailingSynthesizedComment(comment) { + if (!writer.isAtStartOfLine()) { + writer.writeSpace(" "); + } + writeSynthesizedComment(comment); + if (comment.hasTrailingNewLine) { + writer.writeLine(); + } + } + function writeSynthesizedComment(comment) { + var text = formatSynthesizedComment(comment); + var lineMap = comment.kind === 3 /* MultiLineCommentTrivia */ ? ts.computeLineStarts(text) : undefined; + ts.writeCommentRange(text, lineMap, writer, 0, text.length, newLine); + } + function formatSynthesizedComment(comment) { + return comment.kind === 3 /* MultiLineCommentTrivia */ + ? "/*" + comment.text + "*/" + : "//" + comment.text; + } + function emitBodyWithDetachedComments(node, detachedRange, emitCallback) { + enterComment(); + var pos = detachedRange.pos, end = detachedRange.end; + var emitFlags = ts.getEmitFlags(node); + var skipLeadingComments = pos < 0 || (emitFlags & 512 /* NoLeadingComments */) !== 0; + var skipTrailingComments = commentsDisabled || end < 0 || (emitFlags & 1024 /* NoTrailingComments */) !== 0; + if (!skipLeadingComments) { + emitDetachedCommentsAndUpdateCommentsInfo(detachedRange); + } + exitComment(); + if (emitFlags & 2048 /* NoNestedComments */ && !commentsDisabled) { + commentsDisabled = true; + emitCallback(node); + commentsDisabled = false; + } + else { + emitCallback(node); + } + enterComment(); + if (!skipTrailingComments) { + emitLeadingComments(detachedRange.end, /*isEmittedNode*/ true); + if (hasWrittenComment && !writer.isAtStartOfLine()) { + writer.writeLine(); + } + } + exitComment(); + } + function emitLeadingComments(pos, isEmittedNode) { + hasWrittenComment = false; + if (isEmittedNode) { + forEachLeadingCommentToEmit(pos, emitLeadingComment); + } + else if (pos === 0) { + // If the node will not be emitted in JS, remove all the comments(normal, pinned and ///) associated with the node, + // unless it is a triple slash comment at the top of the file. + // For Example: + // /// + // declare var x; + // /// + // interface F {} + // The first /// will NOT be removed while the second one will be removed even though both node will not be emitted + forEachLeadingCommentToEmit(pos, emitTripleSlashLeadingComment); + } + } + function emitTripleSlashLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos) { + if (isTripleSlashComment(commentPos, commentEnd)) { + emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos); + } + } + function shouldWriteComment(text, pos) { + if (printerOptions.onlyPrintJsDocStyle) { + return (ts.isJSDocLikeText(text, pos) || ts.isPinnedComment(text, pos)); + } + return true; + } + function emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos) { + if (!shouldWriteComment(currentSourceFile.text, commentPos)) + return; + if (!hasWrittenComment) { + ts.emitNewLineBeforeLeadingCommentOfPosition(getCurrentLineMap(), writer, rangePos, commentPos); + hasWrittenComment = true; + } + // Leading comments are emitted at /*leading comment1 */space/*leading comment*/space + emitPos(commentPos); + ts.writeCommentRange(currentSourceFile.text, getCurrentLineMap(), writer, commentPos, commentEnd, newLine); + emitPos(commentEnd); + if (hasTrailingNewLine) { + writer.writeLine(); + } + else if (kind === 3 /* MultiLineCommentTrivia */) { + writer.writeSpace(" "); + } + } + function emitLeadingCommentsOfPosition(pos) { + if (commentsDisabled || pos === -1) { + return; + } + emitLeadingComments(pos, /*isEmittedNode*/ true); + } + function emitTrailingComments(pos) { + forEachTrailingCommentToEmit(pos, emitTrailingComment); + } + function emitTrailingComment(commentPos, commentEnd, _kind, hasTrailingNewLine) { + if (!shouldWriteComment(currentSourceFile.text, commentPos)) + return; + // trailing comments are emitted at space/*trailing comment1 */space/*trailing comment2*/ + if (!writer.isAtStartOfLine()) { + writer.writeSpace(" "); + } + emitPos(commentPos); + ts.writeCommentRange(currentSourceFile.text, getCurrentLineMap(), writer, commentPos, commentEnd, newLine); + emitPos(commentEnd); + if (hasTrailingNewLine) { + writer.writeLine(); + } + } + function emitTrailingCommentsOfPosition(pos, prefixSpace) { + if (commentsDisabled) { + return; + } + enterComment(); + forEachTrailingCommentToEmit(pos, prefixSpace ? emitTrailingComment : emitTrailingCommentOfPosition); + exitComment(); + } + function emitTrailingCommentOfPosition(commentPos, commentEnd, _kind, hasTrailingNewLine) { + // trailing comments of a position are emitted at /*trailing comment1 */space/*trailing comment*/space + emitPos(commentPos); + ts.writeCommentRange(currentSourceFile.text, getCurrentLineMap(), writer, commentPos, commentEnd, newLine); + emitPos(commentEnd); + if (hasTrailingNewLine) { + writer.writeLine(); + } + else { + writer.writeSpace(" "); + } + } + function forEachLeadingCommentToEmit(pos, cb) { + // Emit the leading comments only if the container's pos doesn't match because the container should take care of emitting these comments + if (currentSourceFile && (containerPos === -1 || pos !== containerPos)) { + if (hasDetachedComments(pos)) { + forEachLeadingCommentWithoutDetachedComments(cb); + } + else { + ts.forEachLeadingCommentRange(currentSourceFile.text, pos, cb, /*state*/ pos); + } + } + } + function forEachTrailingCommentToEmit(end, cb) { + // Emit the trailing comments only if the container's end doesn't match because the container should take care of emitting these comments + if (currentSourceFile && (containerEnd === -1 || (end !== containerEnd && end !== declarationListContainerEnd))) { + ts.forEachTrailingCommentRange(currentSourceFile.text, end, cb); + } + } + function hasDetachedComments(pos) { + return detachedCommentsInfo !== undefined && ts.last(detachedCommentsInfo).nodePos === pos; + } + function forEachLeadingCommentWithoutDetachedComments(cb) { + // get the leading comments from detachedPos + var pos = ts.last(detachedCommentsInfo).detachedCommentEndPos; + if (detachedCommentsInfo.length - 1) { + detachedCommentsInfo.pop(); + } + else { + detachedCommentsInfo = undefined; + } + ts.forEachLeadingCommentRange(currentSourceFile.text, pos, cb, /*state*/ pos); + } + function emitDetachedCommentsAndUpdateCommentsInfo(range) { + var currentDetachedCommentInfo = ts.emitDetachedComments(currentSourceFile.text, getCurrentLineMap(), writer, emitComment, range, newLine, commentsDisabled); + if (currentDetachedCommentInfo) { + if (detachedCommentsInfo) { + detachedCommentsInfo.push(currentDetachedCommentInfo); + } + else { + detachedCommentsInfo = [currentDetachedCommentInfo]; + } + } + } + function emitComment(text, lineMap, writer, commentPos, commentEnd, newLine) { + if (!shouldWriteComment(currentSourceFile.text, commentPos)) + return; + emitPos(commentPos); + ts.writeCommentRange(text, lineMap, writer, commentPos, commentEnd, newLine); + emitPos(commentEnd); + } + /** + * Determine if the given comment is a triple-slash + * + * @return true if the comment is a triple-slash comment else false + */ + function isTripleSlashComment(commentPos, commentEnd) { + return ts.isRecognizedTripleSlashComment(currentSourceFile.text, commentPos, commentEnd); + } + // Source Maps + function pipelineEmitWithSourceMap(hint, node) { + var pipelinePhase = getNextPipelinePhase(3 /* SourceMaps */, node); + if (ts.isUnparsedSource(node) && node.sourceMapText !== undefined) { + var parsed = ts.tryParseRawSourceMap(node.sourceMapText); + if (parsed) { + sourceMapGenerator.appendSourceMap(writer.getLine(), writer.getColumn(), parsed, node.sourceMapPath); + } + pipelinePhase(hint, node); + } + else { + var _a = ts.getSourceMapRange(node), pos = _a.pos, end = _a.end, _b = _a.source, source = _b === void 0 ? sourceMapSource : _b; + var emitFlags = ts.getEmitFlags(node); + if (node.kind !== 307 /* NotEmittedStatement */ + && (emitFlags & 16 /* NoLeadingSourceMap */) === 0 + && pos >= 0) { + emitSourcePos(source, skipSourceTrivia(source, pos)); + } + if (emitFlags & 64 /* NoNestedSourceMaps */) { + sourceMapsDisabled = true; + pipelinePhase(hint, node); + sourceMapsDisabled = false; + } + else { + pipelinePhase(hint, node); + } + if (node.kind !== 307 /* NotEmittedStatement */ + && (emitFlags & 32 /* NoTrailingSourceMap */) === 0 + && end >= 0) { + emitSourcePos(source, end); + } + } + } + /** + * Skips trivia such as comments and white-space that can optionally overriden by the source map source + */ + function skipSourceTrivia(source, pos) { + return source.skipTrivia ? source.skipTrivia(pos) : ts.skipTrivia(sourceMapSource.text, pos); + } + /** + * Emits a mapping. + * + * If the position is synthetic (undefined or a negative value), no mapping will be + * created. + * + * @param pos The position. + */ + function emitPos(pos) { + if (sourceMapsDisabled || ts.positionIsSynthesized(pos) || isJsonSourceMapSource(sourceMapSource)) { + return; + } + var _a = ts.getLineAndCharacterOfPosition(currentSourceFile, pos), sourceLine = _a.line, sourceCharacter = _a.character; + sourceMapGenerator.addMapping(writer.getLine(), writer.getColumn(), sourceMapSourceIndex, sourceLine, sourceCharacter, + /*nameIndex*/ undefined); + } + function emitSourcePos(source, pos) { + if (source !== sourceMapSource) { + var savedSourceMapSource = sourceMapSource; + setSourceMapSource(source); + emitPos(pos); + setSourceMapSource(savedSourceMapSource); + } + else { + emitPos(pos); + } + } + /** + * Emits a token of a node with possible leading and trailing source maps. + * + * @param node The node containing the token. + * @param token The token to emit. + * @param tokenStartPos The start pos of the token. + * @param emitCallback The callback used to emit the token. + */ + function emitTokenWithSourceMap(node, token, writer, tokenPos, emitCallback) { + if (sourceMapsDisabled || node && ts.isInJsonFile(node)) { + return emitCallback(token, writer, tokenPos); + } + var emitNode = node && node.emitNode; + var emitFlags = emitNode && emitNode.flags || 0 /* None */; + var range = emitNode && emitNode.tokenSourceMapRanges && emitNode.tokenSourceMapRanges[token]; + var source = range && range.source || sourceMapSource; + tokenPos = skipSourceTrivia(source, range ? range.pos : tokenPos); + if ((emitFlags & 128 /* NoTokenLeadingSourceMaps */) === 0 && tokenPos >= 0) { + emitSourcePos(source, tokenPos); + } + tokenPos = emitCallback(token, writer, tokenPos); + if (range) + tokenPos = range.end; + if ((emitFlags & 256 /* NoTokenTrailingSourceMaps */) === 0 && tokenPos >= 0) { + emitSourcePos(source, tokenPos); + } + return tokenPos; + } + function setSourceMapSource(source) { + if (sourceMapsDisabled) { + return; + } + sourceMapSource = source; + if (isJsonSourceMapSource(source)) { + return; + } + sourceMapSourceIndex = sourceMapGenerator.addSource(source.fileName); + if (printerOptions.inlineSources) { + sourceMapGenerator.setSourceContent(sourceMapSourceIndex, source.text); + } + } + function isJsonSourceMapSource(sourceFile) { + return ts.fileExtensionIs(sourceFile.fileName, ".json" /* Json */); + } + } + ts.createPrinter = createPrinter; + function createBracketsMap() { + var brackets = []; + brackets[1024 /* Braces */] = ["{", "}"]; + brackets[2048 /* Parenthesis */] = ["(", ")"]; + brackets[4096 /* AngleBrackets */] = ["<", ">"]; + brackets[8192 /* SquareBrackets */] = ["[", "]"]; + return brackets; + } + function getOpeningBracket(format) { + return brackets[format & 15360 /* BracketsMask */][0]; + } + function getClosingBracket(format) { + return brackets[format & 15360 /* BracketsMask */][1]; + } + // Flags enum to track count of temp variables and a few dedicated names + var TempFlags; + (function (TempFlags) { + TempFlags[TempFlags["Auto"] = 0] = "Auto"; + TempFlags[TempFlags["CountMask"] = 268435455] = "CountMask"; + TempFlags[TempFlags["_i"] = 268435456] = "_i"; + })(TempFlags || (TempFlags = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + function createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensitiveFileNames) { + if (!host.getDirectories || !host.readDirectory) { + return undefined; + } + var cachedReadDirectoryResult = ts.createMap(); + var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); + return { + useCaseSensitiveFileNames: useCaseSensitiveFileNames, + fileExists: fileExists, + readFile: function (path, encoding) { return host.readFile(path, encoding); }, + directoryExists: host.directoryExists && directoryExists, + getDirectories: getDirectories, + readDirectory: readDirectory, + createDirectory: host.createDirectory && createDirectory, + writeFile: host.writeFile && writeFile, + addOrDeleteFileOrDirectory: addOrDeleteFileOrDirectory, + addOrDeleteFile: addOrDeleteFile, + clearCache: clearCache + }; + function toPath(fileName) { + return ts.toPath(fileName, currentDirectory, getCanonicalFileName); + } + function getCachedFileSystemEntries(rootDirPath) { + return cachedReadDirectoryResult.get(ts.ensureTrailingDirectorySeparator(rootDirPath)); + } + function getCachedFileSystemEntriesForBaseDir(path) { + return getCachedFileSystemEntries(ts.getDirectoryPath(path)); + } + function getBaseNameOfFileName(fileName) { + return ts.getBaseFileName(ts.normalizePath(fileName)); + } + function createCachedFileSystemEntries(rootDir, rootDirPath) { + var resultFromHost = { + files: ts.map(host.readDirectory(rootDir, /*extensions*/ undefined, /*exclude*/ undefined, /*include*/ ["*.*"]), getBaseNameOfFileName) || [], + directories: host.getDirectories(rootDir) || [] + }; + cachedReadDirectoryResult.set(ts.ensureTrailingDirectorySeparator(rootDirPath), resultFromHost); + return resultFromHost; + } + /** + * If the readDirectory result was already cached, it returns that + * Otherwise gets result from host and caches it. + * The host request is done under try catch block to avoid caching incorrect result + */ + function tryReadDirectory(rootDir, rootDirPath) { + rootDirPath = ts.ensureTrailingDirectorySeparator(rootDirPath); + var cachedResult = getCachedFileSystemEntries(rootDirPath); + if (cachedResult) { + return cachedResult; + } + try { + return createCachedFileSystemEntries(rootDir, rootDirPath); + } + catch (_e) { + // If there is exception to read directories, dont cache the result and direct the calls to host + ts.Debug.assert(!cachedReadDirectoryResult.has(ts.ensureTrailingDirectorySeparator(rootDirPath))); + return undefined; + } + } + function fileNameEqual(name1, name2) { + return getCanonicalFileName(name1) === getCanonicalFileName(name2); + } + function hasEntry(entries, name) { + return ts.some(entries, function (file) { return fileNameEqual(file, name); }); + } + function updateFileSystemEntry(entries, baseName, isValid) { + if (hasEntry(entries, baseName)) { + if (!isValid) { + return ts.filterMutate(entries, function (entry) { return !fileNameEqual(entry, baseName); }); + } + } + else if (isValid) { + return entries.push(baseName); + } + } + function writeFile(fileName, data, writeByteOrderMark) { + var path = toPath(fileName); + var result = getCachedFileSystemEntriesForBaseDir(path); + if (result) { + updateFilesOfFileSystemEntry(result, getBaseNameOfFileName(fileName), /*fileExists*/ true); + } + return host.writeFile(fileName, data, writeByteOrderMark); + } + function fileExists(fileName) { + var path = toPath(fileName); + var result = getCachedFileSystemEntriesForBaseDir(path); + return result && hasEntry(result.files, getBaseNameOfFileName(fileName)) || + host.fileExists(fileName); + } + function directoryExists(dirPath) { + var path = toPath(dirPath); + return cachedReadDirectoryResult.has(ts.ensureTrailingDirectorySeparator(path)) || host.directoryExists(dirPath); + } + function createDirectory(dirPath) { + var path = toPath(dirPath); + var result = getCachedFileSystemEntriesForBaseDir(path); + var baseFileName = getBaseNameOfFileName(dirPath); + if (result) { + updateFileSystemEntry(result.directories, baseFileName, /*isValid*/ true); + } + host.createDirectory(dirPath); + } + function getDirectories(rootDir) { + var rootDirPath = toPath(rootDir); + var result = tryReadDirectory(rootDir, rootDirPath); + if (result) { + return result.directories.slice(); + } + return host.getDirectories(rootDir); + } + function readDirectory(rootDir, extensions, excludes, includes, depth) { + var rootDirPath = toPath(rootDir); + var result = tryReadDirectory(rootDir, rootDirPath); + if (result) { + return ts.matchFiles(rootDir, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries); + } + return host.readDirectory(rootDir, extensions, excludes, includes, depth); + function getFileSystemEntries(dir) { + var path = toPath(dir); + if (path === rootDirPath) { + return result; + } + return tryReadDirectory(dir, path) || ts.emptyFileSystemEntries; + } + } + function addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath) { + var existingResult = getCachedFileSystemEntries(fileOrDirectoryPath); + if (existingResult) { + // Just clear the cache for now + // For now just clear the cache, since this could mean that multiple level entries might need to be re-evaluated + clearCache(); + return undefined; + } + var parentResult = getCachedFileSystemEntriesForBaseDir(fileOrDirectoryPath); + if (!parentResult) { + return undefined; + } + // This was earlier a file (hence not in cached directory contents) + // or we never cached the directory containing it + if (!host.directoryExists) { + // Since host doesnt support directory exists, clear the cache as otherwise it might not be same + clearCache(); + return undefined; + } + var baseName = getBaseNameOfFileName(fileOrDirectory); + var fsQueryResult = { + fileExists: host.fileExists(fileOrDirectoryPath), + directoryExists: host.directoryExists(fileOrDirectoryPath) + }; + if (fsQueryResult.directoryExists || hasEntry(parentResult.directories, baseName)) { + // Folder added or removed, clear the cache instead of updating the folder and its structure + clearCache(); + } + else { + // No need to update the directory structure, just files + updateFilesOfFileSystemEntry(parentResult, baseName, fsQueryResult.fileExists); + } + return fsQueryResult; + } + function addOrDeleteFile(fileName, filePath, eventKind) { + if (eventKind === ts.FileWatcherEventKind.Changed) { + return; + } + var parentResult = getCachedFileSystemEntriesForBaseDir(filePath); + if (parentResult) { + updateFilesOfFileSystemEntry(parentResult, getBaseNameOfFileName(fileName), eventKind === ts.FileWatcherEventKind.Created); + } + } + function updateFilesOfFileSystemEntry(parentResult, baseName, fileExists) { + updateFileSystemEntry(parentResult.files, baseName, fileExists); + } + function clearCache() { + cachedReadDirectoryResult.clear(); + } + } + ts.createCachedDirectoryStructureHost = createCachedDirectoryStructureHost; + var ConfigFileProgramReloadLevel; + (function (ConfigFileProgramReloadLevel) { + ConfigFileProgramReloadLevel[ConfigFileProgramReloadLevel["None"] = 0] = "None"; + /** Update the file name list from the disk */ + ConfigFileProgramReloadLevel[ConfigFileProgramReloadLevel["Partial"] = 1] = "Partial"; + /** Reload completely by re-reading contents of config file from disk and updating program */ + ConfigFileProgramReloadLevel[ConfigFileProgramReloadLevel["Full"] = 2] = "Full"; + })(ConfigFileProgramReloadLevel = ts.ConfigFileProgramReloadLevel || (ts.ConfigFileProgramReloadLevel = {})); + /** + * Updates the existing missing file watches with the new set of missing files after new program is created + */ + function updateMissingFilePathsWatch(program, missingFileWatches, createMissingFileWatch) { + var missingFilePaths = program.getMissingFilePaths(); + var newMissingFilePathMap = ts.arrayToSet(missingFilePaths); + // Update the missing file paths watcher + ts.mutateMap(missingFileWatches, newMissingFilePathMap, { + // Watch the missing files + createNewValue: createMissingFileWatch, + // Files that are no longer missing (e.g. because they are no longer required) + // should no longer be watched. + onDeleteValue: ts.closeFileWatcher + }); + } + ts.updateMissingFilePathsWatch = updateMissingFilePathsWatch; + /** + * Updates the existing wild card directory watches with the new set of wild card directories from the config file + * after new program is created because the config file was reloaded or program was created first time from the config file + * Note that there is no need to call this function when the program is updated with additional files without reloading config files, + * as wildcard directories wont change unless reloading config file + */ + function updateWatchingWildcardDirectories(existingWatchedForWildcards, wildcardDirectories, watchDirectory) { + ts.mutateMap(existingWatchedForWildcards, wildcardDirectories, { + // Create new watch and recursive info + createNewValue: createWildcardDirectoryWatcher, + // Close existing watch thats not needed any more + onDeleteValue: closeFileWatcherOf, + // Close existing watch that doesnt match in the flags + onExistingValue: updateWildcardDirectoryWatcher + }); + function createWildcardDirectoryWatcher(directory, flags) { + // Create new watch and recursive info + return { + watcher: watchDirectory(directory, flags), + flags: flags + }; + } + function updateWildcardDirectoryWatcher(existingWatcher, flags, directory) { + // Watcher needs to be updated if the recursive flags dont match + if (existingWatcher.flags === flags) { + return; + } + existingWatcher.watcher.close(); + existingWatchedForWildcards.set(directory, createWildcardDirectoryWatcher(directory, flags)); + } + } + ts.updateWatchingWildcardDirectories = updateWatchingWildcardDirectories; + function isEmittedFileOfProgram(program, file) { + if (!program) { + return false; + } + return program.isEmittedFile(file); + } + ts.isEmittedFileOfProgram = isEmittedFileOfProgram; + var WatchLogLevel; + (function (WatchLogLevel) { + WatchLogLevel[WatchLogLevel["None"] = 0] = "None"; + WatchLogLevel[WatchLogLevel["TriggerOnly"] = 1] = "TriggerOnly"; + WatchLogLevel[WatchLogLevel["Verbose"] = 2] = "Verbose"; + })(WatchLogLevel = ts.WatchLogLevel || (ts.WatchLogLevel = {})); + function getWatchFactory(watchLogLevel, log, getDetailWatchInfo) { + return getWatchFactoryWith(watchLogLevel, log, getDetailWatchInfo, watchFile, watchDirectory); + } + ts.getWatchFactory = getWatchFactory; + function getWatchFactoryWith(watchLogLevel, log, getDetailWatchInfo, watchFile, watchDirectory) { + var createFileWatcher = getCreateFileWatcher(watchLogLevel, watchFile); + var createFilePathWatcher = watchLogLevel === WatchLogLevel.None ? watchFilePath : createFileWatcher; + var createDirectoryWatcher = getCreateFileWatcher(watchLogLevel, watchDirectory); + return { + watchFile: function (host, file, callback, pollingInterval, detailInfo1, detailInfo2) { + return createFileWatcher(host, file, callback, pollingInterval, /*passThrough*/ undefined, detailInfo1, detailInfo2, watchFile, log, "FileWatcher", getDetailWatchInfo); + }, + watchFilePath: function (host, file, callback, pollingInterval, path, detailInfo1, detailInfo2) { + return createFilePathWatcher(host, file, callback, pollingInterval, path, detailInfo1, detailInfo2, watchFile, log, "FileWatcher", getDetailWatchInfo); + }, + watchDirectory: function (host, directory, callback, flags, detailInfo1, detailInfo2) { + return createDirectoryWatcher(host, directory, callback, flags, /*passThrough*/ undefined, detailInfo1, detailInfo2, watchDirectory, log, "DirectoryWatcher", getDetailWatchInfo); + } + }; + function watchFilePath(host, file, callback, pollingInterval, path) { + return watchFile(host, file, function (fileName, eventKind) { return callback(fileName, eventKind, path); }, pollingInterval); + } + } + function watchFile(host, file, callback, pollingInterval) { + return host.watchFile(file, callback, pollingInterval); + } + function watchDirectory(host, directory, callback, flags) { + return host.watchDirectory(directory, callback, (flags & 1 /* Recursive */) !== 0); + } + function getCreateFileWatcher(watchLogLevel, addWatch) { + switch (watchLogLevel) { + case WatchLogLevel.None: + return addWatch; + case WatchLogLevel.TriggerOnly: + return createFileWatcherWithTriggerLogging; + case WatchLogLevel.Verbose: + return addWatch === watchDirectory ? createDirectoryWatcherWithLogging : createFileWatcherWithLogging; + } + } + function createFileWatcherWithLogging(host, file, cb, flags, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo) { + log(watchCaption + ":: Added:: " + getWatchInfo(file, flags, detailInfo1, detailInfo2, getDetailWatchInfo)); + var watcher = createFileWatcherWithTriggerLogging(host, file, cb, flags, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo); + return { + close: function () { + log(watchCaption + ":: Close:: " + getWatchInfo(file, flags, detailInfo1, detailInfo2, getDetailWatchInfo)); + watcher.close(); + } + }; + } + function createDirectoryWatcherWithLogging(host, file, cb, flags, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo) { + var watchInfo = watchCaption + ":: Added:: " + getWatchInfo(file, flags, detailInfo1, detailInfo2, getDetailWatchInfo); + log(watchInfo); + var start = ts.timestamp(); + var watcher = createFileWatcherWithTriggerLogging(host, file, cb, flags, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo); + var elapsed = ts.timestamp() - start; + log("Elapsed:: " + elapsed + "ms " + watchInfo); + return { + close: function () { + var watchInfo = watchCaption + ":: Close:: " + getWatchInfo(file, flags, detailInfo1, detailInfo2, getDetailWatchInfo); + log(watchInfo); + var start = ts.timestamp(); + watcher.close(); + var elapsed = ts.timestamp() - start; + log("Elapsed:: " + elapsed + "ms " + watchInfo); + } + }; + } + function createFileWatcherWithTriggerLogging(host, file, cb, flags, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo) { + return addWatch(host, file, function (fileName, cbOptional) { + var triggerredInfo = watchCaption + ":: Triggered with " + fileName + " " + (cbOptional !== undefined ? cbOptional : "") + ":: " + getWatchInfo(file, flags, detailInfo1, detailInfo2, getDetailWatchInfo); + log(triggerredInfo); + var start = ts.timestamp(); + cb(fileName, cbOptional, passThrough); + var elapsed = ts.timestamp() - start; + log("Elapsed:: " + elapsed + "ms " + triggerredInfo); + }, flags); + } + function getWatchInfo(file, flags, detailInfo1, detailInfo2, getDetailWatchInfo) { + return "WatchInfo: " + file + " " + flags + " " + (getDetailWatchInfo ? getDetailWatchInfo(detailInfo1, detailInfo2) : detailInfo1); + } + function closeFileWatcherOf(objWithWatcher) { + objWithWatcher.watcher.close(); + } + ts.closeFileWatcherOf = closeFileWatcherOf; +})(ts || (ts = {})); +var ts; +(function (ts) { + var ignoreDiagnosticCommentRegEx = /(^\s*$)|(^\s*\/\/\/?\s*(@ts-ignore)?)/; + function findConfigFile(searchPath, fileExists, configName) { + if (configName === void 0) { configName = "tsconfig.json"; } + return ts.forEachAncestorDirectory(searchPath, function (ancestor) { + var fileName = ts.combinePaths(ancestor, configName); + return fileExists(fileName) ? fileName : undefined; + }); + } + ts.findConfigFile = findConfigFile; + function resolveTripleslashReference(moduleName, containingFile) { + var basePath = ts.getDirectoryPath(containingFile); + var referencedFileName = ts.isRootedDiskPath(moduleName) ? moduleName : ts.combinePaths(basePath, moduleName); + return ts.normalizePath(referencedFileName); + } + ts.resolveTripleslashReference = resolveTripleslashReference; + /* @internal */ + function computeCommonSourceDirectoryOfFilenames(fileNames, currentDirectory, getCanonicalFileName) { + var commonPathComponents; + var failed = ts.forEach(fileNames, function (sourceFile) { + // Each file contributes into common source file path + var sourcePathComponents = ts.getNormalizedPathComponents(sourceFile, currentDirectory); + sourcePathComponents.pop(); // The base file name is not part of the common directory path + if (!commonPathComponents) { + // first file + commonPathComponents = sourcePathComponents; + return; + } + var n = Math.min(commonPathComponents.length, sourcePathComponents.length); + for (var i = 0; i < n; i++) { + if (getCanonicalFileName(commonPathComponents[i]) !== getCanonicalFileName(sourcePathComponents[i])) { + if (i === 0) { + // Failed to find any common path component + return true; + } + // New common path found that is 0 -> i-1 + commonPathComponents.length = i; + break; + } + } + // If the sourcePathComponents was shorter than the commonPathComponents, truncate to the sourcePathComponents + if (sourcePathComponents.length < commonPathComponents.length) { + commonPathComponents.length = sourcePathComponents.length; + } + }); + // A common path can not be found when paths span multiple drives on windows, for example + if (failed) { + return ""; + } + if (!commonPathComponents) { // Can happen when all input files are .d.ts files + return currentDirectory; + } + return ts.getPathFromPathComponents(commonPathComponents); + } + ts.computeCommonSourceDirectoryOfFilenames = computeCommonSourceDirectoryOfFilenames; + function createCompilerHost(options, setParentNodes) { + return createCompilerHostWorker(options, setParentNodes); + } + ts.createCompilerHost = createCompilerHost; + /*@internal*/ + // TODO(shkamat): update this after reworking ts build API + function createCompilerHostWorker(options, setParentNodes, system) { + if (system === void 0) { system = ts.sys; } + var existingDirectories = ts.createMap(); + function getCanonicalFileName(fileName) { + // if underlying system can distinguish between two files whose names differs only in cases then file name already in canonical form. + // otherwise use toLowerCase as a canonical form. + return system.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); + } + function getSourceFile(fileName, languageVersion, onError) { + var text; + try { + ts.performance.mark("beforeIORead"); + text = compilerHost.readFile(fileName); + ts.performance.mark("afterIORead"); + ts.performance.measure("I/O Read", "beforeIORead", "afterIORead"); + } + catch (e) { + if (onError) { + onError(e.message); + } + text = ""; + } + return text !== undefined ? ts.createSourceFile(fileName, text, languageVersion, setParentNodes) : undefined; + } + function directoryExists(directoryPath) { + if (existingDirectories.has(directoryPath)) { + return true; + } + if (system.directoryExists(directoryPath)) { + existingDirectories.set(directoryPath, true); + return true; + } + return false; + } + function ensureDirectoriesExist(directoryPath) { + if (directoryPath.length > ts.getRootLength(directoryPath) && !directoryExists(directoryPath)) { + var parentDirectory = ts.getDirectoryPath(directoryPath); + ensureDirectoriesExist(parentDirectory); + if (compilerHost.createDirectory) { + compilerHost.createDirectory(directoryPath); + } + else { + system.createDirectory(directoryPath); + } + } + } + var outputFingerprints; + function writeFileIfUpdated(fileName, data, writeByteOrderMark) { + if (!outputFingerprints) { + outputFingerprints = ts.createMap(); + } + var hash = system.createHash(data); // TODO: GH#18217 + var mtimeBefore = system.getModifiedTime(fileName); // TODO: GH#18217 + if (mtimeBefore) { + var fingerprint = outputFingerprints.get(fileName); + // If output has not been changed, and the file has no external modification + if (fingerprint && + fingerprint.byteOrderMark === writeByteOrderMark && + fingerprint.hash === hash && + fingerprint.mtime.getTime() === mtimeBefore.getTime()) { + return; + } + } + system.writeFile(fileName, data, writeByteOrderMark); + var mtimeAfter = system.getModifiedTime(fileName) || ts.missingFileModifiedTime; // TODO: GH#18217 + outputFingerprints.set(fileName, { + hash: hash, + byteOrderMark: writeByteOrderMark, + mtime: mtimeAfter + }); + } + function writeFile(fileName, data, writeByteOrderMark, onError) { + try { + ts.performance.mark("beforeIOWrite"); + ensureDirectoriesExist(ts.getDirectoryPath(ts.normalizePath(fileName))); + if (ts.isWatchSet(options) && system.createHash && system.getModifiedTime) { + writeFileIfUpdated(fileName, data, writeByteOrderMark); + } + else { + system.writeFile(fileName, data, writeByteOrderMark); + } + ts.performance.mark("afterIOWrite"); + ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite"); + } + catch (e) { + if (onError) { + onError(e.message); + } + } + } + function getDefaultLibLocation() { + return ts.getDirectoryPath(ts.normalizePath(system.getExecutingFilePath())); + } + var newLine = ts.getNewLineCharacter(options, function () { return system.newLine; }); + var realpath = system.realpath && (function (path) { return system.realpath(path); }); + var compilerHost = { + getSourceFile: getSourceFile, + getDefaultLibLocation: getDefaultLibLocation, + getDefaultLibFileName: function (options) { return ts.combinePaths(getDefaultLibLocation(), ts.getDefaultLibFileName(options)); }, + writeFile: writeFile, + getCurrentDirectory: ts.memoize(function () { return system.getCurrentDirectory(); }), + useCaseSensitiveFileNames: function () { return system.useCaseSensitiveFileNames; }, + getCanonicalFileName: getCanonicalFileName, + getNewLine: function () { return newLine; }, + fileExists: function (fileName) { return system.fileExists(fileName); }, + readFile: function (fileName) { return system.readFile(fileName); }, + trace: function (s) { return system.write(s + newLine); }, + directoryExists: function (directoryName) { return system.directoryExists(directoryName); }, + getEnvironmentVariable: function (name) { return system.getEnvironmentVariable ? system.getEnvironmentVariable(name) : ""; }, + getDirectories: function (path) { return system.getDirectories(path); }, + realpath: realpath, + readDirectory: function (path, extensions, include, exclude, depth) { return system.readDirectory(path, extensions, include, exclude, depth); }, + createDirectory: function (d) { return system.createDirectory(d); } + }; + return compilerHost; + } + ts.createCompilerHostWorker = createCompilerHostWorker; + /*@internal*/ + function changeCompilerHostToUseCache(host, toPath, useCacheForSourceFile) { + var originalReadFile = host.readFile; + var originalFileExists = host.fileExists; + var originalDirectoryExists = host.directoryExists; + var originalCreateDirectory = host.createDirectory; + var originalWriteFile = host.writeFile; + var originalGetSourceFile = host.getSourceFile; + var readFileCache = ts.createMap(); + var fileExistsCache = ts.createMap(); + var directoryExistsCache = ts.createMap(); + var sourceFileCache = ts.createMap(); + var readFileWithCache = function (fileName) { + var key = toPath(fileName); + var value = readFileCache.get(key); + if (value !== undefined) + return value || undefined; + return setReadFileCache(key, fileName); + }; + var setReadFileCache = function (key, fileName) { + var newValue = originalReadFile.call(host, fileName); + readFileCache.set(key, newValue || false); + return newValue; + }; + host.readFile = function (fileName) { + var key = toPath(fileName); + var value = readFileCache.get(key); + if (value !== undefined) + return value; // could be .d.ts from output + if (!ts.fileExtensionIs(fileName, ".json" /* Json */)) { + return originalReadFile.call(host, fileName); + } + return setReadFileCache(key, fileName); + }; + if (useCacheForSourceFile) { + host.getSourceFile = function (fileName, languageVersion, onError, shouldCreateNewSourceFile) { + var key = toPath(fileName); + var value = sourceFileCache.get(key); + if (value) + return value; + var sourceFile = originalGetSourceFile.call(host, fileName, languageVersion, onError, shouldCreateNewSourceFile); + if (sourceFile && (ts.isDeclarationFileName(fileName) || ts.fileExtensionIs(fileName, ".json" /* Json */))) { + sourceFileCache.set(key, sourceFile); + } + return sourceFile; + }; + } + // fileExists for any kind of extension + host.fileExists = function (fileName) { + var key = toPath(fileName); + var value = fileExistsCache.get(key); + if (value !== undefined) + return value; + var newValue = originalFileExists.call(host, fileName); + fileExistsCache.set(key, !!newValue); + return newValue; + }; + host.writeFile = function (fileName, data, writeByteOrderMark, onError, sourceFiles) { + var key = toPath(fileName); + fileExistsCache.delete(key); + var value = readFileCache.get(key); + if (value && value !== data) { + readFileCache.delete(key); + sourceFileCache.delete(key); + } + else if (useCacheForSourceFile) { + var sourceFile = sourceFileCache.get(key); + if (sourceFile && sourceFile.text !== data) { + sourceFileCache.delete(key); + } + } + originalWriteFile.call(host, fileName, data, writeByteOrderMark, onError, sourceFiles); + }; + // directoryExists + if (originalDirectoryExists && originalCreateDirectory) { + host.directoryExists = function (directory) { + var key = toPath(directory); + var value = directoryExistsCache.get(key); + if (value !== undefined) + return value; + var newValue = originalDirectoryExists.call(host, directory); + directoryExistsCache.set(key, !!newValue); + return newValue; + }; + host.createDirectory = function (directory) { + var key = toPath(directory); + directoryExistsCache.delete(key); + originalCreateDirectory.call(host, directory); + }; + } + return { + originalReadFile: originalReadFile, + originalFileExists: originalFileExists, + originalDirectoryExists: originalDirectoryExists, + originalCreateDirectory: originalCreateDirectory, + originalWriteFile: originalWriteFile, + originalGetSourceFile: originalGetSourceFile, + readFileWithCache: readFileWithCache + }; + } + ts.changeCompilerHostToUseCache = changeCompilerHostToUseCache; + function getPreEmitDiagnostics(program, sourceFile, cancellationToken) { + var diagnostics = program.getConfigFileParsingDiagnostics().concat(program.getOptionsDiagnostics(cancellationToken), program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken)); + if (ts.getEmitDeclarations(program.getCompilerOptions())) { + ts.addRange(diagnostics, program.getDeclarationDiagnostics(sourceFile, cancellationToken)); + } + return ts.sortAndDeduplicateDiagnostics(diagnostics); + } + ts.getPreEmitDiagnostics = getPreEmitDiagnostics; + function formatDiagnostics(diagnostics, host) { + var output = ""; + for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { + var diagnostic = diagnostics_2[_i]; + output += formatDiagnostic(diagnostic, host); + } + return output; + } + ts.formatDiagnostics = formatDiagnostics; + function formatDiagnostic(diagnostic, host) { + var errorMessage = ts.diagnosticCategoryName(diagnostic) + " TS" + diagnostic.code + ": " + flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine()) + host.getNewLine(); + if (diagnostic.file) { + var _a = ts.getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start), line = _a.line, character = _a.character; // TODO: GH#18217 + var fileName = diagnostic.file.fileName; + var relativeFileName = ts.convertToRelativePath(fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); }); + return relativeFileName + "(" + (line + 1) + "," + (character + 1) + "): " + errorMessage; + } + return errorMessage; + } + ts.formatDiagnostic = formatDiagnostic; + /** @internal */ + var ForegroundColorEscapeSequences; + (function (ForegroundColorEscapeSequences) { + ForegroundColorEscapeSequences["Grey"] = "\u001B[90m"; + ForegroundColorEscapeSequences["Red"] = "\u001B[91m"; + ForegroundColorEscapeSequences["Yellow"] = "\u001B[93m"; + ForegroundColorEscapeSequences["Blue"] = "\u001B[94m"; + ForegroundColorEscapeSequences["Cyan"] = "\u001B[96m"; + })(ForegroundColorEscapeSequences = ts.ForegroundColorEscapeSequences || (ts.ForegroundColorEscapeSequences = {})); + var gutterStyleSequence = "\u001b[7m"; + var gutterSeparator = " "; + var resetEscapeSequence = "\u001b[0m"; + var ellipsis = "..."; + var halfIndent = " "; + var indent = " "; + function getCategoryFormat(category) { + switch (category) { + case ts.DiagnosticCategory.Error: return ForegroundColorEscapeSequences.Red; + case ts.DiagnosticCategory.Warning: return ForegroundColorEscapeSequences.Yellow; + case ts.DiagnosticCategory.Suggestion: return ts.Debug.fail("Should never get an Info diagnostic on the command line."); + case ts.DiagnosticCategory.Message: return ForegroundColorEscapeSequences.Blue; + } + } + /** @internal */ + function formatColorAndReset(text, formatStyle) { + return formatStyle + text + resetEscapeSequence; + } + ts.formatColorAndReset = formatColorAndReset; + function padLeft(s, length) { + while (s.length < length) { + s = " " + s; + } + return s; + } + function formatCodeSpan(file, start, length, indent, squiggleColor, host) { + var _a = ts.getLineAndCharacterOfPosition(file, start), firstLine = _a.line, firstLineChar = _a.character; + var _b = ts.getLineAndCharacterOfPosition(file, start + length), lastLine = _b.line, lastLineChar = _b.character; + var lastLineInFile = ts.getLineAndCharacterOfPosition(file, file.text.length).line; + var hasMoreThanFiveLines = (lastLine - firstLine) >= 4; + var gutterWidth = (lastLine + 1 + "").length; + if (hasMoreThanFiveLines) { + gutterWidth = Math.max(ellipsis.length, gutterWidth); + } + var context = ""; + for (var i = firstLine; i <= lastLine; i++) { + context += host.getNewLine(); + // If the error spans over 5 lines, we'll only show the first 2 and last 2 lines, + // so we'll skip ahead to the second-to-last line. + if (hasMoreThanFiveLines && firstLine + 1 < i && i < lastLine - 1) { + context += indent + formatColorAndReset(padLeft(ellipsis, gutterWidth), gutterStyleSequence) + gutterSeparator + host.getNewLine(); + i = lastLine - 1; + } + var lineStart = ts.getPositionOfLineAndCharacter(file, i, 0); + var lineEnd = i < lastLineInFile ? ts.getPositionOfLineAndCharacter(file, i + 1, 0) : file.text.length; + var lineContent = file.text.slice(lineStart, lineEnd); + lineContent = lineContent.replace(/\s+$/g, ""); // trim from end + lineContent = lineContent.replace("\t", " "); // convert tabs to single spaces + // Output the gutter and the actual contents of the line. + context += indent + formatColorAndReset(padLeft(i + 1 + "", gutterWidth), gutterStyleSequence) + gutterSeparator; + context += lineContent + host.getNewLine(); + // Output the gutter and the error span for the line using tildes. + context += indent + formatColorAndReset(padLeft("", gutterWidth), gutterStyleSequence) + gutterSeparator; + context += squiggleColor; + if (i === firstLine) { + // If we're on the last line, then limit it to the last character of the last line. + // Otherwise, we'll just squiggle the rest of the line, giving 'slice' no end position. + var lastCharForLine = i === lastLine ? lastLineChar : undefined; + context += lineContent.slice(0, firstLineChar).replace(/\S/g, " "); + context += lineContent.slice(firstLineChar, lastCharForLine).replace(/./g, "~"); + } + else if (i === lastLine) { + context += lineContent.slice(0, lastLineChar).replace(/./g, "~"); + } + else { + // Squiggle the entire line. + context += lineContent.replace(/./g, "~"); + } + context += resetEscapeSequence; + } + return context; + } + /* @internal */ + function formatLocation(file, start, host, color) { + if (color === void 0) { color = formatColorAndReset; } + var _a = ts.getLineAndCharacterOfPosition(file, start), firstLine = _a.line, firstLineChar = _a.character; // TODO: GH#18217 + var relativeFileName = host ? ts.convertToRelativePath(file.fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); }) : file.fileName; + var output = ""; + output += color(relativeFileName, ForegroundColorEscapeSequences.Cyan); + output += ":"; + output += color("" + (firstLine + 1), ForegroundColorEscapeSequences.Yellow); + output += ":"; + output += color("" + (firstLineChar + 1), ForegroundColorEscapeSequences.Yellow); + return output; + } + ts.formatLocation = formatLocation; + function formatDiagnosticsWithColorAndContext(diagnostics, host) { + var output = ""; + for (var _i = 0, diagnostics_3 = diagnostics; _i < diagnostics_3.length; _i++) { + var diagnostic = diagnostics_3[_i]; + if (diagnostic.file) { + var file = diagnostic.file, start = diagnostic.start; + output += formatLocation(file, start, host); // TODO: GH#18217 + output += " - "; + } + output += formatColorAndReset(ts.diagnosticCategoryName(diagnostic), getCategoryFormat(diagnostic.category)); + output += formatColorAndReset(" TS" + diagnostic.code + ": ", ForegroundColorEscapeSequences.Grey); + output += flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine()); + if (diagnostic.file) { + output += host.getNewLine(); + output += formatCodeSpan(diagnostic.file, diagnostic.start, diagnostic.length, "", getCategoryFormat(diagnostic.category), host); // TODO: GH#18217 + if (diagnostic.relatedInformation) { + output += host.getNewLine(); + for (var _a = 0, _b = diagnostic.relatedInformation; _a < _b.length; _a++) { + var _c = _b[_a], file = _c.file, start = _c.start, length_4 = _c.length, messageText = _c.messageText; + if (file) { + output += host.getNewLine(); + output += halfIndent + formatLocation(file, start, host); // TODO: GH#18217 + output += formatCodeSpan(file, start, length_4, indent, ForegroundColorEscapeSequences.Cyan, host); // TODO: GH#18217 + } + output += host.getNewLine(); + output += indent + flattenDiagnosticMessageText(messageText, host.getNewLine()); + } + } + } + output += host.getNewLine(); + } + return output; + } + ts.formatDiagnosticsWithColorAndContext = formatDiagnosticsWithColorAndContext; + function flattenDiagnosticMessageText(messageText, newLine) { + if (ts.isString(messageText)) { + return messageText; + } + else { + var diagnosticChain = messageText; + var result = ""; + var indent_1 = 0; + while (diagnosticChain) { + if (indent_1) { + result += newLine; + for (var i = 0; i < indent_1; i++) { + result += " "; + } + } + result += diagnosticChain.messageText; + indent_1++; + diagnosticChain = diagnosticChain.next; + } + return result; + } + } + ts.flattenDiagnosticMessageText = flattenDiagnosticMessageText; + function loadWithLocalCache(names, containingFile, redirectedReference, loader) { + if (names.length === 0) { + return []; + } + var resolutions = []; + var cache = ts.createMap(); + for (var _i = 0, names_1 = names; _i < names_1.length; _i++) { + var name = names_1[_i]; + var result = void 0; + if (cache.has(name)) { + result = cache.get(name); + } + else { + cache.set(name, result = loader(name, containingFile, redirectedReference)); + } + resolutions.push(result); + } + return resolutions; + } + /** + * Determines if program structure is upto date or needs to be recreated + */ + /* @internal */ + function isProgramUptoDate(program, rootFileNames, newOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, projectReferences) { + // If we haven't created a program yet or have changed automatic type directives, then it is not up-to-date + if (!program || hasChangedAutomaticTypeDirectiveNames) { + return false; + } + // If number of files in the program do not match, it is not up-to-date + if (program.getRootFileNames().length !== rootFileNames.length) { + return false; + } + var seenResolvedRefs; + // If project references dont match + if (!ts.arrayIsEqualTo(program.getProjectReferences(), projectReferences, projectReferenceUptoDate)) { + return false; + } + // If any file is not up-to-date, then the whole program is not up-to-date + if (program.getSourceFiles().some(sourceFileNotUptoDate)) { + return false; + } + // If any of the missing file paths are now created + if (program.getMissingFilePaths().some(fileExists)) { + return false; + } + var currentOptions = program.getCompilerOptions(); + // If the compilation settings do no match, then the program is not up-to-date + if (!ts.compareDataObjects(currentOptions, newOptions)) { + return false; + } + // If everything matches but the text of config file is changed, + // error locations can change for program options, so update the program + if (currentOptions.configFile && newOptions.configFile) { + return currentOptions.configFile.text === newOptions.configFile.text; + } + return true; + function sourceFileNotUptoDate(sourceFile) { + return !sourceFileVersionUptoDate(sourceFile) || + hasInvalidatedResolution(sourceFile.path); + } + function sourceFileVersionUptoDate(sourceFile) { + return sourceFile.version === getSourceVersion(sourceFile.resolvedPath); + } + function projectReferenceUptoDate(oldRef, newRef, index) { + if (!ts.projectReferenceIsEqualTo(oldRef, newRef)) { + return false; + } + return resolvedProjectReferenceUptoDate(program.getResolvedProjectReferences()[index], oldRef); + } + function resolvedProjectReferenceUptoDate(oldResolvedRef, oldRef) { + if (oldResolvedRef) { + if (ts.contains(seenResolvedRefs, oldResolvedRef)) { + // Assume true + return true; + } + // If sourceFile for the oldResolvedRef existed, check the version for uptodate + if (!sourceFileVersionUptoDate(oldResolvedRef.sourceFile)) { + return false; + } + // Add to seen before checking the referenced paths of this config file + (seenResolvedRefs || (seenResolvedRefs = [])).push(oldResolvedRef); + // If child project references are upto date, this project reference is uptodate + return !ts.forEach(oldResolvedRef.references, function (childResolvedRef, index) { + return !resolvedProjectReferenceUptoDate(childResolvedRef, oldResolvedRef.commandLine.projectReferences[index]); + }); + } + // In old program, not able to resolve project reference path, + // so if config file doesnt exist, it is uptodate. + return !fileExists(resolveProjectReferencePath(oldRef)); + } + } + ts.isProgramUptoDate = isProgramUptoDate; + function getConfigFileParsingDiagnostics(configFileParseResult) { + return configFileParseResult.options.configFile ? configFileParseResult.options.configFile.parseDiagnostics.concat(configFileParseResult.errors) : + configFileParseResult.errors; + } + ts.getConfigFileParsingDiagnostics = getConfigFileParsingDiagnostics; + /** + * Determine if source file needs to be re-created even if its text hasn't changed + */ + function shouldProgramCreateNewSourceFiles(program, newOptions) { + if (!program) + return false; + // If any compiler options change, we can't reuse old source file even if version match + // The change in options like these could result in change in syntax tree or `sourceFile.bindDiagnostics`. + var oldOptions = program.getCompilerOptions(); + return !!ts.sourceFileAffectingCompilerOptions.some(function (option) { + return !ts.isJsonEqual(ts.getCompilerOptionValue(oldOptions, option), ts.getCompilerOptionValue(newOptions, option)); + }); + } + function createCreateProgramOptions(rootNames, options, host, oldProgram, configFileParsingDiagnostics) { + return { + rootNames: rootNames, + options: options, + host: host, + oldProgram: oldProgram, + configFileParsingDiagnostics: configFileParsingDiagnostics + }; + } + function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _configFileParsingDiagnostics) { + var createProgramOptions = ts.isArray(rootNamesOrOptions) ? createCreateProgramOptions(rootNamesOrOptions, _options, _host, _oldProgram, _configFileParsingDiagnostics) : rootNamesOrOptions; // TODO: GH#18217 + var rootNames = createProgramOptions.rootNames, options = createProgramOptions.options, configFileParsingDiagnostics = createProgramOptions.configFileParsingDiagnostics, projectReferences = createProgramOptions.projectReferences; + var oldProgram = createProgramOptions.oldProgram; + var program; + var processingDefaultLibFiles; + var processingOtherFiles; + var files; + var commonSourceDirectory; + var diagnosticsProducingTypeChecker; + var noDiagnosticsTypeChecker; + var classifiableNames; + var ambientModuleNameToUnmodifiedFileName = ts.createMap(); + var cachedSemanticDiagnosticsForFile = {}; + var cachedDeclarationDiagnosticsForFile = {}; + var resolvedTypeReferenceDirectives = ts.createMap(); + var fileProcessingDiagnostics = ts.createDiagnosticCollection(); + // The below settings are to track if a .js file should be add to the program if loaded via searching under node_modules. + // This works as imported modules are discovered recursively in a depth first manner, specifically: + // - For each root file, findSourceFile is called. + // - This calls processImportedModules for each module imported in the source file. + // - This calls resolveModuleNames, and then calls findSourceFile for each resolved module. + // As all these operations happen - and are nested - within the createProgram call, they close over the below variables. + // The current resolution depth is tracked by incrementing/decrementing as the depth first search progresses. + var maxNodeModuleJsDepth = typeof options.maxNodeModuleJsDepth === "number" ? options.maxNodeModuleJsDepth : 0; + var currentNodeModulesDepth = 0; + // If a module has some of its imports skipped due to being at the depth limit under node_modules, then track + // this, as it may be imported at a shallower depth later, and then it will need its skipped imports processed. + var modulesWithElidedImports = ts.createMap(); + // Track source files that are source files found by searching under node_modules, as these shouldn't be compiled. + var sourceFilesFoundSearchingNodeModules = ts.createMap(); + ts.performance.mark("beforeProgram"); + var host = createProgramOptions.host || createCompilerHost(options); + var configParsingHost = parseConfigHostFromCompilerHost(host); + var skipDefaultLib = options.noLib; + var getDefaultLibraryFileName = ts.memoize(function () { return host.getDefaultLibFileName(options); }); + var defaultLibraryPath = host.getDefaultLibLocation ? host.getDefaultLibLocation() : ts.getDirectoryPath(getDefaultLibraryFileName()); + var programDiagnostics = ts.createDiagnosticCollection(); + var currentDirectory = host.getCurrentDirectory(); + var supportedExtensions = ts.getSupportedExtensions(options); + var supportedExtensionsWithJsonIfResolveJsonModule = ts.getSuppoertedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions); + // Map storing if there is emit blocking diagnostics for given input + var hasEmitBlockingDiagnostics = ts.createMap(); + var _compilerOptionsObjectLiteralSyntax; + var moduleResolutionCache; + var resolveModuleNamesWorker; + var hasInvalidatedResolution = host.hasInvalidatedResolution || ts.returnFalse; + if (host.resolveModuleNames) { + resolveModuleNamesWorker = function (moduleNames, containingFile, reusedNames, redirectedReference) { return host.resolveModuleNames(ts.Debug.assertEachDefined(moduleNames), containingFile, reusedNames, redirectedReference).map(function (resolved) { + // An older host may have omitted extension, in which case we should infer it from the file extension of resolvedFileName. + if (!resolved || resolved.extension !== undefined) { + return resolved; + } + var withExtension = ts.clone(resolved); + withExtension.extension = ts.extensionFromPath(resolved.resolvedFileName); + return withExtension; + }); }; + } + else { + moduleResolutionCache = ts.createModuleResolutionCache(currentDirectory, function (x) { return host.getCanonicalFileName(x); }); + var loader_1 = function (moduleName, containingFile, redirectedReference) { return ts.resolveModuleName(moduleName, containingFile, options, host, moduleResolutionCache, redirectedReference).resolvedModule; }; // TODO: GH#18217 + resolveModuleNamesWorker = function (moduleNames, containingFile, _reusedNames, redirectedReference) { return loadWithLocalCache(ts.Debug.assertEachDefined(moduleNames), containingFile, redirectedReference, loader_1); }; + } + var resolveTypeReferenceDirectiveNamesWorker; + if (host.resolveTypeReferenceDirectives) { + resolveTypeReferenceDirectiveNamesWorker = function (typeDirectiveNames, containingFile, redirectedReference) { return host.resolveTypeReferenceDirectives(ts.Debug.assertEachDefined(typeDirectiveNames), containingFile, redirectedReference); }; + } + else { + var loader_2 = function (typesRef, containingFile, redirectedReference) { return ts.resolveTypeReferenceDirective(typesRef, containingFile, options, host, redirectedReference).resolvedTypeReferenceDirective; }; // TODO: GH#18217 + resolveTypeReferenceDirectiveNamesWorker = function (typeReferenceDirectiveNames, containingFile, redirectedReference) { return loadWithLocalCache(ts.Debug.assertEachDefined(typeReferenceDirectiveNames), containingFile, redirectedReference, loader_2); }; + } + // Map from a stringified PackageId to the source file with that id. + // Only one source file may have a given packageId. Others become redirects (see createRedirectSourceFile). + // `packageIdToSourceFile` is only used while building the program, while `sourceFileToPackageName` and `isSourceFileTargetOfRedirect` are kept around. + var packageIdToSourceFile = ts.createMap(); + // Maps from a SourceFile's `.path` to the name of the package it was imported with. + var sourceFileToPackageName = ts.createMap(); + // Key is a file name. Value is the (non-empty, or undefined) list of files that redirect to it. + var redirectTargetsMap = ts.createMultiMap(); + var filesByName = ts.createMap(); + var missingFilePaths; + // stores 'filename -> file association' ignoring case + // used to track cases when two file names differ only in casing + var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createMap() : undefined; + // A parallel array to projectReferences storing the results of reading in the referenced tsconfig files + var resolvedProjectReferences; + var projectReferenceRedirects; + var mapFromFileToProjectReferenceRedirects; + var shouldCreateNewSourceFile = shouldProgramCreateNewSourceFiles(oldProgram, options); + var structuralIsReused = tryReuseStructureFromOldProgram(); + if (structuralIsReused !== 2 /* Completely */) { + processingDefaultLibFiles = []; + processingOtherFiles = []; + if (projectReferences) { + if (!resolvedProjectReferences) { + resolvedProjectReferences = projectReferences.map(parseProjectReferenceConfigFile); + } + if (rootNames.length) { + for (var _i = 0, resolvedProjectReferences_1 = resolvedProjectReferences; _i < resolvedProjectReferences_1.length; _i++) { + var parsedRef = resolvedProjectReferences_1[_i]; + if (parsedRef) { + var out = parsedRef.commandLine.options.outFile || parsedRef.commandLine.options.out; + if (out) { + var dtsOutfile = ts.changeExtension(out, ".d.ts"); + processSourceFile(dtsOutfile, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined); + } + } + } + } + } + ts.forEach(rootNames, function (name) { return processRootFile(name, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false); }); + // load type declarations specified via 'types' argument or implicitly from types/ and node_modules/@types folders + var typeReferences = rootNames.length ? ts.getAutomaticTypeDirectiveNames(options, host) : ts.emptyArray; + if (typeReferences.length) { + // This containingFilename needs to match with the one used in managed-side + var containingDirectory = options.configFilePath ? ts.getDirectoryPath(options.configFilePath) : host.getCurrentDirectory(); + var containingFilename = ts.combinePaths(containingDirectory, "__inferred type names__.ts"); + var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeReferences, containingFilename); + for (var i = 0; i < typeReferences.length; i++) { + processTypeReferenceDirective(typeReferences[i], resolutions[i]); + } + } + // Do not process the default library if: + // - The '--noLib' flag is used. + // - A 'no-default-lib' reference comment is encountered in + // processing the root files. + if (rootNames.length && !skipDefaultLib) { + // If '--lib' is not specified, include default library file according to '--target' + // otherwise, using options specified in '--lib' instead of '--target' default library file + var defaultLibraryFileName = getDefaultLibraryFileName(); + if (!options.lib && defaultLibraryFileName) { + processRootFile(defaultLibraryFileName, /*isDefaultLib*/ true, /*ignoreNoDefaultLib*/ false); + } + else { + ts.forEach(options.lib, function (libFileName) { + processRootFile(ts.combinePaths(defaultLibraryPath, libFileName), /*isDefaultLib*/ true, /*ignoreNoDefaultLib*/ false); + }); + } + } + missingFilePaths = ts.arrayFrom(filesByName.keys(), function (p) { return p; }).filter(function (p) { return !filesByName.get(p); }); + files = ts.stableSort(processingDefaultLibFiles, compareDefaultLibFiles).concat(processingOtherFiles); + processingDefaultLibFiles = undefined; + processingOtherFiles = undefined; + } + ts.Debug.assert(!!missingFilePaths); + // Release any files we have acquired in the old program but are + // not part of the new program. + if (oldProgram && host.onReleaseOldSourceFile) { + var oldSourceFiles = oldProgram.getSourceFiles(); + for (var _a = 0, oldSourceFiles_1 = oldSourceFiles; _a < oldSourceFiles_1.length; _a++) { + var oldSourceFile = oldSourceFiles_1[_a]; + var newFile = getSourceFileByPath(oldSourceFile.resolvedPath); + if (shouldCreateNewSourceFile || !newFile || + // old file wasnt redirect but new file is + (oldSourceFile.resolvedPath === oldSourceFile.path && newFile.resolvedPath !== oldSourceFile.path)) { + host.onReleaseOldSourceFile(oldSourceFile, oldProgram.getCompilerOptions(), !!getSourceFileByPath(oldSourceFile.path)); + } + } + oldProgram.forEachResolvedProjectReference(function (resolvedProjectReference, resolvedProjectReferencePath) { + if (resolvedProjectReference && !getResolvedProjectReferenceByPath(resolvedProjectReferencePath)) { + host.onReleaseOldSourceFile(resolvedProjectReference.sourceFile, oldProgram.getCompilerOptions(), /*hasSourceFileByPath*/ false); + } + }); + } + // unconditionally set oldProgram to undefined to prevent it from being captured in closure + oldProgram = undefined; + program = { + getRootFileNames: function () { return rootNames; }, + getSourceFile: getSourceFile, + getSourceFileByPath: getSourceFileByPath, + getSourceFiles: function () { return files; }, + getMissingFilePaths: function () { return missingFilePaths; }, + getCompilerOptions: function () { return options; }, + getSyntacticDiagnostics: getSyntacticDiagnostics, + getOptionsDiagnostics: getOptionsDiagnostics, + getGlobalDiagnostics: getGlobalDiagnostics, + getSemanticDiagnostics: getSemanticDiagnostics, + getSuggestionDiagnostics: getSuggestionDiagnostics, + getDeclarationDiagnostics: getDeclarationDiagnostics, + getTypeChecker: getTypeChecker, + getClassifiableNames: getClassifiableNames, + getDiagnosticsProducingTypeChecker: getDiagnosticsProducingTypeChecker, + getCommonSourceDirectory: getCommonSourceDirectory, + emit: emit, + getCurrentDirectory: function () { return currentDirectory; }, + getNodeCount: function () { return getDiagnosticsProducingTypeChecker().getNodeCount(); }, + getIdentifierCount: function () { return getDiagnosticsProducingTypeChecker().getIdentifierCount(); }, + getSymbolCount: function () { return getDiagnosticsProducingTypeChecker().getSymbolCount(); }, + getTypeCount: function () { return getDiagnosticsProducingTypeChecker().getTypeCount(); }, + getFileProcessingDiagnostics: function () { return fileProcessingDiagnostics; }, + getResolvedTypeReferenceDirectives: function () { return resolvedTypeReferenceDirectives; }, + isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary, + isSourceFileDefaultLibrary: isSourceFileDefaultLibrary, + dropDiagnosticsProducingTypeChecker: dropDiagnosticsProducingTypeChecker, + getSourceFileFromReference: getSourceFileFromReference, + getLibFileFromReference: getLibFileFromReference, + sourceFileToPackageName: sourceFileToPackageName, + redirectTargetsMap: redirectTargetsMap, + isEmittedFile: isEmittedFile, + getConfigFileParsingDiagnostics: getConfigFileParsingDiagnostics, + getResolvedModuleWithFailedLookupLocationsFromCache: getResolvedModuleWithFailedLookupLocationsFromCache, + getProjectReferences: getProjectReferences, + getResolvedProjectReferences: getResolvedProjectReferences, + getProjectReferenceRedirect: getProjectReferenceRedirect, + getResolvedProjectReferenceToRedirect: getResolvedProjectReferenceToRedirect, + getResolvedProjectReferenceByPath: getResolvedProjectReferenceByPath, + forEachResolvedProjectReference: forEachResolvedProjectReference + }; + verifyCompilerOptions(); + ts.performance.mark("afterProgram"); + ts.performance.measure("Program", "beforeProgram", "afterProgram"); + return program; + function compareDefaultLibFiles(a, b) { + return ts.compareValues(getDefaultLibFilePriority(a), getDefaultLibFilePriority(b)); + } + function getDefaultLibFilePriority(a) { + if (ts.containsPath(defaultLibraryPath, a.fileName, /*ignoreCase*/ false)) { + var basename = ts.getBaseFileName(a.fileName); + if (basename === "lib.d.ts" || basename === "lib.es6.d.ts") + return 0; + var name = ts.removeSuffix(ts.removePrefix(basename, "lib."), ".d.ts"); + var index = ts.libs.indexOf(name); + if (index !== -1) + return index + 1; + } + return ts.libs.length + 2; + } + function getResolvedModuleWithFailedLookupLocationsFromCache(moduleName, containingFile) { + return moduleResolutionCache && ts.resolveModuleNameFromCache(moduleName, containingFile, moduleResolutionCache); + } + function toPath(fileName) { + return ts.toPath(fileName, currentDirectory, getCanonicalFileName); + } + function getCommonSourceDirectory() { + if (commonSourceDirectory === undefined) { + var emittedFiles = ts.filter(files, function (file) { return ts.sourceFileMayBeEmitted(file, options, isSourceFileFromExternalLibrary); }); + if (options.rootDir && checkSourceFilesBelongToPath(emittedFiles, options.rootDir)) { + // If a rootDir is specified use it as the commonSourceDirectory + commonSourceDirectory = ts.getNormalizedAbsolutePath(options.rootDir, currentDirectory); + } + else if (options.composite && options.configFilePath) { + // Project compilations never infer their root from the input source paths + commonSourceDirectory = ts.getDirectoryPath(ts.normalizeSlashes(options.configFilePath)); + checkSourceFilesBelongToPath(emittedFiles, commonSourceDirectory); + } + else { + commonSourceDirectory = computeCommonSourceDirectory(emittedFiles); + } + if (commonSourceDirectory && commonSourceDirectory[commonSourceDirectory.length - 1] !== ts.directorySeparator) { + // Make sure directory path ends with directory separator so this string can directly + // used to replace with "" to get the relative path of the source file and the relative path doesn't + // start with / making it rooted path + commonSourceDirectory += ts.directorySeparator; + } + } + return commonSourceDirectory; + } + function getClassifiableNames() { + if (!classifiableNames) { + // Initialize a checker so that all our files are bound. + getTypeChecker(); + classifiableNames = ts.createUnderscoreEscapedMap(); + for (var _i = 0, files_2 = files; _i < files_2.length; _i++) { + var sourceFile = files_2[_i]; + ts.copyEntries(sourceFile.classifiableNames, classifiableNames); + } + } + return classifiableNames; + } + function resolveModuleNamesReusingOldState(moduleNames, containingFile, file) { + if (structuralIsReused === 0 /* Not */ && !file.ambientModuleNames.length) { + // If the old program state does not permit reusing resolutions and `file` does not contain locally defined ambient modules, + // the best we can do is fallback to the default logic. + return resolveModuleNamesWorker(moduleNames, containingFile, /*reusedNames*/ undefined, getResolvedProjectReferenceToRedirect(file.originalFileName)); + } + var oldSourceFile = oldProgram && oldProgram.getSourceFile(containingFile); + if (oldSourceFile !== file && file.resolvedModules) { + // `file` was created for the new program. + // + // We only set `file.resolvedModules` via work from the current function, + // so it is defined iff we already called the current function on `file`. + // That call happened no later than the creation of the `file` object, + // which per above occurred during the current program creation. + // Since we assume the filesystem does not change during program creation, + // it is safe to reuse resolutions from the earlier call. + var result_5 = []; + for (var _i = 0, moduleNames_1 = moduleNames; _i < moduleNames_1.length; _i++) { + var moduleName = moduleNames_1[_i]; + var resolvedModule = file.resolvedModules.get(moduleName); + result_5.push(resolvedModule); + } + return result_5; + } + // At this point, we know at least one of the following hold: + // - file has local declarations for ambient modules + // - old program state is available + // With this information, we can infer some module resolutions without performing resolution. + /** An ordered list of module names for which we cannot recover the resolution. */ + var unknownModuleNames; + /** + * The indexing of elements in this list matches that of `moduleNames`. + * + * Before combining results, result[i] is in one of the following states: + * * undefined: needs to be recomputed, + * * predictedToResolveToAmbientModuleMarker: known to be an ambient module. + * Needs to be reset to undefined before returning, + * * ResolvedModuleFull instance: can be reused. + */ + var result; + var reusedNames; + /** A transient placeholder used to mark predicted resolution in the result list. */ + var predictedToResolveToAmbientModuleMarker = {}; + for (var i = 0; i < moduleNames.length; i++) { + var moduleName = moduleNames[i]; + // If the source file is unchanged and doesnt have invalidated resolution, reuse the module resolutions + if (file === oldSourceFile && !hasInvalidatedResolution(oldSourceFile.path)) { + var oldResolvedModule = oldSourceFile && oldSourceFile.resolvedModules.get(moduleName); + if (oldResolvedModule) { + if (ts.isTraceEnabled(options, host)) { + ts.trace(host, ts.Diagnostics.Reusing_resolution_of_module_0_to_file_1_from_old_program, moduleName, containingFile); + } + (result || (result = new Array(moduleNames.length)))[i] = oldResolvedModule; + (reusedNames || (reusedNames = [])).push(moduleName); + continue; + } + } + // We know moduleName resolves to an ambient module provided that moduleName: + // - is in the list of ambient modules locally declared in the current source file. + // - resolved to an ambient module in the old program whose declaration is in an unmodified file + // (so the same module declaration will land in the new program) + var resolvesToAmbientModuleInNonModifiedFile = false; + if (ts.contains(file.ambientModuleNames, moduleName)) { + resolvesToAmbientModuleInNonModifiedFile = true; + if (ts.isTraceEnabled(options, host)) { + ts.trace(host, ts.Diagnostics.Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1, moduleName, containingFile); + } + } + else { + resolvesToAmbientModuleInNonModifiedFile = moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName); + } + if (resolvesToAmbientModuleInNonModifiedFile) { + (result || (result = new Array(moduleNames.length)))[i] = predictedToResolveToAmbientModuleMarker; + } + else { + // Resolution failed in the old program, or resolved to an ambient module for which we can't reuse the result. + (unknownModuleNames || (unknownModuleNames = [])).push(moduleName); + } + } + var resolutions = unknownModuleNames && unknownModuleNames.length + ? resolveModuleNamesWorker(unknownModuleNames, containingFile, reusedNames, getResolvedProjectReferenceToRedirect(file.originalFileName)) + : ts.emptyArray; + // Combine results of resolutions and predicted results + if (!result) { + // There were no unresolved/ambient resolutions. + ts.Debug.assert(resolutions.length === moduleNames.length); + return resolutions; + } + var j = 0; + for (var i = 0; i < result.length; i++) { + if (result[i]) { + // `result[i]` is either a `ResolvedModuleFull` or a marker. + // If it is the former, we can leave it as is. + if (result[i] === predictedToResolveToAmbientModuleMarker) { + result[i] = undefined; // TODO: GH#18217 + } + } + else { + result[i] = resolutions[j]; + j++; + } + } + ts.Debug.assert(j === resolutions.length); + return result; + // If we change our policy of rechecking failed lookups on each program create, + // we should adjust the value returned here. + function moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName) { + var resolutionToFile = ts.getResolvedModule(oldSourceFile, moduleName); + var resolvedFile = resolutionToFile && oldProgram.getSourceFile(resolutionToFile.resolvedFileName); + if (resolutionToFile && resolvedFile && !resolvedFile.externalModuleIndicator) { + // In the old program, we resolved to an ambient module that was in the same + // place as we expected to find an actual module file. + // We actually need to return 'false' here even though this seems like a 'true' case + // because the normal module resolution algorithm will find this anyway. + return false; + } + // at least one of declarations should come from non-modified source file + var unmodifiedFile = ambientModuleNameToUnmodifiedFileName.get(moduleName); + if (!unmodifiedFile) { + return false; + } + if (ts.isTraceEnabled(options, host)) { + ts.trace(host, ts.Diagnostics.Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified, moduleName, unmodifiedFile); + } + return true; + } + } + function canReuseProjectReferences() { + return !forEachProjectReference(oldProgram.getProjectReferences(), oldProgram.getResolvedProjectReferences(), function (oldResolvedRef, index, parent) { + var newRef = (parent ? parent.commandLine.projectReferences : projectReferences)[index]; + var newResolvedRef = parseProjectReferenceConfigFile(newRef); + if (oldResolvedRef) { + // Resolved project reference has gone missing or changed + return !newResolvedRef || newResolvedRef.sourceFile !== oldResolvedRef.sourceFile; + } + else { + // A previously-unresolved reference may be resolved now + return newResolvedRef !== undefined; + } + }, function (oldProjectReferences, parent) { + // If array of references is changed, we cant resue old program + var newReferences = parent ? getResolvedProjectReferenceByPath(parent.sourceFile.path).commandLine.projectReferences : projectReferences; + return !ts.arrayIsEqualTo(oldProjectReferences, newReferences, ts.projectReferenceIsEqualTo); + }); + } + function tryReuseStructureFromOldProgram() { + if (!oldProgram) { + return 0 /* Not */; + } + // check properties that can affect structure of the program or module resolution strategy + // if any of these properties has changed - structure cannot be reused + var oldOptions = oldProgram.getCompilerOptions(); + if (ts.changesAffectModuleResolution(oldOptions, options)) { + return oldProgram.structureIsReused = 0 /* Not */; + } + ts.Debug.assert(!(oldProgram.structureIsReused & (2 /* Completely */ | 1 /* SafeModules */))); + // there is an old program, check if we can reuse its structure + var oldRootNames = oldProgram.getRootFileNames(); + if (!ts.arrayIsEqualTo(oldRootNames, rootNames)) { + return oldProgram.structureIsReused = 0 /* Not */; + } + if (!ts.arrayIsEqualTo(options.types, oldOptions.types)) { + return oldProgram.structureIsReused = 0 /* Not */; + } + // Check if any referenced project tsconfig files are different + if (!canReuseProjectReferences()) { + return oldProgram.structureIsReused = 0 /* Not */; + } + if (projectReferences) { + resolvedProjectReferences = projectReferences.map(parseProjectReferenceConfigFile); + } + // check if program source files has changed in the way that can affect structure of the program + var newSourceFiles = []; + var modifiedSourceFiles = []; + oldProgram.structureIsReused = 2 /* Completely */; + // If the missing file paths are now present, it can change the progam structure, + // and hence cant reuse the structure. + // This is same as how we dont reuse the structure if one of the file from old program is now missing + if (oldProgram.getMissingFilePaths().some(function (missingFilePath) { return host.fileExists(missingFilePath); })) { + return oldProgram.structureIsReused = 0 /* Not */; + } + var oldSourceFiles = oldProgram.getSourceFiles(); + var SeenPackageName; + (function (SeenPackageName) { + SeenPackageName[SeenPackageName["Exists"] = 0] = "Exists"; + SeenPackageName[SeenPackageName["Modified"] = 1] = "Modified"; + })(SeenPackageName || (SeenPackageName = {})); + var seenPackageNames = ts.createMap(); + for (var _i = 0, oldSourceFiles_2 = oldSourceFiles; _i < oldSourceFiles_2.length; _i++) { + var oldSourceFile = oldSourceFiles_2[_i]; + var newSourceFile = host.getSourceFileByPath + ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.resolvedPath, options.target, /*onError*/ undefined, shouldCreateNewSourceFile) + : host.getSourceFile(oldSourceFile.fileName, options.target, /*onError*/ undefined, shouldCreateNewSourceFile); // TODO: GH#18217 + if (!newSourceFile) { + return oldProgram.structureIsReused = 0 /* Not */; + } + ts.Debug.assert(!newSourceFile.redirectInfo, "Host should not return a redirect source file from `getSourceFile`"); + var fileChanged = void 0; + if (oldSourceFile.redirectInfo) { + // We got `newSourceFile` by path, so it is actually for the unredirected file. + // This lets us know if the unredirected file has changed. If it has we should break the redirect. + if (newSourceFile !== oldSourceFile.redirectInfo.unredirected) { + // Underlying file has changed. Might not redirect anymore. Must rebuild program. + return oldProgram.structureIsReused = 0 /* Not */; + } + fileChanged = false; + newSourceFile = oldSourceFile; // Use the redirect. + } + else if (oldProgram.redirectTargetsMap.has(oldSourceFile.path)) { + // If a redirected-to source file changes, the redirect may be broken. + if (newSourceFile !== oldSourceFile) { + return oldProgram.structureIsReused = 0 /* Not */; + } + fileChanged = false; + } + else { + fileChanged = newSourceFile !== oldSourceFile; + } + // Since the project references havent changed, its right to set originalFileName and resolvedPath here + newSourceFile.path = oldSourceFile.path; + newSourceFile.originalFileName = oldSourceFile.originalFileName; + newSourceFile.resolvedPath = oldSourceFile.resolvedPath; + newSourceFile.fileName = oldSourceFile.fileName; + var packageName = oldProgram.sourceFileToPackageName.get(oldSourceFile.path); + if (packageName !== undefined) { + // If there are 2 different source files for the same package name and at least one of them changes, + // they might become redirects. So we must rebuild the program. + var prevKind = seenPackageNames.get(packageName); + var newKind = fileChanged ? 1 /* Modified */ : 0 /* Exists */; + if ((prevKind !== undefined && newKind === 1 /* Modified */) || prevKind === 1 /* Modified */) { + return oldProgram.structureIsReused = 0 /* Not */; + } + seenPackageNames.set(packageName, newKind); + } + if (fileChanged) { + // The `newSourceFile` object was created for the new program. + if (!ts.arrayIsEqualTo(oldSourceFile.libReferenceDirectives, newSourceFile.libReferenceDirectives, fileReferenceIsEqualTo)) { + // 'lib' references has changed. Matches behavior in changesAffectModuleResolution + return oldProgram.structureIsReused = 0 /* Not */; + } + if (oldSourceFile.hasNoDefaultLib !== newSourceFile.hasNoDefaultLib) { + // value of no-default-lib has changed + // this will affect if default library is injected into the list of files + oldProgram.structureIsReused = 1 /* SafeModules */; + } + // check tripleslash references + if (!ts.arrayIsEqualTo(oldSourceFile.referencedFiles, newSourceFile.referencedFiles, fileReferenceIsEqualTo)) { + // tripleslash references has changed + oldProgram.structureIsReused = 1 /* SafeModules */; + } + // check imports and module augmentations + collectExternalModuleReferences(newSourceFile); + if (!ts.arrayIsEqualTo(oldSourceFile.imports, newSourceFile.imports, moduleNameIsEqualTo)) { + // imports has changed + oldProgram.structureIsReused = 1 /* SafeModules */; + } + if (!ts.arrayIsEqualTo(oldSourceFile.moduleAugmentations, newSourceFile.moduleAugmentations, moduleNameIsEqualTo)) { + // moduleAugmentations has changed + oldProgram.structureIsReused = 1 /* SafeModules */; + } + if ((oldSourceFile.flags & 1572864 /* PermanentlySetIncrementalFlags */) !== (newSourceFile.flags & 1572864 /* PermanentlySetIncrementalFlags */)) { + // dynamicImport has changed + oldProgram.structureIsReused = 1 /* SafeModules */; + } + if (!ts.arrayIsEqualTo(oldSourceFile.typeReferenceDirectives, newSourceFile.typeReferenceDirectives, fileReferenceIsEqualTo)) { + // 'types' references has changed + oldProgram.structureIsReused = 1 /* SafeModules */; + } + // tentatively approve the file + modifiedSourceFiles.push({ oldFile: oldSourceFile, newFile: newSourceFile }); + } + else if (hasInvalidatedResolution(oldSourceFile.path)) { + // 'module/types' references could have changed + oldProgram.structureIsReused = 1 /* SafeModules */; + // add file to the modified list so that we will resolve it later + modifiedSourceFiles.push({ oldFile: oldSourceFile, newFile: newSourceFile }); + } + // if file has passed all checks it should be safe to reuse it + newSourceFiles.push(newSourceFile); + } + if (oldProgram.structureIsReused !== 2 /* Completely */) { + return oldProgram.structureIsReused; + } + var modifiedFiles = modifiedSourceFiles.map(function (f) { return f.oldFile; }); + for (var _a = 0, oldSourceFiles_3 = oldSourceFiles; _a < oldSourceFiles_3.length; _a++) { + var oldFile = oldSourceFiles_3[_a]; + if (!ts.contains(modifiedFiles, oldFile)) { + for (var _b = 0, _c = oldFile.ambientModuleNames; _b < _c.length; _b++) { + var moduleName = _c[_b]; + ambientModuleNameToUnmodifiedFileName.set(moduleName, oldFile.fileName); + } + } + } + // try to verify results of module resolution + for (var _d = 0, modifiedSourceFiles_1 = modifiedSourceFiles; _d < modifiedSourceFiles_1.length; _d++) { + var _e = modifiedSourceFiles_1[_d], oldSourceFile = _e.oldFile, newSourceFile = _e.newFile; + var newSourceFilePath = ts.getNormalizedAbsolutePath(newSourceFile.originalFileName, currentDirectory); + if (resolveModuleNamesWorker) { + var moduleNames = getModuleNames(newSourceFile); + var resolutions = resolveModuleNamesReusingOldState(moduleNames, newSourceFilePath, newSourceFile); + // ensure that module resolution results are still correct + var resolutionsChanged = ts.hasChangesInResolutions(moduleNames, resolutions, oldSourceFile.resolvedModules, ts.moduleResolutionIsEqualTo); + if (resolutionsChanged) { + oldProgram.structureIsReused = 1 /* SafeModules */; + newSourceFile.resolvedModules = ts.zipToMap(moduleNames, resolutions); + } + else { + newSourceFile.resolvedModules = oldSourceFile.resolvedModules; + } + } + if (resolveTypeReferenceDirectiveNamesWorker) { + // We lower-case all type references because npm automatically lowercases all packages. See GH#9824. + var typesReferenceDirectives = ts.map(newSourceFile.typeReferenceDirectives, function (ref) { return ref.fileName.toLocaleLowerCase(); }); + var resolutions = resolveTypeReferenceDirectiveNamesWorker(typesReferenceDirectives, newSourceFilePath, getResolvedProjectReferenceToRedirect(newSourceFile.originalFileName)); + // ensure that types resolutions are still correct + var resolutionsChanged = ts.hasChangesInResolutions(typesReferenceDirectives, resolutions, oldSourceFile.resolvedTypeReferenceDirectiveNames, ts.typeDirectiveIsEqualTo); + if (resolutionsChanged) { + oldProgram.structureIsReused = 1 /* SafeModules */; + newSourceFile.resolvedTypeReferenceDirectiveNames = ts.zipToMap(typesReferenceDirectives, resolutions); + } + else { + newSourceFile.resolvedTypeReferenceDirectiveNames = oldSourceFile.resolvedTypeReferenceDirectiveNames; + } + } + } + if (oldProgram.structureIsReused !== 2 /* Completely */) { + return oldProgram.structureIsReused; + } + if (host.hasChangedAutomaticTypeDirectiveNames) { + return oldProgram.structureIsReused = 1 /* SafeModules */; + } + missingFilePaths = oldProgram.getMissingFilePaths(); + // update fileName -> file mapping + for (var _f = 0, newSourceFiles_1 = newSourceFiles; _f < newSourceFiles_1.length; _f++) { + var newSourceFile = newSourceFiles_1[_f]; + var filePath = newSourceFile.path; + addFileToFilesByName(newSourceFile, filePath, newSourceFile.resolvedPath); + // Set the file as found during node modules search if it was found that way in old progra, + if (oldProgram.isSourceFileFromExternalLibrary(oldProgram.getSourceFileByPath(filePath))) { + sourceFilesFoundSearchingNodeModules.set(filePath, true); + } + } + files = newSourceFiles; + fileProcessingDiagnostics = oldProgram.getFileProcessingDiagnostics(); + for (var _g = 0, modifiedSourceFiles_2 = modifiedSourceFiles; _g < modifiedSourceFiles_2.length; _g++) { + var modifiedFile = modifiedSourceFiles_2[_g]; + fileProcessingDiagnostics.reattachFileDiagnostics(modifiedFile.newFile); + } + resolvedTypeReferenceDirectives = oldProgram.getResolvedTypeReferenceDirectives(); + sourceFileToPackageName = oldProgram.sourceFileToPackageName; + redirectTargetsMap = oldProgram.redirectTargetsMap; + return oldProgram.structureIsReused = 2 /* Completely */; + } + function getEmitHost(writeFileCallback) { + return __assign({ getPrependNodes: getPrependNodes, + getCanonicalFileName: getCanonicalFileName, getCommonSourceDirectory: program.getCommonSourceDirectory, getCompilerOptions: program.getCompilerOptions, getCurrentDirectory: function () { return currentDirectory; }, getNewLine: function () { return host.getNewLine(); }, getSourceFile: program.getSourceFile, getSourceFileByPath: program.getSourceFileByPath, getSourceFiles: program.getSourceFiles, getLibFileFromReference: program.getLibFileFromReference, isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary, writeFile: writeFileCallback || (function (fileName, data, writeByteOrderMark, onError, sourceFiles) { return host.writeFile(fileName, data, writeByteOrderMark, onError, sourceFiles); }), isEmitBlocked: isEmitBlocked, readFile: function (f) { return host.readFile(f); }, fileExists: function (f) { + // Use local caches + var path = toPath(f); + if (getSourceFileByPath(path)) + return true; + if (ts.contains(missingFilePaths, path)) + return false; + // Before falling back to the host + return host.fileExists(f); + } }, (host.directoryExists ? { directoryExists: function (f) { return host.directoryExists(f); } } : {}), { useCaseSensitiveFileNames: function () { return host.useCaseSensitiveFileNames(); } }); + } + function getResolvedProjectReferences() { + return resolvedProjectReferences; + } + function getProjectReferences() { + return projectReferences; + } + function getPrependNodes() { + if (!projectReferences) { + return ts.emptyArray; + } + var nodes = []; + for (var i = 0; i < projectReferences.length; i++) { + var ref = projectReferences[i]; + var resolvedRefOpts = resolvedProjectReferences[i].commandLine; + if (ref.prepend && resolvedRefOpts && resolvedRefOpts.options) { + var out = resolvedRefOpts.options.outFile || resolvedRefOpts.options.out; + // Upstream project didn't have outFile set -- skip (error will have been issued earlier) + if (!out) + continue; + var dtsFilename = ts.changeExtension(out, ".d.ts"); + var js = host.readFile(out) || "/* Input file " + out + " was missing */\r\n"; + var jsMapPath = out + ".map"; // TODO: try to read sourceMappingUrl comment from the file + var jsMap = host.readFile(jsMapPath); + var dts = host.readFile(dtsFilename) || "/* Input file " + dtsFilename + " was missing */\r\n"; + var dtsMapPath = dtsFilename + ".map"; + var dtsMap = host.readFile(dtsMapPath); + var node = ts.createInputFiles(js, dts, jsMap && jsMapPath, jsMap, dtsMap && dtsMapPath, dtsMap); + nodes.push(node); + } + } + return nodes; + } + function isSourceFileFromExternalLibrary(file) { + return !!sourceFilesFoundSearchingNodeModules.get(file.path); + } + function isSourceFileDefaultLibrary(file) { + if (file.hasNoDefaultLib) { + return true; + } + if (!options.noLib) { + return false; + } + // If '--lib' is not specified, include default library file according to '--target' + // otherwise, using options specified in '--lib' instead of '--target' default library file + var equalityComparer = host.useCaseSensitiveFileNames() ? ts.equateStringsCaseSensitive : ts.equateStringsCaseInsensitive; + if (!options.lib) { + return equalityComparer(file.fileName, getDefaultLibraryFileName()); + } + else { + return ts.some(options.lib, function (libFileName) { return equalityComparer(file.fileName, ts.combinePaths(defaultLibraryPath, libFileName)); }); + } + } + function getDiagnosticsProducingTypeChecker() { + return diagnosticsProducingTypeChecker || (diagnosticsProducingTypeChecker = ts.createTypeChecker(program, /*produceDiagnostics:*/ true)); + } + function dropDiagnosticsProducingTypeChecker() { + diagnosticsProducingTypeChecker = undefined; + } + function getTypeChecker() { + return noDiagnosticsTypeChecker || (noDiagnosticsTypeChecker = ts.createTypeChecker(program, /*produceDiagnostics:*/ false)); + } + function emit(sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles, transformers) { + return runWithCancellationToken(function () { return emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles, transformers); }); + } + function isEmitBlocked(emitFileName) { + return hasEmitBlockingDiagnostics.has(toPath(emitFileName)); + } + function emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles, customTransformers) { + var declarationDiagnostics = []; + if (!emitOnlyDtsFiles) { + if (options.noEmit) { + return { diagnostics: declarationDiagnostics, sourceMaps: undefined, emittedFiles: undefined, emitSkipped: true }; + } + // If the noEmitOnError flag is set, then check if we have any errors so far. If so, + // immediately bail out. Note that we pass 'undefined' for 'sourceFile' so that we + // get any preEmit diagnostics, not just the ones + if (options.noEmitOnError) { + var diagnostics = program.getOptionsDiagnostics(cancellationToken).concat(program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken)); + if (diagnostics.length === 0 && ts.getEmitDeclarations(program.getCompilerOptions())) { + declarationDiagnostics = program.getDeclarationDiagnostics(/*sourceFile*/ undefined, cancellationToken); + } + if (diagnostics.length > 0 || declarationDiagnostics.length > 0) { + return { + diagnostics: ts.concatenate(diagnostics, declarationDiagnostics), + sourceMaps: undefined, + emittedFiles: undefined, + emitSkipped: true + }; + } + } + } + // Create the emit resolver outside of the "emitTime" tracking code below. That way + // any cost associated with it (like type checking) are appropriate associated with + // the type-checking counter. + // + // If the -out option is specified, we should not pass the source file to getEmitResolver. + // This is because in the -out scenario all files need to be emitted, and therefore all + // files need to be type checked. And the way to specify that all files need to be type + // checked is to not pass the file to getEmitResolver. + var emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile, cancellationToken); + ts.performance.mark("beforeEmit"); + var transformers = emitOnlyDtsFiles ? [] : ts.getTransformers(options, customTransformers); + var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile, // TODO: GH#18217 + emitOnlyDtsFiles, transformers, customTransformers && customTransformers.afterDeclarations); + ts.performance.mark("afterEmit"); + ts.performance.measure("Emit", "beforeEmit", "afterEmit"); + return emitResult; + } + function getSourceFile(fileName) { + return getSourceFileByPath(toPath(fileName)); + } + function getSourceFileByPath(path) { + return filesByName.get(path); + } + function getDiagnosticsHelper(sourceFile, getDiagnostics, cancellationToken) { + if (sourceFile) { + return getDiagnostics(sourceFile, cancellationToken); + } + return ts.sortAndDeduplicateDiagnostics(ts.flatMap(program.getSourceFiles(), function (sourceFile) { + if (cancellationToken) { + cancellationToken.throwIfCancellationRequested(); + } + return getDiagnostics(sourceFile, cancellationToken); + })); + } + function getSyntacticDiagnostics(sourceFile, cancellationToken) { + return getDiagnosticsHelper(sourceFile, getSyntacticDiagnosticsForFile, cancellationToken); + } + function getSemanticDiagnostics(sourceFile, cancellationToken) { + return getDiagnosticsHelper(sourceFile, getSemanticDiagnosticsForFile, cancellationToken); + } + function getDeclarationDiagnostics(sourceFile, cancellationToken) { + var options = program.getCompilerOptions(); + // collect diagnostics from the program only once if either no source file was specified or out/outFile is set (bundled emit) + if (!sourceFile || options.out || options.outFile) { + return getDeclarationDiagnosticsWorker(sourceFile, cancellationToken); + } + else { + return getDiagnosticsHelper(sourceFile, getDeclarationDiagnosticsForFile, cancellationToken); + } + } + function getSyntacticDiagnosticsForFile(sourceFile) { + // For JavaScript files, we report semantic errors for using TypeScript-only + // constructs from within a JavaScript file as syntactic errors. + if (ts.isSourceFileJS(sourceFile)) { + if (!sourceFile.additionalSyntacticDiagnostics) { + sourceFile.additionalSyntacticDiagnostics = getJSSyntacticDiagnosticsForFile(sourceFile); + } + return ts.concatenate(sourceFile.additionalSyntacticDiagnostics, sourceFile.parseDiagnostics); + } + return sourceFile.parseDiagnostics; + } + function runWithCancellationToken(func) { + try { + return func(); + } + catch (e) { + if (e instanceof ts.OperationCanceledException) { + // We were canceled while performing the operation. Because our type checker + // might be a bad state, we need to throw it away. + // + // Note: we are overly aggressive here. We do not actually *have* to throw away + // the "noDiagnosticsTypeChecker". However, for simplicity, i'd like to keep + // the lifetimes of these two TypeCheckers the same. Also, we generally only + // cancel when the user has made a change anyways. And, in that case, we (the + // program instance) will get thrown away anyways. So trying to keep one of + // these type checkers alive doesn't serve much purpose. + noDiagnosticsTypeChecker = undefined; + diagnosticsProducingTypeChecker = undefined; + } + throw e; + } + } + function getSemanticDiagnosticsForFile(sourceFile, cancellationToken) { + return getAndCacheDiagnostics(sourceFile, cancellationToken, cachedSemanticDiagnosticsForFile, getSemanticDiagnosticsForFileNoCache); + } + function getSemanticDiagnosticsForFileNoCache(sourceFile, cancellationToken) { + return runWithCancellationToken(function () { + if (ts.skipTypeChecking(sourceFile, options)) { + return ts.emptyArray; + } + var typeChecker = getDiagnosticsProducingTypeChecker(); + ts.Debug.assert(!!sourceFile.bindDiagnostics); + var isCheckJs = ts.isCheckJsEnabledForFile(sourceFile, options); + // By default, only type-check .ts, .tsx, 'Deferred' and 'External' files (external files are added by plugins) + var includeBindAndCheckDiagnostics = sourceFile.scriptKind === 3 /* TS */ || sourceFile.scriptKind === 4 /* TSX */ || + sourceFile.scriptKind === 5 /* External */ || isCheckJs || sourceFile.scriptKind === 7 /* Deferred */; + var bindDiagnostics = includeBindAndCheckDiagnostics ? sourceFile.bindDiagnostics : ts.emptyArray; + var checkDiagnostics = includeBindAndCheckDiagnostics ? typeChecker.getDiagnostics(sourceFile, cancellationToken) : ts.emptyArray; + var fileProcessingDiagnosticsInFile = fileProcessingDiagnostics.getDiagnostics(sourceFile.fileName); + var programDiagnosticsInFile = programDiagnostics.getDiagnostics(sourceFile.fileName); + var diagnostics; + for (var _i = 0, _a = [bindDiagnostics, checkDiagnostics, fileProcessingDiagnosticsInFile, programDiagnosticsInFile, isCheckJs ? sourceFile.jsDocDiagnostics : undefined]; _i < _a.length; _i++) { + var diags = _a[_i]; + if (diags) { + for (var _b = 0, diags_1 = diags; _b < diags_1.length; _b++) { + var diag = diags_1[_b]; + if (shouldReportDiagnostic(diag)) { + diagnostics = ts.append(diagnostics, diag); + } + } + } + } + return diagnostics; + }); + } + function getSuggestionDiagnostics(sourceFile, cancellationToken) { + return runWithCancellationToken(function () { + return getDiagnosticsProducingTypeChecker().getSuggestionDiagnostics(sourceFile, cancellationToken); + }); + } + /** + * Skip errors if previous line start with '// @ts-ignore' comment, not counting non-empty non-comment lines + */ + function shouldReportDiagnostic(diagnostic) { + var file = diagnostic.file, start = diagnostic.start; + if (file) { + var lineStarts = ts.getLineStarts(file); + var line = ts.computeLineAndCharacterOfPosition(lineStarts, start).line; // TODO: GH#18217 + while (line > 0) { + var previousLineText = file.text.slice(lineStarts[line - 1], lineStarts[line]); + var result = ignoreDiagnosticCommentRegEx.exec(previousLineText); + if (!result) { + // non-empty line + return true; + } + if (result[3]) { + // @ts-ignore + return false; + } + line--; + } + } + return true; + } + function getJSSyntacticDiagnosticsForFile(sourceFile) { + return runWithCancellationToken(function () { + var diagnostics = []; + var parent = sourceFile; + walk(sourceFile); + return diagnostics; + function walk(node) { + // Return directly from the case if the given node doesnt want to visit each child + // Otherwise break to visit each child + switch (parent.kind) { + case 151 /* Parameter */: + case 154 /* PropertyDeclaration */: + if (parent.questionToken === node) { + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, "?")); + return; + } + // falls through + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 196 /* FunctionExpression */: + case 239 /* FunctionDeclaration */: + case 197 /* ArrowFunction */: + case 237 /* VariableDeclaration */: + // type annotation + if (parent.type === node) { + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.types_can_only_be_used_in_a_ts_file)); + return; + } + } + switch (node.kind) { + case 248 /* ImportEqualsDeclaration */: + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.import_can_only_be_used_in_a_ts_file)); + return; + case 254 /* ExportAssignment */: + if (node.isExportEquals) { + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.export_can_only_be_used_in_a_ts_file)); + return; + } + break; + case 273 /* HeritageClause */: + var heritageClause = node; + if (heritageClause.token === 109 /* ImplementsKeyword */) { + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.implements_clauses_can_only_be_used_in_a_ts_file)); + return; + } + break; + case 241 /* InterfaceDeclaration */: + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.interface_declarations_can_only_be_used_in_a_ts_file)); + return; + case 244 /* ModuleDeclaration */: + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.module_declarations_can_only_be_used_in_a_ts_file)); + return; + case 242 /* TypeAliasDeclaration */: + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.type_aliases_can_only_be_used_in_a_ts_file)); + return; + case 243 /* EnumDeclaration */: + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.enum_declarations_can_only_be_used_in_a_ts_file)); + return; + case 213 /* NonNullExpression */: + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.non_null_assertions_can_only_be_used_in_a_ts_file)); + return; + case 212 /* AsExpression */: + diagnostics.push(createDiagnosticForNode(node.type, ts.Diagnostics.type_assertion_expressions_can_only_be_used_in_a_ts_file)); + return; + case 194 /* TypeAssertionExpression */: + ts.Debug.fail(); // Won't parse these in a JS file anyway, as they are interpreted as JSX. + } + var prevParent = parent; + parent = node; + ts.forEachChild(node, walk, walkArray); + parent = prevParent; + } + function walkArray(nodes) { + if (parent.decorators === nodes && !options.experimentalDecorators) { + diagnostics.push(createDiagnosticForNode(parent, ts.Diagnostics.Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_to_remove_this_warning)); + } + switch (parent.kind) { + case 240 /* ClassDeclaration */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 196 /* FunctionExpression */: + case 239 /* FunctionDeclaration */: + case 197 /* ArrowFunction */: + // Check type parameters + if (nodes === parent.typeParameters) { + diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.type_parameter_declarations_can_only_be_used_in_a_ts_file)); + return; + } + // falls through + case 219 /* VariableStatement */: + // Check modifiers + if (nodes === parent.modifiers) { + return checkModifiers(nodes, parent.kind === 219 /* VariableStatement */); + } + break; + case 154 /* PropertyDeclaration */: + // Check modifiers of property declaration + if (nodes === parent.modifiers) { + for (var _i = 0, _a = nodes; _i < _a.length; _i++) { + var modifier = _a[_i]; + if (modifier.kind !== 116 /* StaticKeyword */) { + diagnostics.push(createDiagnosticForNode(modifier, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, ts.tokenToString(modifier.kind))); + } + } + return; + } + break; + case 151 /* Parameter */: + // Check modifiers of parameter declaration + if (nodes === parent.modifiers) { + diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.parameter_modifiers_can_only_be_used_in_a_ts_file)); + return; + } + break; + case 191 /* CallExpression */: + case 192 /* NewExpression */: + case 211 /* ExpressionWithTypeArguments */: + case 261 /* JsxSelfClosingElement */: + case 262 /* JsxOpeningElement */: + // Check type arguments + if (nodes === parent.typeArguments) { + diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.type_arguments_can_only_be_used_in_a_ts_file)); + return; + } + break; + } + for (var _b = 0, nodes_6 = nodes; _b < nodes_6.length; _b++) { + var node = nodes_6[_b]; + walk(node); + } + } + function checkModifiers(modifiers, isConstValid) { + for (var _i = 0, modifiers_1 = modifiers; _i < modifiers_1.length; _i++) { + var modifier = modifiers_1[_i]; + switch (modifier.kind) { + case 77 /* ConstKeyword */: + if (isConstValid) { + continue; + } + // to report error, + // falls through + case 115 /* PublicKeyword */: + case 113 /* PrivateKeyword */: + case 114 /* ProtectedKeyword */: + case 133 /* ReadonlyKeyword */: + case 125 /* DeclareKeyword */: + case 118 /* AbstractKeyword */: + diagnostics.push(createDiagnosticForNode(modifier, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, ts.tokenToString(modifier.kind))); + break; + // These are all legal modifiers. + case 116 /* StaticKeyword */: + case 85 /* ExportKeyword */: + case 80 /* DefaultKeyword */: + } + } + } + function createDiagnosticForNodeArray(nodes, message, arg0, arg1, arg2) { + var start = nodes.pos; + return ts.createFileDiagnostic(sourceFile, start, nodes.end - start, message, arg0, arg1, arg2); + } + // Since these are syntactic diagnostics, parent might not have been set + // this means the sourceFile cannot be infered from the node + function createDiagnosticForNode(node, message, arg0, arg1, arg2) { + return ts.createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2); + } + }); + } + function getDeclarationDiagnosticsWorker(sourceFile, cancellationToken) { + return getAndCacheDiagnostics(sourceFile, cancellationToken, cachedDeclarationDiagnosticsForFile, getDeclarationDiagnosticsForFileNoCache); + } + function getDeclarationDiagnosticsForFileNoCache(sourceFile, cancellationToken) { + return runWithCancellationToken(function () { + var resolver = getDiagnosticsProducingTypeChecker().getEmitResolver(sourceFile, cancellationToken); + // Don't actually write any files since we're just getting diagnostics. + return ts.getDeclarationDiagnostics(getEmitHost(ts.noop), resolver, sourceFile); + }); + } + function getAndCacheDiagnostics(sourceFile, cancellationToken, cache, getDiagnostics) { + var cachedResult = sourceFile + ? cache.perFile && cache.perFile.get(sourceFile.path) + : cache.allDiagnostics; + if (cachedResult) { + return cachedResult; + } + var result = getDiagnostics(sourceFile, cancellationToken) || ts.emptyArray; // TODO: GH#18217 + if (sourceFile) { + if (!cache.perFile) { + cache.perFile = ts.createMap(); + } + cache.perFile.set(sourceFile.path, result); + } + else { + cache.allDiagnostics = result; + } + return result; + } + function getDeclarationDiagnosticsForFile(sourceFile, cancellationToken) { + return sourceFile.isDeclarationFile ? [] : getDeclarationDiagnosticsWorker(sourceFile, cancellationToken); + } + function getOptionsDiagnostics() { + return ts.sortAndDeduplicateDiagnostics(ts.concatenate(fileProcessingDiagnostics.getGlobalDiagnostics(), ts.concatenate(programDiagnostics.getGlobalDiagnostics(), getOptionsDiagnosticsOfConfigFile()))); + } + function getOptionsDiagnosticsOfConfigFile() { + if (!options.configFile) { + return ts.emptyArray; + } + var diagnostics = programDiagnostics.getDiagnostics(options.configFile.fileName); + forEachResolvedProjectReference(function (resolvedRef) { + if (resolvedRef) { + diagnostics = ts.concatenate(diagnostics, programDiagnostics.getDiagnostics(resolvedRef.sourceFile.fileName)); + } + }); + return diagnostics; + } + function getGlobalDiagnostics() { + return rootNames.length ? ts.sortAndDeduplicateDiagnostics(getDiagnosticsProducingTypeChecker().getGlobalDiagnostics().slice()) : ts.emptyArray; + } + function getConfigFileParsingDiagnostics() { + return configFileParsingDiagnostics || ts.emptyArray; + } + function processRootFile(fileName, isDefaultLib, ignoreNoDefaultLib) { + processSourceFile(ts.normalizePath(fileName), isDefaultLib, ignoreNoDefaultLib, /*packageId*/ undefined); + } + function fileReferenceIsEqualTo(a, b) { + return a.fileName === b.fileName; + } + function moduleNameIsEqualTo(a, b) { + return a.kind === 72 /* Identifier */ + ? b.kind === 72 /* Identifier */ && a.escapedText === b.escapedText + : b.kind === 10 /* StringLiteral */ && a.text === b.text; + } + function collectExternalModuleReferences(file) { + if (file.imports) { + return; + } + var isJavaScriptFile = ts.isSourceFileJS(file); + var isExternalModuleFile = ts.isExternalModule(file); + // file.imports may not be undefined if there exists dynamic import + var imports; + var moduleAugmentations; + var ambientModules; + // If we are importing helpers, we need to add a synthetic reference to resolve the + // helpers library. + if (options.importHelpers + && (options.isolatedModules || isExternalModuleFile) + && !file.isDeclarationFile) { + // synthesize 'import "tslib"' declaration + var externalHelpersModuleReference = ts.createLiteral(ts.externalHelpersModuleNameText); + var importDecl = ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*importClause*/ undefined, externalHelpersModuleReference); + ts.addEmitFlags(importDecl, 67108864 /* NeverApplyImportHelper */); + externalHelpersModuleReference.parent = importDecl; + importDecl.parent = file; + imports = [externalHelpersModuleReference]; + } + for (var _i = 0, _a = file.statements; _i < _a.length; _i++) { + var node = _a[_i]; + collectModuleReferences(node, /*inAmbientModule*/ false); + } + if ((file.flags & 524288 /* PossiblyContainsDynamicImport */) || isJavaScriptFile) { + collectDynamicImportOrRequireCalls(file); + } + file.imports = imports || ts.emptyArray; + file.moduleAugmentations = moduleAugmentations || ts.emptyArray; + file.ambientModuleNames = ambientModules || ts.emptyArray; + return; + function collectModuleReferences(node, inAmbientModule) { + if (ts.isAnyImportOrReExport(node)) { + var moduleNameExpr = ts.getExternalModuleName(node); + // TypeScript 1.0 spec (April 2014): 12.1.6 + // An ExternalImportDeclaration in an AmbientExternalModuleDeclaration may reference other external modules + // only through top - level external module names. Relative external module names are not permitted. + if (moduleNameExpr && ts.isStringLiteral(moduleNameExpr) && moduleNameExpr.text && (!inAmbientModule || !ts.isExternalModuleNameRelative(moduleNameExpr.text))) { + imports = ts.append(imports, moduleNameExpr); + } + } + else if (ts.isModuleDeclaration(node)) { + if (ts.isAmbientModule(node) && (inAmbientModule || ts.hasModifier(node, 2 /* Ambient */) || file.isDeclarationFile)) { + var nameText = ts.getTextOfIdentifierOrLiteral(node.name); + // Ambient module declarations can be interpreted as augmentations for some existing external modules. + // This will happen in two cases: + // - if current file is external module then module augmentation is a ambient module declaration defined in the top level scope + // - if current file is not external module then module augmentation is an ambient module declaration with non-relative module name + // immediately nested in top level ambient module declaration . + if (isExternalModuleFile || (inAmbientModule && !ts.isExternalModuleNameRelative(nameText))) { + (moduleAugmentations || (moduleAugmentations = [])).push(node.name); + } + else if (!inAmbientModule) { + if (file.isDeclarationFile) { + // for global .d.ts files record name of ambient module + (ambientModules || (ambientModules = [])).push(nameText); + } + // An AmbientExternalModuleDeclaration declares an external module. + // This type of declaration is permitted only in the global module. + // The StringLiteral must specify a top - level external module name. + // Relative external module names are not permitted + // NOTE: body of ambient module is always a module block, if it exists + var body = node.body; + if (body) { + for (var _i = 0, _a = body.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + collectModuleReferences(statement, /*inAmbientModule*/ true); + } + } + } + } + } + } + function collectDynamicImportOrRequireCalls(file) { + var r = /import|require/g; + while (r.exec(file.text) !== null) { + var node = getNodeAtPosition(file, r.lastIndex); + if (ts.isRequireCall(node, /*checkArgumentIsStringLiteralLike*/ true)) { + imports = ts.append(imports, node.arguments[0]); + } + // we have to check the argument list has length of 1. We will still have to process these even though we have parsing error. + else if (ts.isImportCall(node) && node.arguments.length === 1 && ts.isStringLiteralLike(node.arguments[0])) { + imports = ts.append(imports, node.arguments[0]); + } + else if (ts.isLiteralImportTypeNode(node)) { + imports = ts.append(imports, node.argument.literal); + } + } + } + /** Returns a token if position is in [start-of-leading-trivia, end), includes JSDoc only in JS files */ + function getNodeAtPosition(sourceFile, position) { + var current = sourceFile; + var getContainingChild = function (child) { + if (child.pos <= position && (position < child.end || (position === child.end && (child.kind === 1 /* EndOfFileToken */)))) { + return child; + } + }; + while (true) { + var child = isJavaScriptFile && ts.hasJSDocNodes(current) && ts.forEach(current.jsDoc, getContainingChild) || ts.forEachChild(current, getContainingChild); + if (!child) { + return current; + } + current = child; + } + } + } + function getLibFileFromReference(ref) { + var libName = ref.fileName.toLocaleLowerCase(); + var libFileName = ts.libMap.get(libName); + if (libFileName) { + return getSourceFile(ts.combinePaths(defaultLibraryPath, libFileName)); + } + } + /** This should have similar behavior to 'processSourceFile' without diagnostics or mutation. */ + function getSourceFileFromReference(referencingFile, ref) { + return getSourceFileFromReferenceWorker(resolveTripleslashReference(ref.fileName, referencingFile.fileName), function (fileName) { return filesByName.get(toPath(fileName)); }); + } + function getSourceFileFromReferenceWorker(fileName, getSourceFile, fail, refFile) { + if (ts.hasExtension(fileName)) { + if (!options.allowNonTsExtensions && !ts.forEach(supportedExtensionsWithJsonIfResolveJsonModule, function (extension) { return ts.fileExtensionIs(host.getCanonicalFileName(fileName), extension); })) { + if (fail) + fail(ts.Diagnostics.File_0_has_unsupported_extension_The_only_supported_extensions_are_1, fileName, "'" + supportedExtensions.join("', '") + "'"); + return undefined; + } + var sourceFile = getSourceFile(fileName); + if (fail) { + if (!sourceFile) { + var redirect = getProjectReferenceRedirect(fileName); + if (redirect) { + fail(ts.Diagnostics.Output_file_0_has_not_been_built_from_source_file_1, redirect, fileName); + } + else { + fail(ts.Diagnostics.File_0_not_found, fileName); + } + } + else if (refFile && host.getCanonicalFileName(fileName) === host.getCanonicalFileName(refFile.fileName)) { + fail(ts.Diagnostics.A_file_cannot_have_a_reference_to_itself); + } + } + return sourceFile; + } + else { + var sourceFileNoExtension = options.allowNonTsExtensions && getSourceFile(fileName); + if (sourceFileNoExtension) + return sourceFileNoExtension; + if (fail && options.allowNonTsExtensions) { + fail(ts.Diagnostics.File_0_not_found, fileName); + return undefined; + } + var sourceFileWithAddedExtension = ts.forEach(supportedExtensions, function (extension) { return getSourceFile(fileName + extension); }); + if (fail && !sourceFileWithAddedExtension) + fail(ts.Diagnostics.File_0_not_found, fileName + ".ts" /* Ts */); + return sourceFileWithAddedExtension; + } + } + /** This has side effects through `findSourceFile`. */ + function processSourceFile(fileName, isDefaultLib, ignoreNoDefaultLib, packageId, refFile, refPos, refEnd) { + getSourceFileFromReferenceWorker(fileName, function (fileName) { return findSourceFile(fileName, toPath(fileName), isDefaultLib, ignoreNoDefaultLib, refFile, refPos, refEnd, packageId); }, // TODO: GH#18217 + function (diagnostic) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + fileProcessingDiagnostics.add(refFile !== undefined && refEnd !== undefined && refPos !== undefined + ? ts.createFileDiagnostic.apply(void 0, [refFile, refPos, refEnd - refPos, diagnostic].concat(args)) : ts.createCompilerDiagnostic.apply(void 0, [diagnostic].concat(args))); + }, refFile); + } + function reportFileNamesDifferOnlyInCasingError(fileName, existingFileName, refFile, refPos, refEnd) { + if (refFile !== undefined && refPos !== undefined && refEnd !== undefined) { + fileProcessingDiagnostics.add(ts.createFileDiagnostic(refFile, refPos, refEnd - refPos, ts.Diagnostics.File_name_0_differs_from_already_included_file_name_1_only_in_casing, fileName, existingFileName)); + } + else { + fileProcessingDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_name_0_differs_from_already_included_file_name_1_only_in_casing, fileName, existingFileName)); + } + } + function createRedirectSourceFile(redirectTarget, unredirected, fileName, path, resolvedPath, originalFileName) { + var redirect = Object.create(redirectTarget); + redirect.fileName = fileName; + redirect.path = path; + redirect.resolvedPath = resolvedPath; + redirect.originalFileName = originalFileName; + redirect.redirectInfo = { redirectTarget: redirectTarget, unredirected: unredirected }; + sourceFilesFoundSearchingNodeModules.set(path, currentNodeModulesDepth > 0); + Object.defineProperties(redirect, { + id: { + get: function () { return this.redirectInfo.redirectTarget.id; }, + set: function (value) { this.redirectInfo.redirectTarget.id = value; }, + }, + symbol: { + get: function () { return this.redirectInfo.redirectTarget.symbol; }, + set: function (value) { this.redirectInfo.redirectTarget.symbol = value; }, + }, + }); + return redirect; + } + // Get source file from normalized fileName + function findSourceFile(fileName, path, isDefaultLib, ignoreNoDefaultLib, refFile, refPos, refEnd, packageId) { + var originalFileName = fileName; + if (filesByName.has(path)) { + var file_1 = filesByName.get(path); + // try to check if we've already seen this file but with a different casing in path + // NOTE: this only makes sense for case-insensitive file systems, and only on files which are not redirected + if (file_1 && options.forceConsistentCasingInFileNames) { + var inputName = fileName; + var checkedName = file_1.fileName; + var isRedirect = toPath(checkedName) !== toPath(inputName); + if (isRedirect) { + inputName = getProjectReferenceRedirect(fileName) || fileName; + } + if (ts.getNormalizedAbsolutePath(checkedName, currentDirectory) !== ts.getNormalizedAbsolutePath(inputName, currentDirectory)) { + reportFileNamesDifferOnlyInCasingError(inputName, checkedName, refFile, refPos, refEnd); + } + } + // If the file was previously found via a node_modules search, but is now being processed as a root file, + // then everything it sucks in may also be marked incorrectly, and needs to be checked again. + if (file_1 && sourceFilesFoundSearchingNodeModules.get(file_1.path) && currentNodeModulesDepth === 0) { + sourceFilesFoundSearchingNodeModules.set(file_1.path, false); + if (!options.noResolve) { + processReferencedFiles(file_1, isDefaultLib); + processTypeReferenceDirectives(file_1); + } + processLibReferenceDirectives(file_1); + modulesWithElidedImports.set(file_1.path, false); + processImportedModules(file_1); + } + // See if we need to reprocess the imports due to prior skipped imports + else if (file_1 && modulesWithElidedImports.get(file_1.path)) { + if (currentNodeModulesDepth < maxNodeModuleJsDepth) { + modulesWithElidedImports.set(file_1.path, false); + processImportedModules(file_1); + } + } + return file_1; + } + var redirectedPath; + if (refFile) { + var redirect = getProjectReferenceRedirect(fileName); + if (redirect) { + (refFile.redirectedReferences || (refFile.redirectedReferences = [])).push(fileName); + fileName = redirect; + // Once we start redirecting to a file, we can potentially come back to it + // via a back-reference from another file in the .d.ts folder. If that happens we'll + // end up trying to add it to the program *again* because we were tracking it via its + // original (un-redirected) name. So we have to map both the original path and the redirected path + // to the source file we're about to find/create + redirectedPath = toPath(redirect); + } + } + // We haven't looked for this file, do so now and cache result + var file = host.getSourceFile(fileName, options.target, function (hostErrorMessage) { + if (refFile !== undefined && refPos !== undefined && refEnd !== undefined) { + fileProcessingDiagnostics.add(ts.createFileDiagnostic(refFile, refPos, refEnd - refPos, ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, hostErrorMessage)); + } + else { + fileProcessingDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, hostErrorMessage)); + } + }, shouldCreateNewSourceFile); + if (packageId) { + var packageIdKey = ts.packageIdToString(packageId); + var fileFromPackageId = packageIdToSourceFile.get(packageIdKey); + if (fileFromPackageId) { + // Some other SourceFile already exists with this package name and version. + // Instead of creating a duplicate, just redirect to the existing one. + var dupFile = createRedirectSourceFile(fileFromPackageId, file, fileName, path, toPath(fileName), originalFileName); // TODO: GH#18217 + redirectTargetsMap.add(fileFromPackageId.path, fileName); + addFileToFilesByName(dupFile, path, redirectedPath); + sourceFileToPackageName.set(path, packageId.name); + processingOtherFiles.push(dupFile); + return dupFile; + } + else if (file) { + // This is the first source file to have this packageId. + packageIdToSourceFile.set(packageIdKey, file); + sourceFileToPackageName.set(path, packageId.name); + } + } + addFileToFilesByName(file, path, redirectedPath); + if (file) { + sourceFilesFoundSearchingNodeModules.set(path, currentNodeModulesDepth > 0); + file.path = path; + file.resolvedPath = toPath(fileName); + file.originalFileName = originalFileName; + if (host.useCaseSensitiveFileNames()) { + var pathLowerCase = path.toLowerCase(); + // for case-sensitive file systems check if we've already seen some file with similar filename ignoring case + var existingFile = filesByNameIgnoreCase.get(pathLowerCase); + if (existingFile) { + reportFileNamesDifferOnlyInCasingError(fileName, existingFile.fileName, refFile, refPos, refEnd); + } + else { + filesByNameIgnoreCase.set(pathLowerCase, file); + } + } + skipDefaultLib = skipDefaultLib || (file.hasNoDefaultLib && !ignoreNoDefaultLib); + if (!options.noResolve) { + processReferencedFiles(file, isDefaultLib); + processTypeReferenceDirectives(file); + } + processLibReferenceDirectives(file); + // always process imported modules to record module name resolutions + processImportedModules(file); + if (isDefaultLib) { + processingDefaultLibFiles.push(file); + } + else { + processingOtherFiles.push(file); + } + } + return file; + } + function addFileToFilesByName(file, path, redirectedPath) { + filesByName.set(path, file); + if (redirectedPath) { + filesByName.set(redirectedPath, file); + } + } + function getProjectReferenceRedirect(fileName) { + // Ignore dts or any of the non ts files + if (!resolvedProjectReferences || !resolvedProjectReferences.length || ts.fileExtensionIs(fileName, ".d.ts" /* Dts */) || !ts.fileExtensionIsOneOf(fileName, ts.supportedTSExtensions)) { + return undefined; + } + // If this file is produced by a referenced project, we need to rewrite it to + // look in the output folder of the referenced project rather than the input + var referencedProject = getResolvedProjectReferenceToRedirect(fileName); + if (!referencedProject) { + return undefined; + } + var out = referencedProject.commandLine.options.outFile || referencedProject.commandLine.options.out; + return out ? + ts.changeExtension(out, ".d.ts" /* Dts */) : + ts.getOutputDeclarationFileName(fileName, referencedProject.commandLine); + } + /** + * Get the referenced project if the file is input file from that reference project + */ + function getResolvedProjectReferenceToRedirect(fileName) { + if (mapFromFileToProjectReferenceRedirects === undefined) { + mapFromFileToProjectReferenceRedirects = ts.createMap(); + forEachResolvedProjectReference(function (referencedProject, referenceProjectPath) { + // not input file from the referenced project, ignore + if (referencedProject && + toPath(options.configFilePath) !== referenceProjectPath) { + referencedProject.commandLine.fileNames.forEach(function (f) { + return mapFromFileToProjectReferenceRedirects.set(toPath(f), referenceProjectPath); + }); + } + }); + } + var referencedProjectPath = mapFromFileToProjectReferenceRedirects.get(toPath(fileName)); + return referencedProjectPath && getResolvedProjectReferenceByPath(referencedProjectPath); + } + function forEachResolvedProjectReference(cb) { + return forEachProjectReference(projectReferences, resolvedProjectReferences, function (resolvedRef, index, parent) { + var ref = (parent ? parent.commandLine.projectReferences : projectReferences)[index]; + var resolvedRefPath = toPath(resolveProjectReferencePath(ref)); + return cb(resolvedRef, resolvedRefPath); + }); + } + function forEachProjectReference(projectReferences, resolvedProjectReferences, cbResolvedRef, cbRef) { + var seenResolvedRefs; + return worker(projectReferences, resolvedProjectReferences, /*parent*/ undefined, cbResolvedRef, cbRef); + function worker(projectReferences, resolvedProjectReferences, parent, cbResolvedRef, cbRef) { + // Visit project references first + if (cbRef) { + var result = cbRef(projectReferences, parent); + if (result) { + return result; + } + } + return ts.forEach(resolvedProjectReferences, function (resolvedRef, index) { + if (ts.contains(seenResolvedRefs, resolvedRef)) { + // ignore recursives + return undefined; + } + var result = cbResolvedRef(resolvedRef, index, parent); + if (result) { + return result; + } + if (!resolvedRef) + return undefined; + (seenResolvedRefs || (seenResolvedRefs = [])).push(resolvedRef); + return worker(resolvedRef.commandLine.projectReferences, resolvedRef.references, resolvedRef, cbResolvedRef, cbRef); + }); + } + } + function getResolvedProjectReferenceByPath(projectReferencePath) { + if (!projectReferenceRedirects) { + return undefined; + } + return projectReferenceRedirects.get(projectReferencePath) || undefined; + } + function processReferencedFiles(file, isDefaultLib) { + ts.forEach(file.referencedFiles, function (ref) { + var referencedFileName = resolveTripleslashReference(ref.fileName, file.originalFileName); + processSourceFile(referencedFileName, isDefaultLib, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined, file, ref.pos, ref.end); + }); + } + function processTypeReferenceDirectives(file) { + // We lower-case all type references because npm automatically lowercases all packages. See GH#9824. + var typeDirectives = ts.map(file.typeReferenceDirectives, function (ref) { return ref.fileName.toLocaleLowerCase(); }); + if (!typeDirectives) { + return; + } + var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeDirectives, file.originalFileName, getResolvedProjectReferenceToRedirect(file.originalFileName)); + for (var i = 0; i < typeDirectives.length; i++) { + var ref = file.typeReferenceDirectives[i]; + var resolvedTypeReferenceDirective = resolutions[i]; + // store resolved type directive on the file + var fileName = ref.fileName.toLocaleLowerCase(); + ts.setResolvedTypeReferenceDirective(file, fileName, resolvedTypeReferenceDirective); + processTypeReferenceDirective(fileName, resolvedTypeReferenceDirective, file, ref.pos, ref.end); + } + } + function processTypeReferenceDirective(typeReferenceDirective, resolvedTypeReferenceDirective, refFile, refPos, refEnd) { + // If we already found this library as a primary reference - nothing to do + var previousResolution = resolvedTypeReferenceDirectives.get(typeReferenceDirective); + if (previousResolution && previousResolution.primary) { + return; + } + var saveResolution = true; + if (resolvedTypeReferenceDirective) { + if (resolvedTypeReferenceDirective.isExternalLibraryImport) + currentNodeModulesDepth++; + if (resolvedTypeReferenceDirective.primary) { + // resolved from the primary path + processSourceFile(resolvedTypeReferenceDirective.resolvedFileName, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, resolvedTypeReferenceDirective.packageId, refFile, refPos, refEnd); // TODO: GH#18217 + } + else { + // If we already resolved to this file, it must have been a secondary reference. Check file contents + // for sameness and possibly issue an error + if (previousResolution) { + // Don't bother reading the file again if it's the same file. + if (resolvedTypeReferenceDirective.resolvedFileName !== previousResolution.resolvedFileName) { + var otherFileText = host.readFile(resolvedTypeReferenceDirective.resolvedFileName); + if (otherFileText !== getSourceFile(previousResolution.resolvedFileName).text) { + fileProcessingDiagnostics.add(createDiagnostic(refFile, refPos, refEnd, // TODO: GH#18217 + ts.Diagnostics.Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict, typeReferenceDirective, resolvedTypeReferenceDirective.resolvedFileName, previousResolution.resolvedFileName)); + } + } + // don't overwrite previous resolution result + saveResolution = false; + } + else { + // First resolution of this library + processSourceFile(resolvedTypeReferenceDirective.resolvedFileName, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, resolvedTypeReferenceDirective.packageId, refFile, refPos, refEnd); + } + } + if (resolvedTypeReferenceDirective.isExternalLibraryImport) + currentNodeModulesDepth--; + } + else { + fileProcessingDiagnostics.add(createDiagnostic(refFile, refPos, refEnd, ts.Diagnostics.Cannot_find_type_definition_file_for_0, typeReferenceDirective)); // TODO: GH#18217 + } + if (saveResolution) { + resolvedTypeReferenceDirectives.set(typeReferenceDirective, resolvedTypeReferenceDirective); + } + } + function processLibReferenceDirectives(file) { + ts.forEach(file.libReferenceDirectives, function (libReference) { + var libName = libReference.fileName.toLocaleLowerCase(); + var libFileName = ts.libMap.get(libName); + if (libFileName) { + // we ignore any 'no-default-lib' reference set on this file. + processRootFile(ts.combinePaths(defaultLibraryPath, libFileName), /*isDefaultLib*/ true, /*ignoreNoDefaultLib*/ true); + } + else { + var unqualifiedLibName = ts.removeSuffix(ts.removePrefix(libName, "lib."), ".d.ts"); + var suggestion = ts.getSpellingSuggestion(unqualifiedLibName, ts.libs, ts.identity); + var message = suggestion ? ts.Diagnostics.Cannot_find_lib_definition_for_0_Did_you_mean_1 : ts.Diagnostics.Cannot_find_lib_definition_for_0; + fileProcessingDiagnostics.add(createDiagnostic(file, libReference.pos, libReference.end, message, libName, suggestion)); + } + }); + } + function createDiagnostic(refFile, refPos, refEnd, message) { + var args = []; + for (var _i = 4; _i < arguments.length; _i++) { + args[_i - 4] = arguments[_i]; + } + if (refFile === undefined || refPos === undefined || refEnd === undefined) { + return ts.createCompilerDiagnostic.apply(void 0, [message].concat(args)); + } + else { + return ts.createFileDiagnostic.apply(void 0, [refFile, refPos, refEnd - refPos, message].concat(args)); + } + } + function getCanonicalFileName(fileName) { + return host.getCanonicalFileName(fileName); + } + function processImportedModules(file) { + collectExternalModuleReferences(file); + if (file.imports.length || file.moduleAugmentations.length) { + // Because global augmentation doesn't have string literal name, we can check for global augmentation as such. + var moduleNames = getModuleNames(file); + var resolutions = resolveModuleNamesReusingOldState(moduleNames, ts.getNormalizedAbsolutePath(file.originalFileName, currentDirectory), file); + ts.Debug.assert(resolutions.length === moduleNames.length); + for (var i = 0; i < moduleNames.length; i++) { + var resolution = resolutions[i]; + ts.setResolvedModule(file, moduleNames[i], resolution); + if (!resolution) { + continue; + } + var isFromNodeModulesSearch = resolution.isExternalLibraryImport; + var isJsFile = !ts.resolutionExtensionIsTSOrJson(resolution.extension); + var isJsFileFromNodeModules = isFromNodeModulesSearch && isJsFile; + var resolvedFileName = resolution.resolvedFileName; + if (isFromNodeModulesSearch) { + currentNodeModulesDepth++; + } + // add file to program only if: + // - resolution was successful + // - noResolve is falsy + // - module name comes from the list of imports + // - it's not a top level JavaScript module that exceeded the search max + var elideImport = isJsFileFromNodeModules && currentNodeModulesDepth > maxNodeModuleJsDepth; + // Don't add the file if it has a bad extension (e.g. 'tsx' if we don't have '--allowJs') + // This may still end up being an untyped module -- the file won't be included but imports will be allowed. + var shouldAddFile = resolvedFileName + && !getResolutionDiagnostic(options, resolution) + && !options.noResolve + && i < file.imports.length + && !elideImport + && !(isJsFile && !options.allowJs) + && (ts.isInJSFile(file.imports[i]) || !(file.imports[i].flags & 2097152 /* JSDoc */)); + if (elideImport) { + modulesWithElidedImports.set(file.path, true); + } + else if (shouldAddFile) { + var path = toPath(resolvedFileName); + var pos = ts.skipTrivia(file.text, file.imports[i].pos); + findSourceFile(resolvedFileName, path, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, file, pos, file.imports[i].end, resolution.packageId); + } + if (isFromNodeModulesSearch) { + currentNodeModulesDepth--; + } + } + } + else { + // no imports - drop cached module resolutions + file.resolvedModules = undefined; + } + } + function computeCommonSourceDirectory(sourceFiles) { + var fileNames = ts.mapDefined(sourceFiles, function (file) { return file.isDeclarationFile ? undefined : file.fileName; }); + return computeCommonSourceDirectoryOfFilenames(fileNames, currentDirectory, getCanonicalFileName); + } + function checkSourceFilesBelongToPath(sourceFiles, rootDirectory) { + var allFilesBelongToPath = true; + var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory)); + for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) { + var sourceFile = sourceFiles_2[_i]; + if (!sourceFile.isDeclarationFile) { + var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); + if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, sourceFile.fileName, rootDirectory)); + allFilesBelongToPath = false; + } + } + } + return allFilesBelongToPath; + } + function parseProjectReferenceConfigFile(ref) { + if (!projectReferenceRedirects) { + projectReferenceRedirects = ts.createMap(); + } + // The actual filename (i.e. add "/tsconfig.json" if necessary) + var refPath = resolveProjectReferencePath(ref); + var sourceFilePath = toPath(refPath); + var fromCache = projectReferenceRedirects.get(sourceFilePath); + if (fromCache !== undefined) { + return fromCache || undefined; + } + // An absolute path pointing to the containing directory of the config file + var basePath = ts.getNormalizedAbsolutePath(ts.getDirectoryPath(refPath), host.getCurrentDirectory()); + var sourceFile = host.getSourceFile(refPath, 100 /* JSON */); + addFileToFilesByName(sourceFile, sourceFilePath, /*redirectedPath*/ undefined); + if (sourceFile === undefined) { + projectReferenceRedirects.set(sourceFilePath, false); + return undefined; + } + sourceFile.path = sourceFilePath; + sourceFile.resolvedPath = sourceFilePath; + sourceFile.originalFileName = refPath; + var commandLine = ts.parseJsonSourceFileConfigFileContent(sourceFile, configParsingHost, basePath, /*existingOptions*/ undefined, refPath); + var resolvedRef = { commandLine: commandLine, sourceFile: sourceFile }; + projectReferenceRedirects.set(sourceFilePath, resolvedRef); + if (commandLine.projectReferences) { + resolvedRef.references = commandLine.projectReferences.map(parseProjectReferenceConfigFile); + } + return resolvedRef; + } + function verifyCompilerOptions() { + if (options.strictPropertyInitialization && !ts.getStrictOptionValue(options, "strictNullChecks")) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "strictPropertyInitialization", "strictNullChecks"); + } + if (options.isolatedModules) { + if (ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, getEmitDeclarationOptionName(options), "isolatedModules"); + } + if (options.noEmitOnError) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmitOnError", "isolatedModules"); + } + if (options.out) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "out", "isolatedModules"); + } + if (options.outFile) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "outFile", "isolatedModules"); + } + } + if (options.inlineSourceMap) { + if (options.sourceMap) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "sourceMap", "inlineSourceMap"); + } + if (options.mapRoot) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "mapRoot", "inlineSourceMap"); + } + } + if (options.paths && options.baseUrl === undefined) { + createDiagnosticForOptionName(ts.Diagnostics.Option_paths_cannot_be_used_without_specifying_baseUrl_option, "paths"); + } + if (options.composite) { + if (options.declaration === false) { + createDiagnosticForOptionName(ts.Diagnostics.Composite_projects_may_not_disable_declaration_emit, "declaration"); + } + } + verifyProjectReferences(); + // List of collected files is complete; validate exhautiveness if this is a project with a file list + if (options.composite) { + var sourceFiles = files.filter(function (f) { return !f.isDeclarationFile; }); + if (rootNames.length < sourceFiles.length) { + var normalizedRootNames = rootNames.map(function (r) { return ts.normalizePath(r).toLowerCase(); }); + for (var _i = 0, _a = sourceFiles.map(function (f) { return ts.normalizePath(f.path).toLowerCase(); }); _i < _a.length; _i++) { + var file = _a[_i]; + if (normalizedRootNames.indexOf(file) === -1) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern, file)); + } + } + } + } + if (options.paths) { + for (var key in options.paths) { + if (!ts.hasProperty(options.paths, key)) { + continue; + } + if (!ts.hasZeroOrOneAsteriskCharacter(key)) { + createDiagnosticForOptionPaths(/*onKey*/ true, key, ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, key); + } + if (ts.isArray(options.paths[key])) { + var len = options.paths[key].length; + if (len === 0) { + createDiagnosticForOptionPaths(/*onKey*/ false, key, ts.Diagnostics.Substitutions_for_pattern_0_shouldn_t_be_an_empty_array, key); + } + for (var i = 0; i < len; i++) { + var subst = options.paths[key][i]; + var typeOfSubst = typeof subst; + if (typeOfSubst === "string") { + if (!ts.hasZeroOrOneAsteriskCharacter(subst)) { + createDiagnosticForOptionPathKeyValue(key, i, ts.Diagnostics.Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character, subst, key); + } + } + else { + createDiagnosticForOptionPathKeyValue(key, i, ts.Diagnostics.Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2, subst, key, typeOfSubst); + } + } + } + else { + createDiagnosticForOptionPaths(/*onKey*/ false, key, ts.Diagnostics.Substitutions_for_pattern_0_should_be_an_array, key); + } + } + } + if (!options.sourceMap && !options.inlineSourceMap) { + if (options.inlineSources) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided, "inlineSources"); + } + if (options.sourceRoot) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided, "sourceRoot"); + } + } + if (options.out && options.outFile) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "out", "outFile"); + } + if (options.mapRoot && !(options.sourceMap || options.declarationMap)) { + // Error to specify --mapRoot without --sourcemap + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "mapRoot", "sourceMap", "declarationMap"); + } + if (options.declarationDir) { + if (!ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "declarationDir", "declaration", "composite"); + } + if (options.out || options.outFile) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "declarationDir", options.out ? "out" : "outFile"); + } + } + if (options.declarationMap && !ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "declarationMap", "declaration", "composite"); + } + if (options.lib && options.noLib) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "lib", "noLib"); + } + if (options.noImplicitUseStrict && ts.getStrictOptionValue(options, "alwaysStrict")) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noImplicitUseStrict", "alwaysStrict"); + } + var languageVersion = options.target || 0 /* ES3 */; + var outFile = options.outFile || options.out; + var firstNonAmbientExternalModuleSourceFile = ts.find(files, function (f) { return ts.isExternalModule(f) && !f.isDeclarationFile; }); + if (options.isolatedModules) { + if (options.module === ts.ModuleKind.None && languageVersion < 2 /* ES2015 */) { + createDiagnosticForOptionName(ts.Diagnostics.Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher, "isolatedModules", "target"); + } + var firstNonExternalModuleSourceFile = ts.find(files, function (f) { return !ts.isExternalModule(f) && !f.isDeclarationFile && f.scriptKind !== 6 /* JSON */; }); + if (firstNonExternalModuleSourceFile) { + var span = ts.getErrorSpanForNode(firstNonExternalModuleSourceFile, firstNonExternalModuleSourceFile); + programDiagnostics.add(ts.createFileDiagnostic(firstNonExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided)); + } + } + else if (firstNonAmbientExternalModuleSourceFile && languageVersion < 2 /* ES2015 */ && options.module === ts.ModuleKind.None) { + // We cannot use createDiagnosticFromNode because nodes do not have parents yet + var span = ts.getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, firstNonAmbientExternalModuleSourceFile.externalModuleIndicator); + programDiagnostics.add(ts.createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_use_imports_exports_or_module_augmentations_when_module_is_none)); + } + // Cannot specify module gen that isn't amd or system with --out + if (outFile && !options.emitDeclarationOnly) { + if (options.module && !(options.module === ts.ModuleKind.AMD || options.module === ts.ModuleKind.System)) { + createDiagnosticForOptionName(ts.Diagnostics.Only_amd_and_system_modules_are_supported_alongside_0, options.out ? "out" : "outFile", "module"); + } + else if (options.module === undefined && firstNonAmbientExternalModuleSourceFile) { + var span = ts.getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, firstNonAmbientExternalModuleSourceFile.externalModuleIndicator); + programDiagnostics.add(ts.createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system, options.out ? "out" : "outFile")); + } + } + if (options.resolveJsonModule) { + if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { + createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy, "resolveJsonModule"); + } + // Any emit other than common js, amd, es2015 or esnext is error + else if (!ts.hasJsonModuleEmitEnabled(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_esNext, "resolveJsonModule", "module"); + } + } + // there has to be common source directory if user specified --outdir || --sourceRoot + // if user specified --mapRoot, there needs to be common source directory if there would be multiple files being emitted + if (options.outDir || // there is --outDir specified + options.sourceRoot || // there is --sourceRoot specified + options.mapRoot) { // there is --mapRoot specified + // Precalculate and cache the common source directory + var dir = getCommonSourceDirectory(); + // If we failed to find a good common directory, but outDir is specified and at least one of our files is on a windows drive/URL/other resource, add a failure + if (options.outDir && dir === "" && files.some(function (file) { return ts.getRootLength(file.fileName) > 1; })) { + createDiagnosticForOptionName(ts.Diagnostics.Cannot_find_the_common_subdirectory_path_for_the_input_files, "outDir"); + } + } + if (!options.noEmit && options.allowJs && ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "allowJs", getEmitDeclarationOptionName(options)); + } + if (options.checkJs && !options.allowJs) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "checkJs", "allowJs")); + } + if (options.emitDeclarationOnly) { + if (!ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "emitDeclarationOnly", "declaration", "composite"); + } + if (options.noEmit) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "emitDeclarationOnly", "noEmit"); + } + } + if (options.emitDecoratorMetadata && + !options.experimentalDecorators) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDecoratorMetadata", "experimentalDecorators"); + } + if (options.jsxFactory) { + if (options.reactNamespace) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "reactNamespace", "jsxFactory"); + } + if (!ts.parseIsolatedEntityName(options.jsxFactory, languageVersion)) { + createOptionValueDiagnostic("jsxFactory", ts.Diagnostics.Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name, options.jsxFactory); + } + } + else if (options.reactNamespace && !ts.isIdentifierText(options.reactNamespace, languageVersion)) { + createOptionValueDiagnostic("reactNamespace", ts.Diagnostics.Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier, options.reactNamespace); + } + // If the emit is enabled make sure that every output file is unique and not overwriting any of the input files + if (!options.noEmit && !options.suppressOutputPathCheck) { + var emitHost = getEmitHost(); + var emitFilesSeen_1 = ts.createMap(); + ts.forEachEmittedFile(emitHost, function (emitFileNames) { + if (!options.emitDeclarationOnly) { + verifyEmitFilePath(emitFileNames.jsFilePath, emitFilesSeen_1); + } + verifyEmitFilePath(emitFileNames.declarationFilePath, emitFilesSeen_1); + }); + } + // Verify that all the emit files are unique and don't overwrite input files + function verifyEmitFilePath(emitFileName, emitFilesSeen) { + if (emitFileName) { + var emitFilePath = toPath(emitFileName); + // Report error if the output overwrites input file + if (filesByName.has(emitFilePath)) { + var chain_2; + if (!options.configFilePath) { + // The program is from either an inferred project or an external project + chain_2 = ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig); + } + chain_2 = ts.chainDiagnosticMessages(chain_2, ts.Diagnostics.Cannot_write_file_0_because_it_would_overwrite_input_file, emitFileName); + blockEmittingOfFile(emitFileName, ts.createCompilerDiagnosticFromMessageChain(chain_2)); + } + var emitFileKey = !host.useCaseSensitiveFileNames() ? emitFilePath.toLocaleLowerCase() : emitFilePath; + // Report error if multiple files write into same file + if (emitFilesSeen.has(emitFileKey)) { + // Already seen the same emit file - report error + blockEmittingOfFile(emitFileName, ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files, emitFileName)); + } + else { + emitFilesSeen.set(emitFileKey, true); + } + } + } + } + function verifyProjectReferences() { + forEachProjectReference(projectReferences, resolvedProjectReferences, function (resolvedRef, index, parent) { + var ref = (parent ? parent.commandLine.projectReferences : projectReferences)[index]; + var parentFile = parent && parent.sourceFile; + if (!resolvedRef) { + createDiagnosticForReference(parentFile, index, ts.Diagnostics.File_0_not_found, ref.path); + return; + } + var options = resolvedRef.commandLine.options; + if (!options.composite) { + // ok to not have composite if the current program is container only + var inputs = parent ? parent.commandLine.fileNames : rootNames; + if (inputs.length) { + createDiagnosticForReference(parentFile, index, ts.Diagnostics.Referenced_project_0_must_have_setting_composite_Colon_true, ref.path); + } + } + if (ref.prepend) { + var out = options.outFile || options.out; + if (out) { + if (!host.fileExists(out)) { + createDiagnosticForReference(parentFile, index, ts.Diagnostics.Output_file_0_from_project_1_does_not_exist, out, ref.path); + } + } + else { + createDiagnosticForReference(parentFile, index, ts.Diagnostics.Cannot_prepend_project_0_because_it_does_not_have_outFile_set, ref.path); + } + } + }); + } + function createDiagnosticForOptionPathKeyValue(key, valueIndex, message, arg0, arg1, arg2) { + var needCompilerDiagnostic = true; + var pathsSyntax = getOptionPathsSyntax(); + for (var _i = 0, pathsSyntax_1 = pathsSyntax; _i < pathsSyntax_1.length; _i++) { + var pathProp = pathsSyntax_1[_i]; + if (ts.isObjectLiteralExpression(pathProp.initializer)) { + for (var _a = 0, _b = ts.getPropertyAssignment(pathProp.initializer, key); _a < _b.length; _a++) { + var keyProps = _b[_a]; + var initializer = keyProps.initializer; + if (ts.isArrayLiteralExpression(initializer) && initializer.elements.length > valueIndex) { + programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(options.configFile, initializer.elements[valueIndex], message, arg0, arg1, arg2)); + needCompilerDiagnostic = false; + } + } + } + } + if (needCompilerDiagnostic) { + programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1, arg2)); + } + } + function createDiagnosticForOptionPaths(onKey, key, message, arg0) { + var needCompilerDiagnostic = true; + var pathsSyntax = getOptionPathsSyntax(); + for (var _i = 0, pathsSyntax_2 = pathsSyntax; _i < pathsSyntax_2.length; _i++) { + var pathProp = pathsSyntax_2[_i]; + if (ts.isObjectLiteralExpression(pathProp.initializer) && + createOptionDiagnosticInObjectLiteralSyntax(pathProp.initializer, onKey, key, /*key2*/ undefined, message, arg0)) { + needCompilerDiagnostic = false; + } + } + if (needCompilerDiagnostic) { + programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0)); + } + } + function getOptionsSyntaxByName(name) { + var compilerOptionsObjectLiteralSyntax = getCompilerOptionsObjectLiteralSyntax(); + if (compilerOptionsObjectLiteralSyntax) { + return ts.getPropertyAssignment(compilerOptionsObjectLiteralSyntax, name); + } + return undefined; + } + function getOptionPathsSyntax() { + return getOptionsSyntaxByName("paths") || ts.emptyArray; + } + function createDiagnosticForOptionName(message, option1, option2, option3) { + createDiagnosticForOption(/*onKey*/ true, option1, option2, message, option1, option2, option3); + } + function createOptionValueDiagnostic(option1, message, arg0) { + createDiagnosticForOption(/*onKey*/ false, option1, /*option2*/ undefined, message, arg0); + } + function createDiagnosticForReference(sourceFile, index, message, arg0, arg1) { + var referencesSyntax = ts.firstDefined(ts.getTsConfigPropArray(sourceFile || options.configFile, "references"), function (property) { return ts.isArrayLiteralExpression(property.initializer) ? property.initializer : undefined; }); + if (referencesSyntax && referencesSyntax.elements.length > index) { + programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(sourceFile || options.configFile, referencesSyntax.elements[index], message, arg0, arg1)); + } + else { + programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1)); + } + } + function createDiagnosticForOption(onKey, option1, option2, message, arg0, arg1, arg2) { + var compilerOptionsObjectLiteralSyntax = getCompilerOptionsObjectLiteralSyntax(); + var needCompilerDiagnostic = !compilerOptionsObjectLiteralSyntax || + !createOptionDiagnosticInObjectLiteralSyntax(compilerOptionsObjectLiteralSyntax, onKey, option1, option2, message, arg0, arg1, arg2); + if (needCompilerDiagnostic) { + programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1, arg2)); + } + } + function getCompilerOptionsObjectLiteralSyntax() { + if (_compilerOptionsObjectLiteralSyntax === undefined) { + _compilerOptionsObjectLiteralSyntax = null; // tslint:disable-line:no-null-keyword + var jsonObjectLiteral = ts.getTsConfigObjectLiteralExpression(options.configFile); + if (jsonObjectLiteral) { + for (var _i = 0, _a = ts.getPropertyAssignment(jsonObjectLiteral, "compilerOptions"); _i < _a.length; _i++) { + var prop = _a[_i]; + if (ts.isObjectLiteralExpression(prop.initializer)) { + _compilerOptionsObjectLiteralSyntax = prop.initializer; + break; + } + } + } + } + return _compilerOptionsObjectLiteralSyntax; + } + function createOptionDiagnosticInObjectLiteralSyntax(objectLiteral, onKey, key1, key2, message, arg0, arg1, arg2) { + var props = ts.getPropertyAssignment(objectLiteral, key1, key2); + for (var _i = 0, props_2 = props; _i < props_2.length; _i++) { + var prop = props_2[_i]; + programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(options.configFile, onKey ? prop.name : prop.initializer, message, arg0, arg1, arg2)); + } + return !!props.length; + } + function blockEmittingOfFile(emitFileName, diag) { + hasEmitBlockingDiagnostics.set(toPath(emitFileName), true); + programDiagnostics.add(diag); + } + function isEmittedFile(file) { + if (options.noEmit) { + return false; + } + // If this is source file, its not emitted file + var filePath = toPath(file); + if (getSourceFileByPath(filePath)) { + return false; + } + // If options have --outFile or --out just check that + var out = options.outFile || options.out; + if (out) { + return isSameFile(filePath, out) || isSameFile(filePath, ts.removeFileExtension(out) + ".d.ts" /* Dts */); + } + // If declarationDir is specified, return if its a file in that directory + if (options.declarationDir && ts.containsPath(options.declarationDir, filePath, currentDirectory, !host.useCaseSensitiveFileNames())) { + return true; + } + // If --outDir, check if file is in that directory + if (options.outDir) { + return ts.containsPath(options.outDir, filePath, currentDirectory, !host.useCaseSensitiveFileNames()); + } + if (ts.fileExtensionIsOneOf(filePath, ts.supportedJSExtensions) || ts.fileExtensionIs(filePath, ".d.ts" /* Dts */)) { + // Otherwise just check if sourceFile with the name exists + var filePathWithoutExtension = ts.removeFileExtension(filePath); + return !!getSourceFileByPath((filePathWithoutExtension + ".ts" /* Ts */)) || + !!getSourceFileByPath((filePathWithoutExtension + ".tsx" /* Tsx */)); + } + return false; + } + function isSameFile(file1, file2) { + return ts.comparePaths(file1, file2, currentDirectory, !host.useCaseSensitiveFileNames()) === 0 /* EqualTo */; + } + } + ts.createProgram = createProgram; + /* @internal */ + function parseConfigHostFromCompilerHost(host) { + return { + fileExists: function (f) { return host.fileExists(f); }, + readDirectory: function (root, extensions, excludes, includes, depth) { + ts.Debug.assertDefined(host.readDirectory, "'CompilerHost.readDirectory' must be implemented to correctly process 'projectReferences'"); + return host.readDirectory(root, extensions, excludes, includes, depth); + }, + readFile: function (f) { return host.readFile(f); }, + useCaseSensitiveFileNames: host.useCaseSensitiveFileNames(), + getCurrentDirectory: function () { return host.getCurrentDirectory(); }, + onUnRecoverableConfigFileDiagnostic: function () { return undefined; }, + trace: host.trace ? function (s) { return host.trace(s); } : undefined + }; + } + ts.parseConfigHostFromCompilerHost = parseConfigHostFromCompilerHost; + function resolveProjectReferencePath(hostOrRef, ref) { + var passedInRef = ref ? ref : hostOrRef; + return ts.resolveConfigFileProjectName(passedInRef.path); + } + ts.resolveProjectReferencePath = resolveProjectReferencePath; + function getEmitDeclarationOptionName(options) { + return options.declaration ? "declaration" : "composite"; + } + /* @internal */ + /** + * Returns a DiagnosticMessage if we won't include a resolved module due to its extension. + * The DiagnosticMessage's parameters are the imported module name, and the filename it resolved to. + * This returns a diagnostic even if the module will be an untyped module. + */ + function getResolutionDiagnostic(options, _a) { + var extension = _a.extension; + switch (extension) { + case ".ts" /* Ts */: + case ".d.ts" /* Dts */: + // These are always allowed. + return undefined; + case ".tsx" /* Tsx */: + return needJsx(); + case ".jsx" /* Jsx */: + return needJsx() || needAllowJs(); + case ".js" /* Js */: + return needAllowJs(); + case ".json" /* Json */: + return needResolveJsonModule(); + } + function needJsx() { + return options.jsx ? undefined : ts.Diagnostics.Module_0_was_resolved_to_1_but_jsx_is_not_set; + } + function needAllowJs() { + return options.allowJs || !ts.getStrictOptionValue(options, "noImplicitAny") ? undefined : ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type; + } + function needResolveJsonModule() { + return options.resolveJsonModule ? undefined : ts.Diagnostics.Module_0_was_resolved_to_1_but_resolveJsonModule_is_not_used; + } + } + ts.getResolutionDiagnostic = getResolutionDiagnostic; + function getModuleNames(_a) { + var imports = _a.imports, moduleAugmentations = _a.moduleAugmentations; + var res = imports.map(function (i) { return i.text; }); + for (var _i = 0, moduleAugmentations_1 = moduleAugmentations; _i < moduleAugmentations_1.length; _i++) { + var aug = moduleAugmentations_1[_i]; + if (aug.kind === 10 /* StringLiteral */) { + res.push(aug.text); + } + // Do nothing if it's an Identifier; we don't need to do module resolution for `declare global`. + } + return res; + } +})(ts || (ts = {})); +/*@internal*/ +var ts; +(function (ts) { + function getFileEmitOutput(program, sourceFile, emitOnlyDtsFiles, cancellationToken, customTransformers) { + var outputFiles = []; + var emitResult = program.emit(sourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); + return { outputFiles: outputFiles, emitSkipped: emitResult.emitSkipped, exportedModulesFromDeclarationEmit: emitResult.exportedModulesFromDeclarationEmit }; + function writeFile(fileName, text, writeByteOrderMark) { + outputFiles.push({ name: fileName, writeByteOrderMark: writeByteOrderMark, text: text }); + } + } + ts.getFileEmitOutput = getFileEmitOutput; +})(ts || (ts = {})); +/*@internal*/ +(function (ts) { + var BuilderState; + (function (BuilderState) { + /** + * Get the referencedFile from the imported module symbol + */ + function getReferencedFileFromImportedModuleSymbol(symbol) { + if (symbol.declarations && symbol.declarations[0]) { + var declarationSourceFile = ts.getSourceFileOfNode(symbol.declarations[0]); + return declarationSourceFile && declarationSourceFile.resolvedPath; + } + } + /** + * Get the referencedFile from the import name node from file + */ + function getReferencedFileFromImportLiteral(checker, importName) { + var symbol = checker.getSymbolAtLocation(importName); + return symbol && getReferencedFileFromImportedModuleSymbol(symbol); + } + /** + * Gets the path to reference file from file name, it could be resolvedPath if present otherwise path + */ + function getReferencedFileFromFileName(program, fileName, sourceFileDirectory, getCanonicalFileName) { + return ts.toPath(program.getProjectReferenceRedirect(fileName) || fileName, sourceFileDirectory, getCanonicalFileName); + } + /** + * Gets the referenced files for a file from the program with values for the keys as referenced file's path to be true + */ + function getReferencedFiles(program, sourceFile, getCanonicalFileName) { + var referencedFiles; + // We need to use a set here since the code can contain the same import twice, + // but that will only be one dependency. + // To avoid invernal conversion, the key of the referencedFiles map must be of type Path + if (sourceFile.imports && sourceFile.imports.length > 0) { + var checker = program.getTypeChecker(); + for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { + var importName = _a[_i]; + var declarationSourceFilePath = getReferencedFileFromImportLiteral(checker, importName); + if (declarationSourceFilePath) { + addReferencedFile(declarationSourceFilePath); + } + } + } + var sourceFileDirectory = ts.getDirectoryPath(sourceFile.path); + // Handle triple slash references + if (sourceFile.referencedFiles && sourceFile.referencedFiles.length > 0) { + for (var _b = 0, _c = sourceFile.referencedFiles; _b < _c.length; _b++) { + var referencedFile = _c[_b]; + var referencedPath = getReferencedFileFromFileName(program, referencedFile.fileName, sourceFileDirectory, getCanonicalFileName); + addReferencedFile(referencedPath); + } + } + // Handle type reference directives + if (sourceFile.resolvedTypeReferenceDirectiveNames) { + sourceFile.resolvedTypeReferenceDirectiveNames.forEach(function (resolvedTypeReferenceDirective) { + if (!resolvedTypeReferenceDirective) { + return; + } + var fileName = resolvedTypeReferenceDirective.resolvedFileName; // TODO: GH#18217 + var typeFilePath = getReferencedFileFromFileName(program, fileName, sourceFileDirectory, getCanonicalFileName); + addReferencedFile(typeFilePath); + }); + } + // Add module augmentation as references + if (sourceFile.moduleAugmentations.length) { + var checker = program.getTypeChecker(); + for (var _d = 0, _e = sourceFile.moduleAugmentations; _d < _e.length; _d++) { + var moduleName = _e[_d]; + if (!ts.isStringLiteral(moduleName)) { + continue; + } + var symbol = checker.getSymbolAtLocation(moduleName); + if (!symbol) { + continue; + } + // Add any file other than our own as reference + addReferenceFromAmbientModule(symbol); + } + } + // From ambient modules + for (var _f = 0, _g = program.getTypeChecker().getAmbientModules(); _f < _g.length; _f++) { + var ambientModule = _g[_f]; + if (ambientModule.declarations.length > 1) { + addReferenceFromAmbientModule(ambientModule); + } + } + return referencedFiles; + function addReferenceFromAmbientModule(symbol) { + // Add any file other than our own as reference + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + var declarationSourceFile = ts.getSourceFileOfNode(declaration); + if (declarationSourceFile && + declarationSourceFile !== sourceFile) { + addReferencedFile(declarationSourceFile.resolvedPath); + } + } + } + function addReferencedFile(referencedPath) { + if (!referencedFiles) { + referencedFiles = ts.createMap(); + } + referencedFiles.set(referencedPath, true); + } + } + /** + * Returns true if oldState is reusable, that is the emitKind = module/non module has not changed + */ + function canReuseOldState(newReferencedMap, oldState) { + return oldState && !oldState.referencedMap === !newReferencedMap; + } + BuilderState.canReuseOldState = canReuseOldState; + /** + * Creates the state of file references and signature for the new program from oldState if it is safe + */ + function create(newProgram, getCanonicalFileName, oldState) { + var fileInfos = ts.createMap(); + var referencedMap = newProgram.getCompilerOptions().module !== ts.ModuleKind.None ? ts.createMap() : undefined; + var exportedModulesMap = referencedMap ? ts.createMap() : undefined; + var hasCalledUpdateShapeSignature = ts.createMap(); + var useOldState = canReuseOldState(referencedMap, oldState); + // Create the reference map, and set the file infos + for (var _i = 0, _a = newProgram.getSourceFiles(); _i < _a.length; _i++) { + var sourceFile = _a[_i]; + var version_1 = sourceFile.version; + var oldInfo = useOldState ? oldState.fileInfos.get(sourceFile.path) : undefined; + if (referencedMap) { + var newReferences = getReferencedFiles(newProgram, sourceFile, getCanonicalFileName); + if (newReferences) { + referencedMap.set(sourceFile.path, newReferences); + } + // Copy old visible to outside files map + if (useOldState) { + var exportedModules = oldState.exportedModulesMap.get(sourceFile.path); + if (exportedModules) { + exportedModulesMap.set(sourceFile.path, exportedModules); + } + } + } + fileInfos.set(sourceFile.path, { version: version_1, signature: oldInfo && oldInfo.signature }); + } + return { + fileInfos: fileInfos, + referencedMap: referencedMap, + exportedModulesMap: exportedModulesMap, + hasCalledUpdateShapeSignature: hasCalledUpdateShapeSignature, + allFilesExcludingDefaultLibraryFile: undefined, + allFileNames: undefined + }; + } + BuilderState.create = create; + /** + * Gets the files affected by the path from the program + */ + function getFilesAffectedBy(state, programOfThisState, path, cancellationToken, computeHash, cacheToUpdateSignature, exportedModulesMapCache) { + // Since the operation could be cancelled, the signatures are always stored in the cache + // They will be commited once it is safe to use them + // eg when calling this api from tsserver, if there is no cancellation of the operation + // In the other cases the affected files signatures are commited only after the iteration through the result is complete + var signatureCache = cacheToUpdateSignature || ts.createMap(); + var sourceFile = programOfThisState.getSourceFileByPath(path); + if (!sourceFile) { + return ts.emptyArray; + } + if (!updateShapeSignature(state, programOfThisState, sourceFile, signatureCache, cancellationToken, computeHash, exportedModulesMapCache)) { + return [sourceFile]; + } + var result = (state.referencedMap ? getFilesAffectedByUpdatedShapeWhenModuleEmit : getFilesAffectedByUpdatedShapeWhenNonModuleEmit)(state, programOfThisState, sourceFile, signatureCache, cancellationToken, computeHash, exportedModulesMapCache); + if (!cacheToUpdateSignature) { + // Commit all the signatures in the signature cache + updateSignaturesFromCache(state, signatureCache); + } + return result; + } + BuilderState.getFilesAffectedBy = getFilesAffectedBy; + /** + * Updates the signatures from the cache into state's fileinfo signatures + * This should be called whenever it is safe to commit the state of the builder + */ + function updateSignaturesFromCache(state, signatureCache) { + signatureCache.forEach(function (signature, path) { + state.fileInfos.get(path).signature = signature; + state.hasCalledUpdateShapeSignature.set(path, true); + }); + } + BuilderState.updateSignaturesFromCache = updateSignaturesFromCache; + /** + * Returns if the shape of the signature has changed since last emit + */ + function updateShapeSignature(state, programOfThisState, sourceFile, cacheToUpdateSignature, cancellationToken, computeHash, exportedModulesMapCache) { + ts.Debug.assert(!!sourceFile); + ts.Debug.assert(!exportedModulesMapCache || !!state.exportedModulesMap, "Compute visible to outside map only if visibleToOutsideReferencedMap present in the state"); + // If we have cached the result for this file, that means hence forth we should assume file shape is uptodate + if (state.hasCalledUpdateShapeSignature.has(sourceFile.path) || cacheToUpdateSignature.has(sourceFile.path)) { + return false; + } + var info = state.fileInfos.get(sourceFile.path); + if (!info) + return ts.Debug.fail(); + var prevSignature = info.signature; + var latestSignature; + if (sourceFile.isDeclarationFile) { + latestSignature = sourceFile.version; + if (exportedModulesMapCache && latestSignature !== prevSignature) { + // All the references in this file are exported + var references = state.referencedMap ? state.referencedMap.get(sourceFile.path) : undefined; + exportedModulesMapCache.set(sourceFile.path, references || false); + } + } + else { + var emitOutput = ts.getFileEmitOutput(programOfThisState, sourceFile, /*emitOnlyDtsFiles*/ true, cancellationToken); + if (emitOutput.outputFiles && emitOutput.outputFiles.length > 0) { + latestSignature = computeHash(emitOutput.outputFiles[0].text); + if (exportedModulesMapCache && latestSignature !== prevSignature) { + updateExportedModules(sourceFile, emitOutput.exportedModulesFromDeclarationEmit, exportedModulesMapCache); + } + } + else { + latestSignature = prevSignature; // TODO: GH#18217 + } + } + cacheToUpdateSignature.set(sourceFile.path, latestSignature); + return !prevSignature || latestSignature !== prevSignature; + } + /** + * Coverts the declaration emit result into exported modules map + */ + function updateExportedModules(sourceFile, exportedModulesFromDeclarationEmit, exportedModulesMapCache) { + if (!exportedModulesFromDeclarationEmit) { + exportedModulesMapCache.set(sourceFile.path, false); + return; + } + var exportedModules; + exportedModulesFromDeclarationEmit.forEach(function (symbol) { return addExportedModule(getReferencedFileFromImportedModuleSymbol(symbol)); }); + exportedModulesMapCache.set(sourceFile.path, exportedModules || false); + function addExportedModule(exportedModulePath) { + if (exportedModulePath) { + if (!exportedModules) { + exportedModules = ts.createMap(); + } + exportedModules.set(exportedModulePath, true); + } + } + } + /** + * Updates the exported modules from cache into state's exported modules map + * This should be called whenever it is safe to commit the state of the builder + */ + function updateExportedFilesMapFromCache(state, exportedModulesMapCache) { + if (exportedModulesMapCache) { + ts.Debug.assert(!!state.exportedModulesMap); + exportedModulesMapCache.forEach(function (exportedModules, path) { + if (exportedModules) { + state.exportedModulesMap.set(path, exportedModules); + } + else { + state.exportedModulesMap.delete(path); + } + }); + } + } + BuilderState.updateExportedFilesMapFromCache = updateExportedFilesMapFromCache; + /** + * Get all the dependencies of the sourceFile + */ + function getAllDependencies(state, programOfThisState, sourceFile) { + var _a; + var compilerOptions = programOfThisState.getCompilerOptions(); + // With --out or --outFile all outputs go into single file, all files depend on each other + if (compilerOptions.outFile || compilerOptions.out) { + return getAllFileNames(state, programOfThisState); + } + // If this is non module emit, or its a global file, it depends on all the source files + if (!state.referencedMap || isFileAffectingGlobalScope(sourceFile)) { + return getAllFileNames(state, programOfThisState); + } + // Get the references, traversing deep from the referenceMap + var seenMap = ts.createMap(); + var queue = [sourceFile.path]; + while (queue.length) { + var path = queue.pop(); + if (!seenMap.has(path)) { + seenMap.set(path, true); + var references = state.referencedMap.get(path); + if (references) { + var iterator = references.keys(); + for (var _b = iterator.next(), value = _b.value, done = _b.done; !done; _a = iterator.next(), value = _a.value, done = _a.done, _a) { + queue.push(value); + } + } + } + } + return ts.arrayFrom(ts.mapDefinedIterator(seenMap.keys(), function (path) { + var file = programOfThisState.getSourceFileByPath(path); + return file ? file.fileName : path; + })); + } + BuilderState.getAllDependencies = getAllDependencies; + /** + * Gets the names of all files from the program + */ + function getAllFileNames(state, programOfThisState) { + if (!state.allFileNames) { + var sourceFiles = programOfThisState.getSourceFiles(); + state.allFileNames = sourceFiles === ts.emptyArray ? ts.emptyArray : sourceFiles.map(function (file) { return file.fileName; }); + } + return state.allFileNames; + } + /** + * Gets the files referenced by the the file path + */ + function getReferencedByPaths(state, referencedFilePath) { + return ts.arrayFrom(ts.mapDefinedIterator(state.referencedMap.entries(), function (_a) { + var filePath = _a[0], referencesInFile = _a[1]; + return referencesInFile.has(referencedFilePath) ? filePath : undefined; + })); + } + /** + * For script files that contains only ambient external modules, although they are not actually external module files, + * they can only be consumed via importing elements from them. Regular script files cannot consume them. Therefore, + * there are no point to rebuild all script files if these special files have changed. However, if any statement + * in the file is not ambient external module, we treat it as a regular script file. + */ + function containsOnlyAmbientModules(sourceFile) { + for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + if (!ts.isModuleWithStringLiteralName(statement)) { + return false; + } + } + return true; + } + /** + * Return true if file contains anything that augments to global scope we need to build them as if + * they are global files as well as module + */ + function containsGlobalScopeAugmentation(sourceFile) { + return ts.some(sourceFile.moduleAugmentations, function (augmentation) { return ts.isGlobalScopeAugmentation(augmentation.parent); }); + } + /** + * Return true if the file will invalidate all files because it affectes global scope + */ + function isFileAffectingGlobalScope(sourceFile) { + return containsGlobalScopeAugmentation(sourceFile) || + !ts.isExternalModule(sourceFile) && !containsOnlyAmbientModules(sourceFile); + } + /** + * Gets all files of the program excluding the default library file + */ + function getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, firstSourceFile) { + // Use cached result + if (state.allFilesExcludingDefaultLibraryFile) { + return state.allFilesExcludingDefaultLibraryFile; + } + var result; + addSourceFile(firstSourceFile); + for (var _i = 0, _a = programOfThisState.getSourceFiles(); _i < _a.length; _i++) { + var sourceFile = _a[_i]; + if (sourceFile !== firstSourceFile) { + addSourceFile(sourceFile); + } + } + state.allFilesExcludingDefaultLibraryFile = result || ts.emptyArray; + return state.allFilesExcludingDefaultLibraryFile; + function addSourceFile(sourceFile) { + if (!programOfThisState.isSourceFileDefaultLibrary(sourceFile)) { + (result || (result = [])).push(sourceFile); + } + } + } + /** + * When program emits non modular code, gets the files affected by the sourceFile whose shape has changed + */ + function getFilesAffectedByUpdatedShapeWhenNonModuleEmit(state, programOfThisState, sourceFileWithUpdatedShape) { + var compilerOptions = programOfThisState.getCompilerOptions(); + // If `--out` or `--outFile` is specified, any new emit will result in re-emitting the entire project, + // so returning the file itself is good enough. + if (compilerOptions && (compilerOptions.out || compilerOptions.outFile)) { + return [sourceFileWithUpdatedShape]; + } + return getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, sourceFileWithUpdatedShape); + } + /** + * When program emits modular code, gets the files affected by the sourceFile whose shape has changed + */ + function getFilesAffectedByUpdatedShapeWhenModuleEmit(state, programOfThisState, sourceFileWithUpdatedShape, cacheToUpdateSignature, cancellationToken, computeHash, exportedModulesMapCache) { + if (isFileAffectingGlobalScope(sourceFileWithUpdatedShape)) { + return getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, sourceFileWithUpdatedShape); + } + var compilerOptions = programOfThisState.getCompilerOptions(); + if (compilerOptions && (compilerOptions.isolatedModules || compilerOptions.out || compilerOptions.outFile)) { + return [sourceFileWithUpdatedShape]; + } + // Now we need to if each file in the referencedBy list has a shape change as well. + // Because if so, its own referencedBy files need to be saved as well to make the + // emitting result consistent with files on disk. + var seenFileNamesMap = ts.createMap(); + // Start with the paths this file was referenced by + seenFileNamesMap.set(sourceFileWithUpdatedShape.path, sourceFileWithUpdatedShape); + var queue = getReferencedByPaths(state, sourceFileWithUpdatedShape.path); + while (queue.length > 0) { + var currentPath = queue.pop(); + if (!seenFileNamesMap.has(currentPath)) { + var currentSourceFile = programOfThisState.getSourceFileByPath(currentPath); + seenFileNamesMap.set(currentPath, currentSourceFile); + if (currentSourceFile && updateShapeSignature(state, programOfThisState, currentSourceFile, cacheToUpdateSignature, cancellationToken, computeHash, exportedModulesMapCache)) { // TODO: GH#18217 + queue.push.apply(// TODO: GH#18217 + queue, getReferencedByPaths(state, currentPath)); + } + } + } + // Return array of values that needs emit + // Return array of values that needs emit + return ts.arrayFrom(ts.mapDefinedIterator(seenFileNamesMap.values(), function (value) { return value; })); + } + })(BuilderState = ts.BuilderState || (ts.BuilderState = {})); +})(ts || (ts = {})); +/*@internal*/ +var ts; +(function (ts) { + function hasSameKeys(map1, map2) { + // Has same size and every key is present in both maps + return map1 === map2 || map1 !== undefined && map2 !== undefined && map1.size === map2.size && !ts.forEachKey(map1, function (key) { return !map2.has(key); }); + } + /** + * Create the state so that we can iterate on changedFiles/affected files + */ + function createBuilderProgramState(newProgram, getCanonicalFileName, oldState) { + var state = ts.BuilderState.create(newProgram, getCanonicalFileName, oldState); + state.program = newProgram; + var compilerOptions = newProgram.getCompilerOptions(); + if (!compilerOptions.outFile && !compilerOptions.out) { + state.semanticDiagnosticsPerFile = ts.createMap(); + } + state.changedFilesSet = ts.createMap(); + var useOldState = ts.BuilderState.canReuseOldState(state.referencedMap, oldState); + var oldCompilerOptions = useOldState ? oldState.program.getCompilerOptions() : undefined; + var canCopySemanticDiagnostics = useOldState && oldState.semanticDiagnosticsPerFile && !!state.semanticDiagnosticsPerFile && + !ts.compilerOptionsAffectSemanticDiagnostics(compilerOptions, oldCompilerOptions); + if (useOldState) { + // Verify the sanity of old state + if (!oldState.currentChangedFilePath) { + ts.Debug.assert(!oldState.affectedFiles && (!oldState.currentAffectedFilesSignatures || !oldState.currentAffectedFilesSignatures.size), "Cannot reuse if only few affected files of currentChangedFile were iterated"); + } + if (canCopySemanticDiagnostics) { + ts.Debug.assert(!ts.forEachKey(oldState.changedFilesSet, function (path) { return oldState.semanticDiagnosticsPerFile.has(path); }), "Semantic diagnostics shouldnt be available for changed files"); + } + // Copy old state's changed files set + ts.copyEntries(oldState.changedFilesSet, state.changedFilesSet); + } + // Update changed files and copy semantic diagnostics if we can + var referencedMap = state.referencedMap; + var oldReferencedMap = useOldState ? oldState.referencedMap : undefined; + var copyDeclarationFileDiagnostics = canCopySemanticDiagnostics && !compilerOptions.skipLibCheck === !oldCompilerOptions.skipLibCheck; + var copyLibFileDiagnostics = copyDeclarationFileDiagnostics && !compilerOptions.skipDefaultLibCheck === !oldCompilerOptions.skipDefaultLibCheck; + state.fileInfos.forEach(function (info, sourceFilePath) { + var oldInfo; + var newReferences; + // if not using old state, every file is changed + if (!useOldState || + // File wasnt present in old state + !(oldInfo = oldState.fileInfos.get(sourceFilePath)) || + // versions dont match + oldInfo.version !== info.version || + // Referenced files changed + !hasSameKeys(newReferences = referencedMap && referencedMap.get(sourceFilePath), oldReferencedMap && oldReferencedMap.get(sourceFilePath)) || + // Referenced file was deleted in the new program + newReferences && ts.forEachKey(newReferences, function (path) { return !state.fileInfos.has(path) && oldState.fileInfos.has(path); })) { + // Register file as changed file and do not copy semantic diagnostics, since all changed files need to be re-evaluated + state.changedFilesSet.set(sourceFilePath, true); + } + else if (canCopySemanticDiagnostics) { + var sourceFile = state.program.getSourceFileByPath(sourceFilePath); + if (sourceFile.isDeclarationFile && !copyDeclarationFileDiagnostics) { + return; + } + if (sourceFile.hasNoDefaultLib && !copyLibFileDiagnostics) { + return; + } + // Unchanged file copy diagnostics + var diagnostics = oldState.semanticDiagnosticsPerFile.get(sourceFilePath); + if (diagnostics) { + state.semanticDiagnosticsPerFile.set(sourceFilePath, diagnostics); + if (!state.semanticDiagnosticsFromOldState) { + state.semanticDiagnosticsFromOldState = ts.createMap(); + } + state.semanticDiagnosticsFromOldState.set(sourceFilePath, true); + } + } + }); + return state; + } + /** + * Verifies that source file is ok to be used in calls that arent handled by next + */ + function assertSourceFileOkWithoutNextAffectedCall(state, sourceFile) { + ts.Debug.assert(!sourceFile || !state.affectedFiles || state.affectedFiles[state.affectedFilesIndex - 1] !== sourceFile || !state.semanticDiagnosticsPerFile.has(sourceFile.path)); + } + /** + * This function returns the next affected file to be processed. + * Note that until doneAffected is called it would keep reporting same result + * This is to allow the callers to be able to actually remove affected file only when the operation is complete + * eg. if during diagnostics check cancellation token ends up cancelling the request, the affected file should be retained + */ + function getNextAffectedFile(state, cancellationToken, computeHash) { + while (true) { + var affectedFiles = state.affectedFiles; + if (affectedFiles) { + var seenAffectedFiles = state.seenAffectedFiles; + var affectedFilesIndex = state.affectedFilesIndex; // TODO: GH#18217 + while (affectedFilesIndex < affectedFiles.length) { + var affectedFile = affectedFiles[affectedFilesIndex]; + if (!seenAffectedFiles.has(affectedFile.path)) { + // Set the next affected file as seen and remove the cached semantic diagnostics + state.affectedFilesIndex = affectedFilesIndex; + cleanSemanticDiagnosticsOfAffectedFile(state, affectedFile); + return affectedFile; + } + seenAffectedFiles.set(affectedFile.path, true); + affectedFilesIndex++; + } + // Remove the changed file from the change set + state.changedFilesSet.delete(state.currentChangedFilePath); + state.currentChangedFilePath = undefined; + // Commit the changes in file signature + ts.BuilderState.updateSignaturesFromCache(state, state.currentAffectedFilesSignatures); + state.currentAffectedFilesSignatures.clear(); + ts.BuilderState.updateExportedFilesMapFromCache(state, state.currentAffectedFilesExportedModulesMap); + state.affectedFiles = undefined; + } + // Get next changed file + var nextKey = state.changedFilesSet.keys().next(); + if (nextKey.done) { + // Done + return undefined; + } + // With --out or --outFile all outputs go into single file + // so operations are performed directly on program, return program + var compilerOptions = state.program.getCompilerOptions(); + if (compilerOptions.outFile || compilerOptions.out) { + ts.Debug.assert(!state.semanticDiagnosticsPerFile); + return state.program; + } + // Get next batch of affected files + state.currentAffectedFilesSignatures = state.currentAffectedFilesSignatures || ts.createMap(); + if (state.exportedModulesMap) { + state.currentAffectedFilesExportedModulesMap = state.currentAffectedFilesExportedModulesMap || ts.createMap(); + } + state.affectedFiles = ts.BuilderState.getFilesAffectedBy(state, state.program, nextKey.value, cancellationToken, computeHash, state.currentAffectedFilesSignatures, state.currentAffectedFilesExportedModulesMap); + state.currentChangedFilePath = nextKey.value; + state.affectedFilesIndex = 0; + state.seenAffectedFiles = state.seenAffectedFiles || ts.createMap(); + } + } + /** + * Remove the semantic diagnostics cached from old state for affected File and the files that are referencing modules that export entities from affected file + */ + function cleanSemanticDiagnosticsOfAffectedFile(state, affectedFile) { + if (removeSemanticDiagnosticsOf(state, affectedFile.path)) { + // If there are no more diagnostics from old cache, done + return; + } + // Clean lib file diagnostics if its all files excluding default files to emit + if (state.allFilesExcludingDefaultLibraryFile === state.affectedFiles && !state.cleanedDiagnosticsOfLibFiles) { + state.cleanedDiagnosticsOfLibFiles = true; + var options_2 = state.program.getCompilerOptions(); + if (ts.forEach(state.program.getSourceFiles(), function (f) { + return state.program.isSourceFileDefaultLibrary(f) && + !ts.skipTypeChecking(f, options_2) && + removeSemanticDiagnosticsOf(state, f.path); + })) { + return; + } + } + // If there was change in signature for the changed file, + // then delete the semantic diagnostics for files that are affected by using exports of this module + if (!state.exportedModulesMap || state.affectedFiles.length === 1 || !state.changedFilesSet.has(affectedFile.path)) { + return; + } + ts.Debug.assert(!!state.currentAffectedFilesExportedModulesMap); + var seenFileAndExportsOfFile = ts.createMap(); + // Go through exported modules from cache first + // If exported modules has path, all files referencing file exported from are affected + if (ts.forEachEntry(state.currentAffectedFilesExportedModulesMap, function (exportedModules, exportedFromPath) { + return exportedModules && + exportedModules.has(affectedFile.path) && + removeSemanticDiagnosticsOfFilesReferencingPath(state, exportedFromPath, seenFileAndExportsOfFile); + })) { + return; + } + // If exported from path is not from cache and exported modules has path, all files referencing file exported from are affected + ts.forEachEntry(state.exportedModulesMap, function (exportedModules, exportedFromPath) { + return !state.currentAffectedFilesExportedModulesMap.has(exportedFromPath) && // If we already iterated this through cache, ignore it + exportedModules.has(affectedFile.path) && + removeSemanticDiagnosticsOfFilesReferencingPath(state, exportedFromPath, seenFileAndExportsOfFile); + }); + } + /** + * removes the semantic diagnostics of files referencing referencedPath and + * returns true if there are no more semantic diagnostics from old state + */ + function removeSemanticDiagnosticsOfFilesReferencingPath(state, referencedPath, seenFileAndExportsOfFile) { + return ts.forEachEntry(state.referencedMap, function (referencesInFile, filePath) { + return referencesInFile.has(referencedPath) && removeSemanticDiagnosticsOfFileAndExportsOfFile(state, filePath, seenFileAndExportsOfFile); + }); + } + /** + * Removes semantic diagnostics of file and anything that exports this file + */ + function removeSemanticDiagnosticsOfFileAndExportsOfFile(state, filePath, seenFileAndExportsOfFile) { + if (!ts.addToSeen(seenFileAndExportsOfFile, filePath)) { + return false; + } + if (removeSemanticDiagnosticsOf(state, filePath)) { + // If there are no more diagnostics from old cache, done + return true; + } + ts.Debug.assert(!!state.currentAffectedFilesExportedModulesMap); + // Go through exported modules from cache first + // If exported modules has path, all files referencing file exported from are affected + if (ts.forEachEntry(state.currentAffectedFilesExportedModulesMap, function (exportedModules, exportedFromPath) { + return exportedModules && + exportedModules.has(filePath) && + removeSemanticDiagnosticsOfFileAndExportsOfFile(state, exportedFromPath, seenFileAndExportsOfFile); + })) { + return true; + } + // If exported from path is not from cache and exported modules has path, all files referencing file exported from are affected + return !!ts.forEachEntry(state.exportedModulesMap, function (exportedModules, exportedFromPath) { + return !state.currentAffectedFilesExportedModulesMap.has(exportedFromPath) && // If we already iterated this through cache, ignore it + exportedModules.has(filePath) && + removeSemanticDiagnosticsOfFileAndExportsOfFile(state, exportedFromPath, seenFileAndExportsOfFile); + }); + } + /** + * Removes semantic diagnostics for path and + * returns true if there are no more semantic diagnostics from the old state + */ + function removeSemanticDiagnosticsOf(state, path) { + if (!state.semanticDiagnosticsFromOldState) { + return true; + } + state.semanticDiagnosticsFromOldState.delete(path); + state.semanticDiagnosticsPerFile.delete(path); + return !state.semanticDiagnosticsFromOldState.size; + } + /** + * This is called after completing operation on the next affected file. + * The operations here are postponed to ensure that cancellation during the iteration is handled correctly + */ + function doneWithAffectedFile(state, affected) { + if (affected === state.program) { + state.changedFilesSet.clear(); + } + else { + state.seenAffectedFiles.set(affected.path, true); + state.affectedFilesIndex++; + } + } + /** + * Returns the result with affected file + */ + function toAffectedFileResult(state, result, affected) { + doneWithAffectedFile(state, affected); + return { result: result, affected: affected }; + } + /** + * Gets the semantic diagnostics either from cache if present, or otherwise from program and caches it + * Note that it is assumed that the when asked about semantic diagnostics, the file has been taken out of affected files/changed file set + */ + function getSemanticDiagnosticsOfFile(state, sourceFile, cancellationToken) { + var path = sourceFile.path; + var cachedDiagnostics = state.semanticDiagnosticsPerFile.get(path); + // Report the semantic diagnostics from the cache if we already have those diagnostics present + if (cachedDiagnostics) { + return cachedDiagnostics; + } + // Diagnostics werent cached, get them from program, and cache the result + var diagnostics = state.program.getSemanticDiagnostics(sourceFile, cancellationToken); + state.semanticDiagnosticsPerFile.set(path, diagnostics); + return diagnostics; + } + var BuilderProgramKind; + (function (BuilderProgramKind) { + BuilderProgramKind[BuilderProgramKind["SemanticDiagnosticsBuilderProgram"] = 0] = "SemanticDiagnosticsBuilderProgram"; + BuilderProgramKind[BuilderProgramKind["EmitAndSemanticDiagnosticsBuilderProgram"] = 1] = "EmitAndSemanticDiagnosticsBuilderProgram"; + })(BuilderProgramKind = ts.BuilderProgramKind || (ts.BuilderProgramKind = {})); + function getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { + var host; + var newProgram; + var oldProgram; + if (newProgramOrRootNames === undefined) { + ts.Debug.assert(hostOrOptions === undefined); + host = oldProgramOrHost; + oldProgram = configFileParsingDiagnosticsOrOldProgram; + ts.Debug.assert(!!oldProgram); + newProgram = oldProgram.getProgram(); + } + else if (ts.isArray(newProgramOrRootNames)) { + oldProgram = configFileParsingDiagnosticsOrOldProgram; + newProgram = ts.createProgram({ + rootNames: newProgramOrRootNames, + options: hostOrOptions, + host: oldProgramOrHost, + oldProgram: oldProgram && oldProgram.getProgram(), + configFileParsingDiagnostics: configFileParsingDiagnostics, + projectReferences: projectReferences + }); + host = oldProgramOrHost; + } + else { + newProgram = newProgramOrRootNames; + host = hostOrOptions; + oldProgram = oldProgramOrHost; + configFileParsingDiagnostics = configFileParsingDiagnosticsOrOldProgram; + } + return { host: host, newProgram: newProgram, oldProgram: oldProgram, configFileParsingDiagnostics: configFileParsingDiagnostics || ts.emptyArray }; + } + ts.getBuilderCreationParameters = getBuilderCreationParameters; + function createBuilderProgram(kind, _a) { + var newProgram = _a.newProgram, host = _a.host, oldProgram = _a.oldProgram, configFileParsingDiagnostics = _a.configFileParsingDiagnostics; + // Return same program if underlying program doesnt change + var oldState = oldProgram && oldProgram.getState(); + if (oldState && newProgram === oldState.program && configFileParsingDiagnostics === newProgram.getConfigFileParsingDiagnostics()) { + newProgram = undefined; // TODO: GH#18217 + oldState = undefined; + return oldProgram; + } + /** + * Create the canonical file name for identity + */ + var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames()); + /** + * Computing hash to for signature verification + */ + var computeHash = host.createHash || ts.identity; + var state = createBuilderProgramState(newProgram, getCanonicalFileName, oldState); + // To ensure that we arent storing any references to old program or new program without state + newProgram = undefined; // TODO: GH#18217 + oldProgram = undefined; + oldState = undefined; + var result = { + getState: function () { return state; }, + getProgram: function () { return state.program; }, + getCompilerOptions: function () { return state.program.getCompilerOptions(); }, + getSourceFile: function (fileName) { return state.program.getSourceFile(fileName); }, + getSourceFiles: function () { return state.program.getSourceFiles(); }, + getOptionsDiagnostics: function (cancellationToken) { return state.program.getOptionsDiagnostics(cancellationToken); }, + getGlobalDiagnostics: function (cancellationToken) { return state.program.getGlobalDiagnostics(cancellationToken); }, + getConfigFileParsingDiagnostics: function () { return configFileParsingDiagnostics || state.program.getConfigFileParsingDiagnostics(); }, + getSyntacticDiagnostics: function (sourceFile, cancellationToken) { return state.program.getSyntacticDiagnostics(sourceFile, cancellationToken); }, + getSemanticDiagnostics: getSemanticDiagnostics, + emit: emit, + getAllDependencies: function (sourceFile) { return ts.BuilderState.getAllDependencies(state, state.program, sourceFile); }, + getCurrentDirectory: function () { return state.program.getCurrentDirectory(); } + }; + if (kind === BuilderProgramKind.SemanticDiagnosticsBuilderProgram) { + result.getSemanticDiagnosticsOfNextAffectedFile = getSemanticDiagnosticsOfNextAffectedFile; + } + else if (kind === BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram) { + result.emitNextAffectedFile = emitNextAffectedFile; + } + else { + ts.notImplemented(); + } + return result; + /** + * Emits the next affected file's emit result (EmitResult and sourceFiles emitted) or returns undefined if iteration is complete + * The first of writeFile if provided, writeFile of BuilderProgramHost if provided, writeFile of compiler host + * in that order would be used to write the files + */ + function emitNextAffectedFile(writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) { + var affected = getNextAffectedFile(state, cancellationToken, computeHash); + if (!affected) { + // Done + return undefined; + } + return toAffectedFileResult(state, + // When whole program is affected, do emit only once (eg when --out or --outFile is specified) + // Otherwise just affected file + state.program.emit(affected === state.program ? undefined : affected, writeFile || host.writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers), affected); + } + /** + * Emits the JavaScript and declaration files. + * When targetSource file is specified, emits the files corresponding to that source file, + * otherwise for the whole program. + * In case of EmitAndSemanticDiagnosticsBuilderProgram, when targetSourceFile is specified, + * it is assumed that that file is handled from affected file list. If targetSourceFile is not specified, + * it will only emit all the affected files instead of whole program + * + * The first of writeFile if provided, writeFile of BuilderProgramHost if provided, writeFile of compiler host + * in that order would be used to write the files + */ + function emit(targetSourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) { + if (kind === BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram) { + assertSourceFileOkWithoutNextAffectedCall(state, targetSourceFile); + if (!targetSourceFile) { + // Emit and report any errors we ran into. + var sourceMaps = []; + var emitSkipped = false; + var diagnostics = void 0; + var emittedFiles = []; + var affectedEmitResult = void 0; + while (affectedEmitResult = emitNextAffectedFile(writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers)) { + emitSkipped = emitSkipped || affectedEmitResult.result.emitSkipped; + diagnostics = ts.addRange(diagnostics, affectedEmitResult.result.diagnostics); + emittedFiles = ts.addRange(emittedFiles, affectedEmitResult.result.emittedFiles); + sourceMaps = ts.addRange(sourceMaps, affectedEmitResult.result.sourceMaps); + } + return { + emitSkipped: emitSkipped, + diagnostics: diagnostics || ts.emptyArray, + emittedFiles: emittedFiles, + sourceMaps: sourceMaps + }; + } + } + return state.program.emit(targetSourceFile, writeFile || host.writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); + } + /** + * Return the semantic diagnostics for the next affected file or undefined if iteration is complete + * If provided ignoreSourceFile would be called before getting the diagnostics and would ignore the sourceFile if the returned value was true + */ + function getSemanticDiagnosticsOfNextAffectedFile(cancellationToken, ignoreSourceFile) { + while (true) { + var affected = getNextAffectedFile(state, cancellationToken, computeHash); + if (!affected) { + // Done + return undefined; + } + else if (affected === state.program) { + // When whole program is affected, get all semantic diagnostics (eg when --out or --outFile is specified) + return toAffectedFileResult(state, state.program.getSemanticDiagnostics(/*targetSourceFile*/ undefined, cancellationToken), affected); + } + // Get diagnostics for the affected file if its not ignored + if (ignoreSourceFile && ignoreSourceFile(affected)) { + // Get next affected file + doneWithAffectedFile(state, affected); + continue; + } + return toAffectedFileResult(state, getSemanticDiagnosticsOfFile(state, affected, cancellationToken), affected); + } + } + /** + * Gets the semantic diagnostics from the program corresponding to this state of file (if provided) or whole program + * The semantic diagnostics are cached and managed here + * Note that it is assumed that when asked about semantic diagnostics through this API, + * the file has been taken out of affected files so it is safe to use cache or get from program and cache the diagnostics + * In case of SemanticDiagnosticsBuilderProgram if the source file is not provided, + * it will iterate through all the affected files, to ensure that cache stays valid and yet provide a way to get all semantic diagnostics + */ + function getSemanticDiagnostics(sourceFile, cancellationToken) { + assertSourceFileOkWithoutNextAffectedCall(state, sourceFile); + var compilerOptions = state.program.getCompilerOptions(); + if (compilerOptions.outFile || compilerOptions.out) { + ts.Debug.assert(!state.semanticDiagnosticsPerFile); + // We dont need to cache the diagnostics just return them from program + return state.program.getSemanticDiagnostics(sourceFile, cancellationToken); + } + if (sourceFile) { + return getSemanticDiagnosticsOfFile(state, sourceFile, cancellationToken); + } + if (kind === BuilderProgramKind.SemanticDiagnosticsBuilderProgram) { + // When semantic builder asks for diagnostics of the whole program, + // ensure that all the affected files are handled + var affected = void 0; + while (affected = getNextAffectedFile(state, cancellationToken, computeHash)) { + doneWithAffectedFile(state, affected); + } + } + var diagnostics; + for (var _i = 0, _a = state.program.getSourceFiles(); _i < _a.length; _i++) { + var sourceFile_2 = _a[_i]; + diagnostics = ts.addRange(diagnostics, getSemanticDiagnosticsOfFile(state, sourceFile_2, cancellationToken)); + } + return diagnostics || ts.emptyArray; + } + } + ts.createBuilderProgram = createBuilderProgram; +})(ts || (ts = {})); +(function (ts) { + function createSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { + return ts.createBuilderProgram(ts.BuilderProgramKind.SemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences)); + } + ts.createSemanticDiagnosticsBuilderProgram = createSemanticDiagnosticsBuilderProgram; + function createEmitAndSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { + return ts.createBuilderProgram(ts.BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences)); + } + ts.createEmitAndSemanticDiagnosticsBuilderProgram = createEmitAndSemanticDiagnosticsBuilderProgram; + function createAbstractBuilder(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { + var program = ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences).newProgram; + return { + // Only return program, all other methods are not implemented + getProgram: function () { return program; }, + getState: ts.notImplemented, + getCompilerOptions: ts.notImplemented, + getSourceFile: ts.notImplemented, + getSourceFiles: ts.notImplemented, + getOptionsDiagnostics: ts.notImplemented, + getGlobalDiagnostics: ts.notImplemented, + getConfigFileParsingDiagnostics: ts.notImplemented, + getSyntacticDiagnostics: ts.notImplemented, + getSemanticDiagnostics: ts.notImplemented, + emit: ts.notImplemented, + getAllDependencies: ts.notImplemented, + getCurrentDirectory: ts.notImplemented + }; + } + ts.createAbstractBuilder = createAbstractBuilder; +})(ts || (ts = {})); +/*@internal*/ +var ts; +(function (ts) { + function isPathInNodeModulesStartingWithDot(path) { + return ts.stringContains(path, "/node_modules/."); + } + ts.isPathInNodeModulesStartingWithDot = isPathInNodeModulesStartingWithDot; + ts.maxNumberOfFilesToIterateForInvalidation = 256; + function createResolutionCache(resolutionHost, rootDirForResolution, logChangesWhenResolvingModule) { + var filesWithChangedSetOfUnresolvedImports; + var filesWithInvalidatedResolutions; + var filesWithInvalidatedNonRelativeUnresolvedImports; + var allFilesHaveInvalidatedResolution = false; + var nonRelativeExternalModuleResolutions = ts.createMultiMap(); + var getCurrentDirectory = ts.memoize(function () { return resolutionHost.getCurrentDirectory(); }); // TODO: GH#18217 + var cachedDirectoryStructureHost = resolutionHost.getCachedDirectoryStructureHost(); + // The resolvedModuleNames and resolvedTypeReferenceDirectives are the cache of resolutions per file. + // The key in the map is source file's path. + // The values are Map of resolutions with key being name lookedup. + var resolvedModuleNames = ts.createMap(); + var perDirectoryResolvedModuleNames = ts.createCacheWithRedirects(); + var nonRelativeModuleNameCache = ts.createCacheWithRedirects(); + var moduleResolutionCache = ts.createModuleResolutionCacheWithMaps(perDirectoryResolvedModuleNames, nonRelativeModuleNameCache, getCurrentDirectory(), resolutionHost.getCanonicalFileName); + var resolvedTypeReferenceDirectives = ts.createMap(); + var perDirectoryResolvedTypeReferenceDirectives = ts.createCacheWithRedirects(); + /** + * These are the extensions that failed lookup files will have by default, + * any other extension of failed lookup will be store that path in custom failed lookup path + * This helps in not having to comb through all resolutions when files are added/removed + * Note that .d.ts file also has .d.ts extension hence will be part of default extensions + */ + var failedLookupDefaultExtensions = [".ts" /* Ts */, ".tsx" /* Tsx */, ".js" /* Js */, ".jsx" /* Jsx */, ".json" /* Json */]; + var customFailedLookupPaths = ts.createMap(); + var directoryWatchesOfFailedLookups = ts.createMap(); + var rootDir = rootDirForResolution && ts.removeTrailingDirectorySeparator(ts.getNormalizedAbsolutePath(rootDirForResolution, getCurrentDirectory())); + var rootPath = (rootDir && resolutionHost.toPath(rootDir)); // TODO: GH#18217 + // TypeRoot watches for the types that get added as part of getAutomaticTypeDirectiveNames + var typeRootsWatches = ts.createMap(); + return { + startRecordingFilesWithChangedResolutions: startRecordingFilesWithChangedResolutions, + finishRecordingFilesWithChangedResolutions: finishRecordingFilesWithChangedResolutions, + // perDirectoryResolvedModuleNames and perDirectoryResolvedTypeReferenceDirectives could be non empty if there was exception during program update + // (between startCachingPerDirectoryResolution and finishCachingPerDirectoryResolution) + startCachingPerDirectoryResolution: clearPerDirectoryResolutions, + finishCachingPerDirectoryResolution: finishCachingPerDirectoryResolution, + resolveModuleNames: resolveModuleNames, + getResolvedModuleWithFailedLookupLocationsFromCache: getResolvedModuleWithFailedLookupLocationsFromCache, + resolveTypeReferenceDirectives: resolveTypeReferenceDirectives, + removeResolutionsFromProjectReferenceRedirects: removeResolutionsFromProjectReferenceRedirects, + removeResolutionsOfFile: removeResolutionsOfFile, + invalidateResolutionOfFile: invalidateResolutionOfFile, + setFilesWithInvalidatedNonRelativeUnresolvedImports: setFilesWithInvalidatedNonRelativeUnresolvedImports, + createHasInvalidatedResolution: createHasInvalidatedResolution, + updateTypeRootsWatch: updateTypeRootsWatch, + closeTypeRootsWatch: closeTypeRootsWatch, + clear: clear + }; + function getResolvedModule(resolution) { + return resolution.resolvedModule; + } + function getResolvedTypeReferenceDirective(resolution) { + return resolution.resolvedTypeReferenceDirective; + } + function isInDirectoryPath(dir, file) { + if (dir === undefined || file.length <= dir.length) { + return false; + } + return ts.startsWith(file, dir) && file[dir.length] === ts.directorySeparator; + } + function clear() { + ts.clearMap(directoryWatchesOfFailedLookups, ts.closeFileWatcherOf); + customFailedLookupPaths.clear(); + nonRelativeExternalModuleResolutions.clear(); + closeTypeRootsWatch(); + resolvedModuleNames.clear(); + resolvedTypeReferenceDirectives.clear(); + allFilesHaveInvalidatedResolution = false; + // perDirectoryResolvedModuleNames and perDirectoryResolvedTypeReferenceDirectives could be non empty if there was exception during program update + // (between startCachingPerDirectoryResolution and finishCachingPerDirectoryResolution) + clearPerDirectoryResolutions(); + } + function startRecordingFilesWithChangedResolutions() { + filesWithChangedSetOfUnresolvedImports = []; + } + function finishRecordingFilesWithChangedResolutions() { + var collected = filesWithChangedSetOfUnresolvedImports; + filesWithChangedSetOfUnresolvedImports = undefined; + return collected; + } + function isFileWithInvalidatedNonRelativeUnresolvedImports(path) { + if (!filesWithInvalidatedNonRelativeUnresolvedImports) { + return false; + } + // Invalidated if file has unresolved imports + var value = filesWithInvalidatedNonRelativeUnresolvedImports.get(path); + return !!value && !!value.length; + } + function createHasInvalidatedResolution(forceAllFilesAsInvalidated) { + if (allFilesHaveInvalidatedResolution || forceAllFilesAsInvalidated) { + // Any file asked would have invalidated resolution + filesWithInvalidatedResolutions = undefined; + return ts.returnTrue; + } + var collected = filesWithInvalidatedResolutions; + filesWithInvalidatedResolutions = undefined; + return function (path) { return (!!collected && collected.has(path)) || + isFileWithInvalidatedNonRelativeUnresolvedImports(path); }; + } + function clearPerDirectoryResolutions() { + perDirectoryResolvedModuleNames.clear(); + nonRelativeModuleNameCache.clear(); + perDirectoryResolvedTypeReferenceDirectives.clear(); + nonRelativeExternalModuleResolutions.forEach(watchFailedLookupLocationOfNonRelativeModuleResolutions); + nonRelativeExternalModuleResolutions.clear(); + } + function finishCachingPerDirectoryResolution() { + allFilesHaveInvalidatedResolution = false; + filesWithInvalidatedNonRelativeUnresolvedImports = undefined; + clearPerDirectoryResolutions(); + directoryWatchesOfFailedLookups.forEach(function (watcher, path) { + if (watcher.refCount === 0) { + directoryWatchesOfFailedLookups.delete(path); + watcher.watcher.close(); + } + }); + } + function resolveModuleName(moduleName, containingFile, compilerOptions, host, redirectedReference) { + var primaryResult = ts.resolveModuleName(moduleName, containingFile, compilerOptions, host, moduleResolutionCache, redirectedReference); + // return result immediately only if global cache support is not enabled or if it is .ts, .tsx or .d.ts + if (!resolutionHost.getGlobalCache) { + return primaryResult; + } + // otherwise try to load typings from @types + var globalCache = resolutionHost.getGlobalCache(); + if (globalCache !== undefined && !ts.isExternalModuleNameRelative(moduleName) && !(primaryResult.resolvedModule && ts.extensionIsTS(primaryResult.resolvedModule.extension))) { + // create different collection of failed lookup locations for second pass + // if it will fail and we've already found something during the first pass - we don't want to pollute its results + var _a = ts.loadModuleFromGlobalCache(moduleName, resolutionHost.projectName, compilerOptions, host, globalCache), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; + if (resolvedModule) { + return { resolvedModule: resolvedModule, failedLookupLocations: ts.addRange(primaryResult.failedLookupLocations, failedLookupLocations) }; + } + } + // Default return the result from the first pass + return primaryResult; + } + function resolveNamesWithLocalCache(names, containingFile, redirectedReference, cache, perDirectoryCacheWithRedirects, loader, getResolutionWithResolvedFileName, shouldRetryResolution, reusedNames, logChanges) { + var path = resolutionHost.toPath(containingFile); + var resolutionsInFile = cache.get(path) || cache.set(path, ts.createMap()).get(path); + var dirPath = ts.getDirectoryPath(path); + var perDirectoryCache = perDirectoryCacheWithRedirects.getOrCreateMapOfCacheRedirects(redirectedReference); + var perDirectoryResolution = perDirectoryCache.get(dirPath); + if (!perDirectoryResolution) { + perDirectoryResolution = ts.createMap(); + perDirectoryCache.set(dirPath, perDirectoryResolution); + } + var resolvedModules = []; + var compilerOptions = resolutionHost.getCompilationSettings(); + var hasInvalidatedNonRelativeUnresolvedImport = logChanges && isFileWithInvalidatedNonRelativeUnresolvedImports(path); + // All the resolutions in this file are invalidated if this file wasnt resolved using same redirect + var program = resolutionHost.getCurrentProgram(); + var oldRedirect = program && program.getResolvedProjectReferenceToRedirect(containingFile); + var unmatchedRedirects = oldRedirect ? + !redirectedReference || redirectedReference.sourceFile.path !== oldRedirect.sourceFile.path : + !!redirectedReference; + var seenNamesInFile = ts.createMap(); + for (var _i = 0, names_2 = names; _i < names_2.length; _i++) { + var name = names_2[_i]; + var resolution = resolutionsInFile.get(name); + // Resolution is valid if it is present and not invalidated + if (!seenNamesInFile.has(name) && + allFilesHaveInvalidatedResolution || unmatchedRedirects || !resolution || resolution.isInvalidated || + // If the name is unresolved import that was invalidated, recalculate + (hasInvalidatedNonRelativeUnresolvedImport && !ts.isExternalModuleNameRelative(name) && shouldRetryResolution(resolution))) { + var existingResolution = resolution; + var resolutionInDirectory = perDirectoryResolution.get(name); + if (resolutionInDirectory) { + resolution = resolutionInDirectory; + } + else { + resolution = loader(name, containingFile, compilerOptions, resolutionHost, redirectedReference); + perDirectoryResolution.set(name, resolution); + } + resolutionsInFile.set(name, resolution); + watchFailedLookupLocationsOfExternalModuleResolutions(name, resolution); + if (existingResolution) { + stopWatchFailedLookupLocationOfResolution(existingResolution); + } + if (logChanges && filesWithChangedSetOfUnresolvedImports && !resolutionIsEqualTo(existingResolution, resolution)) { + filesWithChangedSetOfUnresolvedImports.push(path); + // reset log changes to avoid recording the same file multiple times + logChanges = false; + } + } + ts.Debug.assert(resolution !== undefined && !resolution.isInvalidated); + seenNamesInFile.set(name, true); + resolvedModules.push(getResolutionWithResolvedFileName(resolution)); + } + // Stop watching and remove the unused name + resolutionsInFile.forEach(function (resolution, name) { + if (!seenNamesInFile.has(name) && !ts.contains(reusedNames, name)) { + stopWatchFailedLookupLocationOfResolution(resolution); + resolutionsInFile.delete(name); + } + }); + return resolvedModules; + function resolutionIsEqualTo(oldResolution, newResolution) { + if (oldResolution === newResolution) { + return true; + } + if (!oldResolution || !newResolution) { + return false; + } + var oldResult = getResolutionWithResolvedFileName(oldResolution); + var newResult = getResolutionWithResolvedFileName(newResolution); + if (oldResult === newResult) { + return true; + } + if (!oldResult || !newResult) { + return false; + } + return oldResult.resolvedFileName === newResult.resolvedFileName; + } + } + function resolveTypeReferenceDirectives(typeDirectiveNames, containingFile, redirectedReference) { + return resolveNamesWithLocalCache(typeDirectiveNames, containingFile, redirectedReference, resolvedTypeReferenceDirectives, perDirectoryResolvedTypeReferenceDirectives, ts.resolveTypeReferenceDirective, getResolvedTypeReferenceDirective, + /*shouldRetryResolution*/ function (resolution) { return resolution.resolvedTypeReferenceDirective === undefined; }, + /*reusedNames*/ undefined, /*logChanges*/ false); + } + function resolveModuleNames(moduleNames, containingFile, reusedNames, redirectedReference) { + return resolveNamesWithLocalCache(moduleNames, containingFile, redirectedReference, resolvedModuleNames, perDirectoryResolvedModuleNames, resolveModuleName, getResolvedModule, + /*shouldRetryResolution*/ function (resolution) { return !resolution.resolvedModule || !ts.resolutionExtensionIsTSOrJson(resolution.resolvedModule.extension); }, reusedNames, logChangesWhenResolvingModule); + } + function getResolvedModuleWithFailedLookupLocationsFromCache(moduleName, containingFile) { + var cache = resolvedModuleNames.get(resolutionHost.toPath(containingFile)); + return cache && cache.get(moduleName); + } + function isNodeModulesDirectory(dirPath) { + return ts.endsWith(dirPath, "/node_modules"); + } + function isNodeModulesAtTypesDirectory(dirPath) { + return ts.endsWith(dirPath, "/node_modules/@types"); + } + /** + * Filter out paths like + * "/", "/user", "/user/username", "/user/username/folderAtRoot", + * "c:/", "c:/users", "c:/users/username", "c:/users/username/folderAtRoot", "c:/folderAtRoot" + * @param dirPath + */ + function canWatchDirectory(dirPath) { + var rootLength = ts.getRootLength(dirPath); + if (dirPath.length === rootLength) { + // Ignore "/", "c:/" + return false; + } + var nextDirectorySeparator = dirPath.indexOf(ts.directorySeparator, rootLength); + if (nextDirectorySeparator === -1) { + // ignore "/user", "c:/users" or "c:/folderAtRoot" + return false; + } + if (dirPath.charCodeAt(0) !== 47 /* slash */ && + dirPath.substr(rootLength, nextDirectorySeparator).search(/users/i) === -1) { + // Paths like c:/folderAtRoot/subFolder are allowed + return true; + } + for (var searchIndex = nextDirectorySeparator + 1, searchLevels = 2; searchLevels > 0; searchLevels--) { + searchIndex = dirPath.indexOf(ts.directorySeparator, searchIndex) + 1; + if (searchIndex === 0) { + // Folder isnt at expected minimun levels + return false; + } + } + return true; + } + function getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath) { + if (isInDirectoryPath(rootPath, failedLookupLocationPath)) { + // Ensure failed look up is normalized path + failedLookupLocation = ts.isRootedDiskPath(failedLookupLocation) ? ts.normalizePath(failedLookupLocation) : ts.getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory()); + ts.Debug.assert(failedLookupLocation.length === failedLookupLocationPath.length, "FailedLookup: " + failedLookupLocation + " failedLookupLocationPath: " + failedLookupLocationPath); // tslint:disable-line + var subDirectoryInRoot = failedLookupLocationPath.indexOf(ts.directorySeparator, rootPath.length + 1); + if (subDirectoryInRoot !== -1) { + // Instead of watching root, watch directory in root to avoid watching excluded directories not needed for module resolution + return { dir: failedLookupLocation.substr(0, subDirectoryInRoot), dirPath: failedLookupLocationPath.substr(0, subDirectoryInRoot) }; + } + else { + // Always watch root directory non recursively + return { dir: rootDir, dirPath: rootPath, nonRecursive: false }; // TODO: GH#18217 + } + } + return getDirectoryToWatchFromFailedLookupLocationDirectory(ts.getDirectoryPath(ts.getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory())), ts.getDirectoryPath(failedLookupLocationPath)); + } + function getDirectoryToWatchFromFailedLookupLocationDirectory(dir, dirPath) { + // If directory path contains node module, get the most parent node_modules directory for watching + while (ts.pathContainsNodeModules(dirPath)) { + dir = ts.getDirectoryPath(dir); + dirPath = ts.getDirectoryPath(dirPath); + } + // If the directory is node_modules use it to watch, always watch it recursively + if (isNodeModulesDirectory(dirPath)) { + return canWatchDirectory(ts.getDirectoryPath(dirPath)) ? { dir: dir, dirPath: dirPath } : undefined; + } + var nonRecursive = true; + // Use some ancestor of the root directory + var subDirectoryPath, subDirectory; + if (rootPath !== undefined) { + while (!isInDirectoryPath(dirPath, rootPath)) { + var parentPath = ts.getDirectoryPath(dirPath); + if (parentPath === dirPath) { + break; + } + nonRecursive = false; + subDirectoryPath = dirPath; + subDirectory = dir; + dirPath = parentPath; + dir = ts.getDirectoryPath(dir); + } + } + return canWatchDirectory(dirPath) ? { dir: subDirectory || dir, dirPath: subDirectoryPath || dirPath, nonRecursive: nonRecursive } : undefined; + } + function isPathWithDefaultFailedLookupExtension(path) { + return ts.fileExtensionIsOneOf(path, failedLookupDefaultExtensions); + } + function watchFailedLookupLocationsOfExternalModuleResolutions(name, resolution) { + // No need to set the resolution refCount + if (resolution.failedLookupLocations && resolution.failedLookupLocations.length) { + if (resolution.refCount) { + resolution.refCount++; + } + else { + resolution.refCount = 1; + if (ts.isExternalModuleNameRelative(name)) { + watchFailedLookupLocationOfResolution(resolution); + } + else { + nonRelativeExternalModuleResolutions.add(name, resolution); + } + } + } + } + function watchFailedLookupLocationOfResolution(resolution) { + ts.Debug.assert(!!resolution.refCount); + var failedLookupLocations = resolution.failedLookupLocations; + var setAtRoot = false; + for (var _i = 0, failedLookupLocations_1 = failedLookupLocations; _i < failedLookupLocations_1.length; _i++) { + var failedLookupLocation = failedLookupLocations_1[_i]; + var failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation); + var toWatch = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath); + if (toWatch) { + var dir = toWatch.dir, dirPath = toWatch.dirPath, nonRecursive = toWatch.nonRecursive; + // If the failed lookup location path is not one of the supported extensions, + // store it in the custom path + if (!isPathWithDefaultFailedLookupExtension(failedLookupLocationPath)) { + var refCount = customFailedLookupPaths.get(failedLookupLocationPath) || 0; + customFailedLookupPaths.set(failedLookupLocationPath, refCount + 1); + } + if (dirPath === rootPath) { + ts.Debug.assert(!nonRecursive); + setAtRoot = true; + } + else { + setDirectoryWatcher(dir, dirPath, nonRecursive); + } + } + } + if (setAtRoot) { + // This is always non recursive + setDirectoryWatcher(rootDir, rootPath, /*nonRecursive*/ true); // TODO: GH#18217 + } + } + function setRefCountToUndefined(resolution) { + resolution.refCount = undefined; + } + function watchFailedLookupLocationOfNonRelativeModuleResolutions(resolutions, name) { + var program = resolutionHost.getCurrentProgram(); + var updateResolution = program && program.getTypeChecker().tryFindAmbientModuleWithoutAugmentations(name) ? + setRefCountToUndefined : watchFailedLookupLocationOfResolution; + resolutions.forEach(updateResolution); + } + function setDirectoryWatcher(dir, dirPath, nonRecursive) { + var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath); + if (dirWatcher) { + ts.Debug.assert(!!nonRecursive === !!dirWatcher.nonRecursive); + dirWatcher.refCount++; + } + else { + directoryWatchesOfFailedLookups.set(dirPath, { watcher: createDirectoryWatcher(dir, dirPath, nonRecursive), refCount: 1, nonRecursive: nonRecursive }); + } + } + function stopWatchFailedLookupLocationOfResolution(resolution) { + if (!resolution.refCount) { + return; + } + resolution.refCount--; + if (resolution.refCount) { + return; + } + var failedLookupLocations = resolution.failedLookupLocations; + var removeAtRoot = false; + for (var _i = 0, failedLookupLocations_2 = failedLookupLocations; _i < failedLookupLocations_2.length; _i++) { + var failedLookupLocation = failedLookupLocations_2[_i]; + var failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation); + var toWatch = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath); + if (toWatch) { + var dirPath = toWatch.dirPath; + var refCount = customFailedLookupPaths.get(failedLookupLocationPath); + if (refCount) { + if (refCount === 1) { + customFailedLookupPaths.delete(failedLookupLocationPath); + } + else { + ts.Debug.assert(refCount > 1); + customFailedLookupPaths.set(failedLookupLocationPath, refCount - 1); + } + } + if (dirPath === rootPath) { + removeAtRoot = true; + } + else { + removeDirectoryWatcher(dirPath); + } + } + } + if (removeAtRoot) { + removeDirectoryWatcher(rootPath); + } + } + function removeDirectoryWatcher(dirPath) { + var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath); + // Do not close the watcher yet since it might be needed by other failed lookup locations. + dirWatcher.refCount--; + } + function createDirectoryWatcher(directory, dirPath, nonRecursive) { + return resolutionHost.watchDirectoryOfFailedLookupLocation(directory, function (fileOrDirectory) { + var fileOrDirectoryPath = resolutionHost.toPath(fileOrDirectory); + if (cachedDirectoryStructureHost) { + // Since the file existence changed, update the sourceFiles cache + cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); + } + if (!allFilesHaveInvalidatedResolution && invalidateResolutionOfFailedLookupLocation(fileOrDirectoryPath, dirPath === fileOrDirectoryPath)) { + resolutionHost.onInvalidatedResolution(); + } + }, nonRecursive ? 0 /* None */ : 1 /* Recursive */); + } + function removeResolutionsOfFileFromCache(cache, filePath) { + // Deleted file, stop watching failed lookups for all the resolutions in the file + var resolutions = cache.get(filePath); + if (resolutions) { + resolutions.forEach(stopWatchFailedLookupLocationOfResolution); + cache.delete(filePath); + } + } + function removeResolutionsFromProjectReferenceRedirects(filePath) { + if (!ts.fileExtensionIs(filePath, ".json" /* Json */)) { + return; + } + var program = resolutionHost.getCurrentProgram(); + if (!program) { + return; + } + // If this file is input file for the referenced project, get it + var resolvedProjectReference = program.getResolvedProjectReferenceByPath(filePath); + if (!resolvedProjectReference) { + return; + } + // filePath is for the projectReference and the containing file is from this project reference, invalidate the resolution + resolvedProjectReference.commandLine.fileNames.forEach(function (f) { return removeResolutionsOfFile(resolutionHost.toPath(f)); }); + } + function removeResolutionsOfFile(filePath) { + removeResolutionsOfFileFromCache(resolvedModuleNames, filePath); + removeResolutionsOfFileFromCache(resolvedTypeReferenceDirectives, filePath); + } + function invalidateResolutionCache(cache, isInvalidatedResolution, getResolutionWithResolvedFileName) { + var seen = ts.createMap(); + cache.forEach(function (resolutions, containingFilePath) { + var dirPath = ts.getDirectoryPath(containingFilePath); + var seenInDir = seen.get(dirPath); + if (!seenInDir) { + seenInDir = ts.createMap(); + seen.set(dirPath, seenInDir); + } + resolutions.forEach(function (resolution, name) { + if (seenInDir.has(name)) { + return; + } + seenInDir.set(name, true); + if (!resolution.isInvalidated && isInvalidatedResolution(resolution, getResolutionWithResolvedFileName)) { + // Mark the file as needing re-evaluation of module resolution instead of using it blindly. + resolution.isInvalidated = true; + (filesWithInvalidatedResolutions || (filesWithInvalidatedResolutions = ts.createMap())).set(containingFilePath, true); + } + }); + }); + } + function hasReachedResolutionIterationLimit() { + var maxSize = resolutionHost.maxNumberOfFilesToIterateForInvalidation || ts.maxNumberOfFilesToIterateForInvalidation; + return resolvedModuleNames.size > maxSize || resolvedTypeReferenceDirectives.size > maxSize; + } + function invalidateResolutions(isInvalidatedResolution) { + // If more than maxNumberOfFilesToIterateForInvalidation present, + // just invalidated all files and recalculate the resolutions for files instead + if (hasReachedResolutionIterationLimit()) { + allFilesHaveInvalidatedResolution = true; + return; + } + invalidateResolutionCache(resolvedModuleNames, isInvalidatedResolution, getResolvedModule); + invalidateResolutionCache(resolvedTypeReferenceDirectives, isInvalidatedResolution, getResolvedTypeReferenceDirective); + } + function invalidateResolutionOfFile(filePath) { + removeResolutionsOfFile(filePath); + invalidateResolutions( + // Resolution is invalidated if the resulting file name is same as the deleted file path + function (resolution, getResolutionWithResolvedFileName) { + var result = getResolutionWithResolvedFileName(resolution); + return !!result && resolutionHost.toPath(result.resolvedFileName) === filePath; // TODO: GH#18217 + }); + } + function setFilesWithInvalidatedNonRelativeUnresolvedImports(filesMap) { + ts.Debug.assert(filesWithInvalidatedNonRelativeUnresolvedImports === filesMap || filesWithInvalidatedNonRelativeUnresolvedImports === undefined); + filesWithInvalidatedNonRelativeUnresolvedImports = filesMap; + } + function invalidateResolutionOfFailedLookupLocation(fileOrDirectoryPath, isCreatingWatchedDirectory) { + var isChangedFailedLookupLocation; + if (isCreatingWatchedDirectory) { + // Watching directory is created + // Invalidate any resolution has failed lookup in this directory + isChangedFailedLookupLocation = function (location) { return isInDirectoryPath(fileOrDirectoryPath, resolutionHost.toPath(location)); }; + } + else { + // If something to do with folder/file starting with "." in node_modules folder, skip it + if (isPathInNodeModulesStartingWithDot(fileOrDirectoryPath)) + return false; + // Some file or directory in the watching directory is created + // Return early if it does not have any of the watching extension or not the custom failed lookup path + var dirOfFileOrDirectory = ts.getDirectoryPath(fileOrDirectoryPath); + if (isNodeModulesAtTypesDirectory(fileOrDirectoryPath) || isNodeModulesDirectory(fileOrDirectoryPath) || + isNodeModulesAtTypesDirectory(dirOfFileOrDirectory) || isNodeModulesDirectory(dirOfFileOrDirectory)) { + // Invalidate any resolution from this directory + isChangedFailedLookupLocation = function (location) { + var locationPath = resolutionHost.toPath(location); + return locationPath === fileOrDirectoryPath || ts.startsWith(resolutionHost.toPath(location), fileOrDirectoryPath); + }; + } + else { + if (!isPathWithDefaultFailedLookupExtension(fileOrDirectoryPath) && !customFailedLookupPaths.has(fileOrDirectoryPath)) { + return false; + } + // Ignore emits from the program + if (ts.isEmittedFileOfProgram(resolutionHost.getCurrentProgram(), fileOrDirectoryPath)) { + return false; + } + // Resolution need to be invalidated if failed lookup location is same as the file or directory getting created + isChangedFailedLookupLocation = function (location) { return resolutionHost.toPath(location) === fileOrDirectoryPath; }; + } + } + var hasChangedFailedLookupLocation = function (resolution) { return ts.some(resolution.failedLookupLocations, isChangedFailedLookupLocation); }; + var invalidatedFilesCount = filesWithInvalidatedResolutions && filesWithInvalidatedResolutions.size; + invalidateResolutions( + // Resolution is invalidated if the resulting file name is same as the deleted file path + hasChangedFailedLookupLocation); + return allFilesHaveInvalidatedResolution || filesWithInvalidatedResolutions && filesWithInvalidatedResolutions.size !== invalidatedFilesCount; + } + function closeTypeRootsWatch() { + ts.clearMap(typeRootsWatches, ts.closeFileWatcher); + } + function getDirectoryToWatchFailedLookupLocationFromTypeRoot(typeRoot, typeRootPath) { + if (allFilesHaveInvalidatedResolution) { + return undefined; + } + if (isInDirectoryPath(rootPath, typeRootPath)) { + return rootPath; + } + var toWatch = getDirectoryToWatchFromFailedLookupLocationDirectory(typeRoot, typeRootPath); + return toWatch && directoryWatchesOfFailedLookups.has(toWatch.dirPath) ? toWatch.dirPath : undefined; + } + function createTypeRootsWatch(typeRootPath, typeRoot) { + // Create new watch and recursive info + return resolutionHost.watchTypeRootsDirectory(typeRoot, function (fileOrDirectory) { + var fileOrDirectoryPath = resolutionHost.toPath(fileOrDirectory); + if (cachedDirectoryStructureHost) { + // Since the file existence changed, update the sourceFiles cache + cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); + } + // For now just recompile + // We could potentially store more data here about whether it was/would be really be used or not + // and with that determine to trigger compilation but for now this is enough + resolutionHost.onChangedAutomaticTypeDirectiveNames(); + // Since directory watchers invoked are flaky, the failed lookup location events might not be triggered + // So handle to failed lookup locations here as well to ensure we are invalidating resolutions + var dirPath = getDirectoryToWatchFailedLookupLocationFromTypeRoot(typeRoot, typeRootPath); + if (dirPath && invalidateResolutionOfFailedLookupLocation(fileOrDirectoryPath, dirPath === fileOrDirectoryPath)) { + resolutionHost.onInvalidatedResolution(); + } + }, 1 /* Recursive */); + } + /** + * Watches the types that would get added as part of getAutomaticTypeDirectiveNames + * To be called when compiler options change + */ + function updateTypeRootsWatch() { + var options = resolutionHost.getCompilationSettings(); + if (options.types) { + // No need to do any watch since resolution cache is going to handle the failed lookups + // for the types added by this + closeTypeRootsWatch(); + return; + } + // we need to assume the directories exist to ensure that we can get all the type root directories that get included + // But filter directories that are at root level to say directory doesnt exist, so that we arent watching them + var typeRoots = ts.getEffectiveTypeRoots(options, { directoryExists: directoryExistsForTypeRootWatch, getCurrentDirectory: getCurrentDirectory }); + if (typeRoots) { + ts.mutateMap(typeRootsWatches, ts.arrayToMap(typeRoots, function (tr) { return resolutionHost.toPath(tr); }), { + createNewValue: createTypeRootsWatch, + onDeleteValue: ts.closeFileWatcher + }); + } + else { + closeTypeRootsWatch(); + } + } + /** + * Use this function to return if directory exists to get type roots to watch + * If we return directory exists then only the paths will be added to type roots + * Hence return true for all directories except root directories which are filtered from watching + */ + function directoryExistsForTypeRootWatch(nodeTypesDirectory) { + var dir = ts.getDirectoryPath(ts.getDirectoryPath(nodeTypesDirectory)); + var dirPath = resolutionHost.toPath(dir); + return dirPath === rootPath || canWatchDirectory(dirPath); + } + } + ts.createResolutionCache = createResolutionCache; +})(ts || (ts = {})); +// Used by importFixes, getEditsForFileRename, and declaration emit to synthesize import module specifiers. +/* @internal */ +var ts; +(function (ts) { + var moduleSpecifiers; + (function (moduleSpecifiers) { + var RelativePreference; + (function (RelativePreference) { + RelativePreference[RelativePreference["Relative"] = 0] = "Relative"; + RelativePreference[RelativePreference["NonRelative"] = 1] = "NonRelative"; + RelativePreference[RelativePreference["Auto"] = 2] = "Auto"; + })(RelativePreference || (RelativePreference = {})); + // See UserPreferences#importPathEnding + var Ending; + (function (Ending) { + Ending[Ending["Minimal"] = 0] = "Minimal"; + Ending[Ending["Index"] = 1] = "Index"; + Ending[Ending["JsExtension"] = 2] = "JsExtension"; + })(Ending || (Ending = {})); + function getPreferences(_a, compilerOptions, importingSourceFile) { + var importModuleSpecifierPreference = _a.importModuleSpecifierPreference, importModuleSpecifierEnding = _a.importModuleSpecifierEnding; + return { + relativePreference: importModuleSpecifierPreference === "relative" ? 0 /* Relative */ : importModuleSpecifierPreference === "non-relative" ? 1 /* NonRelative */ : 2 /* Auto */, + ending: getEnding(), + }; + function getEnding() { + switch (importModuleSpecifierEnding) { + case "minimal": return 0 /* Minimal */; + case "index": return 1 /* Index */; + case "js": return 2 /* JsExtension */; + default: return usesJsExtensionOnImports(importingSourceFile) ? 2 /* JsExtension */ + : ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.NodeJs ? 1 /* Index */ : 0 /* Minimal */; + } + } + } + function getPreferencesForUpdate(compilerOptions, oldImportSpecifier) { + return { + relativePreference: ts.isExternalModuleNameRelative(oldImportSpecifier) ? 0 /* Relative */ : 1 /* NonRelative */, + ending: ts.hasJSOrJsonFileExtension(oldImportSpecifier) ? 2 /* JsExtension */ + : ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.NodeJs || ts.endsWith(oldImportSpecifier, "index") ? 1 /* Index */ : 0 /* Minimal */, + }; + } + function updateModuleSpecifier(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, oldImportSpecifier) { + var res = getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, getPreferencesForUpdate(compilerOptions, oldImportSpecifier)); + if (res === oldImportSpecifier) + return undefined; + return res; + } + moduleSpecifiers.updateModuleSpecifier = updateModuleSpecifier; + // Note: importingSourceFile is just for usesJsExtensionOnImports + function getModuleSpecifier(compilerOptions, importingSourceFile, importingSourceFileName, toFileName, host, files, preferences, redirectTargetsMap) { + if (preferences === void 0) { preferences = {}; } + return getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, getPreferences(preferences, compilerOptions, importingSourceFile)); + } + moduleSpecifiers.getModuleSpecifier = getModuleSpecifier; + function getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, preferences) { + var info = getInfo(importingSourceFileName, host); + var modulePaths = getAllModulePaths(files, importingSourceFileName, toFileName, info.getCanonicalFileName, host, redirectTargetsMap); + return ts.firstDefined(modulePaths, function (moduleFileName) { return tryGetModuleNameAsNodeModule(moduleFileName, info, host, compilerOptions); }) || + getLocalModuleSpecifier(toFileName, info, compilerOptions, preferences); + } + // Returns an import for each symlink and for the realpath. + function getModuleSpecifiers(moduleSymbol, compilerOptions, importingSourceFile, host, files, userPreferences, redirectTargetsMap) { + var ambient = tryGetModuleNameFromAmbientModule(moduleSymbol); + if (ambient) + return [ambient]; + var info = getInfo(importingSourceFile.path, host); + var moduleSourceFile = ts.getSourceFileOfNode(moduleSymbol.valueDeclaration || ts.getNonAugmentationDeclaration(moduleSymbol)); + var modulePaths = getAllModulePaths(files, importingSourceFile.path, moduleSourceFile.fileName, info.getCanonicalFileName, host, redirectTargetsMap); + var preferences = getPreferences(userPreferences, compilerOptions, importingSourceFile); + var global = ts.mapDefined(modulePaths, function (moduleFileName) { return tryGetModuleNameAsNodeModule(moduleFileName, info, host, compilerOptions); }); + return global.length ? global : modulePaths.map(function (moduleFileName) { return getLocalModuleSpecifier(moduleFileName, info, compilerOptions, preferences); }); + } + moduleSpecifiers.getModuleSpecifiers = getModuleSpecifiers; + // importingSourceFileName is separate because getEditsForFileRename may need to specify an updated path + function getInfo(importingSourceFileName, host) { + var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames ? host.useCaseSensitiveFileNames() : true); + var sourceDirectory = ts.getDirectoryPath(importingSourceFileName); + return { getCanonicalFileName: getCanonicalFileName, sourceDirectory: sourceDirectory }; + } + function getLocalModuleSpecifier(moduleFileName, _a, compilerOptions, _b) { + var getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory; + var ending = _b.ending, relativePreference = _b.relativePreference; + var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths, rootDirs = compilerOptions.rootDirs; + var relativePath = rootDirs && tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName) || + removeExtensionAndIndexPostFix(ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, moduleFileName, getCanonicalFileName)), ending, compilerOptions); + if (!baseUrl || relativePreference === 0 /* Relative */) { + return relativePath; + } + var relativeToBaseUrl = getRelativePathIfInDirectory(moduleFileName, baseUrl, getCanonicalFileName); + if (!relativeToBaseUrl) { + return relativePath; + } + var importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, ending, compilerOptions); + var fromPaths = paths && tryGetModuleNameFromPaths(ts.removeFileExtension(relativeToBaseUrl), importRelativeToBaseUrl, paths); + var nonRelative = fromPaths === undefined ? importRelativeToBaseUrl : fromPaths; + if (relativePreference === 1 /* NonRelative */) { + return nonRelative; + } + if (relativePreference !== 2 /* Auto */) + ts.Debug.assertNever(relativePreference); + // Prefer a relative import over a baseUrl import if it has fewer components. + return isPathRelativeToParent(nonRelative) || countPathComponents(relativePath) < countPathComponents(nonRelative) ? relativePath : nonRelative; + } + function countPathComponents(path) { + var count = 0; + for (var i = ts.startsWith(path, "./") ? 2 : 0; i < path.length; i++) { + if (path.charCodeAt(i) === 47 /* slash */) + count++; + } + return count; + } + moduleSpecifiers.countPathComponents = countPathComponents; + function usesJsExtensionOnImports(_a) { + var imports = _a.imports; + return ts.firstDefined(imports, function (_a) { + var text = _a.text; + return ts.pathIsRelative(text) ? ts.hasJSOrJsonFileExtension(text) : undefined; + }) || false; + } + function stringsEqual(a, b, getCanonicalFileName) { + return getCanonicalFileName(a) === getCanonicalFileName(b); + } + // KLUDGE: Don't assume one 'node_modules' links to another. More likely a single directory inside the node_modules is the symlink. + // ALso, don't assume that an `@foo` directory is linked. More likely the contents of that are linked. + function isNodeModulesOrScopedPackageDirectory(s, getCanonicalFileName) { + return getCanonicalFileName(s) === "node_modules" || ts.startsWith(s, "@"); + } + function guessDirectorySymlink(a, b, cwd, getCanonicalFileName) { + var aParts = ts.getPathComponents(ts.toPath(a, cwd, getCanonicalFileName)); + var bParts = ts.getPathComponents(ts.toPath(b, cwd, getCanonicalFileName)); + while (!isNodeModulesOrScopedPackageDirectory(aParts[aParts.length - 2], getCanonicalFileName) && + !isNodeModulesOrScopedPackageDirectory(bParts[bParts.length - 2], getCanonicalFileName) && + stringsEqual(aParts[aParts.length - 1], bParts[bParts.length - 1], getCanonicalFileName)) { + aParts.pop(); + bParts.pop(); + } + return [ts.getPathFromPathComponents(aParts), ts.getPathFromPathComponents(bParts)]; + } + function discoverProbableSymlinks(files, getCanonicalFileName, cwd) { + var result = ts.createMap(); + var symlinks = ts.mapDefined(files, function (sf) { + return sf.resolvedModules && ts.firstDefinedIterator(sf.resolvedModules.values(), function (res) { + return res && res.originalPath && res.resolvedFileName !== res.originalPath ? [res.resolvedFileName, res.originalPath] : undefined; + }); + }); + for (var _i = 0, symlinks_1 = symlinks; _i < symlinks_1.length; _i++) { + var _a = symlinks_1[_i], resolvedPath = _a[0], originalPath = _a[1]; + var _b = guessDirectorySymlink(resolvedPath, originalPath, cwd, getCanonicalFileName), commonResolved = _b[0], commonOriginal = _b[1]; + result.set(commonOriginal, commonResolved); + } + return result; + } + /** + * Looks for existing imports that use symlinks to this module. + * Symlinks will be returned first so they are preferred over the real path. + */ + function getAllModulePaths(files, importingFileName, importedFileName, getCanonicalFileName, host, redirectTargetsMap) { + var redirects = redirectTargetsMap.get(importedFileName); + var importedFileNames = redirects ? redirects.concat([importedFileName]) : [importedFileName]; + var cwd = host.getCurrentDirectory ? host.getCurrentDirectory() : ""; + var targets = importedFileNames.map(function (f) { return ts.getNormalizedAbsolutePath(f, cwd); }); + var links = discoverProbableSymlinks(files, getCanonicalFileName, cwd); + var result = []; + var compareStrings = (!host.useCaseSensitiveFileNames || host.useCaseSensitiveFileNames()) ? ts.compareStringsCaseSensitive : ts.compareStringsCaseInsensitive; + links.forEach(function (resolved, path) { + if (ts.startsWithDirectory(importingFileName, resolved, getCanonicalFileName)) { + return; // Don't want to a package to globally import from itself + } + var target = targets.find(function (t) { return compareStrings(t.slice(0, resolved.length + 1), resolved + "/") === 0 /* EqualTo */; }); + if (target === undefined) + return; + var relative = ts.getRelativePathFromDirectory(resolved, target, getCanonicalFileName); + var option = ts.resolvePath(path, relative); + if (!host.fileExists || host.fileExists(option)) { + result.push(option); + } + }); + result.push.apply(result, targets); + return result; + } + function tryGetModuleNameFromAmbientModule(moduleSymbol) { + var decl = ts.find(moduleSymbol.declarations, function (d) { return ts.isNonGlobalAmbientModule(d) && (!ts.isExternalModuleAugmentation(d) || !ts.isExternalModuleNameRelative(ts.getTextOfIdentifierOrLiteral(d.name))); }); + if (decl) { + return decl.name.text; + } + } + function tryGetModuleNameFromPaths(relativeToBaseUrlWithIndex, relativeToBaseUrl, paths) { + for (var key in paths) { + for (var _i = 0, _a = paths[key]; _i < _a.length; _i++) { + var patternText_1 = _a[_i]; + var pattern = ts.removeFileExtension(ts.normalizePath(patternText_1)); + var indexOfStar = pattern.indexOf("*"); + if (indexOfStar !== -1) { + var prefix = pattern.substr(0, indexOfStar); + var suffix = pattern.substr(indexOfStar + 1); + if (relativeToBaseUrl.length >= prefix.length + suffix.length && + ts.startsWith(relativeToBaseUrl, prefix) && + ts.endsWith(relativeToBaseUrl, suffix) || + !suffix && relativeToBaseUrl === ts.removeTrailingDirectorySeparator(prefix)) { + var matchedStar = relativeToBaseUrl.substr(prefix.length, relativeToBaseUrl.length - suffix.length); + return key.replace("*", matchedStar); + } + } + else if (pattern === relativeToBaseUrl || pattern === relativeToBaseUrlWithIndex) { + return key; + } + } + } + } + function tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName) { + var normalizedTargetPath = getPathRelativeToRootDirs(moduleFileName, rootDirs, getCanonicalFileName); + if (normalizedTargetPath === undefined) { + return undefined; + } + var normalizedSourcePath = getPathRelativeToRootDirs(sourceDirectory, rootDirs, getCanonicalFileName); + var relativePath = normalizedSourcePath !== undefined ? ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(normalizedSourcePath, normalizedTargetPath, getCanonicalFileName)) : normalizedTargetPath; + return ts.removeFileExtension(relativePath); + } + function tryGetModuleNameAsNodeModule(moduleFileName, _a, host, options) { + var getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory; + if (!host.fileExists || !host.readFile) { + return undefined; + } + var parts = getNodeModulePathParts(moduleFileName); + if (!parts) { + return undefined; + } + var packageRootPath = moduleFileName.substring(0, parts.packageRootIndex); + var packageJsonPath = ts.combinePaths(packageRootPath, "package.json"); + var packageJsonContent = host.fileExists(packageJsonPath) + ? JSON.parse(host.readFile(packageJsonPath)) + : undefined; + var versionPaths = packageJsonContent && packageJsonContent.typesVersions + ? ts.getPackageJsonTypesVersionsPaths(packageJsonContent.typesVersions) + : undefined; + if (versionPaths) { + var subModuleName = moduleFileName.slice(parts.packageRootIndex + 1); + var fromPaths = tryGetModuleNameFromPaths(ts.removeFileExtension(subModuleName), removeExtensionAndIndexPostFix(subModuleName, 0 /* Minimal */, options), versionPaths.paths); + if (fromPaths !== undefined) { + moduleFileName = ts.combinePaths(moduleFileName.slice(0, parts.packageRootIndex), fromPaths); + } + } + // Simplify the full file path to something that can be resolved by Node. + // If the module could be imported by a directory name, use that directory's name + var moduleSpecifier = getDirectoryOrExtensionlessFileName(moduleFileName); + // Get a path that's relative to node_modules or the importing file's path + // if node_modules folder is in this folder or any of its parent folders, no need to keep it. + if (!ts.startsWith(sourceDirectory, getCanonicalFileName(moduleSpecifier.substring(0, parts.topLevelNodeModulesIndex)))) + return undefined; + // If the module was found in @types, get the actual Node package name + var nodeModulesDirectoryName = moduleSpecifier.substring(parts.topLevelPackageNameIndex + 1); + var packageName = ts.getPackageNameFromTypesPackageName(nodeModulesDirectoryName); + // For classic resolution, only allow importing from node_modules/@types, not other node_modules + return ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs && packageName === nodeModulesDirectoryName ? undefined : packageName; + function getDirectoryOrExtensionlessFileName(path) { + // If the file is the main module, it can be imported by the package name + if (packageJsonContent) { + var mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main; + if (mainFileRelative) { + var mainExportFile = ts.toPath(mainFileRelative, packageRootPath, getCanonicalFileName); + if (ts.removeFileExtension(mainExportFile) === ts.removeFileExtension(getCanonicalFileName(path))) { + return packageRootPath; + } + } + } + // We still have a file name - remove the extension + var fullModulePathWithoutExtension = ts.removeFileExtension(path); + // If the file is /index, it can be imported by its directory name + // IFF there is not _also_ a file by the same name + if (getCanonicalFileName(fullModulePathWithoutExtension.substring(parts.fileNameIndex)) === "/index" && !tryGetAnyFileFromPath(host, fullModulePathWithoutExtension.substring(0, parts.fileNameIndex))) { + return fullModulePathWithoutExtension.substring(0, parts.fileNameIndex); + } + return fullModulePathWithoutExtension; + } + } + function tryGetAnyFileFromPath(host, path) { + if (!host.fileExists) + return; + // We check all js, `node` and `json` extensions in addition to TS, since node module resolution would also choose those over the directory + var extensions = ts.getSupportedExtensions({ allowJs: true }, [{ extension: "node", isMixedContent: false }, { extension: "json", isMixedContent: false, scriptKind: 6 /* JSON */ }]); + for (var _i = 0, extensions_3 = extensions; _i < extensions_3.length; _i++) { + var e = extensions_3[_i]; + var fullPath = path + e; + if (host.fileExists(fullPath)) { + return fullPath; + } + } + } + function getNodeModulePathParts(fullPath) { + // If fullPath can't be valid module file within node_modules, returns undefined. + // Example of expected pattern: /base/path/node_modules/[@scope/otherpackage/@otherscope/node_modules/]package/[subdirectory/]file.js + // Returns indices: ^ ^ ^ ^ + var topLevelNodeModulesIndex = 0; + var topLevelPackageNameIndex = 0; + var packageRootIndex = 0; + var fileNameIndex = 0; + var States; + (function (States) { + States[States["BeforeNodeModules"] = 0] = "BeforeNodeModules"; + States[States["NodeModules"] = 1] = "NodeModules"; + States[States["Scope"] = 2] = "Scope"; + States[States["PackageContent"] = 3] = "PackageContent"; + })(States || (States = {})); + var partStart = 0; + var partEnd = 0; + var state = 0 /* BeforeNodeModules */; + while (partEnd >= 0) { + partStart = partEnd; + partEnd = fullPath.indexOf("/", partStart + 1); + switch (state) { + case 0 /* BeforeNodeModules */: + if (fullPath.indexOf(ts.nodeModulesPathPart, partStart) === partStart) { + topLevelNodeModulesIndex = partStart; + topLevelPackageNameIndex = partEnd; + state = 1 /* NodeModules */; + } + break; + case 1 /* NodeModules */: + case 2 /* Scope */: + if (state === 1 /* NodeModules */ && fullPath.charAt(partStart + 1) === "@") { + state = 2 /* Scope */; + } + else { + packageRootIndex = partEnd; + state = 3 /* PackageContent */; + } + break; + case 3 /* PackageContent */: + if (fullPath.indexOf(ts.nodeModulesPathPart, partStart) === partStart) { + state = 1 /* NodeModules */; + } + else { + state = 3 /* PackageContent */; + } + break; + } + } + fileNameIndex = partStart; + return state > 1 /* NodeModules */ ? { topLevelNodeModulesIndex: topLevelNodeModulesIndex, topLevelPackageNameIndex: topLevelPackageNameIndex, packageRootIndex: packageRootIndex, fileNameIndex: fileNameIndex } : undefined; + } + function getPathRelativeToRootDirs(path, rootDirs, getCanonicalFileName) { + return ts.firstDefined(rootDirs, function (rootDir) { + var relativePath = getRelativePathIfInDirectory(path, rootDir, getCanonicalFileName); // TODO: GH#18217 + return isPathRelativeToParent(relativePath) ? undefined : relativePath; + }); + } + function removeExtensionAndIndexPostFix(fileName, ending, options) { + if (ts.fileExtensionIs(fileName, ".json" /* Json */)) + return fileName; + var noExtension = ts.removeFileExtension(fileName); + switch (ending) { + case 0 /* Minimal */: + return ts.removeSuffix(noExtension, "/index"); + case 1 /* Index */: + return noExtension; + case 2 /* JsExtension */: + return noExtension + getJSExtensionForFile(fileName, options); + default: + return ts.Debug.assertNever(ending); + } + } + function getJSExtensionForFile(fileName, options) { + var ext = ts.extensionFromPath(fileName); + switch (ext) { + case ".ts" /* Ts */: + case ".d.ts" /* Dts */: + return ".js" /* Js */; + case ".tsx" /* Tsx */: + return options.jsx === 1 /* Preserve */ ? ".jsx" /* Jsx */ : ".js" /* Js */; + case ".js" /* Js */: + case ".jsx" /* Jsx */: + case ".json" /* Json */: + return ext; + default: + return ts.Debug.assertNever(ext); + } + } + function getRelativePathIfInDirectory(path, directoryPath, getCanonicalFileName) { + var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); + return ts.isRootedDiskPath(relativePath) ? undefined : relativePath; + } + function isPathRelativeToParent(path) { + return ts.startsWith(path, ".."); + } + })(moduleSpecifiers = ts.moduleSpecifiers || (ts.moduleSpecifiers = {})); +})(ts || (ts = {})); +/*@internal*/ +var ts; +(function (ts) { + var sysFormatDiagnosticsHost = ts.sys ? { + getCurrentDirectory: function () { return ts.sys.getCurrentDirectory(); }, + getNewLine: function () { return ts.sys.newLine; }, + getCanonicalFileName: ts.createGetCanonicalFileName(ts.sys.useCaseSensitiveFileNames) + } : undefined; // TODO: GH#18217 + /** + * Create a function that reports error by writing to the system and handles the formating of the diagnostic + */ + function createDiagnosticReporter(system, pretty) { + var host = system === ts.sys ? sysFormatDiagnosticsHost : { + getCurrentDirectory: function () { return system.getCurrentDirectory(); }, + getNewLine: function () { return system.newLine; }, + getCanonicalFileName: ts.createGetCanonicalFileName(system.useCaseSensitiveFileNames), + }; + if (!pretty) { + return function (diagnostic) { return system.write(ts.formatDiagnostic(diagnostic, host)); }; + } + var diagnostics = new Array(1); + return function (diagnostic) { + diagnostics[0] = diagnostic; + system.write(ts.formatDiagnosticsWithColorAndContext(diagnostics, host) + host.getNewLine()); + diagnostics[0] = undefined; // TODO: GH#18217 + }; + } + ts.createDiagnosticReporter = createDiagnosticReporter; + /** + * @returns Whether the screen was cleared. + */ + function clearScreenIfNotWatchingForFileChanges(system, diagnostic, options) { + if (system.clearScreen && + !options.preserveWatchOutput && + !options.extendedDiagnostics && + !options.diagnostics && + ts.contains(ts.screenStartingMessageCodes, diagnostic.code)) { + system.clearScreen(); + return true; + } + return false; + } + ts.screenStartingMessageCodes = [ + ts.Diagnostics.Starting_compilation_in_watch_mode.code, + ts.Diagnostics.File_change_detected_Starting_incremental_compilation.code, + ]; + function getPlainDiagnosticFollowingNewLines(diagnostic, newLine) { + return ts.contains(ts.screenStartingMessageCodes, diagnostic.code) + ? newLine + newLine + : newLine; + } + /** + * Create a function that reports watch status by writing to the system and handles the formating of the diagnostic + */ + function createWatchStatusReporter(system, pretty) { + return pretty ? + function (diagnostic, newLine, options) { + clearScreenIfNotWatchingForFileChanges(system, diagnostic, options); + var output = "[" + ts.formatColorAndReset(new Date().toLocaleTimeString(), ts.ForegroundColorEscapeSequences.Grey) + "] "; + output += "" + ts.flattenDiagnosticMessageText(diagnostic.messageText, system.newLine) + (newLine + newLine); + system.write(output); + } : + function (diagnostic, newLine, options) { + var output = ""; + if (!clearScreenIfNotWatchingForFileChanges(system, diagnostic, options)) { + output += newLine; + } + output += new Date().toLocaleTimeString() + " - "; + output += "" + ts.flattenDiagnosticMessageText(diagnostic.messageText, system.newLine) + getPlainDiagnosticFollowingNewLines(diagnostic, newLine); + system.write(output); + }; + } + ts.createWatchStatusReporter = createWatchStatusReporter; + /** Parses config file using System interface */ + function parseConfigFileWithSystem(configFileName, optionsToExtend, system, reportDiagnostic) { + var host = system; + host.onUnRecoverableConfigFileDiagnostic = function (diagnostic) { return reportUnrecoverableDiagnostic(ts.sys, reportDiagnostic, diagnostic); }; + var result = ts.getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host); + host.onUnRecoverableConfigFileDiagnostic = undefined; // TODO: GH#18217 + return result; + } + ts.parseConfigFileWithSystem = parseConfigFileWithSystem; + function getErrorCountForSummary(diagnostics) { + return ts.countWhere(diagnostics, function (diagnostic) { return diagnostic.category === ts.DiagnosticCategory.Error; }); + } + ts.getErrorCountForSummary = getErrorCountForSummary; + function getWatchErrorSummaryDiagnosticMessage(errorCount) { + return errorCount === 1 ? + ts.Diagnostics.Found_1_error_Watching_for_file_changes : + ts.Diagnostics.Found_0_errors_Watching_for_file_changes; + } + ts.getWatchErrorSummaryDiagnosticMessage = getWatchErrorSummaryDiagnosticMessage; + function getErrorSummaryText(errorCount, newLine) { + if (errorCount === 0) + return ""; + var d = ts.createCompilerDiagnostic(errorCount === 1 ? ts.Diagnostics.Found_1_error : ts.Diagnostics.Found_0_errors, errorCount); + return "" + newLine + ts.flattenDiagnosticMessageText(d.messageText, newLine) + newLine + newLine; + } + ts.getErrorSummaryText = getErrorSummaryText; + /** + * Helper that emit files, report diagnostics and lists emitted and/or source files depending on compiler options + */ + function emitFilesAndReportErrors(program, reportDiagnostic, writeFileName, reportSummary, writeFile) { + // First get and report any syntactic errors. + var diagnostics = program.getConfigFileParsingDiagnostics().slice(); + var configFileParsingDiagnosticsLength = diagnostics.length; + ts.addRange(diagnostics, program.getSyntacticDiagnostics()); + var reportSemanticDiagnostics = false; + // If we didn't have any syntactic errors, then also try getting the global and + // semantic errors. + if (diagnostics.length === configFileParsingDiagnosticsLength) { + ts.addRange(diagnostics, program.getOptionsDiagnostics()); + ts.addRange(diagnostics, program.getGlobalDiagnostics()); + if (diagnostics.length === configFileParsingDiagnosticsLength) { + reportSemanticDiagnostics = true; + } + } + // Emit and report any errors we ran into. + var _a = program.emit(/*targetSourceFile*/ undefined, writeFile), emittedFiles = _a.emittedFiles, emitSkipped = _a.emitSkipped, emitDiagnostics = _a.diagnostics; + ts.addRange(diagnostics, emitDiagnostics); + if (reportSemanticDiagnostics) { + ts.addRange(diagnostics, program.getSemanticDiagnostics()); + } + ts.sortAndDeduplicateDiagnostics(diagnostics).forEach(reportDiagnostic); + if (writeFileName) { + var currentDir_1 = program.getCurrentDirectory(); + ts.forEach(emittedFiles, function (file) { + var filepath = ts.getNormalizedAbsolutePath(file, currentDir_1); + writeFileName("TSFILE: " + filepath); + }); + if (program.getCompilerOptions().listFiles) { + ts.forEach(program.getSourceFiles(), function (file) { + writeFileName(file.fileName); + }); + } + } + if (reportSummary) { + reportSummary(getErrorCountForSummary(diagnostics)); + } + if (emitSkipped && diagnostics.length > 0) { + // If the emitter didn't emit anything, then pass that value along. + return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; + } + else if (diagnostics.length > 0) { + // The emitter emitted something, inform the caller if that happened in the presence + // of diagnostics or not. + return ts.ExitStatus.DiagnosticsPresent_OutputsGenerated; + } + return ts.ExitStatus.Success; + } + ts.emitFilesAndReportErrors = emitFilesAndReportErrors; + var noopFileWatcher = { close: ts.noop }; + function createWatchHost(system, reportWatchStatus) { + if (system === void 0) { system = ts.sys; } + var onWatchStatusChange = reportWatchStatus || createWatchStatusReporter(system); + return { + onWatchStatusChange: onWatchStatusChange, + watchFile: system.watchFile ? (function (path, callback, pollingInterval) { return system.watchFile(path, callback, pollingInterval); }) : function () { return noopFileWatcher; }, + watchDirectory: system.watchDirectory ? (function (path, callback, recursive) { return system.watchDirectory(path, callback, recursive); }) : function () { return noopFileWatcher; }, + setTimeout: system.setTimeout ? (function (callback, ms) { + var args = []; + for (var _i = 2; _i < arguments.length; _i++) { + args[_i - 2] = arguments[_i]; + } + var _a; + return (_a = system.setTimeout).call.apply(_a, [system, callback, ms].concat(args)); + }) : ts.noop, + clearTimeout: system.clearTimeout ? (function (timeoutId) { return system.clearTimeout(timeoutId); }) : ts.noop + }; + } + ts.createWatchHost = createWatchHost; + /** + * Creates the watch compiler host that can be extended with config file or root file names and options host + */ + function createWatchCompilerHost(system, createProgram, reportDiagnostic, reportWatchStatus) { + if (system === void 0) { system = ts.sys; } + if (!createProgram) { + createProgram = ts.createEmitAndSemanticDiagnosticsBuilderProgram; + } + var host = system; + host; // tslint:disable-line no-unused-expression (TODO: `host` is unused!) + var useCaseSensitiveFileNames = function () { return system.useCaseSensitiveFileNames; }; + var writeFileName = function (s) { return system.write(s + system.newLine); }; + var _a = createWatchHost(system, reportWatchStatus), onWatchStatusChange = _a.onWatchStatusChange, watchFile = _a.watchFile, watchDirectory = _a.watchDirectory, setTimeout = _a.setTimeout, clearTimeout = _a.clearTimeout; + return { + useCaseSensitiveFileNames: useCaseSensitiveFileNames, + getNewLine: function () { return system.newLine; }, + getCurrentDirectory: function () { return system.getCurrentDirectory(); }, + getDefaultLibLocation: getDefaultLibLocation, + getDefaultLibFileName: function (options) { return ts.combinePaths(getDefaultLibLocation(), ts.getDefaultLibFileName(options)); }, + fileExists: function (path) { return system.fileExists(path); }, + readFile: function (path, encoding) { return system.readFile(path, encoding); }, + directoryExists: function (path) { return system.directoryExists(path); }, + getDirectories: function (path) { return system.getDirectories(path); }, + readDirectory: function (path, extensions, exclude, include, depth) { return system.readDirectory(path, extensions, exclude, include, depth); }, + realpath: system.realpath && (function (path) { return system.realpath(path); }), + getEnvironmentVariable: system.getEnvironmentVariable && (function (name) { return system.getEnvironmentVariable(name); }), + watchFile: watchFile, + watchDirectory: watchDirectory, + setTimeout: setTimeout, + clearTimeout: clearTimeout, + trace: function (s) { return system.write(s); }, + onWatchStatusChange: onWatchStatusChange, + createDirectory: function (path) { return system.createDirectory(path); }, + writeFile: function (path, data, writeByteOrderMark) { return system.writeFile(path, data, writeByteOrderMark); }, + onCachedDirectoryStructureHostCreate: function (cacheHost) { return host = cacheHost || system; }, + createHash: system.createHash && (function (s) { return system.createHash(s); }), + createProgram: createProgram, + afterProgramCreate: emitFilesAndReportErrorUsingBuilder + }; + function getDefaultLibLocation() { + return ts.getDirectoryPath(ts.normalizePath(system.getExecutingFilePath())); + } + function emitFilesAndReportErrorUsingBuilder(builderProgram) { + var compilerOptions = builderProgram.getCompilerOptions(); + var newLine = ts.getNewLineCharacter(compilerOptions, function () { return system.newLine; }); + emitFilesAndReportErrors(builderProgram, reportDiagnostic, writeFileName, function (errorCount) { return onWatchStatusChange(ts.createCompilerDiagnostic(getWatchErrorSummaryDiagnosticMessage(errorCount), errorCount), newLine, compilerOptions); }); + } + } + /** + * Report error and exit + */ + function reportUnrecoverableDiagnostic(system, reportDiagnostic, diagnostic) { + reportDiagnostic(diagnostic); + system.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); + } + /** + * Creates the watch compiler host from system for config file in watch mode + */ + function createWatchCompilerHostOfConfigFile(configFileName, optionsToExtend, system, createProgram, reportDiagnostic, reportWatchStatus) { + var diagnosticReporter = reportDiagnostic || createDiagnosticReporter(system); + var host = createWatchCompilerHost(system, createProgram, diagnosticReporter, reportWatchStatus); + host.onUnRecoverableConfigFileDiagnostic = function (diagnostic) { return reportUnrecoverableDiagnostic(system, diagnosticReporter, diagnostic); }; + host.configFileName = configFileName; + host.optionsToExtend = optionsToExtend; + return host; + } + ts.createWatchCompilerHostOfConfigFile = createWatchCompilerHostOfConfigFile; + /** + * Creates the watch compiler host from system for compiling root files and options in watch mode + */ + function createWatchCompilerHostOfFilesAndCompilerOptions(rootFiles, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences) { + var host = createWatchCompilerHost(system, createProgram, reportDiagnostic || createDiagnosticReporter(system), reportWatchStatus); + host.rootFiles = rootFiles; + host.options = options; + host.projectReferences = projectReferences; + return host; + } + ts.createWatchCompilerHostOfFilesAndCompilerOptions = createWatchCompilerHostOfFilesAndCompilerOptions; +})(ts || (ts = {})); +(function (ts) { + function createWatchCompilerHost(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences) { + if (ts.isArray(rootFilesOrConfigFileName)) { + return ts.createWatchCompilerHostOfFilesAndCompilerOptions(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences); // TODO: GH#18217 + } + else { + return ts.createWatchCompilerHostOfConfigFile(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus); + } + } + ts.createWatchCompilerHost = createWatchCompilerHost; + var initialVersion = 1; + function createWatchProgram(host) { + var builderProgram; + var reloadLevel; // level to indicate if the program needs to be reloaded from config file/just filenames etc + var missingFilesMap; // Map of file watchers for the missing files + var watchedWildcardDirectories; // map of watchers for the wild card directories in the config file + var timerToUpdateProgram; // timer callback to recompile the program + var sourceFilesCache = ts.createMap(); // Cache that stores the source file and version info + var missingFilePathsRequestedForRelease; // These paths are held temparirly so that we can remove the entry from source file cache if the file is not tracked by missing files + var hasChangedCompilerOptions = false; // True if the compiler options have changed between compilations + var hasChangedAutomaticTypeDirectiveNames = false; // True if the automatic type directives have changed + var useCaseSensitiveFileNames = host.useCaseSensitiveFileNames(); + var currentDirectory = host.getCurrentDirectory(); + var getCurrentDirectory = function () { return currentDirectory; }; + var readFile = function (path, encoding) { return host.readFile(path, encoding); }; + var configFileName = host.configFileName, _a = host.optionsToExtend, optionsToExtendForConfigFile = _a === void 0 ? {} : _a, createProgram = host.createProgram; + var rootFileNames = host.rootFiles, compilerOptions = host.options, projectReferences = host.projectReferences; + var configFileSpecs; + var configFileParsingDiagnostics; + var canConfigFileJsonReportNoInputFiles = false; + var hasChangedConfigFileParsingErrors = false; + var cachedDirectoryStructureHost = configFileName === undefined ? undefined : ts.createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensitiveFileNames); + if (cachedDirectoryStructureHost && host.onCachedDirectoryStructureHostCreate) { + host.onCachedDirectoryStructureHostCreate(cachedDirectoryStructureHost); + } + var directoryStructureHost = cachedDirectoryStructureHost || host; + var parseConfigFileHost = { + useCaseSensitiveFileNames: useCaseSensitiveFileNames, + readDirectory: function (path, extensions, exclude, include, depth) { return directoryStructureHost.readDirectory(path, extensions, exclude, include, depth); }, + fileExists: function (path) { return host.fileExists(path); }, + readFile: readFile, + getCurrentDirectory: getCurrentDirectory, + onUnRecoverableConfigFileDiagnostic: host.onUnRecoverableConfigFileDiagnostic, + trace: host.trace ? function (s) { return host.trace(s); } : undefined + }; + // From tsc we want to get already parsed result and hence check for rootFileNames + var newLine = updateNewLine(); + if (configFileName && host.configFileParsingResult) { + setConfigFileParsingResult(host.configFileParsingResult); + newLine = updateNewLine(); + } + reportWatchDiagnostic(ts.Diagnostics.Starting_compilation_in_watch_mode); + if (configFileName && !host.configFileParsingResult) { + newLine = ts.getNewLineCharacter(optionsToExtendForConfigFile, function () { return host.getNewLine(); }); + ts.Debug.assert(!rootFileNames); + parseConfigFile(); + newLine = updateNewLine(); + } + var trace = host.trace && (function (s) { host.trace(s + newLine); }); + var watchLogLevel = trace ? compilerOptions.extendedDiagnostics ? ts.WatchLogLevel.Verbose : + compilerOptions.diagnostics ? ts.WatchLogLevel.TriggerOnly : ts.WatchLogLevel.None : ts.WatchLogLevel.None; + var writeLog = watchLogLevel !== ts.WatchLogLevel.None ? trace : ts.noop; // TODO: GH#18217 + var _b = ts.getWatchFactory(watchLogLevel, writeLog), watchFile = _b.watchFile, watchFilePath = _b.watchFilePath, watchDirectory = _b.watchDirectory; + var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); + writeLog("Current directory: " + currentDirectory + " CaseSensitiveFileNames: " + useCaseSensitiveFileNames); + if (configFileName) { + watchFile(host, configFileName, scheduleProgramReload, ts.PollingInterval.High, "Config file"); + } + var compilerHost = { + // Members for CompilerHost + getSourceFile: function (fileName, languageVersion, onError, shouldCreateNewSourceFile) { return getVersionedSourceFileByPath(fileName, toPath(fileName), languageVersion, onError, shouldCreateNewSourceFile); }, + getSourceFileByPath: getVersionedSourceFileByPath, + getDefaultLibLocation: host.getDefaultLibLocation && (function () { return host.getDefaultLibLocation(); }), + getDefaultLibFileName: function (options) { return host.getDefaultLibFileName(options); }, + writeFile: writeFile, + getCurrentDirectory: getCurrentDirectory, + useCaseSensitiveFileNames: function () { return useCaseSensitiveFileNames; }, + getCanonicalFileName: getCanonicalFileName, + getNewLine: function () { return newLine; }, + fileExists: fileExists, + readFile: readFile, + trace: trace, + directoryExists: directoryStructureHost.directoryExists && (function (path) { return directoryStructureHost.directoryExists(path); }), + getDirectories: (directoryStructureHost.getDirectories && (function (path) { return directoryStructureHost.getDirectories(path); })), + realpath: host.realpath && (function (s) { return host.realpath(s); }), + getEnvironmentVariable: host.getEnvironmentVariable ? (function (name) { return host.getEnvironmentVariable(name); }) : (function () { return ""; }), + onReleaseOldSourceFile: onReleaseOldSourceFile, + createHash: host.createHash && (function (data) { return host.createHash(data); }), + // Members for ResolutionCacheHost + toPath: toPath, + getCompilationSettings: function () { return compilerOptions; }, + watchDirectoryOfFailedLookupLocation: function (dir, cb, flags) { return watchDirectory(host, dir, cb, flags, "Failed Lookup Locations"); }, + watchTypeRootsDirectory: function (dir, cb, flags) { return watchDirectory(host, dir, cb, flags, "Type roots"); }, + getCachedDirectoryStructureHost: function () { return cachedDirectoryStructureHost; }, + onInvalidatedResolution: scheduleProgramUpdate, + onChangedAutomaticTypeDirectiveNames: function () { + hasChangedAutomaticTypeDirectiveNames = true; + scheduleProgramUpdate(); + }, + maxNumberOfFilesToIterateForInvalidation: host.maxNumberOfFilesToIterateForInvalidation, + getCurrentProgram: getCurrentProgram, + writeLog: writeLog, + readDirectory: function (path, extensions, exclude, include, depth) { return directoryStructureHost.readDirectory(path, extensions, exclude, include, depth); }, + }; + // Cache for the module resolution + var resolutionCache = ts.createResolutionCache(compilerHost, configFileName ? + ts.getDirectoryPath(ts.getNormalizedAbsolutePath(configFileName, currentDirectory)) : + currentDirectory, + /*logChangesWhenResolvingModule*/ false); + // Resolve module using host module resolution strategy if provided otherwise use resolution cache to resolve module names + compilerHost.resolveModuleNames = host.resolveModuleNames ? + (function (moduleNames, containingFile, reusedNames, redirectedReference) { return host.resolveModuleNames(moduleNames, containingFile, reusedNames, redirectedReference); }) : + (function (moduleNames, containingFile, reusedNames, redirectedReference) { return resolutionCache.resolveModuleNames(moduleNames, containingFile, reusedNames, redirectedReference); }); + compilerHost.resolveTypeReferenceDirectives = host.resolveTypeReferenceDirectives ? + (function (typeDirectiveNames, containingFile, redirectedReference) { return host.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile, redirectedReference); }) : + (function (typeDirectiveNames, containingFile, redirectedReference) { return resolutionCache.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile, redirectedReference); }); + var userProvidedResolution = !!host.resolveModuleNames || !!host.resolveTypeReferenceDirectives; + synchronizeProgram(); + // Update the wild card directory watch + watchConfigFileWildCardDirectories(); + return configFileName ? + { getCurrentProgram: getCurrentBuilderProgram, getProgram: synchronizeProgram } : + { getCurrentProgram: getCurrentBuilderProgram, getProgram: synchronizeProgram, updateRootFileNames: updateRootFileNames }; + function getCurrentBuilderProgram() { + return builderProgram; + } + function getCurrentProgram() { + return builderProgram && builderProgram.getProgram(); + } + function synchronizeProgram() { + writeLog("Synchronizing program"); + var program = getCurrentProgram(); + if (hasChangedCompilerOptions) { + newLine = updateNewLine(); + if (program && ts.changesAffectModuleResolution(program.getCompilerOptions(), compilerOptions)) { + resolutionCache.clear(); + } + } + // All resolutions are invalid if user provided resolutions + var hasInvalidatedResolution = resolutionCache.createHasInvalidatedResolution(userProvidedResolution); + if (ts.isProgramUptoDate(getCurrentProgram(), rootFileNames, compilerOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, projectReferences)) { + if (hasChangedConfigFileParsingErrors) { + builderProgram = createProgram(/*rootNames*/ undefined, /*options*/ undefined, compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences); + hasChangedConfigFileParsingErrors = false; + } + } + else { + createNewProgram(program, hasInvalidatedResolution); + } + if (host.afterProgramCreate) { + host.afterProgramCreate(builderProgram); + } + return builderProgram; + } + function createNewProgram(program, hasInvalidatedResolution) { + // Compile the program + if (watchLogLevel !== ts.WatchLogLevel.None) { + writeLog("CreatingProgramWith::"); + writeLog(" roots: " + JSON.stringify(rootFileNames)); + writeLog(" options: " + JSON.stringify(compilerOptions)); + } + var needsUpdateInTypeRootWatch = hasChangedCompilerOptions || !program; + hasChangedCompilerOptions = false; + hasChangedConfigFileParsingErrors = false; + resolutionCache.startCachingPerDirectoryResolution(); + compilerHost.hasInvalidatedResolution = hasInvalidatedResolution; + compilerHost.hasChangedAutomaticTypeDirectiveNames = hasChangedAutomaticTypeDirectiveNames; + builderProgram = createProgram(rootFileNames, compilerOptions, compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences); + resolutionCache.finishCachingPerDirectoryResolution(); + // Update watches + ts.updateMissingFilePathsWatch(builderProgram.getProgram(), missingFilesMap || (missingFilesMap = ts.createMap()), watchMissingFilePath); + if (needsUpdateInTypeRootWatch) { + resolutionCache.updateTypeRootsWatch(); + } + if (missingFilePathsRequestedForRelease) { + // These are the paths that program creater told us as not in use any more but were missing on the disk. + // We didnt remove the entry for them from sourceFiles cache so that we dont have to do File IO, + // if there is already watcher for it (for missing files) + // At this point our watches were updated, hence now we know that these paths are not tracked and need to be removed + // so that at later time we have correct result of their presence + for (var _i = 0, missingFilePathsRequestedForRelease_1 = missingFilePathsRequestedForRelease; _i < missingFilePathsRequestedForRelease_1.length; _i++) { + var missingFilePath = missingFilePathsRequestedForRelease_1[_i]; + if (!missingFilesMap.has(missingFilePath)) { + sourceFilesCache.delete(missingFilePath); + } + } + missingFilePathsRequestedForRelease = undefined; + } + } + function updateRootFileNames(files) { + ts.Debug.assert(!configFileName, "Cannot update root file names with config file watch mode"); + rootFileNames = files; + scheduleProgramUpdate(); + } + function updateNewLine() { + return ts.getNewLineCharacter(compilerOptions || optionsToExtendForConfigFile, function () { return host.getNewLine(); }); + } + function toPath(fileName) { + return ts.toPath(fileName, currentDirectory, getCanonicalFileName); + } + function isFileMissingOnHost(hostSourceFile) { + return typeof hostSourceFile === "number"; + } + function isFilePresentOnHost(hostSourceFile) { + return !!hostSourceFile.sourceFile; + } + function fileExists(fileName) { + var path = toPath(fileName); + // If file is missing on host from cache, we can definitely say file doesnt exist + // otherwise we need to ensure from the disk + if (isFileMissingOnHost(sourceFilesCache.get(path))) { + return true; + } + return directoryStructureHost.fileExists(fileName); + } + function getVersionedSourceFileByPath(fileName, path, languageVersion, onError, shouldCreateNewSourceFile) { + var hostSourceFile = sourceFilesCache.get(path); + // No source file on the host + if (isFileMissingOnHost(hostSourceFile)) { + return undefined; + } + // Create new source file if requested or the versions dont match + if (!hostSourceFile || shouldCreateNewSourceFile || !isFilePresentOnHost(hostSourceFile) || hostSourceFile.version.toString() !== hostSourceFile.sourceFile.version) { + var sourceFile = getNewSourceFile(); + if (hostSourceFile) { + if (shouldCreateNewSourceFile) { + hostSourceFile.version++; + } + if (sourceFile) { + // Set the source file and create file watcher now that file was present on the disk + hostSourceFile.sourceFile = sourceFile; + sourceFile.version = hostSourceFile.version.toString(); + if (!hostSourceFile.fileWatcher) { + hostSourceFile.fileWatcher = watchFilePath(host, fileName, onSourceFileChange, ts.PollingInterval.Low, path, "Source file"); + } + } + else { + // There is no source file on host any more, close the watch, missing file paths will track it + if (isFilePresentOnHost(hostSourceFile)) { + hostSourceFile.fileWatcher.close(); + } + sourceFilesCache.set(path, hostSourceFile.version); + } + } + else { + if (sourceFile) { + sourceFile.version = initialVersion.toString(); + var fileWatcher = watchFilePath(host, fileName, onSourceFileChange, ts.PollingInterval.Low, path, "Source file"); + sourceFilesCache.set(path, { sourceFile: sourceFile, version: initialVersion, fileWatcher: fileWatcher }); + } + else { + sourceFilesCache.set(path, initialVersion); + } + } + return sourceFile; + } + return hostSourceFile.sourceFile; + function getNewSourceFile() { + var text; + try { + ts.performance.mark("beforeIORead"); + text = host.readFile(fileName, compilerOptions.charset); + ts.performance.mark("afterIORead"); + ts.performance.measure("I/O Read", "beforeIORead", "afterIORead"); + } + catch (e) { + if (onError) { + onError(e.message); + } + } + return text !== undefined ? ts.createSourceFile(fileName, text, languageVersion) : undefined; + } + } + function nextSourceFileVersion(path) { + var hostSourceFile = sourceFilesCache.get(path); + if (hostSourceFile !== undefined) { + if (isFileMissingOnHost(hostSourceFile)) { + // The next version, lets set it as presence unknown file + sourceFilesCache.set(path, { version: Number(hostSourceFile) + 1 }); + } + else { + hostSourceFile.version++; + } + } + } + function getSourceVersion(path) { + var hostSourceFile = sourceFilesCache.get(path); + return !hostSourceFile || isFileMissingOnHost(hostSourceFile) ? undefined : hostSourceFile.version.toString(); + } + function onReleaseOldSourceFile(oldSourceFile, _oldOptions, hasSourceFileByPath) { + var hostSourceFileInfo = sourceFilesCache.get(oldSourceFile.resolvedPath); + // If this is the source file thats in the cache and new program doesnt need it, + // remove the cached entry. + // Note we arent deleting entry if file became missing in new program or + // there was version update and new source file was created. + if (hostSourceFileInfo) { + // record the missing file paths so they can be removed later if watchers arent tracking them + if (isFileMissingOnHost(hostSourceFileInfo)) { + (missingFilePathsRequestedForRelease || (missingFilePathsRequestedForRelease = [])).push(oldSourceFile.path); + } + else if (hostSourceFileInfo.sourceFile === oldSourceFile) { + if (hostSourceFileInfo.fileWatcher) { + hostSourceFileInfo.fileWatcher.close(); + } + sourceFilesCache.delete(oldSourceFile.resolvedPath); + if (!hasSourceFileByPath) { + resolutionCache.removeResolutionsOfFile(oldSourceFile.path); + } + } + } + } + function reportWatchDiagnostic(message) { + if (host.onWatchStatusChange) { + host.onWatchStatusChange(ts.createCompilerDiagnostic(message), newLine, compilerOptions || optionsToExtendForConfigFile); + } + } + // Upon detecting a file change, wait for 250ms and then perform a recompilation. This gives batch + // operations (such as saving all modified files in an editor) a chance to complete before we kick + // off a new compilation. + function scheduleProgramUpdate() { + if (!host.setTimeout || !host.clearTimeout) { + return; + } + if (timerToUpdateProgram) { + host.clearTimeout(timerToUpdateProgram); + } + writeLog("Scheduling update"); + timerToUpdateProgram = host.setTimeout(updateProgram, 250); + } + function scheduleProgramReload() { + ts.Debug.assert(!!configFileName); + reloadLevel = ts.ConfigFileProgramReloadLevel.Full; + scheduleProgramUpdate(); + } + function updateProgram() { + timerToUpdateProgram = undefined; + reportWatchDiagnostic(ts.Diagnostics.File_change_detected_Starting_incremental_compilation); + switch (reloadLevel) { + case ts.ConfigFileProgramReloadLevel.Partial: + return reloadFileNamesFromConfigFile(); + case ts.ConfigFileProgramReloadLevel.Full: + return reloadConfigFile(); + default: + synchronizeProgram(); + return; + } + } + function reloadFileNamesFromConfigFile() { + writeLog("Reloading new file names and options"); + var result = ts.getFileNamesFromConfigSpecs(configFileSpecs, ts.getDirectoryPath(configFileName), compilerOptions, parseConfigFileHost); + if (ts.updateErrorForNoInputFiles(result, configFileName, configFileSpecs, configFileParsingDiagnostics, canConfigFileJsonReportNoInputFiles)) { + hasChangedConfigFileParsingErrors = true; + } + rootFileNames = result.fileNames; + // Update the program + synchronizeProgram(); + } + function reloadConfigFile() { + writeLog("Reloading config file: " + configFileName); + reloadLevel = ts.ConfigFileProgramReloadLevel.None; + if (cachedDirectoryStructureHost) { + cachedDirectoryStructureHost.clearCache(); + } + parseConfigFile(); + hasChangedCompilerOptions = true; + synchronizeProgram(); + // Update the wild card directory watch + watchConfigFileWildCardDirectories(); + } + function parseConfigFile() { + setConfigFileParsingResult(ts.getParsedCommandLineOfConfigFile(configFileName, optionsToExtendForConfigFile, parseConfigFileHost)); // TODO: GH#18217 + } + function setConfigFileParsingResult(configFileParseResult) { + rootFileNames = configFileParseResult.fileNames; + compilerOptions = configFileParseResult.options; + configFileSpecs = configFileParseResult.configFileSpecs; // TODO: GH#18217 + projectReferences = configFileParseResult.projectReferences; + configFileParsingDiagnostics = ts.getConfigFileParsingDiagnostics(configFileParseResult).slice(); + canConfigFileJsonReportNoInputFiles = ts.canJsonReportNoInutFiles(configFileParseResult.raw); + hasChangedConfigFileParsingErrors = true; + } + function onSourceFileChange(fileName, eventKind, path) { + updateCachedSystemWithFile(fileName, path, eventKind); + // Update the source file cache + if (eventKind === ts.FileWatcherEventKind.Deleted && sourceFilesCache.get(path)) { + resolutionCache.invalidateResolutionOfFile(path); + } + resolutionCache.removeResolutionsFromProjectReferenceRedirects(path); + nextSourceFileVersion(path); + // Update the program + scheduleProgramUpdate(); + } + function updateCachedSystemWithFile(fileName, path, eventKind) { + if (cachedDirectoryStructureHost) { + cachedDirectoryStructureHost.addOrDeleteFile(fileName, path, eventKind); + } + } + function watchMissingFilePath(missingFilePath) { + return watchFilePath(host, missingFilePath, onMissingFileChange, ts.PollingInterval.Medium, missingFilePath, "Missing file"); + } + function onMissingFileChange(fileName, eventKind, missingFilePath) { + updateCachedSystemWithFile(fileName, missingFilePath, eventKind); + if (eventKind === ts.FileWatcherEventKind.Created && missingFilesMap.has(missingFilePath)) { + missingFilesMap.get(missingFilePath).close(); + missingFilesMap.delete(missingFilePath); + // Delete the entry in the source files cache so that new source file is created + nextSourceFileVersion(missingFilePath); + // When a missing file is created, we should update the graph. + scheduleProgramUpdate(); + } + } + function watchConfigFileWildCardDirectories() { + if (configFileSpecs) { + ts.updateWatchingWildcardDirectories(watchedWildcardDirectories || (watchedWildcardDirectories = ts.createMap()), ts.createMapFromTemplate(configFileSpecs.wildcardDirectories), watchWildcardDirectory); + } + else if (watchedWildcardDirectories) { + ts.clearMap(watchedWildcardDirectories, ts.closeFileWatcherOf); + } + } + function watchWildcardDirectory(directory, flags) { + return watchDirectory(host, directory, function (fileOrDirectory) { + ts.Debug.assert(!!configFileName); + var fileOrDirectoryPath = toPath(fileOrDirectory); + // Since the file existance changed, update the sourceFiles cache + if (cachedDirectoryStructureHost) { + cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); + } + nextSourceFileVersion(fileOrDirectoryPath); + if (ts.isPathInNodeModulesStartingWithDot(fileOrDirectoryPath)) + return; + // If the the added or created file or directory is not supported file name, ignore the file + // But when watched directory is added/removed, we need to reload the file list + if (fileOrDirectoryPath !== directory && ts.hasExtension(fileOrDirectoryPath) && !ts.isSupportedSourceFileName(fileOrDirectory, compilerOptions)) { + writeLog("Project: " + configFileName + " Detected file add/remove of non supported extension: " + fileOrDirectory); + return; + } + // Reload is pending, do the reload + if (reloadLevel !== ts.ConfigFileProgramReloadLevel.Full) { + reloadLevel = ts.ConfigFileProgramReloadLevel.Partial; + // Schedule Update the program + scheduleProgramUpdate(); + } + }, flags, "Wild card directories"); + } + function ensureDirectoriesExist(directoryPath) { + if (directoryPath.length > ts.getRootLength(directoryPath) && !host.directoryExists(directoryPath)) { + var parentDirectory = ts.getDirectoryPath(directoryPath); + ensureDirectoriesExist(parentDirectory); + host.createDirectory(directoryPath); + } + } + function writeFile(fileName, text, writeByteOrderMark, onError) { + try { + ts.performance.mark("beforeIOWrite"); + ensureDirectoriesExist(ts.getDirectoryPath(ts.normalizePath(fileName))); + host.writeFile(fileName, text, writeByteOrderMark); + ts.performance.mark("afterIOWrite"); + ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite"); + } + catch (e) { + if (onError) { + onError(e.message); + } + } + } + } + ts.createWatchProgram = createWatchProgram; +})(ts || (ts = {})); +// Currently we do not want to expose API for build, we should work out the API, and then expose it just like we did for builder/watch +/*@internal*/ +var ts; +(function (ts) { + var minimumDate = new Date(-8640000000000000); + var maximumDate = new Date(8640000000000000); + var BuildResultFlags; + (function (BuildResultFlags) { + BuildResultFlags[BuildResultFlags["None"] = 0] = "None"; + /** + * No errors of any kind occurred during build + */ + BuildResultFlags[BuildResultFlags["Success"] = 1] = "Success"; + /** + * None of the .d.ts files emitted by this build were + * different from the existing files on disk + */ + BuildResultFlags[BuildResultFlags["DeclarationOutputUnchanged"] = 2] = "DeclarationOutputUnchanged"; + BuildResultFlags[BuildResultFlags["ConfigFileErrors"] = 4] = "ConfigFileErrors"; + BuildResultFlags[BuildResultFlags["SyntaxErrors"] = 8] = "SyntaxErrors"; + BuildResultFlags[BuildResultFlags["TypeErrors"] = 16] = "TypeErrors"; + BuildResultFlags[BuildResultFlags["DeclarationEmitErrors"] = 32] = "DeclarationEmitErrors"; + BuildResultFlags[BuildResultFlags["EmitErrors"] = 64] = "EmitErrors"; + BuildResultFlags[BuildResultFlags["AnyErrors"] = 124] = "AnyErrors"; + })(BuildResultFlags || (BuildResultFlags = {})); + var UpToDateStatusType; + (function (UpToDateStatusType) { + UpToDateStatusType[UpToDateStatusType["Unbuildable"] = 0] = "Unbuildable"; + UpToDateStatusType[UpToDateStatusType["UpToDate"] = 1] = "UpToDate"; + /** + * The project appears out of date because its upstream inputs are newer than its outputs, + * but all of its outputs are actually newer than the previous identical outputs of its (.d.ts) inputs. + * This means we can Pseudo-build (just touch timestamps), as if we had actually built this project. + */ + UpToDateStatusType[UpToDateStatusType["UpToDateWithUpstreamTypes"] = 2] = "UpToDateWithUpstreamTypes"; + UpToDateStatusType[UpToDateStatusType["OutputMissing"] = 3] = "OutputMissing"; + UpToDateStatusType[UpToDateStatusType["OutOfDateWithSelf"] = 4] = "OutOfDateWithSelf"; + UpToDateStatusType[UpToDateStatusType["OutOfDateWithUpstream"] = 5] = "OutOfDateWithUpstream"; + UpToDateStatusType[UpToDateStatusType["UpstreamOutOfDate"] = 6] = "UpstreamOutOfDate"; + UpToDateStatusType[UpToDateStatusType["UpstreamBlocked"] = 7] = "UpstreamBlocked"; + UpToDateStatusType[UpToDateStatusType["ComputingUpstream"] = 8] = "ComputingUpstream"; + /** + * Projects with no outputs (i.e. "solution" files) + */ + UpToDateStatusType[UpToDateStatusType["ContainerOnly"] = 9] = "ContainerOnly"; + })(UpToDateStatusType = ts.UpToDateStatusType || (ts.UpToDateStatusType = {})); + function createFileMap(toPath) { + // tslint:disable-next-line:no-null-keyword + var lookup = ts.createMap(); + return { + setValue: setValue, + getValue: getValue, + removeKey: removeKey, + forEach: forEach, + hasKey: hasKey, + getSize: getSize, + clear: clear + }; + function forEach(action) { + lookup.forEach(action); + } + function hasKey(fileName) { + return lookup.has(toPath(fileName)); + } + function removeKey(fileName) { + lookup.delete(toPath(fileName)); + } + function setValue(fileName, value) { + lookup.set(toPath(fileName), value); + } + function getValue(fileName) { + return lookup.get(toPath(fileName)); + } + function getSize() { + return lookup.size; + } + function clear() { + lookup.clear(); + } + } + function getOrCreateValueFromConfigFileMap(configFileMap, resolved, createT) { + var existingValue = configFileMap.getValue(resolved); + var newValue; + if (!existingValue) { + newValue = createT(); + configFileMap.setValue(resolved, newValue); + } + return existingValue || newValue; + } + function getOrCreateValueMapFromConfigFileMap(configFileMap, resolved) { + return getOrCreateValueFromConfigFileMap(configFileMap, resolved, ts.createMap); + } + function getOutputDeclarationFileName(inputFileName, configFile) { + var relativePath = ts.getRelativePathFromDirectory(rootDirOfOptions(configFile.options, configFile.options.configFilePath), inputFileName, /*ignoreCase*/ true); + var outputPath = ts.resolvePath(configFile.options.declarationDir || configFile.options.outDir || ts.getDirectoryPath(configFile.options.configFilePath), relativePath); + return ts.changeExtension(outputPath, ".d.ts" /* Dts */); + } + ts.getOutputDeclarationFileName = getOutputDeclarationFileName; + function getOutputJSFileName(inputFileName, configFile) { + var relativePath = ts.getRelativePathFromDirectory(rootDirOfOptions(configFile.options, configFile.options.configFilePath), inputFileName, /*ignoreCase*/ true); + var outputPath = ts.resolvePath(configFile.options.outDir || ts.getDirectoryPath(configFile.options.configFilePath), relativePath); + var newExtension = ts.fileExtensionIs(inputFileName, ".json" /* Json */) ? ".json" /* Json */ : + ts.fileExtensionIs(inputFileName, ".tsx" /* Tsx */) && configFile.options.jsx === 1 /* Preserve */ ? ".jsx" /* Jsx */ : ".js" /* Js */; + return ts.changeExtension(outputPath, newExtension); + } + function getOutputFileNames(inputFileName, configFile) { + // outFile is handled elsewhere; .d.ts files don't generate outputs + if (configFile.options.outFile || configFile.options.out || ts.fileExtensionIs(inputFileName, ".d.ts" /* Dts */)) { + return ts.emptyArray; + } + var outputs = []; + var js = getOutputJSFileName(inputFileName, configFile); + outputs.push(js); + if (configFile.options.sourceMap) { + outputs.push(js + ".map"); + } + if (ts.getEmitDeclarations(configFile.options) && !ts.fileExtensionIs(inputFileName, ".json" /* Json */)) { + var dts = getOutputDeclarationFileName(inputFileName, configFile); + outputs.push(dts); + if (configFile.options.declarationMap) { + outputs.push(dts + ".map"); + } + } + return outputs; + } + function getOutFileOutputs(project) { + var out = project.options.outFile || project.options.out; + if (!out) { + return ts.Debug.fail("outFile must be set"); + } + var outputs = []; + outputs.push(out); + if (project.options.sourceMap) { + outputs.push(out + ".map"); + } + if (ts.getEmitDeclarations(project.options)) { + var dts = ts.changeExtension(out, ".d.ts" /* Dts */); + outputs.push(dts); + if (project.options.declarationMap) { + outputs.push(dts + ".map"); + } + } + return outputs; + } + function rootDirOfOptions(opts, configFileName) { + return opts.rootDir || ts.getDirectoryPath(configFileName); + } + function newer(date1, date2) { + return date2 > date1 ? date2 : date1; + } + function isDeclarationFile(fileName) { + return ts.fileExtensionIs(fileName, ".d.ts" /* Dts */); + } + /** + * Create a function that reports watch status by writing to the system and handles the formating of the diagnostic + */ + function createBuilderStatusReporter(system, pretty) { + return function (diagnostic) { + var output = pretty ? "[" + ts.formatColorAndReset(new Date().toLocaleTimeString(), ts.ForegroundColorEscapeSequences.Grey) + "] " : new Date().toLocaleTimeString() + " - "; + output += "" + ts.flattenDiagnosticMessageText(diagnostic.messageText, system.newLine) + (system.newLine + system.newLine); + system.write(output); + }; + } + ts.createBuilderStatusReporter = createBuilderStatusReporter; + function createSolutionBuilderHostBase(system, reportDiagnostic, reportSolutionBuilderStatus) { + if (system === void 0) { system = ts.sys; } + var host = ts.createCompilerHostWorker({}, /*setParentNodes*/ undefined, system); + host.getModifiedTime = system.getModifiedTime ? function (path) { return system.getModifiedTime(path); } : function () { return undefined; }; + host.setModifiedTime = system.setModifiedTime ? function (path, date) { return system.setModifiedTime(path, date); } : ts.noop; + host.deleteFile = system.deleteFile ? function (path) { return system.deleteFile(path); } : ts.noop; + host.reportDiagnostic = reportDiagnostic || ts.createDiagnosticReporter(system); + host.reportSolutionBuilderStatus = reportSolutionBuilderStatus || createBuilderStatusReporter(system); + return host; + } + function createSolutionBuilderHost(system, reportDiagnostic, reportSolutionBuilderStatus, reportErrorSummary) { + if (system === void 0) { system = ts.sys; } + var host = createSolutionBuilderHostBase(system, reportDiagnostic, reportSolutionBuilderStatus); + host.reportErrorSummary = reportErrorSummary; + return host; + } + ts.createSolutionBuilderHost = createSolutionBuilderHost; + function createSolutionBuilderWithWatchHost(system, reportDiagnostic, reportSolutionBuilderStatus, reportWatchStatus) { + var host = createSolutionBuilderHostBase(system, reportDiagnostic, reportSolutionBuilderStatus); + var watchHost = ts.createWatchHost(system, reportWatchStatus); + host.onWatchStatusChange = watchHost.onWatchStatusChange; + host.watchFile = watchHost.watchFile; + host.watchDirectory = watchHost.watchDirectory; + host.setTimeout = watchHost.setTimeout; + host.clearTimeout = watchHost.clearTimeout; + return host; + } + ts.createSolutionBuilderWithWatchHost = createSolutionBuilderWithWatchHost; + function getCompilerOptionsOfBuildOptions(buildOptions) { + var result = {}; + ts.commonOptionsWithBuild.forEach(function (option) { + result[option.name] = buildOptions[option.name]; + }); + return result; + } + function createSolutionBuilder(host, rootNames, defaultOptions) { + var hostWithWatch = host; + var currentDirectory = host.getCurrentDirectory(); + var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames()); + var parseConfigFileHost = ts.parseConfigHostFromCompilerHost(host); + // State of the solution + var options = defaultOptions; + var baseCompilerOptions = getCompilerOptionsOfBuildOptions(options); + var configFileCache = createFileMap(toPath); + /** Map from output file name to its pre-build timestamp */ + var unchangedOutputs = createFileMap(toPath); + /** Map from config file name to up-to-date status */ + var projectStatus = createFileMap(toPath); + var missingRoots = ts.createMap(); + var globalDependencyGraph; + var writeFileName = function (s) { return host.trace && host.trace(s); }; + var readFileWithCache = function (f) { return host.readFile(f); }; + // Watch state + var diagnostics = createFileMap(toPath); + var projectPendingBuild = createFileMap(toPath); + var projectErrorsReported = createFileMap(toPath); + var invalidatedProjectQueue = []; + var nextProjectToBuild = 0; + var timerToBuildInvalidatedProject; + var reportFileChangeDetected = false; + // Watches for the solution + var allWatchedWildcardDirectories = createFileMap(toPath); + var allWatchedInputFiles = createFileMap(toPath); + var allWatchedConfigFiles = createFileMap(toPath); + return { + buildAllProjects: buildAllProjects, + getUpToDateStatusOfFile: getUpToDateStatusOfFile, + cleanAllProjects: cleanAllProjects, + resetBuildContext: resetBuildContext, + getBuildGraph: getBuildGraph, + invalidateProject: invalidateProject, + buildInvalidatedProject: buildInvalidatedProject, + resolveProjectName: resolveProjectName, + startWatching: startWatching + }; + function toPath(fileName) { + return ts.toPath(fileName, currentDirectory, getCanonicalFileName); + } + function resetBuildContext(opts) { + if (opts === void 0) { opts = defaultOptions; } + options = opts; + baseCompilerOptions = getCompilerOptionsOfBuildOptions(options); + configFileCache.clear(); + unchangedOutputs.clear(); + projectStatus.clear(); + missingRoots.clear(); + globalDependencyGraph = undefined; + diagnostics.clear(); + projectPendingBuild.clear(); + projectErrorsReported.clear(); + invalidatedProjectQueue.length = 0; + nextProjectToBuild = 0; + if (timerToBuildInvalidatedProject) { + clearTimeout(timerToBuildInvalidatedProject); + timerToBuildInvalidatedProject = undefined; + } + reportFileChangeDetected = false; + ts.clearMap(allWatchedWildcardDirectories, function (wildCardWatches) { return ts.clearMap(wildCardWatches, ts.closeFileWatcherOf); }); + ts.clearMap(allWatchedInputFiles, function (inputFileWatches) { return ts.clearMap(inputFileWatches, ts.closeFileWatcher); }); + ts.clearMap(allWatchedConfigFiles, ts.closeFileWatcher); + } + function isParsedCommandLine(entry) { + return !!entry.options; + } + function parseConfigFile(configFilePath) { + var value = configFileCache.getValue(configFilePath); + if (value) { + return isParsedCommandLine(value) ? value : undefined; + } + var diagnostic; + parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = function (d) { return diagnostic = d; }; + var parsed = ts.getParsedCommandLineOfConfigFile(configFilePath, baseCompilerOptions, parseConfigFileHost); + parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = ts.noop; + configFileCache.setValue(configFilePath, parsed || diagnostic); + return parsed; + } + function reportStatus(message) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + host.reportSolutionBuilderStatus(ts.createCompilerDiagnostic.apply(void 0, [message].concat(args))); + } + function reportWatchStatus(message) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + if (hostWithWatch.onWatchStatusChange) { + hostWithWatch.onWatchStatusChange(ts.createCompilerDiagnostic.apply(void 0, [message].concat(args)), host.getNewLine(), baseCompilerOptions); + } + } + function startWatching() { + var graph = getGlobalDependencyGraph(); + for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { + var resolved = _a[_i]; + // Watch this file + watchConfigFile(resolved); + var cfg = parseConfigFile(resolved); + if (cfg) { + // Update watchers for wildcard directories + watchWildCardDirectories(resolved, cfg); + // Watch input files + watchInputFiles(resolved, cfg); + } + } + } + function watchConfigFile(resolved) { + if (options.watch && !allWatchedConfigFiles.hasKey(resolved)) { + allWatchedConfigFiles.setValue(resolved, hostWithWatch.watchFile(resolved, function () { + invalidateProjectAndScheduleBuilds(resolved, ts.ConfigFileProgramReloadLevel.Full); + })); + } + } + function watchWildCardDirectories(resolved, parsed) { + if (!options.watch) + return; + ts.updateWatchingWildcardDirectories(getOrCreateValueMapFromConfigFileMap(allWatchedWildcardDirectories, resolved), ts.createMapFromTemplate(parsed.configFileSpecs.wildcardDirectories), function (dir, flags) { + return hostWithWatch.watchDirectory(dir, function (fileOrDirectory) { + var fileOrDirectoryPath = toPath(fileOrDirectory); + if (fileOrDirectoryPath !== toPath(dir) && ts.hasExtension(fileOrDirectoryPath) && !ts.isSupportedSourceFileName(fileOrDirectory, parsed.options)) { + // writeLog(`Project: ${configFileName} Detected file add/remove of non supported extension: ${fileOrDirectory}`); + return; + } + if (isOutputFile(fileOrDirectory, parsed)) { + // writeLog(`${fileOrDirectory} is output file`); + return; + } + invalidateProjectAndScheduleBuilds(resolved, ts.ConfigFileProgramReloadLevel.Partial); + }, !!(flags & 1 /* Recursive */)); + }); + } + function watchInputFiles(resolved, parsed) { + if (!options.watch) + return; + ts.mutateMap(getOrCreateValueMapFromConfigFileMap(allWatchedInputFiles, resolved), ts.arrayToMap(parsed.fileNames, toPath), { + createNewValue: function (_key, input) { return hostWithWatch.watchFile(input, function () { + invalidateProjectAndScheduleBuilds(resolved, ts.ConfigFileProgramReloadLevel.None); + }); }, + onDeleteValue: ts.closeFileWatcher, + }); + } + function isOutputFile(fileName, configFile) { + if (configFile.options.noEmit) + return false; + // ts or tsx files are not output + if (!ts.fileExtensionIs(fileName, ".d.ts" /* Dts */) && + (ts.fileExtensionIs(fileName, ".ts" /* Ts */) || ts.fileExtensionIs(fileName, ".tsx" /* Tsx */))) { + return false; + } + // If options have --outFile or --out, check if its that + var out = configFile.options.outFile || configFile.options.out; + if (out && (isSameFile(fileName, out) || isSameFile(fileName, ts.removeFileExtension(out) + ".d.ts" /* Dts */))) { + return true; + } + // If declarationDir is specified, return if its a file in that directory + if (configFile.options.declarationDir && ts.containsPath(configFile.options.declarationDir, fileName, currentDirectory, !host.useCaseSensitiveFileNames())) { + return true; + } + // If --outDir, check if file is in that directory + if (configFile.options.outDir && ts.containsPath(configFile.options.outDir, fileName, currentDirectory, !host.useCaseSensitiveFileNames())) { + return true; + } + return !ts.forEach(configFile.fileNames, function (inputFile) { return isSameFile(fileName, inputFile); }); + } + function isSameFile(file1, file2) { + return ts.comparePaths(file1, file2, currentDirectory, !host.useCaseSensitiveFileNames()) === 0 /* EqualTo */; + } + function invalidateProjectAndScheduleBuilds(resolved, reloadLevel) { + reportFileChangeDetected = true; + invalidateResolvedProject(resolved, reloadLevel); + scheduleBuildInvalidatedProject(); + } + function getUpToDateStatusOfFile(configFileName) { + return getUpToDateStatus(parseConfigFile(configFileName)); + } + function getBuildGraph(configFileNames) { + return createDependencyGraph(resolveProjectNames(configFileNames)); + } + function getGlobalDependencyGraph() { + return globalDependencyGraph || (globalDependencyGraph = getBuildGraph(rootNames)); + } + function getUpToDateStatus(project) { + if (project === undefined) { + return { type: UpToDateStatusType.Unbuildable, reason: "File deleted mid-build" }; + } + var prior = projectStatus.getValue(project.options.configFilePath); + if (prior !== undefined) { + return prior; + } + var actual = getUpToDateStatusWorker(project); + projectStatus.setValue(project.options.configFilePath, actual); + return actual; + } + function getUpToDateStatusWorker(project) { + var newestInputFileName = undefined; + var newestInputFileTime = minimumDate; + // Get timestamps of input files + for (var _i = 0, _a = project.fileNames; _i < _a.length; _i++) { + var inputFile = _a[_i]; + if (!host.fileExists(inputFile)) { + return { + type: UpToDateStatusType.Unbuildable, + reason: inputFile + " does not exist" + }; + } + var inputTime = host.getModifiedTime(inputFile) || ts.missingFileModifiedTime; + if (inputTime > newestInputFileTime) { + newestInputFileName = inputFile; + newestInputFileTime = inputTime; + } + } + // Collect the expected outputs of this project + var outputs = getAllProjectOutputs(project); + if (outputs.length === 0) { + return { + type: UpToDateStatusType.ContainerOnly + }; + } + // Now see if all outputs are newer than the newest input + var oldestOutputFileName = "(none)"; + var oldestOutputFileTime = maximumDate; + var newestOutputFileName = "(none)"; + var newestOutputFileTime = minimumDate; + var missingOutputFileName; + var newestDeclarationFileContentChangedTime = minimumDate; + var isOutOfDateWithInputs = false; + for (var _b = 0, outputs_1 = outputs; _b < outputs_1.length; _b++) { + var output = outputs_1[_b]; + // Output is missing; can stop checking + // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status + if (!host.fileExists(output)) { + missingOutputFileName = output; + break; + } + var outputTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; + if (outputTime < oldestOutputFileTime) { + oldestOutputFileTime = outputTime; + oldestOutputFileName = output; + } + // If an output is older than the newest input, we can stop checking + // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status + if (outputTime < newestInputFileTime) { + isOutOfDateWithInputs = true; + break; + } + if (outputTime > newestOutputFileTime) { + newestOutputFileTime = outputTime; + newestOutputFileName = output; + } + // Keep track of when the most recent time a .d.ts file was changed. + // In addition to file timestamps, we also keep track of when a .d.ts file + // had its file touched but not had its contents changed - this allows us + // to skip a downstream typecheck + if (isDeclarationFile(output)) { + var unchangedTime = unchangedOutputs.getValue(output); + if (unchangedTime !== undefined) { + newestDeclarationFileContentChangedTime = newer(unchangedTime, newestDeclarationFileContentChangedTime); + } + else { + var outputModifiedTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; + newestDeclarationFileContentChangedTime = newer(newestDeclarationFileContentChangedTime, outputModifiedTime); + } + } + } + var pseudoUpToDate = false; + var usesPrepend = false; + var upstreamChangedProject; + if (project.projectReferences) { + projectStatus.setValue(project.options.configFilePath, { type: UpToDateStatusType.ComputingUpstream }); + for (var _c = 0, _d = project.projectReferences; _c < _d.length; _c++) { + var ref = _d[_c]; + usesPrepend = usesPrepend || !!(ref.prepend); + var resolvedRef = ts.resolveProjectReferencePath(ref); + var refStatus = getUpToDateStatus(parseConfigFile(resolvedRef)); + // Its a circular reference ignore the status of this project + if (refStatus.type === UpToDateStatusType.ComputingUpstream) { + continue; + } + // An upstream project is blocked + if (refStatus.type === UpToDateStatusType.Unbuildable) { + return { + type: UpToDateStatusType.UpstreamBlocked, + upstreamProjectName: ref.path + }; + } + // If the upstream project is out of date, then so are we (someone shouldn't have asked, though?) + if (refStatus.type !== UpToDateStatusType.UpToDate) { + return { + type: UpToDateStatusType.UpstreamOutOfDate, + upstreamProjectName: ref.path + }; + } + // If the upstream project's newest file is older than our oldest output, we + // can't be out of date because of it + if (refStatus.newestInputFileTime && refStatus.newestInputFileTime <= oldestOutputFileTime) { + continue; + } + // If the upstream project has only change .d.ts files, and we've built + // *after* those files, then we're "psuedo up to date" and eligible for a fast rebuild + if (refStatus.newestDeclarationFileContentChangedTime && refStatus.newestDeclarationFileContentChangedTime <= oldestOutputFileTime) { + pseudoUpToDate = true; + upstreamChangedProject = ref.path; + continue; + } + // We have an output older than an upstream output - we are out of date + ts.Debug.assert(oldestOutputFileName !== undefined, "Should have an oldest output filename here"); + return { + type: UpToDateStatusType.OutOfDateWithUpstream, + outOfDateOutputFileName: oldestOutputFileName, + newerProjectName: ref.path + }; + } + } + if (missingOutputFileName !== undefined) { + return { + type: UpToDateStatusType.OutputMissing, + missingOutputFileName: missingOutputFileName + }; + } + if (isOutOfDateWithInputs) { + return { + type: UpToDateStatusType.OutOfDateWithSelf, + outOfDateOutputFileName: oldestOutputFileName, + newerInputFileName: newestInputFileName + }; + } + if (usesPrepend && pseudoUpToDate) { + return { + type: UpToDateStatusType.OutOfDateWithUpstream, + outOfDateOutputFileName: oldestOutputFileName, + newerProjectName: upstreamChangedProject + }; + } + // Up to date + return { + type: pseudoUpToDate ? UpToDateStatusType.UpToDateWithUpstreamTypes : UpToDateStatusType.UpToDate, + newestDeclarationFileContentChangedTime: newestDeclarationFileContentChangedTime, + newestInputFileTime: newestInputFileTime, + newestOutputFileTime: newestOutputFileTime, + newestInputFileName: newestInputFileName, + newestOutputFileName: newestOutputFileName, + oldestOutputFileName: oldestOutputFileName + }; + } + function invalidateProject(configFileName, reloadLevel) { + invalidateResolvedProject(resolveProjectName(configFileName), reloadLevel); + } + function invalidateResolvedProject(resolved, reloadLevel) { + if (reloadLevel === ts.ConfigFileProgramReloadLevel.Full) { + configFileCache.removeKey(resolved); + globalDependencyGraph = undefined; + } + projectStatus.removeKey(resolved); + diagnostics.removeKey(resolved); + addProjToQueue(resolved, reloadLevel); + } + /** + * return true if new addition + */ + function addProjToQueue(proj, reloadLevel) { + var value = projectPendingBuild.getValue(proj); + if (value === undefined) { + projectPendingBuild.setValue(proj, reloadLevel || ts.ConfigFileProgramReloadLevel.None); + invalidatedProjectQueue.push(proj); + } + else if (value < (reloadLevel || ts.ConfigFileProgramReloadLevel.None)) { + projectPendingBuild.setValue(proj, reloadLevel || ts.ConfigFileProgramReloadLevel.None); + } + } + function getNextInvalidatedProject() { + if (nextProjectToBuild < invalidatedProjectQueue.length) { + var project = invalidatedProjectQueue[nextProjectToBuild]; + nextProjectToBuild++; + var reloadLevel = projectPendingBuild.getValue(project); + projectPendingBuild.removeKey(project); + if (!projectPendingBuild.getSize()) { + invalidatedProjectQueue.length = 0; + nextProjectToBuild = 0; + } + return { project: project, reloadLevel: reloadLevel }; + } + } + function hasPendingInvalidatedProjects() { + return !!projectPendingBuild.getSize(); + } + function scheduleBuildInvalidatedProject() { + if (!hostWithWatch.setTimeout || !hostWithWatch.clearTimeout) { + return; + } + if (timerToBuildInvalidatedProject) { + hostWithWatch.clearTimeout(timerToBuildInvalidatedProject); + } + timerToBuildInvalidatedProject = hostWithWatch.setTimeout(buildInvalidatedProject, 250); + } + function buildInvalidatedProject() { + timerToBuildInvalidatedProject = undefined; + if (reportFileChangeDetected) { + reportFileChangeDetected = false; + projectErrorsReported.clear(); + reportWatchStatus(ts.Diagnostics.File_change_detected_Starting_incremental_compilation); + } + var buildProject = getNextInvalidatedProject(); + if (buildProject) { + buildSingleInvalidatedProject(buildProject.project, buildProject.reloadLevel); + if (hasPendingInvalidatedProjects()) { + if (options.watch && !timerToBuildInvalidatedProject) { + scheduleBuildInvalidatedProject(); + } + } + else { + reportErrorSummary(); + } + } + } + function reportErrorSummary() { + if (options.watch || host.reportErrorSummary) { + // Report errors from the other projects + getGlobalDependencyGraph().buildQueue.forEach(function (project) { + if (!projectErrorsReported.hasKey(project)) { + reportErrors(diagnostics.getValue(project) || ts.emptyArray); + } + }); + var totalErrors_1 = 0; + diagnostics.forEach(function (singleProjectErrors) { return totalErrors_1 += ts.getErrorCountForSummary(singleProjectErrors); }); + if (options.watch) { + reportWatchStatus(ts.getWatchErrorSummaryDiagnosticMessage(totalErrors_1), totalErrors_1); + } + else { + host.reportErrorSummary(totalErrors_1); + } + } + } + function buildSingleInvalidatedProject(resolved, reloadLevel) { + var proj = parseConfigFile(resolved); + if (!proj) { + reportParseConfigFileDiagnostic(resolved); + return; + } + if (reloadLevel === ts.ConfigFileProgramReloadLevel.Full) { + watchConfigFile(resolved); + watchWildCardDirectories(resolved, proj); + watchInputFiles(resolved, proj); + } + else if (reloadLevel === ts.ConfigFileProgramReloadLevel.Partial) { + // Update file names + var result = ts.getFileNamesFromConfigSpecs(proj.configFileSpecs, ts.getDirectoryPath(resolved), proj.options, parseConfigFileHost); + ts.updateErrorForNoInputFiles(result, resolved, proj.configFileSpecs, proj.errors, ts.canJsonReportNoInutFiles(proj.raw)); + proj.fileNames = result.fileNames; + watchInputFiles(resolved, proj); + } + var status = getUpToDateStatus(proj); + verboseReportProjectStatus(resolved, status); + if (status.type === UpToDateStatusType.UpstreamBlocked) { + if (options.verbose) + reportStatus(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, resolved, status.upstreamProjectName); + return; + } + var buildResult = buildSingleProject(resolved); + var dependencyGraph = getGlobalDependencyGraph(); + var referencingProjects = dependencyGraph.referencingProjectsMap.getValue(resolved); + if (!referencingProjects) + return; + // Always use build order to queue projects + for (var _i = 0, _a = dependencyGraph.buildQueue; _i < _a.length; _i++) { + var project = _a[_i]; + var prepend = referencingProjects.getValue(project); + // If the project is referenced with prepend, always build downstream projectm, + // otherwise queue it only if declaration output changed + if (prepend || (prepend !== undefined && !(buildResult & BuildResultFlags.DeclarationOutputUnchanged))) { + addProjToQueue(project); + } + } + } + function createDependencyGraph(roots) { + var temporaryMarks = createFileMap(toPath); + var permanentMarks = createFileMap(toPath); + var circularityReportStack = []; + var buildOrder = []; + var referencingProjectsMap = createFileMap(toPath); + for (var _i = 0, roots_1 = roots; _i < roots_1.length; _i++) { + var root = roots_1[_i]; + visit(root); + } + return { + buildQueue: buildOrder, + referencingProjectsMap: referencingProjectsMap + }; + function visit(projPath, inCircularContext) { + // Already visited + if (permanentMarks.hasKey(projPath)) + return; + // Circular + if (temporaryMarks.hasKey(projPath)) { + if (!inCircularContext) { + // TODO:: Do we report this as error? + reportStatus(ts.Diagnostics.Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0, circularityReportStack.join("\r\n")); + } + return; + } + temporaryMarks.setValue(projPath, true); + circularityReportStack.push(projPath); + var parsed = parseConfigFile(projPath); + if (parsed && parsed.projectReferences) { + for (var _i = 0, _a = parsed.projectReferences; _i < _a.length; _i++) { + var ref = _a[_i]; + var resolvedRefPath = resolveProjectName(ref.path); + visit(resolvedRefPath, inCircularContext || ref.circular); + // Get projects referencing resolvedRefPath and add projPath to it + var referencingProjects = getOrCreateValueFromConfigFileMap(referencingProjectsMap, resolvedRefPath, function () { return createFileMap(toPath); }); + referencingProjects.setValue(projPath, !!ref.prepend); + } + } + circularityReportStack.pop(); + permanentMarks.setValue(projPath, true); + buildOrder.push(projPath); + } + } + function buildSingleProject(proj) { + if (options.dry) { + reportStatus(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj); + return BuildResultFlags.Success; + } + if (options.verbose) + reportStatus(ts.Diagnostics.Building_project_0, proj); + var resultFlags = BuildResultFlags.None; + resultFlags |= BuildResultFlags.DeclarationOutputUnchanged; + var configFile = parseConfigFile(proj); + if (!configFile) { + // Failed to read the config file + resultFlags |= BuildResultFlags.ConfigFileErrors; + reportParseConfigFileDiagnostic(proj); + projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Config file errors" }); + return resultFlags; + } + if (configFile.fileNames.length === 0) { + reportAndStoreErrors(proj, configFile.errors); + // Nothing to build - must be a solution file, basically + return BuildResultFlags.None; + } + var programOptions = { + projectReferences: configFile.projectReferences, + host: host, + rootNames: configFile.fileNames, + options: configFile.options, + configFileParsingDiagnostics: configFile.errors + }; + if (host.beforeCreateProgram) { + host.beforeCreateProgram(options); + } + var program = ts.createProgram(programOptions); + // Don't emit anything in the presence of syntactic errors or options diagnostics + var syntaxDiagnostics = program.getOptionsDiagnostics().concat(program.getConfigFileParsingDiagnostics(), program.getSyntacticDiagnostics()); + if (syntaxDiagnostics.length) { + return buildErrors(syntaxDiagnostics, BuildResultFlags.SyntaxErrors, "Syntactic"); + } + // Same as above but now for semantic diagnostics + var semanticDiagnostics = program.getSemanticDiagnostics(); + if (semanticDiagnostics.length) { + return buildErrors(semanticDiagnostics, BuildResultFlags.TypeErrors, "Semantic"); + } + var newestDeclarationFileContentChangedTime = minimumDate; + var anyDtsChanged = false; + var declDiagnostics; + var reportDeclarationDiagnostics = function (d) { return (declDiagnostics || (declDiagnostics = [])).push(d); }; + var outputFiles = []; + ts.emitFilesAndReportErrors(program, reportDeclarationDiagnostics, writeFileName, /*reportSummary*/ undefined, function (name, text, writeByteOrderMark) { return outputFiles.push({ name: name, text: text, writeByteOrderMark: writeByteOrderMark }); }); + // Don't emit .d.ts if there are decl file errors + if (declDiagnostics) { + return buildErrors(declDiagnostics, BuildResultFlags.DeclarationEmitErrors, "Declaration file"); + } + // Actual Emit + var emitterDiagnostics = ts.createDiagnosticCollection(); + outputFiles.forEach(function (_a) { + var name = _a.name, text = _a.text, writeByteOrderMark = _a.writeByteOrderMark; + var priorChangeTime; + if (!anyDtsChanged && isDeclarationFile(name)) { + // Check for unchanged .d.ts files + if (host.fileExists(name) && readFileWithCache(name) === text) { + priorChangeTime = host.getModifiedTime(name); + } + else { + resultFlags &= ~BuildResultFlags.DeclarationOutputUnchanged; + anyDtsChanged = true; + } + } + ts.writeFile(host, emitterDiagnostics, name, text, writeByteOrderMark); + if (priorChangeTime !== undefined) { + newestDeclarationFileContentChangedTime = newer(priorChangeTime, newestDeclarationFileContentChangedTime); + unchangedOutputs.setValue(name, priorChangeTime); + } + }); + var emitDiagnostics = emitterDiagnostics.getDiagnostics(); + if (emitDiagnostics.length) { + return buildErrors(emitDiagnostics, BuildResultFlags.EmitErrors, "Emit"); + } + var status = { + type: UpToDateStatusType.UpToDate, + newestDeclarationFileContentChangedTime: anyDtsChanged ? maximumDate : newestDeclarationFileContentChangedTime + }; + diagnostics.removeKey(proj); + projectStatus.setValue(proj, status); + if (host.afterProgramEmitAndDiagnostics) { + host.afterProgramEmitAndDiagnostics(program); + } + return resultFlags; + function buildErrors(diagnostics, errorFlags, errorType) { + resultFlags |= errorFlags; + reportAndStoreErrors(proj, diagnostics); + projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: errorType + " errors" }); + if (host.afterProgramEmitAndDiagnostics) { + host.afterProgramEmitAndDiagnostics(program); + } + return resultFlags; + } + } + function updateOutputTimestamps(proj) { + if (options.dry) { + return reportStatus(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj.options.configFilePath); + } + if (options.verbose) { + reportStatus(ts.Diagnostics.Updating_output_timestamps_of_project_0, proj.options.configFilePath); + } + var now = new Date(); + var outputs = getAllProjectOutputs(proj); + var priorNewestUpdateTime = minimumDate; + for (var _i = 0, outputs_2 = outputs; _i < outputs_2.length; _i++) { + var file = outputs_2[_i]; + if (isDeclarationFile(file)) { + priorNewestUpdateTime = newer(priorNewestUpdateTime, host.getModifiedTime(file) || ts.missingFileModifiedTime); + } + host.setModifiedTime(file, now); + } + projectStatus.setValue(proj.options.configFilePath, { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: priorNewestUpdateTime }); + } + function getFilesToClean() { + // Get the same graph for cleaning we'd use for building + var graph = getGlobalDependencyGraph(); + var filesToDelete = []; + for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { + var proj = _a[_i]; + var parsed = parseConfigFile(proj); + if (parsed === undefined) { + // File has gone missing; fine to ignore here + reportParseConfigFileDiagnostic(proj); + continue; + } + var outputs = getAllProjectOutputs(parsed); + for (var _b = 0, outputs_3 = outputs; _b < outputs_3.length; _b++) { + var output = outputs_3[_b]; + if (host.fileExists(output)) { + filesToDelete.push(output); + } + } + } + return filesToDelete; + } + function cleanAllProjects() { + var filesToDelete = getFilesToClean(); + if (options.dry) { + reportStatus(ts.Diagnostics.A_non_dry_build_would_delete_the_following_files_Colon_0, filesToDelete.map(function (f) { return "\r\n * " + f; }).join("")); + return ts.ExitStatus.Success; + } + for (var _i = 0, filesToDelete_1 = filesToDelete; _i < filesToDelete_1.length; _i++) { + var output = filesToDelete_1[_i]; + host.deleteFile(output); + } + return ts.ExitStatus.Success; + } + function resolveProjectName(name) { + return resolveConfigFileProjectName(ts.resolvePath(host.getCurrentDirectory(), name)); + } + function resolveProjectNames(configFileNames) { + return configFileNames.map(resolveProjectName); + } + function buildAllProjects() { + if (options.watch) { + reportWatchStatus(ts.Diagnostics.Starting_compilation_in_watch_mode); + } + // TODO:: In watch mode as well to use caches for incremental build once we can invalidate caches correctly and have right api + // Override readFile for json files and output .d.ts to cache the text + var _a = ts.changeCompilerHostToUseCache(host, toPath, /*useCacheForSourceFile*/ true), originalReadFile = _a.originalReadFile, originalFileExists = _a.originalFileExists, originalDirectoryExists = _a.originalDirectoryExists, originalCreateDirectory = _a.originalCreateDirectory, originalWriteFile = _a.originalWriteFile, originalGetSourceFile = _a.originalGetSourceFile, newReadFileWithCache = _a.readFileWithCache; + var savedReadFileWithCache = readFileWithCache; + readFileWithCache = newReadFileWithCache; + var graph = getGlobalDependencyGraph(); + reportBuildQueue(graph); + var anyFailed = false; + for (var _i = 0, _b = graph.buildQueue; _i < _b.length; _i++) { + var next = _b[_i]; + var proj = parseConfigFile(next); + if (proj === undefined) { + reportParseConfigFileDiagnostic(next); + anyFailed = true; + break; + } + // report errors early when using continue or break statements + var errors = proj.errors; + var status = getUpToDateStatus(proj); + verboseReportProjectStatus(next, status); + var projName = proj.options.configFilePath; + if (status.type === UpToDateStatusType.UpToDate && !options.force) { + reportAndStoreErrors(next, errors); + // Up to date, skip + if (defaultOptions.dry) { + // In a dry build, inform the user of this fact + reportStatus(ts.Diagnostics.Project_0_is_up_to_date, projName); + } + continue; + } + if (status.type === UpToDateStatusType.UpToDateWithUpstreamTypes && !options.force) { + reportAndStoreErrors(next, errors); + // Fake build + updateOutputTimestamps(proj); + continue; + } + if (status.type === UpToDateStatusType.UpstreamBlocked) { + reportAndStoreErrors(next, errors); + if (options.verbose) + reportStatus(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, projName, status.upstreamProjectName); + continue; + } + if (status.type === UpToDateStatusType.ContainerOnly) { + reportAndStoreErrors(next, errors); + // Do nothing + continue; + } + var buildResult = buildSingleProject(next); + anyFailed = anyFailed || !!(buildResult & BuildResultFlags.AnyErrors); + } + reportErrorSummary(); + host.readFile = originalReadFile; + host.fileExists = originalFileExists; + host.directoryExists = originalDirectoryExists; + host.createDirectory = originalCreateDirectory; + host.writeFile = originalWriteFile; + readFileWithCache = savedReadFileWithCache; + host.getSourceFile = originalGetSourceFile; + return anyFailed ? ts.ExitStatus.DiagnosticsPresent_OutputsSkipped : ts.ExitStatus.Success; + } + function reportParseConfigFileDiagnostic(proj) { + reportAndStoreErrors(proj, [configFileCache.getValue(proj)]); + } + function reportAndStoreErrors(proj, errors) { + reportErrors(errors); + projectErrorsReported.setValue(proj, true); + diagnostics.setValue(proj, errors); + } + function reportErrors(errors) { + errors.forEach(function (err) { return host.reportDiagnostic(err); }); + } + /** + * Report the build ordering inferred from the current project graph if we're in verbose mode + */ + function reportBuildQueue(graph) { + if (options.verbose) { + reportStatus(ts.Diagnostics.Projects_in_this_build_Colon_0, graph.buildQueue.map(function (s) { return "\r\n * " + relName(s); }).join("")); + } + } + function relName(path) { + return ts.convertToRelativePath(path, host.getCurrentDirectory(), function (f) { return host.getCanonicalFileName(f); }); + } + /** + * Report the up-to-date status of a project if we're in verbose mode + */ + function verboseReportProjectStatus(configFileName, status) { + if (!options.verbose) + return; + return formatUpToDateStatus(configFileName, status, relName, reportStatus); + } + } + ts.createSolutionBuilder = createSolutionBuilder; + function resolveConfigFileProjectName(project) { + if (ts.fileExtensionIs(project, ".json" /* Json */)) { + return project; + } + return ts.combinePaths(project, "tsconfig.json"); + } + ts.resolveConfigFileProjectName = resolveConfigFileProjectName; + function getAllProjectOutputs(project) { + if (project.options.outFile || project.options.out) { + return getOutFileOutputs(project); + } + else { + var outputs = []; + for (var _i = 0, _a = project.fileNames; _i < _a.length; _i++) { + var inputFile = _a[_i]; + outputs.push.apply(outputs, getOutputFileNames(inputFile, project)); + } + return outputs; + } + } + ts.getAllProjectOutputs = getAllProjectOutputs; + function formatUpToDateStatus(configFileName, status, relName, formatMessage) { + switch (status.type) { + case UpToDateStatusType.OutOfDateWithSelf: + return formatMessage(ts.Diagnostics.Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2, relName(configFileName), relName(status.outOfDateOutputFileName), relName(status.newerInputFileName)); + case UpToDateStatusType.OutOfDateWithUpstream: + return formatMessage(ts.Diagnostics.Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2, relName(configFileName), relName(status.outOfDateOutputFileName), relName(status.newerProjectName)); + case UpToDateStatusType.OutputMissing: + return formatMessage(ts.Diagnostics.Project_0_is_out_of_date_because_output_file_1_does_not_exist, relName(configFileName), relName(status.missingOutputFileName)); + case UpToDateStatusType.UpToDate: + if (status.newestInputFileTime !== undefined) { + return formatMessage(ts.Diagnostics.Project_0_is_up_to_date_because_newest_input_1_is_older_than_oldest_output_2, relName(configFileName), relName(status.newestInputFileName || ""), relName(status.oldestOutputFileName || "")); + } + // Don't report anything for "up to date because it was already built" -- too verbose + break; + case UpToDateStatusType.UpToDateWithUpstreamTypes: + return formatMessage(ts.Diagnostics.Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies, relName(configFileName)); + case UpToDateStatusType.UpstreamOutOfDate: + return formatMessage(ts.Diagnostics.Project_0_is_out_of_date_because_its_dependency_1_is_out_of_date, relName(configFileName), relName(status.upstreamProjectName)); + case UpToDateStatusType.UpstreamBlocked: + return formatMessage(ts.Diagnostics.Project_0_can_t_be_built_because_its_dependency_1_has_errors, relName(configFileName), relName(status.upstreamProjectName)); + case UpToDateStatusType.Unbuildable: + return formatMessage(ts.Diagnostics.Failed_to_parse_file_0_Colon_1, relName(configFileName), status.reason); + case UpToDateStatusType.ContainerOnly: + // Don't report status on "solution" projects + case UpToDateStatusType.ComputingUpstream: + // Should never leak from getUptoDateStatusWorker + break; + default: + ts.assertType(status); + } + } + ts.formatUpToDateStatus = formatUpToDateStatus; +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var ValueKind; + (function (ValueKind) { + ValueKind[ValueKind["Const"] = 0] = "Const"; + ValueKind[ValueKind["Array"] = 1] = "Array"; + ValueKind[ValueKind["FunctionOrClass"] = 2] = "FunctionOrClass"; + ValueKind[ValueKind["Object"] = 3] = "Object"; + })(ValueKind = ts.ValueKind || (ts.ValueKind = {})); + function inspectModule(fileNameToRequire) { + return inspectValue(ts.removeFileExtension(ts.getBaseFileName(fileNameToRequire)), tryRequire(fileNameToRequire)); + } + ts.inspectModule = inspectModule; + function inspectValue(name, value) { + return getValueInfo(name, value, getRecurser()); + } + ts.inspectValue = inspectValue; + function getRecurser() { + var seen = new Set(); + var nameStack = []; + return function (obj, name, cbOk, cbFail) { + if (seen.has(obj) || nameStack.length > 4) { + return cbFail(seen.has(obj), nameStack); + } + seen.add(obj); + nameStack.push(name); + var res = cbOk(); + nameStack.pop(); + seen.delete(obj); + return res; + }; + } + function getValueInfo(name, value, recurser) { + return recurser(value, name, function () { + if (typeof value === "function") + return getFunctionOrClassInfo(value, name, recurser); + if (typeof value === "object") { + var builtin = getBuiltinType(name, value, recurser); + if (builtin !== undefined) + return builtin; + var entries = getEntriesOfObject(value); + var hasNontrivialPrototype = Object.getPrototypeOf(value) !== Object.prototype; + var members = ts.flatMap(entries, function (_a) { + var key = _a.key, value = _a.value; + return getValueInfo(key, value, recurser); + }); + return { kind: 3 /* Object */, name: name, hasNontrivialPrototype: hasNontrivialPrototype, members: members }; + } + return { kind: 0 /* Const */, name: name, typeName: isNullOrUndefined(value) ? "any" : typeof value }; + }, function (isCircularReference, keyStack) { return anyValue(name, " " + (isCircularReference ? "Circular reference" : "Too-deep object hierarchy") + " from " + keyStack.join(".")); }); + } + function getFunctionOrClassInfo(fn, name, recurser) { + var prototypeMembers = getPrototypeMembers(fn, recurser); + var namespaceMembers = ts.flatMap(getEntriesOfObject(fn), function (_a) { + var key = _a.key, value = _a.value; + return getValueInfo(key, value, recurser); + }); + var toString = ts.cast(Function.prototype.toString.call(fn), ts.isString); + var source = ts.stringContains(toString, "{ [native code] }") ? getFunctionLength(fn) : toString; + return { kind: 2 /* FunctionOrClass */, name: name, source: source, namespaceMembers: namespaceMembers, prototypeMembers: prototypeMembers }; + } + var builtins = ts.memoize(function () { + var map = ts.createMap(); + for (var _i = 0, _a = getEntriesOfObject(global); _i < _a.length; _i++) { + var _b = _a[_i], key = _b.key, value = _b.value; + if (typeof value === "function" && typeof value.prototype === "object" && value !== Object) { + map.set(key, value); + } + } + return map; + }); + function getBuiltinType(name, value, recurser) { + return ts.isArray(value) + ? { name: name, kind: 1 /* Array */, inner: value.length && getValueInfo("element", ts.first(value), recurser) || anyValue(name) } + : ts.forEachEntry(builtins(), function (builtin, builtinName) { + return value instanceof builtin ? { kind: 0 /* Const */, name: name, typeName: builtinName } : undefined; + }); + } + function getPrototypeMembers(fn, recurser) { + var prototype = fn.prototype; + // tslint:disable-next-line no-unnecessary-type-assertion (TODO: update LKG and it will really be unnecessary) + return typeof prototype !== "object" || prototype === null ? ts.emptyArray : ts.mapDefined(getEntriesOfObject(prototype), function (_a) { + var key = _a.key, value = _a.value; + return key === "constructor" ? undefined : getValueInfo(key, value, recurser); + }); + } + var ignoredProperties = new Set(["arguments", "caller", "constructor", "eval", "super_"]); + var reservedFunctionProperties = new Set(Object.getOwnPropertyNames(ts.noop)); + function getEntriesOfObject(obj) { + var seen = ts.createMap(); + var entries = []; + var chain = obj; + while (!isNullOrUndefined(chain) && chain !== Object.prototype && chain !== Function.prototype) { + for (var _i = 0, _a = Object.getOwnPropertyNames(chain); _i < _a.length; _i++) { + var key = _a[_i]; + if (!isJsPrivate(key) && + !ignoredProperties.has(key) && + (typeof obj !== "function" || !reservedFunctionProperties.has(key)) && + // Don't add property from a higher prototype if it already exists in a lower one + ts.addToSeen(seen, key)) { + var value = safeGetPropertyOfObject(chain, key); + // Don't repeat "toString" that matches signature from Object.prototype + if (!(key === "toString" && typeof value === "function" && value.length === 0)) { + entries.push({ key: key, value: value }); + } + } + } + chain = Object.getPrototypeOf(chain); + } + return entries.sort(function (e1, e2) { return ts.compareStringsCaseSensitive(e1.key, e2.key); }); + } + function getFunctionLength(fn) { + return ts.tryCast(safeGetPropertyOfObject(fn, "length"), ts.isNumber) || 0; + } + function safeGetPropertyOfObject(obj, key) { + var desc = Object.getOwnPropertyDescriptor(obj, key); + return desc && desc.value; + } + function isNullOrUndefined(value) { + return value == null; // tslint:disable-line + } + function anyValue(name, comment) { + return { kind: 0 /* Const */, name: name, typeName: "any", comment: comment }; + } + function isJsPrivate(name) { + return name.startsWith("_"); + } + ts.isJsPrivate = isJsPrivate; + function tryRequire(fileNameToRequire) { + try { + return require(fileNameToRequire); + } + catch (_a) { + return undefined; + } + } +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var server; + (function (server) { + // tslint:disable variable-name + server.ActionSet = "action::set"; + server.ActionInvalidate = "action::invalidate"; + server.ActionPackageInstalled = "action::packageInstalled"; + server.ActionValueInspected = "action::valueInspected"; + server.EventTypesRegistry = "event::typesRegistry"; + server.EventBeginInstallTypes = "event::beginInstallTypes"; + server.EventEndInstallTypes = "event::endInstallTypes"; + server.EventInitializationFailed = "event::initializationFailed"; + var Arguments; + (function (Arguments) { + Arguments.GlobalCacheLocation = "--globalTypingsCacheLocation"; + Arguments.LogFile = "--logFile"; + Arguments.EnableTelemetry = "--enableTelemetry"; + Arguments.TypingSafeListLocation = "--typingSafeListLocation"; + Arguments.TypesMapLocation = "--typesMapLocation"; + /** + * This argument specifies the location of the NPM executable. + * typingsInstaller will run the command with `${npmLocation} install ...`. + */ + Arguments.NpmLocation = "--npmLocation"; + })(Arguments = server.Arguments || (server.Arguments = {})); + function hasArgument(argumentName) { + return ts.sys.args.indexOf(argumentName) >= 0; + } + server.hasArgument = hasArgument; + function findArgument(argumentName) { + var index = ts.sys.args.indexOf(argumentName); + return index >= 0 && index < ts.sys.args.length - 1 + ? ts.sys.args[index + 1] + : undefined; + } + server.findArgument = findArgument; + function nowString() { + // E.g. "12:34:56.789" + var d = new Date(); + return d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds() + "." + d.getMilliseconds(); + } + server.nowString = nowString; + })(server = ts.server || (ts.server = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var JsTyping; + (function (JsTyping) { + function isTypingUpToDate(cachedTyping, availableTypingVersions) { + var availableVersion = new ts.Version(ts.getProperty(availableTypingVersions, "ts" + ts.versionMajorMinor) || ts.getProperty(availableTypingVersions, "latest")); + return availableVersion.compareTo(cachedTyping.version) <= 0; + } + JsTyping.isTypingUpToDate = isTypingUpToDate; + JsTyping.nodeCoreModuleList = [ + "assert", + "async_hooks", + "buffer", + "child_process", + "cluster", + "console", + "constants", + "crypto", + "dgram", + "dns", + "domain", + "events", + "fs", + "http", + "https", + "http2", + "inspector", + "net", + "os", + "path", + "perf_hooks", + "process", + "punycode", + "querystring", + "readline", + "repl", + "stream", + "string_decoder", + "timers", + "tls", + "tty", + "url", + "util", + "v8", + "vm", + "zlib" + ]; + JsTyping.nodeCoreModules = ts.arrayToSet(JsTyping.nodeCoreModuleList); + function loadSafeList(host, safeListPath) { + var result = ts.readConfigFile(safeListPath, function (path) { return host.readFile(path); }); + return ts.createMapFromTemplate(result.config); + } + JsTyping.loadSafeList = loadSafeList; + function loadTypesMap(host, typesMapPath) { + var result = ts.readConfigFile(typesMapPath, function (path) { return host.readFile(path); }); + if (result.config) { + return ts.createMapFromTemplate(result.config.simpleMap); + } + return undefined; + } + JsTyping.loadTypesMap = loadTypesMap; + /** + * @param host is the object providing I/O related operations. + * @param fileNames are the file names that belong to the same project + * @param projectRootPath is the path to the project root directory + * @param safeListPath is the path used to retrieve the safe list + * @param packageNameToTypingLocation is the map of package names to their cached typing locations and installed versions + * @param typeAcquisition is used to customize the typing acquisition process + * @param compilerOptions are used as a source for typing inference + */ + function discoverTypings(host, log, fileNames, projectRootPath, safeList, packageNameToTypingLocation, typeAcquisition, unresolvedImports, typesRegistry) { + if (!typeAcquisition || !typeAcquisition.enable) { + return { cachedTypingPaths: [], newTypingNames: [], filesToWatch: [] }; + } + // A typing name to typing file path mapping + var inferredTypings = ts.createMap(); + // Only infer typings for .js and .jsx files + fileNames = ts.mapDefined(fileNames, function (fileName) { + var path = ts.normalizePath(fileName); + if (ts.hasJSFileExtension(path)) { + return path; + } + }); + var filesToWatch = []; + if (typeAcquisition.include) + addInferredTypings(typeAcquisition.include, "Explicitly included types"); + var exclude = typeAcquisition.exclude || []; + // Directories to search for package.json, bower.json and other typing information + var possibleSearchDirs = ts.arrayToSet(fileNames, ts.getDirectoryPath); + possibleSearchDirs.set(projectRootPath, true); + possibleSearchDirs.forEach(function (_true, searchDir) { + var packageJsonPath = ts.combinePaths(searchDir, "package.json"); + getTypingNamesFromJson(packageJsonPath, filesToWatch); + var bowerJsonPath = ts.combinePaths(searchDir, "bower.json"); + getTypingNamesFromJson(bowerJsonPath, filesToWatch); + var bowerComponentsPath = ts.combinePaths(searchDir, "bower_components"); + getTypingNamesFromPackagesFolder(bowerComponentsPath, filesToWatch); + var nodeModulesPath = ts.combinePaths(searchDir, "node_modules"); + getTypingNamesFromPackagesFolder(nodeModulesPath, filesToWatch); + }); + getTypingNamesFromSourceFileNames(fileNames); + // add typings for unresolved imports + if (unresolvedImports) { + var module_1 = ts.deduplicate(unresolvedImports.map(function (moduleId) { return JsTyping.nodeCoreModules.has(moduleId) ? "node" : moduleId; }), ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive); + addInferredTypings(module_1, "Inferred typings from unresolved imports"); + } + // Add the cached typing locations for inferred typings that are already installed + packageNameToTypingLocation.forEach(function (typing, name) { + var registryEntry = typesRegistry.get(name); + if (inferredTypings.has(name) && inferredTypings.get(name) === undefined && registryEntry !== undefined && isTypingUpToDate(typing, registryEntry)) { + inferredTypings.set(name, typing.typingLocation); + } + }); + // Remove typings that the user has added to the exclude list + for (var _i = 0, exclude_1 = exclude; _i < exclude_1.length; _i++) { + var excludeTypingName = exclude_1[_i]; + var didDelete = inferredTypings.delete(excludeTypingName); + if (didDelete && log) + log("Typing for " + excludeTypingName + " is in exclude list, will be ignored."); + } + var newTypingNames = []; + var cachedTypingPaths = []; + inferredTypings.forEach(function (inferred, typing) { + if (inferred !== undefined) { + cachedTypingPaths.push(inferred); + } + else { + newTypingNames.push(typing); + } + }); + var result = { cachedTypingPaths: cachedTypingPaths, newTypingNames: newTypingNames, filesToWatch: filesToWatch }; + if (log) + log("Result: " + JSON.stringify(result)); + return result; + function addInferredTyping(typingName) { + if (!inferredTypings.has(typingName)) { + inferredTypings.set(typingName, undefined); // TODO: GH#18217 + } + } + function addInferredTypings(typingNames, message) { + if (log) + log(message + ": " + JSON.stringify(typingNames)); + ts.forEach(typingNames, addInferredTyping); + } + /** + * Get the typing info from common package manager json files like package.json or bower.json + */ + function getTypingNamesFromJson(jsonPath, filesToWatch) { + if (!host.fileExists(jsonPath)) { + return; + } + filesToWatch.push(jsonPath); + var jsonConfig = ts.readConfigFile(jsonPath, function (path) { return host.readFile(path); }).config; + var jsonTypingNames = ts.flatMap([jsonConfig.dependencies, jsonConfig.devDependencies, jsonConfig.optionalDependencies, jsonConfig.peerDependencies], ts.getOwnKeys); + addInferredTypings(jsonTypingNames, "Typing names in '" + jsonPath + "' dependencies"); + } + /** + * Infer typing names from given file names. For example, the file name "jquery-min.2.3.4.js" + * should be inferred to the 'jquery' typing name; and "angular-route.1.2.3.js" should be inferred + * to the 'angular-route' typing name. + * @param fileNames are the names for source files in the project + */ + function getTypingNamesFromSourceFileNames(fileNames) { + var fromFileNames = ts.mapDefined(fileNames, function (j) { + if (!ts.hasJSFileExtension(j)) + return undefined; + var inferredTypingName = ts.removeFileExtension(ts.getBaseFileName(j.toLowerCase())); + var cleanedTypingName = ts.removeMinAndVersionNumbers(inferredTypingName); + return safeList.get(cleanedTypingName); + }); + if (fromFileNames.length) { + addInferredTypings(fromFileNames, "Inferred typings from file names"); + } + var hasJsxFile = ts.some(fileNames, function (f) { return ts.fileExtensionIs(f, ".jsx" /* Jsx */); }); + if (hasJsxFile) { + if (log) + log("Inferred 'react' typings due to presence of '.jsx' extension"); + addInferredTyping("react"); + } + } + /** + * Infer typing names from packages folder (ex: node_module, bower_components) + * @param packagesFolderPath is the path to the packages folder + */ + function getTypingNamesFromPackagesFolder(packagesFolderPath, filesToWatch) { + filesToWatch.push(packagesFolderPath); + // Todo: add support for ModuleResolutionHost too + if (!host.directoryExists(packagesFolderPath)) { + return; + } + // depth of 2, so we access `node_modules/foo` but not `node_modules/foo/bar` + var fileNames = host.readDirectory(packagesFolderPath, [".json" /* Json */], /*excludes*/ undefined, /*includes*/ undefined, /*depth*/ 2); + if (log) + log("Searching for typing names in " + packagesFolderPath + "; all files: " + JSON.stringify(fileNames)); + var packageNames = []; + for (var _i = 0, fileNames_1 = fileNames; _i < fileNames_1.length; _i++) { + var fileName = fileNames_1[_i]; + var normalizedFileName = ts.normalizePath(fileName); + var baseFileName = ts.getBaseFileName(normalizedFileName); + if (baseFileName !== "package.json" && baseFileName !== "bower.json") { + continue; + } + var result_6 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); }); + var packageJson = result_6.config; + // npm 3's package.json contains a "_requiredBy" field + // we should include all the top level module names for npm 2, and only module names whose + // "_requiredBy" field starts with "#" or equals "/" for npm 3. + if (baseFileName === "package.json" && packageJson._requiredBy && + ts.filter(packageJson._requiredBy, function (r) { return r[0] === "#" || r === "/"; }).length === 0) { + continue; + } + // If the package has its own d.ts typings, those will take precedence. Otherwise the package name will be used + // to download d.ts files from DefinitelyTyped + if (!packageJson.name) { + continue; + } + var ownTypes = packageJson.types || packageJson.typings; + if (ownTypes) { + var absolutePath = ts.getNormalizedAbsolutePath(ownTypes, ts.getDirectoryPath(normalizedFileName)); + if (log) + log(" Package '" + packageJson.name + "' provides its own types."); + inferredTypings.set(packageJson.name, absolutePath); + } + else { + packageNames.push(packageJson.name); + } + } + addInferredTypings(packageNames, " Found package names"); + } + } + JsTyping.discoverTypings = discoverTypings; + var PackageNameValidationResult; + (function (PackageNameValidationResult) { + PackageNameValidationResult[PackageNameValidationResult["Ok"] = 0] = "Ok"; + PackageNameValidationResult[PackageNameValidationResult["ScopedPackagesNotSupported"] = 1] = "ScopedPackagesNotSupported"; + PackageNameValidationResult[PackageNameValidationResult["EmptyName"] = 2] = "EmptyName"; + PackageNameValidationResult[PackageNameValidationResult["NameTooLong"] = 3] = "NameTooLong"; + PackageNameValidationResult[PackageNameValidationResult["NameStartsWithDot"] = 4] = "NameStartsWithDot"; + PackageNameValidationResult[PackageNameValidationResult["NameStartsWithUnderscore"] = 5] = "NameStartsWithUnderscore"; + PackageNameValidationResult[PackageNameValidationResult["NameContainsNonURISafeCharacters"] = 6] = "NameContainsNonURISafeCharacters"; + })(PackageNameValidationResult = JsTyping.PackageNameValidationResult || (JsTyping.PackageNameValidationResult = {})); + var maxPackageNameLength = 214; + /** + * Validates package name using rules defined at https://docs.npmjs.com/files/package.json + */ + function validatePackageName(packageName) { + if (!packageName) { + return 2 /* EmptyName */; + } + if (packageName.length > maxPackageNameLength) { + return 3 /* NameTooLong */; + } + if (packageName.charCodeAt(0) === 46 /* dot */) { + return 4 /* NameStartsWithDot */; + } + if (packageName.charCodeAt(0) === 95 /* _ */) { + return 5 /* NameStartsWithUnderscore */; + } + // check if name is scope package like: starts with @ and has one '/' in the middle + // scoped packages are not currently supported + // TODO: when support will be added we'll need to split and check both scope and package name + if (/^@[^/]+\/[^/]+$/.test(packageName)) { + return 1 /* ScopedPackagesNotSupported */; + } + if (encodeURIComponent(packageName) !== packageName) { + return 6 /* NameContainsNonURISafeCharacters */; + } + return 0 /* Ok */; + } + JsTyping.validatePackageName = validatePackageName; + function renderPackageNameValidationFailure(result, typing) { + switch (result) { + case 2 /* EmptyName */: + return "Package name '" + typing + "' cannot be empty"; + case 3 /* NameTooLong */: + return "Package name '" + typing + "' should be less than " + maxPackageNameLength + " characters"; + case 4 /* NameStartsWithDot */: + return "Package name '" + typing + "' cannot start with '.'"; + case 5 /* NameStartsWithUnderscore */: + return "Package name '" + typing + "' cannot start with '_'"; + case 1 /* ScopedPackagesNotSupported */: + return "Package '" + typing + "' is scoped and currently is not supported"; + case 6 /* NameContainsNonURISafeCharacters */: + return "Package name '" + typing + "' contains non URI safe characters"; + case 0 /* Ok */: + return ts.Debug.fail(); // Shouldn't have called this. + default: + throw ts.Debug.assertNever(result); + } + } + JsTyping.renderPackageNameValidationFailure = renderPackageNameValidationFailure; + })(JsTyping = ts.JsTyping || (ts.JsTyping = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + var ScriptSnapshot; + (function (ScriptSnapshot) { + var StringScriptSnapshot = /** @class */ (function () { + function StringScriptSnapshot(text) { + this.text = text; + } + StringScriptSnapshot.prototype.getText = function (start, end) { + return start === 0 && end === this.text.length + ? this.text + : this.text.substring(start, end); + }; + StringScriptSnapshot.prototype.getLength = function () { + return this.text.length; + }; + StringScriptSnapshot.prototype.getChangeRange = function () { + // Text-based snapshots do not support incremental parsing. Return undefined + // to signal that to the caller. + return undefined; + }; + return StringScriptSnapshot; + }()); + function fromString(text) { + return new StringScriptSnapshot(text); + } + ScriptSnapshot.fromString = fromString; + })(ScriptSnapshot = ts.ScriptSnapshot || (ts.ScriptSnapshot = {})); + /* @internal */ + ts.emptyOptions = {}; + var HighlightSpanKind; + (function (HighlightSpanKind) { + HighlightSpanKind["none"] = "none"; + HighlightSpanKind["definition"] = "definition"; + HighlightSpanKind["reference"] = "reference"; + HighlightSpanKind["writtenReference"] = "writtenReference"; + })(HighlightSpanKind = ts.HighlightSpanKind || (ts.HighlightSpanKind = {})); + var IndentStyle; + (function (IndentStyle) { + IndentStyle[IndentStyle["None"] = 0] = "None"; + IndentStyle[IndentStyle["Block"] = 1] = "Block"; + IndentStyle[IndentStyle["Smart"] = 2] = "Smart"; + })(IndentStyle = ts.IndentStyle || (ts.IndentStyle = {})); + function getDefaultFormatCodeSettings(newLineCharacter) { + return { + indentSize: 4, + tabSize: 4, + newLineCharacter: newLineCharacter || "\n", + convertTabsToSpaces: true, + indentStyle: IndentStyle.Smart, + insertSpaceAfterConstructor: false, + insertSpaceAfterCommaDelimiter: true, + insertSpaceAfterSemicolonInForStatements: true, + insertSpaceBeforeAndAfterBinaryOperators: true, + insertSpaceAfterKeywordsInControlFlowStatements: true, + insertSpaceAfterFunctionKeywordForAnonymousFunctions: false, + insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: false, + insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: false, + insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces: true, + insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: false, + insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces: false, + insertSpaceBeforeFunctionParenthesis: false, + placeOpenBraceOnNewLineForFunctions: false, + placeOpenBraceOnNewLineForControlBlocks: false, + }; + } + ts.getDefaultFormatCodeSettings = getDefaultFormatCodeSettings; + /* @internal */ + ts.testFormatSettings = getDefaultFormatCodeSettings("\n"); + var SymbolDisplayPartKind; + (function (SymbolDisplayPartKind) { + SymbolDisplayPartKind[SymbolDisplayPartKind["aliasName"] = 0] = "aliasName"; + SymbolDisplayPartKind[SymbolDisplayPartKind["className"] = 1] = "className"; + SymbolDisplayPartKind[SymbolDisplayPartKind["enumName"] = 2] = "enumName"; + SymbolDisplayPartKind[SymbolDisplayPartKind["fieldName"] = 3] = "fieldName"; + SymbolDisplayPartKind[SymbolDisplayPartKind["interfaceName"] = 4] = "interfaceName"; + SymbolDisplayPartKind[SymbolDisplayPartKind["keyword"] = 5] = "keyword"; + SymbolDisplayPartKind[SymbolDisplayPartKind["lineBreak"] = 6] = "lineBreak"; + SymbolDisplayPartKind[SymbolDisplayPartKind["numericLiteral"] = 7] = "numericLiteral"; + SymbolDisplayPartKind[SymbolDisplayPartKind["stringLiteral"] = 8] = "stringLiteral"; + SymbolDisplayPartKind[SymbolDisplayPartKind["localName"] = 9] = "localName"; + SymbolDisplayPartKind[SymbolDisplayPartKind["methodName"] = 10] = "methodName"; + SymbolDisplayPartKind[SymbolDisplayPartKind["moduleName"] = 11] = "moduleName"; + SymbolDisplayPartKind[SymbolDisplayPartKind["operator"] = 12] = "operator"; + SymbolDisplayPartKind[SymbolDisplayPartKind["parameterName"] = 13] = "parameterName"; + SymbolDisplayPartKind[SymbolDisplayPartKind["propertyName"] = 14] = "propertyName"; + SymbolDisplayPartKind[SymbolDisplayPartKind["punctuation"] = 15] = "punctuation"; + SymbolDisplayPartKind[SymbolDisplayPartKind["space"] = 16] = "space"; + SymbolDisplayPartKind[SymbolDisplayPartKind["text"] = 17] = "text"; + SymbolDisplayPartKind[SymbolDisplayPartKind["typeParameterName"] = 18] = "typeParameterName"; + SymbolDisplayPartKind[SymbolDisplayPartKind["enumMemberName"] = 19] = "enumMemberName"; + SymbolDisplayPartKind[SymbolDisplayPartKind["functionName"] = 20] = "functionName"; + SymbolDisplayPartKind[SymbolDisplayPartKind["regularExpressionLiteral"] = 21] = "regularExpressionLiteral"; + })(SymbolDisplayPartKind = ts.SymbolDisplayPartKind || (ts.SymbolDisplayPartKind = {})); + var OutliningSpanKind; + (function (OutliningSpanKind) { + /** Single or multi-line comments */ + OutliningSpanKind["Comment"] = "comment"; + /** Sections marked by '// #region' and '// #endregion' comments */ + OutliningSpanKind["Region"] = "region"; + /** Declarations and expressions */ + OutliningSpanKind["Code"] = "code"; + /** Contiguous blocks of import declarations */ + OutliningSpanKind["Imports"] = "imports"; + })(OutliningSpanKind = ts.OutliningSpanKind || (ts.OutliningSpanKind = {})); + var OutputFileType; + (function (OutputFileType) { + OutputFileType[OutputFileType["JavaScript"] = 0] = "JavaScript"; + OutputFileType[OutputFileType["SourceMap"] = 1] = "SourceMap"; + OutputFileType[OutputFileType["Declaration"] = 2] = "Declaration"; + })(OutputFileType = ts.OutputFileType || (ts.OutputFileType = {})); + var EndOfLineState; + (function (EndOfLineState) { + EndOfLineState[EndOfLineState["None"] = 0] = "None"; + EndOfLineState[EndOfLineState["InMultiLineCommentTrivia"] = 1] = "InMultiLineCommentTrivia"; + EndOfLineState[EndOfLineState["InSingleQuoteStringLiteral"] = 2] = "InSingleQuoteStringLiteral"; + EndOfLineState[EndOfLineState["InDoubleQuoteStringLiteral"] = 3] = "InDoubleQuoteStringLiteral"; + EndOfLineState[EndOfLineState["InTemplateHeadOrNoSubstitutionTemplate"] = 4] = "InTemplateHeadOrNoSubstitutionTemplate"; + EndOfLineState[EndOfLineState["InTemplateMiddleOrTail"] = 5] = "InTemplateMiddleOrTail"; + EndOfLineState[EndOfLineState["InTemplateSubstitutionPosition"] = 6] = "InTemplateSubstitutionPosition"; + })(EndOfLineState = ts.EndOfLineState || (ts.EndOfLineState = {})); + var TokenClass; + (function (TokenClass) { + TokenClass[TokenClass["Punctuation"] = 0] = "Punctuation"; + TokenClass[TokenClass["Keyword"] = 1] = "Keyword"; + TokenClass[TokenClass["Operator"] = 2] = "Operator"; + TokenClass[TokenClass["Comment"] = 3] = "Comment"; + TokenClass[TokenClass["Whitespace"] = 4] = "Whitespace"; + TokenClass[TokenClass["Identifier"] = 5] = "Identifier"; + TokenClass[TokenClass["NumberLiteral"] = 6] = "NumberLiteral"; + TokenClass[TokenClass["BigIntLiteral"] = 7] = "BigIntLiteral"; + TokenClass[TokenClass["StringLiteral"] = 8] = "StringLiteral"; + TokenClass[TokenClass["RegExpLiteral"] = 9] = "RegExpLiteral"; + })(TokenClass = ts.TokenClass || (ts.TokenClass = {})); + var ScriptElementKind; + (function (ScriptElementKind) { + ScriptElementKind["unknown"] = ""; + ScriptElementKind["warning"] = "warning"; + /** predefined type (void) or keyword (class) */ + ScriptElementKind["keyword"] = "keyword"; + /** top level script node */ + ScriptElementKind["scriptElement"] = "script"; + /** module foo {} */ + ScriptElementKind["moduleElement"] = "module"; + /** class X {} */ + ScriptElementKind["classElement"] = "class"; + /** var x = class X {} */ + ScriptElementKind["localClassElement"] = "local class"; + /** interface Y {} */ + ScriptElementKind["interfaceElement"] = "interface"; + /** type T = ... */ + ScriptElementKind["typeElement"] = "type"; + /** enum E */ + ScriptElementKind["enumElement"] = "enum"; + ScriptElementKind["enumMemberElement"] = "enum member"; + /** + * Inside module and script only + * const v = .. + */ + ScriptElementKind["variableElement"] = "var"; + /** Inside function */ + ScriptElementKind["localVariableElement"] = "local var"; + /** + * Inside module and script only + * function f() { } + */ + ScriptElementKind["functionElement"] = "function"; + /** Inside function */ + ScriptElementKind["localFunctionElement"] = "local function"; + /** class X { [public|private]* foo() {} } */ + ScriptElementKind["memberFunctionElement"] = "method"; + /** class X { [public|private]* [get|set] foo:number; } */ + ScriptElementKind["memberGetAccessorElement"] = "getter"; + ScriptElementKind["memberSetAccessorElement"] = "setter"; + /** + * class X { [public|private]* foo:number; } + * interface Y { foo:number; } + */ + ScriptElementKind["memberVariableElement"] = "property"; + /** class X { constructor() { } } */ + ScriptElementKind["constructorImplementationElement"] = "constructor"; + /** interface Y { ():number; } */ + ScriptElementKind["callSignatureElement"] = "call"; + /** interface Y { []:number; } */ + ScriptElementKind["indexSignatureElement"] = "index"; + /** interface Y { new():Y; } */ + ScriptElementKind["constructSignatureElement"] = "construct"; + /** function foo(*Y*: string) */ + ScriptElementKind["parameterElement"] = "parameter"; + ScriptElementKind["typeParameterElement"] = "type parameter"; + ScriptElementKind["primitiveType"] = "primitive type"; + ScriptElementKind["label"] = "label"; + ScriptElementKind["alias"] = "alias"; + ScriptElementKind["constElement"] = "const"; + ScriptElementKind["letElement"] = "let"; + ScriptElementKind["directory"] = "directory"; + ScriptElementKind["externalModuleName"] = "external module name"; + /** + * + */ + ScriptElementKind["jsxAttribute"] = "JSX attribute"; + /** String literal */ + ScriptElementKind["string"] = "string"; + })(ScriptElementKind = ts.ScriptElementKind || (ts.ScriptElementKind = {})); + var ScriptElementKindModifier; + (function (ScriptElementKindModifier) { + ScriptElementKindModifier["none"] = ""; + ScriptElementKindModifier["publicMemberModifier"] = "public"; + ScriptElementKindModifier["privateMemberModifier"] = "private"; + ScriptElementKindModifier["protectedMemberModifier"] = "protected"; + ScriptElementKindModifier["exportedModifier"] = "export"; + ScriptElementKindModifier["ambientModifier"] = "declare"; + ScriptElementKindModifier["staticModifier"] = "static"; + ScriptElementKindModifier["abstractModifier"] = "abstract"; + ScriptElementKindModifier["optionalModifier"] = "optional"; + ScriptElementKindModifier["dtsModifier"] = ".d.ts"; + ScriptElementKindModifier["tsModifier"] = ".ts"; + ScriptElementKindModifier["tsxModifier"] = ".tsx"; + ScriptElementKindModifier["jsModifier"] = ".js"; + ScriptElementKindModifier["jsxModifier"] = ".jsx"; + ScriptElementKindModifier["jsonModifier"] = ".json"; + })(ScriptElementKindModifier = ts.ScriptElementKindModifier || (ts.ScriptElementKindModifier = {})); + var ClassificationTypeNames; + (function (ClassificationTypeNames) { + ClassificationTypeNames["comment"] = "comment"; + ClassificationTypeNames["identifier"] = "identifier"; + ClassificationTypeNames["keyword"] = "keyword"; + ClassificationTypeNames["numericLiteral"] = "number"; + ClassificationTypeNames["bigintLiteral"] = "bigint"; + ClassificationTypeNames["operator"] = "operator"; + ClassificationTypeNames["stringLiteral"] = "string"; + ClassificationTypeNames["whiteSpace"] = "whitespace"; + ClassificationTypeNames["text"] = "text"; + ClassificationTypeNames["punctuation"] = "punctuation"; + ClassificationTypeNames["className"] = "class name"; + ClassificationTypeNames["enumName"] = "enum name"; + ClassificationTypeNames["interfaceName"] = "interface name"; + ClassificationTypeNames["moduleName"] = "module name"; + ClassificationTypeNames["typeParameterName"] = "type parameter name"; + ClassificationTypeNames["typeAliasName"] = "type alias name"; + ClassificationTypeNames["parameterName"] = "parameter name"; + ClassificationTypeNames["docCommentTagName"] = "doc comment tag name"; + ClassificationTypeNames["jsxOpenTagName"] = "jsx open tag name"; + ClassificationTypeNames["jsxCloseTagName"] = "jsx close tag name"; + ClassificationTypeNames["jsxSelfClosingTagName"] = "jsx self closing tag name"; + ClassificationTypeNames["jsxAttribute"] = "jsx attribute"; + ClassificationTypeNames["jsxText"] = "jsx text"; + ClassificationTypeNames["jsxAttributeStringLiteralValue"] = "jsx attribute string literal value"; + })(ClassificationTypeNames = ts.ClassificationTypeNames || (ts.ClassificationTypeNames = {})); + var ClassificationType; + (function (ClassificationType) { + ClassificationType[ClassificationType["comment"] = 1] = "comment"; + ClassificationType[ClassificationType["identifier"] = 2] = "identifier"; + ClassificationType[ClassificationType["keyword"] = 3] = "keyword"; + ClassificationType[ClassificationType["numericLiteral"] = 4] = "numericLiteral"; + ClassificationType[ClassificationType["operator"] = 5] = "operator"; + ClassificationType[ClassificationType["stringLiteral"] = 6] = "stringLiteral"; + ClassificationType[ClassificationType["regularExpressionLiteral"] = 7] = "regularExpressionLiteral"; + ClassificationType[ClassificationType["whiteSpace"] = 8] = "whiteSpace"; + ClassificationType[ClassificationType["text"] = 9] = "text"; + ClassificationType[ClassificationType["punctuation"] = 10] = "punctuation"; + ClassificationType[ClassificationType["className"] = 11] = "className"; + ClassificationType[ClassificationType["enumName"] = 12] = "enumName"; + ClassificationType[ClassificationType["interfaceName"] = 13] = "interfaceName"; + ClassificationType[ClassificationType["moduleName"] = 14] = "moduleName"; + ClassificationType[ClassificationType["typeParameterName"] = 15] = "typeParameterName"; + ClassificationType[ClassificationType["typeAliasName"] = 16] = "typeAliasName"; + ClassificationType[ClassificationType["parameterName"] = 17] = "parameterName"; + ClassificationType[ClassificationType["docCommentTagName"] = 18] = "docCommentTagName"; + ClassificationType[ClassificationType["jsxOpenTagName"] = 19] = "jsxOpenTagName"; + ClassificationType[ClassificationType["jsxCloseTagName"] = 20] = "jsxCloseTagName"; + ClassificationType[ClassificationType["jsxSelfClosingTagName"] = 21] = "jsxSelfClosingTagName"; + ClassificationType[ClassificationType["jsxAttribute"] = 22] = "jsxAttribute"; + ClassificationType[ClassificationType["jsxText"] = 23] = "jsxText"; + ClassificationType[ClassificationType["jsxAttributeStringLiteralValue"] = 24] = "jsxAttributeStringLiteralValue"; + ClassificationType[ClassificationType["bigintLiteral"] = 25] = "bigintLiteral"; + })(ClassificationType = ts.ClassificationType || (ts.ClassificationType = {})); +})(ts || (ts = {})); +// These utilities are common to multiple language service features. +/* @internal */ +var ts; +(function (ts) { + ts.scanner = ts.createScanner(6 /* Latest */, /*skipTrivia*/ true); + var SemanticMeaning; + (function (SemanticMeaning) { + SemanticMeaning[SemanticMeaning["None"] = 0] = "None"; + SemanticMeaning[SemanticMeaning["Value"] = 1] = "Value"; + SemanticMeaning[SemanticMeaning["Type"] = 2] = "Type"; + SemanticMeaning[SemanticMeaning["Namespace"] = 4] = "Namespace"; + SemanticMeaning[SemanticMeaning["All"] = 7] = "All"; + })(SemanticMeaning = ts.SemanticMeaning || (ts.SemanticMeaning = {})); + function getMeaningFromDeclaration(node) { + switch (node.kind) { + case 237 /* VariableDeclaration */: + return ts.isInJSFile(node) && ts.getJSDocEnumTag(node) ? 7 /* All */ : 1 /* Value */; + case 151 /* Parameter */: + case 186 /* BindingElement */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 275 /* PropertyAssignment */: + case 276 /* ShorthandPropertyAssignment */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 274 /* CatchClause */: + case 267 /* JsxAttribute */: + return 1 /* Value */; + case 150 /* TypeParameter */: + case 241 /* InterfaceDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 168 /* TypeLiteral */: + return 2 /* Type */; + case 304 /* JSDocTypedefTag */: + // If it has no name node, it shares the name with the value declaration below it. + return node.name === undefined ? 1 /* Value */ | 2 /* Type */ : 2 /* Type */; + case 278 /* EnumMember */: + case 240 /* ClassDeclaration */: + return 1 /* Value */ | 2 /* Type */; + case 244 /* ModuleDeclaration */: + if (ts.isAmbientModule(node)) { + return 4 /* Namespace */ | 1 /* Value */; + } + else if (ts.getModuleInstanceState(node) === 1 /* Instantiated */) { + return 4 /* Namespace */ | 1 /* Value */; + } + else { + return 4 /* Namespace */; + } + case 243 /* EnumDeclaration */: + case 252 /* NamedImports */: + case 253 /* ImportSpecifier */: + case 248 /* ImportEqualsDeclaration */: + case 249 /* ImportDeclaration */: + case 254 /* ExportAssignment */: + case 255 /* ExportDeclaration */: + return 7 /* All */; + // An external module can be a Value + case 279 /* SourceFile */: + return 4 /* Namespace */ | 1 /* Value */; + } + return 7 /* All */; + } + ts.getMeaningFromDeclaration = getMeaningFromDeclaration; + function getMeaningFromLocation(node) { + if (node.kind === 279 /* SourceFile */) { + return 1 /* Value */; + } + else if (node.parent.kind === 254 /* ExportAssignment */ || node.parent.kind === 259 /* ExternalModuleReference */) { + return 7 /* All */; + } + else if (isInRightSideOfInternalImportEqualsDeclaration(node)) { + return getMeaningFromRightHandSideOfImportEquals(node); + } + else if (ts.isDeclarationName(node)) { + return getMeaningFromDeclaration(node.parent); + } + else if (isTypeReference(node)) { + return 2 /* Type */; + } + else if (isNamespaceReference(node)) { + return 4 /* Namespace */; + } + else if (ts.isTypeParameterDeclaration(node.parent)) { + ts.Debug.assert(ts.isJSDocTemplateTag(node.parent.parent)); // Else would be handled by isDeclarationName + return 2 /* Type */; + } + else if (ts.isLiteralTypeNode(node.parent)) { + // This might be T["name"], which is actually referencing a property and not a type. So allow both meanings. + return 2 /* Type */ | 1 /* Value */; + } + else { + return 1 /* Value */; + } + } + ts.getMeaningFromLocation = getMeaningFromLocation; + function getMeaningFromRightHandSideOfImportEquals(node) { + // import a = |b|; // Namespace + // import a = |b.c|; // Value, type, namespace + // import a = |b.c|.d; // Namespace + var name = node.kind === 148 /* QualifiedName */ ? node : ts.isQualifiedName(node.parent) && node.parent.right === node ? node.parent : undefined; + return name && name.parent.kind === 248 /* ImportEqualsDeclaration */ ? 7 /* All */ : 4 /* Namespace */; + } + function isInRightSideOfInternalImportEqualsDeclaration(node) { + while (node.parent.kind === 148 /* QualifiedName */) { + node = node.parent; + } + return ts.isInternalModuleImportEqualsDeclaration(node.parent) && node.parent.moduleReference === node; + } + ts.isInRightSideOfInternalImportEqualsDeclaration = isInRightSideOfInternalImportEqualsDeclaration; + function isNamespaceReference(node) { + return isQualifiedNameNamespaceReference(node) || isPropertyAccessNamespaceReference(node); + } + function isQualifiedNameNamespaceReference(node) { + var root = node; + var isLastClause = true; + if (root.parent.kind === 148 /* QualifiedName */) { + while (root.parent && root.parent.kind === 148 /* QualifiedName */) { + root = root.parent; + } + isLastClause = root.right === node; + } + return root.parent.kind === 164 /* TypeReference */ && !isLastClause; + } + function isPropertyAccessNamespaceReference(node) { + var root = node; + var isLastClause = true; + if (root.parent.kind === 189 /* PropertyAccessExpression */) { + while (root.parent && root.parent.kind === 189 /* PropertyAccessExpression */) { + root = root.parent; + } + isLastClause = root.name === node; + } + if (!isLastClause && root.parent.kind === 211 /* ExpressionWithTypeArguments */ && root.parent.parent.kind === 273 /* HeritageClause */) { + var decl = root.parent.parent.parent; + return (decl.kind === 240 /* ClassDeclaration */ && root.parent.parent.token === 109 /* ImplementsKeyword */) || + (decl.kind === 241 /* InterfaceDeclaration */ && root.parent.parent.token === 86 /* ExtendsKeyword */); + } + return false; + } + function isTypeReference(node) { + if (ts.isRightSideOfQualifiedNameOrPropertyAccess(node)) { + node = node.parent; + } + switch (node.kind) { + case 100 /* ThisKeyword */: + return !ts.isExpressionNode(node); + case 178 /* ThisType */: + return true; + } + switch (node.parent.kind) { + case 164 /* TypeReference */: + return true; + case 183 /* ImportType */: + return !node.parent.isTypeOf; + case 211 /* ExpressionWithTypeArguments */: + return !ts.isExpressionWithTypeArgumentsInClassExtendsClause(node.parent); + } + return false; + } + function isCallExpressionTarget(node) { + return isCallOrNewExpressionTargetWorker(node, ts.isCallExpression); + } + ts.isCallExpressionTarget = isCallExpressionTarget; + function isNewExpressionTarget(node) { + return isCallOrNewExpressionTargetWorker(node, ts.isNewExpression); + } + ts.isNewExpressionTarget = isNewExpressionTarget; + function isCallOrNewExpressionTarget(node) { + return isCallOrNewExpressionTargetWorker(node, ts.isCallOrNewExpression); + } + ts.isCallOrNewExpressionTarget = isCallOrNewExpressionTarget; + function isCallOrNewExpressionTargetWorker(node, pred) { + var target = climbPastPropertyAccess(node); + return !!target && !!target.parent && pred(target.parent) && target.parent.expression === target; + } + function climbPastPropertyAccess(node) { + return isRightSideOfPropertyAccess(node) ? node.parent : node; + } + ts.climbPastPropertyAccess = climbPastPropertyAccess; + function getTargetLabel(referenceNode, labelName) { + while (referenceNode) { + if (referenceNode.kind === 233 /* LabeledStatement */ && referenceNode.label.escapedText === labelName) { + return referenceNode.label; + } + referenceNode = referenceNode.parent; + } + return undefined; + } + ts.getTargetLabel = getTargetLabel; + function hasPropertyAccessExpressionWithName(node, funcName) { + if (!ts.isPropertyAccessExpression(node.expression)) { + return false; + } + return node.expression.name.text === funcName; + } + ts.hasPropertyAccessExpressionWithName = hasPropertyAccessExpressionWithName; + function isJumpStatementTarget(node) { + return node.kind === 72 /* Identifier */ && ts.isBreakOrContinueStatement(node.parent) && node.parent.label === node; + } + ts.isJumpStatementTarget = isJumpStatementTarget; + function isLabelOfLabeledStatement(node) { + return node.kind === 72 /* Identifier */ && ts.isLabeledStatement(node.parent) && node.parent.label === node; + } + ts.isLabelOfLabeledStatement = isLabelOfLabeledStatement; + function isLabelName(node) { + return isLabelOfLabeledStatement(node) || isJumpStatementTarget(node); + } + ts.isLabelName = isLabelName; + function isTagName(node) { + return ts.isJSDocTag(node.parent) && node.parent.tagName === node; + } + ts.isTagName = isTagName; + function isRightSideOfQualifiedName(node) { + return node.parent.kind === 148 /* QualifiedName */ && node.parent.right === node; + } + ts.isRightSideOfQualifiedName = isRightSideOfQualifiedName; + function isRightSideOfPropertyAccess(node) { + return node && node.parent && node.parent.kind === 189 /* PropertyAccessExpression */ && node.parent.name === node; + } + ts.isRightSideOfPropertyAccess = isRightSideOfPropertyAccess; + function isNameOfModuleDeclaration(node) { + return node.parent.kind === 244 /* ModuleDeclaration */ && node.parent.name === node; + } + ts.isNameOfModuleDeclaration = isNameOfModuleDeclaration; + function isNameOfFunctionDeclaration(node) { + return node.kind === 72 /* Identifier */ && + ts.isFunctionLike(node.parent) && node.parent.name === node; + } + ts.isNameOfFunctionDeclaration = isNameOfFunctionDeclaration; + function isLiteralNameOfPropertyDeclarationOrIndexAccess(node) { + switch (node.parent.kind) { + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 275 /* PropertyAssignment */: + case 278 /* EnumMember */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 244 /* ModuleDeclaration */: + return ts.getNameOfDeclaration(node.parent) === node; + case 190 /* ElementAccessExpression */: + return node.parent.argumentExpression === node; + case 149 /* ComputedPropertyName */: + return true; + case 182 /* LiteralType */: + return node.parent.parent.kind === 180 /* IndexedAccessType */; + default: + return false; + } + } + ts.isLiteralNameOfPropertyDeclarationOrIndexAccess = isLiteralNameOfPropertyDeclarationOrIndexAccess; + function isExpressionOfExternalModuleImportEqualsDeclaration(node) { + return ts.isExternalModuleImportEqualsDeclaration(node.parent.parent) && + ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node; + } + ts.isExpressionOfExternalModuleImportEqualsDeclaration = isExpressionOfExternalModuleImportEqualsDeclaration; + function getContainerNode(node) { + if (ts.isJSDocTypeAlias(node)) { + // This doesn't just apply to the node immediately under the comment, but to everything in its parent's scope. + // node.parent = the JSDoc comment, node.parent.parent = the node having the comment. + // Then we get parent again in the loop. + node = node.parent.parent; + } + while (true) { + node = node.parent; + if (!node) { + return undefined; + } + switch (node.kind) { + case 279 /* SourceFile */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + case 243 /* EnumDeclaration */: + case 244 /* ModuleDeclaration */: + return node; + } + } + } + ts.getContainerNode = getContainerNode; + function getNodeKind(node) { + switch (node.kind) { + case 279 /* SourceFile */: + return ts.isExternalModule(node) ? "module" /* moduleElement */ : "script" /* scriptElement */; + case 244 /* ModuleDeclaration */: + return "module" /* moduleElement */; + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + return "class" /* classElement */; + case 241 /* InterfaceDeclaration */: return "interface" /* interfaceElement */; + case 242 /* TypeAliasDeclaration */: + case 297 /* JSDocCallbackTag */: + case 304 /* JSDocTypedefTag */: + return "type" /* typeElement */; + case 243 /* EnumDeclaration */: return "enum" /* enumElement */; + case 237 /* VariableDeclaration */: + return getKindOfVariableDeclaration(node); + case 186 /* BindingElement */: + return getKindOfVariableDeclaration(ts.getRootDeclaration(node)); + case 197 /* ArrowFunction */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + return "function" /* functionElement */; + case 158 /* GetAccessor */: return "getter" /* memberGetAccessorElement */; + case 159 /* SetAccessor */: return "setter" /* memberSetAccessorElement */; + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + return "method" /* memberFunctionElement */; + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + return "property" /* memberVariableElement */; + case 162 /* IndexSignature */: return "index" /* indexSignatureElement */; + case 161 /* ConstructSignature */: return "construct" /* constructSignatureElement */; + case 160 /* CallSignature */: return "call" /* callSignatureElement */; + case 157 /* Constructor */: return "constructor" /* constructorImplementationElement */; + case 150 /* TypeParameter */: return "type parameter" /* typeParameterElement */; + case 278 /* EnumMember */: return "enum member" /* enumMemberElement */; + case 151 /* Parameter */: return ts.hasModifier(node, 92 /* ParameterPropertyModifier */) ? "property" /* memberVariableElement */ : "parameter" /* parameterElement */; + case 248 /* ImportEqualsDeclaration */: + case 253 /* ImportSpecifier */: + case 257 /* ExportSpecifier */: + case 251 /* NamespaceImport */: + return "alias" /* alias */; + case 204 /* BinaryExpression */: + var kind = ts.getAssignmentDeclarationKind(node); + var right = node.right; + switch (kind) { + case 7 /* ObjectDefinePropertyValue */: + case 8 /* ObjectDefinePropertyExports */: + case 9 /* ObjectDefinePrototypeProperty */: + case 0 /* None */: + return "" /* unknown */; + case 1 /* ExportsProperty */: + case 2 /* ModuleExports */: + var rightKind = getNodeKind(right); + return rightKind === "" /* unknown */ ? "const" /* constElement */ : rightKind; + case 3 /* PrototypeProperty */: + return ts.isFunctionExpression(right) ? "method" /* memberFunctionElement */ : "property" /* memberVariableElement */; + case 4 /* ThisProperty */: + return "property" /* memberVariableElement */; // property + case 5 /* Property */: + // static method / property + return ts.isFunctionExpression(right) ? "method" /* memberFunctionElement */ : "property" /* memberVariableElement */; + case 6 /* Prototype */: + return "local class" /* localClassElement */; + default: { + ts.assertType(kind); + return "" /* unknown */; + } + } + case 72 /* Identifier */: + return ts.isImportClause(node.parent) ? "alias" /* alias */ : "" /* unknown */; + default: + return "" /* unknown */; + } + function getKindOfVariableDeclaration(v) { + return ts.isVarConst(v) + ? "const" /* constElement */ + : ts.isLet(v) + ? "let" /* letElement */ + : "var" /* variableElement */; + } + } + ts.getNodeKind = getNodeKind; + function isThis(node) { + switch (node.kind) { + case 100 /* ThisKeyword */: + // case SyntaxKind.ThisType: TODO: GH#9267 + return true; + case 72 /* Identifier */: + // 'this' as a parameter + return ts.identifierIsThisKeyword(node) && node.parent.kind === 151 /* Parameter */; + default: + return false; + } + } + ts.isThis = isThis; + // Matches the beginning of a triple slash directive + var tripleSlashDirectivePrefixRegex = /^\/\/\/\s*= range.end; + } + ts.startEndContainsRange = startEndContainsRange; + function rangeContainsStartEnd(range, start, end) { + return range.pos <= start && range.end >= end; + } + ts.rangeContainsStartEnd = rangeContainsStartEnd; + function rangeOverlapsWithStartEnd(r1, start, end) { + return startEndOverlapsWithStartEnd(r1.pos, r1.end, start, end); + } + ts.rangeOverlapsWithStartEnd = rangeOverlapsWithStartEnd; + function nodeOverlapsWithStartEnd(node, sourceFile, start, end) { + return startEndOverlapsWithStartEnd(node.getStart(sourceFile), node.end, start, end); + } + ts.nodeOverlapsWithStartEnd = nodeOverlapsWithStartEnd; + function startEndOverlapsWithStartEnd(start1, end1, start2, end2) { + var start = Math.max(start1, start2); + var end = Math.min(end1, end2); + return start < end; + } + ts.startEndOverlapsWithStartEnd = startEndOverlapsWithStartEnd; + /** + * Assumes `candidate.start <= position` holds. + */ + function positionBelongsToNode(candidate, position, sourceFile) { + ts.Debug.assert(candidate.pos <= position); + return position < candidate.end || !isCompletedNode(candidate, sourceFile); + } + ts.positionBelongsToNode = positionBelongsToNode; + function isCompletedNode(n, sourceFile) { + if (n === undefined || ts.nodeIsMissing(n)) { + return false; + } + switch (n.kind) { + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + case 243 /* EnumDeclaration */: + case 188 /* ObjectLiteralExpression */: + case 184 /* ObjectBindingPattern */: + case 168 /* TypeLiteral */: + case 218 /* Block */: + case 245 /* ModuleBlock */: + case 246 /* CaseBlock */: + case 252 /* NamedImports */: + case 256 /* NamedExports */: + return nodeEndsWith(n, 19 /* CloseBraceToken */, sourceFile); + case 274 /* CatchClause */: + return isCompletedNode(n.block, sourceFile); + case 192 /* NewExpression */: + if (!n.arguments) { + return true; + } + // falls through + case 191 /* CallExpression */: + case 195 /* ParenthesizedExpression */: + case 177 /* ParenthesizedType */: + return nodeEndsWith(n, 21 /* CloseParenToken */, sourceFile); + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + return isCompletedNode(n.type, sourceFile); + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 161 /* ConstructSignature */: + case 160 /* CallSignature */: + case 197 /* ArrowFunction */: + if (n.body) { + return isCompletedNode(n.body, sourceFile); + } + if (n.type) { + return isCompletedNode(n.type, sourceFile); + } + // Even though type parameters can be unclosed, we can get away with + // having at least a closing paren. + return hasChildOfKind(n, 21 /* CloseParenToken */, sourceFile); + case 244 /* ModuleDeclaration */: + return !!n.body && isCompletedNode(n.body, sourceFile); + case 222 /* IfStatement */: + if (n.elseStatement) { + return isCompletedNode(n.elseStatement, sourceFile); + } + return isCompletedNode(n.thenStatement, sourceFile); + case 221 /* ExpressionStatement */: + return isCompletedNode(n.expression, sourceFile) || + hasChildOfKind(n, 26 /* SemicolonToken */, sourceFile); + case 187 /* ArrayLiteralExpression */: + case 185 /* ArrayBindingPattern */: + case 190 /* ElementAccessExpression */: + case 149 /* ComputedPropertyName */: + case 170 /* TupleType */: + return nodeEndsWith(n, 23 /* CloseBracketToken */, sourceFile); + case 162 /* IndexSignature */: + if (n.type) { + return isCompletedNode(n.type, sourceFile); + } + return hasChildOfKind(n, 23 /* CloseBracketToken */, sourceFile); + case 271 /* CaseClause */: + case 272 /* DefaultClause */: + // there is no such thing as terminator token for CaseClause/DefaultClause so for simplicity always consider them non-completed + return false; + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + case 224 /* WhileStatement */: + return isCompletedNode(n.statement, sourceFile); + case 223 /* DoStatement */: + // rough approximation: if DoStatement has While keyword - then if node is completed is checking the presence of ')'; + return hasChildOfKind(n, 107 /* WhileKeyword */, sourceFile) + ? nodeEndsWith(n, 21 /* CloseParenToken */, sourceFile) + : isCompletedNode(n.statement, sourceFile); + case 167 /* TypeQuery */: + return isCompletedNode(n.exprName, sourceFile); + case 199 /* TypeOfExpression */: + case 198 /* DeleteExpression */: + case 200 /* VoidExpression */: + case 207 /* YieldExpression */: + case 208 /* SpreadElement */: + var unaryWordExpression = n; + return isCompletedNode(unaryWordExpression.expression, sourceFile); + case 193 /* TaggedTemplateExpression */: + return isCompletedNode(n.template, sourceFile); + case 206 /* TemplateExpression */: + var lastSpan = ts.lastOrUndefined(n.templateSpans); + return isCompletedNode(lastSpan, sourceFile); + case 216 /* TemplateSpan */: + return ts.nodeIsPresent(n.literal); + case 255 /* ExportDeclaration */: + case 249 /* ImportDeclaration */: + return ts.nodeIsPresent(n.moduleSpecifier); + case 202 /* PrefixUnaryExpression */: + return isCompletedNode(n.operand, sourceFile); + case 204 /* BinaryExpression */: + return isCompletedNode(n.right, sourceFile); + case 205 /* ConditionalExpression */: + return isCompletedNode(n.whenFalse, sourceFile); + default: + return true; + } + } + /* + * Checks if node ends with 'expectedLastToken'. + * If child at position 'length - 1' is 'SemicolonToken' it is skipped and 'expectedLastToken' is compared with child at position 'length - 2'. + */ + function nodeEndsWith(n, expectedLastToken, sourceFile) { + var children = n.getChildren(sourceFile); + if (children.length) { + var lastChild = ts.last(children); + if (lastChild.kind === expectedLastToken) { + return true; + } + else if (lastChild.kind === 26 /* SemicolonToken */ && children.length !== 1) { + return children[children.length - 2].kind === expectedLastToken; + } + } + return false; + } + function findListItemInfo(node) { + var list = findContainingList(node); + // It is possible at this point for syntaxList to be undefined, either if + // node.parent had no list child, or if none of its list children contained + // the span of node. If this happens, return undefined. The caller should + // handle this case. + if (!list) { + return undefined; + } + var children = list.getChildren(); + var listItemIndex = ts.indexOfNode(children, node); + return { + listItemIndex: listItemIndex, + list: list + }; + } + ts.findListItemInfo = findListItemInfo; + function hasChildOfKind(n, kind, sourceFile) { + return !!findChildOfKind(n, kind, sourceFile); + } + ts.hasChildOfKind = hasChildOfKind; + function findChildOfKind(n, kind, sourceFile) { + return ts.find(n.getChildren(sourceFile), function (c) { return c.kind === kind; }); + } + ts.findChildOfKind = findChildOfKind; + function findContainingList(node) { + // The node might be a list element (nonsynthetic) or a comma (synthetic). Either way, it will + // be parented by the container of the SyntaxList, not the SyntaxList itself. + // In order to find the list item index, we first need to locate SyntaxList itself and then search + // for the position of the relevant node (or comma). + var syntaxList = ts.find(node.parent.getChildren(), function (c) { return ts.isSyntaxList(c) && rangeContainsRange(c, node); }); + // Either we didn't find an appropriate list, or the list must contain us. + ts.Debug.assert(!syntaxList || ts.contains(syntaxList.getChildren(), node)); + return syntaxList; + } + ts.findContainingList = findContainingList; + /** + * Gets the token whose text has range [start, end) and + * position >= start and (position < end or (position === end && token is literal or keyword or identifier)) + */ + function getTouchingPropertyName(sourceFile, position) { + return getTouchingToken(sourceFile, position, function (n) { return ts.isPropertyNameLiteral(n) || ts.isKeyword(n.kind); }); + } + ts.getTouchingPropertyName = getTouchingPropertyName; + /** + * Returns the token if position is in [start, end). + * If position === end, returns the preceding token if includeItemAtEndPosition(previousToken) === true + */ + function getTouchingToken(sourceFile, position, includePrecedingTokenAtEndPosition) { + return getTokenAtPositionWorker(sourceFile, position, /*allowPositionInLeadingTrivia*/ false, includePrecedingTokenAtEndPosition, /*includeEndPosition*/ false); + } + ts.getTouchingToken = getTouchingToken; + /** Returns a token if position is in [start-of-leading-trivia, end) */ + function getTokenAtPosition(sourceFile, position) { + return getTokenAtPositionWorker(sourceFile, position, /*allowPositionInLeadingTrivia*/ true, /*includePrecedingTokenAtEndPosition*/ undefined, /*includeEndPosition*/ false); + } + ts.getTokenAtPosition = getTokenAtPosition; + /** Get the token whose text contains the position */ + function getTokenAtPositionWorker(sourceFile, position, allowPositionInLeadingTrivia, includePrecedingTokenAtEndPosition, includeEndPosition) { + var current = sourceFile; + outer: while (true) { + // find the child that contains 'position' + for (var _i = 0, _a = current.getChildren(sourceFile); _i < _a.length; _i++) { + var child = _a[_i]; + var start = allowPositionInLeadingTrivia ? child.getFullStart() : child.getStart(sourceFile, /*includeJsDoc*/ true); + if (start > position) { + // If this child begins after position, then all subsequent children will as well. + break; + } + var end = child.getEnd(); + if (position < end || (position === end && (child.kind === 1 /* EndOfFileToken */ || includeEndPosition))) { + current = child; + continue outer; + } + else if (includePrecedingTokenAtEndPosition && end === position) { + var previousToken = findPrecedingToken(position, sourceFile, child); + if (previousToken && includePrecedingTokenAtEndPosition(previousToken)) { + return previousToken; + } + } + } + return current; + } + } + /** + * The token on the left of the position is the token that strictly includes the position + * or sits to the left of the cursor if it is on a boundary. For example + * + * fo|o -> will return foo + * foo |bar -> will return foo + * + */ + function findTokenOnLeftOfPosition(file, position) { + // Ideally, getTokenAtPosition should return a token. However, it is currently + // broken, so we do a check to make sure the result was indeed a token. + var tokenAtPosition = getTokenAtPosition(file, position); + if (ts.isToken(tokenAtPosition) && position > tokenAtPosition.getStart(file) && position < tokenAtPosition.getEnd()) { + return tokenAtPosition; + } + return findPrecedingToken(position, file); + } + ts.findTokenOnLeftOfPosition = findTokenOnLeftOfPosition; + function findNextToken(previousToken, parent, sourceFile) { + return find(parent); + function find(n) { + if (ts.isToken(n) && n.pos === previousToken.end) { + // this is token that starts at the end of previous token - return it + return n; + } + return ts.firstDefined(n.getChildren(), function (child) { + var shouldDiveInChildNode = + // previous token is enclosed somewhere in the child + (child.pos <= previousToken.pos && child.end > previousToken.end) || + // previous token ends exactly at the beginning of child + (child.pos === previousToken.end); + return shouldDiveInChildNode && nodeHasTokens(child, sourceFile) ? find(child) : undefined; + }); + } + } + ts.findNextToken = findNextToken; + /** + * Finds the rightmost token satisfying `token.end <= position`, + * excluding `JsxText` tokens containing only whitespace. + */ + function findPrecedingToken(position, sourceFile, startNode, excludeJsdoc) { + var result = find(startNode || sourceFile); + ts.Debug.assert(!(result && isWhiteSpaceOnlyJsxText(result))); + return result; + function find(n) { + if (isNonWhitespaceToken(n) && n.kind !== 1 /* EndOfFileToken */) { + return n; + } + var children = n.getChildren(sourceFile); + for (var i = 0; i < children.length; i++) { + var child = children[i]; + // Note that the span of a node's tokens is [node.getStart(...), node.end). + // Given that `position < child.end` and child has constituent tokens, we distinguish these cases: + // 1) `position` precedes `child`'s tokens or `child` has no tokens (ie: in a comment or whitespace preceding `child`): + // we need to find the last token in a previous child. + // 2) `position` is within the same span: we recurse on `child`. + if (position < child.end) { + var start = child.getStart(sourceFile, /*includeJsDoc*/ !excludeJsdoc); + var lookInPreviousChild = (start >= position) || // cursor in the leading trivia + !nodeHasTokens(child, sourceFile) || + isWhiteSpaceOnlyJsxText(child); + if (lookInPreviousChild) { + // actual start of the node is past the position - previous token should be at the end of previous child + var candidate_2 = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ i, sourceFile); + return candidate_2 && findRightmostToken(candidate_2, sourceFile); + } + else { + // candidate should be in this node + return find(child); + } + } + } + ts.Debug.assert(startNode !== undefined || n.kind === 279 /* SourceFile */ || n.kind === 1 /* EndOfFileToken */ || ts.isJSDocCommentContainingNode(n)); + // Here we know that none of child token nodes embrace the position, + // the only known case is when position is at the end of the file. + // Try to find the rightmost token in the file without filtering. + // Namely we are skipping the check: 'position < node.end' + var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ children.length, sourceFile); + return candidate && findRightmostToken(candidate, sourceFile); + } + } + ts.findPrecedingToken = findPrecedingToken; + function isNonWhitespaceToken(n) { + return ts.isToken(n) && !isWhiteSpaceOnlyJsxText(n); + } + function findRightmostToken(n, sourceFile) { + if (isNonWhitespaceToken(n)) { + return n; + } + var children = n.getChildren(sourceFile); + var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ children.length, sourceFile); + return candidate && findRightmostToken(candidate, sourceFile); + } + /** + * Finds the rightmost child to the left of `children[exclusiveStartPosition]` which is a non-all-whitespace token or has constituent tokens. + */ + function findRightmostChildNodeWithTokens(children, exclusiveStartPosition, sourceFile) { + for (var i = exclusiveStartPosition - 1; i >= 0; i--) { + var child = children[i]; + if (isWhiteSpaceOnlyJsxText(child)) { + ts.Debug.assert(i > 0, "`JsxText` tokens should not be the first child of `JsxElement | JsxSelfClosingElement`"); + } + else if (nodeHasTokens(children[i], sourceFile)) { + return children[i]; + } + } + } + function isInString(sourceFile, position, previousToken) { + if (previousToken === void 0) { previousToken = findPrecedingToken(position, sourceFile); } + if (previousToken && ts.isStringTextContainingNode(previousToken)) { + var start = previousToken.getStart(sourceFile); + var end = previousToken.getEnd(); + // To be "in" one of these literals, the position has to be: + // 1. entirely within the token text. + // 2. at the end position of an unterminated token. + // 3. at the end of a regular expression (due to trailing flags like '/foo/g'). + if (start < position && position < end) { + return true; + } + if (position === end) { + return !!previousToken.isUnterminated; + } + } + return false; + } + ts.isInString = isInString; + /** + * returns true if the position is in between the open and close elements of an JSX expression. + */ + function isInsideJsxElementOrAttribute(sourceFile, position) { + var token = getTokenAtPosition(sourceFile, position); + if (!token) { + return false; + } + if (token.kind === 11 /* JsxText */) { + return true; + } + //
      Hello |
      + if (token.kind === 28 /* LessThanToken */ && token.parent.kind === 11 /* JsxText */) { + return true; + } + //
      { |
      or
      + if (token.kind === 28 /* LessThanToken */ && token.parent.kind === 270 /* JsxExpression */) { + return true; + } + //
      { + // | + // } < /div> + if (token && token.kind === 19 /* CloseBraceToken */ && token.parent.kind === 270 /* JsxExpression */) { + return true; + } + //
      |
      + if (token.kind === 28 /* LessThanToken */ && token.parent.kind === 263 /* JsxClosingElement */) { + return true; + } + return false; + } + ts.isInsideJsxElementOrAttribute = isInsideJsxElementOrAttribute; + function isWhiteSpaceOnlyJsxText(node) { + return ts.isJsxText(node) && node.containsOnlyWhiteSpaces; + } + function isInTemplateString(sourceFile, position) { + var token = getTokenAtPosition(sourceFile, position); + return ts.isTemplateLiteralKind(token.kind) && position > token.getStart(sourceFile); + } + ts.isInTemplateString = isInTemplateString; + function isInJSXText(sourceFile, position) { + var token = getTokenAtPosition(sourceFile, position); + if (ts.isJsxText(token)) { + return true; + } + if (token.kind === 18 /* OpenBraceToken */ && ts.isJsxExpression(token.parent) && ts.isJsxElement(token.parent.parent)) { + return true; + } + if (token.kind === 28 /* LessThanToken */ && ts.isJsxOpeningLikeElement(token.parent) && ts.isJsxElement(token.parent.parent)) { + return true; + } + return false; + } + ts.isInJSXText = isInJSXText; + function findPrecedingMatchingToken(token, matchingTokenKind, sourceFile) { + var tokenKind = token.kind; + var remainingMatchingTokens = 0; + while (true) { + var preceding = findPrecedingToken(token.getFullStart(), sourceFile); + if (!preceding) { + return undefined; + } + token = preceding; + if (token.kind === matchingTokenKind) { + if (remainingMatchingTokens === 0) { + return token; + } + remainingMatchingTokens--; + } + else if (token.kind === tokenKind) { + remainingMatchingTokens++; + } + } + } + ts.findPrecedingMatchingToken = findPrecedingMatchingToken; + function isPossiblyTypeArgumentPosition(token, sourceFile, checker) { + var info = getPossibleTypeArgumentsInfo(token, sourceFile); + return info !== undefined && (ts.isPartOfTypeNode(info.called) || + getPossibleGenericSignatures(info.called, info.nTypeArguments, checker).length !== 0 || + isPossiblyTypeArgumentPosition(info.called, sourceFile, checker)); + } + ts.isPossiblyTypeArgumentPosition = isPossiblyTypeArgumentPosition; + function getPossibleGenericSignatures(called, typeArgumentCount, checker) { + var type = checker.getTypeAtLocation(called); + var signatures = ts.isNewExpression(called.parent) ? type.getConstructSignatures() : type.getCallSignatures(); + return signatures.filter(function (candidate) { return !!candidate.typeParameters && candidate.typeParameters.length >= typeArgumentCount; }); + } + ts.getPossibleGenericSignatures = getPossibleGenericSignatures; + // Get info for an expression like `f <` that may be the start of type arguments. + function getPossibleTypeArgumentsInfo(tokenIn, sourceFile) { + var token = tokenIn; + // This function determines if the node could be type argument position + // Since during editing, when type argument list is not complete, + // the tree could be of any shape depending on the tokens parsed before current node, + // scanning of the previous identifier followed by "<" before current node would give us better result + // Note that we also balance out the already provided type arguments, arrays, object literals while doing so + var remainingLessThanTokens = 0; + var nTypeArguments = 0; + while (token) { + switch (token.kind) { + case 28 /* LessThanToken */: + // Found the beginning of the generic argument expression + token = findPrecedingToken(token.getFullStart(), sourceFile); + if (!token || !ts.isIdentifier(token)) + return undefined; + if (!remainingLessThanTokens) { + return ts.isDeclarationName(token) ? undefined : { called: token, nTypeArguments: nTypeArguments }; + } + remainingLessThanTokens--; + break; + case 48 /* GreaterThanGreaterThanGreaterThanToken */: + remainingLessThanTokens = +3; + break; + case 47 /* GreaterThanGreaterThanToken */: + remainingLessThanTokens = +2; + break; + case 30 /* GreaterThanToken */: + remainingLessThanTokens++; + break; + case 19 /* CloseBraceToken */: + // This can be object type, skip until we find the matching open brace token + // Skip until the matching open brace token + token = findPrecedingMatchingToken(token, 18 /* OpenBraceToken */, sourceFile); + if (!token) + return undefined; + break; + case 21 /* CloseParenToken */: + // This can be object type, skip until we find the matching open brace token + // Skip until the matching open brace token + token = findPrecedingMatchingToken(token, 20 /* OpenParenToken */, sourceFile); + if (!token) + return undefined; + break; + case 23 /* CloseBracketToken */: + // This can be object type, skip until we find the matching open brace token + // Skip until the matching open brace token + token = findPrecedingMatchingToken(token, 22 /* OpenBracketToken */, sourceFile); + if (!token) + return undefined; + break; + // Valid tokens in a type name. Skip. + case 27 /* CommaToken */: + nTypeArguments++; + break; + case 37 /* EqualsGreaterThanToken */: + case 72 /* Identifier */: + case 10 /* StringLiteral */: + case 8 /* NumericLiteral */: + case 9 /* BigIntLiteral */: + case 102 /* TrueKeyword */: + case 87 /* FalseKeyword */: + case 104 /* TypeOfKeyword */: + case 86 /* ExtendsKeyword */: + case 129 /* KeyOfKeyword */: + case 24 /* DotToken */: + case 50 /* BarToken */: + case 56 /* QuestionToken */: + case 57 /* ColonToken */: + break; + default: + if (ts.isTypeNode(token)) { + break; + } + // Invalid token in type + return undefined; + } + token = findPrecedingToken(token.getFullStart(), sourceFile); + } + return undefined; + } + ts.getPossibleTypeArgumentsInfo = getPossibleTypeArgumentsInfo; + /** + * Returns true if the cursor at position in sourceFile is within a comment. + * + * @param tokenAtPosition Must equal `getTokenAtPosition(sourceFile, position) + * @param predicate Additional predicate to test on the comment range. + */ + function isInComment(sourceFile, position, tokenAtPosition) { + return ts.formatting.getRangeOfEnclosingComment(sourceFile, position, /*precedingToken*/ undefined, tokenAtPosition); + } + ts.isInComment = isInComment; + function hasDocComment(sourceFile, position) { + var token = getTokenAtPosition(sourceFile, position); + return !!ts.findAncestor(token, ts.isJSDoc); + } + ts.hasDocComment = hasDocComment; + function nodeHasTokens(n, sourceFile) { + // If we have a token or node that has a non-zero width, it must have tokens. + // Note: getWidth() does not take trivia into account. + return n.kind === 1 /* EndOfFileToken */ ? !!n.jsDoc : n.getWidth(sourceFile) !== 0; + } + function getNodeModifiers(node) { + var flags = ts.isDeclaration(node) ? ts.getCombinedModifierFlags(node) : 0 /* None */; + var result = []; + if (flags & 8 /* Private */) + result.push("private" /* privateMemberModifier */); + if (flags & 16 /* Protected */) + result.push("protected" /* protectedMemberModifier */); + if (flags & 4 /* Public */) + result.push("public" /* publicMemberModifier */); + if (flags & 32 /* Static */) + result.push("static" /* staticModifier */); + if (flags & 128 /* Abstract */) + result.push("abstract" /* abstractModifier */); + if (flags & 1 /* Export */) + result.push("export" /* exportedModifier */); + if (node.flags & 4194304 /* Ambient */) + result.push("declare" /* ambientModifier */); + return result.length > 0 ? result.join(",") : "" /* none */; + } + ts.getNodeModifiers = getNodeModifiers; + function getTypeArgumentOrTypeParameterList(node) { + if (node.kind === 164 /* TypeReference */ || node.kind === 191 /* CallExpression */) { + return node.typeArguments; + } + if (ts.isFunctionLike(node) || node.kind === 240 /* ClassDeclaration */ || node.kind === 241 /* InterfaceDeclaration */) { + return node.typeParameters; + } + return undefined; + } + ts.getTypeArgumentOrTypeParameterList = getTypeArgumentOrTypeParameterList; + function isComment(kind) { + return kind === 2 /* SingleLineCommentTrivia */ || kind === 3 /* MultiLineCommentTrivia */; + } + ts.isComment = isComment; + function isStringOrRegularExpressionOrTemplateLiteral(kind) { + if (kind === 10 /* StringLiteral */ + || kind === 13 /* RegularExpressionLiteral */ + || ts.isTemplateLiteralKind(kind)) { + return true; + } + return false; + } + ts.isStringOrRegularExpressionOrTemplateLiteral = isStringOrRegularExpressionOrTemplateLiteral; + function isPunctuation(kind) { + return 18 /* FirstPunctuation */ <= kind && kind <= 71 /* LastPunctuation */; + } + ts.isPunctuation = isPunctuation; + function isInsideTemplateLiteral(node, position, sourceFile) { + return ts.isTemplateLiteralKind(node.kind) + && (node.getStart(sourceFile) < position && position < node.end) || (!!node.isUnterminated && position === node.end); + } + ts.isInsideTemplateLiteral = isInsideTemplateLiteral; + function isAccessibilityModifier(kind) { + switch (kind) { + case 115 /* PublicKeyword */: + case 113 /* PrivateKeyword */: + case 114 /* ProtectedKeyword */: + return true; + } + return false; + } + ts.isAccessibilityModifier = isAccessibilityModifier; + function cloneCompilerOptions(options) { + var result = ts.clone(options); + ts.setConfigFileInOptions(result, options && options.configFile); + return result; + } + ts.cloneCompilerOptions = cloneCompilerOptions; + function isArrayLiteralOrObjectLiteralDestructuringPattern(node) { + if (node.kind === 187 /* ArrayLiteralExpression */ || + node.kind === 188 /* ObjectLiteralExpression */) { + // [a,b,c] from: + // [a, b, c] = someExpression; + if (node.parent.kind === 204 /* BinaryExpression */ && + node.parent.left === node && + node.parent.operatorToken.kind === 59 /* EqualsToken */) { + return true; + } + // [a, b, c] from: + // for([a, b, c] of expression) + if (node.parent.kind === 227 /* ForOfStatement */ && + node.parent.initializer === node) { + return true; + } + // [a, b, c] of + // [x, [a, b, c] ] = someExpression + // or + // {x, a: {a, b, c} } = someExpression + if (isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent.kind === 275 /* PropertyAssignment */ ? node.parent.parent : node.parent)) { + return true; + } + } + return false; + } + ts.isArrayLiteralOrObjectLiteralDestructuringPattern = isArrayLiteralOrObjectLiteralDestructuringPattern; + function isInReferenceComment(sourceFile, position) { + return isInReferenceCommentWorker(sourceFile, position, /*shouldBeReference*/ true); + } + ts.isInReferenceComment = isInReferenceComment; + function isInNonReferenceComment(sourceFile, position) { + return isInReferenceCommentWorker(sourceFile, position, /*shouldBeReference*/ false); + } + ts.isInNonReferenceComment = isInNonReferenceComment; + function isInReferenceCommentWorker(sourceFile, position, shouldBeReference) { + var range = isInComment(sourceFile, position, /*tokenAtPosition*/ undefined); + return !!range && shouldBeReference === tripleSlashDirectivePrefixRegex.test(sourceFile.text.substring(range.pos, range.end)); + } + function createTextSpanFromNode(node, sourceFile) { + return ts.createTextSpanFromBounds(node.getStart(sourceFile), node.getEnd()); + } + ts.createTextSpanFromNode = createTextSpanFromNode; + function createTextRangeFromNode(node, sourceFile) { + return ts.createRange(node.getStart(sourceFile), node.end); + } + ts.createTextRangeFromNode = createTextRangeFromNode; + function createTextSpanFromRange(range) { + return ts.createTextSpanFromBounds(range.pos, range.end); + } + ts.createTextSpanFromRange = createTextSpanFromRange; + function createTextRangeFromSpan(span) { + return ts.createRange(span.start, span.start + span.length); + } + ts.createTextRangeFromSpan = createTextRangeFromSpan; + function createTextChangeFromStartLength(start, length, newText) { + return createTextChange(ts.createTextSpan(start, length), newText); + } + ts.createTextChangeFromStartLength = createTextChangeFromStartLength; + function createTextChange(span, newText) { + return { span: span, newText: newText }; + } + ts.createTextChange = createTextChange; + ts.typeKeywords = [ + 120 /* AnyKeyword */, + 146 /* BigIntKeyword */, + 123 /* BooleanKeyword */, + 87 /* FalseKeyword */, + 129 /* KeyOfKeyword */, + 132 /* NeverKeyword */, + 96 /* NullKeyword */, + 135 /* NumberKeyword */, + 136 /* ObjectKeyword */, + 138 /* StringKeyword */, + 139 /* SymbolKeyword */, + 102 /* TrueKeyword */, + 106 /* VoidKeyword */, + 141 /* UndefinedKeyword */, + 142 /* UniqueKeyword */, + 143 /* UnknownKeyword */, + ]; + function isTypeKeyword(kind) { + return ts.contains(ts.typeKeywords, kind); + } + ts.isTypeKeyword = isTypeKeyword; + /** True if the symbol is for an external module, as opposed to a namespace. */ + function isExternalModuleSymbol(moduleSymbol) { + return !!(moduleSymbol.flags & 1536 /* Module */) && moduleSymbol.name.charCodeAt(0) === 34 /* doubleQuote */; + } + ts.isExternalModuleSymbol = isExternalModuleSymbol; + function nodeSeenTracker() { + var seen = []; + return function (node) { + var id = ts.getNodeId(node); + return !seen[id] && (seen[id] = true); + }; + } + ts.nodeSeenTracker = nodeSeenTracker; + function getSnapshotText(snap) { + return snap.getText(0, snap.getLength()); + } + ts.getSnapshotText = getSnapshotText; + function repeatString(str, count) { + var result = ""; + for (var i = 0; i < count; i++) { + result += str; + } + return result; + } + ts.repeatString = repeatString; + function skipConstraint(type) { + return type.isTypeParameter() ? type.getConstraint() || type : type; + } + ts.skipConstraint = skipConstraint; + function getNameFromPropertyName(name) { + return name.kind === 149 /* ComputedPropertyName */ + // treat computed property names where expression is string/numeric literal as just string/numeric literal + ? ts.isStringOrNumericLiteralLike(name.expression) ? name.expression.text : undefined + : ts.getTextOfIdentifierOrLiteral(name); + } + ts.getNameFromPropertyName = getNameFromPropertyName; + function programContainsEs6Modules(program) { + return program.getSourceFiles().some(function (s) { return !s.isDeclarationFile && !program.isSourceFileFromExternalLibrary(s) && !!s.externalModuleIndicator; }); + } + ts.programContainsEs6Modules = programContainsEs6Modules; + function compilerOptionsIndicateEs6Modules(compilerOptions) { + return !!compilerOptions.module || compilerOptions.target >= 2 /* ES2015 */ || !!compilerOptions.noEmit; + } + ts.compilerOptionsIndicateEs6Modules = compilerOptionsIndicateEs6Modules; + function hostUsesCaseSensitiveFileNames(host) { + return host.useCaseSensitiveFileNames ? host.useCaseSensitiveFileNames() : false; + } + ts.hostUsesCaseSensitiveFileNames = hostUsesCaseSensitiveFileNames; + function hostGetCanonicalFileName(host) { + return ts.createGetCanonicalFileName(hostUsesCaseSensitiveFileNames(host)); + } + ts.hostGetCanonicalFileName = hostGetCanonicalFileName; + function makeImportIfNecessary(defaultImport, namedImports, moduleSpecifier, quotePreference) { + return defaultImport || namedImports && namedImports.length ? makeImport(defaultImport, namedImports, moduleSpecifier, quotePreference) : undefined; + } + ts.makeImportIfNecessary = makeImportIfNecessary; + function makeImport(defaultImport, namedImports, moduleSpecifier, quotePreference) { + return ts.createImportDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, defaultImport || namedImports + ? ts.createImportClause(defaultImport, namedImports && namedImports.length ? ts.createNamedImports(namedImports) : undefined) + : undefined, typeof moduleSpecifier === "string" ? makeStringLiteral(moduleSpecifier, quotePreference) : moduleSpecifier); + } + ts.makeImport = makeImport; + function makeStringLiteral(text, quotePreference) { + return ts.createLiteral(text, quotePreference === 0 /* Single */); + } + ts.makeStringLiteral = makeStringLiteral; + var QuotePreference; + (function (QuotePreference) { + QuotePreference[QuotePreference["Single"] = 0] = "Single"; + QuotePreference[QuotePreference["Double"] = 1] = "Double"; + })(QuotePreference = ts.QuotePreference || (ts.QuotePreference = {})); + function quotePreferenceFromString(str, sourceFile) { + return ts.isStringDoubleQuoted(str, sourceFile) ? 1 /* Double */ : 0 /* Single */; + } + ts.quotePreferenceFromString = quotePreferenceFromString; + function getQuotePreference(sourceFile, preferences) { + if (preferences.quotePreference) { + return preferences.quotePreference === "single" ? 0 /* Single */ : 1 /* Double */; + } + else { + var firstModuleSpecifier = sourceFile.imports && ts.find(sourceFile.imports, ts.isStringLiteral); + return firstModuleSpecifier ? quotePreferenceFromString(firstModuleSpecifier, sourceFile) : 1 /* Double */; + } + } + ts.getQuotePreference = getQuotePreference; + function getQuoteFromPreference(qp) { + switch (qp) { + case 0 /* Single */: return "'"; + case 1 /* Double */: return '"'; + default: return ts.Debug.assertNever(qp); + } + } + ts.getQuoteFromPreference = getQuoteFromPreference; + function symbolNameNoDefault(symbol) { + var escaped = symbolEscapedNameNoDefault(symbol); + return escaped === undefined ? undefined : ts.unescapeLeadingUnderscores(escaped); + } + ts.symbolNameNoDefault = symbolNameNoDefault; + function symbolEscapedNameNoDefault(symbol) { + if (symbol.escapedName !== "default" /* Default */) { + return symbol.escapedName; + } + return ts.firstDefined(symbol.declarations, function (decl) { + var name = ts.getNameOfDeclaration(decl); + return name && name.kind === 72 /* Identifier */ ? name.escapedText : undefined; + }); + } + ts.symbolEscapedNameNoDefault = symbolEscapedNameNoDefault; + function isObjectBindingElementWithoutPropertyName(bindingElement) { + return ts.isBindingElement(bindingElement) && + ts.isObjectBindingPattern(bindingElement.parent) && + ts.isIdentifier(bindingElement.name) && + !bindingElement.propertyName; + } + ts.isObjectBindingElementWithoutPropertyName = isObjectBindingElementWithoutPropertyName; + function getPropertySymbolFromBindingElement(checker, bindingElement) { + var typeOfPattern = checker.getTypeAtLocation(bindingElement.parent); + return typeOfPattern && checker.getPropertyOfType(typeOfPattern, bindingElement.name.text); + } + ts.getPropertySymbolFromBindingElement = getPropertySymbolFromBindingElement; + /** + * Find symbol of the given property-name and add the symbol to the given result array + * @param symbol a symbol to start searching for the given propertyName + * @param propertyName a name of property to search for + * @param result an array of symbol of found property symbols + * @param previousIterationSymbolsCache a cache of symbol from previous iterations of calling this function to prevent infinite revisiting of the same symbol. + * The value of previousIterationSymbol is undefined when the function is first called. + */ + function getPropertySymbolsFromBaseTypes(symbol, propertyName, checker, cb) { + var seen = ts.createMap(); + return recur(symbol); + function recur(symbol) { + // Use `addToSeen` to ensure we don't infinitely recurse in this situation: + // interface C extends C { + // /*findRef*/propName: string; + // } + if (!(symbol.flags & (32 /* Class */ | 64 /* Interface */)) || !ts.addToSeen(seen, ts.getSymbolId(symbol))) + return; + return ts.firstDefined(symbol.declarations, function (declaration) { return ts.firstDefined(ts.getAllSuperTypeNodes(declaration), function (typeReference) { + var type = checker.getTypeAtLocation(typeReference); + var propertySymbol = type && type.symbol && checker.getPropertyOfType(type, propertyName); + // Visit the typeReference as well to see if it directly or indirectly uses that property + return type && propertySymbol && (ts.firstDefined(checker.getRootSymbols(propertySymbol), cb) || recur(type.symbol)); + }); }); + } + } + ts.getPropertySymbolsFromBaseTypes = getPropertySymbolsFromBaseTypes; + function isMemberSymbolInBaseType(memberSymbol, checker) { + return getPropertySymbolsFromBaseTypes(memberSymbol.parent, memberSymbol.name, checker, function (_) { return true; }) || false; + } + ts.isMemberSymbolInBaseType = isMemberSymbolInBaseType; + function getParentNodeInSpan(node, file, span) { + if (!node) + return undefined; + while (node.parent) { + if (ts.isSourceFile(node.parent) || !spanContainsNode(span, node.parent, file)) { + return node; + } + node = node.parent; + } + } + ts.getParentNodeInSpan = getParentNodeInSpan; + function spanContainsNode(span, node, file) { + return ts.textSpanContainsPosition(span, node.getStart(file)) && + node.getEnd() <= ts.textSpanEnd(span); + } + function findModifier(node, kind) { + return node.modifiers && ts.find(node.modifiers, function (m) { return m.kind === kind; }); + } + ts.findModifier = findModifier; + function insertImport(changes, sourceFile, importDecl) { + var lastImportDeclaration = ts.findLast(sourceFile.statements, ts.isAnyImportSyntax); + if (lastImportDeclaration) { + changes.insertNodeAfter(sourceFile, lastImportDeclaration, importDecl); + } + else { + changes.insertNodeAtTopOfFile(sourceFile, importDecl, /*blankLineBetween*/ true); + } + } + ts.insertImport = insertImport; + function textSpansEqual(a, b) { + return !!a && !!b && a.start === b.start && a.length === b.length; + } + ts.textSpansEqual = textSpansEqual; + function documentSpansEqual(a, b) { + return a.fileName === b.fileName && textSpansEqual(a.textSpan, b.textSpan); + } + ts.documentSpansEqual = documentSpansEqual; +})(ts || (ts = {})); +// Display-part writer helpers +/* @internal */ +(function (ts) { + function isFirstDeclarationOfSymbolParameter(symbol) { + return symbol.declarations && symbol.declarations.length > 0 && symbol.declarations[0].kind === 151 /* Parameter */; + } + ts.isFirstDeclarationOfSymbolParameter = isFirstDeclarationOfSymbolParameter; + var displayPartWriter = getDisplayPartWriter(); + function getDisplayPartWriter() { + var absoluteMaximumLength = ts.defaultMaximumTruncationLength * 10; // A hard cutoff to avoid overloading the messaging channel in worst-case scenarios + var displayParts; + var lineStart; + var indent; + var length; + resetWriter(); + var unknownWrite = function (text) { return writeKind(text, ts.SymbolDisplayPartKind.text); }; + return { + displayParts: function () { + var finalText = displayParts.length && displayParts[displayParts.length - 1].text; + if (length > absoluteMaximumLength && finalText && finalText !== "...") { + if (!ts.isWhiteSpaceLike(finalText.charCodeAt(finalText.length - 1))) { + displayParts.push(displayPart(" ", ts.SymbolDisplayPartKind.space)); + } + displayParts.push(displayPart("...", ts.SymbolDisplayPartKind.punctuation)); + } + return displayParts; + }, + writeKeyword: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.keyword); }, + writeOperator: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.operator); }, + writePunctuation: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.punctuation); }, + writeTrailingSemicolon: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.punctuation); }, + writeSpace: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.space); }, + writeStringLiteral: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.stringLiteral); }, + writeParameter: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.parameterName); }, + writeProperty: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.propertyName); }, + writeLiteral: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.stringLiteral); }, + writeSymbol: writeSymbol, + writeLine: writeLine, + write: unknownWrite, + writeComment: unknownWrite, + getText: function () { return ""; }, + getTextPos: function () { return 0; }, + getColumn: function () { return 0; }, + getLine: function () { return 0; }, + isAtStartOfLine: function () { return false; }, + rawWrite: ts.notImplemented, + getIndent: function () { return indent; }, + increaseIndent: function () { indent++; }, + decreaseIndent: function () { indent--; }, + clear: resetWriter, + trackSymbol: ts.noop, + reportInaccessibleThisError: ts.noop, + reportInaccessibleUniqueSymbolError: ts.noop, + reportPrivateInBaseOfClassExpression: ts.noop, + }; + function writeIndent() { + if (length > absoluteMaximumLength) + return; + if (lineStart) { + var indentString = ts.getIndentString(indent); + if (indentString) { + length += indentString.length; + displayParts.push(displayPart(indentString, ts.SymbolDisplayPartKind.space)); + } + lineStart = false; + } + } + function writeKind(text, kind) { + if (length > absoluteMaximumLength) + return; + writeIndent(); + length += text.length; + displayParts.push(displayPart(text, kind)); + } + function writeSymbol(text, symbol) { + if (length > absoluteMaximumLength) + return; + writeIndent(); + length += text.length; + displayParts.push(symbolPart(text, symbol)); + } + function writeLine() { + if (length > absoluteMaximumLength) + return; + length += 1; + displayParts.push(lineBreakPart()); + lineStart = true; + } + function resetWriter() { + displayParts = []; + lineStart = true; + indent = 0; + length = 0; + } + } + function symbolPart(text, symbol) { + return displayPart(text, displayPartKind(symbol)); + function displayPartKind(symbol) { + var flags = symbol.flags; + if (flags & 3 /* Variable */) { + return isFirstDeclarationOfSymbolParameter(symbol) ? ts.SymbolDisplayPartKind.parameterName : ts.SymbolDisplayPartKind.localName; + } + else if (flags & 4 /* Property */) { + return ts.SymbolDisplayPartKind.propertyName; + } + else if (flags & 32768 /* GetAccessor */) { + return ts.SymbolDisplayPartKind.propertyName; + } + else if (flags & 65536 /* SetAccessor */) { + return ts.SymbolDisplayPartKind.propertyName; + } + else if (flags & 8 /* EnumMember */) { + return ts.SymbolDisplayPartKind.enumMemberName; + } + else if (flags & 16 /* Function */) { + return ts.SymbolDisplayPartKind.functionName; + } + else if (flags & 32 /* Class */) { + return ts.SymbolDisplayPartKind.className; + } + else if (flags & 64 /* Interface */) { + return ts.SymbolDisplayPartKind.interfaceName; + } + else if (flags & 384 /* Enum */) { + return ts.SymbolDisplayPartKind.enumName; + } + else if (flags & 1536 /* Module */) { + return ts.SymbolDisplayPartKind.moduleName; + } + else if (flags & 8192 /* Method */) { + return ts.SymbolDisplayPartKind.methodName; + } + else if (flags & 262144 /* TypeParameter */) { + return ts.SymbolDisplayPartKind.typeParameterName; + } + else if (flags & 524288 /* TypeAlias */) { + return ts.SymbolDisplayPartKind.aliasName; + } + else if (flags & 2097152 /* Alias */) { + return ts.SymbolDisplayPartKind.aliasName; + } + return ts.SymbolDisplayPartKind.text; + } + } + ts.symbolPart = symbolPart; + function displayPart(text, kind) { + return { text: text, kind: ts.SymbolDisplayPartKind[kind] }; + } + ts.displayPart = displayPart; + function spacePart() { + return displayPart(" ", ts.SymbolDisplayPartKind.space); + } + ts.spacePart = spacePart; + function keywordPart(kind) { + return displayPart(ts.tokenToString(kind), ts.SymbolDisplayPartKind.keyword); + } + ts.keywordPart = keywordPart; + function punctuationPart(kind) { + return displayPart(ts.tokenToString(kind), ts.SymbolDisplayPartKind.punctuation); + } + ts.punctuationPart = punctuationPart; + function operatorPart(kind) { + return displayPart(ts.tokenToString(kind), ts.SymbolDisplayPartKind.operator); + } + ts.operatorPart = operatorPart; + function textOrKeywordPart(text) { + var kind = ts.stringToToken(text); + return kind === undefined + ? textPart(text) + : keywordPart(kind); + } + ts.textOrKeywordPart = textOrKeywordPart; + function textPart(text) { + return displayPart(text, ts.SymbolDisplayPartKind.text); + } + ts.textPart = textPart; + var carriageReturnLineFeed = "\r\n"; + /** + * The default is CRLF. + */ + function getNewLineOrDefaultFromHost(host, formatSettings) { + return (formatSettings && formatSettings.newLineCharacter) || + (host.getNewLine && host.getNewLine()) || + carriageReturnLineFeed; + } + ts.getNewLineOrDefaultFromHost = getNewLineOrDefaultFromHost; + function lineBreakPart() { + return displayPart("\n", ts.SymbolDisplayPartKind.lineBreak); + } + ts.lineBreakPart = lineBreakPart; + function mapToDisplayParts(writeDisplayParts) { + try { + writeDisplayParts(displayPartWriter); + return displayPartWriter.displayParts(); + } + finally { + displayPartWriter.clear(); + } + } + ts.mapToDisplayParts = mapToDisplayParts; + function typeToDisplayParts(typechecker, type, enclosingDeclaration, flags) { + if (flags === void 0) { flags = 0 /* None */; } + return mapToDisplayParts(function (writer) { + typechecker.writeType(type, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */ | 16384 /* UseAliasDefinedOutsideCurrentScope */, writer); + }); + } + ts.typeToDisplayParts = typeToDisplayParts; + function symbolToDisplayParts(typeChecker, symbol, enclosingDeclaration, meaning, flags) { + if (flags === void 0) { flags = 0 /* None */; } + return mapToDisplayParts(function (writer) { + typeChecker.writeSymbol(symbol, enclosingDeclaration, meaning, flags | 8 /* UseAliasDefinedOutsideCurrentScope */, writer); + }); + } + ts.symbolToDisplayParts = symbolToDisplayParts; + function signatureToDisplayParts(typechecker, signature, enclosingDeclaration, flags) { + if (flags === void 0) { flags = 0 /* None */; } + flags |= 16384 /* UseAliasDefinedOutsideCurrentScope */ | 1024 /* MultilineObjectLiterals */ | 32 /* WriteTypeArgumentsOfSignature */ | 8192 /* OmitParameterModifiers */; + return mapToDisplayParts(function (writer) { + typechecker.writeSignature(signature, enclosingDeclaration, flags, /*signatureKind*/ undefined, writer); + }); + } + ts.signatureToDisplayParts = signatureToDisplayParts; + function isImportOrExportSpecifierName(location) { + return !!location.parent && ts.isImportOrExportSpecifier(location.parent) && location.parent.propertyName === location; + } + ts.isImportOrExportSpecifierName = isImportOrExportSpecifierName; + /** + * Strip off existed single quotes or double quotes from a given string + * + * @return non-quoted string + */ + function stripQuotes(name) { + var length = name.length; + if (length >= 2 && name.charCodeAt(0) === name.charCodeAt(length - 1) && startsWithQuote(name)) { + return name.substring(1, length - 1); + } + return name; + } + ts.stripQuotes = stripQuotes; + function startsWithQuote(name) { + return ts.isSingleOrDoubleQuote(name.charCodeAt(0)); + } + ts.startsWithQuote = startsWithQuote; + function scriptKindIs(fileName, host) { + var scriptKinds = []; + for (var _i = 2; _i < arguments.length; _i++) { + scriptKinds[_i - 2] = arguments[_i]; + } + var scriptKind = getScriptKind(fileName, host); + return ts.some(scriptKinds, function (k) { return k === scriptKind; }); + } + ts.scriptKindIs = scriptKindIs; + function getScriptKind(fileName, host) { + // First check to see if the script kind was specified by the host. Chances are the host + // may override the default script kind for the file extension. + return ts.ensureScriptKind(fileName, host && host.getScriptKind && host.getScriptKind(fileName)); + } + ts.getScriptKind = getScriptKind; + function getUniqueSymbolId(symbol, checker) { + return ts.getSymbolId(ts.skipAlias(symbol, checker)); + } + ts.getUniqueSymbolId = getUniqueSymbolId; + function getFirstNonSpaceCharacterPosition(text, position) { + while (ts.isWhiteSpaceLike(text.charCodeAt(position))) { + position += 1; + } + return position; + } + ts.getFirstNonSpaceCharacterPosition = getFirstNonSpaceCharacterPosition; + function getPrecedingNonSpaceCharacterPosition(text, position) { + while (position > -1 && ts.isWhiteSpaceSingleLine(text.charCodeAt(position))) { + position -= 1; + } + return position + 1; + } + ts.getPrecedingNonSpaceCharacterPosition = getPrecedingNonSpaceCharacterPosition; + /** + * Creates a deep, memberwise clone of a node with no source map location. + * + * WARNING: This is an expensive operation and is only intended to be used in refactorings + * and code fixes (because those are triggered by explicit user actions). + */ + function getSynthesizedDeepClone(node, includeTrivia) { + if (includeTrivia === void 0) { includeTrivia = true; } + var clone = node && getSynthesizedDeepCloneWorker(node); + if (clone && !includeTrivia) + suppressLeadingAndTrailingTrivia(clone); + return clone; + } + ts.getSynthesizedDeepClone = getSynthesizedDeepClone; + function getSynthesizedDeepCloneWithRenames(node, includeTrivia, renameMap, checker, callback) { + if (includeTrivia === void 0) { includeTrivia = true; } + var clone; + if (ts.isIdentifier(node) && renameMap && checker) { + var symbol = checker.getSymbolAtLocation(node); + var renameInfo = symbol && renameMap.get(String(ts.getSymbolId(symbol))); + if (renameInfo) { + clone = ts.createIdentifier(renameInfo.text); + } + } + if (!clone) { + clone = getSynthesizedDeepCloneWorker(node, renameMap, checker, callback); + } + if (clone && !includeTrivia) + suppressLeadingAndTrailingTrivia(clone); + if (callback && clone) + callback(node, clone); + return clone; + } + ts.getSynthesizedDeepCloneWithRenames = getSynthesizedDeepCloneWithRenames; + function getSynthesizedDeepCloneWorker(node, renameMap, checker, callback) { + var visited = (renameMap || checker || callback) ? + ts.visitEachChild(node, wrapper, ts.nullTransformationContext) : + ts.visitEachChild(node, getSynthesizedDeepClone, ts.nullTransformationContext); + if (visited === node) { + // This only happens for leaf nodes - internal nodes always see their children change. + var clone_8 = ts.getSynthesizedClone(node); + if (ts.isStringLiteral(clone_8)) { + clone_8.textSourceNode = node; + } + else if (ts.isNumericLiteral(clone_8)) { + clone_8.numericLiteralFlags = node.numericLiteralFlags; + } + return ts.setTextRange(clone_8, node); + } + // PERF: As an optimization, rather than calling getSynthesizedClone, we'll update + // the new node created by visitEachChild with the extra changes getSynthesizedClone + // would have made. + visited.parent = undefined; + return visited; + function wrapper(node) { + return getSynthesizedDeepCloneWithRenames(node, /*includeTrivia*/ true, renameMap, checker, callback); + } + } + function getSynthesizedDeepClones(nodes, includeTrivia) { + if (includeTrivia === void 0) { includeTrivia = true; } + return nodes && ts.createNodeArray(nodes.map(function (n) { return getSynthesizedDeepClone(n, includeTrivia); }), nodes.hasTrailingComma); + } + ts.getSynthesizedDeepClones = getSynthesizedDeepClones; + /** + * Sets EmitFlags to suppress leading and trailing trivia on the node. + */ + function suppressLeadingAndTrailingTrivia(node) { + suppressLeadingTrivia(node); + suppressTrailingTrivia(node); + } + ts.suppressLeadingAndTrailingTrivia = suppressLeadingAndTrailingTrivia; + /** + * Sets EmitFlags to suppress leading trivia on the node. + */ + function suppressLeadingTrivia(node) { + addEmitFlagsRecursively(node, 512 /* NoLeadingComments */, getFirstChild); + } + ts.suppressLeadingTrivia = suppressLeadingTrivia; + /** + * Sets EmitFlags to suppress trailing trivia on the node. + */ + function suppressTrailingTrivia(node) { + addEmitFlagsRecursively(node, 1024 /* NoTrailingComments */, ts.getLastChild); + } + ts.suppressTrailingTrivia = suppressTrailingTrivia; + function addEmitFlagsRecursively(node, flag, getChild) { + ts.addEmitFlags(node, flag); + var child = getChild(node); + if (child) + addEmitFlagsRecursively(child, flag, getChild); + } + function getFirstChild(node) { + return node.forEachChild(function (child) { return child; }); + } + function getUniqueName(baseName, sourceFile) { + var nameText = baseName; + for (var i = 1; !ts.isFileLevelUniqueName(sourceFile, nameText); i++) { + nameText = baseName + "_" + i; + } + return nameText; + } + ts.getUniqueName = getUniqueName; + /** + * @return The index of the (only) reference to the extracted symbol. We want the cursor + * to be on the reference, rather than the declaration, because it's closer to where the + * user was before extracting it. + */ + function getRenameLocation(edits, renameFilename, name, preferLastLocation) { + var delta = 0; + var lastPos = -1; + for (var _i = 0, edits_1 = edits; _i < edits_1.length; _i++) { + var _a = edits_1[_i], fileName = _a.fileName, textChanges_2 = _a.textChanges; + ts.Debug.assert(fileName === renameFilename); + for (var _b = 0, textChanges_1 = textChanges_2; _b < textChanges_1.length; _b++) { + var change = textChanges_1[_b]; + var span = change.span, newText = change.newText; + var index = indexInTextChange(newText, name); + if (index !== -1) { + lastPos = span.start + delta + index; + // If the reference comes first, return immediately. + if (!preferLastLocation) { + return lastPos; + } + } + delta += newText.length - span.length; + } + } + // If the declaration comes first, return the position of the last occurrence. + ts.Debug.assert(preferLastLocation); + ts.Debug.assert(lastPos >= 0); + return lastPos; + } + ts.getRenameLocation = getRenameLocation; + function copyComments(sourceNode, targetNode, sourceFile, commentKind, hasTrailingNewLine) { + ts.forEachLeadingCommentRange(sourceFile.text, sourceNode.pos, function (pos, end, kind, htnl) { + if (kind === 3 /* MultiLineCommentTrivia */) { + // Remove leading /* + pos += 2; + // Remove trailing */ + end -= 2; + } + else { + // Remove leading // + pos += 2; + } + ts.addSyntheticLeadingComment(targetNode, commentKind || kind, sourceFile.text.slice(pos, end), hasTrailingNewLine !== undefined ? hasTrailingNewLine : htnl); + }); + } + ts.copyComments = copyComments; + function indexInTextChange(change, name) { + if (ts.startsWith(change, name)) + return 0; + // Add a " " to avoid references inside words + var idx = change.indexOf(" " + name); + if (idx === -1) + idx = change.indexOf("." + name); + if (idx === -1) + idx = change.indexOf('"' + name); + return idx === -1 ? -1 : idx + 1; + } + function getContextualTypeFromParent(node, checker) { + var parent = node.parent; + switch (parent.kind) { + case 192 /* NewExpression */: + return checker.getContextualType(parent); + case 204 /* BinaryExpression */: { + var _a = parent, left = _a.left, operatorToken = _a.operatorToken, right = _a.right; + return isEqualityOperatorKind(operatorToken.kind) + ? checker.getTypeAtLocation(node === right ? left : right) + : checker.getContextualType(node); + } + case 271 /* CaseClause */: + return parent.expression === node ? getSwitchedType(parent, checker) : undefined; + default: + return checker.getContextualType(node); + } + } + ts.getContextualTypeFromParent = getContextualTypeFromParent; + function quote(text, preferences) { + if (/^\d+$/.test(text)) { + return text; + } + var quoted = JSON.stringify(text); + switch (preferences.quotePreference) { + case undefined: + case "double": + return quoted; + case "single": + return "'" + stripQuotes(quoted).replace("'", "\\'").replace('\\"', '"') + "'"; + default: + return ts.Debug.assertNever(preferences.quotePreference); + } + } + ts.quote = quote; + function isEqualityOperatorKind(kind) { + switch (kind) { + case 35 /* EqualsEqualsEqualsToken */: + case 33 /* EqualsEqualsToken */: + case 36 /* ExclamationEqualsEqualsToken */: + case 34 /* ExclamationEqualsToken */: + return true; + default: + return false; + } + } + ts.isEqualityOperatorKind = isEqualityOperatorKind; + function isStringLiteralOrTemplate(node) { + switch (node.kind) { + case 10 /* StringLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: + case 206 /* TemplateExpression */: + case 193 /* TaggedTemplateExpression */: + return true; + default: + return false; + } + } + ts.isStringLiteralOrTemplate = isStringLiteralOrTemplate; + function hasIndexSignature(type) { + return !!type.getStringIndexType() || !!type.getNumberIndexType(); + } + ts.hasIndexSignature = hasIndexSignature; + function getSwitchedType(caseClause, checker) { + return checker.getTypeAtLocation(caseClause.parent.parent.expression); + } + ts.getSwitchedType = getSwitchedType; +})(ts || (ts = {})); +var ts; +(function (ts) { + function createClassifier() { + var scanner = ts.createScanner(6 /* Latest */, /*skipTrivia*/ false); + function getClassificationsForLine(text, lexState, syntacticClassifierAbsent) { + return convertClassificationsToResult(getEncodedLexicalClassifications(text, lexState, syntacticClassifierAbsent), text); + } + // If there is a syntactic classifier ('syntacticClassifierAbsent' is false), + // we will be more conservative in order to avoid conflicting with the syntactic classifier. + function getEncodedLexicalClassifications(text, lexState, syntacticClassifierAbsent) { + var token = 0 /* Unknown */; + var lastNonTriviaToken = 0 /* Unknown */; + // Just a stack of TemplateHeads and OpenCurlyBraces, used to perform rudimentary (inexact) + // classification on template strings. Because of the context free nature of templates, + // the only precise way to classify a template portion would be by propagating the stack across + // lines, just as we do with the end-of-line state. However, this is a burden for implementers, + // and the behavior is entirely subsumed by the syntactic classifier anyway, so we instead + // flatten any nesting when the template stack is non-empty and encode it in the end-of-line state. + // Situations in which this fails are + // 1) When template strings are nested across different lines: + // `hello ${ `world + // ` }` + // + // Where on the second line, you will get the closing of a template, + // a closing curly, and a new template. + // + // 2) When substitution expressions have curly braces and the curly brace falls on the next line: + // `hello ${ () => { + // return "world" } } ` + // + // Where on the second line, you will get the 'return' keyword, + // a string literal, and a template end consisting of '} } `'. + var templateStack = []; + var _a = getPrefixFromLexState(lexState), prefix = _a.prefix, pushTemplate = _a.pushTemplate; + text = prefix + text; + var offset = prefix.length; + if (pushTemplate) { + templateStack.push(15 /* TemplateHead */); + } + scanner.setText(text); + var endOfLineState = 0 /* None */; + var spans = []; + // We can run into an unfortunate interaction between the lexical and syntactic classifier + // when the user is typing something generic. Consider the case where the user types: + // + // Foo tokens. It's a weak heuristic, but should + // work well enough in practice. + var angleBracketStack = 0; + do { + token = scanner.scan(); + if (!ts.isTrivia(token)) { + handleToken(); + lastNonTriviaToken = token; + } + var end = scanner.getTextPos(); + pushEncodedClassification(scanner.getTokenPos(), end, offset, classFromKind(token), spans); + if (end >= text.length) { + var end_1 = getNewEndOfLineState(scanner, token, ts.lastOrUndefined(templateStack)); + if (end_1 !== undefined) { + endOfLineState = end_1; + } + } + } while (token !== 1 /* EndOfFileToken */); + function handleToken() { + switch (token) { + case 42 /* SlashToken */: + case 64 /* SlashEqualsToken */: + if (!noRegexTable[lastNonTriviaToken] && scanner.reScanSlashToken() === 13 /* RegularExpressionLiteral */) { + token = 13 /* RegularExpressionLiteral */; + } + break; + case 28 /* LessThanToken */: + if (lastNonTriviaToken === 72 /* Identifier */) { + // Could be the start of something generic. Keep track of that by bumping + // up the current count of generic contexts we may be in. + angleBracketStack++; + } + break; + case 30 /* GreaterThanToken */: + if (angleBracketStack > 0) { + // If we think we're currently in something generic, then mark that that + // generic entity is complete. + angleBracketStack--; + } + break; + case 120 /* AnyKeyword */: + case 138 /* StringKeyword */: + case 135 /* NumberKeyword */: + case 123 /* BooleanKeyword */: + case 139 /* SymbolKeyword */: + if (angleBracketStack > 0 && !syntacticClassifierAbsent) { + // If it looks like we're could be in something generic, don't classify this + // as a keyword. We may just get overwritten by the syntactic classifier, + // causing a noisy experience for the user. + token = 72 /* Identifier */; + } + break; + case 15 /* TemplateHead */: + templateStack.push(token); + break; + case 18 /* OpenBraceToken */: + // If we don't have anything on the template stack, + // then we aren't trying to keep track of a previously scanned template head. + if (templateStack.length > 0) { + templateStack.push(token); + } + break; + case 19 /* CloseBraceToken */: + // If we don't have anything on the template stack, + // then we aren't trying to keep track of a previously scanned template head. + if (templateStack.length > 0) { + var lastTemplateStackToken = ts.lastOrUndefined(templateStack); + if (lastTemplateStackToken === 15 /* TemplateHead */) { + token = scanner.reScanTemplateToken(); + // Only pop on a TemplateTail; a TemplateMiddle indicates there is more for us. + if (token === 17 /* TemplateTail */) { + templateStack.pop(); + } + else { + ts.Debug.assertEqual(token, 16 /* TemplateMiddle */, "Should have been a template middle."); + } + } + else { + ts.Debug.assertEqual(lastTemplateStackToken, 18 /* OpenBraceToken */, "Should have been an open brace"); + templateStack.pop(); + } + } + break; + default: + if (!ts.isKeyword(token)) { + break; + } + if (lastNonTriviaToken === 24 /* DotToken */) { + token = 72 /* Identifier */; + } + else if (ts.isKeyword(lastNonTriviaToken) && ts.isKeyword(token) && !canFollow(lastNonTriviaToken, token)) { + // We have two keywords in a row. Only treat the second as a keyword if + // it's a sequence that could legally occur in the language. Otherwise + // treat it as an identifier. This way, if someone writes "private var" + // we recognize that 'var' is actually an identifier here. + token = 72 /* Identifier */; + } + } + } + return { endOfLineState: endOfLineState, spans: spans }; + } + return { getClassificationsForLine: getClassificationsForLine, getEncodedLexicalClassifications: getEncodedLexicalClassifications }; + } + ts.createClassifier = createClassifier; + /// We do not have a full parser support to know when we should parse a regex or not + /// If we consider every slash token to be a regex, we could be missing cases like "1/2/3", where + /// we have a series of divide operator. this list allows us to be more accurate by ruling out + /// locations where a regexp cannot exist. + var noRegexTable = ts.arrayToNumericMap([ + 72 /* Identifier */, + 10 /* StringLiteral */, + 8 /* NumericLiteral */, + 9 /* BigIntLiteral */, + 13 /* RegularExpressionLiteral */, + 100 /* ThisKeyword */, + 44 /* PlusPlusToken */, + 45 /* MinusMinusToken */, + 21 /* CloseParenToken */, + 23 /* CloseBracketToken */, + 19 /* CloseBraceToken */, + 102 /* TrueKeyword */, + 87 /* FalseKeyword */, + ], function (token) { return token; }, function () { return true; }); + function getNewEndOfLineState(scanner, token, lastOnTemplateStack) { + switch (token) { + case 10 /* StringLiteral */: { + // Check to see if we finished up on a multiline string literal. + if (!scanner.isUnterminated()) + return undefined; + var tokenText = scanner.getTokenText(); + var lastCharIndex = tokenText.length - 1; + var numBackslashes = 0; + while (tokenText.charCodeAt(lastCharIndex - numBackslashes) === 92 /* backslash */) { + numBackslashes++; + } + // If we have an odd number of backslashes, then the multiline string is unclosed + if ((numBackslashes & 1) === 0) + return undefined; + return tokenText.charCodeAt(0) === 34 /* doubleQuote */ ? 3 /* InDoubleQuoteStringLiteral */ : 2 /* InSingleQuoteStringLiteral */; + } + case 3 /* MultiLineCommentTrivia */: + // Check to see if the multiline comment was unclosed. + return scanner.isUnterminated() ? 1 /* InMultiLineCommentTrivia */ : undefined; + default: + if (ts.isTemplateLiteralKind(token)) { + if (!scanner.isUnterminated()) { + return undefined; + } + switch (token) { + case 17 /* TemplateTail */: + return 5 /* InTemplateMiddleOrTail */; + case 14 /* NoSubstitutionTemplateLiteral */: + return 4 /* InTemplateHeadOrNoSubstitutionTemplate */; + default: + return ts.Debug.fail("Only 'NoSubstitutionTemplateLiteral's and 'TemplateTail's can be unterminated; got SyntaxKind #" + token); + } + } + return lastOnTemplateStack === 15 /* TemplateHead */ ? 6 /* InTemplateSubstitutionPosition */ : undefined; + } + } + function pushEncodedClassification(start, end, offset, classification, result) { + if (classification === 8 /* whiteSpace */) { + // Don't bother with whitespace classifications. They're not needed. + return; + } + if (start === 0 && offset > 0) { + // We're classifying the first token, and this was a case where we prepended text. + // We should consider the start of this token to be at the start of the original text. + start += offset; + } + var length = end - start; + if (length > 0) { + // All our tokens are in relation to the augmented text. Move them back to be + // relative to the original text. + result.push(start - offset, length, classification); + } + } + function convertClassificationsToResult(classifications, text) { + var entries = []; + var dense = classifications.spans; + var lastEnd = 0; + for (var i = 0; i < dense.length; i += 3) { + var start = dense[i]; + var length_5 = dense[i + 1]; + var type = dense[i + 2]; + // Make a whitespace entry between the last item and this one. + if (lastEnd >= 0) { + var whitespaceLength_1 = start - lastEnd; + if (whitespaceLength_1 > 0) { + entries.push({ length: whitespaceLength_1, classification: ts.TokenClass.Whitespace }); + } + } + entries.push({ length: length_5, classification: convertClassification(type) }); + lastEnd = start + length_5; + } + var whitespaceLength = text.length - lastEnd; + if (whitespaceLength > 0) { + entries.push({ length: whitespaceLength, classification: ts.TokenClass.Whitespace }); + } + return { entries: entries, finalLexState: classifications.endOfLineState }; + } + function convertClassification(type) { + switch (type) { + case 1 /* comment */: return ts.TokenClass.Comment; + case 3 /* keyword */: return ts.TokenClass.Keyword; + case 4 /* numericLiteral */: return ts.TokenClass.NumberLiteral; + case 25 /* bigintLiteral */: return ts.TokenClass.BigIntLiteral; + case 5 /* operator */: return ts.TokenClass.Operator; + case 6 /* stringLiteral */: return ts.TokenClass.StringLiteral; + case 8 /* whiteSpace */: return ts.TokenClass.Whitespace; + case 10 /* punctuation */: return ts.TokenClass.Punctuation; + case 2 /* identifier */: + case 11 /* className */: + case 12 /* enumName */: + case 13 /* interfaceName */: + case 14 /* moduleName */: + case 15 /* typeParameterName */: + case 16 /* typeAliasName */: + case 9 /* text */: + case 17 /* parameterName */: + return ts.TokenClass.Identifier; + default: + return undefined; // TODO: GH#18217 Debug.assertNever(type); + } + } + /** Returns true if 'keyword2' can legally follow 'keyword1' in any language construct. */ + function canFollow(keyword1, keyword2) { + if (!ts.isAccessibilityModifier(keyword1)) { + // Assume any other keyword combination is legal. + // This can be refined in the future if there are more cases we want the classifier to be better at. + return true; + } + switch (keyword2) { + case 126 /* GetKeyword */: + case 137 /* SetKeyword */: + case 124 /* ConstructorKeyword */: + case 116 /* StaticKeyword */: + return true; // Allow things like "public get", "public constructor" and "public static". + default: + return false; // Any other keyword following "public" is actually an identifier, not a real keyword. + } + } + function getPrefixFromLexState(lexState) { + // If we're in a string literal, then prepend: "\ + // (and a newline). That way when we lex we'll think we're still in a string literal. + // + // If we're in a multiline comment, then prepend: /* + // (and a newline). That way when we lex we'll think we're still in a multiline comment. + switch (lexState) { + case 3 /* InDoubleQuoteStringLiteral */: + return { prefix: "\"\\\n" }; + case 2 /* InSingleQuoteStringLiteral */: + return { prefix: "'\\\n" }; + case 1 /* InMultiLineCommentTrivia */: + return { prefix: "/*\n" }; + case 4 /* InTemplateHeadOrNoSubstitutionTemplate */: + return { prefix: "`\n" }; + case 5 /* InTemplateMiddleOrTail */: + return { prefix: "}\n", pushTemplate: true }; + case 6 /* InTemplateSubstitutionPosition */: + return { prefix: "", pushTemplate: true }; + case 0 /* None */: + return { prefix: "" }; + default: + return ts.Debug.assertNever(lexState); + } + } + function isBinaryExpressionOperatorToken(token) { + switch (token) { + case 40 /* AsteriskToken */: + case 42 /* SlashToken */: + case 43 /* PercentToken */: + case 38 /* PlusToken */: + case 39 /* MinusToken */: + case 46 /* LessThanLessThanToken */: + case 47 /* GreaterThanGreaterThanToken */: + case 48 /* GreaterThanGreaterThanGreaterThanToken */: + case 28 /* LessThanToken */: + case 30 /* GreaterThanToken */: + case 31 /* LessThanEqualsToken */: + case 32 /* GreaterThanEqualsToken */: + case 94 /* InstanceOfKeyword */: + case 93 /* InKeyword */: + case 119 /* AsKeyword */: + case 33 /* EqualsEqualsToken */: + case 34 /* ExclamationEqualsToken */: + case 35 /* EqualsEqualsEqualsToken */: + case 36 /* ExclamationEqualsEqualsToken */: + case 49 /* AmpersandToken */: + case 51 /* CaretToken */: + case 50 /* BarToken */: + case 54 /* AmpersandAmpersandToken */: + case 55 /* BarBarToken */: + case 70 /* BarEqualsToken */: + case 69 /* AmpersandEqualsToken */: + case 71 /* CaretEqualsToken */: + case 66 /* LessThanLessThanEqualsToken */: + case 67 /* GreaterThanGreaterThanEqualsToken */: + case 68 /* GreaterThanGreaterThanGreaterThanEqualsToken */: + case 60 /* PlusEqualsToken */: + case 61 /* MinusEqualsToken */: + case 62 /* AsteriskEqualsToken */: + case 64 /* SlashEqualsToken */: + case 65 /* PercentEqualsToken */: + case 59 /* EqualsToken */: + case 27 /* CommaToken */: + return true; + default: + return false; + } + } + function isPrefixUnaryExpressionOperatorToken(token) { + switch (token) { + case 38 /* PlusToken */: + case 39 /* MinusToken */: + case 53 /* TildeToken */: + case 52 /* ExclamationToken */: + case 44 /* PlusPlusToken */: + case 45 /* MinusMinusToken */: + return true; + default: + return false; + } + } + function classFromKind(token) { + if (ts.isKeyword(token)) { + return 3 /* keyword */; + } + else if (isBinaryExpressionOperatorToken(token) || isPrefixUnaryExpressionOperatorToken(token)) { + return 5 /* operator */; + } + else if (token >= 18 /* FirstPunctuation */ && token <= 71 /* LastPunctuation */) { + return 10 /* punctuation */; + } + switch (token) { + case 8 /* NumericLiteral */: + return 4 /* numericLiteral */; + case 9 /* BigIntLiteral */: + return 25 /* bigintLiteral */; + case 10 /* StringLiteral */: + return 6 /* stringLiteral */; + case 13 /* RegularExpressionLiteral */: + return 7 /* regularExpressionLiteral */; + case 7 /* ConflictMarkerTrivia */: + case 3 /* MultiLineCommentTrivia */: + case 2 /* SingleLineCommentTrivia */: + return 1 /* comment */; + case 5 /* WhitespaceTrivia */: + case 4 /* NewLineTrivia */: + return 8 /* whiteSpace */; + case 72 /* Identifier */: + default: + if (ts.isTemplateLiteralKind(token)) { + return 6 /* stringLiteral */; + } + return 2 /* identifier */; + } + } + /* @internal */ + function getSemanticClassifications(typeChecker, cancellationToken, sourceFile, classifiableNames, span) { + return convertClassificationsToSpans(getEncodedSemanticClassifications(typeChecker, cancellationToken, sourceFile, classifiableNames, span)); + } + ts.getSemanticClassifications = getSemanticClassifications; + function checkForClassificationCancellation(cancellationToken, kind) { + // We don't want to actually call back into our host on every node to find out if we've + // been canceled. That would be an enormous amount of chattyness, along with the all + // the overhead of marshalling the data to/from the host. So instead we pick a few + // reasonable node kinds to bother checking on. These node kinds represent high level + // constructs that we would expect to see commonly, but just at a far less frequent + // interval. + // + // For example, in checker.ts (around 750k) we only have around 600 of these constructs. + // That means we're calling back into the host around every 1.2k of the file we process. + // Lib.d.ts has similar numbers. + switch (kind) { + case 244 /* ModuleDeclaration */: + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + case 239 /* FunctionDeclaration */: + cancellationToken.throwIfCancellationRequested(); + } + } + /* @internal */ + function getEncodedSemanticClassifications(typeChecker, cancellationToken, sourceFile, classifiableNames, span) { + var spans = []; + sourceFile.forEachChild(function cb(node) { + // Only walk into nodes that intersect the requested span. + if (!node || !ts.textSpanIntersectsWith(span, node.pos, node.getFullWidth())) { + return; + } + checkForClassificationCancellation(cancellationToken, node.kind); + // Only bother calling into the typechecker if this is an identifier that + // could possibly resolve to a type name. This makes classification run + // in a third of the time it would normally take. + if (ts.isIdentifier(node) && !ts.nodeIsMissing(node) && classifiableNames.has(node.escapedText)) { + var symbol = typeChecker.getSymbolAtLocation(node); + var type = symbol && classifySymbol(symbol, ts.getMeaningFromLocation(node), typeChecker); + if (type) { + pushClassification(node.getStart(sourceFile), node.getEnd(), type); + } + } + node.forEachChild(cb); + }); + return { spans: spans, endOfLineState: 0 /* None */ }; + function pushClassification(start, end, type) { + spans.push(start); + spans.push(end - start); + spans.push(type); + } + } + ts.getEncodedSemanticClassifications = getEncodedSemanticClassifications; + function classifySymbol(symbol, meaningAtPosition, checker) { + var flags = symbol.getFlags(); + if ((flags & 2885600 /* Classifiable */) === 0 /* None */) { + return undefined; + } + else if (flags & 32 /* Class */) { + return 11 /* className */; + } + else if (flags & 384 /* Enum */) { + return 12 /* enumName */; + } + else if (flags & 524288 /* TypeAlias */) { + return 16 /* typeAliasName */; + } + else if (flags & 1536 /* Module */) { + // Only classify a module as such if + // - It appears in a namespace context. + // - There exists a module declaration which actually impacts the value side. + return meaningAtPosition & 4 /* Namespace */ || meaningAtPosition & 1 /* Value */ && hasValueSideModule(symbol) ? 14 /* moduleName */ : undefined; + } + else if (flags & 2097152 /* Alias */) { + return classifySymbol(checker.getAliasedSymbol(symbol), meaningAtPosition, checker); + } + else if (meaningAtPosition & 2 /* Type */) { + return flags & 64 /* Interface */ ? 13 /* interfaceName */ : flags & 262144 /* TypeParameter */ ? 15 /* typeParameterName */ : undefined; + } + else { + return undefined; + } + } + /** Returns true if there exists a module that introduces entities on the value side. */ + function hasValueSideModule(symbol) { + return ts.some(symbol.declarations, function (declaration) { + return ts.isModuleDeclaration(declaration) && ts.getModuleInstanceState(declaration) === 1 /* Instantiated */; + }); + } + function getClassificationTypeName(type) { + switch (type) { + case 1 /* comment */: return "comment" /* comment */; + case 2 /* identifier */: return "identifier" /* identifier */; + case 3 /* keyword */: return "keyword" /* keyword */; + case 4 /* numericLiteral */: return "number" /* numericLiteral */; + case 25 /* bigintLiteral */: return "bigint" /* bigintLiteral */; + case 5 /* operator */: return "operator" /* operator */; + case 6 /* stringLiteral */: return "string" /* stringLiteral */; + case 8 /* whiteSpace */: return "whitespace" /* whiteSpace */; + case 9 /* text */: return "text" /* text */; + case 10 /* punctuation */: return "punctuation" /* punctuation */; + case 11 /* className */: return "class name" /* className */; + case 12 /* enumName */: return "enum name" /* enumName */; + case 13 /* interfaceName */: return "interface name" /* interfaceName */; + case 14 /* moduleName */: return "module name" /* moduleName */; + case 15 /* typeParameterName */: return "type parameter name" /* typeParameterName */; + case 16 /* typeAliasName */: return "type alias name" /* typeAliasName */; + case 17 /* parameterName */: return "parameter name" /* parameterName */; + case 18 /* docCommentTagName */: return "doc comment tag name" /* docCommentTagName */; + case 19 /* jsxOpenTagName */: return "jsx open tag name" /* jsxOpenTagName */; + case 20 /* jsxCloseTagName */: return "jsx close tag name" /* jsxCloseTagName */; + case 21 /* jsxSelfClosingTagName */: return "jsx self closing tag name" /* jsxSelfClosingTagName */; + case 22 /* jsxAttribute */: return "jsx attribute" /* jsxAttribute */; + case 23 /* jsxText */: return "jsx text" /* jsxText */; + case 24 /* jsxAttributeStringLiteralValue */: return "jsx attribute string literal value" /* jsxAttributeStringLiteralValue */; + default: return undefined; // TODO: GH#18217 throw Debug.assertNever(type); + } + } + function convertClassificationsToSpans(classifications) { + ts.Debug.assert(classifications.spans.length % 3 === 0); + var dense = classifications.spans; + var result = []; + for (var i = 0; i < dense.length; i += 3) { + result.push({ + textSpan: ts.createTextSpan(dense[i], dense[i + 1]), + classificationType: getClassificationTypeName(dense[i + 2]) + }); + } + return result; + } + /* @internal */ + function getSyntacticClassifications(cancellationToken, sourceFile, span) { + return convertClassificationsToSpans(getEncodedSyntacticClassifications(cancellationToken, sourceFile, span)); + } + ts.getSyntacticClassifications = getSyntacticClassifications; + /* @internal */ + function getEncodedSyntacticClassifications(cancellationToken, sourceFile, span) { + var spanStart = span.start; + var spanLength = span.length; + // Make a scanner we can get trivia from. + var triviaScanner = ts.createScanner(6 /* Latest */, /*skipTrivia*/ false, sourceFile.languageVariant, sourceFile.text); + var mergeConflictScanner = ts.createScanner(6 /* Latest */, /*skipTrivia*/ false, sourceFile.languageVariant, sourceFile.text); + var result = []; + processElement(sourceFile); + return { spans: result, endOfLineState: 0 /* None */ }; + function pushClassification(start, length, type) { + result.push(start); + result.push(length); + result.push(type); + } + function classifyLeadingTriviaAndGetTokenStart(token) { + triviaScanner.setTextPos(token.pos); + while (true) { + var start = triviaScanner.getTextPos(); + // only bother scanning if we have something that could be trivia. + if (!ts.couldStartTrivia(sourceFile.text, start)) { + return start; + } + var kind = triviaScanner.scan(); + var end = triviaScanner.getTextPos(); + var width = end - start; + // The moment we get something that isn't trivia, then stop processing. + if (!ts.isTrivia(kind)) { + return start; + } + switch (kind) { + case 4 /* NewLineTrivia */: + case 5 /* WhitespaceTrivia */: + // Don't bother with newlines/whitespace. + continue; + case 2 /* SingleLineCommentTrivia */: + case 3 /* MultiLineCommentTrivia */: + // Only bother with the trivia if it at least intersects the span of interest. + classifyComment(token, kind, start, width); + // Classifying a comment might cause us to reuse the trivia scanner + // (because of jsdoc comments). So after we classify the comment make + // sure we set the scanner position back to where it needs to be. + triviaScanner.setTextPos(end); + continue; + case 7 /* ConflictMarkerTrivia */: + var text = sourceFile.text; + var ch = text.charCodeAt(start); + // for the <<<<<<< and >>>>>>> markers, we just add them in as comments + // in the classification stream. + if (ch === 60 /* lessThan */ || ch === 62 /* greaterThan */) { + pushClassification(start, width, 1 /* comment */); + continue; + } + // for the ||||||| and ======== markers, add a comment for the first line, + // and then lex all subsequent lines up until the end of the conflict marker. + ts.Debug.assert(ch === 124 /* bar */ || ch === 61 /* equals */); + classifyDisabledMergeCode(text, start, end); + break; + case 6 /* ShebangTrivia */: + // TODO: Maybe we should classify these. + break; + default: + ts.Debug.assertNever(kind); + } + } + } + function classifyComment(token, kind, start, width) { + if (kind === 3 /* MultiLineCommentTrivia */) { + // See if this is a doc comment. If so, we'll classify certain portions of it + // specially. + var docCommentAndDiagnostics = ts.parseIsolatedJSDocComment(sourceFile.text, start, width); + if (docCommentAndDiagnostics && docCommentAndDiagnostics.jsDoc) { + // TODO: This should be predicated on `token["kind"]` being compatible with `HasJSDoc["kind"]` + docCommentAndDiagnostics.jsDoc.parent = token; + classifyJSDocComment(docCommentAndDiagnostics.jsDoc); + return; + } + } + // Simple comment. Just add as is. + pushCommentRange(start, width); + } + function pushCommentRange(start, width) { + pushClassification(start, width, 1 /* comment */); + } + function classifyJSDocComment(docComment) { + var pos = docComment.pos; + if (docComment.tags) { + for (var _i = 0, _a = docComment.tags; _i < _a.length; _i++) { + var tag = _a[_i]; + // As we walk through each tag, classify the portion of text from the end of + // the last tag (or the start of the entire doc comment) as 'comment'. + if (tag.pos !== pos) { + pushCommentRange(pos, tag.pos - pos); + } + pushClassification(tag.pos, 1, 10 /* punctuation */); // "@" + pushClassification(tag.tagName.pos, tag.tagName.end - tag.tagName.pos, 18 /* docCommentTagName */); // e.g. "param" + pos = tag.tagName.end; + switch (tag.kind) { + case 299 /* JSDocParameterTag */: + processJSDocParameterTag(tag); + break; + case 303 /* JSDocTemplateTag */: + processJSDocTemplateTag(tag); + pos = tag.end; + break; + case 302 /* JSDocTypeTag */: + processElement(tag.typeExpression); + pos = tag.end; + break; + case 300 /* JSDocReturnTag */: + processElement(tag.typeExpression); + pos = tag.end; + break; + } + } + } + if (pos !== docComment.end) { + pushCommentRange(pos, docComment.end - pos); + } + return; + function processJSDocParameterTag(tag) { + if (tag.isNameFirst) { + pushCommentRange(pos, tag.name.pos - pos); + pushClassification(tag.name.pos, tag.name.end - tag.name.pos, 17 /* parameterName */); + pos = tag.name.end; + } + if (tag.typeExpression) { + pushCommentRange(pos, tag.typeExpression.pos - pos); + processElement(tag.typeExpression); + pos = tag.typeExpression.end; + } + if (!tag.isNameFirst) { + pushCommentRange(pos, tag.name.pos - pos); + pushClassification(tag.name.pos, tag.name.end - tag.name.pos, 17 /* parameterName */); + pos = tag.name.end; + } + } + } + function processJSDocTemplateTag(tag) { + for (var _i = 0, _a = tag.getChildren(); _i < _a.length; _i++) { + var child = _a[_i]; + processElement(child); + } + } + function classifyDisabledMergeCode(text, start, end) { + // Classify the line that the ||||||| or ======= marker is on as a comment. + // Then just lex all further tokens and add them to the result. + var i; + for (i = start; i < end; i++) { + if (ts.isLineBreak(text.charCodeAt(i))) { + break; + } + } + pushClassification(start, i - start, 1 /* comment */); + mergeConflictScanner.setTextPos(i); + while (mergeConflictScanner.getTextPos() < end) { + classifyDisabledCodeToken(); + } + } + function classifyDisabledCodeToken() { + var start = mergeConflictScanner.getTextPos(); + var tokenKind = mergeConflictScanner.scan(); + var end = mergeConflictScanner.getTextPos(); + var type = classifyTokenType(tokenKind); + if (type) { + pushClassification(start, end - start, type); + } + } + /** + * Returns true if node should be treated as classified and no further processing is required. + * False will mean that node is not classified and traverse routine should recurse into node contents. + */ + function tryClassifyNode(node) { + if (ts.isJSDoc(node)) { + return true; + } + if (ts.nodeIsMissing(node)) { + return true; + } + var classifiedElementName = tryClassifyJsxElementName(node); + if (!ts.isToken(node) && node.kind !== 11 /* JsxText */ && classifiedElementName === undefined) { + return false; + } + var tokenStart = node.kind === 11 /* JsxText */ ? node.pos : classifyLeadingTriviaAndGetTokenStart(node); + var tokenWidth = node.end - tokenStart; + ts.Debug.assert(tokenWidth >= 0); + if (tokenWidth > 0) { + var type = classifiedElementName || classifyTokenType(node.kind, node); + if (type) { + pushClassification(tokenStart, tokenWidth, type); + } + } + return true; + } + function tryClassifyJsxElementName(token) { + switch (token.parent && token.parent.kind) { + case 262 /* JsxOpeningElement */: + if (token.parent.tagName === token) { + return 19 /* jsxOpenTagName */; + } + break; + case 263 /* JsxClosingElement */: + if (token.parent.tagName === token) { + return 20 /* jsxCloseTagName */; + } + break; + case 261 /* JsxSelfClosingElement */: + if (token.parent.tagName === token) { + return 21 /* jsxSelfClosingTagName */; + } + break; + case 267 /* JsxAttribute */: + if (token.parent.name === token) { + return 22 /* jsxAttribute */; + } + break; + } + return undefined; + } + // for accurate classification, the actual token should be passed in. however, for + // cases like 'disabled merge code' classification, we just get the token kind and + // classify based on that instead. + function classifyTokenType(tokenKind, token) { + if (ts.isKeyword(tokenKind)) { + return 3 /* keyword */; + } + // Special case `<` and `>`: If they appear in a generic context they are punctuation, + // not operators. + if (tokenKind === 28 /* LessThanToken */ || tokenKind === 30 /* GreaterThanToken */) { + // If the node owning the token has a type argument list or type parameter list, then + // we can effectively assume that a '<' and '>' belong to those lists. + if (token && ts.getTypeArgumentOrTypeParameterList(token.parent)) { + return 10 /* punctuation */; + } + } + if (ts.isPunctuation(tokenKind)) { + if (token) { + var parent = token.parent; + if (tokenKind === 59 /* EqualsToken */) { + // the '=' in a variable declaration is special cased here. + if (parent.kind === 237 /* VariableDeclaration */ || + parent.kind === 154 /* PropertyDeclaration */ || + parent.kind === 151 /* Parameter */ || + parent.kind === 267 /* JsxAttribute */) { + return 5 /* operator */; + } + } + if (parent.kind === 204 /* BinaryExpression */ || + parent.kind === 202 /* PrefixUnaryExpression */ || + parent.kind === 203 /* PostfixUnaryExpression */ || + parent.kind === 205 /* ConditionalExpression */) { + return 5 /* operator */; + } + } + return 10 /* punctuation */; + } + else if (tokenKind === 8 /* NumericLiteral */) { + return 4 /* numericLiteral */; + } + else if (tokenKind === 9 /* BigIntLiteral */) { + return 25 /* bigintLiteral */; + } + else if (tokenKind === 10 /* StringLiteral */) { + // TODO: GH#18217 + return token.parent.kind === 267 /* JsxAttribute */ ? 24 /* jsxAttributeStringLiteralValue */ : 6 /* stringLiteral */; + } + else if (tokenKind === 13 /* RegularExpressionLiteral */) { + // TODO: we should get another classification type for these literals. + return 6 /* stringLiteral */; + } + else if (ts.isTemplateLiteralKind(tokenKind)) { + // TODO (drosen): we should *also* get another classification type for these literals. + return 6 /* stringLiteral */; + } + else if (tokenKind === 11 /* JsxText */) { + return 23 /* jsxText */; + } + else if (tokenKind === 72 /* Identifier */) { + if (token) { + switch (token.parent.kind) { + case 240 /* ClassDeclaration */: + if (token.parent.name === token) { + return 11 /* className */; + } + return; + case 150 /* TypeParameter */: + if (token.parent.name === token) { + return 15 /* typeParameterName */; + } + return; + case 241 /* InterfaceDeclaration */: + if (token.parent.name === token) { + return 13 /* interfaceName */; + } + return; + case 243 /* EnumDeclaration */: + if (token.parent.name === token) { + return 12 /* enumName */; + } + return; + case 244 /* ModuleDeclaration */: + if (token.parent.name === token) { + return 14 /* moduleName */; + } + return; + case 151 /* Parameter */: + if (token.parent.name === token) { + return ts.isThisIdentifier(token) ? 3 /* keyword */ : 17 /* parameterName */; + } + return; + } + } + return 2 /* identifier */; + } + } + function processElement(element) { + if (!element) { + return; + } + // Ignore nodes that don't intersect the original span to classify. + if (ts.decodedTextSpanIntersectsWith(spanStart, spanLength, element.pos, element.getFullWidth())) { + checkForClassificationCancellation(cancellationToken, element.kind); + for (var _i = 0, _a = element.getChildren(sourceFile); _i < _a.length; _i++) { + var child = _a[_i]; + if (!tryClassifyNode(child)) { + // Recurse into our child nodes. + processElement(child); + } + } + } + } + } + ts.getEncodedSyntacticClassifications = getEncodedSyntacticClassifications; +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var Completions; + (function (Completions) { + var StringCompletions; + (function (StringCompletions) { + function getStringLiteralCompletions(sourceFile, position, contextToken, checker, options, host, log, preferences) { + if (ts.isInReferenceComment(sourceFile, position)) { + var entries = getTripleSlashReferenceCompletion(sourceFile, position, options, host); + return entries && convertPathCompletions(entries); + } + if (ts.isInString(sourceFile, position, contextToken)) { + return !contextToken || !ts.isStringLiteralLike(contextToken) + ? undefined + : convertStringLiteralCompletions(getStringLiteralCompletionEntries(sourceFile, contextToken, position, checker, options, host), sourceFile, checker, log, preferences); + } + } + StringCompletions.getStringLiteralCompletions = getStringLiteralCompletions; + function convertStringLiteralCompletions(completion, sourceFile, checker, log, preferences) { + if (completion === undefined) { + return undefined; + } + switch (completion.kind) { + case 0 /* Paths */: + return convertPathCompletions(completion.paths); + case 1 /* Properties */: { + var entries = []; + Completions.getCompletionEntriesFromSymbols(completion.symbols, entries, sourceFile, sourceFile, checker, 6 /* ESNext */, log, 4 /* String */, preferences); // Target will not be used, so arbitrary + return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: completion.hasIndexSignature, entries: entries }; + } + case 2 /* Types */: { + var entries = completion.types.map(function (type) { return ({ name: type.value, kindModifiers: "" /* none */, kind: "string" /* string */, sortText: "0" }); }); + return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: completion.isNewIdentifier, entries: entries }; + } + default: + return ts.Debug.assertNever(completion); + } + } + function getStringLiteralCompletionDetails(name, sourceFile, position, contextToken, checker, options, host, cancellationToken) { + if (!contextToken || !ts.isStringLiteralLike(contextToken)) + return undefined; + var completions = getStringLiteralCompletionEntries(sourceFile, contextToken, position, checker, options, host); + return completions && stringLiteralCompletionDetails(name, contextToken, completions, sourceFile, checker, cancellationToken); + } + StringCompletions.getStringLiteralCompletionDetails = getStringLiteralCompletionDetails; + function stringLiteralCompletionDetails(name, location, completion, sourceFile, checker, cancellationToken) { + switch (completion.kind) { + case 0 /* Paths */: { + var match = ts.find(completion.paths, function (p) { return p.name === name; }); + return match && Completions.createCompletionDetails(name, kindModifiersFromExtension(match.extension), match.kind, [ts.textPart(name)]); + } + case 1 /* Properties */: { + var match = ts.find(completion.symbols, function (s) { return s.name === name; }); + return match && Completions.createCompletionDetailsForSymbol(match, checker, sourceFile, location, cancellationToken); + } + case 2 /* Types */: + return ts.find(completion.types, function (t) { return t.value === name; }) ? Completions.createCompletionDetails(name, "" /* none */, "type" /* typeElement */, [ts.textPart(name)]) : undefined; + default: + return ts.Debug.assertNever(completion); + } + } + function convertPathCompletions(pathCompletions) { + var isGlobalCompletion = false; // We don't want the editor to offer any other completions, such as snippets, inside a comment. + var isNewIdentifierLocation = true; // The user may type in a path that doesn't yet exist, creating a "new identifier" with respect to the collection of identifiers the server is aware of. + var entries = pathCompletions.map(function (_a) { + var name = _a.name, kind = _a.kind, span = _a.span, extension = _a.extension; + return ({ name: name, kind: kind, kindModifiers: kindModifiersFromExtension(extension), sortText: "0", replacementSpan: span }); + }); + return { isGlobalCompletion: isGlobalCompletion, isMemberCompletion: false, isNewIdentifierLocation: isNewIdentifierLocation, entries: entries }; + } + function kindModifiersFromExtension(extension) { + switch (extension) { + case ".d.ts" /* Dts */: return ".d.ts" /* dtsModifier */; + case ".js" /* Js */: return ".js" /* jsModifier */; + case ".json" /* Json */: return ".json" /* jsonModifier */; + case ".jsx" /* Jsx */: return ".jsx" /* jsxModifier */; + case ".ts" /* Ts */: return ".ts" /* tsModifier */; + case ".tsx" /* Tsx */: return ".tsx" /* tsxModifier */; + case undefined: return "" /* none */; + default: + return ts.Debug.assertNever(extension); + } + } + var StringLiteralCompletionKind; + (function (StringLiteralCompletionKind) { + StringLiteralCompletionKind[StringLiteralCompletionKind["Paths"] = 0] = "Paths"; + StringLiteralCompletionKind[StringLiteralCompletionKind["Properties"] = 1] = "Properties"; + StringLiteralCompletionKind[StringLiteralCompletionKind["Types"] = 2] = "Types"; + })(StringLiteralCompletionKind || (StringLiteralCompletionKind = {})); + function getStringLiteralCompletionEntries(sourceFile, node, position, typeChecker, compilerOptions, host) { + var parent = node.parent; + switch (parent.kind) { + case 182 /* LiteralType */: + switch (parent.parent.kind) { + case 164 /* TypeReference */: + return { kind: 2 /* Types */, types: getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(parent)), isNewIdentifier: false }; + case 180 /* IndexedAccessType */: + // Get all apparent property names + // i.e. interface Foo { + // foo: string; + // bar: string; + // } + // let x: Foo["/*completion position*/"] + return stringLiteralCompletionsFromProperties(typeChecker.getTypeFromTypeNode(parent.parent.objectType)); + case 183 /* ImportType */: + return { kind: 0 /* Paths */, paths: getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker) }; + case 173 /* UnionType */: { + if (!ts.isTypeReferenceNode(parent.parent.parent)) + return undefined; + var alreadyUsedTypes_1 = getAlreadyUsedTypesInStringLiteralUnion(parent.parent, parent); + var types = getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(parent.parent)).filter(function (t) { return !ts.contains(alreadyUsedTypes_1, t.value); }); + return { kind: 2 /* Types */, types: types, isNewIdentifier: false }; + } + default: + return undefined; + } + case 275 /* PropertyAssignment */: + if (ts.isObjectLiteralExpression(parent.parent) && parent.name === node) { + // Get quoted name of properties of the object literal expression + // i.e. interface ConfigFiles { + // 'jspm:dev': string + // } + // let files: ConfigFiles = { + // '/*completion position*/' + // } + // + // function foo(c: ConfigFiles) {} + // foo({ + // '/*completion position*/' + // }); + return stringLiteralCompletionsFromProperties(typeChecker.getContextualType(parent.parent)); + } + return fromContextualType(); + case 190 /* ElementAccessExpression */: { + var _a = parent, expression = _a.expression, argumentExpression = _a.argumentExpression; + if (node === argumentExpression) { + // Get all names of properties on the expression + // i.e. interface A { + // 'prop1': string + // } + // let a: A; + // a['/*completion position*/'] + return stringLiteralCompletionsFromProperties(typeChecker.getTypeAtLocation(expression)); + } + return undefined; + } + case 191 /* CallExpression */: + case 192 /* NewExpression */: + if (!ts.isRequireCall(parent, /*checkArgumentIsStringLiteralLike*/ false) && !ts.isImportCall(parent)) { + var argumentInfo = ts.SignatureHelp.getArgumentInfoForCompletions(node, position, sourceFile); + // Get string literal completions from specialized signatures of the target + // i.e. declare function f(a: 'A'); + // f("/*completion position*/") + return argumentInfo ? getStringLiteralCompletionsFromSignature(argumentInfo, typeChecker) : fromContextualType(); + } + // falls through (is `require("")` or `import("")`) + case 249 /* ImportDeclaration */: + case 255 /* ExportDeclaration */: + case 259 /* ExternalModuleReference */: + // Get all known external module names or complete a path to a module + // i.e. import * as ns from "/*completion position*/"; + // var y = import("/*completion position*/"); + // import x = require("/*completion position*/"); + // var y = require("/*completion position*/"); + // export * from "/*completion position*/"; + return { kind: 0 /* Paths */, paths: getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker) }; + default: + return fromContextualType(); + } + function fromContextualType() { + // Get completion for string literal from string literal type + // i.e. var x: "hi" | "hello" = "/*completion position*/" + return { kind: 2 /* Types */, types: getStringLiteralTypes(ts.getContextualTypeFromParent(node, typeChecker)), isNewIdentifier: false }; + } + } + function getAlreadyUsedTypesInStringLiteralUnion(union, current) { + return ts.mapDefined(union.types, function (type) { + return type !== current && ts.isLiteralTypeNode(type) && ts.isStringLiteral(type.literal) ? type.literal.text : undefined; + }); + } + function getStringLiteralCompletionsFromSignature(argumentInfo, checker) { + var isNewIdentifier = false; + var uniques = ts.createMap(); + var candidates = []; + checker.getResolvedSignature(argumentInfo.invocation, candidates, argumentInfo.argumentCount); + var types = ts.flatMap(candidates, function (candidate) { + if (!candidate.hasRestParameter && argumentInfo.argumentCount > candidate.parameters.length) + return; + var type = checker.getParameterType(candidate, argumentInfo.argumentIndex); + isNewIdentifier = isNewIdentifier || !!(type.flags & 4 /* String */); + return getStringLiteralTypes(type, uniques); + }); + return { kind: 2 /* Types */, types: types, isNewIdentifier: isNewIdentifier }; + } + function stringLiteralCompletionsFromProperties(type) { + return type && { kind: 1 /* Properties */, symbols: type.getApparentProperties(), hasIndexSignature: ts.hasIndexSignature(type) }; + } + function getStringLiteralTypes(type, uniques) { + if (uniques === void 0) { uniques = ts.createMap(); } + if (!type) + return ts.emptyArray; + type = ts.skipConstraint(type); + return type.isUnion() + ? ts.flatMap(type.types, function (t) { return getStringLiteralTypes(t, uniques); }) + : type.isStringLiteral() && !(type.flags & 1024 /* EnumLiteral */) && ts.addToSeen(uniques, type.value) + ? [type] + : ts.emptyArray; + } + function nameAndKind(name, kind, extension) { + return { name: name, kind: kind, extension: extension }; + } + function directoryResult(name) { + return nameAndKind(name, "directory" /* directory */, /*extension*/ undefined); + } + function addReplacementSpans(text, textStart, names) { + var span = getDirectoryFragmentTextSpan(text, textStart); + return names.map(function (_a) { + var name = _a.name, kind = _a.kind, extension = _a.extension; + return ({ name: name, kind: kind, extension: extension, span: span }); + }); + } + function getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker) { + return addReplacementSpans(node.text, node.getStart(sourceFile) + 1, getStringLiteralCompletionsFromModuleNamesWorker(sourceFile, node, compilerOptions, host, typeChecker)); + } + function getStringLiteralCompletionsFromModuleNamesWorker(sourceFile, node, compilerOptions, host, typeChecker) { + var literalValue = ts.normalizeSlashes(node.text); + var scriptPath = sourceFile.path; + var scriptDirectory = ts.getDirectoryPath(scriptPath); + return isPathRelativeToScript(literalValue) || !compilerOptions.baseUrl && (ts.isRootedDiskPath(literalValue) || ts.isUrl(literalValue)) + ? getCompletionEntriesForRelativeModules(literalValue, scriptDirectory, compilerOptions, host, scriptPath) + : getCompletionEntriesForNonRelativeModules(literalValue, scriptDirectory, compilerOptions, host, typeChecker); + } + function getExtensionOptions(compilerOptions, includeExtensions) { + if (includeExtensions === void 0) { includeExtensions = false; } + return { extensions: getSupportedExtensionsForModuleResolution(compilerOptions), includeExtensions: includeExtensions }; + } + function getCompletionEntriesForRelativeModules(literalValue, scriptDirectory, compilerOptions, host, scriptPath) { + var extensionOptions = getExtensionOptions(compilerOptions); + if (compilerOptions.rootDirs) { + return getCompletionEntriesForDirectoryFragmentWithRootDirs(compilerOptions.rootDirs, literalValue, scriptDirectory, extensionOptions, compilerOptions, host, scriptPath); + } + else { + return getCompletionEntriesForDirectoryFragment(literalValue, scriptDirectory, extensionOptions, host, scriptPath); + } + } + function getSupportedExtensionsForModuleResolution(compilerOptions) { + var extensions = ts.getSupportedExtensions(compilerOptions); + return compilerOptions.resolveJsonModule && ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs ? + extensions.concat(".json" /* Json */) : + extensions; + } + /** + * Takes a script path and returns paths for all potential folders that could be merged with its + * containing folder via the "rootDirs" compiler option + */ + function getBaseDirectoriesFromRootDirs(rootDirs, basePath, scriptDirectory, ignoreCase) { + // Make all paths absolute/normalized if they are not already + rootDirs = rootDirs.map(function (rootDirectory) { return ts.normalizePath(ts.isRootedDiskPath(rootDirectory) ? rootDirectory : ts.combinePaths(basePath, rootDirectory)); }); + // Determine the path to the directory containing the script relative to the root directory it is contained within + var relativeDirectory = ts.firstDefined(rootDirs, function (rootDirectory) { + return ts.containsPath(rootDirectory, scriptDirectory, basePath, ignoreCase) ? scriptDirectory.substr(rootDirectory.length) : undefined; + }); // TODO: GH#18217 + // Now find a path for each potential directory that is to be merged with the one containing the script + return ts.deduplicate(rootDirs.map(function (rootDirectory) { return ts.combinePaths(rootDirectory, relativeDirectory); }).concat([scriptDirectory]), ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive); + } + function getCompletionEntriesForDirectoryFragmentWithRootDirs(rootDirs, fragment, scriptDirectory, extensionOptions, compilerOptions, host, exclude) { + var basePath = compilerOptions.project || host.getCurrentDirectory(); + var ignoreCase = !(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames()); + var baseDirectories = getBaseDirectoriesFromRootDirs(rootDirs, basePath, scriptDirectory, ignoreCase); + return ts.flatMap(baseDirectories, function (baseDirectory) { return getCompletionEntriesForDirectoryFragment(fragment, baseDirectory, extensionOptions, host, exclude); }); + } + /** + * Given a path ending at a directory, gets the completions for the path, and filters for those entries containing the basename. + */ + function getCompletionEntriesForDirectoryFragment(fragment, scriptPath, _a, host, exclude, result) { + var extensions = _a.extensions, includeExtensions = _a.includeExtensions; + if (result === void 0) { result = []; } + if (fragment === undefined) { + fragment = ""; + } + fragment = ts.normalizeSlashes(fragment); + /** + * Remove the basename from the path. Note that we don't use the basename to filter completions; + * the client is responsible for refining completions. + */ + if (!ts.hasTrailingDirectorySeparator(fragment)) { + fragment = ts.getDirectoryPath(fragment); + } + if (fragment === "") { + fragment = "." + ts.directorySeparator; + } + fragment = ts.ensureTrailingDirectorySeparator(fragment); + // const absolutePath = normalizeAndPreserveTrailingSlash(isRootedDiskPath(fragment) ? fragment : combinePaths(scriptPath, fragment)); // TODO(rbuckton): should use resolvePaths + var absolutePath = ts.resolvePath(scriptPath, fragment); + var baseDirectory = ts.hasTrailingDirectorySeparator(absolutePath) ? absolutePath : ts.getDirectoryPath(absolutePath); + var ignoreCase = !(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames()); + if (!tryDirectoryExists(host, baseDirectory)) + return result; + // Enumerate the available files if possible + var files = tryReadDirectory(host, baseDirectory, extensions, /*exclude*/ undefined, /*include*/ ["./*"]); + if (files) { + /** + * Multiple file entries might map to the same truncated name once we remove extensions + * (happens iff includeExtensions === false)so we use a set-like data structure. Eg: + * + * both foo.ts and foo.tsx become foo + */ + var foundFiles = ts.createMap(); // maps file to its extension + for (var _i = 0, files_3 = files; _i < files_3.length; _i++) { + var filePath = files_3[_i]; + filePath = ts.normalizePath(filePath); + if (exclude && ts.comparePaths(filePath, exclude, scriptPath, ignoreCase) === 0 /* EqualTo */) { + continue; + } + var foundFileName = includeExtensions || ts.fileExtensionIs(filePath, ".json" /* Json */) ? ts.getBaseFileName(filePath) : ts.removeFileExtension(ts.getBaseFileName(filePath)); + foundFiles.set(foundFileName, ts.tryGetExtensionFromPath(filePath)); + } + foundFiles.forEach(function (ext, foundFile) { + result.push(nameAndKind(foundFile, "script" /* scriptElement */, ext)); + }); + } + // If possible, get folder completion as well + var directories = tryGetDirectories(host, baseDirectory); + if (directories) { + for (var _b = 0, directories_1 = directories; _b < directories_1.length; _b++) { + var directory = directories_1[_b]; + var directoryName = ts.getBaseFileName(ts.normalizePath(directory)); + if (directoryName !== "@types") { + result.push(directoryResult(directoryName)); + } + } + } + // check for a version redirect + var packageJsonPath = findPackageJson(baseDirectory, host); + if (packageJsonPath) { + var packageJson = ts.readJson(packageJsonPath, host); + var typesVersions = packageJson.typesVersions; + if (typeof typesVersions === "object") { + var versionResult = ts.getPackageJsonTypesVersionsPaths(typesVersions); + var versionPaths = versionResult && versionResult.paths; + var rest = absolutePath.slice(ts.ensureTrailingDirectorySeparator(baseDirectory).length); + if (versionPaths) { + addCompletionEntriesFromPaths(result, rest, baseDirectory, extensions, versionPaths, host); + } + } + } + return result; + } + function addCompletionEntriesFromPaths(result, fragment, baseDirectory, fileExtensions, paths, host) { + for (var path in paths) { + if (!ts.hasProperty(paths, path)) + continue; + var patterns = paths[path]; + if (patterns) { + var _loop_10 = function (name, kind, extension) { + // Path mappings may provide a duplicate way to get to something we've already added, so don't add again. + if (!result.some(function (entry) { return entry.name === name; })) { + result.push(nameAndKind(name, kind, extension)); + } + }; + for (var _i = 0, _a = getCompletionsForPathMapping(path, patterns, fragment, baseDirectory, fileExtensions, host); _i < _a.length; _i++) { + var _b = _a[_i], name = _b.name, kind = _b.kind, extension = _b.extension; + _loop_10(name, kind, extension); + } + } + } + } + /** + * Check all of the declared modules and those in node modules. Possible sources of modules: + * Modules that are found by the type checker + * Modules found relative to "baseUrl" compliler options (including patterns from "paths" compiler option) + * Modules from node_modules (i.e. those listed in package.json) + * This includes all files that are found in node_modules/moduleName/ with acceptable file extensions + */ + function getCompletionEntriesForNonRelativeModules(fragment, scriptPath, compilerOptions, host, typeChecker) { + var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths; + var result = []; + var extensionOptions = getExtensionOptions(compilerOptions); + if (baseUrl) { + var projectDir = compilerOptions.project || host.getCurrentDirectory(); + var absolute = ts.normalizePath(ts.combinePaths(projectDir, baseUrl)); + getCompletionEntriesForDirectoryFragment(fragment, absolute, extensionOptions, host, /*exclude*/ undefined, result); + if (paths) { + addCompletionEntriesFromPaths(result, fragment, absolute, extensionOptions.extensions, paths, host); + } + } + var fragmentDirectory = getFragmentDirectory(fragment); + for (var _i = 0, _a = getAmbientModuleCompletions(fragment, fragmentDirectory, typeChecker); _i < _a.length; _i++) { + var ambientName = _a[_i]; + result.push(nameAndKind(ambientName, "external module name" /* externalModuleName */, /*extension*/ undefined)); + } + getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, fragmentDirectory, extensionOptions, result); + if (ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs) { + // If looking for a global package name, don't just include everything in `node_modules` because that includes dependencies' own dependencies. + // (But do if we didn't find anything, e.g. 'package.json' missing.) + var foundGlobal = false; + if (fragmentDirectory === undefined) { + var _loop_11 = function (moduleName) { + if (!result.some(function (entry) { return entry.name === moduleName; })) { + foundGlobal = true; + result.push(nameAndKind(moduleName, "external module name" /* externalModuleName */, /*extension*/ undefined)); + } + }; + for (var _b = 0, _c = enumerateNodeModulesVisibleToScript(host, scriptPath); _b < _c.length; _b++) { + var moduleName = _c[_b]; + _loop_11(moduleName); + } + } + if (!foundGlobal) { + ts.forEachAncestorDirectory(scriptPath, function (ancestor) { + var nodeModules = ts.combinePaths(ancestor, "node_modules"); + if (tryDirectoryExists(host, nodeModules)) { + getCompletionEntriesForDirectoryFragment(fragment, nodeModules, extensionOptions, host, /*exclude*/ undefined, result); + } + }); + } + } + return result; + } + function getFragmentDirectory(fragment) { + return containsSlash(fragment) ? ts.hasTrailingDirectorySeparator(fragment) ? fragment : ts.getDirectoryPath(fragment) : undefined; + } + function getCompletionsForPathMapping(path, patterns, fragment, baseUrl, fileExtensions, host) { + if (!ts.endsWith(path, "*")) { + // For a path mapping "foo": ["/x/y/z.ts"], add "foo" itself as a completion. + return !ts.stringContains(path, "*") ? justPathMappingName(path) : ts.emptyArray; + } + var pathPrefix = path.slice(0, path.length - 1); + var remainingFragment = ts.tryRemovePrefix(fragment, pathPrefix); + return remainingFragment === undefined ? justPathMappingName(pathPrefix) : ts.flatMap(patterns, function (pattern) { + return getModulesForPathsPattern(remainingFragment, baseUrl, pattern, fileExtensions, host); + }); + function justPathMappingName(name) { + return ts.startsWith(name, fragment) ? [directoryResult(name)] : ts.emptyArray; + } + } + function getModulesForPathsPattern(fragment, baseUrl, pattern, fileExtensions, host) { + if (!host.readDirectory) { + return undefined; + } + var parsed = ts.hasZeroOrOneAsteriskCharacter(pattern) ? ts.tryParsePattern(pattern) : undefined; + if (!parsed) { + return undefined; + } + // The prefix has two effective parts: the directory path and the base component after the filepath that is not a + // full directory component. For example: directory/path/of/prefix/base* + var normalizedPrefix = ts.resolvePath(parsed.prefix); + var normalizedPrefixDirectory = ts.hasTrailingDirectorySeparator(parsed.prefix) ? normalizedPrefix : ts.getDirectoryPath(normalizedPrefix); + var normalizedPrefixBase = ts.hasTrailingDirectorySeparator(parsed.prefix) ? "" : ts.getBaseFileName(normalizedPrefix); + var fragmentHasPath = containsSlash(fragment); + var fragmentDirectory = fragmentHasPath ? ts.hasTrailingDirectorySeparator(fragment) ? fragment : ts.getDirectoryPath(fragment) : undefined; + // Try and expand the prefix to include any path from the fragment so that we can limit the readDirectory call + var expandedPrefixDirectory = fragmentHasPath ? ts.combinePaths(normalizedPrefixDirectory, normalizedPrefixBase + fragmentDirectory) : normalizedPrefixDirectory; + var normalizedSuffix = ts.normalizePath(parsed.suffix); + // Need to normalize after combining: If we combinePaths("a", "../b"), we want "b" and not "a/../b". + var baseDirectory = ts.normalizePath(ts.combinePaths(baseUrl, expandedPrefixDirectory)); + var completePrefix = fragmentHasPath ? baseDirectory : ts.ensureTrailingDirectorySeparator(baseDirectory) + normalizedPrefixBase; + // If we have a suffix, then we need to read the directory all the way down. We could create a glob + // that encodes the suffix, but we would have to escape the character "?" which readDirectory + // doesn't support. For now, this is safer but slower + var includeGlob = normalizedSuffix ? "**/*" : "./*"; + var matches = ts.mapDefined(tryReadDirectory(host, baseDirectory, fileExtensions, /*exclude*/ undefined, [includeGlob]), function (match) { + var extension = ts.tryGetExtensionFromPath(match); + var name = trimPrefixAndSuffix(match); + return name === undefined ? undefined : nameAndKind(ts.removeFileExtension(name), "script" /* scriptElement */, extension); + }); + var directories = ts.mapDefined(tryGetDirectories(host, baseDirectory).map(function (d) { return ts.combinePaths(baseDirectory, d); }), function (dir) { + var name = trimPrefixAndSuffix(dir); + return name === undefined ? undefined : directoryResult(name); + }); + return matches.concat(directories); + function trimPrefixAndSuffix(path) { + var inner = withoutStartAndEnd(ts.normalizePath(path), completePrefix, normalizedSuffix); + return inner === undefined ? undefined : removeLeadingDirectorySeparator(inner); + } + } + function withoutStartAndEnd(s, start, end) { + return ts.startsWith(s, start) && ts.endsWith(s, end) ? s.slice(start.length, s.length - end.length) : undefined; + } + function removeLeadingDirectorySeparator(path) { + return path[0] === ts.directorySeparator ? path.slice(1) : path; + } + function getAmbientModuleCompletions(fragment, fragmentDirectory, checker) { + // Get modules that the type checker picked up + var ambientModules = checker.getAmbientModules().map(function (sym) { return ts.stripQuotes(sym.name); }); + var nonRelativeModuleNames = ambientModules.filter(function (moduleName) { return ts.startsWith(moduleName, fragment); }); + // Nested modules of the form "module-name/sub" need to be adjusted to only return the string + // after the last '/' that appears in the fragment because that's where the replacement span + // starts + if (fragmentDirectory !== undefined) { + var moduleNameWithSeparator_1 = ts.ensureTrailingDirectorySeparator(fragmentDirectory); + return nonRelativeModuleNames.map(function (nonRelativeModuleName) { return ts.removePrefix(nonRelativeModuleName, moduleNameWithSeparator_1); }); + } + return nonRelativeModuleNames; + } + function getTripleSlashReferenceCompletion(sourceFile, position, compilerOptions, host) { + var token = ts.getTokenAtPosition(sourceFile, position); + var commentRanges = ts.getLeadingCommentRanges(sourceFile.text, token.pos); + var range = commentRanges && ts.find(commentRanges, function (commentRange) { return position >= commentRange.pos && position <= commentRange.end; }); + if (!range) { + return undefined; + } + var text = sourceFile.text.slice(range.pos, position); + var match = tripleSlashDirectiveFragmentRegex.exec(text); + if (!match) { + return undefined; + } + var prefix = match[1], kind = match[2], toComplete = match[3]; + var scriptPath = ts.getDirectoryPath(sourceFile.path); + var names = kind === "path" ? getCompletionEntriesForDirectoryFragment(toComplete, scriptPath, getExtensionOptions(compilerOptions, /*includeExtensions*/ true), host, sourceFile.path) + : kind === "types" ? getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, getFragmentDirectory(toComplete), getExtensionOptions(compilerOptions)) + : ts.Debug.fail(); + return addReplacementSpans(toComplete, range.pos + prefix.length, names); + } + function getCompletionEntriesFromTypings(host, options, scriptPath, fragmentDirectory, extensionOptions, result) { + if (result === void 0) { result = []; } + // Check for typings specified in compiler options + var seen = ts.createMap(); + var typeRoots = tryAndIgnoreErrors(function () { return ts.getEffectiveTypeRoots(options, host); }) || ts.emptyArray; + for (var _i = 0, typeRoots_2 = typeRoots; _i < typeRoots_2.length; _i++) { + var root = typeRoots_2[_i]; + getCompletionEntriesFromDirectories(root); + } + // Also get all @types typings installed in visible node_modules directories + for (var _a = 0, _b = findPackageJsons(scriptPath, host); _a < _b.length; _a++) { + var packageJson = _b[_a]; + var typesDir = ts.combinePaths(ts.getDirectoryPath(packageJson), "node_modules/@types"); + getCompletionEntriesFromDirectories(typesDir); + } + return result; + function getCompletionEntriesFromDirectories(directory) { + if (!tryDirectoryExists(host, directory)) + return; + for (var _i = 0, _a = tryGetDirectories(host, directory); _i < _a.length; _i++) { + var typeDirectoryName = _a[_i]; + var packageName = ts.unmangleScopedPackageName(typeDirectoryName); + if (options.types && !ts.contains(options.types, packageName)) + continue; + if (fragmentDirectory === undefined) { + if (!seen.has(packageName)) { + result.push(nameAndKind(packageName, "external module name" /* externalModuleName */, /*extension*/ undefined)); + seen.set(packageName, true); + } + } + else { + var baseDirectory = ts.combinePaths(directory, typeDirectoryName); + var remainingFragment = ts.tryRemoveDirectoryPrefix(fragmentDirectory, packageName, ts.hostGetCanonicalFileName(host)); + if (remainingFragment !== undefined) { + getCompletionEntriesForDirectoryFragment(remainingFragment, baseDirectory, extensionOptions, host, /*exclude*/ undefined, result); + } + } + } + } + } + function findPackageJsons(directory, host) { + var paths = []; + ts.forEachAncestorDirectory(directory, function (ancestor) { + var currentConfigPath = ts.findConfigFile(ancestor, function (f) { return tryFileExists(host, f); }, "package.json"); + if (!currentConfigPath) { + return true; // break out + } + paths.push(currentConfigPath); + }); + return paths; + } + function findPackageJson(directory, host) { + var packageJson; + ts.forEachAncestorDirectory(directory, function (ancestor) { + if (ancestor === "node_modules") + return true; + packageJson = ts.findConfigFile(ancestor, function (f) { return tryFileExists(host, f); }, "package.json"); + if (packageJson) { + return true; // break out + } + }); + return packageJson; + } + function enumerateNodeModulesVisibleToScript(host, scriptPath) { + if (!host.readFile || !host.fileExists) + return ts.emptyArray; + var result = []; + for (var _i = 0, _a = findPackageJsons(scriptPath, host); _i < _a.length; _i++) { + var packageJson = _a[_i]; + var contents = ts.readJson(packageJson, host); // Cast to assert that readFile is defined + // Provide completions for all non @types dependencies + for (var _b = 0, nodeModulesDependencyKeys_1 = nodeModulesDependencyKeys; _b < nodeModulesDependencyKeys_1.length; _b++) { + var key = nodeModulesDependencyKeys_1[_b]; + var dependencies = contents[key]; + if (!dependencies) + continue; + for (var dep in dependencies) { + if (dependencies.hasOwnProperty(dep) && !ts.startsWith(dep, "@types/")) { + result.push(dep); + } + } + } + } + return result; + } + // Replace everything after the last directory separator that appears + function getDirectoryFragmentTextSpan(text, textStart) { + var index = Math.max(text.lastIndexOf(ts.directorySeparator), text.lastIndexOf("\\")); + var offset = index !== -1 ? index + 1 : 0; + // If the range is an identifier, span is unnecessary. + var length = text.length - offset; + return length === 0 || ts.isIdentifierText(text.substr(offset, length), 6 /* ESNext */) ? undefined : ts.createTextSpan(textStart + offset, length); + } + // Returns true if the path is explicitly relative to the script (i.e. relative to . or ..) + function isPathRelativeToScript(path) { + if (path && path.length >= 2 && path.charCodeAt(0) === 46 /* dot */) { + var slashIndex = path.length >= 3 && path.charCodeAt(1) === 46 /* dot */ ? 2 : 1; + var slashCharCode = path.charCodeAt(slashIndex); + return slashCharCode === 47 /* slash */ || slashCharCode === 92 /* backslash */; + } + return false; + } + /** + * Matches a triple slash reference directive with an incomplete string literal for its path. Used + * to determine if the caret is currently within the string literal and capture the literal fragment + * for completions. + * For example, this matches + * + * /// " with type any + // And at `
      ` (with a closing `>`), the completion list will contain "div". + var tagName = location.parent.parent.openingElement.tagName; + var hasClosingAngleBracket = !!ts.findChildOfKind(location.parent, 30 /* GreaterThanToken */, sourceFile); + var entry = { + name: tagName.getFullText(sourceFile) + (hasClosingAngleBracket ? "" : ">"), + kind: "class" /* classElement */, + kindModifiers: undefined, + sortText: "0", + }; + return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: false, entries: [entry] }; + } + var entries = []; + if (isUncheckedFile(sourceFile, compilerOptions)) { + var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, preferences, propertyAccessToConvert, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap); + getJSCompletionEntries(sourceFile, location.pos, uniqueNames, compilerOptions.target, entries); // TODO: GH#18217 + } + else { + if ((!symbols || symbols.length === 0) && keywordFilters === 0 /* None */) { + return undefined; + } + getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, preferences, propertyAccessToConvert, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap); + } + if (keywordFilters !== 0 /* None */) { + var entryNames = ts.arrayToSet(entries, function (e) { return e.name; }); + for (var _i = 0, _a = getKeywordCompletions(keywordFilters); _i < _a.length; _i++) { + var keywordEntry = _a[_i]; + if (!entryNames.has(keywordEntry.name)) { + entries.push(keywordEntry); + } + } + } + for (var _b = 0, literals_1 = literals; _b < literals_1.length; _b++) { + var literal = literals_1[_b]; + entries.push(createCompletionEntryForLiteral(literal)); + } + return { isGlobalCompletion: isInSnippetScope, isMemberCompletion: isMemberCompletionKind(completionKind), isNewIdentifierLocation: isNewIdentifierLocation, entries: entries }; + } + function isUncheckedFile(sourceFile, compilerOptions) { + return ts.isSourceFileJS(sourceFile) && !ts.isCheckJsEnabledForFile(sourceFile, compilerOptions); + } + function isMemberCompletionKind(kind) { + switch (kind) { + case 0 /* ObjectPropertyDeclaration */: + case 3 /* MemberLike */: + case 2 /* PropertyAccess */: + return true; + default: + return false; + } + } + function getJSCompletionEntries(sourceFile, position, uniqueNames, target, entries) { + ts.getNameTable(sourceFile).forEach(function (pos, name) { + // Skip identifiers produced only from the current location + if (pos === position) { + return; + } + var realName = ts.unescapeLeadingUnderscores(name); + if (ts.addToSeen(uniqueNames, realName) && ts.isIdentifierText(realName, target)) { + entries.push({ + name: realName, + kind: "warning" /* warning */, + kindModifiers: "", + sortText: "1" + }); + } + }); + } + var completionNameForLiteral = function (literal) { + return typeof literal === "object" ? ts.pseudoBigIntToString(literal) + "n" : JSON.stringify(literal); + }; + function createCompletionEntryForLiteral(literal) { + return { name: completionNameForLiteral(literal), kind: "string" /* string */, kindModifiers: "" /* none */, sortText: "0" }; + } + function createCompletionEntry(symbol, location, sourceFile, typeChecker, target, kind, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, preferences) { + var info = getCompletionEntryDisplayNameForSymbol(symbol, target, origin, kind); + if (!info) { + return undefined; + } + var name = info.name, needsConvertPropertyAccess = info.needsConvertPropertyAccess; + var insertText; + var replacementSpan; + if (origin && origin.kind === 0 /* ThisType */) { + insertText = needsConvertPropertyAccess ? "this[" + ts.quote(name, preferences) + "]" : "this." + name; + } + // We should only have needsConvertPropertyAccess if there's a property access to convert. But see #21790. + // Somehow there was a global with a non-identifier name. Hopefully someone will complain about getting a "foo bar" global completion and provide a repro. + else if ((origin && originIsSymbolMember(origin) || needsConvertPropertyAccess) && propertyAccessToConvert) { + insertText = needsConvertPropertyAccess ? "[" + ts.quote(name, preferences) + "]" : "[" + name + "]"; + var dot = ts.findChildOfKind(propertyAccessToConvert, 24 /* DotToken */, sourceFile); + // If the text after the '.' starts with this name, write over it. Else, add new text. + var end = ts.startsWith(name, propertyAccessToConvert.name.text) ? propertyAccessToConvert.name.end : dot.end; + replacementSpan = ts.createTextSpanFromBounds(dot.getStart(sourceFile), end); + } + if (isJsxInitializer) { + if (insertText === undefined) + insertText = name; + insertText = "{" + insertText + "}"; + if (typeof isJsxInitializer !== "boolean") { + replacementSpan = ts.createTextSpanFromNode(isJsxInitializer, sourceFile); + } + } + if (insertText !== undefined && !preferences.includeCompletionsWithInsertText) { + return undefined; + } + // TODO(drosen): Right now we just permit *all* semantic meanings when calling + // 'getSymbolKind' which is permissible given that it is backwards compatible; but + // really we should consider passing the meaning for the node so that we don't report + // that a suggestion for a value is an interface. We COULD also just do what + // 'getSymbolModifiers' does, which is to use the first declaration. + // Use a 'sortText' of 0' so that all symbol completion entries come before any other + // entries (like JavaScript identifier entries). + return { + name: name, + kind: ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, location), + kindModifiers: ts.SymbolDisplay.getSymbolModifiers(symbol), + sortText: "0", + source: getSourceFromOrigin(origin), + hasAction: trueOrUndefined(!!origin && originIsExport(origin)), + isRecommended: trueOrUndefined(isRecommendedCompletionMatch(symbol, recommendedCompletion, typeChecker)), + insertText: insertText, + replacementSpan: replacementSpan, + }; + } + function isRecommendedCompletionMatch(localSymbol, recommendedCompletion, checker) { + return localSymbol === recommendedCompletion || + !!(localSymbol.flags & 1048576 /* ExportValue */) && checker.getExportSymbolOfSymbol(localSymbol) === recommendedCompletion; + } + function trueOrUndefined(b) { + return b ? true : undefined; + } + function getSourceFromOrigin(origin) { + return origin && originIsExport(origin) ? ts.stripQuotes(origin.moduleSymbol.name) : undefined; + } + function getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, target, log, kind, preferences, propertyAccessToConvert, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap) { + var start = ts.timestamp(); + // Tracks unique names. + // We don't set this for global variables or completions from external module exports, because we can have multiple of those. + // Based on the order we add things we will always see locals first, then globals, then module exports. + // So adding a completion for a local will prevent us from adding completions for external module exports sharing the same name. + var uniques = ts.createMap(); + for (var _i = 0, symbols_3 = symbols; _i < symbols_3.length; _i++) { + var symbol = symbols_3[_i]; + var origin = symbolToOriginInfoMap ? symbolToOriginInfoMap[ts.getSymbolId(symbol)] : undefined; + var entry = createCompletionEntry(symbol, location, sourceFile, typeChecker, target, kind, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, preferences); + if (!entry) { + continue; + } + var name = entry.name; + if (uniques.has(name)) { + continue; + } + // Latter case tests whether this is a global variable. + if (!origin && !(symbol.parent === undefined && !ts.some(symbol.declarations, function (d) { return d.getSourceFile() === location.getSourceFile(); }))) { // TODO: GH#18217 + uniques.set(name, true); + } + entries.push(entry); + } + log("getCompletionsAtPosition: getCompletionEntriesFromSymbols: " + (ts.timestamp() - start)); + return uniques; + } + Completions.getCompletionEntriesFromSymbols = getCompletionEntriesFromSymbols; + function getLabelCompletionAtPosition(node) { + var entries = getLabelStatementCompletions(node); + if (entries.length) { + return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries }; + } + } + function getLabelStatementCompletions(node) { + var entries = []; + var uniques = ts.createMap(); + var current = node; + while (current) { + if (ts.isFunctionLike(current)) { + break; + } + if (ts.isLabeledStatement(current)) { + var name = current.label.text; + if (!uniques.has(name)) { + uniques.set(name, true); + entries.push({ + name: name, + kindModifiers: "" /* none */, + kind: "label" /* label */, + sortText: "0" + }); + } + } + current = current.parent; + } + return entries; + } + function getSymbolCompletionFromEntryId(program, log, sourceFile, position, entryId) { + var compilerOptions = program.getCompilerOptions(); + var completionData = getCompletionData(program, log, sourceFile, isUncheckedFile(sourceFile, compilerOptions), position, { includeCompletionsForModuleExports: true, includeCompletionsWithInsertText: true }, entryId); + if (!completionData) { + return { type: "none" }; + } + if (completionData.kind !== 0 /* Data */) { + return { type: "request", request: completionData }; + } + var symbols = completionData.symbols, literals = completionData.literals, location = completionData.location, completionKind = completionData.completionKind, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap, previousToken = completionData.previousToken, isJsxInitializer = completionData.isJsxInitializer; + var literal = ts.find(literals, function (l) { return completionNameForLiteral(l) === entryId.name; }); + if (literal !== undefined) + return { type: "literal", literal: literal }; + // Find the symbol with the matching entry name. + // We don't need to perform character checks here because we're only comparing the + // name against 'entryName' (which is known to be good), not building a new + // completion entry. + return ts.firstDefined(symbols, function (symbol) { + var origin = symbolToOriginInfoMap[ts.getSymbolId(symbol)]; + var info = getCompletionEntryDisplayNameForSymbol(symbol, compilerOptions.target, origin, completionKind); + return info && info.name === entryId.name && getSourceFromOrigin(origin) === entryId.source + ? { type: "symbol", symbol: symbol, location: location, symbolToOriginInfoMap: symbolToOriginInfoMap, previousToken: previousToken, isJsxInitializer: isJsxInitializer } + : undefined; + }) || { type: "none" }; + } + function getSymbolName(symbol, origin, target) { + return origin && originIsExport(origin) && origin.isDefaultExport && symbol.escapedName === "default" /* Default */ + // Name of "export default foo;" is "foo". Name of "export default 0" is the filename converted to camelCase. + ? ts.firstDefined(symbol.declarations, function (d) { return ts.isExportAssignment(d) && ts.isIdentifier(d.expression) ? d.expression.text : undefined; }) + || ts.codefix.moduleSymbolToValidIdentifier(origin.moduleSymbol, target) + : symbol.name; + } + function getCompletionEntryDetails(program, log, sourceFile, position, entryId, host, formatContext, preferences, cancellationToken) { + var typeChecker = program.getTypeChecker(); + var compilerOptions = program.getCompilerOptions(); + var name = entryId.name; + var contextToken = ts.findPrecedingToken(position, sourceFile); + if (ts.isInString(sourceFile, position, contextToken)) { + return Completions.StringCompletions.getStringLiteralCompletionDetails(name, sourceFile, position, contextToken, typeChecker, compilerOptions, host, cancellationToken); + } + // Compute all the completion symbols again. + var symbolCompletion = getSymbolCompletionFromEntryId(program, log, sourceFile, position, entryId); + switch (symbolCompletion.type) { + case "request": { + var request = symbolCompletion.request; + switch (request.kind) { + case 1 /* JsDocTagName */: + return ts.JsDoc.getJSDocTagNameCompletionDetails(name); + case 2 /* JsDocTag */: + return ts.JsDoc.getJSDocTagCompletionDetails(name); + case 3 /* JsDocParameterName */: + return ts.JsDoc.getJSDocParameterNameCompletionDetails(name); + default: + return ts.Debug.assertNever(request); + } + } + case "symbol": { + var symbol = symbolCompletion.symbol, location = symbolCompletion.location, symbolToOriginInfoMap = symbolCompletion.symbolToOriginInfoMap, previousToken = symbolCompletion.previousToken; + var _a = getCompletionEntryCodeActionsAndSourceDisplay(symbolToOriginInfoMap, symbol, program, typeChecker, host, compilerOptions, sourceFile, position, previousToken, formatContext, preferences), codeActions = _a.codeActions, sourceDisplay = _a.sourceDisplay; + return createCompletionDetailsForSymbol(symbol, typeChecker, sourceFile, location, cancellationToken, codeActions, sourceDisplay); // TODO: GH#18217 + } + case "literal": { + var literal = symbolCompletion.literal; + return createSimpleDetails(completionNameForLiteral(literal), "string" /* string */, typeof literal === "string" ? ts.SymbolDisplayPartKind.stringLiteral : ts.SymbolDisplayPartKind.numericLiteral); + } + case "none": + // Didn't find a symbol with this name. See if we can find a keyword instead. + return allKeywordsCompletions().some(function (c) { return c.name === name; }) ? createSimpleDetails(name, "keyword" /* keyword */, ts.SymbolDisplayPartKind.keyword) : undefined; + default: + ts.Debug.assertNever(symbolCompletion); + } + } + Completions.getCompletionEntryDetails = getCompletionEntryDetails; + function createSimpleDetails(name, kind, kind2) { + return createCompletionDetails(name, "" /* none */, kind, [ts.displayPart(name, kind2)]); + } + function createCompletionDetailsForSymbol(symbol, checker, sourceFile, location, cancellationToken, codeActions, sourceDisplay) { + var _a = checker.runWithCancellationToken(cancellationToken, function (checker) { + return ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, sourceFile, location, location, 7 /* All */); + }), displayParts = _a.displayParts, documentation = _a.documentation, symbolKind = _a.symbolKind, tags = _a.tags; + return createCompletionDetails(symbol.name, ts.SymbolDisplay.getSymbolModifiers(symbol), symbolKind, displayParts, documentation, tags, codeActions, sourceDisplay); + } + Completions.createCompletionDetailsForSymbol = createCompletionDetailsForSymbol; + function createCompletionDetails(name, kindModifiers, kind, displayParts, documentation, tags, codeActions, source) { + return { name: name, kindModifiers: kindModifiers, kind: kind, displayParts: displayParts, documentation: documentation, tags: tags, codeActions: codeActions, source: source }; + } + Completions.createCompletionDetails = createCompletionDetails; + function getCompletionEntryCodeActionsAndSourceDisplay(symbolToOriginInfoMap, symbol, program, checker, host, compilerOptions, sourceFile, position, previousToken, formatContext, preferences) { + var symbolOriginInfo = symbolToOriginInfoMap[ts.getSymbolId(symbol)]; + if (!symbolOriginInfo || !originIsExport(symbolOriginInfo)) { + return { codeActions: undefined, sourceDisplay: undefined }; + } + var moduleSymbol = symbolOriginInfo.moduleSymbol; + var exportedSymbol = checker.getMergedSymbol(ts.skipAlias(symbol.exportSymbol || symbol, checker)); + var _a = ts.codefix.getImportCompletionAction(exportedSymbol, moduleSymbol, sourceFile, getSymbolName(symbol, symbolOriginInfo, compilerOptions.target), host, program, formatContext, previousToken && ts.isIdentifier(previousToken) ? previousToken.getStart(sourceFile) : position, preferences), moduleSpecifier = _a.moduleSpecifier, codeAction = _a.codeAction; + return { sourceDisplay: [ts.textPart(moduleSpecifier)], codeActions: [codeAction] }; + } + function getCompletionEntrySymbol(program, log, sourceFile, position, entryId) { + var completion = getSymbolCompletionFromEntryId(program, log, sourceFile, position, entryId); + return completion.type === "symbol" ? completion.symbol : undefined; + } + Completions.getCompletionEntrySymbol = getCompletionEntrySymbol; + var CompletionDataKind; + (function (CompletionDataKind) { + CompletionDataKind[CompletionDataKind["Data"] = 0] = "Data"; + CompletionDataKind[CompletionDataKind["JsDocTagName"] = 1] = "JsDocTagName"; + CompletionDataKind[CompletionDataKind["JsDocTag"] = 2] = "JsDocTag"; + CompletionDataKind[CompletionDataKind["JsDocParameterName"] = 3] = "JsDocParameterName"; + })(CompletionDataKind || (CompletionDataKind = {})); + var CompletionKind; + (function (CompletionKind) { + CompletionKind[CompletionKind["ObjectPropertyDeclaration"] = 0] = "ObjectPropertyDeclaration"; + CompletionKind[CompletionKind["Global"] = 1] = "Global"; + CompletionKind[CompletionKind["PropertyAccess"] = 2] = "PropertyAccess"; + CompletionKind[CompletionKind["MemberLike"] = 3] = "MemberLike"; + CompletionKind[CompletionKind["String"] = 4] = "String"; + CompletionKind[CompletionKind["None"] = 5] = "None"; + })(CompletionKind = Completions.CompletionKind || (Completions.CompletionKind = {})); + function getRecommendedCompletion(previousToken, contextualType, checker) { + // For a union, return the first one with a recommended completion. + return ts.firstDefined(contextualType && (contextualType.isUnion() ? contextualType.types : [contextualType]), function (type) { + var symbol = type && type.symbol; + // Don't include make a recommended completion for an abstract class + return symbol && (symbol.flags & (8 /* EnumMember */ | 384 /* Enum */ | 32 /* Class */) && !ts.isAbstractConstructorSymbol(symbol)) + ? getFirstSymbolInChain(symbol, previousToken, checker) + : undefined; + }); + } + function getContextualType(previousToken, position, sourceFile, checker) { + var parent = previousToken.parent; + switch (previousToken.kind) { + case 72 /* Identifier */: + return ts.getContextualTypeFromParent(previousToken, checker); + case 59 /* EqualsToken */: + switch (parent.kind) { + case 237 /* VariableDeclaration */: + return checker.getContextualType(parent.initializer); // TODO: GH#18217 + case 204 /* BinaryExpression */: + return checker.getTypeAtLocation(parent.left); + case 267 /* JsxAttribute */: + return checker.getContextualTypeForJsxAttribute(parent); + default: + return undefined; + } + case 95 /* NewKeyword */: + return checker.getContextualType(parent); + case 74 /* CaseKeyword */: + return ts.getSwitchedType(ts.cast(parent, ts.isCaseClause), checker); + case 18 /* OpenBraceToken */: + return ts.isJsxExpression(parent) && parent.parent.kind !== 260 /* JsxElement */ ? checker.getContextualTypeForJsxAttribute(parent.parent) : undefined; + default: + var argInfo = ts.SignatureHelp.getArgumentInfoForCompletions(previousToken, position, sourceFile); + return argInfo + // At `,`, treat this as the next argument after the comma. + ? checker.getContextualTypeForArgumentAtIndex(argInfo.invocation, argInfo.argumentIndex + (previousToken.kind === 27 /* CommaToken */ ? 1 : 0)) + : ts.isEqualityOperatorKind(previousToken.kind) && ts.isBinaryExpression(parent) && ts.isEqualityOperatorKind(parent.operatorToken.kind) + // completion at `x ===/**/` should be for the right side + ? checker.getTypeAtLocation(parent.left) + : checker.getContextualType(previousToken); + } + } + function getFirstSymbolInChain(symbol, enclosingDeclaration, checker) { + var chain = checker.getAccessibleSymbolChain(symbol, enclosingDeclaration, /*meaning*/ 67108863 /* All */, /*useOnlyExternalAliasing*/ false); + if (chain) + return ts.first(chain); + return symbol.parent && (isModuleSymbol(symbol.parent) ? symbol : getFirstSymbolInChain(symbol.parent, enclosingDeclaration, checker)); + } + function isModuleSymbol(symbol) { + return symbol.declarations.some(function (d) { return d.kind === 279 /* SourceFile */; }); + } + function getCompletionData(program, log, sourceFile, isUncheckedFile, position, preferences, detailsEntryId) { + var typeChecker = program.getTypeChecker(); + var start = ts.timestamp(); + var currentToken = ts.getTokenAtPosition(sourceFile, position); // TODO: GH#15853 + // We will check for jsdoc comments with insideComment and getJsDocTagAtPosition. (TODO: that seems rather inefficient to check the same thing so many times.) + log("getCompletionData: Get current token: " + (ts.timestamp() - start)); + start = ts.timestamp(); + var insideComment = ts.isInComment(sourceFile, position, currentToken); + log("getCompletionData: Is inside comment: " + (ts.timestamp() - start)); + var insideJsDocTagTypeExpression = false; + var isInSnippetScope = false; + if (insideComment) { + if (ts.hasDocComment(sourceFile, position)) { + if (sourceFile.text.charCodeAt(position - 1) === 64 /* at */) { + // The current position is next to the '@' sign, when no tag name being provided yet. + // Provide a full list of tag names + return { kind: 1 /* JsDocTagName */ }; + } + else { + // When completion is requested without "@", we will have check to make sure that + // there are no comments prefix the request position. We will only allow "*" and space. + // e.g + // /** |c| /* + // + // /** + // |c| + // */ + // + // /** + // * |c| + // */ + // + // /** + // * |c| + // */ + var lineStart = ts.getLineStartPositionForPosition(position, sourceFile); + if (!(sourceFile.text.substring(lineStart, position).match(/[^\*|\s|(/\*\*)]/))) { + return { kind: 2 /* JsDocTag */ }; + } + } + } + // Completion should work inside certain JsDoc tags. For example: + // /** @type {number | string} */ + // Completion should work in the brackets + var tag = getJsDocTagAtPosition(currentToken, position); + if (tag) { + if (tag.tagName.pos <= position && position <= tag.tagName.end) { + return { kind: 1 /* JsDocTagName */ }; + } + if (isTagWithTypeExpression(tag) && tag.typeExpression && tag.typeExpression.kind === 283 /* JSDocTypeExpression */) { + currentToken = ts.getTokenAtPosition(sourceFile, position); + if (!currentToken || + (!ts.isDeclarationName(currentToken) && + (currentToken.parent.kind !== 305 /* JSDocPropertyTag */ || + currentToken.parent.name !== currentToken))) { + // Use as type location if inside tag's type expression + insideJsDocTagTypeExpression = isCurrentlyEditingNode(tag.typeExpression); + } + } + if (ts.isJSDocParameterTag(tag) && (ts.nodeIsMissing(tag.name) || tag.name.pos <= position && position <= tag.name.end)) { + return { kind: 3 /* JsDocParameterName */, tag: tag }; + } + } + if (!insideJsDocTagTypeExpression) { + // Proceed if the current position is in jsDoc tag expression; otherwise it is a normal + // comment or the plain text part of a jsDoc comment, so no completion should be available + log("Returning an empty list because completion was inside a regular comment or plain text part of a JsDoc comment."); + return undefined; + } + } + start = ts.timestamp(); + var previousToken = ts.findPrecedingToken(position, sourceFile, /*startNode*/ undefined); // TODO: GH#18217 + log("getCompletionData: Get previous token 1: " + (ts.timestamp() - start)); + // The decision to provide completion depends on the contextToken, which is determined through the previousToken. + // Note: 'previousToken' (and thus 'contextToken') can be undefined if we are the beginning of the file + var contextToken = previousToken; + // Check if the caret is at the end of an identifier; this is a partial identifier that we want to complete: e.g. a.toS| + // Skip this partial identifier and adjust the contextToken to the token that precedes it. + if (contextToken && position <= contextToken.end && (ts.isIdentifier(contextToken) || ts.isKeyword(contextToken.kind))) { + var start_3 = ts.timestamp(); + contextToken = ts.findPrecedingToken(contextToken.getFullStart(), sourceFile, /*startNode*/ undefined); // TODO: GH#18217 + log("getCompletionData: Get previous token 2: " + (ts.timestamp() - start_3)); + } + // Find the node where completion is requested on. + // Also determine whether we are trying to complete with members of that node + // or attributes of a JSX tag. + var node = currentToken; + var propertyAccessToConvert; + var isRightOfDot = false; + var isRightOfOpenTag = false; + var isStartingCloseTag = false; + var isJsxInitializer = false; + var location = ts.getTouchingPropertyName(sourceFile, position); + if (contextToken) { + // Bail out if this is a known invalid completion location + if (isCompletionListBlocker(contextToken)) { + log("Returning an empty list because completion was requested in an invalid position."); + return undefined; + } + var parent = contextToken.parent; + if (contextToken.kind === 24 /* DotToken */) { + isRightOfDot = true; + switch (parent.kind) { + case 189 /* PropertyAccessExpression */: + propertyAccessToConvert = parent; + node = propertyAccessToConvert.expression; + break; + case 148 /* QualifiedName */: + node = parent.left; + break; + case 244 /* ModuleDeclaration */: + node = parent.name; + break; + case 183 /* ImportType */: + case 214 /* MetaProperty */: + node = parent; + break; + default: + // There is nothing that precedes the dot, so this likely just a stray character + // or leading into a '...' token. Just bail out instead. + return undefined; + } + } + else if (sourceFile.languageVariant === 1 /* JSX */) { + // + // If the tagname is a property access expression, we will then walk up to the top most of property access expression. + // Then, try to get a JSX container and its associated attributes type. + if (parent && parent.kind === 189 /* PropertyAccessExpression */) { + contextToken = parent; + parent = parent.parent; + } + // Fix location + if (currentToken.parent === location) { + switch (currentToken.kind) { + case 30 /* GreaterThanToken */: + if (currentToken.parent.kind === 260 /* JsxElement */ || currentToken.parent.kind === 262 /* JsxOpeningElement */) { + location = currentToken; + } + break; + case 42 /* SlashToken */: + if (currentToken.parent.kind === 261 /* JsxSelfClosingElement */) { + location = currentToken; + } + break; + } + } + switch (parent.kind) { + case 263 /* JsxClosingElement */: + if (contextToken.kind === 42 /* SlashToken */) { + isStartingCloseTag = true; + location = contextToken; + } + break; + case 204 /* BinaryExpression */: + if (!binaryExpressionMayBeOpenTag(parent)) { + break; + } + // falls through + case 261 /* JsxSelfClosingElement */: + case 260 /* JsxElement */: + case 262 /* JsxOpeningElement */: + if (contextToken.kind === 28 /* LessThanToken */) { + isRightOfOpenTag = true; + location = contextToken; + } + break; + case 267 /* JsxAttribute */: + switch (previousToken.kind) { + case 59 /* EqualsToken */: + isJsxInitializer = true; + break; + case 72 /* Identifier */: + // For `
      ` we don't want to treat this as a jsx inializer, instead it's the attribute name. + if (parent !== previousToken.parent && + !parent.initializer && + ts.findChildOfKind(parent, 59 /* EqualsToken */, sourceFile)) { + isJsxInitializer = previousToken; + } + } + break; + } + } + } + var semanticStart = ts.timestamp(); + var completionKind = 5 /* None */; + var isNewIdentifierLocation = false; + var keywordFilters = 0 /* None */; + var symbols = []; + var symbolToOriginInfoMap = []; + if (isRightOfDot) { + getTypeScriptMemberSymbols(); + } + else if (isRightOfOpenTag) { + var tagSymbols = ts.Debug.assertEachDefined(typeChecker.getJsxIntrinsicTagNamesAt(location), "getJsxIntrinsicTagNames() should all be defined"); + tryGetGlobalSymbols(); + symbols = tagSymbols.concat(symbols); + completionKind = 3 /* MemberLike */; + keywordFilters = 0 /* None */; + } + else if (isStartingCloseTag) { + var tagName = contextToken.parent.parent.openingElement.tagName; + var tagSymbol = typeChecker.getSymbolAtLocation(tagName); + if (tagSymbol) { + symbols = [tagSymbol]; + } + completionKind = 3 /* MemberLike */; + keywordFilters = 0 /* None */; + } + else { + // For JavaScript or TypeScript, if we're not after a dot, then just try to get the + // global symbols in scope. These results should be valid for either language as + // the set of symbols that can be referenced from this location. + if (!tryGetGlobalSymbols()) { + return undefined; + } + } + log("getCompletionData: Semantic work: " + (ts.timestamp() - semanticStart)); + var contextualType = previousToken && getContextualType(previousToken, position, sourceFile, typeChecker); + var literals = ts.mapDefined(contextualType && (contextualType.isUnion() ? contextualType.types : [contextualType]), function (t) { return t.isLiteral() ? t.value : undefined; }); + var recommendedCompletion = previousToken && contextualType && getRecommendedCompletion(previousToken, contextualType, typeChecker); + return { kind: 0 /* Data */, symbols: symbols, completionKind: completionKind, isInSnippetScope: isInSnippetScope, propertyAccessToConvert: propertyAccessToConvert, isNewIdentifierLocation: isNewIdentifierLocation, location: location, keywordFilters: keywordFilters, literals: literals, symbolToOriginInfoMap: symbolToOriginInfoMap, recommendedCompletion: recommendedCompletion, previousToken: previousToken, isJsxInitializer: isJsxInitializer }; + function isTagWithTypeExpression(tag) { + switch (tag.kind) { + case 299 /* JSDocParameterTag */: + case 305 /* JSDocPropertyTag */: + case 300 /* JSDocReturnTag */: + case 302 /* JSDocTypeTag */: + case 304 /* JSDocTypedefTag */: + return true; + default: + return false; + } + } + function getTypeScriptMemberSymbols() { + // Right of dot member completion list + completionKind = 2 /* PropertyAccess */; + // Since this is qualified name check its a type node location + var isImportType = ts.isLiteralImportTypeNode(node); + var isTypeLocation = insideJsDocTagTypeExpression || (isImportType && !node.isTypeOf) || ts.isPartOfTypeNode(node.parent); + var isRhsOfImportDeclaration = ts.isInRightSideOfInternalImportEqualsDeclaration(node); + var allowTypeOrValue = isRhsOfImportDeclaration || (!isTypeLocation && ts.isPossiblyTypeArgumentPosition(contextToken, sourceFile, typeChecker)); + if (ts.isEntityName(node) || isImportType) { + var isNamespaceName = ts.isModuleDeclaration(node.parent); + if (isNamespaceName) + isNewIdentifierLocation = true; + var symbol = typeChecker.getSymbolAtLocation(node); + if (symbol) { + symbol = ts.skipAlias(symbol, typeChecker); + if (symbol.flags & (1536 /* Module */ | 384 /* Enum */)) { + // Extract module or enum members + var exportedSymbols = ts.Debug.assertEachDefined(typeChecker.getExportsOfModule(symbol), "getExportsOfModule() should all be defined"); + var isValidValueAccess_1 = function (symbol) { return typeChecker.isValidPropertyAccess(isImportType ? node : (node.parent), symbol.name); }; + var isValidTypeAccess_1 = function (symbol) { return symbolCanBeReferencedAtTypeLocation(symbol); }; + var isValidAccess = isNamespaceName + // At `namespace N.M/**/`, if this is the only declaration of `M`, don't include `M` as a completion. + ? function (symbol) { return !!(symbol.flags & 1920 /* Namespace */) && !symbol.declarations.every(function (d) { return d.parent === node.parent; }); } + : allowTypeOrValue ? + // Any kind is allowed when dotting off namespace in internal import equals declaration + function (symbol) { return isValidTypeAccess_1(symbol) || isValidValueAccess_1(symbol); } : + isTypeLocation ? isValidTypeAccess_1 : isValidValueAccess_1; + for (var _i = 0, exportedSymbols_1 = exportedSymbols; _i < exportedSymbols_1.length; _i++) { + var exportedSymbol = exportedSymbols_1[_i]; + if (isValidAccess(exportedSymbol)) { + symbols.push(exportedSymbol); + } + } + // If the module is merged with a value, we must get the type of the class and add its propertes (for inherited static methods). + if (!isTypeLocation && symbol.declarations.some(function (d) { return d.kind !== 279 /* SourceFile */ && d.kind !== 244 /* ModuleDeclaration */ && d.kind !== 243 /* EnumDeclaration */; })) { + addTypeProperties(typeChecker.getTypeOfSymbolAtLocation(symbol, node)); + } + return; + } + } + } + if (ts.isMetaProperty(node) && (node.keywordToken === 95 /* NewKeyword */ || node.keywordToken === 92 /* ImportKeyword */)) { + var completion = (node.keywordToken === 95 /* NewKeyword */) ? "target" : "meta"; + symbols.push(typeChecker.createSymbol(4 /* Property */, ts.escapeLeadingUnderscores(completion))); + return; + } + if (!isTypeLocation) { + addTypeProperties(typeChecker.getTypeAtLocation(node)); + } + } + function addTypeProperties(type) { + isNewIdentifierLocation = !!type.getStringIndexType(); + if (isUncheckedFile) { + // In javascript files, for union types, we don't just get the members that + // the individual types have in common, we also include all the members that + // each individual type has. This is because we're going to add all identifiers + // anyways. So we might as well elevate the members that were at least part + // of the individual types to a higher status since we know what they are. + symbols.push.apply(symbols, getPropertiesForCompletion(type, typeChecker)); + } + else { + for (var _i = 0, _a = type.getApparentProperties(); _i < _a.length; _i++) { + var symbol = _a[_i]; + if (typeChecker.isValidPropertyAccessForCompletions(node.kind === 183 /* ImportType */ ? node : node.parent, type, symbol)) { + addPropertySymbol(symbol); + } + } + } + } + function addPropertySymbol(symbol) { + // For a computed property with an accessible name like `Symbol.iterator`, + // we'll add a completion for the *name* `Symbol` instead of for the property. + // If this is e.g. [Symbol.iterator], add a completion for `Symbol`. + var computedPropertyName = ts.firstDefined(symbol.declarations, function (decl) { return ts.tryCast(ts.getNameOfDeclaration(decl), ts.isComputedPropertyName); }); + if (computedPropertyName) { + var leftMostName = getLeftMostName(computedPropertyName.expression); // The completion is for `Symbol`, not `iterator`. + var nameSymbol = leftMostName && typeChecker.getSymbolAtLocation(leftMostName); + // If this is nested like for `namespace N { export const sym = Symbol(); }`, we'll add the completion for `N`. + var firstAccessibleSymbol = nameSymbol && getFirstSymbolInChain(nameSymbol, contextToken, typeChecker); + if (firstAccessibleSymbol && !symbolToOriginInfoMap[ts.getSymbolId(firstAccessibleSymbol)]) { + symbols.push(firstAccessibleSymbol); + var moduleSymbol = firstAccessibleSymbol.parent; + symbolToOriginInfoMap[ts.getSymbolId(firstAccessibleSymbol)] = + !moduleSymbol || !ts.isExternalModuleSymbol(moduleSymbol) ? { kind: 1 /* SymbolMemberNoExport */ } : { kind: 2 /* SymbolMemberExport */, moduleSymbol: moduleSymbol, isDefaultExport: false }; + } + } + else { + symbols.push(symbol); + } + } + /** Given 'a.b.c', returns 'a'. */ + function getLeftMostName(e) { + return ts.isIdentifier(e) ? e : ts.isPropertyAccessExpression(e) ? getLeftMostName(e.expression) : undefined; + } + function tryGetGlobalSymbols() { + var result = tryGetObjectLikeCompletionSymbols() + || tryGetImportOrExportClauseCompletionSymbols() + || tryGetConstructorCompletion() + || tryGetClassLikeCompletionSymbols() + || tryGetJsxCompletionSymbols() + || (getGlobalCompletions(), 1 /* Success */); + return result === 1 /* Success */; + } + function tryGetConstructorCompletion() { + if (!tryGetConstructorLikeCompletionContainer(contextToken)) + return 0 /* Continue */; + // no members, only keywords + completionKind = 5 /* None */; + // Declaring new property/method/accessor + isNewIdentifierLocation = true; + // Has keywords for constructor parameter + keywordFilters = 4 /* ConstructorParameterKeywords */; + return 1 /* Success */; + } + function tryGetJsxCompletionSymbols() { + var jsxContainer = tryGetContainingJsxElement(contextToken); + // Cursor is inside a JSX self-closing element or opening element + var attrsType = jsxContainer && typeChecker.getContextualType(jsxContainer.attributes); + if (!attrsType) + return 0 /* Continue */; + symbols = filterJsxAttributes(getPropertiesForObjectExpression(attrsType, jsxContainer.attributes, typeChecker), jsxContainer.attributes.properties); + completionKind = 3 /* MemberLike */; + isNewIdentifierLocation = false; + return 1 /* Success */; + } + function getGlobalCompletions() { + keywordFilters = tryGetFunctionLikeBodyCompletionContainer(contextToken) ? 5 /* FunctionLikeBodyKeywords */ : 1 /* All */; + // Get all entities in the current scope. + completionKind = 1 /* Global */; + isNewIdentifierLocation = isNewIdentifierDefinitionLocation(contextToken); + if (previousToken !== contextToken) { + ts.Debug.assert(!!previousToken, "Expected 'contextToken' to be defined when different from 'previousToken'."); + } + // We need to find the node that will give us an appropriate scope to begin + // aggregating completion candidates. This is achieved in 'getScopeNode' + // by finding the first node that encompasses a position, accounting for whether a node + // is "complete" to decide whether a position belongs to the node. + // + // However, at the end of an identifier, we are interested in the scope of the identifier + // itself, but fall outside of the identifier. For instance: + // + // xyz => x$ + // + // the cursor is outside of both the 'x' and the arrow function 'xyz => x', + // so 'xyz' is not returned in our results. + // + // We define 'adjustedPosition' so that we may appropriately account for + // being at the end of an identifier. The intention is that if requesting completion + // at the end of an identifier, it should be effectively equivalent to requesting completion + // anywhere inside/at the beginning of the identifier. So in the previous case, the + // 'adjustedPosition' will work as if requesting completion in the following: + // + // xyz => $x + // + // If previousToken !== contextToken, then + // - 'contextToken' was adjusted to the token prior to 'previousToken' + // because we were at the end of an identifier. + // - 'previousToken' is defined. + var adjustedPosition = previousToken !== contextToken ? + previousToken.getStart() : + position; + var scopeNode = getScopeNode(contextToken, adjustedPosition, sourceFile) || sourceFile; + isInSnippetScope = isSnippetScope(scopeNode); + var isTypeOnly = isTypeOnlyCompletion(); + var symbolMeanings = (isTypeOnly ? 0 /* None */ : 67220415 /* Value */) | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */; + symbols = ts.Debug.assertEachDefined(typeChecker.getSymbolsInScope(scopeNode, symbolMeanings), "getSymbolsInScope() should all be defined"); + // Need to insert 'this.' before properties of `this` type, so only do that if `includeInsertTextCompletions` + if (preferences.includeCompletionsWithInsertText && scopeNode.kind !== 279 /* SourceFile */) { + var thisType = typeChecker.tryGetThisTypeAt(scopeNode); + if (thisType) { + for (var _i = 0, _a = getPropertiesForCompletion(thisType, typeChecker); _i < _a.length; _i++) { + var symbol = _a[_i]; + symbolToOriginInfoMap[ts.getSymbolId(symbol)] = { kind: 0 /* ThisType */ }; + symbols.push(symbol); + } + } + } + if (shouldOfferImportCompletions()) { + getSymbolsFromOtherSourceFileExports(symbols, previousToken && ts.isIdentifier(previousToken) ? previousToken.text : "", program.getCompilerOptions().target); + } + filterGlobalCompletion(symbols); + } + function shouldOfferImportCompletions() { + // If not already a module, must have modules enabled and not currently be in a commonjs module. (TODO: import completions for commonjs) + if (!preferences.includeCompletionsForModuleExports) + return false; + // If already using ES6 modules, OK to continue using them. + if (sourceFile.externalModuleIndicator) + return true; + // If already using commonjs, don't introduce ES6. + if (sourceFile.commonJsModuleIndicator) + return false; + // If module transpilation is enabled or we're targeting es6 or above, or not emitting, OK. + if (ts.compilerOptionsIndicateEs6Modules(program.getCompilerOptions())) + return true; + // If some file is using ES6 modules, assume that it's OK to add more. + return ts.programContainsEs6Modules(program); + } + function isSnippetScope(scopeNode) { + switch (scopeNode.kind) { + case 279 /* SourceFile */: + case 206 /* TemplateExpression */: + case 270 /* JsxExpression */: + case 218 /* Block */: + return true; + default: + return ts.isStatement(scopeNode); + } + } + function filterGlobalCompletion(symbols) { + var isTypeOnly = isTypeOnlyCompletion(); + var allowTypes = isTypeOnly || !isContextTokenValueLocation(contextToken) && ts.isPossiblyTypeArgumentPosition(contextToken, sourceFile, typeChecker); + if (isTypeOnly) + keywordFilters = 6 /* TypeKeywords */; + ts.filterMutate(symbols, function (symbol) { + if (!ts.isSourceFile(location)) { + // export = /**/ here we want to get all meanings, so any symbol is ok + if (ts.isExportAssignment(location.parent)) { + return true; + } + symbol = ts.skipAlias(symbol, typeChecker); + // import m = /**/ <-- It can only access namespace (if typing import = x. this would get member symbols and not namespace) + if (ts.isInRightSideOfInternalImportEqualsDeclaration(location)) { + return !!(symbol.flags & 1920 /* Namespace */); + } + if (allowTypes) { + // Its a type, but you can reach it by namespace.type as well + var symbolAllowedAsType = symbolCanBeReferencedAtTypeLocation(symbol); + if (symbolAllowedAsType || isTypeOnly) { + return symbolAllowedAsType; + } + } + } + // expressions are value space (which includes the value namespaces) + return !!(ts.getCombinedLocalAndExportSymbolFlags(symbol) & 67220415 /* Value */); + }); + } + function isTypeOnlyCompletion() { + return insideJsDocTagTypeExpression || !isContextTokenValueLocation(contextToken) && (ts.isPartOfTypeNode(location) || isContextTokenTypeLocation(contextToken)); + } + function isContextTokenValueLocation(contextToken) { + return contextToken && + contextToken.kind === 104 /* TypeOfKeyword */ && + (contextToken.parent.kind === 167 /* TypeQuery */ || ts.isTypeOfExpression(contextToken.parent)); + } + function isContextTokenTypeLocation(contextToken) { + if (contextToken) { + var parentKind = contextToken.parent.kind; + switch (contextToken.kind) { + case 57 /* ColonToken */: + return parentKind === 154 /* PropertyDeclaration */ || + parentKind === 153 /* PropertySignature */ || + parentKind === 151 /* Parameter */ || + parentKind === 237 /* VariableDeclaration */ || + ts.isFunctionLikeKind(parentKind); + case 59 /* EqualsToken */: + return parentKind === 242 /* TypeAliasDeclaration */; + case 119 /* AsKeyword */: + return parentKind === 212 /* AsExpression */; + } + } + return false; + } + /** True if symbol is a type or a module containing at least one type. */ + function symbolCanBeReferencedAtTypeLocation(symbol, seenModules) { + if (seenModules === void 0) { seenModules = ts.createMap(); } + var sym = ts.skipAlias(symbol.exportSymbol || symbol, typeChecker); + return !!(sym.flags & 67897832 /* Type */) || + !!(sym.flags & 1536 /* Module */) && + ts.addToSeen(seenModules, ts.getSymbolId(sym)) && + typeChecker.getExportsOfModule(sym).some(function (e) { return symbolCanBeReferencedAtTypeLocation(e, seenModules); }); + } + function getSymbolsFromOtherSourceFileExports(symbols, tokenText, target) { + var tokenTextLowerCase = tokenText.toLowerCase(); + var seenResolvedModules = ts.createMap(); + ts.codefix.forEachExternalModuleToImportFrom(typeChecker, sourceFile, program.getSourceFiles(), function (moduleSymbol) { + // Perf -- ignore other modules if this is a request for details + if (detailsEntryId && detailsEntryId.source && ts.stripQuotes(moduleSymbol.name) !== detailsEntryId.source) { + return; + } + var resolvedModuleSymbol = typeChecker.resolveExternalModuleSymbol(moduleSymbol); + // resolvedModuleSymbol may be a namespace. A namespace may be `export =` by multiple module declarations, but only keep the first one. + if (!ts.addToSeen(seenResolvedModules, ts.getSymbolId(resolvedModuleSymbol))) { + return; + } + if (resolvedModuleSymbol !== moduleSymbol && + // Don't add another completion for `export =` of a symbol that's already global. + // So in `declare namespace foo {} declare module "foo" { export = foo; }`, there will just be the global completion for `foo`. + ts.some(resolvedModuleSymbol.declarations, function (d) { return !!d.getSourceFile().externalModuleIndicator; })) { + symbols.push(resolvedModuleSymbol); + symbolToOriginInfoMap[ts.getSymbolId(resolvedModuleSymbol)] = { kind: 3 /* Export */, moduleSymbol: moduleSymbol, isDefaultExport: false }; + } + for (var _i = 0, _a = typeChecker.getExportsOfModule(moduleSymbol); _i < _a.length; _i++) { + var symbol = _a[_i]; + // Don't add a completion for a re-export, only for the original. + // The actual import fix might end up coming from a re-export -- we don't compute that until getting completion details. + // This is just to avoid adding duplicate completion entries. + // + // If `symbol.parent !== ...`, this is an `export * from "foo"` re-export. Those don't create new symbols. + if (typeChecker.getMergedSymbol(symbol.parent) !== resolvedModuleSymbol + || ts.some(symbol.declarations, function (d) { + // If `!!d.name.originalKeywordKind`, this is `export { _break as break };` -- skip this and prefer the keyword completion. + // If `!!d.parent.parent.moduleSpecifier`, this is `export { foo } from "foo"` re-export, which creates a new symbol (thus isn't caught by the first check). + return ts.isExportSpecifier(d) && (d.propertyName ? ts.isIdentifierANonContextualKeyword(d.name) : !!d.parent.parent.moduleSpecifier); + })) { + continue; + } + var isDefaultExport = symbol.escapedName === "default" /* Default */; + if (isDefaultExport) { + symbol = ts.getLocalSymbolForExportDefault(symbol) || symbol; + } + var origin = { kind: 3 /* Export */, moduleSymbol: moduleSymbol, isDefaultExport: isDefaultExport }; + if (detailsEntryId || stringContainsCharactersInOrder(getSymbolName(symbol, origin, target).toLowerCase(), tokenTextLowerCase)) { + symbols.push(symbol); + symbolToOriginInfoMap[ts.getSymbolId(symbol)] = origin; + } + } + }); + } + /** + * True if you could remove some characters in `a` to get `b`. + * E.g., true for "abcdef" and "bdf". + * But not true for "abcdef" and "dbf". + */ + function stringContainsCharactersInOrder(str, characters) { + if (characters.length === 0) { + return true; + } + var characterIndex = 0; + for (var strIndex = 0; strIndex < str.length; strIndex++) { + if (str.charCodeAt(strIndex) === characters.charCodeAt(characterIndex)) { + characterIndex++; + if (characterIndex === characters.length) { + return true; + } + } + } + // Did not find all characters + return false; + } + /** + * Finds the first node that "embraces" the position, so that one may + * accurately aggregate locals from the closest containing scope. + */ + function getScopeNode(initialToken, position, sourceFile) { + var scope = initialToken; + while (scope && !ts.positionBelongsToNode(scope, position, sourceFile)) { + scope = scope.parent; + } + return scope; + } + function isCompletionListBlocker(contextToken) { + var start = ts.timestamp(); + var result = isInStringOrRegularExpressionOrTemplateLiteral(contextToken) || + isSolelyIdentifierDefinitionLocation(contextToken) || + isDotOfNumericLiteral(contextToken) || + isInJsxText(contextToken); + log("getCompletionsAtPosition: isCompletionListBlocker: " + (ts.timestamp() - start)); + return result; + } + function isInJsxText(contextToken) { + if (contextToken.kind === 11 /* JsxText */) { + return true; + } + if (contextToken.kind === 30 /* GreaterThanToken */ && contextToken.parent) { + if (contextToken.parent.kind === 262 /* JsxOpeningElement */) { + return true; + } + if (contextToken.parent.kind === 263 /* JsxClosingElement */ || contextToken.parent.kind === 261 /* JsxSelfClosingElement */) { + return !!contextToken.parent.parent && contextToken.parent.parent.kind === 260 /* JsxElement */; + } + } + return false; + } + function isNewIdentifierDefinitionLocation(previousToken) { + if (previousToken) { + var containingNodeKind = previousToken.parent.kind; + // Previous token may have been a keyword that was converted to an identifier. + switch (keywordForNode(previousToken)) { + case 27 /* CommaToken */: + return containingNodeKind === 191 /* CallExpression */ // func( a, | + || containingNodeKind === 157 /* Constructor */ // constructor( a, | /* public, protected, private keywords are allowed here, so show completion */ + || containingNodeKind === 192 /* NewExpression */ // new C(a, | + || containingNodeKind === 187 /* ArrayLiteralExpression */ // [a, | + || containingNodeKind === 204 /* BinaryExpression */ // const x = (a, | + || containingNodeKind === 165 /* FunctionType */; // var x: (s: string, list| + case 20 /* OpenParenToken */: + return containingNodeKind === 191 /* CallExpression */ // func( | + || containingNodeKind === 157 /* Constructor */ // constructor( | + || containingNodeKind === 192 /* NewExpression */ // new C(a| + || containingNodeKind === 195 /* ParenthesizedExpression */ // const x = (a| + || containingNodeKind === 177 /* ParenthesizedType */; // function F(pred: (a| /* this can become an arrow function, where 'a' is the argument */ + case 22 /* OpenBracketToken */: + return containingNodeKind === 187 /* ArrayLiteralExpression */ // [ | + || containingNodeKind === 162 /* IndexSignature */ // [ | : string ] + || containingNodeKind === 149 /* ComputedPropertyName */; // [ | /* this can become an index signature */ + case 130 /* ModuleKeyword */: // module | + case 131 /* NamespaceKeyword */: // namespace | + return true; + case 24 /* DotToken */: + return containingNodeKind === 244 /* ModuleDeclaration */; // module A.| + case 18 /* OpenBraceToken */: + return containingNodeKind === 240 /* ClassDeclaration */; // class A{ | + case 59 /* EqualsToken */: + return containingNodeKind === 237 /* VariableDeclaration */ // const x = a| + || containingNodeKind === 204 /* BinaryExpression */; // x = a| + case 15 /* TemplateHead */: + return containingNodeKind === 206 /* TemplateExpression */; // `aa ${| + case 16 /* TemplateMiddle */: + return containingNodeKind === 216 /* TemplateSpan */; // `aa ${10} dd ${| + case 115 /* PublicKeyword */: + case 113 /* PrivateKeyword */: + case 114 /* ProtectedKeyword */: + return containingNodeKind === 154 /* PropertyDeclaration */; // class A{ public | + } + } + return false; + } + function isInStringOrRegularExpressionOrTemplateLiteral(contextToken) { + // To be "in" one of these literals, the position has to be: + // 1. entirely within the token text. + // 2. at the end position of an unterminated token. + // 3. at the end of a regular expression (due to trailing flags like '/foo/g'). + return (ts.isRegularExpressionLiteral(contextToken) || ts.isStringTextContainingNode(contextToken)) && (ts.rangeContainsPositionExclusive(ts.createTextRangeFromSpan(ts.createTextSpanFromNode(contextToken)), position) || + position === contextToken.end && (!!contextToken.isUnterminated || ts.isRegularExpressionLiteral(contextToken))); + } + /** + * Aggregates relevant symbols for completion in object literals and object binding patterns. + * Relevant symbols are stored in the captured 'symbols' variable. + * + * @returns true if 'symbols' was successfully populated; false otherwise. + */ + function tryGetObjectLikeCompletionSymbols() { + var objectLikeContainer = tryGetObjectLikeCompletionContainer(contextToken); + if (!objectLikeContainer) + return 0 /* Continue */; + // We're looking up possible property names from contextual/inferred/declared type. + completionKind = 0 /* ObjectPropertyDeclaration */; + var typeMembers; + var existingMembers; + if (objectLikeContainer.kind === 188 /* ObjectLiteralExpression */) { + var typeForObject = typeChecker.getContextualType(objectLikeContainer); + if (!typeForObject) + return 2 /* Fail */; + isNewIdentifierLocation = ts.hasIndexSignature(typeForObject); + typeMembers = getPropertiesForObjectExpression(typeForObject, objectLikeContainer, typeChecker); + existingMembers = objectLikeContainer.properties; + } + else { + ts.Debug.assert(objectLikeContainer.kind === 184 /* ObjectBindingPattern */); + // We are *only* completing on properties from the type being destructured. + isNewIdentifierLocation = false; + var rootDeclaration = ts.getRootDeclaration(objectLikeContainer.parent); + if (!ts.isVariableLike(rootDeclaration)) + return ts.Debug.fail("Root declaration is not variable-like."); + // We don't want to complete using the type acquired by the shape + // of the binding pattern; we are only interested in types acquired + // through type declaration or inference. + // Also proceed if rootDeclaration is a parameter and if its containing function expression/arrow function is contextually typed - + // type of parameter will flow in from the contextual type of the function + var canGetType = ts.hasInitializer(rootDeclaration) || ts.hasType(rootDeclaration) || rootDeclaration.parent.parent.kind === 227 /* ForOfStatement */; + if (!canGetType && rootDeclaration.kind === 151 /* Parameter */) { + if (ts.isExpression(rootDeclaration.parent)) { + canGetType = !!typeChecker.getContextualType(rootDeclaration.parent); + } + else if (rootDeclaration.parent.kind === 156 /* MethodDeclaration */ || rootDeclaration.parent.kind === 159 /* SetAccessor */) { + canGetType = ts.isExpression(rootDeclaration.parent.parent) && !!typeChecker.getContextualType(rootDeclaration.parent.parent); + } + } + if (canGetType) { + var typeForObject = typeChecker.getTypeAtLocation(objectLikeContainer); + if (!typeForObject) + return 2 /* Fail */; + // In a binding pattern, get only known properties. Everywhere else we will get all possible properties. + typeMembers = typeChecker.getPropertiesOfType(typeForObject).filter(function (symbol) { return !(ts.getDeclarationModifierFlagsFromSymbol(symbol) & 24 /* NonPublicAccessibilityModifier */); }); + existingMembers = objectLikeContainer.elements; + } + } + if (typeMembers && typeMembers.length > 0) { + // Add filtered items to the completion list + symbols = filterObjectMembersList(typeMembers, ts.Debug.assertDefined(existingMembers)); + } + return 1 /* Success */; + } + /** + * Aggregates relevant symbols for completion in import clauses and export clauses + * whose declarations have a module specifier; for instance, symbols will be aggregated for + * + * import { | } from "moduleName"; + * export { a as foo, | } from "moduleName"; + * + * but not for + * + * export { | }; + * + * Relevant symbols are stored in the captured 'symbols' variable. + * + * @returns true if 'symbols' was successfully populated; false otherwise. + */ + function tryGetImportOrExportClauseCompletionSymbols() { + // `import { |` or `import { a as 0, | }` + var namedImportsOrExports = contextToken && (contextToken.kind === 18 /* OpenBraceToken */ || contextToken.kind === 27 /* CommaToken */) + ? ts.tryCast(contextToken.parent, ts.isNamedImportsOrExports) : undefined; + if (!namedImportsOrExports) + return 0 /* Continue */; + // cursor is in an import clause + // try to show exported member for imported module + var moduleSpecifier = (namedImportsOrExports.kind === 252 /* NamedImports */ ? namedImportsOrExports.parent.parent : namedImportsOrExports.parent).moduleSpecifier; + var moduleSpecifierSymbol = typeChecker.getSymbolAtLocation(moduleSpecifier); // TODO: GH#18217 + if (!moduleSpecifierSymbol) + return 2 /* Fail */; + completionKind = 3 /* MemberLike */; + isNewIdentifierLocation = false; + var exports = typeChecker.getExportsAndPropertiesOfModule(moduleSpecifierSymbol); + var existing = ts.arrayToSet(namedImportsOrExports.elements, function (n) { return isCurrentlyEditingNode(n) ? undefined : (n.propertyName || n.name).escapedText; }); + symbols = exports.filter(function (e) { return e.escapedName !== "default" /* Default */ && !existing.get(e.escapedName); }); + return 1 /* Success */; + } + /** + * Aggregates relevant symbols for completion in class declaration + * Relevant symbols are stored in the captured 'symbols' variable. + */ + function tryGetClassLikeCompletionSymbols() { + var decl = tryGetObjectTypeDeclarationCompletionContainer(sourceFile, contextToken, location); + if (!decl) + return 0 /* Continue */; + // We're looking up possible property names from parent type. + completionKind = 3 /* MemberLike */; + // Declaring new property/method/accessor + isNewIdentifierLocation = true; + keywordFilters = contextToken.kind === 40 /* AsteriskToken */ ? 0 /* None */ : + ts.isClassLike(decl) ? 2 /* ClassElementKeywords */ : 3 /* InterfaceElementKeywords */; + // If you're in an interface you don't want to repeat things from super-interface. So just stop here. + if (!ts.isClassLike(decl)) + return 1 /* Success */; + var classElement = contextToken.parent; + var classElementModifierFlags = ts.isClassElement(classElement) ? ts.getModifierFlags(classElement) : 0 /* None */; + // If this is context token is not something we are editing now, consider if this would lead to be modifier + if (contextToken.kind === 72 /* Identifier */ && !isCurrentlyEditingNode(contextToken)) { + switch (contextToken.getText()) { + case "private": + classElementModifierFlags = classElementModifierFlags | 8 /* Private */; + break; + case "static": + classElementModifierFlags = classElementModifierFlags | 32 /* Static */; + break; + } + } + // No member list for private methods + if (!(classElementModifierFlags & 8 /* Private */)) { + // List of property symbols of base type that are not private and already implemented + var baseSymbols = ts.flatMap(ts.getAllSuperTypeNodes(decl), function (baseTypeNode) { + var type = typeChecker.getTypeAtLocation(baseTypeNode); + return type && typeChecker.getPropertiesOfType(classElementModifierFlags & 32 /* Static */ ? typeChecker.getTypeOfSymbolAtLocation(type.symbol, decl) : type); + }); + symbols = filterClassMembersList(baseSymbols, decl.members, classElementModifierFlags); + } + return 1 /* Success */; + } + /** + * Returns the immediate owning object literal or binding pattern of a context token, + * on the condition that one exists and that the context implies completion should be given. + */ + function tryGetObjectLikeCompletionContainer(contextToken) { + if (contextToken) { + var parent = contextToken.parent; + switch (contextToken.kind) { + case 18 /* OpenBraceToken */: // const x = { | + case 27 /* CommaToken */: // const x = { a: 0, | + if (ts.isObjectLiteralExpression(parent) || ts.isObjectBindingPattern(parent)) { + return parent; + } + break; + case 40 /* AsteriskToken */: + return ts.isMethodDeclaration(parent) ? ts.tryCast(parent.parent, ts.isObjectLiteralExpression) : undefined; + case 72 /* Identifier */: + return contextToken.text === "async" && ts.isShorthandPropertyAssignment(contextToken.parent) + ? contextToken.parent.parent : undefined; + } + } + return undefined; + } + function isConstructorParameterCompletion(node) { + return !!node.parent && ts.isParameter(node.parent) && ts.isConstructorDeclaration(node.parent.parent) + && (ts.isParameterPropertyModifier(node.kind) || ts.isDeclarationName(node)); + } + /** + * Returns the immediate owning class declaration of a context token, + * on the condition that one exists and that the context implies completion should be given. + */ + function tryGetConstructorLikeCompletionContainer(contextToken) { + if (contextToken) { + var parent = contextToken.parent; + switch (contextToken.kind) { + case 20 /* OpenParenToken */: + case 27 /* CommaToken */: + return ts.isConstructorDeclaration(contextToken.parent) ? contextToken.parent : undefined; + default: + if (isConstructorParameterCompletion(contextToken)) { + return parent.parent; + } + } + } + return undefined; + } + function tryGetFunctionLikeBodyCompletionContainer(contextToken) { + if (contextToken) { + var prev_1; + var container = ts.findAncestor(contextToken.parent, function (node) { + if (ts.isClassLike(node)) { + return "quit"; + } + if (ts.isFunctionLikeDeclaration(node) && prev_1 === node.body) { + return true; + } + prev_1 = node; + return false; + }); + return container && container; + } + } + function tryGetContainingJsxElement(contextToken) { + if (contextToken) { + var parent = contextToken.parent; + switch (contextToken.kind) { + case 30 /* GreaterThanToken */: // End of a type argument list + case 29 /* LessThanSlashToken */: + case 42 /* SlashToken */: + case 72 /* Identifier */: + case 189 /* PropertyAccessExpression */: + case 268 /* JsxAttributes */: + case 267 /* JsxAttribute */: + case 269 /* JsxSpreadAttribute */: + if (parent && (parent.kind === 261 /* JsxSelfClosingElement */ || parent.kind === 262 /* JsxOpeningElement */)) { + if (contextToken.kind === 30 /* GreaterThanToken */) { + var precedingToken = ts.findPrecedingToken(contextToken.pos, sourceFile, /*startNode*/ undefined); + if (!parent.typeArguments || (precedingToken && precedingToken.kind === 42 /* SlashToken */)) + break; + } + return parent; + } + else if (parent.kind === 267 /* JsxAttribute */) { + // Currently we parse JsxOpeningLikeElement as: + // JsxOpeningLikeElement + // attributes: JsxAttributes + // properties: NodeArray + return parent.parent.parent; + } + break; + // The context token is the closing } or " of an attribute, which means + // its parent is a JsxExpression, whose parent is a JsxAttribute, + // whose parent is a JsxOpeningLikeElement + case 10 /* StringLiteral */: + if (parent && ((parent.kind === 267 /* JsxAttribute */) || (parent.kind === 269 /* JsxSpreadAttribute */))) { + // Currently we parse JsxOpeningLikeElement as: + // JsxOpeningLikeElement + // attributes: JsxAttributes + // properties: NodeArray + return parent.parent.parent; + } + break; + case 19 /* CloseBraceToken */: + if (parent && + parent.kind === 270 /* JsxExpression */ && + parent.parent && parent.parent.kind === 267 /* JsxAttribute */) { + // Currently we parse JsxOpeningLikeElement as: + // JsxOpeningLikeElement + // attributes: JsxAttributes + // properties: NodeArray + // each JsxAttribute can have initializer as JsxExpression + return parent.parent.parent.parent; + } + if (parent && parent.kind === 269 /* JsxSpreadAttribute */) { + // Currently we parse JsxOpeningLikeElement as: + // JsxOpeningLikeElement + // attributes: JsxAttributes + // properties: NodeArray + return parent.parent.parent; + } + break; + } + } + return undefined; + } + /** + * @returns true if we are certain that the currently edited location must define a new location; false otherwise. + */ + function isSolelyIdentifierDefinitionLocation(contextToken) { + var parent = contextToken.parent; + var containingNodeKind = parent.kind; + switch (contextToken.kind) { + case 27 /* CommaToken */: + return containingNodeKind === 237 /* VariableDeclaration */ || + containingNodeKind === 238 /* VariableDeclarationList */ || + containingNodeKind === 219 /* VariableStatement */ || + containingNodeKind === 243 /* EnumDeclaration */ || // enum a { foo, | + isFunctionLikeButNotConstructor(containingNodeKind) || + containingNodeKind === 241 /* InterfaceDeclaration */ || // interface A= contextToken.pos); + case 24 /* DotToken */: + return containingNodeKind === 185 /* ArrayBindingPattern */; // var [.| + case 57 /* ColonToken */: + return containingNodeKind === 186 /* BindingElement */; // var {x :html| + case 22 /* OpenBracketToken */: + return containingNodeKind === 185 /* ArrayBindingPattern */; // var [x| + case 20 /* OpenParenToken */: + return containingNodeKind === 274 /* CatchClause */ || + isFunctionLikeButNotConstructor(containingNodeKind); + case 18 /* OpenBraceToken */: + return containingNodeKind === 243 /* EnumDeclaration */; // enum a { | + case 28 /* LessThanToken */: + return containingNodeKind === 240 /* ClassDeclaration */ || // class A< | + containingNodeKind === 209 /* ClassExpression */ || // var C = class D< | + containingNodeKind === 241 /* InterfaceDeclaration */ || // interface A< | + containingNodeKind === 242 /* TypeAliasDeclaration */ || // type List< | + ts.isFunctionLikeKind(containingNodeKind); + case 116 /* StaticKeyword */: + return containingNodeKind === 154 /* PropertyDeclaration */ && !ts.isClassLike(parent.parent); + case 25 /* DotDotDotToken */: + return containingNodeKind === 151 /* Parameter */ || + (!!parent.parent && parent.parent.kind === 185 /* ArrayBindingPattern */); // var [...z| + case 115 /* PublicKeyword */: + case 113 /* PrivateKeyword */: + case 114 /* ProtectedKeyword */: + return containingNodeKind === 151 /* Parameter */ && !ts.isConstructorDeclaration(parent.parent); + case 119 /* AsKeyword */: + return containingNodeKind === 253 /* ImportSpecifier */ || + containingNodeKind === 257 /* ExportSpecifier */ || + containingNodeKind === 251 /* NamespaceImport */; + case 126 /* GetKeyword */: + case 137 /* SetKeyword */: + return !isFromObjectTypeDeclaration(contextToken); + case 76 /* ClassKeyword */: + case 84 /* EnumKeyword */: + case 110 /* InterfaceKeyword */: + case 90 /* FunctionKeyword */: + case 105 /* VarKeyword */: + case 92 /* ImportKeyword */: + case 111 /* LetKeyword */: + case 77 /* ConstKeyword */: + case 117 /* YieldKeyword */: + case 140 /* TypeKeyword */: // type htm| + return true; + case 40 /* AsteriskToken */: + return ts.isFunctionLike(contextToken.parent) && !ts.isMethodDeclaration(contextToken.parent); + } + // If the previous token is keyword correspoding to class member completion keyword + // there will be completion available here + if (isClassMemberCompletionKeyword(keywordForNode(contextToken)) && isFromObjectTypeDeclaration(contextToken)) { + return false; + } + if (isConstructorParameterCompletion(contextToken)) { + // constructor parameter completion is available only if + // - its modifier of the constructor parameter or + // - its name of the parameter and not being edited + // eg. constructor(a |<- this shouldnt show completion + if (!ts.isIdentifier(contextToken) || + ts.isParameterPropertyModifier(keywordForNode(contextToken)) || + isCurrentlyEditingNode(contextToken)) { + return false; + } + } + // Previous token may have been a keyword that was converted to an identifier. + switch (keywordForNode(contextToken)) { + case 118 /* AbstractKeyword */: + case 76 /* ClassKeyword */: + case 77 /* ConstKeyword */: + case 125 /* DeclareKeyword */: + case 84 /* EnumKeyword */: + case 90 /* FunctionKeyword */: + case 110 /* InterfaceKeyword */: + case 111 /* LetKeyword */: + case 113 /* PrivateKeyword */: + case 114 /* ProtectedKeyword */: + case 115 /* PublicKeyword */: + case 116 /* StaticKeyword */: + case 105 /* VarKeyword */: + case 117 /* YieldKeyword */: + return true; + case 121 /* AsyncKeyword */: + return ts.isPropertyDeclaration(contextToken.parent); + } + return ts.isDeclarationName(contextToken) + && !ts.isJsxAttribute(contextToken.parent) + // Don't block completions if we're in `class C /**/`, because we're *past* the end of the identifier and might want to complete `extends`. + // If `contextToken !== previousToken`, this is `class C ex/**/`. + && !(ts.isClassLike(contextToken.parent) && (contextToken !== previousToken || position > previousToken.end)); + } + function isFunctionLikeButNotConstructor(kind) { + return ts.isFunctionLikeKind(kind) && kind !== 157 /* Constructor */; + } + function isDotOfNumericLiteral(contextToken) { + if (contextToken.kind === 8 /* NumericLiteral */) { + var text = contextToken.getFullText(); + return text.charAt(text.length - 1) === "."; + } + return false; + } + /** + * Filters out completion suggestions for named imports or exports. + * + * @returns Symbols to be suggested in an object binding pattern or object literal expression, barring those whose declarations + * do not occur at the current position and have not otherwise been typed. + */ + function filterObjectMembersList(contextualMemberSymbols, existingMembers) { + if (existingMembers.length === 0) { + return contextualMemberSymbols; + } + var existingMemberNames = ts.createUnderscoreEscapedMap(); + for (var _i = 0, existingMembers_1 = existingMembers; _i < existingMembers_1.length; _i++) { + var m = existingMembers_1[_i]; + // Ignore omitted expressions for missing members + if (m.kind !== 275 /* PropertyAssignment */ && + m.kind !== 276 /* ShorthandPropertyAssignment */ && + m.kind !== 186 /* BindingElement */ && + m.kind !== 156 /* MethodDeclaration */ && + m.kind !== 158 /* GetAccessor */ && + m.kind !== 159 /* SetAccessor */) { + continue; + } + // If this is the current item we are editing right now, do not filter it out + if (isCurrentlyEditingNode(m)) { + continue; + } + var existingName = void 0; + if (ts.isBindingElement(m) && m.propertyName) { + // include only identifiers in completion list + if (m.propertyName.kind === 72 /* Identifier */) { + existingName = m.propertyName.escapedText; + } + } + else { + // TODO: Account for computed property name + // NOTE: if one only performs this step when m.name is an identifier, + // things like '__proto__' are not filtered out. + var name = ts.getNameOfDeclaration(m); + existingName = name && ts.isPropertyNameLiteral(name) ? ts.getEscapedTextOfIdentifierOrLiteral(name) : undefined; + } + existingMemberNames.set(existingName, true); // TODO: GH#18217 + } + return contextualMemberSymbols.filter(function (m) { return !existingMemberNames.get(m.escapedName); }); + } + /** + * Filters out completion suggestions for class elements. + * + * @returns Symbols to be suggested in an class element depending on existing memebers and symbol flags + */ + function filterClassMembersList(baseSymbols, existingMembers, currentClassElementModifierFlags) { + var existingMemberNames = ts.createUnderscoreEscapedMap(); + for (var _i = 0, existingMembers_2 = existingMembers; _i < existingMembers_2.length; _i++) { + var m = existingMembers_2[_i]; + // Ignore omitted expressions for missing members + if (m.kind !== 154 /* PropertyDeclaration */ && + m.kind !== 156 /* MethodDeclaration */ && + m.kind !== 158 /* GetAccessor */ && + m.kind !== 159 /* SetAccessor */) { + continue; + } + // If this is the current item we are editing right now, do not filter it out + if (isCurrentlyEditingNode(m)) { + continue; + } + // Dont filter member even if the name matches if it is declared private in the list + if (ts.hasModifier(m, 8 /* Private */)) { + continue; + } + // do not filter it out if the static presence doesnt match + if (ts.hasModifier(m, 32 /* Static */) !== !!(currentClassElementModifierFlags & 32 /* Static */)) { + continue; + } + var existingName = ts.getPropertyNameForPropertyNameNode(m.name); + if (existingName) { + existingMemberNames.set(existingName, true); + } + } + return baseSymbols.filter(function (propertySymbol) { + return !existingMemberNames.has(propertySymbol.escapedName) && + !!propertySymbol.declarations && + !(ts.getDeclarationModifierFlagsFromSymbol(propertySymbol) & 8 /* Private */); + }); + } + /** + * Filters out completion suggestions from 'symbols' according to existing JSX attributes. + * + * @returns Symbols to be suggested in a JSX element, barring those whose attributes + * do not occur at the current position and have not otherwise been typed. + */ + function filterJsxAttributes(symbols, attributes) { + var seenNames = ts.createUnderscoreEscapedMap(); + for (var _i = 0, attributes_1 = attributes; _i < attributes_1.length; _i++) { + var attr = attributes_1[_i]; + // If this is the current item we are editing right now, do not filter it out + if (isCurrentlyEditingNode(attr)) { + continue; + } + if (attr.kind === 267 /* JsxAttribute */) { + seenNames.set(attr.name.escapedText, true); + } + } + return symbols.filter(function (a) { return !seenNames.get(a.escapedName); }); + } + function isCurrentlyEditingNode(node) { + return node.getStart(sourceFile) <= position && position <= node.getEnd(); + } + } + function getCompletionEntryDisplayNameForSymbol(symbol, target, origin, kind) { + var name = getSymbolName(symbol, origin, target); + if (name === undefined + // If the symbol is external module, don't show it in the completion list + // (i.e declare module "http" { const x; } | // <= request completion here, "http" should not be there) + || symbol.flags & 1536 /* Module */ && ts.startsWithQuote(name) + // If the symbol is the internal name of an ES symbol, it is not a valid entry. Internal names for ES symbols start with "__@" + || ts.isKnownSymbol(symbol)) { + return undefined; + } + var validIdentiferResult = { name: name, needsConvertPropertyAccess: false }; + if (ts.isIdentifierText(name, target)) + return validIdentiferResult; + switch (kind) { + case 3 /* MemberLike */: + return undefined; + case 0 /* ObjectPropertyDeclaration */: + // TODO: GH#18169 + return { name: JSON.stringify(name), needsConvertPropertyAccess: false }; + case 2 /* PropertyAccess */: + case 1 /* Global */: // For a 'this.' completion it will be in a global context, but may have a non-identifier name. + // Don't add a completion for a name starting with a space. See https://github.com/Microsoft/TypeScript/pull/20547 + return name.charCodeAt(0) === 32 /* space */ ? undefined : { name: name, needsConvertPropertyAccess: true }; + case 5 /* None */: + case 4 /* String */: + return validIdentiferResult; + default: + ts.Debug.assertNever(kind); + } + } + // A cache of completion entries for keywords, these do not change between sessions + var _keywordCompletions = []; + var allKeywordsCompletions = ts.memoize(function () { + var res = []; + for (var i = 73 /* FirstKeyword */; i <= 147 /* LastKeyword */; i++) { + res.push({ + name: ts.tokenToString(i), + kind: "keyword" /* keyword */, + kindModifiers: "" /* none */, + sortText: "0" + }); + } + return res; + }); + function getKeywordCompletions(keywordFilter) { + return _keywordCompletions[keywordFilter] || (_keywordCompletions[keywordFilter] = allKeywordsCompletions().filter(function (entry) { + var kind = ts.stringToToken(entry.name); + switch (keywordFilter) { + case 0 /* None */: + return false; + case 1 /* All */: + return kind === 121 /* AsyncKeyword */ || 122 /* AwaitKeyword */ || !ts.isContextualKeyword(kind) && !isClassMemberCompletionKeyword(kind) || kind === 125 /* DeclareKeyword */ || kind === 130 /* ModuleKeyword */ + || ts.isTypeKeyword(kind) && kind !== 141 /* UndefinedKeyword */; + case 2 /* ClassElementKeywords */: + return isClassMemberCompletionKeyword(kind); + case 3 /* InterfaceElementKeywords */: + return isInterfaceOrTypeLiteralCompletionKeyword(kind); + case 4 /* ConstructorParameterKeywords */: + return ts.isParameterPropertyModifier(kind); + case 5 /* FunctionLikeBodyKeywords */: + return isFunctionLikeBodyKeyword(kind); + case 6 /* TypeKeywords */: + return ts.isTypeKeyword(kind); + default: + return ts.Debug.assertNever(keywordFilter); + } + })); + } + function isInterfaceOrTypeLiteralCompletionKeyword(kind) { + return kind === 133 /* ReadonlyKeyword */; + } + function isClassMemberCompletionKeyword(kind) { + switch (kind) { + case 118 /* AbstractKeyword */: + case 124 /* ConstructorKeyword */: + case 126 /* GetKeyword */: + case 137 /* SetKeyword */: + case 121 /* AsyncKeyword */: + return true; + default: + return ts.isClassMemberModifier(kind); + } + } + function isFunctionLikeBodyKeyword(kind) { + return kind === 121 /* AsyncKeyword */ || kind === 122 /* AwaitKeyword */ || !ts.isContextualKeyword(kind) && !isClassMemberCompletionKeyword(kind); + } + function keywordForNode(node) { + return ts.isIdentifier(node) ? node.originalKeywordKind || 0 /* Unknown */ : node.kind; + } + /** Get the corresponding JSDocTag node if the position is in a jsDoc comment */ + function getJsDocTagAtPosition(node, position) { + var jsdoc = ts.findAncestor(node, ts.isJSDoc); + return jsdoc && jsdoc.tags && (ts.rangeContainsPosition(jsdoc, position) ? ts.findLast(jsdoc.tags, function (tag) { return tag.pos < position; }) : undefined); + } + function getPropertiesForObjectExpression(contextualType, obj, checker) { + return contextualType.isUnion() + ? checker.getAllPossiblePropertiesOfTypes(contextualType.types.filter(function (memberType) { + // If we're providing completions for an object literal, skip primitive, array-like, or callable types since those shouldn't be implemented by object literals. + return !(memberType.flags & 131068 /* Primitive */ || + checker.isArrayLikeType(memberType) || + ts.typeHasCallOrConstructSignatures(memberType, checker) || + checker.isTypeInvalidDueToUnionDiscriminant(memberType, obj)); + })) + : contextualType.getApparentProperties(); + } + /** + * Gets all properties on a type, but if that type is a union of several types, + * excludes array-like types or callable/constructable types. + */ + function getPropertiesForCompletion(type, checker) { + return type.isUnion() + ? ts.Debug.assertEachDefined(checker.getAllPossiblePropertiesOfTypes(type.types), "getAllPossiblePropertiesOfTypes() should all be defined") + : ts.Debug.assertEachDefined(type.getApparentProperties(), "getApparentProperties() should all be defined"); + } + /** + * Returns the immediate owning class declaration of a context token, + * on the condition that one exists and that the context implies completion should be given. + */ + function tryGetObjectTypeDeclarationCompletionContainer(sourceFile, contextToken, location) { + // class c { method() { } | method2() { } } + switch (location.kind) { + case 306 /* SyntaxList */: + return ts.tryCast(location.parent, ts.isObjectTypeDeclaration); + case 1 /* EndOfFileToken */: + var cls = ts.tryCast(ts.lastOrUndefined(ts.cast(location.parent, ts.isSourceFile).statements), ts.isObjectTypeDeclaration); + if (cls && !ts.findChildOfKind(cls, 19 /* CloseBraceToken */, sourceFile)) { + return cls; + } + } + if (!contextToken) + return undefined; + switch (contextToken.kind) { + case 26 /* SemicolonToken */: // class c {getValue(): number; | } + case 19 /* CloseBraceToken */: // class c { method() { } | } + // class c { method() { } b| } + return isFromObjectTypeDeclaration(location) && location.parent.name === location + ? location.parent.parent + : ts.tryCast(location, ts.isObjectTypeDeclaration); + case 18 /* OpenBraceToken */: // class c { | + case 27 /* CommaToken */: // class c {getValue(): number, | } + return ts.tryCast(contextToken.parent, ts.isObjectTypeDeclaration); + default: + if (!isFromObjectTypeDeclaration(contextToken)) + return undefined; + var isValidKeyword = ts.isClassLike(contextToken.parent.parent) ? isClassMemberCompletionKeyword : isInterfaceOrTypeLiteralCompletionKeyword; + return (isValidKeyword(contextToken.kind) || contextToken.kind === 40 /* AsteriskToken */ || ts.isIdentifier(contextToken) && isValidKeyword(ts.stringToToken(contextToken.text))) // TODO: GH#18217 + ? contextToken.parent.parent : undefined; + } + } + // TODO: GH#19856 Would like to return `node is Node & { parent: (ClassElement | TypeElement) & { parent: ObjectTypeDeclaration } }` but then compilation takes > 10 minutes + function isFromObjectTypeDeclaration(node) { + return node.parent && ts.isClassOrTypeElement(node.parent) && ts.isObjectTypeDeclaration(node.parent.parent); + } + function isValidTrigger(sourceFile, triggerCharacter, contextToken, position) { + switch (triggerCharacter) { + case ".": + case "@": + return true; + case '"': + case "'": + case "`": + // Only automatically bring up completions if this is an opening quote. + return !!contextToken && ts.isStringLiteralOrTemplate(contextToken) && position === contextToken.getStart(sourceFile) + 1; + case "<": + // Opening JSX tag + return !!contextToken && contextToken.kind === 28 /* LessThanToken */ && (!ts.isBinaryExpression(contextToken.parent) || binaryExpressionMayBeOpenTag(contextToken.parent)); + case "/": + return !!contextToken && (ts.isStringLiteralLike(contextToken) + ? !!ts.tryGetImportFromModuleSpecifier(contextToken) + : contextToken.kind === 42 /* SlashToken */ && ts.isJsxClosingElement(contextToken.parent)); + default: + return ts.Debug.assertNever(triggerCharacter); + } + } + function binaryExpressionMayBeOpenTag(_a) { + var left = _a.left; + return ts.nodeIsMissing(left); + } + })(Completions = ts.Completions || (ts.Completions = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var DocumentHighlights; + (function (DocumentHighlights) { + function getDocumentHighlights(program, cancellationToken, sourceFile, position, sourceFilesToSearch) { + var node = ts.getTouchingPropertyName(sourceFile, position); + if (node.parent && (ts.isJsxOpeningElement(node.parent) && node.parent.tagName === node || ts.isJsxClosingElement(node.parent))) { + // For a JSX element, just highlight the matching tag, not all references. + var _a = node.parent.parent, openingElement = _a.openingElement, closingElement = _a.closingElement; + var highlightSpans = [openingElement, closingElement].map(function (_a) { + var tagName = _a.tagName; + return getHighlightSpanForNode(tagName, sourceFile); + }); + return [{ fileName: sourceFile.fileName, highlightSpans: highlightSpans }]; + } + return getSemanticDocumentHighlights(position, node, program, cancellationToken, sourceFilesToSearch) || getSyntacticDocumentHighlights(node, sourceFile); + } + DocumentHighlights.getDocumentHighlights = getDocumentHighlights; + function getHighlightSpanForNode(node, sourceFile) { + return { + fileName: sourceFile.fileName, + textSpan: ts.createTextSpanFromNode(node, sourceFile), + kind: "none" /* none */ + }; + } + function getSemanticDocumentHighlights(position, node, program, cancellationToken, sourceFilesToSearch) { + var sourceFilesSet = ts.arrayToSet(sourceFilesToSearch, function (f) { return f.fileName; }); + var referenceEntries = ts.FindAllReferences.getReferenceEntriesForNode(position, node, program, sourceFilesToSearch, cancellationToken, /*options*/ undefined, sourceFilesSet); + if (!referenceEntries) + return undefined; + var map = ts.arrayToMultiMap(referenceEntries.map(ts.FindAllReferences.toHighlightSpan), function (e) { return e.fileName; }, function (e) { return e.span; }); + return ts.arrayFrom(map.entries(), function (_a) { + var fileName = _a[0], highlightSpans = _a[1]; + if (!sourceFilesSet.has(fileName)) { + ts.Debug.assert(program.redirectTargetsMap.has(fileName)); + var redirectTarget_1 = program.getSourceFile(fileName); + var redirect = ts.find(sourceFilesToSearch, function (f) { return !!f.redirectInfo && f.redirectInfo.redirectTarget === redirectTarget_1; }); + fileName = redirect.fileName; + ts.Debug.assert(sourceFilesSet.has(fileName)); + } + return { fileName: fileName, highlightSpans: highlightSpans }; + }); + } + function getSyntacticDocumentHighlights(node, sourceFile) { + var highlightSpans = getHighlightSpans(node, sourceFile); + return highlightSpans && [{ fileName: sourceFile.fileName, highlightSpans: highlightSpans }]; + } + function getHighlightSpans(node, sourceFile) { + switch (node.kind) { + case 91 /* IfKeyword */: + case 83 /* ElseKeyword */: + return ts.isIfStatement(node.parent) ? getIfElseOccurrences(node.parent, sourceFile) : undefined; + case 97 /* ReturnKeyword */: + return useParent(node.parent, ts.isReturnStatement, getReturnOccurrences); + case 101 /* ThrowKeyword */: + return useParent(node.parent, ts.isThrowStatement, getThrowOccurrences); + case 103 /* TryKeyword */: + case 75 /* CatchKeyword */: + case 88 /* FinallyKeyword */: + var tryStatement = node.kind === 75 /* CatchKeyword */ ? node.parent.parent : node.parent; + return useParent(tryStatement, ts.isTryStatement, getTryCatchFinallyOccurrences); + case 99 /* SwitchKeyword */: + return useParent(node.parent, ts.isSwitchStatement, getSwitchCaseDefaultOccurrences); + case 74 /* CaseKeyword */: + case 80 /* DefaultKeyword */: + return useParent(node.parent.parent.parent, ts.isSwitchStatement, getSwitchCaseDefaultOccurrences); + case 73 /* BreakKeyword */: + case 78 /* ContinueKeyword */: + return useParent(node.parent, ts.isBreakOrContinueStatement, getBreakOrContinueStatementOccurrences); + case 89 /* ForKeyword */: + case 107 /* WhileKeyword */: + case 82 /* DoKeyword */: + return useParent(node.parent, function (n) { return ts.isIterationStatement(n, /*lookInLabeledStatements*/ true); }, getLoopBreakContinueOccurrences); + case 124 /* ConstructorKeyword */: + return getFromAllDeclarations(ts.isConstructorDeclaration, [124 /* ConstructorKeyword */]); + case 126 /* GetKeyword */: + case 137 /* SetKeyword */: + return getFromAllDeclarations(ts.isAccessor, [126 /* GetKeyword */, 137 /* SetKeyword */]); + case 122 /* AwaitKeyword */: + return useParent(node.parent, ts.isAwaitExpression, getAsyncAndAwaitOccurrences); + case 121 /* AsyncKeyword */: + return highlightSpans(getAsyncAndAwaitOccurrences(node)); + case 117 /* YieldKeyword */: + return highlightSpans(getYieldOccurrences(node)); + default: + return ts.isModifierKind(node.kind) && (ts.isDeclaration(node.parent) || ts.isVariableStatement(node.parent)) + ? highlightSpans(getModifierOccurrences(node.kind, node.parent)) + : undefined; + } + function getFromAllDeclarations(nodeTest, keywords) { + return useParent(node.parent, nodeTest, function (decl) { return ts.mapDefined(decl.symbol.declarations, function (d) { + return nodeTest(d) ? ts.find(d.getChildren(sourceFile), function (c) { return ts.contains(keywords, c.kind); }) : undefined; + }); }); + } + function useParent(node, nodeTest, getNodes) { + return nodeTest(node) ? highlightSpans(getNodes(node, sourceFile)) : undefined; + } + function highlightSpans(nodes) { + return nodes && nodes.map(function (node) { return getHighlightSpanForNode(node, sourceFile); }); + } + } + /** + * Aggregates all throw-statements within this node *without* crossing + * into function boundaries and try-blocks with catch-clauses. + */ + function aggregateOwnedThrowStatements(node) { + if (ts.isThrowStatement(node)) { + return [node]; + } + else if (ts.isTryStatement(node)) { + // Exceptions thrown within a try block lacking a catch clause are "owned" in the current context. + return ts.concatenate(node.catchClause ? aggregateOwnedThrowStatements(node.catchClause) : node.tryBlock && aggregateOwnedThrowStatements(node.tryBlock), node.finallyBlock && aggregateOwnedThrowStatements(node.finallyBlock)); + } + // Do not cross function boundaries. + return ts.isFunctionLike(node) ? undefined : flatMapChildren(node, aggregateOwnedThrowStatements); + } + /** + * For lack of a better name, this function takes a throw statement and returns the + * nearest ancestor that is a try-block (whose try statement has a catch clause), + * function-block, or source file. + */ + function getThrowStatementOwner(throwStatement) { + var child = throwStatement; + while (child.parent) { + var parent = child.parent; + if (ts.isFunctionBlock(parent) || parent.kind === 279 /* SourceFile */) { + return parent; + } + // A throw-statement is only owned by a try-statement if the try-statement has + // a catch clause, and if the throw-statement occurs within the try block. + if (ts.isTryStatement(parent) && parent.tryBlock === child && parent.catchClause) { + return child; + } + child = parent; + } + return undefined; + } + function aggregateAllBreakAndContinueStatements(node) { + return ts.isBreakOrContinueStatement(node) ? [node] : ts.isFunctionLike(node) ? undefined : flatMapChildren(node, aggregateAllBreakAndContinueStatements); + } + function flatMapChildren(node, cb) { + var result = []; + node.forEachChild(function (child) { + var value = cb(child); + if (value !== undefined) { + result.push.apply(result, ts.toArray(value)); + } + }); + return result; + } + function ownsBreakOrContinueStatement(owner, statement) { + var actualOwner = getBreakOrContinueOwner(statement); + return !!actualOwner && actualOwner === owner; + } + function getBreakOrContinueOwner(statement) { + return ts.findAncestor(statement, function (node) { + switch (node.kind) { + case 232 /* SwitchStatement */: + if (statement.kind === 228 /* ContinueStatement */) { + return false; + } + // falls through + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + case 224 /* WhileStatement */: + case 223 /* DoStatement */: + return !statement.label || isLabeledBy(node, statement.label.escapedText); + default: + // Don't cross function boundaries. + // TODO: GH#20090 + return ts.isFunctionLike(node) && "quit"; + } + }); + } + function getModifierOccurrences(modifier, declaration) { + return ts.mapDefined(getNodesToSearchForModifier(declaration, ts.modifierToFlag(modifier)), function (node) { return ts.findModifier(node, modifier); }); + } + function getNodesToSearchForModifier(declaration, modifierFlag) { + // Types of node whose children might have modifiers. + var container = declaration.parent; + switch (container.kind) { + case 245 /* ModuleBlock */: + case 279 /* SourceFile */: + case 218 /* Block */: + case 271 /* CaseClause */: + case 272 /* DefaultClause */: + // Container is either a class declaration or the declaration is a classDeclaration + if (modifierFlag & 128 /* Abstract */ && ts.isClassDeclaration(declaration)) { + return declaration.members.concat([declaration]); + } + else { + return container.statements; + } + case 157 /* Constructor */: + case 156 /* MethodDeclaration */: + case 239 /* FunctionDeclaration */: + return container.parameters.concat((ts.isClassLike(container.parent) ? container.parent.members : [])); + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + var nodes = container.members; + // If we're an accessibility modifier, we're in an instance member and should search + // the constructor's parameter list for instance members as well. + if (modifierFlag & 28 /* AccessibilityModifier */) { + var constructor = ts.find(container.members, ts.isConstructorDeclaration); + if (constructor) { + return nodes.concat(constructor.parameters); + } + } + else if (modifierFlag & 128 /* Abstract */) { + return nodes.concat([container]); + } + return nodes; + default: + ts.Debug.assertNever(container, "Invalid container kind."); + } + } + function pushKeywordIf(keywordList, token) { + var expected = []; + for (var _i = 2; _i < arguments.length; _i++) { + expected[_i - 2] = arguments[_i]; + } + if (token && ts.contains(expected, token.kind)) { + keywordList.push(token); + return true; + } + return false; + } + function getLoopBreakContinueOccurrences(loopNode) { + var keywords = []; + if (pushKeywordIf(keywords, loopNode.getFirstToken(), 89 /* ForKeyword */, 107 /* WhileKeyword */, 82 /* DoKeyword */)) { + // If we succeeded and got a do-while loop, then start looking for a 'while' keyword. + if (loopNode.kind === 223 /* DoStatement */) { + var loopTokens = loopNode.getChildren(); + for (var i = loopTokens.length - 1; i >= 0; i--) { + if (pushKeywordIf(keywords, loopTokens[i], 107 /* WhileKeyword */)) { + break; + } + } + } + } + ts.forEach(aggregateAllBreakAndContinueStatements(loopNode.statement), function (statement) { + if (ownsBreakOrContinueStatement(loopNode, statement)) { + pushKeywordIf(keywords, statement.getFirstToken(), 73 /* BreakKeyword */, 78 /* ContinueKeyword */); + } + }); + return keywords; + } + function getBreakOrContinueStatementOccurrences(breakOrContinueStatement) { + var owner = getBreakOrContinueOwner(breakOrContinueStatement); + if (owner) { + switch (owner.kind) { + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + case 223 /* DoStatement */: + case 224 /* WhileStatement */: + return getLoopBreakContinueOccurrences(owner); + case 232 /* SwitchStatement */: + return getSwitchCaseDefaultOccurrences(owner); + } + } + return undefined; + } + function getSwitchCaseDefaultOccurrences(switchStatement) { + var keywords = []; + pushKeywordIf(keywords, switchStatement.getFirstToken(), 99 /* SwitchKeyword */); + // Go through each clause in the switch statement, collecting the 'case'/'default' keywords. + ts.forEach(switchStatement.caseBlock.clauses, function (clause) { + pushKeywordIf(keywords, clause.getFirstToken(), 74 /* CaseKeyword */, 80 /* DefaultKeyword */); + ts.forEach(aggregateAllBreakAndContinueStatements(clause), function (statement) { + if (ownsBreakOrContinueStatement(switchStatement, statement)) { + pushKeywordIf(keywords, statement.getFirstToken(), 73 /* BreakKeyword */); + } + }); + }); + return keywords; + } + function getTryCatchFinallyOccurrences(tryStatement, sourceFile) { + var keywords = []; + pushKeywordIf(keywords, tryStatement.getFirstToken(), 103 /* TryKeyword */); + if (tryStatement.catchClause) { + pushKeywordIf(keywords, tryStatement.catchClause.getFirstToken(), 75 /* CatchKeyword */); + } + if (tryStatement.finallyBlock) { + var finallyKeyword = ts.findChildOfKind(tryStatement, 88 /* FinallyKeyword */, sourceFile); + pushKeywordIf(keywords, finallyKeyword, 88 /* FinallyKeyword */); + } + return keywords; + } + function getThrowOccurrences(throwStatement, sourceFile) { + var owner = getThrowStatementOwner(throwStatement); + if (!owner) { + return undefined; + } + var keywords = []; + ts.forEach(aggregateOwnedThrowStatements(owner), function (throwStatement) { + keywords.push(ts.findChildOfKind(throwStatement, 101 /* ThrowKeyword */, sourceFile)); + }); + // If the "owner" is a function, then we equate 'return' and 'throw' statements in their + // ability to "jump out" of the function, and include occurrences for both. + if (ts.isFunctionBlock(owner)) { + ts.forEachReturnStatement(owner, function (returnStatement) { + keywords.push(ts.findChildOfKind(returnStatement, 97 /* ReturnKeyword */, sourceFile)); + }); + } + return keywords; + } + function getReturnOccurrences(returnStatement, sourceFile) { + var func = ts.getContainingFunction(returnStatement); + if (!func) { + return undefined; + } + var keywords = []; + ts.forEachReturnStatement(ts.cast(func.body, ts.isBlock), function (returnStatement) { + keywords.push(ts.findChildOfKind(returnStatement, 97 /* ReturnKeyword */, sourceFile)); + }); + // Include 'throw' statements that do not occur within a try block. + ts.forEach(aggregateOwnedThrowStatements(func.body), function (throwStatement) { + keywords.push(ts.findChildOfKind(throwStatement, 101 /* ThrowKeyword */, sourceFile)); + }); + return keywords; + } + function getAsyncAndAwaitOccurrences(node) { + var func = ts.getContainingFunction(node); + if (!func) { + return undefined; + } + var keywords = []; + if (func.modifiers) { + func.modifiers.forEach(function (modifier) { + pushKeywordIf(keywords, modifier, 121 /* AsyncKeyword */); + }); + } + ts.forEachChild(func, function (child) { + traverseWithoutCrossingFunction(child, function (node) { + if (ts.isAwaitExpression(node)) { + pushKeywordIf(keywords, node.getFirstToken(), 122 /* AwaitKeyword */); + } + }); + }); + return keywords; + } + function getYieldOccurrences(node) { + var func = ts.getContainingFunction(node); + if (!func) { + return undefined; + } + var keywords = []; + ts.forEachChild(func, function (child) { + traverseWithoutCrossingFunction(child, function (node) { + if (ts.isYieldExpression(node)) { + pushKeywordIf(keywords, node.getFirstToken(), 117 /* YieldKeyword */); + } + }); + }); + return keywords; + } + // Do not cross function/class/interface/module/type boundaries. + function traverseWithoutCrossingFunction(node, cb) { + cb(node); + if (!ts.isFunctionLike(node) && !ts.isClassLike(node) && !ts.isInterfaceDeclaration(node) && !ts.isModuleDeclaration(node) && !ts.isTypeAliasDeclaration(node) && !ts.isTypeNode(node)) { + ts.forEachChild(node, function (child) { return traverseWithoutCrossingFunction(child, cb); }); + } + } + function getIfElseOccurrences(ifStatement, sourceFile) { + var keywords = getIfElseKeywords(ifStatement, sourceFile); + var result = []; + // We'd like to highlight else/ifs together if they are only separated by whitespace + // (i.e. the keywords are separated by no comments, no newlines). + for (var i = 0; i < keywords.length; i++) { + if (keywords[i].kind === 83 /* ElseKeyword */ && i < keywords.length - 1) { + var elseKeyword = keywords[i]; + var ifKeyword = keywords[i + 1]; // this *should* always be an 'if' keyword. + var shouldCombineElseAndIf = true; + // Avoid recalculating getStart() by iterating backwards. + for (var j = ifKeyword.getStart(sourceFile) - 1; j >= elseKeyword.end; j--) { + if (!ts.isWhiteSpaceSingleLine(sourceFile.text.charCodeAt(j))) { + shouldCombineElseAndIf = false; + break; + } + } + if (shouldCombineElseAndIf) { + result.push({ + fileName: sourceFile.fileName, + textSpan: ts.createTextSpanFromBounds(elseKeyword.getStart(), ifKeyword.end), + kind: "reference" /* reference */ + }); + i++; // skip the next keyword + continue; + } + } + // Ordinary case: just highlight the keyword. + result.push(getHighlightSpanForNode(keywords[i], sourceFile)); + } + return result; + } + function getIfElseKeywords(ifStatement, sourceFile) { + var keywords = []; + // Traverse upwards through all parent if-statements linked by their else-branches. + while (ts.isIfStatement(ifStatement.parent) && ifStatement.parent.elseStatement === ifStatement) { + ifStatement = ifStatement.parent; + } + // Now traverse back down through the else branches, aggregating if/else keywords of if-statements. + while (true) { + var children = ifStatement.getChildren(sourceFile); + pushKeywordIf(keywords, children[0], 91 /* IfKeyword */); + // Generally the 'else' keyword is second-to-last, so we traverse backwards. + for (var i = children.length - 1; i >= 0; i--) { + if (pushKeywordIf(keywords, children[i], 83 /* ElseKeyword */)) { + break; + } + } + if (!ifStatement.elseStatement || !ts.isIfStatement(ifStatement.elseStatement)) { + break; + } + ifStatement = ifStatement.elseStatement; + } + return keywords; + } + /** + * Whether or not a 'node' is preceded by a label of the given string. + * Note: 'node' cannot be a SourceFile. + */ + function isLabeledBy(node, labelName) { + return !!ts.findAncestor(node.parent, function (owner) { return !ts.isLabeledStatement(owner) ? "quit" : owner.label.escapedText === labelName; }); + } + })(DocumentHighlights = ts.DocumentHighlights || (ts.DocumentHighlights = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + function createDocumentRegistry(useCaseSensitiveFileNames, currentDirectory) { + return createDocumentRegistryInternal(useCaseSensitiveFileNames, currentDirectory); + } + ts.createDocumentRegistry = createDocumentRegistry; + /*@internal*/ + function createDocumentRegistryInternal(useCaseSensitiveFileNames, currentDirectory, externalCache) { + if (currentDirectory === void 0) { currentDirectory = ""; } + // Maps from compiler setting target (ES3, ES5, etc.) to all the cached documents we have + // for those settings. + var buckets = ts.createMap(); + var getCanonicalFileName = ts.createGetCanonicalFileName(!!useCaseSensitiveFileNames); + function reportStats() { + var bucketInfoArray = ts.arrayFrom(buckets.keys()).filter(function (name) { return name && name.charAt(0) === "_"; }).map(function (name) { + var entries = buckets.get(name); + var sourceFiles = []; + entries.forEach(function (entry, name) { + sourceFiles.push({ + name: name, + refCount: entry.languageServiceRefCount + }); + }); + sourceFiles.sort(function (x, y) { return y.refCount - x.refCount; }); + return { + bucket: name, + sourceFiles: sourceFiles + }; + }); + return JSON.stringify(bucketInfoArray, undefined, 2); + } + function acquireDocument(fileName, compilationSettings, scriptSnapshot, version, scriptKind) { + var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); + var key = getKeyForCompilationSettings(compilationSettings); + return acquireDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind); + } + function acquireDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind) { + return acquireOrUpdateDocument(fileName, path, compilationSettings, key, scriptSnapshot, version, /*acquiring*/ true, scriptKind); + } + function updateDocument(fileName, compilationSettings, scriptSnapshot, version, scriptKind) { + var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); + var key = getKeyForCompilationSettings(compilationSettings); + return updateDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind); + } + function updateDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind) { + return acquireOrUpdateDocument(fileName, path, compilationSettings, key, scriptSnapshot, version, /*acquiring*/ false, scriptKind); + } + function acquireOrUpdateDocument(fileName, path, compilationSettings, key, scriptSnapshot, version, acquiring, scriptKind) { + var bucket = ts.getOrUpdate(buckets, key, ts.createMap); + var entry = bucket.get(path); + var scriptTarget = scriptKind === 6 /* JSON */ ? 100 /* JSON */ : compilationSettings.target || 1 /* ES5 */; + if (!entry && externalCache) { + var sourceFile = externalCache.getDocument(key, path); + if (sourceFile) { + ts.Debug.assert(acquiring); + entry = { + sourceFile: sourceFile, + languageServiceRefCount: 0 + }; + bucket.set(path, entry); + } + } + if (!entry) { + // Have never seen this file with these settings. Create a new source file for it. + var sourceFile = ts.createLanguageServiceSourceFile(fileName, scriptSnapshot, scriptTarget, version, /*setNodeParents*/ false, scriptKind); + if (externalCache) { + externalCache.setDocument(key, path, sourceFile); + } + entry = { + sourceFile: sourceFile, + languageServiceRefCount: 1, + }; + bucket.set(path, entry); + } + else { + // We have an entry for this file. However, it may be for a different version of + // the script snapshot. If so, update it appropriately. Otherwise, we can just + // return it as is. + if (entry.sourceFile.version !== version) { + entry.sourceFile = ts.updateLanguageServiceSourceFile(entry.sourceFile, scriptSnapshot, version, scriptSnapshot.getChangeRange(entry.sourceFile.scriptSnapshot)); // TODO: GH#18217 + if (externalCache) { + externalCache.setDocument(key, path, entry.sourceFile); + } + } + // If we're acquiring, then this is the first time this LS is asking for this document. + // Increase our ref count so we know there's another LS using the document. If we're + // not acquiring, then that means the LS is 'updating' the file instead, and that means + // it has already acquired the document previously. As such, we do not need to increase + // the ref count. + if (acquiring) { + entry.languageServiceRefCount++; + } + } + ts.Debug.assert(entry.languageServiceRefCount !== 0); + return entry.sourceFile; + } + function releaseDocument(fileName, compilationSettings) { + var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); + var key = getKeyForCompilationSettings(compilationSettings); + return releaseDocumentWithKey(path, key); + } + function releaseDocumentWithKey(path, key) { + var bucket = ts.Debug.assertDefined(buckets.get(key)); + var entry = bucket.get(path); + entry.languageServiceRefCount--; + ts.Debug.assert(entry.languageServiceRefCount >= 0); + if (entry.languageServiceRefCount === 0) { + bucket.delete(path); + } + } + function getLanguageServiceRefCounts(path) { + return ts.arrayFrom(buckets.entries(), function (_a) { + var key = _a[0], bucket = _a[1]; + var entry = bucket.get(path); + return [key, entry && entry.languageServiceRefCount]; + }); + } + return { + acquireDocument: acquireDocument, + acquireDocumentWithKey: acquireDocumentWithKey, + updateDocument: updateDocument, + updateDocumentWithKey: updateDocumentWithKey, + releaseDocument: releaseDocument, + releaseDocumentWithKey: releaseDocumentWithKey, + getLanguageServiceRefCounts: getLanguageServiceRefCounts, + reportStats: reportStats, + getKeyForCompilationSettings: getKeyForCompilationSettings + }; + } + ts.createDocumentRegistryInternal = createDocumentRegistryInternal; + function getKeyForCompilationSettings(settings) { + return ts.sourceFileAffectingCompilerOptions.map(function (option) { return ts.getCompilerOptionValue(settings, option); }).join("|"); + } +})(ts || (ts = {})); +/* Code for finding imports of an exported symbol. Used only by FindAllReferences. */ +/* @internal */ +var ts; +(function (ts) { + var FindAllReferences; + (function (FindAllReferences) { + /** Creates the imports map and returns an ImportTracker that uses it. Call this lazily to avoid calling `getDirectImportsMap` unnecessarily. */ + function createImportTracker(sourceFiles, sourceFilesSet, checker, cancellationToken) { + var allDirectImports = getDirectImportsMap(sourceFiles, checker, cancellationToken); + return function (exportSymbol, exportInfo, isForRename) { + var _a = getImportersForExport(sourceFiles, sourceFilesSet, allDirectImports, exportInfo, checker, cancellationToken), directImports = _a.directImports, indirectUsers = _a.indirectUsers; + return __assign({ indirectUsers: indirectUsers }, getSearchesFromDirectImports(directImports, exportSymbol, exportInfo.exportKind, checker, isForRename)); + }; + } + FindAllReferences.createImportTracker = createImportTracker; + var ExportKind; + (function (ExportKind) { + ExportKind[ExportKind["Named"] = 0] = "Named"; + ExportKind[ExportKind["Default"] = 1] = "Default"; + ExportKind[ExportKind["ExportEquals"] = 2] = "ExportEquals"; + })(ExportKind = FindAllReferences.ExportKind || (FindAllReferences.ExportKind = {})); + var ImportExport; + (function (ImportExport) { + ImportExport[ImportExport["Import"] = 0] = "Import"; + ImportExport[ImportExport["Export"] = 1] = "Export"; + })(ImportExport = FindAllReferences.ImportExport || (FindAllReferences.ImportExport = {})); + /** Returns import statements that directly reference the exporting module, and a list of files that may access the module through a namespace. */ + function getImportersForExport(sourceFiles, sourceFilesSet, allDirectImports, _a, checker, cancellationToken) { + var exportingModuleSymbol = _a.exportingModuleSymbol, exportKind = _a.exportKind; + var markSeenDirectImport = ts.nodeSeenTracker(); + var markSeenIndirectUser = ts.nodeSeenTracker(); + var directImports = []; + var isAvailableThroughGlobal = !!exportingModuleSymbol.globalExports; + var indirectUserDeclarations = isAvailableThroughGlobal ? undefined : []; + handleDirectImports(exportingModuleSymbol); + return { directImports: directImports, indirectUsers: getIndirectUsers() }; + function getIndirectUsers() { + if (isAvailableThroughGlobal) { + // It has `export as namespace`, so anything could potentially use it. + return sourceFiles; + } + // Module augmentations may use this module's exports without importing it. + for (var _i = 0, _a = exportingModuleSymbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + if (ts.isExternalModuleAugmentation(decl) && sourceFilesSet.has(decl.getSourceFile().fileName)) { + addIndirectUser(decl); + } + } + // This may return duplicates (if there are multiple module declarations in a single source file, all importing the same thing as a namespace), but `State.markSearchedSymbol` will handle that. + return indirectUserDeclarations.map(ts.getSourceFileOfNode); + } + function handleDirectImports(exportingModuleSymbol) { + var theseDirectImports = getDirectImports(exportingModuleSymbol); + if (theseDirectImports) { + for (var _i = 0, theseDirectImports_1 = theseDirectImports; _i < theseDirectImports_1.length; _i++) { + var direct = theseDirectImports_1[_i]; + if (!markSeenDirectImport(direct)) { + continue; + } + if (cancellationToken) + cancellationToken.throwIfCancellationRequested(); + switch (direct.kind) { + case 191 /* CallExpression */: + if (!isAvailableThroughGlobal) { + var parent = direct.parent; + if (exportKind === 2 /* ExportEquals */ && parent.kind === 237 /* VariableDeclaration */) { + var name = parent.name; + if (name.kind === 72 /* Identifier */) { + directImports.push(name); + break; + } + } + // Don't support re-exporting 'require()' calls, so just add a single indirect user. + addIndirectUser(direct.getSourceFile()); + } + break; + case 72 /* Identifier */: // for 'const x = require("y"); + break; // TODO: GH#23879 + case 248 /* ImportEqualsDeclaration */: + handleNamespaceImport(direct, direct.name, ts.hasModifier(direct, 1 /* Export */), /*alreadyAddedDirect*/ false); + break; + case 249 /* ImportDeclaration */: + directImports.push(direct); + var namedBindings = direct.importClause && direct.importClause.namedBindings; + if (namedBindings && namedBindings.kind === 251 /* NamespaceImport */) { + handleNamespaceImport(direct, namedBindings.name, /*isReExport*/ false, /*alreadyAddedDirect*/ true); + } + else if (!isAvailableThroughGlobal && ts.isDefaultImport(direct)) { + addIndirectUser(getSourceFileLikeForImportDeclaration(direct)); // Add a check for indirect uses to handle synthetic default imports + } + break; + case 255 /* ExportDeclaration */: + if (!direct.exportClause) { + // This is `export * from "foo"`, so imports of this module may import the export too. + handleDirectImports(getContainingModuleSymbol(direct, checker)); + } + else { + // This is `export { foo } from "foo"` and creates an alias symbol, so recursive search will get handle re-exports. + directImports.push(direct); + } + break; + case 183 /* ImportType */: + directImports.push(direct); + break; + default: + ts.Debug.assertNever(direct, "Unexpected import kind: " + ts.Debug.showSyntaxKind(direct)); + } + } + } + } + function handleNamespaceImport(importDeclaration, name, isReExport, alreadyAddedDirect) { + if (exportKind === 2 /* ExportEquals */) { + // This is a direct import, not import-as-namespace. + if (!alreadyAddedDirect) + directImports.push(importDeclaration); + } + else if (!isAvailableThroughGlobal) { + var sourceFileLike = getSourceFileLikeForImportDeclaration(importDeclaration); + ts.Debug.assert(sourceFileLike.kind === 279 /* SourceFile */ || sourceFileLike.kind === 244 /* ModuleDeclaration */); + if (isReExport || findNamespaceReExports(sourceFileLike, name, checker)) { + addIndirectUsers(sourceFileLike); + } + else { + addIndirectUser(sourceFileLike); + } + } + } + function addIndirectUser(sourceFileLike) { + ts.Debug.assert(!isAvailableThroughGlobal); + var isNew = markSeenIndirectUser(sourceFileLike); + if (isNew) { + indirectUserDeclarations.push(sourceFileLike); // TODO: GH#18217 + } + return isNew; + } + /** Adds a module and all of its transitive dependencies as possible indirect users. */ + function addIndirectUsers(sourceFileLike) { + if (!addIndirectUser(sourceFileLike)) { + return; + } + var moduleSymbol = checker.getMergedSymbol(sourceFileLike.symbol); + ts.Debug.assert(!!(moduleSymbol.flags & 1536 /* Module */)); + var directImports = getDirectImports(moduleSymbol); + if (directImports) { + for (var _i = 0, directImports_1 = directImports; _i < directImports_1.length; _i++) { + var directImport = directImports_1[_i]; + addIndirectUsers(getSourceFileLikeForImportDeclaration(directImport)); + } + } + } + function getDirectImports(moduleSymbol) { + return allDirectImports.get(ts.getSymbolId(moduleSymbol).toString()); + } + } + /** + * Given the set of direct imports of a module, we need to find which ones import the particular exported symbol. + * The returned `importSearches` will result in the entire source file being searched. + * But re-exports will be placed in 'singleReferences' since they cannot be locally referenced. + */ + function getSearchesFromDirectImports(directImports, exportSymbol, exportKind, checker, isForRename) { + var importSearches = []; + var singleReferences = []; + function addSearch(location, symbol) { + importSearches.push([location, symbol]); + } + if (directImports) { + for (var _i = 0, directImports_2 = directImports; _i < directImports_2.length; _i++) { + var decl = directImports_2[_i]; + handleImport(decl); + } + } + return { importSearches: importSearches, singleReferences: singleReferences }; + function handleImport(decl) { + if (decl.kind === 248 /* ImportEqualsDeclaration */) { + if (isExternalModuleImportEquals(decl)) { + handleNamespaceImportLike(decl.name); + } + return; + } + if (decl.kind === 72 /* Identifier */) { + handleNamespaceImportLike(decl); + return; + } + if (decl.kind === 183 /* ImportType */) { + if (decl.qualifier) { + if (ts.isIdentifier(decl.qualifier) && decl.qualifier.escapedText === ts.symbolName(exportSymbol)) { + singleReferences.push(decl.qualifier); + } + } + else if (exportKind === 2 /* ExportEquals */) { + singleReferences.push(decl.argument.literal); + } + return; + } + // Ignore if there's a grammar error + if (decl.moduleSpecifier.kind !== 10 /* StringLiteral */) { + return; + } + if (decl.kind === 255 /* ExportDeclaration */) { + searchForNamedImport(decl.exportClause); + return; + } + var _a = decl.importClause || { name: undefined, namedBindings: undefined }, name = _a.name, namedBindings = _a.namedBindings; + if (namedBindings) { + switch (namedBindings.kind) { + case 251 /* NamespaceImport */: + handleNamespaceImportLike(namedBindings.name); + break; + case 252 /* NamedImports */: + // 'default' might be accessed as a named import `{ default as foo }`. + if (exportKind === 0 /* Named */ || exportKind === 1 /* Default */) { + searchForNamedImport(namedBindings); + } + break; + default: + ts.Debug.assertNever(namedBindings); + } + } + // `export =` might be imported by a default import if `--allowSyntheticDefaultImports` is on, so this handles both ExportKind.Default and ExportKind.ExportEquals. + // If a default import has the same name as the default export, allow to rename it. + // Given `import f` and `export default function f`, we will rename both, but for `import g` we will rename just that. + if (name && (exportKind === 1 /* Default */ || exportKind === 2 /* ExportEquals */) && (!isForRename || name.escapedText === ts.symbolEscapedNameNoDefault(exportSymbol))) { + var defaultImportAlias = checker.getSymbolAtLocation(name); + addSearch(name, defaultImportAlias); + } + } + /** + * `import x = require("./x") or `import * as x from "./x"`. + * An `export =` may be imported by this syntax, so it may be a direct import. + * If it's not a direct import, it will be in `indirectUsers`, so we don't have to do anything here. + */ + function handleNamespaceImportLike(importName) { + // Don't rename an import that already has a different name than the export. + if (exportKind === 2 /* ExportEquals */ && (!isForRename || isNameMatch(importName.escapedText))) { + addSearch(importName, checker.getSymbolAtLocation(importName)); + } + } + function searchForNamedImport(namedBindings) { + if (!namedBindings) { + return; + } + for (var _i = 0, _a = namedBindings.elements; _i < _a.length; _i++) { + var element = _a[_i]; + var name = element.name, propertyName = element.propertyName; + if (!isNameMatch((propertyName || name).escapedText)) { + continue; + } + if (propertyName) { + // This is `import { foo as bar } from "./a"` or `export { foo as bar } from "./a"`. `foo` isn't a local in the file, so just add it as a single reference. + singleReferences.push(propertyName); + // If renaming `{ foo as bar }`, don't touch `bar`, just `foo`. + // But do rename `foo` in ` { default as foo }` if that's the original export name. + if (!isForRename || name.escapedText === exportSymbol.escapedName) { + // Search locally for `bar`. + addSearch(name, checker.getSymbolAtLocation(name)); + } + } + else { + var localSymbol = element.kind === 257 /* ExportSpecifier */ && element.propertyName + ? checker.getExportSpecifierLocalTargetSymbol(element) // For re-exporting under a different name, we want to get the re-exported symbol. + : checker.getSymbolAtLocation(name); + addSearch(name, localSymbol); + } + } + } + function isNameMatch(name) { + // Use name of "default" even in `export =` case because we may have allowSyntheticDefaultImports + return name === exportSymbol.escapedName || exportKind !== 0 /* Named */ && name === "default" /* Default */; + } + } + /** Returns 'true' is the namespace 'name' is re-exported from this module, and 'false' if it is only used locally. */ + function findNamespaceReExports(sourceFileLike, name, checker) { + var namespaceImportSymbol = checker.getSymbolAtLocation(name); + return !!forEachPossibleImportOrExportStatement(sourceFileLike, function (statement) { + if (!ts.isExportDeclaration(statement)) + return; + var exportClause = statement.exportClause, moduleSpecifier = statement.moduleSpecifier; + return !moduleSpecifier && exportClause && + exportClause.elements.some(function (element) { return checker.getExportSpecifierLocalTargetSymbol(element) === namespaceImportSymbol; }); + }); + } + function findModuleReferences(program, sourceFiles, searchModuleSymbol) { + var refs = []; + var checker = program.getTypeChecker(); + for (var _i = 0, sourceFiles_3 = sourceFiles; _i < sourceFiles_3.length; _i++) { + var referencingFile = sourceFiles_3[_i]; + var searchSourceFile = searchModuleSymbol.valueDeclaration; + if (searchSourceFile.kind === 279 /* SourceFile */) { + for (var _a = 0, _b = referencingFile.referencedFiles; _a < _b.length; _a++) { + var ref = _b[_a]; + if (program.getSourceFileFromReference(referencingFile, ref) === searchSourceFile) { + refs.push({ kind: "reference", referencingFile: referencingFile, ref: ref }); + } + } + for (var _c = 0, _d = referencingFile.typeReferenceDirectives; _c < _d.length; _c++) { + var ref = _d[_c]; + var referenced = program.getResolvedTypeReferenceDirectives().get(ref.fileName); + if (referenced !== undefined && referenced.resolvedFileName === searchSourceFile.fileName) { + refs.push({ kind: "reference", referencingFile: referencingFile, ref: ref }); + } + } + } + forEachImport(referencingFile, function (_importDecl, moduleSpecifier) { + var moduleSymbol = checker.getSymbolAtLocation(moduleSpecifier); + if (moduleSymbol === searchModuleSymbol) { + refs.push({ kind: "import", literal: moduleSpecifier }); + } + }); + } + return refs; + } + FindAllReferences.findModuleReferences = findModuleReferences; + /** Returns a map from a module symbol Id to all import statements that directly reference the module. */ + function getDirectImportsMap(sourceFiles, checker, cancellationToken) { + var map = ts.createMap(); + for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) { + var sourceFile = sourceFiles_4[_i]; + if (cancellationToken) + cancellationToken.throwIfCancellationRequested(); + forEachImport(sourceFile, function (importDecl, moduleSpecifier) { + var moduleSymbol = checker.getSymbolAtLocation(moduleSpecifier); + if (moduleSymbol) { + var id = ts.getSymbolId(moduleSymbol).toString(); + var imports = map.get(id); + if (!imports) { + map.set(id, imports = []); + } + imports.push(importDecl); + } + }); + } + return map; + } + /** Iterates over all statements at the top level or in module declarations. Returns the first truthy result. */ + function forEachPossibleImportOrExportStatement(sourceFileLike, action) { + return ts.forEach(sourceFileLike.kind === 279 /* SourceFile */ ? sourceFileLike.statements : sourceFileLike.body.statements, function (statement) { + return action(statement) || (isAmbientModuleDeclaration(statement) && ts.forEach(statement.body && statement.body.statements, action)); + }); + } + /** Calls `action` for each import, re-export, or require() in a file. */ + function forEachImport(sourceFile, action) { + if (sourceFile.externalModuleIndicator || sourceFile.imports !== undefined) { + for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { + var i = _a[_i]; + action(ts.importFromModuleSpecifier(i), i); + } + } + else { + forEachPossibleImportOrExportStatement(sourceFile, function (statement) { + switch (statement.kind) { + case 255 /* ExportDeclaration */: + case 249 /* ImportDeclaration */: { + var decl = statement; + if (decl.moduleSpecifier && ts.isStringLiteral(decl.moduleSpecifier)) { + action(decl, decl.moduleSpecifier); + } + break; + } + case 248 /* ImportEqualsDeclaration */: { + var decl = statement; + if (isExternalModuleImportEquals(decl)) { + action(decl, decl.moduleReference.expression); + } + break; + } + } + }); + } + } + /** + * Given a local reference, we might notice that it's an import/export and recursively search for references of that. + * If at an import, look locally for the symbol it imports. + * If an an export, look for all imports of it. + * This doesn't handle export specifiers; that is done in `getReferencesAtExportSpecifier`. + * @param comingFromExport If we are doing a search for all exports, don't bother looking backwards for the imported symbol, since that's the reason we're here. + */ + function getImportOrExportSymbol(node, symbol, checker, comingFromExport) { + return comingFromExport ? getExport() : getExport() || getImport(); + function getExport() { + var parent = node.parent; + var grandParent = parent.parent; + if (symbol.exportSymbol) { + if (parent.kind === 189 /* PropertyAccessExpression */) { + // When accessing an export of a JS module, there's no alias. The symbol will still be flagged as an export even though we're at the use. + // So check that we are at the declaration. + return symbol.declarations.some(function (d) { return d === parent; }) && ts.isBinaryExpression(grandParent) + ? getSpecialPropertyExport(grandParent, /*useLhsSymbol*/ false) + : undefined; + } + else { + return exportInfo(symbol.exportSymbol, getExportKindForDeclaration(parent)); + } + } + else { + var exportNode = getExportNode(parent, node); + if (exportNode && ts.hasModifier(exportNode, 1 /* Export */)) { + if (ts.isImportEqualsDeclaration(exportNode) && exportNode.moduleReference === node) { + // We're at `Y` in `export import X = Y`. This is not the exported symbol, the left-hand-side is. So treat this as an import statement. + if (comingFromExport) { + return undefined; + } + var lhsSymbol = checker.getSymbolAtLocation(exportNode.name); + return { kind: 0 /* Import */, symbol: lhsSymbol }; + } + else { + return exportInfo(symbol, getExportKindForDeclaration(exportNode)); + } + } + // If we are in `export = a;` or `export default a;`, `parent` is the export assignment. + else if (ts.isExportAssignment(parent)) { + return getExportAssignmentExport(parent); + } + // If we are in `export = class A {};` (or `export = class A {};`) at `A`, `parent.parent` is the export assignment. + else if (ts.isExportAssignment(grandParent)) { + return getExportAssignmentExport(grandParent); + } + // Similar for `module.exports =` and `exports.A =`. + else if (ts.isBinaryExpression(parent)) { + return getSpecialPropertyExport(parent, /*useLhsSymbol*/ true); + } + else if (ts.isBinaryExpression(grandParent)) { + return getSpecialPropertyExport(grandParent, /*useLhsSymbol*/ true); + } + else if (ts.isJSDocTypedefTag(parent)) { + return exportInfo(symbol, 0 /* Named */); + } + } + function getExportAssignmentExport(ex) { + // Get the symbol for the `export =` node; its parent is the module it's the export of. + var exportingModuleSymbol = ts.Debug.assertDefined(ex.symbol.parent, "Expected export symbol to have a parent"); + var exportKind = ex.isExportEquals ? 2 /* ExportEquals */ : 1 /* Default */; + return { kind: 1 /* Export */, symbol: symbol, exportInfo: { exportingModuleSymbol: exportingModuleSymbol, exportKind: exportKind } }; + } + function getSpecialPropertyExport(node, useLhsSymbol) { + var kind; + switch (ts.getAssignmentDeclarationKind(node)) { + case 1 /* ExportsProperty */: + kind = 0 /* Named */; + break; + case 2 /* ModuleExports */: + kind = 2 /* ExportEquals */; + break; + default: + return undefined; + } + var sym = useLhsSymbol ? checker.getSymbolAtLocation(ts.cast(node.left, ts.isPropertyAccessExpression).name) : symbol; + // Better detection for GH#20803 + if (sym && !(checker.getMergedSymbol(sym.parent).flags & 1536 /* Module */)) { + ts.Debug.fail("Special property assignment kind does not have a module as its parent. Assignment is " + ts.Debug.showSymbol(sym) + ", parent is " + ts.Debug.showSymbol(sym.parent)); + } + return sym && exportInfo(sym, kind); + } + } + function getImport() { + var isImport = isNodeImport(node); + if (!isImport) + return undefined; + // A symbol being imported is always an alias. So get what that aliases to find the local symbol. + var importedSymbol = checker.getImmediateAliasedSymbol(symbol); + if (!importedSymbol) + return undefined; + // Search on the local symbol in the exporting module, not the exported symbol. + importedSymbol = skipExportSpecifierSymbol(importedSymbol, checker); + // Similarly, skip past the symbol for 'export =' + if (importedSymbol.escapedName === "export=") { + importedSymbol = getExportEqualsLocalSymbol(importedSymbol, checker); + } + // If the import has a different name than the export, do not continue searching. + // If `importedName` is undefined, do continue searching as the export is anonymous. + // (All imports returned from this function will be ignored anyway if we are in rename and this is a not a named export.) + var importedName = ts.symbolEscapedNameNoDefault(importedSymbol); + if (importedName === undefined || importedName === "default" /* Default */ || importedName === symbol.escapedName) { + return { kind: 0 /* Import */, symbol: importedSymbol }; + } + } + function exportInfo(symbol, kind) { + var exportInfo = getExportInfo(symbol, kind, checker); + return exportInfo && { kind: 1 /* Export */, symbol: symbol, exportInfo: exportInfo }; + } + // Not meant for use with export specifiers or export assignment. + function getExportKindForDeclaration(node) { + return ts.hasModifier(node, 512 /* Default */) ? 1 /* Default */ : 0 /* Named */; + } + } + FindAllReferences.getImportOrExportSymbol = getImportOrExportSymbol; + function getExportEqualsLocalSymbol(importedSymbol, checker) { + if (importedSymbol.flags & 2097152 /* Alias */) { + return ts.Debug.assertDefined(checker.getImmediateAliasedSymbol(importedSymbol)); + } + var decl = importedSymbol.valueDeclaration; + if (ts.isExportAssignment(decl)) { // `export = class {}` + return ts.Debug.assertDefined(decl.expression.symbol); + } + else if (ts.isBinaryExpression(decl)) { // `module.exports = class {}` + return ts.Debug.assertDefined(decl.right.symbol); + } + else if (ts.isSourceFile(decl)) { // json module + return ts.Debug.assertDefined(decl.symbol); + } + return ts.Debug.fail(); + } + // If a reference is a class expression, the exported node would be its parent. + // If a reference is a variable declaration, the exported node would be the variable statement. + function getExportNode(parent, node) { + if (parent.kind === 237 /* VariableDeclaration */) { + var p = parent; + return p.name !== node ? undefined : + p.parent.kind === 274 /* CatchClause */ ? undefined : p.parent.parent.kind === 219 /* VariableStatement */ ? p.parent.parent : undefined; + } + else { + return parent; + } + } + function isNodeImport(node) { + var parent = node.parent; + switch (parent.kind) { + case 248 /* ImportEqualsDeclaration */: + return parent.name === node && isExternalModuleImportEquals(parent); + case 253 /* ImportSpecifier */: + // For a rename import `{ foo as bar }`, don't search for the imported symbol. Just find local uses of `bar`. + return !parent.propertyName; + case 250 /* ImportClause */: + case 251 /* NamespaceImport */: + ts.Debug.assert(parent.name === node); + return true; + default: + return false; + } + } + function getExportInfo(exportSymbol, exportKind, checker) { + var moduleSymbol = exportSymbol.parent; + if (!moduleSymbol) + return undefined; // This can happen if an `export` is not at the top-level (which is a compile error). + var exportingModuleSymbol = checker.getMergedSymbol(moduleSymbol); // Need to get merged symbol in case there's an augmentation. + // `export` may appear in a namespace. In that case, just rely on global search. + return ts.isExternalModuleSymbol(exportingModuleSymbol) ? { exportingModuleSymbol: exportingModuleSymbol, exportKind: exportKind } : undefined; + } + FindAllReferences.getExportInfo = getExportInfo; + /** If at an export specifier, go to the symbol it refers to. */ + function skipExportSpecifierSymbol(symbol, checker) { + // For `export { foo } from './bar", there's nothing to skip, because it does not create a new alias. But `export { foo } does. + if (symbol.declarations) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (ts.isExportSpecifier(declaration) && !declaration.propertyName && !declaration.parent.parent.moduleSpecifier) { + return checker.getExportSpecifierLocalTargetSymbol(declaration); + } + } + } + return symbol; + } + function getContainingModuleSymbol(importer, checker) { + return checker.getMergedSymbol(getSourceFileLikeForImportDeclaration(importer).symbol); + } + function getSourceFileLikeForImportDeclaration(node) { + if (node.kind === 191 /* CallExpression */) { + return node.getSourceFile(); + } + var parent = node.parent; + if (parent.kind === 279 /* SourceFile */) { + return parent; + } + ts.Debug.assert(parent.kind === 245 /* ModuleBlock */); + return ts.cast(parent.parent, isAmbientModuleDeclaration); + } + function isAmbientModuleDeclaration(node) { + return node.kind === 244 /* ModuleDeclaration */ && node.name.kind === 10 /* StringLiteral */; + } + function isExternalModuleImportEquals(eq) { + return eq.moduleReference.kind === 259 /* ExternalModuleReference */ && eq.moduleReference.expression.kind === 10 /* StringLiteral */; + } + })(FindAllReferences = ts.FindAllReferences || (ts.FindAllReferences = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var FindAllReferences; + (function (FindAllReferences) { + var DefinitionKind; + (function (DefinitionKind) { + DefinitionKind[DefinitionKind["Symbol"] = 0] = "Symbol"; + DefinitionKind[DefinitionKind["Label"] = 1] = "Label"; + DefinitionKind[DefinitionKind["Keyword"] = 2] = "Keyword"; + DefinitionKind[DefinitionKind["This"] = 3] = "This"; + DefinitionKind[DefinitionKind["String"] = 4] = "String"; + })(DefinitionKind = FindAllReferences.DefinitionKind || (FindAllReferences.DefinitionKind = {})); + var EntryKind; + (function (EntryKind) { + EntryKind[EntryKind["Span"] = 0] = "Span"; + EntryKind[EntryKind["Node"] = 1] = "Node"; + EntryKind[EntryKind["StringLiteral"] = 2] = "StringLiteral"; + EntryKind[EntryKind["SearchedLocalFoundProperty"] = 3] = "SearchedLocalFoundProperty"; + EntryKind[EntryKind["SearchedPropertyFoundLocal"] = 4] = "SearchedPropertyFoundLocal"; + })(EntryKind = FindAllReferences.EntryKind || (FindAllReferences.EntryKind = {})); + function nodeEntry(node, kind) { + if (kind === void 0) { kind = 1 /* Node */; } + return { kind: kind, node: node.name || node }; + } + FindAllReferences.nodeEntry = nodeEntry; + function findReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position) { + var node = ts.getTouchingPropertyName(sourceFile, position); + var referencedSymbols = FindAllReferences.Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken); + var checker = program.getTypeChecker(); + return !referencedSymbols || !referencedSymbols.length ? undefined : ts.mapDefined(referencedSymbols, function (_a) { + var definition = _a.definition, references = _a.references; + // Only include referenced symbols that have a valid definition. + return definition && { + definition: checker.runWithCancellationToken(cancellationToken, function (checker) { return definitionToReferencedSymbolDefinitionInfo(definition, checker, node); }), + references: references.map(toReferenceEntry) + }; + }); + } + FindAllReferences.findReferencedSymbols = findReferencedSymbols; + function getImplementationsAtPosition(program, cancellationToken, sourceFiles, sourceFile, position) { + var node = ts.getTouchingPropertyName(sourceFile, position); + var referenceEntries = getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node, position); + var checker = program.getTypeChecker(); + return ts.map(referenceEntries, function (entry) { return toImplementationLocation(entry, checker); }); + } + FindAllReferences.getImplementationsAtPosition = getImplementationsAtPosition; + function getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node, position) { + if (node.kind === 279 /* SourceFile */) { + return undefined; + } + var checker = program.getTypeChecker(); + // If invoked directly on a shorthand property assignment, then return + // the declaration of the symbol being assigned (not the symbol being assigned to). + if (node.parent.kind === 276 /* ShorthandPropertyAssignment */) { + var result_7 = []; + FindAllReferences.Core.getReferenceEntriesForShorthandPropertyAssignment(node, checker, function (node) { return result_7.push(nodeEntry(node)); }); + return result_7; + } + else if (node.kind === 98 /* SuperKeyword */ || ts.isSuperProperty(node.parent)) { + // References to and accesses on the super keyword only have one possible implementation, so no + // need to "Find all References" + var symbol = checker.getSymbolAtLocation(node); + return symbol.valueDeclaration && [nodeEntry(symbol.valueDeclaration)]; + } + else { + // Perform "Find all References" and retrieve only those that are implementations + return getReferenceEntriesForNode(position, node, program, sourceFiles, cancellationToken, { implementations: true }); + } + } + function findReferenceOrRenameEntries(program, cancellationToken, sourceFiles, node, position, options, convertEntry) { + return ts.map(flattenEntries(FindAllReferences.Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options)), function (entry) { return convertEntry(entry, node, program.getTypeChecker()); }); + } + FindAllReferences.findReferenceOrRenameEntries = findReferenceOrRenameEntries; + function getReferenceEntriesForNode(position, node, program, sourceFiles, cancellationToken, options, sourceFilesSet) { + if (options === void 0) { options = {}; } + if (sourceFilesSet === void 0) { sourceFilesSet = ts.arrayToSet(sourceFiles, function (f) { return f.fileName; }); } + return flattenEntries(FindAllReferences.Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options, sourceFilesSet)); + } + FindAllReferences.getReferenceEntriesForNode = getReferenceEntriesForNode; + function flattenEntries(referenceSymbols) { + return referenceSymbols && ts.flatMap(referenceSymbols, function (r) { return r.references; }); + } + function definitionToReferencedSymbolDefinitionInfo(def, checker, originalNode) { + var info = (function () { + switch (def.type) { + case 0 /* Symbol */: { + var symbol = def.symbol; + var _a = getDefinitionKindAndDisplayParts(symbol, checker, originalNode), displayParts_1 = _a.displayParts, kind_1 = _a.kind; + var name_3 = displayParts_1.map(function (p) { return p.text; }).join(""); + return { node: symbol.declarations ? ts.getNameOfDeclaration(ts.first(symbol.declarations)) || ts.first(symbol.declarations) : originalNode, name: name_3, kind: kind_1, displayParts: displayParts_1 }; + } + case 1 /* Label */: { + var node_3 = def.node; + return { node: node_3, name: node_3.text, kind: "label" /* label */, displayParts: [ts.displayPart(node_3.text, ts.SymbolDisplayPartKind.text)] }; + } + case 2 /* Keyword */: { + var node_4 = def.node; + var name_4 = ts.tokenToString(node_4.kind); + return { node: node_4, name: name_4, kind: "keyword" /* keyword */, displayParts: [{ text: name_4, kind: "keyword" /* keyword */ }] }; + } + case 3 /* This */: { + var node_5 = def.node; + var symbol = checker.getSymbolAtLocation(node_5); + var displayParts_2 = symbol && ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, node_5.getSourceFile(), ts.getContainerNode(node_5), node_5).displayParts || [ts.textPart("this")]; + return { node: node_5, name: "this", kind: "var" /* variableElement */, displayParts: displayParts_2 }; + } + case 4 /* String */: { + var node_6 = def.node; + return { node: node_6, name: node_6.text, kind: "var" /* variableElement */, displayParts: [ts.displayPart(ts.getTextOfNode(node_6), ts.SymbolDisplayPartKind.stringLiteral)] }; + } + default: + return ts.Debug.assertNever(def); + } + })(); + var node = info.node, name = info.name, kind = info.kind, displayParts = info.displayParts; + var sourceFile = node.getSourceFile(); + return { containerKind: "" /* unknown */, containerName: "", fileName: sourceFile.fileName, kind: kind, name: name, textSpan: getTextSpan(ts.isComputedPropertyName(node) ? node.expression : node, sourceFile), displayParts: displayParts }; + } + function getDefinitionKindAndDisplayParts(symbol, checker, node) { + var meaning = FindAllReferences.Core.getIntersectingMeaningFromDeclarations(node, symbol); + var enclosingDeclaration = symbol.declarations && ts.firstOrUndefined(symbol.declarations) || node; + var _a = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, enclosingDeclaration.getSourceFile(), enclosingDeclaration, enclosingDeclaration, meaning), displayParts = _a.displayParts, symbolKind = _a.symbolKind; + return { displayParts: displayParts, kind: symbolKind }; + } + function toRenameLocation(entry, originalNode, checker) { + return __assign({}, entryToDocumentSpan(entry), getPrefixAndSuffixText(entry, originalNode, checker)); + } + FindAllReferences.toRenameLocation = toRenameLocation; + function toReferenceEntry(entry) { + var _a = entryToDocumentSpan(entry), textSpan = _a.textSpan, fileName = _a.fileName; + if (entry.kind === 0 /* Span */) { + return { textSpan: textSpan, fileName: fileName, isWriteAccess: false, isDefinition: false }; + } + var kind = entry.kind, node = entry.node; + return { + textSpan: textSpan, + fileName: fileName, + isWriteAccess: isWriteAccessForReference(node), + isDefinition: node.kind === 80 /* DefaultKeyword */ + || !!ts.getDeclarationFromName(node) + || ts.isLiteralComputedPropertyDeclarationName(node), + isInString: kind === 2 /* StringLiteral */ ? true : undefined, + }; + } + FindAllReferences.toReferenceEntry = toReferenceEntry; + function entryToDocumentSpan(entry) { + if (entry.kind === 0 /* Span */) { + return { textSpan: entry.textSpan, fileName: entry.fileName }; + } + else { + var sourceFile = entry.node.getSourceFile(); + return { textSpan: getTextSpan(entry.node, sourceFile), fileName: sourceFile.fileName }; + } + } + function getPrefixAndSuffixText(entry, originalNode, checker) { + if (entry.kind !== 0 /* Span */ && ts.isIdentifier(originalNode)) { + var node = entry.node, kind = entry.kind; + var name = originalNode.text; + var isShorthandAssignment = ts.isShorthandPropertyAssignment(node.parent); + if (isShorthandAssignment || ts.isObjectBindingElementWithoutPropertyName(node.parent)) { + var prefixColon = { prefixText: name + ": " }; + var suffixColon = { suffixText: ": " + name }; + return kind === 3 /* SearchedLocalFoundProperty */ ? prefixColon + : kind === 4 /* SearchedPropertyFoundLocal */ ? suffixColon + // In `const o = { x }; o.x`, symbolAtLocation at `x` in `{ x }` is the property symbol. + // For a binding element `const { x } = o;`, symbolAtLocation at `x` is the property symbol. + : isShorthandAssignment ? suffixColon : prefixColon; + } + else if (ts.isImportSpecifier(entry.node.parent) && !entry.node.parent.propertyName) { + // If the original symbol was using this alias, just rename the alias. + var originalSymbol = ts.isExportSpecifier(originalNode.parent) ? checker.getExportSpecifierLocalTargetSymbol(originalNode.parent) : checker.getSymbolAtLocation(originalNode); + return ts.contains(originalSymbol.declarations, entry.node.parent) ? { prefixText: name + " as " } : ts.emptyOptions; + } + else if (ts.isExportSpecifier(entry.node.parent) && !entry.node.parent.propertyName) { + return originalNode === entry.node ? { prefixText: name + " as " } : { suffixText: " as " + name }; + } + } + return ts.emptyOptions; + } + function toImplementationLocation(entry, checker) { + if (entry.kind !== 0 /* Span */) { + var node = entry.node; + var sourceFile = node.getSourceFile(); + return __assign({ textSpan: getTextSpan(node, sourceFile), fileName: sourceFile.fileName }, implementationKindDisplayParts(node, checker)); + } + else { + var textSpan = entry.textSpan, fileName = entry.fileName; + return { textSpan: textSpan, fileName: fileName, kind: "" /* unknown */, displayParts: [] }; + } + } + function implementationKindDisplayParts(node, checker) { + var symbol = checker.getSymbolAtLocation(ts.isDeclaration(node) && node.name ? node.name : node); + if (symbol) { + return getDefinitionKindAndDisplayParts(symbol, checker, node); + } + else if (node.kind === 188 /* ObjectLiteralExpression */) { + return { + kind: "interface" /* interfaceElement */, + displayParts: [ts.punctuationPart(20 /* OpenParenToken */), ts.textPart("object literal"), ts.punctuationPart(21 /* CloseParenToken */)] + }; + } + else if (node.kind === 209 /* ClassExpression */) { + return { + kind: "local class" /* localClassElement */, + displayParts: [ts.punctuationPart(20 /* OpenParenToken */), ts.textPart("anonymous local class"), ts.punctuationPart(21 /* CloseParenToken */)] + }; + } + else { + return { kind: ts.getNodeKind(node), displayParts: [] }; + } + } + function toHighlightSpan(entry) { + if (entry.kind === 0 /* Span */) { + var fileName = entry.fileName, textSpan = entry.textSpan; + return { fileName: fileName, span: { textSpan: textSpan, kind: "reference" /* reference */ } }; + } + var node = entry.node, kind = entry.kind; + var sourceFile = node.getSourceFile(); + var writeAccess = isWriteAccessForReference(node); + var span = { + textSpan: getTextSpan(node, sourceFile), + kind: writeAccess ? "writtenReference" /* writtenReference */ : "reference" /* reference */, + isInString: kind === 2 /* StringLiteral */ ? true : undefined, + }; + return { fileName: sourceFile.fileName, span: span }; + } + FindAllReferences.toHighlightSpan = toHighlightSpan; + function getTextSpan(node, sourceFile) { + var start = node.getStart(sourceFile); + var end = node.getEnd(); + if (node.kind === 10 /* StringLiteral */) { + start += 1; + end -= 1; + } + return ts.createTextSpanFromBounds(start, end); + } + /** A node is considered a writeAccess iff it is a name of a declaration or a target of an assignment */ + function isWriteAccessForReference(node) { + var decl = ts.getDeclarationFromName(node); + return !!decl && declarationIsWriteAccess(decl) || node.kind === 80 /* DefaultKeyword */ || ts.isWriteAccess(node); + } + /** + * True if 'decl' provides a value, as in `function f() {}`; + * false if 'decl' is just a location for a future write, as in 'let x;' + */ + function declarationIsWriteAccess(decl) { + // Consider anything in an ambient declaration to be a write access since it may be coming from JS. + if (!!(decl.flags & 4194304 /* Ambient */)) + return true; + switch (decl.kind) { + case 204 /* BinaryExpression */: + case 186 /* BindingElement */: + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 80 /* DefaultKeyword */: + case 243 /* EnumDeclaration */: + case 278 /* EnumMember */: + case 257 /* ExportSpecifier */: + case 250 /* ImportClause */: // default import + case 248 /* ImportEqualsDeclaration */: + case 253 /* ImportSpecifier */: + case 241 /* InterfaceDeclaration */: + case 297 /* JSDocCallbackTag */: + case 304 /* JSDocTypedefTag */: + case 267 /* JsxAttribute */: + case 244 /* ModuleDeclaration */: + case 247 /* NamespaceExportDeclaration */: + case 251 /* NamespaceImport */: + case 151 /* Parameter */: + case 276 /* ShorthandPropertyAssignment */: + case 242 /* TypeAliasDeclaration */: + case 150 /* TypeParameter */: + return true; + case 275 /* PropertyAssignment */: + // In `({ x: y } = 0);`, `x` is not a write access. (Won't call this function for `y`.) + return !ts.isArrayLiteralOrObjectLiteralDestructuringPattern(decl.parent); + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 157 /* Constructor */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + return !!decl.body; + case 237 /* VariableDeclaration */: + case 154 /* PropertyDeclaration */: + return !!decl.initializer || ts.isCatchClause(decl.parent); + case 155 /* MethodSignature */: + case 153 /* PropertySignature */: + case 305 /* JSDocPropertyTag */: + case 299 /* JSDocParameterTag */: + return false; + default: + return ts.Debug.failBadSyntaxKind(decl); + } + } + })(FindAllReferences = ts.FindAllReferences || (ts.FindAllReferences = {})); +})(ts || (ts = {})); +/** Encapsulates the core find-all-references algorithm. */ +/* @internal */ +(function (ts) { + var FindAllReferences; + (function (FindAllReferences) { + var Core; + (function (Core) { + /** Core find-all-references algorithm. Handles special cases before delegating to `getReferencedSymbolsForSymbol`. */ + function getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options, sourceFilesSet) { + if (options === void 0) { options = {}; } + if (sourceFilesSet === void 0) { sourceFilesSet = ts.arrayToSet(sourceFiles, function (f) { return f.fileName; }); } + if (ts.isSourceFile(node)) { + var reference = ts.GoToDefinition.getReferenceAtPosition(node, position, program); + var moduleSymbol = reference && program.getTypeChecker().getMergedSymbol(reference.file.symbol); + return moduleSymbol && getReferencedSymbolsForModule(program, moduleSymbol, /*excludeImportTypeOfExportEquals*/ false, sourceFiles, sourceFilesSet); + } + if (!options.implementations) { + var special = getReferencedSymbolsSpecial(node, sourceFiles, cancellationToken); + if (special) { + return special; + } + } + var checker = program.getTypeChecker(); + var symbol = checker.getSymbolAtLocation(node); + // Could not find a symbol e.g. unknown identifier + if (!symbol) { + // String literal might be a property (and thus have a symbol), so do this here rather than in getReferencedSymbolsSpecial. + return !options.implementations && ts.isStringLiteral(node) ? getReferencesForStringLiteral(node, sourceFiles, cancellationToken) : undefined; + } + if (symbol.escapedName === "export=" /* ExportEquals */) { + return getReferencedSymbolsForModule(program, symbol.parent, /*excludeImportTypeOfExportEquals*/ false, sourceFiles, sourceFilesSet); + } + var moduleReferences = ts.emptyArray; + var moduleSourceFile = isModuleSymbol(symbol); + var referencedNode = node; + if (moduleSourceFile) { + var exportEquals = symbol.exports.get("export=" /* ExportEquals */); + // If !!exportEquals, we're about to add references to `import("mod")` anyway, so don't double-count them. + moduleReferences = getReferencedSymbolsForModule(program, symbol, !!exportEquals, sourceFiles, sourceFilesSet); + if (!exportEquals || !sourceFilesSet.has(moduleSourceFile.fileName)) + return moduleReferences; + // Continue to get references to 'export ='. + symbol = ts.skipAlias(exportEquals, checker); + referencedNode = undefined; + } + return ts.concatenate(moduleReferences, getReferencedSymbolsForSymbol(symbol, referencedNode, sourceFiles, sourceFilesSet, checker, cancellationToken, options)); + } + Core.getReferencedSymbolsForNode = getReferencedSymbolsForNode; + function isModuleSymbol(symbol) { + return symbol.flags & 1536 /* Module */ ? ts.find(symbol.declarations, ts.isSourceFile) : undefined; + } + function getReferencedSymbolsForModule(program, symbol, excludeImportTypeOfExportEquals, sourceFiles, sourceFilesSet) { + ts.Debug.assert(!!symbol.valueDeclaration); + var references = ts.mapDefined(FindAllReferences.findModuleReferences(program, sourceFiles, symbol), function (reference) { + if (reference.kind === "import") { + var parent = reference.literal.parent; + if (ts.isLiteralTypeNode(parent)) { + var importType = ts.cast(parent.parent, ts.isImportTypeNode); + if (excludeImportTypeOfExportEquals && !importType.qualifier) { + return undefined; + } + } + // import("foo") with no qualifier will reference the `export =` of the module, which may be referenced anyway. + return FindAllReferences.nodeEntry(reference.literal); + } + else { + return { + kind: 0 /* Span */, + fileName: reference.referencingFile.fileName, + textSpan: ts.createTextSpanFromRange(reference.ref), + }; + } + }); + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + switch (decl.kind) { + case 279 /* SourceFile */: + // Don't include the source file itself. (This may not be ideal behavior, but awkward to include an entire file as a reference.) + break; + case 244 /* ModuleDeclaration */: + if (sourceFilesSet.has(decl.getSourceFile().fileName)) { + references.push(FindAllReferences.nodeEntry(decl.name)); + } + break; + default: + // This may be merged with something. + ts.Debug.fail("Expected a module symbol to be declared by a SourceFile or ModuleDeclaration."); + } + } + var exported = symbol.exports.get("export=" /* ExportEquals */); + if (exported) { + for (var _b = 0, _c = exported.declarations; _b < _c.length; _b++) { + var decl = _c[_b]; + var sourceFile = decl.getSourceFile(); + if (sourceFilesSet.has(sourceFile.fileName)) { + // At `module.exports = ...`, reference node is `module` + var node = ts.isBinaryExpression(decl) && ts.isPropertyAccessExpression(decl.left) + ? decl.left.expression + : ts.isExportAssignment(decl) + ? ts.Debug.assertDefined(ts.findChildOfKind(decl, 85 /* ExportKeyword */, sourceFile)) + : ts.getNameOfDeclaration(decl) || decl; + references.push(FindAllReferences.nodeEntry(node)); + } + } + } + return references.length ? [{ definition: { type: 0 /* Symbol */, symbol: symbol }, references: references }] : ts.emptyArray; + } + /** getReferencedSymbols for special node kinds. */ + function getReferencedSymbolsSpecial(node, sourceFiles, cancellationToken) { + if (ts.isTypeKeyword(node.kind)) { + return getAllReferencesForKeyword(sourceFiles, node.kind, cancellationToken); + } + // Labels + if (ts.isJumpStatementTarget(node)) { + var labelDefinition = ts.getTargetLabel(node.parent, node.text); + // if we have a label definition, look within its statement for references, if not, then + // the label is undefined and we have no results.. + return labelDefinition && getLabelReferencesInNode(labelDefinition.parent, labelDefinition); + } + else if (ts.isLabelOfLabeledStatement(node)) { + // it is a label definition and not a target, search within the parent labeledStatement + return getLabelReferencesInNode(node.parent, node); + } + if (ts.isThis(node)) { + return getReferencesForThisKeyword(node, sourceFiles, cancellationToken); + } + if (node.kind === 98 /* SuperKeyword */) { + return getReferencesForSuperKeyword(node); + } + return undefined; + } + /** Core find-all-references algorithm for a normal symbol. */ + function getReferencedSymbolsForSymbol(originalSymbol, node, sourceFiles, sourceFilesSet, checker, cancellationToken, options) { + var symbol = node && skipPastExportOrImportSpecifierOrUnion(originalSymbol, node, checker, !!options.isForRename) || originalSymbol; + // Compute the meaning from the location and the symbol it references + var searchMeaning = node ? getIntersectingMeaningFromDeclarations(node, symbol) : 7 /* All */; + var result = []; + var state = new State(sourceFiles, sourceFilesSet, node ? getSpecialSearchKind(node) : 0 /* None */, checker, cancellationToken, searchMeaning, options, result); + var exportSpecifier = !options.isForRename ? undefined : ts.find(symbol.declarations, ts.isExportSpecifier); + if (exportSpecifier) { + // When renaming at an export specifier, rename the export and not the thing being exported. + getReferencesAtExportSpecifier(exportSpecifier.name, symbol, exportSpecifier, state.createSearch(node, originalSymbol, /*comingFrom*/ undefined), state, /*addReferencesHere*/ true, /*alwaysGetReferences*/ true); + } + else if (node && node.kind === 80 /* DefaultKeyword */) { + addReference(node, symbol, state); + searchForImportsOfExport(node, symbol, { exportingModuleSymbol: ts.Debug.assertDefined(symbol.parent, "Expected export symbol to have a parent"), exportKind: 1 /* Default */ }, state); + } + else { + var search = state.createSearch(node, symbol, /*comingFrom*/ undefined, { allSearchSymbols: node ? populateSearchSymbolSet(symbol, node, checker, !!options.isForRename, !!options.implementations) : [symbol] }); + // Try to get the smallest valid scope that we can limit our search to; + // otherwise we'll need to search globally (i.e. include each file). + var scope = getSymbolScope(symbol); + if (scope) { + getReferencesInContainer(scope, scope.getSourceFile(), search, state, /*addReferencesHere*/ !(ts.isSourceFile(scope) && !ts.contains(sourceFiles, scope))); + } + else { + // Global search + for (var _i = 0, _a = state.sourceFiles; _i < _a.length; _i++) { + var sourceFile = _a[_i]; + state.cancellationToken.throwIfCancellationRequested(); + searchForName(sourceFile, search, state); + } + } + } + return result; + } + function getSpecialSearchKind(node) { + switch (node.kind) { + case 124 /* ConstructorKeyword */: + return 1 /* Constructor */; + case 72 /* Identifier */: + if (ts.isClassLike(node.parent)) { + ts.Debug.assert(node.parent.name === node); + return 2 /* Class */; + } + // falls through + default: + return 0 /* None */; + } + } + /** Handle a few special cases relating to export/import specifiers. */ + function skipPastExportOrImportSpecifierOrUnion(symbol, node, checker, isForRename) { + var parent = node.parent; + if (ts.isExportSpecifier(parent) && !isForRename) { + return getLocalSymbolForExportSpecifier(node, symbol, parent, checker); + } + // If the symbol is declared as part of a declaration like `{ type: "a" } | { type: "b" }`, use the property on the union type to get more references. + return ts.firstDefined(symbol.declarations, function (decl) { + if (!decl.parent) { + // Assertions for GH#21814. We should be handling SourceFile symbols in `getReferencedSymbolsForModule` instead of getting here. + ts.Debug.fail("Unexpected symbol at " + ts.Debug.showSyntaxKind(node) + ": " + ts.Debug.showSymbol(symbol)); + } + return ts.isTypeLiteralNode(decl.parent) && ts.isUnionTypeNode(decl.parent.parent) + ? checker.getPropertyOfType(checker.getTypeFromTypeNode(decl.parent.parent), symbol.name) + : undefined; + }); + } + var SpecialSearchKind; + (function (SpecialSearchKind) { + SpecialSearchKind[SpecialSearchKind["None"] = 0] = "None"; + SpecialSearchKind[SpecialSearchKind["Constructor"] = 1] = "Constructor"; + SpecialSearchKind[SpecialSearchKind["Class"] = 2] = "Class"; + })(SpecialSearchKind || (SpecialSearchKind = {})); + /** + * Holds all state needed for the finding references. + * Unlike `Search`, there is only one `State`. + */ + var State = /** @class */ (function () { + function State(sourceFiles, sourceFilesSet, + /** True if we're searching for constructor references. */ + specialSearchKind, checker, cancellationToken, searchMeaning, options, result) { + this.sourceFiles = sourceFiles; + this.sourceFilesSet = sourceFilesSet; + this.specialSearchKind = specialSearchKind; + this.checker = checker; + this.cancellationToken = cancellationToken; + this.searchMeaning = searchMeaning; + this.options = options; + this.result = result; + /** Cache for `explicitlyinheritsFrom`. */ + this.inheritsFromCache = ts.createMap(); + /** + * Type nodes can contain multiple references to the same type. For example: + * let x: Foo & (Foo & Bar) = ... + * Because we are returning the implementation locations and not the identifier locations, + * duplicate entries would be returned here as each of the type references is part of + * the same implementation. For that reason, check before we add a new entry. + */ + this.markSeenContainingTypeReference = ts.nodeSeenTracker(); + /** + * It's possible that we will encounter the right side of `export { foo as bar } from "x";` more than once. + * For example: + * // b.ts + * export { foo as bar } from "./a"; + * import { bar } from "./b"; + * + * Normally at `foo as bar` we directly add `foo` and do not locally search for it (since it doesn't declare a local). + * But another reference to it may appear in the same source file. + * See `tests/cases/fourslash/transitiveExportImports3.ts`. + */ + this.markSeenReExportRHS = ts.nodeSeenTracker(); + this.symbolIdToReferences = []; + // Source file ID → symbol ID → Whether the symbol has been searched for in the source file. + this.sourceFileToSeenSymbols = []; + } + State.prototype.includesSourceFile = function (sourceFile) { + return this.sourceFilesSet.has(sourceFile.fileName); + }; + /** Gets every place to look for references of an exported symbols. See `ImportsResult` in `importTracker.ts` for more documentation. */ + State.prototype.getImportSearches = function (exportSymbol, exportInfo) { + if (!this.importTracker) + this.importTracker = FindAllReferences.createImportTracker(this.sourceFiles, this.sourceFilesSet, this.checker, this.cancellationToken); + return this.importTracker(exportSymbol, exportInfo, !!this.options.isForRename); + }; + /** @param allSearchSymbols set of additional symbols for use by `includes`. */ + State.prototype.createSearch = function (location, symbol, comingFrom, searchOptions) { + if (searchOptions === void 0) { searchOptions = {}; } + // Note: if this is an external module symbol, the name doesn't include quotes. + // Note: getLocalSymbolForExportDefault handles `export default class C {}`, but not `export default C` or `export { C as default }`. + // The other two forms seem to be handled downstream (e.g. in `skipPastExportOrImportSpecifier`), so special-casing the first form + // here appears to be intentional). + var _a = searchOptions.text, text = _a === void 0 ? ts.stripQuotes(ts.unescapeLeadingUnderscores((ts.getLocalSymbolForExportDefault(symbol) || symbol).escapedName)) : _a, _b = searchOptions.allSearchSymbols, allSearchSymbols = _b === void 0 ? [symbol] : _b; + var escapedText = ts.escapeLeadingUnderscores(text); + var parents = this.options.implementations && location ? getParentSymbolsOfPropertyAccess(location, symbol, this.checker) : undefined; + return { symbol: symbol, comingFrom: comingFrom, text: text, escapedText: escapedText, parents: parents, allSearchSymbols: allSearchSymbols, includes: function (sym) { return ts.contains(allSearchSymbols, sym); } }; + }; + /** + * Callback to add references for a particular searched symbol. + * This initializes a reference group, so only call this if you will add at least one reference. + */ + State.prototype.referenceAdder = function (searchSymbol) { + var symbolId = ts.getSymbolId(searchSymbol); + var references = this.symbolIdToReferences[symbolId]; + if (!references) { + references = this.symbolIdToReferences[symbolId] = []; + this.result.push({ definition: { type: 0 /* Symbol */, symbol: searchSymbol }, references: references }); + } + return function (node, kind) { return references.push(FindAllReferences.nodeEntry(node, kind)); }; + }; + /** Add a reference with no associated definition. */ + State.prototype.addStringOrCommentReference = function (fileName, textSpan) { + this.result.push({ + definition: undefined, + references: [{ kind: 0 /* Span */, fileName: fileName, textSpan: textSpan }] + }); + }; + /** Returns `true` the first time we search for a symbol in a file and `false` afterwards. */ + State.prototype.markSearchedSymbols = function (sourceFile, symbols) { + var sourceId = ts.getNodeId(sourceFile); + var seenSymbols = this.sourceFileToSeenSymbols[sourceId] || (this.sourceFileToSeenSymbols[sourceId] = ts.createMap()); + var anyNewSymbols = false; + for (var _i = 0, symbols_4 = symbols; _i < symbols_4.length; _i++) { + var sym = symbols_4[_i]; + anyNewSymbols = ts.addToSeen(seenSymbols, ts.getSymbolId(sym)) || anyNewSymbols; + } + return anyNewSymbols; + }; + return State; + }()); + /** Search for all imports of a given exported symbol using `State.getImportSearches`. */ + function searchForImportsOfExport(exportLocation, exportSymbol, exportInfo, state) { + var _a = state.getImportSearches(exportSymbol, exportInfo), importSearches = _a.importSearches, singleReferences = _a.singleReferences, indirectUsers = _a.indirectUsers; + // For `import { foo as bar }` just add the reference to `foo`, and don't otherwise search in the file. + if (singleReferences.length) { + var addRef = state.referenceAdder(exportSymbol); + for (var _i = 0, singleReferences_1 = singleReferences; _i < singleReferences_1.length; _i++) { + var singleRef = singleReferences_1[_i]; + if (shouldAddSingleReference(singleRef, state)) + addRef(singleRef); + } + } + // For each import, find all references to that import in its source file. + for (var _b = 0, importSearches_1 = importSearches; _b < importSearches_1.length; _b++) { + var _c = importSearches_1[_b], importLocation = _c[0], importSymbol = _c[1]; + getReferencesInSourceFile(importLocation.getSourceFile(), state.createSearch(importLocation, importSymbol, 1 /* Export */), state); + } + if (indirectUsers.length) { + var indirectSearch = void 0; + switch (exportInfo.exportKind) { + case 0 /* Named */: + indirectSearch = state.createSearch(exportLocation, exportSymbol, 1 /* Export */); + break; + case 1 /* Default */: + // Search for a property access to '.default'. This can't be renamed. + indirectSearch = state.options.isForRename ? undefined : state.createSearch(exportLocation, exportSymbol, 1 /* Export */, { text: "default" }); + break; + case 2 /* ExportEquals */: + break; + } + if (indirectSearch) { + for (var _d = 0, indirectUsers_1 = indirectUsers; _d < indirectUsers_1.length; _d++) { + var indirectUser = indirectUsers_1[_d]; + searchForName(indirectUser, indirectSearch, state); + } + } + } + } + function eachExportReference(sourceFiles, checker, cancellationToken, exportSymbol, exportingModuleSymbol, exportName, isDefaultExport, cb) { + var importTracker = FindAllReferences.createImportTracker(sourceFiles, ts.arrayToSet(sourceFiles, function (f) { return f.fileName; }), checker, cancellationToken); + var _a = importTracker(exportSymbol, { exportKind: isDefaultExport ? 1 /* Default */ : 0 /* Named */, exportingModuleSymbol: exportingModuleSymbol }, /*isForRename*/ false), importSearches = _a.importSearches, indirectUsers = _a.indirectUsers; + for (var _i = 0, importSearches_2 = importSearches; _i < importSearches_2.length; _i++) { + var importLocation = importSearches_2[_i][0]; + cb(importLocation); + } + for (var _b = 0, indirectUsers_2 = indirectUsers; _b < indirectUsers_2.length; _b++) { + var indirectUser = indirectUsers_2[_b]; + for (var _c = 0, _d = getPossibleSymbolReferenceNodes(indirectUser, isDefaultExport ? "default" : exportName); _c < _d.length; _c++) { + var node = _d[_c]; + // Import specifiers should be handled by importSearches + if (ts.isIdentifier(node) && !ts.isImportOrExportSpecifier(node.parent) && checker.getSymbolAtLocation(node) === exportSymbol) { + cb(node); + } + } + } + } + Core.eachExportReference = eachExportReference; + function shouldAddSingleReference(singleRef, state) { + if (!hasMatchingMeaning(singleRef, state)) + return false; + if (!state.options.isForRename) + return true; + // Don't rename an import type `import("./module-name")` when renaming `name` in `export = name;` + if (!ts.isIdentifier(singleRef)) + return false; + // At `default` in `import { default as x }` or `export { default as x }`, do add a reference, but do not rename. + return !(ts.isImportOrExportSpecifier(singleRef.parent) && singleRef.escapedText === "default" /* Default */); + } + // Go to the symbol we imported from and find references for it. + function searchForImportedSymbol(symbol, state) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + var exportingFile = declaration.getSourceFile(); + // Need to search in the file even if it's not in the search-file set, because it might export the symbol. + getReferencesInSourceFile(exportingFile, state.createSearch(declaration, symbol, 0 /* Import */), state, state.includesSourceFile(exportingFile)); + } + } + /** Search for all occurences of an identifier in a source file (and filter out the ones that match). */ + function searchForName(sourceFile, search, state) { + if (ts.getNameTable(sourceFile).get(search.escapedText) !== undefined) { + getReferencesInSourceFile(sourceFile, search, state); + } + } + function getPropertySymbolOfDestructuringAssignment(location, checker) { + return ts.isArrayLiteralOrObjectLiteralDestructuringPattern(location.parent.parent) + ? checker.getPropertySymbolOfDestructuringAssignment(location) + : undefined; + } + /** + * Determines the smallest scope in which a symbol may have named references. + * Note that not every construct has been accounted for. This function can + * probably be improved. + * + * @returns undefined if the scope cannot be determined, implying that + * a reference to a symbol can occur anywhere. + */ + function getSymbolScope(symbol) { + // If this is the symbol of a named function expression or named class expression, + // then named references are limited to its own scope. + var declarations = symbol.declarations, flags = symbol.flags, parent = symbol.parent, valueDeclaration = symbol.valueDeclaration; + if (valueDeclaration && (valueDeclaration.kind === 196 /* FunctionExpression */ || valueDeclaration.kind === 209 /* ClassExpression */)) { + return valueDeclaration; + } + if (!declarations) { + return undefined; + } + // If this is private property or method, the scope is the containing class + if (flags & (4 /* Property */ | 8192 /* Method */)) { + var privateDeclaration = ts.find(declarations, function (d) { return ts.hasModifier(d, 8 /* Private */); }); + if (privateDeclaration) { + return ts.getAncestor(privateDeclaration, 240 /* ClassDeclaration */); + } + // Else this is a public property and could be accessed from anywhere. + return undefined; + } + // If symbol is of object binding pattern element without property name we would want to + // look for property too and that could be anywhere + if (declarations.some(ts.isObjectBindingElementWithoutPropertyName)) { + return undefined; + } + /* + If the symbol has a parent, it's globally visible unless: + - It's a private property (handled above). + - It's a type parameter. + - The parent is an external module: then we should only search in the module (and recurse on the export later). + - But if the parent has `export as namespace`, the symbol is globally visible through that namespace. + */ + var exposedByParent = parent && !(symbol.flags & 262144 /* TypeParameter */); + if (exposedByParent && !(ts.isExternalModuleSymbol(parent) && !parent.globalExports)) { + return undefined; + } + var scope; + for (var _i = 0, declarations_11 = declarations; _i < declarations_11.length; _i++) { + var declaration = declarations_11[_i]; + var container = ts.getContainerNode(declaration); + if (scope && scope !== container) { + // Different declarations have different containers, bail out + return undefined; + } + if (!container || container.kind === 279 /* SourceFile */ && !ts.isExternalOrCommonJsModule(container)) { + // This is a global variable and not an external module, any declaration defined + // within this scope is visible outside the file + return undefined; + } + // The search scope is the container node + scope = container; + } + // If symbol.parent, this means we are in an export of an external module. (Otherwise we would have returned `undefined` above.) + // For an export of a module, we may be in a declaration file, and it may be accessed elsewhere. E.g.: + // declare module "a" { export type T = number; } + // declare module "b" { import { T } from "a"; export const x: T; } + // So we must search the whole source file. (Because we will mark the source file as seen, we we won't return to it when searching for imports.) + return exposedByParent ? scope.getSourceFile() : scope; // TODO: GH#18217 + } + /** Used as a quick check for whether a symbol is used at all in a file (besides its definition). */ + function isSymbolReferencedInFile(definition, checker, sourceFile) { + return eachSymbolReferenceInFile(definition, checker, sourceFile, function () { return true; }) || false; + } + Core.isSymbolReferencedInFile = isSymbolReferencedInFile; + function eachSymbolReferenceInFile(definition, checker, sourceFile, cb) { + var symbol = ts.isParameterPropertyDeclaration(definition.parent) + ? ts.first(checker.getSymbolsOfParameterPropertyDeclaration(definition.parent, definition.text)) + : checker.getSymbolAtLocation(definition); + if (!symbol) + return undefined; + for (var _i = 0, _a = getPossibleSymbolReferenceNodes(sourceFile, symbol.name); _i < _a.length; _i++) { + var token = _a[_i]; + if (!ts.isIdentifier(token) || token === definition || token.escapedText !== definition.escapedText) + continue; + var referenceSymbol = checker.getSymbolAtLocation(token); // See GH#19955 for why the type annotation is necessary + if (referenceSymbol === symbol + || checker.getShorthandAssignmentValueSymbol(token.parent) === symbol + || ts.isExportSpecifier(token.parent) && getLocalSymbolForExportSpecifier(token, referenceSymbol, token.parent, checker) === symbol) { + var res = cb(token); + if (res) + return res; + } + } + } + Core.eachSymbolReferenceInFile = eachSymbolReferenceInFile; + function eachSignatureCall(signature, sourceFiles, checker, cb) { + if (!signature.name || !ts.isIdentifier(signature.name)) + return; + var symbol = ts.Debug.assertDefined(checker.getSymbolAtLocation(signature.name)); + for (var _i = 0, sourceFiles_5 = sourceFiles; _i < sourceFiles_5.length; _i++) { + var sourceFile = sourceFiles_5[_i]; + for (var _a = 0, _b = getPossibleSymbolReferenceNodes(sourceFile, symbol.name); _a < _b.length; _a++) { + var name = _b[_a]; + if (!ts.isIdentifier(name) || name === signature.name || name.escapedText !== signature.name.escapedText) + continue; + var called = ts.climbPastPropertyAccess(name); + var call = called.parent; + if (!ts.isCallExpression(call) || call.expression !== called) + continue; + var referenceSymbol = checker.getSymbolAtLocation(name); + if (referenceSymbol && checker.getRootSymbols(referenceSymbol).some(function (s) { return s === symbol; })) { + cb(call); + } + } + } + } + Core.eachSignatureCall = eachSignatureCall; + function getPossibleSymbolReferenceNodes(sourceFile, symbolName, container) { + if (container === void 0) { container = sourceFile; } + return getPossibleSymbolReferencePositions(sourceFile, symbolName, container).map(function (pos) { return ts.getTouchingPropertyName(sourceFile, pos); }); + } + function getPossibleSymbolReferencePositions(sourceFile, symbolName, container) { + if (container === void 0) { container = sourceFile; } + var positions = []; + /// TODO: Cache symbol existence for files to save text search + // Also, need to make this work for unicode escapes. + // Be resilient in the face of a symbol with no name or zero length name + if (!symbolName || !symbolName.length) { + return positions; + } + var text = sourceFile.text; + var sourceLength = text.length; + var symbolNameLength = symbolName.length; + var position = text.indexOf(symbolName, container.pos); + while (position >= 0) { + // If we are past the end, stop looking + if (position > container.end) + break; + // We found a match. Make sure it's not part of a larger word (i.e. the char + // before and after it have to be a non-identifier char). + var endPosition = position + symbolNameLength; + if ((position === 0 || !ts.isIdentifierPart(text.charCodeAt(position - 1), 6 /* Latest */)) && + (endPosition === sourceLength || !ts.isIdentifierPart(text.charCodeAt(endPosition), 6 /* Latest */))) { + // Found a real match. Keep searching. + positions.push(position); + } + position = text.indexOf(symbolName, position + symbolNameLength + 1); + } + return positions; + } + function getLabelReferencesInNode(container, targetLabel) { + var sourceFile = container.getSourceFile(); + var labelName = targetLabel.text; + var references = ts.mapDefined(getPossibleSymbolReferenceNodes(sourceFile, labelName, container), function (node) { + // Only pick labels that are either the target label, or have a target that is the target label + return node === targetLabel || (ts.isJumpStatementTarget(node) && ts.getTargetLabel(node, labelName) === targetLabel) ? FindAllReferences.nodeEntry(node) : undefined; + }); + return [{ definition: { type: 1 /* Label */, node: targetLabel }, references: references }]; + } + function isValidReferencePosition(node, searchSymbolName) { + // Compare the length so we filter out strict superstrings of the symbol we are looking for + switch (node.kind) { + case 72 /* Identifier */: + return node.text.length === searchSymbolName.length; + case 10 /* StringLiteral */: { + var str = node; + return (ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(str) || ts.isNameOfModuleDeclaration(node) || ts.isExpressionOfExternalModuleImportEqualsDeclaration(node) || (ts.isCallExpression(node.parent) && ts.isBindableObjectDefinePropertyCall(node.parent) && node.parent.arguments[1] === node)) && + str.text.length === searchSymbolName.length; + } + case 8 /* NumericLiteral */: + return ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node) && node.text.length === searchSymbolName.length; + case 80 /* DefaultKeyword */: + return "default".length === searchSymbolName.length; + default: + return false; + } + } + function getAllReferencesForKeyword(sourceFiles, keywordKind, cancellationToken) { + var references = ts.flatMap(sourceFiles, function (sourceFile) { + cancellationToken.throwIfCancellationRequested(); + return ts.mapDefined(getPossibleSymbolReferenceNodes(sourceFile, ts.tokenToString(keywordKind), sourceFile), function (referenceLocation) { + return referenceLocation.kind === keywordKind ? FindAllReferences.nodeEntry(referenceLocation) : undefined; + }); + }); + return references.length ? [{ definition: { type: 2 /* Keyword */, node: references[0].node }, references: references }] : undefined; + } + function getReferencesInSourceFile(sourceFile, search, state, addReferencesHere) { + if (addReferencesHere === void 0) { addReferencesHere = true; } + state.cancellationToken.throwIfCancellationRequested(); + return getReferencesInContainer(sourceFile, sourceFile, search, state, addReferencesHere); + } + /** + * Search within node "container" for references for a search value, where the search value is defined as a + * tuple of(searchSymbol, searchText, searchLocation, and searchMeaning). + * searchLocation: a node where the search value + */ + function getReferencesInContainer(container, sourceFile, search, state, addReferencesHere) { + if (!state.markSearchedSymbols(sourceFile, search.allSearchSymbols)) { + return; + } + for (var _i = 0, _a = getPossibleSymbolReferencePositions(sourceFile, search.text, container); _i < _a.length; _i++) { + var position = _a[_i]; + getReferencesAtLocation(sourceFile, position, search, state, addReferencesHere); + } + } + function hasMatchingMeaning(referenceLocation, state) { + return !!(ts.getMeaningFromLocation(referenceLocation) & state.searchMeaning); + } + function getReferencesAtLocation(sourceFile, position, search, state, addReferencesHere) { + var referenceLocation = ts.getTouchingPropertyName(sourceFile, position); + if (!isValidReferencePosition(referenceLocation, search.text)) { + // This wasn't the start of a token. Check to see if it might be a + // match in a comment or string if that's what the caller is asking + // for. + if (!state.options.implementations && (state.options.findInStrings && ts.isInString(sourceFile, position) || state.options.findInComments && ts.isInNonReferenceComment(sourceFile, position))) { + // In the case where we're looking inside comments/strings, we don't have + // an actual definition. So just use 'undefined' here. Features like + // 'Rename' won't care (as they ignore the definitions), and features like + // 'FindReferences' will just filter out these results. + state.addStringOrCommentReference(sourceFile.fileName, ts.createTextSpan(position, search.text.length)); + } + return; + } + if (!hasMatchingMeaning(referenceLocation, state)) + return; + var referenceSymbol = state.checker.getSymbolAtLocation(referenceLocation); + if (!referenceSymbol) { + return; + } + var parent = referenceLocation.parent; + if (ts.isImportSpecifier(parent) && parent.propertyName === referenceLocation) { + // This is added through `singleReferences` in ImportsResult. If we happen to see it again, don't add it again. + return; + } + if (ts.isExportSpecifier(parent)) { + ts.Debug.assert(referenceLocation.kind === 72 /* Identifier */); + getReferencesAtExportSpecifier(referenceLocation, referenceSymbol, parent, search, state, addReferencesHere); + return; + } + var relatedSymbol = getRelatedSymbol(search, referenceSymbol, referenceLocation, state); + if (!relatedSymbol) { + getReferenceForShorthandProperty(referenceSymbol, search, state); + return; + } + switch (state.specialSearchKind) { + case 0 /* None */: + if (addReferencesHere) + addReference(referenceLocation, relatedSymbol, state); + break; + case 1 /* Constructor */: + addConstructorReferences(referenceLocation, sourceFile, search, state); + break; + case 2 /* Class */: + addClassStaticThisReferences(referenceLocation, search, state); + break; + default: + ts.Debug.assertNever(state.specialSearchKind); + } + getImportOrExportReferences(referenceLocation, referenceSymbol, search, state); + } + function getReferencesAtExportSpecifier(referenceLocation, referenceSymbol, exportSpecifier, search, state, addReferencesHere, alwaysGetReferences) { + var parent = exportSpecifier.parent, propertyName = exportSpecifier.propertyName, name = exportSpecifier.name; + var exportDeclaration = parent.parent; + var localSymbol = getLocalSymbolForExportSpecifier(referenceLocation, referenceSymbol, exportSpecifier, state.checker); + if (!alwaysGetReferences && !search.includes(localSymbol)) { + return; + } + if (!propertyName) { + // Don't rename at `export { default } from "m";`. (but do continue to search for imports of the re-export) + if (!(state.options.isForRename && (name.escapedText === "default" /* Default */))) { + addRef(); + } + } + else if (referenceLocation === propertyName) { + // For `export { foo as bar } from "baz"`, "`foo`" will be added from the singleReferences for import searches of the original export. + // For `export { foo as bar };`, where `foo` is a local, so add it now. + if (!exportDeclaration.moduleSpecifier) { + addRef(); + } + if (addReferencesHere && !state.options.isForRename && state.markSeenReExportRHS(name)) { + addReference(name, ts.Debug.assertDefined(exportSpecifier.symbol), state); + } + } + else { + if (state.markSeenReExportRHS(referenceLocation)) { + addRef(); + } + } + // For `export { foo as bar }`, rename `foo`, but not `bar`. + if (!state.options.isForRename || alwaysGetReferences) { + var exportKind = referenceLocation.originalKeywordKind === 80 /* DefaultKeyword */ ? 1 /* Default */ : 0 /* Named */; + var exportSymbol = ts.Debug.assertDefined(exportSpecifier.symbol); + var exportInfo = ts.Debug.assertDefined(FindAllReferences.getExportInfo(exportSymbol, exportKind, state.checker)); + searchForImportsOfExport(referenceLocation, exportSymbol, exportInfo, state); + } + // At `export { x } from "foo"`, also search for the imported symbol `"foo".x`. + if (search.comingFrom !== 1 /* Export */ && exportDeclaration.moduleSpecifier && !propertyName && !state.options.isForRename) { + var imported = state.checker.getExportSpecifierLocalTargetSymbol(exportSpecifier); + if (imported) + searchForImportedSymbol(imported, state); + } + function addRef() { + if (addReferencesHere) + addReference(referenceLocation, localSymbol, state); + } + } + function getLocalSymbolForExportSpecifier(referenceLocation, referenceSymbol, exportSpecifier, checker) { + return isExportSpecifierAlias(referenceLocation, exportSpecifier) && checker.getExportSpecifierLocalTargetSymbol(exportSpecifier) || referenceSymbol; + } + function isExportSpecifierAlias(referenceLocation, exportSpecifier) { + var parent = exportSpecifier.parent, propertyName = exportSpecifier.propertyName, name = exportSpecifier.name; + ts.Debug.assert(propertyName === referenceLocation || name === referenceLocation); + if (propertyName) { + // Given `export { foo as bar } [from "someModule"]`: It's an alias at `foo`, but at `bar` it's a new symbol. + return propertyName === referenceLocation; + } + else { + // `export { foo } from "foo"` is a re-export. + // `export { foo };` is not a re-export, it creates an alias for the local variable `foo`. + return !parent.parent.moduleSpecifier; + } + } + function getImportOrExportReferences(referenceLocation, referenceSymbol, search, state) { + var importOrExport = FindAllReferences.getImportOrExportSymbol(referenceLocation, referenceSymbol, state.checker, search.comingFrom === 1 /* Export */); + if (!importOrExport) + return; + var symbol = importOrExport.symbol; + if (importOrExport.kind === 0 /* Import */) { + if (!state.options.isForRename) { + searchForImportedSymbol(symbol, state); + } + } + else { + searchForImportsOfExport(referenceLocation, symbol, importOrExport.exportInfo, state); + } + } + function getReferenceForShorthandProperty(_a, search, state) { + var flags = _a.flags, valueDeclaration = _a.valueDeclaration; + var shorthandValueSymbol = state.checker.getShorthandAssignmentValueSymbol(valueDeclaration); + var name = valueDeclaration && ts.getNameOfDeclaration(valueDeclaration); + /* + * Because in short-hand property assignment, an identifier which stored as name of the short-hand property assignment + * has two meanings: property name and property value. Therefore when we do findAllReference at the position where + * an identifier is declared, the language service should return the position of the variable declaration as well as + * the position in short-hand property assignment excluding property accessing. However, if we do findAllReference at the + * position of property accessing, the referenceEntry of such position will be handled in the first case. + */ + if (!(flags & 33554432 /* Transient */) && name && search.includes(shorthandValueSymbol)) { + addReference(name, shorthandValueSymbol, state); + } + } + function addReference(referenceLocation, relatedSymbol, state) { + var _a = "kind" in relatedSymbol ? relatedSymbol : { kind: undefined, symbol: relatedSymbol }, kind = _a.kind, symbol = _a.symbol; + var addRef = state.referenceAdder(symbol); + if (state.options.implementations) { + addImplementationReferences(referenceLocation, addRef, state); + } + else { + addRef(referenceLocation, kind); + } + } + /** Adds references when a constructor is used with `new this()` in its own class and `super()` calls in subclasses. */ + function addConstructorReferences(referenceLocation, sourceFile, search, state) { + if (ts.isNewExpressionTarget(referenceLocation)) { + addReference(referenceLocation, search.symbol, state); + } + var pusher = function () { return state.referenceAdder(search.symbol); }; + if (ts.isClassLike(referenceLocation.parent)) { + ts.Debug.assert(referenceLocation.kind === 80 /* DefaultKeyword */ || referenceLocation.parent.name === referenceLocation); + // This is the class declaration containing the constructor. + findOwnConstructorReferences(search.symbol, sourceFile, pusher()); + } + else { + // If this class appears in `extends C`, then the extending class' "super" calls are references. + var classExtending = tryGetClassByExtendingIdentifier(referenceLocation); + if (classExtending) { + findSuperConstructorAccesses(classExtending, pusher()); + } + } + } + function addClassStaticThisReferences(referenceLocation, search, state) { + addReference(referenceLocation, search.symbol, state); + var classLike = referenceLocation.parent; + if (state.options.isForRename || !ts.isClassLike(classLike)) + return; + ts.Debug.assert(classLike.name === referenceLocation); + var addRef = state.referenceAdder(search.symbol); + for (var _i = 0, _a = classLike.members; _i < _a.length; _i++) { + var member = _a[_i]; + if (!(ts.isMethodOrAccessor(member) && ts.hasModifier(member, 32 /* Static */))) { + continue; + } + if (member.body) { + member.body.forEachChild(function cb(node) { + if (node.kind === 100 /* ThisKeyword */) { + addRef(node); + } + else if (!ts.isFunctionLike(node) && !ts.isClassLike(node)) { + node.forEachChild(cb); + } + }); + } + } + } + /** + * `classSymbol` is the class where the constructor was defined. + * Reference the constructor and all calls to `new this()`. + */ + function findOwnConstructorReferences(classSymbol, sourceFile, addNode) { + for (var _i = 0, _a = classSymbol.members.get("__constructor" /* Constructor */).declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + var ctrKeyword = ts.findChildOfKind(decl, 124 /* ConstructorKeyword */, sourceFile); + ts.Debug.assert(decl.kind === 157 /* Constructor */ && !!ctrKeyword); + addNode(ctrKeyword); + } + classSymbol.exports.forEach(function (member) { + var decl = member.valueDeclaration; + if (decl && decl.kind === 156 /* MethodDeclaration */) { + var body = decl.body; + if (body) { + forEachDescendantOfKind(body, 100 /* ThisKeyword */, function (thisKeyword) { + if (ts.isNewExpressionTarget(thisKeyword)) { + addNode(thisKeyword); + } + }); + } + } + }); + } + /** Find references to `super` in the constructor of an extending class. */ + function findSuperConstructorAccesses(cls, addNode) { + var ctr = cls.symbol.members.get("__constructor" /* Constructor */); + if (!ctr) { + return; + } + for (var _i = 0, _a = ctr.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + ts.Debug.assert(decl.kind === 157 /* Constructor */); + var body = decl.body; + if (body) { + forEachDescendantOfKind(body, 98 /* SuperKeyword */, function (node) { + if (ts.isCallExpressionTarget(node)) { + addNode(node); + } + }); + } + } + } + function addImplementationReferences(refNode, addReference, state) { + // Check if we found a function/propertyAssignment/method with an implementation or initializer + if (ts.isDeclarationName(refNode) && isImplementation(refNode.parent)) { + addReference(refNode); + return; + } + if (refNode.kind !== 72 /* Identifier */) { + return; + } + if (refNode.parent.kind === 276 /* ShorthandPropertyAssignment */) { + // Go ahead and dereference the shorthand assignment by going to its definition + getReferenceEntriesForShorthandPropertyAssignment(refNode, state.checker, addReference); + } + // Check if the node is within an extends or implements clause + var containingClass = getContainingClassIfInHeritageClause(refNode); + if (containingClass) { + addReference(containingClass); + return; + } + // If we got a type reference, try and see if the reference applies to any expressions that can implement an interface + // Find the first node whose parent isn't a type node -- i.e., the highest type node. + var typeNode = ts.findAncestor(refNode, function (a) { return !ts.isQualifiedName(a.parent) && !ts.isTypeNode(a.parent) && !ts.isTypeElement(a.parent); }); + var typeHavingNode = typeNode.parent; + if (ts.hasType(typeHavingNode) && typeHavingNode.type === typeNode && state.markSeenContainingTypeReference(typeHavingNode)) { + if (ts.hasInitializer(typeHavingNode)) { + addIfImplementation(typeHavingNode.initializer); + } + else if (ts.isFunctionLike(typeHavingNode) && typeHavingNode.body) { + var body = typeHavingNode.body; + if (body.kind === 218 /* Block */) { + ts.forEachReturnStatement(body, function (returnStatement) { + if (returnStatement.expression) + addIfImplementation(returnStatement.expression); + }); + } + else { + addIfImplementation(body); + } + } + else if (ts.isAssertionExpression(typeHavingNode)) { + addIfImplementation(typeHavingNode.expression); + } + } + function addIfImplementation(e) { + if (isImplementationExpression(e)) + addReference(e); + } + } + function getContainingClassIfInHeritageClause(node) { + return ts.isIdentifier(node) || ts.isPropertyAccessExpression(node) ? getContainingClassIfInHeritageClause(node.parent) + : ts.isExpressionWithTypeArguments(node) ? ts.tryCast(node.parent.parent, ts.isClassLike) : undefined; + } + /** + * Returns true if this is an expression that can be considered an implementation + */ + function isImplementationExpression(node) { + switch (node.kind) { + case 195 /* ParenthesizedExpression */: + return isImplementationExpression(node.expression); + case 197 /* ArrowFunction */: + case 196 /* FunctionExpression */: + case 188 /* ObjectLiteralExpression */: + case 209 /* ClassExpression */: + case 187 /* ArrayLiteralExpression */: + return true; + default: + return false; + } + } + /** + * Determines if the parent symbol occurs somewhere in the child's ancestry. If the parent symbol + * is an interface, determines if some ancestor of the child symbol extends or inherits from it. + * Also takes in a cache of previous results which makes this slightly more efficient and is + * necessary to avoid potential loops like so: + * class A extends B { } + * class B extends A { } + * + * We traverse the AST rather than using the type checker because users are typically only interested + * in explicit implementations of an interface/class when calling "Go to Implementation". Sibling + * implementations of types that share a common ancestor with the type whose implementation we are + * searching for need to be filtered out of the results. The type checker doesn't let us make the + * distinction between structurally compatible implementations and explicit implementations, so we + * must use the AST. + * + * @param symbol A class or interface Symbol + * @param parent Another class or interface Symbol + * @param cachedResults A map of symbol id pairs (i.e. "child,parent") to booleans indicating previous results + */ + function explicitlyInheritsFrom(symbol, parent, cachedResults, checker) { + if (symbol === parent) { + return true; + } + var key = ts.getSymbolId(symbol) + "," + ts.getSymbolId(parent); + var cached = cachedResults.get(key); + if (cached !== undefined) { + return cached; + } + // Set the key so that we don't infinitely recurse + cachedResults.set(key, false); + var inherits = symbol.declarations.some(function (declaration) { + return ts.getAllSuperTypeNodes(declaration).some(function (typeReference) { + var type = checker.getTypeAtLocation(typeReference); + return !!type && !!type.symbol && explicitlyInheritsFrom(type.symbol, parent, cachedResults, checker); + }); + }); + cachedResults.set(key, inherits); + return inherits; + } + function getReferencesForSuperKeyword(superKeyword) { + var searchSpaceNode = ts.getSuperContainer(superKeyword, /*stopOnFunctions*/ false); + if (!searchSpaceNode) { + return undefined; + } + // Whether 'super' occurs in a static context within a class. + var staticFlag = 32 /* Static */; + switch (searchSpaceNode.kind) { + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + staticFlag &= ts.getModifierFlags(searchSpaceNode); + searchSpaceNode = searchSpaceNode.parent; // re-assign to be the owning class + break; + default: + return undefined; + } + var sourceFile = searchSpaceNode.getSourceFile(); + var references = ts.mapDefined(getPossibleSymbolReferenceNodes(sourceFile, "super", searchSpaceNode), function (node) { + if (node.kind !== 98 /* SuperKeyword */) { + return; + } + var container = ts.getSuperContainer(node, /*stopOnFunctions*/ false); + // If we have a 'super' container, we must have an enclosing class. + // Now make sure the owning class is the same as the search-space + // and has the same static qualifier as the original 'super's owner. + return container && (32 /* Static */ & ts.getModifierFlags(container)) === staticFlag && container.parent.symbol === searchSpaceNode.symbol ? FindAllReferences.nodeEntry(node) : undefined; + }); + return [{ definition: { type: 0 /* Symbol */, symbol: searchSpaceNode.symbol }, references: references }]; + } + function getReferencesForThisKeyword(thisOrSuperKeyword, sourceFiles, cancellationToken) { + var searchSpaceNode = ts.getThisContainer(thisOrSuperKeyword, /* includeArrowFunctions */ false); + // Whether 'this' occurs in a static context within a class. + var staticFlag = 32 /* Static */; + switch (searchSpaceNode.kind) { + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + if (ts.isObjectLiteralMethod(searchSpaceNode)) { + break; + } + // falls through + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + staticFlag &= ts.getModifierFlags(searchSpaceNode); + searchSpaceNode = searchSpaceNode.parent; // re-assign to be the owning class + break; + case 279 /* SourceFile */: + if (ts.isExternalModule(searchSpaceNode)) { + return undefined; + } + // falls through + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + break; + // Computed properties in classes are not handled here because references to this are illegal, + // so there is no point finding references to them. + default: + return undefined; + } + var references = ts.flatMap(searchSpaceNode.kind === 279 /* SourceFile */ ? sourceFiles : [searchSpaceNode.getSourceFile()], function (sourceFile) { + cancellationToken.throwIfCancellationRequested(); + return getPossibleSymbolReferenceNodes(sourceFile, "this", ts.isSourceFile(searchSpaceNode) ? sourceFile : searchSpaceNode).filter(function (node) { + if (!ts.isThis(node)) { + return false; + } + var container = ts.getThisContainer(node, /* includeArrowFunctions */ false); + switch (searchSpaceNode.kind) { + case 196 /* FunctionExpression */: + case 239 /* FunctionDeclaration */: + return searchSpaceNode.symbol === container.symbol; + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + return ts.isObjectLiteralMethod(searchSpaceNode) && searchSpaceNode.symbol === container.symbol; + case 209 /* ClassExpression */: + case 240 /* ClassDeclaration */: + // Make sure the container belongs to the same class + // and has the appropriate static modifier from the original container. + return container.parent && searchSpaceNode.symbol === container.parent.symbol && (ts.getModifierFlags(container) & 32 /* Static */) === staticFlag; + case 279 /* SourceFile */: + return container.kind === 279 /* SourceFile */ && !ts.isExternalModule(container); + } + }); + }).map(function (n) { return FindAllReferences.nodeEntry(n); }); + var thisParameter = ts.firstDefined(references, function (r) { return ts.isParameter(r.node.parent) ? r.node : undefined; }); + return [{ + definition: { type: 3 /* This */, node: thisParameter || thisOrSuperKeyword }, + references: references + }]; + } + function getReferencesForStringLiteral(node, sourceFiles, cancellationToken) { + var references = ts.flatMap(sourceFiles, function (sourceFile) { + cancellationToken.throwIfCancellationRequested(); + return ts.mapDefined(getPossibleSymbolReferenceNodes(sourceFile, node.text), function (ref) { + return ts.isStringLiteral(ref) && ref.text === node.text ? FindAllReferences.nodeEntry(ref, 2 /* StringLiteral */) : undefined; + }); + }); + return [{ + definition: { type: 4 /* String */, node: node }, + references: references + }]; + } + // For certain symbol kinds, we need to include other symbols in the search set. + // This is not needed when searching for re-exports. + function populateSearchSymbolSet(symbol, location, checker, isForRename, implementations) { + var result = []; + forEachRelatedSymbol(symbol, location, checker, isForRename, function (sym, root, base) { result.push(base || root || sym); }, + /*allowBaseTypes*/ function () { return !implementations; }); + return result; + } + function forEachRelatedSymbol(symbol, location, checker, isForRenamePopulateSearchSymbolSet, cbSymbol, allowBaseTypes) { + var containingObjectLiteralElement = ts.getContainingObjectLiteralElement(location); + if (containingObjectLiteralElement) { + /* Because in short-hand property assignment, location has two meaning : property name and as value of the property + * When we do findAllReference at the position of the short-hand property assignment, we would want to have references to position of + * property name and variable declaration of the identifier. + * Like in below example, when querying for all references for an identifier 'name', of the property assignment, the language service + * should show both 'name' in 'obj' and 'name' in variable declaration + * const name = "Foo"; + * const obj = { name }; + * In order to do that, we will populate the search set with the value symbol of the identifier as a value of the property assignment + * so that when matching with potential reference symbol, both symbols from property declaration and variable declaration + * will be included correctly. + */ + var shorthandValueSymbol = checker.getShorthandAssignmentValueSymbol(location.parent); // gets the local symbol + if (shorthandValueSymbol && isForRenamePopulateSearchSymbolSet) { + // When renaming 'x' in `const o = { x }`, just rename the local variable, not the property. + return cbSymbol(shorthandValueSymbol, /*rootSymbol*/ undefined, /*baseSymbol*/ undefined, 3 /* SearchedLocalFoundProperty */); + } + // If the location is in a context sensitive location (i.e. in an object literal) try + // to get a contextual type for it, and add the property symbol from the contextual + // type to the search set + var contextualType = checker.getContextualType(containingObjectLiteralElement.parent); + var res_1 = contextualType && ts.firstDefined(ts.getPropertySymbolsFromContextualType(containingObjectLiteralElement, checker, contextualType, /*unionSymbolOk*/ true), function (sym) { return fromRoot(sym, 4 /* SearchedPropertyFoundLocal */); }); + if (res_1) + return res_1; + // If the location is name of property symbol from object literal destructuring pattern + // Search the property symbol + // for ( { property: p2 } of elems) { } + var propertySymbol = getPropertySymbolOfDestructuringAssignment(location, checker); + var res1 = propertySymbol && cbSymbol(propertySymbol, /*rootSymbol*/ undefined, /*baseSymbol*/ undefined, 4 /* SearchedPropertyFoundLocal */); + if (res1) + return res1; + var res2 = shorthandValueSymbol && cbSymbol(shorthandValueSymbol, /*rootSymbol*/ undefined, /*baseSymbol*/ undefined, 3 /* SearchedLocalFoundProperty */); + if (res2) + return res2; + } + var res = fromRoot(symbol); + if (res) + return res; + if (symbol.valueDeclaration && ts.isParameterPropertyDeclaration(symbol.valueDeclaration)) { + // For a parameter property, now try on the other symbol (property if this was a parameter, parameter if this was a property). + var paramProps = checker.getSymbolsOfParameterPropertyDeclaration(ts.cast(symbol.valueDeclaration, ts.isParameter), symbol.name); + ts.Debug.assert(paramProps.length === 2 && !!(paramProps[0].flags & 1 /* FunctionScopedVariable */) && !!(paramProps[1].flags & 4 /* Property */)); // is [parameter, property] + return fromRoot(symbol.flags & 1 /* FunctionScopedVariable */ ? paramProps[1] : paramProps[0]); + } + // symbolAtLocation for a binding element is the local symbol. See if the search symbol is the property. + // Don't do this when populating search set for a rename -- just rename the local. + if (!isForRenamePopulateSearchSymbolSet) { + var bindingElementPropertySymbol = ts.isObjectBindingElementWithoutPropertyName(location.parent) ? ts.getPropertySymbolFromBindingElement(checker, location.parent) : undefined; + return bindingElementPropertySymbol && fromRoot(bindingElementPropertySymbol, 4 /* SearchedPropertyFoundLocal */); + } + function fromRoot(sym, kind) { + // If this is a union property: + // - In populateSearchSymbolsSet we will add all the symbols from all its source symbols in all unioned types. + // - In findRelatedSymbol, we will just use the union symbol if any source symbol is included in the search. + // If the symbol is an instantiation from a another symbol (e.g. widened symbol): + // - In populateSearchSymbolsSet, add the root the list + // - In findRelatedSymbol, return the source symbol if that is in the search. (Do not return the instantiation symbol.) + return ts.firstDefined(checker.getRootSymbols(sym), function (rootSymbol) { + return cbSymbol(sym, rootSymbol, /*baseSymbol*/ undefined, kind) + // Add symbol of properties/methods of the same name in base classes and implemented interfaces definitions + || (rootSymbol.parent && rootSymbol.parent.flags & (32 /* Class */ | 64 /* Interface */) && allowBaseTypes(rootSymbol) + ? ts.getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.name, checker, function (base) { return cbSymbol(sym, rootSymbol, base, kind); }) + : undefined); + }); + } + } + function getRelatedSymbol(search, referenceSymbol, referenceLocation, state) { + var checker = state.checker; + return forEachRelatedSymbol(referenceSymbol, referenceLocation, checker, /*isForRenamePopulateSearchSymbolSet*/ false, function (sym, rootSymbol, baseSymbol, kind) { return search.includes(baseSymbol || rootSymbol || sym) + // For a base type, use the symbol for the derived type. For a synthetic (e.g. union) property, use the union symbol. + ? { symbol: rootSymbol && !(ts.getCheckFlags(sym) & 6 /* Synthetic */) ? rootSymbol : sym, kind: kind } + : undefined; }, + /*allowBaseTypes*/ function (rootSymbol) { + return !(search.parents && !search.parents.some(function (parent) { return explicitlyInheritsFrom(rootSymbol.parent, parent, state.inheritsFromCache, checker); })); + }); + } + /** + * Given an initial searchMeaning, extracted from a location, widen the search scope based on the declarations + * of the corresponding symbol. e.g. if we are searching for "Foo" in value position, but "Foo" references a class + * then we need to widen the search to include type positions as well. + * On the contrary, if we are searching for "Bar" in type position and we trace bar to an interface, and an uninstantiated + * module, we want to keep the search limited to only types, as the two declarations (interface and uninstantiated module) + * do not intersect in any of the three spaces. + */ + function getIntersectingMeaningFromDeclarations(node, symbol) { + var meaning = ts.getMeaningFromLocation(node); + var declarations = symbol.declarations; + if (declarations) { + var lastIterationMeaning = void 0; + do { + // The result is order-sensitive, for instance if initialMeaning === Namespace, and declarations = [class, instantiated module] + // we need to consider both as they initialMeaning intersects with the module in the namespace space, and the module + // intersects with the class in the value space. + // To achieve that we will keep iterating until the result stabilizes. + // Remember the last meaning + lastIterationMeaning = meaning; + for (var _i = 0, declarations_12 = declarations; _i < declarations_12.length; _i++) { + var declaration = declarations_12[_i]; + var declarationMeaning = ts.getMeaningFromDeclaration(declaration); + if (declarationMeaning & meaning) { + meaning |= declarationMeaning; + } + } + } while (meaning !== lastIterationMeaning); + } + return meaning; + } + Core.getIntersectingMeaningFromDeclarations = getIntersectingMeaningFromDeclarations; + function isImplementation(node) { + return !!(node.flags & 4194304 /* Ambient */) + || (ts.isVariableLike(node) ? ts.hasInitializer(node) + : ts.isFunctionLikeDeclaration(node) ? !!node.body + : ts.isClassLike(node) || ts.isModuleOrEnumDeclaration(node)); + } + function getReferenceEntriesForShorthandPropertyAssignment(node, checker, addReference) { + var refSymbol = checker.getSymbolAtLocation(node); + var shorthandSymbol = checker.getShorthandAssignmentValueSymbol(refSymbol.valueDeclaration); + if (shorthandSymbol) { + for (var _i = 0, _a = shorthandSymbol.getDeclarations(); _i < _a.length; _i++) { + var declaration = _a[_i]; + if (ts.getMeaningFromDeclaration(declaration) & 1 /* Value */) { + addReference(declaration); + } + } + } + } + Core.getReferenceEntriesForShorthandPropertyAssignment = getReferenceEntriesForShorthandPropertyAssignment; + function forEachDescendantOfKind(node, kind, action) { + ts.forEachChild(node, function (child) { + if (child.kind === kind) { + action(child); + } + forEachDescendantOfKind(child, kind, action); + }); + } + /** Get `C` given `N` if `N` is in the position `class C extends N` or `class C extends foo.N` where `N` is an identifier. */ + function tryGetClassByExtendingIdentifier(node) { + return ts.tryGetClassExtendingExpressionWithTypeArguments(ts.climbPastPropertyAccess(node).parent); + } + /** + * If we are just looking for implementations and this is a property access expression, we need to get the + * symbol of the local type of the symbol the property is being accessed on. This is because our search + * symbol may have a different parent symbol if the local type's symbol does not declare the property + * being accessed (i.e. it is declared in some parent class or interface) + */ + function getParentSymbolsOfPropertyAccess(location, symbol, checker) { + var propertyAccessExpression = ts.isRightSideOfPropertyAccess(location) ? location.parent : undefined; + var lhsType = propertyAccessExpression && checker.getTypeAtLocation(propertyAccessExpression.expression); + var res = ts.mapDefined(lhsType && (lhsType.isUnionOrIntersection() ? lhsType.types : lhsType.symbol === symbol.parent ? undefined : [lhsType]), function (t) { + return t.symbol && t.symbol.flags & (32 /* Class */ | 64 /* Interface */) ? t.symbol : undefined; + }); + return res.length === 0 ? undefined : res; + } + })(Core = FindAllReferences.Core || (FindAllReferences.Core = {})); + })(FindAllReferences = ts.FindAllReferences || (ts.FindAllReferences = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + function getEditsForFileRename(program, oldFileOrDirPath, newFileOrDirPath, host, formatContext, _preferences, sourceMapper) { + var useCaseSensitiveFileNames = ts.hostUsesCaseSensitiveFileNames(host); + var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); + var oldToNew = getPathUpdater(oldFileOrDirPath, newFileOrDirPath, getCanonicalFileName, sourceMapper); + var newToOld = getPathUpdater(newFileOrDirPath, oldFileOrDirPath, getCanonicalFileName, sourceMapper); + return ts.textChanges.ChangeTracker.with({ host: host, formatContext: formatContext }, function (changeTracker) { + updateTsconfigFiles(program, changeTracker, oldToNew, oldFileOrDirPath, newFileOrDirPath, host.getCurrentDirectory(), useCaseSensitiveFileNames); + updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName); + }); + } + ts.getEditsForFileRename = getEditsForFileRename; + // exported for tests + function getPathUpdater(oldFileOrDirPath, newFileOrDirPath, getCanonicalFileName, sourceMapper) { + var canonicalOldPath = getCanonicalFileName(oldFileOrDirPath); + return function (path) { + var originalPath = sourceMapper && sourceMapper.tryGetSourcePosition({ fileName: path, pos: 0 }); + var updatedPath = getUpdatedPath(originalPath ? originalPath.fileName : path); + return originalPath + ? updatedPath === undefined ? undefined : makeCorrespondingRelativeChange(originalPath.fileName, updatedPath, path, getCanonicalFileName) + : updatedPath; + }; + function getUpdatedPath(pathToUpdate) { + if (getCanonicalFileName(pathToUpdate) === canonicalOldPath) + return newFileOrDirPath; + var suffix = ts.tryRemoveDirectoryPrefix(pathToUpdate, canonicalOldPath, getCanonicalFileName); + return suffix === undefined ? undefined : newFileOrDirPath + "/" + suffix; + } + } + ts.getPathUpdater = getPathUpdater; + // Relative path from a0 to b0 should be same as relative path from a1 to b1. Returns b1. + function makeCorrespondingRelativeChange(a0, b0, a1, getCanonicalFileName) { + var rel = ts.getRelativePathFromFile(a0, b0, getCanonicalFileName); + return combinePathsSafe(ts.getDirectoryPath(a1), rel); + } + function updateTsconfigFiles(program, changeTracker, oldToNew, oldFileOrDirPath, newFileOrDirPath, currentDirectory, useCaseSensitiveFileNames) { + var configFile = program.getCompilerOptions().configFile; + if (!configFile) + return; + var configDir = ts.getDirectoryPath(configFile.fileName); + var jsonObjectLiteral = ts.getTsConfigObjectLiteralExpression(configFile); + if (!jsonObjectLiteral) + return; + forEachProperty(jsonObjectLiteral, function (property, propertyName) { + switch (propertyName) { + case "files": + case "include": + case "exclude": { + var foundExactMatch = updatePaths(property); + if (!foundExactMatch && propertyName === "include" && ts.isArrayLiteralExpression(property.initializer)) { + var includes = ts.mapDefined(property.initializer.elements, function (e) { return ts.isStringLiteral(e) ? e.text : undefined; }); + var matchers = ts.getFileMatcherPatterns(configDir, /*excludes*/ [], includes, useCaseSensitiveFileNames, currentDirectory); + // If there isn't some include for this, add a new one. + if (ts.getRegexFromPattern(ts.Debug.assertDefined(matchers.includeFilePattern), useCaseSensitiveFileNames).test(oldFileOrDirPath) && + !ts.getRegexFromPattern(ts.Debug.assertDefined(matchers.includeFilePattern), useCaseSensitiveFileNames).test(newFileOrDirPath)) { + changeTracker.insertNodeAfter(configFile, ts.last(property.initializer.elements), ts.createStringLiteral(relativePath(newFileOrDirPath))); + } + } + break; + } + case "compilerOptions": + forEachProperty(property.initializer, function (property, propertyName) { + var option = ts.getOptionFromName(propertyName); + if (option && (option.isFilePath || option.type === "list" && option.element.isFilePath)) { + updatePaths(property); + } + else if (propertyName === "paths") { + forEachProperty(property.initializer, function (pathsProperty) { + if (!ts.isArrayLiteralExpression(pathsProperty.initializer)) + return; + for (var _i = 0, _a = pathsProperty.initializer.elements; _i < _a.length; _i++) { + var e = _a[_i]; + tryUpdateString(e); + } + }); + } + }); + break; + } + }); + function updatePaths(property) { + // Type annotation needed due to #7294 + var elements = ts.isArrayLiteralExpression(property.initializer) ? property.initializer.elements : [property.initializer]; + var foundExactMatch = false; + for (var _i = 0, elements_5 = elements; _i < elements_5.length; _i++) { + var element = elements_5[_i]; + foundExactMatch = tryUpdateString(element) || foundExactMatch; + } + return foundExactMatch; + } + function tryUpdateString(element) { + if (!ts.isStringLiteral(element)) + return false; + var elementFileName = combinePathsSafe(configDir, element.text); + var updated = oldToNew(elementFileName); + if (updated !== undefined) { + changeTracker.replaceRangeWithText(configFile, createStringRange(element, configFile), relativePath(updated)); + return true; + } + return false; + } + function relativePath(path) { + return ts.getRelativePathFromDirectory(configDir, path, /*ignoreCase*/ !useCaseSensitiveFileNames); + } + } + function updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName) { + var allFiles = program.getSourceFiles(); + var _loop_12 = function (sourceFile) { + var newFromOld = oldToNew(sourceFile.path); + var newImportFromPath = newFromOld !== undefined ? newFromOld : sourceFile.path; + var newImportFromDirectory = ts.getDirectoryPath(newImportFromPath); + var oldFromNew = newToOld(sourceFile.fileName); + var oldImportFromPath = oldFromNew || sourceFile.fileName; + var oldImportFromDirectory = ts.getDirectoryPath(oldImportFromPath); + var importingSourceFileMoved = newFromOld !== undefined || oldFromNew !== undefined; + updateImportsWorker(sourceFile, changeTracker, function (referenceText) { + if (!ts.pathIsRelative(referenceText)) + return undefined; + var oldAbsolute = combinePathsSafe(oldImportFromDirectory, referenceText); + var newAbsolute = oldToNew(oldAbsolute); + return newAbsolute === undefined ? undefined : ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(newImportFromDirectory, newAbsolute, getCanonicalFileName)); + }, function (importLiteral) { + var importedModuleSymbol = program.getTypeChecker().getSymbolAtLocation(importLiteral); + // No need to update if it's an ambient module^M + if (importedModuleSymbol && importedModuleSymbol.declarations.some(function (d) { return ts.isAmbientModule(d); })) + return undefined; + var toImport = oldFromNew !== undefined + // If we're at the new location (file was already renamed), need to redo module resolution starting from the old location. + // TODO:GH#18217 + ? getSourceFileToImportFromResolved(ts.resolveModuleName(importLiteral.text, oldImportFromPath, program.getCompilerOptions(), host), oldToNew, host) + : getSourceFileToImport(importedModuleSymbol, importLiteral, sourceFile, program, host, oldToNew); + // Need an update if the imported file moved, or the importing file moved and was using a relative path. + return toImport !== undefined && (toImport.updated || (importingSourceFileMoved && ts.pathIsRelative(importLiteral.text))) + ? ts.moduleSpecifiers.updateModuleSpecifier(program.getCompilerOptions(), newImportFromPath, toImport.newFileName, host, allFiles, program.redirectTargetsMap, importLiteral.text) + : undefined; + }); + }; + for (var _i = 0, allFiles_1 = allFiles; _i < allFiles_1.length; _i++) { + var sourceFile = allFiles_1[_i]; + _loop_12(sourceFile); + } + } + function combineNormal(pathA, pathB) { + return ts.normalizePath(ts.combinePaths(pathA, pathB)); + } + function combinePathsSafe(pathA, pathB) { + return ts.ensurePathIsNonModuleName(combineNormal(pathA, pathB)); + } + function getSourceFileToImport(importedModuleSymbol, importLiteral, importingSourceFile, program, host, oldToNew) { + if (importedModuleSymbol) { + // `find` should succeed because we checked for ambient modules before calling this function. + var oldFileName = ts.find(importedModuleSymbol.declarations, ts.isSourceFile).fileName; + var newFileName = oldToNew(oldFileName); + return newFileName === undefined ? { newFileName: oldFileName, updated: false } : { newFileName: newFileName, updated: true }; + } + else { + var resolved = host.resolveModuleNames + ? host.getResolvedModuleWithFailedLookupLocationsFromCache && host.getResolvedModuleWithFailedLookupLocationsFromCache(importLiteral.text, importingSourceFile.fileName) + : program.getResolvedModuleWithFailedLookupLocationsFromCache(importLiteral.text, importingSourceFile.fileName); + return getSourceFileToImportFromResolved(resolved, oldToNew, host); + } + } + function getSourceFileToImportFromResolved(resolved, oldToNew, host) { + // Search through all locations looking for a moved file, and only then test already existing files. + // This is because if `a.ts` is compiled to `a.js` and `a.ts` is moved, we don't want to resolve anything to `a.js`, but to `a.ts`'s new location. + return tryEach(tryGetNewFile) || tryEach(tryGetOldFile); + function tryEach(cb) { + return resolved && ((resolved.resolvedModule && cb(resolved.resolvedModule.resolvedFileName)) || ts.firstDefined(resolved.failedLookupLocations, cb)); + } + function tryGetNewFile(oldFileName) { + var newFileName = oldToNew(oldFileName); + return newFileName !== undefined && host.fileExists(newFileName) ? { newFileName: newFileName, updated: true } : undefined; // TODO: GH#18217 + } + function tryGetOldFile(oldFileName) { + var newFileName = oldToNew(oldFileName); + return host.fileExists(oldFileName) ? newFileName !== undefined ? { newFileName: newFileName, updated: true } : { newFileName: oldFileName, updated: false } : undefined; // TODO: GH#18217 + } + } + function updateImportsWorker(sourceFile, changeTracker, updateRef, updateImport) { + for (var _i = 0, _a = sourceFile.referencedFiles || ts.emptyArray; _i < _a.length; _i++) { // TODO: GH#26162 + var ref = _a[_i]; + var updated = updateRef(ref.fileName); + if (updated !== undefined && updated !== sourceFile.text.slice(ref.pos, ref.end)) + changeTracker.replaceRangeWithText(sourceFile, ref, updated); + } + for (var _b = 0, _c = sourceFile.imports; _b < _c.length; _b++) { + var importStringLiteral = _c[_b]; + var updated = updateImport(importStringLiteral); + if (updated !== undefined && updated !== importStringLiteral.text) + changeTracker.replaceRangeWithText(sourceFile, createStringRange(importStringLiteral, sourceFile), updated); + } + } + function createStringRange(node, sourceFile) { + return ts.createRange(node.getStart(sourceFile) + 1, node.end - 1); + } + function forEachProperty(objectLiteral, cb) { + if (!ts.isObjectLiteralExpression(objectLiteral)) + return; + for (var _i = 0, _a = objectLiteral.properties; _i < _a.length; _i++) { + var property = _a[_i]; + if (ts.isPropertyAssignment(property) && ts.isStringLiteral(property.name)) { + cb(property, property.name.text); + } + } + } +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var GoToDefinition; + (function (GoToDefinition) { + function getDefinitionAtPosition(program, sourceFile, position) { + var reference = getReferenceAtPosition(sourceFile, position, program); + if (reference) { + return [getDefinitionInfoForFileReference(reference.fileName, reference.file.fileName)]; + } + var node = ts.getTouchingPropertyName(sourceFile, position); + if (node === sourceFile) { + return undefined; + } + var parent = node.parent; + // Labels + if (ts.isJumpStatementTarget(node)) { + var label = ts.getTargetLabel(node.parent, node.text); + return label ? [createDefinitionInfoFromName(label, "label" /* label */, node.text, /*containerName*/ undefined)] : undefined; // TODO: GH#18217 + } + var typeChecker = program.getTypeChecker(); + var symbol = getSymbol(node, typeChecker); + // Could not find a symbol e.g. node is string or number keyword, + // or the symbol was an internal symbol and does not have a declaration e.g. undefined symbol + if (!symbol) { + return getDefinitionInfoForIndexSignatures(node, typeChecker); + } + var calledDeclaration = tryGetSignatureDeclaration(typeChecker, node); + // Don't go to the component constructor definition for a JSX element, just go to the component definition. + if (calledDeclaration && !(ts.isJsxOpeningLikeElement(node.parent) && isConstructorLike(calledDeclaration))) { + var sigInfo = createDefinitionFromSignatureDeclaration(typeChecker, calledDeclaration); + // For a function, if this is the original function definition, return just sigInfo. + // If this is the original constructor definition, parent is the class. + if (typeChecker.getRootSymbols(symbol).some(function (s) { return symbolMatchesSignature(s, calledDeclaration); }) || + // TODO: GH#25533 Following check shouldn't be necessary if 'require' is an alias + symbol.declarations && symbol.declarations.some(function (d) { return ts.isVariableDeclaration(d) && !!d.initializer && ts.isRequireCall(d.initializer, /*checkArgumentIsStringLiteralLike*/ false); })) { + return [sigInfo]; + } + else { + var defs = getDefinitionFromSymbol(typeChecker, symbol, node) || ts.emptyArray; + // For a 'super()' call, put the signature first, else put the variable first. + return node.kind === 98 /* SuperKeyword */ ? [sigInfo].concat(defs) : defs.concat([sigInfo]); + } + } + // Because name in short-hand property assignment has two different meanings: property name and property value, + // using go-to-definition at such position should go to the variable declaration of the property value rather than + // go to the declaration of the property name (in this case stay at the same position). However, if go-to-definition + // is performed at the location of property access, we would like to go to definition of the property in the short-hand + // assignment. This case and others are handled by the following code. + if (node.parent.kind === 276 /* ShorthandPropertyAssignment */) { + var shorthandSymbol_1 = typeChecker.getShorthandAssignmentValueSymbol(symbol.valueDeclaration); + return shorthandSymbol_1 ? shorthandSymbol_1.declarations.map(function (decl) { return createDefinitionInfo(decl, typeChecker, shorthandSymbol_1, node); }) : []; + } + // If the node is the name of a BindingElement within an ObjectBindingPattern instead of just returning the + // declaration the symbol (which is itself), we should try to get to the original type of the ObjectBindingPattern + // and return the property declaration for the referenced property. + // For example: + // import('./foo').then(({ b/*goto*/ar }) => undefined); => should get use to the declaration in file "./foo" + // + // function bar(onfulfilled: (value: T) => void) { //....} + // interface Test { + // pr/*destination*/op1: number + // } + // bar(({pr/*goto*/op1})=>{}); + if (ts.isPropertyName(node) && ts.isBindingElement(parent) && ts.isObjectBindingPattern(parent.parent) && + (node === (parent.propertyName || parent.name))) { + var name_5 = ts.getNameFromPropertyName(node); + var type = typeChecker.getTypeAtLocation(parent.parent); + return name_5 === undefined ? ts.emptyArray : ts.flatMap(type.isUnion() ? type.types : [type], function (t) { + var prop = t.getProperty(name_5); + return prop && getDefinitionFromSymbol(typeChecker, prop, node); + }); + } + // If the current location we want to find its definition is in an object literal, try to get the contextual type for the + // object literal, lookup the property symbol in the contextual type, and use this for goto-definition. + // For example + // interface Props{ + // /*first*/prop1: number + // prop2: boolean + // } + // function Foo(arg: Props) {} + // Foo( { pr/*1*/op1: 10, prop2: true }) + var element = ts.getContainingObjectLiteralElement(node); + if (element) { + var contextualType = element && typeChecker.getContextualType(element.parent); + if (contextualType) { + return ts.flatMap(ts.getPropertySymbolsFromContextualType(element, typeChecker, contextualType, /*unionSymbolOk*/ false), function (propertySymbol) { + return getDefinitionFromSymbol(typeChecker, propertySymbol, node); + }); + } + } + return getDefinitionFromSymbol(typeChecker, symbol, node); + } + GoToDefinition.getDefinitionAtPosition = getDefinitionAtPosition; + /** + * True if we should not add definitions for both the signature symbol and the definition symbol. + * True for `const |f = |() => 0`, false for `function |f() {} const |g = f;`. + */ + function symbolMatchesSignature(s, calledDeclaration) { + return s === calledDeclaration.symbol || s === calledDeclaration.symbol.parent || + !ts.isCallLikeExpression(calledDeclaration.parent) && s === calledDeclaration.parent.symbol; + } + function getReferenceAtPosition(sourceFile, position, program) { + var referencePath = findReferenceInPosition(sourceFile.referencedFiles, position); + if (referencePath) { + var file = ts.tryResolveScriptReference(program, sourceFile, referencePath); + return file && { fileName: referencePath.fileName, file: file }; + } + var typeReferenceDirective = findReferenceInPosition(sourceFile.typeReferenceDirectives, position); + if (typeReferenceDirective) { + var reference = program.getResolvedTypeReferenceDirectives().get(typeReferenceDirective.fileName); + var file = reference && program.getSourceFile(reference.resolvedFileName); // TODO:GH#18217 + return file && { fileName: typeReferenceDirective.fileName, file: file }; + } + var libReferenceDirective = findReferenceInPosition(sourceFile.libReferenceDirectives, position); + if (libReferenceDirective) { + var file = program.getLibFileFromReference(libReferenceDirective); + return file && { fileName: libReferenceDirective.fileName, file: file }; + } + return undefined; + } + GoToDefinition.getReferenceAtPosition = getReferenceAtPosition; + /// Goto type + function getTypeDefinitionAtPosition(typeChecker, sourceFile, position) { + var node = ts.getTouchingPropertyName(sourceFile, position); + if (node === sourceFile) { + return undefined; + } + var symbol = typeChecker.getSymbolAtLocation(node); + if (!symbol) + return undefined; + var typeAtLocation = typeChecker.getTypeOfSymbolAtLocation(symbol, node); + var returnType = tryGetReturnTypeOfFunction(symbol, typeAtLocation, typeChecker); + var fromReturnType = returnType && definitionFromType(returnType, typeChecker, node); + // If a function returns 'void' or some other type with no definition, just return the function definition. + return fromReturnType && fromReturnType.length !== 0 ? fromReturnType : definitionFromType(typeAtLocation, typeChecker, node); + } + GoToDefinition.getTypeDefinitionAtPosition = getTypeDefinitionAtPosition; + function definitionFromType(type, checker, node) { + return ts.flatMap(type.isUnion() && !(type.flags & 32 /* Enum */) ? type.types : [type], function (t) { + return t.symbol && getDefinitionFromSymbol(checker, t.symbol, node); + }); + } + function tryGetReturnTypeOfFunction(symbol, type, checker) { + // If the type is just a function's inferred type, + // go-to-type should go to the return type instead, since go-to-definition takes you to the function anyway. + if (type.symbol === symbol || + // At `const f = () => {}`, the symbol is `f` and the type symbol is at `() => {}` + symbol.valueDeclaration && type.symbol && ts.isVariableDeclaration(symbol.valueDeclaration) && symbol.valueDeclaration.initializer === type.symbol.valueDeclaration) { + var sigs = type.getCallSignatures(); + if (sigs.length === 1) + return checker.getReturnTypeOfSignature(ts.first(sigs)); + } + return undefined; + } + function getDefinitionAndBoundSpan(program, sourceFile, position) { + var definitions = getDefinitionAtPosition(program, sourceFile, position); + if (!definitions || definitions.length === 0) { + return undefined; + } + // Check if position is on triple slash reference. + var comment = findReferenceInPosition(sourceFile.referencedFiles, position) || + findReferenceInPosition(sourceFile.typeReferenceDirectives, position) || + findReferenceInPosition(sourceFile.libReferenceDirectives, position); + if (comment) { + return { definitions: definitions, textSpan: ts.createTextSpanFromRange(comment) }; + } + var node = ts.getTouchingPropertyName(sourceFile, position); + var textSpan = ts.createTextSpan(node.getStart(), node.getWidth()); + return { definitions: definitions, textSpan: textSpan }; + } + GoToDefinition.getDefinitionAndBoundSpan = getDefinitionAndBoundSpan; + // At 'x.foo', see if the type of 'x' has an index signature, and if so find its declarations. + function getDefinitionInfoForIndexSignatures(node, checker) { + if (!ts.isPropertyAccessExpression(node.parent) || node.parent.name !== node) + return; + var type = checker.getTypeAtLocation(node.parent.expression); + return ts.mapDefined(type.isUnionOrIntersection() ? type.types : [type], function (nonUnionType) { + var info = checker.getIndexInfoOfType(nonUnionType, 0 /* String */); + return info && info.declaration && createDefinitionFromSignatureDeclaration(checker, info.declaration); + }); + } + function getSymbol(node, checker) { + var symbol = checker.getSymbolAtLocation(node); + // If this is an alias, and the request came at the declaration location + // get the aliased symbol instead. This allows for goto def on an import e.g. + // import {A, B} from "mod"; + // to jump to the implementation directly. + if (symbol && symbol.flags & 2097152 /* Alias */ && shouldSkipAlias(node, symbol.declarations[0])) { + var aliased = checker.getAliasedSymbol(symbol); + if (aliased.declarations) { + return aliased; + } + } + return symbol; + } + // Go to the original declaration for cases: + // + // (1) when the aliased symbol was declared in the location(parent). + // (2) when the aliased symbol is originating from an import. + // + function shouldSkipAlias(node, declaration) { + if (node.kind !== 72 /* Identifier */) { + return false; + } + if (node.parent === declaration) { + return true; + } + switch (declaration.kind) { + case 250 /* ImportClause */: + case 248 /* ImportEqualsDeclaration */: + return true; + case 253 /* ImportSpecifier */: + return declaration.parent.kind === 252 /* NamedImports */; + default: + return false; + } + } + function getDefinitionFromSymbol(typeChecker, symbol, node) { + return getConstructSignatureDefinition() || getCallSignatureDefinition() || ts.map(symbol.declarations, function (declaration) { return createDefinitionInfo(declaration, typeChecker, symbol, node); }); + function getConstructSignatureDefinition() { + // Applicable only if we are in a new expression, or we are on a constructor declaration + // and in either case the symbol has a construct signature definition, i.e. class + if (symbol.flags & 32 /* Class */ && (ts.isNewExpressionTarget(node) || node.kind === 124 /* ConstructorKeyword */)) { + var cls = ts.find(symbol.declarations, ts.isClassLike) || ts.Debug.fail("Expected declaration to have at least one class-like declaration"); + return getSignatureDefinition(cls.members, /*selectConstructors*/ true); + } + } + function getCallSignatureDefinition() { + return ts.isCallOrNewExpressionTarget(node) || ts.isNameOfFunctionDeclaration(node) + ? getSignatureDefinition(symbol.declarations, /*selectConstructors*/ false) + : undefined; + } + function getSignatureDefinition(signatureDeclarations, selectConstructors) { + if (!signatureDeclarations) { + return undefined; + } + var declarations = signatureDeclarations.filter(selectConstructors ? ts.isConstructorDeclaration : ts.isFunctionLike); + return declarations.length + ? [createDefinitionInfo(ts.find(declarations, function (d) { return !!d.body; }) || ts.last(declarations), typeChecker, symbol, node)] + : undefined; + } + } + /** Creates a DefinitionInfo from a Declaration, using the declaration's name if possible. */ + function createDefinitionInfo(declaration, checker, symbol, node) { + var symbolName = checker.symbolToString(symbol); // Do not get scoped name, just the name of the symbol + var symbolKind = ts.SymbolDisplay.getSymbolKind(checker, symbol, node); + var containerName = symbol.parent ? checker.symbolToString(symbol.parent, node) : ""; + return createDefinitionInfoFromName(declaration, symbolKind, symbolName, containerName); + } + /** Creates a DefinitionInfo directly from the name of a declaration. */ + function createDefinitionInfoFromName(declaration, symbolKind, symbolName, containerName) { + var name = ts.getNameOfDeclaration(declaration) || declaration; + var sourceFile = name.getSourceFile(); + return { + fileName: sourceFile.fileName, + textSpan: ts.createTextSpanFromNode(name, sourceFile), + kind: symbolKind, + name: symbolName, + containerKind: undefined, + containerName: containerName + }; + } + function createDefinitionFromSignatureDeclaration(typeChecker, decl) { + return createDefinitionInfo(decl, typeChecker, decl.symbol, decl); + } + function findReferenceInPosition(refs, pos) { + return ts.find(refs, function (ref) { return ts.textRangeContainsPositionInclusive(ref, pos); }); + } + GoToDefinition.findReferenceInPosition = findReferenceInPosition; + function getDefinitionInfoForFileReference(name, targetFileName) { + return { + fileName: targetFileName, + textSpan: ts.createTextSpanFromBounds(0, 0), + kind: "script" /* scriptElement */, + name: name, + containerName: undefined, + containerKind: undefined, + }; + } + /** Returns a CallLikeExpression where `node` is the target being invoked. */ + function getAncestorCallLikeExpression(node) { + var target = climbPastManyPropertyAccesses(node); + var callLike = target.parent; + return callLike && ts.isCallLikeExpression(callLike) && ts.getInvokedExpression(callLike) === target ? callLike : undefined; + } + function climbPastManyPropertyAccesses(node) { + return ts.isRightSideOfPropertyAccess(node) ? climbPastManyPropertyAccesses(node.parent) : node; + } + function tryGetSignatureDeclaration(typeChecker, node) { + var callLike = getAncestorCallLikeExpression(node); + var signature = callLike && typeChecker.getResolvedSignature(callLike); + // Don't go to a function type, go to the value having that type. + return ts.tryCast(signature && signature.declaration, function (d) { return ts.isFunctionLike(d) && !ts.isFunctionTypeNode(d); }); + } + function isConstructorLike(node) { + switch (node.kind) { + case 157 /* Constructor */: + case 166 /* ConstructorType */: + case 161 /* ConstructSignature */: + return true; + default: + return false; + } + } + })(GoToDefinition = ts.GoToDefinition || (ts.GoToDefinition = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var JsDoc; + (function (JsDoc) { + var jsDocTagNames = [ + "abstract", + "access", + "alias", + "argument", + "async", + "augments", + "author", + "borrows", + "callback", + "class", + "classdesc", + "constant", + "constructor", + "constructs", + "copyright", + "default", + "deprecated", + "description", + "emits", + "enum", + "event", + "example", + "exports", + "extends", + "external", + "field", + "file", + "fileoverview", + "fires", + "function", + "generator", + "global", + "hideconstructor", + "host", + "ignore", + "implements", + "inheritdoc", + "inner", + "instance", + "interface", + "kind", + "lends", + "license", + "listens", + "member", + "memberof", + "method", + "mixes", + "module", + "name", + "namespace", + "override", + "package", + "param", + "private", + "property", + "protected", + "public", + "readonly", + "requires", + "returns", + "see", + "since", + "static", + "summary", + "template", + "this", + "throws", + "todo", + "tutorial", + "type", + "typedef", + "var", + "variation", + "version", + "virtual", + "yields" + ]; + var jsDocTagNameCompletionEntries; + var jsDocTagCompletionEntries; + function getJsDocCommentsFromDeclarations(declarations) { + // Only collect doc comments from duplicate declarations once: + // In case of a union property there might be same declaration multiple times + // which only varies in type parameter + // Eg. const a: Array | Array; a.length + // The property length will have two declarations of property length coming + // from Array - Array and Array + var documentationComment = []; + forEachUnique(declarations, function (declaration) { + for (var _i = 0, _a = getCommentHavingNodes(declaration); _i < _a.length; _i++) { + var comment = _a[_i].comment; + if (comment === undefined) + continue; + if (documentationComment.length) { + documentationComment.push(ts.lineBreakPart()); + } + documentationComment.push(ts.textPart(comment)); + } + }); + return documentationComment; + } + JsDoc.getJsDocCommentsFromDeclarations = getJsDocCommentsFromDeclarations; + function getCommentHavingNodes(declaration) { + switch (declaration.kind) { + case 299 /* JSDocParameterTag */: + case 305 /* JSDocPropertyTag */: + return [declaration]; + case 297 /* JSDocCallbackTag */: + case 304 /* JSDocTypedefTag */: + return [declaration, declaration.parent]; + default: + return ts.getJSDocCommentsAndTags(declaration); + } + } + function getJsDocTagsFromDeclarations(declarations) { + // Only collect doc comments from duplicate declarations once. + var tags = []; + forEachUnique(declarations, function (declaration) { + for (var _i = 0, _a = ts.getJSDocTags(declaration); _i < _a.length; _i++) { + var tag = _a[_i]; + tags.push({ name: tag.tagName.text, text: getCommentText(tag) }); + } + }); + return tags; + } + JsDoc.getJsDocTagsFromDeclarations = getJsDocTagsFromDeclarations; + function getCommentText(tag) { + var comment = tag.comment; + switch (tag.kind) { + case 295 /* JSDocAugmentsTag */: + return withNode(tag.class); + case 303 /* JSDocTemplateTag */: + return withList(tag.typeParameters); + case 302 /* JSDocTypeTag */: + return withNode(tag.typeExpression); + case 304 /* JSDocTypedefTag */: + case 297 /* JSDocCallbackTag */: + case 305 /* JSDocPropertyTag */: + case 299 /* JSDocParameterTag */: + var name = tag.name; + return name ? withNode(name) : comment; + default: + return comment; + } + function withNode(node) { + return addComment(node.getText()); + } + function withList(list) { + return addComment(list.map(function (x) { return x.getText(); }).join(", ")); + } + function addComment(s) { + return comment === undefined ? s : s + " " + comment; + } + } + /** + * Iterates through 'array' by index and performs the callback on each element of array until the callback + * returns a truthy value, then returns that value. + * If no such value is found, the callback is applied to each element of array and undefined is returned. + */ + function forEachUnique(array, callback) { + if (array) { + for (var i = 0; i < array.length; i++) { + if (array.indexOf(array[i]) === i) { + var result = callback(array[i], i); + if (result) { + return result; + } + } + } + } + return undefined; + } + function getJSDocTagNameCompletions() { + return jsDocTagNameCompletionEntries || (jsDocTagNameCompletionEntries = ts.map(jsDocTagNames, function (tagName) { + return { + name: tagName, + kind: "keyword" /* keyword */, + kindModifiers: "", + sortText: "0", + }; + })); + } + JsDoc.getJSDocTagNameCompletions = getJSDocTagNameCompletions; + JsDoc.getJSDocTagNameCompletionDetails = getJSDocTagCompletionDetails; + function getJSDocTagCompletions() { + return jsDocTagCompletionEntries || (jsDocTagCompletionEntries = ts.map(jsDocTagNames, function (tagName) { + return { + name: "@" + tagName, + kind: "keyword" /* keyword */, + kindModifiers: "", + sortText: "0" + }; + })); + } + JsDoc.getJSDocTagCompletions = getJSDocTagCompletions; + function getJSDocTagCompletionDetails(name) { + return { + name: name, + kind: "" /* unknown */, + kindModifiers: "", + displayParts: [ts.textPart(name)], + documentation: ts.emptyArray, + tags: undefined, + codeActions: undefined, + }; + } + JsDoc.getJSDocTagCompletionDetails = getJSDocTagCompletionDetails; + function getJSDocParameterNameCompletions(tag) { + if (!ts.isIdentifier(tag.name)) { + return ts.emptyArray; + } + var nameThusFar = tag.name.text; + var jsdoc = tag.parent; + var fn = jsdoc.parent; + if (!ts.isFunctionLike(fn)) + return []; + return ts.mapDefined(fn.parameters, function (param) { + if (!ts.isIdentifier(param.name)) + return undefined; + var name = param.name.text; + if (jsdoc.tags.some(function (t) { return t !== tag && ts.isJSDocParameterTag(t) && ts.isIdentifier(t.name) && t.name.escapedText === name; }) // TODO: GH#18217 + || nameThusFar !== undefined && !ts.startsWith(name, nameThusFar)) { + return undefined; + } + return { name: name, kind: "parameter" /* parameterElement */, kindModifiers: "", sortText: "0" }; + }); + } + JsDoc.getJSDocParameterNameCompletions = getJSDocParameterNameCompletions; + function getJSDocParameterNameCompletionDetails(name) { + return { + name: name, + kind: "parameter" /* parameterElement */, + kindModifiers: "", + displayParts: [ts.textPart(name)], + documentation: ts.emptyArray, + tags: undefined, + codeActions: undefined, + }; + } + JsDoc.getJSDocParameterNameCompletionDetails = getJSDocParameterNameCompletionDetails; + /** + * Checks if position points to a valid position to add JSDoc comments, and if so, + * returns the appropriate template. Otherwise returns an empty string. + * Valid positions are + * - outside of comments, statements, and expressions, and + * - preceding a: + * - function/constructor/method declaration + * - class declarations + * - variable statements + * - namespace declarations + * - interface declarations + * - method signatures + * - type alias declarations + * + * Hosts should ideally check that: + * - The line is all whitespace up to 'position' before performing the insertion. + * - If the keystroke sequence "/\*\*" induced the call, we also check that the next + * non-whitespace character is '*', which (approximately) indicates whether we added + * the second '*' to complete an existing (JSDoc) comment. + * @param fileName The file in which to perform the check. + * @param position The (character-indexed) position in the file where the check should + * be performed. + */ + function getDocCommentTemplateAtPosition(newLine, sourceFile, position) { + var tokenAtPos = ts.getTokenAtPosition(sourceFile, position); + var existingDocComment = ts.findAncestor(tokenAtPos, ts.isJSDoc); + if (existingDocComment && (existingDocComment.comment !== undefined || ts.length(existingDocComment.tags))) { + // Non-empty comment already exists. + return undefined; + } + var tokenStart = tokenAtPos.getStart(sourceFile); + // Don't provide a doc comment template based on a *previous* node. (But an existing empty jsdoc comment will likely start before `position`.) + if (!existingDocComment && tokenStart < position) { + return undefined; + } + var commentOwnerInfo = getCommentOwnerInfo(tokenAtPos); + if (!commentOwnerInfo) { + return undefined; + } + var commentOwner = commentOwnerInfo.commentOwner, parameters = commentOwnerInfo.parameters; + if (commentOwner.getStart(sourceFile) < position) { + return undefined; + } + if (!parameters || parameters.length === 0) { + // if there are no parameters, just complete to a single line JSDoc comment + var singleLineResult = "/** */"; + return { newText: singleLineResult, caretOffset: 3 }; + } + var indentationStr = getIndentationStringAtPosition(sourceFile, position); + // A doc comment consists of the following + // * The opening comment line + // * the first line (without a param) for the object's untagged info (this is also where the caret ends up) + // * the '@param'-tagged lines + // * TODO: other tags. + // * the closing comment line + // * if the caret was directly in front of the object, then we add an extra line and indentation. + var preamble = "/**" + newLine + indentationStr + " * "; + var result = preamble + newLine + + parameterDocComments(parameters, ts.hasJSFileExtension(sourceFile.fileName), indentationStr, newLine) + + indentationStr + " */" + + (tokenStart === position ? newLine + indentationStr : ""); + return { newText: result, caretOffset: preamble.length }; + } + JsDoc.getDocCommentTemplateAtPosition = getDocCommentTemplateAtPosition; + function getIndentationStringAtPosition(sourceFile, position) { + var text = sourceFile.text; + var lineStart = ts.getLineStartPositionForPosition(position, sourceFile); + var pos = lineStart; + for (; pos <= position && ts.isWhiteSpaceSingleLine(text.charCodeAt(pos)); pos++) + ; + return text.slice(lineStart, pos); + } + function parameterDocComments(parameters, isJavaScriptFile, indentationStr, newLine) { + return parameters.map(function (_a, i) { + var name = _a.name, dotDotDotToken = _a.dotDotDotToken; + var paramName = name.kind === 72 /* Identifier */ ? name.text : "param" + i; + var type = isJavaScriptFile ? (dotDotDotToken ? "{...any} " : "{any} ") : ""; + return indentationStr + " * @param " + type + paramName + newLine; + }).join(""); + } + function getCommentOwnerInfo(tokenAtPos) { + return ts.forEachAncestor(tokenAtPos, getCommentOwnerInfoWorker); + } + function getCommentOwnerInfoWorker(commentOwner) { + switch (commentOwner.kind) { + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 156 /* MethodDeclaration */: + case 157 /* Constructor */: + case 155 /* MethodSignature */: + var parameters = commentOwner.parameters; + return { commentOwner: commentOwner, parameters: parameters }; + case 275 /* PropertyAssignment */: + return getCommentOwnerInfoWorker(commentOwner.initializer); + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + case 153 /* PropertySignature */: + case 243 /* EnumDeclaration */: + case 278 /* EnumMember */: + case 242 /* TypeAliasDeclaration */: + return { commentOwner: commentOwner }; + case 219 /* VariableStatement */: { + var varStatement = commentOwner; + var varDeclarations = varStatement.declarationList.declarations; + var parameters_1 = varDeclarations.length === 1 && varDeclarations[0].initializer + ? getParametersFromRightHandSideOfAssignment(varDeclarations[0].initializer) + : undefined; + return { commentOwner: commentOwner, parameters: parameters_1 }; + } + case 279 /* SourceFile */: + return "quit"; + case 244 /* ModuleDeclaration */: + // If in walking up the tree, we hit a a nested namespace declaration, + // then we must be somewhere within a dotted namespace name; however we don't + // want to give back a JSDoc template for the 'b' or 'c' in 'namespace a.b.c { }'. + return commentOwner.parent.kind === 244 /* ModuleDeclaration */ ? undefined : { commentOwner: commentOwner }; + case 204 /* BinaryExpression */: { + var be = commentOwner; + if (ts.getAssignmentDeclarationKind(be) === 0 /* None */) { + return "quit"; + } + var parameters_2 = ts.isFunctionLike(be.right) ? be.right.parameters : ts.emptyArray; + return { commentOwner: commentOwner, parameters: parameters_2 }; + } + } + } + /** + * Digs into an an initializer or RHS operand of an assignment operation + * to get the parameters of an apt signature corresponding to a + * function expression or a class expression. + * + * @param rightHandSide the expression which may contain an appropriate set of parameters + * @returns the parameters of a signature found on the RHS if one exists; otherwise 'emptyArray'. + */ + function getParametersFromRightHandSideOfAssignment(rightHandSide) { + while (rightHandSide.kind === 195 /* ParenthesizedExpression */) { + rightHandSide = rightHandSide.expression; + } + switch (rightHandSide.kind) { + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + return rightHandSide.parameters; + case 209 /* ClassExpression */: { + var ctr = ts.find(rightHandSide.members, ts.isConstructorDeclaration); + return ctr ? ctr.parameters : ts.emptyArray; + } + } + return ts.emptyArray; + } + })(JsDoc = ts.JsDoc || (ts.JsDoc = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var NavigateTo; + (function (NavigateTo) { + function getNavigateToItems(sourceFiles, checker, cancellationToken, searchValue, maxResultCount, excludeDtsFiles) { + var patternMatcher = ts.createPatternMatcher(searchValue); + if (!patternMatcher) + return ts.emptyArray; + var rawItems = []; + var _loop_13 = function (sourceFile) { + cancellationToken.throwIfCancellationRequested(); + if (excludeDtsFiles && sourceFile.isDeclarationFile) { + return "continue"; + } + sourceFile.getNamedDeclarations().forEach(function (declarations, name) { + getItemsFromNamedDeclaration(patternMatcher, name, declarations, checker, sourceFile.fileName, rawItems); + }); + }; + // Search the declarations in all files and output matched NavigateToItem into array of NavigateToItem[] + for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) { + var sourceFile = sourceFiles_6[_i]; + _loop_13(sourceFile); + } + rawItems.sort(compareNavigateToItems); + return (maxResultCount === undefined ? rawItems : rawItems.slice(0, maxResultCount)).map(createNavigateToItem); + } + NavigateTo.getNavigateToItems = getNavigateToItems; + function getItemsFromNamedDeclaration(patternMatcher, name, declarations, checker, fileName, rawItems) { + // First do a quick check to see if the name of the declaration matches the + // last portion of the (possibly) dotted name they're searching for. + var match = patternMatcher.getMatchForLastSegmentOfPattern(name); + if (!match) { + return; // continue to next named declarations + } + for (var _i = 0, declarations_13 = declarations; _i < declarations_13.length; _i++) { + var declaration = declarations_13[_i]; + if (!shouldKeepItem(declaration, checker)) + continue; + if (patternMatcher.patternContainsDots) { + // If the pattern has dots in it, then also see if the declaration container matches as well. + var fullMatch = patternMatcher.getFullMatch(getContainers(declaration), name); + if (fullMatch) { + rawItems.push({ name: name, fileName: fileName, matchKind: fullMatch.kind, isCaseSensitive: fullMatch.isCaseSensitive, declaration: declaration }); + } + } + else { + rawItems.push({ name: name, fileName: fileName, matchKind: match.kind, isCaseSensitive: match.isCaseSensitive, declaration: declaration }); + } + } + } + function shouldKeepItem(declaration, checker) { + switch (declaration.kind) { + case 250 /* ImportClause */: + case 253 /* ImportSpecifier */: + case 248 /* ImportEqualsDeclaration */: + var importer = checker.getSymbolAtLocation(declaration.name); // TODO: GH#18217 + var imported = checker.getAliasedSymbol(importer); + return importer.escapedName !== imported.escapedName; + default: + return true; + } + } + function tryAddSingleDeclarationName(declaration, containers) { + var name = ts.getNameOfDeclaration(declaration); + return !!name && (pushLiteral(name, containers) || name.kind === 149 /* ComputedPropertyName */ && tryAddComputedPropertyName(name.expression, containers)); + } + // Only added the names of computed properties if they're simple dotted expressions, like: + // + // [X.Y.Z]() { } + function tryAddComputedPropertyName(expression, containers) { + return pushLiteral(expression, containers) + || ts.isPropertyAccessExpression(expression) && (containers.push(expression.name.text), true) && tryAddComputedPropertyName(expression.expression, containers); + } + function pushLiteral(node, containers) { + return ts.isPropertyNameLiteral(node) && (containers.push(ts.getTextOfIdentifierOrLiteral(node)), true); + } + function getContainers(declaration) { + var containers = []; + // First, if we started with a computed property name, then add all but the last + // portion into the container array. + var name = ts.getNameOfDeclaration(declaration); + if (name && name.kind === 149 /* ComputedPropertyName */ && !tryAddComputedPropertyName(name.expression, containers)) { + return ts.emptyArray; + } + // Don't include the last portion. + containers.shift(); + // Now, walk up our containers, adding all their names to the container array. + var container = ts.getContainerNode(declaration); + while (container) { + if (!tryAddSingleDeclarationName(container, containers)) { + return ts.emptyArray; + } + container = ts.getContainerNode(container); + } + return containers.reverse(); + } + function compareNavigateToItems(i1, i2) { + // TODO(cyrusn): get the gamut of comparisons that VS already uses here. + return ts.compareValues(i1.matchKind, i2.matchKind) + || ts.compareStringsCaseSensitiveUI(i1.name, i2.name); + } + function createNavigateToItem(rawItem) { + var declaration = rawItem.declaration; + var container = ts.getContainerNode(declaration); + var containerName = container && ts.getNameOfDeclaration(container); + return { + name: rawItem.name, + kind: ts.getNodeKind(declaration), + kindModifiers: ts.getNodeModifiers(declaration), + matchKind: ts.PatternMatchKind[rawItem.matchKind], + isCaseSensitive: rawItem.isCaseSensitive, + fileName: rawItem.fileName, + textSpan: ts.createTextSpanFromNode(declaration), + // TODO(jfreeman): What should be the containerName when the container has a computed name? + containerName: containerName ? containerName.text : "", + containerKind: containerName ? ts.getNodeKind(container) : "" /* unknown */, + }; + } + })(NavigateTo = ts.NavigateTo || (ts.NavigateTo = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var NavigationBar; + (function (NavigationBar) { + /** + * Matches all whitespace characters in a string. Eg: + * + * "app. + * + * onactivated" + * + * matches because of the newline, whereas + * + * "app.onactivated" + * + * does not match. + */ + var whiteSpaceRegex = /\s+/g; + // Keep sourceFile handy so we don't have to search for it every time we need to call `getText`. + var curCancellationToken; + var curSourceFile; + /** + * For performance, we keep navigation bar parents on a stack rather than passing them through each recursion. + * `parent` is the current parent and is *not* stored in parentsStack. + * `startNode` sets a new parent and `endNode` returns to the previous parent. + */ + var parentsStack = []; + var parent; + // NavigationBarItem requires an array, but will not mutate it, so just give it this for performance. + var emptyChildItemArray = []; + function getNavigationBarItems(sourceFile, cancellationToken) { + curCancellationToken = cancellationToken; + curSourceFile = sourceFile; + try { + return ts.map(topLevelItems(rootNavigationBarNode(sourceFile)), convertToTopLevelItem); + } + finally { + reset(); + } + } + NavigationBar.getNavigationBarItems = getNavigationBarItems; + function getNavigationTree(sourceFile, cancellationToken) { + curCancellationToken = cancellationToken; + curSourceFile = sourceFile; + try { + return convertToTree(rootNavigationBarNode(sourceFile)); + } + finally { + reset(); + } + } + NavigationBar.getNavigationTree = getNavigationTree; + function reset() { + curSourceFile = undefined; + curCancellationToken = undefined; + parentsStack = []; + parent = undefined; + emptyChildItemArray = []; + } + function nodeText(node) { + return node.getText(curSourceFile); + } + function navigationBarNodeKind(n) { + return n.node.kind; + } + function pushChild(parent, child) { + if (parent.children) { + parent.children.push(child); + } + else { + parent.children = [child]; + } + } + function rootNavigationBarNode(sourceFile) { + ts.Debug.assert(!parentsStack.length); + var root = { node: sourceFile, name: undefined, additionalNodes: undefined, parent: undefined, children: undefined, indent: 0 }; + parent = root; + for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + addChildrenRecursively(statement); + } + endNode(); + ts.Debug.assert(!parent && !parentsStack.length); + return root; + } + function addLeafNode(node) { + pushChild(parent, emptyNavigationBarNode(node)); + } + function emptyNavigationBarNode(node) { + return { + node: node, + name: ts.isDeclaration(node) || ts.isExpression(node) ? ts.getNameOfDeclaration(node) : undefined, + additionalNodes: undefined, + parent: parent, + children: undefined, + indent: parent.indent + 1 + }; + } + /** + * Add a new level of NavigationBarNodes. + * This pushes to the stack, so you must call `endNode` when you are done adding to this node. + */ + function startNode(node) { + var navNode = emptyNavigationBarNode(node); + pushChild(parent, navNode); + // Save the old parent + parentsStack.push(parent); + parent = navNode; + } + /** Call after calling `startNode` and adding children to it. */ + function endNode() { + if (parent.children) { + mergeChildren(parent.children, parent); + sortChildren(parent.children); + } + parent = parentsStack.pop(); + } + function addNodeWithRecursiveChild(node, child) { + startNode(node); + addChildrenRecursively(child); + endNode(); + } + /** Look for navigation bar items in node's subtree, adding them to the current `parent`. */ + function addChildrenRecursively(node) { + curCancellationToken.throwIfCancellationRequested(); + if (!node || ts.isToken(node)) { + return; + } + switch (node.kind) { + case 157 /* Constructor */: + // Get parameter properties, and treat them as being on the *same* level as the constructor, not under it. + var ctr = node; + addNodeWithRecursiveChild(ctr, ctr.body); + // Parameter properties are children of the class, not the constructor. + for (var _i = 0, _a = ctr.parameters; _i < _a.length; _i++) { + var param = _a[_i]; + if (ts.isParameterPropertyDeclaration(param)) { + addLeafNode(param); + } + } + break; + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 155 /* MethodSignature */: + if (!ts.hasDynamicName(node)) { + addNodeWithRecursiveChild(node, node.body); + } + break; + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + if (!ts.hasDynamicName(node)) { + addLeafNode(node); + } + break; + case 250 /* ImportClause */: + var importClause = node; + // Handle default import case e.g.: + // import d from "mod"; + if (importClause.name) { + addLeafNode(importClause.name); + } + // Handle named bindings in imports e.g.: + // import * as NS from "mod"; + // import {a, b as B} from "mod"; + var namedBindings = importClause.namedBindings; + if (namedBindings) { + if (namedBindings.kind === 251 /* NamespaceImport */) { + addLeafNode(namedBindings); + } + else { + for (var _b = 0, _c = namedBindings.elements; _b < _c.length; _b++) { + var element = _c[_b]; + addLeafNode(element); + } + } + } + break; + case 186 /* BindingElement */: + case 237 /* VariableDeclaration */: + var _d = node, name = _d.name, initializer = _d.initializer; + if (ts.isBindingPattern(name)) { + addChildrenRecursively(name); + } + else if (initializer && isFunctionOrClassExpression(initializer)) { + if (initializer.name) { + // Don't add a node for the VariableDeclaration, just for the initializer. + addChildrenRecursively(initializer); + } + else { + // Add a node for the VariableDeclaration, but not for the initializer. + startNode(node); + ts.forEachChild(initializer, addChildrenRecursively); + endNode(); + } + } + else { + addNodeWithRecursiveChild(node, initializer); + } + break; + case 197 /* ArrowFunction */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + addNodeWithRecursiveChild(node, node.body); + break; + case 243 /* EnumDeclaration */: + startNode(node); + for (var _e = 0, _f = node.members; _e < _f.length; _e++) { + var member = _f[_e]; + if (!isComputedProperty(member)) { + addLeafNode(member); + } + } + endNode(); + break; + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 241 /* InterfaceDeclaration */: + startNode(node); + for (var _g = 0, _h = node.members; _g < _h.length; _g++) { + var member = _h[_g]; + addChildrenRecursively(member); + } + endNode(); + break; + case 244 /* ModuleDeclaration */: + addNodeWithRecursiveChild(node, getInteriorModule(node).body); + break; + case 257 /* ExportSpecifier */: + case 248 /* ImportEqualsDeclaration */: + case 162 /* IndexSignature */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 242 /* TypeAliasDeclaration */: + addLeafNode(node); + break; + case 204 /* BinaryExpression */: { + var special = ts.getAssignmentDeclarationKind(node); + switch (special) { + case 1 /* ExportsProperty */: + case 2 /* ModuleExports */: + case 3 /* PrototypeProperty */: + case 6 /* Prototype */: + addNodeWithRecursiveChild(node, node.right); + return; + case 4 /* ThisProperty */: + case 5 /* Property */: + case 0 /* None */: + case 7 /* ObjectDefinePropertyValue */: + case 8 /* ObjectDefinePropertyExports */: + case 9 /* ObjectDefinePrototypeProperty */: + break; + default: + ts.Debug.assertNever(special); + } + } + // falls through + default: + if (ts.hasJSDocNodes(node)) { + ts.forEach(node.jsDoc, function (jsDoc) { + ts.forEach(jsDoc.tags, function (tag) { + if (ts.isJSDocTypeAlias(tag)) { + addLeafNode(tag); + } + }); + }); + } + ts.forEachChild(node, addChildrenRecursively); + } + } + /** Merge declarations of the same kind. */ + function mergeChildren(children, node) { + var nameToItems = ts.createMap(); + ts.filterMutate(children, function (child) { + var declName = ts.getNameOfDeclaration(child.node); + var name = declName && nodeText(declName); + if (!name) { + // Anonymous items are never merged. + return true; + } + var itemsWithSameName = nameToItems.get(name); + if (!itemsWithSameName) { + nameToItems.set(name, child); + return true; + } + if (itemsWithSameName instanceof Array) { + for (var _i = 0, itemsWithSameName_1 = itemsWithSameName; _i < itemsWithSameName_1.length; _i++) { + var itemWithSameName = itemsWithSameName_1[_i]; + if (tryMerge(itemWithSameName, child, node)) { + return false; + } + } + itemsWithSameName.push(child); + return true; + } + else { + var itemWithSameName = itemsWithSameName; + if (tryMerge(itemWithSameName, child, node)) { + return false; + } + nameToItems.set(name, [itemWithSameName, child]); + return true; + } + }); + } + function tryMerge(a, b, parent) { + if (shouldReallyMerge(a.node, b.node, parent)) { + merge(a, b); + return true; + } + return false; + } + /** a and b have the same name, but they may not be mergeable. */ + function shouldReallyMerge(a, b, parent) { + if (a.kind !== b.kind || a.parent !== b.parent && !(isOwnChild(a, parent) && isOwnChild(b, parent))) { + return false; + } + switch (a.kind) { + case 154 /* PropertyDeclaration */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + return ts.hasModifier(a, 32 /* Static */) === ts.hasModifier(b, 32 /* Static */); + case 244 /* ModuleDeclaration */: + return areSameModule(a, b); + default: + return true; + } + } + // We want to merge own children like `I` in in `module A { interface I {} } module A { interface I {} }` + // We don't want to merge unrelated children like `m` in `const o = { a: { m() {} }, b: { m() {} } };` + function isOwnChild(n, parent) { + var par = ts.isModuleBlock(n.parent) ? n.parent.parent : n.parent; + return par === parent.node || ts.contains(parent.additionalNodes, par); + } + // We use 1 NavNode to represent 'A.B.C', but there are multiple source nodes. + // Only merge module nodes that have the same chain. Don't merge 'A.B.C' with 'A'! + function areSameModule(a, b) { + // TODO: GH#18217 + return a.body.kind === b.body.kind && (a.body.kind !== 244 /* ModuleDeclaration */ || areSameModule(a.body, b.body)); + } + /** Merge source into target. Source should be thrown away after this is called. */ + function merge(target, source) { + var _a; + target.additionalNodes = target.additionalNodes || []; + target.additionalNodes.push(source.node); + if (source.additionalNodes) { + (_a = target.additionalNodes).push.apply(_a, source.additionalNodes); + } + target.children = ts.concatenate(target.children, source.children); + if (target.children) { + mergeChildren(target.children, target); + sortChildren(target.children); + } + } + /** Recursively ensure that each NavNode's children are in sorted order. */ + function sortChildren(children) { + children.sort(compareChildren); + } + function compareChildren(child1, child2) { + return ts.compareStringsCaseSensitiveUI(tryGetName(child1.node), tryGetName(child2.node)) // TODO: GH#18217 + || ts.compareValues(navigationBarNodeKind(child1), navigationBarNodeKind(child2)); + } + /** + * This differs from getItemName because this is just used for sorting. + * We only sort nodes by name that have a more-or-less "direct" name, as opposed to `new()` and the like. + * So `new()` can still come before an `aardvark` method. + */ + function tryGetName(node) { + if (node.kind === 244 /* ModuleDeclaration */) { + return getModuleName(node); + } + var declName = ts.getNameOfDeclaration(node); + if (declName && ts.isPropertyName(declName)) { + return ts.unescapeLeadingUnderscores(ts.getPropertyNameForPropertyNameNode(declName)); // TODO: GH#18217 + } + switch (node.kind) { + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 209 /* ClassExpression */: + return getFunctionOrClassName(node); + default: + return undefined; + } + } + function getItemName(node, name) { + if (node.kind === 244 /* ModuleDeclaration */) { + return getModuleName(node); + } + if (name) { + var text = nodeText(name); + if (text.length > 0) { + return text; + } + } + switch (node.kind) { + case 279 /* SourceFile */: + var sourceFile = node; + return ts.isExternalModule(sourceFile) + ? "\"" + ts.escapeString(ts.getBaseFileName(ts.removeFileExtension(ts.normalizePath(sourceFile.fileName)))) + "\"" + : ""; + case 197 /* ArrowFunction */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + if (ts.getModifierFlags(node) & 512 /* Default */) { + return "default"; + } + // We may get a string with newlines or other whitespace in the case of an object dereference + // (eg: "app\n.onactivated"), so we should remove the whitespace for readabiltiy in the + // navigation bar. + return getFunctionOrClassName(node); + case 157 /* Constructor */: + return "constructor"; + case 161 /* ConstructSignature */: + return "new()"; + case 160 /* CallSignature */: + return "()"; + case 162 /* IndexSignature */: + return "[]"; + default: + return ""; + } + } + /** Flattens the NavNode tree to a list, keeping only the top-level items. */ + function topLevelItems(root) { + var topLevel = []; + function recur(item) { + if (isTopLevel(item)) { + topLevel.push(item); + if (item.children) { + for (var _i = 0, _a = item.children; _i < _a.length; _i++) { + var child = _a[_i]; + recur(child); + } + } + } + } + recur(root); + return topLevel; + function isTopLevel(item) { + switch (navigationBarNodeKind(item)) { + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 243 /* EnumDeclaration */: + case 241 /* InterfaceDeclaration */: + case 244 /* ModuleDeclaration */: + case 279 /* SourceFile */: + case 242 /* TypeAliasDeclaration */: + case 304 /* JSDocTypedefTag */: + case 297 /* JSDocCallbackTag */: + return true; + case 157 /* Constructor */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 237 /* VariableDeclaration */: + return hasSomeImportantChild(item); + case 197 /* ArrowFunction */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + return isTopLevelFunctionDeclaration(item); + default: + return false; + } + function isTopLevelFunctionDeclaration(item) { + if (!item.node.body) { + return false; + } + switch (navigationBarNodeKind(item.parent)) { + case 245 /* ModuleBlock */: + case 279 /* SourceFile */: + case 156 /* MethodDeclaration */: + case 157 /* Constructor */: + return true; + default: + return hasSomeImportantChild(item); + } + } + function hasSomeImportantChild(item) { + return ts.some(item.children, function (child) { + var childKind = navigationBarNodeKind(child); + return childKind !== 237 /* VariableDeclaration */ && childKind !== 186 /* BindingElement */; + }); + } + } + } + function convertToTree(n) { + return { + text: getItemName(n.node, n.name), + kind: ts.getNodeKind(n.node), + kindModifiers: getModifiers(n.node), + spans: getSpans(n), + nameSpan: n.name && getNodeSpan(n.name), + childItems: ts.map(n.children, convertToTree) + }; + } + function convertToTopLevelItem(n) { + return { + text: getItemName(n.node, n.name), + kind: ts.getNodeKind(n.node), + kindModifiers: getModifiers(n.node), + spans: getSpans(n), + childItems: ts.map(n.children, convertToChildItem) || emptyChildItemArray, + indent: n.indent, + bolded: false, + grayed: false + }; + function convertToChildItem(n) { + return { + text: getItemName(n.node, n.name), + kind: ts.getNodeKind(n.node), + kindModifiers: ts.getNodeModifiers(n.node), + spans: getSpans(n), + childItems: emptyChildItemArray, + indent: 0, + bolded: false, + grayed: false + }; + } + } + function getSpans(n) { + var spans = [getNodeSpan(n.node)]; + if (n.additionalNodes) { + for (var _i = 0, _a = n.additionalNodes; _i < _a.length; _i++) { + var node = _a[_i]; + spans.push(getNodeSpan(node)); + } + } + return spans; + } + function getModuleName(moduleDeclaration) { + // We want to maintain quotation marks. + if (ts.isAmbientModule(moduleDeclaration)) { + return ts.getTextOfNode(moduleDeclaration.name); + } + // Otherwise, we need to aggregate each identifier to build up the qualified name. + var result = []; + result.push(ts.getTextOfIdentifierOrLiteral(moduleDeclaration.name)); + while (moduleDeclaration.body && moduleDeclaration.body.kind === 244 /* ModuleDeclaration */) { + moduleDeclaration = moduleDeclaration.body; + result.push(ts.getTextOfIdentifierOrLiteral(moduleDeclaration.name)); + } + return result.join("."); + } + /** + * For 'module A.B.C', we want to get the node for 'C'. + * We store 'A' as associated with a NavNode, and use getModuleName to traverse down again. + */ + function getInteriorModule(decl) { + return decl.body && ts.isModuleDeclaration(decl.body) ? getInteriorModule(decl.body) : decl; + } + function isComputedProperty(member) { + return !member.name || member.name.kind === 149 /* ComputedPropertyName */; + } + function getNodeSpan(node) { + return node.kind === 279 /* SourceFile */ ? ts.createTextSpanFromRange(node) : ts.createTextSpanFromNode(node, curSourceFile); + } + function getModifiers(node) { + if (node.parent && node.parent.kind === 237 /* VariableDeclaration */) { + node = node.parent; + } + return ts.getNodeModifiers(node); + } + function getFunctionOrClassName(node) { + var parent = node.parent; + if (node.name && ts.getFullWidth(node.name) > 0) { + return ts.declarationNameToString(node.name); + } + // See if it is a var initializer. If so, use the var name. + else if (ts.isVariableDeclaration(parent)) { + return ts.declarationNameToString(parent.name); + } + // See if it is of the form " = function(){...}". If so, use the text from the left-hand side. + else if (ts.isBinaryExpression(parent) && parent.operatorToken.kind === 59 /* EqualsToken */) { + return nodeText(parent.left).replace(whiteSpaceRegex, ""); + } + // See if it is a property assignment, and if so use the property name + else if (ts.isPropertyAssignment(parent)) { + return nodeText(parent.name); + } + // Default exports are named "default" + else if (ts.getModifierFlags(node) & 512 /* Default */) { + return "default"; + } + else if (ts.isClassLike(node)) { + return ""; + } + else if (ts.isCallExpression(parent)) { + var name = getCalledExpressionName(parent.expression); + if (name !== undefined) { + var args = ts.mapDefined(parent.arguments, function (a) { return ts.isStringLiteral(a) ? a.getText(curSourceFile) : undefined; }).join(", "); + return name + "(" + args + ") callback"; + } + } + return ""; + } + function getCalledExpressionName(expr) { + if (ts.isIdentifier(expr)) { + return expr.text; + } + else if (ts.isPropertyAccessExpression(expr)) { + var left = getCalledExpressionName(expr.expression); + var right = expr.name.text; + return left === undefined ? right : left + "." + right; + } + else { + return undefined; + } + } + function isFunctionOrClassExpression(node) { + switch (node.kind) { + case 197 /* ArrowFunction */: + case 196 /* FunctionExpression */: + case 209 /* ClassExpression */: + return true; + default: + return false; + } + } + })(NavigationBar = ts.NavigationBar || (ts.NavigationBar = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var OrganizeImports; + (function (OrganizeImports) { + /** + * Organize imports by: + * 1) Removing unused imports + * 2) Coalescing imports from the same module + * 3) Sorting imports + */ + function organizeImports(sourceFile, formatContext, host, program, _preferences) { + var changeTracker = ts.textChanges.ChangeTracker.fromContext({ host: host, formatContext: formatContext }); + var coalesceAndOrganizeImports = function (importGroup) { return coalesceImports(removeUnusedImports(importGroup, sourceFile, program)); }; + // All of the old ImportDeclarations in the file, in syntactic order. + var topLevelImportDecls = sourceFile.statements.filter(ts.isImportDeclaration); + organizeImportsWorker(topLevelImportDecls, coalesceAndOrganizeImports); + // All of the old ExportDeclarations in the file, in syntactic order. + var topLevelExportDecls = sourceFile.statements.filter(ts.isExportDeclaration); + organizeImportsWorker(topLevelExportDecls, coalesceExports); + for (var _i = 0, _a = sourceFile.statements.filter(ts.isAmbientModule); _i < _a.length; _i++) { + var ambientModule = _a[_i]; + var ambientModuleBody = getModuleBlock(ambientModule); // TODO: GH#18217 + var ambientModuleImportDecls = ambientModuleBody.statements.filter(ts.isImportDeclaration); + organizeImportsWorker(ambientModuleImportDecls, coalesceAndOrganizeImports); + var ambientModuleExportDecls = ambientModuleBody.statements.filter(ts.isExportDeclaration); + organizeImportsWorker(ambientModuleExportDecls, coalesceExports); + } + return changeTracker.getChanges(); + function organizeImportsWorker(oldImportDecls, coalesce) { + if (ts.length(oldImportDecls) === 0) { + return; + } + // Special case: normally, we'd expect leading and trailing trivia to follow each import + // around as it's sorted. However, we do not want this to happen for leading trivia + // on the first import because it is probably the header comment for the file. + // Consider: we could do a more careful check that this trivia is actually a header, + // but the consequences of being wrong are very minor. + ts.suppressLeadingTrivia(oldImportDecls[0]); + var oldImportGroups = ts.group(oldImportDecls, function (importDecl) { return getExternalModuleName(importDecl.moduleSpecifier); }); + var sortedImportGroups = ts.stableSort(oldImportGroups, function (group1, group2) { return compareModuleSpecifiers(group1[0].moduleSpecifier, group2[0].moduleSpecifier); }); + var newImportDecls = ts.flatMap(sortedImportGroups, function (importGroup) { + return getExternalModuleName(importGroup[0].moduleSpecifier) + ? coalesce(importGroup) + : importGroup; + }); + // Delete or replace the first import. + if (newImportDecls.length === 0) { + changeTracker.delete(sourceFile, oldImportDecls[0]); + } + else { + // Note: Delete the surrounding trivia because it will have been retained in newImportDecls. + changeTracker.replaceNodeWithNodes(sourceFile, oldImportDecls[0], newImportDecls, { + useNonAdjustedStartPosition: true, + useNonAdjustedEndPosition: false, + suffix: ts.getNewLineOrDefaultFromHost(host, formatContext.options), + }); + } + // Delete any subsequent imports. + for (var i = 1; i < oldImportDecls.length; i++) { + changeTracker.delete(sourceFile, oldImportDecls[i]); + } + } + } + OrganizeImports.organizeImports = organizeImports; + function getModuleBlock(moduleDecl) { + var body = moduleDecl.body; + return body && !ts.isIdentifier(body) ? (ts.isModuleBlock(body) ? body : getModuleBlock(body)) : undefined; + } + function removeUnusedImports(oldImports, sourceFile, program) { + var typeChecker = program.getTypeChecker(); + var jsxNamespace = typeChecker.getJsxNamespace(); + var jsxElementsPresent = !!(sourceFile.transformFlags & 4 /* ContainsJsx */); + var usedImports = []; + for (var _i = 0, oldImports_1 = oldImports; _i < oldImports_1.length; _i++) { + var importDecl = oldImports_1[_i]; + var importClause = importDecl.importClause; + if (!importClause) { + // Imports without import clauses are assumed to be included for their side effects and are not removed. + usedImports.push(importDecl); + continue; + } + var name = importClause.name, namedBindings = importClause.namedBindings; + // Default import + if (name && !isDeclarationUsed(name)) { + name = undefined; + } + if (namedBindings) { + if (ts.isNamespaceImport(namedBindings)) { + // Namespace import + if (!isDeclarationUsed(namedBindings.name)) { + namedBindings = undefined; + } + } + else { + // List of named imports + var newElements = namedBindings.elements.filter(function (e) { return isDeclarationUsed(e.name); }); + if (newElements.length < namedBindings.elements.length) { + namedBindings = newElements.length + ? ts.updateNamedImports(namedBindings, newElements) + : undefined; + } + } + } + if (name || namedBindings) { + usedImports.push(updateImportDeclarationAndClause(importDecl, name, namedBindings)); + } + } + return usedImports; + function isDeclarationUsed(identifier) { + // The JSX factory symbol is always used if JSX elements are present - even if they are not allowed. + return jsxElementsPresent && (identifier.text === jsxNamespace) || ts.FindAllReferences.Core.isSymbolReferencedInFile(identifier, typeChecker, sourceFile); + } + } + function getExternalModuleName(specifier) { + return specifier !== undefined && ts.isStringLiteralLike(specifier) + ? specifier.text + : undefined; + } + // Internal for testing + /** + * @param importGroup a list of ImportDeclarations, all with the same module name. + */ + function coalesceImports(importGroup) { + if (importGroup.length === 0) { + return importGroup; + } + var _a = getCategorizedImports(importGroup), importWithoutClause = _a.importWithoutClause, defaultImports = _a.defaultImports, namespaceImports = _a.namespaceImports, namedImports = _a.namedImports; + var coalescedImports = []; + if (importWithoutClause) { + coalescedImports.push(importWithoutClause); + } + // Normally, we don't combine default and namespace imports, but it would be silly to + // produce two import declarations in this special case. + if (defaultImports.length === 1 && namespaceImports.length === 1 && namedImports.length === 0) { + // Add the namespace import to the existing default ImportDeclaration. + var defaultImport = defaultImports[0]; + coalescedImports.push(updateImportDeclarationAndClause(defaultImport, defaultImport.importClause.name, namespaceImports[0].importClause.namedBindings)); // TODO: GH#18217 + return coalescedImports; + } + var sortedNamespaceImports = ts.stableSort(namespaceImports, function (i1, i2) { + return compareIdentifiers(i1.importClause.namedBindings.name, i2.importClause.namedBindings.name); + }); // TODO: GH#18217 + for (var _i = 0, sortedNamespaceImports_1 = sortedNamespaceImports; _i < sortedNamespaceImports_1.length; _i++) { + var namespaceImport = sortedNamespaceImports_1[_i]; + // Drop the name, if any + coalescedImports.push(updateImportDeclarationAndClause(namespaceImport, /*name*/ undefined, namespaceImport.importClause.namedBindings)); // TODO: GH#18217 + } + if (defaultImports.length === 0 && namedImports.length === 0) { + return coalescedImports; + } + var newDefaultImport; + var newImportSpecifiers = []; + if (defaultImports.length === 1) { + newDefaultImport = defaultImports[0].importClause.name; + } + else { + for (var _b = 0, defaultImports_1 = defaultImports; _b < defaultImports_1.length; _b++) { + var defaultImport = defaultImports_1[_b]; + newImportSpecifiers.push(ts.createImportSpecifier(ts.createIdentifier("default"), defaultImport.importClause.name)); // TODO: GH#18217 + } + } + newImportSpecifiers.push.apply(newImportSpecifiers, ts.flatMap(namedImports, function (i) { return i.importClause.namedBindings.elements; })); // TODO: GH#18217 + var sortedImportSpecifiers = sortSpecifiers(newImportSpecifiers); + var importDecl = defaultImports.length > 0 + ? defaultImports[0] + : namedImports[0]; + var newNamedImports = sortedImportSpecifiers.length === 0 + ? newDefaultImport + ? undefined + : ts.createNamedImports(ts.emptyArray) + : namedImports.length === 0 + ? ts.createNamedImports(sortedImportSpecifiers) + : ts.updateNamedImports(namedImports[0].importClause.namedBindings, sortedImportSpecifiers); // TODO: GH#18217 + coalescedImports.push(updateImportDeclarationAndClause(importDecl, newDefaultImport, newNamedImports)); + return coalescedImports; + /* + * Returns entire import declarations because they may already have been rewritten and + * may lack parent pointers. The desired parts can easily be recovered based on the + * categorization. + * + * NB: There may be overlap between `defaultImports` and `namespaceImports`/`namedImports`. + */ + function getCategorizedImports(importGroup) { + var importWithoutClause; + var defaultImports = []; + var namespaceImports = []; + var namedImports = []; + for (var _i = 0, importGroup_1 = importGroup; _i < importGroup_1.length; _i++) { + var importDeclaration = importGroup_1[_i]; + if (importDeclaration.importClause === undefined) { + // Only the first such import is interesting - the others are redundant. + // Note: Unfortunately, we will lose trivia that was on this node. + importWithoutClause = importWithoutClause || importDeclaration; + continue; + } + var _a = importDeclaration.importClause, name = _a.name, namedBindings = _a.namedBindings; + if (name) { + defaultImports.push(importDeclaration); + } + if (namedBindings) { + if (ts.isNamespaceImport(namedBindings)) { + namespaceImports.push(importDeclaration); + } + else { + namedImports.push(importDeclaration); + } + } + } + return { + importWithoutClause: importWithoutClause, + defaultImports: defaultImports, + namespaceImports: namespaceImports, + namedImports: namedImports, + }; + } + } + OrganizeImports.coalesceImports = coalesceImports; + // Internal for testing + /** + * @param exportGroup a list of ExportDeclarations, all with the same module name. + */ + function coalesceExports(exportGroup) { + if (exportGroup.length === 0) { + return exportGroup; + } + var _a = getCategorizedExports(exportGroup), exportWithoutClause = _a.exportWithoutClause, namedExports = _a.namedExports; + var coalescedExports = []; + if (exportWithoutClause) { + coalescedExports.push(exportWithoutClause); + } + if (namedExports.length === 0) { + return coalescedExports; + } + var newExportSpecifiers = []; + newExportSpecifiers.push.apply(newExportSpecifiers, ts.flatMap(namedExports, function (i) { return (i.exportClause).elements; })); + var sortedExportSpecifiers = sortSpecifiers(newExportSpecifiers); + var exportDecl = namedExports[0]; + coalescedExports.push(ts.updateExportDeclaration(exportDecl, exportDecl.decorators, exportDecl.modifiers, ts.updateNamedExports(exportDecl.exportClause, sortedExportSpecifiers), exportDecl.moduleSpecifier)); + return coalescedExports; + /* + * Returns entire export declarations because they may already have been rewritten and + * may lack parent pointers. The desired parts can easily be recovered based on the + * categorization. + */ + function getCategorizedExports(exportGroup) { + var exportWithoutClause; + var namedExports = []; + for (var _i = 0, exportGroup_1 = exportGroup; _i < exportGroup_1.length; _i++) { + var exportDeclaration = exportGroup_1[_i]; + if (exportDeclaration.exportClause === undefined) { + // Only the first such export is interesting - the others are redundant. + // Note: Unfortunately, we will lose trivia that was on this node. + exportWithoutClause = exportWithoutClause || exportDeclaration; + } + else { + namedExports.push(exportDeclaration); + } + } + return { + exportWithoutClause: exportWithoutClause, + namedExports: namedExports, + }; + } + } + OrganizeImports.coalesceExports = coalesceExports; + function updateImportDeclarationAndClause(importDeclaration, name, namedBindings) { + return ts.updateImportDeclaration(importDeclaration, importDeclaration.decorators, importDeclaration.modifiers, ts.updateImportClause(importDeclaration.importClause, name, namedBindings), // TODO: GH#18217 + importDeclaration.moduleSpecifier); + } + function sortSpecifiers(specifiers) { + return ts.stableSort(specifiers, function (s1, s2) { + return compareIdentifiers(s1.propertyName || s1.name, s2.propertyName || s2.name) || + compareIdentifiers(s1.name, s2.name); + }); + } + /* internal */ // Exported for testing + function compareModuleSpecifiers(m1, m2) { + var name1 = getExternalModuleName(m1); + var name2 = getExternalModuleName(m2); + return ts.compareBooleans(name1 === undefined, name2 === undefined) || + ts.compareBooleans(ts.isExternalModuleNameRelative(name1), ts.isExternalModuleNameRelative(name2)) || + ts.compareStringsCaseInsensitive(name1, name2); + } + OrganizeImports.compareModuleSpecifiers = compareModuleSpecifiers; + function compareIdentifiers(s1, s2) { + return ts.compareStringsCaseInsensitive(s1.text, s2.text); + } + })(OrganizeImports = ts.OrganizeImports || (ts.OrganizeImports = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var OutliningElementsCollector; + (function (OutliningElementsCollector) { + function collectElements(sourceFile, cancellationToken) { + var res = []; + addNodeOutliningSpans(sourceFile, cancellationToken, res); + addRegionOutliningSpans(sourceFile, res); + return res.sort(function (span1, span2) { return span1.textSpan.start - span2.textSpan.start; }); + } + OutliningElementsCollector.collectElements = collectElements; + function addNodeOutliningSpans(sourceFile, cancellationToken, out) { + var depthRemaining = 40; + var current = 0; + var statements = sourceFile.statements; + var n = statements.length; + while (current < n) { + while (current < n && !ts.isAnyImportSyntax(statements[current])) { + visitNonImportNode(statements[current]); + current++; + } + if (current === n) + break; + var firstImport = current; + while (current < n && ts.isAnyImportSyntax(statements[current])) { + addOutliningForLeadingCommentsForNode(statements[current], sourceFile, cancellationToken, out); + current++; + } + var lastImport = current - 1; + if (lastImport !== firstImport) { + out.push(createOutliningSpanFromBounds(ts.findChildOfKind(statements[firstImport], 92 /* ImportKeyword */, sourceFile).getStart(sourceFile), statements[lastImport].getEnd(), "imports" /* Imports */)); + } + } + function visitNonImportNode(n) { + if (depthRemaining === 0) + return; + cancellationToken.throwIfCancellationRequested(); + if (ts.isDeclaration(n)) { + addOutliningForLeadingCommentsForNode(n, sourceFile, cancellationToken, out); + } + var span = getOutliningSpanForNode(n, sourceFile); + if (span) + out.push(span); + depthRemaining--; + if (ts.isIfStatement(n) && n.elseStatement && ts.isIfStatement(n.elseStatement)) { + // Consider an 'else if' to be on the same depth as the 'if'. + visitNonImportNode(n.expression); + visitNonImportNode(n.thenStatement); + depthRemaining++; + visitNonImportNode(n.elseStatement); + depthRemaining--; + } + else { + n.forEachChild(visitNonImportNode); + } + depthRemaining++; + } + } + function addRegionOutliningSpans(sourceFile, out) { + var regions = []; + var lineStarts = sourceFile.getLineStarts(); + for (var i = 0; i < lineStarts.length; i++) { + var currentLineStart = lineStarts[i]; + var lineEnd = i + 1 === lineStarts.length ? sourceFile.getEnd() : lineStarts[i + 1] - 1; + var lineText = sourceFile.text.substring(currentLineStart, lineEnd); + var result = isRegionDelimiter(lineText); + if (!result || ts.isInComment(sourceFile, currentLineStart)) { + continue; + } + if (!result[1]) { + var span = ts.createTextSpanFromBounds(sourceFile.text.indexOf("//", currentLineStart), lineEnd); + regions.push(createOutliningSpan(span, "region" /* Region */, span, /*autoCollapse*/ false, result[2] || "#region")); + } + else { + var region = regions.pop(); + if (region) { + region.textSpan.length = lineEnd - region.textSpan.start; + region.hintSpan.length = lineEnd - region.textSpan.start; + out.push(region); + } + } + } + } + var regionDelimiterRegExp = /^\s*\/\/\s*#(end)?region(?:\s+(.*))?(?:\r)?$/; + function isRegionDelimiter(lineText) { + return regionDelimiterRegExp.exec(lineText); + } + function addOutliningForLeadingCommentsForNode(n, sourceFile, cancellationToken, out) { + var comments = ts.getLeadingCommentRangesOfNode(n, sourceFile); + if (!comments) + return; + var firstSingleLineCommentStart = -1; + var lastSingleLineCommentEnd = -1; + var singleLineCommentCount = 0; + var sourceText = sourceFile.getFullText(); + for (var _i = 0, comments_2 = comments; _i < comments_2.length; _i++) { + var _a = comments_2[_i], kind = _a.kind, pos = _a.pos, end = _a.end; + cancellationToken.throwIfCancellationRequested(); + switch (kind) { + case 2 /* SingleLineCommentTrivia */: + // never fold region delimiters into single-line comment regions + var commentText = sourceText.slice(pos, end); + if (isRegionDelimiter(commentText)) { + combineAndAddMultipleSingleLineComments(); + singleLineCommentCount = 0; + break; + } + // For single line comments, combine consecutive ones (2 or more) into + // a single span from the start of the first till the end of the last + if (singleLineCommentCount === 0) { + firstSingleLineCommentStart = pos; + } + lastSingleLineCommentEnd = end; + singleLineCommentCount++; + break; + case 3 /* MultiLineCommentTrivia */: + combineAndAddMultipleSingleLineComments(); + out.push(createOutliningSpanFromBounds(pos, end, "comment" /* Comment */)); + singleLineCommentCount = 0; + break; + default: + ts.Debug.assertNever(kind); + } + } + combineAndAddMultipleSingleLineComments(); + function combineAndAddMultipleSingleLineComments() { + // Only outline spans of two or more consecutive single line comments + if (singleLineCommentCount > 1) { + out.push(createOutliningSpanFromBounds(firstSingleLineCommentStart, lastSingleLineCommentEnd, "comment" /* Comment */)); + } + } + } + function createOutliningSpanFromBounds(pos, end, kind) { + return createOutliningSpan(ts.createTextSpanFromBounds(pos, end), kind); + } + function getOutliningSpanForNode(n, sourceFile) { + switch (n.kind) { + case 218 /* Block */: + if (ts.isFunctionBlock(n)) { + return spanForNode(n.parent, /*autoCollapse*/ n.parent.kind !== 197 /* ArrowFunction */); + } + // Check if the block is standalone, or 'attached' to some parent statement. + // If the latter, we want to collapse the block, but consider its hint span + // to be the entire span of the parent. + switch (n.parent.kind) { + case 223 /* DoStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + case 225 /* ForStatement */: + case 222 /* IfStatement */: + case 224 /* WhileStatement */: + case 231 /* WithStatement */: + case 274 /* CatchClause */: + return spanForNode(n.parent); + case 235 /* TryStatement */: + // Could be the try-block, or the finally-block. + var tryStatement = n.parent; + if (tryStatement.tryBlock === n) { + return spanForNode(n.parent); + } + else if (tryStatement.finallyBlock === n) { + return spanForNode(ts.findChildOfKind(tryStatement, 88 /* FinallyKeyword */, sourceFile)); + } + // falls through + default: + // Block was a standalone block. In this case we want to only collapse + // the span of the block, independent of any parent span. + return createOutliningSpan(ts.createTextSpanFromNode(n, sourceFile), "code" /* Code */); + } + case 245 /* ModuleBlock */: + return spanForNode(n.parent); + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + case 243 /* EnumDeclaration */: + case 246 /* CaseBlock */: + return spanForNode(n); + case 188 /* ObjectLiteralExpression */: + return spanForObjectOrArrayLiteral(n); + case 187 /* ArrayLiteralExpression */: + return spanForObjectOrArrayLiteral(n, 22 /* OpenBracketToken */); + case 260 /* JsxElement */: + return spanForJSXElement(n); + case 261 /* JsxSelfClosingElement */: + case 262 /* JsxOpeningElement */: + return spanForJSXAttributes(n.attributes); + } + function spanForJSXElement(node) { + var textSpan = ts.createTextSpanFromBounds(node.openingElement.getStart(sourceFile), node.closingElement.getEnd()); + var tagName = node.openingElement.tagName.getText(sourceFile); + var bannerText = "<" + tagName + ">..."; + return createOutliningSpan(textSpan, "code" /* Code */, textSpan, /*autoCollapse*/ false, bannerText); + } + function spanForJSXAttributes(node) { + if (node.properties.length === 0) { + return undefined; + } + return createOutliningSpanFromBounds(node.getStart(sourceFile), node.getEnd(), "code" /* Code */); + } + function spanForObjectOrArrayLiteral(node, open) { + if (open === void 0) { open = 18 /* OpenBraceToken */; } + // If the block has no leading keywords and is inside an array literal, + // we only want to collapse the span of the block. + // Otherwise, the collapsed section will include the end of the previous line. + return spanForNode(node, /*autoCollapse*/ false, /*useFullStart*/ !ts.isArrayLiteralExpression(node.parent), open); + } + function spanForNode(hintSpanNode, autoCollapse, useFullStart, open) { + if (autoCollapse === void 0) { autoCollapse = false; } + if (useFullStart === void 0) { useFullStart = true; } + if (open === void 0) { open = 18 /* OpenBraceToken */; } + var openToken = ts.findChildOfKind(n, open, sourceFile); + var close = open === 18 /* OpenBraceToken */ ? 19 /* CloseBraceToken */ : 23 /* CloseBracketToken */; + var closeToken = ts.findChildOfKind(n, close, sourceFile); + if (!openToken || !closeToken) { + return undefined; + } + var textSpan = ts.createTextSpanFromBounds(useFullStart ? openToken.getFullStart() : openToken.getStart(sourceFile), closeToken.getEnd()); + return createOutliningSpan(textSpan, "code" /* Code */, ts.createTextSpanFromNode(hintSpanNode, sourceFile), autoCollapse); + } + } + function createOutliningSpan(textSpan, kind, hintSpan, autoCollapse, bannerText) { + if (hintSpan === void 0) { hintSpan = textSpan; } + if (autoCollapse === void 0) { autoCollapse = false; } + if (bannerText === void 0) { bannerText = "..."; } + return { textSpan: textSpan, kind: kind, hintSpan: hintSpan, bannerText: bannerText, autoCollapse: autoCollapse }; + } + })(OutliningElementsCollector = ts.OutliningElementsCollector || (ts.OutliningElementsCollector = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + // Note(cyrusn): this enum is ordered from strongest match type to weakest match type. + var PatternMatchKind; + (function (PatternMatchKind) { + PatternMatchKind[PatternMatchKind["exact"] = 0] = "exact"; + PatternMatchKind[PatternMatchKind["prefix"] = 1] = "prefix"; + PatternMatchKind[PatternMatchKind["substring"] = 2] = "substring"; + PatternMatchKind[PatternMatchKind["camelCase"] = 3] = "camelCase"; + })(PatternMatchKind = ts.PatternMatchKind || (ts.PatternMatchKind = {})); + function createPatternMatch(kind, isCaseSensitive) { + return { + kind: kind, + isCaseSensitive: isCaseSensitive + }; + } + function createPatternMatcher(pattern) { + // We'll often see the same candidate string many times when searching (For example, when + // we see the name of a module that is used everywhere, or the name of an overload). As + // such, we cache the information we compute about the candidate for the life of this + // pattern matcher so we don't have to compute it multiple times. + var stringToWordSpans = ts.createMap(); + var dotSeparatedSegments = pattern.trim().split(".").map(function (p) { return createSegment(p.trim()); }); + // A segment is considered invalid if we couldn't find any words in it. + if (dotSeparatedSegments.some(function (segment) { return !segment.subWordTextChunks.length; })) + return undefined; + return { + getFullMatch: function (containers, candidate) { return getFullMatch(containers, candidate, dotSeparatedSegments, stringToWordSpans); }, + getMatchForLastSegmentOfPattern: function (candidate) { return matchSegment(candidate, ts.last(dotSeparatedSegments), stringToWordSpans); }, + patternContainsDots: dotSeparatedSegments.length > 1 + }; + } + ts.createPatternMatcher = createPatternMatcher; + function getFullMatch(candidateContainers, candidate, dotSeparatedSegments, stringToWordSpans) { + // First, check that the last part of the dot separated pattern matches the name of the + // candidate. If not, then there's no point in proceeding and doing the more + // expensive work. + var candidateMatch = matchSegment(candidate, ts.last(dotSeparatedSegments), stringToWordSpans); + if (!candidateMatch) { + return undefined; + } + // -1 because the last part was checked against the name, and only the rest + // of the parts are checked against the container. + if (dotSeparatedSegments.length - 1 > candidateContainers.length) { + // There weren't enough container parts to match against the pattern parts. + // So this definitely doesn't match. + return undefined; + } + var bestMatch; + for (var i = dotSeparatedSegments.length - 2, j = candidateContainers.length - 1; i >= 0; i -= 1, j -= 1) { + bestMatch = betterMatch(bestMatch, matchSegment(candidateContainers[j], dotSeparatedSegments[i], stringToWordSpans)); + } + return bestMatch; + } + function getWordSpans(word, stringToWordSpans) { + var spans = stringToWordSpans.get(word); + if (!spans) { + stringToWordSpans.set(word, spans = breakIntoWordSpans(word)); + } + return spans; + } + function matchTextChunk(candidate, chunk, stringToWordSpans) { + var index = indexOfIgnoringCase(candidate, chunk.textLowerCase); + if (index === 0) { + // a) Check if the word is a prefix of the candidate, in a case insensitive or + // sensitive manner. If it does, return that there was an exact match if the word and candidate are the same length, else a prefix match. + return createPatternMatch(chunk.text.length === candidate.length ? PatternMatchKind.exact : PatternMatchKind.prefix, /*isCaseSensitive:*/ ts.startsWith(candidate, chunk.text)); + } + if (chunk.isLowerCase) { + if (index === -1) + return undefined; + // b) If the part is entirely lowercase, then check if it is contained anywhere in the + // candidate in a case insensitive manner. If so, return that there was a substring + // match. + // + // Note: We only have a substring match if the lowercase part is prefix match of some + // word part. That way we don't match something like 'Class' when the user types 'a'. + // But we would match 'FooAttribute' (since 'Attribute' starts with 'a'). + var wordSpans = getWordSpans(candidate, stringToWordSpans); + for (var _i = 0, wordSpans_1 = wordSpans; _i < wordSpans_1.length; _i++) { + var span = wordSpans_1[_i]; + if (partStartsWith(candidate, span, chunk.text, /*ignoreCase:*/ true)) { + return createPatternMatch(PatternMatchKind.substring, /*isCaseSensitive:*/ partStartsWith(candidate, span, chunk.text, /*ignoreCase:*/ false)); + } + } + // c) Is the pattern a substring of the candidate starting on one of the candidate's word boundaries? + // We could check every character boundary start of the candidate for the pattern. However, that's + // an m * n operation in the wost case. Instead, find the first instance of the pattern + // substring, and see if it starts on a capital letter. It seems unlikely that the user will try to + // filter the list based on a substring that starts on a capital letter and also with a lowercase one. + // (Pattern: fogbar, Candidate: quuxfogbarFogBar). + if (chunk.text.length < candidate.length && isUpperCaseLetter(candidate.charCodeAt(index))) { + return createPatternMatch(PatternMatchKind.substring, /*isCaseSensitive:*/ false); + } + } + else { + // d) If the part was not entirely lowercase, then check if it is contained in the + // candidate in a case *sensitive* manner. If so, return that there was a substring + // match. + if (candidate.indexOf(chunk.text) > 0) { + return createPatternMatch(PatternMatchKind.substring, /*isCaseSensitive:*/ true); + } + // e) If the part was not entirely lowercase, then attempt a camel cased match as well. + if (chunk.characterSpans.length > 0) { + var candidateParts = getWordSpans(candidate, stringToWordSpans); + var isCaseSensitive = tryCamelCaseMatch(candidate, candidateParts, chunk, /*ignoreCase:*/ false) ? true + : tryCamelCaseMatch(candidate, candidateParts, chunk, /*ignoreCase:*/ true) ? false : undefined; + if (isCaseSensitive !== undefined) { + return createPatternMatch(PatternMatchKind.camelCase, isCaseSensitive); + } + } + } + } + function matchSegment(candidate, segment, stringToWordSpans) { + // First check if the segment matches as is. This is also useful if the segment contains + // characters we would normally strip when splitting into parts that we also may want to + // match in the candidate. For example if the segment is "@int" and the candidate is + // "@int", then that will show up as an exact match here. + // + // Note: if the segment contains a space or an asterisk then we must assume that it's a + // multi-word segment. + if (every(segment.totalTextChunk.text, function (ch) { return ch !== 32 /* space */ && ch !== 42 /* asterisk */; })) { + var match = matchTextChunk(candidate, segment.totalTextChunk, stringToWordSpans); + if (match) + return match; + } + // The logic for pattern matching is now as follows: + // + // 1) Break the segment passed in into words. Breaking is rather simple and a + // good way to think about it that if gives you all the individual alphanumeric words + // of the pattern. + // + // 2) For each word try to match the word against the candidate value. + // + // 3) Matching is as follows: + // + // a) Check if the word is a prefix of the candidate, in a case insensitive or + // sensitive manner. If it does, return that there was an exact match if the word and candidate are the same length, else a prefix match. + // + // If the word is entirely lowercase: + // b) Then check if it is contained anywhere in the + // candidate in a case insensitive manner. If so, return that there was a substring + // match. + // + // Note: We only have a substring match if the lowercase part is prefix match of + // some word part. That way we don't match something like 'Class' when the user + // types 'a'. But we would match 'FooAttribute' (since 'Attribute' starts with + // 'a'). + // + // c) The word is all lower case. Is it a case insensitive substring of the candidate starting + // on a part boundary of the candidate? + // + // Else: + // d) If the word was not entirely lowercase, then check if it is contained in the + // candidate in a case *sensitive* manner. If so, return that there was a substring + // match. + // + // e) If the word was not entirely lowercase, then attempt a camel cased match as + // well. + // + // Only if all words have some sort of match is the pattern considered matched. + var subWordTextChunks = segment.subWordTextChunks; + var bestMatch; + for (var _i = 0, subWordTextChunks_1 = subWordTextChunks; _i < subWordTextChunks_1.length; _i++) { + var subWordTextChunk = subWordTextChunks_1[_i]; + bestMatch = betterMatch(bestMatch, matchTextChunk(candidate, subWordTextChunk, stringToWordSpans)); + } + return bestMatch; + } + function betterMatch(a, b) { + return ts.min(a, b, compareMatches); + } + function compareMatches(a, b) { + return a === undefined ? 1 /* GreaterThan */ : b === undefined ? -1 /* LessThan */ + : ts.compareValues(a.kind, b.kind) || ts.compareBooleans(!a.isCaseSensitive, !b.isCaseSensitive); + } + function partStartsWith(candidate, candidateSpan, pattern, ignoreCase, patternSpan) { + if (patternSpan === void 0) { patternSpan = { start: 0, length: pattern.length }; } + return patternSpan.length <= candidateSpan.length // If pattern part is longer than the candidate part there can never be a match. + && everyInRange(0, patternSpan.length, function (i) { return equalChars(pattern.charCodeAt(patternSpan.start + i), candidate.charCodeAt(candidateSpan.start + i), ignoreCase); }); + } + function equalChars(ch1, ch2, ignoreCase) { + return ignoreCase ? toLowerCase(ch1) === toLowerCase(ch2) : ch1 === ch2; + } + function tryCamelCaseMatch(candidate, candidateParts, chunk, ignoreCase) { + var chunkCharacterSpans = chunk.characterSpans; + // Note: we may have more pattern parts than candidate parts. This is because multiple + // pattern parts may match a candidate part. For example "SiUI" against "SimpleUI". + // We'll have 3 pattern parts Si/U/I against two candidate parts Simple/UI. However, U + // and I will both match in UI. + var currentCandidate = 0; + var currentChunkSpan = 0; + var firstMatch; + var contiguous; + while (true) { + // Let's consider our termination cases + if (currentChunkSpan === chunkCharacterSpans.length) { + return true; + } + else if (currentCandidate === candidateParts.length) { + // No match, since we still have more of the pattern to hit + return false; + } + var candidatePart = candidateParts[currentCandidate]; + var gotOneMatchThisCandidate = false; + // Consider the case of matching SiUI against SimpleUIElement. The candidate parts + // will be Simple/UI/Element, and the pattern parts will be Si/U/I. We'll match 'Si' + // against 'Simple' first. Then we'll match 'U' against 'UI'. However, we want to + // still keep matching pattern parts against that candidate part. + for (; currentChunkSpan < chunkCharacterSpans.length; currentChunkSpan++) { + var chunkCharacterSpan = chunkCharacterSpans[currentChunkSpan]; + if (gotOneMatchThisCandidate) { + // We've already gotten one pattern part match in this candidate. We will + // only continue trying to consumer pattern parts if the last part and this + // part are both upper case. + if (!isUpperCaseLetter(chunk.text.charCodeAt(chunkCharacterSpans[currentChunkSpan - 1].start)) || + !isUpperCaseLetter(chunk.text.charCodeAt(chunkCharacterSpans[currentChunkSpan].start))) { + break; + } + } + if (!partStartsWith(candidate, candidatePart, chunk.text, ignoreCase, chunkCharacterSpan)) { + break; + } + gotOneMatchThisCandidate = true; + firstMatch = firstMatch === undefined ? currentCandidate : firstMatch; + // If we were contiguous, then keep that value. If we weren't, then keep that + // value. If we don't know, then set the value to 'true' as an initial match is + // obviously contiguous. + contiguous = contiguous === undefined ? true : contiguous; + candidatePart = ts.createTextSpan(candidatePart.start + chunkCharacterSpan.length, candidatePart.length - chunkCharacterSpan.length); + } + // Check if we matched anything at all. If we didn't, then we need to unset the + // contiguous bit if we currently had it set. + // If we haven't set the bit yet, then that means we haven't matched anything so + // far, and we don't want to change that. + if (!gotOneMatchThisCandidate && contiguous !== undefined) { + contiguous = false; + } + // Move onto the next candidate. + currentCandidate++; + } + } + function createSegment(text) { + return { + totalTextChunk: createTextChunk(text), + subWordTextChunks: breakPatternIntoTextChunks(text) + }; + } + function isUpperCaseLetter(ch) { + // Fast check for the ascii range. + if (ch >= 65 /* A */ && ch <= 90 /* Z */) { + return true; + } + if (ch < 127 /* maxAsciiCharacter */ || !ts.isUnicodeIdentifierStart(ch, 6 /* Latest */)) { + return false; + } + // TODO: find a way to determine this for any unicode characters in a + // non-allocating manner. + var str = String.fromCharCode(ch); + return str === str.toUpperCase(); + } + function isLowerCaseLetter(ch) { + // Fast check for the ascii range. + if (ch >= 97 /* a */ && ch <= 122 /* z */) { + return true; + } + if (ch < 127 /* maxAsciiCharacter */ || !ts.isUnicodeIdentifierStart(ch, 6 /* Latest */)) { + return false; + } + // TODO: find a way to determine this for any unicode characters in a + // non-allocating manner. + var str = String.fromCharCode(ch); + return str === str.toLowerCase(); + } + // Assumes 'value' is already lowercase. + function indexOfIgnoringCase(str, value) { + var n = str.length - value.length; + var _loop_14 = function (start) { + if (every(value, function (valueChar, i) { return toLowerCase(str.charCodeAt(i + start)) === valueChar; })) { + return { value: start }; + } + }; + for (var start = 0; start <= n; start++) { + var state_3 = _loop_14(start); + if (typeof state_3 === "object") + return state_3.value; + } + return -1; + } + function toLowerCase(ch) { + // Fast convert for the ascii range. + if (ch >= 65 /* A */ && ch <= 90 /* Z */) { + return 97 /* a */ + (ch - 65 /* A */); + } + if (ch < 127 /* maxAsciiCharacter */) { + return ch; + } + // TODO: find a way to compute this for any unicode characters in a + // non-allocating manner. + return String.fromCharCode(ch).toLowerCase().charCodeAt(0); + } + function isDigit(ch) { + // TODO(cyrusn): Find a way to support this for unicode digits. + return ch >= 48 /* _0 */ && ch <= 57 /* _9 */; + } + function isWordChar(ch) { + return isUpperCaseLetter(ch) || isLowerCaseLetter(ch) || isDigit(ch) || ch === 95 /* _ */ || ch === 36 /* $ */; + } + function breakPatternIntoTextChunks(pattern) { + var result = []; + var wordStart = 0; + var wordLength = 0; + for (var i = 0; i < pattern.length; i++) { + var ch = pattern.charCodeAt(i); + if (isWordChar(ch)) { + if (wordLength === 0) { + wordStart = i; + } + wordLength++; + } + else { + if (wordLength > 0) { + result.push(createTextChunk(pattern.substr(wordStart, wordLength))); + wordLength = 0; + } + } + } + if (wordLength > 0) { + result.push(createTextChunk(pattern.substr(wordStart, wordLength))); + } + return result; + } + function createTextChunk(text) { + var textLowerCase = text.toLowerCase(); + return { + text: text, + textLowerCase: textLowerCase, + isLowerCase: text === textLowerCase, + characterSpans: breakIntoCharacterSpans(text) + }; + } + function breakIntoCharacterSpans(identifier) { + return breakIntoSpans(identifier, /*word:*/ false); + } + ts.breakIntoCharacterSpans = breakIntoCharacterSpans; + function breakIntoWordSpans(identifier) { + return breakIntoSpans(identifier, /*word:*/ true); + } + ts.breakIntoWordSpans = breakIntoWordSpans; + function breakIntoSpans(identifier, word) { + var result = []; + var wordStart = 0; + for (var i = 1; i < identifier.length; i++) { + var lastIsDigit = isDigit(identifier.charCodeAt(i - 1)); + var currentIsDigit = isDigit(identifier.charCodeAt(i)); + var hasTransitionFromLowerToUpper = transitionFromLowerToUpper(identifier, word, i); + var hasTransitionFromUpperToLower = word && transitionFromUpperToLower(identifier, i, wordStart); + if (charIsPunctuation(identifier.charCodeAt(i - 1)) || + charIsPunctuation(identifier.charCodeAt(i)) || + lastIsDigit !== currentIsDigit || + hasTransitionFromLowerToUpper || + hasTransitionFromUpperToLower) { + if (!isAllPunctuation(identifier, wordStart, i)) { + result.push(ts.createTextSpan(wordStart, i - wordStart)); + } + wordStart = i; + } + } + if (!isAllPunctuation(identifier, wordStart, identifier.length)) { + result.push(ts.createTextSpan(wordStart, identifier.length - wordStart)); + } + return result; + } + function charIsPunctuation(ch) { + switch (ch) { + case 33 /* exclamation */: + case 34 /* doubleQuote */: + case 35 /* hash */: + case 37 /* percent */: + case 38 /* ampersand */: + case 39 /* singleQuote */: + case 40 /* openParen */: + case 41 /* closeParen */: + case 42 /* asterisk */: + case 44 /* comma */: + case 45 /* minus */: + case 46 /* dot */: + case 47 /* slash */: + case 58 /* colon */: + case 59 /* semicolon */: + case 63 /* question */: + case 64 /* at */: + case 91 /* openBracket */: + case 92 /* backslash */: + case 93 /* closeBracket */: + case 95 /* _ */: + case 123 /* openBrace */: + case 125 /* closeBrace */: + return true; + } + return false; + } + function isAllPunctuation(identifier, start, end) { + return every(identifier, function (ch) { return charIsPunctuation(ch) && ch !== 95 /* _ */; }, start, end); + } + function transitionFromUpperToLower(identifier, index, wordStart) { + // Cases this supports: + // 1) IDisposable -> I, Disposable + // 2) UIElement -> UI, Element + // 3) HTMLDocument -> HTML, Document + // + // etc. + // We have a transition from an upper to a lower letter here. But we only + // want to break if all the letters that preceded are uppercase. i.e. if we + // have "Foo" we don't want to break that into "F, oo". But if we have + // "IFoo" or "UIFoo", then we want to break that into "I, Foo" and "UI, + // Foo". i.e. the last uppercase letter belongs to the lowercase letters + // that follows. Note: this will make the following not split properly: + // "HELLOthere". However, these sorts of names do not show up in .Net + // programs. + return index !== wordStart + && index + 1 < identifier.length + && isUpperCaseLetter(identifier.charCodeAt(index)) + && isLowerCaseLetter(identifier.charCodeAt(index + 1)) + && every(identifier, isUpperCaseLetter, wordStart, index); + } + function transitionFromLowerToUpper(identifier, word, index) { + var lastIsUpper = isUpperCaseLetter(identifier.charCodeAt(index - 1)); + var currentIsUpper = isUpperCaseLetter(identifier.charCodeAt(index)); + // See if the casing indicates we're starting a new word. Note: if we're breaking on + // words, then just seeing an upper case character isn't enough. Instead, it has to + // be uppercase and the previous character can't be uppercase. + // + // For example, breaking "AddMetadata" on words would make: Add Metadata + // + // on characters would be: A dd M etadata + // + // Break "AM" on words would be: AM + // + // on characters would be: A M + // + // We break the search string on characters. But we break the symbol name on words. + return currentIsUpper && (!word || !lastIsUpper); + } + function everyInRange(start, end, pred) { + for (var i = start; i < end; i++) { + if (!pred(i)) { + return false; + } + } + return true; + } + function every(s, pred, start, end) { + if (start === void 0) { start = 0; } + if (end === void 0) { end = s.length; } + return everyInRange(start, end, function (i) { return pred(s.charCodeAt(i), i); }); + } +})(ts || (ts = {})); +var ts; +(function (ts) { + function preProcessFile(sourceText, readImportFiles, detectJavaScriptImports) { + if (readImportFiles === void 0) { readImportFiles = true; } + if (detectJavaScriptImports === void 0) { detectJavaScriptImports = false; } + var pragmaContext = { + languageVersion: 1 /* ES5 */, + pragmas: undefined, + checkJsDirective: undefined, + referencedFiles: [], + typeReferenceDirectives: [], + libReferenceDirectives: [], + amdDependencies: [], + hasNoDefaultLib: undefined, + moduleName: undefined + }; + var importedFiles = []; + var ambientExternalModules; + var lastToken; + var currentToken; + var braceNesting = 0; + // assume that text represent an external module if it contains at least one top level import/export + // ambient modules that are found inside external modules are interpreted as module augmentations + var externalModule = false; + function nextToken() { + lastToken = currentToken; + currentToken = ts.scanner.scan(); + if (currentToken === 18 /* OpenBraceToken */) { + braceNesting++; + } + else if (currentToken === 19 /* CloseBraceToken */) { + braceNesting--; + } + return currentToken; + } + function getFileReference() { + var fileName = ts.scanner.getTokenValue(); + var pos = ts.scanner.getTokenPos(); + return { fileName: fileName, pos: pos, end: pos + fileName.length }; + } + function recordAmbientExternalModule() { + if (!ambientExternalModules) { + ambientExternalModules = []; + } + ambientExternalModules.push({ ref: getFileReference(), depth: braceNesting }); + } + function recordModuleName() { + importedFiles.push(getFileReference()); + markAsExternalModuleIfTopLevel(); + } + function markAsExternalModuleIfTopLevel() { + if (braceNesting === 0) { + externalModule = true; + } + } + /** + * Returns true if at least one token was consumed from the stream + */ + function tryConsumeDeclare() { + var token = ts.scanner.getToken(); + if (token === 125 /* DeclareKeyword */) { + // declare module "mod" + token = nextToken(); + if (token === 130 /* ModuleKeyword */) { + token = nextToken(); + if (token === 10 /* StringLiteral */) { + recordAmbientExternalModule(); + } + } + return true; + } + return false; + } + /** + * Returns true if at least one token was consumed from the stream + */ + function tryConsumeImport() { + if (lastToken === 24 /* DotToken */) { + return false; + } + var token = ts.scanner.getToken(); + if (token === 92 /* ImportKeyword */) { + token = nextToken(); + if (token === 20 /* OpenParenToken */) { + token = nextToken(); + if (token === 10 /* StringLiteral */) { + // import("mod"); + recordModuleName(); + return true; + } + } + else if (token === 10 /* StringLiteral */) { + // import "mod"; + recordModuleName(); + return true; + } + else { + if (token === 72 /* Identifier */ || ts.isKeyword(token)) { + token = nextToken(); + if (token === 144 /* FromKeyword */) { + token = nextToken(); + if (token === 10 /* StringLiteral */) { + // import d from "mod"; + recordModuleName(); + return true; + } + } + else if (token === 59 /* EqualsToken */) { + if (tryConsumeRequireCall(/*skipCurrentToken*/ true)) { + return true; + } + } + else if (token === 27 /* CommaToken */) { + // consume comma and keep going + token = nextToken(); + } + else { + // unknown syntax + return true; + } + } + if (token === 18 /* OpenBraceToken */) { + token = nextToken(); + // consume "{ a as B, c, d as D}" clauses + // make sure that it stops on EOF + while (token !== 19 /* CloseBraceToken */ && token !== 1 /* EndOfFileToken */) { + token = nextToken(); + } + if (token === 19 /* CloseBraceToken */) { + token = nextToken(); + if (token === 144 /* FromKeyword */) { + token = nextToken(); + if (token === 10 /* StringLiteral */) { + // import {a as A} from "mod"; + // import d, {a, b as B} from "mod" + recordModuleName(); + } + } + } + } + else if (token === 40 /* AsteriskToken */) { + token = nextToken(); + if (token === 119 /* AsKeyword */) { + token = nextToken(); + if (token === 72 /* Identifier */ || ts.isKeyword(token)) { + token = nextToken(); + if (token === 144 /* FromKeyword */) { + token = nextToken(); + if (token === 10 /* StringLiteral */) { + // import * as NS from "mod" + // import d, * as NS from "mod" + recordModuleName(); + } + } + } + } + } + } + return true; + } + return false; + } + function tryConsumeExport() { + var token = ts.scanner.getToken(); + if (token === 85 /* ExportKeyword */) { + markAsExternalModuleIfTopLevel(); + token = nextToken(); + if (token === 18 /* OpenBraceToken */) { + token = nextToken(); + // consume "{ a as B, c, d as D}" clauses + // make sure it stops on EOF + while (token !== 19 /* CloseBraceToken */ && token !== 1 /* EndOfFileToken */) { + token = nextToken(); + } + if (token === 19 /* CloseBraceToken */) { + token = nextToken(); + if (token === 144 /* FromKeyword */) { + token = nextToken(); + if (token === 10 /* StringLiteral */) { + // export {a as A} from "mod"; + // export {a, b as B} from "mod" + recordModuleName(); + } + } + } + } + else if (token === 40 /* AsteriskToken */) { + token = nextToken(); + if (token === 144 /* FromKeyword */) { + token = nextToken(); + if (token === 10 /* StringLiteral */) { + // export * from "mod" + recordModuleName(); + } + } + } + else if (token === 92 /* ImportKeyword */) { + token = nextToken(); + if (token === 72 /* Identifier */ || ts.isKeyword(token)) { + token = nextToken(); + if (token === 59 /* EqualsToken */) { + if (tryConsumeRequireCall(/*skipCurrentToken*/ true)) { + return true; + } + } + } + } + return true; + } + return false; + } + function tryConsumeRequireCall(skipCurrentToken) { + var token = skipCurrentToken ? nextToken() : ts.scanner.getToken(); + if (token === 134 /* RequireKeyword */) { + token = nextToken(); + if (token === 20 /* OpenParenToken */) { + token = nextToken(); + if (token === 10 /* StringLiteral */) { + // require("mod"); + recordModuleName(); + } + } + return true; + } + return false; + } + function tryConsumeDefine() { + var token = ts.scanner.getToken(); + if (token === 72 /* Identifier */ && ts.scanner.getTokenValue() === "define") { + token = nextToken(); + if (token !== 20 /* OpenParenToken */) { + return true; + } + token = nextToken(); + if (token === 10 /* StringLiteral */) { + // looks like define ("modname", ... - skip string literal and comma + token = nextToken(); + if (token === 27 /* CommaToken */) { + token = nextToken(); + } + else { + // unexpected token + return true; + } + } + // should be start of dependency list + if (token !== 22 /* OpenBracketToken */) { + return true; + } + // skip open bracket + token = nextToken(); + // scan until ']' or EOF + while (token !== 23 /* CloseBracketToken */ && token !== 1 /* EndOfFileToken */) { + // record string literals as module names + if (token === 10 /* StringLiteral */) { + recordModuleName(); + } + token = nextToken(); + } + return true; + } + return false; + } + function processImports() { + ts.scanner.setText(sourceText); + nextToken(); + // Look for: + // import "mod"; + // import d from "mod" + // import {a as A } from "mod"; + // import * as NS from "mod" + // import d, {a, b as B} from "mod" + // import i = require("mod"); + // import("mod"); + // export * from "mod" + // export {a as b} from "mod" + // export import i = require("mod") + // (for JavaScript files) require("mod") + // Do not look for: + // AnySymbol.import("mod") + // AnySymbol.nested.import("mod") + while (true) { + if (ts.scanner.getToken() === 1 /* EndOfFileToken */) { + break; + } + // check if at least one of alternative have moved scanner forward + if (tryConsumeDeclare() || + tryConsumeImport() || + tryConsumeExport() || + (detectJavaScriptImports && (tryConsumeRequireCall(/*skipCurrentToken*/ false) || tryConsumeDefine()))) { + continue; + } + else { + nextToken(); + } + } + ts.scanner.setText(undefined); + } + if (readImportFiles) { + processImports(); + } + ts.processCommentPragmas(pragmaContext, sourceText); + ts.processPragmasIntoFields(pragmaContext, ts.noop); + if (externalModule) { + // for external modules module all nested ambient modules are augmentations + if (ambientExternalModules) { + // move all detected ambient modules to imported files since they need to be resolved + for (var _i = 0, ambientExternalModules_1 = ambientExternalModules; _i < ambientExternalModules_1.length; _i++) { + var decl = ambientExternalModules_1[_i]; + importedFiles.push(decl.ref); + } + } + return { referencedFiles: pragmaContext.referencedFiles, typeReferenceDirectives: pragmaContext.typeReferenceDirectives, libReferenceDirectives: pragmaContext.libReferenceDirectives, importedFiles: importedFiles, isLibFile: !!pragmaContext.hasNoDefaultLib, ambientExternalModules: undefined }; + } + else { + // for global scripts ambient modules still can have augmentations - look for ambient modules with depth > 0 + var ambientModuleNames = void 0; + if (ambientExternalModules) { + for (var _a = 0, ambientExternalModules_2 = ambientExternalModules; _a < ambientExternalModules_2.length; _a++) { + var decl = ambientExternalModules_2[_a]; + if (decl.depth === 0) { + if (!ambientModuleNames) { + ambientModuleNames = []; + } + ambientModuleNames.push(decl.ref.fileName); + } + else { + importedFiles.push(decl.ref); + } + } + } + return { referencedFiles: pragmaContext.referencedFiles, typeReferenceDirectives: pragmaContext.typeReferenceDirectives, libReferenceDirectives: pragmaContext.libReferenceDirectives, importedFiles: importedFiles, isLibFile: !!pragmaContext.hasNoDefaultLib, ambientExternalModules: ambientModuleNames }; + } + } + ts.preProcessFile = preProcessFile; +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var Rename; + (function (Rename) { + function getRenameInfo(program, sourceFile, position) { + var node = ts.getTouchingPropertyName(sourceFile, position); + var renameInfo = node && nodeIsEligibleForRename(node) + ? getRenameInfoForNode(node, program.getTypeChecker(), sourceFile, function (declaration) { return program.isSourceFileDefaultLibrary(declaration.getSourceFile()); }) + : undefined; + return renameInfo || getRenameInfoError(ts.Diagnostics.You_cannot_rename_this_element); + } + Rename.getRenameInfo = getRenameInfo; + function getRenameInfoForNode(node, typeChecker, sourceFile, isDefinedInLibraryFile) { + var symbol = typeChecker.getSymbolAtLocation(node); + if (!symbol) + return; + // Only allow a symbol to be renamed if it actually has at least one declaration. + var declarations = symbol.declarations; + if (!declarations || declarations.length === 0) + return; + // Disallow rename for elements that are defined in the standard TypeScript library. + if (declarations.some(isDefinedInLibraryFile)) { + return getRenameInfoError(ts.Diagnostics.You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library); + } + // Cannot rename `default` as in `import { default as foo } from "./someModule"; + if (ts.isIdentifier(node) && node.originalKeywordKind === 80 /* DefaultKeyword */ && symbol.parent.flags & 1536 /* Module */) { + return undefined; + } + if (ts.isStringLiteralLike(node) && ts.tryGetImportFromModuleSpecifier(node)) { + return getRenameInfoForModule(node, sourceFile, symbol); + } + var kind = ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, node); + var specifierName = (ts.isImportOrExportSpecifierName(node) || ts.isStringOrNumericLiteralLike(node) && node.parent.kind === 149 /* ComputedPropertyName */) + ? ts.stripQuotes(ts.getTextOfIdentifierOrLiteral(node)) + : undefined; + var displayName = specifierName || typeChecker.symbolToString(symbol); + var fullDisplayName = specifierName || typeChecker.getFullyQualifiedName(symbol); + return getRenameInfoSuccess(displayName, fullDisplayName, kind, ts.SymbolDisplay.getSymbolModifiers(symbol), node, sourceFile); + } + function getRenameInfoForModule(node, sourceFile, moduleSymbol) { + if (!ts.isExternalModuleNameRelative(node.text)) { + return getRenameInfoError(ts.Diagnostics.You_cannot_rename_a_module_via_a_global_import); + } + var moduleSourceFile = ts.find(moduleSymbol.declarations, ts.isSourceFile); + if (!moduleSourceFile) + return undefined; + var withoutIndex = node.text.endsWith("/index") || node.text.endsWith("/index.js") ? undefined : ts.tryRemoveSuffix(ts.removeFileExtension(moduleSourceFile.fileName), "/index"); + var name = withoutIndex === undefined ? moduleSourceFile.fileName : withoutIndex; + var kind = withoutIndex === undefined ? "module" /* moduleElement */ : "directory" /* directory */; + var indexAfterLastSlash = node.text.lastIndexOf("/") + 1; + // Span should only be the last component of the path. + 1 to account for the quote character. + var triggerSpan = ts.createTextSpan(node.getStart(sourceFile) + 1 + indexAfterLastSlash, node.text.length - indexAfterLastSlash); + return { + canRename: true, + fileToRename: name, + kind: kind, + displayName: name, + fullDisplayName: name, + kindModifiers: "" /* none */, + triggerSpan: triggerSpan, + }; + } + function getRenameInfoSuccess(displayName, fullDisplayName, kind, kindModifiers, node, sourceFile) { + return { + canRename: true, + fileToRename: undefined, + kind: kind, + displayName: displayName, + fullDisplayName: fullDisplayName, + kindModifiers: kindModifiers, + triggerSpan: createTriggerSpanForNode(node, sourceFile) + }; + } + function getRenameInfoError(diagnostic) { + return { canRename: false, localizedErrorMessage: ts.getLocaleSpecificMessage(diagnostic) }; + } + function createTriggerSpanForNode(node, sourceFile) { + var start = node.getStart(sourceFile); + var width = node.getWidth(sourceFile); + if (node.kind === 10 /* StringLiteral */) { + // Exclude the quotes + start += 1; + width -= 2; + } + return ts.createTextSpan(start, width); + } + function nodeIsEligibleForRename(node) { + switch (node.kind) { + case 72 /* Identifier */: + case 10 /* StringLiteral */: + case 100 /* ThisKeyword */: + return true; + case 8 /* NumericLiteral */: + return ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node); + default: + return false; + } + } + })(Rename = ts.Rename || (ts.Rename = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var SignatureHelp; + (function (SignatureHelp) { + var InvocationKind; + (function (InvocationKind) { + InvocationKind[InvocationKind["Call"] = 0] = "Call"; + InvocationKind[InvocationKind["TypeArgs"] = 1] = "TypeArgs"; + InvocationKind[InvocationKind["Contextual"] = 2] = "Contextual"; + })(InvocationKind || (InvocationKind = {})); + function getSignatureHelpItems(program, sourceFile, position, triggerReason, cancellationToken) { + var typeChecker = program.getTypeChecker(); + // Decide whether to show signature help + var startingToken = ts.findTokenOnLeftOfPosition(sourceFile, position); + if (!startingToken) { + // We are at the beginning of the file + return undefined; + } + // Only need to be careful if the user typed a character and signature help wasn't showing. + var onlyUseSyntacticOwners = !!triggerReason && triggerReason.kind === "characterTyped"; + // Bail out quickly in the middle of a string or comment, don't provide signature help unless the user explicitly requested it. + if (onlyUseSyntacticOwners && (ts.isInString(sourceFile, position, startingToken) || ts.isInComment(sourceFile, position))) { + return undefined; + } + var isManuallyInvoked = !!triggerReason && triggerReason.kind === "invoked"; + var argumentInfo = getContainingArgumentInfo(startingToken, position, sourceFile, typeChecker, isManuallyInvoked); + if (!argumentInfo) + return undefined; + cancellationToken.throwIfCancellationRequested(); + // Extra syntactic and semantic filtering of signature help + var candidateInfo = getCandidateOrTypeInfo(argumentInfo, typeChecker, sourceFile, startingToken, onlyUseSyntacticOwners); + cancellationToken.throwIfCancellationRequested(); + if (!candidateInfo) { + // We didn't have any sig help items produced by the TS compiler. If this is a JS + // file, then see if we can figure out anything better. + return ts.isSourceFileJS(sourceFile) ? createJSSignatureHelpItems(argumentInfo, program, cancellationToken) : undefined; + } + return typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { + return candidateInfo.kind === 0 /* Candidate */ + ? createSignatureHelpItems(candidateInfo.candidates, candidateInfo.resolvedSignature, argumentInfo, sourceFile, typeChecker) + : createTypeHelpItems(candidateInfo.symbol, argumentInfo, sourceFile, typeChecker); + }); + } + SignatureHelp.getSignatureHelpItems = getSignatureHelpItems; + var CandidateOrTypeKind; + (function (CandidateOrTypeKind) { + CandidateOrTypeKind[CandidateOrTypeKind["Candidate"] = 0] = "Candidate"; + CandidateOrTypeKind[CandidateOrTypeKind["Type"] = 1] = "Type"; + })(CandidateOrTypeKind || (CandidateOrTypeKind = {})); + function getCandidateOrTypeInfo(_a, checker, sourceFile, startingToken, onlyUseSyntacticOwners) { + var invocation = _a.invocation, argumentCount = _a.argumentCount; + switch (invocation.kind) { + case 0 /* Call */: { + if (onlyUseSyntacticOwners && !isSyntacticOwner(startingToken, invocation.node, sourceFile)) { + return undefined; + } + var candidates = []; + var resolvedSignature = checker.getResolvedSignatureForSignatureHelp(invocation.node, candidates, argumentCount); // TODO: GH#18217 + return candidates.length === 0 ? undefined : { kind: 0 /* Candidate */, candidates: candidates, resolvedSignature: resolvedSignature }; + } + case 1 /* TypeArgs */: { + var called = invocation.called; + if (onlyUseSyntacticOwners && !containsPrecedingToken(startingToken, sourceFile, ts.isIdentifier(called) ? called.parent : called)) { + return undefined; + } + var candidates = ts.getPossibleGenericSignatures(called, argumentCount, checker); + if (candidates.length !== 0) + return { kind: 0 /* Candidate */, candidates: candidates, resolvedSignature: ts.first(candidates) }; + var symbol = checker.getSymbolAtLocation(called); + return symbol && { kind: 1 /* Type */, symbol: symbol }; + } + case 2 /* Contextual */: + return { kind: 0 /* Candidate */, candidates: [invocation.signature], resolvedSignature: invocation.signature }; + default: + return ts.Debug.assertNever(invocation); + } + } + function isSyntacticOwner(startingToken, node, sourceFile) { + if (!ts.isCallOrNewExpression(node)) + return false; + var invocationChildren = node.getChildren(sourceFile); + switch (startingToken.kind) { + case 20 /* OpenParenToken */: + return ts.contains(invocationChildren, startingToken); + case 27 /* CommaToken */: { + var containingList = ts.findContainingList(startingToken); + return !!containingList && ts.contains(invocationChildren, containingList); + } + case 28 /* LessThanToken */: + return containsPrecedingToken(startingToken, sourceFile, node.expression); + default: + return false; + } + } + function createJSSignatureHelpItems(argumentInfo, program, cancellationToken) { + if (argumentInfo.invocation.kind === 2 /* Contextual */) + return undefined; + // See if we can find some symbol with the call expression name that has call signatures. + var expression = getExpressionFromInvocation(argumentInfo.invocation); + var name = ts.isIdentifier(expression) ? expression.text : ts.isPropertyAccessExpression(expression) ? expression.name.text : undefined; + var typeChecker = program.getTypeChecker(); + return name === undefined ? undefined : ts.firstDefined(program.getSourceFiles(), function (sourceFile) { + return ts.firstDefined(sourceFile.getNamedDeclarations().get(name), function (declaration) { + var type = declaration.symbol && typeChecker.getTypeOfSymbolAtLocation(declaration.symbol, declaration); + var callSignatures = type && type.getCallSignatures(); + if (callSignatures && callSignatures.length) { + return typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { return createSignatureHelpItems(callSignatures, callSignatures[0], argumentInfo, sourceFile, typeChecker); }); + } + }); + }); + } + function containsPrecedingToken(startingToken, sourceFile, container) { + var precedingToken = ts.Debug.assertDefined(ts.findPrecedingToken(startingToken.getFullStart(), sourceFile, startingToken.parent, /*excludeJsdoc*/ true)); + return ts.rangeContainsRange(container, precedingToken); + } + function getArgumentInfoForCompletions(node, position, sourceFile) { + var info = getImmediatelyContainingArgumentInfo(node, position, sourceFile); + return !info || info.isTypeParameterList || info.invocation.kind !== 0 /* Call */ ? undefined + : { invocation: info.invocation.node, argumentCount: info.argumentCount, argumentIndex: info.argumentIndex }; + } + SignatureHelp.getArgumentInfoForCompletions = getArgumentInfoForCompletions; + function getArgumentOrParameterListInfo(node, sourceFile) { + var info = getArgumentOrParameterListAndIndex(node, sourceFile); + if (!info) + return undefined; + var list = info.list, argumentIndex = info.argumentIndex; + var argumentCount = getArgumentCount(list); + if (argumentIndex !== 0) { + ts.Debug.assertLessThan(argumentIndex, argumentCount); + } + var argumentsSpan = getApplicableSpanForArguments(list, sourceFile); + return { list: list, argumentIndex: argumentIndex, argumentCount: argumentCount, argumentsSpan: argumentsSpan }; + } + function getArgumentOrParameterListAndIndex(node, sourceFile) { + if (node.kind === 28 /* LessThanToken */ || node.kind === 20 /* OpenParenToken */) { + // Find the list that starts right *after* the < or ( token. + // If the user has just opened a list, consider this item 0. + return { list: getChildListThatStartsWithOpenerToken(node.parent, node, sourceFile), argumentIndex: 0 }; + } + else { + // findListItemInfo can return undefined if we are not in parent's argument list + // or type argument list. This includes cases where the cursor is: + // - To the right of the closing parenthesis, non-substitution template, or template tail. + // - Between the type arguments and the arguments (greater than token) + // - On the target of the call (parent.func) + // - On the 'new' keyword in a 'new' expression + var list = ts.findContainingList(node); + return list && { list: list, argumentIndex: getArgumentIndex(list, node) }; + } + } + /** + * Returns relevant information for the argument list and the current argument if we are + * in the argument of an invocation; returns undefined otherwise. + */ + function getImmediatelyContainingArgumentInfo(node, position, sourceFile) { + var parent = node.parent; + if (ts.isCallOrNewExpression(parent)) { + var invocation = parent; + // There are 3 cases to handle: + // 1. The token introduces a list, and should begin a signature help session + // 2. The token is either not associated with a list, or ends a list, so the session should end + // 3. The token is buried inside a list, and should give signature help + // + // The following are examples of each: + // + // Case 1: + // foo<#T, U>(#a, b) -> The token introduces a list, and should begin a signature help session + // Case 2: + // fo#o#(a, b)# -> The token is either not associated with a list, or ends a list, so the session should end + // Case 3: + // foo(a#, #b#) -> The token is buried inside a list, and should give signature help + // Find out if 'node' is an argument, a type argument, or neither + var info = getArgumentOrParameterListInfo(node, sourceFile); + if (!info) + return undefined; + var list = info.list, argumentIndex = info.argumentIndex, argumentCount = info.argumentCount, argumentsSpan = info.argumentsSpan; + var isTypeParameterList = !!parent.typeArguments && parent.typeArguments.pos === list.pos; + return { isTypeParameterList: isTypeParameterList, invocation: { kind: 0 /* Call */, node: invocation }, argumentsSpan: argumentsSpan, argumentIndex: argumentIndex, argumentCount: argumentCount }; + } + else if (ts.isNoSubstitutionTemplateLiteral(node) && ts.isTaggedTemplateExpression(parent)) { + // Check if we're actually inside the template; + // otherwise we'll fall out and return undefined. + if (ts.isInsideTemplateLiteral(node, position, sourceFile)) { + return getArgumentListInfoForTemplate(parent, /*argumentIndex*/ 0, sourceFile); + } + return undefined; + } + else if (ts.isTemplateHead(node) && parent.parent.kind === 193 /* TaggedTemplateExpression */) { + var templateExpression = parent; + var tagExpression = templateExpression.parent; + ts.Debug.assert(templateExpression.kind === 206 /* TemplateExpression */); + var argumentIndex = ts.isInsideTemplateLiteral(node, position, sourceFile) ? 0 : 1; + return getArgumentListInfoForTemplate(tagExpression, argumentIndex, sourceFile); + } + else if (ts.isTemplateSpan(parent) && ts.isTaggedTemplateExpression(parent.parent.parent)) { + var templateSpan = parent; + var tagExpression = parent.parent.parent; + // If we're just after a template tail, don't show signature help. + if (ts.isTemplateTail(node) && !ts.isInsideTemplateLiteral(node, position, sourceFile)) { + return undefined; + } + var spanIndex = templateSpan.parent.templateSpans.indexOf(templateSpan); + var argumentIndex = getArgumentIndexForTemplatePiece(spanIndex, node, position, sourceFile); + return getArgumentListInfoForTemplate(tagExpression, argumentIndex, sourceFile); + } + else if (ts.isJsxOpeningLikeElement(parent)) { + // Provide a signature help for JSX opening element or JSX self-closing element. + // This is not guarantee that JSX tag-name is resolved into stateless function component. (that is done in "getSignatureHelpItems") + // i.e + // export function MainButton(props: ButtonProps, context: any): JSX.Element { ... } + // ' 'b'. So, in this case the arg count will be 2. However, there + // is a small subtlety. If you have "Foo(a,)", then the child list will just have + // 'a' ''. So, in the case where the last child is a comma, we increase the + // arg count by one to compensate. + // + // Note: this subtlety only applies to the last comma. If you had "Foo(a,," then + // we'll have: 'a' '' '' + // That will give us 2 non-commas. We then add one for the last comma, giving us an + // arg count of 3. + var listChildren = argumentsList.getChildren(); + var argumentCount = ts.countWhere(listChildren, function (arg) { return arg.kind !== 27 /* CommaToken */; }); + if (listChildren.length > 0 && ts.last(listChildren).kind === 27 /* CommaToken */) { + argumentCount++; + } + return argumentCount; + } + // spanIndex is either the index for a given template span. + // This does not give appropriate results for a NoSubstitutionTemplateLiteral + function getArgumentIndexForTemplatePiece(spanIndex, node, position, sourceFile) { + // Because the TemplateStringsArray is the first argument, we have to offset each substitution expression by 1. + // There are three cases we can encounter: + // 1. We are precisely in the template literal (argIndex = 0). + // 2. We are in or to the right of the substitution expression (argIndex = spanIndex + 1). + // 3. We are directly to the right of the template literal, but because we look for the token on the left, + // not enough to put us in the substitution expression; we should consider ourselves part of + // the *next* span's expression by offsetting the index (argIndex = (spanIndex + 1) + 1). + // + // tslint:disable no-double-space + // Example: f `# abcd $#{# 1 + 1# }# efghi ${ #"#hello"# } # ` + // ^ ^ ^ ^ ^ ^ ^ ^ ^ + // Case: 1 1 3 2 1 3 2 2 1 + // tslint:enable no-double-space + ts.Debug.assert(position >= node.getStart(), "Assumed 'position' could not occur before node."); + if (ts.isTemplateLiteralToken(node)) { + if (ts.isInsideTemplateLiteral(node, position, sourceFile)) { + return 0; + } + return spanIndex + 2; + } + return spanIndex + 1; + } + function getArgumentListInfoForTemplate(tagExpression, argumentIndex, sourceFile) { + // argumentCount is either 1 or (numSpans + 1) to account for the template strings array argument. + var argumentCount = ts.isNoSubstitutionTemplateLiteral(tagExpression.template) ? 1 : tagExpression.template.templateSpans.length + 1; + if (argumentIndex !== 0) { + ts.Debug.assertLessThan(argumentIndex, argumentCount); + } + return { + isTypeParameterList: false, + invocation: { kind: 0 /* Call */, node: tagExpression }, + argumentsSpan: getApplicableSpanForTaggedTemplate(tagExpression, sourceFile), + argumentIndex: argumentIndex, + argumentCount: argumentCount + }; + } + function getApplicableSpanForArguments(argumentsList, sourceFile) { + // We use full start and skip trivia on the end because we want to include trivia on + // both sides. For example, + // + // foo( /*comment */ a, b, c /*comment*/ ) + // | | + // + // The applicable span is from the first bar to the second bar (inclusive, + // but not including parentheses) + var applicableSpanStart = argumentsList.getFullStart(); + var applicableSpanEnd = ts.skipTrivia(sourceFile.text, argumentsList.getEnd(), /*stopAfterLineBreak*/ false); + return ts.createTextSpan(applicableSpanStart, applicableSpanEnd - applicableSpanStart); + } + function getApplicableSpanForTaggedTemplate(taggedTemplate, sourceFile) { + var template = taggedTemplate.template; + var applicableSpanStart = template.getStart(); + var applicableSpanEnd = template.getEnd(); + // We need to adjust the end position for the case where the template does not have a tail. + // Otherwise, we will not show signature help past the expression. + // For example, + // + // ` ${ 1 + 1 foo(10) + // | | + // This is because a Missing node has no width. However, what we actually want is to include trivia + // leading up to the next token in case the user is about to type in a TemplateMiddle or TemplateTail. + if (template.kind === 206 /* TemplateExpression */) { + var lastSpan = ts.last(template.templateSpans); + if (lastSpan.literal.getFullWidth() === 0) { + applicableSpanEnd = ts.skipTrivia(sourceFile.text, applicableSpanEnd, /*stopAfterLineBreak*/ false); + } + } + return ts.createTextSpan(applicableSpanStart, applicableSpanEnd - applicableSpanStart); + } + function getContainingArgumentInfo(node, position, sourceFile, checker, isManuallyInvoked) { + var _loop_15 = function (n) { + // If the node is not a subspan of its parent, this is a big problem. + // There have been crashes that might be caused by this violation. + ts.Debug.assert(ts.rangeContainsRange(n.parent, n), "Not a subspan", function () { return "Child: " + ts.Debug.showSyntaxKind(n) + ", parent: " + ts.Debug.showSyntaxKind(n.parent); }); + var argumentInfo = getImmediatelyContainingArgumentOrContextualParameterInfo(n, position, sourceFile, checker); + if (argumentInfo) { + return { value: argumentInfo }; + } + }; + for (var n = node; isManuallyInvoked || (!ts.isBlock(n) && !ts.isSourceFile(n)); n = n.parent) { + var state_4 = _loop_15(n); + if (typeof state_4 === "object") + return state_4.value; + } + return undefined; + } + function getChildListThatStartsWithOpenerToken(parent, openerToken, sourceFile) { + var children = parent.getChildren(sourceFile); + var indexOfOpenerToken = children.indexOf(openerToken); + ts.Debug.assert(indexOfOpenerToken >= 0 && children.length > indexOfOpenerToken + 1); + return children[indexOfOpenerToken + 1]; + } + function getExpressionFromInvocation(invocation) { + return invocation.kind === 0 /* Call */ ? ts.getInvokedExpression(invocation.node) : invocation.called; + } + function getEnclosingDeclarationFromInvocation(invocation) { + return invocation.kind === 0 /* Call */ ? invocation.node : invocation.kind === 1 /* TypeArgs */ ? invocation.called : invocation.node; + } + var signatureHelpNodeBuilderFlags = 8192 /* OmitParameterModifiers */ | 70221824 /* IgnoreErrors */ | 16384 /* UseAliasDefinedOutsideCurrentScope */; + function createSignatureHelpItems(candidates, resolvedSignature, _a, sourceFile, typeChecker) { + var isTypeParameterList = _a.isTypeParameterList, argumentCount = _a.argumentCount, applicableSpan = _a.argumentsSpan, invocation = _a.invocation, argumentIndex = _a.argumentIndex; + var enclosingDeclaration = getEnclosingDeclarationFromInvocation(invocation); + var callTargetSymbol = invocation.kind === 2 /* Contextual */ ? invocation.symbol : typeChecker.getSymbolAtLocation(getExpressionFromInvocation(invocation)); + var callTargetDisplayParts = callTargetSymbol ? ts.symbolToDisplayParts(typeChecker, callTargetSymbol, /*enclosingDeclaration*/ undefined, /*meaning*/ undefined) : ts.emptyArray; + var items = candidates.map(function (candidateSignature) { return getSignatureHelpItem(candidateSignature, callTargetDisplayParts, isTypeParameterList, typeChecker, enclosingDeclaration, sourceFile); }); + if (argumentIndex !== 0) { + ts.Debug.assertLessThan(argumentIndex, argumentCount); + } + var selectedItemIndex = candidates.indexOf(resolvedSignature); + ts.Debug.assert(selectedItemIndex !== -1); // If candidates is non-empty it should always include bestSignature. We check for an empty candidates before calling this function. + return { items: items, applicableSpan: applicableSpan, selectedItemIndex: selectedItemIndex, argumentIndex: argumentIndex, argumentCount: argumentCount }; + } + function createTypeHelpItems(symbol, _a, sourceFile, checker) { + var argumentCount = _a.argumentCount, applicableSpan = _a.argumentsSpan, invocation = _a.invocation, argumentIndex = _a.argumentIndex; + var typeParameters = checker.getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); + if (!typeParameters) + return undefined; + var items = [getTypeHelpItem(symbol, typeParameters, checker, getEnclosingDeclarationFromInvocation(invocation), sourceFile)]; + return { items: items, applicableSpan: applicableSpan, selectedItemIndex: 0, argumentIndex: argumentIndex, argumentCount: argumentCount }; + } + function getTypeHelpItem(symbol, typeParameters, checker, enclosingDeclaration, sourceFile) { + var typeSymbolDisplay = ts.symbolToDisplayParts(checker, symbol); + var printer = ts.createPrinter({ removeComments: true }); + var parameters = typeParameters.map(function (t) { return createSignatureHelpParameterForTypeParameter(t, checker, enclosingDeclaration, sourceFile, printer); }); + var documentation = symbol.getDocumentationComment(checker); + var tags = symbol.getJsDocTags(); + var prefixDisplayParts = typeSymbolDisplay.concat([ts.punctuationPart(28 /* LessThanToken */)]); + return { isVariadic: false, prefixDisplayParts: prefixDisplayParts, suffixDisplayParts: [ts.punctuationPart(30 /* GreaterThanToken */)], separatorDisplayParts: separatorDisplayParts, parameters: parameters, documentation: documentation, tags: tags }; + } + var separatorDisplayParts = [ts.punctuationPart(27 /* CommaToken */), ts.spacePart()]; + function getSignatureHelpItem(candidateSignature, callTargetDisplayParts, isTypeParameterList, checker, enclosingDeclaration, sourceFile) { + var _a = (isTypeParameterList ? itemInfoForTypeParameters : itemInfoForParameters)(candidateSignature, checker, enclosingDeclaration, sourceFile), isVariadic = _a.isVariadic, parameters = _a.parameters, prefix = _a.prefix, suffix = _a.suffix; + var prefixDisplayParts = callTargetDisplayParts.concat(prefix); + var suffixDisplayParts = suffix.concat(returnTypeToDisplayParts(candidateSignature, enclosingDeclaration, checker)); + var documentation = candidateSignature.getDocumentationComment(checker); + var tags = candidateSignature.getJsDocTags(); + return { isVariadic: isVariadic, prefixDisplayParts: prefixDisplayParts, suffixDisplayParts: suffixDisplayParts, separatorDisplayParts: separatorDisplayParts, parameters: parameters, documentation: documentation, tags: tags }; + } + function returnTypeToDisplayParts(candidateSignature, enclosingDeclaration, checker) { + return ts.mapToDisplayParts(function (writer) { + writer.writePunctuation(":"); + writer.writeSpace(" "); + var predicate = checker.getTypePredicateOfSignature(candidateSignature); + if (predicate) { + checker.writeTypePredicate(predicate, enclosingDeclaration, /*flags*/ undefined, writer); + } + else { + checker.writeType(checker.getReturnTypeOfSignature(candidateSignature), enclosingDeclaration, /*flags*/ undefined, writer); + } + }); + } + function itemInfoForTypeParameters(candidateSignature, checker, enclosingDeclaration, sourceFile) { + var typeParameters = (candidateSignature.target || candidateSignature).typeParameters; + var printer = ts.createPrinter({ removeComments: true }); + var parameters = (typeParameters || ts.emptyArray).map(function (t) { return createSignatureHelpParameterForTypeParameter(t, checker, enclosingDeclaration, sourceFile, printer); }); + var parameterParts = ts.mapToDisplayParts(function (writer) { + var thisParameter = candidateSignature.thisParameter ? [checker.symbolToParameterDeclaration(candidateSignature.thisParameter, enclosingDeclaration, signatureHelpNodeBuilderFlags)] : []; + var params = ts.createNodeArray(thisParameter.concat(candidateSignature.parameters.map(function (param) { return checker.symbolToParameterDeclaration(param, enclosingDeclaration, signatureHelpNodeBuilderFlags); }))); + printer.writeList(2576 /* CallExpressionArguments */, params, sourceFile, writer); + }); + return { isVariadic: false, parameters: parameters, prefix: [ts.punctuationPart(28 /* LessThanToken */)], suffix: [ts.punctuationPart(30 /* GreaterThanToken */)].concat(parameterParts) }; + } + function itemInfoForParameters(candidateSignature, checker, enclosingDeclaration, sourceFile) { + var isVariadic = candidateSignature.hasRestParameter; + var printer = ts.createPrinter({ removeComments: true }); + var typeParameterParts = ts.mapToDisplayParts(function (writer) { + if (candidateSignature.typeParameters && candidateSignature.typeParameters.length) { + var args = ts.createNodeArray(candidateSignature.typeParameters.map(function (p) { return checker.typeParameterToDeclaration(p, enclosingDeclaration); })); + printer.writeList(53776 /* TypeParameters */, args, sourceFile, writer); + } + }); + var parameters = candidateSignature.parameters.map(function (p) { return createSignatureHelpParameterForParameter(p, checker, enclosingDeclaration, sourceFile, printer); }); + return { isVariadic: isVariadic, parameters: parameters, prefix: typeParameterParts.concat([ts.punctuationPart(20 /* OpenParenToken */)]), suffix: [ts.punctuationPart(21 /* CloseParenToken */)] }; + } + function createSignatureHelpParameterForParameter(parameter, checker, enclosingDeclaration, sourceFile, printer) { + var displayParts = ts.mapToDisplayParts(function (writer) { + var param = checker.symbolToParameterDeclaration(parameter, enclosingDeclaration, signatureHelpNodeBuilderFlags); + printer.writeNode(4 /* Unspecified */, param, sourceFile, writer); + }); + var isOptional = checker.isOptionalParameter(parameter.valueDeclaration); + return { name: parameter.name, documentation: parameter.getDocumentationComment(checker), displayParts: displayParts, isOptional: isOptional }; + } + function createSignatureHelpParameterForTypeParameter(typeParameter, checker, enclosingDeclaration, sourceFile, printer) { + var displayParts = ts.mapToDisplayParts(function (writer) { + var param = checker.typeParameterToDeclaration(typeParameter, enclosingDeclaration); + printer.writeNode(4 /* Unspecified */, param, sourceFile, writer); + }); + return { name: typeParameter.symbol.name, documentation: typeParameter.symbol.getDocumentationComment(checker), displayParts: displayParts, isOptional: false }; + } + })(SignatureHelp = ts.SignatureHelp || (ts.SignatureHelp = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var base64UrlRegExp = /^data:(?:application\/json(?:;charset=[uU][tT][fF]-8);base64,([A-Za-z0-9+\/=]+)$)?/; + function getSourceMapper(useCaseSensitiveFileNames, currentDirectory, log, host, getProgram) { + var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); + var sourcemappedFileCache; + return { tryGetSourcePosition: tryGetSourcePosition, tryGetGeneratedPosition: tryGetGeneratedPosition, toLineColumnOffset: toLineColumnOffset, clearCache: clearCache }; + function toPath(fileName) { + return ts.toPath(fileName, currentDirectory, getCanonicalFileName); + } + function scanForSourcemapURL(fileName) { + var mappedFile = sourcemappedFileCache.get(toPath(fileName)); + if (!mappedFile) { + return; + } + return ts.tryGetSourceMappingURL(mappedFile.text, ts.getLineStarts(mappedFile)); + } + function convertDocumentToSourceMapper(file, contents, mapFileName) { + var map = ts.tryParseRawSourceMap(contents); + if (!map || !map.sources || !map.file || !map.mappings) { + // obviously invalid map + return file.sourceMapper = ts.identitySourceMapConsumer; + } + var program = getProgram(); + return file.sourceMapper = ts.createDocumentPositionMapper({ + getSourceFileLike: function (s) { + // Lookup file in program, if provided + var file = program && program.getSourceFileByPath(s); + // file returned here could be .d.ts when asked for .ts file if projectReferences and module resolution created this source file + if (file === undefined || file.resolvedPath !== s) { + // Otherwise check the cache (which may hit disk) + return sourcemappedFileCache.get(s); + } + return file; + }, + getCanonicalFileName: getCanonicalFileName, + log: log, + }, map, mapFileName); + } + function getSourceMapper(fileName, file) { + if (!host.readFile || !host.fileExists) { + return file.sourceMapper = ts.identitySourceMapConsumer; + } + if (file.sourceMapper) { + return file.sourceMapper; + } + var mapFileName = scanForSourcemapURL(fileName); + if (mapFileName) { + var match = base64UrlRegExp.exec(mapFileName); + if (match) { + if (match[1]) { + var base64Object = match[1]; + return convertDocumentToSourceMapper(file, ts.base64decode(ts.sys, base64Object), fileName); + } + // Not a data URL we can parse, skip it + mapFileName = undefined; + } + } + var possibleMapLocations = []; + if (mapFileName) { + possibleMapLocations.push(mapFileName); + } + possibleMapLocations.push(fileName + ".map"); + for (var _i = 0, possibleMapLocations_1 = possibleMapLocations; _i < possibleMapLocations_1.length; _i++) { + var location = possibleMapLocations_1[_i]; + var mapPath = ts.toPath(location, ts.getDirectoryPath(fileName), getCanonicalFileName); + if (host.fileExists(mapPath)) { + return convertDocumentToSourceMapper(file, host.readFile(mapPath), mapPath); // TODO: GH#18217 + } + } + return file.sourceMapper = ts.identitySourceMapConsumer; + } + function tryGetSourcePosition(info) { + if (!ts.isDeclarationFileName(info.fileName)) + return undefined; + var file = getFile(info.fileName); + if (!file) + return undefined; + var newLoc = getSourceMapper(info.fileName, file).getSourcePosition(info); + return newLoc === info ? undefined : tryGetSourcePosition(newLoc) || newLoc; + } + function tryGetGeneratedPosition(info) { + var program = getProgram(); + var options = program.getCompilerOptions(); + var outPath = options.outFile || options.out; + var declarationPath = outPath ? + ts.removeFileExtension(outPath) + ".d.ts" /* Dts */ : + ts.getDeclarationEmitOutputFilePathWorker(info.fileName, program.getCompilerOptions(), currentDirectory, program.getCommonSourceDirectory(), getCanonicalFileName); + if (declarationPath === undefined) + return undefined; + var declarationFile = getFile(declarationPath); + if (!declarationFile) + return undefined; + var newLoc = getSourceMapper(declarationPath, declarationFile).getGeneratedPosition(info); + return newLoc === info ? undefined : newLoc; + } + function getFile(fileName) { + var path = toPath(fileName); + var file = getProgram().getSourceFileByPath(path); + if (file && file.resolvedPath === path) { + return file; + } + return sourcemappedFileCache.get(path); + } + function toLineColumnOffset(fileName, position) { + var file = getFile(fileName); // TODO: GH#18217 + return file.getLineAndCharacterOfPosition(position); + } + function clearCache() { + sourcemappedFileCache = createSourceFileLikeCache(host); + } + } + ts.getSourceMapper = getSourceMapper; + function createSourceFileLikeCache(host) { + var cached = ts.createMap(); + return { + get: function (path) { + if (cached.has(path)) { + return cached.get(path); + } + if (!host.fileExists || !host.readFile || !host.fileExists(path)) + return; + // And failing that, check the disk + var text = host.readFile(path); // TODO: GH#18217 + var file = { + text: text, + lineMap: undefined, + getLineAndCharacterOfPosition: function (pos) { + return ts.computeLineAndCharacterOfPosition(ts.getLineStarts(this), pos); + } + }; + cached.set(path, file); + return file; + } + }; + } +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + function computeSuggestionDiagnostics(sourceFile, program, cancellationToken) { + program.getSemanticDiagnostics(sourceFile, cancellationToken); + var diags = []; + var checker = program.getTypeChecker(); + if (sourceFile.commonJsModuleIndicator && + (ts.programContainsEs6Modules(program) || ts.compilerOptionsIndicateEs6Modules(program.getCompilerOptions())) && + containsTopLevelCommonjs(sourceFile)) { + diags.push(ts.createDiagnosticForNode(getErrorNodeFromCommonJsIndicator(sourceFile.commonJsModuleIndicator), ts.Diagnostics.File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module)); + } + var isJsFile = ts.isSourceFileJS(sourceFile); + check(sourceFile); + if (ts.getAllowSyntheticDefaultImports(program.getCompilerOptions())) { + for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { + var moduleSpecifier = _a[_i]; + var importNode = ts.importFromModuleSpecifier(moduleSpecifier); + var name = importNameForConvertToDefaultImport(importNode); + if (!name) + continue; + var module_2 = ts.getResolvedModule(sourceFile, moduleSpecifier.text); + var resolvedFile = module_2 && program.getSourceFile(module_2.resolvedFileName); + if (resolvedFile && resolvedFile.externalModuleIndicator && ts.isExportAssignment(resolvedFile.externalModuleIndicator) && resolvedFile.externalModuleIndicator.isExportEquals) { + diags.push(ts.createDiagnosticForNode(name, ts.Diagnostics.Import_may_be_converted_to_a_default_import)); + } + } + } + ts.addRange(diags, sourceFile.bindSuggestionDiagnostics); + ts.addRange(diags, program.getSuggestionDiagnostics(sourceFile, cancellationToken)); + return diags.sort(function (d1, d2) { return d1.start - d2.start; }); + function check(node) { + if (isJsFile) { + switch (node.kind) { + case 196 /* FunctionExpression */: + var decl = ts.getDeclarationOfExpando(node); + if (decl) { + var symbol_2 = decl.symbol; + if (symbol_2 && (symbol_2.exports && symbol_2.exports.size || symbol_2.members && symbol_2.members.size)) { + diags.push(ts.createDiagnosticForNode(ts.isVariableDeclaration(node.parent) ? node.parent.name : node, ts.Diagnostics.This_constructor_function_may_be_converted_to_a_class_declaration)); + break; + } + } + // falls through if no diagnostic was created + case 239 /* FunctionDeclaration */: + var symbol = node.symbol; + if (symbol.members && (symbol.members.size > 0)) { + diags.push(ts.createDiagnosticForNode(ts.isVariableDeclaration(node.parent) ? node.parent.name : node, ts.Diagnostics.This_constructor_function_may_be_converted_to_a_class_declaration)); + } + break; + } + } + else { + if (ts.isVariableStatement(node) && + node.parent === sourceFile && + node.declarationList.flags & 2 /* Const */ && + node.declarationList.declarations.length === 1) { + var init = node.declarationList.declarations[0].initializer; + if (init && ts.isRequireCall(init, /*checkArgumentIsStringLiteralLike*/ true)) { + diags.push(ts.createDiagnosticForNode(init, ts.Diagnostics.require_call_may_be_converted_to_an_import)); + } + } + if (ts.codefix.parameterShouldGetTypeFromJSDoc(node)) { + diags.push(ts.createDiagnosticForNode(node.name || node, ts.Diagnostics.JSDoc_types_may_be_moved_to_TypeScript_types)); + } + } + if (ts.isFunctionLikeDeclaration(node)) { + addConvertToAsyncFunctionDiagnostics(node, checker, diags); + } + node.forEachChild(check); + } + } + ts.computeSuggestionDiagnostics = computeSuggestionDiagnostics; + // convertToEs6Module only works on top-level, so don't trigger it if commonjs code only appears in nested scopes. + function containsTopLevelCommonjs(sourceFile) { + return sourceFile.statements.some(function (statement) { + switch (statement.kind) { + case 219 /* VariableStatement */: + return statement.declarationList.declarations.some(function (decl) { + return !!decl.initializer && ts.isRequireCall(propertyAccessLeftHandSide(decl.initializer), /*checkArgumentIsStringLiteralLike*/ true); + }); + case 221 /* ExpressionStatement */: { + var expression = statement.expression; + if (!ts.isBinaryExpression(expression)) + return ts.isRequireCall(expression, /*checkArgumentIsStringLiteralLike*/ true); + var kind = ts.getAssignmentDeclarationKind(expression); + return kind === 1 /* ExportsProperty */ || kind === 2 /* ModuleExports */; + } + default: + return false; + } + }); + } + function propertyAccessLeftHandSide(node) { + return ts.isPropertyAccessExpression(node) ? propertyAccessLeftHandSide(node.expression) : node; + } + function importNameForConvertToDefaultImport(node) { + switch (node.kind) { + case 249 /* ImportDeclaration */: + var importClause = node.importClause, moduleSpecifier = node.moduleSpecifier; + return importClause && !importClause.name && importClause.namedBindings && importClause.namedBindings.kind === 251 /* NamespaceImport */ && ts.isStringLiteral(moduleSpecifier) + ? importClause.namedBindings.name + : undefined; + case 248 /* ImportEqualsDeclaration */: + return node.name; + default: + return undefined; + } + } + function addConvertToAsyncFunctionDiagnostics(node, checker, diags) { + if (!ts.isAsyncFunction(node) && + node.body && + ts.isBlock(node.body) && + hasReturnStatementWithPromiseHandler(node.body) && + returnsPromise(node, checker)) { + diags.push(ts.createDiagnosticForNode(!node.name && ts.isVariableDeclaration(node.parent) && ts.isIdentifier(node.parent.name) ? node.parent.name : node, ts.Diagnostics.This_may_be_converted_to_an_async_function)); + } + } + function returnsPromise(node, checker) { + var functionType = checker.getTypeAtLocation(node); + var callSignatures = checker.getSignaturesOfType(functionType, 0 /* Call */); + var returnType = callSignatures.length ? checker.getReturnTypeOfSignature(callSignatures[0]) : undefined; + return !!returnType && !!checker.getPromisedTypeOfPromise(returnType); + } + function getErrorNodeFromCommonJsIndicator(commonJsModuleIndicator) { + return ts.isBinaryExpression(commonJsModuleIndicator) ? commonJsModuleIndicator.left : commonJsModuleIndicator; + } + function hasReturnStatementWithPromiseHandler(body) { + return !!ts.forEachReturnStatement(body, isReturnStatementWithFixablePromiseHandler); + } + function isReturnStatementWithFixablePromiseHandler(node) { + return ts.isReturnStatement(node) && !!node.expression && isFixablePromiseHandler(node.expression); + } + ts.isReturnStatementWithFixablePromiseHandler = isReturnStatementWithFixablePromiseHandler; + // Should be kept up to date with transformExpression in convertToAsyncFunction.ts + function isFixablePromiseHandler(node) { + // ensure outermost call exists and is a promise handler + if (!isPromiseHandler(node) || !node.arguments.every(isFixablePromiseArgument)) { + return false; + } + // ensure all chained calls are valid + var currentNode = node.expression; + while (isPromiseHandler(currentNode) || ts.isPropertyAccessExpression(currentNode)) { + if (ts.isCallExpression(currentNode) && !currentNode.arguments.every(isFixablePromiseArgument)) { + return false; + } + currentNode = currentNode.expression; + } + return true; + } + ts.isFixablePromiseHandler = isFixablePromiseHandler; + function isPromiseHandler(node) { + return ts.isCallExpression(node) && (ts.hasPropertyAccessExpressionWithName(node, "then") || ts.hasPropertyAccessExpressionWithName(node, "catch")); + } + // should be kept up to date with getTransformationBody in convertToAsyncFunction.ts + function isFixablePromiseArgument(arg) { + switch (arg.kind) { + case 96 /* NullKeyword */: + case 72 /* Identifier */: // identifier includes undefined + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + return true; + default: + return false; + } + } +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var SymbolDisplay; + (function (SymbolDisplay) { + // TODO(drosen): use contextual SemanticMeaning. + function getSymbolKind(typeChecker, symbol, location) { + var result = getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, location); + if (result !== "" /* unknown */) { + return result; + } + var flags = ts.getCombinedLocalAndExportSymbolFlags(symbol); + if (flags & 32 /* Class */) { + return ts.getDeclarationOfKind(symbol, 209 /* ClassExpression */) ? + "local class" /* localClassElement */ : "class" /* classElement */; + } + if (flags & 384 /* Enum */) + return "enum" /* enumElement */; + if (flags & 524288 /* TypeAlias */) + return "type" /* typeElement */; + if (flags & 64 /* Interface */) + return "interface" /* interfaceElement */; + if (flags & 262144 /* TypeParameter */) + return "type parameter" /* typeParameterElement */; + if (flags & 262144 /* TypeParameter */) + return "type parameter" /* typeParameterElement */; + if (flags & 8 /* EnumMember */) + return "enum member" /* enumMemberElement */; + if (flags & 2097152 /* Alias */) + return "alias" /* alias */; + if (flags & 1536 /* Module */) + return "module" /* moduleElement */; + return result; + } + SymbolDisplay.getSymbolKind = getSymbolKind; + function getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, location) { + var roots = typeChecker.getRootSymbols(symbol); + // If this is a method from a mapped type, leave as a method so long as it still has a call signature. + if (roots.length === 1 + && ts.first(roots).flags & 8192 /* Method */ + // Ensure the mapped version is still a method, as opposed to `{ [K in keyof I]: number }`. + && typeChecker.getTypeOfSymbolAtLocation(symbol, location).getNonNullableType().getCallSignatures().length !== 0) { + return "method" /* memberFunctionElement */; + } + if (typeChecker.isUndefinedSymbol(symbol)) { + return "var" /* variableElement */; + } + if (typeChecker.isArgumentsSymbol(symbol)) { + return "local var" /* localVariableElement */; + } + if (location.kind === 100 /* ThisKeyword */ && ts.isExpression(location)) { + return "parameter" /* parameterElement */; + } + var flags = ts.getCombinedLocalAndExportSymbolFlags(symbol); + if (flags & 3 /* Variable */) { + if (ts.isFirstDeclarationOfSymbolParameter(symbol)) { + return "parameter" /* parameterElement */; + } + else if (symbol.valueDeclaration && ts.isVarConst(symbol.valueDeclaration)) { + return "const" /* constElement */; + } + else if (ts.forEach(symbol.declarations, ts.isLet)) { + return "let" /* letElement */; + } + return isLocalVariableOrFunction(symbol) ? "local var" /* localVariableElement */ : "var" /* variableElement */; + } + if (flags & 16 /* Function */) + return isLocalVariableOrFunction(symbol) ? "local function" /* localFunctionElement */ : "function" /* functionElement */; + if (flags & 32768 /* GetAccessor */) + return "getter" /* memberGetAccessorElement */; + if (flags & 65536 /* SetAccessor */) + return "setter" /* memberSetAccessorElement */; + if (flags & 8192 /* Method */) + return "method" /* memberFunctionElement */; + if (flags & 16384 /* Constructor */) + return "constructor" /* constructorImplementationElement */; + if (flags & 4 /* Property */) { + if (flags & 33554432 /* Transient */ && symbol.checkFlags & 6 /* Synthetic */) { + // If union property is result of union of non method (property/accessors/variables), it is labeled as property + var unionPropertyKind = ts.forEach(typeChecker.getRootSymbols(symbol), function (rootSymbol) { + var rootSymbolFlags = rootSymbol.getFlags(); + if (rootSymbolFlags & (98308 /* PropertyOrAccessor */ | 3 /* Variable */)) { + return "property" /* memberVariableElement */; + } + // May be a Function if this was from `typeof N` with `namespace N { function f();. }`. + ts.Debug.assert(!!(rootSymbolFlags & (8192 /* Method */ | 16 /* Function */))); + }); + if (!unionPropertyKind) { + // If this was union of all methods, + // make sure it has call signatures before we can label it as method + var typeOfUnionProperty = typeChecker.getTypeOfSymbolAtLocation(symbol, location); + if (typeOfUnionProperty.getCallSignatures().length) { + return "method" /* memberFunctionElement */; + } + return "property" /* memberVariableElement */; + } + return unionPropertyKind; + } + // If we requested completions after `x.` at the top-level, we may be at a source file location. + switch (location.parent && location.parent.kind) { + // If we've typed a character of the attribute name, will be 'JsxAttribute', else will be 'JsxOpeningElement'. + case 262 /* JsxOpeningElement */: + case 260 /* JsxElement */: + case 261 /* JsxSelfClosingElement */: + return location.kind === 72 /* Identifier */ ? "property" /* memberVariableElement */ : "JSX attribute" /* jsxAttribute */; + case 267 /* JsxAttribute */: + return "JSX attribute" /* jsxAttribute */; + default: + return "property" /* memberVariableElement */; + } + } + return "" /* unknown */; + } + function getSymbolModifiers(symbol) { + var nodeModifiers = symbol && symbol.declarations && symbol.declarations.length > 0 + ? ts.getNodeModifiers(symbol.declarations[0]) + : "" /* none */; + var symbolModifiers = symbol && symbol.flags & 16777216 /* Optional */ ? + "optional" /* optionalModifier */ + : "" /* none */; + return nodeModifiers && symbolModifiers ? nodeModifiers + "," + symbolModifiers : nodeModifiers || symbolModifiers; + } + SymbolDisplay.getSymbolModifiers = getSymbolModifiers; + // TODO(drosen): Currently completion entry details passes the SemanticMeaning.All instead of using semanticMeaning of location + function getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, enclosingDeclaration, location, semanticMeaning, alias) { + if (semanticMeaning === void 0) { semanticMeaning = ts.getMeaningFromLocation(location); } + var displayParts = []; + var documentation; + var tags; + var symbolFlags = ts.getCombinedLocalAndExportSymbolFlags(symbol); + var symbolKind = semanticMeaning & 1 /* Value */ ? getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, location) : "" /* unknown */; + var hasAddedSymbolInfo = false; + var isThisExpression = location.kind === 100 /* ThisKeyword */ && ts.isInExpressionContext(location); + var type; + var printer; + var documentationFromAlias; + var tagsFromAlias; + if (location.kind === 100 /* ThisKeyword */ && !isThisExpression) { + return { displayParts: [ts.keywordPart(100 /* ThisKeyword */)], documentation: [], symbolKind: "primitive type" /* primitiveType */, tags: undefined }; + } + // Class at constructor site need to be shown as constructor apart from property,method, vars + if (symbolKind !== "" /* unknown */ || symbolFlags & 32 /* Class */ || symbolFlags & 2097152 /* Alias */) { + // If it is accessor they are allowed only if location is at name of the accessor + if (symbolKind === "getter" /* memberGetAccessorElement */ || symbolKind === "setter" /* memberSetAccessorElement */) { + symbolKind = "property" /* memberVariableElement */; + } + var signature = void 0; + type = isThisExpression ? typeChecker.getTypeAtLocation(location) : typeChecker.getTypeOfSymbolAtLocation(symbol.exportSymbol || symbol, location); + if (location.parent && location.parent.kind === 189 /* PropertyAccessExpression */) { + var right = location.parent.name; + // Either the location is on the right of a property access, or on the left and the right is missing + if (right === location || (right && right.getFullWidth() === 0)) { + location = location.parent; + } + } + // try get the call/construct signature from the type if it matches + var callExpressionLike = void 0; + if (ts.isCallOrNewExpression(location)) { + callExpressionLike = location; + } + else if (ts.isCallExpressionTarget(location) || ts.isNewExpressionTarget(location)) { + callExpressionLike = location.parent; + } + else if (location.parent && ts.isJsxOpeningLikeElement(location.parent) && ts.isFunctionLike(symbol.valueDeclaration)) { + callExpressionLike = location.parent; + } + if (callExpressionLike) { + var candidateSignatures = []; + signature = typeChecker.getResolvedSignature(callExpressionLike, candidateSignatures); // TODO: GH#18217 + var useConstructSignatures = callExpressionLike.kind === 192 /* NewExpression */ || (ts.isCallExpression(callExpressionLike) && callExpressionLike.expression.kind === 98 /* SuperKeyword */); + var allSignatures = useConstructSignatures ? type.getConstructSignatures() : type.getCallSignatures(); + if (!ts.contains(allSignatures, signature.target) && !ts.contains(allSignatures, signature)) { + // Get the first signature if there is one -- allSignatures may contain + // either the original signature or its target, so check for either + signature = allSignatures.length ? allSignatures[0] : undefined; + } + if (signature) { + if (useConstructSignatures && (symbolFlags & 32 /* Class */)) { + // Constructor + symbolKind = "constructor" /* constructorImplementationElement */; + addPrefixForAnyFunctionOrVar(type.symbol, symbolKind); + } + else if (symbolFlags & 2097152 /* Alias */) { + symbolKind = "alias" /* alias */; + pushSymbolKind(symbolKind); + displayParts.push(ts.spacePart()); + if (useConstructSignatures) { + displayParts.push(ts.keywordPart(95 /* NewKeyword */)); + displayParts.push(ts.spacePart()); + } + addFullSymbolName(symbol); + } + else { + addPrefixForAnyFunctionOrVar(symbol, symbolKind); + } + switch (symbolKind) { + case "JSX attribute" /* jsxAttribute */: + case "property" /* memberVariableElement */: + case "var" /* variableElement */: + case "const" /* constElement */: + case "let" /* letElement */: + case "parameter" /* parameterElement */: + case "local var" /* localVariableElement */: + // If it is call or construct signature of lambda's write type name + displayParts.push(ts.punctuationPart(57 /* ColonToken */)); + displayParts.push(ts.spacePart()); + if (!(ts.getObjectFlags(type) & 16 /* Anonymous */) && type.symbol) { + ts.addRange(displayParts, ts.symbolToDisplayParts(typeChecker, type.symbol, enclosingDeclaration, /*meaning*/ undefined, 4 /* AllowAnyNodeKind */ | 1 /* WriteTypeParametersOrArguments */)); + displayParts.push(ts.lineBreakPart()); + } + if (useConstructSignatures) { + displayParts.push(ts.keywordPart(95 /* NewKeyword */)); + displayParts.push(ts.spacePart()); + } + addSignatureDisplayParts(signature, allSignatures, 262144 /* WriteArrowStyleSignature */); + break; + default: + // Just signature + addSignatureDisplayParts(signature, allSignatures); + } + hasAddedSymbolInfo = true; + } + } + else if ((ts.isNameOfFunctionDeclaration(location) && !(symbolFlags & 98304 /* Accessor */)) || // name of function declaration + (location.kind === 124 /* ConstructorKeyword */ && location.parent.kind === 157 /* Constructor */)) { // At constructor keyword of constructor declaration + // get the signature from the declaration and write it + var functionDeclaration_1 = location.parent; + // Use function declaration to write the signatures only if the symbol corresponding to this declaration + var locationIsSymbolDeclaration = ts.find(symbol.declarations, function (declaration) { + return declaration === (location.kind === 124 /* ConstructorKeyword */ ? functionDeclaration_1.parent : functionDeclaration_1); + }); + if (locationIsSymbolDeclaration) { + var allSignatures = functionDeclaration_1.kind === 157 /* Constructor */ ? type.getNonNullableType().getConstructSignatures() : type.getNonNullableType().getCallSignatures(); + if (!typeChecker.isImplementationOfOverload(functionDeclaration_1)) { + signature = typeChecker.getSignatureFromDeclaration(functionDeclaration_1); // TODO: GH#18217 + } + else { + signature = allSignatures[0]; + } + if (functionDeclaration_1.kind === 157 /* Constructor */) { + // show (constructor) Type(...) signature + symbolKind = "constructor" /* constructorImplementationElement */; + addPrefixForAnyFunctionOrVar(type.symbol, symbolKind); + } + else { + // (function/method) symbol(..signature) + addPrefixForAnyFunctionOrVar(functionDeclaration_1.kind === 160 /* CallSignature */ && + !(type.symbol.flags & 2048 /* TypeLiteral */ || type.symbol.flags & 4096 /* ObjectLiteral */) ? type.symbol : symbol, symbolKind); + } + addSignatureDisplayParts(signature, allSignatures); + hasAddedSymbolInfo = true; + } + } + } + if (symbolFlags & 32 /* Class */ && !hasAddedSymbolInfo && !isThisExpression) { + addAliasPrefixIfNecessary(); + if (ts.getDeclarationOfKind(symbol, 209 /* ClassExpression */)) { + // Special case for class expressions because we would like to indicate that + // the class name is local to the class body (similar to function expression) + // (local class) class + pushSymbolKind("local class" /* localClassElement */); + } + else { + // Class declaration has name which is not local. + displayParts.push(ts.keywordPart(76 /* ClassKeyword */)); + } + displayParts.push(ts.spacePart()); + addFullSymbolName(symbol); + writeTypeParametersOfSymbol(symbol, sourceFile); + } + if ((symbolFlags & 64 /* Interface */) && (semanticMeaning & 2 /* Type */)) { + prefixNextMeaning(); + displayParts.push(ts.keywordPart(110 /* InterfaceKeyword */)); + displayParts.push(ts.spacePart()); + addFullSymbolName(symbol); + writeTypeParametersOfSymbol(symbol, sourceFile); + } + if ((symbolFlags & 524288 /* TypeAlias */) && (semanticMeaning & 2 /* Type */)) { + prefixNextMeaning(); + displayParts.push(ts.keywordPart(140 /* TypeKeyword */)); + displayParts.push(ts.spacePart()); + addFullSymbolName(symbol); + writeTypeParametersOfSymbol(symbol, sourceFile); + displayParts.push(ts.spacePart()); + displayParts.push(ts.operatorPart(59 /* EqualsToken */)); + displayParts.push(ts.spacePart()); + ts.addRange(displayParts, ts.typeToDisplayParts(typeChecker, typeChecker.getDeclaredTypeOfSymbol(symbol), enclosingDeclaration, 8388608 /* InTypeAlias */)); + } + if (symbolFlags & 384 /* Enum */) { + prefixNextMeaning(); + if (ts.some(symbol.declarations, function (d) { return ts.isEnumDeclaration(d) && ts.isEnumConst(d); })) { + displayParts.push(ts.keywordPart(77 /* ConstKeyword */)); + displayParts.push(ts.spacePart()); + } + displayParts.push(ts.keywordPart(84 /* EnumKeyword */)); + displayParts.push(ts.spacePart()); + addFullSymbolName(symbol); + } + if (symbolFlags & 1536 /* Module */) { + prefixNextMeaning(); + var declaration = ts.getDeclarationOfKind(symbol, 244 /* ModuleDeclaration */); + var isNamespace = declaration && declaration.name && declaration.name.kind === 72 /* Identifier */; + displayParts.push(ts.keywordPart(isNamespace ? 131 /* NamespaceKeyword */ : 130 /* ModuleKeyword */)); + displayParts.push(ts.spacePart()); + addFullSymbolName(symbol); + } + if ((symbolFlags & 262144 /* TypeParameter */) && (semanticMeaning & 2 /* Type */)) { + prefixNextMeaning(); + displayParts.push(ts.punctuationPart(20 /* OpenParenToken */)); + displayParts.push(ts.textPart("type parameter")); + displayParts.push(ts.punctuationPart(21 /* CloseParenToken */)); + displayParts.push(ts.spacePart()); + addFullSymbolName(symbol); + if (symbol.parent) { + // Class/Interface type parameter + addInPrefix(); + addFullSymbolName(symbol.parent, enclosingDeclaration); + writeTypeParametersOfSymbol(symbol.parent, enclosingDeclaration); + } + else { + // Method/function type parameter + var decl = ts.getDeclarationOfKind(symbol, 150 /* TypeParameter */); + if (decl === undefined) + return ts.Debug.fail(); + var declaration = decl.parent; + if (declaration) { + if (ts.isFunctionLikeKind(declaration.kind)) { + addInPrefix(); + var signature = typeChecker.getSignatureFromDeclaration(declaration); // TODO: GH#18217 + if (declaration.kind === 161 /* ConstructSignature */) { + displayParts.push(ts.keywordPart(95 /* NewKeyword */)); + displayParts.push(ts.spacePart()); + } + else if (declaration.kind !== 160 /* CallSignature */ && declaration.name) { + addFullSymbolName(declaration.symbol); + } + ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, sourceFile, 32 /* WriteTypeArgumentsOfSignature */)); + } + else if (declaration.kind === 242 /* TypeAliasDeclaration */) { + // Type alias type parameter + // For example + // type list = T[]; // Both T will go through same code path + addInPrefix(); + displayParts.push(ts.keywordPart(140 /* TypeKeyword */)); + displayParts.push(ts.spacePart()); + addFullSymbolName(declaration.symbol); + writeTypeParametersOfSymbol(declaration.symbol, sourceFile); + } + } + } + } + if (symbolFlags & 8 /* EnumMember */) { + symbolKind = "enum member" /* enumMemberElement */; + addPrefixForAnyFunctionOrVar(symbol, "enum member"); + var declaration = symbol.declarations[0]; + if (declaration.kind === 278 /* EnumMember */) { + var constantValue = typeChecker.getConstantValue(declaration); + if (constantValue !== undefined) { + displayParts.push(ts.spacePart()); + displayParts.push(ts.operatorPart(59 /* EqualsToken */)); + displayParts.push(ts.spacePart()); + displayParts.push(ts.displayPart(ts.getTextOfConstantValue(constantValue), typeof constantValue === "number" ? ts.SymbolDisplayPartKind.numericLiteral : ts.SymbolDisplayPartKind.stringLiteral)); + } + } + } + if (symbolFlags & 2097152 /* Alias */) { + prefixNextMeaning(); + if (!hasAddedSymbolInfo) { + var resolvedSymbol = typeChecker.getAliasedSymbol(symbol); + if (resolvedSymbol !== symbol && resolvedSymbol.declarations && resolvedSymbol.declarations.length > 0) { + var resolvedNode = resolvedSymbol.declarations[0]; + var declarationName = ts.getNameOfDeclaration(resolvedNode); + if (declarationName) { + var isExternalModuleDeclaration = ts.isModuleWithStringLiteralName(resolvedNode) && + ts.hasModifier(resolvedNode, 2 /* Ambient */); + var shouldUseAliasName = symbol.name !== "default" && !isExternalModuleDeclaration; + var resolvedInfo = getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, resolvedSymbol, ts.getSourceFileOfNode(resolvedNode), resolvedNode, declarationName, semanticMeaning, shouldUseAliasName ? symbol : resolvedSymbol); + displayParts.push.apply(displayParts, resolvedInfo.displayParts); + displayParts.push(ts.lineBreakPart()); + documentationFromAlias = resolvedInfo.documentation; + tagsFromAlias = resolvedInfo.tags; + } + } + } + switch (symbol.declarations[0].kind) { + case 247 /* NamespaceExportDeclaration */: + displayParts.push(ts.keywordPart(85 /* ExportKeyword */)); + displayParts.push(ts.spacePart()); + displayParts.push(ts.keywordPart(131 /* NamespaceKeyword */)); + break; + case 254 /* ExportAssignment */: + displayParts.push(ts.keywordPart(85 /* ExportKeyword */)); + displayParts.push(ts.spacePart()); + displayParts.push(ts.keywordPart(symbol.declarations[0].isExportEquals ? 59 /* EqualsToken */ : 80 /* DefaultKeyword */)); + break; + case 257 /* ExportSpecifier */: + displayParts.push(ts.keywordPart(85 /* ExportKeyword */)); + break; + default: + displayParts.push(ts.keywordPart(92 /* ImportKeyword */)); + } + displayParts.push(ts.spacePart()); + addFullSymbolName(symbol); + ts.forEach(symbol.declarations, function (declaration) { + if (declaration.kind === 248 /* ImportEqualsDeclaration */) { + var importEqualsDeclaration = declaration; + if (ts.isExternalModuleImportEqualsDeclaration(importEqualsDeclaration)) { + displayParts.push(ts.spacePart()); + displayParts.push(ts.operatorPart(59 /* EqualsToken */)); + displayParts.push(ts.spacePart()); + displayParts.push(ts.keywordPart(134 /* RequireKeyword */)); + displayParts.push(ts.punctuationPart(20 /* OpenParenToken */)); + displayParts.push(ts.displayPart(ts.getTextOfNode(ts.getExternalModuleImportEqualsDeclarationExpression(importEqualsDeclaration)), ts.SymbolDisplayPartKind.stringLiteral)); + displayParts.push(ts.punctuationPart(21 /* CloseParenToken */)); + } + else { + var internalAliasSymbol = typeChecker.getSymbolAtLocation(importEqualsDeclaration.moduleReference); + if (internalAliasSymbol) { + displayParts.push(ts.spacePart()); + displayParts.push(ts.operatorPart(59 /* EqualsToken */)); + displayParts.push(ts.spacePart()); + addFullSymbolName(internalAliasSymbol, enclosingDeclaration); + } + } + return true; + } + }); + } + if (!hasAddedSymbolInfo) { + if (symbolKind !== "" /* unknown */) { + if (type) { + if (isThisExpression) { + prefixNextMeaning(); + displayParts.push(ts.keywordPart(100 /* ThisKeyword */)); + } + else { + addPrefixForAnyFunctionOrVar(symbol, symbolKind); + } + // For properties, variables and local vars: show the type + if (symbolKind === "property" /* memberVariableElement */ || + symbolKind === "JSX attribute" /* jsxAttribute */ || + symbolFlags & 3 /* Variable */ || + symbolKind === "local var" /* localVariableElement */ || + isThisExpression) { + displayParts.push(ts.punctuationPart(57 /* ColonToken */)); + displayParts.push(ts.spacePart()); + // If the type is type parameter, format it specially + if (type.symbol && type.symbol.flags & 262144 /* TypeParameter */) { + var typeParameterParts = ts.mapToDisplayParts(function (writer) { + var param = typeChecker.typeParameterToDeclaration(type, enclosingDeclaration); + getPrinter().writeNode(4 /* Unspecified */, param, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosingDeclaration)), writer); + }); + ts.addRange(displayParts, typeParameterParts); + } + else { + ts.addRange(displayParts, ts.typeToDisplayParts(typeChecker, type, enclosingDeclaration)); + } + } + else if (symbolFlags & 16 /* Function */ || + symbolFlags & 8192 /* Method */ || + symbolFlags & 16384 /* Constructor */ || + symbolFlags & 131072 /* Signature */ || + symbolFlags & 98304 /* Accessor */ || + symbolKind === "method" /* memberFunctionElement */) { + var allSignatures = type.getNonNullableType().getCallSignatures(); + if (allSignatures.length) { + addSignatureDisplayParts(allSignatures[0], allSignatures); + } + } + } + } + else { + symbolKind = getSymbolKind(typeChecker, symbol, location); + } + } + if (!documentation) { + documentation = symbol.getDocumentationComment(typeChecker); + tags = symbol.getJsDocTags(); + if (documentation.length === 0 && symbolFlags & 4 /* Property */) { + // For some special property access expressions like `exports.foo = foo` or `module.exports.foo = foo` + // there documentation comments might be attached to the right hand side symbol of their declarations. + // The pattern of such special property access is that the parent symbol is the symbol of the file. + if (symbol.parent && ts.forEach(symbol.parent.declarations, function (declaration) { return declaration.kind === 279 /* SourceFile */; })) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (!declaration.parent || declaration.parent.kind !== 204 /* BinaryExpression */) { + continue; + } + var rhsSymbol = typeChecker.getSymbolAtLocation(declaration.parent.right); + if (!rhsSymbol) { + continue; + } + documentation = rhsSymbol.getDocumentationComment(typeChecker); + tags = rhsSymbol.getJsDocTags(); + if (documentation.length > 0) { + break; + } + } + } + } + } + if (documentation.length === 0 && documentationFromAlias) { + documentation = documentationFromAlias; + } + if (tags.length === 0 && tagsFromAlias) { + tags = tagsFromAlias; + } + return { displayParts: displayParts, documentation: documentation, symbolKind: symbolKind, tags: tags.length === 0 ? undefined : tags }; + function getPrinter() { + if (!printer) { + printer = ts.createPrinter({ removeComments: true }); + } + return printer; + } + function prefixNextMeaning() { + if (displayParts.length) { + displayParts.push(ts.lineBreakPart()); + } + addAliasPrefixIfNecessary(); + } + function addAliasPrefixIfNecessary() { + if (alias) { + pushSymbolKind("alias" /* alias */); + displayParts.push(ts.spacePart()); + } + } + function addInPrefix() { + displayParts.push(ts.spacePart()); + displayParts.push(ts.keywordPart(93 /* InKeyword */)); + displayParts.push(ts.spacePart()); + } + function addFullSymbolName(symbolToDisplay, enclosingDeclaration) { + if (alias && symbolToDisplay === symbol) { + symbolToDisplay = alias; + } + var fullSymbolDisplayParts = ts.symbolToDisplayParts(typeChecker, symbolToDisplay, enclosingDeclaration || sourceFile, /*meaning*/ undefined, 1 /* WriteTypeParametersOrArguments */ | 2 /* UseOnlyExternalAliasing */ | 4 /* AllowAnyNodeKind */); + ts.addRange(displayParts, fullSymbolDisplayParts); + if (symbol.flags & 16777216 /* Optional */) { + displayParts.push(ts.punctuationPart(56 /* QuestionToken */)); + } + } + function addPrefixForAnyFunctionOrVar(symbol, symbolKind) { + prefixNextMeaning(); + if (symbolKind) { + pushSymbolKind(symbolKind); + if (symbol && !ts.some(symbol.declarations, function (d) { return ts.isArrowFunction(d) || (ts.isFunctionExpression(d) || ts.isClassExpression(d)) && !d.name; })) { + displayParts.push(ts.spacePart()); + addFullSymbolName(symbol); + } + } + } + function pushSymbolKind(symbolKind) { + switch (symbolKind) { + case "var" /* variableElement */: + case "function" /* functionElement */: + case "let" /* letElement */: + case "const" /* constElement */: + case "constructor" /* constructorImplementationElement */: + displayParts.push(ts.textOrKeywordPart(symbolKind)); + return; + default: + displayParts.push(ts.punctuationPart(20 /* OpenParenToken */)); + displayParts.push(ts.textOrKeywordPart(symbolKind)); + displayParts.push(ts.punctuationPart(21 /* CloseParenToken */)); + return; + } + } + function addSignatureDisplayParts(signature, allSignatures, flags) { + if (flags === void 0) { flags = 0 /* None */; } + ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, enclosingDeclaration, flags | 32 /* WriteTypeArgumentsOfSignature */)); + if (allSignatures.length > 1) { + displayParts.push(ts.spacePart()); + displayParts.push(ts.punctuationPart(20 /* OpenParenToken */)); + displayParts.push(ts.operatorPart(38 /* PlusToken */)); + displayParts.push(ts.displayPart((allSignatures.length - 1).toString(), ts.SymbolDisplayPartKind.numericLiteral)); + displayParts.push(ts.spacePart()); + displayParts.push(ts.textPart(allSignatures.length === 2 ? "overload" : "overloads")); + displayParts.push(ts.punctuationPart(21 /* CloseParenToken */)); + } + var docComment = signature.getDocumentationComment(typeChecker); + documentation = docComment.length === 0 ? undefined : docComment; + tags = signature.getJsDocTags(); + } + function writeTypeParametersOfSymbol(symbol, enclosingDeclaration) { + var typeParameterParts = ts.mapToDisplayParts(function (writer) { + var params = typeChecker.symbolToTypeParameterDeclarations(symbol, enclosingDeclaration); + getPrinter().writeList(53776 /* TypeParameters */, params, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosingDeclaration)), writer); + }); + ts.addRange(displayParts, typeParameterParts); + } + } + SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind = getSymbolDisplayPartsDocumentationAndSymbolKind; + function isLocalVariableOrFunction(symbol) { + if (symbol.parent) { + return false; // This is exported symbol + } + return ts.forEach(symbol.declarations, function (declaration) { + // Function expressions are local + if (declaration.kind === 196 /* FunctionExpression */) { + return true; + } + if (declaration.kind !== 237 /* VariableDeclaration */ && declaration.kind !== 239 /* FunctionDeclaration */) { + return false; + } + // If the parent is not sourceFile or module block it is local variable + for (var parent = declaration.parent; !ts.isFunctionBlock(parent); parent = parent.parent) { + // Reached source file or module block + if (parent.kind === 279 /* SourceFile */ || parent.kind === 245 /* ModuleBlock */) { + return false; + } + } + // parent is in function block + return true; + }); + } + })(SymbolDisplay = ts.SymbolDisplay || (ts.SymbolDisplay = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + /* + * This function will compile source text from 'input' argument using specified compiler options. + * If not options are provided - it will use a set of default compiler options. + * Extra compiler options that will unconditionally be used by this function are: + * - isolatedModules = true + * - allowNonTsExtensions = true + * - noLib = true + * - noResolve = true + */ + function transpileModule(input, transpileOptions) { + var diagnostics = []; + var options = transpileOptions.compilerOptions ? fixupCompilerOptions(transpileOptions.compilerOptions, diagnostics) : ts.getDefaultCompilerOptions(); + options.isolatedModules = true; + // transpileModule does not write anything to disk so there is no need to verify that there are no conflicts between input and output paths. + options.suppressOutputPathCheck = true; + // Filename can be non-ts file. + options.allowNonTsExtensions = true; + // We are not returning a sourceFile for lib file when asked by the program, + // so pass --noLib to avoid reporting a file not found error. + options.noLib = true; + // Clear out other settings that would not be used in transpiling this module + options.lib = undefined; + options.types = undefined; + options.noEmit = undefined; + options.noEmitOnError = undefined; + options.paths = undefined; + options.rootDirs = undefined; + options.declaration = undefined; + options.composite = undefined; + options.declarationDir = undefined; + options.out = undefined; + options.outFile = undefined; + // We are not doing a full typecheck, we are not resolving the whole context, + // so pass --noResolve to avoid reporting missing file errors. + options.noResolve = true; + // if jsx is specified then treat file as .tsx + var inputFileName = transpileOptions.fileName || (options.jsx ? "module.tsx" : "module.ts"); + var sourceFile = ts.createSourceFile(inputFileName, input, options.target); // TODO: GH#18217 + if (transpileOptions.moduleName) { + sourceFile.moduleName = transpileOptions.moduleName; + } + if (transpileOptions.renamedDependencies) { + sourceFile.renamedDependencies = ts.createMapFromTemplate(transpileOptions.renamedDependencies); + } + var newLine = ts.getNewLineCharacter(options); + // Output + var outputText; + var sourceMapText; + // Create a compilerHost object to allow the compiler to read and write files + var compilerHost = { + getSourceFile: function (fileName) { return fileName === ts.normalizePath(inputFileName) ? sourceFile : undefined; }, + writeFile: function (name, text) { + if (ts.fileExtensionIs(name, ".map")) { + ts.Debug.assertEqual(sourceMapText, undefined, "Unexpected multiple source map outputs, file:", name); + sourceMapText = text; + } + else { + ts.Debug.assertEqual(outputText, undefined, "Unexpected multiple outputs, file:", name); + outputText = text; + } + }, + getDefaultLibFileName: function () { return "lib.d.ts"; }, + useCaseSensitiveFileNames: function () { return false; }, + getCanonicalFileName: function (fileName) { return fileName; }, + getCurrentDirectory: function () { return ""; }, + getNewLine: function () { return newLine; }, + fileExists: function (fileName) { return fileName === inputFileName; }, + readFile: function () { return ""; }, + directoryExists: function () { return true; }, + getDirectories: function () { return []; } + }; + var program = ts.createProgram([inputFileName], options, compilerHost); + if (transpileOptions.reportDiagnostics) { + ts.addRange(/*to*/ diagnostics, /*from*/ program.getSyntacticDiagnostics(sourceFile)); + ts.addRange(/*to*/ diagnostics, /*from*/ program.getOptionsDiagnostics()); + } + // Emit + program.emit(/*targetSourceFile*/ undefined, /*writeFile*/ undefined, /*cancellationToken*/ undefined, /*emitOnlyDtsFiles*/ undefined, transpileOptions.transformers); + if (outputText === undefined) + return ts.Debug.fail("Output generation failed"); + return { outputText: outputText, diagnostics: diagnostics, sourceMapText: sourceMapText }; + } + ts.transpileModule = transpileModule; + /* + * This is a shortcut function for transpileModule - it accepts transpileOptions as parameters and returns only outputText part of the result. + */ + function transpile(input, compilerOptions, fileName, diagnostics, moduleName) { + var output = transpileModule(input, { compilerOptions: compilerOptions, fileName: fileName, reportDiagnostics: !!diagnostics, moduleName: moduleName }); + // addRange correctly handles cases when wither 'from' or 'to' argument is missing + ts.addRange(diagnostics, output.diagnostics); + return output.outputText; + } + ts.transpile = transpile; + var commandLineOptionsStringToEnum; + /** JS users may pass in string values for enum compiler options (such as ModuleKind), so convert. */ + /*@internal*/ + function fixupCompilerOptions(options, diagnostics) { + // Lazily create this value to fix module loading errors. + commandLineOptionsStringToEnum = commandLineOptionsStringToEnum || ts.filter(ts.optionDeclarations, function (o) { + return typeof o.type === "object" && !ts.forEachEntry(o.type, function (v) { return typeof v !== "number"; }); + }); + options = ts.cloneCompilerOptions(options); + var _loop_16 = function (opt) { + if (!ts.hasProperty(options, opt.name)) { + return "continue"; + } + var value = options[opt.name]; + // Value should be a key of opt.type + if (ts.isString(value)) { + // If value is not a string, this will fail + options[opt.name] = ts.parseCustomTypeOption(opt, value, diagnostics); + } + else { + if (!ts.forEachEntry(opt.type, function (v) { return v === value; })) { + // Supplied value isn't a valid enum value. + diagnostics.push(ts.createCompilerDiagnosticForInvalidCustomType(opt)); + } + } + }; + for (var _i = 0, commandLineOptionsStringToEnum_1 = commandLineOptionsStringToEnum; _i < commandLineOptionsStringToEnum_1.length; _i++) { + var opt = commandLineOptionsStringToEnum_1[_i]; + _loop_16(opt); + } + return options; + } + ts.fixupCompilerOptions = fixupCompilerOptions; +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var formatting; + (function (formatting) { + var FormattingRequestKind; + (function (FormattingRequestKind) { + FormattingRequestKind[FormattingRequestKind["FormatDocument"] = 0] = "FormatDocument"; + FormattingRequestKind[FormattingRequestKind["FormatSelection"] = 1] = "FormatSelection"; + FormattingRequestKind[FormattingRequestKind["FormatOnEnter"] = 2] = "FormatOnEnter"; + FormattingRequestKind[FormattingRequestKind["FormatOnSemicolon"] = 3] = "FormatOnSemicolon"; + FormattingRequestKind[FormattingRequestKind["FormatOnOpeningCurlyBrace"] = 4] = "FormatOnOpeningCurlyBrace"; + FormattingRequestKind[FormattingRequestKind["FormatOnClosingCurlyBrace"] = 5] = "FormatOnClosingCurlyBrace"; + })(FormattingRequestKind = formatting.FormattingRequestKind || (formatting.FormattingRequestKind = {})); + var FormattingContext = /** @class */ (function () { + function FormattingContext(sourceFile, formattingRequestKind, options) { + this.sourceFile = sourceFile; + this.formattingRequestKind = formattingRequestKind; + this.options = options; + } + FormattingContext.prototype.updateContext = function (currentRange, currentTokenParent, nextRange, nextTokenParent, commonParent) { + this.currentTokenSpan = ts.Debug.assertDefined(currentRange); + this.currentTokenParent = ts.Debug.assertDefined(currentTokenParent); + this.nextTokenSpan = ts.Debug.assertDefined(nextRange); + this.nextTokenParent = ts.Debug.assertDefined(nextTokenParent); + this.contextNode = ts.Debug.assertDefined(commonParent); + // drop cached results + this.contextNodeAllOnSameLine = undefined; + this.nextNodeAllOnSameLine = undefined; + this.tokensAreOnSameLine = undefined; + this.contextNodeBlockIsOnOneLine = undefined; + this.nextNodeBlockIsOnOneLine = undefined; + }; + FormattingContext.prototype.ContextNodeAllOnSameLine = function () { + if (this.contextNodeAllOnSameLine === undefined) { + this.contextNodeAllOnSameLine = this.NodeIsOnOneLine(this.contextNode); + } + return this.contextNodeAllOnSameLine; + }; + FormattingContext.prototype.NextNodeAllOnSameLine = function () { + if (this.nextNodeAllOnSameLine === undefined) { + this.nextNodeAllOnSameLine = this.NodeIsOnOneLine(this.nextTokenParent); + } + return this.nextNodeAllOnSameLine; + }; + FormattingContext.prototype.TokensAreOnSameLine = function () { + if (this.tokensAreOnSameLine === undefined) { + var startLine = this.sourceFile.getLineAndCharacterOfPosition(this.currentTokenSpan.pos).line; + var endLine = this.sourceFile.getLineAndCharacterOfPosition(this.nextTokenSpan.pos).line; + this.tokensAreOnSameLine = (startLine === endLine); + } + return this.tokensAreOnSameLine; + }; + FormattingContext.prototype.ContextNodeBlockIsOnOneLine = function () { + if (this.contextNodeBlockIsOnOneLine === undefined) { + this.contextNodeBlockIsOnOneLine = this.BlockIsOnOneLine(this.contextNode); + } + return this.contextNodeBlockIsOnOneLine; + }; + FormattingContext.prototype.NextNodeBlockIsOnOneLine = function () { + if (this.nextNodeBlockIsOnOneLine === undefined) { + this.nextNodeBlockIsOnOneLine = this.BlockIsOnOneLine(this.nextTokenParent); + } + return this.nextNodeBlockIsOnOneLine; + }; + FormattingContext.prototype.NodeIsOnOneLine = function (node) { + var startLine = this.sourceFile.getLineAndCharacterOfPosition(node.getStart(this.sourceFile)).line; + var endLine = this.sourceFile.getLineAndCharacterOfPosition(node.getEnd()).line; + return startLine === endLine; + }; + FormattingContext.prototype.BlockIsOnOneLine = function (node) { + var openBrace = ts.findChildOfKind(node, 18 /* OpenBraceToken */, this.sourceFile); + var closeBrace = ts.findChildOfKind(node, 19 /* CloseBraceToken */, this.sourceFile); + if (openBrace && closeBrace) { + var startLine = this.sourceFile.getLineAndCharacterOfPosition(openBrace.getEnd()).line; + var endLine = this.sourceFile.getLineAndCharacterOfPosition(closeBrace.getStart(this.sourceFile)).line; + return startLine === endLine; + } + return false; + }; + return FormattingContext; + }()); + formatting.FormattingContext = FormattingContext; + })(formatting = ts.formatting || (ts.formatting = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var formatting; + (function (formatting) { + var standardScanner = ts.createScanner(6 /* Latest */, /*skipTrivia*/ false, 0 /* Standard */); + var jsxScanner = ts.createScanner(6 /* Latest */, /*skipTrivia*/ false, 1 /* JSX */); + var ScanAction; + (function (ScanAction) { + ScanAction[ScanAction["Scan"] = 0] = "Scan"; + ScanAction[ScanAction["RescanGreaterThanToken"] = 1] = "RescanGreaterThanToken"; + ScanAction[ScanAction["RescanSlashToken"] = 2] = "RescanSlashToken"; + ScanAction[ScanAction["RescanTemplateToken"] = 3] = "RescanTemplateToken"; + ScanAction[ScanAction["RescanJsxIdentifier"] = 4] = "RescanJsxIdentifier"; + ScanAction[ScanAction["RescanJsxText"] = 5] = "RescanJsxText"; + })(ScanAction || (ScanAction = {})); + function getFormattingScanner(text, languageVariant, startPos, endPos, cb) { + var scanner = languageVariant === 1 /* JSX */ ? jsxScanner : standardScanner; + scanner.setText(text); + scanner.setTextPos(startPos); + var wasNewLine = true; + var leadingTrivia; + var trailingTrivia; + var savedPos; + var lastScanAction; + var lastTokenInfo; + var res = cb({ + advance: advance, + readTokenInfo: readTokenInfo, + isOnToken: isOnToken, + getCurrentLeadingTrivia: function () { return leadingTrivia; }, + lastTrailingTriviaWasNewLine: function () { return wasNewLine; }, + skipToEndOf: skipToEndOf, + }); + lastTokenInfo = undefined; + scanner.setText(undefined); + return res; + function advance() { + lastTokenInfo = undefined; + var isStarted = scanner.getStartPos() !== startPos; + if (isStarted) { + wasNewLine = !!trailingTrivia && ts.last(trailingTrivia).kind === 4 /* NewLineTrivia */; + } + else { + scanner.scan(); + } + leadingTrivia = undefined; + trailingTrivia = undefined; + var pos = scanner.getStartPos(); + // Read leading trivia and token + while (pos < endPos) { + var t = scanner.getToken(); + if (!ts.isTrivia(t)) { + break; + } + // consume leading trivia + scanner.scan(); + var item = { + pos: pos, + end: scanner.getStartPos(), + kind: t + }; + pos = scanner.getStartPos(); + leadingTrivia = ts.append(leadingTrivia, item); + } + savedPos = scanner.getStartPos(); + } + function shouldRescanGreaterThanToken(node) { + switch (node.kind) { + case 32 /* GreaterThanEqualsToken */: + case 67 /* GreaterThanGreaterThanEqualsToken */: + case 68 /* GreaterThanGreaterThanGreaterThanEqualsToken */: + case 48 /* GreaterThanGreaterThanGreaterThanToken */: + case 47 /* GreaterThanGreaterThanToken */: + return true; + } + return false; + } + function shouldRescanJsxIdentifier(node) { + if (node.parent) { + switch (node.parent.kind) { + case 267 /* JsxAttribute */: + case 262 /* JsxOpeningElement */: + case 263 /* JsxClosingElement */: + case 261 /* JsxSelfClosingElement */: + // May parse an identifier like `module-layout`; that will be scanned as a keyword at first, but we should parse the whole thing to get an identifier. + return ts.isKeyword(node.kind) || node.kind === 72 /* Identifier */; + } + } + return false; + } + function shouldRescanJsxText(node) { + return node.kind === 11 /* JsxText */; + } + function shouldRescanSlashToken(container) { + return container.kind === 13 /* RegularExpressionLiteral */; + } + function shouldRescanTemplateToken(container) { + return container.kind === 16 /* TemplateMiddle */ || + container.kind === 17 /* TemplateTail */; + } + function startsWithSlashToken(t) { + return t === 42 /* SlashToken */ || t === 64 /* SlashEqualsToken */; + } + function readTokenInfo(n) { + ts.Debug.assert(isOnToken()); + // normally scanner returns the smallest available token + // check the kind of context node to determine if scanner should have more greedy behavior and consume more text. + var expectedScanAction = shouldRescanGreaterThanToken(n) + ? 1 /* RescanGreaterThanToken */ + : shouldRescanSlashToken(n) + ? 2 /* RescanSlashToken */ + : shouldRescanTemplateToken(n) + ? 3 /* RescanTemplateToken */ + : shouldRescanJsxIdentifier(n) + ? 4 /* RescanJsxIdentifier */ + : shouldRescanJsxText(n) + ? 5 /* RescanJsxText */ + : 0 /* Scan */; + if (lastTokenInfo && expectedScanAction === lastScanAction) { + // readTokenInfo was called before with the same expected scan action. + // No need to re-scan text, return existing 'lastTokenInfo' + // it is ok to call fixTokenKind here since it does not affect + // what portion of text is consumed. In contrast rescanning can change it, + // i.e. for '>=' when originally scanner eats just one character + // and rescanning forces it to consume more. + return fixTokenKind(lastTokenInfo, n); + } + if (scanner.getStartPos() !== savedPos) { + ts.Debug.assert(lastTokenInfo !== undefined); + // readTokenInfo was called before but scan action differs - rescan text + scanner.setTextPos(savedPos); + scanner.scan(); + } + var currentToken = getNextToken(n, expectedScanAction); + var token = { + pos: scanner.getStartPos(), + end: scanner.getTextPos(), + kind: currentToken + }; + // consume trailing trivia + if (trailingTrivia) { + trailingTrivia = undefined; + } + while (scanner.getStartPos() < endPos) { + currentToken = scanner.scan(); + if (!ts.isTrivia(currentToken)) { + break; + } + var trivia = { + pos: scanner.getStartPos(), + end: scanner.getTextPos(), + kind: currentToken + }; + if (!trailingTrivia) { + trailingTrivia = []; + } + trailingTrivia.push(trivia); + if (currentToken === 4 /* NewLineTrivia */) { + // move past new line + scanner.scan(); + break; + } + } + lastTokenInfo = { leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia, token: token }; + return fixTokenKind(lastTokenInfo, n); + } + function getNextToken(n, expectedScanAction) { + var token = scanner.getToken(); + lastScanAction = 0 /* Scan */; + switch (expectedScanAction) { + case 1 /* RescanGreaterThanToken */: + if (token === 30 /* GreaterThanToken */) { + lastScanAction = 1 /* RescanGreaterThanToken */; + var newToken = scanner.reScanGreaterToken(); + ts.Debug.assert(n.kind === newToken); + return newToken; + } + break; + case 2 /* RescanSlashToken */: + if (startsWithSlashToken(token)) { + lastScanAction = 2 /* RescanSlashToken */; + var newToken = scanner.reScanSlashToken(); + ts.Debug.assert(n.kind === newToken); + return newToken; + } + break; + case 3 /* RescanTemplateToken */: + if (token === 19 /* CloseBraceToken */) { + lastScanAction = 3 /* RescanTemplateToken */; + return scanner.reScanTemplateToken(); + } + break; + case 4 /* RescanJsxIdentifier */: + lastScanAction = 4 /* RescanJsxIdentifier */; + return scanner.scanJsxIdentifier(); + case 5 /* RescanJsxText */: + lastScanAction = 5 /* RescanJsxText */; + return scanner.reScanJsxToken(); + case 0 /* Scan */: + break; + default: + ts.Debug.assertNever(expectedScanAction); + } + return token; + } + function isOnToken() { + var current = lastTokenInfo ? lastTokenInfo.token.kind : scanner.getToken(); + var startPos = lastTokenInfo ? lastTokenInfo.token.pos : scanner.getStartPos(); + return startPos < endPos && current !== 1 /* EndOfFileToken */ && !ts.isTrivia(current); + } + // when containing node in the tree is token + // but its kind differs from the kind that was returned by the scanner, + // then kind needs to be fixed. This might happen in cases + // when parser interprets token differently, i.e keyword treated as identifier + function fixTokenKind(tokenInfo, container) { + if (ts.isToken(container) && tokenInfo.token.kind !== container.kind) { + tokenInfo.token.kind = container.kind; + } + return tokenInfo; + } + function skipToEndOf(node) { + scanner.setTextPos(node.end); + savedPos = scanner.getStartPos(); + lastScanAction = undefined; + lastTokenInfo = undefined; + wasNewLine = false; + leadingTrivia = undefined; + trailingTrivia = undefined; + } + } + formatting.getFormattingScanner = getFormattingScanner; + })(formatting = ts.formatting || (ts.formatting = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var formatting; + (function (formatting) { + formatting.anyContext = ts.emptyArray; + var RuleAction; + (function (RuleAction) { + RuleAction[RuleAction["Ignore"] = 1] = "Ignore"; + RuleAction[RuleAction["Space"] = 2] = "Space"; + RuleAction[RuleAction["NewLine"] = 4] = "NewLine"; + RuleAction[RuleAction["Delete"] = 8] = "Delete"; + })(RuleAction = formatting.RuleAction || (formatting.RuleAction = {})); + var RuleFlags; + (function (RuleFlags) { + RuleFlags[RuleFlags["None"] = 0] = "None"; + RuleFlags[RuleFlags["CanDeleteNewLines"] = 1] = "CanDeleteNewLines"; + })(RuleFlags = formatting.RuleFlags || (formatting.RuleFlags = {})); + })(formatting = ts.formatting || (ts.formatting = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var formatting; + (function (formatting) { + function getAllRules() { + var allTokens = []; + for (var token = 0 /* FirstToken */; token <= 147 /* LastToken */; token++) { + allTokens.push(token); + } + function anyTokenExcept() { + var tokens = []; + for (var _i = 0; _i < arguments.length; _i++) { + tokens[_i] = arguments[_i]; + } + return { tokens: allTokens.filter(function (t) { return !tokens.some(function (t2) { return t2 === t; }); }), isSpecific: false }; + } + var anyToken = { tokens: allTokens, isSpecific: false }; + var anyTokenIncludingMultilineComments = tokenRangeFrom(allTokens.concat([3 /* MultiLineCommentTrivia */])); + var keywords = tokenRangeFromRange(73 /* FirstKeyword */, 147 /* LastKeyword */); + var binaryOperators = tokenRangeFromRange(28 /* FirstBinaryOperator */, 71 /* LastBinaryOperator */); + var binaryKeywordOperators = [93 /* InKeyword */, 94 /* InstanceOfKeyword */, 147 /* OfKeyword */, 119 /* AsKeyword */, 128 /* IsKeyword */]; + var unaryPrefixOperators = [44 /* PlusPlusToken */, 45 /* MinusMinusToken */, 53 /* TildeToken */, 52 /* ExclamationToken */]; + var unaryPrefixExpressions = [ + 8 /* NumericLiteral */, 9 /* BigIntLiteral */, 72 /* Identifier */, 20 /* OpenParenToken */, + 22 /* OpenBracketToken */, 18 /* OpenBraceToken */, 100 /* ThisKeyword */, 95 /* NewKeyword */ + ]; + var unaryPreincrementExpressions = [72 /* Identifier */, 20 /* OpenParenToken */, 100 /* ThisKeyword */, 95 /* NewKeyword */]; + var unaryPostincrementExpressions = [72 /* Identifier */, 21 /* CloseParenToken */, 23 /* CloseBracketToken */, 95 /* NewKeyword */]; + var unaryPredecrementExpressions = [72 /* Identifier */, 20 /* OpenParenToken */, 100 /* ThisKeyword */, 95 /* NewKeyword */]; + var unaryPostdecrementExpressions = [72 /* Identifier */, 21 /* CloseParenToken */, 23 /* CloseBracketToken */, 95 /* NewKeyword */]; + var comments = [2 /* SingleLineCommentTrivia */, 3 /* MultiLineCommentTrivia */]; + var typeNames = [72 /* Identifier */].concat(ts.typeKeywords); + // Place a space before open brace in a function declaration + // TypeScript: Function can have return types, which can be made of tons of different token kinds + var functionOpenBraceLeftTokenRange = anyTokenIncludingMultilineComments; + // Place a space before open brace in a TypeScript declaration that has braces as children (class, module, enum, etc) + var typeScriptOpenBraceLeftTokenRange = tokenRangeFrom([72 /* Identifier */, 3 /* MultiLineCommentTrivia */, 76 /* ClassKeyword */, 85 /* ExportKeyword */, 92 /* ImportKeyword */]); + // Place a space before open brace in a control flow construct + var controlOpenBraceLeftTokenRange = tokenRangeFrom([21 /* CloseParenToken */, 3 /* MultiLineCommentTrivia */, 82 /* DoKeyword */, 103 /* TryKeyword */, 88 /* FinallyKeyword */, 83 /* ElseKeyword */]); + // These rules are higher in priority than user-configurable + var highPriorityCommonRules = [ + // Leave comments alone + rule("IgnoreBeforeComment", anyToken, comments, formatting.anyContext, 1 /* Ignore */), + rule("IgnoreAfterLineComment", 2 /* SingleLineCommentTrivia */, anyToken, formatting.anyContext, 1 /* Ignore */), + rule("NotSpaceBeforeColon", anyToken, 57 /* ColonToken */, [isNonJsxSameLineTokenContext, isNotBinaryOpContext, isNotTypeAnnotationContext], 8 /* Delete */), + rule("SpaceAfterColon", 57 /* ColonToken */, anyToken, [isNonJsxSameLineTokenContext, isNotBinaryOpContext], 2 /* Space */), + rule("NoSpaceBeforeQuestionMark", anyToken, 56 /* QuestionToken */, [isNonJsxSameLineTokenContext, isNotBinaryOpContext], 8 /* Delete */), + // insert space after '?' only when it is used in conditional operator + rule("SpaceAfterQuestionMarkInConditionalOperator", 56 /* QuestionToken */, anyToken, [isNonJsxSameLineTokenContext, isConditionalOperatorContext], 2 /* Space */), + // in other cases there should be no space between '?' and next token + rule("NoSpaceAfterQuestionMark", 56 /* QuestionToken */, anyToken, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceBeforeDot", anyToken, 24 /* DotToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceAfterDot", 24 /* DotToken */, anyToken, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceBetweenImportParenInImportType", 92 /* ImportKeyword */, 20 /* OpenParenToken */, [isNonJsxSameLineTokenContext, isImportTypeContext], 8 /* Delete */), + // Special handling of unary operators. + // Prefix operators generally shouldn't have a space between + // them and their target unary expression. + rule("NoSpaceAfterUnaryPrefixOperator", unaryPrefixOperators, unaryPrefixExpressions, [isNonJsxSameLineTokenContext, isNotBinaryOpContext], 8 /* Delete */), + rule("NoSpaceAfterUnaryPreincrementOperator", 44 /* PlusPlusToken */, unaryPreincrementExpressions, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceAfterUnaryPredecrementOperator", 45 /* MinusMinusToken */, unaryPredecrementExpressions, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceBeforeUnaryPostincrementOperator", unaryPostincrementExpressions, 44 /* PlusPlusToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceBeforeUnaryPostdecrementOperator", unaryPostdecrementExpressions, 45 /* MinusMinusToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + // More unary operator special-casing. + // DevDiv 181814: Be careful when removing leading whitespace + // around unary operators. Examples: + // 1 - -2 --X--> 1--2 + // a + ++b --X--> a+++b + rule("SpaceAfterPostincrementWhenFollowedByAdd", 44 /* PlusPlusToken */, 38 /* PlusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), + rule("SpaceAfterAddWhenFollowedByUnaryPlus", 38 /* PlusToken */, 38 /* PlusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), + rule("SpaceAfterAddWhenFollowedByPreincrement", 38 /* PlusToken */, 44 /* PlusPlusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), + rule("SpaceAfterPostdecrementWhenFollowedBySubtract", 45 /* MinusMinusToken */, 39 /* MinusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), + rule("SpaceAfterSubtractWhenFollowedByUnaryMinus", 39 /* MinusToken */, 39 /* MinusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), + rule("SpaceAfterSubtractWhenFollowedByPredecrement", 39 /* MinusToken */, 45 /* MinusMinusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), + rule("NoSpaceAfterCloseBrace", 19 /* CloseBraceToken */, [27 /* CommaToken */, 26 /* SemicolonToken */], [isNonJsxSameLineTokenContext], 8 /* Delete */), + // For functions and control block place } on a new line [multi-line rule] + rule("NewLineBeforeCloseBraceInBlockContext", anyTokenIncludingMultilineComments, 19 /* CloseBraceToken */, [isMultilineBlockContext], 4 /* NewLine */), + // Space/new line after }. + rule("SpaceAfterCloseBrace", 19 /* CloseBraceToken */, anyTokenExcept(21 /* CloseParenToken */), [isNonJsxSameLineTokenContext, isAfterCodeBlockContext], 2 /* Space */), + // Special case for (}, else) and (}, while) since else & while tokens are not part of the tree which makes SpaceAfterCloseBrace rule not applied + // Also should not apply to }) + rule("SpaceBetweenCloseBraceAndElse", 19 /* CloseBraceToken */, 83 /* ElseKeyword */, [isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceBetweenCloseBraceAndWhile", 19 /* CloseBraceToken */, 107 /* WhileKeyword */, [isNonJsxSameLineTokenContext], 2 /* Space */), + rule("NoSpaceBetweenEmptyBraceBrackets", 18 /* OpenBraceToken */, 19 /* CloseBraceToken */, [isNonJsxSameLineTokenContext, isObjectContext], 8 /* Delete */), + // Add a space after control dec context if the next character is an open bracket ex: 'if (false)[a, b] = [1, 2];' -> 'if (false) [a, b] = [1, 2];' + rule("SpaceAfterConditionalClosingParen", 21 /* CloseParenToken */, 22 /* OpenBracketToken */, [isControlDeclContext], 2 /* Space */), + rule("NoSpaceBetweenFunctionKeywordAndStar", 90 /* FunctionKeyword */, 40 /* AsteriskToken */, [isFunctionDeclarationOrFunctionExpressionContext], 8 /* Delete */), + rule("SpaceAfterStarInGeneratorDeclaration", 40 /* AsteriskToken */, [72 /* Identifier */, 20 /* OpenParenToken */], [isFunctionDeclarationOrFunctionExpressionContext], 2 /* Space */), + rule("SpaceAfterFunctionInFuncDecl", 90 /* FunctionKeyword */, anyToken, [isFunctionDeclContext], 2 /* Space */), + // Insert new line after { and before } in multi-line contexts. + rule("NewLineAfterOpenBraceInBlockContext", 18 /* OpenBraceToken */, anyToken, [isMultilineBlockContext], 4 /* NewLine */), + // For get/set members, we check for (identifier,identifier) since get/set don't have tokens and they are represented as just an identifier token. + // Though, we do extra check on the context to make sure we are dealing with get/set node. Example: + // get x() {} + // set x(val) {} + rule("SpaceAfterGetSetInMember", [126 /* GetKeyword */, 137 /* SetKeyword */], 72 /* Identifier */, [isFunctionDeclContext], 2 /* Space */), + rule("NoSpaceBetweenYieldKeywordAndStar", 117 /* YieldKeyword */, 40 /* AsteriskToken */, [isNonJsxSameLineTokenContext, isYieldOrYieldStarWithOperand], 8 /* Delete */), + rule("SpaceBetweenYieldOrYieldStarAndOperand", [117 /* YieldKeyword */, 40 /* AsteriskToken */], anyToken, [isNonJsxSameLineTokenContext, isYieldOrYieldStarWithOperand], 2 /* Space */), + rule("NoSpaceBetweenReturnAndSemicolon", 97 /* ReturnKeyword */, 26 /* SemicolonToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("SpaceAfterCertainKeywords", [105 /* VarKeyword */, 101 /* ThrowKeyword */, 95 /* NewKeyword */, 81 /* DeleteKeyword */, 97 /* ReturnKeyword */, 104 /* TypeOfKeyword */, 122 /* AwaitKeyword */], anyToken, [isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceAfterLetConstInVariableDeclaration", [111 /* LetKeyword */, 77 /* ConstKeyword */], anyToken, [isNonJsxSameLineTokenContext, isStartOfVariableDeclarationList], 2 /* Space */), + rule("NoSpaceBeforeOpenParenInFuncCall", anyToken, 20 /* OpenParenToken */, [isNonJsxSameLineTokenContext, isFunctionCallOrNewContext, isPreviousTokenNotComma], 8 /* Delete */), + // Special case for binary operators (that are keywords). For these we have to add a space and shouldn't follow any user options. + rule("SpaceBeforeBinaryKeywordOperator", anyToken, binaryKeywordOperators, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), + rule("SpaceAfterBinaryKeywordOperator", binaryKeywordOperators, anyToken, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), + rule("SpaceAfterVoidOperator", 106 /* VoidKeyword */, anyToken, [isNonJsxSameLineTokenContext, isVoidOpContext], 2 /* Space */), + // Async-await + rule("SpaceBetweenAsyncAndOpenParen", 121 /* AsyncKeyword */, 20 /* OpenParenToken */, [isArrowFunctionContext, isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceBetweenAsyncAndFunctionKeyword", 121 /* AsyncKeyword */, 90 /* FunctionKeyword */, [isNonJsxSameLineTokenContext], 2 /* Space */), + // Template string + rule("NoSpaceBetweenTagAndTemplateString", [72 /* Identifier */, 21 /* CloseParenToken */], [14 /* NoSubstitutionTemplateLiteral */, 15 /* TemplateHead */], [isNonJsxSameLineTokenContext], 8 /* Delete */), + // JSX opening elements + rule("SpaceBeforeJsxAttribute", anyToken, 72 /* Identifier */, [isNextTokenParentJsxAttribute, isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceBeforeSlashInJsxOpeningElement", anyToken, 42 /* SlashToken */, [isJsxSelfClosingElementContext, isNonJsxSameLineTokenContext], 2 /* Space */), + rule("NoSpaceBeforeGreaterThanTokenInJsxOpeningElement", 42 /* SlashToken */, 30 /* GreaterThanToken */, [isJsxSelfClosingElementContext, isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceBeforeEqualInJsxAttribute", anyToken, 59 /* EqualsToken */, [isJsxAttributeContext, isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceAfterEqualInJsxAttribute", 59 /* EqualsToken */, anyToken, [isJsxAttributeContext, isNonJsxSameLineTokenContext], 8 /* Delete */), + // TypeScript-specific rules + // Use of module as a function call. e.g.: import m2 = module("m2"); + rule("NoSpaceAfterModuleImport", [130 /* ModuleKeyword */, 134 /* RequireKeyword */], 20 /* OpenParenToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + // Add a space around certain TypeScript keywords + rule("SpaceAfterCertainTypeScriptKeywords", [ + 118 /* AbstractKeyword */, + 76 /* ClassKeyword */, + 125 /* DeclareKeyword */, + 80 /* DefaultKeyword */, + 84 /* EnumKeyword */, + 85 /* ExportKeyword */, + 86 /* ExtendsKeyword */, + 126 /* GetKeyword */, + 109 /* ImplementsKeyword */, + 92 /* ImportKeyword */, + 110 /* InterfaceKeyword */, + 130 /* ModuleKeyword */, + 131 /* NamespaceKeyword */, + 113 /* PrivateKeyword */, + 115 /* PublicKeyword */, + 114 /* ProtectedKeyword */, + 133 /* ReadonlyKeyword */, + 137 /* SetKeyword */, + 116 /* StaticKeyword */, + 140 /* TypeKeyword */, + 144 /* FromKeyword */, + 129 /* KeyOfKeyword */, + 127 /* InferKeyword */, + ], anyToken, [isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceBeforeCertainTypeScriptKeywords", anyToken, [86 /* ExtendsKeyword */, 109 /* ImplementsKeyword */, 144 /* FromKeyword */], [isNonJsxSameLineTokenContext], 2 /* Space */), + // Treat string literals in module names as identifiers, and add a space between the literal and the opening Brace braces, e.g.: module "m2" { + rule("SpaceAfterModuleName", 10 /* StringLiteral */, 18 /* OpenBraceToken */, [isModuleDeclContext], 2 /* Space */), + // Lambda expressions + rule("SpaceBeforeArrow", anyToken, 37 /* EqualsGreaterThanToken */, [isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceAfterArrow", 37 /* EqualsGreaterThanToken */, anyToken, [isNonJsxSameLineTokenContext], 2 /* Space */), + // Optional parameters and let args + rule("NoSpaceAfterEllipsis", 25 /* DotDotDotToken */, 72 /* Identifier */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceAfterOptionalParameters", 56 /* QuestionToken */, [21 /* CloseParenToken */, 27 /* CommaToken */], [isNonJsxSameLineTokenContext, isNotBinaryOpContext], 8 /* Delete */), + // Remove spaces in empty interface literals. e.g.: x: {} + rule("NoSpaceBetweenEmptyInterfaceBraceBrackets", 18 /* OpenBraceToken */, 19 /* CloseBraceToken */, [isNonJsxSameLineTokenContext, isObjectTypeContext], 8 /* Delete */), + // generics and type assertions + rule("NoSpaceBeforeOpenAngularBracket", typeNames, 28 /* LessThanToken */, [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext], 8 /* Delete */), + rule("NoSpaceBetweenCloseParenAndAngularBracket", 21 /* CloseParenToken */, 28 /* LessThanToken */, [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext], 8 /* Delete */), + rule("NoSpaceAfterOpenAngularBracket", 28 /* LessThanToken */, anyToken, [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext], 8 /* Delete */), + rule("NoSpaceBeforeCloseAngularBracket", anyToken, 30 /* GreaterThanToken */, [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext], 8 /* Delete */), + rule("NoSpaceAfterCloseAngularBracket", 30 /* GreaterThanToken */, [20 /* OpenParenToken */, 22 /* OpenBracketToken */, 30 /* GreaterThanToken */, 27 /* CommaToken */], [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext, isNotFunctionDeclContext /*To prevent an interference with the SpaceBeforeOpenParenInFuncDecl rule*/], 8 /* Delete */), + // decorators + rule("SpaceBeforeAt", [21 /* CloseParenToken */, 72 /* Identifier */], 58 /* AtToken */, [isNonJsxSameLineTokenContext], 2 /* Space */), + rule("NoSpaceAfterAt", 58 /* AtToken */, anyToken, [isNonJsxSameLineTokenContext], 8 /* Delete */), + // Insert space after @ in decorator + rule("SpaceAfterDecorator", anyToken, [ + 118 /* AbstractKeyword */, + 72 /* Identifier */, + 85 /* ExportKeyword */, + 80 /* DefaultKeyword */, + 76 /* ClassKeyword */, + 116 /* StaticKeyword */, + 115 /* PublicKeyword */, + 113 /* PrivateKeyword */, + 114 /* ProtectedKeyword */, + 126 /* GetKeyword */, + 137 /* SetKeyword */, + 22 /* OpenBracketToken */, + 40 /* AsteriskToken */, + ], [isEndOfDecoratorContextOnSameLine], 2 /* Space */), + rule("NoSpaceBeforeNonNullAssertionOperator", anyToken, 52 /* ExclamationToken */, [isNonJsxSameLineTokenContext, isNonNullAssertionContext], 8 /* Delete */), + rule("NoSpaceAfterNewKeywordOnConstructorSignature", 95 /* NewKeyword */, 20 /* OpenParenToken */, [isNonJsxSameLineTokenContext, isConstructorSignatureContext], 8 /* Delete */), + ]; + // These rules are applied after high priority + var userConfigurableRules = [ + // Treat constructor as an identifier in a function declaration, and remove spaces between constructor and following left parentheses + rule("SpaceAfterConstructor", 124 /* ConstructorKeyword */, 20 /* OpenParenToken */, [isOptionEnabled("insertSpaceAfterConstructor"), isNonJsxSameLineTokenContext], 2 /* Space */), + rule("NoSpaceAfterConstructor", 124 /* ConstructorKeyword */, 20 /* OpenParenToken */, [isOptionDisabledOrUndefined("insertSpaceAfterConstructor"), isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("SpaceAfterComma", 27 /* CommaToken */, anyToken, [isOptionEnabled("insertSpaceAfterCommaDelimiter"), isNonJsxSameLineTokenContext, isNonJsxElementOrFragmentContext, isNextTokenNotCloseBracket], 2 /* Space */), + rule("NoSpaceAfterComma", 27 /* CommaToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterCommaDelimiter"), isNonJsxSameLineTokenContext, isNonJsxElementOrFragmentContext], 8 /* Delete */), + // Insert space after function keyword for anonymous functions + rule("SpaceAfterAnonymousFunctionKeyword", 90 /* FunctionKeyword */, 20 /* OpenParenToken */, [isOptionEnabled("insertSpaceAfterFunctionKeywordForAnonymousFunctions"), isFunctionDeclContext], 2 /* Space */), + rule("NoSpaceAfterAnonymousFunctionKeyword", 90 /* FunctionKeyword */, 20 /* OpenParenToken */, [isOptionDisabledOrUndefined("insertSpaceAfterFunctionKeywordForAnonymousFunctions"), isFunctionDeclContext], 8 /* Delete */), + // Insert space after keywords in control flow statements + rule("SpaceAfterKeywordInControl", keywords, 20 /* OpenParenToken */, [isOptionEnabled("insertSpaceAfterKeywordsInControlFlowStatements"), isControlDeclContext], 2 /* Space */), + rule("NoSpaceAfterKeywordInControl", keywords, 20 /* OpenParenToken */, [isOptionDisabledOrUndefined("insertSpaceAfterKeywordsInControlFlowStatements"), isControlDeclContext], 8 /* Delete */), + // Insert space after opening and before closing nonempty parenthesis + rule("SpaceAfterOpenParen", 20 /* OpenParenToken */, anyToken, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceBeforeCloseParen", anyToken, 21 /* CloseParenToken */, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceBetweenOpenParens", 20 /* OpenParenToken */, 20 /* OpenParenToken */, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext], 2 /* Space */), + rule("NoSpaceBetweenParens", 20 /* OpenParenToken */, 21 /* CloseParenToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceAfterOpenParen", 20 /* OpenParenToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceBeforeCloseParen", anyToken, 21 /* CloseParenToken */, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext], 8 /* Delete */), + // Insert space after opening and before closing nonempty brackets + rule("SpaceAfterOpenBracket", 22 /* OpenBracketToken */, anyToken, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceBeforeCloseBracket", anyToken, 23 /* CloseBracketToken */, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), isNonJsxSameLineTokenContext], 2 /* Space */), + rule("NoSpaceBetweenBrackets", 22 /* OpenBracketToken */, 23 /* CloseBracketToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceAfterOpenBracket", 22 /* OpenBracketToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceBeforeCloseBracket", anyToken, 23 /* CloseBracketToken */, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), isNonJsxSameLineTokenContext], 8 /* Delete */), + // Insert a space after { and before } in single-line contexts, but remove space from empty object literals {}. + rule("SpaceAfterOpenBrace", 18 /* OpenBraceToken */, anyToken, [isOptionEnabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), isBraceWrappedContext], 2 /* Space */), + rule("SpaceBeforeCloseBrace", anyToken, 19 /* CloseBraceToken */, [isOptionEnabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), isBraceWrappedContext], 2 /* Space */), + rule("NoSpaceBetweenEmptyBraceBrackets", 18 /* OpenBraceToken */, 19 /* CloseBraceToken */, [isNonJsxSameLineTokenContext, isObjectContext], 8 /* Delete */), + rule("NoSpaceAfterOpenBrace", 18 /* OpenBraceToken */, anyToken, [isOptionDisabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceBeforeCloseBrace", anyToken, 19 /* CloseBraceToken */, [isOptionDisabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), isNonJsxSameLineTokenContext], 8 /* Delete */), + // Insert space after opening and before closing template string braces + rule("SpaceAfterTemplateHeadAndMiddle", [15 /* TemplateHead */, 16 /* TemplateMiddle */], anyToken, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceBeforeTemplateMiddleAndTail", anyToken, [16 /* TemplateMiddle */, 17 /* TemplateTail */], [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), isNonJsxSameLineTokenContext], 2 /* Space */), + rule("NoSpaceAfterTemplateHeadAndMiddle", [15 /* TemplateHead */, 16 /* TemplateMiddle */], anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceBeforeTemplateMiddleAndTail", anyToken, [16 /* TemplateMiddle */, 17 /* TemplateTail */], [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), isNonJsxSameLineTokenContext], 8 /* Delete */), + // No space after { and before } in JSX expression + rule("SpaceAfterOpenBraceInJsxExpression", 18 /* OpenBraceToken */, anyToken, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), isNonJsxSameLineTokenContext, isJsxExpressionContext], 2 /* Space */), + rule("SpaceBeforeCloseBraceInJsxExpression", anyToken, 19 /* CloseBraceToken */, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), isNonJsxSameLineTokenContext, isJsxExpressionContext], 2 /* Space */), + rule("NoSpaceAfterOpenBraceInJsxExpression", 18 /* OpenBraceToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), isNonJsxSameLineTokenContext, isJsxExpressionContext], 8 /* Delete */), + rule("NoSpaceBeforeCloseBraceInJsxExpression", anyToken, 19 /* CloseBraceToken */, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), isNonJsxSameLineTokenContext, isJsxExpressionContext], 8 /* Delete */), + // Insert space after semicolon in for statement + rule("SpaceAfterSemicolonInFor", 26 /* SemicolonToken */, anyToken, [isOptionEnabled("insertSpaceAfterSemicolonInForStatements"), isNonJsxSameLineTokenContext, isForContext], 2 /* Space */), + rule("NoSpaceAfterSemicolonInFor", 26 /* SemicolonToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterSemicolonInForStatements"), isNonJsxSameLineTokenContext, isForContext], 8 /* Delete */), + // Insert space before and after binary operators + rule("SpaceBeforeBinaryOperator", anyToken, binaryOperators, [isOptionEnabled("insertSpaceBeforeAndAfterBinaryOperators"), isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), + rule("SpaceAfterBinaryOperator", binaryOperators, anyToken, [isOptionEnabled("insertSpaceBeforeAndAfterBinaryOperators"), isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), + rule("NoSpaceBeforeBinaryOperator", anyToken, binaryOperators, [isOptionDisabledOrUndefined("insertSpaceBeforeAndAfterBinaryOperators"), isNonJsxSameLineTokenContext, isBinaryOpContext], 8 /* Delete */), + rule("NoSpaceAfterBinaryOperator", binaryOperators, anyToken, [isOptionDisabledOrUndefined("insertSpaceBeforeAndAfterBinaryOperators"), isNonJsxSameLineTokenContext, isBinaryOpContext], 8 /* Delete */), + rule("SpaceBeforeOpenParenInFuncDecl", anyToken, 20 /* OpenParenToken */, [isOptionEnabled("insertSpaceBeforeFunctionParenthesis"), isNonJsxSameLineTokenContext, isFunctionDeclContext], 2 /* Space */), + rule("NoSpaceBeforeOpenParenInFuncDecl", anyToken, 20 /* OpenParenToken */, [isOptionDisabledOrUndefined("insertSpaceBeforeFunctionParenthesis"), isNonJsxSameLineTokenContext, isFunctionDeclContext], 8 /* Delete */), + // Open Brace braces after control block + rule("NewLineBeforeOpenBraceInControl", controlOpenBraceLeftTokenRange, 18 /* OpenBraceToken */, [isOptionEnabled("placeOpenBraceOnNewLineForControlBlocks"), isControlDeclContext, isBeforeMultilineBlockContext], 4 /* NewLine */, 1 /* CanDeleteNewLines */), + // Open Brace braces after function + // TypeScript: Function can have return types, which can be made of tons of different token kinds + rule("NewLineBeforeOpenBraceInFunction", functionOpenBraceLeftTokenRange, 18 /* OpenBraceToken */, [isOptionEnabled("placeOpenBraceOnNewLineForFunctions"), isFunctionDeclContext, isBeforeMultilineBlockContext], 4 /* NewLine */, 1 /* CanDeleteNewLines */), + // Open Brace braces after TypeScript module/class/interface + rule("NewLineBeforeOpenBraceInTypeScriptDeclWithBlock", typeScriptOpenBraceLeftTokenRange, 18 /* OpenBraceToken */, [isOptionEnabled("placeOpenBraceOnNewLineForFunctions"), isTypeScriptDeclWithBlockContext, isBeforeMultilineBlockContext], 4 /* NewLine */, 1 /* CanDeleteNewLines */), + rule("SpaceAfterTypeAssertion", 30 /* GreaterThanToken */, anyToken, [isOptionEnabled("insertSpaceAfterTypeAssertion"), isNonJsxSameLineTokenContext, isTypeAssertionContext], 2 /* Space */), + rule("NoSpaceAfterTypeAssertion", 30 /* GreaterThanToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterTypeAssertion"), isNonJsxSameLineTokenContext, isTypeAssertionContext], 8 /* Delete */), + rule("SpaceBeforeTypeAnnotation", anyToken, 57 /* ColonToken */, [isOptionEnabled("insertSpaceBeforeTypeAnnotation"), isNonJsxSameLineTokenContext, isTypeAnnotationContext], 2 /* Space */), + rule("NoSpaceBeforeTypeAnnotation", anyToken, 57 /* ColonToken */, [isOptionDisabledOrUndefined("insertSpaceBeforeTypeAnnotation"), isNonJsxSameLineTokenContext, isTypeAnnotationContext], 8 /* Delete */), + ]; + // These rules are lower in priority than user-configurable. Rules earlier in this list have priority over rules later in the list. + var lowPriorityCommonRules = [ + // Space after keyword but not before ; or : or ? + rule("NoSpaceBeforeSemicolon", anyToken, 26 /* SemicolonToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("SpaceBeforeOpenBraceInControl", controlOpenBraceLeftTokenRange, 18 /* OpenBraceToken */, [isOptionDisabledOrUndefinedOrTokensOnSameLine("placeOpenBraceOnNewLineForControlBlocks"), isControlDeclContext, isNotFormatOnEnter, isSameLineTokenOrBeforeBlockContext], 2 /* Space */, 1 /* CanDeleteNewLines */), + rule("SpaceBeforeOpenBraceInFunction", functionOpenBraceLeftTokenRange, 18 /* OpenBraceToken */, [isOptionDisabledOrUndefinedOrTokensOnSameLine("placeOpenBraceOnNewLineForFunctions"), isFunctionDeclContext, isBeforeBlockContext, isNotFormatOnEnter, isSameLineTokenOrBeforeBlockContext], 2 /* Space */, 1 /* CanDeleteNewLines */), + rule("SpaceBeforeOpenBraceInTypeScriptDeclWithBlock", typeScriptOpenBraceLeftTokenRange, 18 /* OpenBraceToken */, [isOptionDisabledOrUndefinedOrTokensOnSameLine("placeOpenBraceOnNewLineForFunctions"), isTypeScriptDeclWithBlockContext, isNotFormatOnEnter, isSameLineTokenOrBeforeBlockContext], 2 /* Space */, 1 /* CanDeleteNewLines */), + rule("NoSpaceBeforeComma", anyToken, 27 /* CommaToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + // No space before and after indexer `x[]` + rule("NoSpaceBeforeOpenBracket", anyTokenExcept(121 /* AsyncKeyword */, 74 /* CaseKeyword */), 22 /* OpenBracketToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceAfterCloseBracket", 23 /* CloseBracketToken */, anyToken, [isNonJsxSameLineTokenContext, isNotBeforeBlockInFunctionDeclarationContext], 8 /* Delete */), + rule("SpaceAfterSemicolon", 26 /* SemicolonToken */, anyToken, [isNonJsxSameLineTokenContext], 2 /* Space */), + // Remove extra space between for and await + rule("SpaceBetweenForAndAwaitKeyword", 89 /* ForKeyword */, 122 /* AwaitKeyword */, [isNonJsxSameLineTokenContext], 2 /* Space */), + // Add a space between statements. All keywords except (do,else,case) has open/close parens after them. + // So, we have a rule to add a space for [),Any], [do,Any], [else,Any], and [case,Any] + rule("SpaceBetweenStatements", [21 /* CloseParenToken */, 82 /* DoKeyword */, 83 /* ElseKeyword */, 74 /* CaseKeyword */], anyToken, [isNonJsxSameLineTokenContext, isNonJsxElementOrFragmentContext, isNotForContext], 2 /* Space */), + // This low-pri rule takes care of "try {" and "finally {" in case the rule SpaceBeforeOpenBraceInControl didn't execute on FormatOnEnter. + rule("SpaceAfterTryFinally", [103 /* TryKeyword */, 88 /* FinallyKeyword */], 18 /* OpenBraceToken */, [isNonJsxSameLineTokenContext], 2 /* Space */), + ]; + return highPriorityCommonRules.concat(userConfigurableRules, lowPriorityCommonRules); + } + formatting.getAllRules = getAllRules; + function rule(debugName, left, right, context, action, flags) { + if (flags === void 0) { flags = 0 /* None */; } + return { leftTokenRange: toTokenRange(left), rightTokenRange: toTokenRange(right), rule: { debugName: debugName, context: context, action: action, flags: flags } }; + } + function tokenRangeFrom(tokens) { + return { tokens: tokens, isSpecific: true }; + } + function toTokenRange(arg) { + return typeof arg === "number" ? tokenRangeFrom([arg]) : ts.isArray(arg) ? tokenRangeFrom(arg) : arg; + } + function tokenRangeFromRange(from, to, except) { + if (except === void 0) { except = []; } + var tokens = []; + for (var token = from; token <= to; token++) { + if (!ts.contains(except, token)) { + tokens.push(token); + } + } + return tokenRangeFrom(tokens); + } + /// + /// Contexts + /// + function isOptionEnabled(optionName) { + return function (context) { return context.options && context.options.hasOwnProperty(optionName) && !!context.options[optionName]; }; + } + function isOptionDisabled(optionName) { + return function (context) { return context.options && context.options.hasOwnProperty(optionName) && !context.options[optionName]; }; + } + function isOptionDisabledOrUndefined(optionName) { + return function (context) { return !context.options || !context.options.hasOwnProperty(optionName) || !context.options[optionName]; }; + } + function isOptionDisabledOrUndefinedOrTokensOnSameLine(optionName) { + return function (context) { return !context.options || !context.options.hasOwnProperty(optionName) || !context.options[optionName] || context.TokensAreOnSameLine(); }; + } + function isOptionEnabledOrUndefined(optionName) { + return function (context) { return !context.options || !context.options.hasOwnProperty(optionName) || !!context.options[optionName]; }; + } + function isForContext(context) { + return context.contextNode.kind === 225 /* ForStatement */; + } + function isNotForContext(context) { + return !isForContext(context); + } + function isBinaryOpContext(context) { + switch (context.contextNode.kind) { + case 204 /* BinaryExpression */: + case 205 /* ConditionalExpression */: + case 175 /* ConditionalType */: + case 212 /* AsExpression */: + case 257 /* ExportSpecifier */: + case 253 /* ImportSpecifier */: + case 163 /* TypePredicate */: + case 173 /* UnionType */: + case 174 /* IntersectionType */: + return true; + // equals in binding elements: function foo([[x, y] = [1, 2]]) + case 186 /* BindingElement */: + // equals in type X = ... + case 242 /* TypeAliasDeclaration */: + // equal in import a = module('a'); + case 248 /* ImportEqualsDeclaration */: + // equal in let a = 0; + case 237 /* VariableDeclaration */: + // equal in p = 0; + case 151 /* Parameter */: + case 278 /* EnumMember */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + return context.currentTokenSpan.kind === 59 /* EqualsToken */ || context.nextTokenSpan.kind === 59 /* EqualsToken */; + // "in" keyword in for (let x in []) { } + case 226 /* ForInStatement */: + // "in" keyword in [P in keyof T]: T[P] + case 150 /* TypeParameter */: + return context.currentTokenSpan.kind === 93 /* InKeyword */ || context.nextTokenSpan.kind === 93 /* InKeyword */; + // Technically, "of" is not a binary operator, but format it the same way as "in" + case 227 /* ForOfStatement */: + return context.currentTokenSpan.kind === 147 /* OfKeyword */ || context.nextTokenSpan.kind === 147 /* OfKeyword */; + } + return false; + } + function isNotBinaryOpContext(context) { + return !isBinaryOpContext(context); + } + function isNotTypeAnnotationContext(context) { + return !isTypeAnnotationContext(context); + } + function isTypeAnnotationContext(context) { + var contextKind = context.contextNode.kind; + return contextKind === 154 /* PropertyDeclaration */ || + contextKind === 153 /* PropertySignature */ || + contextKind === 151 /* Parameter */ || + contextKind === 237 /* VariableDeclaration */ || + ts.isFunctionLikeKind(contextKind); + } + function isConditionalOperatorContext(context) { + return context.contextNode.kind === 205 /* ConditionalExpression */ || + context.contextNode.kind === 175 /* ConditionalType */; + } + function isSameLineTokenOrBeforeBlockContext(context) { + return context.TokensAreOnSameLine() || isBeforeBlockContext(context); + } + function isBraceWrappedContext(context) { + return context.contextNode.kind === 184 /* ObjectBindingPattern */ || + context.contextNode.kind === 181 /* MappedType */ || + isSingleLineBlockContext(context); + } + // This check is done before an open brace in a control construct, a function, or a typescript block declaration + function isBeforeMultilineBlockContext(context) { + return isBeforeBlockContext(context) && !(context.NextNodeAllOnSameLine() || context.NextNodeBlockIsOnOneLine()); + } + function isMultilineBlockContext(context) { + return isBlockContext(context) && !(context.ContextNodeAllOnSameLine() || context.ContextNodeBlockIsOnOneLine()); + } + function isSingleLineBlockContext(context) { + return isBlockContext(context) && (context.ContextNodeAllOnSameLine() || context.ContextNodeBlockIsOnOneLine()); + } + function isBlockContext(context) { + return nodeIsBlockContext(context.contextNode); + } + function isBeforeBlockContext(context) { + return nodeIsBlockContext(context.nextTokenParent); + } + // IMPORTANT!!! This method must return true ONLY for nodes with open and close braces as immediate children + function nodeIsBlockContext(node) { + if (nodeIsTypeScriptDeclWithBlockContext(node)) { + // This means we are in a context that looks like a block to the user, but in the grammar is actually not a node (it's a class, module, enum, object type literal, etc). + return true; + } + switch (node.kind) { + case 218 /* Block */: + case 246 /* CaseBlock */: + case 188 /* ObjectLiteralExpression */: + case 245 /* ModuleBlock */: + return true; + } + return false; + } + function isFunctionDeclContext(context) { + switch (context.contextNode.kind) { + case 239 /* FunctionDeclaration */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + // case SyntaxKind.MemberFunctionDeclaration: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + // case SyntaxKind.MethodSignature: + case 160 /* CallSignature */: + case 196 /* FunctionExpression */: + case 157 /* Constructor */: + case 197 /* ArrowFunction */: + // case SyntaxKind.ConstructorDeclaration: + // case SyntaxKind.SimpleArrowFunctionExpression: + // case SyntaxKind.ParenthesizedArrowFunctionExpression: + case 241 /* InterfaceDeclaration */: // This one is not truly a function, but for formatting purposes, it acts just like one + return true; + } + return false; + } + function isNotFunctionDeclContext(context) { + return !isFunctionDeclContext(context); + } + function isFunctionDeclarationOrFunctionExpressionContext(context) { + return context.contextNode.kind === 239 /* FunctionDeclaration */ || context.contextNode.kind === 196 /* FunctionExpression */; + } + function isTypeScriptDeclWithBlockContext(context) { + return nodeIsTypeScriptDeclWithBlockContext(context.contextNode); + } + function nodeIsTypeScriptDeclWithBlockContext(node) { + switch (node.kind) { + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 241 /* InterfaceDeclaration */: + case 243 /* EnumDeclaration */: + case 168 /* TypeLiteral */: + case 244 /* ModuleDeclaration */: + case 255 /* ExportDeclaration */: + case 256 /* NamedExports */: + case 249 /* ImportDeclaration */: + case 252 /* NamedImports */: + return true; + } + return false; + } + function isAfterCodeBlockContext(context) { + switch (context.currentTokenParent.kind) { + case 240 /* ClassDeclaration */: + case 244 /* ModuleDeclaration */: + case 243 /* EnumDeclaration */: + case 274 /* CatchClause */: + case 245 /* ModuleBlock */: + case 232 /* SwitchStatement */: + return true; + case 218 /* Block */: { + var blockParent = context.currentTokenParent.parent; + // In a codefix scenario, we can't rely on parents being set. So just always return true. + if (!blockParent || blockParent.kind !== 197 /* ArrowFunction */ && blockParent.kind !== 196 /* FunctionExpression */) { + return true; + } + } + } + return false; + } + function isControlDeclContext(context) { + switch (context.contextNode.kind) { + case 222 /* IfStatement */: + case 232 /* SwitchStatement */: + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + case 224 /* WhileStatement */: + case 235 /* TryStatement */: + case 223 /* DoStatement */: + case 231 /* WithStatement */: + // TODO + // case SyntaxKind.ElseClause: + case 274 /* CatchClause */: + return true; + default: + return false; + } + } + function isObjectContext(context) { + return context.contextNode.kind === 188 /* ObjectLiteralExpression */; + } + function isFunctionCallContext(context) { + return context.contextNode.kind === 191 /* CallExpression */; + } + function isNewContext(context) { + return context.contextNode.kind === 192 /* NewExpression */; + } + function isFunctionCallOrNewContext(context) { + return isFunctionCallContext(context) || isNewContext(context); + } + function isPreviousTokenNotComma(context) { + return context.currentTokenSpan.kind !== 27 /* CommaToken */; + } + function isNextTokenNotCloseBracket(context) { + return context.nextTokenSpan.kind !== 23 /* CloseBracketToken */; + } + function isArrowFunctionContext(context) { + return context.contextNode.kind === 197 /* ArrowFunction */; + } + function isImportTypeContext(context) { + return context.contextNode.kind === 183 /* ImportType */; + } + function isNonJsxSameLineTokenContext(context) { + return context.TokensAreOnSameLine() && context.contextNode.kind !== 11 /* JsxText */; + } + function isNonJsxElementOrFragmentContext(context) { + return context.contextNode.kind !== 260 /* JsxElement */ && context.contextNode.kind !== 264 /* JsxFragment */; + } + function isJsxExpressionContext(context) { + return context.contextNode.kind === 270 /* JsxExpression */ || context.contextNode.kind === 269 /* JsxSpreadAttribute */; + } + function isNextTokenParentJsxAttribute(context) { + return context.nextTokenParent.kind === 267 /* JsxAttribute */; + } + function isJsxAttributeContext(context) { + return context.contextNode.kind === 267 /* JsxAttribute */; + } + function isJsxSelfClosingElementContext(context) { + return context.contextNode.kind === 261 /* JsxSelfClosingElement */; + } + function isNotBeforeBlockInFunctionDeclarationContext(context) { + return !isFunctionDeclContext(context) && !isBeforeBlockContext(context); + } + function isEndOfDecoratorContextOnSameLine(context) { + return context.TokensAreOnSameLine() && + !!context.contextNode.decorators && + nodeIsInDecoratorContext(context.currentTokenParent) && + !nodeIsInDecoratorContext(context.nextTokenParent); + } + function nodeIsInDecoratorContext(node) { + while (ts.isExpressionNode(node)) { + node = node.parent; + } + return node.kind === 152 /* Decorator */; + } + function isStartOfVariableDeclarationList(context) { + return context.currentTokenParent.kind === 238 /* VariableDeclarationList */ && + context.currentTokenParent.getStart(context.sourceFile) === context.currentTokenSpan.pos; + } + function isNotFormatOnEnter(context) { + return context.formattingRequestKind !== 2 /* FormatOnEnter */; + } + function isModuleDeclContext(context) { + return context.contextNode.kind === 244 /* ModuleDeclaration */; + } + function isObjectTypeContext(context) { + return context.contextNode.kind === 168 /* TypeLiteral */; // && context.contextNode.parent.kind !== SyntaxKind.InterfaceDeclaration; + } + function isConstructorSignatureContext(context) { + return context.contextNode.kind === 161 /* ConstructSignature */; + } + function isTypeArgumentOrParameterOrAssertion(token, parent) { + if (token.kind !== 28 /* LessThanToken */ && token.kind !== 30 /* GreaterThanToken */) { + return false; + } + switch (parent.kind) { + case 164 /* TypeReference */: + case 194 /* TypeAssertionExpression */: + case 242 /* TypeAliasDeclaration */: + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 241 /* InterfaceDeclaration */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 191 /* CallExpression */: + case 192 /* NewExpression */: + case 211 /* ExpressionWithTypeArguments */: + return true; + default: + return false; + } + } + function isTypeArgumentOrParameterOrAssertionContext(context) { + return isTypeArgumentOrParameterOrAssertion(context.currentTokenSpan, context.currentTokenParent) || + isTypeArgumentOrParameterOrAssertion(context.nextTokenSpan, context.nextTokenParent); + } + function isTypeAssertionContext(context) { + return context.contextNode.kind === 194 /* TypeAssertionExpression */; + } + function isVoidOpContext(context) { + return context.currentTokenSpan.kind === 106 /* VoidKeyword */ && context.currentTokenParent.kind === 200 /* VoidExpression */; + } + function isYieldOrYieldStarWithOperand(context) { + return context.contextNode.kind === 207 /* YieldExpression */ && context.contextNode.expression !== undefined; + } + function isNonNullAssertionContext(context) { + return context.contextNode.kind === 213 /* NonNullExpression */; + } + })(formatting = ts.formatting || (ts.formatting = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var formatting; + (function (formatting) { + function getFormatContext(options) { + return { options: options, getRule: getRulesMap() }; + } + formatting.getFormatContext = getFormatContext; + var rulesMapCache; + function getRulesMap() { + if (rulesMapCache === undefined) { + rulesMapCache = createRulesMap(formatting.getAllRules()); + } + return rulesMapCache; + } + function createRulesMap(rules) { + var map = buildMap(rules); + return function (context) { + var bucket = map[getRuleBucketIndex(context.currentTokenSpan.kind, context.nextTokenSpan.kind)]; + return bucket && ts.find(bucket, function (rule) { return ts.every(rule.context, function (c) { return c(context); }); }); + }; + } + function buildMap(rules) { + // Map from bucket index to array of rules + var map = new Array(mapRowLength * mapRowLength); + // This array is used only during construction of the rulesbucket in the map + var rulesBucketConstructionStateList = new Array(map.length); + for (var _i = 0, rules_1 = rules; _i < rules_1.length; _i++) { + var rule = rules_1[_i]; + var specificRule = rule.leftTokenRange.isSpecific && rule.rightTokenRange.isSpecific; + for (var _a = 0, _b = rule.leftTokenRange.tokens; _a < _b.length; _a++) { + var left = _b[_a]; + for (var _c = 0, _d = rule.rightTokenRange.tokens; _c < _d.length; _c++) { + var right = _d[_c]; + var index = getRuleBucketIndex(left, right); + var rulesBucket = map[index]; + if (rulesBucket === undefined) { + rulesBucket = map[index] = []; + } + addRule(rulesBucket, rule.rule, specificRule, rulesBucketConstructionStateList, index); + } + } + } + return map; + } + function getRuleBucketIndex(row, column) { + ts.Debug.assert(row <= 147 /* LastKeyword */ && column <= 147 /* LastKeyword */, "Must compute formatting context from tokens"); + return (row * mapRowLength) + column; + } + var maskBitSize = 5; + var mask = 31; // MaskBitSize bits + var mapRowLength = 147 /* LastToken */ + 1; + var RulesPosition; + (function (RulesPosition) { + RulesPosition[RulesPosition["IgnoreRulesSpecific"] = 0] = "IgnoreRulesSpecific"; + RulesPosition[RulesPosition["IgnoreRulesAny"] = maskBitSize * 1] = "IgnoreRulesAny"; + RulesPosition[RulesPosition["ContextRulesSpecific"] = maskBitSize * 2] = "ContextRulesSpecific"; + RulesPosition[RulesPosition["ContextRulesAny"] = maskBitSize * 3] = "ContextRulesAny"; + RulesPosition[RulesPosition["NoContextRulesSpecific"] = maskBitSize * 4] = "NoContextRulesSpecific"; + RulesPosition[RulesPosition["NoContextRulesAny"] = maskBitSize * 5] = "NoContextRulesAny"; + })(RulesPosition || (RulesPosition = {})); + // The Rules list contains all the inserted rules into a rulebucket in the following order: + // 1- Ignore rules with specific token combination + // 2- Ignore rules with any token combination + // 3- Context rules with specific token combination + // 4- Context rules with any token combination + // 5- Non-context rules with specific token combination + // 6- Non-context rules with any token combination + // + // The member rulesInsertionIndexBitmap is used to describe the number of rules + // in each sub-bucket (above) hence can be used to know the index of where to insert + // the next rule. It's a bitmap which contains 6 different sections each is given 5 bits. + // + // Example: + // In order to insert a rule to the end of sub-bucket (3), we get the index by adding + // the values in the bitmap segments 3rd, 2nd, and 1st. + function addRule(rules, rule, specificTokens, constructionState, rulesBucketIndex) { + var position = rule.action === 1 /* Ignore */ + ? specificTokens ? RulesPosition.IgnoreRulesSpecific : RulesPosition.IgnoreRulesAny + : rule.context !== formatting.anyContext + ? specificTokens ? RulesPosition.ContextRulesSpecific : RulesPosition.ContextRulesAny + : specificTokens ? RulesPosition.NoContextRulesSpecific : RulesPosition.NoContextRulesAny; + var state = constructionState[rulesBucketIndex] || 0; + rules.splice(getInsertionIndex(state, position), 0, rule); + constructionState[rulesBucketIndex] = increaseInsertionIndex(state, position); + } + function getInsertionIndex(indexBitmap, maskPosition) { + var index = 0; + for (var pos = 0; pos <= maskPosition; pos += maskBitSize) { + index += indexBitmap & mask; + indexBitmap >>= maskBitSize; + } + return index; + } + function increaseInsertionIndex(indexBitmap, maskPosition) { + var value = ((indexBitmap >> maskPosition) & mask) + 1; + ts.Debug.assert((value & mask) === value, "Adding more rules into the sub-bucket than allowed. Maximum allowed is 32 rules."); + return (indexBitmap & ~(mask << maskPosition)) | (value << maskPosition); + } + })(formatting = ts.formatting || (ts.formatting = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var formatting; + (function (formatting) { + var Constants; + (function (Constants) { + Constants[Constants["Unknown"] = -1] = "Unknown"; + })(Constants || (Constants = {})); + function formatOnEnter(position, sourceFile, formatContext) { + var line = sourceFile.getLineAndCharacterOfPosition(position).line; + if (line === 0) { + return []; + } + // After the enter key, the cursor is now at a new line. The new line may or may not contain non-whitespace characters. + // If the new line has only whitespaces, we won't want to format this line, because that would remove the indentation as + // trailing whitespaces. So the end of the formatting span should be the later one between: + // 1. the end of the previous line + // 2. the last non-whitespace character in the current line + var endOfFormatSpan = ts.getEndLinePosition(line, sourceFile); + while (ts.isWhiteSpaceSingleLine(sourceFile.text.charCodeAt(endOfFormatSpan))) { + endOfFormatSpan--; + } + // if the character at the end of the span is a line break, we shouldn't include it, because it indicates we don't want to + // touch the current line at all. Also, on some OSes the line break consists of two characters (\r\n), we should test if the + // previous character before the end of format span is line break character as well. + if (ts.isLineBreak(sourceFile.text.charCodeAt(endOfFormatSpan))) { + endOfFormatSpan--; + } + var span = { + // get start position for the previous line + pos: ts.getStartPositionOfLine(line - 1, sourceFile), + // end value is exclusive so add 1 to the result + end: endOfFormatSpan + 1 + }; + return formatSpan(span, sourceFile, formatContext, 2 /* FormatOnEnter */); + } + formatting.formatOnEnter = formatOnEnter; + function formatOnSemicolon(position, sourceFile, formatContext) { + var semicolon = findImmediatelyPrecedingTokenOfKind(position, 26 /* SemicolonToken */, sourceFile); + return formatNodeLines(findOutermostNodeWithinListLevel(semicolon), sourceFile, formatContext, 3 /* FormatOnSemicolon */); + } + formatting.formatOnSemicolon = formatOnSemicolon; + function formatOnOpeningCurly(position, sourceFile, formatContext) { + var openingCurly = findImmediatelyPrecedingTokenOfKind(position, 18 /* OpenBraceToken */, sourceFile); + if (!openingCurly) { + return []; + } + var curlyBraceRange = openingCurly.parent; + var outermostNode = findOutermostNodeWithinListLevel(curlyBraceRange); + /** + * We limit the span to end at the opening curly to handle the case where + * the brace matched to that just typed will be incorrect after further edits. + * For example, we could type the opening curly for the following method + * body without brace-matching activated: + * ``` + * class C { + * foo() + * } + * ``` + * and we wouldn't want to move the closing brace. + */ + var textRange = { + pos: ts.getLineStartPositionForPosition(outermostNode.getStart(sourceFile), sourceFile), + end: position + }; + return formatSpan(textRange, sourceFile, formatContext, 4 /* FormatOnOpeningCurlyBrace */); + } + formatting.formatOnOpeningCurly = formatOnOpeningCurly; + function formatOnClosingCurly(position, sourceFile, formatContext) { + var precedingToken = findImmediatelyPrecedingTokenOfKind(position, 19 /* CloseBraceToken */, sourceFile); + return formatNodeLines(findOutermostNodeWithinListLevel(precedingToken), sourceFile, formatContext, 5 /* FormatOnClosingCurlyBrace */); + } + formatting.formatOnClosingCurly = formatOnClosingCurly; + function formatDocument(sourceFile, formatContext) { + var span = { + pos: 0, + end: sourceFile.text.length + }; + return formatSpan(span, sourceFile, formatContext, 0 /* FormatDocument */); + } + formatting.formatDocument = formatDocument; + function formatSelection(start, end, sourceFile, formatContext) { + // format from the beginning of the line + var span = { + pos: ts.getLineStartPositionForPosition(start, sourceFile), + end: end, + }; + return formatSpan(span, sourceFile, formatContext, 1 /* FormatSelection */); + } + formatting.formatSelection = formatSelection; + /** + * Validating `expectedTokenKind` ensures the token was typed in the context we expect (eg: not a comment). + * @param expectedTokenKind The kind of the last token constituting the desired parent node. + */ + function findImmediatelyPrecedingTokenOfKind(end, expectedTokenKind, sourceFile) { + var precedingToken = ts.findPrecedingToken(end, sourceFile); + return precedingToken && precedingToken.kind === expectedTokenKind && end === precedingToken.getEnd() ? + precedingToken : + undefined; + } + /** + * Finds the highest node enclosing `node` at the same list level as `node` + * and whose end does not exceed `node.end`. + * + * Consider typing the following + * ``` + * let x = 1; + * while (true) { + * } + * ``` + * Upon typing the closing curly, we want to format the entire `while`-statement, but not the preceding + * variable declaration. + */ + function findOutermostNodeWithinListLevel(node) { + var current = node; + while (current && + current.parent && + current.parent.end === node.end && + !isListElement(current.parent, current)) { + current = current.parent; + } + return current; + } + // Returns true if node is a element in some list in parent + // i.e. parent is class declaration with the list of members and node is one of members. + function isListElement(parent, node) { + switch (parent.kind) { + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + return ts.rangeContainsRange(parent.members, node); + case 244 /* ModuleDeclaration */: + var body = parent.body; + return !!body && body.kind === 245 /* ModuleBlock */ && ts.rangeContainsRange(body.statements, node); + case 279 /* SourceFile */: + case 218 /* Block */: + case 245 /* ModuleBlock */: + return ts.rangeContainsRange(parent.statements, node); + case 274 /* CatchClause */: + return ts.rangeContainsRange(parent.block.statements, node); + } + return false; + } + /** find node that fully contains given text range */ + function findEnclosingNode(range, sourceFile) { + return find(sourceFile); + function find(n) { + var candidate = ts.forEachChild(n, function (c) { return ts.startEndContainsRange(c.getStart(sourceFile), c.end, range) && c; }); + if (candidate) { + var result = find(candidate); + if (result) { + return result; + } + } + return n; + } + } + /** formatting is not applied to ranges that contain parse errors. + * This function will return a predicate that for a given text range will tell + * if there are any parse errors that overlap with the range. + */ + function prepareRangeContainsErrorFunction(errors, originalRange) { + if (!errors.length) { + return rangeHasNoErrors; + } + // pick only errors that fall in range + var sorted = errors + .filter(function (d) { return ts.rangeOverlapsWithStartEnd(originalRange, d.start, d.start + d.length); }) // TODO: GH#18217 + .sort(function (e1, e2) { return e1.start - e2.start; }); + if (!sorted.length) { + return rangeHasNoErrors; + } + var index = 0; + return function (r) { + // in current implementation sequence of arguments [r1, r2...] is monotonically increasing. + // 'index' tracks the index of the most recent error that was checked. + while (true) { + if (index >= sorted.length) { + // all errors in the range were already checked -> no error in specified range + return false; + } + var error = sorted[index]; + if (r.end <= error.start) { + // specified range ends before the error refered by 'index' - no error in range + return false; + } + if (ts.startEndOverlapsWithStartEnd(r.pos, r.end, error.start, error.start + error.length)) { + // specified range overlaps with error range + return true; + } + index++; + } + }; + function rangeHasNoErrors() { + return false; + } + } + /** + * Start of the original range might fall inside the comment - scanner will not yield appropriate results + * This function will look for token that is located before the start of target range + * and return its end as start position for the scanner. + */ + function getScanStartPosition(enclosingNode, originalRange, sourceFile) { + var start = enclosingNode.getStart(sourceFile); + if (start === originalRange.pos && enclosingNode.end === originalRange.end) { + return start; + } + var precedingToken = ts.findPrecedingToken(originalRange.pos, sourceFile); + if (!precedingToken) { + // no preceding token found - start from the beginning of enclosing node + return enclosingNode.pos; + } + // preceding token ends after the start of original range (i.e when originalRange.pos falls in the middle of literal) + // start from the beginning of enclosingNode to handle the entire 'originalRange' + if (precedingToken.end >= originalRange.pos) { + return enclosingNode.pos; + } + return precedingToken.end; + } + /* + * For cases like + * if (a || + * b ||$ + * c) {...} + * If we hit Enter at $ we want line ' b ||' to be indented. + * Formatting will be applied to the last two lines. + * Node that fully encloses these lines is binary expression 'a ||...'. + * Initial indentation for this node will be 0. + * Binary expressions don't introduce new indentation scopes, however it is possible + * that some parent node on the same line does - like if statement in this case. + * Note that we are considering parents only from the same line with initial node - + * if parent is on the different line - its delta was already contributed + * to the initial indentation. + */ + function getOwnOrInheritedDelta(n, options, sourceFile) { + var previousLine = -1 /* Unknown */; + var child; + while (n) { + var line = sourceFile.getLineAndCharacterOfPosition(n.getStart(sourceFile)).line; + if (previousLine !== -1 /* Unknown */ && line !== previousLine) { + break; + } + if (formatting.SmartIndenter.shouldIndentChildNode(options, n, child, sourceFile)) { + return options.indentSize; + } + previousLine = line; + child = n; + n = n.parent; + } + return 0; + } + function formatNodeGivenIndentation(node, sourceFileLike, languageVariant, initialIndentation, delta, formatContext) { + var range = { pos: 0, end: sourceFileLike.text.length }; + return formatting.getFormattingScanner(sourceFileLike.text, languageVariant, range.pos, range.end, function (scanner) { return formatSpanWorker(range, node, initialIndentation, delta, scanner, formatContext, 1 /* FormatSelection */, function (_) { return false; }, // assume that node does not have any errors + sourceFileLike); }); + } + formatting.formatNodeGivenIndentation = formatNodeGivenIndentation; + function formatNodeLines(node, sourceFile, formatContext, requestKind) { + if (!node) { + return []; + } + var span = { + pos: ts.getLineStartPositionForPosition(node.getStart(sourceFile), sourceFile), + end: node.end + }; + return formatSpan(span, sourceFile, formatContext, requestKind); + } + function formatSpan(originalRange, sourceFile, formatContext, requestKind) { + // find the smallest node that fully wraps the range and compute the initial indentation for the node + var enclosingNode = findEnclosingNode(originalRange, sourceFile); + return formatting.getFormattingScanner(sourceFile.text, sourceFile.languageVariant, getScanStartPosition(enclosingNode, originalRange, sourceFile), originalRange.end, function (scanner) { return formatSpanWorker(originalRange, enclosingNode, formatting.SmartIndenter.getIndentationForNode(enclosingNode, originalRange, sourceFile, formatContext.options), getOwnOrInheritedDelta(enclosingNode, formatContext.options, sourceFile), scanner, formatContext, requestKind, prepareRangeContainsErrorFunction(sourceFile.parseDiagnostics, originalRange), sourceFile); }); + } + function formatSpanWorker(originalRange, enclosingNode, initialIndentation, delta, formattingScanner, _a, requestKind, rangeContainsError, sourceFile) { + var options = _a.options, getRule = _a.getRule; + // formatting context is used by rules provider + var formattingContext = new formatting.FormattingContext(sourceFile, requestKind, options); + var previousRange; + var previousParent; + var previousRangeStartLine; + var lastIndentedLine; + var indentationOnLastIndentedLine = -1 /* Unknown */; + var edits = []; + formattingScanner.advance(); + if (formattingScanner.isOnToken()) { + var startLine = sourceFile.getLineAndCharacterOfPosition(enclosingNode.getStart(sourceFile)).line; + var undecoratedStartLine = startLine; + if (enclosingNode.decorators) { + undecoratedStartLine = sourceFile.getLineAndCharacterOfPosition(ts.getNonDecoratorTokenPosOfNode(enclosingNode, sourceFile)).line; + } + processNode(enclosingNode, enclosingNode, startLine, undecoratedStartLine, initialIndentation, delta); + } + if (!formattingScanner.isOnToken()) { + var leadingTrivia = formattingScanner.getCurrentLeadingTrivia(); + if (leadingTrivia) { + indentTriviaItems(leadingTrivia, initialIndentation, /*indentNextTokenOrTrivia*/ false, function (item) { return processRange(item, sourceFile.getLineAndCharacterOfPosition(item.pos), enclosingNode, enclosingNode, /*dynamicIndentation*/ undefined); }); + trimTrailingWhitespacesForRemainingRange(); + } + } + return edits; + // local functions + /** Tries to compute the indentation for a list element. + * If list element is not in range then + * function will pick its actual indentation + * so it can be pushed downstream as inherited indentation. + * If list element is in the range - its indentation will be equal + * to inherited indentation from its predecessors. + */ + function tryComputeIndentationForListItem(startPos, endPos, parentStartLine, range, inheritedIndentation) { + if (ts.rangeOverlapsWithStartEnd(range, startPos, endPos) || + ts.rangeContainsStartEnd(range, startPos, endPos) /* Not to miss zero-range nodes e.g. JsxText */) { + if (inheritedIndentation !== -1 /* Unknown */) { + return inheritedIndentation; + } + } + else { + var startLine = sourceFile.getLineAndCharacterOfPosition(startPos).line; + var startLinePosition = ts.getLineStartPositionForPosition(startPos, sourceFile); + var column = formatting.SmartIndenter.findFirstNonWhitespaceColumn(startLinePosition, startPos, sourceFile, options); + if (startLine !== parentStartLine || startPos === column) { + // Use the base indent size if it is greater than + // the indentation of the inherited predecessor. + var baseIndentSize = formatting.SmartIndenter.getBaseIndentation(options); + return baseIndentSize > column ? baseIndentSize : column; + } + } + return -1 /* Unknown */; + } + function computeIndentation(node, startLine, inheritedIndentation, parent, parentDynamicIndentation, effectiveParentStartLine) { + var delta = formatting.SmartIndenter.shouldIndentChildNode(options, node) ? options.indentSize : 0; + if (effectiveParentStartLine === startLine) { + // if node is located on the same line with the parent + // - inherit indentation from the parent + // - push children if either parent of node itself has non-zero delta + return { + indentation: startLine === lastIndentedLine ? indentationOnLastIndentedLine : parentDynamicIndentation.getIndentation(), + delta: Math.min(options.indentSize, parentDynamicIndentation.getDelta(node) + delta) + }; + } + else if (inheritedIndentation === -1 /* Unknown */) { + if (node.kind === 20 /* OpenParenToken */ && startLine === lastIndentedLine) { + // the is used for chaining methods formatting + // - we need to get the indentation on last line and the delta of parent + return { indentation: indentationOnLastIndentedLine, delta: parentDynamicIndentation.getDelta(node) }; + } + else if (formatting.SmartIndenter.childStartsOnTheSameLineWithElseInIfStatement(parent, node, startLine, sourceFile)) { + return { indentation: parentDynamicIndentation.getIndentation(), delta: delta }; + } + else { + return { indentation: parentDynamicIndentation.getIndentation() + parentDynamicIndentation.getDelta(node), delta: delta }; + } + } + else { + return { indentation: inheritedIndentation, delta: delta }; + } + } + function getFirstNonDecoratorTokenOfNode(node) { + if (node.modifiers && node.modifiers.length) { + return node.modifiers[0].kind; + } + switch (node.kind) { + case 240 /* ClassDeclaration */: return 76 /* ClassKeyword */; + case 241 /* InterfaceDeclaration */: return 110 /* InterfaceKeyword */; + case 239 /* FunctionDeclaration */: return 90 /* FunctionKeyword */; + case 243 /* EnumDeclaration */: return 243 /* EnumDeclaration */; + case 158 /* GetAccessor */: return 126 /* GetKeyword */; + case 159 /* SetAccessor */: return 137 /* SetKeyword */; + case 156 /* MethodDeclaration */: + if (node.asteriskToken) { + return 40 /* AsteriskToken */; + } + // falls through + case 154 /* PropertyDeclaration */: + case 151 /* Parameter */: + var name = ts.getNameOfDeclaration(node); + if (name) { + return name.kind; + } + } + } + function getDynamicIndentation(node, nodeStartLine, indentation, delta) { + return { + getIndentationForComment: function (kind, tokenIndentation, container) { + switch (kind) { + // preceding comment to the token that closes the indentation scope inherits the indentation from the scope + // .. { + // // comment + // } + case 19 /* CloseBraceToken */: + case 23 /* CloseBracketToken */: + case 21 /* CloseParenToken */: + return indentation + getDelta(container); + } + return tokenIndentation !== -1 /* Unknown */ ? tokenIndentation : indentation; + }, + // if list end token is LessThanToken '>' then its delta should be explicitly suppressed + // so that LessThanToken as a binary operator can still be indented. + // foo.then + // < + // number, + // string, + // >(); + // vs + // var a = xValue + // > yValue; + getIndentationForToken: function (line, kind, container, suppressDelta) { + return !suppressDelta && shouldAddDelta(line, kind, container) ? indentation + getDelta(container) : indentation; + }, + getIndentation: function () { return indentation; }, + getDelta: getDelta, + recomputeIndentation: function (lineAdded) { + if (node.parent && formatting.SmartIndenter.shouldIndentChildNode(options, node.parent, node, sourceFile)) { + indentation += lineAdded ? options.indentSize : -options.indentSize; + delta = formatting.SmartIndenter.shouldIndentChildNode(options, node) ? options.indentSize : 0; + } + } + }; + function shouldAddDelta(line, kind, container) { + switch (kind) { + // open and close brace, 'else' and 'while' (in do statement) tokens has indentation of the parent + case 18 /* OpenBraceToken */: + case 19 /* CloseBraceToken */: + case 21 /* CloseParenToken */: + case 83 /* ElseKeyword */: + case 107 /* WhileKeyword */: + case 58 /* AtToken */: + return false; + case 42 /* SlashToken */: + case 30 /* GreaterThanToken */: + switch (container.kind) { + case 262 /* JsxOpeningElement */: + case 263 /* JsxClosingElement */: + case 261 /* JsxSelfClosingElement */: + return false; + } + break; + case 22 /* OpenBracketToken */: + case 23 /* CloseBracketToken */: + if (container.kind !== 181 /* MappedType */) { + return false; + } + break; + } + // if token line equals to the line of containing node (this is a first token in the node) - use node indentation + return nodeStartLine !== line + // if this token is the first token following the list of decorators, we do not need to indent + && !(node.decorators && kind === getFirstNonDecoratorTokenOfNode(node)); + } + function getDelta(child) { + // Delta value should be zero when the node explicitly prevents indentation of the child node + return formatting.SmartIndenter.nodeWillIndentChild(options, node, child, sourceFile, /*indentByDefault*/ true) ? delta : 0; + } + } + function processNode(node, contextNode, nodeStartLine, undecoratedNodeStartLine, indentation, delta) { + if (!ts.rangeOverlapsWithStartEnd(originalRange, node.getStart(sourceFile), node.getEnd())) { + return; + } + var nodeDynamicIndentation = getDynamicIndentation(node, nodeStartLine, indentation, delta); + // a useful observations when tracking context node + // / + // [a] + // / | \ + // [b] [c] [d] + // node 'a' is a context node for nodes 'b', 'c', 'd' + // except for the leftmost leaf token in [b] - in this case context node ('e') is located somewhere above 'a' + // this rule can be applied recursively to child nodes of 'a'. + // + // context node is set to parent node value after processing every child node + // context node is set to parent of the token after processing every token + var childContextNode = contextNode; + // if there are any tokens that logically belong to node and interleave child nodes + // such tokens will be consumed in processChildNode for the child that follows them + ts.forEachChild(node, function (child) { + processChildNode(child, /*inheritedIndentation*/ -1 /* Unknown */, node, nodeDynamicIndentation, nodeStartLine, undecoratedNodeStartLine, /*isListItem*/ false); + }, function (nodes) { + processChildNodes(nodes, node, nodeStartLine, nodeDynamicIndentation); + }); + // proceed any tokens in the node that are located after child nodes + while (formattingScanner.isOnToken()) { + var tokenInfo = formattingScanner.readTokenInfo(node); + if (tokenInfo.token.end > node.end) { + break; + } + consumeTokenAndAdvanceScanner(tokenInfo, node, nodeDynamicIndentation, node); + } + function processChildNode(child, inheritedIndentation, parent, parentDynamicIndentation, parentStartLine, undecoratedParentStartLine, isListItem, isFirstListItem) { + var childStartPos = child.getStart(sourceFile); + var childStartLine = sourceFile.getLineAndCharacterOfPosition(childStartPos).line; + var undecoratedChildStartLine = childStartLine; + if (child.decorators) { + undecoratedChildStartLine = sourceFile.getLineAndCharacterOfPosition(ts.getNonDecoratorTokenPosOfNode(child, sourceFile)).line; + } + // if child is a list item - try to get its indentation, only if parent is within the original range. + var childIndentationAmount = -1 /* Unknown */; + if (isListItem && ts.rangeContainsRange(originalRange, parent)) { + childIndentationAmount = tryComputeIndentationForListItem(childStartPos, child.end, parentStartLine, originalRange, inheritedIndentation); + if (childIndentationAmount !== -1 /* Unknown */) { + inheritedIndentation = childIndentationAmount; + } + } + // child node is outside the target range - do not dive inside + if (!ts.rangeOverlapsWithStartEnd(originalRange, child.pos, child.end)) { + if (child.end < originalRange.pos) { + formattingScanner.skipToEndOf(child); + } + return inheritedIndentation; + } + if (child.getFullWidth() === 0) { + return inheritedIndentation; + } + while (formattingScanner.isOnToken()) { + // proceed any parent tokens that are located prior to child.getStart() + var tokenInfo = formattingScanner.readTokenInfo(node); + if (tokenInfo.token.end > childStartPos) { + // stop when formatting scanner advances past the beginning of the child + break; + } + consumeTokenAndAdvanceScanner(tokenInfo, node, parentDynamicIndentation, node); + } + if (!formattingScanner.isOnToken()) { + return inheritedIndentation; + } + // JSX text shouldn't affect indenting + if (ts.isToken(child) && child.kind !== 11 /* JsxText */) { + // if child node is a token, it does not impact indentation, proceed it using parent indentation scope rules + var tokenInfo = formattingScanner.readTokenInfo(child); + ts.Debug.assert(tokenInfo.token.end === child.end, "Token end is child end"); + consumeTokenAndAdvanceScanner(tokenInfo, node, parentDynamicIndentation, child); + return inheritedIndentation; + } + var effectiveParentStartLine = child.kind === 152 /* Decorator */ ? childStartLine : undecoratedParentStartLine; + var childIndentation = computeIndentation(child, childStartLine, childIndentationAmount, node, parentDynamicIndentation, effectiveParentStartLine); + processNode(child, childContextNode, childStartLine, undecoratedChildStartLine, childIndentation.indentation, childIndentation.delta); + if (child.kind === 11 /* JsxText */) { + var range = { pos: child.getStart(), end: child.getEnd() }; + indentMultilineCommentOrJsxText(range, childIndentation.indentation, /*firstLineIsIndented*/ true, /*indentFinalLine*/ false); + } + childContextNode = node; + if (isFirstListItem && parent.kind === 187 /* ArrayLiteralExpression */ && inheritedIndentation === -1 /* Unknown */) { + inheritedIndentation = childIndentation.indentation; + } + return inheritedIndentation; + } + function processChildNodes(nodes, parent, parentStartLine, parentDynamicIndentation) { + ts.Debug.assert(ts.isNodeArray(nodes)); + var listStartToken = getOpenTokenForList(parent, nodes); + var listDynamicIndentation = parentDynamicIndentation; + var startLine = parentStartLine; + if (listStartToken !== 0 /* Unknown */) { + // introduce a new indentation scope for lists (including list start and end tokens) + while (formattingScanner.isOnToken()) { + var tokenInfo = formattingScanner.readTokenInfo(parent); + if (tokenInfo.token.end > nodes.pos) { + // stop when formatting scanner moves past the beginning of node list + break; + } + else if (tokenInfo.token.kind === listStartToken) { + // consume list start token + startLine = sourceFile.getLineAndCharacterOfPosition(tokenInfo.token.pos).line; + consumeTokenAndAdvanceScanner(tokenInfo, parent, parentDynamicIndentation, parent); + var indentationOnListStartToken = void 0; + if (indentationOnLastIndentedLine !== -1 /* Unknown */) { + // scanner just processed list start token so consider last indentation as list indentation + // function foo(): { // last indentation was 0, list item will be indented based on this value + // foo: number; + // }: {}; + indentationOnListStartToken = indentationOnLastIndentedLine; + } + else { + var startLinePosition = ts.getLineStartPositionForPosition(tokenInfo.token.pos, sourceFile); + indentationOnListStartToken = formatting.SmartIndenter.findFirstNonWhitespaceColumn(startLinePosition, tokenInfo.token.pos, sourceFile, options); + } + listDynamicIndentation = getDynamicIndentation(parent, parentStartLine, indentationOnListStartToken, options.indentSize); // TODO: GH#18217 + } + else { + // consume any tokens that precede the list as child elements of 'node' using its indentation scope + consumeTokenAndAdvanceScanner(tokenInfo, parent, parentDynamicIndentation, parent); + } + } + } + var inheritedIndentation = -1 /* Unknown */; + for (var i = 0; i < nodes.length; i++) { + var child = nodes[i]; + inheritedIndentation = processChildNode(child, inheritedIndentation, node, listDynamicIndentation, startLine, startLine, /*isListItem*/ true, /*isFirstListItem*/ i === 0); + } + var listEndToken = getCloseTokenForOpenToken(listStartToken); + if (listEndToken !== 0 /* Unknown */ && formattingScanner.isOnToken()) { + var tokenInfo = formattingScanner.readTokenInfo(parent); + if (tokenInfo.token.kind === 27 /* CommaToken */ && ts.isCallLikeExpression(parent)) { + formattingScanner.advance(); + tokenInfo = formattingScanner.isOnToken() ? formattingScanner.readTokenInfo(parent) : undefined; + } + // consume the list end token only if it is still belong to the parent + // there might be the case when current token matches end token but does not considered as one + // function (x: function) <-- + // without this check close paren will be interpreted as list end token for function expression which is wrong + if (tokenInfo && tokenInfo.token.kind === listEndToken && ts.rangeContainsRange(parent, tokenInfo.token)) { + // consume list end token + consumeTokenAndAdvanceScanner(tokenInfo, parent, listDynamicIndentation, parent, /*isListEndToken*/ true); + } + } + } + function consumeTokenAndAdvanceScanner(currentTokenInfo, parent, dynamicIndentation, container, isListEndToken) { + ts.Debug.assert(ts.rangeContainsRange(parent, currentTokenInfo.token)); + var lastTriviaWasNewLine = formattingScanner.lastTrailingTriviaWasNewLine(); + var indentToken = false; + if (currentTokenInfo.leadingTrivia) { + processTrivia(currentTokenInfo.leadingTrivia, parent, childContextNode, dynamicIndentation); + } + var lineAction = 0 /* None */; + var isTokenInRange = ts.rangeContainsRange(originalRange, currentTokenInfo.token); + var tokenStart = sourceFile.getLineAndCharacterOfPosition(currentTokenInfo.token.pos); + if (isTokenInRange) { + var rangeHasError = rangeContainsError(currentTokenInfo.token); + // save previousRange since processRange will overwrite this value with current one + var savePreviousRange = previousRange; + lineAction = processRange(currentTokenInfo.token, tokenStart, parent, childContextNode, dynamicIndentation); + // do not indent comments\token if token range overlaps with some error + if (!rangeHasError) { + if (lineAction === 0 /* None */) { + // indent token only if end line of previous range does not match start line of the token + var prevEndLine = savePreviousRange && sourceFile.getLineAndCharacterOfPosition(savePreviousRange.end).line; + indentToken = lastTriviaWasNewLine && tokenStart.line !== prevEndLine; + } + else { + indentToken = lineAction === 1 /* LineAdded */; + } + } + } + if (currentTokenInfo.trailingTrivia) { + processTrivia(currentTokenInfo.trailingTrivia, parent, childContextNode, dynamicIndentation); + } + if (indentToken) { + var tokenIndentation = (isTokenInRange && !rangeContainsError(currentTokenInfo.token)) ? + dynamicIndentation.getIndentationForToken(tokenStart.line, currentTokenInfo.token.kind, container, !!isListEndToken) : + -1 /* Unknown */; + var indentNextTokenOrTrivia = true; + if (currentTokenInfo.leadingTrivia) { + var commentIndentation_1 = dynamicIndentation.getIndentationForComment(currentTokenInfo.token.kind, tokenIndentation, container); + indentNextTokenOrTrivia = indentTriviaItems(currentTokenInfo.leadingTrivia, commentIndentation_1, indentNextTokenOrTrivia, function (item) { return insertIndentation(item.pos, commentIndentation_1, /*lineAdded*/ false); }); + } + // indent token only if is it is in target range and does not overlap with any error ranges + if (tokenIndentation !== -1 /* Unknown */ && indentNextTokenOrTrivia) { + insertIndentation(currentTokenInfo.token.pos, tokenIndentation, lineAction === 1 /* LineAdded */); + lastIndentedLine = tokenStart.line; + indentationOnLastIndentedLine = tokenIndentation; + } + } + formattingScanner.advance(); + childContextNode = parent; + } + } + function indentTriviaItems(trivia, commentIndentation, indentNextTokenOrTrivia, indentSingleLine) { + for (var _i = 0, trivia_1 = trivia; _i < trivia_1.length; _i++) { + var triviaItem = trivia_1[_i]; + var triviaInRange = ts.rangeContainsRange(originalRange, triviaItem); + switch (triviaItem.kind) { + case 3 /* MultiLineCommentTrivia */: + if (triviaInRange) { + indentMultilineCommentOrJsxText(triviaItem, commentIndentation, /*firstLineIsIndented*/ !indentNextTokenOrTrivia); + } + indentNextTokenOrTrivia = false; + break; + case 2 /* SingleLineCommentTrivia */: + if (indentNextTokenOrTrivia && triviaInRange) { + indentSingleLine(triviaItem); + } + indentNextTokenOrTrivia = false; + break; + case 4 /* NewLineTrivia */: + indentNextTokenOrTrivia = true; + break; + } + } + return indentNextTokenOrTrivia; + } + function processTrivia(trivia, parent, contextNode, dynamicIndentation) { + for (var _i = 0, trivia_2 = trivia; _i < trivia_2.length; _i++) { + var triviaItem = trivia_2[_i]; + if (ts.isComment(triviaItem.kind) && ts.rangeContainsRange(originalRange, triviaItem)) { + var triviaItemStart = sourceFile.getLineAndCharacterOfPosition(triviaItem.pos); + processRange(triviaItem, triviaItemStart, parent, contextNode, dynamicIndentation); + } + } + } + function processRange(range, rangeStart, parent, contextNode, dynamicIndentation) { + var rangeHasError = rangeContainsError(range); + var lineAction = 0 /* None */; + if (!rangeHasError) { + if (!previousRange) { + // trim whitespaces starting from the beginning of the span up to the current line + var originalStart = sourceFile.getLineAndCharacterOfPosition(originalRange.pos); + trimTrailingWhitespacesForLines(originalStart.line, rangeStart.line); + } + else { + lineAction = + processPair(range, rangeStart.line, parent, previousRange, previousRangeStartLine, previousParent, contextNode, dynamicIndentation); + } + } + previousRange = range; + previousParent = parent; + previousRangeStartLine = rangeStart.line; + return lineAction; + } + function processPair(currentItem, currentStartLine, currentParent, previousItem, previousStartLine, previousParent, contextNode, dynamicIndentation) { + formattingContext.updateContext(previousItem, previousParent, currentItem, currentParent, contextNode); + var rule = getRule(formattingContext); + var trimTrailingWhitespaces; + var lineAction = 0 /* None */; + if (rule) { + lineAction = applyRuleEdits(rule, previousItem, previousStartLine, currentItem, currentStartLine); + switch (lineAction) { + case 2 /* LineRemoved */: + // Handle the case where the next line is moved to be the end of this line. + // In this case we don't indent the next line in the next pass. + if (currentParent.getStart(sourceFile) === currentItem.pos) { + dynamicIndentation.recomputeIndentation(/*lineAddedByFormatting*/ false); + } + break; + case 1 /* LineAdded */: + // Handle the case where token2 is moved to the new line. + // In this case we indent token2 in the next pass but we set + // sameLineIndent flag to notify the indenter that the indentation is within the line. + if (currentParent.getStart(sourceFile) === currentItem.pos) { + dynamicIndentation.recomputeIndentation(/*lineAddedByFormatting*/ true); + } + break; + default: + ts.Debug.assert(lineAction === 0 /* None */); + } + // We need to trim trailing whitespace between the tokens if they were on different lines, and no rule was applied to put them on the same line + trimTrailingWhitespaces = !(rule.action & 8 /* Delete */) && rule.flags !== 1 /* CanDeleteNewLines */; + } + else { + trimTrailingWhitespaces = true; + } + if (currentStartLine !== previousStartLine && trimTrailingWhitespaces) { + // We need to trim trailing whitespace between the tokens if they were on different lines, and no rule was applied to put them on the same line + trimTrailingWhitespacesForLines(previousStartLine, currentStartLine, previousItem); + } + return lineAction; + } + function insertIndentation(pos, indentation, lineAdded) { + var indentationString = getIndentationString(indentation, options); + if (lineAdded) { + // new line is added before the token by the formatting rules + // insert indentation string at the very beginning of the token + recordReplace(pos, 0, indentationString); + } + else { + var tokenStart = sourceFile.getLineAndCharacterOfPosition(pos); + var startLinePosition = ts.getStartPositionOfLine(tokenStart.line, sourceFile); + if (indentation !== characterToColumn(startLinePosition, tokenStart.character) || indentationIsDifferent(indentationString, startLinePosition)) { + recordReplace(startLinePosition, tokenStart.character, indentationString); + } + } + } + function characterToColumn(startLinePosition, characterInLine) { + var column = 0; + for (var i = 0; i < characterInLine; i++) { + if (sourceFile.text.charCodeAt(startLinePosition + i) === 9 /* tab */) { + column += options.tabSize - column % options.tabSize; + } + else { + column++; + } + } + return column; + } + function indentationIsDifferent(indentationString, startLinePosition) { + return indentationString !== sourceFile.text.substr(startLinePosition, indentationString.length); + } + function indentMultilineCommentOrJsxText(commentRange, indentation, firstLineIsIndented, indentFinalLine) { + if (indentFinalLine === void 0) { indentFinalLine = true; } + // split comment in lines + var startLine = sourceFile.getLineAndCharacterOfPosition(commentRange.pos).line; + var endLine = sourceFile.getLineAndCharacterOfPosition(commentRange.end).line; + if (startLine === endLine) { + if (!firstLineIsIndented) { + // treat as single line comment + insertIndentation(commentRange.pos, indentation, /*lineAdded*/ false); + } + return; + } + var parts = []; + var startPos = commentRange.pos; + for (var line = startLine; line < endLine; line++) { + var endOfLine = ts.getEndLinePosition(line, sourceFile); + parts.push({ pos: startPos, end: endOfLine }); + startPos = ts.getStartPositionOfLine(line + 1, sourceFile); + } + if (indentFinalLine) { + parts.push({ pos: startPos, end: commentRange.end }); + } + if (parts.length === 0) + return; + var startLinePos = ts.getStartPositionOfLine(startLine, sourceFile); + var nonWhitespaceColumnInFirstPart = formatting.SmartIndenter.findFirstNonWhitespaceCharacterAndColumn(startLinePos, parts[0].pos, sourceFile, options); + if (indentation === nonWhitespaceColumnInFirstPart.column) { + return; + } + var startIndex = 0; + if (firstLineIsIndented) { + startIndex = 1; + startLine++; + } + // shift all parts on the delta size + var delta = indentation - nonWhitespaceColumnInFirstPart.column; + for (var i = startIndex; i < parts.length; i++, startLine++) { + var startLinePos_1 = ts.getStartPositionOfLine(startLine, sourceFile); + var nonWhitespaceCharacterAndColumn = i === 0 + ? nonWhitespaceColumnInFirstPart + : formatting.SmartIndenter.findFirstNonWhitespaceCharacterAndColumn(parts[i].pos, parts[i].end, sourceFile, options); + var newIndentation = nonWhitespaceCharacterAndColumn.column + delta; + if (newIndentation > 0) { + var indentationString = getIndentationString(newIndentation, options); + recordReplace(startLinePos_1, nonWhitespaceCharacterAndColumn.character, indentationString); + } + else { + recordDelete(startLinePos_1, nonWhitespaceCharacterAndColumn.character); + } + } + } + function trimTrailingWhitespacesForLines(line1, line2, range) { + for (var line = line1; line < line2; line++) { + var lineStartPosition = ts.getStartPositionOfLine(line, sourceFile); + var lineEndPosition = ts.getEndLinePosition(line, sourceFile); + // do not trim whitespaces in comments or template expression + if (range && (ts.isComment(range.kind) || ts.isStringOrRegularExpressionOrTemplateLiteral(range.kind)) && range.pos <= lineEndPosition && range.end > lineEndPosition) { + continue; + } + var whitespaceStart = getTrailingWhitespaceStartPosition(lineStartPosition, lineEndPosition); + if (whitespaceStart !== -1) { + ts.Debug.assert(whitespaceStart === lineStartPosition || !ts.isWhiteSpaceSingleLine(sourceFile.text.charCodeAt(whitespaceStart - 1))); + recordDelete(whitespaceStart, lineEndPosition + 1 - whitespaceStart); + } + } + } + /** + * @param start The position of the first character in range + * @param end The position of the last character in range + */ + function getTrailingWhitespaceStartPosition(start, end) { + var pos = end; + while (pos >= start && ts.isWhiteSpaceSingleLine(sourceFile.text.charCodeAt(pos))) { + pos--; + } + if (pos !== end) { + return pos + 1; + } + return -1; + } + /** + * Trimming will be done for lines after the previous range + */ + function trimTrailingWhitespacesForRemainingRange() { + var startPosition = previousRange ? previousRange.end : originalRange.pos; + var startLine = sourceFile.getLineAndCharacterOfPosition(startPosition).line; + var endLine = sourceFile.getLineAndCharacterOfPosition(originalRange.end).line; + trimTrailingWhitespacesForLines(startLine, endLine + 1, previousRange); + } + function recordDelete(start, len) { + if (len) { + edits.push(ts.createTextChangeFromStartLength(start, len, "")); + } + } + function recordReplace(start, len, newText) { + if (len || newText) { + edits.push(ts.createTextChangeFromStartLength(start, len, newText)); + } + } + function applyRuleEdits(rule, previousRange, previousStartLine, currentRange, currentStartLine) { + var onLaterLine = currentStartLine !== previousStartLine; + switch (rule.action) { + case 1 /* Ignore */: + // no action required + return 0 /* None */; + case 8 /* Delete */: + if (previousRange.end !== currentRange.pos) { + // delete characters starting from t1.end up to t2.pos exclusive + recordDelete(previousRange.end, currentRange.pos - previousRange.end); + return onLaterLine ? 2 /* LineRemoved */ : 0 /* None */; + } + break; + case 4 /* NewLine */: + // exit early if we on different lines and rule cannot change number of newlines + // if line1 and line2 are on subsequent lines then no edits are required - ok to exit + // if line1 and line2 are separated with more than one newline - ok to exit since we cannot delete extra new lines + if (rule.flags !== 1 /* CanDeleteNewLines */ && previousStartLine !== currentStartLine) { + return 0 /* None */; + } + // edit should not be applied if we have one line feed between elements + var lineDelta = currentStartLine - previousStartLine; + if (lineDelta !== 1) { + recordReplace(previousRange.end, currentRange.pos - previousRange.end, options.newLineCharacter); + return onLaterLine ? 0 /* None */ : 1 /* LineAdded */; + } + break; + case 2 /* Space */: + // exit early if we on different lines and rule cannot change number of newlines + if (rule.flags !== 1 /* CanDeleteNewLines */ && previousStartLine !== currentStartLine) { + return 0 /* None */; + } + var posDelta = currentRange.pos - previousRange.end; + if (posDelta !== 1 || sourceFile.text.charCodeAt(previousRange.end) !== 32 /* space */) { + recordReplace(previousRange.end, currentRange.pos - previousRange.end, " "); + return onLaterLine ? 2 /* LineRemoved */ : 0 /* None */; + } + } + return 0 /* None */; + } + } + var LineAction; + (function (LineAction) { + LineAction[LineAction["None"] = 0] = "None"; + LineAction[LineAction["LineAdded"] = 1] = "LineAdded"; + LineAction[LineAction["LineRemoved"] = 2] = "LineRemoved"; + })(LineAction || (LineAction = {})); + /** + * @param precedingToken pass `null` if preceding token was already computed and result was `undefined`. + */ + function getRangeOfEnclosingComment(sourceFile, position, precedingToken, // tslint:disable-line:no-null-keyword + tokenAtPosition) { + if (tokenAtPosition === void 0) { tokenAtPosition = ts.getTokenAtPosition(sourceFile, position); } + var jsdoc = ts.findAncestor(tokenAtPosition, ts.isJSDoc); + if (jsdoc) + tokenAtPosition = jsdoc.parent; + var tokenStart = tokenAtPosition.getStart(sourceFile); + if (tokenStart <= position && position < tokenAtPosition.getEnd()) { + return undefined; + } + precedingToken = precedingToken === null ? undefined : precedingToken === undefined ? ts.findPrecedingToken(position, sourceFile) : precedingToken; + // Between two consecutive tokens, all comments are either trailing on the former + // or leading on the latter (and none are in both lists). + var trailingRangesOfPreviousToken = precedingToken && ts.getTrailingCommentRanges(sourceFile.text, precedingToken.end); + var leadingCommentRangesOfNextToken = ts.getLeadingCommentRangesOfNode(tokenAtPosition, sourceFile); + var commentRanges = ts.concatenate(trailingRangesOfPreviousToken, leadingCommentRangesOfNextToken); + return commentRanges && ts.find(commentRanges, function (range) { return ts.rangeContainsPositionExclusive(range, position) || + // The end marker of a single-line comment does not include the newline character. + // With caret at `^`, in the following case, we are inside a comment (^ denotes the cursor position): + // + // // asdf ^\n + // + // But for closed multi-line comments, we don't want to be inside the comment in the following case: + // + // /* asdf */^ + // + // However, unterminated multi-line comments *do* contain their end. + // + // Internally, we represent the end of the comment at the newline and closing '/', respectively. + // + position === range.end && (range.kind === 2 /* SingleLineCommentTrivia */ || position === sourceFile.getFullWidth()); }); + } + formatting.getRangeOfEnclosingComment = getRangeOfEnclosingComment; + function getOpenTokenForList(node, list) { + switch (node.kind) { + case 157 /* Constructor */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 197 /* ArrowFunction */: + if (node.typeParameters === list) { + return 28 /* LessThanToken */; + } + else if (node.parameters === list) { + return 20 /* OpenParenToken */; + } + break; + case 191 /* CallExpression */: + case 192 /* NewExpression */: + if (node.typeArguments === list) { + return 28 /* LessThanToken */; + } + else if (node.arguments === list) { + return 20 /* OpenParenToken */; + } + break; + case 164 /* TypeReference */: + if (node.typeArguments === list) { + return 28 /* LessThanToken */; + } + break; + case 168 /* TypeLiteral */: + return 18 /* OpenBraceToken */; + } + return 0 /* Unknown */; + } + function getCloseTokenForOpenToken(kind) { + switch (kind) { + case 20 /* OpenParenToken */: + return 21 /* CloseParenToken */; + case 28 /* LessThanToken */: + return 30 /* GreaterThanToken */; + case 18 /* OpenBraceToken */: + return 19 /* CloseBraceToken */; + } + return 0 /* Unknown */; + } + var internedSizes; + var internedTabsIndentation; + var internedSpacesIndentation; + function getIndentationString(indentation, options) { + // reset interned strings if FormatCodeOptions were changed + var resetInternedStrings = !internedSizes || (internedSizes.tabSize !== options.tabSize || internedSizes.indentSize !== options.indentSize); + if (resetInternedStrings) { + internedSizes = { tabSize: options.tabSize, indentSize: options.indentSize }; + internedTabsIndentation = internedSpacesIndentation = undefined; + } + if (!options.convertTabsToSpaces) { + var tabs = Math.floor(indentation / options.tabSize); + var spaces = indentation - tabs * options.tabSize; + var tabString = void 0; + if (!internedTabsIndentation) { + internedTabsIndentation = []; + } + if (internedTabsIndentation[tabs] === undefined) { + internedTabsIndentation[tabs] = tabString = ts.repeatString("\t", tabs); + } + else { + tabString = internedTabsIndentation[tabs]; + } + return spaces ? tabString + ts.repeatString(" ", spaces) : tabString; + } + else { + var spacesString = void 0; + var quotient = Math.floor(indentation / options.indentSize); + var remainder = indentation % options.indentSize; + if (!internedSpacesIndentation) { + internedSpacesIndentation = []; + } + if (internedSpacesIndentation[quotient] === undefined) { + spacesString = ts.repeatString(" ", options.indentSize * quotient); + internedSpacesIndentation[quotient] = spacesString; + } + else { + spacesString = internedSpacesIndentation[quotient]; + } + return remainder ? spacesString + ts.repeatString(" ", remainder) : spacesString; + } + } + formatting.getIndentationString = getIndentationString; + })(formatting = ts.formatting || (ts.formatting = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var formatting; + (function (formatting) { + var SmartIndenter; + (function (SmartIndenter) { + var Value; + (function (Value) { + Value[Value["Unknown"] = -1] = "Unknown"; + })(Value || (Value = {})); + /** + * @param assumeNewLineBeforeCloseBrace + * `false` when called on text from a real source file. + * `true` when we need to assume `position` is on a newline. + * + * This is useful for codefixes. Consider + * ``` + * function f() { + * |} + * ``` + * with `position` at `|`. + * + * When inserting some text after an open brace, we would like to get indentation as if a newline was already there. + * By default indentation at `position` will be 0 so 'assumeNewLineBeforeCloseBrace' overrides this behavior. + */ + function getIndentation(position, sourceFile, options, assumeNewLineBeforeCloseBrace) { + if (assumeNewLineBeforeCloseBrace === void 0) { assumeNewLineBeforeCloseBrace = false; } + if (position > sourceFile.text.length) { + return getBaseIndentation(options); // past EOF + } + // no indentation when the indent style is set to none, + // so we can return fast + if (options.indentStyle === ts.IndentStyle.None) { + return 0; + } + var precedingToken = ts.findPrecedingToken(position, sourceFile, /*startNode*/ undefined, /*excludeJsdoc*/ true); + var enclosingCommentRange = formatting.getRangeOfEnclosingComment(sourceFile, position, precedingToken || null); // tslint:disable-line:no-null-keyword + if (enclosingCommentRange && enclosingCommentRange.kind === 3 /* MultiLineCommentTrivia */) { + return getCommentIndent(sourceFile, position, options, enclosingCommentRange); + } + if (!precedingToken) { + return getBaseIndentation(options); + } + // no indentation in string \regex\template literals + var precedingTokenIsLiteral = ts.isStringOrRegularExpressionOrTemplateLiteral(precedingToken.kind); + if (precedingTokenIsLiteral && precedingToken.getStart(sourceFile) <= position && position < precedingToken.end) { + return 0; + } + var lineAtPosition = sourceFile.getLineAndCharacterOfPosition(position).line; + // indentation is first non-whitespace character in a previous line + // for block indentation, we should look for a line which contains something that's not + // whitespace. + if (options.indentStyle === ts.IndentStyle.Block) { + return getBlockIndent(sourceFile, position, options); + } + if (precedingToken.kind === 27 /* CommaToken */ && precedingToken.parent.kind !== 204 /* BinaryExpression */) { + // previous token is comma that separates items in list - find the previous item and try to derive indentation from it + var actualIndentation = getActualIndentationForListItemBeforeComma(precedingToken, sourceFile, options); + if (actualIndentation !== -1 /* Unknown */) { + return actualIndentation; + } + } + var containerList = getListByPosition(position, precedingToken.parent, sourceFile); + // use list position if the preceding token is before any list items + if (containerList && !ts.rangeContainsRange(containerList, precedingToken)) { + return getActualIndentationForListStartLine(containerList, sourceFile, options) + options.indentSize; // TODO: GH#18217 + } + return getSmartIndent(sourceFile, position, precedingToken, lineAtPosition, assumeNewLineBeforeCloseBrace, options); + } + SmartIndenter.getIndentation = getIndentation; + function getCommentIndent(sourceFile, position, options, enclosingCommentRange) { + var previousLine = ts.getLineAndCharacterOfPosition(sourceFile, position).line - 1; + var commentStartLine = ts.getLineAndCharacterOfPosition(sourceFile, enclosingCommentRange.pos).line; + ts.Debug.assert(commentStartLine >= 0); + if (previousLine <= commentStartLine) { + return findFirstNonWhitespaceColumn(ts.getStartPositionOfLine(commentStartLine, sourceFile), position, sourceFile, options); + } + var startPositionOfLine = ts.getStartPositionOfLine(previousLine, sourceFile); + var _a = findFirstNonWhitespaceCharacterAndColumn(startPositionOfLine, position, sourceFile, options), column = _a.column, character = _a.character; + if (column === 0) { + return column; + } + var firstNonWhitespaceCharacterCode = sourceFile.text.charCodeAt(startPositionOfLine + character); + return firstNonWhitespaceCharacterCode === 42 /* asterisk */ ? column - 1 : column; + } + function getBlockIndent(sourceFile, position, options) { + // move backwards until we find a line with a non-whitespace character, + // then find the first non-whitespace character for that line. + var current = position; + while (current > 0) { + var char = sourceFile.text.charCodeAt(current); + if (!ts.isWhiteSpaceLike(char)) { + break; + } + current--; + } + var lineStart = ts.getLineStartPositionForPosition(current, sourceFile); + return findFirstNonWhitespaceColumn(lineStart, current, sourceFile, options); + } + function getSmartIndent(sourceFile, position, precedingToken, lineAtPosition, assumeNewLineBeforeCloseBrace, options) { + // try to find node that can contribute to indentation and includes 'position' starting from 'precedingToken' + // if such node is found - compute initial indentation for 'position' inside this node + var previous; + var current = precedingToken; + while (current) { + if (ts.positionBelongsToNode(current, position, sourceFile) && shouldIndentChildNode(options, current, previous, sourceFile, /*isNextChild*/ true)) { + var currentStart = getStartLineAndCharacterForNode(current, sourceFile); + var nextTokenKind = nextTokenIsCurlyBraceOnSameLineAsCursor(precedingToken, current, lineAtPosition, sourceFile); + var indentationDelta = nextTokenKind !== 0 /* Unknown */ + // handle cases when codefix is about to be inserted before the close brace + ? assumeNewLineBeforeCloseBrace && nextTokenKind === 2 /* CloseBrace */ ? options.indentSize : 0 + : lineAtPosition !== currentStart.line ? options.indentSize : 0; + return getIndentationForNodeWorker(current, currentStart, /*ignoreActualIndentationRange*/ undefined, indentationDelta, sourceFile, /*isNextChild*/ true, options); // TODO: GH#18217 + } + // check if current node is a list item - if yes, take indentation from it + // do not consider parent-child line sharing yet: + // function foo(a + // | preceding node 'a' does share line with its parent but indentation is expected + var actualIndentation = getActualIndentationForListItem(current, sourceFile, options, /*listIndentsChild*/ true); + if (actualIndentation !== -1 /* Unknown */) { + return actualIndentation; + } + previous = current; + current = current.parent; + } + // no parent was found - return the base indentation of the SourceFile + return getBaseIndentation(options); + } + function getIndentationForNode(n, ignoreActualIndentationRange, sourceFile, options) { + var start = sourceFile.getLineAndCharacterOfPosition(n.getStart(sourceFile)); + return getIndentationForNodeWorker(n, start, ignoreActualIndentationRange, /*indentationDelta*/ 0, sourceFile, /*isNextChild*/ false, options); + } + SmartIndenter.getIndentationForNode = getIndentationForNode; + function getBaseIndentation(options) { + return options.baseIndentSize || 0; + } + SmartIndenter.getBaseIndentation = getBaseIndentation; + function getIndentationForNodeWorker(current, currentStart, ignoreActualIndentationRange, indentationDelta, sourceFile, isNextChild, options) { + var parent = current.parent; + // Walk up the tree and collect indentation for parent-child node pairs. Indentation is not added if + // * parent and child nodes start on the same line, or + // * parent is an IfStatement and child starts on the same line as an 'else clause'. + while (parent) { + var useActualIndentation = true; + if (ignoreActualIndentationRange) { + var start = current.getStart(sourceFile); + useActualIndentation = start < ignoreActualIndentationRange.pos || start > ignoreActualIndentationRange.end; + } + var containingListOrParentStart = getContainingListOrParentStart(parent, current, sourceFile); + var parentAndChildShareLine = containingListOrParentStart.line === currentStart.line || + childStartsOnTheSameLineWithElseInIfStatement(parent, current, currentStart.line, sourceFile); + if (useActualIndentation) { + // check if current node is a list item - if yes, take indentation from it + var actualIndentation = getActualIndentationForListItem(current, sourceFile, options, !parentAndChildShareLine); + if (actualIndentation !== -1 /* Unknown */) { + return actualIndentation + indentationDelta; + } + // try to fetch actual indentation for current node from source text + actualIndentation = getActualIndentationForNode(current, parent, currentStart, parentAndChildShareLine, sourceFile, options); + if (actualIndentation !== -1 /* Unknown */) { + return actualIndentation + indentationDelta; + } + } + // increase indentation if parent node wants its content to be indented and parent and child nodes don't start on the same line + if (shouldIndentChildNode(options, parent, current, sourceFile, isNextChild) && !parentAndChildShareLine) { + indentationDelta += options.indentSize; + } + // In our AST, a call argument's `parent` is the call-expression, not the argument list. + // We would like to increase indentation based on the relationship between an argument and its argument-list, + // so we spoof the starting position of the (parent) call-expression to match the (non-parent) argument-list. + // But, the spoofed start-value could then cause a problem when comparing the start position of the call-expression + // to *its* parent (in the case of an iife, an expression statement), adding an extra level of indentation. + // + // Instead, when at an argument, we unspoof the starting position of the enclosing call expression + // *after* applying indentation for the argument. + var useTrueStart = isArgumentAndStartLineOverlapsExpressionBeingCalled(parent, current, currentStart.line, sourceFile); + current = parent; + parent = current.parent; + currentStart = useTrueStart ? sourceFile.getLineAndCharacterOfPosition(current.getStart(sourceFile)) : containingListOrParentStart; + } + return indentationDelta + getBaseIndentation(options); + } + function getContainingListOrParentStart(parent, child, sourceFile) { + var containingList = getContainingList(child, sourceFile); + var startPos = containingList ? containingList.pos : parent.getStart(sourceFile); + return sourceFile.getLineAndCharacterOfPosition(startPos); + } + /* + * Function returns Value.Unknown if indentation cannot be determined + */ + function getActualIndentationForListItemBeforeComma(commaToken, sourceFile, options) { + // previous token is comma that separates items in list - find the previous item and try to derive indentation from it + var commaItemInfo = ts.findListItemInfo(commaToken); + if (commaItemInfo && commaItemInfo.listItemIndex > 0) { + return deriveActualIndentationFromList(commaItemInfo.list.getChildren(), commaItemInfo.listItemIndex - 1, sourceFile, options); + } + else { + // handle broken code gracefully + return -1 /* Unknown */; + } + } + /* + * Function returns Value.Unknown if actual indentation for node should not be used (i.e because node is nested expression) + */ + function getActualIndentationForNode(current, parent, currentLineAndChar, parentAndChildShareLine, sourceFile, options) { + // actual indentation is used for statements\declarations if one of cases below is true: + // - parent is SourceFile - by default immediate children of SourceFile are not indented except when user indents them manually + // - parent and child are not on the same line + var useActualIndentation = (ts.isDeclaration(current) || ts.isStatementButNotDeclaration(current)) && + (parent.kind === 279 /* SourceFile */ || !parentAndChildShareLine); + if (!useActualIndentation) { + return -1 /* Unknown */; + } + return findColumnForFirstNonWhitespaceCharacterInLine(currentLineAndChar, sourceFile, options); + } + var NextTokenKind; + (function (NextTokenKind) { + NextTokenKind[NextTokenKind["Unknown"] = 0] = "Unknown"; + NextTokenKind[NextTokenKind["OpenBrace"] = 1] = "OpenBrace"; + NextTokenKind[NextTokenKind["CloseBrace"] = 2] = "CloseBrace"; + })(NextTokenKind || (NextTokenKind = {})); + function nextTokenIsCurlyBraceOnSameLineAsCursor(precedingToken, current, lineAtPosition, sourceFile) { + var nextToken = ts.findNextToken(precedingToken, current, sourceFile); + if (!nextToken) { + return 0 /* Unknown */; + } + if (nextToken.kind === 18 /* OpenBraceToken */) { + // open braces are always indented at the parent level + return 1 /* OpenBrace */; + } + else if (nextToken.kind === 19 /* CloseBraceToken */) { + // close braces are indented at the parent level if they are located on the same line with cursor + // this means that if new line will be added at $ position, this case will be indented + // class A { + // $ + // } + /// and this one - not + // class A { + // $} + var nextTokenStartLine = getStartLineAndCharacterForNode(nextToken, sourceFile).line; + return lineAtPosition === nextTokenStartLine ? 2 /* CloseBrace */ : 0 /* Unknown */; + } + return 0 /* Unknown */; + } + function getStartLineAndCharacterForNode(n, sourceFile) { + return sourceFile.getLineAndCharacterOfPosition(n.getStart(sourceFile)); + } + function isArgumentAndStartLineOverlapsExpressionBeingCalled(parent, child, childStartLine, sourceFile) { + if (!(ts.isCallExpression(parent) && ts.contains(parent.arguments, child))) { + return false; + } + var expressionOfCallExpressionEnd = parent.expression.getEnd(); + var expressionOfCallExpressionEndLine = ts.getLineAndCharacterOfPosition(sourceFile, expressionOfCallExpressionEnd).line; + return expressionOfCallExpressionEndLine === childStartLine; + } + SmartIndenter.isArgumentAndStartLineOverlapsExpressionBeingCalled = isArgumentAndStartLineOverlapsExpressionBeingCalled; + function childStartsOnTheSameLineWithElseInIfStatement(parent, child, childStartLine, sourceFile) { + if (parent.kind === 222 /* IfStatement */ && parent.elseStatement === child) { + var elseKeyword = ts.findChildOfKind(parent, 83 /* ElseKeyword */, sourceFile); + ts.Debug.assert(elseKeyword !== undefined); + var elseKeywordStartLine = getStartLineAndCharacterForNode(elseKeyword, sourceFile).line; + return elseKeywordStartLine === childStartLine; + } + return false; + } + SmartIndenter.childStartsOnTheSameLineWithElseInIfStatement = childStartsOnTheSameLineWithElseInIfStatement; + function getContainingList(node, sourceFile) { + return node.parent && getListByRange(node.getStart(sourceFile), node.getEnd(), node.parent, sourceFile); + } + SmartIndenter.getContainingList = getContainingList; + function getListByPosition(pos, node, sourceFile) { + return node && getListByRange(pos, pos, node, sourceFile); + } + function getListByRange(start, end, node, sourceFile) { + switch (node.kind) { + case 164 /* TypeReference */: + return getList(node.typeArguments); + case 188 /* ObjectLiteralExpression */: + return getList(node.properties); + case 187 /* ArrayLiteralExpression */: + return getList(node.elements); + case 168 /* TypeLiteral */: + return getList(node.members); + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 160 /* CallSignature */: + case 157 /* Constructor */: + case 166 /* ConstructorType */: + case 161 /* ConstructSignature */: + return getList(node.typeParameters) || getList(node.parameters); + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 241 /* InterfaceDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 303 /* JSDocTemplateTag */: + return getList(node.typeParameters); + case 192 /* NewExpression */: + case 191 /* CallExpression */: + return getList(node.typeArguments) || getList(node.arguments); + case 238 /* VariableDeclarationList */: + return getList(node.declarations); + case 252 /* NamedImports */: + case 256 /* NamedExports */: + return getList(node.elements); + case 184 /* ObjectBindingPattern */: + case 185 /* ArrayBindingPattern */: + return getList(node.elements); + } + function getList(list) { + return list && ts.rangeContainsStartEnd(getVisualListRange(node, list, sourceFile), start, end) ? list : undefined; + } + } + function getVisualListRange(node, list, sourceFile) { + var children = node.getChildren(sourceFile); + for (var i = 1; i < children.length - 1; i++) { + if (children[i].pos === list.pos && children[i].end === list.end) { + return { pos: children[i - 1].end, end: children[i + 1].getStart(sourceFile) }; + } + } + return list; + } + function getActualIndentationForListStartLine(list, sourceFile, options) { + if (!list) { + return -1 /* Unknown */; + } + return findColumnForFirstNonWhitespaceCharacterInLine(sourceFile.getLineAndCharacterOfPosition(list.pos), sourceFile, options); + } + function getActualIndentationForListItem(node, sourceFile, options, listIndentsChild) { + if (node.parent && node.parent.kind === 238 /* VariableDeclarationList */) { + // VariableDeclarationList has no wrapping tokens + return -1 /* Unknown */; + } + var containingList = getContainingList(node, sourceFile); + if (containingList) { + var index = containingList.indexOf(node); + if (index !== -1) { + var result = deriveActualIndentationFromList(containingList, index, sourceFile, options); + if (result !== -1 /* Unknown */) { + return result; + } + } + return getActualIndentationForListStartLine(containingList, sourceFile, options) + (listIndentsChild ? options.indentSize : 0); // TODO: GH#18217 + } + return -1 /* Unknown */; + } + function deriveActualIndentationFromList(list, index, sourceFile, options) { + ts.Debug.assert(index >= 0 && index < list.length); + var node = list[index]; + // walk toward the start of the list starting from current node and check if the line is the same for all items. + // if end line for item [i - 1] differs from the start line for item [i] - find column of the first non-whitespace character on the line of item [i] + var lineAndCharacter = getStartLineAndCharacterForNode(node, sourceFile); + for (var i = index - 1; i >= 0; i--) { + if (list[i].kind === 27 /* CommaToken */) { + continue; + } + // skip list items that ends on the same line with the current list element + var prevEndLine = sourceFile.getLineAndCharacterOfPosition(list[i].end).line; + if (prevEndLine !== lineAndCharacter.line) { + return findColumnForFirstNonWhitespaceCharacterInLine(lineAndCharacter, sourceFile, options); + } + lineAndCharacter = getStartLineAndCharacterForNode(list[i], sourceFile); + } + return -1 /* Unknown */; + } + function findColumnForFirstNonWhitespaceCharacterInLine(lineAndCharacter, sourceFile, options) { + var lineStart = sourceFile.getPositionOfLineAndCharacter(lineAndCharacter.line, 0); + return findFirstNonWhitespaceColumn(lineStart, lineStart + lineAndCharacter.character, sourceFile, options); + } + /** + * Character is the actual index of the character since the beginning of the line. + * Column - position of the character after expanding tabs to spaces. + * "0\t2$" + * value of 'character' for '$' is 3 + * value of 'column' for '$' is 6 (assuming that tab size is 4) + */ + function findFirstNonWhitespaceCharacterAndColumn(startPos, endPos, sourceFile, options) { + var character = 0; + var column = 0; + for (var pos = startPos; pos < endPos; pos++) { + var ch = sourceFile.text.charCodeAt(pos); + if (!ts.isWhiteSpaceSingleLine(ch)) { + break; + } + if (ch === 9 /* tab */) { + column += options.tabSize + (column % options.tabSize); + } + else { + column++; + } + character++; + } + return { column: column, character: character }; + } + SmartIndenter.findFirstNonWhitespaceCharacterAndColumn = findFirstNonWhitespaceCharacterAndColumn; + function findFirstNonWhitespaceColumn(startPos, endPos, sourceFile, options) { + return findFirstNonWhitespaceCharacterAndColumn(startPos, endPos, sourceFile, options).column; + } + SmartIndenter.findFirstNonWhitespaceColumn = findFirstNonWhitespaceColumn; + function nodeWillIndentChild(settings, parent, child, sourceFile, indentByDefault) { + var childKind = child ? child.kind : 0 /* Unknown */; + switch (parent.kind) { + case 221 /* ExpressionStatement */: + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 241 /* InterfaceDeclaration */: + case 243 /* EnumDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 187 /* ArrayLiteralExpression */: + case 218 /* Block */: + case 245 /* ModuleBlock */: + case 188 /* ObjectLiteralExpression */: + case 168 /* TypeLiteral */: + case 181 /* MappedType */: + case 170 /* TupleType */: + case 246 /* CaseBlock */: + case 272 /* DefaultClause */: + case 271 /* CaseClause */: + case 195 /* ParenthesizedExpression */: + case 189 /* PropertyAccessExpression */: + case 191 /* CallExpression */: + case 192 /* NewExpression */: + case 219 /* VariableStatement */: + case 254 /* ExportAssignment */: + case 230 /* ReturnStatement */: + case 205 /* ConditionalExpression */: + case 185 /* ArrayBindingPattern */: + case 184 /* ObjectBindingPattern */: + case 262 /* JsxOpeningElement */: + case 265 /* JsxOpeningFragment */: + case 261 /* JsxSelfClosingElement */: + case 270 /* JsxExpression */: + case 155 /* MethodSignature */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 151 /* Parameter */: + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + case 177 /* ParenthesizedType */: + case 193 /* TaggedTemplateExpression */: + case 201 /* AwaitExpression */: + case 256 /* NamedExports */: + case 252 /* NamedImports */: + case 257 /* ExportSpecifier */: + case 253 /* ImportSpecifier */: + case 154 /* PropertyDeclaration */: + return true; + case 237 /* VariableDeclaration */: + case 275 /* PropertyAssignment */: + if (!settings.indentMultiLineObjectLiteralBeginningOnBlankLine && sourceFile && childKind === 188 /* ObjectLiteralExpression */) { // TODO: GH#18217 + return rangeIsOnOneLine(sourceFile, child); + } + return true; + case 223 /* DoStatement */: + case 224 /* WhileStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + case 225 /* ForStatement */: + case 222 /* IfStatement */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 156 /* MethodDeclaration */: + case 197 /* ArrowFunction */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + return childKind !== 218 /* Block */; + case 255 /* ExportDeclaration */: + return childKind !== 256 /* NamedExports */; + case 249 /* ImportDeclaration */: + return childKind !== 250 /* ImportClause */ || + (!!child.namedBindings && child.namedBindings.kind !== 252 /* NamedImports */); + case 260 /* JsxElement */: + return childKind !== 263 /* JsxClosingElement */; + case 264 /* JsxFragment */: + return childKind !== 266 /* JsxClosingFragment */; + case 174 /* IntersectionType */: + case 173 /* UnionType */: + if (childKind === 168 /* TypeLiteral */) { + return false; + } + // falls through + } + // No explicit rule for given nodes so the result will follow the default value argument + return indentByDefault; + } + SmartIndenter.nodeWillIndentChild = nodeWillIndentChild; + function isControlFlowEndingStatement(kind, parent) { + switch (kind) { + case 230 /* ReturnStatement */: + case 234 /* ThrowStatement */: + case 228 /* ContinueStatement */: + case 229 /* BreakStatement */: + return parent.kind !== 218 /* Block */; + default: + return false; + } + } + /** + * True when the parent node should indent the given child by an explicit rule. + * @param isNextChild If true, we are judging indent of a hypothetical child *after* this one, not the current child. + */ + function shouldIndentChildNode(settings, parent, child, sourceFile, isNextChild) { + if (isNextChild === void 0) { isNextChild = false; } + return nodeWillIndentChild(settings, parent, child, sourceFile, /*indentByDefault*/ false) + && !(isNextChild && child && isControlFlowEndingStatement(child.kind, parent)); + } + SmartIndenter.shouldIndentChildNode = shouldIndentChildNode; + function rangeIsOnOneLine(sourceFile, range) { + var rangeStart = ts.skipTrivia(sourceFile.text, range.pos); + var startLine = sourceFile.getLineAndCharacterOfPosition(rangeStart).line; + var endLine = sourceFile.getLineAndCharacterOfPosition(range.end).line; + return startLine === endLine; + } + })(SmartIndenter = formatting.SmartIndenter || (formatting.SmartIndenter = {})); + })(formatting = ts.formatting || (ts.formatting = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var textChanges; + (function (textChanges_3) { + /** + * Currently for simplicity we store recovered positions on the node itself. + * It can be changed to side-table later if we decide that current design is too invasive. + */ + function getPos(n) { + var result = n.__pos; + ts.Debug.assert(typeof result === "number"); + return result; + } + function setPos(n, pos) { + ts.Debug.assert(typeof pos === "number"); + n.__pos = pos; + } + function getEnd(n) { + var result = n.__end; + ts.Debug.assert(typeof result === "number"); + return result; + } + function setEnd(n, end) { + ts.Debug.assert(typeof end === "number"); + n.__end = end; + } + var Position; + (function (Position) { + Position[Position["FullStart"] = 0] = "FullStart"; + Position[Position["Start"] = 1] = "Start"; + })(Position = textChanges_3.Position || (textChanges_3.Position = {})); + function skipWhitespacesAndLineBreaks(text, start) { + return ts.skipTrivia(text, start, /*stopAfterLineBreak*/ false, /*stopAtComments*/ true); + } + function hasCommentsBeforeLineBreak(text, start) { + var i = start; + while (i < text.length) { + var ch = text.charCodeAt(i); + if (ts.isWhiteSpaceSingleLine(ch)) { + i++; + continue; + } + return ch === 47 /* slash */; + } + return false; + } + textChanges_3.useNonAdjustedPositions = { + useNonAdjustedStartPosition: true, + useNonAdjustedEndPosition: true, + }; + var ChangeKind; + (function (ChangeKind) { + ChangeKind[ChangeKind["Remove"] = 0] = "Remove"; + ChangeKind[ChangeKind["ReplaceWithSingleNode"] = 1] = "ReplaceWithSingleNode"; + ChangeKind[ChangeKind["ReplaceWithMultipleNodes"] = 2] = "ReplaceWithMultipleNodes"; + ChangeKind[ChangeKind["Text"] = 3] = "Text"; + })(ChangeKind || (ChangeKind = {})); + function getAdjustedRange(sourceFile, startNode, endNode, options) { + return { pos: getAdjustedStartPosition(sourceFile, startNode, options, Position.Start), end: getAdjustedEndPosition(sourceFile, endNode, options) }; + } + function getAdjustedStartPosition(sourceFile, node, options, position) { + if (options.useNonAdjustedStartPosition) { + return node.getStart(sourceFile); + } + var fullStart = node.getFullStart(); + var start = node.getStart(sourceFile); + if (fullStart === start) { + return start; + } + var fullStartLine = ts.getLineStartPositionForPosition(fullStart, sourceFile); + var startLine = ts.getLineStartPositionForPosition(start, sourceFile); + if (startLine === fullStartLine) { + // full start and start of the node are on the same line + // a, b; + // ^ ^ + // | start + // fullstart + // when b is replaced - we usually want to keep the leading trvia + // when b is deleted - we delete it + return position === Position.Start ? start : fullStart; + } + // get start position of the line following the line that contains fullstart position + // (but only if the fullstart isn't the very beginning of the file) + var nextLineStart = fullStart > 0 ? 1 : 0; + var adjustedStartPosition = ts.getStartPositionOfLine(ts.getLineOfLocalPosition(sourceFile, fullStartLine) + nextLineStart, sourceFile); + // skip whitespaces/newlines + adjustedStartPosition = skipWhitespacesAndLineBreaks(sourceFile.text, adjustedStartPosition); + return ts.getStartPositionOfLine(ts.getLineOfLocalPosition(sourceFile, adjustedStartPosition), sourceFile); + } + function getAdjustedEndPosition(sourceFile, node, options) { + var end = node.end; + if (options.useNonAdjustedEndPosition || ts.isExpression(node)) { + return end; + } + var newEnd = ts.skipTrivia(sourceFile.text, end, /*stopAfterLineBreak*/ true); + return newEnd !== end && ts.isLineBreak(sourceFile.text.charCodeAt(newEnd - 1)) + ? newEnd + : end; + } + /** + * Checks if 'candidate' argument is a legal separator in the list that contains 'node' as an element + */ + function isSeparator(node, candidate) { + return !!candidate && !!node.parent && (candidate.kind === 27 /* CommaToken */ || (candidate.kind === 26 /* SemicolonToken */ && node.parent.kind === 188 /* ObjectLiteralExpression */)); + } + function spaces(count) { + var s = ""; + for (var i = 0; i < count; i++) { + s += " "; + } + return s; + } + var ChangeTracker = /** @class */ (function () { + /** Public for tests only. Other callers should use `ChangeTracker.with`. */ + function ChangeTracker(newLineCharacter, formatContext) { + this.newLineCharacter = newLineCharacter; + this.formatContext = formatContext; + this.changes = []; + this.newFiles = []; + this.classesWithNodesInsertedAtStart = ts.createMap(); // Set implemented as Map + this.deletedNodes = []; + } + ChangeTracker.fromContext = function (context) { + return new ChangeTracker(ts.getNewLineOrDefaultFromHost(context.host, context.formatContext.options), context.formatContext); + }; + ChangeTracker.with = function (context, cb) { + var tracker = ChangeTracker.fromContext(context); + cb(tracker); + return tracker.getChanges(); + }; + ChangeTracker.prototype.deleteRange = function (sourceFile, range) { + this.changes.push({ kind: ChangeKind.Remove, sourceFile: sourceFile, range: range }); + }; + ChangeTracker.prototype.delete = function (sourceFile, node) { + this.deletedNodes.push({ sourceFile: sourceFile, node: node }); + }; + ChangeTracker.prototype.deleteModifier = function (sourceFile, modifier) { + this.deleteRange(sourceFile, { pos: modifier.getStart(sourceFile), end: ts.skipTrivia(sourceFile.text, modifier.end, /*stopAfterLineBreak*/ true) }); + }; + ChangeTracker.prototype.deleteNodeRange = function (sourceFile, startNode, endNode, options) { + if (options === void 0) { options = {}; } + var startPosition = getAdjustedStartPosition(sourceFile, startNode, options, Position.FullStart); + var endPosition = getAdjustedEndPosition(sourceFile, endNode, options); + this.deleteRange(sourceFile, { pos: startPosition, end: endPosition }); + }; + ChangeTracker.prototype.deleteNodeRangeExcludingEnd = function (sourceFile, startNode, afterEndNode, options) { + if (options === void 0) { options = {}; } + var startPosition = getAdjustedStartPosition(sourceFile, startNode, options, Position.FullStart); + var endPosition = afterEndNode === undefined ? sourceFile.text.length : getAdjustedStartPosition(sourceFile, afterEndNode, options, Position.FullStart); + this.deleteRange(sourceFile, { pos: startPosition, end: endPosition }); + }; + ChangeTracker.prototype.replaceRange = function (sourceFile, range, newNode, options) { + if (options === void 0) { options = {}; } + this.changes.push({ kind: ChangeKind.ReplaceWithSingleNode, sourceFile: sourceFile, range: range, options: options, node: newNode }); + }; + ChangeTracker.prototype.replaceNode = function (sourceFile, oldNode, newNode, options) { + if (options === void 0) { options = textChanges_3.useNonAdjustedPositions; } + this.replaceRange(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, options), newNode, options); + }; + ChangeTracker.prototype.replaceNodeRange = function (sourceFile, startNode, endNode, newNode, options) { + if (options === void 0) { options = textChanges_3.useNonAdjustedPositions; } + this.replaceRange(sourceFile, getAdjustedRange(sourceFile, startNode, endNode, options), newNode, options); + }; + ChangeTracker.prototype.replaceRangeWithNodes = function (sourceFile, range, newNodes, options) { + if (options === void 0) { options = {}; } + this.changes.push({ kind: ChangeKind.ReplaceWithMultipleNodes, sourceFile: sourceFile, range: range, options: options, nodes: newNodes }); + }; + ChangeTracker.prototype.replaceNodeWithNodes = function (sourceFile, oldNode, newNodes, options) { + if (options === void 0) { options = textChanges_3.useNonAdjustedPositions; } + this.replaceRangeWithNodes(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, options), newNodes, options); + }; + ChangeTracker.prototype.replaceNodeWithText = function (sourceFile, oldNode, text) { + this.replaceRangeWithText(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, textChanges_3.useNonAdjustedPositions), text); + }; + ChangeTracker.prototype.replaceNodeRangeWithNodes = function (sourceFile, startNode, endNode, newNodes, options) { + if (options === void 0) { options = textChanges_3.useNonAdjustedPositions; } + this.replaceRangeWithNodes(sourceFile, getAdjustedRange(sourceFile, startNode, endNode, options), newNodes, options); + }; + ChangeTracker.prototype.nextCommaToken = function (sourceFile, node) { + var next = ts.findNextToken(node, node.parent, sourceFile); + return next && next.kind === 27 /* CommaToken */ ? next : undefined; + }; + ChangeTracker.prototype.replacePropertyAssignment = function (sourceFile, oldNode, newNode) { + var suffix = this.nextCommaToken(sourceFile, oldNode) ? "" : ("," + this.newLineCharacter); + this.replaceNode(sourceFile, oldNode, newNode, { suffix: suffix }); + }; + ChangeTracker.prototype.insertNodeAt = function (sourceFile, pos, newNode, options) { + if (options === void 0) { options = {}; } + this.replaceRange(sourceFile, ts.createRange(pos), newNode, options); + }; + ChangeTracker.prototype.insertNodesAt = function (sourceFile, pos, newNodes, options) { + if (options === void 0) { options = {}; } + this.replaceRangeWithNodes(sourceFile, ts.createRange(pos), newNodes, options); + }; + ChangeTracker.prototype.insertNodeAtTopOfFile = function (sourceFile, newNode, blankLineBetween) { + var pos = getInsertionPositionAtSourceFileTop(sourceFile); + this.insertNodeAt(sourceFile, pos, newNode, { + prefix: pos === 0 ? undefined : this.newLineCharacter, + suffix: (ts.isLineBreak(sourceFile.text.charCodeAt(pos)) ? "" : this.newLineCharacter) + (blankLineBetween ? this.newLineCharacter : ""), + }); + }; + ChangeTracker.prototype.insertNodeBefore = function (sourceFile, before, newNode, blankLineBetween) { + if (blankLineBetween === void 0) { blankLineBetween = false; } + this.insertNodeAt(sourceFile, getAdjustedStartPosition(sourceFile, before, {}, Position.Start), newNode, this.getOptionsForInsertNodeBefore(before, blankLineBetween)); + }; + ChangeTracker.prototype.insertModifierBefore = function (sourceFile, modifier, before) { + var pos = before.getStart(sourceFile); + this.insertNodeAt(sourceFile, pos, ts.createToken(modifier), { suffix: " " }); + }; + ChangeTracker.prototype.insertLastModifierBefore = function (sourceFile, modifier, before) { + if (!before.modifiers) { + this.insertModifierBefore(sourceFile, modifier, before); + return; + } + var pos = before.modifiers.end; + this.insertNodeAt(sourceFile, pos, ts.createToken(modifier), { prefix: " " }); + }; + ChangeTracker.prototype.insertCommentBeforeLine = function (sourceFile, lineNumber, position, commentText) { + var lineStartPosition = ts.getStartPositionOfLine(lineNumber, sourceFile); + var startPosition = ts.getFirstNonSpaceCharacterPosition(sourceFile.text, lineStartPosition); + // First try to see if we can put the comment on the previous line. + // We need to make sure that we are not in the middle of a string literal or a comment. + // If so, we do not want to separate the node from its comment if we can. + // Otherwise, add an extra new line immediately before the error span. + var insertAtLineStart = isValidLocationToAddComment(sourceFile, startPosition); + var token = ts.getTouchingToken(sourceFile, insertAtLineStart ? startPosition : position); + var indent = sourceFile.text.slice(lineStartPosition, startPosition); + var text = (insertAtLineStart ? "" : this.newLineCharacter) + "//" + commentText + this.newLineCharacter + indent; + this.insertText(sourceFile, token.getStart(sourceFile), text); + }; + ChangeTracker.prototype.insertJsdocCommentBefore = function (sourceFile, node, tag) { + var fnStart = node.getStart(sourceFile); + if (node.jsDoc) { + for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { + var jsdoc = _a[_i]; + this.deleteRange(sourceFile, { + pos: ts.getLineStartPositionForPosition(jsdoc.getStart(sourceFile), sourceFile), + end: getAdjustedEndPosition(sourceFile, jsdoc, /*options*/ {}) + }); + } + } + var startPosition = ts.getPrecedingNonSpaceCharacterPosition(sourceFile.text, fnStart - 1); + var indent = sourceFile.text.slice(startPosition, fnStart); + this.insertNodeAt(sourceFile, fnStart, tag, { preserveLeadingWhitespace: false, suffix: this.newLineCharacter + indent }); + }; + ChangeTracker.prototype.replaceRangeWithText = function (sourceFile, range, text) { + this.changes.push({ kind: ChangeKind.Text, sourceFile: sourceFile, range: range, text: text }); + }; + ChangeTracker.prototype.insertText = function (sourceFile, pos, text) { + this.replaceRangeWithText(sourceFile, ts.createRange(pos), text); + }; + /** Prefer this over replacing a node with another that has a type annotation, as it avoids reformatting the other parts of the node. */ + ChangeTracker.prototype.tryInsertTypeAnnotation = function (sourceFile, node, type) { + var endNode; + if (ts.isFunctionLike(node)) { + endNode = ts.findChildOfKind(node, 21 /* CloseParenToken */, sourceFile); + if (!endNode) { + if (!ts.isArrowFunction(node)) + return; // Function missing parentheses, give up + // If no `)`, is an arrow function `x => x`, so use the end of the first parameter + endNode = ts.first(node.parameters); + } + } + else { + endNode = node.kind !== 237 /* VariableDeclaration */ && node.questionToken ? node.questionToken : node.name; + } + this.insertNodeAt(sourceFile, endNode.end, type, { prefix: ": " }); + }; + ChangeTracker.prototype.insertTypeParameters = function (sourceFile, node, typeParameters) { + // If no `(`, is an arrow function `x => x`, so use the pos of the first parameter + var start = (ts.findChildOfKind(node, 20 /* OpenParenToken */, sourceFile) || ts.first(node.parameters)).getStart(sourceFile); + this.insertNodesAt(sourceFile, start, typeParameters, { prefix: "<", suffix: ">" }); + }; + ChangeTracker.prototype.getOptionsForInsertNodeBefore = function (before, doubleNewlines) { + if (ts.isStatement(before) || ts.isClassElement(before)) { + return { suffix: doubleNewlines ? this.newLineCharacter + this.newLineCharacter : this.newLineCharacter }; + } + else if (ts.isVariableDeclaration(before)) { // insert `x = 1, ` into `const x = 1, y = 2; + return { suffix: ", " }; + } + else if (ts.isParameter(before)) { + return {}; + } + else if (ts.isStringLiteral(before) && ts.isImportDeclaration(before.parent) || ts.isNamedImports(before)) { + return { suffix: ", " }; + } + return ts.Debug.failBadSyntaxKind(before); // We haven't handled this kind of node yet -- add it + }; + ChangeTracker.prototype.insertNodeAtConstructorStart = function (sourceFile, ctr, newStatement) { + var firstStatement = ts.firstOrUndefined(ctr.body.statements); + if (!firstStatement || !ctr.body.multiLine) { + this.replaceConstructorBody(sourceFile, ctr, [newStatement].concat(ctr.body.statements)); + } + else { + this.insertNodeBefore(sourceFile, firstStatement, newStatement); + } + }; + ChangeTracker.prototype.insertNodeAtConstructorEnd = function (sourceFile, ctr, newStatement) { + var lastStatement = ts.lastOrUndefined(ctr.body.statements); + if (!lastStatement || !ctr.body.multiLine) { + this.replaceConstructorBody(sourceFile, ctr, ctr.body.statements.concat([newStatement])); + } + else { + this.insertNodeAfter(sourceFile, lastStatement, newStatement); + } + }; + ChangeTracker.prototype.replaceConstructorBody = function (sourceFile, ctr, statements) { + this.replaceNode(sourceFile, ctr.body, ts.createBlock(statements, /*multiLine*/ true)); + }; + ChangeTracker.prototype.insertNodeAtEndOfScope = function (sourceFile, scope, newNode) { + var pos = getAdjustedStartPosition(sourceFile, scope.getLastToken(), {}, Position.Start); + this.insertNodeAt(sourceFile, pos, newNode, { + prefix: ts.isLineBreak(sourceFile.text.charCodeAt(scope.getLastToken().pos)) ? this.newLineCharacter : this.newLineCharacter + this.newLineCharacter, + suffix: this.newLineCharacter + }); + }; + ChangeTracker.prototype.insertNodeAtClassStart = function (sourceFile, cls, newElement) { + this.insertNodeAtStartWorker(sourceFile, cls, newElement); + }; + ChangeTracker.prototype.insertNodeAtObjectStart = function (sourceFile, obj, newElement) { + this.insertNodeAtStartWorker(sourceFile, obj, newElement); + }; + ChangeTracker.prototype.insertNodeAtStartWorker = function (sourceFile, cls, newElement) { + var clsStart = cls.getStart(sourceFile); + var indentation = ts.formatting.SmartIndenter.findFirstNonWhitespaceColumn(ts.getLineStartPositionForPosition(clsStart, sourceFile), clsStart, sourceFile, this.formatContext.options) + + this.formatContext.options.indentSize; + this.insertNodeAt(sourceFile, getMembersOrProperties(cls).pos, newElement, __assign({ indentation: indentation }, this.getInsertNodeAtStartPrefixSuffix(sourceFile, cls))); + }; + ChangeTracker.prototype.getInsertNodeAtStartPrefixSuffix = function (sourceFile, cls) { + var comma = ts.isObjectLiteralExpression(cls) ? "," : ""; + if (getMembersOrProperties(cls).length === 0) { + if (ts.addToSeen(this.classesWithNodesInsertedAtStart, ts.getNodeId(cls), { node: cls, sourceFile: sourceFile })) { + // For `class C {\n}`, don't add the trailing "\n" + var shouldSuffix = ts.positionsAreOnSameLine.apply(void 0, getClassOrObjectBraceEnds(cls, sourceFile).concat([sourceFile])); // TODO: GH#4130 remove 'as any' + return { prefix: this.newLineCharacter, suffix: comma + (shouldSuffix ? this.newLineCharacter : "") }; + } + else { + return { prefix: "", suffix: comma + this.newLineCharacter }; + } + } + else { + return { prefix: this.newLineCharacter, suffix: comma }; + } + }; + ChangeTracker.prototype.insertNodeAfterComma = function (sourceFile, after, newNode) { + var endPosition = this.insertNodeAfterWorker(sourceFile, this.nextCommaToken(sourceFile, after) || after, newNode); + this.insertNodeAt(sourceFile, endPosition, newNode, this.getInsertNodeAfterOptions(sourceFile, after)); + }; + ChangeTracker.prototype.insertNodeAfter = function (sourceFile, after, newNode) { + var endPosition = this.insertNodeAfterWorker(sourceFile, after, newNode); + this.insertNodeAt(sourceFile, endPosition, newNode, this.getInsertNodeAfterOptions(sourceFile, after)); + }; + ChangeTracker.prototype.insertNodeAtEndOfList = function (sourceFile, list, newNode) { + this.insertNodeAt(sourceFile, list.end, newNode, { prefix: ", " }); + }; + ChangeTracker.prototype.insertNodesAfter = function (sourceFile, after, newNodes) { + var endPosition = this.insertNodeAfterWorker(sourceFile, after, ts.first(newNodes)); + this.insertNodesAt(sourceFile, endPosition, newNodes, this.getInsertNodeAfterOptions(sourceFile, after)); + }; + ChangeTracker.prototype.insertNodeAfterWorker = function (sourceFile, after, newNode) { + if (needSemicolonBetween(after, newNode)) { + // check if previous statement ends with semicolon + // if not - insert semicolon to preserve the code from changing the meaning due to ASI + if (sourceFile.text.charCodeAt(after.end - 1) !== 59 /* semicolon */) { + this.replaceRange(sourceFile, ts.createRange(after.end), ts.createToken(26 /* SemicolonToken */)); + } + } + var endPosition = getAdjustedEndPosition(sourceFile, after, {}); + return endPosition; + }; + ChangeTracker.prototype.getInsertNodeAfterOptions = function (sourceFile, after) { + var options = this.getInsertNodeAfterOptionsWorker(after); + return __assign({}, options, { prefix: after.end === sourceFile.end && ts.isStatement(after) ? (options.prefix ? "\n" + options.prefix : "\n") : options.prefix }); + }; + ChangeTracker.prototype.getInsertNodeAfterOptionsWorker = function (node) { + switch (node.kind) { + case 240 /* ClassDeclaration */: + case 244 /* ModuleDeclaration */: + return { prefix: this.newLineCharacter, suffix: this.newLineCharacter }; + case 237 /* VariableDeclaration */: + case 10 /* StringLiteral */: + case 72 /* Identifier */: + return { prefix: ", " }; + case 275 /* PropertyAssignment */: + return { suffix: "," + this.newLineCharacter }; + case 85 /* ExportKeyword */: + return { prefix: " " }; + case 151 /* Parameter */: + return {}; + default: + ts.Debug.assert(ts.isStatement(node) || ts.isClassOrTypeElement(node)); // Else we haven't handled this kind of node yet -- add it + return { suffix: this.newLineCharacter }; + } + }; + ChangeTracker.prototype.insertName = function (sourceFile, node, name) { + ts.Debug.assert(!node.name); + if (node.kind === 197 /* ArrowFunction */) { + var arrow = ts.findChildOfKind(node, 37 /* EqualsGreaterThanToken */, sourceFile); + var lparen = ts.findChildOfKind(node, 20 /* OpenParenToken */, sourceFile); + if (lparen) { + // `() => {}` --> `function f() {}` + this.insertNodesAt(sourceFile, lparen.getStart(sourceFile), [ts.createToken(90 /* FunctionKeyword */), ts.createIdentifier(name)], { joiner: " " }); + deleteNode(this, sourceFile, arrow); + } + else { + // `x => {}` -> `function f(x) {}` + this.insertText(sourceFile, ts.first(node.parameters).getStart(sourceFile), "function " + name + "("); + // Replacing full range of arrow to get rid of the leading space -- replace ` =>` with `)` + this.replaceRange(sourceFile, arrow, ts.createToken(21 /* CloseParenToken */)); + } + if (node.body.kind !== 218 /* Block */) { + // `() => 0` => `function f() { return 0; }` + this.insertNodesAt(sourceFile, node.body.getStart(sourceFile), [ts.createToken(18 /* OpenBraceToken */), ts.createToken(97 /* ReturnKeyword */)], { joiner: " ", suffix: " " }); + this.insertNodesAt(sourceFile, node.body.end, [ts.createToken(26 /* SemicolonToken */), ts.createToken(19 /* CloseBraceToken */)], { joiner: " " }); + } + } + else { + var pos = ts.findChildOfKind(node, node.kind === 196 /* FunctionExpression */ ? 90 /* FunctionKeyword */ : 76 /* ClassKeyword */, sourceFile).end; + this.insertNodeAt(sourceFile, pos, ts.createIdentifier(name), { prefix: " " }); + } + }; + ChangeTracker.prototype.insertExportModifier = function (sourceFile, node) { + this.insertText(sourceFile, node.getStart(sourceFile), "export "); + }; + /** + * This function should be used to insert nodes in lists when nodes don't carry separators as the part of the node range, + * i.e. arguments in arguments lists, parameters in parameter lists etc. + * Note that separators are part of the node in statements and class elements. + */ + ChangeTracker.prototype.insertNodeInListAfter = function (sourceFile, after, newNode, containingList) { + if (containingList === void 0) { containingList = ts.formatting.SmartIndenter.getContainingList(after, sourceFile); } + if (!containingList) { + ts.Debug.fail("node is not a list element"); + return; + } + var index = ts.indexOfNode(containingList, after); + if (index < 0) { + return; + } + var end = after.getEnd(); + if (index !== containingList.length - 1) { + // any element except the last one + // use next sibling as an anchor + var nextToken = ts.getTokenAtPosition(sourceFile, after.end); + if (nextToken && isSeparator(after, nextToken)) { + // for list + // a, b, c + // create change for adding 'e' after 'a' as + // - find start of next element after a (it is b) + // - use this start as start and end position in final change + // - build text of change by formatting the text of node + separator + whitespace trivia of b + // in multiline case it will work as + // a, + // b, + // c, + // result - '*' denotes leading trivia that will be inserted after new text (displayed as '#') + // a,* + // ***insertedtext# + // ###b, + // c, + // find line and character of the next element + var lineAndCharOfNextElement = ts.getLineAndCharacterOfPosition(sourceFile, skipWhitespacesAndLineBreaks(sourceFile.text, containingList[index + 1].getFullStart())); + // find line and character of the token that precedes next element (usually it is separator) + var lineAndCharOfNextToken = ts.getLineAndCharacterOfPosition(sourceFile, nextToken.end); + var prefix = void 0; + var startPos = void 0; + if (lineAndCharOfNextToken.line === lineAndCharOfNextElement.line) { + // next element is located on the same line with separator: + // a,$$$$b + // ^ ^ + // | |-next element + // |-separator + // where $$$ is some leading trivia + // for a newly inserted node we'll maintain the same relative position comparing to separator and replace leading trivia with spaces + // a, x,$$$$b + // ^ ^ ^ + // | | |-next element + // | |-new inserted node padded with spaces + // |-separator + startPos = nextToken.end; + prefix = spaces(lineAndCharOfNextElement.character - lineAndCharOfNextToken.character); + } + else { + // next element is located on different line that separator + // let insert position be the beginning of the line that contains next element + startPos = ts.getStartPositionOfLine(lineAndCharOfNextElement.line, sourceFile); + } + // write separator and leading trivia of the next element as suffix + var suffix = "" + ts.tokenToString(nextToken.kind) + sourceFile.text.substring(nextToken.end, containingList[index + 1].getStart(sourceFile)); + this.replaceRange(sourceFile, ts.createRange(startPos, containingList[index + 1].getStart(sourceFile)), newNode, { prefix: prefix, suffix: suffix }); + } + } + else { + var afterStart = after.getStart(sourceFile); + var afterStartLinePosition = ts.getLineStartPositionForPosition(afterStart, sourceFile); + var separator = void 0; + var multilineList = false; + // insert element after the last element in the list that has more than one item + // pick the element preceding the after element to: + // - pick the separator + // - determine if list is a multiline + if (containingList.length === 1) { + // if list has only one element then we'll format is as multiline if node has comment in trailing trivia, or as singleline otherwise + // i.e. var x = 1 // this is x + // | new element will be inserted at this position + separator = 27 /* CommaToken */; + } + else { + // element has more than one element, pick separator from the list + var tokenBeforeInsertPosition = ts.findPrecedingToken(after.pos, sourceFile); + separator = isSeparator(after, tokenBeforeInsertPosition) ? tokenBeforeInsertPosition.kind : 27 /* CommaToken */; + // determine if list is multiline by checking lines of after element and element that precedes it. + var afterMinusOneStartLinePosition = ts.getLineStartPositionForPosition(containingList[index - 1].getStart(sourceFile), sourceFile); + multilineList = afterMinusOneStartLinePosition !== afterStartLinePosition; + } + if (hasCommentsBeforeLineBreak(sourceFile.text, after.end)) { + // in this case we'll always treat containing list as multiline + multilineList = true; + } + if (multilineList) { + // insert separator immediately following the 'after' node to preserve comments in trailing trivia + this.replaceRange(sourceFile, ts.createRange(end), ts.createToken(separator)); + // use the same indentation as 'after' item + var indentation = ts.formatting.SmartIndenter.findFirstNonWhitespaceColumn(afterStartLinePosition, afterStart, sourceFile, this.formatContext.options); + // insert element before the line break on the line that contains 'after' element + var insertPos = ts.skipTrivia(sourceFile.text, end, /*stopAfterLineBreak*/ true, /*stopAtComments*/ false); + if (insertPos !== end && ts.isLineBreak(sourceFile.text.charCodeAt(insertPos - 1))) { + insertPos--; + } + this.replaceRange(sourceFile, ts.createRange(insertPos), newNode, { indentation: indentation, prefix: this.newLineCharacter }); + } + else { + this.replaceRange(sourceFile, ts.createRange(end), newNode, { prefix: ts.tokenToString(separator) + " " }); + } + } + }; + ChangeTracker.prototype.finishClassesWithNodesInsertedAtStart = function () { + var _this = this; + this.classesWithNodesInsertedAtStart.forEach(function (_a) { + var node = _a.node, sourceFile = _a.sourceFile; + var _b = getClassOrObjectBraceEnds(node, sourceFile), openBraceEnd = _b[0], closeBraceEnd = _b[1]; + // For `class C { }` remove the whitespace inside the braces. + if (ts.positionsAreOnSameLine(openBraceEnd, closeBraceEnd, sourceFile) && openBraceEnd !== closeBraceEnd - 1) { + _this.deleteRange(sourceFile, ts.createRange(openBraceEnd, closeBraceEnd - 1)); + } + }); + }; + ChangeTracker.prototype.finishDeleteDeclarations = function () { + var _this = this; + var deletedNodesInLists = new ts.NodeSet(); // Stores nodes in lists that we already deleted. Used to avoid deleting `, ` twice in `a, b`. + var _loop_17 = function (sourceFile, node) { + if (!this_1.deletedNodes.some(function (d) { return d.sourceFile === sourceFile && ts.rangeContainsRangeExclusive(d.node, node); })) { + if (ts.isArray(node)) { + this_1.deleteRange(sourceFile, ts.rangeOfTypeParameters(node)); + } + else { + deleteDeclaration.deleteDeclaration(this_1, deletedNodesInLists, sourceFile, node); + } + } + }; + var this_1 = this; + for (var _i = 0, _a = this.deletedNodes; _i < _a.length; _i++) { + var _b = _a[_i], sourceFile = _b.sourceFile, node = _b.node; + _loop_17(sourceFile, node); + } + deletedNodesInLists.forEach(function (node) { + var sourceFile = node.getSourceFile(); + var list = ts.formatting.SmartIndenter.getContainingList(node, sourceFile); + if (node !== ts.last(list)) + return; + var lastNonDeletedIndex = ts.findLastIndex(list, function (n) { return !deletedNodesInLists.has(n); }, list.length - 2); + if (lastNonDeletedIndex !== -1) { + _this.deleteRange(sourceFile, { pos: list[lastNonDeletedIndex].end, end: startPositionToDeleteNodeInList(sourceFile, list[lastNonDeletedIndex + 1]) }); + } + }); + }; + /** + * Note: after calling this, the TextChanges object must be discarded! + * @param validate only for tests + * The reason we must validate as part of this method is that `getNonFormattedText` changes the node's positions, + * so we can only call this once and can't get the non-formatted text separately. + */ + ChangeTracker.prototype.getChanges = function (validate) { + this.finishDeleteDeclarations(); + this.finishClassesWithNodesInsertedAtStart(); + var changes = changesToText.getTextChangesFromChanges(this.changes, this.newLineCharacter, this.formatContext, validate); + for (var _i = 0, _a = this.newFiles; _i < _a.length; _i++) { + var _b = _a[_i], oldFile = _b.oldFile, fileName = _b.fileName, statements = _b.statements; + changes.push(changesToText.newFileChanges(oldFile, fileName, statements, this.newLineCharacter, this.formatContext)); + } + return changes; + }; + ChangeTracker.prototype.createNewFile = function (oldFile, fileName, statements) { + this.newFiles.push({ oldFile: oldFile, fileName: fileName, statements: statements }); + }; + return ChangeTracker; + }()); + textChanges_3.ChangeTracker = ChangeTracker; + // find first non-whitespace position in the leading trivia of the node + function startPositionToDeleteNodeInList(sourceFile, node) { + return ts.skipTrivia(sourceFile.text, getAdjustedStartPosition(sourceFile, node, {}, Position.FullStart), /*stopAfterLineBreak*/ false, /*stopAtComments*/ true); + } + function getClassOrObjectBraceEnds(cls, sourceFile) { + return [ts.findChildOfKind(cls, 18 /* OpenBraceToken */, sourceFile).end, ts.findChildOfKind(cls, 19 /* CloseBraceToken */, sourceFile).end]; + } + function getMembersOrProperties(cls) { + return ts.isObjectLiteralExpression(cls) ? cls.properties : cls.members; + } + function getNewFileText(statements, scriptKind, newLineCharacter, formatContext) { + return changesToText.newFileChangesWorker(/*oldFile*/ undefined, scriptKind, statements, newLineCharacter, formatContext); + } + textChanges_3.getNewFileText = getNewFileText; + var changesToText; + (function (changesToText) { + function getTextChangesFromChanges(changes, newLineCharacter, formatContext, validate) { + return ts.group(changes, function (c) { return c.sourceFile.path; }).map(function (changesInFile) { + var sourceFile = changesInFile[0].sourceFile; + // order changes by start position + // If the start position is the same, put the shorter range first, since an empty range (x, x) may precede (x, y) but not vice-versa. + var normalized = ts.stableSort(changesInFile, function (a, b) { return (a.range.pos - b.range.pos) || (a.range.end - b.range.end); }); + var _loop_18 = function (i) { + ts.Debug.assert(normalized[i].range.end <= normalized[i + 1].range.pos, "Changes overlap", function () { + return JSON.stringify(normalized[i].range) + " and " + JSON.stringify(normalized[i + 1].range); + }); + }; + // verify that change intervals do not overlap, except possibly at end points. + for (var i = 0; i < normalized.length - 1; i++) { + _loop_18(i); + } + var textChanges = normalized.map(function (c) { + return ts.createTextChange(ts.createTextSpanFromRange(c.range), computeNewText(c, sourceFile, newLineCharacter, formatContext, validate)); + }); + return { fileName: sourceFile.fileName, textChanges: textChanges }; + }); + } + changesToText.getTextChangesFromChanges = getTextChangesFromChanges; + function newFileChanges(oldFile, fileName, statements, newLineCharacter, formatContext) { + var text = newFileChangesWorker(oldFile, ts.getScriptKindFromFileName(fileName), statements, newLineCharacter, formatContext); + return { fileName: fileName, textChanges: [ts.createTextChange(ts.createTextSpan(0, 0), text)], isNewFile: true }; + } + changesToText.newFileChanges = newFileChanges; + function newFileChangesWorker(oldFile, scriptKind, statements, newLineCharacter, formatContext) { + // TODO: this emits the file, parses it back, then formats it that -- may be a less roundabout way to do this + var nonFormattedText = statements.map(function (s) { return getNonformattedText(s, oldFile, newLineCharacter).text; }).join(newLineCharacter); + var sourceFile = ts.createSourceFile("any file name", nonFormattedText, 6 /* ESNext */, /*setParentNodes*/ true, scriptKind); + var changes = ts.formatting.formatDocument(sourceFile, formatContext); + return applyChanges(nonFormattedText, changes) + newLineCharacter; + } + changesToText.newFileChangesWorker = newFileChangesWorker; + function computeNewText(change, sourceFile, newLineCharacter, formatContext, validate) { + if (change.kind === ChangeKind.Remove) { + return ""; + } + if (change.kind === ChangeKind.Text) { + return change.text; + } + var _a = change.options, options = _a === void 0 ? {} : _a, pos = change.range.pos; + var format = function (n) { return getFormattedTextOfNode(n, sourceFile, pos, options, newLineCharacter, formatContext, validate); }; + var text = change.kind === ChangeKind.ReplaceWithMultipleNodes + ? change.nodes.map(function (n) { return ts.removeSuffix(format(n), newLineCharacter); }).join(change.options.joiner || newLineCharacter) // TODO: GH#18217 + : format(change.node); + // strip initial indentation (spaces or tabs) if text will be inserted in the middle of the line + var noIndent = (options.preserveLeadingWhitespace || options.indentation !== undefined || ts.getLineStartPositionForPosition(pos, sourceFile) === pos) ? text : text.replace(/^\s+/, ""); + return (options.prefix || "") + noIndent + (options.suffix || ""); + } + /** Note: this may mutate `nodeIn`. */ + function getFormattedTextOfNode(nodeIn, sourceFile, pos, _a, newLineCharacter, formatContext, validate) { + var indentation = _a.indentation, prefix = _a.prefix, delta = _a.delta; + var _b = getNonformattedText(nodeIn, sourceFile, newLineCharacter), node = _b.node, text = _b.text; + if (validate) + validate(node, text); + var formatOptions = formatContext.options; + var initialIndentation = indentation !== undefined + ? indentation + : ts.formatting.SmartIndenter.getIndentation(pos, sourceFile, formatOptions, prefix === newLineCharacter || ts.getLineStartPositionForPosition(pos, sourceFile) === pos); + if (delta === undefined) { + delta = ts.formatting.SmartIndenter.shouldIndentChildNode(formatContext.options, nodeIn) ? (formatOptions.indentSize || 0) : 0; + } + var file = { text: text, getLineAndCharacterOfPosition: function (pos) { return ts.getLineAndCharacterOfPosition(this, pos); } }; + var changes = ts.formatting.formatNodeGivenIndentation(node, file, sourceFile.languageVariant, initialIndentation, delta, formatContext); + return applyChanges(text, changes); + } + /** Note: output node may be mutated input node. */ + function getNonformattedText(node, sourceFile, newLineCharacter) { + var writer = new Writer(newLineCharacter); + var newLine = newLineCharacter === "\n" ? 1 /* LineFeed */ : 0 /* CarriageReturnLineFeed */; + ts.createPrinter({ newLine: newLine, neverAsciiEscape: true }, writer).writeNode(4 /* Unspecified */, node, sourceFile, writer); + return { text: writer.getText(), node: assignPositionsToNode(node) }; + } + changesToText.getNonformattedText = getNonformattedText; + })(changesToText || (changesToText = {})); + function applyChanges(text, changes) { + for (var i = changes.length - 1; i >= 0; i--) { + var _a = changes[i], span = _a.span, newText = _a.newText; + text = "" + text.substring(0, span.start) + newText + text.substring(ts.textSpanEnd(span)); + } + return text; + } + textChanges_3.applyChanges = applyChanges; + function isTrivia(s) { + return ts.skipTrivia(s, 0) === s.length; + } + function assignPositionsToNode(node) { + var visited = ts.visitEachChild(node, assignPositionsToNode, ts.nullTransformationContext, assignPositionsToNodeArray, assignPositionsToNode); // TODO: GH#18217 + // create proxy node for non synthesized nodes + var newNode = ts.nodeIsSynthesized(visited) ? visited : Object.create(visited); + newNode.pos = getPos(node); + newNode.end = getEnd(node); + return newNode; + } + function assignPositionsToNodeArray(nodes, visitor, test, start, count) { + var visited = ts.visitNodes(nodes, visitor, test, start, count); + if (!visited) { + return visited; + } + // clone nodearray if necessary + var nodeArray = visited === nodes ? ts.createNodeArray(visited.slice(0)) : visited; + nodeArray.pos = getPos(nodes); + nodeArray.end = getEnd(nodes); + return nodeArray; + } + var Writer = /** @class */ (function () { + function Writer(newLine) { + var _this = this; + this.lastNonTriviaPosition = 0; + this.writer = ts.createTextWriter(newLine); + this.onEmitNode = function (hint, node, printCallback) { + if (node) { + setPos(node, _this.lastNonTriviaPosition); + } + printCallback(hint, node); + if (node) { + setEnd(node, _this.lastNonTriviaPosition); + } + }; + this.onBeforeEmitNodeArray = function (nodes) { + if (nodes) { + setPos(nodes, _this.lastNonTriviaPosition); + } + }; + this.onAfterEmitNodeArray = function (nodes) { + if (nodes) { + setEnd(nodes, _this.lastNonTriviaPosition); + } + }; + this.onBeforeEmitToken = function (node) { + if (node) { + setPos(node, _this.lastNonTriviaPosition); + } + }; + this.onAfterEmitToken = function (node) { + if (node) { + setEnd(node, _this.lastNonTriviaPosition); + } + }; + } + Writer.prototype.setLastNonTriviaPosition = function (s, force) { + if (force || !isTrivia(s)) { + this.lastNonTriviaPosition = this.writer.getTextPos(); + var i = 0; + while (ts.isWhiteSpaceLike(s.charCodeAt(s.length - i - 1))) { + i++; + } + // trim trailing whitespaces + this.lastNonTriviaPosition -= i; + } + }; + Writer.prototype.write = function (s) { + this.writer.write(s); + this.setLastNonTriviaPosition(s, /*force*/ false); + }; + Writer.prototype.writeComment = function (s) { + this.writer.writeComment(s); + }; + Writer.prototype.writeKeyword = function (s) { + this.writer.writeKeyword(s); + this.setLastNonTriviaPosition(s, /*force*/ false); + }; + Writer.prototype.writeOperator = function (s) { + this.writer.writeOperator(s); + this.setLastNonTriviaPosition(s, /*force*/ false); + }; + Writer.prototype.writePunctuation = function (s) { + this.writer.writePunctuation(s); + this.setLastNonTriviaPosition(s, /*force*/ false); + }; + Writer.prototype.writeTrailingSemicolon = function (s) { + this.writer.writeTrailingSemicolon(s); + this.setLastNonTriviaPosition(s, /*force*/ false); + }; + Writer.prototype.writeParameter = function (s) { + this.writer.writeParameter(s); + this.setLastNonTriviaPosition(s, /*force*/ false); + }; + Writer.prototype.writeProperty = function (s) { + this.writer.writeProperty(s); + this.setLastNonTriviaPosition(s, /*force*/ false); + }; + Writer.prototype.writeSpace = function (s) { + this.writer.writeSpace(s); + this.setLastNonTriviaPosition(s, /*force*/ false); + }; + Writer.prototype.writeStringLiteral = function (s) { + this.writer.writeStringLiteral(s); + this.setLastNonTriviaPosition(s, /*force*/ false); + }; + Writer.prototype.writeSymbol = function (s, sym) { + this.writer.writeSymbol(s, sym); + this.setLastNonTriviaPosition(s, /*force*/ false); + }; + Writer.prototype.writeLine = function () { + this.writer.writeLine(); + }; + Writer.prototype.increaseIndent = function () { + this.writer.increaseIndent(); + }; + Writer.prototype.decreaseIndent = function () { + this.writer.decreaseIndent(); + }; + Writer.prototype.getText = function () { + return this.writer.getText(); + }; + Writer.prototype.rawWrite = function (s) { + this.writer.rawWrite(s); + this.setLastNonTriviaPosition(s, /*force*/ false); + }; + Writer.prototype.writeLiteral = function (s) { + this.writer.writeLiteral(s); + this.setLastNonTriviaPosition(s, /*force*/ true); + }; + Writer.prototype.getTextPos = function () { + return this.writer.getTextPos(); + }; + Writer.prototype.getLine = function () { + return this.writer.getLine(); + }; + Writer.prototype.getColumn = function () { + return this.writer.getColumn(); + }; + Writer.prototype.getIndent = function () { + return this.writer.getIndent(); + }; + Writer.prototype.isAtStartOfLine = function () { + return this.writer.isAtStartOfLine(); + }; + Writer.prototype.clear = function () { + this.writer.clear(); + this.lastNonTriviaPosition = 0; + }; + return Writer; + }()); + function getInsertionPositionAtSourceFileTop(sourceFile) { + var lastPrologue; + for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { + var node = _a[_i]; + if (ts.isPrologueDirective(node)) { + lastPrologue = node; + } + else { + break; + } + } + var position = 0; + var text = sourceFile.text; + if (lastPrologue) { + position = lastPrologue.end; + advancePastLineBreak(); + return position; + } + var shebang = ts.getShebang(text); + if (shebang !== undefined) { + position = shebang.length; + advancePastLineBreak(); + } + // For a source file, it is possible there are detached comments we should not skip + var ranges = ts.getLeadingCommentRanges(text, position); + if (!ranges) + return position; + // However we should still skip a pinned comment at the top + if (ranges.length && ranges[0].kind === 3 /* MultiLineCommentTrivia */ && ts.isPinnedComment(text, ranges[0].pos)) { + position = ranges[0].end; + advancePastLineBreak(); + ranges = ranges.slice(1); + } + // As well as any triple slash references + for (var _b = 0, ranges_1 = ranges; _b < ranges_1.length; _b++) { + var range = ranges_1[_b]; + if (range.kind === 2 /* SingleLineCommentTrivia */ && ts.isRecognizedTripleSlashComment(text, range.pos, range.end)) { + position = range.end; + advancePastLineBreak(); + continue; + } + break; + } + return position; + function advancePastLineBreak() { + if (position < text.length) { + var charCode = text.charCodeAt(position); + if (ts.isLineBreak(charCode)) { + position++; + if (position < text.length && charCode === 13 /* carriageReturn */ && text.charCodeAt(position) === 10 /* lineFeed */) { + position++; + } + } + } + } + } + function isValidLocationToAddComment(sourceFile, position) { + return !ts.isInComment(sourceFile, position) && !ts.isInString(sourceFile, position) && !ts.isInTemplateString(sourceFile, position) && !ts.isInJSXText(sourceFile, position); + } + textChanges_3.isValidLocationToAddComment = isValidLocationToAddComment; + function needSemicolonBetween(a, b) { + return (ts.isPropertySignature(a) || ts.isPropertyDeclaration(a)) && ts.isClassOrTypeElement(b) && b.name.kind === 149 /* ComputedPropertyName */ + || ts.isStatementButNotDeclaration(a) && ts.isStatementButNotDeclaration(b); // TODO: only if b would start with a `(` or `[` + } + var deleteDeclaration; + (function (deleteDeclaration_1) { + function deleteDeclaration(changes, deletedNodesInLists, sourceFile, node) { + switch (node.kind) { + case 151 /* Parameter */: { + var oldFunction = node.parent; + if (ts.isArrowFunction(oldFunction) && + oldFunction.parameters.length === 1 && + !ts.findChildOfKind(oldFunction, 20 /* OpenParenToken */, sourceFile)) { + // Lambdas with exactly one parameter are special because, after removal, there + // must be an empty parameter list (i.e. `()`) and this won't necessarily be the + // case if the parameter is simply removed (e.g. in `x => 1`). + changes.replaceNodeWithText(sourceFile, node, "()"); + } + else { + deleteNodeInList(changes, deletedNodesInLists, sourceFile, node); + } + break; + } + case 249 /* ImportDeclaration */: + deleteNode(changes, sourceFile, node, + // For first import, leave header comment in place + node === sourceFile.imports[0].parent ? { useNonAdjustedStartPosition: true, useNonAdjustedEndPosition: false } : undefined); + break; + case 186 /* BindingElement */: + var pattern = node.parent; + var preserveComma = pattern.kind === 185 /* ArrayBindingPattern */ && node !== ts.last(pattern.elements); + if (preserveComma) { + deleteNode(changes, sourceFile, node); + } + else { + deleteNodeInList(changes, deletedNodesInLists, sourceFile, node); + } + break; + case 237 /* VariableDeclaration */: + deleteVariableDeclaration(changes, deletedNodesInLists, sourceFile, node); + break; + case 150 /* TypeParameter */: + deleteNodeInList(changes, deletedNodesInLists, sourceFile, node); + break; + case 253 /* ImportSpecifier */: + var namedImports = node.parent; + if (namedImports.elements.length === 1) { + deleteImportBinding(changes, sourceFile, namedImports); + } + else { + deleteNodeInList(changes, deletedNodesInLists, sourceFile, node); + } + break; + case 251 /* NamespaceImport */: + deleteImportBinding(changes, sourceFile, node); + break; + default: + if (ts.isImportClause(node.parent) && node.parent.name === node) { + deleteDefaultImport(changes, sourceFile, node.parent); + } + else if (ts.isCallLikeExpression(node.parent)) { + deleteNodeInList(changes, deletedNodesInLists, sourceFile, node); + } + else { + deleteNode(changes, sourceFile, node, node.kind === 26 /* SemicolonToken */ ? { useNonAdjustedEndPosition: true } : undefined); + } + } + } + deleteDeclaration_1.deleteDeclaration = deleteDeclaration; + function deleteDefaultImport(changes, sourceFile, importClause) { + if (!importClause.namedBindings) { + // Delete the whole import + deleteNode(changes, sourceFile, importClause.parent); + } + else { + // import |d,| * as ns from './file' + var start = importClause.name.getStart(sourceFile); + var nextToken = ts.getTokenAtPosition(sourceFile, importClause.name.end); + if (nextToken && nextToken.kind === 27 /* CommaToken */) { + // shift first non-whitespace position after comma to the start position of the node + var end = ts.skipTrivia(sourceFile.text, nextToken.end, /*stopAfterLineBreaks*/ false, /*stopAtComments*/ true); + changes.deleteRange(sourceFile, { pos: start, end: end }); + } + else { + deleteNode(changes, sourceFile, importClause.name); + } + } + } + function deleteImportBinding(changes, sourceFile, node) { + if (node.parent.name) { + // Delete named imports while preserving the default import + // import d|, * as ns| from './file' + // import d|, { a }| from './file' + var previousToken = ts.Debug.assertDefined(ts.getTokenAtPosition(sourceFile, node.pos - 1)); + changes.deleteRange(sourceFile, { pos: previousToken.getStart(sourceFile), end: node.end }); + } + else { + // Delete the entire import declaration + // |import * as ns from './file'| + // |import { a } from './file'| + var importDecl = ts.getAncestor(node, 249 /* ImportDeclaration */); + deleteNode(changes, sourceFile, importDecl); + } + } + function deleteVariableDeclaration(changes, deletedNodesInLists, sourceFile, node) { + var parent = node.parent; + if (parent.kind === 274 /* CatchClause */) { + // TODO: There's currently no unused diagnostic for this, could be a suggestion + changes.deleteNodeRange(sourceFile, ts.findChildOfKind(parent, 20 /* OpenParenToken */, sourceFile), ts.findChildOfKind(parent, 21 /* CloseParenToken */, sourceFile)); + return; + } + if (parent.declarations.length !== 1) { + deleteNodeInList(changes, deletedNodesInLists, sourceFile, node); + return; + } + var gp = parent.parent; + switch (gp.kind) { + case 227 /* ForOfStatement */: + case 226 /* ForInStatement */: + changes.replaceNode(sourceFile, node, ts.createObjectLiteral()); + break; + case 225 /* ForStatement */: + deleteNode(changes, sourceFile, parent); + break; + case 219 /* VariableStatement */: + deleteNode(changes, sourceFile, gp); + break; + default: + ts.Debug.assertNever(gp); + } + } + })(deleteDeclaration || (deleteDeclaration = {})); + /** Warning: This deletes comments too. See `copyComments` in `convertFunctionToEs6Class`. */ + // Exported for tests only! (TODO: improve tests to not need this) + function deleteNode(changes, sourceFile, node, options) { + if (options === void 0) { options = {}; } + var startPosition = getAdjustedStartPosition(sourceFile, node, options, Position.FullStart); + var endPosition = getAdjustedEndPosition(sourceFile, node, options); + changes.deleteRange(sourceFile, { pos: startPosition, end: endPosition }); + } + textChanges_3.deleteNode = deleteNode; + function deleteNodeInList(changes, deletedNodesInLists, sourceFile, node) { + var containingList = ts.Debug.assertDefined(ts.formatting.SmartIndenter.getContainingList(node, sourceFile)); + var index = ts.indexOfNode(containingList, node); + ts.Debug.assert(index !== -1); + if (containingList.length === 1) { + deleteNode(changes, sourceFile, node); + return; + } + // Note: We will only delete a comma *after* a node. This will leave a trailing comma if we delete the last node. + // That's handled in the end by `finishTrailingCommaAfterDeletingNodesInList`. + ts.Debug.assert(!deletedNodesInLists.has(node), "Deleting a node twice"); + deletedNodesInLists.add(node); + changes.deleteRange(sourceFile, { + pos: startPositionToDeleteNodeInList(sourceFile, node), + end: index === containingList.length - 1 ? getAdjustedEndPosition(sourceFile, node, {}) : startPositionToDeleteNodeInList(sourceFile, containingList[index + 1]), + }); + } + })(textChanges = ts.textChanges || (ts.textChanges = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var errorCodeToFixes = ts.createMultiMap(); + var fixIdToRegistration = ts.createMap(); + function diagnosticToString(diag) { + return ts.isArray(diag) + ? ts.formatStringFromArgs(ts.getLocaleSpecificMessage(diag[0]), diag.slice(1)) + : ts.getLocaleSpecificMessage(diag); + } + function createCodeFixActionNoFixId(fixName, changes, description) { + return createCodeFixActionWorker(fixName, diagnosticToString(description), changes, /*fixId*/ undefined, /*fixAllDescription*/ undefined); + } + codefix.createCodeFixActionNoFixId = createCodeFixActionNoFixId; + function createCodeFixAction(fixName, changes, description, fixId, fixAllDescription, command) { + return createCodeFixActionWorker(fixName, diagnosticToString(description), changes, fixId, diagnosticToString(fixAllDescription), command); + } + codefix.createCodeFixAction = createCodeFixAction; + function createCodeFixActionWorker(fixName, description, changes, fixId, fixAllDescription, command) { + return { fixName: fixName, description: description, changes: changes, fixId: fixId, fixAllDescription: fixAllDescription, commands: command ? [command] : undefined }; + } + function registerCodeFix(reg) { + for (var _i = 0, _a = reg.errorCodes; _i < _a.length; _i++) { + var error = _a[_i]; + errorCodeToFixes.add(String(error), reg); + } + if (reg.fixIds) { + for (var _b = 0, _c = reg.fixIds; _b < _c.length; _b++) { + var fixId = _c[_b]; + ts.Debug.assert(!fixIdToRegistration.has(fixId)); + fixIdToRegistration.set(fixId, reg); + } + } + } + codefix.registerCodeFix = registerCodeFix; + function getSupportedErrorCodes() { + return ts.arrayFrom(errorCodeToFixes.keys()); + } + codefix.getSupportedErrorCodes = getSupportedErrorCodes; + function getFixes(context) { + return ts.flatMap(errorCodeToFixes.get(String(context.errorCode)) || ts.emptyArray, function (f) { return f.getCodeActions(context); }); + } + codefix.getFixes = getFixes; + function getAllFixes(context) { + // Currently fixId is always a string. + return fixIdToRegistration.get(ts.cast(context.fixId, ts.isString)).getAllCodeActions(context); + } + codefix.getAllFixes = getAllFixes; + function createCombinedCodeActions(changes, commands) { + return { changes: changes, commands: commands }; + } + codefix.createCombinedCodeActions = createCombinedCodeActions; + function createFileTextChanges(fileName, textChanges) { + return { fileName: fileName, textChanges: textChanges }; + } + codefix.createFileTextChanges = createFileTextChanges; + function codeFixAll(context, errorCodes, use) { + var commands = []; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return eachDiagnostic(context, errorCodes, function (diag) { return use(t, diag, commands); }); }); + return createCombinedCodeActions(changes, commands.length === 0 ? undefined : commands); + } + codefix.codeFixAll = codeFixAll; + function eachDiagnostic(_a, errorCodes, cb) { + var program = _a.program, sourceFile = _a.sourceFile, cancellationToken = _a.cancellationToken; + for (var _i = 0, _b = program.getSemanticDiagnostics(sourceFile, cancellationToken).concat(ts.computeSuggestionDiagnostics(sourceFile, program, cancellationToken)); _i < _b.length; _i++) { + var diag = _b[_i]; + if (ts.contains(errorCodes, diag.code)) { + cb(diag); + } + } + } + codefix.eachDiagnostic = eachDiagnostic; + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var refactor; + (function (refactor_1) { + // A map with the refactor code as key, the refactor itself as value + // e.g. nonSuggestableRefactors[refactorCode] -> the refactor you want + var refactors = ts.createMap(); + /** @param name An unique code associated with each refactor. Does not have to be human-readable. */ + function registerRefactor(name, refactor) { + refactors.set(name, refactor); + } + refactor_1.registerRefactor = registerRefactor; + function getApplicableRefactors(context) { + return ts.arrayFrom(ts.flatMapIterator(refactors.values(), function (refactor) { + return context.cancellationToken && context.cancellationToken.isCancellationRequested() ? undefined : refactor.getAvailableActions(context); + })); + } + refactor_1.getApplicableRefactors = getApplicableRefactors; + function getEditsForRefactor(context, refactorName, actionName) { + var refactor = refactors.get(refactorName); + return refactor && refactor.getEditsForAction(context, actionName); + } + refactor_1.getEditsForRefactor = getEditsForRefactor; + })(refactor = ts.refactor || (ts.refactor = {})); + function getRefactorContextSpan(_a) { + var startPosition = _a.startPosition, endPosition = _a.endPosition; + return ts.createTextSpanFromBounds(startPosition, endPosition === undefined ? startPosition : endPosition); + } + ts.getRefactorContextSpan = getRefactorContextSpan; +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "addConvertToUnknownForNonOverlappingTypes"; + var errorCodes = [ts.Diagnostics.Conversion_of_type_0_to_type_1_may_be_a_mistake_because_neither_type_sufficiently_overlaps_with_the_other_If_this_was_intentional_convert_the_expression_to_unknown_first.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return makeChange(t, context.sourceFile, context.span.start); }); + return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Add_unknown_conversion_for_non_overlapping_types, fixId, ts.Diagnostics.Add_unknown_to_all_conversions_of_non_overlapping_types)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { return makeChange(changes, diag.file, diag.start); }); }, + }); + function makeChange(changeTracker, sourceFile, pos) { + var token = ts.getTokenAtPosition(sourceFile, pos); + var assertion = ts.Debug.assertDefined(ts.findAncestor(token, function (n) { return ts.isAsExpression(n) || ts.isTypeAssertion(n); })); + var replacement = ts.isAsExpression(assertion) + ? ts.createAsExpression(assertion.expression, ts.createKeywordTypeNode(143 /* UnknownKeyword */)) + : ts.createTypeAssertion(ts.createKeywordTypeNode(143 /* UnknownKeyword */), assertion.expression); + changeTracker.replaceNode(sourceFile, assertion.expression, replacement); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "addMissingInvocationForDecorator"; + var errorCodes = [ts.Diagnostics._0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write_0.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return makeChange(t, context.sourceFile, context.span.start); }); + return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Call_decorator_expression, fixId, ts.Diagnostics.Add_to_all_uncalled_decorators)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { return makeChange(changes, diag.file, diag.start); }); }, + }); + function makeChange(changeTracker, sourceFile, pos) { + var token = ts.getTokenAtPosition(sourceFile, pos); + var decorator = ts.findAncestor(token, ts.isDecorator); + ts.Debug.assert(!!decorator, "Expected position to be owned by a decorator."); + var replacement = ts.createCall(decorator.expression, /*typeArguments*/ undefined, /*argumentsArray*/ undefined); + changeTracker.replaceNode(sourceFile, decorator.expression, replacement); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "annotateWithTypeFromJSDoc"; + var errorCodes = [ts.Diagnostics.JSDoc_types_may_be_moved_to_TypeScript_types.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var decl = getDeclaration(context.sourceFile, context.span.start); + if (!decl) + return; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, context.sourceFile, decl); }); + return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Annotate_with_type_from_JSDoc, fixId, ts.Diagnostics.Annotate_everything_with_types_from_JSDoc)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var decl = getDeclaration(diag.file, diag.start); + if (decl) + doChange(changes, diag.file, decl); + }); }, + }); + function getDeclaration(file, pos) { + var name = ts.getTokenAtPosition(file, pos); + // For an arrow function with no name, 'name' lands on the first parameter. + return ts.tryCast(ts.isParameter(name.parent) ? name.parent.parent : name.parent, parameterShouldGetTypeFromJSDoc); + } + function parameterShouldGetTypeFromJSDoc(node) { + return isDeclarationWithType(node) && hasUsableJSDoc(node); + } + codefix.parameterShouldGetTypeFromJSDoc = parameterShouldGetTypeFromJSDoc; + function hasUsableJSDoc(decl) { + return ts.isFunctionLikeDeclaration(decl) + ? decl.parameters.some(hasUsableJSDoc) || (!decl.type && !!ts.getJSDocReturnType(decl)) + : !decl.type && !!ts.getJSDocType(decl); + } + function doChange(changes, sourceFile, decl) { + if (ts.isFunctionLikeDeclaration(decl) && (ts.getJSDocReturnType(decl) || decl.parameters.some(function (p) { return !!ts.getJSDocType(p); }))) { + if (!decl.typeParameters) { + var typeParameters = ts.getJSDocTypeParameterDeclarations(decl); + if (typeParameters.length) + changes.insertTypeParameters(sourceFile, decl, typeParameters); + } + var needParens = ts.isArrowFunction(decl) && !ts.findChildOfKind(decl, 20 /* OpenParenToken */, sourceFile); + if (needParens) + changes.insertNodeBefore(sourceFile, ts.first(decl.parameters), ts.createToken(20 /* OpenParenToken */)); + for (var _i = 0, _a = decl.parameters; _i < _a.length; _i++) { + var param = _a[_i]; + if (!param.type) { + var paramType = ts.getJSDocType(param); + if (paramType) + changes.tryInsertTypeAnnotation(sourceFile, param, transformJSDocType(paramType)); + } + } + if (needParens) + changes.insertNodeAfter(sourceFile, ts.last(decl.parameters), ts.createToken(21 /* CloseParenToken */)); + if (!decl.type) { + var returnType = ts.getJSDocReturnType(decl); + if (returnType) + changes.tryInsertTypeAnnotation(sourceFile, decl, transformJSDocType(returnType)); + } + } + else { + var jsdocType = ts.Debug.assertDefined(ts.getJSDocType(decl)); // If not defined, shouldn't have been an error to fix + ts.Debug.assert(!decl.type); // If defined, shouldn't have been an error to fix. + changes.tryInsertTypeAnnotation(sourceFile, decl, transformJSDocType(jsdocType)); + } + } + function isDeclarationWithType(node) { + return ts.isFunctionLikeDeclaration(node) || + node.kind === 237 /* VariableDeclaration */ || + node.kind === 153 /* PropertySignature */ || + node.kind === 154 /* PropertyDeclaration */; + } + function transformJSDocType(node) { + switch (node.kind) { + case 284 /* JSDocAllType */: + case 285 /* JSDocUnknownType */: + return ts.createTypeReferenceNode("any", ts.emptyArray); + case 288 /* JSDocOptionalType */: + return transformJSDocOptionalType(node); + case 287 /* JSDocNonNullableType */: + return transformJSDocType(node.type); + case 286 /* JSDocNullableType */: + return transformJSDocNullableType(node); + case 290 /* JSDocVariadicType */: + return transformJSDocVariadicType(node); + case 289 /* JSDocFunctionType */: + return transformJSDocFunctionType(node); + case 164 /* TypeReference */: + return transformJSDocTypeReference(node); + default: + var visited = ts.visitEachChild(node, transformJSDocType, /*context*/ undefined); // TODO: GH#18217 + ts.setEmitFlags(visited, 1 /* SingleLine */); + return visited; + } + } + function transformJSDocOptionalType(node) { + return ts.createUnionTypeNode([ts.visitNode(node.type, transformJSDocType), ts.createTypeReferenceNode("undefined", ts.emptyArray)]); + } + function transformJSDocNullableType(node) { + return ts.createUnionTypeNode([ts.visitNode(node.type, transformJSDocType), ts.createTypeReferenceNode("null", ts.emptyArray)]); + } + function transformJSDocVariadicType(node) { + return ts.createArrayTypeNode(ts.visitNode(node.type, transformJSDocType)); + } + function transformJSDocFunctionType(node) { + return ts.createFunctionTypeNode(ts.emptyArray, node.parameters.map(transformJSDocParameter), node.type); + } + function transformJSDocParameter(node) { + var index = node.parent.parameters.indexOf(node); + var isRest = node.type.kind === 290 /* JSDocVariadicType */ && index === node.parent.parameters.length - 1; // TODO: GH#18217 + var name = node.name || (isRest ? "rest" : "arg" + index); + var dotdotdot = isRest ? ts.createToken(25 /* DotDotDotToken */) : node.dotDotDotToken; + return ts.createParameter(node.decorators, node.modifiers, dotdotdot, name, node.questionToken, ts.visitNode(node.type, transformJSDocType), node.initializer); + } + function transformJSDocTypeReference(node) { + var name = node.typeName; + var args = node.typeArguments; + if (ts.isIdentifier(node.typeName)) { + if (ts.isJSDocIndexSignature(node)) { + return transformJSDocIndexSignature(node); + } + var text = node.typeName.text; + switch (node.typeName.text) { + case "String": + case "Boolean": + case "Object": + case "Number": + text = text.toLowerCase(); + break; + case "array": + case "date": + case "promise": + text = text[0].toUpperCase() + text.slice(1); + break; + } + name = ts.createIdentifier(text); + if ((text === "Array" || text === "Promise") && !node.typeArguments) { + args = ts.createNodeArray([ts.createTypeReferenceNode("any", ts.emptyArray)]); + } + else { + args = ts.visitNodes(node.typeArguments, transformJSDocType); + } + } + return ts.createTypeReferenceNode(name, args); + } + function transformJSDocIndexSignature(node) { + var index = ts.createParameter( + /*decorators*/ undefined, + /*modifiers*/ undefined, + /*dotDotDotToken*/ undefined, node.typeArguments[0].kind === 135 /* NumberKeyword */ ? "n" : "s", + /*questionToken*/ undefined, ts.createTypeReferenceNode(node.typeArguments[0].kind === 135 /* NumberKeyword */ ? "number" : "string", []), + /*initializer*/ undefined); + var indexSignature = ts.createTypeLiteralNode([ts.createIndexSignature(/*decorators*/ undefined, /*modifiers*/ undefined, [index], node.typeArguments[1])]); + ts.setEmitFlags(indexSignature, 1 /* SingleLine */); + return indexSignature; + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "inferFromUsage"; + var errorCodes = [ + // Variable declarations + ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code, + // Variable uses + ts.Diagnostics.Variable_0_implicitly_has_an_1_type.code, + // Parameter declarations + ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code, + ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code, + // Get Accessor declarations + ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation.code, + ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type.code, + // Set Accessor declarations + ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code, + // Property declarations + ts.Diagnostics.Member_0_implicitly_has_an_1_type.code, + //// Suggestions + // Variable declarations + ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_but_a_better_type_may_be_inferred_from_usage.code, + // Variable uses + ts.Diagnostics.Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code, + // Parameter declarations + ts.Diagnostics.Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code, + ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage.code, + // Get Accessor declarations + ts.Diagnostics.Property_0_implicitly_has_type_any_but_a_better_type_for_its_get_accessor_may_be_inferred_from_usage.code, + ts.Diagnostics._0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage.code, + // Set Accessor declarations + ts.Diagnostics.Property_0_implicitly_has_type_any_but_a_better_type_for_its_set_accessor_may_be_inferred_from_usage.code, + // Property declarations + ts.Diagnostics.Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code, + ]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var sourceFile = context.sourceFile, program = context.program, start = context.span.start, errorCode = context.errorCode, cancellationToken = context.cancellationToken, host = context.host; + var token = ts.getTokenAtPosition(sourceFile, start); + var declaration; + var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { declaration = doChange(changes, sourceFile, token, errorCode, program, cancellationToken, /*markSeen*/ ts.returnTrue, host); }); + var name = declaration && ts.getNameOfDeclaration(declaration); + return !name || changes.length === 0 ? undefined + : [codefix.createCodeFixAction(fixId, changes, [getDiagnostic(errorCode, token), name.getText(sourceFile)], fixId, ts.Diagnostics.Infer_all_types_from_usage)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { + var sourceFile = context.sourceFile, program = context.program, cancellationToken = context.cancellationToken, host = context.host; + var markSeen = ts.nodeSeenTracker(); + return codefix.codeFixAll(context, errorCodes, function (changes, err) { + doChange(changes, sourceFile, ts.getTokenAtPosition(err.file, err.start), err.code, program, cancellationToken, markSeen, host); + }); + }, + }); + function getDiagnostic(errorCode, token) { + switch (errorCode) { + case ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code: + case ts.Diagnostics.Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code: + return ts.isSetAccessorDeclaration(ts.getContainingFunction(token)) ? ts.Diagnostics.Infer_type_of_0_from_usage : ts.Diagnostics.Infer_parameter_types_from_usage; // TODO: GH#18217 + case ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code: + case ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage.code: + return ts.Diagnostics.Infer_parameter_types_from_usage; + default: + return ts.Diagnostics.Infer_type_of_0_from_usage; + } + } + /** Map suggestion code to error code */ + function mapSuggestionDiagnostic(errorCode) { + switch (errorCode) { + case ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_but_a_better_type_may_be_inferred_from_usage.code: + return ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code; + case ts.Diagnostics.Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code: + return ts.Diagnostics.Variable_0_implicitly_has_an_1_type.code; + case ts.Diagnostics.Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code: + return ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code; + case ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage.code: + return ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code; + case ts.Diagnostics.Property_0_implicitly_has_type_any_but_a_better_type_for_its_get_accessor_may_be_inferred_from_usage.code: + return ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation.code; + case ts.Diagnostics._0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage.code: + return ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type.code; + case ts.Diagnostics.Property_0_implicitly_has_type_any_but_a_better_type_for_its_set_accessor_may_be_inferred_from_usage.code: + return ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code; + case ts.Diagnostics.Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code: + return ts.Diagnostics.Member_0_implicitly_has_an_1_type.code; + } + return errorCode; + } + function doChange(changes, sourceFile, token, errorCode, program, cancellationToken, markSeen, host) { + if (!ts.isParameterPropertyModifier(token.kind) && token.kind !== 72 /* Identifier */ && token.kind !== 25 /* DotDotDotToken */ && token.kind !== 100 /* ThisKeyword */) { + return undefined; + } + var parent = token.parent; + errorCode = mapSuggestionDiagnostic(errorCode); + switch (errorCode) { + // Variable and Property declarations + case ts.Diagnostics.Member_0_implicitly_has_an_1_type.code: + case ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code: + if ((ts.isVariableDeclaration(parent) && markSeen(parent)) || ts.isPropertyDeclaration(parent) || ts.isPropertySignature(parent)) { // handle bad location + annotateVariableDeclaration(changes, sourceFile, parent, program, host, cancellationToken); + return parent; + } + if (ts.isPropertyAccessExpression(parent)) { + var type = inferTypeForVariableFromUsage(parent.name, program, cancellationToken); + var typeNode = getTypeNodeIfAccessible(type, parent, program, host); + if (typeNode) { + // Note that the codefix will never fire with an existing `@type` tag, so there is no need to merge tags + var typeTag = ts.createJSDocTypeTag(ts.createJSDocTypeExpression(typeNode), /*comment*/ ""); + addJSDocTags(changes, sourceFile, ts.cast(parent.parent.parent, ts.isExpressionStatement), [typeTag]); + } + return parent; + } + return undefined; + case ts.Diagnostics.Variable_0_implicitly_has_an_1_type.code: { + var symbol = program.getTypeChecker().getSymbolAtLocation(token); + if (symbol && symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && markSeen(symbol.valueDeclaration)) { + annotateVariableDeclaration(changes, sourceFile, symbol.valueDeclaration, program, host, cancellationToken); + return symbol.valueDeclaration; + } + return undefined; + } + } + var containingFunction = ts.getContainingFunction(token); + if (containingFunction === undefined) { + return undefined; + } + switch (errorCode) { + // Parameter declarations + case ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code: + if (ts.isSetAccessorDeclaration(containingFunction)) { + annotateSetAccessor(changes, sourceFile, containingFunction, program, host, cancellationToken); + return containingFunction; + } + // falls through + case ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code: + if (markSeen(containingFunction)) { + var param = ts.cast(parent, ts.isParameter); + annotateParameters(changes, sourceFile, param, containingFunction, program, host, cancellationToken); + return param; + } + return undefined; + // Get Accessor declarations + case ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation.code: + case ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type.code: + if (ts.isGetAccessorDeclaration(containingFunction) && ts.isIdentifier(containingFunction.name)) { + annotate(changes, sourceFile, containingFunction, inferTypeForVariableFromUsage(containingFunction.name, program, cancellationToken), program, host); + return containingFunction; + } + return undefined; + // Set Accessor declarations + case ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code: + if (ts.isSetAccessorDeclaration(containingFunction)) { + annotateSetAccessor(changes, sourceFile, containingFunction, program, host, cancellationToken); + return containingFunction; + } + return undefined; + default: + return ts.Debug.fail(String(errorCode)); + } + } + function annotateVariableDeclaration(changes, sourceFile, declaration, program, host, cancellationToken) { + if (ts.isIdentifier(declaration.name)) { + annotate(changes, sourceFile, declaration, inferTypeForVariableFromUsage(declaration.name, program, cancellationToken), program, host); + } + } + function annotateParameters(changes, sourceFile, parameterDeclaration, containingFunction, program, host, cancellationToken) { + if (!ts.isIdentifier(parameterDeclaration.name)) { + return; + } + var parameterInferences = inferTypeForParametersFromUsage(containingFunction, sourceFile, program, cancellationToken) || + containingFunction.parameters.map(function (p) { return ({ + declaration: p, + type: ts.isIdentifier(p.name) ? inferTypeForVariableFromUsage(p.name, program, cancellationToken) : program.getTypeChecker().getAnyType() + }); }); + ts.Debug.assert(containingFunction.parameters.length === parameterInferences.length); + if (ts.isInJSFile(containingFunction)) { + annotateJSDocParameters(changes, sourceFile, parameterInferences, program, host); + } + else { + var needParens = ts.isArrowFunction(containingFunction) && !ts.findChildOfKind(containingFunction, 20 /* OpenParenToken */, sourceFile); + if (needParens) + changes.insertNodeBefore(sourceFile, ts.first(containingFunction.parameters), ts.createToken(20 /* OpenParenToken */)); + for (var _i = 0, parameterInferences_1 = parameterInferences; _i < parameterInferences_1.length; _i++) { + var _a = parameterInferences_1[_i], declaration = _a.declaration, type = _a.type; + if (declaration && !declaration.type && !declaration.initializer) { + annotate(changes, sourceFile, declaration, type, program, host); + } + } + if (needParens) + changes.insertNodeAfter(sourceFile, ts.last(containingFunction.parameters), ts.createToken(21 /* CloseParenToken */)); + } + } + function annotateSetAccessor(changes, sourceFile, setAccessorDeclaration, program, host, cancellationToken) { + var param = ts.firstOrUndefined(setAccessorDeclaration.parameters); + if (param && ts.isIdentifier(setAccessorDeclaration.name) && ts.isIdentifier(param.name)) { + var type = inferTypeForVariableFromUsage(setAccessorDeclaration.name, program, cancellationToken); + if (type === program.getTypeChecker().getAnyType()) { + type = inferTypeForVariableFromUsage(param.name, program, cancellationToken); + } + if (ts.isInJSFile(setAccessorDeclaration)) { + annotateJSDocParameters(changes, sourceFile, [{ declaration: param, type: type }], program, host); + } + else { + annotate(changes, sourceFile, param, type, program, host); + } + } + } + function annotate(changes, sourceFile, declaration, type, program, host) { + var typeNode = getTypeNodeIfAccessible(type, declaration, program, host); + if (typeNode) { + if (ts.isInJSFile(sourceFile) && declaration.kind !== 153 /* PropertySignature */) { + var parent = ts.isVariableDeclaration(declaration) ? ts.tryCast(declaration.parent.parent, ts.isVariableStatement) : declaration; + if (!parent) { + return; + } + var typeExpression = ts.createJSDocTypeExpression(typeNode); + var typeTag = ts.isGetAccessorDeclaration(declaration) ? ts.createJSDocReturnTag(typeExpression, "") : ts.createJSDocTypeTag(typeExpression, ""); + addJSDocTags(changes, sourceFile, parent, [typeTag]); + } + else { + changes.tryInsertTypeAnnotation(sourceFile, declaration, typeNode); + } + } + } + function annotateJSDocParameters(changes, sourceFile, parameterInferences, program, host) { + var signature = parameterInferences.length && parameterInferences[0].declaration.parent; + if (!signature) { + return; + } + var paramTags = ts.mapDefined(parameterInferences, function (inference) { + var param = inference.declaration; + // only infer parameters that have (1) no type and (2) an accessible inferred type + if (param.initializer || ts.getJSDocType(param) || !ts.isIdentifier(param.name)) + return; + var typeNode = inference.type && getTypeNodeIfAccessible(inference.type, param, program, host); + var name = ts.getSynthesizedClone(param.name); + ts.setEmitFlags(name, 1536 /* NoComments */ | 2048 /* NoNestedComments */); + return typeNode && ts.createJSDocParamTag(name, !!inference.isOptional, ts.createJSDocTypeExpression(typeNode), ""); + }); + addJSDocTags(changes, sourceFile, signature, paramTags); + } + function addJSDocTags(changes, sourceFile, parent, newTags) { + var comments = ts.mapDefined(parent.jsDoc, function (j) { return j.comment; }); + var oldTags = ts.flatMapToMutable(parent.jsDoc, function (j) { return j.tags; }); + var unmergedNewTags = newTags.filter(function (newTag) { return !oldTags || !oldTags.some(function (tag, i) { + var merged = tryMergeJsdocTags(tag, newTag); + if (merged) + oldTags[i] = merged; + return !!merged; + }); }); + var tag = ts.createJSDocComment(comments.join("\n"), ts.createNodeArray((oldTags || ts.emptyArray).concat(unmergedNewTags))); + changes.insertJsdocCommentBefore(sourceFile, parent, tag); + } + function tryMergeJsdocTags(oldTag, newTag) { + if (oldTag.kind !== newTag.kind) { + return undefined; + } + switch (oldTag.kind) { + case 299 /* JSDocParameterTag */: { + var oldParam = oldTag; + var newParam = newTag; + return ts.isIdentifier(oldParam.name) && ts.isIdentifier(newParam.name) && oldParam.name.escapedText === newParam.name.escapedText + ? ts.createJSDocParamTag(newParam.name, newParam.isBracketed, newParam.typeExpression, oldParam.comment) + : undefined; + } + case 300 /* JSDocReturnTag */: + return ts.createJSDocReturnTag(newTag.typeExpression, oldTag.comment); + } + } + function getTypeNodeIfAccessible(type, enclosingScope, program, host) { + var checker = program.getTypeChecker(); + var typeIsAccessible = true; + var notAccessible = function () { typeIsAccessible = false; }; + var res = checker.typeToTypeNode(type, enclosingScope, /*flags*/ undefined, { + trackSymbol: function (symbol, declaration, meaning) { + // TODO: GH#18217 + typeIsAccessible = typeIsAccessible && checker.isSymbolAccessible(symbol, declaration, meaning, /*shouldComputeAliasToMarkVisible*/ false).accessibility === 0 /* Accessible */; + }, + reportInaccessibleThisError: notAccessible, + reportPrivateInBaseOfClassExpression: notAccessible, + reportInaccessibleUniqueSymbolError: notAccessible, + moduleResolverHost: { + readFile: host.readFile, + fileExists: host.fileExists, + directoryExists: host.directoryExists, + getSourceFiles: program.getSourceFiles, + getCurrentDirectory: program.getCurrentDirectory, + getCommonSourceDirectory: program.getCommonSourceDirectory, + } + }); + return typeIsAccessible ? res : undefined; + } + function getReferences(token, program, cancellationToken) { + // Position shouldn't matter since token is not a SourceFile. + return ts.mapDefined(ts.FindAllReferences.getReferenceEntriesForNode(-1, token, program, program.getSourceFiles(), cancellationToken), function (entry) { + return entry.kind !== 0 /* Span */ ? ts.tryCast(entry.node, ts.isIdentifier) : undefined; + }); + } + function inferTypeForVariableFromUsage(token, program, cancellationToken) { + var references = getReferences(token, program, cancellationToken); + var checker = program.getTypeChecker(); + var types = InferFromReference.inferTypesFromReferences(references, checker, cancellationToken); + return InferFromReference.unifyFromContext(types, checker); + } + function inferTypeForParametersFromUsage(containingFunction, sourceFile, program, cancellationToken) { + var searchToken; + switch (containingFunction.kind) { + case 157 /* Constructor */: + searchToken = ts.findChildOfKind(containingFunction, 124 /* ConstructorKeyword */, sourceFile); + break; + case 197 /* ArrowFunction */: + case 196 /* FunctionExpression */: + var parent = containingFunction.parent; + searchToken = ts.isVariableDeclaration(parent) && ts.isIdentifier(parent.name) ? + parent.name : + containingFunction.name; + break; + case 239 /* FunctionDeclaration */: + case 156 /* MethodDeclaration */: + searchToken = containingFunction.name; + break; + } + if (searchToken) { + return InferFromReference.inferTypeForParametersFromReferences(getReferences(searchToken, program, cancellationToken), containingFunction, program, cancellationToken); + } + } + var InferFromReference; + (function (InferFromReference) { + function inferTypesFromReferences(references, checker, cancellationToken) { + var usageContext = {}; + for (var _i = 0, references_1 = references; _i < references_1.length; _i++) { + var reference = references_1[_i]; + cancellationToken.throwIfCancellationRequested(); + inferTypeFromContext(reference, checker, usageContext); + } + return inferFromContext(usageContext, checker); + } + InferFromReference.inferTypesFromReferences = inferTypesFromReferences; + function inferTypeForParametersFromReferences(references, declaration, program, cancellationToken) { + var checker = program.getTypeChecker(); + if (references.length === 0) { + return undefined; + } + if (!declaration.parameters) { + return undefined; + } + var usageContext = {}; + for (var _i = 0, references_2 = references; _i < references_2.length; _i++) { + var reference = references_2[_i]; + cancellationToken.throwIfCancellationRequested(); + inferTypeFromContext(reference, checker, usageContext); + } + var callContexts = (usageContext.constructContexts || []).concat(usageContext.callContexts || []); + return declaration.parameters.map(function (parameter, parameterIndex) { + var types = []; + var isRest = ts.isRestParameter(parameter); + var isOptional = false; + for (var _i = 0, callContexts_1 = callContexts; _i < callContexts_1.length; _i++) { + var callContext = callContexts_1[_i]; + if (callContext.argumentTypes.length <= parameterIndex) { + isOptional = ts.isInJSFile(declaration); + types.push(checker.getUndefinedType()); + } + else if (isRest) { + for (var i = parameterIndex; i < callContext.argumentTypes.length; i++) { + types.push(checker.getBaseTypeOfLiteralType(callContext.argumentTypes[i])); + } + } + else { + types.push(checker.getBaseTypeOfLiteralType(callContext.argumentTypes[parameterIndex])); + } + } + if (ts.isIdentifier(parameter.name)) { + var inferred = inferTypesFromReferences(getReferences(parameter.name, program, cancellationToken), checker, cancellationToken); + types.push.apply(types, (isRest ? ts.mapDefined(inferred, checker.getElementTypeOfArrayType) : inferred)); + } + var type = unifyFromContext(types, checker); + return { + type: isRest ? checker.createArrayType(type) : type, + isOptional: isOptional && !isRest, + declaration: parameter + }; + }); + } + InferFromReference.inferTypeForParametersFromReferences = inferTypeForParametersFromReferences; + function inferTypeFromContext(node, checker, usageContext) { + while (ts.isRightSideOfQualifiedNameOrPropertyAccess(node)) { + node = node.parent; + } + switch (node.parent.kind) { + case 203 /* PostfixUnaryExpression */: + usageContext.isNumber = true; + break; + case 202 /* PrefixUnaryExpression */: + inferTypeFromPrefixUnaryExpressionContext(node.parent, usageContext); + break; + case 204 /* BinaryExpression */: + inferTypeFromBinaryExpressionContext(node, node.parent, checker, usageContext); + break; + case 271 /* CaseClause */: + case 272 /* DefaultClause */: + inferTypeFromSwitchStatementLabelContext(node.parent, checker, usageContext); + break; + case 191 /* CallExpression */: + case 192 /* NewExpression */: + if (node.parent.expression === node) { + inferTypeFromCallExpressionContext(node.parent, checker, usageContext); + } + else { + inferTypeFromContextualType(node, checker, usageContext); + } + break; + case 189 /* PropertyAccessExpression */: + inferTypeFromPropertyAccessExpressionContext(node.parent, checker, usageContext); + break; + case 190 /* ElementAccessExpression */: + inferTypeFromPropertyElementExpressionContext(node.parent, node, checker, usageContext); + break; + case 237 /* VariableDeclaration */: { + var _a = node.parent, name = _a.name, initializer = _a.initializer; + if (node === name) { + if (initializer) { // This can happen for `let x = null;` which still has an implicit-any error. + addCandidateType(usageContext, checker.getTypeAtLocation(initializer)); + } + break; + } + } + // falls through + default: + return inferTypeFromContextualType(node, checker, usageContext); + } + } + function inferTypeFromContextualType(node, checker, usageContext) { + if (ts.isExpressionNode(node)) { + addCandidateType(usageContext, checker.getContextualType(node)); + } + } + function inferTypeFromPrefixUnaryExpressionContext(node, usageContext) { + switch (node.operator) { + case 44 /* PlusPlusToken */: + case 45 /* MinusMinusToken */: + case 39 /* MinusToken */: + case 53 /* TildeToken */: + usageContext.isNumber = true; + break; + case 38 /* PlusToken */: + usageContext.isNumberOrString = true; + break; + // case SyntaxKind.ExclamationToken: + // no inferences here; + } + } + function inferTypeFromBinaryExpressionContext(node, parent, checker, usageContext) { + switch (parent.operatorToken.kind) { + // ExponentiationOperator + case 41 /* AsteriskAsteriskToken */: + // MultiplicativeOperator + case 40 /* AsteriskToken */: + case 42 /* SlashToken */: + case 43 /* PercentToken */: + // ShiftOperator + case 46 /* LessThanLessThanToken */: + case 47 /* GreaterThanGreaterThanToken */: + case 48 /* GreaterThanGreaterThanGreaterThanToken */: + // BitwiseOperator + case 49 /* AmpersandToken */: + case 50 /* BarToken */: + case 51 /* CaretToken */: + // CompoundAssignmentOperator + case 61 /* MinusEqualsToken */: + case 63 /* AsteriskAsteriskEqualsToken */: + case 62 /* AsteriskEqualsToken */: + case 64 /* SlashEqualsToken */: + case 65 /* PercentEqualsToken */: + case 69 /* AmpersandEqualsToken */: + case 70 /* BarEqualsToken */: + case 71 /* CaretEqualsToken */: + case 66 /* LessThanLessThanEqualsToken */: + case 68 /* GreaterThanGreaterThanGreaterThanEqualsToken */: + case 67 /* GreaterThanGreaterThanEqualsToken */: + // AdditiveOperator + case 39 /* MinusToken */: + // RelationalOperator + case 28 /* LessThanToken */: + case 31 /* LessThanEqualsToken */: + case 30 /* GreaterThanToken */: + case 32 /* GreaterThanEqualsToken */: + var operandType = checker.getTypeAtLocation(parent.left === node ? parent.right : parent.left); + if (operandType.flags & 1056 /* EnumLike */) { + addCandidateType(usageContext, operandType); + } + else { + usageContext.isNumber = true; + } + break; + case 60 /* PlusEqualsToken */: + case 38 /* PlusToken */: + var otherOperandType = checker.getTypeAtLocation(parent.left === node ? parent.right : parent.left); + if (otherOperandType.flags & 1056 /* EnumLike */) { + addCandidateType(usageContext, otherOperandType); + } + else if (otherOperandType.flags & 296 /* NumberLike */) { + usageContext.isNumber = true; + } + else if (otherOperandType.flags & 132 /* StringLike */) { + usageContext.isString = true; + } + else { + usageContext.isNumberOrString = true; + } + break; + // AssignmentOperators + case 59 /* EqualsToken */: + case 33 /* EqualsEqualsToken */: + case 35 /* EqualsEqualsEqualsToken */: + case 36 /* ExclamationEqualsEqualsToken */: + case 34 /* ExclamationEqualsToken */: + addCandidateType(usageContext, checker.getTypeAtLocation(parent.left === node ? parent.right : parent.left)); + break; + case 93 /* InKeyword */: + if (node === parent.left) { + usageContext.isString = true; + } + break; + // LogicalOperator + case 55 /* BarBarToken */: + if (node === parent.left && + (node.parent.parent.kind === 237 /* VariableDeclaration */ || ts.isAssignmentExpression(node.parent.parent, /*excludeCompoundAssignment*/ true))) { + // var x = x || {}; + // TODO: use getFalsyflagsOfType + addCandidateType(usageContext, checker.getTypeAtLocation(parent.right)); + } + break; + case 54 /* AmpersandAmpersandToken */: + case 27 /* CommaToken */: + case 94 /* InstanceOfKeyword */: + // nothing to infer here + break; + } + } + function inferTypeFromSwitchStatementLabelContext(parent, checker, usageContext) { + addCandidateType(usageContext, checker.getTypeAtLocation(parent.parent.parent.expression)); + } + function inferTypeFromCallExpressionContext(parent, checker, usageContext) { + var callContext = { + argumentTypes: [], + returnType: {} + }; + if (parent.arguments) { + for (var _i = 0, _a = parent.arguments; _i < _a.length; _i++) { + var argument = _a[_i]; + callContext.argumentTypes.push(checker.getTypeAtLocation(argument)); + } + } + inferTypeFromContext(parent, checker, callContext.returnType); + if (parent.kind === 191 /* CallExpression */) { + (usageContext.callContexts || (usageContext.callContexts = [])).push(callContext); + } + else { + (usageContext.constructContexts || (usageContext.constructContexts = [])).push(callContext); + } + } + function inferTypeFromPropertyAccessExpressionContext(parent, checker, usageContext) { + var name = ts.escapeLeadingUnderscores(parent.name.text); + if (!usageContext.properties) { + usageContext.properties = ts.createUnderscoreEscapedMap(); + } + var propertyUsageContext = usageContext.properties.get(name) || {}; + inferTypeFromContext(parent, checker, propertyUsageContext); + usageContext.properties.set(name, propertyUsageContext); + } + function inferTypeFromPropertyElementExpressionContext(parent, node, checker, usageContext) { + if (node === parent.argumentExpression) { + usageContext.isNumberOrString = true; + return; + } + else { + var indexType = checker.getTypeAtLocation(parent.argumentExpression); + var indexUsageContext = {}; + inferTypeFromContext(parent, checker, indexUsageContext); + if (indexType.flags & 296 /* NumberLike */) { + usageContext.numberIndexContext = indexUsageContext; + } + else { + usageContext.stringIndexContext = indexUsageContext; + } + } + } + function removeLowPriorityInferences(inferences, priorities) { + var toRemove = []; + for (var _i = 0, inferences_2 = inferences; _i < inferences_2.length; _i++) { + var i = inferences_2[_i]; + for (var _a = 0, priorities_1 = priorities; _a < priorities_1.length; _a++) { + var _b = priorities_1[_a], high = _b.high, low = _b.low; + if (high(i)) { + ts.Debug.assert(!low(i)); + toRemove.push(low); + } + } + } + return inferences.filter(function (i) { return toRemove.every(function (f) { return !f(i); }); }); + } + function unifyFromContext(inferences, checker, fallback) { + if (fallback === void 0) { fallback = checker.getAnyType(); } + if (!inferences.length) + return fallback; + // 1. string or number individually override string | number + // 2. non-any, non-void overrides any or void + // 3. non-nullable, non-any, non-void, non-anonymous overrides anonymous types + var stringNumber = checker.getUnionType([checker.getStringType(), checker.getNumberType()]); + var priorities = [ + { + high: function (t) { return t === checker.getStringType() || t === checker.getNumberType(); }, + low: function (t) { return t === stringNumber; } + }, + { + high: function (t) { return !(t.flags & (1 /* Any */ | 16384 /* Void */)); }, + low: function (t) { return !!(t.flags & (1 /* Any */ | 16384 /* Void */)); } + }, + { + high: function (t) { return !(t.flags & (98304 /* Nullable */ | 1 /* Any */ | 16384 /* Void */)) && !(checker.getObjectFlags(t) & 16 /* Anonymous */); }, + low: function (t) { return !!(checker.getObjectFlags(t) & 16 /* Anonymous */); } + } + ]; + var good = removeLowPriorityInferences(inferences, priorities); + var anons = good.filter(function (i) { return checker.getObjectFlags(i) & 16 /* Anonymous */; }); + if (anons.length) { + good = good.filter(function (i) { return !(checker.getObjectFlags(i) & 16 /* Anonymous */); }); + good.push(unifyAnonymousTypes(anons, checker)); + } + return checker.getWidenedType(checker.getUnionType(good)); + } + InferFromReference.unifyFromContext = unifyFromContext; + function unifyAnonymousTypes(anons, checker) { + if (anons.length === 1) { + return anons[0]; + } + var calls = []; + var constructs = []; + var stringIndices = []; + var numberIndices = []; + var stringIndexReadonly = false; + var numberIndexReadonly = false; + var props = ts.createMultiMap(); + for (var _i = 0, anons_1 = anons; _i < anons_1.length; _i++) { + var anon = anons_1[_i]; + for (var _a = 0, _b = checker.getPropertiesOfType(anon); _a < _b.length; _a++) { + var p = _b[_a]; + props.add(p.name, checker.getTypeOfSymbolAtLocation(p, p.valueDeclaration)); + } + calls.push.apply(calls, checker.getSignaturesOfType(anon, 0 /* Call */)); + constructs.push.apply(constructs, checker.getSignaturesOfType(anon, 1 /* Construct */)); + if (anon.stringIndexInfo) { + stringIndices.push(anon.stringIndexInfo.type); + stringIndexReadonly = stringIndexReadonly || anon.stringIndexInfo.isReadonly; + } + if (anon.numberIndexInfo) { + numberIndices.push(anon.numberIndexInfo.type); + numberIndexReadonly = numberIndexReadonly || anon.numberIndexInfo.isReadonly; + } + } + var members = ts.mapEntries(props, function (name, types) { + var isOptional = types.length < anons.length ? 16777216 /* Optional */ : 0; + var s = checker.createSymbol(4 /* Property */ | isOptional, name); + s.type = checker.getUnionType(types); + return [name, s]; + }); + return checker.createAnonymousType(anons[0].symbol, members, calls, constructs, stringIndices.length ? checker.createIndexInfo(checker.getUnionType(stringIndices), stringIndexReadonly) : undefined, numberIndices.length ? checker.createIndexInfo(checker.getUnionType(numberIndices), numberIndexReadonly) : undefined); + } + function inferFromContext(usageContext, checker) { + var types = []; + if (usageContext.isNumber) { + types.push(checker.getNumberType()); + } + if (usageContext.isString) { + types.push(checker.getStringType()); + } + if (usageContext.isNumberOrString) { + types.push(checker.getUnionType([checker.getStringType(), checker.getNumberType()])); + } + types.push.apply(types, (usageContext.candidateTypes || []).map(function (t) { return checker.getBaseTypeOfLiteralType(t); })); + if (usageContext.properties && hasCallContext(usageContext.properties.get("then"))) { + var paramType = getParameterTypeFromCallContexts(0, usageContext.properties.get("then").callContexts, /*isRestParameter*/ false, checker); // TODO: GH#18217 + var types_19 = paramType.getCallSignatures().map(function (c) { return c.getReturnType(); }); + types_19.push(checker.createPromiseType(types_19.length ? checker.getUnionType(types_19, 2 /* Subtype */) : checker.getAnyType())); + } + else if (usageContext.properties && hasCallContext(usageContext.properties.get("push"))) { + types.push(checker.createArrayType(getParameterTypeFromCallContexts(0, usageContext.properties.get("push").callContexts, /*isRestParameter*/ false, checker))); + } + if (usageContext.numberIndexContext) { + types.push(checker.createArrayType(recur(usageContext.numberIndexContext))); + } + else if (usageContext.properties || usageContext.callContexts || usageContext.constructContexts || usageContext.stringIndexContext) { + var members_6 = ts.createUnderscoreEscapedMap(); + var callSignatures = []; + var constructSignatures = []; + var stringIndexInfo = void 0; + if (usageContext.properties) { + usageContext.properties.forEach(function (context, name) { + var symbol = checker.createSymbol(4 /* Property */, name); + symbol.type = recur(context); + members_6.set(name, symbol); + }); + } + if (usageContext.callContexts) { + for (var _i = 0, _a = usageContext.callContexts; _i < _a.length; _i++) { + var callContext = _a[_i]; + callSignatures.push(getSignatureFromCallContext(callContext, checker)); + } + } + if (usageContext.constructContexts) { + for (var _b = 0, _c = usageContext.constructContexts; _b < _c.length; _b++) { + var constructContext = _c[_b]; + constructSignatures.push(getSignatureFromCallContext(constructContext, checker)); + } + } + if (usageContext.stringIndexContext) { + stringIndexInfo = checker.createIndexInfo(recur(usageContext.stringIndexContext), /*isReadonly*/ false); + } + types.push(checker.createAnonymousType(/*symbol*/ undefined, members_6, callSignatures, constructSignatures, stringIndexInfo, /*numberIndexInfo*/ undefined)); // TODO: GH#18217 + } + return types; + function recur(innerContext) { + return unifyFromContext(inferFromContext(innerContext, checker), checker); + } + } + function getParameterTypeFromCallContexts(parameterIndex, callContexts, isRestParameter, checker) { + var types = []; + if (callContexts) { + for (var _i = 0, callContexts_2 = callContexts; _i < callContexts_2.length; _i++) { + var callContext = callContexts_2[_i]; + if (callContext.argumentTypes.length > parameterIndex) { + if (isRestParameter) { + types = ts.concatenate(types, ts.map(callContext.argumentTypes.slice(parameterIndex), function (a) { return checker.getBaseTypeOfLiteralType(a); })); + } + else { + types.push(checker.getBaseTypeOfLiteralType(callContext.argumentTypes[parameterIndex])); + } + } + } + } + if (types.length) { + var type = checker.getWidenedType(checker.getUnionType(types, 2 /* Subtype */)); + return isRestParameter ? checker.createArrayType(type) : type; + } + return undefined; + } + function getSignatureFromCallContext(callContext, checker) { + var parameters = []; + for (var i = 0; i < callContext.argumentTypes.length; i++) { + var symbol = checker.createSymbol(1 /* FunctionScopedVariable */, ts.escapeLeadingUnderscores("arg" + i)); + symbol.type = checker.getWidenedType(checker.getBaseTypeOfLiteralType(callContext.argumentTypes[i])); + parameters.push(symbol); + } + var returnType = unifyFromContext(inferFromContext(callContext.returnType, checker), checker, checker.getVoidType()); + // TODO: GH#18217 + return checker.createSignature(/*declaration*/ undefined, /*typeParameters*/ undefined, /*thisParameter*/ undefined, parameters, returnType, /*typePredicate*/ undefined, callContext.argumentTypes.length, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + } + function addCandidateType(context, type) { + if (type && !(type.flags & 1 /* Any */) && !(type.flags & 131072 /* Never */)) { + (context.candidateTypes || (context.candidateTypes = [])).push(type); + } + } + function hasCallContext(usageContext) { + return !!usageContext && !!usageContext.callContexts; + } + })(InferFromReference || (InferFromReference = {})); + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "convertFunctionToEs6Class"; + var errorCodes = [ts.Diagnostics.This_constructor_function_may_be_converted_to_a_class_declaration.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, context.sourceFile, context.span.start, context.program.getTypeChecker()); }); + return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Convert_function_to_an_ES2015_class, fixId, ts.Diagnostics.Convert_all_constructor_functions_to_classes)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, err) { return doChange(changes, err.file, err.start, context.program.getTypeChecker()); }); }, + }); + function doChange(changes, sourceFile, position, checker) { + var ctorSymbol = checker.getSymbolAtLocation(ts.getTokenAtPosition(sourceFile, position)); + if (!ctorSymbol || !(ctorSymbol.flags & (16 /* Function */ | 3 /* Variable */))) { + // Bad input + return undefined; + } + var ctorDeclaration = ctorSymbol.valueDeclaration; + var precedingNode; + var newClassDeclaration; + switch (ctorDeclaration.kind) { + case 239 /* FunctionDeclaration */: + precedingNode = ctorDeclaration; + changes.delete(sourceFile, ctorDeclaration); + newClassDeclaration = createClassFromFunctionDeclaration(ctorDeclaration); + break; + case 237 /* VariableDeclaration */: + precedingNode = ctorDeclaration.parent.parent; + newClassDeclaration = createClassFromVariableDeclaration(ctorDeclaration); + if (ctorDeclaration.parent.declarations.length === 1) { + ts.copyComments(precedingNode, newClassDeclaration, sourceFile); // TODO: GH#18217 + changes.delete(sourceFile, precedingNode); + } + else { + changes.delete(sourceFile, ctorDeclaration); + } + break; + } + if (!newClassDeclaration) { + return undefined; + } + ts.copyComments(ctorDeclaration, newClassDeclaration, sourceFile); + // Because the preceding node could be touched, we need to insert nodes before delete nodes. + changes.insertNodeAfter(sourceFile, precedingNode, newClassDeclaration); + function createClassElementsFromSymbol(symbol) { + var memberElements = []; + // all instance members are stored in the "member" array of symbol + if (symbol.members) { + symbol.members.forEach(function (member) { + var memberElement = createClassElement(member, /*modifiers*/ undefined); + if (memberElement) { + memberElements.push(memberElement); + } + }); + } + // all static members are stored in the "exports" array of symbol + if (symbol.exports) { + symbol.exports.forEach(function (member) { + var memberElement = createClassElement(member, [ts.createToken(116 /* StaticKeyword */)]); + if (memberElement) { + memberElements.push(memberElement); + } + }); + } + return memberElements; + function shouldConvertDeclaration(_target, source) { + // Right now the only thing we can convert are function expressions - other values shouldn't get + // transformed. We can update this once ES public class properties are available. + return ts.isFunctionLike(source); + } + function createClassElement(symbol, modifiers) { + // Right now the only thing we can convert are function expressions, which are marked as methods + if (!(symbol.flags & 8192 /* Method */)) { + return; + } + var memberDeclaration = symbol.valueDeclaration; + var assignmentBinaryExpression = memberDeclaration.parent; + if (!shouldConvertDeclaration(memberDeclaration, assignmentBinaryExpression.right)) { + return; + } + // delete the entire statement if this expression is the sole expression to take care of the semicolon at the end + var nodeToDelete = assignmentBinaryExpression.parent && assignmentBinaryExpression.parent.kind === 221 /* ExpressionStatement */ + ? assignmentBinaryExpression.parent : assignmentBinaryExpression; + changes.delete(sourceFile, nodeToDelete); + if (!assignmentBinaryExpression.right) { + return ts.createProperty([], modifiers, symbol.name, /*questionToken*/ undefined, + /*type*/ undefined, /*initializer*/ undefined); + } + switch (assignmentBinaryExpression.right.kind) { + case 196 /* FunctionExpression */: { + var functionExpression = assignmentBinaryExpression.right; + var fullModifiers = ts.concatenate(modifiers, getModifierKindFromSource(functionExpression, 121 /* AsyncKeyword */)); + var method = ts.createMethod(/*decorators*/ undefined, fullModifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined, + /*typeParameters*/ undefined, functionExpression.parameters, /*type*/ undefined, functionExpression.body); + ts.copyComments(assignmentBinaryExpression, method, sourceFile); + return method; + } + case 197 /* ArrowFunction */: { + var arrowFunction = assignmentBinaryExpression.right; + var arrowFunctionBody = arrowFunction.body; + var bodyBlock = void 0; + // case 1: () => { return [1,2,3] } + if (arrowFunctionBody.kind === 218 /* Block */) { + bodyBlock = arrowFunctionBody; + } + // case 2: () => [1,2,3] + else { + bodyBlock = ts.createBlock([ts.createReturn(arrowFunctionBody)]); + } + var fullModifiers = ts.concatenate(modifiers, getModifierKindFromSource(arrowFunction, 121 /* AsyncKeyword */)); + var method = ts.createMethod(/*decorators*/ undefined, fullModifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined, + /*typeParameters*/ undefined, arrowFunction.parameters, /*type*/ undefined, bodyBlock); + ts.copyComments(assignmentBinaryExpression, method, sourceFile); + return method; + } + default: { + // Don't try to declare members in JavaScript files + if (ts.isSourceFileJS(sourceFile)) { + return; + } + var prop = ts.createProperty(/*decorators*/ undefined, modifiers, memberDeclaration.name, /*questionToken*/ undefined, + /*type*/ undefined, assignmentBinaryExpression.right); + ts.copyComments(assignmentBinaryExpression.parent, prop, sourceFile); + return prop; + } + } + } + } + function createClassFromVariableDeclaration(node) { + var initializer = node.initializer; + if (!initializer || initializer.kind !== 196 /* FunctionExpression */) { + return undefined; + } + if (node.name.kind !== 72 /* Identifier */) { + return undefined; + } + var memberElements = createClassElementsFromSymbol(node.symbol); + if (initializer.body) { + memberElements.unshift(ts.createConstructor(/*decorators*/ undefined, /*modifiers*/ undefined, initializer.parameters, initializer.body)); + } + var modifiers = getModifierKindFromSource(precedingNode, 85 /* ExportKeyword */); + var cls = ts.createClassDeclaration(/*decorators*/ undefined, modifiers, node.name, + /*typeParameters*/ undefined, /*heritageClauses*/ undefined, memberElements); + // Don't call copyComments here because we'll already leave them in place + return cls; + } + function createClassFromFunctionDeclaration(node) { + var memberElements = createClassElementsFromSymbol(ctorSymbol); + if (node.body) { + memberElements.unshift(ts.createConstructor(/*decorators*/ undefined, /*modifiers*/ undefined, node.parameters, node.body)); + } + var modifiers = getModifierKindFromSource(node, 85 /* ExportKeyword */); + var cls = ts.createClassDeclaration(/*decorators*/ undefined, modifiers, node.name, + /*typeParameters*/ undefined, /*heritageClauses*/ undefined, memberElements); + // Don't call copyComments here because we'll already leave them in place + return cls; + } + } + function getModifierKindFromSource(source, kind) { + return ts.filter(source.modifiers, function (modifier) { return modifier.kind === kind; }); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "convertToAsyncFunction"; + var errorCodes = [ts.Diagnostics.This_may_be_converted_to_an_async_function.code]; + var codeActionSucceeded = true; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + codeActionSucceeded = true; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return convertToAsyncFunction(t, context.sourceFile, context.span.start, context.program.getTypeChecker(), context); }); + return codeActionSucceeded ? [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Convert_to_async_function, fixId, ts.Diagnostics.Convert_all_to_async_functions)] : []; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, err) { return convertToAsyncFunction(changes, err.file, err.start, context.program.getTypeChecker(), context); }); }, + }); + function convertToAsyncFunction(changes, sourceFile, position, checker, context) { + // get the function declaration - returns a promise + var tokenAtPosition = ts.getTokenAtPosition(sourceFile, position); + var functionToConvert; + // if the parent of a FunctionLikeDeclaration is a variable declaration, the convertToAsync diagnostic will be reported on the variable name + if (ts.isIdentifier(tokenAtPosition) && ts.isVariableDeclaration(tokenAtPosition.parent) && + tokenAtPosition.parent.initializer && ts.isFunctionLikeDeclaration(tokenAtPosition.parent.initializer)) { + functionToConvert = tokenAtPosition.parent.initializer; + } + else { + functionToConvert = ts.tryCast(ts.getContainingFunction(ts.getTokenAtPosition(sourceFile, position)), ts.isFunctionLikeDeclaration); + } + if (!functionToConvert) { + return; + } + var synthNamesMap = ts.createMap(); + var originalTypeMap = ts.createMap(); + var allVarNames = []; + var isInJavascript = ts.isInJSFile(functionToConvert); + var setOfExpressionsToReturn = getAllPromiseExpressionsToReturn(functionToConvert, checker); + var functionToConvertRenamed = renameCollidingVarNames(functionToConvert, checker, synthNamesMap, context, setOfExpressionsToReturn, originalTypeMap, allVarNames); + var constIdentifiers = getConstIdentifiers(synthNamesMap); + var returnStatements = functionToConvertRenamed.body && ts.isBlock(functionToConvertRenamed.body) ? getReturnStatementsWithPromiseHandlers(functionToConvertRenamed.body) : ts.emptyArray; + var transformer = { checker: checker, synthNamesMap: synthNamesMap, allVarNames: allVarNames, setOfExpressionsToReturn: setOfExpressionsToReturn, constIdentifiers: constIdentifiers, originalTypeMap: originalTypeMap, isInJSFile: isInJavascript }; + if (!returnStatements.length) { + return; + } + // add the async keyword + changes.insertLastModifierBefore(sourceFile, 121 /* AsyncKeyword */, functionToConvert); + function startTransformation(node, nodeToReplace) { + var newNodes = transformExpression(node, transformer, node); + changes.replaceNodeWithNodes(sourceFile, nodeToReplace, newNodes); + } + var _loop_19 = function (statement) { + ts.forEachChild(statement, function visit(node) { + if (ts.isCallExpression(node)) { + startTransformation(node, statement); + } + else if (!ts.isFunctionLike(node)) { + ts.forEachChild(node, visit); + } + }); + }; + for (var _i = 0, returnStatements_1 = returnStatements; _i < returnStatements_1.length; _i++) { + var statement = returnStatements_1[_i]; + _loop_19(statement); + } + } + function getReturnStatementsWithPromiseHandlers(body) { + var res = []; + ts.forEachReturnStatement(body, function (ret) { + if (ts.isReturnStatementWithFixablePromiseHandler(ret)) + res.push(ret); + }); + return res; + } + // Returns the identifiers that are never reassigned in the refactor + function getConstIdentifiers(synthNamesMap) { + var constIdentifiers = []; + synthNamesMap.forEach(function (val) { + if (val.numberOfAssignmentsOriginal === 0) { + constIdentifiers.push(val.identifier); + } + }); + return constIdentifiers; + } + /* + Finds all of the expressions of promise type that should not be saved in a variable during the refactor + */ + function getAllPromiseExpressionsToReturn(func, checker) { + if (!func.body) { + return ts.createMap(); + } + var setOfExpressionsToReturn = ts.createMap(); + ts.forEachChild(func.body, function visit(node) { + if (isPromiseReturningExpression(node, checker, "then")) { + setOfExpressionsToReturn.set(ts.getNodeId(node).toString(), true); + ts.forEach(node.arguments, visit); + } + else if (isPromiseReturningExpression(node, checker, "catch")) { + setOfExpressionsToReturn.set(ts.getNodeId(node).toString(), true); + // if .catch() is the last call in the chain, move leftward in the chain until we hit something else that should be returned + ts.forEachChild(node, visit); + } + else if (isPromiseReturningExpression(node, checker)) { + setOfExpressionsToReturn.set(ts.getNodeId(node).toString(), true); + // don't recurse here, since we won't refactor any children or arguments of the expression + } + else { + ts.forEachChild(node, visit); + } + }); + return setOfExpressionsToReturn; + } + /* + Returns true if node is a promise returning expression + If name is not undefined, node is a promise returning call of name + */ + function isPromiseReturningExpression(node, checker, name) { + var isNodeExpression = name ? ts.isCallExpression(node) : ts.isExpression(node); + var isExpressionOfName = isNodeExpression && (!name || ts.hasPropertyAccessExpressionWithName(node, name)); + var nodeType = isExpressionOfName && checker.getTypeAtLocation(node); + return !!(nodeType && checker.getPromisedTypeOfPromise(nodeType)); + } + function declaredInFile(symbol, sourceFile) { + return symbol.valueDeclaration && symbol.valueDeclaration.getSourceFile() === sourceFile; + } + /* + Renaming of identifiers may be neccesary as the refactor changes scopes - + This function collects all existing identifier names and names of identifiers that will be created in the refactor. + It then checks for any collisions and renames them through getSynthesizedDeepClone + */ + function renameCollidingVarNames(nodeToRename, checker, synthNamesMap, context, setOfAllExpressionsToReturn, originalType, allVarNames) { + var identsToRenameMap = ts.createMap(); // key is the symbol id + var collidingSymbolMap = ts.createMap(); + ts.forEachChild(nodeToRename, function visit(node) { + if (!ts.isIdentifier(node)) { + ts.forEachChild(node, visit); + return; + } + var symbol = checker.getSymbolAtLocation(node); + var isDefinedInFile = symbol && declaredInFile(symbol, context.sourceFile); + if (symbol && isDefinedInFile) { + var type = checker.getTypeAtLocation(node); + var lastCallSignature = getLastCallSignature(type, checker); + var symbolIdString = ts.getSymbolId(symbol).toString(); + // if the identifier refers to a function we want to add the new synthesized variable for the declaration (ex. blob in let blob = res(arg)) + // Note - the choice of the last call signature is arbitrary + if (lastCallSignature && !ts.isFunctionLikeDeclaration(node.parent) && !synthNamesMap.has(symbolIdString)) { + var firstParameter = ts.firstOrUndefined(lastCallSignature.parameters); + var ident = firstParameter && ts.isParameter(firstParameter.valueDeclaration) && ts.tryCast(firstParameter.valueDeclaration.name, ts.isIdentifier) || ts.createOptimisticUniqueName("result"); + var synthName = getNewNameIfConflict(ident, collidingSymbolMap); + synthNamesMap.set(symbolIdString, synthName); + allVarNames.push({ identifier: synthName.identifier, symbol: symbol }); + addNameToFrequencyMap(collidingSymbolMap, ident.text, symbol); + } + // we only care about identifiers that are parameters and declarations (don't care about other uses) + else if (node.parent && (ts.isParameter(node.parent) || ts.isVariableDeclaration(node.parent))) { + var originalName = node.text; + var collidingSymbols = collidingSymbolMap.get(originalName); + // if the identifier name conflicts with a different identifier that we've already seen + if (collidingSymbols && collidingSymbols.some(function (prevSymbol) { return prevSymbol !== symbol; })) { + var newName = getNewNameIfConflict(node, collidingSymbolMap); + identsToRenameMap.set(symbolIdString, newName.identifier); + synthNamesMap.set(symbolIdString, newName); + allVarNames.push({ identifier: newName.identifier, symbol: symbol }); + addNameToFrequencyMap(collidingSymbolMap, originalName, symbol); + } + else { + var identifier = ts.getSynthesizedDeepClone(node); + identsToRenameMap.set(symbolIdString, identifier); + synthNamesMap.set(symbolIdString, { identifier: identifier, types: [], numberOfAssignmentsOriginal: allVarNames.filter(function (elem) { return elem.identifier.text === node.text; }).length /*, numberOfAssignmentsSynthesized: 0*/ }); + if ((ts.isParameter(node.parent) && isExpressionOrCallOnTypePromise(node.parent.parent)) || ts.isVariableDeclaration(node.parent)) { + allVarNames.push({ identifier: identifier, symbol: symbol }); + addNameToFrequencyMap(collidingSymbolMap, originalName, symbol); + } + } + } + } + }); + return ts.getSynthesizedDeepCloneWithRenames(nodeToRename, /*includeTrivia*/ true, identsToRenameMap, checker, deepCloneCallback); + function isExpressionOrCallOnTypePromise(child) { + var node = child.parent; + if (ts.isCallExpression(node) || ts.isIdentifier(node) && !setOfAllExpressionsToReturn.get(ts.getNodeId(node).toString())) { + var nodeType = checker.getTypeAtLocation(node); + var isPromise = nodeType && checker.getPromisedTypeOfPromise(nodeType); + return !!isPromise; + } + return false; + } + function deepCloneCallback(node, clone) { + if (ts.isIdentifier(node)) { + var symbol = checker.getSymbolAtLocation(node); + var symboldIdString = symbol && ts.getSymbolId(symbol).toString(); + var renameInfo = symbol && synthNamesMap.get(symboldIdString); + if (renameInfo) { + var type = checker.getTypeAtLocation(node); + originalType.set(ts.getNodeId(clone).toString(), type); + } + } + var val = setOfAllExpressionsToReturn.get(ts.getNodeId(node).toString()); + if (val !== undefined) { + setOfAllExpressionsToReturn.delete(ts.getNodeId(node).toString()); + setOfAllExpressionsToReturn.set(ts.getNodeId(clone).toString(), val); + } + } + } + function addNameToFrequencyMap(renamedVarNameFrequencyMap, originalName, symbol) { + if (renamedVarNameFrequencyMap.has(originalName)) { + renamedVarNameFrequencyMap.get(originalName).push(symbol); + } + else { + renamedVarNameFrequencyMap.set(originalName, [symbol]); + } + } + function getNewNameIfConflict(name, originalNames) { + var numVarsSameName = (originalNames.get(name.text) || ts.emptyArray).length; + var numberOfAssignmentsOriginal = 0; + var identifier = numVarsSameName === 0 ? name : ts.createIdentifier(name.text + "_" + numVarsSameName); + return { identifier: identifier, types: [], numberOfAssignmentsOriginal: numberOfAssignmentsOriginal }; + } + // dispatch function to recursively build the refactoring + // should be kept up to date with isFixablePromiseHandler in suggestionDiagnostics.ts + function transformExpression(node, transformer, outermostParent, prevArgName) { + if (!node) { + return ts.emptyArray; + } + var originalType = ts.isIdentifier(node) && transformer.originalTypeMap.get(ts.getNodeId(node).toString()); + var nodeType = originalType || transformer.checker.getTypeAtLocation(node); + if (ts.isCallExpression(node) && ts.hasPropertyAccessExpressionWithName(node, "then") && nodeType && !!transformer.checker.getPromisedTypeOfPromise(nodeType)) { + return transformThen(node, transformer, outermostParent, prevArgName); + } + else if (ts.isCallExpression(node) && ts.hasPropertyAccessExpressionWithName(node, "catch") && nodeType && !!transformer.checker.getPromisedTypeOfPromise(nodeType)) { + return transformCatch(node, transformer, prevArgName); + } + else if (ts.isPropertyAccessExpression(node)) { + return transformExpression(node.expression, transformer, outermostParent, prevArgName); + } + else if (nodeType && transformer.checker.getPromisedTypeOfPromise(nodeType)) { + return transformPromiseCall(node, transformer, prevArgName); + } + codeActionSucceeded = false; + return ts.emptyArray; + } + function transformCatch(node, transformer, prevArgName) { + var func = node.arguments[0]; + var argName = getArgName(func, transformer); + var shouldReturn = transformer.setOfExpressionsToReturn.get(ts.getNodeId(node).toString()); + /* + If there is another call in the chain after the .catch() we are transforming, we will need to save the result of both paths (try block and catch block) + To do this, we will need to synthesize a variable that we were not aware of while we were adding identifiers to the synthNamesMap + We will use the prevArgName and then update the synthNamesMap with a new variable name for the next transformation step + */ + if (prevArgName && !shouldReturn) { + prevArgName.numberOfAssignmentsOriginal = 2; // Try block and catch block + transformer.synthNamesMap.forEach(function (val, key) { + if (val.identifier.text === prevArgName.identifier.text) { + var newSynthName = createUniqueSynthName(prevArgName); + transformer.synthNamesMap.set(key, newSynthName); + } + }); + // update the constIdentifiers list + if (transformer.constIdentifiers.some(function (elem) { return elem.text === prevArgName.identifier.text; })) { + transformer.constIdentifiers.push(createUniqueSynthName(prevArgName).identifier); + } + } + var tryBlock = ts.createBlock(transformExpression(node.expression, transformer, node, prevArgName)); + var transformationBody = getTransformationBody(func, prevArgName, argName, node, transformer); + var catchArg = argName ? argName.identifier.text : "e"; + var catchClause = ts.createCatchClause(catchArg, ts.createBlock(transformationBody)); + /* + In order to avoid an implicit any, we will synthesize a type for the declaration using the unions of the types of both paths (try block and catch block) + */ + var varDeclList; + if (prevArgName && !shouldReturn) { + var typeArray = prevArgName.types; + var unionType = transformer.checker.getUnionType(typeArray, 2 /* Subtype */); + var unionTypeNode = transformer.isInJSFile ? undefined : transformer.checker.typeToTypeNode(unionType); + var varDecl = [ts.createVariableDeclaration(ts.getSynthesizedDeepClone(prevArgName.identifier), unionTypeNode)]; + varDeclList = ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList(varDecl, 1 /* Let */)); + } + var tryStatement = ts.createTry(tryBlock, catchClause, /*finallyBlock*/ undefined); + return varDeclList ? [varDeclList, tryStatement] : [tryStatement]; + } + function createUniqueSynthName(prevArgName) { + var renamedPrevArg = ts.createOptimisticUniqueName(prevArgName.identifier.text); + var newSynthName = { identifier: renamedPrevArg, types: [], numberOfAssignmentsOriginal: 0 }; + return newSynthName; + } + function transformThen(node, transformer, outermostParent, prevArgName) { + var _a = node.arguments, res = _a[0], rej = _a[1]; + if (!res) { + return transformExpression(node.expression, transformer, outermostParent); + } + var argNameRes = getArgName(res, transformer); + var transformationBody = getTransformationBody(res, prevArgName, argNameRes, node, transformer); + if (rej) { + var argNameRej = getArgName(rej, transformer); + var tryBlock = ts.createBlock(transformExpression(node.expression, transformer, node, argNameRes).concat(transformationBody)); + var transformationBody2 = getTransformationBody(rej, prevArgName, argNameRej, node, transformer); + var catchArg = argNameRej ? argNameRej.identifier.text : "e"; + var catchClause = ts.createCatchClause(catchArg, ts.createBlock(transformationBody2)); + return [ts.createTry(tryBlock, catchClause, /* finallyBlock */ undefined)]; + } + return transformExpression(node.expression, transformer, node, argNameRes).concat(transformationBody); + } + function getFlagOfIdentifier(node, constIdentifiers) { + var inArr = constIdentifiers.some(function (elem) { return elem.text === node.text; }); + return inArr ? 2 /* Const */ : 1 /* Let */; + } + function transformPromiseCall(node, transformer, prevArgName) { + var shouldReturn = transformer.setOfExpressionsToReturn.get(ts.getNodeId(node).toString()); + // the identifier is empty when the handler (.then()) ignores the argument - In this situation we do not need to save the result of the promise returning call + var originalNodeParent = node.original ? node.original.parent : node.parent; + if (prevArgName && !shouldReturn && (!originalNodeParent || ts.isPropertyAccessExpression(originalNodeParent))) { + return createTransformedStatement(prevArgName, ts.createAwait(node), transformer); + } + else if (!prevArgName && !shouldReturn && (!originalNodeParent || ts.isPropertyAccessExpression(originalNodeParent))) { + return [ts.createStatement(ts.createAwait(node))]; + } + return [ts.createReturn(ts.getSynthesizedDeepClone(node))]; + } + function createTransformedStatement(prevArgName, rightHandSide, transformer) { + if (!prevArgName || prevArgName.identifier.text.length === 0) { + // if there's no argName to assign to, there still might be side effects + return [ts.createStatement(rightHandSide)]; + } + if (prevArgName.types.length < prevArgName.numberOfAssignmentsOriginal) { + // if the variable has already been declared, we don't need "let" or "const" + return [ts.createStatement(ts.createAssignment(ts.getSynthesizedDeepClone(prevArgName.identifier), rightHandSide))]; + } + return [ts.createVariableStatement(/*modifiers*/ undefined, (ts.createVariableDeclarationList([ts.createVariableDeclaration(ts.getSynthesizedDeepClone(prevArgName.identifier), /*type*/ undefined, rightHandSide)], getFlagOfIdentifier(prevArgName.identifier, transformer.constIdentifiers))))]; + } + // should be kept up to date with isFixablePromiseArgument in suggestionDiagnostics.ts + function getTransformationBody(func, prevArgName, argName, parent, transformer) { + var shouldReturn = transformer.setOfExpressionsToReturn.get(ts.getNodeId(parent).toString()); + switch (func.kind) { + case 96 /* NullKeyword */: + // do not produce a transformed statement for a null argument + break; + case 72 /* Identifier */: // identifier includes undefined + if (!argName) { + // undefined was argument passed to promise handler + break; + } + var synthCall = ts.createCall(ts.getSynthesizedDeepClone(func), /*typeArguments*/ undefined, [argName.identifier]); + if (shouldReturn) { + return [ts.createReturn(synthCall)]; + } + var type = transformer.originalTypeMap.get(ts.getNodeId(func).toString()) || transformer.checker.getTypeAtLocation(func); + var callSignatures = transformer.checker.getSignaturesOfType(type, 0 /* Call */); + if (!callSignatures.length) { + // if identifier in handler has no call signatures, it's invalid + codeActionSucceeded = false; + break; + } + var returnType = callSignatures[0].getReturnType(); + var varDeclOrAssignment = createTransformedStatement(prevArgName, ts.createAwait(synthCall), transformer); + if (prevArgName) { + prevArgName.types.push(returnType); + } + return varDeclOrAssignment; + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: { + var funcBody = func.body; + // Arrow functions with block bodies { } will enter this control flow + if (ts.isBlock(funcBody)) { + var refactoredStmts = []; + var seenReturnStatement = false; + for (var _i = 0, _a = funcBody.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + if (ts.isReturnStatement(statement)) { + seenReturnStatement = true; + } + if (ts.isReturnStatementWithFixablePromiseHandler(statement)) { + refactoredStmts = refactoredStmts.concat(getInnerTransformationBody(transformer, [statement], prevArgName)); + } + else { + refactoredStmts.push(statement); + } + } + return shouldReturn ? refactoredStmts.map(function (s) { return ts.getSynthesizedDeepClone(s); }) : + removeReturns(refactoredStmts, prevArgName === undefined ? undefined : prevArgName.identifier, transformer, seenReturnStatement); + } + else { + var innerRetStmts = ts.isFixablePromiseHandler(funcBody) ? [ts.createReturn(funcBody)] : ts.emptyArray; + var innerCbBody = getInnerTransformationBody(transformer, innerRetStmts, prevArgName); + if (innerCbBody.length > 0) { + return innerCbBody; + } + var type_6 = transformer.checker.getTypeAtLocation(func); + var returnType_1 = getLastCallSignature(type_6, transformer.checker).getReturnType(); + var rightHandSide = ts.getSynthesizedDeepClone(funcBody); + var possiblyAwaitedRightHandSide = !!transformer.checker.getPromisedTypeOfPromise(returnType_1) ? ts.createAwait(rightHandSide) : rightHandSide; + if (!shouldReturn) { + var transformedStatement = createTransformedStatement(prevArgName, possiblyAwaitedRightHandSide, transformer); + if (prevArgName) { + prevArgName.types.push(returnType_1); + } + return transformedStatement; + } + else { + return [ts.createReturn(possiblyAwaitedRightHandSide)]; + } + } + } + default: + // If no cases apply, we've found a transformation body we don't know how to handle, so the refactoring should no-op to avoid deleting code. + codeActionSucceeded = false; + break; + } + return ts.emptyArray; + } + function getLastCallSignature(type, checker) { + var callSignatures = checker.getSignaturesOfType(type, 0 /* Call */); + return ts.lastOrUndefined(callSignatures); + } + function removeReturns(stmts, prevArgName, transformer, seenReturnStatement) { + var ret = []; + for (var _i = 0, stmts_1 = stmts; _i < stmts_1.length; _i++) { + var stmt = stmts_1[_i]; + if (ts.isReturnStatement(stmt)) { + if (stmt.expression) { + var possiblyAwaitedExpression = isPromiseReturningExpression(stmt.expression, transformer.checker) ? ts.createAwait(stmt.expression) : stmt.expression; + if (prevArgName === undefined) { + ret.push(ts.createExpressionStatement(possiblyAwaitedExpression)); + } + else { + ret.push(ts.createVariableStatement(/*modifiers*/ undefined, (ts.createVariableDeclarationList([ts.createVariableDeclaration(prevArgName, /*type*/ undefined, possiblyAwaitedExpression)], getFlagOfIdentifier(prevArgName, transformer.constIdentifiers))))); + } + } + } + else { + ret.push(ts.getSynthesizedDeepClone(stmt)); + } + } + // if block has no return statement, need to define prevArgName as undefined to prevent undeclared variables + if (!seenReturnStatement && prevArgName !== undefined) { + ret.push(ts.createVariableStatement(/*modifiers*/ undefined, (ts.createVariableDeclarationList([ts.createVariableDeclaration(prevArgName, /*type*/ undefined, ts.createIdentifier("undefined"))], getFlagOfIdentifier(prevArgName, transformer.constIdentifiers))))); + } + return ret; + } + function getInnerTransformationBody(transformer, innerRetStmts, prevArgName) { + var innerCbBody = []; + for (var _i = 0, innerRetStmts_1 = innerRetStmts; _i < innerRetStmts_1.length; _i++) { + var stmt = innerRetStmts_1[_i]; + ts.forEachChild(stmt, function visit(node) { + if (ts.isCallExpression(node)) { + var temp = transformExpression(node, transformer, node, prevArgName); + innerCbBody = innerCbBody.concat(temp); + if (innerCbBody.length > 0) { + return; + } + } + else if (!ts.isFunctionLike(node)) { + ts.forEachChild(node, visit); + } + }); + } + return innerCbBody; + } + function getArgName(funcNode, transformer) { + var numberOfAssignmentsOriginal = 0; + var types = []; + var name; + if (ts.isFunctionLikeDeclaration(funcNode)) { + if (funcNode.parameters.length > 0) { + var param = funcNode.parameters[0].name; + name = getMapEntryOrDefault(param); + } + } + else if (ts.isIdentifier(funcNode)) { + name = getMapEntryOrDefault(funcNode); + } + // return undefined argName when arg is null or undefined + if (!name || name.identifier.text === "undefined") { + return undefined; + } + return name; + function getMapEntryOrDefault(identifier) { + var originalNode = getOriginalNode(identifier); + var symbol = getSymbol(originalNode); + if (!symbol) { + return { identifier: identifier, types: types, numberOfAssignmentsOriginal: numberOfAssignmentsOriginal }; + } + var mapEntry = transformer.synthNamesMap.get(ts.getSymbolId(symbol).toString()); + return mapEntry || { identifier: identifier, types: types, numberOfAssignmentsOriginal: numberOfAssignmentsOriginal }; + } + function getSymbol(node) { + return node.symbol ? node.symbol : transformer.checker.getSymbolAtLocation(node); + } + function getOriginalNode(node) { + return node.original ? node.original : node; + } + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + codefix.registerCodeFix({ + errorCodes: [ts.Diagnostics.File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module.code], + getCodeActions: function (context) { + var sourceFile = context.sourceFile, program = context.program, preferences = context.preferences; + var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { + var moduleExportsChangedToDefault = convertFileToEs6Module(sourceFile, program.getTypeChecker(), changes, program.getCompilerOptions().target, ts.getQuotePreference(sourceFile, preferences)); + if (moduleExportsChangedToDefault) { + for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { + var importingFile = _a[_i]; + fixImportOfModuleExports(importingFile, sourceFile, changes, ts.getQuotePreference(importingFile, preferences)); + } + } + }); + // No support for fix-all since this applies to the whole file at once anyway. + return [codefix.createCodeFixActionNoFixId("convertToEs6Module", changes, ts.Diagnostics.Convert_to_ES6_module)]; + }, + }); + function fixImportOfModuleExports(importingFile, exportingFile, changes, quotePreference) { + for (var _i = 0, _a = importingFile.imports; _i < _a.length; _i++) { + var moduleSpecifier = _a[_i]; + var imported = ts.getResolvedModule(importingFile, moduleSpecifier.text); + if (!imported || imported.resolvedFileName !== exportingFile.fileName) { + continue; + } + var importNode = ts.importFromModuleSpecifier(moduleSpecifier); + switch (importNode.kind) { + case 248 /* ImportEqualsDeclaration */: + changes.replaceNode(importingFile, importNode, ts.makeImport(importNode.name, /*namedImports*/ undefined, moduleSpecifier, quotePreference)); + break; + case 191 /* CallExpression */: + if (ts.isRequireCall(importNode, /*checkArgumentIsStringLiteralLike*/ false)) { + changes.replaceNode(importingFile, importNode, ts.createPropertyAccess(ts.getSynthesizedDeepClone(importNode), "default")); + } + break; + } + } + } + /** @returns Whether we converted a `module.exports =` to a default export. */ + function convertFileToEs6Module(sourceFile, checker, changes, target, quotePreference) { + var identifiers = { original: collectFreeIdentifiers(sourceFile), additional: ts.createMap() }; + var exports = collectExportRenames(sourceFile, checker, identifiers); + convertExportsAccesses(sourceFile, exports, changes); + var moduleExportsChangedToDefault = false; + for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + var moduleExportsChanged = convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports, quotePreference); + moduleExportsChangedToDefault = moduleExportsChangedToDefault || moduleExportsChanged; + } + return moduleExportsChangedToDefault; + } + function collectExportRenames(sourceFile, checker, identifiers) { + var res = ts.createMap(); + forEachExportReference(sourceFile, function (node) { + var _a = node.name, text = _a.text, originalKeywordKind = _a.originalKeywordKind; + if (!res.has(text) && (originalKeywordKind !== undefined && ts.isNonContextualKeyword(originalKeywordKind) + || checker.resolveName(node.name.text, node, 67220415 /* Value */, /*excludeGlobals*/ true))) { + // Unconditionally add an underscore in case `text` is a keyword. + res.set(text, makeUniqueName("_" + text, identifiers)); + } + }); + return res; + } + function convertExportsAccesses(sourceFile, exports, changes) { + forEachExportReference(sourceFile, function (node, isAssignmentLhs) { + if (isAssignmentLhs) { + return; + } + var text = node.name.text; + changes.replaceNode(sourceFile, node, ts.createIdentifier(exports.get(text) || text)); + }); + } + function forEachExportReference(sourceFile, cb) { + sourceFile.forEachChild(function recur(node) { + if (ts.isPropertyAccessExpression(node) && ts.isExportsOrModuleExportsOrAlias(sourceFile, node.expression)) { + var parent = node.parent; + cb(node, ts.isBinaryExpression(parent) && parent.left === node && parent.operatorToken.kind === 59 /* EqualsToken */); + } + node.forEachChild(recur); + }); + } + function convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports, quotePreference) { + switch (statement.kind) { + case 219 /* VariableStatement */: + convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target, quotePreference); + return false; + case 221 /* ExpressionStatement */: { + var expression = statement.expression; + switch (expression.kind) { + case 191 /* CallExpression */: { + if (ts.isRequireCall(expression, /*checkArgumentIsStringLiteralLike*/ true)) { + // For side-effecting require() call, just make a side-effecting import. + changes.replaceNode(sourceFile, statement, ts.makeImport(/*name*/ undefined, /*namedImports*/ undefined, expression.arguments[0], quotePreference)); + } + return false; + } + case 204 /* BinaryExpression */: { + var operatorToken = expression.operatorToken; + return operatorToken.kind === 59 /* EqualsToken */ && convertAssignment(sourceFile, checker, expression, changes, exports); + } + } + } + // falls through + default: + return false; + } + } + function convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target, quotePreference) { + var declarationList = statement.declarationList; + var foundImport = false; + var newNodes = ts.flatMap(declarationList.declarations, function (decl) { + var name = decl.name, initializer = decl.initializer; + if (initializer) { + if (ts.isExportsOrModuleExportsOrAlias(sourceFile, initializer)) { + // `const alias = module.exports;` can be removed. + foundImport = true; + return []; + } + else if (ts.isRequireCall(initializer, /*checkArgumentIsStringLiteralLike*/ true)) { + foundImport = true; + return convertSingleImport(sourceFile, name, initializer.arguments[0], changes, checker, identifiers, target, quotePreference); + } + else if (ts.isPropertyAccessExpression(initializer) && ts.isRequireCall(initializer.expression, /*checkArgumentIsStringLiteralLike*/ true)) { + foundImport = true; + return convertPropertyAccessImport(name, initializer.name.text, initializer.expression.arguments[0], identifiers, quotePreference); + } + } + // Move it out to its own variable statement. (This will not be used if `!foundImport`) + return ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([decl], declarationList.flags)); + }); + if (foundImport) { + // useNonAdjustedEndPosition to ensure we don't eat the newline after the statement. + changes.replaceNodeWithNodes(sourceFile, statement, newNodes); + } + } + /** Converts `const name = require("moduleSpecifier").propertyName` */ + function convertPropertyAccessImport(name, propertyName, moduleSpecifier, identifiers, quotePreference) { + switch (name.kind) { + case 184 /* ObjectBindingPattern */: + case 185 /* ArrayBindingPattern */: { + // `const [a, b] = require("c").d` --> `import { d } from "c"; const [a, b] = d;` + var tmp = makeUniqueName(propertyName, identifiers); + return [ + makeSingleImport(tmp, propertyName, moduleSpecifier, quotePreference), + makeConst(/*modifiers*/ undefined, name, ts.createIdentifier(tmp)), + ]; + } + case 72 /* Identifier */: + // `const a = require("b").c` --> `import { c as a } from "./b"; + return [makeSingleImport(name.text, propertyName, moduleSpecifier, quotePreference)]; + default: + return ts.Debug.assertNever(name); + } + } + function convertAssignment(sourceFile, checker, assignment, changes, exports) { + var left = assignment.left, right = assignment.right; + if (!ts.isPropertyAccessExpression(left)) { + return false; + } + if (ts.isExportsOrModuleExportsOrAlias(sourceFile, left)) { + if (ts.isExportsOrModuleExportsOrAlias(sourceFile, right)) { + // `const alias = module.exports;` or `module.exports = alias;` can be removed. + changes.delete(sourceFile, assignment.parent); + } + else { + var replacement = ts.isObjectLiteralExpression(right) ? tryChangeModuleExportsObject(right) + : ts.isRequireCall(right, /*checkArgumentIsStringLiteralLike*/ true) ? convertReExportAll(right.arguments[0], checker) + : undefined; + if (replacement) { + changes.replaceNodeWithNodes(sourceFile, assignment.parent, replacement[0]); + return replacement[1]; + } + else { + changes.replaceRangeWithText(sourceFile, ts.createRange(left.getStart(sourceFile), right.pos), "export default"); + return true; + } + } + } + else if (ts.isExportsOrModuleExportsOrAlias(sourceFile, left.expression)) { + convertNamedExport(sourceFile, assignment, changes, exports); + } + return false; + } + /** + * Convert `module.exports = { ... }` to individual exports.. + * We can't always do this if the module has interesting members -- then it will be a default export instead. + */ + function tryChangeModuleExportsObject(object) { + var statements = ts.mapAllOrFail(object.properties, function (prop) { + switch (prop.kind) { + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + // TODO: Maybe we should handle this? See fourslash test `refactorConvertToEs6Module_export_object_shorthand.ts`. + case 276 /* ShorthandPropertyAssignment */: + case 277 /* SpreadAssignment */: + return undefined; + case 275 /* PropertyAssignment */: + return !ts.isIdentifier(prop.name) ? undefined : convertExportsDotXEquals_replaceNode(prop.name.text, prop.initializer); + case 156 /* MethodDeclaration */: + return !ts.isIdentifier(prop.name) ? undefined : functionExpressionToDeclaration(prop.name.text, [ts.createToken(85 /* ExportKeyword */)], prop); + default: + ts.Debug.assertNever(prop); + } + }); + return statements && [statements, false]; + } + function convertNamedExport(sourceFile, assignment, changes, exports) { + // If "originalKeywordKind" was set, this is e.g. `exports. + var text = assignment.left.name.text; + var rename = exports.get(text); + if (rename !== undefined) { + /* + const _class = 0; + export { _class as class }; + */ + var newNodes = [ + makeConst(/*modifiers*/ undefined, rename, assignment.right), + makeExportDeclaration([ts.createExportSpecifier(rename, text)]), + ]; + changes.replaceNodeWithNodes(sourceFile, assignment.parent, newNodes); + } + else { + convertExportsPropertyAssignment(assignment, sourceFile, changes); + } + } + function convertReExportAll(reExported, checker) { + // `module.exports = require("x");` ==> `export * from "x"; export { default } from "x";` + var moduleSpecifier = reExported.text; + var moduleSymbol = checker.getSymbolAtLocation(reExported); + var exports = moduleSymbol ? moduleSymbol.exports : ts.emptyUnderscoreEscapedMap; + return exports.has("export=") + ? [[reExportDefault(moduleSpecifier)], true] + : !exports.has("default") + ? [[reExportStar(moduleSpecifier)], false] + // If there's some non-default export, must include both `export *` and `export default`. + : exports.size > 1 ? [[reExportStar(moduleSpecifier), reExportDefault(moduleSpecifier)], true] : [[reExportDefault(moduleSpecifier)], true]; + } + function reExportStar(moduleSpecifier) { + return makeExportDeclaration(/*exportClause*/ undefined, moduleSpecifier); + } + function reExportDefault(moduleSpecifier) { + return makeExportDeclaration([ts.createExportSpecifier(/*propertyName*/ undefined, "default")], moduleSpecifier); + } + function convertExportsPropertyAssignment(_a, sourceFile, changes) { + var left = _a.left, right = _a.right, parent = _a.parent; + var name = left.name.text; + if ((ts.isFunctionExpression(right) || ts.isArrowFunction(right) || ts.isClassExpression(right)) && (!right.name || right.name.text === name)) { + // `exports.f = function() {}` -> `export function f() {}` -- Replace `exports.f = ` with `export `, and insert the name after `function`. + changes.replaceRange(sourceFile, { pos: left.getStart(sourceFile), end: right.getStart(sourceFile) }, ts.createToken(85 /* ExportKeyword */), { suffix: " " }); + if (!right.name) + changes.insertName(sourceFile, right, name); + var semi = ts.findChildOfKind(parent, 26 /* SemicolonToken */, sourceFile); + if (semi) + changes.delete(sourceFile, semi); + } + else { + // `exports.f = function g() {}` -> `export const f = function g() {}` -- just replace `exports.` with `export const ` + changes.replaceNodeRangeWithNodes(sourceFile, left.expression, ts.findChildOfKind(left, 24 /* DotToken */, sourceFile), [ts.createToken(85 /* ExportKeyword */), ts.createToken(77 /* ConstKeyword */)], { joiner: " ", suffix: " " }); + } + } + // TODO: GH#22492 this will cause an error if a change has been made inside the body of the node. + function convertExportsDotXEquals_replaceNode(name, exported) { + var modifiers = [ts.createToken(85 /* ExportKeyword */)]; + switch (exported.kind) { + case 196 /* FunctionExpression */: { + var expressionName = exported.name; + if (expressionName && expressionName.text !== name) { + // `exports.f = function g() {}` -> `export const f = function g() {}` + return exportConst(); + } + } + // falls through + case 197 /* ArrowFunction */: + // `exports.f = function() {}` --> `export function f() {}` + return functionExpressionToDeclaration(name, modifiers, exported); + case 209 /* ClassExpression */: + // `exports.C = class {}` --> `export class C {}` + return classExpressionToDeclaration(name, modifiers, exported); + default: + return exportConst(); + } + function exportConst() { + // `exports.x = 0;` --> `export const x = 0;` + return makeConst(modifiers, ts.createIdentifier(name), exported); // TODO: GH#18217 + } + } + /** + * Converts `const <> = require("x");`. + * Returns nodes that will replace the variable declaration for the commonjs import. + * May also make use `changes` to remove qualifiers at the use sites of imports, to change `mod.x` to `x`. + */ + function convertSingleImport(file, name, moduleSpecifier, changes, checker, identifiers, target, quotePreference) { + switch (name.kind) { + case 184 /* ObjectBindingPattern */: { + var importSpecifiers = ts.mapAllOrFail(name.elements, function (e) { + return e.dotDotDotToken || e.initializer || e.propertyName && !ts.isIdentifier(e.propertyName) || !ts.isIdentifier(e.name) + ? undefined + : makeImportSpecifier(e.propertyName && e.propertyName.text, e.name.text); + }); // tslint:disable-line no-unnecessary-type-assertion (TODO: GH#18217) + if (importSpecifiers) { + return [ts.makeImport(/*name*/ undefined, importSpecifiers, moduleSpecifier, quotePreference)]; + } + } + // falls through -- object destructuring has an interesting pattern and must be a variable declaration + case 185 /* ArrayBindingPattern */: { + /* + import x from "x"; + const [a, b, c] = x; + */ + var tmp = makeUniqueName(codefix.moduleSpecifierToValidIdentifier(moduleSpecifier.text, target), identifiers); + return [ + ts.makeImport(ts.createIdentifier(tmp), /*namedImports*/ undefined, moduleSpecifier, quotePreference), + makeConst(/*modifiers*/ undefined, ts.getSynthesizedDeepClone(name), ts.createIdentifier(tmp)), + ]; + } + case 72 /* Identifier */: + return convertSingleIdentifierImport(file, name, moduleSpecifier, changes, checker, identifiers, quotePreference); + default: + return ts.Debug.assertNever(name); + } + } + /** + * Convert `import x = require("x").` + * Also converts uses like `x.y()` to `y()` and uses a named import. + */ + function convertSingleIdentifierImport(file, name, moduleSpecifier, changes, checker, identifiers, quotePreference) { + var nameSymbol = checker.getSymbolAtLocation(name); + // Maps from module property name to name actually used. (The same if there isn't shadowing.) + var namedBindingsNames = ts.createMap(); + // True if there is some non-property use like `x()` or `f(x)`. + var needDefaultImport = false; + for (var _i = 0, _a = identifiers.original.get(name.text); _i < _a.length; _i++) { + var use = _a[_i]; + if (checker.getSymbolAtLocation(use) !== nameSymbol || use === name) { + // This was a use of a different symbol with the same name, due to shadowing. Ignore. + continue; + } + var parent = use.parent; + if (ts.isPropertyAccessExpression(parent)) { + var expression = parent.expression, propertyName = parent.name.text; + ts.Debug.assert(expression === use); // Else shouldn't have been in `collectIdentifiers` + var idName = namedBindingsNames.get(propertyName); + if (idName === undefined) { + idName = makeUniqueName(propertyName, identifiers); + namedBindingsNames.set(propertyName, idName); + } + changes.replaceNode(file, parent, ts.createIdentifier(idName)); + } + else { + needDefaultImport = true; + } + } + var namedBindings = namedBindingsNames.size === 0 ? undefined : ts.arrayFrom(ts.mapIterator(namedBindingsNames.entries(), function (_a) { + var propertyName = _a[0], idName = _a[1]; + return ts.createImportSpecifier(propertyName === idName ? undefined : ts.createIdentifier(propertyName), ts.createIdentifier(idName)); + })); + if (!namedBindings) { + // If it was unused, ensure that we at least import *something*. + needDefaultImport = true; + } + return [ts.makeImport(needDefaultImport ? ts.getSynthesizedDeepClone(name) : undefined, namedBindings, moduleSpecifier, quotePreference)]; + } + // Identifiers helpers + function makeUniqueName(name, identifiers) { + while (identifiers.original.has(name) || identifiers.additional.has(name)) { + name = "_" + name; + } + identifiers.additional.set(name, true); + return name; + } + function collectFreeIdentifiers(file) { + var map = ts.createMultiMap(); + forEachFreeIdentifier(file, function (id) { return map.add(id.text, id); }); + return map; + } + /** + * A free identifier is an identifier that can be accessed through name lookup as a local variable. + * In the expression `x.y`, `x` is a free identifier, but `y` is not. + */ + function forEachFreeIdentifier(node, cb) { + if (ts.isIdentifier(node) && isFreeIdentifier(node)) + cb(node); + node.forEachChild(function (child) { return forEachFreeIdentifier(child, cb); }); + } + function isFreeIdentifier(node) { + var parent = node.parent; + switch (parent.kind) { + case 189 /* PropertyAccessExpression */: + return parent.name !== node; + case 186 /* BindingElement */: + return parent.propertyName !== node; + case 253 /* ImportSpecifier */: + return parent.propertyName !== node; + default: + return true; + } + } + // Node helpers + function functionExpressionToDeclaration(name, additionalModifiers, fn) { + return ts.createFunctionDeclaration(ts.getSynthesizedDeepClones(fn.decorators), // TODO: GH#19915 Don't think this is even legal. + ts.concatenate(additionalModifiers, ts.getSynthesizedDeepClones(fn.modifiers)), ts.getSynthesizedDeepClone(fn.asteriskToken), name, ts.getSynthesizedDeepClones(fn.typeParameters), ts.getSynthesizedDeepClones(fn.parameters), ts.getSynthesizedDeepClone(fn.type), ts.convertToFunctionBody(ts.getSynthesizedDeepClone(fn.body))); + } + function classExpressionToDeclaration(name, additionalModifiers, cls) { + return ts.createClassDeclaration(ts.getSynthesizedDeepClones(cls.decorators), // TODO: GH#19915 Don't think this is even legal. + ts.concatenate(additionalModifiers, ts.getSynthesizedDeepClones(cls.modifiers)), name, ts.getSynthesizedDeepClones(cls.typeParameters), ts.getSynthesizedDeepClones(cls.heritageClauses), ts.getSynthesizedDeepClones(cls.members)); + } + function makeSingleImport(localName, propertyName, moduleSpecifier, quotePreference) { + return propertyName === "default" + ? ts.makeImport(ts.createIdentifier(localName), /*namedImports*/ undefined, moduleSpecifier, quotePreference) + : ts.makeImport(/*name*/ undefined, [makeImportSpecifier(propertyName, localName)], moduleSpecifier, quotePreference); + } + function makeImportSpecifier(propertyName, name) { + return ts.createImportSpecifier(propertyName !== undefined && propertyName !== name ? ts.createIdentifier(propertyName) : undefined, ts.createIdentifier(name)); + } + function makeConst(modifiers, name, init) { + return ts.createVariableStatement(modifiers, ts.createVariableDeclarationList([ts.createVariableDeclaration(name, /*type*/ undefined, init)], 2 /* Const */)); + } + function makeExportDeclaration(exportSpecifiers, moduleSpecifier) { + return ts.createExportDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, exportSpecifiers && ts.createNamedExports(exportSpecifiers), moduleSpecifier === undefined ? undefined : ts.createLiteral(moduleSpecifier)); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "correctQualifiedNameToIndexedAccessType"; + var errorCodes = [ts.Diagnostics.Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_property_1_in_0_with_0_1.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var qualifiedName = getQualifiedName(context.sourceFile, context.span.start); + if (!qualifiedName) + return undefined; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, context.sourceFile, qualifiedName); }); + var newText = qualifiedName.left.text + "[\"" + qualifiedName.right.text + "\"]"; + return [codefix.createCodeFixAction(fixId, changes, [ts.Diagnostics.Rewrite_as_the_indexed_access_type_0, newText], fixId, ts.Diagnostics.Rewrite_all_as_indexed_access_types)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var q = getQualifiedName(diag.file, diag.start); + if (q) { + doChange(changes, diag.file, q); + } + }); }, + }); + function getQualifiedName(sourceFile, pos) { + var qualifiedName = ts.findAncestor(ts.getTokenAtPosition(sourceFile, pos), ts.isQualifiedName); + ts.Debug.assert(!!qualifiedName, "Expected position to be owned by a qualified name."); + return ts.isIdentifier(qualifiedName.left) ? qualifiedName : undefined; + } + function doChange(changeTracker, sourceFile, qualifiedName) { + var rightText = qualifiedName.right.text; + var replacement = ts.createIndexedAccessTypeNode(ts.createTypeReferenceNode(qualifiedName.left, /*typeArguments*/ undefined), ts.createLiteralTypeNode(ts.createLiteral(rightText))); + changeTracker.replaceNode(sourceFile, qualifiedName, replacement); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var errorCodes = [ts.Diagnostics.Class_0_incorrectly_implements_interface_1.code, + ts.Diagnostics.Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass.code]; + var fixId = "fixClassIncorrectlyImplementsInterface"; // TODO: share a group with fixClassDoesntImplementInheritedAbstractMember? + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var program = context.program, sourceFile = context.sourceFile, span = context.span; + var classDeclaration = getClass(sourceFile, span.start); + var checker = program.getTypeChecker(); + return ts.mapDefined(ts.getClassImplementsHeritageClauseElements(classDeclaration), function (implementedTypeNode) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMissingDeclarations(checker, implementedTypeNode, sourceFile, classDeclaration, t, context.preferences); }); + return changes.length === 0 ? undefined : codefix.createCodeFixAction(fixId, changes, [ts.Diagnostics.Implement_interface_0, implementedTypeNode.getText(sourceFile)], fixId, ts.Diagnostics.Implement_all_unimplemented_interfaces); + }); + }, + fixIds: [fixId], + getAllCodeActions: function (context) { + var seenClassDeclarations = ts.createMap(); + return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var classDeclaration = getClass(diag.file, diag.start); + if (ts.addToSeen(seenClassDeclarations, ts.getNodeId(classDeclaration))) { + for (var _i = 0, _a = ts.getClassImplementsHeritageClauseElements(classDeclaration); _i < _a.length; _i++) { + var implementedTypeNode = _a[_i]; + addMissingDeclarations(context.program.getTypeChecker(), implementedTypeNode, diag.file, classDeclaration, changes, context.preferences); + } + } + }); + }, + }); + function getClass(sourceFile, pos) { + return ts.Debug.assertDefined(ts.getContainingClass(ts.getTokenAtPosition(sourceFile, pos))); + } + function symbolPointsToNonPrivateMember(symbol) { + return !(ts.getModifierFlags(symbol.valueDeclaration) & 8 /* Private */); + } + function addMissingDeclarations(checker, implementedTypeNode, sourceFile, classDeclaration, changeTracker, preferences) { + var maybeHeritageClauseSymbol = getHeritageClauseSymbolTable(classDeclaration, checker); + // Note that this is ultimately derived from a map indexed by symbol names, + // so duplicates cannot occur. + var implementedType = checker.getTypeAtLocation(implementedTypeNode); + var implementedTypeSymbols = checker.getPropertiesOfType(implementedType); + var nonPrivateAndNotExistedInHeritageClauseMembers = implementedTypeSymbols.filter(ts.and(symbolPointsToNonPrivateMember, function (symbol) { return !maybeHeritageClauseSymbol.has(symbol.escapedName); })); + var classType = checker.getTypeAtLocation(classDeclaration); + if (!classType.getNumberIndexType()) { + createMissingIndexSignatureDeclaration(implementedType, 1 /* Number */); + } + if (!classType.getStringIndexType()) { + createMissingIndexSignatureDeclaration(implementedType, 0 /* String */); + } + codefix.createMissingMemberNodes(classDeclaration, nonPrivateAndNotExistedInHeritageClauseMembers, checker, preferences, function (member) { return changeTracker.insertNodeAtClassStart(sourceFile, classDeclaration, member); }); + function createMissingIndexSignatureDeclaration(type, kind) { + var indexInfoOfKind = checker.getIndexInfoOfType(type, kind); + if (indexInfoOfKind) { + changeTracker.insertNodeAtClassStart(sourceFile, classDeclaration, checker.indexInfoToIndexSignatureDeclaration(indexInfoOfKind, kind, classDeclaration)); + } + } + } + function getHeritageClauseSymbolTable(classDeclaration, checker) { + var heritageClauseNode = ts.getEffectiveBaseTypeNode(classDeclaration); + if (!heritageClauseNode) + return ts.createSymbolTable(); + var heritageClauseType = checker.getTypeAtLocation(heritageClauseNode); + var heritageClauseTypeSymbols = checker.getPropertiesOfType(heritageClauseType); + return ts.createSymbolTable(heritageClauseTypeSymbols.filter(symbolPointsToNonPrivateMember)); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + codefix.importFixId = "fixMissingImport"; + var errorCodes = [ + ts.Diagnostics.Cannot_find_name_0.code, + ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1.code, + ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0.code, + ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_static_member_1_0.code, + ts.Diagnostics.Cannot_find_namespace_0.code, + ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code, + ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here.code, + ]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var errorCode = context.errorCode, preferences = context.preferences, sourceFile = context.sourceFile, span = context.span; + var info = getFixesInfo(context, errorCode, span.start); + if (!info) + return undefined; + var fixes = info.fixes, symbolName = info.symbolName; + var quotePreference = ts.getQuotePreference(sourceFile, preferences); + return fixes.map(function (fix) { return codeActionForFix(context, sourceFile, symbolName, fix, quotePreference); }); + }, + fixIds: [codefix.importFixId], + getAllCodeActions: function (context) { + var sourceFile = context.sourceFile, preferences = context.preferences; + // Namespace fixes don't conflict, so just build a list. + var addToNamespace = []; + var importType = []; + // Keys are import clause node IDs. + var addToExisting = ts.createMap(); + // Keys are module specifiers. + var newImports = ts.createMap(); + codefix.eachDiagnostic(context, errorCodes, function (diag) { + var info = getFixesInfo(context, diag.code, diag.start); + if (!info || !info.fixes.length) + return; + var fixes = info.fixes, symbolName = info.symbolName; + var fix = ts.first(fixes); + switch (fix.kind) { + case 0 /* UseNamespace */: + addToNamespace.push(fix); + break; + case 1 /* ImportType */: + importType.push(fix); + break; + case 2 /* AddToExisting */: { + var importClause = fix.importClause, importKind = fix.importKind; + var key = String(ts.getNodeId(importClause)); + var entry = addToExisting.get(key); + if (!entry) { + addToExisting.set(key, entry = { importClause: importClause, defaultImport: undefined, namedImports: [] }); + } + if (importKind === 0 /* Named */) { + ts.pushIfUnique(entry.namedImports, symbolName); + } + else { + ts.Debug.assert(entry.defaultImport === undefined || entry.defaultImport === symbolName); + entry.defaultImport = symbolName; + } + break; + } + case 3 /* AddNew */: { + var moduleSpecifier = fix.moduleSpecifier, importKind = fix.importKind; + var entry = newImports.get(moduleSpecifier); + if (!entry) { + newImports.set(moduleSpecifier, entry = { defaultImport: undefined, namedImports: [], namespaceLikeImport: undefined }); + } + switch (importKind) { + case 1 /* Default */: + ts.Debug.assert(entry.defaultImport === undefined || entry.defaultImport === symbolName); + entry.defaultImport = symbolName; + break; + case 0 /* Named */: + ts.pushIfUnique(entry.namedImports, symbolName); + break; + case 3 /* Equals */: + case 2 /* Namespace */: + ts.Debug.assert(entry.namespaceLikeImport === undefined || entry.namespaceLikeImport.name === symbolName); + entry.namespaceLikeImport = { importKind: importKind, name: symbolName }; + break; + } + break; + } + default: + ts.Debug.assertNever(fix); + } + }); + return codefix.createCombinedCodeActions(ts.textChanges.ChangeTracker.with(context, function (changes) { + var quotePreference = ts.getQuotePreference(sourceFile, preferences); + for (var _i = 0, addToNamespace_1 = addToNamespace; _i < addToNamespace_1.length; _i++) { + var fix = addToNamespace_1[_i]; + addNamespaceQualifier(changes, sourceFile, fix); + } + for (var _a = 0, importType_1 = importType; _a < importType_1.length; _a++) { + var fix = importType_1[_a]; + addImportType(changes, sourceFile, fix, quotePreference); + } + addToExisting.forEach(function (_a) { + var importClause = _a.importClause, defaultImport = _a.defaultImport, namedImports = _a.namedImports; + doAddExistingFix(changes, sourceFile, importClause, defaultImport, namedImports); + }); + newImports.forEach(function (imports, moduleSpecifier) { + addNewImports(changes, sourceFile, moduleSpecifier, quotePreference, imports); + }); + })); + }, + }); + // Sorted with the preferred fix coming first. + var ImportFixKind; + (function (ImportFixKind) { + ImportFixKind[ImportFixKind["UseNamespace"] = 0] = "UseNamespace"; + ImportFixKind[ImportFixKind["ImportType"] = 1] = "ImportType"; + ImportFixKind[ImportFixKind["AddToExisting"] = 2] = "AddToExisting"; + ImportFixKind[ImportFixKind["AddNew"] = 3] = "AddNew"; + })(ImportFixKind || (ImportFixKind = {})); + var ImportKind; + (function (ImportKind) { + ImportKind[ImportKind["Named"] = 0] = "Named"; + ImportKind[ImportKind["Default"] = 1] = "Default"; + ImportKind[ImportKind["Namespace"] = 2] = "Namespace"; + ImportKind[ImportKind["Equals"] = 3] = "Equals"; + })(ImportKind || (ImportKind = {})); + function getImportCompletionAction(exportedSymbol, moduleSymbol, sourceFile, symbolName, host, program, formatContext, position, preferences) { + var exportInfos = getAllReExportingModules(exportedSymbol, moduleSymbol, symbolName, sourceFile, program.getCompilerOptions(), program.getTypeChecker(), program.getSourceFiles()); + ts.Debug.assert(exportInfos.some(function (info) { return info.moduleSymbol === moduleSymbol; })); + // We sort the best codefixes first, so taking `first` is best for completions. + var moduleSpecifier = ts.first(getNewImportInfos(program, sourceFile, position, exportInfos, host, preferences)).moduleSpecifier; + var fix = ts.first(getFixForImport(exportInfos, symbolName, position, program, sourceFile, host, preferences)); + return { moduleSpecifier: moduleSpecifier, codeAction: codeFixActionToCodeAction(codeActionForFix({ host: host, formatContext: formatContext }, sourceFile, symbolName, fix, ts.getQuotePreference(sourceFile, preferences))) }; + } + codefix.getImportCompletionAction = getImportCompletionAction; + function codeFixActionToCodeAction(_a) { + var description = _a.description, changes = _a.changes, commands = _a.commands; + return { description: description, changes: changes, commands: commands }; + } + function getAllReExportingModules(exportedSymbol, exportingModuleSymbol, symbolName, sourceFile, compilerOptions, checker, allSourceFiles) { + var result = []; + forEachExternalModule(checker, allSourceFiles, function (moduleSymbol, moduleFile) { + // Don't import from a re-export when looking "up" like to `./index` or `../index`. + if (moduleFile && moduleSymbol !== exportingModuleSymbol && ts.startsWith(sourceFile.fileName, ts.getDirectoryPath(moduleFile.fileName))) { + return; + } + var defaultInfo = getDefaultLikeExportInfo(moduleSymbol, checker, compilerOptions); + if (defaultInfo && defaultInfo.name === symbolName && ts.skipAlias(defaultInfo.symbol, checker) === exportedSymbol) { + result.push({ moduleSymbol: moduleSymbol, importKind: defaultInfo.kind, exportedSymbolIsTypeOnly: isTypeOnlySymbol(defaultInfo.symbol, checker) }); + } + for (var _i = 0, _a = checker.getExportsOfModule(moduleSymbol); _i < _a.length; _i++) { + var exported = _a[_i]; + if (exported.name === symbolName && ts.skipAlias(exported, checker) === exportedSymbol) { + result.push({ moduleSymbol: moduleSymbol, importKind: 0 /* Named */, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exported, checker) }); + } + } + }); + return result; + } + function isTypeOnlySymbol(s, checker) { + return !(ts.skipAlias(s, checker).flags & 67220415 /* Value */); + } + function getFixForImport(exportInfos, symbolName, position, program, sourceFile, host, preferences) { + var checker = program.getTypeChecker(); + var existingImports = ts.flatMap(exportInfos, function (info) { return getExistingImportDeclarations(info, checker, sourceFile); }); + var useNamespace = position === undefined ? undefined : tryUseExistingNamespaceImport(existingImports, symbolName, position, checker); + var addToExisting = tryAddToExistingImport(existingImports); + // Don't bother providing an action to add a new import if we can add to an existing one. + var addImport = addToExisting ? [addToExisting] : getFixesForAddImport(exportInfos, existingImports, program, sourceFile, position, host, preferences); + return (useNamespace ? [useNamespace] : ts.emptyArray).concat(addImport); + } + function tryUseExistingNamespaceImport(existingImports, symbolName, position, checker) { + // It is possible that multiple import statements with the same specifier exist in the file. + // e.g. + // + // import * as ns from "foo"; + // import { member1, member2 } from "foo"; + // + // member3/**/ <-- cusor here + // + // in this case we should provie 2 actions: + // 1. change "member3" to "ns.member3" + // 2. add "member3" to the second import statement's import list + // and it is up to the user to decide which one fits best. + return ts.firstDefined(existingImports, function (_a) { + var declaration = _a.declaration; + var namespace = getNamespaceImportName(declaration); + if (namespace) { + var moduleSymbol = checker.getAliasedSymbol(checker.getSymbolAtLocation(namespace)); + if (moduleSymbol && moduleSymbol.exports.has(ts.escapeLeadingUnderscores(symbolName))) { + return { kind: 0 /* UseNamespace */, namespacePrefix: namespace.text, position: position }; + } + } + }); + } + function tryAddToExistingImport(existingImports) { + return ts.firstDefined(existingImports, function (_a) { + var declaration = _a.declaration, importKind = _a.importKind; + if (declaration.kind !== 249 /* ImportDeclaration */) + return undefined; + var importClause = declaration.importClause; + if (!importClause) + return undefined; + var name = importClause.name, namedBindings = importClause.namedBindings; + return importKind === 1 /* Default */ && !name || importKind === 0 /* Named */ && (!namedBindings || namedBindings.kind === 252 /* NamedImports */) + ? { kind: 2 /* AddToExisting */, importClause: importClause, importKind: importKind } + : undefined; + }); + } + function getNamespaceImportName(declaration) { + if (declaration.kind === 249 /* ImportDeclaration */) { + var namedBindings = declaration.importClause && ts.isImportClause(declaration.importClause) && declaration.importClause.namedBindings; + return namedBindings && namedBindings.kind === 251 /* NamespaceImport */ ? namedBindings.name : undefined; + } + else { + return declaration.name; + } + } + function getExistingImportDeclarations(_a, checker, sourceFile) { + var moduleSymbol = _a.moduleSymbol, importKind = _a.importKind, exportedSymbolIsTypeOnly = _a.exportedSymbolIsTypeOnly; + // Can't use an es6 import for a type in JS. + return exportedSymbolIsTypeOnly && ts.isSourceFileJS(sourceFile) ? ts.emptyArray : ts.mapDefined(sourceFile.imports, function (moduleSpecifier) { + var i = ts.importFromModuleSpecifier(moduleSpecifier); + return (i.kind === 249 /* ImportDeclaration */ || i.kind === 248 /* ImportEqualsDeclaration */) + && checker.getSymbolAtLocation(moduleSpecifier) === moduleSymbol ? { declaration: i, importKind: importKind } : undefined; + }); + } + function getNewImportInfos(program, sourceFile, position, moduleSymbols, host, preferences) { + var isJs = ts.isSourceFileJS(sourceFile); + var choicesForEachExportingModule = ts.flatMap(moduleSymbols, function (_a) { + var moduleSymbol = _a.moduleSymbol, importKind = _a.importKind, exportedSymbolIsTypeOnly = _a.exportedSymbolIsTypeOnly; + return ts.moduleSpecifiers.getModuleSpecifiers(moduleSymbol, program.getCompilerOptions(), sourceFile, host, program.getSourceFiles(), preferences, program.redirectTargetsMap) + .map(function (moduleSpecifier) { + // `position` should only be undefined at a missing jsx namespace, in which case we shouldn't be looking for pure types. + return exportedSymbolIsTypeOnly && isJs ? { kind: 1 /* ImportType */, moduleSpecifier: moduleSpecifier, position: ts.Debug.assertDefined(position) } : { kind: 3 /* AddNew */, moduleSpecifier: moduleSpecifier, importKind: importKind }; + }); + }); + // Sort to keep the shortest paths first + return ts.sort(choicesForEachExportingModule, function (a, b) { return a.moduleSpecifier.length - b.moduleSpecifier.length; }); + } + function getFixesForAddImport(exportInfos, existingImports, program, sourceFile, position, host, preferences) { + var existingDeclaration = ts.firstDefined(existingImports, newImportInfoFromExistingSpecifier); + return existingDeclaration ? [existingDeclaration] : getNewImportInfos(program, sourceFile, position, exportInfos, host, preferences); + } + function newImportInfoFromExistingSpecifier(_a) { + var declaration = _a.declaration, importKind = _a.importKind; + var expression = declaration.kind === 249 /* ImportDeclaration */ + ? declaration.moduleSpecifier + : declaration.moduleReference.kind === 259 /* ExternalModuleReference */ + ? declaration.moduleReference.expression + : undefined; + return expression && ts.isStringLiteral(expression) ? { kind: 3 /* AddNew */, moduleSpecifier: expression.text, importKind: importKind } : undefined; + } + function getFixesInfo(context, errorCode, pos) { + var symbolToken = ts.getTokenAtPosition(context.sourceFile, pos); + var info = errorCode === ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code + ? getFixesInfoForUMDImport(context, symbolToken) + : ts.isIdentifier(symbolToken) ? getFixesInfoForNonUMDImport(context, symbolToken) : undefined; + return info && __assign({}, info, { fixes: ts.sort(info.fixes, function (a, b) { return a.kind - b.kind; }) }); + } + function getFixesInfoForUMDImport(_a, token) { + var sourceFile = _a.sourceFile, program = _a.program, host = _a.host, preferences = _a.preferences; + var checker = program.getTypeChecker(); + var umdSymbol = getUmdSymbol(token, checker); + if (!umdSymbol) + return undefined; + var symbol = checker.getAliasedSymbol(umdSymbol); + var symbolName = umdSymbol.name; + var exportInfos = [{ moduleSymbol: symbol, importKind: getUmdImportKind(program.getCompilerOptions()), exportedSymbolIsTypeOnly: false }]; + var fixes = getFixForImport(exportInfos, symbolName, ts.isIdentifier(token) ? token.getStart(sourceFile) : undefined, program, sourceFile, host, preferences); + return { fixes: fixes, symbolName: symbolName }; + } + function getUmdSymbol(token, checker) { + // try the identifier to see if it is the umd symbol + var umdSymbol = ts.isIdentifier(token) ? checker.getSymbolAtLocation(token) : undefined; + if (ts.isUMDExportSymbol(umdSymbol)) + return umdSymbol; + // The error wasn't for the symbolAtLocation, it was for the JSX tag itself, which needs access to e.g. `React`. + var parent = token.parent; + return (ts.isJsxOpeningLikeElement(parent) && parent.tagName === token) || ts.isJsxOpeningFragment(parent) + ? ts.tryCast(checker.resolveName(checker.getJsxNamespace(parent), ts.isJsxOpeningLikeElement(parent) ? token : parent, 67220415 /* Value */, /*excludeGlobals*/ false), ts.isUMDExportSymbol) + : undefined; + } + function getUmdImportKind(compilerOptions) { + // Import a synthetic `default` if enabled. + if (ts.getAllowSyntheticDefaultImports(compilerOptions)) { + return 1 /* Default */; + } + // When a synthetic `default` is unavailable, use `import..require` if the module kind supports it. + var moduleKind = ts.getEmitModuleKind(compilerOptions); + switch (moduleKind) { + case ts.ModuleKind.AMD: + case ts.ModuleKind.CommonJS: + case ts.ModuleKind.UMD: + return 3 /* Equals */; + case ts.ModuleKind.System: + case ts.ModuleKind.ES2015: + case ts.ModuleKind.ESNext: + case ts.ModuleKind.None: + // Fall back to the `import * as ns` style import. + return 2 /* Namespace */; + default: + return ts.Debug.assertNever(moduleKind); + } + } + function getFixesInfoForNonUMDImport(_a, symbolToken) { + var sourceFile = _a.sourceFile, program = _a.program, cancellationToken = _a.cancellationToken, host = _a.host, preferences = _a.preferences; + var checker = program.getTypeChecker(); + // If we're at ``, we must check if `Foo` is already in scope, and if so, get an import for `React` instead. + var symbolName = ts.isJsxOpeningLikeElement(symbolToken.parent) + && symbolToken.parent.tagName === symbolToken + && (ts.isIntrinsicJsxName(symbolToken.text) || checker.resolveName(symbolToken.text, symbolToken, 67108863 /* All */, /*excludeGlobals*/ false)) + ? checker.getJsxNamespace() + : symbolToken.text; + // "default" is a keyword and not a legal identifier for the import, so we don't expect it here + ts.Debug.assert(symbolName !== "default" /* Default */); + var fixes = ts.arrayFrom(ts.flatMapIterator(getExportInfos(symbolName, ts.getMeaningFromLocation(symbolToken), cancellationToken, sourceFile, checker, program).entries(), function (_a) { + var _ = _a[0], exportInfos = _a[1]; + return getFixForImport(exportInfos, symbolName, symbolToken.getStart(sourceFile), program, sourceFile, host, preferences); + })); + return { fixes: fixes, symbolName: symbolName }; + } + // Returns a map from an exported symbol's ID to a list of every way it's (re-)exported. + function getExportInfos(symbolName, currentTokenMeaning, cancellationToken, sourceFile, checker, program) { + // For each original symbol, keep all re-exports of that symbol together so we can call `getCodeActionsForImport` on the whole group at once. + // Maps symbol id to info for modules providing that symbol (original export + re-exports). + var originalSymbolToExportInfos = ts.createMultiMap(); + function addSymbol(moduleSymbol, exportedSymbol, importKind) { + originalSymbolToExportInfos.add(ts.getUniqueSymbolId(exportedSymbol, checker).toString(), { moduleSymbol: moduleSymbol, importKind: importKind, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exportedSymbol, checker) }); + } + forEachExternalModuleToImportFrom(checker, sourceFile, program.getSourceFiles(), function (moduleSymbol) { + cancellationToken.throwIfCancellationRequested(); + var defaultInfo = getDefaultLikeExportInfo(moduleSymbol, checker, program.getCompilerOptions()); + if (defaultInfo && defaultInfo.name === symbolName && symbolHasMeaning(defaultInfo.symbolForMeaning, currentTokenMeaning)) { + addSymbol(moduleSymbol, defaultInfo.symbol, defaultInfo.kind); + } + // check exports with the same name + var exportSymbolWithIdenticalName = checker.tryGetMemberInModuleExportsAndProperties(symbolName, moduleSymbol); + if (exportSymbolWithIdenticalName && symbolHasMeaning(exportSymbolWithIdenticalName, currentTokenMeaning)) { + addSymbol(moduleSymbol, exportSymbolWithIdenticalName, 0 /* Named */); + } + }); + return originalSymbolToExportInfos; + } + function getDefaultLikeExportInfo(moduleSymbol, checker, compilerOptions) { + var exported = getDefaultLikeExportWorker(moduleSymbol, checker); + if (!exported) + return undefined; + var symbol = exported.symbol, kind = exported.kind; + var info = getDefaultExportInfoWorker(symbol, moduleSymbol, checker, compilerOptions); + return info && __assign({ symbol: symbol, kind: kind }, info); + } + function getDefaultLikeExportWorker(moduleSymbol, checker) { + var defaultExport = checker.tryGetMemberInModuleExports("default" /* Default */, moduleSymbol); + if (defaultExport) + return { symbol: defaultExport, kind: 1 /* Default */ }; + var exportEquals = checker.resolveExternalModuleSymbol(moduleSymbol); + return exportEquals === moduleSymbol ? undefined : { symbol: exportEquals, kind: 3 /* Equals */ }; + } + function getDefaultExportInfoWorker(defaultExport, moduleSymbol, checker, compilerOptions) { + var localSymbol = ts.getLocalSymbolForExportDefault(defaultExport); + if (localSymbol) + return { symbolForMeaning: localSymbol, name: localSymbol.name }; + var name = getNameForExportDefault(defaultExport); + if (name !== undefined) + return { symbolForMeaning: defaultExport, name: name }; + if (defaultExport.flags & 2097152 /* Alias */) { + var aliased = checker.getImmediateAliasedSymbol(defaultExport); + return aliased && getDefaultExportInfoWorker(aliased, ts.Debug.assertDefined(aliased.parent), checker, compilerOptions); + } + else { + return { symbolForMeaning: defaultExport, name: moduleSymbolToValidIdentifier(moduleSymbol, compilerOptions.target) }; + } + } + function getNameForExportDefault(symbol) { + return symbol.declarations && ts.firstDefined(symbol.declarations, function (declaration) { + if (ts.isExportAssignment(declaration)) { + if (ts.isIdentifier(declaration.expression)) { + return declaration.expression.text; + } + } + else if (ts.isExportSpecifier(declaration)) { + ts.Debug.assert(declaration.name.text === "default" /* Default */); + return declaration.propertyName && declaration.propertyName.text; + } + }); + } + function codeActionForFix(context, sourceFile, symbolName, fix, quotePreference) { + var diag; + var changes = ts.textChanges.ChangeTracker.with(context, function (tracker) { + diag = codeActionForFixWorker(tracker, sourceFile, symbolName, fix, quotePreference); + }); + return codefix.createCodeFixAction("import", changes, diag, codefix.importFixId, ts.Diagnostics.Add_all_missing_imports); + } + function codeActionForFixWorker(changes, sourceFile, symbolName, fix, quotePreference) { + switch (fix.kind) { + case 0 /* UseNamespace */: + addNamespaceQualifier(changes, sourceFile, fix); + return [ts.Diagnostics.Change_0_to_1, symbolName, fix.namespacePrefix + "." + symbolName]; + case 1 /* ImportType */: + addImportType(changes, sourceFile, fix, quotePreference); + return [ts.Diagnostics.Change_0_to_1, symbolName, getImportTypePrefix(fix.moduleSpecifier, quotePreference) + symbolName]; + case 2 /* AddToExisting */: { + var importClause = fix.importClause, importKind = fix.importKind; + doAddExistingFix(changes, sourceFile, importClause, importKind === 1 /* Default */ ? symbolName : undefined, importKind === 0 /* Named */ ? [symbolName] : ts.emptyArray); + var moduleSpecifierWithoutQuotes = ts.stripQuotes(importClause.parent.moduleSpecifier.getText()); + return [importKind === 1 /* Default */ ? ts.Diagnostics.Add_default_import_0_to_existing_import_declaration_from_1 : ts.Diagnostics.Add_0_to_existing_import_declaration_from_1, symbolName, moduleSpecifierWithoutQuotes]; // you too! + } + case 3 /* AddNew */: { + var importKind = fix.importKind, moduleSpecifier = fix.moduleSpecifier; + addNewImports(changes, sourceFile, moduleSpecifier, quotePreference, importKind === 1 /* Default */ ? { defaultImport: symbolName, namedImports: ts.emptyArray, namespaceLikeImport: undefined } + : importKind === 0 /* Named */ ? { defaultImport: undefined, namedImports: [symbolName], namespaceLikeImport: undefined } + : { defaultImport: undefined, namedImports: ts.emptyArray, namespaceLikeImport: { importKind: importKind, name: symbolName } }); + return [importKind === 1 /* Default */ ? ts.Diagnostics.Import_default_0_from_module_1 : ts.Diagnostics.Import_0_from_module_1, symbolName, moduleSpecifier]; + } + default: + return ts.Debug.assertNever(fix); + } + } + function doAddExistingFix(changes, sourceFile, clause, defaultImport, namedImports) { + if (defaultImport) { + ts.Debug.assert(!clause.name); + changes.insertNodeAt(sourceFile, clause.getStart(sourceFile), ts.createIdentifier(defaultImport), { suffix: ", " }); + } + if (namedImports.length) { + var specifiers = namedImports.map(function (name) { return ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(name)); }); + if (clause.namedBindings && ts.cast(clause.namedBindings, ts.isNamedImports).elements.length) { + for (var _i = 0, specifiers_1 = specifiers; _i < specifiers_1.length; _i++) { + var spec = specifiers_1[_i]; + changes.insertNodeInListAfter(sourceFile, ts.last(ts.cast(clause.namedBindings, ts.isNamedImports).elements), spec); + } + } + else { + if (specifiers.length) { + var namedImports_1 = ts.createNamedImports(specifiers); + if (clause.namedBindings) { + changes.replaceNode(sourceFile, clause.namedBindings, namedImports_1); + } + else { + changes.insertNodeAfter(sourceFile, ts.Debug.assertDefined(clause.name), namedImports_1); + } + } + } + } + } + function addNamespaceQualifier(changes, sourceFile, _a) { + var namespacePrefix = _a.namespacePrefix, position = _a.position; + changes.insertText(sourceFile, position, namespacePrefix + "."); + } + function addImportType(changes, sourceFile, _a, quotePreference) { + var moduleSpecifier = _a.moduleSpecifier, position = _a.position; + changes.insertText(sourceFile, position, getImportTypePrefix(moduleSpecifier, quotePreference)); + } + function getImportTypePrefix(moduleSpecifier, quotePreference) { + var quote = ts.getQuoteFromPreference(quotePreference); + return "import(" + quote + moduleSpecifier + quote + ")."; + } + function addNewImports(changes, sourceFile, moduleSpecifier, quotePreference, _a) { + var defaultImport = _a.defaultImport, namedImports = _a.namedImports, namespaceLikeImport = _a.namespaceLikeImport; + var quotedModuleSpecifier = ts.makeStringLiteral(moduleSpecifier, quotePreference); + if (defaultImport !== undefined || namedImports.length) { + ts.insertImport(changes, sourceFile, ts.makeImport(defaultImport === undefined ? undefined : ts.createIdentifier(defaultImport), namedImports.map(function (n) { return ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(n)); }), moduleSpecifier, quotePreference)); + } + if (namespaceLikeImport) { + ts.insertImport(changes, sourceFile, namespaceLikeImport.importKind === 3 /* Equals */ + ? ts.createImportEqualsDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createIdentifier(namespaceLikeImport.name), ts.createExternalModuleReference(quotedModuleSpecifier)) + : ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(ts.createIdentifier(namespaceLikeImport.name))), quotedModuleSpecifier)); + } + } + function symbolHasMeaning(_a, meaning) { + var declarations = _a.declarations; + return ts.some(declarations, function (decl) { return !!(ts.getMeaningFromDeclaration(decl) & meaning); }); + } + function forEachExternalModuleToImportFrom(checker, from, allSourceFiles, cb) { + forEachExternalModule(checker, allSourceFiles, function (module, sourceFile) { + if (sourceFile === undefined || sourceFile !== from && isImportablePath(from.fileName, sourceFile.fileName)) { + cb(module); + } + }); + } + codefix.forEachExternalModuleToImportFrom = forEachExternalModuleToImportFrom; + function forEachExternalModule(checker, allSourceFiles, cb) { + for (var _i = 0, _a = checker.getAmbientModules(); _i < _a.length; _i++) { + var ambient = _a[_i]; + cb(ambient, /*sourceFile*/ undefined); + } + for (var _b = 0, allSourceFiles_1 = allSourceFiles; _b < allSourceFiles_1.length; _b++) { + var sourceFile = allSourceFiles_1[_b]; + if (ts.isExternalOrCommonJsModule(sourceFile)) { + cb(checker.getMergedSymbol(sourceFile.symbol), sourceFile); + } + } + } + /** + * Don't include something from a `node_modules` that isn't actually reachable by a global import. + * A relative import to node_modules is usually a bad idea. + */ + function isImportablePath(fromPath, toPath) { + // If it's in a `node_modules` but is not reachable from here via a global import, don't bother. + var toNodeModules = ts.forEachAncestorDirectory(toPath, function (ancestor) { return ts.getBaseFileName(ancestor) === "node_modules" ? ancestor : undefined; }); + return toNodeModules === undefined || ts.startsWith(fromPath, ts.getDirectoryPath(toNodeModules)); + } + function moduleSymbolToValidIdentifier(moduleSymbol, target) { + return moduleSpecifierToValidIdentifier(ts.removeFileExtension(ts.stripQuotes(moduleSymbol.name)), target); + } + codefix.moduleSymbolToValidIdentifier = moduleSymbolToValidIdentifier; + function moduleSpecifierToValidIdentifier(moduleSpecifier, target) { + var baseName = ts.getBaseFileName(ts.removeSuffix(moduleSpecifier, "/index")); + var res = ""; + var lastCharWasValid = true; + var firstCharCode = baseName.charCodeAt(0); + if (ts.isIdentifierStart(firstCharCode, target)) { + res += String.fromCharCode(firstCharCode); + } + else { + lastCharWasValid = false; + } + for (var i = 1; i < baseName.length; i++) { + var ch = baseName.charCodeAt(i); + var isValid = ts.isIdentifierPart(ch, target); + if (isValid) { + var char = String.fromCharCode(ch); + if (!lastCharWasValid) { + char = char.toUpperCase(); + } + res += char; + } + lastCharWasValid = isValid; + } + // Need `|| "_"` to ensure result isn't empty. + return !ts.isStringANonContextualKeyword(res) ? res || "_" : "_" + res; + } + codefix.moduleSpecifierToValidIdentifier = moduleSpecifierToValidIdentifier; + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "fixSpelling"; + var errorCodes = [ + ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2.code, + ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1.code, + ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0.code, + ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_static_member_1_0.code, + ts.Diagnostics.Module_0_has_no_exported_member_1_Did_you_mean_2.code, + ]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var sourceFile = context.sourceFile; + var info = getInfo(sourceFile, context.span.start, context); + if (!info) + return undefined; + var node = info.node, suggestion = info.suggestion; + var target = context.host.getCompilationSettings().target; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, node, suggestion, target); }); + return [codefix.createCodeFixAction("spelling", changes, [ts.Diagnostics.Change_spelling_to_0, suggestion], fixId, ts.Diagnostics.Fix_all_detected_spelling_errors)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var info = getInfo(diag.file, diag.start, context); + var target = context.host.getCompilationSettings().target; + if (info) + doChange(changes, context.sourceFile, info.node, info.suggestion, target); + }); }, + }); + function getInfo(sourceFile, pos, context) { + // This is the identifier of the misspelled word. eg: + // this.speling = 1; + // ^^^^^^^ + var node = ts.getTokenAtPosition(sourceFile, pos); + var checker = context.program.getTypeChecker(); + var suggestion; + if (ts.isPropertyAccessExpression(node.parent) && node.parent.name === node) { + ts.Debug.assert(node.kind === 72 /* Identifier */); + var containingType = checker.getTypeAtLocation(node.parent.expression); + suggestion = checker.getSuggestionForNonexistentProperty(node, containingType); + } + else if (ts.isImportSpecifier(node.parent) && node.parent.name === node) { + ts.Debug.assert(node.kind === 72 /* Identifier */); + var importDeclaration = ts.findAncestor(node, ts.isImportDeclaration); + var resolvedSourceFile = getResolvedSourceFileFromImportDeclaration(sourceFile, context, importDeclaration); + if (resolvedSourceFile && resolvedSourceFile.symbol) { + suggestion = checker.getSuggestionForNonexistentExport(node, resolvedSourceFile.symbol); + } + } + else { + var meaning = ts.getMeaningFromLocation(node); + var name = ts.getTextOfNode(node); + ts.Debug.assert(name !== undefined, "name should be defined"); + suggestion = checker.getSuggestionForNonexistentSymbol(node, name, convertSemanticMeaningToSymbolFlags(meaning)); + } + return suggestion === undefined ? undefined : { node: node, suggestion: suggestion }; + } + function doChange(changes, sourceFile, node, suggestion, target) { + if (!ts.isIdentifierText(suggestion, target) && ts.isPropertyAccessExpression(node.parent)) { + changes.replaceNode(sourceFile, node.parent, ts.createElementAccess(node.parent.expression, ts.createLiteral(suggestion))); + } + else { + changes.replaceNode(sourceFile, node, ts.createIdentifier(suggestion)); + } + } + function convertSemanticMeaningToSymbolFlags(meaning) { + var flags = 0; + if (meaning & 4 /* Namespace */) { + flags |= 1920 /* Namespace */; + } + if (meaning & 2 /* Type */) { + flags |= 67897832 /* Type */; + } + if (meaning & 1 /* Value */) { + flags |= 67220415 /* Value */; + } + return flags; + } + function getResolvedSourceFileFromImportDeclaration(sourceFile, context, importDeclaration) { + if (!importDeclaration || !ts.isStringLiteralLike(importDeclaration.moduleSpecifier)) + return undefined; + var resolvedModule = ts.getResolvedModule(sourceFile, importDeclaration.moduleSpecifier.text); + if (!resolvedModule) + return undefined; + return context.program.getSourceFile(resolvedModule.resolvedFileName); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixName = "addMissingMember"; + var errorCodes = [ + ts.Diagnostics.Property_0_does_not_exist_on_type_1.code, + ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2.code, + ts.Diagnostics.Property_0_is_missing_in_type_1_but_required_in_type_2.code, + ts.Diagnostics.Type_0_is_missing_the_following_properties_from_type_1_Colon_2.code, + ts.Diagnostics.Type_0_is_missing_the_following_properties_from_type_1_Colon_2_and_3_more.code + ]; + var fixId = "addMissingMember"; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var info = getInfo(context.sourceFile, context.span.start, context.program.getTypeChecker()); + if (!info) + return undefined; + if (info.kind === 0 /* Enum */) { + var token_1 = info.token, parentDeclaration_1 = info.parentDeclaration; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addEnumMemberDeclaration(t, context.program.getTypeChecker(), token_1, parentDeclaration_1); }); + return [codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Add_missing_enum_member_0, token_1.text], fixId, ts.Diagnostics.Add_all_missing_members)]; + } + var parentDeclaration = info.parentDeclaration, declSourceFile = info.declSourceFile, inJs = info.inJs, makeStatic = info.makeStatic, token = info.token, call = info.call; + var methodCodeAction = call && getActionForMethodDeclaration(context, declSourceFile, parentDeclaration, token, call, makeStatic, inJs, context.preferences); + var addMember = inJs && !ts.isInterfaceDeclaration(parentDeclaration) ? + ts.singleElementArray(getActionsForAddMissingMemberInJavascriptFile(context, declSourceFile, parentDeclaration, token.text, makeStatic)) : + getActionsForAddMissingMemberInTypeScriptFile(context, declSourceFile, parentDeclaration, token, makeStatic); + return ts.concatenate(ts.singleElementArray(methodCodeAction), addMember); + }, + fixIds: [fixId], + getAllCodeActions: function (context) { + var program = context.program, preferences = context.preferences; + var checker = program.getTypeChecker(); + var seen = ts.createMap(); + var typeDeclToMembers = new ts.NodeMap(); + return codefix.createCombinedCodeActions(ts.textChanges.ChangeTracker.with(context, function (changes) { + codefix.eachDiagnostic(context, errorCodes, function (diag) { + var info = getInfo(diag.file, diag.start, checker); + if (!info || !ts.addToSeen(seen, ts.getNodeId(info.parentDeclaration) + "#" + info.token.text)) { + return; + } + if (info.kind === 0 /* Enum */) { + var token = info.token, parentDeclaration = info.parentDeclaration; + addEnumMemberDeclaration(changes, checker, token, parentDeclaration); + } + else { + var parentDeclaration = info.parentDeclaration, token_2 = info.token; + var infos = typeDeclToMembers.getOrUpdate(parentDeclaration, function () { return []; }); + if (!infos.some(function (i) { return i.token.text === token_2.text; })) + infos.push(info); + } + }); + typeDeclToMembers.forEach(function (infos, classDeclaration) { + var supers = getAllSupers(classDeclaration, checker); + var _loop_20 = function (info) { + // If some superclass added this property, don't add it again. + if (supers.some(function (superClassOrInterface) { + var superInfos = typeDeclToMembers.get(superClassOrInterface); + return !!superInfos && superInfos.some(function (_a) { + var token = _a.token; + return token.text === info.token.text; + }); + })) + return "continue"; + var parentDeclaration = info.parentDeclaration, declSourceFile = info.declSourceFile, inJs = info.inJs, makeStatic = info.makeStatic, token = info.token, call = info.call; + // Always prefer to add a method declaration if possible. + if (call) { + addMethodDeclaration(context, changes, declSourceFile, parentDeclaration, token, call, makeStatic, inJs, preferences); + } + else { + if (inJs && !ts.isInterfaceDeclaration(parentDeclaration)) { + addMissingMemberInJs(changes, declSourceFile, parentDeclaration, token.text, makeStatic); + } + else { + var typeNode = getTypeNode(program.getTypeChecker(), parentDeclaration, token); + addPropertyDeclaration(changes, declSourceFile, parentDeclaration, token.text, typeNode, makeStatic); + } + } + }; + for (var _i = 0, infos_1 = infos; _i < infos_1.length; _i++) { + var info = infos_1[_i]; + _loop_20(info); + } + }); + })); + }, + }); + function getAllSupers(decl, checker) { + var res = []; + while (decl) { + var superElement = ts.getClassExtendsHeritageElement(decl); + var superSymbol = superElement && checker.getSymbolAtLocation(superElement.expression); + var superDecl = superSymbol && ts.find(superSymbol.declarations, ts.isClassLike); + if (superDecl) { + res.push(superDecl); + } + decl = superDecl; + } + return res; + } + var InfoKind; + (function (InfoKind) { + InfoKind[InfoKind["Enum"] = 0] = "Enum"; + InfoKind[InfoKind["ClassOrInterface"] = 1] = "ClassOrInterface"; + })(InfoKind || (InfoKind = {})); + function getInfo(tokenSourceFile, tokenPos, checker) { + // The identifier of the missing property. eg: + // this.missing = 1; + // ^^^^^^^ + var token = ts.getTokenAtPosition(tokenSourceFile, tokenPos); + if (!ts.isIdentifier(token)) { + return undefined; + } + var parent = token.parent; + if (!ts.isPropertyAccessExpression(parent)) + return undefined; + var leftExpressionType = ts.skipConstraint(checker.getTypeAtLocation(parent.expression)); + var symbol = leftExpressionType.symbol; + if (!symbol || !symbol.declarations) + return undefined; + // Prefer to change the class instead of the interface if they are merged + var classOrInterface = ts.find(symbol.declarations, ts.isClassLike) || ts.find(symbol.declarations, ts.isInterfaceDeclaration); + if (classOrInterface) { + var makeStatic = (leftExpressionType.target || leftExpressionType) !== checker.getDeclaredTypeOfSymbol(symbol); + var declSourceFile = classOrInterface.getSourceFile(); + var inJs = ts.isSourceFileJS(declSourceFile); + var call = ts.tryCast(parent.parent, ts.isCallExpression); + return { kind: 1 /* ClassOrInterface */, token: token, parentDeclaration: classOrInterface, makeStatic: makeStatic, declSourceFile: declSourceFile, inJs: inJs, call: call }; + } + var enumDeclaration = ts.find(symbol.declarations, ts.isEnumDeclaration); + if (enumDeclaration) { + return { kind: 0 /* Enum */, token: token, parentDeclaration: enumDeclaration }; + } + return undefined; + } + function getActionsForAddMissingMemberInJavascriptFile(context, declSourceFile, classDeclaration, tokenName, makeStatic) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMissingMemberInJs(t, declSourceFile, classDeclaration, tokenName, makeStatic); }); + return changes.length === 0 ? undefined + : codefix.createCodeFixAction(fixName, changes, [makeStatic ? ts.Diagnostics.Initialize_static_property_0 : ts.Diagnostics.Initialize_property_0_in_the_constructor, tokenName], fixId, ts.Diagnostics.Add_all_missing_members); + } + function addMissingMemberInJs(changeTracker, declSourceFile, classDeclaration, tokenName, makeStatic) { + if (makeStatic) { + if (classDeclaration.kind === 209 /* ClassExpression */) { + return; + } + var className = classDeclaration.name.getText(); + var staticInitialization = initializePropertyToUndefined(ts.createIdentifier(className), tokenName); + changeTracker.insertNodeAfter(declSourceFile, classDeclaration, staticInitialization); + } + else { + var classConstructor = ts.getFirstConstructorWithBody(classDeclaration); + if (!classConstructor) { + return; + } + var propertyInitialization = initializePropertyToUndefined(ts.createThis(), tokenName); + changeTracker.insertNodeAtConstructorEnd(declSourceFile, classConstructor, propertyInitialization); + } + } + function initializePropertyToUndefined(obj, propertyName) { + return ts.createStatement(ts.createAssignment(ts.createPropertyAccess(obj, propertyName), ts.createIdentifier("undefined"))); + } + function getActionsForAddMissingMemberInTypeScriptFile(context, declSourceFile, classDeclaration, token, makeStatic) { + var typeNode = getTypeNode(context.program.getTypeChecker(), classDeclaration, token); + var addProp = createAddPropertyDeclarationAction(context, declSourceFile, classDeclaration, makeStatic, token.text, typeNode); + return makeStatic ? [addProp] : [addProp, createAddIndexSignatureAction(context, declSourceFile, classDeclaration, token.text, typeNode)]; + } + function getTypeNode(checker, classDeclaration, token) { + var typeNode; + if (token.parent.parent.kind === 204 /* BinaryExpression */) { + var binaryExpression = token.parent.parent; + var otherExpression = token.parent === binaryExpression.left ? binaryExpression.right : binaryExpression.left; + var widenedType = checker.getWidenedType(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(otherExpression))); + typeNode = checker.typeToTypeNode(widenedType, classDeclaration); + } + else { + var contextualType = checker.getContextualType(token.parent); + typeNode = contextualType ? checker.typeToTypeNode(contextualType) : undefined; + } + return typeNode || ts.createKeywordTypeNode(120 /* AnyKeyword */); + } + function createAddPropertyDeclarationAction(context, declSourceFile, classDeclaration, makeStatic, tokenName, typeNode) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addPropertyDeclaration(t, declSourceFile, classDeclaration, tokenName, typeNode, makeStatic); }); + return codefix.createCodeFixAction(fixName, changes, [makeStatic ? ts.Diagnostics.Declare_static_property_0 : ts.Diagnostics.Declare_property_0, tokenName], fixId, ts.Diagnostics.Add_all_missing_members); + } + function addPropertyDeclaration(changeTracker, declSourceFile, classDeclaration, tokenName, typeNode, makeStatic) { + var property = ts.createProperty( + /*decorators*/ undefined, + /*modifiers*/ makeStatic ? [ts.createToken(116 /* StaticKeyword */)] : undefined, tokenName, + /*questionToken*/ undefined, typeNode, + /*initializer*/ undefined); + var lastProp = getNodeToInsertPropertyAfter(classDeclaration); + if (lastProp) { + changeTracker.insertNodeAfter(declSourceFile, lastProp, property); + } + else { + changeTracker.insertNodeAtClassStart(declSourceFile, classDeclaration, property); + } + } + // Gets the last of the first run of PropertyDeclarations, or undefined if the class does not start with a PropertyDeclaration. + function getNodeToInsertPropertyAfter(cls) { + var res; + for (var _i = 0, _a = cls.members; _i < _a.length; _i++) { + var member = _a[_i]; + if (!ts.isPropertyDeclaration(member)) + break; + res = member; + } + return res; + } + function createAddIndexSignatureAction(context, declSourceFile, classDeclaration, tokenName, typeNode) { + // Index signatures cannot have the static modifier. + var stringTypeNode = ts.createKeywordTypeNode(138 /* StringKeyword */); + var indexingParameter = ts.createParameter( + /*decorators*/ undefined, + /*modifiers*/ undefined, + /*dotDotDotToken*/ undefined, "x", + /*questionToken*/ undefined, stringTypeNode, + /*initializer*/ undefined); + var indexSignature = ts.createIndexSignature( + /*decorators*/ undefined, + /*modifiers*/ undefined, [indexingParameter], typeNode); + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.insertNodeAtClassStart(declSourceFile, classDeclaration, indexSignature); }); + // No fixId here because code-fix-all currently only works on adding individual named properties. + return codefix.createCodeFixActionNoFixId(fixName, changes, [ts.Diagnostics.Add_index_signature_for_property_0, tokenName]); + } + function getActionForMethodDeclaration(context, declSourceFile, classDeclaration, token, callExpression, makeStatic, inJs, preferences) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMethodDeclaration(context, t, declSourceFile, classDeclaration, token, callExpression, makeStatic, inJs, preferences); }); + return codefix.createCodeFixAction(fixName, changes, [makeStatic ? ts.Diagnostics.Declare_static_method_0 : ts.Diagnostics.Declare_method_0, token.text], fixId, ts.Diagnostics.Add_all_missing_members); + } + function addMethodDeclaration(context, changeTracker, declSourceFile, typeDecl, token, callExpression, makeStatic, inJs, preferences) { + var methodDeclaration = codefix.createMethodFromCallExpression(context, callExpression, token.text, inJs, makeStatic, preferences, !ts.isInterfaceDeclaration(typeDecl)); + var containingMethodDeclaration = ts.getAncestor(callExpression, 156 /* MethodDeclaration */); + if (containingMethodDeclaration && containingMethodDeclaration.parent === typeDecl) { + changeTracker.insertNodeAfter(declSourceFile, containingMethodDeclaration, methodDeclaration); + } + else { + changeTracker.insertNodeAtClassStart(declSourceFile, typeDecl, methodDeclaration); + } + } + function addEnumMemberDeclaration(changes, checker, token, enumDeclaration) { + /** + * create initializer only literal enum that has string initializer. + * value of initializer is a string literal that equal to name of enum member. + * numeric enum or empty enum will not create initializer. + */ + var hasStringInitializer = ts.some(enumDeclaration.members, function (member) { + var type = checker.getTypeAtLocation(member); + return !!(type && type.flags & 132 /* StringLike */); + }); + var enumMember = ts.createEnumMember(token, hasStringInitializer ? ts.createStringLiteral(token.text) : undefined); + changes.replaceNode(enumDeclaration.getSourceFile(), enumDeclaration, ts.updateEnumDeclaration(enumDeclaration, enumDeclaration.decorators, enumDeclaration.modifiers, enumDeclaration.name, ts.concatenate(enumDeclaration.members, ts.singleElementArray(enumMember)))); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixName = "fixCannotFindModule"; + var fixIdInstallTypesPackage = "installTypesPackage"; + var fixIdGenerateTypes = "generateTypes"; + var errorCodeCannotFindModule = ts.Diagnostics.Cannot_find_module_0.code; + var errorCodes = [ + errorCodeCannotFindModule, + ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type.code, + ]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var host = context.host, sourceFile = context.sourceFile, start = context.span.start; + var packageName = tryGetImportedPackageName(sourceFile, start); + if (packageName === undefined) + return undefined; + var typesPackageName = getTypesPackageNameToInstall(packageName, host, context.errorCode); + return typesPackageName === undefined + ? ts.singleElementArray(tryGetGenerateTypesAction(context, packageName)) + : [codefix.createCodeFixAction(fixName, /*changes*/ [], [ts.Diagnostics.Install_0, typesPackageName], fixIdInstallTypesPackage, ts.Diagnostics.Install_all_missing_types_packages, getInstallCommand(sourceFile.fileName, typesPackageName))]; + }, + fixIds: [fixIdInstallTypesPackage, fixIdGenerateTypes], + getAllCodeActions: function (context) { + var savedTypesDir = null; // tslint:disable-line no-null-keyword + return codefix.codeFixAll(context, errorCodes, function (changes, diag, commands) { + var packageName = tryGetImportedPackageName(diag.file, diag.start); + if (packageName === undefined) + return undefined; + switch (context.fixId) { + case fixIdInstallTypesPackage: { + var pkg = getTypesPackageNameToInstall(packageName, context.host, diag.code); + if (pkg) { + commands.push(getInstallCommand(diag.file.fileName, pkg)); + } + break; + } + case fixIdGenerateTypes: { + var typesDir = savedTypesDir !== null ? savedTypesDir : savedTypesDir = getOrCreateTypesDirectory(changes, context); + var command = typesDir === undefined ? undefined : tryGenerateTypes(typesDir, packageName, context); + if (command) + commands.push(command); + break; + } + default: + ts.Debug.fail("Bad fixId: " + context.fixId); + } + }); + }, + }); + function tryGetGenerateTypesAction(context, packageName) { + var command; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { + var typesDir = getOrCreateTypesDirectory(t, context); + command = typesDir === undefined ? undefined : tryGenerateTypes(typesDir, packageName, context); + }); + return command && codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Generate_types_for_0, packageName], fixIdGenerateTypes, ts.Diagnostics.Generate_types_for_all_packages_without_types, command); + } + function tryGenerateTypes(typesDir, packageName, context) { + var file = context.sourceFile.fileName; + var fileToGenerateTypesFor = ts.tryResolveJSModule(packageName, ts.getDirectoryPath(file), context.host); // TODO: GH#18217 + if (fileToGenerateTypesFor === undefined) + return undefined; + var outputFileName = ts.resolvePath(ts.getDirectoryPath(context.program.getCompilerOptions().configFile.fileName), typesDir, packageName + ".d.ts"); + if (context.host.fileExists(outputFileName)) + return undefined; + return { type: "generate types", file: file, fileToGenerateTypesFor: fileToGenerateTypesFor, outputFileName: outputFileName }; + } + // If no types directory exists yet, adds it to tsconfig.json + function getOrCreateTypesDirectory(changes, context) { + var configFile = context.program.getCompilerOptions().configFile; + if (!configFile) + return undefined; + var tsconfigObjectLiteral = ts.getTsConfigObjectLiteralExpression(configFile); + if (!tsconfigObjectLiteral) + return undefined; + var compilerOptionsProperty = findProperty(tsconfigObjectLiteral, "compilerOptions"); + if (!compilerOptionsProperty) { + var newCompilerOptions = ts.createObjectLiteral([makeDefaultBaseUrl(), makeDefaultPaths()]); + changes.insertNodeAtObjectStart(configFile, tsconfigObjectLiteral, createJsonPropertyAssignment("compilerOptions", newCompilerOptions)); + return defaultTypesDirectoryName; + } + var compilerOptions = compilerOptionsProperty.initializer; + if (!ts.isObjectLiteralExpression(compilerOptions)) + return defaultTypesDirectoryName; + var baseUrl = getOrAddBaseUrl(changes, configFile, compilerOptions); + var typesDirectoryFromPathMapping = getOrAddPathMapping(changes, configFile, compilerOptions); + return ts.combinePaths(baseUrl, typesDirectoryFromPathMapping); + } + var defaultBaseUrl = "."; + function makeDefaultBaseUrl() { + return createJsonPropertyAssignment("baseUrl", ts.createStringLiteral(defaultBaseUrl)); + } + function getOrAddBaseUrl(changes, tsconfig, compilerOptions) { + var baseUrlProp = findProperty(compilerOptions, "baseUrl"); + if (baseUrlProp) { + return ts.isStringLiteral(baseUrlProp.initializer) ? baseUrlProp.initializer.text : defaultBaseUrl; + } + else { + changes.insertNodeAtObjectStart(tsconfig, compilerOptions, makeDefaultBaseUrl()); + return defaultBaseUrl; + } + } + var defaultTypesDirectoryName = "types"; + function makeDefaultPathMapping() { + return createJsonPropertyAssignment("*", ts.createArrayLiteral([ts.createStringLiteral(defaultTypesDirectoryName + "/*")])); + } + function makeDefaultPaths() { + return createJsonPropertyAssignment("paths", ts.createObjectLiteral([makeDefaultPathMapping()])); + } + function getOrAddPathMapping(changes, tsconfig, compilerOptions) { + var paths = findProperty(compilerOptions, "paths"); + if (!paths || !ts.isObjectLiteralExpression(paths.initializer)) { + changes.insertNodeAtObjectStart(tsconfig, compilerOptions, makeDefaultPaths()); + return defaultTypesDirectoryName; + } + // Look for an existing path mapping. Should look like `"*": "foo/*"`. + var existing = ts.firstDefined(paths.initializer.properties, function (prop) { + return ts.isPropertyAssignment(prop) && ts.isStringLiteral(prop.name) && prop.name.text === "*" && ts.isArrayLiteralExpression(prop.initializer) + ? ts.firstDefined(prop.initializer.elements, function (value) { return ts.isStringLiteral(value) ? ts.tryRemoveSuffix(value.text, "/*") : undefined; }) + : undefined; + }); + if (existing) + return existing; + changes.insertNodeAtObjectStart(tsconfig, paths.initializer, makeDefaultPathMapping()); + return defaultTypesDirectoryName; + } + function createJsonPropertyAssignment(name, initializer) { + return ts.createPropertyAssignment(ts.createStringLiteral(name), initializer); + } + function findProperty(obj, name) { + return ts.find(obj.properties, function (p) { return ts.isPropertyAssignment(p) && !!p.name && ts.isStringLiteral(p.name) && p.name.text === name; }); + } + function getInstallCommand(fileName, packageName) { + return { type: "install package", file: fileName, packageName: packageName }; + } + function tryGetImportedPackageName(sourceFile, pos) { + var moduleName = ts.cast(ts.getTokenAtPosition(sourceFile, pos), ts.isStringLiteral).text; + var packageName = ts.parsePackageName(moduleName).packageName; + return ts.isExternalModuleNameRelative(packageName) ? undefined : packageName; + } + function getTypesPackageNameToInstall(packageName, host, diagCode) { + return diagCode === errorCodeCannotFindModule + ? (ts.JsTyping.nodeCoreModules.has(packageName) ? "@types/node" : undefined) + : (host.isKnownTypesPackageName(packageName) ? ts.getTypesPackageName(packageName) : undefined); // TODO: GH#18217 + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var errorCodes = [ + ts.Diagnostics.Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2.code, + ts.Diagnostics.Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1.code, + ]; + var fixId = "fixClassDoesntImplementInheritedAbstractMember"; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var program = context.program, sourceFile = context.sourceFile, span = context.span; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { + return addMissingMembers(getClass(sourceFile, span.start), sourceFile, program.getTypeChecker(), t, context.preferences); + }); + return changes.length === 0 ? undefined : [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Implement_inherited_abstract_class, fixId, ts.Diagnostics.Implement_all_inherited_abstract_classes)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { + var seenClassDeclarations = ts.createMap(); + return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var classDeclaration = getClass(diag.file, diag.start); + if (ts.addToSeen(seenClassDeclarations, ts.getNodeId(classDeclaration))) { + addMissingMembers(classDeclaration, context.sourceFile, context.program.getTypeChecker(), changes, context.preferences); + } + }); + }, + }); + function getClass(sourceFile, pos) { + // Token is the identifier in the case of a class declaration + // or the class keyword token in the case of a class expression. + var token = ts.getTokenAtPosition(sourceFile, pos); + return ts.cast(token.parent, ts.isClassLike); + } + function addMissingMembers(classDeclaration, sourceFile, checker, changeTracker, preferences) { + var extendsNode = ts.getEffectiveBaseTypeNode(classDeclaration); + var instantiatedExtendsType = checker.getTypeAtLocation(extendsNode); + // Note that this is ultimately derived from a map indexed by symbol names, + // so duplicates cannot occur. + var abstractAndNonPrivateExtendsSymbols = checker.getPropertiesOfType(instantiatedExtendsType).filter(symbolPointsToNonPrivateAndAbstractMember); + codefix.createMissingMemberNodes(classDeclaration, abstractAndNonPrivateExtendsSymbols, checker, preferences, function (member) { return changeTracker.insertNodeAtClassStart(sourceFile, classDeclaration, member); }); + } + function symbolPointsToNonPrivateAndAbstractMember(symbol) { + // See `codeFixClassExtendAbstractProtectedProperty.ts` in https://github.com/Microsoft/TypeScript/pull/11547/files + // (now named `codeFixClassExtendAbstractPrivateProperty.ts`) + var flags = ts.getModifierFlags(ts.first(symbol.getDeclarations())); + return !(flags & 8 /* Private */) && !!(flags & 128 /* Abstract */); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "classSuperMustPrecedeThisAccess"; + var errorCodes = [ts.Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var sourceFile = context.sourceFile, span = context.span; + var nodes = getNodes(sourceFile, span.start); + if (!nodes) + return undefined; + var constructor = nodes.constructor, superCall = nodes.superCall; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, constructor, superCall); }); + return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Make_super_call_the_first_statement_in_the_constructor, fixId, ts.Diagnostics.Make_all_super_calls_the_first_statement_in_their_constructor)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { + var sourceFile = context.sourceFile; + var seenClasses = ts.createMap(); // Ensure we only do this once per class. + return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var nodes = getNodes(diag.file, diag.start); + if (!nodes) + return; + var constructor = nodes.constructor, superCall = nodes.superCall; + if (ts.addToSeen(seenClasses, ts.getNodeId(constructor.parent))) { + doChange(changes, sourceFile, constructor, superCall); + } + }); + }, + }); + function doChange(changes, sourceFile, constructor, superCall) { + changes.insertNodeAtConstructorStart(sourceFile, constructor, superCall); + changes.delete(sourceFile, superCall); + } + function getNodes(sourceFile, pos) { + var token = ts.getTokenAtPosition(sourceFile, pos); + if (token.kind !== 100 /* ThisKeyword */) + return undefined; + var constructor = ts.getContainingFunction(token); + var superCall = findSuperCall(constructor.body); + // figure out if the `this` access is actually inside the supercall + // i.e. super(this.a), since in that case we won't suggest a fix + return superCall && !superCall.expression.arguments.some(function (arg) { return ts.isPropertyAccessExpression(arg) && arg.expression === token; }) ? { constructor: constructor, superCall: superCall } : undefined; + } + function findSuperCall(n) { + return ts.isExpressionStatement(n) && ts.isSuperCall(n.expression) + ? n + : ts.isFunctionLike(n) + ? undefined + : ts.forEachChild(n, findSuperCall); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "constructorForDerivedNeedSuperCall"; + var errorCodes = [ts.Diagnostics.Constructors_for_derived_classes_must_contain_a_super_call.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var sourceFile = context.sourceFile, span = context.span; + var ctr = getNode(sourceFile, span.start); + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, ctr); }); + return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Add_missing_super_call, fixId, ts.Diagnostics.Add_all_missing_super_calls)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + return doChange(changes, context.sourceFile, getNode(diag.file, diag.start)); + }); }, + }); + function getNode(sourceFile, pos) { + var token = ts.getTokenAtPosition(sourceFile, pos); + ts.Debug.assert(token.kind === 124 /* ConstructorKeyword */); + return token.parent; + } + function doChange(changes, sourceFile, ctr) { + var superCall = ts.createStatement(ts.createCall(ts.createSuper(), /*typeArguments*/ undefined, /*argumentsArray*/ ts.emptyArray)); + changes.insertNodeAtConstructorStart(sourceFile, ctr, superCall); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "extendsInterfaceBecomesImplements"; + var errorCodes = [ts.Diagnostics.Cannot_extend_an_interface_0_Did_you_mean_implements.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var sourceFile = context.sourceFile; + var nodes = getNodes(sourceFile, context.span.start); + if (!nodes) + return undefined; + var extendsToken = nodes.extendsToken, heritageClauses = nodes.heritageClauses; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChanges(t, sourceFile, extendsToken, heritageClauses); }); + return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Change_extends_to_implements, fixId, ts.Diagnostics.Change_all_extended_interfaces_to_implements)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var nodes = getNodes(diag.file, diag.start); + if (nodes) + doChanges(changes, diag.file, nodes.extendsToken, nodes.heritageClauses); + }); }, + }); + function getNodes(sourceFile, pos) { + var token = ts.getTokenAtPosition(sourceFile, pos); + var heritageClauses = ts.getContainingClass(token).heritageClauses; + var extendsToken = heritageClauses[0].getFirstToken(); + return extendsToken.kind === 86 /* ExtendsKeyword */ ? { extendsToken: extendsToken, heritageClauses: heritageClauses } : undefined; + } + function doChanges(changes, sourceFile, extendsToken, heritageClauses) { + changes.replaceNode(sourceFile, extendsToken, ts.createToken(109 /* ImplementsKeyword */)); + // If there is already an implements clause, replace the implements keyword with a comma. + if (heritageClauses.length === 2 && + heritageClauses[0].token === 86 /* ExtendsKeyword */ && + heritageClauses[1].token === 109 /* ImplementsKeyword */) { + var implementsToken = heritageClauses[1].getFirstToken(); + var implementsFullStart = implementsToken.getFullStart(); + changes.replaceRange(sourceFile, { pos: implementsFullStart, end: implementsFullStart }, ts.createToken(27 /* CommaToken */)); + // Rough heuristic: delete trailing whitespace after keyword so that it's not excessive. + // (Trailing because leading might be indentation, which is more sensitive.) + var text = sourceFile.text; + var end = implementsToken.end; + while (end < text.length && ts.isWhiteSpaceSingleLine(text.charCodeAt(end))) { + end++; + } + changes.deleteRange(sourceFile, { pos: implementsToken.getStart(), end: end }); + } + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "forgottenThisPropertyAccess"; + var didYouMeanStaticMemberCode = ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_static_member_1_0.code; + var errorCodes = [ + ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0.code, + didYouMeanStaticMemberCode, + ]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var sourceFile = context.sourceFile; + var info = getInfo(sourceFile, context.span.start, context.errorCode); + if (!info) { + return undefined; + } + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, info); }); + return [codefix.createCodeFixAction(fixId, changes, [ts.Diagnostics.Add_0_to_unresolved_variable, info.className || "this"], fixId, ts.Diagnostics.Add_qualifier_to_all_unresolved_variables_matching_a_member_name)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var info = getInfo(diag.file, diag.start, diag.code); + if (info) + doChange(changes, context.sourceFile, info); + }); }, + }); + function getInfo(sourceFile, pos, diagCode) { + var node = ts.getTokenAtPosition(sourceFile, pos); + if (!ts.isIdentifier(node)) + return undefined; + return { node: node, className: diagCode === didYouMeanStaticMemberCode ? ts.getContainingClass(node).name.text : undefined }; + } + function doChange(changes, sourceFile, _a) { + var node = _a.node, className = _a.className; + // TODO (https://github.com/Microsoft/TypeScript/issues/21246): use shared helper + ts.suppressLeadingAndTrailingTrivia(node); + changes.replaceNode(sourceFile, node, ts.createPropertyAccess(className ? ts.createIdentifier(className) : ts.createThis(), node)); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixName = "unusedIdentifier"; + var fixIdPrefix = "unusedIdentifier_prefix"; + var fixIdDelete = "unusedIdentifier_delete"; + var fixIdInfer = "unusedIdentifier_infer"; + var errorCodes = [ + ts.Diagnostics._0_is_declared_but_its_value_is_never_read.code, + ts.Diagnostics._0_is_declared_but_never_used.code, + ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read.code, + ts.Diagnostics.All_imports_in_import_declaration_are_unused.code, + ts.Diagnostics.All_destructured_elements_are_unused.code, + ts.Diagnostics.All_variables_are_unused.code, + ts.Diagnostics.All_type_parameters_are_unused.code, + ]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var errorCode = context.errorCode, sourceFile = context.sourceFile, program = context.program; + var checker = program.getTypeChecker(); + var sourceFiles = program.getSourceFiles(); + var token = ts.getTokenAtPosition(sourceFile, context.span.start); + if (ts.isJSDocTemplateTag(token)) { + return [createDeleteFix(ts.textChanges.ChangeTracker.with(context, function (t) { return t.delete(sourceFile, token); }), ts.Diagnostics.Remove_template_tag)]; + } + if (token.kind === 28 /* LessThanToken */) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return deleteTypeParameters(t, sourceFile, token); }); + return [createDeleteFix(changes, ts.Diagnostics.Remove_type_parameters)]; + } + var importDecl = tryGetFullImport(token); + if (importDecl) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.delete(sourceFile, importDecl); }); + return [createDeleteFix(changes, [ts.Diagnostics.Remove_import_from_0, ts.showModuleSpecifier(importDecl)])]; + } + var delDestructure = ts.textChanges.ChangeTracker.with(context, function (t) { + return tryDeleteFullDestructure(token, t, sourceFile, checker, sourceFiles, /*isFixAll*/ false); + }); + if (delDestructure.length) { + return [createDeleteFix(delDestructure, ts.Diagnostics.Remove_destructuring)]; + } + var delVar = ts.textChanges.ChangeTracker.with(context, function (t) { return tryDeleteFullVariableStatement(sourceFile, token, t); }); + if (delVar.length) { + return [createDeleteFix(delVar, ts.Diagnostics.Remove_variable_statement)]; + } + var result = []; + if (token.kind === 127 /* InferKeyword */) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return changeInferToUnknown(t, sourceFile, token); }); + var name = ts.cast(token.parent, ts.isInferTypeNode).typeParameter.name.text; + result.push(codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Replace_infer_0_with_unknown, name], fixIdInfer, ts.Diagnostics.Replace_all_unused_infer_with_unknown)); + } + else { + var deletion = ts.textChanges.ChangeTracker.with(context, function (t) { + return tryDeleteDeclaration(sourceFile, token, t, checker, sourceFiles, /*isFixAll*/ false); + }); + if (deletion.length) { + var name = ts.isComputedPropertyName(token.parent) ? token.parent : token; + result.push(createDeleteFix(deletion, [ts.Diagnostics.Remove_declaration_for_Colon_0, name.getText(sourceFile)])); + } + } + var prefix = ts.textChanges.ChangeTracker.with(context, function (t) { return tryPrefixDeclaration(t, errorCode, sourceFile, token); }); + if (prefix.length) { + result.push(codefix.createCodeFixAction(fixName, prefix, [ts.Diagnostics.Prefix_0_with_an_underscore, token.getText(sourceFile)], fixIdPrefix, ts.Diagnostics.Prefix_all_unused_declarations_with_where_possible)); + } + return result; + }, + fixIds: [fixIdPrefix, fixIdDelete, fixIdInfer], + getAllCodeActions: function (context) { + var sourceFile = context.sourceFile, program = context.program; + var checker = program.getTypeChecker(); + var sourceFiles = program.getSourceFiles(); + return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var token = ts.getTokenAtPosition(sourceFile, diag.start); + switch (context.fixId) { + case fixIdPrefix: + tryPrefixDeclaration(changes, diag.code, sourceFile, token); + break; + case fixIdDelete: { + if (token.kind === 127 /* InferKeyword */) + break; // Can't delete + var importDecl = tryGetFullImport(token); + if (importDecl) { + changes.delete(sourceFile, importDecl); + } + else if (ts.isJSDocTemplateTag(token)) { + changes.delete(sourceFile, token); + } + else if (token.kind === 28 /* LessThanToken */) { + deleteTypeParameters(changes, sourceFile, token); + } + else if (!tryDeleteFullDestructure(token, changes, sourceFile, checker, sourceFiles, /*isFixAll*/ true) && + !tryDeleteFullVariableStatement(sourceFile, token, changes)) { + tryDeleteDeclaration(sourceFile, token, changes, checker, sourceFiles, /*isFixAll*/ true); + } + break; + } + case fixIdInfer: + if (token.kind === 127 /* InferKeyword */) { + changeInferToUnknown(changes, sourceFile, token); + } + break; + default: + ts.Debug.fail(JSON.stringify(context.fixId)); + } + }); + }, + }); + function changeInferToUnknown(changes, sourceFile, token) { + changes.replaceNode(sourceFile, token.parent, ts.createKeywordTypeNode(143 /* UnknownKeyword */)); + } + function createDeleteFix(changes, diag) { + return codefix.createCodeFixAction(fixName, changes, diag, fixIdDelete, ts.Diagnostics.Delete_all_unused_declarations); + } + function deleteTypeParameters(changes, sourceFile, token) { + changes.delete(sourceFile, ts.Debug.assertDefined(ts.cast(token.parent, ts.isDeclarationWithTypeParameterChildren).typeParameters)); + } + // Sometimes the diagnostic span is an entire ImportDeclaration, so we should remove the whole thing. + function tryGetFullImport(token) { + return token.kind === 92 /* ImportKeyword */ ? ts.tryCast(token.parent, ts.isImportDeclaration) : undefined; + } + function tryDeleteFullDestructure(token, changes, sourceFile, checker, sourceFiles, isFixAll) { + if (token.kind !== 18 /* OpenBraceToken */ || !ts.isObjectBindingPattern(token.parent)) + return false; + var decl = token.parent.parent; + if (decl.kind === 151 /* Parameter */) { + tryDeleteParameter(changes, sourceFile, decl, checker, sourceFiles, isFixAll); + } + else { + changes.delete(sourceFile, decl); + } + return true; + } + function tryDeleteFullVariableStatement(sourceFile, token, changes) { + var declarationList = ts.tryCast(token.parent, ts.isVariableDeclarationList); + if (declarationList && declarationList.getChildren(sourceFile)[0] === token) { + changes.delete(sourceFile, declarationList.parent.kind === 219 /* VariableStatement */ ? declarationList.parent : declarationList); + return true; + } + return false; + } + function tryPrefixDeclaration(changes, errorCode, sourceFile, token) { + // Don't offer to prefix a property. + if (errorCode === ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read.code) + return; + if (token.kind === 127 /* InferKeyword */) { + token = ts.cast(token.parent, ts.isInferTypeNode).typeParameter.name; + } + if (ts.isIdentifier(token) && canPrefix(token)) { + changes.replaceNode(sourceFile, token, ts.createIdentifier("_" + token.text)); + } + } + function canPrefix(token) { + switch (token.parent.kind) { + case 151 /* Parameter */: + case 150 /* TypeParameter */: + return true; + case 237 /* VariableDeclaration */: { + var varDecl = token.parent; + switch (varDecl.parent.parent.kind) { + case 227 /* ForOfStatement */: + case 226 /* ForInStatement */: + return true; + } + } + } + return false; + } + function tryDeleteDeclaration(sourceFile, token, changes, checker, sourceFiles, isFixAll) { + tryDeleteDeclarationWorker(token, changes, sourceFile, checker, sourceFiles, isFixAll); + if (ts.isIdentifier(token)) + deleteAssignments(changes, sourceFile, token, checker); + } + function deleteAssignments(changes, sourceFile, token, checker) { + ts.FindAllReferences.Core.eachSymbolReferenceInFile(token, checker, sourceFile, function (ref) { + if (ts.isPropertyAccessExpression(ref.parent) && ref.parent.name === ref) + ref = ref.parent; + if (ts.isBinaryExpression(ref.parent) && ts.isExpressionStatement(ref.parent.parent) && ref.parent.left === ref) { + changes.delete(sourceFile, ref.parent.parent); + } + }); + } + function tryDeleteDeclarationWorker(token, changes, sourceFile, checker, sourceFiles, isFixAll) { + var parent = token.parent; + if (ts.isParameter(parent)) { + tryDeleteParameter(changes, sourceFile, parent, checker, sourceFiles, isFixAll); + } + else { + changes.delete(sourceFile, ts.isImportClause(parent) ? token : ts.isComputedPropertyName(parent) ? parent.parent : parent); + } + } + function tryDeleteParameter(changes, sourceFile, p, checker, sourceFiles, isFixAll) { + if (mayDeleteParameter(p, checker, isFixAll)) { + if (p.modifiers && p.modifiers.length > 0 + && (!ts.isIdentifier(p.name) || ts.FindAllReferences.Core.isSymbolReferencedInFile(p.name, checker, sourceFile))) { + p.modifiers.forEach(function (modifier) { + changes.deleteModifier(sourceFile, modifier); + }); + } + else { + changes.delete(sourceFile, p); + deleteUnusedArguments(changes, sourceFile, p, sourceFiles, checker); + } + } + } + function mayDeleteParameter(p, checker, isFixAll) { + var parent = p.parent; + switch (parent.kind) { + case 156 /* MethodDeclaration */: + // Don't remove a parameter if this overrides something. + var symbol = checker.getSymbolAtLocation(parent.name); + if (ts.isMemberSymbolInBaseType(symbol, checker)) + return false; + // falls through + case 157 /* Constructor */: + case 239 /* FunctionDeclaration */: + return true; + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: { + // Can't remove a non-last parameter in a callback. Can remove a parameter in code-fix-all if future parameters are also unused. + var parameters = parent.parameters; + var index = parameters.indexOf(p); + ts.Debug.assert(index !== -1); + return isFixAll + ? parameters.slice(index + 1).every(function (p) { return p.name.kind === 72 /* Identifier */ && !p.symbol.isReferenced; }) + : index === parameters.length - 1; + } + case 159 /* SetAccessor */: + // Setter must have a parameter + return false; + default: + return ts.Debug.failBadSyntaxKind(parent); + } + } + function deleteUnusedArguments(changes, sourceFile, deletedParameter, sourceFiles, checker) { + ts.FindAllReferences.Core.eachSignatureCall(deletedParameter.parent, sourceFiles, checker, function (call) { + var index = deletedParameter.parent.parameters.indexOf(deletedParameter); + if (call.arguments.length > index) { // Just in case the call didn't provide enough arguments. + changes.delete(sourceFile, call.arguments[index]); + } + }); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "fixUnreachableCode"; + var errorCodes = [ts.Diagnostics.Unreachable_code_detected.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, context.sourceFile, context.span.start, context.span.length); }); + return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Remove_unreachable_code, fixId, ts.Diagnostics.Remove_all_unreachable_code)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { return doChange(changes, diag.file, diag.start, diag.length); }); }, + }); + function doChange(changes, sourceFile, start, length) { + var token = ts.getTokenAtPosition(sourceFile, start); + var statement = ts.findAncestor(token, ts.isStatement); + ts.Debug.assert(statement.getStart(sourceFile) === token.getStart(sourceFile)); + var container = (ts.isBlock(statement.parent) ? statement.parent : statement).parent; + if (!ts.isBlock(statement.parent) || statement === ts.first(statement.parent.statements)) { + switch (container.kind) { + case 222 /* IfStatement */: + if (container.elseStatement) { + if (ts.isBlock(statement.parent)) { + break; + } + else { + changes.replaceNode(sourceFile, statement, ts.createBlock(ts.emptyArray)); + } + return; + } + // falls through + case 224 /* WhileStatement */: + case 225 /* ForStatement */: + changes.delete(sourceFile, container); + return; + } + } + if (ts.isBlock(statement.parent)) { + var end_2 = start + length; + var lastStatement = ts.Debug.assertDefined(lastWhere(ts.sliceAfter(statement.parent.statements, statement), function (s) { return s.pos < end_2; })); + changes.deleteNodeRange(sourceFile, statement, lastStatement); + } + else { + changes.delete(sourceFile, statement); + } + } + function lastWhere(a, pred) { + var last; + for (var _i = 0, a_1 = a; _i < a_1.length; _i++) { + var value = a_1[_i]; + if (!pred(value)) + break; + last = value; + } + return last; + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "fixUnusedLabel"; + var errorCodes = [ts.Diagnostics.Unused_label.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, context.sourceFile, context.span.start); }); + return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Remove_unused_label, fixId, ts.Diagnostics.Remove_all_unused_labels)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { return doChange(changes, diag.file, diag.start); }); }, + }); + function doChange(changes, sourceFile, start) { + var token = ts.getTokenAtPosition(sourceFile, start); + var labeledStatement = ts.cast(token.parent, ts.isLabeledStatement); + var pos = token.getStart(sourceFile); + var statementPos = labeledStatement.statement.getStart(sourceFile); + // If label is on a separate line, just delete the rest of that line, but not the indentation of the labeled statement. + var end = ts.positionsAreOnSameLine(pos, statementPos, sourceFile) ? statementPos + : ts.skipTrivia(sourceFile.text, ts.findChildOfKind(labeledStatement, 57 /* ColonToken */, sourceFile).end, /*stopAfterLineBreak*/ true); + changes.deleteRange(sourceFile, { pos: pos, end: end }); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixIdPlain = "fixJSDocTypes_plain"; + var fixIdNullable = "fixJSDocTypes_nullable"; + var errorCodes = [ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var sourceFile = context.sourceFile; + var checker = context.program.getTypeChecker(); + var info = getInfo(sourceFile, context.span.start, checker); + if (!info) + return undefined; + var typeNode = info.typeNode, type = info.type; + var original = typeNode.getText(sourceFile); + var actions = [fix(type, fixIdPlain, ts.Diagnostics.Change_all_jsdoc_style_types_to_TypeScript)]; + if (typeNode.kind === 286 /* JSDocNullableType */) { + // for nullable types, suggest the flow-compatible `T | null | undefined` + // in addition to the jsdoc/closure-compatible `T | null` + actions.push(fix(checker.getNullableType(type, 32768 /* Undefined */), fixIdNullable, ts.Diagnostics.Change_all_jsdoc_style_types_to_TypeScript_and_add_undefined_to_nullable_types)); + } + return actions; + function fix(type, fixId, fixAllDescription) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, typeNode, type, checker); }); + return codefix.createCodeFixAction("jdocTypes", changes, [ts.Diagnostics.Change_0_to_1, original, checker.typeToString(type)], fixId, fixAllDescription); + } + }, + fixIds: [fixIdPlain, fixIdNullable], + getAllCodeActions: function (context) { + var fixId = context.fixId, program = context.program, sourceFile = context.sourceFile; + var checker = program.getTypeChecker(); + return codefix.codeFixAll(context, errorCodes, function (changes, err) { + var info = getInfo(err.file, err.start, checker); + if (!info) + return; + var typeNode = info.typeNode, type = info.type; + var fixedType = typeNode.kind === 286 /* JSDocNullableType */ && fixId === fixIdNullable ? checker.getNullableType(type, 32768 /* Undefined */) : type; + doChange(changes, sourceFile, typeNode, fixedType, checker); + }); + } + }); + function doChange(changes, sourceFile, oldTypeNode, newType, checker) { + changes.replaceNode(sourceFile, oldTypeNode, checker.typeToTypeNode(newType, /*enclosingDeclaration*/ oldTypeNode)); // TODO: GH#18217 + } + function getInfo(sourceFile, pos, checker) { + var decl = ts.findAncestor(ts.getTokenAtPosition(sourceFile, pos), isTypeContainer); + var typeNode = decl && decl.type; + return typeNode && { typeNode: typeNode, type: checker.getTypeFromTypeNode(typeNode) }; + } + function isTypeContainer(node) { + // NOTE: Some locations are not handled yet: + // MappedTypeNode.typeParameters and SignatureDeclaration.typeParameters, as well as CallExpression.typeArguments + switch (node.kind) { + case 212 /* AsExpression */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 239 /* FunctionDeclaration */: + case 158 /* GetAccessor */: + case 162 /* IndexSignature */: + case 181 /* MappedType */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 151 /* Parameter */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 159 /* SetAccessor */: + case 242 /* TypeAliasDeclaration */: + case 194 /* TypeAssertionExpression */: + case 237 /* VariableDeclaration */: + return true; + default: + return false; + } + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "fixAwaitInSyncFunction"; + var errorCodes = [ + ts.Diagnostics.await_expression_is_only_allowed_within_an_async_function.code, + ts.Diagnostics.A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator.code, + ]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var sourceFile = context.sourceFile, span = context.span; + var nodes = getNodes(sourceFile, span.start); + if (!nodes) + return undefined; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, nodes); }); + return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Add_async_modifier_to_containing_function, fixId, ts.Diagnostics.Add_all_missing_async_modifiers)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var nodes = getNodes(diag.file, diag.start); + if (!nodes) + return; + doChange(changes, context.sourceFile, nodes); + }); }, + }); + function getReturnType(expr) { + if (expr.type) { + return expr.type; + } + if (ts.isVariableDeclaration(expr.parent) && + expr.parent.type && + ts.isFunctionTypeNode(expr.parent.type)) { + return expr.parent.type.type; + } + } + function getNodes(sourceFile, start) { + var token = ts.getTokenAtPosition(sourceFile, start); + var containingFunction = ts.getContainingFunction(token); + if (!containingFunction) { + return; + } + var insertBefore; + switch (containingFunction.kind) { + case 156 /* MethodDeclaration */: + insertBefore = containingFunction.name; + break; + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + insertBefore = ts.findChildOfKind(containingFunction, 90 /* FunctionKeyword */, sourceFile); + break; + case 197 /* ArrowFunction */: + insertBefore = ts.findChildOfKind(containingFunction, 20 /* OpenParenToken */, sourceFile) || ts.first(containingFunction.parameters); + break; + default: + return; + } + return insertBefore && { + insertBefore: insertBefore, + returnType: getReturnType(containingFunction) + }; + } + function doChange(changes, sourceFile, _a) { + var insertBefore = _a.insertBefore, returnType = _a.returnType; + if (returnType) { + var entityName = ts.getEntityNameFromTypeNode(returnType); + if (!entityName || entityName.kind !== 72 /* Identifier */ || entityName.text !== "Promise") { + changes.replaceNode(sourceFile, returnType, ts.createTypeReferenceNode("Promise", ts.createNodeArray([returnType]))); + } + } + changes.insertModifierBefore(sourceFile, 121 /* AsyncKeyword */, insertBefore); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixName = "disableJsDiagnostics"; + var fixId = "disableJsDiagnostics"; + var errorCodes = ts.mapDefined(Object.keys(ts.Diagnostics), function (key) { + var diag = ts.Diagnostics[key]; + return diag.category === ts.DiagnosticCategory.Error ? diag.code : undefined; + }); + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var sourceFile = context.sourceFile, program = context.program, span = context.span, host = context.host, formatContext = context.formatContext; + if (!ts.isInJSFile(sourceFile) || !ts.isCheckJsEnabledForFile(sourceFile, program.getCompilerOptions())) { + return undefined; + } + var fixes = [ + // fixId unnecessary because adding `// @ts-nocheck` even once will ignore every error in the file. + codefix.createCodeFixActionNoFixId(fixName, [codefix.createFileTextChanges(sourceFile.fileName, [ + ts.createTextChange(sourceFile.checkJsDirective + ? ts.createTextSpanFromBounds(sourceFile.checkJsDirective.pos, sourceFile.checkJsDirective.end) + : ts.createTextSpan(0, 0), "// @ts-nocheck" + ts.getNewLineOrDefaultFromHost(host, formatContext.options)), + ])], ts.Diagnostics.Disable_checking_for_this_file), + ]; + if (ts.textChanges.isValidLocationToAddComment(sourceFile, span.start)) { + fixes.unshift(codefix.createCodeFixAction(fixName, ts.textChanges.ChangeTracker.with(context, function (t) { return makeChange(t, sourceFile, span.start); }), ts.Diagnostics.Ignore_this_error_message, fixId, ts.Diagnostics.Add_ts_ignore_to_all_error_messages)); + } + return fixes; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { + var seenLines = ts.createMap(); + return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + if (ts.textChanges.isValidLocationToAddComment(diag.file, diag.start)) { + makeChange(changes, diag.file, diag.start, seenLines); + } + }); + }, + }); + function makeChange(changes, sourceFile, position, seenLines) { + var lineNumber = ts.getLineAndCharacterOfPosition(sourceFile, position).line; + // Only need to add `// @ts-ignore` for a line once. + if (!seenLines || ts.addToSeen(seenLines, lineNumber)) { + changes.insertCommentBeforeLine(sourceFile, lineNumber, position, " @ts-ignore"); + } + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + /** + * Finds members of the resolved type that are missing in the class pointed to by class decl + * and generates source code for the missing members. + * @param possiblyMissingSymbols The collection of symbols to filter and then get insertions for. + * @returns Empty string iff there are no member insertions. + */ + function createMissingMemberNodes(classDeclaration, possiblyMissingSymbols, checker, preferences, out) { + var classMembers = classDeclaration.symbol.members; + for (var _i = 0, possiblyMissingSymbols_1 = possiblyMissingSymbols; _i < possiblyMissingSymbols_1.length; _i++) { + var symbol = possiblyMissingSymbols_1[_i]; + if (!classMembers.has(symbol.escapedName)) { + addNewNodeForMemberSymbol(symbol, classDeclaration, checker, preferences, out); + } + } + } + codefix.createMissingMemberNodes = createMissingMemberNodes; + /** + * @returns Empty string iff there we can't figure out a representation for `symbol` in `enclosingDeclaration`. + */ + function addNewNodeForMemberSymbol(symbol, enclosingDeclaration, checker, preferences, out) { + var declarations = symbol.getDeclarations(); + if (!(declarations && declarations.length)) { + return undefined; + } + var declaration = declarations[0]; + var name = ts.getSynthesizedDeepClone(ts.getNameOfDeclaration(declaration), /*includeTrivia*/ false); + var visibilityModifier = createVisibilityModifier(ts.getModifierFlags(declaration)); + var modifiers = visibilityModifier ? ts.createNodeArray([visibilityModifier]) : undefined; + var type = checker.getWidenedType(checker.getTypeOfSymbolAtLocation(symbol, enclosingDeclaration)); + var optional = !!(symbol.flags & 16777216 /* Optional */); + switch (declaration.kind) { + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 153 /* PropertySignature */: + case 154 /* PropertyDeclaration */: + var typeNode = checker.typeToTypeNode(type, enclosingDeclaration); + out(ts.createProperty( + /*decorators*/ undefined, modifiers, name, optional ? ts.createToken(56 /* QuestionToken */) : undefined, typeNode, + /*initializer*/ undefined)); + break; + case 155 /* MethodSignature */: + case 156 /* MethodDeclaration */: + // The signature for the implementation appears as an entry in `signatures` iff + // there is only one signature. + // If there are overloads and an implementation signature, it appears as an + // extra declaration that isn't a signature for `type`. + // If there is more than one overload but no implementation signature + // (eg: an abstract method or interface declaration), there is a 1-1 + // correspondence of declarations and signatures. + var signatures = checker.getSignaturesOfType(type, 0 /* Call */); + if (!ts.some(signatures)) { + break; + } + if (declarations.length === 1) { + ts.Debug.assert(signatures.length === 1); + var signature = signatures[0]; + outputMethod(signature, modifiers, name, createStubbedMethodBody(preferences)); + break; + } + for (var _i = 0, signatures_7 = signatures; _i < signatures_7.length; _i++) { + var signature = signatures_7[_i]; + // Need to ensure nodes are fresh each time so they can have different positions. + outputMethod(signature, ts.getSynthesizedDeepClones(modifiers, /*includeTrivia*/ false), ts.getSynthesizedDeepClone(name, /*includeTrivia*/ false)); + } + if (declarations.length > signatures.length) { + var signature = checker.getSignatureFromDeclaration(declarations[declarations.length - 1]); + outputMethod(signature, modifiers, name, createStubbedMethodBody(preferences)); + } + else { + ts.Debug.assert(declarations.length === signatures.length); + out(createMethodImplementingSignatures(signatures, name, optional, modifiers, preferences)); + } + break; + } + function outputMethod(signature, modifiers, name, body) { + var method = signatureToMethodDeclaration(checker, signature, enclosingDeclaration, modifiers, name, optional, body); + if (method) + out(method); + } + } + function signatureToMethodDeclaration(checker, signature, enclosingDeclaration, modifiers, name, optional, body) { + var signatureDeclaration = checker.signatureToSignatureDeclaration(signature, 156 /* MethodDeclaration */, enclosingDeclaration, 256 /* SuppressAnyReturnType */); + if (!signatureDeclaration) { + return undefined; + } + signatureDeclaration.decorators = undefined; + signatureDeclaration.modifiers = modifiers; + signatureDeclaration.name = name; + signatureDeclaration.questionToken = optional ? ts.createToken(56 /* QuestionToken */) : undefined; + signatureDeclaration.body = body; + return signatureDeclaration; + } + function createMethodFromCallExpression(context, call, methodName, inJs, makeStatic, preferences, body) { + var typeArguments = call.typeArguments, args = call.arguments, parent = call.parent; + var checker = context.program.getTypeChecker(); + var types = ts.map(args, function (arg) { + // Widen the type so we don't emit nonsense annotations like "function fn(x: 3) {" + return checker.typeToTypeNode(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(arg))); + }); + var names = ts.map(args, function (arg) { + return ts.isIdentifier(arg) ? arg.text : + ts.isPropertyAccessExpression(arg) ? arg.name.text : undefined; + }); + var contextualType = checker.getContextualType(call); + var returnType = inJs ? undefined : contextualType && checker.typeToTypeNode(contextualType, call) || ts.createKeywordTypeNode(120 /* AnyKeyword */); + return ts.createMethod( + /*decorators*/ undefined, + /*modifiers*/ makeStatic ? [ts.createToken(116 /* StaticKeyword */)] : undefined, + /*asteriskToken*/ ts.isYieldExpression(parent) ? ts.createToken(40 /* AsteriskToken */) : undefined, methodName, + /*questionToken*/ undefined, + /*typeParameters*/ inJs ? undefined : ts.map(typeArguments, function (_, i) { + return ts.createTypeParameterDeclaration(84 /* T */ + typeArguments.length - 1 <= 90 /* Z */ ? String.fromCharCode(84 /* T */ + i) : "T" + i); + }), + /*parameters*/ createDummyParameters(args.length, names, types, /*minArgumentCount*/ undefined, inJs), + /*type*/ returnType, body ? createStubbedMethodBody(preferences) : undefined); + } + codefix.createMethodFromCallExpression = createMethodFromCallExpression; + function createDummyParameters(argCount, names, types, minArgumentCount, inJs) { + var parameters = []; + for (var i = 0; i < argCount; i++) { + var newParameter = ts.createParameter( + /*decorators*/ undefined, + /*modifiers*/ undefined, + /*dotDotDotToken*/ undefined, + /*name*/ names && names[i] || "arg" + i, + /*questionToken*/ minArgumentCount !== undefined && i >= minArgumentCount ? ts.createToken(56 /* QuestionToken */) : undefined, + /*type*/ inJs ? undefined : types && types[i] || ts.createKeywordTypeNode(120 /* AnyKeyword */), + /*initializer*/ undefined); + parameters.push(newParameter); + } + return parameters; + } + function createMethodImplementingSignatures(signatures, name, optional, modifiers, preferences) { + /** This is *a* signature with the maximal number of arguments, + * such that if there is a "maximal" signature without rest arguments, + * this is one of them. + */ + var maxArgsSignature = signatures[0]; + var minArgumentCount = signatures[0].minArgumentCount; + var someSigHasRestParameter = false; + for (var _i = 0, signatures_8 = signatures; _i < signatures_8.length; _i++) { + var sig = signatures_8[_i]; + minArgumentCount = Math.min(sig.minArgumentCount, minArgumentCount); + if (sig.hasRestParameter) { + someSigHasRestParameter = true; + } + if (sig.parameters.length >= maxArgsSignature.parameters.length && (!sig.hasRestParameter || maxArgsSignature.hasRestParameter)) { + maxArgsSignature = sig; + } + } + var maxNonRestArgs = maxArgsSignature.parameters.length - (maxArgsSignature.hasRestParameter ? 1 : 0); + var maxArgsParameterSymbolNames = maxArgsSignature.parameters.map(function (symbol) { return symbol.name; }); + var parameters = createDummyParameters(maxNonRestArgs, maxArgsParameterSymbolNames, /* types */ undefined, minArgumentCount, /*inJs*/ false); + if (someSigHasRestParameter) { + var anyArrayType = ts.createArrayTypeNode(ts.createKeywordTypeNode(120 /* AnyKeyword */)); + var restParameter = ts.createParameter( + /*decorators*/ undefined, + /*modifiers*/ undefined, ts.createToken(25 /* DotDotDotToken */), maxArgsParameterSymbolNames[maxNonRestArgs] || "rest", + /*questionToken*/ maxNonRestArgs >= minArgumentCount ? ts.createToken(56 /* QuestionToken */) : undefined, anyArrayType, + /*initializer*/ undefined); + parameters.push(restParameter); + } + return createStubbedMethod(modifiers, name, optional, + /*typeParameters*/ undefined, parameters, + /*returnType*/ undefined, preferences); + } + function createStubbedMethod(modifiers, name, optional, typeParameters, parameters, returnType, preferences) { + return ts.createMethod( + /*decorators*/ undefined, modifiers, + /*asteriskToken*/ undefined, name, optional ? ts.createToken(56 /* QuestionToken */) : undefined, typeParameters, parameters, returnType, createStubbedMethodBody(preferences)); + } + function createStubbedMethodBody(preferences) { + return ts.createBlock([ts.createThrow(ts.createNew(ts.createIdentifier("Error"), + /*typeArguments*/ undefined, [ts.createLiteral("Method not implemented.", /*isSingleQuote*/ preferences.quotePreference === "single")]))], + /*multiline*/ true); + } + function createVisibilityModifier(flags) { + if (flags & 4 /* Public */) { + return ts.createToken(115 /* PublicKeyword */); + } + else if (flags & 16 /* Protected */) { + return ts.createToken(114 /* ProtectedKeyword */); + } + return undefined; + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixName = "invalidImportSyntax"; + function getCodeFixesForImportDeclaration(context, node) { + var sourceFile = ts.getSourceFileOfNode(node); + var namespace = ts.getNamespaceDeclarationNode(node); + var opts = context.program.getCompilerOptions(); + var variations = []; + // import Bluebird from "bluebird"; + variations.push(createAction(context, sourceFile, node, ts.makeImport(namespace.name, /*namedImports*/ undefined, node.moduleSpecifier, ts.getQuotePreference(sourceFile, context.preferences)))); + if (ts.getEmitModuleKind(opts) === ts.ModuleKind.CommonJS) { + // import Bluebird = require("bluebird"); + variations.push(createAction(context, sourceFile, node, ts.createImportEqualsDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, namespace.name, ts.createExternalModuleReference(node.moduleSpecifier)))); + } + return variations; + } + function createAction(context, sourceFile, node, replacement) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.replaceNode(sourceFile, node, replacement); }); + return codefix.createCodeFixActionNoFixId(fixName, changes, [ts.Diagnostics.Replace_import_with_0, changes[0].textChanges[0].newText]); + } + codefix.registerCodeFix({ + errorCodes: [ + ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures.code, + ts.Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature.code, + ], + getCodeActions: getActionsForUsageOfInvalidImport + }); + function getActionsForUsageOfInvalidImport(context) { + var sourceFile = context.sourceFile; + var targetKind = ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures.code === context.errorCode ? 191 /* CallExpression */ : 192 /* NewExpression */; + var node = ts.findAncestor(ts.getTokenAtPosition(sourceFile, context.span.start), function (a) { return a.kind === targetKind && a.getStart() === context.span.start && a.getEnd() === (context.span.start + context.span.length); }); + if (!node) { + return []; + } + var expr = node.expression; + return getImportCodeFixesForExpression(context, expr); + } + codefix.registerCodeFix({ + errorCodes: [ + // The following error codes cover pretty much all assignability errors that could involve an expression + ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1.code, + ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1.code, + ts.Diagnostics.Type_0_is_not_assignable_to_type_1.code, + ts.Diagnostics.Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated.code, + ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1.code, + ts.Diagnostics.Property_0_of_type_1_is_not_assignable_to_string_index_type_2.code, + ts.Diagnostics.Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2.code, + ts.Diagnostics.Numeric_index_type_0_is_not_assignable_to_string_index_type_1.code, + ts.Diagnostics.Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2.code, + ts.Diagnostics.Property_0_in_type_1_is_not_assignable_to_type_2.code, + ts.Diagnostics.Property_0_of_JSX_spread_attribute_is_not_assignable_to_target_property.code, + ts.Diagnostics.The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1.code, + ], + getCodeActions: getActionsForInvalidImportLocation + }); + function getActionsForInvalidImportLocation(context) { + var sourceFile = context.sourceFile; + var node = ts.findAncestor(ts.getTokenAtPosition(sourceFile, context.span.start), function (a) { return a.getStart() === context.span.start && a.getEnd() === (context.span.start + context.span.length); }); + if (!node) { + return []; + } + return getImportCodeFixesForExpression(context, node); + } + function getImportCodeFixesForExpression(context, expr) { + var type = context.program.getTypeChecker().getTypeAtLocation(expr); + if (!(type.symbol && type.symbol.originatingImport)) { + return []; + } + var fixes = []; + var relatedImport = type.symbol.originatingImport; // TODO: GH#18217 + if (!ts.isImportCall(relatedImport)) { + ts.addRange(fixes, getCodeFixesForImportDeclaration(context, relatedImport)); + } + if (ts.isExpression(expr) && !(ts.isNamedDeclaration(expr.parent) && expr.parent.name === expr)) { + var sourceFile_3 = context.sourceFile; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.replaceNode(sourceFile_3, expr, ts.createPropertyAccess(expr, "default"), {}); }); + fixes.push(codefix.createCodeFixActionNoFixId(fixName, changes, ts.Diagnostics.Use_synthetic_default_member)); + } + return fixes; + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixName = "strictClassInitialization"; + var fixIdAddDefiniteAssignmentAssertions = "addMissingPropertyDefiniteAssignmentAssertions"; + var fixIdAddUndefinedType = "addMissingPropertyUndefinedType"; + var fixIdAddInitializer = "addMissingPropertyInitializer"; + var errorCodes = [ts.Diagnostics.Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var propertyDeclaration = getPropertyDeclaration(context.sourceFile, context.span.start); + if (!propertyDeclaration) + return; + var result = [ + getActionForAddMissingUndefinedType(context, propertyDeclaration), + getActionForAddMissingDefiniteAssignmentAssertion(context, propertyDeclaration) + ]; + ts.append(result, getActionForAddMissingInitializer(context, propertyDeclaration)); + return result; + }, + fixIds: [fixIdAddDefiniteAssignmentAssertions, fixIdAddUndefinedType, fixIdAddInitializer], + getAllCodeActions: function (context) { + return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var propertyDeclaration = getPropertyDeclaration(diag.file, diag.start); + if (!propertyDeclaration) + return; + switch (context.fixId) { + case fixIdAddDefiniteAssignmentAssertions: + addDefiniteAssignmentAssertion(changes, diag.file, propertyDeclaration); + break; + case fixIdAddUndefinedType: + addUndefinedType(changes, diag.file, propertyDeclaration); + break; + case fixIdAddInitializer: + var checker = context.program.getTypeChecker(); + var initializer = getInitializer(checker, propertyDeclaration); + if (!initializer) + return; + addInitializer(changes, diag.file, propertyDeclaration, initializer); + break; + default: + ts.Debug.fail(JSON.stringify(context.fixId)); + } + }); + }, + }); + function getPropertyDeclaration(sourceFile, pos) { + var token = ts.getTokenAtPosition(sourceFile, pos); + return ts.isIdentifier(token) ? ts.cast(token.parent, ts.isPropertyDeclaration) : undefined; + } + function getActionForAddMissingDefiniteAssignmentAssertion(context, propertyDeclaration) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addDefiniteAssignmentAssertion(t, context.sourceFile, propertyDeclaration); }); + return codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Add_definite_assignment_assertion_to_property_0, propertyDeclaration.getText()], fixIdAddDefiniteAssignmentAssertions, ts.Diagnostics.Add_definite_assignment_assertions_to_all_uninitialized_properties); + } + function addDefiniteAssignmentAssertion(changeTracker, propertyDeclarationSourceFile, propertyDeclaration) { + var property = ts.updateProperty(propertyDeclaration, propertyDeclaration.decorators, propertyDeclaration.modifiers, propertyDeclaration.name, ts.createToken(52 /* ExclamationToken */), propertyDeclaration.type, propertyDeclaration.initializer); + changeTracker.replaceNode(propertyDeclarationSourceFile, propertyDeclaration, property); + } + function getActionForAddMissingUndefinedType(context, propertyDeclaration) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addUndefinedType(t, context.sourceFile, propertyDeclaration); }); + return codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Add_undefined_type_to_property_0, propertyDeclaration.name.getText()], fixIdAddUndefinedType, ts.Diagnostics.Add_undefined_type_to_all_uninitialized_properties); + } + function addUndefinedType(changeTracker, propertyDeclarationSourceFile, propertyDeclaration) { + var undefinedTypeNode = ts.createKeywordTypeNode(141 /* UndefinedKeyword */); + var type = propertyDeclaration.type; // TODO: GH#18217 + var types = ts.isUnionTypeNode(type) ? type.types.concat(undefinedTypeNode) : [type, undefinedTypeNode]; + changeTracker.replaceNode(propertyDeclarationSourceFile, type, ts.createUnionTypeNode(types)); + } + function getActionForAddMissingInitializer(context, propertyDeclaration) { + var checker = context.program.getTypeChecker(); + var initializer = getInitializer(checker, propertyDeclaration); + if (!initializer) + return undefined; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addInitializer(t, context.sourceFile, propertyDeclaration, initializer); }); + return codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Add_initializer_to_property_0, propertyDeclaration.name.getText()], fixIdAddInitializer, ts.Diagnostics.Add_initializers_to_all_uninitialized_properties); + } + function addInitializer(changeTracker, propertyDeclarationSourceFile, propertyDeclaration, initializer) { + var property = ts.updateProperty(propertyDeclaration, propertyDeclaration.decorators, propertyDeclaration.modifiers, propertyDeclaration.name, propertyDeclaration.questionToken, propertyDeclaration.type, initializer); + changeTracker.replaceNode(propertyDeclarationSourceFile, propertyDeclaration, property); + } + function getInitializer(checker, propertyDeclaration) { + return getDefaultValueFromType(checker, checker.getTypeFromTypeNode(propertyDeclaration.type)); // TODO: GH#18217 + } + function getDefaultValueFromType(checker, type) { + if (type.flags & 512 /* BooleanLiteral */) { + return (type === checker.getFalseType() || type === checker.getFalseType(/*fresh*/ true)) ? ts.createFalse() : ts.createTrue(); + } + else if (type.isLiteral()) { + return ts.createLiteral(type.value); + } + else if (type.isUnion()) { + return ts.firstDefined(type.types, function (t) { return getDefaultValueFromType(checker, t); }); + } + else if (type.isClass()) { + var classDeclaration = ts.getClassLikeDeclarationOfSymbol(type.symbol); + if (!classDeclaration || ts.hasModifier(classDeclaration, 128 /* Abstract */)) + return undefined; + var constructorDeclaration = ts.getFirstConstructorWithBody(classDeclaration); + if (constructorDeclaration && constructorDeclaration.parameters.length) + return undefined; + return ts.createNew(ts.createIdentifier(type.symbol.name), /*typeArguments*/ undefined, /*argumentsArray*/ undefined); + } + else if (checker.isArrayLikeType(type)) { + return ts.createArrayLiteral(); + } + return undefined; + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + function generateTypesForModule(name, moduleValue, formatSettings) { + return generateTypesForModuleOrGlobal(name, moduleValue, formatSettings, 0 /* ExportEquals */); + } + ts.generateTypesForModule = generateTypesForModule; + function generateTypesForGlobal(name, globalValue, formatSettings) { + return generateTypesForModuleOrGlobal(name, globalValue, formatSettings, 3 /* Global */); + } + ts.generateTypesForGlobal = generateTypesForGlobal; + function generateTypesForModuleOrGlobal(name, globalValue, formatSettings, outputKind) { + return valueInfoToDeclarationFileText(ts.inspectValue(name, globalValue), formatSettings, outputKind); + } + /* @internal */ + function valueInfoToDeclarationFileText(valueInfo, formatSettings, outputKind) { + if (outputKind === void 0) { outputKind = 0 /* ExportEquals */; } + return ts.textChanges.getNewFileText(toStatements(valueInfo, outputKind), 3 /* TS */, formatSettings.newLineCharacter || "\n", ts.formatting.getFormatContext(formatSettings)); + } + ts.valueInfoToDeclarationFileText = valueInfoToDeclarationFileText; + var OutputKind; + (function (OutputKind) { + OutputKind[OutputKind["ExportEquals"] = 0] = "ExportEquals"; + OutputKind[OutputKind["NamedExport"] = 1] = "NamedExport"; + OutputKind[OutputKind["NamespaceMember"] = 2] = "NamespaceMember"; + OutputKind[OutputKind["Global"] = 3] = "Global"; + })(OutputKind || (OutputKind = {})); + function toNamespaceMemberStatements(info) { + return toStatements(info, 2 /* NamespaceMember */); + } + function toStatements(info, kind) { + var isDefault = info.name === "default" /* Default */; + var name = isDefault ? "_default" : info.name; + if (!isValidIdentifier(name) || isDefault && kind !== 1 /* NamedExport */) + return ts.emptyArray; + var modifiers = isDefault && info.kind === 2 /* FunctionOrClass */ ? [ts.createModifier(85 /* ExportKeyword */), ts.createModifier(80 /* DefaultKeyword */)] + : kind === 3 /* Global */ || kind === 0 /* ExportEquals */ ? [ts.createModifier(125 /* DeclareKeyword */)] + : kind === 1 /* NamedExport */ ? [ts.createModifier(85 /* ExportKeyword */)] + : undefined; + var exportEquals = function () { return kind === 0 /* ExportEquals */ ? [exportEqualsOrDefault(info.name, /*isExportEquals*/ true)] : ts.emptyArray; }; + var exportDefault = function () { return isDefault ? [exportEqualsOrDefault("_default", /*isExportEquals*/ false)] : ts.emptyArray; }; + switch (info.kind) { + case 2 /* FunctionOrClass */: + return exportEquals().concat(functionOrClassToStatements(modifiers, name, info)); + case 3 /* Object */: + var members = info.members, hasNontrivialPrototype = info.hasNontrivialPrototype; + if (!hasNontrivialPrototype) { + if (kind === 0 /* ExportEquals */) { + return ts.flatMap(members, function (v) { return toStatements(v, 1 /* NamedExport */); }); + } + if (members.some(function (m) { return m.kind === 2 /* FunctionOrClass */; })) { + // If some member is a function, use a namespace so it gets a FunctionDeclaration or ClassDeclaration. + return exportDefault().concat([createNamespace(modifiers, name, ts.flatMap(members, toNamespaceMemberStatements))]); + } + } + // falls through + case 0 /* Const */: + case 1 /* Array */: { + var comment = info.kind === 0 /* Const */ ? info.comment : undefined; + var constVar = ts.createVariableStatement(modifiers, ts.createVariableDeclarationList([ts.createVariableDeclaration(name, toType(info))], 2 /* Const */)); + return exportEquals().concat(exportDefault(), [addComment(constVar, comment)]); + } + default: + return ts.Debug.assertNever(info); + } + } + function exportEqualsOrDefault(name, isExportEquals) { + return ts.createExportAssignment(/*decorators*/ undefined, /*modifiers*/ undefined, isExportEquals, ts.createIdentifier(name)); + } + function functionOrClassToStatements(modifiers, name, _a) { + var source = _a.source, prototypeMembers = _a.prototypeMembers, namespaceMembers = _a.namespaceMembers; + var fnAst = parseClassOrFunctionBody(source); + var _b = fnAst === undefined ? { parameters: ts.emptyArray, returnType: anyType() } : getParametersAndReturnType(fnAst), parameters = _b.parameters, returnType = _b.returnType; + var protoOrInstanceMembers = ts.createMap(); + if (typeof fnAst === "object") + getConstructorFunctionInstanceProperties(fnAst, protoOrInstanceMembers); + for (var _i = 0, prototypeMembers_1 = prototypeMembers; _i < prototypeMembers_1.length; _i++) { + var p = prototypeMembers_1[_i]; + // ignore non-functions on the prototype + if (p.kind === 2 /* FunctionOrClass */) { + var m = tryGetMethod(p); + if (m) { + protoOrInstanceMembers.set(p.name, m); + } + } + } + var classStaticMembers = protoOrInstanceMembers.size !== 0 || fnAst === undefined || typeof fnAst !== "number" && fnAst.kind === 157 /* Constructor */ ? [] : undefined; + var namespaceStatements = ts.flatMap(namespaceMembers, function (info) { + if (!isValidIdentifier(info.name)) + return undefined; + if (classStaticMembers) { + switch (info.kind) { + case 3 /* Object */: + if (info.members.some(function (m) { return m.kind === 2 /* FunctionOrClass */; })) { + break; + } + // falls through + case 1 /* Array */: + case 0 /* Const */: + classStaticMembers.push(addComment(ts.createProperty(/*decorators*/ undefined, [ts.createModifier(116 /* StaticKeyword */)], info.name, /*questionOrExclamationToken*/ undefined, toType(info), /*initializer*/ undefined), info.kind === 0 /* Const */ ? info.comment : undefined)); + return undefined; + case 2 /* FunctionOrClass */: + if (!info.namespaceMembers.length) { // Else, can't merge a static method with a namespace. Must make it a function on the namespace. + var sig = tryGetMethod(info, [ts.createModifier(116 /* StaticKeyword */)]); + if (sig) { + classStaticMembers.push(sig); + return undefined; + } + } + break; + default: + ts.Debug.assertNever(info); + } + } + return toStatements(info, 2 /* NamespaceMember */); + }); + var decl = classStaticMembers + ? ts.createClassDeclaration( + /*decorators*/ undefined, modifiers, name, + /*typeParameters*/ undefined, + /*heritageClauses*/ undefined, classStaticMembers.concat((parameters.length ? [ts.createConstructor(/*decorators*/ undefined, /*modifiers*/ undefined, parameters, /*body*/ undefined)] : ts.emptyArray), ts.arrayFrom(protoOrInstanceMembers.values()))) + : ts.createFunctionDeclaration(/*decorators*/ undefined, modifiers, /*asteriskToken*/ undefined, name, /*typeParameters*/ undefined, parameters, returnType, /*body*/ undefined); + return [decl].concat((namespaceStatements.length === 0 ? ts.emptyArray : [createNamespace(modifiers && modifiers.map(function (m) { return ts.getSynthesizedDeepClone(m); }), name, namespaceStatements)])); + } + function tryGetMethod(_a, modifiers) { + var name = _a.name, source = _a.source; + if (!isValidIdentifier(name)) + return undefined; + var fnAst = parseClassOrFunctionBody(source); + if (fnAst === undefined || (typeof fnAst !== "number" && fnAst.kind === 157 /* Constructor */)) + return undefined; + var sig = getParametersAndReturnType(fnAst); + return sig && ts.createMethod( + /*decorators*/ undefined, modifiers, + /*asteriskToken*/ undefined, name, + /*questionToken*/ undefined, + /*typeParameters*/ undefined, sig.parameters, sig.returnType, + /*body*/ undefined); + } + function toType(info) { + switch (info.kind) { + case 0 /* Const */: + return ts.createTypeReferenceNode(info.typeName, /*typeArguments*/ undefined); + case 1 /* Array */: + return ts.createArrayTypeNode(toType(info.inner)); + case 2 /* FunctionOrClass */: + return ts.createTypeReferenceNode("Function", /*typeArguments*/ undefined); // Normally we create a FunctionDeclaration, but this can happen for a function in an array. + case 3 /* Object */: + return ts.createTypeLiteralNode(info.members.map(function (m) { return ts.createPropertySignature(/*modifiers*/ undefined, toPropertyName(m.name), /*questionToken*/ undefined, toType(m), /*initializer*/ undefined); })); + default: + return ts.Debug.assertNever(info); + } + } + function toPropertyName(name) { + return ts.isIdentifierText(name, 6 /* ESNext */) ? ts.createIdentifier(name) : ts.createStringLiteral(name); + } + // Parses assignments to "this.x" in the constructor into class property declarations + function getConstructorFunctionInstanceProperties(fnAst, members) { + forEachOwnNodeOfFunction(fnAst, function (node) { + if (ts.isAssignmentExpression(node, /*excludeCompoundAssignment*/ true) && + ts.isPropertyAccessExpression(node.left) && node.left.expression.kind === 100 /* ThisKeyword */) { + var name_6 = node.left.name.text; + if (!ts.isJsPrivate(name_6)) { + ts.getOrUpdate(members, name_6, function () { return ts.createProperty(/*decorators*/ undefined, /*modifiers*/ undefined, name_6, /*questionOrExclamationToken*/ undefined, anyType(), /*initializer*/ undefined); }); + } + } + }); + } + function getParametersAndReturnType(fnAst) { + if (typeof fnAst === "number") { + return { parameters: ts.fill(fnAst, function (i) { return makeParameter("p" + i, anyType()); }), returnType: anyType() }; + } + var usedArguments = false, hasReturn = false; + forEachOwnNodeOfFunction(fnAst, function (node) { + usedArguments = usedArguments || ts.isIdentifier(node) && node.text === "arguments"; + hasReturn = hasReturn || ts.isReturnStatement(node) && !!node.expression && node.expression.kind !== 200 /* VoidExpression */; + }); + var parameters = fnAst.parameters.map(function (p) { return makeParameter("" + p.name.getText(), inferParameterType(fnAst, p)); }).concat((usedArguments ? [makeRestParameter()] : ts.emptyArray)); + return { parameters: parameters, returnType: hasReturn ? anyType() : ts.createKeywordTypeNode(106 /* VoidKeyword */) }; + } + function makeParameter(name, type) { + return ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, name, /*questionToken*/ undefined, type); + } + function makeRestParameter() { + return ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createToken(25 /* DotDotDotToken */), "args", /*questionToken*/ undefined, ts.createArrayTypeNode(anyType())); + } + /** Returns 'undefined' for class with no declared constructor */ + function parseClassOrFunctionBody(source) { + if (typeof source === "number") + return source; + var classOrFunction = ts.tryCast(parseExpression(source), function (node) { return ts.isFunctionExpression(node) || ts.isArrowFunction(node) || ts.isClassExpression(node); }); + return classOrFunction + ? ts.isClassExpression(classOrFunction) ? ts.find(classOrFunction.members, ts.isConstructorDeclaration) : classOrFunction + // If that didn't parse, it's a method `m() {}`. Parse again inside of an object literal. + : ts.cast(ts.first(ts.cast(parseExpression("{ " + source + " }"), ts.isObjectLiteralExpression).properties), ts.isMethodDeclaration); + } + function parseExpression(expr) { + var text = "const _ = " + expr; + var srcFile = ts.createSourceFile("test.ts", text, 6 /* Latest */, /*setParentNodes*/ true); + return ts.first(ts.cast(ts.first(srcFile.statements), ts.isVariableStatement).declarationList.declarations).initializer; + } + function inferParameterType(_fn, _param) { + // TODO: Inspect function body for clues (see inferFromUsage.ts) + return anyType(); + } + // Descends through all nodes in a function, but not in nested functions. + function forEachOwnNodeOfFunction(fnAst, cb) { + fnAst.body.forEachChild(function recur(node) { + cb(node); + if (!ts.isFunctionLike(node)) + node.forEachChild(recur); + }); + } + function isValidIdentifier(name) { + var keyword = ts.stringToToken(name); + return !(keyword && ts.isNonContextualKeyword(keyword)) && ts.isIdentifierText(name, 6 /* ESNext */); + } + function addComment(node, comment) { + if (comment !== undefined) + ts.addSyntheticLeadingComment(node, 2 /* SingleLineCommentTrivia */, comment); + return node; + } + function anyType() { + return ts.createKeywordTypeNode(120 /* AnyKeyword */); + } + function createNamespace(modifiers, name, statements) { + return ts.createModuleDeclaration(/*decorators*/ undefined, modifiers, ts.createIdentifier(name), ts.createModuleBlock(statements), 16 /* Namespace */); + } +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "requireInTs"; + var errorCodes = [ts.Diagnostics.require_call_may_be_converted_to_an_import.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, context.sourceFile, context.span.start, context.program); }); + return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Convert_require_to_import, fixId, ts.Diagnostics.Convert_all_require_to_import)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { return doChange(changes, diag.file, diag.start, context.program); }); }, + }); + function doChange(changes, sourceFile, pos, program) { + var _a = getInfo(sourceFile, pos), statement = _a.statement, name = _a.name, required = _a.required; + changes.replaceNode(sourceFile, statement, ts.getAllowSyntheticDefaultImports(program.getCompilerOptions()) + ? ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createImportClause(name, /*namedBindings*/ undefined), required) + : ts.createImportEqualsDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, name, ts.createExternalModuleReference(required))); + } + function getInfo(sourceFile, pos) { + var parent = ts.getTokenAtPosition(sourceFile, pos).parent; + if (!ts.isRequireCall(parent, /*checkArgumentIsStringLiteralLike*/ true)) + throw ts.Debug.failBadSyntaxKind(parent); + var decl = ts.cast(parent.parent, ts.isVariableDeclaration); + return { statement: ts.cast(decl.parent.parent, ts.isVariableStatement), name: ts.cast(decl.name, ts.isIdentifier), required: parent.arguments[0] }; + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "useDefaultImport"; + var errorCodes = [ts.Diagnostics.Import_may_be_converted_to_a_default_import.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var sourceFile = context.sourceFile, start = context.span.start; + var info = getInfo(sourceFile, start); + if (!info) + return undefined; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, info, context.preferences); }); + return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Convert_to_default_import, fixId, ts.Diagnostics.Convert_all_to_default_imports)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var info = getInfo(diag.file, diag.start); + if (info) + doChange(changes, diag.file, info, context.preferences); + }); }, + }); + function getInfo(sourceFile, pos) { + var name = ts.getTokenAtPosition(sourceFile, pos); + if (!ts.isIdentifier(name)) + return undefined; // bad input + var parent = name.parent; + if (ts.isImportEqualsDeclaration(parent) && ts.isExternalModuleReference(parent.moduleReference)) { + return { importNode: parent, name: name, moduleSpecifier: parent.moduleReference.expression }; + } + else if (ts.isNamespaceImport(parent)) { + var importNode = parent.parent.parent; + return { importNode: importNode, name: name, moduleSpecifier: importNode.moduleSpecifier }; + } + } + function doChange(changes, sourceFile, info, preferences) { + changes.replaceNode(sourceFile, info.importNode, ts.makeImport(info.name, /*namedImports*/ undefined, info.moduleSpecifier, ts.getQuotePreference(sourceFile, preferences))); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixIdAddMissingTypeof = "fixAddModuleReferTypeMissingTypeof"; + var fixId = fixIdAddMissingTypeof; + var errorCodes = [ts.Diagnostics.Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var sourceFile = context.sourceFile, span = context.span; + var importType = getImportTypeNode(sourceFile, span.start); + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, importType); }); + return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Add_missing_typeof, fixId, ts.Diagnostics.Add_missing_typeof)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + return doChange(changes, context.sourceFile, getImportTypeNode(diag.file, diag.start)); + }); }, + }); + function getImportTypeNode(sourceFile, pos) { + var token = ts.getTokenAtPosition(sourceFile, pos); + ts.Debug.assert(token.kind === 92 /* ImportKeyword */); + ts.Debug.assert(token.parent.kind === 183 /* ImportType */); + return token.parent; + } + function doChange(changes, sourceFile, importType) { + var newTypeNode = ts.updateImportTypeNode(importType, importType.argument, importType.qualifier, importType.typeArguments, /* isTypeOf */ true); + changes.replaceNode(sourceFile, importType, newTypeNode); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixIdAddMissingTypeof = "fixConvertToMappedObjectType"; + var fixId = fixIdAddMissingTypeof; + var errorCodes = [ts.Diagnostics.An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var sourceFile = context.sourceFile, span = context.span; + var info = getInfo(sourceFile, span.start); + if (!info) + return undefined; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, info); }); + var name = ts.idText(info.container.name); + return [codefix.createCodeFixAction(fixId, changes, [ts.Diagnostics.Convert_0_to_mapped_object_type, name], fixId, [ts.Diagnostics.Convert_0_to_mapped_object_type, name])]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var info = getInfo(diag.file, diag.start); + if (info) + doChange(changes, diag.file, info); + }); } + }); + function getInfo(sourceFile, pos) { + var token = ts.getTokenAtPosition(sourceFile, pos); + var indexSignature = ts.cast(token.parent.parent, ts.isIndexSignatureDeclaration); + if (ts.isClassDeclaration(indexSignature.parent)) + return undefined; + var container = ts.isInterfaceDeclaration(indexSignature.parent) ? indexSignature.parent : ts.cast(indexSignature.parent.parent, ts.isTypeAliasDeclaration); + return { indexSignature: indexSignature, container: container }; + } + function createTypeAliasFromInterface(declaration, type) { + return ts.createTypeAliasDeclaration(declaration.decorators, declaration.modifiers, declaration.name, declaration.typeParameters, type); + } + function doChange(changes, sourceFile, _a) { + var indexSignature = _a.indexSignature, container = _a.container; + var members = ts.isInterfaceDeclaration(container) ? container.members : container.type.members; + var otherMembers = members.filter(function (member) { return !ts.isIndexSignatureDeclaration(member); }); + var parameter = ts.first(indexSignature.parameters); + var mappedTypeParameter = ts.createTypeParameterDeclaration(ts.cast(parameter.name, ts.isIdentifier), parameter.type); + var mappedIntersectionType = ts.createMappedTypeNode(ts.hasReadonlyModifier(indexSignature) ? ts.createModifier(133 /* ReadonlyKeyword */) : undefined, mappedTypeParameter, indexSignature.questionToken, indexSignature.type); + var intersectionType = ts.createIntersectionTypeNode(ts.getAllSuperTypeNodes(container).concat([ + mappedIntersectionType + ], (otherMembers.length ? [ts.createTypeLiteralNode(otherMembers)] : ts.emptyArray))); + changes.replaceNode(sourceFile, container, createTypeAliasFromInterface(container, intersectionType)); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var refactor; + (function (refactor) { + var refactorName = "Convert export"; + var actionNameDefaultToNamed = "Convert default export to named export"; + var actionNameNamedToDefault = "Convert named export to default export"; + refactor.registerRefactor(refactorName, { + getAvailableActions: function (context) { + var info = getInfo(context); + if (!info) + return ts.emptyArray; + var description = info.wasDefault ? ts.Diagnostics.Convert_default_export_to_named_export.message : ts.Diagnostics.Convert_named_export_to_default_export.message; + var actionName = info.wasDefault ? actionNameDefaultToNamed : actionNameNamedToDefault; + return [{ name: refactorName, description: description, actions: [{ name: actionName, description: description }] }]; + }, + getEditsForAction: function (context, actionName) { + ts.Debug.assert(actionName === actionNameDefaultToNamed || actionName === actionNameNamedToDefault); + var edits = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(context.file, context.program, ts.Debug.assertDefined(getInfo(context)), t, context.cancellationToken); }); + return { edits: edits, renameFilename: undefined, renameLocation: undefined }; + }, + }); + function getInfo(context) { + var file = context.file; + var span = ts.getRefactorContextSpan(context); + var token = ts.getTokenAtPosition(file, span.start); + var exportNode = ts.getParentNodeInSpan(token, file, span); + if (!exportNode || (!ts.isSourceFile(exportNode.parent) && !(ts.isModuleBlock(exportNode.parent) && ts.isAmbientModule(exportNode.parent.parent)))) { + return undefined; + } + var exportingModuleSymbol = ts.isSourceFile(exportNode.parent) ? exportNode.parent.symbol : exportNode.parent.parent.symbol; + var flags = ts.getModifierFlags(exportNode); + var wasDefault = !!(flags & 512 /* Default */); + // If source file already has a default export, don't offer refactor. + if (!(flags & 1 /* Export */) || !wasDefault && exportingModuleSymbol.exports.has("default" /* Default */)) { + return undefined; + } + switch (exportNode.kind) { + case 239 /* FunctionDeclaration */: + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + case 243 /* EnumDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 244 /* ModuleDeclaration */: { + var node = exportNode; + return node.name && ts.isIdentifier(node.name) ? { exportNode: node, exportName: node.name, wasDefault: wasDefault, exportingModuleSymbol: exportingModuleSymbol } : undefined; + } + case 219 /* VariableStatement */: { + var vs = exportNode; + // Must be `export const x = something;`. + if (!(vs.declarationList.flags & 2 /* Const */) || vs.declarationList.declarations.length !== 1) { + return undefined; + } + var decl = ts.first(vs.declarationList.declarations); + if (!decl.initializer) + return undefined; + ts.Debug.assert(!wasDefault); + return ts.isIdentifier(decl.name) ? { exportNode: vs, exportName: decl.name, wasDefault: wasDefault, exportingModuleSymbol: exportingModuleSymbol } : undefined; + } + default: + return undefined; + } + } + function doChange(exportingSourceFile, program, info, changes, cancellationToken) { + changeExport(exportingSourceFile, info, changes, program.getTypeChecker()); + changeImports(program, info, changes, cancellationToken); + } + function changeExport(exportingSourceFile, _a, changes, checker) { + var wasDefault = _a.wasDefault, exportNode = _a.exportNode, exportName = _a.exportName; + if (wasDefault) { + changes.delete(exportingSourceFile, ts.Debug.assertDefined(ts.findModifier(exportNode, 80 /* DefaultKeyword */))); + } + else { + var exportKeyword = ts.Debug.assertDefined(ts.findModifier(exportNode, 85 /* ExportKeyword */)); + switch (exportNode.kind) { + case 239 /* FunctionDeclaration */: + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + changes.insertNodeAfter(exportingSourceFile, exportKeyword, ts.createToken(80 /* DefaultKeyword */)); + break; + case 219 /* VariableStatement */: + // If 'x' isn't used in this file, `export const x = 0;` --> `export default 0;` + if (!ts.FindAllReferences.Core.isSymbolReferencedInFile(exportName, checker, exportingSourceFile)) { + // We checked in `getInfo` that an initializer exists. + changes.replaceNode(exportingSourceFile, exportNode, ts.createExportDefault(ts.Debug.assertDefined(ts.first(exportNode.declarationList.declarations).initializer))); + break; + } + // falls through + case 243 /* EnumDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 244 /* ModuleDeclaration */: + // `export type T = number;` -> `type T = number; export default T;` + changes.deleteModifier(exportingSourceFile, exportKeyword); + changes.insertNodeAfter(exportingSourceFile, exportNode, ts.createExportDefault(ts.createIdentifier(exportName.text))); + break; + default: + ts.Debug.assertNever(exportNode); + } + } + } + function changeImports(program, _a, changes, cancellationToken) { + var wasDefault = _a.wasDefault, exportName = _a.exportName, exportingModuleSymbol = _a.exportingModuleSymbol; + var checker = program.getTypeChecker(); + var exportSymbol = ts.Debug.assertDefined(checker.getSymbolAtLocation(exportName)); + ts.FindAllReferences.Core.eachExportReference(program.getSourceFiles(), checker, cancellationToken, exportSymbol, exportingModuleSymbol, exportName.text, wasDefault, function (ref) { + var importingSourceFile = ref.getSourceFile(); + if (wasDefault) { + changeDefaultToNamedImport(importingSourceFile, ref, changes, exportName.text); + } + else { + changeNamedToDefaultImport(importingSourceFile, ref, changes); + } + }); + } + function changeDefaultToNamedImport(importingSourceFile, ref, changes, exportName) { + var parent = ref.parent; + switch (parent.kind) { + case 189 /* PropertyAccessExpression */: + // `a.default` --> `a.foo` + changes.replaceNode(importingSourceFile, ref, ts.createIdentifier(exportName)); + break; + case 253 /* ImportSpecifier */: + case 257 /* ExportSpecifier */: { + var spec = parent; + // `default as foo` --> `foo`, `default as bar` --> `foo as bar` + changes.replaceNode(importingSourceFile, spec, makeImportSpecifier(exportName, spec.name.text)); + break; + } + case 250 /* ImportClause */: { + var clause = parent; + ts.Debug.assert(clause.name === ref); + var spec = makeImportSpecifier(exportName, ref.text); + var namedBindings = clause.namedBindings; + if (!namedBindings) { + // `import foo from "./a";` --> `import { foo } from "./a";` + changes.replaceNode(importingSourceFile, ref, ts.createNamedImports([spec])); + } + else if (namedBindings.kind === 251 /* NamespaceImport */) { + // `import foo, * as a from "./a";` --> `import * as a from ".a/"; import { foo } from "./a";` + changes.deleteRange(importingSourceFile, { pos: ref.getStart(importingSourceFile), end: namedBindings.getStart(importingSourceFile) }); + var quotePreference = ts.isStringLiteral(clause.parent.moduleSpecifier) ? ts.quotePreferenceFromString(clause.parent.moduleSpecifier, importingSourceFile) : 1 /* Double */; + var newImport = ts.makeImport(/*default*/ undefined, [makeImportSpecifier(exportName, ref.text)], clause.parent.moduleSpecifier, quotePreference); + changes.insertNodeAfter(importingSourceFile, clause.parent, newImport); + } + else { + // `import foo, { bar } from "./a"` --> `import { bar, foo } from "./a";` + changes.delete(importingSourceFile, ref); + changes.insertNodeAtEndOfList(importingSourceFile, namedBindings.elements, spec); + } + break; + } + default: + ts.Debug.failBadSyntaxKind(parent); + } + } + function changeNamedToDefaultImport(importingSourceFile, ref, changes) { + var parent = ref.parent; + switch (parent.kind) { + case 189 /* PropertyAccessExpression */: + // `a.foo` --> `a.default` + changes.replaceNode(importingSourceFile, ref, ts.createIdentifier("default")); + break; + case 253 /* ImportSpecifier */: { + // `import { foo } from "./a";` --> `import foo from "./a";` + // `import { foo as bar } from "./a";` --> `import bar from "./a";` + var defaultImport = ts.createIdentifier(parent.name.text); + if (parent.parent.elements.length === 1) { + changes.replaceNode(importingSourceFile, parent.parent, defaultImport); + } + else { + changes.delete(importingSourceFile, parent); + changes.insertNodeBefore(importingSourceFile, parent.parent, defaultImport); + } + break; + } + case 257 /* ExportSpecifier */: { + // `export { foo } from "./a";` --> `export { default as foo } from "./a";` + // `export { foo as bar } from "./a";` --> `export { default as bar } from "./a";` + // `export { foo as default } from "./a";` --> `export { default } from "./a";` + // (Because `export foo from "./a";` isn't valid syntax.) + changes.replaceNode(importingSourceFile, parent, makeExportSpecifier("default", parent.name.text)); + break; + } + default: + ts.Debug.assertNever(parent); + } + } + function makeImportSpecifier(propertyName, name) { + return ts.createImportSpecifier(propertyName === name ? undefined : ts.createIdentifier(propertyName), ts.createIdentifier(name)); + } + function makeExportSpecifier(propertyName, name) { + return ts.createExportSpecifier(propertyName === name ? undefined : ts.createIdentifier(propertyName), ts.createIdentifier(name)); + } + })(refactor = ts.refactor || (ts.refactor = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var refactor; + (function (refactor) { + var refactorName = "Convert import"; + var actionNameNamespaceToNamed = "Convert namespace import to named imports"; + var actionNameNamedToNamespace = "Convert named imports to namespace import"; + refactor.registerRefactor(refactorName, { + getAvailableActions: function (context) { + var i = getImportToConvert(context); + if (!i) + return ts.emptyArray; + var description = i.kind === 251 /* NamespaceImport */ ? ts.Diagnostics.Convert_namespace_import_to_named_imports.message : ts.Diagnostics.Convert_named_imports_to_namespace_import.message; + var actionName = i.kind === 251 /* NamespaceImport */ ? actionNameNamespaceToNamed : actionNameNamedToNamespace; + return [{ name: refactorName, description: description, actions: [{ name: actionName, description: description }] }]; + }, + getEditsForAction: function (context, actionName) { + ts.Debug.assert(actionName === actionNameNamespaceToNamed || actionName === actionNameNamedToNamespace); + var edits = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(context.file, context.program, t, ts.Debug.assertDefined(getImportToConvert(context))); }); + return { edits: edits, renameFilename: undefined, renameLocation: undefined }; + } + }); + // Can convert imports of the form `import * as m from "m";` or `import d, { x, y } from "m";`. + function getImportToConvert(context) { + var file = context.file; + var span = ts.getRefactorContextSpan(context); + var token = ts.getTokenAtPosition(file, span.start); + var importDecl = ts.getParentNodeInSpan(token, file, span); + if (!importDecl || !ts.isImportDeclaration(importDecl)) + return undefined; + var importClause = importDecl.importClause; + return importClause && importClause.namedBindings; + } + function doChange(sourceFile, program, changes, toConvert) { + var checker = program.getTypeChecker(); + if (toConvert.kind === 251 /* NamespaceImport */) { + doChangeNamespaceToNamed(sourceFile, checker, changes, toConvert, ts.getAllowSyntheticDefaultImports(program.getCompilerOptions())); + } + else { + doChangeNamedToNamespace(sourceFile, checker, changes, toConvert); + } + } + function doChangeNamespaceToNamed(sourceFile, checker, changes, toConvert, allowSyntheticDefaultImports) { + var usedAsNamespaceOrDefault = false; + var nodesToReplace = []; + var conflictingNames = ts.createMap(); + ts.FindAllReferences.Core.eachSymbolReferenceInFile(toConvert.name, checker, sourceFile, function (id) { + if (!ts.isPropertyAccessExpression(id.parent)) { + usedAsNamespaceOrDefault = true; + } + else { + var parent = ts.cast(id.parent, ts.isPropertyAccessExpression); + var exportName = parent.name.text; + if (checker.resolveName(exportName, id, 67108863 /* All */, /*excludeGlobals*/ true)) { + conflictingNames.set(exportName, true); + } + ts.Debug.assert(parent.expression === id); + nodesToReplace.push(parent); + } + }); + // We may need to change `mod.x` to `_x` to avoid a name conflict. + var exportNameToImportName = ts.createMap(); + for (var _i = 0, nodesToReplace_1 = nodesToReplace; _i < nodesToReplace_1.length; _i++) { + var propertyAccess = nodesToReplace_1[_i]; + var exportName = propertyAccess.name.text; + var importName = exportNameToImportName.get(exportName); + if (importName === undefined) { + exportNameToImportName.set(exportName, importName = conflictingNames.has(exportName) ? ts.getUniqueName(exportName, sourceFile) : exportName); + } + changes.replaceNode(sourceFile, propertyAccess, ts.createIdentifier(importName)); + } + var importSpecifiers = []; + exportNameToImportName.forEach(function (name, propertyName) { + importSpecifiers.push(ts.createImportSpecifier(name === propertyName ? undefined : ts.createIdentifier(propertyName), ts.createIdentifier(name))); + }); + var importDecl = toConvert.parent.parent; + if (usedAsNamespaceOrDefault && !allowSyntheticDefaultImports) { + // Need to leave the namespace import alone + changes.insertNodeAfter(sourceFile, importDecl, updateImport(importDecl, /*defaultImportName*/ undefined, importSpecifiers)); + } + else { + changes.replaceNode(sourceFile, importDecl, updateImport(importDecl, usedAsNamespaceOrDefault ? ts.createIdentifier(toConvert.name.text) : undefined, importSpecifiers)); + } + } + function doChangeNamedToNamespace(sourceFile, checker, changes, toConvert) { + var importDecl = toConvert.parent.parent; + var moduleSpecifier = importDecl.moduleSpecifier; + var preferredName = moduleSpecifier && ts.isStringLiteral(moduleSpecifier) ? ts.codefix.moduleSpecifierToValidIdentifier(moduleSpecifier.text, 6 /* ESNext */) : "module"; + var namespaceNameConflicts = toConvert.elements.some(function (element) { + return ts.FindAllReferences.Core.eachSymbolReferenceInFile(element.name, checker, sourceFile, function (id) { + return !!checker.resolveName(preferredName, id, 67108863 /* All */, /*excludeGlobals*/ true); + }) || false; + }); + var namespaceImportName = namespaceNameConflicts ? ts.getUniqueName(preferredName, sourceFile) : preferredName; + var neededNamedImports = []; + var _loop_21 = function (element) { + var propertyName = (element.propertyName || element.name).text; + ts.FindAllReferences.Core.eachSymbolReferenceInFile(element.name, checker, sourceFile, function (id) { + var access = ts.createPropertyAccess(ts.createIdentifier(namespaceImportName), propertyName); + if (ts.isShorthandPropertyAssignment(id.parent)) { + changes.replaceNode(sourceFile, id.parent, ts.createPropertyAssignment(id.text, access)); + } + else if (ts.isExportSpecifier(id.parent) && !id.parent.propertyName) { + if (!neededNamedImports.some(function (n) { return n.name === element.name; })) { + neededNamedImports.push(ts.createImportSpecifier(element.propertyName && ts.createIdentifier(element.propertyName.text), ts.createIdentifier(element.name.text))); + } + } + else { + changes.replaceNode(sourceFile, id, access); + } + }); + }; + for (var _i = 0, _a = toConvert.elements; _i < _a.length; _i++) { + var element = _a[_i]; + _loop_21(element); + } + changes.replaceNode(sourceFile, toConvert, ts.createNamespaceImport(ts.createIdentifier(namespaceImportName))); + if (neededNamedImports.length) { + changes.insertNodeAfter(sourceFile, toConvert.parent.parent, updateImport(importDecl, /*defaultImportName*/ undefined, neededNamedImports)); + } + } + function updateImport(old, defaultImportName, elements) { + return ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createImportClause(defaultImportName, elements && elements.length ? ts.createNamedImports(elements) : undefined), old.moduleSpecifier); + } + })(refactor = ts.refactor || (ts.refactor = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var refactor; + (function (refactor) { + var extractSymbol; + (function (extractSymbol) { + var refactorName = "Extract Symbol"; + refactor.registerRefactor(refactorName, { getAvailableActions: getAvailableActions, getEditsForAction: getEditsForAction }); + /** + * Compute the associated code actions + * Exported for tests. + */ + function getAvailableActions(context) { + var rangeToExtract = getRangeToExtract(context.file, ts.getRefactorContextSpan(context)); + var targetRange = rangeToExtract.targetRange; + if (targetRange === undefined) { + return ts.emptyArray; + } + var extractions = getPossibleExtractions(targetRange, context); + if (extractions === undefined) { + // No extractions possible + return ts.emptyArray; + } + var functionActions = []; + var usedFunctionNames = ts.createMap(); + var constantActions = []; + var usedConstantNames = ts.createMap(); + var i = 0; + for (var _i = 0, extractions_1 = extractions; _i < extractions_1.length; _i++) { + var _a = extractions_1[_i], functionExtraction = _a.functionExtraction, constantExtraction = _a.constantExtraction; + // Skip these since we don't have a way to report errors yet + if (functionExtraction.errors.length === 0) { + // Don't issue refactorings with duplicated names. + // Scopes come back in "innermost first" order, so extractions will + // preferentially go into nearer scopes + var description = functionExtraction.description; + if (!usedFunctionNames.has(description)) { + usedFunctionNames.set(description, true); + functionActions.push({ + description: description, + name: "function_scope_" + i + }); + } + } + // Skip these since we don't have a way to report errors yet + if (constantExtraction.errors.length === 0) { + // Don't issue refactorings with duplicated names. + // Scopes come back in "innermost first" order, so extractions will + // preferentially go into nearer scopes + var description = constantExtraction.description; + if (!usedConstantNames.has(description)) { + usedConstantNames.set(description, true); + constantActions.push({ + description: description, + name: "constant_scope_" + i + }); + } + } + // *do* increment i anyway because we'll look for the i-th scope + // later when actually doing the refactoring if the user requests it + i++; + } + var infos = []; + if (functionActions.length) { + infos.push({ + name: refactorName, + description: ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_function), + actions: functionActions + }); + } + if (constantActions.length) { + infos.push({ + name: refactorName, + description: ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_constant), + actions: constantActions + }); + } + return infos.length ? infos : ts.emptyArray; + } + extractSymbol.getAvailableActions = getAvailableActions; + /* Exported for tests */ + function getEditsForAction(context, actionName) { + var rangeToExtract = getRangeToExtract(context.file, ts.getRefactorContextSpan(context)); + var targetRange = rangeToExtract.targetRange; // TODO:GH#18217 + var parsedFunctionIndexMatch = /^function_scope_(\d+)$/.exec(actionName); + if (parsedFunctionIndexMatch) { + var index = +parsedFunctionIndexMatch[1]; + ts.Debug.assert(isFinite(index), "Expected to parse a finite number from the function scope index"); + return getFunctionExtractionAtIndex(targetRange, context, index); + } + var parsedConstantIndexMatch = /^constant_scope_(\d+)$/.exec(actionName); + if (parsedConstantIndexMatch) { + var index = +parsedConstantIndexMatch[1]; + ts.Debug.assert(isFinite(index), "Expected to parse a finite number from the constant scope index"); + return getConstantExtractionAtIndex(targetRange, context, index); + } + ts.Debug.fail("Unrecognized action name"); + } + extractSymbol.getEditsForAction = getEditsForAction; + // Move these into diagnostic messages if they become user-facing + var Messages; + (function (Messages) { + function createMessage(message) { + return { message: message, code: 0, category: ts.DiagnosticCategory.Message, key: message }; + } + Messages.cannotExtractRange = createMessage("Cannot extract range."); + Messages.cannotExtractImport = createMessage("Cannot extract import statement."); + Messages.cannotExtractSuper = createMessage("Cannot extract super call."); + Messages.cannotExtractEmpty = createMessage("Cannot extract empty range."); + Messages.expressionExpected = createMessage("expression expected."); + Messages.uselessConstantType = createMessage("No reason to extract constant of type."); + Messages.statementOrExpressionExpected = createMessage("Statement or expression expected."); + Messages.cannotExtractRangeContainingConditionalBreakOrContinueStatements = createMessage("Cannot extract range containing conditional break or continue statements."); + Messages.cannotExtractRangeContainingConditionalReturnStatement = createMessage("Cannot extract range containing conditional return statement."); + Messages.cannotExtractRangeContainingLabeledBreakOrContinueStatementWithTargetOutsideOfTheRange = createMessage("Cannot extract range containing labeled break or continue with target outside of the range."); + Messages.cannotExtractRangeThatContainsWritesToReferencesLocatedOutsideOfTheTargetRangeInGenerators = createMessage("Cannot extract range containing writes to references located outside of the target range in generators."); + Messages.typeWillNotBeVisibleInTheNewScope = createMessage("Type will not visible in the new scope."); + Messages.functionWillNotBeVisibleInTheNewScope = createMessage("Function will not visible in the new scope."); + Messages.cannotExtractIdentifier = createMessage("Select more than a single identifier."); + Messages.cannotExtractExportedEntity = createMessage("Cannot extract exported declaration"); + Messages.cannotWriteInExpression = createMessage("Cannot write back side-effects when extracting an expression"); + Messages.cannotExtractReadonlyPropertyInitializerOutsideConstructor = createMessage("Cannot move initialization of read-only class property outside of the constructor"); + Messages.cannotExtractAmbientBlock = createMessage("Cannot extract code from ambient contexts"); + Messages.cannotAccessVariablesFromNestedScopes = createMessage("Cannot access variables from nested scopes"); + Messages.cannotExtractToOtherFunctionLike = createMessage("Cannot extract method to a function-like scope that is not a function"); + Messages.cannotExtractToJSClass = createMessage("Cannot extract constant to a class scope in JS"); + Messages.cannotExtractToExpressionArrowFunction = createMessage("Cannot extract constant to an arrow function without a block"); + })(Messages = extractSymbol.Messages || (extractSymbol.Messages = {})); + var RangeFacts; + (function (RangeFacts) { + RangeFacts[RangeFacts["None"] = 0] = "None"; + RangeFacts[RangeFacts["HasReturn"] = 1] = "HasReturn"; + RangeFacts[RangeFacts["IsGenerator"] = 2] = "IsGenerator"; + RangeFacts[RangeFacts["IsAsyncFunction"] = 4] = "IsAsyncFunction"; + RangeFacts[RangeFacts["UsesThis"] = 8] = "UsesThis"; + /** + * The range is in a function which needs the 'static' modifier in a class + */ + RangeFacts[RangeFacts["InStaticRegion"] = 16] = "InStaticRegion"; + })(RangeFacts || (RangeFacts = {})); + /** + * getRangeToExtract takes a span inside a text file and returns either an expression or an array + * of statements representing the minimum set of nodes needed to extract the entire span. This + * process may fail, in which case a set of errors is returned instead (these are currently + * not shown to the user, but can be used by us diagnostically) + */ + // exported only for tests + function getRangeToExtract(sourceFile, span) { + var length = span.length; + if (length === 0) { + return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractEmpty)] }; + } + // Walk up starting from the the start position until we find a non-SourceFile node that subsumes the selected span. + // This may fail (e.g. you select two statements in the root of a source file) + var start = ts.getParentNodeInSpan(ts.getTokenAtPosition(sourceFile, span.start), sourceFile, span); + // Do the same for the ending position + var end = ts.getParentNodeInSpan(ts.findTokenOnLeftOfPosition(sourceFile, ts.textSpanEnd(span)), sourceFile, span); + var declarations = []; + // We'll modify these flags as we walk the tree to collect data + // about what things need to be done as part of the extraction. + var rangeFacts = RangeFacts.None; + if (!start || !end) { + // cannot find either start or end node + return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractRange)] }; + } + if (start.parent !== end.parent) { + // start and end nodes belong to different subtrees + return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractRange)] }; + } + if (start !== end) { + // start and end should be statements and parent should be either block or a source file + if (!isBlockLike(start.parent)) { + return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractRange)] }; + } + var statements = []; + var start2 = start; // TODO: GH#18217 Need to alias `start` to get this to compile. See https://github.com/Microsoft/TypeScript/issues/19955#issuecomment-344118248 + for (var _i = 0, _a = start2.parent.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + if (statement === start || statements.length) { + var errors_1 = checkNode(statement); + if (errors_1) { + return { errors: errors_1 }; + } + statements.push(statement); + } + if (statement === end) { + break; + } + } + if (!statements.length) { + // https://github.com/Microsoft/TypeScript/issues/20559 + // Ranges like [|case 1: break;|] will fail to populate `statements` because + // they will never find `start` in `start.parent.statements`. + // Consider: We could support ranges like [|case 1:|] by refining them to just + // the expression. + return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractRange)] }; + } + return { targetRange: { range: statements, facts: rangeFacts, declarations: declarations } }; + } + if (ts.isReturnStatement(start) && !start.expression) { + // Makes no sense to extract an expression-less return statement. + return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractRange)] }; + } + // We have a single node (start) + var node = refineNode(start); + var errors = checkRootNode(node) || checkNode(node); + if (errors) { + return { errors: errors }; + } + return { targetRange: { range: getStatementOrExpressionRange(node), facts: rangeFacts, declarations: declarations } }; // TODO: GH#18217 + /** + * Attempt to refine the extraction node (generally, by shrinking it) to produce better results. + * @param node The unrefined extraction node. + */ + function refineNode(node) { + if (ts.isReturnStatement(node)) { + if (node.expression) { + return node.expression; + } + } + else if (ts.isVariableStatement(node)) { + var numInitializers = 0; + var lastInitializer = void 0; + for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (declaration.initializer) { + numInitializers++; + lastInitializer = declaration.initializer; + } + } + if (numInitializers === 1) { + return lastInitializer; + } + // No special handling if there are multiple initializers. + } + else if (ts.isVariableDeclaration(node)) { + if (node.initializer) { + return node.initializer; + } + } + return node; + } + function checkRootNode(node) { + if (ts.isIdentifier(ts.isExpressionStatement(node) ? node.expression : node)) { + return [ts.createDiagnosticForNode(node, Messages.cannotExtractIdentifier)]; + } + return undefined; + } + function checkForStaticContext(nodeToCheck, containingClass) { + var current = nodeToCheck; + while (current !== containingClass) { + if (current.kind === 154 /* PropertyDeclaration */) { + if (ts.hasModifier(current, 32 /* Static */)) { + rangeFacts |= RangeFacts.InStaticRegion; + } + break; + } + else if (current.kind === 151 /* Parameter */) { + var ctorOrMethod = ts.getContainingFunction(current); + if (ctorOrMethod.kind === 157 /* Constructor */) { + rangeFacts |= RangeFacts.InStaticRegion; + } + break; + } + else if (current.kind === 156 /* MethodDeclaration */) { + if (ts.hasModifier(current, 32 /* Static */)) { + rangeFacts |= RangeFacts.InStaticRegion; + } + } + current = current.parent; + } + } + // Verifies whether we can actually extract this node or not. + function checkNode(nodeToCheck) { + var PermittedJumps; + (function (PermittedJumps) { + PermittedJumps[PermittedJumps["None"] = 0] = "None"; + PermittedJumps[PermittedJumps["Break"] = 1] = "Break"; + PermittedJumps[PermittedJumps["Continue"] = 2] = "Continue"; + PermittedJumps[PermittedJumps["Return"] = 4] = "Return"; + })(PermittedJumps || (PermittedJumps = {})); + // We believe it's true because the node is from the (unmodified) tree. + ts.Debug.assert(nodeToCheck.pos <= nodeToCheck.end, "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809"); + // For understanding how skipTrivia functioned: + ts.Debug.assert(!ts.positionIsSynthesized(nodeToCheck.pos), "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809"); + if (!ts.isStatement(nodeToCheck) && !(ts.isExpressionNode(nodeToCheck) && isExtractableExpression(nodeToCheck))) { + return [ts.createDiagnosticForNode(nodeToCheck, Messages.statementOrExpressionExpected)]; + } + if (nodeToCheck.flags & 4194304 /* Ambient */) { + return [ts.createDiagnosticForNode(nodeToCheck, Messages.cannotExtractAmbientBlock)]; + } + // If we're in a class, see whether we're in a static region (static property initializer, static method, class constructor parameter default) + var containingClass = ts.getContainingClass(nodeToCheck); + if (containingClass) { + checkForStaticContext(nodeToCheck, containingClass); + } + var errors; + var permittedJumps = 4 /* Return */; + var seenLabels; + visit(nodeToCheck); + return errors; + function visit(node) { + if (errors) { + // already found an error - can stop now + return true; + } + if (ts.isDeclaration(node)) { + var declaringNode = (node.kind === 237 /* VariableDeclaration */) ? node.parent.parent : node; + if (ts.hasModifier(declaringNode, 1 /* Export */)) { + // TODO: GH#18217 Silly to use `errors ||` since it's definitely not defined (see top of `visit`) + // Also, if we're only pushing one error, just use `let error: Diagnostic | undefined`! + // Also TODO: GH#19956 + (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractExportedEntity)); + return true; + } + declarations.push(node.symbol); + } + // Some things can't be extracted in certain situations + switch (node.kind) { + case 249 /* ImportDeclaration */: + (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractImport)); + return true; + case 98 /* SuperKeyword */: + // For a super *constructor call*, we have to be extracting the entire class, + // but a super *method call* simply implies a 'this' reference + if (node.parent.kind === 191 /* CallExpression */) { + // Super constructor call + var containingClass_1 = ts.getContainingClass(node); // TODO:GH#18217 + if (containingClass_1.pos < span.start || containingClass_1.end >= (span.start + span.length)) { + (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractSuper)); + return true; + } + } + else { + rangeFacts |= RangeFacts.UsesThis; + } + break; + } + if (ts.isFunctionLikeDeclaration(node) || ts.isClassLike(node)) { + switch (node.kind) { + case 239 /* FunctionDeclaration */: + case 240 /* ClassDeclaration */: + if (ts.isSourceFile(node.parent) && node.parent.externalModuleIndicator === undefined) { + // You cannot extract global declarations + (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.functionWillNotBeVisibleInTheNewScope)); + } + break; + } + // do not dive into functions or classes + return false; + } + var savedPermittedJumps = permittedJumps; + switch (node.kind) { + case 222 /* IfStatement */: + permittedJumps = 0 /* None */; + break; + case 235 /* TryStatement */: + // forbid all jumps inside try blocks + permittedJumps = 0 /* None */; + break; + case 218 /* Block */: + if (node.parent && node.parent.kind === 235 /* TryStatement */ && node.parent.finallyBlock === node) { + // allow unconditional returns from finally blocks + permittedJumps = 4 /* Return */; + } + break; + case 271 /* CaseClause */: + // allow unlabeled break inside case clauses + permittedJumps |= 1 /* Break */; + break; + default: + if (ts.isIterationStatement(node, /*lookInLabeledStatements*/ false)) { + // allow unlabeled break/continue inside loops + permittedJumps |= 1 /* Break */ | 2 /* Continue */; + } + break; + } + switch (node.kind) { + case 178 /* ThisType */: + case 100 /* ThisKeyword */: + rangeFacts |= RangeFacts.UsesThis; + break; + case 233 /* LabeledStatement */: + { + var label = node.label; + (seenLabels || (seenLabels = [])).push(label.escapedText); + ts.forEachChild(node, visit); + seenLabels.pop(); + break; + } + case 229 /* BreakStatement */: + case 228 /* ContinueStatement */: + { + var label = node.label; + if (label) { + if (!ts.contains(seenLabels, label.escapedText)) { + // attempts to jump to label that is not in range to be extracted + (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractRangeContainingLabeledBreakOrContinueStatementWithTargetOutsideOfTheRange)); + } + } + else { + if (!(permittedJumps & (node.kind === 229 /* BreakStatement */ ? 1 /* Break */ : 2 /* Continue */))) { + // attempt to break or continue in a forbidden context + (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractRangeContainingConditionalBreakOrContinueStatements)); + } + } + break; + } + case 201 /* AwaitExpression */: + rangeFacts |= RangeFacts.IsAsyncFunction; + break; + case 207 /* YieldExpression */: + rangeFacts |= RangeFacts.IsGenerator; + break; + case 230 /* ReturnStatement */: + if (permittedJumps & 4 /* Return */) { + rangeFacts |= RangeFacts.HasReturn; + } + else { + (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractRangeContainingConditionalReturnStatement)); + } + break; + default: + ts.forEachChild(node, visit); + break; + } + permittedJumps = savedPermittedJumps; + } + } + } + extractSymbol.getRangeToExtract = getRangeToExtract; + function getStatementOrExpressionRange(node) { + if (ts.isStatement(node)) { + return [node]; + } + else if (ts.isExpressionNode(node)) { + // If our selection is the expression in an ExpressionStatement, expand + // the selection to include the enclosing Statement (this stops us + // from trying to care about the return value of the extracted function + // and eliminates double semicolon insertion in certain scenarios) + return ts.isExpressionStatement(node.parent) ? [node.parent] : node; + } + return undefined; + } + function isScope(node) { + return ts.isFunctionLikeDeclaration(node) || ts.isSourceFile(node) || ts.isModuleBlock(node) || ts.isClassLike(node); + } + /** + * Computes possible places we could extract the function into. For example, + * you may be able to extract into a class method *or* local closure *or* namespace function, + * depending on what's in the extracted body. + */ + function collectEnclosingScopes(range) { + var current = isReadonlyArray(range.range) ? ts.first(range.range) : range.range; + if (range.facts & RangeFacts.UsesThis) { + // if range uses this as keyword or as type inside the class then it can only be extracted to a method of the containing class + var containingClass = ts.getContainingClass(current); + if (containingClass) { + var containingFunction = ts.findAncestor(current, ts.isFunctionLikeDeclaration); + return containingFunction + ? [containingFunction, containingClass] + : [containingClass]; + } + } + var scopes = []; + while (true) { + current = current.parent; + // A function parameter's initializer is actually in the outer scope, not the function declaration + if (current.kind === 151 /* Parameter */) { + // Skip all the way to the outer scope of the function that declared this parameter + current = ts.findAncestor(current, function (parent) { return ts.isFunctionLikeDeclaration(parent); }).parent; + } + // We want to find the nearest parent where we can place an "equivalent" sibling to the node we're extracting out of. + // Walk up to the closest parent of a place where we can logically put a sibling: + // * Function declaration + // * Class declaration or expression + // * Module/namespace or source file + if (isScope(current)) { + scopes.push(current); + if (current.kind === 279 /* SourceFile */) { + return scopes; + } + } + } + } + function getFunctionExtractionAtIndex(targetRange, context, requestedChangesIndex) { + var _a = getPossibleExtractionsWorker(targetRange, context), scopes = _a.scopes, _b = _a.readsAndWrites, target = _b.target, usagesPerScope = _b.usagesPerScope, functionErrorsPerScope = _b.functionErrorsPerScope, exposedVariableDeclarations = _b.exposedVariableDeclarations; + ts.Debug.assert(!functionErrorsPerScope[requestedChangesIndex].length, "The extraction went missing? How?"); + context.cancellationToken.throwIfCancellationRequested(); // TODO: GH#18217 + return extractFunctionInScope(target, scopes[requestedChangesIndex], usagesPerScope[requestedChangesIndex], exposedVariableDeclarations, targetRange, context); + } + function getConstantExtractionAtIndex(targetRange, context, requestedChangesIndex) { + var _a = getPossibleExtractionsWorker(targetRange, context), scopes = _a.scopes, _b = _a.readsAndWrites, target = _b.target, usagesPerScope = _b.usagesPerScope, constantErrorsPerScope = _b.constantErrorsPerScope, exposedVariableDeclarations = _b.exposedVariableDeclarations; + ts.Debug.assert(!constantErrorsPerScope[requestedChangesIndex].length, "The extraction went missing? How?"); + ts.Debug.assert(exposedVariableDeclarations.length === 0, "Extract constant accepted a range containing a variable declaration?"); + context.cancellationToken.throwIfCancellationRequested(); + var expression = ts.isExpression(target) + ? target + : target.statements[0].expression; + return extractConstantInScope(expression, scopes[requestedChangesIndex], usagesPerScope[requestedChangesIndex], targetRange.facts, context); + } + /** + * Given a piece of text to extract ('targetRange'), computes a list of possible extractions. + * Each returned ExtractResultForScope corresponds to a possible target scope and is either a set of changes + * or an error explaining why we can't extract into that scope. + */ + function getPossibleExtractions(targetRange, context) { + var _a = getPossibleExtractionsWorker(targetRange, context), scopes = _a.scopes, _b = _a.readsAndWrites, functionErrorsPerScope = _b.functionErrorsPerScope, constantErrorsPerScope = _b.constantErrorsPerScope; + // Need the inner type annotation to avoid https://github.com/Microsoft/TypeScript/issues/7547 + var extractions = scopes.map(function (scope, i) { + var functionDescriptionPart = getDescriptionForFunctionInScope(scope); + var constantDescriptionPart = getDescriptionForConstantInScope(scope); + var scopeDescription = ts.isFunctionLikeDeclaration(scope) + ? getDescriptionForFunctionLikeDeclaration(scope) + : ts.isClassLike(scope) + ? getDescriptionForClassLikeDeclaration(scope) + : getDescriptionForModuleLikeDeclaration(scope); + var functionDescription; + var constantDescription; + if (scopeDescription === 1 /* Global */) { + functionDescription = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_to_0_in_1_scope), [functionDescriptionPart, "global"]); + constantDescription = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_to_0_in_1_scope), [constantDescriptionPart, "global"]); + } + else if (scopeDescription === 0 /* Module */) { + functionDescription = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_to_0_in_1_scope), [functionDescriptionPart, "module"]); + constantDescription = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_to_0_in_1_scope), [constantDescriptionPart, "module"]); + } + else { + functionDescription = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_to_0_in_1), [functionDescriptionPart, scopeDescription]); + constantDescription = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_to_0_in_1), [constantDescriptionPart, scopeDescription]); + } + // Customize the phrasing for the innermost scope to increase clarity. + if (i === 0 && !ts.isClassLike(scope)) { + constantDescription = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_to_0_in_enclosing_scope), [constantDescriptionPart]); + } + return { + functionExtraction: { + description: functionDescription, + errors: functionErrorsPerScope[i], + }, + constantExtraction: { + description: constantDescription, + errors: constantErrorsPerScope[i], + }, + }; + }); + return extractions; + } + function getPossibleExtractionsWorker(targetRange, context) { + var sourceFile = context.file; + var scopes = collectEnclosingScopes(targetRange); + var enclosingTextRange = getEnclosingTextRange(targetRange, sourceFile); + var readsAndWrites = collectReadsAndWrites(targetRange, scopes, enclosingTextRange, sourceFile, context.program.getTypeChecker(), context.cancellationToken); + return { scopes: scopes, readsAndWrites: readsAndWrites }; + } + function getDescriptionForFunctionInScope(scope) { + return ts.isFunctionLikeDeclaration(scope) + ? "inner function" + : ts.isClassLike(scope) + ? "method" + : "function"; + } + function getDescriptionForConstantInScope(scope) { + return ts.isClassLike(scope) + ? "readonly field" + : "constant"; + } + function getDescriptionForFunctionLikeDeclaration(scope) { + switch (scope.kind) { + case 157 /* Constructor */: + return "constructor"; + case 196 /* FunctionExpression */: + case 239 /* FunctionDeclaration */: + return scope.name + ? "function '" + scope.name.text + "'" + : "anonymous function"; + case 197 /* ArrowFunction */: + return "arrow function"; + case 156 /* MethodDeclaration */: + return "method '" + scope.name.getText() + "'"; + case 158 /* GetAccessor */: + return "'get " + scope.name.getText() + "'"; + case 159 /* SetAccessor */: + return "'set " + scope.name.getText() + "'"; + default: + throw ts.Debug.assertNever(scope); + } + } + function getDescriptionForClassLikeDeclaration(scope) { + return scope.kind === 240 /* ClassDeclaration */ + ? scope.name ? "class '" + scope.name.text + "'" : "anonymous class declaration" + : scope.name ? "class expression '" + scope.name.text + "'" : "anonymous class expression"; + } + function getDescriptionForModuleLikeDeclaration(scope) { + return scope.kind === 245 /* ModuleBlock */ + ? "namespace '" + scope.parent.name.getText() + "'" + : scope.externalModuleIndicator ? 0 /* Module */ : 1 /* Global */; + } + var SpecialScope; + (function (SpecialScope) { + SpecialScope[SpecialScope["Module"] = 0] = "Module"; + SpecialScope[SpecialScope["Global"] = 1] = "Global"; + })(SpecialScope || (SpecialScope = {})); + /** + * Result of 'extractRange' operation for a specific scope. + * Stores either a list of changes that should be applied to extract a range or a list of errors + */ + function extractFunctionInScope(node, scope, _a, exposedVariableDeclarations, range, context) { + var usagesInScope = _a.usages, typeParameterUsages = _a.typeParameterUsages, substitutions = _a.substitutions; + var checker = context.program.getTypeChecker(); + // Make a unique name for the extracted function + var file = scope.getSourceFile(); + var functionNameText = ts.getUniqueName(ts.isClassLike(scope) ? "newMethod" : "newFunction", file); + var isJS = ts.isInJSFile(scope); + var functionName = ts.createIdentifier(functionNameText); + var returnType; + var parameters = []; + var callArguments = []; + var writes; + usagesInScope.forEach(function (usage, name) { + var typeNode; + if (!isJS) { + var type = checker.getTypeOfSymbolAtLocation(usage.symbol, usage.node); + // Widen the type so we don't emit nonsense annotations like "function fn(x: 3) {" + type = checker.getBaseTypeOfLiteralType(type); + typeNode = checker.typeToTypeNode(type, scope, 1 /* NoTruncation */); + } + var paramDecl = ts.createParameter( + /*decorators*/ undefined, + /*modifiers*/ undefined, + /*dotDotDotToken*/ undefined, + /*name*/ name, + /*questionToken*/ undefined, typeNode); + parameters.push(paramDecl); + if (usage.usage === 2 /* Write */) { + (writes || (writes = [])).push(usage); + } + callArguments.push(ts.createIdentifier(name)); + }); + var typeParametersAndDeclarations = ts.arrayFrom(typeParameterUsages.values()).map(function (type) { return ({ type: type, declaration: getFirstDeclaration(type) }); }); + var sortedTypeParametersAndDeclarations = typeParametersAndDeclarations.sort(compareTypesByDeclarationOrder); + var typeParameters = sortedTypeParametersAndDeclarations.length === 0 + ? undefined + : sortedTypeParametersAndDeclarations.map(function (t) { return t.declaration; }); + // Strictly speaking, we should check whether each name actually binds to the appropriate type + // parameter. In cases of shadowing, they may not. + var callTypeArguments = typeParameters !== undefined + ? typeParameters.map(function (decl) { return ts.createTypeReferenceNode(decl.name, /*typeArguments*/ undefined); }) + : undefined; + // Provide explicit return types for contextually-typed functions + // to avoid problems when there are literal types present + if (ts.isExpression(node) && !isJS) { + var contextualType = checker.getContextualType(node); + returnType = checker.typeToTypeNode(contextualType, scope, 1 /* NoTruncation */); // TODO: GH#18217 + } + var _b = transformFunctionBody(node, exposedVariableDeclarations, writes, substitutions, !!(range.facts & RangeFacts.HasReturn)), body = _b.body, returnValueProperty = _b.returnValueProperty; + ts.suppressLeadingAndTrailingTrivia(body); + var newFunction; + if (ts.isClassLike(scope)) { + // always create private method in TypeScript files + var modifiers = isJS ? [] : [ts.createToken(113 /* PrivateKeyword */)]; + if (range.facts & RangeFacts.InStaticRegion) { + modifiers.push(ts.createToken(116 /* StaticKeyword */)); + } + if (range.facts & RangeFacts.IsAsyncFunction) { + modifiers.push(ts.createToken(121 /* AsyncKeyword */)); + } + newFunction = ts.createMethod( + /*decorators*/ undefined, modifiers.length ? modifiers : undefined, range.facts & RangeFacts.IsGenerator ? ts.createToken(40 /* AsteriskToken */) : undefined, functionName, + /*questionToken*/ undefined, typeParameters, parameters, returnType, body); + } + else { + newFunction = ts.createFunctionDeclaration( + /*decorators*/ undefined, range.facts & RangeFacts.IsAsyncFunction ? [ts.createToken(121 /* AsyncKeyword */)] : undefined, range.facts & RangeFacts.IsGenerator ? ts.createToken(40 /* AsteriskToken */) : undefined, functionName, typeParameters, parameters, returnType, body); + } + var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); + var minInsertionPos = (isReadonlyArray(range.range) ? ts.last(range.range) : range.range).end; + var nodeToInsertBefore = getNodeToInsertFunctionBefore(minInsertionPos, scope); + if (nodeToInsertBefore) { + changeTracker.insertNodeBefore(context.file, nodeToInsertBefore, newFunction, /*blankLineBetween*/ true); + } + else { + changeTracker.insertNodeAtEndOfScope(context.file, scope, newFunction); + } + var newNodes = []; + // replace range with function call + var called = getCalledExpression(scope, range, functionNameText); + var call = ts.createCall(called, callTypeArguments, // Note that no attempt is made to take advantage of type argument inference + callArguments); + if (range.facts & RangeFacts.IsGenerator) { + call = ts.createYield(ts.createToken(40 /* AsteriskToken */), call); + } + if (range.facts & RangeFacts.IsAsyncFunction) { + call = ts.createAwait(call); + } + if (exposedVariableDeclarations.length && !writes) { + // No need to mix declarations and writes. + // How could any variables be exposed if there's a return statement? + ts.Debug.assert(!returnValueProperty); + ts.Debug.assert(!(range.facts & RangeFacts.HasReturn)); + if (exposedVariableDeclarations.length === 1) { + // Declaring exactly one variable: let x = newFunction(); + var variableDeclaration = exposedVariableDeclarations[0]; + newNodes.push(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(ts.getSynthesizedDeepClone(variableDeclaration.name), /*type*/ ts.getSynthesizedDeepClone(variableDeclaration.type), /*initializer*/ call)], // TODO (acasey): test binding patterns + variableDeclaration.parent.flags))); + } + else { + // Declaring multiple variables / return properties: + // let {x, y} = newFunction(); + var bindingElements = []; + var typeElements = []; + var commonNodeFlags = exposedVariableDeclarations[0].parent.flags; + var sawExplicitType = false; + for (var _i = 0, exposedVariableDeclarations_1 = exposedVariableDeclarations; _i < exposedVariableDeclarations_1.length; _i++) { + var variableDeclaration = exposedVariableDeclarations_1[_i]; + bindingElements.push(ts.createBindingElement( + /*dotDotDotToken*/ undefined, + /*propertyName*/ undefined, + /*name*/ ts.getSynthesizedDeepClone(variableDeclaration.name))); + // Being returned through an object literal will have widened the type. + var variableType = checker.typeToTypeNode(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(variableDeclaration)), scope, 1 /* NoTruncation */); + typeElements.push(ts.createPropertySignature( + /*modifiers*/ undefined, + /*name*/ variableDeclaration.symbol.name, + /*questionToken*/ undefined, + /*type*/ variableType, + /*initializer*/ undefined)); + sawExplicitType = sawExplicitType || variableDeclaration.type !== undefined; + commonNodeFlags = commonNodeFlags & variableDeclaration.parent.flags; + } + var typeLiteral = sawExplicitType ? ts.createTypeLiteralNode(typeElements) : undefined; + if (typeLiteral) { + ts.setEmitFlags(typeLiteral, 1 /* SingleLine */); + } + newNodes.push(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(ts.createObjectBindingPattern(bindingElements), + /*type*/ typeLiteral, + /*initializer*/ call)], commonNodeFlags))); + } + } + else if (exposedVariableDeclarations.length || writes) { + if (exposedVariableDeclarations.length) { + // CONSIDER: we're going to create one statement per variable, but we could actually preserve their original grouping. + for (var _c = 0, exposedVariableDeclarations_2 = exposedVariableDeclarations; _c < exposedVariableDeclarations_2.length; _c++) { + var variableDeclaration = exposedVariableDeclarations_2[_c]; + var flags = variableDeclaration.parent.flags; + if (flags & 2 /* Const */) { + flags = (flags & ~2 /* Const */) | 1 /* Let */; + } + newNodes.push(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(variableDeclaration.symbol.name, getTypeDeepCloneUnionUndefined(variableDeclaration.type))], flags))); + } + } + if (returnValueProperty) { + // has both writes and return, need to create variable declaration to hold return value; + newNodes.push(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(returnValueProperty, getTypeDeepCloneUnionUndefined(returnType))], 1 /* Let */))); + } + var assignments = getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes); + if (returnValueProperty) { + assignments.unshift(ts.createShorthandPropertyAssignment(returnValueProperty)); + } + // propagate writes back + if (assignments.length === 1) { + // We would only have introduced a return value property if there had been + // other assignments to make. + ts.Debug.assert(!returnValueProperty); + newNodes.push(ts.createStatement(ts.createAssignment(assignments[0].name, call))); + if (range.facts & RangeFacts.HasReturn) { + newNodes.push(ts.createReturn()); + } + } + else { + // emit e.g. + // { a, b, __return } = newFunction(a, b); + // return __return; + newNodes.push(ts.createStatement(ts.createAssignment(ts.createObjectLiteral(assignments), call))); + if (returnValueProperty) { + newNodes.push(ts.createReturn(ts.createIdentifier(returnValueProperty))); + } + } + } + else { + if (range.facts & RangeFacts.HasReturn) { + newNodes.push(ts.createReturn(call)); + } + else if (isReadonlyArray(range.range)) { + newNodes.push(ts.createStatement(call)); + } + else { + newNodes.push(call); + } + } + if (isReadonlyArray(range.range)) { + changeTracker.replaceNodeRangeWithNodes(context.file, ts.first(range.range), ts.last(range.range), newNodes); + } + else { + changeTracker.replaceNodeWithNodes(context.file, range.range, newNodes); + } + var edits = changeTracker.getChanges(); + var renameRange = isReadonlyArray(range.range) ? ts.first(range.range) : range.range; + var renameFilename = renameRange.getSourceFile().fileName; + var renameLocation = ts.getRenameLocation(edits, renameFilename, functionNameText, /*isDeclaredBeforeUse*/ false); + return { renameFilename: renameFilename, renameLocation: renameLocation, edits: edits }; + function getTypeDeepCloneUnionUndefined(typeNode) { + if (typeNode === undefined) { + return undefined; + } + var clone = ts.getSynthesizedDeepClone(typeNode); + var withoutParens = clone; + while (ts.isParenthesizedTypeNode(withoutParens)) { + withoutParens = withoutParens.type; + } + return ts.isUnionTypeNode(withoutParens) && ts.find(withoutParens.types, function (t) { return t.kind === 141 /* UndefinedKeyword */; }) + ? clone + : ts.createUnionTypeNode([clone, ts.createKeywordTypeNode(141 /* UndefinedKeyword */)]); + } + } + /** + * Result of 'extractRange' operation for a specific scope. + * Stores either a list of changes that should be applied to extract a range or a list of errors + */ + function extractConstantInScope(node, scope, _a, rangeFacts, context) { + var substitutions = _a.substitutions; + var checker = context.program.getTypeChecker(); + // Make a unique name for the extracted variable + var file = scope.getSourceFile(); + var localNameText = ts.getUniqueName(ts.isClassLike(scope) ? "newProperty" : "newLocal", file); + var isJS = ts.isInJSFile(scope); + var variableType = isJS || !checker.isContextSensitive(node) + ? undefined + : checker.typeToTypeNode(checker.getContextualType(node), scope, 1 /* NoTruncation */); // TODO: GH#18217 + var initializer = transformConstantInitializer(node, substitutions); + ts.suppressLeadingAndTrailingTrivia(initializer); + var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); + if (ts.isClassLike(scope)) { + ts.Debug.assert(!isJS); // See CannotExtractToJSClass + var modifiers = []; + modifiers.push(ts.createToken(113 /* PrivateKeyword */)); + if (rangeFacts & RangeFacts.InStaticRegion) { + modifiers.push(ts.createToken(116 /* StaticKeyword */)); + } + modifiers.push(ts.createToken(133 /* ReadonlyKeyword */)); + var newVariable = ts.createProperty( + /*decorators*/ undefined, modifiers, localNameText, + /*questionToken*/ undefined, variableType, initializer); + var localReference = ts.createPropertyAccess(rangeFacts & RangeFacts.InStaticRegion + ? ts.createIdentifier(scope.name.getText()) // TODO: GH#18217 + : ts.createThis(), ts.createIdentifier(localNameText)); + // Declare + var maxInsertionPos = node.pos; + var nodeToInsertBefore = getNodeToInsertPropertyBefore(maxInsertionPos, scope); + changeTracker.insertNodeBefore(context.file, nodeToInsertBefore, newVariable, /*blankLineBetween*/ true); + // Consume + changeTracker.replaceNode(context.file, node, localReference); + } + else { + var newVariableDeclaration = ts.createVariableDeclaration(localNameText, variableType, initializer); + // If the node is part of an initializer in a list of variable declarations, insert a new + // variable declaration into the list (in case it depends on earlier ones). + // CONSIDER: If the declaration list isn't const, we might want to split it into multiple + // lists so that the newly extracted one can be const. + var oldVariableDeclaration = getContainingVariableDeclarationIfInList(node, scope); + if (oldVariableDeclaration) { + // Declare + // CONSIDER: could detect that each is on a separate line (See `extractConstant_VariableList_MultipleLines` in `extractConstants.ts`) + changeTracker.insertNodeBefore(context.file, oldVariableDeclaration, newVariableDeclaration); + // Consume + var localReference = ts.createIdentifier(localNameText); + changeTracker.replaceNode(context.file, node, localReference); + } + else if (node.parent.kind === 221 /* ExpressionStatement */ && scope === ts.findAncestor(node, isScope)) { + // If the parent is an expression statement and the target scope is the immediately enclosing one, + // replace the statement with the declaration. + var newVariableStatement = ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([newVariableDeclaration], 2 /* Const */)); + changeTracker.replaceNode(context.file, node.parent, newVariableStatement); + } + else { + var newVariableStatement = ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([newVariableDeclaration], 2 /* Const */)); + // Declare + var nodeToInsertBefore = getNodeToInsertConstantBefore(node, scope); + if (nodeToInsertBefore.pos === 0) { + changeTracker.insertNodeAtTopOfFile(context.file, newVariableStatement, /*blankLineBetween*/ false); + } + else { + changeTracker.insertNodeBefore(context.file, nodeToInsertBefore, newVariableStatement, /*blankLineBetween*/ false); + } + // Consume + if (node.parent.kind === 221 /* ExpressionStatement */) { + // If the parent is an expression statement, delete it. + changeTracker.delete(context.file, node.parent); + } + else { + var localReference = ts.createIdentifier(localNameText); + changeTracker.replaceNode(context.file, node, localReference); + } + } + } + var edits = changeTracker.getChanges(); + var renameFilename = node.getSourceFile().fileName; + var renameLocation = ts.getRenameLocation(edits, renameFilename, localNameText, /*isDeclaredBeforeUse*/ true); + return { renameFilename: renameFilename, renameLocation: renameLocation, edits: edits }; + } + function getContainingVariableDeclarationIfInList(node, scope) { + var prevNode; + while (node !== undefined && node !== scope) { + if (ts.isVariableDeclaration(node) && + node.initializer === prevNode && + ts.isVariableDeclarationList(node.parent) && + node.parent.declarations.length > 1) { + return node; + } + prevNode = node; + node = node.parent; + } + } + function getFirstDeclaration(type) { + var firstDeclaration; + var symbol = type.symbol; + if (symbol && symbol.declarations) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (firstDeclaration === undefined || declaration.pos < firstDeclaration.pos) { + firstDeclaration = declaration; + } + } + } + return firstDeclaration; + } + function compareTypesByDeclarationOrder(_a, _b) { + var type1 = _a.type, declaration1 = _a.declaration; + var type2 = _b.type, declaration2 = _b.declaration; + return ts.compareProperties(declaration1, declaration2, "pos", ts.compareValues) + || ts.compareStringsCaseSensitive(type1.symbol ? type1.symbol.getName() : "", type2.symbol ? type2.symbol.getName() : "") + || ts.compareValues(type1.id, type2.id); + } + function getCalledExpression(scope, range, functionNameText) { + var functionReference = ts.createIdentifier(functionNameText); + if (ts.isClassLike(scope)) { + var lhs = range.facts & RangeFacts.InStaticRegion ? ts.createIdentifier(scope.name.text) : ts.createThis(); // TODO: GH#18217 + return ts.createPropertyAccess(lhs, functionReference); + } + else { + return functionReference; + } + } + function transformFunctionBody(body, exposedVariableDeclarations, writes, substitutions, hasReturn) { + var hasWritesOrVariableDeclarations = writes !== undefined || exposedVariableDeclarations.length > 0; + if (ts.isBlock(body) && !hasWritesOrVariableDeclarations && substitutions.size === 0) { + // already block, no declarations or writes to propagate back, no substitutions - can use node as is + return { body: ts.createBlock(body.statements, /*multLine*/ true), returnValueProperty: undefined }; + } + var returnValueProperty; + var ignoreReturns = false; + var statements = ts.createNodeArray(ts.isBlock(body) ? body.statements.slice(0) : [ts.isStatement(body) ? body : ts.createReturn(body)]); + // rewrite body if either there are writes that should be propagated back via return statements or there are substitutions + if (hasWritesOrVariableDeclarations || substitutions.size) { + var rewrittenStatements = ts.visitNodes(statements, visitor).slice(); + if (hasWritesOrVariableDeclarations && !hasReturn && ts.isStatement(body)) { + // add return at the end to propagate writes back in case if control flow falls out of the function body + // it is ok to know that range has at least one return since it we only allow unconditional returns + var assignments = getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes); + if (assignments.length === 1) { + rewrittenStatements.push(ts.createReturn(assignments[0].name)); + } + else { + rewrittenStatements.push(ts.createReturn(ts.createObjectLiteral(assignments))); + } + } + return { body: ts.createBlock(rewrittenStatements, /*multiLine*/ true), returnValueProperty: returnValueProperty }; + } + else { + return { body: ts.createBlock(statements, /*multiLine*/ true), returnValueProperty: undefined }; + } + function visitor(node) { + if (!ignoreReturns && node.kind === 230 /* ReturnStatement */ && hasWritesOrVariableDeclarations) { + var assignments = getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes); + if (node.expression) { + if (!returnValueProperty) { + returnValueProperty = "__return"; + } + assignments.unshift(ts.createPropertyAssignment(returnValueProperty, ts.visitNode(node.expression, visitor))); + } + if (assignments.length === 1) { + return ts.createReturn(assignments[0].name); + } + else { + return ts.createReturn(ts.createObjectLiteral(assignments)); + } + } + else { + var oldIgnoreReturns = ignoreReturns; + ignoreReturns = ignoreReturns || ts.isFunctionLikeDeclaration(node) || ts.isClassLike(node); + var substitution = substitutions.get(ts.getNodeId(node).toString()); + var result = substitution ? ts.getSynthesizedDeepClone(substitution) : ts.visitEachChild(node, visitor, ts.nullTransformationContext); + ignoreReturns = oldIgnoreReturns; + return result; + } + } + } + function transformConstantInitializer(initializer, substitutions) { + return substitutions.size + ? visitor(initializer) + : initializer; + function visitor(node) { + var substitution = substitutions.get(ts.getNodeId(node).toString()); + return substitution ? ts.getSynthesizedDeepClone(substitution) : ts.visitEachChild(node, visitor, ts.nullTransformationContext); + } + } + function getStatementsOrClassElements(scope) { + if (ts.isFunctionLikeDeclaration(scope)) { + var body = scope.body; // TODO: GH#18217 + if (ts.isBlock(body)) { + return body.statements; + } + } + else if (ts.isModuleBlock(scope) || ts.isSourceFile(scope)) { + return scope.statements; + } + else if (ts.isClassLike(scope)) { + return scope.members; + } + else { + ts.assertType(scope); + } + return ts.emptyArray; + } + /** + * If `scope` contains a function after `minPos`, then return the first such function. + * Otherwise, return `undefined`. + */ + function getNodeToInsertFunctionBefore(minPos, scope) { + return ts.find(getStatementsOrClassElements(scope), function (child) { + return child.pos >= minPos && ts.isFunctionLikeDeclaration(child) && !ts.isConstructorDeclaration(child); + }); + } + function getNodeToInsertPropertyBefore(maxPos, scope) { + var members = scope.members; + ts.Debug.assert(members.length > 0); // There must be at least one child, since we extracted from one. + var prevMember; + var allProperties = true; + for (var _i = 0, members_7 = members; _i < members_7.length; _i++) { + var member = members_7[_i]; + if (member.pos > maxPos) { + return prevMember || members[0]; + } + if (allProperties && !ts.isPropertyDeclaration(member)) { + // If it is non-vacuously true that all preceding members are properties, + // insert before the current member (i.e. at the end of the list of properties). + if (prevMember !== undefined) { + return member; + } + allProperties = false; + } + prevMember = member; + } + if (prevMember === undefined) + return ts.Debug.fail(); // If the loop didn't return, then it did set prevMember. + return prevMember; + } + function getNodeToInsertConstantBefore(node, scope) { + ts.Debug.assert(!ts.isClassLike(scope)); + var prevScope; + for (var curr = node; curr !== scope; curr = curr.parent) { + if (isScope(curr)) { + prevScope = curr; + } + } + for (var curr = (prevScope || node).parent;; curr = curr.parent) { + if (isBlockLike(curr)) { + var prevStatement = void 0; + for (var _i = 0, _a = curr.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + if (statement.pos > node.pos) { + break; + } + prevStatement = statement; + } + if (!prevStatement && ts.isCaseClause(curr)) { + // We must have been in the expression of the case clause. + ts.Debug.assert(ts.isSwitchStatement(curr.parent.parent)); + return curr.parent.parent; + } + // There must be at least one statement since we started in one. + return ts.Debug.assertDefined(prevStatement); + } + ts.Debug.assert(curr !== scope, "Didn't encounter a block-like before encountering scope"); + } + } + function getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes) { + var variableAssignments = ts.map(exposedVariableDeclarations, function (v) { return ts.createShorthandPropertyAssignment(v.symbol.name); }); + var writeAssignments = ts.map(writes, function (w) { return ts.createShorthandPropertyAssignment(w.symbol.name); }); + // TODO: GH#18217 `variableAssignments` not possibly undefined! + return variableAssignments === undefined + ? writeAssignments + : writeAssignments === undefined + ? variableAssignments + : variableAssignments.concat(writeAssignments); + } + function isReadonlyArray(v) { + return ts.isArray(v); + } + /** + * Produces a range that spans the entirety of nodes, given a selection + * that might start/end in the middle of nodes. + * + * For example, when the user makes a selection like this + * v---v + * var someThing = foo + bar; + * this returns ^-------^ + */ + function getEnclosingTextRange(targetRange, sourceFile) { + return isReadonlyArray(targetRange.range) + ? { pos: ts.first(targetRange.range).getStart(sourceFile), end: ts.last(targetRange.range).getEnd() } + : targetRange.range; + } + var Usage; + (function (Usage) { + // value should be passed to extracted method + Usage[Usage["Read"] = 1] = "Read"; + // value should be passed to extracted method and propagated back + Usage[Usage["Write"] = 2] = "Write"; + })(Usage || (Usage = {})); + function collectReadsAndWrites(targetRange, scopes, enclosingTextRange, sourceFile, checker, cancellationToken) { + var allTypeParameterUsages = ts.createMap(); // Key is type ID + var usagesPerScope = []; + var substitutionsPerScope = []; + var functionErrorsPerScope = []; + var constantErrorsPerScope = []; + var visibleDeclarationsInExtractedRange = []; + var exposedVariableSymbolSet = ts.createMap(); // Key is symbol ID + var exposedVariableDeclarations = []; + var firstExposedNonVariableDeclaration; + var expression = !isReadonlyArray(targetRange.range) + ? targetRange.range + : targetRange.range.length === 1 && ts.isExpressionStatement(targetRange.range[0]) + ? targetRange.range[0].expression + : undefined; + var expressionDiagnostic; + if (expression === undefined) { + var statements = targetRange.range; + var start = ts.first(statements).getStart(); + var end = ts.last(statements).end; + expressionDiagnostic = ts.createFileDiagnostic(sourceFile, start, end - start, Messages.expressionExpected); + } + else if (checker.getTypeAtLocation(expression).flags & (16384 /* Void */ | 131072 /* Never */)) { + expressionDiagnostic = ts.createDiagnosticForNode(expression, Messages.uselessConstantType); + } + // initialize results + for (var _i = 0, scopes_1 = scopes; _i < scopes_1.length; _i++) { + var scope = scopes_1[_i]; + usagesPerScope.push({ usages: ts.createMap(), typeParameterUsages: ts.createMap(), substitutions: ts.createMap() }); + substitutionsPerScope.push(ts.createMap()); + functionErrorsPerScope.push(ts.isFunctionLikeDeclaration(scope) && scope.kind !== 239 /* FunctionDeclaration */ + ? [ts.createDiagnosticForNode(scope, Messages.cannotExtractToOtherFunctionLike)] + : []); + var constantErrors = []; + if (expressionDiagnostic) { + constantErrors.push(expressionDiagnostic); + } + if (ts.isClassLike(scope) && ts.isInJSFile(scope)) { + constantErrors.push(ts.createDiagnosticForNode(scope, Messages.cannotExtractToJSClass)); + } + if (ts.isArrowFunction(scope) && !ts.isBlock(scope.body)) { + // TODO (https://github.com/Microsoft/TypeScript/issues/18924): allow this + constantErrors.push(ts.createDiagnosticForNode(scope, Messages.cannotExtractToExpressionArrowFunction)); + } + constantErrorsPerScope.push(constantErrors); + } + var seenUsages = ts.createMap(); + var target = isReadonlyArray(targetRange.range) ? ts.createBlock(targetRange.range) : targetRange.range; + var unmodifiedNode = isReadonlyArray(targetRange.range) ? ts.first(targetRange.range) : targetRange.range; + var inGenericContext = isInGenericContext(unmodifiedNode); + collectUsages(target); + // Unfortunately, this code takes advantage of the knowledge that the generated method + // will use the contextual type of an expression as the return type of the extracted + // method (and will therefore "use" all the types involved). + if (inGenericContext && !isReadonlyArray(targetRange.range)) { + var contextualType = checker.getContextualType(targetRange.range); // TODO: GH#18217 + recordTypeParameterUsages(contextualType); + } + if (allTypeParameterUsages.size > 0) { + var seenTypeParameterUsages = ts.createMap(); // Key is type ID + var i_1 = 0; + for (var curr = unmodifiedNode; curr !== undefined && i_1 < scopes.length; curr = curr.parent) { + if (curr === scopes[i_1]) { + // Copy current contents of seenTypeParameterUsages into scope. + seenTypeParameterUsages.forEach(function (typeParameter, id) { + usagesPerScope[i_1].typeParameterUsages.set(id, typeParameter); + }); + i_1++; + } + // Note that we add the current node's type parameters *after* updating the corresponding scope. + if (ts.isDeclarationWithTypeParameters(curr)) { + for (var _a = 0, _b = ts.getEffectiveTypeParameterDeclarations(curr); _a < _b.length; _a++) { + var typeParameterDecl = _b[_a]; + var typeParameter = checker.getTypeAtLocation(typeParameterDecl); + if (allTypeParameterUsages.has(typeParameter.id.toString())) { + seenTypeParameterUsages.set(typeParameter.id.toString(), typeParameter); + } + } + } + } + // If we didn't get through all the scopes, then there were some that weren't in our + // parent chain (impossible at time of writing). A conservative solution would be to + // copy allTypeParameterUsages into all remaining scopes. + ts.Debug.assert(i_1 === scopes.length); + } + // If there are any declarations in the extracted block that are used in the same enclosing + // lexical scope, we can't move the extraction "up" as those declarations will become unreachable + if (visibleDeclarationsInExtractedRange.length) { + var containingLexicalScopeOfExtraction = ts.isBlockScope(scopes[0], scopes[0].parent) + ? scopes[0] + : ts.getEnclosingBlockScopeContainer(scopes[0]); + ts.forEachChild(containingLexicalScopeOfExtraction, checkForUsedDeclarations); + } + var _loop_22 = function (i) { + var scopeUsages = usagesPerScope[i]; + // Special case: in the innermost scope, all usages are available. + // (The computed value reflects the value at the top-level of the scope, but the + // local will actually be declared at the same level as the extracted expression). + if (i > 0 && (scopeUsages.usages.size > 0 || scopeUsages.typeParameterUsages.size > 0)) { + var errorNode = isReadonlyArray(targetRange.range) ? targetRange.range[0] : targetRange.range; + constantErrorsPerScope[i].push(ts.createDiagnosticForNode(errorNode, Messages.cannotAccessVariablesFromNestedScopes)); + } + var hasWrite = false; + var readonlyClassPropertyWrite; + usagesPerScope[i].usages.forEach(function (value) { + if (value.usage === 2 /* Write */) { + hasWrite = true; + if (value.symbol.flags & 106500 /* ClassMember */ && + value.symbol.valueDeclaration && + ts.hasModifier(value.symbol.valueDeclaration, 64 /* Readonly */)) { + readonlyClassPropertyWrite = value.symbol.valueDeclaration; + } + } + }); + // If an expression was extracted, then there shouldn't have been any variable declarations. + ts.Debug.assert(isReadonlyArray(targetRange.range) || exposedVariableDeclarations.length === 0); + if (hasWrite && !isReadonlyArray(targetRange.range)) { + var diag = ts.createDiagnosticForNode(targetRange.range, Messages.cannotWriteInExpression); + functionErrorsPerScope[i].push(diag); + constantErrorsPerScope[i].push(diag); + } + else if (readonlyClassPropertyWrite && i > 0) { + var diag = ts.createDiagnosticForNode(readonlyClassPropertyWrite, Messages.cannotExtractReadonlyPropertyInitializerOutsideConstructor); + functionErrorsPerScope[i].push(diag); + constantErrorsPerScope[i].push(diag); + } + else if (firstExposedNonVariableDeclaration) { + var diag = ts.createDiagnosticForNode(firstExposedNonVariableDeclaration, Messages.cannotExtractExportedEntity); + functionErrorsPerScope[i].push(diag); + constantErrorsPerScope[i].push(diag); + } + }; + for (var i = 0; i < scopes.length; i++) { + _loop_22(i); + } + return { target: target, usagesPerScope: usagesPerScope, functionErrorsPerScope: functionErrorsPerScope, constantErrorsPerScope: constantErrorsPerScope, exposedVariableDeclarations: exposedVariableDeclarations }; + function isInGenericContext(node) { + return !!ts.findAncestor(node, function (n) { return ts.isDeclarationWithTypeParameters(n) && ts.getEffectiveTypeParameterDeclarations(n).length !== 0; }); + } + function recordTypeParameterUsages(type) { + // PERF: This is potentially very expensive. `type` could be a library type with + // a lot of properties, each of which the walker will visit. Unfortunately, the + // solution isn't as trivial as filtering to user types because of (e.g.) Array. + var symbolWalker = checker.getSymbolWalker(function () { return (cancellationToken.throwIfCancellationRequested(), true); }); + var visitedTypes = symbolWalker.walkType(type).visitedTypes; + for (var _i = 0, visitedTypes_1 = visitedTypes; _i < visitedTypes_1.length; _i++) { + var visitedType = visitedTypes_1[_i]; + if (visitedType.isTypeParameter()) { + allTypeParameterUsages.set(visitedType.id.toString(), visitedType); + } + } + } + function collectUsages(node, valueUsage) { + if (valueUsage === void 0) { valueUsage = 1 /* Read */; } + if (inGenericContext) { + var type = checker.getTypeAtLocation(node); + recordTypeParameterUsages(type); + } + if (ts.isDeclaration(node) && node.symbol) { + visibleDeclarationsInExtractedRange.push(node); + } + if (ts.isAssignmentExpression(node)) { + // use 'write' as default usage for values + collectUsages(node.left, 2 /* Write */); + collectUsages(node.right); + } + else if (ts.isUnaryExpressionWithWrite(node)) { + collectUsages(node.operand, 2 /* Write */); + } + else if (ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node)) { + // use 'write' as default usage for values + ts.forEachChild(node, collectUsages); + } + else if (ts.isIdentifier(node)) { + if (!node.parent) { + return; + } + if (ts.isQualifiedName(node.parent) && node !== node.parent.left) { + return; + } + if (ts.isPropertyAccessExpression(node.parent) && node !== node.parent.expression) { + return; + } + recordUsage(node, valueUsage, /*isTypeNode*/ ts.isPartOfTypeNode(node)); + } + else { + ts.forEachChild(node, collectUsages); + } + } + function recordUsage(n, usage, isTypeNode) { + var symbolId = recordUsagebySymbol(n, usage, isTypeNode); + if (symbolId) { + for (var i = 0; i < scopes.length; i++) { + // push substitution from map to map to simplify rewriting + var substitution = substitutionsPerScope[i].get(symbolId); + if (substitution) { + usagesPerScope[i].substitutions.set(ts.getNodeId(n).toString(), substitution); + } + } + } + } + function recordUsagebySymbol(identifier, usage, isTypeName) { + var symbol = getSymbolReferencedByIdentifier(identifier); + if (!symbol) { + // cannot find symbol - do nothing + return undefined; + } + var symbolId = ts.getSymbolId(symbol).toString(); + var lastUsage = seenUsages.get(symbolId); + // there are two kinds of value usages + // - reads - if range contains a read from the value located outside of the range then value should be passed as a parameter + // - writes - if range contains a write to a value located outside the range the value should be passed as a parameter and + // returned as a return value + // 'write' case is a superset of 'read' so if we already have processed 'write' of some symbol there is not need to handle 'read' + // since all information is already recorded + if (lastUsage && lastUsage >= usage) { + return symbolId; + } + seenUsages.set(symbolId, usage); + if (lastUsage) { + // if we get here this means that we are trying to handle 'write' and 'read' was already processed + // walk scopes and update existing records. + for (var _i = 0, usagesPerScope_1 = usagesPerScope; _i < usagesPerScope_1.length; _i++) { + var perScope = usagesPerScope_1[_i]; + var prevEntry = perScope.usages.get(identifier.text); + if (prevEntry) { + perScope.usages.set(identifier.text, { usage: usage, symbol: symbol, node: identifier }); + } + } + return symbolId; + } + // find first declaration in this file + var decls = symbol.getDeclarations(); + var declInFile = decls && ts.find(decls, function (d) { return d.getSourceFile() === sourceFile; }); + if (!declInFile) { + return undefined; + } + if (ts.rangeContainsStartEnd(enclosingTextRange, declInFile.getStart(), declInFile.end)) { + // declaration is located in range to be extracted - do nothing + return undefined; + } + if (targetRange.facts & RangeFacts.IsGenerator && usage === 2 /* Write */) { + // this is write to a reference located outside of the target scope and range is extracted into generator + // currently this is unsupported scenario + var diag = ts.createDiagnosticForNode(identifier, Messages.cannotExtractRangeThatContainsWritesToReferencesLocatedOutsideOfTheTargetRangeInGenerators); + for (var _a = 0, functionErrorsPerScope_1 = functionErrorsPerScope; _a < functionErrorsPerScope_1.length; _a++) { + var errors = functionErrorsPerScope_1[_a]; + errors.push(diag); + } + for (var _b = 0, constantErrorsPerScope_1 = constantErrorsPerScope; _b < constantErrorsPerScope_1.length; _b++) { + var errors = constantErrorsPerScope_1[_b]; + errors.push(diag); + } + } + for (var i = 0; i < scopes.length; i++) { + var scope = scopes[i]; + var resolvedSymbol = checker.resolveName(symbol.name, scope, symbol.flags, /*excludeGlobals*/ false); + if (resolvedSymbol === symbol) { + continue; + } + if (!substitutionsPerScope[i].has(symbolId)) { + var substitution = tryReplaceWithQualifiedNameOrPropertyAccess(symbol.exportSymbol || symbol, scope, isTypeName); + if (substitution) { + substitutionsPerScope[i].set(symbolId, substitution); + } + else if (isTypeName) { + // If the symbol is a type parameter that won't be in scope, we'll pass it as a type argument + // so there's no problem. + if (!(symbol.flags & 262144 /* TypeParameter */)) { + var diag = ts.createDiagnosticForNode(identifier, Messages.typeWillNotBeVisibleInTheNewScope); + functionErrorsPerScope[i].push(diag); + constantErrorsPerScope[i].push(diag); + } + } + else { + usagesPerScope[i].usages.set(identifier.text, { usage: usage, symbol: symbol, node: identifier }); + } + } + } + return symbolId; + } + function checkForUsedDeclarations(node) { + // If this node is entirely within the original extraction range, we don't need to do anything. + if (node === targetRange.range || (isReadonlyArray(targetRange.range) && targetRange.range.indexOf(node) >= 0)) { + return; + } + // Otherwise check and recurse. + var sym = ts.isIdentifier(node) + ? getSymbolReferencedByIdentifier(node) + : checker.getSymbolAtLocation(node); + if (sym) { + var decl = ts.find(visibleDeclarationsInExtractedRange, function (d) { return d.symbol === sym; }); + if (decl) { + if (ts.isVariableDeclaration(decl)) { + var idString = decl.symbol.id.toString(); + if (!exposedVariableSymbolSet.has(idString)) { + exposedVariableDeclarations.push(decl); + exposedVariableSymbolSet.set(idString, true); + } + } + else { + // CONSIDER: this includes binding elements, which we could + // expose in the same way as variables. + firstExposedNonVariableDeclaration = firstExposedNonVariableDeclaration || decl; + } + } + } + ts.forEachChild(node, checkForUsedDeclarations); + } + /** + * Return the symbol referenced by an identifier (even if it declares a different symbol). + */ + function getSymbolReferencedByIdentifier(identifier) { + // If the identifier is both a property name and its value, we're only interested in its value + // (since the name is a declaration and will be included in the extracted range). + return identifier.parent && ts.isShorthandPropertyAssignment(identifier.parent) && identifier.parent.name === identifier + ? checker.getShorthandAssignmentValueSymbol(identifier.parent) + : checker.getSymbolAtLocation(identifier); + } + function tryReplaceWithQualifiedNameOrPropertyAccess(symbol, scopeDecl, isTypeNode) { + if (!symbol) { + return undefined; + } + var decls = symbol.getDeclarations(); + if (decls && decls.some(function (d) { return d.parent === scopeDecl; })) { + return ts.createIdentifier(symbol.name); + } + var prefix = tryReplaceWithQualifiedNameOrPropertyAccess(symbol.parent, scopeDecl, isTypeNode); + if (prefix === undefined) { + return undefined; + } + return isTypeNode + ? ts.createQualifiedName(prefix, ts.createIdentifier(symbol.name)) + : ts.createPropertyAccess(prefix, symbol.name); + } + } + /** + * Computes whether or not a node represents an expression in a position where it could + * be extracted. + * The isExpression() in utilities.ts returns some false positives we need to handle, + * such as `import x from 'y'` -- the 'y' is a StringLiteral but is *not* an expression + * in the sense of something that you could extract on + */ + function isExtractableExpression(node) { + var parent = node.parent; + switch (parent.kind) { + case 278 /* EnumMember */: + return false; + } + switch (node.kind) { + case 10 /* StringLiteral */: + return parent.kind !== 249 /* ImportDeclaration */ && + parent.kind !== 253 /* ImportSpecifier */; + case 208 /* SpreadElement */: + case 184 /* ObjectBindingPattern */: + case 186 /* BindingElement */: + return false; + case 72 /* Identifier */: + return parent.kind !== 186 /* BindingElement */ && + parent.kind !== 253 /* ImportSpecifier */ && + parent.kind !== 257 /* ExportSpecifier */; + } + return true; + } + function isBlockLike(node) { + switch (node.kind) { + case 218 /* Block */: + case 279 /* SourceFile */: + case 245 /* ModuleBlock */: + case 271 /* CaseClause */: + return true; + default: + return false; + } + } + })(extractSymbol = refactor.extractSymbol || (refactor.extractSymbol = {})); + })(refactor = ts.refactor || (ts.refactor = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var refactor; + (function (refactor) { + var generateGetAccessorAndSetAccessor; + (function (generateGetAccessorAndSetAccessor) { + var actionName = "Generate 'get' and 'set' accessors"; + var actionDescription = ts.Diagnostics.Generate_get_and_set_accessors.message; + refactor.registerRefactor(actionName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions }); + function getAvailableActions(context) { + if (!getConvertibleFieldAtPosition(context)) + return ts.emptyArray; + return [{ + name: actionName, + description: actionDescription, + actions: [ + { + name: actionName, + description: actionDescription + } + ] + }]; + } + function getEditsForAction(context, _actionName) { + var file = context.file; + var fieldInfo = getConvertibleFieldAtPosition(context); + if (!fieldInfo) + return undefined; + var isJS = ts.isSourceFileJS(file); + var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); + var isStatic = fieldInfo.isStatic, isReadonly = fieldInfo.isReadonly, fieldName = fieldInfo.fieldName, accessorName = fieldInfo.accessorName, originalName = fieldInfo.originalName, type = fieldInfo.type, container = fieldInfo.container, declaration = fieldInfo.declaration, renameAccessor = fieldInfo.renameAccessor; + ts.suppressLeadingAndTrailingTrivia(fieldName); + ts.suppressLeadingAndTrailingTrivia(declaration); + ts.suppressLeadingAndTrailingTrivia(container); + var isInClassLike = ts.isClassLike(container); + // avoid Readonly modifier because it will convert to get accessor + var modifierFlags = ts.getModifierFlags(declaration) & ~64 /* Readonly */; + var accessorModifiers = isInClassLike + ? !modifierFlags || modifierFlags & 8 /* Private */ + ? getModifiers(isJS, isStatic, 115 /* PublicKeyword */) + : ts.createNodeArray(ts.createModifiersFromModifierFlags(modifierFlags)) + : undefined; + var fieldModifiers = isInClassLike ? getModifiers(isJS, isStatic, 113 /* PrivateKeyword */) : undefined; + updateFieldDeclaration(changeTracker, file, declaration, fieldName, fieldModifiers); + var getAccessor = generateGetAccessor(fieldName, accessorName, type, accessorModifiers, isStatic, container); + ts.suppressLeadingAndTrailingTrivia(getAccessor); + insertAccessor(changeTracker, file, getAccessor, declaration, container); + if (isReadonly) { + // readonly modifier only existed in classLikeDeclaration + var constructor = ts.getFirstConstructorWithBody(container); + if (constructor) { + updateReadonlyPropertyInitializerStatementConstructor(changeTracker, file, constructor, fieldName.text, originalName); + } + } + else { + var setAccessor = generateSetAccessor(fieldName, accessorName, type, accessorModifiers, isStatic, container); + ts.suppressLeadingAndTrailingTrivia(setAccessor); + insertAccessor(changeTracker, file, setAccessor, declaration, container); + } + var edits = changeTracker.getChanges(); + var renameFilename = file.fileName; + var nameNeedRename = renameAccessor ? accessorName : fieldName; + var renameLocationOffset = ts.isIdentifier(nameNeedRename) ? 0 : -1; + var renameLocation = renameLocationOffset + ts.getRenameLocation(edits, renameFilename, nameNeedRename.text, /*preferLastLocation*/ ts.isParameter(declaration)); + return { renameFilename: renameFilename, renameLocation: renameLocation, edits: edits }; + } + function isConvertibleName(name) { + return ts.isIdentifier(name) || ts.isStringLiteral(name); + } + function isAcceptedDeclaration(node) { + return ts.isParameterPropertyDeclaration(node) || ts.isPropertyDeclaration(node) || ts.isPropertyAssignment(node); + } + function createPropertyName(name, originalName) { + return ts.isIdentifier(originalName) ? ts.createIdentifier(name) : ts.createLiteral(name); + } + function createAccessorAccessExpression(fieldName, isStatic, container) { + var leftHead = isStatic ? container.name : ts.createThis(); // TODO: GH#18217 + return ts.isIdentifier(fieldName) ? ts.createPropertyAccess(leftHead, fieldName) : ts.createElementAccess(leftHead, ts.createLiteral(fieldName)); + } + function getModifiers(isJS, isStatic, accessModifier) { + var modifiers = ts.append(!isJS ? [ts.createToken(accessModifier)] : undefined, isStatic ? ts.createToken(116 /* StaticKeyword */) : undefined); + return modifiers && ts.createNodeArray(modifiers); + } + function startsWithUnderscore(name) { + return name.charCodeAt(0) === 95 /* _ */; + } + function getConvertibleFieldAtPosition(context) { + var file = context.file, startPosition = context.startPosition, endPosition = context.endPosition; + var node = ts.getTokenAtPosition(file, startPosition); + var declaration = ts.findAncestor(node.parent, isAcceptedDeclaration); + // make sure declaration have AccessibilityModifier or Static Modifier or Readonly Modifier + var meaning = 28 /* AccessibilityModifier */ | 32 /* Static */ | 64 /* Readonly */; + if (!declaration || !ts.nodeOverlapsWithStartEnd(declaration.name, file, startPosition, endPosition) // TODO: GH#18217 + || !isConvertibleName(declaration.name) || (ts.getModifierFlags(declaration) | meaning) !== meaning) + return undefined; + var name = declaration.name.text; + var startWithUnderscore = startsWithUnderscore(name); + var fieldName = createPropertyName(startWithUnderscore ? name : ts.getUniqueName("_" + name, file), declaration.name); + var accessorName = createPropertyName(startWithUnderscore ? ts.getUniqueName(name.substring(1), file) : name, declaration.name); + return { + isStatic: ts.hasStaticModifier(declaration), + isReadonly: ts.hasReadonlyModifier(declaration), + type: ts.getTypeAnnotationNode(declaration), + container: declaration.kind === 151 /* Parameter */ ? declaration.parent.parent : declaration.parent, + originalName: declaration.name.text, + declaration: declaration, + fieldName: fieldName, + accessorName: accessorName, + renameAccessor: startWithUnderscore + }; + } + function generateGetAccessor(fieldName, accessorName, type, modifiers, isStatic, container) { + return ts.createGetAccessor( + /*decorators*/ undefined, modifiers, accessorName, + /*parameters*/ undefined, // TODO: GH#18217 + type, ts.createBlock([ + ts.createReturn(createAccessorAccessExpression(fieldName, isStatic, container)) + ], /*multiLine*/ true)); + } + function generateSetAccessor(fieldName, accessorName, type, modifiers, isStatic, container) { + return ts.createSetAccessor( + /*decorators*/ undefined, modifiers, accessorName, [ts.createParameter( + /*decorators*/ undefined, + /*modifiers*/ undefined, + /*dotDotDotToken*/ undefined, ts.createIdentifier("value"), + /*questionToken*/ undefined, type)], ts.createBlock([ + ts.createStatement(ts.createAssignment(createAccessorAccessExpression(fieldName, isStatic, container), ts.createIdentifier("value"))) + ], /*multiLine*/ true)); + } + function updatePropertyDeclaration(changeTracker, file, declaration, fieldName, modifiers) { + var property = ts.updateProperty(declaration, declaration.decorators, modifiers, fieldName, declaration.questionToken || declaration.exclamationToken, declaration.type, declaration.initializer); + changeTracker.replaceNode(file, declaration, property); + } + function updatePropertyAssignmentDeclaration(changeTracker, file, declaration, fieldName) { + var assignment = ts.updatePropertyAssignment(declaration, fieldName, declaration.initializer); + changeTracker.replacePropertyAssignment(file, declaration, assignment); + } + function updateFieldDeclaration(changeTracker, file, declaration, fieldName, modifiers) { + if (ts.isPropertyDeclaration(declaration)) { + updatePropertyDeclaration(changeTracker, file, declaration, fieldName, modifiers); + } + else if (ts.isPropertyAssignment(declaration)) { + updatePropertyAssignmentDeclaration(changeTracker, file, declaration, fieldName); + } + else { + changeTracker.replaceNode(file, declaration, ts.updateParameter(declaration, declaration.decorators, modifiers, declaration.dotDotDotToken, ts.cast(fieldName, ts.isIdentifier), declaration.questionToken, declaration.type, declaration.initializer)); + } + } + function insertAccessor(changeTracker, file, accessor, declaration, container) { + ts.isParameterPropertyDeclaration(declaration) + ? changeTracker.insertNodeAtClassStart(file, container, accessor) + : ts.isPropertyAssignment(declaration) + ? changeTracker.insertNodeAfterComma(file, declaration, accessor) + : changeTracker.insertNodeAfter(file, declaration, accessor); + } + function updateReadonlyPropertyInitializerStatementConstructor(changeTracker, file, constructor, fieldName, originalName) { + if (!constructor.body) + return; + constructor.body.forEachChild(function recur(node) { + if (ts.isElementAccessExpression(node) && + node.expression.kind === 100 /* ThisKeyword */ && + ts.isStringLiteral(node.argumentExpression) && + node.argumentExpression.text === originalName && + ts.isWriteAccess(node)) { + changeTracker.replaceNode(file, node.argumentExpression, ts.createStringLiteral(fieldName)); + } + if (ts.isPropertyAccessExpression(node) && node.expression.kind === 100 /* ThisKeyword */ && node.name.text === originalName && ts.isWriteAccess(node)) { + changeTracker.replaceNode(file, node.name, ts.createIdentifier(fieldName)); + } + if (!ts.isFunctionLike(node) && !ts.isClassLike(node)) { + node.forEachChild(recur); + } + }); + } + })(generateGetAccessorAndSetAccessor = refactor.generateGetAccessorAndSetAccessor || (refactor.generateGetAccessorAndSetAccessor = {})); + })(refactor = ts.refactor || (ts.refactor = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var refactor; + (function (refactor) { + var refactorName = "Move to a new file"; + refactor.registerRefactor(refactorName, { + getAvailableActions: function (context) { + if (!context.preferences.allowTextChangesInNewFiles || getStatementsToMove(context) === undefined) + return ts.emptyArray; + var description = ts.getLocaleSpecificMessage(ts.Diagnostics.Move_to_a_new_file); + return [{ name: refactorName, description: description, actions: [{ name: refactorName, description: description }] }]; + }, + getEditsForAction: function (context, actionName) { + ts.Debug.assert(actionName === refactorName); + var statements = ts.Debug.assertDefined(getStatementsToMove(context)); + var edits = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(context.file, context.program, statements, t, context.host, context.preferences); }); + return { edits: edits, renameFilename: undefined, renameLocation: undefined }; + } + }); + function getRangeToMove(context) { + var file = context.file; + var range = ts.createTextRangeFromSpan(ts.getRefactorContextSpan(context)); + var statements = file.statements; + var startNodeIndex = ts.findIndex(statements, function (s) { return s.end > range.pos; }); + if (startNodeIndex === -1) + return undefined; + var startStatement = statements[startNodeIndex]; + if (ts.isNamedDeclaration(startStatement) && startStatement.name && ts.rangeContainsRange(startStatement.name, range)) { + return { toMove: [statements[startNodeIndex]], afterLast: statements[startNodeIndex + 1] }; + } + // Can't only partially include the start node or be partially into the next node + if (range.pos > startStatement.getStart(file)) + return undefined; + var afterEndNodeIndex = ts.findIndex(statements, function (s) { return s.end > range.end; }, startNodeIndex); + // Can't be partially into the next node + if (afterEndNodeIndex !== -1 && (afterEndNodeIndex === 0 || statements[afterEndNodeIndex].getStart(file) < range.end)) + return undefined; + return { + toMove: statements.slice(startNodeIndex, afterEndNodeIndex === -1 ? statements.length : afterEndNodeIndex), + afterLast: afterEndNodeIndex === -1 ? undefined : statements[afterEndNodeIndex], + }; + } + function doChange(oldFile, program, toMove, changes, host, preferences) { + var checker = program.getTypeChecker(); + var usage = getUsageInfo(oldFile, toMove.all, checker); + var currentDirectory = ts.getDirectoryPath(oldFile.fileName); + var extension = ts.extensionFromPath(oldFile.fileName); + var newModuleName = makeUniqueModuleName(getNewModuleName(usage.movedSymbols), extension, currentDirectory, host); + var newFileNameWithExtension = newModuleName + extension; + // If previous file was global, this is easy. + changes.createNewFile(oldFile, ts.combinePaths(currentDirectory, newFileNameWithExtension), getNewStatementsAndRemoveFromOldFile(oldFile, usage, changes, toMove, program, newModuleName, preferences)); + addNewFileToTsconfig(program, changes, oldFile.fileName, newFileNameWithExtension, ts.hostGetCanonicalFileName(host)); + } + // Filters imports out of the range of statements to move. Imports will be copied to the new file anyway, and may still be needed in the old file. + function getStatementsToMove(context) { + var rangeToMove = getRangeToMove(context); + if (rangeToMove === undefined) + return undefined; + var all = []; + var ranges = []; + var toMove = rangeToMove.toMove, afterLast = rangeToMove.afterLast; + ts.getRangesWhere(toMove, function (s) { return !isPureImport(s); }, function (start, afterEndIndex) { + for (var i = start; i < afterEndIndex; i++) + all.push(toMove[i]); + ranges.push({ first: toMove[start], afterLast: afterLast }); + }); + return all.length === 0 ? undefined : { all: all, ranges: ranges }; + } + function isPureImport(node) { + switch (node.kind) { + case 249 /* ImportDeclaration */: + return true; + case 248 /* ImportEqualsDeclaration */: + return !ts.hasModifier(node, 1 /* Export */); + case 219 /* VariableStatement */: + return node.declarationList.declarations.every(function (d) { return !!d.initializer && ts.isRequireCall(d.initializer, /*checkArgumentIsStringLiteralLike*/ true); }); + default: + return false; + } + } + function addNewFileToTsconfig(program, changes, oldFileName, newFileNameWithExtension, getCanonicalFileName) { + var cfg = program.getCompilerOptions().configFile; + if (!cfg) + return; + var newFileAbsolutePath = ts.normalizePath(ts.combinePaths(oldFileName, "..", newFileNameWithExtension)); + var newFilePath = ts.getRelativePathFromFile(cfg.fileName, newFileAbsolutePath, getCanonicalFileName); + var cfgObject = cfg.statements[0] && ts.tryCast(cfg.statements[0].expression, ts.isObjectLiteralExpression); + var filesProp = cfgObject && ts.find(cfgObject.properties, function (prop) { + return ts.isPropertyAssignment(prop) && ts.isStringLiteral(prop.name) && prop.name.text === "files"; + }); + if (filesProp && ts.isArrayLiteralExpression(filesProp.initializer)) { + changes.insertNodeInListAfter(cfg, ts.last(filesProp.initializer.elements), ts.createLiteral(newFilePath), filesProp.initializer.elements); + } + } + function getNewStatementsAndRemoveFromOldFile(oldFile, usage, changes, toMove, program, newModuleName, preferences) { + var checker = program.getTypeChecker(); + if (!oldFile.externalModuleIndicator && !oldFile.commonJsModuleIndicator) { + deleteMovedStatements(oldFile, toMove.ranges, changes); + return toMove.all; + } + var useEs6ModuleSyntax = !!oldFile.externalModuleIndicator; + var quotePreference = ts.getQuotePreference(oldFile, preferences); + var importsFromNewFile = createOldFileImportsFromNewFile(usage.oldFileImportsFromNewFile, newModuleName, useEs6ModuleSyntax, quotePreference); + if (importsFromNewFile) { + ts.insertImport(changes, oldFile, importsFromNewFile); + } + deleteUnusedOldImports(oldFile, toMove.all, changes, usage.unusedImportsFromOldFile, checker); + deleteMovedStatements(oldFile, toMove.ranges, changes); + updateImportsInOtherFiles(changes, program, oldFile, usage.movedSymbols, newModuleName); + return getNewFileImportsAndAddExportInOldFile(oldFile, usage.oldImportsNeededByNewFile, usage.newFileImportsFromOldFile, changes, checker, useEs6ModuleSyntax, quotePreference).concat(addExports(oldFile, toMove.all, usage.oldFileImportsFromNewFile, useEs6ModuleSyntax)); + } + function deleteMovedStatements(sourceFile, moved, changes) { + for (var _i = 0, moved_1 = moved; _i < moved_1.length; _i++) { + var _a = moved_1[_i], first_1 = _a.first, afterLast = _a.afterLast; + changes.deleteNodeRangeExcludingEnd(sourceFile, first_1, afterLast); + } + } + function deleteUnusedOldImports(oldFile, toMove, changes, toDelete, checker) { + for (var _i = 0, _a = oldFile.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + if (ts.contains(toMove, statement)) + continue; + forEachImportInStatement(statement, function (i) { return deleteUnusedImports(oldFile, i, changes, function (name) { return toDelete.has(checker.getSymbolAtLocation(name)); }); }); + } + } + function updateImportsInOtherFiles(changes, program, oldFile, movedSymbols, newModuleName) { + var checker = program.getTypeChecker(); + var _loop_23 = function (sourceFile) { + if (sourceFile === oldFile) + return "continue"; + var _loop_24 = function (statement) { + forEachImportInStatement(statement, function (importNode) { + if (checker.getSymbolAtLocation(moduleSpecifierFromImport(importNode)) !== oldFile.symbol) + return; + var shouldMove = function (name) { + var symbol = ts.isBindingElement(name.parent) + ? ts.getPropertySymbolFromBindingElement(checker, name.parent) + : ts.skipAlias(checker.getSymbolAtLocation(name), checker); // TODO: GH#18217 + return !!symbol && movedSymbols.has(symbol); + }; + deleteUnusedImports(sourceFile, importNode, changes, shouldMove); // These will be changed to imports from the new file + var newModuleSpecifier = ts.combinePaths(ts.getDirectoryPath(moduleSpecifierFromImport(importNode).text), newModuleName); + var newImportDeclaration = filterImport(importNode, ts.createLiteral(newModuleSpecifier), shouldMove); + if (newImportDeclaration) + changes.insertNodeAfter(sourceFile, statement, newImportDeclaration); + var ns = getNamespaceLikeImport(importNode); + if (ns) + updateNamespaceLikeImport(changes, sourceFile, checker, movedSymbols, newModuleName, newModuleSpecifier, ns, importNode); + }); + }; + for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + _loop_24(statement); + } + }; + for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { + var sourceFile = _a[_i]; + _loop_23(sourceFile); + } + } + function getNamespaceLikeImport(node) { + switch (node.kind) { + case 249 /* ImportDeclaration */: + return node.importClause && node.importClause.namedBindings && node.importClause.namedBindings.kind === 251 /* NamespaceImport */ ? + node.importClause.namedBindings.name : undefined; + case 248 /* ImportEqualsDeclaration */: + return node.name; + case 237 /* VariableDeclaration */: + return ts.tryCast(node.name, ts.isIdentifier); + default: + return ts.Debug.assertNever(node); + } + } + function updateNamespaceLikeImport(changes, sourceFile, checker, movedSymbols, newModuleName, newModuleSpecifier, oldImportId, oldImportNode) { + var preferredNewNamespaceName = ts.codefix.moduleSpecifierToValidIdentifier(newModuleName, 6 /* ESNext */); + var needUniqueName = false; + var toChange = []; + ts.FindAllReferences.Core.eachSymbolReferenceInFile(oldImportId, checker, sourceFile, function (ref) { + if (!ts.isPropertyAccessExpression(ref.parent)) + return; + needUniqueName = needUniqueName || !!checker.resolveName(preferredNewNamespaceName, ref, 67108863 /* All */, /*excludeGlobals*/ true); + if (movedSymbols.has(checker.getSymbolAtLocation(ref.parent.name))) { + toChange.push(ref); + } + }); + if (toChange.length) { + var newNamespaceName = needUniqueName ? ts.getUniqueName(preferredNewNamespaceName, sourceFile) : preferredNewNamespaceName; + for (var _i = 0, toChange_1 = toChange; _i < toChange_1.length; _i++) { + var ref = toChange_1[_i]; + changes.replaceNode(sourceFile, ref, ts.createIdentifier(newNamespaceName)); + } + changes.insertNodeAfter(sourceFile, oldImportNode, updateNamespaceLikeImportNode(oldImportNode, newModuleName, newModuleSpecifier)); + } + } + function updateNamespaceLikeImportNode(node, newNamespaceName, newModuleSpecifier) { + var newNamespaceId = ts.createIdentifier(newNamespaceName); + var newModuleString = ts.createLiteral(newModuleSpecifier); + switch (node.kind) { + case 249 /* ImportDeclaration */: + return ts.createImportDeclaration( + /*decorators*/ undefined, /*modifiers*/ undefined, ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(newNamespaceId)), newModuleString); + case 248 /* ImportEqualsDeclaration */: + return ts.createImportEqualsDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, newNamespaceId, ts.createExternalModuleReference(newModuleString)); + case 237 /* VariableDeclaration */: + return ts.createVariableDeclaration(newNamespaceId, /*type*/ undefined, createRequireCall(newModuleString)); + default: + return ts.Debug.assertNever(node); + } + } + function moduleSpecifierFromImport(i) { + return (i.kind === 249 /* ImportDeclaration */ ? i.moduleSpecifier + : i.kind === 248 /* ImportEqualsDeclaration */ ? i.moduleReference.expression + : i.initializer.arguments[0]); + } + function forEachImportInStatement(statement, cb) { + if (ts.isImportDeclaration(statement)) { + if (ts.isStringLiteral(statement.moduleSpecifier)) + cb(statement); + } + else if (ts.isImportEqualsDeclaration(statement)) { + if (ts.isExternalModuleReference(statement.moduleReference) && ts.isStringLiteralLike(statement.moduleReference.expression)) { + cb(statement); + } + } + else if (ts.isVariableStatement(statement)) { + for (var _i = 0, _a = statement.declarationList.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + if (decl.initializer && ts.isRequireCall(decl.initializer, /*checkArgumentIsStringLiteralLike*/ true)) { + cb(decl); + } + } + } + } + function createOldFileImportsFromNewFile(newFileNeedExport, newFileNameWithExtension, useEs6Imports, quotePreference) { + var defaultImport; + var imports = []; + newFileNeedExport.forEach(function (symbol) { + if (symbol.escapedName === "default" /* Default */) { + defaultImport = ts.createIdentifier(ts.symbolNameNoDefault(symbol)); // TODO: GH#18217 + } + else { + imports.push(symbol.name); + } + }); + return makeImportOrRequire(defaultImport, imports, newFileNameWithExtension, useEs6Imports, quotePreference); + } + function makeImportOrRequire(defaultImport, imports, path, useEs6Imports, quotePreference) { + path = ts.ensurePathIsNonModuleName(path); + if (useEs6Imports) { + var specifiers = imports.map(function (i) { return ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(i)); }); + return ts.makeImportIfNecessary(defaultImport, specifiers, path, quotePreference); + } + else { + ts.Debug.assert(!defaultImport); // If there's a default export, it should have been an es6 module. + var bindingElements = imports.map(function (i) { return ts.createBindingElement(/*dotDotDotToken*/ undefined, /*propertyName*/ undefined, i); }); + return bindingElements.length + ? makeVariableStatement(ts.createObjectBindingPattern(bindingElements), /*type*/ undefined, createRequireCall(ts.createLiteral(path))) + : undefined; + } + } + function makeVariableStatement(name, type, initializer, flags) { + if (flags === void 0) { flags = 2 /* Const */; } + return ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(name, type, initializer)], flags)); + } + function createRequireCall(moduleSpecifier) { + return ts.createCall(ts.createIdentifier("require"), /*typeArguments*/ undefined, [moduleSpecifier]); + } + function addExports(sourceFile, toMove, needExport, useEs6Exports) { + return ts.flatMap(toMove, function (statement) { + if (isTopLevelDeclarationStatement(statement) && + !isExported(sourceFile, statement, useEs6Exports) && + forEachTopLevelDeclaration(statement, function (d) { return needExport.has(ts.Debug.assertDefined(d.symbol)); })) { + var exports_2 = addExport(statement, useEs6Exports); + if (exports_2) + return exports_2; + } + return statement; + }); + } + function deleteUnusedImports(sourceFile, importDecl, changes, isUnused) { + switch (importDecl.kind) { + case 249 /* ImportDeclaration */: + deleteUnusedImportsInDeclaration(sourceFile, importDecl, changes, isUnused); + break; + case 248 /* ImportEqualsDeclaration */: + if (isUnused(importDecl.name)) { + changes.delete(sourceFile, importDecl); + } + break; + case 237 /* VariableDeclaration */: + deleteUnusedImportsInVariableDeclaration(sourceFile, importDecl, changes, isUnused); + break; + default: + ts.Debug.assertNever(importDecl); + } + } + function deleteUnusedImportsInDeclaration(sourceFile, importDecl, changes, isUnused) { + if (!importDecl.importClause) + return; + var _a = importDecl.importClause, name = _a.name, namedBindings = _a.namedBindings; + var defaultUnused = !name || isUnused(name); + var namedBindingsUnused = !namedBindings || + (namedBindings.kind === 251 /* NamespaceImport */ ? isUnused(namedBindings.name) : namedBindings.elements.length !== 0 && namedBindings.elements.every(function (e) { return isUnused(e.name); })); + if (defaultUnused && namedBindingsUnused) { + changes.delete(sourceFile, importDecl); + } + else { + if (name && defaultUnused) { + changes.delete(sourceFile, name); + } + if (namedBindings) { + if (namedBindingsUnused) { + changes.delete(sourceFile, namedBindings); + } + else if (namedBindings.kind === 252 /* NamedImports */) { + for (var _i = 0, _b = namedBindings.elements; _i < _b.length; _i++) { + var element = _b[_i]; + if (isUnused(element.name)) + changes.delete(sourceFile, element); + } + } + } + } + } + function deleteUnusedImportsInVariableDeclaration(sourceFile, varDecl, changes, isUnused) { + var name = varDecl.name; + switch (name.kind) { + case 72 /* Identifier */: + if (isUnused(name)) { + changes.delete(sourceFile, name); + } + break; + case 185 /* ArrayBindingPattern */: + break; + case 184 /* ObjectBindingPattern */: + if (name.elements.every(function (e) { return ts.isIdentifier(e.name) && isUnused(e.name); })) { + changes.delete(sourceFile, ts.isVariableDeclarationList(varDecl.parent) && varDecl.parent.declarations.length === 1 ? varDecl.parent.parent : varDecl); + } + else { + for (var _i = 0, _a = name.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (ts.isIdentifier(element.name) && isUnused(element.name)) { + changes.delete(sourceFile, element.name); + } + } + } + break; + } + } + function getNewFileImportsAndAddExportInOldFile(oldFile, importsToCopy, newFileImportsFromOldFile, changes, checker, useEs6ModuleSyntax, quotePreference) { + var copiedOldImports = []; + for (var _i = 0, _a = oldFile.statements; _i < _a.length; _i++) { + var oldStatement = _a[_i]; + forEachImportInStatement(oldStatement, function (i) { + ts.append(copiedOldImports, filterImport(i, moduleSpecifierFromImport(i), function (name) { return importsToCopy.has(checker.getSymbolAtLocation(name)); })); + }); + } + // Also, import things used from the old file, and insert 'export' modifiers as necessary in the old file. + var oldFileDefault; + var oldFileNamedImports = []; + var markSeenTop = ts.nodeSeenTracker(); // Needed because multiple declarations may appear in `const x = 0, y = 1;`. + newFileImportsFromOldFile.forEach(function (symbol) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + if (!isTopLevelDeclaration(decl)) + continue; + var name = nameOfTopLevelDeclaration(decl); + if (!name) + continue; + var top = getTopLevelDeclarationStatement(decl); + if (markSeenTop(top)) { + addExportToChanges(oldFile, top, changes, useEs6ModuleSyntax); + } + if (ts.hasModifier(decl, 512 /* Default */)) { + oldFileDefault = name; + } + else { + oldFileNamedImports.push(name.text); + } + } + }); + ts.append(copiedOldImports, makeImportOrRequire(oldFileDefault, oldFileNamedImports, ts.removeFileExtension(ts.getBaseFileName(oldFile.fileName)), useEs6ModuleSyntax, quotePreference)); + return copiedOldImports; + } + function makeUniqueModuleName(moduleName, extension, inDirectory, host) { + var newModuleName = moduleName; + for (var i = 1;; i++) { + var name = ts.combinePaths(inDirectory, newModuleName + extension); + if (!host.fileExists(name)) + return newModuleName; // TODO: GH#18217 + newModuleName = moduleName + "." + i; + } + } + function getNewModuleName(movedSymbols) { + return movedSymbols.forEachEntry(ts.symbolNameNoDefault) || "newFile"; + } + function getUsageInfo(oldFile, toMove, checker) { + var movedSymbols = new SymbolSet(); + var oldImportsNeededByNewFile = new SymbolSet(); + var newFileImportsFromOldFile = new SymbolSet(); + for (var _i = 0, toMove_1 = toMove; _i < toMove_1.length; _i++) { + var statement = toMove_1[_i]; + forEachTopLevelDeclaration(statement, function (decl) { + movedSymbols.add(ts.Debug.assertDefined(ts.isExpressionStatement(decl) ? checker.getSymbolAtLocation(decl.expression.left) : decl.symbol)); + }); + } + for (var _a = 0, toMove_2 = toMove; _a < toMove_2.length; _a++) { + var statement = toMove_2[_a]; + forEachReference(statement, checker, function (symbol) { + if (!symbol.declarations) + return; + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + if (isInImport(decl)) { + oldImportsNeededByNewFile.add(symbol); + } + else if (isTopLevelDeclaration(decl) && sourceFileOfTopLevelDeclaration(decl) === oldFile && !movedSymbols.has(symbol)) { + newFileImportsFromOldFile.add(symbol); + } + } + }); + } + var unusedImportsFromOldFile = oldImportsNeededByNewFile.clone(); + var oldFileImportsFromNewFile = new SymbolSet(); + for (var _b = 0, _c = oldFile.statements; _b < _c.length; _b++) { + var statement = _c[_b]; + if (ts.contains(toMove, statement)) + continue; + forEachReference(statement, checker, function (symbol) { + if (movedSymbols.has(symbol)) + oldFileImportsFromNewFile.add(symbol); + unusedImportsFromOldFile.delete(symbol); + }); + } + return { movedSymbols: movedSymbols, newFileImportsFromOldFile: newFileImportsFromOldFile, oldFileImportsFromNewFile: oldFileImportsFromNewFile, oldImportsNeededByNewFile: oldImportsNeededByNewFile, unusedImportsFromOldFile: unusedImportsFromOldFile }; + } + // Below should all be utilities + function isInImport(decl) { + switch (decl.kind) { + case 248 /* ImportEqualsDeclaration */: + case 253 /* ImportSpecifier */: + case 250 /* ImportClause */: + return true; + case 237 /* VariableDeclaration */: + return isVariableDeclarationInImport(decl); + case 186 /* BindingElement */: + return ts.isVariableDeclaration(decl.parent.parent) && isVariableDeclarationInImport(decl.parent.parent); + default: + return false; + } + } + function isVariableDeclarationInImport(decl) { + return ts.isSourceFile(decl.parent.parent.parent) && + decl.initializer && ts.isRequireCall(decl.initializer, /*checkArgumentIsStringLiteralLike*/ true); + } + function filterImport(i, moduleSpecifier, keep) { + switch (i.kind) { + case 249 /* ImportDeclaration */: { + var clause = i.importClause; + if (!clause) + return undefined; + var defaultImport = clause.name && keep(clause.name) ? clause.name : undefined; + var namedBindings = clause.namedBindings && filterNamedBindings(clause.namedBindings, keep); + return defaultImport || namedBindings + ? ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createImportClause(defaultImport, namedBindings), moduleSpecifier) + : undefined; + } + case 248 /* ImportEqualsDeclaration */: + return keep(i.name) ? i : undefined; + case 237 /* VariableDeclaration */: { + var name = filterBindingName(i.name, keep); + return name ? makeVariableStatement(name, i.type, createRequireCall(moduleSpecifier), i.parent.flags) : undefined; + } + default: + return ts.Debug.assertNever(i); + } + } + function filterNamedBindings(namedBindings, keep) { + if (namedBindings.kind === 251 /* NamespaceImport */) { + return keep(namedBindings.name) ? namedBindings : undefined; + } + else { + var newElements = namedBindings.elements.filter(function (e) { return keep(e.name); }); + return newElements.length ? ts.createNamedImports(newElements) : undefined; + } + } + function filterBindingName(name, keep) { + switch (name.kind) { + case 72 /* Identifier */: + return keep(name) ? name : undefined; + case 185 /* ArrayBindingPattern */: + return name; + case 184 /* ObjectBindingPattern */: { + // We can't handle nested destructurings or property names well here, so just copy them all. + var newElements = name.elements.filter(function (prop) { return prop.propertyName || !ts.isIdentifier(prop.name) || keep(prop.name); }); + return newElements.length ? ts.createObjectBindingPattern(newElements) : undefined; + } + } + } + function forEachReference(node, checker, onReference) { + node.forEachChild(function cb(node) { + if (ts.isIdentifier(node) && !ts.isDeclarationName(node)) { + var sym = checker.getSymbolAtLocation(node); + if (sym) + onReference(sym); + } + else { + node.forEachChild(cb); + } + }); + } + var SymbolSet = /** @class */ (function () { + function SymbolSet() { + this.map = ts.createMap(); + } + SymbolSet.prototype.add = function (symbol) { + this.map.set(String(ts.getSymbolId(symbol)), symbol); + }; + SymbolSet.prototype.has = function (symbol) { + return this.map.has(String(ts.getSymbolId(symbol))); + }; + SymbolSet.prototype.delete = function (symbol) { + this.map.delete(String(ts.getSymbolId(symbol))); + }; + SymbolSet.prototype.forEach = function (cb) { + this.map.forEach(cb); + }; + SymbolSet.prototype.forEachEntry = function (cb) { + return ts.forEachEntry(this.map, cb); + }; + SymbolSet.prototype.clone = function () { + var clone = new SymbolSet(); + ts.copyEntries(this.map, clone.map); + return clone; + }; + return SymbolSet; + }()); + function isTopLevelDeclaration(node) { + return isNonVariableTopLevelDeclaration(node) && ts.isSourceFile(node.parent) || ts.isVariableDeclaration(node) && ts.isSourceFile(node.parent.parent.parent); + } + function sourceFileOfTopLevelDeclaration(node) { + return ts.isVariableDeclaration(node) ? node.parent.parent.parent : node.parent; + } + function isTopLevelDeclarationStatement(node) { + ts.Debug.assert(ts.isSourceFile(node.parent)); + return isNonVariableTopLevelDeclaration(node) || ts.isVariableStatement(node); + } + function isNonVariableTopLevelDeclaration(node) { + switch (node.kind) { + case 239 /* FunctionDeclaration */: + case 240 /* ClassDeclaration */: + case 244 /* ModuleDeclaration */: + case 243 /* EnumDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 241 /* InterfaceDeclaration */: + case 248 /* ImportEqualsDeclaration */: + return true; + default: + return false; + } + } + function forEachTopLevelDeclaration(statement, cb) { + switch (statement.kind) { + case 239 /* FunctionDeclaration */: + case 240 /* ClassDeclaration */: + case 244 /* ModuleDeclaration */: + case 243 /* EnumDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 241 /* InterfaceDeclaration */: + case 248 /* ImportEqualsDeclaration */: + return cb(statement); + case 219 /* VariableStatement */: + return ts.firstDefined(statement.declarationList.declarations, function (decl) { return forEachTopLevelDeclarationInBindingName(decl.name, cb); }); + case 221 /* ExpressionStatement */: { + var expression = statement.expression; + return ts.isBinaryExpression(expression) && ts.getAssignmentDeclarationKind(expression) === 1 /* ExportsProperty */ + ? cb(statement) + : undefined; + } + } + } + function forEachTopLevelDeclarationInBindingName(name, cb) { + switch (name.kind) { + case 72 /* Identifier */: + return cb(ts.cast(name.parent, function (x) { return ts.isVariableDeclaration(x) || ts.isBindingElement(x); })); + case 185 /* ArrayBindingPattern */: + case 184 /* ObjectBindingPattern */: + return ts.firstDefined(name.elements, function (em) { return ts.isOmittedExpression(em) ? undefined : forEachTopLevelDeclarationInBindingName(em.name, cb); }); + default: + return ts.Debug.assertNever(name); + } + } + function nameOfTopLevelDeclaration(d) { + return ts.isExpressionStatement(d) ? d.expression.left.name : ts.tryCast(d.name, ts.isIdentifier); + } + function getTopLevelDeclarationStatement(d) { + switch (d.kind) { + case 237 /* VariableDeclaration */: + return d.parent.parent; + case 186 /* BindingElement */: + return getTopLevelDeclarationStatement(ts.cast(d.parent.parent, function (p) { return ts.isVariableDeclaration(p) || ts.isBindingElement(p); })); + default: + return d; + } + } + function addExportToChanges(sourceFile, decl, changes, useEs6Exports) { + if (isExported(sourceFile, decl, useEs6Exports)) + return; + if (useEs6Exports) { + if (!ts.isExpressionStatement(decl)) + changes.insertExportModifier(sourceFile, decl); + } + else { + var names = getNamesToExportInCommonJS(decl); + if (names.length !== 0) + changes.insertNodesAfter(sourceFile, decl, names.map(createExportAssignment)); + } + } + function isExported(sourceFile, decl, useEs6Exports) { + if (useEs6Exports) { + return !ts.isExpressionStatement(decl) && ts.hasModifier(decl, 1 /* Export */); + } + else { + return getNamesToExportInCommonJS(decl).some(function (name) { return sourceFile.symbol.exports.has(ts.escapeLeadingUnderscores(name)); }); + } + } + function addExport(decl, useEs6Exports) { + return useEs6Exports ? [addEs6Export(decl)] : addCommonjsExport(decl); + } + function addEs6Export(d) { + var modifiers = ts.concatenate([ts.createModifier(85 /* ExportKeyword */)], d.modifiers); + switch (d.kind) { + case 239 /* FunctionDeclaration */: + return ts.updateFunctionDeclaration(d, d.decorators, modifiers, d.asteriskToken, d.name, d.typeParameters, d.parameters, d.type, d.body); + case 240 /* ClassDeclaration */: + return ts.updateClassDeclaration(d, d.decorators, modifiers, d.name, d.typeParameters, d.heritageClauses, d.members); + case 219 /* VariableStatement */: + return ts.updateVariableStatement(d, modifiers, d.declarationList); + case 244 /* ModuleDeclaration */: + return ts.updateModuleDeclaration(d, d.decorators, modifiers, d.name, d.body); + case 243 /* EnumDeclaration */: + return ts.updateEnumDeclaration(d, d.decorators, modifiers, d.name, d.members); + case 242 /* TypeAliasDeclaration */: + return ts.updateTypeAliasDeclaration(d, d.decorators, modifiers, d.name, d.typeParameters, d.type); + case 241 /* InterfaceDeclaration */: + return ts.updateInterfaceDeclaration(d, d.decorators, modifiers, d.name, d.typeParameters, d.heritageClauses, d.members); + case 248 /* ImportEqualsDeclaration */: + return ts.updateImportEqualsDeclaration(d, d.decorators, modifiers, d.name, d.moduleReference); + case 221 /* ExpressionStatement */: + return ts.Debug.fail(); // Shouldn't try to add 'export' keyword to `exports.x = ...` + default: + return ts.Debug.assertNever(d); + } + } + function addCommonjsExport(decl) { + return [decl].concat(getNamesToExportInCommonJS(decl).map(createExportAssignment)); + } + function getNamesToExportInCommonJS(decl) { + switch (decl.kind) { + case 239 /* FunctionDeclaration */: + case 240 /* ClassDeclaration */: + return [decl.name.text]; // TODO: GH#18217 + case 219 /* VariableStatement */: + return ts.mapDefined(decl.declarationList.declarations, function (d) { return ts.isIdentifier(d.name) ? d.name.text : undefined; }); + case 244 /* ModuleDeclaration */: + case 243 /* EnumDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 241 /* InterfaceDeclaration */: + case 248 /* ImportEqualsDeclaration */: + return ts.emptyArray; + case 221 /* ExpressionStatement */: + return ts.Debug.fail(); // Shouldn't try to add 'export' keyword to `exports.x = ...` + default: + return ts.Debug.assertNever(decl); + } + } + /** Creates `exports.x = x;` */ + function createExportAssignment(name) { + return ts.createExpressionStatement(ts.createBinary(ts.createPropertyAccess(ts.createIdentifier("exports"), ts.createIdentifier(name)), 59 /* EqualsToken */, ts.createIdentifier(name))); + } + })(refactor = ts.refactor || (ts.refactor = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var refactor; + (function (refactor) { + var addOrRemoveBracesToArrowFunction; + (function (addOrRemoveBracesToArrowFunction) { + var refactorName = "Add or remove braces in an arrow function"; + var refactorDescription = ts.Diagnostics.Add_or_remove_braces_in_an_arrow_function.message; + var addBracesActionName = "Add braces to arrow function"; + var removeBracesActionName = "Remove braces from arrow function"; + var addBracesActionDescription = ts.Diagnostics.Add_braces_to_arrow_function.message; + var removeBracesActionDescription = ts.Diagnostics.Remove_braces_from_arrow_function.message; + refactor.registerRefactor(refactorName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions }); + function getAvailableActions(context) { + var file = context.file, startPosition = context.startPosition; + var info = getConvertibleArrowFunctionAtPosition(file, startPosition); + if (!info) + return ts.emptyArray; + return [{ + name: refactorName, + description: refactorDescription, + actions: [ + info.addBraces ? + { + name: addBracesActionName, + description: addBracesActionDescription + } : { + name: removeBracesActionName, + description: removeBracesActionDescription + } + ] + }]; + } + function getEditsForAction(context, actionName) { + var file = context.file, startPosition = context.startPosition; + var info = getConvertibleArrowFunctionAtPosition(file, startPosition); + if (!info) + return undefined; + var expression = info.expression, returnStatement = info.returnStatement, func = info.func; + var body; + if (actionName === addBracesActionName) { + var returnStatement_1 = ts.createReturn(expression); + body = ts.createBlock([returnStatement_1], /* multiLine */ true); + ts.suppressLeadingAndTrailingTrivia(body); + ts.copyComments(expression, returnStatement_1, file, 3 /* MultiLineCommentTrivia */, /* hasTrailingNewLine */ true); + } + else if (actionName === removeBracesActionName && returnStatement) { + var actualExpression = expression || ts.createVoidZero(); + body = needsParentheses(actualExpression) ? ts.createParen(actualExpression) : actualExpression; + ts.suppressLeadingAndTrailingTrivia(body); + ts.copyComments(returnStatement, body, file, 3 /* MultiLineCommentTrivia */, /* hasTrailingNewLine */ false); + } + else { + ts.Debug.fail("invalid action"); + } + var edits = ts.textChanges.ChangeTracker.with(context, function (t) { return t.replaceNode(file, func.body, body); }); + return { renameFilename: undefined, renameLocation: undefined, edits: edits }; + } + function needsParentheses(expression) { + return ts.isBinaryExpression(expression) && expression.operatorToken.kind === 27 /* CommaToken */ || ts.isObjectLiteralExpression(expression); + } + function getConvertibleArrowFunctionAtPosition(file, startPosition) { + var node = ts.getTokenAtPosition(file, startPosition); + var func = ts.getContainingFunction(node); + if (!func || !ts.isArrowFunction(func) || (!ts.rangeContainsRange(func, node) || ts.rangeContainsRange(func.body, node))) + return undefined; + if (ts.isExpression(func.body)) { + return { + func: func, + addBraces: true, + expression: func.body + }; + } + else if (func.body.statements.length === 1) { + var firstStatement = ts.first(func.body.statements); + if (ts.isReturnStatement(firstStatement)) { + return { + func: func, + addBraces: false, + expression: firstStatement.expression, + returnStatement: firstStatement + }; + } + } + return undefined; + } + })(addOrRemoveBracesToArrowFunction = refactor.addOrRemoveBracesToArrowFunction || (refactor.addOrRemoveBracesToArrowFunction = {})); + })(refactor = ts.refactor || (ts.refactor = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + /** The version of the language service API */ + ts.servicesVersion = "0.8"; + function createNode(kind, pos, end, parent) { + var node = ts.isNodeKind(kind) ? new NodeObject(kind, pos, end) : + kind === 72 /* Identifier */ ? new IdentifierObject(72 /* Identifier */, pos, end) : + new TokenObject(kind, pos, end); + node.parent = parent; + node.flags = parent.flags & 12679168 /* ContextFlags */; + return node; + } + var NodeObject = /** @class */ (function () { + function NodeObject(kind, pos, end) { + this.pos = pos; + this.end = end; + this.flags = 0 /* None */; + this.transformFlags = undefined; // TODO: GH#18217 + this.parent = undefined; + this.kind = kind; + } + NodeObject.prototype.assertHasRealPosition = function (message) { + // tslint:disable-next-line:debug-assert + ts.Debug.assert(!ts.positionIsSynthesized(this.pos) && !ts.positionIsSynthesized(this.end), message || "Node must have a real position for this operation"); + }; + NodeObject.prototype.getSourceFile = function () { + return ts.getSourceFileOfNode(this); + }; + NodeObject.prototype.getStart = function (sourceFile, includeJsDocComment) { + this.assertHasRealPosition(); + return ts.getTokenPosOfNode(this, sourceFile, includeJsDocComment); + }; + NodeObject.prototype.getFullStart = function () { + this.assertHasRealPosition(); + return this.pos; + }; + NodeObject.prototype.getEnd = function () { + this.assertHasRealPosition(); + return this.end; + }; + NodeObject.prototype.getWidth = function (sourceFile) { + this.assertHasRealPosition(); + return this.getEnd() - this.getStart(sourceFile); + }; + NodeObject.prototype.getFullWidth = function () { + this.assertHasRealPosition(); + return this.end - this.pos; + }; + NodeObject.prototype.getLeadingTriviaWidth = function (sourceFile) { + this.assertHasRealPosition(); + return this.getStart(sourceFile) - this.pos; + }; + NodeObject.prototype.getFullText = function (sourceFile) { + this.assertHasRealPosition(); + return (sourceFile || this.getSourceFile()).text.substring(this.pos, this.end); + }; + NodeObject.prototype.getText = function (sourceFile) { + this.assertHasRealPosition(); + if (!sourceFile) { + sourceFile = this.getSourceFile(); + } + return sourceFile.text.substring(this.getStart(sourceFile), this.getEnd()); + }; + NodeObject.prototype.getChildCount = function (sourceFile) { + return this.getChildren(sourceFile).length; + }; + NodeObject.prototype.getChildAt = function (index, sourceFile) { + return this.getChildren(sourceFile)[index]; + }; + NodeObject.prototype.getChildren = function (sourceFile) { + this.assertHasRealPosition("Node without a real position cannot be scanned and thus has no token nodes - use forEachChild and collect the result if that's fine"); + return this._children || (this._children = createChildren(this, sourceFile)); + }; + NodeObject.prototype.getFirstToken = function (sourceFile) { + this.assertHasRealPosition(); + var children = this.getChildren(sourceFile); + if (!children.length) { + return undefined; + } + var child = ts.find(children, function (kid) { return kid.kind < 283 /* FirstJSDocNode */ || kid.kind > 305 /* LastJSDocNode */; }); + return child.kind < 148 /* FirstNode */ ? + child : + child.getFirstToken(sourceFile); + }; + NodeObject.prototype.getLastToken = function (sourceFile) { + this.assertHasRealPosition(); + var children = this.getChildren(sourceFile); + var child = ts.lastOrUndefined(children); + if (!child) { + return undefined; + } + return child.kind < 148 /* FirstNode */ ? child : child.getLastToken(sourceFile); + }; + NodeObject.prototype.forEachChild = function (cbNode, cbNodeArray) { + return ts.forEachChild(this, cbNode, cbNodeArray); + }; + return NodeObject; + }()); + function createChildren(node, sourceFile) { + if (!ts.isNodeKind(node.kind)) { + return ts.emptyArray; + } + var children = []; + if (ts.isJSDocCommentContainingNode(node)) { + /** Don't add trivia for "tokens" since this is in a comment. */ + node.forEachChild(function (child) { children.push(child); }); + return children; + } + ts.scanner.setText((sourceFile || node.getSourceFile()).text); + var pos = node.pos; + var processNode = function (child) { + addSyntheticNodes(children, pos, child.pos, node); + children.push(child); + pos = child.end; + }; + var processNodes = function (nodes) { + addSyntheticNodes(children, pos, nodes.pos, node); + children.push(createSyntaxList(nodes, node)); + pos = nodes.end; + }; + // jsDocComments need to be the first children + ts.forEach(node.jsDoc, processNode); + // For syntactic classifications, all trivia are classified together, including jsdoc comments. + // For that to work, the jsdoc comments should still be the leading trivia of the first child. + // Restoring the scanner position ensures that. + pos = node.pos; + node.forEachChild(processNode, processNodes); + addSyntheticNodes(children, pos, node.end, node); + ts.scanner.setText(undefined); + return children; + } + function addSyntheticNodes(nodes, pos, end, parent) { + ts.scanner.setTextPos(pos); + while (pos < end) { + var token = ts.scanner.scan(); + var textPos = ts.scanner.getTextPos(); + if (textPos <= end) { + if (token === 72 /* Identifier */) { + ts.Debug.fail("Did not expect " + ts.Debug.showSyntaxKind(parent) + " to have an Identifier in its trivia"); + } + nodes.push(createNode(token, pos, textPos, parent)); + } + pos = textPos; + if (token === 1 /* EndOfFileToken */) { + break; + } + } + } + function createSyntaxList(nodes, parent) { + var list = createNode(306 /* SyntaxList */, nodes.pos, nodes.end, parent); + list._children = []; + var pos = nodes.pos; + for (var _i = 0, nodes_7 = nodes; _i < nodes_7.length; _i++) { + var node = nodes_7[_i]; + addSyntheticNodes(list._children, pos, node.pos, parent); + list._children.push(node); + pos = node.end; + } + addSyntheticNodes(list._children, pos, nodes.end, parent); + return list; + } + var TokenOrIdentifierObject = /** @class */ (function () { + function TokenOrIdentifierObject(pos, end) { + // Set properties in same order as NodeObject + this.pos = pos; + this.end = end; + this.flags = 0 /* None */; + this.parent = undefined; + } + TokenOrIdentifierObject.prototype.getSourceFile = function () { + return ts.getSourceFileOfNode(this); + }; + TokenOrIdentifierObject.prototype.getStart = function (sourceFile, includeJsDocComment) { + return ts.getTokenPosOfNode(this, sourceFile, includeJsDocComment); + }; + TokenOrIdentifierObject.prototype.getFullStart = function () { + return this.pos; + }; + TokenOrIdentifierObject.prototype.getEnd = function () { + return this.end; + }; + TokenOrIdentifierObject.prototype.getWidth = function (sourceFile) { + return this.getEnd() - this.getStart(sourceFile); + }; + TokenOrIdentifierObject.prototype.getFullWidth = function () { + return this.end - this.pos; + }; + TokenOrIdentifierObject.prototype.getLeadingTriviaWidth = function (sourceFile) { + return this.getStart(sourceFile) - this.pos; + }; + TokenOrIdentifierObject.prototype.getFullText = function (sourceFile) { + return (sourceFile || this.getSourceFile()).text.substring(this.pos, this.end); + }; + TokenOrIdentifierObject.prototype.getText = function (sourceFile) { + if (!sourceFile) { + sourceFile = this.getSourceFile(); + } + return sourceFile.text.substring(this.getStart(sourceFile), this.getEnd()); + }; + TokenOrIdentifierObject.prototype.getChildCount = function () { + return 0; + }; + TokenOrIdentifierObject.prototype.getChildAt = function () { + return undefined; // TODO: GH#18217 + }; + TokenOrIdentifierObject.prototype.getChildren = function () { + return this.kind === 1 /* EndOfFileToken */ ? this.jsDoc || ts.emptyArray : ts.emptyArray; + }; + TokenOrIdentifierObject.prototype.getFirstToken = function () { + return undefined; + }; + TokenOrIdentifierObject.prototype.getLastToken = function () { + return undefined; + }; + TokenOrIdentifierObject.prototype.forEachChild = function () { + return undefined; + }; + return TokenOrIdentifierObject; + }()); + var SymbolObject = /** @class */ (function () { + function SymbolObject(flags, name) { + this.flags = flags; + this.escapedName = name; + } + SymbolObject.prototype.getFlags = function () { + return this.flags; + }; + Object.defineProperty(SymbolObject.prototype, "name", { + get: function () { + return ts.symbolName(this); + }, + enumerable: true, + configurable: true + }); + SymbolObject.prototype.getEscapedName = function () { + return this.escapedName; + }; + SymbolObject.prototype.getName = function () { + return this.name; + }; + SymbolObject.prototype.getDeclarations = function () { + return this.declarations; + }; + SymbolObject.prototype.getDocumentationComment = function (checker) { + if (!this.documentationComment) { + this.documentationComment = ts.emptyArray; // Set temporarily to avoid an infinite loop finding inherited docs + this.documentationComment = getDocumentationComment(this.declarations, checker); + } + return this.documentationComment; + }; + SymbolObject.prototype.getJsDocTags = function () { + if (this.tags === undefined) { + this.tags = ts.JsDoc.getJsDocTagsFromDeclarations(this.declarations); + } + return this.tags; + }; + return SymbolObject; + }()); + var TokenObject = /** @class */ (function (_super) { + __extends(TokenObject, _super); + function TokenObject(kind, pos, end) { + var _this = _super.call(this, pos, end) || this; + _this.kind = kind; + return _this; + } + return TokenObject; + }(TokenOrIdentifierObject)); + var IdentifierObject = /** @class */ (function (_super) { + __extends(IdentifierObject, _super); + function IdentifierObject(_kind, pos, end) { + return _super.call(this, pos, end) || this; + } + Object.defineProperty(IdentifierObject.prototype, "text", { + get: function () { + return ts.idText(this); + }, + enumerable: true, + configurable: true + }); + return IdentifierObject; + }(TokenOrIdentifierObject)); + IdentifierObject.prototype.kind = 72 /* Identifier */; + var TypeObject = /** @class */ (function () { + function TypeObject(checker, flags) { + this.checker = checker; + this.flags = flags; + } + TypeObject.prototype.getFlags = function () { + return this.flags; + }; + TypeObject.prototype.getSymbol = function () { + return this.symbol; + }; + TypeObject.prototype.getProperties = function () { + return this.checker.getPropertiesOfType(this); + }; + TypeObject.prototype.getProperty = function (propertyName) { + return this.checker.getPropertyOfType(this, propertyName); + }; + TypeObject.prototype.getApparentProperties = function () { + return this.checker.getAugmentedPropertiesOfType(this); + }; + TypeObject.prototype.getCallSignatures = function () { + return this.checker.getSignaturesOfType(this, 0 /* Call */); + }; + TypeObject.prototype.getConstructSignatures = function () { + return this.checker.getSignaturesOfType(this, 1 /* Construct */); + }; + TypeObject.prototype.getStringIndexType = function () { + return this.checker.getIndexTypeOfType(this, 0 /* String */); + }; + TypeObject.prototype.getNumberIndexType = function () { + return this.checker.getIndexTypeOfType(this, 1 /* Number */); + }; + TypeObject.prototype.getBaseTypes = function () { + return this.isClassOrInterface() ? this.checker.getBaseTypes(this) : undefined; + }; + TypeObject.prototype.getNonNullableType = function () { + return this.checker.getNonNullableType(this); + }; + TypeObject.prototype.getConstraint = function () { + return this.checker.getBaseConstraintOfType(this); + }; + TypeObject.prototype.getDefault = function () { + return this.checker.getDefaultFromTypeParameter(this); + }; + TypeObject.prototype.isUnion = function () { + return !!(this.flags & 1048576 /* Union */); + }; + TypeObject.prototype.isIntersection = function () { + return !!(this.flags & 2097152 /* Intersection */); + }; + TypeObject.prototype.isUnionOrIntersection = function () { + return !!(this.flags & 3145728 /* UnionOrIntersection */); + }; + TypeObject.prototype.isLiteral = function () { + return !!(this.flags & 384 /* StringOrNumberLiteral */); + }; + TypeObject.prototype.isStringLiteral = function () { + return !!(this.flags & 128 /* StringLiteral */); + }; + TypeObject.prototype.isNumberLiteral = function () { + return !!(this.flags & 256 /* NumberLiteral */); + }; + TypeObject.prototype.isTypeParameter = function () { + return !!(this.flags & 262144 /* TypeParameter */); + }; + TypeObject.prototype.isClassOrInterface = function () { + return !!(ts.getObjectFlags(this) & 3 /* ClassOrInterface */); + }; + TypeObject.prototype.isClass = function () { + return !!(ts.getObjectFlags(this) & 1 /* Class */); + }; + return TypeObject; + }()); + var SignatureObject = /** @class */ (function () { + function SignatureObject(checker) { + this.checker = checker; + } + SignatureObject.prototype.getDeclaration = function () { + return this.declaration; + }; + SignatureObject.prototype.getTypeParameters = function () { + return this.typeParameters; + }; + SignatureObject.prototype.getParameters = function () { + return this.parameters; + }; + SignatureObject.prototype.getReturnType = function () { + return this.checker.getReturnTypeOfSignature(this); + }; + SignatureObject.prototype.getDocumentationComment = function () { + return this.documentationComment || (this.documentationComment = getDocumentationComment(ts.singleElementArray(this.declaration), this.checker)); + }; + SignatureObject.prototype.getJsDocTags = function () { + if (this.jsDocTags === undefined) { + this.jsDocTags = this.declaration ? ts.JsDoc.getJsDocTagsFromDeclarations([this.declaration]) : []; + } + return this.jsDocTags; + }; + return SignatureObject; + }()); + /** + * Returns whether or not the given node has a JSDoc "inheritDoc" tag on it. + * @param node the Node in question. + * @returns `true` if `node` has a JSDoc "inheritDoc" tag on it, otherwise `false`. + */ + function hasJSDocInheritDocTag(node) { + return ts.getJSDocTags(node).some(function (tag) { return tag.tagName.text === "inheritDoc"; }); + } + function getDocumentationComment(declarations, checker) { + if (!declarations) + return ts.emptyArray; + var doc = ts.JsDoc.getJsDocCommentsFromDeclarations(declarations); + if (doc.length === 0 || declarations.some(hasJSDocInheritDocTag)) { + for (var _i = 0, declarations_14 = declarations; _i < declarations_14.length; _i++) { + var declaration = declarations_14[_i]; + var inheritedDocs = findInheritedJSDocComments(declaration, declaration.symbol.name, checker); // TODO: GH#18217 + // TODO: GH#16312 Return a ReadonlyArray, avoid copying inheritedDocs + if (inheritedDocs) + doc = doc.length === 0 ? inheritedDocs.slice() : inheritedDocs.concat(ts.lineBreakPart(), doc); + } + } + return doc; + } + /** + * Attempts to find JSDoc comments for possibly-inherited properties. Checks superclasses then traverses + * implemented interfaces until a symbol is found with the same name and with documentation. + * @param declaration The possibly-inherited declaration to find comments for. + * @param propertyName The name of the possibly-inherited property. + * @param typeChecker A TypeChecker, used to find inherited properties. + * @returns A filled array of documentation comments if any were found, otherwise an empty array. + */ + function findInheritedJSDocComments(declaration, propertyName, typeChecker) { + return ts.firstDefined(declaration.parent ? ts.getAllSuperTypeNodes(declaration.parent) : ts.emptyArray, function (superTypeNode) { + var superType = typeChecker.getTypeAtLocation(superTypeNode); + var baseProperty = superType && typeChecker.getPropertyOfType(superType, propertyName); + var inheritedDocs = baseProperty && baseProperty.getDocumentationComment(typeChecker); + return inheritedDocs && inheritedDocs.length ? inheritedDocs : undefined; + }); + } + var SourceFileObject = /** @class */ (function (_super) { + __extends(SourceFileObject, _super); + function SourceFileObject(kind, pos, end) { + return _super.call(this, kind, pos, end) || this; + } + SourceFileObject.prototype.update = function (newText, textChangeRange) { + return ts.updateSourceFile(this, newText, textChangeRange); + }; + SourceFileObject.prototype.getLineAndCharacterOfPosition = function (position) { + return ts.getLineAndCharacterOfPosition(this, position); + }; + SourceFileObject.prototype.getLineStarts = function () { + return ts.getLineStarts(this); + }; + SourceFileObject.prototype.getPositionOfLineAndCharacter = function (line, character) { + return ts.getPositionOfLineAndCharacter(this, line, character); + }; + SourceFileObject.prototype.getLineEndOfPosition = function (pos) { + var line = this.getLineAndCharacterOfPosition(pos).line; + var lineStarts = this.getLineStarts(); + var lastCharPos; + if (line + 1 >= lineStarts.length) { + lastCharPos = this.getEnd(); + } + if (!lastCharPos) { + lastCharPos = lineStarts[line + 1] - 1; + } + var fullText = this.getFullText(); + // if the new line is "\r\n", we should return the last non-new-line-character position + return fullText[lastCharPos] === "\n" && fullText[lastCharPos - 1] === "\r" ? lastCharPos - 1 : lastCharPos; + }; + SourceFileObject.prototype.getNamedDeclarations = function () { + if (!this.namedDeclarations) { + this.namedDeclarations = this.computeNamedDeclarations(); + } + return this.namedDeclarations; + }; + SourceFileObject.prototype.computeNamedDeclarations = function () { + var result = ts.createMultiMap(); + this.forEachChild(visit); + return result; + function addDeclaration(declaration) { + var name = getDeclarationName(declaration); + if (name) { + result.add(name, declaration); + } + } + function getDeclarations(name) { + var declarations = result.get(name); + if (!declarations) { + result.set(name, declarations = []); + } + return declarations; + } + function getDeclarationName(declaration) { + var name = ts.getNonAssignedNameOfDeclaration(declaration); + return name && (ts.isComputedPropertyName(name) && ts.isPropertyAccessExpression(name.expression) ? name.expression.name.text + : ts.isPropertyName(name) ? ts.getNameFromPropertyName(name) : undefined); + } + function visit(node) { + switch (node.kind) { + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + var functionDeclaration = node; + var declarationName = getDeclarationName(functionDeclaration); + if (declarationName) { + var declarations = getDeclarations(declarationName); + var lastDeclaration = ts.lastOrUndefined(declarations); + // Check whether this declaration belongs to an "overload group". + if (lastDeclaration && functionDeclaration.parent === lastDeclaration.parent && functionDeclaration.symbol === lastDeclaration.symbol) { + // Overwrite the last declaration if it was an overload + // and this one is an implementation. + if (functionDeclaration.body && !lastDeclaration.body) { + declarations[declarations.length - 1] = functionDeclaration; + } + } + else { + declarations.push(functionDeclaration); + } + } + ts.forEachChild(node, visit); + break; + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 241 /* InterfaceDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 243 /* EnumDeclaration */: + case 244 /* ModuleDeclaration */: + case 248 /* ImportEqualsDeclaration */: + case 257 /* ExportSpecifier */: + case 253 /* ImportSpecifier */: + case 250 /* ImportClause */: + case 251 /* NamespaceImport */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 168 /* TypeLiteral */: + addDeclaration(node); + ts.forEachChild(node, visit); + break; + case 151 /* Parameter */: + // Only consider parameter properties + if (!ts.hasModifier(node, 92 /* ParameterPropertyModifier */)) { + break; + } + // falls through + case 237 /* VariableDeclaration */: + case 186 /* BindingElement */: { + var decl = node; + if (ts.isBindingPattern(decl.name)) { + ts.forEachChild(decl.name, visit); + break; + } + if (decl.initializer) { + visit(decl.initializer); + } + } + // falls through + case 278 /* EnumMember */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + addDeclaration(node); + break; + case 255 /* ExportDeclaration */: + // Handle named exports case e.g.: + // export {a, b as B} from "mod"; + if (node.exportClause) { + ts.forEach(node.exportClause.elements, visit); + } + break; + case 249 /* ImportDeclaration */: + var importClause = node.importClause; + if (importClause) { + // Handle default import case e.g.: + // import d from "mod"; + if (importClause.name) { + addDeclaration(importClause.name); + } + // Handle named bindings in imports e.g.: + // import * as NS from "mod"; + // import {a, b as B} from "mod"; + if (importClause.namedBindings) { + if (importClause.namedBindings.kind === 251 /* NamespaceImport */) { + addDeclaration(importClause.namedBindings); + } + else { + ts.forEach(importClause.namedBindings.elements, visit); + } + } + } + break; + case 204 /* BinaryExpression */: + if (ts.getAssignmentDeclarationKind(node) !== 0 /* None */) { + addDeclaration(node); + } + // falls through + default: + ts.forEachChild(node, visit); + } + } + }; + return SourceFileObject; + }(NodeObject)); + var SourceMapSourceObject = /** @class */ (function () { + function SourceMapSourceObject(fileName, text, skipTrivia) { + this.fileName = fileName; + this.text = text; + this.skipTrivia = skipTrivia; + } + SourceMapSourceObject.prototype.getLineAndCharacterOfPosition = function (pos) { + return ts.getLineAndCharacterOfPosition(this, pos); + }; + return SourceMapSourceObject; + }()); + function getServicesObjectAllocator() { + return { + getNodeConstructor: function () { return NodeObject; }, + getTokenConstructor: function () { return TokenObject; }, + getIdentifierConstructor: function () { return IdentifierObject; }, + getSourceFileConstructor: function () { return SourceFileObject; }, + getSymbolConstructor: function () { return SymbolObject; }, + getTypeConstructor: function () { return TypeObject; }, + getSignatureConstructor: function () { return SignatureObject; }, + getSourceMapSourceConstructor: function () { return SourceMapSourceObject; }, + }; + } + function toEditorSettings(optionsAsMap) { + var allPropertiesAreCamelCased = true; + for (var key in optionsAsMap) { + if (ts.hasProperty(optionsAsMap, key) && !isCamelCase(key)) { + allPropertiesAreCamelCased = false; + break; + } + } + if (allPropertiesAreCamelCased) { + return optionsAsMap; + } + var settings = {}; + for (var key in optionsAsMap) { + if (ts.hasProperty(optionsAsMap, key)) { + var newKey = isCamelCase(key) ? key : key.charAt(0).toLowerCase() + key.substr(1); + settings[newKey] = optionsAsMap[key]; + } + } + return settings; + } + ts.toEditorSettings = toEditorSettings; + function isCamelCase(s) { + return !s.length || s.charAt(0) === s.charAt(0).toLowerCase(); + } + function displayPartsToString(displayParts) { + if (displayParts) { + return ts.map(displayParts, function (displayPart) { return displayPart.text; }).join(""); + } + return ""; + } + ts.displayPartsToString = displayPartsToString; + function getDefaultCompilerOptions() { + // Always default to "ScriptTarget.ES5" for the language service + return { + target: 1 /* ES5 */, + jsx: 1 /* Preserve */ + }; + } + ts.getDefaultCompilerOptions = getDefaultCompilerOptions; + function getSupportedCodeFixes() { + return ts.codefix.getSupportedErrorCodes(); + } + ts.getSupportedCodeFixes = getSupportedCodeFixes; + // Cache host information about script Should be refreshed + // at each language service public entry point, since we don't know when + // the set of scripts handled by the host changes. + var HostCache = /** @class */ (function () { + function HostCache(host, getCanonicalFileName) { + this.host = host; + // script id => script index + this.currentDirectory = host.getCurrentDirectory(); + this.fileNameToEntry = ts.createMap(); + // Initialize the list with the root file names + var rootFileNames = host.getScriptFileNames(); + for (var _i = 0, rootFileNames_1 = rootFileNames; _i < rootFileNames_1.length; _i++) { + var fileName = rootFileNames_1[_i]; + this.createEntry(fileName, ts.toPath(fileName, this.currentDirectory, getCanonicalFileName)); + } + // store the compilation settings + this._compilationSettings = host.getCompilationSettings() || getDefaultCompilerOptions(); + } + HostCache.prototype.compilationSettings = function () { + return this._compilationSettings; + }; + HostCache.prototype.getProjectReferences = function () { + return this.host.getProjectReferences && this.host.getProjectReferences(); + }; + HostCache.prototype.createEntry = function (fileName, path) { + var entry; + var scriptSnapshot = this.host.getScriptSnapshot(fileName); + if (scriptSnapshot) { + entry = { + hostFileName: fileName, + version: this.host.getScriptVersion(fileName), + scriptSnapshot: scriptSnapshot, + scriptKind: ts.getScriptKind(fileName, this.host) + }; + } + else { + entry = fileName; + } + this.fileNameToEntry.set(path, entry); + return entry; + }; + HostCache.prototype.getEntryByPath = function (path) { + return this.fileNameToEntry.get(path); + }; + HostCache.prototype.getHostFileInformation = function (path) { + var entry = this.fileNameToEntry.get(path); + return !ts.isString(entry) ? entry : undefined; + }; + HostCache.prototype.getOrCreateEntryByPath = function (fileName, path) { + var info = this.getEntryByPath(path) || this.createEntry(fileName, path); + return ts.isString(info) ? undefined : info; // TODO: GH#18217 + }; + HostCache.prototype.getRootFileNames = function () { + var names = []; + this.fileNameToEntry.forEach(function (entry) { + if (ts.isString(entry)) { + names.push(entry); + } + else { + if (entry.scriptKind !== 6 /* JSON */) { + names.push(entry.hostFileName); + } + } + }); + return names; + }; + HostCache.prototype.getVersion = function (path) { + var file = this.getHostFileInformation(path); + return (file && file.version); // TODO: GH#18217 + }; + HostCache.prototype.getScriptSnapshot = function (path) { + var file = this.getHostFileInformation(path); + return (file && file.scriptSnapshot); // TODO: GH#18217 + }; + return HostCache; + }()); + var SyntaxTreeCache = /** @class */ (function () { + function SyntaxTreeCache(host) { + this.host = host; + } + SyntaxTreeCache.prototype.getCurrentSourceFile = function (fileName) { + var scriptSnapshot = this.host.getScriptSnapshot(fileName); + if (!scriptSnapshot) { + // The host does not know about this file. + throw new Error("Could not find file: '" + fileName + "'."); + } + var scriptKind = ts.getScriptKind(fileName, this.host); + var version = this.host.getScriptVersion(fileName); + var sourceFile; + if (this.currentFileName !== fileName) { + // This is a new file, just parse it + sourceFile = createLanguageServiceSourceFile(fileName, scriptSnapshot, 6 /* Latest */, version, /*setNodeParents*/ true, scriptKind); + } + else if (this.currentFileVersion !== version) { + // This is the same file, just a newer version. Incrementally parse the file. + var editRange = scriptSnapshot.getChangeRange(this.currentFileScriptSnapshot); + sourceFile = updateLanguageServiceSourceFile(this.currentSourceFile, scriptSnapshot, version, editRange); + } + if (sourceFile) { + // All done, ensure state is up to date + this.currentFileVersion = version; + this.currentFileName = fileName; + this.currentFileScriptSnapshot = scriptSnapshot; + this.currentSourceFile = sourceFile; + } + return this.currentSourceFile; + }; + return SyntaxTreeCache; + }()); + function setSourceFileFields(sourceFile, scriptSnapshot, version) { + sourceFile.version = version; + sourceFile.scriptSnapshot = scriptSnapshot; + } + function createLanguageServiceSourceFile(fileName, scriptSnapshot, scriptTarget, version, setNodeParents, scriptKind) { + var sourceFile = ts.createSourceFile(fileName, ts.getSnapshotText(scriptSnapshot), scriptTarget, setNodeParents, scriptKind); + setSourceFileFields(sourceFile, scriptSnapshot, version); + return sourceFile; + } + ts.createLanguageServiceSourceFile = createLanguageServiceSourceFile; + ts.disableIncrementalParsing = false; + function updateLanguageServiceSourceFile(sourceFile, scriptSnapshot, version, textChangeRange, aggressiveChecks) { + // If we were given a text change range, and our version or open-ness changed, then + // incrementally parse this file. + if (textChangeRange) { + if (version !== sourceFile.version) { + // Once incremental parsing is ready, then just call into this function. + if (!ts.disableIncrementalParsing) { + var newText = void 0; + // grab the fragment from the beginning of the original text to the beginning of the span + var prefix = textChangeRange.span.start !== 0 + ? sourceFile.text.substr(0, textChangeRange.span.start) + : ""; + // grab the fragment from the end of the span till the end of the original text + var suffix = ts.textSpanEnd(textChangeRange.span) !== sourceFile.text.length + ? sourceFile.text.substr(ts.textSpanEnd(textChangeRange.span)) + : ""; + if (textChangeRange.newLength === 0) { + // edit was a deletion - just combine prefix and suffix + newText = prefix && suffix ? prefix + suffix : prefix || suffix; + } + else { + // it was actual edit, fetch the fragment of new text that correspond to new span + var changedText = scriptSnapshot.getText(textChangeRange.span.start, textChangeRange.span.start + textChangeRange.newLength); + // combine prefix, changed text and suffix + newText = prefix && suffix + ? prefix + changedText + suffix + : prefix + ? (prefix + changedText) + : (changedText + suffix); + } + var newSourceFile = ts.updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks); + setSourceFileFields(newSourceFile, scriptSnapshot, version); + // after incremental parsing nameTable might not be up-to-date + // drop it so it can be lazily recreated later + newSourceFile.nameTable = undefined; + // dispose all resources held by old script snapshot + if (sourceFile !== newSourceFile && sourceFile.scriptSnapshot) { + if (sourceFile.scriptSnapshot.dispose) { + sourceFile.scriptSnapshot.dispose(); + } + sourceFile.scriptSnapshot = undefined; + } + return newSourceFile; + } + } + } + // Otherwise, just create a new source file. + return createLanguageServiceSourceFile(sourceFile.fileName, scriptSnapshot, sourceFile.languageVersion, version, /*setNodeParents*/ true, sourceFile.scriptKind); + } + ts.updateLanguageServiceSourceFile = updateLanguageServiceSourceFile; + var CancellationTokenObject = /** @class */ (function () { + function CancellationTokenObject(cancellationToken) { + this.cancellationToken = cancellationToken; + } + CancellationTokenObject.prototype.isCancellationRequested = function () { + return !!this.cancellationToken && this.cancellationToken.isCancellationRequested(); + }; + CancellationTokenObject.prototype.throwIfCancellationRequested = function () { + if (this.isCancellationRequested()) { + throw new ts.OperationCanceledException(); + } + }; + return CancellationTokenObject; + }()); + /* @internal */ + /** A cancellation that throttles calls to the host */ + var ThrottledCancellationToken = /** @class */ (function () { + function ThrottledCancellationToken(hostCancellationToken, throttleWaitMilliseconds) { + if (throttleWaitMilliseconds === void 0) { throttleWaitMilliseconds = 20; } + this.hostCancellationToken = hostCancellationToken; + this.throttleWaitMilliseconds = throttleWaitMilliseconds; + // Store when we last tried to cancel. Checking cancellation can be expensive (as we have + // to marshall over to the host layer). So we only bother actually checking once enough + // time has passed. + this.lastCancellationCheckTime = 0; + } + ThrottledCancellationToken.prototype.isCancellationRequested = function () { + var time = ts.timestamp(); + var duration = Math.abs(time - this.lastCancellationCheckTime); + if (duration >= this.throttleWaitMilliseconds) { + // Check no more than once every throttle wait milliseconds + this.lastCancellationCheckTime = time; + return this.hostCancellationToken.isCancellationRequested(); + } + return false; + }; + ThrottledCancellationToken.prototype.throwIfCancellationRequested = function () { + if (this.isCancellationRequested()) { + throw new ts.OperationCanceledException(); + } + }; + return ThrottledCancellationToken; + }()); + ts.ThrottledCancellationToken = ThrottledCancellationToken; + function createLanguageService(host, documentRegistry, syntaxOnly) { + if (documentRegistry === void 0) { documentRegistry = ts.createDocumentRegistry(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames(), host.getCurrentDirectory()); } + if (syntaxOnly === void 0) { syntaxOnly = false; } + var _a; + var syntaxTreeCache = new SyntaxTreeCache(host); + var program; + var lastProjectVersion; + var lastTypesRootVersion = 0; + var cancellationToken = new CancellationTokenObject(host.getCancellationToken && host.getCancellationToken()); + var currentDirectory = host.getCurrentDirectory(); + // Check if the localized messages json is set, otherwise query the host for it + if (!ts.localizedDiagnosticMessages && host.getLocalizedDiagnosticMessages) { + ts.localizedDiagnosticMessages = host.getLocalizedDiagnosticMessages(); + } + function log(message) { + if (host.log) { + host.log(message); + } + } + var useCaseSensitiveFileNames = ts.hostUsesCaseSensitiveFileNames(host); + var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); + var sourceMapper = ts.getSourceMapper(useCaseSensitiveFileNames, currentDirectory, log, host, function () { return program; }); + function getValidSourceFile(fileName) { + var sourceFile = program.getSourceFile(fileName); + if (!sourceFile) { + throw new Error("Could not find file: '" + fileName + "'."); + } + return sourceFile; + } + function synchronizeHostData() { + ts.Debug.assert(!syntaxOnly); + // perform fast check if host supports it + if (host.getProjectVersion) { + var hostProjectVersion = host.getProjectVersion(); + if (hostProjectVersion) { + if (lastProjectVersion === hostProjectVersion && !host.hasChangedAutomaticTypeDirectiveNames) { + return; + } + lastProjectVersion = hostProjectVersion; + } + } + var typeRootsVersion = host.getTypeRootsVersion ? host.getTypeRootsVersion() : 0; + if (lastTypesRootVersion !== typeRootsVersion) { + log("TypeRoots version has changed; provide new program"); + program = undefined; // TODO: GH#18217 + lastTypesRootVersion = typeRootsVersion; + } + // Get a fresh cache of the host information + var hostCache = new HostCache(host, getCanonicalFileName); + var rootFileNames = hostCache.getRootFileNames(); + var hasInvalidatedResolution = host.hasInvalidatedResolution || ts.returnFalse; + var projectReferences = hostCache.getProjectReferences(); + // If the program is already up-to-date, we can reuse it + if (ts.isProgramUptoDate(program, rootFileNames, hostCache.compilationSettings(), function (path) { return hostCache.getVersion(path); }, fileExists, hasInvalidatedResolution, !!host.hasChangedAutomaticTypeDirectiveNames, projectReferences)) { + return; + } + // IMPORTANT - It is critical from this moment onward that we do not check + // cancellation tokens. We are about to mutate source files from a previous program + // instance. If we cancel midway through, we may end up in an inconsistent state where + // the program points to old source files that have been invalidated because of + // incremental parsing. + var newSettings = hostCache.compilationSettings(); + // Now create a new compiler + var compilerHost = { + getSourceFile: getOrCreateSourceFile, + getSourceFileByPath: getOrCreateSourceFileByPath, + getCancellationToken: function () { return cancellationToken; }, + getCanonicalFileName: getCanonicalFileName, + useCaseSensitiveFileNames: function () { return useCaseSensitiveFileNames; }, + getNewLine: function () { return ts.getNewLineCharacter(newSettings, function () { return ts.getNewLineOrDefaultFromHost(host); }); }, + getDefaultLibFileName: function (options) { return host.getDefaultLibFileName(options); }, + writeFile: ts.noop, + getCurrentDirectory: function () { return currentDirectory; }, + fileExists: fileExists, + readFile: function (fileName) { + // stub missing host functionality + var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); + var entry = hostCache && hostCache.getEntryByPath(path); + if (entry) { + return ts.isString(entry) ? undefined : ts.getSnapshotText(entry.scriptSnapshot); + } + return host.readFile && host.readFile(fileName); + }, + realpath: host.realpath && (function (path) { return host.realpath(path); }), + directoryExists: function (directoryName) { + return ts.directoryProbablyExists(directoryName, host); + }, + getDirectories: function (path) { + return host.getDirectories ? host.getDirectories(path) : []; + }, + readDirectory: function (path, extensions, exclude, include, depth) { + ts.Debug.assertDefined(host.readDirectory, "'LanguageServiceHost.readDirectory' must be implemented to correctly process 'projectReferences'"); + return host.readDirectory(path, extensions, exclude, include, depth); + }, + onReleaseOldSourceFile: onReleaseOldSourceFile, + hasInvalidatedResolution: hasInvalidatedResolution, + hasChangedAutomaticTypeDirectiveNames: host.hasChangedAutomaticTypeDirectiveNames + }; + if (host.trace) { + compilerHost.trace = function (message) { return host.trace(message); }; + } + if (host.resolveModuleNames) { + compilerHost.resolveModuleNames = function (moduleNames, containingFile, reusedNames, redirectedReference) { return host.resolveModuleNames(moduleNames, containingFile, reusedNames, redirectedReference); }; + } + if (host.resolveTypeReferenceDirectives) { + compilerHost.resolveTypeReferenceDirectives = function (typeReferenceDirectiveNames, containingFile, redirectedReference) { + return host.resolveTypeReferenceDirectives(typeReferenceDirectiveNames, containingFile, redirectedReference); + }; + } + var documentRegistryBucketKey = documentRegistry.getKeyForCompilationSettings(newSettings); + var options = { + rootNames: rootFileNames, + options: newSettings, + host: compilerHost, + oldProgram: program, + projectReferences: projectReferences + }; + program = ts.createProgram(options); + // hostCache is captured in the closure for 'getOrCreateSourceFile' but it should not be used past this point. + // It needs to be cleared to allow all collected snapshots to be released + hostCache = undefined; + // We reset this cache on structure invalidation so we don't hold on to outdated files for long; however we can't use the `compilerHost` above, + // Because it only functions until `hostCache` is cleared, while we'll potentially need the functionality to lazily read sourcemap files during + // the course of whatever called `synchronizeHostData` + sourceMapper.clearCache(); + // Make sure all the nodes in the program are both bound, and have their parent + // pointers set property. + program.getTypeChecker(); + return; + function fileExists(fileName) { + var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); + var entry = hostCache && hostCache.getEntryByPath(path); + return entry ? + !ts.isString(entry) : + (!!host.fileExists && host.fileExists(fileName)); + } + // Release any files we have acquired in the old program but are + // not part of the new program. + function onReleaseOldSourceFile(oldSourceFile, oldOptions) { + var oldSettingsKey = documentRegistry.getKeyForCompilationSettings(oldOptions); + documentRegistry.releaseDocumentWithKey(oldSourceFile.resolvedPath, oldSettingsKey); + } + function getOrCreateSourceFile(fileName, languageVersion, onError, shouldCreateNewSourceFile) { + return getOrCreateSourceFileByPath(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), languageVersion, onError, shouldCreateNewSourceFile); + } + function getOrCreateSourceFileByPath(fileName, path, _languageVersion, _onError, shouldCreateNewSourceFile) { + ts.Debug.assert(hostCache !== undefined, "getOrCreateSourceFileByPath called after typical CompilerHost lifetime, check the callstack something with a reference to an old host."); + // The program is asking for this file, check first if the host can locate it. + // If the host can not locate the file, then it does not exist. return undefined + // to the program to allow reporting of errors for missing files. + var hostFileInformation = hostCache && hostCache.getOrCreateEntryByPath(fileName, path); + if (!hostFileInformation) { + return undefined; + } + // Check if the language version has changed since we last created a program; if they are the same, + // it is safe to reuse the sourceFiles; if not, then the shape of the AST can change, and the oldSourceFile + // can not be reused. we have to dump all syntax trees and create new ones. + if (!shouldCreateNewSourceFile) { + // Check if the old program had this file already + var oldSourceFile = program && program.getSourceFileByPath(path); + if (oldSourceFile) { + // We already had a source file for this file name. Go to the registry to + // ensure that we get the right up to date version of it. We need this to + // address the following race-condition. Specifically, say we have the following: + // + // LS1 + // \ + // DocumentRegistry + // / + // LS2 + // + // Each LS has a reference to file 'foo.ts' at version 1. LS2 then updates + // it's version of 'foo.ts' to version 2. This will cause LS2 and the + // DocumentRegistry to have version 2 of the document. HOwever, LS1 will + // have version 1. And *importantly* this source file will be *corrupt*. + // The act of creating version 2 of the file irrevocably damages the version + // 1 file. + // + // So, later when we call into LS1, we need to make sure that it doesn't use + // it's source file any more, and instead defers to DocumentRegistry to get + // either version 1, version 2 (or some other version) depending on what the + // host says should be used. + // We do not support the scenario where a host can modify a registered + // file's script kind, i.e. in one project some file is treated as ".ts" + // and in another as ".js" + ts.Debug.assertEqual(hostFileInformation.scriptKind, oldSourceFile.scriptKind, "Registered script kind should match new script kind.", path); + return documentRegistry.updateDocumentWithKey(fileName, path, newSettings, documentRegistryBucketKey, hostFileInformation.scriptSnapshot, hostFileInformation.version, hostFileInformation.scriptKind); + } + // We didn't already have the file. Fall through and acquire it from the registry. + } + // Could not find this file in the old program, create a new SourceFile for it. + return documentRegistry.acquireDocumentWithKey(fileName, path, newSettings, documentRegistryBucketKey, hostFileInformation.scriptSnapshot, hostFileInformation.version, hostFileInformation.scriptKind); + } + } + // TODO: GH#18217 frequently asserted as defined + function getProgram() { + if (syntaxOnly) { + ts.Debug.assert(program === undefined); + return undefined; + } + synchronizeHostData(); + return program; + } + function cleanupSemanticCache() { + program = undefined; // TODO: GH#18217 + } + function dispose() { + if (program) { + ts.forEach(program.getSourceFiles(), function (f) { + return documentRegistry.releaseDocument(f.fileName, program.getCompilerOptions()); + }); + program = undefined; // TODO: GH#18217 + } + host = undefined; + } + /// Diagnostics + function getSyntacticDiagnostics(fileName) { + synchronizeHostData(); + return program.getSyntacticDiagnostics(getValidSourceFile(fileName), cancellationToken).slice(); + } + /** + * getSemanticDiagnostics return array of Diagnostics. If '-d' is not enabled, only report semantic errors + * If '-d' enabled, report both semantic and emitter errors + */ + function getSemanticDiagnostics(fileName) { + synchronizeHostData(); + var targetSourceFile = getValidSourceFile(fileName); + // Only perform the action per file regardless of '-out' flag as LanguageServiceHost is expected to call this function per file. + // Therefore only get diagnostics for given file. + var semanticDiagnostics = program.getSemanticDiagnostics(targetSourceFile, cancellationToken); + if (!ts.getEmitDeclarations(program.getCompilerOptions())) { + return semanticDiagnostics.slice(); + } + // If '-d' is enabled, check for emitter error. One example of emitter error is export class implements non-export interface + var declarationDiagnostics = program.getDeclarationDiagnostics(targetSourceFile, cancellationToken); + return semanticDiagnostics.concat(declarationDiagnostics); + } + function getSuggestionDiagnostics(fileName) { + synchronizeHostData(); + return ts.computeSuggestionDiagnostics(getValidSourceFile(fileName), program, cancellationToken); + } + function getCompilerOptionsDiagnostics() { + synchronizeHostData(); + return program.getOptionsDiagnostics(cancellationToken).concat(program.getGlobalDiagnostics(cancellationToken)); + } + function getCompletionsAtPosition(fileName, position, options) { + if (options === void 0) { options = ts.emptyOptions; } + // Convert from deprecated options names to new names + var fullPreferences = __assign({}, ts.identity(options), { includeCompletionsForModuleExports: options.includeCompletionsForModuleExports || options.includeExternalModuleExports, includeCompletionsWithInsertText: options.includeCompletionsWithInsertText || options.includeInsertTextCompletions }); + synchronizeHostData(); + return ts.Completions.getCompletionsAtPosition(host, program, log, getValidSourceFile(fileName), position, fullPreferences, options.triggerCharacter); + } + function getCompletionEntryDetails(fileName, position, name, formattingOptions, source, preferences) { + if (preferences === void 0) { preferences = ts.emptyOptions; } + synchronizeHostData(); + return ts.Completions.getCompletionEntryDetails(program, log, getValidSourceFile(fileName), position, { name: name, source: source }, host, (formattingOptions && ts.formatting.getFormatContext(formattingOptions)), // TODO: GH#18217 + preferences, cancellationToken); + } + function getCompletionEntrySymbol(fileName, position, name, source) { + synchronizeHostData(); + return ts.Completions.getCompletionEntrySymbol(program, log, getValidSourceFile(fileName), position, { name: name, source: source }); + } + function getQuickInfoAtPosition(fileName, position) { + synchronizeHostData(); + var sourceFile = getValidSourceFile(fileName); + var node = ts.getTouchingPropertyName(sourceFile, position); + if (node === sourceFile) { + // Avoid giving quickInfo for the sourceFile as a whole. + return undefined; + } + var typeChecker = program.getTypeChecker(); + var symbol = getSymbolAtLocationForQuickInfo(node, typeChecker); + if (!symbol || typeChecker.isUnknownSymbol(symbol)) { + var type_7 = shouldGetType(sourceFile, node, position) ? typeChecker.getTypeAtLocation(node) : undefined; + return type_7 && { + kind: "" /* unknown */, + kindModifiers: "" /* none */, + textSpan: ts.createTextSpanFromNode(node, sourceFile), + displayParts: typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { return ts.typeToDisplayParts(typeChecker, type_7, ts.getContainerNode(node)); }), + documentation: type_7.symbol ? type_7.symbol.getDocumentationComment(typeChecker) : undefined, + tags: type_7.symbol ? type_7.symbol.getJsDocTags() : undefined + }; + } + var _a = typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { + return ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, ts.getContainerNode(node), node); + }), symbolKind = _a.symbolKind, displayParts = _a.displayParts, documentation = _a.documentation, tags = _a.tags; + return { + kind: symbolKind, + kindModifiers: ts.SymbolDisplay.getSymbolModifiers(symbol), + textSpan: ts.createTextSpanFromNode(node, sourceFile), + displayParts: displayParts, + documentation: documentation, + tags: tags, + }; + } + function shouldGetType(sourceFile, node, position) { + switch (node.kind) { + case 72 /* Identifier */: + return !ts.isLabelName(node) && !ts.isTagName(node); + case 189 /* PropertyAccessExpression */: + case 148 /* QualifiedName */: + // Don't return quickInfo if inside the comment in `a/**/.b` + return !ts.isInComment(sourceFile, position); + case 100 /* ThisKeyword */: + case 178 /* ThisType */: + case 98 /* SuperKeyword */: + return true; + default: + return false; + } + } + /// Goto definition + function getDefinitionAtPosition(fileName, position) { + synchronizeHostData(); + return ts.GoToDefinition.getDefinitionAtPosition(program, getValidSourceFile(fileName), position); + } + function getDefinitionAndBoundSpan(fileName, position) { + synchronizeHostData(); + return ts.GoToDefinition.getDefinitionAndBoundSpan(program, getValidSourceFile(fileName), position); + } + function getTypeDefinitionAtPosition(fileName, position) { + synchronizeHostData(); + return ts.GoToDefinition.getTypeDefinitionAtPosition(program.getTypeChecker(), getValidSourceFile(fileName), position); + } + /// Goto implementation + function getImplementationAtPosition(fileName, position) { + synchronizeHostData(); + return ts.FindAllReferences.getImplementationsAtPosition(program, cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position); + } + /// References and Occurrences + function getOccurrencesAtPosition(fileName, position) { + return ts.flatMap(getDocumentHighlights(fileName, position, [fileName]), function (entry) { return entry.highlightSpans.map(function (highlightSpan) { return ({ + fileName: entry.fileName, + textSpan: highlightSpan.textSpan, + isWriteAccess: highlightSpan.kind === "writtenReference" /* writtenReference */, + isDefinition: false, + isInString: highlightSpan.isInString, + }); }); }); + } + function getDocumentHighlights(fileName, position, filesToSearch) { + var normalizedFileName = ts.normalizePath(fileName); + ts.Debug.assert(filesToSearch.some(function (f) { return ts.normalizePath(f) === normalizedFileName; })); + synchronizeHostData(); + var sourceFilesToSearch = filesToSearch.map(getValidSourceFile); + var sourceFile = getValidSourceFile(fileName); + return ts.DocumentHighlights.getDocumentHighlights(program, cancellationToken, sourceFile, position, sourceFilesToSearch); + } + function findRenameLocations(fileName, position, findInStrings, findInComments) { + synchronizeHostData(); + var sourceFile = getValidSourceFile(fileName); + var node = ts.getTouchingPropertyName(sourceFile, position); + if (ts.isIdentifier(node) && (ts.isJsxOpeningElement(node.parent) || ts.isJsxClosingElement(node.parent)) && ts.isIntrinsicJsxName(node.escapedText)) { + var _a = node.parent.parent, openingElement = _a.openingElement, closingElement = _a.closingElement; + return [openingElement, closingElement].map(function (node) { + return ({ fileName: sourceFile.fileName, textSpan: ts.createTextSpanFromNode(node.tagName, sourceFile) }); + }); + } + else { + return getReferencesWorker(node, position, { findInStrings: findInStrings, findInComments: findInComments, isForRename: true }, ts.FindAllReferences.toRenameLocation); + } + } + function getReferencesAtPosition(fileName, position) { + synchronizeHostData(); + return getReferencesWorker(ts.getTouchingPropertyName(getValidSourceFile(fileName), position), position, {}, ts.FindAllReferences.toReferenceEntry); + } + function getReferencesWorker(node, position, options, cb) { + synchronizeHostData(); + // Exclude default library when renaming as commonly user don't want to change that file. + var sourceFiles = options && options.isForRename + ? program.getSourceFiles().filter(function (sourceFile) { return !program.isSourceFileDefaultLibrary(sourceFile); }) + : program.getSourceFiles(); + return ts.FindAllReferences.findReferenceOrRenameEntries(program, cancellationToken, sourceFiles, node, position, options, cb); + } + function findReferences(fileName, position) { + synchronizeHostData(); + return ts.FindAllReferences.findReferencedSymbols(program, cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position); + } + function getNavigateToItems(searchValue, maxResultCount, fileName, excludeDtsFiles) { + if (excludeDtsFiles === void 0) { excludeDtsFiles = false; } + synchronizeHostData(); + var sourceFiles = fileName ? [getValidSourceFile(fileName)] : program.getSourceFiles(); + return ts.NavigateTo.getNavigateToItems(sourceFiles, program.getTypeChecker(), cancellationToken, searchValue, maxResultCount, excludeDtsFiles); + } + function getEmitOutput(fileName, emitOnlyDtsFiles) { + if (emitOnlyDtsFiles === void 0) { emitOnlyDtsFiles = false; } + synchronizeHostData(); + var sourceFile = getValidSourceFile(fileName); + var customTransformers = host.getCustomTransformers && host.getCustomTransformers(); + return ts.getFileEmitOutput(program, sourceFile, emitOnlyDtsFiles, cancellationToken, customTransformers); + } + // Signature help + /** + * This is a semantic operation. + */ + function getSignatureHelpItems(fileName, position, _a) { + var triggerReason = (_a === void 0 ? ts.emptyOptions : _a).triggerReason; + synchronizeHostData(); + var sourceFile = getValidSourceFile(fileName); + return ts.SignatureHelp.getSignatureHelpItems(program, sourceFile, position, triggerReason, cancellationToken); + } + /// Syntactic features + function getNonBoundSourceFile(fileName) { + return syntaxTreeCache.getCurrentSourceFile(fileName); + } + function getNameOrDottedNameSpan(fileName, startPos, _endPos) { + var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); + // Get node at the location + var node = ts.getTouchingPropertyName(sourceFile, startPos); + if (node === sourceFile) { + return undefined; + } + switch (node.kind) { + case 189 /* PropertyAccessExpression */: + case 148 /* QualifiedName */: + case 10 /* StringLiteral */: + case 87 /* FalseKeyword */: + case 102 /* TrueKeyword */: + case 96 /* NullKeyword */: + case 98 /* SuperKeyword */: + case 100 /* ThisKeyword */: + case 178 /* ThisType */: + case 72 /* Identifier */: + break; + // Cant create the text span + default: + return undefined; + } + var nodeForStartPos = node; + while (true) { + if (ts.isRightSideOfPropertyAccess(nodeForStartPos) || ts.isRightSideOfQualifiedName(nodeForStartPos)) { + // If on the span is in right side of the the property or qualified name, return the span from the qualified name pos to end of this node + nodeForStartPos = nodeForStartPos.parent; + } + else if (ts.isNameOfModuleDeclaration(nodeForStartPos)) { + // If this is name of a module declarations, check if this is right side of dotted module name + // If parent of the module declaration which is parent of this node is module declaration and its body is the module declaration that this node is name of + // Then this name is name from dotted module + if (nodeForStartPos.parent.parent.kind === 244 /* ModuleDeclaration */ && + nodeForStartPos.parent.parent.body === nodeForStartPos.parent) { + // Use parent module declarations name for start pos + nodeForStartPos = nodeForStartPos.parent.parent.name; + } + else { + // We have to use this name for start pos + break; + } + } + else { + // Is not a member expression so we have found the node for start pos + break; + } + } + return ts.createTextSpanFromBounds(nodeForStartPos.getStart(), node.getEnd()); + } + function getBreakpointStatementAtPosition(fileName, position) { + // doesn't use compiler - no need to synchronize with host + var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); + return ts.BreakpointResolver.spanInSourceFileAtLocation(sourceFile, position); + } + function getNavigationBarItems(fileName) { + return ts.NavigationBar.getNavigationBarItems(syntaxTreeCache.getCurrentSourceFile(fileName), cancellationToken); + } + function getNavigationTree(fileName) { + return ts.NavigationBar.getNavigationTree(syntaxTreeCache.getCurrentSourceFile(fileName), cancellationToken); + } + function isTsOrTsxFile(fileName) { + var kind = ts.getScriptKind(fileName, host); + return kind === 3 /* TS */ || kind === 4 /* TSX */; + } + function getSemanticClassifications(fileName, span) { + if (!isTsOrTsxFile(fileName)) { + // do not run semantic classification on non-ts-or-tsx files + return []; + } + synchronizeHostData(); + return ts.getSemanticClassifications(program.getTypeChecker(), cancellationToken, getValidSourceFile(fileName), program.getClassifiableNames(), span); + } + function getEncodedSemanticClassifications(fileName, span) { + if (!isTsOrTsxFile(fileName)) { + // do not run semantic classification on non-ts-or-tsx files + return { spans: [], endOfLineState: 0 /* None */ }; + } + synchronizeHostData(); + return ts.getEncodedSemanticClassifications(program.getTypeChecker(), cancellationToken, getValidSourceFile(fileName), program.getClassifiableNames(), span); + } + function getSyntacticClassifications(fileName, span) { + // doesn't use compiler - no need to synchronize with host + return ts.getSyntacticClassifications(cancellationToken, syntaxTreeCache.getCurrentSourceFile(fileName), span); + } + function getEncodedSyntacticClassifications(fileName, span) { + // doesn't use compiler - no need to synchronize with host + return ts.getEncodedSyntacticClassifications(cancellationToken, syntaxTreeCache.getCurrentSourceFile(fileName), span); + } + function getOutliningSpans(fileName) { + // doesn't use compiler - no need to synchronize with host + var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); + return ts.OutliningElementsCollector.collectElements(sourceFile, cancellationToken); + } + var braceMatching = ts.createMapFromTemplate((_a = {}, + _a[18 /* OpenBraceToken */] = 19 /* CloseBraceToken */, + _a[20 /* OpenParenToken */] = 21 /* CloseParenToken */, + _a[22 /* OpenBracketToken */] = 23 /* CloseBracketToken */, + _a[30 /* GreaterThanToken */] = 28 /* LessThanToken */, + _a)); + braceMatching.forEach(function (value, key) { return braceMatching.set(value.toString(), Number(key)); }); + function getBraceMatchingAtPosition(fileName, position) { + var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); + var token = ts.getTouchingToken(sourceFile, position); + var matchKind = token.getStart(sourceFile) === position ? braceMatching.get(token.kind.toString()) : undefined; + var match = matchKind && ts.findChildOfKind(token.parent, matchKind, sourceFile); + // We want to order the braces when we return the result. + return match ? [ts.createTextSpanFromNode(token, sourceFile), ts.createTextSpanFromNode(match, sourceFile)].sort(function (a, b) { return a.start - b.start; }) : ts.emptyArray; + } + function getIndentationAtPosition(fileName, position, editorOptions) { + var start = ts.timestamp(); + var settings = toEditorSettings(editorOptions); + var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); + log("getIndentationAtPosition: getCurrentSourceFile: " + (ts.timestamp() - start)); + start = ts.timestamp(); + var result = ts.formatting.SmartIndenter.getIndentation(position, sourceFile, settings); + log("getIndentationAtPosition: computeIndentation : " + (ts.timestamp() - start)); + return result; + } + function getFormattingEditsForRange(fileName, start, end, options) { + var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); + return ts.formatting.formatSelection(start, end, sourceFile, ts.formatting.getFormatContext(toEditorSettings(options))); + } + function getFormattingEditsForDocument(fileName, options) { + return ts.formatting.formatDocument(syntaxTreeCache.getCurrentSourceFile(fileName), ts.formatting.getFormatContext(toEditorSettings(options))); + } + function getFormattingEditsAfterKeystroke(fileName, position, key, options) { + var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); + var formatContext = ts.formatting.getFormatContext(toEditorSettings(options)); + if (!ts.isInComment(sourceFile, position)) { + switch (key) { + case "{": + return ts.formatting.formatOnOpeningCurly(position, sourceFile, formatContext); + case "}": + return ts.formatting.formatOnClosingCurly(position, sourceFile, formatContext); + case ";": + return ts.formatting.formatOnSemicolon(position, sourceFile, formatContext); + case "\n": + return ts.formatting.formatOnEnter(position, sourceFile, formatContext); + } + } + return []; + } + function getCodeFixesAtPosition(fileName, start, end, errorCodes, formatOptions, preferences) { + if (preferences === void 0) { preferences = ts.emptyOptions; } + synchronizeHostData(); + var sourceFile = getValidSourceFile(fileName); + var span = ts.createTextSpanFromBounds(start, end); + var formatContext = ts.formatting.getFormatContext(formatOptions); + return ts.flatMap(ts.deduplicate(errorCodes, ts.equateValues, ts.compareValues), function (errorCode) { + cancellationToken.throwIfCancellationRequested(); + return ts.codefix.getFixes({ errorCode: errorCode, sourceFile: sourceFile, span: span, program: program, host: host, cancellationToken: cancellationToken, formatContext: formatContext, preferences: preferences }); + }); + } + function getCombinedCodeFix(scope, fixId, formatOptions, preferences) { + if (preferences === void 0) { preferences = ts.emptyOptions; } + synchronizeHostData(); + ts.Debug.assert(scope.type === "file"); + var sourceFile = getValidSourceFile(scope.fileName); + var formatContext = ts.formatting.getFormatContext(formatOptions); + return ts.codefix.getAllFixes({ fixId: fixId, sourceFile: sourceFile, program: program, host: host, cancellationToken: cancellationToken, formatContext: formatContext, preferences: preferences }); + } + function organizeImports(scope, formatOptions, preferences) { + if (preferences === void 0) { preferences = ts.emptyOptions; } + synchronizeHostData(); + ts.Debug.assert(scope.type === "file"); + var sourceFile = getValidSourceFile(scope.fileName); + var formatContext = ts.formatting.getFormatContext(formatOptions); + return ts.OrganizeImports.organizeImports(sourceFile, formatContext, host, program, preferences); + } + function getEditsForFileRename(oldFilePath, newFilePath, formatOptions, preferences) { + if (preferences === void 0) { preferences = ts.emptyOptions; } + return ts.getEditsForFileRename(getProgram(), oldFilePath, newFilePath, host, ts.formatting.getFormatContext(formatOptions), preferences, sourceMapper); + } + function applyCodeActionCommand(fileName, actionOrFormatSettingsOrUndefined) { + var action = typeof fileName === "string" ? actionOrFormatSettingsOrUndefined : fileName; + var formatSettings = typeof fileName !== "string" ? actionOrFormatSettingsOrUndefined : undefined; + return ts.isArray(action) ? Promise.all(action.map(function (a) { return applySingleCodeActionCommand(a, formatSettings); })) : applySingleCodeActionCommand(action, formatSettings); + } + function applySingleCodeActionCommand(action, formatSettings) { + var getPath = function (path) { return ts.toPath(path, currentDirectory, getCanonicalFileName); }; + switch (action.type) { + case "install package": + return host.installPackage + ? host.installPackage({ fileName: getPath(action.file), packageName: action.packageName }) + : Promise.reject("Host does not implement `installPackage`"); + case "generate types": { + var fileToGenerateTypesFor = action.fileToGenerateTypesFor, outputFileName_1 = action.outputFileName; + if (!host.inspectValue) + return Promise.reject("Host does not implement `installPackage`"); + var valueInfoPromise = host.inspectValue({ fileNameToRequire: fileToGenerateTypesFor }); + return valueInfoPromise.then(function (valueInfo) { + var fullOut = getPath(outputFileName_1); + host.writeFile(fullOut, ts.valueInfoToDeclarationFileText(valueInfo, formatSettings || ts.testFormatSettings)); // TODO: GH#18217 + return { successMessage: "Wrote types to '" + fullOut + "'" }; + }); + } + default: + return ts.Debug.assertNever(action); + } + } + function getDocCommentTemplateAtPosition(fileName, position) { + return ts.JsDoc.getDocCommentTemplateAtPosition(ts.getNewLineOrDefaultFromHost(host), syntaxTreeCache.getCurrentSourceFile(fileName), position); + } + function isValidBraceCompletionAtPosition(fileName, position, openingBrace) { + // '<' is currently not supported, figuring out if we're in a Generic Type vs. a comparison is too + // expensive to do during typing scenarios + // i.e. whether we're dealing with: + // var x = new foo<| ( with class foo{} ) + // or + // var y = 3 <| + if (openingBrace === 60 /* lessThan */) { + return false; + } + var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); + // Check if in a context where we don't want to perform any insertion + if (ts.isInString(sourceFile, position)) { + return false; + } + if (ts.isInsideJsxElementOrAttribute(sourceFile, position)) { + return openingBrace === 123 /* openBrace */; + } + if (ts.isInTemplateString(sourceFile, position)) { + return false; + } + switch (openingBrace) { + case 39 /* singleQuote */: + case 34 /* doubleQuote */: + case 96 /* backtick */: + return !ts.isInComment(sourceFile, position); + } + return true; + } + function getJsxClosingTagAtPosition(fileName, position) { + var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); + var token = ts.findPrecedingToken(position, sourceFile); + if (!token) + return undefined; + var element = token.kind === 30 /* GreaterThanToken */ && ts.isJsxOpeningElement(token.parent) ? token.parent.parent + : ts.isJsxText(token) ? token.parent : undefined; + if (element && isUnclosedTag(element)) { + return { newText: "" }; + } + } + function isUnclosedTag(_a) { + var openingElement = _a.openingElement, closingElement = _a.closingElement, parent = _a.parent; + return !ts.tagNamesAreEquivalent(openingElement.tagName, closingElement.tagName) || + ts.isJsxElement(parent) && ts.tagNamesAreEquivalent(openingElement.tagName, parent.openingElement.tagName) && isUnclosedTag(parent); + } + function getSpanOfEnclosingComment(fileName, position, onlyMultiLine) { + var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); + var range = ts.formatting.getRangeOfEnclosingComment(sourceFile, position); + return range && (!onlyMultiLine || range.kind === 3 /* MultiLineCommentTrivia */) ? ts.createTextSpanFromRange(range) : undefined; + } + function getTodoComments(fileName, descriptors) { + // Note: while getting todo comments seems like a syntactic operation, we actually + // treat it as a semantic operation here. This is because we expect our host to call + // this on every single file. If we treat this syntactically, then that will cause + // us to populate and throw away the tree in our syntax tree cache for each file. By + // treating this as a semantic operation, we can access any tree without throwing + // anything away. + synchronizeHostData(); + var sourceFile = getValidSourceFile(fileName); + cancellationToken.throwIfCancellationRequested(); + var fileContents = sourceFile.text; + var result = []; + // Exclude node_modules files as we don't want to show the todos of external libraries. + if (descriptors.length > 0 && !isNodeModulesFile(sourceFile.fileName)) { + var regExp = getTodoCommentsRegExp(); + var matchArray = void 0; + while (matchArray = regExp.exec(fileContents)) { + cancellationToken.throwIfCancellationRequested(); + // If we got a match, here is what the match array will look like. Say the source text is: + // + // " // hack 1" + // + // The result array with the regexp: will be: + // + // ["// hack 1", "// ", "hack 1", undefined, "hack"] + // + // Here are the relevant capture groups: + // 0) The full match for the entire regexp. + // 1) The preamble to the message portion. + // 2) The message portion. + // 3...N) The descriptor that was matched - by index. 'undefined' for each + // descriptor that didn't match. an actual value if it did match. + // + // i.e. 'undefined' in position 3 above means TODO(jason) didn't match. + // "hack" in position 4 means HACK did match. + var firstDescriptorCaptureIndex = 3; + ts.Debug.assert(matchArray.length === descriptors.length + firstDescriptorCaptureIndex); + var preamble = matchArray[1]; + var matchPosition = matchArray.index + preamble.length; + // OK, we have found a match in the file. This is only an acceptable match if + // it is contained within a comment. + if (!ts.isInComment(sourceFile, matchPosition)) { + continue; + } + var descriptor = void 0; + for (var i = 0; i < descriptors.length; i++) { + if (matchArray[i + firstDescriptorCaptureIndex]) { + descriptor = descriptors[i]; + } + } + if (descriptor === undefined) + return ts.Debug.fail(); + // We don't want to match something like 'TODOBY', so we make sure a non + // letter/digit follows the match. + if (isLetterOrDigit(fileContents.charCodeAt(matchPosition + descriptor.text.length))) { + continue; + } + var message = matchArray[2]; + result.push({ descriptor: descriptor, message: message, position: matchPosition }); + } + } + return result; + function escapeRegExp(str) { + return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"); + } + function getTodoCommentsRegExp() { + // NOTE: `?:` means 'non-capture group'. It allows us to have groups without having to + // filter them out later in the final result array. + // TODO comments can appear in one of the following forms: + // + // 1) // TODO or /////////// TODO + // + // 2) /* TODO or /********** TODO + // + // 3) /* + // * TODO + // */ + // + // The following three regexps are used to match the start of the text up to the TODO + // comment portion. + var singleLineCommentStart = /(?:\/\/+\s*)/.source; + var multiLineCommentStart = /(?:\/\*+\s*)/.source; + var anyNumberOfSpacesAndAsterisksAtStartOfLine = /(?:^(?:\s|\*)*)/.source; + // Match any of the above three TODO comment start regexps. + // Note that the outermost group *is* a capture group. We want to capture the preamble + // so that we can determine the starting position of the TODO comment match. + var preamble = "(" + anyNumberOfSpacesAndAsterisksAtStartOfLine + "|" + singleLineCommentStart + "|" + multiLineCommentStart + ")"; + // Takes the descriptors and forms a regexp that matches them as if they were literals. + // For example, if the descriptors are "TODO(jason)" and "HACK", then this will be: + // + // (?:(TODO\(jason\))|(HACK)) + // + // Note that the outermost group is *not* a capture group, but the innermost groups + // *are* capture groups. By capturing the inner literals we can determine after + // matching which descriptor we are dealing with. + var literals = "(?:" + ts.map(descriptors, function (d) { return "(" + escapeRegExp(d.text) + ")"; }).join("|") + ")"; + // After matching a descriptor literal, the following regexp matches the rest of the + // text up to the end of the line (or */). + var endOfLineOrEndOfComment = /(?:$|\*\/)/.source; + var messageRemainder = /(?:.*?)/.source; + // This is the portion of the match we'll return as part of the TODO comment result. We + // match the literal portion up to the end of the line or end of comment. + var messagePortion = "(" + literals + messageRemainder + ")"; + var regExpString = preamble + messagePortion + endOfLineOrEndOfComment; + // The final regexp will look like this: + // /((?:\/\/+\s*)|(?:\/\*+\s*)|(?:^(?:\s|\*)*))((?:(TODO\(jason\))|(HACK))(?:.*?))(?:$|\*\/)/gim + // The flags of the regexp are important here. + // 'g' is so that we are doing a global search and can find matches several times + // in the input. + // + // 'i' is for case insensitivity (We do this to match C# TODO comment code). + // + // 'm' is so we can find matches in a multi-line input. + return new RegExp(regExpString, "gim"); + } + function isLetterOrDigit(char) { + return (char >= 97 /* a */ && char <= 122 /* z */) || + (char >= 65 /* A */ && char <= 90 /* Z */) || + (char >= 48 /* _0 */ && char <= 57 /* _9 */); + } + function isNodeModulesFile(path) { + return ts.stringContains(path, "/node_modules/"); + } + } + function getRenameInfo(fileName, position) { + synchronizeHostData(); + return ts.Rename.getRenameInfo(program, getValidSourceFile(fileName), position); + } + function getRefactorContext(file, positionOrRange, preferences, formatOptions) { + var _a = typeof positionOrRange === "number" ? [positionOrRange, undefined] : [positionOrRange.pos, positionOrRange.end], startPosition = _a[0], endPosition = _a[1]; + return { + file: file, + startPosition: startPosition, + endPosition: endPosition, + program: getProgram(), + host: host, + formatContext: ts.formatting.getFormatContext(formatOptions), + cancellationToken: cancellationToken, + preferences: preferences, + }; + } + function getApplicableRefactors(fileName, positionOrRange, preferences) { + if (preferences === void 0) { preferences = ts.emptyOptions; } + synchronizeHostData(); + var file = getValidSourceFile(fileName); + return ts.refactor.getApplicableRefactors(getRefactorContext(file, positionOrRange, preferences)); + } + function getEditsForRefactor(fileName, formatOptions, positionOrRange, refactorName, actionName, preferences) { + if (preferences === void 0) { preferences = ts.emptyOptions; } + synchronizeHostData(); + var file = getValidSourceFile(fileName); + return ts.refactor.getEditsForRefactor(getRefactorContext(file, positionOrRange, preferences, formatOptions), refactorName, actionName); + } + return { + dispose: dispose, + cleanupSemanticCache: cleanupSemanticCache, + getSyntacticDiagnostics: getSyntacticDiagnostics, + getSemanticDiagnostics: getSemanticDiagnostics, + getSuggestionDiagnostics: getSuggestionDiagnostics, + getCompilerOptionsDiagnostics: getCompilerOptionsDiagnostics, + getSyntacticClassifications: getSyntacticClassifications, + getSemanticClassifications: getSemanticClassifications, + getEncodedSyntacticClassifications: getEncodedSyntacticClassifications, + getEncodedSemanticClassifications: getEncodedSemanticClassifications, + getCompletionsAtPosition: getCompletionsAtPosition, + getCompletionEntryDetails: getCompletionEntryDetails, + getCompletionEntrySymbol: getCompletionEntrySymbol, + getSignatureHelpItems: getSignatureHelpItems, + getQuickInfoAtPosition: getQuickInfoAtPosition, + getDefinitionAtPosition: getDefinitionAtPosition, + getDefinitionAndBoundSpan: getDefinitionAndBoundSpan, + getImplementationAtPosition: getImplementationAtPosition, + getTypeDefinitionAtPosition: getTypeDefinitionAtPosition, + getReferencesAtPosition: getReferencesAtPosition, + findReferences: findReferences, + getOccurrencesAtPosition: getOccurrencesAtPosition, + getDocumentHighlights: getDocumentHighlights, + getNameOrDottedNameSpan: getNameOrDottedNameSpan, + getBreakpointStatementAtPosition: getBreakpointStatementAtPosition, + getNavigateToItems: getNavigateToItems, + getRenameInfo: getRenameInfo, + findRenameLocations: findRenameLocations, + getNavigationBarItems: getNavigationBarItems, + getNavigationTree: getNavigationTree, + getOutliningSpans: getOutliningSpans, + getTodoComments: getTodoComments, + getBraceMatchingAtPosition: getBraceMatchingAtPosition, + getIndentationAtPosition: getIndentationAtPosition, + getFormattingEditsForRange: getFormattingEditsForRange, + getFormattingEditsForDocument: getFormattingEditsForDocument, + getFormattingEditsAfterKeystroke: getFormattingEditsAfterKeystroke, + getDocCommentTemplateAtPosition: getDocCommentTemplateAtPosition, + isValidBraceCompletionAtPosition: isValidBraceCompletionAtPosition, + getJsxClosingTagAtPosition: getJsxClosingTagAtPosition, + getSpanOfEnclosingComment: getSpanOfEnclosingComment, + getCodeFixesAtPosition: getCodeFixesAtPosition, + getCombinedCodeFix: getCombinedCodeFix, + applyCodeActionCommand: applyCodeActionCommand, + organizeImports: organizeImports, + getEditsForFileRename: getEditsForFileRename, + getEmitOutput: getEmitOutput, + getNonBoundSourceFile: getNonBoundSourceFile, + getProgram: getProgram, + getApplicableRefactors: getApplicableRefactors, + getEditsForRefactor: getEditsForRefactor, + toLineColumnOffset: sourceMapper.toLineColumnOffset, + getSourceMapper: function () { return sourceMapper; }, + }; + } + ts.createLanguageService = createLanguageService; + /* @internal */ + /** Names in the name table are escaped, so an identifier `__foo` will have a name table entry `___foo`. */ + function getNameTable(sourceFile) { + if (!sourceFile.nameTable) { + initializeNameTable(sourceFile); + } + return sourceFile.nameTable; // TODO: GH#18217 + } + ts.getNameTable = getNameTable; + function initializeNameTable(sourceFile) { + var nameTable = sourceFile.nameTable = ts.createUnderscoreEscapedMap(); + sourceFile.forEachChild(function walk(node) { + if (ts.isIdentifier(node) && !ts.isTagName(node) && node.escapedText || ts.isStringOrNumericLiteralLike(node) && literalIsName(node)) { + var text = ts.getEscapedTextOfIdentifierOrLiteral(node); + nameTable.set(text, nameTable.get(text) === undefined ? node.pos : -1); + } + ts.forEachChild(node, walk); + if (ts.hasJSDocNodes(node)) { + for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { + var jsDoc = _a[_i]; + ts.forEachChild(jsDoc, walk); + } + } + }); + } + /** + * We want to store any numbers/strings if they were a name that could be + * related to a declaration. So, if we have 'import x = require("something")' + * then we want 'something' to be in the name table. Similarly, if we have + * "a['propname']" then we want to store "propname" in the name table. + */ + function literalIsName(node) { + return ts.isDeclarationName(node) || + node.parent.kind === 259 /* ExternalModuleReference */ || + isArgumentOfElementAccessExpression(node) || + ts.isLiteralComputedPropertyDeclarationName(node); + } + /** + * Returns the containing object literal property declaration given a possible name node, e.g. "a" in x = { "a": 1 } + */ + /* @internal */ + function getContainingObjectLiteralElement(node) { + var element = getContainingObjectLiteralElementWorker(node); + return element && (ts.isObjectLiteralExpression(element.parent) || ts.isJsxAttributes(element.parent)) ? element : undefined; + } + ts.getContainingObjectLiteralElement = getContainingObjectLiteralElement; + function getContainingObjectLiteralElementWorker(node) { + switch (node.kind) { + case 10 /* StringLiteral */: + case 8 /* NumericLiteral */: + if (node.parent.kind === 149 /* ComputedPropertyName */) { + return ts.isObjectLiteralElement(node.parent.parent) ? node.parent.parent : undefined; + } + // falls through + case 72 /* Identifier */: + return ts.isObjectLiteralElement(node.parent) && + (node.parent.parent.kind === 188 /* ObjectLiteralExpression */ || node.parent.parent.kind === 268 /* JsxAttributes */) && + node.parent.name === node ? node.parent : undefined; + } + return undefined; + } + function getSymbolAtLocationForQuickInfo(node, checker) { + var object = getContainingObjectLiteralElement(node); + if (object) { + var contextualType = checker.getContextualType(object.parent); + var properties = contextualType && getPropertySymbolsFromContextualType(object, checker, contextualType, /*unionSymbolOk*/ false); + if (properties && properties.length === 1) { + return ts.first(properties); + } + } + return checker.getSymbolAtLocation(node); + } + /** Gets all symbols for one property. Does not get symbols for every property. */ + /* @internal */ + function getPropertySymbolsFromContextualType(node, checker, contextualType, unionSymbolOk) { + var name = ts.getNameFromPropertyName(node.name); + if (!name) + return ts.emptyArray; + if (!contextualType.isUnion()) { + var symbol = contextualType.getProperty(name); + return symbol ? [symbol] : ts.emptyArray; + } + var discriminatedPropertySymbols = ts.mapDefined(contextualType.types, function (t) { return ts.isObjectLiteralExpression(node.parent) && checker.isTypeInvalidDueToUnionDiscriminant(t, node.parent) ? undefined : t.getProperty(name); }); + if (unionSymbolOk && (discriminatedPropertySymbols.length === 0 || discriminatedPropertySymbols.length === contextualType.types.length)) { + var symbol = contextualType.getProperty(name); + if (symbol) + return [symbol]; + } + if (discriminatedPropertySymbols.length === 0) { + // Bad discriminant -- do again without discriminating + return ts.mapDefined(contextualType.types, function (t) { return t.getProperty(name); }); + } + return discriminatedPropertySymbols; + } + ts.getPropertySymbolsFromContextualType = getPropertySymbolsFromContextualType; + function isArgumentOfElementAccessExpression(node) { + return node && + node.parent && + node.parent.kind === 190 /* ElementAccessExpression */ && + node.parent.argumentExpression === node; + } + /** + * Get the path of the default library files (lib.d.ts) as distributed with the typescript + * node package. + * The functionality is not supported if the ts module is consumed outside of a node module. + */ + function getDefaultLibFilePath(options) { + // Check __dirname is defined and that we are on a node.js system. + if (typeof __dirname !== "undefined") { + return __dirname + ts.directorySeparator + ts.getDefaultLibFileName(options); + } + throw new Error("getDefaultLibFilePath is only supported when consumed as a node module. "); + } + ts.getDefaultLibFilePath = getDefaultLibFilePath; + ts.objectAllocator = getServicesObjectAllocator(); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var BreakpointResolver; + (function (BreakpointResolver) { + /** + * Get the breakpoint span in given sourceFile + */ + function spanInSourceFileAtLocation(sourceFile, position) { + // Cannot set breakpoint in dts file + if (sourceFile.isDeclarationFile) { + return undefined; + } + var tokenAtLocation = ts.getTokenAtPosition(sourceFile, position); + var lineOfPosition = sourceFile.getLineAndCharacterOfPosition(position).line; + if (sourceFile.getLineAndCharacterOfPosition(tokenAtLocation.getStart(sourceFile)).line > lineOfPosition) { + // Get previous token if the token is returned starts on new line + // eg: let x =10; |--- cursor is here + // let y = 10; + // token at position will return let keyword on second line as the token but we would like to use + // token on same line if trailing trivia (comments or white spaces on same line) part of the last token on that line + var preceding = ts.findPrecedingToken(tokenAtLocation.pos, sourceFile); + // It's a blank line + if (!preceding || sourceFile.getLineAndCharacterOfPosition(preceding.getEnd()).line !== lineOfPosition) { + return undefined; + } + tokenAtLocation = preceding; + } + // Cannot set breakpoint in ambient declarations + if (tokenAtLocation.flags & 4194304 /* Ambient */) { + return undefined; + } + // Get the span in the node based on its syntax + return spanInNode(tokenAtLocation); + function textSpan(startNode, endNode) { + var start = startNode.decorators ? + ts.skipTrivia(sourceFile.text, startNode.decorators.end) : + startNode.getStart(sourceFile); + return ts.createTextSpanFromBounds(start, (endNode || startNode).getEnd()); + } + function textSpanEndingAtNextToken(startNode, previousTokenToFindNextEndToken) { + return textSpan(startNode, ts.findNextToken(previousTokenToFindNextEndToken, previousTokenToFindNextEndToken.parent, sourceFile)); + } + function spanInNodeIfStartsOnSameLine(node, otherwiseOnNode) { + if (node && lineOfPosition === sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile)).line) { + return spanInNode(node); + } + return spanInNode(otherwiseOnNode); + } + function spanInNodeArray(nodeArray) { + return ts.createTextSpanFromBounds(ts.skipTrivia(sourceFile.text, nodeArray.pos), nodeArray.end); + } + function spanInPreviousNode(node) { + return spanInNode(ts.findPrecedingToken(node.pos, sourceFile)); + } + function spanInNextNode(node) { + return spanInNode(ts.findNextToken(node, node.parent, sourceFile)); + } + function spanInNode(node) { + if (node) { + var parent = node.parent; + switch (node.kind) { + case 219 /* VariableStatement */: + // Span on first variable declaration + return spanInVariableDeclaration(node.declarationList.declarations[0]); + case 237 /* VariableDeclaration */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + return spanInVariableDeclaration(node); + case 151 /* Parameter */: + return spanInParameterDeclaration(node); + case 239 /* FunctionDeclaration */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 157 /* Constructor */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + return spanInFunctionDeclaration(node); + case 218 /* Block */: + if (ts.isFunctionBlock(node)) { + return spanInFunctionBlock(node); + } + // falls through + case 245 /* ModuleBlock */: + return spanInBlock(node); + case 274 /* CatchClause */: + return spanInBlock(node.block); + case 221 /* ExpressionStatement */: + // span on the expression + return textSpan(node.expression); + case 230 /* ReturnStatement */: + // span on return keyword and expression if present + return textSpan(node.getChildAt(0), node.expression); + case 224 /* WhileStatement */: + // Span on while(...) + return textSpanEndingAtNextToken(node, node.expression); + case 223 /* DoStatement */: + // span in statement of the do statement + return spanInNode(node.statement); + case 236 /* DebuggerStatement */: + // span on debugger keyword + return textSpan(node.getChildAt(0)); + case 222 /* IfStatement */: + // set on if(..) span + return textSpanEndingAtNextToken(node, node.expression); + case 233 /* LabeledStatement */: + // span in statement + return spanInNode(node.statement); + case 229 /* BreakStatement */: + case 228 /* ContinueStatement */: + // On break or continue keyword and label if present + return textSpan(node.getChildAt(0), node.label); + case 225 /* ForStatement */: + return spanInForStatement(node); + case 226 /* ForInStatement */: + // span of for (a in ...) + return textSpanEndingAtNextToken(node, node.expression); + case 227 /* ForOfStatement */: + // span in initializer + return spanInInitializerOfForLike(node); + case 232 /* SwitchStatement */: + // span on switch(...) + return textSpanEndingAtNextToken(node, node.expression); + case 271 /* CaseClause */: + case 272 /* DefaultClause */: + // span in first statement of the clause + return spanInNode(node.statements[0]); + case 235 /* TryStatement */: + // span in try block + return spanInBlock(node.tryBlock); + case 234 /* ThrowStatement */: + // span in throw ... + return textSpan(node, node.expression); + case 254 /* ExportAssignment */: + // span on export = id + return textSpan(node, node.expression); + case 248 /* ImportEqualsDeclaration */: + // import statement without including semicolon + return textSpan(node, node.moduleReference); + case 249 /* ImportDeclaration */: + // import statement without including semicolon + return textSpan(node, node.moduleSpecifier); + case 255 /* ExportDeclaration */: + // import statement without including semicolon + return textSpan(node, node.moduleSpecifier); + case 244 /* ModuleDeclaration */: + // span on complete module if it is instantiated + if (ts.getModuleInstanceState(node) !== 1 /* Instantiated */) { + return undefined; + } + // falls through + case 240 /* ClassDeclaration */: + case 243 /* EnumDeclaration */: + case 278 /* EnumMember */: + case 186 /* BindingElement */: + // span on complete node + return textSpan(node); + case 231 /* WithStatement */: + // span in statement + return spanInNode(node.statement); + case 152 /* Decorator */: + return spanInNodeArray(parent.decorators); + case 184 /* ObjectBindingPattern */: + case 185 /* ArrayBindingPattern */: + return spanInBindingPattern(node); + // No breakpoint in interface, type alias + case 241 /* InterfaceDeclaration */: + case 242 /* TypeAliasDeclaration */: + return undefined; + // Tokens: + case 26 /* SemicolonToken */: + case 1 /* EndOfFileToken */: + return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(node.pos, sourceFile)); + case 27 /* CommaToken */: + return spanInPreviousNode(node); + case 18 /* OpenBraceToken */: + return spanInOpenBraceToken(node); + case 19 /* CloseBraceToken */: + return spanInCloseBraceToken(node); + case 23 /* CloseBracketToken */: + return spanInCloseBracketToken(node); + case 20 /* OpenParenToken */: + return spanInOpenParenToken(node); + case 21 /* CloseParenToken */: + return spanInCloseParenToken(node); + case 57 /* ColonToken */: + return spanInColonToken(node); + case 30 /* GreaterThanToken */: + case 28 /* LessThanToken */: + return spanInGreaterThanOrLessThanToken(node); + // Keywords: + case 107 /* WhileKeyword */: + return spanInWhileKeyword(node); + case 83 /* ElseKeyword */: + case 75 /* CatchKeyword */: + case 88 /* FinallyKeyword */: + return spanInNextNode(node); + case 147 /* OfKeyword */: + return spanInOfKeyword(node); + default: + // Destructuring pattern in destructuring assignment + // [a, b, c] of + // [a, b, c] = expression + if (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node)) { + return spanInArrayLiteralOrObjectLiteralDestructuringPattern(node); + } + // Set breakpoint on identifier element of destructuring pattern + // `a` or `...c` or `d: x` from + // `[a, b, ...c]` or `{ a, b }` or `{ d: x }` from destructuring pattern + if ((node.kind === 72 /* Identifier */ || + node.kind === 208 /* SpreadElement */ || + node.kind === 275 /* PropertyAssignment */ || + node.kind === 276 /* ShorthandPropertyAssignment */) && + ts.isArrayLiteralOrObjectLiteralDestructuringPattern(parent)) { + return textSpan(node); + } + if (node.kind === 204 /* BinaryExpression */) { + var _a = node, left = _a.left, operatorToken = _a.operatorToken; + // Set breakpoint in destructuring pattern if its destructuring assignment + // [a, b, c] or {a, b, c} of + // [a, b, c] = expression or + // {a, b, c} = expression + if (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(left)) { + return spanInArrayLiteralOrObjectLiteralDestructuringPattern(left); + } + if (operatorToken.kind === 59 /* EqualsToken */ && ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent)) { + // Set breakpoint on assignment expression element of destructuring pattern + // a = expression of + // [a = expression, b, c] = someExpression or + // { a = expression, b, c } = someExpression + return textSpan(node); + } + if (operatorToken.kind === 27 /* CommaToken */) { + return spanInNode(left); + } + } + if (ts.isExpressionNode(node)) { + switch (parent.kind) { + case 223 /* DoStatement */: + // Set span as if on while keyword + return spanInPreviousNode(node); + case 152 /* Decorator */: + // Set breakpoint on the decorator emit + return spanInNode(node.parent); + case 225 /* ForStatement */: + case 227 /* ForOfStatement */: + return textSpan(node); + case 204 /* BinaryExpression */: + if (node.parent.operatorToken.kind === 27 /* CommaToken */) { + // If this is a comma expression, the breakpoint is possible in this expression + return textSpan(node); + } + break; + case 197 /* ArrowFunction */: + if (node.parent.body === node) { + // If this is body of arrow function, it is allowed to have the breakpoint + return textSpan(node); + } + break; + } + } + switch (node.parent.kind) { + case 275 /* PropertyAssignment */: + // If this is name of property assignment, set breakpoint in the initializer + if (node.parent.name === node && + !ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent.parent)) { + return spanInNode(node.parent.initializer); + } + break; + case 194 /* TypeAssertionExpression */: + // Breakpoint in type assertion goes to its operand + if (node.parent.type === node) { + return spanInNextNode(node.parent.type); + } + break; + case 237 /* VariableDeclaration */: + case 151 /* Parameter */: { + // initializer of variable/parameter declaration go to previous node + var _b = node.parent, initializer = _b.initializer, type = _b.type; + if (initializer === node || type === node || ts.isAssignmentOperator(node.kind)) { + return spanInPreviousNode(node); + } + break; + } + case 204 /* BinaryExpression */: { + var left = node.parent.left; + if (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(left) && node !== left) { + // If initializer of destructuring assignment move to previous token + return spanInPreviousNode(node); + } + break; + } + default: + // return type of function go to previous token + if (ts.isFunctionLike(node.parent) && node.parent.type === node) { + return spanInPreviousNode(node); + } + } + // Default go to parent to set the breakpoint + return spanInNode(node.parent); + } + } + function textSpanFromVariableDeclaration(variableDeclaration) { + if (ts.isVariableDeclarationList(variableDeclaration.parent) && variableDeclaration.parent.declarations[0] === variableDeclaration) { + // First declaration - include let keyword + return textSpan(ts.findPrecedingToken(variableDeclaration.pos, sourceFile, variableDeclaration.parent), variableDeclaration); + } + else { + // Span only on this declaration + return textSpan(variableDeclaration); + } + } + function spanInVariableDeclaration(variableDeclaration) { + // If declaration of for in statement, just set the span in parent + if (variableDeclaration.parent.parent.kind === 226 /* ForInStatement */) { + return spanInNode(variableDeclaration.parent.parent); + } + var parent = variableDeclaration.parent; + // If this is a destructuring pattern, set breakpoint in binding pattern + if (ts.isBindingPattern(variableDeclaration.name)) { + return spanInBindingPattern(variableDeclaration.name); + } + // Breakpoint is possible in variableDeclaration only if there is initialization + // or its declaration from 'for of' + if (variableDeclaration.initializer || + ts.hasModifier(variableDeclaration, 1 /* Export */) || + parent.parent.kind === 227 /* ForOfStatement */) { + return textSpanFromVariableDeclaration(variableDeclaration); + } + if (ts.isVariableDeclarationList(variableDeclaration.parent) && + variableDeclaration.parent.declarations[0] !== variableDeclaration) { + // If we cannot set breakpoint on this declaration, set it on previous one + // Because the variable declaration may be binding pattern and + // we would like to set breakpoint in last binding element if that's the case, + // use preceding token instead + return spanInNode(ts.findPrecedingToken(variableDeclaration.pos, sourceFile, variableDeclaration.parent)); + } + } + function canHaveSpanInParameterDeclaration(parameter) { + // Breakpoint is possible on parameter only if it has initializer, is a rest parameter, or has public or private modifier + return !!parameter.initializer || parameter.dotDotDotToken !== undefined || + ts.hasModifier(parameter, 4 /* Public */ | 8 /* Private */); + } + function spanInParameterDeclaration(parameter) { + if (ts.isBindingPattern(parameter.name)) { + // Set breakpoint in binding pattern + return spanInBindingPattern(parameter.name); + } + else if (canHaveSpanInParameterDeclaration(parameter)) { + return textSpan(parameter); + } + else { + var functionDeclaration = parameter.parent; + var indexOfParameter = functionDeclaration.parameters.indexOf(parameter); + ts.Debug.assert(indexOfParameter !== -1); + if (indexOfParameter !== 0) { + // Not a first parameter, go to previous parameter + return spanInParameterDeclaration(functionDeclaration.parameters[indexOfParameter - 1]); + } + else { + // Set breakpoint in the function declaration body + return spanInNode(functionDeclaration.body); + } + } + } + function canFunctionHaveSpanInWholeDeclaration(functionDeclaration) { + return ts.hasModifier(functionDeclaration, 1 /* Export */) || + (functionDeclaration.parent.kind === 240 /* ClassDeclaration */ && functionDeclaration.kind !== 157 /* Constructor */); + } + function spanInFunctionDeclaration(functionDeclaration) { + // No breakpoints in the function signature + if (!functionDeclaration.body) { + return undefined; + } + if (canFunctionHaveSpanInWholeDeclaration(functionDeclaration)) { + // Set the span on whole function declaration + return textSpan(functionDeclaration); + } + // Set span in function body + return spanInNode(functionDeclaration.body); + } + function spanInFunctionBlock(block) { + var nodeForSpanInBlock = block.statements.length ? block.statements[0] : block.getLastToken(); + if (canFunctionHaveSpanInWholeDeclaration(block.parent)) { + return spanInNodeIfStartsOnSameLine(block.parent, nodeForSpanInBlock); + } + return spanInNode(nodeForSpanInBlock); + } + function spanInBlock(block) { + switch (block.parent.kind) { + case 244 /* ModuleDeclaration */: + if (ts.getModuleInstanceState(block.parent) !== 1 /* Instantiated */) { + return undefined; + } + // falls through + // Set on parent if on same line otherwise on first statement + case 224 /* WhileStatement */: + case 222 /* IfStatement */: + case 226 /* ForInStatement */: + return spanInNodeIfStartsOnSameLine(block.parent, block.statements[0]); + // Set span on previous token if it starts on same line otherwise on the first statement of the block + case 225 /* ForStatement */: + case 227 /* ForOfStatement */: + return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(block.pos, sourceFile, block.parent), block.statements[0]); + } + // Default action is to set on first statement + return spanInNode(block.statements[0]); + } + function spanInInitializerOfForLike(forLikeStatement) { + if (forLikeStatement.initializer.kind === 238 /* VariableDeclarationList */) { + // Declaration list - set breakpoint in first declaration + var variableDeclarationList = forLikeStatement.initializer; + if (variableDeclarationList.declarations.length > 0) { + return spanInNode(variableDeclarationList.declarations[0]); + } + } + else { + // Expression - set breakpoint in it + return spanInNode(forLikeStatement.initializer); + } + } + function spanInForStatement(forStatement) { + if (forStatement.initializer) { + return spanInInitializerOfForLike(forStatement); + } + if (forStatement.condition) { + return textSpan(forStatement.condition); + } + if (forStatement.incrementor) { + return textSpan(forStatement.incrementor); + } + } + function spanInBindingPattern(bindingPattern) { + // Set breakpoint in first binding element + var firstBindingElement = ts.forEach(bindingPattern.elements, function (element) { return element.kind !== 210 /* OmittedExpression */ ? element : undefined; }); + if (firstBindingElement) { + return spanInNode(firstBindingElement); + } + // Empty binding pattern of binding element, set breakpoint on binding element + if (bindingPattern.parent.kind === 186 /* BindingElement */) { + return textSpan(bindingPattern.parent); + } + // Variable declaration is used as the span + return textSpanFromVariableDeclaration(bindingPattern.parent); + } + function spanInArrayLiteralOrObjectLiteralDestructuringPattern(node) { + ts.Debug.assert(node.kind !== 185 /* ArrayBindingPattern */ && node.kind !== 184 /* ObjectBindingPattern */); + var elements = node.kind === 187 /* ArrayLiteralExpression */ ? node.elements : node.properties; + var firstBindingElement = ts.forEach(elements, function (element) { return element.kind !== 210 /* OmittedExpression */ ? element : undefined; }); + if (firstBindingElement) { + return spanInNode(firstBindingElement); + } + // Could be ArrayLiteral from destructuring assignment or + // just nested element in another destructuring assignment + // set breakpoint on assignment when parent is destructuring assignment + // Otherwise set breakpoint for this element + return textSpan(node.parent.kind === 204 /* BinaryExpression */ ? node.parent : node); + } + // Tokens: + function spanInOpenBraceToken(node) { + switch (node.parent.kind) { + case 243 /* EnumDeclaration */: + var enumDeclaration = node.parent; + return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(node.pos, sourceFile, node.parent), enumDeclaration.members.length ? enumDeclaration.members[0] : enumDeclaration.getLastToken(sourceFile)); + case 240 /* ClassDeclaration */: + var classDeclaration = node.parent; + return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(node.pos, sourceFile, node.parent), classDeclaration.members.length ? classDeclaration.members[0] : classDeclaration.getLastToken(sourceFile)); + case 246 /* CaseBlock */: + return spanInNodeIfStartsOnSameLine(node.parent.parent, node.parent.clauses[0]); + } + // Default to parent node + return spanInNode(node.parent); + } + function spanInCloseBraceToken(node) { + switch (node.parent.kind) { + case 245 /* ModuleBlock */: + // If this is not an instantiated module block, no bp span + if (ts.getModuleInstanceState(node.parent.parent) !== 1 /* Instantiated */) { + return undefined; + } + // falls through + case 243 /* EnumDeclaration */: + case 240 /* ClassDeclaration */: + // Span on close brace token + return textSpan(node); + case 218 /* Block */: + if (ts.isFunctionBlock(node.parent)) { + // Span on close brace token + return textSpan(node); + } + // falls through + case 274 /* CatchClause */: + return spanInNode(ts.lastOrUndefined(node.parent.statements)); + case 246 /* CaseBlock */: + // breakpoint in last statement of the last clause + var caseBlock = node.parent; + var lastClause = ts.lastOrUndefined(caseBlock.clauses); + if (lastClause) { + return spanInNode(ts.lastOrUndefined(lastClause.statements)); + } + return undefined; + case 184 /* ObjectBindingPattern */: + // Breakpoint in last binding element or binding pattern if it contains no elements + var bindingPattern = node.parent; + return spanInNode(ts.lastOrUndefined(bindingPattern.elements) || bindingPattern); + // Default to parent node + default: + if (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent)) { + // Breakpoint in last binding element or binding pattern if it contains no elements + var objectLiteral = node.parent; + return textSpan(ts.lastOrUndefined(objectLiteral.properties) || objectLiteral); + } + return spanInNode(node.parent); + } + } + function spanInCloseBracketToken(node) { + switch (node.parent.kind) { + case 185 /* ArrayBindingPattern */: + // Breakpoint in last binding element or binding pattern if it contains no elements + var bindingPattern = node.parent; + return textSpan(ts.lastOrUndefined(bindingPattern.elements) || bindingPattern); + default: + if (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent)) { + // Breakpoint in last binding element or binding pattern if it contains no elements + var arrayLiteral = node.parent; + return textSpan(ts.lastOrUndefined(arrayLiteral.elements) || arrayLiteral); + } + // Default to parent node + return spanInNode(node.parent); + } + } + function spanInOpenParenToken(node) { + if (node.parent.kind === 223 /* DoStatement */ || // Go to while keyword and do action instead + node.parent.kind === 191 /* CallExpression */ || + node.parent.kind === 192 /* NewExpression */) { + return spanInPreviousNode(node); + } + if (node.parent.kind === 195 /* ParenthesizedExpression */) { + return spanInNextNode(node); + } + // Default to parent node + return spanInNode(node.parent); + } + function spanInCloseParenToken(node) { + // Is this close paren token of parameter list, set span in previous token + switch (node.parent.kind) { + case 196 /* FunctionExpression */: + case 239 /* FunctionDeclaration */: + case 197 /* ArrowFunction */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 157 /* Constructor */: + case 224 /* WhileStatement */: + case 223 /* DoStatement */: + case 225 /* ForStatement */: + case 227 /* ForOfStatement */: + case 191 /* CallExpression */: + case 192 /* NewExpression */: + case 195 /* ParenthesizedExpression */: + return spanInPreviousNode(node); + // Default to parent node + default: + return spanInNode(node.parent); + } + } + function spanInColonToken(node) { + // Is this : specifying return annotation of the function declaration + if (ts.isFunctionLike(node.parent) || + node.parent.kind === 275 /* PropertyAssignment */ || + node.parent.kind === 151 /* Parameter */) { + return spanInPreviousNode(node); + } + return spanInNode(node.parent); + } + function spanInGreaterThanOrLessThanToken(node) { + if (node.parent.kind === 194 /* TypeAssertionExpression */) { + return spanInNextNode(node); + } + return spanInNode(node.parent); + } + function spanInWhileKeyword(node) { + if (node.parent.kind === 223 /* DoStatement */) { + // Set span on while expression + return textSpanEndingAtNextToken(node, node.parent.expression); + } + // Default to parent node + return spanInNode(node.parent); + } + function spanInOfKeyword(node) { + if (node.parent.kind === 227 /* ForOfStatement */) { + // Set using next token + return spanInNextNode(node); + } + // Default to parent node + return spanInNode(node.parent); + } + } + } + BreakpointResolver.spanInSourceFileAtLocation = spanInSourceFileAtLocation; + })(BreakpointResolver = ts.BreakpointResolver || (ts.BreakpointResolver = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + /** + * Transform one or more nodes using the supplied transformers. + * @param source A single `Node` or an array of `Node` objects. + * @param transformers An array of `TransformerFactory` callbacks used to process the transformation. + * @param compilerOptions Optional compiler options. + */ + function transform(source, transformers, compilerOptions) { + var diagnostics = []; + compilerOptions = ts.fixupCompilerOptions(compilerOptions, diagnostics); // TODO: GH#18217 + var nodes = ts.isArray(source) ? source : [source]; + var result = ts.transformNodes(/*resolver*/ undefined, /*emitHost*/ undefined, compilerOptions, nodes, transformers, /*allowDtsFiles*/ true); + result.diagnostics = ts.concatenate(result.diagnostics, diagnostics); + return result; + } + ts.transform = transform; +})(ts || (ts = {})); +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +/* @internal */ +var debugObjectHost = (function () { return this; })(); +// We need to use 'null' to interface with the managed side. +/* tslint:disable:no-null-keyword */ +/* tslint:disable:no-in-operator */ +/* @internal */ +var ts; +(function (ts) { + function logInternalError(logger, err) { + if (logger) { + logger.log("*INTERNAL ERROR* - Exception in typescript services: " + err.message); + } + } + var ScriptSnapshotShimAdapter = /** @class */ (function () { + function ScriptSnapshotShimAdapter(scriptSnapshotShim) { + this.scriptSnapshotShim = scriptSnapshotShim; + } + ScriptSnapshotShimAdapter.prototype.getText = function (start, end) { + return this.scriptSnapshotShim.getText(start, end); + }; + ScriptSnapshotShimAdapter.prototype.getLength = function () { + return this.scriptSnapshotShim.getLength(); + }; + ScriptSnapshotShimAdapter.prototype.getChangeRange = function (oldSnapshot) { + var oldSnapshotShim = oldSnapshot; + var encoded = this.scriptSnapshotShim.getChangeRange(oldSnapshotShim.scriptSnapshotShim); + if (encoded === null) { + return null; // TODO: GH#18217 + } + var decoded = JSON.parse(encoded); // TODO: GH#18217 + return ts.createTextChangeRange(ts.createTextSpan(decoded.span.start, decoded.span.length), decoded.newLength); + }; + ScriptSnapshotShimAdapter.prototype.dispose = function () { + // if scriptSnapshotShim is a COM object then property check becomes method call with no arguments + // 'in' does not have this effect + if ("dispose" in this.scriptSnapshotShim) { + this.scriptSnapshotShim.dispose(); // TODO: GH#18217 Can we just use `if (this.scriptSnapshotShim.dispose)`? + } + }; + return ScriptSnapshotShimAdapter; + }()); + var LanguageServiceShimHostAdapter = /** @class */ (function () { + function LanguageServiceShimHostAdapter(shimHost) { + var _this = this; + this.shimHost = shimHost; + this.loggingEnabled = false; + this.tracingEnabled = false; + // if shimHost is a COM object then property check will become method call with no arguments. + // 'in' does not have this effect. + if ("getModuleResolutionsForFile" in this.shimHost) { + this.resolveModuleNames = function (moduleNames, containingFile) { + var resolutionsInFile = JSON.parse(_this.shimHost.getModuleResolutionsForFile(containingFile)); // TODO: GH#18217 + return ts.map(moduleNames, function (name) { + var result = ts.getProperty(resolutionsInFile, name); + return result ? { resolvedFileName: result, extension: ts.extensionFromPath(result), isExternalLibraryImport: false } : undefined; + }); + }; + } + if ("directoryExists" in this.shimHost) { + this.directoryExists = function (directoryName) { return _this.shimHost.directoryExists(directoryName); }; + } + if ("getTypeReferenceDirectiveResolutionsForFile" in this.shimHost) { + this.resolveTypeReferenceDirectives = function (typeDirectiveNames, containingFile) { + var typeDirectivesForFile = JSON.parse(_this.shimHost.getTypeReferenceDirectiveResolutionsForFile(containingFile)); // TODO: GH#18217 + return ts.map(typeDirectiveNames, function (name) { return ts.getProperty(typeDirectivesForFile, name); }); + }; + } + } + LanguageServiceShimHostAdapter.prototype.log = function (s) { + if (this.loggingEnabled) { + this.shimHost.log(s); + } + }; + LanguageServiceShimHostAdapter.prototype.trace = function (s) { + if (this.tracingEnabled) { + this.shimHost.trace(s); + } + }; + LanguageServiceShimHostAdapter.prototype.error = function (s) { + this.shimHost.error(s); + }; + LanguageServiceShimHostAdapter.prototype.getProjectVersion = function () { + if (!this.shimHost.getProjectVersion) { + // shimmed host does not support getProjectVersion + return undefined; // TODO: GH#18217 + } + return this.shimHost.getProjectVersion(); + }; + LanguageServiceShimHostAdapter.prototype.getTypeRootsVersion = function () { + if (!this.shimHost.getTypeRootsVersion) { + return 0; + } + return this.shimHost.getTypeRootsVersion(); + }; + LanguageServiceShimHostAdapter.prototype.useCaseSensitiveFileNames = function () { + return this.shimHost.useCaseSensitiveFileNames ? this.shimHost.useCaseSensitiveFileNames() : false; + }; + LanguageServiceShimHostAdapter.prototype.getCompilationSettings = function () { + var settingsJson = this.shimHost.getCompilationSettings(); + if (settingsJson === null || settingsJson === "") { + throw Error("LanguageServiceShimHostAdapter.getCompilationSettings: empty compilationSettings"); + } + var compilerOptions = JSON.parse(settingsJson); + // permit language service to handle all files (filtering should be performed on the host side) + compilerOptions.allowNonTsExtensions = true; + return compilerOptions; + }; + LanguageServiceShimHostAdapter.prototype.getScriptFileNames = function () { + var encoded = this.shimHost.getScriptFileNames(); + return JSON.parse(encoded); + }; + LanguageServiceShimHostAdapter.prototype.getScriptSnapshot = function (fileName) { + var scriptSnapshot = this.shimHost.getScriptSnapshot(fileName); + return scriptSnapshot && new ScriptSnapshotShimAdapter(scriptSnapshot); + }; + LanguageServiceShimHostAdapter.prototype.getScriptKind = function (fileName) { + if ("getScriptKind" in this.shimHost) { + return this.shimHost.getScriptKind(fileName); // TODO: GH#18217 + } + else { + return 0 /* Unknown */; + } + }; + LanguageServiceShimHostAdapter.prototype.getScriptVersion = function (fileName) { + return this.shimHost.getScriptVersion(fileName); + }; + LanguageServiceShimHostAdapter.prototype.getLocalizedDiagnosticMessages = function () { + var diagnosticMessagesJson = this.shimHost.getLocalizedDiagnosticMessages(); + if (diagnosticMessagesJson === null || diagnosticMessagesJson === "") { + return null; + } + try { + return JSON.parse(diagnosticMessagesJson); + } + catch (e) { + this.log(e.description || "diagnosticMessages.generated.json has invalid JSON format"); + return null; + } + }; + LanguageServiceShimHostAdapter.prototype.getCancellationToken = function () { + var hostCancellationToken = this.shimHost.getCancellationToken(); + return new ts.ThrottledCancellationToken(hostCancellationToken); + }; + LanguageServiceShimHostAdapter.prototype.getCurrentDirectory = function () { + return this.shimHost.getCurrentDirectory(); + }; + LanguageServiceShimHostAdapter.prototype.getDirectories = function (path) { + return JSON.parse(this.shimHost.getDirectories(path)); + }; + LanguageServiceShimHostAdapter.prototype.getDefaultLibFileName = function (options) { + return this.shimHost.getDefaultLibFileName(JSON.stringify(options)); + }; + LanguageServiceShimHostAdapter.prototype.readDirectory = function (path, extensions, exclude, include, depth) { + var pattern = ts.getFileMatcherPatterns(path, exclude, include, this.shimHost.useCaseSensitiveFileNames(), this.shimHost.getCurrentDirectory()); // TODO: GH#18217 + return JSON.parse(this.shimHost.readDirectory(path, JSON.stringify(extensions), JSON.stringify(pattern.basePaths), pattern.excludePattern, pattern.includeFilePattern, pattern.includeDirectoryPattern, depth)); + }; + LanguageServiceShimHostAdapter.prototype.readFile = function (path, encoding) { + return this.shimHost.readFile(path, encoding); + }; + LanguageServiceShimHostAdapter.prototype.fileExists = function (path) { + return this.shimHost.fileExists(path); + }; + return LanguageServiceShimHostAdapter; + }()); + ts.LanguageServiceShimHostAdapter = LanguageServiceShimHostAdapter; + var CoreServicesShimHostAdapter = /** @class */ (function () { + function CoreServicesShimHostAdapter(shimHost) { + var _this = this; + this.shimHost = shimHost; + this.useCaseSensitiveFileNames = this.shimHost.useCaseSensitiveFileNames ? this.shimHost.useCaseSensitiveFileNames() : false; + if ("directoryExists" in this.shimHost) { + this.directoryExists = function (directoryName) { return _this.shimHost.directoryExists(directoryName); }; + } + else { + this.directoryExists = undefined; // TODO: GH#18217 + } + if ("realpath" in this.shimHost) { + this.realpath = function (path) { return _this.shimHost.realpath(path); }; // TODO: GH#18217 + } + else { + this.realpath = undefined; // TODO: GH#18217 + } + } + CoreServicesShimHostAdapter.prototype.readDirectory = function (rootDir, extensions, exclude, include, depth) { + var pattern = ts.getFileMatcherPatterns(rootDir, exclude, include, this.shimHost.useCaseSensitiveFileNames(), this.shimHost.getCurrentDirectory()); // TODO: GH#18217 + return JSON.parse(this.shimHost.readDirectory(rootDir, JSON.stringify(extensions), JSON.stringify(pattern.basePaths), pattern.excludePattern, pattern.includeFilePattern, pattern.includeDirectoryPattern, depth)); + }; + CoreServicesShimHostAdapter.prototype.fileExists = function (fileName) { + return this.shimHost.fileExists(fileName); + }; + CoreServicesShimHostAdapter.prototype.readFile = function (fileName) { + return this.shimHost.readFile(fileName); + }; + CoreServicesShimHostAdapter.prototype.getDirectories = function (path) { + return JSON.parse(this.shimHost.getDirectories(path)); + }; + return CoreServicesShimHostAdapter; + }()); + ts.CoreServicesShimHostAdapter = CoreServicesShimHostAdapter; + function simpleForwardCall(logger, actionDescription, action, logPerformance) { + var start; + if (logPerformance) { + logger.log(actionDescription); + start = ts.timestamp(); + } + var result = action(); + if (logPerformance) { + var end = ts.timestamp(); + logger.log(actionDescription + " completed in " + (end - start) + " msec"); + if (ts.isString(result)) { + var str = result; + if (str.length > 128) { + str = str.substring(0, 128) + "..."; + } + logger.log(" result.length=" + str.length + ", result='" + JSON.stringify(str) + "'"); + } + } + return result; + } + function forwardJSONCall(logger, actionDescription, action, logPerformance) { + return forwardCall(logger, actionDescription, /*returnJson*/ true, action, logPerformance); + } + function forwardCall(logger, actionDescription, returnJson, action, logPerformance) { + try { + var result = simpleForwardCall(logger, actionDescription, action, logPerformance); + return returnJson ? JSON.stringify({ result: result }) : result; + } + catch (err) { + if (err instanceof ts.OperationCanceledException) { + return JSON.stringify({ canceled: true }); + } + logInternalError(logger, err); + err.description = actionDescription; + return JSON.stringify({ error: err }); + } + } + var ShimBase = /** @class */ (function () { + function ShimBase(factory) { + this.factory = factory; + factory.registerShim(this); + } + ShimBase.prototype.dispose = function (_dummy) { + this.factory.unregisterShim(this); + }; + return ShimBase; + }()); + function realizeDiagnostics(diagnostics, newLine) { + return diagnostics.map(function (d) { return realizeDiagnostic(d, newLine); }); + } + ts.realizeDiagnostics = realizeDiagnostics; + function realizeDiagnostic(diagnostic, newLine) { + return { + message: ts.flattenDiagnosticMessageText(diagnostic.messageText, newLine), + start: diagnostic.start, + length: diagnostic.length, + category: ts.diagnosticCategoryName(diagnostic), + code: diagnostic.code, + reportsUnnecessary: diagnostic.reportsUnnecessary, + }; + } + var LanguageServiceShimObject = /** @class */ (function (_super) { + __extends(LanguageServiceShimObject, _super); + function LanguageServiceShimObject(factory, host, languageService) { + var _this = _super.call(this, factory) || this; + _this.host = host; + _this.languageService = languageService; + _this.logPerformance = false; + _this.logger = _this.host; + return _this; + } + LanguageServiceShimObject.prototype.forwardJSONCall = function (actionDescription, action) { + return forwardJSONCall(this.logger, actionDescription, action, this.logPerformance); + }; + /// DISPOSE + /** + * Ensure (almost) deterministic release of internal Javascript resources when + * some external native objects holds onto us (e.g. Com/Interop). + */ + LanguageServiceShimObject.prototype.dispose = function (dummy) { + this.logger.log("dispose()"); + this.languageService.dispose(); + this.languageService = null; + // force a GC + if (debugObjectHost && debugObjectHost.CollectGarbage) { + debugObjectHost.CollectGarbage(); + this.logger.log("CollectGarbage()"); + } + this.logger = null; + _super.prototype.dispose.call(this, dummy); + }; + /// REFRESH + /** + * Update the list of scripts known to the compiler + */ + LanguageServiceShimObject.prototype.refresh = function (throwOnError) { + this.forwardJSONCall("refresh(" + throwOnError + ")", function () { return null; }); + }; + LanguageServiceShimObject.prototype.cleanupSemanticCache = function () { + var _this = this; + this.forwardJSONCall("cleanupSemanticCache()", function () { + _this.languageService.cleanupSemanticCache(); + return null; + }); + }; + LanguageServiceShimObject.prototype.realizeDiagnostics = function (diagnostics) { + var newLine = ts.getNewLineOrDefaultFromHost(this.host); + return realizeDiagnostics(diagnostics, newLine); + }; + LanguageServiceShimObject.prototype.getSyntacticClassifications = function (fileName, start, length) { + var _this = this; + return this.forwardJSONCall("getSyntacticClassifications('" + fileName + "', " + start + ", " + length + ")", function () { return _this.languageService.getSyntacticClassifications(fileName, ts.createTextSpan(start, length)); }); + }; + LanguageServiceShimObject.prototype.getSemanticClassifications = function (fileName, start, length) { + var _this = this; + return this.forwardJSONCall("getSemanticClassifications('" + fileName + "', " + start + ", " + length + ")", function () { return _this.languageService.getSemanticClassifications(fileName, ts.createTextSpan(start, length)); }); + }; + LanguageServiceShimObject.prototype.getEncodedSyntacticClassifications = function (fileName, start, length) { + var _this = this; + return this.forwardJSONCall("getEncodedSyntacticClassifications('" + fileName + "', " + start + ", " + length + ")", + // directly serialize the spans out to a string. This is much faster to decode + // on the managed side versus a full JSON array. + function () { return convertClassifications(_this.languageService.getEncodedSyntacticClassifications(fileName, ts.createTextSpan(start, length))); }); + }; + LanguageServiceShimObject.prototype.getEncodedSemanticClassifications = function (fileName, start, length) { + var _this = this; + return this.forwardJSONCall("getEncodedSemanticClassifications('" + fileName + "', " + start + ", " + length + ")", + // directly serialize the spans out to a string. This is much faster to decode + // on the managed side versus a full JSON array. + function () { return convertClassifications(_this.languageService.getEncodedSemanticClassifications(fileName, ts.createTextSpan(start, length))); }); + }; + LanguageServiceShimObject.prototype.getSyntacticDiagnostics = function (fileName) { + var _this = this; + return this.forwardJSONCall("getSyntacticDiagnostics('" + fileName + "')", function () { + var diagnostics = _this.languageService.getSyntacticDiagnostics(fileName); + return _this.realizeDiagnostics(diagnostics); + }); + }; + LanguageServiceShimObject.prototype.getSemanticDiagnostics = function (fileName) { + var _this = this; + return this.forwardJSONCall("getSemanticDiagnostics('" + fileName + "')", function () { + var diagnostics = _this.languageService.getSemanticDiagnostics(fileName); + return _this.realizeDiagnostics(diagnostics); + }); + }; + LanguageServiceShimObject.prototype.getSuggestionDiagnostics = function (fileName) { + var _this = this; + return this.forwardJSONCall("getSuggestionDiagnostics('" + fileName + "')", function () { return _this.realizeDiagnostics(_this.languageService.getSuggestionDiagnostics(fileName)); }); + }; + LanguageServiceShimObject.prototype.getCompilerOptionsDiagnostics = function () { + var _this = this; + return this.forwardJSONCall("getCompilerOptionsDiagnostics()", function () { + var diagnostics = _this.languageService.getCompilerOptionsDiagnostics(); + return _this.realizeDiagnostics(diagnostics); + }); + }; + /// QUICKINFO + /** + * Computes a string representation of the type at the requested position + * in the active file. + */ + LanguageServiceShimObject.prototype.getQuickInfoAtPosition = function (fileName, position) { + var _this = this; + return this.forwardJSONCall("getQuickInfoAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getQuickInfoAtPosition(fileName, position); }); + }; + /// NAMEORDOTTEDNAMESPAN + /** + * Computes span information of the name or dotted name at the requested position + * in the active file. + */ + LanguageServiceShimObject.prototype.getNameOrDottedNameSpan = function (fileName, startPos, endPos) { + var _this = this; + return this.forwardJSONCall("getNameOrDottedNameSpan('" + fileName + "', " + startPos + ", " + endPos + ")", function () { return _this.languageService.getNameOrDottedNameSpan(fileName, startPos, endPos); }); + }; + /** + * STATEMENTSPAN + * Computes span information of statement at the requested position in the active file. + */ + LanguageServiceShimObject.prototype.getBreakpointStatementAtPosition = function (fileName, position) { + var _this = this; + return this.forwardJSONCall("getBreakpointStatementAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getBreakpointStatementAtPosition(fileName, position); }); + }; + /// SIGNATUREHELP + LanguageServiceShimObject.prototype.getSignatureHelpItems = function (fileName, position, options) { + var _this = this; + return this.forwardJSONCall("getSignatureHelpItems('" + fileName + "', " + position + ")", function () { return _this.languageService.getSignatureHelpItems(fileName, position, options); }); + }; + /// GOTO DEFINITION + /** + * Computes the definition location and file for the symbol + * at the requested position. + */ + LanguageServiceShimObject.prototype.getDefinitionAtPosition = function (fileName, position) { + var _this = this; + return this.forwardJSONCall("getDefinitionAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getDefinitionAtPosition(fileName, position); }); + }; + /** + * Computes the definition location and file for the symbol + * at the requested position. + */ + LanguageServiceShimObject.prototype.getDefinitionAndBoundSpan = function (fileName, position) { + var _this = this; + return this.forwardJSONCall("getDefinitionAndBoundSpan('" + fileName + "', " + position + ")", function () { return _this.languageService.getDefinitionAndBoundSpan(fileName, position); }); + }; + /// GOTO Type + /** + * Computes the definition location of the type of the symbol + * at the requested position. + */ + LanguageServiceShimObject.prototype.getTypeDefinitionAtPosition = function (fileName, position) { + var _this = this; + return this.forwardJSONCall("getTypeDefinitionAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getTypeDefinitionAtPosition(fileName, position); }); + }; + /// GOTO Implementation + /** + * Computes the implementation location of the symbol + * at the requested position. + */ + LanguageServiceShimObject.prototype.getImplementationAtPosition = function (fileName, position) { + var _this = this; + return this.forwardJSONCall("getImplementationAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getImplementationAtPosition(fileName, position); }); + }; + LanguageServiceShimObject.prototype.getRenameInfo = function (fileName, position) { + var _this = this; + return this.forwardJSONCall("getRenameInfo('" + fileName + "', " + position + ")", function () { return _this.languageService.getRenameInfo(fileName, position); }); + }; + LanguageServiceShimObject.prototype.findRenameLocations = function (fileName, position, findInStrings, findInComments) { + var _this = this; + return this.forwardJSONCall("findRenameLocations('" + fileName + "', " + position + ", " + findInStrings + ", " + findInComments + ")", function () { return _this.languageService.findRenameLocations(fileName, position, findInStrings, findInComments); }); + }; + /// GET BRACE MATCHING + LanguageServiceShimObject.prototype.getBraceMatchingAtPosition = function (fileName, position) { + var _this = this; + return this.forwardJSONCall("getBraceMatchingAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getBraceMatchingAtPosition(fileName, position); }); + }; + LanguageServiceShimObject.prototype.isValidBraceCompletionAtPosition = function (fileName, position, openingBrace) { + var _this = this; + return this.forwardJSONCall("isValidBraceCompletionAtPosition('" + fileName + "', " + position + ", " + openingBrace + ")", function () { return _this.languageService.isValidBraceCompletionAtPosition(fileName, position, openingBrace); }); + }; + LanguageServiceShimObject.prototype.getSpanOfEnclosingComment = function (fileName, position, onlyMultiLine) { + var _this = this; + return this.forwardJSONCall("getSpanOfEnclosingComment('" + fileName + "', " + position + ")", function () { return _this.languageService.getSpanOfEnclosingComment(fileName, position, onlyMultiLine); }); + }; + /// GET SMART INDENT + LanguageServiceShimObject.prototype.getIndentationAtPosition = function (fileName, position, options /*Services.EditorOptions*/) { + var _this = this; + return this.forwardJSONCall("getIndentationAtPosition('" + fileName + "', " + position + ")", function () { + var localOptions = JSON.parse(options); + return _this.languageService.getIndentationAtPosition(fileName, position, localOptions); + }); + }; + /// GET REFERENCES + LanguageServiceShimObject.prototype.getReferencesAtPosition = function (fileName, position) { + var _this = this; + return this.forwardJSONCall("getReferencesAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getReferencesAtPosition(fileName, position); }); + }; + LanguageServiceShimObject.prototype.findReferences = function (fileName, position) { + var _this = this; + return this.forwardJSONCall("findReferences('" + fileName + "', " + position + ")", function () { return _this.languageService.findReferences(fileName, position); }); + }; + LanguageServiceShimObject.prototype.getOccurrencesAtPosition = function (fileName, position) { + var _this = this; + return this.forwardJSONCall("getOccurrencesAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getOccurrencesAtPosition(fileName, position); }); + }; + LanguageServiceShimObject.prototype.getDocumentHighlights = function (fileName, position, filesToSearch) { + var _this = this; + return this.forwardJSONCall("getDocumentHighlights('" + fileName + "', " + position + ")", function () { + var results = _this.languageService.getDocumentHighlights(fileName, position, JSON.parse(filesToSearch)); + // workaround for VS document highlighting issue - keep only items from the initial file + var normalizedName = ts.normalizeSlashes(fileName).toLowerCase(); + return ts.filter(results, function (r) { return ts.normalizeSlashes(r.fileName).toLowerCase() === normalizedName; }); + }); + }; + /// COMPLETION LISTS + /** + * Get a string based representation of the completions + * to provide at the given source position and providing a member completion + * list if requested. + */ + LanguageServiceShimObject.prototype.getCompletionsAtPosition = function (fileName, position, preferences) { + var _this = this; + return this.forwardJSONCall("getCompletionsAtPosition('" + fileName + "', " + position + ", " + preferences + ")", function () { return _this.languageService.getCompletionsAtPosition(fileName, position, preferences); }); + }; + /** Get a string based representation of a completion list entry details */ + LanguageServiceShimObject.prototype.getCompletionEntryDetails = function (fileName, position, entryName, formatOptions, source, preferences) { + var _this = this; + return this.forwardJSONCall("getCompletionEntryDetails('" + fileName + "', " + position + ", '" + entryName + "')", function () { + var localOptions = formatOptions === undefined ? undefined : JSON.parse(formatOptions); + return _this.languageService.getCompletionEntryDetails(fileName, position, entryName, localOptions, source, preferences); + }); + }; + LanguageServiceShimObject.prototype.getFormattingEditsForRange = function (fileName, start, end, options /*Services.FormatCodeOptions*/) { + var _this = this; + return this.forwardJSONCall("getFormattingEditsForRange('" + fileName + "', " + start + ", " + end + ")", function () { + var localOptions = JSON.parse(options); + return _this.languageService.getFormattingEditsForRange(fileName, start, end, localOptions); + }); + }; + LanguageServiceShimObject.prototype.getFormattingEditsForDocument = function (fileName, options /*Services.FormatCodeOptions*/) { + var _this = this; + return this.forwardJSONCall("getFormattingEditsForDocument('" + fileName + "')", function () { + var localOptions = JSON.parse(options); + return _this.languageService.getFormattingEditsForDocument(fileName, localOptions); + }); + }; + LanguageServiceShimObject.prototype.getFormattingEditsAfterKeystroke = function (fileName, position, key, options /*Services.FormatCodeOptions*/) { + var _this = this; + return this.forwardJSONCall("getFormattingEditsAfterKeystroke('" + fileName + "', " + position + ", '" + key + "')", function () { + var localOptions = JSON.parse(options); + return _this.languageService.getFormattingEditsAfterKeystroke(fileName, position, key, localOptions); + }); + }; + LanguageServiceShimObject.prototype.getDocCommentTemplateAtPosition = function (fileName, position) { + var _this = this; + return this.forwardJSONCall("getDocCommentTemplateAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getDocCommentTemplateAtPosition(fileName, position); }); + }; + /// NAVIGATE TO + /** Return a list of symbols that are interesting to navigate to */ + LanguageServiceShimObject.prototype.getNavigateToItems = function (searchValue, maxResultCount, fileName) { + var _this = this; + return this.forwardJSONCall("getNavigateToItems('" + searchValue + "', " + maxResultCount + ", " + fileName + ")", function () { return _this.languageService.getNavigateToItems(searchValue, maxResultCount, fileName); }); + }; + LanguageServiceShimObject.prototype.getNavigationBarItems = function (fileName) { + var _this = this; + return this.forwardJSONCall("getNavigationBarItems('" + fileName + "')", function () { return _this.languageService.getNavigationBarItems(fileName); }); + }; + LanguageServiceShimObject.prototype.getNavigationTree = function (fileName) { + var _this = this; + return this.forwardJSONCall("getNavigationTree('" + fileName + "')", function () { return _this.languageService.getNavigationTree(fileName); }); + }; + LanguageServiceShimObject.prototype.getOutliningSpans = function (fileName) { + var _this = this; + return this.forwardJSONCall("getOutliningSpans('" + fileName + "')", function () { return _this.languageService.getOutliningSpans(fileName); }); + }; + LanguageServiceShimObject.prototype.getTodoComments = function (fileName, descriptors) { + var _this = this; + return this.forwardJSONCall("getTodoComments('" + fileName + "')", function () { return _this.languageService.getTodoComments(fileName, JSON.parse(descriptors)); }); + }; + /// Emit + LanguageServiceShimObject.prototype.getEmitOutput = function (fileName) { + var _this = this; + return this.forwardJSONCall("getEmitOutput('" + fileName + "')", function () { return _this.languageService.getEmitOutput(fileName); }); + }; + LanguageServiceShimObject.prototype.getEmitOutputObject = function (fileName) { + var _this = this; + return forwardCall(this.logger, "getEmitOutput('" + fileName + "')", + /*returnJson*/ false, function () { return _this.languageService.getEmitOutput(fileName); }, this.logPerformance); + }; + return LanguageServiceShimObject; + }(ShimBase)); + function convertClassifications(classifications) { + return { spans: classifications.spans.join(","), endOfLineState: classifications.endOfLineState }; + } + var ClassifierShimObject = /** @class */ (function (_super) { + __extends(ClassifierShimObject, _super); + function ClassifierShimObject(factory, logger) { + var _this = _super.call(this, factory) || this; + _this.logger = logger; + _this.logPerformance = false; + _this.classifier = ts.createClassifier(); + return _this; + } + ClassifierShimObject.prototype.getEncodedLexicalClassifications = function (text, lexState, syntacticClassifierAbsent) { + var _this = this; + if (syntacticClassifierAbsent === void 0) { syntacticClassifierAbsent = false; } + return forwardJSONCall(this.logger, "getEncodedLexicalClassifications", function () { return convertClassifications(_this.classifier.getEncodedLexicalClassifications(text, lexState, syntacticClassifierAbsent)); }, this.logPerformance); + }; + /// COLORIZATION + ClassifierShimObject.prototype.getClassificationsForLine = function (text, lexState, classifyKeywordsInGenerics) { + if (classifyKeywordsInGenerics === void 0) { classifyKeywordsInGenerics = false; } + var classification = this.classifier.getClassificationsForLine(text, lexState, classifyKeywordsInGenerics); + var result = ""; + for (var _i = 0, _a = classification.entries; _i < _a.length; _i++) { + var item = _a[_i]; + result += item.length + "\n"; + result += item.classification + "\n"; + } + result += classification.finalLexState; + return result; + }; + return ClassifierShimObject; + }(ShimBase)); + var CoreServicesShimObject = /** @class */ (function (_super) { + __extends(CoreServicesShimObject, _super); + function CoreServicesShimObject(factory, logger, host) { + var _this = _super.call(this, factory) || this; + _this.logger = logger; + _this.host = host; + _this.logPerformance = false; + return _this; + } + CoreServicesShimObject.prototype.forwardJSONCall = function (actionDescription, action) { + return forwardJSONCall(this.logger, actionDescription, action, this.logPerformance); + }; + CoreServicesShimObject.prototype.resolveModuleName = function (fileName, moduleName, compilerOptionsJson) { + var _this = this; + return this.forwardJSONCall("resolveModuleName('" + fileName + "')", function () { + var compilerOptions = JSON.parse(compilerOptionsJson); + var result = ts.resolveModuleName(moduleName, ts.normalizeSlashes(fileName), compilerOptions, _this.host); + var resolvedFileName = result.resolvedModule ? result.resolvedModule.resolvedFileName : undefined; + if (result.resolvedModule && result.resolvedModule.extension !== ".ts" /* Ts */ && result.resolvedModule.extension !== ".tsx" /* Tsx */ && result.resolvedModule.extension !== ".d.ts" /* Dts */) { + resolvedFileName = undefined; + } + return { + resolvedFileName: resolvedFileName, + failedLookupLocations: result.failedLookupLocations + }; + }); + }; + CoreServicesShimObject.prototype.resolveTypeReferenceDirective = function (fileName, typeReferenceDirective, compilerOptionsJson) { + var _this = this; + return this.forwardJSONCall("resolveTypeReferenceDirective(" + fileName + ")", function () { + var compilerOptions = JSON.parse(compilerOptionsJson); + var result = ts.resolveTypeReferenceDirective(typeReferenceDirective, ts.normalizeSlashes(fileName), compilerOptions, _this.host); + return { + resolvedFileName: result.resolvedTypeReferenceDirective ? result.resolvedTypeReferenceDirective.resolvedFileName : undefined, + primary: result.resolvedTypeReferenceDirective ? result.resolvedTypeReferenceDirective.primary : true, + failedLookupLocations: result.failedLookupLocations + }; + }); + }; + CoreServicesShimObject.prototype.getPreProcessedFileInfo = function (fileName, sourceTextSnapshot) { + var _this = this; + return this.forwardJSONCall("getPreProcessedFileInfo('" + fileName + "')", function () { + // for now treat files as JavaScript + var result = ts.preProcessFile(ts.getSnapshotText(sourceTextSnapshot), /* readImportFiles */ true, /* detectJavaScriptImports */ true); + return { + referencedFiles: _this.convertFileReferences(result.referencedFiles), + importedFiles: _this.convertFileReferences(result.importedFiles), + ambientExternalModules: result.ambientExternalModules, + isLibFile: result.isLibFile, + typeReferenceDirectives: _this.convertFileReferences(result.typeReferenceDirectives), + libReferenceDirectives: _this.convertFileReferences(result.libReferenceDirectives) + }; + }); + }; + CoreServicesShimObject.prototype.getAutomaticTypeDirectiveNames = function (compilerOptionsJson) { + var _this = this; + return this.forwardJSONCall("getAutomaticTypeDirectiveNames('" + compilerOptionsJson + "')", function () { + var compilerOptions = JSON.parse(compilerOptionsJson); + return ts.getAutomaticTypeDirectiveNames(compilerOptions, _this.host); + }); + }; + CoreServicesShimObject.prototype.convertFileReferences = function (refs) { + if (!refs) { + return undefined; + } + var result = []; + for (var _i = 0, refs_1 = refs; _i < refs_1.length; _i++) { + var ref = refs_1[_i]; + result.push({ + path: ts.normalizeSlashes(ref.fileName), + position: ref.pos, + length: ref.end - ref.pos + }); + } + return result; + }; + CoreServicesShimObject.prototype.getTSConfigFileInfo = function (fileName, sourceTextSnapshot) { + var _this = this; + return this.forwardJSONCall("getTSConfigFileInfo('" + fileName + "')", function () { + var result = ts.parseJsonText(fileName, ts.getSnapshotText(sourceTextSnapshot)); + var normalizedFileName = ts.normalizeSlashes(fileName); + var configFile = ts.parseJsonSourceFileConfigFileContent(result, _this.host, ts.getDirectoryPath(normalizedFileName), /*existingOptions*/ {}, normalizedFileName); + return { + options: configFile.options, + typeAcquisition: configFile.typeAcquisition, + files: configFile.fileNames, + raw: configFile.raw, + errors: realizeDiagnostics(result.parseDiagnostics.concat(configFile.errors), "\r\n") + }; + }); + }; + CoreServicesShimObject.prototype.getDefaultCompilationSettings = function () { + return this.forwardJSONCall("getDefaultCompilationSettings()", function () { return ts.getDefaultCompilerOptions(); }); + }; + CoreServicesShimObject.prototype.discoverTypings = function (discoverTypingsJson) { + var _this = this; + var getCanonicalFileName = ts.createGetCanonicalFileName(/*useCaseSensitivefileNames:*/ false); + return this.forwardJSONCall("discoverTypings()", function () { + var info = JSON.parse(discoverTypingsJson); + if (_this.safeList === undefined) { + _this.safeList = ts.JsTyping.loadSafeList(_this.host, ts.toPath(info.safeListPath, info.safeListPath, getCanonicalFileName)); + } + return ts.JsTyping.discoverTypings(_this.host, function (msg) { return _this.logger.log(msg); }, info.fileNames, ts.toPath(info.projectRootPath, info.projectRootPath, getCanonicalFileName), _this.safeList, info.packageNameToTypingLocation, info.typeAcquisition, info.unresolvedImports, info.typesRegistry); + }); + }; + return CoreServicesShimObject; + }(ShimBase)); + var TypeScriptServicesFactory = /** @class */ (function () { + function TypeScriptServicesFactory() { + this._shims = []; + } + /* + * Returns script API version. + */ + TypeScriptServicesFactory.prototype.getServicesVersion = function () { + return ts.servicesVersion; + }; + TypeScriptServicesFactory.prototype.createLanguageServiceShim = function (host) { + try { + if (this.documentRegistry === undefined) { + this.documentRegistry = ts.createDocumentRegistry(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames(), host.getCurrentDirectory()); + } + var hostAdapter = new LanguageServiceShimHostAdapter(host); + var languageService = ts.createLanguageService(hostAdapter, this.documentRegistry, /*syntaxOnly*/ false); + return new LanguageServiceShimObject(this, host, languageService); + } + catch (err) { + logInternalError(host, err); + throw err; + } + }; + TypeScriptServicesFactory.prototype.createClassifierShim = function (logger) { + try { + return new ClassifierShimObject(this, logger); + } + catch (err) { + logInternalError(logger, err); + throw err; + } + }; + TypeScriptServicesFactory.prototype.createCoreServicesShim = function (host) { + try { + var adapter = new CoreServicesShimHostAdapter(host); + return new CoreServicesShimObject(this, host, adapter); + } + catch (err) { + logInternalError(host, err); + throw err; + } + }; + TypeScriptServicesFactory.prototype.close = function () { + // Forget all the registered shims + ts.clear(this._shims); + this.documentRegistry = undefined; + }; + TypeScriptServicesFactory.prototype.registerShim = function (shim) { + this._shims.push(shim); + }; + TypeScriptServicesFactory.prototype.unregisterShim = function (shim) { + for (var i = 0; i < this._shims.length; i++) { + if (this._shims[i] === shim) { + delete this._shims[i]; + return; + } + } + throw new Error("Invalid operation"); + }; + return TypeScriptServicesFactory; + }()); + ts.TypeScriptServicesFactory = TypeScriptServicesFactory; + if (typeof module !== "undefined" && module.exports) { + module.exports = ts; + } +})(ts || (ts = {})); +/* tslint:enable:no-in-operator */ +/* tslint:enable:no-null */ +/// TODO: this is used by VS, clean this up on both sides of the interface +/* @internal */ +var TypeScript; +(function (TypeScript) { + var Services; + (function (Services) { + Services.TypeScriptServicesFactory = ts.TypeScriptServicesFactory; + })(Services = TypeScript.Services || (TypeScript.Services = {})); +})(TypeScript || (TypeScript = {})); +// 'toolsVersion' gets consumed by the managed side, so it's not unused. +// TODO: it should be moved into a namespace though. +/* @internal */ +var toolsVersion = ts.versionMajorMinor; +var ts; +(function (ts) { + var server; + (function (server) { + var LogLevel; + (function (LogLevel) { + LogLevel[LogLevel["terse"] = 0] = "terse"; + LogLevel[LogLevel["normal"] = 1] = "normal"; + LogLevel[LogLevel["requestTime"] = 2] = "requestTime"; + LogLevel[LogLevel["verbose"] = 3] = "verbose"; + })(LogLevel = server.LogLevel || (server.LogLevel = {})); + server.emptyArray = createSortedArray(); + // TODO: Use a const enum (https://github.com/Microsoft/TypeScript/issues/16804) + var Msg; + (function (Msg) { + Msg["Err"] = "Err"; + Msg["Info"] = "Info"; + Msg["Perf"] = "Perf"; + })(Msg = server.Msg || (server.Msg = {})); + function createInstallTypingsRequest(project, typeAcquisition, unresolvedImports, cachePath) { + return { + projectName: project.getProjectName(), + fileNames: project.getFileNames(/*excludeFilesFromExternalLibraries*/ true, /*excludeConfigFiles*/ true).concat(project.getExcludedFiles()), + compilerOptions: project.getCompilationSettings(), + typeAcquisition: typeAcquisition, + unresolvedImports: unresolvedImports, + projectRootPath: project.getCurrentDirectory(), + cachePath: cachePath, + kind: "discover" + }; + } + server.createInstallTypingsRequest = createInstallTypingsRequest; + var Errors; + (function (Errors) { + function ThrowNoProject() { + throw new Error("No Project."); + } + Errors.ThrowNoProject = ThrowNoProject; + function ThrowProjectLanguageServiceDisabled() { + throw new Error("The project's language service is disabled."); + } + Errors.ThrowProjectLanguageServiceDisabled = ThrowProjectLanguageServiceDisabled; + function ThrowProjectDoesNotContainDocument(fileName, project) { + throw new Error("Project '" + project.getProjectName() + "' does not contain document '" + fileName + "'"); + } + Errors.ThrowProjectDoesNotContainDocument = ThrowProjectDoesNotContainDocument; + })(Errors = server.Errors || (server.Errors = {})); + function toNormalizedPath(fileName) { + return ts.normalizePath(fileName); + } + server.toNormalizedPath = toNormalizedPath; + function normalizedPathToPath(normalizedPath, currentDirectory, getCanonicalFileName) { + var f = ts.isRootedDiskPath(normalizedPath) ? normalizedPath : ts.getNormalizedAbsolutePath(normalizedPath, currentDirectory); + return getCanonicalFileName(f); + } + server.normalizedPathToPath = normalizedPathToPath; + function asNormalizedPath(fileName) { + return fileName; + } + server.asNormalizedPath = asNormalizedPath; + function createNormalizedPathMap() { + var map = ts.createMap(); + return { + get: function (path) { + return map.get(path); + }, + set: function (path, value) { + map.set(path, value); + }, + contains: function (path) { + return map.has(path); + }, + remove: function (path) { + map.delete(path); + } + }; + } + server.createNormalizedPathMap = createNormalizedPathMap; + function isInferredProjectName(name) { + // POSIX defines /dev/null as a device - there should be no file with this prefix + return /dev\/null\/inferredProject\d+\*/.test(name); + } + server.isInferredProjectName = isInferredProjectName; + function makeInferredProjectName(counter) { + return "/dev/null/inferredProject" + counter + "*"; + } + server.makeInferredProjectName = makeInferredProjectName; + function createSortedArray() { + return []; // TODO: GH#19873 + } + server.createSortedArray = createSortedArray; + })(server = ts.server || (ts.server = {})); +})(ts || (ts = {})); +/* @internal */ +(function (ts) { + var server; + (function (server) { + var ThrottledOperations = /** @class */ (function () { + function ThrottledOperations(host, logger) { + this.host = host; + this.pendingTimeouts = ts.createMap(); + this.logger = logger.hasLevel(server.LogLevel.verbose) ? logger : undefined; + } + /** + * Wait `number` milliseconds and then invoke `cb`. If, while waiting, schedule + * is called again with the same `operationId`, cancel this operation in favor + * of the new one. (Note that the amount of time the canceled operation had been + * waiting does not affect the amount of time that the new operation waits.) + */ + ThrottledOperations.prototype.schedule = function (operationId, delay, cb) { + var pendingTimeout = this.pendingTimeouts.get(operationId); + if (pendingTimeout) { + // another operation was already scheduled for this id - cancel it + this.host.clearTimeout(pendingTimeout); + } + // schedule new operation, pass arguments + this.pendingTimeouts.set(operationId, this.host.setTimeout(ThrottledOperations.run, delay, this, operationId, cb)); + if (this.logger) { + this.logger.info("Scheduled: " + operationId + (pendingTimeout ? ", Cancelled earlier one" : "")); + } + }; + ThrottledOperations.run = function (self, operationId, cb) { + self.pendingTimeouts.delete(operationId); + if (self.logger) { + self.logger.info("Running: " + operationId); + } + cb(); + }; + return ThrottledOperations; + }()); + server.ThrottledOperations = ThrottledOperations; + var GcTimer = /** @class */ (function () { + function GcTimer(host, delay, logger) { + this.host = host; + this.delay = delay; + this.logger = logger; + } + GcTimer.prototype.scheduleCollect = function () { + if (!this.host.gc || this.timerId !== undefined) { + // no global.gc or collection was already scheduled - skip this request + return; + } + this.timerId = this.host.setTimeout(GcTimer.run, this.delay, this); + }; + GcTimer.run = function (self) { + self.timerId = undefined; + var log = self.logger.hasLevel(server.LogLevel.requestTime); + var before = log && self.host.getMemoryUsage(); // TODO: GH#18217 + self.host.gc(); // TODO: GH#18217 + if (log) { + var after = self.host.getMemoryUsage(); // TODO: GH#18217 + self.logger.perftrc("GC::before " + before + ", after " + after); + } + }; + return GcTimer; + }()); + server.GcTimer = GcTimer; + function getBaseConfigFileName(configFilePath) { + var base = ts.getBaseFileName(configFilePath); + return base === "tsconfig.json" || base === "jsconfig.json" ? base : undefined; + } + server.getBaseConfigFileName = getBaseConfigFileName; + function removeSorted(array, remove, compare) { + if (!array || array.length === 0) { + return; + } + if (array[0] === remove) { + array.splice(0, 1); + return; + } + var removeIndex = ts.binarySearch(array, remove, ts.identity, compare); + if (removeIndex >= 0) { + array.splice(removeIndex, 1); + } + } + server.removeSorted = removeSorted; + var indentStr = "\n "; + function indent(str) { + return indentStr + str.replace(/\n/g, indentStr); + } + server.indent = indent; + /** Put stringified JSON on the next line, indented. */ + function stringifyIndented(json) { + return indentStr + JSON.stringify(json); + } + server.stringifyIndented = stringifyIndented; + })(server = ts.server || (ts.server = {})); +})(ts || (ts = {})); +// tslint:disable no-unnecessary-qualifier +/** + * Declaration module describing the TypeScript Server protocol + */ +var ts; +(function (ts) { + var server; + (function (server) { + var protocol; + (function (protocol) { + // NOTE: If updating this, be sure to also update `allCommandNames` in `harness/unittests/session.ts`. + var CommandTypes; + (function (CommandTypes) { + CommandTypes["JsxClosingTag"] = "jsxClosingTag"; + CommandTypes["Brace"] = "brace"; + /* @internal */ + CommandTypes["BraceFull"] = "brace-full"; + CommandTypes["BraceCompletion"] = "braceCompletion"; + CommandTypes["GetSpanOfEnclosingComment"] = "getSpanOfEnclosingComment"; + CommandTypes["Change"] = "change"; + CommandTypes["Close"] = "close"; + /** @deprecated Prefer CompletionInfo -- see comment on CompletionsResponse */ + CommandTypes["Completions"] = "completions"; + CommandTypes["CompletionInfo"] = "completionInfo"; + /* @internal */ + CommandTypes["CompletionsFull"] = "completions-full"; + CommandTypes["CompletionDetails"] = "completionEntryDetails"; + /* @internal */ + CommandTypes["CompletionDetailsFull"] = "completionEntryDetails-full"; + CommandTypes["CompileOnSaveAffectedFileList"] = "compileOnSaveAffectedFileList"; + CommandTypes["CompileOnSaveEmitFile"] = "compileOnSaveEmitFile"; + CommandTypes["Configure"] = "configure"; + CommandTypes["Definition"] = "definition"; + /* @internal */ + CommandTypes["DefinitionFull"] = "definition-full"; + CommandTypes["DefinitionAndBoundSpan"] = "definitionAndBoundSpan"; + /* @internal */ + CommandTypes["DefinitionAndBoundSpanFull"] = "definitionAndBoundSpan-full"; + CommandTypes["Implementation"] = "implementation"; + /* @internal */ + CommandTypes["ImplementationFull"] = "implementation-full"; + /* @internal */ + CommandTypes["EmitOutput"] = "emit-output"; + CommandTypes["Exit"] = "exit"; + CommandTypes["Format"] = "format"; + CommandTypes["Formatonkey"] = "formatonkey"; + /* @internal */ + CommandTypes["FormatFull"] = "format-full"; + /* @internal */ + CommandTypes["FormatonkeyFull"] = "formatonkey-full"; + /* @internal */ + CommandTypes["FormatRangeFull"] = "formatRange-full"; + CommandTypes["Geterr"] = "geterr"; + CommandTypes["GeterrForProject"] = "geterrForProject"; + CommandTypes["SemanticDiagnosticsSync"] = "semanticDiagnosticsSync"; + CommandTypes["SyntacticDiagnosticsSync"] = "syntacticDiagnosticsSync"; + CommandTypes["SuggestionDiagnosticsSync"] = "suggestionDiagnosticsSync"; + CommandTypes["NavBar"] = "navbar"; + /* @internal */ + CommandTypes["NavBarFull"] = "navbar-full"; + CommandTypes["Navto"] = "navto"; + /* @internal */ + CommandTypes["NavtoFull"] = "navto-full"; + CommandTypes["NavTree"] = "navtree"; + CommandTypes["NavTreeFull"] = "navtree-full"; + /** @deprecated */ + CommandTypes["Occurrences"] = "occurrences"; + CommandTypes["DocumentHighlights"] = "documentHighlights"; + /* @internal */ + CommandTypes["DocumentHighlightsFull"] = "documentHighlights-full"; + CommandTypes["Open"] = "open"; + CommandTypes["Quickinfo"] = "quickinfo"; + /* @internal */ + CommandTypes["QuickinfoFull"] = "quickinfo-full"; + CommandTypes["References"] = "references"; + /* @internal */ + CommandTypes["ReferencesFull"] = "references-full"; + CommandTypes["Reload"] = "reload"; + CommandTypes["Rename"] = "rename"; + /* @internal */ + CommandTypes["RenameInfoFull"] = "rename-full"; + /* @internal */ + CommandTypes["RenameLocationsFull"] = "renameLocations-full"; + CommandTypes["Saveto"] = "saveto"; + CommandTypes["SignatureHelp"] = "signatureHelp"; + /* @internal */ + CommandTypes["SignatureHelpFull"] = "signatureHelp-full"; + CommandTypes["Status"] = "status"; + CommandTypes["TypeDefinition"] = "typeDefinition"; + CommandTypes["ProjectInfo"] = "projectInfo"; + CommandTypes["ReloadProjects"] = "reloadProjects"; + CommandTypes["Unknown"] = "unknown"; + CommandTypes["OpenExternalProject"] = "openExternalProject"; + CommandTypes["OpenExternalProjects"] = "openExternalProjects"; + CommandTypes["CloseExternalProject"] = "closeExternalProject"; + /* @internal */ + CommandTypes["SynchronizeProjectList"] = "synchronizeProjectList"; + /* @internal */ + CommandTypes["ApplyChangedToOpenFiles"] = "applyChangedToOpenFiles"; + /* @internal */ + CommandTypes["EncodedSemanticClassificationsFull"] = "encodedSemanticClassifications-full"; + /* @internal */ + CommandTypes["Cleanup"] = "cleanup"; + CommandTypes["GetOutliningSpans"] = "getOutliningSpans"; + /* @internal */ + CommandTypes["GetOutliningSpansFull"] = "outliningSpans"; + CommandTypes["TodoComments"] = "todoComments"; + CommandTypes["Indentation"] = "indentation"; + CommandTypes["DocCommentTemplate"] = "docCommentTemplate"; + /* @internal */ + CommandTypes["CompilerOptionsDiagnosticsFull"] = "compilerOptionsDiagnostics-full"; + /* @internal */ + CommandTypes["NameOrDottedNameSpan"] = "nameOrDottedNameSpan"; + /* @internal */ + CommandTypes["BreakpointStatement"] = "breakpointStatement"; + CommandTypes["CompilerOptionsForInferredProjects"] = "compilerOptionsForInferredProjects"; + CommandTypes["GetCodeFixes"] = "getCodeFixes"; + /* @internal */ + CommandTypes["GetCodeFixesFull"] = "getCodeFixes-full"; + CommandTypes["GetCombinedCodeFix"] = "getCombinedCodeFix"; + /* @internal */ + CommandTypes["GetCombinedCodeFixFull"] = "getCombinedCodeFix-full"; + CommandTypes["ApplyCodeActionCommand"] = "applyCodeActionCommand"; + CommandTypes["GetSupportedCodeFixes"] = "getSupportedCodeFixes"; + CommandTypes["GetApplicableRefactors"] = "getApplicableRefactors"; + CommandTypes["GetEditsForRefactor"] = "getEditsForRefactor"; + /* @internal */ + CommandTypes["GetEditsForRefactorFull"] = "getEditsForRefactor-full"; + CommandTypes["OrganizeImports"] = "organizeImports"; + /* @internal */ + CommandTypes["OrganizeImportsFull"] = "organizeImports-full"; + CommandTypes["GetEditsForFileRename"] = "getEditsForFileRename"; + /* @internal */ + CommandTypes["GetEditsForFileRenameFull"] = "getEditsForFileRename-full"; + CommandTypes["ConfigurePlugin"] = "configurePlugin"; + // NOTE: If updating this, be sure to also update `allCommandNames` in `harness/unittests/session.ts`. + })(CommandTypes = protocol.CommandTypes || (protocol.CommandTypes = {})); + var IndentStyle; + (function (IndentStyle) { + IndentStyle["None"] = "None"; + IndentStyle["Block"] = "Block"; + IndentStyle["Smart"] = "Smart"; + })(IndentStyle = protocol.IndentStyle || (protocol.IndentStyle = {})); + var JsxEmit; + (function (JsxEmit) { + JsxEmit["None"] = "None"; + JsxEmit["Preserve"] = "Preserve"; + JsxEmit["ReactNative"] = "ReactNative"; + JsxEmit["React"] = "React"; + })(JsxEmit = protocol.JsxEmit || (protocol.JsxEmit = {})); + var ModuleKind; + (function (ModuleKind) { + ModuleKind["None"] = "None"; + ModuleKind["CommonJS"] = "CommonJS"; + ModuleKind["AMD"] = "AMD"; + ModuleKind["UMD"] = "UMD"; + ModuleKind["System"] = "System"; + ModuleKind["ES6"] = "ES6"; + ModuleKind["ES2015"] = "ES2015"; + ModuleKind["ESNext"] = "ESNext"; + })(ModuleKind = protocol.ModuleKind || (protocol.ModuleKind = {})); + var ModuleResolutionKind; + (function (ModuleResolutionKind) { + ModuleResolutionKind["Classic"] = "Classic"; + ModuleResolutionKind["Node"] = "Node"; + })(ModuleResolutionKind = protocol.ModuleResolutionKind || (protocol.ModuleResolutionKind = {})); + var NewLineKind; + (function (NewLineKind) { + NewLineKind["Crlf"] = "Crlf"; + NewLineKind["Lf"] = "Lf"; + })(NewLineKind = protocol.NewLineKind || (protocol.NewLineKind = {})); + var ScriptTarget; + (function (ScriptTarget) { + ScriptTarget["ES3"] = "ES3"; + ScriptTarget["ES5"] = "ES5"; + ScriptTarget["ES6"] = "ES6"; + ScriptTarget["ES2015"] = "ES2015"; + ScriptTarget["ES2016"] = "ES2016"; + ScriptTarget["ES2017"] = "ES2017"; + ScriptTarget["ESNext"] = "ESNext"; + })(ScriptTarget = protocol.ScriptTarget || (protocol.ScriptTarget = {})); + })(protocol = server.protocol || (server.protocol = {})); + })(server = ts.server || (ts.server = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + var server; + (function (server) { + /* @internal */ + var TextStorage = /** @class */ (function () { + function TextStorage(host, fileName, initialVersion, info) { + this.host = host; + this.fileName = fileName; + this.info = info; + /** + * True if the text is for the file thats open in the editor + */ + this.isOpen = false; + /** + * True if the text present is the text from the file on the disk + */ + this.ownFileText = false; + /** + * True when reloading contents of file from the disk is pending + */ + this.pendingReloadFromDisk = false; + this.version = initialVersion || { svc: 0, text: 0 }; + } + TextStorage.prototype.getVersion = function () { + return this.svc + ? "SVC-" + this.version.svc + "-" + this.svc.getSnapshotVersion() + : "Text-" + this.version.text; + }; + TextStorage.prototype.hasScriptVersionCache_TestOnly = function () { + return this.svc !== undefined; + }; + TextStorage.prototype.useScriptVersionCache_TestOnly = function () { + this.switchToScriptVersionCache(); + }; + /** Public for testing */ + TextStorage.prototype.useText = function (newText) { + this.svc = undefined; + this.text = newText; + this.lineMap = undefined; + this.fileSize = undefined; + this.version.text++; + }; + TextStorage.prototype.edit = function (start, end, newText) { + this.switchToScriptVersionCache().edit(start, end - start, newText); + this.ownFileText = false; + this.text = undefined; + this.lineMap = undefined; + this.fileSize = undefined; + }; + /** + * Set the contents as newText + * returns true if text changed + */ + TextStorage.prototype.reload = function (newText) { + ts.Debug.assert(newText !== undefined); + // Reload always has fresh content + this.pendingReloadFromDisk = false; + // If text changed set the text + // This also ensures that if we had switched to version cache, + // we are switching back to text. + // The change to version cache will happen when needed + // Thus avoiding the computation if there are no changes + if (this.text !== newText) { + this.useText(newText); + // We cant guarantee new text is own file text + this.ownFileText = false; + return true; + } + return false; + }; + /** + * Reads the contents from tempFile(if supplied) or own file and sets it as contents + * returns true if text changed + */ + TextStorage.prototype.reloadWithFileText = function (tempFileName) { + var _a = this.getFileTextAndSize(tempFileName), newText = _a.text, fileSize = _a.fileSize; + var reloaded = this.reload(newText); + this.fileSize = fileSize; // NB: after reload since reload clears it + this.ownFileText = !tempFileName || tempFileName === this.fileName; + return reloaded; + }; + /** + * Reloads the contents from the file if there is no pending reload from disk or the contents of file are same as file text + * returns true if text changed + */ + TextStorage.prototype.reloadFromDisk = function () { + if (!this.pendingReloadFromDisk && !this.ownFileText) { + return this.reloadWithFileText(); + } + return false; + }; + TextStorage.prototype.delayReloadFromFileIntoText = function () { + this.pendingReloadFromDisk = true; + }; + /** + * For telemetry purposes, we would like to be able to report the size of the file. + * However, we do not want telemetry to require extra file I/O so we report a size + * that may be stale (e.g. may not reflect change made on disk since the last reload). + * NB: Will read from disk if the file contents have never been loaded because + * telemetry falsely indicating size 0 would be counter-productive. + */ + TextStorage.prototype.getTelemetryFileSize = function () { + return !!this.fileSize + ? this.fileSize + : !!this.text // Check text before svc because its length is cheaper + ? this.text.length // Could be wrong if this.pendingReloadFromDisk + : !!this.svc + ? this.svc.getSnapshot().getLength() // Could be wrong if this.pendingReloadFromDisk + : this.getSnapshot().getLength(); // Should be strictly correct + }; + TextStorage.prototype.getSnapshot = function () { + return this.useScriptVersionCacheIfValidOrOpen() + ? this.svc.getSnapshot() + : ts.ScriptSnapshot.fromString(this.getOrLoadText()); + }; + TextStorage.prototype.getLineInfo = function (line) { + return this.switchToScriptVersionCache().getLineInfo(line); + }; + /** + * @param line 0 based index + */ + TextStorage.prototype.lineToTextSpan = function (line) { + if (!this.useScriptVersionCacheIfValidOrOpen()) { + var lineMap = this.getLineMap(); + var start = lineMap[line]; // -1 since line is 1-based + var end = line + 1 < lineMap.length ? lineMap[line + 1] : this.text.length; + return ts.createTextSpanFromBounds(start, end); + } + return this.svc.lineToTextSpan(line); + }; + /** + * @param line 1 based index + * @param offset 1 based index + */ + TextStorage.prototype.lineOffsetToPosition = function (line, offset) { + if (!this.useScriptVersionCacheIfValidOrOpen()) { + return ts.computePositionOfLineAndCharacter(this.getLineMap(), line - 1, offset - 1, this.text); + } + // TODO: assert this offset is actually on the line + return this.svc.lineOffsetToPosition(line, offset); + }; + TextStorage.prototype.positionToLineOffset = function (position) { + if (!this.useScriptVersionCacheIfValidOrOpen()) { + var _a = ts.computeLineAndCharacterOfPosition(this.getLineMap(), position), line = _a.line, character = _a.character; + return { line: line + 1, offset: character + 1 }; + } + return this.svc.positionToLineOffset(position); + }; + TextStorage.prototype.getFileTextAndSize = function (tempFileName) { + var _this = this; + var text; + var fileName = tempFileName || this.fileName; + var getText = function () { return text === undefined ? (text = _this.host.readFile(fileName) || "") : text; }; + // Only non typescript files have size limitation + if (!ts.hasTSFileExtension(this.fileName)) { + var fileSize = this.host.getFileSize ? this.host.getFileSize(fileName) : getText().length; + if (fileSize > server.maxFileSize) { + ts.Debug.assert(!!this.info.containingProjects.length); + var service = this.info.containingProjects[0].projectService; + service.logger.info("Skipped loading contents of large file " + fileName + " for info " + this.info.fileName + ": fileSize: " + fileSize); + this.info.containingProjects[0].projectService.sendLargeFileReferencedEvent(fileName, fileSize); + return { text: "", fileSize: fileSize }; + } + } + return { text: getText() }; + }; + TextStorage.prototype.switchToScriptVersionCache = function () { + if (!this.svc || this.pendingReloadFromDisk) { + this.svc = server.ScriptVersionCache.fromString(this.getOrLoadText()); + this.version.svc++; + } + return this.svc; + }; + TextStorage.prototype.useScriptVersionCacheIfValidOrOpen = function () { + // If this is open script, use the cache + if (this.isOpen) { + return this.switchToScriptVersionCache(); + } + // If there is pending reload from the disk then, reload the text + if (this.pendingReloadFromDisk) { + this.reloadWithFileText(); + } + // At this point if svc is present its valid + return this.svc; + }; + TextStorage.prototype.getOrLoadText = function () { + if (this.text === undefined || this.pendingReloadFromDisk) { + ts.Debug.assert(!this.svc || this.pendingReloadFromDisk, "ScriptVersionCache should not be set when reloading from disk"); + this.reloadWithFileText(); + } + return this.text; + }; + TextStorage.prototype.getLineMap = function () { + ts.Debug.assert(!this.svc, "ScriptVersionCache should not be set"); + return this.lineMap || (this.lineMap = ts.computeLineStarts(this.getOrLoadText())); + }; + return TextStorage; + }()); + server.TextStorage = TextStorage; + /*@internal*/ + function isDynamicFileName(fileName) { + return fileName[0] === "^" || ts.getBaseFileName(fileName)[0] === "^"; + } + server.isDynamicFileName = isDynamicFileName; + var ScriptInfo = /** @class */ (function () { + function ScriptInfo(host, fileName, scriptKind, hasMixedContent, path, initialVersion) { + this.host = host; + this.fileName = fileName; + this.scriptKind = scriptKind; + this.hasMixedContent = hasMixedContent; + this.path = path; + /** + * All projects that include this file + */ + this.containingProjects = []; + this.isDynamic = isDynamicFileName(fileName); + this.textStorage = new TextStorage(host, fileName, initialVersion, this); + if (hasMixedContent || this.isDynamic) { + this.textStorage.reload(""); + this.realpath = this.path; + } + this.scriptKind = scriptKind + ? scriptKind + : ts.getScriptKindFromFileName(fileName); + } + /*@internal*/ + ScriptInfo.prototype.getVersion = function () { + return this.textStorage.version; + }; + /*@internal*/ + ScriptInfo.prototype.getTelemetryFileSize = function () { + return this.textStorage.getTelemetryFileSize(); + }; + /*@internal*/ + ScriptInfo.prototype.isDynamicOrHasMixedContent = function () { + return this.hasMixedContent || this.isDynamic; + }; + ScriptInfo.prototype.isScriptOpen = function () { + return this.textStorage.isOpen; + }; + ScriptInfo.prototype.open = function (newText) { + this.textStorage.isOpen = true; + if (newText !== undefined && + this.textStorage.reload(newText)) { + // reload new contents only if the existing contents changed + this.markContainingProjectsAsDirty(); + } + }; + ScriptInfo.prototype.close = function (fileExists) { + if (fileExists === void 0) { fileExists = true; } + this.textStorage.isOpen = false; + if (this.isDynamicOrHasMixedContent() || !fileExists) { + if (this.textStorage.reload("")) { + this.markContainingProjectsAsDirty(); + } + } + else if (this.textStorage.reloadFromDisk()) { + this.markContainingProjectsAsDirty(); + } + }; + ScriptInfo.prototype.getSnapshot = function () { + return this.textStorage.getSnapshot(); + }; + ScriptInfo.prototype.ensureRealPath = function () { + if (this.realpath === undefined) { + // Default is just the path + this.realpath = this.path; + if (this.host.realpath) { + ts.Debug.assert(!!this.containingProjects.length); + var project = this.containingProjects[0]; + var realpath = this.host.realpath(this.path); + if (realpath) { + this.realpath = project.toPath(realpath); + // If it is different from this.path, add to the map + if (this.realpath !== this.path) { + project.projectService.realpathToScriptInfos.add(this.realpath, this); // TODO: GH#18217 + } + } + } + } + }; + /*@internal*/ + ScriptInfo.prototype.getRealpathIfDifferent = function () { + return this.realpath && this.realpath !== this.path ? this.realpath : undefined; + }; + ScriptInfo.prototype.getFormatCodeSettings = function () { return this.formatSettings; }; + ScriptInfo.prototype.getPreferences = function () { return this.preferences; }; + ScriptInfo.prototype.attachToProject = function (project) { + var isNew = !this.isAttached(project); + if (isNew) { + this.containingProjects.push(project); + project.onFileAddedOrRemoved(); + if (!project.getCompilerOptions().preserveSymlinks) { + this.ensureRealPath(); + } + } + return isNew; + }; + ScriptInfo.prototype.isAttached = function (project) { + // unrolled for common cases + switch (this.containingProjects.length) { + case 0: return false; + case 1: return this.containingProjects[0] === project; + case 2: return this.containingProjects[0] === project || this.containingProjects[1] === project; + default: return ts.contains(this.containingProjects, project); + } + }; + ScriptInfo.prototype.detachFromProject = function (project) { + // unrolled for common cases + switch (this.containingProjects.length) { + case 0: + return; + case 1: + if (this.containingProjects[0] === project) { + project.onFileAddedOrRemoved(); + this.containingProjects.pop(); + } + break; + case 2: + if (this.containingProjects[0] === project) { + project.onFileAddedOrRemoved(); + this.containingProjects[0] = this.containingProjects.pop(); + } + else if (this.containingProjects[1] === project) { + project.onFileAddedOrRemoved(); + this.containingProjects.pop(); + } + break; + default: + if (ts.unorderedRemoveItem(this.containingProjects, project)) { + project.onFileAddedOrRemoved(); + } + break; + } + }; + ScriptInfo.prototype.detachAllProjects = function () { + for (var _i = 0, _a = this.containingProjects; _i < _a.length; _i++) { + var p = _a[_i]; + if (p.projectKind === server.ProjectKind.Configured) { + p.getCachedDirectoryStructureHost().addOrDeleteFile(this.fileName, this.path, ts.FileWatcherEventKind.Deleted); + } + var isInfoRoot = p.isRoot(this); + // detach is unnecessary since we'll clean the list of containing projects anyways + p.removeFile(this, /*fileExists*/ false, /*detachFromProjects*/ false); + // If the info was for the external or configured project's root, + // add missing file as the root + if (isInfoRoot && p.projectKind !== server.ProjectKind.Inferred) { + p.addMissingFileRoot(this.fileName); + } + } + ts.clear(this.containingProjects); + }; + ScriptInfo.prototype.getDefaultProject = function () { + switch (this.containingProjects.length) { + case 0: + return server.Errors.ThrowNoProject(); + case 1: + return this.containingProjects[0]; + default: + // if this file belongs to multiple projects, the first configured project should be + // the default project; if no configured projects, the first external project should + // be the default project; otherwise the first inferred project should be the default. + var firstExternalProject = void 0; + for (var _i = 0, _a = this.containingProjects; _i < _a.length; _i++) { + var project = _a[_i]; + if (project.projectKind === server.ProjectKind.Configured) { + return project; + } + else if (project.projectKind === server.ProjectKind.External && !firstExternalProject) { + firstExternalProject = project; + } + } + return firstExternalProject || this.containingProjects[0]; + } + }; + ScriptInfo.prototype.registerFileUpdate = function () { + for (var _i = 0, _a = this.containingProjects; _i < _a.length; _i++) { + var p = _a[_i]; + p.registerFileUpdate(this.path); + } + }; + ScriptInfo.prototype.setOptions = function (formatSettings, preferences) { + if (formatSettings) { + if (!this.formatSettings) { + this.formatSettings = ts.getDefaultFormatCodeSettings(this.host.newLine); + ts.assign(this.formatSettings, formatSettings); + } + else { + this.formatSettings = __assign({}, this.formatSettings, formatSettings); + } + } + if (preferences) { + if (!this.preferences) { + this.preferences = ts.emptyOptions; + } + this.preferences = __assign({}, this.preferences, preferences); + } + }; + ScriptInfo.prototype.getLatestVersion = function () { + return this.textStorage.getVersion(); + }; + ScriptInfo.prototype.saveTo = function (fileName) { + this.host.writeFile(fileName, ts.getSnapshotText(this.textStorage.getSnapshot())); + }; + /*@internal*/ + ScriptInfo.prototype.delayReloadNonMixedContentFile = function () { + ts.Debug.assert(!this.isDynamicOrHasMixedContent()); + this.textStorage.delayReloadFromFileIntoText(); + this.markContainingProjectsAsDirty(); + }; + ScriptInfo.prototype.reloadFromFile = function (tempFileName) { + if (this.isDynamicOrHasMixedContent()) { + this.textStorage.reload(""); + this.markContainingProjectsAsDirty(); + return true; + } + else { + if (this.textStorage.reloadWithFileText(tempFileName)) { + this.markContainingProjectsAsDirty(); + return true; + } + } + return false; + }; + /*@internal*/ + ScriptInfo.prototype.getLineInfo = function (line) { + return this.textStorage.getLineInfo(line); + }; + ScriptInfo.prototype.editContent = function (start, end, newText) { + this.textStorage.edit(start, end, newText); + this.markContainingProjectsAsDirty(); + }; + ScriptInfo.prototype.markContainingProjectsAsDirty = function () { + for (var _i = 0, _a = this.containingProjects; _i < _a.length; _i++) { + var p = _a[_i]; + p.markAsDirty(); + } + }; + ScriptInfo.prototype.isOrphan = function () { + return !ts.forEach(this.containingProjects, function (p) { return !p.isOrphan(); }); + }; + /** + * @param line 1 based index + */ + ScriptInfo.prototype.lineToTextSpan = function (line) { + return this.textStorage.lineToTextSpan(line); + }; + /** + * @param line 1 based index + * @param offset 1 based index + */ + ScriptInfo.prototype.lineOffsetToPosition = function (line, offset) { + return this.textStorage.lineOffsetToPosition(line, offset); + }; + ScriptInfo.prototype.positionToLineOffset = function (position) { + return this.textStorage.positionToLineOffset(position); + }; + ScriptInfo.prototype.isJavaScript = function () { + return this.scriptKind === 1 /* JS */ || this.scriptKind === 2 /* JSX */; + }; + return ScriptInfo; + }()); + server.ScriptInfo = ScriptInfo; + })(server = ts.server || (ts.server = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + var server; + (function (server) { + server.nullTypingsInstaller = { + isKnownTypesPackageName: ts.returnFalse, + // Should never be called because we never provide a types registry. + installPackage: ts.notImplemented, + inspectValue: ts.notImplemented, + enqueueInstallTypingsRequest: ts.noop, + attach: ts.noop, + onProjectClosed: ts.noop, + globalTypingsCacheLocation: undefined // TODO: GH#18217 + }; + function setIsEqualTo(arr1, arr2) { + if (arr1 === arr2) { + return true; + } + if ((arr1 || server.emptyArray).length === 0 && (arr2 || server.emptyArray).length === 0) { + return true; + } + var set = ts.createMap(); + var unique = 0; + for (var _i = 0, _a = arr1; _i < _a.length; _i++) { + var v = _a[_i]; + if (set.get(v) !== true) { + set.set(v, true); + unique++; + } + } + for (var _b = 0, _c = arr2; _b < _c.length; _b++) { + var v = _c[_b]; + var isSet = set.get(v); + if (isSet === undefined) { + return false; + } + if (isSet === true) { + set.set(v, false); + unique--; + } + } + return unique === 0; + } + function typeAcquisitionChanged(opt1, opt2) { + return opt1.enable !== opt2.enable || + !setIsEqualTo(opt1.include, opt2.include) || + !setIsEqualTo(opt1.exclude, opt2.exclude); + } + function compilerOptionsChanged(opt1, opt2) { + // TODO: add more relevant properties + return opt1.allowJs !== opt2.allowJs; + } + function unresolvedImportsChanged(imports1, imports2) { + if (imports1 === imports2) { + return false; + } + return !ts.arrayIsEqualTo(imports1, imports2); + } + /*@internal*/ + var TypingsCache = /** @class */ (function () { + function TypingsCache(installer) { + this.installer = installer; + this.perProjectCache = ts.createMap(); + } + TypingsCache.prototype.isKnownTypesPackageName = function (name) { + return this.installer.isKnownTypesPackageName(name); + }; + TypingsCache.prototype.installPackage = function (options) { + return this.installer.installPackage(options); + }; + TypingsCache.prototype.inspectValue = function (options) { + return this.installer.inspectValue(options); + }; + TypingsCache.prototype.enqueueInstallTypingsForProject = function (project, unresolvedImports, forceRefresh) { + var typeAcquisition = project.getTypeAcquisition(); + if (!typeAcquisition || !typeAcquisition.enable) { + return; + } + var entry = this.perProjectCache.get(project.getProjectName()); + if (forceRefresh || + !entry || + typeAcquisitionChanged(typeAcquisition, entry.typeAcquisition) || + compilerOptionsChanged(project.getCompilationSettings(), entry.compilerOptions) || + unresolvedImportsChanged(unresolvedImports, entry.unresolvedImports)) { + // Note: entry is now poisoned since it does not really contain typings for a given combination of compiler options\typings options. + // instead it acts as a placeholder to prevent issuing multiple requests + this.perProjectCache.set(project.getProjectName(), { + compilerOptions: project.getCompilationSettings(), + typeAcquisition: typeAcquisition, + typings: entry ? entry.typings : server.emptyArray, + unresolvedImports: unresolvedImports, + poisoned: true + }); + // something has been changed, issue a request to update typings + this.installer.enqueueInstallTypingsRequest(project, typeAcquisition, unresolvedImports); + } + }; + TypingsCache.prototype.updateTypingsForProject = function (projectName, compilerOptions, typeAcquisition, unresolvedImports, newTypings) { + var typings = ts.sort(newTypings); + this.perProjectCache.set(projectName, { + compilerOptions: compilerOptions, + typeAcquisition: typeAcquisition, + typings: typings, + unresolvedImports: unresolvedImports, + poisoned: false + }); + return !typeAcquisition || !typeAcquisition.enable ? server.emptyArray : typings; + }; + TypingsCache.prototype.onProjectClosed = function (project) { + this.perProjectCache.delete(project.getProjectName()); + this.installer.onProjectClosed(project); + }; + return TypingsCache; + }()); + server.TypingsCache = TypingsCache; + })(server = ts.server || (ts.server = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + var server; + (function (server) { + var ProjectKind; + (function (ProjectKind) { + ProjectKind[ProjectKind["Inferred"] = 0] = "Inferred"; + ProjectKind[ProjectKind["Configured"] = 1] = "Configured"; + ProjectKind[ProjectKind["External"] = 2] = "External"; + })(ProjectKind = server.ProjectKind || (server.ProjectKind = {})); + /* @internal */ + function countEachFileTypes(infos, includeSizes) { + if (includeSizes === void 0) { includeSizes = false; } + var result = { + js: 0, jsSize: 0, + jsx: 0, jsxSize: 0, + ts: 0, tsSize: 0, + tsx: 0, tsxSize: 0, + dts: 0, dtsSize: 0, + deferred: 0, deferredSize: 0, + }; + for (var _i = 0, infos_2 = infos; _i < infos_2.length; _i++) { + var info = infos_2[_i]; + var fileSize = includeSizes ? info.getTelemetryFileSize() : 0; + switch (info.scriptKind) { + case 1 /* JS */: + result.js += 1; + result.jsSize += fileSize; + break; + case 2 /* JSX */: + result.jsx += 1; + result.jsxSize += fileSize; + break; + case 3 /* TS */: + if (ts.fileExtensionIs(info.fileName, ".d.ts" /* Dts */)) { + result.dts += 1; + result.dtsSize += fileSize; + } + else { + result.ts += 1; + result.tsSize += fileSize; + } + break; + case 4 /* TSX */: + result.tsx += 1; + result.tsxSize += fileSize; + break; + case 7 /* Deferred */: + result.deferred += 1; + result.deferredSize += fileSize; + break; + } + } + return result; + } + server.countEachFileTypes = countEachFileTypes; + function hasOneOrMoreJsAndNoTsFiles(project) { + var counts = countEachFileTypes(project.getScriptInfos()); + return counts.js > 0 && counts.ts === 0 && counts.tsx === 0; + } + function allRootFilesAreJsOrDts(project) { + var counts = countEachFileTypes(project.getRootScriptInfos()); + return counts.ts === 0 && counts.tsx === 0; + } + server.allRootFilesAreJsOrDts = allRootFilesAreJsOrDts; + function allFilesAreJsOrDts(project) { + var counts = countEachFileTypes(project.getScriptInfos()); + return counts.ts === 0 && counts.tsx === 0; + } + server.allFilesAreJsOrDts = allFilesAreJsOrDts; + /* @internal */ + function hasNoTypeScriptSource(fileNames) { + return !fileNames.some(function (fileName) { return (ts.fileExtensionIs(fileName, ".ts" /* Ts */) && !ts.fileExtensionIs(fileName, ".d.ts" /* Dts */)) || ts.fileExtensionIs(fileName, ".tsx" /* Tsx */); }); + } + server.hasNoTypeScriptSource = hasNoTypeScriptSource; + /* @internal */ + function isScriptInfo(value) { + return value instanceof server.ScriptInfo; + } + server.isScriptInfo = isScriptInfo; + var Project = /** @class */ (function () { + /*@internal*/ + function Project(projectName, projectKind, projectService, documentRegistry, hasExplicitListOfFiles, lastFileExceededProgramSize, compilerOptions, compileOnSaveEnabled, directoryStructureHost, currentDirectory) { + var _this = this; + this.projectName = projectName; + this.projectKind = projectKind; + this.projectService = projectService; + this.documentRegistry = documentRegistry; + this.compilerOptions = compilerOptions; + this.compileOnSaveEnabled = compileOnSaveEnabled; + this.rootFiles = []; + this.rootFilesMap = ts.createMap(); + this.plugins = []; + /*@internal*/ + /** + * This is map from files to unresolved imports in it + * Maop does not contain entries for files that do not have unresolved imports + * This helps in containing the set of files to invalidate + */ + this.cachedUnresolvedImportsPerFile = ts.createMap(); + /*@internal*/ + this.hasAddedorRemovedFiles = false; + /** + * Last version that was reported. + */ + this.lastReportedVersion = 0; + /** + * Current project's program version. (incremented everytime new program is created that is not complete reuse from the old one) + * This property is changed in 'updateGraph' based on the set of files in program + */ + this.projectProgramVersion = 0; + /** + * Current version of the project state. It is changed when: + * - new root file was added/removed + * - edit happen in some file that is currently included in the project. + * This property is different from projectStructureVersion since in most cases edits don't affect set of files in the project + */ + this.projectStateVersion = 0; + this.isInitialLoadPending = ts.returnFalse; + /*@internal*/ + this.dirty = false; + /*@internal*/ + this.hasChangedAutomaticTypeDirectiveNames = false; + /*@internal*/ + this.typingFiles = server.emptyArray; + this.directoryStructureHost = directoryStructureHost; + this.currentDirectory = this.projectService.getNormalizedAbsolutePath(currentDirectory || ""); + this.getCanonicalFileName = this.projectService.toCanonicalFileName; + this.cancellationToken = new ts.ThrottledCancellationToken(this.projectService.cancellationToken, this.projectService.throttleWaitMilliseconds); + if (!this.compilerOptions) { + this.compilerOptions = ts.getDefaultCompilerOptions(); + this.compilerOptions.allowNonTsExtensions = true; + this.compilerOptions.allowJs = true; + } + else if (hasExplicitListOfFiles || this.compilerOptions.allowJs || this.projectService.hasDeferredExtension()) { + // If files are listed explicitly or allowJs is specified, allow all extensions + this.compilerOptions.allowNonTsExtensions = true; + } + this.languageServiceEnabled = !projectService.syntaxOnly; + this.setInternalCompilerOptionsForEmittingJsFiles(); + var host = this.projectService.host; + if (this.projectService.logger.loggingEnabled()) { + this.trace = function (s) { return _this.writeLog(s); }; + } + else if (host.trace) { + this.trace = function (s) { return host.trace(s); }; + } + if (host.realpath) { + this.realpath = function (path) { return host.realpath(path); }; + } + // Use the current directory as resolution root only if the project created using current directory string + this.resolutionCache = ts.createResolutionCache(this, currentDirectory && this.currentDirectory, /*logChangesWhenResolvingModule*/ true); + this.languageService = ts.createLanguageService(this, this.documentRegistry, projectService.syntaxOnly); + if (lastFileExceededProgramSize) { + this.disableLanguageService(lastFileExceededProgramSize); + } + this.markAsDirty(); + this.projectService.pendingEnsureProjectForOpenFiles = true; + } + Project.prototype.isNonTsProject = function () { + server.updateProjectIfDirty(this); + return allFilesAreJsOrDts(this); + }; + Project.prototype.isJsOnlyProject = function () { + server.updateProjectIfDirty(this); + return hasOneOrMoreJsAndNoTsFiles(this); + }; + Project.resolveModule = function (moduleName, initialDir, host, log) { + var resolvedPath = ts.normalizeSlashes(host.resolvePath(ts.combinePaths(initialDir, "node_modules"))); + log("Loading " + moduleName + " from " + initialDir + " (resolved to " + resolvedPath + ")"); + var result = host.require(resolvedPath, moduleName); // TODO: GH#18217 + if (result.error) { + var err = result.error.stack || result.error.message || JSON.stringify(result.error); + log("Failed to load module '" + moduleName + "': " + err); + return undefined; + } + return result.module; + }; + Project.prototype.isKnownTypesPackageName = function (name) { + return this.typingsCache.isKnownTypesPackageName(name); + }; + Project.prototype.installPackage = function (options) { + return this.typingsCache.installPackage(__assign({}, options, { projectName: this.projectName, projectRootPath: this.toPath(this.currentDirectory) })); + }; + /* @internal */ + Project.prototype.inspectValue = function (options) { + return this.typingsCache.inspectValue(options); + }; + Object.defineProperty(Project.prototype, "typingsCache", { + get: function () { + return this.projectService.typingsCache; + }, + enumerable: true, + configurable: true + }); + // Method of LanguageServiceHost + Project.prototype.getCompilationSettings = function () { + return this.compilerOptions; + }; + // Method to support public API + Project.prototype.getCompilerOptions = function () { + return this.getCompilationSettings(); + }; + Project.prototype.getNewLine = function () { + return this.projectService.host.newLine; + }; + Project.prototype.getProjectVersion = function () { + return this.projectStateVersion.toString(); + }; + Project.prototype.getProjectReferences = function () { + return undefined; + }; + Project.prototype.getScriptFileNames = function () { + var _this = this; + if (!this.rootFiles) { + return ts.emptyArray; + } + var result; + this.rootFilesMap.forEach(function (value) { + if (_this.languageServiceEnabled || (isScriptInfo(value) && value.isScriptOpen())) { + // if language service is disabled - process only files that are open + (result || (result = [])).push(isScriptInfo(value) ? value.fileName : value); + } + }); + return ts.addRange(result, this.typingFiles) || ts.emptyArray; + }; + Project.prototype.getOrCreateScriptInfoAndAttachToProject = function (fileName) { + var scriptInfo = this.projectService.getOrCreateScriptInfoNotOpenedByClient(fileName, this.currentDirectory, this.directoryStructureHost); + if (scriptInfo) { + var existingValue = this.rootFilesMap.get(scriptInfo.path); + if (existingValue !== scriptInfo && existingValue !== undefined) { + // This was missing path earlier but now the file exists. Update the root + this.rootFiles.push(scriptInfo); + this.rootFilesMap.set(scriptInfo.path, scriptInfo); + } + scriptInfo.attachToProject(this); + } + return scriptInfo; + }; + Project.prototype.getScriptKind = function (fileName) { + var info = this.getOrCreateScriptInfoAndAttachToProject(fileName); + return (info && info.scriptKind); // TODO: GH#18217 + }; + Project.prototype.getScriptVersion = function (filename) { + var info = this.getOrCreateScriptInfoAndAttachToProject(filename); + return (info && info.getLatestVersion()); // TODO: GH#18217 + }; + Project.prototype.getScriptSnapshot = function (filename) { + var scriptInfo = this.getOrCreateScriptInfoAndAttachToProject(filename); + if (scriptInfo) { + return scriptInfo.getSnapshot(); + } + }; + Project.prototype.getCancellationToken = function () { + return this.cancellationToken; + }; + Project.prototype.getCurrentDirectory = function () { + return this.currentDirectory; + }; + Project.prototype.getDefaultLibFileName = function () { + var nodeModuleBinDir = ts.getDirectoryPath(ts.normalizePath(this.projectService.getExecutingFilePath())); + return ts.combinePaths(nodeModuleBinDir, ts.getDefaultLibFileName(this.compilerOptions)); + }; + Project.prototype.useCaseSensitiveFileNames = function () { + return this.projectService.host.useCaseSensitiveFileNames; + }; + Project.prototype.readDirectory = function (path, extensions, exclude, include, depth) { + return this.directoryStructureHost.readDirectory(path, extensions, exclude, include, depth); + }; + Project.prototype.readFile = function (fileName) { + return this.projectService.host.readFile(fileName); + }; + Project.prototype.writeFile = function (fileName, content) { + return this.projectService.host.writeFile(fileName, content); + }; + Project.prototype.fileExists = function (file) { + // As an optimization, don't hit the disks for files we already know don't exist + // (because we're watching for their creation). + var path = this.toPath(file); + return !this.isWatchedMissingFile(path) && this.directoryStructureHost.fileExists(file); + }; + Project.prototype.resolveModuleNames = function (moduleNames, containingFile, reusedNames, redirectedReference) { + return this.resolutionCache.resolveModuleNames(moduleNames, containingFile, reusedNames, redirectedReference); + }; + Project.prototype.getResolvedModuleWithFailedLookupLocationsFromCache = function (moduleName, containingFile) { + return this.resolutionCache.getResolvedModuleWithFailedLookupLocationsFromCache(moduleName, containingFile); + }; + Project.prototype.resolveTypeReferenceDirectives = function (typeDirectiveNames, containingFile, redirectedReference) { + return this.resolutionCache.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile, redirectedReference); + }; + Project.prototype.directoryExists = function (path) { + return this.directoryStructureHost.directoryExists(path); // TODO: GH#18217 + }; + Project.prototype.getDirectories = function (path) { + return this.directoryStructureHost.getDirectories(path); // TODO: GH#18217 + }; + /*@internal*/ + Project.prototype.getCachedDirectoryStructureHost = function () { + return undefined; // TODO: GH#18217 + }; + /*@internal*/ + Project.prototype.toPath = function (fileName) { + return ts.toPath(fileName, this.currentDirectory, this.projectService.toCanonicalFileName); + }; + /*@internal*/ + Project.prototype.watchDirectoryOfFailedLookupLocation = function (directory, cb, flags) { + return this.projectService.watchFactory.watchDirectory(this.projectService.host, directory, cb, flags, "Directory of Failed lookup locations in module resolution" /* FailedLookupLocation */, this); + }; + /*@internal*/ + Project.prototype.onInvalidatedResolution = function () { + this.projectService.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles(this); + }; + /*@internal*/ + Project.prototype.watchTypeRootsDirectory = function (directory, cb, flags) { + return this.projectService.watchFactory.watchDirectory(this.projectService.host, directory, cb, flags, "Type root directory" /* TypeRoots */, this); + }; + /*@internal*/ + Project.prototype.onChangedAutomaticTypeDirectiveNames = function () { + this.hasChangedAutomaticTypeDirectiveNames = true; + this.projectService.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles(this); + }; + /*@internal*/ + Project.prototype.getGlobalCache = function () { + return this.getTypeAcquisition().enable ? this.projectService.typingsInstaller.globalTypingsCacheLocation : undefined; + }; + /*@internal*/ + Project.prototype.writeLog = function (s) { + this.projectService.logger.info(s); + }; + Project.prototype.log = function (s) { + this.writeLog(s); + }; + Project.prototype.error = function (s) { + this.projectService.logger.msg(s, server.Msg.Err); + }; + Project.prototype.setInternalCompilerOptionsForEmittingJsFiles = function () { + if (this.projectKind === ProjectKind.Inferred || this.projectKind === ProjectKind.External) { + this.compilerOptions.noEmitForJsFiles = true; + } + }; + /** + * Get the errors that dont have any file name associated + */ + Project.prototype.getGlobalProjectErrors = function () { + return server.emptyArray; + }; + Project.prototype.getAllProjectErrors = function () { + return server.emptyArray; + }; + Project.prototype.getLanguageService = function (ensureSynchronized) { + if (ensureSynchronized === void 0) { ensureSynchronized = true; } + if (ensureSynchronized) { + server.updateProjectIfDirty(this); + } + return this.languageService; + }; + /** @internal */ + Project.prototype.getSourceMapper = function () { + return this.getLanguageService().getSourceMapper(); + }; + Project.prototype.shouldEmitFile = function (scriptInfo) { + return scriptInfo && !scriptInfo.isDynamicOrHasMixedContent(); + }; + Project.prototype.getCompileOnSaveAffectedFileList = function (scriptInfo) { + var _this = this; + if (!this.languageServiceEnabled) { + return []; + } + server.updateProjectIfDirty(this); + this.builderState = ts.BuilderState.create(this.program, this.projectService.toCanonicalFileName, this.builderState); + return ts.mapDefined(ts.BuilderState.getFilesAffectedBy(this.builderState, this.program, scriptInfo.path, this.cancellationToken, function (data) { return _this.projectService.host.createHash(data); }), // TODO: GH#18217 + function (// TODO: GH#18217 + sourceFile) { return _this.shouldEmitFile(_this.projectService.getScriptInfoForPath(sourceFile.path)) ? sourceFile.fileName : undefined; }); + }; + /** + * Returns true if emit was conducted + */ + Project.prototype.emitFile = function (scriptInfo, writeFile) { + if (!this.languageServiceEnabled || !this.shouldEmitFile(scriptInfo)) { + return false; + } + var _a = this.getLanguageService(/*ensureSynchronized*/ false).getEmitOutput(scriptInfo.fileName), emitSkipped = _a.emitSkipped, outputFiles = _a.outputFiles; + if (!emitSkipped) { + for (var _i = 0, outputFiles_1 = outputFiles; _i < outputFiles_1.length; _i++) { + var outputFile = outputFiles_1[_i]; + var outputFileAbsoluteFileName = ts.getNormalizedAbsolutePath(outputFile.name, this.currentDirectory); + writeFile(outputFileAbsoluteFileName, outputFile.text, outputFile.writeByteOrderMark); + } + } + return !emitSkipped; + }; + Project.prototype.enableLanguageService = function () { + if (this.languageServiceEnabled || this.projectService.syntaxOnly) { + return; + } + this.languageServiceEnabled = true; + this.lastFileExceededProgramSize = undefined; + this.projectService.onUpdateLanguageServiceStateForProject(this, /*languageServiceEnabled*/ true); + }; + Project.prototype.disableLanguageService = function (lastFileExceededProgramSize) { + if (!this.languageServiceEnabled) { + return; + } + ts.Debug.assert(!this.projectService.syntaxOnly); + this.languageService.cleanupSemanticCache(); + this.languageServiceEnabled = false; + this.lastFileExceededProgramSize = lastFileExceededProgramSize; + this.builderState = undefined; + this.resolutionCache.closeTypeRootsWatch(); + this.projectService.onUpdateLanguageServiceStateForProject(this, /*languageServiceEnabled*/ false); + }; + Project.prototype.getProjectName = function () { + return this.projectName; + }; + Project.prototype.removeLocalTypingsFromTypeAcquisition = function (newTypeAcquisition) { + if (!newTypeAcquisition || !newTypeAcquisition.include) { + // Nothing to filter out, so just return as-is + return newTypeAcquisition; + } + return __assign({}, newTypeAcquisition, { include: this.removeExistingTypings(newTypeAcquisition.include) }); + }; + Project.prototype.getExternalFiles = function () { + var _this = this; + return ts.sort(ts.flatMap(this.plugins, function (plugin) { + if (typeof plugin.module.getExternalFiles !== "function") + return; + try { + return plugin.module.getExternalFiles(_this); + } + catch (e) { + _this.projectService.logger.info("A plugin threw an exception in getExternalFiles: " + e); + if (e.stack) { + _this.projectService.logger.info(e.stack); + } + } + })); + }; + Project.prototype.getSourceFile = function (path) { + if (!this.program) { + return undefined; + } + return this.program.getSourceFileByPath(path); + }; + /* @internal */ + Project.prototype.getSourceFileOrConfigFile = function (path) { + var options = this.program.getCompilerOptions(); + return path === options.configFilePath ? options.configFile : this.getSourceFile(path); + }; + Project.prototype.close = function () { + var _this = this; + if (this.program) { + // if we have a program - release all files that are enlisted in program but arent root + // The releasing of the roots happens later + // The project could have pending update remaining and hence the info could be in the files but not in program graph + for (var _i = 0, _a = this.program.getSourceFiles(); _i < _a.length; _i++) { + var f = _a[_i]; + this.detachScriptInfoIfNotRoot(f.fileName); + } + this.program.forEachResolvedProjectReference(function (ref) { + if (ref) { + _this.detachScriptInfoFromProject(ref.sourceFile.fileName); + } + }); + } + // Release external files + ts.forEach(this.externalFiles, function (externalFile) { return _this.detachScriptInfoIfNotRoot(externalFile); }); + // Always remove root files from the project + for (var _b = 0, _c = this.rootFiles; _b < _c.length; _b++) { + var root = _c[_b]; + root.detachFromProject(this); + } + this.projectService.pendingEnsureProjectForOpenFiles = true; + this.rootFiles = undefined; + this.rootFilesMap = undefined; + this.externalFiles = undefined; + this.program = undefined; + this.builderState = undefined; + this.resolutionCache.clear(); + this.resolutionCache = undefined; + this.cachedUnresolvedImportsPerFile = undefined; + this.directoryStructureHost = undefined; + // Clean up file watchers waiting for missing files + if (this.missingFilesMap) { + ts.clearMap(this.missingFilesMap, ts.closeFileWatcher); + this.missingFilesMap = undefined; + } + // signal language service to release source files acquired from document registry + this.languageService.dispose(); + this.languageService = undefined; + }; + Project.prototype.detachScriptInfoIfNotRoot = function (uncheckedFilename) { + var info = this.projectService.getScriptInfo(uncheckedFilename); + // We might not find the script info in case its not associated with the project any more + // and project graph was not updated (eg delayed update graph in case of files changed/deleted on the disk) + if (info && !this.isRoot(info)) { + info.detachFromProject(this); + } + }; + Project.prototype.isClosed = function () { + return this.rootFiles === undefined; + }; + Project.prototype.hasRoots = function () { + return this.rootFiles && this.rootFiles.length > 0; + }; + /*@internal*/ + Project.prototype.isOrphan = function () { + return false; + }; + Project.prototype.getRootFiles = function () { + return this.rootFiles && this.rootFiles.map(function (info) { return info.fileName; }); + }; + /*@internal*/ + Project.prototype.getRootFilesMap = function () { + return this.rootFilesMap; + }; + Project.prototype.getRootScriptInfos = function () { + return this.rootFiles; + }; + Project.prototype.getScriptInfos = function () { + var _this = this; + if (!this.languageServiceEnabled) { + // if language service is not enabled - return just root files + return this.rootFiles; + } + return ts.map(this.program.getSourceFiles(), function (sourceFile) { + var scriptInfo = _this.projectService.getScriptInfoForPath(sourceFile.resolvedPath); + ts.Debug.assert(!!scriptInfo, "getScriptInfo", function () { return "scriptInfo for a file '" + sourceFile.fileName + "' Path: '" + sourceFile.path + "' / '" + sourceFile.resolvedPath + "' is missing."; }); + return scriptInfo; + }); + }; + Project.prototype.getExcludedFiles = function () { + return server.emptyArray; + }; + Project.prototype.getFileNames = function (excludeFilesFromExternalLibraries, excludeConfigFiles) { + if (!this.program) { + return []; + } + if (!this.languageServiceEnabled) { + // if language service is disabled assume that all files in program are root files + default library + var rootFiles = this.getRootFiles(); + if (this.compilerOptions) { + var defaultLibrary = ts.getDefaultLibFilePath(this.compilerOptions); + if (defaultLibrary) { + (rootFiles || (rootFiles = [])).push(server.asNormalizedPath(defaultLibrary)); + } + } + return rootFiles; + } + var result = []; + for (var _i = 0, _a = this.program.getSourceFiles(); _i < _a.length; _i++) { + var f = _a[_i]; + if (excludeFilesFromExternalLibraries && this.program.isSourceFileFromExternalLibrary(f)) { + continue; + } + result.push(server.asNormalizedPath(f.fileName)); + } + if (!excludeConfigFiles) { + var configFile = this.program.getCompilerOptions().configFile; + if (configFile) { + result.push(server.asNormalizedPath(configFile.fileName)); + if (configFile.extendedSourceFiles) { + for (var _b = 0, _c = configFile.extendedSourceFiles; _b < _c.length; _b++) { + var f = _c[_b]; + result.push(server.asNormalizedPath(f)); + } + } + } + } + return result; + }; + Project.prototype.hasConfigFile = function (configFilePath) { + if (this.program && this.languageServiceEnabled) { + var configFile = this.program.getCompilerOptions().configFile; + if (configFile) { + if (configFilePath === server.asNormalizedPath(configFile.fileName)) { + return true; + } + if (configFile.extendedSourceFiles) { + for (var _i = 0, _a = configFile.extendedSourceFiles; _i < _a.length; _i++) { + var f = _a[_i]; + if (configFilePath === server.asNormalizedPath(f)) { + return true; + } + } + } + } + } + return false; + }; + Project.prototype.containsScriptInfo = function (info) { + return this.isRoot(info) || (!!this.program && this.program.getSourceFileByPath(info.path) !== undefined); + }; + Project.prototype.containsFile = function (filename, requireOpen) { + var info = this.projectService.getScriptInfoForNormalizedPath(filename); + if (info && (info.isScriptOpen() || !requireOpen)) { + return this.containsScriptInfo(info); + } + return false; + }; + Project.prototype.isRoot = function (info) { + return this.rootFilesMap && this.rootFilesMap.get(info.path) === info; + }; + // add a root file to project + Project.prototype.addRoot = function (info) { + ts.Debug.assert(!this.isRoot(info)); + this.rootFiles.push(info); + this.rootFilesMap.set(info.path, info); + info.attachToProject(this); + this.markAsDirty(); + }; + // add a root file that doesnt exist on host + Project.prototype.addMissingFileRoot = function (fileName) { + var path = this.projectService.toPath(fileName); + this.rootFilesMap.set(path, fileName); + this.markAsDirty(); + }; + Project.prototype.removeFile = function (info, fileExists, detachFromProject) { + if (this.isRoot(info)) { + this.removeRoot(info); + } + if (fileExists) { + // If file is present, just remove the resolutions for the file + this.resolutionCache.removeResolutionsOfFile(info.path); + } + else { + this.resolutionCache.invalidateResolutionOfFile(info.path); + } + this.cachedUnresolvedImportsPerFile.delete(info.path); + if (detachFromProject) { + info.detachFromProject(this); + } + this.markAsDirty(); + }; + Project.prototype.registerFileUpdate = function (fileName) { + (this.updatedFileNames || (this.updatedFileNames = ts.createMap())).set(fileName, true); + }; + Project.prototype.markAsDirty = function () { + if (!this.dirty) { + this.projectStateVersion++; + this.dirty = true; + } + }; + /* @internal */ + Project.prototype.onFileAddedOrRemoved = function () { + this.hasAddedorRemovedFiles = true; + }; + /** + * Updates set of files that contribute to this project + * @returns: true if set of files in the project stays the same and false - otherwise. + */ + Project.prototype.updateGraph = function () { + this.resolutionCache.startRecordingFilesWithChangedResolutions(); + var hasNewProgram = this.updateGraphWorker(); + var hasAddedorRemovedFiles = this.hasAddedorRemovedFiles; + this.hasAddedorRemovedFiles = false; + var changedFiles = this.resolutionCache.finishRecordingFilesWithChangedResolutions() || server.emptyArray; + for (var _i = 0, changedFiles_1 = changedFiles; _i < changedFiles_1.length; _i++) { + var file = changedFiles_1[_i]; + // delete cached information for changed files + this.cachedUnresolvedImportsPerFile.delete(file); + } + // update builder only if language service is enabled + // otherwise tell it to drop its internal state + if (this.languageServiceEnabled) { + // 1. no changes in structure, no changes in unresolved imports - do nothing + // 2. no changes in structure, unresolved imports were changed - collect unresolved imports for all files + // (can reuse cached imports for files that were not changed) + // 3. new files were added/removed, but compilation settings stays the same - collect unresolved imports for all new/modified files + // (can reuse cached imports for files that were not changed) + // 4. compilation settings were changed in the way that might affect module resolution - drop all caches and collect all data from the scratch + if (hasNewProgram || changedFiles.length) { + this.lastCachedUnresolvedImportsList = getUnresolvedImports(this.program, this.cachedUnresolvedImportsPerFile); + } + this.projectService.typingsCache.enqueueInstallTypingsForProject(this, this.lastCachedUnresolvedImportsList, hasAddedorRemovedFiles); + } + else { + this.lastCachedUnresolvedImportsList = undefined; + } + if (hasNewProgram) { + this.projectProgramVersion++; + } + return !hasNewProgram; + }; + /*@internal*/ + Project.prototype.updateTypingFiles = function (typingFiles) { + var _this = this; + ts.enumerateInsertsAndDeletes(typingFiles, this.typingFiles, ts.getStringComparer(!this.useCaseSensitiveFileNames()), + /*inserted*/ ts.noop, function (removed) { return _this.detachScriptInfoFromProject(removed); }); + this.typingFiles = typingFiles; + // Invalidate files with unresolved imports + this.resolutionCache.setFilesWithInvalidatedNonRelativeUnresolvedImports(this.cachedUnresolvedImportsPerFile); + }; + /* @internal */ + Project.prototype.getCurrentProgram = function () { + return this.program; + }; + Project.prototype.removeExistingTypings = function (include) { + var existing = ts.getAutomaticTypeDirectiveNames(this.getCompilerOptions(), this.directoryStructureHost); + return include.filter(function (i) { return existing.indexOf(i) < 0; }); + }; + Project.prototype.updateGraphWorker = function () { + var _this = this; + var oldProgram = this.program; + ts.Debug.assert(!this.isClosed(), "Called update graph worker of closed project"); + this.writeLog("Starting updateGraphWorker: Project: " + this.getProjectName()); + var start = ts.timestamp(); + this.hasInvalidatedResolution = this.resolutionCache.createHasInvalidatedResolution(); + this.resolutionCache.startCachingPerDirectoryResolution(); + this.program = this.languageService.getProgram(); // TODO: GH#18217 + this.dirty = false; + this.resolutionCache.finishCachingPerDirectoryResolution(); + ts.Debug.assert(oldProgram === undefined || this.program !== undefined); + // bump up the version if + // - oldProgram is not set - this is a first time updateGraph is called + // - newProgram is different from the old program and structure of the old program was not reused. + var hasNewProgram = this.program && (!oldProgram || (this.program !== oldProgram && !(oldProgram.structureIsReused & 2 /* Completely */))); + this.hasChangedAutomaticTypeDirectiveNames = false; + if (hasNewProgram) { + if (oldProgram) { + for (var _i = 0, _a = oldProgram.getSourceFiles(); _i < _a.length; _i++) { + var f = _a[_i]; + var newFile = this.program.getSourceFileByPath(f.resolvedPath); + if (!newFile || (f.resolvedPath === f.path && newFile.resolvedPath !== f.path)) { + // new program does not contain this file - detach it from the project + // - remove resolutions only if the new program doesnt contain source file by the path (not resolvedPath since path is used for resolution) + this.detachScriptInfoFromProject(f.fileName, !!this.program.getSourceFileByPath(f.path)); + } + } + oldProgram.forEachResolvedProjectReference(function (resolvedProjectReference, resolvedProjectReferencePath) { + if (resolvedProjectReference && !_this.program.getResolvedProjectReferenceByPath(resolvedProjectReferencePath)) { + _this.detachScriptInfoFromProject(resolvedProjectReference.sourceFile.fileName); + } + }); + } + // Update the missing file paths watcher + ts.updateMissingFilePathsWatch(this.program, this.missingFilesMap || (this.missingFilesMap = ts.createMap()), + // Watch the missing files + function (missingFilePath) { return _this.addMissingFileWatcher(missingFilePath); }); + // Watch the type locations that would be added to program as part of automatic type resolutions + if (this.languageServiceEnabled) { + this.resolutionCache.updateTypeRootsWatch(); + } + } + var oldExternalFiles = this.externalFiles || server.emptyArray; + this.externalFiles = this.getExternalFiles(); + ts.enumerateInsertsAndDeletes(this.externalFiles, oldExternalFiles, ts.getStringComparer(!this.useCaseSensitiveFileNames()), + // Ensure a ScriptInfo is created for new external files. This is performed indirectly + // by the LSHost for files in the program when the program is retrieved above but + // the program doesn't contain external files so this must be done explicitly. + function (inserted) { + var scriptInfo = _this.projectService.getOrCreateScriptInfoNotOpenedByClient(inserted, _this.currentDirectory, _this.directoryStructureHost); + scriptInfo.attachToProject(_this); + }, function (removed) { return _this.detachScriptInfoFromProject(removed); }); + var elapsed = ts.timestamp() - start; + this.writeLog("Finishing updateGraphWorker: Project: " + this.getProjectName() + " Version: " + this.getProjectVersion() + " structureChanged: " + hasNewProgram + " Elapsed: " + elapsed + "ms"); + return hasNewProgram; + }; + Project.prototype.detachScriptInfoFromProject = function (uncheckedFileName, noRemoveResolution) { + var scriptInfoToDetach = this.projectService.getScriptInfo(uncheckedFileName); + if (scriptInfoToDetach) { + scriptInfoToDetach.detachFromProject(this); + if (!noRemoveResolution) { + this.resolutionCache.removeResolutionsOfFile(scriptInfoToDetach.path); + } + } + }; + Project.prototype.addMissingFileWatcher = function (missingFilePath) { + var _this = this; + var fileWatcher = this.projectService.watchFactory.watchFile(this.projectService.host, missingFilePath, function (fileName, eventKind) { + if (_this.projectKind === ProjectKind.Configured) { + _this.getCachedDirectoryStructureHost().addOrDeleteFile(fileName, missingFilePath, eventKind); + } + if (eventKind === ts.FileWatcherEventKind.Created && _this.missingFilesMap.has(missingFilePath)) { + _this.missingFilesMap.delete(missingFilePath); + fileWatcher.close(); + // When a missing file is created, we should update the graph. + _this.projectService.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles(_this); + } + }, ts.PollingInterval.Medium, "Missing file from program" /* MissingFilePath */, this); + return fileWatcher; + }; + Project.prototype.isWatchedMissingFile = function (path) { + return !!this.missingFilesMap && this.missingFilesMap.has(path); + }; + Project.prototype.getScriptInfoForNormalizedPath = function (fileName) { + var scriptInfo = this.projectService.getScriptInfoForPath(this.toPath(fileName)); + if (scriptInfo && !scriptInfo.isAttached(this)) { + return server.Errors.ThrowProjectDoesNotContainDocument(fileName, this); + } + return scriptInfo; + }; + Project.prototype.getScriptInfo = function (uncheckedFileName) { + return this.projectService.getScriptInfo(uncheckedFileName); + }; + Project.prototype.filesToString = function (writeProjectFileNames) { + if (!this.program) { + return "\tFiles (0)\n"; + } + var sourceFiles = this.program.getSourceFiles(); + var strBuilder = "\tFiles (" + sourceFiles.length + ")\n"; + if (writeProjectFileNames) { + for (var _i = 0, sourceFiles_7 = sourceFiles; _i < sourceFiles_7.length; _i++) { + var file = sourceFiles_7[_i]; + strBuilder += "\t" + file.fileName + "\n"; + } + } + return strBuilder; + }; + /*@internal*/ + Project.prototype.print = function (counter) { + this.writeLog("Project '" + this.projectName + "' (" + ProjectKind[this.projectKind] + ") " + (counter === undefined ? "" : counter)); + this.writeLog(this.filesToString(this.projectService.logger.hasLevel(server.LogLevel.verbose))); + this.writeLog("-----------------------------------------------"); + }; + Project.prototype.setCompilerOptions = function (compilerOptions) { + if (compilerOptions) { + compilerOptions.allowNonTsExtensions = true; + var oldOptions = this.compilerOptions; + this.compilerOptions = compilerOptions; + this.setInternalCompilerOptionsForEmittingJsFiles(); + if (ts.changesAffectModuleResolution(oldOptions, compilerOptions)) { + // reset cached unresolved imports if changes in compiler options affected module resolution + this.cachedUnresolvedImportsPerFile.clear(); + this.lastCachedUnresolvedImportsList = undefined; + this.resolutionCache.clear(); + } + this.markAsDirty(); + } + }; + /* @internal */ + Project.prototype.getChangesSinceVersion = function (lastKnownVersion) { + // Update the graph only if initial configured project load is not pending + if (!this.isInitialLoadPending()) { + server.updateProjectIfDirty(this); + } + var info = { + projectName: this.getProjectName(), + version: this.projectProgramVersion, + isInferred: this.projectKind === ProjectKind.Inferred, + options: this.getCompilationSettings(), + languageServiceDisabled: !this.languageServiceEnabled, + lastFileExceededProgramSize: this.lastFileExceededProgramSize + }; + var updatedFileNames = this.updatedFileNames; + this.updatedFileNames = undefined; + // check if requested version is the same that we have reported last time + if (this.lastReportedFileNames && lastKnownVersion === this.lastReportedVersion) { + // if current structure version is the same - return info without any changes + if (this.projectProgramVersion === this.lastReportedVersion && !updatedFileNames) { + return { info: info, projectErrors: this.getGlobalProjectErrors() }; + } + // compute and return the difference + var lastReportedFileNames_1 = this.lastReportedFileNames; + var externalFiles = this.getExternalFiles().map(function (f) { return server.toNormalizedPath(f); }); + var currentFiles_1 = ts.arrayToSet(this.getFileNames().concat(externalFiles)); + var added_1 = []; + var removed_1 = []; + var updated = updatedFileNames ? ts.arrayFrom(updatedFileNames.keys()) : []; + ts.forEachKey(currentFiles_1, function (id) { + if (!lastReportedFileNames_1.has(id)) { + added_1.push(id); + } + }); + ts.forEachKey(lastReportedFileNames_1, function (id) { + if (!currentFiles_1.has(id)) { + removed_1.push(id); + } + }); + this.lastReportedFileNames = currentFiles_1; + this.lastReportedVersion = this.projectProgramVersion; + return { info: info, changes: { added: added_1, removed: removed_1, updated: updated }, projectErrors: this.getGlobalProjectErrors() }; + } + else { + // unknown version - return everything + var projectFileNames = this.getFileNames(); + var externalFiles = this.getExternalFiles().map(function (f) { return server.toNormalizedPath(f); }); + var allFiles = projectFileNames.concat(externalFiles); + this.lastReportedFileNames = ts.arrayToSet(allFiles); + this.lastReportedVersion = this.projectProgramVersion; + return { info: info, files: allFiles, projectErrors: this.getGlobalProjectErrors() }; + } + }; + // remove a root file from project + Project.prototype.removeRoot = function (info) { + ts.orderedRemoveItem(this.rootFiles, info); + this.rootFilesMap.delete(info.path); + }; + Project.prototype.enableGlobalPlugins = function (options, pluginConfigOverrides) { + var host = this.projectService.host; + if (!host.require) { + this.projectService.logger.info("Plugins were requested but not running in environment that supports 'require'. Nothing will be loaded"); + return; + } + // Search our peer node_modules, then any globally-specified probe paths + // ../../.. to walk from X/node_modules/typescript/lib/tsserver.js to X/node_modules/ + var searchPaths = [ts.combinePaths(this.projectService.getExecutingFilePath(), "../../..")].concat(this.projectService.pluginProbeLocations); + if (this.projectService.globalPlugins) { + var _loop_25 = function (globalPluginName) { + // Skip empty names from odd commandline parses + if (!globalPluginName) + return "continue"; + // Skip already-locally-loaded plugins + if (options.plugins && options.plugins.some(function (p) { return p.name === globalPluginName; })) + return "continue"; + // Provide global: true so plugins can detect why they can't find their config + this_2.projectService.logger.info("Loading global plugin " + globalPluginName); + this_2.enablePlugin({ name: globalPluginName, global: true }, searchPaths, pluginConfigOverrides); + }; + var this_2 = this; + // Enable global plugins with synthetic configuration entries + for (var _i = 0, _a = this.projectService.globalPlugins; _i < _a.length; _i++) { + var globalPluginName = _a[_i]; + _loop_25(globalPluginName); + } + } + }; + Project.prototype.enablePlugin = function (pluginConfigEntry, searchPaths, pluginConfigOverrides) { + var _this = this; + this.projectService.logger.info("Enabling plugin " + pluginConfigEntry.name + " from candidate paths: " + searchPaths.join(",")); + var log = function (message) { + _this.projectService.logger.info(message); + }; + var resolvedModule = ts.firstDefined(searchPaths, function (searchPath) { + return Project.resolveModule(pluginConfigEntry.name, searchPath, _this.projectService.host, log); + }); + if (resolvedModule) { + var configurationOverride = pluginConfigOverrides && pluginConfigOverrides.get(pluginConfigEntry.name); + if (configurationOverride) { + // Preserve the name property since it's immutable + var pluginName = pluginConfigEntry.name; + pluginConfigEntry = configurationOverride; + pluginConfigEntry.name = pluginName; + } + this.enableProxy(resolvedModule, pluginConfigEntry); + } + else { + this.projectService.logger.info("Couldn't find " + pluginConfigEntry.name); + } + }; + Project.prototype.enableProxy = function (pluginModuleFactory, configEntry) { + try { + if (typeof pluginModuleFactory !== "function") { + this.projectService.logger.info("Skipped loading plugin " + configEntry.name + " because it did expose a proper factory function"); + return; + } + var info = { + config: configEntry, + project: this, + languageService: this.languageService, + languageServiceHost: this, + serverHost: this.projectService.host + }; + var pluginModule = pluginModuleFactory({ typescript: ts }); + var newLS = pluginModule.create(info); + for (var _i = 0, _a = Object.keys(this.languageService); _i < _a.length; _i++) { + var k = _a[_i]; + if (!(k in newLS)) { + this.projectService.logger.info("Plugin activation warning: Missing proxied method " + k + " in created LS. Patching."); + newLS[k] = this.languageService[k]; + } + } + this.projectService.logger.info("Plugin validation succeded"); + this.languageService = newLS; + this.plugins.push({ name: configEntry.name, module: pluginModule }); + } + catch (e) { + this.projectService.logger.info("Plugin activation failed: " + e); + } + }; + /*@internal*/ + Project.prototype.onPluginConfigurationChanged = function (pluginName, configuration) { + this.plugins.filter(function (plugin) { return plugin.name === pluginName; }).forEach(function (plugin) { + if (plugin.module.onConfigurationChanged) { + plugin.module.onConfigurationChanged(configuration); + } + }); + }; + /** Starts a new check for diagnostics. Call this if some file has updated that would cause diagnostics to be changed. */ + Project.prototype.refreshDiagnostics = function () { + this.projectService.sendProjectsUpdatedInBackgroundEvent(); + }; + return Project; + }()); + server.Project = Project; + function getUnresolvedImports(program, cachedUnresolvedImportsPerFile) { + var ambientModules = program.getTypeChecker().getAmbientModules().map(function (mod) { return ts.stripQuotes(mod.getName()); }); + return ts.sortAndDeduplicate(ts.flatMap(program.getSourceFiles(), function (sourceFile) { + return extractUnresolvedImportsFromSourceFile(sourceFile, ambientModules, cachedUnresolvedImportsPerFile); + })); + } + function extractUnresolvedImportsFromSourceFile(file, ambientModules, cachedUnresolvedImportsPerFile) { + return ts.getOrUpdate(cachedUnresolvedImportsPerFile, file.path, function () { + if (!file.resolvedModules) + return server.emptyArray; + var unresolvedImports; + file.resolvedModules.forEach(function (resolvedModule, name) { + // pick unresolved non-relative names + if ((!resolvedModule || !ts.resolutionExtensionIsTSOrJson(resolvedModule.extension)) && + !ts.isExternalModuleNameRelative(name) && + !ambientModules.some(function (m) { return m === name; })) { + unresolvedImports = ts.append(unresolvedImports, ts.parsePackageName(name).packageName); + } + }); + return unresolvedImports || server.emptyArray; + }); + } + /** + * If a file is opened and no tsconfig (or jsconfig) is found, + * the file and its imports/references are put into an InferredProject. + */ + var InferredProject = /** @class */ (function (_super) { + __extends(InferredProject, _super); + /*@internal*/ + function InferredProject(projectService, documentRegistry, compilerOptions, projectRootPath, currentDirectory, pluginConfigOverrides) { + var _this = _super.call(this, InferredProject.newName(), ProjectKind.Inferred, projectService, documentRegistry, + // TODO: GH#18217 + /*files*/ undefined, + /*lastFileExceededProgramSize*/ undefined, compilerOptions, + /*compileOnSaveEnabled*/ false, projectService.host, currentDirectory) || this; + _this._isJsInferredProject = false; + _this.projectRootPath = projectRootPath && projectService.toCanonicalFileName(projectRootPath); + if (!projectRootPath && !projectService.useSingleInferredProject) { + _this.canonicalCurrentDirectory = projectService.toCanonicalFileName(_this.currentDirectory); + } + _this.enableGlobalPlugins(_this.getCompilerOptions(), pluginConfigOverrides); + return _this; + } + InferredProject.prototype.toggleJsInferredProject = function (isJsInferredProject) { + if (isJsInferredProject !== this._isJsInferredProject) { + this._isJsInferredProject = isJsInferredProject; + this.setCompilerOptions(); + } + }; + InferredProject.prototype.setCompilerOptions = function (options) { + // Avoid manipulating the given options directly + if (!options && !this.getCompilationSettings()) { + return; + } + var newOptions = ts.cloneCompilerOptions(options || this.getCompilationSettings()); + if (this._isJsInferredProject && typeof newOptions.maxNodeModuleJsDepth !== "number") { + newOptions.maxNodeModuleJsDepth = 2; + } + else if (!this._isJsInferredProject) { + newOptions.maxNodeModuleJsDepth = undefined; + } + newOptions.allowJs = true; + _super.prototype.setCompilerOptions.call(this, newOptions); + }; + InferredProject.prototype.addRoot = function (info) { + ts.Debug.assert(info.isScriptOpen()); + this.projectService.startWatchingConfigFilesForInferredProjectRoot(info); + if (!this._isJsInferredProject && info.isJavaScript()) { + this.toggleJsInferredProject(/*isJsInferredProject*/ true); + } + _super.prototype.addRoot.call(this, info); + }; + InferredProject.prototype.removeRoot = function (info) { + this.projectService.stopWatchingConfigFilesForInferredProjectRoot(info); + _super.prototype.removeRoot.call(this, info); + if (this._isJsInferredProject && info.isJavaScript()) { + if (ts.every(this.getRootScriptInfos(), function (rootInfo) { return !rootInfo.isJavaScript(); })) { + this.toggleJsInferredProject(/*isJsInferredProject*/ false); + } + } + }; + /*@internal*/ + InferredProject.prototype.isOrphan = function () { + return !this.hasRoots(); + }; + InferredProject.prototype.isProjectWithSingleRoot = function () { + // - when useSingleInferredProject is not set and projectRootPath is not set, + // we can guarantee that this will be the only root + // - other wise it has single root if it has single root script info + return (!this.projectRootPath && !this.projectService.useSingleInferredProject) || + this.getRootScriptInfos().length === 1; + }; + InferredProject.prototype.close = function () { + var _this = this; + ts.forEach(this.getRootScriptInfos(), function (info) { return _this.projectService.stopWatchingConfigFilesForInferredProjectRoot(info); }); + _super.prototype.close.call(this); + }; + InferredProject.prototype.getTypeAcquisition = function () { + return { + enable: allRootFilesAreJsOrDts(this), + include: [], + exclude: [] + }; + }; + InferredProject.newName = (function () { + var nextId = 1; + return function () { + var id = nextId; + nextId++; + return server.makeInferredProjectName(id); + }; + })(); + return InferredProject; + }(Project)); + server.InferredProject = InferredProject; + /** + * If a file is opened, the server will look for a tsconfig (or jsconfig) + * and if successfull create a ConfiguredProject for it. + * Otherwise it will create an InferredProject. + */ + var ConfiguredProject = /** @class */ (function (_super) { + __extends(ConfiguredProject, _super); + /*@internal*/ + function ConfiguredProject(configFileName, projectService, documentRegistry, cachedDirectoryStructureHost) { + var _this = _super.call(this, configFileName, ProjectKind.Configured, projectService, documentRegistry, + /*hasExplicitListOfFiles*/ false, + /*lastFileExceededProgramSize*/ undefined, + /*compilerOptions*/ {}, + /*compileOnSaveEnabled*/ false, cachedDirectoryStructureHost, ts.getDirectoryPath(configFileName)) || this; + /*@internal*/ + _this.canConfigFileJsonReportNoInputFiles = false; + /** Ref count to the project when opened from external project */ + _this.externalProjectRefCount = 0; + _this.isInitialLoadPending = ts.returnTrue; + /*@internal*/ + _this.sendLoadingProjectFinish = false; + _this.canonicalConfigFilePath = server.asNormalizedPath(projectService.toCanonicalFileName(configFileName)); + return _this; + } + /** + * If the project has reload from disk pending, it reloads (and then updates graph as part of that) instead of just updating the graph + * @returns: true if set of files in the project stays the same and false - otherwise. + */ + ConfiguredProject.prototype.updateGraph = function () { + this.isInitialLoadPending = ts.returnFalse; + var reloadLevel = this.pendingReload; + this.pendingReload = ts.ConfigFileProgramReloadLevel.None; + var result; + switch (reloadLevel) { + case ts.ConfigFileProgramReloadLevel.Partial: + result = this.projectService.reloadFileNamesOfConfiguredProject(this); + break; + case ts.ConfigFileProgramReloadLevel.Full: + var reason = ts.Debug.assertDefined(this.pendingReloadReason); + this.pendingReloadReason = undefined; + this.projectService.reloadConfiguredProject(this, reason); + result = true; + break; + default: + result = _super.prototype.updateGraph.call(this); + } + this.projectService.sendProjectLoadingFinishEvent(this); + this.projectService.sendProjectTelemetry(this); + this.projectService.sendSurveyReady(this); + return result; + }; + /*@internal*/ + ConfiguredProject.prototype.getCachedDirectoryStructureHost = function () { + return this.directoryStructureHost; + }; + ConfiguredProject.prototype.getConfigFilePath = function () { + return server.asNormalizedPath(this.getProjectName()); + }; + ConfiguredProject.prototype.getProjectReferences = function () { + return this.projectReferences; + }; + ConfiguredProject.prototype.updateReferences = function (refs) { + this.projectReferences = refs; + }; + /*@internal*/ + ConfiguredProject.prototype.forEachResolvedProjectReference = function (cb) { + var program = this.getCurrentProgram(); + return program && program.forEachResolvedProjectReference(cb); + }; + /*@internal*/ + ConfiguredProject.prototype.enablePluginsWithOptions = function (options, pluginConfigOverrides) { + var host = this.projectService.host; + if (!host.require) { + this.projectService.logger.info("Plugins were requested but not running in environment that supports 'require'. Nothing will be loaded"); + return; + } + // Search our peer node_modules, then any globally-specified probe paths + // ../../.. to walk from X/node_modules/typescript/lib/tsserver.js to X/node_modules/ + var searchPaths = [ts.combinePaths(this.projectService.getExecutingFilePath(), "../../..")].concat(this.projectService.pluginProbeLocations); + if (this.projectService.allowLocalPluginLoads) { + var local = ts.getDirectoryPath(this.canonicalConfigFilePath); + this.projectService.logger.info("Local plugin loading enabled; adding " + local + " to search paths"); + searchPaths.unshift(local); + } + // Enable tsconfig-specified plugins + if (options.plugins) { + for (var _i = 0, _a = options.plugins; _i < _a.length; _i++) { + var pluginConfigEntry = _a[_i]; + this.enablePlugin(pluginConfigEntry, searchPaths, pluginConfigOverrides); + } + } + this.enableGlobalPlugins(options, pluginConfigOverrides); + }; + /** + * Get the errors that dont have any file name associated + */ + ConfiguredProject.prototype.getGlobalProjectErrors = function () { + return ts.filter(this.projectErrors, function (diagnostic) { return !diagnostic.file; }) || server.emptyArray; + }; + /** + * Get all the project errors + */ + ConfiguredProject.prototype.getAllProjectErrors = function () { + return this.projectErrors || server.emptyArray; + }; + ConfiguredProject.prototype.setProjectErrors = function (projectErrors) { + this.projectErrors = projectErrors; + }; + ConfiguredProject.prototype.setTypeAcquisition = function (newTypeAcquisition) { + this.typeAcquisition = this.removeLocalTypingsFromTypeAcquisition(newTypeAcquisition); + }; + ConfiguredProject.prototype.getTypeAcquisition = function () { + return this.typeAcquisition; + }; + /*@internal*/ + ConfiguredProject.prototype.watchWildcards = function (wildcardDirectories) { + var _this = this; + ts.updateWatchingWildcardDirectories(this.directoriesWatchedForWildcards || (this.directoriesWatchedForWildcards = ts.createMap()), wildcardDirectories, + // Create new directory watcher + function (directory, flags) { return _this.projectService.watchWildcardDirectory(directory, flags, _this); }); + }; + /*@internal*/ + ConfiguredProject.prototype.stopWatchingWildCards = function () { + if (this.directoriesWatchedForWildcards) { + ts.clearMap(this.directoriesWatchedForWildcards, ts.closeFileWatcherOf); + this.directoriesWatchedForWildcards = undefined; + } + }; + ConfiguredProject.prototype.close = function () { + if (this.configFileWatcher) { + this.configFileWatcher.close(); + this.configFileWatcher = undefined; + } + this.stopWatchingWildCards(); + this.projectErrors = undefined; + this.configFileSpecs = undefined; + _super.prototype.close.call(this); + }; + /* @internal */ + ConfiguredProject.prototype.addExternalProjectReference = function () { + this.externalProjectRefCount++; + }; + /* @internal */ + ConfiguredProject.prototype.deleteExternalProjectReference = function () { + this.externalProjectRefCount--; + }; + /** Returns true if the project is needed by any of the open script info/external project */ + /* @internal */ + ConfiguredProject.prototype.hasOpenRef = function () { + var _this = this; + if (!!this.externalProjectRefCount) { + return true; + } + // Closed project doesnt have any reference + if (this.isClosed()) { + return false; + } + var configFileExistenceInfo = this.projectService.getConfigFileExistenceInfo(this); + if (this.projectService.hasPendingProjectUpdate(this)) { + // If there is pending update for this project, + // we dont know if this project would be needed by any of the open files impacted by this config file + // In that case keep the project alive if there are open files impacted by this project + return !!configFileExistenceInfo.openFilesImpactedByConfigFile.size; + } + // If there is no pending update for this project, + // We know exact set of open files that get impacted by this configured project as the files in the project + // The project is referenced only if open files impacted by this project are present in this project + return ts.forEachEntry(configFileExistenceInfo.openFilesImpactedByConfigFile, function (_value, infoPath) { return _this.containsScriptInfo(_this.projectService.getScriptInfoForPath(infoPath)); }) || false; + }; + /*@internal*/ + ConfiguredProject.prototype.hasExternalProjectRef = function () { + return !!this.externalProjectRefCount; + }; + ConfiguredProject.prototype.getEffectiveTypeRoots = function () { + return ts.getEffectiveTypeRoots(this.getCompilationSettings(), this.directoryStructureHost) || []; + }; + /*@internal*/ + ConfiguredProject.prototype.updateErrorOnNoInputFiles = function (fileNameResult) { + ts.updateErrorForNoInputFiles(fileNameResult, this.getConfigFilePath(), this.configFileSpecs, this.projectErrors, this.canConfigFileJsonReportNoInputFiles); + }; + return ConfiguredProject; + }(Project)); + server.ConfiguredProject = ConfiguredProject; + /** + * Project whose configuration is handled externally, such as in a '.csproj'. + * These are created only if a host explicitly calls `openExternalProject`. + */ + var ExternalProject = /** @class */ (function (_super) { + __extends(ExternalProject, _super); + /*@internal*/ + function ExternalProject(externalProjectName, projectService, documentRegistry, compilerOptions, lastFileExceededProgramSize, compileOnSaveEnabled, projectFilePath) { + var _this = _super.call(this, externalProjectName, ProjectKind.External, projectService, documentRegistry, + /*hasExplicitListOfFiles*/ true, lastFileExceededProgramSize, compilerOptions, compileOnSaveEnabled, projectService.host, ts.getDirectoryPath(projectFilePath || ts.normalizeSlashes(externalProjectName))) || this; + _this.externalProjectName = externalProjectName; + _this.compileOnSaveEnabled = compileOnSaveEnabled; + _this.excludedFiles = []; + return _this; + } + ExternalProject.prototype.updateGraph = function () { + var result = _super.prototype.updateGraph.call(this); + this.projectService.sendProjectTelemetry(this); + this.projectService.sendSurveyReady(this); + return result; + }; + ExternalProject.prototype.getExcludedFiles = function () { + return this.excludedFiles; + }; + ExternalProject.prototype.getTypeAcquisition = function () { + return this.typeAcquisition; + }; + ExternalProject.prototype.setTypeAcquisition = function (newTypeAcquisition) { + ts.Debug.assert(!!newTypeAcquisition, "newTypeAcquisition may not be null/undefined"); + ts.Debug.assert(!!newTypeAcquisition.include, "newTypeAcquisition.include may not be null/undefined"); + ts.Debug.assert(!!newTypeAcquisition.exclude, "newTypeAcquisition.exclude may not be null/undefined"); + ts.Debug.assert(typeof newTypeAcquisition.enable === "boolean", "newTypeAcquisition.enable may not be null/undefined"); + this.typeAcquisition = this.removeLocalTypingsFromTypeAcquisition(newTypeAcquisition); + }; + return ExternalProject; + }(Project)); + server.ExternalProject = ExternalProject; + })(server = ts.server || (ts.server = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + var server; + (function (server) { + server.maxProgramSizeForNonTsFiles = 20 * 1024 * 1024; + /*@internal*/ + server.maxFileSize = 4 * 1024 * 1024; + // tslint:disable variable-name + server.ProjectsUpdatedInBackgroundEvent = "projectsUpdatedInBackground"; + server.ProjectLoadingStartEvent = "projectLoadingStart"; + server.ProjectLoadingFinishEvent = "projectLoadingFinish"; + server.SurveyReady = "surveyReady"; + server.LargeFileReferencedEvent = "largeFileReferenced"; + server.ConfigFileDiagEvent = "configFileDiag"; + server.ProjectLanguageServiceStateEvent = "projectLanguageServiceState"; + server.ProjectInfoTelemetryEvent = "projectInfo"; + server.OpenFileInfoTelemetryEvent = "openFileInfo"; + function prepareConvertersForEnumLikeCompilerOptions(commandLineOptions) { + var map = ts.createMap(); + for (var _i = 0, commandLineOptions_1 = commandLineOptions; _i < commandLineOptions_1.length; _i++) { + var option = commandLineOptions_1[_i]; + if (typeof option.type === "object") { + var optionMap = option.type; + // verify that map contains only numbers + optionMap.forEach(function (value) { + ts.Debug.assert(typeof value === "number"); + }); + map.set(option.name, optionMap); + } + } + return map; + } + var compilerOptionConverters = prepareConvertersForEnumLikeCompilerOptions(ts.optionDeclarations); + var indentStyle = ts.createMapFromTemplate({ + none: ts.IndentStyle.None, + block: ts.IndentStyle.Block, + smart: ts.IndentStyle.Smart + }); + /** + * How to understand this block: + * * The 'match' property is a regexp that matches a filename. + * * If 'match' is successful, then: + * * All files from 'exclude' are removed from the project. See below. + * * All 'types' are included in ATA + * * What the heck is 'exclude' ? + * * An array of an array of strings and numbers + * * Each array is: + * * An array of strings and numbers + * * The strings are literals + * * The numbers refer to capture group indices from the 'match' regexp + * * Remember that '1' is the first group + * * These are concatenated together to form a new regexp + * * Filenames matching these regexps are excluded from the project + * This default value is tested in tsserverProjectSystem.ts; add tests there + * if you are changing this so that you can be sure your regexp works! + */ + var defaultTypeSafeList = { + "jquery": { + // jquery files can have names like "jquery-1.10.2.min.js" (or "jquery.intellisense.js") + match: /jquery(-(\.?\d+)+)?(\.intellisense)?(\.min)?\.js$/i, + types: ["jquery"] + }, + "WinJS": { + // e.g. c:/temp/UWApp1/lib/winjs-4.0.1/js/base.js + match: /^(.*\/winjs-[.\d]+)\/js\/base\.js$/i, + exclude: [["^", 1, "/.*"]], + types: ["winjs"] // And fetch the @types package for WinJS + }, + "Kendo": { + // e.g. /Kendo3/wwwroot/lib/kendo/kendo.all.min.js + match: /^(.*\/kendo(-ui)?)\/kendo\.all(\.min)?\.js$/i, + exclude: [["^", 1, "/.*"]], + types: ["kendo-ui"] + }, + "Office Nuget": { + // e.g. /scripts/Office/1/excel-15.debug.js + match: /^(.*\/office\/1)\/excel-\d+\.debug\.js$/i, + exclude: [["^", 1, "/.*"]], + types: ["office"] // @types package to fetch instead + }, + "References": { + match: /^(.*\/_references\.js)$/i, + exclude: [["^", 1, "$"]] + } + }; + function convertFormatOptions(protocolOptions) { + if (ts.isString(protocolOptions.indentStyle)) { + protocolOptions.indentStyle = indentStyle.get(protocolOptions.indentStyle.toLowerCase()); + ts.Debug.assert(protocolOptions.indentStyle !== undefined); + } + return protocolOptions; + } + server.convertFormatOptions = convertFormatOptions; + function convertCompilerOptions(protocolOptions) { + compilerOptionConverters.forEach(function (mappedValues, id) { + var propertyValue = protocolOptions[id]; + if (ts.isString(propertyValue)) { + protocolOptions[id] = mappedValues.get(propertyValue.toLowerCase()); + } + }); + return protocolOptions; + } + server.convertCompilerOptions = convertCompilerOptions; + function tryConvertScriptKindName(scriptKindName) { + return ts.isString(scriptKindName) ? convertScriptKindName(scriptKindName) : scriptKindName; + } + server.tryConvertScriptKindName = tryConvertScriptKindName; + function convertScriptKindName(scriptKindName) { + switch (scriptKindName) { + case "JS": + return 1 /* JS */; + case "JSX": + return 2 /* JSX */; + case "TS": + return 3 /* TS */; + case "TSX": + return 4 /* TSX */; + default: + return 0 /* Unknown */; + } + } + server.convertScriptKindName = convertScriptKindName; + /*@internal*/ + function convertUserPreferences(preferences) { + var lazyConfiguredProjectsFromExternalProject = preferences.lazyConfiguredProjectsFromExternalProject, userPreferences = __rest(preferences, ["lazyConfiguredProjectsFromExternalProject"]); + return userPreferences; + } + server.convertUserPreferences = convertUserPreferences; + var fileNamePropertyReader = { + getFileName: function (x) { return x; }, + getScriptKind: function (fileName, extraFileExtensions) { + var result; + if (extraFileExtensions) { + var fileExtension_1 = ts.getAnyExtensionFromPath(fileName); + if (fileExtension_1) { + ts.some(extraFileExtensions, function (info) { + if (info.extension === fileExtension_1) { + result = info.scriptKind; + return true; + } + return false; + }); + } + } + return result; // TODO: GH#18217 + }, + hasMixedContent: function (fileName, extraFileExtensions) { return ts.some(extraFileExtensions, function (ext) { return ext.isMixedContent && ts.fileExtensionIs(fileName, ext.extension); }); }, + }; + var externalFilePropertyReader = { + getFileName: function (x) { return x.fileName; }, + getScriptKind: function (x) { return tryConvertScriptKindName(x.scriptKind); }, + hasMixedContent: function (x) { return !!x.hasMixedContent; }, + }; + function findProjectByName(projectName, projects) { + for (var _i = 0, projects_1 = projects; _i < projects_1.length; _i++) { + var proj = projects_1[_i]; + if (proj.getProjectName() === projectName) { + return proj; + } + } + } + /* @internal */ + var WatchType; + (function (WatchType) { + WatchType["ConfigFilePath"] = "Config file for the program"; + WatchType["MissingFilePath"] = "Missing file from program"; + WatchType["WildcardDirectories"] = "Wild card directory"; + WatchType["ClosedScriptInfo"] = "Closed Script info"; + WatchType["ConfigFileForInferredRoot"] = "Config file for the inferred project root"; + WatchType["FailedLookupLocation"] = "Directory of Failed lookup locations in module resolution"; + WatchType["TypeRoots"] = "Type root directory"; + WatchType["NodeModulesForClosedScriptInfo"] = "node_modules for closed script infos in them"; + })(WatchType = server.WatchType || (server.WatchType = {})); + var ConfigFileWatcherStatus; + (function (ConfigFileWatcherStatus) { + ConfigFileWatcherStatus["ReloadingFiles"] = "Reloading configured projects for files"; + ConfigFileWatcherStatus["ReloadingInferredRootFiles"] = "Reloading configured projects for only inferred root files"; + ConfigFileWatcherStatus["UpdatedCallback"] = "Updated the callback"; + ConfigFileWatcherStatus["OpenFilesImpactedByConfigFileAdd"] = "File added to open files impacted by this config file"; + ConfigFileWatcherStatus["OpenFilesImpactedByConfigFileRemove"] = "File removed from open files impacted by this config file"; + ConfigFileWatcherStatus["RootOfInferredProjectTrue"] = "Open file was set as Inferred root"; + ConfigFileWatcherStatus["RootOfInferredProjectFalse"] = "Open file was set as not inferred root"; + })(ConfigFileWatcherStatus || (ConfigFileWatcherStatus = {})); + function isOpenScriptInfo(infoOrFileName) { + return !!infoOrFileName.containingProjects; + } + function getDetailWatchInfo(watchType, project) { + return "Project: " + (project ? project.getProjectName() : "") + " WatchType: " + watchType; + } + function isScriptInfoWatchedFromNodeModules(info) { + return !info.isScriptOpen() && info.mTime !== undefined; + } + /*@internal*/ + function updateProjectIfDirty(project) { + return project.dirty && project.updateGraph(); + } + server.updateProjectIfDirty = updateProjectIfDirty; + function setProjectOptionsUsed(project) { + if (project.projectKind === server.ProjectKind.Configured) { + project.projectOptions = true; + } + } + var ProjectService = /** @class */ (function () { + function ProjectService(opts) { + var _this = this; + /** + * Container of all known scripts + */ + this.filenameToScriptInfo = ts.createMap(); + this.scriptInfoInNodeModulesWatchers = ts.createMap(); + /** + * Contains all the deleted script info's version information so that + * it does not reset when creating script info again + * (and could have potentially collided with version where contents mismatch) + */ + this.filenameToScriptInfoVersion = ts.createMap(); + // Set of all '.js' files ever opened. + this.allJsFilesForOpenFileTelemetry = ts.createMap(); + /** + * maps external project file name to list of config files that were the part of this project + */ + this.externalProjectToConfiguredProjectMap = ts.createMap(); + /** + * external projects (configuration and list of root files is not controlled by tsserver) + */ + this.externalProjects = []; + /** + * projects built from openFileRoots + */ + this.inferredProjects = []; + /** + * projects specified by a tsconfig.json file + */ + this.configuredProjects = ts.createMap(); + /** + * Open files: with value being project root path, and key being Path of the file that is open + */ + this.openFiles = ts.createMap(); + /** + * Map of open files that are opened without complete path but have projectRoot as current directory + */ + this.openFilesWithNonRootedDiskPath = ts.createMap(); + this.compilerOptionsForInferredProjectsPerProjectRoot = ts.createMap(); + /** + * Project size for configured or external projects + */ + this.projectToSizeMap = ts.createMap(); + /** + * This is a map of config file paths existance that doesnt need query to disk + * - The entry can be present because there is inferred project that needs to watch addition of config file to directory + * In this case the exists could be true/false based on config file is present or not + * - Or it is present if we have configured project open with config file at that location + * In this case the exists property is always true + */ + this.configFileExistenceInfoCache = ts.createMap(); + this.safelist = defaultTypeSafeList; + this.legacySafelist = ts.createMap(); + this.pendingProjectUpdates = ts.createMap(); + /* @internal */ + this.pendingEnsureProjectForOpenFiles = false; + /** Tracks projects that we have already sent telemetry for. */ + this.seenProjects = ts.createMap(); + /** Tracks projects that we have already sent survey events for. */ + this.seenSurveyProjects = ts.createMap(); + this.host = opts.host; + this.logger = opts.logger; + this.cancellationToken = opts.cancellationToken; + this.useSingleInferredProject = opts.useSingleInferredProject; + this.useInferredProjectPerProjectRoot = opts.useInferredProjectPerProjectRoot; + this.typingsInstaller = opts.typingsInstaller || server.nullTypingsInstaller; + this.throttleWaitMilliseconds = opts.throttleWaitMilliseconds; + this.eventHandler = opts.eventHandler; + this.suppressDiagnosticEvents = opts.suppressDiagnosticEvents; + this.globalPlugins = opts.globalPlugins || server.emptyArray; + this.pluginProbeLocations = opts.pluginProbeLocations || server.emptyArray; + this.allowLocalPluginLoads = !!opts.allowLocalPluginLoads; + this.typesMapLocation = (opts.typesMapLocation === undefined) ? ts.combinePaths(ts.getDirectoryPath(this.getExecutingFilePath()), "typesMap.json") : opts.typesMapLocation; + this.syntaxOnly = opts.syntaxOnly; + ts.Debug.assert(!!this.host.createHash, "'ServerHost.createHash' is required for ProjectService"); + if (this.host.realpath) { + this.realpathToScriptInfos = ts.createMultiMap(); + } + this.currentDirectory = server.toNormalizedPath(this.host.getCurrentDirectory()); + this.toCanonicalFileName = ts.createGetCanonicalFileName(this.host.useCaseSensitiveFileNames); + this.globalCacheLocationDirectoryPath = this.typingsInstaller.globalTypingsCacheLocation + ? ts.ensureTrailingDirectorySeparator(this.toPath(this.typingsInstaller.globalTypingsCacheLocation)) + : undefined; + this.throttledOperations = new server.ThrottledOperations(this.host, this.logger); + if (this.typesMapLocation) { + this.loadTypesMap(); + } + else { + this.logger.info("No types map provided; using the default"); + } + this.typingsInstaller.attach(this); + this.typingsCache = new server.TypingsCache(this.typingsInstaller); + this.hostConfiguration = { + formatCodeOptions: ts.getDefaultFormatCodeSettings(this.host.newLine), + preferences: ts.emptyOptions, + hostInfo: "Unknown host", + extraFileExtensions: [] + }; + this.documentRegistry = ts.createDocumentRegistryInternal(this.host.useCaseSensitiveFileNames, this.currentDirectory, this); + var watchLogLevel = this.logger.hasLevel(server.LogLevel.verbose) ? ts.WatchLogLevel.Verbose : + this.logger.loggingEnabled() ? ts.WatchLogLevel.TriggerOnly : ts.WatchLogLevel.None; + var log = watchLogLevel !== ts.WatchLogLevel.None ? (function (s) { return _this.logger.info(s); }) : ts.noop; + this.watchFactory = ts.getWatchFactory(watchLogLevel, log, getDetailWatchInfo); + } + ProjectService.prototype.toPath = function (fileName) { + return ts.toPath(fileName, this.currentDirectory, this.toCanonicalFileName); + }; + /*@internal*/ + ProjectService.prototype.getExecutingFilePath = function () { + return this.getNormalizedAbsolutePath(this.host.getExecutingFilePath()); + }; + /*@internal*/ + ProjectService.prototype.getNormalizedAbsolutePath = function (fileName) { + return ts.getNormalizedAbsolutePath(fileName, this.host.getCurrentDirectory()); + }; + /*@internal*/ + ProjectService.prototype.setDocument = function (key, path, sourceFile) { + var info = ts.Debug.assertDefined(this.getScriptInfoForPath(path)); + info.cacheSourceFile = { key: key, sourceFile: sourceFile }; + }; + /*@internal*/ + ProjectService.prototype.getDocument = function (key, path) { + var info = this.getScriptInfoForPath(path); + return info && info.cacheSourceFile && info.cacheSourceFile.key === key ? info.cacheSourceFile.sourceFile : undefined; + }; + /* @internal */ + ProjectService.prototype.ensureInferredProjectsUpToDate_TestOnly = function () { + this.ensureProjectStructuresUptoDate(); + }; + /* @internal */ + ProjectService.prototype.getCompilerOptionsForInferredProjects = function () { + return this.compilerOptionsForInferredProjects; + }; + /* @internal */ + ProjectService.prototype.onUpdateLanguageServiceStateForProject = function (project, languageServiceEnabled) { + if (!this.eventHandler) { + return; + } + var event = { + eventName: server.ProjectLanguageServiceStateEvent, + data: { project: project, languageServiceEnabled: languageServiceEnabled } + }; + this.eventHandler(event); + }; + ProjectService.prototype.loadTypesMap = function () { + try { + var fileContent = this.host.readFile(this.typesMapLocation); // TODO: GH#18217 + if (fileContent === undefined) { + this.logger.info("Provided types map file \"" + this.typesMapLocation + "\" doesn't exist"); + return; + } + var raw = JSON.parse(fileContent); + // Parse the regexps + for (var _i = 0, _a = Object.keys(raw.typesMap); _i < _a.length; _i++) { + var k = _a[_i]; + raw.typesMap[k].match = new RegExp(raw.typesMap[k].match, "i"); + } + // raw is now fixed and ready + this.safelist = raw.typesMap; + for (var key in raw.simpleMap) { + if (raw.simpleMap.hasOwnProperty(key)) { + this.legacySafelist.set(key, raw.simpleMap[key].toLowerCase()); + } + } + } + catch (e) { + this.logger.info("Error loading types map: " + e); + this.safelist = defaultTypeSafeList; + this.legacySafelist.clear(); + } + }; + ProjectService.prototype.updateTypingsForProject = function (response) { + var project = this.findProject(response.projectName); + if (!project) { + return; + } + switch (response.kind) { + case server.ActionSet: + // Update the typing files and update the project + project.updateTypingFiles(this.typingsCache.updateTypingsForProject(response.projectName, response.compilerOptions, response.typeAcquisition, response.unresolvedImports, response.typings)); + break; + case server.ActionInvalidate: + // Do not clear resolution cache, there was changes detected in typings, so enque typing request and let it get us correct results + this.typingsCache.enqueueInstallTypingsForProject(project, project.lastCachedUnresolvedImportsList, /*forceRefresh*/ true); + return; + } + this.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles(project); + }; + ProjectService.prototype.delayEnsureProjectForOpenFiles = function () { + var _this = this; + this.pendingEnsureProjectForOpenFiles = true; + this.throttledOperations.schedule("*ensureProjectForOpenFiles*", /*delay*/ 250, function () { + if (_this.pendingProjectUpdates.size !== 0) { + _this.delayEnsureProjectForOpenFiles(); + } + else { + if (_this.pendingEnsureProjectForOpenFiles) { + _this.ensureProjectForOpenFiles(); + // Send the event to notify that there were background project updates + // send current list of open files + _this.sendProjectsUpdatedInBackgroundEvent(); + } + } + }); + }; + ProjectService.prototype.delayUpdateProjectGraph = function (project) { + var _this = this; + project.markAsDirty(); + var projectName = project.getProjectName(); + this.pendingProjectUpdates.set(projectName, project); + this.throttledOperations.schedule(projectName, /*delay*/ 250, function () { + if (_this.pendingProjectUpdates.delete(projectName)) { + updateProjectIfDirty(project); + } + }); + }; + /*@internal*/ + ProjectService.prototype.hasPendingProjectUpdate = function (project) { + return this.pendingProjectUpdates.has(project.getProjectName()); + }; + /* @internal */ + ProjectService.prototype.sendProjectsUpdatedInBackgroundEvent = function () { + var _this = this; + if (!this.eventHandler) { + return; + } + var event = { + eventName: server.ProjectsUpdatedInBackgroundEvent, + data: { + openFiles: ts.arrayFrom(this.openFiles.keys(), function (path) { return _this.getScriptInfoForPath(path).fileName; }) + } + }; + this.eventHandler(event); + }; + /* @internal */ + ProjectService.prototype.sendSurveyReadyEvent = function (surveyId) { + if (!this.eventHandler) { + return; + } + this.eventHandler({ eventName: server.SurveyReady, data: { surveyId: surveyId } }); + }; + /* @internal */ + ProjectService.prototype.sendLargeFileReferencedEvent = function (file, fileSize) { + if (!this.eventHandler) { + return; + } + var event = { + eventName: server.LargeFileReferencedEvent, + data: { file: file, fileSize: fileSize, maxFileSize: server.maxFileSize } + }; + this.eventHandler(event); + }; + /* @internal */ + ProjectService.prototype.sendProjectLoadingStartEvent = function (project, reason) { + if (!this.eventHandler) { + return; + } + project.sendLoadingProjectFinish = true; + var event = { + eventName: server.ProjectLoadingStartEvent, + data: { project: project, reason: reason } + }; + this.eventHandler(event); + }; + /* @internal */ + ProjectService.prototype.sendProjectLoadingFinishEvent = function (project) { + if (!this.eventHandler || !project.sendLoadingProjectFinish) { + return; + } + project.sendLoadingProjectFinish = false; + var event = { + eventName: server.ProjectLoadingFinishEvent, + data: { project: project } + }; + this.eventHandler(event); + }; + /* @internal */ + ProjectService.prototype.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles = function (project) { + this.delayUpdateProjectGraph(project); + this.delayEnsureProjectForOpenFiles(); + }; + ProjectService.prototype.delayUpdateProjectGraphs = function (projects) { + if (projects.length) { + for (var _i = 0, projects_2 = projects; _i < projects_2.length; _i++) { + var project = projects_2[_i]; + this.delayUpdateProjectGraph(project); + } + this.delayEnsureProjectForOpenFiles(); + } + }; + ProjectService.prototype.setCompilerOptionsForInferredProjects = function (projectCompilerOptions, projectRootPath) { + ts.Debug.assert(projectRootPath === undefined || this.useInferredProjectPerProjectRoot, "Setting compiler options per project root path is only supported when useInferredProjectPerProjectRoot is enabled"); + var compilerOptions = convertCompilerOptions(projectCompilerOptions); + // always set 'allowNonTsExtensions' for inferred projects since user cannot configure it from the outside + // previously we did not expose a way for user to change these settings and this option was enabled by default + compilerOptions.allowNonTsExtensions = true; + var canonicalProjectRootPath = projectRootPath && this.toCanonicalFileName(projectRootPath); + if (canonicalProjectRootPath) { + this.compilerOptionsForInferredProjectsPerProjectRoot.set(canonicalProjectRootPath, compilerOptions); + } + else { + this.compilerOptionsForInferredProjects = compilerOptions; + } + for (var _i = 0, _a = this.inferredProjects; _i < _a.length; _i++) { + var project = _a[_i]; + // Only update compiler options in the following cases: + // - Inferred projects without a projectRootPath, if the new options do not apply to + // a workspace root + // - Inferred projects with a projectRootPath, if the new options do not apply to a + // workspace root and there is no more specific set of options for that project's + // root path + // - Inferred projects with a projectRootPath, if the new options apply to that + // project root path. + if (canonicalProjectRootPath ? + project.projectRootPath === canonicalProjectRootPath : + !project.projectRootPath || !this.compilerOptionsForInferredProjectsPerProjectRoot.has(project.projectRootPath)) { + project.setCompilerOptions(compilerOptions); + project.compileOnSaveEnabled = compilerOptions.compileOnSave; + project.markAsDirty(); + this.delayUpdateProjectGraph(project); + } + } + this.delayEnsureProjectForOpenFiles(); + }; + ProjectService.prototype.findProject = function (projectName) { + if (projectName === undefined) { + return undefined; + } + if (server.isInferredProjectName(projectName)) { + return findProjectByName(projectName, this.inferredProjects); + } + return this.findExternalProjectByProjectName(projectName) || this.findConfiguredProjectByProjectName(server.toNormalizedPath(projectName)); + }; + /* @internal */ + ProjectService.prototype.forEachProject = function (cb) { + this.externalProjects.forEach(cb); + this.configuredProjects.forEach(cb); + this.inferredProjects.forEach(cb); + }; + /* @internal */ + ProjectService.prototype.forEachEnabledProject = function (cb) { + this.forEachProject(function (project) { + if (!project.isOrphan() && project.languageServiceEnabled) { + cb(project); + } + }); + }; + ProjectService.prototype.getDefaultProjectForFile = function (fileName, ensureProject) { + return ensureProject ? this.ensureDefaultProjectForFile(fileName) : this.tryGetDefaultProjectForFile(fileName); + }; + /* @internal */ + ProjectService.prototype.tryGetDefaultProjectForFile = function (fileName) { + var scriptInfo = this.getScriptInfoForNormalizedPath(fileName); + return scriptInfo && !scriptInfo.isOrphan() ? scriptInfo.getDefaultProject() : undefined; + }; + /* @internal */ + ProjectService.prototype.ensureDefaultProjectForFile = function (fileName) { + return this.tryGetDefaultProjectForFile(fileName) || this.doEnsureDefaultProjectForFile(fileName); + }; + ProjectService.prototype.doEnsureDefaultProjectForFile = function (fileName) { + this.ensureProjectStructuresUptoDate(); + var scriptInfo = this.getScriptInfoForNormalizedPath(fileName); + return scriptInfo ? scriptInfo.getDefaultProject() : (this.logErrorForScriptInfoNotFound(fileName), server.Errors.ThrowNoProject()); + }; + ProjectService.prototype.getScriptInfoEnsuringProjectsUptoDate = function (uncheckedFileName) { + this.ensureProjectStructuresUptoDate(); + return this.getScriptInfo(uncheckedFileName); + }; + /** + * Ensures the project structures are upto date + * This means, + * - we go through all the projects and update them if they are dirty + * - if updates reflect some change in structure or there was pending request to ensure projects for open files + * ensure that each open script info has project + */ + ProjectService.prototype.ensureProjectStructuresUptoDate = function () { + var hasChanges = this.pendingEnsureProjectForOpenFiles; + this.pendingProjectUpdates.clear(); + var updateGraph = function (project) { + hasChanges = updateProjectIfDirty(project) || hasChanges; + }; + this.externalProjects.forEach(updateGraph); + this.configuredProjects.forEach(updateGraph); + this.inferredProjects.forEach(updateGraph); + if (hasChanges) { + this.ensureProjectForOpenFiles(); + } + }; + ProjectService.prototype.getFormatCodeOptions = function (file) { + var info = this.getScriptInfoForNormalizedPath(file); + return info && info.getFormatCodeSettings() || this.hostConfiguration.formatCodeOptions; + }; + ProjectService.prototype.getPreferences = function (file) { + var info = this.getScriptInfoForNormalizedPath(file); + return info && info.getPreferences() || this.hostConfiguration.preferences; + }; + ProjectService.prototype.getHostFormatCodeOptions = function () { + return this.hostConfiguration.formatCodeOptions; + }; + ProjectService.prototype.getHostPreferences = function () { + return this.hostConfiguration.preferences; + }; + ProjectService.prototype.onSourceFileChanged = function (fileName, eventKind, path) { + var info = this.getScriptInfoForPath(path); + if (!info) { + this.logger.msg("Error: got watch notification for unknown file: " + fileName); + } + else { + if (info.containingProjects) { + info.containingProjects.forEach(function (project) { return project.resolutionCache.removeResolutionsFromProjectReferenceRedirects(info.path); }); + } + if (eventKind === ts.FileWatcherEventKind.Deleted) { + // File was deleted + this.handleDeletedFile(info); + } + else if (!info.isScriptOpen()) { + // file has been changed which might affect the set of referenced files in projects that include + // this file and set of inferred projects + info.delayReloadNonMixedContentFile(); + this.delayUpdateProjectGraphs(info.containingProjects); + } + } + }; + ProjectService.prototype.handleDeletedFile = function (info) { + this.stopWatchingScriptInfo(info); + if (!info.isScriptOpen()) { + this.deleteScriptInfo(info); + // capture list of projects since detachAllProjects will wipe out original list + var containingProjects = info.containingProjects.slice(); + info.detachAllProjects(); + // update projects to make sure that set of referenced files is correct + this.delayUpdateProjectGraphs(containingProjects); + } + }; + /** + * This is to watch whenever files are added or removed to the wildcard directories + */ + /*@internal*/ + ProjectService.prototype.watchWildcardDirectory = function (directory, flags, project) { + var _this = this; + return this.watchFactory.watchDirectory(this.host, directory, function (fileOrDirectory) { + var fileOrDirectoryPath = _this.toPath(fileOrDirectory); + project.getCachedDirectoryStructureHost().addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); + if (ts.isPathInNodeModulesStartingWithDot(fileOrDirectoryPath)) + return; + var configFilename = project.getConfigFilePath(); + // If the the added or created file or directory is not supported file name, ignore the file + // But when watched directory is added/removed, we need to reload the file list + if (fileOrDirectoryPath !== directory && ts.hasExtension(fileOrDirectoryPath) && !ts.isSupportedSourceFileName(fileOrDirectory, project.getCompilationSettings(), _this.hostConfiguration.extraFileExtensions)) { + _this.logger.info("Project: " + configFilename + " Detected file add/remove of non supported extension: " + fileOrDirectory); + return; + } + // Reload is pending, do the reload + if (project.pendingReload !== ts.ConfigFileProgramReloadLevel.Full) { + project.pendingReload = ts.ConfigFileProgramReloadLevel.Partial; + _this.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles(project); + } + }, flags, "Wild card directory" /* WildcardDirectories */, project); + }; + /** Gets the config file existence info for the configured project */ + /*@internal*/ + ProjectService.prototype.getConfigFileExistenceInfo = function (project) { + return this.configFileExistenceInfoCache.get(project.canonicalConfigFilePath); + }; + ProjectService.prototype.onConfigChangedForConfiguredProject = function (project, eventKind) { + var configFileExistenceInfo = this.getConfigFileExistenceInfo(project); + if (eventKind === ts.FileWatcherEventKind.Deleted) { + // Update the cached status + // We arent updating or removing the cached config file presence info as that will be taken care of by + // setConfigFilePresenceByClosedConfigFile when the project is closed (depending on tracking open files) + configFileExistenceInfo.exists = false; + this.removeProject(project); + // Reload the configured projects for the open files in the map as they are affected by this config file + // Since the configured project was deleted, we want to reload projects for all the open files including files + // that are not root of the inferred project + this.logConfigFileWatchUpdate(project.getConfigFilePath(), project.canonicalConfigFilePath, configFileExistenceInfo, "Reloading configured projects for files" /* ReloadingFiles */); + this.delayReloadConfiguredProjectForFiles(configFileExistenceInfo, /*ignoreIfNotInferredProjectRoot*/ false); + } + else { + this.logConfigFileWatchUpdate(project.getConfigFilePath(), project.canonicalConfigFilePath, configFileExistenceInfo, "Reloading configured projects for only inferred root files" /* ReloadingInferredRootFiles */); + project.pendingReload = ts.ConfigFileProgramReloadLevel.Full; + project.pendingReloadReason = "Change in config file detected"; + this.delayUpdateProjectGraph(project); + // As we scheduled the update on configured project graph, + // we would need to schedule the project reload for only the root of inferred projects + this.delayReloadConfiguredProjectForFiles(configFileExistenceInfo, /*ignoreIfNotInferredProjectRoot*/ true); + } + }; + /** + * This is the callback function for the config file add/remove/change at any location + * that matters to open script info but doesnt have configured project open + * for the config file + */ + ProjectService.prototype.onConfigFileChangeForOpenScriptInfo = function (configFileName, eventKind) { + // This callback is called only if we dont have config file project for this config file + var canonicalConfigPath = server.normalizedPathToPath(configFileName, this.currentDirectory, this.toCanonicalFileName); + var configFileExistenceInfo = this.configFileExistenceInfoCache.get(canonicalConfigPath); + configFileExistenceInfo.exists = (eventKind !== ts.FileWatcherEventKind.Deleted); + this.logConfigFileWatchUpdate(configFileName, canonicalConfigPath, configFileExistenceInfo, "Reloading configured projects for files" /* ReloadingFiles */); + // Because there is no configured project open for the config file, the tracking open files map + // will only have open files that need the re-detection of the project and hence + // reload projects for all the tracking open files in the map + this.delayReloadConfiguredProjectForFiles(configFileExistenceInfo, /*ignoreIfNotInferredProjectRoot*/ false); + }; + ProjectService.prototype.removeProject = function (project) { + var _this = this; + this.logger.info("`remove Project::"); + project.print(); + project.close(); + if (ts.Debug.shouldAssert(1 /* Normal */)) { + this.filenameToScriptInfo.forEach(function (info) { return ts.Debug.assert(!info.isAttached(project), "Found script Info still attached to project", function () { return project.projectName + ": ScriptInfos still attached: " + JSON.stringify(ts.mapDefined(ts.arrayFrom(_this.filenameToScriptInfo.values()), function (info) { return info.isAttached(project) ? info : undefined; })); }); }); + } + // Remove the project from pending project updates + this.pendingProjectUpdates.delete(project.getProjectName()); + switch (project.projectKind) { + case server.ProjectKind.External: + ts.unorderedRemoveItem(this.externalProjects, project); + this.projectToSizeMap.delete(project.getProjectName()); + break; + case server.ProjectKind.Configured: + this.configuredProjects.delete(project.canonicalConfigFilePath); + this.projectToSizeMap.delete(project.canonicalConfigFilePath); + this.setConfigFileExistenceInfoByClosedConfiguredProject(project); + break; + case server.ProjectKind.Inferred: + ts.unorderedRemoveItem(this.inferredProjects, project); + break; + } + }; + /*@internal*/ + ProjectService.prototype.assignOrphanScriptInfoToInferredProject = function (info, projectRootPath) { + ts.Debug.assert(info.isOrphan()); + var project = this.getOrCreateInferredProjectForProjectRootPathIfEnabled(info, projectRootPath) || + this.getOrCreateSingleInferredProjectIfEnabled() || + this.getOrCreateSingleInferredWithoutProjectRoot(info.isDynamic ? this.currentDirectory : ts.getDirectoryPath(info.path)); + project.addRoot(info); + if (info.containingProjects[0] !== project) { + // Ensure this is first project, we could be in this scenario because info could be part of orphan project + info.detachFromProject(project); + info.containingProjects.unshift(project); + } + project.updateGraph(); + if (!this.useSingleInferredProject && !project.projectRootPath) { + var _loop_26 = function (inferredProject) { + if (inferredProject === project || inferredProject.isOrphan()) { + return "continue"; + } + // Remove the inferred project if the root of it is now part of newly created inferred project + // e.g through references + // Which means if any root of inferred project is part of more than 1 project can be removed + // This logic is same as iterating over all open files and calling + // this.removeRootOfInferredProjectIfNowPartOfOtherProject(f); + // Since this is also called from refreshInferredProject and closeOpen file + // to update inferred projects of the open file, this iteration might be faster + // instead of scanning all open files + var roots = inferredProject.getRootScriptInfos(); + ts.Debug.assert(roots.length === 1 || !!inferredProject.projectRootPath); + if (roots.length === 1 && ts.forEach(roots[0].containingProjects, function (p) { return p !== roots[0].containingProjects[0] && !p.isOrphan(); })) { + inferredProject.removeFile(roots[0], /*fileExists*/ true, /*detachFromProject*/ true); + } + }; + // Note that we need to create a copy of the array since the list of project can change + for (var _i = 0, _a = this.inferredProjects; _i < _a.length; _i++) { + var inferredProject = _a[_i]; + _loop_26(inferredProject); + } + } + return project; + }; + /** + * Remove this file from the set of open, non-configured files. + * @param info The file that has been closed or newly configured + */ + ProjectService.prototype.closeOpenFile = function (info) { + var _this = this; + // Closing file should trigger re-reading the file content from disk. This is + // because the user may chose to discard the buffer content before saving + // to the disk, and the server's version of the file can be out of sync. + var fileExists = this.host.fileExists(info.fileName); + info.close(fileExists); + this.stopWatchingConfigFilesForClosedScriptInfo(info); + var canonicalFileName = this.toCanonicalFileName(info.fileName); + if (this.openFilesWithNonRootedDiskPath.get(canonicalFileName) === info) { + this.openFilesWithNonRootedDiskPath.delete(canonicalFileName); + } + // collect all projects that should be removed + var ensureProjectsForOpenFiles = false; + for (var _i = 0, _a = info.containingProjects; _i < _a.length; _i++) { + var p = _a[_i]; + if (p.projectKind === server.ProjectKind.Configured) { + if (info.hasMixedContent) { + info.registerFileUpdate(); + } + // Do not remove the project so that we can reuse this project + // if it would need to be re-created with next file open + } + else if (p.projectKind === server.ProjectKind.Inferred && p.isRoot(info)) { + // If this was the last open root file of inferred project + if (p.isProjectWithSingleRoot()) { + ensureProjectsForOpenFiles = true; + } + p.removeFile(info, fileExists, /*detachFromProject*/ true); + // Do not remove the project even if this was last root of the inferred project + // so that we can reuse this project, if it would need to be re-created with next file open + } + if (!p.languageServiceEnabled) { + // if project language service is disabled then we create a program only for open files. + // this means that project should be marked as dirty to force rebuilding of the program + // on the next request + p.markAsDirty(); + } + } + this.openFiles.delete(info.path); + if (ensureProjectsForOpenFiles) { + // collect orphaned files and assign them to inferred project just like we treat open of a file + this.openFiles.forEach(function (projectRootPath, path) { + var info = _this.getScriptInfoForPath(path); + // collect all orphaned script infos from open files + if (info.isOrphan()) { + _this.assignOrphanScriptInfoToInferredProject(info, projectRootPath); + } + }); + } + // Cleanup script infos that arent part of any project (eg. those could be closed script infos not referenced by any project) + // is postponed to next file open so that if file from same project is opened, + // we wont end up creating same script infos + // If the current info is being just closed - add the watcher file to track changes + // But if file was deleted, handle that part + if (fileExists) { + this.watchClosedScriptInfo(info); + } + else { + this.handleDeletedFile(info); + } + }; + ProjectService.prototype.deleteScriptInfo = function (info) { + this.filenameToScriptInfo.delete(info.path); + this.filenameToScriptInfoVersion.set(info.path, info.getVersion()); + var realpath = info.getRealpathIfDifferent(); + if (realpath) { + this.realpathToScriptInfos.remove(realpath, info); // TODO: GH#18217 + } + }; + ProjectService.prototype.configFileExists = function (configFileName, canonicalConfigFilePath, info) { + var configFileExistenceInfo = this.configFileExistenceInfoCache.get(canonicalConfigFilePath); + if (configFileExistenceInfo) { + // By default the info would get impacted by presence of config file since its in the detection path + // Only adding the info as a root to inferred project will need the existence to be watched by file watcher + if (isOpenScriptInfo(info) && !configFileExistenceInfo.openFilesImpactedByConfigFile.has(info.path)) { + configFileExistenceInfo.openFilesImpactedByConfigFile.set(info.path, false); + this.logConfigFileWatchUpdate(configFileName, canonicalConfigFilePath, configFileExistenceInfo, "File added to open files impacted by this config file" /* OpenFilesImpactedByConfigFileAdd */); + } + return configFileExistenceInfo.exists; + } + // Theoretically we should be adding watch for the directory here itself. + // In practice there will be very few scenarios where the config file gets added + // somewhere inside the another config file directory. + // And technically we could handle that case in configFile's directory watcher in some cases + // But given that its a rare scenario it seems like too much overhead. (we werent watching those directories earlier either) + // So what we are now watching is: configFile if the configured project corresponding to it is open + // Or the whole chain of config files for the roots of the inferred projects + // Cache the host value of file exists and add the info to map of open files impacted by this config file + var exists = this.host.fileExists(configFileName); + var openFilesImpactedByConfigFile = ts.createMap(); + if (isOpenScriptInfo(info)) { + openFilesImpactedByConfigFile.set(info.path, false); + } + configFileExistenceInfo = { exists: exists, openFilesImpactedByConfigFile: openFilesImpactedByConfigFile }; + this.configFileExistenceInfoCache.set(canonicalConfigFilePath, configFileExistenceInfo); + this.logConfigFileWatchUpdate(configFileName, canonicalConfigFilePath, configFileExistenceInfo, "File added to open files impacted by this config file" /* OpenFilesImpactedByConfigFileAdd */); + return exists; + }; + ProjectService.prototype.setConfigFileExistenceByNewConfiguredProject = function (project) { + var configFileExistenceInfo = this.getConfigFileExistenceInfo(project); + if (configFileExistenceInfo) { + ts.Debug.assert(configFileExistenceInfo.exists); + // close existing watcher + if (configFileExistenceInfo.configFileWatcherForRootOfInferredProject) { + var configFileName = project.getConfigFilePath(); + configFileExistenceInfo.configFileWatcherForRootOfInferredProject.close(); + configFileExistenceInfo.configFileWatcherForRootOfInferredProject = undefined; + this.logConfigFileWatchUpdate(configFileName, project.canonicalConfigFilePath, configFileExistenceInfo, "Updated the callback" /* UpdatedCallback */); + } + } + else { + // We could be in this scenario if project is the configured project tracked by external project + // Since that route doesnt check if the config file is present or not + this.configFileExistenceInfoCache.set(project.canonicalConfigFilePath, { + exists: true, + openFilesImpactedByConfigFile: ts.createMap() + }); + } + }; + /** + * Returns true if the configFileExistenceInfo is needed/impacted by open files that are root of inferred project + */ + ProjectService.prototype.configFileExistenceImpactsRootOfInferredProject = function (configFileExistenceInfo) { + return ts.forEachEntry(configFileExistenceInfo.openFilesImpactedByConfigFile, function (isRootOfInferredProject) { return isRootOfInferredProject; }); + }; + ProjectService.prototype.setConfigFileExistenceInfoByClosedConfiguredProject = function (closedProject) { + var configFileExistenceInfo = this.getConfigFileExistenceInfo(closedProject); + ts.Debug.assert(!!configFileExistenceInfo); + if (configFileExistenceInfo.openFilesImpactedByConfigFile.size) { + var configFileName = closedProject.getConfigFilePath(); + // If there are open files that are impacted by this config file existence + // but none of them are root of inferred project, the config file watcher will be + // created when any of the script infos are added as root of inferred project + if (this.configFileExistenceImpactsRootOfInferredProject(configFileExistenceInfo)) { + ts.Debug.assert(!configFileExistenceInfo.configFileWatcherForRootOfInferredProject); + this.createConfigFileWatcherOfConfigFileExistence(configFileName, closedProject.canonicalConfigFilePath, configFileExistenceInfo); + } + } + else { + // There is not a single file open thats tracking the status of this config file. Remove from cache + this.configFileExistenceInfoCache.delete(closedProject.canonicalConfigFilePath); + } + }; + ProjectService.prototype.logConfigFileWatchUpdate = function (configFileName, canonicalConfigFilePath, configFileExistenceInfo, status) { + var _this = this; + if (!this.logger.hasLevel(server.LogLevel.verbose)) { + return; + } + var inferredRoots = []; + var otherFiles = []; + configFileExistenceInfo.openFilesImpactedByConfigFile.forEach(function (isRootOfInferredProject, key) { + var info = _this.getScriptInfoForPath(key); + (isRootOfInferredProject ? inferredRoots : otherFiles).push(info.fileName); + }); + var watches = []; + if (configFileExistenceInfo.configFileWatcherForRootOfInferredProject) { + watches.push("Config file for the inferred project root" /* ConfigFileForInferredRoot */); + } + if (this.configuredProjects.has(canonicalConfigFilePath)) { + watches.push("Config file for the program" /* ConfigFilePath */); + } + this.logger.info("ConfigFilePresence:: Current Watches: " + watches + ":: File: " + configFileName + " Currently impacted open files: RootsOfInferredProjects: " + inferredRoots + " OtherOpenFiles: " + otherFiles + " Status: " + status); + }; + /** + * Create the watcher for the configFileExistenceInfo + */ + ProjectService.prototype.createConfigFileWatcherOfConfigFileExistence = function (configFileName, canonicalConfigFilePath, configFileExistenceInfo) { + var _this = this; + configFileExistenceInfo.configFileWatcherForRootOfInferredProject = this.watchFactory.watchFile(this.host, configFileName, function (_filename, eventKind) { return _this.onConfigFileChangeForOpenScriptInfo(configFileName, eventKind); }, ts.PollingInterval.High, "Config file for the inferred project root" /* ConfigFileForInferredRoot */); + this.logConfigFileWatchUpdate(configFileName, canonicalConfigFilePath, configFileExistenceInfo, "Updated the callback" /* UpdatedCallback */); + }; + /** + * Close the config file watcher in the cached ConfigFileExistenceInfo + * if there arent any open files that are root of inferred project + */ + ProjectService.prototype.closeConfigFileWatcherOfConfigFileExistenceInfo = function (configFileExistenceInfo) { + // Close the config file watcher if there are no more open files that are root of inferred project + if (configFileExistenceInfo.configFileWatcherForRootOfInferredProject && + !this.configFileExistenceImpactsRootOfInferredProject(configFileExistenceInfo)) { + configFileExistenceInfo.configFileWatcherForRootOfInferredProject.close(); + configFileExistenceInfo.configFileWatcherForRootOfInferredProject = undefined; + } + }; + /** + * This is called on file close, so that we stop watching the config file for this script info + */ + ProjectService.prototype.stopWatchingConfigFilesForClosedScriptInfo = function (info) { + var _this = this; + ts.Debug.assert(!info.isScriptOpen()); + this.forEachConfigFileLocation(info, function (configFileName, canonicalConfigFilePath) { + var configFileExistenceInfo = _this.configFileExistenceInfoCache.get(canonicalConfigFilePath); + if (configFileExistenceInfo) { + var infoIsRootOfInferredProject = configFileExistenceInfo.openFilesImpactedByConfigFile.get(info.path); + // Delete the info from map, since this file is no more open + configFileExistenceInfo.openFilesImpactedByConfigFile.delete(info.path); + _this.logConfigFileWatchUpdate(configFileName, canonicalConfigFilePath, configFileExistenceInfo, "File removed from open files impacted by this config file" /* OpenFilesImpactedByConfigFileRemove */); + // If the script info was not root of inferred project, + // there wont be config file watch open because of this script info + if (infoIsRootOfInferredProject) { + // But if it is a root, it could be the last script info that is root of inferred project + // and hence we would need to close the config file watcher + _this.closeConfigFileWatcherOfConfigFileExistenceInfo(configFileExistenceInfo); + } + // If there are no open files that are impacted by configFileExistenceInfo after closing this script info + // there is no configured project present, remove the cached existence info + if (!configFileExistenceInfo.openFilesImpactedByConfigFile.size && + !_this.getConfiguredProjectByCanonicalConfigFilePath(canonicalConfigFilePath)) { + ts.Debug.assert(!configFileExistenceInfo.configFileWatcherForRootOfInferredProject); + _this.configFileExistenceInfoCache.delete(canonicalConfigFilePath); + } + } + }); + }; + /** + * This is called by inferred project whenever script info is added as a root + */ + /* @internal */ + ProjectService.prototype.startWatchingConfigFilesForInferredProjectRoot = function (info) { + var _this = this; + ts.Debug.assert(info.isScriptOpen()); + this.forEachConfigFileLocation(info, function (configFileName, canonicalConfigFilePath) { + var configFileExistenceInfo = _this.configFileExistenceInfoCache.get(canonicalConfigFilePath); + if (!configFileExistenceInfo) { + // Create the cache + configFileExistenceInfo = { + exists: _this.host.fileExists(configFileName), + openFilesImpactedByConfigFile: ts.createMap() + }; + _this.configFileExistenceInfoCache.set(canonicalConfigFilePath, configFileExistenceInfo); + } + // Set this file as the root of inferred project + configFileExistenceInfo.openFilesImpactedByConfigFile.set(info.path, true); + _this.logConfigFileWatchUpdate(configFileName, canonicalConfigFilePath, configFileExistenceInfo, "Open file was set as Inferred root" /* RootOfInferredProjectTrue */); + // If there is no configured project for this config file, add the file watcher + if (!configFileExistenceInfo.configFileWatcherForRootOfInferredProject && + !_this.getConfiguredProjectByCanonicalConfigFilePath(canonicalConfigFilePath)) { + _this.createConfigFileWatcherOfConfigFileExistence(configFileName, canonicalConfigFilePath, configFileExistenceInfo); + } + }); + }; + /** + * This is called by inferred project whenever root script info is removed from it + */ + /* @internal */ + ProjectService.prototype.stopWatchingConfigFilesForInferredProjectRoot = function (info) { + var _this = this; + this.forEachConfigFileLocation(info, function (configFileName, canonicalConfigFilePath) { + var configFileExistenceInfo = _this.configFileExistenceInfoCache.get(canonicalConfigFilePath); + if (configFileExistenceInfo && configFileExistenceInfo.openFilesImpactedByConfigFile.has(info.path)) { + ts.Debug.assert(info.isScriptOpen()); + // Info is not root of inferred project any more + configFileExistenceInfo.openFilesImpactedByConfigFile.set(info.path, false); + _this.logConfigFileWatchUpdate(configFileName, canonicalConfigFilePath, configFileExistenceInfo, "Open file was set as not inferred root" /* RootOfInferredProjectFalse */); + // Close the config file watcher + _this.closeConfigFileWatcherOfConfigFileExistenceInfo(configFileExistenceInfo); + } + }); + }; + /** + * This function tries to search for a tsconfig.json for the given file. + * This is different from the method the compiler uses because + * the compiler can assume it will always start searching in the + * current directory (the directory in which tsc was invoked). + * The server must start searching from the directory containing + * the newly opened file. + */ + ProjectService.prototype.forEachConfigFileLocation = function (info, action) { + var _this = this; + if (this.syntaxOnly) { + return undefined; + } + ts.Debug.assert(!isOpenScriptInfo(info) || this.openFiles.has(info.path)); + var projectRootPath = this.openFiles.get(info.path); + var searchPath = server.asNormalizedPath(ts.getDirectoryPath(info.fileName)); + var isSearchPathInProjectRoot = function () { return ts.containsPath(projectRootPath, searchPath, _this.currentDirectory, !_this.host.useCaseSensitiveFileNames); }; + // If projectRootPath doesn't contain info.path, then do normal search for config file + var anySearchPathOk = !projectRootPath || !isSearchPathInProjectRoot(); + do { + var canonicalSearchPath = server.normalizedPathToPath(searchPath, this.currentDirectory, this.toCanonicalFileName); + var tsconfigFileName = server.asNormalizedPath(ts.combinePaths(searchPath, "tsconfig.json")); + var result = action(tsconfigFileName, ts.combinePaths(canonicalSearchPath, "tsconfig.json")); + if (result) { + return tsconfigFileName; + } + var jsconfigFileName = server.asNormalizedPath(ts.combinePaths(searchPath, "jsconfig.json")); + result = action(jsconfigFileName, ts.combinePaths(canonicalSearchPath, "jsconfig.json")); + if (result) { + return jsconfigFileName; + } + var parentPath = server.asNormalizedPath(ts.getDirectoryPath(searchPath)); + if (parentPath === searchPath) { + break; + } + searchPath = parentPath; + } while (anySearchPathOk || isSearchPathInProjectRoot()); + return undefined; + }; + /** + * This function tries to search for a tsconfig.json for the given file. + * This is different from the method the compiler uses because + * the compiler can assume it will always start searching in the + * current directory (the directory in which tsc was invoked). + * The server must start searching from the directory containing + * the newly opened file. + * If script info is passed in, it is asserted to be open script info + * otherwise just file name + */ + ProjectService.prototype.getConfigFileNameForFile = function (info) { + var _this = this; + if (isOpenScriptInfo(info)) + ts.Debug.assert(info.isScriptOpen()); + this.logger.info("Search path: " + ts.getDirectoryPath(info.fileName)); + var configFileName = this.forEachConfigFileLocation(info, function (configFileName, canonicalConfigFilePath) { + return _this.configFileExists(configFileName, canonicalConfigFilePath, info); + }); + if (configFileName) { + this.logger.info("For info: " + info.fileName + " :: Config file name: " + configFileName); + } + else { + this.logger.info("For info: " + info.fileName + " :: No config files found."); + } + return configFileName; + }; + ProjectService.prototype.printProjects = function () { + var _this = this; + if (!this.logger.hasLevel(server.LogLevel.normal)) { + return; + } + var writeProjectFileNames = this.logger.hasLevel(server.LogLevel.verbose); + this.logger.startGroup(); + var counter = printProjectsWithCounter(this.externalProjects, 0); + counter = printProjectsWithCounter(ts.arrayFrom(this.configuredProjects.values()), counter); + printProjectsWithCounter(this.inferredProjects, counter); + this.logger.info("Open files: "); + this.openFiles.forEach(function (projectRootPath, path) { + var info = _this.getScriptInfoForPath(path); + _this.logger.info("\tFileName: " + info.fileName + " ProjectRootPath: " + projectRootPath); + if (writeProjectFileNames) { + _this.logger.info("\t\tProjects: " + info.containingProjects.map(function (p) { return p.getProjectName(); })); + } + }); + this.logger.endGroup(); + }; + ProjectService.prototype.findConfiguredProjectByProjectName = function (configFileName) { + // make sure that casing of config file name is consistent + var canonicalConfigFilePath = server.asNormalizedPath(this.toCanonicalFileName(configFileName)); + return this.getConfiguredProjectByCanonicalConfigFilePath(canonicalConfigFilePath); + }; + ProjectService.prototype.getConfiguredProjectByCanonicalConfigFilePath = function (canonicalConfigFilePath) { + return this.configuredProjects.get(canonicalConfigFilePath); + }; + ProjectService.prototype.findExternalProjectByProjectName = function (projectFileName) { + return findProjectByName(projectFileName, this.externalProjects); + }; + /** Get a filename if the language service exceeds the maximum allowed program size; otherwise returns undefined. */ + ProjectService.prototype.getFilenameForExceededTotalSizeLimitForNonTsFiles = function (name, options, fileNames, propertyReader) { + if (options && options.disableSizeLimit || !this.host.getFileSize) { + return; + } + var availableSpace = server.maxProgramSizeForNonTsFiles; + this.projectToSizeMap.set(name, 0); + this.projectToSizeMap.forEach(function (val) { return (availableSpace -= (val || 0)); }); + var totalNonTsFileSize = 0; + for (var _i = 0, fileNames_2 = fileNames; _i < fileNames_2.length; _i++) { + var f = fileNames_2[_i]; + var fileName = propertyReader.getFileName(f); + if (ts.hasTSFileExtension(fileName)) { + continue; + } + totalNonTsFileSize += this.host.getFileSize(fileName); + if (totalNonTsFileSize > server.maxProgramSizeForNonTsFiles || totalNonTsFileSize > availableSpace) { + this.logger.info(getExceedLimitMessage({ propertyReader: propertyReader, hasTSFileExtension: ts.hasTSFileExtension, host: this.host }, totalNonTsFileSize)); + // Keep the size as zero since it's disabled + return fileName; + } + } + this.projectToSizeMap.set(name, totalNonTsFileSize); + return; + function getExceedLimitMessage(context, totalNonTsFileSize) { + var files = getTop5LargestFiles(context); + return "Non TS file size exceeded limit (" + totalNonTsFileSize + "). Largest files: " + files.map(function (file) { return file.name + ":" + file.size; }).join(", "); + } + function getTop5LargestFiles(_a) { + var propertyReader = _a.propertyReader, hasTSFileExtension = _a.hasTSFileExtension, host = _a.host; + return fileNames.map(function (f) { return propertyReader.getFileName(f); }) + .filter(function (name) { return hasTSFileExtension(name); }) + .map(function (name) { return ({ name: name, size: host.getFileSize(name) }); }) // TODO: GH#18217 + .sort(function (a, b) { return b.size - a.size; }) + .slice(0, 5); + } + }; + ProjectService.prototype.createExternalProject = function (projectFileName, files, options, typeAcquisition, excludedFiles) { + var compilerOptions = convertCompilerOptions(options); + var project = new server.ExternalProject(projectFileName, this, this.documentRegistry, compilerOptions, + /*lastFileExceededProgramSize*/ this.getFilenameForExceededTotalSizeLimitForNonTsFiles(projectFileName, compilerOptions, files, externalFilePropertyReader), options.compileOnSave === undefined ? true : options.compileOnSave); + project.excludedFiles = excludedFiles; + this.addFilesToNonInferredProject(project, files, externalFilePropertyReader, typeAcquisition); + this.externalProjects.push(project); + return project; + }; + /*@internal*/ + ProjectService.prototype.sendSurveyReady = function (project) { + if (this.seenSurveyProjects.has(project.projectName)) { + return; + } + if (project.getCompilerOptions().checkJs !== undefined) { + var name = "checkJs"; + this.logger.info("Survey " + name + " is ready"); + this.sendSurveyReadyEvent(name); + this.seenSurveyProjects.set(project.projectName, true); + } + }; + /*@internal*/ + ProjectService.prototype.sendProjectTelemetry = function (project) { + if (this.seenProjects.has(project.projectName)) { + setProjectOptionsUsed(project); + return; + } + this.seenProjects.set(project.projectName, true); + if (!this.eventHandler || !this.host.createSHA256Hash) { + setProjectOptionsUsed(project); + return; + } + var projectOptions = project.projectKind === server.ProjectKind.Configured ? project.projectOptions : undefined; + setProjectOptionsUsed(project); + var data = { + projectId: this.host.createSHA256Hash(project.projectName), + fileStats: server.countEachFileTypes(project.getScriptInfos(), /*includeSizes*/ true), + compilerOptions: ts.convertCompilerOptionsForTelemetry(project.getCompilationSettings()), + typeAcquisition: convertTypeAcquisition(project.getTypeAcquisition()), + extends: projectOptions && projectOptions.configHasExtendsProperty, + files: projectOptions && projectOptions.configHasFilesProperty, + include: projectOptions && projectOptions.configHasIncludeProperty, + exclude: projectOptions && projectOptions.configHasExcludeProperty, + compileOnSave: project.compileOnSaveEnabled, + configFileName: configFileName(), + projectType: project instanceof server.ExternalProject ? "external" : "configured", + languageServiceEnabled: project.languageServiceEnabled, + version: ts.version, + }; + this.eventHandler({ eventName: server.ProjectInfoTelemetryEvent, data: data }); + function configFileName() { + if (!(project instanceof server.ConfiguredProject)) { + return "other"; + } + return server.getBaseConfigFileName(project.getConfigFilePath()) || "other"; + } + function convertTypeAcquisition(_a) { + var enable = _a.enable, include = _a.include, exclude = _a.exclude; + return { + enable: enable, + include: include !== undefined && include.length !== 0, + exclude: exclude !== undefined && exclude.length !== 0, + }; + } + }; + ProjectService.prototype.addFilesToNonInferredProject = function (project, files, propertyReader, typeAcquisition) { + this.updateNonInferredProjectFiles(project, files, propertyReader); + project.setTypeAcquisition(typeAcquisition); + }; + ProjectService.prototype.createConfiguredProject = function (configFileName) { + var _this = this; + var cachedDirectoryStructureHost = ts.createCachedDirectoryStructureHost(this.host, this.host.getCurrentDirectory(), this.host.useCaseSensitiveFileNames); // TODO: GH#18217 + this.logger.info("Opened configuration file " + configFileName); + var project = new server.ConfiguredProject(configFileName, this, this.documentRegistry, cachedDirectoryStructureHost); + // TODO: We probably should also watch the configFiles that are extended + project.configFileWatcher = this.watchFactory.watchFile(this.host, configFileName, function (_fileName, eventKind) { return _this.onConfigChangedForConfiguredProject(project, eventKind); }, ts.PollingInterval.High, "Config file for the program" /* ConfigFilePath */, project); + this.configuredProjects.set(project.canonicalConfigFilePath, project); + this.setConfigFileExistenceByNewConfiguredProject(project); + return project; + }; + /* @internal */ + ProjectService.prototype.createConfiguredProjectWithDelayLoad = function (configFileName, reason) { + var project = this.createConfiguredProject(configFileName); + project.pendingReload = ts.ConfigFileProgramReloadLevel.Full; + project.pendingReloadReason = reason; + return project; + }; + /* @internal */ + ProjectService.prototype.createAndLoadConfiguredProject = function (configFileName, reason) { + var project = this.createConfiguredProject(configFileName); + this.loadConfiguredProject(project, reason); + return project; + }; + /* @internal */ + ProjectService.prototype.createLoadAndUpdateConfiguredProject = function (configFileName, reason) { + var project = this.createAndLoadConfiguredProject(configFileName, reason); + project.updateGraph(); + return project; + }; + /** + * Read the config file of the project, and update the project root file names. + */ + /* @internal */ + ProjectService.prototype.loadConfiguredProject = function (project, reason) { + this.sendProjectLoadingStartEvent(project, reason); + // Read updated contents from disk + var configFilename = ts.normalizePath(project.getConfigFilePath()); + var configFileContent = this.host.readFile(configFilename); // TODO: GH#18217 + var result = ts.parseJsonText(configFilename, configFileContent); + if (!result.endOfFileToken) { + result.endOfFileToken = { kind: 1 /* EndOfFileToken */ }; + } + var configFileErrors = result.parseDiagnostics; + var parsedCommandLine = ts.parseJsonSourceFileConfigFileContent(result, project.getCachedDirectoryStructureHost(), ts.getDirectoryPath(configFilename), + /*existingOptions*/ {}, configFilename, + /*resolutionStack*/ [], this.hostConfiguration.extraFileExtensions); + if (parsedCommandLine.errors.length) { + configFileErrors.push.apply(configFileErrors, parsedCommandLine.errors); + } + ts.Debug.assert(!!parsedCommandLine.fileNames); + var compilerOptions = parsedCommandLine.options; + // Update the project + if (!project.projectOptions) { + project.projectOptions = { + configHasExtendsProperty: parsedCommandLine.raw.extends !== undefined, + configHasFilesProperty: parsedCommandLine.raw.files !== undefined, + configHasIncludeProperty: parsedCommandLine.raw.include !== undefined, + configHasExcludeProperty: parsedCommandLine.raw.exclude !== undefined + }; + } + project.configFileSpecs = parsedCommandLine.configFileSpecs; + project.canConfigFileJsonReportNoInputFiles = ts.canJsonReportNoInutFiles(parsedCommandLine.raw); + project.setProjectErrors(configFileErrors); + project.updateReferences(parsedCommandLine.projectReferences); + var lastFileExceededProgramSize = this.getFilenameForExceededTotalSizeLimitForNonTsFiles(project.canonicalConfigFilePath, compilerOptions, parsedCommandLine.fileNames, fileNamePropertyReader); + if (lastFileExceededProgramSize) { + project.disableLanguageService(lastFileExceededProgramSize); + project.stopWatchingWildCards(); + } + else { + project.enableLanguageService(); + project.watchWildcards(ts.createMapFromTemplate(parsedCommandLine.wildcardDirectories)); // TODO: GH#18217 + } + project.enablePluginsWithOptions(compilerOptions, this.currentPluginConfigOverrides); + var filesToAdd = parsedCommandLine.fileNames.concat(project.getExternalFiles()); + this.updateRootAndOptionsOfNonInferredProject(project, filesToAdd, fileNamePropertyReader, compilerOptions, parsedCommandLine.typeAcquisition, parsedCommandLine.compileOnSave); // TODO: GH#18217 + }; + ProjectService.prototype.updateNonInferredProjectFiles = function (project, files, propertyReader) { + var projectRootFilesMap = project.getRootFilesMap(); + var newRootScriptInfoMap = ts.createMap(); + for (var _i = 0, files_4 = files; _i < files_4.length; _i++) { + var f = files_4[_i]; + var newRootFile = propertyReader.getFileName(f); + var normalizedPath = server.toNormalizedPath(newRootFile); + var isDynamic = server.isDynamicFileName(normalizedPath); + var scriptInfo = void 0; + var path = void 0; + // Use the project's fileExists so that it can use caching instead of reaching to disk for the query + if (!isDynamic && !project.fileExists(newRootFile)) { + path = server.normalizedPathToPath(normalizedPath, this.currentDirectory, this.toCanonicalFileName); + var existingValue = projectRootFilesMap.get(path); + if (server.isScriptInfo(existingValue)) { + project.removeFile(existingValue, /*fileExists*/ false, /*detachFromProject*/ true); + } + projectRootFilesMap.set(path, normalizedPath); + scriptInfo = normalizedPath; + } + else { + var scriptKind = propertyReader.getScriptKind(f, this.hostConfiguration.extraFileExtensions); + var hasMixedContent = propertyReader.hasMixedContent(f, this.hostConfiguration.extraFileExtensions); + scriptInfo = this.getOrCreateScriptInfoNotOpenedByClientForNormalizedPath(normalizedPath, project.currentDirectory, scriptKind, hasMixedContent, project.directoryStructureHost); // TODO: GH#18217 + path = scriptInfo.path; + // If this script info is not already a root add it + if (!project.isRoot(scriptInfo)) { + project.addRoot(scriptInfo); + if (scriptInfo.isScriptOpen()) { + // if file is already root in some inferred project + // - remove the file from that project and delete the project if necessary + this.removeRootOfInferredProjectIfNowPartOfOtherProject(scriptInfo); + } + } + } + newRootScriptInfoMap.set(path, scriptInfo); + } + // project's root file map size is always going to be same or larger than new roots map + // as we have already all the new files to the project + if (projectRootFilesMap.size > newRootScriptInfoMap.size) { + projectRootFilesMap.forEach(function (value, path) { + if (!newRootScriptInfoMap.has(path)) { + if (server.isScriptInfo(value)) { + project.removeFile(value, project.fileExists(path), /*detachFromProject*/ true); + } + else { + projectRootFilesMap.delete(path); + } + } + }); + } + // Just to ensure that even if root files dont change, the changes to the non root file are picked up, + // mark the project as dirty unconditionally + project.markAsDirty(); + }; + ProjectService.prototype.updateRootAndOptionsOfNonInferredProject = function (project, newUncheckedFiles, propertyReader, newOptions, newTypeAcquisition, compileOnSave) { + project.setCompilerOptions(newOptions); + // VS only set the CompileOnSaveEnabled option in the request if the option was changed recently + // therefore if it is undefined, it should not be updated. + if (compileOnSave !== undefined) { + project.compileOnSaveEnabled = compileOnSave; + } + this.addFilesToNonInferredProject(project, newUncheckedFiles, propertyReader, newTypeAcquisition); + }; + /** + * Reload the file names from config file specs and update the project graph + */ + /*@internal*/ + ProjectService.prototype.reloadFileNamesOfConfiguredProject = function (project) { + var configFileSpecs = project.configFileSpecs; // TODO: GH#18217 + var configFileName = project.getConfigFilePath(); + var fileNamesResult = ts.getFileNamesFromConfigSpecs(configFileSpecs, ts.getDirectoryPath(configFileName), project.getCompilationSettings(), project.getCachedDirectoryStructureHost(), this.hostConfiguration.extraFileExtensions); + project.updateErrorOnNoInputFiles(fileNamesResult); + this.updateNonInferredProjectFiles(project, fileNamesResult.fileNames.concat(project.getExternalFiles()), fileNamePropertyReader); + return project.updateGraph(); + }; + /** + * Read the config file of the project again by clearing the cache and update the project graph + */ + /* @internal */ + ProjectService.prototype.reloadConfiguredProject = function (project, reason) { + // At this point, there is no reason to not have configFile in the host + var host = project.getCachedDirectoryStructureHost(); + // Clear the cache since we are reloading the project from disk + host.clearCache(); + var configFileName = project.getConfigFilePath(); + this.logger.info("Reloading configured project " + configFileName); + // Load project from the disk + this.loadConfiguredProject(project, reason); + project.updateGraph(); + this.sendConfigFileDiagEvent(project, configFileName); + }; + ProjectService.prototype.sendConfigFileDiagEvent = function (project, triggerFile) { + if (!this.eventHandler || this.suppressDiagnosticEvents) { + return; + } + var diagnostics = project.getLanguageService().getCompilerOptionsDiagnostics(); + diagnostics.push.apply(diagnostics, project.getAllProjectErrors()); + this.eventHandler({ + eventName: server.ConfigFileDiagEvent, + data: { configFileName: project.getConfigFilePath(), diagnostics: diagnostics, triggerFile: triggerFile } + }); + }; + ProjectService.prototype.getOrCreateInferredProjectForProjectRootPathIfEnabled = function (info, projectRootPath) { + if (info.isDynamic || !this.useInferredProjectPerProjectRoot) { + return undefined; + } + if (projectRootPath) { + var canonicalProjectRootPath = this.toCanonicalFileName(projectRootPath); + // if we have an explicit project root path, find (or create) the matching inferred project. + for (var _i = 0, _a = this.inferredProjects; _i < _a.length; _i++) { + var project = _a[_i]; + if (project.projectRootPath === canonicalProjectRootPath) { + return project; + } + } + return this.createInferredProject(projectRootPath, /*isSingleInferredProject*/ false, projectRootPath); + } + // we don't have an explicit root path, so we should try to find an inferred project + // that more closely contains the file. + var bestMatch; + for (var _b = 0, _c = this.inferredProjects; _b < _c.length; _b++) { + var project = _c[_b]; + // ignore single inferred projects (handled elsewhere) + if (!project.projectRootPath) + continue; + // ignore inferred projects that don't contain the root's path + if (!ts.containsPath(project.projectRootPath, info.path, this.host.getCurrentDirectory(), !this.host.useCaseSensitiveFileNames)) + continue; + // ignore inferred projects that are higher up in the project root. + // TODO(rbuckton): Should we add the file as a root to these as well? + if (bestMatch && bestMatch.projectRootPath.length > project.projectRootPath.length) + continue; + bestMatch = project; + } + return bestMatch; + }; + ProjectService.prototype.getOrCreateSingleInferredProjectIfEnabled = function () { + if (!this.useSingleInferredProject) { + return undefined; + } + // If `useInferredProjectPerProjectRoot` is not enabled, then there will only be one + // inferred project for all files. If `useInferredProjectPerProjectRoot` is enabled + // then we want to put all files that are not opened with a `projectRootPath` into + // the same inferred project. + // + // To avoid the cost of searching through the array and to optimize for the case where + // `useInferredProjectPerProjectRoot` is not enabled, we will always put the inferred + // project for non-rooted files at the front of the array. + if (this.inferredProjects.length > 0 && this.inferredProjects[0].projectRootPath === undefined) { + return this.inferredProjects[0]; + } + // Single inferred project does not have a project root and hence no current directory + return this.createInferredProject(/*currentDirectory*/ undefined, /*isSingleInferredProject*/ true); + }; + ProjectService.prototype.getOrCreateSingleInferredWithoutProjectRoot = function (currentDirectory) { + ts.Debug.assert(!this.useSingleInferredProject); + var expectedCurrentDirectory = this.toCanonicalFileName(this.getNormalizedAbsolutePath(currentDirectory || "")); + // Reuse the project with same current directory but no roots + for (var _i = 0, _a = this.inferredProjects; _i < _a.length; _i++) { + var inferredProject = _a[_i]; + if (!inferredProject.projectRootPath && + inferredProject.isOrphan() && + inferredProject.canonicalCurrentDirectory === expectedCurrentDirectory) { + return inferredProject; + } + } + return this.createInferredProject(currentDirectory); + }; + ProjectService.prototype.createInferredProject = function (currentDirectory, isSingleInferredProject, projectRootPath) { + var compilerOptions = projectRootPath && this.compilerOptionsForInferredProjectsPerProjectRoot.get(projectRootPath) || this.compilerOptionsForInferredProjects; // TODO: GH#18217 + var project = new server.InferredProject(this, this.documentRegistry, compilerOptions, projectRootPath, currentDirectory, this.currentPluginConfigOverrides); + if (isSingleInferredProject) { + this.inferredProjects.unshift(project); + } + else { + this.inferredProjects.push(project); + } + return project; + }; + /*@internal*/ + ProjectService.prototype.getOrCreateScriptInfoNotOpenedByClient = function (uncheckedFileName, currentDirectory, hostToQueryFileExistsOn) { + return this.getOrCreateScriptInfoNotOpenedByClientForNormalizedPath(server.toNormalizedPath(uncheckedFileName), currentDirectory, /*scriptKind*/ undefined, + /*hasMixedContent*/ undefined, hostToQueryFileExistsOn); + }; + ProjectService.prototype.getScriptInfo = function (uncheckedFileName) { + return this.getScriptInfoForNormalizedPath(server.toNormalizedPath(uncheckedFileName)); + }; + /* @internal */ + ProjectService.prototype.getScriptInfoOrConfig = function (uncheckedFileName) { + var path = server.toNormalizedPath(uncheckedFileName); + var info = this.getScriptInfoForNormalizedPath(path); + if (info) + return info; + var configProject = this.configuredProjects.get(uncheckedFileName); + return configProject && configProject.getCompilerOptions().configFile; + }; + /* @internal */ + ProjectService.prototype.logErrorForScriptInfoNotFound = function (fileName) { + var names = ts.arrayFrom(this.filenameToScriptInfo.entries()).map(function (_a) { + var path = _a[0], scriptInfo = _a[1]; + return ({ path: path, fileName: scriptInfo.fileName }); + }); + this.logger.msg("Could not find file " + JSON.stringify(fileName) + ".\nAll files are: " + JSON.stringify(names), server.Msg.Err); + }; + /** + * Returns the projects that contain script info through SymLink + * Note that this does not return projects in info.containingProjects + */ + /*@internal*/ + ProjectService.prototype.getSymlinkedProjects = function (info) { + var projects; + if (this.realpathToScriptInfos) { + var realpath = info.getRealpathIfDifferent(); + if (realpath) { + ts.forEach(this.realpathToScriptInfos.get(realpath), combineProjects); + } + ts.forEach(this.realpathToScriptInfos.get(info.path), combineProjects); + } + return projects; + function combineProjects(toAddInfo) { + if (toAddInfo !== info) { + var _loop_27 = function (project) { + // Add the projects only if they can use symLink targets and not already in the list + if (project.languageServiceEnabled && + !project.isOrphan() && + !project.getCompilerOptions().preserveSymlinks && + !ts.contains(info.containingProjects, project)) { + if (!projects) { + projects = ts.createMultiMap(); + projects.add(toAddInfo.path, project); + } + else if (!ts.forEachEntry(projects, function (projs, path) { return path === toAddInfo.path ? false : ts.contains(projs, project); })) { + projects.add(toAddInfo.path, project); + } + } + }; + for (var _i = 0, _a = toAddInfo.containingProjects; _i < _a.length; _i++) { + var project = _a[_i]; + _loop_27(project); + } + } + } + }; + ProjectService.prototype.watchClosedScriptInfo = function (info) { + var _this = this; + ts.Debug.assert(!info.fileWatcher); + // do not watch files with mixed content - server doesn't know how to interpret it + // do not watch files in the global cache location + if (!info.isDynamicOrHasMixedContent() && + (!this.globalCacheLocationDirectoryPath || + !ts.startsWith(info.path, this.globalCacheLocationDirectoryPath))) { + var indexOfNodeModules = info.path.indexOf("/node_modules/"); + if (!this.host.getModifiedTime || indexOfNodeModules === -1) { + info.fileWatcher = this.watchFactory.watchFilePath(this.host, info.fileName, function (fileName, eventKind, path) { return _this.onSourceFileChanged(fileName, eventKind, path); }, ts.PollingInterval.Medium, info.path, "Closed Script info" /* ClosedScriptInfo */); + } + else { + info.mTime = this.getModifiedTime(info); + info.fileWatcher = this.watchClosedScriptInfoInNodeModules(info.path.substr(0, indexOfNodeModules)); + } + } + }; + ProjectService.prototype.watchClosedScriptInfoInNodeModules = function (dir) { + var _this = this; + // Watch only directory + var existing = this.scriptInfoInNodeModulesWatchers.get(dir); + if (existing) { + existing.refCount++; + return existing; + } + var watchDir = dir + "/node_modules"; + var watcher = this.watchFactory.watchDirectory(this.host, watchDir, function (fileOrDirectory) { + var fileOrDirectoryPath = _this.toPath(fileOrDirectory); + if (ts.isPathInNodeModulesStartingWithDot(fileOrDirectoryPath)) + return; + // Has extension + ts.Debug.assert(result.refCount > 0); + if (watchDir === fileOrDirectoryPath) { + _this.refreshScriptInfosInDirectory(watchDir); + } + else { + var info = _this.getScriptInfoForPath(fileOrDirectoryPath); + if (info) { + if (isScriptInfoWatchedFromNodeModules(info)) { + _this.refreshScriptInfo(info); + } + } + // Folder + else if (!ts.hasExtension(fileOrDirectoryPath)) { + _this.refreshScriptInfosInDirectory(fileOrDirectoryPath); + } + } + }, 1 /* Recursive */, "node_modules for closed script infos in them" /* NodeModulesForClosedScriptInfo */); + var result = { + close: function () { + if (result.refCount === 1) { + watcher.close(); + _this.scriptInfoInNodeModulesWatchers.delete(dir); + } + else { + result.refCount--; + } + }, + refCount: 1 + }; + this.scriptInfoInNodeModulesWatchers.set(dir, result); + return result; + }; + ProjectService.prototype.getModifiedTime = function (info) { + return (this.host.getModifiedTime(info.path) || ts.missingFileModifiedTime).getTime(); + }; + ProjectService.prototype.refreshScriptInfo = function (info) { + var mTime = this.getModifiedTime(info); + if (mTime !== info.mTime) { + var eventKind = ts.getFileWatcherEventKind(info.mTime, mTime); + info.mTime = mTime; + this.onSourceFileChanged(info.fileName, eventKind, info.path); + } + }; + ProjectService.prototype.refreshScriptInfosInDirectory = function (dir) { + var _this = this; + dir = dir + ts.directorySeparator; + this.filenameToScriptInfo.forEach(function (info) { + if (isScriptInfoWatchedFromNodeModules(info) && ts.startsWith(info.path, dir)) { + _this.refreshScriptInfo(info); + } + }); + }; + ProjectService.prototype.stopWatchingScriptInfo = function (info) { + if (info.fileWatcher) { + info.fileWatcher.close(); + info.fileWatcher = undefined; + } + }; + ProjectService.prototype.getOrCreateScriptInfoNotOpenedByClientForNormalizedPath = function (fileName, currentDirectory, scriptKind, hasMixedContent, hostToQueryFileExistsOn) { + if (ts.isRootedDiskPath(fileName) || server.isDynamicFileName(fileName)) { + return this.getOrCreateScriptInfoWorker(fileName, currentDirectory, /*openedByClient*/ false, /*fileContent*/ undefined, scriptKind, hasMixedContent, hostToQueryFileExistsOn); + } + // This is non rooted path with different current directory than project service current directory + // Only paths recognized are open relative file paths + var info = this.openFilesWithNonRootedDiskPath.get(this.toCanonicalFileName(fileName)); + if (info) { + return info; + } + // This means triple slash references wont be resolved in dynamic and unsaved files + // which is intentional since we dont know what it means to be relative to non disk files + return undefined; + }; + ProjectService.prototype.getOrCreateScriptInfoOpenedByClientForNormalizedPath = function (fileName, currentDirectory, fileContent, scriptKind, hasMixedContent) { + return this.getOrCreateScriptInfoWorker(fileName, currentDirectory, /*openedByClient*/ true, fileContent, scriptKind, hasMixedContent); + }; + ProjectService.prototype.getOrCreateScriptInfoForNormalizedPath = function (fileName, openedByClient, fileContent, scriptKind, hasMixedContent, hostToQueryFileExistsOn) { + return this.getOrCreateScriptInfoWorker(fileName, this.currentDirectory, openedByClient, fileContent, scriptKind, hasMixedContent, hostToQueryFileExistsOn); + }; + ProjectService.prototype.getOrCreateScriptInfoWorker = function (fileName, currentDirectory, openedByClient, fileContent, scriptKind, hasMixedContent, hostToQueryFileExistsOn) { + var _this = this; + ts.Debug.assert(fileContent === undefined || openedByClient, "ScriptInfo needs to be opened by client to be able to set its user defined content"); + var path = server.normalizedPathToPath(fileName, currentDirectory, this.toCanonicalFileName); + var info = this.getScriptInfoForPath(path); + if (!info) { + var isDynamic = server.isDynamicFileName(fileName); + ts.Debug.assert(ts.isRootedDiskPath(fileName) || isDynamic || openedByClient, "", function () { return JSON.stringify({ fileName: fileName, currentDirectory: currentDirectory, hostCurrentDirectory: _this.currentDirectory, openKeys: ts.arrayFrom(_this.openFilesWithNonRootedDiskPath.keys()) }) + "\nScript info with non-dynamic relative file name can only be open script info or in context of host currentDirectory"; }); + ts.Debug.assert(!ts.isRootedDiskPath(fileName) || this.currentDirectory === currentDirectory || !this.openFilesWithNonRootedDiskPath.has(this.toCanonicalFileName(fileName)), "", function () { return JSON.stringify({ fileName: fileName, currentDirectory: currentDirectory, hostCurrentDirectory: _this.currentDirectory, openKeys: ts.arrayFrom(_this.openFilesWithNonRootedDiskPath.keys()) }) + "\nOpen script files with non rooted disk path opened with current directory context cannot have same canonical names"; }); + ts.Debug.assert(!isDynamic || this.currentDirectory === currentDirectory, "", function () { return JSON.stringify({ fileName: fileName, currentDirectory: currentDirectory, hostCurrentDirectory: _this.currentDirectory, openKeys: ts.arrayFrom(_this.openFilesWithNonRootedDiskPath.keys()) }) + "\nDynamic files must always have current directory context since containing external project name will always match the script info name."; }); + // If the file is not opened by client and the file doesnot exist on the disk, return + if (!openedByClient && !isDynamic && !(hostToQueryFileExistsOn || this.host).fileExists(fileName)) { + return; + } + info = new server.ScriptInfo(this.host, fileName, scriptKind, !!hasMixedContent, path, this.filenameToScriptInfoVersion.get(path)); // TODO: GH#18217 + this.filenameToScriptInfo.set(info.path, info); + this.filenameToScriptInfoVersion.delete(info.path); + if (!openedByClient) { + this.watchClosedScriptInfo(info); + } + else if (!ts.isRootedDiskPath(fileName) && !isDynamic) { + // File that is opened by user but isn't rooted disk path + this.openFilesWithNonRootedDiskPath.set(this.toCanonicalFileName(fileName), info); + } + } + if (openedByClient && !info.isScriptOpen()) { + // Opening closed script info + // either it was created just now, or was part of projects but was closed + this.stopWatchingScriptInfo(info); + info.open(fileContent); + if (hasMixedContent) { + info.registerFileUpdate(); + } + } + else { + ts.Debug.assert(fileContent === undefined); + } + return info; + }; + /** + * This gets the script info for the normalized path. If the path is not rooted disk path then the open script info with project root context is preferred + */ + ProjectService.prototype.getScriptInfoForNormalizedPath = function (fileName) { + return !ts.isRootedDiskPath(fileName) && this.openFilesWithNonRootedDiskPath.get(this.toCanonicalFileName(fileName)) || + this.getScriptInfoForPath(server.normalizedPathToPath(fileName, this.currentDirectory, this.toCanonicalFileName)); + }; + ProjectService.prototype.getScriptInfoForPath = function (fileName) { + return this.filenameToScriptInfo.get(fileName); + }; + ProjectService.prototype.setHostConfiguration = function (args) { + var _this = this; + if (args.file) { + var info = this.getScriptInfoForNormalizedPath(server.toNormalizedPath(args.file)); + if (info) { + info.setOptions(convertFormatOptions(args.formatOptions), args.preferences); + this.logger.info("Host configuration update for file " + args.file); + } + } + else { + if (args.hostInfo !== undefined) { + this.hostConfiguration.hostInfo = args.hostInfo; + this.logger.info("Host information " + args.hostInfo); + } + if (args.formatOptions) { + this.hostConfiguration.formatCodeOptions = __assign({}, this.hostConfiguration.formatCodeOptions, convertFormatOptions(args.formatOptions)); + this.logger.info("Format host information updated"); + } + if (args.preferences) { + var lazyConfiguredProjectsFromExternalProject = this.hostConfiguration.preferences.lazyConfiguredProjectsFromExternalProject; + this.hostConfiguration.preferences = __assign({}, this.hostConfiguration.preferences, args.preferences); + if (lazyConfiguredProjectsFromExternalProject && !this.hostConfiguration.preferences.lazyConfiguredProjectsFromExternalProject) { + // Load configured projects for external projects that are pending reload + this.configuredProjects.forEach(function (project) { + if (project.hasExternalProjectRef() && + project.pendingReload === ts.ConfigFileProgramReloadLevel.Full && + !_this.pendingProjectUpdates.has(project.getProjectName())) { + project.updateGraph(); + } + }); + } + } + if (args.extraFileExtensions) { + this.hostConfiguration.extraFileExtensions = args.extraFileExtensions; + // We need to update the project structures again as it is possible that existing + // project structure could have more or less files depending on extensions permitted + this.reloadProjects(); + this.logger.info("Host file extension mappings updated"); + } + } + }; + ProjectService.prototype.closeLog = function () { + this.logger.close(); + }; + /** + * This function rebuilds the project for every file opened by the client + * This does not reload contents of open files from disk. But we could do that if needed + */ + ProjectService.prototype.reloadProjects = function () { + this.logger.info("reload projects."); + // If we want this to also reload open files from disk, we could do that, + // but then we need to make sure we arent calling this function + // (and would separate out below reloading of projects to be called when immediate reload is needed) + // as there is no need to load contents of the files from the disk + // Reload Projects + this.reloadConfiguredProjectForFiles(this.openFiles, /*delayReload*/ false, ts.returnTrue, "User requested reload projects"); + this.ensureProjectForOpenFiles(); + }; + ProjectService.prototype.delayReloadConfiguredProjectForFiles = function (configFileExistenceInfo, ignoreIfNotRootOfInferredProject) { + // Get open files to reload projects for + this.reloadConfiguredProjectForFiles(configFileExistenceInfo.openFilesImpactedByConfigFile, + /*delayReload*/ true, ignoreIfNotRootOfInferredProject ? + function (isRootOfInferredProject) { return isRootOfInferredProject; } : // Reload open files if they are root of inferred project + ts.returnTrue, // Reload all the open files impacted by config file + "Change in config file detected"); + this.delayEnsureProjectForOpenFiles(); + }; + /** + * This function goes through all the openFiles and tries to file the config file for them. + * If the config file is found and it refers to existing project, it reloads it either immediately + * or schedules it for reload depending on delayReload option + * If the there is no existing project it just opens the configured project for the config file + * reloadForInfo provides a way to filter out files to reload configured project for + */ + ProjectService.prototype.reloadConfiguredProjectForFiles = function (openFiles, delayReload, shouldReloadProjectFor, reason) { + var _this = this; + var updatedProjects = ts.createMap(); + // try to reload config file for all open files + openFiles.forEach(function (openFileValue, path) { + // Filter out the files that need to be ignored + if (!shouldReloadProjectFor(openFileValue)) { + return; + } + var info = _this.getScriptInfoForPath(path); // TODO: GH#18217 + ts.Debug.assert(info.isScriptOpen()); + // This tries to search for a tsconfig.json for the given file. If we found it, + // we first detect if there is already a configured project created for it: if so, + // we re- read the tsconfig file content and update the project only if we havent already done so + // otherwise we create a new one. + var configFileName = _this.getConfigFileNameForFile(info); + if (configFileName) { + var project = _this.findConfiguredProjectByProjectName(configFileName) || _this.createConfiguredProject(configFileName); + if (!updatedProjects.has(configFileName)) { + if (delayReload) { + project.pendingReload = ts.ConfigFileProgramReloadLevel.Full; + project.pendingReloadReason = reason; + _this.delayUpdateProjectGraph(project); + } + else { + // reload from the disk + _this.reloadConfiguredProject(project, reason); + } + updatedProjects.set(configFileName, true); + } + } + }); + }; + /** + * Remove the root of inferred project if script info is part of another project + */ + ProjectService.prototype.removeRootOfInferredProjectIfNowPartOfOtherProject = function (info) { + // If the script info is root of inferred project, it could only be first containing project + // since info is added as root to the inferred project only when there are no other projects containing it + // So when it is root of the inferred project and after project structure updates its now part + // of multiple project it needs to be removed from that inferred project because: + // - references in inferred project supercede the root part + // - root / reference in non - inferred project beats root in inferred project + // eg. say this is structure /a/b/a.ts /a/b/c.ts where c.ts references a.ts + // When a.ts is opened, since there is no configured project/external project a.ts can be part of + // a.ts is added as root to inferred project. + // Now at time of opening c.ts, c.ts is also not aprt of any existing project, + // so it will be added to inferred project as a root. (for sake of this example assume single inferred project is false) + // So at this poing a.ts is part of first inferred project and second inferred project (of which c.ts is root) + // And hence it needs to be removed from the first inferred project. + ts.Debug.assert(info.containingProjects.length > 0); + var firstProject = info.containingProjects[0]; + if (!firstProject.isOrphan() && + firstProject.projectKind === server.ProjectKind.Inferred && + firstProject.isRoot(info) && + ts.forEach(info.containingProjects, function (p) { return p !== firstProject && !p.isOrphan(); })) { + firstProject.removeFile(info, /*fileExists*/ true, /*detachFromProject*/ true); + } + }; + /** + * This function is to update the project structure for every inferred project. + * It is called on the premise that all the configured projects are + * up to date. + * This will go through open files and assign them to inferred project if open file is not part of any other project + * After that all the inferred project graphs are updated + */ + ProjectService.prototype.ensureProjectForOpenFiles = function () { + var _this = this; + this.logger.info("Structure before ensureProjectForOpenFiles:"); + this.printProjects(); + this.openFiles.forEach(function (projectRootPath, path) { + var info = _this.getScriptInfoForPath(path); + // collect all orphaned script infos from open files + if (info.isOrphan()) { + _this.assignOrphanScriptInfoToInferredProject(info, projectRootPath); + } + else { + // Or remove the root of inferred project if is referenced in more than one projects + _this.removeRootOfInferredProjectIfNowPartOfOtherProject(info); + } + }); + this.pendingEnsureProjectForOpenFiles = false; + this.inferredProjects.forEach(updateProjectIfDirty); + this.logger.info("Structure after ensureProjectForOpenFiles:"); + this.printProjects(); + }; + /** + * Open file whose contents is managed by the client + * @param filename is absolute pathname + * @param fileContent is a known version of the file content that is more up to date than the one on disk + */ + ProjectService.prototype.openClientFile = function (fileName, fileContent, scriptKind, projectRootPath) { + return this.openClientFileWithNormalizedPath(server.toNormalizedPath(fileName), fileContent, scriptKind, /*hasMixedContent*/ false, projectRootPath ? server.toNormalizedPath(projectRootPath) : undefined); + }; + /*@internal*/ + ProjectService.prototype.getOriginalLocationEnsuringConfiguredProject = function (project, location) { + var originalLocation = project.getSourceMapper().tryGetSourcePosition(location); + if (!originalLocation) + return undefined; + var fileName = originalLocation.fileName; + if (!this.getScriptInfo(fileName) && !this.host.fileExists(fileName)) + return undefined; + var originalFileInfo = { fileName: server.toNormalizedPath(fileName), path: this.toPath(fileName) }; + var configFileName = this.getConfigFileNameForFile(originalFileInfo); + if (!configFileName) + return undefined; + var configuredProject = this.findConfiguredProjectByProjectName(configFileName) || + this.createAndLoadConfiguredProject(configFileName, "Creating project for original file: " + originalFileInfo.fileName + " for location: " + location.fileName); + updateProjectIfDirty(configuredProject); + // Keep this configured project as referenced from project + addOriginalConfiguredProject(configuredProject); + var originalScriptInfo = this.getScriptInfo(fileName); + if (!originalScriptInfo || !originalScriptInfo.containingProjects.length) + return undefined; + // Add configured projects as referenced + originalScriptInfo.containingProjects.forEach(function (project) { + if (project.projectKind === server.ProjectKind.Configured) { + addOriginalConfiguredProject(project); + } + }); + return originalLocation; + function addOriginalConfiguredProject(originalProject) { + if (!project.originalConfiguredProjects) { + project.originalConfiguredProjects = ts.createMap(); + } + project.originalConfiguredProjects.set(originalProject.canonicalConfigFilePath, true); + } + }; + /** @internal */ + ProjectService.prototype.fileExists = function (fileName) { + return this.filenameToScriptInfo.has(fileName) || this.host.fileExists(fileName); + }; + ProjectService.prototype.findExternalProjectContainingOpenScriptInfo = function (info) { + return ts.find(this.externalProjects, function (proj) { + // Ensure project structure is up-to-date to check if info is present in external project + updateProjectIfDirty(proj); + return proj.containsScriptInfo(info); + }); + }; + ProjectService.prototype.openClientFileWithNormalizedPath = function (fileName, fileContent, scriptKind, hasMixedContent, projectRootPath) { + var _this = this; + var configFileName; + var configFileErrors; + var info = this.getOrCreateScriptInfoOpenedByClientForNormalizedPath(fileName, projectRootPath ? this.getNormalizedAbsolutePath(projectRootPath) : this.currentDirectory, fileContent, scriptKind, hasMixedContent); // TODO: GH#18217 + this.openFiles.set(info.path, projectRootPath); + var project = this.findExternalProjectContainingOpenScriptInfo(info); + if (!project && !this.syntaxOnly) { // Checking syntaxOnly is an optimization + configFileName = this.getConfigFileNameForFile(info); + if (configFileName) { + project = this.findConfiguredProjectByProjectName(configFileName); + if (!project) { + project = this.createLoadAndUpdateConfiguredProject(configFileName, "Creating possible configured project for " + fileName + " to open"); + // Send the event only if the project got created as part of this open request and info is part of the project + if (info.isOrphan()) { + // Since the file isnt part of configured project, do not send config file info + configFileName = undefined; + } + else { + configFileErrors = project.getAllProjectErrors(); + this.sendConfigFileDiagEvent(project, fileName); + } + } + else { + // Ensure project is ready to check if it contains opened script info + updateProjectIfDirty(project); + } + } + } + // Project we have at this point is going to be updated since its either found through + // - external project search, which updates the project before checking if info is present in it + // - configured project - either created or updated to ensure we know correct status of info + // At this point we need to ensure that containing projects of the info are uptodate + // This will ensure that later question of info.isOrphan() will return correct answer + // and we correctly create inferred project for the info + info.containingProjects.forEach(updateProjectIfDirty); + // At this point if file is part of any any configured or external project, then it would be present in the containing projects + // So if it still doesnt have any containing projects, it needs to be part of inferred project + if (info.isOrphan()) { + this.assignOrphanScriptInfoToInferredProject(info, projectRootPath); + } + ts.Debug.assert(!info.isOrphan()); + // This was postponed from closeOpenFile to after opening next file, + // so that we can reuse the project if we need to right away + this.removeOrphanConfiguredProjects(); + // Remove orphan inferred projects now that we have reused projects + // We need to create a duplicate because we cant guarantee order after removal + for (var _i = 0, _a = this.inferredProjects.slice(); _i < _a.length; _i++) { + var inferredProject = _a[_i]; + if (inferredProject.isOrphan()) { + this.removeProject(inferredProject); + } + } + // Delete the orphan files here because there might be orphan script infos (which are not part of project) + // when some file/s were closed which resulted in project removal. + // It was then postponed to cleanup these script infos so that they can be reused if + // the file from that old project is reopened because of opening file from here. + this.filenameToScriptInfo.forEach(function (info) { + if (!info.isScriptOpen() && info.isOrphan()) { + // if there are not projects that include this script info - delete it + _this.stopWatchingScriptInfo(info); + _this.deleteScriptInfo(info); + } + }); + this.printProjects(); + this.telemetryOnOpenFile(info); + return { configFileName: configFileName, configFileErrors: configFileErrors }; + }; + ProjectService.prototype.removeOrphanConfiguredProjects = function () { + var _this = this; + var toRemoveConfiguredProjects = ts.cloneMap(this.configuredProjects); + // Do not remove configured projects that are used as original projects of other + this.inferredProjects.forEach(markOriginalProjectsAsUsed); + this.externalProjects.forEach(markOriginalProjectsAsUsed); + this.configuredProjects.forEach(function (project) { + // If project has open ref (there are more than zero references from external project/open file), keep it alive as well as any project it references + if (project.hasOpenRef()) { + toRemoveConfiguredProjects.delete(project.canonicalConfigFilePath); + markOriginalProjectsAsUsed(project); + } + else { + // If the configured project for project reference has more than zero references, keep it alive + project.forEachResolvedProjectReference(function (ref) { + if (ref) { + var refProject = _this.configuredProjects.get(ref.sourceFile.path); + if (refProject && refProject.hasOpenRef()) { + toRemoveConfiguredProjects.delete(project.canonicalConfigFilePath); + } + } + }); + } + }); + // Remove all the non marked projects + toRemoveConfiguredProjects.forEach(function (project) { return _this.removeProject(project); }); + function markOriginalProjectsAsUsed(project) { + if (!project.isOrphan() && project.originalConfiguredProjects) { + project.originalConfiguredProjects.forEach(function (_value, configuredProjectPath) { return toRemoveConfiguredProjects.delete(configuredProjectPath); }); + } + } + }; + ProjectService.prototype.telemetryOnOpenFile = function (scriptInfo) { + if (this.syntaxOnly || !this.eventHandler || !scriptInfo.isJavaScript() || !ts.addToSeen(this.allJsFilesForOpenFileTelemetry, scriptInfo.path)) { + return; + } + var info = { checkJs: !!scriptInfo.getDefaultProject().getSourceFile(scriptInfo.path).checkJsDirective }; + this.eventHandler({ eventName: server.OpenFileInfoTelemetryEvent, data: { info: info } }); + }; + /** + * Close file whose contents is managed by the client + * @param filename is absolute pathname + */ + ProjectService.prototype.closeClientFile = function (uncheckedFileName) { + var info = this.getScriptInfoForNormalizedPath(server.toNormalizedPath(uncheckedFileName)); + if (info) { + this.closeOpenFile(info); + } + this.printProjects(); + }; + ProjectService.prototype.collectChanges = function (lastKnownProjectVersions, currentProjects, result) { + var _loop_28 = function (proj) { + var knownProject = ts.find(lastKnownProjectVersions, function (p) { return p.projectName === proj.getProjectName(); }); + result.push(proj.getChangesSinceVersion(knownProject && knownProject.version)); + }; + for (var _i = 0, currentProjects_1 = currentProjects; _i < currentProjects_1.length; _i++) { + var proj = currentProjects_1[_i]; + _loop_28(proj); + } + }; + /* @internal */ + ProjectService.prototype.synchronizeProjectList = function (knownProjects) { + var files = []; + this.collectChanges(knownProjects, this.externalProjects, files); + this.collectChanges(knownProjects, ts.arrayFrom(this.configuredProjects.values()), files); + this.collectChanges(knownProjects, this.inferredProjects, files); + return files; + }; + /* @internal */ + ProjectService.prototype.applyChangesInOpenFiles = function (openFiles, changedFiles, closedFiles) { + if (openFiles) { + for (var _i = 0, openFiles_1 = openFiles; _i < openFiles_1.length; _i++) { + var file = openFiles_1[_i]; + var scriptInfo = this.getScriptInfo(file.fileName); + ts.Debug.assert(!scriptInfo || !scriptInfo.isScriptOpen(), "Script should not exist and not be open already"); + var normalizedPath = scriptInfo ? scriptInfo.fileName : server.toNormalizedPath(file.fileName); + this.openClientFileWithNormalizedPath(normalizedPath, file.content, tryConvertScriptKindName(file.scriptKind), file.hasMixedContent); // TODO: GH#18217 + } + } + if (changedFiles) { + for (var _a = 0, changedFiles_2 = changedFiles; _a < changedFiles_2.length; _a++) { + var file = changedFiles_2[_a]; + var scriptInfo = this.getScriptInfo(file.fileName); + ts.Debug.assert(!!scriptInfo); + this.applyChangesToFile(scriptInfo, file.changes); + } + } + if (closedFiles) { + for (var _b = 0, closedFiles_1 = closedFiles; _b < closedFiles_1.length; _b++) { + var file = closedFiles_1[_b]; + this.closeClientFile(file); + } + } + }; + /* @internal */ + ProjectService.prototype.applyChangesToFile = function (scriptInfo, changes) { + // apply changes in reverse order + for (var i = changes.length - 1; i >= 0; i--) { + var change = changes[i]; + scriptInfo.editContent(change.span.start, change.span.start + change.span.length, change.newText); + } + }; + ProjectService.prototype.closeConfiguredProjectReferencedFromExternalProject = function (configFile) { + var configuredProject = this.findConfiguredProjectByProjectName(configFile); + if (configuredProject) { + configuredProject.deleteExternalProjectReference(); + if (!configuredProject.hasOpenRef()) { + this.removeProject(configuredProject); + return; + } + } + }; + ProjectService.prototype.closeExternalProject = function (uncheckedFileName) { + var fileName = server.toNormalizedPath(uncheckedFileName); + var configFiles = this.externalProjectToConfiguredProjectMap.get(fileName); + if (configFiles) { + for (var _i = 0, configFiles_1 = configFiles; _i < configFiles_1.length; _i++) { + var configFile = configFiles_1[_i]; + this.closeConfiguredProjectReferencedFromExternalProject(configFile); + } + this.externalProjectToConfiguredProjectMap.delete(fileName); + } + else { + // close external project + var externalProject = this.findExternalProjectByProjectName(uncheckedFileName); + if (externalProject) { + this.removeProject(externalProject); + } + } + }; + ProjectService.prototype.openExternalProjects = function (projects) { + var _this = this; + // record project list before the update + var projectsToClose = ts.arrayToMap(this.externalProjects, function (p) { return p.getProjectName(); }, function (_) { return true; }); + ts.forEachKey(this.externalProjectToConfiguredProjectMap, function (externalProjectName) { + projectsToClose.set(externalProjectName, true); + }); + for (var _i = 0, projects_3 = projects; _i < projects_3.length; _i++) { + var externalProject = projects_3[_i]; + this.openExternalProject(externalProject); + // delete project that is present in input list + projectsToClose.delete(externalProject.projectFileName); + } + // close projects that were missing in the input list + ts.forEachKey(projectsToClose, function (externalProjectName) { + _this.closeExternalProject(externalProjectName); + }); + }; + ProjectService.escapeFilenameForRegex = function (filename) { + return filename.replace(this.filenameEscapeRegexp, "\\$&"); + }; + ProjectService.prototype.resetSafeList = function () { + this.safelist = defaultTypeSafeList; + }; + ProjectService.prototype.applySafeList = function (proj) { + var _this = this; + var rootFiles = proj.rootFiles; + var typeAcquisition = proj.typeAcquisition; + ts.Debug.assert(!!typeAcquisition, "proj.typeAcquisition should be set by now"); + // If type acquisition has been explicitly disabled, do not exclude anything from the project + if (typeAcquisition.enable === false) { + return []; + } + var typeAcqInclude = typeAcquisition.include || (typeAcquisition.include = []); + var excludeRules = []; + var normalizedNames = rootFiles.map(function (f) { return ts.normalizeSlashes(f.fileName); }); + var excludedFiles = []; + var _loop_29 = function (name) { + var rule = this_3.safelist[name]; + for (var _i = 0, normalizedNames_1 = normalizedNames; _i < normalizedNames_1.length; _i++) { + var root = normalizedNames_1[_i]; + if (rule.match.test(root)) { + this_3.logger.info("Excluding files based on rule " + name + " matching file '" + root + "'"); + // If the file matches, collect its types packages and exclude rules + if (rule.types) { + for (var _a = 0, _b = rule.types; _a < _b.length; _a++) { + var type = _b[_a]; + // Best-effort de-duping here - doesn't need to be unduplicated but + // we don't want the list to become a 400-element array of just 'kendo' + if (typeAcqInclude.indexOf(type) < 0) { + typeAcqInclude.push(type); + } + } + } + if (rule.exclude) { + var _loop_31 = function (exclude) { + var processedRule = root.replace(rule.match, function () { + var groups = []; + for (var _i = 0; _i < arguments.length; _i++) { + groups[_i] = arguments[_i]; + } + return exclude.map(function (groupNumberOrString) { + // RegExp group numbers are 1-based, but the first element in groups + // is actually the original string, so it all works out in the end. + if (typeof groupNumberOrString === "number") { + if (!ts.isString(groups[groupNumberOrString])) { + // Specification was wrong - exclude nothing! + _this.logger.info("Incorrect RegExp specification in safelist rule " + name + " - not enough groups"); + // * can't appear in a filename; escape it because it's feeding into a RegExp + return "\\*"; + } + return ProjectService.escapeFilenameForRegex(groups[groupNumberOrString]); + } + return groupNumberOrString; + }).join(""); + }); + if (excludeRules.indexOf(processedRule) === -1) { + excludeRules.push(processedRule); + } + }; + for (var _c = 0, _d = rule.exclude; _c < _d.length; _c++) { + var exclude = _d[_c]; + _loop_31(exclude); + } + } + else { + // If not rules listed, add the default rule to exclude the matched file + var escaped = ProjectService.escapeFilenameForRegex(root); + if (excludeRules.indexOf(escaped) < 0) { + excludeRules.push(escaped); + } + } + } + } + }; + var this_3 = this; + for (var _i = 0, _a = Object.keys(this.safelist); _i < _a.length; _i++) { + var name = _a[_i]; + _loop_29(name); + } + var excludeRegexes = excludeRules.map(function (e) { return new RegExp(e, "i"); }); + var filesToKeep = []; + var _loop_30 = function (i) { + if (excludeRegexes.some(function (re) { return re.test(normalizedNames[i]); })) { + excludedFiles.push(normalizedNames[i]); + } + else { + var exclude = false; + if (typeAcquisition.enable || typeAcquisition.enableAutoDiscovery) { + var baseName = ts.getBaseFileName(normalizedNames[i].toLowerCase()); + if (ts.fileExtensionIs(baseName, "js")) { + var inferredTypingName = ts.removeFileExtension(baseName); + var cleanedTypingName = ts.removeMinAndVersionNumbers(inferredTypingName); + var typeName = this_4.legacySafelist.get(cleanedTypingName); + if (typeName !== undefined) { + this_4.logger.info("Excluded '" + normalizedNames[i] + "' because it matched " + cleanedTypingName + " from the legacy safelist"); + excludedFiles.push(normalizedNames[i]); + // *exclude* it from the project... + exclude = true; + // ... but *include* it in the list of types to acquire + // Same best-effort dedupe as above + if (typeAcqInclude.indexOf(typeName) < 0) { + typeAcqInclude.push(typeName); + } + } + } + } + if (!exclude) { + // Exclude any minified files that get this far + if (/^.+[\.-]min\.js$/.test(normalizedNames[i])) { + excludedFiles.push(normalizedNames[i]); + } + else { + filesToKeep.push(proj.rootFiles[i]); + } + } + } + }; + var this_4 = this; + for (var i = 0; i < proj.rootFiles.length; i++) { + _loop_30(i); + } + proj.rootFiles = filesToKeep; + return excludedFiles; + }; + ProjectService.prototype.openExternalProject = function (proj) { + // typingOptions has been deprecated and is only supported for backward compatibility + // purposes. It should be removed in future releases - use typeAcquisition instead. + if (proj.typingOptions && !proj.typeAcquisition) { + var typeAcquisition = ts.convertEnableAutoDiscoveryToEnable(proj.typingOptions); + proj.typeAcquisition = typeAcquisition; + } + proj.typeAcquisition = proj.typeAcquisition || {}; + proj.typeAcquisition.include = proj.typeAcquisition.include || []; + proj.typeAcquisition.exclude = proj.typeAcquisition.exclude || []; + if (proj.typeAcquisition.enable === undefined) { + proj.typeAcquisition.enable = server.hasNoTypeScriptSource(proj.rootFiles.map(function (f) { return f.fileName; })); + } + var excludedFiles = this.applySafeList(proj); + var tsConfigFiles; + var rootFiles = []; + for (var _i = 0, _a = proj.rootFiles; _i < _a.length; _i++) { + var file = _a[_i]; + var normalized = server.toNormalizedPath(file.fileName); + if (server.getBaseConfigFileName(normalized)) { + if (!this.syntaxOnly && this.host.fileExists(normalized)) { + (tsConfigFiles || (tsConfigFiles = [])).push(normalized); + } + } + else { + rootFiles.push(file); + } + } + // sort config files to simplify comparison later + if (tsConfigFiles) { + tsConfigFiles.sort(); + } + var externalProject = this.findExternalProjectByProjectName(proj.projectFileName); + var exisingConfigFiles; + if (externalProject) { + externalProject.excludedFiles = excludedFiles; + if (!tsConfigFiles) { + var compilerOptions = convertCompilerOptions(proj.options); + var lastFileExceededProgramSize = this.getFilenameForExceededTotalSizeLimitForNonTsFiles(proj.projectFileName, compilerOptions, proj.rootFiles, externalFilePropertyReader); + if (lastFileExceededProgramSize) { + externalProject.disableLanguageService(lastFileExceededProgramSize); + } + else { + externalProject.enableLanguageService(); + } + // external project already exists and not config files were added - update the project and return; + // The graph update here isnt postponed since any file open operation needs all updated external projects + this.updateRootAndOptionsOfNonInferredProject(externalProject, proj.rootFiles, externalFilePropertyReader, compilerOptions, proj.typeAcquisition, proj.options.compileOnSave); + externalProject.updateGraph(); + return; + } + // some config files were added to external project (that previously were not there) + // close existing project and later we'll open a set of configured projects for these files + this.closeExternalProject(proj.projectFileName); + } + else if (this.externalProjectToConfiguredProjectMap.get(proj.projectFileName)) { + // this project used to include config files + if (!tsConfigFiles) { + // config files were removed from the project - close existing external project which in turn will close configured projects + this.closeExternalProject(proj.projectFileName); + } + else { + // project previously had some config files - compare them with new set of files and close all configured projects that correspond to unused files + var oldConfigFiles = this.externalProjectToConfiguredProjectMap.get(proj.projectFileName); + var iNew = 0; + var iOld = 0; + while (iNew < tsConfigFiles.length && iOld < oldConfigFiles.length) { + var newConfig = tsConfigFiles[iNew]; + var oldConfig = oldConfigFiles[iOld]; + if (oldConfig < newConfig) { + this.closeConfiguredProjectReferencedFromExternalProject(oldConfig); + iOld++; + } + else if (oldConfig > newConfig) { + iNew++; + } + else { + // record existing config files so avoid extra add-refs + (exisingConfigFiles || (exisingConfigFiles = [])).push(oldConfig); + iOld++; + iNew++; + } + } + for (var i = iOld; i < oldConfigFiles.length; i++) { + // projects for all remaining old config files should be closed + this.closeConfiguredProjectReferencedFromExternalProject(oldConfigFiles[i]); + } + } + } + if (tsConfigFiles) { + // store the list of tsconfig files that belong to the external project + this.externalProjectToConfiguredProjectMap.set(proj.projectFileName, tsConfigFiles); + for (var _b = 0, tsConfigFiles_1 = tsConfigFiles; _b < tsConfigFiles_1.length; _b++) { + var tsconfigFile = tsConfigFiles_1[_b]; + var project = this.findConfiguredProjectByProjectName(tsconfigFile); + if (!project) { + // errors are stored in the project, do not need to update the graph + project = this.getHostPreferences().lazyConfiguredProjectsFromExternalProject ? + this.createConfiguredProjectWithDelayLoad(tsconfigFile, "Creating configured project in external project: " + proj.projectFileName) : + this.createLoadAndUpdateConfiguredProject(tsconfigFile, "Creating configured project in external project: " + proj.projectFileName); + } + if (project && !ts.contains(exisingConfigFiles, tsconfigFile)) { + // keep project alive even if no documents are opened - its lifetime is bound to the lifetime of containing external project + project.addExternalProjectReference(); + } + } + } + else { + // no config files - remove the item from the collection + // Create external project and update its graph, do not delay update since + // any file open operation needs all updated external projects + this.externalProjectToConfiguredProjectMap.delete(proj.projectFileName); + var project = this.createExternalProject(proj.projectFileName, rootFiles, proj.options, proj.typeAcquisition, excludedFiles); + project.updateGraph(); + } + }; + ProjectService.prototype.hasDeferredExtension = function () { + for (var _i = 0, _a = this.hostConfiguration.extraFileExtensions; _i < _a.length; _i++) { // TODO: GH#18217 + var extension = _a[_i]; + if (extension.scriptKind === 7 /* Deferred */) { + return true; + } + } + return false; + }; + ProjectService.prototype.configurePlugin = function (args) { + // For any projects that already have the plugin loaded, configure the plugin + this.forEachEnabledProject(function (project) { return project.onPluginConfigurationChanged(args.pluginName, args.configuration); }); + // Also save the current configuration to pass on to any projects that are yet to be loaded. + // If a plugin is configured twice, only the latest configuration will be remembered. + this.currentPluginConfigOverrides = this.currentPluginConfigOverrides || ts.createMap(); + this.currentPluginConfigOverrides.set(args.pluginName, args.configuration); + }; + /** Makes a filename safe to insert in a RegExp */ + ProjectService.filenameEscapeRegexp = /[-\/\\^$*+?.()|[\]{}]/g; + return ProjectService; + }()); + server.ProjectService = ProjectService; + /* @internal */ + function isConfigFile(config) { + return config.kind !== undefined; + } + server.isConfigFile = isConfigFile; + function printProjectsWithCounter(projects, counter) { + for (var _i = 0, projects_4 = projects; _i < projects_4.length; _i++) { + var project = projects_4[_i]; + project.print(counter); + counter++; + } + return counter; + } + })(server = ts.server || (ts.server = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + var server; + (function (server) { + server.nullCancellationToken = { + isCancellationRequested: function () { return false; }, + setRequest: function () { return void 0; }, + resetRequest: function () { return void 0; } + }; + function hrTimeToMilliseconds(time) { + var seconds = time[0]; + var nanoseconds = time[1]; + return ((1e9 * seconds) + nanoseconds) / 1000000.0; + } + function isDeclarationFileInJSOnlyNonConfiguredProject(project, file) { + // Checking for semantic diagnostics is an expensive process. We want to avoid it if we + // know for sure it is not needed. + // For instance, .d.ts files injected by ATA automatically do not produce any relevant + // errors to a JS- only project. + // + // Note that configured projects can set skipLibCheck (on by default in jsconfig.json) to + // disable checking for declaration files. We only need to verify for inferred projects (e.g. + // miscellaneous context in VS) and external projects(e.g.VS.csproj project) with only JS + // files. + // + // We still want to check .js files in a JS-only inferred or external project (e.g. if the + // file has '// @ts-check'). + if ((project.projectKind === server.ProjectKind.Inferred || project.projectKind === server.ProjectKind.External) && + project.isJsOnlyProject()) { + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + return scriptInfo && !scriptInfo.isJavaScript(); + } + return false; + } + function formatDiag(fileName, project, diag) { + var scriptInfo = project.getScriptInfoForNormalizedPath(fileName); // TODO: GH#18217 + return { + start: scriptInfo.positionToLineOffset(diag.start), + end: scriptInfo.positionToLineOffset(diag.start + diag.length), + text: ts.flattenDiagnosticMessageText(diag.messageText, "\n"), + code: diag.code, + category: ts.diagnosticCategoryName(diag), + reportsUnnecessary: diag.reportsUnnecessary, + source: diag.source, + relatedInformation: ts.map(diag.relatedInformation, formatRelatedInformation), + }; + } + function formatRelatedInformation(info) { + if (!info.file) { + return { + message: ts.flattenDiagnosticMessageText(info.messageText, "\n"), + category: ts.diagnosticCategoryName(info), + code: info.code + }; + } + return { + span: { + start: convertToLocation(ts.getLineAndCharacterOfPosition(info.file, info.start)), + end: convertToLocation(ts.getLineAndCharacterOfPosition(info.file, info.start + info.length)), + file: info.file.fileName + }, + message: ts.flattenDiagnosticMessageText(info.messageText, "\n"), + category: ts.diagnosticCategoryName(info), + code: info.code + }; + } + function convertToLocation(lineAndCharacter) { + return { line: lineAndCharacter.line + 1, offset: lineAndCharacter.character + 1 }; + } + function formatConfigFileDiag(diag, includeFileName) { + var start = (diag.file && convertToLocation(ts.getLineAndCharacterOfPosition(diag.file, diag.start))); // TODO: GH#18217 + var end = (diag.file && convertToLocation(ts.getLineAndCharacterOfPosition(diag.file, diag.start + diag.length))); // TODO: GH#18217 + var text = ts.flattenDiagnosticMessageText(diag.messageText, "\n"); + var code = diag.code, source = diag.source; + var category = ts.diagnosticCategoryName(diag); + var common = { + start: start, + end: end, + text: text, + code: code, + category: category, + reportsUnnecessary: diag.reportsUnnecessary, + source: source, + relatedInformation: ts.map(diag.relatedInformation, formatRelatedInformation), + }; + return includeFileName + ? __assign({}, common, { fileName: diag.file && diag.file.fileName }) : common; + } + function allEditsBeforePos(edits, pos) { + return edits.every(function (edit) { return ts.textSpanEnd(edit.span) < pos; }); + } + server.CommandNames = server.protocol.CommandTypes; // tslint:disable-line variable-name + function formatMessage(msg, logger, byteLength, newLine) { + var verboseLogging = logger.hasLevel(server.LogLevel.verbose); + var json = JSON.stringify(msg); + if (verboseLogging) { + logger.info(msg.type + ":" + server.indent(json)); + } + var len = byteLength(json, "utf8"); + return "Content-Length: " + (1 + len) + "\r\n\r\n" + json + newLine; + } + server.formatMessage = formatMessage; + /** + * Represents operation that can schedule its next step to be executed later. + * Scheduling is done via instance of NextStep. If on current step subsequent step was not scheduled - operation is assumed to be completed. + */ + var MultistepOperation = /** @class */ (function () { + function MultistepOperation(operationHost) { + this.operationHost = operationHost; + } + MultistepOperation.prototype.startNew = function (action) { + this.complete(); + this.requestId = this.operationHost.getCurrentRequestId(); + this.executeAction(action); + }; + MultistepOperation.prototype.complete = function () { + if (this.requestId !== undefined) { + this.operationHost.sendRequestCompletedEvent(this.requestId); + this.requestId = undefined; + } + this.setTimerHandle(undefined); + this.setImmediateId(undefined); + }; + MultistepOperation.prototype.immediate = function (action) { + var _this = this; + var requestId = this.requestId; + ts.Debug.assert(requestId === this.operationHost.getCurrentRequestId(), "immediate: incorrect request id"); + this.setImmediateId(this.operationHost.getServerHost().setImmediate(function () { + _this.immediateId = undefined; + _this.operationHost.executeWithRequestId(requestId, function () { return _this.executeAction(action); }); + })); + }; + MultistepOperation.prototype.delay = function (ms, action) { + var _this = this; + var requestId = this.requestId; + ts.Debug.assert(requestId === this.operationHost.getCurrentRequestId(), "delay: incorrect request id"); + this.setTimerHandle(this.operationHost.getServerHost().setTimeout(function () { + _this.timerHandle = undefined; + _this.operationHost.executeWithRequestId(requestId, function () { return _this.executeAction(action); }); + }, ms)); + }; + MultistepOperation.prototype.executeAction = function (action) { + var stop = false; + try { + if (this.operationHost.isCancellationRequested()) { + stop = true; + } + else { + action(this); + } + } + catch (e) { + stop = true; + // ignore cancellation request + if (!(e instanceof ts.OperationCanceledException)) { + this.operationHost.logError(e, "delayed processing of request " + this.requestId); + } + } + if (stop || !this.hasPendingWork()) { + this.complete(); + } + }; + MultistepOperation.prototype.setTimerHandle = function (timerHandle) { + if (this.timerHandle !== undefined) { + this.operationHost.getServerHost().clearTimeout(this.timerHandle); + } + this.timerHandle = timerHandle; + }; + MultistepOperation.prototype.setImmediateId = function (immediateId) { + if (this.immediateId !== undefined) { + this.operationHost.getServerHost().clearImmediate(this.immediateId); + } + this.immediateId = immediateId; + }; + MultistepOperation.prototype.hasPendingWork = function () { + return !!this.timerHandle || !!this.immediateId; + }; + return MultistepOperation; + }()); + /** @internal */ + function toEvent(eventName, body) { + return { + seq: 0, + type: "event", + event: eventName, + body: body + }; + } + server.toEvent = toEvent; + /** + * This helper function processes a list of projects and return the concatenated, sortd and deduplicated output of processing each project. + */ + function combineProjectOutput(defaultValue, getValue, projects, action) { + var outputs = ts.flatMapToMutable(ts.isArray(projects) ? projects : projects.projects, function (project) { return action(project, defaultValue); }); + if (!ts.isArray(projects) && projects.symLinkedProjects) { + projects.symLinkedProjects.forEach(function (projects, path) { + var value = getValue(path); + outputs.push.apply(outputs, ts.flatMap(projects, function (project) { return action(project, value); })); + }); + } + return ts.deduplicate(outputs, ts.equateValues); + } + function combineProjectOutputFromEveryProject(projectService, action, areEqual) { + var outputs = []; + projectService.forEachEnabledProject(function (project) { + var theseOutputs = action(project); + outputs.push.apply(outputs, theseOutputs.filter(function (output) { return !outputs.some(function (o) { return areEqual(o, output); }); })); + }); + return outputs; + } + function combineProjectOutputWhileOpeningReferencedProjects(projects, defaultProject, action, getLocation, resultsEqual) { + var outputs = []; + combineProjectOutputWorker(projects, defaultProject, + /*initialLocation*/ undefined, function (_a, tryAddToTodo) { + var project = _a.project; + for (var _i = 0, _b = action(project); _i < _b.length; _i++) { + var output = _b[_i]; + if (!ts.contains(outputs, output, resultsEqual) && !tryAddToTodo(project, getLocation(output))) { + outputs.push(output); + } + } + }, + /*getDefinition*/ undefined); + return outputs; + } + function combineProjectOutputForRenameLocations(projects, defaultProject, initialLocation, findInStrings, findInComments) { + var outputs = []; + combineProjectOutputWorker(projects, defaultProject, initialLocation, function (_a, tryAddToTodo) { + var project = _a.project, location = _a.location; + for (var _i = 0, _b = project.getLanguageService().findRenameLocations(location.fileName, location.pos, findInStrings, findInComments) || server.emptyArray; _i < _b.length; _i++) { + var output = _b[_i]; + if (!ts.contains(outputs, output, ts.documentSpansEqual) && !tryAddToTodo(project, documentSpanLocation(output))) { + outputs.push(output); + } + } + }, function () { return getDefinitionLocation(defaultProject, initialLocation); }); + return outputs; + } + function getDefinitionLocation(defaultProject, initialLocation) { + var infos = defaultProject.getLanguageService().getDefinitionAtPosition(initialLocation.fileName, initialLocation.pos); + var info = infos && ts.firstOrUndefined(infos); + return info && { fileName: info.fileName, pos: info.textSpan.start }; + } + function combineProjectOutputForReferences(projects, defaultProject, initialLocation) { + var outputs = []; + combineProjectOutputWorker(projects, defaultProject, initialLocation, function (_a, getMappedLocation) { + var project = _a.project, location = _a.location; + var _loop_32 = function (outputReferencedSymbol) { + var mappedDefinitionFile = getMappedLocation(project, documentSpanLocation(outputReferencedSymbol.definition)); + var definition = mappedDefinitionFile === undefined ? outputReferencedSymbol.definition : __assign({}, outputReferencedSymbol.definition, { textSpan: ts.createTextSpan(mappedDefinitionFile.pos, outputReferencedSymbol.definition.textSpan.length), fileName: mappedDefinitionFile.fileName }); + var symbolToAddTo = ts.find(outputs, function (o) { return ts.documentSpansEqual(o.definition, definition); }); + if (!symbolToAddTo) { + symbolToAddTo = { definition: definition, references: [] }; + outputs.push(symbolToAddTo); + } + for (var _i = 0, _a = outputReferencedSymbol.references; _i < _a.length; _i++) { + var ref = _a[_i]; + // If it's in a mapped file, that is added to the todo list by `getMappedLocation`. + if (!ts.contains(symbolToAddTo.references, ref, ts.documentSpansEqual) && !getMappedLocation(project, documentSpanLocation(ref))) { + symbolToAddTo.references.push(ref); + } + } + }; + for (var _i = 0, _b = project.getLanguageService().findReferences(location.fileName, location.pos) || server.emptyArray; _i < _b.length; _i++) { + var outputReferencedSymbol = _b[_i]; + _loop_32(outputReferencedSymbol); + } + }, function () { return getDefinitionLocation(defaultProject, initialLocation); }); + return outputs.filter(function (o) { return o.references.length !== 0; }); + } + function forEachProjectInProjects(projects, path, cb) { + for (var _i = 0, _a = ts.isArray(projects) ? projects : projects.projects; _i < _a.length; _i++) { + var project = _a[_i]; + cb(project, path); + } + if (!ts.isArray(projects) && projects.symLinkedProjects) { + projects.symLinkedProjects.forEach(function (symlinkedProjects, symlinkedPath) { + for (var _i = 0, symlinkedProjects_1 = symlinkedProjects; _i < symlinkedProjects_1.length; _i++) { + var project = symlinkedProjects_1[_i]; + cb(project, symlinkedPath); + } + }); + } + } + function combineProjectOutputWorker(projects, defaultProject, initialLocation, cb, getDefinition) { + var projectService = defaultProject.projectService; + var toDo; + var seenProjects = ts.createMap(); + forEachProjectInProjects(projects, initialLocation && initialLocation.fileName, function (project, path) { + // TLocation shoud be either `DocumentPosition` or `undefined`. Since `initialLocation` is `TLocation` this cast should be valid. + var location = (initialLocation ? { fileName: path, pos: initialLocation.pos } : undefined); + toDo = callbackProjectAndLocation({ project: project, location: location }, projectService, toDo, seenProjects, cb); + }); + // After initial references are collected, go over every other project and see if it has a reference for the symbol definition. + if (getDefinition) { + var memGetDefinition_1 = ts.memoize(getDefinition); + projectService.forEachEnabledProject(function (project) { + if (!ts.addToSeen(seenProjects, project.projectName)) + return; + var definition = getDefinitionInProject(memGetDefinition_1(), defaultProject, project); + if (definition) { + toDo = callbackProjectAndLocation({ project: project, location: definition }, projectService, toDo, seenProjects, cb); + } + }); + } + while (toDo && toDo.length) { + toDo = callbackProjectAndLocation(ts.Debug.assertDefined(toDo.pop()), projectService, toDo, seenProjects, cb); + } + } + function getDefinitionInProject(definition, definingProject, project) { + if (!definition || project.containsFile(server.toNormalizedPath(definition.fileName))) + return definition; + var mappedDefinition = definingProject.getLanguageService().getSourceMapper().tryGetGeneratedPosition(definition); + return mappedDefinition && project.containsFile(server.toNormalizedPath(mappedDefinition.fileName)) ? mappedDefinition : undefined; + } + function callbackProjectAndLocation(projectAndLocation, projectService, toDo, seenProjects, cb) { + if (projectAndLocation.project.getCancellationToken().isCancellationRequested()) + return undefined; // Skip rest of toDo if cancelled + cb(projectAndLocation, function (project, location) { + seenProjects.set(projectAndLocation.project.projectName, true); + var originalLocation = projectService.getOriginalLocationEnsuringConfiguredProject(project, location); + if (!originalLocation) + return undefined; + var originalScriptInfo = projectService.getScriptInfo(originalLocation.fileName); + toDo = toDo || []; + for (var _i = 0, _a = originalScriptInfo.containingProjects; _i < _a.length; _i++) { + var project_1 = _a[_i]; + addToTodo({ project: project_1, location: originalLocation }, toDo, seenProjects); + } + var symlinkedProjectsMap = projectService.getSymlinkedProjects(originalScriptInfo); + if (symlinkedProjectsMap) { + symlinkedProjectsMap.forEach(function (symlinkedProjects) { + for (var _i = 0, symlinkedProjects_2 = symlinkedProjects; _i < symlinkedProjects_2.length; _i++) { + var symlinkedProject = symlinkedProjects_2[_i]; + addToTodo({ project: symlinkedProject, location: originalLocation }, toDo, seenProjects); + } + }); + } + return originalLocation; + }); + return toDo; + } + function addToTodo(projectAndLocation, toDo, seenProjects) { + if (ts.addToSeen(seenProjects, projectAndLocation.project.projectName)) + toDo.push(projectAndLocation); + } + function documentSpanLocation(_a) { + var fileName = _a.fileName, textSpan = _a.textSpan; + return { fileName: fileName, pos: textSpan.start }; + } + function getMappedLocation(location, projectService, project) { + var mapsTo = project.getSourceMapper().tryGetSourcePosition(location); + return mapsTo && projectService.fileExists(server.toNormalizedPath(mapsTo.fileName)) ? mapsTo : undefined; + } + var Session = /** @class */ (function () { + function Session(opts) { + var _a; + var _this = this; + this.changeSeq = 0; + this.handlers = ts.createMapFromTemplate((_a = {}, + _a[server.CommandNames.Status] = function () { + var response = { version: ts.version }; + return _this.requiredResponse(response); + }, + _a[server.CommandNames.OpenExternalProject] = function (request) { + _this.projectService.openExternalProject(request.arguments); + // TODO: GH#20447 report errors + return _this.requiredResponse(/*response*/ true); + }, + _a[server.CommandNames.OpenExternalProjects] = function (request) { + _this.projectService.openExternalProjects(request.arguments.projects); + // TODO: GH#20447 report errors + return _this.requiredResponse(/*response*/ true); + }, + _a[server.CommandNames.CloseExternalProject] = function (request) { + _this.projectService.closeExternalProject(request.arguments.projectFileName); + // TODO: GH#20447 report errors + return _this.requiredResponse(/*response*/ true); + }, + _a[server.CommandNames.SynchronizeProjectList] = function (request) { + var result = _this.projectService.synchronizeProjectList(request.arguments.knownProjects); + if (!result.some(function (p) { return p.projectErrors && p.projectErrors.length !== 0; })) { + return _this.requiredResponse(result); + } + var converted = ts.map(result, function (p) { + if (!p.projectErrors || p.projectErrors.length === 0) { + return p; + } + return { + info: p.info, + changes: p.changes, + files: p.files, + projectErrors: _this.convertToDiagnosticsWithLinePosition(p.projectErrors, /*scriptInfo*/ undefined) + }; + }); + return _this.requiredResponse(converted); + }, + _a[server.CommandNames.ApplyChangedToOpenFiles] = function (request) { + _this.changeSeq++; + _this.projectService.applyChangesInOpenFiles(request.arguments.openFiles, request.arguments.changedFiles, request.arguments.closedFiles); // TODO: GH#18217 + // TODO: report errors + return _this.requiredResponse(/*response*/ true); + }, + _a[server.CommandNames.Exit] = function () { + _this.exit(); + return _this.notRequired(); + }, + _a[server.CommandNames.Definition] = function (request) { + return _this.requiredResponse(_this.getDefinition(request.arguments, /*simplifiedResult*/ true)); + }, + _a[server.CommandNames.DefinitionFull] = function (request) { + return _this.requiredResponse(_this.getDefinition(request.arguments, /*simplifiedResult*/ false)); + }, + _a[server.CommandNames.DefinitionAndBoundSpan] = function (request) { + return _this.requiredResponse(_this.getDefinitionAndBoundSpan(request.arguments, /*simplifiedResult*/ true)); + }, + _a[server.CommandNames.DefinitionAndBoundSpanFull] = function (request) { + return _this.requiredResponse(_this.getDefinitionAndBoundSpan(request.arguments, /*simplifiedResult*/ false)); + }, + _a[server.CommandNames.EmitOutput] = function (request) { + return _this.requiredResponse(_this.getEmitOutput(request.arguments)); + }, + _a[server.CommandNames.TypeDefinition] = function (request) { + return _this.requiredResponse(_this.getTypeDefinition(request.arguments)); + }, + _a[server.CommandNames.Implementation] = function (request) { + return _this.requiredResponse(_this.getImplementation(request.arguments, /*simplifiedResult*/ true)); + }, + _a[server.CommandNames.ImplementationFull] = function (request) { + return _this.requiredResponse(_this.getImplementation(request.arguments, /*simplifiedResult*/ false)); + }, + _a[server.CommandNames.References] = function (request) { + return _this.requiredResponse(_this.getReferences(request.arguments, /*simplifiedResult*/ true)); + }, + _a[server.CommandNames.ReferencesFull] = function (request) { + return _this.requiredResponse(_this.getReferences(request.arguments, /*simplifiedResult*/ false)); + }, + _a[server.CommandNames.Rename] = function (request) { + return _this.requiredResponse(_this.getRenameLocations(request.arguments, /*simplifiedResult*/ true)); + }, + _a[server.CommandNames.RenameLocationsFull] = function (request) { + return _this.requiredResponse(_this.getRenameLocations(request.arguments, /*simplifiedResult*/ false)); + }, + _a[server.CommandNames.RenameInfoFull] = function (request) { + return _this.requiredResponse(_this.getRenameInfo(request.arguments)); + }, + _a[server.CommandNames.Open] = function (request) { + _this.openClientFile(server.toNormalizedPath(request.arguments.file), request.arguments.fileContent, server.convertScriptKindName(request.arguments.scriptKindName), // TODO: GH#18217 + request.arguments.projectRootPath ? server.toNormalizedPath(request.arguments.projectRootPath) : undefined); + return _this.notRequired(); + }, + _a[server.CommandNames.Quickinfo] = function (request) { + return _this.requiredResponse(_this.getQuickInfoWorker(request.arguments, /*simplifiedResult*/ true)); + }, + _a[server.CommandNames.QuickinfoFull] = function (request) { + return _this.requiredResponse(_this.getQuickInfoWorker(request.arguments, /*simplifiedResult*/ false)); + }, + _a[server.CommandNames.GetOutliningSpans] = function (request) { + return _this.requiredResponse(_this.getOutliningSpans(request.arguments, /*simplifiedResult*/ true)); + }, + _a[server.CommandNames.GetOutliningSpansFull] = function (request) { + return _this.requiredResponse(_this.getOutliningSpans(request.arguments, /*simplifiedResult*/ false)); + }, + _a[server.CommandNames.TodoComments] = function (request) { + return _this.requiredResponse(_this.getTodoComments(request.arguments)); + }, + _a[server.CommandNames.Indentation] = function (request) { + return _this.requiredResponse(_this.getIndentation(request.arguments)); + }, + _a[server.CommandNames.NameOrDottedNameSpan] = function (request) { + return _this.requiredResponse(_this.getNameOrDottedNameSpan(request.arguments)); + }, + _a[server.CommandNames.BreakpointStatement] = function (request) { + return _this.requiredResponse(_this.getBreakpointStatement(request.arguments)); + }, + _a[server.CommandNames.BraceCompletion] = function (request) { + return _this.requiredResponse(_this.isValidBraceCompletion(request.arguments)); + }, + _a[server.CommandNames.DocCommentTemplate] = function (request) { + return _this.requiredResponse(_this.getDocCommentTemplate(request.arguments)); + }, + _a[server.CommandNames.GetSpanOfEnclosingComment] = function (request) { + return _this.requiredResponse(_this.getSpanOfEnclosingComment(request.arguments)); + }, + _a[server.CommandNames.Format] = function (request) { + return _this.requiredResponse(_this.getFormattingEditsForRange(request.arguments)); + }, + _a[server.CommandNames.Formatonkey] = function (request) { + return _this.requiredResponse(_this.getFormattingEditsAfterKeystroke(request.arguments)); + }, + _a[server.CommandNames.FormatFull] = function (request) { + return _this.requiredResponse(_this.getFormattingEditsForDocumentFull(request.arguments)); + }, + _a[server.CommandNames.FormatonkeyFull] = function (request) { + return _this.requiredResponse(_this.getFormattingEditsAfterKeystrokeFull(request.arguments)); + }, + _a[server.CommandNames.FormatRangeFull] = function (request) { + return _this.requiredResponse(_this.getFormattingEditsForRangeFull(request.arguments)); + }, + _a[server.CommandNames.CompletionInfo] = function (request) { + return _this.requiredResponse(_this.getCompletions(request.arguments, server.CommandNames.CompletionInfo)); + }, + _a[server.CommandNames.Completions] = function (request) { + return _this.requiredResponse(_this.getCompletions(request.arguments, server.CommandNames.Completions)); + }, + _a[server.CommandNames.CompletionsFull] = function (request) { + return _this.requiredResponse(_this.getCompletions(request.arguments, server.CommandNames.CompletionsFull)); + }, + _a[server.CommandNames.CompletionDetails] = function (request) { + return _this.requiredResponse(_this.getCompletionEntryDetails(request.arguments, /*simplifiedResult*/ true)); + }, + _a[server.CommandNames.CompletionDetailsFull] = function (request) { + return _this.requiredResponse(_this.getCompletionEntryDetails(request.arguments, /*simplifiedResult*/ false)); + }, + _a[server.CommandNames.CompileOnSaveAffectedFileList] = function (request) { + return _this.requiredResponse(_this.getCompileOnSaveAffectedFileList(request.arguments)); + }, + _a[server.CommandNames.CompileOnSaveEmitFile] = function (request) { + return _this.requiredResponse(_this.emitFile(request.arguments)); + }, + _a[server.CommandNames.SignatureHelp] = function (request) { + return _this.requiredResponse(_this.getSignatureHelpItems(request.arguments, /*simplifiedResult*/ true)); + }, + _a[server.CommandNames.SignatureHelpFull] = function (request) { + return _this.requiredResponse(_this.getSignatureHelpItems(request.arguments, /*simplifiedResult*/ false)); + }, + _a[server.CommandNames.CompilerOptionsDiagnosticsFull] = function (request) { + return _this.requiredResponse(_this.getCompilerOptionsDiagnostics(request.arguments)); + }, + _a[server.CommandNames.EncodedSemanticClassificationsFull] = function (request) { + return _this.requiredResponse(_this.getEncodedSemanticClassifications(request.arguments)); + }, + _a[server.CommandNames.Cleanup] = function () { + _this.cleanup(); + return _this.requiredResponse(/*response*/ true); + }, + _a[server.CommandNames.SemanticDiagnosticsSync] = function (request) { + return _this.requiredResponse(_this.getSemanticDiagnosticsSync(request.arguments)); + }, + _a[server.CommandNames.SyntacticDiagnosticsSync] = function (request) { + return _this.requiredResponse(_this.getSyntacticDiagnosticsSync(request.arguments)); + }, + _a[server.CommandNames.SuggestionDiagnosticsSync] = function (request) { + return _this.requiredResponse(_this.getSuggestionDiagnosticsSync(request.arguments)); + }, + _a[server.CommandNames.Geterr] = function (request) { + _this.errorCheck.startNew(function (next) { return _this.getDiagnostics(next, request.arguments.delay, request.arguments.files); }); + return _this.notRequired(); + }, + _a[server.CommandNames.GeterrForProject] = function (request) { + _this.errorCheck.startNew(function (next) { return _this.getDiagnosticsForProject(next, request.arguments.delay, request.arguments.file); }); + return _this.notRequired(); + }, + _a[server.CommandNames.Change] = function (request) { + _this.change(request.arguments); + return _this.notRequired(); + }, + _a[server.CommandNames.Configure] = function (request) { + _this.projectService.setHostConfiguration(request.arguments); + _this.doOutput(/*info*/ undefined, server.CommandNames.Configure, request.seq, /*success*/ true); + return _this.notRequired(); + }, + _a[server.CommandNames.Reload] = function (request) { + _this.reload(request.arguments, request.seq); + return _this.requiredResponse({ reloadFinished: true }); + }, + _a[server.CommandNames.Saveto] = function (request) { + var savetoArgs = request.arguments; + _this.saveToTmp(savetoArgs.file, savetoArgs.tmpfile); + return _this.notRequired(); + }, + _a[server.CommandNames.Close] = function (request) { + var closeArgs = request.arguments; + _this.closeClientFile(closeArgs.file); + return _this.notRequired(); + }, + _a[server.CommandNames.Navto] = function (request) { + return _this.requiredResponse(_this.getNavigateToItems(request.arguments, /*simplifiedResult*/ true)); + }, + _a[server.CommandNames.NavtoFull] = function (request) { + return _this.requiredResponse(_this.getNavigateToItems(request.arguments, /*simplifiedResult*/ false)); + }, + _a[server.CommandNames.Brace] = function (request) { + return _this.requiredResponse(_this.getBraceMatching(request.arguments, /*simplifiedResult*/ true)); + }, + _a[server.CommandNames.BraceFull] = function (request) { + return _this.requiredResponse(_this.getBraceMatching(request.arguments, /*simplifiedResult*/ false)); + }, + _a[server.CommandNames.NavBar] = function (request) { + return _this.requiredResponse(_this.getNavigationBarItems(request.arguments, /*simplifiedResult*/ true)); + }, + _a[server.CommandNames.NavBarFull] = function (request) { + return _this.requiredResponse(_this.getNavigationBarItems(request.arguments, /*simplifiedResult*/ false)); + }, + _a[server.CommandNames.NavTree] = function (request) { + return _this.requiredResponse(_this.getNavigationTree(request.arguments, /*simplifiedResult*/ true)); + }, + _a[server.CommandNames.NavTreeFull] = function (request) { + return _this.requiredResponse(_this.getNavigationTree(request.arguments, /*simplifiedResult*/ false)); + }, + _a[server.CommandNames.Occurrences] = function (request) { + return _this.requiredResponse(_this.getOccurrences(request.arguments)); + }, + _a[server.CommandNames.DocumentHighlights] = function (request) { + return _this.requiredResponse(_this.getDocumentHighlights(request.arguments, /*simplifiedResult*/ true)); + }, + _a[server.CommandNames.DocumentHighlightsFull] = function (request) { + return _this.requiredResponse(_this.getDocumentHighlights(request.arguments, /*simplifiedResult*/ false)); + }, + _a[server.CommandNames.CompilerOptionsForInferredProjects] = function (request) { + _this.setCompilerOptionsForInferredProjects(request.arguments); + return _this.requiredResponse(/*response*/ true); + }, + _a[server.CommandNames.ProjectInfo] = function (request) { + return _this.requiredResponse(_this.getProjectInfo(request.arguments)); + }, + _a[server.CommandNames.ReloadProjects] = function () { + _this.projectService.reloadProjects(); + return _this.notRequired(); + }, + _a[server.CommandNames.JsxClosingTag] = function (request) { + return _this.requiredResponse(_this.getJsxClosingTag(request.arguments)); + }, + _a[server.CommandNames.GetCodeFixes] = function (request) { + return _this.requiredResponse(_this.getCodeFixes(request.arguments, /*simplifiedResult*/ true)); + }, + _a[server.CommandNames.GetCodeFixesFull] = function (request) { + return _this.requiredResponse(_this.getCodeFixes(request.arguments, /*simplifiedResult*/ false)); + }, + _a[server.CommandNames.GetCombinedCodeFix] = function (request) { + return _this.requiredResponse(_this.getCombinedCodeFix(request.arguments, /*simplifiedResult*/ true)); + }, + _a[server.CommandNames.GetCombinedCodeFixFull] = function (request) { + return _this.requiredResponse(_this.getCombinedCodeFix(request.arguments, /*simplifiedResult*/ false)); + }, + _a[server.CommandNames.ApplyCodeActionCommand] = function (request) { + return _this.requiredResponse(_this.applyCodeActionCommand(request.arguments)); + }, + _a[server.CommandNames.GetSupportedCodeFixes] = function () { + return _this.requiredResponse(_this.getSupportedCodeFixes()); + }, + _a[server.CommandNames.GetApplicableRefactors] = function (request) { + return _this.requiredResponse(_this.getApplicableRefactors(request.arguments)); + }, + _a[server.CommandNames.GetEditsForRefactor] = function (request) { + return _this.requiredResponse(_this.getEditsForRefactor(request.arguments, /*simplifiedResult*/ true)); + }, + _a[server.CommandNames.GetEditsForRefactorFull] = function (request) { + return _this.requiredResponse(_this.getEditsForRefactor(request.arguments, /*simplifiedResult*/ false)); + }, + _a[server.CommandNames.OrganizeImports] = function (request) { + return _this.requiredResponse(_this.organizeImports(request.arguments, /*simplifiedResult*/ true)); + }, + _a[server.CommandNames.OrganizeImportsFull] = function (request) { + return _this.requiredResponse(_this.organizeImports(request.arguments, /*simplifiedResult*/ false)); + }, + _a[server.CommandNames.GetEditsForFileRename] = function (request) { + return _this.requiredResponse(_this.getEditsForFileRename(request.arguments, /*simplifiedResult*/ true)); + }, + _a[server.CommandNames.GetEditsForFileRenameFull] = function (request) { + return _this.requiredResponse(_this.getEditsForFileRename(request.arguments, /*simplifiedResult*/ false)); + }, + _a[server.CommandNames.ConfigurePlugin] = function (request) { + _this.configurePlugin(request.arguments); + return _this.notRequired(); + }, + _a)); + this.host = opts.host; + this.cancellationToken = opts.cancellationToken; + this.typingsInstaller = opts.typingsInstaller; + this.byteLength = opts.byteLength; + this.hrtime = opts.hrtime; + this.logger = opts.logger; + this.canUseEvents = opts.canUseEvents; + this.suppressDiagnosticEvents = opts.suppressDiagnosticEvents; + this.noGetErrOnBackgroundUpdate = opts.noGetErrOnBackgroundUpdate; + var throttleWaitMilliseconds = opts.throttleWaitMilliseconds; + this.eventHandler = this.canUseEvents + ? opts.eventHandler || (function (event) { return _this.defaultEventHandler(event); }) + : undefined; + var multistepOperationHost = { + executeWithRequestId: function (requestId, action) { return _this.executeWithRequestId(requestId, action); }, + getCurrentRequestId: function () { return _this.currentRequestId; }, + getServerHost: function () { return _this.host; }, + logError: function (err, cmd) { return _this.logError(err, cmd); }, + sendRequestCompletedEvent: function (requestId) { return _this.sendRequestCompletedEvent(requestId); }, + isCancellationRequested: function () { return _this.cancellationToken.isCancellationRequested(); } + }; + this.errorCheck = new MultistepOperation(multistepOperationHost); + var settings = { + host: this.host, + logger: this.logger, + cancellationToken: this.cancellationToken, + useSingleInferredProject: opts.useSingleInferredProject, + useInferredProjectPerProjectRoot: opts.useInferredProjectPerProjectRoot, + typingsInstaller: this.typingsInstaller, + throttleWaitMilliseconds: throttleWaitMilliseconds, + eventHandler: this.eventHandler, + suppressDiagnosticEvents: this.suppressDiagnosticEvents, + globalPlugins: opts.globalPlugins, + pluginProbeLocations: opts.pluginProbeLocations, + allowLocalPluginLoads: opts.allowLocalPluginLoads, + typesMapLocation: opts.typesMapLocation, + syntaxOnly: opts.syntaxOnly, + }; + this.projectService = new server.ProjectService(settings); + this.gcTimer = new server.GcTimer(this.host, /*delay*/ 7000, this.logger); + } + Session.prototype.sendRequestCompletedEvent = function (requestId) { + this.event({ request_seq: requestId }, "requestCompleted"); + }; + Session.prototype.defaultEventHandler = function (event) { + switch (event.eventName) { + case server.ProjectsUpdatedInBackgroundEvent: + var openFiles = event.data.openFiles; + this.projectsUpdatedInBackgroundEvent(openFiles); + break; + case server.ProjectLoadingStartEvent: + var _a = event.data, project = _a.project, reason = _a.reason; + this.event({ projectName: project.getProjectName(), reason: reason }, server.ProjectLoadingStartEvent); + break; + case server.ProjectLoadingFinishEvent: + var finishProject = event.data.project; + this.event({ projectName: finishProject.getProjectName() }, server.ProjectLoadingFinishEvent); + break; + case server.LargeFileReferencedEvent: + var _b = event.data, file = _b.file, fileSize = _b.fileSize, maxFileSize_1 = _b.maxFileSize; + this.event({ file: file, fileSize: fileSize, maxFileSize: maxFileSize_1 }, server.LargeFileReferencedEvent); + break; + case server.ConfigFileDiagEvent: + var _c = event.data, triggerFile = _c.triggerFile, configFile = _c.configFileName, diagnostics = _c.diagnostics; + var bakedDiags = ts.map(diagnostics, function (diagnostic) { return formatConfigFileDiag(diagnostic, /*includeFileName*/ true); }); + this.event({ + triggerFile: triggerFile, + configFile: configFile, + diagnostics: bakedDiags + }, server.ConfigFileDiagEvent); + break; + case server.SurveyReady: + var surveyId = event.data.surveyId; + this.event({ surveyId: surveyId }, server.SurveyReady); + break; + case server.ProjectLanguageServiceStateEvent: { + var eventName = server.ProjectLanguageServiceStateEvent; + this.event({ + projectName: event.data.project.getProjectName(), + languageServiceEnabled: event.data.languageServiceEnabled + }, eventName); + break; + } + case server.ProjectInfoTelemetryEvent: { + var eventName = "telemetry"; + this.event({ + telemetryEventName: event.eventName, + payload: event.data, + }, eventName); + break; + } + } + }; + Session.prototype.projectsUpdatedInBackgroundEvent = function (openFiles) { + var _this = this; + this.projectService.logger.info("got projects updated in background, updating diagnostics for " + openFiles); + if (openFiles.length) { + if (!this.suppressDiagnosticEvents && !this.noGetErrOnBackgroundUpdate) { + var checkList_1 = this.createCheckList(openFiles); + // For now only queue error checking for open files. We can change this to include non open files as well + this.errorCheck.startNew(function (next) { return _this.updateErrorCheck(next, checkList_1, 100, /*requireOpen*/ true); }); + } + // Send project changed event + this.event({ + openFiles: openFiles + }, server.ProjectsUpdatedInBackgroundEvent); + } + }; + Session.prototype.logError = function (err, cmd) { + this.logErrorWorker(err, cmd); + }; + Session.prototype.logErrorWorker = function (err, cmd, fileRequest) { + var msg = "Exception on executing command " + cmd; + if (err.message) { + msg += ":\n" + server.indent(err.message); + if (err.stack) { + msg += "\n" + server.indent(err.stack); + } + } + if (fileRequest && this.logger.hasLevel(server.LogLevel.verbose)) { + try { + var _a = this.getFileAndProject(fileRequest), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + if (scriptInfo) { + var text = ts.getSnapshotText(scriptInfo.getSnapshot()); + msg += "\n\nFile text of " + fileRequest.file + ":" + server.indent(text) + "\n"; + } + } + catch (_b) { } // tslint:disable-line no-empty + } + this.logger.msg(msg, server.Msg.Err); + }; + Session.prototype.send = function (msg) { + if (msg.type === "event" && !this.canUseEvents) { + if (this.logger.hasLevel(server.LogLevel.verbose)) { + this.logger.info("Session does not support events: ignored event: " + JSON.stringify(msg)); + } + return; + } + this.host.write(formatMessage(msg, this.logger, this.byteLength, this.host.newLine)); + }; + Session.prototype.event = function (body, eventName) { + this.send(toEvent(eventName, body)); + }; + // For backwards-compatibility only. + /** @deprecated */ + Session.prototype.output = function (info, cmdName, reqSeq, errorMsg) { + this.doOutput(info, cmdName, reqSeq, /*success*/ !errorMsg, errorMsg); // TODO: GH#18217 + }; + Session.prototype.doOutput = function (info, cmdName, reqSeq, success, message) { + var res = { + seq: 0, + type: "response", + command: cmdName, + request_seq: reqSeq, + success: success, + }; + if (success) { + var metadata = void 0; + if (ts.isArray(info)) { + res.body = info; + metadata = info.metadata; + delete info.metadata; + } + else if (typeof info === "object") { + if (info.metadata) { + var _a = info, infoMetadata = _a.metadata, body = __rest(_a, ["metadata"]); + res.body = body; + metadata = infoMetadata; + } + else { + res.body = info; + } + } + else { + res.body = info; + } + if (metadata) + res.metadata = metadata; + } + else { + ts.Debug.assert(info === undefined); + } + if (message) { + res.message = message; + } + this.send(res); + }; + Session.prototype.semanticCheck = function (file, project) { + var diags = isDeclarationFileInJSOnlyNonConfiguredProject(project, file) + ? server.emptyArray + : project.getLanguageService().getSemanticDiagnostics(file); + this.sendDiagnosticsEvent(file, project, diags, "semanticDiag"); + }; + Session.prototype.syntacticCheck = function (file, project) { + this.sendDiagnosticsEvent(file, project, project.getLanguageService().getSyntacticDiagnostics(file), "syntaxDiag"); + }; + Session.prototype.suggestionCheck = function (file, project) { + this.sendDiagnosticsEvent(file, project, project.getLanguageService().getSuggestionDiagnostics(file), "suggestionDiag"); + }; + Session.prototype.sendDiagnosticsEvent = function (file, project, diagnostics, kind) { + try { + this.event({ file: file, diagnostics: diagnostics.map(function (diag) { return formatDiag(file, project, diag); }) }, kind); + } + catch (err) { + this.logError(err, kind); + } + }; + /** It is the caller's responsibility to verify that `!this.suppressDiagnosticEvents`. */ + Session.prototype.updateErrorCheck = function (next, checkList, ms, requireOpen) { + var _this = this; + if (requireOpen === void 0) { requireOpen = true; } + ts.Debug.assert(!this.suppressDiagnosticEvents); // Caller's responsibility + var seq = this.changeSeq; + var followMs = Math.min(ms, 200); + var index = 0; + var checkOne = function () { + if (_this.changeSeq !== seq) { + return; + } + var _a = checkList[index], fileName = _a.fileName, project = _a.project; + index++; + // Ensure the project is upto date before checking if this file is present in the project + server.updateProjectIfDirty(project); + if (!project.containsFile(fileName, requireOpen)) { + return; + } + _this.syntacticCheck(fileName, project); + if (_this.changeSeq !== seq) { + return; + } + next.immediate(function () { + _this.semanticCheck(fileName, project); + if (_this.changeSeq !== seq) { + return; + } + var goNext = function () { + if (checkList.length > index) { + next.delay(followMs, checkOne); + } + }; + if (_this.getPreferences(fileName).disableSuggestions) { + goNext(); + } + else { + next.immediate(function () { + _this.suggestionCheck(fileName, project); + goNext(); + }); + } + }); + }; + if (checkList.length > index && this.changeSeq === seq) { + next.delay(ms, checkOne); + } + }; + Session.prototype.cleanProjects = function (caption, projects) { + if (!projects) { + return; + } + this.logger.info("cleaning " + caption); + for (var _i = 0, projects_5 = projects; _i < projects_5.length; _i++) { + var p = projects_5[_i]; + p.getLanguageService(/*ensureSynchronized*/ false).cleanupSemanticCache(); + } + }; + Session.prototype.cleanup = function () { + this.cleanProjects("inferred projects", this.projectService.inferredProjects); + this.cleanProjects("configured projects", ts.arrayFrom(this.projectService.configuredProjects.values())); + this.cleanProjects("external projects", this.projectService.externalProjects); + if (this.host.gc) { + this.logger.info("host.gc()"); + this.host.gc(); + } + }; + Session.prototype.getEncodedSemanticClassifications = function (args) { + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + return project.getLanguageService().getEncodedSemanticClassifications(file, args); + }; + Session.prototype.getProject = function (projectFileName) { + return projectFileName === undefined ? undefined : this.projectService.findProject(projectFileName); + }; + Session.prototype.getConfigFileAndProject = function (args) { + var project = this.getProject(args.projectFileName); + var file = server.toNormalizedPath(args.file); + return { + configFile: project && project.hasConfigFile(file) ? file : undefined, + project: project + }; + }; + Session.prototype.getConfigFileDiagnostics = function (configFile, project, includeLinePosition) { + var projectErrors = project.getAllProjectErrors(); + var optionsErrors = project.getLanguageService().getCompilerOptionsDiagnostics(); + var diagnosticsForConfigFile = ts.filter(ts.concatenate(projectErrors, optionsErrors), function (diagnostic) { return !!diagnostic.file && diagnostic.file.fileName === configFile; }); + return includeLinePosition ? + this.convertToDiagnosticsWithLinePositionFromDiagnosticFile(diagnosticsForConfigFile) : + ts.map(diagnosticsForConfigFile, function (diagnostic) { return formatConfigFileDiag(diagnostic, /*includeFileName*/ false); }); + }; + Session.prototype.convertToDiagnosticsWithLinePositionFromDiagnosticFile = function (diagnostics) { + var _this = this; + return diagnostics.map(function (d) { return ({ + message: ts.flattenDiagnosticMessageText(d.messageText, _this.host.newLine), + start: d.start, + length: d.length, + category: ts.diagnosticCategoryName(d), + code: d.code, + startLocation: (d.file && convertToLocation(ts.getLineAndCharacterOfPosition(d.file, d.start))), + endLocation: (d.file && convertToLocation(ts.getLineAndCharacterOfPosition(d.file, d.start + d.length))), + relatedInformation: ts.map(d.relatedInformation, formatRelatedInformation) + }); }); + }; + Session.prototype.getCompilerOptionsDiagnostics = function (args) { + var project = this.getProject(args.projectFileName); + // Get diagnostics that dont have associated file with them + // The diagnostics which have file would be in config file and + // would be reported as part of configFileDiagnostics + return this.convertToDiagnosticsWithLinePosition(ts.filter(project.getLanguageService().getCompilerOptionsDiagnostics(), function (diagnostic) { return !diagnostic.file; }), + /*scriptInfo*/ undefined); + }; + Session.prototype.convertToDiagnosticsWithLinePosition = function (diagnostics, scriptInfo) { + var _this = this; + return diagnostics.map(function (d) { return ({ + message: ts.flattenDiagnosticMessageText(d.messageText, _this.host.newLine), + start: d.start, + length: d.length, + category: ts.diagnosticCategoryName(d), + code: d.code, + source: d.source, + startLocation: scriptInfo && scriptInfo.positionToLineOffset(d.start), + endLocation: scriptInfo && scriptInfo.positionToLineOffset(d.start + d.length), + reportsUnnecessary: d.reportsUnnecessary, + relatedInformation: ts.map(d.relatedInformation, formatRelatedInformation), + }); }); + }; + Session.prototype.getDiagnosticsWorker = function (args, isSemantic, selector, includeLinePosition) { + var _a = this.getFileAndProject(args), project = _a.project, file = _a.file; + if (isSemantic && isDeclarationFileInJSOnlyNonConfiguredProject(project, file)) { + return server.emptyArray; + } + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var diagnostics = selector(project, file); + return includeLinePosition + ? this.convertToDiagnosticsWithLinePosition(diagnostics, scriptInfo) + : diagnostics.map(function (d) { return formatDiag(file, project, d); }); + }; + Session.prototype.getDefinition = function (args, simplifiedResult) { + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + var position = this.getPositionInFile(args, file); + var definitions = this.mapDefinitionInfoLocations(project.getLanguageService().getDefinitionAtPosition(file, position) || server.emptyArray, project); + return simplifiedResult ? this.mapDefinitionInfo(definitions, project) : definitions.map(Session.mapToOriginalLocation); + }; + Session.prototype.mapDefinitionInfoLocations = function (definitions, project) { + var _this = this; + return definitions.map(function (info) { + var newLoc = getMappedLocation(documentSpanLocation(info), _this.projectService, project); + return !newLoc ? info : { + containerKind: info.containerKind, + containerName: info.containerName, + fileName: newLoc.fileName, + kind: info.kind, + name: info.name, + textSpan: { + start: newLoc.pos, + length: info.textSpan.length + }, + originalFileName: info.fileName, + originalTextSpan: info.textSpan, + }; + }); + }; + Session.prototype.getDefinitionAndBoundSpan = function (args, simplifiedResult) { + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + var position = this.getPositionInFile(args, file); + var scriptInfo = ts.Debug.assertDefined(project.getScriptInfo(file)); + var unmappedDefinitionAndBoundSpan = project.getLanguageService().getDefinitionAndBoundSpan(file, position); + if (!unmappedDefinitionAndBoundSpan || !unmappedDefinitionAndBoundSpan.definitions) { + return { + definitions: server.emptyArray, + textSpan: undefined // TODO: GH#18217 + }; + } + var definitions = this.mapDefinitionInfoLocations(unmappedDefinitionAndBoundSpan.definitions, project); + var textSpan = unmappedDefinitionAndBoundSpan.textSpan; + if (simplifiedResult) { + return { + definitions: this.mapDefinitionInfo(definitions, project), + textSpan: this.toLocationTextSpan(textSpan, scriptInfo) + }; + } + return { + definitions: definitions.map(Session.mapToOriginalLocation), + textSpan: textSpan, + }; + }; + Session.prototype.getEmitOutput = function (args) { + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + return project.getLanguageService().getEmitOutput(file); + }; + Session.prototype.mapDefinitionInfo = function (definitions, project) { + var _this = this; + return definitions.map(function (def) { return _this.toFileSpan(def.fileName, def.textSpan, project); }); + }; + /* + * When we map a .d.ts location to .ts, Visual Studio gets confused because there's no associated Roslyn Document in + * the same project which corresponds to the file. VS Code has no problem with this, and luckily we have two protocols. + * This retains the existing behavior for the "simplified" (VS Code) protocol but stores the .d.ts location in a + * set of additional fields, and does the reverse for VS (store the .d.ts location where + * it used to be and stores the .ts location in the additional fields). + */ + Session.mapToOriginalLocation = function (def) { + if (def.originalFileName) { + ts.Debug.assert(def.originalTextSpan !== undefined, "originalTextSpan should be present if originalFileName is"); + return __assign({}, def, { fileName: def.originalFileName, textSpan: def.originalTextSpan, targetFileName: def.fileName, targetTextSpan: def.textSpan }); + } + return def; + }; + Session.prototype.toFileSpan = function (fileName, textSpan, project) { + var ls = project.getLanguageService(); + var start = ls.toLineColumnOffset(fileName, textSpan.start); // TODO: GH#18217 + var end = ls.toLineColumnOffset(fileName, ts.textSpanEnd(textSpan)); + return { + file: fileName, + start: { line: start.line + 1, offset: start.character + 1 }, + end: { line: end.line + 1, offset: end.character + 1 } + }; + }; + Session.prototype.getTypeDefinition = function (args) { + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + var position = this.getPositionInFile(args, file); + var definitions = this.mapDefinitionInfoLocations(project.getLanguageService().getTypeDefinitionAtPosition(file, position) || server.emptyArray, project); + return this.mapDefinitionInfo(definitions, project); + }; + Session.prototype.mapImplementationLocations = function (implementations, project) { + var _this = this; + return implementations.map(function (info) { + var newLoc = getMappedLocation(documentSpanLocation(info), _this.projectService, project); + return !newLoc ? info : { + fileName: newLoc.fileName, + kind: info.kind, + displayParts: info.displayParts, + textSpan: { + start: newLoc.pos, + length: info.textSpan.length + }, + originalFileName: info.fileName, + originalTextSpan: info.textSpan, + }; + }); + }; + Session.prototype.getImplementation = function (args, simplifiedResult) { + var _this = this; + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + var position = this.getPositionInFile(args, file); + var implementations = this.mapImplementationLocations(project.getLanguageService().getImplementationAtPosition(file, position) || server.emptyArray, project); + if (simplifiedResult) { + return implementations.map(function (_a) { + var fileName = _a.fileName, textSpan = _a.textSpan; + return _this.toFileSpan(fileName, textSpan, project); + }); + } + return implementations.map(Session.mapToOriginalLocation); + }; + Session.prototype.getOccurrences = function (args) { + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + var position = this.getPositionInFile(args, file); + var occurrences = project.getLanguageService().getOccurrencesAtPosition(file, position); + if (!occurrences) { + return server.emptyArray; + } + return occurrences.map(function (occurrence) { + var fileName = occurrence.fileName, isWriteAccess = occurrence.isWriteAccess, textSpan = occurrence.textSpan, isInString = occurrence.isInString; + var scriptInfo = project.getScriptInfo(fileName); + var result = { + start: scriptInfo.positionToLineOffset(textSpan.start), + end: scriptInfo.positionToLineOffset(ts.textSpanEnd(textSpan)), + file: fileName, + isWriteAccess: isWriteAccess, + }; + // no need to serialize the property if it is not true + if (isInString) { + result.isInString = isInString; + } + return result; + }); + }; + Session.prototype.getSyntacticDiagnosticsSync = function (args) { + var configFile = this.getConfigFileAndProject(args).configFile; + if (configFile) { + // all the config file errors are reported as part of semantic check so nothing to report here + return server.emptyArray; + } + return this.getDiagnosticsWorker(args, /*isSemantic*/ false, function (project, file) { return project.getLanguageService().getSyntacticDiagnostics(file); }, !!args.includeLinePosition); + }; + Session.prototype.getSemanticDiagnosticsSync = function (args) { + var _a = this.getConfigFileAndProject(args), configFile = _a.configFile, project = _a.project; + if (configFile) { + return this.getConfigFileDiagnostics(configFile, project, !!args.includeLinePosition); // TODO: GH#18217 + } + return this.getDiagnosticsWorker(args, /*isSemantic*/ true, function (project, file) { return project.getLanguageService().getSemanticDiagnostics(file); }, !!args.includeLinePosition); + }; + Session.prototype.getSuggestionDiagnosticsSync = function (args) { + var configFile = this.getConfigFileAndProject(args).configFile; + if (configFile) { + // Currently there are no info diagnostics for config files. + return server.emptyArray; + } + // isSemantic because we don't want to info diagnostics in declaration files for JS-only users + return this.getDiagnosticsWorker(args, /*isSemantic*/ true, function (project, file) { return project.getLanguageService().getSuggestionDiagnostics(file); }, !!args.includeLinePosition); + }; + Session.prototype.getJsxClosingTag = function (args) { + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + var position = this.getPositionInFile(args, file); + var tag = project.getLanguageService().getJsxClosingTagAtPosition(file, position); + return tag === undefined ? undefined : { newText: tag.newText, caretOffset: 0 }; + }; + Session.prototype.getDocumentHighlights = function (args, simplifiedResult) { + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + var position = this.getPositionInFile(args, file); + var documentHighlights = project.getLanguageService().getDocumentHighlights(file, position, args.filesToSearch); + if (!documentHighlights) { + return server.emptyArray; + } + if (simplifiedResult) { + return documentHighlights.map(convertToDocumentHighlightsItem); + } + else { + return documentHighlights; + } + function convertToDocumentHighlightsItem(documentHighlights) { + var fileName = documentHighlights.fileName, highlightSpans = documentHighlights.highlightSpans; + var scriptInfo = project.getScriptInfo(fileName); + return { + file: fileName, + highlightSpans: highlightSpans.map(convertHighlightSpan) + }; + function convertHighlightSpan(highlightSpan) { + var textSpan = highlightSpan.textSpan, kind = highlightSpan.kind; + var start = scriptInfo.positionToLineOffset(textSpan.start); + var end = scriptInfo.positionToLineOffset(ts.textSpanEnd(textSpan)); + return { start: start, end: end, kind: kind }; + } + } + }; + Session.prototype.setCompilerOptionsForInferredProjects = function (args) { + this.projectService.setCompilerOptionsForInferredProjects(args.options, args.projectRootPath); + }; + Session.prototype.getProjectInfo = function (args) { + return this.getProjectInfoWorker(args.file, args.projectFileName, args.needFileNameList, /*excludeConfigFiles*/ false); + }; + Session.prototype.getProjectInfoWorker = function (uncheckedFileName, projectFileName, needFileNameList, excludeConfigFiles) { + var project = this.getFileAndProjectWorker(uncheckedFileName, projectFileName).project; + server.updateProjectIfDirty(project); + var projectInfo = { + configFileName: project.getProjectName(), + languageServiceDisabled: !project.languageServiceEnabled, + fileNames: needFileNameList ? project.getFileNames(/*excludeFilesFromExternalLibraries*/ false, excludeConfigFiles) : undefined + }; + return projectInfo; + }; + Session.prototype.getRenameInfo = function (args) { + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + var position = this.getPositionInFile(args, file); + return project.getLanguageService().getRenameInfo(file, position); + }; + Session.prototype.getProjects = function (args, getScriptInfoEnsuringProjectsUptoDate, ignoreNoProjectError) { + var projects; + var symLinkedProjects; + if (args.projectFileName) { + var project = this.getProject(args.projectFileName); + if (project) { + projects = [project]; + } + } + else { + var scriptInfo = getScriptInfoEnsuringProjectsUptoDate ? + this.projectService.getScriptInfoEnsuringProjectsUptoDate(args.file) : + this.projectService.getScriptInfo(args.file); + if (!scriptInfo) { + if (ignoreNoProjectError) + return server.emptyArray; + this.projectService.logErrorForScriptInfoNotFound(args.file); + return server.Errors.ThrowNoProject(); + } + projects = scriptInfo.containingProjects; + symLinkedProjects = this.projectService.getSymlinkedProjects(scriptInfo); + } + // filter handles case when 'projects' is undefined + projects = ts.filter(projects, function (p) { return p.languageServiceEnabled && !p.isOrphan(); }); + if (!ignoreNoProjectError && (!projects || !projects.length) && !symLinkedProjects) { + this.projectService.logErrorForScriptInfoNotFound(args.file); + return server.Errors.ThrowNoProject(); + } + return symLinkedProjects ? { projects: projects, symLinkedProjects: symLinkedProjects } : projects; // TODO: GH#18217 + }; + Session.prototype.getDefaultProject = function (args) { + if (args.projectFileName) { + var project = this.getProject(args.projectFileName); + if (project) { + return project; + } + } + var info = this.projectService.getScriptInfo(args.file); + return info.getDefaultProject(); + }; + Session.prototype.getRenameLocations = function (args, simplifiedResult) { + var file = server.toNormalizedPath(args.file); + var position = this.getPositionInFile(args, file); + var projects = this.getProjects(args); + var locations = combineProjectOutputForRenameLocations(projects, this.getDefaultProject(args), { fileName: args.file, pos: position }, !!args.findInStrings, !!args.findInComments); + if (!simplifiedResult) + return locations; + var defaultProject = this.getDefaultProject(args); + var renameInfo = this.mapRenameInfo(defaultProject.getLanguageService().getRenameInfo(file, position), ts.Debug.assertDefined(this.projectService.getScriptInfo(file))); + return { info: renameInfo, locs: this.toSpanGroups(locations) }; + }; + Session.prototype.mapRenameInfo = function (info, scriptInfo) { + if (info.canRename) { + var canRename = info.canRename, fileToRename = info.fileToRename, displayName = info.displayName, fullDisplayName = info.fullDisplayName, kind = info.kind, kindModifiers = info.kindModifiers, triggerSpan = info.triggerSpan; + return ts.identity({ canRename: canRename, fileToRename: fileToRename, displayName: displayName, fullDisplayName: fullDisplayName, kind: kind, kindModifiers: kindModifiers, triggerSpan: this.toLocationTextSpan(triggerSpan, scriptInfo) }); + } + else { + return info; + } + }; + Session.prototype.toSpanGroups = function (locations) { + var map = ts.createMap(); + for (var _i = 0, locations_1 = locations; _i < locations_1.length; _i++) { + var _a = locations_1[_i]; + var fileName = _a.fileName, textSpan = _a.textSpan, _ = _a.originalTextSpan, _1 = _a.originalFileName, prefixSuffixText = __rest(_a, ["fileName", "textSpan", "originalTextSpan", "originalFileName"]); + var group_2 = map.get(fileName); + if (!group_2) + map.set(fileName, group_2 = { file: fileName, locs: [] }); + var scriptInfo = ts.Debug.assertDefined(this.projectService.getScriptInfo(fileName)); + group_2.locs.push(__assign({}, this.toLocationTextSpan(textSpan, scriptInfo), prefixSuffixText)); + } + return ts.arrayFrom(map.values()); + }; + Session.prototype.getReferences = function (args, simplifiedResult) { + var _this = this; + var file = server.toNormalizedPath(args.file); + var projects = this.getProjects(args); + var position = this.getPositionInFile(args, file); + var references = combineProjectOutputForReferences(projects, this.getDefaultProject(args), { fileName: args.file, pos: position }); + if (simplifiedResult) { + var defaultProject = this.getDefaultProject(args); + var scriptInfo = defaultProject.getScriptInfoForNormalizedPath(file); + var nameInfo = defaultProject.getLanguageService().getQuickInfoAtPosition(file, position); + var symbolDisplayString = nameInfo ? ts.displayPartsToString(nameInfo.displayParts) : ""; + var nameSpan = nameInfo && nameInfo.textSpan; + var symbolStartOffset = nameSpan ? scriptInfo.positionToLineOffset(nameSpan.start).offset : 0; + var symbolName_3 = nameSpan ? scriptInfo.getSnapshot().getText(nameSpan.start, ts.textSpanEnd(nameSpan)) : ""; + var refs = ts.flatMap(references, function (referencedSymbol) { + return referencedSymbol.references.map(function (_a) { + var fileName = _a.fileName, textSpan = _a.textSpan, isWriteAccess = _a.isWriteAccess, isDefinition = _a.isDefinition; + var scriptInfo = ts.Debug.assertDefined(_this.projectService.getScriptInfo(fileName)); + var start = scriptInfo.positionToLineOffset(textSpan.start); + var lineSpan = scriptInfo.lineToTextSpan(start.line - 1); + var lineText = scriptInfo.getSnapshot().getText(lineSpan.start, ts.textSpanEnd(lineSpan)).replace(/\r|\n/g, ""); + return __assign({}, toFileSpan(fileName, textSpan, scriptInfo), { lineText: lineText, isWriteAccess: isWriteAccess, isDefinition: isDefinition }); + }); + }); + var result = { refs: refs, symbolName: symbolName_3, symbolStartOffset: symbolStartOffset, symbolDisplayString: symbolDisplayString }; + return result; + } + else { + return references; + } + }; + /** + * @param fileName is the name of the file to be opened + * @param fileContent is a version of the file content that is known to be more up to date than the one on disk + */ + Session.prototype.openClientFile = function (fileName, fileContent, scriptKind, projectRootPath) { + this.projectService.openClientFileWithNormalizedPath(fileName, fileContent, scriptKind, /*hasMixedContent*/ false, projectRootPath); + }; + Session.prototype.getPosition = function (args, scriptInfo) { + return args.position !== undefined ? args.position : scriptInfo.lineOffsetToPosition(args.line, args.offset); + }; + Session.prototype.getPositionInFile = function (args, file) { + var scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file); + return this.getPosition(args, scriptInfo); + }; + Session.prototype.getFileAndProject = function (args) { + return this.getFileAndProjectWorker(args.file, args.projectFileName); + }; + Session.prototype.getFileAndLanguageServiceForSyntacticOperation = function (args) { + // Since this is syntactic operation, there should always be project for the file + // we wouldnt have to ensure project but rather throw if we dont get project + var file = server.toNormalizedPath(args.file); + var project = this.getProject(args.projectFileName) || this.projectService.tryGetDefaultProjectForFile(file); + if (!project) { + return server.Errors.ThrowNoProject(); + } + return { + file: file, + languageService: project.getLanguageService(/*ensureSynchronized*/ false) + }; + }; + Session.prototype.getFileAndProjectWorker = function (uncheckedFileName, projectFileName) { + var file = server.toNormalizedPath(uncheckedFileName); + var project = this.getProject(projectFileName) || this.projectService.ensureDefaultProjectForFile(file); + return { file: file, project: project }; + }; + Session.prototype.getOutliningSpans = function (args, simplifiedResult) { + var _this = this; + var _a = this.getFileAndLanguageServiceForSyntacticOperation(args), file = _a.file, languageService = _a.languageService; + var spans = languageService.getOutliningSpans(file); + if (simplifiedResult) { + var scriptInfo_1 = this.projectService.getScriptInfoForNormalizedPath(file); + return spans.map(function (s) { return ({ + textSpan: _this.toLocationTextSpan(s.textSpan, scriptInfo_1), + hintSpan: _this.toLocationTextSpan(s.hintSpan, scriptInfo_1), + bannerText: s.bannerText, + autoCollapse: s.autoCollapse, + kind: s.kind + }); }); + } + else { + return spans; + } + }; + Session.prototype.getTodoComments = function (args) { + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + return project.getLanguageService().getTodoComments(file, args.descriptors); + }; + Session.prototype.getDocCommentTemplate = function (args) { + var _a = this.getFileAndLanguageServiceForSyntacticOperation(args), file = _a.file, languageService = _a.languageService; + var position = this.getPositionInFile(args, file); + return languageService.getDocCommentTemplateAtPosition(file, position); + }; + Session.prototype.getSpanOfEnclosingComment = function (args) { + var _a = this.getFileAndLanguageServiceForSyntacticOperation(args), file = _a.file, languageService = _a.languageService; + var onlyMultiLine = args.onlyMultiLine; + var position = this.getPositionInFile(args, file); + return languageService.getSpanOfEnclosingComment(file, position, onlyMultiLine); + }; + Session.prototype.getIndentation = function (args) { + var _a = this.getFileAndLanguageServiceForSyntacticOperation(args), file = _a.file, languageService = _a.languageService; + var position = this.getPositionInFile(args, file); + var options = args.options ? server.convertFormatOptions(args.options) : this.getFormatOptions(file); + var indentation = languageService.getIndentationAtPosition(file, position, options); + return { position: position, indentation: indentation }; + }; + Session.prototype.getBreakpointStatement = function (args) { + var _a = this.getFileAndLanguageServiceForSyntacticOperation(args), file = _a.file, languageService = _a.languageService; + var position = this.getPositionInFile(args, file); + return languageService.getBreakpointStatementAtPosition(file, position); + }; + Session.prototype.getNameOrDottedNameSpan = function (args) { + var _a = this.getFileAndLanguageServiceForSyntacticOperation(args), file = _a.file, languageService = _a.languageService; + var position = this.getPositionInFile(args, file); + return languageService.getNameOrDottedNameSpan(file, position, position); + }; + Session.prototype.isValidBraceCompletion = function (args) { + var _a = this.getFileAndLanguageServiceForSyntacticOperation(args), file = _a.file, languageService = _a.languageService; + var position = this.getPositionInFile(args, file); + return languageService.isValidBraceCompletionAtPosition(file, position, args.openingBrace.charCodeAt(0)); + }; + Session.prototype.getQuickInfoWorker = function (args, simplifiedResult) { + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + var scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file); + var quickInfo = project.getLanguageService().getQuickInfoAtPosition(file, this.getPosition(args, scriptInfo)); + if (!quickInfo) { + return undefined; + } + if (simplifiedResult) { + var displayString = ts.displayPartsToString(quickInfo.displayParts); + var docString = ts.displayPartsToString(quickInfo.documentation); + return { + kind: quickInfo.kind, + kindModifiers: quickInfo.kindModifiers, + start: scriptInfo.positionToLineOffset(quickInfo.textSpan.start), + end: scriptInfo.positionToLineOffset(ts.textSpanEnd(quickInfo.textSpan)), + displayString: displayString, + documentation: docString, + tags: quickInfo.tags || [] + }; + } + else { + return quickInfo; + } + }; + Session.prototype.getFormattingEditsForRange = function (args) { + var _this = this; + var _a = this.getFileAndLanguageServiceForSyntacticOperation(args), file = _a.file, languageService = _a.languageService; + var scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file); + var startPosition = scriptInfo.lineOffsetToPosition(args.line, args.offset); + var endPosition = scriptInfo.lineOffsetToPosition(args.endLine, args.endOffset); + // TODO: avoid duplicate code (with formatonkey) + var edits = languageService.getFormattingEditsForRange(file, startPosition, endPosition, this.getFormatOptions(file)); + if (!edits) { + return undefined; + } + return edits.map(function (edit) { return _this.convertTextChangeToCodeEdit(edit, scriptInfo); }); + }; + Session.prototype.getFormattingEditsForRangeFull = function (args) { + var _a = this.getFileAndLanguageServiceForSyntacticOperation(args), file = _a.file, languageService = _a.languageService; + var options = args.options ? server.convertFormatOptions(args.options) : this.getFormatOptions(file); + return languageService.getFormattingEditsForRange(file, args.position, args.endPosition, options); // TODO: GH#18217 + }; + Session.prototype.getFormattingEditsForDocumentFull = function (args) { + var _a = this.getFileAndLanguageServiceForSyntacticOperation(args), file = _a.file, languageService = _a.languageService; + var options = args.options ? server.convertFormatOptions(args.options) : this.getFormatOptions(file); + return languageService.getFormattingEditsForDocument(file, options); + }; + Session.prototype.getFormattingEditsAfterKeystrokeFull = function (args) { + var _a = this.getFileAndLanguageServiceForSyntacticOperation(args), file = _a.file, languageService = _a.languageService; + var options = args.options ? server.convertFormatOptions(args.options) : this.getFormatOptions(file); + return languageService.getFormattingEditsAfterKeystroke(file, args.position, args.key, options); // TODO: GH#18217 + }; + Session.prototype.getFormattingEditsAfterKeystroke = function (args) { + var _a = this.getFileAndLanguageServiceForSyntacticOperation(args), file = _a.file, languageService = _a.languageService; + var scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file); + var position = scriptInfo.lineOffsetToPosition(args.line, args.offset); + var formatOptions = this.getFormatOptions(file); + var edits = languageService.getFormattingEditsAfterKeystroke(file, position, args.key, formatOptions); + // Check whether we should auto-indent. This will be when + // the position is on a line containing only whitespace. + // This should leave the edits returned from + // getFormattingEditsAfterKeystroke either empty or pertaining + // only to the previous line. If all this is true, then + // add edits necessary to properly indent the current line. + if ((args.key === "\n") && ((!edits) || (edits.length === 0) || allEditsBeforePos(edits, position))) { + var _b = scriptInfo.getLineInfo(args.line), lineText = _b.lineText, absolutePosition = _b.absolutePosition; + if (lineText && lineText.search("\\S") < 0) { + var preferredIndent = languageService.getIndentationAtPosition(file, position, formatOptions); + var hasIndent = 0; + var i = void 0, len = void 0; + for (i = 0, len = lineText.length; i < len; i++) { + if (lineText.charAt(i) === " ") { + hasIndent++; + } + else if (lineText.charAt(i) === "\t") { + hasIndent += formatOptions.tabSize; // TODO: GH#18217 + } + else { + break; + } + } + // i points to the first non whitespace character + if (preferredIndent !== hasIndent) { + var firstNoWhiteSpacePosition = absolutePosition + i; + edits.push({ + span: ts.createTextSpanFromBounds(absolutePosition, firstNoWhiteSpacePosition), + newText: ts.formatting.getIndentationString(preferredIndent, formatOptions) + }); + } + } + } + if (!edits) { + return undefined; + } + return edits.map(function (edit) { + return { + start: scriptInfo.positionToLineOffset(edit.span.start), + end: scriptInfo.positionToLineOffset(ts.textSpanEnd(edit.span)), + newText: edit.newText ? edit.newText : "" + }; + }); + }; + Session.prototype.getCompletions = function (args, kind) { + var _this = this; + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + var scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file); + var position = this.getPosition(args, scriptInfo); + var completions = project.getLanguageService().getCompletionsAtPosition(file, position, __assign({}, server.convertUserPreferences(this.getPreferences(file)), { triggerCharacter: args.triggerCharacter, includeExternalModuleExports: args.includeExternalModuleExports, includeInsertTextCompletions: args.includeInsertTextCompletions })); + if (completions === undefined) + return undefined; + if (kind === "completions-full" /* CompletionsFull */) + return completions; + var prefix = args.prefix || ""; + var entries = ts.mapDefined(completions.entries, function (entry) { + if (completions.isMemberCompletion || ts.startsWith(entry.name.toLowerCase(), prefix.toLowerCase())) { + var name = entry.name, kind_2 = entry.kind, kindModifiers = entry.kindModifiers, sortText = entry.sortText, insertText = entry.insertText, replacementSpan = entry.replacementSpan, hasAction = entry.hasAction, source = entry.source, isRecommended = entry.isRecommended; + var convertedSpan = replacementSpan ? _this.toLocationTextSpan(replacementSpan, scriptInfo) : undefined; + // Use `hasAction || undefined` to avoid serializing `false`. + return { name: name, kind: kind_2, kindModifiers: kindModifiers, sortText: sortText, insertText: insertText, replacementSpan: convertedSpan, hasAction: hasAction || undefined, source: source, isRecommended: isRecommended }; + } + }).sort(function (a, b) { return ts.compareStringsCaseSensitiveUI(a.name, b.name); }); + if (kind === "completions" /* Completions */) { + if (completions.metadata) + entries.metadata = completions.metadata; + return entries; + } + var res = __assign({}, completions, { entries: entries }); + return res; + }; + Session.prototype.getCompletionEntryDetails = function (args, simplifiedResult) { + var _this = this; + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + var scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file); + var position = this.getPosition(args, scriptInfo); + var formattingOptions = project.projectService.getFormatCodeOptions(file); + var result = ts.mapDefined(args.entryNames, function (entryName) { + var _a = typeof entryName === "string" ? { name: entryName, source: undefined } : entryName, name = _a.name, source = _a.source; + return project.getLanguageService().getCompletionEntryDetails(file, position, name, formattingOptions, source, _this.getPreferences(file)); + }); + return simplifiedResult + ? result.map(function (details) { return (__assign({}, details, { codeActions: ts.map(details.codeActions, function (action) { return _this.mapCodeAction(action); }) })); }) + : result; + }; + Session.prototype.getCompileOnSaveAffectedFileList = function (args) { + var _this = this; + var projects = this.getProjects(args, /*getScriptInfoEnsuringProjectsUptoDate*/ true, /*ignoreNoProjectError*/ true); + var info = this.projectService.getScriptInfo(args.file); + if (!info) { + return server.emptyArray; + } + return combineProjectOutput(info, function (path) { return _this.projectService.getScriptInfoForPath(path); }, projects, function (project, info) { + var result; + if (project.compileOnSaveEnabled && project.languageServiceEnabled && !project.isOrphan() && !project.getCompilationSettings().noEmit) { + result = { + projectFileName: project.getProjectName(), + fileNames: project.getCompileOnSaveAffectedFileList(info), + projectUsesOutFile: !!project.getCompilationSettings().outFile || !!project.getCompilationSettings().out + }; + } + return result; + }); + }; + Session.prototype.emitFile = function (args) { + var _this = this; + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + if (!project) { + server.Errors.ThrowNoProject(); + } + if (!project.languageServiceEnabled) { + return false; + } + var scriptInfo = project.getScriptInfo(file); + return project.emitFile(scriptInfo, function (path, data, writeByteOrderMark) { return _this.host.writeFile(path, data, writeByteOrderMark); }); + }; + Session.prototype.getSignatureHelpItems = function (args, simplifiedResult) { + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + var scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file); + var position = this.getPosition(args, scriptInfo); + var helpItems = project.getLanguageService().getSignatureHelpItems(file, position, args); + if (!helpItems) { + return undefined; + } + if (simplifiedResult) { + var span = helpItems.applicableSpan; + return { + items: helpItems.items, + applicableSpan: { + start: scriptInfo.positionToLineOffset(span.start), + end: scriptInfo.positionToLineOffset(span.start + span.length) + }, + selectedItemIndex: helpItems.selectedItemIndex, + argumentIndex: helpItems.argumentIndex, + argumentCount: helpItems.argumentCount, + }; + } + else { + return helpItems; + } + }; + Session.prototype.createCheckList = function (fileNames, defaultProject) { + var _this = this; + return ts.mapDefined(fileNames, function (uncheckedFileName) { + var fileName = server.toNormalizedPath(uncheckedFileName); + var project = defaultProject || _this.projectService.tryGetDefaultProjectForFile(fileName); + return project && { fileName: fileName, project: project }; + }); + }; + Session.prototype.getDiagnostics = function (next, delay, fileNames) { + if (this.suppressDiagnosticEvents) { + return; + } + var checkList = this.createCheckList(fileNames); + if (checkList.length > 0) { + this.updateErrorCheck(next, checkList, delay); + } + }; + Session.prototype.change = function (args) { + var scriptInfo = this.projectService.getScriptInfo(args.file); + ts.Debug.assert(!!scriptInfo); + var start = scriptInfo.lineOffsetToPosition(args.line, args.offset); + var end = scriptInfo.lineOffsetToPosition(args.endLine, args.endOffset); + if (start >= 0) { + this.changeSeq++; + this.projectService.applyChangesToFile(scriptInfo, [{ + span: { start: start, length: end - start }, + newText: args.insertString // TODO: GH#18217 + }]); + } + }; + Session.prototype.reload = function (args, reqSeq) { + var file = server.toNormalizedPath(args.file); + var tempFileName = args.tmpfile === undefined ? undefined : server.toNormalizedPath(args.tmpfile); + var info = this.projectService.getScriptInfoForNormalizedPath(file); + if (info) { + this.changeSeq++; + // make sure no changes happen before this one is finished + if (info.reloadFromFile(tempFileName)) { + this.doOutput(/*info*/ undefined, server.CommandNames.Reload, reqSeq, /*success*/ true); + } + } + }; + Session.prototype.saveToTmp = function (fileName, tempFileName) { + var scriptInfo = this.projectService.getScriptInfo(fileName); + if (scriptInfo) { + scriptInfo.saveTo(tempFileName); + } + }; + Session.prototype.closeClientFile = function (fileName) { + if (!fileName) { + return; + } + var file = ts.normalizePath(fileName); + this.projectService.closeClientFile(file); + }; + Session.prototype.mapLocationNavigationBarItems = function (items, scriptInfo) { + var _this = this; + return ts.map(items, function (item) { return ({ + text: item.text, + kind: item.kind, + kindModifiers: item.kindModifiers, + spans: item.spans.map(function (span) { return _this.toLocationTextSpan(span, scriptInfo); }), + childItems: _this.mapLocationNavigationBarItems(item.childItems, scriptInfo), + indent: item.indent + }); }); + }; + Session.prototype.getNavigationBarItems = function (args, simplifiedResult) { + var _a = this.getFileAndLanguageServiceForSyntacticOperation(args), file = _a.file, languageService = _a.languageService; + var items = languageService.getNavigationBarItems(file); + return !items + ? undefined + : simplifiedResult + ? this.mapLocationNavigationBarItems(items, this.projectService.getScriptInfoForNormalizedPath(file)) + : items; + }; + Session.prototype.toLocationNavigationTree = function (tree, scriptInfo) { + var _this = this; + return { + text: tree.text, + kind: tree.kind, + kindModifiers: tree.kindModifiers, + spans: tree.spans.map(function (span) { return _this.toLocationTextSpan(span, scriptInfo); }), + nameSpan: tree.nameSpan && this.toLocationTextSpan(tree.nameSpan, scriptInfo), + childItems: ts.map(tree.childItems, function (item) { return _this.toLocationNavigationTree(item, scriptInfo); }) + }; + }; + Session.prototype.toLocationTextSpan = function (span, scriptInfo) { + return { + start: scriptInfo.positionToLineOffset(span.start), + end: scriptInfo.positionToLineOffset(ts.textSpanEnd(span)) + }; + }; + Session.prototype.getNavigationTree = function (args, simplifiedResult) { + var _a = this.getFileAndLanguageServiceForSyntacticOperation(args), file = _a.file, languageService = _a.languageService; + var tree = languageService.getNavigationTree(file); + return !tree + ? undefined + : simplifiedResult + ? this.toLocationNavigationTree(tree, this.projectService.getScriptInfoForNormalizedPath(file)) + : tree; + }; + Session.prototype.getNavigateToItems = function (args, simplifiedResult) { + var _this = this; + var full = this.getFullNavigateToItems(args); + return !simplifiedResult ? full : full.map(function (navItem) { + var _a = _this.getFileAndProject({ file: navItem.fileName }), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfo(file); + var bakedItem = { + name: navItem.name, + kind: navItem.kind, + isCaseSensitive: navItem.isCaseSensitive, + matchKind: navItem.matchKind, + file: navItem.fileName, + start: scriptInfo.positionToLineOffset(navItem.textSpan.start), + end: scriptInfo.positionToLineOffset(ts.textSpanEnd(navItem.textSpan)) + }; + if (navItem.kindModifiers && (navItem.kindModifiers !== "")) { + bakedItem.kindModifiers = navItem.kindModifiers; + } + if (navItem.containerName && (navItem.containerName.length > 0)) { + bakedItem.containerName = navItem.containerName; + } + if (navItem.containerKind && (navItem.containerKind.length > 0)) { + bakedItem.containerKind = navItem.containerKind; + } + return bakedItem; + }); + }; + Session.prototype.getFullNavigateToItems = function (args) { + var currentFileOnly = args.currentFileOnly, searchValue = args.searchValue, maxResultCount = args.maxResultCount; + if (currentFileOnly) { + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + return project.getLanguageService().getNavigateToItems(searchValue, maxResultCount, file); + } + else { + return combineProjectOutputWhileOpeningReferencedProjects(this.getProjects(args), this.getDefaultProject(args), function (project) { + return project.getLanguageService().getNavigateToItems(searchValue, maxResultCount, /*fileName*/ undefined, /*excludeDts*/ project.isNonTsProject()); + }, documentSpanLocation, navigateToItemIsEqualTo); + } + function navigateToItemIsEqualTo(a, b) { + if (a === b) { + return true; + } + if (!a || !b) { + return false; + } + return a.containerKind === b.containerKind && + a.containerName === b.containerName && + a.fileName === b.fileName && + a.isCaseSensitive === b.isCaseSensitive && + a.kind === b.kind && + a.kindModifiers === b.containerName && + a.matchKind === b.matchKind && + a.name === b.name && + a.textSpan.start === b.textSpan.start && + a.textSpan.length === b.textSpan.length; + } + }; + Session.prototype.getSupportedCodeFixes = function () { + return ts.getSupportedCodeFixes(); + }; + Session.prototype.isLocation = function (locationOrSpan) { + return locationOrSpan.line !== undefined; + }; + Session.prototype.extractPositionOrRange = function (args, scriptInfo) { + var position; + var textRange; + if (this.isLocation(args)) { + position = getPosition(args); + } + else { + var _a = this.getStartAndEndPosition(args, scriptInfo), startPosition = _a.startPosition, endPosition = _a.endPosition; + textRange = { pos: startPosition, end: endPosition }; + } + return ts.Debug.assertDefined(position === undefined ? textRange : position); + function getPosition(loc) { + return loc.position !== undefined ? loc.position : scriptInfo.lineOffsetToPosition(loc.line, loc.offset); + } + }; + Session.prototype.getApplicableRefactors = function (args) { + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + return project.getLanguageService().getApplicableRefactors(file, this.extractPositionOrRange(args, scriptInfo), this.getPreferences(file)); + }; + Session.prototype.getEditsForRefactor = function (args, simplifiedResult) { + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var result = project.getLanguageService().getEditsForRefactor(file, this.getFormatOptions(file), this.extractPositionOrRange(args, scriptInfo), args.refactor, args.action, this.getPreferences(file)); + if (result === undefined) { + return { + edits: [] + }; + } + if (simplifiedResult) { + var renameFilename = result.renameFilename, renameLocation = result.renameLocation, edits = result.edits; + var mappedRenameLocation = void 0; + if (renameFilename !== undefined && renameLocation !== undefined) { + var renameScriptInfo = project.getScriptInfoForNormalizedPath(server.toNormalizedPath(renameFilename)); + mappedRenameLocation = getLocationInNewDocument(ts.getSnapshotText(renameScriptInfo.getSnapshot()), renameFilename, renameLocation, edits); + } + return { renameLocation: mappedRenameLocation, renameFilename: renameFilename, edits: this.mapTextChangesToCodeEdits(edits) }; + } + else { + return result; + } + }; + Session.prototype.organizeImports = function (_a, simplifiedResult) { + var scope = _a.scope; + ts.Debug.assert(scope.type === "file"); + var _b = this.getFileAndProject(scope.args), file = _b.file, project = _b.project; + var changes = project.getLanguageService().organizeImports({ type: "file", fileName: file }, this.getFormatOptions(file), this.getPreferences(file)); + if (simplifiedResult) { + return this.mapTextChangesToCodeEdits(changes); + } + else { + return changes; + } + }; + Session.prototype.getEditsForFileRename = function (args, simplifiedResult) { + var _this = this; + var oldPath = server.toNormalizedPath(args.oldFilePath); + var newPath = server.toNormalizedPath(args.newFilePath); + var formatOptions = this.getHostFormatOptions(); + var preferences = this.getHostPreferences(); + var changes = combineProjectOutputFromEveryProject(this.projectService, function (project) { return project.getLanguageService().getEditsForFileRename(oldPath, newPath, formatOptions, preferences); }, function (a, b) { return a.fileName === b.fileName; }); + return simplifiedResult ? changes.map(function (c) { return _this.mapTextChangeToCodeEdit(c); }) : changes; + }; + Session.prototype.getCodeFixes = function (args, simplifiedResult) { + var _this = this; + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var _b = this.getStartAndEndPosition(args, scriptInfo), startPosition = _b.startPosition, endPosition = _b.endPosition; + var codeActions = project.getLanguageService().getCodeFixesAtPosition(file, startPosition, endPosition, args.errorCodes, this.getFormatOptions(file), this.getPreferences(file)); + return simplifiedResult ? codeActions.map(function (codeAction) { return _this.mapCodeFixAction(codeAction); }) : codeActions; + }; + Session.prototype.getCombinedCodeFix = function (_a, simplifiedResult) { + var scope = _a.scope, fixId = _a.fixId; + ts.Debug.assert(scope.type === "file"); + var _b = this.getFileAndProject(scope.args), file = _b.file, project = _b.project; + var res = project.getLanguageService().getCombinedCodeFix({ type: "file", fileName: file }, fixId, this.getFormatOptions(file), this.getPreferences(file)); + if (simplifiedResult) { + return { changes: this.mapTextChangesToCodeEdits(res.changes), commands: res.commands }; + } + else { + return res; + } + }; + Session.prototype.applyCodeActionCommand = function (args) { + var commands = args.command; // They should be sending back the command we sent them. + for (var _i = 0, _a = ts.toArray(commands); _i < _a.length; _i++) { + var command = _a[_i]; + var _b = this.getFileAndProject(command), file = _b.file, project = _b.project; + project.getLanguageService().applyCodeActionCommand(command, this.getFormatOptions(file)).then(function (_result) { }, function (_error) { }); + } + return {}; + }; + Session.prototype.getStartAndEndPosition = function (args, scriptInfo) { + var startPosition, endPosition; + if (args.startPosition !== undefined) { + startPosition = args.startPosition; + } + else { + startPosition = scriptInfo.lineOffsetToPosition(args.startLine, args.startOffset); + // save the result so we don't always recompute + args.startPosition = startPosition; + } + if (args.endPosition !== undefined) { + endPosition = args.endPosition; + } + else { + endPosition = scriptInfo.lineOffsetToPosition(args.endLine, args.endOffset); + args.endPosition = endPosition; + } + return { startPosition: startPosition, endPosition: endPosition }; + }; + Session.prototype.mapCodeAction = function (_a) { + var description = _a.description, changes = _a.changes, commands = _a.commands; + return { description: description, changes: this.mapTextChangesToCodeEdits(changes), commands: commands }; + }; + Session.prototype.mapCodeFixAction = function (_a) { + var fixName = _a.fixName, description = _a.description, changes = _a.changes, commands = _a.commands, fixId = _a.fixId, fixAllDescription = _a.fixAllDescription; + return { fixName: fixName, description: description, changes: this.mapTextChangesToCodeEdits(changes), commands: commands, fixId: fixId, fixAllDescription: fixAllDescription }; + }; + Session.prototype.mapTextChangesToCodeEdits = function (textChanges) { + var _this = this; + return textChanges.map(function (change) { return _this.mapTextChangeToCodeEdit(change); }); + }; + Session.prototype.mapTextChangeToCodeEdit = function (textChanges) { + var scriptInfo = this.projectService.getScriptInfoOrConfig(textChanges.fileName); + if (!!textChanges.isNewFile === !!scriptInfo) { + if (!scriptInfo) { // and !isNewFile + this.projectService.logErrorForScriptInfoNotFound(textChanges.fileName); + } + ts.Debug.fail("Expected isNewFile for (only) new files. " + JSON.stringify({ isNewFile: !!textChanges.isNewFile, hasScriptInfo: !!scriptInfo })); + } + return scriptInfo + ? { fileName: textChanges.fileName, textChanges: textChanges.textChanges.map(function (textChange) { return convertTextChangeToCodeEdit(textChange, scriptInfo); }) } + : convertNewFileTextChangeToCodeEdit(textChanges); + }; + Session.prototype.convertTextChangeToCodeEdit = function (change, scriptInfo) { + return { + start: scriptInfo.positionToLineOffset(change.span.start), + end: scriptInfo.positionToLineOffset(change.span.start + change.span.length), + newText: change.newText ? change.newText : "" + }; + }; + Session.prototype.getBraceMatching = function (args, simplifiedResult) { + var _this = this; + var _a = this.getFileAndLanguageServiceForSyntacticOperation(args), file = _a.file, languageService = _a.languageService; + var scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file); + var position = this.getPosition(args, scriptInfo); + var spans = languageService.getBraceMatchingAtPosition(file, position); + return !spans + ? undefined + : simplifiedResult + ? spans.map(function (span) { return _this.toLocationTextSpan(span, scriptInfo); }) + : spans; + }; + Session.prototype.getDiagnosticsForProject = function (next, delay, fileName) { + if (this.suppressDiagnosticEvents) { + return; + } + var _a = this.getProjectInfoWorker(fileName, /*projectFileName*/ undefined, /*needFileNameList*/ true, /*excludeConfigFiles*/ true), fileNames = _a.fileNames, languageServiceDisabled = _a.languageServiceDisabled; + if (languageServiceDisabled) { + return; + } + // No need to analyze lib.d.ts + var fileNamesInProject = fileNames.filter(function (value) { return !ts.stringContains(value, "lib.d.ts"); }); // TODO: GH#18217 + if (fileNamesInProject.length === 0) { + return; + } + // Sort the file name list to make the recently touched files come first + var highPriorityFiles = []; + var mediumPriorityFiles = []; + var lowPriorityFiles = []; + var veryLowPriorityFiles = []; + var normalizedFileName = server.toNormalizedPath(fileName); + var project = this.projectService.ensureDefaultProjectForFile(normalizedFileName); + for (var _i = 0, fileNamesInProject_1 = fileNamesInProject; _i < fileNamesInProject_1.length; _i++) { + var fileNameInProject = fileNamesInProject_1[_i]; + if (this.getCanonicalFileName(fileNameInProject) === this.getCanonicalFileName(fileName)) { + highPriorityFiles.push(fileNameInProject); + } + else { + var info = this.projectService.getScriptInfo(fileNameInProject); // TODO: GH#18217 + if (!info.isScriptOpen()) { + if (ts.fileExtensionIs(fileNameInProject, ".d.ts" /* Dts */)) { + veryLowPriorityFiles.push(fileNameInProject); + } + else { + lowPriorityFiles.push(fileNameInProject); + } + } + else { + mediumPriorityFiles.push(fileNameInProject); + } + } + } + var sortedFiles = highPriorityFiles.concat(mediumPriorityFiles, lowPriorityFiles, veryLowPriorityFiles); + var checkList = sortedFiles.map(function (fileName) { return ({ fileName: fileName, project: project }); }); + // Project level error analysis runs on background files too, therefore + // doesn't require the file to be opened + this.updateErrorCheck(next, checkList, delay, /*requireOpen*/ false); + }; + Session.prototype.configurePlugin = function (args) { + this.projectService.configurePlugin(args); + }; + Session.prototype.getCanonicalFileName = function (fileName) { + var name = this.host.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); + return ts.normalizePath(name); + }; + Session.prototype.exit = function () { }; + Session.prototype.notRequired = function () { + return { responseRequired: false }; + }; + Session.prototype.requiredResponse = function (response) { + return { response: response, responseRequired: true }; + }; + Session.prototype.addProtocolHandler = function (command, handler) { + if (this.handlers.has(command)) { + throw new Error("Protocol handler already exists for command \"" + command + "\""); + } + this.handlers.set(command, handler); + }; + Session.prototype.setCurrentRequest = function (requestId) { + ts.Debug.assert(this.currentRequestId === undefined); + this.currentRequestId = requestId; + this.cancellationToken.setRequest(requestId); + }; + Session.prototype.resetCurrentRequest = function (requestId) { + ts.Debug.assert(this.currentRequestId === requestId); + this.currentRequestId = undefined; // TODO: GH#18217 + this.cancellationToken.resetRequest(requestId); + }; + Session.prototype.executeWithRequestId = function (requestId, f) { + try { + this.setCurrentRequest(requestId); + return f(); + } + finally { + this.resetCurrentRequest(requestId); + } + }; + Session.prototype.executeCommand = function (request) { + var handler = this.handlers.get(request.command); + if (handler) { + return this.executeWithRequestId(request.seq, function () { return handler(request); }); + } + else { + this.logger.msg("Unrecognized JSON command:" + server.stringifyIndented(request), server.Msg.Err); + this.doOutput(/*info*/ undefined, server.CommandNames.Unknown, request.seq, /*success*/ false, "Unrecognized JSON command: " + request.command); + return { responseRequired: false }; + } + }; + Session.prototype.onMessage = function (message) { + this.gcTimer.scheduleCollect(); + var start; + if (this.logger.hasLevel(server.LogLevel.requestTime)) { + start = this.hrtime(); + if (this.logger.hasLevel(server.LogLevel.verbose)) { + this.logger.info("request:" + server.indent(message)); + } + } + var request; + var relevantFile; + try { + request = JSON.parse(message); + relevantFile = request.arguments && request.arguments.file ? request.arguments : undefined; + var _a = this.executeCommand(request), response = _a.response, responseRequired = _a.responseRequired; + if (this.logger.hasLevel(server.LogLevel.requestTime)) { + var elapsedTime = hrTimeToMilliseconds(this.hrtime(start)).toFixed(4); + if (responseRequired) { + this.logger.perftrc(request.seq + "::" + request.command + ": elapsed time (in milliseconds) " + elapsedTime); + } + else { + this.logger.perftrc(request.seq + "::" + request.command + ": async elapsed time (in milliseconds) " + elapsedTime); + } + } + if (response) { + this.doOutput(response, request.command, request.seq, /*success*/ true); + } + else if (responseRequired) { + this.doOutput(/*info*/ undefined, request.command, request.seq, /*success*/ false, "No content available."); + } + } + catch (err) { + if (err instanceof ts.OperationCanceledException) { + // Handle cancellation exceptions + this.doOutput({ canceled: true }, request.command, request.seq, /*success*/ true); + return; + } + this.logErrorWorker(err, message, relevantFile); + this.doOutput( + /*info*/ undefined, request ? request.command : server.CommandNames.Unknown, request ? request.seq : 0, + /*success*/ false, "Error processing request. " + err.message + "\n" + err.stack); + } + }; + Session.prototype.getFormatOptions = function (file) { + return this.projectService.getFormatCodeOptions(file); + }; + Session.prototype.getPreferences = function (file) { + return this.projectService.getPreferences(file); + }; + Session.prototype.getHostFormatOptions = function () { + return this.projectService.getHostFormatCodeOptions(); + }; + Session.prototype.getHostPreferences = function () { + return this.projectService.getHostPreferences(); + }; + return Session; + }()); + server.Session = Session; + function toFileSpan(fileName, textSpan, scriptInfo) { + return { file: fileName, start: scriptInfo.positionToLineOffset(textSpan.start), end: scriptInfo.positionToLineOffset(ts.textSpanEnd(textSpan)) }; + } + function convertTextChangeToCodeEdit(change, scriptInfo) { + return { start: positionToLineOffset(scriptInfo, change.span.start), end: positionToLineOffset(scriptInfo, ts.textSpanEnd(change.span)), newText: change.newText }; + } + function positionToLineOffset(info, position) { + return server.isConfigFile(info) ? locationFromLineAndCharacter(info.getLineAndCharacterOfPosition(position)) : info.positionToLineOffset(position); + } + function locationFromLineAndCharacter(lc) { + return { line: lc.line + 1, offset: lc.character + 1 }; + } + function convertNewFileTextChangeToCodeEdit(textChanges) { + ts.Debug.assert(textChanges.textChanges.length === 1); + var change = ts.first(textChanges.textChanges); + ts.Debug.assert(change.span.start === 0 && change.span.length === 0); + return { fileName: textChanges.fileName, textChanges: [{ start: { line: 0, offset: 0 }, end: { line: 0, offset: 0 }, newText: change.newText }] }; + } + /* @internal */ // Exported only for tests + function getLocationInNewDocument(oldText, renameFilename, renameLocation, edits) { + var newText = applyEdits(oldText, renameFilename, edits); + var _a = ts.computeLineAndCharacterOfPosition(ts.computeLineStarts(newText), renameLocation), line = _a.line, character = _a.character; + return { line: line + 1, offset: character + 1 }; + } + server.getLocationInNewDocument = getLocationInNewDocument; + function applyEdits(text, textFilename, edits) { + for (var _i = 0, edits_2 = edits; _i < edits_2.length; _i++) { + var _a = edits_2[_i], fileName = _a.fileName, textChanges_4 = _a.textChanges; + if (fileName !== textFilename) { + continue; + } + for (var i = textChanges_4.length - 1; i >= 0; i--) { + var _b = textChanges_4[i], newText = _b.newText, _c = _b.span, start = _c.start, length_6 = _c.length; + text = text.slice(0, start) + newText + text.slice(start + length_6); + } + } + return text; + } + })(server = ts.server || (ts.server = {})); +})(ts || (ts = {})); +/*@internal*/ +var ts; +(function (ts) { + var server; + (function (server) { + var lineCollectionCapacity = 4; + var CharRangeSection; + (function (CharRangeSection) { + CharRangeSection[CharRangeSection["PreStart"] = 0] = "PreStart"; + CharRangeSection[CharRangeSection["Start"] = 1] = "Start"; + CharRangeSection[CharRangeSection["Entire"] = 2] = "Entire"; + CharRangeSection[CharRangeSection["Mid"] = 3] = "Mid"; + CharRangeSection[CharRangeSection["End"] = 4] = "End"; + CharRangeSection[CharRangeSection["PostEnd"] = 5] = "PostEnd"; + })(CharRangeSection || (CharRangeSection = {})); + var EditWalker = /** @class */ (function () { + function EditWalker() { + this.goSubtree = true; + this.lineIndex = new LineIndex(); + this.endBranch = []; + this.state = 2 /* Entire */; + this.initialText = ""; + this.trailingText = ""; + this.lineIndex.root = new LineNode(); + this.startPath = [this.lineIndex.root]; + this.stack = [this.lineIndex.root]; + } + Object.defineProperty(EditWalker.prototype, "done", { + get: function () { return false; }, + enumerable: true, + configurable: true + }); + EditWalker.prototype.insertLines = function (insertedText, suppressTrailingText) { + if (suppressTrailingText) { + this.trailingText = ""; + } + if (insertedText) { + insertedText = this.initialText + insertedText + this.trailingText; + } + else { + insertedText = this.initialText + this.trailingText; + } + var lm = LineIndex.linesFromText(insertedText); + var lines = lm.lines; + if (lines.length > 1) { + if (lines[lines.length - 1] === "") { + lines.pop(); + } + } + var branchParent; + var lastZeroCount; + for (var k = this.endBranch.length - 1; k >= 0; k--) { + this.endBranch[k].updateCounts(); + if (this.endBranch[k].charCount() === 0) { + lastZeroCount = this.endBranch[k]; + if (k > 0) { + branchParent = this.endBranch[k - 1]; + } + else { + branchParent = this.branchNode; + } + } + } + if (lastZeroCount) { + branchParent.remove(lastZeroCount); + } + // path at least length two (root and leaf) + var leafNode = this.startPath[this.startPath.length - 1]; + if (lines.length > 0) { + leafNode.text = lines[0]; + if (lines.length > 1) { + var insertedNodes = new Array(lines.length - 1); + var startNode = leafNode; + for (var i = 1; i < lines.length; i++) { + insertedNodes[i - 1] = new LineLeaf(lines[i]); + } + var pathIndex = this.startPath.length - 2; + while (pathIndex >= 0) { + var insertionNode = this.startPath[pathIndex]; + insertedNodes = insertionNode.insertAt(startNode, insertedNodes); + pathIndex--; + startNode = insertionNode; + } + var insertedNodesLen = insertedNodes.length; + while (insertedNodesLen > 0) { + var newRoot = new LineNode(); + newRoot.add(this.lineIndex.root); + insertedNodes = newRoot.insertAt(this.lineIndex.root, insertedNodes); + insertedNodesLen = insertedNodes.length; + this.lineIndex.root = newRoot; + } + this.lineIndex.root.updateCounts(); + } + else { + for (var j = this.startPath.length - 2; j >= 0; j--) { + this.startPath[j].updateCounts(); + } + } + } + else { + var insertionNode = this.startPath[this.startPath.length - 2]; + // no content for leaf node, so delete it + insertionNode.remove(leafNode); + for (var j = this.startPath.length - 2; j >= 0; j--) { + this.startPath[j].updateCounts(); + } + } + return this.lineIndex; + }; + EditWalker.prototype.post = function (_relativeStart, _relativeLength, lineCollection) { + // have visited the path for start of range, now looking for end + // if range is on single line, we will never make this state transition + if (lineCollection === this.lineCollectionAtBranch) { + this.state = 4 /* End */; + } + // always pop stack because post only called when child has been visited + this.stack.pop(); + }; + EditWalker.prototype.pre = function (_relativeStart, _relativeLength, lineCollection, _parent, nodeType) { + // currentNode corresponds to parent, but in the new tree + var currentNode = this.stack[this.stack.length - 1]; + if ((this.state === 2 /* Entire */) && (nodeType === 1 /* Start */)) { + // if range is on single line, we will never make this state transition + this.state = 1 /* Start */; + this.branchNode = currentNode; + this.lineCollectionAtBranch = lineCollection; + } + var child; + function fresh(node) { + if (node.isLeaf()) { + return new LineLeaf(""); + } + else + return new LineNode(); + } + switch (nodeType) { + case 0 /* PreStart */: + this.goSubtree = false; + if (this.state !== 4 /* End */) { + currentNode.add(lineCollection); + } + break; + case 1 /* Start */: + if (this.state === 4 /* End */) { + this.goSubtree = false; + } + else { + child = fresh(lineCollection); + currentNode.add(child); + this.startPath.push(child); + } + break; + case 2 /* Entire */: + if (this.state !== 4 /* End */) { + child = fresh(lineCollection); + currentNode.add(child); + this.startPath.push(child); + } + else { + if (!lineCollection.isLeaf()) { + child = fresh(lineCollection); + currentNode.add(child); + this.endBranch.push(child); + } + } + break; + case 3 /* Mid */: + this.goSubtree = false; + break; + case 4 /* End */: + if (this.state !== 4 /* End */) { + this.goSubtree = false; + } + else { + if (!lineCollection.isLeaf()) { + child = fresh(lineCollection); + currentNode.add(child); + this.endBranch.push(child); + } + } + break; + case 5 /* PostEnd */: + this.goSubtree = false; + if (this.state !== 1 /* Start */) { + currentNode.add(lineCollection); + } + break; + } + if (this.goSubtree) { + this.stack.push(child); + } + }; + // just gather text from the leaves + EditWalker.prototype.leaf = function (relativeStart, relativeLength, ll) { + if (this.state === 1 /* Start */) { + this.initialText = ll.text.substring(0, relativeStart); + } + else if (this.state === 2 /* Entire */) { + this.initialText = ll.text.substring(0, relativeStart); + this.trailingText = ll.text.substring(relativeStart + relativeLength); + } + else { + // state is CharRangeSection.End + this.trailingText = ll.text.substring(relativeStart + relativeLength); + } + }; + return EditWalker; + }()); + // text change information + var TextChange = /** @class */ (function () { + function TextChange(pos, deleteLen, insertedText) { + this.pos = pos; + this.deleteLen = deleteLen; + this.insertedText = insertedText; + } + TextChange.prototype.getTextChangeRange = function () { + return ts.createTextChangeRange(ts.createTextSpan(this.pos, this.deleteLen), this.insertedText ? this.insertedText.length : 0); + }; + return TextChange; + }()); + var ScriptVersionCache = /** @class */ (function () { + function ScriptVersionCache() { + this.changes = []; + this.versions = new Array(ScriptVersionCache.maxVersions); + this.minVersion = 0; // no versions earlier than min version will maintain change history + this.currentVersion = 0; + } + ScriptVersionCache.prototype.versionToIndex = function (version) { + if (version < this.minVersion || version > this.currentVersion) { + return undefined; + } + return version % ScriptVersionCache.maxVersions; + }; + ScriptVersionCache.prototype.currentVersionToIndex = function () { + return this.currentVersion % ScriptVersionCache.maxVersions; + }; + // REVIEW: can optimize by coalescing simple edits + ScriptVersionCache.prototype.edit = function (pos, deleteLen, insertedText) { + this.changes.push(new TextChange(pos, deleteLen, insertedText)); + if (this.changes.length > ScriptVersionCache.changeNumberThreshold || + deleteLen > ScriptVersionCache.changeLengthThreshold || + insertedText && insertedText.length > ScriptVersionCache.changeLengthThreshold) { + this.getSnapshot(); + } + }; + ScriptVersionCache.prototype.getSnapshot = function () { return this._getSnapshot(); }; + ScriptVersionCache.prototype._getSnapshot = function () { + var snap = this.versions[this.currentVersionToIndex()]; + if (this.changes.length > 0) { + var snapIndex = snap.index; + for (var _i = 0, _a = this.changes; _i < _a.length; _i++) { + var change = _a[_i]; + snapIndex = snapIndex.edit(change.pos, change.deleteLen, change.insertedText); + } + snap = new LineIndexSnapshot(this.currentVersion + 1, this, snapIndex, this.changes); + this.currentVersion = snap.version; + this.versions[this.currentVersionToIndex()] = snap; + this.changes = []; + if ((this.currentVersion - this.minVersion) >= ScriptVersionCache.maxVersions) { + this.minVersion = (this.currentVersion - ScriptVersionCache.maxVersions) + 1; + } + } + return snap; + }; + ScriptVersionCache.prototype.getSnapshotVersion = function () { + return this._getSnapshot().version; + }; + ScriptVersionCache.prototype.getLineInfo = function (line) { + return this._getSnapshot().index.lineNumberToInfo(line); + }; + ScriptVersionCache.prototype.lineOffsetToPosition = function (line, column) { + return this._getSnapshot().index.absolutePositionOfStartOfLine(line) + (column - 1); + }; + ScriptVersionCache.prototype.positionToLineOffset = function (position) { + return this._getSnapshot().index.positionToLineOffset(position); + }; + ScriptVersionCache.prototype.lineToTextSpan = function (line) { + var index = this._getSnapshot().index; + var _a = index.lineNumberToInfo(line + 1), lineText = _a.lineText, absolutePosition = _a.absolutePosition; + var len = lineText !== undefined ? lineText.length : index.absolutePositionOfStartOfLine(line + 2) - absolutePosition; + return ts.createTextSpan(absolutePosition, len); + }; + ScriptVersionCache.prototype.getTextChangesBetweenVersions = function (oldVersion, newVersion) { + if (oldVersion < newVersion) { + if (oldVersion >= this.minVersion) { + var textChangeRanges = []; + for (var i = oldVersion + 1; i <= newVersion; i++) { + var snap = this.versions[this.versionToIndex(i)]; // TODO: GH#18217 + for (var _i = 0, _a = snap.changesSincePreviousVersion; _i < _a.length; _i++) { + var textChange = _a[_i]; + textChangeRanges.push(textChange.getTextChangeRange()); + } + } + return ts.collapseTextChangeRangesAcrossMultipleVersions(textChangeRanges); + } + else { + return undefined; + } + } + else { + return ts.unchangedTextChangeRange; + } + }; + ScriptVersionCache.fromString = function (script) { + var svc = new ScriptVersionCache(); + var snap = new LineIndexSnapshot(0, svc, new LineIndex()); + svc.versions[svc.currentVersion] = snap; + var lm = LineIndex.linesFromText(script); + snap.index.load(lm.lines); + return svc; + }; + ScriptVersionCache.changeNumberThreshold = 8; + ScriptVersionCache.changeLengthThreshold = 256; + ScriptVersionCache.maxVersions = 8; + return ScriptVersionCache; + }()); + server.ScriptVersionCache = ScriptVersionCache; + var LineIndexSnapshot = /** @class */ (function () { + function LineIndexSnapshot(version, cache, index, changesSincePreviousVersion) { + if (changesSincePreviousVersion === void 0) { changesSincePreviousVersion = server.emptyArray; } + this.version = version; + this.cache = cache; + this.index = index; + this.changesSincePreviousVersion = changesSincePreviousVersion; + } + LineIndexSnapshot.prototype.getText = function (rangeStart, rangeEnd) { + return this.index.getText(rangeStart, rangeEnd - rangeStart); + }; + LineIndexSnapshot.prototype.getLength = function () { + return this.index.getLength(); + }; + LineIndexSnapshot.prototype.getChangeRange = function (oldSnapshot) { + if (oldSnapshot instanceof LineIndexSnapshot && this.cache === oldSnapshot.cache) { + if (this.version <= oldSnapshot.version) { + return ts.unchangedTextChangeRange; + } + else { + return this.cache.getTextChangesBetweenVersions(oldSnapshot.version, this.version); + } + } + }; + return LineIndexSnapshot; + }()); + var LineIndex = /** @class */ (function () { + function LineIndex() { + // set this to true to check each edit for accuracy + this.checkEdits = false; + } + LineIndex.prototype.absolutePositionOfStartOfLine = function (oneBasedLine) { + return this.lineNumberToInfo(oneBasedLine).absolutePosition; + }; + LineIndex.prototype.positionToLineOffset = function (position) { + var _a = this.root.charOffsetToLineInfo(1, position), oneBasedLine = _a.oneBasedLine, zeroBasedColumn = _a.zeroBasedColumn; + return { line: oneBasedLine, offset: zeroBasedColumn + 1 }; + }; + LineIndex.prototype.positionToColumnAndLineText = function (position) { + return this.root.charOffsetToLineInfo(1, position); + }; + LineIndex.prototype.lineNumberToInfo = function (oneBasedLine) { + var lineCount = this.root.lineCount(); + if (oneBasedLine <= lineCount) { + var _a = this.root.lineNumberToInfo(oneBasedLine, 0), position = _a.position, leaf = _a.leaf; + return { absolutePosition: position, lineText: leaf && leaf.text }; + } + else { + return { absolutePosition: this.root.charCount(), lineText: undefined }; + } + }; + LineIndex.prototype.load = function (lines) { + if (lines.length > 0) { + var leaves = []; + for (var i = 0; i < lines.length; i++) { + leaves[i] = new LineLeaf(lines[i]); + } + this.root = LineIndex.buildTreeFromBottom(leaves); + } + else { + this.root = new LineNode(); + } + }; + LineIndex.prototype.walk = function (rangeStart, rangeLength, walkFns) { + this.root.walk(rangeStart, rangeLength, walkFns); + }; + LineIndex.prototype.getText = function (rangeStart, rangeLength) { + var accum = ""; + if ((rangeLength > 0) && (rangeStart < this.root.charCount())) { + this.walk(rangeStart, rangeLength, { + goSubtree: true, + done: false, + leaf: function (relativeStart, relativeLength, ll) { + accum = accum.concat(ll.text.substring(relativeStart, relativeStart + relativeLength)); + } + }); + } + return accum; + }; + LineIndex.prototype.getLength = function () { + return this.root.charCount(); + }; + LineIndex.prototype.every = function (f, rangeStart, rangeEnd) { + if (!rangeEnd) { + rangeEnd = this.root.charCount(); + } + var walkFns = { + goSubtree: true, + done: false, + leaf: function (relativeStart, relativeLength, ll) { + if (!f(ll, relativeStart, relativeLength)) { + this.done = true; + } + } + }; + this.walk(rangeStart, rangeEnd - rangeStart, walkFns); + return !walkFns.done; + }; + LineIndex.prototype.edit = function (pos, deleteLength, newText) { + if (this.root.charCount() === 0) { + ts.Debug.assert(deleteLength === 0); // Can't delete from empty document + if (newText !== undefined) { + this.load(LineIndex.linesFromText(newText).lines); + return this; + } + return undefined; // TODO: GH#18217 + } + else { + var checkText = void 0; + if (this.checkEdits) { + var source = this.getText(0, this.root.charCount()); + checkText = source.slice(0, pos) + newText + source.slice(pos + deleteLength); + } + var walker = new EditWalker(); + var suppressTrailingText = false; + if (pos >= this.root.charCount()) { + // insert at end + pos = this.root.charCount() - 1; + var endString = this.getText(pos, 1); + if (newText) { + newText = endString + newText; + } + else { + newText = endString; + } + deleteLength = 0; + suppressTrailingText = true; + } + else if (deleteLength > 0) { + // check whether last characters deleted are line break + var e = pos + deleteLength; + var _a = this.positionToColumnAndLineText(e), zeroBasedColumn = _a.zeroBasedColumn, lineText = _a.lineText; + if (zeroBasedColumn === 0) { + // move range end just past line that will merge with previous line + deleteLength += lineText.length; // TODO: GH#18217 + // store text by appending to end of insertedText + newText = newText ? newText + lineText : lineText; + } + } + this.root.walk(pos, deleteLength, walker); + walker.insertLines(newText, suppressTrailingText); + if (this.checkEdits) { + var updatedText = walker.lineIndex.getText(0, walker.lineIndex.getLength()); + ts.Debug.assert(checkText === updatedText, "buffer edit mismatch"); + } + return walker.lineIndex; + } + }; + LineIndex.buildTreeFromBottom = function (nodes) { + if (nodes.length < lineCollectionCapacity) { + return new LineNode(nodes); + } + var interiorNodes = new Array(Math.ceil(nodes.length / lineCollectionCapacity)); + var nodeIndex = 0; + for (var i = 0; i < interiorNodes.length; i++) { + var end = Math.min(nodeIndex + lineCollectionCapacity, nodes.length); + interiorNodes[i] = new LineNode(nodes.slice(nodeIndex, end)); + nodeIndex = end; + } + return this.buildTreeFromBottom(interiorNodes); + }; + LineIndex.linesFromText = function (text) { + var lineMap = ts.computeLineStarts(text); + if (lineMap.length === 0) { + return { lines: [], lineMap: lineMap }; + } + var lines = new Array(lineMap.length); + var lc = lineMap.length - 1; + for (var lmi = 0; lmi < lc; lmi++) { + lines[lmi] = text.substring(lineMap[lmi], lineMap[lmi + 1]); + } + var endText = text.substring(lineMap[lc]); + if (endText.length > 0) { + lines[lc] = endText; + } + else { + lines.pop(); + } + return { lines: lines, lineMap: lineMap }; + }; + return LineIndex; + }()); + server.LineIndex = LineIndex; + var LineNode = /** @class */ (function () { + function LineNode(children) { + if (children === void 0) { children = []; } + this.children = children; + this.totalChars = 0; + this.totalLines = 0; + if (children.length) + this.updateCounts(); + } + LineNode.prototype.isLeaf = function () { + return false; + }; + LineNode.prototype.updateCounts = function () { + this.totalChars = 0; + this.totalLines = 0; + for (var _i = 0, _a = this.children; _i < _a.length; _i++) { + var child = _a[_i]; + this.totalChars += child.charCount(); + this.totalLines += child.lineCount(); + } + }; + LineNode.prototype.execWalk = function (rangeStart, rangeLength, walkFns, childIndex, nodeType) { + if (walkFns.pre) { + walkFns.pre(rangeStart, rangeLength, this.children[childIndex], this, nodeType); + } + if (walkFns.goSubtree) { + this.children[childIndex].walk(rangeStart, rangeLength, walkFns); + if (walkFns.post) { + walkFns.post(rangeStart, rangeLength, this.children[childIndex], this, nodeType); + } + } + else { + walkFns.goSubtree = true; + } + return walkFns.done; + }; + LineNode.prototype.skipChild = function (relativeStart, relativeLength, childIndex, walkFns, nodeType) { + if (walkFns.pre && (!walkFns.done)) { + walkFns.pre(relativeStart, relativeLength, this.children[childIndex], this, nodeType); + walkFns.goSubtree = true; + } + }; + LineNode.prototype.walk = function (rangeStart, rangeLength, walkFns) { + // assume (rangeStart < this.totalChars) && (rangeLength <= this.totalChars) + var childIndex = 0; + var childCharCount = this.children[childIndex].charCount(); + // find sub-tree containing start + var adjustedStart = rangeStart; + while (adjustedStart >= childCharCount) { + this.skipChild(adjustedStart, rangeLength, childIndex, walkFns, 0 /* PreStart */); + adjustedStart -= childCharCount; + childIndex++; + childCharCount = this.children[childIndex].charCount(); + } + // Case I: both start and end of range in same subtree + if ((adjustedStart + rangeLength) <= childCharCount) { + if (this.execWalk(adjustedStart, rangeLength, walkFns, childIndex, 2 /* Entire */)) { + return; + } + } + else { + // Case II: start and end of range in different subtrees (possibly with subtrees in the middle) + if (this.execWalk(adjustedStart, childCharCount - adjustedStart, walkFns, childIndex, 1 /* Start */)) { + return; + } + var adjustedLength = rangeLength - (childCharCount - adjustedStart); + childIndex++; + var child = this.children[childIndex]; + childCharCount = child.charCount(); + while (adjustedLength > childCharCount) { + if (this.execWalk(0, childCharCount, walkFns, childIndex, 3 /* Mid */)) { + return; + } + adjustedLength -= childCharCount; + childIndex++; + childCharCount = this.children[childIndex].charCount(); + } + if (adjustedLength > 0) { + if (this.execWalk(0, adjustedLength, walkFns, childIndex, 4 /* End */)) { + return; + } + } + } + // Process any subtrees after the one containing range end + if (walkFns.pre) { + var clen = this.children.length; + if (childIndex < (clen - 1)) { + for (var ej = childIndex + 1; ej < clen; ej++) { + this.skipChild(0, 0, ej, walkFns, 5 /* PostEnd */); + } + } + } + }; + // Input position is relative to the start of this node. + // Output line number is absolute. + LineNode.prototype.charOffsetToLineInfo = function (lineNumberAccumulator, relativePosition) { + if (this.children.length === 0) { + // Root node might have no children if this is an empty document. + return { oneBasedLine: lineNumberAccumulator, zeroBasedColumn: relativePosition, lineText: undefined }; + } + for (var _i = 0, _a = this.children; _i < _a.length; _i++) { + var child = _a[_i]; + if (child.charCount() > relativePosition) { + if (child.isLeaf()) { + return { oneBasedLine: lineNumberAccumulator, zeroBasedColumn: relativePosition, lineText: child.text }; + } + else { + return child.charOffsetToLineInfo(lineNumberAccumulator, relativePosition); + } + } + else { + relativePosition -= child.charCount(); + lineNumberAccumulator += child.lineCount(); + } + } + // Skipped all children + var leaf = this.lineNumberToInfo(this.lineCount(), 0).leaf; + return { oneBasedLine: this.lineCount(), zeroBasedColumn: leaf ? leaf.charCount() : 0, lineText: undefined }; + }; + /** + * Input line number is relative to the start of this node. + * Output line number is relative to the child. + * positionAccumulator will be an absolute position once relativeLineNumber reaches 0. + */ + LineNode.prototype.lineNumberToInfo = function (relativeOneBasedLine, positionAccumulator) { + for (var _i = 0, _a = this.children; _i < _a.length; _i++) { + var child = _a[_i]; + var childLineCount = child.lineCount(); + if (childLineCount >= relativeOneBasedLine) { + return child.isLeaf() ? { position: positionAccumulator, leaf: child } : child.lineNumberToInfo(relativeOneBasedLine, positionAccumulator); + } + else { + relativeOneBasedLine -= childLineCount; + positionAccumulator += child.charCount(); + } + } + return { position: positionAccumulator, leaf: undefined }; + }; + LineNode.prototype.splitAfter = function (childIndex) { + var splitNode; + var clen = this.children.length; + childIndex++; + var endLength = childIndex; + if (childIndex < clen) { + splitNode = new LineNode(); + while (childIndex < clen) { + splitNode.add(this.children[childIndex]); + childIndex++; + } + splitNode.updateCounts(); + } + this.children.length = endLength; + return splitNode; + }; + LineNode.prototype.remove = function (child) { + var childIndex = this.findChildIndex(child); + var clen = this.children.length; + if (childIndex < (clen - 1)) { + for (var i = childIndex; i < (clen - 1); i++) { + this.children[i] = this.children[i + 1]; + } + } + this.children.pop(); + }; + LineNode.prototype.findChildIndex = function (child) { + var childIndex = this.children.indexOf(child); + ts.Debug.assert(childIndex !== -1); + return childIndex; + }; + LineNode.prototype.insertAt = function (child, nodes) { + var childIndex = this.findChildIndex(child); + var clen = this.children.length; + var nodeCount = nodes.length; + // if child is last and there is more room and only one node to place, place it + if ((clen < lineCollectionCapacity) && (childIndex === (clen - 1)) && (nodeCount === 1)) { + this.add(nodes[0]); + this.updateCounts(); + return []; + } + else { + var shiftNode = this.splitAfter(childIndex); + var nodeIndex = 0; + childIndex++; + while ((childIndex < lineCollectionCapacity) && (nodeIndex < nodeCount)) { + this.children[childIndex] = nodes[nodeIndex]; + childIndex++; + nodeIndex++; + } + var splitNodes = []; + var splitNodeCount = 0; + if (nodeIndex < nodeCount) { + splitNodeCount = Math.ceil((nodeCount - nodeIndex) / lineCollectionCapacity); + splitNodes = new Array(splitNodeCount); + var splitNodeIndex = 0; + for (var i = 0; i < splitNodeCount; i++) { + splitNodes[i] = new LineNode(); + } + var splitNode = splitNodes[0]; + while (nodeIndex < nodeCount) { + splitNode.add(nodes[nodeIndex]); + nodeIndex++; + if (splitNode.children.length === lineCollectionCapacity) { + splitNodeIndex++; + splitNode = splitNodes[splitNodeIndex]; + } + } + for (var i = splitNodes.length - 1; i >= 0; i--) { + if (splitNodes[i].children.length === 0) { + splitNodes.pop(); + } + } + } + if (shiftNode) { + splitNodes.push(shiftNode); + } + this.updateCounts(); + for (var i = 0; i < splitNodeCount; i++) { + splitNodes[i].updateCounts(); + } + return splitNodes; + } + }; + // assume there is room for the item; return true if more room + LineNode.prototype.add = function (collection) { + this.children.push(collection); + ts.Debug.assert(this.children.length <= lineCollectionCapacity); + }; + LineNode.prototype.charCount = function () { + return this.totalChars; + }; + LineNode.prototype.lineCount = function () { + return this.totalLines; + }; + return LineNode; + }()); + var LineLeaf = /** @class */ (function () { + function LineLeaf(text) { + this.text = text; + } + LineLeaf.prototype.isLeaf = function () { + return true; + }; + LineLeaf.prototype.walk = function (rangeStart, rangeLength, walkFns) { + walkFns.leaf(rangeStart, rangeLength, this); + }; + LineLeaf.prototype.charCount = function () { + return this.text.length; + }; + LineLeaf.prototype.lineCount = function () { + return 1; + }; + return LineLeaf; + }()); + })(server = ts.server || (ts.server = {})); +})(ts || (ts = {})); +//# sourceMappingURL=tsserverlibrary.out.js.map \ No newline at end of file diff --git a/node_modules/typescript/lib/typesMap.json b/node_modules/typescript/lib/typesMap.json new file mode 100644 index 0000000..fe286d3 --- /dev/null +++ b/node_modules/typescript/lib/typesMap.json @@ -0,0 +1,497 @@ +{ + "typesMap": { + "jquery": { + "match": "jquery(-(\\.?\\d+)+)?(\\.intellisense)?(\\.min)?\\.js$", + "types": ["jquery"] + }, + "WinJS": { + "match": "^(.*\\/winjs-[.\\d]+)\\/js\\/base\\.js$", + "exclude": [["^", 1, "/.*"]], + "types": ["winjs"] + }, + "Kendo": { + "match": "^(.*\\/kendo(-ui)?)\\/kendo\\.all(\\.min)?\\.js$", + "exclude": [["^", 1, "/.*"]], + "types": ["kendo-ui"] + }, + "Office Nuget": { + "match": "^(.*\\/office\\/1)\\/excel-\\d+\\.debug\\.js$", + "exclude": [["^", 1, "/.*"]], + "types": ["office"] + }, + "References": { + "match": "^(.*\\/_references\\.js)$", + "exclude": [["^", 1, "$"]] + }, + "Datatables.net": { + "match": "^.*\\/(jquery\\.)?dataTables(\\.all)?(\\.min)?\\.js$", + "types": ["datatables.net"] + }, + "Ace": { + "match": "^(.*)\\/ace.js", + "exclude": [["^", 1, "/.*"]], + "types": ["ace"] + } + }, + "simpleMap": { + "accounting": "accounting", + "ace.js": "ace", + "ag-grid": "ag-grid", + "alertify": "alertify", + "alt": "alt", + "amcharts.js": "amcharts", + "amplify": "amplifyjs", + "angular": "angular", + "angular-bootstrap-lightbox": "angular-bootstrap-lightbox", + "angular-cookie": "angular-cookie", + "angular-file-upload": "angular-file-upload", + "angularfire": "angularfire", + "angular-gettext": "angular-gettext", + "angular-google-analytics": "angular-google-analytics", + "angular-local-storage": "angular-local-storage", + "angularLocalStorage": "angularLocalStorage", + "angular-scroll": "angular-scroll", + "angular-spinner": "angular-spinner", + "angular-strap": "angular-strap", + "angulartics": "angulartics", + "angular-toastr": "angular-toastr", + "angular-translate": "angular-translate", + "angular-ui-router": "angular-ui-router", + "angular-ui-tree": "angular-ui-tree", + "angular-wizard": "angular-wizard", + "async": "async", + "atmosphere": "atmosphere", + "aws-sdk": "aws-sdk", + "aws-sdk-js": "aws-sdk", + "axios": "axios", + "backbone": "backbone", + "backbone.layoutmanager": "backbone.layoutmanager", + "backbone.paginator": "backbone.paginator", + "backbone.radio": "backbone.radio", + "backbone-associations": "backbone-associations", + "backbone-relational": "backbone-relational", + "backgrid": "backgrid", + "Bacon": "baconjs", + "benchmark": "benchmark", + "blazy": "blazy", + "bliss": "blissfuljs", + "bluebird": "bluebird", + "body-parser": "body-parser", + "bootbox": "bootbox", + "bootstrap": "bootstrap", + "bootstrap-editable": "x-editable", + "bootstrap-maxlength": "bootstrap-maxlength", + "bootstrap-notify": "bootstrap-notify", + "bootstrap-slider": "bootstrap-slider", + "bootstrap-switch": "bootstrap-switch", + "bowser": "bowser", + "breeze": "breeze", + "browserify": "browserify", + "bson": "bson", + "c3": "c3", + "canvasjs": "canvasjs", + "chai": "chai", + "chalk": "chalk", + "chance": "chance", + "chartist": "chartist", + "cheerio": "cheerio", + "chokidar": "chokidar", + "chosen.jquery": "chosen", + "chroma": "chroma-js", + "ckeditor.js": "ckeditor", + "cli-color": "cli-color", + "clipboard": "clipboard", + "codemirror": "codemirror", + "colors": "colors", + "commander": "commander", + "commonmark": "commonmark", + "compression": "compression", + "confidence": "confidence", + "connect": "connect", + "Control.FullScreen": "leaflet.fullscreen", + "cookie": "cookie", + "cookie-parser": "cookie-parser", + "cookies": "cookies", + "core": "core-js", + "core-js": "core-js", + "crossfilter": "crossfilter", + "crossroads": "crossroads", + "css": "css", + "ct-ui-router-extras": "ui-router-extras", + "d3": "d3", + "dagre-d3": "dagre-d3", + "dat.gui": "dat-gui", + "debug": "debug", + "deep-diff": "deep-diff", + "Dexie": "dexie", + "dialogs": "angular-dialog-service", + "dojo.js": "dojo", + "doT": "dot", + "dragula": "dragula", + "drop": "drop", + "dropbox": "dropboxjs", + "dropzone": "dropzone", + "Dts Name": "Dts Name", + "dust-core": "dustjs-linkedin", + "easeljs": "easeljs", + "ejs": "ejs", + "ember": "ember", + "envify": "envify", + "epiceditor": "epiceditor", + "es6-promise": "es6-promise", + "ES6-Promise": "es6-promise", + "es6-shim": "es6-shim", + "expect": "expect", + "express": "express", + "express-session": "express-session", + "ext-all.js": "extjs", + "extend": "extend", + "fabric": "fabricjs", + "faker": "faker", + "fastclick": "fastclick", + "favico": "favico.js", + "featherlight": "featherlight", + "FileSaver": "FileSaver", + "fingerprint": "fingerprintjs", + "fixed-data-table": "fixed-data-table", + "flickity.pkgd": "flickity", + "flight": "flight", + "flow": "flowjs", + "Flux": "flux", + "formly": "angular-formly", + "foundation": "foundation", + "fpsmeter": "fpsmeter", + "fuse": "fuse", + "generator": "yeoman-generator", + "gl-matrix": "gl-matrix", + "globalize": "globalize", + "graceful-fs": "graceful-fs", + "gridstack": "gridstack", + "gulp": "gulp", + "gulp-rename": "gulp-rename", + "gulp-uglify": "gulp-uglify", + "gulp-util": "gulp-util", + "hammer": "hammerjs", + "handlebars": "handlebars", + "hasher": "hasher", + "he": "he", + "hello.all": "hellojs", + "highcharts.js": "highcharts", + "highlight": "highlightjs", + "history": "history", + "History": "history", + "hopscotch": "hopscotch", + "hotkeys": "angular-hotkeys", + "html2canvas": "html2canvas", + "humane": "humane", + "i18next": "i18next", + "icheck": "icheck", + "impress": "impress", + "incremental-dom": "incremental-dom", + "Inquirer": "inquirer", + "insight": "insight", + "interact": "interactjs", + "intercom": "intercomjs", + "intro": "intro.js", + "ion.rangeSlider": "ion.rangeSlider", + "ionic": "ionic", + "is": "is_js", + "iscroll": "iscroll", + "jade": "jade", + "jasmine": "jasmine", + "joint": "jointjs", + "jquery": "jquery", + "jquery.address": "jquery.address", + "jquery.are-you-sure": "jquery.are-you-sure", + "jquery.blockUI": "jquery.blockUI", + "jquery.bootstrap.wizard": "jquery.bootstrap.wizard", + "jquery.bootstrap-touchspin": "bootstrap-touchspin", + "jquery.color": "jquery.color", + "jquery.colorbox": "jquery.colorbox", + "jquery.contextMenu": "jquery.contextMenu", + "jquery.cookie": "jquery.cookie", + "jquery.customSelect": "jquery.customSelect", + "jquery.cycle.all": "jquery.cycle", + "jquery.cycle2": "jquery.cycle2", + "jquery.dataTables": "jquery.dataTables", + "jquery.dropotron": "jquery.dropotron", + "jquery.fancybox.pack.js": "fancybox", + "jquery.fancytree-all": "jquery.fancytree", + "jquery.fileupload": "jquery.fileupload", + "jquery.flot": "flot", + "jquery.form": "jquery.form", + "jquery.gridster": "jquery.gridster", + "jquery.handsontable.full": "jquery-handsontable", + "jquery.joyride": "jquery.joyride", + "jquery.jqGrid": "jqgrid", + "jquery.mmenu": "jquery.mmenu", + "jquery.mockjax": "jquery-mockjax", + "jquery.noty": "jquery.noty", + "jquery.payment": "jquery.payment", + "jquery.pjax": "jquery.pjax", + "jquery.placeholder": "jquery.placeholder", + "jquery.qrcode": "jquery.qrcode", + "jquery.qtip": "qtip2", + "jquery.raty": "raty", + "jquery.scrollTo": "jquery.scrollTo", + "jquery.signalR": "signalr", + "jquery.simplemodal": "jquery.simplemodal", + "jquery.timeago": "jquery.timeago", + "jquery.tinyscrollbar": "jquery.tinyscrollbar", + "jquery.tipsy": "jquery.tipsy", + "jquery.tooltipster": "tooltipster", + "jquery.transit": "jquery.transit", + "jquery.uniform": "jquery.uniform", + "jquery.watch": "watch", + "jquery-sortable": "jquery-sortable", + "jquery-ui": "jqueryui", + "js.cookie": "js-cookie", + "js-data": "js-data", + "js-data-angular": "js-data-angular", + "js-data-http": "js-data-http", + "jsdom": "jsdom", + "jsnlog": "jsnlog", + "json5": "json5", + "jspdf": "jspdf", + "jsrender": "jsrender", + "js-signals": "js-signals", + "jstorage": "jstorage", + "jstree": "jstree", + "js-yaml": "js-yaml", + "jszip": "jszip", + "katex": "katex", + "kefir": "kefir", + "keymaster": "keymaster", + "keypress": "keypress", + "kinetic": "kineticjs", + "knockback": "knockback", + "knockout": "knockout", + "knockout.mapping": "knockout.mapping", + "knockout.validation": "knockout.validation", + "knockout-paging": "knockout-paging", + "knockout-pre-rendered": "knockout-pre-rendered", + "ladda": "ladda", + "later": "later", + "lazy": "lazy.js", + "Leaflet.Editable": "leaflet-editable", + "leaflet.js": "leaflet", + "less": "less", + "linq": "linq", + "loading-bar": "angular-loading-bar", + "lodash": "lodash", + "log4javascript": "log4javascript", + "loglevel": "loglevel", + "lokijs": "lokijs", + "lovefield": "lovefield", + "lunr": "lunr", + "lz-string": "lz-string", + "mailcheck": "mailcheck", + "maquette": "maquette", + "marked": "marked", + "math": "mathjs", + "MathJax.js": "mathjax", + "matter": "matter-js", + "md5": "blueimp-md5", + "md5.js": "crypto-js", + "messenger": "messenger", + "method-override": "method-override", + "minimatch": "minimatch", + "minimist": "minimist", + "mithril": "mithril", + "mobile-detect": "mobile-detect", + "mocha": "mocha", + "mock-ajax": "jasmine-ajax", + "modernizr": "modernizr", + "Modernizr": "Modernizr", + "moment": "moment", + "moment-range": "moment-range", + "moment-timezone": "moment-timezone", + "mongoose": "mongoose", + "morgan": "morgan", + "mousetrap": "mousetrap", + "ms": "ms", + "mustache": "mustache", + "native.history": "history", + "nconf": "nconf", + "ncp": "ncp", + "nedb": "nedb", + "ng-cordova": "ng-cordova", + "ngDialog": "ng-dialog", + "ng-flow-standalone": "ng-flow", + "ng-grid": "ng-grid", + "ng-i18next": "ng-i18next", + "ng-table": "ng-table", + "node_redis": "redis", + "node-clone": "clone", + "node-fs-extra": "fs-extra", + "node-glob": "glob", + "Nodemailer": "nodemailer", + "node-mime": "mime", + "node-mkdirp": "mkdirp", + "node-mongodb-native": "mongodb", + "node-mysql": "mysql", + "node-open": "open", + "node-optimist": "optimist", + "node-progress": "progress", + "node-semver": "semver", + "node-tar": "tar", + "node-uuid": "node-uuid", + "node-xml2js": "xml2js", + "nopt": "nopt", + "notify": "notify", + "nouislider": "nouislider", + "npm": "npm", + "nprogress": "nprogress", + "numbro": "numbro", + "numeral": "numeraljs", + "nunjucks": "nunjucks", + "nv.d3": "nvd3", + "object-assign": "object-assign", + "oboe-browser": "oboe", + "office": "office-js", + "offline": "offline-js", + "onsenui": "onsenui", + "OpenLayers.js": "openlayers", + "openpgp": "openpgp", + "p2": "p2", + "packery.pkgd": "packery", + "page": "page", + "pako": "pako", + "papaparse": "papaparse", + "passport": "passport", + "passport-local": "passport-local", + "path": "pathjs", + "pdfkit":"pdfkit", + "peer": "peerjs", + "peg": "pegjs", + "photoswipe": "photoswipe", + "picker.js": "pickadate", + "pikaday": "pikaday", + "pixi": "pixi.js", + "platform": "platform", + "Please": "pleasejs", + "plottable": "plottable", + "polymer": "polymer", + "postal": "postal", + "preloadjs": "preloadjs", + "progress": "progress", + "purify": "dompurify", + "purl": "purl", + "q": "q", + "qs": "qs", + "qunit": "qunit", + "ractive": "ractive", + "rangy-core": "rangy", + "raphael": "raphael", + "raven": "ravenjs", + "react": "react", + "react-bootstrap": "react-bootstrap", + "react-intl": "react-intl", + "react-redux": "react-redux", + "ReactRouter": "react-router", + "ready": "domready", + "redux": "redux", + "request": "request", + "require": "require", + "restangular": "restangular", + "reveal": "reveal", + "rickshaw": "rickshaw", + "rimraf": "rimraf", + "rivets": "rivets", + "rx": "rx", + "rx.angular": "rx-angular", + "sammy": "sammyjs", + "SAT": "sat", + "sax-js": "sax", + "screenfull": "screenfull", + "seedrandom": "seedrandom", + "select2": "select2", + "selectize": "selectize", + "serve-favicon": "serve-favicon", + "serve-static": "serve-static", + "shelljs": "shelljs", + "should": "should", + "showdown": "showdown", + "sigma": "sigmajs", + "signature_pad": "signature_pad", + "sinon": "sinon", + "sjcl": "sjcl", + "slick": "slick-carousel", + "smoothie": "smoothie", + "socket.io": "socket.io", + "socket.io-client": "socket.io-client", + "sockjs": "sockjs-client", + "sortable": "angular-ui-sortable", + "soundjs": "soundjs", + "source-map": "source-map", + "spectrum": "spectrum", + "spin": "spin", + "sprintf": "sprintf", + "stampit": "stampit", + "state-machine": "state-machine", + "Stats": "stats", + "store": "storejs", + "string": "string", + "string_score": "string_score", + "strophe": "strophe", + "stylus": "stylus", + "sugar": "sugar", + "superagent": "superagent", + "svg": "svgjs", + "svg-injector": "svg-injector", + "swfobject": "swfobject", + "swig": "swig", + "swipe": "swipe", + "swiper": "swiper", + "system.js": "systemjs", + "tether": "tether", + "three": "threejs", + "through": "through", + "through2": "through2", + "timeline": "timelinejs", + "tinycolor": "tinycolor", + "tmhDynamicLocale": "angular-dynamic-locale", + "toaster": "angularjs-toaster", + "toastr": "toastr", + "tracking": "tracking", + "trunk8": "trunk8", + "turf": "turf", + "tweenjs": "tweenjs", + "TweenMax": "gsap", + "twig": "twig", + "twix": "twix", + "typeahead.bundle": "typeahead", + "typescript": "typescript", + "ui": "winjs", + "ui-bootstrap-tpls": "angular-ui-bootstrap", + "ui-grid": "ui-grid", + "uikit": "uikit", + "underscore": "underscore", + "underscore.string": "underscore.string", + "update-notifier": "update-notifier", + "url": "jsurl", + "UUID": "uuid", + "validator": "validator", + "vega": "vega", + "vex": "vex-js", + "video": "videojs", + "vue": "vue", + "vue-router": "vue-router", + "webtorrent": "webtorrent", + "when": "when", + "winston": "winston", + "wrench-js": "wrench", + "ws": "ws", + "xlsx": "xlsx", + "xml2json": "x2js", + "xmlbuilder-js": "xmlbuilder", + "xregexp": "xregexp", + "yargs": "yargs", + "yosay": "yosay", + "yui": "yui", + "yui3": "yui", + "zepto": "zepto", + "ZeroClipboard": "zeroclipboard", + "ZSchema-browser": "z-schema" + } +} \ No newline at end of file diff --git a/node_modules/typescript/lib/typescript.d.ts b/node_modules/typescript/lib/typescript.d.ts new file mode 100644 index 0000000..cfaad2a --- /dev/null +++ b/node_modules/typescript/lib/typescript.d.ts @@ -0,0 +1,5567 @@ +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + +declare namespace ts { + const versionMajorMinor = "3.2"; + /** The version of the TypeScript compiler release */ + const version: string; +} +declare namespace ts { + /** + * Type of objects whose values are all of the same type. + * The `in` and `for-in` operators can *not* be safely used, + * since `Object.prototype` may be modified by outside code. + */ + interface MapLike { + [index: string]: T; + } + interface SortedReadonlyArray extends ReadonlyArray { + " __sortedArrayBrand": any; + } + interface SortedArray extends Array { + " __sortedArrayBrand": any; + } + /** ES6 Map interface, only read methods included. */ + interface ReadonlyMap { + get(key: string): T | undefined; + has(key: string): boolean; + forEach(action: (value: T, key: string) => void): void; + readonly size: number; + keys(): Iterator; + values(): Iterator; + entries(): Iterator<[string, T]>; + } + /** ES6 Map interface. */ + interface Map extends ReadonlyMap { + set(key: string, value: T): this; + delete(key: string): boolean; + clear(): void; + } + /** ES6 Iterator type. */ + interface Iterator { + next(): { + value: T; + done: false; + } | { + value: never; + done: true; + }; + } + /** Array that is only intended to be pushed to, never read. */ + interface Push { + push(...values: T[]): void; + } +} +declare namespace ts { + type Path = string & { + __pathBrand: any; + }; + interface TextRange { + pos: number; + end: number; + } + type JsDocSyntaxKind = SyntaxKind.EndOfFileToken | SyntaxKind.WhitespaceTrivia | SyntaxKind.AtToken | SyntaxKind.NewLineTrivia | SyntaxKind.AsteriskToken | SyntaxKind.OpenBraceToken | SyntaxKind.CloseBraceToken | SyntaxKind.LessThanToken | SyntaxKind.OpenBracketToken | SyntaxKind.CloseBracketToken | SyntaxKind.EqualsToken | SyntaxKind.CommaToken | SyntaxKind.DotToken | SyntaxKind.Identifier | SyntaxKind.NoSubstitutionTemplateLiteral | SyntaxKind.Unknown | KeywordSyntaxKind; + type KeywordSyntaxKind = SyntaxKind.AbstractKeyword | SyntaxKind.AnyKeyword | SyntaxKind.AsKeyword | SyntaxKind.BigIntKeyword | SyntaxKind.BooleanKeyword | SyntaxKind.BreakKeyword | SyntaxKind.CaseKeyword | SyntaxKind.CatchKeyword | SyntaxKind.ClassKeyword | SyntaxKind.ContinueKeyword | SyntaxKind.ConstKeyword | SyntaxKind.ConstructorKeyword | SyntaxKind.DebuggerKeyword | SyntaxKind.DeclareKeyword | SyntaxKind.DefaultKeyword | SyntaxKind.DeleteKeyword | SyntaxKind.DoKeyword | SyntaxKind.ElseKeyword | SyntaxKind.EnumKeyword | SyntaxKind.ExportKeyword | SyntaxKind.ExtendsKeyword | SyntaxKind.FalseKeyword | SyntaxKind.FinallyKeyword | SyntaxKind.ForKeyword | SyntaxKind.FromKeyword | SyntaxKind.FunctionKeyword | SyntaxKind.GetKeyword | SyntaxKind.IfKeyword | SyntaxKind.ImplementsKeyword | SyntaxKind.ImportKeyword | SyntaxKind.InKeyword | SyntaxKind.InferKeyword | SyntaxKind.InstanceOfKeyword | SyntaxKind.InterfaceKeyword | SyntaxKind.IsKeyword | SyntaxKind.KeyOfKeyword | SyntaxKind.LetKeyword | SyntaxKind.ModuleKeyword | SyntaxKind.NamespaceKeyword | SyntaxKind.NeverKeyword | SyntaxKind.NewKeyword | SyntaxKind.NullKeyword | SyntaxKind.NumberKeyword | SyntaxKind.ObjectKeyword | SyntaxKind.PackageKeyword | SyntaxKind.PrivateKeyword | SyntaxKind.ProtectedKeyword | SyntaxKind.PublicKeyword | SyntaxKind.ReadonlyKeyword | SyntaxKind.RequireKeyword | SyntaxKind.GlobalKeyword | SyntaxKind.ReturnKeyword | SyntaxKind.SetKeyword | SyntaxKind.StaticKeyword | SyntaxKind.StringKeyword | SyntaxKind.SuperKeyword | SyntaxKind.SwitchKeyword | SyntaxKind.SymbolKeyword | SyntaxKind.ThisKeyword | SyntaxKind.ThrowKeyword | SyntaxKind.TrueKeyword | SyntaxKind.TryKeyword | SyntaxKind.TypeKeyword | SyntaxKind.TypeOfKeyword | SyntaxKind.UndefinedKeyword | SyntaxKind.UniqueKeyword | SyntaxKind.UnknownKeyword | SyntaxKind.VarKeyword | SyntaxKind.VoidKeyword | SyntaxKind.WhileKeyword | SyntaxKind.WithKeyword | SyntaxKind.YieldKeyword | SyntaxKind.AsyncKeyword | SyntaxKind.AwaitKeyword | SyntaxKind.OfKeyword; + type JsxTokenSyntaxKind = SyntaxKind.LessThanSlashToken | SyntaxKind.EndOfFileToken | SyntaxKind.ConflictMarkerTrivia | SyntaxKind.JsxText | SyntaxKind.JsxTextAllWhiteSpaces | SyntaxKind.OpenBraceToken | SyntaxKind.LessThanToken; + enum SyntaxKind { + Unknown = 0, + EndOfFileToken = 1, + SingleLineCommentTrivia = 2, + MultiLineCommentTrivia = 3, + NewLineTrivia = 4, + WhitespaceTrivia = 5, + ShebangTrivia = 6, + ConflictMarkerTrivia = 7, + NumericLiteral = 8, + BigIntLiteral = 9, + StringLiteral = 10, + JsxText = 11, + JsxTextAllWhiteSpaces = 12, + RegularExpressionLiteral = 13, + NoSubstitutionTemplateLiteral = 14, + TemplateHead = 15, + TemplateMiddle = 16, + TemplateTail = 17, + OpenBraceToken = 18, + CloseBraceToken = 19, + OpenParenToken = 20, + CloseParenToken = 21, + OpenBracketToken = 22, + CloseBracketToken = 23, + DotToken = 24, + DotDotDotToken = 25, + SemicolonToken = 26, + CommaToken = 27, + LessThanToken = 28, + LessThanSlashToken = 29, + GreaterThanToken = 30, + LessThanEqualsToken = 31, + GreaterThanEqualsToken = 32, + EqualsEqualsToken = 33, + ExclamationEqualsToken = 34, + EqualsEqualsEqualsToken = 35, + ExclamationEqualsEqualsToken = 36, + EqualsGreaterThanToken = 37, + PlusToken = 38, + MinusToken = 39, + AsteriskToken = 40, + AsteriskAsteriskToken = 41, + SlashToken = 42, + PercentToken = 43, + PlusPlusToken = 44, + MinusMinusToken = 45, + LessThanLessThanToken = 46, + GreaterThanGreaterThanToken = 47, + GreaterThanGreaterThanGreaterThanToken = 48, + AmpersandToken = 49, + BarToken = 50, + CaretToken = 51, + ExclamationToken = 52, + TildeToken = 53, + AmpersandAmpersandToken = 54, + BarBarToken = 55, + QuestionToken = 56, + ColonToken = 57, + AtToken = 58, + EqualsToken = 59, + PlusEqualsToken = 60, + MinusEqualsToken = 61, + AsteriskEqualsToken = 62, + AsteriskAsteriskEqualsToken = 63, + SlashEqualsToken = 64, + PercentEqualsToken = 65, + LessThanLessThanEqualsToken = 66, + GreaterThanGreaterThanEqualsToken = 67, + GreaterThanGreaterThanGreaterThanEqualsToken = 68, + AmpersandEqualsToken = 69, + BarEqualsToken = 70, + CaretEqualsToken = 71, + Identifier = 72, + BreakKeyword = 73, + CaseKeyword = 74, + CatchKeyword = 75, + ClassKeyword = 76, + ConstKeyword = 77, + ContinueKeyword = 78, + DebuggerKeyword = 79, + DefaultKeyword = 80, + DeleteKeyword = 81, + DoKeyword = 82, + ElseKeyword = 83, + EnumKeyword = 84, + ExportKeyword = 85, + ExtendsKeyword = 86, + FalseKeyword = 87, + FinallyKeyword = 88, + ForKeyword = 89, + FunctionKeyword = 90, + IfKeyword = 91, + ImportKeyword = 92, + InKeyword = 93, + InstanceOfKeyword = 94, + NewKeyword = 95, + NullKeyword = 96, + ReturnKeyword = 97, + SuperKeyword = 98, + SwitchKeyword = 99, + ThisKeyword = 100, + ThrowKeyword = 101, + TrueKeyword = 102, + TryKeyword = 103, + TypeOfKeyword = 104, + VarKeyword = 105, + VoidKeyword = 106, + WhileKeyword = 107, + WithKeyword = 108, + ImplementsKeyword = 109, + InterfaceKeyword = 110, + LetKeyword = 111, + PackageKeyword = 112, + PrivateKeyword = 113, + ProtectedKeyword = 114, + PublicKeyword = 115, + StaticKeyword = 116, + YieldKeyword = 117, + AbstractKeyword = 118, + AsKeyword = 119, + AnyKeyword = 120, + AsyncKeyword = 121, + AwaitKeyword = 122, + BooleanKeyword = 123, + ConstructorKeyword = 124, + DeclareKeyword = 125, + GetKeyword = 126, + InferKeyword = 127, + IsKeyword = 128, + KeyOfKeyword = 129, + ModuleKeyword = 130, + NamespaceKeyword = 131, + NeverKeyword = 132, + ReadonlyKeyword = 133, + RequireKeyword = 134, + NumberKeyword = 135, + ObjectKeyword = 136, + SetKeyword = 137, + StringKeyword = 138, + SymbolKeyword = 139, + TypeKeyword = 140, + UndefinedKeyword = 141, + UniqueKeyword = 142, + UnknownKeyword = 143, + FromKeyword = 144, + GlobalKeyword = 145, + BigIntKeyword = 146, + OfKeyword = 147, + QualifiedName = 148, + ComputedPropertyName = 149, + TypeParameter = 150, + Parameter = 151, + Decorator = 152, + PropertySignature = 153, + PropertyDeclaration = 154, + MethodSignature = 155, + MethodDeclaration = 156, + Constructor = 157, + GetAccessor = 158, + SetAccessor = 159, + CallSignature = 160, + ConstructSignature = 161, + IndexSignature = 162, + TypePredicate = 163, + TypeReference = 164, + FunctionType = 165, + ConstructorType = 166, + TypeQuery = 167, + TypeLiteral = 168, + ArrayType = 169, + TupleType = 170, + OptionalType = 171, + RestType = 172, + UnionType = 173, + IntersectionType = 174, + ConditionalType = 175, + InferType = 176, + ParenthesizedType = 177, + ThisType = 178, + TypeOperator = 179, + IndexedAccessType = 180, + MappedType = 181, + LiteralType = 182, + ImportType = 183, + ObjectBindingPattern = 184, + ArrayBindingPattern = 185, + BindingElement = 186, + ArrayLiteralExpression = 187, + ObjectLiteralExpression = 188, + PropertyAccessExpression = 189, + ElementAccessExpression = 190, + CallExpression = 191, + NewExpression = 192, + TaggedTemplateExpression = 193, + TypeAssertionExpression = 194, + ParenthesizedExpression = 195, + FunctionExpression = 196, + ArrowFunction = 197, + DeleteExpression = 198, + TypeOfExpression = 199, + VoidExpression = 200, + AwaitExpression = 201, + PrefixUnaryExpression = 202, + PostfixUnaryExpression = 203, + BinaryExpression = 204, + ConditionalExpression = 205, + TemplateExpression = 206, + YieldExpression = 207, + SpreadElement = 208, + ClassExpression = 209, + OmittedExpression = 210, + ExpressionWithTypeArguments = 211, + AsExpression = 212, + NonNullExpression = 213, + MetaProperty = 214, + SyntheticExpression = 215, + TemplateSpan = 216, + SemicolonClassElement = 217, + Block = 218, + VariableStatement = 219, + EmptyStatement = 220, + ExpressionStatement = 221, + IfStatement = 222, + DoStatement = 223, + WhileStatement = 224, + ForStatement = 225, + ForInStatement = 226, + ForOfStatement = 227, + ContinueStatement = 228, + BreakStatement = 229, + ReturnStatement = 230, + WithStatement = 231, + SwitchStatement = 232, + LabeledStatement = 233, + ThrowStatement = 234, + TryStatement = 235, + DebuggerStatement = 236, + VariableDeclaration = 237, + VariableDeclarationList = 238, + FunctionDeclaration = 239, + ClassDeclaration = 240, + InterfaceDeclaration = 241, + TypeAliasDeclaration = 242, + EnumDeclaration = 243, + ModuleDeclaration = 244, + ModuleBlock = 245, + CaseBlock = 246, + NamespaceExportDeclaration = 247, + ImportEqualsDeclaration = 248, + ImportDeclaration = 249, + ImportClause = 250, + NamespaceImport = 251, + NamedImports = 252, + ImportSpecifier = 253, + ExportAssignment = 254, + ExportDeclaration = 255, + NamedExports = 256, + ExportSpecifier = 257, + MissingDeclaration = 258, + ExternalModuleReference = 259, + JsxElement = 260, + JsxSelfClosingElement = 261, + JsxOpeningElement = 262, + JsxClosingElement = 263, + JsxFragment = 264, + JsxOpeningFragment = 265, + JsxClosingFragment = 266, + JsxAttribute = 267, + JsxAttributes = 268, + JsxSpreadAttribute = 269, + JsxExpression = 270, + CaseClause = 271, + DefaultClause = 272, + HeritageClause = 273, + CatchClause = 274, + PropertyAssignment = 275, + ShorthandPropertyAssignment = 276, + SpreadAssignment = 277, + EnumMember = 278, + SourceFile = 279, + Bundle = 280, + UnparsedSource = 281, + InputFiles = 282, + JSDocTypeExpression = 283, + JSDocAllType = 284, + JSDocUnknownType = 285, + JSDocNullableType = 286, + JSDocNonNullableType = 287, + JSDocOptionalType = 288, + JSDocFunctionType = 289, + JSDocVariadicType = 290, + JSDocComment = 291, + JSDocTypeLiteral = 292, + JSDocSignature = 293, + JSDocTag = 294, + JSDocAugmentsTag = 295, + JSDocClassTag = 296, + JSDocCallbackTag = 297, + JSDocEnumTag = 298, + JSDocParameterTag = 299, + JSDocReturnTag = 300, + JSDocThisTag = 301, + JSDocTypeTag = 302, + JSDocTemplateTag = 303, + JSDocTypedefTag = 304, + JSDocPropertyTag = 305, + SyntaxList = 306, + NotEmittedStatement = 307, + PartiallyEmittedExpression = 308, + CommaListExpression = 309, + MergeDeclarationMarker = 310, + EndOfDeclarationMarker = 311, + Count = 312, + FirstAssignment = 59, + LastAssignment = 71, + FirstCompoundAssignment = 60, + LastCompoundAssignment = 71, + FirstReservedWord = 73, + LastReservedWord = 108, + FirstKeyword = 73, + LastKeyword = 147, + FirstFutureReservedWord = 109, + LastFutureReservedWord = 117, + FirstTypeNode = 163, + LastTypeNode = 183, + FirstPunctuation = 18, + LastPunctuation = 71, + FirstToken = 0, + LastToken = 147, + FirstTriviaToken = 2, + LastTriviaToken = 7, + FirstLiteralToken = 8, + LastLiteralToken = 14, + FirstTemplateToken = 14, + LastTemplateToken = 17, + FirstBinaryOperator = 28, + LastBinaryOperator = 71, + FirstNode = 148, + FirstJSDocNode = 283, + LastJSDocNode = 305, + FirstJSDocTagNode = 294, + LastJSDocTagNode = 305 + } + enum NodeFlags { + None = 0, + Let = 1, + Const = 2, + NestedNamespace = 4, + Synthesized = 8, + Namespace = 16, + ExportContext = 32, + ContainsThis = 64, + HasImplicitReturn = 128, + HasExplicitReturn = 256, + GlobalAugmentation = 512, + HasAsyncFunctions = 1024, + DisallowInContext = 2048, + YieldContext = 4096, + DecoratorContext = 8192, + AwaitContext = 16384, + ThisNodeHasError = 32768, + JavaScriptFile = 65536, + ThisNodeOrAnySubNodesHasError = 131072, + HasAggregatedChildData = 262144, + JSDoc = 2097152, + JsonFile = 16777216, + BlockScoped = 3, + ReachabilityCheckFlags = 384, + ReachabilityAndEmitFlags = 1408, + ContextFlags = 12679168, + TypeExcludesFlags = 20480 + } + enum ModifierFlags { + None = 0, + Export = 1, + Ambient = 2, + Public = 4, + Private = 8, + Protected = 16, + Static = 32, + Readonly = 64, + Abstract = 128, + Async = 256, + Default = 512, + Const = 2048, + HasComputedFlags = 536870912, + AccessibilityModifier = 28, + ParameterPropertyModifier = 92, + NonPublicAccessibilityModifier = 24, + TypeScriptModifier = 2270, + ExportDefault = 513, + All = 3071 + } + enum JsxFlags { + None = 0, + /** An element from a named property of the JSX.IntrinsicElements interface */ + IntrinsicNamedElement = 1, + /** An element inferred from the string index signature of the JSX.IntrinsicElements interface */ + IntrinsicIndexedElement = 2, + IntrinsicElement = 3 + } + interface Node extends TextRange { + kind: SyntaxKind; + flags: NodeFlags; + decorators?: NodeArray; + modifiers?: ModifiersArray; + parent: Node; + } + interface JSDocContainer { + } + type HasJSDoc = ParameterDeclaration | CallSignatureDeclaration | ConstructSignatureDeclaration | MethodSignature | PropertySignature | ArrowFunction | ParenthesizedExpression | SpreadAssignment | ShorthandPropertyAssignment | PropertyAssignment | FunctionExpression | LabeledStatement | ExpressionStatement | VariableStatement | FunctionDeclaration | ConstructorDeclaration | MethodDeclaration | PropertyDeclaration | AccessorDeclaration | ClassLikeDeclaration | InterfaceDeclaration | TypeAliasDeclaration | EnumMember | EnumDeclaration | ModuleDeclaration | ImportEqualsDeclaration | IndexSignatureDeclaration | FunctionTypeNode | ConstructorTypeNode | JSDocFunctionType | ExportDeclaration | EndOfFileToken; + type HasType = SignatureDeclaration | VariableDeclaration | ParameterDeclaration | PropertySignature | PropertyDeclaration | TypePredicateNode | ParenthesizedTypeNode | TypeOperatorNode | MappedTypeNode | AssertionExpression | TypeAliasDeclaration | JSDocTypeExpression | JSDocNonNullableType | JSDocNullableType | JSDocOptionalType | JSDocVariadicType; + type HasInitializer = HasExpressionInitializer | ForStatement | ForInStatement | ForOfStatement | JsxAttribute; + type HasExpressionInitializer = VariableDeclaration | ParameterDeclaration | BindingElement | PropertySignature | PropertyDeclaration | PropertyAssignment | EnumMember; + interface NodeArray extends ReadonlyArray, TextRange { + hasTrailingComma?: boolean; + } + interface Token extends Node { + kind: TKind; + } + type DotDotDotToken = Token; + type QuestionToken = Token; + type ExclamationToken = Token; + type ColonToken = Token; + type EqualsToken = Token; + type AsteriskToken = Token; + type EqualsGreaterThanToken = Token; + type EndOfFileToken = Token & JSDocContainer; + type ReadonlyToken = Token; + type AwaitKeywordToken = Token; + type PlusToken = Token; + type MinusToken = Token; + type Modifier = Token | Token | Token | Token | Token | Token | Token | Token | Token | Token | Token; + type ModifiersArray = NodeArray; + interface Identifier extends PrimaryExpression, Declaration { + kind: SyntaxKind.Identifier; + /** + * Prefer to use `id.unescapedText`. (Note: This is available only in services, not internally to the TypeScript compiler.) + * Text of identifier, but if the identifier begins with two underscores, this will begin with three. + */ + escapedText: __String; + originalKeywordKind?: SyntaxKind; + isInJSDocNamespace?: boolean; + } + interface TransientIdentifier extends Identifier { + resolvedSymbol: Symbol; + } + interface QualifiedName extends Node { + kind: SyntaxKind.QualifiedName; + left: EntityName; + right: Identifier; + } + type EntityName = Identifier | QualifiedName; + type PropertyName = Identifier | StringLiteral | NumericLiteral | ComputedPropertyName; + type DeclarationName = Identifier | StringLiteralLike | NumericLiteral | ComputedPropertyName | BindingPattern; + interface Declaration extends Node { + _declarationBrand: any; + } + interface NamedDeclaration extends Declaration { + name?: DeclarationName; + } + interface DeclarationStatement extends NamedDeclaration, Statement { + name?: Identifier | StringLiteral | NumericLiteral; + } + interface ComputedPropertyName extends Node { + parent: Declaration; + kind: SyntaxKind.ComputedPropertyName; + expression: Expression; + } + interface Decorator extends Node { + kind: SyntaxKind.Decorator; + parent: NamedDeclaration; + expression: LeftHandSideExpression; + } + interface TypeParameterDeclaration extends NamedDeclaration { + kind: SyntaxKind.TypeParameter; + parent: DeclarationWithTypeParameterChildren | InferTypeNode; + name: Identifier; + /** Note: Consider calling `getEffectiveConstraintOfTypeParameter` */ + constraint?: TypeNode; + default?: TypeNode; + expression?: Expression; + } + interface SignatureDeclarationBase extends NamedDeclaration, JSDocContainer { + kind: SignatureDeclaration["kind"]; + name?: PropertyName; + typeParameters?: NodeArray; + parameters: NodeArray; + type?: TypeNode; + } + type SignatureDeclaration = CallSignatureDeclaration | ConstructSignatureDeclaration | MethodSignature | IndexSignatureDeclaration | FunctionTypeNode | ConstructorTypeNode | JSDocFunctionType | FunctionDeclaration | MethodDeclaration | ConstructorDeclaration | AccessorDeclaration | FunctionExpression | ArrowFunction; + interface CallSignatureDeclaration extends SignatureDeclarationBase, TypeElement { + kind: SyntaxKind.CallSignature; + } + interface ConstructSignatureDeclaration extends SignatureDeclarationBase, TypeElement { + kind: SyntaxKind.ConstructSignature; + } + type BindingName = Identifier | BindingPattern; + interface VariableDeclaration extends NamedDeclaration { + kind: SyntaxKind.VariableDeclaration; + parent: VariableDeclarationList | CatchClause; + name: BindingName; + exclamationToken?: ExclamationToken; + type?: TypeNode; + initializer?: Expression; + } + interface VariableDeclarationList extends Node { + kind: SyntaxKind.VariableDeclarationList; + parent: VariableStatement | ForStatement | ForOfStatement | ForInStatement; + declarations: NodeArray; + } + interface ParameterDeclaration extends NamedDeclaration, JSDocContainer { + kind: SyntaxKind.Parameter; + parent: SignatureDeclaration; + dotDotDotToken?: DotDotDotToken; + name: BindingName; + questionToken?: QuestionToken; + type?: TypeNode; + initializer?: Expression; + } + interface BindingElement extends NamedDeclaration { + kind: SyntaxKind.BindingElement; + parent: BindingPattern; + propertyName?: PropertyName; + dotDotDotToken?: DotDotDotToken; + name: BindingName; + initializer?: Expression; + } + interface PropertySignature extends TypeElement, JSDocContainer { + kind: SyntaxKind.PropertySignature; + name: PropertyName; + questionToken?: QuestionToken; + type?: TypeNode; + initializer?: Expression; + } + interface PropertyDeclaration extends ClassElement, JSDocContainer { + kind: SyntaxKind.PropertyDeclaration; + parent: ClassLikeDeclaration; + name: PropertyName; + questionToken?: QuestionToken; + exclamationToken?: ExclamationToken; + type?: TypeNode; + initializer?: Expression; + } + interface ObjectLiteralElement extends NamedDeclaration { + _objectLiteralBrandBrand: any; + name?: PropertyName; + } + /** Unlike ObjectLiteralElement, excludes JSXAttribute and JSXSpreadAttribute. */ + type ObjectLiteralElementLike = PropertyAssignment | ShorthandPropertyAssignment | SpreadAssignment | MethodDeclaration | AccessorDeclaration; + interface PropertyAssignment extends ObjectLiteralElement, JSDocContainer { + parent: ObjectLiteralExpression; + kind: SyntaxKind.PropertyAssignment; + name: PropertyName; + questionToken?: QuestionToken; + initializer: Expression; + } + interface ShorthandPropertyAssignment extends ObjectLiteralElement, JSDocContainer { + parent: ObjectLiteralExpression; + kind: SyntaxKind.ShorthandPropertyAssignment; + name: Identifier; + questionToken?: QuestionToken; + exclamationToken?: ExclamationToken; + equalsToken?: Token; + objectAssignmentInitializer?: Expression; + } + interface SpreadAssignment extends ObjectLiteralElement, JSDocContainer { + parent: ObjectLiteralExpression; + kind: SyntaxKind.SpreadAssignment; + expression: Expression; + } + type VariableLikeDeclaration = VariableDeclaration | ParameterDeclaration | BindingElement | PropertyDeclaration | PropertyAssignment | PropertySignature | JsxAttribute | ShorthandPropertyAssignment | EnumMember | JSDocPropertyTag | JSDocParameterTag; + interface PropertyLikeDeclaration extends NamedDeclaration { + name: PropertyName; + } + interface ObjectBindingPattern extends Node { + kind: SyntaxKind.ObjectBindingPattern; + parent: VariableDeclaration | ParameterDeclaration | BindingElement; + elements: NodeArray; + } + interface ArrayBindingPattern extends Node { + kind: SyntaxKind.ArrayBindingPattern; + parent: VariableDeclaration | ParameterDeclaration | BindingElement; + elements: NodeArray; + } + type BindingPattern = ObjectBindingPattern | ArrayBindingPattern; + type ArrayBindingElement = BindingElement | OmittedExpression; + /** + * Several node kinds share function-like features such as a signature, + * a name, and a body. These nodes should extend FunctionLikeDeclarationBase. + * Examples: + * - FunctionDeclaration + * - MethodDeclaration + * - AccessorDeclaration + */ + interface FunctionLikeDeclarationBase extends SignatureDeclarationBase { + _functionLikeDeclarationBrand: any; + asteriskToken?: AsteriskToken; + questionToken?: QuestionToken; + exclamationToken?: ExclamationToken; + body?: Block | Expression; + } + type FunctionLikeDeclaration = FunctionDeclaration | MethodDeclaration | GetAccessorDeclaration | SetAccessorDeclaration | ConstructorDeclaration | FunctionExpression | ArrowFunction; + /** @deprecated Use SignatureDeclaration */ + type FunctionLike = SignatureDeclaration; + interface FunctionDeclaration extends FunctionLikeDeclarationBase, DeclarationStatement { + kind: SyntaxKind.FunctionDeclaration; + name?: Identifier; + body?: FunctionBody; + } + interface MethodSignature extends SignatureDeclarationBase, TypeElement { + kind: SyntaxKind.MethodSignature; + parent: ObjectTypeDeclaration; + name: PropertyName; + } + interface MethodDeclaration extends FunctionLikeDeclarationBase, ClassElement, ObjectLiteralElement, JSDocContainer { + kind: SyntaxKind.MethodDeclaration; + parent: ClassLikeDeclaration | ObjectLiteralExpression; + name: PropertyName; + body?: FunctionBody; + } + interface ConstructorDeclaration extends FunctionLikeDeclarationBase, ClassElement, JSDocContainer { + kind: SyntaxKind.Constructor; + parent: ClassLikeDeclaration; + body?: FunctionBody; + } + /** For when we encounter a semicolon in a class declaration. ES6 allows these as class elements. */ + interface SemicolonClassElement extends ClassElement { + kind: SyntaxKind.SemicolonClassElement; + parent: ClassLikeDeclaration; + } + interface GetAccessorDeclaration extends FunctionLikeDeclarationBase, ClassElement, ObjectLiteralElement, JSDocContainer { + kind: SyntaxKind.GetAccessor; + parent: ClassLikeDeclaration | ObjectLiteralExpression; + name: PropertyName; + body?: FunctionBody; + } + interface SetAccessorDeclaration extends FunctionLikeDeclarationBase, ClassElement, ObjectLiteralElement, JSDocContainer { + kind: SyntaxKind.SetAccessor; + parent: ClassLikeDeclaration | ObjectLiteralExpression; + name: PropertyName; + body?: FunctionBody; + } + type AccessorDeclaration = GetAccessorDeclaration | SetAccessorDeclaration; + interface IndexSignatureDeclaration extends SignatureDeclarationBase, ClassElement, TypeElement { + kind: SyntaxKind.IndexSignature; + parent: ObjectTypeDeclaration; + } + interface TypeNode extends Node { + _typeNodeBrand: any; + } + interface KeywordTypeNode extends TypeNode { + kind: SyntaxKind.AnyKeyword | SyntaxKind.UnknownKeyword | SyntaxKind.NumberKeyword | SyntaxKind.BigIntKeyword | SyntaxKind.ObjectKeyword | SyntaxKind.BooleanKeyword | SyntaxKind.StringKeyword | SyntaxKind.SymbolKeyword | SyntaxKind.ThisKeyword | SyntaxKind.VoidKeyword | SyntaxKind.UndefinedKeyword | SyntaxKind.NullKeyword | SyntaxKind.NeverKeyword; + } + interface ImportTypeNode extends NodeWithTypeArguments { + kind: SyntaxKind.ImportType; + isTypeOf?: boolean; + argument: TypeNode; + qualifier?: EntityName; + } + interface ThisTypeNode extends TypeNode { + kind: SyntaxKind.ThisType; + } + type FunctionOrConstructorTypeNode = FunctionTypeNode | ConstructorTypeNode; + interface FunctionOrConstructorTypeNodeBase extends TypeNode, SignatureDeclarationBase { + kind: SyntaxKind.FunctionType | SyntaxKind.ConstructorType; + type: TypeNode; + } + interface FunctionTypeNode extends FunctionOrConstructorTypeNodeBase { + kind: SyntaxKind.FunctionType; + } + interface ConstructorTypeNode extends FunctionOrConstructorTypeNodeBase { + kind: SyntaxKind.ConstructorType; + } + interface NodeWithTypeArguments extends TypeNode { + typeArguments?: NodeArray; + } + type TypeReferenceType = TypeReferenceNode | ExpressionWithTypeArguments; + interface TypeReferenceNode extends NodeWithTypeArguments { + kind: SyntaxKind.TypeReference; + typeName: EntityName; + } + interface TypePredicateNode extends TypeNode { + kind: SyntaxKind.TypePredicate; + parent: SignatureDeclaration | JSDocTypeExpression; + parameterName: Identifier | ThisTypeNode; + type: TypeNode; + } + interface TypeQueryNode extends TypeNode { + kind: SyntaxKind.TypeQuery; + exprName: EntityName; + } + interface TypeLiteralNode extends TypeNode, Declaration { + kind: SyntaxKind.TypeLiteral; + members: NodeArray; + } + interface ArrayTypeNode extends TypeNode { + kind: SyntaxKind.ArrayType; + elementType: TypeNode; + } + interface TupleTypeNode extends TypeNode { + kind: SyntaxKind.TupleType; + elementTypes: NodeArray; + } + interface OptionalTypeNode extends TypeNode { + kind: SyntaxKind.OptionalType; + type: TypeNode; + } + interface RestTypeNode extends TypeNode { + kind: SyntaxKind.RestType; + type: TypeNode; + } + type UnionOrIntersectionTypeNode = UnionTypeNode | IntersectionTypeNode; + interface UnionTypeNode extends TypeNode { + kind: SyntaxKind.UnionType; + types: NodeArray; + } + interface IntersectionTypeNode extends TypeNode { + kind: SyntaxKind.IntersectionType; + types: NodeArray; + } + interface ConditionalTypeNode extends TypeNode { + kind: SyntaxKind.ConditionalType; + checkType: TypeNode; + extendsType: TypeNode; + trueType: TypeNode; + falseType: TypeNode; + } + interface InferTypeNode extends TypeNode { + kind: SyntaxKind.InferType; + typeParameter: TypeParameterDeclaration; + } + interface ParenthesizedTypeNode extends TypeNode { + kind: SyntaxKind.ParenthesizedType; + type: TypeNode; + } + interface TypeOperatorNode extends TypeNode { + kind: SyntaxKind.TypeOperator; + operator: SyntaxKind.KeyOfKeyword | SyntaxKind.UniqueKeyword; + type: TypeNode; + } + interface IndexedAccessTypeNode extends TypeNode { + kind: SyntaxKind.IndexedAccessType; + objectType: TypeNode; + indexType: TypeNode; + } + interface MappedTypeNode extends TypeNode, Declaration { + kind: SyntaxKind.MappedType; + readonlyToken?: ReadonlyToken | PlusToken | MinusToken; + typeParameter: TypeParameterDeclaration; + questionToken?: QuestionToken | PlusToken | MinusToken; + type?: TypeNode; + } + interface LiteralTypeNode extends TypeNode { + kind: SyntaxKind.LiteralType; + literal: BooleanLiteral | LiteralExpression | PrefixUnaryExpression; + } + interface StringLiteral extends LiteralExpression { + kind: SyntaxKind.StringLiteral; + } + type StringLiteralLike = StringLiteral | NoSubstitutionTemplateLiteral; + interface Expression extends Node { + _expressionBrand: any; + } + interface OmittedExpression extends Expression { + kind: SyntaxKind.OmittedExpression; + } + interface PartiallyEmittedExpression extends LeftHandSideExpression { + kind: SyntaxKind.PartiallyEmittedExpression; + expression: Expression; + } + interface UnaryExpression extends Expression { + _unaryExpressionBrand: any; + } + /** Deprecated, please use UpdateExpression */ + type IncrementExpression = UpdateExpression; + interface UpdateExpression extends UnaryExpression { + _updateExpressionBrand: any; + } + type PrefixUnaryOperator = SyntaxKind.PlusPlusToken | SyntaxKind.MinusMinusToken | SyntaxKind.PlusToken | SyntaxKind.MinusToken | SyntaxKind.TildeToken | SyntaxKind.ExclamationToken; + interface PrefixUnaryExpression extends UpdateExpression { + kind: SyntaxKind.PrefixUnaryExpression; + operator: PrefixUnaryOperator; + operand: UnaryExpression; + } + type PostfixUnaryOperator = SyntaxKind.PlusPlusToken | SyntaxKind.MinusMinusToken; + interface PostfixUnaryExpression extends UpdateExpression { + kind: SyntaxKind.PostfixUnaryExpression; + operand: LeftHandSideExpression; + operator: PostfixUnaryOperator; + } + interface LeftHandSideExpression extends UpdateExpression { + _leftHandSideExpressionBrand: any; + } + interface MemberExpression extends LeftHandSideExpression { + _memberExpressionBrand: any; + } + interface PrimaryExpression extends MemberExpression { + _primaryExpressionBrand: any; + } + interface NullLiteral extends PrimaryExpression, TypeNode { + kind: SyntaxKind.NullKeyword; + } + interface BooleanLiteral extends PrimaryExpression, TypeNode { + kind: SyntaxKind.TrueKeyword | SyntaxKind.FalseKeyword; + } + interface ThisExpression extends PrimaryExpression, KeywordTypeNode { + kind: SyntaxKind.ThisKeyword; + } + interface SuperExpression extends PrimaryExpression { + kind: SyntaxKind.SuperKeyword; + } + interface ImportExpression extends PrimaryExpression { + kind: SyntaxKind.ImportKeyword; + } + interface DeleteExpression extends UnaryExpression { + kind: SyntaxKind.DeleteExpression; + expression: UnaryExpression; + } + interface TypeOfExpression extends UnaryExpression { + kind: SyntaxKind.TypeOfExpression; + expression: UnaryExpression; + } + interface VoidExpression extends UnaryExpression { + kind: SyntaxKind.VoidExpression; + expression: UnaryExpression; + } + interface AwaitExpression extends UnaryExpression { + kind: SyntaxKind.AwaitExpression; + expression: UnaryExpression; + } + interface YieldExpression extends Expression { + kind: SyntaxKind.YieldExpression; + asteriskToken?: AsteriskToken; + expression?: Expression; + } + interface SyntheticExpression extends Expression { + kind: SyntaxKind.SyntheticExpression; + isSpread: boolean; + type: Type; + } + type ExponentiationOperator = SyntaxKind.AsteriskAsteriskToken; + type MultiplicativeOperator = SyntaxKind.AsteriskToken | SyntaxKind.SlashToken | SyntaxKind.PercentToken; + type MultiplicativeOperatorOrHigher = ExponentiationOperator | MultiplicativeOperator; + type AdditiveOperator = SyntaxKind.PlusToken | SyntaxKind.MinusToken; + type AdditiveOperatorOrHigher = MultiplicativeOperatorOrHigher | AdditiveOperator; + type ShiftOperator = SyntaxKind.LessThanLessThanToken | SyntaxKind.GreaterThanGreaterThanToken | SyntaxKind.GreaterThanGreaterThanGreaterThanToken; + type ShiftOperatorOrHigher = AdditiveOperatorOrHigher | ShiftOperator; + type RelationalOperator = SyntaxKind.LessThanToken | SyntaxKind.LessThanEqualsToken | SyntaxKind.GreaterThanToken | SyntaxKind.GreaterThanEqualsToken | SyntaxKind.InstanceOfKeyword | SyntaxKind.InKeyword; + type RelationalOperatorOrHigher = ShiftOperatorOrHigher | RelationalOperator; + type EqualityOperator = SyntaxKind.EqualsEqualsToken | SyntaxKind.EqualsEqualsEqualsToken | SyntaxKind.ExclamationEqualsEqualsToken | SyntaxKind.ExclamationEqualsToken; + type EqualityOperatorOrHigher = RelationalOperatorOrHigher | EqualityOperator; + type BitwiseOperator = SyntaxKind.AmpersandToken | SyntaxKind.BarToken | SyntaxKind.CaretToken; + type BitwiseOperatorOrHigher = EqualityOperatorOrHigher | BitwiseOperator; + type LogicalOperator = SyntaxKind.AmpersandAmpersandToken | SyntaxKind.BarBarToken; + type LogicalOperatorOrHigher = BitwiseOperatorOrHigher | LogicalOperator; + type CompoundAssignmentOperator = SyntaxKind.PlusEqualsToken | SyntaxKind.MinusEqualsToken | SyntaxKind.AsteriskAsteriskEqualsToken | SyntaxKind.AsteriskEqualsToken | SyntaxKind.SlashEqualsToken | SyntaxKind.PercentEqualsToken | SyntaxKind.AmpersandEqualsToken | SyntaxKind.BarEqualsToken | SyntaxKind.CaretEqualsToken | SyntaxKind.LessThanLessThanEqualsToken | SyntaxKind.GreaterThanGreaterThanGreaterThanEqualsToken | SyntaxKind.GreaterThanGreaterThanEqualsToken; + type AssignmentOperator = SyntaxKind.EqualsToken | CompoundAssignmentOperator; + type AssignmentOperatorOrHigher = LogicalOperatorOrHigher | AssignmentOperator; + type BinaryOperator = AssignmentOperatorOrHigher | SyntaxKind.CommaToken; + type BinaryOperatorToken = Token; + interface BinaryExpression extends Expression, Declaration { + kind: SyntaxKind.BinaryExpression; + left: Expression; + operatorToken: BinaryOperatorToken; + right: Expression; + } + type AssignmentOperatorToken = Token; + interface AssignmentExpression extends BinaryExpression { + left: LeftHandSideExpression; + operatorToken: TOperator; + } + interface ObjectDestructuringAssignment extends AssignmentExpression { + left: ObjectLiteralExpression; + } + interface ArrayDestructuringAssignment extends AssignmentExpression { + left: ArrayLiteralExpression; + } + type DestructuringAssignment = ObjectDestructuringAssignment | ArrayDestructuringAssignment; + type BindingOrAssignmentElement = VariableDeclaration | ParameterDeclaration | BindingElement | PropertyAssignment | ShorthandPropertyAssignment | SpreadAssignment | OmittedExpression | SpreadElement | ArrayLiteralExpression | ObjectLiteralExpression | AssignmentExpression | Identifier | PropertyAccessExpression | ElementAccessExpression; + type BindingOrAssignmentElementRestIndicator = DotDotDotToken | SpreadElement | SpreadAssignment; + type BindingOrAssignmentElementTarget = BindingOrAssignmentPattern | Identifier | PropertyAccessExpression | ElementAccessExpression | OmittedExpression; + type ObjectBindingOrAssignmentPattern = ObjectBindingPattern | ObjectLiteralExpression; + type ArrayBindingOrAssignmentPattern = ArrayBindingPattern | ArrayLiteralExpression; + type AssignmentPattern = ObjectLiteralExpression | ArrayLiteralExpression; + type BindingOrAssignmentPattern = ObjectBindingOrAssignmentPattern | ArrayBindingOrAssignmentPattern; + interface ConditionalExpression extends Expression { + kind: SyntaxKind.ConditionalExpression; + condition: Expression; + questionToken: QuestionToken; + whenTrue: Expression; + colonToken: ColonToken; + whenFalse: Expression; + } + type FunctionBody = Block; + type ConciseBody = FunctionBody | Expression; + interface FunctionExpression extends PrimaryExpression, FunctionLikeDeclarationBase, JSDocContainer { + kind: SyntaxKind.FunctionExpression; + name?: Identifier; + body: FunctionBody; + } + interface ArrowFunction extends Expression, FunctionLikeDeclarationBase, JSDocContainer { + kind: SyntaxKind.ArrowFunction; + equalsGreaterThanToken: EqualsGreaterThanToken; + body: ConciseBody; + name: never; + } + interface LiteralLikeNode extends Node { + text: string; + isUnterminated?: boolean; + hasExtendedUnicodeEscape?: boolean; + } + interface LiteralExpression extends LiteralLikeNode, PrimaryExpression { + _literalExpressionBrand: any; + } + interface RegularExpressionLiteral extends LiteralExpression { + kind: SyntaxKind.RegularExpressionLiteral; + } + interface NoSubstitutionTemplateLiteral extends LiteralExpression { + kind: SyntaxKind.NoSubstitutionTemplateLiteral; + } + interface NumericLiteral extends LiteralExpression { + kind: SyntaxKind.NumericLiteral; + } + interface BigIntLiteral extends LiteralExpression { + kind: SyntaxKind.BigIntLiteral; + } + interface TemplateHead extends LiteralLikeNode { + kind: SyntaxKind.TemplateHead; + parent: TemplateExpression; + } + interface TemplateMiddle extends LiteralLikeNode { + kind: SyntaxKind.TemplateMiddle; + parent: TemplateSpan; + } + interface TemplateTail extends LiteralLikeNode { + kind: SyntaxKind.TemplateTail; + parent: TemplateSpan; + } + type TemplateLiteral = TemplateExpression | NoSubstitutionTemplateLiteral; + interface TemplateExpression extends PrimaryExpression { + kind: SyntaxKind.TemplateExpression; + head: TemplateHead; + templateSpans: NodeArray; + } + interface TemplateSpan extends Node { + kind: SyntaxKind.TemplateSpan; + parent: TemplateExpression; + expression: Expression; + literal: TemplateMiddle | TemplateTail; + } + interface ParenthesizedExpression extends PrimaryExpression, JSDocContainer { + kind: SyntaxKind.ParenthesizedExpression; + expression: Expression; + } + interface ArrayLiteralExpression extends PrimaryExpression { + kind: SyntaxKind.ArrayLiteralExpression; + elements: NodeArray; + } + interface SpreadElement extends Expression { + kind: SyntaxKind.SpreadElement; + parent: ArrayLiteralExpression | CallExpression | NewExpression; + expression: Expression; + } + /** + * This interface is a base interface for ObjectLiteralExpression and JSXAttributes to extend from. JSXAttributes is similar to + * ObjectLiteralExpression in that it contains array of properties; however, JSXAttributes' properties can only be + * JSXAttribute or JSXSpreadAttribute. ObjectLiteralExpression, on the other hand, can only have properties of type + * ObjectLiteralElement (e.g. PropertyAssignment, ShorthandPropertyAssignment etc.) + */ + interface ObjectLiteralExpressionBase extends PrimaryExpression, Declaration { + properties: NodeArray; + } + interface ObjectLiteralExpression extends ObjectLiteralExpressionBase { + kind: SyntaxKind.ObjectLiteralExpression; + } + type EntityNameExpression = Identifier | PropertyAccessEntityNameExpression; + type EntityNameOrEntityNameExpression = EntityName | EntityNameExpression; + interface PropertyAccessExpression extends MemberExpression, NamedDeclaration { + kind: SyntaxKind.PropertyAccessExpression; + expression: LeftHandSideExpression; + name: Identifier; + } + interface SuperPropertyAccessExpression extends PropertyAccessExpression { + expression: SuperExpression; + } + /** Brand for a PropertyAccessExpression which, like a QualifiedName, consists of a sequence of identifiers separated by dots. */ + interface PropertyAccessEntityNameExpression extends PropertyAccessExpression { + _propertyAccessExpressionLikeQualifiedNameBrand?: any; + expression: EntityNameExpression; + } + interface ElementAccessExpression extends MemberExpression { + kind: SyntaxKind.ElementAccessExpression; + expression: LeftHandSideExpression; + argumentExpression: Expression; + } + interface SuperElementAccessExpression extends ElementAccessExpression { + expression: SuperExpression; + } + type SuperProperty = SuperPropertyAccessExpression | SuperElementAccessExpression; + interface CallExpression extends LeftHandSideExpression, Declaration { + kind: SyntaxKind.CallExpression; + expression: LeftHandSideExpression; + typeArguments?: NodeArray; + arguments: NodeArray; + } + interface SuperCall extends CallExpression { + expression: SuperExpression; + } + interface ImportCall extends CallExpression { + expression: ImportExpression; + } + interface ExpressionWithTypeArguments extends NodeWithTypeArguments { + kind: SyntaxKind.ExpressionWithTypeArguments; + parent: HeritageClause | JSDocAugmentsTag; + expression: LeftHandSideExpression; + } + interface NewExpression extends PrimaryExpression, Declaration { + kind: SyntaxKind.NewExpression; + expression: LeftHandSideExpression; + typeArguments?: NodeArray; + arguments?: NodeArray; + } + interface TaggedTemplateExpression extends MemberExpression { + kind: SyntaxKind.TaggedTemplateExpression; + tag: LeftHandSideExpression; + typeArguments?: NodeArray; + template: TemplateLiteral; + } + type CallLikeExpression = CallExpression | NewExpression | TaggedTemplateExpression | Decorator | JsxOpeningLikeElement; + interface AsExpression extends Expression { + kind: SyntaxKind.AsExpression; + expression: Expression; + type: TypeNode; + } + interface TypeAssertion extends UnaryExpression { + kind: SyntaxKind.TypeAssertionExpression; + type: TypeNode; + expression: UnaryExpression; + } + type AssertionExpression = TypeAssertion | AsExpression; + interface NonNullExpression extends LeftHandSideExpression { + kind: SyntaxKind.NonNullExpression; + expression: Expression; + } + interface MetaProperty extends PrimaryExpression { + kind: SyntaxKind.MetaProperty; + keywordToken: SyntaxKind.NewKeyword | SyntaxKind.ImportKeyword; + name: Identifier; + } + interface JsxElement extends PrimaryExpression { + kind: SyntaxKind.JsxElement; + openingElement: JsxOpeningElement; + children: NodeArray; + closingElement: JsxClosingElement; + } + type JsxOpeningLikeElement = JsxSelfClosingElement | JsxOpeningElement; + type JsxAttributeLike = JsxAttribute | JsxSpreadAttribute; + type JsxTagNameExpression = Identifier | ThisExpression | JsxTagNamePropertyAccess; + interface JsxTagNamePropertyAccess extends PropertyAccessExpression { + expression: JsxTagNameExpression; + } + interface JsxAttributes extends ObjectLiteralExpressionBase { + parent: JsxOpeningLikeElement; + } + interface JsxOpeningElement extends Expression { + kind: SyntaxKind.JsxOpeningElement; + parent: JsxElement; + tagName: JsxTagNameExpression; + typeArguments?: NodeArray; + attributes: JsxAttributes; + } + interface JsxSelfClosingElement extends PrimaryExpression { + kind: SyntaxKind.JsxSelfClosingElement; + tagName: JsxTagNameExpression; + typeArguments?: NodeArray; + attributes: JsxAttributes; + } + interface JsxFragment extends PrimaryExpression { + kind: SyntaxKind.JsxFragment; + openingFragment: JsxOpeningFragment; + children: NodeArray; + closingFragment: JsxClosingFragment; + } + interface JsxOpeningFragment extends Expression { + kind: SyntaxKind.JsxOpeningFragment; + parent: JsxFragment; + } + interface JsxClosingFragment extends Expression { + kind: SyntaxKind.JsxClosingFragment; + parent: JsxFragment; + } + interface JsxAttribute extends ObjectLiteralElement { + kind: SyntaxKind.JsxAttribute; + parent: JsxAttributes; + name: Identifier; + initializer?: StringLiteral | JsxExpression; + } + interface JsxSpreadAttribute extends ObjectLiteralElement { + kind: SyntaxKind.JsxSpreadAttribute; + parent: JsxAttributes; + expression: Expression; + } + interface JsxClosingElement extends Node { + kind: SyntaxKind.JsxClosingElement; + parent: JsxElement; + tagName: JsxTagNameExpression; + } + interface JsxExpression extends Expression { + kind: SyntaxKind.JsxExpression; + parent: JsxElement | JsxAttributeLike; + dotDotDotToken?: Token; + expression?: Expression; + } + interface JsxText extends Node { + kind: SyntaxKind.JsxText; + containsOnlyWhiteSpaces: boolean; + parent: JsxElement; + } + type JsxChild = JsxText | JsxExpression | JsxElement | JsxSelfClosingElement | JsxFragment; + interface Statement extends Node { + _statementBrand: any; + } + interface NotEmittedStatement extends Statement { + kind: SyntaxKind.NotEmittedStatement; + } + /** + * A list of comma-separated expressions. This node is only created by transformations. + */ + interface CommaListExpression extends Expression { + kind: SyntaxKind.CommaListExpression; + elements: NodeArray; + } + interface EmptyStatement extends Statement { + kind: SyntaxKind.EmptyStatement; + } + interface DebuggerStatement extends Statement { + kind: SyntaxKind.DebuggerStatement; + } + interface MissingDeclaration extends DeclarationStatement { + kind: SyntaxKind.MissingDeclaration; + name?: Identifier; + } + type BlockLike = SourceFile | Block | ModuleBlock | CaseOrDefaultClause; + interface Block extends Statement { + kind: SyntaxKind.Block; + statements: NodeArray; + } + interface VariableStatement extends Statement, JSDocContainer { + kind: SyntaxKind.VariableStatement; + declarationList: VariableDeclarationList; + } + interface ExpressionStatement extends Statement, JSDocContainer { + kind: SyntaxKind.ExpressionStatement; + expression: Expression; + } + interface IfStatement extends Statement { + kind: SyntaxKind.IfStatement; + expression: Expression; + thenStatement: Statement; + elseStatement?: Statement; + } + interface IterationStatement extends Statement { + statement: Statement; + } + interface DoStatement extends IterationStatement { + kind: SyntaxKind.DoStatement; + expression: Expression; + } + interface WhileStatement extends IterationStatement { + kind: SyntaxKind.WhileStatement; + expression: Expression; + } + type ForInitializer = VariableDeclarationList | Expression; + interface ForStatement extends IterationStatement { + kind: SyntaxKind.ForStatement; + initializer?: ForInitializer; + condition?: Expression; + incrementor?: Expression; + } + type ForInOrOfStatement = ForInStatement | ForOfStatement; + interface ForInStatement extends IterationStatement { + kind: SyntaxKind.ForInStatement; + initializer: ForInitializer; + expression: Expression; + } + interface ForOfStatement extends IterationStatement { + kind: SyntaxKind.ForOfStatement; + awaitModifier?: AwaitKeywordToken; + initializer: ForInitializer; + expression: Expression; + } + interface BreakStatement extends Statement { + kind: SyntaxKind.BreakStatement; + label?: Identifier; + } + interface ContinueStatement extends Statement { + kind: SyntaxKind.ContinueStatement; + label?: Identifier; + } + type BreakOrContinueStatement = BreakStatement | ContinueStatement; + interface ReturnStatement extends Statement { + kind: SyntaxKind.ReturnStatement; + expression?: Expression; + } + interface WithStatement extends Statement { + kind: SyntaxKind.WithStatement; + expression: Expression; + statement: Statement; + } + interface SwitchStatement extends Statement { + kind: SyntaxKind.SwitchStatement; + expression: Expression; + caseBlock: CaseBlock; + possiblyExhaustive?: boolean; + } + interface CaseBlock extends Node { + kind: SyntaxKind.CaseBlock; + parent: SwitchStatement; + clauses: NodeArray; + } + interface CaseClause extends Node { + kind: SyntaxKind.CaseClause; + parent: CaseBlock; + expression: Expression; + statements: NodeArray; + } + interface DefaultClause extends Node { + kind: SyntaxKind.DefaultClause; + parent: CaseBlock; + statements: NodeArray; + } + type CaseOrDefaultClause = CaseClause | DefaultClause; + interface LabeledStatement extends Statement, JSDocContainer { + kind: SyntaxKind.LabeledStatement; + label: Identifier; + statement: Statement; + } + interface ThrowStatement extends Statement { + kind: SyntaxKind.ThrowStatement; + expression?: Expression; + } + interface TryStatement extends Statement { + kind: SyntaxKind.TryStatement; + tryBlock: Block; + catchClause?: CatchClause; + finallyBlock?: Block; + } + interface CatchClause extends Node { + kind: SyntaxKind.CatchClause; + parent: TryStatement; + variableDeclaration?: VariableDeclaration; + block: Block; + } + type ObjectTypeDeclaration = ClassLikeDeclaration | InterfaceDeclaration | TypeLiteralNode; + type DeclarationWithTypeParameters = DeclarationWithTypeParameterChildren | JSDocTypedefTag | JSDocCallbackTag | JSDocSignature; + type DeclarationWithTypeParameterChildren = SignatureDeclaration | ClassLikeDeclaration | InterfaceDeclaration | TypeAliasDeclaration | JSDocTemplateTag; + interface ClassLikeDeclarationBase extends NamedDeclaration, JSDocContainer { + kind: SyntaxKind.ClassDeclaration | SyntaxKind.ClassExpression; + name?: Identifier; + typeParameters?: NodeArray; + heritageClauses?: NodeArray; + members: NodeArray; + } + interface ClassDeclaration extends ClassLikeDeclarationBase, DeclarationStatement { + kind: SyntaxKind.ClassDeclaration; + /** May be undefined in `export default class { ... }`. */ + name?: Identifier; + } + interface ClassExpression extends ClassLikeDeclarationBase, PrimaryExpression { + kind: SyntaxKind.ClassExpression; + } + type ClassLikeDeclaration = ClassDeclaration | ClassExpression; + interface ClassElement extends NamedDeclaration { + _classElementBrand: any; + name?: PropertyName; + } + interface TypeElement extends NamedDeclaration { + _typeElementBrand: any; + name?: PropertyName; + questionToken?: QuestionToken; + } + interface InterfaceDeclaration extends DeclarationStatement, JSDocContainer { + kind: SyntaxKind.InterfaceDeclaration; + name: Identifier; + typeParameters?: NodeArray; + heritageClauses?: NodeArray; + members: NodeArray; + } + interface HeritageClause extends Node { + kind: SyntaxKind.HeritageClause; + parent: InterfaceDeclaration | ClassLikeDeclaration; + token: SyntaxKind.ExtendsKeyword | SyntaxKind.ImplementsKeyword; + types: NodeArray; + } + interface TypeAliasDeclaration extends DeclarationStatement, JSDocContainer { + kind: SyntaxKind.TypeAliasDeclaration; + name: Identifier; + typeParameters?: NodeArray; + type: TypeNode; + } + interface EnumMember extends NamedDeclaration, JSDocContainer { + kind: SyntaxKind.EnumMember; + parent: EnumDeclaration; + name: PropertyName; + initializer?: Expression; + } + interface EnumDeclaration extends DeclarationStatement, JSDocContainer { + kind: SyntaxKind.EnumDeclaration; + name: Identifier; + members: NodeArray; + } + type ModuleName = Identifier | StringLiteral; + type ModuleBody = NamespaceBody | JSDocNamespaceBody; + interface ModuleDeclaration extends DeclarationStatement, JSDocContainer { + kind: SyntaxKind.ModuleDeclaration; + parent: ModuleBody | SourceFile; + name: ModuleName; + body?: ModuleBody | JSDocNamespaceDeclaration; + } + type NamespaceBody = ModuleBlock | NamespaceDeclaration; + interface NamespaceDeclaration extends ModuleDeclaration { + name: Identifier; + body: NamespaceBody; + } + type JSDocNamespaceBody = Identifier | JSDocNamespaceDeclaration; + interface JSDocNamespaceDeclaration extends ModuleDeclaration { + name: Identifier; + body?: JSDocNamespaceBody; + } + interface ModuleBlock extends Node, Statement { + kind: SyntaxKind.ModuleBlock; + parent: ModuleDeclaration; + statements: NodeArray; + } + type ModuleReference = EntityName | ExternalModuleReference; + /** + * One of: + * - import x = require("mod"); + * - import x = M.x; + */ + interface ImportEqualsDeclaration extends DeclarationStatement, JSDocContainer { + kind: SyntaxKind.ImportEqualsDeclaration; + parent: SourceFile | ModuleBlock; + name: Identifier; + moduleReference: ModuleReference; + } + interface ExternalModuleReference extends Node { + kind: SyntaxKind.ExternalModuleReference; + parent: ImportEqualsDeclaration; + expression: Expression; + } + interface ImportDeclaration extends Statement { + kind: SyntaxKind.ImportDeclaration; + parent: SourceFile | ModuleBlock; + importClause?: ImportClause; + /** If this is not a StringLiteral it will be a grammar error. */ + moduleSpecifier: Expression; + } + type NamedImportBindings = NamespaceImport | NamedImports; + interface ImportClause extends NamedDeclaration { + kind: SyntaxKind.ImportClause; + parent: ImportDeclaration; + name?: Identifier; + namedBindings?: NamedImportBindings; + } + interface NamespaceImport extends NamedDeclaration { + kind: SyntaxKind.NamespaceImport; + parent: ImportClause; + name: Identifier; + } + interface NamespaceExportDeclaration extends DeclarationStatement { + kind: SyntaxKind.NamespaceExportDeclaration; + name: Identifier; + } + interface ExportDeclaration extends DeclarationStatement, JSDocContainer { + kind: SyntaxKind.ExportDeclaration; + parent: SourceFile | ModuleBlock; + /** Will not be assigned in the case of `export * from "foo";` */ + exportClause?: NamedExports; + /** If this is not a StringLiteral it will be a grammar error. */ + moduleSpecifier?: Expression; + } + interface NamedImports extends Node { + kind: SyntaxKind.NamedImports; + parent: ImportClause; + elements: NodeArray; + } + interface NamedExports extends Node { + kind: SyntaxKind.NamedExports; + parent: ExportDeclaration; + elements: NodeArray; + } + type NamedImportsOrExports = NamedImports | NamedExports; + interface ImportSpecifier extends NamedDeclaration { + kind: SyntaxKind.ImportSpecifier; + parent: NamedImports; + propertyName?: Identifier; + name: Identifier; + } + interface ExportSpecifier extends NamedDeclaration { + kind: SyntaxKind.ExportSpecifier; + parent: NamedExports; + propertyName?: Identifier; + name: Identifier; + } + type ImportOrExportSpecifier = ImportSpecifier | ExportSpecifier; + /** + * This is either an `export =` or an `export default` declaration. + * Unless `isExportEquals` is set, this node was parsed as an `export default`. + */ + interface ExportAssignment extends DeclarationStatement { + kind: SyntaxKind.ExportAssignment; + parent: SourceFile; + isExportEquals?: boolean; + expression: Expression; + } + interface FileReference extends TextRange { + fileName: string; + } + interface CheckJsDirective extends TextRange { + enabled: boolean; + } + type CommentKind = SyntaxKind.SingleLineCommentTrivia | SyntaxKind.MultiLineCommentTrivia; + interface CommentRange extends TextRange { + hasTrailingNewLine?: boolean; + kind: CommentKind; + } + interface SynthesizedComment extends CommentRange { + text: string; + pos: -1; + end: -1; + } + interface JSDocTypeExpression extends TypeNode { + kind: SyntaxKind.JSDocTypeExpression; + type: TypeNode; + } + interface JSDocType extends TypeNode { + _jsDocTypeBrand: any; + } + interface JSDocAllType extends JSDocType { + kind: SyntaxKind.JSDocAllType; + } + interface JSDocUnknownType extends JSDocType { + kind: SyntaxKind.JSDocUnknownType; + } + interface JSDocNonNullableType extends JSDocType { + kind: SyntaxKind.JSDocNonNullableType; + type: TypeNode; + } + interface JSDocNullableType extends JSDocType { + kind: SyntaxKind.JSDocNullableType; + type: TypeNode; + } + interface JSDocOptionalType extends JSDocType { + kind: SyntaxKind.JSDocOptionalType; + type: TypeNode; + } + interface JSDocFunctionType extends JSDocType, SignatureDeclarationBase { + kind: SyntaxKind.JSDocFunctionType; + } + interface JSDocVariadicType extends JSDocType { + kind: SyntaxKind.JSDocVariadicType; + type: TypeNode; + } + type JSDocTypeReferencingNode = JSDocVariadicType | JSDocOptionalType | JSDocNullableType | JSDocNonNullableType; + interface JSDoc extends Node { + kind: SyntaxKind.JSDocComment; + parent: HasJSDoc; + tags?: NodeArray; + comment?: string; + } + interface JSDocTag extends Node { + parent: JSDoc | JSDocTypeLiteral; + tagName: Identifier; + comment?: string; + } + interface JSDocUnknownTag extends JSDocTag { + kind: SyntaxKind.JSDocTag; + } + /** + * Note that `@extends` is a synonym of `@augments`. + * Both tags are represented by this interface. + */ + interface JSDocAugmentsTag extends JSDocTag { + kind: SyntaxKind.JSDocAugmentsTag; + class: ExpressionWithTypeArguments & { + expression: Identifier | PropertyAccessEntityNameExpression; + }; + } + interface JSDocClassTag extends JSDocTag { + kind: SyntaxKind.JSDocClassTag; + } + interface JSDocEnumTag extends JSDocTag { + kind: SyntaxKind.JSDocEnumTag; + typeExpression?: JSDocTypeExpression; + } + interface JSDocThisTag extends JSDocTag { + kind: SyntaxKind.JSDocThisTag; + typeExpression?: JSDocTypeExpression; + } + interface JSDocTemplateTag extends JSDocTag { + kind: SyntaxKind.JSDocTemplateTag; + constraint: JSDocTypeExpression | undefined; + typeParameters: NodeArray; + } + interface JSDocReturnTag extends JSDocTag { + kind: SyntaxKind.JSDocReturnTag; + typeExpression?: JSDocTypeExpression; + } + interface JSDocTypeTag extends JSDocTag { + kind: SyntaxKind.JSDocTypeTag; + typeExpression?: JSDocTypeExpression; + } + interface JSDocTypedefTag extends JSDocTag, NamedDeclaration { + parent: JSDoc; + kind: SyntaxKind.JSDocTypedefTag; + fullName?: JSDocNamespaceDeclaration | Identifier; + name?: Identifier; + typeExpression?: JSDocTypeExpression | JSDocTypeLiteral; + } + interface JSDocCallbackTag extends JSDocTag, NamedDeclaration { + parent: JSDoc; + kind: SyntaxKind.JSDocCallbackTag; + fullName?: JSDocNamespaceDeclaration | Identifier; + name?: Identifier; + typeExpression: JSDocSignature; + } + interface JSDocSignature extends JSDocType, Declaration { + kind: SyntaxKind.JSDocSignature; + typeParameters?: ReadonlyArray; + parameters: ReadonlyArray; + type: JSDocReturnTag | undefined; + } + interface JSDocPropertyLikeTag extends JSDocTag, Declaration { + parent: JSDoc; + name: EntityName; + typeExpression?: JSDocTypeExpression; + /** Whether the property name came before the type -- non-standard for JSDoc, but Typescript-like */ + isNameFirst: boolean; + isBracketed: boolean; + } + interface JSDocPropertyTag extends JSDocPropertyLikeTag { + kind: SyntaxKind.JSDocPropertyTag; + } + interface JSDocParameterTag extends JSDocPropertyLikeTag { + kind: SyntaxKind.JSDocParameterTag; + } + interface JSDocTypeLiteral extends JSDocType { + kind: SyntaxKind.JSDocTypeLiteral; + jsDocPropertyTags?: ReadonlyArray; + /** If true, then this type literal represents an *array* of its type. */ + isArrayType?: boolean; + } + enum FlowFlags { + Unreachable = 1, + Start = 2, + BranchLabel = 4, + LoopLabel = 8, + Assignment = 16, + TrueCondition = 32, + FalseCondition = 64, + SwitchClause = 128, + ArrayMutation = 256, + Referenced = 512, + Shared = 1024, + PreFinally = 2048, + AfterFinally = 4096, + Label = 12, + Condition = 96 + } + interface FlowLock { + locked?: boolean; + } + interface AfterFinallyFlow extends FlowNodeBase, FlowLock { + antecedent: FlowNode; + } + interface PreFinallyFlow extends FlowNodeBase { + antecedent: FlowNode; + lock: FlowLock; + } + type FlowNode = AfterFinallyFlow | PreFinallyFlow | FlowStart | FlowLabel | FlowAssignment | FlowCondition | FlowSwitchClause | FlowArrayMutation; + interface FlowNodeBase { + flags: FlowFlags; + id?: number; + } + interface FlowStart extends FlowNodeBase { + container?: FunctionExpression | ArrowFunction | MethodDeclaration; + } + interface FlowLabel extends FlowNodeBase { + antecedents: FlowNode[] | undefined; + } + interface FlowAssignment extends FlowNodeBase { + node: Expression | VariableDeclaration | BindingElement; + antecedent: FlowNode; + } + interface FlowCondition extends FlowNodeBase { + expression: Expression; + antecedent: FlowNode; + } + interface FlowSwitchClause extends FlowNodeBase { + switchStatement: SwitchStatement; + clauseStart: number; + clauseEnd: number; + antecedent: FlowNode; + } + interface FlowArrayMutation extends FlowNodeBase { + node: CallExpression | BinaryExpression; + antecedent: FlowNode; + } + type FlowType = Type | IncompleteType; + interface IncompleteType { + flags: TypeFlags; + type: Type; + } + interface AmdDependency { + path: string; + name?: string; + } + interface SourceFile extends Declaration { + kind: SyntaxKind.SourceFile; + statements: NodeArray; + endOfFileToken: Token; + fileName: string; + text: string; + amdDependencies: ReadonlyArray; + moduleName?: string; + referencedFiles: ReadonlyArray; + typeReferenceDirectives: ReadonlyArray; + libReferenceDirectives: ReadonlyArray; + languageVariant: LanguageVariant; + isDeclarationFile: boolean; + /** + * lib.d.ts should have a reference comment like + * + * /// + * + * If any other file has this comment, it signals not to include lib.d.ts + * because this containing file is intended to act as a default library. + */ + hasNoDefaultLib: boolean; + languageVersion: ScriptTarget; + } + interface Bundle extends Node { + kind: SyntaxKind.Bundle; + prepends: ReadonlyArray; + sourceFiles: ReadonlyArray; + } + interface InputFiles extends Node { + kind: SyntaxKind.InputFiles; + javascriptText: string; + javascriptMapPath?: string; + javascriptMapText?: string; + declarationText: string; + declarationMapPath?: string; + declarationMapText?: string; + } + interface UnparsedSource extends Node { + kind: SyntaxKind.UnparsedSource; + text: string; + sourceMapPath?: string; + sourceMapText?: string; + } + interface JsonSourceFile extends SourceFile { + statements: NodeArray; + } + interface TsConfigSourceFile extends JsonSourceFile { + extendedSourceFiles?: string[]; + } + interface JsonMinusNumericLiteral extends PrefixUnaryExpression { + kind: SyntaxKind.PrefixUnaryExpression; + operator: SyntaxKind.MinusToken; + operand: NumericLiteral; + } + interface JsonObjectExpressionStatement extends ExpressionStatement { + expression: ObjectLiteralExpression | ArrayLiteralExpression | JsonMinusNumericLiteral | NumericLiteral | StringLiteral | BooleanLiteral | NullLiteral; + } + interface ScriptReferenceHost { + getCompilerOptions(): CompilerOptions; + getSourceFile(fileName: string): SourceFile | undefined; + getSourceFileByPath(path: Path): SourceFile | undefined; + getCurrentDirectory(): string; + } + interface ParseConfigHost { + useCaseSensitiveFileNames: boolean; + readDirectory(rootDir: string, extensions: ReadonlyArray, excludes: ReadonlyArray | undefined, includes: ReadonlyArray, depth?: number): ReadonlyArray; + /** + * Gets a value indicating whether the specified path exists and is a file. + * @param path The path to test. + */ + fileExists(path: string): boolean; + readFile(path: string): string | undefined; + trace?(s: string): void; + } + /** + * Branded string for keeping track of when we've turned an ambiguous path + * specified like "./blah" to an absolute path to an actual + * tsconfig file, e.g. "/root/blah/tsconfig.json" + */ + type ResolvedConfigFileName = string & { + _isResolvedConfigFileName: never; + }; + type WriteFileCallback = (fileName: string, data: string, writeByteOrderMark: boolean, onError: ((message: string) => void) | undefined, sourceFiles?: ReadonlyArray) => void; + class OperationCanceledException { + } + interface CancellationToken { + isCancellationRequested(): boolean; + /** @throws OperationCanceledException if isCancellationRequested is true */ + throwIfCancellationRequested(): void; + } + interface Program extends ScriptReferenceHost { + /** + * Get a list of root file names that were passed to a 'createProgram' + */ + getRootFileNames(): ReadonlyArray; + /** + * Get a list of files in the program + */ + getSourceFiles(): ReadonlyArray; + /** + * Emits the JavaScript and declaration files. If targetSourceFile is not specified, then + * the JavaScript and declaration files will be produced for all the files in this program. + * If targetSourceFile is specified, then only the JavaScript and declaration for that + * specific file will be generated. + * + * If writeFile is not specified then the writeFile callback from the compiler host will be + * used for writing the JavaScript and declaration files. Otherwise, the writeFile parameter + * will be invoked when writing the JavaScript and declaration files. + */ + emit(targetSourceFile?: SourceFile, writeFile?: WriteFileCallback, cancellationToken?: CancellationToken, emitOnlyDtsFiles?: boolean, customTransformers?: CustomTransformers): EmitResult; + getOptionsDiagnostics(cancellationToken?: CancellationToken): ReadonlyArray; + getGlobalDiagnostics(cancellationToken?: CancellationToken): ReadonlyArray; + getSyntacticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray; + /** The first time this is called, it will return global diagnostics (no location). */ + getSemanticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray; + getDeclarationDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray; + getConfigFileParsingDiagnostics(): ReadonlyArray; + /** + * Gets a type checker that can be used to semantically analyze source files in the program. + */ + getTypeChecker(): TypeChecker; + isSourceFileFromExternalLibrary(file: SourceFile): boolean; + isSourceFileDefaultLibrary(file: SourceFile): boolean; + getProjectReferences(): ReadonlyArray | undefined; + getResolvedProjectReferences(): ReadonlyArray | undefined; + } + interface ResolvedProjectReference { + commandLine: ParsedCommandLine; + sourceFile: SourceFile; + references?: ReadonlyArray; + } + interface CustomTransformers { + /** Custom transformers to evaluate before built-in .js transformations. */ + before?: TransformerFactory[]; + /** Custom transformers to evaluate after built-in .js transformations. */ + after?: TransformerFactory[]; + /** Custom transformers to evaluate after built-in .d.ts transformations. */ + afterDeclarations?: TransformerFactory[]; + } + interface SourceMapSpan { + /** Line number in the .js file. */ + emittedLine: number; + /** Column number in the .js file. */ + emittedColumn: number; + /** Line number in the .ts file. */ + sourceLine: number; + /** Column number in the .ts file. */ + sourceColumn: number; + /** Optional name (index into names array) associated with this span. */ + nameIndex?: number; + /** .ts file (index into sources array) associated with this span */ + sourceIndex: number; + } + /** Return code used by getEmitOutput function to indicate status of the function */ + enum ExitStatus { + Success = 0, + DiagnosticsPresent_OutputsSkipped = 1, + DiagnosticsPresent_OutputsGenerated = 2 + } + interface EmitResult { + emitSkipped: boolean; + /** Contains declaration emit diagnostics */ + diagnostics: ReadonlyArray; + emittedFiles?: string[]; + } + interface TypeChecker { + getTypeOfSymbolAtLocation(symbol: Symbol, node: Node): Type; + getDeclaredTypeOfSymbol(symbol: Symbol): Type; + getPropertiesOfType(type: Type): Symbol[]; + getPropertyOfType(type: Type, propertyName: string): Symbol | undefined; + getIndexInfoOfType(type: Type, kind: IndexKind): IndexInfo | undefined; + getSignaturesOfType(type: Type, kind: SignatureKind): ReadonlyArray; + getIndexTypeOfType(type: Type, kind: IndexKind): Type | undefined; + getBaseTypes(type: InterfaceType): BaseType[]; + getBaseTypeOfLiteralType(type: Type): Type; + getWidenedType(type: Type): Type; + getReturnTypeOfSignature(signature: Signature): Type; + getNullableType(type: Type, flags: TypeFlags): Type; + getNonNullableType(type: Type): Type; + /** Note that the resulting nodes cannot be checked. */ + typeToTypeNode(type: Type, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): TypeNode | undefined; + /** Note that the resulting nodes cannot be checked. */ + signatureToSignatureDeclaration(signature: Signature, kind: SyntaxKind, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): (SignatureDeclaration & { + typeArguments?: NodeArray; + }) | undefined; + /** Note that the resulting nodes cannot be checked. */ + indexInfoToIndexSignatureDeclaration(indexInfo: IndexInfo, kind: IndexKind, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): IndexSignatureDeclaration | undefined; + /** Note that the resulting nodes cannot be checked. */ + symbolToEntityName(symbol: Symbol, meaning: SymbolFlags, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): EntityName | undefined; + /** Note that the resulting nodes cannot be checked. */ + symbolToExpression(symbol: Symbol, meaning: SymbolFlags, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): Expression | undefined; + /** Note that the resulting nodes cannot be checked. */ + symbolToTypeParameterDeclarations(symbol: Symbol, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): NodeArray | undefined; + /** Note that the resulting nodes cannot be checked. */ + symbolToParameterDeclaration(symbol: Symbol, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): ParameterDeclaration | undefined; + /** Note that the resulting nodes cannot be checked. */ + typeParameterToDeclaration(parameter: TypeParameter, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): TypeParameterDeclaration | undefined; + getSymbolsInScope(location: Node, meaning: SymbolFlags): Symbol[]; + getSymbolAtLocation(node: Node): Symbol | undefined; + getSymbolsOfParameterPropertyDeclaration(parameter: ParameterDeclaration, parameterName: string): Symbol[]; + /** + * The function returns the value (local variable) symbol of an identifier in the short-hand property assignment. + * This is necessary as an identifier in short-hand property assignment can contains two meaning: property name and property value. + */ + getShorthandAssignmentValueSymbol(location: Node): Symbol | undefined; + getExportSpecifierLocalTargetSymbol(location: ExportSpecifier): Symbol | undefined; + /** + * If a symbol is a local symbol with an associated exported symbol, returns the exported symbol. + * Otherwise returns its input. + * For example, at `export type T = number;`: + * - `getSymbolAtLocation` at the location `T` will return the exported symbol for `T`. + * - But the result of `getSymbolsInScope` will contain the *local* symbol for `T`, not the exported symbol. + * - Calling `getExportSymbolOfSymbol` on that local symbol will return the exported symbol. + */ + getExportSymbolOfSymbol(symbol: Symbol): Symbol; + getPropertySymbolOfDestructuringAssignment(location: Identifier): Symbol | undefined; + getTypeAtLocation(node: Node): Type; + getTypeFromTypeNode(node: TypeNode): Type; + signatureToString(signature: Signature, enclosingDeclaration?: Node, flags?: TypeFormatFlags, kind?: SignatureKind): string; + typeToString(type: Type, enclosingDeclaration?: Node, flags?: TypeFormatFlags): string; + symbolToString(symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags, flags?: SymbolFormatFlags): string; + typePredicateToString(predicate: TypePredicate, enclosingDeclaration?: Node, flags?: TypeFormatFlags): string; + getFullyQualifiedName(symbol: Symbol): string; + getAugmentedPropertiesOfType(type: Type): Symbol[]; + getRootSymbols(symbol: Symbol): ReadonlyArray; + getContextualType(node: Expression): Type | undefined; + /** + * returns unknownSignature in the case of an error. + * returns undefined if the node is not valid. + * @param argumentCount Apparent number of arguments, passed in case of a possibly incomplete call. This should come from an ArgumentListInfo. See `signatureHelp.ts`. + */ + getResolvedSignature(node: CallLikeExpression, candidatesOutArray?: Signature[], argumentCount?: number): Signature | undefined; + getSignatureFromDeclaration(declaration: SignatureDeclaration): Signature | undefined; + isImplementationOfOverload(node: SignatureDeclaration): boolean | undefined; + isUndefinedSymbol(symbol: Symbol): boolean; + isArgumentsSymbol(symbol: Symbol): boolean; + isUnknownSymbol(symbol: Symbol): boolean; + getConstantValue(node: EnumMember | PropertyAccessExpression | ElementAccessExpression): string | number | undefined; + isValidPropertyAccess(node: PropertyAccessExpression | QualifiedName | ImportTypeNode, propertyName: string): boolean; + /** Follow all aliases to get the original symbol. */ + getAliasedSymbol(symbol: Symbol): Symbol; + getExportsOfModule(moduleSymbol: Symbol): Symbol[]; + getJsxIntrinsicTagNamesAt(location: Node): Symbol[]; + isOptionalParameter(node: ParameterDeclaration): boolean; + getAmbientModules(): Symbol[]; + tryGetMemberInModuleExports(memberName: string, moduleSymbol: Symbol): Symbol | undefined; + getApparentType(type: Type): Type; + getBaseConstraintOfType(type: Type): Type | undefined; + getDefaultFromTypeParameter(type: Type): Type | undefined; + /** + * Depending on the operation performed, it may be appropriate to throw away the checker + * if the cancellation token is triggered. Typically, if it is used for error checking + * and the operation is cancelled, then it should be discarded, otherwise it is safe to keep. + */ + runWithCancellationToken(token: CancellationToken, cb: (checker: TypeChecker) => T): T; + } + enum NodeBuilderFlags { + None = 0, + NoTruncation = 1, + WriteArrayAsGenericType = 2, + GenerateNamesForShadowedTypeParams = 4, + UseStructuralFallback = 8, + ForbidIndexedAccessSymbolReferences = 16, + WriteTypeArgumentsOfSignature = 32, + UseFullyQualifiedType = 64, + UseOnlyExternalAliasing = 128, + SuppressAnyReturnType = 256, + WriteTypeParametersInQualifiedName = 512, + MultilineObjectLiterals = 1024, + WriteClassExpressionAsTypeLiteral = 2048, + UseTypeOfFunction = 4096, + OmitParameterModifiers = 8192, + UseAliasDefinedOutsideCurrentScope = 16384, + AllowThisInObjectLiteral = 32768, + AllowQualifedNameInPlaceOfIdentifier = 65536, + AllowAnonymousIdentifier = 131072, + AllowEmptyUnionOrIntersection = 262144, + AllowEmptyTuple = 524288, + AllowUniqueESSymbolType = 1048576, + AllowEmptyIndexInfoType = 2097152, + AllowNodeModulesRelativePaths = 67108864, + IgnoreErrors = 70221824, + InObjectTypeLiteral = 4194304, + InTypeAlias = 8388608, + InInitialEntityName = 16777216, + InReverseMappedType = 33554432 + } + enum TypeFormatFlags { + None = 0, + NoTruncation = 1, + WriteArrayAsGenericType = 2, + UseStructuralFallback = 8, + WriteTypeArgumentsOfSignature = 32, + UseFullyQualifiedType = 64, + SuppressAnyReturnType = 256, + MultilineObjectLiterals = 1024, + WriteClassExpressionAsTypeLiteral = 2048, + UseTypeOfFunction = 4096, + OmitParameterModifiers = 8192, + UseAliasDefinedOutsideCurrentScope = 16384, + AllowUniqueESSymbolType = 1048576, + AddUndefined = 131072, + WriteArrowStyleSignature = 262144, + InArrayType = 524288, + InElementType = 2097152, + InFirstTypeArgument = 4194304, + InTypeAlias = 8388608, + /** @deprecated */ WriteOwnNameForAnyLike = 0, + NodeBuilderFlagsMask = 9469291 + } + enum SymbolFormatFlags { + None = 0, + WriteTypeParametersOrArguments = 1, + UseOnlyExternalAliasing = 2, + AllowAnyNodeKind = 4, + UseAliasDefinedOutsideCurrentScope = 8 + } + enum TypePredicateKind { + This = 0, + Identifier = 1 + } + interface TypePredicateBase { + kind: TypePredicateKind; + type: Type; + } + interface ThisTypePredicate extends TypePredicateBase { + kind: TypePredicateKind.This; + } + interface IdentifierTypePredicate extends TypePredicateBase { + kind: TypePredicateKind.Identifier; + parameterName: string; + parameterIndex: number; + } + type TypePredicate = IdentifierTypePredicate | ThisTypePredicate; + enum SymbolFlags { + None = 0, + FunctionScopedVariable = 1, + BlockScopedVariable = 2, + Property = 4, + EnumMember = 8, + Function = 16, + Class = 32, + Interface = 64, + ConstEnum = 128, + RegularEnum = 256, + ValueModule = 512, + NamespaceModule = 1024, + TypeLiteral = 2048, + ObjectLiteral = 4096, + Method = 8192, + Constructor = 16384, + GetAccessor = 32768, + SetAccessor = 65536, + Signature = 131072, + TypeParameter = 262144, + TypeAlias = 524288, + ExportValue = 1048576, + Alias = 2097152, + Prototype = 4194304, + ExportStar = 8388608, + Optional = 16777216, + Transient = 33554432, + Assignment = 67108864, + ModuleExports = 134217728, + Enum = 384, + Variable = 3, + Value = 67220415, + Type = 67897832, + Namespace = 1920, + Module = 1536, + Accessor = 98304, + FunctionScopedVariableExcludes = 67220414, + BlockScopedVariableExcludes = 67220415, + ParameterExcludes = 67220415, + PropertyExcludes = 0, + EnumMemberExcludes = 68008959, + FunctionExcludes = 67219887, + ClassExcludes = 68008383, + InterfaceExcludes = 67897736, + RegularEnumExcludes = 68008191, + ConstEnumExcludes = 68008831, + ValueModuleExcludes = 110735, + NamespaceModuleExcludes = 0, + MethodExcludes = 67212223, + GetAccessorExcludes = 67154879, + SetAccessorExcludes = 67187647, + TypeParameterExcludes = 67635688, + TypeAliasExcludes = 67897832, + AliasExcludes = 2097152, + ModuleMember = 2623475, + ExportHasLocal = 944, + BlockScoped = 418, + PropertyOrAccessor = 98308, + ClassMember = 106500 + } + interface Symbol { + flags: SymbolFlags; + escapedName: __String; + declarations: Declaration[]; + valueDeclaration: Declaration; + members?: SymbolTable; + exports?: SymbolTable; + globalExports?: SymbolTable; + } + enum InternalSymbolName { + Call = "__call", + Constructor = "__constructor", + New = "__new", + Index = "__index", + ExportStar = "__export", + Global = "__global", + Missing = "__missing", + Type = "__type", + Object = "__object", + JSXAttributes = "__jsxAttributes", + Class = "__class", + Function = "__function", + Computed = "__computed", + Resolving = "__resolving__", + ExportEquals = "export=", + Default = "default", + This = "this" + } + /** + * This represents a string whose leading underscore have been escaped by adding extra leading underscores. + * The shape of this brand is rather unique compared to others we've used. + * Instead of just an intersection of a string and an object, it is that union-ed + * with an intersection of void and an object. This makes it wholly incompatible + * with a normal string (which is good, it cannot be misused on assignment or on usage), + * while still being comparable with a normal string via === (also good) and castable from a string. + */ + type __String = (string & { + __escapedIdentifier: void; + }) | (void & { + __escapedIdentifier: void; + }) | InternalSymbolName; + /** ReadonlyMap where keys are `__String`s. */ + interface ReadonlyUnderscoreEscapedMap { + get(key: __String): T | undefined; + has(key: __String): boolean; + forEach(action: (value: T, key: __String) => void): void; + readonly size: number; + keys(): Iterator<__String>; + values(): Iterator; + entries(): Iterator<[__String, T]>; + } + /** Map where keys are `__String`s. */ + interface UnderscoreEscapedMap extends ReadonlyUnderscoreEscapedMap { + set(key: __String, value: T): this; + delete(key: __String): boolean; + clear(): void; + } + /** SymbolTable based on ES6 Map interface. */ + type SymbolTable = UnderscoreEscapedMap; + enum TypeFlags { + Any = 1, + Unknown = 2, + String = 4, + Number = 8, + Boolean = 16, + Enum = 32, + BigInt = 64, + StringLiteral = 128, + NumberLiteral = 256, + BooleanLiteral = 512, + EnumLiteral = 1024, + BigIntLiteral = 2048, + ESSymbol = 4096, + UniqueESSymbol = 8192, + Void = 16384, + Undefined = 32768, + Null = 65536, + Never = 131072, + TypeParameter = 262144, + Object = 524288, + Union = 1048576, + Intersection = 2097152, + Index = 4194304, + IndexedAccess = 8388608, + Conditional = 16777216, + Substitution = 33554432, + NonPrimitive = 67108864, + Literal = 2944, + Unit = 109440, + StringOrNumberLiteral = 384, + PossiblyFalsy = 117724, + StringLike = 132, + NumberLike = 296, + BigIntLike = 2112, + BooleanLike = 528, + EnumLike = 1056, + ESSymbolLike = 12288, + VoidLike = 49152, + UnionOrIntersection = 3145728, + StructuredType = 3670016, + TypeVariable = 8650752, + InstantiableNonPrimitive = 58982400, + InstantiablePrimitive = 4194304, + Instantiable = 63176704, + StructuredOrInstantiable = 66846720, + Narrowable = 133970943, + NotUnionOrUnit = 67637251 + } + type DestructuringPattern = BindingPattern | ObjectLiteralExpression | ArrayLiteralExpression; + interface Type { + flags: TypeFlags; + symbol: Symbol; + pattern?: DestructuringPattern; + aliasSymbol?: Symbol; + aliasTypeArguments?: ReadonlyArray; + } + interface LiteralType extends Type { + value: string | number | PseudoBigInt; + freshType: LiteralType; + regularType: LiteralType; + } + interface UniqueESSymbolType extends Type { + symbol: Symbol; + } + interface StringLiteralType extends LiteralType { + value: string; + } + interface NumberLiteralType extends LiteralType { + value: number; + } + interface BigIntLiteralType extends LiteralType { + value: PseudoBigInt; + } + interface EnumType extends Type { + } + enum ObjectFlags { + Class = 1, + Interface = 2, + Reference = 4, + Tuple = 8, + Anonymous = 16, + Mapped = 32, + Instantiated = 64, + ObjectLiteral = 128, + EvolvingArray = 256, + ObjectLiteralPatternWithComputedProperties = 512, + ContainsSpread = 1024, + ReverseMapped = 2048, + JsxAttributes = 4096, + MarkerType = 8192, + JSLiteral = 16384, + FreshLiteral = 32768, + ClassOrInterface = 3 + } + interface ObjectType extends Type { + objectFlags: ObjectFlags; + } + /** Class and interface types (ObjectFlags.Class and ObjectFlags.Interface). */ + interface InterfaceType extends ObjectType { + typeParameters: TypeParameter[] | undefined; + outerTypeParameters: TypeParameter[] | undefined; + localTypeParameters: TypeParameter[] | undefined; + thisType: TypeParameter | undefined; + } + type BaseType = ObjectType | IntersectionType; + interface InterfaceTypeWithDeclaredMembers extends InterfaceType { + declaredProperties: Symbol[]; + declaredCallSignatures: Signature[]; + declaredConstructSignatures: Signature[]; + declaredStringIndexInfo?: IndexInfo; + declaredNumberIndexInfo?: IndexInfo; + } + /** + * Type references (ObjectFlags.Reference). When a class or interface has type parameters or + * a "this" type, references to the class or interface are made using type references. The + * typeArguments property specifies the types to substitute for the type parameters of the + * class or interface and optionally includes an extra element that specifies the type to + * substitute for "this" in the resulting instantiation. When no extra argument is present, + * the type reference itself is substituted for "this". The typeArguments property is undefined + * if the class or interface has no type parameters and the reference isn't specifying an + * explicit "this" argument. + */ + interface TypeReference extends ObjectType { + target: GenericType; + typeArguments?: ReadonlyArray; + } + interface GenericType extends InterfaceType, TypeReference { + } + interface TupleType extends GenericType { + minLength: number; + hasRestElement: boolean; + associatedNames?: __String[]; + } + interface TupleTypeReference extends TypeReference { + target: TupleType; + } + interface UnionOrIntersectionType extends Type { + types: Type[]; + } + interface UnionType extends UnionOrIntersectionType { + } + interface IntersectionType extends UnionOrIntersectionType { + } + type StructuredType = ObjectType | UnionType | IntersectionType; + interface EvolvingArrayType extends ObjectType { + elementType: Type; + finalArrayType?: Type; + } + interface InstantiableType extends Type { + } + interface TypeParameter extends InstantiableType { + } + interface IndexedAccessType extends InstantiableType { + objectType: Type; + indexType: Type; + constraint?: Type; + simplified?: Type; + } + type TypeVariable = TypeParameter | IndexedAccessType; + interface IndexType extends InstantiableType { + type: InstantiableType | UnionOrIntersectionType; + } + interface ConditionalRoot { + node: ConditionalTypeNode; + checkType: Type; + extendsType: Type; + trueType: Type; + falseType: Type; + isDistributive: boolean; + inferTypeParameters?: TypeParameter[]; + outerTypeParameters?: TypeParameter[]; + instantiations?: Map; + aliasSymbol?: Symbol; + aliasTypeArguments?: Type[]; + } + interface ConditionalType extends InstantiableType { + root: ConditionalRoot; + checkType: Type; + extendsType: Type; + resolvedTrueType?: Type; + resolvedFalseType?: Type; + } + interface SubstitutionType extends InstantiableType { + typeVariable: TypeVariable; + substitute: Type; + } + enum SignatureKind { + Call = 0, + Construct = 1 + } + interface Signature { + declaration?: SignatureDeclaration | JSDocSignature; + typeParameters?: ReadonlyArray; + parameters: ReadonlyArray; + } + enum IndexKind { + String = 0, + Number = 1 + } + interface IndexInfo { + type: Type; + isReadonly: boolean; + declaration?: IndexSignatureDeclaration; + } + enum InferencePriority { + NakedTypeVariable = 1, + HomomorphicMappedType = 2, + MappedTypeConstraint = 4, + ReturnType = 8, + LiteralKeyof = 16, + NoConstraints = 32, + AlwaysStrict = 64, + PriorityImpliesCombination = 28 + } + /** @deprecated Use FileExtensionInfo instead. */ + type JsFileExtensionInfo = FileExtensionInfo; + interface FileExtensionInfo { + extension: string; + isMixedContent: boolean; + scriptKind?: ScriptKind; + } + interface DiagnosticMessage { + key: string; + category: DiagnosticCategory; + code: number; + message: string; + reportsUnnecessary?: {}; + } + /** + * A linked list of formatted diagnostic messages to be used as part of a multiline message. + * It is built from the bottom up, leaving the head to be the "main" diagnostic. + * While it seems that DiagnosticMessageChain is structurally similar to DiagnosticMessage, + * the difference is that messages are all preformatted in DMC. + */ + interface DiagnosticMessageChain { + messageText: string; + category: DiagnosticCategory; + code: number; + next?: DiagnosticMessageChain; + } + interface Diagnostic extends DiagnosticRelatedInformation { + /** May store more in future. For now, this will simply be `true` to indicate when a diagnostic is an unused-identifier diagnostic. */ + reportsUnnecessary?: {}; + source?: string; + relatedInformation?: DiagnosticRelatedInformation[]; + } + interface DiagnosticRelatedInformation { + category: DiagnosticCategory; + code: number; + file: SourceFile | undefined; + start: number | undefined; + length: number | undefined; + messageText: string | DiagnosticMessageChain; + } + interface DiagnosticWithLocation extends Diagnostic { + file: SourceFile; + start: number; + length: number; + } + enum DiagnosticCategory { + Warning = 0, + Error = 1, + Suggestion = 2, + Message = 3 + } + enum ModuleResolutionKind { + Classic = 1, + NodeJs = 2 + } + interface PluginImport { + name: string; + } + interface ProjectReference { + /** A normalized path on disk */ + path: string; + /** The path as the user originally wrote it */ + originalPath?: string; + /** True if the output of this reference should be prepended to the output of this project. Only valid for --outFile compilations */ + prepend?: boolean; + /** True if it is intended that this reference form a circularity */ + circular?: boolean; + } + type CompilerOptionsValue = string | number | boolean | (string | number)[] | string[] | MapLike | PluginImport[] | ProjectReference[] | null | undefined; + interface CompilerOptions { + allowJs?: boolean; + allowSyntheticDefaultImports?: boolean; + allowUnreachableCode?: boolean; + allowUnusedLabels?: boolean; + alwaysStrict?: boolean; + baseUrl?: string; + charset?: string; + checkJs?: boolean; + declaration?: boolean; + declarationMap?: boolean; + emitDeclarationOnly?: boolean; + declarationDir?: string; + disableSizeLimit?: boolean; + downlevelIteration?: boolean; + emitBOM?: boolean; + emitDecoratorMetadata?: boolean; + experimentalDecorators?: boolean; + forceConsistentCasingInFileNames?: boolean; + importHelpers?: boolean; + inlineSourceMap?: boolean; + inlineSources?: boolean; + isolatedModules?: boolean; + jsx?: JsxEmit; + keyofStringsOnly?: boolean; + lib?: string[]; + locale?: string; + mapRoot?: string; + maxNodeModuleJsDepth?: number; + module?: ModuleKind; + moduleResolution?: ModuleResolutionKind; + newLine?: NewLineKind; + noEmit?: boolean; + noEmitHelpers?: boolean; + noEmitOnError?: boolean; + noErrorTruncation?: boolean; + noFallthroughCasesInSwitch?: boolean; + noImplicitAny?: boolean; + noImplicitReturns?: boolean; + noImplicitThis?: boolean; + noStrictGenericChecks?: boolean; + noUnusedLocals?: boolean; + noUnusedParameters?: boolean; + noImplicitUseStrict?: boolean; + noLib?: boolean; + noResolve?: boolean; + out?: string; + outDir?: string; + outFile?: string; + paths?: MapLike; + preserveConstEnums?: boolean; + preserveSymlinks?: boolean; + project?: string; + reactNamespace?: string; + jsxFactory?: string; + composite?: boolean; + removeComments?: boolean; + rootDir?: string; + rootDirs?: string[]; + skipLibCheck?: boolean; + skipDefaultLibCheck?: boolean; + sourceMap?: boolean; + sourceRoot?: string; + strict?: boolean; + strictFunctionTypes?: boolean; + strictBindCallApply?: boolean; + strictNullChecks?: boolean; + strictPropertyInitialization?: boolean; + stripInternal?: boolean; + suppressExcessPropertyErrors?: boolean; + suppressImplicitAnyIndexErrors?: boolean; + target?: ScriptTarget; + traceResolution?: boolean; + resolveJsonModule?: boolean; + types?: string[]; + /** Paths used to compute primary types search locations */ + typeRoots?: string[]; + esModuleInterop?: boolean; + [option: string]: CompilerOptionsValue | TsConfigSourceFile | undefined; + } + interface TypeAcquisition { + enableAutoDiscovery?: boolean; + enable?: boolean; + include?: string[]; + exclude?: string[]; + [option: string]: string[] | boolean | undefined; + } + enum ModuleKind { + None = 0, + CommonJS = 1, + AMD = 2, + UMD = 3, + System = 4, + ES2015 = 5, + ESNext = 6 + } + enum JsxEmit { + None = 0, + Preserve = 1, + React = 2, + ReactNative = 3 + } + enum NewLineKind { + CarriageReturnLineFeed = 0, + LineFeed = 1 + } + interface LineAndCharacter { + /** 0-based. */ + line: number; + character: number; + } + enum ScriptKind { + Unknown = 0, + JS = 1, + JSX = 2, + TS = 3, + TSX = 4, + External = 5, + JSON = 6, + /** + * Used on extensions that doesn't define the ScriptKind but the content defines it. + * Deferred extensions are going to be included in all project contexts. + */ + Deferred = 7 + } + enum ScriptTarget { + ES3 = 0, + ES5 = 1, + ES2015 = 2, + ES2016 = 3, + ES2017 = 4, + ES2018 = 5, + ESNext = 6, + JSON = 100, + Latest = 6 + } + enum LanguageVariant { + Standard = 0, + JSX = 1 + } + /** Either a parsed command line or a parsed tsconfig.json */ + interface ParsedCommandLine { + options: CompilerOptions; + typeAcquisition?: TypeAcquisition; + fileNames: string[]; + projectReferences?: ReadonlyArray; + raw?: any; + errors: Diagnostic[]; + wildcardDirectories?: MapLike; + compileOnSave?: boolean; + } + enum WatchDirectoryFlags { + None = 0, + Recursive = 1 + } + interface ExpandResult { + fileNames: string[]; + wildcardDirectories: MapLike; + } + interface CreateProgramOptions { + rootNames: ReadonlyArray; + options: CompilerOptions; + projectReferences?: ReadonlyArray; + host?: CompilerHost; + oldProgram?: Program; + configFileParsingDiagnostics?: ReadonlyArray; + } + interface ModuleResolutionHost { + fileExists(fileName: string): boolean; + readFile(fileName: string): string | undefined; + trace?(s: string): void; + directoryExists?(directoryName: string): boolean; + /** + * Resolve a symbolic link. + * @see https://nodejs.org/api/fs.html#fs_fs_realpathsync_path_options + */ + realpath?(path: string): string; + getCurrentDirectory?(): string; + getDirectories?(path: string): string[]; + } + /** + * Represents the result of module resolution. + * Module resolution will pick up tsx/jsx/js files even if '--jsx' and '--allowJs' are turned off. + * The Program will then filter results based on these flags. + * + * Prefer to return a `ResolvedModuleFull` so that the file type does not have to be inferred. + */ + interface ResolvedModule { + /** Path of the file the module was resolved to. */ + resolvedFileName: string; + /** True if `resolvedFileName` comes from `node_modules`. */ + isExternalLibraryImport?: boolean; + } + /** + * ResolvedModule with an explicitly provided `extension` property. + * Prefer this over `ResolvedModule`. + * If changing this, remember to change `moduleResolutionIsEqualTo`. + */ + interface ResolvedModuleFull extends ResolvedModule { + /** + * Extension of resolvedFileName. This must match what's at the end of resolvedFileName. + * This is optional for backwards-compatibility, but will be added if not provided. + */ + extension: Extension; + packageId?: PackageId; + } + /** + * Unique identifier with a package name and version. + * If changing this, remember to change `packageIdIsEqual`. + */ + interface PackageId { + /** + * Name of the package. + * Should not include `@types`. + * If accessing a non-index file, this should include its name e.g. "foo/bar". + */ + name: string; + /** + * Name of a submodule within this package. + * May be "". + */ + subModuleName: string; + /** Version of the package, e.g. "1.2.3" */ + version: string; + } + enum Extension { + Ts = ".ts", + Tsx = ".tsx", + Dts = ".d.ts", + Js = ".js", + Jsx = ".jsx", + Json = ".json" + } + interface ResolvedModuleWithFailedLookupLocations { + readonly resolvedModule: ResolvedModuleFull | undefined; + } + interface ResolvedTypeReferenceDirective { + primary: boolean; + resolvedFileName: string | undefined; + packageId?: PackageId; + /** True if `resolvedFileName` comes from `node_modules`. */ + isExternalLibraryImport?: boolean; + } + interface ResolvedTypeReferenceDirectiveWithFailedLookupLocations { + readonly resolvedTypeReferenceDirective: ResolvedTypeReferenceDirective | undefined; + readonly failedLookupLocations: ReadonlyArray; + } + interface CompilerHost extends ModuleResolutionHost { + getSourceFile(fileName: string, languageVersion: ScriptTarget, onError?: (message: string) => void, shouldCreateNewSourceFile?: boolean): SourceFile | undefined; + getSourceFileByPath?(fileName: string, path: Path, languageVersion: ScriptTarget, onError?: (message: string) => void, shouldCreateNewSourceFile?: boolean): SourceFile | undefined; + getCancellationToken?(): CancellationToken; + getDefaultLibFileName(options: CompilerOptions): string; + getDefaultLibLocation?(): string; + writeFile: WriteFileCallback; + getCurrentDirectory(): string; + getDirectories(path: string): string[]; + getCanonicalFileName(fileName: string): string; + useCaseSensitiveFileNames(): boolean; + getNewLine(): string; + readDirectory?(rootDir: string, extensions: ReadonlyArray, excludes: ReadonlyArray | undefined, includes: ReadonlyArray, depth?: number): string[]; + resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[], redirectedReference?: ResolvedProjectReference): (ResolvedModule | undefined)[]; + /** + * This method is a companion for 'resolveModuleNames' and is used to resolve 'types' references to actual type declaration files + */ + resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string, redirectedReference?: ResolvedProjectReference): (ResolvedTypeReferenceDirective | undefined)[]; + getEnvironmentVariable?(name: string): string | undefined; + createHash?(data: string): string; + } + interface SourceMapRange extends TextRange { + source?: SourceMapSource; + } + interface SourceMapSource { + fileName: string; + text: string; + skipTrivia?: (pos: number) => number; + } + enum EmitFlags { + None = 0, + SingleLine = 1, + AdviseOnEmitNode = 2, + NoSubstitution = 4, + CapturesThis = 8, + NoLeadingSourceMap = 16, + NoTrailingSourceMap = 32, + NoSourceMap = 48, + NoNestedSourceMaps = 64, + NoTokenLeadingSourceMaps = 128, + NoTokenTrailingSourceMaps = 256, + NoTokenSourceMaps = 384, + NoLeadingComments = 512, + NoTrailingComments = 1024, + NoComments = 1536, + NoNestedComments = 2048, + HelperName = 4096, + ExportName = 8192, + LocalName = 16384, + InternalName = 32768, + Indented = 65536, + NoIndentation = 131072, + AsyncFunctionBody = 262144, + ReuseTempVariableScope = 524288, + CustomPrologue = 1048576, + NoHoisting = 2097152, + HasEndOfDeclarationMarker = 4194304, + Iterator = 8388608, + NoAsciiEscaping = 16777216 + } + interface EmitHelper { + readonly name: string; + readonly scoped: boolean; + readonly text: string | ((node: EmitHelperUniqueNameCallback) => string); + readonly priority?: number; + } + type EmitHelperUniqueNameCallback = (name: string) => string; + enum EmitHint { + SourceFile = 0, + Expression = 1, + IdentifierName = 2, + MappedTypeParameter = 3, + Unspecified = 4, + EmbeddedStatement = 5 + } + interface TransformationContext { + /** Gets the compiler options supplied to the transformer. */ + getCompilerOptions(): CompilerOptions; + /** Starts a new lexical environment. */ + startLexicalEnvironment(): void; + /** Suspends the current lexical environment, usually after visiting a parameter list. */ + suspendLexicalEnvironment(): void; + /** Resumes a suspended lexical environment, usually before visiting a function body. */ + resumeLexicalEnvironment(): void; + /** Ends a lexical environment, returning any declarations. */ + endLexicalEnvironment(): Statement[] | undefined; + /** Hoists a function declaration to the containing scope. */ + hoistFunctionDeclaration(node: FunctionDeclaration): void; + /** Hoists a variable declaration to the containing scope. */ + hoistVariableDeclaration(node: Identifier): void; + /** Records a request for a non-scoped emit helper in the current context. */ + requestEmitHelper(helper: EmitHelper): void; + /** Gets and resets the requested non-scoped emit helpers. */ + readEmitHelpers(): EmitHelper[] | undefined; + /** Enables expression substitutions in the pretty printer for the provided SyntaxKind. */ + enableSubstitution(kind: SyntaxKind): void; + /** Determines whether expression substitutions are enabled for the provided node. */ + isSubstitutionEnabled(node: Node): boolean; + /** + * Hook used by transformers to substitute expressions just before they + * are emitted by the pretty printer. + * + * NOTE: Transformation hooks should only be modified during `Transformer` initialization, + * before returning the `NodeTransformer` callback. + */ + onSubstituteNode: (hint: EmitHint, node: Node) => Node; + /** + * Enables before/after emit notifications in the pretty printer for the provided + * SyntaxKind. + */ + enableEmitNotification(kind: SyntaxKind): void; + /** + * Determines whether before/after emit notifications should be raised in the pretty + * printer when it emits a node. + */ + isEmitNotificationEnabled(node: Node): boolean; + /** + * Hook used to allow transformers to capture state before or after + * the printer emits a node. + * + * NOTE: Transformation hooks should only be modified during `Transformer` initialization, + * before returning the `NodeTransformer` callback. + */ + onEmitNode: (hint: EmitHint, node: Node, emitCallback: (hint: EmitHint, node: Node) => void) => void; + } + interface TransformationResult { + /** Gets the transformed source files. */ + transformed: T[]; + /** Gets diagnostics for the transformation. */ + diagnostics?: DiagnosticWithLocation[]; + /** + * Gets a substitute for a node, if one is available; otherwise, returns the original node. + * + * @param hint A hint as to the intended usage of the node. + * @param node The node to substitute. + */ + substituteNode(hint: EmitHint, node: Node): Node; + /** + * Emits a node with possible notification. + * + * @param hint A hint as to the intended usage of the node. + * @param node The node to emit. + * @param emitCallback A callback used to emit the node. + */ + emitNodeWithNotification(hint: EmitHint, node: Node, emitCallback: (hint: EmitHint, node: Node) => void): void; + /** + * Clean up EmitNode entries on any parse-tree nodes. + */ + dispose(): void; + } + /** + * A function that is used to initialize and return a `Transformer` callback, which in turn + * will be used to transform one or more nodes. + */ + type TransformerFactory = (context: TransformationContext) => Transformer; + /** + * A function that transforms a node. + */ + type Transformer = (node: T) => T; + /** + * A function that accepts and possibly transforms a node. + */ + type Visitor = (node: Node) => VisitResult; + type VisitResult = T | T[] | undefined; + interface Printer { + /** + * Print a node and its subtree as-is, without any emit transformations. + * @param hint A value indicating the purpose of a node. This is primarily used to + * distinguish between an `Identifier` used in an expression position, versus an + * `Identifier` used as an `IdentifierName` as part of a declaration. For most nodes you + * should just pass `Unspecified`. + * @param node The node to print. The node and its subtree are printed as-is, without any + * emit transformations. + * @param sourceFile A source file that provides context for the node. The source text of + * the file is used to emit the original source content for literals and identifiers, while + * the identifiers of the source file are used when generating unique names to avoid + * collisions. + */ + printNode(hint: EmitHint, node: Node, sourceFile: SourceFile): string; + /** + * Prints a list of nodes using the given format flags + */ + printList(format: ListFormat, list: NodeArray, sourceFile: SourceFile): string; + /** + * Prints a source file as-is, without any emit transformations. + */ + printFile(sourceFile: SourceFile): string; + /** + * Prints a bundle of source files as-is, without any emit transformations. + */ + printBundle(bundle: Bundle): string; + } + interface PrintHandlers { + /** + * A hook used by the Printer when generating unique names to avoid collisions with + * globally defined names that exist outside of the current source file. + */ + hasGlobalName?(name: string): boolean; + /** + * A hook used by the Printer to provide notifications prior to emitting a node. A + * compatible implementation **must** invoke `emitCallback` with the provided `hint` and + * `node` values. + * @param hint A hint indicating the intended purpose of the node. + * @param node The node to emit. + * @param emitCallback A callback that, when invoked, will emit the node. + * @example + * ```ts + * var printer = createPrinter(printerOptions, { + * onEmitNode(hint, node, emitCallback) { + * // set up or track state prior to emitting the node... + * emitCallback(hint, node); + * // restore state after emitting the node... + * } + * }); + * ``` + */ + onEmitNode?(hint: EmitHint, node: Node | undefined, emitCallback: (hint: EmitHint, node: Node | undefined) => void): void; + /** + * A hook used by the Printer to perform just-in-time substitution of a node. This is + * primarily used by node transformations that need to substitute one node for another, + * such as replacing `myExportedVar` with `exports.myExportedVar`. + * @param hint A hint indicating the intended purpose of the node. + * @param node The node to emit. + * @example + * ```ts + * var printer = createPrinter(printerOptions, { + * substituteNode(hint, node) { + * // perform substitution if necessary... + * return node; + * } + * }); + * ``` + */ + substituteNode?(hint: EmitHint, node: Node): Node; + } + interface PrinterOptions { + removeComments?: boolean; + newLine?: NewLineKind; + omitTrailingSemicolon?: boolean; + noEmitHelpers?: boolean; + } + interface GetEffectiveTypeRootsHost { + directoryExists?(directoryName: string): boolean; + getCurrentDirectory?(): string; + } + interface TextSpan { + start: number; + length: number; + } + interface TextChangeRange { + span: TextSpan; + newLength: number; + } + interface SyntaxList extends Node { + _children: Node[]; + } + enum ListFormat { + None = 0, + SingleLine = 0, + MultiLine = 1, + PreserveLines = 2, + LinesMask = 3, + NotDelimited = 0, + BarDelimited = 4, + AmpersandDelimited = 8, + CommaDelimited = 16, + AsteriskDelimited = 32, + DelimitersMask = 60, + AllowTrailingComma = 64, + Indented = 128, + SpaceBetweenBraces = 256, + SpaceBetweenSiblings = 512, + Braces = 1024, + Parenthesis = 2048, + AngleBrackets = 4096, + SquareBrackets = 8192, + BracketsMask = 15360, + OptionalIfUndefined = 16384, + OptionalIfEmpty = 32768, + Optional = 49152, + PreferNewLine = 65536, + NoTrailingNewLine = 131072, + NoInterveningComments = 262144, + NoSpaceIfEmpty = 524288, + SingleElement = 1048576, + Modifiers = 262656, + HeritageClauses = 512, + SingleLineTypeLiteralMembers = 768, + MultiLineTypeLiteralMembers = 32897, + TupleTypeElements = 528, + UnionTypeConstituents = 516, + IntersectionTypeConstituents = 520, + ObjectBindingPatternElements = 525136, + ArrayBindingPatternElements = 524880, + ObjectLiteralExpressionProperties = 526226, + ArrayLiteralExpressionElements = 8914, + CommaListElements = 528, + CallExpressionArguments = 2576, + NewExpressionArguments = 18960, + TemplateExpressionSpans = 262144, + SingleLineBlockStatements = 768, + MultiLineBlockStatements = 129, + VariableDeclarationList = 528, + SingleLineFunctionBodyStatements = 768, + MultiLineFunctionBodyStatements = 1, + ClassHeritageClauses = 0, + ClassMembers = 129, + InterfaceMembers = 129, + EnumMembers = 145, + CaseBlockClauses = 129, + NamedImportsOrExportsElements = 525136, + JsxElementOrFragmentChildren = 262144, + JsxElementAttributes = 262656, + CaseOrDefaultClauseStatements = 163969, + HeritageClauseTypes = 528, + SourceFileStatements = 131073, + Decorators = 49153, + TypeArguments = 53776, + TypeParameters = 53776, + Parameters = 2576, + IndexSignatureParameters = 8848, + JSDocComment = 33 + } + interface UserPreferences { + readonly disableSuggestions?: boolean; + readonly quotePreference?: "double" | "single"; + readonly includeCompletionsForModuleExports?: boolean; + readonly includeCompletionsWithInsertText?: boolean; + readonly importModuleSpecifierPreference?: "relative" | "non-relative"; + /** Determines whether we import `foo/index.ts` as "foo", "foo/index", or "foo/index.js" */ + readonly importModuleSpecifierEnding?: "minimal" | "index" | "js"; + readonly allowTextChangesInNewFiles?: boolean; + } + /** Represents a bigint literal value without requiring bigint support */ + interface PseudoBigInt { + negative: boolean; + base10Value: string; + } +} +declare function setTimeout(handler: (...args: any[]) => void, timeout: number): any; +declare function clearTimeout(handle: any): void; +declare namespace ts { + enum FileWatcherEventKind { + Created = 0, + Changed = 1, + Deleted = 2 + } + type FileWatcherCallback = (fileName: string, eventKind: FileWatcherEventKind) => void; + type DirectoryWatcherCallback = (fileName: string) => void; + interface System { + args: string[]; + newLine: string; + useCaseSensitiveFileNames: boolean; + write(s: string): void; + writeOutputIsTTY?(): boolean; + readFile(path: string, encoding?: string): string | undefined; + getFileSize?(path: string): number; + writeFile(path: string, data: string, writeByteOrderMark?: boolean): void; + /** + * @pollingInterval - this parameter is used in polling-based watchers and ignored in watchers that + * use native OS file watching + */ + watchFile?(path: string, callback: FileWatcherCallback, pollingInterval?: number): FileWatcher; + watchDirectory?(path: string, callback: DirectoryWatcherCallback, recursive?: boolean): FileWatcher; + resolvePath(path: string): string; + fileExists(path: string): boolean; + directoryExists(path: string): boolean; + createDirectory(path: string): void; + getExecutingFilePath(): string; + getCurrentDirectory(): string; + getDirectories(path: string): string[]; + readDirectory(path: string, extensions?: ReadonlyArray, exclude?: ReadonlyArray, include?: ReadonlyArray, depth?: number): string[]; + getModifiedTime?(path: string): Date | undefined; + setModifiedTime?(path: string, time: Date): void; + deleteFile?(path: string): void; + /** + * A good implementation is node.js' `crypto.createHash`. (https://nodejs.org/api/crypto.html#crypto_crypto_createhash_algorithm) + */ + createHash?(data: string): string; + /** This must be cryptographically secure. Only implement this method using `crypto.createHash("sha256")`. */ + createSHA256Hash?(data: string): string; + getMemoryUsage?(): number; + exit(exitCode?: number): void; + realpath?(path: string): string; + setTimeout?(callback: (...args: any[]) => void, ms: number, ...args: any[]): any; + clearTimeout?(timeoutId: any): void; + clearScreen?(): void; + base64decode?(input: string): string; + base64encode?(input: string): string; + } + interface FileWatcher { + close(): void; + } + function getNodeMajorVersion(): number | undefined; + let sys: System; +} +declare namespace ts { + type ErrorCallback = (message: DiagnosticMessage, length: number) => void; + interface Scanner { + getStartPos(): number; + getToken(): SyntaxKind; + getTextPos(): number; + getTokenPos(): number; + getTokenText(): string; + getTokenValue(): string; + hasExtendedUnicodeEscape(): boolean; + hasPrecedingLineBreak(): boolean; + isIdentifier(): boolean; + isReservedWord(): boolean; + isUnterminated(): boolean; + reScanGreaterToken(): SyntaxKind; + reScanSlashToken(): SyntaxKind; + reScanTemplateToken(): SyntaxKind; + scanJsxIdentifier(): SyntaxKind; + scanJsxAttributeValue(): SyntaxKind; + reScanJsxToken(): JsxTokenSyntaxKind; + scanJsxToken(): JsxTokenSyntaxKind; + scanJSDocToken(): JsDocSyntaxKind; + scan(): SyntaxKind; + getText(): string; + setText(text: string | undefined, start?: number, length?: number): void; + setOnError(onError: ErrorCallback | undefined): void; + setScriptTarget(scriptTarget: ScriptTarget): void; + setLanguageVariant(variant: LanguageVariant): void; + setTextPos(textPos: number): void; + lookAhead(callback: () => T): T; + scanRange(start: number, length: number, callback: () => T): T; + tryScan(callback: () => T): T; + } + function tokenToString(t: SyntaxKind): string | undefined; + function getPositionOfLineAndCharacter(sourceFile: SourceFileLike, line: number, character: number): number; + function getLineAndCharacterOfPosition(sourceFile: SourceFileLike, position: number): LineAndCharacter; + function isWhiteSpaceLike(ch: number): boolean; + /** Does not include line breaks. For that, see isWhiteSpaceLike. */ + function isWhiteSpaceSingleLine(ch: number): boolean; + function isLineBreak(ch: number): boolean; + function couldStartTrivia(text: string, pos: number): boolean; + function forEachLeadingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean) => U): U | undefined; + function forEachLeadingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T) => U, state: T): U | undefined; + function forEachTrailingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean) => U): U | undefined; + function forEachTrailingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T) => U, state: T): U | undefined; + function reduceEachLeadingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T, memo: U) => U, state: T, initial: U): U | undefined; + function reduceEachTrailingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T, memo: U) => U, state: T, initial: U): U | undefined; + function getLeadingCommentRanges(text: string, pos: number): CommentRange[] | undefined; + function getTrailingCommentRanges(text: string, pos: number): CommentRange[] | undefined; + /** Optionally, get the shebang */ + function getShebang(text: string): string | undefined; + function isIdentifierStart(ch: number, languageVersion: ScriptTarget | undefined): boolean; + function isIdentifierPart(ch: number, languageVersion: ScriptTarget | undefined): boolean; + function createScanner(languageVersion: ScriptTarget, skipTrivia: boolean, languageVariant?: LanguageVariant, textInitial?: string, onError?: ErrorCallback, start?: number, length?: number): Scanner; +} +declare namespace ts { + function isExternalModuleNameRelative(moduleName: string): boolean; + function sortAndDeduplicateDiagnostics(diagnostics: ReadonlyArray): SortedReadonlyArray; +} +declare namespace ts { + function getDefaultLibFileName(options: CompilerOptions): string; + function textSpanEnd(span: TextSpan): number; + function textSpanIsEmpty(span: TextSpan): boolean; + function textSpanContainsPosition(span: TextSpan, position: number): boolean; + function textSpanContainsTextSpan(span: TextSpan, other: TextSpan): boolean; + function textSpanOverlapsWith(span: TextSpan, other: TextSpan): boolean; + function textSpanOverlap(span1: TextSpan, span2: TextSpan): TextSpan | undefined; + function textSpanIntersectsWithTextSpan(span: TextSpan, other: TextSpan): boolean; + function textSpanIntersectsWith(span: TextSpan, start: number, length: number): boolean; + function decodedTextSpanIntersectsWith(start1: number, length1: number, start2: number, length2: number): boolean; + function textSpanIntersectsWithPosition(span: TextSpan, position: number): boolean; + function textSpanIntersection(span1: TextSpan, span2: TextSpan): TextSpan | undefined; + function createTextSpan(start: number, length: number): TextSpan; + function createTextSpanFromBounds(start: number, end: number): TextSpan; + function textChangeRangeNewSpan(range: TextChangeRange): TextSpan; + function textChangeRangeIsUnchanged(range: TextChangeRange): boolean; + function createTextChangeRange(span: TextSpan, newLength: number): TextChangeRange; + let unchangedTextChangeRange: TextChangeRange; + /** + * Called to merge all the changes that occurred across several versions of a script snapshot + * into a single change. i.e. if a user keeps making successive edits to a script we will + * have a text change from V1 to V2, V2 to V3, ..., Vn. + * + * This function will then merge those changes into a single change range valid between V1 and + * Vn. + */ + function collapseTextChangeRangesAcrossMultipleVersions(changes: ReadonlyArray): TextChangeRange; + function getTypeParameterOwner(d: Declaration): Declaration | undefined; + type ParameterPropertyDeclaration = ParameterDeclaration & { + parent: ConstructorDeclaration; + name: Identifier; + }; + function isParameterPropertyDeclaration(node: Node): node is ParameterPropertyDeclaration; + function isEmptyBindingPattern(node: BindingName): node is BindingPattern; + function isEmptyBindingElement(node: BindingElement): boolean; + function walkUpBindingElementsAndPatterns(binding: BindingElement): VariableDeclaration | ParameterDeclaration; + function getCombinedModifierFlags(node: Declaration): ModifierFlags; + function getCombinedNodeFlags(node: Node): NodeFlags; + /** + * Checks to see if the locale is in the appropriate format, + * and if it is, attempts to set the appropriate language. + */ + function validateLocaleAndSetLanguage(locale: string, sys: { + getExecutingFilePath(): string; + resolvePath(path: string): string; + fileExists(fileName: string): boolean; + readFile(fileName: string): string | undefined; + }, errors?: Push): void; + function getOriginalNode(node: Node): Node; + function getOriginalNode(node: Node, nodeTest: (node: Node) => node is T): T; + function getOriginalNode(node: Node | undefined): Node | undefined; + function getOriginalNode(node: Node | undefined, nodeTest: (node: Node | undefined) => node is T): T | undefined; + /** + * Gets a value indicating whether a node originated in the parse tree. + * + * @param node The node to test. + */ + function isParseTreeNode(node: Node): boolean; + /** + * Gets the original parse tree node for a node. + * + * @param node The original node. + * @returns The original parse tree node if found; otherwise, undefined. + */ + function getParseTreeNode(node: Node): Node; + /** + * Gets the original parse tree node for a node. + * + * @param node The original node. + * @param nodeTest A callback used to ensure the correct type of parse tree node is returned. + * @returns The original parse tree node if found; otherwise, undefined. + */ + function getParseTreeNode(node: Node | undefined, nodeTest?: (node: Node) => node is T): T | undefined; + /** Add an extra underscore to identifiers that start with two underscores to avoid issues with magic names like '__proto__' */ + function escapeLeadingUnderscores(identifier: string): __String; + /** + * Remove extra underscore from escaped identifier text content. + * + * @param identifier The escaped identifier text. + * @returns The unescaped identifier text. + */ + function unescapeLeadingUnderscores(identifier: __String): string; + function idText(identifier: Identifier): string; + function symbolName(symbol: Symbol): string; + function getNameOfJSDocTypedef(declaration: JSDocTypedefTag): Identifier | undefined; + function getNameOfDeclaration(declaration: Declaration | Expression): DeclarationName | undefined; + /** + * Gets the JSDoc parameter tags for the node if present. + * + * @remarks Returns any JSDoc param tag whose name matches the provided + * parameter, whether a param tag on a containing function + * expression, or a param tag on a variable declaration whose + * initializer is the containing function. The tags closest to the + * node are returned first, so in the previous example, the param + * tag on the containing function expression would be first. + * + * For binding patterns, parameter tags are matched by position. + */ + function getJSDocParameterTags(param: ParameterDeclaration): ReadonlyArray; + /** + * Gets the JSDoc type parameter tags for the node if present. + * + * @remarks Returns any JSDoc template tag whose names match the provided + * parameter, whether a template tag on a containing function + * expression, or a template tag on a variable declaration whose + * initializer is the containing function. The tags closest to the + * node are returned first, so in the previous example, the template + * tag on the containing function expression would be first. + */ + function getJSDocTypeParameterTags(param: TypeParameterDeclaration): ReadonlyArray; + /** + * Return true if the node has JSDoc parameter tags. + * + * @remarks Includes parameter tags that are not directly on the node, + * for example on a variable declaration whose initializer is a function expression. + */ + function hasJSDocParameterTags(node: FunctionLikeDeclaration | SignatureDeclaration): boolean; + /** Gets the JSDoc augments tag for the node if present */ + function getJSDocAugmentsTag(node: Node): JSDocAugmentsTag | undefined; + /** Gets the JSDoc class tag for the node if present */ + function getJSDocClassTag(node: Node): JSDocClassTag | undefined; + /** Gets the JSDoc enum tag for the node if present */ + function getJSDocEnumTag(node: Node): JSDocEnumTag | undefined; + /** Gets the JSDoc this tag for the node if present */ + function getJSDocThisTag(node: Node): JSDocThisTag | undefined; + /** Gets the JSDoc return tag for the node if present */ + function getJSDocReturnTag(node: Node): JSDocReturnTag | undefined; + /** Gets the JSDoc template tag for the node if present */ + function getJSDocTemplateTag(node: Node): JSDocTemplateTag | undefined; + /** Gets the JSDoc type tag for the node if present and valid */ + function getJSDocTypeTag(node: Node): JSDocTypeTag | undefined; + /** + * Gets the type node for the node if provided via JSDoc. + * + * @remarks The search includes any JSDoc param tag that relates + * to the provided parameter, for example a type tag on the + * parameter itself, or a param tag on a containing function + * expression, or a param tag on a variable declaration whose + * initializer is the containing function. The tags closest to the + * node are examined first, so in the previous example, the type + * tag directly on the node would be returned. + */ + function getJSDocType(node: Node): TypeNode | undefined; + /** + * Gets the return type node for the node if provided via JSDoc return tag or type tag. + * + * @remarks `getJSDocReturnTag` just gets the whole JSDoc tag. This function + * gets the type from inside the braces, after the fat arrow, etc. + */ + function getJSDocReturnType(node: Node): TypeNode | undefined; + /** Get all JSDoc tags related to a node, including those on parent nodes. */ + function getJSDocTags(node: Node): ReadonlyArray; + /** Gets all JSDoc tags of a specified kind, or undefined if not present. */ + function getAllJSDocTagsOfKind(node: Node, kind: SyntaxKind): ReadonlyArray; + /** + * Gets the effective type parameters. If the node was parsed in a + * JavaScript file, gets the type parameters from the `@template` tag from JSDoc. + */ + function getEffectiveTypeParameterDeclarations(node: DeclarationWithTypeParameters): ReadonlyArray; + function getEffectiveConstraintOfTypeParameter(node: TypeParameterDeclaration): TypeNode | undefined; +} +declare namespace ts { + function isNumericLiteral(node: Node): node is NumericLiteral; + function isBigIntLiteral(node: Node): node is BigIntLiteral; + function isStringLiteral(node: Node): node is StringLiteral; + function isJsxText(node: Node): node is JsxText; + function isRegularExpressionLiteral(node: Node): node is RegularExpressionLiteral; + function isNoSubstitutionTemplateLiteral(node: Node): node is NoSubstitutionTemplateLiteral; + function isTemplateHead(node: Node): node is TemplateHead; + function isTemplateMiddle(node: Node): node is TemplateMiddle; + function isTemplateTail(node: Node): node is TemplateTail; + function isIdentifier(node: Node): node is Identifier; + function isQualifiedName(node: Node): node is QualifiedName; + function isComputedPropertyName(node: Node): node is ComputedPropertyName; + function isTypeParameterDeclaration(node: Node): node is TypeParameterDeclaration; + function isParameter(node: Node): node is ParameterDeclaration; + function isDecorator(node: Node): node is Decorator; + function isPropertySignature(node: Node): node is PropertySignature; + function isPropertyDeclaration(node: Node): node is PropertyDeclaration; + function isMethodSignature(node: Node): node is MethodSignature; + function isMethodDeclaration(node: Node): node is MethodDeclaration; + function isConstructorDeclaration(node: Node): node is ConstructorDeclaration; + function isGetAccessorDeclaration(node: Node): node is GetAccessorDeclaration; + function isSetAccessorDeclaration(node: Node): node is SetAccessorDeclaration; + function isCallSignatureDeclaration(node: Node): node is CallSignatureDeclaration; + function isConstructSignatureDeclaration(node: Node): node is ConstructSignatureDeclaration; + function isIndexSignatureDeclaration(node: Node): node is IndexSignatureDeclaration; + function isTypePredicateNode(node: Node): node is TypePredicateNode; + function isTypeReferenceNode(node: Node): node is TypeReferenceNode; + function isFunctionTypeNode(node: Node): node is FunctionTypeNode; + function isConstructorTypeNode(node: Node): node is ConstructorTypeNode; + function isTypeQueryNode(node: Node): node is TypeQueryNode; + function isTypeLiteralNode(node: Node): node is TypeLiteralNode; + function isArrayTypeNode(node: Node): node is ArrayTypeNode; + function isTupleTypeNode(node: Node): node is TupleTypeNode; + function isUnionTypeNode(node: Node): node is UnionTypeNode; + function isIntersectionTypeNode(node: Node): node is IntersectionTypeNode; + function isConditionalTypeNode(node: Node): node is ConditionalTypeNode; + function isInferTypeNode(node: Node): node is InferTypeNode; + function isParenthesizedTypeNode(node: Node): node is ParenthesizedTypeNode; + function isThisTypeNode(node: Node): node is ThisTypeNode; + function isTypeOperatorNode(node: Node): node is TypeOperatorNode; + function isIndexedAccessTypeNode(node: Node): node is IndexedAccessTypeNode; + function isMappedTypeNode(node: Node): node is MappedTypeNode; + function isLiteralTypeNode(node: Node): node is LiteralTypeNode; + function isImportTypeNode(node: Node): node is ImportTypeNode; + function isObjectBindingPattern(node: Node): node is ObjectBindingPattern; + function isArrayBindingPattern(node: Node): node is ArrayBindingPattern; + function isBindingElement(node: Node): node is BindingElement; + function isArrayLiteralExpression(node: Node): node is ArrayLiteralExpression; + function isObjectLiteralExpression(node: Node): node is ObjectLiteralExpression; + function isPropertyAccessExpression(node: Node): node is PropertyAccessExpression; + function isElementAccessExpression(node: Node): node is ElementAccessExpression; + function isCallExpression(node: Node): node is CallExpression; + function isNewExpression(node: Node): node is NewExpression; + function isTaggedTemplateExpression(node: Node): node is TaggedTemplateExpression; + function isTypeAssertion(node: Node): node is TypeAssertion; + function isParenthesizedExpression(node: Node): node is ParenthesizedExpression; + function skipPartiallyEmittedExpressions(node: Expression): Expression; + function skipPartiallyEmittedExpressions(node: Node): Node; + function isFunctionExpression(node: Node): node is FunctionExpression; + function isArrowFunction(node: Node): node is ArrowFunction; + function isDeleteExpression(node: Node): node is DeleteExpression; + function isTypeOfExpression(node: Node): node is TypeOfExpression; + function isVoidExpression(node: Node): node is VoidExpression; + function isAwaitExpression(node: Node): node is AwaitExpression; + function isPrefixUnaryExpression(node: Node): node is PrefixUnaryExpression; + function isPostfixUnaryExpression(node: Node): node is PostfixUnaryExpression; + function isBinaryExpression(node: Node): node is BinaryExpression; + function isConditionalExpression(node: Node): node is ConditionalExpression; + function isTemplateExpression(node: Node): node is TemplateExpression; + function isYieldExpression(node: Node): node is YieldExpression; + function isSpreadElement(node: Node): node is SpreadElement; + function isClassExpression(node: Node): node is ClassExpression; + function isOmittedExpression(node: Node): node is OmittedExpression; + function isExpressionWithTypeArguments(node: Node): node is ExpressionWithTypeArguments; + function isAsExpression(node: Node): node is AsExpression; + function isNonNullExpression(node: Node): node is NonNullExpression; + function isMetaProperty(node: Node): node is MetaProperty; + function isTemplateSpan(node: Node): node is TemplateSpan; + function isSemicolonClassElement(node: Node): node is SemicolonClassElement; + function isBlock(node: Node): node is Block; + function isVariableStatement(node: Node): node is VariableStatement; + function isEmptyStatement(node: Node): node is EmptyStatement; + function isExpressionStatement(node: Node): node is ExpressionStatement; + function isIfStatement(node: Node): node is IfStatement; + function isDoStatement(node: Node): node is DoStatement; + function isWhileStatement(node: Node): node is WhileStatement; + function isForStatement(node: Node): node is ForStatement; + function isForInStatement(node: Node): node is ForInStatement; + function isForOfStatement(node: Node): node is ForOfStatement; + function isContinueStatement(node: Node): node is ContinueStatement; + function isBreakStatement(node: Node): node is BreakStatement; + function isBreakOrContinueStatement(node: Node): node is BreakOrContinueStatement; + function isReturnStatement(node: Node): node is ReturnStatement; + function isWithStatement(node: Node): node is WithStatement; + function isSwitchStatement(node: Node): node is SwitchStatement; + function isLabeledStatement(node: Node): node is LabeledStatement; + function isThrowStatement(node: Node): node is ThrowStatement; + function isTryStatement(node: Node): node is TryStatement; + function isDebuggerStatement(node: Node): node is DebuggerStatement; + function isVariableDeclaration(node: Node): node is VariableDeclaration; + function isVariableDeclarationList(node: Node): node is VariableDeclarationList; + function isFunctionDeclaration(node: Node): node is FunctionDeclaration; + function isClassDeclaration(node: Node): node is ClassDeclaration; + function isInterfaceDeclaration(node: Node): node is InterfaceDeclaration; + function isTypeAliasDeclaration(node: Node): node is TypeAliasDeclaration; + function isEnumDeclaration(node: Node): node is EnumDeclaration; + function isModuleDeclaration(node: Node): node is ModuleDeclaration; + function isModuleBlock(node: Node): node is ModuleBlock; + function isCaseBlock(node: Node): node is CaseBlock; + function isNamespaceExportDeclaration(node: Node): node is NamespaceExportDeclaration; + function isImportEqualsDeclaration(node: Node): node is ImportEqualsDeclaration; + function isImportDeclaration(node: Node): node is ImportDeclaration; + function isImportClause(node: Node): node is ImportClause; + function isNamespaceImport(node: Node): node is NamespaceImport; + function isNamedImports(node: Node): node is NamedImports; + function isImportSpecifier(node: Node): node is ImportSpecifier; + function isExportAssignment(node: Node): node is ExportAssignment; + function isExportDeclaration(node: Node): node is ExportDeclaration; + function isNamedExports(node: Node): node is NamedExports; + function isExportSpecifier(node: Node): node is ExportSpecifier; + function isMissingDeclaration(node: Node): node is MissingDeclaration; + function isExternalModuleReference(node: Node): node is ExternalModuleReference; + function isJsxElement(node: Node): node is JsxElement; + function isJsxSelfClosingElement(node: Node): node is JsxSelfClosingElement; + function isJsxOpeningElement(node: Node): node is JsxOpeningElement; + function isJsxClosingElement(node: Node): node is JsxClosingElement; + function isJsxFragment(node: Node): node is JsxFragment; + function isJsxOpeningFragment(node: Node): node is JsxOpeningFragment; + function isJsxClosingFragment(node: Node): node is JsxClosingFragment; + function isJsxAttribute(node: Node): node is JsxAttribute; + function isJsxAttributes(node: Node): node is JsxAttributes; + function isJsxSpreadAttribute(node: Node): node is JsxSpreadAttribute; + function isJsxExpression(node: Node): node is JsxExpression; + function isCaseClause(node: Node): node is CaseClause; + function isDefaultClause(node: Node): node is DefaultClause; + function isHeritageClause(node: Node): node is HeritageClause; + function isCatchClause(node: Node): node is CatchClause; + function isPropertyAssignment(node: Node): node is PropertyAssignment; + function isShorthandPropertyAssignment(node: Node): node is ShorthandPropertyAssignment; + function isSpreadAssignment(node: Node): node is SpreadAssignment; + function isEnumMember(node: Node): node is EnumMember; + function isSourceFile(node: Node): node is SourceFile; + function isBundle(node: Node): node is Bundle; + function isUnparsedSource(node: Node): node is UnparsedSource; + function isJSDocTypeExpression(node: Node): node is JSDocTypeExpression; + function isJSDocAllType(node: JSDocAllType): node is JSDocAllType; + function isJSDocUnknownType(node: Node): node is JSDocUnknownType; + function isJSDocNullableType(node: Node): node is JSDocNullableType; + function isJSDocNonNullableType(node: Node): node is JSDocNonNullableType; + function isJSDocOptionalType(node: Node): node is JSDocOptionalType; + function isJSDocFunctionType(node: Node): node is JSDocFunctionType; + function isJSDocVariadicType(node: Node): node is JSDocVariadicType; + function isJSDoc(node: Node): node is JSDoc; + function isJSDocAugmentsTag(node: Node): node is JSDocAugmentsTag; + function isJSDocClassTag(node: Node): node is JSDocClassTag; + function isJSDocEnumTag(node: Node): node is JSDocEnumTag; + function isJSDocThisTag(node: Node): node is JSDocThisTag; + function isJSDocParameterTag(node: Node): node is JSDocParameterTag; + function isJSDocReturnTag(node: Node): node is JSDocReturnTag; + function isJSDocTypeTag(node: Node): node is JSDocTypeTag; + function isJSDocTemplateTag(node: Node): node is JSDocTemplateTag; + function isJSDocTypedefTag(node: Node): node is JSDocTypedefTag; + function isJSDocPropertyTag(node: Node): node is JSDocPropertyTag; + function isJSDocPropertyLikeTag(node: Node): node is JSDocPropertyLikeTag; + function isJSDocTypeLiteral(node: Node): node is JSDocTypeLiteral; + function isJSDocCallbackTag(node: Node): node is JSDocCallbackTag; + function isJSDocSignature(node: Node): node is JSDocSignature; +} +declare namespace ts { + /** + * True if node is of some token syntax kind. + * For example, this is true for an IfKeyword but not for an IfStatement. + * Literals are considered tokens, except TemplateLiteral, but does include TemplateHead/Middle/Tail. + */ + function isToken(n: Node): boolean; + function isLiteralExpression(node: Node): node is LiteralExpression; + type TemplateLiteralToken = NoSubstitutionTemplateLiteral | TemplateHead | TemplateMiddle | TemplateTail; + function isTemplateLiteralToken(node: Node): node is TemplateLiteralToken; + function isTemplateMiddleOrTemplateTail(node: Node): node is TemplateMiddle | TemplateTail; + function isImportOrExportSpecifier(node: Node): node is ImportSpecifier | ExportSpecifier; + function isStringTextContainingNode(node: Node): node is StringLiteral | TemplateLiteralToken; + function isModifier(node: Node): node is Modifier; + function isEntityName(node: Node): node is EntityName; + function isPropertyName(node: Node): node is PropertyName; + function isBindingName(node: Node): node is BindingName; + function isFunctionLike(node: Node): node is SignatureDeclaration; + function isClassElement(node: Node): node is ClassElement; + function isClassLike(node: Node): node is ClassLikeDeclaration; + function isAccessor(node: Node): node is AccessorDeclaration; + function isTypeElement(node: Node): node is TypeElement; + function isClassOrTypeElement(node: Node): node is ClassElement | TypeElement; + function isObjectLiteralElementLike(node: Node): node is ObjectLiteralElementLike; + /** + * Node test that determines whether a node is a valid type node. + * This differs from the `isPartOfTypeNode` function which determines whether a node is *part* + * of a TypeNode. + */ + function isTypeNode(node: Node): node is TypeNode; + function isFunctionOrConstructorTypeNode(node: Node): node is FunctionTypeNode | ConstructorTypeNode; + function isPropertyAccessOrQualifiedName(node: Node): node is PropertyAccessExpression | QualifiedName; + function isCallLikeExpression(node: Node): node is CallLikeExpression; + function isCallOrNewExpression(node: Node): node is CallExpression | NewExpression; + function isTemplateLiteral(node: Node): node is TemplateLiteral; + function isAssertionExpression(node: Node): node is AssertionExpression; + function isIterationStatement(node: Node, lookInLabeledStatements: false): node is IterationStatement; + function isIterationStatement(node: Node, lookInLabeledStatements: boolean): node is IterationStatement | LabeledStatement; + function isJsxOpeningLikeElement(node: Node): node is JsxOpeningLikeElement; + function isCaseOrDefaultClause(node: Node): node is CaseOrDefaultClause; + /** True if node is of a kind that may contain comment text. */ + function isJSDocCommentContainingNode(node: Node): boolean; + function isSetAccessor(node: Node): node is SetAccessorDeclaration; + function isGetAccessor(node: Node): node is GetAccessorDeclaration; + function isObjectLiteralElement(node: Node): node is ObjectLiteralElement; + function isStringLiteralLike(node: Node): node is StringLiteralLike; +} +declare namespace ts { + function createNode(kind: SyntaxKind, pos?: number, end?: number): Node; + /** + * Invokes a callback for each child of the given node. The 'cbNode' callback is invoked for all child nodes + * stored in properties. If a 'cbNodes' callback is specified, it is invoked for embedded arrays; otherwise, + * embedded arrays are flattened and the 'cbNode' callback is invoked for each element. If a callback returns + * a truthy value, iteration stops and that value is returned. Otherwise, undefined is returned. + * + * @param node a given node to visit its children + * @param cbNode a callback to be invoked for all child nodes + * @param cbNodes a callback to be invoked for embedded array + * + * @remarks `forEachChild` must visit the children of a node in the order + * that they appear in the source code. The language service depends on this property to locate nodes by position. + */ + function forEachChild(node: Node, cbNode: (node: Node) => T | undefined, cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined; + function createSourceFile(fileName: string, sourceText: string, languageVersion: ScriptTarget, setParentNodes?: boolean, scriptKind?: ScriptKind): SourceFile; + function parseIsolatedEntityName(text: string, languageVersion: ScriptTarget): EntityName | undefined; + /** + * Parse json text into SyntaxTree and return node and parse errors if any + * @param fileName + * @param sourceText + */ + function parseJsonText(fileName: string, sourceText: string): JsonSourceFile; + function isExternalModule(file: SourceFile): boolean; + function updateSourceFile(sourceFile: SourceFile, newText: string, textChangeRange: TextChangeRange, aggressiveChecks?: boolean): SourceFile; +} +declare namespace ts { + function parseCommandLine(commandLine: ReadonlyArray, readFile?: (path: string) => string | undefined): ParsedCommandLine; + type DiagnosticReporter = (diagnostic: Diagnostic) => void; + /** + * Reports config file diagnostics + */ + interface ConfigFileDiagnosticsReporter { + /** + * Reports unrecoverable error when parsing config file + */ + onUnRecoverableConfigFileDiagnostic: DiagnosticReporter; + } + /** + * Interface extending ParseConfigHost to support ParseConfigFile that reads config file and reports errors + */ + interface ParseConfigFileHost extends ParseConfigHost, ConfigFileDiagnosticsReporter { + getCurrentDirectory(): string; + } + /** + * Reads the config file, reports errors if any and exits if the config file cannot be found + */ + function getParsedCommandLineOfConfigFile(configFileName: string, optionsToExtend: CompilerOptions, host: ParseConfigFileHost): ParsedCommandLine | undefined; + /** + * Read tsconfig.json file + * @param fileName The path to the config file + */ + function readConfigFile(fileName: string, readFile: (path: string) => string | undefined): { + config?: any; + error?: Diagnostic; + }; + /** + * Parse the text of the tsconfig.json file + * @param fileName The path to the config file + * @param jsonText The text of the config file + */ + function parseConfigFileTextToJson(fileName: string, jsonText: string): { + config?: any; + error?: Diagnostic; + }; + /** + * Read tsconfig.json file + * @param fileName The path to the config file + */ + function readJsonConfigFile(fileName: string, readFile: (path: string) => string | undefined): TsConfigSourceFile; + /** + * Convert the json syntax tree into the json value + */ + function convertToObject(sourceFile: JsonSourceFile, errors: Push): any; + /** + * Parse the contents of a config file (tsconfig.json). + * @param json The contents of the config file to parse + * @param host Instance of ParseConfigHost used to enumerate files in folder. + * @param basePath A root directory to resolve relative path entries in the config + * file to. e.g. outDir + */ + function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[], extraFileExtensions?: ReadonlyArray): ParsedCommandLine; + /** + * Parse the contents of a config file (tsconfig.json). + * @param jsonNode The contents of the config file to parse + * @param host Instance of ParseConfigHost used to enumerate files in folder. + * @param basePath A root directory to resolve relative path entries in the config + * file to. e.g. outDir + */ + function parseJsonSourceFileConfigFileContent(sourceFile: TsConfigSourceFile, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[], extraFileExtensions?: ReadonlyArray): ParsedCommandLine; + function convertCompilerOptionsFromJson(jsonOptions: any, basePath: string, configFileName?: string): { + options: CompilerOptions; + errors: Diagnostic[]; + }; + function convertTypeAcquisitionFromJson(jsonOptions: any, basePath: string, configFileName?: string): { + options: TypeAcquisition; + errors: Diagnostic[]; + }; +} +declare namespace ts { + function getEffectiveTypeRoots(options: CompilerOptions, host: GetEffectiveTypeRootsHost): string[] | undefined; + /** + * @param {string | undefined} containingFile - file that contains type reference directive, can be undefined if containing file is unknown. + * This is possible in case if resolution is performed for directives specified via 'types' parameter. In this case initial path for secondary lookups + * is assumed to be the same as root directory of the project. + */ + function resolveTypeReferenceDirective(typeReferenceDirectiveName: string, containingFile: string | undefined, options: CompilerOptions, host: ModuleResolutionHost, redirectedReference?: ResolvedProjectReference): ResolvedTypeReferenceDirectiveWithFailedLookupLocations; + /** + * Given a set of options, returns the set of type directive names + * that should be included for this program automatically. + * This list could either come from the config file, + * or from enumerating the types root + initial secondary types lookup location. + * More type directives might appear in the program later as a result of loading actual source files; + * this list is only the set of defaults that are implicitly included. + */ + function getAutomaticTypeDirectiveNames(options: CompilerOptions, host: ModuleResolutionHost): string[]; + /** + * Cached module resolutions per containing directory. + * This assumes that any module id will have the same resolution for sibling files located in the same folder. + */ + interface ModuleResolutionCache extends NonRelativeModuleNameResolutionCache { + getOrCreateCacheForDirectory(directoryName: string, redirectedReference?: ResolvedProjectReference): Map; + } + /** + * Stored map from non-relative module name to a table: directory -> result of module lookup in this directory + * We support only non-relative module names because resolution of relative module names is usually more deterministic and thus less expensive. + */ + interface NonRelativeModuleNameResolutionCache { + getOrCreateCacheForModuleName(nonRelativeModuleName: string, redirectedReference?: ResolvedProjectReference): PerModuleNameCache; + } + interface PerModuleNameCache { + get(directory: string): ResolvedModuleWithFailedLookupLocations | undefined; + set(directory: string, result: ResolvedModuleWithFailedLookupLocations): void; + } + function createModuleResolutionCache(currentDirectory: string, getCanonicalFileName: (s: string) => string): ModuleResolutionCache; + function resolveModuleNameFromCache(moduleName: string, containingFile: string, cache: ModuleResolutionCache): ResolvedModuleWithFailedLookupLocations | undefined; + function resolveModuleName(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: ModuleResolutionCache, redirectedReference?: ResolvedProjectReference): ResolvedModuleWithFailedLookupLocations; + function nodeModuleNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: ModuleResolutionCache, redirectedReference?: ResolvedProjectReference): ResolvedModuleWithFailedLookupLocations; + function classicNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: NonRelativeModuleNameResolutionCache, redirectedReference?: ResolvedProjectReference): ResolvedModuleWithFailedLookupLocations; +} +declare namespace ts { + function createNodeArray(elements?: ReadonlyArray, hasTrailingComma?: boolean): NodeArray; + /** If a node is passed, creates a string literal whose source text is read from a source node during emit. */ + function createLiteral(value: string | StringLiteral | NoSubstitutionTemplateLiteral | NumericLiteral | Identifier): StringLiteral; + function createLiteral(value: number | PseudoBigInt): NumericLiteral; + function createLiteral(value: boolean): BooleanLiteral; + function createLiteral(value: string | number | PseudoBigInt | boolean): PrimaryExpression; + function createNumericLiteral(value: string): NumericLiteral; + function createBigIntLiteral(value: string): BigIntLiteral; + function createStringLiteral(text: string): StringLiteral; + function createRegularExpressionLiteral(text: string): RegularExpressionLiteral; + function createIdentifier(text: string): Identifier; + function updateIdentifier(node: Identifier): Identifier; + /** Create a unique temporary variable. */ + function createTempVariable(recordTempVariable: ((node: Identifier) => void) | undefined): Identifier; + /** Create a unique temporary variable for use in a loop. */ + function createLoopVariable(): Identifier; + /** Create a unique name based on the supplied text. */ + function createUniqueName(text: string): Identifier; + /** Create a unique name based on the supplied text. */ + function createOptimisticUniqueName(text: string): Identifier; + /** Create a unique name based on the supplied text. This does not consider names injected by the transformer. */ + function createFileLevelUniqueName(text: string): Identifier; + /** Create a unique name generated for a node. */ + function getGeneratedNameForNode(node: Node | undefined): Identifier; + function createToken(token: TKind): Token; + function createSuper(): SuperExpression; + function createThis(): ThisExpression & Token; + function createNull(): NullLiteral & Token; + function createTrue(): BooleanLiteral & Token; + function createFalse(): BooleanLiteral & Token; + function createModifier(kind: T): Token; + function createModifiersFromModifierFlags(flags: ModifierFlags): Modifier[]; + function createQualifiedName(left: EntityName, right: string | Identifier): QualifiedName; + function updateQualifiedName(node: QualifiedName, left: EntityName, right: Identifier): QualifiedName; + function createComputedPropertyName(expression: Expression): ComputedPropertyName; + function updateComputedPropertyName(node: ComputedPropertyName, expression: Expression): ComputedPropertyName; + function createTypeParameterDeclaration(name: string | Identifier, constraint?: TypeNode, defaultType?: TypeNode): TypeParameterDeclaration; + function updateTypeParameterDeclaration(node: TypeParameterDeclaration, name: Identifier, constraint: TypeNode | undefined, defaultType: TypeNode | undefined): TypeParameterDeclaration; + function createParameter(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, dotDotDotToken: DotDotDotToken | undefined, name: string | BindingName, questionToken?: QuestionToken, type?: TypeNode, initializer?: Expression): ParameterDeclaration; + function updateParameter(node: ParameterDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, dotDotDotToken: DotDotDotToken | undefined, name: string | BindingName, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): ParameterDeclaration; + function createDecorator(expression: Expression): Decorator; + function updateDecorator(node: Decorator, expression: Expression): Decorator; + function createPropertySignature(modifiers: ReadonlyArray | undefined, name: PropertyName | string, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): PropertySignature; + function updatePropertySignature(node: PropertySignature, modifiers: ReadonlyArray | undefined, name: PropertyName, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): PropertySignature; + function createProperty(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: string | PropertyName, questionOrExclamationToken: QuestionToken | ExclamationToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): PropertyDeclaration; + function updateProperty(node: PropertyDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: string | PropertyName, questionOrExclamationToken: QuestionToken | ExclamationToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): PropertyDeclaration; + function createMethodSignature(typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined): MethodSignature; + function updateMethodSignature(node: MethodSignature, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined, name: PropertyName, questionToken: QuestionToken | undefined): MethodSignature; + function createMethod(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, asteriskToken: AsteriskToken | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined, typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode | undefined, body: Block | undefined): MethodDeclaration; + function updateMethod(node: MethodDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, asteriskToken: AsteriskToken | undefined, name: PropertyName, questionToken: QuestionToken | undefined, typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode | undefined, body: Block | undefined): MethodDeclaration; + function createConstructor(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, parameters: ReadonlyArray, body: Block | undefined): ConstructorDeclaration; + function updateConstructor(node: ConstructorDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, parameters: ReadonlyArray, body: Block | undefined): ConstructorDeclaration; + function createGetAccessor(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: string | PropertyName, parameters: ReadonlyArray, type: TypeNode | undefined, body: Block | undefined): GetAccessorDeclaration; + function updateGetAccessor(node: GetAccessorDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: PropertyName, parameters: ReadonlyArray, type: TypeNode | undefined, body: Block | undefined): GetAccessorDeclaration; + function createSetAccessor(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: string | PropertyName, parameters: ReadonlyArray, body: Block | undefined): SetAccessorDeclaration; + function updateSetAccessor(node: SetAccessorDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: PropertyName, parameters: ReadonlyArray, body: Block | undefined): SetAccessorDeclaration; + function createCallSignature(typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode | undefined): CallSignatureDeclaration; + function updateCallSignature(node: CallSignatureDeclaration, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined): CallSignatureDeclaration; + function createConstructSignature(typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode | undefined): ConstructSignatureDeclaration; + function updateConstructSignature(node: ConstructSignatureDeclaration, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined): ConstructSignatureDeclaration; + function createIndexSignature(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode): IndexSignatureDeclaration; + function updateIndexSignature(node: IndexSignatureDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode): IndexSignatureDeclaration; + function createKeywordTypeNode(kind: KeywordTypeNode["kind"]): KeywordTypeNode; + function createTypePredicateNode(parameterName: Identifier | ThisTypeNode | string, type: TypeNode): TypePredicateNode; + function updateTypePredicateNode(node: TypePredicateNode, parameterName: Identifier | ThisTypeNode, type: TypeNode): TypePredicateNode; + function createTypeReferenceNode(typeName: string | EntityName, typeArguments: ReadonlyArray | undefined): TypeReferenceNode; + function updateTypeReferenceNode(node: TypeReferenceNode, typeName: EntityName, typeArguments: NodeArray | undefined): TypeReferenceNode; + function createFunctionTypeNode(typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode | undefined): FunctionTypeNode; + function updateFunctionTypeNode(node: FunctionTypeNode, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined): FunctionTypeNode; + function createConstructorTypeNode(typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode | undefined): ConstructorTypeNode; + function updateConstructorTypeNode(node: ConstructorTypeNode, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined): ConstructorTypeNode; + function createTypeQueryNode(exprName: EntityName): TypeQueryNode; + function updateTypeQueryNode(node: TypeQueryNode, exprName: EntityName): TypeQueryNode; + function createTypeLiteralNode(members: ReadonlyArray | undefined): TypeLiteralNode; + function updateTypeLiteralNode(node: TypeLiteralNode, members: NodeArray): TypeLiteralNode; + function createArrayTypeNode(elementType: TypeNode): ArrayTypeNode; + function updateArrayTypeNode(node: ArrayTypeNode, elementType: TypeNode): ArrayTypeNode; + function createTupleTypeNode(elementTypes: ReadonlyArray): TupleTypeNode; + function updateTupleTypeNode(node: TupleTypeNode, elementTypes: ReadonlyArray): TupleTypeNode; + function createOptionalTypeNode(type: TypeNode): OptionalTypeNode; + function updateOptionalTypeNode(node: OptionalTypeNode, type: TypeNode): OptionalTypeNode; + function createRestTypeNode(type: TypeNode): RestTypeNode; + function updateRestTypeNode(node: RestTypeNode, type: TypeNode): RestTypeNode; + function createUnionTypeNode(types: ReadonlyArray): UnionTypeNode; + function updateUnionTypeNode(node: UnionTypeNode, types: NodeArray): UnionTypeNode; + function createIntersectionTypeNode(types: ReadonlyArray): IntersectionTypeNode; + function updateIntersectionTypeNode(node: IntersectionTypeNode, types: NodeArray): IntersectionTypeNode; + function createUnionOrIntersectionTypeNode(kind: SyntaxKind.UnionType | SyntaxKind.IntersectionType, types: ReadonlyArray): UnionOrIntersectionTypeNode; + function createConditionalTypeNode(checkType: TypeNode, extendsType: TypeNode, trueType: TypeNode, falseType: TypeNode): ConditionalTypeNode; + function updateConditionalTypeNode(node: ConditionalTypeNode, checkType: TypeNode, extendsType: TypeNode, trueType: TypeNode, falseType: TypeNode): ConditionalTypeNode; + function createInferTypeNode(typeParameter: TypeParameterDeclaration): InferTypeNode; + function updateInferTypeNode(node: InferTypeNode, typeParameter: TypeParameterDeclaration): InferTypeNode; + function createImportTypeNode(argument: TypeNode, qualifier?: EntityName, typeArguments?: ReadonlyArray, isTypeOf?: boolean): ImportTypeNode; + function updateImportTypeNode(node: ImportTypeNode, argument: TypeNode, qualifier?: EntityName, typeArguments?: ReadonlyArray, isTypeOf?: boolean): ImportTypeNode; + function createParenthesizedType(type: TypeNode): ParenthesizedTypeNode; + function updateParenthesizedType(node: ParenthesizedTypeNode, type: TypeNode): ParenthesizedTypeNode; + function createThisTypeNode(): ThisTypeNode; + function createTypeOperatorNode(type: TypeNode): TypeOperatorNode; + function createTypeOperatorNode(operator: SyntaxKind.KeyOfKeyword | SyntaxKind.UniqueKeyword, type: TypeNode): TypeOperatorNode; + function updateTypeOperatorNode(node: TypeOperatorNode, type: TypeNode): TypeOperatorNode; + function createIndexedAccessTypeNode(objectType: TypeNode, indexType: TypeNode): IndexedAccessTypeNode; + function updateIndexedAccessTypeNode(node: IndexedAccessTypeNode, objectType: TypeNode, indexType: TypeNode): IndexedAccessTypeNode; + function createMappedTypeNode(readonlyToken: ReadonlyToken | PlusToken | MinusToken | undefined, typeParameter: TypeParameterDeclaration, questionToken: QuestionToken | PlusToken | MinusToken | undefined, type: TypeNode | undefined): MappedTypeNode; + function updateMappedTypeNode(node: MappedTypeNode, readonlyToken: ReadonlyToken | PlusToken | MinusToken | undefined, typeParameter: TypeParameterDeclaration, questionToken: QuestionToken | PlusToken | MinusToken | undefined, type: TypeNode | undefined): MappedTypeNode; + function createLiteralTypeNode(literal: LiteralTypeNode["literal"]): LiteralTypeNode; + function updateLiteralTypeNode(node: LiteralTypeNode, literal: LiteralTypeNode["literal"]): LiteralTypeNode; + function createObjectBindingPattern(elements: ReadonlyArray): ObjectBindingPattern; + function updateObjectBindingPattern(node: ObjectBindingPattern, elements: ReadonlyArray): ObjectBindingPattern; + function createArrayBindingPattern(elements: ReadonlyArray): ArrayBindingPattern; + function updateArrayBindingPattern(node: ArrayBindingPattern, elements: ReadonlyArray): ArrayBindingPattern; + function createBindingElement(dotDotDotToken: DotDotDotToken | undefined, propertyName: string | PropertyName | undefined, name: string | BindingName, initializer?: Expression): BindingElement; + function updateBindingElement(node: BindingElement, dotDotDotToken: DotDotDotToken | undefined, propertyName: PropertyName | undefined, name: BindingName, initializer: Expression | undefined): BindingElement; + function createArrayLiteral(elements?: ReadonlyArray, multiLine?: boolean): ArrayLiteralExpression; + function updateArrayLiteral(node: ArrayLiteralExpression, elements: ReadonlyArray): ArrayLiteralExpression; + function createObjectLiteral(properties?: ReadonlyArray, multiLine?: boolean): ObjectLiteralExpression; + function updateObjectLiteral(node: ObjectLiteralExpression, properties: ReadonlyArray): ObjectLiteralExpression; + function createPropertyAccess(expression: Expression, name: string | Identifier | undefined): PropertyAccessExpression; + function updatePropertyAccess(node: PropertyAccessExpression, expression: Expression, name: Identifier): PropertyAccessExpression; + function createElementAccess(expression: Expression, index: number | Expression): ElementAccessExpression; + function updateElementAccess(node: ElementAccessExpression, expression: Expression, argumentExpression: Expression): ElementAccessExpression; + function createCall(expression: Expression, typeArguments: ReadonlyArray | undefined, argumentsArray: ReadonlyArray | undefined): CallExpression; + function updateCall(node: CallExpression, expression: Expression, typeArguments: ReadonlyArray | undefined, argumentsArray: ReadonlyArray): CallExpression; + function createNew(expression: Expression, typeArguments: ReadonlyArray | undefined, argumentsArray: ReadonlyArray | undefined): NewExpression; + function updateNew(node: NewExpression, expression: Expression, typeArguments: ReadonlyArray | undefined, argumentsArray: ReadonlyArray | undefined): NewExpression; + /** @deprecated */ function createTaggedTemplate(tag: Expression, template: TemplateLiteral): TaggedTemplateExpression; + function createTaggedTemplate(tag: Expression, typeArguments: ReadonlyArray | undefined, template: TemplateLiteral): TaggedTemplateExpression; + /** @deprecated */ function updateTaggedTemplate(node: TaggedTemplateExpression, tag: Expression, template: TemplateLiteral): TaggedTemplateExpression; + function updateTaggedTemplate(node: TaggedTemplateExpression, tag: Expression, typeArguments: ReadonlyArray | undefined, template: TemplateLiteral): TaggedTemplateExpression; + function createTypeAssertion(type: TypeNode, expression: Expression): TypeAssertion; + function updateTypeAssertion(node: TypeAssertion, type: TypeNode, expression: Expression): TypeAssertion; + function createParen(expression: Expression): ParenthesizedExpression; + function updateParen(node: ParenthesizedExpression, expression: Expression): ParenthesizedExpression; + function createFunctionExpression(modifiers: ReadonlyArray | undefined, asteriskToken: AsteriskToken | undefined, name: string | Identifier | undefined, typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray | undefined, type: TypeNode | undefined, body: Block): FunctionExpression; + function updateFunctionExpression(node: FunctionExpression, modifiers: ReadonlyArray | undefined, asteriskToken: AsteriskToken | undefined, name: Identifier | undefined, typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode | undefined, body: Block): FunctionExpression; + function createArrowFunction(modifiers: ReadonlyArray | undefined, typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode | undefined, equalsGreaterThanToken: EqualsGreaterThanToken | undefined, body: ConciseBody): ArrowFunction; + function updateArrowFunction(node: ArrowFunction, modifiers: ReadonlyArray | undefined, typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode | undefined, equalsGreaterThanToken: Token, body: ConciseBody): ArrowFunction; + function createDelete(expression: Expression): DeleteExpression; + function updateDelete(node: DeleteExpression, expression: Expression): DeleteExpression; + function createTypeOf(expression: Expression): TypeOfExpression; + function updateTypeOf(node: TypeOfExpression, expression: Expression): TypeOfExpression; + function createVoid(expression: Expression): VoidExpression; + function updateVoid(node: VoidExpression, expression: Expression): VoidExpression; + function createAwait(expression: Expression): AwaitExpression; + function updateAwait(node: AwaitExpression, expression: Expression): AwaitExpression; + function createPrefix(operator: PrefixUnaryOperator, operand: Expression): PrefixUnaryExpression; + function updatePrefix(node: PrefixUnaryExpression, operand: Expression): PrefixUnaryExpression; + function createPostfix(operand: Expression, operator: PostfixUnaryOperator): PostfixUnaryExpression; + function updatePostfix(node: PostfixUnaryExpression, operand: Expression): PostfixUnaryExpression; + function createBinary(left: Expression, operator: BinaryOperator | BinaryOperatorToken, right: Expression): BinaryExpression; + function updateBinary(node: BinaryExpression, left: Expression, right: Expression, operator?: BinaryOperator | BinaryOperatorToken): BinaryExpression; + /** @deprecated */ function createConditional(condition: Expression, whenTrue: Expression, whenFalse: Expression): ConditionalExpression; + function createConditional(condition: Expression, questionToken: QuestionToken, whenTrue: Expression, colonToken: ColonToken, whenFalse: Expression): ConditionalExpression; + function updateConditional(node: ConditionalExpression, condition: Expression, questionToken: Token, whenTrue: Expression, colonToken: Token, whenFalse: Expression): ConditionalExpression; + function createTemplateExpression(head: TemplateHead, templateSpans: ReadonlyArray): TemplateExpression; + function updateTemplateExpression(node: TemplateExpression, head: TemplateHead, templateSpans: ReadonlyArray): TemplateExpression; + function createTemplateHead(text: string): TemplateHead; + function createTemplateMiddle(text: string): TemplateMiddle; + function createTemplateTail(text: string): TemplateTail; + function createNoSubstitutionTemplateLiteral(text: string): NoSubstitutionTemplateLiteral; + function createYield(expression?: Expression): YieldExpression; + function createYield(asteriskToken: AsteriskToken | undefined, expression: Expression): YieldExpression; + function updateYield(node: YieldExpression, asteriskToken: AsteriskToken | undefined, expression: Expression): YieldExpression; + function createSpread(expression: Expression): SpreadElement; + function updateSpread(node: SpreadElement, expression: Expression): SpreadElement; + function createClassExpression(modifiers: ReadonlyArray | undefined, name: string | Identifier | undefined, typeParameters: ReadonlyArray | undefined, heritageClauses: ReadonlyArray | undefined, members: ReadonlyArray): ClassExpression; + function updateClassExpression(node: ClassExpression, modifiers: ReadonlyArray | undefined, name: Identifier | undefined, typeParameters: ReadonlyArray | undefined, heritageClauses: ReadonlyArray | undefined, members: ReadonlyArray): ClassExpression; + function createOmittedExpression(): OmittedExpression; + function createExpressionWithTypeArguments(typeArguments: ReadonlyArray | undefined, expression: Expression): ExpressionWithTypeArguments; + function updateExpressionWithTypeArguments(node: ExpressionWithTypeArguments, typeArguments: ReadonlyArray | undefined, expression: Expression): ExpressionWithTypeArguments; + function createAsExpression(expression: Expression, type: TypeNode): AsExpression; + function updateAsExpression(node: AsExpression, expression: Expression, type: TypeNode): AsExpression; + function createNonNullExpression(expression: Expression): NonNullExpression; + function updateNonNullExpression(node: NonNullExpression, expression: Expression): NonNullExpression; + function createMetaProperty(keywordToken: MetaProperty["keywordToken"], name: Identifier): MetaProperty; + function updateMetaProperty(node: MetaProperty, name: Identifier): MetaProperty; + function createTemplateSpan(expression: Expression, literal: TemplateMiddle | TemplateTail): TemplateSpan; + function updateTemplateSpan(node: TemplateSpan, expression: Expression, literal: TemplateMiddle | TemplateTail): TemplateSpan; + function createSemicolonClassElement(): SemicolonClassElement; + function createBlock(statements: ReadonlyArray, multiLine?: boolean): Block; + function updateBlock(node: Block, statements: ReadonlyArray): Block; + function createVariableStatement(modifiers: ReadonlyArray | undefined, declarationList: VariableDeclarationList | ReadonlyArray): VariableStatement; + function updateVariableStatement(node: VariableStatement, modifiers: ReadonlyArray | undefined, declarationList: VariableDeclarationList): VariableStatement; + function createEmptyStatement(): EmptyStatement; + function createExpressionStatement(expression: Expression): ExpressionStatement; + function updateExpressionStatement(node: ExpressionStatement, expression: Expression): ExpressionStatement; + /** @deprecated Use `createExpressionStatement` instead. */ + const createStatement: typeof createExpressionStatement; + /** @deprecated Use `updateExpressionStatement` instead. */ + const updateStatement: typeof updateExpressionStatement; + function createIf(expression: Expression, thenStatement: Statement, elseStatement?: Statement): IfStatement; + function updateIf(node: IfStatement, expression: Expression, thenStatement: Statement, elseStatement: Statement | undefined): IfStatement; + function createDo(statement: Statement, expression: Expression): DoStatement; + function updateDo(node: DoStatement, statement: Statement, expression: Expression): DoStatement; + function createWhile(expression: Expression, statement: Statement): WhileStatement; + function updateWhile(node: WhileStatement, expression: Expression, statement: Statement): WhileStatement; + function createFor(initializer: ForInitializer | undefined, condition: Expression | undefined, incrementor: Expression | undefined, statement: Statement): ForStatement; + function updateFor(node: ForStatement, initializer: ForInitializer | undefined, condition: Expression | undefined, incrementor: Expression | undefined, statement: Statement): ForStatement; + function createForIn(initializer: ForInitializer, expression: Expression, statement: Statement): ForInStatement; + function updateForIn(node: ForInStatement, initializer: ForInitializer, expression: Expression, statement: Statement): ForInStatement; + function createForOf(awaitModifier: AwaitKeywordToken | undefined, initializer: ForInitializer, expression: Expression, statement: Statement): ForOfStatement; + function updateForOf(node: ForOfStatement, awaitModifier: AwaitKeywordToken | undefined, initializer: ForInitializer, expression: Expression, statement: Statement): ForOfStatement; + function createContinue(label?: string | Identifier): ContinueStatement; + function updateContinue(node: ContinueStatement, label: Identifier | undefined): ContinueStatement; + function createBreak(label?: string | Identifier): BreakStatement; + function updateBreak(node: BreakStatement, label: Identifier | undefined): BreakStatement; + function createReturn(expression?: Expression): ReturnStatement; + function updateReturn(node: ReturnStatement, expression: Expression | undefined): ReturnStatement; + function createWith(expression: Expression, statement: Statement): WithStatement; + function updateWith(node: WithStatement, expression: Expression, statement: Statement): WithStatement; + function createSwitch(expression: Expression, caseBlock: CaseBlock): SwitchStatement; + function updateSwitch(node: SwitchStatement, expression: Expression, caseBlock: CaseBlock): SwitchStatement; + function createLabel(label: string | Identifier, statement: Statement): LabeledStatement; + function updateLabel(node: LabeledStatement, label: Identifier, statement: Statement): LabeledStatement; + function createThrow(expression: Expression): ThrowStatement; + function updateThrow(node: ThrowStatement, expression: Expression): ThrowStatement; + function createTry(tryBlock: Block, catchClause: CatchClause | undefined, finallyBlock: Block | undefined): TryStatement; + function updateTry(node: TryStatement, tryBlock: Block, catchClause: CatchClause | undefined, finallyBlock: Block | undefined): TryStatement; + function createDebuggerStatement(): DebuggerStatement; + function createVariableDeclaration(name: string | BindingName, type?: TypeNode, initializer?: Expression): VariableDeclaration; + function updateVariableDeclaration(node: VariableDeclaration, name: BindingName, type: TypeNode | undefined, initializer: Expression | undefined): VariableDeclaration; + function createVariableDeclarationList(declarations: ReadonlyArray, flags?: NodeFlags): VariableDeclarationList; + function updateVariableDeclarationList(node: VariableDeclarationList, declarations: ReadonlyArray): VariableDeclarationList; + function createFunctionDeclaration(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, asteriskToken: AsteriskToken | undefined, name: string | Identifier | undefined, typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode | undefined, body: Block | undefined): FunctionDeclaration; + function updateFunctionDeclaration(node: FunctionDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, asteriskToken: AsteriskToken | undefined, name: Identifier | undefined, typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode | undefined, body: Block | undefined): FunctionDeclaration; + function createClassDeclaration(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: string | Identifier | undefined, typeParameters: ReadonlyArray | undefined, heritageClauses: ReadonlyArray | undefined, members: ReadonlyArray): ClassDeclaration; + function updateClassDeclaration(node: ClassDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: Identifier | undefined, typeParameters: ReadonlyArray | undefined, heritageClauses: ReadonlyArray | undefined, members: ReadonlyArray): ClassDeclaration; + function createInterfaceDeclaration(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: string | Identifier, typeParameters: ReadonlyArray | undefined, heritageClauses: ReadonlyArray | undefined, members: ReadonlyArray): InterfaceDeclaration; + function updateInterfaceDeclaration(node: InterfaceDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: Identifier, typeParameters: ReadonlyArray | undefined, heritageClauses: ReadonlyArray | undefined, members: ReadonlyArray): InterfaceDeclaration; + function createTypeAliasDeclaration(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: string | Identifier, typeParameters: ReadonlyArray | undefined, type: TypeNode): TypeAliasDeclaration; + function updateTypeAliasDeclaration(node: TypeAliasDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: Identifier, typeParameters: ReadonlyArray | undefined, type: TypeNode): TypeAliasDeclaration; + function createEnumDeclaration(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: string | Identifier, members: ReadonlyArray): EnumDeclaration; + function updateEnumDeclaration(node: EnumDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: Identifier, members: ReadonlyArray): EnumDeclaration; + function createModuleDeclaration(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: ModuleName, body: ModuleBody | undefined, flags?: NodeFlags): ModuleDeclaration; + function updateModuleDeclaration(node: ModuleDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: ModuleName, body: ModuleBody | undefined): ModuleDeclaration; + function createModuleBlock(statements: ReadonlyArray): ModuleBlock; + function updateModuleBlock(node: ModuleBlock, statements: ReadonlyArray): ModuleBlock; + function createCaseBlock(clauses: ReadonlyArray): CaseBlock; + function updateCaseBlock(node: CaseBlock, clauses: ReadonlyArray): CaseBlock; + function createNamespaceExportDeclaration(name: string | Identifier): NamespaceExportDeclaration; + function updateNamespaceExportDeclaration(node: NamespaceExportDeclaration, name: Identifier): NamespaceExportDeclaration; + function createImportEqualsDeclaration(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: string | Identifier, moduleReference: ModuleReference): ImportEqualsDeclaration; + function updateImportEqualsDeclaration(node: ImportEqualsDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: Identifier, moduleReference: ModuleReference): ImportEqualsDeclaration; + function createImportDeclaration(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, importClause: ImportClause | undefined, moduleSpecifier: Expression): ImportDeclaration; + function updateImportDeclaration(node: ImportDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, importClause: ImportClause | undefined, moduleSpecifier: Expression): ImportDeclaration; + function createImportClause(name: Identifier | undefined, namedBindings: NamedImportBindings | undefined): ImportClause; + function updateImportClause(node: ImportClause, name: Identifier | undefined, namedBindings: NamedImportBindings | undefined): ImportClause; + function createNamespaceImport(name: Identifier): NamespaceImport; + function updateNamespaceImport(node: NamespaceImport, name: Identifier): NamespaceImport; + function createNamedImports(elements: ReadonlyArray): NamedImports; + function updateNamedImports(node: NamedImports, elements: ReadonlyArray): NamedImports; + function createImportSpecifier(propertyName: Identifier | undefined, name: Identifier): ImportSpecifier; + function updateImportSpecifier(node: ImportSpecifier, propertyName: Identifier | undefined, name: Identifier): ImportSpecifier; + function createExportAssignment(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, isExportEquals: boolean | undefined, expression: Expression): ExportAssignment; + function updateExportAssignment(node: ExportAssignment, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, expression: Expression): ExportAssignment; + function createExportDeclaration(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, exportClause: NamedExports | undefined, moduleSpecifier?: Expression): ExportDeclaration; + function updateExportDeclaration(node: ExportDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, exportClause: NamedExports | undefined, moduleSpecifier: Expression | undefined): ExportDeclaration; + function createNamedExports(elements: ReadonlyArray): NamedExports; + function updateNamedExports(node: NamedExports, elements: ReadonlyArray): NamedExports; + function createExportSpecifier(propertyName: string | Identifier | undefined, name: string | Identifier): ExportSpecifier; + function updateExportSpecifier(node: ExportSpecifier, propertyName: Identifier | undefined, name: Identifier): ExportSpecifier; + function createExternalModuleReference(expression: Expression): ExternalModuleReference; + function updateExternalModuleReference(node: ExternalModuleReference, expression: Expression): ExternalModuleReference; + function createJsxElement(openingElement: JsxOpeningElement, children: ReadonlyArray, closingElement: JsxClosingElement): JsxElement; + function updateJsxElement(node: JsxElement, openingElement: JsxOpeningElement, children: ReadonlyArray, closingElement: JsxClosingElement): JsxElement; + function createJsxSelfClosingElement(tagName: JsxTagNameExpression, typeArguments: ReadonlyArray | undefined, attributes: JsxAttributes): JsxSelfClosingElement; + function updateJsxSelfClosingElement(node: JsxSelfClosingElement, tagName: JsxTagNameExpression, typeArguments: ReadonlyArray | undefined, attributes: JsxAttributes): JsxSelfClosingElement; + function createJsxOpeningElement(tagName: JsxTagNameExpression, typeArguments: ReadonlyArray | undefined, attributes: JsxAttributes): JsxOpeningElement; + function updateJsxOpeningElement(node: JsxOpeningElement, tagName: JsxTagNameExpression, typeArguments: ReadonlyArray | undefined, attributes: JsxAttributes): JsxOpeningElement; + function createJsxClosingElement(tagName: JsxTagNameExpression): JsxClosingElement; + function updateJsxClosingElement(node: JsxClosingElement, tagName: JsxTagNameExpression): JsxClosingElement; + function createJsxFragment(openingFragment: JsxOpeningFragment, children: ReadonlyArray, closingFragment: JsxClosingFragment): JsxFragment; + function updateJsxFragment(node: JsxFragment, openingFragment: JsxOpeningFragment, children: ReadonlyArray, closingFragment: JsxClosingFragment): JsxFragment; + function createJsxAttribute(name: Identifier, initializer: StringLiteral | JsxExpression): JsxAttribute; + function updateJsxAttribute(node: JsxAttribute, name: Identifier, initializer: StringLiteral | JsxExpression): JsxAttribute; + function createJsxAttributes(properties: ReadonlyArray): JsxAttributes; + function updateJsxAttributes(node: JsxAttributes, properties: ReadonlyArray): JsxAttributes; + function createJsxSpreadAttribute(expression: Expression): JsxSpreadAttribute; + function updateJsxSpreadAttribute(node: JsxSpreadAttribute, expression: Expression): JsxSpreadAttribute; + function createJsxExpression(dotDotDotToken: DotDotDotToken | undefined, expression: Expression | undefined): JsxExpression; + function updateJsxExpression(node: JsxExpression, expression: Expression | undefined): JsxExpression; + function createCaseClause(expression: Expression, statements: ReadonlyArray): CaseClause; + function updateCaseClause(node: CaseClause, expression: Expression, statements: ReadonlyArray): CaseClause; + function createDefaultClause(statements: ReadonlyArray): DefaultClause; + function updateDefaultClause(node: DefaultClause, statements: ReadonlyArray): DefaultClause; + function createHeritageClause(token: HeritageClause["token"], types: ReadonlyArray): HeritageClause; + function updateHeritageClause(node: HeritageClause, types: ReadonlyArray): HeritageClause; + function createCatchClause(variableDeclaration: string | VariableDeclaration | undefined, block: Block): CatchClause; + function updateCatchClause(node: CatchClause, variableDeclaration: VariableDeclaration | undefined, block: Block): CatchClause; + function createPropertyAssignment(name: string | PropertyName, initializer: Expression): PropertyAssignment; + function updatePropertyAssignment(node: PropertyAssignment, name: PropertyName, initializer: Expression): PropertyAssignment; + function createShorthandPropertyAssignment(name: string | Identifier, objectAssignmentInitializer?: Expression): ShorthandPropertyAssignment; + function updateShorthandPropertyAssignment(node: ShorthandPropertyAssignment, name: Identifier, objectAssignmentInitializer: Expression | undefined): ShorthandPropertyAssignment; + function createSpreadAssignment(expression: Expression): SpreadAssignment; + function updateSpreadAssignment(node: SpreadAssignment, expression: Expression): SpreadAssignment; + function createEnumMember(name: string | PropertyName, initializer?: Expression): EnumMember; + function updateEnumMember(node: EnumMember, name: PropertyName, initializer: Expression | undefined): EnumMember; + function updateSourceFileNode(node: SourceFile, statements: ReadonlyArray, isDeclarationFile?: boolean, referencedFiles?: SourceFile["referencedFiles"], typeReferences?: SourceFile["typeReferenceDirectives"], hasNoDefaultLib?: boolean, libReferences?: SourceFile["libReferenceDirectives"]): SourceFile; + /** + * Creates a shallow, memberwise clone of a node for mutation. + */ + function getMutableClone(node: T): T; + /** + * Creates a synthetic statement to act as a placeholder for a not-emitted statement in + * order to preserve comments. + * + * @param original The original statement. + */ + function createNotEmittedStatement(original: Node): NotEmittedStatement; + /** + * Creates a synthetic expression to act as a placeholder for a not-emitted expression in + * order to preserve comments or sourcemap positions. + * + * @param expression The inner expression to emit. + * @param original The original outer expression. + * @param location The location for the expression. Defaults to the positions from "original" if provided. + */ + function createPartiallyEmittedExpression(expression: Expression, original?: Node): PartiallyEmittedExpression; + function updatePartiallyEmittedExpression(node: PartiallyEmittedExpression, expression: Expression): PartiallyEmittedExpression; + function createCommaList(elements: ReadonlyArray): CommaListExpression; + function updateCommaList(node: CommaListExpression, elements: ReadonlyArray): CommaListExpression; + function createBundle(sourceFiles: ReadonlyArray, prepends?: ReadonlyArray): Bundle; + function createUnparsedSourceFile(text: string): UnparsedSource; + function createUnparsedSourceFile(text: string, mapPath: string | undefined, map: string | undefined): UnparsedSource; + function createInputFiles(javascript: string, declaration: string): InputFiles; + function createInputFiles(javascript: string, declaration: string, javascriptMapPath: string | undefined, javascriptMapText: string | undefined, declarationMapPath: string | undefined, declarationMapText: string | undefined): InputFiles; + function updateBundle(node: Bundle, sourceFiles: ReadonlyArray, prepends?: ReadonlyArray): Bundle; + function createImmediatelyInvokedFunctionExpression(statements: ReadonlyArray): CallExpression; + function createImmediatelyInvokedFunctionExpression(statements: ReadonlyArray, param: ParameterDeclaration, paramValue: Expression): CallExpression; + function createImmediatelyInvokedArrowFunction(statements: ReadonlyArray): CallExpression; + function createImmediatelyInvokedArrowFunction(statements: ReadonlyArray, param: ParameterDeclaration, paramValue: Expression): CallExpression; + function createComma(left: Expression, right: Expression): Expression; + function createLessThan(left: Expression, right: Expression): Expression; + function createAssignment(left: ObjectLiteralExpression | ArrayLiteralExpression, right: Expression): DestructuringAssignment; + function createAssignment(left: Expression, right: Expression): BinaryExpression; + function createStrictEquality(left: Expression, right: Expression): BinaryExpression; + function createStrictInequality(left: Expression, right: Expression): BinaryExpression; + function createAdd(left: Expression, right: Expression): BinaryExpression; + function createSubtract(left: Expression, right: Expression): BinaryExpression; + function createPostfixIncrement(operand: Expression): PostfixUnaryExpression; + function createLogicalAnd(left: Expression, right: Expression): BinaryExpression; + function createLogicalOr(left: Expression, right: Expression): BinaryExpression; + function createLogicalNot(operand: Expression): PrefixUnaryExpression; + function createVoidZero(): VoidExpression; + function createExportDefault(expression: Expression): ExportAssignment; + function createExternalModuleExport(exportName: Identifier): ExportDeclaration; + /** + * Clears any EmitNode entries from parse-tree nodes. + * @param sourceFile A source file. + */ + function disposeEmitNodes(sourceFile: SourceFile): void; + function setTextRange(range: T, location: TextRange | undefined): T; + /** + * Sets flags that control emit behavior of a node. + */ + function setEmitFlags(node: T, emitFlags: EmitFlags): T; + /** + * Gets a custom text range to use when emitting source maps. + */ + function getSourceMapRange(node: Node): SourceMapRange; + /** + * Sets a custom text range to use when emitting source maps. + */ + function setSourceMapRange(node: T, range: SourceMapRange | undefined): T; + /** + * Create an external source map source file reference + */ + function createSourceMapSource(fileName: string, text: string, skipTrivia?: (pos: number) => number): SourceMapSource; + /** + * Gets the TextRange to use for source maps for a token of a node. + */ + function getTokenSourceMapRange(node: Node, token: SyntaxKind): SourceMapRange | undefined; + /** + * Sets the TextRange to use for source maps for a token of a node. + */ + function setTokenSourceMapRange(node: T, token: SyntaxKind, range: SourceMapRange | undefined): T; + /** + * Gets a custom text range to use when emitting comments. + */ + function getCommentRange(node: Node): TextRange; + /** + * Sets a custom text range to use when emitting comments. + */ + function setCommentRange(node: T, range: TextRange): T; + function getSyntheticLeadingComments(node: Node): SynthesizedComment[] | undefined; + function setSyntheticLeadingComments(node: T, comments: SynthesizedComment[] | undefined): T; + function addSyntheticLeadingComment(node: T, kind: SyntaxKind.SingleLineCommentTrivia | SyntaxKind.MultiLineCommentTrivia, text: string, hasTrailingNewLine?: boolean): T; + function getSyntheticTrailingComments(node: Node): SynthesizedComment[] | undefined; + function setSyntheticTrailingComments(node: T, comments: SynthesizedComment[] | undefined): T; + function addSyntheticTrailingComment(node: T, kind: SyntaxKind.SingleLineCommentTrivia | SyntaxKind.MultiLineCommentTrivia, text: string, hasTrailingNewLine?: boolean): T; + function moveSyntheticComments(node: T, original: Node): T; + /** + * Gets the constant value to emit for an expression. + */ + function getConstantValue(node: PropertyAccessExpression | ElementAccessExpression): string | number | undefined; + /** + * Sets the constant value to emit for an expression. + */ + function setConstantValue(node: PropertyAccessExpression | ElementAccessExpression, value: string | number): PropertyAccessExpression | ElementAccessExpression; + /** + * Adds an EmitHelper to a node. + */ + function addEmitHelper(node: T, helper: EmitHelper): T; + /** + * Add EmitHelpers to a node. + */ + function addEmitHelpers(node: T, helpers: EmitHelper[] | undefined): T; + /** + * Removes an EmitHelper from a node. + */ + function removeEmitHelper(node: Node, helper: EmitHelper): boolean; + /** + * Gets the EmitHelpers of a node. + */ + function getEmitHelpers(node: Node): EmitHelper[] | undefined; + /** + * Moves matching emit helpers from a source node to a target node. + */ + function moveEmitHelpers(source: Node, target: Node, predicate: (helper: EmitHelper) => boolean): void; + function setOriginalNode(node: T, original: Node | undefined): T; +} +declare namespace ts { + /** + * Visits a Node using the supplied visitor, possibly returning a new Node in its place. + * + * @param node The Node to visit. + * @param visitor The callback used to visit the Node. + * @param test A callback to execute to verify the Node is valid. + * @param lift An optional callback to execute to lift a NodeArray into a valid Node. + */ + function visitNode(node: T | undefined, visitor: Visitor | undefined, test?: (node: Node) => boolean, lift?: (node: NodeArray) => T): T; + /** + * Visits a Node using the supplied visitor, possibly returning a new Node in its place. + * + * @param node The Node to visit. + * @param visitor The callback used to visit the Node. + * @param test A callback to execute to verify the Node is valid. + * @param lift An optional callback to execute to lift a NodeArray into a valid Node. + */ + function visitNode(node: T | undefined, visitor: Visitor | undefined, test?: (node: Node) => boolean, lift?: (node: NodeArray) => T): T | undefined; + /** + * Visits a NodeArray using the supplied visitor, possibly returning a new NodeArray in its place. + * + * @param nodes The NodeArray to visit. + * @param visitor The callback used to visit a Node. + * @param test A node test to execute for each node. + * @param start An optional value indicating the starting offset at which to start visiting. + * @param count An optional value indicating the maximum number of nodes to visit. + */ + function visitNodes(nodes: NodeArray | undefined, visitor: Visitor, test?: (node: Node) => boolean, start?: number, count?: number): NodeArray; + /** + * Visits a NodeArray using the supplied visitor, possibly returning a new NodeArray in its place. + * + * @param nodes The NodeArray to visit. + * @param visitor The callback used to visit a Node. + * @param test A node test to execute for each node. + * @param start An optional value indicating the starting offset at which to start visiting. + * @param count An optional value indicating the maximum number of nodes to visit. + */ + function visitNodes(nodes: NodeArray | undefined, visitor: Visitor, test?: (node: Node) => boolean, start?: number, count?: number): NodeArray | undefined; + /** + * Starts a new lexical environment and visits a statement list, ending the lexical environment + * and merging hoisted declarations upon completion. + */ + function visitLexicalEnvironment(statements: NodeArray, visitor: Visitor, context: TransformationContext, start?: number, ensureUseStrict?: boolean): NodeArray; + /** + * Starts a new lexical environment and visits a parameter list, suspending the lexical + * environment upon completion. + */ + function visitParameterList(nodes: NodeArray | undefined, visitor: Visitor, context: TransformationContext, nodesVisitor?: typeof visitNodes): NodeArray; + /** + * Resumes a suspended lexical environment and visits a function body, ending the lexical + * environment and merging hoisted declarations upon completion. + */ + function visitFunctionBody(node: FunctionBody, visitor: Visitor, context: TransformationContext): FunctionBody; + /** + * Resumes a suspended lexical environment and visits a function body, ending the lexical + * environment and merging hoisted declarations upon completion. + */ + function visitFunctionBody(node: FunctionBody | undefined, visitor: Visitor, context: TransformationContext): FunctionBody | undefined; + /** + * Resumes a suspended lexical environment and visits a concise body, ending the lexical + * environment and merging hoisted declarations upon completion. + */ + function visitFunctionBody(node: ConciseBody, visitor: Visitor, context: TransformationContext): ConciseBody; + /** + * Visits each child of a Node using the supplied visitor, possibly returning a new Node of the same kind in its place. + * + * @param node The Node whose children will be visited. + * @param visitor The callback used to visit each child. + * @param context A lexical environment context for the visitor. + */ + function visitEachChild(node: T, visitor: Visitor, context: TransformationContext): T; + /** + * Visits each child of a Node using the supplied visitor, possibly returning a new Node of the same kind in its place. + * + * @param node The Node whose children will be visited. + * @param visitor The callback used to visit each child. + * @param context A lexical environment context for the visitor. + */ + function visitEachChild(node: T | undefined, visitor: Visitor, context: TransformationContext, nodesVisitor?: typeof visitNodes, tokenVisitor?: Visitor): T | undefined; +} +declare namespace ts { + function createPrinter(printerOptions?: PrinterOptions, handlers?: PrintHandlers): Printer; +} +declare namespace ts { + function findConfigFile(searchPath: string, fileExists: (fileName: string) => boolean, configName?: string): string | undefined; + function resolveTripleslashReference(moduleName: string, containingFile: string): string; + function createCompilerHost(options: CompilerOptions, setParentNodes?: boolean): CompilerHost; + function getPreEmitDiagnostics(program: Program, sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray; + interface FormatDiagnosticsHost { + getCurrentDirectory(): string; + getCanonicalFileName(fileName: string): string; + getNewLine(): string; + } + function formatDiagnostics(diagnostics: ReadonlyArray, host: FormatDiagnosticsHost): string; + function formatDiagnostic(diagnostic: Diagnostic, host: FormatDiagnosticsHost): string; + function formatDiagnosticsWithColorAndContext(diagnostics: ReadonlyArray, host: FormatDiagnosticsHost): string; + function flattenDiagnosticMessageText(messageText: string | DiagnosticMessageChain | undefined, newLine: string): string; + function getConfigFileParsingDiagnostics(configFileParseResult: ParsedCommandLine): ReadonlyArray; + /** + * Create a new 'Program' instance. A Program is an immutable collection of 'SourceFile's and a 'CompilerOptions' + * that represent a compilation unit. + * + * Creating a program proceeds from a set of root files, expanding the set of inputs by following imports and + * triple-slash-reference-path directives transitively. '@types' and triple-slash-reference-types are also pulled in. + * + * @param createProgramOptions - The options for creating a program. + * @returns A 'Program' object. + */ + function createProgram(createProgramOptions: CreateProgramOptions): Program; + /** + * Create a new 'Program' instance. A Program is an immutable collection of 'SourceFile's and a 'CompilerOptions' + * that represent a compilation unit. + * + * Creating a program proceeds from a set of root files, expanding the set of inputs by following imports and + * triple-slash-reference-path directives transitively. '@types' and triple-slash-reference-types are also pulled in. + * + * @param rootNames - A set of root files. + * @param options - The compiler options which should be used. + * @param host - The host interacts with the underlying file system. + * @param oldProgram - Reuses an old program structure. + * @param configFileParsingDiagnostics - error during config file parsing + * @returns A 'Program' object. + */ + function createProgram(rootNames: ReadonlyArray, options: CompilerOptions, host?: CompilerHost, oldProgram?: Program, configFileParsingDiagnostics?: ReadonlyArray): Program; + /** @deprecated */ interface ResolveProjectReferencePathHost { + fileExists(fileName: string): boolean; + } + /** + * Returns the target config filename of a project reference. + * Note: The file might not exist. + */ + function resolveProjectReferencePath(ref: ProjectReference): ResolvedConfigFileName; + /** @deprecated */ function resolveProjectReferencePath(host: ResolveProjectReferencePathHost, ref: ProjectReference): ResolvedConfigFileName; +} +declare namespace ts { + interface EmitOutput { + outputFiles: OutputFile[]; + emitSkipped: boolean; + } + interface OutputFile { + name: string; + writeByteOrderMark: boolean; + text: string; + } +} +declare namespace ts { + type AffectedFileResult = { + result: T; + affected: SourceFile | Program; + } | undefined; + interface BuilderProgramHost { + /** + * return true if file names are treated with case sensitivity + */ + useCaseSensitiveFileNames(): boolean; + /** + * If provided this would be used this hash instead of actual file shape text for detecting changes + */ + createHash?: (data: string) => string; + /** + * When emit or emitNextAffectedFile are called without writeFile, + * this callback if present would be used to write files + */ + writeFile?: WriteFileCallback; + } + /** + * Builder to manage the program state changes + */ + interface BuilderProgram { + /** + * Returns current program + */ + getProgram(): Program; + /** + * Get compiler options of the program + */ + getCompilerOptions(): CompilerOptions; + /** + * Get the source file in the program with file name + */ + getSourceFile(fileName: string): SourceFile | undefined; + /** + * Get a list of files in the program + */ + getSourceFiles(): ReadonlyArray; + /** + * Get the diagnostics for compiler options + */ + getOptionsDiagnostics(cancellationToken?: CancellationToken): ReadonlyArray; + /** + * Get the diagnostics that dont belong to any file + */ + getGlobalDiagnostics(cancellationToken?: CancellationToken): ReadonlyArray; + /** + * Get the diagnostics from config file parsing + */ + getConfigFileParsingDiagnostics(): ReadonlyArray; + /** + * Get the syntax diagnostics, for all source files if source file is not supplied + */ + getSyntacticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray; + /** + * Get all the dependencies of the file + */ + getAllDependencies(sourceFile: SourceFile): ReadonlyArray; + /** + * Gets the semantic diagnostics from the program corresponding to this state of file (if provided) or whole program + * The semantic diagnostics are cached and managed here + * Note that it is assumed that when asked about semantic diagnostics through this API, + * the file has been taken out of affected files so it is safe to use cache or get from program and cache the diagnostics + * In case of SemanticDiagnosticsBuilderProgram if the source file is not provided, + * it will iterate through all the affected files, to ensure that cache stays valid and yet provide a way to get all semantic diagnostics + */ + getSemanticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray; + /** + * Emits the JavaScript and declaration files. + * When targetSource file is specified, emits the files corresponding to that source file, + * otherwise for the whole program. + * In case of EmitAndSemanticDiagnosticsBuilderProgram, when targetSourceFile is specified, + * it is assumed that that file is handled from affected file list. If targetSourceFile is not specified, + * it will only emit all the affected files instead of whole program + * + * The first of writeFile if provided, writeFile of BuilderProgramHost if provided, writeFile of compiler host + * in that order would be used to write the files + */ + emit(targetSourceFile?: SourceFile, writeFile?: WriteFileCallback, cancellationToken?: CancellationToken, emitOnlyDtsFiles?: boolean, customTransformers?: CustomTransformers): EmitResult; + /** + * Get the current directory of the program + */ + getCurrentDirectory(): string; + } + /** + * The builder that caches the semantic diagnostics for the program and handles the changed files and affected files + */ + interface SemanticDiagnosticsBuilderProgram extends BuilderProgram { + /** + * Gets the semantic diagnostics from the program for the next affected file and caches it + * Returns undefined if the iteration is complete + */ + getSemanticDiagnosticsOfNextAffectedFile(cancellationToken?: CancellationToken, ignoreSourceFile?: (sourceFile: SourceFile) => boolean): AffectedFileResult>; + } + /** + * The builder that can handle the changes in program and iterate through changed file to emit the files + * The semantic diagnostics are cached per file and managed by clearing for the changed/affected files + */ + interface EmitAndSemanticDiagnosticsBuilderProgram extends BuilderProgram { + /** + * Emits the next affected file's emit result (EmitResult and sourceFiles emitted) or returns undefined if iteration is complete + * The first of writeFile if provided, writeFile of BuilderProgramHost if provided, writeFile of compiler host + * in that order would be used to write the files + */ + emitNextAffectedFile(writeFile?: WriteFileCallback, cancellationToken?: CancellationToken, emitOnlyDtsFiles?: boolean, customTransformers?: CustomTransformers): AffectedFileResult; + } + /** + * Create the builder to manage semantic diagnostics and cache them + */ + function createSemanticDiagnosticsBuilderProgram(newProgram: Program, host: BuilderProgramHost, oldProgram?: SemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): SemanticDiagnosticsBuilderProgram; + function createSemanticDiagnosticsBuilderProgram(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: SemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray, projectReferences?: ReadonlyArray): SemanticDiagnosticsBuilderProgram; + /** + * Create the builder that can handle the changes in program and iterate through changed files + * to emit the those files and manage semantic diagnostics cache as well + */ + function createEmitAndSemanticDiagnosticsBuilderProgram(newProgram: Program, host: BuilderProgramHost, oldProgram?: EmitAndSemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): EmitAndSemanticDiagnosticsBuilderProgram; + function createEmitAndSemanticDiagnosticsBuilderProgram(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: EmitAndSemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray, projectReferences?: ReadonlyArray): EmitAndSemanticDiagnosticsBuilderProgram; + /** + * Creates a builder thats just abstraction over program and can be used with watch + */ + function createAbstractBuilder(newProgram: Program, host: BuilderProgramHost, oldProgram?: BuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): BuilderProgram; + function createAbstractBuilder(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: BuilderProgram, configFileParsingDiagnostics?: ReadonlyArray, projectReferences?: ReadonlyArray): BuilderProgram; +} +declare namespace ts { + type WatchStatusReporter = (diagnostic: Diagnostic, newLine: string, options: CompilerOptions) => void; + /** Create the program with rootNames and options, if they are undefined, oldProgram and new configFile diagnostics create new program */ + type CreateProgram = (rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: T, configFileParsingDiagnostics?: ReadonlyArray, projectReferences?: ReadonlyArray | undefined) => T; + /** Host that has watch functionality used in --watch mode */ + interface WatchHost { + /** If provided, called with Diagnostic message that informs about change in watch status */ + onWatchStatusChange?(diagnostic: Diagnostic, newLine: string, options: CompilerOptions): void; + /** Used to watch changes in source files, missing files needed to update the program or config file */ + watchFile(path: string, callback: FileWatcherCallback, pollingInterval?: number): FileWatcher; + /** Used to watch resolved module's failed lookup locations, config file specs, type roots where auto type reference directives are added */ + watchDirectory(path: string, callback: DirectoryWatcherCallback, recursive?: boolean): FileWatcher; + /** If provided, will be used to set delayed compilation, so that multiple changes in short span are compiled together */ + setTimeout?(callback: (...args: any[]) => void, ms: number, ...args: any[]): any; + /** If provided, will be used to reset existing delayed compilation */ + clearTimeout?(timeoutId: any): void; + } + interface WatchCompilerHost extends WatchHost { + /** + * Used to create the program when need for program creation or recreation detected + */ + createProgram: CreateProgram; + /** If provided, callback to invoke after every new program creation */ + afterProgramCreate?(program: T): void; + useCaseSensitiveFileNames(): boolean; + getNewLine(): string; + getCurrentDirectory(): string; + getDefaultLibFileName(options: CompilerOptions): string; + getDefaultLibLocation?(): string; + createHash?(data: string): string; + /** + * Use to check file presence for source files and + * if resolveModuleNames is not provided (complier is in charge of module resolution) then module files as well + */ + fileExists(path: string): boolean; + /** + * Use to read file text for source files and + * if resolveModuleNames is not provided (complier is in charge of module resolution) then module files as well + */ + readFile(path: string, encoding?: string): string | undefined; + /** If provided, used for module resolution as well as to handle directory structure */ + directoryExists?(path: string): boolean; + /** If provided, used in resolutions as well as handling directory structure */ + getDirectories?(path: string): string[]; + /** If provided, used to cache and handle directory structure modifications */ + readDirectory?(path: string, extensions?: ReadonlyArray, exclude?: ReadonlyArray, include?: ReadonlyArray, depth?: number): string[]; + /** Symbol links resolution */ + realpath?(path: string): string; + /** If provided would be used to write log about compilation */ + trace?(s: string): void; + /** If provided is used to get the environment variable */ + getEnvironmentVariable?(name: string): string | undefined; + /** If provided, used to resolve the module names, otherwise typescript's default module resolution */ + resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[], redirectedReference?: ResolvedProjectReference): (ResolvedModule | undefined)[]; + /** If provided, used to resolve type reference directives, otherwise typescript's default resolution */ + resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string, redirectedReference?: ResolvedProjectReference): (ResolvedTypeReferenceDirective | undefined)[]; + } + /** + * Host to create watch with root files and options + */ + interface WatchCompilerHostOfFilesAndCompilerOptions extends WatchCompilerHost { + /** root files to use to generate program */ + rootFiles: string[]; + /** Compiler options */ + options: CompilerOptions; + /** Project References */ + projectReferences?: ReadonlyArray; + } + /** + * Host to create watch with config file + */ + interface WatchCompilerHostOfConfigFile extends WatchCompilerHost, ConfigFileDiagnosticsReporter { + /** Name of the config file to compile */ + configFileName: string; + /** Options to extend */ + optionsToExtend?: CompilerOptions; + /** + * Used to generate source file names from the config file and its include, exclude, files rules + * and also to cache the directory stucture + */ + readDirectory(path: string, extensions?: ReadonlyArray, exclude?: ReadonlyArray, include?: ReadonlyArray, depth?: number): string[]; + } + interface Watch { + /** Synchronize with host and get updated program */ + getProgram(): T; + } + /** + * Creates the watch what generates program using the config file + */ + interface WatchOfConfigFile extends Watch { + } + /** + * Creates the watch that generates program using the root files and compiler options + */ + interface WatchOfFilesAndCompilerOptions extends Watch { + /** Updates the root files in the program, only if this is not config file compilation */ + updateRootFileNames(fileNames: string[]): void; + } + /** + * Create the watch compiler host for either configFile or fileNames and its options + */ + function createWatchCompilerHost(configFileName: string, optionsToExtend: CompilerOptions | undefined, system: System, createProgram?: CreateProgram, reportDiagnostic?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter): WatchCompilerHostOfConfigFile; + function createWatchCompilerHost(rootFiles: string[], options: CompilerOptions, system: System, createProgram?: CreateProgram, reportDiagnostic?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter, projectReferences?: ReadonlyArray): WatchCompilerHostOfFilesAndCompilerOptions; + /** + * Creates the watch from the host for root files and compiler options + */ + function createWatchProgram(host: WatchCompilerHostOfFilesAndCompilerOptions): WatchOfFilesAndCompilerOptions; + /** + * Creates the watch from the host for config file + */ + function createWatchProgram(host: WatchCompilerHostOfConfigFile): WatchOfConfigFile; +} +declare namespace ts.server { + type ActionSet = "action::set"; + type ActionInvalidate = "action::invalidate"; + type ActionPackageInstalled = "action::packageInstalled"; + type ActionValueInspected = "action::valueInspected"; + type EventTypesRegistry = "event::typesRegistry"; + type EventBeginInstallTypes = "event::beginInstallTypes"; + type EventEndInstallTypes = "event::endInstallTypes"; + type EventInitializationFailed = "event::initializationFailed"; + interface TypingInstallerResponse { + readonly kind: ActionSet | ActionInvalidate | EventTypesRegistry | ActionPackageInstalled | ActionValueInspected | EventBeginInstallTypes | EventEndInstallTypes | EventInitializationFailed; + } + interface TypingInstallerRequestWithProjectName { + readonly projectName: string; + } + interface DiscoverTypings extends TypingInstallerRequestWithProjectName { + readonly fileNames: string[]; + readonly projectRootPath: Path; + readonly compilerOptions: CompilerOptions; + readonly typeAcquisition: TypeAcquisition; + readonly unresolvedImports: SortedReadonlyArray; + readonly cachePath?: string; + readonly kind: "discover"; + } + interface CloseProject extends TypingInstallerRequestWithProjectName { + readonly kind: "closeProject"; + } + interface TypesRegistryRequest { + readonly kind: "typesRegistry"; + } + interface InstallPackageRequest extends TypingInstallerRequestWithProjectName { + readonly kind: "installPackage"; + readonly fileName: Path; + readonly packageName: string; + readonly projectRootPath: Path; + } + interface PackageInstalledResponse extends ProjectResponse { + readonly kind: ActionPackageInstalled; + readonly success: boolean; + readonly message: string; + } + interface InitializationFailedResponse extends TypingInstallerResponse { + readonly kind: EventInitializationFailed; + readonly message: string; + } + interface ProjectResponse extends TypingInstallerResponse { + readonly projectName: string; + } + interface InvalidateCachedTypings extends ProjectResponse { + readonly kind: ActionInvalidate; + } + interface InstallTypes extends ProjectResponse { + readonly kind: EventBeginInstallTypes | EventEndInstallTypes; + readonly eventId: number; + readonly typingsInstallerVersion: string; + readonly packagesToInstall: ReadonlyArray; + } + interface BeginInstallTypes extends InstallTypes { + readonly kind: EventBeginInstallTypes; + } + interface EndInstallTypes extends InstallTypes { + readonly kind: EventEndInstallTypes; + readonly installSuccess: boolean; + } + interface SetTypings extends ProjectResponse { + readonly typeAcquisition: TypeAcquisition; + readonly compilerOptions: CompilerOptions; + readonly typings: string[]; + readonly unresolvedImports: SortedReadonlyArray; + readonly kind: ActionSet; + } +} +declare namespace ts { + interface Node { + getSourceFile(): SourceFile; + getChildCount(sourceFile?: SourceFile): number; + getChildAt(index: number, sourceFile?: SourceFile): Node; + getChildren(sourceFile?: SourceFile): Node[]; + getStart(sourceFile?: SourceFile, includeJsDocComment?: boolean): number; + getFullStart(): number; + getEnd(): number; + getWidth(sourceFile?: SourceFileLike): number; + getFullWidth(): number; + getLeadingTriviaWidth(sourceFile?: SourceFile): number; + getFullText(sourceFile?: SourceFile): string; + getText(sourceFile?: SourceFile): string; + getFirstToken(sourceFile?: SourceFile): Node | undefined; + getLastToken(sourceFile?: SourceFile): Node | undefined; + forEachChild(cbNode: (node: Node) => T | undefined, cbNodeArray?: (nodes: NodeArray) => T | undefined): T | undefined; + } + interface Identifier { + readonly text: string; + } + interface Symbol { + readonly name: string; + getFlags(): SymbolFlags; + getEscapedName(): __String; + getName(): string; + getDeclarations(): Declaration[] | undefined; + getDocumentationComment(typeChecker: TypeChecker | undefined): SymbolDisplayPart[]; + getJsDocTags(): JSDocTagInfo[]; + } + interface Type { + getFlags(): TypeFlags; + getSymbol(): Symbol | undefined; + getProperties(): Symbol[]; + getProperty(propertyName: string): Symbol | undefined; + getApparentProperties(): Symbol[]; + getCallSignatures(): ReadonlyArray; + getConstructSignatures(): ReadonlyArray; + getStringIndexType(): Type | undefined; + getNumberIndexType(): Type | undefined; + getBaseTypes(): BaseType[] | undefined; + getNonNullableType(): Type; + getConstraint(): Type | undefined; + getDefault(): Type | undefined; + isUnion(): this is UnionType; + isIntersection(): this is IntersectionType; + isUnionOrIntersection(): this is UnionOrIntersectionType; + isLiteral(): this is LiteralType; + isStringLiteral(): this is StringLiteralType; + isNumberLiteral(): this is NumberLiteralType; + isTypeParameter(): this is TypeParameter; + isClassOrInterface(): this is InterfaceType; + isClass(): this is InterfaceType; + } + interface Signature { + getDeclaration(): SignatureDeclaration; + getTypeParameters(): TypeParameter[] | undefined; + getParameters(): Symbol[]; + getReturnType(): Type; + getDocumentationComment(typeChecker: TypeChecker | undefined): SymbolDisplayPart[]; + getJsDocTags(): JSDocTagInfo[]; + } + interface SourceFile { + getLineAndCharacterOfPosition(pos: number): LineAndCharacter; + getLineEndOfPosition(pos: number): number; + getLineStarts(): ReadonlyArray; + getPositionOfLineAndCharacter(line: number, character: number): number; + update(newText: string, textChangeRange: TextChangeRange): SourceFile; + } + interface SourceFileLike { + getLineAndCharacterOfPosition(pos: number): LineAndCharacter; + } + interface SourceMapSource { + getLineAndCharacterOfPosition(pos: number): LineAndCharacter; + } + /** + * Represents an immutable snapshot of a script at a specified time.Once acquired, the + * snapshot is observably immutable. i.e. the same calls with the same parameters will return + * the same values. + */ + interface IScriptSnapshot { + /** Gets a portion of the script snapshot specified by [start, end). */ + getText(start: number, end: number): string; + /** Gets the length of this script snapshot. */ + getLength(): number; + /** + * Gets the TextChangeRange that describe how the text changed between this text and + * an older version. This information is used by the incremental parser to determine + * what sections of the script need to be re-parsed. 'undefined' can be returned if the + * change range cannot be determined. However, in that case, incremental parsing will + * not happen and the entire document will be re - parsed. + */ + getChangeRange(oldSnapshot: IScriptSnapshot): TextChangeRange | undefined; + /** Releases all resources held by this script snapshot */ + dispose?(): void; + } + namespace ScriptSnapshot { + function fromString(text: string): IScriptSnapshot; + } + interface PreProcessedFileInfo { + referencedFiles: FileReference[]; + typeReferenceDirectives: FileReference[]; + libReferenceDirectives: FileReference[]; + importedFiles: FileReference[]; + ambientExternalModules?: string[]; + isLibFile: boolean; + } + interface HostCancellationToken { + isCancellationRequested(): boolean; + } + interface InstallPackageOptions { + fileName: Path; + packageName: string; + } + interface LanguageServiceHost extends GetEffectiveTypeRootsHost { + getCompilationSettings(): CompilerOptions; + getNewLine?(): string; + getProjectVersion?(): string; + getScriptFileNames(): string[]; + getScriptKind?(fileName: string): ScriptKind; + getScriptVersion(fileName: string): string; + getScriptSnapshot(fileName: string): IScriptSnapshot | undefined; + getProjectReferences?(): ReadonlyArray | undefined; + getLocalizedDiagnosticMessages?(): any; + getCancellationToken?(): HostCancellationToken; + getCurrentDirectory(): string; + getDefaultLibFileName(options: CompilerOptions): string; + log?(s: string): void; + trace?(s: string): void; + error?(s: string): void; + useCaseSensitiveFileNames?(): boolean; + readDirectory?(path: string, extensions?: ReadonlyArray, exclude?: ReadonlyArray, include?: ReadonlyArray, depth?: number): string[]; + readFile?(path: string, encoding?: string): string | undefined; + realpath?(path: string): string; + fileExists?(path: string): boolean; + getTypeRootsVersion?(): number; + resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[], redirectedReference?: ResolvedProjectReference): (ResolvedModule | undefined)[]; + getResolvedModuleWithFailedLookupLocationsFromCache?(modulename: string, containingFile: string): ResolvedModuleWithFailedLookupLocations | undefined; + resolveTypeReferenceDirectives?(typeDirectiveNames: string[], containingFile: string, redirectedReference?: ResolvedProjectReference): (ResolvedTypeReferenceDirective | undefined)[]; + getDirectories?(directoryName: string): string[]; + /** + * Gets a set of custom transformers to use during emit. + */ + getCustomTransformers?(): CustomTransformers | undefined; + isKnownTypesPackageName?(name: string): boolean; + installPackage?(options: InstallPackageOptions): Promise; + writeFile?(fileName: string, content: string): void; + } + type WithMetadata = T & { + metadata?: unknown; + }; + interface LanguageService { + cleanupSemanticCache(): void; + getSyntacticDiagnostics(fileName: string): DiagnosticWithLocation[]; + /** The first time this is called, it will return global diagnostics (no location). */ + getSemanticDiagnostics(fileName: string): Diagnostic[]; + getSuggestionDiagnostics(fileName: string): DiagnosticWithLocation[]; + getCompilerOptionsDiagnostics(): Diagnostic[]; + /** + * @deprecated Use getEncodedSyntacticClassifications instead. + */ + getSyntacticClassifications(fileName: string, span: TextSpan): ClassifiedSpan[]; + /** + * @deprecated Use getEncodedSemanticClassifications instead. + */ + getSemanticClassifications(fileName: string, span: TextSpan): ClassifiedSpan[]; + getEncodedSyntacticClassifications(fileName: string, span: TextSpan): Classifications; + getEncodedSemanticClassifications(fileName: string, span: TextSpan): Classifications; + getCompletionsAtPosition(fileName: string, position: number, options: GetCompletionsAtPositionOptions | undefined): WithMetadata | undefined; + getCompletionEntryDetails(fileName: string, position: number, name: string, formatOptions: FormatCodeOptions | FormatCodeSettings | undefined, source: string | undefined, preferences: UserPreferences | undefined): CompletionEntryDetails | undefined; + getCompletionEntrySymbol(fileName: string, position: number, name: string, source: string | undefined): Symbol | undefined; + getQuickInfoAtPosition(fileName: string, position: number): QuickInfo | undefined; + getNameOrDottedNameSpan(fileName: string, startPos: number, endPos: number): TextSpan | undefined; + getBreakpointStatementAtPosition(fileName: string, position: number): TextSpan | undefined; + getSignatureHelpItems(fileName: string, position: number, options: SignatureHelpItemsOptions | undefined): SignatureHelpItems | undefined; + getRenameInfo(fileName: string, position: number): RenameInfo; + findRenameLocations(fileName: string, position: number, findInStrings: boolean, findInComments: boolean): ReadonlyArray | undefined; + getDefinitionAtPosition(fileName: string, position: number): ReadonlyArray | undefined; + getDefinitionAndBoundSpan(fileName: string, position: number): DefinitionInfoAndBoundSpan | undefined; + getTypeDefinitionAtPosition(fileName: string, position: number): ReadonlyArray | undefined; + getImplementationAtPosition(fileName: string, position: number): ReadonlyArray | undefined; + getReferencesAtPosition(fileName: string, position: number): ReferenceEntry[] | undefined; + findReferences(fileName: string, position: number): ReferencedSymbol[] | undefined; + getDocumentHighlights(fileName: string, position: number, filesToSearch: string[]): DocumentHighlights[] | undefined; + /** @deprecated */ + getOccurrencesAtPosition(fileName: string, position: number): ReadonlyArray | undefined; + getNavigateToItems(searchValue: string, maxResultCount?: number, fileName?: string, excludeDtsFiles?: boolean): NavigateToItem[]; + getNavigationBarItems(fileName: string): NavigationBarItem[]; + getNavigationTree(fileName: string): NavigationTree; + getOutliningSpans(fileName: string): OutliningSpan[]; + getTodoComments(fileName: string, descriptors: TodoCommentDescriptor[]): TodoComment[]; + getBraceMatchingAtPosition(fileName: string, position: number): TextSpan[]; + getIndentationAtPosition(fileName: string, position: number, options: EditorOptions | EditorSettings): number; + getFormattingEditsForRange(fileName: string, start: number, end: number, options: FormatCodeOptions | FormatCodeSettings): TextChange[]; + getFormattingEditsForDocument(fileName: string, options: FormatCodeOptions | FormatCodeSettings): TextChange[]; + getFormattingEditsAfterKeystroke(fileName: string, position: number, key: string, options: FormatCodeOptions | FormatCodeSettings): TextChange[]; + getDocCommentTemplateAtPosition(fileName: string, position: number): TextInsertion | undefined; + isValidBraceCompletionAtPosition(fileName: string, position: number, openingBrace: number): boolean; + /** + * This will return a defined result if the position is after the `>` of the opening tag, or somewhere in the text, of a JSXElement with no closing tag. + * Editors should call this after `>` is typed. + */ + getJsxClosingTagAtPosition(fileName: string, position: number): JsxClosingTagInfo | undefined; + getSpanOfEnclosingComment(fileName: string, position: number, onlyMultiLine: boolean): TextSpan | undefined; + toLineColumnOffset?(fileName: string, position: number): LineAndCharacter; + getCodeFixesAtPosition(fileName: string, start: number, end: number, errorCodes: ReadonlyArray, formatOptions: FormatCodeSettings, preferences: UserPreferences): ReadonlyArray; + getCombinedCodeFix(scope: CombinedCodeFixScope, fixId: {}, formatOptions: FormatCodeSettings, preferences: UserPreferences): CombinedCodeActions; + applyCodeActionCommand(action: CodeActionCommand, formatSettings?: FormatCodeSettings): Promise; + applyCodeActionCommand(action: CodeActionCommand[], formatSettings?: FormatCodeSettings): Promise; + applyCodeActionCommand(action: CodeActionCommand | CodeActionCommand[], formatSettings?: FormatCodeSettings): Promise; + /** @deprecated `fileName` will be ignored */ + applyCodeActionCommand(fileName: string, action: CodeActionCommand): Promise; + /** @deprecated `fileName` will be ignored */ + applyCodeActionCommand(fileName: string, action: CodeActionCommand[]): Promise; + /** @deprecated `fileName` will be ignored */ + applyCodeActionCommand(fileName: string, action: CodeActionCommand | CodeActionCommand[]): Promise; + getApplicableRefactors(fileName: string, positionOrRange: number | TextRange, preferences: UserPreferences | undefined): ApplicableRefactorInfo[]; + getEditsForRefactor(fileName: string, formatOptions: FormatCodeSettings, positionOrRange: number | TextRange, refactorName: string, actionName: string, preferences: UserPreferences | undefined): RefactorEditInfo | undefined; + organizeImports(scope: OrganizeImportsScope, formatOptions: FormatCodeSettings, preferences: UserPreferences | undefined): ReadonlyArray; + getEditsForFileRename(oldFilePath: string, newFilePath: string, formatOptions: FormatCodeSettings, preferences: UserPreferences | undefined): ReadonlyArray; + getEmitOutput(fileName: string, emitOnlyDtsFiles?: boolean): EmitOutput; + getProgram(): Program | undefined; + dispose(): void; + } + interface JsxClosingTagInfo { + readonly newText: string; + } + interface CombinedCodeFixScope { + type: "file"; + fileName: string; + } + type OrganizeImportsScope = CombinedCodeFixScope; + type CompletionsTriggerCharacter = "." | '"' | "'" | "`" | "/" | "@" | "<"; + interface GetCompletionsAtPositionOptions extends UserPreferences { + /** + * If the editor is asking for completions because a certain character was typed + * (as opposed to when the user explicitly requested them) this should be set. + */ + triggerCharacter?: CompletionsTriggerCharacter; + /** @deprecated Use includeCompletionsForModuleExports */ + includeExternalModuleExports?: boolean; + /** @deprecated Use includeCompletionsWithInsertText */ + includeInsertTextCompletions?: boolean; + } + type SignatureHelpTriggerCharacter = "," | "(" | "<"; + type SignatureHelpRetriggerCharacter = SignatureHelpTriggerCharacter | ")"; + interface SignatureHelpItemsOptions { + triggerReason?: SignatureHelpTriggerReason; + } + type SignatureHelpTriggerReason = SignatureHelpInvokedReason | SignatureHelpCharacterTypedReason | SignatureHelpRetriggeredReason; + /** + * Signals that the user manually requested signature help. + * The language service will unconditionally attempt to provide a result. + */ + interface SignatureHelpInvokedReason { + kind: "invoked"; + triggerCharacter?: undefined; + } + /** + * Signals that the signature help request came from a user typing a character. + * Depending on the character and the syntactic context, the request may or may not be served a result. + */ + interface SignatureHelpCharacterTypedReason { + kind: "characterTyped"; + /** + * Character that was responsible for triggering signature help. + */ + triggerCharacter: SignatureHelpTriggerCharacter; + } + /** + * Signals that this signature help request came from typing a character or moving the cursor. + * This should only occur if a signature help session was already active and the editor needs to see if it should adjust. + * The language service will unconditionally attempt to provide a result. + * `triggerCharacter` can be `undefined` for a retrigger caused by a cursor move. + */ + interface SignatureHelpRetriggeredReason { + kind: "retrigger"; + /** + * Character that was responsible for triggering signature help. + */ + triggerCharacter?: SignatureHelpRetriggerCharacter; + } + interface ApplyCodeActionCommandResult { + successMessage: string; + } + interface Classifications { + spans: number[]; + endOfLineState: EndOfLineState; + } + interface ClassifiedSpan { + textSpan: TextSpan; + classificationType: ClassificationTypeNames; + } + /** + * Navigation bar interface designed for visual studio's dual-column layout. + * This does not form a proper tree. + * The navbar is returned as a list of top-level items, each of which has a list of child items. + * Child items always have an empty array for their `childItems`. + */ + interface NavigationBarItem { + text: string; + kind: ScriptElementKind; + kindModifiers: string; + spans: TextSpan[]; + childItems: NavigationBarItem[]; + indent: number; + bolded: boolean; + grayed: boolean; + } + /** + * Node in a tree of nested declarations in a file. + * The top node is always a script or module node. + */ + interface NavigationTree { + /** Name of the declaration, or a short description, e.g. "". */ + text: string; + kind: ScriptElementKind; + /** ScriptElementKindModifier separated by commas, e.g. "public,abstract" */ + kindModifiers: string; + /** + * Spans of the nodes that generated this declaration. + * There will be more than one if this is the result of merging. + */ + spans: TextSpan[]; + nameSpan: TextSpan | undefined; + /** Present if non-empty */ + childItems?: NavigationTree[]; + } + interface TodoCommentDescriptor { + text: string; + priority: number; + } + interface TodoComment { + descriptor: TodoCommentDescriptor; + message: string; + position: number; + } + interface TextChange { + span: TextSpan; + newText: string; + } + interface FileTextChanges { + fileName: string; + textChanges: TextChange[]; + isNewFile?: boolean; + } + interface CodeAction { + /** Description of the code action to display in the UI of the editor */ + description: string; + /** Text changes to apply to each file as part of the code action */ + changes: FileTextChanges[]; + /** + * If the user accepts the code fix, the editor should send the action back in a `applyAction` request. + * This allows the language service to have side effects (e.g. installing dependencies) upon a code fix. + */ + commands?: CodeActionCommand[]; + } + interface CodeFixAction extends CodeAction { + /** Short name to identify the fix, for use by telemetry. */ + fixName: string; + /** + * If present, one may call 'getCombinedCodeFix' with this fixId. + * This may be omitted to indicate that the code fix can't be applied in a group. + */ + fixId?: {}; + fixAllDescription?: string; + } + interface CombinedCodeActions { + changes: ReadonlyArray; + commands?: ReadonlyArray; + } + type CodeActionCommand = InstallPackageAction | GenerateTypesAction; + interface InstallPackageAction { + } + interface GenerateTypesAction extends GenerateTypesOptions { + } + interface GenerateTypesOptions { + readonly file: string; + readonly fileToGenerateTypesFor: string; + readonly outputFileName: string; + } + /** + * A set of one or more available refactoring actions, grouped under a parent refactoring. + */ + interface ApplicableRefactorInfo { + /** + * The programmatic name of the refactoring + */ + name: string; + /** + * A description of this refactoring category to show to the user. + * If the refactoring gets inlined (see below), this text will not be visible. + */ + description: string; + /** + * Inlineable refactorings can have their actions hoisted out to the top level + * of a context menu. Non-inlineanable refactorings should always be shown inside + * their parent grouping. + * + * If not specified, this value is assumed to be 'true' + */ + inlineable?: boolean; + actions: RefactorActionInfo[]; + } + /** + * Represents a single refactoring action - for example, the "Extract Method..." refactor might + * offer several actions, each corresponding to a surround class or closure to extract into. + */ + interface RefactorActionInfo { + /** + * The programmatic name of the refactoring action + */ + name: string; + /** + * A description of this refactoring action to show to the user. + * If the parent refactoring is inlined away, this will be the only text shown, + * so this description should make sense by itself if the parent is inlineable=true + */ + description: string; + } + /** + * A set of edits to make in response to a refactor action, plus an optional + * location where renaming should be invoked from + */ + interface RefactorEditInfo { + edits: FileTextChanges[]; + renameFilename?: string; + renameLocation?: number; + commands?: CodeActionCommand[]; + } + interface TextInsertion { + newText: string; + /** The position in newText the caret should point to after the insertion. */ + caretOffset: number; + } + interface DocumentSpan { + textSpan: TextSpan; + fileName: string; + /** + * If the span represents a location that was remapped (e.g. via a .d.ts.map file), + * then the original filename and span will be specified here + */ + originalTextSpan?: TextSpan; + originalFileName?: string; + } + interface RenameLocation extends DocumentSpan { + readonly prefixText?: string; + readonly suffixText?: string; + } + interface ReferenceEntry extends DocumentSpan { + isWriteAccess: boolean; + isDefinition: boolean; + isInString?: true; + } + interface ImplementationLocation extends DocumentSpan { + kind: ScriptElementKind; + displayParts: SymbolDisplayPart[]; + } + interface DocumentHighlights { + fileName: string; + highlightSpans: HighlightSpan[]; + } + enum HighlightSpanKind { + none = "none", + definition = "definition", + reference = "reference", + writtenReference = "writtenReference" + } + interface HighlightSpan { + fileName?: string; + isInString?: true; + textSpan: TextSpan; + kind: HighlightSpanKind; + } + interface NavigateToItem { + name: string; + kind: ScriptElementKind; + kindModifiers: string; + matchKind: "exact" | "prefix" | "substring" | "camelCase"; + isCaseSensitive: boolean; + fileName: string; + textSpan: TextSpan; + containerName: string; + containerKind: ScriptElementKind; + } + enum IndentStyle { + None = 0, + Block = 1, + Smart = 2 + } + interface EditorOptions { + BaseIndentSize?: number; + IndentSize: number; + TabSize: number; + NewLineCharacter: string; + ConvertTabsToSpaces: boolean; + IndentStyle: IndentStyle; + } + interface EditorSettings { + baseIndentSize?: number; + indentSize?: number; + tabSize?: number; + newLineCharacter?: string; + convertTabsToSpaces?: boolean; + indentStyle?: IndentStyle; + } + interface FormatCodeOptions extends EditorOptions { + InsertSpaceAfterCommaDelimiter: boolean; + InsertSpaceAfterSemicolonInForStatements: boolean; + InsertSpaceBeforeAndAfterBinaryOperators: boolean; + InsertSpaceAfterConstructor?: boolean; + InsertSpaceAfterKeywordsInControlFlowStatements: boolean; + InsertSpaceAfterFunctionKeywordForAnonymousFunctions: boolean; + InsertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: boolean; + InsertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: boolean; + InsertSpaceAfterOpeningAndBeforeClosingNonemptyBraces?: boolean; + InsertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: boolean; + InsertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces?: boolean; + InsertSpaceAfterTypeAssertion?: boolean; + InsertSpaceBeforeFunctionParenthesis?: boolean; + PlaceOpenBraceOnNewLineForFunctions: boolean; + PlaceOpenBraceOnNewLineForControlBlocks: boolean; + insertSpaceBeforeTypeAnnotation?: boolean; + } + interface FormatCodeSettings extends EditorSettings { + readonly insertSpaceAfterCommaDelimiter?: boolean; + readonly insertSpaceAfterSemicolonInForStatements?: boolean; + readonly insertSpaceBeforeAndAfterBinaryOperators?: boolean; + readonly insertSpaceAfterConstructor?: boolean; + readonly insertSpaceAfterKeywordsInControlFlowStatements?: boolean; + readonly insertSpaceAfterFunctionKeywordForAnonymousFunctions?: boolean; + readonly insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis?: boolean; + readonly insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets?: boolean; + readonly insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces?: boolean; + readonly insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces?: boolean; + readonly insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces?: boolean; + readonly insertSpaceAfterTypeAssertion?: boolean; + readonly insertSpaceBeforeFunctionParenthesis?: boolean; + readonly placeOpenBraceOnNewLineForFunctions?: boolean; + readonly placeOpenBraceOnNewLineForControlBlocks?: boolean; + readonly insertSpaceBeforeTypeAnnotation?: boolean; + readonly indentMultiLineObjectLiteralBeginningOnBlankLine?: boolean; + } + function getDefaultFormatCodeSettings(newLineCharacter?: string): FormatCodeSettings; + interface DefinitionInfo extends DocumentSpan { + kind: ScriptElementKind; + name: string; + containerKind: ScriptElementKind; + containerName: string; + } + interface DefinitionInfoAndBoundSpan { + definitions?: ReadonlyArray; + textSpan: TextSpan; + } + interface ReferencedSymbolDefinitionInfo extends DefinitionInfo { + displayParts: SymbolDisplayPart[]; + } + interface ReferencedSymbol { + definition: ReferencedSymbolDefinitionInfo; + references: ReferenceEntry[]; + } + enum SymbolDisplayPartKind { + aliasName = 0, + className = 1, + enumName = 2, + fieldName = 3, + interfaceName = 4, + keyword = 5, + lineBreak = 6, + numericLiteral = 7, + stringLiteral = 8, + localName = 9, + methodName = 10, + moduleName = 11, + operator = 12, + parameterName = 13, + propertyName = 14, + punctuation = 15, + space = 16, + text = 17, + typeParameterName = 18, + enumMemberName = 19, + functionName = 20, + regularExpressionLiteral = 21 + } + interface SymbolDisplayPart { + text: string; + kind: string; + } + interface JSDocTagInfo { + name: string; + text?: string; + } + interface QuickInfo { + kind: ScriptElementKind; + kindModifiers: string; + textSpan: TextSpan; + displayParts?: SymbolDisplayPart[]; + documentation?: SymbolDisplayPart[]; + tags?: JSDocTagInfo[]; + } + type RenameInfo = RenameInfoSuccess | RenameInfoFailure; + interface RenameInfoSuccess { + canRename: true; + /** + * File or directory to rename. + * If set, `getEditsForFileRename` should be called instead of `findRenameLocations`. + */ + fileToRename?: string; + displayName: string; + fullDisplayName: string; + kind: ScriptElementKind; + kindModifiers: string; + triggerSpan: TextSpan; + } + interface RenameInfoFailure { + canRename: false; + localizedErrorMessage: string; + } + interface SignatureHelpParameter { + name: string; + documentation: SymbolDisplayPart[]; + displayParts: SymbolDisplayPart[]; + isOptional: boolean; + } + /** + * Represents a single signature to show in signature help. + * The id is used for subsequent calls into the language service to ask questions about the + * signature help item in the context of any documents that have been updated. i.e. after + * an edit has happened, while signature help is still active, the host can ask important + * questions like 'what parameter is the user currently contained within?'. + */ + interface SignatureHelpItem { + isVariadic: boolean; + prefixDisplayParts: SymbolDisplayPart[]; + suffixDisplayParts: SymbolDisplayPart[]; + separatorDisplayParts: SymbolDisplayPart[]; + parameters: SignatureHelpParameter[]; + documentation: SymbolDisplayPart[]; + tags: JSDocTagInfo[]; + } + /** + * Represents a set of signature help items, and the preferred item that should be selected. + */ + interface SignatureHelpItems { + items: SignatureHelpItem[]; + applicableSpan: TextSpan; + selectedItemIndex: number; + argumentIndex: number; + argumentCount: number; + } + interface CompletionInfo { + /** Not true for all glboal completions. This will be true if the enclosing scope matches a few syntax kinds. See `isSnippetScope`. */ + isGlobalCompletion: boolean; + isMemberCompletion: boolean; + /** + * true when the current location also allows for a new identifier + */ + isNewIdentifierLocation: boolean; + entries: CompletionEntry[]; + } + interface CompletionEntry { + name: string; + kind: ScriptElementKind; + kindModifiers?: string; + sortText: string; + insertText?: string; + /** + * An optional span that indicates the text to be replaced by this completion item. + * If present, this span should be used instead of the default one. + * It will be set if the required span differs from the one generated by the default replacement behavior. + */ + replacementSpan?: TextSpan; + hasAction?: true; + source?: string; + isRecommended?: true; + } + interface CompletionEntryDetails { + name: string; + kind: ScriptElementKind; + kindModifiers: string; + displayParts: SymbolDisplayPart[]; + documentation?: SymbolDisplayPart[]; + tags?: JSDocTagInfo[]; + codeActions?: CodeAction[]; + source?: SymbolDisplayPart[]; + } + interface OutliningSpan { + /** The span of the document to actually collapse. */ + textSpan: TextSpan; + /** The span of the document to display when the user hovers over the collapsed span. */ + hintSpan: TextSpan; + /** The text to display in the editor for the collapsed region. */ + bannerText: string; + /** + * Whether or not this region should be automatically collapsed when + * the 'Collapse to Definitions' command is invoked. + */ + autoCollapse: boolean; + /** + * Classification of the contents of the span + */ + kind: OutliningSpanKind; + } + enum OutliningSpanKind { + /** Single or multi-line comments */ + Comment = "comment", + /** Sections marked by '// #region' and '// #endregion' comments */ + Region = "region", + /** Declarations and expressions */ + Code = "code", + /** Contiguous blocks of import declarations */ + Imports = "imports" + } + enum OutputFileType { + JavaScript = 0, + SourceMap = 1, + Declaration = 2 + } + enum EndOfLineState { + None = 0, + InMultiLineCommentTrivia = 1, + InSingleQuoteStringLiteral = 2, + InDoubleQuoteStringLiteral = 3, + InTemplateHeadOrNoSubstitutionTemplate = 4, + InTemplateMiddleOrTail = 5, + InTemplateSubstitutionPosition = 6 + } + enum TokenClass { + Punctuation = 0, + Keyword = 1, + Operator = 2, + Comment = 3, + Whitespace = 4, + Identifier = 5, + NumberLiteral = 6, + BigIntLiteral = 7, + StringLiteral = 8, + RegExpLiteral = 9 + } + interface ClassificationResult { + finalLexState: EndOfLineState; + entries: ClassificationInfo[]; + } + interface ClassificationInfo { + length: number; + classification: TokenClass; + } + interface Classifier { + /** + * Gives lexical classifications of tokens on a line without any syntactic context. + * For instance, a token consisting of the text 'string' can be either an identifier + * named 'string' or the keyword 'string', however, because this classifier is not aware, + * it relies on certain heuristics to give acceptable results. For classifications where + * speed trumps accuracy, this function is preferable; however, for true accuracy, the + * syntactic classifier is ideal. In fact, in certain editing scenarios, combining the + * lexical, syntactic, and semantic classifiers may issue the best user experience. + * + * @param text The text of a line to classify. + * @param lexState The state of the lexical classifier at the end of the previous line. + * @param syntacticClassifierAbsent Whether the client is *not* using a syntactic classifier. + * If there is no syntactic classifier (syntacticClassifierAbsent=true), + * certain heuristics may be used in its place; however, if there is a + * syntactic classifier (syntacticClassifierAbsent=false), certain + * classifications which may be incorrectly categorized will be given + * back as Identifiers in order to allow the syntactic classifier to + * subsume the classification. + * @deprecated Use getLexicalClassifications instead. + */ + getClassificationsForLine(text: string, lexState: EndOfLineState, syntacticClassifierAbsent: boolean): ClassificationResult; + getEncodedLexicalClassifications(text: string, endOfLineState: EndOfLineState, syntacticClassifierAbsent: boolean): Classifications; + } + enum ScriptElementKind { + unknown = "", + warning = "warning", + /** predefined type (void) or keyword (class) */ + keyword = "keyword", + /** top level script node */ + scriptElement = "script", + /** module foo {} */ + moduleElement = "module", + /** class X {} */ + classElement = "class", + /** var x = class X {} */ + localClassElement = "local class", + /** interface Y {} */ + interfaceElement = "interface", + /** type T = ... */ + typeElement = "type", + /** enum E */ + enumElement = "enum", + enumMemberElement = "enum member", + /** + * Inside module and script only + * const v = .. + */ + variableElement = "var", + /** Inside function */ + localVariableElement = "local var", + /** + * Inside module and script only + * function f() { } + */ + functionElement = "function", + /** Inside function */ + localFunctionElement = "local function", + /** class X { [public|private]* foo() {} } */ + memberFunctionElement = "method", + /** class X { [public|private]* [get|set] foo:number; } */ + memberGetAccessorElement = "getter", + memberSetAccessorElement = "setter", + /** + * class X { [public|private]* foo:number; } + * interface Y { foo:number; } + */ + memberVariableElement = "property", + /** class X { constructor() { } } */ + constructorImplementationElement = "constructor", + /** interface Y { ():number; } */ + callSignatureElement = "call", + /** interface Y { []:number; } */ + indexSignatureElement = "index", + /** interface Y { new():Y; } */ + constructSignatureElement = "construct", + /** function foo(*Y*: string) */ + parameterElement = "parameter", + typeParameterElement = "type parameter", + primitiveType = "primitive type", + label = "label", + alias = "alias", + constElement = "const", + letElement = "let", + directory = "directory", + externalModuleName = "external module name", + /** + * + */ + jsxAttribute = "JSX attribute", + /** String literal */ + string = "string" + } + enum ScriptElementKindModifier { + none = "", + publicMemberModifier = "public", + privateMemberModifier = "private", + protectedMemberModifier = "protected", + exportedModifier = "export", + ambientModifier = "declare", + staticModifier = "static", + abstractModifier = "abstract", + optionalModifier = "optional", + dtsModifier = ".d.ts", + tsModifier = ".ts", + tsxModifier = ".tsx", + jsModifier = ".js", + jsxModifier = ".jsx", + jsonModifier = ".json" + } + enum ClassificationTypeNames { + comment = "comment", + identifier = "identifier", + keyword = "keyword", + numericLiteral = "number", + bigintLiteral = "bigint", + operator = "operator", + stringLiteral = "string", + whiteSpace = "whitespace", + text = "text", + punctuation = "punctuation", + className = "class name", + enumName = "enum name", + interfaceName = "interface name", + moduleName = "module name", + typeParameterName = "type parameter name", + typeAliasName = "type alias name", + parameterName = "parameter name", + docCommentTagName = "doc comment tag name", + jsxOpenTagName = "jsx open tag name", + jsxCloseTagName = "jsx close tag name", + jsxSelfClosingTagName = "jsx self closing tag name", + jsxAttribute = "jsx attribute", + jsxText = "jsx text", + jsxAttributeStringLiteralValue = "jsx attribute string literal value" + } + enum ClassificationType { + comment = 1, + identifier = 2, + keyword = 3, + numericLiteral = 4, + operator = 5, + stringLiteral = 6, + regularExpressionLiteral = 7, + whiteSpace = 8, + text = 9, + punctuation = 10, + className = 11, + enumName = 12, + interfaceName = 13, + moduleName = 14, + typeParameterName = 15, + typeAliasName = 16, + parameterName = 17, + docCommentTagName = 18, + jsxOpenTagName = 19, + jsxCloseTagName = 20, + jsxSelfClosingTagName = 21, + jsxAttribute = 22, + jsxText = 23, + jsxAttributeStringLiteralValue = 24, + bigintLiteral = 25 + } +} +declare namespace ts { + function createClassifier(): Classifier; +} +declare namespace ts { + /** + * The document registry represents a store of SourceFile objects that can be shared between + * multiple LanguageService instances. A LanguageService instance holds on the SourceFile (AST) + * of files in the context. + * SourceFile objects account for most of the memory usage by the language service. Sharing + * the same DocumentRegistry instance between different instances of LanguageService allow + * for more efficient memory utilization since all projects will share at least the library + * file (lib.d.ts). + * + * A more advanced use of the document registry is to serialize sourceFile objects to disk + * and re-hydrate them when needed. + * + * To create a default DocumentRegistry, use createDocumentRegistry to create one, and pass it + * to all subsequent createLanguageService calls. + */ + interface DocumentRegistry { + /** + * Request a stored SourceFile with a given fileName and compilationSettings. + * The first call to acquire will call createLanguageServiceSourceFile to generate + * the SourceFile if was not found in the registry. + * + * @param fileName The name of the file requested + * @param compilationSettings Some compilation settings like target affects the + * shape of a the resulting SourceFile. This allows the DocumentRegistry to store + * multiple copies of the same file for different compilation settings. + * @param scriptSnapshot Text of the file. Only used if the file was not found + * in the registry and a new one was created. + * @param version Current version of the file. Only used if the file was not found + * in the registry and a new one was created. + */ + acquireDocument(fileName: string, compilationSettings: CompilerOptions, scriptSnapshot: IScriptSnapshot, version: string, scriptKind?: ScriptKind): SourceFile; + acquireDocumentWithKey(fileName: string, path: Path, compilationSettings: CompilerOptions, key: DocumentRegistryBucketKey, scriptSnapshot: IScriptSnapshot, version: string, scriptKind?: ScriptKind): SourceFile; + /** + * Request an updated version of an already existing SourceFile with a given fileName + * and compilationSettings. The update will in-turn call updateLanguageServiceSourceFile + * to get an updated SourceFile. + * + * @param fileName The name of the file requested + * @param compilationSettings Some compilation settings like target affects the + * shape of a the resulting SourceFile. This allows the DocumentRegistry to store + * multiple copies of the same file for different compilation settings. + * @param scriptSnapshot Text of the file. + * @param version Current version of the file. + */ + updateDocument(fileName: string, compilationSettings: CompilerOptions, scriptSnapshot: IScriptSnapshot, version: string, scriptKind?: ScriptKind): SourceFile; + updateDocumentWithKey(fileName: string, path: Path, compilationSettings: CompilerOptions, key: DocumentRegistryBucketKey, scriptSnapshot: IScriptSnapshot, version: string, scriptKind?: ScriptKind): SourceFile; + getKeyForCompilationSettings(settings: CompilerOptions): DocumentRegistryBucketKey; + /** + * Informs the DocumentRegistry that a file is not needed any longer. + * + * Note: It is not allowed to call release on a SourceFile that was not acquired from + * this registry originally. + * + * @param fileName The name of the file to be released + * @param compilationSettings The compilation settings used to acquire the file + */ + releaseDocument(fileName: string, compilationSettings: CompilerOptions): void; + releaseDocumentWithKey(path: Path, key: DocumentRegistryBucketKey): void; + reportStats(): string; + } + type DocumentRegistryBucketKey = string & { + __bucketKey: any; + }; + function createDocumentRegistry(useCaseSensitiveFileNames?: boolean, currentDirectory?: string): DocumentRegistry; +} +declare namespace ts { + function preProcessFile(sourceText: string, readImportFiles?: boolean, detectJavaScriptImports?: boolean): PreProcessedFileInfo; +} +declare namespace ts { + interface TranspileOptions { + compilerOptions?: CompilerOptions; + fileName?: string; + reportDiagnostics?: boolean; + moduleName?: string; + renamedDependencies?: MapLike; + transformers?: CustomTransformers; + } + interface TranspileOutput { + outputText: string; + diagnostics?: Diagnostic[]; + sourceMapText?: string; + } + function transpileModule(input: string, transpileOptions: TranspileOptions): TranspileOutput; + function transpile(input: string, compilerOptions?: CompilerOptions, fileName?: string, diagnostics?: Diagnostic[], moduleName?: string): string; +} +declare namespace ts { + function generateTypesForModule(name: string, moduleValue: unknown, formatSettings: FormatCodeSettings): string; + function generateTypesForGlobal(name: string, globalValue: unknown, formatSettings: FormatCodeSettings): string; +} +declare namespace ts { + /** The version of the language service API */ + const servicesVersion = "0.8"; + function toEditorSettings(options: EditorOptions | EditorSettings): EditorSettings; + function displayPartsToString(displayParts: SymbolDisplayPart[] | undefined): string; + function getDefaultCompilerOptions(): CompilerOptions; + function getSupportedCodeFixes(): string[]; + function createLanguageServiceSourceFile(fileName: string, scriptSnapshot: IScriptSnapshot, scriptTarget: ScriptTarget, version: string, setNodeParents: boolean, scriptKind?: ScriptKind): SourceFile; + let disableIncrementalParsing: boolean; + function updateLanguageServiceSourceFile(sourceFile: SourceFile, scriptSnapshot: IScriptSnapshot, version: string, textChangeRange: TextChangeRange | undefined, aggressiveChecks?: boolean): SourceFile; + function createLanguageService(host: LanguageServiceHost, documentRegistry?: DocumentRegistry, syntaxOnly?: boolean): LanguageService; + /** + * Get the path of the default library files (lib.d.ts) as distributed with the typescript + * node package. + * The functionality is not supported if the ts module is consumed outside of a node module. + */ + function getDefaultLibFilePath(options: CompilerOptions): string; +} +declare namespace ts { + /** + * Transform one or more nodes using the supplied transformers. + * @param source A single `Node` or an array of `Node` objects. + * @param transformers An array of `TransformerFactory` callbacks used to process the transformation. + * @param compilerOptions Optional compiler options. + */ + function transform(source: T | T[], transformers: TransformerFactory[], compilerOptions?: CompilerOptions): TransformationResult; +} + +export = ts; \ No newline at end of file diff --git a/node_modules/typescript/lib/typescript.js b/node_modules/typescript/lib/typescript.js new file mode 100644 index 0000000..2a87d69 --- /dev/null +++ b/node_modules/typescript/lib/typescript.js @@ -0,0 +1,119806 @@ +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + +"use strict"; +var __assign = (this && this.__assign) || function () { + __assign = Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; + }; + return __assign.apply(this, arguments); +}; +var __generator = (this && this.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } +}; +var __makeTemplateObject = (this && this.__makeTemplateObject) || function (cooked, raw) { + if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } + return cooked; +}; +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +var ts; +(function (ts) { + // WARNING: The script `configureNightly.ts` uses a regexp to parse out these values. + // If changing the text in this section, be sure to test `configureNightly` too. + ts.versionMajorMinor = "3.2"; + /** The version of the TypeScript compiler release */ + ts.version = ts.versionMajorMinor + ".2"; +})(ts || (ts = {})); +(function (ts) { + /* @internal */ + var Comparison; + (function (Comparison) { + Comparison[Comparison["LessThan"] = -1] = "LessThan"; + Comparison[Comparison["EqualTo"] = 0] = "EqualTo"; + Comparison[Comparison["GreaterThan"] = 1] = "GreaterThan"; + })(Comparison = ts.Comparison || (ts.Comparison = {})); +})(ts || (ts = {})); +/* @internal */ +(function (ts) { + ts.emptyArray = []; + /** Create a MapLike with good performance. */ + function createDictionaryObject() { + var map = Object.create(/*prototype*/ null); // tslint:disable-line:no-null-keyword + // Using 'delete' on an object causes V8 to put the object in dictionary mode. + // This disables creation of hidden classes, which are expensive when an object is + // constantly changing shape. + map.__ = undefined; + delete map.__; + return map; + } + /** Create a new map. If a template object is provided, the map will copy entries from it. */ + function createMap() { + return new ts.MapCtr(); + } + ts.createMap = createMap; + function createMapFromEntries(entries) { + var map = createMap(); + for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) { + var _a = entries_1[_i], key = _a[0], value = _a[1]; + map.set(key, value); + } + return map; + } + ts.createMapFromEntries = createMapFromEntries; + function createMapFromTemplate(template) { + var map = new ts.MapCtr(); + // Copies keys/values from template. Note that for..in will not throw if + // template is undefined, and instead will just exit the loop. + for (var key in template) { + if (hasOwnProperty.call(template, key)) { + map.set(key, template[key]); + } + } + return map; + } + ts.createMapFromTemplate = createMapFromTemplate; + // Internet Explorer's Map doesn't support iteration, so don't use it. + // tslint:disable-next-line no-in-operator variable-name + ts.MapCtr = typeof Map !== "undefined" && "entries" in Map.prototype ? Map : shimMap(); + // Keep the class inside a function so it doesn't get compiled if it's not used. + function shimMap() { + var MapIterator = /** @class */ (function () { + function MapIterator(data, selector) { + this.index = 0; + this.data = data; + this.selector = selector; + this.keys = Object.keys(data); + } + MapIterator.prototype.next = function () { + var index = this.index; + if (index < this.keys.length) { + this.index++; + return { value: this.selector(this.data, this.keys[index]), done: false }; + } + return { value: undefined, done: true }; + }; + return MapIterator; + }()); + return /** @class */ (function () { + function class_1() { + this.data = createDictionaryObject(); + this.size = 0; + } + class_1.prototype.get = function (key) { + return this.data[key]; + }; + class_1.prototype.set = function (key, value) { + if (!this.has(key)) { + this.size++; + } + this.data[key] = value; + return this; + }; + class_1.prototype.has = function (key) { + // tslint:disable-next-line:no-in-operator + return key in this.data; + }; + class_1.prototype.delete = function (key) { + if (this.has(key)) { + this.size--; + delete this.data[key]; + return true; + } + return false; + }; + class_1.prototype.clear = function () { + this.data = createDictionaryObject(); + this.size = 0; + }; + class_1.prototype.keys = function () { + return new MapIterator(this.data, function (_data, key) { return key; }); + }; + class_1.prototype.values = function () { + return new MapIterator(this.data, function (data, key) { return data[key]; }); + }; + class_1.prototype.entries = function () { + return new MapIterator(this.data, function (data, key) { return [key, data[key]]; }); + }; + class_1.prototype.forEach = function (action) { + for (var key in this.data) { + action(this.data[key], key); + } + }; + return class_1; + }()); + } + function length(array) { + return array ? array.length : 0; + } + ts.length = length; + /** + * Iterates through 'array' by index and performs the callback on each element of array until the callback + * returns a truthy value, then returns that value. + * If no such value is found, the callback is applied to each element of array and undefined is returned. + */ + function forEach(array, callback) { + if (array) { + for (var i = 0; i < array.length; i++) { + var result = callback(array[i], i); + if (result) { + return result; + } + } + } + return undefined; + } + ts.forEach = forEach; + /** Like `forEach`, but suitable for use with numbers and strings (which may be falsy). */ + function firstDefined(array, callback) { + if (array === undefined) { + return undefined; + } + for (var i = 0; i < array.length; i++) { + var result = callback(array[i], i); + if (result !== undefined) { + return result; + } + } + return undefined; + } + ts.firstDefined = firstDefined; + function firstDefinedIterator(iter, callback) { + while (true) { + var _a = iter.next(), value = _a.value, done = _a.done; + if (done) { + return undefined; + } + var result = callback(value); + if (result !== undefined) { + return result; + } + } + } + ts.firstDefinedIterator = firstDefinedIterator; + function zipWith(arrayA, arrayB, callback) { + var result = []; + Debug.assertEqual(arrayA.length, arrayB.length); + for (var i = 0; i < arrayA.length; i++) { + result.push(callback(arrayA[i], arrayB[i], i)); + } + return result; + } + ts.zipWith = zipWith; + function zipToIterator(arrayA, arrayB) { + Debug.assertEqual(arrayA.length, arrayB.length); + var i = 0; + return { + next: function () { + if (i === arrayA.length) { + return { value: undefined, done: true }; + } + i++; + return { value: [arrayA[i - 1], arrayB[i - 1]], done: false }; + } + }; + } + ts.zipToIterator = zipToIterator; + function zipToMap(keys, values) { + Debug.assert(keys.length === values.length); + var map = createMap(); + for (var i = 0; i < keys.length; ++i) { + map.set(keys[i], values[i]); + } + return map; + } + ts.zipToMap = zipToMap; + /** + * Iterates through `array` by index and performs the callback on each element of array until the callback + * returns a falsey value, then returns false. + * If no such value is found, the callback is applied to each element of array and `true` is returned. + */ + function every(array, callback) { + if (array) { + for (var i = 0; i < array.length; i++) { + if (!callback(array[i], i)) { + return false; + } + } + } + return true; + } + ts.every = every; + function find(array, predicate) { + for (var i = 0; i < array.length; i++) { + var value = array[i]; + if (predicate(value, i)) { + return value; + } + } + return undefined; + } + ts.find = find; + function findLast(array, predicate) { + for (var i = array.length - 1; i >= 0; i--) { + var value = array[i]; + if (predicate(value, i)) { + return value; + } + } + return undefined; + } + ts.findLast = findLast; + /** Works like Array.prototype.findIndex, returning `-1` if no element satisfying the predicate is found. */ + function findIndex(array, predicate, startIndex) { + for (var i = startIndex || 0; i < array.length; i++) { + if (predicate(array[i], i)) { + return i; + } + } + return -1; + } + ts.findIndex = findIndex; + function findLastIndex(array, predicate, startIndex) { + for (var i = startIndex === undefined ? array.length - 1 : startIndex; i >= 0; i--) { + if (predicate(array[i], i)) { + return i; + } + } + return -1; + } + ts.findLastIndex = findLastIndex; + /** + * Returns the first truthy result of `callback`, or else fails. + * This is like `forEach`, but never returns undefined. + */ + function findMap(array, callback) { + for (var i = 0; i < array.length; i++) { + var result = callback(array[i], i); + if (result) { + return result; + } + } + return Debug.fail(); + } + ts.findMap = findMap; + function contains(array, value, equalityComparer) { + if (equalityComparer === void 0) { equalityComparer = equateValues; } + if (array) { + for (var _i = 0, array_1 = array; _i < array_1.length; _i++) { + var v = array_1[_i]; + if (equalityComparer(v, value)) { + return true; + } + } + } + return false; + } + ts.contains = contains; + function arraysEqual(a, b, equalityComparer) { + if (equalityComparer === void 0) { equalityComparer = equateValues; } + return a.length === b.length && a.every(function (x, i) { return equalityComparer(x, b[i]); }); + } + ts.arraysEqual = arraysEqual; + function indexOfAnyCharCode(text, charCodes, start) { + for (var i = start || 0; i < text.length; i++) { + if (contains(charCodes, text.charCodeAt(i))) { + return i; + } + } + return -1; + } + ts.indexOfAnyCharCode = indexOfAnyCharCode; + function countWhere(array, predicate) { + var count = 0; + if (array) { + for (var i = 0; i < array.length; i++) { + var v = array[i]; + if (predicate(v, i)) { + count++; + } + } + } + return count; + } + ts.countWhere = countWhere; + function filter(array, f) { + if (array) { + var len = array.length; + var i = 0; + while (i < len && f(array[i])) + i++; + if (i < len) { + var result = array.slice(0, i); + i++; + while (i < len) { + var item = array[i]; + if (f(item)) { + result.push(item); + } + i++; + } + return result; + } + } + return array; + } + ts.filter = filter; + function filterMutate(array, f) { + var outIndex = 0; + for (var i = 0; i < array.length; i++) { + if (f(array[i], i, array)) { + array[outIndex] = array[i]; + outIndex++; + } + } + array.length = outIndex; + } + ts.filterMutate = filterMutate; + function clear(array) { + array.length = 0; + } + ts.clear = clear; + function map(array, f) { + var result; + if (array) { + result = []; + for (var i = 0; i < array.length; i++) { + result.push(f(array[i], i)); + } + } + return result; + } + ts.map = map; + function mapIterator(iter, mapFn) { + return { + next: function () { + var iterRes = iter.next(); + return iterRes.done ? iterRes : { value: mapFn(iterRes.value), done: false }; + } + }; + } + ts.mapIterator = mapIterator; + function sameMap(array, f) { + if (array) { + for (var i = 0; i < array.length; i++) { + var item = array[i]; + var mapped = f(item, i); + if (item !== mapped) { + var result = array.slice(0, i); + result.push(mapped); + for (i++; i < array.length; i++) { + result.push(f(array[i], i)); + } + return result; + } + } + } + return array; + } + ts.sameMap = sameMap; + function flatten(array) { + var result; + if (array) { + result = []; + for (var _i = 0, array_2 = array; _i < array_2.length; _i++) { + var v = array_2[_i]; + if (v) { + if (isArray(v)) { + addRange(result, v); + } + else { + result.push(v); + } + } + } + } + return result; + } + ts.flatten = flatten; + /** + * Maps an array. If the mapped value is an array, it is spread into the result. + * + * @param array The array to map. + * @param mapfn The callback used to map the result into one or more values. + */ + function flatMap(array, mapfn) { + var result; + if (array) { + for (var i = 0; i < array.length; i++) { + var v = mapfn(array[i], i); + if (v) { + if (isArray(v)) { + result = addRange(result, v); + } + else { + result = append(result, v); + } + } + } + } + return result || ts.emptyArray; + } + ts.flatMap = flatMap; + function flatMapToMutable(array, mapfn) { + var result = []; + if (array) { + for (var i = 0; i < array.length; i++) { + var v = mapfn(array[i], i); + if (v) { + if (isArray(v)) { + addRange(result, v); + } + else { + result.push(v); + } + } + } + } + return result; + } + ts.flatMapToMutable = flatMapToMutable; + function flatMapIterator(iter, mapfn) { + var first = iter.next(); + if (first.done) { + return ts.emptyIterator; + } + var currentIter = getIterator(first.value); + return { + next: function () { + while (true) { + var currentRes = currentIter.next(); + if (!currentRes.done) { + return currentRes; + } + var iterRes = iter.next(); + if (iterRes.done) { + return iterRes; + } + currentIter = getIterator(iterRes.value); + } + }, + }; + function getIterator(x) { + var res = mapfn(x); + return res === undefined ? ts.emptyIterator : isArray(res) ? arrayIterator(res) : res; + } + } + ts.flatMapIterator = flatMapIterator; + function sameFlatMap(array, mapfn) { + var result; + if (array) { + for (var i = 0; i < array.length; i++) { + var item = array[i]; + var mapped = mapfn(item, i); + if (result || item !== mapped || isArray(mapped)) { + if (!result) { + result = array.slice(0, i); + } + if (isArray(mapped)) { + addRange(result, mapped); + } + else { + result.push(mapped); + } + } + } + } + return result || array; + } + ts.sameFlatMap = sameFlatMap; + function mapAllOrFail(array, mapFn) { + var result = []; + for (var i = 0; i < array.length; i++) { + var mapped = mapFn(array[i], i); + if (mapped === undefined) { + return undefined; + } + result.push(mapped); + } + return result; + } + ts.mapAllOrFail = mapAllOrFail; + function mapDefined(array, mapFn) { + var result = []; + if (array) { + for (var i = 0; i < array.length; i++) { + var mapped = mapFn(array[i], i); + if (mapped !== undefined) { + result.push(mapped); + } + } + } + return result; + } + ts.mapDefined = mapDefined; + function mapDefinedIterator(iter, mapFn) { + return { + next: function () { + while (true) { + var res = iter.next(); + if (res.done) { + return res; + } + var value = mapFn(res.value); + if (value !== undefined) { + return { value: value, done: false }; + } + } + } + }; + } + ts.mapDefinedIterator = mapDefinedIterator; + ts.emptyIterator = { next: function () { return ({ value: undefined, done: true }); } }; + function singleIterator(value) { + var done = false; + return { + next: function () { + var wasDone = done; + done = true; + return wasDone ? { value: undefined, done: true } : { value: value, done: false }; + } + }; + } + ts.singleIterator = singleIterator; + function spanMap(array, keyfn, mapfn) { + var result; + if (array) { + result = []; + var len = array.length; + var previousKey = void 0; + var key = void 0; + var start = 0; + var pos = 0; + while (start < len) { + while (pos < len) { + var value = array[pos]; + key = keyfn(value, pos); + if (pos === 0) { + previousKey = key; + } + else if (key !== previousKey) { + break; + } + pos++; + } + if (start < pos) { + var v = mapfn(array.slice(start, pos), previousKey, start, pos); + if (v) { + result.push(v); + } + start = pos; + } + previousKey = key; + pos++; + } + } + return result; + } + ts.spanMap = spanMap; + function mapEntries(map, f) { + if (!map) { + return undefined; + } + var result = createMap(); + map.forEach(function (value, key) { + var _a = f(key, value), newKey = _a[0], newValue = _a[1]; + result.set(newKey, newValue); + }); + return result; + } + ts.mapEntries = mapEntries; + function some(array, predicate) { + if (array) { + if (predicate) { + for (var _i = 0, array_3 = array; _i < array_3.length; _i++) { + var v = array_3[_i]; + if (predicate(v)) { + return true; + } + } + } + else { + return array.length > 0; + } + } + return false; + } + ts.some = some; + /** Calls the callback with (start, afterEnd) index pairs for each range where 'pred' is true. */ + function getRangesWhere(arr, pred, cb) { + var start; + for (var i = 0; i < arr.length; i++) { + if (pred(arr[i])) { + start = start === undefined ? i : start; + } + else { + if (start !== undefined) { + cb(start, i); + start = undefined; + } + } + } + if (start !== undefined) + cb(start, arr.length); + } + ts.getRangesWhere = getRangesWhere; + function concatenate(array1, array2) { + if (!some(array2)) + return array1; + if (!some(array1)) + return array2; + return array1.concat(array2); + } + ts.concatenate = concatenate; + function deduplicateRelational(array, equalityComparer, comparer) { + // Perform a stable sort of the array. This ensures the first entry in a list of + // duplicates remains the first entry in the result. + var indices = array.map(function (_, i) { return i; }); + stableSortIndices(array, indices, comparer); + var last = array[indices[0]]; + var deduplicated = [indices[0]]; + for (var i = 1; i < indices.length; i++) { + var index = indices[i]; + var item = array[index]; + if (!equalityComparer(last, item)) { + deduplicated.push(index); + last = item; + } + } + // restore original order + deduplicated.sort(); + return deduplicated.map(function (i) { return array[i]; }); + } + function deduplicateEquality(array, equalityComparer) { + var result = []; + for (var _i = 0, array_4 = array; _i < array_4.length; _i++) { + var item = array_4[_i]; + pushIfUnique(result, item, equalityComparer); + } + return result; + } + /** + * Deduplicates an unsorted array. + * @param equalityComparer An optional `EqualityComparer` used to determine if two values are duplicates. + * @param comparer An optional `Comparer` used to sort entries before comparison, though the + * result will remain in the original order in `array`. + */ + function deduplicate(array, equalityComparer, comparer) { + return array.length === 0 ? [] : + array.length === 1 ? array.slice() : + comparer ? deduplicateRelational(array, equalityComparer, comparer) : + deduplicateEquality(array, equalityComparer); + } + ts.deduplicate = deduplicate; + /** + * Deduplicates an array that has already been sorted. + */ + function deduplicateSorted(array, comparer) { + if (array.length === 0) + return ts.emptyArray; + var last = array[0]; + var deduplicated = [last]; + for (var i = 1; i < array.length; i++) { + var next = array[i]; + switch (comparer(next, last)) { + // equality comparison + case true: + // relational comparison + case 0 /* EqualTo */: + continue; + case -1 /* LessThan */: + // If `array` is sorted, `next` should **never** be less than `last`. + return Debug.fail("Array is unsorted."); + } + deduplicated.push(last = next); + } + return deduplicated; + } + function insertSorted(array, insert, compare) { + if (array.length === 0) { + array.push(insert); + return; + } + var insertIndex = binarySearch(array, insert, identity, compare); + if (insertIndex < 0) { + array.splice(~insertIndex, 0, insert); + } + } + ts.insertSorted = insertSorted; + function sortAndDeduplicate(array, comparer, equalityComparer) { + return deduplicateSorted(sort(array, comparer), equalityComparer || comparer || compareStringsCaseSensitive); + } + ts.sortAndDeduplicate = sortAndDeduplicate; + function arrayIsEqualTo(array1, array2, equalityComparer) { + if (equalityComparer === void 0) { equalityComparer = equateValues; } + if (!array1 || !array2) { + return array1 === array2; + } + if (array1.length !== array2.length) { + return false; + } + for (var i = 0; i < array1.length; i++) { + if (!equalityComparer(array1[i], array2[i], i)) { + return false; + } + } + return true; + } + ts.arrayIsEqualTo = arrayIsEqualTo; + function compact(array) { + var result; + if (array) { + for (var i = 0; i < array.length; i++) { + var v = array[i]; + if (result || !v) { + if (!result) { + result = array.slice(0, i); + } + if (v) { + result.push(v); + } + } + } + } + return result || array; + } + ts.compact = compact; + /** + * Gets the relative complement of `arrayA` with respect to `arrayB`, returning the elements that + * are not present in `arrayA` but are present in `arrayB`. Assumes both arrays are sorted + * based on the provided comparer. + */ + function relativeComplement(arrayA, arrayB, comparer) { + if (!arrayB || !arrayA || arrayB.length === 0 || arrayA.length === 0) + return arrayB; + var result = []; + loopB: for (var offsetA = 0, offsetB = 0; offsetB < arrayB.length; offsetB++) { + if (offsetB > 0) { + // Ensure `arrayB` is properly sorted. + Debug.assertGreaterThanOrEqual(comparer(arrayB[offsetB], arrayB[offsetB - 1]), 0 /* EqualTo */); + } + loopA: for (var startA = offsetA; offsetA < arrayA.length; offsetA++) { + if (offsetA > startA) { + // Ensure `arrayA` is properly sorted. We only need to perform this check if + // `offsetA` has changed since we entered the loop. + Debug.assertGreaterThanOrEqual(comparer(arrayA[offsetA], arrayA[offsetA - 1]), 0 /* EqualTo */); + } + switch (comparer(arrayB[offsetB], arrayA[offsetA])) { + case -1 /* LessThan */: + // If B is less than A, B does not exist in arrayA. Add B to the result and + // move to the next element in arrayB without changing the current position + // in arrayA. + result.push(arrayB[offsetB]); + continue loopB; + case 0 /* EqualTo */: + // If B is equal to A, B exists in arrayA. Move to the next element in + // arrayB without adding B to the result or changing the current position + // in arrayA. + continue loopB; + case 1 /* GreaterThan */: + // If B is greater than A, we need to keep looking for B in arrayA. Move to + // the next element in arrayA and recheck. + continue loopA; + } + } + } + return result; + } + ts.relativeComplement = relativeComplement; + function sum(array, prop) { + var result = 0; + for (var _i = 0, array_5 = array; _i < array_5.length; _i++) { + var v = array_5[_i]; + result += v[prop]; + } + return result; + } + ts.sum = sum; + function append(to, value) { + if (value === undefined) + return to; + if (to === undefined) + return [value]; + to.push(value); + return to; + } + ts.append = append; + /** + * Gets the actual offset into an array for a relative offset. Negative offsets indicate a + * position offset from the end of the array. + */ + function toOffset(array, offset) { + return offset < 0 ? array.length + offset : offset; + } + function addRange(to, from, start, end) { + if (from === undefined || from.length === 0) + return to; + if (to === undefined) + return from.slice(start, end); + start = start === undefined ? 0 : toOffset(from, start); + end = end === undefined ? from.length : toOffset(from, end); + for (var i = start; i < end && i < from.length; i++) { + if (from[i] !== undefined) { + to.push(from[i]); + } + } + return to; + } + ts.addRange = addRange; + /** + * @return Whether the value was added. + */ + function pushIfUnique(array, toAdd, equalityComparer) { + if (contains(array, toAdd, equalityComparer)) { + return false; + } + else { + array.push(toAdd); + return true; + } + } + ts.pushIfUnique = pushIfUnique; + /** + * Unlike `pushIfUnique`, this can take `undefined` as an input, and returns a new array. + */ + function appendIfUnique(array, toAdd, equalityComparer) { + if (array) { + pushIfUnique(array, toAdd, equalityComparer); + return array; + } + else { + return [toAdd]; + } + } + ts.appendIfUnique = appendIfUnique; + function stableSortIndices(array, indices, comparer) { + // sort indices by value then position + indices.sort(function (x, y) { return comparer(array[x], array[y]) || compareValues(x, y); }); + } + /** + * Returns a new sorted array. + */ + function sort(array, comparer) { + return (array.length === 0 ? array : array.slice().sort(comparer)); + } + ts.sort = sort; + function arrayIterator(array) { + var i = 0; + return { next: function () { + if (i === array.length) { + return { value: undefined, done: true }; + } + else { + i++; + return { value: array[i - 1], done: false }; + } + } }; + } + ts.arrayIterator = arrayIterator; + /** + * Stable sort of an array. Elements equal to each other maintain their relative position in the array. + */ + function stableSort(array, comparer) { + var indices = array.map(function (_, i) { return i; }); + stableSortIndices(array, indices, comparer); + return indices.map(function (i) { return array[i]; }); + } + ts.stableSort = stableSort; + function rangeEquals(array1, array2, pos, end) { + while (pos < end) { + if (array1[pos] !== array2[pos]) { + return false; + } + pos++; + } + return true; + } + ts.rangeEquals = rangeEquals; + /** + * Returns the element at a specific offset in an array if non-empty, `undefined` otherwise. + * A negative offset indicates the element should be retrieved from the end of the array. + */ + function elementAt(array, offset) { + if (array) { + offset = toOffset(array, offset); + if (offset < array.length) { + return array[offset]; + } + } + return undefined; + } + ts.elementAt = elementAt; + /** + * Returns the first element of an array if non-empty, `undefined` otherwise. + */ + function firstOrUndefined(array) { + return array.length === 0 ? undefined : array[0]; + } + ts.firstOrUndefined = firstOrUndefined; + function first(array) { + Debug.assert(array.length !== 0); + return array[0]; + } + ts.first = first; + /** + * Returns the last element of an array if non-empty, `undefined` otherwise. + */ + function lastOrUndefined(array) { + return array.length === 0 ? undefined : array[array.length - 1]; + } + ts.lastOrUndefined = lastOrUndefined; + function last(array) { + Debug.assert(array.length !== 0); + return array[array.length - 1]; + } + ts.last = last; + /** + * Returns the only element of an array if it contains only one element, `undefined` otherwise. + */ + function singleOrUndefined(array) { + return array && array.length === 1 + ? array[0] + : undefined; + } + ts.singleOrUndefined = singleOrUndefined; + function singleOrMany(array) { + return array && array.length === 1 + ? array[0] + : array; + } + ts.singleOrMany = singleOrMany; + function replaceElement(array, index, value) { + var result = array.slice(0); + result[index] = value; + return result; + } + ts.replaceElement = replaceElement; + /** + * Performs a binary search, finding the index at which `value` occurs in `array`. + * If no such index is found, returns the 2's-complement of first index at which + * `array[index]` exceeds `value`. + * @param array A sorted array whose first element must be no larger than number + * @param value The value to be searched for in the array. + * @param keySelector A callback used to select the search key from `value` and each element of + * `array`. + * @param keyComparer A callback used to compare two keys in a sorted array. + * @param offset An offset into `array` at which to start the search. + */ + function binarySearch(array, value, keySelector, keyComparer, offset) { + return binarySearchKey(array, keySelector(value), keySelector, keyComparer, offset); + } + ts.binarySearch = binarySearch; + /** + * Performs a binary search, finding the index at which an object with `key` occurs in `array`. + * If no such index is found, returns the 2's-complement of first index at which + * `array[index]` exceeds `key`. + * @param array A sorted array whose first element must be no larger than number + * @param key The key to be searched for in the array. + * @param keySelector A callback used to select the search key from each element of `array`. + * @param keyComparer A callback used to compare two keys in a sorted array. + * @param offset An offset into `array` at which to start the search. + */ + function binarySearchKey(array, key, keySelector, keyComparer, offset) { + if (!some(array)) { + return -1; + } + var low = offset || 0; + var high = array.length - 1; + while (low <= high) { + var middle = low + ((high - low) >> 1); + var midKey = keySelector(array[middle]); + switch (keyComparer(midKey, key)) { + case -1 /* LessThan */: + low = middle + 1; + break; + case 0 /* EqualTo */: + return middle; + case 1 /* GreaterThan */: + high = middle - 1; + break; + } + } + return ~low; + } + ts.binarySearchKey = binarySearchKey; + function reduceLeft(array, f, initial, start, count) { + if (array && array.length > 0) { + var size = array.length; + if (size > 0) { + var pos = start === undefined || start < 0 ? 0 : start; + var end = count === undefined || pos + count > size - 1 ? size - 1 : pos + count; + var result = void 0; + if (arguments.length <= 2) { + result = array[pos]; + pos++; + } + else { + result = initial; + } + while (pos <= end) { + result = f(result, array[pos], pos); + pos++; + } + return result; + } + } + return initial; + } + ts.reduceLeft = reduceLeft; + var hasOwnProperty = Object.prototype.hasOwnProperty; + /** + * Indicates whether a map-like contains an own property with the specified key. + * + * @param map A map-like. + * @param key A property key. + */ + function hasProperty(map, key) { + return hasOwnProperty.call(map, key); + } + ts.hasProperty = hasProperty; + /** + * Gets the value of an owned property in a map-like. + * + * @param map A map-like. + * @param key A property key. + */ + function getProperty(map, key) { + return hasOwnProperty.call(map, key) ? map[key] : undefined; + } + ts.getProperty = getProperty; + /** + * Gets the owned, enumerable property keys of a map-like. + */ + function getOwnKeys(map) { + var keys = []; + for (var key in map) { + if (hasOwnProperty.call(map, key)) { + keys.push(key); + } + } + return keys; + } + ts.getOwnKeys = getOwnKeys; + function getOwnValues(sparseArray) { + var values = []; + for (var key in sparseArray) { + if (hasOwnProperty.call(sparseArray, key)) { + values.push(sparseArray[key]); + } + } + return values; + } + ts.getOwnValues = getOwnValues; + function arrayFrom(iterator, map) { + var _a; + var result = []; + for (var _b = iterator.next(), value = _b.value, done = _b.done; !done; _a = iterator.next(), value = _a.value, done = _a.done, _a) { + result.push(map ? map(value) : value); + } + return result; + } + ts.arrayFrom = arrayFrom; + function assign(t) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + for (var _a = 0, args_1 = args; _a < args_1.length; _a++) { + var arg = args_1[_a]; + for (var p in arg) { + if (hasProperty(arg, p)) { + t[p] = arg[p]; // TODO: GH#23368 + } + } + } + return t; + } + ts.assign = assign; + /** + * Performs a shallow equality comparison of the contents of two map-likes. + * + * @param left A map-like whose properties should be compared. + * @param right A map-like whose properties should be compared. + */ + function equalOwnProperties(left, right, equalityComparer) { + if (equalityComparer === void 0) { equalityComparer = equateValues; } + if (left === right) + return true; + if (!left || !right) + return false; + for (var key in left) { + if (hasOwnProperty.call(left, key)) { + if (!hasOwnProperty.call(right, key)) + return false; + if (!equalityComparer(left[key], right[key])) + return false; + } + } + for (var key in right) { + if (hasOwnProperty.call(right, key)) { + if (!hasOwnProperty.call(left, key)) + return false; + } + } + return true; + } + ts.equalOwnProperties = equalOwnProperties; + function arrayToMap(array, makeKey, makeValue) { + if (makeValue === void 0) { makeValue = identity; } + var result = createMap(); + for (var _i = 0, array_6 = array; _i < array_6.length; _i++) { + var value = array_6[_i]; + var key = makeKey(value); + if (key !== undefined) + result.set(key, makeValue(value)); + } + return result; + } + ts.arrayToMap = arrayToMap; + function arrayToNumericMap(array, makeKey, makeValue) { + if (makeValue === void 0) { makeValue = identity; } + var result = []; + for (var _i = 0, array_7 = array; _i < array_7.length; _i++) { + var value = array_7[_i]; + result[makeKey(value)] = makeValue(value); + } + return result; + } + ts.arrayToNumericMap = arrayToNumericMap; + function arrayToMultiMap(values, makeKey, makeValue) { + if (makeValue === void 0) { makeValue = identity; } + var result = createMultiMap(); + for (var _i = 0, values_1 = values; _i < values_1.length; _i++) { + var value = values_1[_i]; + result.add(makeKey(value), makeValue(value)); + } + return result; + } + ts.arrayToMultiMap = arrayToMultiMap; + function group(values, getGroupId) { + return arrayFrom(arrayToMultiMap(values, getGroupId).values()); + } + ts.group = group; + function clone(object) { + var result = {}; + for (var id in object) { + if (hasOwnProperty.call(object, id)) { + result[id] = object[id]; + } + } + return result; + } + ts.clone = clone; + function extend(first, second) { + var result = {}; + for (var id in second) { + if (hasOwnProperty.call(second, id)) { + result[id] = second[id]; + } + } + for (var id in first) { + if (hasOwnProperty.call(first, id)) { + result[id] = first[id]; + } + } + return result; + } + ts.extend = extend; + function createMultiMap() { + var map = createMap(); + map.add = multiMapAdd; + map.remove = multiMapRemove; + return map; + } + ts.createMultiMap = createMultiMap; + function multiMapAdd(key, value) { + var values = this.get(key); + if (values) { + values.push(value); + } + else { + this.set(key, values = [value]); + } + return values; + } + function multiMapRemove(key, value) { + var values = this.get(key); + if (values) { + unorderedRemoveItem(values, value); + if (!values.length) { + this.delete(key); + } + } + } + /** + * Tests whether a value is an array. + */ + function isArray(value) { + return Array.isArray ? Array.isArray(value) : value instanceof Array; + } + ts.isArray = isArray; + function toArray(value) { + return isArray(value) ? value : [value]; + } + ts.toArray = toArray; + /** + * Tests whether a value is string + */ + function isString(text) { + return typeof text === "string"; + } + ts.isString = isString; + function isNumber(x) { + return typeof x === "number"; + } + ts.isNumber = isNumber; + function tryCast(value, test) { + return value !== undefined && test(value) ? value : undefined; + } + ts.tryCast = tryCast; + function cast(value, test) { + if (value !== undefined && test(value)) + return value; + return Debug.fail("Invalid cast. The supplied value " + value + " did not pass the test '" + Debug.getFunctionName(test) + "'."); + } + ts.cast = cast; + /** Does nothing. */ + function noop(_) { } // tslint:disable-line no-empty + ts.noop = noop; + /** Do nothing and return false */ + function returnFalse() { return false; } + ts.returnFalse = returnFalse; + /** Do nothing and return true */ + function returnTrue() { return true; } + ts.returnTrue = returnTrue; + /** Returns its argument. */ + function identity(x) { return x; } + ts.identity = identity; + /** Returns lower case string */ + function toLowerCase(x) { return x.toLowerCase(); } + ts.toLowerCase = toLowerCase; + /** Throws an error because a function is not implemented. */ + function notImplemented() { + throw new Error("Not implemented"); + } + ts.notImplemented = notImplemented; + function memoize(callback) { + var value; + return function () { + if (callback) { + value = callback(); + callback = undefined; + } + return value; + }; + } + ts.memoize = memoize; + function chain(a, b, c, d, e) { + if (e) { + var args_2 = []; + for (var i = 0; i < arguments.length; i++) { + args_2[i] = arguments[i]; + } + return function (t) { return compose.apply(void 0, map(args_2, function (f) { return f(t); })); }; + } + else if (d) { + return function (t) { return compose(a(t), b(t), c(t), d(t)); }; + } + else if (c) { + return function (t) { return compose(a(t), b(t), c(t)); }; + } + else if (b) { + return function (t) { return compose(a(t), b(t)); }; + } + else if (a) { + return function (t) { return compose(a(t)); }; + } + else { + return function (_) { return function (u) { return u; }; }; + } + } + ts.chain = chain; + function compose(a, b, c, d, e) { + if (e) { + var args_3 = []; + for (var i = 0; i < arguments.length; i++) { + args_3[i] = arguments[i]; + } + return function (t) { return reduceLeft(args_3, function (u, f) { return f(u); }, t); }; + } + else if (d) { + return function (t) { return d(c(b(a(t)))); }; + } + else if (c) { + return function (t) { return c(b(a(t))); }; + } + else if (b) { + return function (t) { return b(a(t)); }; + } + else if (a) { + return function (t) { return a(t); }; + } + else { + return function (t) { return t; }; + } + } + ts.compose = compose; + var AssertionLevel; + (function (AssertionLevel) { + AssertionLevel[AssertionLevel["None"] = 0] = "None"; + AssertionLevel[AssertionLevel["Normal"] = 1] = "Normal"; + AssertionLevel[AssertionLevel["Aggressive"] = 2] = "Aggressive"; + AssertionLevel[AssertionLevel["VeryAggressive"] = 3] = "VeryAggressive"; + })(AssertionLevel = ts.AssertionLevel || (ts.AssertionLevel = {})); + var Debug; + (function (Debug) { + Debug.currentAssertionLevel = 0 /* None */; + Debug.isDebugging = false; + function shouldAssert(level) { + return Debug.currentAssertionLevel >= level; + } + Debug.shouldAssert = shouldAssert; + function assert(expression, message, verboseDebugInfo, stackCrawlMark) { + if (!expression) { + if (verboseDebugInfo) { + message += "\r\nVerbose Debug Information: " + (typeof verboseDebugInfo === "string" ? verboseDebugInfo : verboseDebugInfo()); + } + fail(message ? "False expression: " + message : "False expression.", stackCrawlMark || assert); + } + } + Debug.assert = assert; + function assertEqual(a, b, msg, msg2) { + if (a !== b) { + var message = msg ? msg2 ? msg + " " + msg2 : msg : ""; + fail("Expected " + a + " === " + b + ". " + message); + } + } + Debug.assertEqual = assertEqual; + function assertLessThan(a, b, msg) { + if (a >= b) { + fail("Expected " + a + " < " + b + ". " + (msg || "")); + } + } + Debug.assertLessThan = assertLessThan; + function assertLessThanOrEqual(a, b) { + if (a > b) { + fail("Expected " + a + " <= " + b); + } + } + Debug.assertLessThanOrEqual = assertLessThanOrEqual; + function assertGreaterThanOrEqual(a, b) { + if (a < b) { + fail("Expected " + a + " >= " + b); + } + } + Debug.assertGreaterThanOrEqual = assertGreaterThanOrEqual; + function fail(message, stackCrawlMark) { + debugger; + var e = new Error(message ? "Debug Failure. " + message : "Debug Failure."); + if (Error.captureStackTrace) { + Error.captureStackTrace(e, stackCrawlMark || fail); + } + throw e; + } + Debug.fail = fail; + function assertDefined(value, message) { + if (value === undefined || value === null) + return fail(message); + return value; + } + Debug.assertDefined = assertDefined; + function assertEachDefined(value, message) { + for (var _i = 0, value_1 = value; _i < value_1.length; _i++) { + var v = value_1[_i]; + assertDefined(v, message); + } + return value; + } + Debug.assertEachDefined = assertEachDefined; + function assertNever(member, message, stackCrawlMark) { + if (message === void 0) { message = "Illegal value:"; } + var detail = "kind" in member && "pos" in member ? "SyntaxKind: " + Debug.showSyntaxKind(member) : JSON.stringify(member); + return fail(message + " " + detail, stackCrawlMark || assertNever); + } + Debug.assertNever = assertNever; + function getFunctionName(func) { + if (typeof func !== "function") { + return ""; + } + else if (func.hasOwnProperty("name")) { + return func.name; + } + else { + var text = Function.prototype.toString.call(func); + var match = /^function\s+([\w\$]+)\s*\(/.exec(text); + return match ? match[1] : ""; + } + } + Debug.getFunctionName = getFunctionName; + })(Debug = ts.Debug || (ts.Debug = {})); + function equateValues(a, b) { + return a === b; + } + ts.equateValues = equateValues; + /** + * Compare the equality of two strings using a case-sensitive ordinal comparison. + * + * Case-sensitive comparisons compare both strings one code-point at a time using the integer + * value of each code-point after applying `toUpperCase` to each string. We always map both + * strings to their upper-case form as some unicode characters do not properly round-trip to + * lowercase (such as `ẞ` (German sharp capital s)). + */ + function equateStringsCaseInsensitive(a, b) { + return a === b + || a !== undefined + && b !== undefined + && a.toUpperCase() === b.toUpperCase(); + } + ts.equateStringsCaseInsensitive = equateStringsCaseInsensitive; + /** + * Compare the equality of two strings using a case-sensitive ordinal comparison. + * + * Case-sensitive comparisons compare both strings one code-point at a time using the + * integer value of each code-point. + */ + function equateStringsCaseSensitive(a, b) { + return equateValues(a, b); + } + ts.equateStringsCaseSensitive = equateStringsCaseSensitive; + function compareComparableValues(a, b) { + return a === b ? 0 /* EqualTo */ : + a === undefined ? -1 /* LessThan */ : + b === undefined ? 1 /* GreaterThan */ : + a < b ? -1 /* LessThan */ : + 1 /* GreaterThan */; + } + /** + * Compare two numeric values for their order relative to each other. + * To compare strings, use any of the `compareStrings` functions. + */ + function compareValues(a, b) { + return compareComparableValues(a, b); + } + ts.compareValues = compareValues; + function min(a, b, compare) { + return compare(a, b) === -1 /* LessThan */ ? a : b; + } + ts.min = min; + /** + * Compare two strings using a case-insensitive ordinal comparison. + * + * Ordinal comparisons are based on the difference between the unicode code points of both + * strings. Characters with multiple unicode representations are considered unequal. Ordinal + * comparisons provide predictable ordering, but place "a" after "B". + * + * Case-insensitive comparisons compare both strings one code-point at a time using the integer + * value of each code-point after applying `toUpperCase` to each string. We always map both + * strings to their upper-case form as some unicode characters do not properly round-trip to + * lowercase (such as `ẞ` (German sharp capital s)). + */ + function compareStringsCaseInsensitive(a, b) { + if (a === b) + return 0 /* EqualTo */; + if (a === undefined) + return -1 /* LessThan */; + if (b === undefined) + return 1 /* GreaterThan */; + a = a.toUpperCase(); + b = b.toUpperCase(); + return a < b ? -1 /* LessThan */ : a > b ? 1 /* GreaterThan */ : 0 /* EqualTo */; + } + ts.compareStringsCaseInsensitive = compareStringsCaseInsensitive; + /** + * Compare two strings using a case-sensitive ordinal comparison. + * + * Ordinal comparisons are based on the difference between the unicode code points of both + * strings. Characters with multiple unicode representations are considered unequal. Ordinal + * comparisons provide predictable ordering, but place "a" after "B". + * + * Case-sensitive comparisons compare both strings one code-point at a time using the integer + * value of each code-point. + */ + function compareStringsCaseSensitive(a, b) { + return compareComparableValues(a, b); + } + ts.compareStringsCaseSensitive = compareStringsCaseSensitive; + function getStringComparer(ignoreCase) { + return ignoreCase ? compareStringsCaseInsensitive : compareStringsCaseSensitive; + } + ts.getStringComparer = getStringComparer; + /** + * Creates a string comparer for use with string collation in the UI. + */ + var createUIStringComparer = (function () { + var defaultComparer; + var enUSComparer; + var stringComparerFactory = getStringComparerFactory(); + return createStringComparer; + function compareWithCallback(a, b, comparer) { + if (a === b) + return 0 /* EqualTo */; + if (a === undefined) + return -1 /* LessThan */; + if (b === undefined) + return 1 /* GreaterThan */; + var value = comparer(a, b); + return value < 0 ? -1 /* LessThan */ : value > 0 ? 1 /* GreaterThan */ : 0 /* EqualTo */; + } + function createIntlCollatorStringComparer(locale) { + // Intl.Collator.prototype.compare is bound to the collator. See NOTE in + // http://www.ecma-international.org/ecma-402/2.0/#sec-Intl.Collator.prototype.compare + var comparer = new Intl.Collator(locale, { usage: "sort", sensitivity: "variant" }).compare; + return function (a, b) { return compareWithCallback(a, b, comparer); }; + } + function createLocaleCompareStringComparer(locale) { + // if the locale is not the default locale (`undefined`), use the fallback comparer. + if (locale !== undefined) + return createFallbackStringComparer(); + return function (a, b) { return compareWithCallback(a, b, compareStrings); }; + function compareStrings(a, b) { + return a.localeCompare(b); + } + } + function createFallbackStringComparer() { + // An ordinal comparison puts "A" after "b", but for the UI we want "A" before "b". + // We first sort case insensitively. So "Aaa" will come before "baa". + // Then we sort case sensitively, so "aaa" will come before "Aaa". + // + // For case insensitive comparisons we always map both strings to their + // upper-case form as some unicode characters do not properly round-trip to + // lowercase (such as `ẞ` (German sharp capital s)). + return function (a, b) { return compareWithCallback(a, b, compareDictionaryOrder); }; + function compareDictionaryOrder(a, b) { + return compareStrings(a.toUpperCase(), b.toUpperCase()) || compareStrings(a, b); + } + function compareStrings(a, b) { + return a < b ? -1 /* LessThan */ : a > b ? 1 /* GreaterThan */ : 0 /* EqualTo */; + } + } + function getStringComparerFactory() { + // If the host supports Intl, we use it for comparisons using the default locale. + if (typeof Intl === "object" && typeof Intl.Collator === "function") { + return createIntlCollatorStringComparer; + } + // If the host does not support Intl, we fall back to localeCompare. + // localeCompare in Node v0.10 is just an ordinal comparison, so don't use it. + if (typeof String.prototype.localeCompare === "function" && + typeof String.prototype.toLocaleUpperCase === "function" && + "a".localeCompare("B") < 0) { + return createLocaleCompareStringComparer; + } + // Otherwise, fall back to ordinal comparison: + return createFallbackStringComparer; + } + function createStringComparer(locale) { + // Hold onto common string comparers. This avoids constantly reallocating comparers during + // tests. + if (locale === undefined) { + return defaultComparer || (defaultComparer = stringComparerFactory(locale)); + } + else if (locale === "en-US") { + return enUSComparer || (enUSComparer = stringComparerFactory(locale)); + } + else { + return stringComparerFactory(locale); + } + } + })(); + var uiComparerCaseSensitive; + var uiLocale; + function getUILocale() { + return uiLocale; + } + ts.getUILocale = getUILocale; + function setUILocale(value) { + if (uiLocale !== value) { + uiLocale = value; + uiComparerCaseSensitive = undefined; + } + } + ts.setUILocale = setUILocale; + /** + * Compare two strings in a using the case-sensitive sort behavior of the UI locale. + * + * Ordering is not predictable between different host locales, but is best for displaying + * ordered data for UI presentation. Characters with multiple unicode representations may + * be considered equal. + * + * Case-sensitive comparisons compare strings that differ in base characters, or + * accents/diacritic marks, or case as unequal. + */ + function compareStringsCaseSensitiveUI(a, b) { + var comparer = uiComparerCaseSensitive || (uiComparerCaseSensitive = createUIStringComparer(uiLocale)); + return comparer(a, b); + } + ts.compareStringsCaseSensitiveUI = compareStringsCaseSensitiveUI; + function compareProperties(a, b, key, comparer) { + return a === b ? 0 /* EqualTo */ : + a === undefined ? -1 /* LessThan */ : + b === undefined ? 1 /* GreaterThan */ : + comparer(a[key], b[key]); + } + ts.compareProperties = compareProperties; + /** True is greater than false. */ + function compareBooleans(a, b) { + return compareValues(a ? 1 : 0, b ? 1 : 0); + } + ts.compareBooleans = compareBooleans; + /** + * Given a name and a list of names that are *not* equal to the name, return a spelling suggestion if there is one that is close enough. + * Names less than length 3 only check for case-insensitive equality, not Levenshtein distance. + * + * If there is a candidate that's the same except for case, return that. + * If there is a candidate that's within one edit of the name, return that. + * Otherwise, return the candidate with the smallest Levenshtein distance, + * except for candidates: + * * With no name + * * Whose length differs from the target name by more than 0.34 of the length of the name. + * * Whose levenshtein distance is more than 0.4 of the length of the name + * (0.4 allows 1 substitution/transposition for every 5 characters, + * and 1 insertion/deletion at 3 characters) + */ + function getSpellingSuggestion(name, candidates, getName) { + var maximumLengthDifference = Math.min(2, Math.floor(name.length * 0.34)); + var bestDistance = Math.floor(name.length * 0.4) + 1; // If the best result isn't better than this, don't bother. + var bestCandidate; + var justCheckExactMatches = false; + var nameLowerCase = name.toLowerCase(); + for (var _i = 0, candidates_1 = candidates; _i < candidates_1.length; _i++) { + var candidate = candidates_1[_i]; + var candidateName = getName(candidate); + if (candidateName !== undefined && Math.abs(candidateName.length - nameLowerCase.length) <= maximumLengthDifference) { + var candidateNameLowerCase = candidateName.toLowerCase(); + if (candidateNameLowerCase === nameLowerCase) { + if (candidateName === name) { + continue; + } + return candidate; + } + if (justCheckExactMatches) { + continue; + } + if (candidateName.length < 3) { + // Don't bother, user would have noticed a 2-character name having an extra character + continue; + } + // Only care about a result better than the best so far. + var distance = levenshteinWithMax(nameLowerCase, candidateNameLowerCase, bestDistance - 1); + if (distance === undefined) { + continue; + } + if (distance < 3) { + justCheckExactMatches = true; + bestCandidate = candidate; + } + else { + Debug.assert(distance < bestDistance); // Else `levenshteinWithMax` should return undefined + bestDistance = distance; + bestCandidate = candidate; + } + } + } + return bestCandidate; + } + ts.getSpellingSuggestion = getSpellingSuggestion; + function levenshteinWithMax(s1, s2, max) { + var previous = new Array(s2.length + 1); + var current = new Array(s2.length + 1); + /** Represents any value > max. We don't care about the particular value. */ + var big = max + 1; + for (var i = 0; i <= s2.length; i++) { + previous[i] = i; + } + for (var i = 1; i <= s1.length; i++) { + var c1 = s1.charCodeAt(i - 1); + var minJ = i > max ? i - max : 1; + var maxJ = s2.length > max + i ? max + i : s2.length; + current[0] = i; + /** Smallest value of the matrix in the ith column. */ + var colMin = i; + for (var j = 1; j < minJ; j++) { + current[j] = big; + } + for (var j = minJ; j <= maxJ; j++) { + var dist = c1 === s2.charCodeAt(j - 1) + ? previous[j - 1] + : Math.min(/*delete*/ previous[j] + 1, /*insert*/ current[j - 1] + 1, /*substitute*/ previous[j - 1] + 2); + current[j] = dist; + colMin = Math.min(colMin, dist); + } + for (var j = maxJ + 1; j <= s2.length; j++) { + current[j] = big; + } + if (colMin > max) { + // Give up -- everything in this column is > max and it can't get better in future columns. + return undefined; + } + var temp = previous; + previous = current; + current = temp; + } + var res = previous[s2.length]; + return res > max ? undefined : res; + } + function endsWith(str, suffix) { + var expectedPos = str.length - suffix.length; + return expectedPos >= 0 && str.indexOf(suffix, expectedPos) === expectedPos; + } + ts.endsWith = endsWith; + function removeSuffix(str, suffix) { + return endsWith(str, suffix) ? str.slice(0, str.length - suffix.length) : str; + } + ts.removeSuffix = removeSuffix; + function tryRemoveSuffix(str, suffix) { + return endsWith(str, suffix) ? str.slice(0, str.length - suffix.length) : undefined; + } + ts.tryRemoveSuffix = tryRemoveSuffix; + function stringContains(str, substring) { + return str.indexOf(substring) !== -1; + } + ts.stringContains = stringContains; + function fileExtensionIs(path, extension) { + return path.length > extension.length && endsWith(path, extension); + } + ts.fileExtensionIs = fileExtensionIs; + function fileExtensionIsOneOf(path, extensions) { + for (var _i = 0, extensions_1 = extensions; _i < extensions_1.length; _i++) { + var extension = extensions_1[_i]; + if (fileExtensionIs(path, extension)) { + return true; + } + } + return false; + } + ts.fileExtensionIsOneOf = fileExtensionIsOneOf; + /** + * Takes a string like "jquery-min.4.2.3" and returns "jquery" + */ + function removeMinAndVersionNumbers(fileName) { + // Match a "." or "-" followed by a version number or 'min' at the end of the name + var trailingMinOrVersion = /[.-]((min)|(\d+(\.\d+)*))$/; + // The "min" or version may both be present, in either order, so try applying the above twice. + return fileName.replace(trailingMinOrVersion, "").replace(trailingMinOrVersion, ""); + } + ts.removeMinAndVersionNumbers = removeMinAndVersionNumbers; + /** Remove an item from an array, moving everything to its right one space left. */ + function orderedRemoveItem(array, item) { + for (var i = 0; i < array.length; i++) { + if (array[i] === item) { + orderedRemoveItemAt(array, i); + return true; + } + } + return false; + } + ts.orderedRemoveItem = orderedRemoveItem; + /** Remove an item by index from an array, moving everything to its right one space left. */ + function orderedRemoveItemAt(array, index) { + // This seems to be faster than either `array.splice(i, 1)` or `array.copyWithin(i, i+ 1)`. + for (var i = index; i < array.length - 1; i++) { + array[i] = array[i + 1]; + } + array.pop(); + } + ts.orderedRemoveItemAt = orderedRemoveItemAt; + function unorderedRemoveItemAt(array, index) { + // Fill in the "hole" left at `index`. + array[index] = array[array.length - 1]; + array.pop(); + } + ts.unorderedRemoveItemAt = unorderedRemoveItemAt; + /** Remove the *first* occurrence of `item` from the array. */ + function unorderedRemoveItem(array, item) { + return unorderedRemoveFirstItemWhere(array, function (element) { return element === item; }); + } + ts.unorderedRemoveItem = unorderedRemoveItem; + /** Remove the *first* element satisfying `predicate`. */ + function unorderedRemoveFirstItemWhere(array, predicate) { + for (var i = 0; i < array.length; i++) { + if (predicate(array[i])) { + unorderedRemoveItemAt(array, i); + return true; + } + } + return false; + } + function createGetCanonicalFileName(useCaseSensitiveFileNames) { + return useCaseSensitiveFileNames ? identity : toLowerCase; + } + ts.createGetCanonicalFileName = createGetCanonicalFileName; + function patternText(_a) { + var prefix = _a.prefix, suffix = _a.suffix; + return prefix + "*" + suffix; + } + ts.patternText = patternText; + /** + * Given that candidate matches pattern, returns the text matching the '*'. + * E.g.: matchedText(tryParsePattern("foo*baz"), "foobarbaz") === "bar" + */ + function matchedText(pattern, candidate) { + Debug.assert(isPatternMatch(pattern, candidate)); + return candidate.substring(pattern.prefix.length, candidate.length - pattern.suffix.length); + } + ts.matchedText = matchedText; + /** Return the object corresponding to the best pattern to match `candidate`. */ + function findBestPatternMatch(values, getPattern, candidate) { + var matchedValue; + // use length of prefix as betterness criteria + var longestMatchPrefixLength = -1; + for (var _i = 0, values_2 = values; _i < values_2.length; _i++) { + var v = values_2[_i]; + var pattern = getPattern(v); + if (isPatternMatch(pattern, candidate) && pattern.prefix.length > longestMatchPrefixLength) { + longestMatchPrefixLength = pattern.prefix.length; + matchedValue = v; + } + } + return matchedValue; + } + ts.findBestPatternMatch = findBestPatternMatch; + function startsWith(str, prefix) { + return str.lastIndexOf(prefix, 0) === 0; + } + ts.startsWith = startsWith; + function removePrefix(str, prefix) { + return startsWith(str, prefix) ? str.substr(prefix.length) : str; + } + ts.removePrefix = removePrefix; + function tryRemovePrefix(str, prefix, getCanonicalFileName) { + if (getCanonicalFileName === void 0) { getCanonicalFileName = identity; } + return startsWith(getCanonicalFileName(str), getCanonicalFileName(prefix)) ? str.substring(prefix.length) : undefined; + } + ts.tryRemovePrefix = tryRemovePrefix; + function isPatternMatch(_a, candidate) { + var prefix = _a.prefix, suffix = _a.suffix; + return candidate.length >= prefix.length + suffix.length && + startsWith(candidate, prefix) && + endsWith(candidate, suffix); + } + function and(f, g) { + return function (arg) { return f(arg) && g(arg); }; + } + ts.and = and; + function or(f, g) { + return function (arg) { return f(arg) || g(arg); }; + } + ts.or = or; + function assertType(_) { } // tslint:disable-line no-empty + ts.assertType = assertType; + function singleElementArray(t) { + return t === undefined ? undefined : [t]; + } + ts.singleElementArray = singleElementArray; + function enumerateInsertsAndDeletes(newItems, oldItems, comparer, inserted, deleted, unchanged) { + unchanged = unchanged || noop; + var newIndex = 0; + var oldIndex = 0; + var newLen = newItems.length; + var oldLen = oldItems.length; + while (newIndex < newLen && oldIndex < oldLen) { + var newItem = newItems[newIndex]; + var oldItem = oldItems[oldIndex]; + var compareResult = comparer(newItem, oldItem); + if (compareResult === -1 /* LessThan */) { + inserted(newItem); + newIndex++; + } + else if (compareResult === 1 /* GreaterThan */) { + deleted(oldItem); + oldIndex++; + } + else { + unchanged(oldItem, newItem); + newIndex++; + oldIndex++; + } + } + while (newIndex < newLen) { + inserted(newItems[newIndex++]); + } + while (oldIndex < oldLen) { + deleted(oldItems[oldIndex++]); + } + } + ts.enumerateInsertsAndDeletes = enumerateInsertsAndDeletes; + function fill(length, cb) { + return new Array(length).fill(0).map(function (_, i) { return cb(i); }); + } + ts.fill = fill; +})(ts || (ts = {})); +/*@internal*/ +var ts; +(function (ts) { + /** Gets a timestamp with (at least) ms resolution */ + ts.timestamp = typeof performance !== "undefined" && performance.now ? function () { return performance.now(); } : Date.now ? Date.now : function () { return +(new Date()); }; +})(ts || (ts = {})); +/*@internal*/ +/** Performance measurements for the compiler. */ +(function (ts) { + var performance; + (function (performance) { + // NOTE: cannot use ts.noop as core.ts loads after this + var profilerEvent = typeof onProfilerEvent === "function" && onProfilerEvent.profiler === true ? onProfilerEvent : function () { }; + var enabled = false; + var profilerStart = 0; + var counts; + var marks; + var measures; + function createTimerIf(condition, measureName, startMarkName, endMarkName) { + return condition ? createTimer(measureName, startMarkName, endMarkName) : performance.nullTimer; + } + performance.createTimerIf = createTimerIf; + function createTimer(measureName, startMarkName, endMarkName) { + var enterCount = 0; + return { + enter: enter, + exit: exit + }; + function enter() { + if (++enterCount === 1) { + mark(startMarkName); + } + } + function exit() { + if (--enterCount === 0) { + mark(endMarkName); + measure(measureName, startMarkName, endMarkName); + } + else if (enterCount < 0) { + ts.Debug.fail("enter/exit count does not match."); + } + } + } + performance.createTimer = createTimer; + performance.nullTimer = { enter: ts.noop, exit: ts.noop }; + /** + * Marks a performance event. + * + * @param markName The name of the mark. + */ + function mark(markName) { + if (enabled) { + marks.set(markName, ts.timestamp()); + counts.set(markName, (counts.get(markName) || 0) + 1); + profilerEvent(markName); + } + } + performance.mark = mark; + /** + * Adds a performance measurement with the specified name. + * + * @param measureName The name of the performance measurement. + * @param startMarkName The name of the starting mark. If not supplied, the point at which the + * profiler was enabled is used. + * @param endMarkName The name of the ending mark. If not supplied, the current timestamp is + * used. + */ + function measure(measureName, startMarkName, endMarkName) { + if (enabled) { + var end = endMarkName && marks.get(endMarkName) || ts.timestamp(); + var start = startMarkName && marks.get(startMarkName) || profilerStart; + measures.set(measureName, (measures.get(measureName) || 0) + (end - start)); + } + } + performance.measure = measure; + /** + * Gets the number of times a marker was encountered. + * + * @param markName The name of the mark. + */ + function getCount(markName) { + return counts && counts.get(markName) || 0; + } + performance.getCount = getCount; + /** + * Gets the total duration of all measurements with the supplied name. + * + * @param measureName The name of the measure whose durations should be accumulated. + */ + function getDuration(measureName) { + return measures && measures.get(measureName) || 0; + } + performance.getDuration = getDuration; + /** + * Iterate over each measure, performing some action + * + * @param cb The action to perform for each measure + */ + function forEachMeasure(cb) { + measures.forEach(function (measure, key) { + cb(key, measure); + }); + } + performance.forEachMeasure = forEachMeasure; + /** Enables (and resets) performance measurements for the compiler. */ + function enable() { + counts = ts.createMap(); + marks = ts.createMap(); + measures = ts.createMap(); + enabled = true; + profilerStart = ts.timestamp(); + } + performance.enable = enable; + /** Disables performance measurements for the compiler. */ + function disable() { + enabled = false; + } + performance.disable = disable; + })(performance = ts.performance || (ts.performance = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + // https://semver.org/#spec-item-2 + // > A normal version number MUST take the form X.Y.Z where X, Y, and Z are non-negative + // > integers, and MUST NOT contain leading zeroes. X is the major version, Y is the minor + // > version, and Z is the patch version. Each element MUST increase numerically. + // + // NOTE: We differ here in that we allow X and X.Y, with missing parts having the default + // value of `0`. + var versionRegExp = /^(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\-([a-z0-9-.]+))?(?:\+([a-z0-9-.]+))?)?)?$/i; + // https://semver.org/#spec-item-9 + // > A pre-release version MAY be denoted by appending a hyphen and a series of dot separated + // > identifiers immediately following the patch version. Identifiers MUST comprise only ASCII + // > alphanumerics and hyphen [0-9A-Za-z-]. Identifiers MUST NOT be empty. Numeric identifiers + // > MUST NOT include leading zeroes. + var prereleaseRegExp = /^(?:0|[1-9]\d*|[a-z-][a-z0-9-]*)(?:\.(?:0|[1-9]\d*|[a-z-][a-z0-9-]*))*$/i; + // https://semver.org/#spec-item-10 + // > Build metadata MAY be denoted by appending a plus sign and a series of dot separated + // > identifiers immediately following the patch or pre-release version. Identifiers MUST + // > comprise only ASCII alphanumerics and hyphen [0-9A-Za-z-]. Identifiers MUST NOT be empty. + var buildRegExp = /^[a-z0-9-]+(?:\.[a-z0-9-]+)*$/i; + // https://semver.org/#spec-item-9 + // > Numeric identifiers MUST NOT include leading zeroes. + var numericIdentifierRegExp = /^(0|[1-9]\d*)$/; + /** + * Describes a precise semantic version number, https://semver.org + */ + var Version = /** @class */ (function () { + function Version(major, minor, patch, prerelease, build) { + if (minor === void 0) { minor = 0; } + if (patch === void 0) { patch = 0; } + if (prerelease === void 0) { prerelease = ""; } + if (build === void 0) { build = ""; } + if (typeof major === "string") { + var result = ts.Debug.assertDefined(tryParseComponents(major), "Invalid version"); + (major = result.major, minor = result.minor, patch = result.patch, prerelease = result.prerelease, build = result.build); + } + ts.Debug.assert(major >= 0, "Invalid argument: major"); + ts.Debug.assert(minor >= 0, "Invalid argument: minor"); + ts.Debug.assert(patch >= 0, "Invalid argument: patch"); + ts.Debug.assert(!prerelease || prereleaseRegExp.test(prerelease), "Invalid argument: prerelease"); + ts.Debug.assert(!build || buildRegExp.test(build), "Invalid argument: build"); + this.major = major; + this.minor = minor; + this.patch = patch; + this.prerelease = prerelease ? prerelease.split(".") : ts.emptyArray; + this.build = build ? build.split(".") : ts.emptyArray; + } + Version.tryParse = function (text) { + var result = tryParseComponents(text); + if (!result) + return undefined; + var major = result.major, minor = result.minor, patch = result.patch, prerelease = result.prerelease, build = result.build; + return new Version(major, minor, patch, prerelease, build); + }; + Version.prototype.compareTo = function (other) { + // https://semver.org/#spec-item-11 + // > Precedence is determined by the first difference when comparing each of these + // > identifiers from left to right as follows: Major, minor, and patch versions are + // > always compared numerically. + // + // https://semver.org/#spec-item-11 + // > Precedence for two pre-release versions with the same major, minor, and patch version + // > MUST be determined by comparing each dot separated identifier from left to right until + // > a difference is found [...] + // + // https://semver.org/#spec-item-11 + // > Build metadata does not figure into precedence + if (this === other) + return 0 /* EqualTo */; + if (other === undefined) + return 1 /* GreaterThan */; + return ts.compareValues(this.major, other.major) + || ts.compareValues(this.minor, other.minor) + || ts.compareValues(this.patch, other.patch) + || comparePrerelaseIdentifiers(this.prerelease, other.prerelease); + }; + Version.prototype.increment = function (field) { + switch (field) { + case "major": return new Version(this.major + 1, 0, 0); + case "minor": return new Version(this.major, this.minor + 1, 0); + case "patch": return new Version(this.major, this.minor, this.patch + 1); + default: return ts.Debug.assertNever(field); + } + }; + Version.prototype.toString = function () { + var result = this.major + "." + this.minor + "." + this.patch; + if (ts.some(this.prerelease)) + result += "-" + this.prerelease.join("."); + if (ts.some(this.build)) + result += "+" + this.build.join("."); + return result; + }; + Version.zero = new Version(0, 0, 0); + return Version; + }()); + ts.Version = Version; + function tryParseComponents(text) { + var match = versionRegExp.exec(text); + if (!match) + return undefined; + var major = match[1], _a = match[2], minor = _a === void 0 ? "0" : _a, _b = match[3], patch = _b === void 0 ? "0" : _b, _c = match[4], prerelease = _c === void 0 ? "" : _c, _d = match[5], build = _d === void 0 ? "" : _d; + if (prerelease && !prereleaseRegExp.test(prerelease)) + return undefined; + if (build && !buildRegExp.test(build)) + return undefined; + return { + major: parseInt(major, 10), + minor: parseInt(minor, 10), + patch: parseInt(patch, 10), + prerelease: prerelease, + build: build + }; + } + function comparePrerelaseIdentifiers(left, right) { + // https://semver.org/#spec-item-11 + // > When major, minor, and patch are equal, a pre-release version has lower precedence + // > than a normal version. + if (left === right) + return 0 /* EqualTo */; + if (left.length === 0) + return right.length === 0 ? 0 /* EqualTo */ : 1 /* GreaterThan */; + if (right.length === 0) + return -1 /* LessThan */; + // https://semver.org/#spec-item-11 + // > Precedence for two pre-release versions with the same major, minor, and patch version + // > MUST be determined by comparing each dot separated identifier from left to right until + // > a difference is found [...] + var length = Math.min(left.length, right.length); + for (var i = 0; i < length; i++) { + var leftIdentifier = left[i]; + var rightIdentifier = right[i]; + if (leftIdentifier === rightIdentifier) + continue; + var leftIsNumeric = numericIdentifierRegExp.test(leftIdentifier); + var rightIsNumeric = numericIdentifierRegExp.test(rightIdentifier); + if (leftIsNumeric || rightIsNumeric) { + // https://semver.org/#spec-item-11 + // > Numeric identifiers always have lower precedence than non-numeric identifiers. + if (leftIsNumeric !== rightIsNumeric) + return leftIsNumeric ? -1 /* LessThan */ : 1 /* GreaterThan */; + // https://semver.org/#spec-item-11 + // > identifiers consisting of only digits are compared numerically + var result = ts.compareValues(+leftIdentifier, +rightIdentifier); + if (result) + return result; + } + else { + // https://semver.org/#spec-item-11 + // > identifiers with letters or hyphens are compared lexically in ASCII sort order. + var result = ts.compareStringsCaseSensitive(leftIdentifier, rightIdentifier); + if (result) + return result; + } + } + // https://semver.org/#spec-item-11 + // > A larger set of pre-release fields has a higher precedence than a smaller set, if all + // > of the preceding identifiers are equal. + return ts.compareValues(left.length, right.length); + } + /** + * Describes a semantic version range, per https://github.com/npm/node-semver#ranges + */ + var VersionRange = /** @class */ (function () { + function VersionRange(spec) { + this._alternatives = spec ? ts.Debug.assertDefined(parseRange(spec), "Invalid range spec.") : ts.emptyArray; + } + VersionRange.tryParse = function (text) { + var sets = parseRange(text); + if (sets) { + var range = new VersionRange(""); + range._alternatives = sets; + return range; + } + return undefined; + }; + VersionRange.prototype.test = function (version) { + if (typeof version === "string") + version = new Version(version); + return testDisjunction(version, this._alternatives); + }; + VersionRange.prototype.toString = function () { + return formatDisjunction(this._alternatives); + }; + return VersionRange; + }()); + ts.VersionRange = VersionRange; + // https://github.com/npm/node-semver#range-grammar + // + // range-set ::= range ( logical-or range ) * + // range ::= hyphen | simple ( ' ' simple ) * | '' + // logical-or ::= ( ' ' ) * '||' ( ' ' ) * + var logicalOrRegExp = /\s*\|\|\s*/g; + var whitespaceRegExp = /\s+/g; + // https://github.com/npm/node-semver#range-grammar + // + // partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )? + // xr ::= 'x' | 'X' | '*' | nr + // nr ::= '0' | ['1'-'9'] ( ['0'-'9'] ) * + // qualifier ::= ( '-' pre )? ( '+' build )? + // pre ::= parts + // build ::= parts + // parts ::= part ( '.' part ) * + // part ::= nr | [-0-9A-Za-z]+ + var partialRegExp = /^([xX*0]|[1-9]\d*)(?:\.([xX*0]|[1-9]\d*)(?:\.([xX*0]|[1-9]\d*)(?:-([a-z0-9-.]+))?(?:\+([a-z0-9-.]+))?)?)?$/i; + // https://github.com/npm/node-semver#range-grammar + // + // hyphen ::= partial ' - ' partial + var hyphenRegExp = /^\s*([a-z0-9-+.*]+)\s+-\s+([a-z0-9-+.*]+)\s*$/i; + // https://github.com/npm/node-semver#range-grammar + // + // simple ::= primitive | partial | tilde | caret + // primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial + // tilde ::= '~' partial + // caret ::= '^' partial + var rangeRegExp = /^\s*(~|\^|<|<=|>|>=|=)?\s*([a-z0-9-+.*]+)$/i; + function parseRange(text) { + var alternatives = []; + for (var _i = 0, _a = text.trim().split(logicalOrRegExp); _i < _a.length; _i++) { + var range = _a[_i]; + if (!range) + continue; + var comparators = []; + var match = hyphenRegExp.exec(range); + if (match) { + if (!parseHyphen(match[1], match[2], comparators)) + return undefined; + } + else { + for (var _b = 0, _c = range.split(whitespaceRegExp); _b < _c.length; _b++) { + var simple = _c[_b]; + var match_1 = rangeRegExp.exec(simple); + if (!match_1 || !parseComparator(match_1[1], match_1[2], comparators)) + return undefined; + } + } + alternatives.push(comparators); + } + return alternatives; + } + function parsePartial(text) { + var match = partialRegExp.exec(text); + if (!match) + return undefined; + var major = match[1], _a = match[2], minor = _a === void 0 ? "*" : _a, _b = match[3], patch = _b === void 0 ? "*" : _b, prerelease = match[4], build = match[5]; + var version = new Version(isWildcard(major) ? 0 : parseInt(major, 10), isWildcard(major) || isWildcard(minor) ? 0 : parseInt(minor, 10), isWildcard(major) || isWildcard(minor) || isWildcard(patch) ? 0 : parseInt(patch, 10), prerelease, build); + return { version: version, major: major, minor: minor, patch: patch }; + } + function parseHyphen(left, right, comparators) { + var leftResult = parsePartial(left); + if (!leftResult) + return false; + var rightResult = parsePartial(right); + if (!rightResult) + return false; + if (!isWildcard(leftResult.major)) { + comparators.push(createComparator(">=", leftResult.version)); + } + if (!isWildcard(rightResult.major)) { + comparators.push(isWildcard(rightResult.minor) ? createComparator("<", rightResult.version.increment("major")) : + isWildcard(rightResult.patch) ? createComparator("<", rightResult.version.increment("minor")) : + createComparator("<=", rightResult.version)); + } + return true; + } + function parseComparator(operator, text, comparators) { + var result = parsePartial(text); + if (!result) + return false; + var version = result.version, major = result.major, minor = result.minor, patch = result.patch; + if (!isWildcard(major)) { + switch (operator) { + case "~": + comparators.push(createComparator(">=", version)); + comparators.push(createComparator("<", version.increment(isWildcard(minor) ? "major" : + "minor"))); + break; + case "^": + comparators.push(createComparator(">=", version)); + comparators.push(createComparator("<", version.increment(version.major > 0 || isWildcard(minor) ? "major" : + version.minor > 0 || isWildcard(patch) ? "minor" : + "patch"))); + break; + case "<": + case ">=": + comparators.push(createComparator(operator, version)); + break; + case "<=": + case ">": + comparators.push(isWildcard(minor) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("major")) : + isWildcard(patch) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("minor")) : + createComparator(operator, version)); + break; + case "=": + case undefined: + if (isWildcard(minor) || isWildcard(patch)) { + comparators.push(createComparator(">=", version)); + comparators.push(createComparator("<", version.increment(isWildcard(minor) ? "major" : "minor"))); + } + else { + comparators.push(createComparator("=", version)); + } + break; + default: + // unrecognized + return false; + } + } + else if (operator === "<" || operator === ">") { + comparators.push(createComparator("<", Version.zero)); + } + return true; + } + function isWildcard(part) { + return part === "*" || part === "x" || part === "X"; + } + function createComparator(operator, operand) { + return { operator: operator, operand: operand }; + } + function testDisjunction(version, alternatives) { + // an empty disjunction is treated as "*" (all versions) + if (alternatives.length === 0) + return true; + for (var _i = 0, alternatives_1 = alternatives; _i < alternatives_1.length; _i++) { + var alternative = alternatives_1[_i]; + if (testAlternative(version, alternative)) + return true; + } + return false; + } + function testAlternative(version, comparators) { + for (var _i = 0, comparators_1 = comparators; _i < comparators_1.length; _i++) { + var comparator = comparators_1[_i]; + if (!testComparator(version, comparator.operator, comparator.operand)) + return false; + } + return true; + } + function testComparator(version, operator, operand) { + var cmp = version.compareTo(operand); + switch (operator) { + case "<": return cmp < 0; + case "<=": return cmp <= 0; + case ">": return cmp > 0; + case ">=": return cmp >= 0; + case "=": return cmp === 0; + default: return ts.Debug.assertNever(operator); + } + } + function formatDisjunction(alternatives) { + return ts.map(alternatives, formatAlternative).join(" || ") || "*"; + } + function formatAlternative(comparators) { + return ts.map(comparators, formatComparator).join(" "); + } + function formatComparator(comparator) { + return "" + comparator.operator + comparator.operand; + } +})(ts || (ts = {})); +var ts; +(function (ts) { + // token > SyntaxKind.Identifier => token is a keyword + // Also, If you add a new SyntaxKind be sure to keep the `Markers` section at the bottom in sync + var SyntaxKind; + (function (SyntaxKind) { + SyntaxKind[SyntaxKind["Unknown"] = 0] = "Unknown"; + SyntaxKind[SyntaxKind["EndOfFileToken"] = 1] = "EndOfFileToken"; + SyntaxKind[SyntaxKind["SingleLineCommentTrivia"] = 2] = "SingleLineCommentTrivia"; + SyntaxKind[SyntaxKind["MultiLineCommentTrivia"] = 3] = "MultiLineCommentTrivia"; + SyntaxKind[SyntaxKind["NewLineTrivia"] = 4] = "NewLineTrivia"; + SyntaxKind[SyntaxKind["WhitespaceTrivia"] = 5] = "WhitespaceTrivia"; + // We detect and preserve #! on the first line + SyntaxKind[SyntaxKind["ShebangTrivia"] = 6] = "ShebangTrivia"; + // We detect and provide better error recovery when we encounter a git merge marker. This + // allows us to edit files with git-conflict markers in them in a much more pleasant manner. + SyntaxKind[SyntaxKind["ConflictMarkerTrivia"] = 7] = "ConflictMarkerTrivia"; + // Literals + SyntaxKind[SyntaxKind["NumericLiteral"] = 8] = "NumericLiteral"; + SyntaxKind[SyntaxKind["BigIntLiteral"] = 9] = "BigIntLiteral"; + SyntaxKind[SyntaxKind["StringLiteral"] = 10] = "StringLiteral"; + SyntaxKind[SyntaxKind["JsxText"] = 11] = "JsxText"; + SyntaxKind[SyntaxKind["JsxTextAllWhiteSpaces"] = 12] = "JsxTextAllWhiteSpaces"; + SyntaxKind[SyntaxKind["RegularExpressionLiteral"] = 13] = "RegularExpressionLiteral"; + SyntaxKind[SyntaxKind["NoSubstitutionTemplateLiteral"] = 14] = "NoSubstitutionTemplateLiteral"; + // Pseudo-literals + SyntaxKind[SyntaxKind["TemplateHead"] = 15] = "TemplateHead"; + SyntaxKind[SyntaxKind["TemplateMiddle"] = 16] = "TemplateMiddle"; + SyntaxKind[SyntaxKind["TemplateTail"] = 17] = "TemplateTail"; + // Punctuation + SyntaxKind[SyntaxKind["OpenBraceToken"] = 18] = "OpenBraceToken"; + SyntaxKind[SyntaxKind["CloseBraceToken"] = 19] = "CloseBraceToken"; + SyntaxKind[SyntaxKind["OpenParenToken"] = 20] = "OpenParenToken"; + SyntaxKind[SyntaxKind["CloseParenToken"] = 21] = "CloseParenToken"; + SyntaxKind[SyntaxKind["OpenBracketToken"] = 22] = "OpenBracketToken"; + SyntaxKind[SyntaxKind["CloseBracketToken"] = 23] = "CloseBracketToken"; + SyntaxKind[SyntaxKind["DotToken"] = 24] = "DotToken"; + SyntaxKind[SyntaxKind["DotDotDotToken"] = 25] = "DotDotDotToken"; + SyntaxKind[SyntaxKind["SemicolonToken"] = 26] = "SemicolonToken"; + SyntaxKind[SyntaxKind["CommaToken"] = 27] = "CommaToken"; + SyntaxKind[SyntaxKind["LessThanToken"] = 28] = "LessThanToken"; + SyntaxKind[SyntaxKind["LessThanSlashToken"] = 29] = "LessThanSlashToken"; + SyntaxKind[SyntaxKind["GreaterThanToken"] = 30] = "GreaterThanToken"; + SyntaxKind[SyntaxKind["LessThanEqualsToken"] = 31] = "LessThanEqualsToken"; + SyntaxKind[SyntaxKind["GreaterThanEqualsToken"] = 32] = "GreaterThanEqualsToken"; + SyntaxKind[SyntaxKind["EqualsEqualsToken"] = 33] = "EqualsEqualsToken"; + SyntaxKind[SyntaxKind["ExclamationEqualsToken"] = 34] = "ExclamationEqualsToken"; + SyntaxKind[SyntaxKind["EqualsEqualsEqualsToken"] = 35] = "EqualsEqualsEqualsToken"; + SyntaxKind[SyntaxKind["ExclamationEqualsEqualsToken"] = 36] = "ExclamationEqualsEqualsToken"; + SyntaxKind[SyntaxKind["EqualsGreaterThanToken"] = 37] = "EqualsGreaterThanToken"; + SyntaxKind[SyntaxKind["PlusToken"] = 38] = "PlusToken"; + SyntaxKind[SyntaxKind["MinusToken"] = 39] = "MinusToken"; + SyntaxKind[SyntaxKind["AsteriskToken"] = 40] = "AsteriskToken"; + SyntaxKind[SyntaxKind["AsteriskAsteriskToken"] = 41] = "AsteriskAsteriskToken"; + SyntaxKind[SyntaxKind["SlashToken"] = 42] = "SlashToken"; + SyntaxKind[SyntaxKind["PercentToken"] = 43] = "PercentToken"; + SyntaxKind[SyntaxKind["PlusPlusToken"] = 44] = "PlusPlusToken"; + SyntaxKind[SyntaxKind["MinusMinusToken"] = 45] = "MinusMinusToken"; + SyntaxKind[SyntaxKind["LessThanLessThanToken"] = 46] = "LessThanLessThanToken"; + SyntaxKind[SyntaxKind["GreaterThanGreaterThanToken"] = 47] = "GreaterThanGreaterThanToken"; + SyntaxKind[SyntaxKind["GreaterThanGreaterThanGreaterThanToken"] = 48] = "GreaterThanGreaterThanGreaterThanToken"; + SyntaxKind[SyntaxKind["AmpersandToken"] = 49] = "AmpersandToken"; + SyntaxKind[SyntaxKind["BarToken"] = 50] = "BarToken"; + SyntaxKind[SyntaxKind["CaretToken"] = 51] = "CaretToken"; + SyntaxKind[SyntaxKind["ExclamationToken"] = 52] = "ExclamationToken"; + SyntaxKind[SyntaxKind["TildeToken"] = 53] = "TildeToken"; + SyntaxKind[SyntaxKind["AmpersandAmpersandToken"] = 54] = "AmpersandAmpersandToken"; + SyntaxKind[SyntaxKind["BarBarToken"] = 55] = "BarBarToken"; + SyntaxKind[SyntaxKind["QuestionToken"] = 56] = "QuestionToken"; + SyntaxKind[SyntaxKind["ColonToken"] = 57] = "ColonToken"; + SyntaxKind[SyntaxKind["AtToken"] = 58] = "AtToken"; + // Assignments + SyntaxKind[SyntaxKind["EqualsToken"] = 59] = "EqualsToken"; + SyntaxKind[SyntaxKind["PlusEqualsToken"] = 60] = "PlusEqualsToken"; + SyntaxKind[SyntaxKind["MinusEqualsToken"] = 61] = "MinusEqualsToken"; + SyntaxKind[SyntaxKind["AsteriskEqualsToken"] = 62] = "AsteriskEqualsToken"; + SyntaxKind[SyntaxKind["AsteriskAsteriskEqualsToken"] = 63] = "AsteriskAsteriskEqualsToken"; + SyntaxKind[SyntaxKind["SlashEqualsToken"] = 64] = "SlashEqualsToken"; + SyntaxKind[SyntaxKind["PercentEqualsToken"] = 65] = "PercentEqualsToken"; + SyntaxKind[SyntaxKind["LessThanLessThanEqualsToken"] = 66] = "LessThanLessThanEqualsToken"; + SyntaxKind[SyntaxKind["GreaterThanGreaterThanEqualsToken"] = 67] = "GreaterThanGreaterThanEqualsToken"; + SyntaxKind[SyntaxKind["GreaterThanGreaterThanGreaterThanEqualsToken"] = 68] = "GreaterThanGreaterThanGreaterThanEqualsToken"; + SyntaxKind[SyntaxKind["AmpersandEqualsToken"] = 69] = "AmpersandEqualsToken"; + SyntaxKind[SyntaxKind["BarEqualsToken"] = 70] = "BarEqualsToken"; + SyntaxKind[SyntaxKind["CaretEqualsToken"] = 71] = "CaretEqualsToken"; + // Identifiers + SyntaxKind[SyntaxKind["Identifier"] = 72] = "Identifier"; + // Reserved words + SyntaxKind[SyntaxKind["BreakKeyword"] = 73] = "BreakKeyword"; + SyntaxKind[SyntaxKind["CaseKeyword"] = 74] = "CaseKeyword"; + SyntaxKind[SyntaxKind["CatchKeyword"] = 75] = "CatchKeyword"; + SyntaxKind[SyntaxKind["ClassKeyword"] = 76] = "ClassKeyword"; + SyntaxKind[SyntaxKind["ConstKeyword"] = 77] = "ConstKeyword"; + SyntaxKind[SyntaxKind["ContinueKeyword"] = 78] = "ContinueKeyword"; + SyntaxKind[SyntaxKind["DebuggerKeyword"] = 79] = "DebuggerKeyword"; + SyntaxKind[SyntaxKind["DefaultKeyword"] = 80] = "DefaultKeyword"; + SyntaxKind[SyntaxKind["DeleteKeyword"] = 81] = "DeleteKeyword"; + SyntaxKind[SyntaxKind["DoKeyword"] = 82] = "DoKeyword"; + SyntaxKind[SyntaxKind["ElseKeyword"] = 83] = "ElseKeyword"; + SyntaxKind[SyntaxKind["EnumKeyword"] = 84] = "EnumKeyword"; + SyntaxKind[SyntaxKind["ExportKeyword"] = 85] = "ExportKeyword"; + SyntaxKind[SyntaxKind["ExtendsKeyword"] = 86] = "ExtendsKeyword"; + SyntaxKind[SyntaxKind["FalseKeyword"] = 87] = "FalseKeyword"; + SyntaxKind[SyntaxKind["FinallyKeyword"] = 88] = "FinallyKeyword"; + SyntaxKind[SyntaxKind["ForKeyword"] = 89] = "ForKeyword"; + SyntaxKind[SyntaxKind["FunctionKeyword"] = 90] = "FunctionKeyword"; + SyntaxKind[SyntaxKind["IfKeyword"] = 91] = "IfKeyword"; + SyntaxKind[SyntaxKind["ImportKeyword"] = 92] = "ImportKeyword"; + SyntaxKind[SyntaxKind["InKeyword"] = 93] = "InKeyword"; + SyntaxKind[SyntaxKind["InstanceOfKeyword"] = 94] = "InstanceOfKeyword"; + SyntaxKind[SyntaxKind["NewKeyword"] = 95] = "NewKeyword"; + SyntaxKind[SyntaxKind["NullKeyword"] = 96] = "NullKeyword"; + SyntaxKind[SyntaxKind["ReturnKeyword"] = 97] = "ReturnKeyword"; + SyntaxKind[SyntaxKind["SuperKeyword"] = 98] = "SuperKeyword"; + SyntaxKind[SyntaxKind["SwitchKeyword"] = 99] = "SwitchKeyword"; + SyntaxKind[SyntaxKind["ThisKeyword"] = 100] = "ThisKeyword"; + SyntaxKind[SyntaxKind["ThrowKeyword"] = 101] = "ThrowKeyword"; + SyntaxKind[SyntaxKind["TrueKeyword"] = 102] = "TrueKeyword"; + SyntaxKind[SyntaxKind["TryKeyword"] = 103] = "TryKeyword"; + SyntaxKind[SyntaxKind["TypeOfKeyword"] = 104] = "TypeOfKeyword"; + SyntaxKind[SyntaxKind["VarKeyword"] = 105] = "VarKeyword"; + SyntaxKind[SyntaxKind["VoidKeyword"] = 106] = "VoidKeyword"; + SyntaxKind[SyntaxKind["WhileKeyword"] = 107] = "WhileKeyword"; + SyntaxKind[SyntaxKind["WithKeyword"] = 108] = "WithKeyword"; + // Strict mode reserved words + SyntaxKind[SyntaxKind["ImplementsKeyword"] = 109] = "ImplementsKeyword"; + SyntaxKind[SyntaxKind["InterfaceKeyword"] = 110] = "InterfaceKeyword"; + SyntaxKind[SyntaxKind["LetKeyword"] = 111] = "LetKeyword"; + SyntaxKind[SyntaxKind["PackageKeyword"] = 112] = "PackageKeyword"; + SyntaxKind[SyntaxKind["PrivateKeyword"] = 113] = "PrivateKeyword"; + SyntaxKind[SyntaxKind["ProtectedKeyword"] = 114] = "ProtectedKeyword"; + SyntaxKind[SyntaxKind["PublicKeyword"] = 115] = "PublicKeyword"; + SyntaxKind[SyntaxKind["StaticKeyword"] = 116] = "StaticKeyword"; + SyntaxKind[SyntaxKind["YieldKeyword"] = 117] = "YieldKeyword"; + // Contextual keywords + SyntaxKind[SyntaxKind["AbstractKeyword"] = 118] = "AbstractKeyword"; + SyntaxKind[SyntaxKind["AsKeyword"] = 119] = "AsKeyword"; + SyntaxKind[SyntaxKind["AnyKeyword"] = 120] = "AnyKeyword"; + SyntaxKind[SyntaxKind["AsyncKeyword"] = 121] = "AsyncKeyword"; + SyntaxKind[SyntaxKind["AwaitKeyword"] = 122] = "AwaitKeyword"; + SyntaxKind[SyntaxKind["BooleanKeyword"] = 123] = "BooleanKeyword"; + SyntaxKind[SyntaxKind["ConstructorKeyword"] = 124] = "ConstructorKeyword"; + SyntaxKind[SyntaxKind["DeclareKeyword"] = 125] = "DeclareKeyword"; + SyntaxKind[SyntaxKind["GetKeyword"] = 126] = "GetKeyword"; + SyntaxKind[SyntaxKind["InferKeyword"] = 127] = "InferKeyword"; + SyntaxKind[SyntaxKind["IsKeyword"] = 128] = "IsKeyword"; + SyntaxKind[SyntaxKind["KeyOfKeyword"] = 129] = "KeyOfKeyword"; + SyntaxKind[SyntaxKind["ModuleKeyword"] = 130] = "ModuleKeyword"; + SyntaxKind[SyntaxKind["NamespaceKeyword"] = 131] = "NamespaceKeyword"; + SyntaxKind[SyntaxKind["NeverKeyword"] = 132] = "NeverKeyword"; + SyntaxKind[SyntaxKind["ReadonlyKeyword"] = 133] = "ReadonlyKeyword"; + SyntaxKind[SyntaxKind["RequireKeyword"] = 134] = "RequireKeyword"; + SyntaxKind[SyntaxKind["NumberKeyword"] = 135] = "NumberKeyword"; + SyntaxKind[SyntaxKind["ObjectKeyword"] = 136] = "ObjectKeyword"; + SyntaxKind[SyntaxKind["SetKeyword"] = 137] = "SetKeyword"; + SyntaxKind[SyntaxKind["StringKeyword"] = 138] = "StringKeyword"; + SyntaxKind[SyntaxKind["SymbolKeyword"] = 139] = "SymbolKeyword"; + SyntaxKind[SyntaxKind["TypeKeyword"] = 140] = "TypeKeyword"; + SyntaxKind[SyntaxKind["UndefinedKeyword"] = 141] = "UndefinedKeyword"; + SyntaxKind[SyntaxKind["UniqueKeyword"] = 142] = "UniqueKeyword"; + SyntaxKind[SyntaxKind["UnknownKeyword"] = 143] = "UnknownKeyword"; + SyntaxKind[SyntaxKind["FromKeyword"] = 144] = "FromKeyword"; + SyntaxKind[SyntaxKind["GlobalKeyword"] = 145] = "GlobalKeyword"; + SyntaxKind[SyntaxKind["BigIntKeyword"] = 146] = "BigIntKeyword"; + SyntaxKind[SyntaxKind["OfKeyword"] = 147] = "OfKeyword"; + // Parse tree nodes + // Names + SyntaxKind[SyntaxKind["QualifiedName"] = 148] = "QualifiedName"; + SyntaxKind[SyntaxKind["ComputedPropertyName"] = 149] = "ComputedPropertyName"; + // Signature elements + SyntaxKind[SyntaxKind["TypeParameter"] = 150] = "TypeParameter"; + SyntaxKind[SyntaxKind["Parameter"] = 151] = "Parameter"; + SyntaxKind[SyntaxKind["Decorator"] = 152] = "Decorator"; + // TypeMember + SyntaxKind[SyntaxKind["PropertySignature"] = 153] = "PropertySignature"; + SyntaxKind[SyntaxKind["PropertyDeclaration"] = 154] = "PropertyDeclaration"; + SyntaxKind[SyntaxKind["MethodSignature"] = 155] = "MethodSignature"; + SyntaxKind[SyntaxKind["MethodDeclaration"] = 156] = "MethodDeclaration"; + SyntaxKind[SyntaxKind["Constructor"] = 157] = "Constructor"; + SyntaxKind[SyntaxKind["GetAccessor"] = 158] = "GetAccessor"; + SyntaxKind[SyntaxKind["SetAccessor"] = 159] = "SetAccessor"; + SyntaxKind[SyntaxKind["CallSignature"] = 160] = "CallSignature"; + SyntaxKind[SyntaxKind["ConstructSignature"] = 161] = "ConstructSignature"; + SyntaxKind[SyntaxKind["IndexSignature"] = 162] = "IndexSignature"; + // Type + SyntaxKind[SyntaxKind["TypePredicate"] = 163] = "TypePredicate"; + SyntaxKind[SyntaxKind["TypeReference"] = 164] = "TypeReference"; + SyntaxKind[SyntaxKind["FunctionType"] = 165] = "FunctionType"; + SyntaxKind[SyntaxKind["ConstructorType"] = 166] = "ConstructorType"; + SyntaxKind[SyntaxKind["TypeQuery"] = 167] = "TypeQuery"; + SyntaxKind[SyntaxKind["TypeLiteral"] = 168] = "TypeLiteral"; + SyntaxKind[SyntaxKind["ArrayType"] = 169] = "ArrayType"; + SyntaxKind[SyntaxKind["TupleType"] = 170] = "TupleType"; + SyntaxKind[SyntaxKind["OptionalType"] = 171] = "OptionalType"; + SyntaxKind[SyntaxKind["RestType"] = 172] = "RestType"; + SyntaxKind[SyntaxKind["UnionType"] = 173] = "UnionType"; + SyntaxKind[SyntaxKind["IntersectionType"] = 174] = "IntersectionType"; + SyntaxKind[SyntaxKind["ConditionalType"] = 175] = "ConditionalType"; + SyntaxKind[SyntaxKind["InferType"] = 176] = "InferType"; + SyntaxKind[SyntaxKind["ParenthesizedType"] = 177] = "ParenthesizedType"; + SyntaxKind[SyntaxKind["ThisType"] = 178] = "ThisType"; + SyntaxKind[SyntaxKind["TypeOperator"] = 179] = "TypeOperator"; + SyntaxKind[SyntaxKind["IndexedAccessType"] = 180] = "IndexedAccessType"; + SyntaxKind[SyntaxKind["MappedType"] = 181] = "MappedType"; + SyntaxKind[SyntaxKind["LiteralType"] = 182] = "LiteralType"; + SyntaxKind[SyntaxKind["ImportType"] = 183] = "ImportType"; + // Binding patterns + SyntaxKind[SyntaxKind["ObjectBindingPattern"] = 184] = "ObjectBindingPattern"; + SyntaxKind[SyntaxKind["ArrayBindingPattern"] = 185] = "ArrayBindingPattern"; + SyntaxKind[SyntaxKind["BindingElement"] = 186] = "BindingElement"; + // Expression + SyntaxKind[SyntaxKind["ArrayLiteralExpression"] = 187] = "ArrayLiteralExpression"; + SyntaxKind[SyntaxKind["ObjectLiteralExpression"] = 188] = "ObjectLiteralExpression"; + SyntaxKind[SyntaxKind["PropertyAccessExpression"] = 189] = "PropertyAccessExpression"; + SyntaxKind[SyntaxKind["ElementAccessExpression"] = 190] = "ElementAccessExpression"; + SyntaxKind[SyntaxKind["CallExpression"] = 191] = "CallExpression"; + SyntaxKind[SyntaxKind["NewExpression"] = 192] = "NewExpression"; + SyntaxKind[SyntaxKind["TaggedTemplateExpression"] = 193] = "TaggedTemplateExpression"; + SyntaxKind[SyntaxKind["TypeAssertionExpression"] = 194] = "TypeAssertionExpression"; + SyntaxKind[SyntaxKind["ParenthesizedExpression"] = 195] = "ParenthesizedExpression"; + SyntaxKind[SyntaxKind["FunctionExpression"] = 196] = "FunctionExpression"; + SyntaxKind[SyntaxKind["ArrowFunction"] = 197] = "ArrowFunction"; + SyntaxKind[SyntaxKind["DeleteExpression"] = 198] = "DeleteExpression"; + SyntaxKind[SyntaxKind["TypeOfExpression"] = 199] = "TypeOfExpression"; + SyntaxKind[SyntaxKind["VoidExpression"] = 200] = "VoidExpression"; + SyntaxKind[SyntaxKind["AwaitExpression"] = 201] = "AwaitExpression"; + SyntaxKind[SyntaxKind["PrefixUnaryExpression"] = 202] = "PrefixUnaryExpression"; + SyntaxKind[SyntaxKind["PostfixUnaryExpression"] = 203] = "PostfixUnaryExpression"; + SyntaxKind[SyntaxKind["BinaryExpression"] = 204] = "BinaryExpression"; + SyntaxKind[SyntaxKind["ConditionalExpression"] = 205] = "ConditionalExpression"; + SyntaxKind[SyntaxKind["TemplateExpression"] = 206] = "TemplateExpression"; + SyntaxKind[SyntaxKind["YieldExpression"] = 207] = "YieldExpression"; + SyntaxKind[SyntaxKind["SpreadElement"] = 208] = "SpreadElement"; + SyntaxKind[SyntaxKind["ClassExpression"] = 209] = "ClassExpression"; + SyntaxKind[SyntaxKind["OmittedExpression"] = 210] = "OmittedExpression"; + SyntaxKind[SyntaxKind["ExpressionWithTypeArguments"] = 211] = "ExpressionWithTypeArguments"; + SyntaxKind[SyntaxKind["AsExpression"] = 212] = "AsExpression"; + SyntaxKind[SyntaxKind["NonNullExpression"] = 213] = "NonNullExpression"; + SyntaxKind[SyntaxKind["MetaProperty"] = 214] = "MetaProperty"; + SyntaxKind[SyntaxKind["SyntheticExpression"] = 215] = "SyntheticExpression"; + // Misc + SyntaxKind[SyntaxKind["TemplateSpan"] = 216] = "TemplateSpan"; + SyntaxKind[SyntaxKind["SemicolonClassElement"] = 217] = "SemicolonClassElement"; + // Element + SyntaxKind[SyntaxKind["Block"] = 218] = "Block"; + SyntaxKind[SyntaxKind["VariableStatement"] = 219] = "VariableStatement"; + SyntaxKind[SyntaxKind["EmptyStatement"] = 220] = "EmptyStatement"; + SyntaxKind[SyntaxKind["ExpressionStatement"] = 221] = "ExpressionStatement"; + SyntaxKind[SyntaxKind["IfStatement"] = 222] = "IfStatement"; + SyntaxKind[SyntaxKind["DoStatement"] = 223] = "DoStatement"; + SyntaxKind[SyntaxKind["WhileStatement"] = 224] = "WhileStatement"; + SyntaxKind[SyntaxKind["ForStatement"] = 225] = "ForStatement"; + SyntaxKind[SyntaxKind["ForInStatement"] = 226] = "ForInStatement"; + SyntaxKind[SyntaxKind["ForOfStatement"] = 227] = "ForOfStatement"; + SyntaxKind[SyntaxKind["ContinueStatement"] = 228] = "ContinueStatement"; + SyntaxKind[SyntaxKind["BreakStatement"] = 229] = "BreakStatement"; + SyntaxKind[SyntaxKind["ReturnStatement"] = 230] = "ReturnStatement"; + SyntaxKind[SyntaxKind["WithStatement"] = 231] = "WithStatement"; + SyntaxKind[SyntaxKind["SwitchStatement"] = 232] = "SwitchStatement"; + SyntaxKind[SyntaxKind["LabeledStatement"] = 233] = "LabeledStatement"; + SyntaxKind[SyntaxKind["ThrowStatement"] = 234] = "ThrowStatement"; + SyntaxKind[SyntaxKind["TryStatement"] = 235] = "TryStatement"; + SyntaxKind[SyntaxKind["DebuggerStatement"] = 236] = "DebuggerStatement"; + SyntaxKind[SyntaxKind["VariableDeclaration"] = 237] = "VariableDeclaration"; + SyntaxKind[SyntaxKind["VariableDeclarationList"] = 238] = "VariableDeclarationList"; + SyntaxKind[SyntaxKind["FunctionDeclaration"] = 239] = "FunctionDeclaration"; + SyntaxKind[SyntaxKind["ClassDeclaration"] = 240] = "ClassDeclaration"; + SyntaxKind[SyntaxKind["InterfaceDeclaration"] = 241] = "InterfaceDeclaration"; + SyntaxKind[SyntaxKind["TypeAliasDeclaration"] = 242] = "TypeAliasDeclaration"; + SyntaxKind[SyntaxKind["EnumDeclaration"] = 243] = "EnumDeclaration"; + SyntaxKind[SyntaxKind["ModuleDeclaration"] = 244] = "ModuleDeclaration"; + SyntaxKind[SyntaxKind["ModuleBlock"] = 245] = "ModuleBlock"; + SyntaxKind[SyntaxKind["CaseBlock"] = 246] = "CaseBlock"; + SyntaxKind[SyntaxKind["NamespaceExportDeclaration"] = 247] = "NamespaceExportDeclaration"; + SyntaxKind[SyntaxKind["ImportEqualsDeclaration"] = 248] = "ImportEqualsDeclaration"; + SyntaxKind[SyntaxKind["ImportDeclaration"] = 249] = "ImportDeclaration"; + SyntaxKind[SyntaxKind["ImportClause"] = 250] = "ImportClause"; + SyntaxKind[SyntaxKind["NamespaceImport"] = 251] = "NamespaceImport"; + SyntaxKind[SyntaxKind["NamedImports"] = 252] = "NamedImports"; + SyntaxKind[SyntaxKind["ImportSpecifier"] = 253] = "ImportSpecifier"; + SyntaxKind[SyntaxKind["ExportAssignment"] = 254] = "ExportAssignment"; + SyntaxKind[SyntaxKind["ExportDeclaration"] = 255] = "ExportDeclaration"; + SyntaxKind[SyntaxKind["NamedExports"] = 256] = "NamedExports"; + SyntaxKind[SyntaxKind["ExportSpecifier"] = 257] = "ExportSpecifier"; + SyntaxKind[SyntaxKind["MissingDeclaration"] = 258] = "MissingDeclaration"; + // Module references + SyntaxKind[SyntaxKind["ExternalModuleReference"] = 259] = "ExternalModuleReference"; + // JSX + SyntaxKind[SyntaxKind["JsxElement"] = 260] = "JsxElement"; + SyntaxKind[SyntaxKind["JsxSelfClosingElement"] = 261] = "JsxSelfClosingElement"; + SyntaxKind[SyntaxKind["JsxOpeningElement"] = 262] = "JsxOpeningElement"; + SyntaxKind[SyntaxKind["JsxClosingElement"] = 263] = "JsxClosingElement"; + SyntaxKind[SyntaxKind["JsxFragment"] = 264] = "JsxFragment"; + SyntaxKind[SyntaxKind["JsxOpeningFragment"] = 265] = "JsxOpeningFragment"; + SyntaxKind[SyntaxKind["JsxClosingFragment"] = 266] = "JsxClosingFragment"; + SyntaxKind[SyntaxKind["JsxAttribute"] = 267] = "JsxAttribute"; + SyntaxKind[SyntaxKind["JsxAttributes"] = 268] = "JsxAttributes"; + SyntaxKind[SyntaxKind["JsxSpreadAttribute"] = 269] = "JsxSpreadAttribute"; + SyntaxKind[SyntaxKind["JsxExpression"] = 270] = "JsxExpression"; + // Clauses + SyntaxKind[SyntaxKind["CaseClause"] = 271] = "CaseClause"; + SyntaxKind[SyntaxKind["DefaultClause"] = 272] = "DefaultClause"; + SyntaxKind[SyntaxKind["HeritageClause"] = 273] = "HeritageClause"; + SyntaxKind[SyntaxKind["CatchClause"] = 274] = "CatchClause"; + // Property assignments + SyntaxKind[SyntaxKind["PropertyAssignment"] = 275] = "PropertyAssignment"; + SyntaxKind[SyntaxKind["ShorthandPropertyAssignment"] = 276] = "ShorthandPropertyAssignment"; + SyntaxKind[SyntaxKind["SpreadAssignment"] = 277] = "SpreadAssignment"; + // Enum + SyntaxKind[SyntaxKind["EnumMember"] = 278] = "EnumMember"; + // Top-level nodes + SyntaxKind[SyntaxKind["SourceFile"] = 279] = "SourceFile"; + SyntaxKind[SyntaxKind["Bundle"] = 280] = "Bundle"; + SyntaxKind[SyntaxKind["UnparsedSource"] = 281] = "UnparsedSource"; + SyntaxKind[SyntaxKind["InputFiles"] = 282] = "InputFiles"; + // JSDoc nodes + SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 283] = "JSDocTypeExpression"; + // The * type + SyntaxKind[SyntaxKind["JSDocAllType"] = 284] = "JSDocAllType"; + // The ? type + SyntaxKind[SyntaxKind["JSDocUnknownType"] = 285] = "JSDocUnknownType"; + SyntaxKind[SyntaxKind["JSDocNullableType"] = 286] = "JSDocNullableType"; + SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 287] = "JSDocNonNullableType"; + SyntaxKind[SyntaxKind["JSDocOptionalType"] = 288] = "JSDocOptionalType"; + SyntaxKind[SyntaxKind["JSDocFunctionType"] = 289] = "JSDocFunctionType"; + SyntaxKind[SyntaxKind["JSDocVariadicType"] = 290] = "JSDocVariadicType"; + SyntaxKind[SyntaxKind["JSDocComment"] = 291] = "JSDocComment"; + SyntaxKind[SyntaxKind["JSDocTypeLiteral"] = 292] = "JSDocTypeLiteral"; + SyntaxKind[SyntaxKind["JSDocSignature"] = 293] = "JSDocSignature"; + SyntaxKind[SyntaxKind["JSDocTag"] = 294] = "JSDocTag"; + SyntaxKind[SyntaxKind["JSDocAugmentsTag"] = 295] = "JSDocAugmentsTag"; + SyntaxKind[SyntaxKind["JSDocClassTag"] = 296] = "JSDocClassTag"; + SyntaxKind[SyntaxKind["JSDocCallbackTag"] = 297] = "JSDocCallbackTag"; + SyntaxKind[SyntaxKind["JSDocEnumTag"] = 298] = "JSDocEnumTag"; + SyntaxKind[SyntaxKind["JSDocParameterTag"] = 299] = "JSDocParameterTag"; + SyntaxKind[SyntaxKind["JSDocReturnTag"] = 300] = "JSDocReturnTag"; + SyntaxKind[SyntaxKind["JSDocThisTag"] = 301] = "JSDocThisTag"; + SyntaxKind[SyntaxKind["JSDocTypeTag"] = 302] = "JSDocTypeTag"; + SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 303] = "JSDocTemplateTag"; + SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 304] = "JSDocTypedefTag"; + SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 305] = "JSDocPropertyTag"; + // Synthesized list + SyntaxKind[SyntaxKind["SyntaxList"] = 306] = "SyntaxList"; + // Transformation nodes + SyntaxKind[SyntaxKind["NotEmittedStatement"] = 307] = "NotEmittedStatement"; + SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 308] = "PartiallyEmittedExpression"; + SyntaxKind[SyntaxKind["CommaListExpression"] = 309] = "CommaListExpression"; + SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 310] = "MergeDeclarationMarker"; + SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 311] = "EndOfDeclarationMarker"; + // Enum value count + SyntaxKind[SyntaxKind["Count"] = 312] = "Count"; + // Markers + SyntaxKind[SyntaxKind["FirstAssignment"] = 59] = "FirstAssignment"; + SyntaxKind[SyntaxKind["LastAssignment"] = 71] = "LastAssignment"; + SyntaxKind[SyntaxKind["FirstCompoundAssignment"] = 60] = "FirstCompoundAssignment"; + SyntaxKind[SyntaxKind["LastCompoundAssignment"] = 71] = "LastCompoundAssignment"; + SyntaxKind[SyntaxKind["FirstReservedWord"] = 73] = "FirstReservedWord"; + SyntaxKind[SyntaxKind["LastReservedWord"] = 108] = "LastReservedWord"; + SyntaxKind[SyntaxKind["FirstKeyword"] = 73] = "FirstKeyword"; + SyntaxKind[SyntaxKind["LastKeyword"] = 147] = "LastKeyword"; + SyntaxKind[SyntaxKind["FirstFutureReservedWord"] = 109] = "FirstFutureReservedWord"; + SyntaxKind[SyntaxKind["LastFutureReservedWord"] = 117] = "LastFutureReservedWord"; + SyntaxKind[SyntaxKind["FirstTypeNode"] = 163] = "FirstTypeNode"; + SyntaxKind[SyntaxKind["LastTypeNode"] = 183] = "LastTypeNode"; + SyntaxKind[SyntaxKind["FirstPunctuation"] = 18] = "FirstPunctuation"; + SyntaxKind[SyntaxKind["LastPunctuation"] = 71] = "LastPunctuation"; + SyntaxKind[SyntaxKind["FirstToken"] = 0] = "FirstToken"; + SyntaxKind[SyntaxKind["LastToken"] = 147] = "LastToken"; + SyntaxKind[SyntaxKind["FirstTriviaToken"] = 2] = "FirstTriviaToken"; + SyntaxKind[SyntaxKind["LastTriviaToken"] = 7] = "LastTriviaToken"; + SyntaxKind[SyntaxKind["FirstLiteralToken"] = 8] = "FirstLiteralToken"; + SyntaxKind[SyntaxKind["LastLiteralToken"] = 14] = "LastLiteralToken"; + SyntaxKind[SyntaxKind["FirstTemplateToken"] = 14] = "FirstTemplateToken"; + SyntaxKind[SyntaxKind["LastTemplateToken"] = 17] = "LastTemplateToken"; + SyntaxKind[SyntaxKind["FirstBinaryOperator"] = 28] = "FirstBinaryOperator"; + SyntaxKind[SyntaxKind["LastBinaryOperator"] = 71] = "LastBinaryOperator"; + SyntaxKind[SyntaxKind["FirstNode"] = 148] = "FirstNode"; + SyntaxKind[SyntaxKind["FirstJSDocNode"] = 283] = "FirstJSDocNode"; + SyntaxKind[SyntaxKind["LastJSDocNode"] = 305] = "LastJSDocNode"; + SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 294] = "FirstJSDocTagNode"; + SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 305] = "LastJSDocTagNode"; + /* @internal */ SyntaxKind[SyntaxKind["FirstContextualKeyword"] = 118] = "FirstContextualKeyword"; + /* @internal */ SyntaxKind[SyntaxKind["LastContextualKeyword"] = 147] = "LastContextualKeyword"; + })(SyntaxKind = ts.SyntaxKind || (ts.SyntaxKind = {})); + var NodeFlags; + (function (NodeFlags) { + NodeFlags[NodeFlags["None"] = 0] = "None"; + NodeFlags[NodeFlags["Let"] = 1] = "Let"; + NodeFlags[NodeFlags["Const"] = 2] = "Const"; + NodeFlags[NodeFlags["NestedNamespace"] = 4] = "NestedNamespace"; + NodeFlags[NodeFlags["Synthesized"] = 8] = "Synthesized"; + NodeFlags[NodeFlags["Namespace"] = 16] = "Namespace"; + NodeFlags[NodeFlags["ExportContext"] = 32] = "ExportContext"; + NodeFlags[NodeFlags["ContainsThis"] = 64] = "ContainsThis"; + NodeFlags[NodeFlags["HasImplicitReturn"] = 128] = "HasImplicitReturn"; + NodeFlags[NodeFlags["HasExplicitReturn"] = 256] = "HasExplicitReturn"; + NodeFlags[NodeFlags["GlobalAugmentation"] = 512] = "GlobalAugmentation"; + NodeFlags[NodeFlags["HasAsyncFunctions"] = 1024] = "HasAsyncFunctions"; + NodeFlags[NodeFlags["DisallowInContext"] = 2048] = "DisallowInContext"; + NodeFlags[NodeFlags["YieldContext"] = 4096] = "YieldContext"; + NodeFlags[NodeFlags["DecoratorContext"] = 8192] = "DecoratorContext"; + NodeFlags[NodeFlags["AwaitContext"] = 16384] = "AwaitContext"; + NodeFlags[NodeFlags["ThisNodeHasError"] = 32768] = "ThisNodeHasError"; + NodeFlags[NodeFlags["JavaScriptFile"] = 65536] = "JavaScriptFile"; + NodeFlags[NodeFlags["ThisNodeOrAnySubNodesHasError"] = 131072] = "ThisNodeOrAnySubNodesHasError"; + NodeFlags[NodeFlags["HasAggregatedChildData"] = 262144] = "HasAggregatedChildData"; + // These flags will be set when the parser encounters a dynamic import expression or 'import.meta' to avoid + // walking the tree if the flags are not set. However, these flags are just a approximation + // (hence why it's named "PossiblyContainsDynamicImport") because once set, the flags never get cleared. + // During editing, if a dynamic import is removed, incremental parsing will *NOT* clear this flag. + // This means that the tree will always be traversed during module resolution, or when looking for external module indicators. + // However, the removal operation should not occur often and in the case of the + // removal, it is likely that users will add the import anyway. + // The advantage of this approach is its simplicity. For the case of batch compilation, + // we guarantee that users won't have to pay the price of walking the tree if a dynamic import isn't used. + /* @internal */ NodeFlags[NodeFlags["PossiblyContainsDynamicImport"] = 524288] = "PossiblyContainsDynamicImport"; + /* @internal */ NodeFlags[NodeFlags["PossiblyContainsImportMeta"] = 1048576] = "PossiblyContainsImportMeta"; + NodeFlags[NodeFlags["JSDoc"] = 2097152] = "JSDoc"; + /* @internal */ NodeFlags[NodeFlags["Ambient"] = 4194304] = "Ambient"; + /* @internal */ NodeFlags[NodeFlags["InWithStatement"] = 8388608] = "InWithStatement"; + NodeFlags[NodeFlags["JsonFile"] = 16777216] = "JsonFile"; + NodeFlags[NodeFlags["BlockScoped"] = 3] = "BlockScoped"; + NodeFlags[NodeFlags["ReachabilityCheckFlags"] = 384] = "ReachabilityCheckFlags"; + NodeFlags[NodeFlags["ReachabilityAndEmitFlags"] = 1408] = "ReachabilityAndEmitFlags"; + // Parsing context flags + NodeFlags[NodeFlags["ContextFlags"] = 12679168] = "ContextFlags"; + // Exclude these flags when parsing a Type + NodeFlags[NodeFlags["TypeExcludesFlags"] = 20480] = "TypeExcludesFlags"; + // Represents all flags that are potentially set once and + // never cleared on SourceFiles which get re-used in between incremental parses. + // See the comment above on `PossiblyContainsDynamicImport` and `PossiblyContainsImportMeta`. + /* @internal */ NodeFlags[NodeFlags["PermanentlySetIncrementalFlags"] = 1572864] = "PermanentlySetIncrementalFlags"; + })(NodeFlags = ts.NodeFlags || (ts.NodeFlags = {})); + var ModifierFlags; + (function (ModifierFlags) { + ModifierFlags[ModifierFlags["None"] = 0] = "None"; + ModifierFlags[ModifierFlags["Export"] = 1] = "Export"; + ModifierFlags[ModifierFlags["Ambient"] = 2] = "Ambient"; + ModifierFlags[ModifierFlags["Public"] = 4] = "Public"; + ModifierFlags[ModifierFlags["Private"] = 8] = "Private"; + ModifierFlags[ModifierFlags["Protected"] = 16] = "Protected"; + ModifierFlags[ModifierFlags["Static"] = 32] = "Static"; + ModifierFlags[ModifierFlags["Readonly"] = 64] = "Readonly"; + ModifierFlags[ModifierFlags["Abstract"] = 128] = "Abstract"; + ModifierFlags[ModifierFlags["Async"] = 256] = "Async"; + ModifierFlags[ModifierFlags["Default"] = 512] = "Default"; + ModifierFlags[ModifierFlags["Const"] = 2048] = "Const"; + ModifierFlags[ModifierFlags["HasComputedFlags"] = 536870912] = "HasComputedFlags"; + ModifierFlags[ModifierFlags["AccessibilityModifier"] = 28] = "AccessibilityModifier"; + // Accessibility modifiers and 'readonly' can be attached to a parameter in a constructor to make it a property. + ModifierFlags[ModifierFlags["ParameterPropertyModifier"] = 92] = "ParameterPropertyModifier"; + ModifierFlags[ModifierFlags["NonPublicAccessibilityModifier"] = 24] = "NonPublicAccessibilityModifier"; + ModifierFlags[ModifierFlags["TypeScriptModifier"] = 2270] = "TypeScriptModifier"; + ModifierFlags[ModifierFlags["ExportDefault"] = 513] = "ExportDefault"; + ModifierFlags[ModifierFlags["All"] = 3071] = "All"; + })(ModifierFlags = ts.ModifierFlags || (ts.ModifierFlags = {})); + var JsxFlags; + (function (JsxFlags) { + JsxFlags[JsxFlags["None"] = 0] = "None"; + /** An element from a named property of the JSX.IntrinsicElements interface */ + JsxFlags[JsxFlags["IntrinsicNamedElement"] = 1] = "IntrinsicNamedElement"; + /** An element inferred from the string index signature of the JSX.IntrinsicElements interface */ + JsxFlags[JsxFlags["IntrinsicIndexedElement"] = 2] = "IntrinsicIndexedElement"; + JsxFlags[JsxFlags["IntrinsicElement"] = 3] = "IntrinsicElement"; + })(JsxFlags = ts.JsxFlags || (ts.JsxFlags = {})); + /* @internal */ + var RelationComparisonResult; + (function (RelationComparisonResult) { + RelationComparisonResult[RelationComparisonResult["Succeeded"] = 1] = "Succeeded"; + RelationComparisonResult[RelationComparisonResult["Failed"] = 2] = "Failed"; + RelationComparisonResult[RelationComparisonResult["FailedAndReported"] = 3] = "FailedAndReported"; + })(RelationComparisonResult = ts.RelationComparisonResult || (ts.RelationComparisonResult = {})); + /*@internal*/ + var GeneratedIdentifierFlags; + (function (GeneratedIdentifierFlags) { + // Kinds + GeneratedIdentifierFlags[GeneratedIdentifierFlags["None"] = 0] = "None"; + GeneratedIdentifierFlags[GeneratedIdentifierFlags["Auto"] = 1] = "Auto"; + GeneratedIdentifierFlags[GeneratedIdentifierFlags["Loop"] = 2] = "Loop"; + GeneratedIdentifierFlags[GeneratedIdentifierFlags["Unique"] = 3] = "Unique"; + GeneratedIdentifierFlags[GeneratedIdentifierFlags["Node"] = 4] = "Node"; + GeneratedIdentifierFlags[GeneratedIdentifierFlags["KindMask"] = 7] = "KindMask"; + // Flags + GeneratedIdentifierFlags[GeneratedIdentifierFlags["ReservedInNestedScopes"] = 8] = "ReservedInNestedScopes"; + GeneratedIdentifierFlags[GeneratedIdentifierFlags["Optimistic"] = 16] = "Optimistic"; + GeneratedIdentifierFlags[GeneratedIdentifierFlags["FileLevel"] = 32] = "FileLevel"; + })(GeneratedIdentifierFlags = ts.GeneratedIdentifierFlags || (ts.GeneratedIdentifierFlags = {})); + /* @internal */ + var TokenFlags; + (function (TokenFlags) { + TokenFlags[TokenFlags["None"] = 0] = "None"; + TokenFlags[TokenFlags["PrecedingLineBreak"] = 1] = "PrecedingLineBreak"; + TokenFlags[TokenFlags["PrecedingJSDocComment"] = 2] = "PrecedingJSDocComment"; + TokenFlags[TokenFlags["Unterminated"] = 4] = "Unterminated"; + TokenFlags[TokenFlags["ExtendedUnicodeEscape"] = 8] = "ExtendedUnicodeEscape"; + TokenFlags[TokenFlags["Scientific"] = 16] = "Scientific"; + TokenFlags[TokenFlags["Octal"] = 32] = "Octal"; + TokenFlags[TokenFlags["HexSpecifier"] = 64] = "HexSpecifier"; + TokenFlags[TokenFlags["BinarySpecifier"] = 128] = "BinarySpecifier"; + TokenFlags[TokenFlags["OctalSpecifier"] = 256] = "OctalSpecifier"; + TokenFlags[TokenFlags["ContainsSeparator"] = 512] = "ContainsSeparator"; + TokenFlags[TokenFlags["BinaryOrOctalSpecifier"] = 384] = "BinaryOrOctalSpecifier"; + TokenFlags[TokenFlags["NumericLiteralFlags"] = 1008] = "NumericLiteralFlags"; + })(TokenFlags = ts.TokenFlags || (ts.TokenFlags = {})); + var FlowFlags; + (function (FlowFlags) { + FlowFlags[FlowFlags["Unreachable"] = 1] = "Unreachable"; + FlowFlags[FlowFlags["Start"] = 2] = "Start"; + FlowFlags[FlowFlags["BranchLabel"] = 4] = "BranchLabel"; + FlowFlags[FlowFlags["LoopLabel"] = 8] = "LoopLabel"; + FlowFlags[FlowFlags["Assignment"] = 16] = "Assignment"; + FlowFlags[FlowFlags["TrueCondition"] = 32] = "TrueCondition"; + FlowFlags[FlowFlags["FalseCondition"] = 64] = "FalseCondition"; + FlowFlags[FlowFlags["SwitchClause"] = 128] = "SwitchClause"; + FlowFlags[FlowFlags["ArrayMutation"] = 256] = "ArrayMutation"; + FlowFlags[FlowFlags["Referenced"] = 512] = "Referenced"; + FlowFlags[FlowFlags["Shared"] = 1024] = "Shared"; + FlowFlags[FlowFlags["PreFinally"] = 2048] = "PreFinally"; + FlowFlags[FlowFlags["AfterFinally"] = 4096] = "AfterFinally"; + FlowFlags[FlowFlags["Label"] = 12] = "Label"; + FlowFlags[FlowFlags["Condition"] = 96] = "Condition"; + })(FlowFlags = ts.FlowFlags || (ts.FlowFlags = {})); + var OperationCanceledException = /** @class */ (function () { + function OperationCanceledException() { + } + return OperationCanceledException; + }()); + ts.OperationCanceledException = OperationCanceledException; + /* @internal */ + var StructureIsReused; + (function (StructureIsReused) { + StructureIsReused[StructureIsReused["Not"] = 0] = "Not"; + StructureIsReused[StructureIsReused["SafeModules"] = 1] = "SafeModules"; + StructureIsReused[StructureIsReused["Completely"] = 2] = "Completely"; + })(StructureIsReused = ts.StructureIsReused || (ts.StructureIsReused = {})); + /** Return code used by getEmitOutput function to indicate status of the function */ + var ExitStatus; + (function (ExitStatus) { + // Compiler ran successfully. Either this was a simple do-nothing compilation (for example, + // when -version or -help was provided, or this was a normal compilation, no diagnostics + // were produced, and all outputs were generated successfully. + ExitStatus[ExitStatus["Success"] = 0] = "Success"; + // Diagnostics were produced and because of them no code was generated. + ExitStatus[ExitStatus["DiagnosticsPresent_OutputsSkipped"] = 1] = "DiagnosticsPresent_OutputsSkipped"; + // Diagnostics were produced and outputs were generated in spite of them. + ExitStatus[ExitStatus["DiagnosticsPresent_OutputsGenerated"] = 2] = "DiagnosticsPresent_OutputsGenerated"; + })(ExitStatus = ts.ExitStatus || (ts.ExitStatus = {})); + /* @internal */ + var UnionReduction; + (function (UnionReduction) { + UnionReduction[UnionReduction["None"] = 0] = "None"; + UnionReduction[UnionReduction["Literal"] = 1] = "Literal"; + UnionReduction[UnionReduction["Subtype"] = 2] = "Subtype"; + })(UnionReduction = ts.UnionReduction || (ts.UnionReduction = {})); + // NOTE: If modifying this enum, must modify `TypeFormatFlags` too! + var NodeBuilderFlags; + (function (NodeBuilderFlags) { + NodeBuilderFlags[NodeBuilderFlags["None"] = 0] = "None"; + // Options + NodeBuilderFlags[NodeBuilderFlags["NoTruncation"] = 1] = "NoTruncation"; + NodeBuilderFlags[NodeBuilderFlags["WriteArrayAsGenericType"] = 2] = "WriteArrayAsGenericType"; + NodeBuilderFlags[NodeBuilderFlags["GenerateNamesForShadowedTypeParams"] = 4] = "GenerateNamesForShadowedTypeParams"; + NodeBuilderFlags[NodeBuilderFlags["UseStructuralFallback"] = 8] = "UseStructuralFallback"; + NodeBuilderFlags[NodeBuilderFlags["ForbidIndexedAccessSymbolReferences"] = 16] = "ForbidIndexedAccessSymbolReferences"; + NodeBuilderFlags[NodeBuilderFlags["WriteTypeArgumentsOfSignature"] = 32] = "WriteTypeArgumentsOfSignature"; + NodeBuilderFlags[NodeBuilderFlags["UseFullyQualifiedType"] = 64] = "UseFullyQualifiedType"; + NodeBuilderFlags[NodeBuilderFlags["UseOnlyExternalAliasing"] = 128] = "UseOnlyExternalAliasing"; + NodeBuilderFlags[NodeBuilderFlags["SuppressAnyReturnType"] = 256] = "SuppressAnyReturnType"; + NodeBuilderFlags[NodeBuilderFlags["WriteTypeParametersInQualifiedName"] = 512] = "WriteTypeParametersInQualifiedName"; + NodeBuilderFlags[NodeBuilderFlags["MultilineObjectLiterals"] = 1024] = "MultilineObjectLiterals"; + NodeBuilderFlags[NodeBuilderFlags["WriteClassExpressionAsTypeLiteral"] = 2048] = "WriteClassExpressionAsTypeLiteral"; + NodeBuilderFlags[NodeBuilderFlags["UseTypeOfFunction"] = 4096] = "UseTypeOfFunction"; + NodeBuilderFlags[NodeBuilderFlags["OmitParameterModifiers"] = 8192] = "OmitParameterModifiers"; + NodeBuilderFlags[NodeBuilderFlags["UseAliasDefinedOutsideCurrentScope"] = 16384] = "UseAliasDefinedOutsideCurrentScope"; + // Error handling + NodeBuilderFlags[NodeBuilderFlags["AllowThisInObjectLiteral"] = 32768] = "AllowThisInObjectLiteral"; + NodeBuilderFlags[NodeBuilderFlags["AllowQualifedNameInPlaceOfIdentifier"] = 65536] = "AllowQualifedNameInPlaceOfIdentifier"; + NodeBuilderFlags[NodeBuilderFlags["AllowAnonymousIdentifier"] = 131072] = "AllowAnonymousIdentifier"; + NodeBuilderFlags[NodeBuilderFlags["AllowEmptyUnionOrIntersection"] = 262144] = "AllowEmptyUnionOrIntersection"; + NodeBuilderFlags[NodeBuilderFlags["AllowEmptyTuple"] = 524288] = "AllowEmptyTuple"; + NodeBuilderFlags[NodeBuilderFlags["AllowUniqueESSymbolType"] = 1048576] = "AllowUniqueESSymbolType"; + NodeBuilderFlags[NodeBuilderFlags["AllowEmptyIndexInfoType"] = 2097152] = "AllowEmptyIndexInfoType"; + // Errors (cont.) + NodeBuilderFlags[NodeBuilderFlags["AllowNodeModulesRelativePaths"] = 67108864] = "AllowNodeModulesRelativePaths"; + /* @internal */ NodeBuilderFlags[NodeBuilderFlags["DoNotIncludeSymbolChain"] = 134217728] = "DoNotIncludeSymbolChain"; + NodeBuilderFlags[NodeBuilderFlags["IgnoreErrors"] = 70221824] = "IgnoreErrors"; + // State + NodeBuilderFlags[NodeBuilderFlags["InObjectTypeLiteral"] = 4194304] = "InObjectTypeLiteral"; + NodeBuilderFlags[NodeBuilderFlags["InTypeAlias"] = 8388608] = "InTypeAlias"; + NodeBuilderFlags[NodeBuilderFlags["InInitialEntityName"] = 16777216] = "InInitialEntityName"; + NodeBuilderFlags[NodeBuilderFlags["InReverseMappedType"] = 33554432] = "InReverseMappedType"; + })(NodeBuilderFlags = ts.NodeBuilderFlags || (ts.NodeBuilderFlags = {})); + // Ensure the shared flags between this and `NodeBuilderFlags` stay in alignment + var TypeFormatFlags; + (function (TypeFormatFlags) { + TypeFormatFlags[TypeFormatFlags["None"] = 0] = "None"; + TypeFormatFlags[TypeFormatFlags["NoTruncation"] = 1] = "NoTruncation"; + TypeFormatFlags[TypeFormatFlags["WriteArrayAsGenericType"] = 2] = "WriteArrayAsGenericType"; + // hole because there's a hole in node builder flags + TypeFormatFlags[TypeFormatFlags["UseStructuralFallback"] = 8] = "UseStructuralFallback"; + // hole because there's a hole in node builder flags + TypeFormatFlags[TypeFormatFlags["WriteTypeArgumentsOfSignature"] = 32] = "WriteTypeArgumentsOfSignature"; + TypeFormatFlags[TypeFormatFlags["UseFullyQualifiedType"] = 64] = "UseFullyQualifiedType"; + // hole because `UseOnlyExternalAliasing` is here in node builder flags, but functions which take old flags use `SymbolFormatFlags` instead + TypeFormatFlags[TypeFormatFlags["SuppressAnyReturnType"] = 256] = "SuppressAnyReturnType"; + // hole because `WriteTypeParametersInQualifiedName` is here in node builder flags, but functions which take old flags use `SymbolFormatFlags` for this instead + TypeFormatFlags[TypeFormatFlags["MultilineObjectLiterals"] = 1024] = "MultilineObjectLiterals"; + TypeFormatFlags[TypeFormatFlags["WriteClassExpressionAsTypeLiteral"] = 2048] = "WriteClassExpressionAsTypeLiteral"; + TypeFormatFlags[TypeFormatFlags["UseTypeOfFunction"] = 4096] = "UseTypeOfFunction"; + TypeFormatFlags[TypeFormatFlags["OmitParameterModifiers"] = 8192] = "OmitParameterModifiers"; + TypeFormatFlags[TypeFormatFlags["UseAliasDefinedOutsideCurrentScope"] = 16384] = "UseAliasDefinedOutsideCurrentScope"; + // even though `T` can't be accessed in the current scope. + // Error Handling + TypeFormatFlags[TypeFormatFlags["AllowUniqueESSymbolType"] = 1048576] = "AllowUniqueESSymbolType"; + // TypeFormatFlags exclusive + TypeFormatFlags[TypeFormatFlags["AddUndefined"] = 131072] = "AddUndefined"; + TypeFormatFlags[TypeFormatFlags["WriteArrowStyleSignature"] = 262144] = "WriteArrowStyleSignature"; + // State + TypeFormatFlags[TypeFormatFlags["InArrayType"] = 524288] = "InArrayType"; + TypeFormatFlags[TypeFormatFlags["InElementType"] = 2097152] = "InElementType"; + TypeFormatFlags[TypeFormatFlags["InFirstTypeArgument"] = 4194304] = "InFirstTypeArgument"; + TypeFormatFlags[TypeFormatFlags["InTypeAlias"] = 8388608] = "InTypeAlias"; + /** @deprecated */ TypeFormatFlags[TypeFormatFlags["WriteOwnNameForAnyLike"] = 0] = "WriteOwnNameForAnyLike"; + TypeFormatFlags[TypeFormatFlags["NodeBuilderFlagsMask"] = 9469291] = "NodeBuilderFlagsMask"; + })(TypeFormatFlags = ts.TypeFormatFlags || (ts.TypeFormatFlags = {})); + var SymbolFormatFlags; + (function (SymbolFormatFlags) { + SymbolFormatFlags[SymbolFormatFlags["None"] = 0] = "None"; + // Write symbols's type argument if it is instantiated symbol + // eg. class C { p: T } <-- Show p as C.p here + // var a: C; + // var p = a.p; <--- Here p is property of C so show it as C.p instead of just C.p + SymbolFormatFlags[SymbolFormatFlags["WriteTypeParametersOrArguments"] = 1] = "WriteTypeParametersOrArguments"; + // Use only external alias information to get the symbol name in the given context + // eg. module m { export class c { } } import x = m.c; + // When this flag is specified m.c will be used to refer to the class instead of alias symbol x + SymbolFormatFlags[SymbolFormatFlags["UseOnlyExternalAliasing"] = 2] = "UseOnlyExternalAliasing"; + // Build symbol name using any nodes needed, instead of just components of an entity name + SymbolFormatFlags[SymbolFormatFlags["AllowAnyNodeKind"] = 4] = "AllowAnyNodeKind"; + // Prefer aliases which are not directly visible + SymbolFormatFlags[SymbolFormatFlags["UseAliasDefinedOutsideCurrentScope"] = 8] = "UseAliasDefinedOutsideCurrentScope"; + // Skip building an accessible symbol chain + /* @internal */ SymbolFormatFlags[SymbolFormatFlags["DoNotIncludeSymbolChain"] = 16] = "DoNotIncludeSymbolChain"; + })(SymbolFormatFlags = ts.SymbolFormatFlags || (ts.SymbolFormatFlags = {})); + /* @internal */ + var SymbolAccessibility; + (function (SymbolAccessibility) { + SymbolAccessibility[SymbolAccessibility["Accessible"] = 0] = "Accessible"; + SymbolAccessibility[SymbolAccessibility["NotAccessible"] = 1] = "NotAccessible"; + SymbolAccessibility[SymbolAccessibility["CannotBeNamed"] = 2] = "CannotBeNamed"; + })(SymbolAccessibility = ts.SymbolAccessibility || (ts.SymbolAccessibility = {})); + /* @internal */ + var SyntheticSymbolKind; + (function (SyntheticSymbolKind) { + SyntheticSymbolKind[SyntheticSymbolKind["UnionOrIntersection"] = 0] = "UnionOrIntersection"; + SyntheticSymbolKind[SyntheticSymbolKind["Spread"] = 1] = "Spread"; + })(SyntheticSymbolKind = ts.SyntheticSymbolKind || (ts.SyntheticSymbolKind = {})); + var TypePredicateKind; + (function (TypePredicateKind) { + TypePredicateKind[TypePredicateKind["This"] = 0] = "This"; + TypePredicateKind[TypePredicateKind["Identifier"] = 1] = "Identifier"; + })(TypePredicateKind = ts.TypePredicateKind || (ts.TypePredicateKind = {})); + /** Indicates how to serialize the name for a TypeReferenceNode when emitting decorator metadata */ + /* @internal */ + var TypeReferenceSerializationKind; + (function (TypeReferenceSerializationKind) { + TypeReferenceSerializationKind[TypeReferenceSerializationKind["Unknown"] = 0] = "Unknown"; + // should be emitted using a safe fallback. + TypeReferenceSerializationKind[TypeReferenceSerializationKind["TypeWithConstructSignatureAndValue"] = 1] = "TypeWithConstructSignatureAndValue"; + // function that can be reached at runtime (e.g. a `class` + // declaration or a `var` declaration for the static side + // of a type, such as the global `Promise` type in lib.d.ts). + TypeReferenceSerializationKind[TypeReferenceSerializationKind["VoidNullableOrNeverType"] = 2] = "VoidNullableOrNeverType"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["NumberLikeType"] = 3] = "NumberLikeType"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["BigIntLikeType"] = 4] = "BigIntLikeType"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["StringLikeType"] = 5] = "StringLikeType"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["BooleanType"] = 6] = "BooleanType"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["ArrayLikeType"] = 7] = "ArrayLikeType"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["ESSymbolType"] = 8] = "ESSymbolType"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["Promise"] = 9] = "Promise"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["TypeWithCallSignature"] = 10] = "TypeWithCallSignature"; + // with call signatures. + TypeReferenceSerializationKind[TypeReferenceSerializationKind["ObjectType"] = 11] = "ObjectType"; + })(TypeReferenceSerializationKind = ts.TypeReferenceSerializationKind || (ts.TypeReferenceSerializationKind = {})); + var SymbolFlags; + (function (SymbolFlags) { + SymbolFlags[SymbolFlags["None"] = 0] = "None"; + SymbolFlags[SymbolFlags["FunctionScopedVariable"] = 1] = "FunctionScopedVariable"; + SymbolFlags[SymbolFlags["BlockScopedVariable"] = 2] = "BlockScopedVariable"; + SymbolFlags[SymbolFlags["Property"] = 4] = "Property"; + SymbolFlags[SymbolFlags["EnumMember"] = 8] = "EnumMember"; + SymbolFlags[SymbolFlags["Function"] = 16] = "Function"; + SymbolFlags[SymbolFlags["Class"] = 32] = "Class"; + SymbolFlags[SymbolFlags["Interface"] = 64] = "Interface"; + SymbolFlags[SymbolFlags["ConstEnum"] = 128] = "ConstEnum"; + SymbolFlags[SymbolFlags["RegularEnum"] = 256] = "RegularEnum"; + SymbolFlags[SymbolFlags["ValueModule"] = 512] = "ValueModule"; + SymbolFlags[SymbolFlags["NamespaceModule"] = 1024] = "NamespaceModule"; + SymbolFlags[SymbolFlags["TypeLiteral"] = 2048] = "TypeLiteral"; + SymbolFlags[SymbolFlags["ObjectLiteral"] = 4096] = "ObjectLiteral"; + SymbolFlags[SymbolFlags["Method"] = 8192] = "Method"; + SymbolFlags[SymbolFlags["Constructor"] = 16384] = "Constructor"; + SymbolFlags[SymbolFlags["GetAccessor"] = 32768] = "GetAccessor"; + SymbolFlags[SymbolFlags["SetAccessor"] = 65536] = "SetAccessor"; + SymbolFlags[SymbolFlags["Signature"] = 131072] = "Signature"; + SymbolFlags[SymbolFlags["TypeParameter"] = 262144] = "TypeParameter"; + SymbolFlags[SymbolFlags["TypeAlias"] = 524288] = "TypeAlias"; + SymbolFlags[SymbolFlags["ExportValue"] = 1048576] = "ExportValue"; + SymbolFlags[SymbolFlags["Alias"] = 2097152] = "Alias"; + SymbolFlags[SymbolFlags["Prototype"] = 4194304] = "Prototype"; + SymbolFlags[SymbolFlags["ExportStar"] = 8388608] = "ExportStar"; + SymbolFlags[SymbolFlags["Optional"] = 16777216] = "Optional"; + SymbolFlags[SymbolFlags["Transient"] = 33554432] = "Transient"; + SymbolFlags[SymbolFlags["Assignment"] = 67108864] = "Assignment"; + SymbolFlags[SymbolFlags["ModuleExports"] = 134217728] = "ModuleExports"; + /* @internal */ + SymbolFlags[SymbolFlags["All"] = 67108863] = "All"; + SymbolFlags[SymbolFlags["Enum"] = 384] = "Enum"; + SymbolFlags[SymbolFlags["Variable"] = 3] = "Variable"; + SymbolFlags[SymbolFlags["Value"] = 67220415] = "Value"; + SymbolFlags[SymbolFlags["Type"] = 67897832] = "Type"; + SymbolFlags[SymbolFlags["Namespace"] = 1920] = "Namespace"; + SymbolFlags[SymbolFlags["Module"] = 1536] = "Module"; + SymbolFlags[SymbolFlags["Accessor"] = 98304] = "Accessor"; + // Variables can be redeclared, but can not redeclare a block-scoped declaration with the + // same name, or any other value that is not a variable, e.g. ValueModule or Class + SymbolFlags[SymbolFlags["FunctionScopedVariableExcludes"] = 67220414] = "FunctionScopedVariableExcludes"; + // Block-scoped declarations are not allowed to be re-declared + // they can not merge with anything in the value space + SymbolFlags[SymbolFlags["BlockScopedVariableExcludes"] = 67220415] = "BlockScopedVariableExcludes"; + SymbolFlags[SymbolFlags["ParameterExcludes"] = 67220415] = "ParameterExcludes"; + SymbolFlags[SymbolFlags["PropertyExcludes"] = 0] = "PropertyExcludes"; + SymbolFlags[SymbolFlags["EnumMemberExcludes"] = 68008959] = "EnumMemberExcludes"; + SymbolFlags[SymbolFlags["FunctionExcludes"] = 67219887] = "FunctionExcludes"; + SymbolFlags[SymbolFlags["ClassExcludes"] = 68008383] = "ClassExcludes"; + SymbolFlags[SymbolFlags["InterfaceExcludes"] = 67897736] = "InterfaceExcludes"; + SymbolFlags[SymbolFlags["RegularEnumExcludes"] = 68008191] = "RegularEnumExcludes"; + SymbolFlags[SymbolFlags["ConstEnumExcludes"] = 68008831] = "ConstEnumExcludes"; + SymbolFlags[SymbolFlags["ValueModuleExcludes"] = 110735] = "ValueModuleExcludes"; + SymbolFlags[SymbolFlags["NamespaceModuleExcludes"] = 0] = "NamespaceModuleExcludes"; + SymbolFlags[SymbolFlags["MethodExcludes"] = 67212223] = "MethodExcludes"; + SymbolFlags[SymbolFlags["GetAccessorExcludes"] = 67154879] = "GetAccessorExcludes"; + SymbolFlags[SymbolFlags["SetAccessorExcludes"] = 67187647] = "SetAccessorExcludes"; + SymbolFlags[SymbolFlags["TypeParameterExcludes"] = 67635688] = "TypeParameterExcludes"; + SymbolFlags[SymbolFlags["TypeAliasExcludes"] = 67897832] = "TypeAliasExcludes"; + SymbolFlags[SymbolFlags["AliasExcludes"] = 2097152] = "AliasExcludes"; + SymbolFlags[SymbolFlags["ModuleMember"] = 2623475] = "ModuleMember"; + SymbolFlags[SymbolFlags["ExportHasLocal"] = 944] = "ExportHasLocal"; + SymbolFlags[SymbolFlags["BlockScoped"] = 418] = "BlockScoped"; + SymbolFlags[SymbolFlags["PropertyOrAccessor"] = 98308] = "PropertyOrAccessor"; + SymbolFlags[SymbolFlags["ClassMember"] = 106500] = "ClassMember"; + /* @internal */ + // The set of things we consider semantically classifiable. Used to speed up the LS during + // classification. + SymbolFlags[SymbolFlags["Classifiable"] = 2885600] = "Classifiable"; + /* @internal */ + SymbolFlags[SymbolFlags["LateBindingContainer"] = 6240] = "LateBindingContainer"; + })(SymbolFlags = ts.SymbolFlags || (ts.SymbolFlags = {})); + /* @internal */ + var EnumKind; + (function (EnumKind) { + EnumKind[EnumKind["Numeric"] = 0] = "Numeric"; + EnumKind[EnumKind["Literal"] = 1] = "Literal"; // Literal enum (each member has a TypeFlags.EnumLiteral type) + })(EnumKind = ts.EnumKind || (ts.EnumKind = {})); + /* @internal */ + var CheckFlags; + (function (CheckFlags) { + CheckFlags[CheckFlags["Instantiated"] = 1] = "Instantiated"; + CheckFlags[CheckFlags["SyntheticProperty"] = 2] = "SyntheticProperty"; + CheckFlags[CheckFlags["SyntheticMethod"] = 4] = "SyntheticMethod"; + CheckFlags[CheckFlags["Readonly"] = 8] = "Readonly"; + CheckFlags[CheckFlags["Partial"] = 16] = "Partial"; + CheckFlags[CheckFlags["HasNonUniformType"] = 32] = "HasNonUniformType"; + CheckFlags[CheckFlags["ContainsPublic"] = 64] = "ContainsPublic"; + CheckFlags[CheckFlags["ContainsProtected"] = 128] = "ContainsProtected"; + CheckFlags[CheckFlags["ContainsPrivate"] = 256] = "ContainsPrivate"; + CheckFlags[CheckFlags["ContainsStatic"] = 512] = "ContainsStatic"; + CheckFlags[CheckFlags["Late"] = 1024] = "Late"; + CheckFlags[CheckFlags["ReverseMapped"] = 2048] = "ReverseMapped"; + CheckFlags[CheckFlags["OptionalParameter"] = 4096] = "OptionalParameter"; + CheckFlags[CheckFlags["RestParameter"] = 8192] = "RestParameter"; + CheckFlags[CheckFlags["Synthetic"] = 6] = "Synthetic"; + })(CheckFlags = ts.CheckFlags || (ts.CheckFlags = {})); + var InternalSymbolName; + (function (InternalSymbolName) { + InternalSymbolName["Call"] = "__call"; + InternalSymbolName["Constructor"] = "__constructor"; + InternalSymbolName["New"] = "__new"; + InternalSymbolName["Index"] = "__index"; + InternalSymbolName["ExportStar"] = "__export"; + InternalSymbolName["Global"] = "__global"; + InternalSymbolName["Missing"] = "__missing"; + InternalSymbolName["Type"] = "__type"; + InternalSymbolName["Object"] = "__object"; + InternalSymbolName["JSXAttributes"] = "__jsxAttributes"; + InternalSymbolName["Class"] = "__class"; + InternalSymbolName["Function"] = "__function"; + InternalSymbolName["Computed"] = "__computed"; + InternalSymbolName["Resolving"] = "__resolving__"; + InternalSymbolName["ExportEquals"] = "export="; + InternalSymbolName["Default"] = "default"; + InternalSymbolName["This"] = "this"; + })(InternalSymbolName = ts.InternalSymbolName || (ts.InternalSymbolName = {})); + /* @internal */ + var NodeCheckFlags; + (function (NodeCheckFlags) { + NodeCheckFlags[NodeCheckFlags["TypeChecked"] = 1] = "TypeChecked"; + NodeCheckFlags[NodeCheckFlags["LexicalThis"] = 2] = "LexicalThis"; + NodeCheckFlags[NodeCheckFlags["CaptureThis"] = 4] = "CaptureThis"; + NodeCheckFlags[NodeCheckFlags["CaptureNewTarget"] = 8] = "CaptureNewTarget"; + NodeCheckFlags[NodeCheckFlags["SuperInstance"] = 256] = "SuperInstance"; + NodeCheckFlags[NodeCheckFlags["SuperStatic"] = 512] = "SuperStatic"; + NodeCheckFlags[NodeCheckFlags["ContextChecked"] = 1024] = "ContextChecked"; + NodeCheckFlags[NodeCheckFlags["AsyncMethodWithSuper"] = 2048] = "AsyncMethodWithSuper"; + NodeCheckFlags[NodeCheckFlags["AsyncMethodWithSuperBinding"] = 4096] = "AsyncMethodWithSuperBinding"; + NodeCheckFlags[NodeCheckFlags["CaptureArguments"] = 8192] = "CaptureArguments"; + NodeCheckFlags[NodeCheckFlags["EnumValuesComputed"] = 16384] = "EnumValuesComputed"; + NodeCheckFlags[NodeCheckFlags["LexicalModuleMergesWithClass"] = 32768] = "LexicalModuleMergesWithClass"; + NodeCheckFlags[NodeCheckFlags["LoopWithCapturedBlockScopedBinding"] = 65536] = "LoopWithCapturedBlockScopedBinding"; + NodeCheckFlags[NodeCheckFlags["ContainsCapturedBlockScopeBinding"] = 131072] = "ContainsCapturedBlockScopeBinding"; + NodeCheckFlags[NodeCheckFlags["CapturedBlockScopedBinding"] = 262144] = "CapturedBlockScopedBinding"; + NodeCheckFlags[NodeCheckFlags["BlockScopedBindingInLoop"] = 524288] = "BlockScopedBindingInLoop"; + NodeCheckFlags[NodeCheckFlags["ClassWithBodyScopedClassBinding"] = 1048576] = "ClassWithBodyScopedClassBinding"; + NodeCheckFlags[NodeCheckFlags["BodyScopedClassBinding"] = 2097152] = "BodyScopedClassBinding"; + NodeCheckFlags[NodeCheckFlags["NeedsLoopOutParameter"] = 4194304] = "NeedsLoopOutParameter"; + NodeCheckFlags[NodeCheckFlags["AssignmentsMarked"] = 8388608] = "AssignmentsMarked"; + NodeCheckFlags[NodeCheckFlags["ClassWithConstructorReference"] = 16777216] = "ClassWithConstructorReference"; + NodeCheckFlags[NodeCheckFlags["ConstructorReferenceInClass"] = 33554432] = "ConstructorReferenceInClass"; + })(NodeCheckFlags = ts.NodeCheckFlags || (ts.NodeCheckFlags = {})); + var TypeFlags; + (function (TypeFlags) { + TypeFlags[TypeFlags["Any"] = 1] = "Any"; + TypeFlags[TypeFlags["Unknown"] = 2] = "Unknown"; + TypeFlags[TypeFlags["String"] = 4] = "String"; + TypeFlags[TypeFlags["Number"] = 8] = "Number"; + TypeFlags[TypeFlags["Boolean"] = 16] = "Boolean"; + TypeFlags[TypeFlags["Enum"] = 32] = "Enum"; + TypeFlags[TypeFlags["BigInt"] = 64] = "BigInt"; + TypeFlags[TypeFlags["StringLiteral"] = 128] = "StringLiteral"; + TypeFlags[TypeFlags["NumberLiteral"] = 256] = "NumberLiteral"; + TypeFlags[TypeFlags["BooleanLiteral"] = 512] = "BooleanLiteral"; + TypeFlags[TypeFlags["EnumLiteral"] = 1024] = "EnumLiteral"; + TypeFlags[TypeFlags["BigIntLiteral"] = 2048] = "BigIntLiteral"; + TypeFlags[TypeFlags["ESSymbol"] = 4096] = "ESSymbol"; + TypeFlags[TypeFlags["UniqueESSymbol"] = 8192] = "UniqueESSymbol"; + TypeFlags[TypeFlags["Void"] = 16384] = "Void"; + TypeFlags[TypeFlags["Undefined"] = 32768] = "Undefined"; + TypeFlags[TypeFlags["Null"] = 65536] = "Null"; + TypeFlags[TypeFlags["Never"] = 131072] = "Never"; + TypeFlags[TypeFlags["TypeParameter"] = 262144] = "TypeParameter"; + TypeFlags[TypeFlags["Object"] = 524288] = "Object"; + TypeFlags[TypeFlags["Union"] = 1048576] = "Union"; + TypeFlags[TypeFlags["Intersection"] = 2097152] = "Intersection"; + TypeFlags[TypeFlags["Index"] = 4194304] = "Index"; + TypeFlags[TypeFlags["IndexedAccess"] = 8388608] = "IndexedAccess"; + TypeFlags[TypeFlags["Conditional"] = 16777216] = "Conditional"; + TypeFlags[TypeFlags["Substitution"] = 33554432] = "Substitution"; + TypeFlags[TypeFlags["NonPrimitive"] = 67108864] = "NonPrimitive"; + /* @internal */ + TypeFlags[TypeFlags["ContainsWideningType"] = 134217728] = "ContainsWideningType"; + /* @internal */ + TypeFlags[TypeFlags["ContainsObjectLiteral"] = 268435456] = "ContainsObjectLiteral"; + /* @internal */ + TypeFlags[TypeFlags["ContainsAnyFunctionType"] = 536870912] = "ContainsAnyFunctionType"; + /* @internal */ + TypeFlags[TypeFlags["AnyOrUnknown"] = 3] = "AnyOrUnknown"; + /* @internal */ + TypeFlags[TypeFlags["Nullable"] = 98304] = "Nullable"; + TypeFlags[TypeFlags["Literal"] = 2944] = "Literal"; + TypeFlags[TypeFlags["Unit"] = 109440] = "Unit"; + TypeFlags[TypeFlags["StringOrNumberLiteral"] = 384] = "StringOrNumberLiteral"; + /* @internal */ + TypeFlags[TypeFlags["StringOrNumberLiteralOrUnique"] = 8576] = "StringOrNumberLiteralOrUnique"; + /* @internal */ + TypeFlags[TypeFlags["DefinitelyFalsy"] = 117632] = "DefinitelyFalsy"; + TypeFlags[TypeFlags["PossiblyFalsy"] = 117724] = "PossiblyFalsy"; + /* @internal */ + TypeFlags[TypeFlags["Intrinsic"] = 67359327] = "Intrinsic"; + /* @internal */ + TypeFlags[TypeFlags["Primitive"] = 131068] = "Primitive"; + TypeFlags[TypeFlags["StringLike"] = 132] = "StringLike"; + TypeFlags[TypeFlags["NumberLike"] = 296] = "NumberLike"; + TypeFlags[TypeFlags["BigIntLike"] = 2112] = "BigIntLike"; + TypeFlags[TypeFlags["BooleanLike"] = 528] = "BooleanLike"; + TypeFlags[TypeFlags["EnumLike"] = 1056] = "EnumLike"; + TypeFlags[TypeFlags["ESSymbolLike"] = 12288] = "ESSymbolLike"; + TypeFlags[TypeFlags["VoidLike"] = 49152] = "VoidLike"; + /* @internal */ + TypeFlags[TypeFlags["DisjointDomains"] = 67238908] = "DisjointDomains"; + TypeFlags[TypeFlags["UnionOrIntersection"] = 3145728] = "UnionOrIntersection"; + TypeFlags[TypeFlags["StructuredType"] = 3670016] = "StructuredType"; + TypeFlags[TypeFlags["TypeVariable"] = 8650752] = "TypeVariable"; + TypeFlags[TypeFlags["InstantiableNonPrimitive"] = 58982400] = "InstantiableNonPrimitive"; + TypeFlags[TypeFlags["InstantiablePrimitive"] = 4194304] = "InstantiablePrimitive"; + TypeFlags[TypeFlags["Instantiable"] = 63176704] = "Instantiable"; + TypeFlags[TypeFlags["StructuredOrInstantiable"] = 66846720] = "StructuredOrInstantiable"; + // 'Narrowable' types are types where narrowing actually narrows. + // This *should* be every type other than null, undefined, void, and never + TypeFlags[TypeFlags["Narrowable"] = 133970943] = "Narrowable"; + TypeFlags[TypeFlags["NotUnionOrUnit"] = 67637251] = "NotUnionOrUnit"; + /* @internal */ + TypeFlags[TypeFlags["NotPrimitiveUnion"] = 66994211] = "NotPrimitiveUnion"; + /* @internal */ + TypeFlags[TypeFlags["RequiresWidening"] = 402653184] = "RequiresWidening"; + /* @internal */ + TypeFlags[TypeFlags["PropagatingFlags"] = 939524096] = "PropagatingFlags"; + // The following flags are used for different purposes during union and intersection type construction + /* @internal */ + TypeFlags[TypeFlags["NonWideningType"] = 134217728] = "NonWideningType"; + /* @internal */ + TypeFlags[TypeFlags["Wildcard"] = 268435456] = "Wildcard"; + /* @internal */ + TypeFlags[TypeFlags["EmptyObject"] = 536870912] = "EmptyObject"; + /* @internal */ + TypeFlags[TypeFlags["ConstructionFlags"] = 939524096] = "ConstructionFlags"; + // The following flag is used for different purposes by maybeTypeOfKind + /* @internal */ + TypeFlags[TypeFlags["GenericMappedType"] = 134217728] = "GenericMappedType"; + })(TypeFlags = ts.TypeFlags || (ts.TypeFlags = {})); + var ObjectFlags; + (function (ObjectFlags) { + ObjectFlags[ObjectFlags["Class"] = 1] = "Class"; + ObjectFlags[ObjectFlags["Interface"] = 2] = "Interface"; + ObjectFlags[ObjectFlags["Reference"] = 4] = "Reference"; + ObjectFlags[ObjectFlags["Tuple"] = 8] = "Tuple"; + ObjectFlags[ObjectFlags["Anonymous"] = 16] = "Anonymous"; + ObjectFlags[ObjectFlags["Mapped"] = 32] = "Mapped"; + ObjectFlags[ObjectFlags["Instantiated"] = 64] = "Instantiated"; + ObjectFlags[ObjectFlags["ObjectLiteral"] = 128] = "ObjectLiteral"; + ObjectFlags[ObjectFlags["EvolvingArray"] = 256] = "EvolvingArray"; + ObjectFlags[ObjectFlags["ObjectLiteralPatternWithComputedProperties"] = 512] = "ObjectLiteralPatternWithComputedProperties"; + ObjectFlags[ObjectFlags["ContainsSpread"] = 1024] = "ContainsSpread"; + ObjectFlags[ObjectFlags["ReverseMapped"] = 2048] = "ReverseMapped"; + ObjectFlags[ObjectFlags["JsxAttributes"] = 4096] = "JsxAttributes"; + ObjectFlags[ObjectFlags["MarkerType"] = 8192] = "MarkerType"; + ObjectFlags[ObjectFlags["JSLiteral"] = 16384] = "JSLiteral"; + ObjectFlags[ObjectFlags["FreshLiteral"] = 32768] = "FreshLiteral"; + ObjectFlags[ObjectFlags["ClassOrInterface"] = 3] = "ClassOrInterface"; + })(ObjectFlags = ts.ObjectFlags || (ts.ObjectFlags = {})); + /* @internal */ + var Variance; + (function (Variance) { + Variance[Variance["Invariant"] = 0] = "Invariant"; + Variance[Variance["Covariant"] = 1] = "Covariant"; + Variance[Variance["Contravariant"] = 2] = "Contravariant"; + Variance[Variance["Bivariant"] = 3] = "Bivariant"; + Variance[Variance["Independent"] = 4] = "Independent"; + })(Variance = ts.Variance || (ts.Variance = {})); + /* @internal */ + var JsxReferenceKind; + (function (JsxReferenceKind) { + JsxReferenceKind[JsxReferenceKind["Component"] = 0] = "Component"; + JsxReferenceKind[JsxReferenceKind["Function"] = 1] = "Function"; + JsxReferenceKind[JsxReferenceKind["Mixed"] = 2] = "Mixed"; + })(JsxReferenceKind = ts.JsxReferenceKind || (ts.JsxReferenceKind = {})); + var SignatureKind; + (function (SignatureKind) { + SignatureKind[SignatureKind["Call"] = 0] = "Call"; + SignatureKind[SignatureKind["Construct"] = 1] = "Construct"; + })(SignatureKind = ts.SignatureKind || (ts.SignatureKind = {})); + var IndexKind; + (function (IndexKind) { + IndexKind[IndexKind["String"] = 0] = "String"; + IndexKind[IndexKind["Number"] = 1] = "Number"; + })(IndexKind = ts.IndexKind || (ts.IndexKind = {})); + var InferencePriority; + (function (InferencePriority) { + InferencePriority[InferencePriority["NakedTypeVariable"] = 1] = "NakedTypeVariable"; + InferencePriority[InferencePriority["HomomorphicMappedType"] = 2] = "HomomorphicMappedType"; + InferencePriority[InferencePriority["MappedTypeConstraint"] = 4] = "MappedTypeConstraint"; + InferencePriority[InferencePriority["ReturnType"] = 8] = "ReturnType"; + InferencePriority[InferencePriority["LiteralKeyof"] = 16] = "LiteralKeyof"; + InferencePriority[InferencePriority["NoConstraints"] = 32] = "NoConstraints"; + InferencePriority[InferencePriority["AlwaysStrict"] = 64] = "AlwaysStrict"; + InferencePriority[InferencePriority["PriorityImpliesCombination"] = 28] = "PriorityImpliesCombination"; + })(InferencePriority = ts.InferencePriority || (ts.InferencePriority = {})); + /* @internal */ + var InferenceFlags; + (function (InferenceFlags) { + InferenceFlags[InferenceFlags["None"] = 0] = "None"; + InferenceFlags[InferenceFlags["NoDefault"] = 1] = "NoDefault"; + InferenceFlags[InferenceFlags["AnyDefault"] = 2] = "AnyDefault"; + })(InferenceFlags = ts.InferenceFlags || (ts.InferenceFlags = {})); + /** + * Ternary values are defined such that + * x & y is False if either x or y is False. + * x & y is Maybe if either x or y is Maybe, but neither x or y is False. + * x & y is True if both x and y are True. + * x | y is False if both x and y are False. + * x | y is Maybe if either x or y is Maybe, but neither x or y is True. + * x | y is True if either x or y is True. + */ + /* @internal */ + var Ternary; + (function (Ternary) { + Ternary[Ternary["False"] = 0] = "False"; + Ternary[Ternary["Maybe"] = 1] = "Maybe"; + Ternary[Ternary["True"] = -1] = "True"; + })(Ternary = ts.Ternary || (ts.Ternary = {})); + /* @internal */ + var AssignmentDeclarationKind; + (function (AssignmentDeclarationKind) { + AssignmentDeclarationKind[AssignmentDeclarationKind["None"] = 0] = "None"; + /// exports.name = expr + AssignmentDeclarationKind[AssignmentDeclarationKind["ExportsProperty"] = 1] = "ExportsProperty"; + /// module.exports = expr + AssignmentDeclarationKind[AssignmentDeclarationKind["ModuleExports"] = 2] = "ModuleExports"; + /// className.prototype.name = expr + AssignmentDeclarationKind[AssignmentDeclarationKind["PrototypeProperty"] = 3] = "PrototypeProperty"; + /// this.name = expr + AssignmentDeclarationKind[AssignmentDeclarationKind["ThisProperty"] = 4] = "ThisProperty"; + // F.name = expr + AssignmentDeclarationKind[AssignmentDeclarationKind["Property"] = 5] = "Property"; + // F.prototype = { ... } + AssignmentDeclarationKind[AssignmentDeclarationKind["Prototype"] = 6] = "Prototype"; + // Object.defineProperty(x, 'name', { value: any, writable?: boolean (false by default) }); + // Object.defineProperty(x, 'name', { get: Function, set: Function }); + // Object.defineProperty(x, 'name', { get: Function }); + // Object.defineProperty(x, 'name', { set: Function }); + AssignmentDeclarationKind[AssignmentDeclarationKind["ObjectDefinePropertyValue"] = 7] = "ObjectDefinePropertyValue"; + // Object.defineProperty(exports || module.exports, 'name', ...); + AssignmentDeclarationKind[AssignmentDeclarationKind["ObjectDefinePropertyExports"] = 8] = "ObjectDefinePropertyExports"; + // Object.defineProperty(Foo.prototype, 'name', ...); + AssignmentDeclarationKind[AssignmentDeclarationKind["ObjectDefinePrototypeProperty"] = 9] = "ObjectDefinePrototypeProperty"; + })(AssignmentDeclarationKind = ts.AssignmentDeclarationKind || (ts.AssignmentDeclarationKind = {})); + var DiagnosticCategory; + (function (DiagnosticCategory) { + DiagnosticCategory[DiagnosticCategory["Warning"] = 0] = "Warning"; + DiagnosticCategory[DiagnosticCategory["Error"] = 1] = "Error"; + DiagnosticCategory[DiagnosticCategory["Suggestion"] = 2] = "Suggestion"; + DiagnosticCategory[DiagnosticCategory["Message"] = 3] = "Message"; + })(DiagnosticCategory = ts.DiagnosticCategory || (ts.DiagnosticCategory = {})); + /* @internal */ + function diagnosticCategoryName(d, lowerCase) { + if (lowerCase === void 0) { lowerCase = true; } + var name = DiagnosticCategory[d.category]; + return lowerCase ? name.toLowerCase() : name; + } + ts.diagnosticCategoryName = diagnosticCategoryName; + var ModuleResolutionKind; + (function (ModuleResolutionKind) { + ModuleResolutionKind[ModuleResolutionKind["Classic"] = 1] = "Classic"; + ModuleResolutionKind[ModuleResolutionKind["NodeJs"] = 2] = "NodeJs"; + })(ModuleResolutionKind = ts.ModuleResolutionKind || (ts.ModuleResolutionKind = {})); + var ModuleKind; + (function (ModuleKind) { + ModuleKind[ModuleKind["None"] = 0] = "None"; + ModuleKind[ModuleKind["CommonJS"] = 1] = "CommonJS"; + ModuleKind[ModuleKind["AMD"] = 2] = "AMD"; + ModuleKind[ModuleKind["UMD"] = 3] = "UMD"; + ModuleKind[ModuleKind["System"] = 4] = "System"; + ModuleKind[ModuleKind["ES2015"] = 5] = "ES2015"; + ModuleKind[ModuleKind["ESNext"] = 6] = "ESNext"; + })(ModuleKind = ts.ModuleKind || (ts.ModuleKind = {})); + var JsxEmit; + (function (JsxEmit) { + JsxEmit[JsxEmit["None"] = 0] = "None"; + JsxEmit[JsxEmit["Preserve"] = 1] = "Preserve"; + JsxEmit[JsxEmit["React"] = 2] = "React"; + JsxEmit[JsxEmit["ReactNative"] = 3] = "ReactNative"; + })(JsxEmit = ts.JsxEmit || (ts.JsxEmit = {})); + var NewLineKind; + (function (NewLineKind) { + NewLineKind[NewLineKind["CarriageReturnLineFeed"] = 0] = "CarriageReturnLineFeed"; + NewLineKind[NewLineKind["LineFeed"] = 1] = "LineFeed"; + })(NewLineKind = ts.NewLineKind || (ts.NewLineKind = {})); + var ScriptKind; + (function (ScriptKind) { + ScriptKind[ScriptKind["Unknown"] = 0] = "Unknown"; + ScriptKind[ScriptKind["JS"] = 1] = "JS"; + ScriptKind[ScriptKind["JSX"] = 2] = "JSX"; + ScriptKind[ScriptKind["TS"] = 3] = "TS"; + ScriptKind[ScriptKind["TSX"] = 4] = "TSX"; + ScriptKind[ScriptKind["External"] = 5] = "External"; + ScriptKind[ScriptKind["JSON"] = 6] = "JSON"; + /** + * Used on extensions that doesn't define the ScriptKind but the content defines it. + * Deferred extensions are going to be included in all project contexts. + */ + ScriptKind[ScriptKind["Deferred"] = 7] = "Deferred"; + })(ScriptKind = ts.ScriptKind || (ts.ScriptKind = {})); + var ScriptTarget; + (function (ScriptTarget) { + ScriptTarget[ScriptTarget["ES3"] = 0] = "ES3"; + ScriptTarget[ScriptTarget["ES5"] = 1] = "ES5"; + ScriptTarget[ScriptTarget["ES2015"] = 2] = "ES2015"; + ScriptTarget[ScriptTarget["ES2016"] = 3] = "ES2016"; + ScriptTarget[ScriptTarget["ES2017"] = 4] = "ES2017"; + ScriptTarget[ScriptTarget["ES2018"] = 5] = "ES2018"; + ScriptTarget[ScriptTarget["ESNext"] = 6] = "ESNext"; + ScriptTarget[ScriptTarget["JSON"] = 100] = "JSON"; + ScriptTarget[ScriptTarget["Latest"] = 6] = "Latest"; + })(ScriptTarget = ts.ScriptTarget || (ts.ScriptTarget = {})); + var LanguageVariant; + (function (LanguageVariant) { + LanguageVariant[LanguageVariant["Standard"] = 0] = "Standard"; + LanguageVariant[LanguageVariant["JSX"] = 1] = "JSX"; + })(LanguageVariant = ts.LanguageVariant || (ts.LanguageVariant = {})); + var WatchDirectoryFlags; + (function (WatchDirectoryFlags) { + WatchDirectoryFlags[WatchDirectoryFlags["None"] = 0] = "None"; + WatchDirectoryFlags[WatchDirectoryFlags["Recursive"] = 1] = "Recursive"; + })(WatchDirectoryFlags = ts.WatchDirectoryFlags || (ts.WatchDirectoryFlags = {})); + /* @internal */ + var CharacterCodes; + (function (CharacterCodes) { + CharacterCodes[CharacterCodes["nullCharacter"] = 0] = "nullCharacter"; + CharacterCodes[CharacterCodes["maxAsciiCharacter"] = 127] = "maxAsciiCharacter"; + CharacterCodes[CharacterCodes["lineFeed"] = 10] = "lineFeed"; + CharacterCodes[CharacterCodes["carriageReturn"] = 13] = "carriageReturn"; + CharacterCodes[CharacterCodes["lineSeparator"] = 8232] = "lineSeparator"; + CharacterCodes[CharacterCodes["paragraphSeparator"] = 8233] = "paragraphSeparator"; + CharacterCodes[CharacterCodes["nextLine"] = 133] = "nextLine"; + // Unicode 3.0 space characters + CharacterCodes[CharacterCodes["space"] = 32] = "space"; + CharacterCodes[CharacterCodes["nonBreakingSpace"] = 160] = "nonBreakingSpace"; + CharacterCodes[CharacterCodes["enQuad"] = 8192] = "enQuad"; + CharacterCodes[CharacterCodes["emQuad"] = 8193] = "emQuad"; + CharacterCodes[CharacterCodes["enSpace"] = 8194] = "enSpace"; + CharacterCodes[CharacterCodes["emSpace"] = 8195] = "emSpace"; + CharacterCodes[CharacterCodes["threePerEmSpace"] = 8196] = "threePerEmSpace"; + CharacterCodes[CharacterCodes["fourPerEmSpace"] = 8197] = "fourPerEmSpace"; + CharacterCodes[CharacterCodes["sixPerEmSpace"] = 8198] = "sixPerEmSpace"; + CharacterCodes[CharacterCodes["figureSpace"] = 8199] = "figureSpace"; + CharacterCodes[CharacterCodes["punctuationSpace"] = 8200] = "punctuationSpace"; + CharacterCodes[CharacterCodes["thinSpace"] = 8201] = "thinSpace"; + CharacterCodes[CharacterCodes["hairSpace"] = 8202] = "hairSpace"; + CharacterCodes[CharacterCodes["zeroWidthSpace"] = 8203] = "zeroWidthSpace"; + CharacterCodes[CharacterCodes["narrowNoBreakSpace"] = 8239] = "narrowNoBreakSpace"; + CharacterCodes[CharacterCodes["ideographicSpace"] = 12288] = "ideographicSpace"; + CharacterCodes[CharacterCodes["mathematicalSpace"] = 8287] = "mathematicalSpace"; + CharacterCodes[CharacterCodes["ogham"] = 5760] = "ogham"; + CharacterCodes[CharacterCodes["_"] = 95] = "_"; + CharacterCodes[CharacterCodes["$"] = 36] = "$"; + CharacterCodes[CharacterCodes["_0"] = 48] = "_0"; + CharacterCodes[CharacterCodes["_1"] = 49] = "_1"; + CharacterCodes[CharacterCodes["_2"] = 50] = "_2"; + CharacterCodes[CharacterCodes["_3"] = 51] = "_3"; + CharacterCodes[CharacterCodes["_4"] = 52] = "_4"; + CharacterCodes[CharacterCodes["_5"] = 53] = "_5"; + CharacterCodes[CharacterCodes["_6"] = 54] = "_6"; + CharacterCodes[CharacterCodes["_7"] = 55] = "_7"; + CharacterCodes[CharacterCodes["_8"] = 56] = "_8"; + CharacterCodes[CharacterCodes["_9"] = 57] = "_9"; + CharacterCodes[CharacterCodes["a"] = 97] = "a"; + CharacterCodes[CharacterCodes["b"] = 98] = "b"; + CharacterCodes[CharacterCodes["c"] = 99] = "c"; + CharacterCodes[CharacterCodes["d"] = 100] = "d"; + CharacterCodes[CharacterCodes["e"] = 101] = "e"; + CharacterCodes[CharacterCodes["f"] = 102] = "f"; + CharacterCodes[CharacterCodes["g"] = 103] = "g"; + CharacterCodes[CharacterCodes["h"] = 104] = "h"; + CharacterCodes[CharacterCodes["i"] = 105] = "i"; + CharacterCodes[CharacterCodes["j"] = 106] = "j"; + CharacterCodes[CharacterCodes["k"] = 107] = "k"; + CharacterCodes[CharacterCodes["l"] = 108] = "l"; + CharacterCodes[CharacterCodes["m"] = 109] = "m"; + CharacterCodes[CharacterCodes["n"] = 110] = "n"; + CharacterCodes[CharacterCodes["o"] = 111] = "o"; + CharacterCodes[CharacterCodes["p"] = 112] = "p"; + CharacterCodes[CharacterCodes["q"] = 113] = "q"; + CharacterCodes[CharacterCodes["r"] = 114] = "r"; + CharacterCodes[CharacterCodes["s"] = 115] = "s"; + CharacterCodes[CharacterCodes["t"] = 116] = "t"; + CharacterCodes[CharacterCodes["u"] = 117] = "u"; + CharacterCodes[CharacterCodes["v"] = 118] = "v"; + CharacterCodes[CharacterCodes["w"] = 119] = "w"; + CharacterCodes[CharacterCodes["x"] = 120] = "x"; + CharacterCodes[CharacterCodes["y"] = 121] = "y"; + CharacterCodes[CharacterCodes["z"] = 122] = "z"; + CharacterCodes[CharacterCodes["A"] = 65] = "A"; + CharacterCodes[CharacterCodes["B"] = 66] = "B"; + CharacterCodes[CharacterCodes["C"] = 67] = "C"; + CharacterCodes[CharacterCodes["D"] = 68] = "D"; + CharacterCodes[CharacterCodes["E"] = 69] = "E"; + CharacterCodes[CharacterCodes["F"] = 70] = "F"; + CharacterCodes[CharacterCodes["G"] = 71] = "G"; + CharacterCodes[CharacterCodes["H"] = 72] = "H"; + CharacterCodes[CharacterCodes["I"] = 73] = "I"; + CharacterCodes[CharacterCodes["J"] = 74] = "J"; + CharacterCodes[CharacterCodes["K"] = 75] = "K"; + CharacterCodes[CharacterCodes["L"] = 76] = "L"; + CharacterCodes[CharacterCodes["M"] = 77] = "M"; + CharacterCodes[CharacterCodes["N"] = 78] = "N"; + CharacterCodes[CharacterCodes["O"] = 79] = "O"; + CharacterCodes[CharacterCodes["P"] = 80] = "P"; + CharacterCodes[CharacterCodes["Q"] = 81] = "Q"; + CharacterCodes[CharacterCodes["R"] = 82] = "R"; + CharacterCodes[CharacterCodes["S"] = 83] = "S"; + CharacterCodes[CharacterCodes["T"] = 84] = "T"; + CharacterCodes[CharacterCodes["U"] = 85] = "U"; + CharacterCodes[CharacterCodes["V"] = 86] = "V"; + CharacterCodes[CharacterCodes["W"] = 87] = "W"; + CharacterCodes[CharacterCodes["X"] = 88] = "X"; + CharacterCodes[CharacterCodes["Y"] = 89] = "Y"; + CharacterCodes[CharacterCodes["Z"] = 90] = "Z"; + CharacterCodes[CharacterCodes["ampersand"] = 38] = "ampersand"; + CharacterCodes[CharacterCodes["asterisk"] = 42] = "asterisk"; + CharacterCodes[CharacterCodes["at"] = 64] = "at"; + CharacterCodes[CharacterCodes["backslash"] = 92] = "backslash"; + CharacterCodes[CharacterCodes["backtick"] = 96] = "backtick"; + CharacterCodes[CharacterCodes["bar"] = 124] = "bar"; + CharacterCodes[CharacterCodes["caret"] = 94] = "caret"; + CharacterCodes[CharacterCodes["closeBrace"] = 125] = "closeBrace"; + CharacterCodes[CharacterCodes["closeBracket"] = 93] = "closeBracket"; + CharacterCodes[CharacterCodes["closeParen"] = 41] = "closeParen"; + CharacterCodes[CharacterCodes["colon"] = 58] = "colon"; + CharacterCodes[CharacterCodes["comma"] = 44] = "comma"; + CharacterCodes[CharacterCodes["dot"] = 46] = "dot"; + CharacterCodes[CharacterCodes["doubleQuote"] = 34] = "doubleQuote"; + CharacterCodes[CharacterCodes["equals"] = 61] = "equals"; + CharacterCodes[CharacterCodes["exclamation"] = 33] = "exclamation"; + CharacterCodes[CharacterCodes["greaterThan"] = 62] = "greaterThan"; + CharacterCodes[CharacterCodes["hash"] = 35] = "hash"; + CharacterCodes[CharacterCodes["lessThan"] = 60] = "lessThan"; + CharacterCodes[CharacterCodes["minus"] = 45] = "minus"; + CharacterCodes[CharacterCodes["openBrace"] = 123] = "openBrace"; + CharacterCodes[CharacterCodes["openBracket"] = 91] = "openBracket"; + CharacterCodes[CharacterCodes["openParen"] = 40] = "openParen"; + CharacterCodes[CharacterCodes["percent"] = 37] = "percent"; + CharacterCodes[CharacterCodes["plus"] = 43] = "plus"; + CharacterCodes[CharacterCodes["question"] = 63] = "question"; + CharacterCodes[CharacterCodes["semicolon"] = 59] = "semicolon"; + CharacterCodes[CharacterCodes["singleQuote"] = 39] = "singleQuote"; + CharacterCodes[CharacterCodes["slash"] = 47] = "slash"; + CharacterCodes[CharacterCodes["tilde"] = 126] = "tilde"; + CharacterCodes[CharacterCodes["backspace"] = 8] = "backspace"; + CharacterCodes[CharacterCodes["formFeed"] = 12] = "formFeed"; + CharacterCodes[CharacterCodes["byteOrderMark"] = 65279] = "byteOrderMark"; + CharacterCodes[CharacterCodes["tab"] = 9] = "tab"; + CharacterCodes[CharacterCodes["verticalTab"] = 11] = "verticalTab"; + })(CharacterCodes = ts.CharacterCodes || (ts.CharacterCodes = {})); + var Extension; + (function (Extension) { + Extension["Ts"] = ".ts"; + Extension["Tsx"] = ".tsx"; + Extension["Dts"] = ".d.ts"; + Extension["Js"] = ".js"; + Extension["Jsx"] = ".jsx"; + Extension["Json"] = ".json"; + })(Extension = ts.Extension || (ts.Extension = {})); + /* @internal */ + var TransformFlags; + (function (TransformFlags) { + TransformFlags[TransformFlags["None"] = 0] = "None"; + // Facts + // - Flags used to indicate that a node or subtree contains syntax that requires transformation. + TransformFlags[TransformFlags["TypeScript"] = 1] = "TypeScript"; + TransformFlags[TransformFlags["ContainsTypeScript"] = 2] = "ContainsTypeScript"; + TransformFlags[TransformFlags["ContainsJsx"] = 4] = "ContainsJsx"; + TransformFlags[TransformFlags["ContainsESNext"] = 8] = "ContainsESNext"; + TransformFlags[TransformFlags["ContainsES2017"] = 16] = "ContainsES2017"; + TransformFlags[TransformFlags["ContainsES2016"] = 32] = "ContainsES2016"; + TransformFlags[TransformFlags["ES2015"] = 64] = "ES2015"; + TransformFlags[TransformFlags["ContainsES2015"] = 128] = "ContainsES2015"; + TransformFlags[TransformFlags["Generator"] = 256] = "Generator"; + TransformFlags[TransformFlags["ContainsGenerator"] = 512] = "ContainsGenerator"; + TransformFlags[TransformFlags["DestructuringAssignment"] = 1024] = "DestructuringAssignment"; + TransformFlags[TransformFlags["ContainsDestructuringAssignment"] = 2048] = "ContainsDestructuringAssignment"; + // Markers + // - Flags used to indicate that a subtree contains a specific transformation. + TransformFlags[TransformFlags["ContainsTypeScriptClassSyntax"] = 4096] = "ContainsTypeScriptClassSyntax"; + TransformFlags[TransformFlags["ContainsLexicalThis"] = 8192] = "ContainsLexicalThis"; + TransformFlags[TransformFlags["ContainsCapturedLexicalThis"] = 16384] = "ContainsCapturedLexicalThis"; + TransformFlags[TransformFlags["ContainsLexicalThisInComputedPropertyName"] = 32768] = "ContainsLexicalThisInComputedPropertyName"; + TransformFlags[TransformFlags["ContainsDefaultValueAssignments"] = 65536] = "ContainsDefaultValueAssignments"; + TransformFlags[TransformFlags["ContainsRestOrSpread"] = 131072] = "ContainsRestOrSpread"; + TransformFlags[TransformFlags["ContainsObjectRestOrSpread"] = 262144] = "ContainsObjectRestOrSpread"; + TransformFlags[TransformFlags["ContainsComputedPropertyName"] = 524288] = "ContainsComputedPropertyName"; + TransformFlags[TransformFlags["ContainsBlockScopedBinding"] = 1048576] = "ContainsBlockScopedBinding"; + TransformFlags[TransformFlags["ContainsBindingPattern"] = 2097152] = "ContainsBindingPattern"; + TransformFlags[TransformFlags["ContainsYield"] = 4194304] = "ContainsYield"; + TransformFlags[TransformFlags["ContainsHoistedDeclarationOrCompletion"] = 8388608] = "ContainsHoistedDeclarationOrCompletion"; + TransformFlags[TransformFlags["ContainsDynamicImport"] = 16777216] = "ContainsDynamicImport"; + TransformFlags[TransformFlags["Super"] = 33554432] = "Super"; + TransformFlags[TransformFlags["ContainsSuper"] = 67108864] = "ContainsSuper"; + // Please leave this as 1 << 29. + // It is the maximum bit we can set before we outgrow the size of a v8 small integer (SMI) on an x86 system. + // It is a good reminder of how much room we have left + TransformFlags[TransformFlags["HasComputedFlags"] = 536870912] = "HasComputedFlags"; + // Assertions + // - Bitmasks that are used to assert facts about the syntax of a node and its subtree. + TransformFlags[TransformFlags["AssertTypeScript"] = 3] = "AssertTypeScript"; + TransformFlags[TransformFlags["AssertJsx"] = 4] = "AssertJsx"; + TransformFlags[TransformFlags["AssertESNext"] = 8] = "AssertESNext"; + TransformFlags[TransformFlags["AssertES2017"] = 16] = "AssertES2017"; + TransformFlags[TransformFlags["AssertES2016"] = 32] = "AssertES2016"; + TransformFlags[TransformFlags["AssertES2015"] = 192] = "AssertES2015"; + TransformFlags[TransformFlags["AssertGenerator"] = 768] = "AssertGenerator"; + TransformFlags[TransformFlags["AssertDestructuringAssignment"] = 3072] = "AssertDestructuringAssignment"; + // Scope Exclusions + // - Bitmasks that exclude flags from propagating out of a specific context + // into the subtree flags of their container. + TransformFlags[TransformFlags["OuterExpressionExcludes"] = 536872257] = "OuterExpressionExcludes"; + TransformFlags[TransformFlags["PropertyAccessExcludes"] = 570426689] = "PropertyAccessExcludes"; + TransformFlags[TransformFlags["NodeExcludes"] = 637535553] = "NodeExcludes"; + TransformFlags[TransformFlags["ArrowFunctionExcludes"] = 653604161] = "ArrowFunctionExcludes"; + TransformFlags[TransformFlags["FunctionExcludes"] = 653620545] = "FunctionExcludes"; + TransformFlags[TransformFlags["ConstructorExcludes"] = 653616449] = "ConstructorExcludes"; + TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = 653616449] = "MethodOrAccessorExcludes"; + TransformFlags[TransformFlags["ClassExcludes"] = 638121281] = "ClassExcludes"; + TransformFlags[TransformFlags["ModuleExcludes"] = 647001409] = "ModuleExcludes"; + TransformFlags[TransformFlags["TypeExcludes"] = -3] = "TypeExcludes"; + TransformFlags[TransformFlags["ObjectLiteralExcludes"] = 638358849] = "ObjectLiteralExcludes"; + TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = 637666625] = "ArrayLiteralOrCallOrNewExcludes"; + TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = 639894849] = "VariableDeclarationListExcludes"; + TransformFlags[TransformFlags["ParameterExcludes"] = 637535553] = "ParameterExcludes"; + TransformFlags[TransformFlags["CatchClauseExcludes"] = 637797697] = "CatchClauseExcludes"; + TransformFlags[TransformFlags["BindingPatternExcludes"] = 637666625] = "BindingPatternExcludes"; + // Masks + // - Additional bitmasks + TransformFlags[TransformFlags["ES2015FunctionSyntaxMask"] = 81920] = "ES2015FunctionSyntaxMask"; + })(TransformFlags = ts.TransformFlags || (ts.TransformFlags = {})); + var EmitFlags; + (function (EmitFlags) { + EmitFlags[EmitFlags["None"] = 0] = "None"; + EmitFlags[EmitFlags["SingleLine"] = 1] = "SingleLine"; + EmitFlags[EmitFlags["AdviseOnEmitNode"] = 2] = "AdviseOnEmitNode"; + EmitFlags[EmitFlags["NoSubstitution"] = 4] = "NoSubstitution"; + EmitFlags[EmitFlags["CapturesThis"] = 8] = "CapturesThis"; + EmitFlags[EmitFlags["NoLeadingSourceMap"] = 16] = "NoLeadingSourceMap"; + EmitFlags[EmitFlags["NoTrailingSourceMap"] = 32] = "NoTrailingSourceMap"; + EmitFlags[EmitFlags["NoSourceMap"] = 48] = "NoSourceMap"; + EmitFlags[EmitFlags["NoNestedSourceMaps"] = 64] = "NoNestedSourceMaps"; + EmitFlags[EmitFlags["NoTokenLeadingSourceMaps"] = 128] = "NoTokenLeadingSourceMaps"; + EmitFlags[EmitFlags["NoTokenTrailingSourceMaps"] = 256] = "NoTokenTrailingSourceMaps"; + EmitFlags[EmitFlags["NoTokenSourceMaps"] = 384] = "NoTokenSourceMaps"; + EmitFlags[EmitFlags["NoLeadingComments"] = 512] = "NoLeadingComments"; + EmitFlags[EmitFlags["NoTrailingComments"] = 1024] = "NoTrailingComments"; + EmitFlags[EmitFlags["NoComments"] = 1536] = "NoComments"; + EmitFlags[EmitFlags["NoNestedComments"] = 2048] = "NoNestedComments"; + EmitFlags[EmitFlags["HelperName"] = 4096] = "HelperName"; + EmitFlags[EmitFlags["ExportName"] = 8192] = "ExportName"; + EmitFlags[EmitFlags["LocalName"] = 16384] = "LocalName"; + EmitFlags[EmitFlags["InternalName"] = 32768] = "InternalName"; + EmitFlags[EmitFlags["Indented"] = 65536] = "Indented"; + EmitFlags[EmitFlags["NoIndentation"] = 131072] = "NoIndentation"; + EmitFlags[EmitFlags["AsyncFunctionBody"] = 262144] = "AsyncFunctionBody"; + EmitFlags[EmitFlags["ReuseTempVariableScope"] = 524288] = "ReuseTempVariableScope"; + EmitFlags[EmitFlags["CustomPrologue"] = 1048576] = "CustomPrologue"; + EmitFlags[EmitFlags["NoHoisting"] = 2097152] = "NoHoisting"; + EmitFlags[EmitFlags["HasEndOfDeclarationMarker"] = 4194304] = "HasEndOfDeclarationMarker"; + EmitFlags[EmitFlags["Iterator"] = 8388608] = "Iterator"; + EmitFlags[EmitFlags["NoAsciiEscaping"] = 16777216] = "NoAsciiEscaping"; + /*@internal*/ EmitFlags[EmitFlags["TypeScriptClassWrapper"] = 33554432] = "TypeScriptClassWrapper"; + /*@internal*/ EmitFlags[EmitFlags["NeverApplyImportHelper"] = 67108864] = "NeverApplyImportHelper"; + })(EmitFlags = ts.EmitFlags || (ts.EmitFlags = {})); + /** + * Used by the checker, this enum keeps track of external emit helpers that should be type + * checked. + */ + /* @internal */ + var ExternalEmitHelpers; + (function (ExternalEmitHelpers) { + ExternalEmitHelpers[ExternalEmitHelpers["Extends"] = 1] = "Extends"; + ExternalEmitHelpers[ExternalEmitHelpers["Assign"] = 2] = "Assign"; + ExternalEmitHelpers[ExternalEmitHelpers["Rest"] = 4] = "Rest"; + ExternalEmitHelpers[ExternalEmitHelpers["Decorate"] = 8] = "Decorate"; + ExternalEmitHelpers[ExternalEmitHelpers["Metadata"] = 16] = "Metadata"; + ExternalEmitHelpers[ExternalEmitHelpers["Param"] = 32] = "Param"; + ExternalEmitHelpers[ExternalEmitHelpers["Awaiter"] = 64] = "Awaiter"; + ExternalEmitHelpers[ExternalEmitHelpers["Generator"] = 128] = "Generator"; + ExternalEmitHelpers[ExternalEmitHelpers["Values"] = 256] = "Values"; + ExternalEmitHelpers[ExternalEmitHelpers["Read"] = 512] = "Read"; + ExternalEmitHelpers[ExternalEmitHelpers["Spread"] = 1024] = "Spread"; + ExternalEmitHelpers[ExternalEmitHelpers["Await"] = 2048] = "Await"; + ExternalEmitHelpers[ExternalEmitHelpers["AsyncGenerator"] = 4096] = "AsyncGenerator"; + ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegator"] = 8192] = "AsyncDelegator"; + ExternalEmitHelpers[ExternalEmitHelpers["AsyncValues"] = 16384] = "AsyncValues"; + ExternalEmitHelpers[ExternalEmitHelpers["ExportStar"] = 32768] = "ExportStar"; + ExternalEmitHelpers[ExternalEmitHelpers["MakeTemplateObject"] = 65536] = "MakeTemplateObject"; + ExternalEmitHelpers[ExternalEmitHelpers["FirstEmitHelper"] = 1] = "FirstEmitHelper"; + ExternalEmitHelpers[ExternalEmitHelpers["LastEmitHelper"] = 65536] = "LastEmitHelper"; + // Helpers included by ES2015 for..of + ExternalEmitHelpers[ExternalEmitHelpers["ForOfIncludes"] = 256] = "ForOfIncludes"; + // Helpers included by ES2017 for..await..of + ExternalEmitHelpers[ExternalEmitHelpers["ForAwaitOfIncludes"] = 16384] = "ForAwaitOfIncludes"; + // Helpers included by ES2017 async generators + ExternalEmitHelpers[ExternalEmitHelpers["AsyncGeneratorIncludes"] = 6144] = "AsyncGeneratorIncludes"; + // Helpers included by yield* in ES2017 async generators + ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegatorIncludes"] = 26624] = "AsyncDelegatorIncludes"; + // Helpers included by ES2015 spread + ExternalEmitHelpers[ExternalEmitHelpers["SpreadIncludes"] = 1536] = "SpreadIncludes"; + })(ExternalEmitHelpers = ts.ExternalEmitHelpers || (ts.ExternalEmitHelpers = {})); + var EmitHint; + (function (EmitHint) { + EmitHint[EmitHint["SourceFile"] = 0] = "SourceFile"; + EmitHint[EmitHint["Expression"] = 1] = "Expression"; + EmitHint[EmitHint["IdentifierName"] = 2] = "IdentifierName"; + EmitHint[EmitHint["MappedTypeParameter"] = 3] = "MappedTypeParameter"; + EmitHint[EmitHint["Unspecified"] = 4] = "Unspecified"; + EmitHint[EmitHint["EmbeddedStatement"] = 5] = "EmbeddedStatement"; + })(EmitHint = ts.EmitHint || (ts.EmitHint = {})); + var ListFormat; + (function (ListFormat) { + ListFormat[ListFormat["None"] = 0] = "None"; + // Line separators + ListFormat[ListFormat["SingleLine"] = 0] = "SingleLine"; + ListFormat[ListFormat["MultiLine"] = 1] = "MultiLine"; + ListFormat[ListFormat["PreserveLines"] = 2] = "PreserveLines"; + ListFormat[ListFormat["LinesMask"] = 3] = "LinesMask"; + // Delimiters + ListFormat[ListFormat["NotDelimited"] = 0] = "NotDelimited"; + ListFormat[ListFormat["BarDelimited"] = 4] = "BarDelimited"; + ListFormat[ListFormat["AmpersandDelimited"] = 8] = "AmpersandDelimited"; + ListFormat[ListFormat["CommaDelimited"] = 16] = "CommaDelimited"; + ListFormat[ListFormat["AsteriskDelimited"] = 32] = "AsteriskDelimited"; + ListFormat[ListFormat["DelimitersMask"] = 60] = "DelimitersMask"; + ListFormat[ListFormat["AllowTrailingComma"] = 64] = "AllowTrailingComma"; + // Whitespace + ListFormat[ListFormat["Indented"] = 128] = "Indented"; + ListFormat[ListFormat["SpaceBetweenBraces"] = 256] = "SpaceBetweenBraces"; + ListFormat[ListFormat["SpaceBetweenSiblings"] = 512] = "SpaceBetweenSiblings"; + // Brackets/Braces + ListFormat[ListFormat["Braces"] = 1024] = "Braces"; + ListFormat[ListFormat["Parenthesis"] = 2048] = "Parenthesis"; + ListFormat[ListFormat["AngleBrackets"] = 4096] = "AngleBrackets"; + ListFormat[ListFormat["SquareBrackets"] = 8192] = "SquareBrackets"; + ListFormat[ListFormat["BracketsMask"] = 15360] = "BracketsMask"; + ListFormat[ListFormat["OptionalIfUndefined"] = 16384] = "OptionalIfUndefined"; + ListFormat[ListFormat["OptionalIfEmpty"] = 32768] = "OptionalIfEmpty"; + ListFormat[ListFormat["Optional"] = 49152] = "Optional"; + // Other + ListFormat[ListFormat["PreferNewLine"] = 65536] = "PreferNewLine"; + ListFormat[ListFormat["NoTrailingNewLine"] = 131072] = "NoTrailingNewLine"; + ListFormat[ListFormat["NoInterveningComments"] = 262144] = "NoInterveningComments"; + ListFormat[ListFormat["NoSpaceIfEmpty"] = 524288] = "NoSpaceIfEmpty"; + ListFormat[ListFormat["SingleElement"] = 1048576] = "SingleElement"; + // Precomputed Formats + ListFormat[ListFormat["Modifiers"] = 262656] = "Modifiers"; + ListFormat[ListFormat["HeritageClauses"] = 512] = "HeritageClauses"; + ListFormat[ListFormat["SingleLineTypeLiteralMembers"] = 768] = "SingleLineTypeLiteralMembers"; + ListFormat[ListFormat["MultiLineTypeLiteralMembers"] = 32897] = "MultiLineTypeLiteralMembers"; + ListFormat[ListFormat["TupleTypeElements"] = 528] = "TupleTypeElements"; + ListFormat[ListFormat["UnionTypeConstituents"] = 516] = "UnionTypeConstituents"; + ListFormat[ListFormat["IntersectionTypeConstituents"] = 520] = "IntersectionTypeConstituents"; + ListFormat[ListFormat["ObjectBindingPatternElements"] = 525136] = "ObjectBindingPatternElements"; + ListFormat[ListFormat["ArrayBindingPatternElements"] = 524880] = "ArrayBindingPatternElements"; + ListFormat[ListFormat["ObjectLiteralExpressionProperties"] = 526226] = "ObjectLiteralExpressionProperties"; + ListFormat[ListFormat["ArrayLiteralExpressionElements"] = 8914] = "ArrayLiteralExpressionElements"; + ListFormat[ListFormat["CommaListElements"] = 528] = "CommaListElements"; + ListFormat[ListFormat["CallExpressionArguments"] = 2576] = "CallExpressionArguments"; + ListFormat[ListFormat["NewExpressionArguments"] = 18960] = "NewExpressionArguments"; + ListFormat[ListFormat["TemplateExpressionSpans"] = 262144] = "TemplateExpressionSpans"; + ListFormat[ListFormat["SingleLineBlockStatements"] = 768] = "SingleLineBlockStatements"; + ListFormat[ListFormat["MultiLineBlockStatements"] = 129] = "MultiLineBlockStatements"; + ListFormat[ListFormat["VariableDeclarationList"] = 528] = "VariableDeclarationList"; + ListFormat[ListFormat["SingleLineFunctionBodyStatements"] = 768] = "SingleLineFunctionBodyStatements"; + ListFormat[ListFormat["MultiLineFunctionBodyStatements"] = 1] = "MultiLineFunctionBodyStatements"; + ListFormat[ListFormat["ClassHeritageClauses"] = 0] = "ClassHeritageClauses"; + ListFormat[ListFormat["ClassMembers"] = 129] = "ClassMembers"; + ListFormat[ListFormat["InterfaceMembers"] = 129] = "InterfaceMembers"; + ListFormat[ListFormat["EnumMembers"] = 145] = "EnumMembers"; + ListFormat[ListFormat["CaseBlockClauses"] = 129] = "CaseBlockClauses"; + ListFormat[ListFormat["NamedImportsOrExportsElements"] = 525136] = "NamedImportsOrExportsElements"; + ListFormat[ListFormat["JsxElementOrFragmentChildren"] = 262144] = "JsxElementOrFragmentChildren"; + ListFormat[ListFormat["JsxElementAttributes"] = 262656] = "JsxElementAttributes"; + ListFormat[ListFormat["CaseOrDefaultClauseStatements"] = 163969] = "CaseOrDefaultClauseStatements"; + ListFormat[ListFormat["HeritageClauseTypes"] = 528] = "HeritageClauseTypes"; + ListFormat[ListFormat["SourceFileStatements"] = 131073] = "SourceFileStatements"; + ListFormat[ListFormat["Decorators"] = 49153] = "Decorators"; + ListFormat[ListFormat["TypeArguments"] = 53776] = "TypeArguments"; + ListFormat[ListFormat["TypeParameters"] = 53776] = "TypeParameters"; + ListFormat[ListFormat["Parameters"] = 2576] = "Parameters"; + ListFormat[ListFormat["IndexSignatureParameters"] = 8848] = "IndexSignatureParameters"; + ListFormat[ListFormat["JSDocComment"] = 33] = "JSDocComment"; + })(ListFormat = ts.ListFormat || (ts.ListFormat = {})); + /* @internal */ + var PragmaKindFlags; + (function (PragmaKindFlags) { + PragmaKindFlags[PragmaKindFlags["None"] = 0] = "None"; + /** + * Triple slash comment of the form + * /// + */ + PragmaKindFlags[PragmaKindFlags["TripleSlashXML"] = 1] = "TripleSlashXML"; + /** + * Single line comment of the form + * // @pragma-name argval1 argval2 + * or + * /// @pragma-name argval1 argval2 + */ + PragmaKindFlags[PragmaKindFlags["SingleLine"] = 2] = "SingleLine"; + /** + * Multiline non-jsdoc pragma of the form + * /* @pragma-name argval1 argval2 * / + */ + PragmaKindFlags[PragmaKindFlags["MultiLine"] = 4] = "MultiLine"; + PragmaKindFlags[PragmaKindFlags["All"] = 7] = "All"; + PragmaKindFlags[PragmaKindFlags["Default"] = 7] = "Default"; + })(PragmaKindFlags = ts.PragmaKindFlags || (ts.PragmaKindFlags = {})); + /** + * This function only exists to cause exact types to be inferred for all the literals within `commentPragmas` + */ + /* @internal */ + function _contextuallyTypePragmas(args) { + return args; + } + // While not strictly a type, this is here because `PragmaMap` needs to be here to be used with `SourceFile`, and we don't + // fancy effectively defining it twice, once in value-space and once in type-space + /* @internal */ + ts.commentPragmas = _contextuallyTypePragmas({ + "reference": { + args: [ + { name: "types", optional: true, captureSpan: true }, + { name: "lib", optional: true, captureSpan: true }, + { name: "path", optional: true, captureSpan: true }, + { name: "no-default-lib", optional: true } + ], + kind: 1 /* TripleSlashXML */ + }, + "amd-dependency": { + args: [{ name: "path" }, { name: "name", optional: true }], + kind: 1 /* TripleSlashXML */ + }, + "amd-module": { + args: [{ name: "name" }], + kind: 1 /* TripleSlashXML */ + }, + "ts-check": { + kind: 2 /* SingleLine */ + }, + "ts-nocheck": { + kind: 2 /* SingleLine */ + }, + "jsx": { + args: [{ name: "factory" }], + kind: 4 /* MultiLine */ + }, + }); +})(ts || (ts = {})); +var ts; +(function (ts) { + /** + * Set a high stack trace limit to provide more information in case of an error. + * Called for command-line and server use cases. + * Not called if TypeScript is used as a library. + */ + /* @internal */ + function setStackTraceLimit() { + if (Error.stackTraceLimit < 100) { // Also tests that we won't set the property if it doesn't exist. + Error.stackTraceLimit = 100; + } + } + ts.setStackTraceLimit = setStackTraceLimit; + var FileWatcherEventKind; + (function (FileWatcherEventKind) { + FileWatcherEventKind[FileWatcherEventKind["Created"] = 0] = "Created"; + FileWatcherEventKind[FileWatcherEventKind["Changed"] = 1] = "Changed"; + FileWatcherEventKind[FileWatcherEventKind["Deleted"] = 2] = "Deleted"; + })(FileWatcherEventKind = ts.FileWatcherEventKind || (ts.FileWatcherEventKind = {})); + /* @internal */ + var PollingInterval; + (function (PollingInterval) { + PollingInterval[PollingInterval["High"] = 2000] = "High"; + PollingInterval[PollingInterval["Medium"] = 500] = "Medium"; + PollingInterval[PollingInterval["Low"] = 250] = "Low"; + })(PollingInterval = ts.PollingInterval || (ts.PollingInterval = {})); + /* @internal */ + ts.missingFileModifiedTime = new Date(0); // Any subsequent modification will occur after this time + function createPollingIntervalBasedLevels(levels) { + var _a; + return _a = {}, + _a[PollingInterval.Low] = levels.Low, + _a[PollingInterval.Medium] = levels.Medium, + _a[PollingInterval.High] = levels.High, + _a; + } + var defaultChunkLevels = { Low: 32, Medium: 64, High: 256 }; + var pollingChunkSize = createPollingIntervalBasedLevels(defaultChunkLevels); + /* @internal */ + ts.unchangedPollThresholds = createPollingIntervalBasedLevels(defaultChunkLevels); + /* @internal */ + function setCustomPollingValues(system) { + if (!system.getEnvironmentVariable) { + return; + } + var pollingIntervalChanged = setCustomLevels("TSC_WATCH_POLLINGINTERVAL", PollingInterval); + pollingChunkSize = getCustomPollingBasedLevels("TSC_WATCH_POLLINGCHUNKSIZE", defaultChunkLevels) || pollingChunkSize; + ts.unchangedPollThresholds = getCustomPollingBasedLevels("TSC_WATCH_UNCHANGEDPOLLTHRESHOLDS", defaultChunkLevels) || ts.unchangedPollThresholds; + function getLevel(envVar, level) { + return system.getEnvironmentVariable(envVar + "_" + level.toUpperCase()); + } + function getCustomLevels(baseVariable) { + var customLevels; + setCustomLevel("Low"); + setCustomLevel("Medium"); + setCustomLevel("High"); + return customLevels; + function setCustomLevel(level) { + var customLevel = getLevel(baseVariable, level); + if (customLevel) { + (customLevels || (customLevels = {}))[level] = Number(customLevel); + } + } + } + function setCustomLevels(baseVariable, levels) { + var customLevels = getCustomLevels(baseVariable); + if (customLevels) { + setLevel("Low"); + setLevel("Medium"); + setLevel("High"); + return true; + } + return false; + function setLevel(level) { + levels[level] = customLevels[level] || levels[level]; + } + } + function getCustomPollingBasedLevels(baseVariable, defaultLevels) { + var customLevels = getCustomLevels(baseVariable); + return (pollingIntervalChanged || customLevels) && + createPollingIntervalBasedLevels(customLevels ? __assign({}, defaultLevels, customLevels) : defaultLevels); + } + } + ts.setCustomPollingValues = setCustomPollingValues; + /* @internal */ + function createDynamicPriorityPollingWatchFile(host) { + var watchedFiles = []; + var changedFilesInLastPoll = []; + var lowPollingIntervalQueue = createPollingIntervalQueue(PollingInterval.Low); + var mediumPollingIntervalQueue = createPollingIntervalQueue(PollingInterval.Medium); + var highPollingIntervalQueue = createPollingIntervalQueue(PollingInterval.High); + return watchFile; + function watchFile(fileName, callback, defaultPollingInterval) { + var file = { + fileName: fileName, + callback: callback, + unchangedPolls: 0, + mtime: getModifiedTime(fileName) + }; + watchedFiles.push(file); + addToPollingIntervalQueue(file, defaultPollingInterval); + return { + close: function () { + file.isClosed = true; + // Remove from watchedFiles + ts.unorderedRemoveItem(watchedFiles, file); + // Do not update polling interval queue since that will happen as part of polling + } + }; + } + function createPollingIntervalQueue(pollingInterval) { + var queue = []; + queue.pollingInterval = pollingInterval; + queue.pollIndex = 0; + queue.pollScheduled = false; + return queue; + } + function pollPollingIntervalQueue(queue) { + queue.pollIndex = pollQueue(queue, queue.pollingInterval, queue.pollIndex, pollingChunkSize[queue.pollingInterval]); + // Set the next polling index and timeout + if (queue.length) { + scheduleNextPoll(queue.pollingInterval); + } + else { + ts.Debug.assert(queue.pollIndex === 0); + queue.pollScheduled = false; + } + } + function pollLowPollingIntervalQueue(queue) { + // Always poll complete list of changedFilesInLastPoll + pollQueue(changedFilesInLastPoll, PollingInterval.Low, /*pollIndex*/ 0, changedFilesInLastPoll.length); + // Finally do the actual polling of the queue + pollPollingIntervalQueue(queue); + // Schedule poll if there are files in changedFilesInLastPoll but no files in the actual queue + // as pollPollingIntervalQueue wont schedule for next poll + if (!queue.pollScheduled && changedFilesInLastPoll.length) { + scheduleNextPoll(PollingInterval.Low); + } + } + function pollQueue(queue, pollingInterval, pollIndex, chunkSize) { + // Max visit would be all elements of the queue + var needsVisit = queue.length; + var definedValueCopyToIndex = pollIndex; + for (var polled = 0; polled < chunkSize && needsVisit > 0; nextPollIndex(), needsVisit--) { + var watchedFile = queue[pollIndex]; + if (!watchedFile) { + continue; + } + else if (watchedFile.isClosed) { + queue[pollIndex] = undefined; + continue; + } + polled++; + var fileChanged = onWatchedFileStat(watchedFile, getModifiedTime(watchedFile.fileName)); + if (watchedFile.isClosed) { + // Closed watcher as part of callback + queue[pollIndex] = undefined; + } + else if (fileChanged) { + watchedFile.unchangedPolls = 0; + // Changed files go to changedFilesInLastPoll queue + if (queue !== changedFilesInLastPoll) { + queue[pollIndex] = undefined; + addChangedFileToLowPollingIntervalQueue(watchedFile); + } + } + else if (watchedFile.unchangedPolls !== ts.unchangedPollThresholds[pollingInterval]) { + watchedFile.unchangedPolls++; + } + else if (queue === changedFilesInLastPoll) { + // Restart unchangedPollCount for unchanged file and move to low polling interval queue + watchedFile.unchangedPolls = 1; + queue[pollIndex] = undefined; + addToPollingIntervalQueue(watchedFile, PollingInterval.Low); + } + else if (pollingInterval !== PollingInterval.High) { + watchedFile.unchangedPolls++; + queue[pollIndex] = undefined; + addToPollingIntervalQueue(watchedFile, pollingInterval === PollingInterval.Low ? PollingInterval.Medium : PollingInterval.High); + } + if (queue[pollIndex]) { + // Copy this file to the non hole location + if (definedValueCopyToIndex < pollIndex) { + queue[definedValueCopyToIndex] = watchedFile; + queue[pollIndex] = undefined; + } + definedValueCopyToIndex++; + } + } + // Return next poll index + return pollIndex; + function nextPollIndex() { + pollIndex++; + if (pollIndex === queue.length) { + if (definedValueCopyToIndex < pollIndex) { + // There are holes from nextDefinedValueIndex to end of queue, change queue size + queue.length = definedValueCopyToIndex; + } + pollIndex = 0; + definedValueCopyToIndex = 0; + } + } + } + function pollingIntervalQueue(pollingInterval) { + switch (pollingInterval) { + case PollingInterval.Low: + return lowPollingIntervalQueue; + case PollingInterval.Medium: + return mediumPollingIntervalQueue; + case PollingInterval.High: + return highPollingIntervalQueue; + } + } + function addToPollingIntervalQueue(file, pollingInterval) { + pollingIntervalQueue(pollingInterval).push(file); + scheduleNextPollIfNotAlreadyScheduled(pollingInterval); + } + function addChangedFileToLowPollingIntervalQueue(file) { + changedFilesInLastPoll.push(file); + scheduleNextPollIfNotAlreadyScheduled(PollingInterval.Low); + } + function scheduleNextPollIfNotAlreadyScheduled(pollingInterval) { + if (!pollingIntervalQueue(pollingInterval).pollScheduled) { + scheduleNextPoll(pollingInterval); + } + } + function scheduleNextPoll(pollingInterval) { + pollingIntervalQueue(pollingInterval).pollScheduled = host.setTimeout(pollingInterval === PollingInterval.Low ? pollLowPollingIntervalQueue : pollPollingIntervalQueue, pollingInterval, pollingIntervalQueue(pollingInterval)); + } + function getModifiedTime(fileName) { + return host.getModifiedTime(fileName) || ts.missingFileModifiedTime; + } + } + ts.createDynamicPriorityPollingWatchFile = createDynamicPriorityPollingWatchFile; + /** + * Returns true if file status changed + */ + /*@internal*/ + function onWatchedFileStat(watchedFile, modifiedTime) { + var oldTime = watchedFile.mtime.getTime(); + var newTime = modifiedTime.getTime(); + if (oldTime !== newTime) { + watchedFile.mtime = modifiedTime; + watchedFile.callback(watchedFile.fileName, getFileWatcherEventKind(oldTime, newTime)); + return true; + } + return false; + } + ts.onWatchedFileStat = onWatchedFileStat; + /*@internal*/ + function getFileWatcherEventKind(oldTime, newTime) { + return oldTime === 0 + ? FileWatcherEventKind.Created + : newTime === 0 + ? FileWatcherEventKind.Deleted + : FileWatcherEventKind.Changed; + } + ts.getFileWatcherEventKind = getFileWatcherEventKind; + /** + * Watch the directory recursively using host provided method to watch child directories + * that means if this is recursive watcher, watch the children directories as well + * (eg on OS that dont support recursive watch using fs.watch use fs.watchFile) + */ + /*@internal*/ + function createRecursiveDirectoryWatcher(host) { + var cache = ts.createMap(); + var callbackCache = ts.createMultiMap(); + var filePathComparer = ts.getStringComparer(!host.useCaseSensitiveFileNames); + var toCanonicalFilePath = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); + return createDirectoryWatcher; + /** + * Create the directory watcher for the dirPath. + */ + function createDirectoryWatcher(dirName, callback) { + var dirPath = toCanonicalFilePath(dirName); + var directoryWatcher = cache.get(dirPath); + if (directoryWatcher) { + directoryWatcher.refCount++; + } + else { + directoryWatcher = { + watcher: host.watchDirectory(dirName, function (fileName) { + // Call the actual callback + callbackCache.forEach(function (callbacks, rootDirName) { + if (rootDirName === dirPath || (ts.startsWith(dirPath, rootDirName) && dirPath[rootDirName.length] === ts.directorySeparator)) { + callbacks.forEach(function (callback) { return callback(fileName); }); + } + }); + // Iterate through existing children and update the watches if needed + updateChildWatches(dirName, dirPath); + }), + refCount: 1, + childWatches: ts.emptyArray + }; + cache.set(dirPath, directoryWatcher); + updateChildWatches(dirName, dirPath); + } + if (callback) { + callbackCache.add(dirPath, callback); + } + return { + dirName: dirName, + close: function () { + var directoryWatcher = ts.Debug.assertDefined(cache.get(dirPath)); + if (callback) + callbackCache.remove(dirPath, callback); + directoryWatcher.refCount--; + if (directoryWatcher.refCount) + return; + cache.delete(dirPath); + ts.closeFileWatcherOf(directoryWatcher); + directoryWatcher.childWatches.forEach(ts.closeFileWatcher); + } + }; + } + function updateChildWatches(dirName, dirPath) { + // Iterate through existing children and update the watches if needed + var parentWatcher = cache.get(dirPath); + if (parentWatcher) { + parentWatcher.childWatches = watchChildDirectories(dirName, parentWatcher.childWatches); + } + } + /** + * Watch the directories in the parentDir + */ + function watchChildDirectories(parentDir, existingChildWatches) { + var newChildWatches; + ts.enumerateInsertsAndDeletes(host.directoryExists(parentDir) ? ts.mapDefined(host.getAccessibleSortedChildDirectories(parentDir), function (child) { + var childFullName = ts.getNormalizedAbsolutePath(child, parentDir); + // Filter our the symbolic link directories since those arent included in recursive watch + // which is same behaviour when recursive: true is passed to fs.watch + return filePathComparer(childFullName, ts.normalizePath(host.realpath(childFullName))) === 0 /* EqualTo */ ? childFullName : undefined; + }) : ts.emptyArray, existingChildWatches, function (child, childWatcher) { return filePathComparer(child, childWatcher.dirName); }, createAndAddChildDirectoryWatcher, ts.closeFileWatcher, addChildDirectoryWatcher); + return newChildWatches || ts.emptyArray; + /** + * Create new childDirectoryWatcher and add it to the new ChildDirectoryWatcher list + */ + function createAndAddChildDirectoryWatcher(childName) { + var result = createDirectoryWatcher(childName); + addChildDirectoryWatcher(result); + } + /** + * Add child directory watcher to the new ChildDirectoryWatcher list + */ + function addChildDirectoryWatcher(childWatcher) { + (newChildWatches || (newChildWatches = [])).push(childWatcher); + } + } + } + ts.createRecursiveDirectoryWatcher = createRecursiveDirectoryWatcher; + function getNodeMajorVersion() { + if (typeof process === "undefined") { + return undefined; + } + var version = process.version; + if (!version) { + return undefined; + } + var dot = version.indexOf("."); + if (dot === -1) { + return undefined; + } + return parseInt(version.substring(1, dot)); + } + ts.getNodeMajorVersion = getNodeMajorVersion; + // TODO: GH#18217 this is used as if it's certainly defined in many places. + ts.sys = (function () { + // NodeJS detects "\uFEFF" at the start of the string and *replaces* it with the actual + // byte order mark from the specified encoding. Using any other byte order mark does + // not actually work. + var byteOrderMarkIndicator = "\uFEFF"; + function getNodeSystem() { + var _fs = require("fs"); + var _path = require("path"); + var _os = require("os"); + // crypto can be absent on reduced node installations + var _crypto; + try { + _crypto = require("crypto"); + } + catch (_a) { + _crypto = undefined; + } + var Buffer = require("buffer").Buffer; + var nodeVersion = getNodeMajorVersion(); + var isNode4OrLater = nodeVersion >= 4; + var platform = _os.platform(); + var useCaseSensitiveFileNames = isFileSystemCaseSensitive(); + var FileSystemEntryKind; + (function (FileSystemEntryKind) { + FileSystemEntryKind[FileSystemEntryKind["File"] = 0] = "File"; + FileSystemEntryKind[FileSystemEntryKind["Directory"] = 1] = "Directory"; + })(FileSystemEntryKind || (FileSystemEntryKind = {})); + var useNonPollingWatchers = process.env.TSC_NONPOLLING_WATCHER; + var tscWatchFile = process.env.TSC_WATCHFILE; + var tscWatchDirectory = process.env.TSC_WATCHDIRECTORY; + var dynamicPollingWatchFile; + var nodeSystem = { + args: process.argv.slice(2), + newLine: _os.EOL, + useCaseSensitiveFileNames: useCaseSensitiveFileNames, + write: function (s) { + process.stdout.write(s); + }, + writeOutputIsTTY: function () { + return process.stdout.isTTY; + }, + readFile: readFile, + writeFile: writeFile, + watchFile: getWatchFile(), + watchDirectory: getWatchDirectory(), + resolvePath: function (path) { return _path.resolve(path); }, + fileExists: fileExists, + directoryExists: directoryExists, + createDirectory: function (directoryName) { + if (!nodeSystem.directoryExists(directoryName)) { + _fs.mkdirSync(directoryName); + } + }, + getExecutingFilePath: function () { + return __filename; + }, + getCurrentDirectory: function () { + return process.cwd(); + }, + getDirectories: getDirectories, + getEnvironmentVariable: function (name) { + return process.env[name] || ""; + }, + readDirectory: readDirectory, + getModifiedTime: getModifiedTime, + setModifiedTime: setModifiedTime, + deleteFile: deleteFile, + createHash: _crypto ? createMD5HashUsingNativeCrypto : generateDjb2Hash, + createSHA256Hash: _crypto ? createSHA256Hash : undefined, + getMemoryUsage: function () { + if (global.gc) { + global.gc(); + } + return process.memoryUsage().heapUsed; + }, + getFileSize: function (path) { + try { + var stat = _fs.statSync(path); + if (stat.isFile()) { + return stat.size; + } + } + catch ( /*ignore*/_a) { /*ignore*/ } + return 0; + }, + exit: function (exitCode) { + process.exit(exitCode); + }, + realpath: realpath, + debugMode: ts.some(process.execArgv, function (arg) { return /^--(inspect|debug)(-brk)?(=\d+)?$/i.test(arg); }), + tryEnableSourceMapsForHost: function () { + try { + require("source-map-support").install(); + } + catch (_a) { + // Could not enable source maps. + } + }, + setTimeout: setTimeout, + clearTimeout: clearTimeout, + clearScreen: function () { + process.stdout.write("\x1Bc"); + }, + setBlocking: function () { + if (process.stdout && process.stdout._handle && process.stdout._handle.setBlocking) { + process.stdout._handle.setBlocking(true); + } + }, + bufferFrom: bufferFrom, + base64decode: function (input) { return bufferFrom(input, "base64").toString("utf8"); }, + base64encode: function (input) { return bufferFrom(input).toString("base64"); }, + }; + return nodeSystem; + function bufferFrom(input, encoding) { + // See https://github.com/Microsoft/TypeScript/issues/25652 + return Buffer.from && Buffer.from !== Int8Array.from + ? Buffer.from(input, encoding) + : new Buffer(input, encoding); + } + function isFileSystemCaseSensitive() { + // win32\win64 are case insensitive platforms + if (platform === "win32" || platform === "win64") { + return false; + } + // If this file exists under a different case, we must be case-insensitve. + return !fileExists(swapCase(__filename)); + } + /** Convert all lowercase chars to uppercase, and vice-versa */ + function swapCase(s) { + return s.replace(/\w/g, function (ch) { + var up = ch.toUpperCase(); + return ch === up ? ch.toLowerCase() : up; + }); + } + function getWatchFile() { + switch (tscWatchFile) { + case "PriorityPollingInterval": + // Use polling interval based on priority when create watch using host.watchFile + return fsWatchFile; + case "DynamicPriorityPolling": + // Use polling interval but change the interval depending on file changes and their default polling interval + return createDynamicPriorityPollingWatchFile({ getModifiedTime: getModifiedTime, setTimeout: setTimeout }); + case "UseFsEvents": + // Use notifications from FS to watch with falling back to fs.watchFile + return watchFileUsingFsWatch; + case "UseFsEventsWithFallbackDynamicPolling": + // Use notifications from FS to watch with falling back to dynamic watch file + dynamicPollingWatchFile = createDynamicPriorityPollingWatchFile({ getModifiedTime: getModifiedTime, setTimeout: setTimeout }); + return createWatchFileUsingDynamicWatchFile(dynamicPollingWatchFile); + case "UseFsEventsOnParentDirectory": + // Use notifications from FS to watch with falling back to fs.watchFile + return createNonPollingWatchFile(); + } + return useNonPollingWatchers ? + createNonPollingWatchFile() : + // Default to do not use polling interval as it is before this experiment branch + function (fileName, callback) { return fsWatchFile(fileName, callback); }; + } + function getWatchDirectory() { + // Node 4.0 `fs.watch` function supports the "recursive" option on both OSX and Windows + // (ref: https://github.com/nodejs/node/pull/2649 and https://github.com/Microsoft/TypeScript/issues/4643) + var fsSupportsRecursive = isNode4OrLater && (process.platform === "win32" || process.platform === "darwin"); + if (fsSupportsRecursive) { + return watchDirectoryUsingFsWatch; + } + var watchDirectory = tscWatchDirectory === "RecursiveDirectoryUsingFsWatchFile" ? + createWatchDirectoryUsing(fsWatchFile) : + tscWatchDirectory === "RecursiveDirectoryUsingDynamicPriorityPolling" ? + createWatchDirectoryUsing(dynamicPollingWatchFile || createDynamicPriorityPollingWatchFile({ getModifiedTime: getModifiedTime, setTimeout: setTimeout })) : + watchDirectoryUsingFsWatch; + var watchDirectoryRecursively = createRecursiveDirectoryWatcher({ + useCaseSensitiveFileNames: useCaseSensitiveFileNames, + directoryExists: directoryExists, + getAccessibleSortedChildDirectories: function (path) { return getAccessibleFileSystemEntries(path).directories; }, + watchDirectory: watchDirectory, + realpath: realpath + }); + return function (directoryName, callback, recursive) { + if (recursive) { + return watchDirectoryRecursively(directoryName, callback); + } + return watchDirectory(directoryName, callback); + }; + } + function createNonPollingWatchFile() { + // One file can have multiple watchers + var fileWatcherCallbacks = ts.createMultiMap(); + var dirWatchers = ts.createMap(); + var toCanonicalName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); + return nonPollingWatchFile; + function nonPollingWatchFile(fileName, callback) { + var filePath = toCanonicalName(fileName); + fileWatcherCallbacks.add(filePath, callback); + var dirPath = ts.getDirectoryPath(filePath) || "."; + var watcher = dirWatchers.get(dirPath) || createDirectoryWatcher(ts.getDirectoryPath(fileName) || ".", dirPath); + watcher.referenceCount++; + return { + close: function () { + if (watcher.referenceCount === 1) { + watcher.close(); + dirWatchers.delete(dirPath); + } + else { + watcher.referenceCount--; + } + fileWatcherCallbacks.remove(filePath, callback); + } + }; + } + function createDirectoryWatcher(dirName, dirPath) { + var watcher = fsWatchDirectory(dirName, function (_eventName, relativeFileName) { + // When files are deleted from disk, the triggered "rename" event would have a relativefileName of "undefined" + if (!ts.isString(relativeFileName)) { + return; + } + var fileName = ts.getNormalizedAbsolutePath(relativeFileName, dirName); + // Some applications save a working file via rename operations + var callbacks = fileName && fileWatcherCallbacks.get(toCanonicalName(fileName)); + if (callbacks) { + for (var _i = 0, callbacks_1 = callbacks; _i < callbacks_1.length; _i++) { + var fileCallback = callbacks_1[_i]; + fileCallback(fileName, FileWatcherEventKind.Changed); + } + } + }); + watcher.referenceCount = 0; + dirWatchers.set(dirPath, watcher); + return watcher; + } + } + function fsWatchFile(fileName, callback, pollingInterval) { + _fs.watchFile(fileName, { persistent: true, interval: pollingInterval || 250 }, fileChanged); + var eventKind; + return { + close: function () { return _fs.unwatchFile(fileName, fileChanged); } + }; + function fileChanged(curr, prev) { + // previous event kind check is to ensure we recongnize the file as previously also missing when it is restored or renamed twice (that is it disappears and reappears) + // In such case, prevTime returned is same as prev time of event when file was deleted as per node documentation + var isPreviouslyDeleted = +prev.mtime === 0 || eventKind === FileWatcherEventKind.Deleted; + if (+curr.mtime === 0) { + if (isPreviouslyDeleted) { + // Already deleted file, no need to callback again + return; + } + eventKind = FileWatcherEventKind.Deleted; + } + else if (isPreviouslyDeleted) { + eventKind = FileWatcherEventKind.Created; + } + // If there is no change in modified time, ignore the event + else if (+curr.mtime === +prev.mtime) { + return; + } + else { + // File changed + eventKind = FileWatcherEventKind.Changed; + } + callback(fileName, eventKind); + } + } + function createFileWatcherCallback(callback) { + return function (_fileName, eventKind) { return callback(eventKind === FileWatcherEventKind.Changed ? "change" : "rename", ""); }; + } + function createFsWatchCallbackForFileWatcherCallback(fileName, callback) { + return function (eventName) { + if (eventName === "rename") { + callback(fileName, fileExists(fileName) ? FileWatcherEventKind.Created : FileWatcherEventKind.Deleted); + } + else { + // Change + callback(fileName, FileWatcherEventKind.Changed); + } + }; + } + function createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback) { + return function (eventName, relativeFileName) { + // In watchDirectory we only care about adding and removing files (when event name is + // "rename"); changes made within files are handled by corresponding fileWatchers (when + // event name is "change") + if (eventName === "rename") { + // When deleting a file, the passed baseFileName is null + callback(!relativeFileName ? directoryName : ts.normalizePath(ts.combinePaths(directoryName, relativeFileName))); + } + }; + } + function fsWatch(fileOrDirectory, entryKind, callback, recursive, fallbackPollingWatchFile, pollingInterval) { + var options; + /** Watcher for the file system entry depending on whether it is missing or present */ + var watcher = !fileSystemEntryExists(fileOrDirectory, entryKind) ? + watchMissingFileSystemEntry() : + watchPresentFileSystemEntry(); + return { + close: function () { + // Close the watcher (either existing file system entry watcher or missing file system entry watcher) + watcher.close(); + watcher = undefined; + } + }; + /** + * Invoke the callback with rename and update the watcher if not closed + * @param createWatcher + */ + function invokeCallbackAndUpdateWatcher(createWatcher) { + // Call the callback for current directory + callback("rename", ""); + // If watcher is not closed, update it + if (watcher) { + watcher.close(); + watcher = createWatcher(); + } + } + /** + * Watch the file or directory that is currently present + * and when the watched file or directory is deleted, switch to missing file system entry watcher + */ + function watchPresentFileSystemEntry() { + // Node 4.0 `fs.watch` function supports the "recursive" option on both OSX and Windows + // (ref: https://github.com/nodejs/node/pull/2649 and https://github.com/Microsoft/TypeScript/issues/4643) + if (options === undefined) { + if (isNode4OrLater && (process.platform === "win32" || process.platform === "darwin")) { + options = { persistent: true, recursive: !!recursive }; + } + else { + options = { persistent: true }; + } + } + try { + var presentWatcher = _fs.watch(fileOrDirectory, options, callback); + // Watch the missing file or directory or error + presentWatcher.on("error", function () { return invokeCallbackAndUpdateWatcher(watchMissingFileSystemEntry); }); + return presentWatcher; + } + catch (e) { + // Catch the exception and use polling instead + // Eg. on linux the number of watches are limited and one could easily exhaust watches and the exception ENOSPC is thrown when creating watcher at that point + // so instead of throwing error, use fs.watchFile + return watchPresentFileSystemEntryWithFsWatchFile(); + } + } + /** + * Watch the file or directory using fs.watchFile since fs.watch threw exception + * Eg. on linux the number of watches are limited and one could easily exhaust watches and the exception ENOSPC is thrown when creating watcher at that point + */ + function watchPresentFileSystemEntryWithFsWatchFile() { + return fallbackPollingWatchFile(fileOrDirectory, createFileWatcherCallback(callback), pollingInterval); + } + /** + * Watch the file or directory that is missing + * and switch to existing file or directory when the missing filesystem entry is created + */ + function watchMissingFileSystemEntry() { + return fallbackPollingWatchFile(fileOrDirectory, function (_fileName, eventKind) { + if (eventKind === FileWatcherEventKind.Created && fileSystemEntryExists(fileOrDirectory, entryKind)) { + // Call the callback for current file or directory + // For now it could be callback for the inner directory creation, + // but just return current directory, better than current no-op + invokeCallbackAndUpdateWatcher(watchPresentFileSystemEntry); + } + }, pollingInterval); + } + } + function watchFileUsingFsWatch(fileName, callback, pollingInterval) { + return fsWatch(fileName, 0 /* File */, createFsWatchCallbackForFileWatcherCallback(fileName, callback), /*recursive*/ false, fsWatchFile, pollingInterval); + } + function createWatchFileUsingDynamicWatchFile(watchFile) { + return function (fileName, callback, pollingInterval) { return fsWatch(fileName, 0 /* File */, createFsWatchCallbackForFileWatcherCallback(fileName, callback), /*recursive*/ false, watchFile, pollingInterval); }; + } + function fsWatchDirectory(directoryName, callback, recursive) { + return fsWatch(directoryName, 1 /* Directory */, callback, !!recursive, fsWatchFile); + } + function watchDirectoryUsingFsWatch(directoryName, callback, recursive) { + return fsWatchDirectory(directoryName, createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback), recursive); + } + function createWatchDirectoryUsing(fsWatchFile) { + return function (directoryName, callback) { return fsWatchFile(directoryName, function () { return callback(directoryName); }, PollingInterval.Medium); }; + } + function readFile(fileName, _encoding) { + if (!fileExists(fileName)) { + return undefined; + } + var buffer = _fs.readFileSync(fileName); + var len = buffer.length; + if (len >= 2 && buffer[0] === 0xFE && buffer[1] === 0xFF) { + // Big endian UTF-16 byte order mark detected. Since big endian is not supported by node.js, + // flip all byte pairs and treat as little endian. + len &= ~1; // Round down to a multiple of 2 + for (var i = 0; i < len; i += 2) { + var temp = buffer[i]; + buffer[i] = buffer[i + 1]; + buffer[i + 1] = temp; + } + return buffer.toString("utf16le", 2); + } + if (len >= 2 && buffer[0] === 0xFF && buffer[1] === 0xFE) { + // Little endian UTF-16 byte order mark detected + return buffer.toString("utf16le", 2); + } + if (len >= 3 && buffer[0] === 0xEF && buffer[1] === 0xBB && buffer[2] === 0xBF) { + // UTF-8 byte order mark detected + return buffer.toString("utf8", 3); + } + // Default is UTF-8 with no byte order mark + return buffer.toString("utf8"); + } + function writeFile(fileName, data, writeByteOrderMark) { + // If a BOM is required, emit one + if (writeByteOrderMark) { + data = byteOrderMarkIndicator + data; + } + var fd; + try { + fd = _fs.openSync(fileName, "w"); + _fs.writeSync(fd, data, /*position*/ undefined, "utf8"); + } + finally { + if (fd !== undefined) { + _fs.closeSync(fd); + } + } + } + function getAccessibleFileSystemEntries(path) { + try { + var entries = _fs.readdirSync(path || ".").sort(); + var files = []; + var directories = []; + for (var _i = 0, entries_2 = entries; _i < entries_2.length; _i++) { + var entry = entries_2[_i]; + // This is necessary because on some file system node fails to exclude + // "." and "..". See https://github.com/nodejs/node/issues/4002 + if (entry === "." || entry === "..") { + continue; + } + var name = ts.combinePaths(path, entry); + var stat = void 0; + try { + stat = _fs.statSync(name); + } + catch (e) { + continue; + } + if (stat.isFile()) { + files.push(entry); + } + else if (stat.isDirectory()) { + directories.push(entry); + } + } + return { files: files, directories: directories }; + } + catch (e) { + return ts.emptyFileSystemEntries; + } + } + function readDirectory(path, extensions, excludes, includes, depth) { + return ts.matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, process.cwd(), depth, getAccessibleFileSystemEntries); + } + function fileSystemEntryExists(path, entryKind) { + try { + var stat = _fs.statSync(path); + switch (entryKind) { + case 0 /* File */: return stat.isFile(); + case 1 /* Directory */: return stat.isDirectory(); + default: return false; + } + } + catch (e) { + return false; + } + } + function fileExists(path) { + return fileSystemEntryExists(path, 0 /* File */); + } + function directoryExists(path) { + return fileSystemEntryExists(path, 1 /* Directory */); + } + function getDirectories(path) { + return ts.filter(_fs.readdirSync(path), function (dir) { return fileSystemEntryExists(ts.combinePaths(path, dir), 1 /* Directory */); }); + } + function realpath(path) { + try { + return _fs.realpathSync(path); + } + catch (_a) { + return path; + } + } + function getModifiedTime(path) { + try { + return _fs.statSync(path).mtime; + } + catch (e) { + return undefined; + } + } + function setModifiedTime(path, time) { + try { + _fs.utimesSync(path, time, time); + } + catch (e) { + return; + } + } + function deleteFile(path) { + try { + return _fs.unlinkSync(path); + } + catch (e) { + return; + } + } + /** + * djb2 hashing algorithm + * http://www.cse.yorku.ca/~oz/hash.html + */ + function generateDjb2Hash(data) { + var chars = data.split("").map(function (str) { return str.charCodeAt(0); }); + return "" + chars.reduce(function (prev, curr) { return ((prev << 5) + prev) + curr; }, 5381); + } + function createMD5HashUsingNativeCrypto(data) { + var hash = _crypto.createHash("md5"); + hash.update(data); + return hash.digest("hex"); + } + function createSHA256Hash(data) { + var hash = _crypto.createHash("sha256"); + hash.update(data); + return hash.digest("hex"); + } + } + function getChakraSystem() { + var realpath = ChakraHost.realpath && (function (path) { return ChakraHost.realpath(path); }); + return { + newLine: ChakraHost.newLine || "\r\n", + args: ChakraHost.args, + useCaseSensitiveFileNames: !!ChakraHost.useCaseSensitiveFileNames, + write: ChakraHost.echo, + readFile: function (path, _encoding) { + // encoding is automatically handled by the implementation in ChakraHost + return ChakraHost.readFile(path); + }, + writeFile: function (path, data, writeByteOrderMark) { + // If a BOM is required, emit one + if (writeByteOrderMark) { + data = byteOrderMarkIndicator + data; + } + ChakraHost.writeFile(path, data); + }, + resolvePath: ChakraHost.resolvePath, + fileExists: ChakraHost.fileExists, + deleteFile: ChakraHost.deleteFile, + getModifiedTime: ChakraHost.getModifiedTime, + setModifiedTime: ChakraHost.setModifiedTime, + directoryExists: ChakraHost.directoryExists, + createDirectory: ChakraHost.createDirectory, + getExecutingFilePath: function () { return ChakraHost.executingFile; }, + getCurrentDirectory: function () { return ChakraHost.currentDirectory; }, + getDirectories: ChakraHost.getDirectories, + getEnvironmentVariable: ChakraHost.getEnvironmentVariable || (function () { return ""; }), + readDirectory: function (path, extensions, excludes, includes, _depth) { + var pattern = ts.getFileMatcherPatterns(path, excludes, includes, !!ChakraHost.useCaseSensitiveFileNames, ChakraHost.currentDirectory); + return ChakraHost.readDirectory(path, extensions, pattern.basePaths, pattern.excludePattern, pattern.includeFilePattern, pattern.includeDirectoryPattern); + }, + exit: ChakraHost.quit, + realpath: realpath + }; + } + function recursiveCreateDirectory(directoryPath, sys) { + var basePath = ts.getDirectoryPath(directoryPath); + var shouldCreateParent = basePath !== "" && directoryPath !== basePath && !sys.directoryExists(basePath); + if (shouldCreateParent) { + recursiveCreateDirectory(basePath, sys); + } + if (shouldCreateParent || !sys.directoryExists(directoryPath)) { + sys.createDirectory(directoryPath); + } + } + var sys; + if (typeof ChakraHost !== "undefined") { + sys = getChakraSystem(); + } + else if (typeof process !== "undefined" && process.nextTick && !process.browser && typeof require !== "undefined") { + // process and process.nextTick checks if current environment is node-like + // process.browser check excludes webpack and browserify + sys = getNodeSystem(); + } + if (sys) { + // patch writefile to create folder before writing the file + var originalWriteFile_1 = sys.writeFile; + sys.writeFile = function (path, data, writeBom) { + var directoryPath = ts.getDirectoryPath(ts.normalizeSlashes(path)); + if (directoryPath && !sys.directoryExists(directoryPath)) { + recursiveCreateDirectory(directoryPath, sys); + } + originalWriteFile_1.call(sys, path, data, writeBom); + }; + } + return sys; + })(); + if (ts.sys && ts.sys.getEnvironmentVariable) { + setCustomPollingValues(ts.sys); + ts.Debug.currentAssertionLevel = /^development$/i.test(ts.sys.getEnvironmentVariable("NODE_ENV")) + ? 1 /* Normal */ + : 0 /* None */; + } + if (ts.sys && ts.sys.debugMode) { + ts.Debug.isDebugging = true; + } +})(ts || (ts = {})); +// +// generated from './diagnosticInformationMap.generated.ts' by 'src/compiler' +/* @internal */ +var ts; +(function (ts) { + function diag(code, category, key, message, reportsUnnecessary) { + return { code: code, category: category, key: key, message: message, reportsUnnecessary: reportsUnnecessary }; + } + // tslint:disable-next-line variable-name + ts.Diagnostics = { + Unterminated_string_literal: diag(1002, ts.DiagnosticCategory.Error, "Unterminated_string_literal_1002", "Unterminated string literal."), + Identifier_expected: diag(1003, ts.DiagnosticCategory.Error, "Identifier_expected_1003", "Identifier expected."), + _0_expected: diag(1005, ts.DiagnosticCategory.Error, "_0_expected_1005", "'{0}' expected."), + A_file_cannot_have_a_reference_to_itself: diag(1006, ts.DiagnosticCategory.Error, "A_file_cannot_have_a_reference_to_itself_1006", "A file cannot have a reference to itself."), + Trailing_comma_not_allowed: diag(1009, ts.DiagnosticCategory.Error, "Trailing_comma_not_allowed_1009", "Trailing comma not allowed."), + Asterisk_Slash_expected: diag(1010, ts.DiagnosticCategory.Error, "Asterisk_Slash_expected_1010", "'*/' expected."), + An_element_access_expression_should_take_an_argument: diag(1011, ts.DiagnosticCategory.Error, "An_element_access_expression_should_take_an_argument_1011", "An element access expression should take an argument."), + Unexpected_token: diag(1012, ts.DiagnosticCategory.Error, "Unexpected_token_1012", "Unexpected token."), + A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma: diag(1013, ts.DiagnosticCategory.Error, "A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma_1013", "A rest parameter or binding pattern may not have a trailing comma."), + A_rest_parameter_must_be_last_in_a_parameter_list: diag(1014, ts.DiagnosticCategory.Error, "A_rest_parameter_must_be_last_in_a_parameter_list_1014", "A rest parameter must be last in a parameter list."), + Parameter_cannot_have_question_mark_and_initializer: diag(1015, ts.DiagnosticCategory.Error, "Parameter_cannot_have_question_mark_and_initializer_1015", "Parameter cannot have question mark and initializer."), + A_required_parameter_cannot_follow_an_optional_parameter: diag(1016, ts.DiagnosticCategory.Error, "A_required_parameter_cannot_follow_an_optional_parameter_1016", "A required parameter cannot follow an optional parameter."), + An_index_signature_cannot_have_a_rest_parameter: diag(1017, ts.DiagnosticCategory.Error, "An_index_signature_cannot_have_a_rest_parameter_1017", "An index signature cannot have a rest parameter."), + An_index_signature_parameter_cannot_have_an_accessibility_modifier: diag(1018, ts.DiagnosticCategory.Error, "An_index_signature_parameter_cannot_have_an_accessibility_modifier_1018", "An index signature parameter cannot have an accessibility modifier."), + An_index_signature_parameter_cannot_have_a_question_mark: diag(1019, ts.DiagnosticCategory.Error, "An_index_signature_parameter_cannot_have_a_question_mark_1019", "An index signature parameter cannot have a question mark."), + An_index_signature_parameter_cannot_have_an_initializer: diag(1020, ts.DiagnosticCategory.Error, "An_index_signature_parameter_cannot_have_an_initializer_1020", "An index signature parameter cannot have an initializer."), + An_index_signature_must_have_a_type_annotation: diag(1021, ts.DiagnosticCategory.Error, "An_index_signature_must_have_a_type_annotation_1021", "An index signature must have a type annotation."), + An_index_signature_parameter_must_have_a_type_annotation: diag(1022, ts.DiagnosticCategory.Error, "An_index_signature_parameter_must_have_a_type_annotation_1022", "An index signature parameter must have a type annotation."), + An_index_signature_parameter_type_must_be_string_or_number: diag(1023, ts.DiagnosticCategory.Error, "An_index_signature_parameter_type_must_be_string_or_number_1023", "An index signature parameter type must be 'string' or 'number'."), + readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature: diag(1024, ts.DiagnosticCategory.Error, "readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024", "'readonly' modifier can only appear on a property declaration or index signature."), + Accessibility_modifier_already_seen: diag(1028, ts.DiagnosticCategory.Error, "Accessibility_modifier_already_seen_1028", "Accessibility modifier already seen."), + _0_modifier_must_precede_1_modifier: diag(1029, ts.DiagnosticCategory.Error, "_0_modifier_must_precede_1_modifier_1029", "'{0}' modifier must precede '{1}' modifier."), + _0_modifier_already_seen: diag(1030, ts.DiagnosticCategory.Error, "_0_modifier_already_seen_1030", "'{0}' modifier already seen."), + _0_modifier_cannot_appear_on_a_class_element: diag(1031, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_a_class_element_1031", "'{0}' modifier cannot appear on a class element."), + super_must_be_followed_by_an_argument_list_or_member_access: diag(1034, ts.DiagnosticCategory.Error, "super_must_be_followed_by_an_argument_list_or_member_access_1034", "'super' must be followed by an argument list or member access."), + Only_ambient_modules_can_use_quoted_names: diag(1035, ts.DiagnosticCategory.Error, "Only_ambient_modules_can_use_quoted_names_1035", "Only ambient modules can use quoted names."), + Statements_are_not_allowed_in_ambient_contexts: diag(1036, ts.DiagnosticCategory.Error, "Statements_are_not_allowed_in_ambient_contexts_1036", "Statements are not allowed in ambient contexts."), + A_declare_modifier_cannot_be_used_in_an_already_ambient_context: diag(1038, ts.DiagnosticCategory.Error, "A_declare_modifier_cannot_be_used_in_an_already_ambient_context_1038", "A 'declare' modifier cannot be used in an already ambient context."), + Initializers_are_not_allowed_in_ambient_contexts: diag(1039, ts.DiagnosticCategory.Error, "Initializers_are_not_allowed_in_ambient_contexts_1039", "Initializers are not allowed in ambient contexts."), + _0_modifier_cannot_be_used_in_an_ambient_context: diag(1040, ts.DiagnosticCategory.Error, "_0_modifier_cannot_be_used_in_an_ambient_context_1040", "'{0}' modifier cannot be used in an ambient context."), + _0_modifier_cannot_be_used_with_a_class_declaration: diag(1041, ts.DiagnosticCategory.Error, "_0_modifier_cannot_be_used_with_a_class_declaration_1041", "'{0}' modifier cannot be used with a class declaration."), + _0_modifier_cannot_be_used_here: diag(1042, ts.DiagnosticCategory.Error, "_0_modifier_cannot_be_used_here_1042", "'{0}' modifier cannot be used here."), + _0_modifier_cannot_appear_on_a_data_property: diag(1043, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_a_data_property_1043", "'{0}' modifier cannot appear on a data property."), + _0_modifier_cannot_appear_on_a_module_or_namespace_element: diag(1044, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_a_module_or_namespace_element_1044", "'{0}' modifier cannot appear on a module or namespace element."), + A_0_modifier_cannot_be_used_with_an_interface_declaration: diag(1045, ts.DiagnosticCategory.Error, "A_0_modifier_cannot_be_used_with_an_interface_declaration_1045", "A '{0}' modifier cannot be used with an interface declaration."), + A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file: diag(1046, ts.DiagnosticCategory.Error, "A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file_1046", "A 'declare' modifier is required for a top level declaration in a .d.ts file."), + A_rest_parameter_cannot_be_optional: diag(1047, ts.DiagnosticCategory.Error, "A_rest_parameter_cannot_be_optional_1047", "A rest parameter cannot be optional."), + A_rest_parameter_cannot_have_an_initializer: diag(1048, ts.DiagnosticCategory.Error, "A_rest_parameter_cannot_have_an_initializer_1048", "A rest parameter cannot have an initializer."), + A_set_accessor_must_have_exactly_one_parameter: diag(1049, ts.DiagnosticCategory.Error, "A_set_accessor_must_have_exactly_one_parameter_1049", "A 'set' accessor must have exactly one parameter."), + A_set_accessor_cannot_have_an_optional_parameter: diag(1051, ts.DiagnosticCategory.Error, "A_set_accessor_cannot_have_an_optional_parameter_1051", "A 'set' accessor cannot have an optional parameter."), + A_set_accessor_parameter_cannot_have_an_initializer: diag(1052, ts.DiagnosticCategory.Error, "A_set_accessor_parameter_cannot_have_an_initializer_1052", "A 'set' accessor parameter cannot have an initializer."), + A_set_accessor_cannot_have_rest_parameter: diag(1053, ts.DiagnosticCategory.Error, "A_set_accessor_cannot_have_rest_parameter_1053", "A 'set' accessor cannot have rest parameter."), + A_get_accessor_cannot_have_parameters: diag(1054, ts.DiagnosticCategory.Error, "A_get_accessor_cannot_have_parameters_1054", "A 'get' accessor cannot have parameters."), + Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value: diag(1055, ts.DiagnosticCategory.Error, "Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Prom_1055", "Type '{0}' is not a valid async function return type in ES5/ES3 because it does not refer to a Promise-compatible constructor value."), + Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher: diag(1056, ts.DiagnosticCategory.Error, "Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher_1056", "Accessors are only available when targeting ECMAScript 5 and higher."), + An_async_function_or_method_must_have_a_valid_awaitable_return_type: diag(1057, ts.DiagnosticCategory.Error, "An_async_function_or_method_must_have_a_valid_awaitable_return_type_1057", "An async function or method must have a valid awaitable return type."), + The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1058, ts.DiagnosticCategory.Error, "The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_t_1058", "The return type of an async function must either be a valid promise or must not contain a callable 'then' member."), + A_promise_must_have_a_then_method: diag(1059, ts.DiagnosticCategory.Error, "A_promise_must_have_a_then_method_1059", "A promise must have a 'then' method."), + The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback: diag(1060, ts.DiagnosticCategory.Error, "The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback_1060", "The first parameter of the 'then' method of a promise must be a callback."), + Enum_member_must_have_initializer: diag(1061, ts.DiagnosticCategory.Error, "Enum_member_must_have_initializer_1061", "Enum member must have initializer."), + Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method: diag(1062, ts.DiagnosticCategory.Error, "Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method_1062", "Type is referenced directly or indirectly in the fulfillment callback of its own 'then' method."), + An_export_assignment_cannot_be_used_in_a_namespace: diag(1063, ts.DiagnosticCategory.Error, "An_export_assignment_cannot_be_used_in_a_namespace_1063", "An export assignment cannot be used in a namespace."), + The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type: diag(1064, ts.DiagnosticCategory.Error, "The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_1064", "The return type of an async function or method must be the global Promise type."), + In_ambient_enum_declarations_member_initializer_must_be_constant_expression: diag(1066, ts.DiagnosticCategory.Error, "In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066", "In ambient enum declarations member initializer must be constant expression."), + Unexpected_token_A_constructor_method_accessor_or_property_was_expected: diag(1068, ts.DiagnosticCategory.Error, "Unexpected_token_A_constructor_method_accessor_or_property_was_expected_1068", "Unexpected token. A constructor, method, accessor, or property was expected."), + Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces: diag(1069, ts.DiagnosticCategory.Error, "Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces_1069", "Unexpected token. A type parameter name was expected without curly braces."), + _0_modifier_cannot_appear_on_a_type_member: diag(1070, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_a_type_member_1070", "'{0}' modifier cannot appear on a type member."), + _0_modifier_cannot_appear_on_an_index_signature: diag(1071, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_an_index_signature_1071", "'{0}' modifier cannot appear on an index signature."), + A_0_modifier_cannot_be_used_with_an_import_declaration: diag(1079, ts.DiagnosticCategory.Error, "A_0_modifier_cannot_be_used_with_an_import_declaration_1079", "A '{0}' modifier cannot be used with an import declaration."), + Invalid_reference_directive_syntax: diag(1084, ts.DiagnosticCategory.Error, "Invalid_reference_directive_syntax_1084", "Invalid 'reference' directive syntax."), + Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0: diag(1085, ts.DiagnosticCategory.Error, "Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0_1085", "Octal literals are not available when targeting ECMAScript 5 and higher. Use the syntax '{0}'."), + An_accessor_cannot_be_declared_in_an_ambient_context: diag(1086, ts.DiagnosticCategory.Error, "An_accessor_cannot_be_declared_in_an_ambient_context_1086", "An accessor cannot be declared in an ambient context."), + _0_modifier_cannot_appear_on_a_constructor_declaration: diag(1089, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_a_constructor_declaration_1089", "'{0}' modifier cannot appear on a constructor declaration."), + _0_modifier_cannot_appear_on_a_parameter: diag(1090, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_a_parameter_1090", "'{0}' modifier cannot appear on a parameter."), + Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement: diag(1091, ts.DiagnosticCategory.Error, "Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement_1091", "Only a single variable declaration is allowed in a 'for...in' statement."), + Type_parameters_cannot_appear_on_a_constructor_declaration: diag(1092, ts.DiagnosticCategory.Error, "Type_parameters_cannot_appear_on_a_constructor_declaration_1092", "Type parameters cannot appear on a constructor declaration."), + Type_annotation_cannot_appear_on_a_constructor_declaration: diag(1093, ts.DiagnosticCategory.Error, "Type_annotation_cannot_appear_on_a_constructor_declaration_1093", "Type annotation cannot appear on a constructor declaration."), + An_accessor_cannot_have_type_parameters: diag(1094, ts.DiagnosticCategory.Error, "An_accessor_cannot_have_type_parameters_1094", "An accessor cannot have type parameters."), + A_set_accessor_cannot_have_a_return_type_annotation: diag(1095, ts.DiagnosticCategory.Error, "A_set_accessor_cannot_have_a_return_type_annotation_1095", "A 'set' accessor cannot have a return type annotation."), + An_index_signature_must_have_exactly_one_parameter: diag(1096, ts.DiagnosticCategory.Error, "An_index_signature_must_have_exactly_one_parameter_1096", "An index signature must have exactly one parameter."), + _0_list_cannot_be_empty: diag(1097, ts.DiagnosticCategory.Error, "_0_list_cannot_be_empty_1097", "'{0}' list cannot be empty."), + Type_parameter_list_cannot_be_empty: diag(1098, ts.DiagnosticCategory.Error, "Type_parameter_list_cannot_be_empty_1098", "Type parameter list cannot be empty."), + Type_argument_list_cannot_be_empty: diag(1099, ts.DiagnosticCategory.Error, "Type_argument_list_cannot_be_empty_1099", "Type argument list cannot be empty."), + Invalid_use_of_0_in_strict_mode: diag(1100, ts.DiagnosticCategory.Error, "Invalid_use_of_0_in_strict_mode_1100", "Invalid use of '{0}' in strict mode."), + with_statements_are_not_allowed_in_strict_mode: diag(1101, ts.DiagnosticCategory.Error, "with_statements_are_not_allowed_in_strict_mode_1101", "'with' statements are not allowed in strict mode."), + delete_cannot_be_called_on_an_identifier_in_strict_mode: diag(1102, ts.DiagnosticCategory.Error, "delete_cannot_be_called_on_an_identifier_in_strict_mode_1102", "'delete' cannot be called on an identifier in strict mode."), + A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator: diag(1103, ts.DiagnosticCategory.Error, "A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator_1103", "A 'for-await-of' statement is only allowed within an async function or async generator."), + A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement: diag(1104, ts.DiagnosticCategory.Error, "A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement_1104", "A 'continue' statement can only be used within an enclosing iteration statement."), + A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement: diag(1105, ts.DiagnosticCategory.Error, "A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement_1105", "A 'break' statement can only be used within an enclosing iteration or switch statement."), + Jump_target_cannot_cross_function_boundary: diag(1107, ts.DiagnosticCategory.Error, "Jump_target_cannot_cross_function_boundary_1107", "Jump target cannot cross function boundary."), + A_return_statement_can_only_be_used_within_a_function_body: diag(1108, ts.DiagnosticCategory.Error, "A_return_statement_can_only_be_used_within_a_function_body_1108", "A 'return' statement can only be used within a function body."), + Expression_expected: diag(1109, ts.DiagnosticCategory.Error, "Expression_expected_1109", "Expression expected."), + Type_expected: diag(1110, ts.DiagnosticCategory.Error, "Type_expected_1110", "Type expected."), + A_default_clause_cannot_appear_more_than_once_in_a_switch_statement: diag(1113, ts.DiagnosticCategory.Error, "A_default_clause_cannot_appear_more_than_once_in_a_switch_statement_1113", "A 'default' clause cannot appear more than once in a 'switch' statement."), + Duplicate_label_0: diag(1114, ts.DiagnosticCategory.Error, "Duplicate_label_0_1114", "Duplicate label '{0}'."), + A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement: diag(1115, ts.DiagnosticCategory.Error, "A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement_1115", "A 'continue' statement can only jump to a label of an enclosing iteration statement."), + A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement: diag(1116, ts.DiagnosticCategory.Error, "A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement_1116", "A 'break' statement can only jump to a label of an enclosing statement."), + An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode: diag(1117, ts.DiagnosticCategory.Error, "An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode_1117", "An object literal cannot have multiple properties with the same name in strict mode."), + An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name: diag(1118, ts.DiagnosticCategory.Error, "An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name_1118", "An object literal cannot have multiple get/set accessors with the same name."), + An_object_literal_cannot_have_property_and_accessor_with_the_same_name: diag(1119, ts.DiagnosticCategory.Error, "An_object_literal_cannot_have_property_and_accessor_with_the_same_name_1119", "An object literal cannot have property and accessor with the same name."), + An_export_assignment_cannot_have_modifiers: diag(1120, ts.DiagnosticCategory.Error, "An_export_assignment_cannot_have_modifiers_1120", "An export assignment cannot have modifiers."), + Octal_literals_are_not_allowed_in_strict_mode: diag(1121, ts.DiagnosticCategory.Error, "Octal_literals_are_not_allowed_in_strict_mode_1121", "Octal literals are not allowed in strict mode."), + Variable_declaration_list_cannot_be_empty: diag(1123, ts.DiagnosticCategory.Error, "Variable_declaration_list_cannot_be_empty_1123", "Variable declaration list cannot be empty."), + Digit_expected: diag(1124, ts.DiagnosticCategory.Error, "Digit_expected_1124", "Digit expected."), + Hexadecimal_digit_expected: diag(1125, ts.DiagnosticCategory.Error, "Hexadecimal_digit_expected_1125", "Hexadecimal digit expected."), + Unexpected_end_of_text: diag(1126, ts.DiagnosticCategory.Error, "Unexpected_end_of_text_1126", "Unexpected end of text."), + Invalid_character: diag(1127, ts.DiagnosticCategory.Error, "Invalid_character_1127", "Invalid character."), + Declaration_or_statement_expected: diag(1128, ts.DiagnosticCategory.Error, "Declaration_or_statement_expected_1128", "Declaration or statement expected."), + Statement_expected: diag(1129, ts.DiagnosticCategory.Error, "Statement_expected_1129", "Statement expected."), + case_or_default_expected: diag(1130, ts.DiagnosticCategory.Error, "case_or_default_expected_1130", "'case' or 'default' expected."), + Property_or_signature_expected: diag(1131, ts.DiagnosticCategory.Error, "Property_or_signature_expected_1131", "Property or signature expected."), + Enum_member_expected: diag(1132, ts.DiagnosticCategory.Error, "Enum_member_expected_1132", "Enum member expected."), + Variable_declaration_expected: diag(1134, ts.DiagnosticCategory.Error, "Variable_declaration_expected_1134", "Variable declaration expected."), + Argument_expression_expected: diag(1135, ts.DiagnosticCategory.Error, "Argument_expression_expected_1135", "Argument expression expected."), + Property_assignment_expected: diag(1136, ts.DiagnosticCategory.Error, "Property_assignment_expected_1136", "Property assignment expected."), + Expression_or_comma_expected: diag(1137, ts.DiagnosticCategory.Error, "Expression_or_comma_expected_1137", "Expression or comma expected."), + Parameter_declaration_expected: diag(1138, ts.DiagnosticCategory.Error, "Parameter_declaration_expected_1138", "Parameter declaration expected."), + Type_parameter_declaration_expected: diag(1139, ts.DiagnosticCategory.Error, "Type_parameter_declaration_expected_1139", "Type parameter declaration expected."), + Type_argument_expected: diag(1140, ts.DiagnosticCategory.Error, "Type_argument_expected_1140", "Type argument expected."), + String_literal_expected: diag(1141, ts.DiagnosticCategory.Error, "String_literal_expected_1141", "String literal expected."), + Line_break_not_permitted_here: diag(1142, ts.DiagnosticCategory.Error, "Line_break_not_permitted_here_1142", "Line break not permitted here."), + or_expected: diag(1144, ts.DiagnosticCategory.Error, "or_expected_1144", "'{' or ';' expected."), + Declaration_expected: diag(1146, ts.DiagnosticCategory.Error, "Declaration_expected_1146", "Declaration expected."), + Import_declarations_in_a_namespace_cannot_reference_a_module: diag(1147, ts.DiagnosticCategory.Error, "Import_declarations_in_a_namespace_cannot_reference_a_module_1147", "Import declarations in a namespace cannot reference a module."), + Cannot_use_imports_exports_or_module_augmentations_when_module_is_none: diag(1148, ts.DiagnosticCategory.Error, "Cannot_use_imports_exports_or_module_augmentations_when_module_is_none_1148", "Cannot use imports, exports, or module augmentations when '--module' is 'none'."), + File_name_0_differs_from_already_included_file_name_1_only_in_casing: diag(1149, ts.DiagnosticCategory.Error, "File_name_0_differs_from_already_included_file_name_1_only_in_casing_1149", "File name '{0}' differs from already included file name '{1}' only in casing."), + new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead: diag(1150, ts.DiagnosticCategory.Error, "new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead_1150", "'new T[]' cannot be used to create an array. Use 'new Array()' instead."), + const_declarations_must_be_initialized: diag(1155, ts.DiagnosticCategory.Error, "const_declarations_must_be_initialized_1155", "'const' declarations must be initialized."), + const_declarations_can_only_be_declared_inside_a_block: diag(1156, ts.DiagnosticCategory.Error, "const_declarations_can_only_be_declared_inside_a_block_1156", "'const' declarations can only be declared inside a block."), + let_declarations_can_only_be_declared_inside_a_block: diag(1157, ts.DiagnosticCategory.Error, "let_declarations_can_only_be_declared_inside_a_block_1157", "'let' declarations can only be declared inside a block."), + Unterminated_template_literal: diag(1160, ts.DiagnosticCategory.Error, "Unterminated_template_literal_1160", "Unterminated template literal."), + Unterminated_regular_expression_literal: diag(1161, ts.DiagnosticCategory.Error, "Unterminated_regular_expression_literal_1161", "Unterminated regular expression literal."), + An_object_member_cannot_be_declared_optional: diag(1162, ts.DiagnosticCategory.Error, "An_object_member_cannot_be_declared_optional_1162", "An object member cannot be declared optional."), + A_yield_expression_is_only_allowed_in_a_generator_body: diag(1163, ts.DiagnosticCategory.Error, "A_yield_expression_is_only_allowed_in_a_generator_body_1163", "A 'yield' expression is only allowed in a generator body."), + Computed_property_names_are_not_allowed_in_enums: diag(1164, ts.DiagnosticCategory.Error, "Computed_property_names_are_not_allowed_in_enums_1164", "Computed property names are not allowed in enums."), + A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: diag(1165, ts.DiagnosticCategory.Error, "A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_t_1165", "A computed property name in an ambient context must refer to an expression whose type is a literal type or a 'unique symbol' type."), + A_computed_property_name_in_a_class_property_declaration_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: diag(1166, ts.DiagnosticCategory.Error, "A_computed_property_name_in_a_class_property_declaration_must_refer_to_an_expression_whose_type_is_a_1166", "A computed property name in a class property declaration must refer to an expression whose type is a literal type or a 'unique symbol' type."), + A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: diag(1168, ts.DiagnosticCategory.Error, "A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_ty_1168", "A computed property name in a method overload must refer to an expression whose type is a literal type or a 'unique symbol' type."), + A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: diag(1169, ts.DiagnosticCategory.Error, "A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_1169", "A computed property name in an interface must refer to an expression whose type is a literal type or a 'unique symbol' type."), + A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: diag(1170, ts.DiagnosticCategory.Error, "A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type__1170", "A computed property name in a type literal must refer to an expression whose type is a literal type or a 'unique symbol' type."), + A_comma_expression_is_not_allowed_in_a_computed_property_name: diag(1171, ts.DiagnosticCategory.Error, "A_comma_expression_is_not_allowed_in_a_computed_property_name_1171", "A comma expression is not allowed in a computed property name."), + extends_clause_already_seen: diag(1172, ts.DiagnosticCategory.Error, "extends_clause_already_seen_1172", "'extends' clause already seen."), + extends_clause_must_precede_implements_clause: diag(1173, ts.DiagnosticCategory.Error, "extends_clause_must_precede_implements_clause_1173", "'extends' clause must precede 'implements' clause."), + Classes_can_only_extend_a_single_class: diag(1174, ts.DiagnosticCategory.Error, "Classes_can_only_extend_a_single_class_1174", "Classes can only extend a single class."), + implements_clause_already_seen: diag(1175, ts.DiagnosticCategory.Error, "implements_clause_already_seen_1175", "'implements' clause already seen."), + Interface_declaration_cannot_have_implements_clause: diag(1176, ts.DiagnosticCategory.Error, "Interface_declaration_cannot_have_implements_clause_1176", "Interface declaration cannot have 'implements' clause."), + Binary_digit_expected: diag(1177, ts.DiagnosticCategory.Error, "Binary_digit_expected_1177", "Binary digit expected."), + Octal_digit_expected: diag(1178, ts.DiagnosticCategory.Error, "Octal_digit_expected_1178", "Octal digit expected."), + Unexpected_token_expected: diag(1179, ts.DiagnosticCategory.Error, "Unexpected_token_expected_1179", "Unexpected token. '{' expected."), + Property_destructuring_pattern_expected: diag(1180, ts.DiagnosticCategory.Error, "Property_destructuring_pattern_expected_1180", "Property destructuring pattern expected."), + Array_element_destructuring_pattern_expected: diag(1181, ts.DiagnosticCategory.Error, "Array_element_destructuring_pattern_expected_1181", "Array element destructuring pattern expected."), + A_destructuring_declaration_must_have_an_initializer: diag(1182, ts.DiagnosticCategory.Error, "A_destructuring_declaration_must_have_an_initializer_1182", "A destructuring declaration must have an initializer."), + An_implementation_cannot_be_declared_in_ambient_contexts: diag(1183, ts.DiagnosticCategory.Error, "An_implementation_cannot_be_declared_in_ambient_contexts_1183", "An implementation cannot be declared in ambient contexts."), + Modifiers_cannot_appear_here: diag(1184, ts.DiagnosticCategory.Error, "Modifiers_cannot_appear_here_1184", "Modifiers cannot appear here."), + Merge_conflict_marker_encountered: diag(1185, ts.DiagnosticCategory.Error, "Merge_conflict_marker_encountered_1185", "Merge conflict marker encountered."), + A_rest_element_cannot_have_an_initializer: diag(1186, ts.DiagnosticCategory.Error, "A_rest_element_cannot_have_an_initializer_1186", "A rest element cannot have an initializer."), + A_parameter_property_may_not_be_declared_using_a_binding_pattern: diag(1187, ts.DiagnosticCategory.Error, "A_parameter_property_may_not_be_declared_using_a_binding_pattern_1187", "A parameter property may not be declared using a binding pattern."), + Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement: diag(1188, ts.DiagnosticCategory.Error, "Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement_1188", "Only a single variable declaration is allowed in a 'for...of' statement."), + The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer: diag(1189, ts.DiagnosticCategory.Error, "The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer_1189", "The variable declaration of a 'for...in' statement cannot have an initializer."), + The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer: diag(1190, ts.DiagnosticCategory.Error, "The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer_1190", "The variable declaration of a 'for...of' statement cannot have an initializer."), + An_import_declaration_cannot_have_modifiers: diag(1191, ts.DiagnosticCategory.Error, "An_import_declaration_cannot_have_modifiers_1191", "An import declaration cannot have modifiers."), + Module_0_has_no_default_export: diag(1192, ts.DiagnosticCategory.Error, "Module_0_has_no_default_export_1192", "Module '{0}' has no default export."), + An_export_declaration_cannot_have_modifiers: diag(1193, ts.DiagnosticCategory.Error, "An_export_declaration_cannot_have_modifiers_1193", "An export declaration cannot have modifiers."), + Export_declarations_are_not_permitted_in_a_namespace: diag(1194, ts.DiagnosticCategory.Error, "Export_declarations_are_not_permitted_in_a_namespace_1194", "Export declarations are not permitted in a namespace."), + Catch_clause_variable_cannot_have_a_type_annotation: diag(1196, ts.DiagnosticCategory.Error, "Catch_clause_variable_cannot_have_a_type_annotation_1196", "Catch clause variable cannot have a type annotation."), + Catch_clause_variable_cannot_have_an_initializer: diag(1197, ts.DiagnosticCategory.Error, "Catch_clause_variable_cannot_have_an_initializer_1197", "Catch clause variable cannot have an initializer."), + An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive: diag(1198, ts.DiagnosticCategory.Error, "An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive_1198", "An extended Unicode escape value must be between 0x0 and 0x10FFFF inclusive."), + Unterminated_Unicode_escape_sequence: diag(1199, ts.DiagnosticCategory.Error, "Unterminated_Unicode_escape_sequence_1199", "Unterminated Unicode escape sequence."), + Line_terminator_not_permitted_before_arrow: diag(1200, ts.DiagnosticCategory.Error, "Line_terminator_not_permitted_before_arrow_1200", "Line terminator not permitted before arrow."), + Import_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_import_Asterisk_as_ns_from_mod_import_a_from_mod_import_d_from_mod_or_another_module_format_instead: diag(1202, ts.DiagnosticCategory.Error, "Import_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_import_Asterisk_as_1202", "Import assignment cannot be used when targeting ECMAScript modules. Consider using 'import * as ns from \"mod\"', 'import {a} from \"mod\"', 'import d from \"mod\"', or another module format instead."), + Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or_another_module_format_instead: diag(1203, ts.DiagnosticCategory.Error, "Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or__1203", "Export assignment cannot be used when targeting ECMAScript modules. Consider using 'export default' or another module format instead."), + Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided: diag(1205, ts.DiagnosticCategory.Error, "Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205", "Cannot re-export a type when the '--isolatedModules' flag is provided."), + Decorators_are_not_valid_here: diag(1206, ts.DiagnosticCategory.Error, "Decorators_are_not_valid_here_1206", "Decorators are not valid here."), + Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name: diag(1207, ts.DiagnosticCategory.Error, "Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name_1207", "Decorators cannot be applied to multiple get/set accessors of the same name."), + Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided: diag(1208, ts.DiagnosticCategory.Error, "Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided_1208", "Cannot compile namespaces when the '--isolatedModules' flag is provided."), + Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided: diag(1209, ts.DiagnosticCategory.Error, "Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided_1209", "Ambient const enums are not allowed when the '--isolatedModules' flag is provided."), + Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode: diag(1210, ts.DiagnosticCategory.Error, "Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode_1210", "Invalid use of '{0}'. Class definitions are automatically in strict mode."), + A_class_declaration_without_the_default_modifier_must_have_a_name: diag(1211, ts.DiagnosticCategory.Error, "A_class_declaration_without_the_default_modifier_must_have_a_name_1211", "A class declaration without the 'default' modifier must have a name."), + Identifier_expected_0_is_a_reserved_word_in_strict_mode: diag(1212, ts.DiagnosticCategory.Error, "Identifier_expected_0_is_a_reserved_word_in_strict_mode_1212", "Identifier expected. '{0}' is a reserved word in strict mode."), + Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode: diag(1213, ts.DiagnosticCategory.Error, "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_stric_1213", "Identifier expected. '{0}' is a reserved word in strict mode. Class definitions are automatically in strict mode."), + Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode: diag(1214, ts.DiagnosticCategory.Error, "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode_1214", "Identifier expected. '{0}' is a reserved word in strict mode. Modules are automatically in strict mode."), + Invalid_use_of_0_Modules_are_automatically_in_strict_mode: diag(1215, ts.DiagnosticCategory.Error, "Invalid_use_of_0_Modules_are_automatically_in_strict_mode_1215", "Invalid use of '{0}'. Modules are automatically in strict mode."), + Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules: diag(1216, ts.DiagnosticCategory.Error, "Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules_1216", "Identifier expected. '__esModule' is reserved as an exported marker when transforming ECMAScript modules."), + Export_assignment_is_not_supported_when_module_flag_is_system: diag(1218, ts.DiagnosticCategory.Error, "Export_assignment_is_not_supported_when_module_flag_is_system_1218", "Export assignment is not supported when '--module' flag is 'system'."), + Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_to_remove_this_warning: diag(1219, ts.DiagnosticCategory.Error, "Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_t_1219", "Experimental support for decorators is a feature that is subject to change in a future release. Set the 'experimentalDecorators' option to remove this warning."), + Generators_are_only_available_when_targeting_ECMAScript_2015_or_higher: diag(1220, ts.DiagnosticCategory.Error, "Generators_are_only_available_when_targeting_ECMAScript_2015_or_higher_1220", "Generators are only available when targeting ECMAScript 2015 or higher."), + Generators_are_not_allowed_in_an_ambient_context: diag(1221, ts.DiagnosticCategory.Error, "Generators_are_not_allowed_in_an_ambient_context_1221", "Generators are not allowed in an ambient context."), + An_overload_signature_cannot_be_declared_as_a_generator: diag(1222, ts.DiagnosticCategory.Error, "An_overload_signature_cannot_be_declared_as_a_generator_1222", "An overload signature cannot be declared as a generator."), + _0_tag_already_specified: diag(1223, ts.DiagnosticCategory.Error, "_0_tag_already_specified_1223", "'{0}' tag already specified."), + Signature_0_must_be_a_type_predicate: diag(1224, ts.DiagnosticCategory.Error, "Signature_0_must_be_a_type_predicate_1224", "Signature '{0}' must be a type predicate."), + Cannot_find_parameter_0: diag(1225, ts.DiagnosticCategory.Error, "Cannot_find_parameter_0_1225", "Cannot find parameter '{0}'."), + Type_predicate_0_is_not_assignable_to_1: diag(1226, ts.DiagnosticCategory.Error, "Type_predicate_0_is_not_assignable_to_1_1226", "Type predicate '{0}' is not assignable to '{1}'."), + Parameter_0_is_not_in_the_same_position_as_parameter_1: diag(1227, ts.DiagnosticCategory.Error, "Parameter_0_is_not_in_the_same_position_as_parameter_1_1227", "Parameter '{0}' is not in the same position as parameter '{1}'."), + A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods: diag(1228, ts.DiagnosticCategory.Error, "A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods_1228", "A type predicate is only allowed in return type position for functions and methods."), + A_type_predicate_cannot_reference_a_rest_parameter: diag(1229, ts.DiagnosticCategory.Error, "A_type_predicate_cannot_reference_a_rest_parameter_1229", "A type predicate cannot reference a rest parameter."), + A_type_predicate_cannot_reference_element_0_in_a_binding_pattern: diag(1230, ts.DiagnosticCategory.Error, "A_type_predicate_cannot_reference_element_0_in_a_binding_pattern_1230", "A type predicate cannot reference element '{0}' in a binding pattern."), + An_export_assignment_can_only_be_used_in_a_module: diag(1231, ts.DiagnosticCategory.Error, "An_export_assignment_can_only_be_used_in_a_module_1231", "An export assignment can only be used in a module."), + An_import_declaration_can_only_be_used_in_a_namespace_or_module: diag(1232, ts.DiagnosticCategory.Error, "An_import_declaration_can_only_be_used_in_a_namespace_or_module_1232", "An import declaration can only be used in a namespace or module."), + An_export_declaration_can_only_be_used_in_a_module: diag(1233, ts.DiagnosticCategory.Error, "An_export_declaration_can_only_be_used_in_a_module_1233", "An export declaration can only be used in a module."), + An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file: diag(1234, ts.DiagnosticCategory.Error, "An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file_1234", "An ambient module declaration is only allowed at the top level in a file."), + A_namespace_declaration_is_only_allowed_in_a_namespace_or_module: diag(1235, ts.DiagnosticCategory.Error, "A_namespace_declaration_is_only_allowed_in_a_namespace_or_module_1235", "A namespace declaration is only allowed in a namespace or module."), + The_return_type_of_a_property_decorator_function_must_be_either_void_or_any: diag(1236, ts.DiagnosticCategory.Error, "The_return_type_of_a_property_decorator_function_must_be_either_void_or_any_1236", "The return type of a property decorator function must be either 'void' or 'any'."), + The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any: diag(1237, ts.DiagnosticCategory.Error, "The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any_1237", "The return type of a parameter decorator function must be either 'void' or 'any'."), + Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression: diag(1238, ts.DiagnosticCategory.Error, "Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression_1238", "Unable to resolve signature of class decorator when called as an expression."), + Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression: diag(1239, ts.DiagnosticCategory.Error, "Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression_1239", "Unable to resolve signature of parameter decorator when called as an expression."), + Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression: diag(1240, ts.DiagnosticCategory.Error, "Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression_1240", "Unable to resolve signature of property decorator when called as an expression."), + Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression: diag(1241, ts.DiagnosticCategory.Error, "Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression_1241", "Unable to resolve signature of method decorator when called as an expression."), + abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration: diag(1242, ts.DiagnosticCategory.Error, "abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration_1242", "'abstract' modifier can only appear on a class, method, or property declaration."), + _0_modifier_cannot_be_used_with_1_modifier: diag(1243, ts.DiagnosticCategory.Error, "_0_modifier_cannot_be_used_with_1_modifier_1243", "'{0}' modifier cannot be used with '{1}' modifier."), + Abstract_methods_can_only_appear_within_an_abstract_class: diag(1244, ts.DiagnosticCategory.Error, "Abstract_methods_can_only_appear_within_an_abstract_class_1244", "Abstract methods can only appear within an abstract class."), + Method_0_cannot_have_an_implementation_because_it_is_marked_abstract: diag(1245, ts.DiagnosticCategory.Error, "Method_0_cannot_have_an_implementation_because_it_is_marked_abstract_1245", "Method '{0}' cannot have an implementation because it is marked abstract."), + An_interface_property_cannot_have_an_initializer: diag(1246, ts.DiagnosticCategory.Error, "An_interface_property_cannot_have_an_initializer_1246", "An interface property cannot have an initializer."), + A_type_literal_property_cannot_have_an_initializer: diag(1247, ts.DiagnosticCategory.Error, "A_type_literal_property_cannot_have_an_initializer_1247", "A type literal property cannot have an initializer."), + A_class_member_cannot_have_the_0_keyword: diag(1248, ts.DiagnosticCategory.Error, "A_class_member_cannot_have_the_0_keyword_1248", "A class member cannot have the '{0}' keyword."), + A_decorator_can_only_decorate_a_method_implementation_not_an_overload: diag(1249, ts.DiagnosticCategory.Error, "A_decorator_can_only_decorate_a_method_implementation_not_an_overload_1249", "A decorator can only decorate a method implementation, not an overload."), + Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5: diag(1250, ts.DiagnosticCategory.Error, "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_1250", "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'."), + Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_definitions_are_automatically_in_strict_mode: diag(1251, ts.DiagnosticCategory.Error, "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_d_1251", "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Class definitions are automatically in strict mode."), + Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_are_automatically_in_strict_mode: diag(1252, ts.DiagnosticCategory.Error, "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_1252", "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Modules are automatically in strict mode."), + _0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag: diag(1253, ts.DiagnosticCategory.Error, "_0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag_1253", "'{0}' tag cannot be used independently as a top level JSDoc tag."), + A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_reference: diag(1254, ts.DiagnosticCategory.Error, "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_refere_1254", "A 'const' initializer in an ambient context must be a string or numeric literal or literal enum reference."), + A_definite_assignment_assertion_is_not_permitted_in_this_context: diag(1255, ts.DiagnosticCategory.Error, "A_definite_assignment_assertion_is_not_permitted_in_this_context_1255", "A definite assignment assertion '!' is not permitted in this context."), + A_rest_element_must_be_last_in_a_tuple_type: diag(1256, ts.DiagnosticCategory.Error, "A_rest_element_must_be_last_in_a_tuple_type_1256", "A rest element must be last in a tuple type."), + A_required_element_cannot_follow_an_optional_element: diag(1257, ts.DiagnosticCategory.Error, "A_required_element_cannot_follow_an_optional_element_1257", "A required element cannot follow an optional element."), + with_statements_are_not_allowed_in_an_async_function_block: diag(1300, ts.DiagnosticCategory.Error, "with_statements_are_not_allowed_in_an_async_function_block_1300", "'with' statements are not allowed in an async function block."), + await_expression_is_only_allowed_within_an_async_function: diag(1308, ts.DiagnosticCategory.Error, "await_expression_is_only_allowed_within_an_async_function_1308", "'await' expression is only allowed within an async function."), + can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment: diag(1312, ts.DiagnosticCategory.Error, "can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment_1312", "'=' can only be used in an object literal property inside a destructuring assignment."), + The_body_of_an_if_statement_cannot_be_the_empty_statement: diag(1313, ts.DiagnosticCategory.Error, "The_body_of_an_if_statement_cannot_be_the_empty_statement_1313", "The body of an 'if' statement cannot be the empty statement."), + Global_module_exports_may_only_appear_in_module_files: diag(1314, ts.DiagnosticCategory.Error, "Global_module_exports_may_only_appear_in_module_files_1314", "Global module exports may only appear in module files."), + Global_module_exports_may_only_appear_in_declaration_files: diag(1315, ts.DiagnosticCategory.Error, "Global_module_exports_may_only_appear_in_declaration_files_1315", "Global module exports may only appear in declaration files."), + Global_module_exports_may_only_appear_at_top_level: diag(1316, ts.DiagnosticCategory.Error, "Global_module_exports_may_only_appear_at_top_level_1316", "Global module exports may only appear at top level."), + A_parameter_property_cannot_be_declared_using_a_rest_parameter: diag(1317, ts.DiagnosticCategory.Error, "A_parameter_property_cannot_be_declared_using_a_rest_parameter_1317", "A parameter property cannot be declared using a rest parameter."), + An_abstract_accessor_cannot_have_an_implementation: diag(1318, ts.DiagnosticCategory.Error, "An_abstract_accessor_cannot_have_an_implementation_1318", "An abstract accessor cannot have an implementation."), + A_default_export_can_only_be_used_in_an_ECMAScript_style_module: diag(1319, ts.DiagnosticCategory.Error, "A_default_export_can_only_be_used_in_an_ECMAScript_style_module_1319", "A default export can only be used in an ECMAScript-style module."), + Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1320, ts.DiagnosticCategory.Error, "Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member_1320", "Type of 'await' operand must either be a valid promise or must not contain a callable 'then' member."), + Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1321, ts.DiagnosticCategory.Error, "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321", "Type of 'yield' operand in an async generator must either be a valid promise or must not contain a callable 'then' member."), + Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1322, ts.DiagnosticCategory.Error, "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322", "Type of iterated elements of a 'yield*' operand must either be a valid promise or must not contain a callable 'then' member."), + Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext: diag(1323, ts.DiagnosticCategory.Error, "Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext_1323", "Dynamic import is only supported when '--module' flag is 'commonjs' or 'esNext'."), + Dynamic_import_must_have_one_specifier_as_an_argument: diag(1324, ts.DiagnosticCategory.Error, "Dynamic_import_must_have_one_specifier_as_an_argument_1324", "Dynamic import must have one specifier as an argument."), + Specifier_of_dynamic_import_cannot_be_spread_element: diag(1325, ts.DiagnosticCategory.Error, "Specifier_of_dynamic_import_cannot_be_spread_element_1325", "Specifier of dynamic import cannot be spread element."), + Dynamic_import_cannot_have_type_arguments: diag(1326, ts.DiagnosticCategory.Error, "Dynamic_import_cannot_have_type_arguments_1326", "Dynamic import cannot have type arguments"), + String_literal_with_double_quotes_expected: diag(1327, ts.DiagnosticCategory.Error, "String_literal_with_double_quotes_expected_1327", "String literal with double quotes expected."), + Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_literal: diag(1328, ts.DiagnosticCategory.Error, "Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_li_1328", "Property value can only be string literal, numeric literal, 'true', 'false', 'null', object literal or array literal."), + _0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write_0: diag(1329, ts.DiagnosticCategory.Error, "_0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write__1329", "'{0}' accepts too few arguments to be used as a decorator here. Did you mean to call it first and write '@{0}()'?"), + A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly: diag(1330, ts.DiagnosticCategory.Error, "A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly_1330", "A property of an interface or type literal whose type is a 'unique symbol' type must be 'readonly'."), + A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly: diag(1331, ts.DiagnosticCategory.Error, "A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly_1331", "A property of a class whose type is a 'unique symbol' type must be both 'static' and 'readonly'."), + A_variable_whose_type_is_a_unique_symbol_type_must_be_const: diag(1332, ts.DiagnosticCategory.Error, "A_variable_whose_type_is_a_unique_symbol_type_must_be_const_1332", "A variable whose type is a 'unique symbol' type must be 'const'."), + unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name: diag(1333, ts.DiagnosticCategory.Error, "unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name_1333", "'unique symbol' types may not be used on a variable declaration with a binding name."), + unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement: diag(1334, ts.DiagnosticCategory.Error, "unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement_1334", "'unique symbol' types are only allowed on variables in a variable statement."), + unique_symbol_types_are_not_allowed_here: diag(1335, ts.DiagnosticCategory.Error, "unique_symbol_types_are_not_allowed_here_1335", "'unique symbol' types are not allowed here."), + An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead: diag(1336, ts.DiagnosticCategory.Error, "An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead_1336", "An index signature parameter type cannot be a type alias. Consider writing '[{0}: {1}]: {2}' instead."), + An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead: diag(1337, ts.DiagnosticCategory.Error, "An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead_1337", "An index signature parameter type cannot be a union type. Consider using a mapped object type instead."), + infer_declarations_are_only_permitted_in_the_extends_clause_of_a_conditional_type: diag(1338, ts.DiagnosticCategory.Error, "infer_declarations_are_only_permitted_in_the_extends_clause_of_a_conditional_type_1338", "'infer' declarations are only permitted in the 'extends' clause of a conditional type."), + Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here: diag(1339, ts.DiagnosticCategory.Error, "Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here_1339", "Module '{0}' does not refer to a value, but is used as a value here."), + Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0: diag(1340, ts.DiagnosticCategory.Error, "Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0_1340", "Module '{0}' does not refer to a type, but is used as a type here. Did you mean 'typeof import('{0}')'?"), + Type_arguments_cannot_be_used_here: diag(1342, ts.DiagnosticCategory.Error, "Type_arguments_cannot_be_used_here_1342", "Type arguments cannot be used here."), + The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_options: diag(1343, ts.DiagnosticCategory.Error, "The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_option_1343", "The 'import.meta' meta-property is only allowed using 'ESNext' for the 'target' and 'module' compiler options."), + A_label_is_not_allowed_here: diag(1344, ts.DiagnosticCategory.Error, "A_label_is_not_allowed_here_1344", "'A label is not allowed here."), + An_expression_of_type_void_cannot_be_tested_for_truthiness: diag(1345, ts.DiagnosticCategory.Error, "An_expression_of_type_void_cannot_be_tested_for_truthiness_1345", "An expression of type 'void' cannot be tested for truthiness"), + This_parameter_is_not_allowed_with_use_strict_directive: diag(1346, ts.DiagnosticCategory.Error, "This_parameter_is_not_allowed_with_use_strict_directive_1346", "This parameter is not allowed with 'use strict' directive."), + use_strict_directive_cannot_be_used_with_non_simple_parameter_list: diag(1347, ts.DiagnosticCategory.Error, "use_strict_directive_cannot_be_used_with_non_simple_parameter_list_1347", "'use strict' directive cannot be used with non-simple parameter list."), + Non_simple_parameter_declared_here: diag(1348, ts.DiagnosticCategory.Error, "Non_simple_parameter_declared_here_1348", "Non-simple parameter declared here."), + use_strict_directive_used_here: diag(1349, ts.DiagnosticCategory.Error, "use_strict_directive_used_here_1349", "'use strict' directive used here."), + Print_the_final_configuration_instead_of_building: diag(1350, ts.DiagnosticCategory.Message, "Print_the_final_configuration_instead_of_building_1350", "Print the final configuration instead of building."), + Duplicate_identifier_0: diag(2300, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_2300", "Duplicate identifier '{0}'."), + Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: diag(2301, ts.DiagnosticCategory.Error, "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301", "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor."), + Static_members_cannot_reference_class_type_parameters: diag(2302, ts.DiagnosticCategory.Error, "Static_members_cannot_reference_class_type_parameters_2302", "Static members cannot reference class type parameters."), + Circular_definition_of_import_alias_0: diag(2303, ts.DiagnosticCategory.Error, "Circular_definition_of_import_alias_0_2303", "Circular definition of import alias '{0}'."), + Cannot_find_name_0: diag(2304, ts.DiagnosticCategory.Error, "Cannot_find_name_0_2304", "Cannot find name '{0}'."), + Module_0_has_no_exported_member_1: diag(2305, ts.DiagnosticCategory.Error, "Module_0_has_no_exported_member_1_2305", "Module '{0}' has no exported member '{1}'."), + File_0_is_not_a_module: diag(2306, ts.DiagnosticCategory.Error, "File_0_is_not_a_module_2306", "File '{0}' is not a module."), + Cannot_find_module_0: diag(2307, ts.DiagnosticCategory.Error, "Cannot_find_module_0_2307", "Cannot find module '{0}'."), + Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambiguity: diag(2308, ts.DiagnosticCategory.Error, "Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambig_2308", "Module {0} has already exported a member named '{1}'. Consider explicitly re-exporting to resolve the ambiguity."), + An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements: diag(2309, ts.DiagnosticCategory.Error, "An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements_2309", "An export assignment cannot be used in a module with other exported elements."), + Type_0_recursively_references_itself_as_a_base_type: diag(2310, ts.DiagnosticCategory.Error, "Type_0_recursively_references_itself_as_a_base_type_2310", "Type '{0}' recursively references itself as a base type."), + A_class_may_only_extend_another_class: diag(2311, ts.DiagnosticCategory.Error, "A_class_may_only_extend_another_class_2311", "A class may only extend another class."), + An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_members: diag(2312, ts.DiagnosticCategory.Error, "An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_me_2312", "An interface can only extend an object type or intersection of object types with statically known members."), + Type_parameter_0_has_a_circular_constraint: diag(2313, ts.DiagnosticCategory.Error, "Type_parameter_0_has_a_circular_constraint_2313", "Type parameter '{0}' has a circular constraint."), + Generic_type_0_requires_1_type_argument_s: diag(2314, ts.DiagnosticCategory.Error, "Generic_type_0_requires_1_type_argument_s_2314", "Generic type '{0}' requires {1} type argument(s)."), + Type_0_is_not_generic: diag(2315, ts.DiagnosticCategory.Error, "Type_0_is_not_generic_2315", "Type '{0}' is not generic."), + Global_type_0_must_be_a_class_or_interface_type: diag(2316, ts.DiagnosticCategory.Error, "Global_type_0_must_be_a_class_or_interface_type_2316", "Global type '{0}' must be a class or interface type."), + Global_type_0_must_have_1_type_parameter_s: diag(2317, ts.DiagnosticCategory.Error, "Global_type_0_must_have_1_type_parameter_s_2317", "Global type '{0}' must have {1} type parameter(s)."), + Cannot_find_global_type_0: diag(2318, ts.DiagnosticCategory.Error, "Cannot_find_global_type_0_2318", "Cannot find global type '{0}'."), + Named_property_0_of_types_1_and_2_are_not_identical: diag(2319, ts.DiagnosticCategory.Error, "Named_property_0_of_types_1_and_2_are_not_identical_2319", "Named property '{0}' of types '{1}' and '{2}' are not identical."), + Interface_0_cannot_simultaneously_extend_types_1_and_2: diag(2320, ts.DiagnosticCategory.Error, "Interface_0_cannot_simultaneously_extend_types_1_and_2_2320", "Interface '{0}' cannot simultaneously extend types '{1}' and '{2}'."), + Excessive_stack_depth_comparing_types_0_and_1: diag(2321, ts.DiagnosticCategory.Error, "Excessive_stack_depth_comparing_types_0_and_1_2321", "Excessive stack depth comparing types '{0}' and '{1}'."), + Type_0_is_not_assignable_to_type_1: diag(2322, ts.DiagnosticCategory.Error, "Type_0_is_not_assignable_to_type_1_2322", "Type '{0}' is not assignable to type '{1}'."), + Cannot_redeclare_exported_variable_0: diag(2323, ts.DiagnosticCategory.Error, "Cannot_redeclare_exported_variable_0_2323", "Cannot redeclare exported variable '{0}'."), + Property_0_is_missing_in_type_1: diag(2324, ts.DiagnosticCategory.Error, "Property_0_is_missing_in_type_1_2324", "Property '{0}' is missing in type '{1}'."), + Property_0_is_private_in_type_1_but_not_in_type_2: diag(2325, ts.DiagnosticCategory.Error, "Property_0_is_private_in_type_1_but_not_in_type_2_2325", "Property '{0}' is private in type '{1}' but not in type '{2}'."), + Types_of_property_0_are_incompatible: diag(2326, ts.DiagnosticCategory.Error, "Types_of_property_0_are_incompatible_2326", "Types of property '{0}' are incompatible."), + Property_0_is_optional_in_type_1_but_required_in_type_2: diag(2327, ts.DiagnosticCategory.Error, "Property_0_is_optional_in_type_1_but_required_in_type_2_2327", "Property '{0}' is optional in type '{1}' but required in type '{2}'."), + Types_of_parameters_0_and_1_are_incompatible: diag(2328, ts.DiagnosticCategory.Error, "Types_of_parameters_0_and_1_are_incompatible_2328", "Types of parameters '{0}' and '{1}' are incompatible."), + Index_signature_is_missing_in_type_0: diag(2329, ts.DiagnosticCategory.Error, "Index_signature_is_missing_in_type_0_2329", "Index signature is missing in type '{0}'."), + Index_signatures_are_incompatible: diag(2330, ts.DiagnosticCategory.Error, "Index_signatures_are_incompatible_2330", "Index signatures are incompatible."), + this_cannot_be_referenced_in_a_module_or_namespace_body: diag(2331, ts.DiagnosticCategory.Error, "this_cannot_be_referenced_in_a_module_or_namespace_body_2331", "'this' cannot be referenced in a module or namespace body."), + this_cannot_be_referenced_in_current_location: diag(2332, ts.DiagnosticCategory.Error, "this_cannot_be_referenced_in_current_location_2332", "'this' cannot be referenced in current location."), + this_cannot_be_referenced_in_constructor_arguments: diag(2333, ts.DiagnosticCategory.Error, "this_cannot_be_referenced_in_constructor_arguments_2333", "'this' cannot be referenced in constructor arguments."), + this_cannot_be_referenced_in_a_static_property_initializer: diag(2334, ts.DiagnosticCategory.Error, "this_cannot_be_referenced_in_a_static_property_initializer_2334", "'this' cannot be referenced in a static property initializer."), + super_can_only_be_referenced_in_a_derived_class: diag(2335, ts.DiagnosticCategory.Error, "super_can_only_be_referenced_in_a_derived_class_2335", "'super' can only be referenced in a derived class."), + super_cannot_be_referenced_in_constructor_arguments: diag(2336, ts.DiagnosticCategory.Error, "super_cannot_be_referenced_in_constructor_arguments_2336", "'super' cannot be referenced in constructor arguments."), + Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors: diag(2337, ts.DiagnosticCategory.Error, "Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors_2337", "Super calls are not permitted outside constructors or in nested functions inside constructors."), + super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_derived_class: diag(2338, ts.DiagnosticCategory.Error, "super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_der_2338", "'super' property access is permitted only in a constructor, member function, or member accessor of a derived class."), + Property_0_does_not_exist_on_type_1: diag(2339, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_2339", "Property '{0}' does not exist on type '{1}'."), + Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword: diag(2340, ts.DiagnosticCategory.Error, "Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword_2340", "Only public and protected methods of the base class are accessible via the 'super' keyword."), + Property_0_is_private_and_only_accessible_within_class_1: diag(2341, ts.DiagnosticCategory.Error, "Property_0_is_private_and_only_accessible_within_class_1_2341", "Property '{0}' is private and only accessible within class '{1}'."), + An_index_expression_argument_must_be_of_type_string_number_symbol_or_any: diag(2342, ts.DiagnosticCategory.Error, "An_index_expression_argument_must_be_of_type_string_number_symbol_or_any_2342", "An index expression argument must be of type 'string', 'number', 'symbol', or 'any'."), + This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1: diag(2343, ts.DiagnosticCategory.Error, "This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1_2343", "This syntax requires an imported helper named '{1}', but module '{0}' has no exported member '{1}'."), + Type_0_does_not_satisfy_the_constraint_1: diag(2344, ts.DiagnosticCategory.Error, "Type_0_does_not_satisfy_the_constraint_1_2344", "Type '{0}' does not satisfy the constraint '{1}'."), + Argument_of_type_0_is_not_assignable_to_parameter_of_type_1: diag(2345, ts.DiagnosticCategory.Error, "Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_2345", "Argument of type '{0}' is not assignable to parameter of type '{1}'."), + Call_target_does_not_contain_any_signatures: diag(2346, ts.DiagnosticCategory.Error, "Call_target_does_not_contain_any_signatures_2346", "Call target does not contain any signatures."), + Untyped_function_calls_may_not_accept_type_arguments: diag(2347, ts.DiagnosticCategory.Error, "Untyped_function_calls_may_not_accept_type_arguments_2347", "Untyped function calls may not accept type arguments."), + Value_of_type_0_is_not_callable_Did_you_mean_to_include_new: diag(2348, ts.DiagnosticCategory.Error, "Value_of_type_0_is_not_callable_Did_you_mean_to_include_new_2348", "Value of type '{0}' is not callable. Did you mean to include 'new'?"), + Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures: diag(2349, ts.DiagnosticCategory.Error, "Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatur_2349", "Cannot invoke an expression whose type lacks a call signature. Type '{0}' has no compatible call signatures."), + Only_a_void_function_can_be_called_with_the_new_keyword: diag(2350, ts.DiagnosticCategory.Error, "Only_a_void_function_can_be_called_with_the_new_keyword_2350", "Only a void function can be called with the 'new' keyword."), + Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature: diag(2351, ts.DiagnosticCategory.Error, "Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature_2351", "Cannot use 'new' with an expression whose type lacks a call or construct signature."), + Conversion_of_type_0_to_type_1_may_be_a_mistake_because_neither_type_sufficiently_overlaps_with_the_other_If_this_was_intentional_convert_the_expression_to_unknown_first: diag(2352, ts.DiagnosticCategory.Error, "Conversion_of_type_0_to_type_1_may_be_a_mistake_because_neither_type_sufficiently_overlaps_with_the__2352", "Conversion of type '{0}' to type '{1}' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first."), + Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1: diag(2353, ts.DiagnosticCategory.Error, "Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1_2353", "Object literal may only specify known properties, and '{0}' does not exist in type '{1}'."), + This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found: diag(2354, ts.DiagnosticCategory.Error, "This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found_2354", "This syntax requires an imported helper but module '{0}' cannot be found."), + A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value: diag(2355, ts.DiagnosticCategory.Error, "A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value_2355", "A function whose declared type is neither 'void' nor 'any' must return a value."), + An_arithmetic_operand_must_be_of_type_any_number_bigint_or_an_enum_type: diag(2356, ts.DiagnosticCategory.Error, "An_arithmetic_operand_must_be_of_type_any_number_bigint_or_an_enum_type_2356", "An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type."), + The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access: diag(2357, ts.DiagnosticCategory.Error, "The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access_2357", "The operand of an increment or decrement operator must be a variable or a property access."), + The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter: diag(2358, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_paramete_2358", "The left-hand side of an 'instanceof' expression must be of type 'any', an object type or a type parameter."), + The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_Function_interface_type: diag(2359, ts.DiagnosticCategory.Error, "The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_F_2359", "The right-hand side of an 'instanceof' expression must be of type 'any' or of a type assignable to the 'Function' interface type."), + The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol: diag(2360, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol_2360", "The left-hand side of an 'in' expression must be of type 'any', 'string', 'number', or 'symbol'."), + The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter: diag(2361, ts.DiagnosticCategory.Error, "The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter_2361", "The right-hand side of an 'in' expression must be of type 'any', an object type or a type parameter."), + The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type: diag(2362, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type_2362", "The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type."), + The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type: diag(2363, ts.DiagnosticCategory.Error, "The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type_2363", "The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type."), + The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access: diag(2364, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access_2364", "The left-hand side of an assignment expression must be a variable or a property access."), + Operator_0_cannot_be_applied_to_types_1_and_2: diag(2365, ts.DiagnosticCategory.Error, "Operator_0_cannot_be_applied_to_types_1_and_2_2365", "Operator '{0}' cannot be applied to types '{1}' and '{2}'."), + Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined: diag(2366, ts.DiagnosticCategory.Error, "Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined_2366", "Function lacks ending return statement and return type does not include 'undefined'."), + This_condition_will_always_return_0_since_the_types_1_and_2_have_no_overlap: diag(2367, ts.DiagnosticCategory.Error, "This_condition_will_always_return_0_since_the_types_1_and_2_have_no_overlap_2367", "This condition will always return '{0}' since the types '{1}' and '{2}' have no overlap."), + Type_parameter_name_cannot_be_0: diag(2368, ts.DiagnosticCategory.Error, "Type_parameter_name_cannot_be_0_2368", "Type parameter name cannot be '{0}'."), + A_parameter_property_is_only_allowed_in_a_constructor_implementation: diag(2369, ts.DiagnosticCategory.Error, "A_parameter_property_is_only_allowed_in_a_constructor_implementation_2369", "A parameter property is only allowed in a constructor implementation."), + A_rest_parameter_must_be_of_an_array_type: diag(2370, ts.DiagnosticCategory.Error, "A_rest_parameter_must_be_of_an_array_type_2370", "A rest parameter must be of an array type."), + A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation: diag(2371, ts.DiagnosticCategory.Error, "A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation_2371", "A parameter initializer is only allowed in a function or constructor implementation."), + Parameter_0_cannot_be_referenced_in_its_initializer: diag(2372, ts.DiagnosticCategory.Error, "Parameter_0_cannot_be_referenced_in_its_initializer_2372", "Parameter '{0}' cannot be referenced in its initializer."), + Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it: diag(2373, ts.DiagnosticCategory.Error, "Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it_2373", "Initializer of parameter '{0}' cannot reference identifier '{1}' declared after it."), + Duplicate_string_index_signature: diag(2374, ts.DiagnosticCategory.Error, "Duplicate_string_index_signature_2374", "Duplicate string index signature."), + Duplicate_number_index_signature: diag(2375, ts.DiagnosticCategory.Error, "Duplicate_number_index_signature_2375", "Duplicate number index signature."), + A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_properties_or_has_parameter_properties: diag(2376, ts.DiagnosticCategory.Error, "A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_proper_2376", "A 'super' call must be the first statement in the constructor when a class contains initialized properties or has parameter properties."), + Constructors_for_derived_classes_must_contain_a_super_call: diag(2377, ts.DiagnosticCategory.Error, "Constructors_for_derived_classes_must_contain_a_super_call_2377", "Constructors for derived classes must contain a 'super' call."), + A_get_accessor_must_return_a_value: diag(2378, ts.DiagnosticCategory.Error, "A_get_accessor_must_return_a_value_2378", "A 'get' accessor must return a value."), + Getter_and_setter_accessors_do_not_agree_in_visibility: diag(2379, ts.DiagnosticCategory.Error, "Getter_and_setter_accessors_do_not_agree_in_visibility_2379", "Getter and setter accessors do not agree in visibility."), + get_and_set_accessor_must_have_the_same_type: diag(2380, ts.DiagnosticCategory.Error, "get_and_set_accessor_must_have_the_same_type_2380", "'get' and 'set' accessor must have the same type."), + A_signature_with_an_implementation_cannot_use_a_string_literal_type: diag(2381, ts.DiagnosticCategory.Error, "A_signature_with_an_implementation_cannot_use_a_string_literal_type_2381", "A signature with an implementation cannot use a string literal type."), + Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature: diag(2382, ts.DiagnosticCategory.Error, "Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature_2382", "Specialized overload signature is not assignable to any non-specialized signature."), + Overload_signatures_must_all_be_exported_or_non_exported: diag(2383, ts.DiagnosticCategory.Error, "Overload_signatures_must_all_be_exported_or_non_exported_2383", "Overload signatures must all be exported or non-exported."), + Overload_signatures_must_all_be_ambient_or_non_ambient: diag(2384, ts.DiagnosticCategory.Error, "Overload_signatures_must_all_be_ambient_or_non_ambient_2384", "Overload signatures must all be ambient or non-ambient."), + Overload_signatures_must_all_be_public_private_or_protected: diag(2385, ts.DiagnosticCategory.Error, "Overload_signatures_must_all_be_public_private_or_protected_2385", "Overload signatures must all be public, private or protected."), + Overload_signatures_must_all_be_optional_or_required: diag(2386, ts.DiagnosticCategory.Error, "Overload_signatures_must_all_be_optional_or_required_2386", "Overload signatures must all be optional or required."), + Function_overload_must_be_static: diag(2387, ts.DiagnosticCategory.Error, "Function_overload_must_be_static_2387", "Function overload must be static."), + Function_overload_must_not_be_static: diag(2388, ts.DiagnosticCategory.Error, "Function_overload_must_not_be_static_2388", "Function overload must not be static."), + Function_implementation_name_must_be_0: diag(2389, ts.DiagnosticCategory.Error, "Function_implementation_name_must_be_0_2389", "Function implementation name must be '{0}'."), + Constructor_implementation_is_missing: diag(2390, ts.DiagnosticCategory.Error, "Constructor_implementation_is_missing_2390", "Constructor implementation is missing."), + Function_implementation_is_missing_or_not_immediately_following_the_declaration: diag(2391, ts.DiagnosticCategory.Error, "Function_implementation_is_missing_or_not_immediately_following_the_declaration_2391", "Function implementation is missing or not immediately following the declaration."), + Multiple_constructor_implementations_are_not_allowed: diag(2392, ts.DiagnosticCategory.Error, "Multiple_constructor_implementations_are_not_allowed_2392", "Multiple constructor implementations are not allowed."), + Duplicate_function_implementation: diag(2393, ts.DiagnosticCategory.Error, "Duplicate_function_implementation_2393", "Duplicate function implementation."), + Overload_signature_is_not_compatible_with_function_implementation: diag(2394, ts.DiagnosticCategory.Error, "Overload_signature_is_not_compatible_with_function_implementation_2394", "Overload signature is not compatible with function implementation."), + Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local: diag(2395, ts.DiagnosticCategory.Error, "Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local_2395", "Individual declarations in merged declaration '{0}' must be all exported or all local."), + Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters: diag(2396, ts.DiagnosticCategory.Error, "Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters_2396", "Duplicate identifier 'arguments'. Compiler uses 'arguments' to initialize rest parameters."), + Declaration_name_conflicts_with_built_in_global_identifier_0: diag(2397, ts.DiagnosticCategory.Error, "Declaration_name_conflicts_with_built_in_global_identifier_0_2397", "Declaration name conflicts with built-in global identifier '{0}'."), + Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference: diag(2399, ts.DiagnosticCategory.Error, "Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference_2399", "Duplicate identifier '_this'. Compiler uses variable declaration '_this' to capture 'this' reference."), + Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference: diag(2400, ts.DiagnosticCategory.Error, "Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference_2400", "Expression resolves to variable declaration '_this' that compiler uses to capture 'this' reference."), + Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference: diag(2401, ts.DiagnosticCategory.Error, "Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference_2401", "Duplicate identifier '_super'. Compiler uses '_super' to capture base class reference."), + Expression_resolves_to_super_that_compiler_uses_to_capture_base_class_reference: diag(2402, ts.DiagnosticCategory.Error, "Expression_resolves_to_super_that_compiler_uses_to_capture_base_class_reference_2402", "Expression resolves to '_super' that compiler uses to capture base class reference."), + Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2: diag(2403, ts.DiagnosticCategory.Error, "Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_t_2403", "Subsequent variable declarations must have the same type. Variable '{0}' must be of type '{1}', but here has type '{2}'."), + The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation: diag(2404, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation_2404", "The left-hand side of a 'for...in' statement cannot use a type annotation."), + The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any: diag(2405, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any_2405", "The left-hand side of a 'for...in' statement must be of type 'string' or 'any'."), + The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access: diag(2406, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access_2406", "The left-hand side of a 'for...in' statement must be a variable or a property access."), + The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_but_here_has_type_0: diag(2407, ts.DiagnosticCategory.Error, "The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_but_2407", "The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter, but here has type '{0}'."), + Setters_cannot_return_a_value: diag(2408, ts.DiagnosticCategory.Error, "Setters_cannot_return_a_value_2408", "Setters cannot return a value."), + Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class: diag(2409, ts.DiagnosticCategory.Error, "Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class_2409", "Return type of constructor signature must be assignable to the instance type of the class."), + The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any: diag(2410, ts.DiagnosticCategory.Error, "The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any_2410", "The 'with' statement is not supported. All symbols in a 'with' block will have type 'any'."), + Property_0_of_type_1_is_not_assignable_to_string_index_type_2: diag(2411, ts.DiagnosticCategory.Error, "Property_0_of_type_1_is_not_assignable_to_string_index_type_2_2411", "Property '{0}' of type '{1}' is not assignable to string index type '{2}'."), + Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2: diag(2412, ts.DiagnosticCategory.Error, "Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2_2412", "Property '{0}' of type '{1}' is not assignable to numeric index type '{2}'."), + Numeric_index_type_0_is_not_assignable_to_string_index_type_1: diag(2413, ts.DiagnosticCategory.Error, "Numeric_index_type_0_is_not_assignable_to_string_index_type_1_2413", "Numeric index type '{0}' is not assignable to string index type '{1}'."), + Class_name_cannot_be_0: diag(2414, ts.DiagnosticCategory.Error, "Class_name_cannot_be_0_2414", "Class name cannot be '{0}'."), + Class_0_incorrectly_extends_base_class_1: diag(2415, ts.DiagnosticCategory.Error, "Class_0_incorrectly_extends_base_class_1_2415", "Class '{0}' incorrectly extends base class '{1}'."), + Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2: diag(2416, ts.DiagnosticCategory.Error, "Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2_2416", "Property '{0}' in type '{1}' is not assignable to the same property in base type '{2}'."), + Class_static_side_0_incorrectly_extends_base_class_static_side_1: diag(2417, ts.DiagnosticCategory.Error, "Class_static_side_0_incorrectly_extends_base_class_static_side_1_2417", "Class static side '{0}' incorrectly extends base class static side '{1}'."), + Type_of_computed_property_s_value_is_0_which_is_not_assignable_to_type_1: diag(2418, ts.DiagnosticCategory.Error, "Type_of_computed_property_s_value_is_0_which_is_not_assignable_to_type_1_2418", "Type of computed property's value is '{0}', which is not assignable to type '{1}'."), + Class_0_incorrectly_implements_interface_1: diag(2420, ts.DiagnosticCategory.Error, "Class_0_incorrectly_implements_interface_1_2420", "Class '{0}' incorrectly implements interface '{1}'."), + A_class_can_only_implement_an_object_type_or_intersection_of_object_types_with_statically_known_members: diag(2422, ts.DiagnosticCategory.Error, "A_class_can_only_implement_an_object_type_or_intersection_of_object_types_with_statically_known_memb_2422", "A class can only implement an object type or intersection of object types with statically known members."), + Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor: diag(2423, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_access_2423", "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member accessor."), + Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_property: diag(2424, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_proper_2424", "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member property."), + Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_function: diag(2425, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_functi_2425", "Class '{0}' defines instance member property '{1}', but extended class '{2}' defines it as instance member function."), + Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function: diag(2426, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_functi_2426", "Class '{0}' defines instance member accessor '{1}', but extended class '{2}' defines it as instance member function."), + Interface_name_cannot_be_0: diag(2427, ts.DiagnosticCategory.Error, "Interface_name_cannot_be_0_2427", "Interface name cannot be '{0}'."), + All_declarations_of_0_must_have_identical_type_parameters: diag(2428, ts.DiagnosticCategory.Error, "All_declarations_of_0_must_have_identical_type_parameters_2428", "All declarations of '{0}' must have identical type parameters."), + Interface_0_incorrectly_extends_interface_1: diag(2430, ts.DiagnosticCategory.Error, "Interface_0_incorrectly_extends_interface_1_2430", "Interface '{0}' incorrectly extends interface '{1}'."), + Enum_name_cannot_be_0: diag(2431, ts.DiagnosticCategory.Error, "Enum_name_cannot_be_0_2431", "Enum name cannot be '{0}'."), + In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enum_element: diag(2432, ts.DiagnosticCategory.Error, "In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enu_2432", "In an enum with multiple declarations, only one declaration can omit an initializer for its first enum element."), + A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merged: diag(2433, ts.DiagnosticCategory.Error, "A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merg_2433", "A namespace declaration cannot be in a different file from a class or function with which it is merged."), + A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged: diag(2434, ts.DiagnosticCategory.Error, "A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged_2434", "A namespace declaration cannot be located prior to a class or function with which it is merged."), + Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces: diag(2435, ts.DiagnosticCategory.Error, "Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces_2435", "Ambient modules cannot be nested in other modules or namespaces."), + Ambient_module_declaration_cannot_specify_relative_module_name: diag(2436, ts.DiagnosticCategory.Error, "Ambient_module_declaration_cannot_specify_relative_module_name_2436", "Ambient module declaration cannot specify relative module name."), + Module_0_is_hidden_by_a_local_declaration_with_the_same_name: diag(2437, ts.DiagnosticCategory.Error, "Module_0_is_hidden_by_a_local_declaration_with_the_same_name_2437", "Module '{0}' is hidden by a local declaration with the same name."), + Import_name_cannot_be_0: diag(2438, ts.DiagnosticCategory.Error, "Import_name_cannot_be_0_2438", "Import name cannot be '{0}'."), + Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relative_module_name: diag(2439, ts.DiagnosticCategory.Error, "Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relati_2439", "Import or export declaration in an ambient module declaration cannot reference module through relative module name."), + Import_declaration_conflicts_with_local_declaration_of_0: diag(2440, ts.DiagnosticCategory.Error, "Import_declaration_conflicts_with_local_declaration_of_0_2440", "Import declaration conflicts with local declaration of '{0}'."), + Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module: diag(2441, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_2441", "Duplicate identifier '{0}'. Compiler reserves name '{1}' in top level scope of a module."), + Types_have_separate_declarations_of_a_private_property_0: diag(2442, ts.DiagnosticCategory.Error, "Types_have_separate_declarations_of_a_private_property_0_2442", "Types have separate declarations of a private property '{0}'."), + Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2: diag(2443, ts.DiagnosticCategory.Error, "Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2_2443", "Property '{0}' is protected but type '{1}' is not a class derived from '{2}'."), + Property_0_is_protected_in_type_1_but_public_in_type_2: diag(2444, ts.DiagnosticCategory.Error, "Property_0_is_protected_in_type_1_but_public_in_type_2_2444", "Property '{0}' is protected in type '{1}' but public in type '{2}'."), + Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses: diag(2445, ts.DiagnosticCategory.Error, "Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses_2445", "Property '{0}' is protected and only accessible within class '{1}' and its subclasses."), + Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1: diag(2446, ts.DiagnosticCategory.Error, "Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1_2446", "Property '{0}' is protected and only accessible through an instance of class '{1}'."), + The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead: diag(2447, ts.DiagnosticCategory.Error, "The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead_2447", "The '{0}' operator is not allowed for boolean types. Consider using '{1}' instead."), + Block_scoped_variable_0_used_before_its_declaration: diag(2448, ts.DiagnosticCategory.Error, "Block_scoped_variable_0_used_before_its_declaration_2448", "Block-scoped variable '{0}' used before its declaration."), + Class_0_used_before_its_declaration: diag(2449, ts.DiagnosticCategory.Error, "Class_0_used_before_its_declaration_2449", "Class '{0}' used before its declaration."), + Enum_0_used_before_its_declaration: diag(2450, ts.DiagnosticCategory.Error, "Enum_0_used_before_its_declaration_2450", "Enum '{0}' used before its declaration."), + Cannot_redeclare_block_scoped_variable_0: diag(2451, ts.DiagnosticCategory.Error, "Cannot_redeclare_block_scoped_variable_0_2451", "Cannot redeclare block-scoped variable '{0}'."), + An_enum_member_cannot_have_a_numeric_name: diag(2452, ts.DiagnosticCategory.Error, "An_enum_member_cannot_have_a_numeric_name_2452", "An enum member cannot have a numeric name."), + The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_type_arguments_explicitly: diag(2453, ts.DiagnosticCategory.Error, "The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_typ_2453", "The type argument for type parameter '{0}' cannot be inferred from the usage. Consider specifying the type arguments explicitly."), + Variable_0_is_used_before_being_assigned: diag(2454, ts.DiagnosticCategory.Error, "Variable_0_is_used_before_being_assigned_2454", "Variable '{0}' is used before being assigned."), + Type_argument_candidate_1_is_not_a_valid_type_argument_because_it_is_not_a_supertype_of_candidate_0: diag(2455, ts.DiagnosticCategory.Error, "Type_argument_candidate_1_is_not_a_valid_type_argument_because_it_is_not_a_supertype_of_candidate_0_2455", "Type argument candidate '{1}' is not a valid type argument because it is not a supertype of candidate '{0}'."), + Type_alias_0_circularly_references_itself: diag(2456, ts.DiagnosticCategory.Error, "Type_alias_0_circularly_references_itself_2456", "Type alias '{0}' circularly references itself."), + Type_alias_name_cannot_be_0: diag(2457, ts.DiagnosticCategory.Error, "Type_alias_name_cannot_be_0_2457", "Type alias name cannot be '{0}'."), + An_AMD_module_cannot_have_multiple_name_assignments: diag(2458, ts.DiagnosticCategory.Error, "An_AMD_module_cannot_have_multiple_name_assignments_2458", "An AMD module cannot have multiple name assignments."), + Type_0_has_no_property_1_and_no_string_index_signature: diag(2459, ts.DiagnosticCategory.Error, "Type_0_has_no_property_1_and_no_string_index_signature_2459", "Type '{0}' has no property '{1}' and no string index signature."), + Type_0_has_no_property_1: diag(2460, ts.DiagnosticCategory.Error, "Type_0_has_no_property_1_2460", "Type '{0}' has no property '{1}'."), + Type_0_is_not_an_array_type: diag(2461, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_2461", "Type '{0}' is not an array type."), + A_rest_element_must_be_last_in_a_destructuring_pattern: diag(2462, ts.DiagnosticCategory.Error, "A_rest_element_must_be_last_in_a_destructuring_pattern_2462", "A rest element must be last in a destructuring pattern."), + A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature: diag(2463, ts.DiagnosticCategory.Error, "A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature_2463", "A binding pattern parameter cannot be optional in an implementation signature."), + A_computed_property_name_must_be_of_type_string_number_symbol_or_any: diag(2464, ts.DiagnosticCategory.Error, "A_computed_property_name_must_be_of_type_string_number_symbol_or_any_2464", "A computed property name must be of type 'string', 'number', 'symbol', or 'any'."), + this_cannot_be_referenced_in_a_computed_property_name: diag(2465, ts.DiagnosticCategory.Error, "this_cannot_be_referenced_in_a_computed_property_name_2465", "'this' cannot be referenced in a computed property name."), + super_cannot_be_referenced_in_a_computed_property_name: diag(2466, ts.DiagnosticCategory.Error, "super_cannot_be_referenced_in_a_computed_property_name_2466", "'super' cannot be referenced in a computed property name."), + A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type: diag(2467, ts.DiagnosticCategory.Error, "A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type_2467", "A computed property name cannot reference a type parameter from its containing type."), + Cannot_find_global_value_0: diag(2468, ts.DiagnosticCategory.Error, "Cannot_find_global_value_0_2468", "Cannot find global value '{0}'."), + The_0_operator_cannot_be_applied_to_type_symbol: diag(2469, ts.DiagnosticCategory.Error, "The_0_operator_cannot_be_applied_to_type_symbol_2469", "The '{0}' operator cannot be applied to type 'symbol'."), + Symbol_reference_does_not_refer_to_the_global_Symbol_constructor_object: diag(2470, ts.DiagnosticCategory.Error, "Symbol_reference_does_not_refer_to_the_global_Symbol_constructor_object_2470", "'Symbol' reference does not refer to the global Symbol constructor object."), + A_computed_property_name_of_the_form_0_must_be_of_type_symbol: diag(2471, ts.DiagnosticCategory.Error, "A_computed_property_name_of_the_form_0_must_be_of_type_symbol_2471", "A computed property name of the form '{0}' must be of type 'symbol'."), + Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher: diag(2472, ts.DiagnosticCategory.Error, "Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher_2472", "Spread operator in 'new' expressions is only available when targeting ECMAScript 5 and higher."), + Enum_declarations_must_all_be_const_or_non_const: diag(2473, ts.DiagnosticCategory.Error, "Enum_declarations_must_all_be_const_or_non_const_2473", "Enum declarations must all be const or non-const."), + In_const_enum_declarations_member_initializer_must_be_constant_expression: diag(2474, ts.DiagnosticCategory.Error, "In_const_enum_declarations_member_initializer_must_be_constant_expression_2474", "In 'const' enum declarations member initializer must be constant expression."), + const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment_or_type_query: diag(2475, ts.DiagnosticCategory.Error, "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475", "'const' enums can only be used in property or index access expressions or the right hand side of an import declaration or export assignment or type query."), + A_const_enum_member_can_only_be_accessed_using_a_string_literal: diag(2476, ts.DiagnosticCategory.Error, "A_const_enum_member_can_only_be_accessed_using_a_string_literal_2476", "A const enum member can only be accessed using a string literal."), + const_enum_member_initializer_was_evaluated_to_a_non_finite_value: diag(2477, ts.DiagnosticCategory.Error, "const_enum_member_initializer_was_evaluated_to_a_non_finite_value_2477", "'const' enum member initializer was evaluated to a non-finite value."), + const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN: diag(2478, ts.DiagnosticCategory.Error, "const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN_2478", "'const' enum member initializer was evaluated to disallowed value 'NaN'."), + Property_0_does_not_exist_on_const_enum_1: diag(2479, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_const_enum_1_2479", "Property '{0}' does not exist on 'const' enum '{1}'."), + let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations: diag(2480, ts.DiagnosticCategory.Error, "let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations_2480", "'let' is not allowed to be used as a name in 'let' or 'const' declarations."), + Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1: diag(2481, ts.DiagnosticCategory.Error, "Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1_2481", "Cannot initialize outer scoped variable '{0}' in the same scope as block scoped declaration '{1}'."), + The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation: diag(2483, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation_2483", "The left-hand side of a 'for...of' statement cannot use a type annotation."), + Export_declaration_conflicts_with_exported_declaration_of_0: diag(2484, ts.DiagnosticCategory.Error, "Export_declaration_conflicts_with_exported_declaration_of_0_2484", "Export declaration conflicts with exported declaration of '{0}'."), + The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access: diag(2487, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access_2487", "The left-hand side of a 'for...of' statement must be a variable or a property access."), + Type_0_must_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2488, ts.DiagnosticCategory.Error, "Type_0_must_have_a_Symbol_iterator_method_that_returns_an_iterator_2488", "Type '{0}' must have a '[Symbol.iterator]()' method that returns an iterator."), + An_iterator_must_have_a_next_method: diag(2489, ts.DiagnosticCategory.Error, "An_iterator_must_have_a_next_method_2489", "An iterator must have a 'next()' method."), + The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property: diag(2490, ts.DiagnosticCategory.Error, "The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property_2490", "The type returned by the 'next()' method of an iterator must have a 'value' property."), + The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern: diag(2491, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern_2491", "The left-hand side of a 'for...in' statement cannot be a destructuring pattern."), + Cannot_redeclare_identifier_0_in_catch_clause: diag(2492, ts.DiagnosticCategory.Error, "Cannot_redeclare_identifier_0_in_catch_clause_2492", "Cannot redeclare identifier '{0}' in catch clause."), + Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2: diag(2493, ts.DiagnosticCategory.Error, "Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2_2493", "Tuple type '{0}' with length '{1}' cannot be assigned to tuple with length '{2}'."), + Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher: diag(2494, ts.DiagnosticCategory.Error, "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494", "Using a string in a 'for...of' statement is only supported in ECMAScript 5 and higher."), + Type_0_is_not_an_array_type_or_a_string_type: diag(2495, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_a_string_type_2495", "Type '{0}' is not an array type or a string type."), + The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_standard_function_expression: diag(2496, ts.DiagnosticCategory.Error, "The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_stand_2496", "The 'arguments' object cannot be referenced in an arrow function in ES3 and ES5. Consider using a standard function expression."), + Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct: diag(2497, ts.DiagnosticCategory.Error, "Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct_2497", "Module '{0}' resolves to a non-module entity and cannot be imported using this construct."), + Module_0_uses_export_and_cannot_be_used_with_export_Asterisk: diag(2498, ts.DiagnosticCategory.Error, "Module_0_uses_export_and_cannot_be_used_with_export_Asterisk_2498", "Module '{0}' uses 'export =' and cannot be used with 'export *'."), + An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments: diag(2499, ts.DiagnosticCategory.Error, "An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments_2499", "An interface can only extend an identifier/qualified-name with optional type arguments."), + A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments: diag(2500, ts.DiagnosticCategory.Error, "A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments_2500", "A class can only implement an identifier/qualified-name with optional type arguments."), + A_rest_element_cannot_contain_a_binding_pattern: diag(2501, ts.DiagnosticCategory.Error, "A_rest_element_cannot_contain_a_binding_pattern_2501", "A rest element cannot contain a binding pattern."), + _0_is_referenced_directly_or_indirectly_in_its_own_type_annotation: diag(2502, ts.DiagnosticCategory.Error, "_0_is_referenced_directly_or_indirectly_in_its_own_type_annotation_2502", "'{0}' is referenced directly or indirectly in its own type annotation."), + Cannot_find_namespace_0: diag(2503, ts.DiagnosticCategory.Error, "Cannot_find_namespace_0_2503", "Cannot find namespace '{0}'."), + Type_0_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator: diag(2504, ts.DiagnosticCategory.Error, "Type_0_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator_2504", "Type '{0}' must have a '[Symbol.asyncIterator]()' method that returns an async iterator."), + A_generator_cannot_have_a_void_type_annotation: diag(2505, ts.DiagnosticCategory.Error, "A_generator_cannot_have_a_void_type_annotation_2505", "A generator cannot have a 'void' type annotation."), + _0_is_referenced_directly_or_indirectly_in_its_own_base_expression: diag(2506, ts.DiagnosticCategory.Error, "_0_is_referenced_directly_or_indirectly_in_its_own_base_expression_2506", "'{0}' is referenced directly or indirectly in its own base expression."), + Type_0_is_not_a_constructor_function_type: diag(2507, ts.DiagnosticCategory.Error, "Type_0_is_not_a_constructor_function_type_2507", "Type '{0}' is not a constructor function type."), + No_base_constructor_has_the_specified_number_of_type_arguments: diag(2508, ts.DiagnosticCategory.Error, "No_base_constructor_has_the_specified_number_of_type_arguments_2508", "No base constructor has the specified number of type arguments."), + Base_constructor_return_type_0_is_not_an_object_type_or_intersection_of_object_types_with_statically_known_members: diag(2509, ts.DiagnosticCategory.Error, "Base_constructor_return_type_0_is_not_an_object_type_or_intersection_of_object_types_with_statically_2509", "Base constructor return type '{0}' is not an object type or intersection of object types with statically known members."), + Base_constructors_must_all_have_the_same_return_type: diag(2510, ts.DiagnosticCategory.Error, "Base_constructors_must_all_have_the_same_return_type_2510", "Base constructors must all have the same return type."), + Cannot_create_an_instance_of_an_abstract_class: diag(2511, ts.DiagnosticCategory.Error, "Cannot_create_an_instance_of_an_abstract_class_2511", "Cannot create an instance of an abstract class."), + Overload_signatures_must_all_be_abstract_or_non_abstract: diag(2512, ts.DiagnosticCategory.Error, "Overload_signatures_must_all_be_abstract_or_non_abstract_2512", "Overload signatures must all be abstract or non-abstract."), + Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression: diag(2513, ts.DiagnosticCategory.Error, "Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression_2513", "Abstract method '{0}' in class '{1}' cannot be accessed via super expression."), + Classes_containing_abstract_methods_must_be_marked_abstract: diag(2514, ts.DiagnosticCategory.Error, "Classes_containing_abstract_methods_must_be_marked_abstract_2514", "Classes containing abstract methods must be marked abstract."), + Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2: diag(2515, ts.DiagnosticCategory.Error, "Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2_2515", "Non-abstract class '{0}' does not implement inherited abstract member '{1}' from class '{2}'."), + All_declarations_of_an_abstract_method_must_be_consecutive: diag(2516, ts.DiagnosticCategory.Error, "All_declarations_of_an_abstract_method_must_be_consecutive_2516", "All declarations of an abstract method must be consecutive."), + Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type: diag(2517, ts.DiagnosticCategory.Error, "Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type_2517", "Cannot assign an abstract constructor type to a non-abstract constructor type."), + A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard: diag(2518, ts.DiagnosticCategory.Error, "A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard_2518", "A 'this'-based type guard is not compatible with a parameter-based type guard."), + An_async_iterator_must_have_a_next_method: diag(2519, ts.DiagnosticCategory.Error, "An_async_iterator_must_have_a_next_method_2519", "An async iterator must have a 'next()' method."), + Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions: diag(2520, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions_2520", "Duplicate identifier '{0}'. Compiler uses declaration '{1}' to support async functions."), + Expression_resolves_to_variable_declaration_0_that_compiler_uses_to_support_async_functions: diag(2521, ts.DiagnosticCategory.Error, "Expression_resolves_to_variable_declaration_0_that_compiler_uses_to_support_async_functions_2521", "Expression resolves to variable declaration '{0}' that compiler uses to support async functions."), + The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_using_a_standard_function_or_method: diag(2522, ts.DiagnosticCategory.Error, "The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_usi_2522", "The 'arguments' object cannot be referenced in an async function or method in ES3 and ES5. Consider using a standard function or method."), + yield_expressions_cannot_be_used_in_a_parameter_initializer: diag(2523, ts.DiagnosticCategory.Error, "yield_expressions_cannot_be_used_in_a_parameter_initializer_2523", "'yield' expressions cannot be used in a parameter initializer."), + await_expressions_cannot_be_used_in_a_parameter_initializer: diag(2524, ts.DiagnosticCategory.Error, "await_expressions_cannot_be_used_in_a_parameter_initializer_2524", "'await' expressions cannot be used in a parameter initializer."), + Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value: diag(2525, ts.DiagnosticCategory.Error, "Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value_2525", "Initializer provides no value for this binding element and the binding element has no default value."), + A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface: diag(2526, ts.DiagnosticCategory.Error, "A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface_2526", "A 'this' type is available only in a non-static member of a class or interface."), + The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary: diag(2527, ts.DiagnosticCategory.Error, "The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary_2527", "The inferred type of '{0}' references an inaccessible '{1}' type. A type annotation is necessary."), + A_module_cannot_have_multiple_default_exports: diag(2528, ts.DiagnosticCategory.Error, "A_module_cannot_have_multiple_default_exports_2528", "A module cannot have multiple default exports."), + Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_functions: diag(2529, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_func_2529", "Duplicate identifier '{0}'. Compiler reserves name '{1}' in top level scope of a module containing async functions."), + Property_0_is_incompatible_with_index_signature: diag(2530, ts.DiagnosticCategory.Error, "Property_0_is_incompatible_with_index_signature_2530", "Property '{0}' is incompatible with index signature."), + Object_is_possibly_null: diag(2531, ts.DiagnosticCategory.Error, "Object_is_possibly_null_2531", "Object is possibly 'null'."), + Object_is_possibly_undefined: diag(2532, ts.DiagnosticCategory.Error, "Object_is_possibly_undefined_2532", "Object is possibly 'undefined'."), + Object_is_possibly_null_or_undefined: diag(2533, ts.DiagnosticCategory.Error, "Object_is_possibly_null_or_undefined_2533", "Object is possibly 'null' or 'undefined'."), + A_function_returning_never_cannot_have_a_reachable_end_point: diag(2534, ts.DiagnosticCategory.Error, "A_function_returning_never_cannot_have_a_reachable_end_point_2534", "A function returning 'never' cannot have a reachable end point."), + Enum_type_0_has_members_with_initializers_that_are_not_literals: diag(2535, ts.DiagnosticCategory.Error, "Enum_type_0_has_members_with_initializers_that_are_not_literals_2535", "Enum type '{0}' has members with initializers that are not literals."), + Type_0_cannot_be_used_to_index_type_1: diag(2536, ts.DiagnosticCategory.Error, "Type_0_cannot_be_used_to_index_type_1_2536", "Type '{0}' cannot be used to index type '{1}'."), + Type_0_has_no_matching_index_signature_for_type_1: diag(2537, ts.DiagnosticCategory.Error, "Type_0_has_no_matching_index_signature_for_type_1_2537", "Type '{0}' has no matching index signature for type '{1}'."), + Type_0_cannot_be_used_as_an_index_type: diag(2538, ts.DiagnosticCategory.Error, "Type_0_cannot_be_used_as_an_index_type_2538", "Type '{0}' cannot be used as an index type."), + Cannot_assign_to_0_because_it_is_not_a_variable: diag(2539, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_not_a_variable_2539", "Cannot assign to '{0}' because it is not a variable."), + Cannot_assign_to_0_because_it_is_a_read_only_property: diag(2540, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_a_read_only_property_2540", "Cannot assign to '{0}' because it is a read-only property."), + The_target_of_an_assignment_must_be_a_variable_or_a_property_access: diag(2541, ts.DiagnosticCategory.Error, "The_target_of_an_assignment_must_be_a_variable_or_a_property_access_2541", "The target of an assignment must be a variable or a property access."), + Index_signature_in_type_0_only_permits_reading: diag(2542, ts.DiagnosticCategory.Error, "Index_signature_in_type_0_only_permits_reading_2542", "Index signature in type '{0}' only permits reading."), + Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference: diag(2543, ts.DiagnosticCategory.Error, "Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_me_2543", "Duplicate identifier '_newTarget'. Compiler uses variable declaration '_newTarget' to capture 'new.target' meta-property reference."), + Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta_property_reference: diag(2544, ts.DiagnosticCategory.Error, "Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta__2544", "Expression resolves to variable declaration '_newTarget' that compiler uses to capture 'new.target' meta-property reference."), + A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any: diag(2545, ts.DiagnosticCategory.Error, "A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any_2545", "A mixin class must have a constructor with a single rest parameter of type 'any[]'."), + Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1: diag(2546, ts.DiagnosticCategory.Error, "Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1_2546", "Property '{0}' has conflicting declarations and is inaccessible in type '{1}'."), + The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property: diag(2547, ts.DiagnosticCategory.Error, "The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value__2547", "The type returned by the 'next()' method of an async iterator must be a promise for a type with a 'value' property."), + Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2548, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548", "Type '{0}' is not an array type or does not have a '[Symbol.iterator]()' method that returns an iterator."), + Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2549, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549", "Type '{0}' is not an array type or a string type or does not have a '[Symbol.iterator]()' method that returns an iterator."), + Property_0_does_not_exist_on_type_1_Did_you_mean_2: diag(2551, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551", "Property '{0}' does not exist on type '{1}'. Did you mean '{2}'?"), + Cannot_find_name_0_Did_you_mean_1: diag(2552, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Did_you_mean_1_2552", "Cannot find name '{0}'. Did you mean '{1}'?"), + Computed_values_are_not_permitted_in_an_enum_with_string_valued_members: diag(2553, ts.DiagnosticCategory.Error, "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553", "Computed values are not permitted in an enum with string valued members."), + Expected_0_arguments_but_got_1: diag(2554, ts.DiagnosticCategory.Error, "Expected_0_arguments_but_got_1_2554", "Expected {0} arguments, but got {1}."), + Expected_at_least_0_arguments_but_got_1: diag(2555, ts.DiagnosticCategory.Error, "Expected_at_least_0_arguments_but_got_1_2555", "Expected at least {0} arguments, but got {1}."), + Expected_0_arguments_but_got_1_or_more: diag(2556, ts.DiagnosticCategory.Error, "Expected_0_arguments_but_got_1_or_more_2556", "Expected {0} arguments, but got {1} or more."), + Expected_at_least_0_arguments_but_got_1_or_more: diag(2557, ts.DiagnosticCategory.Error, "Expected_at_least_0_arguments_but_got_1_or_more_2557", "Expected at least {0} arguments, but got {1} or more."), + Expected_0_type_arguments_but_got_1: diag(2558, ts.DiagnosticCategory.Error, "Expected_0_type_arguments_but_got_1_2558", "Expected {0} type arguments, but got {1}."), + Type_0_has_no_properties_in_common_with_type_1: diag(2559, ts.DiagnosticCategory.Error, "Type_0_has_no_properties_in_common_with_type_1_2559", "Type '{0}' has no properties in common with type '{1}'."), + Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it: diag(2560, ts.DiagnosticCategory.Error, "Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it_2560", "Value of type '{0}' has no properties in common with type '{1}'. Did you mean to call it?"), + Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_write_2: diag(2561, ts.DiagnosticCategory.Error, "Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_writ_2561", "Object literal may only specify known properties, but '{0}' does not exist in type '{1}'. Did you mean to write '{2}'?"), + Base_class_expressions_cannot_reference_class_type_parameters: diag(2562, ts.DiagnosticCategory.Error, "Base_class_expressions_cannot_reference_class_type_parameters_2562", "Base class expressions cannot reference class type parameters."), + The_containing_function_or_module_body_is_too_large_for_control_flow_analysis: diag(2563, ts.DiagnosticCategory.Error, "The_containing_function_or_module_body_is_too_large_for_control_flow_analysis_2563", "The containing function or module body is too large for control flow analysis."), + Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor: diag(2564, ts.DiagnosticCategory.Error, "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor_2564", "Property '{0}' has no initializer and is not definitely assigned in the constructor."), + Property_0_is_used_before_being_assigned: diag(2565, ts.DiagnosticCategory.Error, "Property_0_is_used_before_being_assigned_2565", "Property '{0}' is used before being assigned."), + A_rest_element_cannot_have_a_property_name: diag(2566, ts.DiagnosticCategory.Error, "A_rest_element_cannot_have_a_property_name_2566", "A rest element cannot have a property name."), + Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations: diag(2567, ts.DiagnosticCategory.Error, "Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations_2567", "Enum declarations can only merge with namespace or other enum declarations."), + Type_0_is_not_an_array_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators: diag(2568, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators_2568", "Type '{0}' is not an array type. Use compiler option '--downlevelIteration' to allow iterating of iterators."), + Type_0_is_not_an_array_type_or_a_string_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators: diag(2569, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_a_string_type_Use_compiler_option_downlevelIteration_to_allow_iterati_2569", "Type '{0}' is not an array type or a string type. Use compiler option '--downlevelIteration' to allow iterating of iterators."), + Property_0_does_not_exist_on_type_1_Did_you_forget_to_use_await: diag(2570, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_Did_you_forget_to_use_await_2570", "Property '{0}' does not exist on type '{1}'. Did you forget to use 'await'?"), + Object_is_of_type_unknown: diag(2571, ts.DiagnosticCategory.Error, "Object_is_of_type_unknown_2571", "Object is of type 'unknown'."), + Rest_signatures_are_incompatible: diag(2572, ts.DiagnosticCategory.Error, "Rest_signatures_are_incompatible_2572", "Rest signatures are incompatible."), + Property_0_is_incompatible_with_rest_element_type: diag(2573, ts.DiagnosticCategory.Error, "Property_0_is_incompatible_with_rest_element_type_2573", "Property '{0}' is incompatible with rest element type."), + A_rest_element_type_must_be_an_array_type: diag(2574, ts.DiagnosticCategory.Error, "A_rest_element_type_must_be_an_array_type_2574", "A rest element type must be an array type."), + No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments: diag(2575, ts.DiagnosticCategory.Error, "No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments_2575", "No overload expects {0} arguments, but overloads do exist that expect either {1} or {2} arguments."), + Property_0_is_a_static_member_of_type_1: diag(2576, ts.DiagnosticCategory.Error, "Property_0_is_a_static_member_of_type_1_2576", "Property '{0}' is a static member of type '{1}'"), + Return_type_annotation_circularly_references_itself: diag(2577, ts.DiagnosticCategory.Error, "Return_type_annotation_circularly_references_itself_2577", "Return type annotation circularly references itself."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_and_then_add_node_to_the_types_field_in_your_tsconfig: diag(2580, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_and_th_2580", "Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i @types/node` and then add `node` to the types field in your tsconfig."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_and_then_add_jquery_to_the_types_field_in_your_tsconfig: diag(2581, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_an_2581", "Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i @types/jquery` and then add `jquery` to the types field in your tsconfig."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha_and_then_add_jest_or_mocha_to_the_types_field_in_your_tsconfig: diag(2582, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashje_2582", "Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha` and then add `jest` or `mocha` to the types field in your tsconfig."), + Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later: diag(2583, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2583", "Cannot find name '{0}'. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later."), + Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom: diag(2584, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2584", "Cannot find name '{0}'. Do you need to change your target library? Try changing the `lib` compiler option to include 'dom'."), + _0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later: diag(2585, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_2585", "'{0}' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later."), + Enum_type_0_circularly_references_itself: diag(2586, ts.DiagnosticCategory.Error, "Enum_type_0_circularly_references_itself_2586", "Enum type '{0}' circularly references itself."), + JSDoc_type_0_circularly_references_itself: diag(2587, ts.DiagnosticCategory.Error, "JSDoc_type_0_circularly_references_itself_2587", "JSDoc type '{0}' circularly references itself."), + Cannot_assign_to_0_because_it_is_a_constant: diag(2588, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_a_constant_2588", "Cannot assign to '{0}' because it is a constant."), + JSX_element_attributes_type_0_may_not_be_a_union_type: diag(2600, ts.DiagnosticCategory.Error, "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", "JSX element attributes type '{0}' may not be a union type."), + The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: diag(2601, ts.DiagnosticCategory.Error, "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", "The return type of a JSX element constructor must return an object type."), + JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: diag(2602, ts.DiagnosticCategory.Error, "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist."), + Property_0_in_type_1_is_not_assignable_to_type_2: diag(2603, ts.DiagnosticCategory.Error, "Property_0_in_type_1_is_not_assignable_to_type_2_2603", "Property '{0}' in type '{1}' is not assignable to type '{2}'."), + JSX_element_type_0_does_not_have_any_construct_or_call_signatures: diag(2604, ts.DiagnosticCategory.Error, "JSX_element_type_0_does_not_have_any_construct_or_call_signatures_2604", "JSX element type '{0}' does not have any construct or call signatures."), + JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements: diag(2605, ts.DiagnosticCategory.Error, "JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements_2605", "JSX element type '{0}' is not a constructor function for JSX elements."), + Property_0_of_JSX_spread_attribute_is_not_assignable_to_target_property: diag(2606, ts.DiagnosticCategory.Error, "Property_0_of_JSX_spread_attribute_is_not_assignable_to_target_property_2606", "Property '{0}' of JSX spread attribute is not assignable to target property."), + JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property: diag(2607, ts.DiagnosticCategory.Error, "JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property_2607", "JSX element class does not support attributes because it does not have a '{0}' property."), + The_global_type_JSX_0_may_not_have_more_than_one_property: diag(2608, ts.DiagnosticCategory.Error, "The_global_type_JSX_0_may_not_have_more_than_one_property_2608", "The global type 'JSX.{0}' may not have more than one property."), + JSX_spread_child_must_be_an_array_type: diag(2609, ts.DiagnosticCategory.Error, "JSX_spread_child_must_be_an_array_type_2609", "JSX spread child must be an array type."), + Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity: diag(2649, ts.DiagnosticCategory.Error, "Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity_2649", "Cannot augment module '{0}' with value exports because it resolves to a non-module entity."), + A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums: diag(2651, ts.DiagnosticCategory.Error, "A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_memb_2651", "A member initializer in a enum declaration cannot reference members declared after it, including members defined in other enums."), + Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead: diag(2652, ts.DiagnosticCategory.Error, "Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_d_2652", "Merged declaration '{0}' cannot include a default export declaration. Consider adding a separate 'export default {0}' declaration instead."), + Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1: diag(2653, ts.DiagnosticCategory.Error, "Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1_2653", "Non-abstract class expression does not implement inherited abstract member '{0}' from class '{1}'."), + Exported_external_package_typings_file_cannot_contain_tripleslash_references_Please_contact_the_package_author_to_update_the_package_definition: diag(2654, ts.DiagnosticCategory.Error, "Exported_external_package_typings_file_cannot_contain_tripleslash_references_Please_contact_the_pack_2654", "Exported external package typings file cannot contain tripleslash references. Please contact the package author to update the package definition."), + Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_the_package_definition: diag(2656, ts.DiagnosticCategory.Error, "Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_2656", "Exported external package typings file '{0}' is not a module. Please contact the package author to update the package definition."), + JSX_expressions_must_have_one_parent_element: diag(2657, ts.DiagnosticCategory.Error, "JSX_expressions_must_have_one_parent_element_2657", "JSX expressions must have one parent element."), + Type_0_provides_no_match_for_the_signature_1: diag(2658, ts.DiagnosticCategory.Error, "Type_0_provides_no_match_for_the_signature_1_2658", "Type '{0}' provides no match for the signature '{1}'."), + super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_higher: diag(2659, ts.DiagnosticCategory.Error, "super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_highe_2659", "'super' is only allowed in members of object literal expressions when option 'target' is 'ES2015' or higher."), + super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions: diag(2660, ts.DiagnosticCategory.Error, "super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions_2660", "'super' can only be referenced in members of derived classes or object literal expressions."), + Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module: diag(2661, ts.DiagnosticCategory.Error, "Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module_2661", "Cannot export '{0}'. Only local declarations can be exported from a module."), + Cannot_find_name_0_Did_you_mean_the_static_member_1_0: diag(2662, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Did_you_mean_the_static_member_1_0_2662", "Cannot find name '{0}'. Did you mean the static member '{1}.{0}'?"), + Cannot_find_name_0_Did_you_mean_the_instance_member_this_0: diag(2663, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Did_you_mean_the_instance_member_this_0_2663", "Cannot find name '{0}'. Did you mean the instance member 'this.{0}'?"), + Invalid_module_name_in_augmentation_module_0_cannot_be_found: diag(2664, ts.DiagnosticCategory.Error, "Invalid_module_name_in_augmentation_module_0_cannot_be_found_2664", "Invalid module name in augmentation, module '{0}' cannot be found."), + Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented: diag(2665, ts.DiagnosticCategory.Error, "Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augm_2665", "Invalid module name in augmentation. Module '{0}' resolves to an untyped module at '{1}', which cannot be augmented."), + Exports_and_export_assignments_are_not_permitted_in_module_augmentations: diag(2666, ts.DiagnosticCategory.Error, "Exports_and_export_assignments_are_not_permitted_in_module_augmentations_2666", "Exports and export assignments are not permitted in module augmentations."), + Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_module: diag(2667, ts.DiagnosticCategory.Error, "Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_mod_2667", "Imports are not permitted in module augmentations. Consider moving them to the enclosing external module."), + export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always_visible: diag(2668, ts.DiagnosticCategory.Error, "export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always__2668", "'export' modifier cannot be applied to ambient modules and module augmentations since they are always visible."), + Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_declarations: diag(2669, ts.DiagnosticCategory.Error, "Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_2669", "Augmentations for the global scope can only be directly nested in external modules or ambient module declarations."), + Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambient_context: diag(2670, ts.DiagnosticCategory.Error, "Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambien_2670", "Augmentations for the global scope should have 'declare' modifier unless they appear in already ambient context."), + Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity: diag(2671, ts.DiagnosticCategory.Error, "Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity_2671", "Cannot augment module '{0}' because it resolves to a non-module entity."), + Cannot_assign_a_0_constructor_type_to_a_1_constructor_type: diag(2672, ts.DiagnosticCategory.Error, "Cannot_assign_a_0_constructor_type_to_a_1_constructor_type_2672", "Cannot assign a '{0}' constructor type to a '{1}' constructor type."), + Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration: diag(2673, ts.DiagnosticCategory.Error, "Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration_2673", "Constructor of class '{0}' is private and only accessible within the class declaration."), + Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration: diag(2674, ts.DiagnosticCategory.Error, "Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration_2674", "Constructor of class '{0}' is protected and only accessible within the class declaration."), + Cannot_extend_a_class_0_Class_constructor_is_marked_as_private: diag(2675, ts.DiagnosticCategory.Error, "Cannot_extend_a_class_0_Class_constructor_is_marked_as_private_2675", "Cannot extend a class '{0}'. Class constructor is marked as private."), + Accessors_must_both_be_abstract_or_non_abstract: diag(2676, ts.DiagnosticCategory.Error, "Accessors_must_both_be_abstract_or_non_abstract_2676", "Accessors must both be abstract or non-abstract."), + A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type: diag(2677, ts.DiagnosticCategory.Error, "A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type_2677", "A type predicate's type must be assignable to its parameter's type."), + Type_0_is_not_comparable_to_type_1: diag(2678, ts.DiagnosticCategory.Error, "Type_0_is_not_comparable_to_type_1_2678", "Type '{0}' is not comparable to type '{1}'."), + A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void: diag(2679, ts.DiagnosticCategory.Error, "A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void_2679", "A function that is called with the 'new' keyword cannot have a 'this' type that is 'void'."), + A_0_parameter_must_be_the_first_parameter: diag(2680, ts.DiagnosticCategory.Error, "A_0_parameter_must_be_the_first_parameter_2680", "A '{0}' parameter must be the first parameter."), + A_constructor_cannot_have_a_this_parameter: diag(2681, ts.DiagnosticCategory.Error, "A_constructor_cannot_have_a_this_parameter_2681", "A constructor cannot have a 'this' parameter."), + get_and_set_accessor_must_have_the_same_this_type: diag(2682, ts.DiagnosticCategory.Error, "get_and_set_accessor_must_have_the_same_this_type_2682", "'get' and 'set' accessor must have the same 'this' type."), + this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation: diag(2683, ts.DiagnosticCategory.Error, "this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_2683", "'this' implicitly has type 'any' because it does not have a type annotation."), + The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1: diag(2684, ts.DiagnosticCategory.Error, "The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1_2684", "The 'this' context of type '{0}' is not assignable to method's 'this' of type '{1}'."), + The_this_types_of_each_signature_are_incompatible: diag(2685, ts.DiagnosticCategory.Error, "The_this_types_of_each_signature_are_incompatible_2685", "The 'this' types of each signature are incompatible."), + _0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead: diag(2686, ts.DiagnosticCategory.Error, "_0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead_2686", "'{0}' refers to a UMD global, but the current file is a module. Consider adding an import instead."), + All_declarations_of_0_must_have_identical_modifiers: diag(2687, ts.DiagnosticCategory.Error, "All_declarations_of_0_must_have_identical_modifiers_2687", "All declarations of '{0}' must have identical modifiers."), + Cannot_find_type_definition_file_for_0: diag(2688, ts.DiagnosticCategory.Error, "Cannot_find_type_definition_file_for_0_2688", "Cannot find type definition file for '{0}'."), + Cannot_extend_an_interface_0_Did_you_mean_implements: diag(2689, ts.DiagnosticCategory.Error, "Cannot_extend_an_interface_0_Did_you_mean_implements_2689", "Cannot extend an interface '{0}'. Did you mean 'implements'?"), + An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead: diag(2691, ts.DiagnosticCategory.Error, "An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead_2691", "An import path cannot end with a '{0}' extension. Consider importing '{1}' instead."), + _0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible: diag(2692, ts.DiagnosticCategory.Error, "_0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible_2692", "'{0}' is a primitive, but '{1}' is a wrapper object. Prefer using '{0}' when possible."), + _0_only_refers_to_a_type_but_is_being_used_as_a_value_here: diag(2693, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_2693", "'{0}' only refers to a type, but is being used as a value here."), + Namespace_0_has_no_exported_member_1: diag(2694, ts.DiagnosticCategory.Error, "Namespace_0_has_no_exported_member_1_2694", "Namespace '{0}' has no exported member '{1}'."), + Left_side_of_comma_operator_is_unused_and_has_no_side_effects: diag(2695, ts.DiagnosticCategory.Error, "Left_side_of_comma_operator_is_unused_and_has_no_side_effects_2695", "Left side of comma operator is unused and has no side effects.", /*reportsUnnecessary*/ true), + The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead: diag(2696, ts.DiagnosticCategory.Error, "The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead_2696", "The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead?"), + An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option: diag(2697, ts.DiagnosticCategory.Error, "An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_in_2697", "An async function or method must return a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your `--lib` option."), + Spread_types_may_only_be_created_from_object_types: diag(2698, ts.DiagnosticCategory.Error, "Spread_types_may_only_be_created_from_object_types_2698", "Spread types may only be created from object types."), + Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1: diag(2699, ts.DiagnosticCategory.Error, "Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1_2699", "Static property '{0}' conflicts with built-in property 'Function.{0}' of constructor function '{1}'."), + Rest_types_may_only_be_created_from_object_types: diag(2700, ts.DiagnosticCategory.Error, "Rest_types_may_only_be_created_from_object_types_2700", "Rest types may only be created from object types."), + The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access: diag(2701, ts.DiagnosticCategory.Error, "The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access_2701", "The target of an object rest assignment must be a variable or a property access."), + _0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here: diag(2702, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here_2702", "'{0}' only refers to a type, but is being used as a namespace here."), + The_operand_of_a_delete_operator_must_be_a_property_reference: diag(2703, ts.DiagnosticCategory.Error, "The_operand_of_a_delete_operator_must_be_a_property_reference_2703", "The operand of a delete operator must be a property reference."), + The_operand_of_a_delete_operator_cannot_be_a_read_only_property: diag(2704, ts.DiagnosticCategory.Error, "The_operand_of_a_delete_operator_cannot_be_a_read_only_property_2704", "The operand of a delete operator cannot be a read-only property."), + An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option: diag(2705, ts.DiagnosticCategory.Error, "An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_de_2705", "An async function or method in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your `--lib` option."), + Required_type_parameters_may_not_follow_optional_type_parameters: diag(2706, ts.DiagnosticCategory.Error, "Required_type_parameters_may_not_follow_optional_type_parameters_2706", "Required type parameters may not follow optional type parameters."), + Generic_type_0_requires_between_1_and_2_type_arguments: diag(2707, ts.DiagnosticCategory.Error, "Generic_type_0_requires_between_1_and_2_type_arguments_2707", "Generic type '{0}' requires between {1} and {2} type arguments."), + Cannot_use_namespace_0_as_a_value: diag(2708, ts.DiagnosticCategory.Error, "Cannot_use_namespace_0_as_a_value_2708", "Cannot use namespace '{0}' as a value."), + Cannot_use_namespace_0_as_a_type: diag(2709, ts.DiagnosticCategory.Error, "Cannot_use_namespace_0_as_a_type_2709", "Cannot use namespace '{0}' as a type."), + _0_are_specified_twice_The_attribute_named_0_will_be_overwritten: diag(2710, ts.DiagnosticCategory.Error, "_0_are_specified_twice_The_attribute_named_0_will_be_overwritten_2710", "'{0}' are specified twice. The attribute named '{0}' will be overwritten."), + A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option: diag(2711, ts.DiagnosticCategory.Error, "A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES20_2711", "A dynamic import call returns a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your `--lib` option."), + A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option: diag(2712, ts.DiagnosticCategory.Error, "A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declarat_2712", "A dynamic import call in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your `--lib` option."), + Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_property_1_in_0_with_0_1: diag(2713, ts.DiagnosticCategory.Error, "Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_p_2713", "Cannot access '{0}.{1}' because '{0}' is a type, but not a namespace. Did you mean to retrieve the type of the property '{1}' in '{0}' with '{0}[\"{1}\"]'?"), + The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context: diag(2714, ts.DiagnosticCategory.Error, "The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context_2714", "The expression of an export assignment must be an identifier or qualified name in an ambient context."), + Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor: diag(2715, ts.DiagnosticCategory.Error, "Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor_2715", "Abstract property '{0}' in class '{1}' cannot be accessed in the constructor."), + Type_parameter_0_has_a_circular_default: diag(2716, ts.DiagnosticCategory.Error, "Type_parameter_0_has_a_circular_default_2716", "Type parameter '{0}' has a circular default."), + Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_type_2: diag(2717, ts.DiagnosticCategory.Error, "Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_t_2717", "Subsequent property declarations must have the same type. Property '{0}' must be of type '{1}', but here has type '{2}'."), + Duplicate_declaration_0: diag(2718, ts.DiagnosticCategory.Error, "Duplicate_declaration_0_2718", "Duplicate declaration '{0}'."), + Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated: diag(2719, ts.DiagnosticCategory.Error, "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_2719", "Type '{0}' is not assignable to type '{1}'. Two different types with this name exist, but they are unrelated."), + Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass: diag(2720, ts.DiagnosticCategory.Error, "Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclas_2720", "Class '{0}' incorrectly implements class '{1}'. Did you mean to extend '{1}' and inherit its members as a subclass?"), + Cannot_invoke_an_object_which_is_possibly_null: diag(2721, ts.DiagnosticCategory.Error, "Cannot_invoke_an_object_which_is_possibly_null_2721", "Cannot invoke an object which is possibly 'null'."), + Cannot_invoke_an_object_which_is_possibly_undefined: diag(2722, ts.DiagnosticCategory.Error, "Cannot_invoke_an_object_which_is_possibly_undefined_2722", "Cannot invoke an object which is possibly 'undefined'."), + Cannot_invoke_an_object_which_is_possibly_null_or_undefined: diag(2723, ts.DiagnosticCategory.Error, "Cannot_invoke_an_object_which_is_possibly_null_or_undefined_2723", "Cannot invoke an object which is possibly 'null' or 'undefined'."), + Module_0_has_no_exported_member_1_Did_you_mean_2: diag(2724, ts.DiagnosticCategory.Error, "Module_0_has_no_exported_member_1_Did_you_mean_2_2724", "Module '{0}' has no exported member '{1}'. Did you mean '{2}'?"), + Class_name_cannot_be_Object_when_targeting_ES5_with_module_0: diag(2725, ts.DiagnosticCategory.Error, "Class_name_cannot_be_Object_when_targeting_ES5_with_module_0_2725", "Class name cannot be 'Object' when targeting ES5 with module {0}."), + Cannot_find_lib_definition_for_0: diag(2726, ts.DiagnosticCategory.Error, "Cannot_find_lib_definition_for_0_2726", "Cannot find lib definition for '{0}'."), + Cannot_find_lib_definition_for_0_Did_you_mean_1: diag(2727, ts.DiagnosticCategory.Error, "Cannot_find_lib_definition_for_0_Did_you_mean_1_2727", "Cannot find lib definition for '{0}'. Did you mean '{1}'?"), + _0_is_declared_here: diag(2728, ts.DiagnosticCategory.Message, "_0_is_declared_here_2728", "'{0}' is declared here."), + Property_0_is_used_before_its_initialization: diag(2729, ts.DiagnosticCategory.Error, "Property_0_is_used_before_its_initialization_2729", "Property '{0}' is used before its initialization."), + An_arrow_function_cannot_have_a_this_parameter: diag(2730, ts.DiagnosticCategory.Error, "An_arrow_function_cannot_have_a_this_parameter_2730", "An arrow function cannot have a 'this' parameter."), + Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_in_String: diag(2731, ts.DiagnosticCategory.Error, "Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_i_2731", "Implicit conversion of a 'symbol' to a 'string' will fail at runtime. Consider wrapping this expression in 'String(...)'."), + Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension: diag(2732, ts.DiagnosticCategory.Error, "Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension_2732", "Cannot find module '{0}'. Consider using '--resolveJsonModule' to import module with '.json' extension"), + It_is_highly_likely_that_you_are_missing_a_semicolon: diag(2734, ts.DiagnosticCategory.Error, "It_is_highly_likely_that_you_are_missing_a_semicolon_2734", "It is highly likely that you are missing a semicolon."), + Did_you_mean_for_0_to_be_constrained_to_type_new_args_Colon_any_1: diag(2735, ts.DiagnosticCategory.Error, "Did_you_mean_for_0_to_be_constrained_to_type_new_args_Colon_any_1_2735", "Did you mean for '{0}' to be constrained to type 'new (...args: any[]) => {1}'?"), + Operator_0_cannot_be_applied_to_type_1: diag(2736, ts.DiagnosticCategory.Error, "Operator_0_cannot_be_applied_to_type_1_2736", "Operator '{0}' cannot be applied to type '{1}'."), + BigInt_literals_are_not_available_when_targeting_lower_than_ESNext: diag(2737, ts.DiagnosticCategory.Error, "BigInt_literals_are_not_available_when_targeting_lower_than_ESNext_2737", "BigInt literals are not available when targeting lower than ESNext."), + An_outer_value_of_this_is_shadowed_by_this_container: diag(2738, ts.DiagnosticCategory.Message, "An_outer_value_of_this_is_shadowed_by_this_container_2738", "An outer value of 'this' is shadowed by this container."), + Type_0_is_missing_the_following_properties_from_type_1_Colon_2: diag(2739, ts.DiagnosticCategory.Error, "Type_0_is_missing_the_following_properties_from_type_1_Colon_2_2739", "Type '{0}' is missing the following properties from type '{1}': {2}"), + Type_0_is_missing_the_following_properties_from_type_1_Colon_2_and_3_more: diag(2740, ts.DiagnosticCategory.Error, "Type_0_is_missing_the_following_properties_from_type_1_Colon_2_and_3_more_2740", "Type '{0}' is missing the following properties from type '{1}': {2}, and {3} more."), + Property_0_is_missing_in_type_1_but_required_in_type_2: diag(2741, ts.DiagnosticCategory.Error, "Property_0_is_missing_in_type_1_but_required_in_type_2_2741", "Property '{0}' is missing in type '{1}' but required in type '{2}'."), + The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_annotation_is_necessary: diag(2742, ts.DiagnosticCategory.Error, "The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_a_2742", "The inferred type of '{0}' cannot be named without a reference to '{1}'. This is likely not portable. A type annotation is necessary."), + Import_declaration_0_is_using_private_name_1: diag(4000, ts.DiagnosticCategory.Error, "Import_declaration_0_is_using_private_name_1_4000", "Import declaration '{0}' is using private name '{1}'."), + Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: diag(4002, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", "Type parameter '{0}' of exported class has or is using private name '{1}'."), + Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: diag(4004, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", "Type parameter '{0}' of exported interface has or is using private name '{1}'."), + Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1: diag(4006, ts.DiagnosticCategory.Error, "Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4006", "Type parameter '{0}' of constructor signature from exported interface has or is using private name '{1}'."), + Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1: diag(4008, ts.DiagnosticCategory.Error, "Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4008", "Type parameter '{0}' of call signature from exported interface has or is using private name '{1}'."), + Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1: diag(4010, ts.DiagnosticCategory.Error, "Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4010", "Type parameter '{0}' of public static method from exported class has or is using private name '{1}'."), + Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1: diag(4012, ts.DiagnosticCategory.Error, "Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4012", "Type parameter '{0}' of public method from exported class has or is using private name '{1}'."), + Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1: diag(4014, ts.DiagnosticCategory.Error, "Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4014", "Type parameter '{0}' of method from exported interface has or is using private name '{1}'."), + Type_parameter_0_of_exported_function_has_or_is_using_private_name_1: diag(4016, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_function_has_or_is_using_private_name_1_4016", "Type parameter '{0}' of exported function has or is using private name '{1}'."), + Implements_clause_of_exported_class_0_has_or_is_using_private_name_1: diag(4019, ts.DiagnosticCategory.Error, "Implements_clause_of_exported_class_0_has_or_is_using_private_name_1_4019", "Implements clause of exported class '{0}' has or is using private name '{1}'."), + extends_clause_of_exported_class_0_has_or_is_using_private_name_1: diag(4020, ts.DiagnosticCategory.Error, "extends_clause_of_exported_class_0_has_or_is_using_private_name_1_4020", "'extends' clause of exported class '{0}' has or is using private name '{1}'."), + extends_clause_of_exported_interface_0_has_or_is_using_private_name_1: diag(4022, ts.DiagnosticCategory.Error, "extends_clause_of_exported_interface_0_has_or_is_using_private_name_1_4022", "'extends' clause of exported interface '{0}' has or is using private name '{1}'."), + Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4023, ts.DiagnosticCategory.Error, "Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4023", "Exported variable '{0}' has or is using name '{1}' from external module {2} but cannot be named."), + Exported_variable_0_has_or_is_using_name_1_from_private_module_2: diag(4024, ts.DiagnosticCategory.Error, "Exported_variable_0_has_or_is_using_name_1_from_private_module_2_4024", "Exported variable '{0}' has or is using name '{1}' from private module '{2}'."), + Exported_variable_0_has_or_is_using_private_name_1: diag(4025, ts.DiagnosticCategory.Error, "Exported_variable_0_has_or_is_using_private_name_1_4025", "Exported variable '{0}' has or is using private name '{1}'."), + Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4026, ts.DiagnosticCategory.Error, "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot__4026", "Public static property '{0}' of exported class has or is using name '{1}' from external module {2} but cannot be named."), + Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4027, ts.DiagnosticCategory.Error, "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4027", "Public static property '{0}' of exported class has or is using name '{1}' from private module '{2}'."), + Public_static_property_0_of_exported_class_has_or_is_using_private_name_1: diag(4028, ts.DiagnosticCategory.Error, "Public_static_property_0_of_exported_class_has_or_is_using_private_name_1_4028", "Public static property '{0}' of exported class has or is using private name '{1}'."), + Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4029, ts.DiagnosticCategory.Error, "Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_name_4029", "Public property '{0}' of exported class has or is using name '{1}' from external module {2} but cannot be named."), + Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4030, ts.DiagnosticCategory.Error, "Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4030", "Public property '{0}' of exported class has or is using name '{1}' from private module '{2}'."), + Public_property_0_of_exported_class_has_or_is_using_private_name_1: diag(4031, ts.DiagnosticCategory.Error, "Public_property_0_of_exported_class_has_or_is_using_private_name_1_4031", "Public property '{0}' of exported class has or is using private name '{1}'."), + Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4032, ts.DiagnosticCategory.Error, "Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4032", "Property '{0}' of exported interface has or is using name '{1}' from private module '{2}'."), + Property_0_of_exported_interface_has_or_is_using_private_name_1: diag(4033, ts.DiagnosticCategory.Error, "Property_0_of_exported_interface_has_or_is_using_private_name_1_4033", "Property '{0}' of exported interface has or is using private name '{1}'."), + Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4034, ts.DiagnosticCategory.Error, "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_name_1_from_private_mod_4034", "Parameter type of public static setter '{0}' from exported class has or is using name '{1}' from private module '{2}'."), + Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1: diag(4035, ts.DiagnosticCategory.Error, "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1_4035", "Parameter type of public static setter '{0}' from exported class has or is using private name '{1}'."), + Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4036, ts.DiagnosticCategory.Error, "Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2_4036", "Parameter type of public setter '{0}' from exported class has or is using name '{1}' from private module '{2}'."), + Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_private_name_1: diag(4037, ts.DiagnosticCategory.Error, "Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_private_name_1_4037", "Parameter type of public setter '{0}' from exported class has or is using private name '{1}'."), + Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4038, ts.DiagnosticCategory.Error, "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_external_modul_4038", "Return type of public static getter '{0}' from exported class has or is using name '{1}' from external module {2} but cannot be named."), + Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4039, ts.DiagnosticCategory.Error, "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_4039", "Return type of public static getter '{0}' from exported class has or is using name '{1}' from private module '{2}'."), + Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_private_name_1: diag(4040, ts.DiagnosticCategory.Error, "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_private_name_1_4040", "Return type of public static getter '{0}' from exported class has or is using private name '{1}'."), + Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4041, ts.DiagnosticCategory.Error, "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_4041", "Return type of public getter '{0}' from exported class has or is using name '{1}' from external module {2} but cannot be named."), + Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4042, ts.DiagnosticCategory.Error, "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2_4042", "Return type of public getter '{0}' from exported class has or is using name '{1}' from private module '{2}'."), + Return_type_of_public_getter_0_from_exported_class_has_or_is_using_private_name_1: diag(4043, ts.DiagnosticCategory.Error, "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_private_name_1_4043", "Return type of public getter '{0}' from exported class has or is using private name '{1}'."), + Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1: diag(4044, ts.DiagnosticCategory.Error, "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_mod_4044", "Return type of constructor signature from exported interface has or is using name '{0}' from private module '{1}'."), + Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0: diag(4045, ts.DiagnosticCategory.Error, "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0_4045", "Return type of constructor signature from exported interface has or is using private name '{0}'."), + Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1: diag(4046, ts.DiagnosticCategory.Error, "Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4046", "Return type of call signature from exported interface has or is using name '{0}' from private module '{1}'."), + Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0: diag(4047, ts.DiagnosticCategory.Error, "Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0_4047", "Return type of call signature from exported interface has or is using private name '{0}'."), + Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1: diag(4048, ts.DiagnosticCategory.Error, "Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4048", "Return type of index signature from exported interface has or is using name '{0}' from private module '{1}'."), + Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0: diag(4049, ts.DiagnosticCategory.Error, "Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0_4049", "Return type of index signature from exported interface has or is using private name '{0}'."), + Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: diag(4050, ts.DiagnosticCategory.Error, "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module__4050", "Return type of public static method from exported class has or is using name '{0}' from external module {1} but cannot be named."), + Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1: diag(4051, ts.DiagnosticCategory.Error, "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4051", "Return type of public static method from exported class has or is using name '{0}' from private module '{1}'."), + Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0: diag(4052, ts.DiagnosticCategory.Error, "Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0_4052", "Return type of public static method from exported class has or is using private name '{0}'."), + Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: diag(4053, ts.DiagnosticCategory.Error, "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_c_4053", "Return type of public method from exported class has or is using name '{0}' from external module {1} but cannot be named."), + Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1: diag(4054, ts.DiagnosticCategory.Error, "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4054", "Return type of public method from exported class has or is using name '{0}' from private module '{1}'."), + Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0: diag(4055, ts.DiagnosticCategory.Error, "Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0_4055", "Return type of public method from exported class has or is using private name '{0}'."), + Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1: diag(4056, ts.DiagnosticCategory.Error, "Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4056", "Return type of method from exported interface has or is using name '{0}' from private module '{1}'."), + Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0: diag(4057, ts.DiagnosticCategory.Error, "Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0_4057", "Return type of method from exported interface has or is using private name '{0}'."), + Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: diag(4058, ts.DiagnosticCategory.Error, "Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named_4058", "Return type of exported function has or is using name '{0}' from external module {1} but cannot be named."), + Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1: diag(4059, ts.DiagnosticCategory.Error, "Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1_4059", "Return type of exported function has or is using name '{0}' from private module '{1}'."), + Return_type_of_exported_function_has_or_is_using_private_name_0: diag(4060, ts.DiagnosticCategory.Error, "Return_type_of_exported_function_has_or_is_using_private_name_0_4060", "Return type of exported function has or is using private name '{0}'."), + Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4061, ts.DiagnosticCategory.Error, "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_can_4061", "Parameter '{0}' of constructor from exported class has or is using name '{1}' from external module {2} but cannot be named."), + Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4062, ts.DiagnosticCategory.Error, "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2_4062", "Parameter '{0}' of constructor from exported class has or is using name '{1}' from private module '{2}'."), + Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1: diag(4063, ts.DiagnosticCategory.Error, "Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1_4063", "Parameter '{0}' of constructor from exported class has or is using private name '{1}'."), + Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4064, ts.DiagnosticCategory.Error, "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_mod_4064", "Parameter '{0}' of constructor signature from exported interface has or is using name '{1}' from private module '{2}'."), + Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1: diag(4065, ts.DiagnosticCategory.Error, "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4065", "Parameter '{0}' of constructor signature from exported interface has or is using private name '{1}'."), + Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4066, ts.DiagnosticCategory.Error, "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4066", "Parameter '{0}' of call signature from exported interface has or is using name '{1}' from private module '{2}'."), + Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1: diag(4067, ts.DiagnosticCategory.Error, "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4067", "Parameter '{0}' of call signature from exported interface has or is using private name '{1}'."), + Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4068, ts.DiagnosticCategory.Error, "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module__4068", "Parameter '{0}' of public static method from exported class has or is using name '{1}' from external module {2} but cannot be named."), + Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4069, ts.DiagnosticCategory.Error, "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4069", "Parameter '{0}' of public static method from exported class has or is using name '{1}' from private module '{2}'."), + Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1: diag(4070, ts.DiagnosticCategory.Error, "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4070", "Parameter '{0}' of public static method from exported class has or is using private name '{1}'."), + Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4071, ts.DiagnosticCategory.Error, "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_c_4071", "Parameter '{0}' of public method from exported class has or is using name '{1}' from external module {2} but cannot be named."), + Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4072, ts.DiagnosticCategory.Error, "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4072", "Parameter '{0}' of public method from exported class has or is using name '{1}' from private module '{2}'."), + Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1: diag(4073, ts.DiagnosticCategory.Error, "Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4073", "Parameter '{0}' of public method from exported class has or is using private name '{1}'."), + Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4074, ts.DiagnosticCategory.Error, "Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4074", "Parameter '{0}' of method from exported interface has or is using name '{1}' from private module '{2}'."), + Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1: diag(4075, ts.DiagnosticCategory.Error, "Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4075", "Parameter '{0}' of method from exported interface has or is using private name '{1}'."), + Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4076, ts.DiagnosticCategory.Error, "Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4076", "Parameter '{0}' of exported function has or is using name '{1}' from external module {2} but cannot be named."), + Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2: diag(4077, ts.DiagnosticCategory.Error, "Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2_4077", "Parameter '{0}' of exported function has or is using name '{1}' from private module '{2}'."), + Parameter_0_of_exported_function_has_or_is_using_private_name_1: diag(4078, ts.DiagnosticCategory.Error, "Parameter_0_of_exported_function_has_or_is_using_private_name_1_4078", "Parameter '{0}' of exported function has or is using private name '{1}'."), + Exported_type_alias_0_has_or_is_using_private_name_1: diag(4081, ts.DiagnosticCategory.Error, "Exported_type_alias_0_has_or_is_using_private_name_1_4081", "Exported type alias '{0}' has or is using private name '{1}'."), + Default_export_of_the_module_has_or_is_using_private_name_0: diag(4082, ts.DiagnosticCategory.Error, "Default_export_of_the_module_has_or_is_using_private_name_0_4082", "Default export of the module has or is using private name '{0}'."), + Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1: diag(4083, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1_4083", "Type parameter '{0}' of exported type alias has or is using private name '{1}'."), + Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict: diag(4090, ts.DiagnosticCategory.Error, "Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_librar_4090", "Conflicting definitions for '{0}' found at '{1}' and '{2}'. Consider installing a specific version of this library to resolve the conflict."), + Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4091, ts.DiagnosticCategory.Error, "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4091", "Parameter '{0}' of index signature from exported interface has or is using name '{1}' from private module '{2}'."), + Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1: diag(4092, ts.DiagnosticCategory.Error, "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1_4092", "Parameter '{0}' of index signature from exported interface has or is using private name '{1}'."), + Property_0_of_exported_class_expression_may_not_be_private_or_protected: diag(4094, ts.DiagnosticCategory.Error, "Property_0_of_exported_class_expression_may_not_be_private_or_protected_4094", "Property '{0}' of exported class expression may not be private or protected."), + Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4095, ts.DiagnosticCategory.Error, "Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_4095", "Public static method '{0}' of exported class has or is using name '{1}' from external module {2} but cannot be named."), + Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4096, ts.DiagnosticCategory.Error, "Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4096", "Public static method '{0}' of exported class has or is using name '{1}' from private module '{2}'."), + Public_static_method_0_of_exported_class_has_or_is_using_private_name_1: diag(4097, ts.DiagnosticCategory.Error, "Public_static_method_0_of_exported_class_has_or_is_using_private_name_1_4097", "Public static method '{0}' of exported class has or is using private name '{1}'."), + Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4098, ts.DiagnosticCategory.Error, "Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4098", "Public method '{0}' of exported class has or is using name '{1}' from external module {2} but cannot be named."), + Public_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4099, ts.DiagnosticCategory.Error, "Public_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4099", "Public method '{0}' of exported class has or is using name '{1}' from private module '{2}'."), + Public_method_0_of_exported_class_has_or_is_using_private_name_1: diag(4100, ts.DiagnosticCategory.Error, "Public_method_0_of_exported_class_has_or_is_using_private_name_1_4100", "Public method '{0}' of exported class has or is using private name '{1}'."), + Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4101, ts.DiagnosticCategory.Error, "Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4101", "Method '{0}' of exported interface has or is using name '{1}' from private module '{2}'."), + Method_0_of_exported_interface_has_or_is_using_private_name_1: diag(4102, ts.DiagnosticCategory.Error, "Method_0_of_exported_interface_has_or_is_using_private_name_1_4102", "Method '{0}' of exported interface has or is using private name '{1}'."), + The_current_host_does_not_support_the_0_option: diag(5001, ts.DiagnosticCategory.Error, "The_current_host_does_not_support_the_0_option_5001", "The current host does not support the '{0}' option."), + Cannot_find_the_common_subdirectory_path_for_the_input_files: diag(5009, ts.DiagnosticCategory.Error, "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009", "Cannot find the common subdirectory path for the input files."), + File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: diag(5010, ts.DiagnosticCategory.Error, "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010", "File specification cannot end in a recursive directory wildcard ('**'): '{0}'."), + Cannot_read_file_0_Colon_1: diag(5012, ts.DiagnosticCategory.Error, "Cannot_read_file_0_Colon_1_5012", "Cannot read file '{0}': {1}."), + Failed_to_parse_file_0_Colon_1: diag(5014, ts.DiagnosticCategory.Error, "Failed_to_parse_file_0_Colon_1_5014", "Failed to parse file '{0}': {1}."), + Unknown_compiler_option_0: diag(5023, ts.DiagnosticCategory.Error, "Unknown_compiler_option_0_5023", "Unknown compiler option '{0}'."), + Compiler_option_0_requires_a_value_of_type_1: diag(5024, ts.DiagnosticCategory.Error, "Compiler_option_0_requires_a_value_of_type_1_5024", "Compiler option '{0}' requires a value of type {1}."), + Could_not_write_file_0_Colon_1: diag(5033, ts.DiagnosticCategory.Error, "Could_not_write_file_0_Colon_1_5033", "Could not write file '{0}': {1}."), + Option_project_cannot_be_mixed_with_source_files_on_a_command_line: diag(5042, ts.DiagnosticCategory.Error, "Option_project_cannot_be_mixed_with_source_files_on_a_command_line_5042", "Option 'project' cannot be mixed with source files on a command line."), + Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher: diag(5047, ts.DiagnosticCategory.Error, "Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES_5047", "Option 'isolatedModules' can only be used when either option '--module' is provided or option 'target' is 'ES2015' or higher."), + Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided: diag(5051, ts.DiagnosticCategory.Error, "Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided_5051", "Option '{0} can only be used when either option '--inlineSourceMap' or option '--sourceMap' is provided."), + Option_0_cannot_be_specified_without_specifying_option_1: diag(5052, ts.DiagnosticCategory.Error, "Option_0_cannot_be_specified_without_specifying_option_1_5052", "Option '{0}' cannot be specified without specifying option '{1}'."), + Option_0_cannot_be_specified_with_option_1: diag(5053, ts.DiagnosticCategory.Error, "Option_0_cannot_be_specified_with_option_1_5053", "Option '{0}' cannot be specified with option '{1}'."), + A_tsconfig_json_file_is_already_defined_at_Colon_0: diag(5054, ts.DiagnosticCategory.Error, "A_tsconfig_json_file_is_already_defined_at_Colon_0_5054", "A 'tsconfig.json' file is already defined at: '{0}'."), + Cannot_write_file_0_because_it_would_overwrite_input_file: diag(5055, ts.DiagnosticCategory.Error, "Cannot_write_file_0_because_it_would_overwrite_input_file_5055", "Cannot write file '{0}' because it would overwrite input file."), + Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files: diag(5056, ts.DiagnosticCategory.Error, "Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files_5056", "Cannot write file '{0}' because it would be overwritten by multiple input files."), + Cannot_find_a_tsconfig_json_file_at_the_specified_directory_Colon_0: diag(5057, ts.DiagnosticCategory.Error, "Cannot_find_a_tsconfig_json_file_at_the_specified_directory_Colon_0_5057", "Cannot find a tsconfig.json file at the specified directory: '{0}'."), + The_specified_path_does_not_exist_Colon_0: diag(5058, ts.DiagnosticCategory.Error, "The_specified_path_does_not_exist_Colon_0_5058", "The specified path does not exist: '{0}'."), + Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier: diag(5059, ts.DiagnosticCategory.Error, "Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier_5059", "Invalid value for '--reactNamespace'. '{0}' is not a valid identifier."), + Option_paths_cannot_be_used_without_specifying_baseUrl_option: diag(5060, ts.DiagnosticCategory.Error, "Option_paths_cannot_be_used_without_specifying_baseUrl_option_5060", "Option 'paths' cannot be used without specifying '--baseUrl' option."), + Pattern_0_can_have_at_most_one_Asterisk_character: diag(5061, ts.DiagnosticCategory.Error, "Pattern_0_can_have_at_most_one_Asterisk_character_5061", "Pattern '{0}' can have at most one '*' character."), + Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character: diag(5062, ts.DiagnosticCategory.Error, "Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character_5062", "Substitution '{0}' in pattern '{1}' in can have at most one '*' character."), + Substitutions_for_pattern_0_should_be_an_array: diag(5063, ts.DiagnosticCategory.Error, "Substitutions_for_pattern_0_should_be_an_array_5063", "Substitutions for pattern '{0}' should be an array."), + Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2: diag(5064, ts.DiagnosticCategory.Error, "Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2_5064", "Substitution '{0}' for pattern '{1}' has incorrect type, expected 'string', got '{2}'."), + File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: diag(5065, ts.DiagnosticCategory.Error, "File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildca_5065", "File specification cannot contain a parent directory ('..') that appears after a recursive directory wildcard ('**'): '{0}'."), + Substitutions_for_pattern_0_shouldn_t_be_an_empty_array: diag(5066, ts.DiagnosticCategory.Error, "Substitutions_for_pattern_0_shouldn_t_be_an_empty_array_5066", "Substitutions for pattern '{0}' shouldn't be an empty array."), + Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name: diag(5067, ts.DiagnosticCategory.Error, "Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name_5067", "Invalid value for 'jsxFactory'. '{0}' is not a valid identifier or qualified-name."), + Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig: diag(5068, ts.DiagnosticCategory.Error, "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068", "Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig."), + Option_0_cannot_be_specified_without_specifying_option_1_or_option_2: diag(5069, ts.DiagnosticCategory.Error, "Option_0_cannot_be_specified_without_specifying_option_1_or_option_2_5069", "Option '{0}' cannot be specified without specifying option '{1}' or option '{2}'."), + Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy: diag(5070, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070", "Option '--resolveJsonModule' cannot be specified without 'node' module resolution strategy."), + Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_esNext: diag(5071, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_5071", "Option '--resolveJsonModule' can only be specified when module code generation is 'commonjs', 'amd', 'es2015' or 'esNext'."), + Unknown_build_option_0: diag(5072, ts.DiagnosticCategory.Error, "Unknown_build_option_0_5072", "Unknown build option '{0}'."), + Build_option_0_requires_a_value_of_type_1: diag(5073, ts.DiagnosticCategory.Error, "Build_option_0_requires_a_value_of_type_1_5073", "Build option '{0}' requires a value of type {1}."), + Generates_a_sourcemap_for_each_corresponding_d_ts_file: diag(6000, ts.DiagnosticCategory.Message, "Generates_a_sourcemap_for_each_corresponding_d_ts_file_6000", "Generates a sourcemap for each corresponding '.d.ts' file."), + Concatenate_and_emit_output_to_single_file: diag(6001, ts.DiagnosticCategory.Message, "Concatenate_and_emit_output_to_single_file_6001", "Concatenate and emit output to single file."), + Generates_corresponding_d_ts_file: diag(6002, ts.DiagnosticCategory.Message, "Generates_corresponding_d_ts_file_6002", "Generates corresponding '.d.ts' file."), + Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations: diag(6003, ts.DiagnosticCategory.Message, "Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations_6003", "Specify the location where debugger should locate map files instead of generated locations."), + Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations: diag(6004, ts.DiagnosticCategory.Message, "Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations_6004", "Specify the location where debugger should locate TypeScript files instead of source locations."), + Watch_input_files: diag(6005, ts.DiagnosticCategory.Message, "Watch_input_files_6005", "Watch input files."), + Redirect_output_structure_to_the_directory: diag(6006, ts.DiagnosticCategory.Message, "Redirect_output_structure_to_the_directory_6006", "Redirect output structure to the directory."), + Do_not_erase_const_enum_declarations_in_generated_code: diag(6007, ts.DiagnosticCategory.Message, "Do_not_erase_const_enum_declarations_in_generated_code_6007", "Do not erase const enum declarations in generated code."), + Do_not_emit_outputs_if_any_errors_were_reported: diag(6008, ts.DiagnosticCategory.Message, "Do_not_emit_outputs_if_any_errors_were_reported_6008", "Do not emit outputs if any errors were reported."), + Do_not_emit_comments_to_output: diag(6009, ts.DiagnosticCategory.Message, "Do_not_emit_comments_to_output_6009", "Do not emit comments to output."), + Do_not_emit_outputs: diag(6010, ts.DiagnosticCategory.Message, "Do_not_emit_outputs_6010", "Do not emit outputs."), + Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking: diag(6011, ts.DiagnosticCategory.Message, "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011", "Allow default imports from modules with no default export. This does not affect code emit, just typechecking."), + Skip_type_checking_of_declaration_files: diag(6012, ts.DiagnosticCategory.Message, "Skip_type_checking_of_declaration_files_6012", "Skip type checking of declaration files."), + Do_not_resolve_the_real_path_of_symlinks: diag(6013, ts.DiagnosticCategory.Message, "Do_not_resolve_the_real_path_of_symlinks_6013", "Do not resolve the real path of symlinks."), + Only_emit_d_ts_declaration_files: diag(6014, ts.DiagnosticCategory.Message, "Only_emit_d_ts_declaration_files_6014", "Only emit '.d.ts' declaration files."), + Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_or_ESNEXT: diag(6015, ts.DiagnosticCategory.Message, "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_or_ESNEXT_6015", "Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'."), + Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext: diag(6016, ts.DiagnosticCategory.Message, "Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext_6016", "Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'."), + Print_this_message: diag(6017, ts.DiagnosticCategory.Message, "Print_this_message_6017", "Print this message."), + Print_the_compiler_s_version: diag(6019, ts.DiagnosticCategory.Message, "Print_the_compiler_s_version_6019", "Print the compiler's version."), + Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json: diag(6020, ts.DiagnosticCategory.Message, "Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json_6020", "Compile the project given the path to its configuration file, or to a folder with a 'tsconfig.json'."), + Syntax_Colon_0: diag(6023, ts.DiagnosticCategory.Message, "Syntax_Colon_0_6023", "Syntax: {0}"), + options: diag(6024, ts.DiagnosticCategory.Message, "options_6024", "options"), + file: diag(6025, ts.DiagnosticCategory.Message, "file_6025", "file"), + Examples_Colon_0: diag(6026, ts.DiagnosticCategory.Message, "Examples_Colon_0_6026", "Examples: {0}"), + Options_Colon: diag(6027, ts.DiagnosticCategory.Message, "Options_Colon_6027", "Options:"), + Version_0: diag(6029, ts.DiagnosticCategory.Message, "Version_0_6029", "Version {0}"), + Insert_command_line_options_and_files_from_a_file: diag(6030, ts.DiagnosticCategory.Message, "Insert_command_line_options_and_files_from_a_file_6030", "Insert command line options and files from a file."), + Starting_compilation_in_watch_mode: diag(6031, ts.DiagnosticCategory.Message, "Starting_compilation_in_watch_mode_6031", "Starting compilation in watch mode..."), + File_change_detected_Starting_incremental_compilation: diag(6032, ts.DiagnosticCategory.Message, "File_change_detected_Starting_incremental_compilation_6032", "File change detected. Starting incremental compilation..."), + KIND: diag(6034, ts.DiagnosticCategory.Message, "KIND_6034", "KIND"), + FILE: diag(6035, ts.DiagnosticCategory.Message, "FILE_6035", "FILE"), + VERSION: diag(6036, ts.DiagnosticCategory.Message, "VERSION_6036", "VERSION"), + LOCATION: diag(6037, ts.DiagnosticCategory.Message, "LOCATION_6037", "LOCATION"), + DIRECTORY: diag(6038, ts.DiagnosticCategory.Message, "DIRECTORY_6038", "DIRECTORY"), + STRATEGY: diag(6039, ts.DiagnosticCategory.Message, "STRATEGY_6039", "STRATEGY"), + FILE_OR_DIRECTORY: diag(6040, ts.DiagnosticCategory.Message, "FILE_OR_DIRECTORY_6040", "FILE OR DIRECTORY"), + Generates_corresponding_map_file: diag(6043, ts.DiagnosticCategory.Message, "Generates_corresponding_map_file_6043", "Generates corresponding '.map' file."), + Compiler_option_0_expects_an_argument: diag(6044, ts.DiagnosticCategory.Error, "Compiler_option_0_expects_an_argument_6044", "Compiler option '{0}' expects an argument."), + Unterminated_quoted_string_in_response_file_0: diag(6045, ts.DiagnosticCategory.Error, "Unterminated_quoted_string_in_response_file_0_6045", "Unterminated quoted string in response file '{0}'."), + Argument_for_0_option_must_be_Colon_1: diag(6046, ts.DiagnosticCategory.Error, "Argument_for_0_option_must_be_Colon_1_6046", "Argument for '{0}' option must be: {1}."), + Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1: diag(6048, ts.DiagnosticCategory.Error, "Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1_6048", "Locale must be of the form or -. For example '{0}' or '{1}'."), + Unsupported_locale_0: diag(6049, ts.DiagnosticCategory.Error, "Unsupported_locale_0_6049", "Unsupported locale '{0}'."), + Unable_to_open_file_0: diag(6050, ts.DiagnosticCategory.Error, "Unable_to_open_file_0_6050", "Unable to open file '{0}'."), + Corrupted_locale_file_0: diag(6051, ts.DiagnosticCategory.Error, "Corrupted_locale_file_0_6051", "Corrupted locale file {0}."), + Raise_error_on_expressions_and_declarations_with_an_implied_any_type: diag(6052, ts.DiagnosticCategory.Message, "Raise_error_on_expressions_and_declarations_with_an_implied_any_type_6052", "Raise error on expressions and declarations with an implied 'any' type."), + File_0_not_found: diag(6053, ts.DiagnosticCategory.Error, "File_0_not_found_6053", "File '{0}' not found."), + File_0_has_unsupported_extension_The_only_supported_extensions_are_1: diag(6054, ts.DiagnosticCategory.Error, "File_0_has_unsupported_extension_The_only_supported_extensions_are_1_6054", "File '{0}' has unsupported extension. The only supported extensions are {1}."), + Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures: diag(6055, ts.DiagnosticCategory.Message, "Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures_6055", "Suppress noImplicitAny errors for indexing objects lacking index signatures."), + Do_not_emit_declarations_for_code_that_has_an_internal_annotation: diag(6056, ts.DiagnosticCategory.Message, "Do_not_emit_declarations_for_code_that_has_an_internal_annotation_6056", "Do not emit declarations for code that has an '@internal' annotation."), + Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir: diag(6058, ts.DiagnosticCategory.Message, "Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir_6058", "Specify the root directory of input files. Use to control the output directory structure with --outDir."), + File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files: diag(6059, ts.DiagnosticCategory.Error, "File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files_6059", "File '{0}' is not under 'rootDir' '{1}'. 'rootDir' is expected to contain all source files."), + Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix: diag(6060, ts.DiagnosticCategory.Message, "Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix_6060", "Specify the end of line sequence to be used when emitting files: 'CRLF' (dos) or 'LF' (unix)."), + NEWLINE: diag(6061, ts.DiagnosticCategory.Message, "NEWLINE_6061", "NEWLINE"), + Option_0_can_only_be_specified_in_tsconfig_json_file: diag(6064, ts.DiagnosticCategory.Error, "Option_0_can_only_be_specified_in_tsconfig_json_file_6064", "Option '{0}' can only be specified in 'tsconfig.json' file."), + Enables_experimental_support_for_ES7_decorators: diag(6065, ts.DiagnosticCategory.Message, "Enables_experimental_support_for_ES7_decorators_6065", "Enables experimental support for ES7 decorators."), + Enables_experimental_support_for_emitting_type_metadata_for_decorators: diag(6066, ts.DiagnosticCategory.Message, "Enables_experimental_support_for_emitting_type_metadata_for_decorators_6066", "Enables experimental support for emitting type metadata for decorators."), + Enables_experimental_support_for_ES7_async_functions: diag(6068, ts.DiagnosticCategory.Message, "Enables_experimental_support_for_ES7_async_functions_6068", "Enables experimental support for ES7 async functions."), + Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6: diag(6069, ts.DiagnosticCategory.Message, "Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6_6069", "Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6)."), + Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file: diag(6070, ts.DiagnosticCategory.Message, "Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file_6070", "Initializes a TypeScript project and creates a tsconfig.json file."), + Successfully_created_a_tsconfig_json_file: diag(6071, ts.DiagnosticCategory.Message, "Successfully_created_a_tsconfig_json_file_6071", "Successfully created a tsconfig.json file."), + Suppress_excess_property_checks_for_object_literals: diag(6072, ts.DiagnosticCategory.Message, "Suppress_excess_property_checks_for_object_literals_6072", "Suppress excess property checks for object literals."), + Stylize_errors_and_messages_using_color_and_context_experimental: diag(6073, ts.DiagnosticCategory.Message, "Stylize_errors_and_messages_using_color_and_context_experimental_6073", "Stylize errors and messages using color and context (experimental)."), + Do_not_report_errors_on_unused_labels: diag(6074, ts.DiagnosticCategory.Message, "Do_not_report_errors_on_unused_labels_6074", "Do not report errors on unused labels."), + Report_error_when_not_all_code_paths_in_function_return_a_value: diag(6075, ts.DiagnosticCategory.Message, "Report_error_when_not_all_code_paths_in_function_return_a_value_6075", "Report error when not all code paths in function return a value."), + Report_errors_for_fallthrough_cases_in_switch_statement: diag(6076, ts.DiagnosticCategory.Message, "Report_errors_for_fallthrough_cases_in_switch_statement_6076", "Report errors for fallthrough cases in switch statement."), + Do_not_report_errors_on_unreachable_code: diag(6077, ts.DiagnosticCategory.Message, "Do_not_report_errors_on_unreachable_code_6077", "Do not report errors on unreachable code."), + Disallow_inconsistently_cased_references_to_the_same_file: diag(6078, ts.DiagnosticCategory.Message, "Disallow_inconsistently_cased_references_to_the_same_file_6078", "Disallow inconsistently-cased references to the same file."), + Specify_library_files_to_be_included_in_the_compilation: diag(6079, ts.DiagnosticCategory.Message, "Specify_library_files_to_be_included_in_the_compilation_6079", "Specify library files to be included in the compilation."), + Specify_JSX_code_generation_Colon_preserve_react_native_or_react: diag(6080, ts.DiagnosticCategory.Message, "Specify_JSX_code_generation_Colon_preserve_react_native_or_react_6080", "Specify JSX code generation: 'preserve', 'react-native', or 'react'."), + File_0_has_an_unsupported_extension_so_skipping_it: diag(6081, ts.DiagnosticCategory.Message, "File_0_has_an_unsupported_extension_so_skipping_it_6081", "File '{0}' has an unsupported extension, so skipping it."), + Only_amd_and_system_modules_are_supported_alongside_0: diag(6082, ts.DiagnosticCategory.Error, "Only_amd_and_system_modules_are_supported_alongside_0_6082", "Only 'amd' and 'system' modules are supported alongside --{0}."), + Base_directory_to_resolve_non_absolute_module_names: diag(6083, ts.DiagnosticCategory.Message, "Base_directory_to_resolve_non_absolute_module_names_6083", "Base directory to resolve non-absolute module names."), + Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react_JSX_emit: diag(6084, ts.DiagnosticCategory.Message, "Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react__6084", "[Deprecated] Use '--jsxFactory' instead. Specify the object invoked for createElement when targeting 'react' JSX emit"), + Enable_tracing_of_the_name_resolution_process: diag(6085, ts.DiagnosticCategory.Message, "Enable_tracing_of_the_name_resolution_process_6085", "Enable tracing of the name resolution process."), + Resolving_module_0_from_1: diag(6086, ts.DiagnosticCategory.Message, "Resolving_module_0_from_1_6086", "======== Resolving module '{0}' from '{1}'. ========"), + Explicitly_specified_module_resolution_kind_Colon_0: diag(6087, ts.DiagnosticCategory.Message, "Explicitly_specified_module_resolution_kind_Colon_0_6087", "Explicitly specified module resolution kind: '{0}'."), + Module_resolution_kind_is_not_specified_using_0: diag(6088, ts.DiagnosticCategory.Message, "Module_resolution_kind_is_not_specified_using_0_6088", "Module resolution kind is not specified, using '{0}'."), + Module_name_0_was_successfully_resolved_to_1: diag(6089, ts.DiagnosticCategory.Message, "Module_name_0_was_successfully_resolved_to_1_6089", "======== Module name '{0}' was successfully resolved to '{1}'. ========"), + Module_name_0_was_not_resolved: diag(6090, ts.DiagnosticCategory.Message, "Module_name_0_was_not_resolved_6090", "======== Module name '{0}' was not resolved. ========"), + paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0: diag(6091, ts.DiagnosticCategory.Message, "paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0_6091", "'paths' option is specified, looking for a pattern to match module name '{0}'."), + Module_name_0_matched_pattern_1: diag(6092, ts.DiagnosticCategory.Message, "Module_name_0_matched_pattern_1_6092", "Module name '{0}', matched pattern '{1}'."), + Trying_substitution_0_candidate_module_location_Colon_1: diag(6093, ts.DiagnosticCategory.Message, "Trying_substitution_0_candidate_module_location_Colon_1_6093", "Trying substitution '{0}', candidate module location: '{1}'."), + Resolving_module_name_0_relative_to_base_url_1_2: diag(6094, ts.DiagnosticCategory.Message, "Resolving_module_name_0_relative_to_base_url_1_2_6094", "Resolving module name '{0}' relative to base url '{1}' - '{2}'."), + Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1: diag(6095, ts.DiagnosticCategory.Message, "Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1_6095", "Loading module as file / folder, candidate module location '{0}', target file type '{1}'."), + File_0_does_not_exist: diag(6096, ts.DiagnosticCategory.Message, "File_0_does_not_exist_6096", "File '{0}' does not exist."), + File_0_exist_use_it_as_a_name_resolution_result: diag(6097, ts.DiagnosticCategory.Message, "File_0_exist_use_it_as_a_name_resolution_result_6097", "File '{0}' exist - use it as a name resolution result."), + Loading_module_0_from_node_modules_folder_target_file_type_1: diag(6098, ts.DiagnosticCategory.Message, "Loading_module_0_from_node_modules_folder_target_file_type_1_6098", "Loading module '{0}' from 'node_modules' folder, target file type '{1}'."), + Found_package_json_at_0: diag(6099, ts.DiagnosticCategory.Message, "Found_package_json_at_0_6099", "Found 'package.json' at '{0}'."), + package_json_does_not_have_a_0_field: diag(6100, ts.DiagnosticCategory.Message, "package_json_does_not_have_a_0_field_6100", "'package.json' does not have a '{0}' field."), + package_json_has_0_field_1_that_references_2: diag(6101, ts.DiagnosticCategory.Message, "package_json_has_0_field_1_that_references_2_6101", "'package.json' has '{0}' field '{1}' that references '{2}'."), + Allow_javascript_files_to_be_compiled: diag(6102, ts.DiagnosticCategory.Message, "Allow_javascript_files_to_be_compiled_6102", "Allow javascript files to be compiled."), + Option_0_should_have_array_of_strings_as_a_value: diag(6103, ts.DiagnosticCategory.Error, "Option_0_should_have_array_of_strings_as_a_value_6103", "Option '{0}' should have array of strings as a value."), + Checking_if_0_is_the_longest_matching_prefix_for_1_2: diag(6104, ts.DiagnosticCategory.Message, "Checking_if_0_is_the_longest_matching_prefix_for_1_2_6104", "Checking if '{0}' is the longest matching prefix for '{1}' - '{2}'."), + Expected_type_of_0_field_in_package_json_to_be_1_got_2: diag(6105, ts.DiagnosticCategory.Message, "Expected_type_of_0_field_in_package_json_to_be_1_got_2_6105", "Expected type of '{0}' field in 'package.json' to be '{1}', got '{2}'."), + baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1: diag(6106, ts.DiagnosticCategory.Message, "baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1_6106", "'baseUrl' option is set to '{0}', using this value to resolve non-relative module name '{1}'."), + rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0: diag(6107, ts.DiagnosticCategory.Message, "rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107", "'rootDirs' option is set, using it to resolve relative module name '{0}'."), + Longest_matching_prefix_for_0_is_1: diag(6108, ts.DiagnosticCategory.Message, "Longest_matching_prefix_for_0_is_1_6108", "Longest matching prefix for '{0}' is '{1}'."), + Loading_0_from_the_root_dir_1_candidate_location_2: diag(6109, ts.DiagnosticCategory.Message, "Loading_0_from_the_root_dir_1_candidate_location_2_6109", "Loading '{0}' from the root dir '{1}', candidate location '{2}'."), + Trying_other_entries_in_rootDirs: diag(6110, ts.DiagnosticCategory.Message, "Trying_other_entries_in_rootDirs_6110", "Trying other entries in 'rootDirs'."), + Module_resolution_using_rootDirs_has_failed: diag(6111, ts.DiagnosticCategory.Message, "Module_resolution_using_rootDirs_has_failed_6111", "Module resolution using 'rootDirs' has failed."), + Do_not_emit_use_strict_directives_in_module_output: diag(6112, ts.DiagnosticCategory.Message, "Do_not_emit_use_strict_directives_in_module_output_6112", "Do not emit 'use strict' directives in module output."), + Enable_strict_null_checks: diag(6113, ts.DiagnosticCategory.Message, "Enable_strict_null_checks_6113", "Enable strict null checks."), + Unknown_option_excludes_Did_you_mean_exclude: diag(6114, ts.DiagnosticCategory.Error, "Unknown_option_excludes_Did_you_mean_exclude_6114", "Unknown option 'excludes'. Did you mean 'exclude'?"), + Raise_error_on_this_expressions_with_an_implied_any_type: diag(6115, ts.DiagnosticCategory.Message, "Raise_error_on_this_expressions_with_an_implied_any_type_6115", "Raise error on 'this' expressions with an implied 'any' type."), + Resolving_type_reference_directive_0_containing_file_1_root_directory_2: diag(6116, ts.DiagnosticCategory.Message, "Resolving_type_reference_directive_0_containing_file_1_root_directory_2_6116", "======== Resolving type reference directive '{0}', containing file '{1}', root directory '{2}'. ========"), + Resolving_using_primary_search_paths: diag(6117, ts.DiagnosticCategory.Message, "Resolving_using_primary_search_paths_6117", "Resolving using primary search paths..."), + Resolving_from_node_modules_folder: diag(6118, ts.DiagnosticCategory.Message, "Resolving_from_node_modules_folder_6118", "Resolving from node_modules folder..."), + Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2: diag(6119, ts.DiagnosticCategory.Message, "Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2_6119", "======== Type reference directive '{0}' was successfully resolved to '{1}', primary: {2}. ========"), + Type_reference_directive_0_was_not_resolved: diag(6120, ts.DiagnosticCategory.Message, "Type_reference_directive_0_was_not_resolved_6120", "======== Type reference directive '{0}' was not resolved. ========"), + Resolving_with_primary_search_path_0: diag(6121, ts.DiagnosticCategory.Message, "Resolving_with_primary_search_path_0_6121", "Resolving with primary search path '{0}'."), + Root_directory_cannot_be_determined_skipping_primary_search_paths: diag(6122, ts.DiagnosticCategory.Message, "Root_directory_cannot_be_determined_skipping_primary_search_paths_6122", "Root directory cannot be determined, skipping primary search paths."), + Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set: diag(6123, ts.DiagnosticCategory.Message, "Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set_6123", "======== Resolving type reference directive '{0}', containing file '{1}', root directory not set. ========"), + Type_declaration_files_to_be_included_in_compilation: diag(6124, ts.DiagnosticCategory.Message, "Type_declaration_files_to_be_included_in_compilation_6124", "Type declaration files to be included in compilation."), + Looking_up_in_node_modules_folder_initial_location_0: diag(6125, ts.DiagnosticCategory.Message, "Looking_up_in_node_modules_folder_initial_location_0_6125", "Looking up in 'node_modules' folder, initial location '{0}'."), + Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder: diag(6126, ts.DiagnosticCategory.Message, "Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126", "Containing file is not specified and root directory cannot be determined, skipping lookup in 'node_modules' folder."), + Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1: diag(6127, ts.DiagnosticCategory.Message, "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1_6127", "======== Resolving type reference directive '{0}', containing file not set, root directory '{1}'. ========"), + Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set: diag(6128, ts.DiagnosticCategory.Message, "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set_6128", "======== Resolving type reference directive '{0}', containing file not set, root directory not set. ========"), + Resolving_real_path_for_0_result_1: diag(6130, ts.DiagnosticCategory.Message, "Resolving_real_path_for_0_result_1_6130", "Resolving real path for '{0}', result '{1}'."), + Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system: diag(6131, ts.DiagnosticCategory.Error, "Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system_6131", "Cannot compile modules using option '{0}' unless the '--module' flag is 'amd' or 'system'."), + File_name_0_has_a_1_extension_stripping_it: diag(6132, ts.DiagnosticCategory.Message, "File_name_0_has_a_1_extension_stripping_it_6132", "File name '{0}' has a '{1}' extension - stripping it."), + _0_is_declared_but_its_value_is_never_read: diag(6133, ts.DiagnosticCategory.Error, "_0_is_declared_but_its_value_is_never_read_6133", "'{0}' is declared but its value is never read.", /*reportsUnnecessary*/ true), + Report_errors_on_unused_locals: diag(6134, ts.DiagnosticCategory.Message, "Report_errors_on_unused_locals_6134", "Report errors on unused locals."), + Report_errors_on_unused_parameters: diag(6135, ts.DiagnosticCategory.Message, "Report_errors_on_unused_parameters_6135", "Report errors on unused parameters."), + The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files: diag(6136, ts.DiagnosticCategory.Message, "The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files_6136", "The maximum dependency depth to search under node_modules and load JavaScript files."), + Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1: diag(6137, ts.DiagnosticCategory.Error, "Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1_6137", "Cannot import type declaration files. Consider importing '{0}' instead of '{1}'."), + Property_0_is_declared_but_its_value_is_never_read: diag(6138, ts.DiagnosticCategory.Error, "Property_0_is_declared_but_its_value_is_never_read_6138", "Property '{0}' is declared but its value is never read.", /*reportsUnnecessary*/ true), + Import_emit_helpers_from_tslib: diag(6139, ts.DiagnosticCategory.Message, "Import_emit_helpers_from_tslib_6139", "Import emit helpers from 'tslib'."), + Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2: diag(6140, ts.DiagnosticCategory.Error, "Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using__6140", "Auto discovery for typings is enabled in project '{0}'. Running extra resolution pass for module '{1}' using cache location '{2}'."), + Parse_in_strict_mode_and_emit_use_strict_for_each_source_file: diag(6141, ts.DiagnosticCategory.Message, "Parse_in_strict_mode_and_emit_use_strict_for_each_source_file_6141", "Parse in strict mode and emit \"use strict\" for each source file."), + Module_0_was_resolved_to_1_but_jsx_is_not_set: diag(6142, ts.DiagnosticCategory.Error, "Module_0_was_resolved_to_1_but_jsx_is_not_set_6142", "Module '{0}' was resolved to '{1}', but '--jsx' is not set."), + Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1: diag(6144, ts.DiagnosticCategory.Message, "Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1_6144", "Module '{0}' was resolved as locally declared ambient module in file '{1}'."), + Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified: diag(6145, ts.DiagnosticCategory.Message, "Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified_6145", "Module '{0}' was resolved as ambient module declared in '{1}' since this file was not modified."), + Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h: diag(6146, ts.DiagnosticCategory.Message, "Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h_6146", "Specify the JSX factory function to use when targeting 'react' JSX emit, e.g. 'React.createElement' or 'h'."), + Resolution_for_module_0_was_found_in_cache_from_location_1: diag(6147, ts.DiagnosticCategory.Message, "Resolution_for_module_0_was_found_in_cache_from_location_1_6147", "Resolution for module '{0}' was found in cache from location '{1}'."), + Directory_0_does_not_exist_skipping_all_lookups_in_it: diag(6148, ts.DiagnosticCategory.Message, "Directory_0_does_not_exist_skipping_all_lookups_in_it_6148", "Directory '{0}' does not exist, skipping all lookups in it."), + Show_diagnostic_information: diag(6149, ts.DiagnosticCategory.Message, "Show_diagnostic_information_6149", "Show diagnostic information."), + Show_verbose_diagnostic_information: diag(6150, ts.DiagnosticCategory.Message, "Show_verbose_diagnostic_information_6150", "Show verbose diagnostic information."), + Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file: diag(6151, ts.DiagnosticCategory.Message, "Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file_6151", "Emit a single file with source maps instead of having a separate file."), + Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap_to_be_set: diag(6152, ts.DiagnosticCategory.Message, "Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap__6152", "Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set."), + Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule: diag(6153, ts.DiagnosticCategory.Message, "Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule_6153", "Transpile each file as a separate module (similar to 'ts.transpileModule')."), + Print_names_of_generated_files_part_of_the_compilation: diag(6154, ts.DiagnosticCategory.Message, "Print_names_of_generated_files_part_of_the_compilation_6154", "Print names of generated files part of the compilation."), + Print_names_of_files_part_of_the_compilation: diag(6155, ts.DiagnosticCategory.Message, "Print_names_of_files_part_of_the_compilation_6155", "Print names of files part of the compilation."), + The_locale_used_when_displaying_messages_to_the_user_e_g_en_us: diag(6156, ts.DiagnosticCategory.Message, "The_locale_used_when_displaying_messages_to_the_user_e_g_en_us_6156", "The locale used when displaying messages to the user (e.g. 'en-us')"), + Do_not_generate_custom_helper_functions_like_extends_in_compiled_output: diag(6157, ts.DiagnosticCategory.Message, "Do_not_generate_custom_helper_functions_like_extends_in_compiled_output_6157", "Do not generate custom helper functions like '__extends' in compiled output."), + Do_not_include_the_default_library_file_lib_d_ts: diag(6158, ts.DiagnosticCategory.Message, "Do_not_include_the_default_library_file_lib_d_ts_6158", "Do not include the default library file (lib.d.ts)."), + Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files: diag(6159, ts.DiagnosticCategory.Message, "Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files_6159", "Do not add triple-slash references or imported modules to the list of compiled files."), + Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files: diag(6160, ts.DiagnosticCategory.Message, "Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files_6160", "[Deprecated] Use '--skipLibCheck' instead. Skip type checking of default library declaration files."), + List_of_folders_to_include_type_definitions_from: diag(6161, ts.DiagnosticCategory.Message, "List_of_folders_to_include_type_definitions_from_6161", "List of folders to include type definitions from."), + Disable_size_limitations_on_JavaScript_projects: diag(6162, ts.DiagnosticCategory.Message, "Disable_size_limitations_on_JavaScript_projects_6162", "Disable size limitations on JavaScript projects."), + The_character_set_of_the_input_files: diag(6163, ts.DiagnosticCategory.Message, "The_character_set_of_the_input_files_6163", "The character set of the input files."), + Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files: diag(6164, ts.DiagnosticCategory.Message, "Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files_6164", "Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files."), + Do_not_truncate_error_messages: diag(6165, ts.DiagnosticCategory.Message, "Do_not_truncate_error_messages_6165", "Do not truncate error messages."), + Output_directory_for_generated_declaration_files: diag(6166, ts.DiagnosticCategory.Message, "Output_directory_for_generated_declaration_files_6166", "Output directory for generated declaration files."), + A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl: diag(6167, ts.DiagnosticCategory.Message, "A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl_6167", "A series of entries which re-map imports to lookup locations relative to the 'baseUrl'."), + List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime: diag(6168, ts.DiagnosticCategory.Message, "List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime_6168", "List of root folders whose combined content represents the structure of the project at runtime."), + Show_all_compiler_options: diag(6169, ts.DiagnosticCategory.Message, "Show_all_compiler_options_6169", "Show all compiler options."), + Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file: diag(6170, ts.DiagnosticCategory.Message, "Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file_6170", "[Deprecated] Use '--outFile' instead. Concatenate and emit output to single file"), + Command_line_Options: diag(6171, ts.DiagnosticCategory.Message, "Command_line_Options_6171", "Command-line Options"), + Basic_Options: diag(6172, ts.DiagnosticCategory.Message, "Basic_Options_6172", "Basic Options"), + Strict_Type_Checking_Options: diag(6173, ts.DiagnosticCategory.Message, "Strict_Type_Checking_Options_6173", "Strict Type-Checking Options"), + Module_Resolution_Options: diag(6174, ts.DiagnosticCategory.Message, "Module_Resolution_Options_6174", "Module Resolution Options"), + Source_Map_Options: diag(6175, ts.DiagnosticCategory.Message, "Source_Map_Options_6175", "Source Map Options"), + Additional_Checks: diag(6176, ts.DiagnosticCategory.Message, "Additional_Checks_6176", "Additional Checks"), + Experimental_Options: diag(6177, ts.DiagnosticCategory.Message, "Experimental_Options_6177", "Experimental Options"), + Advanced_Options: diag(6178, ts.DiagnosticCategory.Message, "Advanced_Options_6178", "Advanced Options"), + Provide_full_support_for_iterables_in_for_of_spread_and_destructuring_when_targeting_ES5_or_ES3: diag(6179, ts.DiagnosticCategory.Message, "Provide_full_support_for_iterables_in_for_of_spread_and_destructuring_when_targeting_ES5_or_ES3_6179", "Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'."), + Enable_all_strict_type_checking_options: diag(6180, ts.DiagnosticCategory.Message, "Enable_all_strict_type_checking_options_6180", "Enable all strict type-checking options."), + List_of_language_service_plugins: diag(6181, ts.DiagnosticCategory.Message, "List_of_language_service_plugins_6181", "List of language service plugins."), + Scoped_package_detected_looking_in_0: diag(6182, ts.DiagnosticCategory.Message, "Scoped_package_detected_looking_in_0_6182", "Scoped package detected, looking in '{0}'"), + Reusing_resolution_of_module_0_to_file_1_from_old_program: diag(6183, ts.DiagnosticCategory.Message, "Reusing_resolution_of_module_0_to_file_1_from_old_program_6183", "Reusing resolution of module '{0}' to file '{1}' from old program."), + Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program: diag(6184, ts.DiagnosticCategory.Message, "Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program_6184", "Reusing module resolutions originating in '{0}' since resolutions are unchanged from old program."), + Disable_strict_checking_of_generic_signatures_in_function_types: diag(6185, ts.DiagnosticCategory.Message, "Disable_strict_checking_of_generic_signatures_in_function_types_6185", "Disable strict checking of generic signatures in function types."), + Enable_strict_checking_of_function_types: diag(6186, ts.DiagnosticCategory.Message, "Enable_strict_checking_of_function_types_6186", "Enable strict checking of function types."), + Enable_strict_checking_of_property_initialization_in_classes: diag(6187, ts.DiagnosticCategory.Message, "Enable_strict_checking_of_property_initialization_in_classes_6187", "Enable strict checking of property initialization in classes."), + Numeric_separators_are_not_allowed_here: diag(6188, ts.DiagnosticCategory.Error, "Numeric_separators_are_not_allowed_here_6188", "Numeric separators are not allowed here."), + Multiple_consecutive_numeric_separators_are_not_permitted: diag(6189, ts.DiagnosticCategory.Error, "Multiple_consecutive_numeric_separators_are_not_permitted_6189", "Multiple consecutive numeric separators are not permitted."), + Found_package_json_at_0_Package_ID_is_1: diag(6190, ts.DiagnosticCategory.Message, "Found_package_json_at_0_Package_ID_is_1_6190", "Found 'package.json' at '{0}'. Package ID is '{1}'."), + Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen: diag(6191, ts.DiagnosticCategory.Message, "Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen_6191", "Whether to keep outdated console output in watch mode instead of clearing the screen."), + All_imports_in_import_declaration_are_unused: diag(6192, ts.DiagnosticCategory.Error, "All_imports_in_import_declaration_are_unused_6192", "All imports in import declaration are unused.", /*reportsUnnecessary*/ true), + Found_1_error_Watching_for_file_changes: diag(6193, ts.DiagnosticCategory.Message, "Found_1_error_Watching_for_file_changes_6193", "Found 1 error. Watching for file changes."), + Found_0_errors_Watching_for_file_changes: diag(6194, ts.DiagnosticCategory.Message, "Found_0_errors_Watching_for_file_changes_6194", "Found {0} errors. Watching for file changes."), + Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols: diag(6195, ts.DiagnosticCategory.Message, "Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols_6195", "Resolve 'keyof' to string valued property names only (no numbers or symbols)."), + _0_is_declared_but_never_used: diag(6196, ts.DiagnosticCategory.Error, "_0_is_declared_but_never_used_6196", "'{0}' is declared but never used.", /*reportsUnnecessary*/ true), + Include_modules_imported_with_json_extension: diag(6197, ts.DiagnosticCategory.Message, "Include_modules_imported_with_json_extension_6197", "Include modules imported with '.json' extension"), + All_destructured_elements_are_unused: diag(6198, ts.DiagnosticCategory.Error, "All_destructured_elements_are_unused_6198", "All destructured elements are unused.", /*reportsUnnecessary*/ true), + All_variables_are_unused: diag(6199, ts.DiagnosticCategory.Error, "All_variables_are_unused_6199", "All variables are unused.", /*reportsUnnecessary*/ true), + Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0: diag(6200, ts.DiagnosticCategory.Error, "Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0_6200", "Definitions of the following identifiers conflict with those in another file: {0}"), + Conflicts_are_in_this_file: diag(6201, ts.DiagnosticCategory.Message, "Conflicts_are_in_this_file_6201", "Conflicts are in this file."), + _0_was_also_declared_here: diag(6203, ts.DiagnosticCategory.Message, "_0_was_also_declared_here_6203", "'{0}' was also declared here."), + and_here: diag(6204, ts.DiagnosticCategory.Message, "and_here_6204", "and here."), + All_type_parameters_are_unused: diag(6205, ts.DiagnosticCategory.Error, "All_type_parameters_are_unused_6205", "All type parameters are unused"), + package_json_has_a_typesVersions_field_with_version_specific_path_mappings: diag(6206, ts.DiagnosticCategory.Message, "package_json_has_a_typesVersions_field_with_version_specific_path_mappings_6206", "'package.json' has a 'typesVersions' field with version-specific path mappings."), + package_json_does_not_have_a_typesVersions_entry_that_matches_version_0: diag(6207, ts.DiagnosticCategory.Message, "package_json_does_not_have_a_typesVersions_entry_that_matches_version_0_6207", "'package.json' does not have a 'typesVersions' entry that matches version '{0}'."), + package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2: diag(6208, ts.DiagnosticCategory.Message, "package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_ma_6208", "'package.json' has a 'typesVersions' entry '{0}' that matches compiler version '{1}', looking for a pattern to match module name '{2}'."), + package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range: diag(6209, ts.DiagnosticCategory.Message, "package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range_6209", "'package.json' has a 'typesVersions' entry '{0}' that is not a valid semver range."), + An_argument_for_0_was_not_provided: diag(6210, ts.DiagnosticCategory.Message, "An_argument_for_0_was_not_provided_6210", "An argument for '{0}' was not provided."), + An_argument_matching_this_binding_pattern_was_not_provided: diag(6211, ts.DiagnosticCategory.Message, "An_argument_matching_this_binding_pattern_was_not_provided_6211", "An argument matching this binding pattern was not provided."), + Did_you_mean_to_call_this_expression: diag(6212, ts.DiagnosticCategory.Message, "Did_you_mean_to_call_this_expression_6212", "Did you mean to call this expression?"), + Did_you_mean_to_use_new_with_this_expression: diag(6213, ts.DiagnosticCategory.Message, "Did_you_mean_to_use_new_with_this_expression_6213", "Did you mean to use 'new' with this expression?"), + Enable_strict_bind_call_and_apply_methods_on_functions: diag(6214, ts.DiagnosticCategory.Message, "Enable_strict_bind_call_and_apply_methods_on_functions_6214", "Enable strict 'bind', 'call', and 'apply' methods on functions."), + Using_compiler_options_of_project_reference_redirect_0: diag(6215, ts.DiagnosticCategory.Message, "Using_compiler_options_of_project_reference_redirect_0_6215", "Using compiler options of project reference redirect '{0}'."), + Found_1_error: diag(6216, ts.DiagnosticCategory.Message, "Found_1_error_6216", "Found 1 error."), + Found_0_errors: diag(6217, ts.DiagnosticCategory.Message, "Found_0_errors_6217", "Found {0} errors."), + Projects_to_reference: diag(6300, ts.DiagnosticCategory.Message, "Projects_to_reference_6300", "Projects to reference"), + Enable_project_compilation: diag(6302, ts.DiagnosticCategory.Message, "Enable_project_compilation_6302", "Enable project compilation"), + Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0: diag(6202, ts.DiagnosticCategory.Error, "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202", "Project references may not form a circular graph. Cycle detected: {0}"), + Composite_projects_may_not_disable_declaration_emit: diag(6304, ts.DiagnosticCategory.Error, "Composite_projects_may_not_disable_declaration_emit_6304", "Composite projects may not disable declaration emit."), + Output_file_0_has_not_been_built_from_source_file_1: diag(6305, ts.DiagnosticCategory.Error, "Output_file_0_has_not_been_built_from_source_file_1_6305", "Output file '{0}' has not been built from source file '{1}'."), + Referenced_project_0_must_have_setting_composite_Colon_true: diag(6306, ts.DiagnosticCategory.Error, "Referenced_project_0_must_have_setting_composite_Colon_true_6306", "Referenced project '{0}' must have setting \"composite\": true."), + File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern: diag(6307, ts.DiagnosticCategory.Error, "File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern_6307", "File '{0}' is not in project file list. Projects must list all files or use an 'include' pattern."), + Cannot_prepend_project_0_because_it_does_not_have_outFile_set: diag(6308, ts.DiagnosticCategory.Error, "Cannot_prepend_project_0_because_it_does_not_have_outFile_set_6308", "Cannot prepend project '{0}' because it does not have 'outFile' set"), + Output_file_0_from_project_1_does_not_exist: diag(6309, ts.DiagnosticCategory.Error, "Output_file_0_from_project_1_does_not_exist_6309", "Output file '{0}' from project '{1}' does not exist"), + Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2: diag(6350, ts.DiagnosticCategory.Message, "Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2_6350", "Project '{0}' is out of date because oldest output '{1}' is older than newest input '{2}'"), + Project_0_is_up_to_date_because_newest_input_1_is_older_than_oldest_output_2: diag(6351, ts.DiagnosticCategory.Message, "Project_0_is_up_to_date_because_newest_input_1_is_older_than_oldest_output_2_6351", "Project '{0}' is up to date because newest input '{1}' is older than oldest output '{2}'"), + Project_0_is_out_of_date_because_output_file_1_does_not_exist: diag(6352, ts.DiagnosticCategory.Message, "Project_0_is_out_of_date_because_output_file_1_does_not_exist_6352", "Project '{0}' is out of date because output file '{1}' does not exist"), + Project_0_is_out_of_date_because_its_dependency_1_is_out_of_date: diag(6353, ts.DiagnosticCategory.Message, "Project_0_is_out_of_date_because_its_dependency_1_is_out_of_date_6353", "Project '{0}' is out of date because its dependency '{1}' is out of date"), + Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies: diag(6354, ts.DiagnosticCategory.Message, "Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies_6354", "Project '{0}' is up to date with .d.ts files from its dependencies"), + Projects_in_this_build_Colon_0: diag(6355, ts.DiagnosticCategory.Message, "Projects_in_this_build_Colon_0_6355", "Projects in this build: {0}"), + A_non_dry_build_would_delete_the_following_files_Colon_0: diag(6356, ts.DiagnosticCategory.Message, "A_non_dry_build_would_delete_the_following_files_Colon_0_6356", "A non-dry build would delete the following files: {0}"), + A_non_dry_build_would_build_project_0: diag(6357, ts.DiagnosticCategory.Message, "A_non_dry_build_would_build_project_0_6357", "A non-dry build would build project '{0}'"), + Building_project_0: diag(6358, ts.DiagnosticCategory.Message, "Building_project_0_6358", "Building project '{0}'..."), + Updating_output_timestamps_of_project_0: diag(6359, ts.DiagnosticCategory.Message, "Updating_output_timestamps_of_project_0_6359", "Updating output timestamps of project '{0}'..."), + delete_this_Project_0_is_up_to_date_because_it_was_previously_built: diag(6360, ts.DiagnosticCategory.Message, "delete_this_Project_0_is_up_to_date_because_it_was_previously_built_6360", "delete this - Project '{0}' is up to date because it was previously built"), + Project_0_is_up_to_date: diag(6361, ts.DiagnosticCategory.Message, "Project_0_is_up_to_date_6361", "Project '{0}' is up to date"), + Skipping_build_of_project_0_because_its_dependency_1_has_errors: diag(6362, ts.DiagnosticCategory.Message, "Skipping_build_of_project_0_because_its_dependency_1_has_errors_6362", "Skipping build of project '{0}' because its dependency '{1}' has errors"), + Project_0_can_t_be_built_because_its_dependency_1_has_errors: diag(6363, ts.DiagnosticCategory.Message, "Project_0_can_t_be_built_because_its_dependency_1_has_errors_6363", "Project '{0}' can't be built because its dependency '{1}' has errors"), + Build_one_or_more_projects_and_their_dependencies_if_out_of_date: diag(6364, ts.DiagnosticCategory.Message, "Build_one_or_more_projects_and_their_dependencies_if_out_of_date_6364", "Build one or more projects and their dependencies, if out of date"), + Delete_the_outputs_of_all_projects: diag(6365, ts.DiagnosticCategory.Message, "Delete_the_outputs_of_all_projects_6365", "Delete the outputs of all projects"), + Enable_verbose_logging: diag(6366, ts.DiagnosticCategory.Message, "Enable_verbose_logging_6366", "Enable verbose logging"), + Show_what_would_be_built_or_deleted_if_specified_with_clean: diag(6367, ts.DiagnosticCategory.Message, "Show_what_would_be_built_or_deleted_if_specified_with_clean_6367", "Show what would be built (or deleted, if specified with '--clean')"), + Build_all_projects_including_those_that_appear_to_be_up_to_date: diag(6368, ts.DiagnosticCategory.Message, "Build_all_projects_including_those_that_appear_to_be_up_to_date_6368", "Build all projects, including those that appear to be up to date"), + Option_build_must_be_the_first_command_line_argument: diag(6369, ts.DiagnosticCategory.Error, "Option_build_must_be_the_first_command_line_argument_6369", "Option '--build' must be the first command line argument."), + Options_0_and_1_cannot_be_combined: diag(6370, ts.DiagnosticCategory.Error, "Options_0_and_1_cannot_be_combined_6370", "Options '{0}' and '{1}' cannot be combined."), + The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1: diag(6500, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1_6500", "The expected type comes from property '{0}' which is declared here on type '{1}'"), + The_expected_type_comes_from_this_index_signature: diag(6501, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_this_index_signature_6501", "The expected type comes from this index signature."), + The_expected_type_comes_from_the_return_type_of_this_signature: diag(6502, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_the_return_type_of_this_signature_6502", "The expected type comes from the return type of this signature."), + Variable_0_implicitly_has_an_1_type: diag(7005, ts.DiagnosticCategory.Error, "Variable_0_implicitly_has_an_1_type_7005", "Variable '{0}' implicitly has an '{1}' type."), + Parameter_0_implicitly_has_an_1_type: diag(7006, ts.DiagnosticCategory.Error, "Parameter_0_implicitly_has_an_1_type_7006", "Parameter '{0}' implicitly has an '{1}' type."), + Member_0_implicitly_has_an_1_type: diag(7008, ts.DiagnosticCategory.Error, "Member_0_implicitly_has_an_1_type_7008", "Member '{0}' implicitly has an '{1}' type."), + new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type: diag(7009, ts.DiagnosticCategory.Error, "new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type_7009", "'new' expression, whose target lacks a construct signature, implicitly has an 'any' type."), + _0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type: diag(7010, ts.DiagnosticCategory.Error, "_0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type_7010", "'{0}', which lacks return-type annotation, implicitly has an '{1}' return type."), + Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type: diag(7011, ts.DiagnosticCategory.Error, "Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type_7011", "Function expression, which lacks return-type annotation, implicitly has an '{0}' return type."), + Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: diag(7013, ts.DiagnosticCategory.Error, "Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7013", "Construct signature, which lacks return-type annotation, implicitly has an 'any' return type."), + Function_type_which_lacks_return_type_annotation_implicitly_has_an_0_return_type: diag(7014, ts.DiagnosticCategory.Error, "Function_type_which_lacks_return_type_annotation_implicitly_has_an_0_return_type_7014", "Function type, which lacks return-type annotation, implicitly has an '{0}' return type."), + Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number: diag(7015, ts.DiagnosticCategory.Error, "Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015", "Element implicitly has an 'any' type because index expression is not of type 'number'."), + Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type: diag(7016, ts.DiagnosticCategory.Error, "Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type_7016", "Could not find a declaration file for module '{0}'. '{1}' implicitly has an 'any' type."), + Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature: diag(7017, ts.DiagnosticCategory.Error, "Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature_7017", "Element implicitly has an 'any' type because type '{0}' has no index signature."), + Object_literal_s_property_0_implicitly_has_an_1_type: diag(7018, ts.DiagnosticCategory.Error, "Object_literal_s_property_0_implicitly_has_an_1_type_7018", "Object literal's property '{0}' implicitly has an '{1}' type."), + Rest_parameter_0_implicitly_has_an_any_type: diag(7019, ts.DiagnosticCategory.Error, "Rest_parameter_0_implicitly_has_an_any_type_7019", "Rest parameter '{0}' implicitly has an 'any[]' type."), + Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: diag(7020, ts.DiagnosticCategory.Error, "Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7020", "Call signature, which lacks return-type annotation, implicitly has an 'any' return type."), + _0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer: diag(7022, ts.DiagnosticCategory.Error, "_0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or__7022", "'{0}' implicitly has type 'any' because it does not have a type annotation and is referenced directly or indirectly in its own initializer."), + _0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions: diag(7023, ts.DiagnosticCategory.Error, "_0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_reference_7023", "'{0}' implicitly has return type 'any' because it does not have a return type annotation and is referenced directly or indirectly in one of its return expressions."), + Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions: diag(7024, ts.DiagnosticCategory.Error, "Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_ref_7024", "Function implicitly has return type 'any' because it does not have a return type annotation and is referenced directly or indirectly in one of its return expressions."), + Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_type: diag(7025, ts.DiagnosticCategory.Error, "Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_typ_7025", "Generator implicitly has type '{0}' because it does not yield any values. Consider supplying a return type."), + JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists: diag(7026, ts.DiagnosticCategory.Error, "JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists_7026", "JSX element implicitly has type 'any' because no interface 'JSX.{0}' exists."), + Unreachable_code_detected: diag(7027, ts.DiagnosticCategory.Error, "Unreachable_code_detected_7027", "Unreachable code detected.", /*reportsUnnecessary*/ true), + Unused_label: diag(7028, ts.DiagnosticCategory.Error, "Unused_label_7028", "Unused label.", /*reportsUnnecessary*/ true), + Fallthrough_case_in_switch: diag(7029, ts.DiagnosticCategory.Error, "Fallthrough_case_in_switch_7029", "Fallthrough case in switch."), + Not_all_code_paths_return_a_value: diag(7030, ts.DiagnosticCategory.Error, "Not_all_code_paths_return_a_value_7030", "Not all code paths return a value."), + Binding_element_0_implicitly_has_an_1_type: diag(7031, ts.DiagnosticCategory.Error, "Binding_element_0_implicitly_has_an_1_type_7031", "Binding element '{0}' implicitly has an '{1}' type."), + Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation: diag(7032, ts.DiagnosticCategory.Error, "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032", "Property '{0}' implicitly has type 'any', because its set accessor lacks a parameter type annotation."), + Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation: diag(7033, ts.DiagnosticCategory.Error, "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033", "Property '{0}' implicitly has type 'any', because its get accessor lacks a return type annotation."), + Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined: diag(7034, ts.DiagnosticCategory.Error, "Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined_7034", "Variable '{0}' implicitly has type '{1}' in some locations where its type cannot be determined."), + Try_npm_install_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0: diag(7035, ts.DiagnosticCategory.Error, "Try_npm_install_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_mod_7035", "Try `npm install @types/{1}` if it exists or add a new declaration (.d.ts) file containing `declare module '{0}';`"), + Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0: diag(7036, ts.DiagnosticCategory.Error, "Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036", "Dynamic import's specifier must be of type 'string', but here has type '{0}'."), + Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for_all_imports_Implies_allowSyntheticDefaultImports: diag(7037, ts.DiagnosticCategory.Message, "Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for__7037", "Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'."), + Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_Consider_using_a_default_import_or_import_require_here_instead: diag(7038, ts.DiagnosticCategory.Message, "Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cau_7038", "Type originates at this import. A namespace-style import cannot be called or constructed, and will cause a failure at runtime. Consider using a default import or import require here instead."), + Mapped_object_type_implicitly_has_an_any_template_type: diag(7039, ts.DiagnosticCategory.Error, "Mapped_object_type_implicitly_has_an_any_template_type_7039", "Mapped object type implicitly has an 'any' template type."), + If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1: diag(7040, ts.DiagnosticCategory.Error, "If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_S_7040", "If the '{0}' package actually exposes this module, consider sending a pull request to amend 'https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/{1}`"), + The_containing_arrow_function_captures_the_global_value_of_this_which_implicitly_has_type_any: diag(7041, ts.DiagnosticCategory.Error, "The_containing_arrow_function_captures_the_global_value_of_this_which_implicitly_has_type_any_7041", "The containing arrow function captures the global value of 'this' which implicitly has type 'any'."), + Module_0_was_resolved_to_1_but_resolveJsonModule_is_not_used: diag(7042, ts.DiagnosticCategory.Error, "Module_0_was_resolved_to_1_but_resolveJsonModule_is_not_used_7042", "Module '{0}' was resolved to '{1}', but '--resolveJsonModule' is not used."), + Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage: diag(7043, ts.DiagnosticCategory.Suggestion, "Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7043", "Variable '{0}' implicitly has an '{1}' type, but a better type may be inferred from usage."), + Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage: diag(7044, ts.DiagnosticCategory.Suggestion, "Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7044", "Parameter '{0}' implicitly has an '{1}' type, but a better type may be inferred from usage."), + Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage: diag(7045, ts.DiagnosticCategory.Suggestion, "Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7045", "Member '{0}' implicitly has an '{1}' type, but a better type may be inferred from usage."), + Variable_0_implicitly_has_type_1_in_some_locations_but_a_better_type_may_be_inferred_from_usage: diag(7046, ts.DiagnosticCategory.Suggestion, "Variable_0_implicitly_has_type_1_in_some_locations_but_a_better_type_may_be_inferred_from_usage_7046", "Variable '{0}' implicitly has type '{1}' in some locations, but a better type may be inferred from usage."), + Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage: diag(7047, ts.DiagnosticCategory.Suggestion, "Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage_7047", "Rest parameter '{0}' implicitly has an 'any[]' type, but a better type may be inferred from usage."), + Property_0_implicitly_has_type_any_but_a_better_type_for_its_get_accessor_may_be_inferred_from_usage: diag(7048, ts.DiagnosticCategory.Suggestion, "Property_0_implicitly_has_type_any_but_a_better_type_for_its_get_accessor_may_be_inferred_from_usage_7048", "Property '{0}' implicitly has type 'any', but a better type for its get accessor may be inferred from usage."), + Property_0_implicitly_has_type_any_but_a_better_type_for_its_set_accessor_may_be_inferred_from_usage: diag(7049, ts.DiagnosticCategory.Suggestion, "Property_0_implicitly_has_type_any_but_a_better_type_for_its_set_accessor_may_be_inferred_from_usage_7049", "Property '{0}' implicitly has type 'any', but a better type for its set accessor may be inferred from usage."), + _0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage: diag(7050, ts.DiagnosticCategory.Suggestion, "_0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage_7050", "'{0}' implicitly has an '{1}' return type, but a better type may be inferred from usage."), + Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1: diag(7051, ts.DiagnosticCategory.Error, "Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1_7051", "Parameter has a name but no type. Did you mean '{0}: {1}'?"), + You_cannot_rename_this_element: diag(8000, ts.DiagnosticCategory.Error, "You_cannot_rename_this_element_8000", "You cannot rename this element."), + You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library: diag(8001, ts.DiagnosticCategory.Error, "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001", "You cannot rename elements that are defined in the standard TypeScript library."), + import_can_only_be_used_in_a_ts_file: diag(8002, ts.DiagnosticCategory.Error, "import_can_only_be_used_in_a_ts_file_8002", "'import ... =' can only be used in a .ts file."), + export_can_only_be_used_in_a_ts_file: diag(8003, ts.DiagnosticCategory.Error, "export_can_only_be_used_in_a_ts_file_8003", "'export=' can only be used in a .ts file."), + type_parameter_declarations_can_only_be_used_in_a_ts_file: diag(8004, ts.DiagnosticCategory.Error, "type_parameter_declarations_can_only_be_used_in_a_ts_file_8004", "'type parameter declarations' can only be used in a .ts file."), + implements_clauses_can_only_be_used_in_a_ts_file: diag(8005, ts.DiagnosticCategory.Error, "implements_clauses_can_only_be_used_in_a_ts_file_8005", "'implements clauses' can only be used in a .ts file."), + interface_declarations_can_only_be_used_in_a_ts_file: diag(8006, ts.DiagnosticCategory.Error, "interface_declarations_can_only_be_used_in_a_ts_file_8006", "'interface declarations' can only be used in a .ts file."), + module_declarations_can_only_be_used_in_a_ts_file: diag(8007, ts.DiagnosticCategory.Error, "module_declarations_can_only_be_used_in_a_ts_file_8007", "'module declarations' can only be used in a .ts file."), + type_aliases_can_only_be_used_in_a_ts_file: diag(8008, ts.DiagnosticCategory.Error, "type_aliases_can_only_be_used_in_a_ts_file_8008", "'type aliases' can only be used in a .ts file."), + _0_can_only_be_used_in_a_ts_file: diag(8009, ts.DiagnosticCategory.Error, "_0_can_only_be_used_in_a_ts_file_8009", "'{0}' can only be used in a .ts file."), + types_can_only_be_used_in_a_ts_file: diag(8010, ts.DiagnosticCategory.Error, "types_can_only_be_used_in_a_ts_file_8010", "'types' can only be used in a .ts file."), + type_arguments_can_only_be_used_in_a_ts_file: diag(8011, ts.DiagnosticCategory.Error, "type_arguments_can_only_be_used_in_a_ts_file_8011", "'type arguments' can only be used in a .ts file."), + parameter_modifiers_can_only_be_used_in_a_ts_file: diag(8012, ts.DiagnosticCategory.Error, "parameter_modifiers_can_only_be_used_in_a_ts_file_8012", "'parameter modifiers' can only be used in a .ts file."), + non_null_assertions_can_only_be_used_in_a_ts_file: diag(8013, ts.DiagnosticCategory.Error, "non_null_assertions_can_only_be_used_in_a_ts_file_8013", "'non-null assertions' can only be used in a .ts file."), + enum_declarations_can_only_be_used_in_a_ts_file: diag(8015, ts.DiagnosticCategory.Error, "enum_declarations_can_only_be_used_in_a_ts_file_8015", "'enum declarations' can only be used in a .ts file."), + type_assertion_expressions_can_only_be_used_in_a_ts_file: diag(8016, ts.DiagnosticCategory.Error, "type_assertion_expressions_can_only_be_used_in_a_ts_file_8016", "'type assertion expressions' can only be used in a .ts file."), + Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0: diag(8017, ts.DiagnosticCategory.Error, "Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0_8017", "Octal literal types must use ES2015 syntax. Use the syntax '{0}'."), + Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0: diag(8018, ts.DiagnosticCategory.Error, "Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0_8018", "Octal literals are not allowed in enums members initializer. Use the syntax '{0}'."), + Report_errors_in_js_files: diag(8019, ts.DiagnosticCategory.Message, "Report_errors_in_js_files_8019", "Report errors in .js files."), + JSDoc_types_can_only_be_used_inside_documentation_comments: diag(8020, ts.DiagnosticCategory.Error, "JSDoc_types_can_only_be_used_inside_documentation_comments_8020", "JSDoc types can only be used inside documentation comments."), + JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags: diag(8021, ts.DiagnosticCategory.Error, "JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags_8021", "JSDoc '@typedef' tag should either have a type annotation or be followed by '@property' or '@member' tags."), + JSDoc_0_is_not_attached_to_a_class: diag(8022, ts.DiagnosticCategory.Error, "JSDoc_0_is_not_attached_to_a_class_8022", "JSDoc '@{0}' is not attached to a class."), + JSDoc_0_1_does_not_match_the_extends_2_clause: diag(8023, ts.DiagnosticCategory.Error, "JSDoc_0_1_does_not_match_the_extends_2_clause_8023", "JSDoc '@{0} {1}' does not match the 'extends {2}' clause."), + JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name: diag(8024, ts.DiagnosticCategory.Error, "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_8024", "JSDoc '@param' tag has name '{0}', but there is no parameter with that name."), + Class_declarations_cannot_have_more_than_one_augments_or_extends_tag: diag(8025, ts.DiagnosticCategory.Error, "Class_declarations_cannot_have_more_than_one_augments_or_extends_tag_8025", "Class declarations cannot have more than one `@augments` or `@extends` tag."), + Expected_0_type_arguments_provide_these_with_an_extends_tag: diag(8026, ts.DiagnosticCategory.Error, "Expected_0_type_arguments_provide_these_with_an_extends_tag_8026", "Expected {0} type arguments; provide these with an '@extends' tag."), + Expected_0_1_type_arguments_provide_these_with_an_extends_tag: diag(8027, ts.DiagnosticCategory.Error, "Expected_0_1_type_arguments_provide_these_with_an_extends_tag_8027", "Expected {0}-{1} type arguments; provide these with an '@extends' tag."), + JSDoc_may_only_appear_in_the_last_parameter_of_a_signature: diag(8028, ts.DiagnosticCategory.Error, "JSDoc_may_only_appear_in_the_last_parameter_of_a_signature_8028", "JSDoc '...' may only appear in the last parameter of a signature."), + JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_had_an_array_type: diag(8029, ts.DiagnosticCategory.Error, "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_h_8029", "JSDoc '@param' tag has name '{0}', but there is no parameter with that name. It would match 'arguments' if it had an array type."), + The_type_of_a_function_declaration_must_match_the_function_s_signature: diag(8030, ts.DiagnosticCategory.Error, "The_type_of_a_function_declaration_must_match_the_function_s_signature_8030", "The type of a function declaration must match the function's signature."), + You_cannot_rename_a_module_via_a_global_import: diag(8031, ts.DiagnosticCategory.Error, "You_cannot_rename_a_module_via_a_global_import_8031", "You cannot rename a module via a global import."), + Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_class_extends_clause: diag(9002, ts.DiagnosticCategory.Error, "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002", "Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clause."), + class_expressions_are_not_currently_supported: diag(9003, ts.DiagnosticCategory.Error, "class_expressions_are_not_currently_supported_9003", "'class' expressions are not currently supported."), + Language_service_is_disabled: diag(9004, ts.DiagnosticCategory.Error, "Language_service_is_disabled_9004", "Language service is disabled."), + JSX_attributes_must_only_be_assigned_a_non_empty_expression: diag(17000, ts.DiagnosticCategory.Error, "JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000", "JSX attributes must only be assigned a non-empty 'expression'."), + JSX_elements_cannot_have_multiple_attributes_with_the_same_name: diag(17001, ts.DiagnosticCategory.Error, "JSX_elements_cannot_have_multiple_attributes_with_the_same_name_17001", "JSX elements cannot have multiple attributes with the same name."), + Expected_corresponding_JSX_closing_tag_for_0: diag(17002, ts.DiagnosticCategory.Error, "Expected_corresponding_JSX_closing_tag_for_0_17002", "Expected corresponding JSX closing tag for '{0}'."), + JSX_attribute_expected: diag(17003, ts.DiagnosticCategory.Error, "JSX_attribute_expected_17003", "JSX attribute expected."), + Cannot_use_JSX_unless_the_jsx_flag_is_provided: diag(17004, ts.DiagnosticCategory.Error, "Cannot_use_JSX_unless_the_jsx_flag_is_provided_17004", "Cannot use JSX unless the '--jsx' flag is provided."), + A_constructor_cannot_contain_a_super_call_when_its_class_extends_null: diag(17005, ts.DiagnosticCategory.Error, "A_constructor_cannot_contain_a_super_call_when_its_class_extends_null_17005", "A constructor cannot contain a 'super' call when its class extends 'null'."), + An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses: diag(17006, ts.DiagnosticCategory.Error, "An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_ex_17006", "An unary expression with the '{0}' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses."), + A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses: diag(17007, ts.DiagnosticCategory.Error, "A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Con_17007", "A type assertion expression is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses."), + JSX_element_0_has_no_corresponding_closing_tag: diag(17008, ts.DiagnosticCategory.Error, "JSX_element_0_has_no_corresponding_closing_tag_17008", "JSX element '{0}' has no corresponding closing tag."), + super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class: diag(17009, ts.DiagnosticCategory.Error, "super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class_17009", "'super' must be called before accessing 'this' in the constructor of a derived class."), + Unknown_type_acquisition_option_0: diag(17010, ts.DiagnosticCategory.Error, "Unknown_type_acquisition_option_0_17010", "Unknown type acquisition option '{0}'."), + super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class: diag(17011, ts.DiagnosticCategory.Error, "super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class_17011", "'super' must be called before accessing a property of 'super' in the constructor of a derived class."), + _0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2: diag(17012, ts.DiagnosticCategory.Error, "_0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2_17012", "'{0}' is not a valid meta-property for keyword '{1}'. Did you mean '{2}'?"), + Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constructor: diag(17013, ts.DiagnosticCategory.Error, "Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constru_17013", "Meta-property '{0}' is only allowed in the body of a function declaration, function expression, or constructor."), + JSX_fragment_has_no_corresponding_closing_tag: diag(17014, ts.DiagnosticCategory.Error, "JSX_fragment_has_no_corresponding_closing_tag_17014", "JSX fragment has no corresponding closing tag."), + Expected_corresponding_closing_tag_for_JSX_fragment: diag(17015, ts.DiagnosticCategory.Error, "Expected_corresponding_closing_tag_for_JSX_fragment_17015", "Expected corresponding closing tag for JSX fragment."), + JSX_fragment_is_not_supported_when_using_jsxFactory: diag(17016, ts.DiagnosticCategory.Error, "JSX_fragment_is_not_supported_when_using_jsxFactory_17016", "JSX fragment is not supported when using --jsxFactory"), + JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma: diag(17017, ts.DiagnosticCategory.Error, "JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma_17017", "JSX fragment is not supported when using an inline JSX factory pragma"), + Circularity_detected_while_resolving_configuration_Colon_0: diag(18000, ts.DiagnosticCategory.Error, "Circularity_detected_while_resolving_configuration_Colon_0_18000", "Circularity detected while resolving configuration: {0}"), + A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not: diag(18001, ts.DiagnosticCategory.Error, "A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not_18001", "A path in an 'extends' option must be relative or rooted, but '{0}' is not."), + The_files_list_in_config_file_0_is_empty: diag(18002, ts.DiagnosticCategory.Error, "The_files_list_in_config_file_0_is_empty_18002", "The 'files' list in config file '{0}' is empty."), + No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2: diag(18003, ts.DiagnosticCategory.Error, "No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2_18003", "No inputs were found in config file '{0}'. Specified 'include' paths were '{1}' and 'exclude' paths were '{2}'."), + File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module: diag(80001, ts.DiagnosticCategory.Suggestion, "File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module_80001", "File is a CommonJS module; it may be converted to an ES6 module."), + This_constructor_function_may_be_converted_to_a_class_declaration: diag(80002, ts.DiagnosticCategory.Suggestion, "This_constructor_function_may_be_converted_to_a_class_declaration_80002", "This constructor function may be converted to a class declaration."), + Import_may_be_converted_to_a_default_import: diag(80003, ts.DiagnosticCategory.Suggestion, "Import_may_be_converted_to_a_default_import_80003", "Import may be converted to a default import."), + JSDoc_types_may_be_moved_to_TypeScript_types: diag(80004, ts.DiagnosticCategory.Suggestion, "JSDoc_types_may_be_moved_to_TypeScript_types_80004", "JSDoc types may be moved to TypeScript types."), + require_call_may_be_converted_to_an_import: diag(80005, ts.DiagnosticCategory.Suggestion, "require_call_may_be_converted_to_an_import_80005", "'require' call may be converted to an import."), + This_may_be_converted_to_an_async_function: diag(80006, ts.DiagnosticCategory.Suggestion, "This_may_be_converted_to_an_async_function_80006", "This may be converted to an async function."), + Add_missing_super_call: diag(90001, ts.DiagnosticCategory.Message, "Add_missing_super_call_90001", "Add missing 'super()' call"), + Make_super_call_the_first_statement_in_the_constructor: diag(90002, ts.DiagnosticCategory.Message, "Make_super_call_the_first_statement_in_the_constructor_90002", "Make 'super()' call the first statement in the constructor"), + Change_extends_to_implements: diag(90003, ts.DiagnosticCategory.Message, "Change_extends_to_implements_90003", "Change 'extends' to 'implements'"), + Remove_declaration_for_Colon_0: diag(90004, ts.DiagnosticCategory.Message, "Remove_declaration_for_Colon_0_90004", "Remove declaration for: '{0}'"), + Remove_import_from_0: diag(90005, ts.DiagnosticCategory.Message, "Remove_import_from_0_90005", "Remove import from '{0}'"), + Implement_interface_0: diag(90006, ts.DiagnosticCategory.Message, "Implement_interface_0_90006", "Implement interface '{0}'"), + Implement_inherited_abstract_class: diag(90007, ts.DiagnosticCategory.Message, "Implement_inherited_abstract_class_90007", "Implement inherited abstract class"), + Add_0_to_unresolved_variable: diag(90008, ts.DiagnosticCategory.Message, "Add_0_to_unresolved_variable_90008", "Add '{0}.' to unresolved variable"), + Remove_destructuring: diag(90009, ts.DiagnosticCategory.Message, "Remove_destructuring_90009", "Remove destructuring"), + Remove_variable_statement: diag(90010, ts.DiagnosticCategory.Message, "Remove_variable_statement_90010", "Remove variable statement"), + Remove_template_tag: diag(90011, ts.DiagnosticCategory.Message, "Remove_template_tag_90011", "Remove template tag"), + Remove_type_parameters: diag(90012, ts.DiagnosticCategory.Message, "Remove_type_parameters_90012", "Remove type parameters"), + Import_0_from_module_1: diag(90013, ts.DiagnosticCategory.Message, "Import_0_from_module_1_90013", "Import '{0}' from module \"{1}\""), + Change_0_to_1: diag(90014, ts.DiagnosticCategory.Message, "Change_0_to_1_90014", "Change '{0}' to '{1}'"), + Add_0_to_existing_import_declaration_from_1: diag(90015, ts.DiagnosticCategory.Message, "Add_0_to_existing_import_declaration_from_1_90015", "Add '{0}' to existing import declaration from \"{1}\""), + Declare_property_0: diag(90016, ts.DiagnosticCategory.Message, "Declare_property_0_90016", "Declare property '{0}'"), + Add_index_signature_for_property_0: diag(90017, ts.DiagnosticCategory.Message, "Add_index_signature_for_property_0_90017", "Add index signature for property '{0}'"), + Disable_checking_for_this_file: diag(90018, ts.DiagnosticCategory.Message, "Disable_checking_for_this_file_90018", "Disable checking for this file"), + Ignore_this_error_message: diag(90019, ts.DiagnosticCategory.Message, "Ignore_this_error_message_90019", "Ignore this error message"), + Initialize_property_0_in_the_constructor: diag(90020, ts.DiagnosticCategory.Message, "Initialize_property_0_in_the_constructor_90020", "Initialize property '{0}' in the constructor"), + Initialize_static_property_0: diag(90021, ts.DiagnosticCategory.Message, "Initialize_static_property_0_90021", "Initialize static property '{0}'"), + Change_spelling_to_0: diag(90022, ts.DiagnosticCategory.Message, "Change_spelling_to_0_90022", "Change spelling to '{0}'"), + Declare_method_0: diag(90023, ts.DiagnosticCategory.Message, "Declare_method_0_90023", "Declare method '{0}'"), + Declare_static_method_0: diag(90024, ts.DiagnosticCategory.Message, "Declare_static_method_0_90024", "Declare static method '{0}'"), + Prefix_0_with_an_underscore: diag(90025, ts.DiagnosticCategory.Message, "Prefix_0_with_an_underscore_90025", "Prefix '{0}' with an underscore"), + Rewrite_as_the_indexed_access_type_0: diag(90026, ts.DiagnosticCategory.Message, "Rewrite_as_the_indexed_access_type_0_90026", "Rewrite as the indexed access type '{0}'"), + Declare_static_property_0: diag(90027, ts.DiagnosticCategory.Message, "Declare_static_property_0_90027", "Declare static property '{0}'"), + Call_decorator_expression: diag(90028, ts.DiagnosticCategory.Message, "Call_decorator_expression_90028", "Call decorator expression"), + Add_async_modifier_to_containing_function: diag(90029, ts.DiagnosticCategory.Message, "Add_async_modifier_to_containing_function_90029", "Add async modifier to containing function"), + Replace_infer_0_with_unknown: diag(90030, ts.DiagnosticCategory.Message, "Replace_infer_0_with_unknown_90030", "Replace 'infer {0}' with 'unknown'"), + Replace_all_unused_infer_with_unknown: diag(90031, ts.DiagnosticCategory.Message, "Replace_all_unused_infer_with_unknown_90031", "Replace all unused 'infer' with 'unknown'"), + Import_default_0_from_module_1: diag(90032, ts.DiagnosticCategory.Message, "Import_default_0_from_module_1_90032", "Import default '{0}' from module \"{1}\""), + Add_default_import_0_to_existing_import_declaration_from_1: diag(90033, ts.DiagnosticCategory.Message, "Add_default_import_0_to_existing_import_declaration_from_1_90033", "Add default import '{0}' to existing import declaration from \"{1}\""), + Add_parameter_name: diag(90034, ts.DiagnosticCategory.Message, "Add_parameter_name_90034", "Add parameter name"), + Convert_function_to_an_ES2015_class: diag(95001, ts.DiagnosticCategory.Message, "Convert_function_to_an_ES2015_class_95001", "Convert function to an ES2015 class"), + Convert_function_0_to_class: diag(95002, ts.DiagnosticCategory.Message, "Convert_function_0_to_class_95002", "Convert function '{0}' to class"), + Extract_to_0_in_1: diag(95004, ts.DiagnosticCategory.Message, "Extract_to_0_in_1_95004", "Extract to {0} in {1}"), + Extract_function: diag(95005, ts.DiagnosticCategory.Message, "Extract_function_95005", "Extract function"), + Extract_constant: diag(95006, ts.DiagnosticCategory.Message, "Extract_constant_95006", "Extract constant"), + Extract_to_0_in_enclosing_scope: diag(95007, ts.DiagnosticCategory.Message, "Extract_to_0_in_enclosing_scope_95007", "Extract to {0} in enclosing scope"), + Extract_to_0_in_1_scope: diag(95008, ts.DiagnosticCategory.Message, "Extract_to_0_in_1_scope_95008", "Extract to {0} in {1} scope"), + Annotate_with_type_from_JSDoc: diag(95009, ts.DiagnosticCategory.Message, "Annotate_with_type_from_JSDoc_95009", "Annotate with type from JSDoc"), + Annotate_with_types_from_JSDoc: diag(95010, ts.DiagnosticCategory.Message, "Annotate_with_types_from_JSDoc_95010", "Annotate with types from JSDoc"), + Infer_type_of_0_from_usage: diag(95011, ts.DiagnosticCategory.Message, "Infer_type_of_0_from_usage_95011", "Infer type of '{0}' from usage"), + Infer_parameter_types_from_usage: diag(95012, ts.DiagnosticCategory.Message, "Infer_parameter_types_from_usage_95012", "Infer parameter types from usage"), + Convert_to_default_import: diag(95013, ts.DiagnosticCategory.Message, "Convert_to_default_import_95013", "Convert to default import"), + Install_0: diag(95014, ts.DiagnosticCategory.Message, "Install_0_95014", "Install '{0}'"), + Replace_import_with_0: diag(95015, ts.DiagnosticCategory.Message, "Replace_import_with_0_95015", "Replace import with '{0}'."), + Use_synthetic_default_member: diag(95016, ts.DiagnosticCategory.Message, "Use_synthetic_default_member_95016", "Use synthetic 'default' member."), + Convert_to_ES6_module: diag(95017, ts.DiagnosticCategory.Message, "Convert_to_ES6_module_95017", "Convert to ES6 module"), + Add_undefined_type_to_property_0: diag(95018, ts.DiagnosticCategory.Message, "Add_undefined_type_to_property_0_95018", "Add 'undefined' type to property '{0}'"), + Add_initializer_to_property_0: diag(95019, ts.DiagnosticCategory.Message, "Add_initializer_to_property_0_95019", "Add initializer to property '{0}'"), + Add_definite_assignment_assertion_to_property_0: diag(95020, ts.DiagnosticCategory.Message, "Add_definite_assignment_assertion_to_property_0_95020", "Add definite assignment assertion to property '{0}'"), + Add_all_missing_members: diag(95022, ts.DiagnosticCategory.Message, "Add_all_missing_members_95022", "Add all missing members"), + Infer_all_types_from_usage: diag(95023, ts.DiagnosticCategory.Message, "Infer_all_types_from_usage_95023", "Infer all types from usage"), + Delete_all_unused_declarations: diag(95024, ts.DiagnosticCategory.Message, "Delete_all_unused_declarations_95024", "Delete all unused declarations"), + Prefix_all_unused_declarations_with_where_possible: diag(95025, ts.DiagnosticCategory.Message, "Prefix_all_unused_declarations_with_where_possible_95025", "Prefix all unused declarations with '_' where possible"), + Fix_all_detected_spelling_errors: diag(95026, ts.DiagnosticCategory.Message, "Fix_all_detected_spelling_errors_95026", "Fix all detected spelling errors"), + Add_initializers_to_all_uninitialized_properties: diag(95027, ts.DiagnosticCategory.Message, "Add_initializers_to_all_uninitialized_properties_95027", "Add initializers to all uninitialized properties"), + Add_definite_assignment_assertions_to_all_uninitialized_properties: diag(95028, ts.DiagnosticCategory.Message, "Add_definite_assignment_assertions_to_all_uninitialized_properties_95028", "Add definite assignment assertions to all uninitialized properties"), + Add_undefined_type_to_all_uninitialized_properties: diag(95029, ts.DiagnosticCategory.Message, "Add_undefined_type_to_all_uninitialized_properties_95029", "Add undefined type to all uninitialized properties"), + Change_all_jsdoc_style_types_to_TypeScript: diag(95030, ts.DiagnosticCategory.Message, "Change_all_jsdoc_style_types_to_TypeScript_95030", "Change all jsdoc-style types to TypeScript"), + Change_all_jsdoc_style_types_to_TypeScript_and_add_undefined_to_nullable_types: diag(95031, ts.DiagnosticCategory.Message, "Change_all_jsdoc_style_types_to_TypeScript_and_add_undefined_to_nullable_types_95031", "Change all jsdoc-style types to TypeScript (and add '| undefined' to nullable types)"), + Implement_all_unimplemented_interfaces: diag(95032, ts.DiagnosticCategory.Message, "Implement_all_unimplemented_interfaces_95032", "Implement all unimplemented interfaces"), + Install_all_missing_types_packages: diag(95033, ts.DiagnosticCategory.Message, "Install_all_missing_types_packages_95033", "Install all missing types packages"), + Rewrite_all_as_indexed_access_types: diag(95034, ts.DiagnosticCategory.Message, "Rewrite_all_as_indexed_access_types_95034", "Rewrite all as indexed access types"), + Convert_all_to_default_imports: diag(95035, ts.DiagnosticCategory.Message, "Convert_all_to_default_imports_95035", "Convert all to default imports"), + Make_all_super_calls_the_first_statement_in_their_constructor: diag(95036, ts.DiagnosticCategory.Message, "Make_all_super_calls_the_first_statement_in_their_constructor_95036", "Make all 'super()' calls the first statement in their constructor"), + Add_qualifier_to_all_unresolved_variables_matching_a_member_name: diag(95037, ts.DiagnosticCategory.Message, "Add_qualifier_to_all_unresolved_variables_matching_a_member_name_95037", "Add qualifier to all unresolved variables matching a member name"), + Change_all_extended_interfaces_to_implements: diag(95038, ts.DiagnosticCategory.Message, "Change_all_extended_interfaces_to_implements_95038", "Change all extended interfaces to 'implements'"), + Add_all_missing_super_calls: diag(95039, ts.DiagnosticCategory.Message, "Add_all_missing_super_calls_95039", "Add all missing super calls"), + Implement_all_inherited_abstract_classes: diag(95040, ts.DiagnosticCategory.Message, "Implement_all_inherited_abstract_classes_95040", "Implement all inherited abstract classes"), + Add_all_missing_async_modifiers: diag(95041, ts.DiagnosticCategory.Message, "Add_all_missing_async_modifiers_95041", "Add all missing 'async' modifiers"), + Add_ts_ignore_to_all_error_messages: diag(95042, ts.DiagnosticCategory.Message, "Add_ts_ignore_to_all_error_messages_95042", "Add '@ts-ignore' to all error messages"), + Annotate_everything_with_types_from_JSDoc: diag(95043, ts.DiagnosticCategory.Message, "Annotate_everything_with_types_from_JSDoc_95043", "Annotate everything with types from JSDoc"), + Add_to_all_uncalled_decorators: diag(95044, ts.DiagnosticCategory.Message, "Add_to_all_uncalled_decorators_95044", "Add '()' to all uncalled decorators"), + Convert_all_constructor_functions_to_classes: diag(95045, ts.DiagnosticCategory.Message, "Convert_all_constructor_functions_to_classes_95045", "Convert all constructor functions to classes"), + Generate_get_and_set_accessors: diag(95046, ts.DiagnosticCategory.Message, "Generate_get_and_set_accessors_95046", "Generate 'get' and 'set' accessors"), + Convert_require_to_import: diag(95047, ts.DiagnosticCategory.Message, "Convert_require_to_import_95047", "Convert 'require' to 'import'"), + Convert_all_require_to_import: diag(95048, ts.DiagnosticCategory.Message, "Convert_all_require_to_import_95048", "Convert all 'require' to 'import'"), + Move_to_a_new_file: diag(95049, ts.DiagnosticCategory.Message, "Move_to_a_new_file_95049", "Move to a new file"), + Remove_unreachable_code: diag(95050, ts.DiagnosticCategory.Message, "Remove_unreachable_code_95050", "Remove unreachable code"), + Remove_all_unreachable_code: diag(95051, ts.DiagnosticCategory.Message, "Remove_all_unreachable_code_95051", "Remove all unreachable code"), + Add_missing_typeof: diag(95052, ts.DiagnosticCategory.Message, "Add_missing_typeof_95052", "Add missing 'typeof'"), + Remove_unused_label: diag(95053, ts.DiagnosticCategory.Message, "Remove_unused_label_95053", "Remove unused label"), + Remove_all_unused_labels: diag(95054, ts.DiagnosticCategory.Message, "Remove_all_unused_labels_95054", "Remove all unused labels"), + Convert_0_to_mapped_object_type: diag(95055, ts.DiagnosticCategory.Message, "Convert_0_to_mapped_object_type_95055", "Convert '{0}' to mapped object type"), + Convert_namespace_import_to_named_imports: diag(95056, ts.DiagnosticCategory.Message, "Convert_namespace_import_to_named_imports_95056", "Convert namespace import to named imports"), + Convert_named_imports_to_namespace_import: diag(95057, ts.DiagnosticCategory.Message, "Convert_named_imports_to_namespace_import_95057", "Convert named imports to namespace import"), + Add_or_remove_braces_in_an_arrow_function: diag(95058, ts.DiagnosticCategory.Message, "Add_or_remove_braces_in_an_arrow_function_95058", "Add or remove braces in an arrow function"), + Add_braces_to_arrow_function: diag(95059, ts.DiagnosticCategory.Message, "Add_braces_to_arrow_function_95059", "Add braces to arrow function"), + Remove_braces_from_arrow_function: diag(95060, ts.DiagnosticCategory.Message, "Remove_braces_from_arrow_function_95060", "Remove braces from arrow function"), + Convert_default_export_to_named_export: diag(95061, ts.DiagnosticCategory.Message, "Convert_default_export_to_named_export_95061", "Convert default export to named export"), + Convert_named_export_to_default_export: diag(95062, ts.DiagnosticCategory.Message, "Convert_named_export_to_default_export_95062", "Convert named export to default export"), + Add_missing_enum_member_0: diag(95063, ts.DiagnosticCategory.Message, "Add_missing_enum_member_0_95063", "Add missing enum member '{0}'"), + Add_all_missing_imports: diag(95064, ts.DiagnosticCategory.Message, "Add_all_missing_imports_95064", "Add all missing imports"), + Convert_to_async_function: diag(95065, ts.DiagnosticCategory.Message, "Convert_to_async_function_95065", "Convert to async function"), + Convert_all_to_async_functions: diag(95066, ts.DiagnosticCategory.Message, "Convert_all_to_async_functions_95066", "Convert all to async functions"), + Generate_types_for_0: diag(95067, ts.DiagnosticCategory.Message, "Generate_types_for_0_95067", "Generate types for '{0}'"), + Generate_types_for_all_packages_without_types: diag(95068, ts.DiagnosticCategory.Message, "Generate_types_for_all_packages_without_types_95068", "Generate types for all packages without types"), + Add_unknown_conversion_for_non_overlapping_types: diag(95069, ts.DiagnosticCategory.Message, "Add_unknown_conversion_for_non_overlapping_types_95069", "Add 'unknown' conversion for non-overlapping types"), + Add_unknown_to_all_conversions_of_non_overlapping_types: diag(95070, ts.DiagnosticCategory.Message, "Add_unknown_to_all_conversions_of_non_overlapping_types_95070", "Add 'unknown' to all conversions of non-overlapping types"), + Add_missing_new_operator_to_call: diag(95071, ts.DiagnosticCategory.Message, "Add_missing_new_operator_to_call_95071", "Add missing 'new' operator to call"), + Add_missing_new_operator_to_all_calls: diag(95072, ts.DiagnosticCategory.Message, "Add_missing_new_operator_to_all_calls_95072", "Add missing 'new' operator to all calls"), + Add_names_to_all_parameters_without_names: diag(95073, ts.DiagnosticCategory.Message, "Add_names_to_all_parameters_without_names_95073", "Add names to all parameters without names"), + }; +})(ts || (ts = {})); +var ts; +(function (ts) { + var _a; + /* @internal */ + function tokenIsIdentifierOrKeyword(token) { + return token >= 72 /* Identifier */; + } + ts.tokenIsIdentifierOrKeyword = tokenIsIdentifierOrKeyword; + /* @internal */ + function tokenIsIdentifierOrKeywordOrGreaterThan(token) { + return token === 30 /* GreaterThanToken */ || tokenIsIdentifierOrKeyword(token); + } + ts.tokenIsIdentifierOrKeywordOrGreaterThan = tokenIsIdentifierOrKeywordOrGreaterThan; + var textToKeywordObj = (_a = { + abstract: 118 /* AbstractKeyword */, + any: 120 /* AnyKeyword */, + as: 119 /* AsKeyword */, + bigint: 146 /* BigIntKeyword */, + boolean: 123 /* BooleanKeyword */, + break: 73 /* BreakKeyword */, + case: 74 /* CaseKeyword */, + catch: 75 /* CatchKeyword */, + class: 76 /* ClassKeyword */, + continue: 78 /* ContinueKeyword */, + const: 77 /* ConstKeyword */ + }, + _a["" + "constructor"] = 124 /* ConstructorKeyword */, + _a.debugger = 79 /* DebuggerKeyword */, + _a.declare = 125 /* DeclareKeyword */, + _a.default = 80 /* DefaultKeyword */, + _a.delete = 81 /* DeleteKeyword */, + _a.do = 82 /* DoKeyword */, + _a.else = 83 /* ElseKeyword */, + _a.enum = 84 /* EnumKeyword */, + _a.export = 85 /* ExportKeyword */, + _a.extends = 86 /* ExtendsKeyword */, + _a.false = 87 /* FalseKeyword */, + _a.finally = 88 /* FinallyKeyword */, + _a.for = 89 /* ForKeyword */, + _a.from = 144 /* FromKeyword */, + _a.function = 90 /* FunctionKeyword */, + _a.get = 126 /* GetKeyword */, + _a.if = 91 /* IfKeyword */, + _a.implements = 109 /* ImplementsKeyword */, + _a.import = 92 /* ImportKeyword */, + _a.in = 93 /* InKeyword */, + _a.infer = 127 /* InferKeyword */, + _a.instanceof = 94 /* InstanceOfKeyword */, + _a.interface = 110 /* InterfaceKeyword */, + _a.is = 128 /* IsKeyword */, + _a.keyof = 129 /* KeyOfKeyword */, + _a.let = 111 /* LetKeyword */, + _a.module = 130 /* ModuleKeyword */, + _a.namespace = 131 /* NamespaceKeyword */, + _a.never = 132 /* NeverKeyword */, + _a.new = 95 /* NewKeyword */, + _a.null = 96 /* NullKeyword */, + _a.number = 135 /* NumberKeyword */, + _a.object = 136 /* ObjectKeyword */, + _a.package = 112 /* PackageKeyword */, + _a.private = 113 /* PrivateKeyword */, + _a.protected = 114 /* ProtectedKeyword */, + _a.public = 115 /* PublicKeyword */, + _a.readonly = 133 /* ReadonlyKeyword */, + _a.require = 134 /* RequireKeyword */, + _a.global = 145 /* GlobalKeyword */, + _a.return = 97 /* ReturnKeyword */, + _a.set = 137 /* SetKeyword */, + _a.static = 116 /* StaticKeyword */, + _a.string = 138 /* StringKeyword */, + _a.super = 98 /* SuperKeyword */, + _a.switch = 99 /* SwitchKeyword */, + _a.symbol = 139 /* SymbolKeyword */, + _a.this = 100 /* ThisKeyword */, + _a.throw = 101 /* ThrowKeyword */, + _a.true = 102 /* TrueKeyword */, + _a.try = 103 /* TryKeyword */, + _a.type = 140 /* TypeKeyword */, + _a.typeof = 104 /* TypeOfKeyword */, + _a.undefined = 141 /* UndefinedKeyword */, + _a.unique = 142 /* UniqueKeyword */, + _a.unknown = 143 /* UnknownKeyword */, + _a.var = 105 /* VarKeyword */, + _a.void = 106 /* VoidKeyword */, + _a.while = 107 /* WhileKeyword */, + _a.with = 108 /* WithKeyword */, + _a.yield = 117 /* YieldKeyword */, + _a.async = 121 /* AsyncKeyword */, + _a.await = 122 /* AwaitKeyword */, + _a.of = 147 /* OfKeyword */, + _a); + var textToKeyword = ts.createMapFromTemplate(textToKeywordObj); + var textToToken = ts.createMapFromTemplate(__assign({}, textToKeywordObj, { "{": 18 /* OpenBraceToken */, "}": 19 /* CloseBraceToken */, "(": 20 /* OpenParenToken */, ")": 21 /* CloseParenToken */, "[": 22 /* OpenBracketToken */, "]": 23 /* CloseBracketToken */, ".": 24 /* DotToken */, "...": 25 /* DotDotDotToken */, ";": 26 /* SemicolonToken */, ",": 27 /* CommaToken */, "<": 28 /* LessThanToken */, ">": 30 /* GreaterThanToken */, "<=": 31 /* LessThanEqualsToken */, ">=": 32 /* GreaterThanEqualsToken */, "==": 33 /* EqualsEqualsToken */, "!=": 34 /* ExclamationEqualsToken */, "===": 35 /* EqualsEqualsEqualsToken */, "!==": 36 /* ExclamationEqualsEqualsToken */, "=>": 37 /* EqualsGreaterThanToken */, "+": 38 /* PlusToken */, "-": 39 /* MinusToken */, "**": 41 /* AsteriskAsteriskToken */, "*": 40 /* AsteriskToken */, "/": 42 /* SlashToken */, "%": 43 /* PercentToken */, "++": 44 /* PlusPlusToken */, "--": 45 /* MinusMinusToken */, "<<": 46 /* LessThanLessThanToken */, ">": 47 /* GreaterThanGreaterThanToken */, ">>>": 48 /* GreaterThanGreaterThanGreaterThanToken */, "&": 49 /* AmpersandToken */, "|": 50 /* BarToken */, "^": 51 /* CaretToken */, "!": 52 /* ExclamationToken */, "~": 53 /* TildeToken */, "&&": 54 /* AmpersandAmpersandToken */, "||": 55 /* BarBarToken */, "?": 56 /* QuestionToken */, ":": 57 /* ColonToken */, "=": 59 /* EqualsToken */, "+=": 60 /* PlusEqualsToken */, "-=": 61 /* MinusEqualsToken */, "*=": 62 /* AsteriskEqualsToken */, "**=": 63 /* AsteriskAsteriskEqualsToken */, "/=": 64 /* SlashEqualsToken */, "%=": 65 /* PercentEqualsToken */, "<<=": 66 /* LessThanLessThanEqualsToken */, ">>=": 67 /* GreaterThanGreaterThanEqualsToken */, ">>>=": 68 /* GreaterThanGreaterThanGreaterThanEqualsToken */, "&=": 69 /* AmpersandEqualsToken */, "|=": 70 /* BarEqualsToken */, "^=": 71 /* CaretEqualsToken */, "@": 58 /* AtToken */ })); + /* + As per ECMAScript Language Specification 3th Edition, Section 7.6: Identifiers + IdentifierStart :: + Can contain Unicode 3.0.0 categories: + Uppercase letter (Lu), + Lowercase letter (Ll), + Titlecase letter (Lt), + Modifier letter (Lm), + Other letter (Lo), or + Letter number (Nl). + IdentifierPart :: = + Can contain IdentifierStart + Unicode 3.0.0 categories: + Non-spacing mark (Mn), + Combining spacing mark (Mc), + Decimal number (Nd), or + Connector punctuation (Pc). + + Codepoint ranges for ES3 Identifiers are extracted from the Unicode 3.0.0 specification at: + http://www.unicode.org/Public/3.0-Update/UnicodeData-3.0.0.txt + */ + var unicodeES3IdentifierStart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 543, 546, 563, 592, 685, 688, 696, 699, 705, 720, 721, 736, 740, 750, 750, 890, 890, 902, 902, 904, 906, 908, 908, 910, 929, 931, 974, 976, 983, 986, 1011, 1024, 1153, 1164, 1220, 1223, 1224, 1227, 1228, 1232, 1269, 1272, 1273, 1329, 1366, 1369, 1369, 1377, 1415, 1488, 1514, 1520, 1522, 1569, 1594, 1600, 1610, 1649, 1747, 1749, 1749, 1765, 1766, 1786, 1788, 1808, 1808, 1810, 1836, 1920, 1957, 2309, 2361, 2365, 2365, 2384, 2384, 2392, 2401, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2524, 2525, 2527, 2529, 2544, 2545, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2649, 2652, 2654, 2654, 2674, 2676, 2693, 2699, 2701, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2749, 2749, 2768, 2768, 2784, 2784, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2870, 2873, 2877, 2877, 2908, 2909, 2911, 2913, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 2997, 2999, 3001, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3168, 3169, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3294, 3294, 3296, 3297, 3333, 3340, 3342, 3344, 3346, 3368, 3370, 3385, 3424, 3425, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3585, 3632, 3634, 3635, 3648, 3654, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3760, 3762, 3763, 3773, 3773, 3776, 3780, 3782, 3782, 3804, 3805, 3840, 3840, 3904, 3911, 3913, 3946, 3976, 3979, 4096, 4129, 4131, 4135, 4137, 4138, 4176, 4181, 4256, 4293, 4304, 4342, 4352, 4441, 4447, 4514, 4520, 4601, 4608, 4614, 4616, 4678, 4680, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4742, 4744, 4744, 4746, 4749, 4752, 4782, 4784, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4814, 4816, 4822, 4824, 4846, 4848, 4878, 4880, 4880, 4882, 4885, 4888, 4894, 4896, 4934, 4936, 4954, 5024, 5108, 5121, 5740, 5743, 5750, 5761, 5786, 5792, 5866, 6016, 6067, 6176, 6263, 6272, 6312, 7680, 7835, 7840, 7929, 7936, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8319, 8319, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8497, 8499, 8505, 8544, 8579, 12293, 12295, 12321, 12329, 12337, 12341, 12344, 12346, 12353, 12436, 12445, 12446, 12449, 12538, 12540, 12542, 12549, 12588, 12593, 12686, 12704, 12727, 13312, 19893, 19968, 40869, 40960, 42124, 44032, 55203, 63744, 64045, 64256, 64262, 64275, 64279, 64285, 64285, 64287, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65136, 65138, 65140, 65140, 65142, 65276, 65313, 65338, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500,]; + var unicodeES3IdentifierPart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 543, 546, 563, 592, 685, 688, 696, 699, 705, 720, 721, 736, 740, 750, 750, 768, 846, 864, 866, 890, 890, 902, 902, 904, 906, 908, 908, 910, 929, 931, 974, 976, 983, 986, 1011, 1024, 1153, 1155, 1158, 1164, 1220, 1223, 1224, 1227, 1228, 1232, 1269, 1272, 1273, 1329, 1366, 1369, 1369, 1377, 1415, 1425, 1441, 1443, 1465, 1467, 1469, 1471, 1471, 1473, 1474, 1476, 1476, 1488, 1514, 1520, 1522, 1569, 1594, 1600, 1621, 1632, 1641, 1648, 1747, 1749, 1756, 1759, 1768, 1770, 1773, 1776, 1788, 1808, 1836, 1840, 1866, 1920, 1968, 2305, 2307, 2309, 2361, 2364, 2381, 2384, 2388, 2392, 2403, 2406, 2415, 2433, 2435, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2492, 2492, 2494, 2500, 2503, 2504, 2507, 2509, 2519, 2519, 2524, 2525, 2527, 2531, 2534, 2545, 2562, 2562, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2620, 2620, 2622, 2626, 2631, 2632, 2635, 2637, 2649, 2652, 2654, 2654, 2662, 2676, 2689, 2691, 2693, 2699, 2701, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2748, 2757, 2759, 2761, 2763, 2765, 2768, 2768, 2784, 2784, 2790, 2799, 2817, 2819, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2870, 2873, 2876, 2883, 2887, 2888, 2891, 2893, 2902, 2903, 2908, 2909, 2911, 2913, 2918, 2927, 2946, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 2997, 2999, 3001, 3006, 3010, 3014, 3016, 3018, 3021, 3031, 3031, 3047, 3055, 3073, 3075, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3134, 3140, 3142, 3144, 3146, 3149, 3157, 3158, 3168, 3169, 3174, 3183, 3202, 3203, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3262, 3268, 3270, 3272, 3274, 3277, 3285, 3286, 3294, 3294, 3296, 3297, 3302, 3311, 3330, 3331, 3333, 3340, 3342, 3344, 3346, 3368, 3370, 3385, 3390, 3395, 3398, 3400, 3402, 3405, 3415, 3415, 3424, 3425, 3430, 3439, 3458, 3459, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3530, 3530, 3535, 3540, 3542, 3542, 3544, 3551, 3570, 3571, 3585, 3642, 3648, 3662, 3664, 3673, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3769, 3771, 3773, 3776, 3780, 3782, 3782, 3784, 3789, 3792, 3801, 3804, 3805, 3840, 3840, 3864, 3865, 3872, 3881, 3893, 3893, 3895, 3895, 3897, 3897, 3902, 3911, 3913, 3946, 3953, 3972, 3974, 3979, 3984, 3991, 3993, 4028, 4038, 4038, 4096, 4129, 4131, 4135, 4137, 4138, 4140, 4146, 4150, 4153, 4160, 4169, 4176, 4185, 4256, 4293, 4304, 4342, 4352, 4441, 4447, 4514, 4520, 4601, 4608, 4614, 4616, 4678, 4680, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4742, 4744, 4744, 4746, 4749, 4752, 4782, 4784, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4814, 4816, 4822, 4824, 4846, 4848, 4878, 4880, 4880, 4882, 4885, 4888, 4894, 4896, 4934, 4936, 4954, 4969, 4977, 5024, 5108, 5121, 5740, 5743, 5750, 5761, 5786, 5792, 5866, 6016, 6099, 6112, 6121, 6160, 6169, 6176, 6263, 6272, 6313, 7680, 7835, 7840, 7929, 7936, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8255, 8256, 8319, 8319, 8400, 8412, 8417, 8417, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8497, 8499, 8505, 8544, 8579, 12293, 12295, 12321, 12335, 12337, 12341, 12344, 12346, 12353, 12436, 12441, 12442, 12445, 12446, 12449, 12542, 12549, 12588, 12593, 12686, 12704, 12727, 13312, 19893, 19968, 40869, 40960, 42124, 44032, 55203, 63744, 64045, 64256, 64262, 64275, 64279, 64285, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65056, 65059, 65075, 65076, 65101, 65103, 65136, 65138, 65140, 65140, 65142, 65276, 65296, 65305, 65313, 65338, 65343, 65343, 65345, 65370, 65381, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500,]; + /* + As per ECMAScript Language Specification 5th Edition, Section 7.6: ISyntaxToken Names and Identifiers + IdentifierStart :: + Can contain Unicode 6.2 categories: + Uppercase letter (Lu), + Lowercase letter (Ll), + Titlecase letter (Lt), + Modifier letter (Lm), + Other letter (Lo), or + Letter number (Nl). + IdentifierPart :: + Can contain IdentifierStart + Unicode 6.2 categories: + Non-spacing mark (Mn), + Combining spacing mark (Mc), + Decimal number (Nd), + Connector punctuation (Pc), + , or + . + + Codepoint ranges for ES5 Identifiers are extracted from the Unicode 6.2 specification at: + http://www.unicode.org/Public/6.2.0/ucd/UnicodeData.txt + */ + var unicodeES5IdentifierStart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 705, 710, 721, 736, 740, 748, 748, 750, 750, 880, 884, 886, 887, 890, 893, 902, 902, 904, 906, 908, 908, 910, 929, 931, 1013, 1015, 1153, 1162, 1319, 1329, 1366, 1369, 1369, 1377, 1415, 1488, 1514, 1520, 1522, 1568, 1610, 1646, 1647, 1649, 1747, 1749, 1749, 1765, 1766, 1774, 1775, 1786, 1788, 1791, 1791, 1808, 1808, 1810, 1839, 1869, 1957, 1969, 1969, 1994, 2026, 2036, 2037, 2042, 2042, 2048, 2069, 2074, 2074, 2084, 2084, 2088, 2088, 2112, 2136, 2208, 2208, 2210, 2220, 2308, 2361, 2365, 2365, 2384, 2384, 2392, 2401, 2417, 2423, 2425, 2431, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2493, 2493, 2510, 2510, 2524, 2525, 2527, 2529, 2544, 2545, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2649, 2652, 2654, 2654, 2674, 2676, 2693, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2749, 2749, 2768, 2768, 2784, 2785, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2869, 2873, 2877, 2877, 2908, 2909, 2911, 2913, 2929, 2929, 2947, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 3001, 3024, 3024, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3133, 3133, 3160, 3161, 3168, 3169, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3261, 3261, 3294, 3294, 3296, 3297, 3313, 3314, 3333, 3340, 3342, 3344, 3346, 3386, 3389, 3389, 3406, 3406, 3424, 3425, 3450, 3455, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3585, 3632, 3634, 3635, 3648, 3654, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3760, 3762, 3763, 3773, 3773, 3776, 3780, 3782, 3782, 3804, 3807, 3840, 3840, 3904, 3911, 3913, 3948, 3976, 3980, 4096, 4138, 4159, 4159, 4176, 4181, 4186, 4189, 4193, 4193, 4197, 4198, 4206, 4208, 4213, 4225, 4238, 4238, 4256, 4293, 4295, 4295, 4301, 4301, 4304, 4346, 4348, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4744, 4746, 4749, 4752, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4822, 4824, 4880, 4882, 4885, 4888, 4954, 4992, 5007, 5024, 5108, 5121, 5740, 5743, 5759, 5761, 5786, 5792, 5866, 5870, 5872, 5888, 5900, 5902, 5905, 5920, 5937, 5952, 5969, 5984, 5996, 5998, 6000, 6016, 6067, 6103, 6103, 6108, 6108, 6176, 6263, 6272, 6312, 6314, 6314, 6320, 6389, 6400, 6428, 6480, 6509, 6512, 6516, 6528, 6571, 6593, 6599, 6656, 6678, 6688, 6740, 6823, 6823, 6917, 6963, 6981, 6987, 7043, 7072, 7086, 7087, 7098, 7141, 7168, 7203, 7245, 7247, 7258, 7293, 7401, 7404, 7406, 7409, 7413, 7414, 7424, 7615, 7680, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8305, 8305, 8319, 8319, 8336, 8348, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8505, 8508, 8511, 8517, 8521, 8526, 8526, 8544, 8584, 11264, 11310, 11312, 11358, 11360, 11492, 11499, 11502, 11506, 11507, 11520, 11557, 11559, 11559, 11565, 11565, 11568, 11623, 11631, 11631, 11648, 11670, 11680, 11686, 11688, 11694, 11696, 11702, 11704, 11710, 11712, 11718, 11720, 11726, 11728, 11734, 11736, 11742, 11823, 11823, 12293, 12295, 12321, 12329, 12337, 12341, 12344, 12348, 12353, 12438, 12445, 12447, 12449, 12538, 12540, 12543, 12549, 12589, 12593, 12686, 12704, 12730, 12784, 12799, 13312, 19893, 19968, 40908, 40960, 42124, 42192, 42237, 42240, 42508, 42512, 42527, 42538, 42539, 42560, 42606, 42623, 42647, 42656, 42735, 42775, 42783, 42786, 42888, 42891, 42894, 42896, 42899, 42912, 42922, 43000, 43009, 43011, 43013, 43015, 43018, 43020, 43042, 43072, 43123, 43138, 43187, 43250, 43255, 43259, 43259, 43274, 43301, 43312, 43334, 43360, 43388, 43396, 43442, 43471, 43471, 43520, 43560, 43584, 43586, 43588, 43595, 43616, 43638, 43642, 43642, 43648, 43695, 43697, 43697, 43701, 43702, 43705, 43709, 43712, 43712, 43714, 43714, 43739, 43741, 43744, 43754, 43762, 43764, 43777, 43782, 43785, 43790, 43793, 43798, 43808, 43814, 43816, 43822, 43968, 44002, 44032, 55203, 55216, 55238, 55243, 55291, 63744, 64109, 64112, 64217, 64256, 64262, 64275, 64279, 64285, 64285, 64287, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65136, 65140, 65142, 65276, 65313, 65338, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500,]; + var unicodeES5IdentifierPart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 705, 710, 721, 736, 740, 748, 748, 750, 750, 768, 884, 886, 887, 890, 893, 902, 902, 904, 906, 908, 908, 910, 929, 931, 1013, 1015, 1153, 1155, 1159, 1162, 1319, 1329, 1366, 1369, 1369, 1377, 1415, 1425, 1469, 1471, 1471, 1473, 1474, 1476, 1477, 1479, 1479, 1488, 1514, 1520, 1522, 1552, 1562, 1568, 1641, 1646, 1747, 1749, 1756, 1759, 1768, 1770, 1788, 1791, 1791, 1808, 1866, 1869, 1969, 1984, 2037, 2042, 2042, 2048, 2093, 2112, 2139, 2208, 2208, 2210, 2220, 2276, 2302, 2304, 2403, 2406, 2415, 2417, 2423, 2425, 2431, 2433, 2435, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2492, 2500, 2503, 2504, 2507, 2510, 2519, 2519, 2524, 2525, 2527, 2531, 2534, 2545, 2561, 2563, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2620, 2620, 2622, 2626, 2631, 2632, 2635, 2637, 2641, 2641, 2649, 2652, 2654, 2654, 2662, 2677, 2689, 2691, 2693, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2748, 2757, 2759, 2761, 2763, 2765, 2768, 2768, 2784, 2787, 2790, 2799, 2817, 2819, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2869, 2873, 2876, 2884, 2887, 2888, 2891, 2893, 2902, 2903, 2908, 2909, 2911, 2915, 2918, 2927, 2929, 2929, 2946, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 3001, 3006, 3010, 3014, 3016, 3018, 3021, 3024, 3024, 3031, 3031, 3046, 3055, 3073, 3075, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3133, 3140, 3142, 3144, 3146, 3149, 3157, 3158, 3160, 3161, 3168, 3171, 3174, 3183, 3202, 3203, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3260, 3268, 3270, 3272, 3274, 3277, 3285, 3286, 3294, 3294, 3296, 3299, 3302, 3311, 3313, 3314, 3330, 3331, 3333, 3340, 3342, 3344, 3346, 3386, 3389, 3396, 3398, 3400, 3402, 3406, 3415, 3415, 3424, 3427, 3430, 3439, 3450, 3455, 3458, 3459, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3530, 3530, 3535, 3540, 3542, 3542, 3544, 3551, 3570, 3571, 3585, 3642, 3648, 3662, 3664, 3673, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3769, 3771, 3773, 3776, 3780, 3782, 3782, 3784, 3789, 3792, 3801, 3804, 3807, 3840, 3840, 3864, 3865, 3872, 3881, 3893, 3893, 3895, 3895, 3897, 3897, 3902, 3911, 3913, 3948, 3953, 3972, 3974, 3991, 3993, 4028, 4038, 4038, 4096, 4169, 4176, 4253, 4256, 4293, 4295, 4295, 4301, 4301, 4304, 4346, 4348, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4744, 4746, 4749, 4752, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4822, 4824, 4880, 4882, 4885, 4888, 4954, 4957, 4959, 4992, 5007, 5024, 5108, 5121, 5740, 5743, 5759, 5761, 5786, 5792, 5866, 5870, 5872, 5888, 5900, 5902, 5908, 5920, 5940, 5952, 5971, 5984, 5996, 5998, 6000, 6002, 6003, 6016, 6099, 6103, 6103, 6108, 6109, 6112, 6121, 6155, 6157, 6160, 6169, 6176, 6263, 6272, 6314, 6320, 6389, 6400, 6428, 6432, 6443, 6448, 6459, 6470, 6509, 6512, 6516, 6528, 6571, 6576, 6601, 6608, 6617, 6656, 6683, 6688, 6750, 6752, 6780, 6783, 6793, 6800, 6809, 6823, 6823, 6912, 6987, 6992, 7001, 7019, 7027, 7040, 7155, 7168, 7223, 7232, 7241, 7245, 7293, 7376, 7378, 7380, 7414, 7424, 7654, 7676, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8204, 8205, 8255, 8256, 8276, 8276, 8305, 8305, 8319, 8319, 8336, 8348, 8400, 8412, 8417, 8417, 8421, 8432, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8505, 8508, 8511, 8517, 8521, 8526, 8526, 8544, 8584, 11264, 11310, 11312, 11358, 11360, 11492, 11499, 11507, 11520, 11557, 11559, 11559, 11565, 11565, 11568, 11623, 11631, 11631, 11647, 11670, 11680, 11686, 11688, 11694, 11696, 11702, 11704, 11710, 11712, 11718, 11720, 11726, 11728, 11734, 11736, 11742, 11744, 11775, 11823, 11823, 12293, 12295, 12321, 12335, 12337, 12341, 12344, 12348, 12353, 12438, 12441, 12442, 12445, 12447, 12449, 12538, 12540, 12543, 12549, 12589, 12593, 12686, 12704, 12730, 12784, 12799, 13312, 19893, 19968, 40908, 40960, 42124, 42192, 42237, 42240, 42508, 42512, 42539, 42560, 42607, 42612, 42621, 42623, 42647, 42655, 42737, 42775, 42783, 42786, 42888, 42891, 42894, 42896, 42899, 42912, 42922, 43000, 43047, 43072, 43123, 43136, 43204, 43216, 43225, 43232, 43255, 43259, 43259, 43264, 43309, 43312, 43347, 43360, 43388, 43392, 43456, 43471, 43481, 43520, 43574, 43584, 43597, 43600, 43609, 43616, 43638, 43642, 43643, 43648, 43714, 43739, 43741, 43744, 43759, 43762, 43766, 43777, 43782, 43785, 43790, 43793, 43798, 43808, 43814, 43816, 43822, 43968, 44010, 44012, 44013, 44016, 44025, 44032, 55203, 55216, 55238, 55243, 55291, 63744, 64109, 64112, 64217, 64256, 64262, 64275, 64279, 64285, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65024, 65039, 65056, 65062, 65075, 65076, 65101, 65103, 65136, 65140, 65142, 65276, 65296, 65305, 65313, 65338, 65343, 65343, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500,]; + function lookupInUnicodeMap(code, map) { + // Bail out quickly if it couldn't possibly be in the map. + if (code < map[0]) { + return false; + } + // Perform binary search in one of the Unicode range maps + var lo = 0; + var hi = map.length; + var mid; + while (lo + 1 < hi) { + mid = lo + (hi - lo) / 2; + // mid has to be even to catch a range's beginning + mid -= mid % 2; + if (map[mid] <= code && code <= map[mid + 1]) { + return true; + } + if (code < map[mid]) { + hi = mid; + } + else { + lo = mid + 2; + } + } + return false; + } + /* @internal */ function isUnicodeIdentifierStart(code, languageVersion) { + return languageVersion >= 1 /* ES5 */ ? + lookupInUnicodeMap(code, unicodeES5IdentifierStart) : + lookupInUnicodeMap(code, unicodeES3IdentifierStart); + } + ts.isUnicodeIdentifierStart = isUnicodeIdentifierStart; + function isUnicodeIdentifierPart(code, languageVersion) { + return languageVersion >= 1 /* ES5 */ ? + lookupInUnicodeMap(code, unicodeES5IdentifierPart) : + lookupInUnicodeMap(code, unicodeES3IdentifierPart); + } + function makeReverseMap(source) { + var result = []; + source.forEach(function (value, name) { + result[value] = name; + }); + return result; + } + var tokenStrings = makeReverseMap(textToToken); + function tokenToString(t) { + return tokenStrings[t]; + } + ts.tokenToString = tokenToString; + /* @internal */ + function stringToToken(s) { + return textToToken.get(s); + } + ts.stringToToken = stringToToken; + /* @internal */ + function computeLineStarts(text) { + var result = new Array(); + var pos = 0; + var lineStart = 0; + while (pos < text.length) { + var ch = text.charCodeAt(pos); + pos++; + switch (ch) { + case 13 /* carriageReturn */: + if (text.charCodeAt(pos) === 10 /* lineFeed */) { + pos++; + } + // falls through + case 10 /* lineFeed */: + result.push(lineStart); + lineStart = pos; + break; + default: + if (ch > 127 /* maxAsciiCharacter */ && isLineBreak(ch)) { + result.push(lineStart); + lineStart = pos; + } + break; + } + } + result.push(lineStart); + return result; + } + ts.computeLineStarts = computeLineStarts; + function getPositionOfLineAndCharacter(sourceFile, line, character) { + return computePositionOfLineAndCharacter(getLineStarts(sourceFile), line, character, sourceFile.text); + } + ts.getPositionOfLineAndCharacter = getPositionOfLineAndCharacter; + /* @internal */ + function getPositionOfLineAndCharacterWithEdits(sourceFile, line, character) { + return computePositionOfLineAndCharacter(getLineStarts(sourceFile), line, character, sourceFile.text, /*allowEdits*/ true); + } + ts.getPositionOfLineAndCharacterWithEdits = getPositionOfLineAndCharacterWithEdits; + /* @internal */ + function computePositionOfLineAndCharacter(lineStarts, line, character, debugText, allowEdits) { + if (line < 0 || line >= lineStarts.length) { + if (allowEdits) { + // Clamp line to nearest allowable value + line = line < 0 ? 0 : line >= lineStarts.length ? lineStarts.length - 1 : line; + } + else { + ts.Debug.fail("Bad line number. Line: " + line + ", lineStarts.length: " + lineStarts.length + " , line map is correct? " + (debugText !== undefined ? ts.arraysEqual(lineStarts, computeLineStarts(debugText)) : "unknown")); + } + } + var res = lineStarts[line] + character; + if (allowEdits) { + // Clamp to nearest allowable values to allow the underlying to be edited without crashing (accuracy is lost, instead) + // TODO: Somehow track edits between file as it was during the creation of sourcemap we have and the current file and + // apply them to the computed position to improve accuracy + return res > lineStarts[line + 1] ? lineStarts[line + 1] : typeof debugText === "string" && res > debugText.length ? debugText.length : res; + } + if (line < lineStarts.length - 1) { + ts.Debug.assert(res < lineStarts[line + 1]); + } + else if (debugText !== undefined) { + ts.Debug.assert(res <= debugText.length); // Allow single character overflow for trailing newline + } + return res; + } + ts.computePositionOfLineAndCharacter = computePositionOfLineAndCharacter; + /* @internal */ + function getLineStarts(sourceFile) { + return sourceFile.lineMap || (sourceFile.lineMap = computeLineStarts(sourceFile.text)); + } + ts.getLineStarts = getLineStarts; + /* @internal */ + /** + * We assume the first line starts at position 0 and 'position' is non-negative. + */ + function computeLineAndCharacterOfPosition(lineStarts, position) { + var lineNumber = ts.binarySearch(lineStarts, position, ts.identity, ts.compareValues); + if (lineNumber < 0) { + // If the actual position was not found, + // the binary search returns the 2's-complement of the next line start + // e.g. if the line starts at [5, 10, 23, 80] and the position requested was 20 + // then the search will return -2. + // + // We want the index of the previous line start, so we subtract 1. + // Review 2's-complement if this is confusing. + lineNumber = ~lineNumber - 1; + ts.Debug.assert(lineNumber !== -1, "position cannot precede the beginning of the file"); + } + return { + line: lineNumber, + character: position - lineStarts[lineNumber] + }; + } + ts.computeLineAndCharacterOfPosition = computeLineAndCharacterOfPosition; + function getLineAndCharacterOfPosition(sourceFile, position) { + return computeLineAndCharacterOfPosition(getLineStarts(sourceFile), position); + } + ts.getLineAndCharacterOfPosition = getLineAndCharacterOfPosition; + function isWhiteSpaceLike(ch) { + return isWhiteSpaceSingleLine(ch) || isLineBreak(ch); + } + ts.isWhiteSpaceLike = isWhiteSpaceLike; + /** Does not include line breaks. For that, see isWhiteSpaceLike. */ + function isWhiteSpaceSingleLine(ch) { + // Note: nextLine is in the Zs space, and should be considered to be a whitespace. + // It is explicitly not a line-break as it isn't in the exact set specified by EcmaScript. + return ch === 32 /* space */ || + ch === 9 /* tab */ || + ch === 11 /* verticalTab */ || + ch === 12 /* formFeed */ || + ch === 160 /* nonBreakingSpace */ || + ch === 133 /* nextLine */ || + ch === 5760 /* ogham */ || + ch >= 8192 /* enQuad */ && ch <= 8203 /* zeroWidthSpace */ || + ch === 8239 /* narrowNoBreakSpace */ || + ch === 8287 /* mathematicalSpace */ || + ch === 12288 /* ideographicSpace */ || + ch === 65279 /* byteOrderMark */; + } + ts.isWhiteSpaceSingleLine = isWhiteSpaceSingleLine; + function isLineBreak(ch) { + // ES5 7.3: + // The ECMAScript line terminator characters are listed in Table 3. + // Table 3: Line Terminator Characters + // Code Unit Value Name Formal Name + // \u000A Line Feed + // \u000D Carriage Return + // \u2028 Line separator + // \u2029 Paragraph separator + // Only the characters in Table 3 are treated as line terminators. Other new line or line + // breaking characters are treated as white space but not as line terminators. + return ch === 10 /* lineFeed */ || + ch === 13 /* carriageReturn */ || + ch === 8232 /* lineSeparator */ || + ch === 8233 /* paragraphSeparator */; + } + ts.isLineBreak = isLineBreak; + function isDigit(ch) { + return ch >= 48 /* _0 */ && ch <= 57 /* _9 */; + } + /* @internal */ + function isOctalDigit(ch) { + return ch >= 48 /* _0 */ && ch <= 55 /* _7 */; + } + ts.isOctalDigit = isOctalDigit; + function couldStartTrivia(text, pos) { + // Keep in sync with skipTrivia + var ch = text.charCodeAt(pos); + switch (ch) { + case 13 /* carriageReturn */: + case 10 /* lineFeed */: + case 9 /* tab */: + case 11 /* verticalTab */: + case 12 /* formFeed */: + case 32 /* space */: + case 47 /* slash */: + // starts of normal trivia + case 60 /* lessThan */: + case 124 /* bar */: + case 61 /* equals */: + case 62 /* greaterThan */: + // Starts of conflict marker trivia + return true; + case 35 /* hash */: + // Only if its the beginning can we have #! trivia + return pos === 0; + default: + return ch > 127 /* maxAsciiCharacter */; + } + } + ts.couldStartTrivia = couldStartTrivia; + /* @internal */ + function skipTrivia(text, pos, stopAfterLineBreak, stopAtComments) { + if (stopAtComments === void 0) { stopAtComments = false; } + if (ts.positionIsSynthesized(pos)) { + return pos; + } + // Keep in sync with couldStartTrivia + while (true) { + var ch = text.charCodeAt(pos); + switch (ch) { + case 13 /* carriageReturn */: + if (text.charCodeAt(pos + 1) === 10 /* lineFeed */) { + pos++; + } + // falls through + case 10 /* lineFeed */: + pos++; + if (stopAfterLineBreak) { + return pos; + } + continue; + case 9 /* tab */: + case 11 /* verticalTab */: + case 12 /* formFeed */: + case 32 /* space */: + pos++; + continue; + case 47 /* slash */: + if (stopAtComments) { + break; + } + if (text.charCodeAt(pos + 1) === 47 /* slash */) { + pos += 2; + while (pos < text.length) { + if (isLineBreak(text.charCodeAt(pos))) { + break; + } + pos++; + } + continue; + } + if (text.charCodeAt(pos + 1) === 42 /* asterisk */) { + pos += 2; + while (pos < text.length) { + if (text.charCodeAt(pos) === 42 /* asterisk */ && text.charCodeAt(pos + 1) === 47 /* slash */) { + pos += 2; + break; + } + pos++; + } + continue; + } + break; + case 60 /* lessThan */: + case 124 /* bar */: + case 61 /* equals */: + case 62 /* greaterThan */: + if (isConflictMarkerTrivia(text, pos)) { + pos = scanConflictMarkerTrivia(text, pos); + continue; + } + break; + case 35 /* hash */: + if (pos === 0 && isShebangTrivia(text, pos)) { + pos = scanShebangTrivia(text, pos); + continue; + } + break; + default: + if (ch > 127 /* maxAsciiCharacter */ && (isWhiteSpaceLike(ch))) { + pos++; + continue; + } + break; + } + return pos; + } + } + ts.skipTrivia = skipTrivia; + // All conflict markers consist of the same character repeated seven times. If it is + // a <<<<<<< or >>>>>>> marker then it is also followed by a space. + var mergeConflictMarkerLength = "<<<<<<<".length; + function isConflictMarkerTrivia(text, pos) { + ts.Debug.assert(pos >= 0); + // Conflict markers must be at the start of a line. + if (pos === 0 || isLineBreak(text.charCodeAt(pos - 1))) { + var ch = text.charCodeAt(pos); + if ((pos + mergeConflictMarkerLength) < text.length) { + for (var i = 0; i < mergeConflictMarkerLength; i++) { + if (text.charCodeAt(pos + i) !== ch) { + return false; + } + } + return ch === 61 /* equals */ || + text.charCodeAt(pos + mergeConflictMarkerLength) === 32 /* space */; + } + } + return false; + } + function scanConflictMarkerTrivia(text, pos, error) { + if (error) { + error(ts.Diagnostics.Merge_conflict_marker_encountered, pos, mergeConflictMarkerLength); + } + var ch = text.charCodeAt(pos); + var len = text.length; + if (ch === 60 /* lessThan */ || ch === 62 /* greaterThan */) { + while (pos < len && !isLineBreak(text.charCodeAt(pos))) { + pos++; + } + } + else { + ts.Debug.assert(ch === 124 /* bar */ || ch === 61 /* equals */); + // Consume everything from the start of a ||||||| or ======= marker to the start + // of the next ======= or >>>>>>> marker. + while (pos < len) { + var currentChar = text.charCodeAt(pos); + if ((currentChar === 61 /* equals */ || currentChar === 62 /* greaterThan */) && currentChar !== ch && isConflictMarkerTrivia(text, pos)) { + break; + } + pos++; + } + } + return pos; + } + var shebangTriviaRegex = /^#!.*/; + function isShebangTrivia(text, pos) { + // Shebangs check must only be done at the start of the file + ts.Debug.assert(pos === 0); + return shebangTriviaRegex.test(text); + } + function scanShebangTrivia(text, pos) { + var shebang = shebangTriviaRegex.exec(text)[0]; + pos = pos + shebang.length; + return pos; + } + /** + * Invokes a callback for each comment range following the provided position. + * + * Single-line comment ranges include the leading double-slash characters but not the ending + * line break. Multi-line comment ranges include the leading slash-asterisk and trailing + * asterisk-slash characters. + * + * @param reduce If true, accumulates the result of calling the callback in a fashion similar + * to reduceLeft. If false, iteration stops when the callback returns a truthy value. + * @param text The source text to scan. + * @param pos The position at which to start scanning. + * @param trailing If false, whitespace is skipped until the first line break and comments + * between that location and the next token are returned. If true, comments occurring + * between the given position and the next line break are returned. + * @param cb The callback to execute as each comment range is encountered. + * @param state A state value to pass to each iteration of the callback. + * @param initial An initial value to pass when accumulating results (when "reduce" is true). + * @returns If "reduce" is true, the accumulated value. If "reduce" is false, the first truthy + * return value of the callback. + */ + function iterateCommentRanges(reduce, text, pos, trailing, cb, state, initial) { + var pendingPos; + var pendingEnd; + var pendingKind; + var pendingHasTrailingNewLine; + var hasPendingCommentRange = false; + var collecting = trailing || pos === 0; + var accumulator = initial; + scan: while (pos >= 0 && pos < text.length) { + var ch = text.charCodeAt(pos); + switch (ch) { + case 13 /* carriageReturn */: + if (text.charCodeAt(pos + 1) === 10 /* lineFeed */) { + pos++; + } + // falls through + case 10 /* lineFeed */: + pos++; + if (trailing) { + break scan; + } + collecting = true; + if (hasPendingCommentRange) { + pendingHasTrailingNewLine = true; + } + continue; + case 9 /* tab */: + case 11 /* verticalTab */: + case 12 /* formFeed */: + case 32 /* space */: + pos++; + continue; + case 47 /* slash */: + var nextChar = text.charCodeAt(pos + 1); + var hasTrailingNewLine = false; + if (nextChar === 47 /* slash */ || nextChar === 42 /* asterisk */) { + var kind = nextChar === 47 /* slash */ ? 2 /* SingleLineCommentTrivia */ : 3 /* MultiLineCommentTrivia */; + var startPos = pos; + pos += 2; + if (nextChar === 47 /* slash */) { + while (pos < text.length) { + if (isLineBreak(text.charCodeAt(pos))) { + hasTrailingNewLine = true; + break; + } + pos++; + } + } + else { + while (pos < text.length) { + if (text.charCodeAt(pos) === 42 /* asterisk */ && text.charCodeAt(pos + 1) === 47 /* slash */) { + pos += 2; + break; + } + pos++; + } + } + if (collecting) { + if (hasPendingCommentRange) { + accumulator = cb(pendingPos, pendingEnd, pendingKind, pendingHasTrailingNewLine, state, accumulator); + if (!reduce && accumulator) { + // If we are not reducing and we have a truthy result, return it. + return accumulator; + } + } + pendingPos = startPos; + pendingEnd = pos; + pendingKind = kind; + pendingHasTrailingNewLine = hasTrailingNewLine; + hasPendingCommentRange = true; + } + continue; + } + break scan; + default: + if (ch > 127 /* maxAsciiCharacter */ && (isWhiteSpaceLike(ch))) { + if (hasPendingCommentRange && isLineBreak(ch)) { + pendingHasTrailingNewLine = true; + } + pos++; + continue; + } + break scan; + } + } + if (hasPendingCommentRange) { + accumulator = cb(pendingPos, pendingEnd, pendingKind, pendingHasTrailingNewLine, state, accumulator); + } + return accumulator; + } + function forEachLeadingCommentRange(text, pos, cb, state) { + return iterateCommentRanges(/*reduce*/ false, text, pos, /*trailing*/ false, cb, state); + } + ts.forEachLeadingCommentRange = forEachLeadingCommentRange; + function forEachTrailingCommentRange(text, pos, cb, state) { + return iterateCommentRanges(/*reduce*/ false, text, pos, /*trailing*/ true, cb, state); + } + ts.forEachTrailingCommentRange = forEachTrailingCommentRange; + function reduceEachLeadingCommentRange(text, pos, cb, state, initial) { + return iterateCommentRanges(/*reduce*/ true, text, pos, /*trailing*/ false, cb, state, initial); + } + ts.reduceEachLeadingCommentRange = reduceEachLeadingCommentRange; + function reduceEachTrailingCommentRange(text, pos, cb, state, initial) { + return iterateCommentRanges(/*reduce*/ true, text, pos, /*trailing*/ true, cb, state, initial); + } + ts.reduceEachTrailingCommentRange = reduceEachTrailingCommentRange; + function appendCommentRange(pos, end, kind, hasTrailingNewLine, _state, comments) { + if (!comments) { + comments = []; + } + comments.push({ kind: kind, pos: pos, end: end, hasTrailingNewLine: hasTrailingNewLine }); + return comments; + } + function getLeadingCommentRanges(text, pos) { + return reduceEachLeadingCommentRange(text, pos, appendCommentRange, /*state*/ undefined, /*initial*/ undefined); + } + ts.getLeadingCommentRanges = getLeadingCommentRanges; + function getTrailingCommentRanges(text, pos) { + return reduceEachTrailingCommentRange(text, pos, appendCommentRange, /*state*/ undefined, /*initial*/ undefined); + } + ts.getTrailingCommentRanges = getTrailingCommentRanges; + /** Optionally, get the shebang */ + function getShebang(text) { + var match = shebangTriviaRegex.exec(text); + if (match) { + return match[0]; + } + } + ts.getShebang = getShebang; + function isIdentifierStart(ch, languageVersion) { + return ch >= 65 /* A */ && ch <= 90 /* Z */ || ch >= 97 /* a */ && ch <= 122 /* z */ || + ch === 36 /* $ */ || ch === 95 /* _ */ || + ch > 127 /* maxAsciiCharacter */ && isUnicodeIdentifierStart(ch, languageVersion); + } + ts.isIdentifierStart = isIdentifierStart; + function isIdentifierPart(ch, languageVersion) { + return ch >= 65 /* A */ && ch <= 90 /* Z */ || ch >= 97 /* a */ && ch <= 122 /* z */ || + ch >= 48 /* _0 */ && ch <= 57 /* _9 */ || ch === 36 /* $ */ || ch === 95 /* _ */ || + ch > 127 /* maxAsciiCharacter */ && isUnicodeIdentifierPart(ch, languageVersion); + } + ts.isIdentifierPart = isIdentifierPart; + /* @internal */ + function isIdentifierText(name, languageVersion) { + if (!isIdentifierStart(name.charCodeAt(0), languageVersion)) { + return false; + } + for (var i = 1; i < name.length; i++) { + if (!isIdentifierPart(name.charCodeAt(i), languageVersion)) { + return false; + } + } + return true; + } + ts.isIdentifierText = isIdentifierText; + // Creates a scanner over a (possibly unspecified) range of a piece of text. + function createScanner(languageVersion, skipTrivia, languageVariant, textInitial, onError, start, length) { + if (languageVariant === void 0) { languageVariant = 0 /* Standard */; } + var text = textInitial; + // Current position (end position of text of current token) + var pos; + // end of text + var end; + // Start position of whitespace before current token + var startPos; + // Start position of text of current token + var tokenPos; + var token; + var tokenValue; + var tokenFlags; + var inJSDocType = 0; + setText(text, start, length); + return { + getStartPos: function () { return startPos; }, + getTextPos: function () { return pos; }, + getToken: function () { return token; }, + getTokenPos: function () { return tokenPos; }, + getTokenText: function () { return text.substring(tokenPos, pos); }, + getTokenValue: function () { return tokenValue; }, + hasExtendedUnicodeEscape: function () { return (tokenFlags & 8 /* ExtendedUnicodeEscape */) !== 0; }, + hasPrecedingLineBreak: function () { return (tokenFlags & 1 /* PrecedingLineBreak */) !== 0; }, + isIdentifier: function () { return token === 72 /* Identifier */ || token > 108 /* LastReservedWord */; }, + isReservedWord: function () { return token >= 73 /* FirstReservedWord */ && token <= 108 /* LastReservedWord */; }, + isUnterminated: function () { return (tokenFlags & 4 /* Unterminated */) !== 0; }, + getTokenFlags: function () { return tokenFlags; }, + reScanGreaterToken: reScanGreaterToken, + reScanSlashToken: reScanSlashToken, + reScanTemplateToken: reScanTemplateToken, + scanJsxIdentifier: scanJsxIdentifier, + scanJsxAttributeValue: scanJsxAttributeValue, + reScanJsxToken: reScanJsxToken, + scanJsxToken: scanJsxToken, + scanJSDocToken: scanJSDocToken, + scan: scan, + getText: getText, + setText: setText, + setScriptTarget: setScriptTarget, + setLanguageVariant: setLanguageVariant, + setOnError: setOnError, + setTextPos: setTextPos, + setInJSDocType: setInJSDocType, + tryScan: tryScan, + lookAhead: lookAhead, + scanRange: scanRange, + }; + function error(message, errPos, length) { + if (errPos === void 0) { errPos = pos; } + if (onError) { + var oldPos = pos; + pos = errPos; + onError(message, length || 0); + pos = oldPos; + } + } + function scanNumberFragment() { + var start = pos; + var allowSeparator = false; + var isPreviousTokenSeparator = false; + var result = ""; + while (true) { + var ch = text.charCodeAt(pos); + if (ch === 95 /* _ */) { + tokenFlags |= 512 /* ContainsSeparator */; + if (allowSeparator) { + allowSeparator = false; + isPreviousTokenSeparator = true; + result += text.substring(start, pos); + } + else if (isPreviousTokenSeparator) { + error(ts.Diagnostics.Multiple_consecutive_numeric_separators_are_not_permitted, pos, 1); + } + else { + error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos, 1); + } + pos++; + start = pos; + continue; + } + if (isDigit(ch)) { + allowSeparator = true; + isPreviousTokenSeparator = false; + pos++; + continue; + } + break; + } + if (text.charCodeAt(pos - 1) === 95 /* _ */) { + error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos - 1, 1); + } + return result + text.substring(start, pos); + } + function scanNumber() { + var start = pos; + var mainFragment = scanNumberFragment(); + var decimalFragment; + var scientificFragment; + if (text.charCodeAt(pos) === 46 /* dot */) { + pos++; + decimalFragment = scanNumberFragment(); + } + var end = pos; + if (text.charCodeAt(pos) === 69 /* E */ || text.charCodeAt(pos) === 101 /* e */) { + pos++; + tokenFlags |= 16 /* Scientific */; + if (text.charCodeAt(pos) === 43 /* plus */ || text.charCodeAt(pos) === 45 /* minus */) + pos++; + var preNumericPart = pos; + var finalFragment = scanNumberFragment(); + if (!finalFragment) { + error(ts.Diagnostics.Digit_expected); + } + else { + scientificFragment = text.substring(end, preNumericPart) + finalFragment; + end = pos; + } + } + var result; + if (tokenFlags & 512 /* ContainsSeparator */) { + result = mainFragment; + if (decimalFragment) { + result += "." + decimalFragment; + } + if (scientificFragment) { + result += scientificFragment; + } + } + else { + result = text.substring(start, end); // No need to use all the fragments; no _ removal needed + } + if (decimalFragment !== undefined || tokenFlags & 16 /* Scientific */) { + return { + type: 8 /* NumericLiteral */, + value: "" + +result // if value is not an integer, it can be safely coerced to a number + }; + } + else { + tokenValue = result; + var type = checkBigIntSuffix(); // if value is an integer, check whether it is a bigint + return { type: type, value: tokenValue }; + } + } + function scanOctalDigits() { + var start = pos; + while (isOctalDigit(text.charCodeAt(pos))) { + pos++; + } + return +(text.substring(start, pos)); + } + /** + * Scans the given number of hexadecimal digits in the text, + * returning -1 if the given number is unavailable. + */ + function scanExactNumberOfHexDigits(count, canHaveSeparators) { + var valueString = scanHexDigits(/*minCount*/ count, /*scanAsManyAsPossible*/ false, canHaveSeparators); + return valueString ? parseInt(valueString, 16) : -1; + } + /** + * Scans as many hexadecimal digits as are available in the text, + * returning "" if the given number of digits was unavailable. + */ + function scanMinimumNumberOfHexDigits(count, canHaveSeparators) { + return scanHexDigits(/*minCount*/ count, /*scanAsManyAsPossible*/ true, canHaveSeparators); + } + function scanHexDigits(minCount, scanAsManyAsPossible, canHaveSeparators) { + var valueChars = []; + var allowSeparator = false; + var isPreviousTokenSeparator = false; + while (valueChars.length < minCount || scanAsManyAsPossible) { + var ch = text.charCodeAt(pos); + if (canHaveSeparators && ch === 95 /* _ */) { + tokenFlags |= 512 /* ContainsSeparator */; + if (allowSeparator) { + allowSeparator = false; + isPreviousTokenSeparator = true; + } + else if (isPreviousTokenSeparator) { + error(ts.Diagnostics.Multiple_consecutive_numeric_separators_are_not_permitted, pos, 1); + } + else { + error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos, 1); + } + pos++; + continue; + } + allowSeparator = canHaveSeparators; + if (ch >= 65 /* A */ && ch <= 70 /* F */) { + ch += 97 /* a */ - 65 /* A */; // standardize hex literals to lowercase + } + else if (!((ch >= 48 /* _0 */ && ch <= 57 /* _9 */) || + (ch >= 97 /* a */ && ch <= 102 /* f */))) { + break; + } + valueChars.push(ch); + pos++; + isPreviousTokenSeparator = false; + } + if (valueChars.length < minCount) { + valueChars = []; + } + if (text.charCodeAt(pos - 1) === 95 /* _ */) { + error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos - 1, 1); + } + return String.fromCharCode.apply(String, valueChars); + } + function scanString(jsxAttributeString) { + if (jsxAttributeString === void 0) { jsxAttributeString = false; } + var quote = text.charCodeAt(pos); + pos++; + var result = ""; + var start = pos; + while (true) { + if (pos >= end) { + result += text.substring(start, pos); + tokenFlags |= 4 /* Unterminated */; + error(ts.Diagnostics.Unterminated_string_literal); + break; + } + var ch = text.charCodeAt(pos); + if (ch === quote) { + result += text.substring(start, pos); + pos++; + break; + } + if (ch === 92 /* backslash */ && !jsxAttributeString) { + result += text.substring(start, pos); + result += scanEscapeSequence(); + start = pos; + continue; + } + if (isLineBreak(ch) && !jsxAttributeString) { + result += text.substring(start, pos); + tokenFlags |= 4 /* Unterminated */; + error(ts.Diagnostics.Unterminated_string_literal); + break; + } + pos++; + } + return result; + } + /** + * Sets the current 'tokenValue' and returns a NoSubstitutionTemplateLiteral or + * a literal component of a TemplateExpression. + */ + function scanTemplateAndSetTokenValue() { + var startedWithBacktick = text.charCodeAt(pos) === 96 /* backtick */; + pos++; + var start = pos; + var contents = ""; + var resultingToken; + while (true) { + if (pos >= end) { + contents += text.substring(start, pos); + tokenFlags |= 4 /* Unterminated */; + error(ts.Diagnostics.Unterminated_template_literal); + resultingToken = startedWithBacktick ? 14 /* NoSubstitutionTemplateLiteral */ : 17 /* TemplateTail */; + break; + } + var currChar = text.charCodeAt(pos); + // '`' + if (currChar === 96 /* backtick */) { + contents += text.substring(start, pos); + pos++; + resultingToken = startedWithBacktick ? 14 /* NoSubstitutionTemplateLiteral */ : 17 /* TemplateTail */; + break; + } + // '${' + if (currChar === 36 /* $ */ && pos + 1 < end && text.charCodeAt(pos + 1) === 123 /* openBrace */) { + contents += text.substring(start, pos); + pos += 2; + resultingToken = startedWithBacktick ? 15 /* TemplateHead */ : 16 /* TemplateMiddle */; + break; + } + // Escape character + if (currChar === 92 /* backslash */) { + contents += text.substring(start, pos); + contents += scanEscapeSequence(); + start = pos; + continue; + } + // Speculated ECMAScript 6 Spec 11.8.6.1: + // and LineTerminatorSequences are normalized to for Template Values + if (currChar === 13 /* carriageReturn */) { + contents += text.substring(start, pos); + pos++; + if (pos < end && text.charCodeAt(pos) === 10 /* lineFeed */) { + pos++; + } + contents += "\n"; + start = pos; + continue; + } + pos++; + } + ts.Debug.assert(resultingToken !== undefined); + tokenValue = contents; + return resultingToken; + } + function scanEscapeSequence() { + pos++; + if (pos >= end) { + error(ts.Diagnostics.Unexpected_end_of_text); + return ""; + } + var ch = text.charCodeAt(pos); + pos++; + switch (ch) { + case 48 /* _0 */: + return "\0"; + case 98 /* b */: + return "\b"; + case 116 /* t */: + return "\t"; + case 110 /* n */: + return "\n"; + case 118 /* v */: + return "\v"; + case 102 /* f */: + return "\f"; + case 114 /* r */: + return "\r"; + case 39 /* singleQuote */: + return "\'"; + case 34 /* doubleQuote */: + return "\""; + case 117 /* u */: + // '\u{DDDDDDDD}' + if (pos < end && text.charCodeAt(pos) === 123 /* openBrace */) { + tokenFlags |= 8 /* ExtendedUnicodeEscape */; + pos++; + return scanExtendedUnicodeEscape(); + } + // '\uDDDD' + return scanHexadecimalEscape(/*numDigits*/ 4); + case 120 /* x */: + // '\xDD' + return scanHexadecimalEscape(/*numDigits*/ 2); + // when encountering a LineContinuation (i.e. a backslash and a line terminator sequence), + // the line terminator is interpreted to be "the empty code unit sequence". + case 13 /* carriageReturn */: + if (pos < end && text.charCodeAt(pos) === 10 /* lineFeed */) { + pos++; + } + // falls through + case 10 /* lineFeed */: + case 8232 /* lineSeparator */: + case 8233 /* paragraphSeparator */: + return ""; + default: + return String.fromCharCode(ch); + } + } + function scanHexadecimalEscape(numDigits) { + var escapedValue = scanExactNumberOfHexDigits(numDigits, /*canHaveSeparators*/ false); + if (escapedValue >= 0) { + return String.fromCharCode(escapedValue); + } + else { + error(ts.Diagnostics.Hexadecimal_digit_expected); + return ""; + } + } + function scanExtendedUnicodeEscape() { + var escapedValueString = scanMinimumNumberOfHexDigits(1, /*canHaveSeparators*/ false); + var escapedValue = escapedValueString ? parseInt(escapedValueString, 16) : -1; + var isInvalidExtendedEscape = false; + // Validate the value of the digit + if (escapedValue < 0) { + error(ts.Diagnostics.Hexadecimal_digit_expected); + isInvalidExtendedEscape = true; + } + else if (escapedValue > 0x10FFFF) { + error(ts.Diagnostics.An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive); + isInvalidExtendedEscape = true; + } + if (pos >= end) { + error(ts.Diagnostics.Unexpected_end_of_text); + isInvalidExtendedEscape = true; + } + else if (text.charCodeAt(pos) === 125 /* closeBrace */) { + // Only swallow the following character up if it's a '}'. + pos++; + } + else { + error(ts.Diagnostics.Unterminated_Unicode_escape_sequence); + isInvalidExtendedEscape = true; + } + if (isInvalidExtendedEscape) { + return ""; + } + return utf16EncodeAsString(escapedValue); + } + // Derived from the 10.1.1 UTF16Encoding of the ES6 Spec. + function utf16EncodeAsString(codePoint) { + ts.Debug.assert(0x0 <= codePoint && codePoint <= 0x10FFFF); + if (codePoint <= 65535) { + return String.fromCharCode(codePoint); + } + var codeUnit1 = Math.floor((codePoint - 65536) / 1024) + 0xD800; + var codeUnit2 = ((codePoint - 65536) % 1024) + 0xDC00; + return String.fromCharCode(codeUnit1, codeUnit2); + } + // Current character is known to be a backslash. Check for Unicode escape of the form '\uXXXX' + // and return code point value if valid Unicode escape is found. Otherwise return -1. + function peekUnicodeEscape() { + if (pos + 5 < end && text.charCodeAt(pos + 1) === 117 /* u */) { + var start_1 = pos; + pos += 2; + var value = scanExactNumberOfHexDigits(4, /*canHaveSeparators*/ false); + pos = start_1; + return value; + } + return -1; + } + function scanIdentifierParts() { + var result = ""; + var start = pos; + while (pos < end) { + var ch = text.charCodeAt(pos); + if (isIdentifierPart(ch, languageVersion)) { + pos++; + } + else if (ch === 92 /* backslash */) { + ch = peekUnicodeEscape(); + if (!(ch >= 0 && isIdentifierPart(ch, languageVersion))) { + break; + } + result += text.substring(start, pos); + result += String.fromCharCode(ch); + // Valid Unicode escape is always six characters + pos += 6; + start = pos; + } + else { + break; + } + } + result += text.substring(start, pos); + return result; + } + function getIdentifierToken() { + // Reserved words are between 2 and 11 characters long and start with a lowercase letter + var len = tokenValue.length; + if (len >= 2 && len <= 11) { + var ch = tokenValue.charCodeAt(0); + if (ch >= 97 /* a */ && ch <= 122 /* z */) { + var keyword = textToKeyword.get(tokenValue); + if (keyword !== undefined) { + return token = keyword; + } + } + } + return token = 72 /* Identifier */; + } + function scanBinaryOrOctalDigits(base) { + var value = ""; + // For counting number of digits; Valid binaryIntegerLiteral must have at least one binary digit following B or b. + // Similarly valid octalIntegerLiteral must have at least one octal digit following o or O. + var separatorAllowed = false; + var isPreviousTokenSeparator = false; + while (true) { + var ch = text.charCodeAt(pos); + // Numeric separators are allowed anywhere within a numeric literal, except not at the beginning, or following another separator + if (ch === 95 /* _ */) { + tokenFlags |= 512 /* ContainsSeparator */; + if (separatorAllowed) { + separatorAllowed = false; + isPreviousTokenSeparator = true; + } + else if (isPreviousTokenSeparator) { + error(ts.Diagnostics.Multiple_consecutive_numeric_separators_are_not_permitted, pos, 1); + } + else { + error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos, 1); + } + pos++; + continue; + } + separatorAllowed = true; + if (!isDigit(ch) || ch - 48 /* _0 */ >= base) { + break; + } + value += text[pos]; + pos++; + isPreviousTokenSeparator = false; + } + if (text.charCodeAt(pos - 1) === 95 /* _ */) { + // Literal ends with underscore - not allowed + error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos - 1, 1); + } + return value; + } + function checkBigIntSuffix() { + if (text.charCodeAt(pos) === 110 /* n */) { + tokenValue += "n"; + // Use base 10 instead of base 2 or base 8 for shorter literals + if (tokenFlags & 384 /* BinaryOrOctalSpecifier */) { + tokenValue = ts.parsePseudoBigInt(tokenValue) + "n"; + } + pos++; + return 9 /* BigIntLiteral */; + } + else { // not a bigint, so can convert to number in simplified form + // Number() may not support 0b or 0o, so use parseInt() instead + var numericValue = tokenFlags & 128 /* BinarySpecifier */ + ? parseInt(tokenValue.slice(2), 2) // skip "0b" + : tokenFlags & 256 /* OctalSpecifier */ + ? parseInt(tokenValue.slice(2), 8) // skip "0o" + : +tokenValue; + tokenValue = "" + numericValue; + return 8 /* NumericLiteral */; + } + } + function scan() { + var _a; + startPos = pos; + tokenFlags = 0; + var asteriskSeen = false; + while (true) { + tokenPos = pos; + if (pos >= end) { + return token = 1 /* EndOfFileToken */; + } + var ch = text.charCodeAt(pos); + // Special handling for shebang + if (ch === 35 /* hash */ && pos === 0 && isShebangTrivia(text, pos)) { + pos = scanShebangTrivia(text, pos); + if (skipTrivia) { + continue; + } + else { + return token = 6 /* ShebangTrivia */; + } + } + switch (ch) { + case 10 /* lineFeed */: + case 13 /* carriageReturn */: + tokenFlags |= 1 /* PrecedingLineBreak */; + if (skipTrivia) { + pos++; + continue; + } + else { + if (ch === 13 /* carriageReturn */ && pos + 1 < end && text.charCodeAt(pos + 1) === 10 /* lineFeed */) { + // consume both CR and LF + pos += 2; + } + else { + pos++; + } + return token = 4 /* NewLineTrivia */; + } + case 9 /* tab */: + case 11 /* verticalTab */: + case 12 /* formFeed */: + case 32 /* space */: + case 160 /* nonBreakingSpace */: + case 5760 /* ogham */: + case 8192 /* enQuad */: + case 8193 /* emQuad */: + case 8194 /* enSpace */: + case 8195 /* emSpace */: + case 8196 /* threePerEmSpace */: + case 8197 /* fourPerEmSpace */: + case 8198 /* sixPerEmSpace */: + case 8199 /* figureSpace */: + case 8200 /* punctuationSpace */: + case 8201 /* thinSpace */: + case 8202 /* hairSpace */: + case 8203 /* zeroWidthSpace */: + case 8239 /* narrowNoBreakSpace */: + case 8287 /* mathematicalSpace */: + case 12288 /* ideographicSpace */: + case 65279 /* byteOrderMark */: + if (skipTrivia) { + pos++; + continue; + } + else { + while (pos < end && isWhiteSpaceSingleLine(text.charCodeAt(pos))) { + pos++; + } + return token = 5 /* WhitespaceTrivia */; + } + case 33 /* exclamation */: + if (text.charCodeAt(pos + 1) === 61 /* equals */) { + if (text.charCodeAt(pos + 2) === 61 /* equals */) { + return pos += 3, token = 36 /* ExclamationEqualsEqualsToken */; + } + return pos += 2, token = 34 /* ExclamationEqualsToken */; + } + pos++; + return token = 52 /* ExclamationToken */; + case 34 /* doubleQuote */: + case 39 /* singleQuote */: + tokenValue = scanString(); + return token = 10 /* StringLiteral */; + case 96 /* backtick */: + return token = scanTemplateAndSetTokenValue(); + case 37 /* percent */: + if (text.charCodeAt(pos + 1) === 61 /* equals */) { + return pos += 2, token = 65 /* PercentEqualsToken */; + } + pos++; + return token = 43 /* PercentToken */; + case 38 /* ampersand */: + if (text.charCodeAt(pos + 1) === 38 /* ampersand */) { + return pos += 2, token = 54 /* AmpersandAmpersandToken */; + } + if (text.charCodeAt(pos + 1) === 61 /* equals */) { + return pos += 2, token = 69 /* AmpersandEqualsToken */; + } + pos++; + return token = 49 /* AmpersandToken */; + case 40 /* openParen */: + pos++; + return token = 20 /* OpenParenToken */; + case 41 /* closeParen */: + pos++; + return token = 21 /* CloseParenToken */; + case 42 /* asterisk */: + if (text.charCodeAt(pos + 1) === 61 /* equals */) { + return pos += 2, token = 62 /* AsteriskEqualsToken */; + } + if (text.charCodeAt(pos + 1) === 42 /* asterisk */) { + if (text.charCodeAt(pos + 2) === 61 /* equals */) { + return pos += 3, token = 63 /* AsteriskAsteriskEqualsToken */; + } + return pos += 2, token = 41 /* AsteriskAsteriskToken */; + } + pos++; + if (inJSDocType && !asteriskSeen && (tokenFlags & 1 /* PrecedingLineBreak */)) { + // decoration at the start of a JSDoc comment line + asteriskSeen = true; + continue; + } + return token = 40 /* AsteriskToken */; + case 43 /* plus */: + if (text.charCodeAt(pos + 1) === 43 /* plus */) { + return pos += 2, token = 44 /* PlusPlusToken */; + } + if (text.charCodeAt(pos + 1) === 61 /* equals */) { + return pos += 2, token = 60 /* PlusEqualsToken */; + } + pos++; + return token = 38 /* PlusToken */; + case 44 /* comma */: + pos++; + return token = 27 /* CommaToken */; + case 45 /* minus */: + if (text.charCodeAt(pos + 1) === 45 /* minus */) { + return pos += 2, token = 45 /* MinusMinusToken */; + } + if (text.charCodeAt(pos + 1) === 61 /* equals */) { + return pos += 2, token = 61 /* MinusEqualsToken */; + } + pos++; + return token = 39 /* MinusToken */; + case 46 /* dot */: + if (isDigit(text.charCodeAt(pos + 1))) { + tokenValue = scanNumber().value; + return token = 8 /* NumericLiteral */; + } + if (text.charCodeAt(pos + 1) === 46 /* dot */ && text.charCodeAt(pos + 2) === 46 /* dot */) { + return pos += 3, token = 25 /* DotDotDotToken */; + } + pos++; + return token = 24 /* DotToken */; + case 47 /* slash */: + // Single-line comment + if (text.charCodeAt(pos + 1) === 47 /* slash */) { + pos += 2; + while (pos < end) { + if (isLineBreak(text.charCodeAt(pos))) { + break; + } + pos++; + } + if (skipTrivia) { + continue; + } + else { + return token = 2 /* SingleLineCommentTrivia */; + } + } + // Multi-line comment + if (text.charCodeAt(pos + 1) === 42 /* asterisk */) { + pos += 2; + if (text.charCodeAt(pos) === 42 /* asterisk */ && text.charCodeAt(pos + 1) !== 47 /* slash */) { + tokenFlags |= 2 /* PrecedingJSDocComment */; + } + var commentClosed = false; + while (pos < end) { + var ch_1 = text.charCodeAt(pos); + if (ch_1 === 42 /* asterisk */ && text.charCodeAt(pos + 1) === 47 /* slash */) { + pos += 2; + commentClosed = true; + break; + } + if (isLineBreak(ch_1)) { + tokenFlags |= 1 /* PrecedingLineBreak */; + } + pos++; + } + if (!commentClosed) { + error(ts.Diagnostics.Asterisk_Slash_expected); + } + if (skipTrivia) { + continue; + } + else { + if (!commentClosed) { + tokenFlags |= 4 /* Unterminated */; + } + return token = 3 /* MultiLineCommentTrivia */; + } + } + if (text.charCodeAt(pos + 1) === 61 /* equals */) { + return pos += 2, token = 64 /* SlashEqualsToken */; + } + pos++; + return token = 42 /* SlashToken */; + case 48 /* _0 */: + if (pos + 2 < end && (text.charCodeAt(pos + 1) === 88 /* X */ || text.charCodeAt(pos + 1) === 120 /* x */)) { + pos += 2; + tokenValue = scanMinimumNumberOfHexDigits(1, /*canHaveSeparators*/ true); + if (!tokenValue) { + error(ts.Diagnostics.Hexadecimal_digit_expected); + tokenValue = "0"; + } + tokenValue = "0x" + tokenValue; + tokenFlags |= 64 /* HexSpecifier */; + return token = checkBigIntSuffix(); + } + else if (pos + 2 < end && (text.charCodeAt(pos + 1) === 66 /* B */ || text.charCodeAt(pos + 1) === 98 /* b */)) { + pos += 2; + tokenValue = scanBinaryOrOctalDigits(/* base */ 2); + if (!tokenValue) { + error(ts.Diagnostics.Binary_digit_expected); + tokenValue = "0"; + } + tokenValue = "0b" + tokenValue; + tokenFlags |= 128 /* BinarySpecifier */; + return token = checkBigIntSuffix(); + } + else if (pos + 2 < end && (text.charCodeAt(pos + 1) === 79 /* O */ || text.charCodeAt(pos + 1) === 111 /* o */)) { + pos += 2; + tokenValue = scanBinaryOrOctalDigits(/* base */ 8); + if (!tokenValue) { + error(ts.Diagnostics.Octal_digit_expected); + tokenValue = "0"; + } + tokenValue = "0o" + tokenValue; + tokenFlags |= 256 /* OctalSpecifier */; + return token = checkBigIntSuffix(); + } + // Try to parse as an octal + if (pos + 1 < end && isOctalDigit(text.charCodeAt(pos + 1))) { + tokenValue = "" + scanOctalDigits(); + tokenFlags |= 32 /* Octal */; + return token = 8 /* NumericLiteral */; + } + // This fall-through is a deviation from the EcmaScript grammar. The grammar says that a leading zero + // can only be followed by an octal digit, a dot, or the end of the number literal. However, we are being + // permissive and allowing decimal digits of the form 08* and 09* (which many browsers also do). + // falls through + case 49 /* _1 */: + case 50 /* _2 */: + case 51 /* _3 */: + case 52 /* _4 */: + case 53 /* _5 */: + case 54 /* _6 */: + case 55 /* _7 */: + case 56 /* _8 */: + case 57 /* _9 */: + (_a = scanNumber(), token = _a.type, tokenValue = _a.value); + return token; + case 58 /* colon */: + pos++; + return token = 57 /* ColonToken */; + case 59 /* semicolon */: + pos++; + return token = 26 /* SemicolonToken */; + case 60 /* lessThan */: + if (isConflictMarkerTrivia(text, pos)) { + pos = scanConflictMarkerTrivia(text, pos, error); + if (skipTrivia) { + continue; + } + else { + return token = 7 /* ConflictMarkerTrivia */; + } + } + if (text.charCodeAt(pos + 1) === 60 /* lessThan */) { + if (text.charCodeAt(pos + 2) === 61 /* equals */) { + return pos += 3, token = 66 /* LessThanLessThanEqualsToken */; + } + return pos += 2, token = 46 /* LessThanLessThanToken */; + } + if (text.charCodeAt(pos + 1) === 61 /* equals */) { + return pos += 2, token = 31 /* LessThanEqualsToken */; + } + if (languageVariant === 1 /* JSX */ && + text.charCodeAt(pos + 1) === 47 /* slash */ && + text.charCodeAt(pos + 2) !== 42 /* asterisk */) { + return pos += 2, token = 29 /* LessThanSlashToken */; + } + pos++; + return token = 28 /* LessThanToken */; + case 61 /* equals */: + if (isConflictMarkerTrivia(text, pos)) { + pos = scanConflictMarkerTrivia(text, pos, error); + if (skipTrivia) { + continue; + } + else { + return token = 7 /* ConflictMarkerTrivia */; + } + } + if (text.charCodeAt(pos + 1) === 61 /* equals */) { + if (text.charCodeAt(pos + 2) === 61 /* equals */) { + return pos += 3, token = 35 /* EqualsEqualsEqualsToken */; + } + return pos += 2, token = 33 /* EqualsEqualsToken */; + } + if (text.charCodeAt(pos + 1) === 62 /* greaterThan */) { + return pos += 2, token = 37 /* EqualsGreaterThanToken */; + } + pos++; + return token = 59 /* EqualsToken */; + case 62 /* greaterThan */: + if (isConflictMarkerTrivia(text, pos)) { + pos = scanConflictMarkerTrivia(text, pos, error); + if (skipTrivia) { + continue; + } + else { + return token = 7 /* ConflictMarkerTrivia */; + } + } + pos++; + return token = 30 /* GreaterThanToken */; + case 63 /* question */: + pos++; + return token = 56 /* QuestionToken */; + case 91 /* openBracket */: + pos++; + return token = 22 /* OpenBracketToken */; + case 93 /* closeBracket */: + pos++; + return token = 23 /* CloseBracketToken */; + case 94 /* caret */: + if (text.charCodeAt(pos + 1) === 61 /* equals */) { + return pos += 2, token = 71 /* CaretEqualsToken */; + } + pos++; + return token = 51 /* CaretToken */; + case 123 /* openBrace */: + pos++; + return token = 18 /* OpenBraceToken */; + case 124 /* bar */: + if (isConflictMarkerTrivia(text, pos)) { + pos = scanConflictMarkerTrivia(text, pos, error); + if (skipTrivia) { + continue; + } + else { + return token = 7 /* ConflictMarkerTrivia */; + } + } + if (text.charCodeAt(pos + 1) === 124 /* bar */) { + return pos += 2, token = 55 /* BarBarToken */; + } + if (text.charCodeAt(pos + 1) === 61 /* equals */) { + return pos += 2, token = 70 /* BarEqualsToken */; + } + pos++; + return token = 50 /* BarToken */; + case 125 /* closeBrace */: + pos++; + return token = 19 /* CloseBraceToken */; + case 126 /* tilde */: + pos++; + return token = 53 /* TildeToken */; + case 64 /* at */: + pos++; + return token = 58 /* AtToken */; + case 92 /* backslash */: + var cookedChar = peekUnicodeEscape(); + if (cookedChar >= 0 && isIdentifierStart(cookedChar, languageVersion)) { + pos += 6; + tokenValue = String.fromCharCode(cookedChar) + scanIdentifierParts(); + return token = getIdentifierToken(); + } + error(ts.Diagnostics.Invalid_character); + pos++; + return token = 0 /* Unknown */; + default: + if (isIdentifierStart(ch, languageVersion)) { + pos++; + while (pos < end && isIdentifierPart(ch = text.charCodeAt(pos), languageVersion)) + pos++; + tokenValue = text.substring(tokenPos, pos); + if (ch === 92 /* backslash */) { + tokenValue += scanIdentifierParts(); + } + return token = getIdentifierToken(); + } + else if (isWhiteSpaceSingleLine(ch)) { + pos++; + continue; + } + else if (isLineBreak(ch)) { + tokenFlags |= 1 /* PrecedingLineBreak */; + pos++; + continue; + } + error(ts.Diagnostics.Invalid_character); + pos++; + return token = 0 /* Unknown */; + } + } + } + function reScanGreaterToken() { + if (token === 30 /* GreaterThanToken */) { + if (text.charCodeAt(pos) === 62 /* greaterThan */) { + if (text.charCodeAt(pos + 1) === 62 /* greaterThan */) { + if (text.charCodeAt(pos + 2) === 61 /* equals */) { + return pos += 3, token = 68 /* GreaterThanGreaterThanGreaterThanEqualsToken */; + } + return pos += 2, token = 48 /* GreaterThanGreaterThanGreaterThanToken */; + } + if (text.charCodeAt(pos + 1) === 61 /* equals */) { + return pos += 2, token = 67 /* GreaterThanGreaterThanEqualsToken */; + } + pos++; + return token = 47 /* GreaterThanGreaterThanToken */; + } + if (text.charCodeAt(pos) === 61 /* equals */) { + pos++; + return token = 32 /* GreaterThanEqualsToken */; + } + } + return token; + } + function reScanSlashToken() { + if (token === 42 /* SlashToken */ || token === 64 /* SlashEqualsToken */) { + var p = tokenPos + 1; + var inEscape = false; + var inCharacterClass = false; + while (true) { + // If we reach the end of a file, or hit a newline, then this is an unterminated + // regex. Report error and return what we have so far. + if (p >= end) { + tokenFlags |= 4 /* Unterminated */; + error(ts.Diagnostics.Unterminated_regular_expression_literal); + break; + } + var ch = text.charCodeAt(p); + if (isLineBreak(ch)) { + tokenFlags |= 4 /* Unterminated */; + error(ts.Diagnostics.Unterminated_regular_expression_literal); + break; + } + if (inEscape) { + // Parsing an escape character; + // reset the flag and just advance to the next char. + inEscape = false; + } + else if (ch === 47 /* slash */ && !inCharacterClass) { + // A slash within a character class is permissible, + // but in general it signals the end of the regexp literal. + p++; + break; + } + else if (ch === 91 /* openBracket */) { + inCharacterClass = true; + } + else if (ch === 92 /* backslash */) { + inEscape = true; + } + else if (ch === 93 /* closeBracket */) { + inCharacterClass = false; + } + p++; + } + while (p < end && isIdentifierPart(text.charCodeAt(p), languageVersion)) { + p++; + } + pos = p; + tokenValue = text.substring(tokenPos, pos); + token = 13 /* RegularExpressionLiteral */; + } + return token; + } + /** + * Unconditionally back up and scan a template expression portion. + */ + function reScanTemplateToken() { + ts.Debug.assert(token === 19 /* CloseBraceToken */, "'reScanTemplateToken' should only be called on a '}'"); + pos = tokenPos; + return token = scanTemplateAndSetTokenValue(); + } + function reScanJsxToken() { + pos = tokenPos = startPos; + return token = scanJsxToken(); + } + function scanJsxToken() { + startPos = tokenPos = pos; + if (pos >= end) { + return token = 1 /* EndOfFileToken */; + } + var char = text.charCodeAt(pos); + if (char === 60 /* lessThan */) { + if (text.charCodeAt(pos + 1) === 47 /* slash */) { + pos += 2; + return token = 29 /* LessThanSlashToken */; + } + pos++; + return token = 28 /* LessThanToken */; + } + if (char === 123 /* openBrace */) { + pos++; + return token = 18 /* OpenBraceToken */; + } + // First non-whitespace character on this line. + var firstNonWhitespace = 0; + // These initial values are special because the first line is: + // firstNonWhitespace = 0 to indicate that we want leading whitspace, + while (pos < end) { + char = text.charCodeAt(pos); + if (char === 123 /* openBrace */) { + break; + } + if (char === 60 /* lessThan */) { + if (isConflictMarkerTrivia(text, pos)) { + pos = scanConflictMarkerTrivia(text, pos, error); + return token = 7 /* ConflictMarkerTrivia */; + } + break; + } + // FirstNonWhitespace is 0, then we only see whitespaces so far. If we see a linebreak, we want to ignore that whitespaces. + // i.e (- : whitespace) + //
      ---- + //
      becomes
      + // + //
      ----
      becomes
      ----
      + if (isLineBreak(char) && firstNonWhitespace === 0) { + firstNonWhitespace = -1; + } + else if (!isWhiteSpaceLike(char)) { + firstNonWhitespace = pos; + } + pos++; + } + return firstNonWhitespace === -1 ? 12 /* JsxTextAllWhiteSpaces */ : 11 /* JsxText */; + } + // Scans a JSX identifier; these differ from normal identifiers in that + // they allow dashes + function scanJsxIdentifier() { + if (tokenIsIdentifierOrKeyword(token)) { + var firstCharPosition = pos; + while (pos < end) { + var ch = text.charCodeAt(pos); + if (ch === 45 /* minus */ || ((firstCharPosition === pos) ? isIdentifierStart(ch, languageVersion) : isIdentifierPart(ch, languageVersion))) { + pos++; + } + else { + break; + } + } + tokenValue += text.substring(firstCharPosition, pos); + } + return token; + } + function scanJsxAttributeValue() { + startPos = pos; + switch (text.charCodeAt(pos)) { + case 34 /* doubleQuote */: + case 39 /* singleQuote */: + tokenValue = scanString(/*jsxAttributeString*/ true); + return token = 10 /* StringLiteral */; + default: + // If this scans anything other than `{`, it's a parse error. + return scan(); + } + } + function scanJSDocToken() { + startPos = tokenPos = pos; + tokenFlags = 0; + if (pos >= end) { + return token = 1 /* EndOfFileToken */; + } + var ch = text.charCodeAt(pos); + pos++; + switch (ch) { + case 9 /* tab */: + case 11 /* verticalTab */: + case 12 /* formFeed */: + case 32 /* space */: + while (pos < end && isWhiteSpaceSingleLine(text.charCodeAt(pos))) { + pos++; + } + return token = 5 /* WhitespaceTrivia */; + case 64 /* at */: + return token = 58 /* AtToken */; + case 10 /* lineFeed */: + case 13 /* carriageReturn */: + tokenFlags |= 1 /* PrecedingLineBreak */; + return token = 4 /* NewLineTrivia */; + case 42 /* asterisk */: + return token = 40 /* AsteriskToken */; + case 123 /* openBrace */: + return token = 18 /* OpenBraceToken */; + case 125 /* closeBrace */: + return token = 19 /* CloseBraceToken */; + case 91 /* openBracket */: + return token = 22 /* OpenBracketToken */; + case 93 /* closeBracket */: + return token = 23 /* CloseBracketToken */; + case 60 /* lessThan */: + return token = 28 /* LessThanToken */; + case 61 /* equals */: + return token = 59 /* EqualsToken */; + case 44 /* comma */: + return token = 27 /* CommaToken */; + case 46 /* dot */: + return token = 24 /* DotToken */; + case 96 /* backtick */: + while (pos < end && text.charCodeAt(pos) !== 96 /* backtick */) { + pos++; + } + tokenValue = text.substring(tokenPos + 1, pos); + pos++; + return token = 14 /* NoSubstitutionTemplateLiteral */; + } + if (isIdentifierStart(ch, 6 /* Latest */)) { + while (isIdentifierPart(text.charCodeAt(pos), 6 /* Latest */) && pos < end) { + pos++; + } + tokenValue = text.substring(tokenPos, pos); + return token = getIdentifierToken(); + } + else { + return token = 0 /* Unknown */; + } + } + function speculationHelper(callback, isLookahead) { + var savePos = pos; + var saveStartPos = startPos; + var saveTokenPos = tokenPos; + var saveToken = token; + var saveTokenValue = tokenValue; + var saveTokenFlags = tokenFlags; + var result = callback(); + // If our callback returned something 'falsy' or we're just looking ahead, + // then unconditionally restore us to where we were. + if (!result || isLookahead) { + pos = savePos; + startPos = saveStartPos; + tokenPos = saveTokenPos; + token = saveToken; + tokenValue = saveTokenValue; + tokenFlags = saveTokenFlags; + } + return result; + } + function scanRange(start, length, callback) { + var saveEnd = end; + var savePos = pos; + var saveStartPos = startPos; + var saveTokenPos = tokenPos; + var saveToken = token; + var saveTokenValue = tokenValue; + var saveTokenFlags = tokenFlags; + setText(text, start, length); + var result = callback(); + end = saveEnd; + pos = savePos; + startPos = saveStartPos; + tokenPos = saveTokenPos; + token = saveToken; + tokenValue = saveTokenValue; + tokenFlags = saveTokenFlags; + return result; + } + function lookAhead(callback) { + return speculationHelper(callback, /*isLookahead*/ true); + } + function tryScan(callback) { + return speculationHelper(callback, /*isLookahead*/ false); + } + function getText() { + return text; + } + function setText(newText, start, length) { + text = newText || ""; + end = length === undefined ? text.length : start + length; + setTextPos(start || 0); + } + function setOnError(errorCallback) { + onError = errorCallback; + } + function setScriptTarget(scriptTarget) { + languageVersion = scriptTarget; + } + function setLanguageVariant(variant) { + languageVariant = variant; + } + function setTextPos(textPos) { + ts.Debug.assert(textPos >= 0); + pos = textPos; + startPos = textPos; + tokenPos = textPos; + token = 0 /* Unknown */; + tokenValue = undefined; + tokenFlags = 0; + } + function setInJSDocType(inType) { + inJSDocType += inType ? 1 : -1; + } + } + ts.createScanner = createScanner; +})(ts || (ts = {})); +var ts; +(function (ts) { + function isExternalModuleNameRelative(moduleName) { + // TypeScript 1.0 spec (April 2014): 11.2.1 + // An external module name is "relative" if the first term is "." or "..". + // Update: We also consider a path like `C:\foo.ts` "relative" because we do not search for it in `node_modules` or treat it as an ambient module. + return ts.pathIsRelative(moduleName) || ts.isRootedDiskPath(moduleName); + } + ts.isExternalModuleNameRelative = isExternalModuleNameRelative; + function sortAndDeduplicateDiagnostics(diagnostics) { + return ts.sortAndDeduplicate(diagnostics, ts.compareDiagnostics); + } + ts.sortAndDeduplicateDiagnostics = sortAndDeduplicateDiagnostics; +})(ts || (ts = {})); +/* @internal */ +(function (ts) { + ts.resolvingEmptyArray = []; + ts.emptyMap = ts.createMap(); + ts.emptyUnderscoreEscapedMap = ts.emptyMap; + ts.externalHelpersModuleNameText = "tslib"; + ts.defaultMaximumTruncationLength = 160; + function getDeclarationOfKind(symbol, kind) { + var declarations = symbol.declarations; + if (declarations) { + for (var _i = 0, declarations_1 = declarations; _i < declarations_1.length; _i++) { + var declaration = declarations_1[_i]; + if (declaration.kind === kind) { + return declaration; + } + } + } + return undefined; + } + ts.getDeclarationOfKind = getDeclarationOfKind; + /** Create a new escaped identifier map. */ + function createUnderscoreEscapedMap() { + return new ts.MapCtr(); + } + ts.createUnderscoreEscapedMap = createUnderscoreEscapedMap; + function hasEntries(map) { + return !!map && !!map.size; + } + ts.hasEntries = hasEntries; + function createSymbolTable(symbols) { + var result = ts.createMap(); + if (symbols) { + for (var _i = 0, symbols_1 = symbols; _i < symbols_1.length; _i++) { + var symbol = symbols_1[_i]; + result.set(symbol.escapedName, symbol); + } + } + return result; + } + ts.createSymbolTable = createSymbolTable; + var stringWriter = createSingleLineStringWriter(); + function createSingleLineStringWriter() { + var str = ""; + var writeText = function (text) { return str += text; }; + return { + getText: function () { return str; }, + write: writeText, + rawWrite: writeText, + writeKeyword: writeText, + writeOperator: writeText, + writePunctuation: writeText, + writeSpace: writeText, + writeStringLiteral: writeText, + writeLiteral: writeText, + writeParameter: writeText, + writeProperty: writeText, + writeSymbol: function (s, _) { return writeText(s); }, + writeTrailingSemicolon: writeText, + writeComment: writeText, + getTextPos: function () { return str.length; }, + getLine: function () { return 0; }, + getColumn: function () { return 0; }, + getIndent: function () { return 0; }, + isAtStartOfLine: function () { return false; }, + // Completely ignore indentation for string writers. And map newlines to + // a single space. + writeLine: function () { return str += " "; }, + increaseIndent: ts.noop, + decreaseIndent: ts.noop, + clear: function () { return str = ""; }, + trackSymbol: ts.noop, + reportInaccessibleThisError: ts.noop, + reportInaccessibleUniqueSymbolError: ts.noop, + reportPrivateInBaseOfClassExpression: ts.noop, + }; + } + function toPath(fileName, basePath, getCanonicalFileName) { + var nonCanonicalizedPath = ts.isRootedDiskPath(fileName) + ? ts.normalizePath(fileName) + : ts.getNormalizedAbsolutePath(fileName, basePath); + return getCanonicalFileName(nonCanonicalizedPath); + } + ts.toPath = toPath; + function changesAffectModuleResolution(oldOptions, newOptions) { + return oldOptions.configFilePath !== newOptions.configFilePath || ts.moduleResolutionOptionDeclarations.some(function (o) { + return !ts.isJsonEqual(ts.getCompilerOptionValue(oldOptions, o), ts.getCompilerOptionValue(newOptions, o)); + }); + } + ts.changesAffectModuleResolution = changesAffectModuleResolution; + function findAncestor(node, callback) { + while (node) { + var result = callback(node); + if (result === "quit") { + return undefined; + } + else if (result) { + return node; + } + node = node.parent; + } + return undefined; + } + ts.findAncestor = findAncestor; + function forEachAncestor(node, callback) { + while (true) { + var res = callback(node); + if (res === "quit") + return undefined; + if (res !== undefined) + return res; + if (ts.isSourceFile(node)) + return undefined; + node = node.parent; + } + } + ts.forEachAncestor = forEachAncestor; + function forEachEntry(map, callback) { + var _a; + var iterator = map.entries(); + for (var _b = iterator.next(), pair = _b.value, done = _b.done; !done; _a = iterator.next(), pair = _a.value, done = _a.done, _a) { + var key = pair[0], value = pair[1]; + var result = callback(value, key); + if (result) { + return result; + } + } + return undefined; + } + ts.forEachEntry = forEachEntry; + function forEachKey(map, callback) { + var _a; + var iterator = map.keys(); + for (var _b = iterator.next(), key = _b.value, done = _b.done; !done; _a = iterator.next(), key = _a.value, done = _a.done, _a) { + var result = callback(key); + if (result) { + return result; + } + } + return undefined; + } + ts.forEachKey = forEachKey; + function copyEntries(source, target) { + source.forEach(function (value, key) { + target.set(key, value); + }); + } + ts.copyEntries = copyEntries; + function arrayToSet(array, makeKey) { + return ts.arrayToMap(array, makeKey || (function (s) { return s; }), function () { return true; }); + } + ts.arrayToSet = arrayToSet; + function cloneMap(map) { + var clone = ts.createMap(); + copyEntries(map, clone); + return clone; + } + ts.cloneMap = cloneMap; + function usingSingleLineStringWriter(action) { + var oldString = stringWriter.getText(); + try { + action(stringWriter); + return stringWriter.getText(); + } + finally { + stringWriter.clear(); + stringWriter.writeKeyword(oldString); + } + } + ts.usingSingleLineStringWriter = usingSingleLineStringWriter; + function getFullWidth(node) { + return node.end - node.pos; + } + ts.getFullWidth = getFullWidth; + function getResolvedModule(sourceFile, moduleNameText) { + return sourceFile && sourceFile.resolvedModules && sourceFile.resolvedModules.get(moduleNameText); + } + ts.getResolvedModule = getResolvedModule; + function setResolvedModule(sourceFile, moduleNameText, resolvedModule) { + if (!sourceFile.resolvedModules) { + sourceFile.resolvedModules = ts.createMap(); + } + sourceFile.resolvedModules.set(moduleNameText, resolvedModule); + } + ts.setResolvedModule = setResolvedModule; + function setResolvedTypeReferenceDirective(sourceFile, typeReferenceDirectiveName, resolvedTypeReferenceDirective) { + if (!sourceFile.resolvedTypeReferenceDirectiveNames) { + sourceFile.resolvedTypeReferenceDirectiveNames = ts.createMap(); + } + sourceFile.resolvedTypeReferenceDirectiveNames.set(typeReferenceDirectiveName, resolvedTypeReferenceDirective); + } + ts.setResolvedTypeReferenceDirective = setResolvedTypeReferenceDirective; + function projectReferenceIsEqualTo(oldRef, newRef) { + return oldRef.path === newRef.path && + !oldRef.prepend === !newRef.prepend && + !oldRef.circular === !newRef.circular; + } + ts.projectReferenceIsEqualTo = projectReferenceIsEqualTo; + function moduleResolutionIsEqualTo(oldResolution, newResolution) { + return oldResolution.isExternalLibraryImport === newResolution.isExternalLibraryImport && + oldResolution.extension === newResolution.extension && + oldResolution.resolvedFileName === newResolution.resolvedFileName && + oldResolution.originalPath === newResolution.originalPath && + packageIdIsEqual(oldResolution.packageId, newResolution.packageId); + } + ts.moduleResolutionIsEqualTo = moduleResolutionIsEqualTo; + function packageIdIsEqual(a, b) { + return a === b || !!a && !!b && a.name === b.name && a.subModuleName === b.subModuleName && a.version === b.version; + } + function packageIdToString(_a) { + var name = _a.name, subModuleName = _a.subModuleName, version = _a.version; + var fullName = subModuleName ? name + "/" + subModuleName : name; + return fullName + "@" + version; + } + ts.packageIdToString = packageIdToString; + function typeDirectiveIsEqualTo(oldResolution, newResolution) { + return oldResolution.resolvedFileName === newResolution.resolvedFileName && oldResolution.primary === newResolution.primary; + } + ts.typeDirectiveIsEqualTo = typeDirectiveIsEqualTo; + function hasChangesInResolutions(names, newResolutions, oldResolutions, comparer) { + ts.Debug.assert(names.length === newResolutions.length); + for (var i = 0; i < names.length; i++) { + var newResolution = newResolutions[i]; + var oldResolution = oldResolutions && oldResolutions.get(names[i]); + var changed = oldResolution + ? !newResolution || !comparer(oldResolution, newResolution) + : newResolution; + if (changed) { + return true; + } + } + return false; + } + ts.hasChangesInResolutions = hasChangesInResolutions; + // Returns true if this node contains a parse error anywhere underneath it. + function containsParseError(node) { + aggregateChildData(node); + return (node.flags & 131072 /* ThisNodeOrAnySubNodesHasError */) !== 0; + } + ts.containsParseError = containsParseError; + function aggregateChildData(node) { + if (!(node.flags & 262144 /* HasAggregatedChildData */)) { + // A node is considered to contain a parse error if: + // a) the parser explicitly marked that it had an error + // b) any of it's children reported that it had an error. + var thisNodeOrAnySubNodesHasError = ((node.flags & 32768 /* ThisNodeHasError */) !== 0) || + ts.forEachChild(node, containsParseError); + // If so, mark ourselves accordingly. + if (thisNodeOrAnySubNodesHasError) { + node.flags |= 131072 /* ThisNodeOrAnySubNodesHasError */; + } + // Also mark that we've propagated the child information to this node. This way we can + // always consult the bit directly on this node without needing to check its children + // again. + node.flags |= 262144 /* HasAggregatedChildData */; + } + } + function getSourceFileOfNode(node) { + while (node && node.kind !== 279 /* SourceFile */) { + node = node.parent; + } + return node; + } + ts.getSourceFileOfNode = getSourceFileOfNode; + function isStatementWithLocals(node) { + switch (node.kind) { + case 218 /* Block */: + case 246 /* CaseBlock */: + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + return true; + } + return false; + } + ts.isStatementWithLocals = isStatementWithLocals; + function getStartPositionOfLine(line, sourceFile) { + ts.Debug.assert(line >= 0); + return ts.getLineStarts(sourceFile)[line]; + } + ts.getStartPositionOfLine = getStartPositionOfLine; + // This is a useful function for debugging purposes. + function nodePosToString(node) { + var file = getSourceFileOfNode(node); + var loc = ts.getLineAndCharacterOfPosition(file, node.pos); + return file.fileName + "(" + (loc.line + 1) + "," + (loc.character + 1) + ")"; + } + ts.nodePosToString = nodePosToString; + function getEndLinePosition(line, sourceFile) { + ts.Debug.assert(line >= 0); + var lineStarts = ts.getLineStarts(sourceFile); + var lineIndex = line; + var sourceText = sourceFile.text; + if (lineIndex + 1 === lineStarts.length) { + // last line - return EOF + return sourceText.length - 1; + } + else { + // current line start + var start = lineStarts[lineIndex]; + // take the start position of the next line - 1 = it should be some line break + var pos = lineStarts[lineIndex + 1] - 1; + ts.Debug.assert(ts.isLineBreak(sourceText.charCodeAt(pos))); + // walk backwards skipping line breaks, stop the the beginning of current line. + // i.e: + // + // $ <- end of line for this position should match the start position + while (start <= pos && ts.isLineBreak(sourceText.charCodeAt(pos))) { + pos--; + } + return pos; + } + } + ts.getEndLinePosition = getEndLinePosition; + /** + * Returns a value indicating whether a name is unique globally or within the current file. + * Note: This does not consider whether a name appears as a free identifier or not, so at the expression `x.y` this includes both `x` and `y`. + */ + function isFileLevelUniqueName(sourceFile, name, hasGlobalName) { + return !(hasGlobalName && hasGlobalName(name)) && !sourceFile.identifiers.has(name); + } + ts.isFileLevelUniqueName = isFileLevelUniqueName; + // Returns true if this node is missing from the actual source code. A 'missing' node is different + // from 'undefined/defined'. When a node is undefined (which can happen for optional nodes + // in the tree), it is definitely missing. However, a node may be defined, but still be + // missing. This happens whenever the parser knows it needs to parse something, but can't + // get anything in the source code that it expects at that location. For example: + // + // let a: ; + // + // Here, the Type in the Type-Annotation is not-optional (as there is a colon in the source + // code). So the parser will attempt to parse out a type, and will create an actual node. + // However, this node will be 'missing' in the sense that no actual source-code/tokens are + // contained within it. + function nodeIsMissing(node) { + if (node === undefined) { + return true; + } + return node.pos === node.end && node.pos >= 0 && node.kind !== 1 /* EndOfFileToken */; + } + ts.nodeIsMissing = nodeIsMissing; + function nodeIsPresent(node) { + return !nodeIsMissing(node); + } + ts.nodeIsPresent = nodeIsPresent; + /** + * Prepends statements to an array while taking care of prologue directives. + */ + function addStatementsAfterPrologue(to, from) { + if (from === undefined || from.length === 0) + return to; + var statementIndex = 0; + // skip all prologue directives to insert at the correct position + for (; statementIndex < to.length; ++statementIndex) { + if (!isPrologueDirective(to[statementIndex])) { + break; + } + } + to.splice.apply(to, [statementIndex, 0].concat(from)); + return to; + } + ts.addStatementsAfterPrologue = addStatementsAfterPrologue; + /** + * Determine if the given comment is a triple-slash + * + * @return true if the comment is a triple-slash comment else false + */ + function isRecognizedTripleSlashComment(text, commentPos, commentEnd) { + // Verify this is /// comment, but do the regexp match only when we first can find /// in the comment text + // so that we don't end up computing comment string and doing match for all // comments + if (text.charCodeAt(commentPos + 1) === 47 /* slash */ && + commentPos + 2 < commentEnd && + text.charCodeAt(commentPos + 2) === 47 /* slash */) { + var textSubStr = text.substring(commentPos, commentEnd); + return textSubStr.match(ts.fullTripleSlashReferencePathRegEx) || + textSubStr.match(ts.fullTripleSlashAMDReferencePathRegEx) || + textSubStr.match(fullTripleSlashReferenceTypeReferenceDirectiveRegEx) || + textSubStr.match(defaultLibReferenceRegEx) ? + true : false; + } + return false; + } + ts.isRecognizedTripleSlashComment = isRecognizedTripleSlashComment; + function isPinnedComment(text, start) { + return text.charCodeAt(start + 1) === 42 /* asterisk */ && + text.charCodeAt(start + 2) === 33 /* exclamation */; + } + ts.isPinnedComment = isPinnedComment; + function getTokenPosOfNode(node, sourceFile, includeJsDoc) { + // With nodes that have no width (i.e. 'Missing' nodes), we actually *don't* + // want to skip trivia because this will launch us forward to the next token. + if (nodeIsMissing(node)) { + return node.pos; + } + if (ts.isJSDocNode(node)) { + return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos, /*stopAfterLineBreak*/ false, /*stopAtComments*/ true); + } + if (includeJsDoc && ts.hasJSDocNodes(node)) { + return getTokenPosOfNode(node.jsDoc[0]); + } + // For a syntax list, it is possible that one of its children has JSDocComment nodes, while + // the syntax list itself considers them as normal trivia. Therefore if we simply skip + // trivia for the list, we may have skipped the JSDocComment as well. So we should process its + // first child to determine the actual position of its first token. + if (node.kind === 306 /* SyntaxList */ && node._children.length > 0) { + return getTokenPosOfNode(node._children[0], sourceFile, includeJsDoc); + } + return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos); + } + ts.getTokenPosOfNode = getTokenPosOfNode; + function getNonDecoratorTokenPosOfNode(node, sourceFile) { + if (nodeIsMissing(node) || !node.decorators) { + return getTokenPosOfNode(node, sourceFile); + } + return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.decorators.end); + } + ts.getNonDecoratorTokenPosOfNode = getNonDecoratorTokenPosOfNode; + function getSourceTextOfNodeFromSourceFile(sourceFile, node, includeTrivia) { + if (includeTrivia === void 0) { includeTrivia = false; } + return getTextOfNodeFromSourceText(sourceFile.text, node, includeTrivia); + } + ts.getSourceTextOfNodeFromSourceFile = getSourceTextOfNodeFromSourceFile; + function isJSDocTypeExpressionOrChild(node) { + return node.kind === 283 /* JSDocTypeExpression */ || (node.parent && isJSDocTypeExpressionOrChild(node.parent)); + } + function getTextOfNodeFromSourceText(sourceText, node, includeTrivia) { + if (includeTrivia === void 0) { includeTrivia = false; } + if (nodeIsMissing(node)) { + return ""; + } + var text = sourceText.substring(includeTrivia ? node.pos : ts.skipTrivia(sourceText, node.pos), node.end); + if (isJSDocTypeExpressionOrChild(node)) { + // strip space + asterisk at line start + text = text.replace(/(^|\r?\n|\r)\s*\*\s*/g, "$1"); + } + return text; + } + ts.getTextOfNodeFromSourceText = getTextOfNodeFromSourceText; + function getTextOfNode(node, includeTrivia) { + if (includeTrivia === void 0) { includeTrivia = false; } + return getSourceTextOfNodeFromSourceFile(getSourceFileOfNode(node), node, includeTrivia); + } + ts.getTextOfNode = getTextOfNode; + function getPos(range) { + return range.pos; + } + /** + * Note: it is expected that the `nodeArray` and the `node` are within the same file. + * For example, searching for a `SourceFile` in a `SourceFile[]` wouldn't work. + */ + function indexOfNode(nodeArray, node) { + return ts.binarySearch(nodeArray, node, getPos, ts.compareValues); + } + ts.indexOfNode = indexOfNode; + /** + * Gets flags that control emit behavior of a node. + */ + function getEmitFlags(node) { + var emitNode = node.emitNode; + return emitNode && emitNode.flags || 0; + } + ts.getEmitFlags = getEmitFlags; + function getLiteralText(node, sourceFile, neverAsciiEscape) { + // If we don't need to downlevel and we can reach the original source text using + // the node's parent reference, then simply get the text as it was originally written. + if (!nodeIsSynthesized(node) && node.parent && !((ts.isNumericLiteral(node) && node.numericLiteralFlags & 512 /* ContainsSeparator */) || + ts.isBigIntLiteral(node))) { + return getSourceTextOfNodeFromSourceFile(sourceFile, node); + } + var escapeText = neverAsciiEscape || (getEmitFlags(node) & 16777216 /* NoAsciiEscaping */) ? escapeString : escapeNonAsciiString; + // If we can't reach the original source text, use the canonical form if it's a number, + // or a (possibly escaped) quoted form of the original text if it's string-like. + switch (node.kind) { + case 10 /* StringLiteral */: + if (node.singleQuote) { + return "'" + escapeText(node.text, 39 /* singleQuote */) + "'"; + } + else { + return '"' + escapeText(node.text, 34 /* doubleQuote */) + '"'; + } + case 14 /* NoSubstitutionTemplateLiteral */: + return "`" + escapeText(node.text, 96 /* backtick */) + "`"; + case 15 /* TemplateHead */: + // tslint:disable-next-line no-invalid-template-strings + return "`" + escapeText(node.text, 96 /* backtick */) + "${"; + case 16 /* TemplateMiddle */: + // tslint:disable-next-line no-invalid-template-strings + return "}" + escapeText(node.text, 96 /* backtick */) + "${"; + case 17 /* TemplateTail */: + return "}" + escapeText(node.text, 96 /* backtick */) + "`"; + case 8 /* NumericLiteral */: + case 9 /* BigIntLiteral */: + case 13 /* RegularExpressionLiteral */: + return node.text; + } + return ts.Debug.fail("Literal kind '" + node.kind + "' not accounted for."); + } + ts.getLiteralText = getLiteralText; + function getTextOfConstantValue(value) { + return ts.isString(value) ? '"' + escapeNonAsciiString(value) + '"' : "" + value; + } + ts.getTextOfConstantValue = getTextOfConstantValue; + // Make an identifier from an external module name by extracting the string after the last "/" and replacing + // all non-alphanumeric characters with underscores + function makeIdentifierFromModuleName(moduleName) { + return ts.getBaseFileName(moduleName).replace(/^(\d)/, "_$1").replace(/\W/g, "_"); + } + ts.makeIdentifierFromModuleName = makeIdentifierFromModuleName; + function isBlockOrCatchScoped(declaration) { + return (ts.getCombinedNodeFlags(declaration) & 3 /* BlockScoped */) !== 0 || + isCatchClauseVariableDeclarationOrBindingElement(declaration); + } + ts.isBlockOrCatchScoped = isBlockOrCatchScoped; + function isCatchClauseVariableDeclarationOrBindingElement(declaration) { + var node = getRootDeclaration(declaration); + return node.kind === 237 /* VariableDeclaration */ && node.parent.kind === 274 /* CatchClause */; + } + ts.isCatchClauseVariableDeclarationOrBindingElement = isCatchClauseVariableDeclarationOrBindingElement; + function isAmbientModule(node) { + return ts.isModuleDeclaration(node) && (node.name.kind === 10 /* StringLiteral */ || isGlobalScopeAugmentation(node)); + } + ts.isAmbientModule = isAmbientModule; + function isModuleWithStringLiteralName(node) { + return ts.isModuleDeclaration(node) && node.name.kind === 10 /* StringLiteral */; + } + ts.isModuleWithStringLiteralName = isModuleWithStringLiteralName; + function isNonGlobalAmbientModule(node) { + return ts.isModuleDeclaration(node) && ts.isStringLiteral(node.name); + } + ts.isNonGlobalAmbientModule = isNonGlobalAmbientModule; + /** + * An effective module (namespace) declaration is either + * 1. An actual declaration: namespace X { ... } + * 2. A Javascript declaration, which is: + * An identifier in a nested property access expression: Y in `X.Y.Z = { ... }` + */ + function isEffectiveModuleDeclaration(node) { + return ts.isModuleDeclaration(node) || ts.isIdentifier(node); + } + ts.isEffectiveModuleDeclaration = isEffectiveModuleDeclaration; + /** Given a symbol for a module, checks that it is a shorthand ambient module. */ + function isShorthandAmbientModuleSymbol(moduleSymbol) { + return isShorthandAmbientModule(moduleSymbol.valueDeclaration); + } + ts.isShorthandAmbientModuleSymbol = isShorthandAmbientModuleSymbol; + function isShorthandAmbientModule(node) { + // The only kind of module that can be missing a body is a shorthand ambient module. + return node && node.kind === 244 /* ModuleDeclaration */ && (!node.body); + } + function isBlockScopedContainerTopLevel(node) { + return node.kind === 279 /* SourceFile */ || + node.kind === 244 /* ModuleDeclaration */ || + ts.isFunctionLike(node); + } + ts.isBlockScopedContainerTopLevel = isBlockScopedContainerTopLevel; + function isGlobalScopeAugmentation(module) { + return !!(module.flags & 512 /* GlobalAugmentation */); + } + ts.isGlobalScopeAugmentation = isGlobalScopeAugmentation; + function isExternalModuleAugmentation(node) { + return isAmbientModule(node) && isModuleAugmentationExternal(node); + } + ts.isExternalModuleAugmentation = isExternalModuleAugmentation; + function isModuleAugmentationExternal(node) { + // external module augmentation is a ambient module declaration that is either: + // - defined in the top level scope and source file is an external module + // - defined inside ambient module declaration located in the top level scope and source file not an external module + switch (node.parent.kind) { + case 279 /* SourceFile */: + return ts.isExternalModule(node.parent); + case 245 /* ModuleBlock */: + return isAmbientModule(node.parent.parent) && ts.isSourceFile(node.parent.parent.parent) && !ts.isExternalModule(node.parent.parent.parent); + } + return false; + } + ts.isModuleAugmentationExternal = isModuleAugmentationExternal; + function getNonAugmentationDeclaration(symbol) { + return ts.find(symbol.declarations, function (d) { return !isExternalModuleAugmentation(d) && !(ts.isModuleDeclaration(d) && isGlobalScopeAugmentation(d)); }); + } + ts.getNonAugmentationDeclaration = getNonAugmentationDeclaration; + function isEffectiveExternalModule(node, compilerOptions) { + return ts.isExternalModule(node) || compilerOptions.isolatedModules || ((ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS) && !!node.commonJsModuleIndicator); + } + ts.isEffectiveExternalModule = isEffectiveExternalModule; + function isBlockScope(node, parentNode) { + switch (node.kind) { + case 279 /* SourceFile */: + case 246 /* CaseBlock */: + case 274 /* CatchClause */: + case 244 /* ModuleDeclaration */: + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + case 157 /* Constructor */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + return true; + case 218 /* Block */: + // function block is not considered block-scope container + // see comment in binder.ts: bind(...), case for SyntaxKind.Block + return !ts.isFunctionLike(parentNode); + } + return false; + } + ts.isBlockScope = isBlockScope; + function isDeclarationWithTypeParameters(node) { + switch (node.kind) { + case 297 /* JSDocCallbackTag */: + case 304 /* JSDocTypedefTag */: + case 293 /* JSDocSignature */: + return true; + default: + ts.assertType(node); + return isDeclarationWithTypeParameterChildren(node); + } + } + ts.isDeclarationWithTypeParameters = isDeclarationWithTypeParameters; + function isDeclarationWithTypeParameterChildren(node) { + switch (node.kind) { + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 155 /* MethodSignature */: + case 162 /* IndexSignature */: + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + case 289 /* JSDocFunctionType */: + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 241 /* InterfaceDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 303 /* JSDocTemplateTag */: + case 239 /* FunctionDeclaration */: + case 156 /* MethodDeclaration */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + return true; + default: + ts.assertType(node); + return false; + } + } + ts.isDeclarationWithTypeParameterChildren = isDeclarationWithTypeParameterChildren; + function isAnyImportSyntax(node) { + switch (node.kind) { + case 249 /* ImportDeclaration */: + case 248 /* ImportEqualsDeclaration */: + return true; + default: + return false; + } + } + ts.isAnyImportSyntax = isAnyImportSyntax; + function isLateVisibilityPaintedStatement(node) { + switch (node.kind) { + case 249 /* ImportDeclaration */: + case 248 /* ImportEqualsDeclaration */: + case 219 /* VariableStatement */: + case 240 /* ClassDeclaration */: + case 239 /* FunctionDeclaration */: + case 244 /* ModuleDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 241 /* InterfaceDeclaration */: + case 243 /* EnumDeclaration */: + return true; + default: + return false; + } + } + ts.isLateVisibilityPaintedStatement = isLateVisibilityPaintedStatement; + function isAnyImportOrReExport(node) { + return isAnyImportSyntax(node) || ts.isExportDeclaration(node); + } + ts.isAnyImportOrReExport = isAnyImportOrReExport; + // Gets the nearest enclosing block scope container that has the provided node + // as a descendant, that is not the provided node. + function getEnclosingBlockScopeContainer(node) { + return findAncestor(node.parent, function (current) { return isBlockScope(current, current.parent); }); + } + ts.getEnclosingBlockScopeContainer = getEnclosingBlockScopeContainer; + // Return display name of an identifier + // Computed property names will just be emitted as "[]", where is the source + // text of the expression in the computed property. + function declarationNameToString(name) { + return !name || getFullWidth(name) === 0 ? "(Missing)" : getTextOfNode(name); + } + ts.declarationNameToString = declarationNameToString; + function getNameFromIndexInfo(info) { + return info.declaration ? declarationNameToString(info.declaration.parameters[0].name) : undefined; + } + ts.getNameFromIndexInfo = getNameFromIndexInfo; + function getTextOfPropertyName(name) { + switch (name.kind) { + case 72 /* Identifier */: + return name.escapedText; + case 10 /* StringLiteral */: + case 8 /* NumericLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: + return ts.escapeLeadingUnderscores(name.text); + case 149 /* ComputedPropertyName */: + return isStringOrNumericLiteralLike(name.expression) ? ts.escapeLeadingUnderscores(name.expression.text) : undefined; // TODO: GH#18217 Almost all uses of this assume the result to be defined! + default: + return ts.Debug.assertNever(name); + } + } + ts.getTextOfPropertyName = getTextOfPropertyName; + function entityNameToString(name) { + switch (name.kind) { + case 72 /* Identifier */: + return getFullWidth(name) === 0 ? ts.idText(name) : getTextOfNode(name); + case 148 /* QualifiedName */: + return entityNameToString(name.left) + "." + entityNameToString(name.right); + case 189 /* PropertyAccessExpression */: + return entityNameToString(name.expression) + "." + entityNameToString(name.name); + default: + throw ts.Debug.assertNever(name); + } + } + ts.entityNameToString = entityNameToString; + function createDiagnosticForNode(node, message, arg0, arg1, arg2, arg3) { + var sourceFile = getSourceFileOfNode(node); + return createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2, arg3); + } + ts.createDiagnosticForNode = createDiagnosticForNode; + function createDiagnosticForNodeArray(sourceFile, nodes, message, arg0, arg1, arg2, arg3) { + var start = ts.skipTrivia(sourceFile.text, nodes.pos); + return ts.createFileDiagnostic(sourceFile, start, nodes.end - start, message, arg0, arg1, arg2, arg3); + } + ts.createDiagnosticForNodeArray = createDiagnosticForNodeArray; + function createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2, arg3) { + var span = getErrorSpanForNode(sourceFile, node); + return ts.createFileDiagnostic(sourceFile, span.start, span.length, message, arg0, arg1, arg2, arg3); + } + ts.createDiagnosticForNodeInSourceFile = createDiagnosticForNodeInSourceFile; + function createDiagnosticForNodeFromMessageChain(node, messageChain, relatedInformation) { + var sourceFile = getSourceFileOfNode(node); + var span = getErrorSpanForNode(sourceFile, node); + return { + file: sourceFile, + start: span.start, + length: span.length, + code: messageChain.code, + category: messageChain.category, + messageText: messageChain.next ? messageChain : messageChain.messageText, + relatedInformation: relatedInformation + }; + } + ts.createDiagnosticForNodeFromMessageChain = createDiagnosticForNodeFromMessageChain; + function getSpanOfTokenAtPosition(sourceFile, pos) { + var scanner = ts.createScanner(sourceFile.languageVersion, /*skipTrivia*/ true, sourceFile.languageVariant, sourceFile.text, /*onError:*/ undefined, pos); + scanner.scan(); + var start = scanner.getTokenPos(); + return ts.createTextSpanFromBounds(start, scanner.getTextPos()); + } + ts.getSpanOfTokenAtPosition = getSpanOfTokenAtPosition; + function getErrorSpanForArrowFunction(sourceFile, node) { + var pos = ts.skipTrivia(sourceFile.text, node.pos); + if (node.body && node.body.kind === 218 /* Block */) { + var startLine = ts.getLineAndCharacterOfPosition(sourceFile, node.body.pos).line; + var endLine = ts.getLineAndCharacterOfPosition(sourceFile, node.body.end).line; + if (startLine < endLine) { + // The arrow function spans multiple lines, + // make the error span be the first line, inclusive. + return ts.createTextSpan(pos, getEndLinePosition(startLine, sourceFile) - pos + 1); + } + } + return ts.createTextSpanFromBounds(pos, node.end); + } + function getErrorSpanForNode(sourceFile, node) { + var errorNode = node; + switch (node.kind) { + case 279 /* SourceFile */: + var pos_1 = ts.skipTrivia(sourceFile.text, 0, /*stopAfterLineBreak*/ false); + if (pos_1 === sourceFile.text.length) { + // file is empty - return span for the beginning of the file + return ts.createTextSpan(0, 0); + } + return getSpanOfTokenAtPosition(sourceFile, pos_1); + // This list is a work in progress. Add missing node kinds to improve their error + // spans. + case 237 /* VariableDeclaration */: + case 186 /* BindingElement */: + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 241 /* InterfaceDeclaration */: + case 244 /* ModuleDeclaration */: + case 243 /* EnumDeclaration */: + case 278 /* EnumMember */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 242 /* TypeAliasDeclaration */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + errorNode = node.name; + break; + case 197 /* ArrowFunction */: + return getErrorSpanForArrowFunction(sourceFile, node); + } + if (errorNode === undefined) { + // If we don't have a better node, then just set the error on the first token of + // construct. + return getSpanOfTokenAtPosition(sourceFile, node.pos); + } + var isMissing = nodeIsMissing(errorNode); + var pos = isMissing + ? errorNode.pos + : ts.skipTrivia(sourceFile.text, errorNode.pos); + // These asserts should all be satisfied for a properly constructed `errorNode`. + if (isMissing) { + ts.Debug.assert(pos === errorNode.pos, "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809"); + ts.Debug.assert(pos === errorNode.end, "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809"); + } + else { + ts.Debug.assert(pos >= errorNode.pos, "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809"); + ts.Debug.assert(pos <= errorNode.end, "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809"); + } + return ts.createTextSpanFromBounds(pos, errorNode.end); + } + ts.getErrorSpanForNode = getErrorSpanForNode; + function isExternalOrCommonJsModule(file) { + return (file.externalModuleIndicator || file.commonJsModuleIndicator) !== undefined; + } + ts.isExternalOrCommonJsModule = isExternalOrCommonJsModule; + function isJsonSourceFile(file) { + return file.scriptKind === 6 /* JSON */; + } + ts.isJsonSourceFile = isJsonSourceFile; + function isEnumConst(node) { + return !!(ts.getCombinedModifierFlags(node) & 2048 /* Const */); + } + ts.isEnumConst = isEnumConst; + function isDeclarationReadonly(declaration) { + return !!(ts.getCombinedModifierFlags(declaration) & 64 /* Readonly */ && !ts.isParameterPropertyDeclaration(declaration)); + } + ts.isDeclarationReadonly = isDeclarationReadonly; + function isVarConst(node) { + return !!(ts.getCombinedNodeFlags(node) & 2 /* Const */); + } + ts.isVarConst = isVarConst; + function isLet(node) { + return !!(ts.getCombinedNodeFlags(node) & 1 /* Let */); + } + ts.isLet = isLet; + function isSuperCall(n) { + return n.kind === 191 /* CallExpression */ && n.expression.kind === 98 /* SuperKeyword */; + } + ts.isSuperCall = isSuperCall; + function isImportCall(n) { + return n.kind === 191 /* CallExpression */ && n.expression.kind === 92 /* ImportKeyword */; + } + ts.isImportCall = isImportCall; + function isLiteralImportTypeNode(n) { + return ts.isImportTypeNode(n) && ts.isLiteralTypeNode(n.argument) && ts.isStringLiteral(n.argument.literal); + } + ts.isLiteralImportTypeNode = isLiteralImportTypeNode; + function isPrologueDirective(node) { + return node.kind === 221 /* ExpressionStatement */ + && node.expression.kind === 10 /* StringLiteral */; + } + ts.isPrologueDirective = isPrologueDirective; + function getLeadingCommentRangesOfNode(node, sourceFileOfNode) { + return node.kind !== 11 /* JsxText */ ? ts.getLeadingCommentRanges(sourceFileOfNode.text, node.pos) : undefined; + } + ts.getLeadingCommentRangesOfNode = getLeadingCommentRangesOfNode; + function getJSDocCommentRanges(node, text) { + var commentRanges = (node.kind === 151 /* Parameter */ || + node.kind === 150 /* TypeParameter */ || + node.kind === 196 /* FunctionExpression */ || + node.kind === 197 /* ArrowFunction */ || + node.kind === 195 /* ParenthesizedExpression */) ? + ts.concatenate(ts.getTrailingCommentRanges(text, node.pos), ts.getLeadingCommentRanges(text, node.pos)) : + ts.getLeadingCommentRanges(text, node.pos); + // True if the comment starts with '/**' but not if it is '/**/' + return ts.filter(commentRanges, function (comment) { + return text.charCodeAt(comment.pos + 1) === 42 /* asterisk */ && + text.charCodeAt(comment.pos + 2) === 42 /* asterisk */ && + text.charCodeAt(comment.pos + 3) !== 47 /* slash */; + }); + } + ts.getJSDocCommentRanges = getJSDocCommentRanges; + ts.fullTripleSlashReferencePathRegEx = /^(\/\/\/\s*/; + var fullTripleSlashReferenceTypeReferenceDirectiveRegEx = /^(\/\/\/\s*/; + ts.fullTripleSlashAMDReferencePathRegEx = /^(\/\/\/\s*/; + var defaultLibReferenceRegEx = /^(\/\/\/\s*/; + function isPartOfTypeNode(node) { + if (163 /* FirstTypeNode */ <= node.kind && node.kind <= 183 /* LastTypeNode */) { + return true; + } + switch (node.kind) { + case 120 /* AnyKeyword */: + case 143 /* UnknownKeyword */: + case 135 /* NumberKeyword */: + case 146 /* BigIntKeyword */: + case 138 /* StringKeyword */: + case 123 /* BooleanKeyword */: + case 139 /* SymbolKeyword */: + case 136 /* ObjectKeyword */: + case 141 /* UndefinedKeyword */: + case 132 /* NeverKeyword */: + return true; + case 106 /* VoidKeyword */: + return node.parent.kind !== 200 /* VoidExpression */; + case 211 /* ExpressionWithTypeArguments */: + return !isExpressionWithTypeArgumentsInClassExtendsClause(node); + case 150 /* TypeParameter */: + return node.parent.kind === 181 /* MappedType */ || node.parent.kind === 176 /* InferType */; + // Identifiers and qualified names may be type nodes, depending on their context. Climb + // above them to find the lowest container + case 72 /* Identifier */: + // If the identifier is the RHS of a qualified name, then it's a type iff its parent is. + if (node.parent.kind === 148 /* QualifiedName */ && node.parent.right === node) { + node = node.parent; + } + else if (node.parent.kind === 189 /* PropertyAccessExpression */ && node.parent.name === node) { + node = node.parent; + } + // At this point, node is either a qualified name or an identifier + ts.Debug.assert(node.kind === 72 /* Identifier */ || node.kind === 148 /* QualifiedName */ || node.kind === 189 /* PropertyAccessExpression */, "'node' was expected to be a qualified name, identifier or property access in 'isPartOfTypeNode'."); + // falls through + case 148 /* QualifiedName */: + case 189 /* PropertyAccessExpression */: + case 100 /* ThisKeyword */: { + var parent = node.parent; + if (parent.kind === 167 /* TypeQuery */) { + return false; + } + if (parent.kind === 183 /* ImportType */) { + return !parent.isTypeOf; + } + // Do not recursively call isPartOfTypeNode on the parent. In the example: + // + // let a: A.B.C; + // + // Calling isPartOfTypeNode would consider the qualified name A.B a type node. + // Only C and A.B.C are type nodes. + if (163 /* FirstTypeNode */ <= parent.kind && parent.kind <= 183 /* LastTypeNode */) { + return true; + } + switch (parent.kind) { + case 211 /* ExpressionWithTypeArguments */: + return !isExpressionWithTypeArgumentsInClassExtendsClause(parent); + case 150 /* TypeParameter */: + return node === parent.constraint; + case 303 /* JSDocTemplateTag */: + return node === parent.constraint; + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 151 /* Parameter */: + case 237 /* VariableDeclaration */: + return node === parent.type; + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 157 /* Constructor */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + return node === parent.type; + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 162 /* IndexSignature */: + return node === parent.type; + case 194 /* TypeAssertionExpression */: + return node === parent.type; + case 191 /* CallExpression */: + case 192 /* NewExpression */: + return ts.contains(parent.typeArguments, node); + case 193 /* TaggedTemplateExpression */: + // TODO (drosen): TaggedTemplateExpressions may eventually support type arguments. + return false; + } + } + } + return false; + } + ts.isPartOfTypeNode = isPartOfTypeNode; + function isChildOfNodeWithKind(node, kind) { + while (node) { + if (node.kind === kind) { + return true; + } + node = node.parent; + } + return false; + } + ts.isChildOfNodeWithKind = isChildOfNodeWithKind; + // Warning: This has the same semantics as the forEach family of functions, + // in that traversal terminates in the event that 'visitor' supplies a truthy value. + function forEachReturnStatement(body, visitor) { + return traverse(body); + function traverse(node) { + switch (node.kind) { + case 230 /* ReturnStatement */: + return visitor(node); + case 246 /* CaseBlock */: + case 218 /* Block */: + case 222 /* IfStatement */: + case 223 /* DoStatement */: + case 224 /* WhileStatement */: + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + case 231 /* WithStatement */: + case 232 /* SwitchStatement */: + case 271 /* CaseClause */: + case 272 /* DefaultClause */: + case 233 /* LabeledStatement */: + case 235 /* TryStatement */: + case 274 /* CatchClause */: + return ts.forEachChild(node, traverse); + } + } + } + ts.forEachReturnStatement = forEachReturnStatement; + function forEachYieldExpression(body, visitor) { + return traverse(body); + function traverse(node) { + switch (node.kind) { + case 207 /* YieldExpression */: + visitor(node); + var operand = node.expression; + if (operand) { + traverse(operand); + } + return; + case 243 /* EnumDeclaration */: + case 241 /* InterfaceDeclaration */: + case 244 /* ModuleDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + // These are not allowed inside a generator now, but eventually they may be allowed + // as local types. Regardless, any yield statements contained within them should be + // skipped in this traversal. + return; + default: + if (ts.isFunctionLike(node)) { + if (node.name && node.name.kind === 149 /* ComputedPropertyName */) { + // Note that we will not include methods/accessors of a class because they would require + // first descending into the class. This is by design. + traverse(node.name.expression); + return; + } + } + else if (!isPartOfTypeNode(node)) { + // This is the general case, which should include mostly expressions and statements. + // Also includes NodeArrays. + ts.forEachChild(node, traverse); + } + } + } + } + ts.forEachYieldExpression = forEachYieldExpression; + /** + * Gets the most likely element type for a TypeNode. This is not an exhaustive test + * as it assumes a rest argument can only be an array type (either T[], or Array). + * + * @param node The type node. + */ + function getRestParameterElementType(node) { + if (node && node.kind === 169 /* ArrayType */) { + return node.elementType; + } + else if (node && node.kind === 164 /* TypeReference */) { + return ts.singleOrUndefined(node.typeArguments); + } + else { + return undefined; + } + } + ts.getRestParameterElementType = getRestParameterElementType; + function getMembersOfDeclaration(node) { + switch (node.kind) { + case 241 /* InterfaceDeclaration */: + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 168 /* TypeLiteral */: + return node.members; + case 188 /* ObjectLiteralExpression */: + return node.properties; + } + } + ts.getMembersOfDeclaration = getMembersOfDeclaration; + function isVariableLike(node) { + if (node) { + switch (node.kind) { + case 186 /* BindingElement */: + case 278 /* EnumMember */: + case 151 /* Parameter */: + case 275 /* PropertyAssignment */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 276 /* ShorthandPropertyAssignment */: + case 237 /* VariableDeclaration */: + return true; + } + } + return false; + } + ts.isVariableLike = isVariableLike; + function isVariableLikeOrAccessor(node) { + return isVariableLike(node) || ts.isAccessor(node); + } + ts.isVariableLikeOrAccessor = isVariableLikeOrAccessor; + function isVariableDeclarationInVariableStatement(node) { + return node.parent.kind === 238 /* VariableDeclarationList */ + && node.parent.parent.kind === 219 /* VariableStatement */; + } + ts.isVariableDeclarationInVariableStatement = isVariableDeclarationInVariableStatement; + function isValidESSymbolDeclaration(node) { + return ts.isVariableDeclaration(node) ? isVarConst(node) && ts.isIdentifier(node.name) && isVariableDeclarationInVariableStatement(node) : + ts.isPropertyDeclaration(node) ? hasReadonlyModifier(node) && hasStaticModifier(node) : + ts.isPropertySignature(node) && hasReadonlyModifier(node); + } + ts.isValidESSymbolDeclaration = isValidESSymbolDeclaration; + function introducesArgumentsExoticObject(node) { + switch (node.kind) { + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + return true; + } + return false; + } + ts.introducesArgumentsExoticObject = introducesArgumentsExoticObject; + function unwrapInnermostStatementOfLabel(node, beforeUnwrapLabelCallback) { + while (true) { + if (beforeUnwrapLabelCallback) { + beforeUnwrapLabelCallback(node); + } + if (node.statement.kind !== 233 /* LabeledStatement */) { + return node.statement; + } + node = node.statement; + } + } + ts.unwrapInnermostStatementOfLabel = unwrapInnermostStatementOfLabel; + function isFunctionBlock(node) { + return node && node.kind === 218 /* Block */ && ts.isFunctionLike(node.parent); + } + ts.isFunctionBlock = isFunctionBlock; + function isObjectLiteralMethod(node) { + return node && node.kind === 156 /* MethodDeclaration */ && node.parent.kind === 188 /* ObjectLiteralExpression */; + } + ts.isObjectLiteralMethod = isObjectLiteralMethod; + function isObjectLiteralOrClassExpressionMethod(node) { + return node.kind === 156 /* MethodDeclaration */ && + (node.parent.kind === 188 /* ObjectLiteralExpression */ || + node.parent.kind === 209 /* ClassExpression */); + } + ts.isObjectLiteralOrClassExpressionMethod = isObjectLiteralOrClassExpressionMethod; + function isIdentifierTypePredicate(predicate) { + return predicate && predicate.kind === 1 /* Identifier */; + } + ts.isIdentifierTypePredicate = isIdentifierTypePredicate; + function isThisTypePredicate(predicate) { + return predicate && predicate.kind === 0 /* This */; + } + ts.isThisTypePredicate = isThisTypePredicate; + function getPropertyAssignment(objectLiteral, key, key2) { + return objectLiteral.properties.filter(function (property) { + if (property.kind === 275 /* PropertyAssignment */) { + var propName = getTextOfPropertyName(property.name); + return key === propName || (!!key2 && key2 === propName); + } + return false; + }); + } + ts.getPropertyAssignment = getPropertyAssignment; + function getTsConfigObjectLiteralExpression(tsConfigSourceFile) { + if (tsConfigSourceFile && tsConfigSourceFile.statements.length) { + var expression = tsConfigSourceFile.statements[0].expression; + return ts.tryCast(expression, ts.isObjectLiteralExpression); + } + } + ts.getTsConfigObjectLiteralExpression = getTsConfigObjectLiteralExpression; + function getTsConfigPropArrayElementValue(tsConfigSourceFile, propKey, elementValue) { + return ts.firstDefined(getTsConfigPropArray(tsConfigSourceFile, propKey), function (property) { + return ts.isArrayLiteralExpression(property.initializer) ? + ts.find(property.initializer.elements, function (element) { return ts.isStringLiteral(element) && element.text === elementValue; }) : + undefined; + }); + } + ts.getTsConfigPropArrayElementValue = getTsConfigPropArrayElementValue; + function getTsConfigPropArray(tsConfigSourceFile, propKey) { + var jsonObjectLiteral = getTsConfigObjectLiteralExpression(tsConfigSourceFile); + return jsonObjectLiteral ? getPropertyAssignment(jsonObjectLiteral, propKey) : ts.emptyArray; + } + ts.getTsConfigPropArray = getTsConfigPropArray; + function getContainingFunction(node) { + return findAncestor(node.parent, ts.isFunctionLike); + } + ts.getContainingFunction = getContainingFunction; + function getContainingClass(node) { + return findAncestor(node.parent, ts.isClassLike); + } + ts.getContainingClass = getContainingClass; + function getThisContainer(node, includeArrowFunctions) { + ts.Debug.assert(node.kind !== 279 /* SourceFile */); + while (true) { + node = node.parent; + if (!node) { + return ts.Debug.fail(); // If we never pass in a SourceFile, this should be unreachable, since we'll stop when we reach that. + } + switch (node.kind) { + case 149 /* ComputedPropertyName */: + // If the grandparent node is an object literal (as opposed to a class), + // then the computed property is not a 'this' container. + // A computed property name in a class needs to be a this container + // so that we can error on it. + if (ts.isClassLike(node.parent.parent)) { + return node; + } + // If this is a computed property, then the parent should not + // make it a this container. The parent might be a property + // in an object literal, like a method or accessor. But in order for + // such a parent to be a this container, the reference must be in + // the *body* of the container. + node = node.parent; + break; + case 152 /* Decorator */: + // Decorators are always applied outside of the body of a class or method. + if (node.parent.kind === 151 /* Parameter */ && ts.isClassElement(node.parent.parent)) { + // If the decorator's parent is a Parameter, we resolve the this container from + // the grandparent class declaration. + node = node.parent.parent; + } + else if (ts.isClassElement(node.parent)) { + // If the decorator's parent is a class element, we resolve the 'this' container + // from the parent class declaration. + node = node.parent; + } + break; + case 197 /* ArrowFunction */: + if (!includeArrowFunctions) { + continue; + } + // falls through + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 244 /* ModuleDeclaration */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 162 /* IndexSignature */: + case 243 /* EnumDeclaration */: + case 279 /* SourceFile */: + return node; + } + } + } + ts.getThisContainer = getThisContainer; + function getNewTargetContainer(node) { + var container = getThisContainer(node, /*includeArrowFunctions*/ false); + if (container) { + switch (container.kind) { + case 157 /* Constructor */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + return container; + } + } + return undefined; + } + ts.getNewTargetContainer = getNewTargetContainer; + /** + * Given an super call/property node, returns the closest node where + * - a super call/property access is legal in the node and not legal in the parent node the node. + * i.e. super call is legal in constructor but not legal in the class body. + * - the container is an arrow function (so caller might need to call getSuperContainer again in case it needs to climb higher) + * - a super call/property is definitely illegal in the container (but might be legal in some subnode) + * i.e. super property access is illegal in function declaration but can be legal in the statement list + */ + function getSuperContainer(node, stopOnFunctions) { + while (true) { + node = node.parent; + if (!node) { + return node; + } + switch (node.kind) { + case 149 /* ComputedPropertyName */: + node = node.parent; + break; + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + if (!stopOnFunctions) { + continue; + } + // falls through + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + return node; + case 152 /* Decorator */: + // Decorators are always applied outside of the body of a class or method. + if (node.parent.kind === 151 /* Parameter */ && ts.isClassElement(node.parent.parent)) { + // If the decorator's parent is a Parameter, we resolve the this container from + // the grandparent class declaration. + node = node.parent.parent; + } + else if (ts.isClassElement(node.parent)) { + // If the decorator's parent is a class element, we resolve the 'this' container + // from the parent class declaration. + node = node.parent; + } + break; + } + } + } + ts.getSuperContainer = getSuperContainer; + function getImmediatelyInvokedFunctionExpression(func) { + if (func.kind === 196 /* FunctionExpression */ || func.kind === 197 /* ArrowFunction */) { + var prev = func; + var parent = func.parent; + while (parent.kind === 195 /* ParenthesizedExpression */) { + prev = parent; + parent = parent.parent; + } + if (parent.kind === 191 /* CallExpression */ && parent.expression === prev) { + return parent; + } + } + } + ts.getImmediatelyInvokedFunctionExpression = getImmediatelyInvokedFunctionExpression; + /** + * Determines whether a node is a property or element access expression for `super`. + */ + function isSuperProperty(node) { + var kind = node.kind; + return (kind === 189 /* PropertyAccessExpression */ || kind === 190 /* ElementAccessExpression */) + && node.expression.kind === 98 /* SuperKeyword */; + } + ts.isSuperProperty = isSuperProperty; + /** + * Determines whether a node is a property or element access expression for `this`. + */ + function isThisProperty(node) { + var kind = node.kind; + return (kind === 189 /* PropertyAccessExpression */ || kind === 190 /* ElementAccessExpression */) + && node.expression.kind === 100 /* ThisKeyword */; + } + ts.isThisProperty = isThisProperty; + function getEntityNameFromTypeNode(node) { + switch (node.kind) { + case 164 /* TypeReference */: + return node.typeName; + case 211 /* ExpressionWithTypeArguments */: + return isEntityNameExpression(node.expression) + ? node.expression + : undefined; + case 72 /* Identifier */: + case 148 /* QualifiedName */: + return node; + } + return undefined; + } + ts.getEntityNameFromTypeNode = getEntityNameFromTypeNode; + function getInvokedExpression(node) { + switch (node.kind) { + case 193 /* TaggedTemplateExpression */: + return node.tag; + case 262 /* JsxOpeningElement */: + case 261 /* JsxSelfClosingElement */: + return node.tagName; + default: + return node.expression; + } + } + ts.getInvokedExpression = getInvokedExpression; + function nodeCanBeDecorated(node, parent, grandparent) { + switch (node.kind) { + case 240 /* ClassDeclaration */: + // classes are valid targets + return true; + case 154 /* PropertyDeclaration */: + // property declarations are valid if their parent is a class declaration. + return parent.kind === 240 /* ClassDeclaration */; + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 156 /* MethodDeclaration */: + // if this method has a body and its parent is a class declaration, this is a valid target. + return node.body !== undefined + && parent.kind === 240 /* ClassDeclaration */; + case 151 /* Parameter */: + // if the parameter's parent has a body and its grandparent is a class declaration, this is a valid target; + return parent.body !== undefined + && (parent.kind === 157 /* Constructor */ + || parent.kind === 156 /* MethodDeclaration */ + || parent.kind === 159 /* SetAccessor */) + && grandparent.kind === 240 /* ClassDeclaration */; + } + return false; + } + ts.nodeCanBeDecorated = nodeCanBeDecorated; + function nodeIsDecorated(node, parent, grandparent) { + return node.decorators !== undefined + && nodeCanBeDecorated(node, parent, grandparent); // TODO: GH#18217 + } + ts.nodeIsDecorated = nodeIsDecorated; + function nodeOrChildIsDecorated(node, parent, grandparent) { + return nodeIsDecorated(node, parent, grandparent) || childIsDecorated(node, parent); // TODO: GH#18217 + } + ts.nodeOrChildIsDecorated = nodeOrChildIsDecorated; + function childIsDecorated(node, parent) { + switch (node.kind) { + case 240 /* ClassDeclaration */: + return ts.some(node.members, function (m) { return nodeOrChildIsDecorated(m, node, parent); }); // TODO: GH#18217 + case 156 /* MethodDeclaration */: + case 159 /* SetAccessor */: + return ts.some(node.parameters, function (p) { return nodeIsDecorated(p, node, parent); }); // TODO: GH#18217 + default: + return false; + } + } + ts.childIsDecorated = childIsDecorated; + function isJSXTagName(node) { + var parent = node.parent; + if (parent.kind === 262 /* JsxOpeningElement */ || + parent.kind === 261 /* JsxSelfClosingElement */ || + parent.kind === 263 /* JsxClosingElement */) { + return parent.tagName === node; + } + return false; + } + ts.isJSXTagName = isJSXTagName; + function isExpressionNode(node) { + switch (node.kind) { + case 98 /* SuperKeyword */: + case 96 /* NullKeyword */: + case 102 /* TrueKeyword */: + case 87 /* FalseKeyword */: + case 13 /* RegularExpressionLiteral */: + case 187 /* ArrayLiteralExpression */: + case 188 /* ObjectLiteralExpression */: + case 189 /* PropertyAccessExpression */: + case 190 /* ElementAccessExpression */: + case 191 /* CallExpression */: + case 192 /* NewExpression */: + case 193 /* TaggedTemplateExpression */: + case 212 /* AsExpression */: + case 194 /* TypeAssertionExpression */: + case 213 /* NonNullExpression */: + case 195 /* ParenthesizedExpression */: + case 196 /* FunctionExpression */: + case 209 /* ClassExpression */: + case 197 /* ArrowFunction */: + case 200 /* VoidExpression */: + case 198 /* DeleteExpression */: + case 199 /* TypeOfExpression */: + case 202 /* PrefixUnaryExpression */: + case 203 /* PostfixUnaryExpression */: + case 204 /* BinaryExpression */: + case 205 /* ConditionalExpression */: + case 208 /* SpreadElement */: + case 206 /* TemplateExpression */: + case 14 /* NoSubstitutionTemplateLiteral */: + case 210 /* OmittedExpression */: + case 260 /* JsxElement */: + case 261 /* JsxSelfClosingElement */: + case 264 /* JsxFragment */: + case 207 /* YieldExpression */: + case 201 /* AwaitExpression */: + case 214 /* MetaProperty */: + return true; + case 148 /* QualifiedName */: + while (node.parent.kind === 148 /* QualifiedName */) { + node = node.parent; + } + return node.parent.kind === 167 /* TypeQuery */ || isJSXTagName(node); + case 72 /* Identifier */: + if (node.parent.kind === 167 /* TypeQuery */ || isJSXTagName(node)) { + return true; + } + // falls through + case 8 /* NumericLiteral */: + case 9 /* BigIntLiteral */: + case 10 /* StringLiteral */: + case 100 /* ThisKeyword */: + return isInExpressionContext(node); + default: + return false; + } + } + ts.isExpressionNode = isExpressionNode; + function isInExpressionContext(node) { + var parent = node.parent; + switch (parent.kind) { + case 237 /* VariableDeclaration */: + case 151 /* Parameter */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 278 /* EnumMember */: + case 275 /* PropertyAssignment */: + case 186 /* BindingElement */: + return parent.initializer === node; + case 221 /* ExpressionStatement */: + case 222 /* IfStatement */: + case 223 /* DoStatement */: + case 224 /* WhileStatement */: + case 230 /* ReturnStatement */: + case 231 /* WithStatement */: + case 232 /* SwitchStatement */: + case 271 /* CaseClause */: + case 234 /* ThrowStatement */: + return parent.expression === node; + case 225 /* ForStatement */: + var forStatement = parent; + return (forStatement.initializer === node && forStatement.initializer.kind !== 238 /* VariableDeclarationList */) || + forStatement.condition === node || + forStatement.incrementor === node; + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + var forInStatement = parent; + return (forInStatement.initializer === node && forInStatement.initializer.kind !== 238 /* VariableDeclarationList */) || + forInStatement.expression === node; + case 194 /* TypeAssertionExpression */: + case 212 /* AsExpression */: + return node === parent.expression; + case 216 /* TemplateSpan */: + return node === parent.expression; + case 149 /* ComputedPropertyName */: + return node === parent.expression; + case 152 /* Decorator */: + case 270 /* JsxExpression */: + case 269 /* JsxSpreadAttribute */: + case 277 /* SpreadAssignment */: + return true; + case 211 /* ExpressionWithTypeArguments */: + return parent.expression === node && isExpressionWithTypeArgumentsInClassExtendsClause(parent); + case 276 /* ShorthandPropertyAssignment */: + return parent.objectAssignmentInitializer === node; + default: + return isExpressionNode(parent); + } + } + ts.isInExpressionContext = isInExpressionContext; + function isExternalModuleImportEqualsDeclaration(node) { + return node.kind === 248 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 259 /* ExternalModuleReference */; + } + ts.isExternalModuleImportEqualsDeclaration = isExternalModuleImportEqualsDeclaration; + function getExternalModuleImportEqualsDeclarationExpression(node) { + ts.Debug.assert(isExternalModuleImportEqualsDeclaration(node)); + return node.moduleReference.expression; + } + ts.getExternalModuleImportEqualsDeclarationExpression = getExternalModuleImportEqualsDeclarationExpression; + function isInternalModuleImportEqualsDeclaration(node) { + return node.kind === 248 /* ImportEqualsDeclaration */ && node.moduleReference.kind !== 259 /* ExternalModuleReference */; + } + ts.isInternalModuleImportEqualsDeclaration = isInternalModuleImportEqualsDeclaration; + function isSourceFileJS(file) { + return isInJSFile(file); + } + ts.isSourceFileJS = isSourceFileJS; + function isSourceFileNotJS(file) { + return !isInJSFile(file); + } + ts.isSourceFileNotJS = isSourceFileNotJS; + function isInJSFile(node) { + return !!node && !!(node.flags & 65536 /* JavaScriptFile */); + } + ts.isInJSFile = isInJSFile; + function isInJsonFile(node) { + return !!node && !!(node.flags & 16777216 /* JsonFile */); + } + ts.isInJsonFile = isInJsonFile; + function isInJSDoc(node) { + return !!node && !!(node.flags & 2097152 /* JSDoc */); + } + ts.isInJSDoc = isInJSDoc; + function isJSDocIndexSignature(node) { + return ts.isTypeReferenceNode(node) && + ts.isIdentifier(node.typeName) && + node.typeName.escapedText === "Object" && + node.typeArguments && node.typeArguments.length === 2 && + (node.typeArguments[0].kind === 138 /* StringKeyword */ || node.typeArguments[0].kind === 135 /* NumberKeyword */); + } + ts.isJSDocIndexSignature = isJSDocIndexSignature; + function isRequireCall(callExpression, checkArgumentIsStringLiteralLike) { + if (callExpression.kind !== 191 /* CallExpression */) { + return false; + } + var _a = callExpression, expression = _a.expression, args = _a.arguments; + if (expression.kind !== 72 /* Identifier */ || expression.escapedText !== "require") { + return false; + } + if (args.length !== 1) { + return false; + } + var arg = args[0]; + return !checkArgumentIsStringLiteralLike || ts.isStringLiteralLike(arg); + } + ts.isRequireCall = isRequireCall; + function isSingleOrDoubleQuote(charCode) { + return charCode === 39 /* singleQuote */ || charCode === 34 /* doubleQuote */; + } + ts.isSingleOrDoubleQuote = isSingleOrDoubleQuote; + function isStringDoubleQuoted(str, sourceFile) { + return getSourceTextOfNodeFromSourceFile(sourceFile, str).charCodeAt(0) === 34 /* doubleQuote */; + } + ts.isStringDoubleQuoted = isStringDoubleQuoted; + function getDeclarationOfExpando(node) { + if (!node.parent) { + return undefined; + } + var name; + var decl; + if (ts.isVariableDeclaration(node.parent) && node.parent.initializer === node) { + if (!isInJSFile(node) && !isVarConst(node.parent)) { + return undefined; + } + name = node.parent.name; + decl = node.parent; + } + else if (ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 59 /* EqualsToken */ && node.parent.right === node) { + name = node.parent.left; + decl = name; + } + else if (ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 55 /* BarBarToken */) { + if (ts.isVariableDeclaration(node.parent.parent) && node.parent.parent.initializer === node.parent) { + name = node.parent.parent.name; + decl = node.parent.parent; + } + else if (ts.isBinaryExpression(node.parent.parent) && node.parent.parent.operatorToken.kind === 59 /* EqualsToken */ && node.parent.parent.right === node.parent) { + name = node.parent.parent.left; + decl = name; + } + if (!name || !isEntityNameExpression(name) || !isSameEntityName(name, node.parent.left)) { + return undefined; + } + } + if (!name || !getExpandoInitializer(node, isPrototypeAccess(name))) { + return undefined; + } + return decl; + } + ts.getDeclarationOfExpando = getDeclarationOfExpando; + function isAssignmentDeclaration(decl) { + return ts.isBinaryExpression(decl) || ts.isPropertyAccessExpression(decl) || ts.isIdentifier(decl) || ts.isCallExpression(decl); + } + ts.isAssignmentDeclaration = isAssignmentDeclaration; + /** Get the initializer, taking into account defaulted Javascript initializers */ + function getEffectiveInitializer(node) { + if (isInJSFile(node) && node.initializer && + ts.isBinaryExpression(node.initializer) && node.initializer.operatorToken.kind === 55 /* BarBarToken */ && + node.name && isEntityNameExpression(node.name) && isSameEntityName(node.name, node.initializer.left)) { + return node.initializer.right; + } + return node.initializer; + } + ts.getEffectiveInitializer = getEffectiveInitializer; + /** Get the declaration initializer when it is container-like (See getExpandoInitializer). */ + function getDeclaredExpandoInitializer(node) { + var init = getEffectiveInitializer(node); + return init && getExpandoInitializer(init, isPrototypeAccess(node.name)); + } + ts.getDeclaredExpandoInitializer = getDeclaredExpandoInitializer; + function hasExpandoValueProperty(node, isPrototypeAssignment) { + return ts.forEach(node.properties, function (p) { return ts.isPropertyAssignment(p) && ts.isIdentifier(p.name) && p.name.escapedText === "value" && p.initializer && getExpandoInitializer(p.initializer, isPrototypeAssignment); }); + } + /** + * Get the assignment 'initializer' -- the righthand side-- when the initializer is container-like (See getExpandoInitializer). + * We treat the right hand side of assignments with container-like initalizers as declarations. + */ + function getAssignedExpandoInitializer(node) { + if (node && node.parent && ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 59 /* EqualsToken */) { + var isPrototypeAssignment = isPrototypeAccess(node.parent.left); + return getExpandoInitializer(node.parent.right, isPrototypeAssignment) || + getDefaultedExpandoInitializer(node.parent.left, node.parent.right, isPrototypeAssignment); + } + if (node && ts.isCallExpression(node) && isBindableObjectDefinePropertyCall(node)) { + var result = hasExpandoValueProperty(node.arguments[2], node.arguments[1].text === "prototype"); + if (result) { + return result; + } + } + } + ts.getAssignedExpandoInitializer = getAssignedExpandoInitializer; + /** + * Recognized expando initializers are: + * 1. (function() {})() -- IIFEs + * 2. function() { } -- Function expressions + * 3. class { } -- Class expressions + * 4. {} -- Empty object literals + * 5. { ... } -- Non-empty object literals, when used to initialize a prototype, like `C.prototype = { m() { } }` + * + * This function returns the provided initializer, or undefined if it is not valid. + */ + function getExpandoInitializer(initializer, isPrototypeAssignment) { + if (ts.isCallExpression(initializer)) { + var e = skipParentheses(initializer.expression); + return e.kind === 196 /* FunctionExpression */ || e.kind === 197 /* ArrowFunction */ ? initializer : undefined; + } + if (initializer.kind === 196 /* FunctionExpression */ || + initializer.kind === 209 /* ClassExpression */ || + initializer.kind === 197 /* ArrowFunction */) { + return initializer; + } + if (ts.isObjectLiteralExpression(initializer) && (initializer.properties.length === 0 || isPrototypeAssignment)) { + return initializer; + } + } + ts.getExpandoInitializer = getExpandoInitializer; + /** + * A defaulted expando initializer matches the pattern + * `Lhs = Lhs || ExpandoInitializer` + * or `var Lhs = Lhs || ExpandoInitializer` + * + * The second Lhs is required to be the same as the first except that it may be prefixed with + * 'window.', 'global.' or 'self.' The second Lhs is otherwise ignored by the binder and checker. + */ + function getDefaultedExpandoInitializer(name, initializer, isPrototypeAssignment) { + var e = ts.isBinaryExpression(initializer) && initializer.operatorToken.kind === 55 /* BarBarToken */ && getExpandoInitializer(initializer.right, isPrototypeAssignment); + if (e && isSameEntityName(name, initializer.left)) { + return e; + } + } + function isDefaultedExpandoInitializer(node) { + var name = ts.isVariableDeclaration(node.parent) ? node.parent.name : + ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 59 /* EqualsToken */ ? node.parent.left : + undefined; + return name && getExpandoInitializer(node.right, isPrototypeAccess(name)) && isEntityNameExpression(name) && isSameEntityName(name, node.left); + } + ts.isDefaultedExpandoInitializer = isDefaultedExpandoInitializer; + /** Given an expando initializer, return its declaration name, or the left-hand side of the assignment if it's part of an assignment declaration. */ + function getNameOfExpando(node) { + if (ts.isBinaryExpression(node.parent)) { + var parent = (node.parent.operatorToken.kind === 55 /* BarBarToken */ && ts.isBinaryExpression(node.parent.parent)) ? node.parent.parent : node.parent; + if (parent.operatorToken.kind === 59 /* EqualsToken */ && ts.isIdentifier(parent.left)) { + return parent.left; + } + } + else if (ts.isVariableDeclaration(node.parent)) { + return node.parent.name; + } + } + ts.getNameOfExpando = getNameOfExpando; + /** + * Is the 'declared' name the same as the one in the initializer? + * @return true for identical entity names, as well as ones where the initializer is prefixed with + * 'window', 'self' or 'global'. For example: + * + * var my = my || {} + * var min = window.min || {} + * my.app = self.my.app || class { } + */ + function isSameEntityName(name, initializer) { + if (ts.isIdentifier(name) && ts.isIdentifier(initializer)) { + return name.escapedText === initializer.escapedText; + } + if (ts.isIdentifier(name) && ts.isPropertyAccessExpression(initializer)) { + return (initializer.expression.kind === 100 /* ThisKeyword */ || + ts.isIdentifier(initializer.expression) && + (initializer.expression.escapedText === "window" || + initializer.expression.escapedText === "self" || + initializer.expression.escapedText === "global")) && + isSameEntityName(name, initializer.name); + } + if (ts.isPropertyAccessExpression(name) && ts.isPropertyAccessExpression(initializer)) { + return name.name.escapedText === initializer.name.escapedText && isSameEntityName(name.expression, initializer.expression); + } + return false; + } + function getRightMostAssignedExpression(node) { + while (isAssignmentExpression(node, /*excludeCompoundAssignments*/ true)) { + node = node.right; + } + return node; + } + ts.getRightMostAssignedExpression = getRightMostAssignedExpression; + function isExportsIdentifier(node) { + return ts.isIdentifier(node) && node.escapedText === "exports"; + } + ts.isExportsIdentifier = isExportsIdentifier; + function isModuleExportsPropertyAccessExpression(node) { + return ts.isPropertyAccessExpression(node) && ts.isIdentifier(node.expression) && node.expression.escapedText === "module" && node.name.escapedText === "exports"; + } + ts.isModuleExportsPropertyAccessExpression = isModuleExportsPropertyAccessExpression; + /// Given a BinaryExpression, returns SpecialPropertyAssignmentKind for the various kinds of property + /// assignments we treat as special in the binder + function getAssignmentDeclarationKind(expr) { + var special = getAssignmentDeclarationKindWorker(expr); + return special === 5 /* Property */ || isInJSFile(expr) ? special : 0 /* None */; + } + ts.getAssignmentDeclarationKind = getAssignmentDeclarationKind; + function isBindableObjectDefinePropertyCall(expr) { + return ts.length(expr.arguments) === 3 && + ts.isPropertyAccessExpression(expr.expression) && + ts.isIdentifier(expr.expression.expression) && + ts.idText(expr.expression.expression) === "Object" && + ts.idText(expr.expression.name) === "defineProperty" && + isStringOrNumericLiteralLike(expr.arguments[1]) && + isEntityNameExpression(expr.arguments[0]); + } + ts.isBindableObjectDefinePropertyCall = isBindableObjectDefinePropertyCall; + function getAssignmentDeclarationKindWorker(expr) { + if (ts.isCallExpression(expr)) { + if (!isBindableObjectDefinePropertyCall(expr)) { + return 0 /* None */; + } + var entityName = expr.arguments[0]; + if (isExportsIdentifier(entityName) || isModuleExportsPropertyAccessExpression(entityName)) { + return 8 /* ObjectDefinePropertyExports */; + } + if (ts.isPropertyAccessExpression(entityName) && entityName.name.escapedText === "prototype" && isEntityNameExpression(entityName.expression)) { + return 9 /* ObjectDefinePrototypeProperty */; + } + return 7 /* ObjectDefinePropertyValue */; + } + if (expr.operatorToken.kind !== 59 /* EqualsToken */ || + !ts.isPropertyAccessExpression(expr.left)) { + return 0 /* None */; + } + var lhs = expr.left; + if (isEntityNameExpression(lhs.expression) && lhs.name.escapedText === "prototype" && ts.isObjectLiteralExpression(getInitializerOfBinaryExpression(expr))) { + // F.prototype = { ... } + return 6 /* Prototype */; + } + return getAssignmentDeclarationPropertyAccessKind(lhs); + } + function getAssignmentDeclarationPropertyAccessKind(lhs) { + if (lhs.expression.kind === 100 /* ThisKeyword */) { + return 4 /* ThisProperty */; + } + else if (isModuleExportsPropertyAccessExpression(lhs)) { + // module.exports = expr + return 2 /* ModuleExports */; + } + else if (isEntityNameExpression(lhs.expression)) { + if (isPrototypeAccess(lhs.expression)) { + // F.G....prototype.x = expr + return 3 /* PrototypeProperty */; + } + var nextToLast = lhs; + while (ts.isPropertyAccessExpression(nextToLast.expression)) { + nextToLast = nextToLast.expression; + } + ts.Debug.assert(ts.isIdentifier(nextToLast.expression)); + var id = nextToLast.expression; + if (id.escapedText === "exports" || + id.escapedText === "module" && nextToLast.name.escapedText === "exports") { + // exports.name = expr OR module.exports.name = expr + return 1 /* ExportsProperty */; + } + // F.G...x = expr + return 5 /* Property */; + } + return 0 /* None */; + } + ts.getAssignmentDeclarationPropertyAccessKind = getAssignmentDeclarationPropertyAccessKind; + function getInitializerOfBinaryExpression(expr) { + while (ts.isBinaryExpression(expr.right)) { + expr = expr.right; + } + return expr.right; + } + ts.getInitializerOfBinaryExpression = getInitializerOfBinaryExpression; + function isPrototypePropertyAssignment(node) { + return ts.isBinaryExpression(node) && getAssignmentDeclarationKind(node) === 3 /* PrototypeProperty */; + } + ts.isPrototypePropertyAssignment = isPrototypePropertyAssignment; + function isSpecialPropertyDeclaration(expr) { + return isInJSFile(expr) && + expr.parent && expr.parent.kind === 221 /* ExpressionStatement */ && + !!ts.getJSDocTypeTag(expr.parent); + } + ts.isSpecialPropertyDeclaration = isSpecialPropertyDeclaration; + function isFunctionSymbol(symbol) { + if (!symbol || !symbol.valueDeclaration) { + return false; + } + var decl = symbol.valueDeclaration; + return decl.kind === 239 /* FunctionDeclaration */ || ts.isVariableDeclaration(decl) && decl.initializer && ts.isFunctionLike(decl.initializer); + } + ts.isFunctionSymbol = isFunctionSymbol; + function importFromModuleSpecifier(node) { + return tryGetImportFromModuleSpecifier(node) || ts.Debug.fail(ts.Debug.showSyntaxKind(node.parent)); + } + ts.importFromModuleSpecifier = importFromModuleSpecifier; + function tryGetImportFromModuleSpecifier(node) { + switch (node.parent.kind) { + case 249 /* ImportDeclaration */: + case 255 /* ExportDeclaration */: + return node.parent; + case 259 /* ExternalModuleReference */: + return node.parent.parent; + case 191 /* CallExpression */: + return isImportCall(node.parent) || isRequireCall(node.parent, /*checkArg*/ false) ? node.parent : undefined; + case 182 /* LiteralType */: + ts.Debug.assert(ts.isStringLiteral(node)); + return ts.tryCast(node.parent.parent, ts.isImportTypeNode); + default: + return undefined; + } + } + ts.tryGetImportFromModuleSpecifier = tryGetImportFromModuleSpecifier; + function getExternalModuleName(node) { + switch (node.kind) { + case 249 /* ImportDeclaration */: + case 255 /* ExportDeclaration */: + return node.moduleSpecifier; + case 248 /* ImportEqualsDeclaration */: + return node.moduleReference.kind === 259 /* ExternalModuleReference */ ? node.moduleReference.expression : undefined; + case 183 /* ImportType */: + return isLiteralImportTypeNode(node) ? node.argument.literal : undefined; + default: + return ts.Debug.assertNever(node); + } + } + ts.getExternalModuleName = getExternalModuleName; + function getNamespaceDeclarationNode(node) { + switch (node.kind) { + case 249 /* ImportDeclaration */: + return node.importClause && ts.tryCast(node.importClause.namedBindings, ts.isNamespaceImport); + case 248 /* ImportEqualsDeclaration */: + return node; + case 255 /* ExportDeclaration */: + return undefined; + default: + return ts.Debug.assertNever(node); + } + } + ts.getNamespaceDeclarationNode = getNamespaceDeclarationNode; + function isDefaultImport(node) { + return node.kind === 249 /* ImportDeclaration */ && !!node.importClause && !!node.importClause.name; + } + ts.isDefaultImport = isDefaultImport; + function hasQuestionToken(node) { + if (node) { + switch (node.kind) { + case 151 /* Parameter */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 276 /* ShorthandPropertyAssignment */: + case 275 /* PropertyAssignment */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + return node.questionToken !== undefined; + } + } + return false; + } + ts.hasQuestionToken = hasQuestionToken; + function isJSDocConstructSignature(node) { + var param = ts.isJSDocFunctionType(node) ? ts.firstOrUndefined(node.parameters) : undefined; + var name = ts.tryCast(param && param.name, ts.isIdentifier); + return !!name && name.escapedText === "new"; + } + ts.isJSDocConstructSignature = isJSDocConstructSignature; + function isJSDocTypeAlias(node) { + return node.kind === 304 /* JSDocTypedefTag */ || node.kind === 297 /* JSDocCallbackTag */; + } + ts.isJSDocTypeAlias = isJSDocTypeAlias; + function isTypeAlias(node) { + return isJSDocTypeAlias(node) || ts.isTypeAliasDeclaration(node); + } + ts.isTypeAlias = isTypeAlias; + function getSourceOfAssignment(node) { + return ts.isExpressionStatement(node) && + node.expression && ts.isBinaryExpression(node.expression) && + node.expression.operatorToken.kind === 59 /* EqualsToken */ + ? node.expression.right + : undefined; + } + function getSourceOfDefaultedAssignment(node) { + return ts.isExpressionStatement(node) && + ts.isBinaryExpression(node.expression) && + getAssignmentDeclarationKind(node.expression) !== 0 /* None */ && + ts.isBinaryExpression(node.expression.right) && + node.expression.right.operatorToken.kind === 55 /* BarBarToken */ + ? node.expression.right.right + : undefined; + } + function getSingleInitializerOfVariableStatementOrPropertyDeclaration(node) { + switch (node.kind) { + case 219 /* VariableStatement */: + var v = getSingleVariableOfVariableStatement(node); + return v && v.initializer; + case 154 /* PropertyDeclaration */: + return node.initializer; + case 275 /* PropertyAssignment */: + return node.initializer; + } + } + function getSingleVariableOfVariableStatement(node) { + return ts.isVariableStatement(node) ? ts.firstOrUndefined(node.declarationList.declarations) : undefined; + } + function getNestedModuleDeclaration(node) { + return ts.isModuleDeclaration(node) && + node.body && + node.body.kind === 244 /* ModuleDeclaration */ + ? node.body + : undefined; + } + function getJSDocCommentsAndTags(hostNode) { + var result; + // Pull parameter comments from declaring function as well + if (isVariableLike(hostNode) && ts.hasInitializer(hostNode) && ts.hasJSDocNodes(hostNode.initializer)) { + result = ts.addRange(result, hostNode.initializer.jsDoc); + } + var node = hostNode; + while (node && node.parent) { + if (ts.hasJSDocNodes(node)) { + result = ts.addRange(result, node.jsDoc); + } + if (node.kind === 151 /* Parameter */) { + result = ts.addRange(result, ts.getJSDocParameterTags(node)); + break; + } + if (node.kind === 150 /* TypeParameter */) { + result = ts.addRange(result, ts.getJSDocTypeParameterTags(node)); + break; + } + node = getNextJSDocCommentLocation(node); + } + return result || ts.emptyArray; + } + ts.getJSDocCommentsAndTags = getJSDocCommentsAndTags; + function getNextJSDocCommentLocation(node) { + var parent = node.parent; + if (parent.kind === 275 /* PropertyAssignment */ || + parent.kind === 154 /* PropertyDeclaration */ || + parent.kind === 221 /* ExpressionStatement */ && node.kind === 189 /* PropertyAccessExpression */ || + getNestedModuleDeclaration(parent) || + ts.isBinaryExpression(node) && node.operatorToken.kind === 59 /* EqualsToken */) { + return parent; + } + // Try to recognize this pattern when node is initializer of variable declaration and JSDoc comments are on containing variable statement. + // /** + // * @param {number} name + // * @returns {number} + // */ + // var x = function(name) { return name.length; } + else if (parent.parent && + (getSingleVariableOfVariableStatement(parent.parent) === node || + ts.isBinaryExpression(parent) && parent.operatorToken.kind === 59 /* EqualsToken */)) { + return parent.parent; + } + else if (parent.parent && parent.parent.parent && + (getSingleVariableOfVariableStatement(parent.parent.parent) || + getSingleInitializerOfVariableStatementOrPropertyDeclaration(parent.parent.parent) === node || + getSourceOfDefaultedAssignment(parent.parent.parent))) { + return parent.parent.parent; + } + } + /** Does the opposite of `getJSDocParameterTags`: given a JSDoc parameter, finds the parameter corresponding to it. */ + function getParameterSymbolFromJSDoc(node) { + if (node.symbol) { + return node.symbol; + } + if (!ts.isIdentifier(node.name)) { + return undefined; + } + var name = node.name.escapedText; + var decl = getHostSignatureFromJSDoc(node); + if (!decl) { + return undefined; + } + var parameter = ts.find(decl.parameters, function (p) { return p.name.kind === 72 /* Identifier */ && p.name.escapedText === name; }); + return parameter && parameter.symbol; + } + ts.getParameterSymbolFromJSDoc = getParameterSymbolFromJSDoc; + function getHostSignatureFromJSDoc(node) { + return getHostSignatureFromJSDocHost(getJSDocHost(node)); + } + ts.getHostSignatureFromJSDoc = getHostSignatureFromJSDoc; + function getHostSignatureFromJSDocHost(host) { + var decl = getSourceOfDefaultedAssignment(host) || + getSourceOfAssignment(host) || + getSingleInitializerOfVariableStatementOrPropertyDeclaration(host) || + getSingleVariableOfVariableStatement(host) || + getNestedModuleDeclaration(host) || + host; + return decl && ts.isFunctionLike(decl) ? decl : undefined; + } + ts.getHostSignatureFromJSDocHost = getHostSignatureFromJSDocHost; + function getJSDocHost(node) { + return ts.Debug.assertDefined(findAncestor(node.parent, ts.isJSDoc)).parent; + } + ts.getJSDocHost = getJSDocHost; + function getTypeParameterFromJsDoc(node) { + var name = node.name.escapedText; + var typeParameters = node.parent.parent.parent.typeParameters; + return ts.find(typeParameters, function (p) { return p.name.escapedText === name; }); + } + ts.getTypeParameterFromJsDoc = getTypeParameterFromJsDoc; + function hasRestParameter(s) { + var last = ts.lastOrUndefined(s.parameters); + return !!last && isRestParameter(last); + } + ts.hasRestParameter = hasRestParameter; + function isRestParameter(node) { + var type = ts.isJSDocParameterTag(node) ? (node.typeExpression && node.typeExpression.type) : node.type; + return node.dotDotDotToken !== undefined || !!type && type.kind === 290 /* JSDocVariadicType */; + } + ts.isRestParameter = isRestParameter; + var AssignmentKind; + (function (AssignmentKind) { + AssignmentKind[AssignmentKind["None"] = 0] = "None"; + AssignmentKind[AssignmentKind["Definite"] = 1] = "Definite"; + AssignmentKind[AssignmentKind["Compound"] = 2] = "Compound"; + })(AssignmentKind = ts.AssignmentKind || (ts.AssignmentKind = {})); + function getAssignmentTargetKind(node) { + var parent = node.parent; + while (true) { + switch (parent.kind) { + case 204 /* BinaryExpression */: + var binaryOperator = parent.operatorToken.kind; + return isAssignmentOperator(binaryOperator) && parent.left === node ? + binaryOperator === 59 /* EqualsToken */ ? 1 /* Definite */ : 2 /* Compound */ : + 0 /* None */; + case 202 /* PrefixUnaryExpression */: + case 203 /* PostfixUnaryExpression */: + var unaryOperator = parent.operator; + return unaryOperator === 44 /* PlusPlusToken */ || unaryOperator === 45 /* MinusMinusToken */ ? 2 /* Compound */ : 0 /* None */; + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + return parent.initializer === node ? 1 /* Definite */ : 0 /* None */; + case 195 /* ParenthesizedExpression */: + case 187 /* ArrayLiteralExpression */: + case 208 /* SpreadElement */: + case 213 /* NonNullExpression */: + node = parent; + break; + case 276 /* ShorthandPropertyAssignment */: + if (parent.name !== node) { + return 0 /* None */; + } + node = parent.parent; + break; + case 275 /* PropertyAssignment */: + if (parent.name === node) { + return 0 /* None */; + } + node = parent.parent; + break; + default: + return 0 /* None */; + } + parent = node.parent; + } + } + ts.getAssignmentTargetKind = getAssignmentTargetKind; + // A node is an assignment target if it is on the left hand side of an '=' token, if it is parented by a property + // assignment in an object literal that is an assignment target, or if it is parented by an array literal that is + // an assignment target. Examples include 'a = xxx', '{ p: a } = xxx', '[{ a }] = xxx'. + // (Note that `p` is not a target in the above examples, only `a`.) + function isAssignmentTarget(node) { + return getAssignmentTargetKind(node) !== 0 /* None */; + } + ts.isAssignmentTarget = isAssignmentTarget; + /** + * Indicates whether a node could contain a `var` VariableDeclarationList that contributes to + * the same `var` declaration scope as the node's parent. + */ + function isNodeWithPossibleHoistedDeclaration(node) { + switch (node.kind) { + case 218 /* Block */: + case 219 /* VariableStatement */: + case 231 /* WithStatement */: + case 222 /* IfStatement */: + case 232 /* SwitchStatement */: + case 246 /* CaseBlock */: + case 271 /* CaseClause */: + case 272 /* DefaultClause */: + case 233 /* LabeledStatement */: + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + case 223 /* DoStatement */: + case 224 /* WhileStatement */: + case 235 /* TryStatement */: + case 274 /* CatchClause */: + return true; + } + return false; + } + ts.isNodeWithPossibleHoistedDeclaration = isNodeWithPossibleHoistedDeclaration; + function isValueSignatureDeclaration(node) { + return ts.isFunctionExpression(node) || ts.isArrowFunction(node) || ts.isMethodOrAccessor(node) || ts.isFunctionDeclaration(node) || ts.isConstructorDeclaration(node); + } + ts.isValueSignatureDeclaration = isValueSignatureDeclaration; + function walkUp(node, kind) { + while (node && node.kind === kind) { + node = node.parent; + } + return node; + } + function walkUpParenthesizedTypes(node) { + return walkUp(node, 177 /* ParenthesizedType */); + } + ts.walkUpParenthesizedTypes = walkUpParenthesizedTypes; + function walkUpParenthesizedExpressions(node) { + return walkUp(node, 195 /* ParenthesizedExpression */); + } + ts.walkUpParenthesizedExpressions = walkUpParenthesizedExpressions; + function skipParentheses(node) { + while (node.kind === 195 /* ParenthesizedExpression */) { + node = node.expression; + } + return node; + } + ts.skipParentheses = skipParentheses; + function skipParenthesesUp(node) { + while (node.kind === 195 /* ParenthesizedExpression */) { + node = node.parent; + } + return node; + } + // a node is delete target iff. it is PropertyAccessExpression/ElementAccessExpression with parentheses skipped + function isDeleteTarget(node) { + if (node.kind !== 189 /* PropertyAccessExpression */ && node.kind !== 190 /* ElementAccessExpression */) { + return false; + } + node = walkUpParenthesizedExpressions(node.parent); + return node && node.kind === 198 /* DeleteExpression */; + } + ts.isDeleteTarget = isDeleteTarget; + function isNodeDescendantOf(node, ancestor) { + while (node) { + if (node === ancestor) + return true; + node = node.parent; + } + return false; + } + ts.isNodeDescendantOf = isNodeDescendantOf; + // True if `name` is the name of a declaration node + function isDeclarationName(name) { + return !ts.isSourceFile(name) && !ts.isBindingPattern(name) && ts.isDeclaration(name.parent) && name.parent.name === name; + } + ts.isDeclarationName = isDeclarationName; + // See GH#16030 + function getDeclarationFromName(name) { + var parent = name.parent; + switch (name.kind) { + case 10 /* StringLiteral */: + case 8 /* NumericLiteral */: + if (ts.isComputedPropertyName(parent)) + return parent.parent; + // falls through + case 72 /* Identifier */: + if (ts.isDeclaration(parent)) { + return parent.name === name ? parent : undefined; + } + else if (ts.isQualifiedName(parent)) { + var tag = parent.parent; + return ts.isJSDocParameterTag(tag) && tag.name === parent ? tag : undefined; + } + else { + var binExp = parent.parent; + return ts.isBinaryExpression(binExp) && + getAssignmentDeclarationKind(binExp) !== 0 /* None */ && + (binExp.left.symbol || binExp.symbol) && + ts.getNameOfDeclaration(binExp) === name + ? binExp + : undefined; + } + default: + return undefined; + } + } + ts.getDeclarationFromName = getDeclarationFromName; + function isLiteralComputedPropertyDeclarationName(node) { + return (node.kind === 10 /* StringLiteral */ || node.kind === 8 /* NumericLiteral */) && + node.parent.kind === 149 /* ComputedPropertyName */ && + ts.isDeclaration(node.parent.parent); + } + ts.isLiteralComputedPropertyDeclarationName = isLiteralComputedPropertyDeclarationName; + // Return true if the given identifier is classified as an IdentifierName + function isIdentifierName(node) { + var parent = node.parent; + switch (parent.kind) { + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 278 /* EnumMember */: + case 275 /* PropertyAssignment */: + case 189 /* PropertyAccessExpression */: + // Name in member declaration or property name in property access + return parent.name === node; + case 148 /* QualifiedName */: + // Name on right hand side of dot in a type query or type reference + if (parent.right === node) { + while (parent.kind === 148 /* QualifiedName */) { + parent = parent.parent; + } + return parent.kind === 167 /* TypeQuery */ || parent.kind === 164 /* TypeReference */; + } + return false; + case 186 /* BindingElement */: + case 253 /* ImportSpecifier */: + // Property name in binding element or import specifier + return parent.propertyName === node; + case 257 /* ExportSpecifier */: + case 267 /* JsxAttribute */: + // Any name in an export specifier or JSX Attribute + return true; + } + return false; + } + ts.isIdentifierName = isIdentifierName; + // An alias symbol is created by one of the following declarations: + // import = ... + // import from ... + // import * as from ... + // import { x as } from ... + // export { x as } from ... + // export = + // export default + // module.exports = + function isAliasSymbolDeclaration(node) { + return node.kind === 248 /* ImportEqualsDeclaration */ || + node.kind === 247 /* NamespaceExportDeclaration */ || + node.kind === 250 /* ImportClause */ && !!node.name || + node.kind === 251 /* NamespaceImport */ || + node.kind === 253 /* ImportSpecifier */ || + node.kind === 257 /* ExportSpecifier */ || + node.kind === 254 /* ExportAssignment */ && exportAssignmentIsAlias(node) || + ts.isBinaryExpression(node) && getAssignmentDeclarationKind(node) === 2 /* ModuleExports */ && exportAssignmentIsAlias(node); + } + ts.isAliasSymbolDeclaration = isAliasSymbolDeclaration; + function exportAssignmentIsAlias(node) { + var e = ts.isExportAssignment(node) ? node.expression : node.right; + return isEntityNameExpression(e) || ts.isClassExpression(e); + } + ts.exportAssignmentIsAlias = exportAssignmentIsAlias; + function getEffectiveBaseTypeNode(node) { + if (isInJSFile(node)) { + // Prefer an @augments tag because it may have type parameters. + var tag = ts.getJSDocAugmentsTag(node); + if (tag) { + return tag.class; + } + } + return getClassExtendsHeritageElement(node); + } + ts.getEffectiveBaseTypeNode = getEffectiveBaseTypeNode; + function getClassExtendsHeritageElement(node) { + var heritageClause = getHeritageClause(node.heritageClauses, 86 /* ExtendsKeyword */); + return heritageClause && heritageClause.types.length > 0 ? heritageClause.types[0] : undefined; + } + ts.getClassExtendsHeritageElement = getClassExtendsHeritageElement; + function getClassImplementsHeritageClauseElements(node) { + var heritageClause = getHeritageClause(node.heritageClauses, 109 /* ImplementsKeyword */); + return heritageClause ? heritageClause.types : undefined; + } + ts.getClassImplementsHeritageClauseElements = getClassImplementsHeritageClauseElements; + /** Returns the node in an `extends` or `implements` clause of a class or interface. */ + function getAllSuperTypeNodes(node) { + return ts.isInterfaceDeclaration(node) ? getInterfaceBaseTypeNodes(node) || ts.emptyArray + : ts.isClassLike(node) ? ts.concatenate(ts.singleElementArray(getEffectiveBaseTypeNode(node)), getClassImplementsHeritageClauseElements(node)) || ts.emptyArray + : ts.emptyArray; + } + ts.getAllSuperTypeNodes = getAllSuperTypeNodes; + function getInterfaceBaseTypeNodes(node) { + var heritageClause = getHeritageClause(node.heritageClauses, 86 /* ExtendsKeyword */); + return heritageClause ? heritageClause.types : undefined; + } + ts.getInterfaceBaseTypeNodes = getInterfaceBaseTypeNodes; + function getHeritageClause(clauses, kind) { + if (clauses) { + for (var _i = 0, clauses_1 = clauses; _i < clauses_1.length; _i++) { + var clause = clauses_1[_i]; + if (clause.token === kind) { + return clause; + } + } + } + return undefined; + } + ts.getHeritageClause = getHeritageClause; + function tryResolveScriptReference(host, sourceFile, reference) { + if (!host.getCompilerOptions().noResolve) { + var referenceFileName = ts.isRootedDiskPath(reference.fileName) ? reference.fileName : ts.combinePaths(ts.getDirectoryPath(sourceFile.fileName), reference.fileName); + return host.getSourceFile(referenceFileName); + } + } + ts.tryResolveScriptReference = tryResolveScriptReference; + function getAncestor(node, kind) { + while (node) { + if (node.kind === kind) { + return node; + } + node = node.parent; + } + return undefined; + } + ts.getAncestor = getAncestor; + function isKeyword(token) { + return 73 /* FirstKeyword */ <= token && token <= 147 /* LastKeyword */; + } + ts.isKeyword = isKeyword; + function isContextualKeyword(token) { + return 118 /* FirstContextualKeyword */ <= token && token <= 147 /* LastContextualKeyword */; + } + ts.isContextualKeyword = isContextualKeyword; + function isNonContextualKeyword(token) { + return isKeyword(token) && !isContextualKeyword(token); + } + ts.isNonContextualKeyword = isNonContextualKeyword; + function isStringANonContextualKeyword(name) { + var token = ts.stringToToken(name); + return token !== undefined && isNonContextualKeyword(token); + } + ts.isStringANonContextualKeyword = isStringANonContextualKeyword; + function isIdentifierANonContextualKeyword(_a) { + var originalKeywordKind = _a.originalKeywordKind; + return !!originalKeywordKind && !isContextualKeyword(originalKeywordKind); + } + ts.isIdentifierANonContextualKeyword = isIdentifierANonContextualKeyword; + function isTrivia(token) { + return 2 /* FirstTriviaToken */ <= token && token <= 7 /* LastTriviaToken */; + } + ts.isTrivia = isTrivia; + var FunctionFlags; + (function (FunctionFlags) { + FunctionFlags[FunctionFlags["Normal"] = 0] = "Normal"; + FunctionFlags[FunctionFlags["Generator"] = 1] = "Generator"; + FunctionFlags[FunctionFlags["Async"] = 2] = "Async"; + FunctionFlags[FunctionFlags["Invalid"] = 4] = "Invalid"; + FunctionFlags[FunctionFlags["AsyncGenerator"] = 3] = "AsyncGenerator"; + })(FunctionFlags = ts.FunctionFlags || (ts.FunctionFlags = {})); + function getFunctionFlags(node) { + if (!node) { + return 4 /* Invalid */; + } + var flags = 0 /* Normal */; + switch (node.kind) { + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 156 /* MethodDeclaration */: + if (node.asteriskToken) { + flags |= 1 /* Generator */; + } + // falls through + case 197 /* ArrowFunction */: + if (hasModifier(node, 256 /* Async */)) { + flags |= 2 /* Async */; + } + break; + } + if (!node.body) { + flags |= 4 /* Invalid */; + } + return flags; + } + ts.getFunctionFlags = getFunctionFlags; + function isAsyncFunction(node) { + switch (node.kind) { + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 156 /* MethodDeclaration */: + return node.body !== undefined + && node.asteriskToken === undefined + && hasModifier(node, 256 /* Async */); + } + return false; + } + ts.isAsyncFunction = isAsyncFunction; + function isStringOrNumericLiteralLike(node) { + return ts.isStringLiteralLike(node) || ts.isNumericLiteral(node); + } + ts.isStringOrNumericLiteralLike = isStringOrNumericLiteralLike; + /** + * A declaration has a dynamic name if both of the following are true: + * 1. The declaration has a computed property name + * 2. The computed name is *not* expressed as Symbol., where name + * is a property of the Symbol constructor that denotes a built in + * Symbol. + */ + function hasDynamicName(declaration) { + var name = ts.getNameOfDeclaration(declaration); + return !!name && isDynamicName(name); + } + ts.hasDynamicName = hasDynamicName; + function isDynamicName(name) { + return name.kind === 149 /* ComputedPropertyName */ && + !isStringOrNumericLiteralLike(name.expression) && + !isWellKnownSymbolSyntactically(name.expression); + } + ts.isDynamicName = isDynamicName; + /** + * Checks if the expression is of the form: + * Symbol.name + * where Symbol is literally the word "Symbol", and name is any identifierName + */ + function isWellKnownSymbolSyntactically(node) { + return ts.isPropertyAccessExpression(node) && isESSymbolIdentifier(node.expression); + } + ts.isWellKnownSymbolSyntactically = isWellKnownSymbolSyntactically; + function getPropertyNameForPropertyNameNode(name) { + switch (name.kind) { + case 72 /* Identifier */: + return name.escapedText; + case 10 /* StringLiteral */: + case 8 /* NumericLiteral */: + return ts.escapeLeadingUnderscores(name.text); + case 149 /* ComputedPropertyName */: + var nameExpression = name.expression; + if (isWellKnownSymbolSyntactically(nameExpression)) { + return getPropertyNameForKnownSymbolName(ts.idText(nameExpression.name)); + } + else if (isStringOrNumericLiteralLike(nameExpression)) { + return ts.escapeLeadingUnderscores(nameExpression.text); + } + return undefined; + default: + return ts.Debug.assertNever(name); + } + } + ts.getPropertyNameForPropertyNameNode = getPropertyNameForPropertyNameNode; + function isPropertyNameLiteral(node) { + switch (node.kind) { + case 72 /* Identifier */: + case 10 /* StringLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: + case 8 /* NumericLiteral */: + return true; + default: + return false; + } + } + ts.isPropertyNameLiteral = isPropertyNameLiteral; + function getTextOfIdentifierOrLiteral(node) { + return node.kind === 72 /* Identifier */ ? ts.idText(node) : node.text; + } + ts.getTextOfIdentifierOrLiteral = getTextOfIdentifierOrLiteral; + function getEscapedTextOfIdentifierOrLiteral(node) { + return node.kind === 72 /* Identifier */ ? node.escapedText : ts.escapeLeadingUnderscores(node.text); + } + ts.getEscapedTextOfIdentifierOrLiteral = getEscapedTextOfIdentifierOrLiteral; + function getPropertyNameForKnownSymbolName(symbolName) { + return "__@" + symbolName; + } + ts.getPropertyNameForKnownSymbolName = getPropertyNameForKnownSymbolName; + function isKnownSymbol(symbol) { + return ts.startsWith(symbol.escapedName, "__@"); + } + ts.isKnownSymbol = isKnownSymbol; + /** + * Includes the word "Symbol" with unicode escapes + */ + function isESSymbolIdentifier(node) { + return node.kind === 72 /* Identifier */ && node.escapedText === "Symbol"; + } + ts.isESSymbolIdentifier = isESSymbolIdentifier; + function isPushOrUnshiftIdentifier(node) { + return node.escapedText === "push" || node.escapedText === "unshift"; + } + ts.isPushOrUnshiftIdentifier = isPushOrUnshiftIdentifier; + function isParameterDeclaration(node) { + var root = getRootDeclaration(node); + return root.kind === 151 /* Parameter */; + } + ts.isParameterDeclaration = isParameterDeclaration; + function getRootDeclaration(node) { + while (node.kind === 186 /* BindingElement */) { + node = node.parent.parent; + } + return node; + } + ts.getRootDeclaration = getRootDeclaration; + function nodeStartsNewLexicalEnvironment(node) { + var kind = node.kind; + return kind === 157 /* Constructor */ + || kind === 196 /* FunctionExpression */ + || kind === 239 /* FunctionDeclaration */ + || kind === 197 /* ArrowFunction */ + || kind === 156 /* MethodDeclaration */ + || kind === 158 /* GetAccessor */ + || kind === 159 /* SetAccessor */ + || kind === 244 /* ModuleDeclaration */ + || kind === 279 /* SourceFile */; + } + ts.nodeStartsNewLexicalEnvironment = nodeStartsNewLexicalEnvironment; + function nodeIsSynthesized(range) { + return ts.positionIsSynthesized(range.pos) + || ts.positionIsSynthesized(range.end); + } + ts.nodeIsSynthesized = nodeIsSynthesized; + function getOriginalSourceFile(sourceFile) { + return ts.getParseTreeNode(sourceFile, ts.isSourceFile) || sourceFile; + } + ts.getOriginalSourceFile = getOriginalSourceFile; + var Associativity; + (function (Associativity) { + Associativity[Associativity["Left"] = 0] = "Left"; + Associativity[Associativity["Right"] = 1] = "Right"; + })(Associativity = ts.Associativity || (ts.Associativity = {})); + function getExpressionAssociativity(expression) { + var operator = getOperator(expression); + var hasArguments = expression.kind === 192 /* NewExpression */ && expression.arguments !== undefined; + return getOperatorAssociativity(expression.kind, operator, hasArguments); + } + ts.getExpressionAssociativity = getExpressionAssociativity; + function getOperatorAssociativity(kind, operator, hasArguments) { + switch (kind) { + case 192 /* NewExpression */: + return hasArguments ? 0 /* Left */ : 1 /* Right */; + case 202 /* PrefixUnaryExpression */: + case 199 /* TypeOfExpression */: + case 200 /* VoidExpression */: + case 198 /* DeleteExpression */: + case 201 /* AwaitExpression */: + case 205 /* ConditionalExpression */: + case 207 /* YieldExpression */: + return 1 /* Right */; + case 204 /* BinaryExpression */: + switch (operator) { + case 41 /* AsteriskAsteriskToken */: + case 59 /* EqualsToken */: + case 60 /* PlusEqualsToken */: + case 61 /* MinusEqualsToken */: + case 63 /* AsteriskAsteriskEqualsToken */: + case 62 /* AsteriskEqualsToken */: + case 64 /* SlashEqualsToken */: + case 65 /* PercentEqualsToken */: + case 66 /* LessThanLessThanEqualsToken */: + case 67 /* GreaterThanGreaterThanEqualsToken */: + case 68 /* GreaterThanGreaterThanGreaterThanEqualsToken */: + case 69 /* AmpersandEqualsToken */: + case 71 /* CaretEqualsToken */: + case 70 /* BarEqualsToken */: + return 1 /* Right */; + } + } + return 0 /* Left */; + } + ts.getOperatorAssociativity = getOperatorAssociativity; + function getExpressionPrecedence(expression) { + var operator = getOperator(expression); + var hasArguments = expression.kind === 192 /* NewExpression */ && expression.arguments !== undefined; + return getOperatorPrecedence(expression.kind, operator, hasArguments); + } + ts.getExpressionPrecedence = getExpressionPrecedence; + function getOperator(expression) { + if (expression.kind === 204 /* BinaryExpression */) { + return expression.operatorToken.kind; + } + else if (expression.kind === 202 /* PrefixUnaryExpression */ || expression.kind === 203 /* PostfixUnaryExpression */) { + return expression.operator; + } + else { + return expression.kind; + } + } + ts.getOperator = getOperator; + function getOperatorPrecedence(nodeKind, operatorKind, hasArguments) { + switch (nodeKind) { + case 309 /* CommaListExpression */: + return 0; + case 208 /* SpreadElement */: + return 1; + case 207 /* YieldExpression */: + return 2; + case 205 /* ConditionalExpression */: + return 4; + case 204 /* BinaryExpression */: + switch (operatorKind) { + case 27 /* CommaToken */: + return 0; + case 59 /* EqualsToken */: + case 60 /* PlusEqualsToken */: + case 61 /* MinusEqualsToken */: + case 63 /* AsteriskAsteriskEqualsToken */: + case 62 /* AsteriskEqualsToken */: + case 64 /* SlashEqualsToken */: + case 65 /* PercentEqualsToken */: + case 66 /* LessThanLessThanEqualsToken */: + case 67 /* GreaterThanGreaterThanEqualsToken */: + case 68 /* GreaterThanGreaterThanGreaterThanEqualsToken */: + case 69 /* AmpersandEqualsToken */: + case 71 /* CaretEqualsToken */: + case 70 /* BarEqualsToken */: + return 3; + default: + return getBinaryOperatorPrecedence(operatorKind); + } + case 202 /* PrefixUnaryExpression */: + case 199 /* TypeOfExpression */: + case 200 /* VoidExpression */: + case 198 /* DeleteExpression */: + case 201 /* AwaitExpression */: + return 16; + case 203 /* PostfixUnaryExpression */: + return 17; + case 191 /* CallExpression */: + return 18; + case 192 /* NewExpression */: + return hasArguments ? 19 : 18; + case 193 /* TaggedTemplateExpression */: + case 189 /* PropertyAccessExpression */: + case 190 /* ElementAccessExpression */: + return 19; + case 100 /* ThisKeyword */: + case 98 /* SuperKeyword */: + case 72 /* Identifier */: + case 96 /* NullKeyword */: + case 102 /* TrueKeyword */: + case 87 /* FalseKeyword */: + case 8 /* NumericLiteral */: + case 9 /* BigIntLiteral */: + case 10 /* StringLiteral */: + case 187 /* ArrayLiteralExpression */: + case 188 /* ObjectLiteralExpression */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 209 /* ClassExpression */: + case 260 /* JsxElement */: + case 261 /* JsxSelfClosingElement */: + case 264 /* JsxFragment */: + case 13 /* RegularExpressionLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: + case 206 /* TemplateExpression */: + case 195 /* ParenthesizedExpression */: + case 210 /* OmittedExpression */: + return 20; + default: + return -1; + } + } + ts.getOperatorPrecedence = getOperatorPrecedence; + function getBinaryOperatorPrecedence(kind) { + switch (kind) { + case 55 /* BarBarToken */: + return 5; + case 54 /* AmpersandAmpersandToken */: + return 6; + case 50 /* BarToken */: + return 7; + case 51 /* CaretToken */: + return 8; + case 49 /* AmpersandToken */: + return 9; + case 33 /* EqualsEqualsToken */: + case 34 /* ExclamationEqualsToken */: + case 35 /* EqualsEqualsEqualsToken */: + case 36 /* ExclamationEqualsEqualsToken */: + return 10; + case 28 /* LessThanToken */: + case 30 /* GreaterThanToken */: + case 31 /* LessThanEqualsToken */: + case 32 /* GreaterThanEqualsToken */: + case 94 /* InstanceOfKeyword */: + case 93 /* InKeyword */: + case 119 /* AsKeyword */: + return 11; + case 46 /* LessThanLessThanToken */: + case 47 /* GreaterThanGreaterThanToken */: + case 48 /* GreaterThanGreaterThanGreaterThanToken */: + return 12; + case 38 /* PlusToken */: + case 39 /* MinusToken */: + return 13; + case 40 /* AsteriskToken */: + case 42 /* SlashToken */: + case 43 /* PercentToken */: + return 14; + case 41 /* AsteriskAsteriskToken */: + return 15; + } + // -1 is lower than all other precedences. Returning it will cause binary expression + // parsing to stop. + return -1; + } + ts.getBinaryOperatorPrecedence = getBinaryOperatorPrecedence; + function createDiagnosticCollection() { + var nonFileDiagnostics = []; // See GH#19873 + var filesWithDiagnostics = []; + var fileDiagnostics = ts.createMap(); + var hasReadNonFileDiagnostics = false; + return { + add: add, + lookup: lookup, + getGlobalDiagnostics: getGlobalDiagnostics, + getDiagnostics: getDiagnostics, + reattachFileDiagnostics: reattachFileDiagnostics + }; + function reattachFileDiagnostics(newFile) { + ts.forEach(fileDiagnostics.get(newFile.fileName), function (diagnostic) { return diagnostic.file = newFile; }); + } + function lookup(diagnostic) { + var diagnostics; + if (diagnostic.file) { + diagnostics = fileDiagnostics.get(diagnostic.file.fileName); + } + else { + diagnostics = nonFileDiagnostics; + } + if (!diagnostics) { + return undefined; + } + var result = ts.binarySearch(diagnostics, diagnostic, ts.identity, ts.compareDiagnosticsSkipRelatedInformation); + if (result >= 0) { + return diagnostics[result]; + } + return undefined; + } + function add(diagnostic) { + var diagnostics; + if (diagnostic.file) { + diagnostics = fileDiagnostics.get(diagnostic.file.fileName); + if (!diagnostics) { + diagnostics = []; // See GH#19873 + fileDiagnostics.set(diagnostic.file.fileName, diagnostics); + ts.insertSorted(filesWithDiagnostics, diagnostic.file.fileName, ts.compareStringsCaseSensitive); + } + } + else { + // If we've already read the non-file diagnostics, do not modify the existing array. + if (hasReadNonFileDiagnostics) { + hasReadNonFileDiagnostics = false; + nonFileDiagnostics = nonFileDiagnostics.slice(); + } + diagnostics = nonFileDiagnostics; + } + ts.insertSorted(diagnostics, diagnostic, ts.compareDiagnostics); + } + function getGlobalDiagnostics() { + hasReadNonFileDiagnostics = true; + return nonFileDiagnostics; + } + function getDiagnostics(fileName) { + if (fileName) { + return fileDiagnostics.get(fileName) || []; + } + var fileDiags = ts.flatMapToMutable(filesWithDiagnostics, function (f) { return fileDiagnostics.get(f); }); + if (!nonFileDiagnostics.length) { + return fileDiags; + } + fileDiags.unshift.apply(fileDiags, nonFileDiagnostics); + return fileDiags; + } + } + ts.createDiagnosticCollection = createDiagnosticCollection; + // This consists of the first 19 unprintable ASCII characters, canonical escapes, lineSeparator, + // paragraphSeparator, and nextLine. The latter three are just desirable to suppress new lines in + // the language service. These characters should be escaped when printing, and if any characters are added, + // the map below must be updated. Note that this regexp *does not* include the 'delete' character. + // There is no reason for this other than that JSON.stringify does not handle it either. + var doubleQuoteEscapedCharsRegExp = /[\\\"\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g; + var singleQuoteEscapedCharsRegExp = /[\\\'\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g; + var backtickQuoteEscapedCharsRegExp = /[\\\`\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g; + var escapedCharsMap = ts.createMapFromTemplate({ + "\t": "\\t", + "\v": "\\v", + "\f": "\\f", + "\b": "\\b", + "\r": "\\r", + "\n": "\\n", + "\\": "\\\\", + "\"": "\\\"", + "\'": "\\\'", + "\`": "\\\`", + "\u2028": "\\u2028", + "\u2029": "\\u2029", + "\u0085": "\\u0085" // nextLine + }); + /** + * Based heavily on the abstract 'Quote'/'QuoteJSONString' operation from ECMA-262 (24.3.2.2), + * but augmented for a few select characters (e.g. lineSeparator, paragraphSeparator, nextLine) + * Note that this doesn't actually wrap the input in double quotes. + */ + function escapeString(s, quoteChar) { + var escapedCharsRegExp = quoteChar === 96 /* backtick */ ? backtickQuoteEscapedCharsRegExp : + quoteChar === 39 /* singleQuote */ ? singleQuoteEscapedCharsRegExp : + doubleQuoteEscapedCharsRegExp; + return s.replace(escapedCharsRegExp, getReplacement); + } + ts.escapeString = escapeString; + function getReplacement(c, offset, input) { + if (c.charCodeAt(0) === 0 /* nullCharacter */) { + var lookAhead = input.charCodeAt(offset + c.length); + if (lookAhead >= 48 /* _0 */ && lookAhead <= 57 /* _9 */) { + // If the null character is followed by digits, print as a hex escape to prevent the result from parsing as an octal (which is forbidden in strict mode) + return "\\x00"; + } + // Otherwise, keep printing a literal \0 for the null character + return "\\0"; + } + return escapedCharsMap.get(c) || get16BitUnicodeEscapeSequence(c.charCodeAt(0)); + } + function isIntrinsicJsxName(name) { + var ch = name.charCodeAt(0); + return (ch >= 97 /* a */ && ch <= 122 /* z */) || ts.stringContains(name, "-"); + } + ts.isIntrinsicJsxName = isIntrinsicJsxName; + function get16BitUnicodeEscapeSequence(charCode) { + var hexCharCode = charCode.toString(16).toUpperCase(); + var paddedHexCode = ("0000" + hexCharCode).slice(-4); + return "\\u" + paddedHexCode; + } + var nonAsciiCharacters = /[^\u0000-\u007F]/g; + function escapeNonAsciiString(s, quoteChar) { + s = escapeString(s, quoteChar); + // Replace non-ASCII characters with '\uNNNN' escapes if any exist. + // Otherwise just return the original string. + return nonAsciiCharacters.test(s) ? + s.replace(nonAsciiCharacters, function (c) { return get16BitUnicodeEscapeSequence(c.charCodeAt(0)); }) : + s; + } + ts.escapeNonAsciiString = escapeNonAsciiString; + var indentStrings = ["", " "]; + function getIndentString(level) { + if (indentStrings[level] === undefined) { + indentStrings[level] = getIndentString(level - 1) + indentStrings[1]; + } + return indentStrings[level]; + } + ts.getIndentString = getIndentString; + function getIndentSize() { + return indentStrings[1].length; + } + ts.getIndentSize = getIndentSize; + function createTextWriter(newLine) { + var output; + var indent; + var lineStart; + var lineCount; + var linePos; + function updateLineCountAndPosFor(s) { + var lineStartsOfS = ts.computeLineStarts(s); + if (lineStartsOfS.length > 1) { + lineCount = lineCount + lineStartsOfS.length - 1; + linePos = output.length - s.length + ts.last(lineStartsOfS); + lineStart = (linePos - output.length) === 0; + } + else { + lineStart = false; + } + } + function write(s) { + if (s && s.length) { + if (lineStart) { + s = getIndentString(indent) + s; + lineStart = false; + } + output += s; + updateLineCountAndPosFor(s); + } + } + function reset() { + output = ""; + indent = 0; + lineStart = true; + lineCount = 0; + linePos = 0; + } + function rawWrite(s) { + if (s !== undefined) { + output += s; + updateLineCountAndPosFor(s); + } + } + function writeLiteral(s) { + if (s && s.length) { + write(s); + } + } + function writeLine() { + if (!lineStart) { + output += newLine; + lineCount++; + linePos = output.length; + lineStart = true; + } + } + reset(); + return { + write: write, + rawWrite: rawWrite, + writeLiteral: writeLiteral, + writeLine: writeLine, + increaseIndent: function () { indent++; }, + decreaseIndent: function () { indent--; }, + getIndent: function () { return indent; }, + getTextPos: function () { return output.length; }, + getLine: function () { return lineCount; }, + getColumn: function () { return lineStart ? indent * getIndentSize() : output.length - linePos; }, + getText: function () { return output; }, + isAtStartOfLine: function () { return lineStart; }, + clear: reset, + reportInaccessibleThisError: ts.noop, + reportPrivateInBaseOfClassExpression: ts.noop, + reportInaccessibleUniqueSymbolError: ts.noop, + trackSymbol: ts.noop, + writeKeyword: write, + writeOperator: write, + writeParameter: write, + writeProperty: write, + writePunctuation: write, + writeSpace: write, + writeStringLiteral: write, + writeSymbol: function (s, _) { return write(s); }, + writeTrailingSemicolon: write, + writeComment: write + }; + } + ts.createTextWriter = createTextWriter; + function getTrailingSemicolonOmittingWriter(writer) { + var pendingTrailingSemicolon = false; + function commitPendingTrailingSemicolon() { + if (pendingTrailingSemicolon) { + writer.writeTrailingSemicolon(";"); + pendingTrailingSemicolon = false; + } + } + return __assign({}, writer, { writeTrailingSemicolon: function () { + pendingTrailingSemicolon = true; + }, + writeLiteral: function (s) { + commitPendingTrailingSemicolon(); + writer.writeLiteral(s); + }, + writeStringLiteral: function (s) { + commitPendingTrailingSemicolon(); + writer.writeStringLiteral(s); + }, + writeSymbol: function (s, sym) { + commitPendingTrailingSemicolon(); + writer.writeSymbol(s, sym); + }, + writePunctuation: function (s) { + commitPendingTrailingSemicolon(); + writer.writePunctuation(s); + }, + writeKeyword: function (s) { + commitPendingTrailingSemicolon(); + writer.writeKeyword(s); + }, + writeOperator: function (s) { + commitPendingTrailingSemicolon(); + writer.writeOperator(s); + }, + writeParameter: function (s) { + commitPendingTrailingSemicolon(); + writer.writeParameter(s); + }, + writeSpace: function (s) { + commitPendingTrailingSemicolon(); + writer.writeSpace(s); + }, + writeProperty: function (s) { + commitPendingTrailingSemicolon(); + writer.writeProperty(s); + }, + writeComment: function (s) { + commitPendingTrailingSemicolon(); + writer.writeComment(s); + }, + writeLine: function () { + commitPendingTrailingSemicolon(); + writer.writeLine(); + }, + increaseIndent: function () { + commitPendingTrailingSemicolon(); + writer.increaseIndent(); + }, + decreaseIndent: function () { + commitPendingTrailingSemicolon(); + writer.decreaseIndent(); + } }); + } + ts.getTrailingSemicolonOmittingWriter = getTrailingSemicolonOmittingWriter; + function getResolvedExternalModuleName(host, file, referenceFile) { + return file.moduleName || getExternalModuleNameFromPath(host, file.fileName, referenceFile && referenceFile.fileName); + } + ts.getResolvedExternalModuleName = getResolvedExternalModuleName; + function getExternalModuleNameFromDeclaration(host, resolver, declaration) { + var file = resolver.getExternalModuleFileFromDeclaration(declaration); + if (!file || file.isDeclarationFile) { + return undefined; + } + return getResolvedExternalModuleName(host, file); + } + ts.getExternalModuleNameFromDeclaration = getExternalModuleNameFromDeclaration; + /** + * Resolves a local path to a path which is absolute to the base of the emit + */ + function getExternalModuleNameFromPath(host, fileName, referencePath) { + var getCanonicalFileName = function (f) { return host.getCanonicalFileName(f); }; + var dir = toPath(referencePath ? ts.getDirectoryPath(referencePath) : host.getCommonSourceDirectory(), host.getCurrentDirectory(), getCanonicalFileName); + var filePath = ts.getNormalizedAbsolutePath(fileName, host.getCurrentDirectory()); + var relativePath = ts.getRelativePathToDirectoryOrUrl(dir, filePath, dir, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); + var extensionless = ts.removeFileExtension(relativePath); + return referencePath ? ts.ensurePathIsNonModuleName(extensionless) : extensionless; + } + ts.getExternalModuleNameFromPath = getExternalModuleNameFromPath; + function getOwnEmitOutputFilePath(fileName, host, extension) { + var compilerOptions = host.getCompilerOptions(); + var emitOutputFilePathWithoutExtension; + if (compilerOptions.outDir) { + emitOutputFilePathWithoutExtension = ts.removeFileExtension(getSourceFilePathInNewDir(fileName, host, compilerOptions.outDir)); + } + else { + emitOutputFilePathWithoutExtension = ts.removeFileExtension(fileName); + } + return emitOutputFilePathWithoutExtension + extension; + } + ts.getOwnEmitOutputFilePath = getOwnEmitOutputFilePath; + function getDeclarationEmitOutputFilePath(fileName, host) { + return getDeclarationEmitOutputFilePathWorker(fileName, host.getCompilerOptions(), host.getCurrentDirectory(), host.getCommonSourceDirectory(), function (f) { return host.getCanonicalFileName(f); }); + } + ts.getDeclarationEmitOutputFilePath = getDeclarationEmitOutputFilePath; + function getDeclarationEmitOutputFilePathWorker(fileName, options, currentDirectory, commonSourceDirectory, getCanonicalFileName) { + var outputDir = options.declarationDir || options.outDir; // Prefer declaration folder if specified + var path = outputDir + ? getSourceFilePathInNewDirWorker(fileName, outputDir, currentDirectory, commonSourceDirectory, getCanonicalFileName) + : fileName; + return ts.removeFileExtension(path) + ".d.ts" /* Dts */; + } + ts.getDeclarationEmitOutputFilePathWorker = getDeclarationEmitOutputFilePathWorker; + /** + * Gets the source files that are expected to have an emit output. + * + * Originally part of `forEachExpectedEmitFile`, this functionality was extracted to support + * transformations. + * + * @param host An EmitHost. + * @param targetSourceFile An optional target source file to emit. + */ + function getSourceFilesToEmit(host, targetSourceFile) { + var options = host.getCompilerOptions(); + var isSourceFileFromExternalLibrary = function (file) { return host.isSourceFileFromExternalLibrary(file); }; + if (options.outFile || options.out) { + var moduleKind = ts.getEmitModuleKind(options); + var moduleEmitEnabled_1 = options.emitDeclarationOnly || moduleKind === ts.ModuleKind.AMD || moduleKind === ts.ModuleKind.System; + // Can emit only sources that are not declaration file and are either non module code or module with --module or --target es6 specified + return ts.filter(host.getSourceFiles(), function (sourceFile) { + return (moduleEmitEnabled_1 || !ts.isExternalModule(sourceFile)) && sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary); + }); + } + else { + var sourceFiles = targetSourceFile === undefined ? host.getSourceFiles() : [targetSourceFile]; + return ts.filter(sourceFiles, function (sourceFile) { return sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary); }); + } + } + ts.getSourceFilesToEmit = getSourceFilesToEmit; + /** Don't call this for `--outFile`, just for `--outDir` or plain emit. `--outFile` needs additional checks. */ + function sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary) { + return !(options.noEmitForJsFiles && isSourceFileJS(sourceFile)) && !sourceFile.isDeclarationFile && !isSourceFileFromExternalLibrary(sourceFile); + } + ts.sourceFileMayBeEmitted = sourceFileMayBeEmitted; + function getSourceFilePathInNewDir(fileName, host, newDirPath) { + return getSourceFilePathInNewDirWorker(fileName, newDirPath, host.getCurrentDirectory(), host.getCommonSourceDirectory(), function (f) { return host.getCanonicalFileName(f); }); + } + ts.getSourceFilePathInNewDir = getSourceFilePathInNewDir; + function getSourceFilePathInNewDirWorker(fileName, newDirPath, currentDirectory, commonSourceDirectory, getCanonicalFileName) { + var sourceFilePath = ts.getNormalizedAbsolutePath(fileName, currentDirectory); + var isSourceFileInCommonSourceDirectory = getCanonicalFileName(sourceFilePath).indexOf(getCanonicalFileName(commonSourceDirectory)) === 0; + sourceFilePath = isSourceFileInCommonSourceDirectory ? sourceFilePath.substring(commonSourceDirectory.length) : sourceFilePath; + return ts.combinePaths(newDirPath, sourceFilePath); + } + ts.getSourceFilePathInNewDirWorker = getSourceFilePathInNewDirWorker; + function writeFile(host, diagnostics, fileName, data, writeByteOrderMark, sourceFiles) { + host.writeFile(fileName, data, writeByteOrderMark, function (hostErrorMessage) { + diagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Could_not_write_file_0_Colon_1, fileName, hostErrorMessage)); + }, sourceFiles); + } + ts.writeFile = writeFile; + function getLineOfLocalPosition(currentSourceFile, pos) { + return ts.getLineAndCharacterOfPosition(currentSourceFile, pos).line; + } + ts.getLineOfLocalPosition = getLineOfLocalPosition; + function getLineOfLocalPositionFromLineMap(lineMap, pos) { + return ts.computeLineAndCharacterOfPosition(lineMap, pos).line; + } + ts.getLineOfLocalPositionFromLineMap = getLineOfLocalPositionFromLineMap; + function getFirstConstructorWithBody(node) { + return ts.find(node.members, function (member) { return ts.isConstructorDeclaration(member) && nodeIsPresent(member.body); }); + } + ts.getFirstConstructorWithBody = getFirstConstructorWithBody; + function getSetAccessorValueParameter(accessor) { + if (accessor && accessor.parameters.length > 0) { + var hasThis = accessor.parameters.length === 2 && parameterIsThisKeyword(accessor.parameters[0]); + return accessor.parameters[hasThis ? 1 : 0]; + } + } + /** Get the type annotation for the value parameter. */ + function getSetAccessorTypeAnnotationNode(accessor) { + var parameter = getSetAccessorValueParameter(accessor); + return parameter && parameter.type; + } + ts.getSetAccessorTypeAnnotationNode = getSetAccessorTypeAnnotationNode; + function getThisParameter(signature) { + // callback tags do not currently support this parameters + if (signature.parameters.length && !ts.isJSDocSignature(signature)) { + var thisParameter = signature.parameters[0]; + if (parameterIsThisKeyword(thisParameter)) { + return thisParameter; + } + } + } + ts.getThisParameter = getThisParameter; + function parameterIsThisKeyword(parameter) { + return isThisIdentifier(parameter.name); + } + ts.parameterIsThisKeyword = parameterIsThisKeyword; + function isThisIdentifier(node) { + return !!node && node.kind === 72 /* Identifier */ && identifierIsThisKeyword(node); + } + ts.isThisIdentifier = isThisIdentifier; + function identifierIsThisKeyword(id) { + return id.originalKeywordKind === 100 /* ThisKeyword */; + } + ts.identifierIsThisKeyword = identifierIsThisKeyword; + function getAllAccessorDeclarations(declarations, accessor) { + // TODO: GH#18217 + var firstAccessor; + var secondAccessor; + var getAccessor; + var setAccessor; + if (hasDynamicName(accessor)) { + firstAccessor = accessor; + if (accessor.kind === 158 /* GetAccessor */) { + getAccessor = accessor; + } + else if (accessor.kind === 159 /* SetAccessor */) { + setAccessor = accessor; + } + else { + ts.Debug.fail("Accessor has wrong kind"); + } + } + else { + ts.forEach(declarations, function (member) { + if (ts.isAccessor(member) + && hasModifier(member, 32 /* Static */) === hasModifier(accessor, 32 /* Static */)) { + var memberName = getPropertyNameForPropertyNameNode(member.name); + var accessorName = getPropertyNameForPropertyNameNode(accessor.name); + if (memberName === accessorName) { + if (!firstAccessor) { + firstAccessor = member; + } + else if (!secondAccessor) { + secondAccessor = member; + } + if (member.kind === 158 /* GetAccessor */ && !getAccessor) { + getAccessor = member; + } + if (member.kind === 159 /* SetAccessor */ && !setAccessor) { + setAccessor = member; + } + } + } + }); + } + return { + firstAccessor: firstAccessor, + secondAccessor: secondAccessor, + getAccessor: getAccessor, + setAccessor: setAccessor + }; + } + ts.getAllAccessorDeclarations = getAllAccessorDeclarations; + /** + * Gets the effective type annotation of a variable, parameter, or property. If the node was + * parsed in a JavaScript file, gets the type annotation from JSDoc. + */ + function getEffectiveTypeAnnotationNode(node) { + var type = node.type; + if (type || !isInJSFile(node)) + return type; + return ts.isJSDocPropertyLikeTag(node) ? node.typeExpression && node.typeExpression.type : ts.getJSDocType(node); + } + ts.getEffectiveTypeAnnotationNode = getEffectiveTypeAnnotationNode; + function getTypeAnnotationNode(node) { + return node.type; + } + ts.getTypeAnnotationNode = getTypeAnnotationNode; + /** + * Gets the effective return type annotation of a signature. If the node was parsed in a + * JavaScript file, gets the return type annotation from JSDoc. + */ + function getEffectiveReturnTypeNode(node) { + return ts.isJSDocSignature(node) ? + node.type && node.type.typeExpression && node.type.typeExpression.type : + node.type || (isInJSFile(node) ? ts.getJSDocReturnType(node) : undefined); + } + ts.getEffectiveReturnTypeNode = getEffectiveReturnTypeNode; + function getJSDocTypeParameterDeclarations(node) { + return ts.flatMap(ts.getJSDocTags(node), function (tag) { return isNonTypeAliasTemplate(tag) ? tag.typeParameters : undefined; }); + } + ts.getJSDocTypeParameterDeclarations = getJSDocTypeParameterDeclarations; + /** template tags are only available when a typedef isn't already using them */ + function isNonTypeAliasTemplate(tag) { + return ts.isJSDocTemplateTag(tag) && !(tag.parent.kind === 291 /* JSDocComment */ && tag.parent.tags.some(isJSDocTypeAlias)); + } + /** + * Gets the effective type annotation of the value parameter of a set accessor. If the node + * was parsed in a JavaScript file, gets the type annotation from JSDoc. + */ + function getEffectiveSetAccessorTypeAnnotationNode(node) { + var parameter = getSetAccessorValueParameter(node); + return parameter && getEffectiveTypeAnnotationNode(parameter); + } + ts.getEffectiveSetAccessorTypeAnnotationNode = getEffectiveSetAccessorTypeAnnotationNode; + function emitNewLineBeforeLeadingComments(lineMap, writer, node, leadingComments) { + emitNewLineBeforeLeadingCommentsOfPosition(lineMap, writer, node.pos, leadingComments); + } + ts.emitNewLineBeforeLeadingComments = emitNewLineBeforeLeadingComments; + function emitNewLineBeforeLeadingCommentsOfPosition(lineMap, writer, pos, leadingComments) { + // If the leading comments start on different line than the start of node, write new line + if (leadingComments && leadingComments.length && pos !== leadingComments[0].pos && + getLineOfLocalPositionFromLineMap(lineMap, pos) !== getLineOfLocalPositionFromLineMap(lineMap, leadingComments[0].pos)) { + writer.writeLine(); + } + } + ts.emitNewLineBeforeLeadingCommentsOfPosition = emitNewLineBeforeLeadingCommentsOfPosition; + function emitNewLineBeforeLeadingCommentOfPosition(lineMap, writer, pos, commentPos) { + // If the leading comments start on different line than the start of node, write new line + if (pos !== commentPos && + getLineOfLocalPositionFromLineMap(lineMap, pos) !== getLineOfLocalPositionFromLineMap(lineMap, commentPos)) { + writer.writeLine(); + } + } + ts.emitNewLineBeforeLeadingCommentOfPosition = emitNewLineBeforeLeadingCommentOfPosition; + function emitComments(text, lineMap, writer, comments, leadingSeparator, trailingSeparator, newLine, writeComment) { + if (comments && comments.length > 0) { + if (leadingSeparator) { + writer.writeSpace(" "); + } + var emitInterveningSeparator = false; + for (var _i = 0, comments_1 = comments; _i < comments_1.length; _i++) { + var comment = comments_1[_i]; + if (emitInterveningSeparator) { + writer.writeSpace(" "); + emitInterveningSeparator = false; + } + writeComment(text, lineMap, writer, comment.pos, comment.end, newLine); + if (comment.hasTrailingNewLine) { + writer.writeLine(); + } + else { + emitInterveningSeparator = true; + } + } + if (emitInterveningSeparator && trailingSeparator) { + writer.writeSpace(" "); + } + } + } + ts.emitComments = emitComments; + /** + * Detached comment is a comment at the top of file or function body that is separated from + * the next statement by space. + */ + function emitDetachedComments(text, lineMap, writer, writeComment, node, newLine, removeComments) { + var leadingComments; + var currentDetachedCommentInfo; + if (removeComments) { + // removeComments is true, only reserve pinned comment at the top of file + // For example: + // /*! Pinned Comment */ + // + // var x = 10; + if (node.pos === 0) { + leadingComments = ts.filter(ts.getLeadingCommentRanges(text, node.pos), isPinnedCommentLocal); + } + } + else { + // removeComments is false, just get detached as normal and bypass the process to filter comment + leadingComments = ts.getLeadingCommentRanges(text, node.pos); + } + if (leadingComments) { + var detachedComments = []; + var lastComment = void 0; + for (var _i = 0, leadingComments_1 = leadingComments; _i < leadingComments_1.length; _i++) { + var comment = leadingComments_1[_i]; + if (lastComment) { + var lastCommentLine = getLineOfLocalPositionFromLineMap(lineMap, lastComment.end); + var commentLine = getLineOfLocalPositionFromLineMap(lineMap, comment.pos); + if (commentLine >= lastCommentLine + 2) { + // There was a blank line between the last comment and this comment. This + // comment is not part of the copyright comments. Return what we have so + // far. + break; + } + } + detachedComments.push(comment); + lastComment = comment; + } + if (detachedComments.length) { + // All comments look like they could have been part of the copyright header. Make + // sure there is at least one blank line between it and the node. If not, it's not + // a copyright header. + var lastCommentLine = getLineOfLocalPositionFromLineMap(lineMap, ts.last(detachedComments).end); + var nodeLine = getLineOfLocalPositionFromLineMap(lineMap, ts.skipTrivia(text, node.pos)); + if (nodeLine >= lastCommentLine + 2) { + // Valid detachedComments + emitNewLineBeforeLeadingComments(lineMap, writer, node, leadingComments); + emitComments(text, lineMap, writer, detachedComments, /*leadingSeparator*/ false, /*trailingSeparator*/ true, newLine, writeComment); + currentDetachedCommentInfo = { nodePos: node.pos, detachedCommentEndPos: ts.last(detachedComments).end }; + } + } + } + return currentDetachedCommentInfo; + function isPinnedCommentLocal(comment) { + return isPinnedComment(text, comment.pos); + } + } + ts.emitDetachedComments = emitDetachedComments; + function writeCommentRange(text, lineMap, writer, commentPos, commentEnd, newLine) { + if (text.charCodeAt(commentPos + 1) === 42 /* asterisk */) { + var firstCommentLineAndCharacter = ts.computeLineAndCharacterOfPosition(lineMap, commentPos); + var lineCount = lineMap.length; + var firstCommentLineIndent = void 0; + for (var pos = commentPos, currentLine = firstCommentLineAndCharacter.line; pos < commentEnd; currentLine++) { + var nextLineStart = (currentLine + 1) === lineCount + ? text.length + 1 + : lineMap[currentLine + 1]; + if (pos !== commentPos) { + // If we are not emitting first line, we need to write the spaces to adjust the alignment + if (firstCommentLineIndent === undefined) { + firstCommentLineIndent = calculateIndent(text, lineMap[firstCommentLineAndCharacter.line], commentPos); + } + // These are number of spaces writer is going to write at current indent + var currentWriterIndentSpacing = writer.getIndent() * getIndentSize(); + // Number of spaces we want to be writing + // eg: Assume writer indent + // module m { + // /* starts at character 9 this is line 1 + // * starts at character pos 4 line --1 = 8 - 8 + 3 + // More left indented comment */ --2 = 8 - 8 + 2 + // class c { } + // } + // module m { + // /* this is line 1 -- Assume current writer indent 8 + // * line --3 = 8 - 4 + 5 + // More right indented comment */ --4 = 8 - 4 + 11 + // class c { } + // } + var spacesToEmit = currentWriterIndentSpacing - firstCommentLineIndent + calculateIndent(text, pos, nextLineStart); + if (spacesToEmit > 0) { + var numberOfSingleSpacesToEmit = spacesToEmit % getIndentSize(); + var indentSizeSpaceString = getIndentString((spacesToEmit - numberOfSingleSpacesToEmit) / getIndentSize()); + // Write indent size string ( in eg 1: = "", 2: "" , 3: string with 8 spaces 4: string with 12 spaces + writer.rawWrite(indentSizeSpaceString); + // Emit the single spaces (in eg: 1: 3 spaces, 2: 2 spaces, 3: 1 space, 4: 3 spaces) + while (numberOfSingleSpacesToEmit) { + writer.rawWrite(" "); + numberOfSingleSpacesToEmit--; + } + } + else { + // No spaces to emit write empty string + writer.rawWrite(""); + } + } + // Write the comment line text + writeTrimmedCurrentLine(text, commentEnd, writer, newLine, pos, nextLineStart); + pos = nextLineStart; + } + } + else { + // Single line comment of style //.... + writer.writeComment(text.substring(commentPos, commentEnd)); + } + } + ts.writeCommentRange = writeCommentRange; + function writeTrimmedCurrentLine(text, commentEnd, writer, newLine, pos, nextLineStart) { + var end = Math.min(commentEnd, nextLineStart - 1); + var currentLineText = text.substring(pos, end).replace(/^\s+|\s+$/g, ""); + if (currentLineText) { + // trimmed forward and ending spaces text + writer.writeComment(currentLineText); + if (end !== commentEnd) { + writer.writeLine(); + } + } + else { + // Empty string - make sure we write empty line + writer.rawWrite(newLine); + } + } + function calculateIndent(text, pos, end) { + var currentLineIndent = 0; + for (; pos < end && ts.isWhiteSpaceSingleLine(text.charCodeAt(pos)); pos++) { + if (text.charCodeAt(pos) === 9 /* tab */) { + // Tabs = TabSize = indent size and go to next tabStop + currentLineIndent += getIndentSize() - (currentLineIndent % getIndentSize()); + } + else { + // Single space + currentLineIndent++; + } + } + return currentLineIndent; + } + function hasModifiers(node) { + return getModifierFlags(node) !== 0 /* None */; + } + ts.hasModifiers = hasModifiers; + function hasModifier(node, flags) { + return !!getSelectedModifierFlags(node, flags); + } + ts.hasModifier = hasModifier; + function hasStaticModifier(node) { + return hasModifier(node, 32 /* Static */); + } + ts.hasStaticModifier = hasStaticModifier; + function hasReadonlyModifier(node) { + return hasModifier(node, 64 /* Readonly */); + } + ts.hasReadonlyModifier = hasReadonlyModifier; + function getSelectedModifierFlags(node, flags) { + return getModifierFlags(node) & flags; + } + ts.getSelectedModifierFlags = getSelectedModifierFlags; + function getModifierFlags(node) { + if (node.modifierFlagsCache & 536870912 /* HasComputedFlags */) { + return node.modifierFlagsCache & ~536870912 /* HasComputedFlags */; + } + var flags = getModifierFlagsNoCache(node); + node.modifierFlagsCache = flags | 536870912 /* HasComputedFlags */; + return flags; + } + ts.getModifierFlags = getModifierFlags; + function getModifierFlagsNoCache(node) { + var flags = 0 /* None */; + if (node.modifiers) { + for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) { + var modifier = _a[_i]; + flags |= modifierToFlag(modifier.kind); + } + } + if (node.flags & 4 /* NestedNamespace */ || (node.kind === 72 /* Identifier */ && node.isInJSDocNamespace)) { + flags |= 1 /* Export */; + } + return flags; + } + ts.getModifierFlagsNoCache = getModifierFlagsNoCache; + function modifierToFlag(token) { + switch (token) { + case 116 /* StaticKeyword */: return 32 /* Static */; + case 115 /* PublicKeyword */: return 4 /* Public */; + case 114 /* ProtectedKeyword */: return 16 /* Protected */; + case 113 /* PrivateKeyword */: return 8 /* Private */; + case 118 /* AbstractKeyword */: return 128 /* Abstract */; + case 85 /* ExportKeyword */: return 1 /* Export */; + case 125 /* DeclareKeyword */: return 2 /* Ambient */; + case 77 /* ConstKeyword */: return 2048 /* Const */; + case 80 /* DefaultKeyword */: return 512 /* Default */; + case 121 /* AsyncKeyword */: return 256 /* Async */; + case 133 /* ReadonlyKeyword */: return 64 /* Readonly */; + } + return 0 /* None */; + } + ts.modifierToFlag = modifierToFlag; + function isLogicalOperator(token) { + return token === 55 /* BarBarToken */ + || token === 54 /* AmpersandAmpersandToken */ + || token === 52 /* ExclamationToken */; + } + ts.isLogicalOperator = isLogicalOperator; + function isAssignmentOperator(token) { + return token >= 59 /* FirstAssignment */ && token <= 71 /* LastAssignment */; + } + ts.isAssignmentOperator = isAssignmentOperator; + /** Get `C` given `N` if `N` is in the position `class C extends N` where `N` is an ExpressionWithTypeArguments. */ + function tryGetClassExtendingExpressionWithTypeArguments(node) { + var cls = tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node); + return cls && !cls.isImplements ? cls.class : undefined; + } + ts.tryGetClassExtendingExpressionWithTypeArguments = tryGetClassExtendingExpressionWithTypeArguments; + function tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node) { + return ts.isExpressionWithTypeArguments(node) + && ts.isHeritageClause(node.parent) + && ts.isClassLike(node.parent.parent) + ? { class: node.parent.parent, isImplements: node.parent.token === 109 /* ImplementsKeyword */ } + : undefined; + } + ts.tryGetClassImplementingOrExtendingExpressionWithTypeArguments = tryGetClassImplementingOrExtendingExpressionWithTypeArguments; + function isAssignmentExpression(node, excludeCompoundAssignment) { + return ts.isBinaryExpression(node) + && (excludeCompoundAssignment + ? node.operatorToken.kind === 59 /* EqualsToken */ + : isAssignmentOperator(node.operatorToken.kind)) + && ts.isLeftHandSideExpression(node.left); + } + ts.isAssignmentExpression = isAssignmentExpression; + function isDestructuringAssignment(node) { + if (isAssignmentExpression(node, /*excludeCompoundAssignment*/ true)) { + var kind = node.left.kind; + return kind === 188 /* ObjectLiteralExpression */ + || kind === 187 /* ArrayLiteralExpression */; + } + return false; + } + ts.isDestructuringAssignment = isDestructuringAssignment; + function isExpressionWithTypeArgumentsInClassExtendsClause(node) { + return tryGetClassExtendingExpressionWithTypeArguments(node) !== undefined; + } + ts.isExpressionWithTypeArgumentsInClassExtendsClause = isExpressionWithTypeArgumentsInClassExtendsClause; + function isEntityNameExpression(node) { + return node.kind === 72 /* Identifier */ || isPropertyAccessEntityNameExpression(node); + } + ts.isEntityNameExpression = isEntityNameExpression; + function isPropertyAccessEntityNameExpression(node) { + return ts.isPropertyAccessExpression(node) && isEntityNameExpression(node.expression); + } + ts.isPropertyAccessEntityNameExpression = isPropertyAccessEntityNameExpression; + function isPrototypeAccess(node) { + return ts.isPropertyAccessExpression(node) && node.name.escapedText === "prototype"; + } + ts.isPrototypeAccess = isPrototypeAccess; + function isRightSideOfQualifiedNameOrPropertyAccess(node) { + return (node.parent.kind === 148 /* QualifiedName */ && node.parent.right === node) || + (node.parent.kind === 189 /* PropertyAccessExpression */ && node.parent.name === node); + } + ts.isRightSideOfQualifiedNameOrPropertyAccess = isRightSideOfQualifiedNameOrPropertyAccess; + function isEmptyObjectLiteral(expression) { + return expression.kind === 188 /* ObjectLiteralExpression */ && + expression.properties.length === 0; + } + ts.isEmptyObjectLiteral = isEmptyObjectLiteral; + function isEmptyArrayLiteral(expression) { + return expression.kind === 187 /* ArrayLiteralExpression */ && + expression.elements.length === 0; + } + ts.isEmptyArrayLiteral = isEmptyArrayLiteral; + function getLocalSymbolForExportDefault(symbol) { + return isExportDefaultSymbol(symbol) ? symbol.declarations[0].localSymbol : undefined; + } + ts.getLocalSymbolForExportDefault = getLocalSymbolForExportDefault; + function isExportDefaultSymbol(symbol) { + return symbol && ts.length(symbol.declarations) > 0 && hasModifier(symbol.declarations[0], 512 /* Default */); + } + /** Return ".ts", ".d.ts", or ".tsx", if that is the extension. */ + function tryExtractTSExtension(fileName) { + return ts.find(ts.supportedTSExtensionsForExtractExtension, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + } + ts.tryExtractTSExtension = tryExtractTSExtension; + /** + * Replace each instance of non-ascii characters by one, two, three, or four escape sequences + * representing the UTF-8 encoding of the character, and return the expanded char code list. + */ + function getExpandedCharCodes(input) { + var output = []; + var length = input.length; + for (var i = 0; i < length; i++) { + var charCode = input.charCodeAt(i); + // handle utf8 + if (charCode < 0x80) { + output.push(charCode); + } + else if (charCode < 0x800) { + output.push((charCode >> 6) | 192); + output.push((charCode & 63) | 128); + } + else if (charCode < 0x10000) { + output.push((charCode >> 12) | 224); + output.push(((charCode >> 6) & 63) | 128); + output.push((charCode & 63) | 128); + } + else if (charCode < 0x20000) { + output.push((charCode >> 18) | 240); + output.push(((charCode >> 12) & 63) | 128); + output.push(((charCode >> 6) & 63) | 128); + output.push((charCode & 63) | 128); + } + else { + ts.Debug.assert(false, "Unexpected code point"); + } + } + return output; + } + var base64Digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; + /** + * Converts a string to a base-64 encoded ASCII string. + */ + function convertToBase64(input) { + var result = ""; + var charCodes = getExpandedCharCodes(input); + var i = 0; + var length = charCodes.length; + var byte1, byte2, byte3, byte4; + while (i < length) { + // Convert every 6-bits in the input 3 character points + // into a base64 digit + byte1 = charCodes[i] >> 2; + byte2 = (charCodes[i] & 3) << 4 | charCodes[i + 1] >> 4; + byte3 = (charCodes[i + 1] & 15) << 2 | charCodes[i + 2] >> 6; + byte4 = charCodes[i + 2] & 63; + // We are out of characters in the input, set the extra + // digits to 64 (padding character). + if (i + 1 >= length) { + byte3 = byte4 = 64; + } + else if (i + 2 >= length) { + byte4 = 64; + } + // Write to the output + result += base64Digits.charAt(byte1) + base64Digits.charAt(byte2) + base64Digits.charAt(byte3) + base64Digits.charAt(byte4); + i += 3; + } + return result; + } + ts.convertToBase64 = convertToBase64; + function getStringFromExpandedCharCodes(codes) { + var output = ""; + var i = 0; + var length = codes.length; + while (i < length) { + var charCode = codes[i]; + if (charCode < 0x80) { + output += String.fromCharCode(charCode); + i++; + } + else if ((charCode & 192) === 192) { + var value = charCode & 63; + i++; + var nextCode = codes[i]; + while ((nextCode & 192) === 128) { + value = (value << 6) | (nextCode & 63); + i++; + nextCode = codes[i]; + } + // `value` may be greater than 10FFFF (the maximum unicode codepoint) - JS will just make this into an invalid character for us + output += String.fromCharCode(value); + } + else { + // We don't want to kill the process when decoding fails (due to a following char byte not + // following a leading char), so we just print the (bad) value + output += String.fromCharCode(charCode); + i++; + } + } + return output; + } + function base64encode(host, input) { + if (host && host.base64encode) { + return host.base64encode(input); + } + return convertToBase64(input); + } + ts.base64encode = base64encode; + function base64decode(host, input) { + if (host && host.base64decode) { + return host.base64decode(input); + } + var length = input.length; + var expandedCharCodes = []; + var i = 0; + while (i < length) { + // Stop decoding once padding characters are present + if (input.charCodeAt(i) === base64Digits.charCodeAt(64)) { + break; + } + // convert 4 input digits into three characters, ignoring padding characters at the end + var ch1 = base64Digits.indexOf(input[i]); + var ch2 = base64Digits.indexOf(input[i + 1]); + var ch3 = base64Digits.indexOf(input[i + 2]); + var ch4 = base64Digits.indexOf(input[i + 3]); + var code1 = ((ch1 & 63) << 2) | ((ch2 >> 4) & 3); + var code2 = ((ch2 & 15) << 4) | ((ch3 >> 2) & 15); + var code3 = ((ch3 & 3) << 6) | (ch4 & 63); + if (code2 === 0 && ch3 !== 0) { // code2 decoded to zero, but ch3 was padding - elide code2 and code3 + expandedCharCodes.push(code1); + } + else if (code3 === 0 && ch4 !== 0) { // code3 decoded to zero, but ch4 was padding, elide code3 + expandedCharCodes.push(code1, code2); + } + else { + expandedCharCodes.push(code1, code2, code3); + } + i += 4; + } + return getStringFromExpandedCharCodes(expandedCharCodes); + } + ts.base64decode = base64decode; + function readJson(path, host) { + try { + var jsonText = host.readFile(path); + if (!jsonText) + return {}; + var result = ts.parseConfigFileTextToJson(path, jsonText); + if (result.error) { + return {}; + } + return result.config; + } + catch (e) { + // gracefully handle if readFile fails or returns not JSON + return {}; + } + } + ts.readJson = readJson; + function directoryProbablyExists(directoryName, host) { + // if host does not support 'directoryExists' assume that directory will exist + return !host.directoryExists || host.directoryExists(directoryName); + } + ts.directoryProbablyExists = directoryProbablyExists; + var carriageReturnLineFeed = "\r\n"; + var lineFeed = "\n"; + function getNewLineCharacter(options, getNewLine) { + switch (options.newLine) { + case 0 /* CarriageReturnLineFeed */: + return carriageReturnLineFeed; + case 1 /* LineFeed */: + return lineFeed; + } + return getNewLine ? getNewLine() : ts.sys ? ts.sys.newLine : carriageReturnLineFeed; + } + ts.getNewLineCharacter = getNewLineCharacter; + /** + * Formats an enum value as a string for debugging and debug assertions. + */ + function formatEnum(value, enumObject, isFlags) { + if (value === void 0) { value = 0; } + var members = getEnumMembers(enumObject); + if (value === 0) { + return members.length > 0 && members[0][0] === 0 ? members[0][1] : "0"; + } + if (isFlags) { + var result = ""; + var remainingFlags = value; + for (var i = members.length - 1; i >= 0 && remainingFlags !== 0; i--) { + var _a = members[i], enumValue = _a[0], enumName = _a[1]; + if (enumValue !== 0 && (remainingFlags & enumValue) === enumValue) { + remainingFlags &= ~enumValue; + result = "" + enumName + (result ? ", " : "") + result; + } + } + if (remainingFlags === 0) { + return result; + } + } + else { + for (var _i = 0, members_1 = members; _i < members_1.length; _i++) { + var _b = members_1[_i], enumValue = _b[0], enumName = _b[1]; + if (enumValue === value) { + return enumName; + } + } + } + return value.toString(); + } + function getEnumMembers(enumObject) { + var result = []; + for (var name in enumObject) { + var value = enumObject[name]; + if (typeof value === "number") { + result.push([value, name]); + } + } + return ts.stableSort(result, function (x, y) { return ts.compareValues(x[0], y[0]); }); + } + function formatSyntaxKind(kind) { + return formatEnum(kind, ts.SyntaxKind, /*isFlags*/ false); + } + ts.formatSyntaxKind = formatSyntaxKind; + function formatModifierFlags(flags) { + return formatEnum(flags, ts.ModifierFlags, /*isFlags*/ true); + } + ts.formatModifierFlags = formatModifierFlags; + function formatTransformFlags(flags) { + return formatEnum(flags, ts.TransformFlags, /*isFlags*/ true); + } + ts.formatTransformFlags = formatTransformFlags; + function formatEmitFlags(flags) { + return formatEnum(flags, ts.EmitFlags, /*isFlags*/ true); + } + ts.formatEmitFlags = formatEmitFlags; + function formatSymbolFlags(flags) { + return formatEnum(flags, ts.SymbolFlags, /*isFlags*/ true); + } + ts.formatSymbolFlags = formatSymbolFlags; + function formatTypeFlags(flags) { + return formatEnum(flags, ts.TypeFlags, /*isFlags*/ true); + } + ts.formatTypeFlags = formatTypeFlags; + function formatObjectFlags(flags) { + return formatEnum(flags, ts.ObjectFlags, /*isFlags*/ true); + } + ts.formatObjectFlags = formatObjectFlags; + /** + * Creates a new TextRange from the provided pos and end. + * + * @param pos The start position. + * @param end The end position. + */ + function createRange(pos, end) { + if (end === void 0) { end = pos; } + ts.Debug.assert(end >= pos || end === -1); + return { pos: pos, end: end }; + } + ts.createRange = createRange; + /** + * Creates a new TextRange from a provided range with a new end position. + * + * @param range A TextRange. + * @param end The new end position. + */ + function moveRangeEnd(range, end) { + return createRange(range.pos, end); + } + ts.moveRangeEnd = moveRangeEnd; + /** + * Creates a new TextRange from a provided range with a new start position. + * + * @param range A TextRange. + * @param pos The new Start position. + */ + function moveRangePos(range, pos) { + return createRange(pos, range.end); + } + ts.moveRangePos = moveRangePos; + /** + * Moves the start position of a range past any decorators. + */ + function moveRangePastDecorators(node) { + return node.decorators && node.decorators.length > 0 + ? moveRangePos(node, node.decorators.end) + : node; + } + ts.moveRangePastDecorators = moveRangePastDecorators; + /** + * Moves the start position of a range past any decorators or modifiers. + */ + function moveRangePastModifiers(node) { + return node.modifiers && node.modifiers.length > 0 + ? moveRangePos(node, node.modifiers.end) + : moveRangePastDecorators(node); + } + ts.moveRangePastModifiers = moveRangePastModifiers; + /** + * Determines whether a TextRange has the same start and end positions. + * + * @param range A TextRange. + */ + function isCollapsedRange(range) { + return range.pos === range.end; + } + ts.isCollapsedRange = isCollapsedRange; + /** + * Creates a new TextRange for a token at the provides start position. + * + * @param pos The start position. + * @param token The token. + */ + function createTokenRange(pos, token) { + return createRange(pos, pos + ts.tokenToString(token).length); + } + ts.createTokenRange = createTokenRange; + function rangeIsOnSingleLine(range, sourceFile) { + return rangeStartIsOnSameLineAsRangeEnd(range, range, sourceFile); + } + ts.rangeIsOnSingleLine = rangeIsOnSingleLine; + function rangeStartPositionsAreOnSameLine(range1, range2, sourceFile) { + return positionsAreOnSameLine(getStartPositionOfRange(range1, sourceFile), getStartPositionOfRange(range2, sourceFile), sourceFile); + } + ts.rangeStartPositionsAreOnSameLine = rangeStartPositionsAreOnSameLine; + function rangeEndPositionsAreOnSameLine(range1, range2, sourceFile) { + return positionsAreOnSameLine(range1.end, range2.end, sourceFile); + } + ts.rangeEndPositionsAreOnSameLine = rangeEndPositionsAreOnSameLine; + function rangeStartIsOnSameLineAsRangeEnd(range1, range2, sourceFile) { + return positionsAreOnSameLine(getStartPositionOfRange(range1, sourceFile), range2.end, sourceFile); + } + ts.rangeStartIsOnSameLineAsRangeEnd = rangeStartIsOnSameLineAsRangeEnd; + function rangeEndIsOnSameLineAsRangeStart(range1, range2, sourceFile) { + return positionsAreOnSameLine(range1.end, getStartPositionOfRange(range2, sourceFile), sourceFile); + } + ts.rangeEndIsOnSameLineAsRangeStart = rangeEndIsOnSameLineAsRangeStart; + function positionsAreOnSameLine(pos1, pos2, sourceFile) { + return pos1 === pos2 || + getLineOfLocalPosition(sourceFile, pos1) === getLineOfLocalPosition(sourceFile, pos2); + } + ts.positionsAreOnSameLine = positionsAreOnSameLine; + function getStartPositionOfRange(range, sourceFile) { + return ts.positionIsSynthesized(range.pos) ? -1 : ts.skipTrivia(sourceFile.text, range.pos); + } + ts.getStartPositionOfRange = getStartPositionOfRange; + /** + * Determines whether a name was originally the declaration name of an enum or namespace + * declaration. + */ + function isDeclarationNameOfEnumOrNamespace(node) { + var parseNode = ts.getParseTreeNode(node); + if (parseNode) { + switch (parseNode.parent.kind) { + case 243 /* EnumDeclaration */: + case 244 /* ModuleDeclaration */: + return parseNode === parseNode.parent.name; + } + } + return false; + } + ts.isDeclarationNameOfEnumOrNamespace = isDeclarationNameOfEnumOrNamespace; + function getInitializedVariables(node) { + return ts.filter(node.declarations, isInitializedVariable); + } + ts.getInitializedVariables = getInitializedVariables; + function isInitializedVariable(node) { + return node.initializer !== undefined; + } + function isWatchSet(options) { + // Firefox has Object.prototype.watch + return options.watch && options.hasOwnProperty("watch"); + } + ts.isWatchSet = isWatchSet; + function closeFileWatcher(watcher) { + watcher.close(); + } + ts.closeFileWatcher = closeFileWatcher; + function getCheckFlags(symbol) { + return symbol.flags & 33554432 /* Transient */ ? symbol.checkFlags : 0; + } + ts.getCheckFlags = getCheckFlags; + function getDeclarationModifierFlagsFromSymbol(s) { + if (s.valueDeclaration) { + var flags = ts.getCombinedModifierFlags(s.valueDeclaration); + return s.parent && s.parent.flags & 32 /* Class */ ? flags : flags & ~28 /* AccessibilityModifier */; + } + if (getCheckFlags(s) & 6 /* Synthetic */) { + var checkFlags = s.checkFlags; + var accessModifier = checkFlags & 256 /* ContainsPrivate */ ? 8 /* Private */ : + checkFlags & 64 /* ContainsPublic */ ? 4 /* Public */ : + 16 /* Protected */; + var staticModifier = checkFlags & 512 /* ContainsStatic */ ? 32 /* Static */ : 0; + return accessModifier | staticModifier; + } + if (s.flags & 4194304 /* Prototype */) { + return 4 /* Public */ | 32 /* Static */; + } + return 0; + } + ts.getDeclarationModifierFlagsFromSymbol = getDeclarationModifierFlagsFromSymbol; + function skipAlias(symbol, checker) { + return symbol.flags & 2097152 /* Alias */ ? checker.getAliasedSymbol(symbol) : symbol; + } + ts.skipAlias = skipAlias; + /** See comment on `declareModuleMember` in `binder.ts`. */ + function getCombinedLocalAndExportSymbolFlags(symbol) { + return symbol.exportSymbol ? symbol.exportSymbol.flags | symbol.flags : symbol.flags; + } + ts.getCombinedLocalAndExportSymbolFlags = getCombinedLocalAndExportSymbolFlags; + function isWriteOnlyAccess(node) { + return accessKind(node) === 1 /* Write */; + } + ts.isWriteOnlyAccess = isWriteOnlyAccess; + function isWriteAccess(node) { + return accessKind(node) !== 0 /* Read */; + } + ts.isWriteAccess = isWriteAccess; + var AccessKind; + (function (AccessKind) { + /** Only reads from a variable. */ + AccessKind[AccessKind["Read"] = 0] = "Read"; + /** Only writes to a variable without using the result. E.g.: `x++;`. */ + AccessKind[AccessKind["Write"] = 1] = "Write"; + /** Writes to a variable and uses the result as an expression. E.g.: `f(x++);`. */ + AccessKind[AccessKind["ReadWrite"] = 2] = "ReadWrite"; + })(AccessKind || (AccessKind = {})); + function accessKind(node) { + var parent = node.parent; + if (!parent) + return 0 /* Read */; + switch (parent.kind) { + case 195 /* ParenthesizedExpression */: + return accessKind(parent); + case 203 /* PostfixUnaryExpression */: + case 202 /* PrefixUnaryExpression */: + var operator = parent.operator; + return operator === 44 /* PlusPlusToken */ || operator === 45 /* MinusMinusToken */ ? writeOrReadWrite() : 0 /* Read */; + case 204 /* BinaryExpression */: + var _a = parent, left = _a.left, operatorToken = _a.operatorToken; + return left === node && isAssignmentOperator(operatorToken.kind) ? + operatorToken.kind === 59 /* EqualsToken */ ? 1 /* Write */ : writeOrReadWrite() + : 0 /* Read */; + case 189 /* PropertyAccessExpression */: + return parent.name !== node ? 0 /* Read */ : accessKind(parent); + case 275 /* PropertyAssignment */: { + var parentAccess = accessKind(parent.parent); + // In `({ x: varname }) = { x: 1 }`, the left `x` is a read, the right `x` is a write. + return node === parent.name ? reverseAccessKind(parentAccess) : parentAccess; + } + case 276 /* ShorthandPropertyAssignment */: + // Assume it's the local variable being accessed, since we don't check public properties for --noUnusedLocals. + return node === parent.objectAssignmentInitializer ? 0 /* Read */ : accessKind(parent.parent); + case 187 /* ArrayLiteralExpression */: + return accessKind(parent); + default: + return 0 /* Read */; + } + function writeOrReadWrite() { + // If grandparent is not an ExpressionStatement, this is used as an expression in addition to having a side effect. + return parent.parent && skipParenthesesUp(parent.parent).kind === 221 /* ExpressionStatement */ ? 1 /* Write */ : 2 /* ReadWrite */; + } + } + function reverseAccessKind(a) { + switch (a) { + case 0 /* Read */: + return 1 /* Write */; + case 1 /* Write */: + return 0 /* Read */; + case 2 /* ReadWrite */: + return 2 /* ReadWrite */; + default: + return ts.Debug.assertNever(a); + } + } + function compareDataObjects(dst, src) { + if (!dst || !src || Object.keys(dst).length !== Object.keys(src).length) { + return false; + } + for (var e in dst) { + if (typeof dst[e] === "object") { + if (!compareDataObjects(dst[e], src[e])) { + return false; + } + } + else if (typeof dst[e] !== "function") { + if (dst[e] !== src[e]) { + return false; + } + } + } + return true; + } + ts.compareDataObjects = compareDataObjects; + /** + * clears already present map by calling onDeleteExistingValue callback before deleting that key/value + */ + function clearMap(map, onDeleteValue) { + // Remove all + map.forEach(onDeleteValue); + map.clear(); + } + ts.clearMap = clearMap; + /** + * Mutates the map with newMap such that keys in map will be same as newMap. + */ + function mutateMap(map, newMap, options) { + var createNewValue = options.createNewValue, onDeleteValue = options.onDeleteValue, onExistingValue = options.onExistingValue; + // Needs update + map.forEach(function (existingValue, key) { + var valueInNewMap = newMap.get(key); + // Not present any more in new map, remove it + if (valueInNewMap === undefined) { + map.delete(key); + onDeleteValue(existingValue, key); + } + // If present notify about existing values + else if (onExistingValue) { + onExistingValue(existingValue, valueInNewMap, key); + } + }); + // Add new values that are not already present + newMap.forEach(function (valueInNewMap, key) { + if (!map.has(key)) { + // New values + map.set(key, createNewValue(key, valueInNewMap)); + } + }); + } + ts.mutateMap = mutateMap; + /** Calls `callback` on `directory` and every ancestor directory it has, returning the first defined result. */ + function forEachAncestorDirectory(directory, callback) { + while (true) { + var result = callback(directory); + if (result !== undefined) { + return result; + } + var parentPath = ts.getDirectoryPath(directory); + if (parentPath === directory) { + return undefined; + } + directory = parentPath; + } + } + ts.forEachAncestorDirectory = forEachAncestorDirectory; + // Return true if the given type is the constructor type for an abstract class + function isAbstractConstructorType(type) { + return !!(getObjectFlags(type) & 16 /* Anonymous */) && !!type.symbol && isAbstractConstructorSymbol(type.symbol); + } + ts.isAbstractConstructorType = isAbstractConstructorType; + function isAbstractConstructorSymbol(symbol) { + if (symbol.flags & 32 /* Class */) { + var declaration = getClassLikeDeclarationOfSymbol(symbol); + return !!declaration && hasModifier(declaration, 128 /* Abstract */); + } + return false; + } + ts.isAbstractConstructorSymbol = isAbstractConstructorSymbol; + function getClassLikeDeclarationOfSymbol(symbol) { + return ts.find(symbol.declarations, ts.isClassLike); + } + ts.getClassLikeDeclarationOfSymbol = getClassLikeDeclarationOfSymbol; + function getObjectFlags(type) { + return type.flags & 524288 /* Object */ ? type.objectFlags : 0; + } + ts.getObjectFlags = getObjectFlags; + function typeHasCallOrConstructSignatures(type, checker) { + return checker.getSignaturesOfType(type, 0 /* Call */).length !== 0 || checker.getSignaturesOfType(type, 1 /* Construct */).length !== 0; + } + ts.typeHasCallOrConstructSignatures = typeHasCallOrConstructSignatures; + function forSomeAncestorDirectory(directory, callback) { + return !!forEachAncestorDirectory(directory, function (d) { return callback(d) ? true : undefined; }); + } + ts.forSomeAncestorDirectory = forSomeAncestorDirectory; + function isUMDExportSymbol(symbol) { + return !!symbol && !!symbol.declarations && !!symbol.declarations[0] && ts.isNamespaceExportDeclaration(symbol.declarations[0]); + } + ts.isUMDExportSymbol = isUMDExportSymbol; + function showModuleSpecifier(_a) { + var moduleSpecifier = _a.moduleSpecifier; + return ts.isStringLiteral(moduleSpecifier) ? moduleSpecifier.text : getTextOfNode(moduleSpecifier); + } + ts.showModuleSpecifier = showModuleSpecifier; + function getLastChild(node) { + var lastChild; + ts.forEachChild(node, function (child) { + if (nodeIsPresent(child)) + lastChild = child; + }, function (children) { + // As an optimization, jump straight to the end of the list. + for (var i = children.length - 1; i >= 0; i--) { + if (nodeIsPresent(children[i])) { + lastChild = children[i]; + break; + } + } + }); + return lastChild; + } + ts.getLastChild = getLastChild; + function addToSeen(seen, key, value) { + if (value === void 0) { value = true; } + key = String(key); + if (seen.has(key)) { + return false; + } + seen.set(key, value); + return true; + } + ts.addToSeen = addToSeen; + function isObjectTypeDeclaration(node) { + return ts.isClassLike(node) || ts.isInterfaceDeclaration(node) || ts.isTypeLiteralNode(node); + } + ts.isObjectTypeDeclaration = isObjectTypeDeclaration; + function isTypeNodeKind(kind) { + return (kind >= 163 /* FirstTypeNode */ && kind <= 183 /* LastTypeNode */) + || kind === 120 /* AnyKeyword */ + || kind === 143 /* UnknownKeyword */ + || kind === 135 /* NumberKeyword */ + || kind === 146 /* BigIntKeyword */ + || kind === 136 /* ObjectKeyword */ + || kind === 123 /* BooleanKeyword */ + || kind === 138 /* StringKeyword */ + || kind === 139 /* SymbolKeyword */ + || kind === 100 /* ThisKeyword */ + || kind === 106 /* VoidKeyword */ + || kind === 141 /* UndefinedKeyword */ + || kind === 96 /* NullKeyword */ + || kind === 132 /* NeverKeyword */ + || kind === 211 /* ExpressionWithTypeArguments */ + || kind === 284 /* JSDocAllType */ + || kind === 285 /* JSDocUnknownType */ + || kind === 286 /* JSDocNullableType */ + || kind === 287 /* JSDocNonNullableType */ + || kind === 288 /* JSDocOptionalType */ + || kind === 289 /* JSDocFunctionType */ + || kind === 290 /* JSDocVariadicType */; + } + ts.isTypeNodeKind = isTypeNodeKind; +})(ts || (ts = {})); +(function (ts) { + function getDefaultLibFileName(options) { + switch (options.target) { + case 6 /* ESNext */: + return "lib.esnext.full.d.ts"; + case 5 /* ES2018 */: + return "lib.es2018.full.d.ts"; + case 4 /* ES2017 */: + return "lib.es2017.full.d.ts"; + case 3 /* ES2016 */: + return "lib.es2016.full.d.ts"; + case 2 /* ES2015 */: + return "lib.es6.d.ts"; // We don't use lib.es2015.full.d.ts due to breaking change. + default: + return "lib.d.ts"; + } + } + ts.getDefaultLibFileName = getDefaultLibFileName; + function textSpanEnd(span) { + return span.start + span.length; + } + ts.textSpanEnd = textSpanEnd; + function textSpanIsEmpty(span) { + return span.length === 0; + } + ts.textSpanIsEmpty = textSpanIsEmpty; + function textSpanContainsPosition(span, position) { + return position >= span.start && position < textSpanEnd(span); + } + ts.textSpanContainsPosition = textSpanContainsPosition; + /* @internal */ + function textRangeContainsPositionInclusive(span, position) { + return position >= span.pos && position <= span.end; + } + ts.textRangeContainsPositionInclusive = textRangeContainsPositionInclusive; + // Returns true if 'span' contains 'other'. + function textSpanContainsTextSpan(span, other) { + return other.start >= span.start && textSpanEnd(other) <= textSpanEnd(span); + } + ts.textSpanContainsTextSpan = textSpanContainsTextSpan; + function textSpanOverlapsWith(span, other) { + return textSpanOverlap(span, other) !== undefined; + } + ts.textSpanOverlapsWith = textSpanOverlapsWith; + function textSpanOverlap(span1, span2) { + var overlap = textSpanIntersection(span1, span2); + return overlap && overlap.length === 0 ? undefined : overlap; + } + ts.textSpanOverlap = textSpanOverlap; + function textSpanIntersectsWithTextSpan(span, other) { + return decodedTextSpanIntersectsWith(span.start, span.length, other.start, other.length); + } + ts.textSpanIntersectsWithTextSpan = textSpanIntersectsWithTextSpan; + function textSpanIntersectsWith(span, start, length) { + return decodedTextSpanIntersectsWith(span.start, span.length, start, length); + } + ts.textSpanIntersectsWith = textSpanIntersectsWith; + function decodedTextSpanIntersectsWith(start1, length1, start2, length2) { + var end1 = start1 + length1; + var end2 = start2 + length2; + return start2 <= end1 && end2 >= start1; + } + ts.decodedTextSpanIntersectsWith = decodedTextSpanIntersectsWith; + function textSpanIntersectsWithPosition(span, position) { + return position <= textSpanEnd(span) && position >= span.start; + } + ts.textSpanIntersectsWithPosition = textSpanIntersectsWithPosition; + function textSpanIntersection(span1, span2) { + var start = Math.max(span1.start, span2.start); + var end = Math.min(textSpanEnd(span1), textSpanEnd(span2)); + return start <= end ? createTextSpanFromBounds(start, end) : undefined; + } + ts.textSpanIntersection = textSpanIntersection; + function createTextSpan(start, length) { + if (start < 0) { + throw new Error("start < 0"); + } + if (length < 0) { + throw new Error("length < 0"); + } + return { start: start, length: length }; + } + ts.createTextSpan = createTextSpan; + function createTextSpanFromBounds(start, end) { + return createTextSpan(start, end - start); + } + ts.createTextSpanFromBounds = createTextSpanFromBounds; + function textChangeRangeNewSpan(range) { + return createTextSpan(range.span.start, range.newLength); + } + ts.textChangeRangeNewSpan = textChangeRangeNewSpan; + function textChangeRangeIsUnchanged(range) { + return textSpanIsEmpty(range.span) && range.newLength === 0; + } + ts.textChangeRangeIsUnchanged = textChangeRangeIsUnchanged; + function createTextChangeRange(span, newLength) { + if (newLength < 0) { + throw new Error("newLength < 0"); + } + return { span: span, newLength: newLength }; + } + ts.createTextChangeRange = createTextChangeRange; + ts.unchangedTextChangeRange = createTextChangeRange(createTextSpan(0, 0), 0); + /** + * Called to merge all the changes that occurred across several versions of a script snapshot + * into a single change. i.e. if a user keeps making successive edits to a script we will + * have a text change from V1 to V2, V2 to V3, ..., Vn. + * + * This function will then merge those changes into a single change range valid between V1 and + * Vn. + */ + function collapseTextChangeRangesAcrossMultipleVersions(changes) { + if (changes.length === 0) { + return ts.unchangedTextChangeRange; + } + if (changes.length === 1) { + return changes[0]; + } + // We change from talking about { { oldStart, oldLength }, newLength } to { oldStart, oldEnd, newEnd } + // as it makes things much easier to reason about. + var change0 = changes[0]; + var oldStartN = change0.span.start; + var oldEndN = textSpanEnd(change0.span); + var newEndN = oldStartN + change0.newLength; + for (var i = 1; i < changes.length; i++) { + var nextChange = changes[i]; + // Consider the following case: + // i.e. two edits. The first represents the text change range { { 10, 50 }, 30 }. i.e. The span starting + // at 10, with length 50 is reduced to length 30. The second represents the text change range { { 30, 30 }, 40 }. + // i.e. the span starting at 30 with length 30 is increased to length 40. + // + // 0 10 20 30 40 50 60 70 80 90 100 + // ------------------------------------------------------------------------------------------------------- + // | / + // | /---- + // T1 | /---- + // | /---- + // | /---- + // ------------------------------------------------------------------------------------------------------- + // | \ + // | \ + // T2 | \ + // | \ + // | \ + // ------------------------------------------------------------------------------------------------------- + // + // Merging these turns out to not be too difficult. First, determining the new start of the change is trivial + // it's just the min of the old and new starts. i.e.: + // + // 0 10 20 30 40 50 60 70 80 90 100 + // ------------------------------------------------------------*------------------------------------------ + // | / + // | /---- + // T1 | /---- + // | /---- + // | /---- + // ----------------------------------------$-------------------$------------------------------------------ + // . | \ + // . | \ + // T2 . | \ + // . | \ + // . | \ + // ----------------------------------------------------------------------*-------------------------------- + // + // (Note the dots represent the newly inferred start. + // Determining the new and old end is also pretty simple. Basically it boils down to paying attention to the + // absolute positions at the asterisks, and the relative change between the dollar signs. Basically, we see + // which if the two $'s precedes the other, and we move that one forward until they line up. in this case that + // means: + // + // 0 10 20 30 40 50 60 70 80 90 100 + // --------------------------------------------------------------------------------*---------------------- + // | / + // | /---- + // T1 | /---- + // | /---- + // | /---- + // ------------------------------------------------------------$------------------------------------------ + // . | \ + // . | \ + // T2 . | \ + // . | \ + // . | \ + // ----------------------------------------------------------------------*-------------------------------- + // + // In other words (in this case), we're recognizing that the second edit happened after where the first edit + // ended with a delta of 20 characters (60 - 40). Thus, if we go back in time to where the first edit started + // that's the same as if we started at char 80 instead of 60. + // + // As it so happens, the same logic applies if the second edit precedes the first edit. In that case rather + // than pushing the first edit forward to match the second, we'll push the second edit forward to match the + // first. + // + // In this case that means we have { oldStart: 10, oldEnd: 80, newEnd: 70 } or, in TextChangeRange + // semantics: { { start: 10, length: 70 }, newLength: 60 } + // + // The math then works out as follows. + // If we have { oldStart1, oldEnd1, newEnd1 } and { oldStart2, oldEnd2, newEnd2 } then we can compute the + // final result like so: + // + // { + // oldStart3: Min(oldStart1, oldStart2), + // oldEnd3: Max(oldEnd1, oldEnd1 + (oldEnd2 - newEnd1)), + // newEnd3: Max(newEnd2, newEnd2 + (newEnd1 - oldEnd2)) + // } + var oldStart1 = oldStartN; + var oldEnd1 = oldEndN; + var newEnd1 = newEndN; + var oldStart2 = nextChange.span.start; + var oldEnd2 = textSpanEnd(nextChange.span); + var newEnd2 = oldStart2 + nextChange.newLength; + oldStartN = Math.min(oldStart1, oldStart2); + oldEndN = Math.max(oldEnd1, oldEnd1 + (oldEnd2 - newEnd1)); + newEndN = Math.max(newEnd2, newEnd2 + (newEnd1 - oldEnd2)); + } + return createTextChangeRange(createTextSpanFromBounds(oldStartN, oldEndN), /*newLength*/ newEndN - oldStartN); + } + ts.collapseTextChangeRangesAcrossMultipleVersions = collapseTextChangeRangesAcrossMultipleVersions; + function getTypeParameterOwner(d) { + if (d && d.kind === 150 /* TypeParameter */) { + for (var current = d; current; current = current.parent) { + if (ts.isFunctionLike(current) || ts.isClassLike(current) || current.kind === 241 /* InterfaceDeclaration */) { + return current; + } + } + } + } + ts.getTypeParameterOwner = getTypeParameterOwner; + function isParameterPropertyDeclaration(node) { + return ts.hasModifier(node, 92 /* ParameterPropertyModifier */) && node.parent.kind === 157 /* Constructor */; + } + ts.isParameterPropertyDeclaration = isParameterPropertyDeclaration; + function isEmptyBindingPattern(node) { + if (ts.isBindingPattern(node)) { + return ts.every(node.elements, isEmptyBindingElement); + } + return false; + } + ts.isEmptyBindingPattern = isEmptyBindingPattern; + function isEmptyBindingElement(node) { + if (ts.isOmittedExpression(node)) { + return true; + } + return isEmptyBindingPattern(node.name); + } + ts.isEmptyBindingElement = isEmptyBindingElement; + function walkUpBindingElementsAndPatterns(binding) { + var node = binding.parent; + while (ts.isBindingElement(node.parent)) { + node = node.parent.parent; + } + return node.parent; + } + ts.walkUpBindingElementsAndPatterns = walkUpBindingElementsAndPatterns; + function getCombinedFlags(node, getFlags) { + if (ts.isBindingElement(node)) { + node = walkUpBindingElementsAndPatterns(node); + } + var flags = getFlags(node); + if (node.kind === 237 /* VariableDeclaration */) { + node = node.parent; + } + if (node && node.kind === 238 /* VariableDeclarationList */) { + flags |= getFlags(node); + node = node.parent; + } + if (node && node.kind === 219 /* VariableStatement */) { + flags |= getFlags(node); + } + return flags; + } + function getCombinedModifierFlags(node) { + return getCombinedFlags(node, ts.getModifierFlags); + } + ts.getCombinedModifierFlags = getCombinedModifierFlags; + // Returns the node flags for this node and all relevant parent nodes. This is done so that + // nodes like variable declarations and binding elements can returned a view of their flags + // that includes the modifiers from their container. i.e. flags like export/declare aren't + // stored on the variable declaration directly, but on the containing variable statement + // (if it has one). Similarly, flags for let/const are store on the variable declaration + // list. By calling this function, all those flags are combined so that the client can treat + // the node as if it actually had those flags. + function getCombinedNodeFlags(node) { + return getCombinedFlags(node, function (n) { return n.flags; }); + } + ts.getCombinedNodeFlags = getCombinedNodeFlags; + /** + * Checks to see if the locale is in the appropriate format, + * and if it is, attempts to set the appropriate language. + */ + function validateLocaleAndSetLanguage(locale, sys, errors) { + var matchResult = /^([a-z]+)([_\-]([a-z]+))?$/.exec(locale.toLowerCase()); + if (!matchResult) { + if (errors) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1, "en", "ja-jp")); + } + return; + } + var language = matchResult[1]; + var territory = matchResult[3]; + // First try the entire locale, then fall back to just language if that's all we have. + // Either ways do not fail, and fallback to the English diagnostic strings. + if (!trySetLanguageAndTerritory(language, territory, errors)) { + trySetLanguageAndTerritory(language, /*territory*/ undefined, errors); + } + // Set the UI locale for string collation + ts.setUILocale(locale); + function trySetLanguageAndTerritory(language, territory, errors) { + var compilerFilePath = ts.normalizePath(sys.getExecutingFilePath()); + var containingDirectoryPath = ts.getDirectoryPath(compilerFilePath); + var filePath = ts.combinePaths(containingDirectoryPath, language); + if (territory) { + filePath = filePath + "-" + territory; + } + filePath = sys.resolvePath(ts.combinePaths(filePath, "diagnosticMessages.generated.json")); + if (!sys.fileExists(filePath)) { + return false; + } + // TODO: Add codePage support for readFile? + var fileContents = ""; + try { + fileContents = sys.readFile(filePath); + } + catch (e) { + if (errors) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unable_to_open_file_0, filePath)); + } + return false; + } + try { + // tslint:disable-next-line no-unnecessary-qualifier (making clear this is a global mutation!) + ts.localizedDiagnosticMessages = JSON.parse(fileContents); + } + catch (_a) { + if (errors) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Corrupted_locale_file_0, filePath)); + } + return false; + } + return true; + } + } + ts.validateLocaleAndSetLanguage = validateLocaleAndSetLanguage; + function getOriginalNode(node, nodeTest) { + if (node) { + while (node.original !== undefined) { + node = node.original; + } + } + return !nodeTest || nodeTest(node) ? node : undefined; + } + ts.getOriginalNode = getOriginalNode; + /** + * Gets a value indicating whether a node originated in the parse tree. + * + * @param node The node to test. + */ + function isParseTreeNode(node) { + return (node.flags & 8 /* Synthesized */) === 0; + } + ts.isParseTreeNode = isParseTreeNode; + function getParseTreeNode(node, nodeTest) { + if (node === undefined || isParseTreeNode(node)) { + return node; + } + node = getOriginalNode(node); + if (isParseTreeNode(node) && (!nodeTest || nodeTest(node))) { + return node; + } + return undefined; + } + ts.getParseTreeNode = getParseTreeNode; + /** Add an extra underscore to identifiers that start with two underscores to avoid issues with magic names like '__proto__' */ + function escapeLeadingUnderscores(identifier) { + return (identifier.length >= 2 && identifier.charCodeAt(0) === 95 /* _ */ && identifier.charCodeAt(1) === 95 /* _ */ ? "_" + identifier : identifier); + } + ts.escapeLeadingUnderscores = escapeLeadingUnderscores; + /** + * Remove extra underscore from escaped identifier text content. + * + * @param identifier The escaped identifier text. + * @returns The unescaped identifier text. + */ + function unescapeLeadingUnderscores(identifier) { + var id = identifier; + return id.length >= 3 && id.charCodeAt(0) === 95 /* _ */ && id.charCodeAt(1) === 95 /* _ */ && id.charCodeAt(2) === 95 /* _ */ ? id.substr(1) : id; + } + ts.unescapeLeadingUnderscores = unescapeLeadingUnderscores; + function idText(identifier) { + return unescapeLeadingUnderscores(identifier.escapedText); + } + ts.idText = idText; + function symbolName(symbol) { + return unescapeLeadingUnderscores(symbol.escapedName); + } + ts.symbolName = symbolName; + /** + * A JSDocTypedef tag has an _optional_ name field - if a name is not directly present, we should + * attempt to draw the name from the node the declaration is on (as that declaration is what its' symbol + * will be merged with) + */ + function nameForNamelessJSDocTypedef(declaration) { + var hostNode = declaration.parent.parent; + if (!hostNode) { + return undefined; + } + // Covers classes, functions - any named declaration host node + if (ts.isDeclaration(hostNode)) { + return getDeclarationIdentifier(hostNode); + } + // Covers remaining cases (returning undefined if none match). + switch (hostNode.kind) { + case 219 /* VariableStatement */: + if (hostNode.declarationList && hostNode.declarationList.declarations[0]) { + return getDeclarationIdentifier(hostNode.declarationList.declarations[0]); + } + break; + case 221 /* ExpressionStatement */: + var expr = hostNode.expression; + switch (expr.kind) { + case 189 /* PropertyAccessExpression */: + return expr.name; + case 190 /* ElementAccessExpression */: + var arg = expr.argumentExpression; + if (ts.isIdentifier(arg)) { + return arg; + } + } + break; + case 195 /* ParenthesizedExpression */: { + return getDeclarationIdentifier(hostNode.expression); + } + case 233 /* LabeledStatement */: { + if (ts.isDeclaration(hostNode.statement) || ts.isExpression(hostNode.statement)) { + return getDeclarationIdentifier(hostNode.statement); + } + break; + } + } + } + function getDeclarationIdentifier(node) { + var name = getNameOfDeclaration(node); + return name && ts.isIdentifier(name) ? name : undefined; + } + function getNameOfJSDocTypedef(declaration) { + return declaration.name || nameForNamelessJSDocTypedef(declaration); + } + ts.getNameOfJSDocTypedef = getNameOfJSDocTypedef; + /** @internal */ + function isNamedDeclaration(node) { + return !!node.name; // A 'name' property should always be a DeclarationName. + } + ts.isNamedDeclaration = isNamedDeclaration; + /** @internal */ + function getNonAssignedNameOfDeclaration(declaration) { + switch (declaration.kind) { + case 72 /* Identifier */: + return declaration; + case 305 /* JSDocPropertyTag */: + case 299 /* JSDocParameterTag */: { + var name = declaration.name; + if (name.kind === 148 /* QualifiedName */) { + return name.right; + } + break; + } + case 191 /* CallExpression */: + case 204 /* BinaryExpression */: { + var expr = declaration; + switch (ts.getAssignmentDeclarationKind(expr)) { + case 1 /* ExportsProperty */: + case 4 /* ThisProperty */: + case 5 /* Property */: + case 3 /* PrototypeProperty */: + return expr.left.name; + case 7 /* ObjectDefinePropertyValue */: + case 8 /* ObjectDefinePropertyExports */: + case 9 /* ObjectDefinePrototypeProperty */: + return expr.arguments[1]; + default: + return undefined; + } + } + case 304 /* JSDocTypedefTag */: + return getNameOfJSDocTypedef(declaration); + case 254 /* ExportAssignment */: { + var expression = declaration.expression; + return ts.isIdentifier(expression) ? expression : undefined; + } + } + return declaration.name; + } + ts.getNonAssignedNameOfDeclaration = getNonAssignedNameOfDeclaration; + function getNameOfDeclaration(declaration) { + if (declaration === undefined) + return undefined; + return getNonAssignedNameOfDeclaration(declaration) || + (ts.isFunctionExpression(declaration) || ts.isClassExpression(declaration) ? getAssignedName(declaration) : undefined); + } + ts.getNameOfDeclaration = getNameOfDeclaration; + function getAssignedName(node) { + if (!node.parent) { + return undefined; + } + else if (ts.isPropertyAssignment(node.parent) || ts.isBindingElement(node.parent)) { + return node.parent.name; + } + else if (ts.isBinaryExpression(node.parent) && node === node.parent.right) { + if (ts.isIdentifier(node.parent.left)) { + return node.parent.left; + } + else if (ts.isPropertyAccessExpression(node.parent.left)) { + return node.parent.left.name; + } + } + } + /** + * Gets the JSDoc parameter tags for the node if present. + * + * @remarks Returns any JSDoc param tag whose name matches the provided + * parameter, whether a param tag on a containing function + * expression, or a param tag on a variable declaration whose + * initializer is the containing function. The tags closest to the + * node are returned first, so in the previous example, the param + * tag on the containing function expression would be first. + * + * For binding patterns, parameter tags are matched by position. + */ + function getJSDocParameterTags(param) { + if (param.name) { + if (ts.isIdentifier(param.name)) { + var name_1 = param.name.escapedText; + return getJSDocTags(param.parent).filter(function (tag) { return ts.isJSDocParameterTag(tag) && ts.isIdentifier(tag.name) && tag.name.escapedText === name_1; }); + } + else { + var i = param.parent.parameters.indexOf(param); + ts.Debug.assert(i > -1, "Parameters should always be in their parents' parameter list"); + var paramTags = getJSDocTags(param.parent).filter(ts.isJSDocParameterTag); + if (i < paramTags.length) { + return [paramTags[i]]; + } + } + } + // return empty array for: out-of-order binding patterns and JSDoc function syntax, which has un-named parameters + return ts.emptyArray; + } + ts.getJSDocParameterTags = getJSDocParameterTags; + /** + * Gets the JSDoc type parameter tags for the node if present. + * + * @remarks Returns any JSDoc template tag whose names match the provided + * parameter, whether a template tag on a containing function + * expression, or a template tag on a variable declaration whose + * initializer is the containing function. The tags closest to the + * node are returned first, so in the previous example, the template + * tag on the containing function expression would be first. + */ + function getJSDocTypeParameterTags(param) { + var name = param.name.escapedText; + return getJSDocTags(param.parent).filter(function (tag) { + return ts.isJSDocTemplateTag(tag) && tag.typeParameters.some(function (tp) { return tp.name.escapedText === name; }); + }); + } + ts.getJSDocTypeParameterTags = getJSDocTypeParameterTags; + /** + * Return true if the node has JSDoc parameter tags. + * + * @remarks Includes parameter tags that are not directly on the node, + * for example on a variable declaration whose initializer is a function expression. + */ + function hasJSDocParameterTags(node) { + return !!getFirstJSDocTag(node, ts.isJSDocParameterTag); + } + ts.hasJSDocParameterTags = hasJSDocParameterTags; + /** Gets the JSDoc augments tag for the node if present */ + function getJSDocAugmentsTag(node) { + return getFirstJSDocTag(node, ts.isJSDocAugmentsTag); + } + ts.getJSDocAugmentsTag = getJSDocAugmentsTag; + /** Gets the JSDoc class tag for the node if present */ + function getJSDocClassTag(node) { + return getFirstJSDocTag(node, ts.isJSDocClassTag); + } + ts.getJSDocClassTag = getJSDocClassTag; + /** Gets the JSDoc enum tag for the node if present */ + function getJSDocEnumTag(node) { + return getFirstJSDocTag(node, ts.isJSDocEnumTag); + } + ts.getJSDocEnumTag = getJSDocEnumTag; + /** Gets the JSDoc this tag for the node if present */ + function getJSDocThisTag(node) { + return getFirstJSDocTag(node, ts.isJSDocThisTag); + } + ts.getJSDocThisTag = getJSDocThisTag; + /** Gets the JSDoc return tag for the node if present */ + function getJSDocReturnTag(node) { + return getFirstJSDocTag(node, ts.isJSDocReturnTag); + } + ts.getJSDocReturnTag = getJSDocReturnTag; + /** Gets the JSDoc template tag for the node if present */ + function getJSDocTemplateTag(node) { + return getFirstJSDocTag(node, ts.isJSDocTemplateTag); + } + ts.getJSDocTemplateTag = getJSDocTemplateTag; + /** Gets the JSDoc type tag for the node if present and valid */ + function getJSDocTypeTag(node) { + // We should have already issued an error if there were multiple type jsdocs, so just use the first one. + var tag = getFirstJSDocTag(node, ts.isJSDocTypeTag); + if (tag && tag.typeExpression && tag.typeExpression.type) { + return tag; + } + return undefined; + } + ts.getJSDocTypeTag = getJSDocTypeTag; + /** + * Gets the type node for the node if provided via JSDoc. + * + * @remarks The search includes any JSDoc param tag that relates + * to the provided parameter, for example a type tag on the + * parameter itself, or a param tag on a containing function + * expression, or a param tag on a variable declaration whose + * initializer is the containing function. The tags closest to the + * node are examined first, so in the previous example, the type + * tag directly on the node would be returned. + */ + function getJSDocType(node) { + var tag = getFirstJSDocTag(node, ts.isJSDocTypeTag); + if (!tag && ts.isParameter(node)) { + tag = ts.find(getJSDocParameterTags(node), function (tag) { return !!tag.typeExpression; }); + } + return tag && tag.typeExpression && tag.typeExpression.type; + } + ts.getJSDocType = getJSDocType; + /** + * Gets the return type node for the node if provided via JSDoc return tag or type tag. + * + * @remarks `getJSDocReturnTag` just gets the whole JSDoc tag. This function + * gets the type from inside the braces, after the fat arrow, etc. + */ + function getJSDocReturnType(node) { + var returnTag = getJSDocReturnTag(node); + if (returnTag && returnTag.typeExpression) { + return returnTag.typeExpression.type; + } + var typeTag = getJSDocTypeTag(node); + if (typeTag && typeTag.typeExpression) { + var type = typeTag.typeExpression.type; + if (ts.isTypeLiteralNode(type)) { + var sig = ts.find(type.members, ts.isCallSignatureDeclaration); + return sig && sig.type; + } + if (ts.isFunctionTypeNode(type)) { + return type.type; + } + } + } + ts.getJSDocReturnType = getJSDocReturnType; + /** Get all JSDoc tags related to a node, including those on parent nodes. */ + function getJSDocTags(node) { + var tags = node.jsDocCache; + // If cache is 'null', that means we did the work of searching for JSDoc tags and came up with nothing. + if (tags === undefined) { + var comments = ts.getJSDocCommentsAndTags(node); + ts.Debug.assert(comments.length < 2 || comments[0] !== comments[1]); + node.jsDocCache = tags = ts.flatMap(comments, function (j) { return ts.isJSDoc(j) ? j.tags : j; }); + } + return tags; + } + ts.getJSDocTags = getJSDocTags; + /** Get the first JSDoc tag of a specified kind, or undefined if not present. */ + function getFirstJSDocTag(node, predicate) { + return ts.find(getJSDocTags(node), predicate); + } + /** Gets all JSDoc tags of a specified kind, or undefined if not present. */ + function getAllJSDocTagsOfKind(node, kind) { + return getJSDocTags(node).filter(function (doc) { return doc.kind === kind; }); + } + ts.getAllJSDocTagsOfKind = getAllJSDocTagsOfKind; + /** + * Gets the effective type parameters. If the node was parsed in a + * JavaScript file, gets the type parameters from the `@template` tag from JSDoc. + */ + function getEffectiveTypeParameterDeclarations(node) { + if (ts.isJSDocSignature(node)) { + return ts.emptyArray; + } + if (ts.isJSDocTypeAlias(node)) { + ts.Debug.assert(node.parent.kind === 291 /* JSDocComment */); + return ts.flatMap(node.parent.tags, function (tag) { return ts.isJSDocTemplateTag(tag) ? tag.typeParameters : undefined; }); + } + if (node.typeParameters) { + return node.typeParameters; + } + if (ts.isInJSFile(node)) { + var decls = ts.getJSDocTypeParameterDeclarations(node); + if (decls.length) { + return decls; + } + var typeTag = getJSDocType(node); + if (typeTag && ts.isFunctionTypeNode(typeTag) && typeTag.typeParameters) { + return typeTag.typeParameters; + } + } + return ts.emptyArray; + } + ts.getEffectiveTypeParameterDeclarations = getEffectiveTypeParameterDeclarations; + function getEffectiveConstraintOfTypeParameter(node) { + return node.constraint ? node.constraint + : ts.isJSDocTemplateTag(node.parent) && node === node.parent.typeParameters[0] + ? node.parent.constraint + : undefined; + } + ts.getEffectiveConstraintOfTypeParameter = getEffectiveConstraintOfTypeParameter; +})(ts || (ts = {})); +// Simple node tests of the form `node.kind === SyntaxKind.Foo`. +(function (ts) { + // Literals + function isNumericLiteral(node) { + return node.kind === 8 /* NumericLiteral */; + } + ts.isNumericLiteral = isNumericLiteral; + function isBigIntLiteral(node) { + return node.kind === 9 /* BigIntLiteral */; + } + ts.isBigIntLiteral = isBigIntLiteral; + function isStringLiteral(node) { + return node.kind === 10 /* StringLiteral */; + } + ts.isStringLiteral = isStringLiteral; + function isJsxText(node) { + return node.kind === 11 /* JsxText */; + } + ts.isJsxText = isJsxText; + function isRegularExpressionLiteral(node) { + return node.kind === 13 /* RegularExpressionLiteral */; + } + ts.isRegularExpressionLiteral = isRegularExpressionLiteral; + function isNoSubstitutionTemplateLiteral(node) { + return node.kind === 14 /* NoSubstitutionTemplateLiteral */; + } + ts.isNoSubstitutionTemplateLiteral = isNoSubstitutionTemplateLiteral; + // Pseudo-literals + function isTemplateHead(node) { + return node.kind === 15 /* TemplateHead */; + } + ts.isTemplateHead = isTemplateHead; + function isTemplateMiddle(node) { + return node.kind === 16 /* TemplateMiddle */; + } + ts.isTemplateMiddle = isTemplateMiddle; + function isTemplateTail(node) { + return node.kind === 17 /* TemplateTail */; + } + ts.isTemplateTail = isTemplateTail; + function isIdentifier(node) { + return node.kind === 72 /* Identifier */; + } + ts.isIdentifier = isIdentifier; + // Names + function isQualifiedName(node) { + return node.kind === 148 /* QualifiedName */; + } + ts.isQualifiedName = isQualifiedName; + function isComputedPropertyName(node) { + return node.kind === 149 /* ComputedPropertyName */; + } + ts.isComputedPropertyName = isComputedPropertyName; + // Signature elements + function isTypeParameterDeclaration(node) { + return node.kind === 150 /* TypeParameter */; + } + ts.isTypeParameterDeclaration = isTypeParameterDeclaration; + function isParameter(node) { + return node.kind === 151 /* Parameter */; + } + ts.isParameter = isParameter; + function isDecorator(node) { + return node.kind === 152 /* Decorator */; + } + ts.isDecorator = isDecorator; + // TypeMember + function isPropertySignature(node) { + return node.kind === 153 /* PropertySignature */; + } + ts.isPropertySignature = isPropertySignature; + function isPropertyDeclaration(node) { + return node.kind === 154 /* PropertyDeclaration */; + } + ts.isPropertyDeclaration = isPropertyDeclaration; + function isMethodSignature(node) { + return node.kind === 155 /* MethodSignature */; + } + ts.isMethodSignature = isMethodSignature; + function isMethodDeclaration(node) { + return node.kind === 156 /* MethodDeclaration */; + } + ts.isMethodDeclaration = isMethodDeclaration; + function isConstructorDeclaration(node) { + return node.kind === 157 /* Constructor */; + } + ts.isConstructorDeclaration = isConstructorDeclaration; + function isGetAccessorDeclaration(node) { + return node.kind === 158 /* GetAccessor */; + } + ts.isGetAccessorDeclaration = isGetAccessorDeclaration; + function isSetAccessorDeclaration(node) { + return node.kind === 159 /* SetAccessor */; + } + ts.isSetAccessorDeclaration = isSetAccessorDeclaration; + function isCallSignatureDeclaration(node) { + return node.kind === 160 /* CallSignature */; + } + ts.isCallSignatureDeclaration = isCallSignatureDeclaration; + function isConstructSignatureDeclaration(node) { + return node.kind === 161 /* ConstructSignature */; + } + ts.isConstructSignatureDeclaration = isConstructSignatureDeclaration; + function isIndexSignatureDeclaration(node) { + return node.kind === 162 /* IndexSignature */; + } + ts.isIndexSignatureDeclaration = isIndexSignatureDeclaration; + /* @internal */ + function isGetOrSetAccessorDeclaration(node) { + return node.kind === 159 /* SetAccessor */ || node.kind === 158 /* GetAccessor */; + } + ts.isGetOrSetAccessorDeclaration = isGetOrSetAccessorDeclaration; + // Type + function isTypePredicateNode(node) { + return node.kind === 163 /* TypePredicate */; + } + ts.isTypePredicateNode = isTypePredicateNode; + function isTypeReferenceNode(node) { + return node.kind === 164 /* TypeReference */; + } + ts.isTypeReferenceNode = isTypeReferenceNode; + function isFunctionTypeNode(node) { + return node.kind === 165 /* FunctionType */; + } + ts.isFunctionTypeNode = isFunctionTypeNode; + function isConstructorTypeNode(node) { + return node.kind === 166 /* ConstructorType */; + } + ts.isConstructorTypeNode = isConstructorTypeNode; + function isTypeQueryNode(node) { + return node.kind === 167 /* TypeQuery */; + } + ts.isTypeQueryNode = isTypeQueryNode; + function isTypeLiteralNode(node) { + return node.kind === 168 /* TypeLiteral */; + } + ts.isTypeLiteralNode = isTypeLiteralNode; + function isArrayTypeNode(node) { + return node.kind === 169 /* ArrayType */; + } + ts.isArrayTypeNode = isArrayTypeNode; + function isTupleTypeNode(node) { + return node.kind === 170 /* TupleType */; + } + ts.isTupleTypeNode = isTupleTypeNode; + function isUnionTypeNode(node) { + return node.kind === 173 /* UnionType */; + } + ts.isUnionTypeNode = isUnionTypeNode; + function isIntersectionTypeNode(node) { + return node.kind === 174 /* IntersectionType */; + } + ts.isIntersectionTypeNode = isIntersectionTypeNode; + function isConditionalTypeNode(node) { + return node.kind === 175 /* ConditionalType */; + } + ts.isConditionalTypeNode = isConditionalTypeNode; + function isInferTypeNode(node) { + return node.kind === 176 /* InferType */; + } + ts.isInferTypeNode = isInferTypeNode; + function isParenthesizedTypeNode(node) { + return node.kind === 177 /* ParenthesizedType */; + } + ts.isParenthesizedTypeNode = isParenthesizedTypeNode; + function isThisTypeNode(node) { + return node.kind === 178 /* ThisType */; + } + ts.isThisTypeNode = isThisTypeNode; + function isTypeOperatorNode(node) { + return node.kind === 179 /* TypeOperator */; + } + ts.isTypeOperatorNode = isTypeOperatorNode; + function isIndexedAccessTypeNode(node) { + return node.kind === 180 /* IndexedAccessType */; + } + ts.isIndexedAccessTypeNode = isIndexedAccessTypeNode; + function isMappedTypeNode(node) { + return node.kind === 181 /* MappedType */; + } + ts.isMappedTypeNode = isMappedTypeNode; + function isLiteralTypeNode(node) { + return node.kind === 182 /* LiteralType */; + } + ts.isLiteralTypeNode = isLiteralTypeNode; + function isImportTypeNode(node) { + return node.kind === 183 /* ImportType */; + } + ts.isImportTypeNode = isImportTypeNode; + // Binding patterns + function isObjectBindingPattern(node) { + return node.kind === 184 /* ObjectBindingPattern */; + } + ts.isObjectBindingPattern = isObjectBindingPattern; + function isArrayBindingPattern(node) { + return node.kind === 185 /* ArrayBindingPattern */; + } + ts.isArrayBindingPattern = isArrayBindingPattern; + function isBindingElement(node) { + return node.kind === 186 /* BindingElement */; + } + ts.isBindingElement = isBindingElement; + // Expression + function isArrayLiteralExpression(node) { + return node.kind === 187 /* ArrayLiteralExpression */; + } + ts.isArrayLiteralExpression = isArrayLiteralExpression; + function isObjectLiteralExpression(node) { + return node.kind === 188 /* ObjectLiteralExpression */; + } + ts.isObjectLiteralExpression = isObjectLiteralExpression; + function isPropertyAccessExpression(node) { + return node.kind === 189 /* PropertyAccessExpression */; + } + ts.isPropertyAccessExpression = isPropertyAccessExpression; + function isElementAccessExpression(node) { + return node.kind === 190 /* ElementAccessExpression */; + } + ts.isElementAccessExpression = isElementAccessExpression; + function isCallExpression(node) { + return node.kind === 191 /* CallExpression */; + } + ts.isCallExpression = isCallExpression; + function isNewExpression(node) { + return node.kind === 192 /* NewExpression */; + } + ts.isNewExpression = isNewExpression; + function isTaggedTemplateExpression(node) { + return node.kind === 193 /* TaggedTemplateExpression */; + } + ts.isTaggedTemplateExpression = isTaggedTemplateExpression; + function isTypeAssertion(node) { + return node.kind === 194 /* TypeAssertionExpression */; + } + ts.isTypeAssertion = isTypeAssertion; + function isParenthesizedExpression(node) { + return node.kind === 195 /* ParenthesizedExpression */; + } + ts.isParenthesizedExpression = isParenthesizedExpression; + function skipPartiallyEmittedExpressions(node) { + while (node.kind === 308 /* PartiallyEmittedExpression */) { + node = node.expression; + } + return node; + } + ts.skipPartiallyEmittedExpressions = skipPartiallyEmittedExpressions; + function isFunctionExpression(node) { + return node.kind === 196 /* FunctionExpression */; + } + ts.isFunctionExpression = isFunctionExpression; + function isArrowFunction(node) { + return node.kind === 197 /* ArrowFunction */; + } + ts.isArrowFunction = isArrowFunction; + function isDeleteExpression(node) { + return node.kind === 198 /* DeleteExpression */; + } + ts.isDeleteExpression = isDeleteExpression; + function isTypeOfExpression(node) { + return node.kind === 199 /* TypeOfExpression */; + } + ts.isTypeOfExpression = isTypeOfExpression; + function isVoidExpression(node) { + return node.kind === 200 /* VoidExpression */; + } + ts.isVoidExpression = isVoidExpression; + function isAwaitExpression(node) { + return node.kind === 201 /* AwaitExpression */; + } + ts.isAwaitExpression = isAwaitExpression; + function isPrefixUnaryExpression(node) { + return node.kind === 202 /* PrefixUnaryExpression */; + } + ts.isPrefixUnaryExpression = isPrefixUnaryExpression; + function isPostfixUnaryExpression(node) { + return node.kind === 203 /* PostfixUnaryExpression */; + } + ts.isPostfixUnaryExpression = isPostfixUnaryExpression; + function isBinaryExpression(node) { + return node.kind === 204 /* BinaryExpression */; + } + ts.isBinaryExpression = isBinaryExpression; + function isConditionalExpression(node) { + return node.kind === 205 /* ConditionalExpression */; + } + ts.isConditionalExpression = isConditionalExpression; + function isTemplateExpression(node) { + return node.kind === 206 /* TemplateExpression */; + } + ts.isTemplateExpression = isTemplateExpression; + function isYieldExpression(node) { + return node.kind === 207 /* YieldExpression */; + } + ts.isYieldExpression = isYieldExpression; + function isSpreadElement(node) { + return node.kind === 208 /* SpreadElement */; + } + ts.isSpreadElement = isSpreadElement; + function isClassExpression(node) { + return node.kind === 209 /* ClassExpression */; + } + ts.isClassExpression = isClassExpression; + function isOmittedExpression(node) { + return node.kind === 210 /* OmittedExpression */; + } + ts.isOmittedExpression = isOmittedExpression; + function isExpressionWithTypeArguments(node) { + return node.kind === 211 /* ExpressionWithTypeArguments */; + } + ts.isExpressionWithTypeArguments = isExpressionWithTypeArguments; + function isAsExpression(node) { + return node.kind === 212 /* AsExpression */; + } + ts.isAsExpression = isAsExpression; + function isNonNullExpression(node) { + return node.kind === 213 /* NonNullExpression */; + } + ts.isNonNullExpression = isNonNullExpression; + function isMetaProperty(node) { + return node.kind === 214 /* MetaProperty */; + } + ts.isMetaProperty = isMetaProperty; + // Misc + function isTemplateSpan(node) { + return node.kind === 216 /* TemplateSpan */; + } + ts.isTemplateSpan = isTemplateSpan; + function isSemicolonClassElement(node) { + return node.kind === 217 /* SemicolonClassElement */; + } + ts.isSemicolonClassElement = isSemicolonClassElement; + // Block + function isBlock(node) { + return node.kind === 218 /* Block */; + } + ts.isBlock = isBlock; + function isVariableStatement(node) { + return node.kind === 219 /* VariableStatement */; + } + ts.isVariableStatement = isVariableStatement; + function isEmptyStatement(node) { + return node.kind === 220 /* EmptyStatement */; + } + ts.isEmptyStatement = isEmptyStatement; + function isExpressionStatement(node) { + return node.kind === 221 /* ExpressionStatement */; + } + ts.isExpressionStatement = isExpressionStatement; + function isIfStatement(node) { + return node.kind === 222 /* IfStatement */; + } + ts.isIfStatement = isIfStatement; + function isDoStatement(node) { + return node.kind === 223 /* DoStatement */; + } + ts.isDoStatement = isDoStatement; + function isWhileStatement(node) { + return node.kind === 224 /* WhileStatement */; + } + ts.isWhileStatement = isWhileStatement; + function isForStatement(node) { + return node.kind === 225 /* ForStatement */; + } + ts.isForStatement = isForStatement; + function isForInStatement(node) { + return node.kind === 226 /* ForInStatement */; + } + ts.isForInStatement = isForInStatement; + function isForOfStatement(node) { + return node.kind === 227 /* ForOfStatement */; + } + ts.isForOfStatement = isForOfStatement; + function isContinueStatement(node) { + return node.kind === 228 /* ContinueStatement */; + } + ts.isContinueStatement = isContinueStatement; + function isBreakStatement(node) { + return node.kind === 229 /* BreakStatement */; + } + ts.isBreakStatement = isBreakStatement; + function isBreakOrContinueStatement(node) { + return node.kind === 229 /* BreakStatement */ || node.kind === 228 /* ContinueStatement */; + } + ts.isBreakOrContinueStatement = isBreakOrContinueStatement; + function isReturnStatement(node) { + return node.kind === 230 /* ReturnStatement */; + } + ts.isReturnStatement = isReturnStatement; + function isWithStatement(node) { + return node.kind === 231 /* WithStatement */; + } + ts.isWithStatement = isWithStatement; + function isSwitchStatement(node) { + return node.kind === 232 /* SwitchStatement */; + } + ts.isSwitchStatement = isSwitchStatement; + function isLabeledStatement(node) { + return node.kind === 233 /* LabeledStatement */; + } + ts.isLabeledStatement = isLabeledStatement; + function isThrowStatement(node) { + return node.kind === 234 /* ThrowStatement */; + } + ts.isThrowStatement = isThrowStatement; + function isTryStatement(node) { + return node.kind === 235 /* TryStatement */; + } + ts.isTryStatement = isTryStatement; + function isDebuggerStatement(node) { + return node.kind === 236 /* DebuggerStatement */; + } + ts.isDebuggerStatement = isDebuggerStatement; + function isVariableDeclaration(node) { + return node.kind === 237 /* VariableDeclaration */; + } + ts.isVariableDeclaration = isVariableDeclaration; + function isVariableDeclarationList(node) { + return node.kind === 238 /* VariableDeclarationList */; + } + ts.isVariableDeclarationList = isVariableDeclarationList; + function isFunctionDeclaration(node) { + return node.kind === 239 /* FunctionDeclaration */; + } + ts.isFunctionDeclaration = isFunctionDeclaration; + function isClassDeclaration(node) { + return node.kind === 240 /* ClassDeclaration */; + } + ts.isClassDeclaration = isClassDeclaration; + function isInterfaceDeclaration(node) { + return node.kind === 241 /* InterfaceDeclaration */; + } + ts.isInterfaceDeclaration = isInterfaceDeclaration; + function isTypeAliasDeclaration(node) { + return node.kind === 242 /* TypeAliasDeclaration */; + } + ts.isTypeAliasDeclaration = isTypeAliasDeclaration; + function isEnumDeclaration(node) { + return node.kind === 243 /* EnumDeclaration */; + } + ts.isEnumDeclaration = isEnumDeclaration; + function isModuleDeclaration(node) { + return node.kind === 244 /* ModuleDeclaration */; + } + ts.isModuleDeclaration = isModuleDeclaration; + function isModuleBlock(node) { + return node.kind === 245 /* ModuleBlock */; + } + ts.isModuleBlock = isModuleBlock; + function isCaseBlock(node) { + return node.kind === 246 /* CaseBlock */; + } + ts.isCaseBlock = isCaseBlock; + function isNamespaceExportDeclaration(node) { + return node.kind === 247 /* NamespaceExportDeclaration */; + } + ts.isNamespaceExportDeclaration = isNamespaceExportDeclaration; + function isImportEqualsDeclaration(node) { + return node.kind === 248 /* ImportEqualsDeclaration */; + } + ts.isImportEqualsDeclaration = isImportEqualsDeclaration; + function isImportDeclaration(node) { + return node.kind === 249 /* ImportDeclaration */; + } + ts.isImportDeclaration = isImportDeclaration; + function isImportClause(node) { + return node.kind === 250 /* ImportClause */; + } + ts.isImportClause = isImportClause; + function isNamespaceImport(node) { + return node.kind === 251 /* NamespaceImport */; + } + ts.isNamespaceImport = isNamespaceImport; + function isNamedImports(node) { + return node.kind === 252 /* NamedImports */; + } + ts.isNamedImports = isNamedImports; + function isImportSpecifier(node) { + return node.kind === 253 /* ImportSpecifier */; + } + ts.isImportSpecifier = isImportSpecifier; + function isExportAssignment(node) { + return node.kind === 254 /* ExportAssignment */; + } + ts.isExportAssignment = isExportAssignment; + function isExportDeclaration(node) { + return node.kind === 255 /* ExportDeclaration */; + } + ts.isExportDeclaration = isExportDeclaration; + function isNamedExports(node) { + return node.kind === 256 /* NamedExports */; + } + ts.isNamedExports = isNamedExports; + function isExportSpecifier(node) { + return node.kind === 257 /* ExportSpecifier */; + } + ts.isExportSpecifier = isExportSpecifier; + function isMissingDeclaration(node) { + return node.kind === 258 /* MissingDeclaration */; + } + ts.isMissingDeclaration = isMissingDeclaration; + // Module References + function isExternalModuleReference(node) { + return node.kind === 259 /* ExternalModuleReference */; + } + ts.isExternalModuleReference = isExternalModuleReference; + // JSX + function isJsxElement(node) { + return node.kind === 260 /* JsxElement */; + } + ts.isJsxElement = isJsxElement; + function isJsxSelfClosingElement(node) { + return node.kind === 261 /* JsxSelfClosingElement */; + } + ts.isJsxSelfClosingElement = isJsxSelfClosingElement; + function isJsxOpeningElement(node) { + return node.kind === 262 /* JsxOpeningElement */; + } + ts.isJsxOpeningElement = isJsxOpeningElement; + function isJsxClosingElement(node) { + return node.kind === 263 /* JsxClosingElement */; + } + ts.isJsxClosingElement = isJsxClosingElement; + function isJsxFragment(node) { + return node.kind === 264 /* JsxFragment */; + } + ts.isJsxFragment = isJsxFragment; + function isJsxOpeningFragment(node) { + return node.kind === 265 /* JsxOpeningFragment */; + } + ts.isJsxOpeningFragment = isJsxOpeningFragment; + function isJsxClosingFragment(node) { + return node.kind === 266 /* JsxClosingFragment */; + } + ts.isJsxClosingFragment = isJsxClosingFragment; + function isJsxAttribute(node) { + return node.kind === 267 /* JsxAttribute */; + } + ts.isJsxAttribute = isJsxAttribute; + function isJsxAttributes(node) { + return node.kind === 268 /* JsxAttributes */; + } + ts.isJsxAttributes = isJsxAttributes; + function isJsxSpreadAttribute(node) { + return node.kind === 269 /* JsxSpreadAttribute */; + } + ts.isJsxSpreadAttribute = isJsxSpreadAttribute; + function isJsxExpression(node) { + return node.kind === 270 /* JsxExpression */; + } + ts.isJsxExpression = isJsxExpression; + // Clauses + function isCaseClause(node) { + return node.kind === 271 /* CaseClause */; + } + ts.isCaseClause = isCaseClause; + function isDefaultClause(node) { + return node.kind === 272 /* DefaultClause */; + } + ts.isDefaultClause = isDefaultClause; + function isHeritageClause(node) { + return node.kind === 273 /* HeritageClause */; + } + ts.isHeritageClause = isHeritageClause; + function isCatchClause(node) { + return node.kind === 274 /* CatchClause */; + } + ts.isCatchClause = isCatchClause; + // Property assignments + function isPropertyAssignment(node) { + return node.kind === 275 /* PropertyAssignment */; + } + ts.isPropertyAssignment = isPropertyAssignment; + function isShorthandPropertyAssignment(node) { + return node.kind === 276 /* ShorthandPropertyAssignment */; + } + ts.isShorthandPropertyAssignment = isShorthandPropertyAssignment; + function isSpreadAssignment(node) { + return node.kind === 277 /* SpreadAssignment */; + } + ts.isSpreadAssignment = isSpreadAssignment; + // Enum + function isEnumMember(node) { + return node.kind === 278 /* EnumMember */; + } + ts.isEnumMember = isEnumMember; + // Top-level nodes + function isSourceFile(node) { + return node.kind === 279 /* SourceFile */; + } + ts.isSourceFile = isSourceFile; + function isBundle(node) { + return node.kind === 280 /* Bundle */; + } + ts.isBundle = isBundle; + function isUnparsedSource(node) { + return node.kind === 281 /* UnparsedSource */; + } + ts.isUnparsedSource = isUnparsedSource; + // JSDoc + function isJSDocTypeExpression(node) { + return node.kind === 283 /* JSDocTypeExpression */; + } + ts.isJSDocTypeExpression = isJSDocTypeExpression; + function isJSDocAllType(node) { + return node.kind === 284 /* JSDocAllType */; + } + ts.isJSDocAllType = isJSDocAllType; + function isJSDocUnknownType(node) { + return node.kind === 285 /* JSDocUnknownType */; + } + ts.isJSDocUnknownType = isJSDocUnknownType; + function isJSDocNullableType(node) { + return node.kind === 286 /* JSDocNullableType */; + } + ts.isJSDocNullableType = isJSDocNullableType; + function isJSDocNonNullableType(node) { + return node.kind === 287 /* JSDocNonNullableType */; + } + ts.isJSDocNonNullableType = isJSDocNonNullableType; + function isJSDocOptionalType(node) { + return node.kind === 288 /* JSDocOptionalType */; + } + ts.isJSDocOptionalType = isJSDocOptionalType; + function isJSDocFunctionType(node) { + return node.kind === 289 /* JSDocFunctionType */; + } + ts.isJSDocFunctionType = isJSDocFunctionType; + function isJSDocVariadicType(node) { + return node.kind === 290 /* JSDocVariadicType */; + } + ts.isJSDocVariadicType = isJSDocVariadicType; + function isJSDoc(node) { + return node.kind === 291 /* JSDocComment */; + } + ts.isJSDoc = isJSDoc; + function isJSDocAugmentsTag(node) { + return node.kind === 295 /* JSDocAugmentsTag */; + } + ts.isJSDocAugmentsTag = isJSDocAugmentsTag; + function isJSDocClassTag(node) { + return node.kind === 296 /* JSDocClassTag */; + } + ts.isJSDocClassTag = isJSDocClassTag; + function isJSDocEnumTag(node) { + return node.kind === 298 /* JSDocEnumTag */; + } + ts.isJSDocEnumTag = isJSDocEnumTag; + function isJSDocThisTag(node) { + return node.kind === 301 /* JSDocThisTag */; + } + ts.isJSDocThisTag = isJSDocThisTag; + function isJSDocParameterTag(node) { + return node.kind === 299 /* JSDocParameterTag */; + } + ts.isJSDocParameterTag = isJSDocParameterTag; + function isJSDocReturnTag(node) { + return node.kind === 300 /* JSDocReturnTag */; + } + ts.isJSDocReturnTag = isJSDocReturnTag; + function isJSDocTypeTag(node) { + return node.kind === 302 /* JSDocTypeTag */; + } + ts.isJSDocTypeTag = isJSDocTypeTag; + function isJSDocTemplateTag(node) { + return node.kind === 303 /* JSDocTemplateTag */; + } + ts.isJSDocTemplateTag = isJSDocTemplateTag; + function isJSDocTypedefTag(node) { + return node.kind === 304 /* JSDocTypedefTag */; + } + ts.isJSDocTypedefTag = isJSDocTypedefTag; + function isJSDocPropertyTag(node) { + return node.kind === 305 /* JSDocPropertyTag */; + } + ts.isJSDocPropertyTag = isJSDocPropertyTag; + function isJSDocPropertyLikeTag(node) { + return node.kind === 305 /* JSDocPropertyTag */ || node.kind === 299 /* JSDocParameterTag */; + } + ts.isJSDocPropertyLikeTag = isJSDocPropertyLikeTag; + function isJSDocTypeLiteral(node) { + return node.kind === 292 /* JSDocTypeLiteral */; + } + ts.isJSDocTypeLiteral = isJSDocTypeLiteral; + function isJSDocCallbackTag(node) { + return node.kind === 297 /* JSDocCallbackTag */; + } + ts.isJSDocCallbackTag = isJSDocCallbackTag; + function isJSDocSignature(node) { + return node.kind === 293 /* JSDocSignature */; + } + ts.isJSDocSignature = isJSDocSignature; +})(ts || (ts = {})); +// Node tests +// +// All node tests in the following list should *not* reference parent pointers so that +// they may be used with transformations. +(function (ts) { + /* @internal */ + function isSyntaxList(n) { + return n.kind === 306 /* SyntaxList */; + } + ts.isSyntaxList = isSyntaxList; + /* @internal */ + function isNode(node) { + return isNodeKind(node.kind); + } + ts.isNode = isNode; + /* @internal */ + function isNodeKind(kind) { + return kind >= 148 /* FirstNode */; + } + ts.isNodeKind = isNodeKind; + /** + * True if node is of some token syntax kind. + * For example, this is true for an IfKeyword but not for an IfStatement. + * Literals are considered tokens, except TemplateLiteral, but does include TemplateHead/Middle/Tail. + */ + function isToken(n) { + return n.kind >= 0 /* FirstToken */ && n.kind <= 147 /* LastToken */; + } + ts.isToken = isToken; + // Node Arrays + /* @internal */ + function isNodeArray(array) { + return array.hasOwnProperty("pos") && array.hasOwnProperty("end"); + } + ts.isNodeArray = isNodeArray; + // Literals + /* @internal */ + function isLiteralKind(kind) { + return 8 /* FirstLiteralToken */ <= kind && kind <= 14 /* LastLiteralToken */; + } + ts.isLiteralKind = isLiteralKind; + function isLiteralExpression(node) { + return isLiteralKind(node.kind); + } + ts.isLiteralExpression = isLiteralExpression; + // Pseudo-literals + /* @internal */ + function isTemplateLiteralKind(kind) { + return 14 /* FirstTemplateToken */ <= kind && kind <= 17 /* LastTemplateToken */; + } + ts.isTemplateLiteralKind = isTemplateLiteralKind; + function isTemplateLiteralToken(node) { + return isTemplateLiteralKind(node.kind); + } + ts.isTemplateLiteralToken = isTemplateLiteralToken; + function isTemplateMiddleOrTemplateTail(node) { + var kind = node.kind; + return kind === 16 /* TemplateMiddle */ + || kind === 17 /* TemplateTail */; + } + ts.isTemplateMiddleOrTemplateTail = isTemplateMiddleOrTemplateTail; + function isImportOrExportSpecifier(node) { + return ts.isImportSpecifier(node) || ts.isExportSpecifier(node); + } + ts.isImportOrExportSpecifier = isImportOrExportSpecifier; + function isStringTextContainingNode(node) { + return node.kind === 10 /* StringLiteral */ || isTemplateLiteralKind(node.kind); + } + ts.isStringTextContainingNode = isStringTextContainingNode; + // Identifiers + /* @internal */ + function isGeneratedIdentifier(node) { + return ts.isIdentifier(node) && (node.autoGenerateFlags & 7 /* KindMask */) > 0 /* None */; + } + ts.isGeneratedIdentifier = isGeneratedIdentifier; + // Keywords + /* @internal */ + function isModifierKind(token) { + switch (token) { + case 118 /* AbstractKeyword */: + case 121 /* AsyncKeyword */: + case 77 /* ConstKeyword */: + case 125 /* DeclareKeyword */: + case 80 /* DefaultKeyword */: + case 85 /* ExportKeyword */: + case 115 /* PublicKeyword */: + case 113 /* PrivateKeyword */: + case 114 /* ProtectedKeyword */: + case 133 /* ReadonlyKeyword */: + case 116 /* StaticKeyword */: + return true; + } + return false; + } + ts.isModifierKind = isModifierKind; + /* @internal */ + function isParameterPropertyModifier(kind) { + return !!(ts.modifierToFlag(kind) & 92 /* ParameterPropertyModifier */); + } + ts.isParameterPropertyModifier = isParameterPropertyModifier; + /* @internal */ + function isClassMemberModifier(idToken) { + return isParameterPropertyModifier(idToken) || idToken === 116 /* StaticKeyword */; + } + ts.isClassMemberModifier = isClassMemberModifier; + function isModifier(node) { + return isModifierKind(node.kind); + } + ts.isModifier = isModifier; + function isEntityName(node) { + var kind = node.kind; + return kind === 148 /* QualifiedName */ + || kind === 72 /* Identifier */; + } + ts.isEntityName = isEntityName; + function isPropertyName(node) { + var kind = node.kind; + return kind === 72 /* Identifier */ + || kind === 10 /* StringLiteral */ + || kind === 8 /* NumericLiteral */ + || kind === 149 /* ComputedPropertyName */; + } + ts.isPropertyName = isPropertyName; + function isBindingName(node) { + var kind = node.kind; + return kind === 72 /* Identifier */ + || kind === 184 /* ObjectBindingPattern */ + || kind === 185 /* ArrayBindingPattern */; + } + ts.isBindingName = isBindingName; + // Functions + function isFunctionLike(node) { + return node && isFunctionLikeKind(node.kind); + } + ts.isFunctionLike = isFunctionLike; + /* @internal */ + function isFunctionLikeDeclaration(node) { + return node && isFunctionLikeDeclarationKind(node.kind); + } + ts.isFunctionLikeDeclaration = isFunctionLikeDeclaration; + function isFunctionLikeDeclarationKind(kind) { + switch (kind) { + case 239 /* FunctionDeclaration */: + case 156 /* MethodDeclaration */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + return true; + default: + return false; + } + } + /* @internal */ + function isFunctionLikeKind(kind) { + switch (kind) { + case 155 /* MethodSignature */: + case 160 /* CallSignature */: + case 293 /* JSDocSignature */: + case 161 /* ConstructSignature */: + case 162 /* IndexSignature */: + case 165 /* FunctionType */: + case 289 /* JSDocFunctionType */: + case 166 /* ConstructorType */: + return true; + default: + return isFunctionLikeDeclarationKind(kind); + } + } + ts.isFunctionLikeKind = isFunctionLikeKind; + /* @internal */ + function isFunctionOrModuleBlock(node) { + return ts.isSourceFile(node) || ts.isModuleBlock(node) || ts.isBlock(node) && isFunctionLike(node.parent); + } + ts.isFunctionOrModuleBlock = isFunctionOrModuleBlock; + // Classes + function isClassElement(node) { + var kind = node.kind; + return kind === 157 /* Constructor */ + || kind === 154 /* PropertyDeclaration */ + || kind === 156 /* MethodDeclaration */ + || kind === 158 /* GetAccessor */ + || kind === 159 /* SetAccessor */ + || kind === 162 /* IndexSignature */ + || kind === 217 /* SemicolonClassElement */; + } + ts.isClassElement = isClassElement; + function isClassLike(node) { + return node && (node.kind === 240 /* ClassDeclaration */ || node.kind === 209 /* ClassExpression */); + } + ts.isClassLike = isClassLike; + function isAccessor(node) { + return node && (node.kind === 158 /* GetAccessor */ || node.kind === 159 /* SetAccessor */); + } + ts.isAccessor = isAccessor; + /* @internal */ + function isMethodOrAccessor(node) { + switch (node.kind) { + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + return true; + default: + return false; + } + } + ts.isMethodOrAccessor = isMethodOrAccessor; + // Type members + function isTypeElement(node) { + var kind = node.kind; + return kind === 161 /* ConstructSignature */ + || kind === 160 /* CallSignature */ + || kind === 153 /* PropertySignature */ + || kind === 155 /* MethodSignature */ + || kind === 162 /* IndexSignature */; + } + ts.isTypeElement = isTypeElement; + function isClassOrTypeElement(node) { + return isTypeElement(node) || isClassElement(node); + } + ts.isClassOrTypeElement = isClassOrTypeElement; + function isObjectLiteralElementLike(node) { + var kind = node.kind; + return kind === 275 /* PropertyAssignment */ + || kind === 276 /* ShorthandPropertyAssignment */ + || kind === 277 /* SpreadAssignment */ + || kind === 156 /* MethodDeclaration */ + || kind === 158 /* GetAccessor */ + || kind === 159 /* SetAccessor */; + } + ts.isObjectLiteralElementLike = isObjectLiteralElementLike; + // Type + /** + * Node test that determines whether a node is a valid type node. + * This differs from the `isPartOfTypeNode` function which determines whether a node is *part* + * of a TypeNode. + */ + function isTypeNode(node) { + return ts.isTypeNodeKind(node.kind); + } + ts.isTypeNode = isTypeNode; + function isFunctionOrConstructorTypeNode(node) { + switch (node.kind) { + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + return true; + } + return false; + } + ts.isFunctionOrConstructorTypeNode = isFunctionOrConstructorTypeNode; + // Binding patterns + /* @internal */ + function isBindingPattern(node) { + if (node) { + var kind = node.kind; + return kind === 185 /* ArrayBindingPattern */ + || kind === 184 /* ObjectBindingPattern */; + } + return false; + } + ts.isBindingPattern = isBindingPattern; + /* @internal */ + function isAssignmentPattern(node) { + var kind = node.kind; + return kind === 187 /* ArrayLiteralExpression */ + || kind === 188 /* ObjectLiteralExpression */; + } + ts.isAssignmentPattern = isAssignmentPattern; + /* @internal */ + function isArrayBindingElement(node) { + var kind = node.kind; + return kind === 186 /* BindingElement */ + || kind === 210 /* OmittedExpression */; + } + ts.isArrayBindingElement = isArrayBindingElement; + /** + * Determines whether the BindingOrAssignmentElement is a BindingElement-like declaration + */ + /* @internal */ + function isDeclarationBindingElement(bindingElement) { + switch (bindingElement.kind) { + case 237 /* VariableDeclaration */: + case 151 /* Parameter */: + case 186 /* BindingElement */: + return true; + } + return false; + } + ts.isDeclarationBindingElement = isDeclarationBindingElement; + /** + * Determines whether a node is a BindingOrAssignmentPattern + */ + /* @internal */ + function isBindingOrAssignmentPattern(node) { + return isObjectBindingOrAssignmentPattern(node) + || isArrayBindingOrAssignmentPattern(node); + } + ts.isBindingOrAssignmentPattern = isBindingOrAssignmentPattern; + /** + * Determines whether a node is an ObjectBindingOrAssignmentPattern + */ + /* @internal */ + function isObjectBindingOrAssignmentPattern(node) { + switch (node.kind) { + case 184 /* ObjectBindingPattern */: + case 188 /* ObjectLiteralExpression */: + return true; + } + return false; + } + ts.isObjectBindingOrAssignmentPattern = isObjectBindingOrAssignmentPattern; + /** + * Determines whether a node is an ArrayBindingOrAssignmentPattern + */ + /* @internal */ + function isArrayBindingOrAssignmentPattern(node) { + switch (node.kind) { + case 185 /* ArrayBindingPattern */: + case 187 /* ArrayLiteralExpression */: + return true; + } + return false; + } + ts.isArrayBindingOrAssignmentPattern = isArrayBindingOrAssignmentPattern; + /* @internal */ + function isPropertyAccessOrQualifiedNameOrImportTypeNode(node) { + var kind = node.kind; + return kind === 189 /* PropertyAccessExpression */ + || kind === 148 /* QualifiedName */ + || kind === 183 /* ImportType */; + } + ts.isPropertyAccessOrQualifiedNameOrImportTypeNode = isPropertyAccessOrQualifiedNameOrImportTypeNode; + // Expression + function isPropertyAccessOrQualifiedName(node) { + var kind = node.kind; + return kind === 189 /* PropertyAccessExpression */ + || kind === 148 /* QualifiedName */; + } + ts.isPropertyAccessOrQualifiedName = isPropertyAccessOrQualifiedName; + function isCallLikeExpression(node) { + switch (node.kind) { + case 262 /* JsxOpeningElement */: + case 261 /* JsxSelfClosingElement */: + case 191 /* CallExpression */: + case 192 /* NewExpression */: + case 193 /* TaggedTemplateExpression */: + case 152 /* Decorator */: + return true; + default: + return false; + } + } + ts.isCallLikeExpression = isCallLikeExpression; + function isCallOrNewExpression(node) { + return node.kind === 191 /* CallExpression */ || node.kind === 192 /* NewExpression */; + } + ts.isCallOrNewExpression = isCallOrNewExpression; + function isTemplateLiteral(node) { + var kind = node.kind; + return kind === 206 /* TemplateExpression */ + || kind === 14 /* NoSubstitutionTemplateLiteral */; + } + ts.isTemplateLiteral = isTemplateLiteral; + /* @internal */ + function isLeftHandSideExpression(node) { + return isLeftHandSideExpressionKind(ts.skipPartiallyEmittedExpressions(node).kind); + } + ts.isLeftHandSideExpression = isLeftHandSideExpression; + function isLeftHandSideExpressionKind(kind) { + switch (kind) { + case 189 /* PropertyAccessExpression */: + case 190 /* ElementAccessExpression */: + case 192 /* NewExpression */: + case 191 /* CallExpression */: + case 260 /* JsxElement */: + case 261 /* JsxSelfClosingElement */: + case 264 /* JsxFragment */: + case 193 /* TaggedTemplateExpression */: + case 187 /* ArrayLiteralExpression */: + case 195 /* ParenthesizedExpression */: + case 188 /* ObjectLiteralExpression */: + case 209 /* ClassExpression */: + case 196 /* FunctionExpression */: + case 72 /* Identifier */: + case 13 /* RegularExpressionLiteral */: + case 8 /* NumericLiteral */: + case 9 /* BigIntLiteral */: + case 10 /* StringLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: + case 206 /* TemplateExpression */: + case 87 /* FalseKeyword */: + case 96 /* NullKeyword */: + case 100 /* ThisKeyword */: + case 102 /* TrueKeyword */: + case 98 /* SuperKeyword */: + case 213 /* NonNullExpression */: + case 214 /* MetaProperty */: + case 92 /* ImportKeyword */: // technically this is only an Expression if it's in a CallExpression + return true; + default: + return false; + } + } + /* @internal */ + function isUnaryExpression(node) { + return isUnaryExpressionKind(ts.skipPartiallyEmittedExpressions(node).kind); + } + ts.isUnaryExpression = isUnaryExpression; + function isUnaryExpressionKind(kind) { + switch (kind) { + case 202 /* PrefixUnaryExpression */: + case 203 /* PostfixUnaryExpression */: + case 198 /* DeleteExpression */: + case 199 /* TypeOfExpression */: + case 200 /* VoidExpression */: + case 201 /* AwaitExpression */: + case 194 /* TypeAssertionExpression */: + return true; + default: + return isLeftHandSideExpressionKind(kind); + } + } + /* @internal */ + function isUnaryExpressionWithWrite(expr) { + switch (expr.kind) { + case 203 /* PostfixUnaryExpression */: + return true; + case 202 /* PrefixUnaryExpression */: + return expr.operator === 44 /* PlusPlusToken */ || + expr.operator === 45 /* MinusMinusToken */; + default: + return false; + } + } + ts.isUnaryExpressionWithWrite = isUnaryExpressionWithWrite; + /* @internal */ + /** + * Determines whether a node is an expression based only on its kind. + * Use `isExpressionNode` if not in transforms. + */ + function isExpression(node) { + return isExpressionKind(ts.skipPartiallyEmittedExpressions(node).kind); + } + ts.isExpression = isExpression; + function isExpressionKind(kind) { + switch (kind) { + case 205 /* ConditionalExpression */: + case 207 /* YieldExpression */: + case 197 /* ArrowFunction */: + case 204 /* BinaryExpression */: + case 208 /* SpreadElement */: + case 212 /* AsExpression */: + case 210 /* OmittedExpression */: + case 309 /* CommaListExpression */: + case 308 /* PartiallyEmittedExpression */: + return true; + default: + return isUnaryExpressionKind(kind); + } + } + function isAssertionExpression(node) { + var kind = node.kind; + return kind === 194 /* TypeAssertionExpression */ + || kind === 212 /* AsExpression */; + } + ts.isAssertionExpression = isAssertionExpression; + /* @internal */ + function isPartiallyEmittedExpression(node) { + return node.kind === 308 /* PartiallyEmittedExpression */; + } + ts.isPartiallyEmittedExpression = isPartiallyEmittedExpression; + /* @internal */ + function isNotEmittedStatement(node) { + return node.kind === 307 /* NotEmittedStatement */; + } + ts.isNotEmittedStatement = isNotEmittedStatement; + /* @internal */ + function isNotEmittedOrPartiallyEmittedNode(node) { + return isNotEmittedStatement(node) + || isPartiallyEmittedExpression(node); + } + ts.isNotEmittedOrPartiallyEmittedNode = isNotEmittedOrPartiallyEmittedNode; + function isIterationStatement(node, lookInLabeledStatements) { + switch (node.kind) { + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + case 223 /* DoStatement */: + case 224 /* WhileStatement */: + return true; + case 233 /* LabeledStatement */: + return lookInLabeledStatements && isIterationStatement(node.statement, lookInLabeledStatements); + } + return false; + } + ts.isIterationStatement = isIterationStatement; + /* @internal */ + function isForInOrOfStatement(node) { + return node.kind === 226 /* ForInStatement */ || node.kind === 227 /* ForOfStatement */; + } + ts.isForInOrOfStatement = isForInOrOfStatement; + // Element + /* @internal */ + function isConciseBody(node) { + return ts.isBlock(node) + || isExpression(node); + } + ts.isConciseBody = isConciseBody; + /* @internal */ + function isFunctionBody(node) { + return ts.isBlock(node); + } + ts.isFunctionBody = isFunctionBody; + /* @internal */ + function isForInitializer(node) { + return ts.isVariableDeclarationList(node) + || isExpression(node); + } + ts.isForInitializer = isForInitializer; + /* @internal */ + function isModuleBody(node) { + var kind = node.kind; + return kind === 245 /* ModuleBlock */ + || kind === 244 /* ModuleDeclaration */ + || kind === 72 /* Identifier */; + } + ts.isModuleBody = isModuleBody; + /* @internal */ + function isNamespaceBody(node) { + var kind = node.kind; + return kind === 245 /* ModuleBlock */ + || kind === 244 /* ModuleDeclaration */; + } + ts.isNamespaceBody = isNamespaceBody; + /* @internal */ + function isJSDocNamespaceBody(node) { + var kind = node.kind; + return kind === 72 /* Identifier */ + || kind === 244 /* ModuleDeclaration */; + } + ts.isJSDocNamespaceBody = isJSDocNamespaceBody; + /* @internal */ + function isNamedImportBindings(node) { + var kind = node.kind; + return kind === 252 /* NamedImports */ + || kind === 251 /* NamespaceImport */; + } + ts.isNamedImportBindings = isNamedImportBindings; + /* @internal */ + function isModuleOrEnumDeclaration(node) { + return node.kind === 244 /* ModuleDeclaration */ || node.kind === 243 /* EnumDeclaration */; + } + ts.isModuleOrEnumDeclaration = isModuleOrEnumDeclaration; + function isDeclarationKind(kind) { + return kind === 197 /* ArrowFunction */ + || kind === 186 /* BindingElement */ + || kind === 240 /* ClassDeclaration */ + || kind === 209 /* ClassExpression */ + || kind === 157 /* Constructor */ + || kind === 243 /* EnumDeclaration */ + || kind === 278 /* EnumMember */ + || kind === 257 /* ExportSpecifier */ + || kind === 239 /* FunctionDeclaration */ + || kind === 196 /* FunctionExpression */ + || kind === 158 /* GetAccessor */ + || kind === 250 /* ImportClause */ + || kind === 248 /* ImportEqualsDeclaration */ + || kind === 253 /* ImportSpecifier */ + || kind === 241 /* InterfaceDeclaration */ + || kind === 267 /* JsxAttribute */ + || kind === 156 /* MethodDeclaration */ + || kind === 155 /* MethodSignature */ + || kind === 244 /* ModuleDeclaration */ + || kind === 247 /* NamespaceExportDeclaration */ + || kind === 251 /* NamespaceImport */ + || kind === 151 /* Parameter */ + || kind === 275 /* PropertyAssignment */ + || kind === 154 /* PropertyDeclaration */ + || kind === 153 /* PropertySignature */ + || kind === 159 /* SetAccessor */ + || kind === 276 /* ShorthandPropertyAssignment */ + || kind === 242 /* TypeAliasDeclaration */ + || kind === 150 /* TypeParameter */ + || kind === 237 /* VariableDeclaration */ + || kind === 304 /* JSDocTypedefTag */ + || kind === 297 /* JSDocCallbackTag */ + || kind === 305 /* JSDocPropertyTag */; + } + function isDeclarationStatementKind(kind) { + return kind === 239 /* FunctionDeclaration */ + || kind === 258 /* MissingDeclaration */ + || kind === 240 /* ClassDeclaration */ + || kind === 241 /* InterfaceDeclaration */ + || kind === 242 /* TypeAliasDeclaration */ + || kind === 243 /* EnumDeclaration */ + || kind === 244 /* ModuleDeclaration */ + || kind === 249 /* ImportDeclaration */ + || kind === 248 /* ImportEqualsDeclaration */ + || kind === 255 /* ExportDeclaration */ + || kind === 254 /* ExportAssignment */ + || kind === 247 /* NamespaceExportDeclaration */; + } + function isStatementKindButNotDeclarationKind(kind) { + return kind === 229 /* BreakStatement */ + || kind === 228 /* ContinueStatement */ + || kind === 236 /* DebuggerStatement */ + || kind === 223 /* DoStatement */ + || kind === 221 /* ExpressionStatement */ + || kind === 220 /* EmptyStatement */ + || kind === 226 /* ForInStatement */ + || kind === 227 /* ForOfStatement */ + || kind === 225 /* ForStatement */ + || kind === 222 /* IfStatement */ + || kind === 233 /* LabeledStatement */ + || kind === 230 /* ReturnStatement */ + || kind === 232 /* SwitchStatement */ + || kind === 234 /* ThrowStatement */ + || kind === 235 /* TryStatement */ + || kind === 219 /* VariableStatement */ + || kind === 224 /* WhileStatement */ + || kind === 231 /* WithStatement */ + || kind === 307 /* NotEmittedStatement */ + || kind === 311 /* EndOfDeclarationMarker */ + || kind === 310 /* MergeDeclarationMarker */; + } + /* @internal */ + function isDeclaration(node) { + if (node.kind === 150 /* TypeParameter */) { + return node.parent.kind !== 303 /* JSDocTemplateTag */ || ts.isInJSFile(node); + } + return isDeclarationKind(node.kind); + } + ts.isDeclaration = isDeclaration; + /* @internal */ + function isDeclarationStatement(node) { + return isDeclarationStatementKind(node.kind); + } + ts.isDeclarationStatement = isDeclarationStatement; + /** + * Determines whether the node is a statement that is not also a declaration + */ + /* @internal */ + function isStatementButNotDeclaration(node) { + return isStatementKindButNotDeclarationKind(node.kind); + } + ts.isStatementButNotDeclaration = isStatementButNotDeclaration; + /* @internal */ + function isStatement(node) { + var kind = node.kind; + return isStatementKindButNotDeclarationKind(kind) + || isDeclarationStatementKind(kind) + || isBlockStatement(node); + } + ts.isStatement = isStatement; + function isBlockStatement(node) { + if (node.kind !== 218 /* Block */) + return false; + if (node.parent !== undefined) { + if (node.parent.kind === 235 /* TryStatement */ || node.parent.kind === 274 /* CatchClause */) { + return false; + } + } + return !ts.isFunctionBlock(node); + } + // Module references + /* @internal */ + function isModuleReference(node) { + var kind = node.kind; + return kind === 259 /* ExternalModuleReference */ + || kind === 148 /* QualifiedName */ + || kind === 72 /* Identifier */; + } + ts.isModuleReference = isModuleReference; + // JSX + /* @internal */ + function isJsxTagNameExpression(node) { + var kind = node.kind; + return kind === 100 /* ThisKeyword */ + || kind === 72 /* Identifier */ + || kind === 189 /* PropertyAccessExpression */; + } + ts.isJsxTagNameExpression = isJsxTagNameExpression; + /* @internal */ + function isJsxChild(node) { + var kind = node.kind; + return kind === 260 /* JsxElement */ + || kind === 270 /* JsxExpression */ + || kind === 261 /* JsxSelfClosingElement */ + || kind === 11 /* JsxText */ + || kind === 264 /* JsxFragment */; + } + ts.isJsxChild = isJsxChild; + /* @internal */ + function isJsxAttributeLike(node) { + var kind = node.kind; + return kind === 267 /* JsxAttribute */ + || kind === 269 /* JsxSpreadAttribute */; + } + ts.isJsxAttributeLike = isJsxAttributeLike; + /* @internal */ + function isStringLiteralOrJsxExpression(node) { + var kind = node.kind; + return kind === 10 /* StringLiteral */ + || kind === 270 /* JsxExpression */; + } + ts.isStringLiteralOrJsxExpression = isStringLiteralOrJsxExpression; + function isJsxOpeningLikeElement(node) { + var kind = node.kind; + return kind === 262 /* JsxOpeningElement */ + || kind === 261 /* JsxSelfClosingElement */; + } + ts.isJsxOpeningLikeElement = isJsxOpeningLikeElement; + // Clauses + function isCaseOrDefaultClause(node) { + var kind = node.kind; + return kind === 271 /* CaseClause */ + || kind === 272 /* DefaultClause */; + } + ts.isCaseOrDefaultClause = isCaseOrDefaultClause; + // JSDoc + /** True if node is of some JSDoc syntax kind. */ + /* @internal */ + function isJSDocNode(node) { + return node.kind >= 283 /* FirstJSDocNode */ && node.kind <= 305 /* LastJSDocNode */; + } + ts.isJSDocNode = isJSDocNode; + /** True if node is of a kind that may contain comment text. */ + function isJSDocCommentContainingNode(node) { + return node.kind === 291 /* JSDocComment */ || isJSDocTag(node) || ts.isJSDocTypeLiteral(node) || ts.isJSDocSignature(node); + } + ts.isJSDocCommentContainingNode = isJSDocCommentContainingNode; + // TODO: determine what this does before making it public. + /* @internal */ + function isJSDocTag(node) { + return node.kind >= 294 /* FirstJSDocTagNode */ && node.kind <= 305 /* LastJSDocTagNode */; + } + ts.isJSDocTag = isJSDocTag; + function isSetAccessor(node) { + return node.kind === 159 /* SetAccessor */; + } + ts.isSetAccessor = isSetAccessor; + function isGetAccessor(node) { + return node.kind === 158 /* GetAccessor */; + } + ts.isGetAccessor = isGetAccessor; + /** True if has jsdoc nodes attached to it. */ + /* @internal */ + // TODO: GH#19856 Would like to return `node is Node & { jsDoc: JSDoc[] }` but it causes long compile times + function hasJSDocNodes(node) { + var jsDoc = node.jsDoc; + return !!jsDoc && jsDoc.length > 0; + } + ts.hasJSDocNodes = hasJSDocNodes; + /** True if has type node attached to it. */ + /* @internal */ + function hasType(node) { + return !!node.type; + } + ts.hasType = hasType; + /** True if has initializer node attached to it. */ + /* @internal */ + function hasInitializer(node) { + return !!node.initializer; + } + ts.hasInitializer = hasInitializer; + /** True if has initializer node attached to it. */ + /* @internal */ + function hasOnlyExpressionInitializer(node) { + return hasInitializer(node) && !ts.isForStatement(node) && !ts.isForInStatement(node) && !ts.isForOfStatement(node) && !ts.isJsxAttribute(node); + } + ts.hasOnlyExpressionInitializer = hasOnlyExpressionInitializer; + function isObjectLiteralElement(node) { + return node.kind === 267 /* JsxAttribute */ || node.kind === 269 /* JsxSpreadAttribute */ || isObjectLiteralElementLike(node); + } + ts.isObjectLiteralElement = isObjectLiteralElement; + /* @internal */ + function isTypeReferenceType(node) { + return node.kind === 164 /* TypeReference */ || node.kind === 211 /* ExpressionWithTypeArguments */; + } + ts.isTypeReferenceType = isTypeReferenceType; + var MAX_SMI_X86 = 1073741823; + /* @internal */ + function guessIndentation(lines) { + var indentation = MAX_SMI_X86; + for (var _i = 0, lines_1 = lines; _i < lines_1.length; _i++) { + var line = lines_1[_i]; + if (!line.length) { + continue; + } + var i = 0; + for (; i < line.length && i < indentation; i++) { + if (!ts.isWhiteSpaceLike(line.charCodeAt(i))) { + break; + } + } + if (i < indentation) { + indentation = i; + } + if (indentation === 0) { + return 0; + } + } + return indentation === MAX_SMI_X86 ? undefined : indentation; + } + ts.guessIndentation = guessIndentation; + function isStringLiteralLike(node) { + return node.kind === 10 /* StringLiteral */ || node.kind === 14 /* NoSubstitutionTemplateLiteral */; + } + ts.isStringLiteralLike = isStringLiteralLike; +})(ts || (ts = {})); +/* @internal */ +(function (ts) { + function isNamedImportsOrExports(node) { + return node.kind === 252 /* NamedImports */ || node.kind === 256 /* NamedExports */; + } + ts.isNamedImportsOrExports = isNamedImportsOrExports; + function Symbol(flags, name) { + this.flags = flags; + this.escapedName = name; + this.declarations = undefined; + this.valueDeclaration = undefined; + this.id = undefined; + this.mergeId = undefined; + this.parent = undefined; + } + function Type(checker, flags) { + this.flags = flags; + if (ts.Debug.isDebugging) { + this.checker = checker; + } + } + function Signature() { } // tslint:disable-line no-empty + function Node(kind, pos, end) { + this.pos = pos; + this.end = end; + this.kind = kind; + this.id = 0; + this.flags = 0 /* None */; + this.modifierFlagsCache = 0 /* None */; + this.transformFlags = 0 /* None */; + this.parent = undefined; + this.original = undefined; + } + function SourceMapSource(fileName, text, skipTrivia) { + this.fileName = fileName; + this.text = text; + this.skipTrivia = skipTrivia || (function (pos) { return pos; }); + } + ts.objectAllocator = { + getNodeConstructor: function () { return Node; }, + getTokenConstructor: function () { return Node; }, + getIdentifierConstructor: function () { return Node; }, + getSourceFileConstructor: function () { return Node; }, + getSymbolConstructor: function () { return Symbol; }, + getTypeConstructor: function () { return Type; }, + getSignatureConstructor: function () { return Signature; }, + getSourceMapSourceConstructor: function () { return SourceMapSource; }, + }; + function formatStringFromArgs(text, args, baseIndex) { + if (baseIndex === void 0) { baseIndex = 0; } + return text.replace(/{(\d+)}/g, function (_match, index) { return "" + ts.Debug.assertDefined(args[+index + baseIndex]); }); + } + ts.formatStringFromArgs = formatStringFromArgs; + function getLocaleSpecificMessage(message) { + return ts.localizedDiagnosticMessages && ts.localizedDiagnosticMessages[message.key] || message.message; + } + ts.getLocaleSpecificMessage = getLocaleSpecificMessage; + function createFileDiagnostic(file, start, length, message) { + ts.Debug.assertGreaterThanOrEqual(start, 0); + ts.Debug.assertGreaterThanOrEqual(length, 0); + if (file) { + ts.Debug.assertLessThanOrEqual(start, file.text.length); + ts.Debug.assertLessThanOrEqual(start + length, file.text.length); + } + var text = getLocaleSpecificMessage(message); + if (arguments.length > 4) { + text = formatStringFromArgs(text, arguments, 4); + } + return { + file: file, + start: start, + length: length, + messageText: text, + category: message.category, + code: message.code, + reportsUnnecessary: message.reportsUnnecessary, + }; + } + ts.createFileDiagnostic = createFileDiagnostic; + function formatMessage(_dummy, message) { + var text = getLocaleSpecificMessage(message); + if (arguments.length > 2) { + text = formatStringFromArgs(text, arguments, 2); + } + return text; + } + ts.formatMessage = formatMessage; + function createCompilerDiagnostic(message) { + var text = getLocaleSpecificMessage(message); + if (arguments.length > 1) { + text = formatStringFromArgs(text, arguments, 1); + } + return { + file: undefined, + start: undefined, + length: undefined, + messageText: text, + category: message.category, + code: message.code, + reportsUnnecessary: message.reportsUnnecessary, + }; + } + ts.createCompilerDiagnostic = createCompilerDiagnostic; + function createCompilerDiagnosticFromMessageChain(chain) { + return { + file: undefined, + start: undefined, + length: undefined, + code: chain.code, + category: chain.category, + messageText: chain.next ? chain : chain.messageText, + }; + } + ts.createCompilerDiagnosticFromMessageChain = createCompilerDiagnosticFromMessageChain; + function chainDiagnosticMessages(details, message) { + var text = getLocaleSpecificMessage(message); + if (arguments.length > 2) { + text = formatStringFromArgs(text, arguments, 2); + } + return { + messageText: text, + category: message.category, + code: message.code, + next: details + }; + } + ts.chainDiagnosticMessages = chainDiagnosticMessages; + function concatenateDiagnosticMessageChains(headChain, tailChain) { + var lastChain = headChain; + while (lastChain.next) { + lastChain = lastChain.next; + } + lastChain.next = tailChain; + return headChain; + } + ts.concatenateDiagnosticMessageChains = concatenateDiagnosticMessageChains; + function getDiagnosticFilePath(diagnostic) { + return diagnostic.file ? diagnostic.file.path : undefined; + } + function compareDiagnostics(d1, d2) { + return compareDiagnosticsSkipRelatedInformation(d1, d2) || + compareRelatedInformation(d1, d2) || + 0 /* EqualTo */; + } + ts.compareDiagnostics = compareDiagnostics; + function compareDiagnosticsSkipRelatedInformation(d1, d2) { + return ts.compareStringsCaseSensitive(getDiagnosticFilePath(d1), getDiagnosticFilePath(d2)) || + ts.compareValues(d1.start, d2.start) || + ts.compareValues(d1.length, d2.length) || + ts.compareValues(d1.code, d2.code) || + compareMessageText(d1.messageText, d2.messageText) || + 0 /* EqualTo */; + } + ts.compareDiagnosticsSkipRelatedInformation = compareDiagnosticsSkipRelatedInformation; + function compareRelatedInformation(d1, d2) { + if (!d1.relatedInformation && !d2.relatedInformation) { + return 0 /* EqualTo */; + } + if (d1.relatedInformation && d2.relatedInformation) { + return ts.compareValues(d1.relatedInformation.length, d2.relatedInformation.length) || ts.forEach(d1.relatedInformation, function (d1i, index) { + var d2i = d2.relatedInformation[index]; + return compareDiagnostics(d1i, d2i); // EqualTo is 0, so falsy, and will cause the next item to be compared + }) || 0 /* EqualTo */; + } + return d1.relatedInformation ? -1 /* LessThan */ : 1 /* GreaterThan */; + } + function compareMessageText(t1, t2) { + var text1 = t1; + var text2 = t2; + while (text1 && text2) { + // We still have both chains. + var string1 = ts.isString(text1) ? text1 : text1.messageText; + var string2 = ts.isString(text2) ? text2 : text2.messageText; + var res = ts.compareStringsCaseSensitive(string1, string2); + if (res) { + return res; + } + text1 = ts.isString(text1) ? undefined : text1.next; + text2 = ts.isString(text2) ? undefined : text2.next; + } + if (!text1 && !text2) { + // if the chains are done, then these messages are the same. + return 0 /* EqualTo */; + } + // We still have one chain remaining. The shorter chain should come first. + return text1 ? 1 /* GreaterThan */ : -1 /* LessThan */; + } + function getEmitScriptTarget(compilerOptions) { + return compilerOptions.target || 0 /* ES3 */; + } + ts.getEmitScriptTarget = getEmitScriptTarget; + function getEmitModuleKind(compilerOptions) { + return typeof compilerOptions.module === "number" ? + compilerOptions.module : + getEmitScriptTarget(compilerOptions) >= 2 /* ES2015 */ ? ts.ModuleKind.ES2015 : ts.ModuleKind.CommonJS; + } + ts.getEmitModuleKind = getEmitModuleKind; + function getEmitModuleResolutionKind(compilerOptions) { + var moduleResolution = compilerOptions.moduleResolution; + if (moduleResolution === undefined) { + moduleResolution = getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS ? ts.ModuleResolutionKind.NodeJs : ts.ModuleResolutionKind.Classic; + } + return moduleResolution; + } + ts.getEmitModuleResolutionKind = getEmitModuleResolutionKind; + function hasJsonModuleEmitEnabled(options) { + switch (getEmitModuleKind(options)) { + case ts.ModuleKind.CommonJS: + case ts.ModuleKind.AMD: + case ts.ModuleKind.ES2015: + case ts.ModuleKind.ESNext: + return true; + default: + return false; + } + } + ts.hasJsonModuleEmitEnabled = hasJsonModuleEmitEnabled; + function unreachableCodeIsError(options) { + return options.allowUnreachableCode === false; + } + ts.unreachableCodeIsError = unreachableCodeIsError; + function unusedLabelIsError(options) { + return options.allowUnusedLabels === false; + } + ts.unusedLabelIsError = unusedLabelIsError; + function getAreDeclarationMapsEnabled(options) { + return !!(getEmitDeclarations(options) && options.declarationMap); + } + ts.getAreDeclarationMapsEnabled = getAreDeclarationMapsEnabled; + function getAllowSyntheticDefaultImports(compilerOptions) { + var moduleKind = getEmitModuleKind(compilerOptions); + return compilerOptions.allowSyntheticDefaultImports !== undefined + ? compilerOptions.allowSyntheticDefaultImports + : compilerOptions.esModuleInterop || + moduleKind === ts.ModuleKind.System; + } + ts.getAllowSyntheticDefaultImports = getAllowSyntheticDefaultImports; + function getEmitDeclarations(compilerOptions) { + return !!(compilerOptions.declaration || compilerOptions.composite); + } + ts.getEmitDeclarations = getEmitDeclarations; + function getStrictOptionValue(compilerOptions, flag) { + return compilerOptions[flag] === undefined ? !!compilerOptions.strict : !!compilerOptions[flag]; + } + ts.getStrictOptionValue = getStrictOptionValue; + function compilerOptionsAffectSemanticDiagnostics(newOptions, oldOptions) { + return oldOptions !== newOptions && + ts.semanticDiagnosticsOptionDeclarations.some(function (option) { return !ts.isJsonEqual(getCompilerOptionValue(oldOptions, option), getCompilerOptionValue(newOptions, option)); }); + } + ts.compilerOptionsAffectSemanticDiagnostics = compilerOptionsAffectSemanticDiagnostics; + function getCompilerOptionValue(options, option) { + return option.strictFlag ? getStrictOptionValue(options, option.name) : options[option.name]; + } + ts.getCompilerOptionValue = getCompilerOptionValue; + function hasZeroOrOneAsteriskCharacter(str) { + var seenAsterisk = false; + for (var i = 0; i < str.length; i++) { + if (str.charCodeAt(i) === 42 /* asterisk */) { + if (!seenAsterisk) { + seenAsterisk = true; + } + else { + // have already seen asterisk + return false; + } + } + } + return true; + } + ts.hasZeroOrOneAsteriskCharacter = hasZeroOrOneAsteriskCharacter; + /** + * Internally, we represent paths as strings with '/' as the directory separator. + * When we make system calls (eg: LanguageServiceHost.getDirectory()), + * we expect the host to correctly handle paths in our specified format. + */ + ts.directorySeparator = "/"; + var altDirectorySeparator = "\\"; + var urlSchemeSeparator = "://"; + var backslashRegExp = /\\/g; + /** + * Normalize path separators. + */ + function normalizeSlashes(path) { + return path.replace(backslashRegExp, ts.directorySeparator); + } + ts.normalizeSlashes = normalizeSlashes; + function isVolumeCharacter(charCode) { + return (charCode >= 97 /* a */ && charCode <= 122 /* z */) || + (charCode >= 65 /* A */ && charCode <= 90 /* Z */); + } + function getFileUrlVolumeSeparatorEnd(url, start) { + var ch0 = url.charCodeAt(start); + if (ch0 === 58 /* colon */) + return start + 1; + if (ch0 === 37 /* percent */ && url.charCodeAt(start + 1) === 51 /* _3 */) { + var ch2 = url.charCodeAt(start + 2); + if (ch2 === 97 /* a */ || ch2 === 65 /* A */) + return start + 3; + } + return -1; + } + /** + * Returns length of the root part of a path or URL (i.e. length of "/", "x:/", "//server/share/, file:///user/files"). + * If the root is part of a URL, the twos-complement of the root length is returned. + */ + function getEncodedRootLength(path) { + if (!path) + return 0; + var ch0 = path.charCodeAt(0); + // POSIX or UNC + if (ch0 === 47 /* slash */ || ch0 === 92 /* backslash */) { + if (path.charCodeAt(1) !== ch0) + return 1; // POSIX: "/" (or non-normalized "\") + var p1 = path.indexOf(ch0 === 47 /* slash */ ? ts.directorySeparator : altDirectorySeparator, 2); + if (p1 < 0) + return path.length; // UNC: "//server" or "\\server" + return p1 + 1; // UNC: "//server/" or "\\server\" + } + // DOS + if (isVolumeCharacter(ch0) && path.charCodeAt(1) === 58 /* colon */) { + var ch2 = path.charCodeAt(2); + if (ch2 === 47 /* slash */ || ch2 === 92 /* backslash */) + return 3; // DOS: "c:/" or "c:\" + if (path.length === 2) + return 2; // DOS: "c:" (but not "c:d") + } + // URL + var schemeEnd = path.indexOf(urlSchemeSeparator); + if (schemeEnd !== -1) { + var authorityStart = schemeEnd + urlSchemeSeparator.length; + var authorityEnd = path.indexOf(ts.directorySeparator, authorityStart); + if (authorityEnd !== -1) { // URL: "file:///", "file://server/", "file://server/path" + // For local "file" URLs, include the leading DOS volume (if present). + // Per https://www.ietf.org/rfc/rfc1738.txt, a host of "" or "localhost" is a + // special case interpreted as "the machine from which the URL is being interpreted". + var scheme = path.slice(0, schemeEnd); + var authority = path.slice(authorityStart, authorityEnd); + if (scheme === "file" && (authority === "" || authority === "localhost") && + isVolumeCharacter(path.charCodeAt(authorityEnd + 1))) { + var volumeSeparatorEnd = getFileUrlVolumeSeparatorEnd(path, authorityEnd + 2); + if (volumeSeparatorEnd !== -1) { + if (path.charCodeAt(volumeSeparatorEnd) === 47 /* slash */) { + // URL: "file:///c:/", "file://localhost/c:/", "file:///c%3a/", "file://localhost/c%3a/" + return ~(volumeSeparatorEnd + 1); + } + if (volumeSeparatorEnd === path.length) { + // URL: "file:///c:", "file://localhost/c:", "file:///c$3a", "file://localhost/c%3a" + // but not "file:///c:d" or "file:///c%3ad" + return ~volumeSeparatorEnd; + } + } + } + return ~(authorityEnd + 1); // URL: "file://server/", "http://server/" + } + return ~path.length; // URL: "file://server", "http://server" + } + // relative + return 0; + } + /** + * Returns length of the root part of a path or URL (i.e. length of "/", "x:/", "//server/share/, file:///user/files"). + * + * For example: + * ```ts + * getRootLength("a") === 0 // "" + * getRootLength("/") === 1 // "/" + * getRootLength("c:") === 2 // "c:" + * getRootLength("c:d") === 0 // "" + * getRootLength("c:/") === 3 // "c:/" + * getRootLength("c:\\") === 3 // "c:\\" + * getRootLength("//server") === 7 // "//server" + * getRootLength("//server/share") === 8 // "//server/" + * getRootLength("\\\\server") === 7 // "\\\\server" + * getRootLength("\\\\server\\share") === 8 // "\\\\server\\" + * getRootLength("file:///path") === 8 // "file:///" + * getRootLength("file:///c:") === 10 // "file:///c:" + * getRootLength("file:///c:d") === 8 // "file:///" + * getRootLength("file:///c:/path") === 11 // "file:///c:/" + * getRootLength("file://server") === 13 // "file://server" + * getRootLength("file://server/path") === 14 // "file://server/" + * getRootLength("http://server") === 13 // "http://server" + * getRootLength("http://server/path") === 14 // "http://server/" + * ``` + */ + function getRootLength(path) { + var rootLength = getEncodedRootLength(path); + return rootLength < 0 ? ~rootLength : rootLength; + } + ts.getRootLength = getRootLength; + // TODO(rbuckton): replace references with `resolvePath` + function normalizePath(path) { + return ts.resolvePath(path); + } + ts.normalizePath = normalizePath; + function normalizePathAndParts(path) { + path = normalizeSlashes(path); + var _a = reducePathComponents(getPathComponents(path)), root = _a[0], parts = _a.slice(1); + if (parts.length) { + var joinedParts = root + parts.join(ts.directorySeparator); + return { path: ts.hasTrailingDirectorySeparator(path) ? ts.ensureTrailingDirectorySeparator(joinedParts) : joinedParts, parts: parts }; + } + else { + return { path: root, parts: parts }; + } + } + ts.normalizePathAndParts = normalizePathAndParts; + function getDirectoryPath(path) { + path = normalizeSlashes(path); + // If the path provided is itself the root, then return it. + var rootLength = getRootLength(path); + if (rootLength === path.length) + return path; + // return the leading portion of the path up to the last (non-terminal) directory separator + // but not including any trailing directory separator. + path = ts.removeTrailingDirectorySeparator(path); + return path.slice(0, Math.max(rootLength, path.lastIndexOf(ts.directorySeparator))); + } + ts.getDirectoryPath = getDirectoryPath; + function startsWithDirectory(fileName, directoryName, getCanonicalFileName) { + var canonicalFileName = getCanonicalFileName(fileName); + var canonicalDirectoryName = getCanonicalFileName(directoryName); + return ts.startsWith(canonicalFileName, canonicalDirectoryName + "/") || ts.startsWith(canonicalFileName, canonicalDirectoryName + "\\"); + } + ts.startsWithDirectory = startsWithDirectory; + function isUrl(path) { + return getEncodedRootLength(path) < 0; + } + ts.isUrl = isUrl; + function pathIsRelative(path) { + return /^\.\.?($|[\\/])/.test(path); + } + ts.pathIsRelative = pathIsRelative; + /** + * Determines whether a path is an absolute path (e.g. starts with `/`, or a dos path + * like `c:`, `c:\` or `c:/`). + */ + function isRootedDiskPath(path) { + return getEncodedRootLength(path) > 0; + } + ts.isRootedDiskPath = isRootedDiskPath; + /** + * Determines whether a path consists only of a path root. + */ + function isDiskPathRoot(path) { + var rootLength = getEncodedRootLength(path); + return rootLength > 0 && rootLength === path.length; + } + ts.isDiskPathRoot = isDiskPathRoot; + function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) { + return !isRootedDiskPath(absoluteOrRelativePath) + ? absoluteOrRelativePath + : ts.getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); + } + ts.convertToRelativePath = convertToRelativePath; + function pathComponents(path, rootLength) { + var root = path.substring(0, rootLength); + var rest = path.substring(rootLength).split(ts.directorySeparator); + if (rest.length && !ts.lastOrUndefined(rest)) + rest.pop(); + return [root].concat(rest); + } + /** + * Parse a path into an array containing a root component (at index 0) and zero or more path + * components (at indices > 0). The result is not normalized. + * If the path is relative, the root component is `""`. + * If the path is absolute, the root component includes the first path separator (`/`). + */ + function getPathComponents(path, currentDirectory) { + if (currentDirectory === void 0) { currentDirectory = ""; } + path = ts.combinePaths(currentDirectory, path); + var rootLength = getRootLength(path); + return pathComponents(path, rootLength); + } + ts.getPathComponents = getPathComponents; + /** + * Reduce an array of path components to a more simplified path by navigating any + * `"."` or `".."` entries in the path. + */ + function reducePathComponents(components) { + if (!ts.some(components)) + return []; + var reduced = [components[0]]; + for (var i = 1; i < components.length; i++) { + var component = components[i]; + if (!component) + continue; + if (component === ".") + continue; + if (component === "..") { + if (reduced.length > 1) { + if (reduced[reduced.length - 1] !== "..") { + reduced.pop(); + continue; + } + } + else if (reduced[0]) + continue; + } + reduced.push(component); + } + return reduced; + } + ts.reducePathComponents = reducePathComponents; + /** + * Parse a path into an array containing a root component (at index 0) and zero or more path + * components (at indices > 0). The result is normalized. + * If the path is relative, the root component is `""`. + * If the path is absolute, the root component includes the first path separator (`/`). + */ + function getNormalizedPathComponents(path, currentDirectory) { + return reducePathComponents(getPathComponents(path, currentDirectory)); + } + ts.getNormalizedPathComponents = getNormalizedPathComponents; + function getNormalizedAbsolutePath(fileName, currentDirectory) { + return getPathFromPathComponents(getNormalizedPathComponents(fileName, currentDirectory)); + } + ts.getNormalizedAbsolutePath = getNormalizedAbsolutePath; + /** + * Formats a parsed path consisting of a root component (at index 0) and zero or more path + * segments (at indices > 0). + */ + function getPathFromPathComponents(pathComponents) { + if (pathComponents.length === 0) + return ""; + var root = pathComponents[0] && ts.ensureTrailingDirectorySeparator(pathComponents[0]); + return root + pathComponents.slice(1).join(ts.directorySeparator); + } + ts.getPathFromPathComponents = getPathFromPathComponents; +})(ts || (ts = {})); +/* @internal */ +(function (ts) { + function getPathComponentsRelativeTo(from, to, stringEqualityComparer, getCanonicalFileName) { + var fromComponents = ts.reducePathComponents(ts.getPathComponents(from)); + var toComponents = ts.reducePathComponents(ts.getPathComponents(to)); + var start; + for (start = 0; start < fromComponents.length && start < toComponents.length; start++) { + var fromComponent = getCanonicalFileName(fromComponents[start]); + var toComponent = getCanonicalFileName(toComponents[start]); + var comparer = start === 0 ? ts.equateStringsCaseInsensitive : stringEqualityComparer; + if (!comparer(fromComponent, toComponent)) + break; + } + if (start === 0) { + return toComponents; + } + var components = toComponents.slice(start); + var relative = []; + for (; start < fromComponents.length; start++) { + relative.push(".."); + } + return [""].concat(relative, components); + } + ts.getPathComponentsRelativeTo = getPathComponentsRelativeTo; + function getRelativePathFromFile(from, to, getCanonicalFileName) { + return ensurePathIsNonModuleName(getRelativePathFromDirectory(ts.getDirectoryPath(from), to, getCanonicalFileName)); + } + ts.getRelativePathFromFile = getRelativePathFromFile; + function getRelativePathFromDirectory(fromDirectory, to, getCanonicalFileNameOrIgnoreCase) { + Debug.assert((ts.getRootLength(fromDirectory) > 0) === (ts.getRootLength(to) > 0), "Paths must either both be absolute or both be relative"); + var getCanonicalFileName = typeof getCanonicalFileNameOrIgnoreCase === "function" ? getCanonicalFileNameOrIgnoreCase : ts.identity; + var ignoreCase = typeof getCanonicalFileNameOrIgnoreCase === "boolean" ? getCanonicalFileNameOrIgnoreCase : false; + var pathComponents = getPathComponentsRelativeTo(fromDirectory, to, ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive, getCanonicalFileName); + return ts.getPathFromPathComponents(pathComponents); + } + ts.getRelativePathFromDirectory = getRelativePathFromDirectory; + function getRelativePathToDirectoryOrUrl(directoryPathOrUrl, relativeOrAbsolutePath, currentDirectory, getCanonicalFileName, isAbsolutePathAnUrl) { + var pathComponents = getPathComponentsRelativeTo(resolvePath(currentDirectory, directoryPathOrUrl), resolvePath(currentDirectory, relativeOrAbsolutePath), ts.equateStringsCaseSensitive, getCanonicalFileName); + var firstComponent = pathComponents[0]; + if (isAbsolutePathAnUrl && ts.isRootedDiskPath(firstComponent)) { + var prefix = firstComponent.charAt(0) === ts.directorySeparator ? "file://" : "file:///"; + pathComponents[0] = prefix + firstComponent; + } + return ts.getPathFromPathComponents(pathComponents); + } + ts.getRelativePathToDirectoryOrUrl = getRelativePathToDirectoryOrUrl; + /** + * Ensures a path is either absolute (prefixed with `/` or `c:`) or dot-relative (prefixed + * with `./` or `../`) so as not to be confused with an unprefixed module name. + */ + function ensurePathIsNonModuleName(path) { + return ts.getRootLength(path) === 0 && !ts.pathIsRelative(path) ? "./" + path : path; + } + ts.ensurePathIsNonModuleName = ensurePathIsNonModuleName; + function getBaseFileName(path, extensions, ignoreCase) { + path = ts.normalizeSlashes(path); + // if the path provided is itself the root, then it has not file name. + var rootLength = ts.getRootLength(path); + if (rootLength === path.length) + return ""; + // return the trailing portion of the path starting after the last (non-terminal) directory + // separator but not including any trailing directory separator. + path = removeTrailingDirectorySeparator(path); + var name = path.slice(Math.max(ts.getRootLength(path), path.lastIndexOf(ts.directorySeparator) + 1)); + var extension = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(name, extensions, ignoreCase) : undefined; + return extension ? name.slice(0, name.length - extension.length) : name; + } + ts.getBaseFileName = getBaseFileName; + /** + * Combines paths. If a path is absolute, it replaces any previous path. + */ + function combinePaths(path) { + var paths = []; + for (var _i = 1; _i < arguments.length; _i++) { + paths[_i - 1] = arguments[_i]; + } + if (path) + path = ts.normalizeSlashes(path); + for (var _a = 0, paths_1 = paths; _a < paths_1.length; _a++) { + var relativePath = paths_1[_a]; + if (!relativePath) + continue; + relativePath = ts.normalizeSlashes(relativePath); + if (!path || ts.getRootLength(relativePath) !== 0) { + path = relativePath; + } + else { + path = ensureTrailingDirectorySeparator(path) + relativePath; + } + } + return path; + } + ts.combinePaths = combinePaths; + /** + * Combines and resolves paths. If a path is absolute, it replaces any previous path. Any + * `.` and `..` path components are resolved. + */ + function resolvePath(path) { + var paths = []; + for (var _i = 1; _i < arguments.length; _i++) { + paths[_i - 1] = arguments[_i]; + } + var combined = ts.some(paths) ? combinePaths.apply(void 0, [path].concat(paths)) : ts.normalizeSlashes(path); + var normalized = ts.getPathFromPathComponents(ts.reducePathComponents(ts.getPathComponents(combined))); + return normalized && hasTrailingDirectorySeparator(combined) ? ensureTrailingDirectorySeparator(normalized) : normalized; + } + ts.resolvePath = resolvePath; + /** + * Determines whether a path has a trailing separator (`/` or `\\`). + */ + function hasTrailingDirectorySeparator(path) { + if (path.length === 0) + return false; + var ch = path.charCodeAt(path.length - 1); + return ch === 47 /* slash */ || ch === 92 /* backslash */; + } + ts.hasTrailingDirectorySeparator = hasTrailingDirectorySeparator; + function removeTrailingDirectorySeparator(path) { + if (hasTrailingDirectorySeparator(path)) { + return path.substr(0, path.length - 1); + } + return path; + } + ts.removeTrailingDirectorySeparator = removeTrailingDirectorySeparator; + function ensureTrailingDirectorySeparator(path) { + if (!hasTrailingDirectorySeparator(path)) { + return path + ts.directorySeparator; + } + return path; + } + ts.ensureTrailingDirectorySeparator = ensureTrailingDirectorySeparator; + function comparePathsWorker(a, b, componentComparer) { + if (a === b) + return 0 /* EqualTo */; + if (a === undefined) + return -1 /* LessThan */; + if (b === undefined) + return 1 /* GreaterThan */; + var aComponents = ts.reducePathComponents(ts.getPathComponents(a)); + var bComponents = ts.reducePathComponents(ts.getPathComponents(b)); + var sharedLength = Math.min(aComponents.length, bComponents.length); + for (var i = 0; i < sharedLength; i++) { + var stringComparer = i === 0 ? ts.compareStringsCaseInsensitive : componentComparer; + var result = stringComparer(aComponents[i], bComponents[i]); + if (result !== 0 /* EqualTo */) { + return result; + } + } + return ts.compareValues(aComponents.length, bComponents.length); + } + /** + * Performs a case-sensitive comparison of two paths. + */ + function comparePathsCaseSensitive(a, b) { + return comparePathsWorker(a, b, ts.compareStringsCaseSensitive); + } + ts.comparePathsCaseSensitive = comparePathsCaseSensitive; + /** + * Performs a case-insensitive comparison of two paths. + */ + function comparePathsCaseInsensitive(a, b) { + return comparePathsWorker(a, b, ts.compareStringsCaseInsensitive); + } + ts.comparePathsCaseInsensitive = comparePathsCaseInsensitive; + function comparePaths(a, b, currentDirectory, ignoreCase) { + if (typeof currentDirectory === "string") { + a = combinePaths(currentDirectory, a); + b = combinePaths(currentDirectory, b); + } + else if (typeof currentDirectory === "boolean") { + ignoreCase = currentDirectory; + } + return comparePathsWorker(a, b, ts.getStringComparer(ignoreCase)); + } + ts.comparePaths = comparePaths; + function containsPath(parent, child, currentDirectory, ignoreCase) { + if (typeof currentDirectory === "string") { + parent = combinePaths(currentDirectory, parent); + child = combinePaths(currentDirectory, child); + } + else if (typeof currentDirectory === "boolean") { + ignoreCase = currentDirectory; + } + if (parent === undefined || child === undefined) + return false; + if (parent === child) + return true; + var parentComponents = ts.reducePathComponents(ts.getPathComponents(parent)); + var childComponents = ts.reducePathComponents(ts.getPathComponents(child)); + if (childComponents.length < parentComponents.length) { + return false; + } + var componentEqualityComparer = ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive; + for (var i = 0; i < parentComponents.length; i++) { + var equalityComparer = i === 0 ? ts.equateStringsCaseInsensitive : componentEqualityComparer; + if (!equalityComparer(parentComponents[i], childComponents[i])) { + return false; + } + } + return true; + } + ts.containsPath = containsPath; + function isDirectorySeparator(charCode) { + return charCode === 47 /* slash */ || charCode === 92 /* backslash */; + } + function stripLeadingDirectorySeparator(s) { + return isDirectorySeparator(s.charCodeAt(0)) ? s.slice(1) : undefined; + } + function tryRemoveDirectoryPrefix(path, dirPath, getCanonicalFileName) { + var withoutPrefix = ts.tryRemovePrefix(path, dirPath, getCanonicalFileName); + return withoutPrefix === undefined ? undefined : stripLeadingDirectorySeparator(withoutPrefix); + } + ts.tryRemoveDirectoryPrefix = tryRemoveDirectoryPrefix; + // Reserved characters, forces escaping of any non-word (or digit), non-whitespace character. + // It may be inefficient (we could just match (/[-[\]{}()*+?.,\\^$|#\s]/g), but this is future + // proof. + var reservedCharacterPattern = /[^\w\s\/]/g; + function regExpEscape(text) { + return text.replace(reservedCharacterPattern, escapeRegExpCharacter); + } + ts.regExpEscape = regExpEscape; + function escapeRegExpCharacter(match) { + return "\\" + match; + } + var wildcardCharCodes = [42 /* asterisk */, 63 /* question */]; + function hasExtension(fileName) { + return ts.stringContains(getBaseFileName(fileName), "."); + } + ts.hasExtension = hasExtension; + ts.commonPackageFolders = ["node_modules", "bower_components", "jspm_packages"]; + var implicitExcludePathRegexPattern = "(?!(" + ts.commonPackageFolders.join("|") + ")(/|$))"; + var filesMatcher = { + /** + * Matches any single directory segment unless it is the last segment and a .min.js file + * Breakdown: + * [^./] # matches everything up to the first . character (excluding directory separators) + * (\\.(?!min\\.js$))? # matches . characters but not if they are part of the .min.js file extension + */ + singleAsteriskRegexFragment: "([^./]|(\\.(?!min\\.js$))?)*", + /** + * Regex for the ** wildcard. Matches any number of subdirectories. When used for including + * files or directories, does not match subdirectories that start with a . character + */ + doubleAsteriskRegexFragment: "(/" + implicitExcludePathRegexPattern + "[^/.][^/]*)*?", + replaceWildcardCharacter: function (match) { return replaceWildcardCharacter(match, filesMatcher.singleAsteriskRegexFragment); } + }; + var directoriesMatcher = { + singleAsteriskRegexFragment: "[^/]*", + /** + * Regex for the ** wildcard. Matches any number of subdirectories. When used for including + * files or directories, does not match subdirectories that start with a . character + */ + doubleAsteriskRegexFragment: "(/" + implicitExcludePathRegexPattern + "[^/.][^/]*)*?", + replaceWildcardCharacter: function (match) { return replaceWildcardCharacter(match, directoriesMatcher.singleAsteriskRegexFragment); } + }; + var excludeMatcher = { + singleAsteriskRegexFragment: "[^/]*", + doubleAsteriskRegexFragment: "(/.+?)?", + replaceWildcardCharacter: function (match) { return replaceWildcardCharacter(match, excludeMatcher.singleAsteriskRegexFragment); } + }; + var wildcardMatchers = { + files: filesMatcher, + directories: directoriesMatcher, + exclude: excludeMatcher + }; + function getRegularExpressionForWildcard(specs, basePath, usage) { + var patterns = getRegularExpressionsForWildcards(specs, basePath, usage); + if (!patterns || !patterns.length) { + return undefined; + } + var pattern = patterns.map(function (pattern) { return "(" + pattern + ")"; }).join("|"); + // If excluding, match "foo/bar/baz...", but if including, only allow "foo". + var terminator = usage === "exclude" ? "($|/)" : "$"; + return "^(" + pattern + ")" + terminator; + } + ts.getRegularExpressionForWildcard = getRegularExpressionForWildcard; + function getRegularExpressionsForWildcards(specs, basePath, usage) { + if (specs === undefined || specs.length === 0) { + return undefined; + } + return ts.flatMap(specs, function (spec) { + return spec && getSubPatternFromSpec(spec, basePath, usage, wildcardMatchers[usage]); + }); + } + ts.getRegularExpressionsForWildcards = getRegularExpressionsForWildcards; + /** + * An "includes" path "foo" is implicitly a glob "foo/** /*" (without the space) if its last component has no extension, + * and does not contain any glob characters itself. + */ + function isImplicitGlob(lastPathComponent) { + return !/[.*?]/.test(lastPathComponent); + } + ts.isImplicitGlob = isImplicitGlob; + function getSubPatternFromSpec(spec, basePath, usage, _a) { + var singleAsteriskRegexFragment = _a.singleAsteriskRegexFragment, doubleAsteriskRegexFragment = _a.doubleAsteriskRegexFragment, replaceWildcardCharacter = _a.replaceWildcardCharacter; + var subpattern = ""; + var hasWrittenComponent = false; + var components = ts.getNormalizedPathComponents(spec, basePath); + var lastComponent = ts.last(components); + if (usage !== "exclude" && lastComponent === "**") { + return undefined; + } + // getNormalizedPathComponents includes the separator for the root component. + // We need to remove to create our regex correctly. + components[0] = removeTrailingDirectorySeparator(components[0]); + if (isImplicitGlob(lastComponent)) { + components.push("**", "*"); + } + var optionalCount = 0; + for (var _i = 0, components_1 = components; _i < components_1.length; _i++) { + var component = components_1[_i]; + if (component === "**") { + subpattern += doubleAsteriskRegexFragment; + } + else { + if (usage === "directories") { + subpattern += "("; + optionalCount++; + } + if (hasWrittenComponent) { + subpattern += ts.directorySeparator; + } + if (usage !== "exclude") { + var componentPattern = ""; + // The * and ? wildcards should not match directories or files that start with . if they + // appear first in a component. Dotted directories and files can be included explicitly + // like so: **/.*/.* + if (component.charCodeAt(0) === 42 /* asterisk */) { + componentPattern += "([^./]" + singleAsteriskRegexFragment + ")?"; + component = component.substr(1); + } + else if (component.charCodeAt(0) === 63 /* question */) { + componentPattern += "[^./]"; + component = component.substr(1); + } + componentPattern += component.replace(reservedCharacterPattern, replaceWildcardCharacter); + // Patterns should not include subfolders like node_modules unless they are + // explicitly included as part of the path. + // + // As an optimization, if the component pattern is the same as the component, + // then there definitely were no wildcard characters and we do not need to + // add the exclusion pattern. + if (componentPattern !== component) { + subpattern += implicitExcludePathRegexPattern; + } + subpattern += componentPattern; + } + else { + subpattern += component.replace(reservedCharacterPattern, replaceWildcardCharacter); + } + } + hasWrittenComponent = true; + } + while (optionalCount > 0) { + subpattern += ")?"; + optionalCount--; + } + return subpattern; + } + function replaceWildcardCharacter(match, singleAsteriskRegexFragment) { + return match === "*" ? singleAsteriskRegexFragment : match === "?" ? "[^/]" : "\\" + match; + } + /** @param path directory of the tsconfig.json */ + function getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory) { + path = ts.normalizePath(path); + currentDirectory = ts.normalizePath(currentDirectory); + var absolutePath = combinePaths(currentDirectory, path); + return { + includeFilePatterns: ts.map(getRegularExpressionsForWildcards(includes, absolutePath, "files"), function (pattern) { return "^" + pattern + "$"; }), + includeFilePattern: getRegularExpressionForWildcard(includes, absolutePath, "files"), + includeDirectoryPattern: getRegularExpressionForWildcard(includes, absolutePath, "directories"), + excludePattern: getRegularExpressionForWildcard(excludes, absolutePath, "exclude"), + basePaths: getBasePaths(path, includes, useCaseSensitiveFileNames) + }; + } + ts.getFileMatcherPatterns = getFileMatcherPatterns; + function getRegexFromPattern(pattern, useCaseSensitiveFileNames) { + return new RegExp(pattern, useCaseSensitiveFileNames ? "" : "i"); + } + ts.getRegexFromPattern = getRegexFromPattern; + /** @param path directory of the tsconfig.json */ + function matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries) { + path = ts.normalizePath(path); + currentDirectory = ts.normalizePath(currentDirectory); + var patterns = getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory); + var includeFileRegexes = patterns.includeFilePatterns && patterns.includeFilePatterns.map(function (pattern) { return getRegexFromPattern(pattern, useCaseSensitiveFileNames); }); + var includeDirectoryRegex = patterns.includeDirectoryPattern && getRegexFromPattern(patterns.includeDirectoryPattern, useCaseSensitiveFileNames); + var excludeRegex = patterns.excludePattern && getRegexFromPattern(patterns.excludePattern, useCaseSensitiveFileNames); + // Associate an array of results with each include regex. This keeps results in order of the "include" order. + // If there are no "includes", then just put everything in results[0]. + var results = includeFileRegexes ? includeFileRegexes.map(function () { return []; }) : [[]]; + for (var _i = 0, _a = patterns.basePaths; _i < _a.length; _i++) { + var basePath = _a[_i]; + visitDirectory(basePath, combinePaths(currentDirectory, basePath), depth); + } + return ts.flatten(results); + function visitDirectory(path, absolutePath, depth) { + var _a = getFileSystemEntries(path), files = _a.files, directories = _a.directories; + var _loop_1 = function (current) { + var name = combinePaths(path, current); + var absoluteName = combinePaths(absolutePath, current); + if (extensions && !ts.fileExtensionIsOneOf(name, extensions)) + return "continue"; + if (excludeRegex && excludeRegex.test(absoluteName)) + return "continue"; + if (!includeFileRegexes) { + results[0].push(name); + } + else { + var includeIndex = ts.findIndex(includeFileRegexes, function (re) { return re.test(absoluteName); }); + if (includeIndex !== -1) { + results[includeIndex].push(name); + } + } + }; + for (var _i = 0, _b = ts.sort(files, ts.compareStringsCaseSensitive); _i < _b.length; _i++) { + var current = _b[_i]; + _loop_1(current); + } + if (depth !== undefined) { + depth--; + if (depth === 0) { + return; + } + } + for (var _c = 0, _d = ts.sort(directories, ts.compareStringsCaseSensitive); _c < _d.length; _c++) { + var current = _d[_c]; + var name = combinePaths(path, current); + var absoluteName = combinePaths(absolutePath, current); + if ((!includeDirectoryRegex || includeDirectoryRegex.test(absoluteName)) && + (!excludeRegex || !excludeRegex.test(absoluteName))) { + visitDirectory(name, absoluteName, depth); + } + } + } + } + ts.matchFiles = matchFiles; + /** + * Computes the unique non-wildcard base paths amongst the provided include patterns. + */ + function getBasePaths(path, includes, useCaseSensitiveFileNames) { + // Storage for our results in the form of literal paths (e.g. the paths as written by the user). + var basePaths = [path]; + if (includes) { + // Storage for literal base paths amongst the include patterns. + var includeBasePaths = []; + for (var _i = 0, includes_1 = includes; _i < includes_1.length; _i++) { + var include = includes_1[_i]; + // We also need to check the relative paths by converting them to absolute and normalizing + // in case they escape the base path (e.g "..\somedirectory") + var absolute = ts.isRootedDiskPath(include) ? include : ts.normalizePath(combinePaths(path, include)); + // Append the literal and canonical candidate base paths. + includeBasePaths.push(getIncludeBasePath(absolute)); + } + // Sort the offsets array using either the literal or canonical path representations. + includeBasePaths.sort(ts.getStringComparer(!useCaseSensitiveFileNames)); + var _loop_2 = function (includeBasePath) { + if (ts.every(basePaths, function (basePath) { return !containsPath(basePath, includeBasePath, path, !useCaseSensitiveFileNames); })) { + basePaths.push(includeBasePath); + } + }; + // Iterate over each include base path and include unique base paths that are not a + // subpath of an existing base path + for (var _a = 0, includeBasePaths_1 = includeBasePaths; _a < includeBasePaths_1.length; _a++) { + var includeBasePath = includeBasePaths_1[_a]; + _loop_2(includeBasePath); + } + } + return basePaths; + } + function getIncludeBasePath(absolute) { + var wildcardOffset = ts.indexOfAnyCharCode(absolute, wildcardCharCodes); + if (wildcardOffset < 0) { + // No "*" or "?" in the path + return !hasExtension(absolute) + ? absolute + : removeTrailingDirectorySeparator(ts.getDirectoryPath(absolute)); + } + return absolute.substring(0, absolute.lastIndexOf(ts.directorySeparator, wildcardOffset)); + } + function ensureScriptKind(fileName, scriptKind) { + // Using scriptKind as a condition handles both: + // - 'scriptKind' is unspecified and thus it is `undefined` + // - 'scriptKind' is set and it is `Unknown` (0) + // If the 'scriptKind' is 'undefined' or 'Unknown' then we attempt + // to get the ScriptKind from the file name. If it cannot be resolved + // from the file name then the default 'TS' script kind is returned. + return scriptKind || getScriptKindFromFileName(fileName) || 3 /* TS */; + } + ts.ensureScriptKind = ensureScriptKind; + function getScriptKindFromFileName(fileName) { + var ext = fileName.substr(fileName.lastIndexOf(".")); + switch (ext.toLowerCase()) { + case ".js" /* Js */: + return 1 /* JS */; + case ".jsx" /* Jsx */: + return 2 /* JSX */; + case ".ts" /* Ts */: + return 3 /* TS */; + case ".tsx" /* Tsx */: + return 4 /* TSX */; + case ".json" /* Json */: + return 6 /* JSON */; + default: + return 0 /* Unknown */; + } + } + ts.getScriptKindFromFileName = getScriptKindFromFileName; + /** + * List of supported extensions in order of file resolution precedence. + */ + ts.supportedTSExtensions = [".ts" /* Ts */, ".tsx" /* Tsx */, ".d.ts" /* Dts */]; + ts.supportedTSExtensionsWithJson = [".ts" /* Ts */, ".tsx" /* Tsx */, ".d.ts" /* Dts */, ".json" /* Json */]; + /** Must have ".d.ts" first because if ".ts" goes first, that will be detected as the extension instead of ".d.ts". */ + ts.supportedTSExtensionsForExtractExtension = [".d.ts" /* Dts */, ".ts" /* Ts */, ".tsx" /* Tsx */]; + ts.supportedJSExtensions = [".js" /* Js */, ".jsx" /* Jsx */]; + ts.supportedJSAndJsonExtensions = [".js" /* Js */, ".jsx" /* Jsx */, ".json" /* Json */]; + var allSupportedExtensions = ts.supportedTSExtensions.concat(ts.supportedJSExtensions); + var allSupportedExtensionsWithJson = ts.supportedTSExtensions.concat(ts.supportedJSExtensions, [".json" /* Json */]); + function getSupportedExtensions(options, extraFileExtensions) { + var needJsExtensions = options && options.allowJs; + if (!extraFileExtensions || extraFileExtensions.length === 0) { + return needJsExtensions ? allSupportedExtensions : ts.supportedTSExtensions; + } + var extensions = (needJsExtensions ? allSupportedExtensions : ts.supportedTSExtensions).concat(ts.mapDefined(extraFileExtensions, function (x) { return x.scriptKind === 7 /* Deferred */ || needJsExtensions && isJSLike(x.scriptKind) ? x.extension : undefined; })); + return ts.deduplicate(extensions, ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive); + } + ts.getSupportedExtensions = getSupportedExtensions; + function getSuppoertedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions) { + if (!options || !options.resolveJsonModule) { + return supportedExtensions; + } + if (supportedExtensions === allSupportedExtensions) { + return allSupportedExtensionsWithJson; + } + if (supportedExtensions === ts.supportedTSExtensions) { + return ts.supportedTSExtensionsWithJson; + } + return supportedExtensions.concat([".json" /* Json */]); + } + ts.getSuppoertedExtensionsWithJsonIfResolveJsonModule = getSuppoertedExtensionsWithJsonIfResolveJsonModule; + function isJSLike(scriptKind) { + return scriptKind === 1 /* JS */ || scriptKind === 2 /* JSX */; + } + function hasJSFileExtension(fileName) { + return ts.some(ts.supportedJSExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + } + ts.hasJSFileExtension = hasJSFileExtension; + function hasJSOrJsonFileExtension(fileName) { + return ts.supportedJSAndJsonExtensions.some(function (ext) { return ts.fileExtensionIs(fileName, ext); }); + } + ts.hasJSOrJsonFileExtension = hasJSOrJsonFileExtension; + function hasTSFileExtension(fileName) { + return ts.some(ts.supportedTSExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + } + ts.hasTSFileExtension = hasTSFileExtension; + function isSupportedSourceFileName(fileName, compilerOptions, extraFileExtensions) { + if (!fileName) { + return false; + } + var supportedExtensions = getSupportedExtensions(compilerOptions, extraFileExtensions); + for (var _i = 0, _a = getSuppoertedExtensionsWithJsonIfResolveJsonModule(compilerOptions, supportedExtensions); _i < _a.length; _i++) { + var extension = _a[_i]; + if (ts.fileExtensionIs(fileName, extension)) { + return true; + } + } + return false; + } + ts.isSupportedSourceFileName = isSupportedSourceFileName; + /** + * Extension boundaries by priority. Lower numbers indicate higher priorities, and are + * aligned to the offset of the highest priority extension in the + * allSupportedExtensions array. + */ + var ExtensionPriority; + (function (ExtensionPriority) { + ExtensionPriority[ExtensionPriority["TypeScriptFiles"] = 0] = "TypeScriptFiles"; + ExtensionPriority[ExtensionPriority["DeclarationAndJavaScriptFiles"] = 2] = "DeclarationAndJavaScriptFiles"; + ExtensionPriority[ExtensionPriority["Highest"] = 0] = "Highest"; + ExtensionPriority[ExtensionPriority["Lowest"] = 2] = "Lowest"; + })(ExtensionPriority = ts.ExtensionPriority || (ts.ExtensionPriority = {})); + function getExtensionPriority(path, supportedExtensions) { + for (var i = supportedExtensions.length - 1; i >= 0; i--) { + if (ts.fileExtensionIs(path, supportedExtensions[i])) { + return adjustExtensionPriority(i, supportedExtensions); + } + } + // If its not in the list of supported extensions, this is likely a + // TypeScript file with a non-ts extension + return 0 /* Highest */; + } + ts.getExtensionPriority = getExtensionPriority; + /** + * Adjusts an extension priority to be the highest priority within the same range. + */ + function adjustExtensionPriority(extensionPriority, supportedExtensions) { + if (extensionPriority < 2 /* DeclarationAndJavaScriptFiles */) { + return 0 /* TypeScriptFiles */; + } + else if (extensionPriority < supportedExtensions.length) { + return 2 /* DeclarationAndJavaScriptFiles */; + } + else { + return supportedExtensions.length; + } + } + ts.adjustExtensionPriority = adjustExtensionPriority; + /** + * Gets the next lowest extension priority for a given priority. + */ + function getNextLowestExtensionPriority(extensionPriority, supportedExtensions) { + if (extensionPriority < 2 /* DeclarationAndJavaScriptFiles */) { + return 2 /* DeclarationAndJavaScriptFiles */; + } + else { + return supportedExtensions.length; + } + } + ts.getNextLowestExtensionPriority = getNextLowestExtensionPriority; + var extensionsToRemove = [".d.ts" /* Dts */, ".ts" /* Ts */, ".js" /* Js */, ".tsx" /* Tsx */, ".jsx" /* Jsx */, ".json" /* Json */]; + function removeFileExtension(path) { + for (var _i = 0, extensionsToRemove_1 = extensionsToRemove; _i < extensionsToRemove_1.length; _i++) { + var ext = extensionsToRemove_1[_i]; + var extensionless = tryRemoveExtension(path, ext); + if (extensionless !== undefined) { + return extensionless; + } + } + return path; + } + ts.removeFileExtension = removeFileExtension; + function tryRemoveExtension(path, extension) { + return ts.fileExtensionIs(path, extension) ? removeExtension(path, extension) : undefined; + } + ts.tryRemoveExtension = tryRemoveExtension; + function removeExtension(path, extension) { + return path.substring(0, path.length - extension.length); + } + ts.removeExtension = removeExtension; + function changeExtension(path, newExtension) { + return changeAnyExtension(path, newExtension, extensionsToRemove, /*ignoreCase*/ false); + } + ts.changeExtension = changeExtension; + function changeAnyExtension(path, ext, extensions, ignoreCase) { + var pathext = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(path, extensions, ignoreCase) : getAnyExtensionFromPath(path); + return pathext ? path.slice(0, path.length - pathext.length) + (ts.startsWith(ext, ".") ? ext : "." + ext) : path; + } + ts.changeAnyExtension = changeAnyExtension; + var Debug; + (function (Debug) { + function showSymbol(symbol) { + var symbolFlags = ts.SymbolFlags; + return "{ flags: " + (symbolFlags ? showFlags(symbol.flags, symbolFlags) : symbol.flags) + "; declarations: " + ts.map(symbol.declarations, showSyntaxKind) + " }"; + } + Debug.showSymbol = showSymbol; + function showFlags(flags, flagsEnum) { + var out = []; + for (var pow = 0; pow <= 30; pow++) { + var n = 1 << pow; + if (flags & n) { + out.push(flagsEnum[n]); + } + } + return out.join("|"); + } + function showSyntaxKind(node) { + var syntaxKind = ts.SyntaxKind; + return syntaxKind ? syntaxKind[node.kind] : node.kind.toString(); + } + Debug.showSyntaxKind = showSyntaxKind; + })(Debug = ts.Debug || (ts.Debug = {})); + function tryParsePattern(pattern) { + // This should be verified outside of here and a proper error thrown. + Debug.assert(ts.hasZeroOrOneAsteriskCharacter(pattern)); + var indexOfStar = pattern.indexOf("*"); + return indexOfStar === -1 ? undefined : { + prefix: pattern.substr(0, indexOfStar), + suffix: pattern.substr(indexOfStar + 1) + }; + } + ts.tryParsePattern = tryParsePattern; + function positionIsSynthesized(pos) { + // This is a fast way of testing the following conditions: + // pos === undefined || pos === null || isNaN(pos) || pos < 0; + return !(pos >= 0); + } + ts.positionIsSynthesized = positionIsSynthesized; + /** True if an extension is one of the supported TypeScript extensions. */ + function extensionIsTS(ext) { + return ext === ".ts" /* Ts */ || ext === ".tsx" /* Tsx */ || ext === ".d.ts" /* Dts */; + } + ts.extensionIsTS = extensionIsTS; + function resolutionExtensionIsTSOrJson(ext) { + return extensionIsTS(ext) || ext === ".json" /* Json */; + } + ts.resolutionExtensionIsTSOrJson = resolutionExtensionIsTSOrJson; + /** + * Gets the extension from a path. + * Path must have a valid extension. + */ + function extensionFromPath(path) { + var ext = tryGetExtensionFromPath(path); + return ext !== undefined ? ext : Debug.fail("File " + path + " has unknown extension."); + } + ts.extensionFromPath = extensionFromPath; + function isAnySupportedFileExtension(path) { + return tryGetExtensionFromPath(path) !== undefined; + } + ts.isAnySupportedFileExtension = isAnySupportedFileExtension; + function tryGetExtensionFromPath(path) { + return ts.find(extensionsToRemove, function (e) { return ts.fileExtensionIs(path, e); }); + } + ts.tryGetExtensionFromPath = tryGetExtensionFromPath; + function getAnyExtensionFromPathWorker(path, extensions, stringEqualityComparer) { + if (typeof extensions === "string") + extensions = [extensions]; + for (var _i = 0, extensions_2 = extensions; _i < extensions_2.length; _i++) { + var extension = extensions_2[_i]; + if (!ts.startsWith(extension, ".")) + extension = "." + extension; + if (path.length >= extension.length && path.charAt(path.length - extension.length) === ".") { + var pathExtension = path.slice(path.length - extension.length); + if (stringEqualityComparer(pathExtension, extension)) { + return pathExtension; + } + } + } + return ""; + } + function getAnyExtensionFromPath(path, extensions, ignoreCase) { + // Retrieves any string from the final "." onwards from a base file name. + // Unlike extensionFromPath, which throws an exception on unrecognized extensions. + if (extensions) { + return getAnyExtensionFromPathWorker(path, extensions, ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive); + } + var baseFileName = getBaseFileName(path); + var extensionIndex = baseFileName.lastIndexOf("."); + if (extensionIndex >= 0) { + return baseFileName.substring(extensionIndex); + } + return ""; + } + ts.getAnyExtensionFromPath = getAnyExtensionFromPath; + function isCheckJsEnabledForFile(sourceFile, compilerOptions) { + return sourceFile.checkJsDirective ? sourceFile.checkJsDirective.enabled : compilerOptions.checkJs; + } + ts.isCheckJsEnabledForFile = isCheckJsEnabledForFile; + ts.emptyFileSystemEntries = { + files: ts.emptyArray, + directories: ts.emptyArray + }; + /** + * patternStrings contains both pattern strings (containing "*") and regular strings. + * Return an exact match if possible, or a pattern match, or undefined. + * (These are verified by verifyCompilerOptions to have 0 or 1 "*" characters.) + */ + function matchPatternOrExact(patternStrings, candidate) { + var patterns = []; + for (var _i = 0, patternStrings_1 = patternStrings; _i < patternStrings_1.length; _i++) { + var patternString = patternStrings_1[_i]; + var pattern = tryParsePattern(patternString); + if (pattern) { + patterns.push(pattern); + } + else if (patternString === candidate) { + // pattern was matched as is - no need to search further + return patternString; + } + } + return ts.findBestPatternMatch(patterns, function (_) { return _; }, candidate); + } + ts.matchPatternOrExact = matchPatternOrExact; + function sliceAfter(arr, value) { + var index = arr.indexOf(value); + Debug.assert(index !== -1); + return arr.slice(index); + } + ts.sliceAfter = sliceAfter; + function minAndMax(arr, getValue) { + Debug.assert(arr.length !== 0); + var min = getValue(arr[0]); + var max = min; + for (var i = 1; i < arr.length; i++) { + var value = getValue(arr[i]); + if (value < min) { + min = value; + } + else if (value > max) { + max = value; + } + } + return { min: min, max: max }; + } + ts.minAndMax = minAndMax; + var NodeSet = /** @class */ (function () { + function NodeSet() { + this.map = ts.createMap(); + } + NodeSet.prototype.add = function (node) { + this.map.set(String(ts.getNodeId(node)), node); + }; + NodeSet.prototype.tryAdd = function (node) { + if (this.has(node)) + return false; + this.add(node); + return true; + }; + NodeSet.prototype.has = function (node) { + return this.map.has(String(ts.getNodeId(node))); + }; + NodeSet.prototype.forEach = function (cb) { + this.map.forEach(cb); + }; + NodeSet.prototype.some = function (pred) { + return ts.forEachEntry(this.map, pred) || false; + }; + return NodeSet; + }()); + ts.NodeSet = NodeSet; + var NodeMap = /** @class */ (function () { + function NodeMap() { + this.map = ts.createMap(); + } + NodeMap.prototype.get = function (node) { + var res = this.map.get(String(ts.getNodeId(node))); + return res && res.value; + }; + NodeMap.prototype.getOrUpdate = function (node, setValue) { + var res = this.get(node); + if (res) + return res; + var value = setValue(); + this.set(node, value); + return value; + }; + NodeMap.prototype.set = function (node, value) { + this.map.set(String(ts.getNodeId(node)), { node: node, value: value }); + }; + NodeMap.prototype.has = function (node) { + return this.map.has(String(ts.getNodeId(node))); + }; + NodeMap.prototype.forEach = function (cb) { + this.map.forEach(function (_a) { + var node = _a.node, value = _a.value; + return cb(value, node); + }); + }; + return NodeMap; + }()); + ts.NodeMap = NodeMap; + function rangeOfNode(node) { + return { pos: ts.getTokenPosOfNode(node), end: node.end }; + } + ts.rangeOfNode = rangeOfNode; + function rangeOfTypeParameters(typeParameters) { + // Include the `<>` + return { pos: typeParameters.pos - 1, end: typeParameters.end + 1 }; + } + ts.rangeOfTypeParameters = rangeOfTypeParameters; + function skipTypeChecking(sourceFile, options) { + // If skipLibCheck is enabled, skip reporting errors if file is a declaration file. + // If skipDefaultLibCheck is enabled, skip reporting errors if file contains a + // '/// ' directive. + return options.skipLibCheck && sourceFile.isDeclarationFile || options.skipDefaultLibCheck && sourceFile.hasNoDefaultLib; + } + ts.skipTypeChecking = skipTypeChecking; + function isJsonEqual(a, b) { + return a === b || typeof a === "object" && a !== null && typeof b === "object" && b !== null && ts.equalOwnProperties(a, b, isJsonEqual); + } + ts.isJsonEqual = isJsonEqual; + function getOrUpdate(map, key, getDefault) { + var got = map.get(key); + if (got === undefined) { + var value = getDefault(); + map.set(key, value); + return value; + } + else { + return got; + } + } + ts.getOrUpdate = getOrUpdate; + /** + * Converts a bigint literal string, e.g. `0x1234n`, + * to its decimal string representation, e.g. `4660`. + */ + function parsePseudoBigInt(stringValue) { + var log2Base; + switch (stringValue.charCodeAt(1)) { // "x" in "0x123" + case 98 /* b */: + case 66 /* B */: // 0b or 0B + log2Base = 1; + break; + case 111 /* o */: + case 79 /* O */: // 0o or 0O + log2Base = 3; + break; + case 120 /* x */: + case 88 /* X */: // 0x or 0X + log2Base = 4; + break; + default: // already in decimal; omit trailing "n" + var nIndex = stringValue.length - 1; + // Skip leading 0s + var nonZeroStart = 0; + while (stringValue.charCodeAt(nonZeroStart) === 48 /* _0 */) { + nonZeroStart++; + } + return stringValue.slice(nonZeroStart, nIndex) || "0"; + } + // Omit leading "0b", "0o", or "0x", and trailing "n" + var startIndex = 2, endIndex = stringValue.length - 1; + var bitsNeeded = (endIndex - startIndex) * log2Base; + // Stores the value specified by the string as a LE array of 16-bit integers + // using Uint16 instead of Uint32 so combining steps can use bitwise operators + var segments = new Uint16Array((bitsNeeded >>> 4) + (bitsNeeded & 15 ? 1 : 0)); + // Add the digits, one at a time + for (var i = endIndex - 1, bitOffset = 0; i >= startIndex; i--, bitOffset += log2Base) { + var segment = bitOffset >>> 4; + var digitChar = stringValue.charCodeAt(i); + // Find character range: 0-9 < A-F < a-f + var digit = digitChar <= 57 /* _9 */ + ? digitChar - 48 /* _0 */ + : 10 + digitChar - + (digitChar <= 70 /* F */ ? 65 /* A */ : 97 /* a */); + var shiftedDigit = digit << (bitOffset & 15); + segments[segment] |= shiftedDigit; + var residual = shiftedDigit >>> 16; + if (residual) + segments[segment + 1] |= residual; // overflows segment + } + // Repeatedly divide segments by 10 and add remainder to base10Value + var base10Value = ""; + var firstNonzeroSegment = segments.length - 1; + var segmentsRemaining = true; + while (segmentsRemaining) { + var mod10 = 0; + segmentsRemaining = false; + for (var segment = firstNonzeroSegment; segment >= 0; segment--) { + var newSegment = mod10 << 16 | segments[segment]; + var segmentValue = (newSegment / 10) | 0; + segments[segment] = segmentValue; + mod10 = newSegment - segmentValue * 10; + if (segmentValue && !segmentsRemaining) { + firstNonzeroSegment = segment; + segmentsRemaining = true; + } + } + base10Value = mod10 + base10Value; + } + return base10Value; + } + ts.parsePseudoBigInt = parsePseudoBigInt; + function pseudoBigIntToString(_a) { + var negative = _a.negative, base10Value = _a.base10Value; + return (negative && base10Value !== "0" ? "-" : "") + base10Value; + } + ts.pseudoBigIntToString = pseudoBigIntToString; +})(ts || (ts = {})); +var ts; +(function (ts) { + var SignatureFlags; + (function (SignatureFlags) { + SignatureFlags[SignatureFlags["None"] = 0] = "None"; + SignatureFlags[SignatureFlags["Yield"] = 1] = "Yield"; + SignatureFlags[SignatureFlags["Await"] = 2] = "Await"; + SignatureFlags[SignatureFlags["Type"] = 4] = "Type"; + SignatureFlags[SignatureFlags["IgnoreMissingOpenBrace"] = 16] = "IgnoreMissingOpenBrace"; + SignatureFlags[SignatureFlags["JSDoc"] = 32] = "JSDoc"; + })(SignatureFlags || (SignatureFlags = {})); + // tslint:disable variable-name + var NodeConstructor; + var TokenConstructor; + var IdentifierConstructor; + var SourceFileConstructor; + // tslint:enable variable-name + function createNode(kind, pos, end) { + if (kind === 279 /* SourceFile */) { + return new (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor()))(kind, pos, end); + } + else if (kind === 72 /* Identifier */) { + return new (IdentifierConstructor || (IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor()))(kind, pos, end); + } + else if (!ts.isNodeKind(kind)) { + return new (TokenConstructor || (TokenConstructor = ts.objectAllocator.getTokenConstructor()))(kind, pos, end); + } + else { + return new (NodeConstructor || (NodeConstructor = ts.objectAllocator.getNodeConstructor()))(kind, pos, end); + } + } + ts.createNode = createNode; + function visitNode(cbNode, node) { + return node && cbNode(node); + } + function visitNodes(cbNode, cbNodes, nodes) { + if (nodes) { + if (cbNodes) { + return cbNodes(nodes); + } + for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) { + var node = nodes_1[_i]; + var result = cbNode(node); + if (result) { + return result; + } + } + } + } + /*@internal*/ + function isJSDocLikeText(text, start) { + return text.charCodeAt(start + 1) === 42 /* asterisk */ && + text.charCodeAt(start + 2) === 42 /* asterisk */ && + text.charCodeAt(start + 3) !== 47 /* slash */; + } + ts.isJSDocLikeText = isJSDocLikeText; + /** + * Invokes a callback for each child of the given node. The 'cbNode' callback is invoked for all child nodes + * stored in properties. If a 'cbNodes' callback is specified, it is invoked for embedded arrays; otherwise, + * embedded arrays are flattened and the 'cbNode' callback is invoked for each element. If a callback returns + * a truthy value, iteration stops and that value is returned. Otherwise, undefined is returned. + * + * @param node a given node to visit its children + * @param cbNode a callback to be invoked for all child nodes + * @param cbNodes a callback to be invoked for embedded array + * + * @remarks `forEachChild` must visit the children of a node in the order + * that they appear in the source code. The language service depends on this property to locate nodes by position. + */ + function forEachChild(node, cbNode, cbNodes) { + if (!node || node.kind <= 147 /* LastToken */) { + return; + } + switch (node.kind) { + case 148 /* QualifiedName */: + return visitNode(cbNode, node.left) || + visitNode(cbNode, node.right); + case 150 /* TypeParameter */: + return visitNode(cbNode, node.name) || + visitNode(cbNode, node.constraint) || + visitNode(cbNode, node.default) || + visitNode(cbNode, node.expression); + case 276 /* ShorthandPropertyAssignment */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.exclamationToken) || + visitNode(cbNode, node.equalsToken) || + visitNode(cbNode, node.objectAssignmentInitializer); + case 277 /* SpreadAssignment */: + return visitNode(cbNode, node.expression); + case 151 /* Parameter */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.dotDotDotToken) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.type) || + visitNode(cbNode, node.initializer); + case 154 /* PropertyDeclaration */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.exclamationToken) || + visitNode(cbNode, node.type) || + visitNode(cbNode, node.initializer); + case 153 /* PropertySignature */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.type) || + visitNode(cbNode, node.initializer); + case 275 /* PropertyAssignment */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.initializer); + case 237 /* VariableDeclaration */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.exclamationToken) || + visitNode(cbNode, node.type) || + visitNode(cbNode, node.initializer); + case 186 /* BindingElement */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.dotDotDotToken) || + visitNode(cbNode, node.propertyName) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.initializer); + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 162 /* IndexSignature */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type); + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 196 /* FunctionExpression */: + case 239 /* FunctionDeclaration */: + case 197 /* ArrowFunction */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.asteriskToken) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.exclamationToken) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type) || + visitNode(cbNode, node.equalsGreaterThanToken) || + visitNode(cbNode, node.body); + case 164 /* TypeReference */: + return visitNode(cbNode, node.typeName) || + visitNodes(cbNode, cbNodes, node.typeArguments); + case 163 /* TypePredicate */: + return visitNode(cbNode, node.parameterName) || + visitNode(cbNode, node.type); + case 167 /* TypeQuery */: + return visitNode(cbNode, node.exprName); + case 168 /* TypeLiteral */: + return visitNodes(cbNode, cbNodes, node.members); + case 169 /* ArrayType */: + return visitNode(cbNode, node.elementType); + case 170 /* TupleType */: + return visitNodes(cbNode, cbNodes, node.elementTypes); + case 173 /* UnionType */: + case 174 /* IntersectionType */: + return visitNodes(cbNode, cbNodes, node.types); + case 175 /* ConditionalType */: + return visitNode(cbNode, node.checkType) || + visitNode(cbNode, node.extendsType) || + visitNode(cbNode, node.trueType) || + visitNode(cbNode, node.falseType); + case 176 /* InferType */: + return visitNode(cbNode, node.typeParameter); + case 183 /* ImportType */: + return visitNode(cbNode, node.argument) || + visitNode(cbNode, node.qualifier) || + visitNodes(cbNode, cbNodes, node.typeArguments); + case 177 /* ParenthesizedType */: + case 179 /* TypeOperator */: + return visitNode(cbNode, node.type); + case 180 /* IndexedAccessType */: + return visitNode(cbNode, node.objectType) || + visitNode(cbNode, node.indexType); + case 181 /* MappedType */: + return visitNode(cbNode, node.readonlyToken) || + visitNode(cbNode, node.typeParameter) || + visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.type); + case 182 /* LiteralType */: + return visitNode(cbNode, node.literal); + case 184 /* ObjectBindingPattern */: + case 185 /* ArrayBindingPattern */: + return visitNodes(cbNode, cbNodes, node.elements); + case 187 /* ArrayLiteralExpression */: + return visitNodes(cbNode, cbNodes, node.elements); + case 188 /* ObjectLiteralExpression */: + return visitNodes(cbNode, cbNodes, node.properties); + case 189 /* PropertyAccessExpression */: + return visitNode(cbNode, node.expression) || + visitNode(cbNode, node.name); + case 190 /* ElementAccessExpression */: + return visitNode(cbNode, node.expression) || + visitNode(cbNode, node.argumentExpression); + case 191 /* CallExpression */: + case 192 /* NewExpression */: + return visitNode(cbNode, node.expression) || + visitNodes(cbNode, cbNodes, node.typeArguments) || + visitNodes(cbNode, cbNodes, node.arguments); + case 193 /* TaggedTemplateExpression */: + return visitNode(cbNode, node.tag) || + visitNodes(cbNode, cbNodes, node.typeArguments) || + visitNode(cbNode, node.template); + case 194 /* TypeAssertionExpression */: + return visitNode(cbNode, node.type) || + visitNode(cbNode, node.expression); + case 195 /* ParenthesizedExpression */: + return visitNode(cbNode, node.expression); + case 198 /* DeleteExpression */: + return visitNode(cbNode, node.expression); + case 199 /* TypeOfExpression */: + return visitNode(cbNode, node.expression); + case 200 /* VoidExpression */: + return visitNode(cbNode, node.expression); + case 202 /* PrefixUnaryExpression */: + return visitNode(cbNode, node.operand); + case 207 /* YieldExpression */: + return visitNode(cbNode, node.asteriskToken) || + visitNode(cbNode, node.expression); + case 201 /* AwaitExpression */: + return visitNode(cbNode, node.expression); + case 203 /* PostfixUnaryExpression */: + return visitNode(cbNode, node.operand); + case 204 /* BinaryExpression */: + return visitNode(cbNode, node.left) || + visitNode(cbNode, node.operatorToken) || + visitNode(cbNode, node.right); + case 212 /* AsExpression */: + return visitNode(cbNode, node.expression) || + visitNode(cbNode, node.type); + case 213 /* NonNullExpression */: + return visitNode(cbNode, node.expression); + case 214 /* MetaProperty */: + return visitNode(cbNode, node.name); + case 205 /* ConditionalExpression */: + return visitNode(cbNode, node.condition) || + visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.whenTrue) || + visitNode(cbNode, node.colonToken) || + visitNode(cbNode, node.whenFalse); + case 208 /* SpreadElement */: + return visitNode(cbNode, node.expression); + case 218 /* Block */: + case 245 /* ModuleBlock */: + return visitNodes(cbNode, cbNodes, node.statements); + case 279 /* SourceFile */: + return visitNodes(cbNode, cbNodes, node.statements) || + visitNode(cbNode, node.endOfFileToken); + case 219 /* VariableStatement */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.declarationList); + case 238 /* VariableDeclarationList */: + return visitNodes(cbNode, cbNodes, node.declarations); + case 221 /* ExpressionStatement */: + return visitNode(cbNode, node.expression); + case 222 /* IfStatement */: + return visitNode(cbNode, node.expression) || + visitNode(cbNode, node.thenStatement) || + visitNode(cbNode, node.elseStatement); + case 223 /* DoStatement */: + return visitNode(cbNode, node.statement) || + visitNode(cbNode, node.expression); + case 224 /* WhileStatement */: + return visitNode(cbNode, node.expression) || + visitNode(cbNode, node.statement); + case 225 /* ForStatement */: + return visitNode(cbNode, node.initializer) || + visitNode(cbNode, node.condition) || + visitNode(cbNode, node.incrementor) || + visitNode(cbNode, node.statement); + case 226 /* ForInStatement */: + return visitNode(cbNode, node.initializer) || + visitNode(cbNode, node.expression) || + visitNode(cbNode, node.statement); + case 227 /* ForOfStatement */: + return visitNode(cbNode, node.awaitModifier) || + visitNode(cbNode, node.initializer) || + visitNode(cbNode, node.expression) || + visitNode(cbNode, node.statement); + case 228 /* ContinueStatement */: + case 229 /* BreakStatement */: + return visitNode(cbNode, node.label); + case 230 /* ReturnStatement */: + return visitNode(cbNode, node.expression); + case 231 /* WithStatement */: + return visitNode(cbNode, node.expression) || + visitNode(cbNode, node.statement); + case 232 /* SwitchStatement */: + return visitNode(cbNode, node.expression) || + visitNode(cbNode, node.caseBlock); + case 246 /* CaseBlock */: + return visitNodes(cbNode, cbNodes, node.clauses); + case 271 /* CaseClause */: + return visitNode(cbNode, node.expression) || + visitNodes(cbNode, cbNodes, node.statements); + case 272 /* DefaultClause */: + return visitNodes(cbNode, cbNodes, node.statements); + case 233 /* LabeledStatement */: + return visitNode(cbNode, node.label) || + visitNode(cbNode, node.statement); + case 234 /* ThrowStatement */: + return visitNode(cbNode, node.expression); + case 235 /* TryStatement */: + return visitNode(cbNode, node.tryBlock) || + visitNode(cbNode, node.catchClause) || + visitNode(cbNode, node.finallyBlock); + case 274 /* CatchClause */: + return visitNode(cbNode, node.variableDeclaration) || + visitNode(cbNode, node.block); + case 152 /* Decorator */: + return visitNode(cbNode, node.expression); + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.heritageClauses) || + visitNodes(cbNode, cbNodes, node.members); + case 241 /* InterfaceDeclaration */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.heritageClauses) || + visitNodes(cbNode, cbNodes, node.members); + case 242 /* TypeAliasDeclaration */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNode(cbNode, node.type); + case 243 /* EnumDeclaration */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNodes(cbNode, cbNodes, node.members); + case 278 /* EnumMember */: + return visitNode(cbNode, node.name) || + visitNode(cbNode, node.initializer); + case 244 /* ModuleDeclaration */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.body); + case 248 /* ImportEqualsDeclaration */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.moduleReference); + case 249 /* ImportDeclaration */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.importClause) || + visitNode(cbNode, node.moduleSpecifier); + case 250 /* ImportClause */: + return visitNode(cbNode, node.name) || + visitNode(cbNode, node.namedBindings); + case 247 /* NamespaceExportDeclaration */: + return visitNode(cbNode, node.name); + case 251 /* NamespaceImport */: + return visitNode(cbNode, node.name); + case 252 /* NamedImports */: + case 256 /* NamedExports */: + return visitNodes(cbNode, cbNodes, node.elements); + case 255 /* ExportDeclaration */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.exportClause) || + visitNode(cbNode, node.moduleSpecifier); + case 253 /* ImportSpecifier */: + case 257 /* ExportSpecifier */: + return visitNode(cbNode, node.propertyName) || + visitNode(cbNode, node.name); + case 254 /* ExportAssignment */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.expression); + case 206 /* TemplateExpression */: + return visitNode(cbNode, node.head) || visitNodes(cbNode, cbNodes, node.templateSpans); + case 216 /* TemplateSpan */: + return visitNode(cbNode, node.expression) || visitNode(cbNode, node.literal); + case 149 /* ComputedPropertyName */: + return visitNode(cbNode, node.expression); + case 273 /* HeritageClause */: + return visitNodes(cbNode, cbNodes, node.types); + case 211 /* ExpressionWithTypeArguments */: + return visitNode(cbNode, node.expression) || + visitNodes(cbNode, cbNodes, node.typeArguments); + case 259 /* ExternalModuleReference */: + return visitNode(cbNode, node.expression); + case 258 /* MissingDeclaration */: + return visitNodes(cbNode, cbNodes, node.decorators); + case 309 /* CommaListExpression */: + return visitNodes(cbNode, cbNodes, node.elements); + case 260 /* JsxElement */: + return visitNode(cbNode, node.openingElement) || + visitNodes(cbNode, cbNodes, node.children) || + visitNode(cbNode, node.closingElement); + case 264 /* JsxFragment */: + return visitNode(cbNode, node.openingFragment) || + visitNodes(cbNode, cbNodes, node.children) || + visitNode(cbNode, node.closingFragment); + case 261 /* JsxSelfClosingElement */: + case 262 /* JsxOpeningElement */: + return visitNode(cbNode, node.tagName) || + visitNodes(cbNode, cbNodes, node.typeArguments) || + visitNode(cbNode, node.attributes); + case 268 /* JsxAttributes */: + return visitNodes(cbNode, cbNodes, node.properties); + case 267 /* JsxAttribute */: + return visitNode(cbNode, node.name) || + visitNode(cbNode, node.initializer); + case 269 /* JsxSpreadAttribute */: + return visitNode(cbNode, node.expression); + case 270 /* JsxExpression */: + return visitNode(cbNode, node.dotDotDotToken) || + visitNode(cbNode, node.expression); + case 263 /* JsxClosingElement */: + return visitNode(cbNode, node.tagName); + case 171 /* OptionalType */: + case 172 /* RestType */: + case 283 /* JSDocTypeExpression */: + case 287 /* JSDocNonNullableType */: + case 286 /* JSDocNullableType */: + case 288 /* JSDocOptionalType */: + case 290 /* JSDocVariadicType */: + return visitNode(cbNode, node.type); + case 289 /* JSDocFunctionType */: + return visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type); + case 291 /* JSDocComment */: + return visitNodes(cbNode, cbNodes, node.tags); + case 299 /* JSDocParameterTag */: + case 305 /* JSDocPropertyTag */: + return visitNode(cbNode, node.tagName) || + (node.isNameFirst + ? visitNode(cbNode, node.name) || + visitNode(cbNode, node.typeExpression) + : visitNode(cbNode, node.typeExpression) || + visitNode(cbNode, node.name)); + case 295 /* JSDocAugmentsTag */: + return visitNode(cbNode, node.tagName) || + visitNode(cbNode, node.class); + case 303 /* JSDocTemplateTag */: + return visitNode(cbNode, node.tagName) || + visitNode(cbNode, node.constraint) || + visitNodes(cbNode, cbNodes, node.typeParameters); + case 304 /* JSDocTypedefTag */: + return visitNode(cbNode, node.tagName) || + (node.typeExpression && + node.typeExpression.kind === 283 /* JSDocTypeExpression */ + ? visitNode(cbNode, node.typeExpression) || + visitNode(cbNode, node.fullName) + : visitNode(cbNode, node.fullName) || + visitNode(cbNode, node.typeExpression)); + case 297 /* JSDocCallbackTag */: + return visitNode(cbNode, node.tagName) || + visitNode(cbNode, node.fullName) || + visitNode(cbNode, node.typeExpression); + case 300 /* JSDocReturnTag */: + case 302 /* JSDocTypeTag */: + case 301 /* JSDocThisTag */: + case 298 /* JSDocEnumTag */: + return visitNode(cbNode, node.tagName) || + visitNode(cbNode, node.typeExpression); + case 293 /* JSDocSignature */: + return ts.forEach(node.typeParameters, cbNode) || + ts.forEach(node.parameters, cbNode) || + visitNode(cbNode, node.type); + case 292 /* JSDocTypeLiteral */: + return ts.forEach(node.jsDocPropertyTags, cbNode); + case 294 /* JSDocTag */: + case 296 /* JSDocClassTag */: + return visitNode(cbNode, node.tagName); + case 308 /* PartiallyEmittedExpression */: + return visitNode(cbNode, node.expression); + } + } + ts.forEachChild = forEachChild; + function createSourceFile(fileName, sourceText, languageVersion, setParentNodes, scriptKind) { + if (setParentNodes === void 0) { setParentNodes = false; } + ts.performance.mark("beforeParse"); + var result; + if (languageVersion === 100 /* JSON */) { + result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes, 6 /* JSON */); + } + else { + result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes, scriptKind); + } + ts.performance.mark("afterParse"); + ts.performance.measure("Parse", "beforeParse", "afterParse"); + return result; + } + ts.createSourceFile = createSourceFile; + function parseIsolatedEntityName(text, languageVersion) { + return Parser.parseIsolatedEntityName(text, languageVersion); + } + ts.parseIsolatedEntityName = parseIsolatedEntityName; + /** + * Parse json text into SyntaxTree and return node and parse errors if any + * @param fileName + * @param sourceText + */ + function parseJsonText(fileName, sourceText) { + return Parser.parseJsonText(fileName, sourceText); + } + ts.parseJsonText = parseJsonText; + // See also `isExternalOrCommonJsModule` in utilities.ts + function isExternalModule(file) { + return file.externalModuleIndicator !== undefined; + } + ts.isExternalModule = isExternalModule; + // Produces a new SourceFile for the 'newText' provided. The 'textChangeRange' parameter + // indicates what changed between the 'text' that this SourceFile has and the 'newText'. + // The SourceFile will be created with the compiler attempting to reuse as many nodes from + // this file as possible. + // + // Note: this function mutates nodes from this SourceFile. That means any existing nodes + // from this SourceFile that are being held onto may change as a result (including + // becoming detached from any SourceFile). It is recommended that this SourceFile not + // be used once 'update' is called on it. + function updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks) { + if (aggressiveChecks === void 0) { aggressiveChecks = false; } + var newSourceFile = IncrementalParser.updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks); + // Because new source file node is created, it may not have the flag PossiblyContainDynamicImport. This is the case if there is no new edit to add dynamic import. + // We will manually port the flag to the new source file. + newSourceFile.flags |= (sourceFile.flags & 1572864 /* PermanentlySetIncrementalFlags */); + return newSourceFile; + } + ts.updateSourceFile = updateSourceFile; + /* @internal */ + function parseIsolatedJSDocComment(content, start, length) { + var result = Parser.JSDocParser.parseIsolatedJSDocComment(content, start, length); + if (result && result.jsDoc) { + // because the jsDocComment was parsed out of the source file, it might + // not be covered by the fixupParentReferences. + Parser.fixupParentReferences(result.jsDoc); + } + return result; + } + ts.parseIsolatedJSDocComment = parseIsolatedJSDocComment; + /* @internal */ + // Exposed only for testing. + function parseJSDocTypeExpressionForTests(content, start, length) { + return Parser.JSDocParser.parseJSDocTypeExpressionForTests(content, start, length); + } + ts.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests; + // Implement the parser as a singleton module. We do this for perf reasons because creating + // parser instances can actually be expensive enough to impact us on projects with many source + // files. + var Parser; + (function (Parser) { + // Share a single scanner across all calls to parse a source file. This helps speed things + // up by avoiding the cost of creating/compiling scanners over and over again. + var scanner = ts.createScanner(6 /* Latest */, /*skipTrivia*/ true); + var disallowInAndDecoratorContext = 2048 /* DisallowInContext */ | 8192 /* DecoratorContext */; + // capture constructors in 'initializeState' to avoid null checks + // tslint:disable variable-name + var NodeConstructor; + var TokenConstructor; + var IdentifierConstructor; + var SourceFileConstructor; + // tslint:enable variable-name + var sourceFile; + var parseDiagnostics; + var syntaxCursor; + var currentToken; + var sourceText; + var nodeCount; + var identifiers; + var identifierCount; + var parsingContext; + // Flags that dictate what parsing context we're in. For example: + // Whether or not we are in strict parsing mode. All that changes in strict parsing mode is + // that some tokens that would be considered identifiers may be considered keywords. + // + // When adding more parser context flags, consider which is the more common case that the + // flag will be in. This should be the 'false' state for that flag. The reason for this is + // that we don't store data in our nodes unless the value is in the *non-default* state. So, + // for example, more often than code 'allows-in' (or doesn't 'disallow-in'). We opt for + // 'disallow-in' set to 'false'. Otherwise, if we had 'allowsIn' set to 'true', then almost + // all nodes would need extra state on them to store this info. + // + // Note: 'allowIn' and 'allowYield' track 1:1 with the [in] and [yield] concepts in the ES6 + // grammar specification. + // + // An important thing about these context concepts. By default they are effectively inherited + // while parsing through every grammar production. i.e. if you don't change them, then when + // you parse a sub-production, it will have the same context values as the parent production. + // This is great most of the time. After all, consider all the 'expression' grammar productions + // and how nearly all of them pass along the 'in' and 'yield' context values: + // + // EqualityExpression[In, Yield] : + // RelationalExpression[?In, ?Yield] + // EqualityExpression[?In, ?Yield] == RelationalExpression[?In, ?Yield] + // EqualityExpression[?In, ?Yield] != RelationalExpression[?In, ?Yield] + // EqualityExpression[?In, ?Yield] === RelationalExpression[?In, ?Yield] + // EqualityExpression[?In, ?Yield] !== RelationalExpression[?In, ?Yield] + // + // Where you have to be careful is then understanding what the points are in the grammar + // where the values are *not* passed along. For example: + // + // SingleNameBinding[Yield,GeneratorParameter] + // [+GeneratorParameter]BindingIdentifier[Yield] Initializer[In]opt + // [~GeneratorParameter]BindingIdentifier[?Yield]Initializer[In, ?Yield]opt + // + // Here this is saying that if the GeneratorParameter context flag is set, that we should + // explicitly set the 'yield' context flag to false before calling into the BindingIdentifier + // and we should explicitly unset the 'yield' context flag before calling into the Initializer. + // production. Conversely, if the GeneratorParameter context flag is not set, then we + // should leave the 'yield' context flag alone. + // + // Getting this all correct is tricky and requires careful reading of the grammar to + // understand when these values should be changed versus when they should be inherited. + // + // Note: it should not be necessary to save/restore these flags during speculative/lookahead + // parsing. These context flags are naturally stored and restored through normal recursive + // descent parsing and unwinding. + var contextFlags; + // Whether or not we've had a parse error since creating the last AST node. If we have + // encountered an error, it will be stored on the next AST node we create. Parse errors + // can be broken down into three categories: + // + // 1) An error that occurred during scanning. For example, an unterminated literal, or a + // character that was completely not understood. + // + // 2) A token was expected, but was not present. This type of error is commonly produced + // by the 'parseExpected' function. + // + // 3) A token was present that no parsing function was able to consume. This type of error + // only occurs in the 'abortParsingListOrMoveToNextToken' function when the parser + // decides to skip the token. + // + // In all of these cases, we want to mark the next node as having had an error before it. + // With this mark, we can know in incremental settings if this node can be reused, or if + // we have to reparse it. If we don't keep this information around, we may just reuse the + // node. in that event we would then not produce the same errors as we did before, causing + // significant confusion problems. + // + // Note: it is necessary that this value be saved/restored during speculative/lookahead + // parsing. During lookahead parsing, we will often create a node. That node will have + // this value attached, and then this value will be set back to 'false'. If we decide to + // rewind, we must get back to the same value we had prior to the lookahead. + // + // Note: any errors at the end of the file that do not precede a regular node, should get + // attached to the EOF token. + var parseErrorBeforeNextFinishedNode = false; + function parseSourceFile(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes, scriptKind) { + if (setParentNodes === void 0) { setParentNodes = false; } + scriptKind = ts.ensureScriptKind(fileName, scriptKind); + if (scriptKind === 6 /* JSON */) { + var result_1 = parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes); + ts.convertToObjectWorker(result_1, result_1.parseDiagnostics, /*returnValue*/ false, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined); + result_1.referencedFiles = ts.emptyArray; + result_1.typeReferenceDirectives = ts.emptyArray; + result_1.libReferenceDirectives = ts.emptyArray; + result_1.amdDependencies = ts.emptyArray; + result_1.hasNoDefaultLib = false; + result_1.pragmas = ts.emptyMap; + return result_1; + } + initializeState(sourceText, languageVersion, syntaxCursor, scriptKind); + var result = parseSourceFileWorker(fileName, languageVersion, setParentNodes, scriptKind); + clearState(); + return result; + } + Parser.parseSourceFile = parseSourceFile; + function parseIsolatedEntityName(content, languageVersion) { + // Choice of `isDeclarationFile` should be arbitrary + initializeState(content, languageVersion, /*syntaxCursor*/ undefined, 1 /* JS */); + // Prime the scanner. + nextToken(); + var entityName = parseEntityName(/*allowReservedWords*/ true); + var isInvalid = token() === 1 /* EndOfFileToken */ && !parseDiagnostics.length; + clearState(); + return isInvalid ? entityName : undefined; + } + Parser.parseIsolatedEntityName = parseIsolatedEntityName; + function parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes) { + if (languageVersion === void 0) { languageVersion = 2 /* ES2015 */; } + initializeState(sourceText, languageVersion, syntaxCursor, 6 /* JSON */); + // Set source file so that errors will be reported with this file name + sourceFile = createSourceFile(fileName, 2 /* ES2015 */, 6 /* JSON */, /*isDeclaration*/ false); + sourceFile.flags = contextFlags; + // Prime the scanner. + nextToken(); + var pos = getNodePos(); + if (token() === 1 /* EndOfFileToken */) { + sourceFile.statements = createNodeArray([], pos, pos); + sourceFile.endOfFileToken = parseTokenNode(); + } + else { + var statement = createNode(221 /* ExpressionStatement */); + switch (token()) { + case 22 /* OpenBracketToken */: + statement.expression = parseArrayLiteralExpression(); + break; + case 102 /* TrueKeyword */: + case 87 /* FalseKeyword */: + case 96 /* NullKeyword */: + statement.expression = parseTokenNode(); + break; + case 39 /* MinusToken */: + if (lookAhead(function () { return nextToken() === 8 /* NumericLiteral */ && nextToken() !== 57 /* ColonToken */; })) { + statement.expression = parsePrefixUnaryExpression(); + } + else { + statement.expression = parseObjectLiteralExpression(); + } + break; + case 8 /* NumericLiteral */: + case 10 /* StringLiteral */: + if (lookAhead(function () { return nextToken() !== 57 /* ColonToken */; })) { + statement.expression = parseLiteralNode(); + break; + } + // falls through + default: + statement.expression = parseObjectLiteralExpression(); + break; + } + finishNode(statement); + sourceFile.statements = createNodeArray([statement], pos); + sourceFile.endOfFileToken = parseExpectedToken(1 /* EndOfFileToken */, ts.Diagnostics.Unexpected_token); + } + if (setParentNodes) { + fixupParentReferences(sourceFile); + } + sourceFile.parseDiagnostics = parseDiagnostics; + var result = sourceFile; + clearState(); + return result; + } + Parser.parseJsonText = parseJsonText; + function getLanguageVariant(scriptKind) { + // .tsx and .jsx files are treated as jsx language variant. + return scriptKind === 4 /* TSX */ || scriptKind === 2 /* JSX */ || scriptKind === 1 /* JS */ || scriptKind === 6 /* JSON */ ? 1 /* JSX */ : 0 /* Standard */; + } + function initializeState(_sourceText, languageVersion, _syntaxCursor, scriptKind) { + NodeConstructor = ts.objectAllocator.getNodeConstructor(); + TokenConstructor = ts.objectAllocator.getTokenConstructor(); + IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor(); + SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor(); + sourceText = _sourceText; + syntaxCursor = _syntaxCursor; + parseDiagnostics = []; + parsingContext = 0; + identifiers = ts.createMap(); + identifierCount = 0; + nodeCount = 0; + switch (scriptKind) { + case 1 /* JS */: + case 2 /* JSX */: + contextFlags = 65536 /* JavaScriptFile */; + break; + case 6 /* JSON */: + contextFlags = 65536 /* JavaScriptFile */ | 16777216 /* JsonFile */; + break; + default: + contextFlags = 0 /* None */; + break; + } + parseErrorBeforeNextFinishedNode = false; + // Initialize and prime the scanner before parsing the source elements. + scanner.setText(sourceText); + scanner.setOnError(scanError); + scanner.setScriptTarget(languageVersion); + scanner.setLanguageVariant(getLanguageVariant(scriptKind)); + } + function clearState() { + // Clear out the text the scanner is pointing at, so it doesn't keep anything alive unnecessarily. + scanner.setText(""); + scanner.setOnError(undefined); + // Clear any data. We don't want to accidentally hold onto it for too long. + parseDiagnostics = undefined; + sourceFile = undefined; + identifiers = undefined; + syntaxCursor = undefined; + sourceText = undefined; + } + function parseSourceFileWorker(fileName, languageVersion, setParentNodes, scriptKind) { + var isDeclarationFile = isDeclarationFileName(fileName); + if (isDeclarationFile) { + contextFlags |= 4194304 /* Ambient */; + } + sourceFile = createSourceFile(fileName, languageVersion, scriptKind, isDeclarationFile); + sourceFile.flags = contextFlags; + // Prime the scanner. + nextToken(); + // A member of ReadonlyArray isn't assignable to a member of T[] (and prevents a direct cast) - but this is where we set up those members so they can be readonly in the future + processCommentPragmas(sourceFile, sourceText); + processPragmasIntoFields(sourceFile, reportPragmaDiagnostic); + sourceFile.statements = parseList(0 /* SourceElements */, parseStatement); + ts.Debug.assert(token() === 1 /* EndOfFileToken */); + sourceFile.endOfFileToken = addJSDocComment(parseTokenNode()); + setExternalModuleIndicator(sourceFile); + sourceFile.nodeCount = nodeCount; + sourceFile.identifierCount = identifierCount; + sourceFile.identifiers = identifiers; + sourceFile.parseDiagnostics = parseDiagnostics; + if (setParentNodes) { + fixupParentReferences(sourceFile); + } + return sourceFile; + function reportPragmaDiagnostic(pos, end, diagnostic) { + parseDiagnostics.push(ts.createFileDiagnostic(sourceFile, pos, end, diagnostic)); + } + } + function addJSDocComment(node) { + ts.Debug.assert(!node.jsDoc); // Should only be called once per node + var jsDoc = ts.mapDefined(ts.getJSDocCommentRanges(node, sourceFile.text), function (comment) { return JSDocParser.parseJSDocComment(node, comment.pos, comment.end - comment.pos); }); + if (jsDoc.length) + node.jsDoc = jsDoc; + return node; + } + function fixupParentReferences(rootNode) { + // normally parent references are set during binding. However, for clients that only need + // a syntax tree, and no semantic features, then the binding process is an unnecessary + // overhead. This functions allows us to set all the parents, without all the expense of + // binding. + var parent = rootNode; + forEachChild(rootNode, visitNode); + return; + function visitNode(n) { + // walk down setting parents that differ from the parent we think it should be. This + // allows us to quickly bail out of setting parents for subtrees during incremental + // parsing + if (n.parent !== parent) { + n.parent = parent; + var saveParent = parent; + parent = n; + forEachChild(n, visitNode); + if (ts.hasJSDocNodes(n)) { + for (var _i = 0, _a = n.jsDoc; _i < _a.length; _i++) { + var jsDoc = _a[_i]; + jsDoc.parent = n; + parent = jsDoc; + forEachChild(jsDoc, visitNode); + } + } + parent = saveParent; + } + } + } + Parser.fixupParentReferences = fixupParentReferences; + function createSourceFile(fileName, languageVersion, scriptKind, isDeclarationFile) { + // code from createNode is inlined here so createNode won't have to deal with special case of creating source files + // this is quite rare comparing to other nodes and createNode should be as fast as possible + var sourceFile = new SourceFileConstructor(279 /* SourceFile */, /*pos*/ 0, /* end */ sourceText.length); + nodeCount++; + sourceFile.text = sourceText; + sourceFile.bindDiagnostics = []; + sourceFile.bindSuggestionDiagnostics = undefined; + sourceFile.languageVersion = languageVersion; + sourceFile.fileName = ts.normalizePath(fileName); + sourceFile.languageVariant = getLanguageVariant(scriptKind); + sourceFile.isDeclarationFile = isDeclarationFile; + sourceFile.scriptKind = scriptKind; + return sourceFile; + } + function setContextFlag(val, flag) { + if (val) { + contextFlags |= flag; + } + else { + contextFlags &= ~flag; + } + } + function setDisallowInContext(val) { + setContextFlag(val, 2048 /* DisallowInContext */); + } + function setYieldContext(val) { + setContextFlag(val, 4096 /* YieldContext */); + } + function setDecoratorContext(val) { + setContextFlag(val, 8192 /* DecoratorContext */); + } + function setAwaitContext(val) { + setContextFlag(val, 16384 /* AwaitContext */); + } + function doOutsideOfContext(context, func) { + // contextFlagsToClear will contain only the context flags that are + // currently set that we need to temporarily clear + // We don't just blindly reset to the previous flags to ensure + // that we do not mutate cached flags for the incremental + // parser (ThisNodeHasError, ThisNodeOrAnySubNodesHasError, and + // HasAggregatedChildData). + var contextFlagsToClear = context & contextFlags; + if (contextFlagsToClear) { + // clear the requested context flags + setContextFlag(/*val*/ false, contextFlagsToClear); + var result = func(); + // restore the context flags we just cleared + setContextFlag(/*val*/ true, contextFlagsToClear); + return result; + } + // no need to do anything special as we are not in any of the requested contexts + return func(); + } + function doInsideOfContext(context, func) { + // contextFlagsToSet will contain only the context flags that + // are not currently set that we need to temporarily enable. + // We don't just blindly reset to the previous flags to ensure + // that we do not mutate cached flags for the incremental + // parser (ThisNodeHasError, ThisNodeOrAnySubNodesHasError, and + // HasAggregatedChildData). + var contextFlagsToSet = context & ~contextFlags; + if (contextFlagsToSet) { + // set the requested context flags + setContextFlag(/*val*/ true, contextFlagsToSet); + var result = func(); + // reset the context flags we just set + setContextFlag(/*val*/ false, contextFlagsToSet); + return result; + } + // no need to do anything special as we are already in all of the requested contexts + return func(); + } + function allowInAnd(func) { + return doOutsideOfContext(2048 /* DisallowInContext */, func); + } + function disallowInAnd(func) { + return doInsideOfContext(2048 /* DisallowInContext */, func); + } + function doInYieldContext(func) { + return doInsideOfContext(4096 /* YieldContext */, func); + } + function doInDecoratorContext(func) { + return doInsideOfContext(8192 /* DecoratorContext */, func); + } + function doInAwaitContext(func) { + return doInsideOfContext(16384 /* AwaitContext */, func); + } + function doOutsideOfAwaitContext(func) { + return doOutsideOfContext(16384 /* AwaitContext */, func); + } + function doInYieldAndAwaitContext(func) { + return doInsideOfContext(4096 /* YieldContext */ | 16384 /* AwaitContext */, func); + } + function inContext(flags) { + return (contextFlags & flags) !== 0; + } + function inYieldContext() { + return inContext(4096 /* YieldContext */); + } + function inDisallowInContext() { + return inContext(2048 /* DisallowInContext */); + } + function inDecoratorContext() { + return inContext(8192 /* DecoratorContext */); + } + function inAwaitContext() { + return inContext(16384 /* AwaitContext */); + } + function parseErrorAtCurrentToken(message, arg0) { + parseErrorAt(scanner.getTokenPos(), scanner.getTextPos(), message, arg0); + } + function parseErrorAtPosition(start, length, message, arg0) { + // Don't report another error if it would just be at the same position as the last error. + var lastError = ts.lastOrUndefined(parseDiagnostics); + if (!lastError || start !== lastError.start) { + parseDiagnostics.push(ts.createFileDiagnostic(sourceFile, start, length, message, arg0)); + } + // Mark that we've encountered an error. We'll set an appropriate bit on the next + // node we finish so that it can't be reused incrementally. + parseErrorBeforeNextFinishedNode = true; + } + function parseErrorAt(start, end, message, arg0) { + parseErrorAtPosition(start, end - start, message, arg0); + } + function parseErrorAtRange(range, message, arg0) { + parseErrorAt(range.pos, range.end, message, arg0); + } + function scanError(message, length) { + parseErrorAtPosition(scanner.getTextPos(), length, message); + } + function getNodePos() { + return scanner.getStartPos(); + } + // Use this function to access the current token instead of reading the currentToken + // variable. Since function results aren't narrowed in control flow analysis, this ensures + // that the type checker doesn't make wrong assumptions about the type of the current + // token (e.g. a call to nextToken() changes the current token but the checker doesn't + // reason about this side effect). Mainstream VMs inline simple functions like this, so + // there is no performance penalty. + function token() { + return currentToken; + } + function nextToken() { + return currentToken = scanner.scan(); + } + function reScanGreaterToken() { + return currentToken = scanner.reScanGreaterToken(); + } + function reScanSlashToken() { + return currentToken = scanner.reScanSlashToken(); + } + function reScanTemplateToken() { + return currentToken = scanner.reScanTemplateToken(); + } + function scanJsxIdentifier() { + return currentToken = scanner.scanJsxIdentifier(); + } + function scanJsxText() { + return currentToken = scanner.scanJsxToken(); + } + function scanJsxAttributeValue() { + return currentToken = scanner.scanJsxAttributeValue(); + } + function speculationHelper(callback, isLookAhead) { + // Keep track of the state we'll need to rollback to if lookahead fails (or if the + // caller asked us to always reset our state). + var saveToken = currentToken; + var saveParseDiagnosticsLength = parseDiagnostics.length; + var saveParseErrorBeforeNextFinishedNode = parseErrorBeforeNextFinishedNode; + // Note: it is not actually necessary to save/restore the context flags here. That's + // because the saving/restoring of these flags happens naturally through the recursive + // descent nature of our parser. However, we still store this here just so we can + // assert that invariant holds. + var saveContextFlags = contextFlags; + // If we're only looking ahead, then tell the scanner to only lookahead as well. + // Otherwise, if we're actually speculatively parsing, then tell the scanner to do the + // same. + var result = isLookAhead + ? scanner.lookAhead(callback) + : scanner.tryScan(callback); + ts.Debug.assert(saveContextFlags === contextFlags); + // If our callback returned something 'falsy' or we're just looking ahead, + // then unconditionally restore us to where we were. + if (!result || isLookAhead) { + currentToken = saveToken; + parseDiagnostics.length = saveParseDiagnosticsLength; + parseErrorBeforeNextFinishedNode = saveParseErrorBeforeNextFinishedNode; + } + return result; + } + /** Invokes the provided callback then unconditionally restores the parser to the state it + * was in immediately prior to invoking the callback. The result of invoking the callback + * is returned from this function. + */ + function lookAhead(callback) { + return speculationHelper(callback, /*isLookAhead*/ true); + } + /** Invokes the provided callback. If the callback returns something falsy, then it restores + * the parser to the state it was in immediately prior to invoking the callback. If the + * callback returns something truthy, then the parser state is not rolled back. The result + * of invoking the callback is returned from this function. + */ + function tryParse(callback) { + return speculationHelper(callback, /*isLookAhead*/ false); + } + // Ignore strict mode flag because we will report an error in type checker instead. + function isIdentifier() { + if (token() === 72 /* Identifier */) { + return true; + } + // If we have a 'yield' keyword, and we're in the [yield] context, then 'yield' is + // considered a keyword and is not an identifier. + if (token() === 117 /* YieldKeyword */ && inYieldContext()) { + return false; + } + // If we have a 'await' keyword, and we're in the [Await] context, then 'await' is + // considered a keyword and is not an identifier. + if (token() === 122 /* AwaitKeyword */ && inAwaitContext()) { + return false; + } + return token() > 108 /* LastReservedWord */; + } + function parseExpected(kind, diagnosticMessage, shouldAdvance) { + if (shouldAdvance === void 0) { shouldAdvance = true; } + if (token() === kind) { + if (shouldAdvance) { + nextToken(); + } + return true; + } + // Report specific message if provided with one. Otherwise, report generic fallback message. + if (diagnosticMessage) { + parseErrorAtCurrentToken(diagnosticMessage); + } + else { + parseErrorAtCurrentToken(ts.Diagnostics._0_expected, ts.tokenToString(kind)); + } + return false; + } + function parseOptional(t) { + if (token() === t) { + nextToken(); + return true; + } + return false; + } + function parseOptionalToken(t) { + if (token() === t) { + return parseTokenNode(); + } + return undefined; + } + function parseExpectedToken(t, diagnosticMessage, arg0) { + return parseOptionalToken(t) || + createMissingNode(t, /*reportAtCurrentPosition*/ false, diagnosticMessage || ts.Diagnostics._0_expected, arg0 || ts.tokenToString(t)); + } + function parseTokenNode() { + var node = createNode(token()); + nextToken(); + return finishNode(node); + } + function canParseSemicolon() { + // If there's a real semicolon, then we can always parse it out. + if (token() === 26 /* SemicolonToken */) { + return true; + } + // We can parse out an optional semicolon in ASI cases in the following cases. + return token() === 19 /* CloseBraceToken */ || token() === 1 /* EndOfFileToken */ || scanner.hasPrecedingLineBreak(); + } + function parseSemicolon() { + if (canParseSemicolon()) { + if (token() === 26 /* SemicolonToken */) { + // consume the semicolon if it was explicitly provided. + nextToken(); + } + return true; + } + else { + return parseExpected(26 /* SemicolonToken */); + } + } + function createNode(kind, pos) { + nodeCount++; + var p = pos >= 0 ? pos : scanner.getStartPos(); + return ts.isNodeKind(kind) || kind === 0 /* Unknown */ ? new NodeConstructor(kind, p, p) : + kind === 72 /* Identifier */ ? new IdentifierConstructor(kind, p, p) : + new TokenConstructor(kind, p, p); + } + function createNodeWithJSDoc(kind, pos) { + var node = createNode(kind, pos); + if (scanner.getTokenFlags() & 2 /* PrecedingJSDocComment */) { + addJSDocComment(node); + } + return node; + } + function createNodeArray(elements, pos, end) { + // Since the element list of a node array is typically created by starting with an empty array and + // repeatedly calling push(), the list may not have the optimal memory layout. We invoke slice() for + // small arrays (1 to 4 elements) to give the VM a chance to allocate an optimal representation. + var length = elements.length; + var array = (length >= 1 && length <= 4 ? elements.slice() : elements); + array.pos = pos; + array.end = end === undefined ? scanner.getStartPos() : end; + return array; + } + function finishNode(node, end) { + node.end = end === undefined ? scanner.getStartPos() : end; + if (contextFlags) { + node.flags |= contextFlags; + } + // Keep track on the node if we encountered an error while parsing it. If we did, then + // we cannot reuse the node incrementally. Once we've marked this node, clear out the + // flag so that we don't mark any subsequent nodes. + if (parseErrorBeforeNextFinishedNode) { + parseErrorBeforeNextFinishedNode = false; + node.flags |= 32768 /* ThisNodeHasError */; + } + return node; + } + function createMissingNode(kind, reportAtCurrentPosition, diagnosticMessage, arg0) { + if (reportAtCurrentPosition) { + parseErrorAtPosition(scanner.getStartPos(), 0, diagnosticMessage, arg0); + } + else if (diagnosticMessage) { + parseErrorAtCurrentToken(diagnosticMessage, arg0); + } + var result = createNode(kind); + if (kind === 72 /* Identifier */) { + result.escapedText = ""; + } + else if (ts.isLiteralKind(kind) || ts.isTemplateLiteralKind(kind)) { + result.text = ""; + } + return finishNode(result); + } + function internIdentifier(text) { + var identifier = identifiers.get(text); + if (identifier === undefined) { + identifiers.set(text, identifier = text); + } + return identifier; + } + // An identifier that starts with two underscores has an extra underscore character prepended to it to avoid issues + // with magic property names like '__proto__'. The 'identifiers' object is used to share a single string instance for + // each identifier in order to reduce memory consumption. + function createIdentifier(isIdentifier, diagnosticMessage) { + identifierCount++; + if (isIdentifier) { + var node = createNode(72 /* Identifier */); + // Store original token kind if it is not just an Identifier so we can report appropriate error later in type checker + if (token() !== 72 /* Identifier */) { + node.originalKeywordKind = token(); + } + node.escapedText = ts.escapeLeadingUnderscores(internIdentifier(scanner.getTokenValue())); + nextToken(); + return finishNode(node); + } + // Only for end of file because the error gets reported incorrectly on embedded script tags. + var reportAtCurrentPosition = token() === 1 /* EndOfFileToken */; + return createMissingNode(72 /* Identifier */, reportAtCurrentPosition, diagnosticMessage || ts.Diagnostics.Identifier_expected); + } + function parseIdentifier(diagnosticMessage) { + return createIdentifier(isIdentifier(), diagnosticMessage); + } + function parseIdentifierName(diagnosticMessage) { + return createIdentifier(ts.tokenIsIdentifierOrKeyword(token()), diagnosticMessage); + } + function isLiteralPropertyName() { + return ts.tokenIsIdentifierOrKeyword(token()) || + token() === 10 /* StringLiteral */ || + token() === 8 /* NumericLiteral */; + } + function parsePropertyNameWorker(allowComputedPropertyNames) { + if (token() === 10 /* StringLiteral */ || token() === 8 /* NumericLiteral */) { + var node = parseLiteralNode(); + node.text = internIdentifier(node.text); + return node; + } + if (allowComputedPropertyNames && token() === 22 /* OpenBracketToken */) { + return parseComputedPropertyName(); + } + return parseIdentifierName(); + } + function parsePropertyName() { + return parsePropertyNameWorker(/*allowComputedPropertyNames*/ true); + } + function parseComputedPropertyName() { + // PropertyName [Yield]: + // LiteralPropertyName + // ComputedPropertyName[?Yield] + var node = createNode(149 /* ComputedPropertyName */); + parseExpected(22 /* OpenBracketToken */); + // We parse any expression (including a comma expression). But the grammar + // says that only an assignment expression is allowed, so the grammar checker + // will error if it sees a comma expression. + node.expression = allowInAnd(parseExpression); + parseExpected(23 /* CloseBracketToken */); + return finishNode(node); + } + function parseContextualModifier(t) { + return token() === t && tryParse(nextTokenCanFollowModifier); + } + function nextTokenIsOnSameLineAndCanFollowModifier() { + nextToken(); + if (scanner.hasPrecedingLineBreak()) { + return false; + } + return canFollowModifier(); + } + function nextTokenCanFollowModifier() { + switch (token()) { + case 77 /* ConstKeyword */: + // 'const' is only a modifier if followed by 'enum'. + return nextToken() === 84 /* EnumKeyword */; + case 85 /* ExportKeyword */: + nextToken(); + if (token() === 80 /* DefaultKeyword */) { + return lookAhead(nextTokenCanFollowDefaultKeyword); + } + return token() !== 40 /* AsteriskToken */ && token() !== 119 /* AsKeyword */ && token() !== 18 /* OpenBraceToken */ && canFollowModifier(); + case 80 /* DefaultKeyword */: + return nextTokenCanFollowDefaultKeyword(); + case 116 /* StaticKeyword */: + case 126 /* GetKeyword */: + case 137 /* SetKeyword */: + nextToken(); + return canFollowModifier(); + default: + return nextTokenIsOnSameLineAndCanFollowModifier(); + } + } + function parseAnyContextualModifier() { + return ts.isModifierKind(token()) && tryParse(nextTokenCanFollowModifier); + } + function canFollowModifier() { + return token() === 22 /* OpenBracketToken */ + || token() === 18 /* OpenBraceToken */ + || token() === 40 /* AsteriskToken */ + || token() === 25 /* DotDotDotToken */ + || isLiteralPropertyName(); + } + function nextTokenCanFollowDefaultKeyword() { + nextToken(); + return token() === 76 /* ClassKeyword */ || token() === 90 /* FunctionKeyword */ || + token() === 110 /* InterfaceKeyword */ || + (token() === 118 /* AbstractKeyword */ && lookAhead(nextTokenIsClassKeywordOnSameLine)) || + (token() === 121 /* AsyncKeyword */ && lookAhead(nextTokenIsFunctionKeywordOnSameLine)); + } + // True if positioned at the start of a list element + function isListElement(parsingContext, inErrorRecovery) { + var node = currentNode(parsingContext); + if (node) { + return true; + } + switch (parsingContext) { + case 0 /* SourceElements */: + case 1 /* BlockStatements */: + case 3 /* SwitchClauseStatements */: + // If we're in error recovery, then we don't want to treat ';' as an empty statement. + // The problem is that ';' can show up in far too many contexts, and if we see one + // and assume it's a statement, then we may bail out inappropriately from whatever + // we're parsing. For example, if we have a semicolon in the middle of a class, then + // we really don't want to assume the class is over and we're on a statement in the + // outer module. We just want to consume and move on. + return !(token() === 26 /* SemicolonToken */ && inErrorRecovery) && isStartOfStatement(); + case 2 /* SwitchClauses */: + return token() === 74 /* CaseKeyword */ || token() === 80 /* DefaultKeyword */; + case 4 /* TypeMembers */: + return lookAhead(isTypeMemberStart); + case 5 /* ClassMembers */: + // We allow semicolons as class elements (as specified by ES6) as long as we're + // not in error recovery. If we're in error recovery, we don't want an errant + // semicolon to be treated as a class member (since they're almost always used + // for statements. + return lookAhead(isClassMemberStart) || (token() === 26 /* SemicolonToken */ && !inErrorRecovery); + case 6 /* EnumMembers */: + // Include open bracket computed properties. This technically also lets in indexers, + // which would be a candidate for improved error reporting. + return token() === 22 /* OpenBracketToken */ || isLiteralPropertyName(); + case 12 /* ObjectLiteralMembers */: + switch (token()) { + case 22 /* OpenBracketToken */: + case 40 /* AsteriskToken */: + case 25 /* DotDotDotToken */: + case 24 /* DotToken */: // Not an object literal member, but don't want to close the object (see `tests/cases/fourslash/completionsDotInObjectLiteral.ts`) + return true; + default: + return isLiteralPropertyName(); + } + case 18 /* RestProperties */: + return isLiteralPropertyName(); + case 9 /* ObjectBindingElements */: + return token() === 22 /* OpenBracketToken */ || token() === 25 /* DotDotDotToken */ || isLiteralPropertyName(); + case 7 /* HeritageClauseElement */: + // If we see `{ ... }` then only consume it as an expression if it is followed by `,` or `{` + // That way we won't consume the body of a class in its heritage clause. + if (token() === 18 /* OpenBraceToken */) { + return lookAhead(isValidHeritageClauseObjectLiteral); + } + if (!inErrorRecovery) { + return isStartOfLeftHandSideExpression() && !isHeritageClauseExtendsOrImplementsKeyword(); + } + else { + // If we're in error recovery we tighten up what we're willing to match. + // That way we don't treat something like "this" as a valid heritage clause + // element during recovery. + return isIdentifier() && !isHeritageClauseExtendsOrImplementsKeyword(); + } + case 8 /* VariableDeclarations */: + return isIdentifierOrPattern(); + case 10 /* ArrayBindingElements */: + return token() === 27 /* CommaToken */ || token() === 25 /* DotDotDotToken */ || isIdentifierOrPattern(); + case 19 /* TypeParameters */: + return isIdentifier(); + case 15 /* ArrayLiteralMembers */: + switch (token()) { + case 27 /* CommaToken */: + case 24 /* DotToken */: // Not an array literal member, but don't want to close the array (see `tests/cases/fourslash/completionsDotInArrayLiteralInObjectLiteral.ts`) + return true; + } + // falls through + case 11 /* ArgumentExpressions */: + return token() === 25 /* DotDotDotToken */ || isStartOfExpression(); + case 16 /* Parameters */: + return isStartOfParameter(/*isJSDocParameter*/ false); + case 17 /* JSDocParameters */: + return isStartOfParameter(/*isJSDocParameter*/ true); + case 20 /* TypeArguments */: + case 21 /* TupleElementTypes */: + return token() === 27 /* CommaToken */ || isStartOfType(); + case 22 /* HeritageClauses */: + return isHeritageClause(); + case 23 /* ImportOrExportSpecifiers */: + return ts.tokenIsIdentifierOrKeyword(token()); + case 13 /* JsxAttributes */: + return ts.tokenIsIdentifierOrKeyword(token()) || token() === 18 /* OpenBraceToken */; + case 14 /* JsxChildren */: + return true; + } + return ts.Debug.fail("Non-exhaustive case in 'isListElement'."); + } + function isValidHeritageClauseObjectLiteral() { + ts.Debug.assert(token() === 18 /* OpenBraceToken */); + if (nextToken() === 19 /* CloseBraceToken */) { + // if we see "extends {}" then only treat the {} as what we're extending (and not + // the class body) if we have: + // + // extends {} { + // extends {}, + // extends {} extends + // extends {} implements + var next = nextToken(); + return next === 27 /* CommaToken */ || next === 18 /* OpenBraceToken */ || next === 86 /* ExtendsKeyword */ || next === 109 /* ImplementsKeyword */; + } + return true; + } + function nextTokenIsIdentifier() { + nextToken(); + return isIdentifier(); + } + function nextTokenIsIdentifierOrKeyword() { + nextToken(); + return ts.tokenIsIdentifierOrKeyword(token()); + } + function nextTokenIsIdentifierOrKeywordOrGreaterThan() { + nextToken(); + return ts.tokenIsIdentifierOrKeywordOrGreaterThan(token()); + } + function isHeritageClauseExtendsOrImplementsKeyword() { + if (token() === 109 /* ImplementsKeyword */ || + token() === 86 /* ExtendsKeyword */) { + return lookAhead(nextTokenIsStartOfExpression); + } + return false; + } + function nextTokenIsStartOfExpression() { + nextToken(); + return isStartOfExpression(); + } + function nextTokenIsStartOfType() { + nextToken(); + return isStartOfType(); + } + // True if positioned at a list terminator + function isListTerminator(kind) { + if (token() === 1 /* EndOfFileToken */) { + // Being at the end of the file ends all lists. + return true; + } + switch (kind) { + case 1 /* BlockStatements */: + case 2 /* SwitchClauses */: + case 4 /* TypeMembers */: + case 5 /* ClassMembers */: + case 6 /* EnumMembers */: + case 12 /* ObjectLiteralMembers */: + case 9 /* ObjectBindingElements */: + case 23 /* ImportOrExportSpecifiers */: + return token() === 19 /* CloseBraceToken */; + case 3 /* SwitchClauseStatements */: + return token() === 19 /* CloseBraceToken */ || token() === 74 /* CaseKeyword */ || token() === 80 /* DefaultKeyword */; + case 7 /* HeritageClauseElement */: + return token() === 18 /* OpenBraceToken */ || token() === 86 /* ExtendsKeyword */ || token() === 109 /* ImplementsKeyword */; + case 8 /* VariableDeclarations */: + return isVariableDeclaratorListTerminator(); + case 19 /* TypeParameters */: + // Tokens other than '>' are here for better error recovery + return token() === 30 /* GreaterThanToken */ || token() === 20 /* OpenParenToken */ || token() === 18 /* OpenBraceToken */ || token() === 86 /* ExtendsKeyword */ || token() === 109 /* ImplementsKeyword */; + case 11 /* ArgumentExpressions */: + // Tokens other than ')' are here for better error recovery + return token() === 21 /* CloseParenToken */ || token() === 26 /* SemicolonToken */; + case 15 /* ArrayLiteralMembers */: + case 21 /* TupleElementTypes */: + case 10 /* ArrayBindingElements */: + return token() === 23 /* CloseBracketToken */; + case 17 /* JSDocParameters */: + case 16 /* Parameters */: + case 18 /* RestProperties */: + // Tokens other than ')' and ']' (the latter for index signatures) are here for better error recovery + return token() === 21 /* CloseParenToken */ || token() === 23 /* CloseBracketToken */ /*|| token === SyntaxKind.OpenBraceToken*/; + case 20 /* TypeArguments */: + // All other tokens should cause the type-argument to terminate except comma token + return token() !== 27 /* CommaToken */; + case 22 /* HeritageClauses */: + return token() === 18 /* OpenBraceToken */ || token() === 19 /* CloseBraceToken */; + case 13 /* JsxAttributes */: + return token() === 30 /* GreaterThanToken */ || token() === 42 /* SlashToken */; + case 14 /* JsxChildren */: + return token() === 28 /* LessThanToken */ && lookAhead(nextTokenIsSlash); + default: + return false; + } + } + function isVariableDeclaratorListTerminator() { + // If we can consume a semicolon (either explicitly, or with ASI), then consider us done + // with parsing the list of variable declarators. + if (canParseSemicolon()) { + return true; + } + // in the case where we're parsing the variable declarator of a 'for-in' statement, we + // are done if we see an 'in' keyword in front of us. Same with for-of + if (isInOrOfKeyword(token())) { + return true; + } + // ERROR RECOVERY TWEAK: + // For better error recovery, if we see an '=>' then we just stop immediately. We've got an + // arrow function here and it's going to be very unlikely that we'll resynchronize and get + // another variable declaration. + if (token() === 37 /* EqualsGreaterThanToken */) { + return true; + } + // Keep trying to parse out variable declarators. + return false; + } + // True if positioned at element or terminator of the current list or any enclosing list + function isInSomeParsingContext() { + for (var kind = 0; kind < 24 /* Count */; kind++) { + if (parsingContext & (1 << kind)) { + if (isListElement(kind, /*inErrorRecovery*/ true) || isListTerminator(kind)) { + return true; + } + } + } + return false; + } + // Parses a list of elements + function parseList(kind, parseElement) { + var saveParsingContext = parsingContext; + parsingContext |= 1 << kind; + var list = []; + var listPos = getNodePos(); + while (!isListTerminator(kind)) { + if (isListElement(kind, /*inErrorRecovery*/ false)) { + var element = parseListElement(kind, parseElement); + list.push(element); + continue; + } + if (abortParsingListOrMoveToNextToken(kind)) { + break; + } + } + parsingContext = saveParsingContext; + return createNodeArray(list, listPos); + } + function parseListElement(parsingContext, parseElement) { + var node = currentNode(parsingContext); + if (node) { + return consumeNode(node); + } + return parseElement(); + } + function currentNode(parsingContext) { + // If there is an outstanding parse error that we've encountered, but not attached to + // some node, then we cannot get a node from the old source tree. This is because we + // want to mark the next node we encounter as being unusable. + // + // Note: This may be too conservative. Perhaps we could reuse the node and set the bit + // on it (or its leftmost child) as having the error. For now though, being conservative + // is nice and likely won't ever affect perf. + if (parseErrorBeforeNextFinishedNode) { + return undefined; + } + if (!syntaxCursor) { + // if we don't have a cursor, we could never return a node from the old tree. + return undefined; + } + var node = syntaxCursor.currentNode(scanner.getStartPos()); + // Can't reuse a missing node. + if (ts.nodeIsMissing(node)) { + return undefined; + } + // Can't reuse a node that intersected the change range. + if (node.intersectsChange) { + return undefined; + } + // Can't reuse a node that contains a parse error. This is necessary so that we + // produce the same set of errors again. + if (ts.containsParseError(node)) { + return undefined; + } + // We can only reuse a node if it was parsed under the same strict mode that we're + // currently in. i.e. if we originally parsed a node in non-strict mode, but then + // the user added 'using strict' at the top of the file, then we can't use that node + // again as the presence of strict mode may cause us to parse the tokens in the file + // differently. + // + // Note: we *can* reuse tokens when the strict mode changes. That's because tokens + // are unaffected by strict mode. It's just the parser will decide what to do with it + // differently depending on what mode it is in. + // + // This also applies to all our other context flags as well. + var nodeContextFlags = node.flags & 12679168 /* ContextFlags */; + if (nodeContextFlags !== contextFlags) { + return undefined; + } + // Ok, we have a node that looks like it could be reused. Now verify that it is valid + // in the current list parsing context that we're currently at. + if (!canReuseNode(node, parsingContext)) { + return undefined; + } + if (node.jsDocCache) { + // jsDocCache may include tags from parent nodes, which might have been modified. + node.jsDocCache = undefined; + } + return node; + } + function consumeNode(node) { + // Move the scanner so it is after the node we just consumed. + scanner.setTextPos(node.end); + nextToken(); + return node; + } + function canReuseNode(node, parsingContext) { + switch (parsingContext) { + case 5 /* ClassMembers */: + return isReusableClassMember(node); + case 2 /* SwitchClauses */: + return isReusableSwitchClause(node); + case 0 /* SourceElements */: + case 1 /* BlockStatements */: + case 3 /* SwitchClauseStatements */: + return isReusableStatement(node); + case 6 /* EnumMembers */: + return isReusableEnumMember(node); + case 4 /* TypeMembers */: + return isReusableTypeMember(node); + case 8 /* VariableDeclarations */: + return isReusableVariableDeclaration(node); + case 17 /* JSDocParameters */: + case 16 /* Parameters */: + return isReusableParameter(node); + case 18 /* RestProperties */: + return false; + // Any other lists we do not care about reusing nodes in. But feel free to add if + // you can do so safely. Danger areas involve nodes that may involve speculative + // parsing. If speculative parsing is involved with the node, then the range the + // parser reached while looking ahead might be in the edited range (see the example + // in canReuseVariableDeclaratorNode for a good case of this). + case 22 /* HeritageClauses */: + // This would probably be safe to reuse. There is no speculative parsing with + // heritage clauses. + case 19 /* TypeParameters */: + // This would probably be safe to reuse. There is no speculative parsing with + // type parameters. Note that that's because type *parameters* only occur in + // unambiguous *type* contexts. While type *arguments* occur in very ambiguous + // *expression* contexts. + case 21 /* TupleElementTypes */: + // This would probably be safe to reuse. There is no speculative parsing with + // tuple types. + // Technically, type argument list types are probably safe to reuse. While + // speculative parsing is involved with them (since type argument lists are only + // produced from speculative parsing a < as a type argument list), we only have + // the types because speculative parsing succeeded. Thus, the lookahead never + // went past the end of the list and rewound. + case 20 /* TypeArguments */: + // Note: these are almost certainly not safe to ever reuse. Expressions commonly + // need a large amount of lookahead, and we should not reuse them as they may + // have actually intersected the edit. + case 11 /* ArgumentExpressions */: + // This is not safe to reuse for the same reason as the 'AssignmentExpression' + // cases. i.e. a property assignment may end with an expression, and thus might + // have lookahead far beyond it's old node. + case 12 /* ObjectLiteralMembers */: + // This is probably not safe to reuse. There can be speculative parsing with + // type names in a heritage clause. There can be generic names in the type + // name list, and there can be left hand side expressions (which can have type + // arguments.) + case 7 /* HeritageClauseElement */: + // Perhaps safe to reuse, but it's unlikely we'd see more than a dozen attributes + // on any given element. Same for children. + case 13 /* JsxAttributes */: + case 14 /* JsxChildren */: + } + return false; + } + function isReusableClassMember(node) { + if (node) { + switch (node.kind) { + case 157 /* Constructor */: + case 162 /* IndexSignature */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 154 /* PropertyDeclaration */: + case 217 /* SemicolonClassElement */: + return true; + case 156 /* MethodDeclaration */: + // Method declarations are not necessarily reusable. An object-literal + // may have a method calls "constructor(...)" and we must reparse that + // into an actual .ConstructorDeclaration. + var methodDeclaration = node; + var nameIsConstructor = methodDeclaration.name.kind === 72 /* Identifier */ && + methodDeclaration.name.originalKeywordKind === 124 /* ConstructorKeyword */; + return !nameIsConstructor; + } + } + return false; + } + function isReusableSwitchClause(node) { + if (node) { + switch (node.kind) { + case 271 /* CaseClause */: + case 272 /* DefaultClause */: + return true; + } + } + return false; + } + function isReusableStatement(node) { + if (node) { + switch (node.kind) { + case 239 /* FunctionDeclaration */: + case 219 /* VariableStatement */: + case 218 /* Block */: + case 222 /* IfStatement */: + case 221 /* ExpressionStatement */: + case 234 /* ThrowStatement */: + case 230 /* ReturnStatement */: + case 232 /* SwitchStatement */: + case 229 /* BreakStatement */: + case 228 /* ContinueStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + case 225 /* ForStatement */: + case 224 /* WhileStatement */: + case 231 /* WithStatement */: + case 220 /* EmptyStatement */: + case 235 /* TryStatement */: + case 233 /* LabeledStatement */: + case 223 /* DoStatement */: + case 236 /* DebuggerStatement */: + case 249 /* ImportDeclaration */: + case 248 /* ImportEqualsDeclaration */: + case 255 /* ExportDeclaration */: + case 254 /* ExportAssignment */: + case 244 /* ModuleDeclaration */: + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + case 243 /* EnumDeclaration */: + case 242 /* TypeAliasDeclaration */: + return true; + } + } + return false; + } + function isReusableEnumMember(node) { + return node.kind === 278 /* EnumMember */; + } + function isReusableTypeMember(node) { + if (node) { + switch (node.kind) { + case 161 /* ConstructSignature */: + case 155 /* MethodSignature */: + case 162 /* IndexSignature */: + case 153 /* PropertySignature */: + case 160 /* CallSignature */: + return true; + } + } + return false; + } + function isReusableVariableDeclaration(node) { + if (node.kind !== 237 /* VariableDeclaration */) { + return false; + } + // Very subtle incremental parsing bug. Consider the following code: + // + // let v = new List < A, B + // + // This is actually legal code. It's a list of variable declarators "v = new List() + // + // then we have a problem. "v = new List= 0) { + // Always preserve a trailing comma by marking it on the NodeArray + result.hasTrailingComma = true; + } + return result; + } + function createMissingList() { + var list = createNodeArray([], getNodePos()); + list.isMissingList = true; + return list; + } + function isMissingList(arr) { + return !!arr.isMissingList; + } + function parseBracketedList(kind, parseElement, open, close) { + if (parseExpected(open)) { + var result = parseDelimitedList(kind, parseElement); + parseExpected(close); + return result; + } + return createMissingList(); + } + function parseEntityName(allowReservedWords, diagnosticMessage) { + var entity = allowReservedWords ? parseIdentifierName(diagnosticMessage) : parseIdentifier(diagnosticMessage); + var dotPos = scanner.getStartPos(); + while (parseOptional(24 /* DotToken */)) { + if (token() === 28 /* LessThanToken */) { + // the entity is part of a JSDoc-style generic, so record the trailing dot for later error reporting + entity.jsdocDotPos = dotPos; + break; + } + dotPos = scanner.getStartPos(); + entity = createQualifiedName(entity, parseRightSideOfDot(allowReservedWords)); + } + return entity; + } + function createQualifiedName(entity, name) { + var node = createNode(148 /* QualifiedName */, entity.pos); + node.left = entity; + node.right = name; + return finishNode(node); + } + function parseRightSideOfDot(allowIdentifierNames) { + // Technically a keyword is valid here as all identifiers and keywords are identifier names. + // However, often we'll encounter this in error situations when the identifier or keyword + // is actually starting another valid construct. + // + // So, we check for the following specific case: + // + // name. + // identifierOrKeyword identifierNameOrKeyword + // + // Note: the newlines are important here. For example, if that above code + // were rewritten into: + // + // name.identifierOrKeyword + // identifierNameOrKeyword + // + // Then we would consider it valid. That's because ASI would take effect and + // the code would be implicitly: "name.identifierOrKeyword; identifierNameOrKeyword". + // In the first case though, ASI will not take effect because there is not a + // line terminator after the identifier or keyword. + if (scanner.hasPrecedingLineBreak() && ts.tokenIsIdentifierOrKeyword(token())) { + var matchesPattern = lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine); + if (matchesPattern) { + // Report that we need an identifier. However, report it right after the dot, + // and not on the next token. This is because the next token might actually + // be an identifier and the error would be quite confusing. + return createMissingNode(72 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Identifier_expected); + } + } + return allowIdentifierNames ? parseIdentifierName() : parseIdentifier(); + } + function parseTemplateExpression() { + var template = createNode(206 /* TemplateExpression */); + template.head = parseTemplateHead(); + ts.Debug.assert(template.head.kind === 15 /* TemplateHead */, "Template head has wrong token kind"); + var list = []; + var listPos = getNodePos(); + do { + list.push(parseTemplateSpan()); + } while (ts.last(list).literal.kind === 16 /* TemplateMiddle */); + template.templateSpans = createNodeArray(list, listPos); + return finishNode(template); + } + function parseTemplateSpan() { + var span = createNode(216 /* TemplateSpan */); + span.expression = allowInAnd(parseExpression); + var literal; + if (token() === 19 /* CloseBraceToken */) { + reScanTemplateToken(); + literal = parseTemplateMiddleOrTemplateTail(); + } + else { + literal = parseExpectedToken(17 /* TemplateTail */, ts.Diagnostics._0_expected, ts.tokenToString(19 /* CloseBraceToken */)); + } + span.literal = literal; + return finishNode(span); + } + function parseLiteralNode() { + return parseLiteralLikeNode(token()); + } + function parseTemplateHead() { + var fragment = parseLiteralLikeNode(token()); + ts.Debug.assert(fragment.kind === 15 /* TemplateHead */, "Template head has wrong token kind"); + return fragment; + } + function parseTemplateMiddleOrTemplateTail() { + var fragment = parseLiteralLikeNode(token()); + ts.Debug.assert(fragment.kind === 16 /* TemplateMiddle */ || fragment.kind === 17 /* TemplateTail */, "Template fragment has wrong token kind"); + return fragment; + } + function parseLiteralLikeNode(kind) { + var node = createNode(kind); + node.text = scanner.getTokenValue(); + if (scanner.hasExtendedUnicodeEscape()) { + node.hasExtendedUnicodeEscape = true; + } + if (scanner.isUnterminated()) { + node.isUnterminated = true; + } + // Octal literals are not allowed in strict mode or ES5 + // Note that theoretically the following condition would hold true literals like 009, + // which is not octal.But because of how the scanner separates the tokens, we would + // never get a token like this. Instead, we would get 00 and 9 as two separate tokens. + // We also do not need to check for negatives because any prefix operator would be part of a + // parent unary expression. + if (node.kind === 8 /* NumericLiteral */) { + node.numericLiteralFlags = scanner.getTokenFlags() & 1008 /* NumericLiteralFlags */; + } + nextToken(); + finishNode(node); + return node; + } + // TYPES + function parseTypeReference() { + var node = createNode(164 /* TypeReference */); + node.typeName = parseEntityName(/*allowReservedWords*/ true, ts.Diagnostics.Type_expected); + if (!scanner.hasPrecedingLineBreak() && token() === 28 /* LessThanToken */) { + node.typeArguments = parseBracketedList(20 /* TypeArguments */, parseType, 28 /* LessThanToken */, 30 /* GreaterThanToken */); + } + return finishNode(node); + } + // If true, we should abort parsing an error function. + function typeHasArrowFunctionBlockingParseError(node) { + switch (node.kind) { + case 164 /* TypeReference */: + return ts.nodeIsMissing(node.typeName); + case 165 /* FunctionType */: + case 166 /* ConstructorType */: { + var _a = node, parameters = _a.parameters, type = _a.type; + return isMissingList(parameters) || typeHasArrowFunctionBlockingParseError(type); + } + case 177 /* ParenthesizedType */: + return typeHasArrowFunctionBlockingParseError(node.type); + default: + return false; + } + } + function parseThisTypePredicate(lhs) { + nextToken(); + var node = createNode(163 /* TypePredicate */, lhs.pos); + node.parameterName = lhs; + node.type = parseType(); + return finishNode(node); + } + function parseThisTypeNode() { + var node = createNode(178 /* ThisType */); + nextToken(); + return finishNode(node); + } + function parseJSDocAllType(postFixEquals) { + var result = createNode(284 /* JSDocAllType */); + if (postFixEquals) { + return createPostfixType(288 /* JSDocOptionalType */, result); + } + else { + nextToken(); + } + return finishNode(result); + } + function parseJSDocNonNullableType() { + var result = createNode(287 /* JSDocNonNullableType */); + nextToken(); + result.type = parseNonArrayType(); + return finishNode(result); + } + function parseJSDocUnknownOrNullableType() { + var pos = scanner.getStartPos(); + // skip the ? + nextToken(); + // Need to lookahead to decide if this is a nullable or unknown type. + // Here are cases where we'll pick the unknown type: + // + // Foo(?, + // { a: ? } + // Foo(?) + // Foo + // Foo(?= + // (?| + if (token() === 27 /* CommaToken */ || + token() === 19 /* CloseBraceToken */ || + token() === 21 /* CloseParenToken */ || + token() === 30 /* GreaterThanToken */ || + token() === 59 /* EqualsToken */ || + token() === 50 /* BarToken */) { + var result = createNode(285 /* JSDocUnknownType */, pos); + return finishNode(result); + } + else { + var result = createNode(286 /* JSDocNullableType */, pos); + result.type = parseType(); + return finishNode(result); + } + } + function parseJSDocFunctionType() { + if (lookAhead(nextTokenIsOpenParen)) { + var result = createNodeWithJSDoc(289 /* JSDocFunctionType */); + nextToken(); + fillSignature(57 /* ColonToken */, 4 /* Type */ | 32 /* JSDoc */, result); + return finishNode(result); + } + var node = createNode(164 /* TypeReference */); + node.typeName = parseIdentifierName(); + return finishNode(node); + } + function parseJSDocParameter() { + var parameter = createNode(151 /* Parameter */); + if (token() === 100 /* ThisKeyword */ || token() === 95 /* NewKeyword */) { + parameter.name = parseIdentifierName(); + parseExpected(57 /* ColonToken */); + } + parameter.type = parseJSDocType(); + return finishNode(parameter); + } + function parseJSDocType() { + scanner.setInJSDocType(true); + var dotdotdot = parseOptionalToken(25 /* DotDotDotToken */); + var type = parseTypeOrTypePredicate(); + scanner.setInJSDocType(false); + if (dotdotdot) { + var variadic = createNode(290 /* JSDocVariadicType */, dotdotdot.pos); + variadic.type = type; + type = finishNode(variadic); + } + if (token() === 59 /* EqualsToken */) { + return createPostfixType(288 /* JSDocOptionalType */, type); + } + return type; + } + function parseTypeQuery() { + var node = createNode(167 /* TypeQuery */); + parseExpected(104 /* TypeOfKeyword */); + node.exprName = parseEntityName(/*allowReservedWords*/ true); + return finishNode(node); + } + function parseTypeParameter() { + var node = createNode(150 /* TypeParameter */); + node.name = parseIdentifier(); + if (parseOptional(86 /* ExtendsKeyword */)) { + // It's not uncommon for people to write improper constraints to a generic. If the + // user writes a constraint that is an expression and not an actual type, then parse + // it out as an expression (so we can recover well), but report that a type is needed + // instead. + if (isStartOfType() || !isStartOfExpression()) { + node.constraint = parseType(); + } + else { + // It was not a type, and it looked like an expression. Parse out an expression + // here so we recover well. Note: it is important that we call parseUnaryExpression + // and not parseExpression here. If the user has: + // + // + // + // We do *not* want to consume the `>` as we're consuming the expression for "". + node.expression = parseUnaryExpressionOrHigher(); + } + } + if (parseOptional(59 /* EqualsToken */)) { + node.default = parseType(); + } + return finishNode(node); + } + function parseTypeParameters() { + if (token() === 28 /* LessThanToken */) { + return parseBracketedList(19 /* TypeParameters */, parseTypeParameter, 28 /* LessThanToken */, 30 /* GreaterThanToken */); + } + } + function parseParameterType() { + if (parseOptional(57 /* ColonToken */)) { + return parseType(); + } + return undefined; + } + function isStartOfParameter(isJSDocParameter) { + return token() === 25 /* DotDotDotToken */ || + isIdentifierOrPattern() || + ts.isModifierKind(token()) || + token() === 58 /* AtToken */ || + isStartOfType(/*inStartOfParameter*/ !isJSDocParameter); + } + function parseParameter() { + var node = createNodeWithJSDoc(151 /* Parameter */); + if (token() === 100 /* ThisKeyword */) { + node.name = createIdentifier(/*isIdentifier*/ true); + node.type = parseParameterType(); + return finishNode(node); + } + node.decorators = parseDecorators(); + node.modifiers = parseModifiers(); + node.dotDotDotToken = parseOptionalToken(25 /* DotDotDotToken */); + // FormalParameter [Yield,Await]: + // BindingElement[?Yield,?Await] + node.name = parseIdentifierOrPattern(); + if (ts.getFullWidth(node.name) === 0 && !ts.hasModifiers(node) && ts.isModifierKind(token())) { + // in cases like + // 'use strict' + // function foo(static) + // isParameter('static') === true, because of isModifier('static') + // however 'static' is not a legal identifier in a strict mode. + // so result of this function will be ParameterDeclaration (flags = 0, name = missing, type = undefined, initializer = undefined) + // and current token will not change => parsing of the enclosing parameter list will last till the end of time (or OOM) + // to avoid this we'll advance cursor to the next token. + nextToken(); + } + node.questionToken = parseOptionalToken(56 /* QuestionToken */); + node.type = parseParameterType(); + node.initializer = parseInitializer(); + return finishNode(node); + } + /** + * Note: If returnToken is EqualsGreaterThanToken, `signature.type` will always be defined. + * @returns If return type parsing succeeds + */ + function fillSignature(returnToken, flags, signature) { + if (!(flags & 32 /* JSDoc */)) { + signature.typeParameters = parseTypeParameters(); + } + var parametersParsedSuccessfully = parseParameterList(signature, flags); + if (shouldParseReturnType(returnToken, !!(flags & 4 /* Type */))) { + signature.type = parseTypeOrTypePredicate(); + if (typeHasArrowFunctionBlockingParseError(signature.type)) + return false; + } + return parametersParsedSuccessfully; + } + function shouldParseReturnType(returnToken, isType) { + if (returnToken === 37 /* EqualsGreaterThanToken */) { + parseExpected(returnToken); + return true; + } + else if (parseOptional(57 /* ColonToken */)) { + return true; + } + else if (isType && token() === 37 /* EqualsGreaterThanToken */) { + // This is easy to get backward, especially in type contexts, so parse the type anyway + parseErrorAtCurrentToken(ts.Diagnostics._0_expected, ts.tokenToString(57 /* ColonToken */)); + nextToken(); + return true; + } + return false; + } + // Returns true on success. + function parseParameterList(signature, flags) { + // FormalParameters [Yield,Await]: (modified) + // [empty] + // FormalParameterList[?Yield,Await] + // + // FormalParameter[Yield,Await]: (modified) + // BindingElement[?Yield,Await] + // + // BindingElement [Yield,Await]: (modified) + // SingleNameBinding[?Yield,?Await] + // BindingPattern[?Yield,?Await]Initializer [In, ?Yield,?Await] opt + // + // SingleNameBinding [Yield,Await]: + // BindingIdentifier[?Yield,?Await]Initializer [In, ?Yield,?Await] opt + if (!parseExpected(20 /* OpenParenToken */)) { + signature.parameters = createMissingList(); + return false; + } + var savedYieldContext = inYieldContext(); + var savedAwaitContext = inAwaitContext(); + setYieldContext(!!(flags & 1 /* Yield */)); + setAwaitContext(!!(flags & 2 /* Await */)); + signature.parameters = flags & 32 /* JSDoc */ ? + parseDelimitedList(17 /* JSDocParameters */, parseJSDocParameter) : + parseDelimitedList(16 /* Parameters */, parseParameter); + setYieldContext(savedYieldContext); + setAwaitContext(savedAwaitContext); + return parseExpected(21 /* CloseParenToken */); + } + function parseTypeMemberSemicolon() { + // We allow type members to be separated by commas or (possibly ASI) semicolons. + // First check if it was a comma. If so, we're done with the member. + if (parseOptional(27 /* CommaToken */)) { + return; + } + // Didn't have a comma. We must have a (possible ASI) semicolon. + parseSemicolon(); + } + function parseSignatureMember(kind) { + var node = createNodeWithJSDoc(kind); + if (kind === 161 /* ConstructSignature */) { + parseExpected(95 /* NewKeyword */); + } + fillSignature(57 /* ColonToken */, 4 /* Type */, node); + parseTypeMemberSemicolon(); + return finishNode(node); + } + function isIndexSignature() { + return token() === 22 /* OpenBracketToken */ && lookAhead(isUnambiguouslyIndexSignature); + } + function isUnambiguouslyIndexSignature() { + // The only allowed sequence is: + // + // [id: + // + // However, for error recovery, we also check the following cases: + // + // [... + // [id, + // [id?, + // [id?: + // [id?] + // [public id + // [private id + // [protected id + // [] + // + nextToken(); + if (token() === 25 /* DotDotDotToken */ || token() === 23 /* CloseBracketToken */) { + return true; + } + if (ts.isModifierKind(token())) { + nextToken(); + if (isIdentifier()) { + return true; + } + } + else if (!isIdentifier()) { + return false; + } + else { + // Skip the identifier + nextToken(); + } + // A colon signifies a well formed indexer + // A comma should be a badly formed indexer because comma expressions are not allowed + // in computed properties. + if (token() === 57 /* ColonToken */ || token() === 27 /* CommaToken */) { + return true; + } + // Question mark could be an indexer with an optional property, + // or it could be a conditional expression in a computed property. + if (token() !== 56 /* QuestionToken */) { + return false; + } + // If any of the following tokens are after the question mark, it cannot + // be a conditional expression, so treat it as an indexer. + nextToken(); + return token() === 57 /* ColonToken */ || token() === 27 /* CommaToken */ || token() === 23 /* CloseBracketToken */; + } + function parseIndexSignatureDeclaration(node) { + node.kind = 162 /* IndexSignature */; + node.parameters = parseBracketedList(16 /* Parameters */, parseParameter, 22 /* OpenBracketToken */, 23 /* CloseBracketToken */); + node.type = parseTypeAnnotation(); + parseTypeMemberSemicolon(); + return finishNode(node); + } + function parsePropertyOrMethodSignature(node) { + node.name = parsePropertyName(); + node.questionToken = parseOptionalToken(56 /* QuestionToken */); + if (token() === 20 /* OpenParenToken */ || token() === 28 /* LessThanToken */) { + node.kind = 155 /* MethodSignature */; + // Method signatures don't exist in expression contexts. So they have neither + // [Yield] nor [Await] + fillSignature(57 /* ColonToken */, 4 /* Type */, node); + } + else { + node.kind = 153 /* PropertySignature */; + node.type = parseTypeAnnotation(); + if (token() === 59 /* EqualsToken */) { + // Although type literal properties cannot not have initializers, we attempt + // to parse an initializer so we can report in the checker that an interface + // property or type literal property cannot have an initializer. + node.initializer = parseInitializer(); + } + } + parseTypeMemberSemicolon(); + return finishNode(node); + } + function isTypeMemberStart() { + // Return true if we have the start of a signature member + if (token() === 20 /* OpenParenToken */ || token() === 28 /* LessThanToken */) { + return true; + } + var idToken = false; + // Eat up all modifiers, but hold on to the last one in case it is actually an identifier + while (ts.isModifierKind(token())) { + idToken = true; + nextToken(); + } + // Index signatures and computed property names are type members + if (token() === 22 /* OpenBracketToken */) { + return true; + } + // Try to get the first property-like token following all modifiers + if (isLiteralPropertyName()) { + idToken = true; + nextToken(); + } + // If we were able to get any potential identifier, check that it is + // the start of a member declaration + if (idToken) { + return token() === 20 /* OpenParenToken */ || + token() === 28 /* LessThanToken */ || + token() === 56 /* QuestionToken */ || + token() === 57 /* ColonToken */ || + token() === 27 /* CommaToken */ || + canParseSemicolon(); + } + return false; + } + function parseTypeMember() { + if (token() === 20 /* OpenParenToken */ || token() === 28 /* LessThanToken */) { + return parseSignatureMember(160 /* CallSignature */); + } + if (token() === 95 /* NewKeyword */ && lookAhead(nextTokenIsOpenParenOrLessThan)) { + return parseSignatureMember(161 /* ConstructSignature */); + } + var node = createNodeWithJSDoc(0 /* Unknown */); + node.modifiers = parseModifiers(); + if (isIndexSignature()) { + return parseIndexSignatureDeclaration(node); + } + return parsePropertyOrMethodSignature(node); + } + function nextTokenIsOpenParenOrLessThan() { + nextToken(); + return token() === 20 /* OpenParenToken */ || token() === 28 /* LessThanToken */; + } + function nextTokenIsDot() { + return nextToken() === 24 /* DotToken */; + } + function nextTokenIsOpenParenOrLessThanOrDot() { + switch (nextToken()) { + case 20 /* OpenParenToken */: + case 28 /* LessThanToken */: + case 24 /* DotToken */: + return true; + } + return false; + } + function parseTypeLiteral() { + var node = createNode(168 /* TypeLiteral */); + node.members = parseObjectTypeMembers(); + return finishNode(node); + } + function parseObjectTypeMembers() { + var members; + if (parseExpected(18 /* OpenBraceToken */)) { + members = parseList(4 /* TypeMembers */, parseTypeMember); + parseExpected(19 /* CloseBraceToken */); + } + else { + members = createMissingList(); + } + return members; + } + function isStartOfMappedType() { + nextToken(); + if (token() === 38 /* PlusToken */ || token() === 39 /* MinusToken */) { + return nextToken() === 133 /* ReadonlyKeyword */; + } + if (token() === 133 /* ReadonlyKeyword */) { + nextToken(); + } + return token() === 22 /* OpenBracketToken */ && nextTokenIsIdentifier() && nextToken() === 93 /* InKeyword */; + } + function parseMappedTypeParameter() { + var node = createNode(150 /* TypeParameter */); + node.name = parseIdentifier(); + parseExpected(93 /* InKeyword */); + node.constraint = parseType(); + return finishNode(node); + } + function parseMappedType() { + var node = createNode(181 /* MappedType */); + parseExpected(18 /* OpenBraceToken */); + if (token() === 133 /* ReadonlyKeyword */ || token() === 38 /* PlusToken */ || token() === 39 /* MinusToken */) { + node.readonlyToken = parseTokenNode(); + if (node.readonlyToken.kind !== 133 /* ReadonlyKeyword */) { + parseExpectedToken(133 /* ReadonlyKeyword */); + } + } + parseExpected(22 /* OpenBracketToken */); + node.typeParameter = parseMappedTypeParameter(); + parseExpected(23 /* CloseBracketToken */); + if (token() === 56 /* QuestionToken */ || token() === 38 /* PlusToken */ || token() === 39 /* MinusToken */) { + node.questionToken = parseTokenNode(); + if (node.questionToken.kind !== 56 /* QuestionToken */) { + parseExpectedToken(56 /* QuestionToken */); + } + } + node.type = parseTypeAnnotation(); + parseSemicolon(); + parseExpected(19 /* CloseBraceToken */); + return finishNode(node); + } + function parseTupleElementType() { + var pos = getNodePos(); + if (parseOptional(25 /* DotDotDotToken */)) { + var node = createNode(172 /* RestType */, pos); + node.type = parseType(); + return finishNode(node); + } + var type = parseType(); + if (!(contextFlags & 2097152 /* JSDoc */) && type.kind === 286 /* JSDocNullableType */ && type.pos === type.type.pos) { + type.kind = 171 /* OptionalType */; + } + return type; + } + function parseTupleType() { + var node = createNode(170 /* TupleType */); + node.elementTypes = parseBracketedList(21 /* TupleElementTypes */, parseTupleElementType, 22 /* OpenBracketToken */, 23 /* CloseBracketToken */); + return finishNode(node); + } + function parseParenthesizedType() { + var node = createNode(177 /* ParenthesizedType */); + parseExpected(20 /* OpenParenToken */); + node.type = parseType(); + parseExpected(21 /* CloseParenToken */); + return finishNode(node); + } + function parseFunctionOrConstructorType() { + var pos = getNodePos(); + var kind = parseOptional(95 /* NewKeyword */) ? 166 /* ConstructorType */ : 165 /* FunctionType */; + var node = createNodeWithJSDoc(kind, pos); + fillSignature(37 /* EqualsGreaterThanToken */, 4 /* Type */, node); + return finishNode(node); + } + function parseKeywordAndNoDot() { + var node = parseTokenNode(); + return token() === 24 /* DotToken */ ? undefined : node; + } + function parseLiteralTypeNode(negative) { + var node = createNode(182 /* LiteralType */); + var unaryMinusExpression; + if (negative) { + unaryMinusExpression = createNode(202 /* PrefixUnaryExpression */); + unaryMinusExpression.operator = 39 /* MinusToken */; + nextToken(); + } + var expression = token() === 102 /* TrueKeyword */ || token() === 87 /* FalseKeyword */ + ? parseTokenNode() + : parseLiteralLikeNode(token()); + if (negative) { + unaryMinusExpression.operand = expression; + finishNode(unaryMinusExpression); + expression = unaryMinusExpression; + } + node.literal = expression; + return finishNode(node); + } + function isStartOfTypeOfImportType() { + nextToken(); + return token() === 92 /* ImportKeyword */; + } + function parseImportType() { + sourceFile.flags |= 524288 /* PossiblyContainsDynamicImport */; + var node = createNode(183 /* ImportType */); + if (parseOptional(104 /* TypeOfKeyword */)) { + node.isTypeOf = true; + } + parseExpected(92 /* ImportKeyword */); + parseExpected(20 /* OpenParenToken */); + node.argument = parseType(); + parseExpected(21 /* CloseParenToken */); + if (parseOptional(24 /* DotToken */)) { + node.qualifier = parseEntityName(/*allowReservedWords*/ true, ts.Diagnostics.Type_expected); + } + node.typeArguments = tryParseTypeArguments(); + return finishNode(node); + } + function nextTokenIsNumericOrBigIntLiteral() { + nextToken(); + return token() === 8 /* NumericLiteral */ || token() === 9 /* BigIntLiteral */; + } + function parseNonArrayType() { + switch (token()) { + case 120 /* AnyKeyword */: + case 143 /* UnknownKeyword */: + case 138 /* StringKeyword */: + case 135 /* NumberKeyword */: + case 146 /* BigIntKeyword */: + case 139 /* SymbolKeyword */: + case 123 /* BooleanKeyword */: + case 141 /* UndefinedKeyword */: + case 132 /* NeverKeyword */: + case 136 /* ObjectKeyword */: + // If these are followed by a dot, then parse these out as a dotted type reference instead. + return tryParse(parseKeywordAndNoDot) || parseTypeReference(); + case 40 /* AsteriskToken */: + return parseJSDocAllType(/*postfixEquals*/ false); + case 62 /* AsteriskEqualsToken */: + return parseJSDocAllType(/*postfixEquals*/ true); + case 56 /* QuestionToken */: + return parseJSDocUnknownOrNullableType(); + case 90 /* FunctionKeyword */: + return parseJSDocFunctionType(); + case 52 /* ExclamationToken */: + return parseJSDocNonNullableType(); + case 14 /* NoSubstitutionTemplateLiteral */: + case 10 /* StringLiteral */: + case 8 /* NumericLiteral */: + case 9 /* BigIntLiteral */: + case 102 /* TrueKeyword */: + case 87 /* FalseKeyword */: + return parseLiteralTypeNode(); + case 39 /* MinusToken */: + return lookAhead(nextTokenIsNumericOrBigIntLiteral) ? parseLiteralTypeNode(/*negative*/ true) : parseTypeReference(); + case 106 /* VoidKeyword */: + case 96 /* NullKeyword */: + return parseTokenNode(); + case 100 /* ThisKeyword */: { + var thisKeyword = parseThisTypeNode(); + if (token() === 128 /* IsKeyword */ && !scanner.hasPrecedingLineBreak()) { + return parseThisTypePredicate(thisKeyword); + } + else { + return thisKeyword; + } + } + case 104 /* TypeOfKeyword */: + return lookAhead(isStartOfTypeOfImportType) ? parseImportType() : parseTypeQuery(); + case 18 /* OpenBraceToken */: + return lookAhead(isStartOfMappedType) ? parseMappedType() : parseTypeLiteral(); + case 22 /* OpenBracketToken */: + return parseTupleType(); + case 20 /* OpenParenToken */: + return parseParenthesizedType(); + case 92 /* ImportKeyword */: + return parseImportType(); + default: + return parseTypeReference(); + } + } + function isStartOfType(inStartOfParameter) { + switch (token()) { + case 120 /* AnyKeyword */: + case 143 /* UnknownKeyword */: + case 138 /* StringKeyword */: + case 135 /* NumberKeyword */: + case 146 /* BigIntKeyword */: + case 123 /* BooleanKeyword */: + case 139 /* SymbolKeyword */: + case 142 /* UniqueKeyword */: + case 106 /* VoidKeyword */: + case 141 /* UndefinedKeyword */: + case 96 /* NullKeyword */: + case 100 /* ThisKeyword */: + case 104 /* TypeOfKeyword */: + case 132 /* NeverKeyword */: + case 18 /* OpenBraceToken */: + case 22 /* OpenBracketToken */: + case 28 /* LessThanToken */: + case 50 /* BarToken */: + case 49 /* AmpersandToken */: + case 95 /* NewKeyword */: + case 10 /* StringLiteral */: + case 8 /* NumericLiteral */: + case 9 /* BigIntLiteral */: + case 102 /* TrueKeyword */: + case 87 /* FalseKeyword */: + case 136 /* ObjectKeyword */: + case 40 /* AsteriskToken */: + case 56 /* QuestionToken */: + case 52 /* ExclamationToken */: + case 25 /* DotDotDotToken */: + case 127 /* InferKeyword */: + case 92 /* ImportKeyword */: + return true; + case 90 /* FunctionKeyword */: + return !inStartOfParameter; + case 39 /* MinusToken */: + return !inStartOfParameter && lookAhead(nextTokenIsNumericOrBigIntLiteral); + case 20 /* OpenParenToken */: + // Only consider '(' the start of a type if followed by ')', '...', an identifier, a modifier, + // or something that starts a type. We don't want to consider things like '(1)' a type. + return !inStartOfParameter && lookAhead(isStartOfParenthesizedOrFunctionType); + default: + return isIdentifier(); + } + } + function isStartOfParenthesizedOrFunctionType() { + nextToken(); + return token() === 21 /* CloseParenToken */ || isStartOfParameter(/*isJSDocParameter*/ false) || isStartOfType(); + } + function parsePostfixTypeOrHigher() { + var type = parseNonArrayType(); + while (!scanner.hasPrecedingLineBreak()) { + switch (token()) { + case 52 /* ExclamationToken */: + type = createPostfixType(287 /* JSDocNonNullableType */, type); + break; + case 56 /* QuestionToken */: + // If not in JSDoc and next token is start of a type we have a conditional type + if (!(contextFlags & 2097152 /* JSDoc */) && lookAhead(nextTokenIsStartOfType)) { + return type; + } + type = createPostfixType(286 /* JSDocNullableType */, type); + break; + case 22 /* OpenBracketToken */: + parseExpected(22 /* OpenBracketToken */); + if (isStartOfType()) { + var node = createNode(180 /* IndexedAccessType */, type.pos); + node.objectType = type; + node.indexType = parseType(); + parseExpected(23 /* CloseBracketToken */); + type = finishNode(node); + } + else { + var node = createNode(169 /* ArrayType */, type.pos); + node.elementType = type; + parseExpected(23 /* CloseBracketToken */); + type = finishNode(node); + } + break; + default: + return type; + } + } + return type; + } + function createPostfixType(kind, type) { + nextToken(); + var postfix = createNode(kind, type.pos); + postfix.type = type; + return finishNode(postfix); + } + function parseTypeOperator(operator) { + var node = createNode(179 /* TypeOperator */); + parseExpected(operator); + node.operator = operator; + node.type = parseTypeOperatorOrHigher(); + return finishNode(node); + } + function parseInferType() { + var node = createNode(176 /* InferType */); + parseExpected(127 /* InferKeyword */); + var typeParameter = createNode(150 /* TypeParameter */); + typeParameter.name = parseIdentifier(); + node.typeParameter = finishNode(typeParameter); + return finishNode(node); + } + function parseTypeOperatorOrHigher() { + var operator = token(); + switch (operator) { + case 129 /* KeyOfKeyword */: + case 142 /* UniqueKeyword */: + return parseTypeOperator(operator); + case 127 /* InferKeyword */: + return parseInferType(); + } + return parsePostfixTypeOrHigher(); + } + function parseUnionOrIntersectionType(kind, parseConstituentType, operator) { + parseOptional(operator); + var type = parseConstituentType(); + if (token() === operator) { + var types = [type]; + while (parseOptional(operator)) { + types.push(parseConstituentType()); + } + var node = createNode(kind, type.pos); + node.types = createNodeArray(types, type.pos); + type = finishNode(node); + } + return type; + } + function parseIntersectionTypeOrHigher() { + return parseUnionOrIntersectionType(174 /* IntersectionType */, parseTypeOperatorOrHigher, 49 /* AmpersandToken */); + } + function parseUnionTypeOrHigher() { + return parseUnionOrIntersectionType(173 /* UnionType */, parseIntersectionTypeOrHigher, 50 /* BarToken */); + } + function isStartOfFunctionType() { + if (token() === 28 /* LessThanToken */) { + return true; + } + return token() === 20 /* OpenParenToken */ && lookAhead(isUnambiguouslyStartOfFunctionType); + } + function skipParameterStart() { + if (ts.isModifierKind(token())) { + // Skip modifiers + parseModifiers(); + } + if (isIdentifier() || token() === 100 /* ThisKeyword */) { + nextToken(); + return true; + } + if (token() === 22 /* OpenBracketToken */ || token() === 18 /* OpenBraceToken */) { + // Return true if we can parse an array or object binding pattern with no errors + var previousErrorCount = parseDiagnostics.length; + parseIdentifierOrPattern(); + return previousErrorCount === parseDiagnostics.length; + } + return false; + } + function isUnambiguouslyStartOfFunctionType() { + nextToken(); + if (token() === 21 /* CloseParenToken */ || token() === 25 /* DotDotDotToken */) { + // ( ) + // ( ... + return true; + } + if (skipParameterStart()) { + // We successfully skipped modifiers (if any) and an identifier or binding pattern, + // now see if we have something that indicates a parameter declaration + if (token() === 57 /* ColonToken */ || token() === 27 /* CommaToken */ || + token() === 56 /* QuestionToken */ || token() === 59 /* EqualsToken */) { + // ( xxx : + // ( xxx , + // ( xxx ? + // ( xxx = + return true; + } + if (token() === 21 /* CloseParenToken */) { + nextToken(); + if (token() === 37 /* EqualsGreaterThanToken */) { + // ( xxx ) => + return true; + } + } + } + return false; + } + function parseTypeOrTypePredicate() { + var typePredicateVariable = isIdentifier() && tryParse(parseTypePredicatePrefix); + var type = parseType(); + if (typePredicateVariable) { + var node = createNode(163 /* TypePredicate */, typePredicateVariable.pos); + node.parameterName = typePredicateVariable; + node.type = type; + return finishNode(node); + } + else { + return type; + } + } + function parseTypePredicatePrefix() { + var id = parseIdentifier(); + if (token() === 128 /* IsKeyword */ && !scanner.hasPrecedingLineBreak()) { + nextToken(); + return id; + } + } + function parseType() { + // The rules about 'yield' only apply to actual code/expression contexts. They don't + // apply to 'type' contexts. So we disable these parameters here before moving on. + return doOutsideOfContext(20480 /* TypeExcludesFlags */, parseTypeWorker); + } + function parseTypeWorker(noConditionalTypes) { + if (isStartOfFunctionType() || token() === 95 /* NewKeyword */) { + return parseFunctionOrConstructorType(); + } + var type = parseUnionTypeOrHigher(); + if (!noConditionalTypes && !scanner.hasPrecedingLineBreak() && parseOptional(86 /* ExtendsKeyword */)) { + var node = createNode(175 /* ConditionalType */, type.pos); + node.checkType = type; + // The type following 'extends' is not permitted to be another conditional type + node.extendsType = parseTypeWorker(/*noConditionalTypes*/ true); + parseExpected(56 /* QuestionToken */); + node.trueType = parseTypeWorker(); + parseExpected(57 /* ColonToken */); + node.falseType = parseTypeWorker(); + return finishNode(node); + } + return type; + } + function parseTypeAnnotation() { + return parseOptional(57 /* ColonToken */) ? parseType() : undefined; + } + // EXPRESSIONS + function isStartOfLeftHandSideExpression() { + switch (token()) { + case 100 /* ThisKeyword */: + case 98 /* SuperKeyword */: + case 96 /* NullKeyword */: + case 102 /* TrueKeyword */: + case 87 /* FalseKeyword */: + case 8 /* NumericLiteral */: + case 9 /* BigIntLiteral */: + case 10 /* StringLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: + case 15 /* TemplateHead */: + case 20 /* OpenParenToken */: + case 22 /* OpenBracketToken */: + case 18 /* OpenBraceToken */: + case 90 /* FunctionKeyword */: + case 76 /* ClassKeyword */: + case 95 /* NewKeyword */: + case 42 /* SlashToken */: + case 64 /* SlashEqualsToken */: + case 72 /* Identifier */: + return true; + case 92 /* ImportKeyword */: + return lookAhead(nextTokenIsOpenParenOrLessThanOrDot); + default: + return isIdentifier(); + } + } + function isStartOfExpression() { + if (isStartOfLeftHandSideExpression()) { + return true; + } + switch (token()) { + case 38 /* PlusToken */: + case 39 /* MinusToken */: + case 53 /* TildeToken */: + case 52 /* ExclamationToken */: + case 81 /* DeleteKeyword */: + case 104 /* TypeOfKeyword */: + case 106 /* VoidKeyword */: + case 44 /* PlusPlusToken */: + case 45 /* MinusMinusToken */: + case 28 /* LessThanToken */: + case 122 /* AwaitKeyword */: + case 117 /* YieldKeyword */: + // Yield/await always starts an expression. Either it is an identifier (in which case + // it is definitely an expression). Or it's a keyword (either because we're in + // a generator or async function, or in strict mode (or both)) and it started a yield or await expression. + return true; + default: + // Error tolerance. If we see the start of some binary operator, we consider + // that the start of an expression. That way we'll parse out a missing identifier, + // give a good message about an identifier being missing, and then consume the + // rest of the binary expression. + if (isBinaryOperator()) { + return true; + } + return isIdentifier(); + } + } + function isStartOfExpressionStatement() { + // As per the grammar, none of '{' or 'function' or 'class' can start an expression statement. + return token() !== 18 /* OpenBraceToken */ && + token() !== 90 /* FunctionKeyword */ && + token() !== 76 /* ClassKeyword */ && + token() !== 58 /* AtToken */ && + isStartOfExpression(); + } + function parseExpression() { + // Expression[in]: + // AssignmentExpression[in] + // Expression[in] , AssignmentExpression[in] + // clear the decorator context when parsing Expression, as it should be unambiguous when parsing a decorator + var saveDecoratorContext = inDecoratorContext(); + if (saveDecoratorContext) { + setDecoratorContext(/*val*/ false); + } + var expr = parseAssignmentExpressionOrHigher(); + var operatorToken; + while ((operatorToken = parseOptionalToken(27 /* CommaToken */))) { + expr = makeBinaryExpression(expr, operatorToken, parseAssignmentExpressionOrHigher()); + } + if (saveDecoratorContext) { + setDecoratorContext(/*val*/ true); + } + return expr; + } + function parseInitializer() { + return parseOptional(59 /* EqualsToken */) ? parseAssignmentExpressionOrHigher() : undefined; + } + function parseAssignmentExpressionOrHigher() { + // AssignmentExpression[in,yield]: + // 1) ConditionalExpression[?in,?yield] + // 2) LeftHandSideExpression = AssignmentExpression[?in,?yield] + // 3) LeftHandSideExpression AssignmentOperator AssignmentExpression[?in,?yield] + // 4) ArrowFunctionExpression[?in,?yield] + // 5) AsyncArrowFunctionExpression[in,yield,await] + // 6) [+Yield] YieldExpression[?In] + // + // Note: for ease of implementation we treat productions '2' and '3' as the same thing. + // (i.e. they're both BinaryExpressions with an assignment operator in it). + // First, do the simple check if we have a YieldExpression (production '6'). + if (isYieldExpression()) { + return parseYieldExpression(); + } + // Then, check if we have an arrow function (production '4' and '5') that starts with a parenthesized + // parameter list or is an async arrow function. + // AsyncArrowFunctionExpression: + // 1) async[no LineTerminator here]AsyncArrowBindingIdentifier[?Yield][no LineTerminator here]=>AsyncConciseBody[?In] + // 2) CoverCallExpressionAndAsyncArrowHead[?Yield, ?Await][no LineTerminator here]=>AsyncConciseBody[?In] + // Production (1) of AsyncArrowFunctionExpression is parsed in "tryParseAsyncSimpleArrowFunctionExpression". + // And production (2) is parsed in "tryParseParenthesizedArrowFunctionExpression". + // + // If we do successfully parse arrow-function, we must *not* recurse for productions 1, 2 or 3. An ArrowFunction is + // not a LeftHandSideExpression, nor does it start a ConditionalExpression. So we are done + // with AssignmentExpression if we see one. + var arrowExpression = tryParseParenthesizedArrowFunctionExpression() || tryParseAsyncSimpleArrowFunctionExpression(); + if (arrowExpression) { + return arrowExpression; + } + // Now try to see if we're in production '1', '2' or '3'. A conditional expression can + // start with a LogicalOrExpression, while the assignment productions can only start with + // LeftHandSideExpressions. + // + // So, first, we try to just parse out a BinaryExpression. If we get something that is a + // LeftHandSide or higher, then we can try to parse out the assignment expression part. + // Otherwise, we try to parse out the conditional expression bit. We want to allow any + // binary expression here, so we pass in the 'lowest' precedence here so that it matches + // and consumes anything. + var expr = parseBinaryExpressionOrHigher(/*precedence*/ 0); + // To avoid a look-ahead, we did not handle the case of an arrow function with a single un-parenthesized + // parameter ('x => ...') above. We handle it here by checking if the parsed expression was a single + // identifier and the current token is an arrow. + if (expr.kind === 72 /* Identifier */ && token() === 37 /* EqualsGreaterThanToken */) { + return parseSimpleArrowFunctionExpression(expr); + } + // Now see if we might be in cases '2' or '3'. + // If the expression was a LHS expression, and we have an assignment operator, then + // we're in '2' or '3'. Consume the assignment and return. + // + // Note: we call reScanGreaterToken so that we get an appropriately merged token + // for cases like `> > =` becoming `>>=` + if (ts.isLeftHandSideExpression(expr) && ts.isAssignmentOperator(reScanGreaterToken())) { + return makeBinaryExpression(expr, parseTokenNode(), parseAssignmentExpressionOrHigher()); + } + // It wasn't an assignment or a lambda. This is a conditional expression: + return parseConditionalExpressionRest(expr); + } + function isYieldExpression() { + if (token() === 117 /* YieldKeyword */) { + // If we have a 'yield' keyword, and this is a context where yield expressions are + // allowed, then definitely parse out a yield expression. + if (inYieldContext()) { + return true; + } + // We're in a context where 'yield expr' is not allowed. However, if we can + // definitely tell that the user was trying to parse a 'yield expr' and not + // just a normal expr that start with a 'yield' identifier, then parse out + // a 'yield expr'. We can then report an error later that they are only + // allowed in generator expressions. + // + // for example, if we see 'yield(foo)', then we'll have to treat that as an + // invocation expression of something called 'yield'. However, if we have + // 'yield foo' then that is not legal as a normal expression, so we can + // definitely recognize this as a yield expression. + // + // for now we just check if the next token is an identifier. More heuristics + // can be added here later as necessary. We just need to make sure that we + // don't accidentally consume something legal. + return lookAhead(nextTokenIsIdentifierOrKeywordOrLiteralOnSameLine); + } + return false; + } + function nextTokenIsIdentifierOnSameLine() { + nextToken(); + return !scanner.hasPrecedingLineBreak() && isIdentifier(); + } + function parseYieldExpression() { + var node = createNode(207 /* YieldExpression */); + // YieldExpression[In] : + // yield + // yield [no LineTerminator here] [Lexical goal InputElementRegExp]AssignmentExpression[?In, Yield] + // yield [no LineTerminator here] * [Lexical goal InputElementRegExp]AssignmentExpression[?In, Yield] + nextToken(); + if (!scanner.hasPrecedingLineBreak() && + (token() === 40 /* AsteriskToken */ || isStartOfExpression())) { + node.asteriskToken = parseOptionalToken(40 /* AsteriskToken */); + node.expression = parseAssignmentExpressionOrHigher(); + return finishNode(node); + } + else { + // if the next token is not on the same line as yield. or we don't have an '*' or + // the start of an expression, then this is just a simple "yield" expression. + return finishNode(node); + } + } + function parseSimpleArrowFunctionExpression(identifier, asyncModifier) { + ts.Debug.assert(token() === 37 /* EqualsGreaterThanToken */, "parseSimpleArrowFunctionExpression should only have been called if we had a =>"); + var node; + if (asyncModifier) { + node = createNode(197 /* ArrowFunction */, asyncModifier.pos); + node.modifiers = asyncModifier; + } + else { + node = createNode(197 /* ArrowFunction */, identifier.pos); + } + var parameter = createNode(151 /* Parameter */, identifier.pos); + parameter.name = identifier; + finishNode(parameter); + node.parameters = createNodeArray([parameter], parameter.pos, parameter.end); + node.equalsGreaterThanToken = parseExpectedToken(37 /* EqualsGreaterThanToken */); + node.body = parseArrowFunctionExpressionBody(/*isAsync*/ !!asyncModifier); + return addJSDocComment(finishNode(node)); + } + function tryParseParenthesizedArrowFunctionExpression() { + var triState = isParenthesizedArrowFunctionExpression(); + if (triState === 0 /* False */) { + // It's definitely not a parenthesized arrow function expression. + return undefined; + } + // If we definitely have an arrow function, then we can just parse one, not requiring a + // following => or { token. Otherwise, we *might* have an arrow function. Try to parse + // it out, but don't allow any ambiguity, and return 'undefined' if this could be an + // expression instead. + var arrowFunction = triState === 1 /* True */ + ? parseParenthesizedArrowFunctionExpressionHead(/*allowAmbiguity*/ true) + : tryParse(parsePossibleParenthesizedArrowFunctionExpressionHead); + if (!arrowFunction) { + // Didn't appear to actually be a parenthesized arrow function. Just bail out. + return undefined; + } + var isAsync = ts.hasModifier(arrowFunction, 256 /* Async */); + // If we have an arrow, then try to parse the body. Even if not, try to parse if we + // have an opening brace, just in case we're in an error state. + var lastToken = token(); + arrowFunction.equalsGreaterThanToken = parseExpectedToken(37 /* EqualsGreaterThanToken */); + arrowFunction.body = (lastToken === 37 /* EqualsGreaterThanToken */ || lastToken === 18 /* OpenBraceToken */) + ? parseArrowFunctionExpressionBody(isAsync) + : parseIdentifier(); + return finishNode(arrowFunction); + } + // True -> We definitely expect a parenthesized arrow function here. + // False -> There *cannot* be a parenthesized arrow function here. + // Unknown -> There *might* be a parenthesized arrow function here. + // Speculatively look ahead to be sure, and rollback if not. + function isParenthesizedArrowFunctionExpression() { + if (token() === 20 /* OpenParenToken */ || token() === 28 /* LessThanToken */ || token() === 121 /* AsyncKeyword */) { + return lookAhead(isParenthesizedArrowFunctionExpressionWorker); + } + if (token() === 37 /* EqualsGreaterThanToken */) { + // ERROR RECOVERY TWEAK: + // If we see a standalone => try to parse it as an arrow function expression as that's + // likely what the user intended to write. + return 1 /* True */; + } + // Definitely not a parenthesized arrow function. + return 0 /* False */; + } + function isParenthesizedArrowFunctionExpressionWorker() { + if (token() === 121 /* AsyncKeyword */) { + nextToken(); + if (scanner.hasPrecedingLineBreak()) { + return 0 /* False */; + } + if (token() !== 20 /* OpenParenToken */ && token() !== 28 /* LessThanToken */) { + return 0 /* False */; + } + } + var first = token(); + var second = nextToken(); + if (first === 20 /* OpenParenToken */) { + if (second === 21 /* CloseParenToken */) { + // Simple cases: "() =>", "(): ", and "() {". + // This is an arrow function with no parameters. + // The last one is not actually an arrow function, + // but this is probably what the user intended. + var third = nextToken(); + switch (third) { + case 37 /* EqualsGreaterThanToken */: + case 57 /* ColonToken */: + case 18 /* OpenBraceToken */: + return 1 /* True */; + default: + return 0 /* False */; + } + } + // If encounter "([" or "({", this could be the start of a binding pattern. + // Examples: + // ([ x ]) => { } + // ({ x }) => { } + // ([ x ]) + // ({ x }) + if (second === 22 /* OpenBracketToken */ || second === 18 /* OpenBraceToken */) { + return 2 /* Unknown */; + } + // Simple case: "(..." + // This is an arrow function with a rest parameter. + if (second === 25 /* DotDotDotToken */) { + return 1 /* True */; + } + // Check for "(xxx yyy", where xxx is a modifier and yyy is an identifier. This + // isn't actually allowed, but we want to treat it as a lambda so we can provide + // a good error message. + if (ts.isModifierKind(second) && second !== 121 /* AsyncKeyword */ && lookAhead(nextTokenIsIdentifier)) { + return 1 /* True */; + } + // If we had "(" followed by something that's not an identifier, + // then this definitely doesn't look like a lambda. "this" is not + // valid, but we want to parse it and then give a semantic error. + if (!isIdentifier() && second !== 100 /* ThisKeyword */) { + return 0 /* False */; + } + switch (nextToken()) { + case 57 /* ColonToken */: + // If we have something like "(a:", then we must have a + // type-annotated parameter in an arrow function expression. + return 1 /* True */; + case 56 /* QuestionToken */: + nextToken(); + // If we have "(a?:" or "(a?," or "(a?=" or "(a?)" then it is definitely a lambda. + if (token() === 57 /* ColonToken */ || token() === 27 /* CommaToken */ || token() === 59 /* EqualsToken */ || token() === 21 /* CloseParenToken */) { + return 1 /* True */; + } + // Otherwise it is definitely not a lambda. + return 0 /* False */; + case 27 /* CommaToken */: + case 59 /* EqualsToken */: + case 21 /* CloseParenToken */: + // If we have "(a," or "(a=" or "(a)" this *could* be an arrow function + return 2 /* Unknown */; + } + // It is definitely not an arrow function + return 0 /* False */; + } + else { + ts.Debug.assert(first === 28 /* LessThanToken */); + // If we have "<" not followed by an identifier, + // then this definitely is not an arrow function. + if (!isIdentifier()) { + return 0 /* False */; + } + // JSX overrides + if (sourceFile.languageVariant === 1 /* JSX */) { + var isArrowFunctionInJsx = lookAhead(function () { + var third = nextToken(); + if (third === 86 /* ExtendsKeyword */) { + var fourth = nextToken(); + switch (fourth) { + case 59 /* EqualsToken */: + case 30 /* GreaterThanToken */: + return false; + default: + return true; + } + } + else if (third === 27 /* CommaToken */) { + return true; + } + return false; + }); + if (isArrowFunctionInJsx) { + return 1 /* True */; + } + return 0 /* False */; + } + // This *could* be a parenthesized arrow function. + return 2 /* Unknown */; + } + } + function parsePossibleParenthesizedArrowFunctionExpressionHead() { + return parseParenthesizedArrowFunctionExpressionHead(/*allowAmbiguity*/ false); + } + function tryParseAsyncSimpleArrowFunctionExpression() { + // We do a check here so that we won't be doing unnecessarily call to "lookAhead" + if (token() === 121 /* AsyncKeyword */) { + if (lookAhead(isUnParenthesizedAsyncArrowFunctionWorker) === 1 /* True */) { + var asyncModifier = parseModifiersForArrowFunction(); + var expr = parseBinaryExpressionOrHigher(/*precedence*/ 0); + return parseSimpleArrowFunctionExpression(expr, asyncModifier); + } + } + return undefined; + } + function isUnParenthesizedAsyncArrowFunctionWorker() { + // AsyncArrowFunctionExpression: + // 1) async[no LineTerminator here]AsyncArrowBindingIdentifier[?Yield][no LineTerminator here]=>AsyncConciseBody[?In] + // 2) CoverCallExpressionAndAsyncArrowHead[?Yield, ?Await][no LineTerminator here]=>AsyncConciseBody[?In] + if (token() === 121 /* AsyncKeyword */) { + nextToken(); + // If the "async" is followed by "=>" token then it is not a beginning of an async arrow-function + // but instead a simple arrow-function which will be parsed inside "parseAssignmentExpressionOrHigher" + if (scanner.hasPrecedingLineBreak() || token() === 37 /* EqualsGreaterThanToken */) { + return 0 /* False */; + } + // Check for un-parenthesized AsyncArrowFunction + var expr = parseBinaryExpressionOrHigher(/*precedence*/ 0); + if (!scanner.hasPrecedingLineBreak() && expr.kind === 72 /* Identifier */ && token() === 37 /* EqualsGreaterThanToken */) { + return 1 /* True */; + } + } + return 0 /* False */; + } + function parseParenthesizedArrowFunctionExpressionHead(allowAmbiguity) { + var node = createNodeWithJSDoc(197 /* ArrowFunction */); + node.modifiers = parseModifiersForArrowFunction(); + var isAsync = ts.hasModifier(node, 256 /* Async */) ? 2 /* Await */ : 0 /* None */; + // Arrow functions are never generators. + // + // If we're speculatively parsing a signature for a parenthesized arrow function, then + // we have to have a complete parameter list. Otherwise we might see something like + // a => (b => c) + // And think that "(b =>" was actually a parenthesized arrow function with a missing + // close paren. + if (!fillSignature(57 /* ColonToken */, isAsync, node) && !allowAmbiguity) { + return undefined; + } + // Parsing a signature isn't enough. + // Parenthesized arrow signatures often look like other valid expressions. + // For instance: + // - "(x = 10)" is an assignment expression parsed as a signature with a default parameter value. + // - "(x,y)" is a comma expression parsed as a signature with two parameters. + // - "a ? (b): c" will have "(b):" parsed as a signature with a return type annotation. + // + // So we need just a bit of lookahead to ensure that it can only be a signature. + if (!allowAmbiguity && token() !== 37 /* EqualsGreaterThanToken */ && token() !== 18 /* OpenBraceToken */) { + // Returning undefined here will cause our caller to rewind to where we started from. + return undefined; + } + return node; + } + function parseArrowFunctionExpressionBody(isAsync) { + if (token() === 18 /* OpenBraceToken */) { + return parseFunctionBlock(isAsync ? 2 /* Await */ : 0 /* None */); + } + if (token() !== 26 /* SemicolonToken */ && + token() !== 90 /* FunctionKeyword */ && + token() !== 76 /* ClassKeyword */ && + isStartOfStatement() && + !isStartOfExpressionStatement()) { + // Check if we got a plain statement (i.e. no expression-statements, no function/class expressions/declarations) + // + // Here we try to recover from a potential error situation in the case where the + // user meant to supply a block. For example, if the user wrote: + // + // a => + // let v = 0; + // } + // + // they may be missing an open brace. Check to see if that's the case so we can + // try to recover better. If we don't do this, then the next close curly we see may end + // up preemptively closing the containing construct. + // + // Note: even when 'IgnoreMissingOpenBrace' is passed, parseBody will still error. + return parseFunctionBlock(16 /* IgnoreMissingOpenBrace */ | (isAsync ? 2 /* Await */ : 0 /* None */)); + } + return isAsync + ? doInAwaitContext(parseAssignmentExpressionOrHigher) + : doOutsideOfAwaitContext(parseAssignmentExpressionOrHigher); + } + function parseConditionalExpressionRest(leftOperand) { + // Note: we are passed in an expression which was produced from parseBinaryExpressionOrHigher. + var questionToken = parseOptionalToken(56 /* QuestionToken */); + if (!questionToken) { + return leftOperand; + } + // Note: we explicitly 'allowIn' in the whenTrue part of the condition expression, and + // we do not that for the 'whenFalse' part. + var node = createNode(205 /* ConditionalExpression */, leftOperand.pos); + node.condition = leftOperand; + node.questionToken = questionToken; + node.whenTrue = doOutsideOfContext(disallowInAndDecoratorContext, parseAssignmentExpressionOrHigher); + node.colonToken = parseExpectedToken(57 /* ColonToken */); + node.whenFalse = ts.nodeIsPresent(node.colonToken) + ? parseAssignmentExpressionOrHigher() + : createMissingNode(72 /* Identifier */, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, ts.tokenToString(57 /* ColonToken */)); + return finishNode(node); + } + function parseBinaryExpressionOrHigher(precedence) { + var leftOperand = parseUnaryExpressionOrHigher(); + return parseBinaryExpressionRest(precedence, leftOperand); + } + function isInOrOfKeyword(t) { + return t === 93 /* InKeyword */ || t === 147 /* OfKeyword */; + } + function parseBinaryExpressionRest(precedence, leftOperand) { + while (true) { + // We either have a binary operator here, or we're finished. We call + // reScanGreaterToken so that we merge token sequences like > and = into >= + reScanGreaterToken(); + var newPrecedence = ts.getBinaryOperatorPrecedence(token()); + // Check the precedence to see if we should "take" this operator + // - For left associative operator (all operator but **), consume the operator, + // recursively call the function below, and parse binaryExpression as a rightOperand + // of the caller if the new precedence of the operator is greater then or equal to the current precedence. + // For example: + // a - b - c; + // ^token; leftOperand = b. Return b to the caller as a rightOperand + // a * b - c + // ^token; leftOperand = b. Return b to the caller as a rightOperand + // a - b * c; + // ^token; leftOperand = b. Return b * c to the caller as a rightOperand + // - For right associative operator (**), consume the operator, recursively call the function + // and parse binaryExpression as a rightOperand of the caller if the new precedence of + // the operator is strictly grater than the current precedence + // For example: + // a ** b ** c; + // ^^token; leftOperand = b. Return b ** c to the caller as a rightOperand + // a - b ** c; + // ^^token; leftOperand = b. Return b ** c to the caller as a rightOperand + // a ** b - c + // ^token; leftOperand = b. Return b to the caller as a rightOperand + var consumeCurrentOperator = token() === 41 /* AsteriskAsteriskToken */ ? + newPrecedence >= precedence : + newPrecedence > precedence; + if (!consumeCurrentOperator) { + break; + } + if (token() === 93 /* InKeyword */ && inDisallowInContext()) { + break; + } + if (token() === 119 /* AsKeyword */) { + // Make sure we *do* perform ASI for constructs like this: + // var x = foo + // as (Bar) + // This should be parsed as an initialized variable, followed + // by a function call to 'as' with the argument 'Bar' + if (scanner.hasPrecedingLineBreak()) { + break; + } + else { + nextToken(); + leftOperand = makeAsExpression(leftOperand, parseType()); + } + } + else { + leftOperand = makeBinaryExpression(leftOperand, parseTokenNode(), parseBinaryExpressionOrHigher(newPrecedence)); + } + } + return leftOperand; + } + function isBinaryOperator() { + if (inDisallowInContext() && token() === 93 /* InKeyword */) { + return false; + } + return ts.getBinaryOperatorPrecedence(token()) > 0; + } + function makeBinaryExpression(left, operatorToken, right) { + var node = createNode(204 /* BinaryExpression */, left.pos); + node.left = left; + node.operatorToken = operatorToken; + node.right = right; + return finishNode(node); + } + function makeAsExpression(left, right) { + var node = createNode(212 /* AsExpression */, left.pos); + node.expression = left; + node.type = right; + return finishNode(node); + } + function parsePrefixUnaryExpression() { + var node = createNode(202 /* PrefixUnaryExpression */); + node.operator = token(); + nextToken(); + node.operand = parseSimpleUnaryExpression(); + return finishNode(node); + } + function parseDeleteExpression() { + var node = createNode(198 /* DeleteExpression */); + nextToken(); + node.expression = parseSimpleUnaryExpression(); + return finishNode(node); + } + function parseTypeOfExpression() { + var node = createNode(199 /* TypeOfExpression */); + nextToken(); + node.expression = parseSimpleUnaryExpression(); + return finishNode(node); + } + function parseVoidExpression() { + var node = createNode(200 /* VoidExpression */); + nextToken(); + node.expression = parseSimpleUnaryExpression(); + return finishNode(node); + } + function isAwaitExpression() { + if (token() === 122 /* AwaitKeyword */) { + if (inAwaitContext()) { + return true; + } + // here we are using similar heuristics as 'isYieldExpression' + return lookAhead(nextTokenIsIdentifierOrKeywordOrLiteralOnSameLine); + } + return false; + } + function parseAwaitExpression() { + var node = createNode(201 /* AwaitExpression */); + nextToken(); + node.expression = parseSimpleUnaryExpression(); + return finishNode(node); + } + /** + * Parse ES7 exponential expression and await expression + * + * ES7 ExponentiationExpression: + * 1) UnaryExpression[?Yield] + * 2) UpdateExpression[?Yield] ** ExponentiationExpression[?Yield] + * + */ + function parseUnaryExpressionOrHigher() { + /** + * ES7 UpdateExpression: + * 1) LeftHandSideExpression[?Yield] + * 2) LeftHandSideExpression[?Yield][no LineTerminator here]++ + * 3) LeftHandSideExpression[?Yield][no LineTerminator here]-- + * 4) ++UnaryExpression[?Yield] + * 5) --UnaryExpression[?Yield] + */ + if (isUpdateExpression()) { + var updateExpression = parseUpdateExpression(); + return token() === 41 /* AsteriskAsteriskToken */ ? + parseBinaryExpressionRest(ts.getBinaryOperatorPrecedence(token()), updateExpression) : + updateExpression; + } + /** + * ES7 UnaryExpression: + * 1) UpdateExpression[?yield] + * 2) delete UpdateExpression[?yield] + * 3) void UpdateExpression[?yield] + * 4) typeof UpdateExpression[?yield] + * 5) + UpdateExpression[?yield] + * 6) - UpdateExpression[?yield] + * 7) ~ UpdateExpression[?yield] + * 8) ! UpdateExpression[?yield] + */ + var unaryOperator = token(); + var simpleUnaryExpression = parseSimpleUnaryExpression(); + if (token() === 41 /* AsteriskAsteriskToken */) { + var pos = ts.skipTrivia(sourceText, simpleUnaryExpression.pos); + var end = simpleUnaryExpression.end; + if (simpleUnaryExpression.kind === 194 /* TypeAssertionExpression */) { + parseErrorAt(pos, end, ts.Diagnostics.A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses); + } + else { + parseErrorAt(pos, end, ts.Diagnostics.An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses, ts.tokenToString(unaryOperator)); + } + } + return simpleUnaryExpression; + } + /** + * Parse ES7 simple-unary expression or higher: + * + * ES7 UnaryExpression: + * 1) UpdateExpression[?yield] + * 2) delete UnaryExpression[?yield] + * 3) void UnaryExpression[?yield] + * 4) typeof UnaryExpression[?yield] + * 5) + UnaryExpression[?yield] + * 6) - UnaryExpression[?yield] + * 7) ~ UnaryExpression[?yield] + * 8) ! UnaryExpression[?yield] + * 9) [+Await] await UnaryExpression[?yield] + */ + function parseSimpleUnaryExpression() { + switch (token()) { + case 38 /* PlusToken */: + case 39 /* MinusToken */: + case 53 /* TildeToken */: + case 52 /* ExclamationToken */: + return parsePrefixUnaryExpression(); + case 81 /* DeleteKeyword */: + return parseDeleteExpression(); + case 104 /* TypeOfKeyword */: + return parseTypeOfExpression(); + case 106 /* VoidKeyword */: + return parseVoidExpression(); + case 28 /* LessThanToken */: + // This is modified UnaryExpression grammar in TypeScript + // UnaryExpression (modified): + // < type > UnaryExpression + return parseTypeAssertion(); + case 122 /* AwaitKeyword */: + if (isAwaitExpression()) { + return parseAwaitExpression(); + } + // falls through + default: + return parseUpdateExpression(); + } + } + /** + * Check if the current token can possibly be an ES7 increment expression. + * + * ES7 UpdateExpression: + * LeftHandSideExpression[?Yield] + * LeftHandSideExpression[?Yield][no LineTerminator here]++ + * LeftHandSideExpression[?Yield][no LineTerminator here]-- + * ++LeftHandSideExpression[?Yield] + * --LeftHandSideExpression[?Yield] + */ + function isUpdateExpression() { + // This function is called inside parseUnaryExpression to decide + // whether to call parseSimpleUnaryExpression or call parseUpdateExpression directly + switch (token()) { + case 38 /* PlusToken */: + case 39 /* MinusToken */: + case 53 /* TildeToken */: + case 52 /* ExclamationToken */: + case 81 /* DeleteKeyword */: + case 104 /* TypeOfKeyword */: + case 106 /* VoidKeyword */: + case 122 /* AwaitKeyword */: + return false; + case 28 /* LessThanToken */: + // If we are not in JSX context, we are parsing TypeAssertion which is an UnaryExpression + if (sourceFile.languageVariant !== 1 /* JSX */) { + return false; + } + // We are in JSX context and the token is part of JSXElement. + // falls through + default: + return true; + } + } + /** + * Parse ES7 UpdateExpression. UpdateExpression is used instead of ES6's PostFixExpression. + * + * ES7 UpdateExpression[yield]: + * 1) LeftHandSideExpression[?yield] + * 2) LeftHandSideExpression[?yield] [[no LineTerminator here]]++ + * 3) LeftHandSideExpression[?yield] [[no LineTerminator here]]-- + * 4) ++LeftHandSideExpression[?yield] + * 5) --LeftHandSideExpression[?yield] + * In TypeScript (2), (3) are parsed as PostfixUnaryExpression. (4), (5) are parsed as PrefixUnaryExpression + */ + function parseUpdateExpression() { + if (token() === 44 /* PlusPlusToken */ || token() === 45 /* MinusMinusToken */) { + var node = createNode(202 /* PrefixUnaryExpression */); + node.operator = token(); + nextToken(); + node.operand = parseLeftHandSideExpressionOrHigher(); + return finishNode(node); + } + else if (sourceFile.languageVariant === 1 /* JSX */ && token() === 28 /* LessThanToken */ && lookAhead(nextTokenIsIdentifierOrKeywordOrGreaterThan)) { + // JSXElement is part of primaryExpression + return parseJsxElementOrSelfClosingElementOrFragment(/*inExpressionContext*/ true); + } + var expression = parseLeftHandSideExpressionOrHigher(); + ts.Debug.assert(ts.isLeftHandSideExpression(expression)); + if ((token() === 44 /* PlusPlusToken */ || token() === 45 /* MinusMinusToken */) && !scanner.hasPrecedingLineBreak()) { + var node = createNode(203 /* PostfixUnaryExpression */, expression.pos); + node.operand = expression; + node.operator = token(); + nextToken(); + return finishNode(node); + } + return expression; + } + function parseLeftHandSideExpressionOrHigher() { + // Original Ecma: + // LeftHandSideExpression: See 11.2 + // NewExpression + // CallExpression + // + // Our simplification: + // + // LeftHandSideExpression: See 11.2 + // MemberExpression + // CallExpression + // + // See comment in parseMemberExpressionOrHigher on how we replaced NewExpression with + // MemberExpression to make our lives easier. + // + // to best understand the below code, it's important to see how CallExpression expands + // out into its own productions: + // + // CallExpression: + // MemberExpression Arguments + // CallExpression Arguments + // CallExpression[Expression] + // CallExpression.IdentifierName + // import (AssignmentExpression) + // super Arguments + // super.IdentifierName + // + // Because of the recursion in these calls, we need to bottom out first. There are three + // bottom out states we can run into: 1) We see 'super' which must start either of + // the last two CallExpression productions. 2) We see 'import' which must start import call. + // 3)we have a MemberExpression which either completes the LeftHandSideExpression, + // or starts the beginning of the first four CallExpression productions. + var expression; + if (token() === 92 /* ImportKeyword */) { + if (lookAhead(nextTokenIsOpenParenOrLessThan)) { + // We don't want to eagerly consume all import keyword as import call expression so we look ahead to find "(" + // For example: + // var foo3 = require("subfolder + // import * as foo1 from "module-from-node + // We want this import to be a statement rather than import call expression + sourceFile.flags |= 524288 /* PossiblyContainsDynamicImport */; + expression = parseTokenNode(); + } + else if (lookAhead(nextTokenIsDot)) { + // This is an 'import.*' metaproperty (i.e. 'import.meta') + var fullStart = scanner.getStartPos(); + nextToken(); // advance past the 'import' + nextToken(); // advance past the dot + var node = createNode(214 /* MetaProperty */, fullStart); + node.keywordToken = 92 /* ImportKeyword */; + node.name = parseIdentifierName(); + expression = finishNode(node); + sourceFile.flags |= 1048576 /* PossiblyContainsImportMeta */; + } + else { + expression = parseMemberExpressionOrHigher(); + } + } + else { + expression = token() === 98 /* SuperKeyword */ ? parseSuperExpression() : parseMemberExpressionOrHigher(); + } + // Now, we *may* be complete. However, we might have consumed the start of a + // CallExpression. As such, we need to consume the rest of it here to be complete. + return parseCallExpressionRest(expression); + } + function parseMemberExpressionOrHigher() { + // Note: to make our lives simpler, we decompose the NewExpression productions and + // place ObjectCreationExpression and FunctionExpression into PrimaryExpression. + // like so: + // + // PrimaryExpression : See 11.1 + // this + // Identifier + // Literal + // ArrayLiteral + // ObjectLiteral + // (Expression) + // FunctionExpression + // new MemberExpression Arguments? + // + // MemberExpression : See 11.2 + // PrimaryExpression + // MemberExpression[Expression] + // MemberExpression.IdentifierName + // + // CallExpression : See 11.2 + // MemberExpression + // CallExpression Arguments + // CallExpression[Expression] + // CallExpression.IdentifierName + // + // Technically this is ambiguous. i.e. CallExpression defines: + // + // CallExpression: + // CallExpression Arguments + // + // If you see: "new Foo()" + // + // Then that could be treated as a single ObjectCreationExpression, or it could be + // treated as the invocation of "new Foo". We disambiguate that in code (to match + // the original grammar) by making sure that if we see an ObjectCreationExpression + // we always consume arguments if they are there. So we treat "new Foo()" as an + // object creation only, and not at all as an invocation. Another way to think + // about this is that for every "new" that we see, we will consume an argument list if + // it is there as part of the *associated* object creation node. Any additional + // argument lists we see, will become invocation expressions. + // + // Because there are no other places in the grammar now that refer to FunctionExpression + // or ObjectCreationExpression, it is safe to push down into the PrimaryExpression + // production. + // + // Because CallExpression and MemberExpression are left recursive, we need to bottom out + // of the recursion immediately. So we parse out a primary expression to start with. + var expression = parsePrimaryExpression(); + return parseMemberExpressionRest(expression); + } + function parseSuperExpression() { + var expression = parseTokenNode(); + if (token() === 20 /* OpenParenToken */ || token() === 24 /* DotToken */ || token() === 22 /* OpenBracketToken */) { + return expression; + } + // If we have seen "super" it must be followed by '(' or '.'. + // If it wasn't then just try to parse out a '.' and report an error. + var node = createNode(189 /* PropertyAccessExpression */, expression.pos); + node.expression = expression; + parseExpectedToken(24 /* DotToken */, ts.Diagnostics.super_must_be_followed_by_an_argument_list_or_member_access); + node.name = parseRightSideOfDot(/*allowIdentifierNames*/ true); + return finishNode(node); + } + function parseJsxElementOrSelfClosingElementOrFragment(inExpressionContext) { + var opening = parseJsxOpeningOrSelfClosingElementOrOpeningFragment(inExpressionContext); + var result; + if (opening.kind === 262 /* JsxOpeningElement */) { + var node = createNode(260 /* JsxElement */, opening.pos); + node.openingElement = opening; + node.children = parseJsxChildren(node.openingElement); + node.closingElement = parseJsxClosingElement(inExpressionContext); + if (!tagNamesAreEquivalent(node.openingElement.tagName, node.closingElement.tagName)) { + parseErrorAtRange(node.closingElement, ts.Diagnostics.Expected_corresponding_JSX_closing_tag_for_0, ts.getTextOfNodeFromSourceText(sourceText, node.openingElement.tagName)); + } + result = finishNode(node); + } + else if (opening.kind === 265 /* JsxOpeningFragment */) { + var node = createNode(264 /* JsxFragment */, opening.pos); + node.openingFragment = opening; + node.children = parseJsxChildren(node.openingFragment); + node.closingFragment = parseJsxClosingFragment(inExpressionContext); + result = finishNode(node); + } + else { + ts.Debug.assert(opening.kind === 261 /* JsxSelfClosingElement */); + // Nothing else to do for self-closing elements + result = opening; + } + // If the user writes the invalid code '
      ' in an expression context (i.e. not wrapped in + // an enclosing tag), we'll naively try to parse ^ this as a 'less than' operator and the remainder of the tag + // as garbage, which will cause the formatter to badly mangle the JSX. Perform a speculative parse of a JSX + // element if we see a < token so that we can wrap it in a synthetic binary expression so the formatter + // does less damage and we can report a better error. + // Since JSX elements are invalid < operands anyway, this lookahead parse will only occur in error scenarios + // of one sort or another. + if (inExpressionContext && token() === 28 /* LessThanToken */) { + var invalidElement = tryParse(function () { return parseJsxElementOrSelfClosingElementOrFragment(/*inExpressionContext*/ true); }); + if (invalidElement) { + parseErrorAtCurrentToken(ts.Diagnostics.JSX_expressions_must_have_one_parent_element); + var badNode = createNode(204 /* BinaryExpression */, result.pos); + badNode.end = invalidElement.end; + badNode.left = result; + badNode.right = invalidElement; + badNode.operatorToken = createMissingNode(27 /* CommaToken */, /*reportAtCurrentPosition*/ false, /*diagnosticMessage*/ undefined); // TODO: GH#18217 + badNode.operatorToken.pos = badNode.operatorToken.end = badNode.right.pos; + return badNode; + } + } + return result; + } + function parseJsxText() { + var node = createNode(11 /* JsxText */); + node.containsOnlyWhiteSpaces = currentToken === 12 /* JsxTextAllWhiteSpaces */; + currentToken = scanner.scanJsxToken(); + return finishNode(node); + } + function parseJsxChild(openingTag, token) { + switch (token) { + case 1 /* EndOfFileToken */: + // If we hit EOF, issue the error at the tag that lacks the closing element + // rather than at the end of the file (which is useless) + if (ts.isJsxOpeningFragment(openingTag)) { + parseErrorAtRange(openingTag, ts.Diagnostics.JSX_fragment_has_no_corresponding_closing_tag); + } + else { + parseErrorAtRange(openingTag.tagName, ts.Diagnostics.JSX_element_0_has_no_corresponding_closing_tag, ts.getTextOfNodeFromSourceText(sourceText, openingTag.tagName)); + } + return undefined; + case 29 /* LessThanSlashToken */: + case 7 /* ConflictMarkerTrivia */: + return undefined; + case 11 /* JsxText */: + case 12 /* JsxTextAllWhiteSpaces */: + return parseJsxText(); + case 18 /* OpenBraceToken */: + return parseJsxExpression(/*inExpressionContext*/ false); + case 28 /* LessThanToken */: + return parseJsxElementOrSelfClosingElementOrFragment(/*inExpressionContext*/ false); + default: + return ts.Debug.assertNever(token); + } + } + function parseJsxChildren(openingTag) { + var list = []; + var listPos = getNodePos(); + var saveParsingContext = parsingContext; + parsingContext |= 1 << 14 /* JsxChildren */; + while (true) { + var child = parseJsxChild(openingTag, currentToken = scanner.reScanJsxToken()); + if (!child) + break; + list.push(child); + } + parsingContext = saveParsingContext; + return createNodeArray(list, listPos); + } + function parseJsxAttributes() { + var jsxAttributes = createNode(268 /* JsxAttributes */); + jsxAttributes.properties = parseList(13 /* JsxAttributes */, parseJsxAttribute); + return finishNode(jsxAttributes); + } + function parseJsxOpeningOrSelfClosingElementOrOpeningFragment(inExpressionContext) { + var fullStart = scanner.getStartPos(); + parseExpected(28 /* LessThanToken */); + if (token() === 30 /* GreaterThanToken */) { + // See below for explanation of scanJsxText + var node_1 = createNode(265 /* JsxOpeningFragment */, fullStart); + scanJsxText(); + return finishNode(node_1); + } + var tagName = parseJsxElementName(); + var typeArguments = tryParseTypeArguments(); + var attributes = parseJsxAttributes(); + var node; + if (token() === 30 /* GreaterThanToken */) { + // Closing tag, so scan the immediately-following text with the JSX scanning instead + // of regular scanning to avoid treating illegal characters (e.g. '#') as immediate + // scanning errors + node = createNode(262 /* JsxOpeningElement */, fullStart); + scanJsxText(); + } + else { + parseExpected(42 /* SlashToken */); + if (inExpressionContext) { + parseExpected(30 /* GreaterThanToken */); + } + else { + parseExpected(30 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false); + scanJsxText(); + } + node = createNode(261 /* JsxSelfClosingElement */, fullStart); + } + node.tagName = tagName; + node.typeArguments = typeArguments; + node.attributes = attributes; + return finishNode(node); + } + function parseJsxElementName() { + scanJsxIdentifier(); + // JsxElement can have name in the form of + // propertyAccessExpression + // primaryExpression in the form of an identifier and "this" keyword + // We can't just simply use parseLeftHandSideExpressionOrHigher because then we will start consider class,function etc as a keyword + // We only want to consider "this" as a primaryExpression + var expression = token() === 100 /* ThisKeyword */ ? + parseTokenNode() : parseIdentifierName(); + while (parseOptional(24 /* DotToken */)) { + var propertyAccess = createNode(189 /* PropertyAccessExpression */, expression.pos); + propertyAccess.expression = expression; + propertyAccess.name = parseRightSideOfDot(/*allowIdentifierNames*/ true); + expression = finishNode(propertyAccess); + } + return expression; + } + function parseJsxExpression(inExpressionContext) { + var node = createNode(270 /* JsxExpression */); + if (!parseExpected(18 /* OpenBraceToken */)) { + return undefined; + } + if (token() !== 19 /* CloseBraceToken */) { + node.dotDotDotToken = parseOptionalToken(25 /* DotDotDotToken */); + node.expression = parseAssignmentExpressionOrHigher(); + } + if (inExpressionContext) { + parseExpected(19 /* CloseBraceToken */); + } + else { + parseExpected(19 /* CloseBraceToken */, /*message*/ undefined, /*shouldAdvance*/ false); + scanJsxText(); + } + return finishNode(node); + } + function parseJsxAttribute() { + if (token() === 18 /* OpenBraceToken */) { + return parseJsxSpreadAttribute(); + } + scanJsxIdentifier(); + var node = createNode(267 /* JsxAttribute */); + node.name = parseIdentifierName(); + if (token() === 59 /* EqualsToken */) { + switch (scanJsxAttributeValue()) { + case 10 /* StringLiteral */: + node.initializer = parseLiteralNode(); + break; + default: + node.initializer = parseJsxExpression(/*inExpressionContext*/ true); + break; + } + } + return finishNode(node); + } + function parseJsxSpreadAttribute() { + var node = createNode(269 /* JsxSpreadAttribute */); + parseExpected(18 /* OpenBraceToken */); + parseExpected(25 /* DotDotDotToken */); + node.expression = parseExpression(); + parseExpected(19 /* CloseBraceToken */); + return finishNode(node); + } + function parseJsxClosingElement(inExpressionContext) { + var node = createNode(263 /* JsxClosingElement */); + parseExpected(29 /* LessThanSlashToken */); + node.tagName = parseJsxElementName(); + if (inExpressionContext) { + parseExpected(30 /* GreaterThanToken */); + } + else { + parseExpected(30 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false); + scanJsxText(); + } + return finishNode(node); + } + function parseJsxClosingFragment(inExpressionContext) { + var node = createNode(266 /* JsxClosingFragment */); + parseExpected(29 /* LessThanSlashToken */); + if (ts.tokenIsIdentifierOrKeyword(token())) { + parseErrorAtRange(parseJsxElementName(), ts.Diagnostics.Expected_corresponding_closing_tag_for_JSX_fragment); + } + if (inExpressionContext) { + parseExpected(30 /* GreaterThanToken */); + } + else { + parseExpected(30 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false); + scanJsxText(); + } + return finishNode(node); + } + function parseTypeAssertion() { + var node = createNode(194 /* TypeAssertionExpression */); + parseExpected(28 /* LessThanToken */); + node.type = parseType(); + parseExpected(30 /* GreaterThanToken */); + node.expression = parseSimpleUnaryExpression(); + return finishNode(node); + } + function parseMemberExpressionRest(expression) { + while (true) { + var dotToken = parseOptionalToken(24 /* DotToken */); + if (dotToken) { + var propertyAccess = createNode(189 /* PropertyAccessExpression */, expression.pos); + propertyAccess.expression = expression; + propertyAccess.name = parseRightSideOfDot(/*allowIdentifierNames*/ true); + expression = finishNode(propertyAccess); + continue; + } + if (token() === 52 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) { + nextToken(); + var nonNullExpression = createNode(213 /* NonNullExpression */, expression.pos); + nonNullExpression.expression = expression; + expression = finishNode(nonNullExpression); + continue; + } + // when in the [Decorator] context, we do not parse ElementAccess as it could be part of a ComputedPropertyName + if (!inDecoratorContext() && parseOptional(22 /* OpenBracketToken */)) { + var indexedAccess = createNode(190 /* ElementAccessExpression */, expression.pos); + indexedAccess.expression = expression; + if (token() === 23 /* CloseBracketToken */) { + indexedAccess.argumentExpression = createMissingNode(72 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.An_element_access_expression_should_take_an_argument); + } + else { + var argument = allowInAnd(parseExpression); + if (ts.isStringOrNumericLiteralLike(argument)) { + argument.text = internIdentifier(argument.text); + } + indexedAccess.argumentExpression = argument; + } + parseExpected(23 /* CloseBracketToken */); + expression = finishNode(indexedAccess); + continue; + } + if (isTemplateStartOfTaggedTemplate()) { + expression = parseTaggedTemplateRest(expression, /*typeArguments*/ undefined); + continue; + } + return expression; + } + } + function isTemplateStartOfTaggedTemplate() { + return token() === 14 /* NoSubstitutionTemplateLiteral */ || token() === 15 /* TemplateHead */; + } + function parseTaggedTemplateRest(tag, typeArguments) { + var tagExpression = createNode(193 /* TaggedTemplateExpression */, tag.pos); + tagExpression.tag = tag; + tagExpression.typeArguments = typeArguments; + tagExpression.template = token() === 14 /* NoSubstitutionTemplateLiteral */ + ? parseLiteralNode() + : parseTemplateExpression(); + return finishNode(tagExpression); + } + function parseCallExpressionRest(expression) { + while (true) { + expression = parseMemberExpressionRest(expression); + if (token() === 28 /* LessThanToken */) { + // See if this is the start of a generic invocation. If so, consume it and + // keep checking for postfix expressions. Otherwise, it's just a '<' that's + // part of an arithmetic expression. Break out so we consume it higher in the + // stack. + var typeArguments = tryParse(parseTypeArgumentsInExpression); + if (!typeArguments) { + return expression; + } + if (isTemplateStartOfTaggedTemplate()) { + expression = parseTaggedTemplateRest(expression, typeArguments); + continue; + } + var callExpr = createNode(191 /* CallExpression */, expression.pos); + callExpr.expression = expression; + callExpr.typeArguments = typeArguments; + callExpr.arguments = parseArgumentList(); + expression = finishNode(callExpr); + continue; + } + else if (token() === 20 /* OpenParenToken */) { + var callExpr = createNode(191 /* CallExpression */, expression.pos); + callExpr.expression = expression; + callExpr.arguments = parseArgumentList(); + expression = finishNode(callExpr); + continue; + } + return expression; + } + } + function parseArgumentList() { + parseExpected(20 /* OpenParenToken */); + var result = parseDelimitedList(11 /* ArgumentExpressions */, parseArgumentExpression); + parseExpected(21 /* CloseParenToken */); + return result; + } + function parseTypeArgumentsInExpression() { + if (!parseOptional(28 /* LessThanToken */)) { + return undefined; + } + var typeArguments = parseDelimitedList(20 /* TypeArguments */, parseType); + if (!parseExpected(30 /* GreaterThanToken */)) { + // If it doesn't have the closing `>` then it's definitely not an type argument list. + return undefined; + } + // If we have a '<', then only parse this as a argument list if the type arguments + // are complete and we have an open paren. if we don't, rewind and return nothing. + return typeArguments && canFollowTypeArgumentsInExpression() + ? typeArguments + : undefined; + } + function canFollowTypeArgumentsInExpression() { + switch (token()) { + case 20 /* OpenParenToken */: // foo( + case 14 /* NoSubstitutionTemplateLiteral */: // foo `...` + case 15 /* TemplateHead */: // foo `...${100}...` + // these are the only tokens can legally follow a type argument + // list. So we definitely want to treat them as type arg lists. + case 24 /* DotToken */: // foo. + case 21 /* CloseParenToken */: // foo) + case 23 /* CloseBracketToken */: // foo] + case 57 /* ColonToken */: // foo: + case 26 /* SemicolonToken */: // foo; + case 56 /* QuestionToken */: // foo? + case 33 /* EqualsEqualsToken */: // foo == + case 35 /* EqualsEqualsEqualsToken */: // foo === + case 34 /* ExclamationEqualsToken */: // foo != + case 36 /* ExclamationEqualsEqualsToken */: // foo !== + case 54 /* AmpersandAmpersandToken */: // foo && + case 55 /* BarBarToken */: // foo || + case 51 /* CaretToken */: // foo ^ + case 49 /* AmpersandToken */: // foo & + case 50 /* BarToken */: // foo | + case 19 /* CloseBraceToken */: // foo } + case 1 /* EndOfFileToken */: // foo + // these cases can't legally follow a type arg list. However, they're not legal + // expressions either. The user is probably in the middle of a generic type. So + // treat it as such. + return true; + case 27 /* CommaToken */: // foo, + case 18 /* OpenBraceToken */: // foo { + // We don't want to treat these as type arguments. Otherwise we'll parse this + // as an invocation expression. Instead, we want to parse out the expression + // in isolation from the type arguments. + default: + // Anything else treat as an expression. + return false; + } + } + function parsePrimaryExpression() { + switch (token()) { + case 8 /* NumericLiteral */: + case 9 /* BigIntLiteral */: + case 10 /* StringLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: + return parseLiteralNode(); + case 100 /* ThisKeyword */: + case 98 /* SuperKeyword */: + case 96 /* NullKeyword */: + case 102 /* TrueKeyword */: + case 87 /* FalseKeyword */: + return parseTokenNode(); + case 20 /* OpenParenToken */: + return parseParenthesizedExpression(); + case 22 /* OpenBracketToken */: + return parseArrayLiteralExpression(); + case 18 /* OpenBraceToken */: + return parseObjectLiteralExpression(); + case 121 /* AsyncKeyword */: + // Async arrow functions are parsed earlier in parseAssignmentExpressionOrHigher. + // If we encounter `async [no LineTerminator here] function` then this is an async + // function; otherwise, its an identifier. + if (!lookAhead(nextTokenIsFunctionKeywordOnSameLine)) { + break; + } + return parseFunctionExpression(); + case 76 /* ClassKeyword */: + return parseClassExpression(); + case 90 /* FunctionKeyword */: + return parseFunctionExpression(); + case 95 /* NewKeyword */: + return parseNewExpressionOrNewDotTarget(); + case 42 /* SlashToken */: + case 64 /* SlashEqualsToken */: + if (reScanSlashToken() === 13 /* RegularExpressionLiteral */) { + return parseLiteralNode(); + } + break; + case 15 /* TemplateHead */: + return parseTemplateExpression(); + } + return parseIdentifier(ts.Diagnostics.Expression_expected); + } + function parseParenthesizedExpression() { + var node = createNodeWithJSDoc(195 /* ParenthesizedExpression */); + parseExpected(20 /* OpenParenToken */); + node.expression = allowInAnd(parseExpression); + parseExpected(21 /* CloseParenToken */); + return finishNode(node); + } + function parseSpreadElement() { + var node = createNode(208 /* SpreadElement */); + parseExpected(25 /* DotDotDotToken */); + node.expression = parseAssignmentExpressionOrHigher(); + return finishNode(node); + } + function parseArgumentOrArrayLiteralElement() { + return token() === 25 /* DotDotDotToken */ ? parseSpreadElement() : + token() === 27 /* CommaToken */ ? createNode(210 /* OmittedExpression */) : + parseAssignmentExpressionOrHigher(); + } + function parseArgumentExpression() { + return doOutsideOfContext(disallowInAndDecoratorContext, parseArgumentOrArrayLiteralElement); + } + function parseArrayLiteralExpression() { + var node = createNode(187 /* ArrayLiteralExpression */); + parseExpected(22 /* OpenBracketToken */); + if (scanner.hasPrecedingLineBreak()) { + node.multiLine = true; + } + node.elements = parseDelimitedList(15 /* ArrayLiteralMembers */, parseArgumentOrArrayLiteralElement); + parseExpected(23 /* CloseBracketToken */); + return finishNode(node); + } + function parseObjectLiteralElement() { + var node = createNodeWithJSDoc(0 /* Unknown */); + if (parseOptionalToken(25 /* DotDotDotToken */)) { + node.kind = 277 /* SpreadAssignment */; + node.expression = parseAssignmentExpressionOrHigher(); + return finishNode(node); + } + node.decorators = parseDecorators(); + node.modifiers = parseModifiers(); + if (parseContextualModifier(126 /* GetKeyword */)) { + return parseAccessorDeclaration(node, 158 /* GetAccessor */); + } + if (parseContextualModifier(137 /* SetKeyword */)) { + return parseAccessorDeclaration(node, 159 /* SetAccessor */); + } + var asteriskToken = parseOptionalToken(40 /* AsteriskToken */); + var tokenIsIdentifier = isIdentifier(); + node.name = parsePropertyName(); + // Disallowing of optional property assignments and definite assignment assertion happens in the grammar checker. + node.questionToken = parseOptionalToken(56 /* QuestionToken */); + node.exclamationToken = parseOptionalToken(52 /* ExclamationToken */); + if (asteriskToken || token() === 20 /* OpenParenToken */ || token() === 28 /* LessThanToken */) { + return parseMethodDeclaration(node, asteriskToken); + } + // check if it is short-hand property assignment or normal property assignment + // NOTE: if token is EqualsToken it is interpreted as CoverInitializedName production + // CoverInitializedName[Yield] : + // IdentifierReference[?Yield] Initializer[In, ?Yield] + // this is necessary because ObjectLiteral productions are also used to cover grammar for ObjectAssignmentPattern + var isShorthandPropertyAssignment = tokenIsIdentifier && (token() !== 57 /* ColonToken */); + if (isShorthandPropertyAssignment) { + node.kind = 276 /* ShorthandPropertyAssignment */; + var equalsToken = parseOptionalToken(59 /* EqualsToken */); + if (equalsToken) { + node.equalsToken = equalsToken; + node.objectAssignmentInitializer = allowInAnd(parseAssignmentExpressionOrHigher); + } + } + else { + node.kind = 275 /* PropertyAssignment */; + parseExpected(57 /* ColonToken */); + node.initializer = allowInAnd(parseAssignmentExpressionOrHigher); + } + return finishNode(node); + } + function parseObjectLiteralExpression() { + var node = createNode(188 /* ObjectLiteralExpression */); + parseExpected(18 /* OpenBraceToken */); + if (scanner.hasPrecedingLineBreak()) { + node.multiLine = true; + } + node.properties = parseDelimitedList(12 /* ObjectLiteralMembers */, parseObjectLiteralElement, /*considerSemicolonAsDelimiter*/ true); + parseExpected(19 /* CloseBraceToken */); + return finishNode(node); + } + function parseFunctionExpression() { + // GeneratorExpression: + // function* BindingIdentifier [Yield][opt](FormalParameters[Yield]){ GeneratorBody } + // + // FunctionExpression: + // function BindingIdentifier[opt](FormalParameters){ FunctionBody } + var saveDecoratorContext = inDecoratorContext(); + if (saveDecoratorContext) { + setDecoratorContext(/*val*/ false); + } + var node = createNodeWithJSDoc(196 /* FunctionExpression */); + node.modifiers = parseModifiers(); + parseExpected(90 /* FunctionKeyword */); + node.asteriskToken = parseOptionalToken(40 /* AsteriskToken */); + var isGenerator = node.asteriskToken ? 1 /* Yield */ : 0 /* None */; + var isAsync = ts.hasModifier(node, 256 /* Async */) ? 2 /* Await */ : 0 /* None */; + node.name = + isGenerator && isAsync ? doInYieldAndAwaitContext(parseOptionalIdentifier) : + isGenerator ? doInYieldContext(parseOptionalIdentifier) : + isAsync ? doInAwaitContext(parseOptionalIdentifier) : + parseOptionalIdentifier(); + fillSignature(57 /* ColonToken */, isGenerator | isAsync, node); + node.body = parseFunctionBlock(isGenerator | isAsync); + if (saveDecoratorContext) { + setDecoratorContext(/*val*/ true); + } + return finishNode(node); + } + function parseOptionalIdentifier() { + return isIdentifier() ? parseIdentifier() : undefined; + } + function parseNewExpressionOrNewDotTarget() { + var fullStart = scanner.getStartPos(); + parseExpected(95 /* NewKeyword */); + if (parseOptional(24 /* DotToken */)) { + var node_2 = createNode(214 /* MetaProperty */, fullStart); + node_2.keywordToken = 95 /* NewKeyword */; + node_2.name = parseIdentifierName(); + return finishNode(node_2); + } + var expression = parsePrimaryExpression(); + var typeArguments; + while (true) { + expression = parseMemberExpressionRest(expression); + typeArguments = tryParse(parseTypeArgumentsInExpression); + if (isTemplateStartOfTaggedTemplate()) { + ts.Debug.assert(!!typeArguments, "Expected a type argument list; all plain tagged template starts should be consumed in 'parseMemberExpressionRest'"); + expression = parseTaggedTemplateRest(expression, typeArguments); + typeArguments = undefined; + } + break; + } + var node = createNode(192 /* NewExpression */, fullStart); + node.expression = expression; + node.typeArguments = typeArguments; + if (node.typeArguments || token() === 20 /* OpenParenToken */) { + node.arguments = parseArgumentList(); + } + return finishNode(node); + } + // STATEMENTS + function parseBlock(ignoreMissingOpenBrace, diagnosticMessage) { + var node = createNode(218 /* Block */); + if (parseExpected(18 /* OpenBraceToken */, diagnosticMessage) || ignoreMissingOpenBrace) { + if (scanner.hasPrecedingLineBreak()) { + node.multiLine = true; + } + node.statements = parseList(1 /* BlockStatements */, parseStatement); + parseExpected(19 /* CloseBraceToken */); + } + else { + node.statements = createMissingList(); + } + return finishNode(node); + } + function parseFunctionBlock(flags, diagnosticMessage) { + var savedYieldContext = inYieldContext(); + setYieldContext(!!(flags & 1 /* Yield */)); + var savedAwaitContext = inAwaitContext(); + setAwaitContext(!!(flags & 2 /* Await */)); + // We may be in a [Decorator] context when parsing a function expression or + // arrow function. The body of the function is not in [Decorator] context. + var saveDecoratorContext = inDecoratorContext(); + if (saveDecoratorContext) { + setDecoratorContext(/*val*/ false); + } + var block = parseBlock(!!(flags & 16 /* IgnoreMissingOpenBrace */), diagnosticMessage); + if (saveDecoratorContext) { + setDecoratorContext(/*val*/ true); + } + setYieldContext(savedYieldContext); + setAwaitContext(savedAwaitContext); + return block; + } + function parseEmptyStatement() { + var node = createNode(220 /* EmptyStatement */); + parseExpected(26 /* SemicolonToken */); + return finishNode(node); + } + function parseIfStatement() { + var node = createNode(222 /* IfStatement */); + parseExpected(91 /* IfKeyword */); + parseExpected(20 /* OpenParenToken */); + node.expression = allowInAnd(parseExpression); + parseExpected(21 /* CloseParenToken */); + node.thenStatement = parseStatement(); + node.elseStatement = parseOptional(83 /* ElseKeyword */) ? parseStatement() : undefined; + return finishNode(node); + } + function parseDoStatement() { + var node = createNode(223 /* DoStatement */); + parseExpected(82 /* DoKeyword */); + node.statement = parseStatement(); + parseExpected(107 /* WhileKeyword */); + parseExpected(20 /* OpenParenToken */); + node.expression = allowInAnd(parseExpression); + parseExpected(21 /* CloseParenToken */); + // From: https://mail.mozilla.org/pipermail/es-discuss/2011-August/016188.html + // 157 min --- All allen at wirfs-brock.com CONF --- "do{;}while(false)false" prohibited in + // spec but allowed in consensus reality. Approved -- this is the de-facto standard whereby + // do;while(0)x will have a semicolon inserted before x. + parseOptional(26 /* SemicolonToken */); + return finishNode(node); + } + function parseWhileStatement() { + var node = createNode(224 /* WhileStatement */); + parseExpected(107 /* WhileKeyword */); + parseExpected(20 /* OpenParenToken */); + node.expression = allowInAnd(parseExpression); + parseExpected(21 /* CloseParenToken */); + node.statement = parseStatement(); + return finishNode(node); + } + function parseForOrForInOrForOfStatement() { + var pos = getNodePos(); + parseExpected(89 /* ForKeyword */); + var awaitToken = parseOptionalToken(122 /* AwaitKeyword */); + parseExpected(20 /* OpenParenToken */); + var initializer; + if (token() !== 26 /* SemicolonToken */) { + if (token() === 105 /* VarKeyword */ || token() === 111 /* LetKeyword */ || token() === 77 /* ConstKeyword */) { + initializer = parseVariableDeclarationList(/*inForStatementInitializer*/ true); + } + else { + initializer = disallowInAnd(parseExpression); + } + } + var forOrForInOrForOfStatement; + if (awaitToken ? parseExpected(147 /* OfKeyword */) : parseOptional(147 /* OfKeyword */)) { + var forOfStatement = createNode(227 /* ForOfStatement */, pos); + forOfStatement.awaitModifier = awaitToken; + forOfStatement.initializer = initializer; + forOfStatement.expression = allowInAnd(parseAssignmentExpressionOrHigher); + parseExpected(21 /* CloseParenToken */); + forOrForInOrForOfStatement = forOfStatement; + } + else if (parseOptional(93 /* InKeyword */)) { + var forInStatement = createNode(226 /* ForInStatement */, pos); + forInStatement.initializer = initializer; + forInStatement.expression = allowInAnd(parseExpression); + parseExpected(21 /* CloseParenToken */); + forOrForInOrForOfStatement = forInStatement; + } + else { + var forStatement = createNode(225 /* ForStatement */, pos); + forStatement.initializer = initializer; + parseExpected(26 /* SemicolonToken */); + if (token() !== 26 /* SemicolonToken */ && token() !== 21 /* CloseParenToken */) { + forStatement.condition = allowInAnd(parseExpression); + } + parseExpected(26 /* SemicolonToken */); + if (token() !== 21 /* CloseParenToken */) { + forStatement.incrementor = allowInAnd(parseExpression); + } + parseExpected(21 /* CloseParenToken */); + forOrForInOrForOfStatement = forStatement; + } + forOrForInOrForOfStatement.statement = parseStatement(); + return finishNode(forOrForInOrForOfStatement); + } + function parseBreakOrContinueStatement(kind) { + var node = createNode(kind); + parseExpected(kind === 229 /* BreakStatement */ ? 73 /* BreakKeyword */ : 78 /* ContinueKeyword */); + if (!canParseSemicolon()) { + node.label = parseIdentifier(); + } + parseSemicolon(); + return finishNode(node); + } + function parseReturnStatement() { + var node = createNode(230 /* ReturnStatement */); + parseExpected(97 /* ReturnKeyword */); + if (!canParseSemicolon()) { + node.expression = allowInAnd(parseExpression); + } + parseSemicolon(); + return finishNode(node); + } + function parseWithStatement() { + var node = createNode(231 /* WithStatement */); + parseExpected(108 /* WithKeyword */); + parseExpected(20 /* OpenParenToken */); + node.expression = allowInAnd(parseExpression); + parseExpected(21 /* CloseParenToken */); + node.statement = doInsideOfContext(8388608 /* InWithStatement */, parseStatement); + return finishNode(node); + } + function parseCaseClause() { + var node = createNode(271 /* CaseClause */); + parseExpected(74 /* CaseKeyword */); + node.expression = allowInAnd(parseExpression); + parseExpected(57 /* ColonToken */); + node.statements = parseList(3 /* SwitchClauseStatements */, parseStatement); + return finishNode(node); + } + function parseDefaultClause() { + var node = createNode(272 /* DefaultClause */); + parseExpected(80 /* DefaultKeyword */); + parseExpected(57 /* ColonToken */); + node.statements = parseList(3 /* SwitchClauseStatements */, parseStatement); + return finishNode(node); + } + function parseCaseOrDefaultClause() { + return token() === 74 /* CaseKeyword */ ? parseCaseClause() : parseDefaultClause(); + } + function parseSwitchStatement() { + var node = createNode(232 /* SwitchStatement */); + parseExpected(99 /* SwitchKeyword */); + parseExpected(20 /* OpenParenToken */); + node.expression = allowInAnd(parseExpression); + parseExpected(21 /* CloseParenToken */); + var caseBlock = createNode(246 /* CaseBlock */); + parseExpected(18 /* OpenBraceToken */); + caseBlock.clauses = parseList(2 /* SwitchClauses */, parseCaseOrDefaultClause); + parseExpected(19 /* CloseBraceToken */); + node.caseBlock = finishNode(caseBlock); + return finishNode(node); + } + function parseThrowStatement() { + // ThrowStatement[Yield] : + // throw [no LineTerminator here]Expression[In, ?Yield]; + // Because of automatic semicolon insertion, we need to report error if this + // throw could be terminated with a semicolon. Note: we can't call 'parseExpression' + // directly as that might consume an expression on the following line. + // We just return 'undefined' in that case. The actual error will be reported in the + // grammar walker. + var node = createNode(234 /* ThrowStatement */); + parseExpected(101 /* ThrowKeyword */); + node.expression = scanner.hasPrecedingLineBreak() ? undefined : allowInAnd(parseExpression); + parseSemicolon(); + return finishNode(node); + } + // TODO: Review for error recovery + function parseTryStatement() { + var node = createNode(235 /* TryStatement */); + parseExpected(103 /* TryKeyword */); + node.tryBlock = parseBlock(/*ignoreMissingOpenBrace*/ false); + node.catchClause = token() === 75 /* CatchKeyword */ ? parseCatchClause() : undefined; + // If we don't have a catch clause, then we must have a finally clause. Try to parse + // one out no matter what. + if (!node.catchClause || token() === 88 /* FinallyKeyword */) { + parseExpected(88 /* FinallyKeyword */); + node.finallyBlock = parseBlock(/*ignoreMissingOpenBrace*/ false); + } + return finishNode(node); + } + function parseCatchClause() { + var result = createNode(274 /* CatchClause */); + parseExpected(75 /* CatchKeyword */); + if (parseOptional(20 /* OpenParenToken */)) { + result.variableDeclaration = parseVariableDeclaration(); + parseExpected(21 /* CloseParenToken */); + } + else { + // Keep shape of node to avoid degrading performance. + result.variableDeclaration = undefined; + } + result.block = parseBlock(/*ignoreMissingOpenBrace*/ false); + return finishNode(result); + } + function parseDebuggerStatement() { + var node = createNode(236 /* DebuggerStatement */); + parseExpected(79 /* DebuggerKeyword */); + parseSemicolon(); + return finishNode(node); + } + function parseExpressionOrLabeledStatement() { + // Avoiding having to do the lookahead for a labeled statement by just trying to parse + // out an expression, seeing if it is identifier and then seeing if it is followed by + // a colon. + var node = createNodeWithJSDoc(0 /* Unknown */); + var expression = allowInAnd(parseExpression); + if (expression.kind === 72 /* Identifier */ && parseOptional(57 /* ColonToken */)) { + node.kind = 233 /* LabeledStatement */; + node.label = expression; + node.statement = parseStatement(); + } + else { + node.kind = 221 /* ExpressionStatement */; + node.expression = expression; + parseSemicolon(); + } + return finishNode(node); + } + function nextTokenIsIdentifierOrKeywordOnSameLine() { + nextToken(); + return ts.tokenIsIdentifierOrKeyword(token()) && !scanner.hasPrecedingLineBreak(); + } + function nextTokenIsClassKeywordOnSameLine() { + nextToken(); + return token() === 76 /* ClassKeyword */ && !scanner.hasPrecedingLineBreak(); + } + function nextTokenIsFunctionKeywordOnSameLine() { + nextToken(); + return token() === 90 /* FunctionKeyword */ && !scanner.hasPrecedingLineBreak(); + } + function nextTokenIsIdentifierOrKeywordOrLiteralOnSameLine() { + nextToken(); + return (ts.tokenIsIdentifierOrKeyword(token()) || token() === 8 /* NumericLiteral */ || token() === 9 /* BigIntLiteral */ || token() === 10 /* StringLiteral */) && !scanner.hasPrecedingLineBreak(); + } + function isDeclaration() { + while (true) { + switch (token()) { + case 105 /* VarKeyword */: + case 111 /* LetKeyword */: + case 77 /* ConstKeyword */: + case 90 /* FunctionKeyword */: + case 76 /* ClassKeyword */: + case 84 /* EnumKeyword */: + return true; + // 'declare', 'module', 'namespace', 'interface'* and 'type' are all legal JavaScript identifiers; + // however, an identifier cannot be followed by another identifier on the same line. This is what we + // count on to parse out the respective declarations. For instance, we exploit this to say that + // + // namespace n + // + // can be none other than the beginning of a namespace declaration, but need to respect that JavaScript sees + // + // namespace + // n + // + // as the identifier 'namespace' on one line followed by the identifier 'n' on another. + // We need to look one token ahead to see if it permissible to try parsing a declaration. + // + // *Note*: 'interface' is actually a strict mode reserved word. So while + // + // "use strict" + // interface + // I {} + // + // could be legal, it would add complexity for very little gain. + case 110 /* InterfaceKeyword */: + case 140 /* TypeKeyword */: + return nextTokenIsIdentifierOnSameLine(); + case 130 /* ModuleKeyword */: + case 131 /* NamespaceKeyword */: + return nextTokenIsIdentifierOrStringLiteralOnSameLine(); + case 118 /* AbstractKeyword */: + case 121 /* AsyncKeyword */: + case 125 /* DeclareKeyword */: + case 113 /* PrivateKeyword */: + case 114 /* ProtectedKeyword */: + case 115 /* PublicKeyword */: + case 133 /* ReadonlyKeyword */: + nextToken(); + // ASI takes effect for this modifier. + if (scanner.hasPrecedingLineBreak()) { + return false; + } + continue; + case 145 /* GlobalKeyword */: + nextToken(); + return token() === 18 /* OpenBraceToken */ || token() === 72 /* Identifier */ || token() === 85 /* ExportKeyword */; + case 92 /* ImportKeyword */: + nextToken(); + return token() === 10 /* StringLiteral */ || token() === 40 /* AsteriskToken */ || + token() === 18 /* OpenBraceToken */ || ts.tokenIsIdentifierOrKeyword(token()); + case 85 /* ExportKeyword */: + nextToken(); + if (token() === 59 /* EqualsToken */ || token() === 40 /* AsteriskToken */ || + token() === 18 /* OpenBraceToken */ || token() === 80 /* DefaultKeyword */ || + token() === 119 /* AsKeyword */) { + return true; + } + continue; + case 116 /* StaticKeyword */: + nextToken(); + continue; + default: + return false; + } + } + } + function isStartOfDeclaration() { + return lookAhead(isDeclaration); + } + function isStartOfStatement() { + switch (token()) { + case 58 /* AtToken */: + case 26 /* SemicolonToken */: + case 18 /* OpenBraceToken */: + case 105 /* VarKeyword */: + case 111 /* LetKeyword */: + case 90 /* FunctionKeyword */: + case 76 /* ClassKeyword */: + case 84 /* EnumKeyword */: + case 91 /* IfKeyword */: + case 82 /* DoKeyword */: + case 107 /* WhileKeyword */: + case 89 /* ForKeyword */: + case 78 /* ContinueKeyword */: + case 73 /* BreakKeyword */: + case 97 /* ReturnKeyword */: + case 108 /* WithKeyword */: + case 99 /* SwitchKeyword */: + case 101 /* ThrowKeyword */: + case 103 /* TryKeyword */: + case 79 /* DebuggerKeyword */: + // 'catch' and 'finally' do not actually indicate that the code is part of a statement, + // however, we say they are here so that we may gracefully parse them and error later. + case 75 /* CatchKeyword */: + case 88 /* FinallyKeyword */: + return true; + case 92 /* ImportKeyword */: + return isStartOfDeclaration() || lookAhead(nextTokenIsOpenParenOrLessThanOrDot); + case 77 /* ConstKeyword */: + case 85 /* ExportKeyword */: + return isStartOfDeclaration(); + case 121 /* AsyncKeyword */: + case 125 /* DeclareKeyword */: + case 110 /* InterfaceKeyword */: + case 130 /* ModuleKeyword */: + case 131 /* NamespaceKeyword */: + case 140 /* TypeKeyword */: + case 145 /* GlobalKeyword */: + // When these don't start a declaration, they're an identifier in an expression statement + return true; + case 115 /* PublicKeyword */: + case 113 /* PrivateKeyword */: + case 114 /* ProtectedKeyword */: + case 116 /* StaticKeyword */: + case 133 /* ReadonlyKeyword */: + // When these don't start a declaration, they may be the start of a class member if an identifier + // immediately follows. Otherwise they're an identifier in an expression statement. + return isStartOfDeclaration() || !lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine); + default: + return isStartOfExpression(); + } + } + function nextTokenIsIdentifierOrStartOfDestructuring() { + nextToken(); + return isIdentifier() || token() === 18 /* OpenBraceToken */ || token() === 22 /* OpenBracketToken */; + } + function isLetDeclaration() { + // In ES6 'let' always starts a lexical declaration if followed by an identifier or { + // or [. + return lookAhead(nextTokenIsIdentifierOrStartOfDestructuring); + } + function parseStatement() { + switch (token()) { + case 26 /* SemicolonToken */: + return parseEmptyStatement(); + case 18 /* OpenBraceToken */: + return parseBlock(/*ignoreMissingOpenBrace*/ false); + case 105 /* VarKeyword */: + return parseVariableStatement(createNodeWithJSDoc(237 /* VariableDeclaration */)); + case 111 /* LetKeyword */: + if (isLetDeclaration()) { + return parseVariableStatement(createNodeWithJSDoc(237 /* VariableDeclaration */)); + } + break; + case 90 /* FunctionKeyword */: + return parseFunctionDeclaration(createNodeWithJSDoc(239 /* FunctionDeclaration */)); + case 76 /* ClassKeyword */: + return parseClassDeclaration(createNodeWithJSDoc(240 /* ClassDeclaration */)); + case 91 /* IfKeyword */: + return parseIfStatement(); + case 82 /* DoKeyword */: + return parseDoStatement(); + case 107 /* WhileKeyword */: + return parseWhileStatement(); + case 89 /* ForKeyword */: + return parseForOrForInOrForOfStatement(); + case 78 /* ContinueKeyword */: + return parseBreakOrContinueStatement(228 /* ContinueStatement */); + case 73 /* BreakKeyword */: + return parseBreakOrContinueStatement(229 /* BreakStatement */); + case 97 /* ReturnKeyword */: + return parseReturnStatement(); + case 108 /* WithKeyword */: + return parseWithStatement(); + case 99 /* SwitchKeyword */: + return parseSwitchStatement(); + case 101 /* ThrowKeyword */: + return parseThrowStatement(); + case 103 /* TryKeyword */: + // Include 'catch' and 'finally' for error recovery. + case 75 /* CatchKeyword */: + case 88 /* FinallyKeyword */: + return parseTryStatement(); + case 79 /* DebuggerKeyword */: + return parseDebuggerStatement(); + case 58 /* AtToken */: + return parseDeclaration(); + case 121 /* AsyncKeyword */: + case 110 /* InterfaceKeyword */: + case 140 /* TypeKeyword */: + case 130 /* ModuleKeyword */: + case 131 /* NamespaceKeyword */: + case 125 /* DeclareKeyword */: + case 77 /* ConstKeyword */: + case 84 /* EnumKeyword */: + case 85 /* ExportKeyword */: + case 92 /* ImportKeyword */: + case 113 /* PrivateKeyword */: + case 114 /* ProtectedKeyword */: + case 115 /* PublicKeyword */: + case 118 /* AbstractKeyword */: + case 116 /* StaticKeyword */: + case 133 /* ReadonlyKeyword */: + case 145 /* GlobalKeyword */: + if (isStartOfDeclaration()) { + return parseDeclaration(); + } + break; + } + return parseExpressionOrLabeledStatement(); + } + function isDeclareModifier(modifier) { + return modifier.kind === 125 /* DeclareKeyword */; + } + function parseDeclaration() { + var node = createNodeWithJSDoc(0 /* Unknown */); + node.decorators = parseDecorators(); + node.modifiers = parseModifiers(); + if (ts.some(node.modifiers, isDeclareModifier)) { + for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) { + var m = _a[_i]; + m.flags |= 4194304 /* Ambient */; + } + return doInsideOfContext(4194304 /* Ambient */, function () { return parseDeclarationWorker(node); }); + } + else { + return parseDeclarationWorker(node); + } + } + function parseDeclarationWorker(node) { + switch (token()) { + case 105 /* VarKeyword */: + case 111 /* LetKeyword */: + case 77 /* ConstKeyword */: + return parseVariableStatement(node); + case 90 /* FunctionKeyword */: + return parseFunctionDeclaration(node); + case 76 /* ClassKeyword */: + return parseClassDeclaration(node); + case 110 /* InterfaceKeyword */: + return parseInterfaceDeclaration(node); + case 140 /* TypeKeyword */: + return parseTypeAliasDeclaration(node); + case 84 /* EnumKeyword */: + return parseEnumDeclaration(node); + case 145 /* GlobalKeyword */: + case 130 /* ModuleKeyword */: + case 131 /* NamespaceKeyword */: + return parseModuleDeclaration(node); + case 92 /* ImportKeyword */: + return parseImportDeclarationOrImportEqualsDeclaration(node); + case 85 /* ExportKeyword */: + nextToken(); + switch (token()) { + case 80 /* DefaultKeyword */: + case 59 /* EqualsToken */: + return parseExportAssignment(node); + case 119 /* AsKeyword */: + return parseNamespaceExportDeclaration(node); + default: + return parseExportDeclaration(node); + } + default: + if (node.decorators || node.modifiers) { + // We reached this point because we encountered decorators and/or modifiers and assumed a declaration + // would follow. For recovery and error reporting purposes, return an incomplete declaration. + var missing = createMissingNode(258 /* MissingDeclaration */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected); + missing.pos = node.pos; + missing.decorators = node.decorators; + missing.modifiers = node.modifiers; + return finishNode(missing); + } + return undefined; // TODO: GH#18217 + } + } + function nextTokenIsIdentifierOrStringLiteralOnSameLine() { + nextToken(); + return !scanner.hasPrecedingLineBreak() && (isIdentifier() || token() === 10 /* StringLiteral */); + } + function parseFunctionBlockOrSemicolon(flags, diagnosticMessage) { + if (token() !== 18 /* OpenBraceToken */ && canParseSemicolon()) { + parseSemicolon(); + return; + } + return parseFunctionBlock(flags, diagnosticMessage); + } + // DECLARATIONS + function parseArrayBindingElement() { + if (token() === 27 /* CommaToken */) { + return createNode(210 /* OmittedExpression */); + } + var node = createNode(186 /* BindingElement */); + node.dotDotDotToken = parseOptionalToken(25 /* DotDotDotToken */); + node.name = parseIdentifierOrPattern(); + node.initializer = parseInitializer(); + return finishNode(node); + } + function parseObjectBindingElement() { + var node = createNode(186 /* BindingElement */); + node.dotDotDotToken = parseOptionalToken(25 /* DotDotDotToken */); + var tokenIsIdentifier = isIdentifier(); + var propertyName = parsePropertyName(); + if (tokenIsIdentifier && token() !== 57 /* ColonToken */) { + node.name = propertyName; + } + else { + parseExpected(57 /* ColonToken */); + node.propertyName = propertyName; + node.name = parseIdentifierOrPattern(); + } + node.initializer = parseInitializer(); + return finishNode(node); + } + function parseObjectBindingPattern() { + var node = createNode(184 /* ObjectBindingPattern */); + parseExpected(18 /* OpenBraceToken */); + node.elements = parseDelimitedList(9 /* ObjectBindingElements */, parseObjectBindingElement); + parseExpected(19 /* CloseBraceToken */); + return finishNode(node); + } + function parseArrayBindingPattern() { + var node = createNode(185 /* ArrayBindingPattern */); + parseExpected(22 /* OpenBracketToken */); + node.elements = parseDelimitedList(10 /* ArrayBindingElements */, parseArrayBindingElement); + parseExpected(23 /* CloseBracketToken */); + return finishNode(node); + } + function isIdentifierOrPattern() { + return token() === 18 /* OpenBraceToken */ || token() === 22 /* OpenBracketToken */ || isIdentifier(); + } + function parseIdentifierOrPattern() { + if (token() === 22 /* OpenBracketToken */) { + return parseArrayBindingPattern(); + } + if (token() === 18 /* OpenBraceToken */) { + return parseObjectBindingPattern(); + } + return parseIdentifier(); + } + function parseVariableDeclarationAllowExclamation() { + return parseVariableDeclaration(/*allowExclamation*/ true); + } + function parseVariableDeclaration(allowExclamation) { + var node = createNode(237 /* VariableDeclaration */); + node.name = parseIdentifierOrPattern(); + if (allowExclamation && node.name.kind === 72 /* Identifier */ && + token() === 52 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) { + node.exclamationToken = parseTokenNode(); + } + node.type = parseTypeAnnotation(); + if (!isInOrOfKeyword(token())) { + node.initializer = parseInitializer(); + } + return finishNode(node); + } + function parseVariableDeclarationList(inForStatementInitializer) { + var node = createNode(238 /* VariableDeclarationList */); + switch (token()) { + case 105 /* VarKeyword */: + break; + case 111 /* LetKeyword */: + node.flags |= 1 /* Let */; + break; + case 77 /* ConstKeyword */: + node.flags |= 2 /* Const */; + break; + default: + ts.Debug.fail(); + } + nextToken(); + // The user may have written the following: + // + // for (let of X) { } + // + // In this case, we want to parse an empty declaration list, and then parse 'of' + // as a keyword. The reason this is not automatic is that 'of' is a valid identifier. + // So we need to look ahead to determine if 'of' should be treated as a keyword in + // this context. + // The checker will then give an error that there is an empty declaration list. + if (token() === 147 /* OfKeyword */ && lookAhead(canFollowContextualOfKeyword)) { + node.declarations = createMissingList(); + } + else { + var savedDisallowIn = inDisallowInContext(); + setDisallowInContext(inForStatementInitializer); + node.declarations = parseDelimitedList(8 /* VariableDeclarations */, inForStatementInitializer ? parseVariableDeclaration : parseVariableDeclarationAllowExclamation); + setDisallowInContext(savedDisallowIn); + } + return finishNode(node); + } + function canFollowContextualOfKeyword() { + return nextTokenIsIdentifier() && nextToken() === 21 /* CloseParenToken */; + } + function parseVariableStatement(node) { + node.kind = 219 /* VariableStatement */; + node.declarationList = parseVariableDeclarationList(/*inForStatementInitializer*/ false); + parseSemicolon(); + return finishNode(node); + } + function parseFunctionDeclaration(node) { + node.kind = 239 /* FunctionDeclaration */; + parseExpected(90 /* FunctionKeyword */); + node.asteriskToken = parseOptionalToken(40 /* AsteriskToken */); + node.name = ts.hasModifier(node, 512 /* Default */) ? parseOptionalIdentifier() : parseIdentifier(); + var isGenerator = node.asteriskToken ? 1 /* Yield */ : 0 /* None */; + var isAsync = ts.hasModifier(node, 256 /* Async */) ? 2 /* Await */ : 0 /* None */; + fillSignature(57 /* ColonToken */, isGenerator | isAsync, node); + node.body = parseFunctionBlockOrSemicolon(isGenerator | isAsync, ts.Diagnostics.or_expected); + return finishNode(node); + } + function parseConstructorDeclaration(node) { + node.kind = 157 /* Constructor */; + parseExpected(124 /* ConstructorKeyword */); + fillSignature(57 /* ColonToken */, 0 /* None */, node); + node.body = parseFunctionBlockOrSemicolon(0 /* None */, ts.Diagnostics.or_expected); + return finishNode(node); + } + function parseMethodDeclaration(node, asteriskToken, diagnosticMessage) { + node.kind = 156 /* MethodDeclaration */; + node.asteriskToken = asteriskToken; + var isGenerator = asteriskToken ? 1 /* Yield */ : 0 /* None */; + var isAsync = ts.hasModifier(node, 256 /* Async */) ? 2 /* Await */ : 0 /* None */; + fillSignature(57 /* ColonToken */, isGenerator | isAsync, node); + node.body = parseFunctionBlockOrSemicolon(isGenerator | isAsync, diagnosticMessage); + return finishNode(node); + } + function parsePropertyDeclaration(node) { + node.kind = 154 /* PropertyDeclaration */; + if (!node.questionToken && token() === 52 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) { + node.exclamationToken = parseTokenNode(); + } + node.type = parseTypeAnnotation(); + // For instance properties specifically, since they are evaluated inside the constructor, + // we do *not * want to parse yield expressions, so we specifically turn the yield context + // off. The grammar would look something like this: + // + // MemberVariableDeclaration[Yield]: + // AccessibilityModifier_opt PropertyName TypeAnnotation_opt Initializer_opt[In]; + // AccessibilityModifier_opt static_opt PropertyName TypeAnnotation_opt Initializer_opt[In, ?Yield]; + // + // The checker may still error in the static case to explicitly disallow the yield expression. + node.initializer = ts.hasModifier(node, 32 /* Static */) + ? allowInAnd(parseInitializer) + : doOutsideOfContext(4096 /* YieldContext */ | 2048 /* DisallowInContext */, parseInitializer); + parseSemicolon(); + return finishNode(node); + } + function parsePropertyOrMethodDeclaration(node) { + var asteriskToken = parseOptionalToken(40 /* AsteriskToken */); + node.name = parsePropertyName(); + // Note: this is not legal as per the grammar. But we allow it in the parser and + // report an error in the grammar checker. + node.questionToken = parseOptionalToken(56 /* QuestionToken */); + if (asteriskToken || token() === 20 /* OpenParenToken */ || token() === 28 /* LessThanToken */) { + return parseMethodDeclaration(node, asteriskToken, ts.Diagnostics.or_expected); + } + return parsePropertyDeclaration(node); + } + function parseAccessorDeclaration(node, kind) { + node.kind = kind; + node.name = parsePropertyName(); + fillSignature(57 /* ColonToken */, 0 /* None */, node); + node.body = parseFunctionBlockOrSemicolon(0 /* None */); + return finishNode(node); + } + function isClassMemberStart() { + var idToken; + if (token() === 58 /* AtToken */) { + return true; + } + // Eat up all modifiers, but hold on to the last one in case it is actually an identifier. + while (ts.isModifierKind(token())) { + idToken = token(); + // If the idToken is a class modifier (protected, private, public, and static), it is + // certain that we are starting to parse class member. This allows better error recovery + // Example: + // public foo() ... // true + // public @dec blah ... // true; we will then report an error later + // export public ... // true; we will then report an error later + if (ts.isClassMemberModifier(idToken)) { + return true; + } + nextToken(); + } + if (token() === 40 /* AsteriskToken */) { + return true; + } + // Try to get the first property-like token following all modifiers. + // This can either be an identifier or the 'get' or 'set' keywords. + if (isLiteralPropertyName()) { + idToken = token(); + nextToken(); + } + // Index signatures and computed properties are class members; we can parse. + if (token() === 22 /* OpenBracketToken */) { + return true; + } + // If we were able to get any potential identifier... + if (idToken !== undefined) { + // If we have a non-keyword identifier, or if we have an accessor, then it's safe to parse. + if (!ts.isKeyword(idToken) || idToken === 137 /* SetKeyword */ || idToken === 126 /* GetKeyword */) { + return true; + } + // If it *is* a keyword, but not an accessor, check a little farther along + // to see if it should actually be parsed as a class member. + switch (token()) { + case 20 /* OpenParenToken */: // Method declaration + case 28 /* LessThanToken */: // Generic Method declaration + case 52 /* ExclamationToken */: // Non-null assertion on property name + case 57 /* ColonToken */: // Type Annotation for declaration + case 59 /* EqualsToken */: // Initializer for declaration + case 56 /* QuestionToken */: // Not valid, but permitted so that it gets caught later on. + return true; + default: + // Covers + // - Semicolons (declaration termination) + // - Closing braces (end-of-class, must be declaration) + // - End-of-files (not valid, but permitted so that it gets caught later on) + // - Line-breaks (enabling *automatic semicolon insertion*) + return canParseSemicolon(); + } + } + return false; + } + function parseDecorators() { + var list; + var listPos = getNodePos(); + while (true) { + var decoratorStart = getNodePos(); + if (!parseOptional(58 /* AtToken */)) { + break; + } + var decorator = createNode(152 /* Decorator */, decoratorStart); + decorator.expression = doInDecoratorContext(parseLeftHandSideExpressionOrHigher); + finishNode(decorator); + (list || (list = [])).push(decorator); + } + return list && createNodeArray(list, listPos); + } + /* + * There are situations in which a modifier like 'const' will appear unexpectedly, such as on a class member. + * In those situations, if we are entirely sure that 'const' is not valid on its own (such as when ASI takes effect + * and turns it into a standalone declaration), then it is better to parse it and report an error later. + * + * In such situations, 'permitInvalidConstAsModifier' should be set to true. + */ + function parseModifiers(permitInvalidConstAsModifier) { + var list; + var listPos = getNodePos(); + while (true) { + var modifierStart = scanner.getStartPos(); + var modifierKind = token(); + if (token() === 77 /* ConstKeyword */ && permitInvalidConstAsModifier) { + // We need to ensure that any subsequent modifiers appear on the same line + // so that when 'const' is a standalone declaration, we don't issue an error. + if (!tryParse(nextTokenIsOnSameLineAndCanFollowModifier)) { + break; + } + } + else { + if (!parseAnyContextualModifier()) { + break; + } + } + var modifier = finishNode(createNode(modifierKind, modifierStart)); + (list || (list = [])).push(modifier); + } + return list && createNodeArray(list, listPos); + } + function parseModifiersForArrowFunction() { + var modifiers; + if (token() === 121 /* AsyncKeyword */) { + var modifierStart = scanner.getStartPos(); + var modifierKind = token(); + nextToken(); + var modifier = finishNode(createNode(modifierKind, modifierStart)); + modifiers = createNodeArray([modifier], modifierStart); + } + return modifiers; + } + function parseClassElement() { + if (token() === 26 /* SemicolonToken */) { + var result = createNode(217 /* SemicolonClassElement */); + nextToken(); + return finishNode(result); + } + var node = createNodeWithJSDoc(0 /* Unknown */); + node.decorators = parseDecorators(); + node.modifiers = parseModifiers(/*permitInvalidConstAsModifier*/ true); + if (parseContextualModifier(126 /* GetKeyword */)) { + return parseAccessorDeclaration(node, 158 /* GetAccessor */); + } + if (parseContextualModifier(137 /* SetKeyword */)) { + return parseAccessorDeclaration(node, 159 /* SetAccessor */); + } + if (token() === 124 /* ConstructorKeyword */) { + return parseConstructorDeclaration(node); + } + if (isIndexSignature()) { + return parseIndexSignatureDeclaration(node); + } + // It is very important that we check this *after* checking indexers because + // the [ token can start an index signature or a computed property name + if (ts.tokenIsIdentifierOrKeyword(token()) || + token() === 10 /* StringLiteral */ || + token() === 8 /* NumericLiteral */ || + token() === 40 /* AsteriskToken */ || + token() === 22 /* OpenBracketToken */) { + return parsePropertyOrMethodDeclaration(node); + } + if (node.decorators || node.modifiers) { + // treat this as a property declaration with a missing name. + node.name = createMissingNode(72 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected); + return parsePropertyDeclaration(node); + } + // 'isClassMemberStart' should have hinted not to attempt parsing. + return ts.Debug.fail("Should not have attempted to parse class member declaration."); + } + function parseClassExpression() { + return parseClassDeclarationOrExpression(createNodeWithJSDoc(0 /* Unknown */), 209 /* ClassExpression */); + } + function parseClassDeclaration(node) { + return parseClassDeclarationOrExpression(node, 240 /* ClassDeclaration */); + } + function parseClassDeclarationOrExpression(node, kind) { + node.kind = kind; + parseExpected(76 /* ClassKeyword */); + node.name = parseNameOfClassDeclarationOrExpression(); + node.typeParameters = parseTypeParameters(); + node.heritageClauses = parseHeritageClauses(); + if (parseExpected(18 /* OpenBraceToken */)) { + // ClassTail[Yield,Await] : (Modified) See 14.5 + // ClassHeritage[?Yield,?Await]opt { ClassBody[?Yield,?Await]opt } + node.members = parseClassMembers(); + parseExpected(19 /* CloseBraceToken */); + } + else { + node.members = createMissingList(); + } + return finishNode(node); + } + function parseNameOfClassDeclarationOrExpression() { + // implements is a future reserved word so + // 'class implements' might mean either + // - class expression with omitted name, 'implements' starts heritage clause + // - class with name 'implements' + // 'isImplementsClause' helps to disambiguate between these two cases + return isIdentifier() && !isImplementsClause() + ? parseIdentifier() + : undefined; + } + function isImplementsClause() { + return token() === 109 /* ImplementsKeyword */ && lookAhead(nextTokenIsIdentifierOrKeyword); + } + function parseHeritageClauses() { + // ClassTail[Yield,Await] : (Modified) See 14.5 + // ClassHeritage[?Yield,?Await]opt { ClassBody[?Yield,?Await]opt } + if (isHeritageClause()) { + return parseList(22 /* HeritageClauses */, parseHeritageClause); + } + return undefined; + } + function parseHeritageClause() { + var tok = token(); + ts.Debug.assert(tok === 86 /* ExtendsKeyword */ || tok === 109 /* ImplementsKeyword */); // isListElement() should ensure this. + var node = createNode(273 /* HeritageClause */); + node.token = tok; + nextToken(); + node.types = parseDelimitedList(7 /* HeritageClauseElement */, parseExpressionWithTypeArguments); + return finishNode(node); + } + function parseExpressionWithTypeArguments() { + var node = createNode(211 /* ExpressionWithTypeArguments */); + node.expression = parseLeftHandSideExpressionOrHigher(); + node.typeArguments = tryParseTypeArguments(); + return finishNode(node); + } + function tryParseTypeArguments() { + return token() === 28 /* LessThanToken */ + ? parseBracketedList(20 /* TypeArguments */, parseType, 28 /* LessThanToken */, 30 /* GreaterThanToken */) + : undefined; + } + function isHeritageClause() { + return token() === 86 /* ExtendsKeyword */ || token() === 109 /* ImplementsKeyword */; + } + function parseClassMembers() { + return parseList(5 /* ClassMembers */, parseClassElement); + } + function parseInterfaceDeclaration(node) { + node.kind = 241 /* InterfaceDeclaration */; + parseExpected(110 /* InterfaceKeyword */); + node.name = parseIdentifier(); + node.typeParameters = parseTypeParameters(); + node.heritageClauses = parseHeritageClauses(); + node.members = parseObjectTypeMembers(); + return finishNode(node); + } + function parseTypeAliasDeclaration(node) { + node.kind = 242 /* TypeAliasDeclaration */; + parseExpected(140 /* TypeKeyword */); + node.name = parseIdentifier(); + node.typeParameters = parseTypeParameters(); + parseExpected(59 /* EqualsToken */); + node.type = parseType(); + parseSemicolon(); + return finishNode(node); + } + // In an ambient declaration, the grammar only allows integer literals as initializers. + // In a non-ambient declaration, the grammar allows uninitialized members only in a + // ConstantEnumMemberSection, which starts at the beginning of an enum declaration + // or any time an integer literal initializer is encountered. + function parseEnumMember() { + var node = createNodeWithJSDoc(278 /* EnumMember */); + node.name = parsePropertyName(); + node.initializer = allowInAnd(parseInitializer); + return finishNode(node); + } + function parseEnumDeclaration(node) { + node.kind = 243 /* EnumDeclaration */; + parseExpected(84 /* EnumKeyword */); + node.name = parseIdentifier(); + if (parseExpected(18 /* OpenBraceToken */)) { + node.members = parseDelimitedList(6 /* EnumMembers */, parseEnumMember); + parseExpected(19 /* CloseBraceToken */); + } + else { + node.members = createMissingList(); + } + return finishNode(node); + } + function parseModuleBlock() { + var node = createNode(245 /* ModuleBlock */); + if (parseExpected(18 /* OpenBraceToken */)) { + node.statements = parseList(1 /* BlockStatements */, parseStatement); + parseExpected(19 /* CloseBraceToken */); + } + else { + node.statements = createMissingList(); + } + return finishNode(node); + } + function parseModuleOrNamespaceDeclaration(node, flags) { + node.kind = 244 /* ModuleDeclaration */; + // If we are parsing a dotted namespace name, we want to + // propagate the 'Namespace' flag across the names if set. + var namespaceFlag = flags & 16 /* Namespace */; + node.flags |= flags; + node.name = parseIdentifier(); + node.body = parseOptional(24 /* DotToken */) + ? parseModuleOrNamespaceDeclaration(createNode(0 /* Unknown */), 4 /* NestedNamespace */ | namespaceFlag) + : parseModuleBlock(); + return finishNode(node); + } + function parseAmbientExternalModuleDeclaration(node) { + node.kind = 244 /* ModuleDeclaration */; + if (token() === 145 /* GlobalKeyword */) { + // parse 'global' as name of global scope augmentation + node.name = parseIdentifier(); + node.flags |= 512 /* GlobalAugmentation */; + } + else { + node.name = parseLiteralNode(); + node.name.text = internIdentifier(node.name.text); + } + if (token() === 18 /* OpenBraceToken */) { + node.body = parseModuleBlock(); + } + else { + parseSemicolon(); + } + return finishNode(node); + } + function parseModuleDeclaration(node) { + var flags = 0; + if (token() === 145 /* GlobalKeyword */) { + // global augmentation + return parseAmbientExternalModuleDeclaration(node); + } + else if (parseOptional(131 /* NamespaceKeyword */)) { + flags |= 16 /* Namespace */; + } + else { + parseExpected(130 /* ModuleKeyword */); + if (token() === 10 /* StringLiteral */) { + return parseAmbientExternalModuleDeclaration(node); + } + } + return parseModuleOrNamespaceDeclaration(node, flags); + } + function isExternalModuleReference() { + return token() === 134 /* RequireKeyword */ && + lookAhead(nextTokenIsOpenParen); + } + function nextTokenIsOpenParen() { + return nextToken() === 20 /* OpenParenToken */; + } + function nextTokenIsSlash() { + return nextToken() === 42 /* SlashToken */; + } + function parseNamespaceExportDeclaration(node) { + node.kind = 247 /* NamespaceExportDeclaration */; + parseExpected(119 /* AsKeyword */); + parseExpected(131 /* NamespaceKeyword */); + node.name = parseIdentifier(); + parseSemicolon(); + return finishNode(node); + } + function parseImportDeclarationOrImportEqualsDeclaration(node) { + parseExpected(92 /* ImportKeyword */); + var afterImportPos = scanner.getStartPos(); + var identifier; + if (isIdentifier()) { + identifier = parseIdentifier(); + if (token() !== 27 /* CommaToken */ && token() !== 144 /* FromKeyword */) { + return parseImportEqualsDeclaration(node, identifier); + } + } + // Import statement + node.kind = 249 /* ImportDeclaration */; + // ImportDeclaration: + // import ImportClause from ModuleSpecifier ; + // import ModuleSpecifier; + if (identifier || // import id + token() === 40 /* AsteriskToken */ || // import * + token() === 18 /* OpenBraceToken */) { // import { + node.importClause = parseImportClause(identifier, afterImportPos); + parseExpected(144 /* FromKeyword */); + } + node.moduleSpecifier = parseModuleSpecifier(); + parseSemicolon(); + return finishNode(node); + } + function parseImportEqualsDeclaration(node, identifier) { + node.kind = 248 /* ImportEqualsDeclaration */; + node.name = identifier; + parseExpected(59 /* EqualsToken */); + node.moduleReference = parseModuleReference(); + parseSemicolon(); + return finishNode(node); + } + function parseImportClause(identifier, fullStart) { + // ImportClause: + // ImportedDefaultBinding + // NameSpaceImport + // NamedImports + // ImportedDefaultBinding, NameSpaceImport + // ImportedDefaultBinding, NamedImports + var importClause = createNode(250 /* ImportClause */, fullStart); + if (identifier) { + // ImportedDefaultBinding: + // ImportedBinding + importClause.name = identifier; + } + // If there was no default import or if there is comma token after default import + // parse namespace or named imports + if (!importClause.name || + parseOptional(27 /* CommaToken */)) { + importClause.namedBindings = token() === 40 /* AsteriskToken */ ? parseNamespaceImport() : parseNamedImportsOrExports(252 /* NamedImports */); + } + return finishNode(importClause); + } + function parseModuleReference() { + return isExternalModuleReference() + ? parseExternalModuleReference() + : parseEntityName(/*allowReservedWords*/ false); + } + function parseExternalModuleReference() { + var node = createNode(259 /* ExternalModuleReference */); + parseExpected(134 /* RequireKeyword */); + parseExpected(20 /* OpenParenToken */); + node.expression = parseModuleSpecifier(); + parseExpected(21 /* CloseParenToken */); + return finishNode(node); + } + function parseModuleSpecifier() { + if (token() === 10 /* StringLiteral */) { + var result = parseLiteralNode(); + result.text = internIdentifier(result.text); + return result; + } + else { + // We allow arbitrary expressions here, even though the grammar only allows string + // literals. We check to ensure that it is only a string literal later in the grammar + // check pass. + return parseExpression(); + } + } + function parseNamespaceImport() { + // NameSpaceImport: + // * as ImportedBinding + var namespaceImport = createNode(251 /* NamespaceImport */); + parseExpected(40 /* AsteriskToken */); + parseExpected(119 /* AsKeyword */); + namespaceImport.name = parseIdentifier(); + return finishNode(namespaceImport); + } + function parseNamedImportsOrExports(kind) { + var node = createNode(kind); + // NamedImports: + // { } + // { ImportsList } + // { ImportsList, } + // ImportsList: + // ImportSpecifier + // ImportsList, ImportSpecifier + node.elements = parseBracketedList(23 /* ImportOrExportSpecifiers */, kind === 252 /* NamedImports */ ? parseImportSpecifier : parseExportSpecifier, 18 /* OpenBraceToken */, 19 /* CloseBraceToken */); + return finishNode(node); + } + function parseExportSpecifier() { + return parseImportOrExportSpecifier(257 /* ExportSpecifier */); + } + function parseImportSpecifier() { + return parseImportOrExportSpecifier(253 /* ImportSpecifier */); + } + function parseImportOrExportSpecifier(kind) { + var node = createNode(kind); + // ImportSpecifier: + // BindingIdentifier + // IdentifierName as BindingIdentifier + // ExportSpecifier: + // IdentifierName + // IdentifierName as IdentifierName + var checkIdentifierIsKeyword = ts.isKeyword(token()) && !isIdentifier(); + var checkIdentifierStart = scanner.getTokenPos(); + var checkIdentifierEnd = scanner.getTextPos(); + var identifierName = parseIdentifierName(); + if (token() === 119 /* AsKeyword */) { + node.propertyName = identifierName; + parseExpected(119 /* AsKeyword */); + checkIdentifierIsKeyword = ts.isKeyword(token()) && !isIdentifier(); + checkIdentifierStart = scanner.getTokenPos(); + checkIdentifierEnd = scanner.getTextPos(); + node.name = parseIdentifierName(); + } + else { + node.name = identifierName; + } + if (kind === 253 /* ImportSpecifier */ && checkIdentifierIsKeyword) { + parseErrorAt(checkIdentifierStart, checkIdentifierEnd, ts.Diagnostics.Identifier_expected); + } + return finishNode(node); + } + function parseExportDeclaration(node) { + node.kind = 255 /* ExportDeclaration */; + if (parseOptional(40 /* AsteriskToken */)) { + parseExpected(144 /* FromKeyword */); + node.moduleSpecifier = parseModuleSpecifier(); + } + else { + node.exportClause = parseNamedImportsOrExports(256 /* NamedExports */); + // It is not uncommon to accidentally omit the 'from' keyword. Additionally, in editing scenarios, + // the 'from' keyword can be parsed as a named export when the export clause is unterminated (i.e. `export { from "moduleName";`) + // If we don't have a 'from' keyword, see if we have a string literal such that ASI won't take effect. + if (token() === 144 /* FromKeyword */ || (token() === 10 /* StringLiteral */ && !scanner.hasPrecedingLineBreak())) { + parseExpected(144 /* FromKeyword */); + node.moduleSpecifier = parseModuleSpecifier(); + } + } + parseSemicolon(); + return finishNode(node); + } + function parseExportAssignment(node) { + node.kind = 254 /* ExportAssignment */; + if (parseOptional(59 /* EqualsToken */)) { + node.isExportEquals = true; + } + else { + parseExpected(80 /* DefaultKeyword */); + } + node.expression = parseAssignmentExpressionOrHigher(); + parseSemicolon(); + return finishNode(node); + } + function setExternalModuleIndicator(sourceFile) { + // Try to use the first top-level import/export when available, then + // fall back to looking for an 'import.meta' somewhere in the tree if necessary. + sourceFile.externalModuleIndicator = + ts.forEach(sourceFile.statements, isAnExternalModuleIndicatorNode) || + getImportMetaIfNecessary(sourceFile); + } + function isAnExternalModuleIndicatorNode(node) { + return ts.hasModifier(node, 1 /* Export */) + || node.kind === 248 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 259 /* ExternalModuleReference */ + || node.kind === 249 /* ImportDeclaration */ + || node.kind === 254 /* ExportAssignment */ + || node.kind === 255 /* ExportDeclaration */ + ? node + : undefined; + } + function getImportMetaIfNecessary(sourceFile) { + return sourceFile.flags & 1048576 /* PossiblyContainsImportMeta */ ? + walkTreeForExternalModuleIndicators(sourceFile) : + undefined; + } + function walkTreeForExternalModuleIndicators(node) { + return isImportMeta(node) ? node : forEachChild(node, walkTreeForExternalModuleIndicators); + } + function isImportMeta(node) { + return ts.isMetaProperty(node) && node.keywordToken === 92 /* ImportKeyword */ && node.name.escapedText === "meta"; + } + var ParsingContext; + (function (ParsingContext) { + ParsingContext[ParsingContext["SourceElements"] = 0] = "SourceElements"; + ParsingContext[ParsingContext["BlockStatements"] = 1] = "BlockStatements"; + ParsingContext[ParsingContext["SwitchClauses"] = 2] = "SwitchClauses"; + ParsingContext[ParsingContext["SwitchClauseStatements"] = 3] = "SwitchClauseStatements"; + ParsingContext[ParsingContext["TypeMembers"] = 4] = "TypeMembers"; + ParsingContext[ParsingContext["ClassMembers"] = 5] = "ClassMembers"; + ParsingContext[ParsingContext["EnumMembers"] = 6] = "EnumMembers"; + ParsingContext[ParsingContext["HeritageClauseElement"] = 7] = "HeritageClauseElement"; + ParsingContext[ParsingContext["VariableDeclarations"] = 8] = "VariableDeclarations"; + ParsingContext[ParsingContext["ObjectBindingElements"] = 9] = "ObjectBindingElements"; + ParsingContext[ParsingContext["ArrayBindingElements"] = 10] = "ArrayBindingElements"; + ParsingContext[ParsingContext["ArgumentExpressions"] = 11] = "ArgumentExpressions"; + ParsingContext[ParsingContext["ObjectLiteralMembers"] = 12] = "ObjectLiteralMembers"; + ParsingContext[ParsingContext["JsxAttributes"] = 13] = "JsxAttributes"; + ParsingContext[ParsingContext["JsxChildren"] = 14] = "JsxChildren"; + ParsingContext[ParsingContext["ArrayLiteralMembers"] = 15] = "ArrayLiteralMembers"; + ParsingContext[ParsingContext["Parameters"] = 16] = "Parameters"; + ParsingContext[ParsingContext["JSDocParameters"] = 17] = "JSDocParameters"; + ParsingContext[ParsingContext["RestProperties"] = 18] = "RestProperties"; + ParsingContext[ParsingContext["TypeParameters"] = 19] = "TypeParameters"; + ParsingContext[ParsingContext["TypeArguments"] = 20] = "TypeArguments"; + ParsingContext[ParsingContext["TupleElementTypes"] = 21] = "TupleElementTypes"; + ParsingContext[ParsingContext["HeritageClauses"] = 22] = "HeritageClauses"; + ParsingContext[ParsingContext["ImportOrExportSpecifiers"] = 23] = "ImportOrExportSpecifiers"; + ParsingContext[ParsingContext["Count"] = 24] = "Count"; // Number of parsing contexts + })(ParsingContext || (ParsingContext = {})); + var Tristate; + (function (Tristate) { + Tristate[Tristate["False"] = 0] = "False"; + Tristate[Tristate["True"] = 1] = "True"; + Tristate[Tristate["Unknown"] = 2] = "Unknown"; + })(Tristate || (Tristate = {})); + var JSDocParser; + (function (JSDocParser) { + function parseJSDocTypeExpressionForTests(content, start, length) { + initializeState(content, 6 /* Latest */, /*_syntaxCursor:*/ undefined, 1 /* JS */); + sourceFile = createSourceFile("file.js", 6 /* Latest */, 1 /* JS */, /*isDeclarationFile*/ false); + scanner.setText(content, start, length); + currentToken = scanner.scan(); + var jsDocTypeExpression = parseJSDocTypeExpression(); + var diagnostics = parseDiagnostics; + clearState(); + return jsDocTypeExpression ? { jsDocTypeExpression: jsDocTypeExpression, diagnostics: diagnostics } : undefined; + } + JSDocParser.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests; + // Parses out a JSDoc type expression. + function parseJSDocTypeExpression(mayOmitBraces) { + var result = createNode(283 /* JSDocTypeExpression */); + var hasBrace = (mayOmitBraces ? parseOptional : parseExpected)(18 /* OpenBraceToken */); + result.type = doInsideOfContext(2097152 /* JSDoc */, parseJSDocType); + if (!mayOmitBraces || hasBrace) { + parseExpected(19 /* CloseBraceToken */); + } + fixupParentReferences(result); + return finishNode(result); + } + JSDocParser.parseJSDocTypeExpression = parseJSDocTypeExpression; + function parseIsolatedJSDocComment(content, start, length) { + initializeState(content, 6 /* Latest */, /*_syntaxCursor:*/ undefined, 1 /* JS */); + sourceFile = { languageVariant: 0 /* Standard */, text: content }; // tslint:disable-line no-object-literal-type-assertion + var jsDoc = parseJSDocCommentWorker(start, length); + var diagnostics = parseDiagnostics; + clearState(); + return jsDoc ? { jsDoc: jsDoc, diagnostics: diagnostics } : undefined; + } + JSDocParser.parseIsolatedJSDocComment = parseIsolatedJSDocComment; + function parseJSDocComment(parent, start, length) { + var _a; + var saveToken = currentToken; + var saveParseDiagnosticsLength = parseDiagnostics.length; + var saveParseErrorBeforeNextFinishedNode = parseErrorBeforeNextFinishedNode; + var comment = parseJSDocCommentWorker(start, length); + if (comment) { + comment.parent = parent; + } + if (contextFlags & 65536 /* JavaScriptFile */) { + if (!sourceFile.jsDocDiagnostics) { + sourceFile.jsDocDiagnostics = []; + } + (_a = sourceFile.jsDocDiagnostics).push.apply(_a, parseDiagnostics); + } + currentToken = saveToken; + parseDiagnostics.length = saveParseDiagnosticsLength; + parseErrorBeforeNextFinishedNode = saveParseErrorBeforeNextFinishedNode; + return comment; + } + JSDocParser.parseJSDocComment = parseJSDocComment; + var JSDocState; + (function (JSDocState) { + JSDocState[JSDocState["BeginningOfLine"] = 0] = "BeginningOfLine"; + JSDocState[JSDocState["SawAsterisk"] = 1] = "SawAsterisk"; + JSDocState[JSDocState["SavingComments"] = 2] = "SavingComments"; + })(JSDocState || (JSDocState = {})); + var PropertyLikeParse; + (function (PropertyLikeParse) { + PropertyLikeParse[PropertyLikeParse["Property"] = 1] = "Property"; + PropertyLikeParse[PropertyLikeParse["Parameter"] = 2] = "Parameter"; + PropertyLikeParse[PropertyLikeParse["CallbackParameter"] = 4] = "CallbackParameter"; + })(PropertyLikeParse || (PropertyLikeParse = {})); + function parseJSDocCommentWorker(start, length) { + if (start === void 0) { start = 0; } + var content = sourceText; + var end = length === undefined ? content.length : start + length; + length = end - start; + ts.Debug.assert(start >= 0); + ts.Debug.assert(start <= end); + ts.Debug.assert(end <= content.length); + // Check for /** (JSDoc opening part) + if (!isJSDocLikeText(content, start)) { + return undefined; + } + var tags; + var tagsPos; + var tagsEnd; + var comments = []; + // + 3 for leading /**, - 5 in total for /** */ + return scanner.scanRange(start + 3, length - 5, function () { + // Initially we can parse out a tag. We also have seen a starting asterisk. + // This is so that /** * @type */ doesn't parse. + var state = 1 /* SawAsterisk */; + var margin; + // + 4 for leading '/** ' + var indent = start - Math.max(content.lastIndexOf("\n", start), 0) + 4; + function pushComment(text) { + if (!margin) { + margin = indent; + } + comments.push(text); + indent += text.length; + } + nextJSDocToken(); + while (parseOptionalJsdoc(5 /* WhitespaceTrivia */)) + ; + if (parseOptionalJsdoc(4 /* NewLineTrivia */)) { + state = 0 /* BeginningOfLine */; + indent = 0; + } + loop: while (true) { + switch (token()) { + case 58 /* AtToken */: + if (state === 0 /* BeginningOfLine */ || state === 1 /* SawAsterisk */) { + removeTrailingWhitespace(comments); + addTag(parseTag(indent)); + // NOTE: According to usejsdoc.org, a tag goes to end of line, except the last tag. + // Real-world comments may break this rule, so "BeginningOfLine" will not be a real line beginning + // for malformed examples like `/** @param {string} x @returns {number} the length */` + state = 0 /* BeginningOfLine */; + margin = undefined; + indent++; + } + else { + pushComment(scanner.getTokenText()); + } + break; + case 4 /* NewLineTrivia */: + comments.push(scanner.getTokenText()); + state = 0 /* BeginningOfLine */; + indent = 0; + break; + case 40 /* AsteriskToken */: + var asterisk = scanner.getTokenText(); + if (state === 1 /* SawAsterisk */ || state === 2 /* SavingComments */) { + // If we've already seen an asterisk, then we can no longer parse a tag on this line + state = 2 /* SavingComments */; + pushComment(asterisk); + } + else { + // Ignore the first asterisk on a line + state = 1 /* SawAsterisk */; + indent += asterisk.length; + } + break; + case 5 /* WhitespaceTrivia */: + // only collect whitespace if we're already saving comments or have just crossed the comment indent margin + var whitespace = scanner.getTokenText(); + if (state === 2 /* SavingComments */) { + comments.push(whitespace); + } + else if (margin !== undefined && indent + whitespace.length > margin) { + comments.push(whitespace.slice(margin - indent - 1)); + } + indent += whitespace.length; + break; + case 1 /* EndOfFileToken */: + break loop; + default: + // Anything else is doc comment text. We just save it. Because it + // wasn't a tag, we can no longer parse a tag on this line until we hit the next + // line break. + state = 2 /* SavingComments */; + pushComment(scanner.getTokenText()); + break; + } + nextJSDocToken(); + } + removeLeadingNewlines(comments); + removeTrailingWhitespace(comments); + return createJSDocComment(); + }); + function removeLeadingNewlines(comments) { + while (comments.length && (comments[0] === "\n" || comments[0] === "\r")) { + comments.shift(); + } + } + function removeTrailingWhitespace(comments) { + while (comments.length && comments[comments.length - 1].trim() === "") { + comments.pop(); + } + } + function createJSDocComment() { + var result = createNode(291 /* JSDocComment */, start); + result.tags = tags && createNodeArray(tags, tagsPos, tagsEnd); + result.comment = comments.length ? comments.join("") : undefined; + return finishNode(result, end); + } + function isNextNonwhitespaceTokenEndOfFile() { + // We must use infinite lookahead, as there could be any number of newlines :( + while (true) { + nextJSDocToken(); + if (token() === 1 /* EndOfFileToken */) { + return true; + } + if (!(token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */)) { + return false; + } + } + } + function skipWhitespace() { + if (token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) { + if (lookAhead(isNextNonwhitespaceTokenEndOfFile)) { + return; // Don't skip whitespace prior to EoF (or end of comment) - that shouldn't be included in any node's range + } + } + while (token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) { + nextJSDocToken(); + } + } + function skipWhitespaceOrAsterisk() { + if (token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) { + if (lookAhead(isNextNonwhitespaceTokenEndOfFile)) { + return; // Don't skip whitespace prior to EoF (or end of comment) - that shouldn't be included in any node's range + } + } + var precedingLineBreak = scanner.hasPrecedingLineBreak(); + while ((precedingLineBreak && token() === 40 /* AsteriskToken */) || token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) { + if (token() === 4 /* NewLineTrivia */) { + precedingLineBreak = true; + } + else if (token() === 40 /* AsteriskToken */) { + precedingLineBreak = false; + } + nextJSDocToken(); + } + } + function parseTag(indent) { + ts.Debug.assert(token() === 58 /* AtToken */); + var start = scanner.getTokenPos(); + nextJSDocToken(); + var tagName = parseJSDocIdentifierName(/*message*/ undefined); + skipWhitespaceOrAsterisk(); + var tag; + switch (tagName.escapedText) { + case "augments": + case "extends": + tag = parseAugmentsTag(start, tagName); + break; + case "class": + case "constructor": + tag = parseClassTag(start, tagName); + break; + case "this": + tag = parseThisTag(start, tagName); + break; + case "enum": + tag = parseEnumTag(start, tagName); + break; + case "arg": + case "argument": + case "param": + return parseParameterOrPropertyTag(start, tagName, 2 /* Parameter */, indent); + case "return": + case "returns": + tag = parseReturnTag(start, tagName); + break; + case "template": + tag = parseTemplateTag(start, tagName); + break; + case "type": + tag = parseTypeTag(start, tagName); + break; + case "typedef": + tag = parseTypedefTag(start, tagName, indent); + break; + case "callback": + tag = parseCallbackTag(start, tagName, indent); + break; + default: + tag = parseUnknownTag(start, tagName); + break; + } + if (!tag.comment) { + // some tags, like typedef and callback, have already parsed their comments earlier + tag.comment = parseTagComments(indent + tag.end - tag.pos); + } + return tag; + } + function parseTagComments(indent) { + var comments = []; + var state = 0 /* BeginningOfLine */; + var margin; + function pushComment(text) { + if (!margin) { + margin = indent; + } + comments.push(text); + indent += text.length; + } + var tok = token(); + loop: while (true) { + switch (tok) { + case 4 /* NewLineTrivia */: + if (state >= 1 /* SawAsterisk */) { + state = 0 /* BeginningOfLine */; + comments.push(scanner.getTokenText()); + } + indent = 0; + break; + case 58 /* AtToken */: + scanner.setTextPos(scanner.getTextPos() - 1); + // falls through + case 1 /* EndOfFileToken */: + // Done + break loop; + case 5 /* WhitespaceTrivia */: + if (state === 2 /* SavingComments */) { + pushComment(scanner.getTokenText()); + } + else { + var whitespace = scanner.getTokenText(); + // if the whitespace crosses the margin, take only the whitespace that passes the margin + if (margin !== undefined && indent + whitespace.length > margin) { + comments.push(whitespace.slice(margin - indent - 1)); + } + indent += whitespace.length; + } + break; + case 18 /* OpenBraceToken */: + state = 2 /* SavingComments */; + if (lookAhead(function () { return nextJSDocToken() === 58 /* AtToken */ && ts.tokenIsIdentifierOrKeyword(nextJSDocToken()) && scanner.getTokenText() === "link"; })) { + pushComment(scanner.getTokenText()); + nextJSDocToken(); + pushComment(scanner.getTokenText()); + nextJSDocToken(); + } + pushComment(scanner.getTokenText()); + break; + case 40 /* AsteriskToken */: + if (state === 0 /* BeginningOfLine */) { + // leading asterisks start recording on the *next* (non-whitespace) token + state = 1 /* SawAsterisk */; + indent += 1; + break; + } + // record the * as a comment + // falls through + default: + state = 2 /* SavingComments */; // leading identifiers start recording as well + pushComment(scanner.getTokenText()); + break; + } + tok = nextJSDocToken(); + } + removeLeadingNewlines(comments); + removeTrailingWhitespace(comments); + return comments.length === 0 ? undefined : comments.join(""); + } + function parseUnknownTag(start, tagName) { + var result = createNode(294 /* JSDocTag */, start); + result.tagName = tagName; + return finishNode(result); + } + function addTag(tag) { + if (!tag) { + return; + } + if (!tags) { + tags = [tag]; + tagsPos = tag.pos; + } + else { + tags.push(tag); + } + tagsEnd = tag.end; + } + function tryParseTypeExpression() { + skipWhitespaceOrAsterisk(); + return token() === 18 /* OpenBraceToken */ ? parseJSDocTypeExpression() : undefined; + } + function parseBracketNameInPropertyAndParamTag() { + if (token() === 14 /* NoSubstitutionTemplateLiteral */) { + // a markdown-quoted name: `arg` is not legal jsdoc, but occurs in the wild + return { name: createIdentifier(/*isIdentifier*/ true), isBracketed: false }; + } + // Looking for something like '[foo]', 'foo', '[foo.bar]' or 'foo.bar' + var isBracketed = parseOptional(22 /* OpenBracketToken */); + var name = parseJSDocEntityName(); + if (isBracketed) { + skipWhitespace(); + // May have an optional default, e.g. '[foo = 42]' + if (parseOptionalToken(59 /* EqualsToken */)) { + parseExpression(); + } + parseExpected(23 /* CloseBracketToken */); + } + return { name: name, isBracketed: isBracketed }; + } + function isObjectOrObjectArrayTypeReference(node) { + switch (node.kind) { + case 136 /* ObjectKeyword */: + return true; + case 169 /* ArrayType */: + return isObjectOrObjectArrayTypeReference(node.elementType); + default: + return ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) && node.typeName.escapedText === "Object"; + } + } + function parseParameterOrPropertyTag(start, tagName, target, indent) { + var typeExpression = tryParseTypeExpression(); + var isNameFirst = !typeExpression; + skipWhitespaceOrAsterisk(); + var _a = parseBracketNameInPropertyAndParamTag(), name = _a.name, isBracketed = _a.isBracketed; + skipWhitespace(); + if (isNameFirst) { + typeExpression = tryParseTypeExpression(); + } + var result = target === 1 /* Property */ ? + createNode(305 /* JSDocPropertyTag */, start) : + createNode(299 /* JSDocParameterTag */, start); + var comment = parseTagComments(indent + scanner.getStartPos() - start); + var nestedTypeLiteral = target !== 4 /* CallbackParameter */ && parseNestedTypeLiteral(typeExpression, name, target, indent); + if (nestedTypeLiteral) { + typeExpression = nestedTypeLiteral; + isNameFirst = true; + } + result.tagName = tagName; + result.typeExpression = typeExpression; + result.name = name; + result.isNameFirst = isNameFirst; + result.isBracketed = isBracketed; + result.comment = comment; + return finishNode(result); + } + function parseNestedTypeLiteral(typeExpression, name, target, indent) { + if (typeExpression && isObjectOrObjectArrayTypeReference(typeExpression.type)) { + var typeLiteralExpression = createNode(283 /* JSDocTypeExpression */, scanner.getTokenPos()); + var child = void 0; + var jsdocTypeLiteral = void 0; + var start_2 = scanner.getStartPos(); + var children = void 0; + while (child = tryParse(function () { return parseChildParameterOrPropertyTag(target, indent, name); })) { + if (child.kind === 299 /* JSDocParameterTag */ || child.kind === 305 /* JSDocPropertyTag */) { + children = ts.append(children, child); + } + } + if (children) { + jsdocTypeLiteral = createNode(292 /* JSDocTypeLiteral */, start_2); + jsdocTypeLiteral.jsDocPropertyTags = children; + if (typeExpression.type.kind === 169 /* ArrayType */) { + jsdocTypeLiteral.isArrayType = true; + } + typeLiteralExpression.type = finishNode(jsdocTypeLiteral); + return finishNode(typeLiteralExpression); + } + } + } + function parseReturnTag(start, tagName) { + if (ts.forEach(tags, function (t) { return t.kind === 300 /* JSDocReturnTag */; })) { + parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText); + } + var result = createNode(300 /* JSDocReturnTag */, start); + result.tagName = tagName; + result.typeExpression = tryParseTypeExpression(); + return finishNode(result); + } + function parseTypeTag(start, tagName) { + if (ts.forEach(tags, function (t) { return t.kind === 302 /* JSDocTypeTag */; })) { + parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText); + } + var result = createNode(302 /* JSDocTypeTag */, start); + result.tagName = tagName; + result.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true); + return finishNode(result); + } + function parseAugmentsTag(start, tagName) { + var result = createNode(295 /* JSDocAugmentsTag */, start); + result.tagName = tagName; + result.class = parseExpressionWithTypeArgumentsForAugments(); + return finishNode(result); + } + function parseExpressionWithTypeArgumentsForAugments() { + var usedBrace = parseOptional(18 /* OpenBraceToken */); + var node = createNode(211 /* ExpressionWithTypeArguments */); + node.expression = parsePropertyAccessEntityNameExpression(); + node.typeArguments = tryParseTypeArguments(); + var res = finishNode(node); + if (usedBrace) { + parseExpected(19 /* CloseBraceToken */); + } + return res; + } + function parsePropertyAccessEntityNameExpression() { + var node = parseJSDocIdentifierName(); + while (parseOptional(24 /* DotToken */)) { + var prop = createNode(189 /* PropertyAccessExpression */, node.pos); + prop.expression = node; + prop.name = parseJSDocIdentifierName(); + node = finishNode(prop); + } + return node; + } + function parseClassTag(start, tagName) { + var tag = createNode(296 /* JSDocClassTag */, start); + tag.tagName = tagName; + return finishNode(tag); + } + function parseThisTag(start, tagName) { + var tag = createNode(301 /* JSDocThisTag */, start); + tag.tagName = tagName; + tag.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true); + skipWhitespace(); + return finishNode(tag); + } + function parseEnumTag(start, tagName) { + var tag = createNode(298 /* JSDocEnumTag */, start); + tag.tagName = tagName; + tag.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true); + skipWhitespace(); + return finishNode(tag); + } + function parseTypedefTag(start, tagName, indent) { + var typeExpression = tryParseTypeExpression(); + skipWhitespaceOrAsterisk(); + var typedefTag = createNode(304 /* JSDocTypedefTag */, start); + typedefTag.tagName = tagName; + typedefTag.fullName = parseJSDocTypeNameWithNamespace(); + typedefTag.name = getJSDocTypeAliasName(typedefTag.fullName); + skipWhitespace(); + typedefTag.comment = parseTagComments(indent); + typedefTag.typeExpression = typeExpression; + var end; + if (!typeExpression || isObjectOrObjectArrayTypeReference(typeExpression.type)) { + var child = void 0; + var jsdocTypeLiteral = void 0; + var childTypeTag = void 0; + while (child = tryParse(function () { return parseChildPropertyTag(indent); })) { + if (!jsdocTypeLiteral) { + jsdocTypeLiteral = createNode(292 /* JSDocTypeLiteral */, start); + } + if (child.kind === 302 /* JSDocTypeTag */) { + if (childTypeTag) { + break; + } + else { + childTypeTag = child; + } + } + else { + jsdocTypeLiteral.jsDocPropertyTags = ts.append(jsdocTypeLiteral.jsDocPropertyTags, child); + } + } + if (jsdocTypeLiteral) { + if (typeExpression && typeExpression.type.kind === 169 /* ArrayType */) { + jsdocTypeLiteral.isArrayType = true; + } + typedefTag.typeExpression = childTypeTag && childTypeTag.typeExpression && !isObjectOrObjectArrayTypeReference(childTypeTag.typeExpression.type) ? + childTypeTag.typeExpression : + finishNode(jsdocTypeLiteral); + end = typedefTag.typeExpression.end; + } + } + // Only include the characters between the name end and the next token if a comment was actually parsed out - otherwise it's just whitespace + return finishNode(typedefTag, end || typedefTag.comment !== undefined ? scanner.getStartPos() : (typedefTag.fullName || typedefTag.typeExpression || typedefTag.tagName).end); + } + function parseJSDocTypeNameWithNamespace(nested) { + var pos = scanner.getTokenPos(); + if (!ts.tokenIsIdentifierOrKeyword(token())) { + return undefined; + } + var typeNameOrNamespaceName = parseJSDocIdentifierName(); + if (parseOptional(24 /* DotToken */)) { + var jsDocNamespaceNode = createNode(244 /* ModuleDeclaration */, pos); + if (nested) { + jsDocNamespaceNode.flags |= 4 /* NestedNamespace */; + } + jsDocNamespaceNode.name = typeNameOrNamespaceName; + jsDocNamespaceNode.body = parseJSDocTypeNameWithNamespace(/*nested*/ true); + return finishNode(jsDocNamespaceNode); + } + if (nested) { + typeNameOrNamespaceName.isInJSDocNamespace = true; + } + return typeNameOrNamespaceName; + } + function parseCallbackTag(start, tagName, indent) { + var callbackTag = createNode(297 /* JSDocCallbackTag */, start); + callbackTag.tagName = tagName; + callbackTag.fullName = parseJSDocTypeNameWithNamespace(); + callbackTag.name = getJSDocTypeAliasName(callbackTag.fullName); + skipWhitespace(); + callbackTag.comment = parseTagComments(indent); + var child; + var jsdocSignature = createNode(293 /* JSDocSignature */, start); + jsdocSignature.parameters = []; + while (child = tryParse(function () { return parseChildParameterOrPropertyTag(4 /* CallbackParameter */, indent); })) { + jsdocSignature.parameters = ts.append(jsdocSignature.parameters, child); + } + var returnTag = tryParse(function () { + if (parseOptionalJsdoc(58 /* AtToken */)) { + var tag = parseTag(indent); + if (tag && tag.kind === 300 /* JSDocReturnTag */) { + return tag; + } + } + }); + if (returnTag) { + jsdocSignature.type = returnTag; + } + callbackTag.typeExpression = finishNode(jsdocSignature); + return finishNode(callbackTag); + } + function getJSDocTypeAliasName(fullName) { + if (fullName) { + var rightNode = fullName; + while (true) { + if (ts.isIdentifier(rightNode) || !rightNode.body) { + return ts.isIdentifier(rightNode) ? rightNode : rightNode.name; + } + rightNode = rightNode.body; + } + } + } + function escapedTextsEqual(a, b) { + while (!ts.isIdentifier(a) || !ts.isIdentifier(b)) { + if (!ts.isIdentifier(a) && !ts.isIdentifier(b) && a.right.escapedText === b.right.escapedText) { + a = a.left; + b = b.left; + } + else { + return false; + } + } + return a.escapedText === b.escapedText; + } + function parseChildPropertyTag(indent) { + return parseChildParameterOrPropertyTag(1 /* Property */, indent); + } + function parseChildParameterOrPropertyTag(target, indent, name) { + var canParseTag = true; + var seenAsterisk = false; + while (true) { + switch (nextJSDocToken()) { + case 58 /* AtToken */: + if (canParseTag) { + var child = tryParseChildTag(target, indent); + if (child && (child.kind === 299 /* JSDocParameterTag */ || child.kind === 305 /* JSDocPropertyTag */) && + target !== 4 /* CallbackParameter */ && + name && (ts.isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) { + return false; + } + return child; + } + seenAsterisk = false; + break; + case 4 /* NewLineTrivia */: + canParseTag = true; + seenAsterisk = false; + break; + case 40 /* AsteriskToken */: + if (seenAsterisk) { + canParseTag = false; + } + seenAsterisk = true; + break; + case 72 /* Identifier */: + canParseTag = false; + break; + case 1 /* EndOfFileToken */: + return false; + } + } + } + function tryParseChildTag(target, indent) { + ts.Debug.assert(token() === 58 /* AtToken */); + var start = scanner.getStartPos(); + nextJSDocToken(); + var tagName = parseJSDocIdentifierName(); + skipWhitespace(); + var t; + switch (tagName.escapedText) { + case "type": + return target === 1 /* Property */ && parseTypeTag(start, tagName); + case "prop": + case "property": + t = 1 /* Property */; + break; + case "arg": + case "argument": + case "param": + t = 2 /* Parameter */ | 4 /* CallbackParameter */; + break; + default: + return false; + } + if (!(target & t)) { + return false; + } + return parseParameterOrPropertyTag(start, tagName, target, indent); + } + function parseTemplateTag(start, tagName) { + // the template tag looks like '@template {Constraint} T,U,V' + var constraint; + if (token() === 18 /* OpenBraceToken */) { + constraint = parseJSDocTypeExpression(); + } + var typeParameters = []; + var typeParametersPos = getNodePos(); + do { + skipWhitespace(); + var typeParameter = createNode(150 /* TypeParameter */); + typeParameter.name = parseJSDocIdentifierName(ts.Diagnostics.Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces); + finishNode(typeParameter); + skipWhitespace(); + typeParameters.push(typeParameter); + } while (parseOptionalJsdoc(27 /* CommaToken */)); + var result = createNode(303 /* JSDocTemplateTag */, start); + result.tagName = tagName; + result.constraint = constraint; + result.typeParameters = createNodeArray(typeParameters, typeParametersPos); + finishNode(result); + return result; + } + function nextJSDocToken() { + return currentToken = scanner.scanJSDocToken(); + } + function parseOptionalJsdoc(t) { + if (token() === t) { + nextJSDocToken(); + return true; + } + return false; + } + function parseJSDocEntityName() { + var entity = parseJSDocIdentifierName(); + if (parseOptional(22 /* OpenBracketToken */)) { + parseExpected(23 /* CloseBracketToken */); + // Note that y[] is accepted as an entity name, but the postfix brackets are not saved for checking. + // Technically usejsdoc.org requires them for specifying a property of a type equivalent to Array<{ x: ...}> + // but it's not worth it to enforce that restriction. + } + while (parseOptional(24 /* DotToken */)) { + var name = parseJSDocIdentifierName(); + if (parseOptional(22 /* OpenBracketToken */)) { + parseExpected(23 /* CloseBracketToken */); + } + entity = createQualifiedName(entity, name); + } + return entity; + } + function parseJSDocIdentifierName(message) { + if (!ts.tokenIsIdentifierOrKeyword(token())) { + return createMissingNode(72 /* Identifier */, /*reportAtCurrentPosition*/ !message, message || ts.Diagnostics.Identifier_expected); + } + var pos = scanner.getTokenPos(); + var end = scanner.getTextPos(); + var result = createNode(72 /* Identifier */, pos); + result.escapedText = ts.escapeLeadingUnderscores(scanner.getTokenText()); + finishNode(result, end); + nextJSDocToken(); + return result; + } + } + JSDocParser.parseJSDocCommentWorker = parseJSDocCommentWorker; + })(JSDocParser = Parser.JSDocParser || (Parser.JSDocParser = {})); + })(Parser || (Parser = {})); + var IncrementalParser; + (function (IncrementalParser) { + function updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks) { + aggressiveChecks = aggressiveChecks || ts.Debug.shouldAssert(2 /* Aggressive */); + checkChangeRange(sourceFile, newText, textChangeRange, aggressiveChecks); + if (ts.textChangeRangeIsUnchanged(textChangeRange)) { + // if the text didn't change, then we can just return our current source file as-is. + return sourceFile; + } + if (sourceFile.statements.length === 0) { + // If we don't have any statements in the current source file, then there's no real + // way to incrementally parse. So just do a full parse instead. + return Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, /*syntaxCursor*/ undefined, /*setParentNodes*/ true, sourceFile.scriptKind); + } + // Make sure we're not trying to incrementally update a source file more than once. Once + // we do an update the original source file is considered unusable from that point onwards. + // + // This is because we do incremental parsing in-place. i.e. we take nodes from the old + // tree and give them new positions and parents. From that point on, trusting the old + // tree at all is not possible as far too much of it may violate invariants. + var incrementalSourceFile = sourceFile; + ts.Debug.assert(!incrementalSourceFile.hasBeenIncrementallyParsed); + incrementalSourceFile.hasBeenIncrementallyParsed = true; + var oldText = sourceFile.text; + var syntaxCursor = createSyntaxCursor(sourceFile); + // Make the actual change larger so that we know to reparse anything whose lookahead + // might have intersected the change. + var changeRange = extendToAffectedRange(sourceFile, textChangeRange); + checkChangeRange(sourceFile, newText, changeRange, aggressiveChecks); + // Ensure that extending the affected range only moved the start of the change range + // earlier in the file. + ts.Debug.assert(changeRange.span.start <= textChangeRange.span.start); + ts.Debug.assert(ts.textSpanEnd(changeRange.span) === ts.textSpanEnd(textChangeRange.span)); + ts.Debug.assert(ts.textSpanEnd(ts.textChangeRangeNewSpan(changeRange)) === ts.textSpanEnd(ts.textChangeRangeNewSpan(textChangeRange))); + // The is the amount the nodes after the edit range need to be adjusted. It can be + // positive (if the edit added characters), negative (if the edit deleted characters) + // or zero (if this was a pure overwrite with nothing added/removed). + var delta = ts.textChangeRangeNewSpan(changeRange).length - changeRange.span.length; + // If we added or removed characters during the edit, then we need to go and adjust all + // the nodes after the edit. Those nodes may move forward (if we inserted chars) or they + // may move backward (if we deleted chars). + // + // Doing this helps us out in two ways. First, it means that any nodes/tokens we want + // to reuse are already at the appropriate position in the new text. That way when we + // reuse them, we don't have to figure out if they need to be adjusted. Second, it makes + // it very easy to determine if we can reuse a node. If the node's position is at where + // we are in the text, then we can reuse it. Otherwise we can't. If the node's position + // is ahead of us, then we'll need to rescan tokens. If the node's position is behind + // us, then we'll need to skip it or crumble it as appropriate + // + // We will also adjust the positions of nodes that intersect the change range as well. + // By doing this, we ensure that all the positions in the old tree are consistent, not + // just the positions of nodes entirely before/after the change range. By being + // consistent, we can then easily map from positions to nodes in the old tree easily. + // + // Also, mark any syntax elements that intersect the changed span. We know, up front, + // that we cannot reuse these elements. + updateTokenPositionsAndMarkElements(incrementalSourceFile, changeRange.span.start, ts.textSpanEnd(changeRange.span), ts.textSpanEnd(ts.textChangeRangeNewSpan(changeRange)), delta, oldText, newText, aggressiveChecks); + // Now that we've set up our internal incremental state just proceed and parse the + // source file in the normal fashion. When possible the parser will retrieve and + // reuse nodes from the old tree. + // + // Note: passing in 'true' for setNodeParents is very important. When incrementally + // parsing, we will be reusing nodes from the old tree, and placing it into new + // parents. If we don't set the parents now, we'll end up with an observably + // inconsistent tree. Setting the parents on the new tree should be very fast. We + // will immediately bail out of walking any subtrees when we can see that their parents + // are already correct. + var result = Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, syntaxCursor, /*setParentNodes*/ true, sourceFile.scriptKind); + return result; + } + IncrementalParser.updateSourceFile = updateSourceFile; + function moveElementEntirelyPastChangeRange(element, isArray, delta, oldText, newText, aggressiveChecks) { + if (isArray) { + visitArray(element); + } + else { + visitNode(element); + } + return; + function visitNode(node) { + var text = ""; + if (aggressiveChecks && shouldCheckNode(node)) { + text = oldText.substring(node.pos, node.end); + } + // Ditch any existing LS children we may have created. This way we can avoid + // moving them forward. + if (node._children) { + node._children = undefined; + } + node.pos += delta; + node.end += delta; + if (aggressiveChecks && shouldCheckNode(node)) { + ts.Debug.assert(text === newText.substring(node.pos, node.end)); + } + forEachChild(node, visitNode, visitArray); + if (ts.hasJSDocNodes(node)) { + for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { + var jsDocComment = _a[_i]; + visitNode(jsDocComment); + } + } + checkNodePositions(node, aggressiveChecks); + } + function visitArray(array) { + array._children = undefined; + array.pos += delta; + array.end += delta; + for (var _i = 0, array_8 = array; _i < array_8.length; _i++) { + var node = array_8[_i]; + visitNode(node); + } + } + } + function shouldCheckNode(node) { + switch (node.kind) { + case 10 /* StringLiteral */: + case 8 /* NumericLiteral */: + case 72 /* Identifier */: + return true; + } + return false; + } + function adjustIntersectingElement(element, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta) { + ts.Debug.assert(element.end >= changeStart, "Adjusting an element that was entirely before the change range"); + ts.Debug.assert(element.pos <= changeRangeOldEnd, "Adjusting an element that was entirely after the change range"); + ts.Debug.assert(element.pos <= element.end); + // We have an element that intersects the change range in some way. It may have its + // start, or its end (or both) in the changed range. We want to adjust any part + // that intersects such that the final tree is in a consistent state. i.e. all + // children have spans within the span of their parent, and all siblings are ordered + // properly. + // We may need to update both the 'pos' and the 'end' of the element. + // If the 'pos' is before the start of the change, then we don't need to touch it. + // If it isn't, then the 'pos' must be inside the change. How we update it will + // depend if delta is positive or negative. If delta is positive then we have + // something like: + // + // -------------------AAA----------------- + // -------------------BBBCCCCCCC----------------- + // + // In this case, we consider any node that started in the change range to still be + // starting at the same position. + // + // however, if the delta is negative, then we instead have something like this: + // + // -------------------XXXYYYYYYY----------------- + // -------------------ZZZ----------------- + // + // In this case, any element that started in the 'X' range will keep its position. + // However any element that started after that will have their pos adjusted to be + // at the end of the new range. i.e. any node that started in the 'Y' range will + // be adjusted to have their start at the end of the 'Z' range. + // + // The element will keep its position if possible. Or Move backward to the new-end + // if it's in the 'Y' range. + element.pos = Math.min(element.pos, changeRangeNewEnd); + // If the 'end' is after the change range, then we always adjust it by the delta + // amount. However, if the end is in the change range, then how we adjust it + // will depend on if delta is positive or negative. If delta is positive then we + // have something like: + // + // -------------------AAA----------------- + // -------------------BBBCCCCCCC----------------- + // + // In this case, we consider any node that ended inside the change range to keep its + // end position. + // + // however, if the delta is negative, then we instead have something like this: + // + // -------------------XXXYYYYYYY----------------- + // -------------------ZZZ----------------- + // + // In this case, any element that ended in the 'X' range will keep its position. + // However any element that ended after that will have their pos adjusted to be + // at the end of the new range. i.e. any node that ended in the 'Y' range will + // be adjusted to have their end at the end of the 'Z' range. + if (element.end >= changeRangeOldEnd) { + // Element ends after the change range. Always adjust the end pos. + element.end += delta; + } + else { + // Element ends in the change range. The element will keep its position if + // possible. Or Move backward to the new-end if it's in the 'Y' range. + element.end = Math.min(element.end, changeRangeNewEnd); + } + ts.Debug.assert(element.pos <= element.end); + if (element.parent) { + ts.Debug.assert(element.pos >= element.parent.pos); + ts.Debug.assert(element.end <= element.parent.end); + } + } + function checkNodePositions(node, aggressiveChecks) { + if (aggressiveChecks) { + var pos_2 = node.pos; + var visitNode_1 = function (child) { + ts.Debug.assert(child.pos >= pos_2); + pos_2 = child.end; + }; + if (ts.hasJSDocNodes(node)) { + for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { + var jsDocComment = _a[_i]; + visitNode_1(jsDocComment); + } + } + forEachChild(node, visitNode_1); + ts.Debug.assert(pos_2 <= node.end); + } + } + function updateTokenPositionsAndMarkElements(sourceFile, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta, oldText, newText, aggressiveChecks) { + visitNode(sourceFile); + return; + function visitNode(child) { + ts.Debug.assert(child.pos <= child.end); + if (child.pos > changeRangeOldEnd) { + // Node is entirely past the change range. We need to move both its pos and + // end, forward or backward appropriately. + moveElementEntirelyPastChangeRange(child, /*isArray*/ false, delta, oldText, newText, aggressiveChecks); + return; + } + // Check if the element intersects the change range. If it does, then it is not + // reusable. Also, we'll need to recurse to see what constituent portions we may + // be able to use. + var fullEnd = child.end; + if (fullEnd >= changeStart) { + child.intersectsChange = true; + child._children = undefined; + // Adjust the pos or end (or both) of the intersecting element accordingly. + adjustIntersectingElement(child, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta); + forEachChild(child, visitNode, visitArray); + if (ts.hasJSDocNodes(child)) { + for (var _i = 0, _a = child.jsDoc; _i < _a.length; _i++) { + var jsDocComment = _a[_i]; + visitNode(jsDocComment); + } + } + checkNodePositions(child, aggressiveChecks); + return; + } + // Otherwise, the node is entirely before the change range. No need to do anything with it. + ts.Debug.assert(fullEnd < changeStart); + } + function visitArray(array) { + ts.Debug.assert(array.pos <= array.end); + if (array.pos > changeRangeOldEnd) { + // Array is entirely after the change range. We need to move it, and move any of + // its children. + moveElementEntirelyPastChangeRange(array, /*isArray*/ true, delta, oldText, newText, aggressiveChecks); + return; + } + // Check if the element intersects the change range. If it does, then it is not + // reusable. Also, we'll need to recurse to see what constituent portions we may + // be able to use. + var fullEnd = array.end; + if (fullEnd >= changeStart) { + array.intersectsChange = true; + array._children = undefined; + // Adjust the pos or end (or both) of the intersecting array accordingly. + adjustIntersectingElement(array, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta); + for (var _i = 0, array_9 = array; _i < array_9.length; _i++) { + var node = array_9[_i]; + visitNode(node); + } + return; + } + // Otherwise, the array is entirely before the change range. No need to do anything with it. + ts.Debug.assert(fullEnd < changeStart); + } + } + function extendToAffectedRange(sourceFile, changeRange) { + // Consider the following code: + // void foo() { /; } + // + // If the text changes with an insertion of / just before the semicolon then we end up with: + // void foo() { //; } + // + // If we were to just use the changeRange a is, then we would not rescan the { token + // (as it does not intersect the actual original change range). Because an edit may + // change the token touching it, we actually need to look back *at least* one token so + // that the prior token sees that change. + var maxLookahead = 1; + var start = changeRange.span.start; + // the first iteration aligns us with the change start. subsequent iteration move us to + // the left by maxLookahead tokens. We only need to do this as long as we're not at the + // start of the tree. + for (var i = 0; start > 0 && i <= maxLookahead; i++) { + var nearestNode = findNearestNodeStartingBeforeOrAtPosition(sourceFile, start); + ts.Debug.assert(nearestNode.pos <= start); + var position = nearestNode.pos; + start = Math.max(0, position - 1); + } + var finalSpan = ts.createTextSpanFromBounds(start, ts.textSpanEnd(changeRange.span)); + var finalLength = changeRange.newLength + (changeRange.span.start - start); + return ts.createTextChangeRange(finalSpan, finalLength); + } + function findNearestNodeStartingBeforeOrAtPosition(sourceFile, position) { + var bestResult = sourceFile; + var lastNodeEntirelyBeforePosition; + forEachChild(sourceFile, visit); + if (lastNodeEntirelyBeforePosition) { + var lastChildOfLastEntireNodeBeforePosition = getLastDescendant(lastNodeEntirelyBeforePosition); + if (lastChildOfLastEntireNodeBeforePosition.pos > bestResult.pos) { + bestResult = lastChildOfLastEntireNodeBeforePosition; + } + } + return bestResult; + function getLastDescendant(node) { + while (true) { + var lastChild = ts.getLastChild(node); + if (lastChild) { + node = lastChild; + } + else { + return node; + } + } + } + function visit(child) { + if (ts.nodeIsMissing(child)) { + // Missing nodes are effectively invisible to us. We never even consider them + // When trying to find the nearest node before us. + return; + } + // If the child intersects this position, then this node is currently the nearest + // node that starts before the position. + if (child.pos <= position) { + if (child.pos >= bestResult.pos) { + // This node starts before the position, and is closer to the position than + // the previous best node we found. It is now the new best node. + bestResult = child; + } + // Now, the node may overlap the position, or it may end entirely before the + // position. If it overlaps with the position, then either it, or one of its + // children must be the nearest node before the position. So we can just + // recurse into this child to see if we can find something better. + if (position < child.end) { + // The nearest node is either this child, or one of the children inside + // of it. We've already marked this child as the best so far. Recurse + // in case one of the children is better. + forEachChild(child, visit); + // Once we look at the children of this node, then there's no need to + // continue any further. + return true; + } + else { + ts.Debug.assert(child.end <= position); + // The child ends entirely before this position. Say you have the following + // (where $ is the position) + // + // ? $ : <...> <...> + // + // We would want to find the nearest preceding node in "complex expr 2". + // To support that, we keep track of this node, and once we're done searching + // for a best node, we recurse down this node to see if we can find a good + // result in it. + // + // This approach allows us to quickly skip over nodes that are entirely + // before the position, while still allowing us to find any nodes in the + // last one that might be what we want. + lastNodeEntirelyBeforePosition = child; + } + } + else { + ts.Debug.assert(child.pos > position); + // We're now at a node that is entirely past the position we're searching for. + // This node (and all following nodes) could never contribute to the result, + // so just skip them by returning 'true' here. + return true; + } + } + } + function checkChangeRange(sourceFile, newText, textChangeRange, aggressiveChecks) { + var oldText = sourceFile.text; + if (textChangeRange) { + ts.Debug.assert((oldText.length - textChangeRange.span.length + textChangeRange.newLength) === newText.length); + if (aggressiveChecks || ts.Debug.shouldAssert(3 /* VeryAggressive */)) { + var oldTextPrefix = oldText.substr(0, textChangeRange.span.start); + var newTextPrefix = newText.substr(0, textChangeRange.span.start); + ts.Debug.assert(oldTextPrefix === newTextPrefix); + var oldTextSuffix = oldText.substring(ts.textSpanEnd(textChangeRange.span), oldText.length); + var newTextSuffix = newText.substring(ts.textSpanEnd(ts.textChangeRangeNewSpan(textChangeRange)), newText.length); + ts.Debug.assert(oldTextSuffix === newTextSuffix); + } + } + } + function createSyntaxCursor(sourceFile) { + var currentArray = sourceFile.statements; + var currentArrayIndex = 0; + ts.Debug.assert(currentArrayIndex < currentArray.length); + var current = currentArray[currentArrayIndex]; + var lastQueriedPosition = -1 /* Value */; + return { + currentNode: function (position) { + // Only compute the current node if the position is different than the last time + // we were asked. The parser commonly asks for the node at the same position + // twice. Once to know if can read an appropriate list element at a certain point, + // and then to actually read and consume the node. + if (position !== lastQueriedPosition) { + // Much of the time the parser will need the very next node in the array that + // we just returned a node from.So just simply check for that case and move + // forward in the array instead of searching for the node again. + if (current && current.end === position && currentArrayIndex < (currentArray.length - 1)) { + currentArrayIndex++; + current = currentArray[currentArrayIndex]; + } + // If we don't have a node, or the node we have isn't in the right position, + // then try to find a viable node at the position requested. + if (!current || current.pos !== position) { + findHighestListElementThatStartsAtPosition(position); + } + } + // Cache this query so that we don't do any extra work if the parser calls back + // into us. Note: this is very common as the parser will make pairs of calls like + // 'isListElement -> parseListElement'. If we were unable to find a node when + // called with 'isListElement', we don't want to redo the work when parseListElement + // is called immediately after. + lastQueriedPosition = position; + // Either we don'd have a node, or we have a node at the position being asked for. + ts.Debug.assert(!current || current.pos === position); + return current; + } + }; + // Finds the highest element in the tree we can find that starts at the provided position. + // The element must be a direct child of some node list in the tree. This way after we + // return it, we can easily return its next sibling in the list. + function findHighestListElementThatStartsAtPosition(position) { + // Clear out any cached state about the last node we found. + currentArray = undefined; + currentArrayIndex = -1 /* Value */; + current = undefined; + // Recurse into the source file to find the highest node at this position. + forEachChild(sourceFile, visitNode, visitArray); + return; + function visitNode(node) { + if (position >= node.pos && position < node.end) { + // Position was within this node. Keep searching deeper to find the node. + forEachChild(node, visitNode, visitArray); + // don't proceed any further in the search. + return true; + } + // position wasn't in this node, have to keep searching. + return false; + } + function visitArray(array) { + if (position >= array.pos && position < array.end) { + // position was in this array. Search through this array to see if we find a + // viable element. + for (var i = 0; i < array.length; i++) { + var child = array[i]; + if (child) { + if (child.pos === position) { + // Found the right node. We're done. + currentArray = array; + currentArrayIndex = i; + current = child; + return true; + } + else { + if (child.pos < position && position < child.end) { + // Position in somewhere within this child. Search in it and + // stop searching in this array. + forEachChild(child, visitNode, visitArray); + return true; + } + } + } + } + } + // position wasn't in this array, have to keep searching. + return false; + } + } + } + var InvalidPosition; + (function (InvalidPosition) { + InvalidPosition[InvalidPosition["Value"] = -1] = "Value"; + })(InvalidPosition || (InvalidPosition = {})); + })(IncrementalParser || (IncrementalParser = {})); + /** @internal */ + function isDeclarationFileName(fileName) { + return ts.fileExtensionIs(fileName, ".d.ts" /* Dts */); + } + ts.isDeclarationFileName = isDeclarationFileName; + /*@internal*/ + function processCommentPragmas(context, sourceText) { + var triviaScanner = ts.createScanner(context.languageVersion, /*skipTrivia*/ false, 0 /* Standard */, sourceText); + var pragmas = []; + // Keep scanning all the leading trivia in the file until we get to something that + // isn't trivia. Any single line comment will be analyzed to see if it is a + // reference comment. + while (true) { + var kind = triviaScanner.scan(); + if (!ts.isTrivia(kind)) { + break; + } + var range = { + kind: triviaScanner.getToken(), + pos: triviaScanner.getTokenPos(), + end: triviaScanner.getTextPos(), + }; + var comment = sourceText.substring(range.pos, range.end); + extractPragmas(pragmas, range, comment); + } + context.pragmas = ts.createMap(); + for (var _i = 0, pragmas_1 = pragmas; _i < pragmas_1.length; _i++) { + var pragma = pragmas_1[_i]; + if (context.pragmas.has(pragma.name)) { // TODO: GH#18217 + var currentValue = context.pragmas.get(pragma.name); + if (currentValue instanceof Array) { + currentValue.push(pragma.args); + } + else { + context.pragmas.set(pragma.name, [currentValue, pragma.args]); + } + continue; + } + context.pragmas.set(pragma.name, pragma.args); + } + } + ts.processCommentPragmas = processCommentPragmas; + /*@internal*/ + function processPragmasIntoFields(context, reportDiagnostic) { + context.checkJsDirective = undefined; + context.referencedFiles = []; + context.typeReferenceDirectives = []; + context.libReferenceDirectives = []; + context.amdDependencies = []; + context.hasNoDefaultLib = false; + context.pragmas.forEach(function (entryOrList, key) { + // TODO: The below should be strongly type-guarded and not need casts/explicit annotations, since entryOrList is related to + // key and key is constrained to a union; but it's not (see GH#21483 for at least partial fix) :( + switch (key) { + case "reference": { + var referencedFiles_1 = context.referencedFiles; + var typeReferenceDirectives_1 = context.typeReferenceDirectives; + var libReferenceDirectives_1 = context.libReferenceDirectives; + ts.forEach(ts.toArray(entryOrList), function (arg) { + // TODO: GH#18217 + if (arg.arguments["no-default-lib"]) { + context.hasNoDefaultLib = true; + } + else if (arg.arguments.types) { + typeReferenceDirectives_1.push({ pos: arg.arguments.types.pos, end: arg.arguments.types.end, fileName: arg.arguments.types.value }); + } + else if (arg.arguments.lib) { + libReferenceDirectives_1.push({ pos: arg.arguments.lib.pos, end: arg.arguments.lib.end, fileName: arg.arguments.lib.value }); + } + else if (arg.arguments.path) { + referencedFiles_1.push({ pos: arg.arguments.path.pos, end: arg.arguments.path.end, fileName: arg.arguments.path.value }); + } + else { + reportDiagnostic(arg.range.pos, arg.range.end - arg.range.pos, ts.Diagnostics.Invalid_reference_directive_syntax); + } + }); + break; + } + case "amd-dependency": { + context.amdDependencies = ts.map(ts.toArray(entryOrList), function (x) { return ({ name: x.arguments.name, path: x.arguments.path }); }); // TODO: GH#18217 + break; + } + case "amd-module": { + if (entryOrList instanceof Array) { + for (var _i = 0, entryOrList_1 = entryOrList; _i < entryOrList_1.length; _i++) { + var entry = entryOrList_1[_i]; + if (context.moduleName) { + // TODO: It's probably fine to issue this diagnostic on all instances of the pragma + reportDiagnostic(entry.range.pos, entry.range.end - entry.range.pos, ts.Diagnostics.An_AMD_module_cannot_have_multiple_name_assignments); + } + context.moduleName = entry.arguments.name; + } + } + else { + context.moduleName = entryOrList.arguments.name; + } + break; + } + case "ts-nocheck": + case "ts-check": { + // _last_ of either nocheck or check in a file is the "winner" + ts.forEach(ts.toArray(entryOrList), function (entry) { + if (!context.checkJsDirective || entry.range.pos > context.checkJsDirective.pos) { // TODO: GH#18217 + context.checkJsDirective = { + enabled: key === "ts-check", + end: entry.range.end, + pos: entry.range.pos + }; + } + }); + break; + } + case "jsx": return; // Accessed directly + default: ts.Debug.fail("Unhandled pragma kind"); // Can this be made into an assertNever in the future? + } + }); + } + ts.processPragmasIntoFields = processPragmasIntoFields; + var namedArgRegExCache = ts.createMap(); + function getNamedArgRegEx(name) { + if (namedArgRegExCache.has(name)) { + return namedArgRegExCache.get(name); + } + var result = new RegExp("(\\s" + name + "\\s*=\\s*)('|\")(.+?)\\2", "im"); + namedArgRegExCache.set(name, result); + return result; + } + var tripleSlashXMLCommentStartRegEx = /^\/\/\/\s*<(\S+)\s.*?\/>/im; + var singleLinePragmaRegEx = /^\/\/\/?\s*@(\S+)\s*(.*)\s*$/im; + function extractPragmas(pragmas, range, text) { + var tripleSlash = range.kind === 2 /* SingleLineCommentTrivia */ && tripleSlashXMLCommentStartRegEx.exec(text); + if (tripleSlash) { + var name = tripleSlash[1].toLowerCase(); // Technically unsafe cast, but we do it so the below check to make it safe typechecks + var pragma = ts.commentPragmas[name]; + if (!pragma || !(pragma.kind & 1 /* TripleSlashXML */)) { + return; + } + if (pragma.args) { + var argument = {}; + for (var _i = 0, _a = pragma.args; _i < _a.length; _i++) { + var arg = _a[_i]; + var matcher = getNamedArgRegEx(arg.name); + var matchResult = matcher.exec(text); + if (!matchResult && !arg.optional) { + return; // Missing required argument, don't parse + } + else if (matchResult) { + if (arg.captureSpan) { + var startPos = range.pos + matchResult.index + matchResult[1].length + matchResult[2].length; + argument[arg.name] = { + value: matchResult[3], + pos: startPos, + end: startPos + matchResult[3].length + }; + } + else { + argument[arg.name] = matchResult[3]; + } + } + } + pragmas.push({ name: name, args: { arguments: argument, range: range } }); + } + else { + pragmas.push({ name: name, args: { arguments: {}, range: range } }); + } + return; + } + var singleLine = range.kind === 2 /* SingleLineCommentTrivia */ && singleLinePragmaRegEx.exec(text); + if (singleLine) { + return addPragmaForMatch(pragmas, range, 2 /* SingleLine */, singleLine); + } + if (range.kind === 3 /* MultiLineCommentTrivia */) { + var multiLinePragmaRegEx = /\s*@(\S+)\s*(.*)\s*$/gim; // Defined inline since it uses the "g" flag, which keeps a persistent index (for iterating) + var multiLineMatch = void 0; + while (multiLineMatch = multiLinePragmaRegEx.exec(text)) { + addPragmaForMatch(pragmas, range, 4 /* MultiLine */, multiLineMatch); + } + } + } + function addPragmaForMatch(pragmas, range, kind, match) { + if (!match) + return; + var name = match[1].toLowerCase(); // Technically unsafe cast, but we do it so they below check to make it safe typechecks + var pragma = ts.commentPragmas[name]; + if (!pragma || !(pragma.kind & kind)) { + return; + } + var args = match[2]; // Split on spaces and match up positionally with definition + var argument = getNamedPragmaArguments(pragma, args); + if (argument === "fail") + return; // Missing required argument, fail to parse it + pragmas.push({ name: name, args: { arguments: argument, range: range } }); + return; + } + function getNamedPragmaArguments(pragma, text) { + if (!text) + return {}; + if (!pragma.args) + return {}; + var args = text.split(/\s+/); + var argMap = {}; + for (var i = 0; i < pragma.args.length; i++) { + var argument = pragma.args[i]; + if (!args[i] && !argument.optional) { + return "fail"; + } + if (argument.captureSpan) { + return ts.Debug.fail("Capture spans not yet implemented for non-xml pragmas"); + } + argMap[argument.name] = args[i]; + } + return argMap; + } + /** @internal */ + function tagNamesAreEquivalent(lhs, rhs) { + if (lhs.kind !== rhs.kind) { + return false; + } + if (lhs.kind === 72 /* Identifier */) { + return lhs.escapedText === rhs.escapedText; + } + if (lhs.kind === 100 /* ThisKeyword */) { + return true; + } + // If we are at this statement then we must have PropertyAccessExpression and because tag name in Jsx element can only + // take forms of JsxTagNameExpression which includes an identifier, "this" expression, or another propertyAccessExpression + // it is safe to case the expression property as such. See parseJsxElementName for how we parse tag name in Jsx element + return lhs.name.escapedText === rhs.name.escapedText && + tagNamesAreEquivalent(lhs.expression, rhs.expression); + } + ts.tagNamesAreEquivalent = tagNamesAreEquivalent; +})(ts || (ts = {})); +var ts; +(function (ts) { + /* @internal */ + ts.compileOnSaveCommandLineOption = { name: "compileOnSave", type: "boolean" }; + // NOTE: The order here is important to default lib ordering as entries will have the same + // order in the generated program (see `getDefaultLibPriority` in program.ts). This + // order also affects overload resolution when a type declared in one lib is + // augmented in another lib. + var libEntries = [ + // JavaScript only + ["es5", "lib.es5.d.ts"], + ["es6", "lib.es2015.d.ts"], + ["es2015", "lib.es2015.d.ts"], + ["es7", "lib.es2016.d.ts"], + ["es2016", "lib.es2016.d.ts"], + ["es2017", "lib.es2017.d.ts"], + ["es2018", "lib.es2018.d.ts"], + ["esnext", "lib.esnext.d.ts"], + // Host only + ["dom", "lib.dom.d.ts"], + ["dom.iterable", "lib.dom.iterable.d.ts"], + ["webworker", "lib.webworker.d.ts"], + ["webworker.importscripts", "lib.webworker.importscripts.d.ts"], + ["scripthost", "lib.scripthost.d.ts"], + // ES2015 Or ESNext By-feature options + ["es2015.core", "lib.es2015.core.d.ts"], + ["es2015.collection", "lib.es2015.collection.d.ts"], + ["es2015.generator", "lib.es2015.generator.d.ts"], + ["es2015.iterable", "lib.es2015.iterable.d.ts"], + ["es2015.promise", "lib.es2015.promise.d.ts"], + ["es2015.proxy", "lib.es2015.proxy.d.ts"], + ["es2015.reflect", "lib.es2015.reflect.d.ts"], + ["es2015.symbol", "lib.es2015.symbol.d.ts"], + ["es2015.symbol.wellknown", "lib.es2015.symbol.wellknown.d.ts"], + ["es2016.array.include", "lib.es2016.array.include.d.ts"], + ["es2017.object", "lib.es2017.object.d.ts"], + ["es2017.sharedmemory", "lib.es2017.sharedmemory.d.ts"], + ["es2017.string", "lib.es2017.string.d.ts"], + ["es2017.intl", "lib.es2017.intl.d.ts"], + ["es2017.typedarrays", "lib.es2017.typedarrays.d.ts"], + ["es2018.intl", "lib.es2018.intl.d.ts"], + ["es2018.promise", "lib.es2018.promise.d.ts"], + ["es2018.regexp", "lib.es2018.regexp.d.ts"], + ["esnext.array", "lib.esnext.array.d.ts"], + ["esnext.symbol", "lib.esnext.symbol.d.ts"], + ["esnext.asynciterable", "lib.esnext.asynciterable.d.ts"], + ["esnext.intl", "lib.esnext.intl.d.ts"], + ["esnext.bigint", "lib.esnext.bigint.d.ts"] + ]; + /** + * An array of supported "lib" reference file names used to determine the order for inclusion + * when referenced, as well as for spelling suggestions. This ensures the correct ordering for + * overload resolution when a type declared in one lib is extended by another. + */ + /* @internal */ + ts.libs = libEntries.map(function (entry) { return entry[0]; }); + /** + * A map of lib names to lib files. This map is used both for parsing the "lib" command line + * option as well as for resolving lib reference directives. + */ + /* @internal */ + ts.libMap = ts.createMapFromEntries(libEntries); + /* @internal */ + ts.commonOptionsWithBuild = [ + { + name: "help", + shortName: "h", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Print_this_message, + }, + { + name: "help", + shortName: "?", + type: "boolean" + }, + { + name: "watch", + shortName: "w", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Watch_input_files, + }, + { + name: "preserveWatchOutput", + type: "boolean", + showInSimplifiedHelpView: false, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen, + }, + { + name: "listFiles", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Print_names_of_files_part_of_the_compilation + }, + { + name: "listEmittedFiles", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Print_names_of_generated_files_part_of_the_compilation + }, + { + name: "pretty", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Stylize_errors_and_messages_using_color_and_context_experimental + }, + { + name: "traceResolution", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Enable_tracing_of_the_name_resolution_process + }, + { + name: "diagnostics", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Show_diagnostic_information + }, + { + name: "extendedDiagnostics", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Show_verbose_diagnostic_information + }, + ]; + /* @internal */ + ts.optionDeclarations = ts.commonOptionsWithBuild.concat([ + { + name: "all", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Show_all_compiler_options, + }, + { + name: "version", + shortName: "v", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Print_the_compiler_s_version, + }, + { + name: "init", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file, + }, + { + name: "project", + shortName: "p", + type: "string", + isFilePath: true, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Command_line_Options, + paramType: ts.Diagnostics.FILE_OR_DIRECTORY, + description: ts.Diagnostics.Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json, + }, + { + name: "build", + type: "boolean", + shortName: "b", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Build_one_or_more_projects_and_their_dependencies_if_out_of_date + }, + { + name: "showConfig", + type: "boolean", + category: ts.Diagnostics.Command_line_Options, + isCommandLineOnly: true, + description: ts.Diagnostics.Print_the_final_configuration_instead_of_building + }, + // Basic + { + name: "target", + shortName: "t", + type: ts.createMapFromTemplate({ + es3: 0 /* ES3 */, + es5: 1 /* ES5 */, + es6: 2 /* ES2015 */, + es2015: 2 /* ES2015 */, + es2016: 3 /* ES2016 */, + es2017: 4 /* ES2017 */, + es2018: 5 /* ES2018 */, + esnext: 6 /* ESNext */, + }), + affectsSourceFile: true, + affectsModuleResolution: true, + paramType: ts.Diagnostics.VERSION, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_or_ESNEXT, + }, + { + name: "module", + shortName: "m", + type: ts.createMapFromTemplate({ + none: ts.ModuleKind.None, + commonjs: ts.ModuleKind.CommonJS, + amd: ts.ModuleKind.AMD, + system: ts.ModuleKind.System, + umd: ts.ModuleKind.UMD, + es6: ts.ModuleKind.ES2015, + es2015: ts.ModuleKind.ES2015, + esnext: ts.ModuleKind.ESNext + }), + affectsModuleResolution: true, + paramType: ts.Diagnostics.KIND, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext, + }, + { + name: "lib", + type: "list", + element: { + name: "lib", + type: ts.libMap + }, + affectsModuleResolution: true, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Specify_library_files_to_be_included_in_the_compilation + }, + { + name: "allowJs", + type: "boolean", + affectsModuleResolution: true, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Allow_javascript_files_to_be_compiled + }, + { + name: "checkJs", + type: "boolean", + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Report_errors_in_js_files + }, + { + name: "jsx", + type: ts.createMapFromTemplate({ + "preserve": 1 /* Preserve */, + "react-native": 3 /* ReactNative */, + "react": 2 /* React */ + }), + affectsSourceFile: true, + paramType: ts.Diagnostics.KIND, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Specify_JSX_code_generation_Colon_preserve_react_native_or_react, + }, + { + name: "declaration", + shortName: "d", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Generates_corresponding_d_ts_file, + }, + { + name: "declarationMap", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Generates_a_sourcemap_for_each_corresponding_d_ts_file, + }, + { + name: "emitDeclarationOnly", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Only_emit_d_ts_declaration_files, + }, + { + name: "sourceMap", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Generates_corresponding_map_file, + }, + { + name: "outFile", + type: "string", + isFilePath: true, + paramType: ts.Diagnostics.FILE, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Concatenate_and_emit_output_to_single_file, + }, + { + name: "outDir", + type: "string", + isFilePath: true, + paramType: ts.Diagnostics.DIRECTORY, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Redirect_output_structure_to_the_directory, + }, + { + name: "rootDir", + type: "string", + isFilePath: true, + paramType: ts.Diagnostics.LOCATION, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir, + }, + { + name: "composite", + type: "boolean", + isTSConfigOnly: true, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Enable_project_compilation, + }, + { + name: "removeComments", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Do_not_emit_comments_to_output, + }, + { + name: "noEmit", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Do_not_emit_outputs, + }, + { + name: "importHelpers", + type: "boolean", + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Import_emit_helpers_from_tslib + }, + { + name: "downlevelIteration", + type: "boolean", + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Provide_full_support_for_iterables_in_for_of_spread_and_destructuring_when_targeting_ES5_or_ES3 + }, + { + name: "isolatedModules", + type: "boolean", + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule + }, + // Strict Type Checks + { + name: "strict", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Strict_Type_Checking_Options, + description: ts.Diagnostics.Enable_all_strict_type_checking_options + }, + { + name: "noImplicitAny", + type: "boolean", + affectsSemanticDiagnostics: true, + strictFlag: true, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Strict_Type_Checking_Options, + description: ts.Diagnostics.Raise_error_on_expressions_and_declarations_with_an_implied_any_type + }, + { + name: "strictNullChecks", + type: "boolean", + affectsSemanticDiagnostics: true, + strictFlag: true, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Strict_Type_Checking_Options, + description: ts.Diagnostics.Enable_strict_null_checks + }, + { + name: "strictFunctionTypes", + type: "boolean", + affectsSemanticDiagnostics: true, + strictFlag: true, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Strict_Type_Checking_Options, + description: ts.Diagnostics.Enable_strict_checking_of_function_types + }, + { + name: "strictBindCallApply", + type: "boolean", + strictFlag: true, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Strict_Type_Checking_Options, + description: ts.Diagnostics.Enable_strict_bind_call_and_apply_methods_on_functions + }, + { + name: "strictPropertyInitialization", + type: "boolean", + affectsSemanticDiagnostics: true, + strictFlag: true, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Strict_Type_Checking_Options, + description: ts.Diagnostics.Enable_strict_checking_of_property_initialization_in_classes + }, + { + name: "noImplicitThis", + type: "boolean", + affectsSemanticDiagnostics: true, + strictFlag: true, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Strict_Type_Checking_Options, + description: ts.Diagnostics.Raise_error_on_this_expressions_with_an_implied_any_type, + }, + { + name: "alwaysStrict", + type: "boolean", + affectsSourceFile: true, + strictFlag: true, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Strict_Type_Checking_Options, + description: ts.Diagnostics.Parse_in_strict_mode_and_emit_use_strict_for_each_source_file + }, + // Additional Checks + { + name: "noUnusedLocals", + type: "boolean", + affectsSemanticDiagnostics: true, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Additional_Checks, + description: ts.Diagnostics.Report_errors_on_unused_locals, + }, + { + name: "noUnusedParameters", + type: "boolean", + affectsSemanticDiagnostics: true, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Additional_Checks, + description: ts.Diagnostics.Report_errors_on_unused_parameters, + }, + { + name: "noImplicitReturns", + type: "boolean", + affectsSemanticDiagnostics: true, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Additional_Checks, + description: ts.Diagnostics.Report_error_when_not_all_code_paths_in_function_return_a_value + }, + { + name: "noFallthroughCasesInSwitch", + type: "boolean", + affectsBindDiagnostics: true, + affectsSemanticDiagnostics: true, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Additional_Checks, + description: ts.Diagnostics.Report_errors_for_fallthrough_cases_in_switch_statement + }, + // Module Resolution + { + name: "moduleResolution", + type: ts.createMapFromTemplate({ + node: ts.ModuleResolutionKind.NodeJs, + classic: ts.ModuleResolutionKind.Classic, + }), + affectsModuleResolution: true, + paramType: ts.Diagnostics.STRATEGY, + category: ts.Diagnostics.Module_Resolution_Options, + description: ts.Diagnostics.Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6, + }, + { + name: "baseUrl", + type: "string", + affectsModuleResolution: true, + isFilePath: true, + category: ts.Diagnostics.Module_Resolution_Options, + description: ts.Diagnostics.Base_directory_to_resolve_non_absolute_module_names + }, + { + // this option can only be specified in tsconfig.json + // use type = object to copy the value as-is + name: "paths", + type: "object", + affectsModuleResolution: true, + isTSConfigOnly: true, + category: ts.Diagnostics.Module_Resolution_Options, + description: ts.Diagnostics.A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl + }, + { + // this option can only be specified in tsconfig.json + // use type = object to copy the value as-is + name: "rootDirs", + type: "list", + isTSConfigOnly: true, + element: { + name: "rootDirs", + type: "string", + isFilePath: true + }, + affectsModuleResolution: true, + category: ts.Diagnostics.Module_Resolution_Options, + description: ts.Diagnostics.List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime + }, + { + name: "typeRoots", + type: "list", + element: { + name: "typeRoots", + type: "string", + isFilePath: true + }, + affectsModuleResolution: true, + category: ts.Diagnostics.Module_Resolution_Options, + description: ts.Diagnostics.List_of_folders_to_include_type_definitions_from + }, + { + name: "types", + type: "list", + element: { + name: "types", + type: "string" + }, + affectsModuleResolution: true, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Module_Resolution_Options, + description: ts.Diagnostics.Type_declaration_files_to_be_included_in_compilation + }, + { + name: "allowSyntheticDefaultImports", + type: "boolean", + affectsSemanticDiagnostics: true, + category: ts.Diagnostics.Module_Resolution_Options, + description: ts.Diagnostics.Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking + }, + { + name: "esModuleInterop", + type: "boolean", + affectsSemanticDiagnostics: true, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Module_Resolution_Options, + description: ts.Diagnostics.Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for_all_imports_Implies_allowSyntheticDefaultImports + }, + { + name: "preserveSymlinks", + type: "boolean", + category: ts.Diagnostics.Module_Resolution_Options, + description: ts.Diagnostics.Do_not_resolve_the_real_path_of_symlinks, + }, + // Source Maps + { + name: "sourceRoot", + type: "string", + paramType: ts.Diagnostics.LOCATION, + category: ts.Diagnostics.Source_Map_Options, + description: ts.Diagnostics.Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations, + }, + { + name: "mapRoot", + type: "string", + paramType: ts.Diagnostics.LOCATION, + category: ts.Diagnostics.Source_Map_Options, + description: ts.Diagnostics.Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations, + }, + { + name: "inlineSourceMap", + type: "boolean", + category: ts.Diagnostics.Source_Map_Options, + description: ts.Diagnostics.Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file + }, + { + name: "inlineSources", + type: "boolean", + category: ts.Diagnostics.Source_Map_Options, + description: ts.Diagnostics.Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap_to_be_set + }, + // Experimental + { + name: "experimentalDecorators", + type: "boolean", + category: ts.Diagnostics.Experimental_Options, + description: ts.Diagnostics.Enables_experimental_support_for_ES7_decorators + }, + { + name: "emitDecoratorMetadata", + type: "boolean", + category: ts.Diagnostics.Experimental_Options, + description: ts.Diagnostics.Enables_experimental_support_for_emitting_type_metadata_for_decorators + }, + // Advanced + { + name: "jsxFactory", + type: "string", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h + }, + { + name: "resolveJsonModule", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Include_modules_imported_with_json_extension + }, + { + name: "out", + type: "string", + isFilePath: false, + // for correct behaviour, please use outFile + category: ts.Diagnostics.Advanced_Options, + paramType: ts.Diagnostics.FILE, + description: ts.Diagnostics.Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file, + }, + { + name: "reactNamespace", + type: "string", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react_JSX_emit + }, + { + name: "skipDefaultLibCheck", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files + }, + { + name: "charset", + type: "string", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.The_character_set_of_the_input_files + }, + { + name: "emitBOM", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files + }, + { + name: "locale", + type: "string", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.The_locale_used_when_displaying_messages_to_the_user_e_g_en_us + }, + { + name: "newLine", + type: ts.createMapFromTemplate({ + crlf: 0 /* CarriageReturnLineFeed */, + lf: 1 /* LineFeed */ + }), + paramType: ts.Diagnostics.NEWLINE, + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix, + }, + { + name: "noErrorTruncation", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Do_not_truncate_error_messages + }, + { + name: "noLib", + type: "boolean", + affectsModuleResolution: true, + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Do_not_include_the_default_library_file_lib_d_ts + }, + { + name: "noResolve", + type: "boolean", + affectsModuleResolution: true, + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files + }, + { + name: "stripInternal", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Do_not_emit_declarations_for_code_that_has_an_internal_annotation, + }, + { + name: "disableSizeLimit", + type: "boolean", + affectsSourceFile: true, + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Disable_size_limitations_on_JavaScript_projects + }, + { + name: "noImplicitUseStrict", + type: "boolean", + affectsSemanticDiagnostics: true, + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Do_not_emit_use_strict_directives_in_module_output + }, + { + name: "noEmitHelpers", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Do_not_generate_custom_helper_functions_like_extends_in_compiled_output + }, + { + name: "noEmitOnError", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Do_not_emit_outputs_if_any_errors_were_reported, + }, + { + name: "preserveConstEnums", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Do_not_erase_const_enum_declarations_in_generated_code + }, + { + name: "declarationDir", + type: "string", + isFilePath: true, + paramType: ts.Diagnostics.DIRECTORY, + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Output_directory_for_generated_declaration_files + }, + { + name: "skipLibCheck", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Skip_type_checking_of_declaration_files, + }, + { + name: "allowUnusedLabels", + type: "boolean", + affectsBindDiagnostics: true, + affectsSemanticDiagnostics: true, + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Do_not_report_errors_on_unused_labels + }, + { + name: "allowUnreachableCode", + type: "boolean", + affectsBindDiagnostics: true, + affectsSemanticDiagnostics: true, + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Do_not_report_errors_on_unreachable_code + }, + { + name: "suppressExcessPropertyErrors", + type: "boolean", + affectsSemanticDiagnostics: true, + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Suppress_excess_property_checks_for_object_literals, + }, + { + name: "suppressImplicitAnyIndexErrors", + type: "boolean", + affectsSemanticDiagnostics: true, + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures, + }, + { + name: "forceConsistentCasingInFileNames", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Disallow_inconsistently_cased_references_to_the_same_file + }, + { + name: "maxNodeModuleJsDepth", + type: "number", + affectsModuleResolution: true, + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files + }, + { + name: "noStrictGenericChecks", + type: "boolean", + affectsSemanticDiagnostics: true, + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Disable_strict_checking_of_generic_signatures_in_function_types, + }, + { + name: "keyofStringsOnly", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols, + }, + { + // A list of plugins to load in the language service + name: "plugins", + type: "list", + isTSConfigOnly: true, + element: { + name: "plugin", + type: "object" + }, + description: ts.Diagnostics.List_of_language_service_plugins + } + ]); + /* @internal */ + ts.semanticDiagnosticsOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsSemanticDiagnostics; }); + /* @internal */ + ts.moduleResolutionOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsModuleResolution; }); + /* @internal */ + ts.sourceFileAffectingCompilerOptions = ts.optionDeclarations.filter(function (option) { + return !!option.affectsSourceFile || !!option.affectsModuleResolution || !!option.affectsBindDiagnostics; + }); + /* @internal */ + ts.buildOpts = ts.commonOptionsWithBuild.concat([ + { + name: "verbose", + shortName: "v", + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Enable_verbose_logging, + type: "boolean" + }, + { + name: "dry", + shortName: "d", + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Show_what_would_be_built_or_deleted_if_specified_with_clean, + type: "boolean" + }, + { + name: "force", + shortName: "f", + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Build_all_projects_including_those_that_appear_to_be_up_to_date, + type: "boolean" + }, + { + name: "clean", + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Delete_the_outputs_of_all_projects, + type: "boolean" + } + ]); + /* @internal */ + ts.typeAcquisitionDeclarations = [ + { + /* @deprecated typingOptions.enableAutoDiscovery + * Use typeAcquisition.enable instead. + */ + name: "enableAutoDiscovery", + type: "boolean", + }, + { + name: "enable", + type: "boolean", + }, + { + name: "include", + type: "list", + element: { + name: "include", + type: "string" + } + }, + { + name: "exclude", + type: "list", + element: { + name: "exclude", + type: "string" + } + } + ]; + /* @internal */ + ts.defaultInitCompilerOptions = { + module: ts.ModuleKind.CommonJS, + target: 1 /* ES5 */, + strict: true, + esModuleInterop: true + }; + var optionNameMapCache; + /* @internal */ + function convertEnableAutoDiscoveryToEnable(typeAcquisition) { + // Convert deprecated typingOptions.enableAutoDiscovery to typeAcquisition.enable + if (typeAcquisition && typeAcquisition.enableAutoDiscovery !== undefined && typeAcquisition.enable === undefined) { + return { + enable: typeAcquisition.enableAutoDiscovery, + include: typeAcquisition.include || [], + exclude: typeAcquisition.exclude || [] + }; + } + return typeAcquisition; + } + ts.convertEnableAutoDiscoveryToEnable = convertEnableAutoDiscoveryToEnable; + function getOptionNameMap() { + return optionNameMapCache || (optionNameMapCache = createOptionNameMap(ts.optionDeclarations)); + } + /*@internal*/ + function createOptionNameMap(optionDeclarations) { + var optionNameMap = ts.createMap(); + var shortOptionNames = ts.createMap(); + ts.forEach(optionDeclarations, function (option) { + optionNameMap.set(option.name.toLowerCase(), option); + if (option.shortName) { + shortOptionNames.set(option.shortName, option.name); + } + }); + return { optionNameMap: optionNameMap, shortOptionNames: shortOptionNames }; + } + ts.createOptionNameMap = createOptionNameMap; + /* @internal */ + function createCompilerDiagnosticForInvalidCustomType(opt) { + return createDiagnosticForInvalidCustomType(opt, ts.createCompilerDiagnostic); + } + ts.createCompilerDiagnosticForInvalidCustomType = createCompilerDiagnosticForInvalidCustomType; + function createDiagnosticForInvalidCustomType(opt, createDiagnostic) { + var namesOfType = ts.arrayFrom(opt.type.keys()).map(function (key) { return "'" + key + "'"; }).join(", "); + return createDiagnostic(ts.Diagnostics.Argument_for_0_option_must_be_Colon_1, "--" + opt.name, namesOfType); + } + /* @internal */ + function parseCustomTypeOption(opt, value, errors) { + return convertJsonOptionOfCustomType(opt, trimString(value || ""), errors); + } + ts.parseCustomTypeOption = parseCustomTypeOption; + /* @internal */ + function parseListTypeOption(opt, value, errors) { + if (value === void 0) { value = ""; } + value = trimString(value); + if (ts.startsWith(value, "-")) { + return undefined; + } + if (value === "") { + return []; + } + var values = value.split(","); + switch (opt.element.type) { + case "number": + return ts.map(values, parseInt); + case "string": + return ts.map(values, function (v) { return v || ""; }); + default: + return ts.mapDefined(values, function (v) { return parseCustomTypeOption(opt.element, v, errors); }); + } + } + ts.parseListTypeOption = parseListTypeOption; + function parseCommandLineWorker(getOptionNameMap, _a, commandLine, readFile) { + var unknownOptionDiagnostic = _a[0], optionTypeMismatchDiagnostic = _a[1]; + var options = {}; + var fileNames = []; + var errors = []; + parseStrings(commandLine); + return { + options: options, + fileNames: fileNames, + errors: errors + }; + function parseStrings(args) { + var i = 0; + while (i < args.length) { + var s = args[i]; + i++; + if (s.charCodeAt(0) === 64 /* at */) { + parseResponseFile(s.slice(1)); + } + else if (s.charCodeAt(0) === 45 /* minus */) { + var opt = getOptionDeclarationFromName(getOptionNameMap, s.slice(s.charCodeAt(1) === 45 /* minus */ ? 2 : 1), /*allowShort*/ true); + if (opt) { + if (opt.isTSConfigOnly) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_can_only_be_specified_in_tsconfig_json_file, opt.name)); + } + else { + // Check to see if no argument was provided (e.g. "--locale" is the last command-line argument). + if (!args[i] && opt.type !== "boolean") { + errors.push(ts.createCompilerDiagnostic(optionTypeMismatchDiagnostic, opt.name)); + } + switch (opt.type) { + case "number": + options[opt.name] = parseInt(args[i]); + i++; + break; + case "boolean": + // boolean flag has optional value true, false, others + var optValue = args[i]; + options[opt.name] = optValue !== "false"; + // consume next argument as boolean flag value + if (optValue === "false" || optValue === "true") { + i++; + } + break; + case "string": + options[opt.name] = args[i] || ""; + i++; + break; + case "list": + var result = parseListTypeOption(opt, args[i], errors); + options[opt.name] = result || []; + if (result) { + i++; + } + break; + // If not a primitive, the possible types are specified in what is effectively a map of options. + default: + options[opt.name] = parseCustomTypeOption(opt, args[i], errors); + i++; + break; + } + } + } + else { + errors.push(ts.createCompilerDiagnostic(unknownOptionDiagnostic, s)); + } + } + else { + fileNames.push(s); + } + } + } + function parseResponseFile(fileName) { + var text = readFile ? readFile(fileName) : ts.sys.readFile(fileName); + if (!text) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_not_found, fileName)); + return; + } + var args = []; + var pos = 0; + while (true) { + while (pos < text.length && text.charCodeAt(pos) <= 32 /* space */) + pos++; + if (pos >= text.length) + break; + var start = pos; + if (text.charCodeAt(start) === 34 /* doubleQuote */) { + pos++; + while (pos < text.length && text.charCodeAt(pos) !== 34 /* doubleQuote */) + pos++; + if (pos < text.length) { + args.push(text.substring(start + 1, pos)); + pos++; + } + else { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unterminated_quoted_string_in_response_file_0, fileName)); + } + } + else { + while (text.charCodeAt(pos) > 32 /* space */) + pos++; + args.push(text.substring(start, pos)); + } + } + parseStrings(args); + } + } + function parseCommandLine(commandLine, readFile) { + return parseCommandLineWorker(getOptionNameMap, [ + ts.Diagnostics.Unknown_compiler_option_0, + ts.Diagnostics.Compiler_option_0_expects_an_argument + ], commandLine, readFile); + } + ts.parseCommandLine = parseCommandLine; + /** @internal */ + function getOptionFromName(optionName, allowShort) { + return getOptionDeclarationFromName(getOptionNameMap, optionName, allowShort); + } + ts.getOptionFromName = getOptionFromName; + function getOptionDeclarationFromName(getOptionNameMap, optionName, allowShort) { + if (allowShort === void 0) { allowShort = false; } + optionName = optionName.toLowerCase(); + var _a = getOptionNameMap(), optionNameMap = _a.optionNameMap, shortOptionNames = _a.shortOptionNames; + // Try to translate short option names to their full equivalents. + if (allowShort) { + var short = shortOptionNames.get(optionName); + if (short !== undefined) { + optionName = short; + } + } + return optionNameMap.get(optionName); + } + /*@internal*/ + function parseBuildCommand(args) { + var buildOptionNameMap; + var returnBuildOptionNameMap = function () { return (buildOptionNameMap || (buildOptionNameMap = createOptionNameMap(ts.buildOpts))); }; + var _a = parseCommandLineWorker(returnBuildOptionNameMap, [ + ts.Diagnostics.Unknown_build_option_0, + ts.Diagnostics.Build_option_0_requires_a_value_of_type_1 + ], args), options = _a.options, projects = _a.fileNames, errors = _a.errors; + var buildOptions = options; + if (projects.length === 0) { + // tsc -b invoked with no extra arguments; act as if invoked with "tsc -b ." + projects.push("."); + } + // Nonsensical combinations + if (buildOptions.clean && buildOptions.force) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "force")); + } + if (buildOptions.clean && buildOptions.verbose) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "verbose")); + } + if (buildOptions.clean && buildOptions.watch) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "watch")); + } + if (buildOptions.watch && buildOptions.dry) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "watch", "dry")); + } + return { buildOptions: buildOptions, projects: projects, errors: errors }; + } + ts.parseBuildCommand = parseBuildCommand; + function getDiagnosticText(_message) { + var _args = []; + for (var _i = 1; _i < arguments.length; _i++) { + _args[_i - 1] = arguments[_i]; + } + var diagnostic = ts.createCompilerDiagnostic.apply(undefined, arguments); + return diagnostic.messageText; + } + /* @internal */ + function printVersion() { + ts.sys.write(getDiagnosticText(ts.Diagnostics.Version_0, ts.version) + ts.sys.newLine); + } + ts.printVersion = printVersion; + /* @internal */ + function printHelp(optionsList, syntaxPrefix) { + if (syntaxPrefix === void 0) { syntaxPrefix = ""; } + var output = []; + // We want to align our "syntax" and "examples" commands to a certain margin. + var syntaxLength = getDiagnosticText(ts.Diagnostics.Syntax_Colon_0, "").length; + var examplesLength = getDiagnosticText(ts.Diagnostics.Examples_Colon_0, "").length; + var marginLength = Math.max(syntaxLength, examplesLength); + // Build up the syntactic skeleton. + var syntax = makePadding(marginLength - syntaxLength); + syntax += "tsc " + syntaxPrefix + "[" + getDiagnosticText(ts.Diagnostics.options) + "] [" + getDiagnosticText(ts.Diagnostics.file) + "...]"; + output.push(getDiagnosticText(ts.Diagnostics.Syntax_Colon_0, syntax)); + output.push(ts.sys.newLine + ts.sys.newLine); + // Build up the list of examples. + var padding = makePadding(marginLength); + output.push(getDiagnosticText(ts.Diagnostics.Examples_Colon_0, makePadding(marginLength - examplesLength) + "tsc hello.ts") + ts.sys.newLine); + output.push(padding + "tsc --outFile file.js file.ts" + ts.sys.newLine); + output.push(padding + "tsc @args.txt" + ts.sys.newLine); + output.push(padding + "tsc --build tsconfig.json" + ts.sys.newLine); + output.push(ts.sys.newLine); + output.push(getDiagnosticText(ts.Diagnostics.Options_Colon) + ts.sys.newLine); + // We want our descriptions to align at the same column in our output, + // so we keep track of the longest option usage string. + marginLength = 0; + var usageColumn = []; // Things like "-d, --declaration" go in here. + var descriptionColumn = []; + var optionsDescriptionMap = ts.createMap(); // Map between option.description and list of option.type if it is a kind + for (var _i = 0, optionsList_1 = optionsList; _i < optionsList_1.length; _i++) { + var option = optionsList_1[_i]; + // If an option lacks a description, + // it is not officially supported. + if (!option.description) { + continue; + } + var usageText_1 = " "; + if (option.shortName) { + usageText_1 += "-" + option.shortName; + usageText_1 += getParamType(option); + usageText_1 += ", "; + } + usageText_1 += "--" + option.name; + usageText_1 += getParamType(option); + usageColumn.push(usageText_1); + var description = void 0; + if (option.name === "lib") { + description = getDiagnosticText(option.description); + var element = option.element; + var typeMap = element.type; + optionsDescriptionMap.set(description, ts.arrayFrom(typeMap.keys()).map(function (key) { return "'" + key + "'"; })); + } + else { + description = getDiagnosticText(option.description); + } + descriptionColumn.push(description); + // Set the new margin for the description column if necessary. + marginLength = Math.max(usageText_1.length, marginLength); + } + // Special case that can't fit in the loop. + var usageText = " @<" + getDiagnosticText(ts.Diagnostics.file) + ">"; + usageColumn.push(usageText); + descriptionColumn.push(getDiagnosticText(ts.Diagnostics.Insert_command_line_options_and_files_from_a_file)); + marginLength = Math.max(usageText.length, marginLength); + // Print out each row, aligning all the descriptions on the same column. + for (var i = 0; i < usageColumn.length; i++) { + var usage = usageColumn[i]; + var description = descriptionColumn[i]; + var kindsList = optionsDescriptionMap.get(description); + output.push(usage + makePadding(marginLength - usage.length + 2) + description + ts.sys.newLine); + if (kindsList) { + output.push(makePadding(marginLength + 4)); + for (var _a = 0, kindsList_1 = kindsList; _a < kindsList_1.length; _a++) { + var kind = kindsList_1[_a]; + output.push(kind + " "); + } + output.push(ts.sys.newLine); + } + } + for (var _b = 0, output_1 = output; _b < output_1.length; _b++) { + var line = output_1[_b]; + ts.sys.write(line); + } + return; + function getParamType(option) { + if (option.paramType !== undefined) { + return " " + getDiagnosticText(option.paramType); + } + return ""; + } + function makePadding(paddingLength) { + return Array(paddingLength + 1).join(" "); + } + } + ts.printHelp = printHelp; + /** + * Reads the config file, reports errors if any and exits if the config file cannot be found + */ + function getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host) { + var configFileText; + try { + configFileText = host.readFile(configFileName); + } + catch (e) { + var error = ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, configFileName, e.message); + host.onUnRecoverableConfigFileDiagnostic(error); + return undefined; + } + if (!configFileText) { + var error = ts.createCompilerDiagnostic(ts.Diagnostics.File_0_not_found, configFileName); + host.onUnRecoverableConfigFileDiagnostic(error); + return undefined; + } + var result = ts.parseJsonText(configFileName, configFileText); + var cwd = host.getCurrentDirectory(); + result.path = ts.toPath(configFileName, cwd, ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames)); + result.resolvedPath = result.path; + result.originalFileName = result.fileName; + return parseJsonSourceFileConfigFileContent(result, host, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), cwd), optionsToExtend, ts.getNormalizedAbsolutePath(configFileName, cwd)); + } + ts.getParsedCommandLineOfConfigFile = getParsedCommandLineOfConfigFile; + /** + * Read tsconfig.json file + * @param fileName The path to the config file + */ + function readConfigFile(fileName, readFile) { + var textOrDiagnostic = tryReadFile(fileName, readFile); + return ts.isString(textOrDiagnostic) ? parseConfigFileTextToJson(fileName, textOrDiagnostic) : { config: {}, error: textOrDiagnostic }; + } + ts.readConfigFile = readConfigFile; + /** + * Parse the text of the tsconfig.json file + * @param fileName The path to the config file + * @param jsonText The text of the config file + */ + function parseConfigFileTextToJson(fileName, jsonText) { + var jsonSourceFile = ts.parseJsonText(fileName, jsonText); + return { + config: convertToObject(jsonSourceFile, jsonSourceFile.parseDiagnostics), + error: jsonSourceFile.parseDiagnostics.length ? jsonSourceFile.parseDiagnostics[0] : undefined + }; + } + ts.parseConfigFileTextToJson = parseConfigFileTextToJson; + /** + * Read tsconfig.json file + * @param fileName The path to the config file + */ + function readJsonConfigFile(fileName, readFile) { + var textOrDiagnostic = tryReadFile(fileName, readFile); + return ts.isString(textOrDiagnostic) ? ts.parseJsonText(fileName, textOrDiagnostic) : { parseDiagnostics: [textOrDiagnostic] }; + } + ts.readJsonConfigFile = readJsonConfigFile; + function tryReadFile(fileName, readFile) { + var text; + try { + text = readFile(fileName); + } + catch (e) { + return ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, e.message); + } + return text === undefined ? ts.createCompilerDiagnostic(ts.Diagnostics.The_specified_path_does_not_exist_Colon_0, fileName) : text; + } + function commandLineOptionsToMap(options) { + return ts.arrayToMap(options, function (option) { return option.name; }); + } + var _tsconfigRootOptions; + function getTsconfigRootOptionsMap() { + if (_tsconfigRootOptions === undefined) { + _tsconfigRootOptions = { + name: undefined, + type: "object", + elementOptions: commandLineOptionsToMap([ + { + name: "compilerOptions", + type: "object", + elementOptions: commandLineOptionsToMap(ts.optionDeclarations), + extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_compiler_option_0 + }, + { + name: "typingOptions", + type: "object", + elementOptions: commandLineOptionsToMap(ts.typeAcquisitionDeclarations), + extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_type_acquisition_option_0 + }, + { + name: "typeAcquisition", + type: "object", + elementOptions: commandLineOptionsToMap(ts.typeAcquisitionDeclarations), + extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_type_acquisition_option_0 + }, + { + name: "extends", + type: "string" + }, + { + name: "references", + type: "list", + element: { + name: "references", + type: "object" + } + }, + { + name: "files", + type: "list", + element: { + name: "files", + type: "string" + } + }, + { + name: "include", + type: "list", + element: { + name: "include", + type: "string" + } + }, + { + name: "exclude", + type: "list", + element: { + name: "exclude", + type: "string" + } + }, + ts.compileOnSaveCommandLineOption + ]) + }; + } + return _tsconfigRootOptions; + } + /** + * Convert the json syntax tree into the json value + */ + function convertToObject(sourceFile, errors) { + return convertToObjectWorker(sourceFile, errors, /*returnValue*/ true, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined); + } + ts.convertToObject = convertToObject; + /** + * Convert the json syntax tree into the json value and report errors + * This returns the json value (apart from checking errors) only if returnValue provided is true. + * Otherwise it just checks the errors and returns undefined + */ + /*@internal*/ + function convertToObjectWorker(sourceFile, errors, returnValue, knownRootOptions, jsonConversionNotifier) { + if (!sourceFile.statements.length) { + return returnValue ? {} : undefined; + } + return convertPropertyValueToJson(sourceFile.statements[0].expression, knownRootOptions); + function isRootOptionMap(knownOptions) { + return knownRootOptions && knownRootOptions.elementOptions === knownOptions; + } + function convertObjectLiteralExpressionToJson(node, knownOptions, extraKeyDiagnosticMessage, parentOption) { + var result = returnValue ? {} : undefined; + for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { + var element = _a[_i]; + if (element.kind !== 275 /* PropertyAssignment */) { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element, ts.Diagnostics.Property_assignment_expected)); + continue; + } + if (element.questionToken) { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.questionToken, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, "?")); + } + if (!isDoubleQuotedString(element.name)) { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, ts.Diagnostics.String_literal_with_double_quotes_expected)); + } + var textOfKey = ts.getTextOfPropertyName(element.name); + var keyText = textOfKey && ts.unescapeLeadingUnderscores(textOfKey); + var option = keyText && knownOptions ? knownOptions.get(keyText) : undefined; + if (keyText && extraKeyDiagnosticMessage && !option) { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, extraKeyDiagnosticMessage, keyText)); + } + var value = convertPropertyValueToJson(element.initializer, option); + if (typeof keyText !== "undefined") { + if (returnValue) { + result[keyText] = value; + } + // Notify key value set, if user asked for it + if (jsonConversionNotifier && + // Current callbacks are only on known parent option or if we are setting values in the root + (parentOption || isRootOptionMap(knownOptions))) { + var isValidOptionValue = isCompilerOptionsValue(option, value); + if (parentOption) { + if (isValidOptionValue) { + // Notify option set in the parent if its a valid option value + jsonConversionNotifier.onSetValidOptionKeyValueInParent(parentOption, option, value); + } + } + else if (isRootOptionMap(knownOptions)) { + if (isValidOptionValue) { + // Notify about the valid root key value being set + jsonConversionNotifier.onSetValidOptionKeyValueInRoot(keyText, element.name, value, element.initializer); + } + else if (!option) { + // Notify about the unknown root key value being set + jsonConversionNotifier.onSetUnknownOptionKeyValueInRoot(keyText, element.name, value, element.initializer); + } + } + } + } + } + return result; + } + function convertArrayLiteralExpressionToJson(elements, elementOption) { + if (!returnValue) { + return elements.forEach(function (element) { return convertPropertyValueToJson(element, elementOption); }); + } + // Filter out invalid values + return ts.filter(elements.map(function (element) { return convertPropertyValueToJson(element, elementOption); }), function (v) { return v !== undefined; }); + } + function convertPropertyValueToJson(valueExpression, option) { + switch (valueExpression.kind) { + case 102 /* TrueKeyword */: + reportInvalidOptionValue(option && option.type !== "boolean"); + return true; + case 87 /* FalseKeyword */: + reportInvalidOptionValue(option && option.type !== "boolean"); + return false; + case 96 /* NullKeyword */: + reportInvalidOptionValue(option && option.name === "extends"); // "extends" is the only option we don't allow null/undefined for + return null; // tslint:disable-line:no-null-keyword + case 10 /* StringLiteral */: + if (!isDoubleQuotedString(valueExpression)) { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, ts.Diagnostics.String_literal_with_double_quotes_expected)); + } + reportInvalidOptionValue(option && (ts.isString(option.type) && option.type !== "string")); + var text = valueExpression.text; + if (option && !ts.isString(option.type)) { + var customOption = option; + // Validate custom option type + if (!customOption.type.has(text.toLowerCase())) { + errors.push(createDiagnosticForInvalidCustomType(customOption, function (message, arg0, arg1) { return ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, message, arg0, arg1); })); + } + } + return text; + case 8 /* NumericLiteral */: + reportInvalidOptionValue(option && option.type !== "number"); + return Number(valueExpression.text); + case 202 /* PrefixUnaryExpression */: + if (valueExpression.operator !== 39 /* MinusToken */ || valueExpression.operand.kind !== 8 /* NumericLiteral */) { + break; // not valid JSON syntax + } + reportInvalidOptionValue(option && option.type !== "number"); + return -Number(valueExpression.operand.text); + case 188 /* ObjectLiteralExpression */: + reportInvalidOptionValue(option && option.type !== "object"); + var objectLiteralExpression = valueExpression; + // Currently having element option declaration in the tsconfig with type "object" + // determines if it needs onSetValidOptionKeyValueInParent callback or not + // At moment there are only "compilerOptions", "typeAcquisition" and "typingOptions" + // that satifies it and need it to modify options set in them (for normalizing file paths) + // vs what we set in the json + // If need arises, we can modify this interface and callbacks as needed + if (option) { + var _a = option, elementOptions = _a.elementOptions, extraKeyDiagnosticMessage = _a.extraKeyDiagnosticMessage, optionName = _a.name; + return convertObjectLiteralExpressionToJson(objectLiteralExpression, elementOptions, extraKeyDiagnosticMessage, optionName); + } + else { + return convertObjectLiteralExpressionToJson(objectLiteralExpression, /* knownOptions*/ undefined, + /*extraKeyDiagnosticMessage */ undefined, /*parentOption*/ undefined); + } + case 187 /* ArrayLiteralExpression */: + reportInvalidOptionValue(option && option.type !== "list"); + return convertArrayLiteralExpressionToJson(valueExpression.elements, option && option.element); + } + // Not in expected format + if (option) { + reportInvalidOptionValue(/*isError*/ true); + } + else { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, ts.Diagnostics.Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_literal)); + } + return undefined; + function reportInvalidOptionValue(isError) { + if (isError) { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, option.name, getCompilerOptionValueTypeString(option))); + } + } + } + function isDoubleQuotedString(node) { + return ts.isStringLiteral(node) && ts.isStringDoubleQuoted(node, sourceFile); + } + } + ts.convertToObjectWorker = convertToObjectWorker; + function getCompilerOptionValueTypeString(option) { + return option.type === "list" ? + "Array" : + ts.isString(option.type) ? option.type : "string"; + } + function isCompilerOptionsValue(option, value) { + if (option) { + if (isNullOrUndefined(value)) + return true; // All options are undefinable/nullable + if (option.type === "list") { + return ts.isArray(value); + } + var expectedType = ts.isString(option.type) ? option.type : "string"; + return typeof value === expectedType; + } + return false; + } + /** + * Generate an uncommented, complete tsconfig for use with "--showConfig" + * @param configParseResult options to be generated into tsconfig.json + * @param configFileName name of the parsed config file - output paths will be generated relative to this + * @param host provides current directory and case sensitivity services + */ + /** @internal */ + function convertToTSConfig(configParseResult, configFileName, host) { + var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); + var files = ts.map(ts.filter(configParseResult.fileNames, (!configParseResult.configFileSpecs || !configParseResult.configFileSpecs.validatedIncludeSpecs) ? function (_) { return true; } : matchesSpecs(configFileName, configParseResult.configFileSpecs.validatedIncludeSpecs, configParseResult.configFileSpecs.validatedExcludeSpecs)), function (f) { return ts.getRelativePathFromFile(ts.getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), ts.getNormalizedAbsolutePath(f, host.getCurrentDirectory()), getCanonicalFileName); }); + var optionMap = serializeCompilerOptions(configParseResult.options, { configFilePath: ts.getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), useCaseSensitiveFileNames: host.useCaseSensitiveFileNames }); + var config = __assign({ compilerOptions: __assign({}, ts.arrayFrom(optionMap.entries()).reduce(function (prev, cur) { + var _a; + return (__assign({}, prev, (_a = {}, _a[cur[0]] = cur[1], _a))); + }, {}), { showConfig: undefined, configFile: undefined, configFilePath: undefined, help: undefined, init: undefined, listFiles: undefined, listEmittedFiles: undefined, project: undefined }), references: ts.map(configParseResult.projectReferences, function (r) { return (__assign({}, r, { path: r.originalPath, originalPath: undefined })); }), files: ts.length(files) ? files : undefined }, (configParseResult.configFileSpecs ? { + include: filterSameAsDefaultInclude(configParseResult.configFileSpecs.validatedIncludeSpecs), + exclude: configParseResult.configFileSpecs.validatedExcludeSpecs + } : {}), { compilerOnSave: !!configParseResult.compileOnSave ? true : undefined }); + return config; + } + ts.convertToTSConfig = convertToTSConfig; + function filterSameAsDefaultInclude(specs) { + if (!ts.length(specs)) + return undefined; + if (ts.length(specs) !== 1) + return specs; + if (specs[0] === "**/*") + return undefined; + return specs; + } + function matchesSpecs(path, includeSpecs, excludeSpecs) { + if (!includeSpecs) + return function (_) { return true; }; + var patterns = ts.getFileMatcherPatterns(path, excludeSpecs, includeSpecs, ts.sys.useCaseSensitiveFileNames, ts.sys.getCurrentDirectory()); + var excludeRe = patterns.excludePattern && ts.getRegexFromPattern(patterns.excludePattern, ts.sys.useCaseSensitiveFileNames); + var includeRe = patterns.includeFilePattern && ts.getRegexFromPattern(patterns.includeFilePattern, ts.sys.useCaseSensitiveFileNames); + if (includeRe) { + if (excludeRe) { + return function (path) { return !(includeRe.test(path) && !excludeRe.test(path)); }; + } + return function (path) { return !includeRe.test(path); }; + } + if (excludeRe) { + return function (path) { return excludeRe.test(path); }; + } + return function (_) { return true; }; + } + function getCustomTypeMapOfCommandLineOption(optionDefinition) { + if (optionDefinition.type === "string" || optionDefinition.type === "number" || optionDefinition.type === "boolean") { + // this is of a type CommandLineOptionOfPrimitiveType + return undefined; + } + else if (optionDefinition.type === "list") { + return getCustomTypeMapOfCommandLineOption(optionDefinition.element); + } + else { + return optionDefinition.type; + } + } + function getNameOfCompilerOptionValue(value, customTypeMap) { + // There is a typeMap associated with this command-line option so use it to map value back to its name + return ts.forEachEntry(customTypeMap, function (mapValue, key) { + if (mapValue === value) { + return key; + } + }); + } + function serializeCompilerOptions(options, pathOptions) { + var result = ts.createMap(); + var optionsNameMap = getOptionNameMap().optionNameMap; + var getCanonicalFileName = pathOptions && ts.createGetCanonicalFileName(pathOptions.useCaseSensitiveFileNames); + var _loop_3 = function (name) { + if (ts.hasProperty(options, name)) { + // tsconfig only options cannot be specified via command line, + // so we can assume that only types that can appear here string | number | boolean + if (optionsNameMap.has(name) && optionsNameMap.get(name).category === ts.Diagnostics.Command_line_Options) { + return "continue"; + } + var value = options[name]; + var optionDefinition = optionsNameMap.get(name.toLowerCase()); + if (optionDefinition) { + var customTypeMap_1 = getCustomTypeMapOfCommandLineOption(optionDefinition); + if (!customTypeMap_1) { + // There is no map associated with this compiler option then use the value as-is + // This is the case if the value is expect to be string, number, boolean or list of string + if (pathOptions && optionDefinition.isFilePath) { + result.set(name, ts.getRelativePathFromFile(pathOptions.configFilePath, ts.getNormalizedAbsolutePath(value, ts.getDirectoryPath(pathOptions.configFilePath)), getCanonicalFileName)); + } + else { + result.set(name, value); + } + } + else { + if (optionDefinition.type === "list") { + result.set(name, value.map(function (element) { return getNameOfCompilerOptionValue(element, customTypeMap_1); })); // TODO: GH#18217 + } + else { + // There is a typeMap associated with this command-line option so use it to map value back to its name + result.set(name, getNameOfCompilerOptionValue(value, customTypeMap_1)); + } + } + } + } + }; + for (var name in options) { + _loop_3(name); + } + return result; + } + /** + * Generate tsconfig configuration when running command line "--init" + * @param options commandlineOptions to be generated into tsconfig.json + * @param fileNames array of filenames to be generated into tsconfig.json + */ + /* @internal */ + function generateTSConfig(options, fileNames, newLine) { + var compilerOptions = ts.extend(options, ts.defaultInitCompilerOptions); + var compilerOptionsMap = serializeCompilerOptions(compilerOptions); + return writeConfigurations(); + function getDefaultValueForOption(option) { + switch (option.type) { + case "number": + return 1; + case "boolean": + return true; + case "string": + return option.isFilePath ? "./" : ""; + case "list": + return []; + case "object": + return {}; + default: + return option.type.keys().next().value; + } + } + function makePadding(paddingLength) { + return Array(paddingLength + 1).join(" "); + } + function isAllowedOption(_a) { + var category = _a.category, name = _a.name; + // Skip options which do not have a category or have category `Command_line_Options` + // Exclude all possible `Advanced_Options` in tsconfig.json which were NOT defined in command line + return category !== undefined + && category !== ts.Diagnostics.Command_line_Options + && (category !== ts.Diagnostics.Advanced_Options || compilerOptionsMap.has(name)); + } + function writeConfigurations() { + // Filter applicable options to place in the file + var categorizedOptions = ts.createMultiMap(); + for (var _i = 0, optionDeclarations_1 = ts.optionDeclarations; _i < optionDeclarations_1.length; _i++) { + var option = optionDeclarations_1[_i]; + var category = option.category; + if (isAllowedOption(option)) { + categorizedOptions.add(ts.getLocaleSpecificMessage(category), option); + } + } + // Serialize all options and their descriptions + var marginLength = 0; + var seenKnownKeys = 0; + var nameColumn = []; + var descriptionColumn = []; + categorizedOptions.forEach(function (options, category) { + if (nameColumn.length !== 0) { + nameColumn.push(""); + descriptionColumn.push(""); + } + nameColumn.push("/* " + category + " */"); + descriptionColumn.push(""); + for (var _i = 0, options_1 = options; _i < options_1.length; _i++) { + var option = options_1[_i]; + var optionName = void 0; + if (compilerOptionsMap.has(option.name)) { + optionName = "\"" + option.name + "\": " + JSON.stringify(compilerOptionsMap.get(option.name)) + ((seenKnownKeys += 1) === compilerOptionsMap.size ? "" : ","); + } + else { + optionName = "// \"" + option.name + "\": " + JSON.stringify(getDefaultValueForOption(option)) + ","; + } + nameColumn.push(optionName); + descriptionColumn.push("/* " + (option.description && ts.getLocaleSpecificMessage(option.description) || option.name) + " */"); + marginLength = Math.max(optionName.length, marginLength); + } + }); + // Write the output + var tab = makePadding(2); + var result = []; + result.push("{"); + result.push(tab + "\"compilerOptions\": {"); + // Print out each row, aligning all the descriptions on the same column. + for (var i = 0; i < nameColumn.length; i++) { + var optionName = nameColumn[i]; + var description = descriptionColumn[i]; + result.push(optionName && "" + tab + tab + optionName + (description && (makePadding(marginLength - optionName.length + 2) + description))); + } + if (fileNames.length) { + result.push(tab + "},"); + result.push(tab + "\"files\": ["); + for (var i = 0; i < fileNames.length; i++) { + result.push("" + tab + tab + JSON.stringify(fileNames[i]) + (i === fileNames.length - 1 ? "" : ",")); + } + result.push(tab + "]"); + } + else { + result.push(tab + "}"); + } + result.push("}"); + return result.join(newLine); + } + } + ts.generateTSConfig = generateTSConfig; + /** + * Parse the contents of a config file (tsconfig.json). + * @param json The contents of the config file to parse + * @param host Instance of ParseConfigHost used to enumerate files in folder. + * @param basePath A root directory to resolve relative path entries in the config + * file to. e.g. outDir + */ + function parseJsonConfigFileContent(json, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions) { + return parseJsonConfigFileContentWorker(json, /*sourceFile*/ undefined, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions); + } + ts.parseJsonConfigFileContent = parseJsonConfigFileContent; + /** + * Parse the contents of a config file (tsconfig.json). + * @param jsonNode The contents of the config file to parse + * @param host Instance of ParseConfigHost used to enumerate files in folder. + * @param basePath A root directory to resolve relative path entries in the config + * file to. e.g. outDir + */ + function parseJsonSourceFileConfigFileContent(sourceFile, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions) { + return parseJsonConfigFileContentWorker(/*json*/ undefined, sourceFile, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions); + } + ts.parseJsonSourceFileConfigFileContent = parseJsonSourceFileConfigFileContent; + /*@internal*/ + function setConfigFileInOptions(options, configFile) { + if (configFile) { + Object.defineProperty(options, "configFile", { enumerable: false, writable: false, value: configFile }); + } + } + ts.setConfigFileInOptions = setConfigFileInOptions; + function isNullOrUndefined(x) { + // tslint:disable-next-line:no-null-keyword + return x === undefined || x === null; + } + function directoryOfCombinedPath(fileName, basePath) { + // Use the `getNormalizedAbsolutePath` function to avoid canonicalizing the path, as it must remain noncanonical + // until consistient casing errors are reported + return ts.getDirectoryPath(ts.getNormalizedAbsolutePath(fileName, basePath)); + } + /** + * Parse the contents of a config file from json or json source file (tsconfig.json). + * @param json The contents of the config file to parse + * @param sourceFile sourceFile corresponding to the Json + * @param host Instance of ParseConfigHost used to enumerate files in folder. + * @param basePath A root directory to resolve relative path entries in the config + * file to. e.g. outDir + * @param resolutionStack Only present for backwards-compatibility. Should be empty. + */ + function parseJsonConfigFileContentWorker(json, sourceFile, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions) { + if (existingOptions === void 0) { existingOptions = {}; } + if (resolutionStack === void 0) { resolutionStack = []; } + if (extraFileExtensions === void 0) { extraFileExtensions = []; } + ts.Debug.assert((json === undefined && sourceFile !== undefined) || (json !== undefined && sourceFile === undefined)); + var errors = []; + var parsedConfig = parseConfig(json, sourceFile, host, basePath, configFileName, resolutionStack, errors); + var raw = parsedConfig.raw; + var options = ts.extend(existingOptions, parsedConfig.options || {}); + options.configFilePath = configFileName && ts.normalizeSlashes(configFileName); + setConfigFileInOptions(options, sourceFile); + var projectReferences; + var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories, spec = _a.spec; + return { + options: options, + fileNames: fileNames, + projectReferences: projectReferences, + typeAcquisition: parsedConfig.typeAcquisition || getDefaultTypeAcquisition(), + raw: raw, + errors: errors, + wildcardDirectories: wildcardDirectories, + compileOnSave: !!raw.compileOnSave, + configFileSpecs: spec + }; + function getFileNames() { + var filesSpecs; + if (ts.hasProperty(raw, "files") && !isNullOrUndefined(raw.files)) { + if (ts.isArray(raw.files)) { + filesSpecs = raw.files; + var hasReferences = ts.hasProperty(raw, "references") && !isNullOrUndefined(raw.references); + var hasZeroOrNoReferences = !hasReferences || raw.references.length === 0; + var hasExtends = ts.hasProperty(raw, "extends"); + if (filesSpecs.length === 0 && hasZeroOrNoReferences && !hasExtends) { + if (sourceFile) { + var fileName = configFileName || "tsconfig.json"; + var diagnosticMessage = ts.Diagnostics.The_files_list_in_config_file_0_is_empty; + var nodeValue = ts.firstDefined(ts.getTsConfigPropArray(sourceFile, "files"), function (property) { return property.initializer; }); + var error = nodeValue + ? ts.createDiagnosticForNodeInSourceFile(sourceFile, nodeValue, diagnosticMessage, fileName) + : ts.createCompilerDiagnostic(diagnosticMessage, fileName); + errors.push(error); + } + else { + createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json"); + } + } + } + else { + createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "files", "Array"); + } + } + var includeSpecs; + if (ts.hasProperty(raw, "include") && !isNullOrUndefined(raw.include)) { + if (ts.isArray(raw.include)) { + includeSpecs = raw.include; + } + else { + createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "include", "Array"); + } + } + var excludeSpecs; + if (ts.hasProperty(raw, "exclude") && !isNullOrUndefined(raw.exclude)) { + if (ts.isArray(raw.exclude)) { + excludeSpecs = raw.exclude; + } + else { + createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "exclude", "Array"); + } + } + else if (raw.compilerOptions) { + var outDir = raw.compilerOptions.outDir; + var declarationDir = raw.compilerOptions.declarationDir; + if (outDir || declarationDir) { + excludeSpecs = [outDir, declarationDir].filter(function (d) { return !!d; }); + } + } + if (filesSpecs === undefined && includeSpecs === undefined) { + includeSpecs = ["**/*"]; + } + var result = matchFileNames(filesSpecs, includeSpecs, excludeSpecs, configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath, options, host, errors, extraFileExtensions, sourceFile); + if (shouldReportNoInputFiles(result, canJsonReportNoInutFiles(raw), resolutionStack)) { + errors.push(getErrorForNoInputFiles(result.spec, configFileName)); + } + if (ts.hasProperty(raw, "references") && !isNullOrUndefined(raw.references)) { + if (ts.isArray(raw.references)) { + for (var _i = 0, _a = raw.references; _i < _a.length; _i++) { + var ref = _a[_i]; + if (typeof ref.path !== "string") { + createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "reference.path", "string"); + } + else { + (projectReferences || (projectReferences = [])).push({ + path: ts.getNormalizedAbsolutePath(ref.path, basePath), + originalPath: ref.path, + prepend: ref.prepend, + circular: ref.circular + }); + } + } + } + else { + createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "references", "Array"); + } + } + return result; + } + function createCompilerDiagnosticOnlyIfJson(message, arg0, arg1) { + if (!sourceFile) { + errors.push(ts.createCompilerDiagnostic(message, arg0, arg1)); + } + } + } + function isErrorNoInputFiles(error) { + return error.code === ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2.code; + } + function getErrorForNoInputFiles(_a, configFileName) { + var includeSpecs = _a.includeSpecs, excludeSpecs = _a.excludeSpecs; + return ts.createCompilerDiagnostic(ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2, configFileName || "tsconfig.json", JSON.stringify(includeSpecs || []), JSON.stringify(excludeSpecs || [])); + } + function shouldReportNoInputFiles(result, canJsonReportNoInutFiles, resolutionStack) { + return result.fileNames.length === 0 && canJsonReportNoInutFiles && (!resolutionStack || resolutionStack.length === 0); + } + /*@internal*/ + function canJsonReportNoInutFiles(raw) { + return !ts.hasProperty(raw, "files") && !ts.hasProperty(raw, "references"); + } + ts.canJsonReportNoInutFiles = canJsonReportNoInutFiles; + /*@internal*/ + function updateErrorForNoInputFiles(result, configFileName, configFileSpecs, configParseDiagnostics, canJsonReportNoInutFiles) { + var existingErrors = configParseDiagnostics.length; + if (shouldReportNoInputFiles(result, canJsonReportNoInutFiles)) { + configParseDiagnostics.push(getErrorForNoInputFiles(configFileSpecs, configFileName)); + } + else { + ts.filterMutate(configParseDiagnostics, function (error) { return !isErrorNoInputFiles(error); }); + } + return existingErrors !== configParseDiagnostics.length; + } + ts.updateErrorForNoInputFiles = updateErrorForNoInputFiles; + function isSuccessfulParsedTsconfig(value) { + return !!value.options; + } + /** + * This *just* extracts options/include/exclude/files out of a config file. + * It does *not* resolve the included files. + */ + function parseConfig(json, sourceFile, host, basePath, configFileName, resolutionStack, errors) { + basePath = ts.normalizeSlashes(basePath); + var resolvedPath = ts.getNormalizedAbsolutePath(configFileName || "", basePath); + if (resolutionStack.indexOf(resolvedPath) >= 0) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Circularity_detected_while_resolving_configuration_Colon_0, resolutionStack.concat([resolvedPath]).join(" -> "))); + return { raw: json || convertToObject(sourceFile, errors) }; + } + var ownConfig = json ? + parseOwnConfigOfJson(json, host, basePath, configFileName, errors) : + parseOwnConfigOfJsonSourceFile(sourceFile, host, basePath, configFileName, errors); + if (ownConfig.extendedConfigPath) { + // copy the resolution stack so it is never reused between branches in potential diamond-problem scenarios. + resolutionStack = resolutionStack.concat([resolvedPath]); + var extendedConfig = getExtendedConfig(sourceFile, ownConfig.extendedConfigPath, host, basePath, resolutionStack, errors); + if (extendedConfig && isSuccessfulParsedTsconfig(extendedConfig)) { + var baseRaw_1 = extendedConfig.raw; + var raw_1 = ownConfig.raw; + var setPropertyInRawIfNotUndefined = function (propertyName) { + var value = raw_1[propertyName] || baseRaw_1[propertyName]; + if (value) { + raw_1[propertyName] = value; + } + }; + setPropertyInRawIfNotUndefined("include"); + setPropertyInRawIfNotUndefined("exclude"); + setPropertyInRawIfNotUndefined("files"); + if (raw_1.compileOnSave === undefined) { + raw_1.compileOnSave = baseRaw_1.compileOnSave; + } + ownConfig.options = ts.assign({}, extendedConfig.options, ownConfig.options); + // TODO extend type typeAcquisition + } + } + return ownConfig; + } + function parseOwnConfigOfJson(json, host, basePath, configFileName, errors) { + if (ts.hasProperty(json, "excludes")) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude)); + } + var options = convertCompilerOptionsFromJsonWorker(json.compilerOptions, basePath, errors, configFileName); + // typingOptions has been deprecated and is only supported for backward compatibility purposes. + // It should be removed in future releases - use typeAcquisition instead. + var typeAcquisition = convertTypeAcquisitionFromJsonWorker(json.typeAcquisition || json.typingOptions, basePath, errors, configFileName); + json.compileOnSave = convertCompileOnSaveOptionFromJson(json, basePath, errors); + var extendedConfigPath; + if (json.extends) { + if (!ts.isString(json.extends)) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "extends", "string")); + } + else { + var newBase = configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath; + extendedConfigPath = getExtendsConfigPath(json.extends, host, newBase, errors, ts.createCompilerDiagnostic); + } + } + return { raw: json, options: options, typeAcquisition: typeAcquisition, extendedConfigPath: extendedConfigPath }; + } + function parseOwnConfigOfJsonSourceFile(sourceFile, host, basePath, configFileName, errors) { + var options = getDefaultCompilerOptions(configFileName); + var typeAcquisition, typingOptionstypeAcquisition; + var extendedConfigPath; + var optionsIterator = { + onSetValidOptionKeyValueInParent: function (parentOption, option, value) { + ts.Debug.assert(parentOption === "compilerOptions" || parentOption === "typeAcquisition" || parentOption === "typingOptions"); + var currentOption = parentOption === "compilerOptions" ? + options : + parentOption === "typeAcquisition" ? + (typeAcquisition || (typeAcquisition = getDefaultTypeAcquisition(configFileName))) : + (typingOptionstypeAcquisition || (typingOptionstypeAcquisition = getDefaultTypeAcquisition(configFileName))); + currentOption[option.name] = normalizeOptionValue(option, basePath, value); + }, + onSetValidOptionKeyValueInRoot: function (key, _keyNode, value, valueNode) { + switch (key) { + case "extends": + var newBase = configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath; + extendedConfigPath = getExtendsConfigPath(value, host, newBase, errors, function (message, arg0) { + return ts.createDiagnosticForNodeInSourceFile(sourceFile, valueNode, message, arg0); + }); + return; + } + }, + onSetUnknownOptionKeyValueInRoot: function (key, keyNode, _value, _valueNode) { + if (key === "excludes") { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, keyNode, ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude)); + } + } + }; + var json = convertToObjectWorker(sourceFile, errors, /*returnValue*/ true, getTsconfigRootOptionsMap(), optionsIterator); + if (!typeAcquisition) { + if (typingOptionstypeAcquisition) { + typeAcquisition = (typingOptionstypeAcquisition.enableAutoDiscovery !== undefined) ? + { + enable: typingOptionstypeAcquisition.enableAutoDiscovery, + include: typingOptionstypeAcquisition.include, + exclude: typingOptionstypeAcquisition.exclude + } : + typingOptionstypeAcquisition; + } + else { + typeAcquisition = getDefaultTypeAcquisition(configFileName); + } + } + return { raw: json, options: options, typeAcquisition: typeAcquisition, extendedConfigPath: extendedConfigPath }; + } + function getExtendsConfigPath(extendedConfig, host, basePath, errors, createDiagnostic) { + extendedConfig = ts.normalizeSlashes(extendedConfig); + if (ts.isRootedDiskPath(extendedConfig) || ts.startsWith(extendedConfig, "./") || ts.startsWith(extendedConfig, "../")) { + var extendedConfigPath = ts.getNormalizedAbsolutePath(extendedConfig, basePath); + if (!host.fileExists(extendedConfigPath) && !ts.endsWith(extendedConfigPath, ".json" /* Json */)) { + extendedConfigPath = extendedConfigPath + ".json"; + if (!host.fileExists(extendedConfigPath)) { + errors.push(createDiagnostic(ts.Diagnostics.File_0_does_not_exist, extendedConfig)); + return undefined; + } + } + return extendedConfigPath; + } + // If the path isn't a rooted or relative path, resolve like a module + var resolved = ts.nodeModuleNameResolver(extendedConfig, ts.combinePaths(basePath, "tsconfig.json"), { moduleResolution: ts.ModuleResolutionKind.NodeJs }, host, /*cache*/ undefined, /*projectRefs*/ undefined, /*lookupConfig*/ true); + if (resolved.resolvedModule) { + return resolved.resolvedModule.resolvedFileName; + } + errors.push(createDiagnostic(ts.Diagnostics.File_0_does_not_exist, extendedConfig)); + return undefined; + } + function getExtendedConfig(sourceFile, extendedConfigPath, host, basePath, resolutionStack, errors) { + var _a; + var extendedResult = readJsonConfigFile(extendedConfigPath, function (path) { return host.readFile(path); }); + if (sourceFile) { + sourceFile.extendedSourceFiles = [extendedResult.fileName]; + } + if (extendedResult.parseDiagnostics.length) { + errors.push.apply(errors, extendedResult.parseDiagnostics); + return undefined; + } + var extendedDirname = ts.getDirectoryPath(extendedConfigPath); + var extendedConfig = parseConfig(/*json*/ undefined, extendedResult, host, extendedDirname, ts.getBaseFileName(extendedConfigPath), resolutionStack, errors); + if (sourceFile && extendedResult.extendedSourceFiles) { + (_a = sourceFile.extendedSourceFiles).push.apply(_a, extendedResult.extendedSourceFiles); + } + if (isSuccessfulParsedTsconfig(extendedConfig)) { + // Update the paths to reflect base path + var relativeDifference_1 = ts.convertToRelativePath(extendedDirname, basePath, ts.identity); + var updatePath_1 = function (path) { return ts.isRootedDiskPath(path) ? path : ts.combinePaths(relativeDifference_1, path); }; + var mapPropertiesInRawIfNotUndefined = function (propertyName) { + if (raw_2[propertyName]) { + raw_2[propertyName] = ts.map(raw_2[propertyName], updatePath_1); + } + }; + var raw_2 = extendedConfig.raw; + mapPropertiesInRawIfNotUndefined("include"); + mapPropertiesInRawIfNotUndefined("exclude"); + mapPropertiesInRawIfNotUndefined("files"); + } + return extendedConfig; + } + function convertCompileOnSaveOptionFromJson(jsonOption, basePath, errors) { + if (!ts.hasProperty(jsonOption, ts.compileOnSaveCommandLineOption.name)) { + return false; + } + var result = convertJsonOption(ts.compileOnSaveCommandLineOption, jsonOption.compileOnSave, basePath, errors); + return typeof result === "boolean" && result; + } + function convertCompilerOptionsFromJson(jsonOptions, basePath, configFileName) { + var errors = []; + var options = convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName); + return { options: options, errors: errors }; + } + ts.convertCompilerOptionsFromJson = convertCompilerOptionsFromJson; + function convertTypeAcquisitionFromJson(jsonOptions, basePath, configFileName) { + var errors = []; + var options = convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName); + return { options: options, errors: errors }; + } + ts.convertTypeAcquisitionFromJson = convertTypeAcquisitionFromJson; + function getDefaultCompilerOptions(configFileName) { + var options = configFileName && ts.getBaseFileName(configFileName) === "jsconfig.json" + ? { allowJs: true, maxNodeModuleJsDepth: 2, allowSyntheticDefaultImports: true, skipLibCheck: true, noEmit: true } + : {}; + return options; + } + function convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName) { + var options = getDefaultCompilerOptions(configFileName); + convertOptionsFromJson(ts.optionDeclarations, jsonOptions, basePath, options, ts.Diagnostics.Unknown_compiler_option_0, errors); + if (configFileName) { + options.configFilePath = ts.normalizeSlashes(configFileName); + } + return options; + } + function getDefaultTypeAcquisition(configFileName) { + return { enable: !!configFileName && ts.getBaseFileName(configFileName) === "jsconfig.json", include: [], exclude: [] }; + } + function convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName) { + var options = getDefaultTypeAcquisition(configFileName); + var typeAcquisition = convertEnableAutoDiscoveryToEnable(jsonOptions); + convertOptionsFromJson(ts.typeAcquisitionDeclarations, typeAcquisition, basePath, options, ts.Diagnostics.Unknown_type_acquisition_option_0, errors); + return options; + } + function convertOptionsFromJson(optionDeclarations, jsonOptions, basePath, defaultOptions, diagnosticMessage, errors) { + if (!jsonOptions) { + return; + } + var optionNameMap = commandLineOptionsToMap(optionDeclarations); + for (var id in jsonOptions) { + var opt = optionNameMap.get(id); + if (opt) { + defaultOptions[opt.name] = convertJsonOption(opt, jsonOptions[id], basePath, errors); + } + else { + errors.push(ts.createCompilerDiagnostic(diagnosticMessage, id)); + } + } + } + function convertJsonOption(opt, value, basePath, errors) { + if (isCompilerOptionsValue(opt, value)) { + var optType = opt.type; + if (optType === "list" && ts.isArray(value)) { + return convertJsonOptionOfListType(opt, value, basePath, errors); + } + else if (!ts.isString(optType)) { + return convertJsonOptionOfCustomType(opt, value, errors); + } + return normalizeNonListOptionValue(opt, basePath, value); + } + else { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, opt.name, getCompilerOptionValueTypeString(opt))); + } + } + function normalizeOptionValue(option, basePath, value) { + if (isNullOrUndefined(value)) + return undefined; + if (option.type === "list") { + var listOption_1 = option; + if (listOption_1.element.isFilePath || !ts.isString(listOption_1.element.type)) { + return ts.filter(ts.map(value, function (v) { return normalizeOptionValue(listOption_1.element, basePath, v); }), function (v) { return !!v; }); + } + return value; + } + else if (!ts.isString(option.type)) { + return option.type.get(ts.isString(value) ? value.toLowerCase() : value); + } + return normalizeNonListOptionValue(option, basePath, value); + } + function normalizeNonListOptionValue(option, basePath, value) { + if (option.isFilePath) { + value = ts.normalizePath(ts.combinePaths(basePath, value)); + if (value === "") { + value = "."; + } + } + return value; + } + function convertJsonOptionOfCustomType(opt, value, errors) { + if (isNullOrUndefined(value)) + return undefined; + var key = value.toLowerCase(); + var val = opt.type.get(key); + if (val !== undefined) { + return val; + } + else { + errors.push(createCompilerDiagnosticForInvalidCustomType(opt)); + } + } + function convertJsonOptionOfListType(option, values, basePath, errors) { + return ts.filter(ts.map(values, function (v) { return convertJsonOption(option.element, v, basePath, errors); }), function (v) { return !!v; }); + } + function trimString(s) { + return typeof s.trim === "function" ? s.trim() : s.replace(/^[\s]+|[\s]+$/g, ""); + } + /** + * Tests for a path that ends in a recursive directory wildcard. + * Matches **, \**, **\, and \**\, but not a**b. + * + * NOTE: used \ in place of / above to avoid issues with multiline comments. + * + * Breakdown: + * (^|\/) # matches either the beginning of the string or a directory separator. + * \*\* # matches the recursive directory wildcard "**". + * \/?$ # matches an optional trailing directory separator at the end of the string. + */ + var invalidTrailingRecursionPattern = /(^|\/)\*\*\/?$/; + /** + * Tests for a path where .. appears after a recursive directory wildcard. + * Matches **\..\*, **\a\..\*, and **\.., but not ..\**\* + * + * NOTE: used \ in place of / above to avoid issues with multiline comments. + * + * Breakdown: + * (^|\/) # matches either the beginning of the string or a directory separator. + * \*\*\/ # matches a recursive directory wildcard "**" followed by a directory separator. + * (.*\/)? # optionally matches any number of characters followed by a directory separator. + * \.\. # matches a parent directory path component ".." + * ($|\/) # matches either the end of the string or a directory separator. + */ + var invalidDotDotAfterRecursiveWildcardPattern = /(^|\/)\*\*\/(.*\/)?\.\.($|\/)/; + /** + * Tests for a path containing a wildcard character in a directory component of the path. + * Matches \*\, \?\, and \a*b\, but not \a\ or \a\*. + * + * NOTE: used \ in place of / above to avoid issues with multiline comments. + * + * Breakdown: + * \/ # matches a directory separator. + * [^/]*? # matches any number of characters excluding directory separators (non-greedy). + * [*?] # matches either a wildcard character (* or ?) + * [^/]* # matches any number of characters excluding directory separators (greedy). + * \/ # matches a directory separator. + */ + var watchRecursivePattern = /\/[^/]*?[*?][^/]*\//; + /** + * Matches the portion of a wildcard path that does not contain wildcards. + * Matches \a of \a\*, or \a\b\c of \a\b\c\?\d. + * + * NOTE: used \ in place of / above to avoid issues with multiline comments. + * + * Breakdown: + * ^ # matches the beginning of the string + * [^*?]* # matches any number of non-wildcard characters + * (?=\/[^/]*[*?]) # lookahead that matches a directory separator followed by + * # a path component that contains at least one wildcard character (* or ?). + */ + var wildcardDirectoryPattern = /^[^*?]*(?=\/[^/]*[*?])/; + /** + * Expands an array of file specifications. + * + * @param filesSpecs The literal file names to include. + * @param includeSpecs The wildcard file specifications to include. + * @param excludeSpecs The wildcard file specifications to exclude. + * @param basePath The base path for any relative file specifications. + * @param options Compiler options. + * @param host The host used to resolve files and directories. + * @param errors An array for diagnostic reporting. + */ + function matchFileNames(filesSpecs, includeSpecs, excludeSpecs, basePath, options, host, errors, extraFileExtensions, jsonSourceFile) { + basePath = ts.normalizePath(basePath); + var validatedIncludeSpecs, validatedExcludeSpecs; + // The exclude spec list is converted into a regular expression, which allows us to quickly + // test whether a file or directory should be excluded before recursively traversing the + // file system. + if (includeSpecs) { + validatedIncludeSpecs = validateSpecs(includeSpecs, errors, /*allowTrailingRecursion*/ false, jsonSourceFile, "include"); + } + if (excludeSpecs) { + validatedExcludeSpecs = validateSpecs(excludeSpecs, errors, /*allowTrailingRecursion*/ true, jsonSourceFile, "exclude"); + } + // Wildcard directories (provided as part of a wildcard path) are stored in a + // file map that marks whether it was a regular wildcard match (with a `*` or `?` token), + // or a recursive directory. This information is used by filesystem watchers to monitor for + // new entries in these paths. + var wildcardDirectories = getWildcardDirectories(validatedIncludeSpecs, validatedExcludeSpecs, basePath, host.useCaseSensitiveFileNames); + var spec = { filesSpecs: filesSpecs, includeSpecs: includeSpecs, excludeSpecs: excludeSpecs, validatedIncludeSpecs: validatedIncludeSpecs, validatedExcludeSpecs: validatedExcludeSpecs, wildcardDirectories: wildcardDirectories }; + return getFileNamesFromConfigSpecs(spec, basePath, options, host, extraFileExtensions); + } + /** + * Gets the file names from the provided config file specs that contain, files, include, exclude and + * other properties needed to resolve the file names + * @param spec The config file specs extracted with file names to include, wildcards to include/exclude and other details + * @param basePath The base path for any relative file specifications. + * @param options Compiler options. + * @param host The host used to resolve files and directories. + * @param extraFileExtensions optionaly file extra file extension information from host + */ + /* @internal */ + function getFileNamesFromConfigSpecs(spec, basePath, options, host, extraFileExtensions) { + if (extraFileExtensions === void 0) { extraFileExtensions = []; } + basePath = ts.normalizePath(basePath); + var keyMapper = host.useCaseSensitiveFileNames ? ts.identity : ts.toLowerCase; + // Literal file names (provided via the "files" array in tsconfig.json) are stored in a + // file map with a possibly case insensitive key. We use this map later when when including + // wildcard paths. + var literalFileMap = ts.createMap(); + // Wildcard paths (provided via the "includes" array in tsconfig.json) are stored in a + // file map with a possibly case insensitive key. We use this map to store paths matched + // via wildcard, and to handle extension priority. + var wildcardFileMap = ts.createMap(); + // Wildcard paths of json files (provided via the "includes" array in tsconfig.json) are stored in a + // file map with a possibly case insensitive key. We use this map to store paths matched + // via wildcard of *.json kind + var wildCardJsonFileMap = ts.createMap(); + var filesSpecs = spec.filesSpecs, validatedIncludeSpecs = spec.validatedIncludeSpecs, validatedExcludeSpecs = spec.validatedExcludeSpecs, wildcardDirectories = spec.wildcardDirectories; + // Rather than requery this for each file and filespec, we query the supported extensions + // once and store it on the expansion context. + var supportedExtensions = ts.getSupportedExtensions(options, extraFileExtensions); + var supportedExtensionsWithJsonIfResolveJsonModule = ts.getSuppoertedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions); + // Literal files are always included verbatim. An "include" or "exclude" specification cannot + // remove a literal file. + if (filesSpecs) { + for (var _i = 0, filesSpecs_1 = filesSpecs; _i < filesSpecs_1.length; _i++) { + var fileName = filesSpecs_1[_i]; + var file = ts.getNormalizedAbsolutePath(fileName, basePath); + literalFileMap.set(keyMapper(file), file); + } + } + var jsonOnlyIncludeRegexes; + if (validatedIncludeSpecs && validatedIncludeSpecs.length > 0) { + var _loop_4 = function (file) { + if (ts.fileExtensionIs(file, ".json" /* Json */)) { + // Valid only if *.json specified + if (!jsonOnlyIncludeRegexes) { + var includes = validatedIncludeSpecs.filter(function (s) { return ts.endsWith(s, ".json" /* Json */); }); + var includeFilePatterns = ts.map(ts.getRegularExpressionsForWildcards(includes, basePath, "files"), function (pattern) { return "^" + pattern + "$"; }); + jsonOnlyIncludeRegexes = includeFilePatterns ? includeFilePatterns.map(function (pattern) { return ts.getRegexFromPattern(pattern, host.useCaseSensitiveFileNames); }) : ts.emptyArray; + } + var includeIndex = ts.findIndex(jsonOnlyIncludeRegexes, function (re) { return re.test(file); }); + if (includeIndex !== -1) { + var key_1 = keyMapper(file); + if (!literalFileMap.has(key_1) && !wildCardJsonFileMap.has(key_1)) { + wildCardJsonFileMap.set(key_1, file); + } + } + return "continue"; + } + // If we have already included a literal or wildcard path with a + // higher priority extension, we should skip this file. + // + // This handles cases where we may encounter both .ts and + // .d.ts (or .js if "allowJs" is enabled) in the same + // directory when they are compilation outputs. + if (hasFileWithHigherPriorityExtension(file, literalFileMap, wildcardFileMap, supportedExtensions, keyMapper)) { + return "continue"; + } + // We may have included a wildcard path with a lower priority + // extension due to the user-defined order of entries in the + // "include" array. If there is a lower priority extension in the + // same directory, we should remove it. + removeWildcardFilesWithLowerPriorityExtension(file, wildcardFileMap, supportedExtensions, keyMapper); + var key = keyMapper(file); + if (!literalFileMap.has(key) && !wildcardFileMap.has(key)) { + wildcardFileMap.set(key, file); + } + }; + for (var _a = 0, _b = host.readDirectory(basePath, supportedExtensionsWithJsonIfResolveJsonModule, validatedExcludeSpecs, validatedIncludeSpecs, /*depth*/ undefined); _a < _b.length; _a++) { + var file = _b[_a]; + _loop_4(file); + } + } + var literalFiles = ts.arrayFrom(literalFileMap.values()); + var wildcardFiles = ts.arrayFrom(wildcardFileMap.values()); + return { + fileNames: literalFiles.concat(wildcardFiles, ts.arrayFrom(wildCardJsonFileMap.values())), + wildcardDirectories: wildcardDirectories, + spec: spec + }; + } + ts.getFileNamesFromConfigSpecs = getFileNamesFromConfigSpecs; + function validateSpecs(specs, errors, allowTrailingRecursion, jsonSourceFile, specKey) { + return specs.filter(function (spec) { + var diag = specToDiagnostic(spec, allowTrailingRecursion); + if (diag !== undefined) { + errors.push(createDiagnostic(diag, spec)); + } + return diag === undefined; + }); + function createDiagnostic(message, spec) { + var element = ts.getTsConfigPropArrayElementValue(jsonSourceFile, specKey, spec); + return element ? + ts.createDiagnosticForNodeInSourceFile(jsonSourceFile, element, message, spec) : + ts.createCompilerDiagnostic(message, spec); + } + } + function specToDiagnostic(spec, allowTrailingRecursion) { + if (!allowTrailingRecursion && invalidTrailingRecursionPattern.test(spec)) { + return ts.Diagnostics.File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0; + } + else if (invalidDotDotAfterRecursiveWildcardPattern.test(spec)) { + return ts.Diagnostics.File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0; + } + } + /** + * Gets directories in a set of include patterns that should be watched for changes. + */ + function getWildcardDirectories(include, exclude, path, useCaseSensitiveFileNames) { + // We watch a directory recursively if it contains a wildcard anywhere in a directory segment + // of the pattern: + // + // /a/b/**/d - Watch /a/b recursively to catch changes to any d in any subfolder recursively + // /a/b/*/d - Watch /a/b recursively to catch any d in any immediate subfolder, even if a new subfolder is added + // /a/b - Watch /a/b recursively to catch changes to anything in any recursive subfoler + // + // We watch a directory without recursion if it contains a wildcard in the file segment of + // the pattern: + // + // /a/b/* - Watch /a/b directly to catch any new file + // /a/b/a?z - Watch /a/b directly to catch any new file matching a?z + var rawExcludeRegex = ts.getRegularExpressionForWildcard(exclude, path, "exclude"); + var excludeRegex = rawExcludeRegex && new RegExp(rawExcludeRegex, useCaseSensitiveFileNames ? "" : "i"); + var wildcardDirectories = {}; + if (include !== undefined) { + var recursiveKeys = []; + for (var _i = 0, include_1 = include; _i < include_1.length; _i++) { + var file = include_1[_i]; + var spec = ts.normalizePath(ts.combinePaths(path, file)); + if (excludeRegex && excludeRegex.test(spec)) { + continue; + } + var match = getWildcardDirectoryFromSpec(spec, useCaseSensitiveFileNames); + if (match) { + var key = match.key, flags = match.flags; + var existingFlags = wildcardDirectories[key]; + if (existingFlags === undefined || existingFlags < flags) { + wildcardDirectories[key] = flags; + if (flags === 1 /* Recursive */) { + recursiveKeys.push(key); + } + } + } + } + // Remove any subpaths under an existing recursively watched directory. + for (var key in wildcardDirectories) { + if (ts.hasProperty(wildcardDirectories, key)) { + for (var _a = 0, recursiveKeys_1 = recursiveKeys; _a < recursiveKeys_1.length; _a++) { + var recursiveKey = recursiveKeys_1[_a]; + if (key !== recursiveKey && ts.containsPath(recursiveKey, key, path, !useCaseSensitiveFileNames)) { + delete wildcardDirectories[key]; + } + } + } + } + } + return wildcardDirectories; + } + function getWildcardDirectoryFromSpec(spec, useCaseSensitiveFileNames) { + var match = wildcardDirectoryPattern.exec(spec); + if (match) { + return { + key: useCaseSensitiveFileNames ? match[0] : match[0].toLowerCase(), + flags: watchRecursivePattern.test(spec) ? 1 /* Recursive */ : 0 /* None */ + }; + } + if (ts.isImplicitGlob(spec)) { + return { key: spec, flags: 1 /* Recursive */ }; + } + return undefined; + } + /** + * Determines whether a literal or wildcard file has already been included that has a higher + * extension priority. + * + * @param file The path to the file. + * @param extensionPriority The priority of the extension. + * @param context The expansion context. + */ + function hasFileWithHigherPriorityExtension(file, literalFiles, wildcardFiles, extensions, keyMapper) { + var extensionPriority = ts.getExtensionPriority(file, extensions); + var adjustedExtensionPriority = ts.adjustExtensionPriority(extensionPriority, extensions); + for (var i = 0 /* Highest */; i < adjustedExtensionPriority; i++) { + var higherPriorityExtension = extensions[i]; + var higherPriorityPath = keyMapper(ts.changeExtension(file, higherPriorityExtension)); + if (literalFiles.has(higherPriorityPath) || wildcardFiles.has(higherPriorityPath)) { + return true; + } + } + return false; + } + /** + * Removes files included via wildcard expansion with a lower extension priority that have + * already been included. + * + * @param file The path to the file. + * @param extensionPriority The priority of the extension. + * @param context The expansion context. + */ + function removeWildcardFilesWithLowerPriorityExtension(file, wildcardFiles, extensions, keyMapper) { + var extensionPriority = ts.getExtensionPriority(file, extensions); + var nextExtensionPriority = ts.getNextLowestExtensionPriority(extensionPriority, extensions); + for (var i = nextExtensionPriority; i < extensions.length; i++) { + var lowerPriorityExtension = extensions[i]; + var lowerPriorityPath = keyMapper(ts.changeExtension(file, lowerPriorityExtension)); + wildcardFiles.delete(lowerPriorityPath); + } + } + /** + * Produces a cleaned version of compiler options with personally identifying info (aka, paths) removed. + * Also converts enum values back to strings. + */ + /* @internal */ + function convertCompilerOptionsForTelemetry(opts) { + var out = {}; + for (var key in opts) { + if (opts.hasOwnProperty(key)) { + var type = getOptionFromName(key); + if (type !== undefined) { // Ignore unknown options + out[key] = getOptionValueWithEmptyStrings(opts[key], type); + } + } + } + return out; + } + ts.convertCompilerOptionsForTelemetry = convertCompilerOptionsForTelemetry; + function getOptionValueWithEmptyStrings(value, option) { + switch (option.type) { + case "object": // "paths". Can't get any useful information from the value since we blank out strings, so just return "". + return ""; + case "string": // Could be any arbitrary string -- use empty string instead. + return ""; + case "number": // Allow numbers, but be sure to check it's actually a number. + return typeof value === "number" ? value : ""; + case "boolean": + return typeof value === "boolean" ? value : ""; + case "list": + var elementType_1 = option.element; + return ts.isArray(value) ? value.map(function (v) { return getOptionValueWithEmptyStrings(v, elementType_1); }) : ""; + default: + return ts.forEachEntry(option.type, function (optionEnumValue, optionStringValue) { + if (optionEnumValue === value) { + return optionStringValue; + } + }); // TODO: GH#18217 + } + } +})(ts || (ts = {})); +var ts; +(function (ts) { + function trace(host) { + host.trace(ts.formatMessage.apply(undefined, arguments)); + } + ts.trace = trace; + /* @internal */ + function isTraceEnabled(compilerOptions, host) { + return !!compilerOptions.traceResolution && host.trace !== undefined; + } + ts.isTraceEnabled = isTraceEnabled; + function withPackageId(packageId, r) { + return r && { path: r.path, extension: r.ext, packageId: packageId }; + } + function noPackageId(r) { + return withPackageId(/*packageId*/ undefined, r); + } + function removeIgnoredPackageId(r) { + if (r) { + ts.Debug.assert(r.packageId === undefined); + return { path: r.path, ext: r.extension }; + } + } + /** + * Kinds of file that we are currently looking for. + * Typically there is one pass with Extensions.TypeScript, then a second pass with Extensions.JavaScript. + */ + var Extensions; + (function (Extensions) { + Extensions[Extensions["TypeScript"] = 0] = "TypeScript"; + Extensions[Extensions["JavaScript"] = 1] = "JavaScript"; + Extensions[Extensions["Json"] = 2] = "Json"; + Extensions[Extensions["TSConfig"] = 3] = "TSConfig"; + Extensions[Extensions["DtsOnly"] = 4] = "DtsOnly"; /** Only '.d.ts' */ + })(Extensions || (Extensions = {})); + /** Used with `Extensions.DtsOnly` to extract the path from TypeScript results. */ + function resolvedTypeScriptOnly(resolved) { + if (!resolved) { + return undefined; + } + ts.Debug.assert(ts.extensionIsTS(resolved.extension)); + return { fileName: resolved.path, packageId: resolved.packageId }; + } + function createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations) { + return { + resolvedModule: resolved && { resolvedFileName: resolved.path, originalPath: resolved.originalPath === true ? undefined : resolved.originalPath, extension: resolved.extension, isExternalLibraryImport: isExternalLibraryImport, packageId: resolved.packageId }, + failedLookupLocations: failedLookupLocations + }; + } + function readPackageJsonField(jsonContent, fieldName, typeOfTag, state) { + if (!ts.hasProperty(jsonContent, fieldName)) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_does_not_have_a_0_field, fieldName); + } + return; + } + var value = jsonContent[fieldName]; + if (typeof value !== typeOfTag || value === null) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_1_got_2, fieldName, typeOfTag, value === null ? "null" : typeof value); + } + return; + } + return value; + } + function readPackageJsonPathField(jsonContent, fieldName, baseDirectory, state) { + var fileName = readPackageJsonField(jsonContent, fieldName, "string", state); + if (fileName === undefined) + return; + var path = ts.normalizePath(ts.combinePaths(baseDirectory, fileName)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, fileName, path); + } + return path; + } + function readPackageJsonTypesFields(jsonContent, baseDirectory, state) { + return readPackageJsonPathField(jsonContent, "typings", baseDirectory, state) + || readPackageJsonPathField(jsonContent, "types", baseDirectory, state); + } + function readPackageJsonTSConfigField(jsonContent, baseDirectory, state) { + return readPackageJsonPathField(jsonContent, "tsconfig", baseDirectory, state); + } + function readPackageJsonMainField(jsonContent, baseDirectory, state) { + return readPackageJsonPathField(jsonContent, "main", baseDirectory, state); + } + function readPackageJsonTypesVersionsField(jsonContent, state) { + var typesVersions = readPackageJsonField(jsonContent, "typesVersions", "object", state); + if (typesVersions === undefined) + return; + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_field_with_version_specific_path_mappings); + } + return typesVersions; + } + function readPackageJsonTypesVersionPaths(jsonContent, state) { + var typesVersions = readPackageJsonTypesVersionsField(jsonContent, state); + if (typesVersions === undefined) + return; + if (state.traceEnabled) { + for (var key in typesVersions) { + if (ts.hasProperty(typesVersions, key) && !ts.VersionRange.tryParse(key)) { + trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range, key); + } + } + } + var result = getPackageJsonTypesVersionsPaths(typesVersions); + if (!result) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_does_not_have_a_typesVersions_entry_that_matches_version_0, ts.versionMajorMinor); + } + return; + } + var bestVersionKey = result.version, bestVersionPaths = result.paths; + if (typeof bestVersionPaths !== "object") { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_1_got_2, "typesVersions['" + bestVersionKey + "']", "object", typeof bestVersionPaths); + } + return; + } + return result; + } + var typeScriptVersion; + /* @internal */ + function getPackageJsonTypesVersionsPaths(typesVersions) { + if (!typeScriptVersion) + typeScriptVersion = new ts.Version(ts.version); + for (var key in typesVersions) { + if (!ts.hasProperty(typesVersions, key)) + continue; + var keyRange = ts.VersionRange.tryParse(key); + if (keyRange === undefined) { + continue; + } + // return the first entry whose range matches the current compiler version. + if (keyRange.test(typeScriptVersion)) { + return { version: key, paths: typesVersions[key] }; + } + } + } + ts.getPackageJsonTypesVersionsPaths = getPackageJsonTypesVersionsPaths; + function getEffectiveTypeRoots(options, host) { + if (options.typeRoots) { + return options.typeRoots; + } + var currentDirectory; + if (options.configFilePath) { + currentDirectory = ts.getDirectoryPath(options.configFilePath); + } + else if (host.getCurrentDirectory) { + currentDirectory = host.getCurrentDirectory(); + } + if (currentDirectory !== undefined) { + return getDefaultTypeRoots(currentDirectory, host); + } + } + ts.getEffectiveTypeRoots = getEffectiveTypeRoots; + /** + * Returns the path to every node_modules/@types directory from some ancestor directory. + * Returns undefined if there are none. + */ + function getDefaultTypeRoots(currentDirectory, host) { + if (!host.directoryExists) { + return [ts.combinePaths(currentDirectory, nodeModulesAtTypes)]; + // And if it doesn't exist, tough. + } + var typeRoots; + ts.forEachAncestorDirectory(ts.normalizePath(currentDirectory), function (directory) { + var atTypes = ts.combinePaths(directory, nodeModulesAtTypes); + if (host.directoryExists(atTypes)) { + (typeRoots || (typeRoots = [])).push(atTypes); + } + return undefined; + }); + return typeRoots; + } + var nodeModulesAtTypes = ts.combinePaths("node_modules", "@types"); + /** + * @param {string | undefined} containingFile - file that contains type reference directive, can be undefined if containing file is unknown. + * This is possible in case if resolution is performed for directives specified via 'types' parameter. In this case initial path for secondary lookups + * is assumed to be the same as root directory of the project. + */ + function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host, redirectedReference) { + var traceEnabled = isTraceEnabled(options, host); + if (redirectedReference) { + options = redirectedReference.commandLine.options; + } + var failedLookupLocations = []; + var moduleResolutionState = { compilerOptions: options, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; + var typeRoots = getEffectiveTypeRoots(options, host); + if (traceEnabled) { + if (containingFile === undefined) { + if (typeRoots === undefined) { + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set, typeReferenceDirectiveName); + } + else { + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1, typeReferenceDirectiveName, typeRoots); + } + } + else { + if (typeRoots === undefined) { + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set, typeReferenceDirectiveName, containingFile); + } + else { + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_2, typeReferenceDirectiveName, containingFile, typeRoots); + } + } + if (redirectedReference) { + trace(host, ts.Diagnostics.Using_compiler_options_of_project_reference_redirect_0, redirectedReference.sourceFile.fileName); + } + } + var resolved = primaryLookup(); + var primary = true; + if (!resolved) { + resolved = secondaryLookup(); + primary = false; + } + var resolvedTypeReferenceDirective; + if (resolved) { + var fileName = resolved.fileName, packageId = resolved.packageId; + var resolvedFileName = options.preserveSymlinks ? fileName : realPath(fileName, host, traceEnabled); + if (traceEnabled) { + trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFileName, primary); + } + resolvedTypeReferenceDirective = { primary: primary, resolvedFileName: resolvedFileName, packageId: packageId, isExternalLibraryImport: pathContainsNodeModules(fileName) }; + } + return { resolvedTypeReferenceDirective: resolvedTypeReferenceDirective, failedLookupLocations: failedLookupLocations }; + function primaryLookup() { + // Check primary library paths + if (typeRoots && typeRoots.length) { + if (traceEnabled) { + trace(host, ts.Diagnostics.Resolving_with_primary_search_path_0, typeRoots.join(", ")); + } + return ts.firstDefined(typeRoots, function (typeRoot) { + var candidate = ts.combinePaths(typeRoot, typeReferenceDirectiveName); + var candidateDirectory = ts.getDirectoryPath(candidate); + var directoryExists = ts.directoryProbablyExists(candidateDirectory, host); + if (!directoryExists && traceEnabled) { + trace(host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, candidateDirectory); + } + return resolvedTypeScriptOnly(loadNodeModuleFromDirectory(Extensions.DtsOnly, candidate, !directoryExists, moduleResolutionState)); + }); + } + else { + if (traceEnabled) { + trace(host, ts.Diagnostics.Root_directory_cannot_be_determined_skipping_primary_search_paths); + } + } + } + function secondaryLookup() { + var initialLocationForSecondaryLookup = containingFile && ts.getDirectoryPath(containingFile); + if (initialLocationForSecondaryLookup !== undefined) { + // check secondary locations + if (traceEnabled) { + trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup); + } + var result = void 0; + if (!ts.isExternalModuleNameRelative(typeReferenceDirectiveName)) { + var searchResult = loadModuleFromNearestNodeModulesDirectory(Extensions.DtsOnly, typeReferenceDirectiveName, initialLocationForSecondaryLookup, moduleResolutionState, /*cache*/ undefined, /*redirectedReference*/ undefined); + result = searchResult && searchResult.value; + } + else { + var candidate = ts.normalizePathAndParts(ts.combinePaths(initialLocationForSecondaryLookup, typeReferenceDirectiveName)).path; + result = nodeLoadModuleByRelativeName(Extensions.DtsOnly, candidate, /*onlyRecordFailures*/ false, moduleResolutionState, /*considerPackageJson*/ true); + } + var resolvedFile = resolvedTypeScriptOnly(result); + if (!resolvedFile && traceEnabled) { + trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName); + } + return resolvedFile; + } + else { + if (traceEnabled) { + trace(host, ts.Diagnostics.Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder); + } + } + } + } + ts.resolveTypeReferenceDirective = resolveTypeReferenceDirective; + /** + * Given a set of options, returns the set of type directive names + * that should be included for this program automatically. + * This list could either come from the config file, + * or from enumerating the types root + initial secondary types lookup location. + * More type directives might appear in the program later as a result of loading actual source files; + * this list is only the set of defaults that are implicitly included. + */ + function getAutomaticTypeDirectiveNames(options, host) { + // Use explicit type list from tsconfig.json + if (options.types) { + return options.types; + } + // Walk the primary type lookup locations + var result = []; + if (host.directoryExists && host.getDirectories) { + var typeRoots = getEffectiveTypeRoots(options, host); + if (typeRoots) { + for (var _i = 0, typeRoots_1 = typeRoots; _i < typeRoots_1.length; _i++) { + var root = typeRoots_1[_i]; + if (host.directoryExists(root)) { + for (var _a = 0, _b = host.getDirectories(root); _a < _b.length; _a++) { + var typeDirectivePath = _b[_a]; + var normalized = ts.normalizePath(typeDirectivePath); + var packageJsonPath = ts.combinePaths(root, normalized, "package.json"); + // `types-publisher` sometimes creates packages with `"typings": null` for packages that don't provide their own types. + // See `createNotNeededPackageJSON` in the types-publisher` repo. + // tslint:disable-next-line:no-null-keyword + var isNotNeededPackage = host.fileExists(packageJsonPath) && ts.readJson(packageJsonPath, host).typings === null; + if (!isNotNeededPackage) { + var baseFileName = ts.getBaseFileName(normalized); + // At this stage, skip results with leading dot. + if (baseFileName.charCodeAt(0) !== 46 /* dot */) { + // Return just the type directive names + result.push(baseFileName); + } + } + } + } + } + } + } + return result; + } + ts.getAutomaticTypeDirectiveNames = getAutomaticTypeDirectiveNames; + function createModuleResolutionCache(currentDirectory, getCanonicalFileName) { + return createModuleResolutionCacheWithMaps(createCacheWithRedirects(), createCacheWithRedirects(), currentDirectory, getCanonicalFileName); + } + ts.createModuleResolutionCache = createModuleResolutionCache; + /*@internal*/ + function createCacheWithRedirects() { + var ownMap = ts.createMap(); + var redirectsMap = ts.createMap(); + return { + ownMap: ownMap, + redirectsMap: redirectsMap, + getOrCreateMapOfCacheRedirects: getOrCreateMapOfCacheRedirects, + clear: clear + }; + function getOrCreateMapOfCacheRedirects(redirectedReference) { + if (!redirectedReference) { + return ownMap; + } + var path = redirectedReference.sourceFile.path; + var redirects = redirectsMap.get(path); + if (!redirects) { + redirects = ts.createMap(); + redirectsMap.set(path, redirects); + } + return redirects; + } + function clear() { + ownMap.clear(); + redirectsMap.clear(); + } + } + ts.createCacheWithRedirects = createCacheWithRedirects; + /*@internal*/ + function createModuleResolutionCacheWithMaps(directoryToModuleNameMap, moduleNameToDirectoryMap, currentDirectory, getCanonicalFileName) { + return { getOrCreateCacheForDirectory: getOrCreateCacheForDirectory, getOrCreateCacheForModuleName: getOrCreateCacheForModuleName }; + function getOrCreateCacheForDirectory(directoryName, redirectedReference) { + var path = ts.toPath(directoryName, currentDirectory, getCanonicalFileName); + return getOrCreateCache(directoryToModuleNameMap, redirectedReference, path, ts.createMap); + } + function getOrCreateCacheForModuleName(nonRelativeModuleName, redirectedReference) { + ts.Debug.assert(!ts.isExternalModuleNameRelative(nonRelativeModuleName)); + return getOrCreateCache(moduleNameToDirectoryMap, redirectedReference, nonRelativeModuleName, createPerModuleNameCache); + } + function getOrCreateCache(cacheWithRedirects, redirectedReference, key, create) { + var cache = cacheWithRedirects.getOrCreateMapOfCacheRedirects(redirectedReference); + var result = cache.get(key); + if (!result) { + result = create(); + cache.set(key, result); + } + return result; + } + function createPerModuleNameCache() { + var directoryPathMap = ts.createMap(); + return { get: get, set: set }; + function get(directory) { + return directoryPathMap.get(ts.toPath(directory, currentDirectory, getCanonicalFileName)); + } + /** + * At first this function add entry directory -> module resolution result to the table. + * Then it computes the set of parent folders for 'directory' that should have the same module resolution result + * and for every parent folder in set it adds entry: parent -> module resolution. . + * Lets say we first directory name: /a/b/c/d/e and resolution result is: /a/b/bar.ts. + * Set of parent folders that should have the same result will be: + * [ + * /a/b/c/d, /a/b/c, /a/b + * ] + * this means that request for module resolution from file in any of these folder will be immediately found in cache. + */ + function set(directory, result) { + var path = ts.toPath(directory, currentDirectory, getCanonicalFileName); + // if entry is already in cache do nothing + if (directoryPathMap.has(path)) { + return; + } + directoryPathMap.set(path, result); + var resolvedFileName = result.resolvedModule && + (result.resolvedModule.originalPath || result.resolvedModule.resolvedFileName); + // find common prefix between directory and resolved file name + // this common prefix should be the shortest path that has the same resolution + // directory: /a/b/c/d/e + // resolvedFileName: /a/b/foo.d.ts + // commonPrefix: /a/b + // for failed lookups cache the result for every directory up to root + var commonPrefix = resolvedFileName && getCommonPrefix(path, resolvedFileName); + var current = path; + while (current !== commonPrefix) { + var parent = ts.getDirectoryPath(current); + if (parent === current || directoryPathMap.has(parent)) { + break; + } + directoryPathMap.set(parent, result); + current = parent; + } + } + function getCommonPrefix(directory, resolution) { + var resolutionDirectory = ts.toPath(ts.getDirectoryPath(resolution), currentDirectory, getCanonicalFileName); + // find first position where directory and resolution differs + var i = 0; + var limit = Math.min(directory.length, resolutionDirectory.length); + while (i < limit && directory.charCodeAt(i) === resolutionDirectory.charCodeAt(i)) { + i++; + } + if (i === directory.length && (resolutionDirectory.length === i || resolutionDirectory[i] === ts.directorySeparator)) { + return directory; + } + var rootLength = ts.getRootLength(directory); + if (i < rootLength) { + return undefined; + } + var sep = directory.lastIndexOf(ts.directorySeparator, i - 1); + if (sep === -1) { + return undefined; + } + return directory.substr(0, Math.max(sep, rootLength)); + } + } + } + ts.createModuleResolutionCacheWithMaps = createModuleResolutionCacheWithMaps; + function resolveModuleNameFromCache(moduleName, containingFile, cache) { + var containingDirectory = ts.getDirectoryPath(containingFile); + var perFolderCache = cache && cache.getOrCreateCacheForDirectory(containingDirectory); + return perFolderCache && perFolderCache.get(moduleName); + } + ts.resolveModuleNameFromCache = resolveModuleNameFromCache; + function resolveModuleName(moduleName, containingFile, compilerOptions, host, cache, redirectedReference) { + var traceEnabled = isTraceEnabled(compilerOptions, host); + if (redirectedReference) { + compilerOptions = redirectedReference.commandLine.options; + } + if (traceEnabled) { + trace(host, ts.Diagnostics.Resolving_module_0_from_1, moduleName, containingFile); + if (redirectedReference) { + trace(host, ts.Diagnostics.Using_compiler_options_of_project_reference_redirect_0, redirectedReference.sourceFile.fileName); + } + } + var containingDirectory = ts.getDirectoryPath(containingFile); + var perFolderCache = cache && cache.getOrCreateCacheForDirectory(containingDirectory, redirectedReference); + var result = perFolderCache && perFolderCache.get(moduleName); + if (result) { + if (traceEnabled) { + trace(host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory); + } + } + else { + var moduleResolution = compilerOptions.moduleResolution; + if (moduleResolution === undefined) { + moduleResolution = ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS ? ts.ModuleResolutionKind.NodeJs : ts.ModuleResolutionKind.Classic; + if (traceEnabled) { + trace(host, ts.Diagnostics.Module_resolution_kind_is_not_specified_using_0, ts.ModuleResolutionKind[moduleResolution]); + } + } + else { + if (traceEnabled) { + trace(host, ts.Diagnostics.Explicitly_specified_module_resolution_kind_Colon_0, ts.ModuleResolutionKind[moduleResolution]); + } + } + switch (moduleResolution) { + case ts.ModuleResolutionKind.NodeJs: + result = nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference); + break; + case ts.ModuleResolutionKind.Classic: + result = classicNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference); + break; + default: + return ts.Debug.fail("Unexpected moduleResolution: " + moduleResolution); + } + if (perFolderCache) { + perFolderCache.set(moduleName, result); + if (!ts.isExternalModuleNameRelative(moduleName)) { + // put result in per-module name cache + cache.getOrCreateCacheForModuleName(moduleName, redirectedReference).set(containingDirectory, result); + } + } + } + if (traceEnabled) { + if (result.resolvedModule) { + trace(host, ts.Diagnostics.Module_name_0_was_successfully_resolved_to_1, moduleName, result.resolvedModule.resolvedFileName); + } + else { + trace(host, ts.Diagnostics.Module_name_0_was_not_resolved, moduleName); + } + } + return result; + } + ts.resolveModuleName = resolveModuleName; + /** + * Any module resolution kind can be augmented with optional settings: 'baseUrl', 'paths' and 'rootDirs' - they are used to + * mitigate differences between design time structure of the project and its runtime counterpart so the same import name + * can be resolved successfully by TypeScript compiler and runtime module loader. + * If these settings are set then loading procedure will try to use them to resolve module name and it can of failure it will + * fallback to standard resolution routine. + * + * - baseUrl - this setting controls how non-relative module names are resolved. If this setting is specified then non-relative + * names will be resolved relative to baseUrl: i.e. if baseUrl is '/a/b' then candidate location to resolve module name 'c/d' will + * be '/a/b/c/d' + * - paths - this setting can only be used when baseUrl is specified. allows to tune how non-relative module names + * will be resolved based on the content of the module name. + * Structure of 'paths' compiler options + * 'paths': { + * pattern-1: [...substitutions], + * pattern-2: [...substitutions], + * ... + * pattern-n: [...substitutions] + * } + * Pattern here is a string that can contain zero or one '*' character. During module resolution module name will be matched against + * all patterns in the list. Matching for patterns that don't contain '*' means that module name must be equal to pattern respecting the case. + * If pattern contains '*' then to match pattern "*" module name must start with the and end with . + * denotes part of the module name between and . + * If module name can be matches with multiple patterns then pattern with the longest prefix will be picked. + * After selecting pattern we'll use list of substitutions to get candidate locations of the module and the try to load module + * from the candidate location. + * Substitution is a string that can contain zero or one '*'. To get candidate location from substitution we'll pick every + * substitution in the list and replace '*' with string. If candidate location is not rooted it + * will be converted to absolute using baseUrl. + * For example: + * baseUrl: /a/b/c + * "paths": { + * // match all module names + * "*": [ + * "*", // use matched name as is, + * // will be looked as /a/b/c/ + * + * "folder1/*" // substitution will convert matched name to 'folder1/', + * // since it is not rooted then final candidate location will be /a/b/c/folder1/ + * ], + * // match module names that start with 'components/' + * "components/*": [ "/root/components/*" ] // substitution will convert /components/folder1/ to '/root/components/folder1/', + * // it is rooted so it will be final candidate location + * } + * + * 'rootDirs' allows the project to be spreaded across multiple locations and resolve modules with relative names as if + * they were in the same location. For example lets say there are two files + * '/local/src/content/file1.ts' + * '/shared/components/contracts/src/content/protocols/file2.ts' + * After bundling content of '/shared/components/contracts/src' will be merged with '/local/src' so + * if file1 has the following import 'import {x} from "./protocols/file2"' it will be resolved successfully in runtime. + * 'rootDirs' provides the way to tell compiler that in order to get the whole project it should behave as if content of all + * root dirs were merged together. + * I.e. for the example above 'rootDirs' will have two entries: [ '/local/src', '/shared/components/contracts/src' ]. + * Compiler will first convert './protocols/file2' into absolute path relative to the location of containing file: + * '/local/src/content/protocols/file2' and try to load it - failure. + * Then it will search 'rootDirs' looking for a longest matching prefix of this absolute path and if such prefix is found - absolute path will + * be converted to a path relative to found rootDir entry './content/protocols/file2' (*). As a last step compiler will check all remaining + * entries in 'rootDirs', use them to build absolute path out of (*) and try to resolve module from this location. + */ + function tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, state) { + var resolved = tryLoadModuleUsingPathsIfEligible(extensions, moduleName, loader, state); + if (resolved) + return resolved.value; + if (!ts.isExternalModuleNameRelative(moduleName)) { + return tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, state); + } + else { + return tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, state); + } + } + function tryLoadModuleUsingPathsIfEligible(extensions, moduleName, loader, state) { + var _a = state.compilerOptions, baseUrl = _a.baseUrl, paths = _a.paths; + if (baseUrl && paths && !ts.pathIsRelative(moduleName)) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, baseUrl, moduleName); + trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName); + } + return tryLoadModuleUsingPaths(extensions, moduleName, baseUrl, paths, loader, /*onlyRecordFailures*/ false, state); + } + } + function tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, state) { + if (!state.compilerOptions.rootDirs) { + return undefined; + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0, moduleName); + } + var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); + var matchedRootDir; + var matchedNormalizedPrefix; + for (var _i = 0, _a = state.compilerOptions.rootDirs; _i < _a.length; _i++) { + var rootDir = _a[_i]; + // rootDirs are expected to be absolute + // in case of tsconfig.json this will happen automatically - compiler will expand relative names + // using location of tsconfig.json as base location + var normalizedRoot = ts.normalizePath(rootDir); + if (!ts.endsWith(normalizedRoot, ts.directorySeparator)) { + normalizedRoot += ts.directorySeparator; + } + var isLongestMatchingPrefix = ts.startsWith(candidate, normalizedRoot) && + (matchedNormalizedPrefix === undefined || matchedNormalizedPrefix.length < normalizedRoot.length); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Checking_if_0_is_the_longest_matching_prefix_for_1_2, normalizedRoot, candidate, isLongestMatchingPrefix); + } + if (isLongestMatchingPrefix) { + matchedNormalizedPrefix = normalizedRoot; + matchedRootDir = rootDir; + } + } + if (matchedNormalizedPrefix) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Longest_matching_prefix_for_0_is_1, candidate, matchedNormalizedPrefix); + } + var suffix = candidate.substr(matchedNormalizedPrefix.length); + // first - try to load from a initial location + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, matchedNormalizedPrefix, candidate); + } + var resolvedFileName = loader(extensions, candidate, !ts.directoryProbablyExists(containingDirectory, state.host), state); + if (resolvedFileName) { + return resolvedFileName; + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Trying_other_entries_in_rootDirs); + } + // then try to resolve using remaining entries in rootDirs + for (var _b = 0, _c = state.compilerOptions.rootDirs; _b < _c.length; _b++) { + var rootDir = _c[_b]; + if (rootDir === matchedRootDir) { + // skip the initially matched entry + continue; + } + var candidate_1 = ts.combinePaths(ts.normalizePath(rootDir), suffix); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, rootDir, candidate_1); + } + var baseDirectory = ts.getDirectoryPath(candidate_1); + var resolvedFileName_1 = loader(extensions, candidate_1, !ts.directoryProbablyExists(baseDirectory, state.host), state); + if (resolvedFileName_1) { + return resolvedFileName_1; + } + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Module_resolution_using_rootDirs_has_failed); + } + } + return undefined; + } + function tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, state) { + var baseUrl = state.compilerOptions.baseUrl; + if (!baseUrl) { + return undefined; + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, baseUrl, moduleName); + } + var candidate = ts.normalizePath(ts.combinePaths(baseUrl, moduleName)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, baseUrl, candidate); + } + return loader(extensions, candidate, !ts.directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); + } + /** + * Expose resolution logic to allow us to use Node module resolution logic from arbitrary locations. + * No way to do this with `require()`: https://github.com/nodejs/node/issues/5963 + * Throws an error if the module can't be resolved. + */ + /* @internal */ + function resolveJSModule(moduleName, initialDir, host) { + var _a = tryResolveJSModuleWorker(moduleName, initialDir, host), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; + if (!resolvedModule) { + throw new Error("Could not resolve JS module '" + moduleName + "' starting at '" + initialDir + "'. Looked in: " + failedLookupLocations.join(", ")); + } + return resolvedModule.resolvedFileName; + } + ts.resolveJSModule = resolveJSModule; + /* @internal */ + function tryResolveJSModule(moduleName, initialDir, host) { + var resolvedModule = tryResolveJSModuleWorker(moduleName, initialDir, host).resolvedModule; + return resolvedModule && resolvedModule.resolvedFileName; + } + ts.tryResolveJSModule = tryResolveJSModule; + var jsOnlyExtensions = [Extensions.JavaScript]; + var tsExtensions = [Extensions.TypeScript, Extensions.JavaScript]; + var tsPlusJsonExtensions = tsExtensions.concat([Extensions.Json]); + var tsconfigExtensions = [Extensions.TSConfig]; + function tryResolveJSModuleWorker(moduleName, initialDir, host) { + return nodeModuleNameResolverWorker(moduleName, initialDir, { moduleResolution: ts.ModuleResolutionKind.NodeJs, allowJs: true }, host, /*cache*/ undefined, jsOnlyExtensions, /*redirectedReferences*/ undefined); + } + function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference, lookupConfig) { + return nodeModuleNameResolverWorker(moduleName, ts.getDirectoryPath(containingFile), compilerOptions, host, cache, lookupConfig ? tsconfigExtensions : (compilerOptions.resolveJsonModule ? tsPlusJsonExtensions : tsExtensions), redirectedReference); + } + ts.nodeModuleNameResolver = nodeModuleNameResolver; + function nodeModuleNameResolverWorker(moduleName, containingDirectory, compilerOptions, host, cache, extensions, redirectedReference) { + var traceEnabled = isTraceEnabled(compilerOptions, host); + var failedLookupLocations = []; + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; + var result = ts.forEach(extensions, function (ext) { return tryResolve(ext); }); + if (result && result.value) { + var _a = result.value, resolved = _a.resolved, isExternalLibraryImport = _a.isExternalLibraryImport; + return createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations); + } + return { resolvedModule: undefined, failedLookupLocations: failedLookupLocations }; + function tryResolve(extensions) { + var loader = function (extensions, candidate, onlyRecordFailures, state) { return nodeLoadModuleByRelativeName(extensions, candidate, onlyRecordFailures, state, /*considerPackageJson*/ true); }; + var resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, state); + if (resolved) { + return toSearchResult({ resolved: resolved, isExternalLibraryImport: pathContainsNodeModules(resolved.path) }); + } + if (!ts.isExternalModuleNameRelative(moduleName)) { + if (traceEnabled) { + trace(host, ts.Diagnostics.Loading_module_0_from_node_modules_folder_target_file_type_1, moduleName, Extensions[extensions]); + } + var resolved_1 = loadModuleFromNearestNodeModulesDirectory(extensions, moduleName, containingDirectory, state, cache, redirectedReference); + if (!resolved_1) + return undefined; + var resolvedValue = resolved_1.value; + if (!compilerOptions.preserveSymlinks && resolvedValue && !resolvedValue.originalPath) { + var path = realPath(resolvedValue.path, host, traceEnabled); + var originalPath = path === resolvedValue.path ? undefined : resolvedValue.path; + resolvedValue = __assign({}, resolvedValue, { path: path, originalPath: originalPath }); + } + // For node_modules lookups, get the real path so that multiple accesses to an `npm link`-ed module do not create duplicate files. + return { value: resolvedValue && { resolved: resolvedValue, isExternalLibraryImport: true } }; + } + else { + var _a = ts.normalizePathAndParts(ts.combinePaths(containingDirectory, moduleName)), candidate = _a.path, parts = _a.parts; + var resolved_2 = nodeLoadModuleByRelativeName(extensions, candidate, /*onlyRecordFailures*/ false, state, /*considerPackageJson*/ true); + // Treat explicit "node_modules" import as an external library import. + return resolved_2 && toSearchResult({ resolved: resolved_2, isExternalLibraryImport: ts.contains(parts, "node_modules") }); + } + } + } + function realPath(path, host, traceEnabled) { + if (!host.realpath) { + return path; + } + var real = ts.normalizePath(host.realpath(path)); + if (traceEnabled) { + trace(host, ts.Diagnostics.Resolving_real_path_for_0_result_1, path, real); + } + ts.Debug.assert(host.fileExists(real), path + " linked to nonexistent file " + real); // tslint:disable-line + return real; + } + function nodeLoadModuleByRelativeName(extensions, candidate, onlyRecordFailures, state, considerPackageJson) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1, candidate, Extensions[extensions]); + } + if (!ts.hasTrailingDirectorySeparator(candidate)) { + if (!onlyRecordFailures) { + var parentOfCandidate = ts.getDirectoryPath(candidate); + if (!ts.directoryProbablyExists(parentOfCandidate, state.host)) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, parentOfCandidate); + } + onlyRecordFailures = true; + } + } + var resolvedFromFile = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state); + if (resolvedFromFile) { + var nm = considerPackageJson ? parseNodeModuleFromPath(resolvedFromFile) : undefined; + var packageInfo = nm && getPackageJsonInfo(nm.packageDirectory, nm.subModuleName, /*onlyRecordFailures*/ false, state); + var packageId = packageInfo && packageInfo.packageId; + return withPackageId(packageId, resolvedFromFile); + } + } + if (!onlyRecordFailures) { + var candidateExists = ts.directoryProbablyExists(candidate, state.host); + if (!candidateExists) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, candidate); + } + onlyRecordFailures = true; + } + } + return loadNodeModuleFromDirectory(extensions, candidate, onlyRecordFailures, state, considerPackageJson); + } + /*@internal*/ + ts.nodeModulesPathPart = "/node_modules/"; + /*@internal*/ + function pathContainsNodeModules(path) { + return ts.stringContains(path, ts.nodeModulesPathPart); + } + ts.pathContainsNodeModules = pathContainsNodeModules; + /** + * This will be called on the successfully resolved path from `loadModuleFromFile`. + * (Not neeeded for `loadModuleFromNodeModules` as that looks up the `package.json` as part of resolution.) + * + * packageDirectory is the directory of the package itself. + * subModuleName is the path within the package. + * For `blah/node_modules/foo/index.d.ts` this is { packageDirectory: "foo", subModuleName: "index.d.ts" }. (Part before "/node_modules/" is ignored.) + * For `/node_modules/foo/bar.d.ts` this is { packageDirectory: "foo", subModuleName": "bar/index.d.ts" }. + * For `/node_modules/@types/foo/bar/index.d.ts` this is { packageDirectory: "@types/foo", subModuleName: "bar/index.d.ts" }. + * For `/node_modules/foo/bar/index.d.ts` this is { packageDirectory: "foo", subModuleName": "bar/index.d.ts" }. + */ + function parseNodeModuleFromPath(resolved) { + var path = ts.normalizePath(resolved.path); + var idx = path.lastIndexOf(ts.nodeModulesPathPart); + if (idx === -1) { + return undefined; + } + var indexAfterNodeModules = idx + ts.nodeModulesPathPart.length; + var indexAfterPackageName = moveToNextDirectorySeparatorIfAvailable(path, indexAfterNodeModules); + if (path.charCodeAt(indexAfterNodeModules) === 64 /* at */) { + indexAfterPackageName = moveToNextDirectorySeparatorIfAvailable(path, indexAfterPackageName); + } + var packageDirectory = path.slice(0, indexAfterPackageName); + var subModuleName = ts.removeExtension(path.slice(indexAfterPackageName + 1), resolved.ext) + ".d.ts" /* Dts */; + return { packageDirectory: packageDirectory, subModuleName: subModuleName }; + } + function moveToNextDirectorySeparatorIfAvailable(path, prevSeparatorIndex) { + var nextSeparatorIndex = path.indexOf(ts.directorySeparator, prevSeparatorIndex + 1); + return nextSeparatorIndex === -1 ? prevSeparatorIndex : nextSeparatorIndex; + } + function addExtensionAndIndex(path) { + if (path === "") { + return "index.d.ts"; + } + if (ts.endsWith(path, ".d.ts")) { + return path; + } + if (path === "index" || ts.endsWith(path, "/index")) { + return path + ".d.ts"; + } + return path + "/index.d.ts"; + } + function loadModuleFromFileNoPackageId(extensions, candidate, onlyRecordFailures, state) { + return noPackageId(loadModuleFromFile(extensions, candidate, onlyRecordFailures, state)); + } + /** + * @param {boolean} onlyRecordFailures - if true then function won't try to actually load files but instead record all attempts as failures. This flag is necessary + * in cases when we know upfront that all load attempts will fail (because containing folder does not exists) however we still need to record all failed lookup locations. + */ + function loadModuleFromFile(extensions, candidate, onlyRecordFailures, state) { + if (extensions === Extensions.Json || extensions === Extensions.TSConfig) { + var extensionLess = ts.tryRemoveExtension(candidate, ".json" /* Json */); + return (extensionLess === undefined && extensions === Extensions.Json) ? undefined : tryAddingExtensions(extensionLess || candidate, extensions, onlyRecordFailures, state); + } + // First, try adding an extension. An import of "foo" could be matched by a file "foo.ts", or "foo.js" by "foo.js.ts" + var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, onlyRecordFailures, state); + if (resolvedByAddingExtension) { + return resolvedByAddingExtension; + } + // If that didn't work, try stripping a ".js" or ".jsx" extension and replacing it with a TypeScript one; + // e.g. "./foo.js" can be matched by "./foo.ts" or "./foo.d.ts" + if (ts.hasJSFileExtension(candidate)) { + var extensionless = ts.removeFileExtension(candidate); + if (state.traceEnabled) { + var extension = candidate.substring(extensionless.length); + trace(state.host, ts.Diagnostics.File_name_0_has_a_1_extension_stripping_it, candidate, extension); + } + return tryAddingExtensions(extensionless, extensions, onlyRecordFailures, state); + } + } + /** Try to return an existing file that adds one of the `extensions` to `candidate`. */ + function tryAddingExtensions(candidate, extensions, onlyRecordFailures, state) { + if (!onlyRecordFailures) { + // check if containing folder exists - if it doesn't then just record failures for all supported extensions without disk probing + var directory = ts.getDirectoryPath(candidate); + if (directory) { + onlyRecordFailures = !ts.directoryProbablyExists(directory, state.host); + } + } + switch (extensions) { + case Extensions.DtsOnly: + return tryExtension(".d.ts" /* Dts */); + case Extensions.TypeScript: + return tryExtension(".ts" /* Ts */) || tryExtension(".tsx" /* Tsx */) || tryExtension(".d.ts" /* Dts */); + case Extensions.JavaScript: + return tryExtension(".js" /* Js */) || tryExtension(".jsx" /* Jsx */); + case Extensions.TSConfig: + case Extensions.Json: + return tryExtension(".json" /* Json */); + } + function tryExtension(ext) { + var path = tryFile(candidate + ext, onlyRecordFailures, state); + return path === undefined ? undefined : { path: path, ext: ext }; + } + } + /** Return the file if it exists. */ + function tryFile(fileName, onlyRecordFailures, state) { + if (!onlyRecordFailures) { + if (state.host.fileExists(fileName)) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_exist_use_it_as_a_name_resolution_result, fileName); + } + return fileName; + } + else { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_does_not_exist, fileName); + } + } + } + state.failedLookupLocations.push(fileName); + return undefined; + } + function loadNodeModuleFromDirectory(extensions, candidate, onlyRecordFailures, state, considerPackageJson) { + if (considerPackageJson === void 0) { considerPackageJson = true; } + var packageInfo = considerPackageJson ? getPackageJsonInfo(candidate, "", onlyRecordFailures, state) : undefined; + var packageId = packageInfo && packageInfo.packageId; + var packageJsonContent = packageInfo && packageInfo.packageJsonContent; + var versionPaths = packageJsonContent && readPackageJsonTypesVersionPaths(packageJsonContent, state); + return withPackageId(packageId, loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths)); + } + function getPackageJsonInfo(packageDirectory, subModuleName, onlyRecordFailures, state) { + var host = state.host, traceEnabled = state.traceEnabled; + var directoryExists = !onlyRecordFailures && ts.directoryProbablyExists(packageDirectory, host); + var packageJsonPath = ts.combinePaths(packageDirectory, "package.json"); + if (directoryExists && host.fileExists(packageJsonPath)) { + var packageJsonContent = ts.readJson(packageJsonPath, host); + if (subModuleName === "") { // looking up the root - need to handle types/typings/main redirects for subModuleName + var path = readPackageJsonTypesFields(packageJsonContent, packageDirectory, state); + if (typeof path === "string") { + subModuleName = addExtensionAndIndex(path.substring(packageDirectory.length + 1)); + } + else { + var jsPath = readPackageJsonMainField(packageJsonContent, packageDirectory, state); + if (typeof jsPath === "string" && jsPath.length > packageDirectory.length) { + var potentialSubModule_1 = jsPath.substring(packageDirectory.length + 1); + subModuleName = (ts.forEach(ts.supportedJSExtensions, function (extension) { + return ts.tryRemoveExtension(potentialSubModule_1, extension); + }) || potentialSubModule_1) + ".d.ts" /* Dts */; + } + else { + subModuleName = "index.d.ts"; + } + } + } + if (!ts.endsWith(subModuleName, ".d.ts" /* Dts */)) { + subModuleName = addExtensionAndIndex(subModuleName); + } + var versionPaths = readPackageJsonTypesVersionPaths(packageJsonContent, state); + var packageId = typeof packageJsonContent.name === "string" && typeof packageJsonContent.version === "string" + ? { name: packageJsonContent.name, subModuleName: subModuleName, version: packageJsonContent.version } + : undefined; + if (traceEnabled) { + if (packageId) { + trace(host, ts.Diagnostics.Found_package_json_at_0_Package_ID_is_1, packageJsonPath, ts.packageIdToString(packageId)); + } + else { + trace(host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); + } + } + return { packageJsonContent: packageJsonContent, packageId: packageId, versionPaths: versionPaths }; + } + else { + if (directoryExists && traceEnabled) { + trace(host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath); + } + // record package json as one of failed lookup locations - in the future if this file will appear it will invalidate resolution results + state.failedLookupLocations.push(packageJsonPath); + } + } + function loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, jsonContent, versionPaths) { + var packageFile; + if (jsonContent) { + switch (extensions) { + case Extensions.JavaScript: + case Extensions.Json: + packageFile = readPackageJsonMainField(jsonContent, candidate, state); + break; + case Extensions.TypeScript: + // When resolving typescript modules, try resolving using main field as well + packageFile = readPackageJsonTypesFields(jsonContent, candidate, state) || readPackageJsonMainField(jsonContent, candidate, state); + break; + case Extensions.DtsOnly: + packageFile = readPackageJsonTypesFields(jsonContent, candidate, state); + break; + case Extensions.TSConfig: + packageFile = readPackageJsonTSConfigField(jsonContent, candidate, state); + break; + default: + return ts.Debug.assertNever(extensions); + } + } + var loader = function (extensions, candidate, onlyRecordFailures, state) { + var fromFile = tryFile(candidate, onlyRecordFailures, state); + if (fromFile) { + var resolved = resolvedIfExtensionMatches(extensions, fromFile); + if (resolved) { + return noPackageId(resolved); + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_has_an_unsupported_extension_so_skipping_it, fromFile); + } + } + // Even if extensions is DtsOnly, we can still look up a .ts file as a result of package.json "types" + var nextExtensions = extensions === Extensions.DtsOnly ? Extensions.TypeScript : extensions; + // Don't do package.json lookup recursively, because Node.js' package lookup doesn't. + return nodeLoadModuleByRelativeName(nextExtensions, candidate, onlyRecordFailures, state, /*considerPackageJson*/ false); + }; + var onlyRecordFailuresForPackageFile = packageFile ? !ts.directoryProbablyExists(ts.getDirectoryPath(packageFile), state.host) : undefined; + var onlyRecordFailuresForIndex = onlyRecordFailures || !ts.directoryProbablyExists(candidate, state.host); + var indexPath = ts.combinePaths(candidate, extensions === Extensions.TSConfig ? "tsconfig" : "index"); + if (versionPaths && (!packageFile || ts.containsPath(candidate, packageFile))) { + var moduleName = ts.getRelativePathFromDirectory(candidate, packageFile || indexPath, /*ignoreCase*/ false); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2, versionPaths.version, ts.version, moduleName); + } + var result = tryLoadModuleUsingPaths(extensions, moduleName, candidate, versionPaths.paths, loader, onlyRecordFailuresForPackageFile || onlyRecordFailuresForIndex, state); + if (result) { + return removeIgnoredPackageId(result.value); + } + } + // It won't have a `packageId` set, because we disabled `considerPackageJson`. + var packageFileResult = packageFile && removeIgnoredPackageId(loader(extensions, packageFile, onlyRecordFailuresForPackageFile, state)); + if (packageFileResult) + return packageFileResult; + return loadModuleFromFile(extensions, indexPath, onlyRecordFailuresForIndex, state); + } + /** Resolve from an arbitrarily specified file. Return `undefined` if it has an unsupported extension. */ + function resolvedIfExtensionMatches(extensions, path) { + var ext = ts.tryGetExtensionFromPath(path); + return ext !== undefined && extensionIsOk(extensions, ext) ? { path: path, ext: ext } : undefined; + } + /** True if `extension` is one of the supported `extensions`. */ + function extensionIsOk(extensions, extension) { + switch (extensions) { + case Extensions.JavaScript: + return extension === ".js" /* Js */ || extension === ".jsx" /* Jsx */; + case Extensions.TSConfig: + case Extensions.Json: + return extension === ".json" /* Json */; + case Extensions.TypeScript: + return extension === ".ts" /* Ts */ || extension === ".tsx" /* Tsx */ || extension === ".d.ts" /* Dts */; + case Extensions.DtsOnly: + return extension === ".d.ts" /* Dts */; + } + } + /* @internal */ + function parsePackageName(moduleName) { + var idx = moduleName.indexOf(ts.directorySeparator); + if (moduleName[0] === "@") { + idx = moduleName.indexOf(ts.directorySeparator, idx + 1); + } + return idx === -1 ? { packageName: moduleName, rest: "" } : { packageName: moduleName.slice(0, idx), rest: moduleName.slice(idx + 1) }; + } + ts.parsePackageName = parsePackageName; + function loadModuleFromNearestNodeModulesDirectory(extensions, moduleName, directory, state, cache, redirectedReference) { + return loadModuleFromNearestNodeModulesDirectoryWorker(extensions, moduleName, directory, state, /*typesScopeOnly*/ false, cache, redirectedReference); + } + function loadModuleFromNearestNodeModulesDirectoryTypesScope(moduleName, directory, state) { + // Extensions parameter here doesn't actually matter, because typesOnly ensures we're just doing @types lookup, which is always DtsOnly. + return loadModuleFromNearestNodeModulesDirectoryWorker(Extensions.DtsOnly, moduleName, directory, state, /*typesScopeOnly*/ true, /*cache*/ undefined, /*redirectedReference*/ undefined); + } + function loadModuleFromNearestNodeModulesDirectoryWorker(extensions, moduleName, directory, state, typesScopeOnly, cache, redirectedReference) { + var perModuleNameCache = cache && cache.getOrCreateCacheForModuleName(moduleName, redirectedReference); + return ts.forEachAncestorDirectory(ts.normalizeSlashes(directory), function (ancestorDirectory) { + if (ts.getBaseFileName(ancestorDirectory) !== "node_modules") { + var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, ancestorDirectory, state); + if (resolutionFromCache) { + return resolutionFromCache; + } + return toSearchResult(loadModuleFromImmediateNodeModulesDirectory(extensions, moduleName, ancestorDirectory, state, typesScopeOnly)); + } + }); + } + function loadModuleFromImmediateNodeModulesDirectory(extensions, moduleName, directory, state, typesScopeOnly) { + var nodeModulesFolder = ts.combinePaths(directory, "node_modules"); + var nodeModulesFolderExists = ts.directoryProbablyExists(nodeModulesFolder, state.host); + if (!nodeModulesFolderExists && state.traceEnabled) { + trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, nodeModulesFolder); + } + var packageResult = typesScopeOnly ? undefined : loadModuleFromSpecificNodeModulesDirectory(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, state); + if (packageResult) { + return packageResult; + } + if (extensions === Extensions.TypeScript || extensions === Extensions.DtsOnly) { + var nodeModulesAtTypes_1 = ts.combinePaths(nodeModulesFolder, "@types"); + var nodeModulesAtTypesExists = nodeModulesFolderExists; + if (nodeModulesFolderExists && !ts.directoryProbablyExists(nodeModulesAtTypes_1, state.host)) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, nodeModulesAtTypes_1); + } + nodeModulesAtTypesExists = false; + } + return loadModuleFromSpecificNodeModulesDirectory(Extensions.DtsOnly, mangleScopedPackageNameWithTrace(moduleName, state), nodeModulesAtTypes_1, nodeModulesAtTypesExists, state); + } + } + function loadModuleFromSpecificNodeModulesDirectory(extensions, moduleName, nodeModulesDirectory, nodeModulesDirectoryExists, state) { + var candidate = ts.normalizePath(ts.combinePaths(nodeModulesDirectory, moduleName)); + // First look for a nested package.json, as in `node_modules/foo/bar/package.json`. + var packageJsonContent; + var packageId; + var versionPaths; + var packageInfo = getPackageJsonInfo(candidate, "", !nodeModulesDirectoryExists, state); + if (packageInfo) { + (packageJsonContent = packageInfo.packageJsonContent, packageId = packageInfo.packageId, versionPaths = packageInfo.versionPaths); + var fromFile = loadModuleFromFile(extensions, candidate, !nodeModulesDirectoryExists, state); + if (fromFile) { + return noPackageId(fromFile); + } + var fromDirectory = loadNodeModuleFromDirectoryWorker(extensions, candidate, !nodeModulesDirectoryExists, state, packageJsonContent, versionPaths); + return withPackageId(packageId, fromDirectory); + } + var loader = function (extensions, candidate, onlyRecordFailures, state) { + var pathAndExtension = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state) || + loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths); + return withPackageId(packageId, pathAndExtension); + }; + var _a = parsePackageName(moduleName), packageName = _a.packageName, rest = _a.rest; + if (rest !== "") { // If "rest" is empty, we just did this search above. + var packageDirectory = ts.combinePaths(nodeModulesDirectory, packageName); + // Don't use a "types" or "main" from here because we're not loading the root, but a subdirectory -- just here for the packageId and path mappings. + var packageInfo_1 = getPackageJsonInfo(packageDirectory, rest, !nodeModulesDirectoryExists, state); + if (packageInfo_1) + (packageId = packageInfo_1.packageId, versionPaths = packageInfo_1.versionPaths); + if (versionPaths) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2, versionPaths.version, ts.version, rest); + } + var packageDirectoryExists = nodeModulesDirectoryExists && ts.directoryProbablyExists(packageDirectory, state.host); + var fromPaths = tryLoadModuleUsingPaths(extensions, rest, packageDirectory, versionPaths.paths, loader, !packageDirectoryExists, state); + if (fromPaths) { + return fromPaths.value; + } + } + } + return loader(extensions, candidate, !nodeModulesDirectoryExists, state); + } + function tryLoadModuleUsingPaths(extensions, moduleName, baseDirectory, paths, loader, onlyRecordFailures, state) { + var matchedPattern = ts.matchPatternOrExact(ts.getOwnKeys(paths), moduleName); + if (matchedPattern) { + var matchedStar_1 = ts.isString(matchedPattern) ? undefined : ts.matchedText(matchedPattern, moduleName); + var matchedPatternText = ts.isString(matchedPattern) ? matchedPattern : ts.patternText(matchedPattern); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText); + } + var resolved = ts.forEach(paths[matchedPatternText], function (subst) { + var path = matchedStar_1 ? subst.replace("*", matchedStar_1) : subst; + var candidate = ts.normalizePath(ts.combinePaths(baseDirectory, path)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path); + } + // A path mapping may have an extension, in contrast to an import, which should omit it. + var extension = ts.tryGetExtensionFromPath(candidate); + if (extension !== undefined) { + var path_1 = tryFile(candidate, onlyRecordFailures, state); + if (path_1 !== undefined) { + return noPackageId({ path: path_1, ext: extension }); + } + } + return loader(extensions, candidate, onlyRecordFailures || !ts.directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); + }); + return { value: resolved }; + } + } + /** Double underscores are used in DefinitelyTyped to delimit scoped packages. */ + var mangledScopedPackageSeparator = "__"; + /** For a scoped package, we must look in `@types/foo__bar` instead of `@types/@foo/bar`. */ + function mangleScopedPackageNameWithTrace(packageName, state) { + var mangled = mangleScopedPackageName(packageName); + if (state.traceEnabled && mangled !== packageName) { + trace(state.host, ts.Diagnostics.Scoped_package_detected_looking_in_0, mangled); + } + return mangled; + } + /* @internal */ + function getTypesPackageName(packageName) { + return "@types/" + mangleScopedPackageName(packageName); + } + ts.getTypesPackageName = getTypesPackageName; + /* @internal */ + function mangleScopedPackageName(packageName) { + if (ts.startsWith(packageName, "@")) { + var replaceSlash = packageName.replace(ts.directorySeparator, mangledScopedPackageSeparator); + if (replaceSlash !== packageName) { + return replaceSlash.slice(1); // Take off the "@" + } + } + return packageName; + } + ts.mangleScopedPackageName = mangleScopedPackageName; + /* @internal */ + function getPackageNameFromTypesPackageName(mangledName) { + var withoutAtTypePrefix = ts.removePrefix(mangledName, "@types/"); + if (withoutAtTypePrefix !== mangledName) { + return unmangleScopedPackageName(withoutAtTypePrefix); + } + return mangledName; + } + ts.getPackageNameFromTypesPackageName = getPackageNameFromTypesPackageName; + /* @internal */ + function unmangleScopedPackageName(typesPackageName) { + return ts.stringContains(typesPackageName, mangledScopedPackageSeparator) ? + "@" + typesPackageName.replace(mangledScopedPackageSeparator, ts.directorySeparator) : + typesPackageName; + } + ts.unmangleScopedPackageName = unmangleScopedPackageName; + function tryFindNonRelativeModuleNameInCache(cache, moduleName, containingDirectory, state) { + var _a; + var result = cache && cache.get(containingDirectory); + if (result) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory); + } + (_a = state.failedLookupLocations).push.apply(_a, result.failedLookupLocations); + return { value: result.resolvedModule && { path: result.resolvedModule.resolvedFileName, originalPath: result.resolvedModule.originalPath || true, extension: result.resolvedModule.extension, packageId: result.resolvedModule.packageId } }; + } + } + function classicNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference) { + var traceEnabled = isTraceEnabled(compilerOptions, host); + var failedLookupLocations = []; + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; + var containingDirectory = ts.getDirectoryPath(containingFile); + var resolved = tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript); + // No originalPath because classic resolution doesn't resolve realPath + return createResolvedModuleWithFailedLookupLocations(resolved && resolved.value, /*isExternalLibraryImport*/ false, failedLookupLocations); + function tryResolve(extensions) { + var resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFileNoPackageId, state); + if (resolvedUsingSettings) { + return { value: resolvedUsingSettings }; + } + if (!ts.isExternalModuleNameRelative(moduleName)) { + var perModuleNameCache_1 = cache && cache.getOrCreateCacheForModuleName(moduleName, redirectedReference); + // Climb up parent directories looking for a module. + var resolved_3 = ts.forEachAncestorDirectory(containingDirectory, function (directory) { + var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache_1, moduleName, directory, state); + if (resolutionFromCache) { + return resolutionFromCache; + } + var searchName = ts.normalizePath(ts.combinePaths(directory, moduleName)); + return toSearchResult(loadModuleFromFileNoPackageId(extensions, searchName, /*onlyRecordFailures*/ false, state)); + }); + if (resolved_3) { + return resolved_3; + } + if (extensions === Extensions.TypeScript) { + // If we didn't find the file normally, look it up in @types. + return loadModuleFromNearestNodeModulesDirectoryTypesScope(moduleName, containingDirectory, state); + } + } + else { + var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); + return toSearchResult(loadModuleFromFileNoPackageId(extensions, candidate, /*onlyRecordFailures*/ false, state)); + } + } + } + ts.classicNameResolver = classicNameResolver; + /** + * LSHost may load a module from a global cache of typings. + * This is the minumum code needed to expose that functionality; the rest is in LSHost. + */ + /* @internal */ + function loadModuleFromGlobalCache(moduleName, projectName, compilerOptions, host, globalCache) { + var traceEnabled = isTraceEnabled(compilerOptions, host); + if (traceEnabled) { + trace(host, ts.Diagnostics.Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2, projectName, moduleName, globalCache); + } + var failedLookupLocations = []; + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; + var resolved = loadModuleFromImmediateNodeModulesDirectory(Extensions.DtsOnly, moduleName, globalCache, state, /*typesScopeOnly*/ false); + return createResolvedModuleWithFailedLookupLocations(resolved, /*isExternalLibraryImport*/ true, failedLookupLocations); + } + ts.loadModuleFromGlobalCache = loadModuleFromGlobalCache; + /** + * Wraps value to SearchResult. + * @returns undefined if value is undefined or { value } otherwise + */ + function toSearchResult(value) { + return value !== undefined ? { value: value } : undefined; + } +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var ModuleInstanceState; + (function (ModuleInstanceState) { + ModuleInstanceState[ModuleInstanceState["NonInstantiated"] = 0] = "NonInstantiated"; + ModuleInstanceState[ModuleInstanceState["Instantiated"] = 1] = "Instantiated"; + ModuleInstanceState[ModuleInstanceState["ConstEnumOnly"] = 2] = "ConstEnumOnly"; + })(ModuleInstanceState = ts.ModuleInstanceState || (ts.ModuleInstanceState = {})); + function getModuleInstanceState(node) { + return node.body ? getModuleInstanceStateWorker(node.body) : 1 /* Instantiated */; + } + ts.getModuleInstanceState = getModuleInstanceState; + function getModuleInstanceStateWorker(node) { + // A module is uninstantiated if it contains only + switch (node.kind) { + // 1. interface declarations, type alias declarations + case 241 /* InterfaceDeclaration */: + case 242 /* TypeAliasDeclaration */: + return 0 /* NonInstantiated */; + // 2. const enum declarations + case 243 /* EnumDeclaration */: + if (ts.isEnumConst(node)) { + return 2 /* ConstEnumOnly */; + } + break; + // 3. non-exported import declarations + case 249 /* ImportDeclaration */: + case 248 /* ImportEqualsDeclaration */: + if (!(ts.hasModifier(node, 1 /* Export */))) { + return 0 /* NonInstantiated */; + } + break; + // 4. other uninstantiated module declarations. + case 245 /* ModuleBlock */: { + var state_1 = 0 /* NonInstantiated */; + ts.forEachChild(node, function (n) { + var childState = getModuleInstanceStateWorker(n); + switch (childState) { + case 0 /* NonInstantiated */: + // child is non-instantiated - continue searching + return; + case 2 /* ConstEnumOnly */: + // child is const enum only - record state and continue searching + state_1 = 2 /* ConstEnumOnly */; + return; + case 1 /* Instantiated */: + // child is instantiated - record state and stop + state_1 = 1 /* Instantiated */; + return true; + default: + ts.Debug.assertNever(childState); + } + }); + return state_1; + } + case 244 /* ModuleDeclaration */: + return getModuleInstanceState(node); + case 72 /* Identifier */: + // Only jsdoc typedef definition can exist in jsdoc namespace, and it should + // be considered the same as type alias + if (node.isInJSDocNamespace) { + return 0 /* NonInstantiated */; + } + } + return 1 /* Instantiated */; + } + var ContainerFlags; + (function (ContainerFlags) { + // The current node is not a container, and no container manipulation should happen before + // recursing into it. + ContainerFlags[ContainerFlags["None"] = 0] = "None"; + // The current node is a container. It should be set as the current container (and block- + // container) before recursing into it. The current node does not have locals. Examples: + // + // Classes, ObjectLiterals, TypeLiterals, Interfaces... + ContainerFlags[ContainerFlags["IsContainer"] = 1] = "IsContainer"; + // The current node is a block-scoped-container. It should be set as the current block- + // container before recursing into it. Examples: + // + // Blocks (when not parented by functions), Catch clauses, For/For-in/For-of statements... + ContainerFlags[ContainerFlags["IsBlockScopedContainer"] = 2] = "IsBlockScopedContainer"; + // The current node is the container of a control flow path. The current control flow should + // be saved and restored, and a new control flow initialized within the container. + ContainerFlags[ContainerFlags["IsControlFlowContainer"] = 4] = "IsControlFlowContainer"; + ContainerFlags[ContainerFlags["IsFunctionLike"] = 8] = "IsFunctionLike"; + ContainerFlags[ContainerFlags["IsFunctionExpression"] = 16] = "IsFunctionExpression"; + ContainerFlags[ContainerFlags["HasLocals"] = 32] = "HasLocals"; + ContainerFlags[ContainerFlags["IsInterface"] = 64] = "IsInterface"; + ContainerFlags[ContainerFlags["IsObjectLiteralOrClassExpressionMethod"] = 128] = "IsObjectLiteralOrClassExpressionMethod"; + })(ContainerFlags || (ContainerFlags = {})); + var binder = createBinder(); + function bindSourceFile(file, options) { + ts.performance.mark("beforeBind"); + binder(file, options); + ts.performance.mark("afterBind"); + ts.performance.measure("Bind", "beforeBind", "afterBind"); + } + ts.bindSourceFile = bindSourceFile; + function createBinder() { + var file; + var options; + var languageVersion; + var parent; + var container; + var thisParentContainer; // Container one level up + var blockScopeContainer; + var lastContainer; + var delayedTypeAliases; + var seenThisKeyword; + // state used by control flow analysis + var currentFlow; + var currentBreakTarget; + var currentContinueTarget; + var currentReturnTarget; + var currentTrueTarget; + var currentFalseTarget; + var preSwitchCaseFlow; + var activeLabels; + var hasExplicitReturn; + // state used for emit helpers + var emitFlags; + // If this file is an external module, then it is automatically in strict-mode according to + // ES6. If it is not an external module, then we'll determine if it is in strict mode or + // not depending on if we see "use strict" in certain places or if we hit a class/namespace + // or if compiler options contain alwaysStrict. + var inStrictMode; + var symbolCount = 0; + var Symbol; // tslint:disable-line variable-name + var classifiableNames; + var unreachableFlow = { flags: 1 /* Unreachable */ }; + var reportedUnreachableFlow = { flags: 1 /* Unreachable */ }; + // state used to aggregate transform flags during bind. + var subtreeTransformFlags = 0 /* None */; + var skipTransformFlagAggregation; + /** + * Inside the binder, we may create a diagnostic for an as-yet unbound node (with potentially no parent pointers, implying no accessible source file) + * If so, the node _must_ be in the current file (as that's the only way anything could have traversed to it to yield it as the error node) + * This version of `createDiagnosticForNode` uses the binder's context to account for this, and always yields correct diagnostics even in these situations. + */ + function createDiagnosticForNode(node, message, arg0, arg1, arg2) { + return ts.createDiagnosticForNodeInSourceFile(ts.getSourceFileOfNode(node) || file, node, message, arg0, arg1, arg2); + } + function bindSourceFile(f, opts) { + file = f; + options = opts; + languageVersion = ts.getEmitScriptTarget(options); + inStrictMode = bindInStrictMode(file, opts); + classifiableNames = ts.createUnderscoreEscapedMap(); + symbolCount = 0; + skipTransformFlagAggregation = file.isDeclarationFile; + Symbol = ts.objectAllocator.getSymbolConstructor(); + if (!file.locals) { + bind(file); + file.symbolCount = symbolCount; + file.classifiableNames = classifiableNames; + delayedBindJSDocTypedefTag(); + } + file = undefined; + options = undefined; + languageVersion = undefined; + parent = undefined; + container = undefined; + thisParentContainer = undefined; + blockScopeContainer = undefined; + lastContainer = undefined; + delayedTypeAliases = undefined; + seenThisKeyword = false; + currentFlow = undefined; + currentBreakTarget = undefined; + currentContinueTarget = undefined; + currentReturnTarget = undefined; + currentTrueTarget = undefined; + currentFalseTarget = undefined; + activeLabels = undefined; + hasExplicitReturn = false; + emitFlags = 0 /* None */; + subtreeTransformFlags = 0 /* None */; + } + return bindSourceFile; + function bindInStrictMode(file, opts) { + if (ts.getStrictOptionValue(opts, "alwaysStrict") && !file.isDeclarationFile) { + // bind in strict mode source files with alwaysStrict option + return true; + } + else { + return !!file.externalModuleIndicator; + } + } + function createSymbol(flags, name) { + symbolCount++; + return new Symbol(flags, name); + } + function addDeclarationToSymbol(symbol, node, symbolFlags) { + symbol.flags |= symbolFlags; + node.symbol = symbol; + symbol.declarations = ts.append(symbol.declarations, node); + if (symbolFlags & (32 /* Class */ | 384 /* Enum */ | 1536 /* Module */ | 3 /* Variable */) && !symbol.exports) { + symbol.exports = ts.createSymbolTable(); + } + if (symbolFlags & (32 /* Class */ | 64 /* Interface */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && !symbol.members) { + symbol.members = ts.createSymbolTable(); + } + if (symbolFlags & 67220415 /* Value */) { + setValueDeclaration(symbol, node); + } + } + function setValueDeclaration(symbol, node) { + var valueDeclaration = symbol.valueDeclaration; + if (!valueDeclaration || + (ts.isAssignmentDeclaration(valueDeclaration) && !ts.isAssignmentDeclaration(node)) || + (valueDeclaration.kind !== node.kind && ts.isEffectiveModuleDeclaration(valueDeclaration))) { + // other kinds of value declarations take precedence over modules and assignment declarations + symbol.valueDeclaration = node; + } + } + // Should not be called on a declaration with a computed property name, + // unless it is a well known Symbol. + function getDeclarationName(node) { + if (node.kind === 254 /* ExportAssignment */) { + return node.isExportEquals ? "export=" /* ExportEquals */ : "default" /* Default */; + } + var name = ts.getNameOfDeclaration(node); + if (name) { + if (ts.isAmbientModule(node)) { + var moduleName = ts.getTextOfIdentifierOrLiteral(name); + return (ts.isGlobalScopeAugmentation(node) ? "__global" : "\"" + moduleName + "\""); + } + if (name.kind === 149 /* ComputedPropertyName */) { + var nameExpression = name.expression; + // treat computed property names where expression is string/numeric literal as just string/numeric literal + if (ts.isStringOrNumericLiteralLike(nameExpression)) { + return ts.escapeLeadingUnderscores(nameExpression.text); + } + ts.Debug.assert(ts.isWellKnownSymbolSyntactically(nameExpression)); + return ts.getPropertyNameForKnownSymbolName(ts.idText(nameExpression.name)); + } + return ts.isPropertyNameLiteral(name) ? ts.getEscapedTextOfIdentifierOrLiteral(name) : undefined; + } + switch (node.kind) { + case 157 /* Constructor */: + return "__constructor" /* Constructor */; + case 165 /* FunctionType */: + case 160 /* CallSignature */: + case 293 /* JSDocSignature */: + return "__call" /* Call */; + case 166 /* ConstructorType */: + case 161 /* ConstructSignature */: + return "__new" /* New */; + case 162 /* IndexSignature */: + return "__index" /* Index */; + case 255 /* ExportDeclaration */: + return "__export" /* ExportStar */; + case 279 /* SourceFile */: + // json file should behave as + // module.exports = ... + return "export=" /* ExportEquals */; + case 204 /* BinaryExpression */: + if (ts.getAssignmentDeclarationKind(node) === 2 /* ModuleExports */) { + // module.exports = ... + return "export=" /* ExportEquals */; + } + ts.Debug.fail("Unknown binary declaration kind"); + break; + case 289 /* JSDocFunctionType */: + return (ts.isJSDocConstructSignature(node) ? "__new" /* New */ : "__call" /* Call */); + case 151 /* Parameter */: + // Parameters with names are handled at the top of this function. Parameters + // without names can only come from JSDocFunctionTypes. + ts.Debug.assert(node.parent.kind === 289 /* JSDocFunctionType */, "Impossible parameter parent kind", function () { return "parent is: " + (ts.SyntaxKind ? ts.SyntaxKind[node.parent.kind] : node.parent.kind) + ", expected JSDocFunctionType"; }); + var functionType = node.parent; + var index = functionType.parameters.indexOf(node); + return "arg" + index; + } + } + function getDisplayName(node) { + return ts.isNamedDeclaration(node) ? ts.declarationNameToString(node.name) : ts.unescapeLeadingUnderscores(ts.Debug.assertDefined(getDeclarationName(node))); + } + /** + * Declares a Symbol for the node and adds it to symbols. Reports errors for conflicting identifier names. + * @param symbolTable - The symbol table which node will be added to. + * @param parent - node's parent declaration. + * @param node - The declaration to be added to the symbol table + * @param includes - The SymbolFlags that node has in addition to its declaration type (eg: export, ambient, etc.) + * @param excludes - The flags which node cannot be declared alongside in a symbol table. Used to report forbidden declarations. + */ + function declareSymbol(symbolTable, parent, node, includes, excludes, isReplaceableByMethod) { + ts.Debug.assert(!ts.hasDynamicName(node)); + var isDefaultExport = ts.hasModifier(node, 512 /* Default */); + // The exported symbol for an export default function/class node is always named "default" + var name = isDefaultExport && parent ? "default" /* Default */ : getDeclarationName(node); + var symbol; + if (name === undefined) { + symbol = createSymbol(0 /* None */, "__missing" /* Missing */); + } + else { + // Check and see if the symbol table already has a symbol with this name. If not, + // create a new symbol with this name and add it to the table. Note that we don't + // give the new symbol any flags *yet*. This ensures that it will not conflict + // with the 'excludes' flags we pass in. + // + // If we do get an existing symbol, see if it conflicts with the new symbol we're + // creating. For example, a 'var' symbol and a 'class' symbol will conflict within + // the same symbol table. If we have a conflict, report the issue on each + // declaration we have for this symbol, and then create a new symbol for this + // declaration. + // + // Note that when properties declared in Javascript constructors + // (marked by isReplaceableByMethod) conflict with another symbol, the property loses. + // Always. This allows the common Javascript pattern of overwriting a prototype method + // with an bound instance method of the same type: `this.method = this.method.bind(this)` + // + // If we created a new symbol, either because we didn't have a symbol with this name + // in the symbol table, or we conflicted with an existing symbol, then just add this + // node as the sole declaration of the new symbol. + // + // Otherwise, we'll be merging into a compatible existing symbol (for example when + // you have multiple 'vars' with the same name in the same container). In this case + // just add this node into the declarations list of the symbol. + symbol = symbolTable.get(name); + if (includes & 2885600 /* Classifiable */) { + classifiableNames.set(name, true); + } + if (!symbol) { + symbolTable.set(name, symbol = createSymbol(0 /* None */, name)); + if (isReplaceableByMethod) + symbol.isReplaceableByMethod = true; + } + else if (isReplaceableByMethod && !symbol.isReplaceableByMethod) { + // A symbol already exists, so don't add this as a declaration. + return symbol; + } + else if (symbol.flags & excludes) { + if (symbol.isReplaceableByMethod) { + // Javascript constructor-declared symbols can be discarded in favor of + // prototype symbols like methods. + symbolTable.set(name, symbol = createSymbol(0 /* None */, name)); + } + else if (!(includes & 3 /* Variable */ && symbol.flags & 67108864 /* Assignment */)) { + // Assignment declarations are allowed to merge with variables, no matter what other flags they have. + if (ts.isNamedDeclaration(node)) { + node.name.parent = node; + } + // Report errors every position with duplicate declaration + // Report errors on previous encountered declarations + var message_1 = symbol.flags & 2 /* BlockScopedVariable */ + ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 + : ts.Diagnostics.Duplicate_identifier_0; + var messageNeedsName_1 = true; + if (symbol.flags & 384 /* Enum */ || includes & 384 /* Enum */) { + message_1 = ts.Diagnostics.Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations; + messageNeedsName_1 = false; + } + if (symbol.declarations && symbol.declarations.length) { + // If the current node is a default export of some sort, then check if + // there are any other default exports that we need to error on. + // We'll know whether we have other default exports depending on if `symbol` already has a declaration list set. + if (isDefaultExport) { + message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; + messageNeedsName_1 = false; + } + else { + // This is to properly report an error in the case "export default { }" is after export default of class declaration or function declaration. + // Error on multiple export default in the following case: + // 1. multiple export default of class declaration or function declaration by checking NodeFlags.Default + // 2. multiple export default of export assignment. This one doesn't have NodeFlags.Default on (as export default doesn't considered as modifiers) + if (symbol.declarations && symbol.declarations.length && + (node.kind === 254 /* ExportAssignment */ && !node.isExportEquals)) { + message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; + messageNeedsName_1 = false; + } + } + } + var addError = function (decl) { + file.bindDiagnostics.push(createDiagnosticForNode(ts.getNameOfDeclaration(decl) || decl, message_1, messageNeedsName_1 ? getDisplayName(decl) : undefined)); + }; + ts.forEach(symbol.declarations, addError); + addError(node); + symbol = createSymbol(0 /* None */, name); + } + } + } + addDeclarationToSymbol(symbol, node, includes); + if (symbol.parent) { + ts.Debug.assert(symbol.parent === parent, "Existing symbol parent should match new one"); + } + else { + symbol.parent = parent; + } + return symbol; + } + function declareModuleMember(node, symbolFlags, symbolExcludes) { + var hasExportModifier = ts.getCombinedModifierFlags(node) & 1 /* Export */; + if (symbolFlags & 2097152 /* Alias */) { + if (node.kind === 257 /* ExportSpecifier */ || (node.kind === 248 /* ImportEqualsDeclaration */ && hasExportModifier)) { + return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); + } + else { + return declareSymbol(container.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes); + } + } + else { + // Exported module members are given 2 symbols: A local symbol that is classified with an ExportValue flag, + // and an associated export symbol with all the correct flags set on it. There are 2 main reasons: + // + // 1. We treat locals and exports of the same name as mutually exclusive within a container. + // That means the binder will issue a Duplicate Identifier error if you mix locals and exports + // with the same name in the same container. + // TODO: Make this a more specific error and decouple it from the exclusion logic. + // 2. When we checkIdentifier in the checker, we set its resolved symbol to the local symbol, + // but return the export symbol (by calling getExportSymbolOfValueSymbolIfExported). That way + // when the emitter comes back to it, it knows not to qualify the name if it was found in a containing scope. + // NOTE: Nested ambient modules always should go to to 'locals' table to prevent their automatic merge + // during global merging in the checker. Why? The only case when ambient module is permitted inside another module is module augmentation + // and this case is specially handled. Module augmentations should only be merged with original module definition + // and should never be merged directly with other augmentation, and the latter case would be possible if automatic merge is allowed. + if (ts.isJSDocTypeAlias(node)) + ts.Debug.assert(ts.isInJSFile(node)); // We shouldn't add symbols for JSDoc nodes if not in a JS file. + if ((!ts.isAmbientModule(node) && (hasExportModifier || container.flags & 32 /* ExportContext */)) || ts.isJSDocTypeAlias(node)) { + if (ts.hasModifier(node, 512 /* Default */) && !getDeclarationName(node)) { + return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); // No local symbol for an unnamed default! + } + var exportKind = symbolFlags & 67220415 /* Value */ ? 1048576 /* ExportValue */ : 0; + var local = declareSymbol(container.locals, /*parent*/ undefined, node, exportKind, symbolExcludes); + local.exportSymbol = declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); + node.localSymbol = local; + return local; + } + else { + return declareSymbol(container.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes); + } + } + } + // All container nodes are kept on a linked list in declaration order. This list is used by + // the getLocalNameOfContainer function in the type checker to validate that the local name + // used for a container is unique. + function bindContainer(node, containerFlags) { + // Before we recurse into a node's children, we first save the existing parent, container + // and block-container. Then after we pop out of processing the children, we restore + // these saved values. + var saveContainer = container; + var saveThisParentContainer = thisParentContainer; + var savedBlockScopeContainer = blockScopeContainer; + // Depending on what kind of node this is, we may have to adjust the current container + // and block-container. If the current node is a container, then it is automatically + // considered the current block-container as well. Also, for containers that we know + // may contain locals, we eagerly initialize the .locals field. We do this because + // it's highly likely that the .locals will be needed to place some child in (for example, + // a parameter, or variable declaration). + // + // However, we do not proactively create the .locals for block-containers because it's + // totally normal and common for block-containers to never actually have a block-scoped + // variable in them. We don't want to end up allocating an object for every 'block' we + // run into when most of them won't be necessary. + // + // Finally, if this is a block-container, then we clear out any existing .locals object + // it may contain within it. This happens in incremental scenarios. Because we can be + // reusing a node from a previous compilation, that node may have had 'locals' created + // for it. We must clear this so we don't accidentally move any stale data forward from + // a previous compilation. + if (containerFlags & 1 /* IsContainer */) { + if (node.kind !== 197 /* ArrowFunction */) { + thisParentContainer = container; + } + container = blockScopeContainer = node; + if (containerFlags & 32 /* HasLocals */) { + container.locals = ts.createSymbolTable(); + } + addToContainerChain(container); + } + else if (containerFlags & 2 /* IsBlockScopedContainer */) { + blockScopeContainer = node; + blockScopeContainer.locals = undefined; + } + if (containerFlags & 4 /* IsControlFlowContainer */) { + var saveCurrentFlow = currentFlow; + var saveBreakTarget = currentBreakTarget; + var saveContinueTarget = currentContinueTarget; + var saveReturnTarget = currentReturnTarget; + var saveActiveLabels = activeLabels; + var saveHasExplicitReturn = hasExplicitReturn; + var isIIFE = containerFlags & 16 /* IsFunctionExpression */ && !ts.hasModifier(node, 256 /* Async */) && + !node.asteriskToken && !!ts.getImmediatelyInvokedFunctionExpression(node); + // A non-async, non-generator IIFE is considered part of the containing control flow. Return statements behave + // similarly to break statements that exit to a label just past the statement body. + if (!isIIFE) { + currentFlow = { flags: 2 /* Start */ }; + if (containerFlags & (16 /* IsFunctionExpression */ | 128 /* IsObjectLiteralOrClassExpressionMethod */)) { + currentFlow.container = node; + } + } + // We create a return control flow graph for IIFEs and constructors. For constructors + // we use the return control flow graph in strict property intialization checks. + currentReturnTarget = isIIFE || node.kind === 157 /* Constructor */ ? createBranchLabel() : undefined; + currentBreakTarget = undefined; + currentContinueTarget = undefined; + activeLabels = undefined; + hasExplicitReturn = false; + bindChildren(node); + // Reset all reachability check related flags on node (for incremental scenarios) + node.flags &= ~1408 /* ReachabilityAndEmitFlags */; + if (!(currentFlow.flags & 1 /* Unreachable */) && containerFlags & 8 /* IsFunctionLike */ && ts.nodeIsPresent(node.body)) { + node.flags |= 128 /* HasImplicitReturn */; + if (hasExplicitReturn) + node.flags |= 256 /* HasExplicitReturn */; + } + if (node.kind === 279 /* SourceFile */) { + node.flags |= emitFlags; + } + if (currentReturnTarget) { + addAntecedent(currentReturnTarget, currentFlow); + currentFlow = finishFlowLabel(currentReturnTarget); + if (node.kind === 157 /* Constructor */) { + node.returnFlowNode = currentFlow; + } + } + if (!isIIFE) { + currentFlow = saveCurrentFlow; + } + currentBreakTarget = saveBreakTarget; + currentContinueTarget = saveContinueTarget; + currentReturnTarget = saveReturnTarget; + activeLabels = saveActiveLabels; + hasExplicitReturn = saveHasExplicitReturn; + } + else if (containerFlags & 64 /* IsInterface */) { + seenThisKeyword = false; + bindChildren(node); + node.flags = seenThisKeyword ? node.flags | 64 /* ContainsThis */ : node.flags & ~64 /* ContainsThis */; + } + else { + bindChildren(node); + } + container = saveContainer; + thisParentContainer = saveThisParentContainer; + blockScopeContainer = savedBlockScopeContainer; + } + function bindChildren(node) { + if (skipTransformFlagAggregation) { + bindChildrenWorker(node); + } + else if (node.transformFlags & 536870912 /* HasComputedFlags */) { + skipTransformFlagAggregation = true; + bindChildrenWorker(node); + skipTransformFlagAggregation = false; + subtreeTransformFlags |= node.transformFlags & ~getTransformFlagsSubtreeExclusions(node.kind); + } + else { + var savedSubtreeTransformFlags = subtreeTransformFlags; + subtreeTransformFlags = 0; + bindChildrenWorker(node); + subtreeTransformFlags = savedSubtreeTransformFlags | computeTransformFlagsForNode(node, subtreeTransformFlags); + } + } + function bindEachFunctionsFirst(nodes) { + bindEach(nodes, function (n) { return n.kind === 239 /* FunctionDeclaration */ ? bind(n) : undefined; }); + bindEach(nodes, function (n) { return n.kind !== 239 /* FunctionDeclaration */ ? bind(n) : undefined; }); + } + function bindEach(nodes, bindFunction) { + if (bindFunction === void 0) { bindFunction = bind; } + if (nodes === undefined) { + return; + } + if (skipTransformFlagAggregation) { + ts.forEach(nodes, bindFunction); + } + else { + var savedSubtreeTransformFlags = subtreeTransformFlags; + subtreeTransformFlags = 0 /* None */; + var nodeArrayFlags = 0 /* None */; + for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) { + var node = nodes_2[_i]; + bindFunction(node); + nodeArrayFlags |= node.transformFlags & ~536870912 /* HasComputedFlags */; + } + nodes.transformFlags = nodeArrayFlags | 536870912 /* HasComputedFlags */; + subtreeTransformFlags |= savedSubtreeTransformFlags; + } + } + function bindEachChild(node) { + ts.forEachChild(node, bind, bindEach); + } + function bindChildrenWorker(node) { + if (checkUnreachable(node)) { + bindEachChild(node); + bindJSDoc(node); + return; + } + switch (node.kind) { + case 224 /* WhileStatement */: + bindWhileStatement(node); + break; + case 223 /* DoStatement */: + bindDoStatement(node); + break; + case 225 /* ForStatement */: + bindForStatement(node); + break; + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + bindForInOrForOfStatement(node); + break; + case 222 /* IfStatement */: + bindIfStatement(node); + break; + case 230 /* ReturnStatement */: + case 234 /* ThrowStatement */: + bindReturnOrThrow(node); + break; + case 229 /* BreakStatement */: + case 228 /* ContinueStatement */: + bindBreakOrContinueStatement(node); + break; + case 235 /* TryStatement */: + bindTryStatement(node); + break; + case 232 /* SwitchStatement */: + bindSwitchStatement(node); + break; + case 246 /* CaseBlock */: + bindCaseBlock(node); + break; + case 271 /* CaseClause */: + bindCaseClause(node); + break; + case 233 /* LabeledStatement */: + bindLabeledStatement(node); + break; + case 202 /* PrefixUnaryExpression */: + bindPrefixUnaryExpressionFlow(node); + break; + case 203 /* PostfixUnaryExpression */: + bindPostfixUnaryExpressionFlow(node); + break; + case 204 /* BinaryExpression */: + bindBinaryExpressionFlow(node); + break; + case 198 /* DeleteExpression */: + bindDeleteExpressionFlow(node); + break; + case 205 /* ConditionalExpression */: + bindConditionalExpressionFlow(node); + break; + case 237 /* VariableDeclaration */: + bindVariableDeclarationFlow(node); + break; + case 191 /* CallExpression */: + bindCallExpressionFlow(node); + break; + case 304 /* JSDocTypedefTag */: + case 297 /* JSDocCallbackTag */: + bindJSDocTypeAlias(node); + break; + // In source files and blocks, bind functions first to match hoisting that occurs at runtime + case 279 /* SourceFile */: { + bindEachFunctionsFirst(node.statements); + bind(node.endOfFileToken); + break; + } + case 218 /* Block */: + case 245 /* ModuleBlock */: + bindEachFunctionsFirst(node.statements); + break; + default: + bindEachChild(node); + break; + } + bindJSDoc(node); + } + function isNarrowingExpression(expr) { + switch (expr.kind) { + case 72 /* Identifier */: + case 100 /* ThisKeyword */: + case 189 /* PropertyAccessExpression */: + case 190 /* ElementAccessExpression */: + return isNarrowableReference(expr); + case 191 /* CallExpression */: + return hasNarrowableArgument(expr); + case 195 /* ParenthesizedExpression */: + return isNarrowingExpression(expr.expression); + case 204 /* BinaryExpression */: + return isNarrowingBinaryExpression(expr); + case 202 /* PrefixUnaryExpression */: + return expr.operator === 52 /* ExclamationToken */ && isNarrowingExpression(expr.operand); + case 199 /* TypeOfExpression */: + return isNarrowingExpression(expr.expression); + } + return false; + } + function isNarrowableReference(expr) { + return expr.kind === 72 /* Identifier */ || expr.kind === 100 /* ThisKeyword */ || expr.kind === 98 /* SuperKeyword */ || + ts.isPropertyAccessExpression(expr) && isNarrowableReference(expr.expression) || + ts.isElementAccessExpression(expr) && expr.argumentExpression && + (ts.isStringLiteral(expr.argumentExpression) || ts.isNumericLiteral(expr.argumentExpression)) && + isNarrowableReference(expr.expression); + } + function hasNarrowableArgument(expr) { + if (expr.arguments) { + for (var _i = 0, _a = expr.arguments; _i < _a.length; _i++) { + var argument = _a[_i]; + if (isNarrowableReference(argument)) { + return true; + } + } + } + if (expr.expression.kind === 189 /* PropertyAccessExpression */ && + isNarrowableReference(expr.expression.expression)) { + return true; + } + return false; + } + function isNarrowingTypeofOperands(expr1, expr2) { + return ts.isTypeOfExpression(expr1) && isNarrowableOperand(expr1.expression) && ts.isStringLiteralLike(expr2); + } + function isNarrowableInOperands(left, right) { + return ts.isStringLiteralLike(left) && isNarrowingExpression(right); + } + function isNarrowingBinaryExpression(expr) { + switch (expr.operatorToken.kind) { + case 59 /* EqualsToken */: + return isNarrowableReference(expr.left); + case 33 /* EqualsEqualsToken */: + case 34 /* ExclamationEqualsToken */: + case 35 /* EqualsEqualsEqualsToken */: + case 36 /* ExclamationEqualsEqualsToken */: + return isNarrowableOperand(expr.left) || isNarrowableOperand(expr.right) || + isNarrowingTypeofOperands(expr.right, expr.left) || isNarrowingTypeofOperands(expr.left, expr.right); + case 94 /* InstanceOfKeyword */: + return isNarrowableOperand(expr.left); + case 93 /* InKeyword */: + return isNarrowableInOperands(expr.left, expr.right); + case 27 /* CommaToken */: + return isNarrowingExpression(expr.right); + } + return false; + } + function isNarrowableOperand(expr) { + switch (expr.kind) { + case 195 /* ParenthesizedExpression */: + return isNarrowableOperand(expr.expression); + case 204 /* BinaryExpression */: + switch (expr.operatorToken.kind) { + case 59 /* EqualsToken */: + return isNarrowableOperand(expr.left); + case 27 /* CommaToken */: + return isNarrowableOperand(expr.right); + } + } + return isNarrowableReference(expr); + } + function createBranchLabel() { + return { + flags: 4 /* BranchLabel */, + antecedents: undefined + }; + } + function createLoopLabel() { + return { + flags: 8 /* LoopLabel */, + antecedents: undefined + }; + } + function setFlowNodeReferenced(flow) { + // On first reference we set the Referenced flag, thereafter we set the Shared flag + flow.flags |= flow.flags & 512 /* Referenced */ ? 1024 /* Shared */ : 512 /* Referenced */; + } + function addAntecedent(label, antecedent) { + if (!(antecedent.flags & 1 /* Unreachable */) && !ts.contains(label.antecedents, antecedent)) { + (label.antecedents || (label.antecedents = [])).push(antecedent); + setFlowNodeReferenced(antecedent); + } + } + function createFlowCondition(flags, antecedent, expression) { + if (antecedent.flags & 1 /* Unreachable */) { + return antecedent; + } + if (!expression) { + return flags & 32 /* TrueCondition */ ? antecedent : unreachableFlow; + } + if (expression.kind === 102 /* TrueKeyword */ && flags & 64 /* FalseCondition */ || + expression.kind === 87 /* FalseKeyword */ && flags & 32 /* TrueCondition */) { + return unreachableFlow; + } + if (!isNarrowingExpression(expression)) { + return antecedent; + } + setFlowNodeReferenced(antecedent); + return { flags: flags, expression: expression, antecedent: antecedent }; + } + function createFlowSwitchClause(antecedent, switchStatement, clauseStart, clauseEnd) { + if (!isNarrowingExpression(switchStatement.expression)) { + return antecedent; + } + setFlowNodeReferenced(antecedent); + return { flags: 128 /* SwitchClause */, switchStatement: switchStatement, clauseStart: clauseStart, clauseEnd: clauseEnd, antecedent: antecedent }; + } + function createFlowAssignment(antecedent, node) { + setFlowNodeReferenced(antecedent); + return { flags: 16 /* Assignment */, antecedent: antecedent, node: node }; + } + function createFlowArrayMutation(antecedent, node) { + setFlowNodeReferenced(antecedent); + var res = { flags: 256 /* ArrayMutation */, antecedent: antecedent, node: node }; + return res; + } + function finishFlowLabel(flow) { + var antecedents = flow.antecedents; + if (!antecedents) { + return unreachableFlow; + } + if (antecedents.length === 1) { + return antecedents[0]; + } + return flow; + } + function isStatementCondition(node) { + var parent = node.parent; + switch (parent.kind) { + case 222 /* IfStatement */: + case 224 /* WhileStatement */: + case 223 /* DoStatement */: + return parent.expression === node; + case 225 /* ForStatement */: + case 205 /* ConditionalExpression */: + return parent.condition === node; + } + return false; + } + function isLogicalExpression(node) { + while (true) { + if (node.kind === 195 /* ParenthesizedExpression */) { + node = node.expression; + } + else if (node.kind === 202 /* PrefixUnaryExpression */ && node.operator === 52 /* ExclamationToken */) { + node = node.operand; + } + else { + return node.kind === 204 /* BinaryExpression */ && (node.operatorToken.kind === 54 /* AmpersandAmpersandToken */ || + node.operatorToken.kind === 55 /* BarBarToken */); + } + } + } + function isTopLevelLogicalExpression(node) { + while (node.parent.kind === 195 /* ParenthesizedExpression */ || + node.parent.kind === 202 /* PrefixUnaryExpression */ && + node.parent.operator === 52 /* ExclamationToken */) { + node = node.parent; + } + return !isStatementCondition(node) && !isLogicalExpression(node.parent); + } + function bindCondition(node, trueTarget, falseTarget) { + var saveTrueTarget = currentTrueTarget; + var saveFalseTarget = currentFalseTarget; + currentTrueTarget = trueTarget; + currentFalseTarget = falseTarget; + bind(node); + currentTrueTarget = saveTrueTarget; + currentFalseTarget = saveFalseTarget; + if (!node || !isLogicalExpression(node)) { + addAntecedent(trueTarget, createFlowCondition(32 /* TrueCondition */, currentFlow, node)); + addAntecedent(falseTarget, createFlowCondition(64 /* FalseCondition */, currentFlow, node)); + } + } + function bindIterativeStatement(node, breakTarget, continueTarget) { + var saveBreakTarget = currentBreakTarget; + var saveContinueTarget = currentContinueTarget; + currentBreakTarget = breakTarget; + currentContinueTarget = continueTarget; + bind(node); + currentBreakTarget = saveBreakTarget; + currentContinueTarget = saveContinueTarget; + } + function bindWhileStatement(node) { + var preWhileLabel = createLoopLabel(); + var preBodyLabel = createBranchLabel(); + var postWhileLabel = createBranchLabel(); + addAntecedent(preWhileLabel, currentFlow); + currentFlow = preWhileLabel; + bindCondition(node.expression, preBodyLabel, postWhileLabel); + currentFlow = finishFlowLabel(preBodyLabel); + bindIterativeStatement(node.statement, postWhileLabel, preWhileLabel); + addAntecedent(preWhileLabel, currentFlow); + currentFlow = finishFlowLabel(postWhileLabel); + } + function bindDoStatement(node) { + var preDoLabel = createLoopLabel(); + var enclosingLabeledStatement = node.parent.kind === 233 /* LabeledStatement */ + ? ts.lastOrUndefined(activeLabels) + : undefined; + // if do statement is wrapped in labeled statement then target labels for break/continue with or without + // label should be the same + var preConditionLabel = enclosingLabeledStatement ? enclosingLabeledStatement.continueTarget : createBranchLabel(); + var postDoLabel = enclosingLabeledStatement ? enclosingLabeledStatement.breakTarget : createBranchLabel(); + addAntecedent(preDoLabel, currentFlow); + currentFlow = preDoLabel; + bindIterativeStatement(node.statement, postDoLabel, preConditionLabel); + addAntecedent(preConditionLabel, currentFlow); + currentFlow = finishFlowLabel(preConditionLabel); + bindCondition(node.expression, preDoLabel, postDoLabel); + currentFlow = finishFlowLabel(postDoLabel); + } + function bindForStatement(node) { + var preLoopLabel = createLoopLabel(); + var preBodyLabel = createBranchLabel(); + var postLoopLabel = createBranchLabel(); + bind(node.initializer); + addAntecedent(preLoopLabel, currentFlow); + currentFlow = preLoopLabel; + bindCondition(node.condition, preBodyLabel, postLoopLabel); + currentFlow = finishFlowLabel(preBodyLabel); + bindIterativeStatement(node.statement, postLoopLabel, preLoopLabel); + bind(node.incrementor); + addAntecedent(preLoopLabel, currentFlow); + currentFlow = finishFlowLabel(postLoopLabel); + } + function bindForInOrForOfStatement(node) { + var preLoopLabel = createLoopLabel(); + var postLoopLabel = createBranchLabel(); + addAntecedent(preLoopLabel, currentFlow); + currentFlow = preLoopLabel; + if (node.kind === 227 /* ForOfStatement */) { + bind(node.awaitModifier); + } + bind(node.expression); + addAntecedent(postLoopLabel, currentFlow); + bind(node.initializer); + if (node.initializer.kind !== 238 /* VariableDeclarationList */) { + bindAssignmentTargetFlow(node.initializer); + } + bindIterativeStatement(node.statement, postLoopLabel, preLoopLabel); + addAntecedent(preLoopLabel, currentFlow); + currentFlow = finishFlowLabel(postLoopLabel); + } + function bindIfStatement(node) { + var thenLabel = createBranchLabel(); + var elseLabel = createBranchLabel(); + var postIfLabel = createBranchLabel(); + bindCondition(node.expression, thenLabel, elseLabel); + currentFlow = finishFlowLabel(thenLabel); + bind(node.thenStatement); + addAntecedent(postIfLabel, currentFlow); + currentFlow = finishFlowLabel(elseLabel); + bind(node.elseStatement); + addAntecedent(postIfLabel, currentFlow); + currentFlow = finishFlowLabel(postIfLabel); + } + function bindReturnOrThrow(node) { + bind(node.expression); + if (node.kind === 230 /* ReturnStatement */) { + hasExplicitReturn = true; + if (currentReturnTarget) { + addAntecedent(currentReturnTarget, currentFlow); + } + } + currentFlow = unreachableFlow; + } + function findActiveLabel(name) { + if (activeLabels) { + for (var _i = 0, activeLabels_1 = activeLabels; _i < activeLabels_1.length; _i++) { + var label = activeLabels_1[_i]; + if (label.name === name) { + return label; + } + } + } + return undefined; + } + function bindBreakOrContinueFlow(node, breakTarget, continueTarget) { + var flowLabel = node.kind === 229 /* BreakStatement */ ? breakTarget : continueTarget; + if (flowLabel) { + addAntecedent(flowLabel, currentFlow); + currentFlow = unreachableFlow; + } + } + function bindBreakOrContinueStatement(node) { + bind(node.label); + if (node.label) { + var activeLabel = findActiveLabel(node.label.escapedText); + if (activeLabel) { + activeLabel.referenced = true; + bindBreakOrContinueFlow(node, activeLabel.breakTarget, activeLabel.continueTarget); + } + } + else { + bindBreakOrContinueFlow(node, currentBreakTarget, currentContinueTarget); + } + } + function bindTryStatement(node) { + var preFinallyLabel = createBranchLabel(); + var preTryFlow = currentFlow; + // TODO: Every statement in try block is potentially an exit point! + bind(node.tryBlock); + addAntecedent(preFinallyLabel, currentFlow); + var flowAfterTry = currentFlow; + var flowAfterCatch = unreachableFlow; + if (node.catchClause) { + currentFlow = preTryFlow; + bind(node.catchClause); + addAntecedent(preFinallyLabel, currentFlow); + flowAfterCatch = currentFlow; + } + if (node.finallyBlock) { + // in finally flow is combined from pre-try/flow from try/flow from catch + // pre-flow is necessary to make sure that finally is reachable even if finally flows in both try and finally blocks are unreachable + // also for finally blocks we inject two extra edges into the flow graph. + // first -> edge that connects pre-try flow with the label at the beginning of the finally block, it has lock associated with it + // second -> edge that represents post-finally flow. + // these edges are used in following scenario: + // let a; (1) + // try { a = someOperation(); (2)} + // finally { (3) console.log(a) } (4) + // (5) a + // flow graph for this case looks roughly like this (arrows show ): + // (1-pre-try-flow) <--.. <-- (2-post-try-flow) + // ^ ^ + // |*****(3-pre-finally-label) -----| + // ^ + // |-- ... <-- (4-post-finally-label) <--- (5) + // In case when we walk the flow starting from inside the finally block we want to take edge '*****' into account + // since it ensures that finally is always reachable. However when we start outside the finally block and go through label (5) + // then edge '*****' should be discarded because label 4 is only reachable if post-finally label-4 is reachable + // Simply speaking code inside finally block is treated as reachable as pre-try-flow + // since we conservatively assume that any line in try block can throw or return in which case we'll enter finally. + // However code after finally is reachable only if control flow was not abrupted in try/catch or finally blocks - it should be composed from + // final flows of these blocks without taking pre-try flow into account. + // + // extra edges that we inject allows to control this behavior + // if when walking the flow we step on post-finally edge - we can mark matching pre-finally edge as locked so it will be skipped. + var preFinallyFlow = { flags: 2048 /* PreFinally */, antecedent: preTryFlow, lock: {} }; + addAntecedent(preFinallyLabel, preFinallyFlow); + currentFlow = finishFlowLabel(preFinallyLabel); + bind(node.finallyBlock); + // if flow after finally is unreachable - keep it + // otherwise check if flows after try and after catch are unreachable + // if yes - convert current flow to unreachable + // i.e. + // try { return "1" } finally { console.log(1); } + // console.log(2); // this line should be unreachable even if flow falls out of finally block + if (!(currentFlow.flags & 1 /* Unreachable */)) { + if ((flowAfterTry.flags & 1 /* Unreachable */) && (flowAfterCatch.flags & 1 /* Unreachable */)) { + currentFlow = flowAfterTry === reportedUnreachableFlow || flowAfterCatch === reportedUnreachableFlow + ? reportedUnreachableFlow + : unreachableFlow; + } + } + if (!(currentFlow.flags & 1 /* Unreachable */)) { + var afterFinallyFlow = { flags: 4096 /* AfterFinally */, antecedent: currentFlow }; + preFinallyFlow.lock = afterFinallyFlow; + currentFlow = afterFinallyFlow; + } + } + else { + currentFlow = finishFlowLabel(preFinallyLabel); + } + } + function bindSwitchStatement(node) { + var postSwitchLabel = createBranchLabel(); + bind(node.expression); + var saveBreakTarget = currentBreakTarget; + var savePreSwitchCaseFlow = preSwitchCaseFlow; + currentBreakTarget = postSwitchLabel; + preSwitchCaseFlow = currentFlow; + bind(node.caseBlock); + addAntecedent(postSwitchLabel, currentFlow); + var hasDefault = ts.forEach(node.caseBlock.clauses, function (c) { return c.kind === 272 /* DefaultClause */; }); + // We mark a switch statement as possibly exhaustive if it has no default clause and if all + // case clauses have unreachable end points (e.g. they all return). + node.possiblyExhaustive = !hasDefault && !postSwitchLabel.antecedents; + if (!hasDefault) { + addAntecedent(postSwitchLabel, createFlowSwitchClause(preSwitchCaseFlow, node, 0, 0)); + } + currentBreakTarget = saveBreakTarget; + preSwitchCaseFlow = savePreSwitchCaseFlow; + currentFlow = finishFlowLabel(postSwitchLabel); + } + function bindCaseBlock(node) { + var savedSubtreeTransformFlags = subtreeTransformFlags; + subtreeTransformFlags = 0; + var clauses = node.clauses; + var fallthroughFlow = unreachableFlow; + for (var i = 0; i < clauses.length; i++) { + var clauseStart = i; + while (!clauses[i].statements.length && i + 1 < clauses.length) { + bind(clauses[i]); + i++; + } + var preCaseLabel = createBranchLabel(); + addAntecedent(preCaseLabel, createFlowSwitchClause(preSwitchCaseFlow, node.parent, clauseStart, i + 1)); + addAntecedent(preCaseLabel, fallthroughFlow); + currentFlow = finishFlowLabel(preCaseLabel); + var clause = clauses[i]; + bind(clause); + fallthroughFlow = currentFlow; + if (!(currentFlow.flags & 1 /* Unreachable */) && i !== clauses.length - 1 && options.noFallthroughCasesInSwitch) { + errorOnFirstToken(clause, ts.Diagnostics.Fallthrough_case_in_switch); + } + } + clauses.transformFlags = subtreeTransformFlags | 536870912 /* HasComputedFlags */; + subtreeTransformFlags |= savedSubtreeTransformFlags; + } + function bindCaseClause(node) { + var saveCurrentFlow = currentFlow; + currentFlow = preSwitchCaseFlow; + bind(node.expression); + currentFlow = saveCurrentFlow; + bindEach(node.statements); + } + function pushActiveLabel(name, breakTarget, continueTarget) { + var activeLabel = { + name: name, + breakTarget: breakTarget, + continueTarget: continueTarget, + referenced: false + }; + (activeLabels || (activeLabels = [])).push(activeLabel); + return activeLabel; + } + function popActiveLabel() { + activeLabels.pop(); + } + function bindLabeledStatement(node) { + var preStatementLabel = createLoopLabel(); + var postStatementLabel = createBranchLabel(); + bind(node.label); + addAntecedent(preStatementLabel, currentFlow); + var activeLabel = pushActiveLabel(node.label.escapedText, postStatementLabel, preStatementLabel); + bind(node.statement); + popActiveLabel(); + if (!activeLabel.referenced && !options.allowUnusedLabels) { + errorOrSuggestionOnNode(ts.unusedLabelIsError(options), node.label, ts.Diagnostics.Unused_label); + } + if (!node.statement || node.statement.kind !== 223 /* DoStatement */) { + // do statement sets current flow inside bindDoStatement + addAntecedent(postStatementLabel, currentFlow); + currentFlow = finishFlowLabel(postStatementLabel); + } + } + function bindDestructuringTargetFlow(node) { + if (node.kind === 204 /* BinaryExpression */ && node.operatorToken.kind === 59 /* EqualsToken */) { + bindAssignmentTargetFlow(node.left); + } + else { + bindAssignmentTargetFlow(node); + } + } + function bindAssignmentTargetFlow(node) { + if (isNarrowableReference(node)) { + currentFlow = createFlowAssignment(currentFlow, node); + } + else if (node.kind === 187 /* ArrayLiteralExpression */) { + for (var _i = 0, _a = node.elements; _i < _a.length; _i++) { + var e = _a[_i]; + if (e.kind === 208 /* SpreadElement */) { + bindAssignmentTargetFlow(e.expression); + } + else { + bindDestructuringTargetFlow(e); + } + } + } + else if (node.kind === 188 /* ObjectLiteralExpression */) { + for (var _b = 0, _c = node.properties; _b < _c.length; _b++) { + var p = _c[_b]; + if (p.kind === 275 /* PropertyAssignment */) { + bindDestructuringTargetFlow(p.initializer); + } + else if (p.kind === 276 /* ShorthandPropertyAssignment */) { + bindAssignmentTargetFlow(p.name); + } + else if (p.kind === 277 /* SpreadAssignment */) { + bindAssignmentTargetFlow(p.expression); + } + } + } + } + function bindLogicalExpression(node, trueTarget, falseTarget) { + var preRightLabel = createBranchLabel(); + if (node.operatorToken.kind === 54 /* AmpersandAmpersandToken */) { + bindCondition(node.left, preRightLabel, falseTarget); + } + else { + bindCondition(node.left, trueTarget, preRightLabel); + } + currentFlow = finishFlowLabel(preRightLabel); + bind(node.operatorToken); + bindCondition(node.right, trueTarget, falseTarget); + } + function bindPrefixUnaryExpressionFlow(node) { + if (node.operator === 52 /* ExclamationToken */) { + var saveTrueTarget = currentTrueTarget; + currentTrueTarget = currentFalseTarget; + currentFalseTarget = saveTrueTarget; + bindEachChild(node); + currentFalseTarget = currentTrueTarget; + currentTrueTarget = saveTrueTarget; + } + else { + bindEachChild(node); + if (node.operator === 44 /* PlusPlusToken */ || node.operator === 45 /* MinusMinusToken */) { + bindAssignmentTargetFlow(node.operand); + } + } + } + function bindPostfixUnaryExpressionFlow(node) { + bindEachChild(node); + if (node.operator === 44 /* PlusPlusToken */ || node.operator === 45 /* MinusMinusToken */) { + bindAssignmentTargetFlow(node.operand); + } + } + function bindBinaryExpressionFlow(node) { + var operator = node.operatorToken.kind; + if (operator === 54 /* AmpersandAmpersandToken */ || operator === 55 /* BarBarToken */) { + if (isTopLevelLogicalExpression(node)) { + var postExpressionLabel = createBranchLabel(); + bindLogicalExpression(node, postExpressionLabel, postExpressionLabel); + currentFlow = finishFlowLabel(postExpressionLabel); + } + else { + bindLogicalExpression(node, currentTrueTarget, currentFalseTarget); + } + } + else { + bindEachChild(node); + if (ts.isAssignmentOperator(operator) && !ts.isAssignmentTarget(node)) { + bindAssignmentTargetFlow(node.left); + if (operator === 59 /* EqualsToken */ && node.left.kind === 190 /* ElementAccessExpression */) { + var elementAccess = node.left; + if (isNarrowableOperand(elementAccess.expression)) { + currentFlow = createFlowArrayMutation(currentFlow, node); + } + } + } + } + } + function bindDeleteExpressionFlow(node) { + bindEachChild(node); + if (node.expression.kind === 189 /* PropertyAccessExpression */) { + bindAssignmentTargetFlow(node.expression); + } + } + function bindConditionalExpressionFlow(node) { + var trueLabel = createBranchLabel(); + var falseLabel = createBranchLabel(); + var postExpressionLabel = createBranchLabel(); + bindCondition(node.condition, trueLabel, falseLabel); + currentFlow = finishFlowLabel(trueLabel); + bind(node.questionToken); + bind(node.whenTrue); + addAntecedent(postExpressionLabel, currentFlow); + currentFlow = finishFlowLabel(falseLabel); + bind(node.colonToken); + bind(node.whenFalse); + addAntecedent(postExpressionLabel, currentFlow); + currentFlow = finishFlowLabel(postExpressionLabel); + } + function bindInitializedVariableFlow(node) { + var name = !ts.isOmittedExpression(node) ? node.name : undefined; + if (ts.isBindingPattern(name)) { + for (var _i = 0, _a = name.elements; _i < _a.length; _i++) { + var child = _a[_i]; + bindInitializedVariableFlow(child); + } + } + else { + currentFlow = createFlowAssignment(currentFlow, node); + } + } + function bindVariableDeclarationFlow(node) { + bindEachChild(node); + if (node.initializer || ts.isForInOrOfStatement(node.parent.parent)) { + bindInitializedVariableFlow(node); + } + } + function bindJSDocTypeAlias(node) { + node.tagName.parent = node; + if (node.fullName) { + setParentPointers(node, node.fullName); + } + } + function bindCallExpressionFlow(node) { + // If the target of the call expression is a function expression or arrow function we have + // an immediately invoked function expression (IIFE). Initialize the flowNode property to + // the current control flow (which includes evaluation of the IIFE arguments). + var expr = node.expression; + while (expr.kind === 195 /* ParenthesizedExpression */) { + expr = expr.expression; + } + if (expr.kind === 196 /* FunctionExpression */ || expr.kind === 197 /* ArrowFunction */) { + bindEach(node.typeArguments); + bindEach(node.arguments); + bind(node.expression); + } + else { + bindEachChild(node); + } + if (node.expression.kind === 189 /* PropertyAccessExpression */) { + var propertyAccess = node.expression; + if (isNarrowableOperand(propertyAccess.expression) && ts.isPushOrUnshiftIdentifier(propertyAccess.name)) { + currentFlow = createFlowArrayMutation(currentFlow, node); + } + } + } + function getContainerFlags(node) { + switch (node.kind) { + case 209 /* ClassExpression */: + case 240 /* ClassDeclaration */: + case 243 /* EnumDeclaration */: + case 188 /* ObjectLiteralExpression */: + case 168 /* TypeLiteral */: + case 292 /* JSDocTypeLiteral */: + case 268 /* JsxAttributes */: + return 1 /* IsContainer */; + case 241 /* InterfaceDeclaration */: + return 1 /* IsContainer */ | 64 /* IsInterface */; + case 244 /* ModuleDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 181 /* MappedType */: + return 1 /* IsContainer */ | 32 /* HasLocals */; + case 279 /* SourceFile */: + return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */; + case 156 /* MethodDeclaration */: + if (ts.isObjectLiteralOrClassExpressionMethod(node)) { + return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */ | 128 /* IsObjectLiteralOrClassExpressionMethod */; + } + // falls through + case 157 /* Constructor */: + case 239 /* FunctionDeclaration */: + case 155 /* MethodSignature */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 160 /* CallSignature */: + case 293 /* JSDocSignature */: + case 289 /* JSDocFunctionType */: + case 165 /* FunctionType */: + case 161 /* ConstructSignature */: + case 162 /* IndexSignature */: + case 166 /* ConstructorType */: + return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */; + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */ | 16 /* IsFunctionExpression */; + case 245 /* ModuleBlock */: + return 4 /* IsControlFlowContainer */; + case 154 /* PropertyDeclaration */: + return node.initializer ? 4 /* IsControlFlowContainer */ : 0; + case 274 /* CatchClause */: + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + case 246 /* CaseBlock */: + return 2 /* IsBlockScopedContainer */; + case 218 /* Block */: + // do not treat blocks directly inside a function as a block-scoped-container. + // Locals that reside in this block should go to the function locals. Otherwise 'x' + // would not appear to be a redeclaration of a block scoped local in the following + // example: + // + // function foo() { + // var x; + // let x; + // } + // + // If we placed 'var x' into the function locals and 'let x' into the locals of + // the block, then there would be no collision. + // + // By not creating a new block-scoped-container here, we ensure that both 'var x' + // and 'let x' go into the Function-container's locals, and we do get a collision + // conflict. + return ts.isFunctionLike(node.parent) ? 0 /* None */ : 2 /* IsBlockScopedContainer */; + } + return 0 /* None */; + } + function addToContainerChain(next) { + if (lastContainer) { + lastContainer.nextContainer = next; + } + lastContainer = next; + } + function declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes) { + switch (container.kind) { + // Modules, source files, and classes need specialized handling for how their + // members are declared (for example, a member of a class will go into a specific + // symbol table depending on if it is static or not). We defer to specialized + // handlers to take care of declaring these child members. + case 244 /* ModuleDeclaration */: + return declareModuleMember(node, symbolFlags, symbolExcludes); + case 279 /* SourceFile */: + return declareSourceFileMember(node, symbolFlags, symbolExcludes); + case 209 /* ClassExpression */: + case 240 /* ClassDeclaration */: + return declareClassMember(node, symbolFlags, symbolExcludes); + case 243 /* EnumDeclaration */: + return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); + case 168 /* TypeLiteral */: + case 292 /* JSDocTypeLiteral */: + case 188 /* ObjectLiteralExpression */: + case 241 /* InterfaceDeclaration */: + case 268 /* JsxAttributes */: + // Interface/Object-types always have their children added to the 'members' of + // their container. They are only accessible through an instance of their + // container, and are never in scope otherwise (even inside the body of the + // object / type / interface declaring them). An exception is type parameters, + // which are in scope without qualification (similar to 'locals'). + return declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes); + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 293 /* JSDocSignature */: + case 162 /* IndexSignature */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 289 /* JSDocFunctionType */: + case 304 /* JSDocTypedefTag */: + case 297 /* JSDocCallbackTag */: + case 242 /* TypeAliasDeclaration */: + case 181 /* MappedType */: + // All the children of these container types are never visible through another + // symbol (i.e. through another symbol's 'exports' or 'members'). Instead, + // they're only accessed 'lexically' (i.e. from code that exists underneath + // their container in the tree). To accomplish this, we simply add their declared + // symbol to the 'locals' of the container. These symbols can then be found as + // the type checker walks up the containers, checking them for matching names. + return declareSymbol(container.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes); + } + } + function declareClassMember(node, symbolFlags, symbolExcludes) { + return ts.hasModifier(node, 32 /* Static */) + ? declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes) + : declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes); + } + function declareSourceFileMember(node, symbolFlags, symbolExcludes) { + return ts.isExternalModule(file) + ? declareModuleMember(node, symbolFlags, symbolExcludes) + : declareSymbol(file.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes); + } + function hasExportDeclarations(node) { + var body = node.kind === 279 /* SourceFile */ ? node : node.body; + if (body && (body.kind === 279 /* SourceFile */ || body.kind === 245 /* ModuleBlock */)) { + for (var _i = 0, _a = body.statements; _i < _a.length; _i++) { + var stat = _a[_i]; + if (stat.kind === 255 /* ExportDeclaration */ || stat.kind === 254 /* ExportAssignment */) { + return true; + } + } + } + return false; + } + function setExportContextFlag(node) { + // A declaration source file or ambient module declaration that contains no export declarations (but possibly regular + // declarations with export modifiers) is an export context in which declarations are implicitly exported. + if (node.flags & 4194304 /* Ambient */ && !hasExportDeclarations(node)) { + node.flags |= 32 /* ExportContext */; + } + else { + node.flags &= ~32 /* ExportContext */; + } + } + function bindModuleDeclaration(node) { + setExportContextFlag(node); + if (ts.isAmbientModule(node)) { + if (ts.hasModifier(node, 1 /* Export */)) { + errorOnFirstToken(node, ts.Diagnostics.export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always_visible); + } + if (ts.isModuleAugmentationExternal(node)) { + declareModuleSymbol(node); + } + else { + var pattern = void 0; + if (node.name.kind === 10 /* StringLiteral */) { + var text = node.name.text; + if (ts.hasZeroOrOneAsteriskCharacter(text)) { + pattern = ts.tryParsePattern(text); + } + else { + errorOnFirstToken(node.name, ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, text); + } + } + var symbol = declareSymbolAndAddToSymbolTable(node, 512 /* ValueModule */, 110735 /* ValueModuleExcludes */); + file.patternAmbientModules = ts.append(file.patternAmbientModules, pattern && { pattern: pattern, symbol: symbol }); + } + } + else { + var state = declareModuleSymbol(node); + if (state !== 0 /* NonInstantiated */) { + var symbol = node.symbol; + // if module was already merged with some function, class or non-const enum, treat it as non-const-enum-only + symbol.constEnumOnlyModule = (!(symbol.flags & (16 /* Function */ | 32 /* Class */ | 256 /* RegularEnum */))) + // Current must be `const enum` only + && state === 2 /* ConstEnumOnly */ + // Can't have been set to 'false' in a previous merged symbol. ('undefined' OK) + && symbol.constEnumOnlyModule !== false; + } + } + } + function declareModuleSymbol(node) { + var state = getModuleInstanceState(node); + var instantiated = state !== 0 /* NonInstantiated */; + declareSymbolAndAddToSymbolTable(node, instantiated ? 512 /* ValueModule */ : 1024 /* NamespaceModule */, instantiated ? 110735 /* ValueModuleExcludes */ : 0 /* NamespaceModuleExcludes */); + return state; + } + function bindFunctionOrConstructorType(node) { + // For a given function symbol "<...>(...) => T" we want to generate a symbol identical + // to the one we would get for: { <...>(...): T } + // + // We do that by making an anonymous type literal symbol, and then setting the function + // symbol as its sole member. To the rest of the system, this symbol will be indistinguishable + // from an actual type literal symbol you would have gotten had you used the long form. + var symbol = createSymbol(131072 /* Signature */, getDeclarationName(node)); // TODO: GH#18217 + addDeclarationToSymbol(symbol, node, 131072 /* Signature */); + var typeLiteralSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */); + addDeclarationToSymbol(typeLiteralSymbol, node, 2048 /* TypeLiteral */); + typeLiteralSymbol.members = ts.createSymbolTable(); + typeLiteralSymbol.members.set(symbol.escapedName, symbol); + } + function bindObjectLiteralExpression(node) { + var ElementKind; + (function (ElementKind) { + ElementKind[ElementKind["Property"] = 1] = "Property"; + ElementKind[ElementKind["Accessor"] = 2] = "Accessor"; + })(ElementKind || (ElementKind = {})); + if (inStrictMode) { + var seen = ts.createUnderscoreEscapedMap(); + for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { + var prop = _a[_i]; + if (prop.kind === 277 /* SpreadAssignment */ || prop.name.kind !== 72 /* Identifier */) { + continue; + } + var identifier = prop.name; + // ECMA-262 11.1.5 Object Initializer + // If previous is not undefined then throw a SyntaxError exception if any of the following conditions are true + // a.This production is contained in strict code and IsDataDescriptor(previous) is true and + // IsDataDescriptor(propId.descriptor) is true. + // b.IsDataDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true. + // c.IsAccessorDescriptor(previous) is true and IsDataDescriptor(propId.descriptor) is true. + // d.IsAccessorDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true + // and either both previous and propId.descriptor have[[Get]] fields or both previous and propId.descriptor have[[Set]] fields + var currentKind = prop.kind === 275 /* PropertyAssignment */ || prop.kind === 276 /* ShorthandPropertyAssignment */ || prop.kind === 156 /* MethodDeclaration */ + ? 1 /* Property */ + : 2 /* Accessor */; + var existingKind = seen.get(identifier.escapedText); + if (!existingKind) { + seen.set(identifier.escapedText, currentKind); + continue; + } + if (currentKind === 1 /* Property */ && existingKind === 1 /* Property */) { + var span = ts.getErrorSpanForNode(file, identifier); + file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, ts.Diagnostics.An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode)); + } + } + } + return bindAnonymousDeclaration(node, 4096 /* ObjectLiteral */, "__object" /* Object */); + } + function bindJsxAttributes(node) { + return bindAnonymousDeclaration(node, 4096 /* ObjectLiteral */, "__jsxAttributes" /* JSXAttributes */); + } + function bindJsxAttribute(node, symbolFlags, symbolExcludes) { + return declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes); + } + function bindAnonymousDeclaration(node, symbolFlags, name) { + var symbol = createSymbol(symbolFlags, name); + if (symbolFlags & (8 /* EnumMember */ | 106500 /* ClassMember */)) { + symbol.parent = container.symbol; + } + addDeclarationToSymbol(symbol, node, symbolFlags); + return symbol; + } + function bindBlockScopedDeclaration(node, symbolFlags, symbolExcludes) { + switch (blockScopeContainer.kind) { + case 244 /* ModuleDeclaration */: + declareModuleMember(node, symbolFlags, symbolExcludes); + break; + case 279 /* SourceFile */: + if (ts.isExternalOrCommonJsModule(container)) { + declareModuleMember(node, symbolFlags, symbolExcludes); + break; + } + // falls through + default: + if (!blockScopeContainer.locals) { + blockScopeContainer.locals = ts.createSymbolTable(); + addToContainerChain(blockScopeContainer); + } + declareSymbol(blockScopeContainer.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes); + } + } + function delayedBindJSDocTypedefTag() { + if (!delayedTypeAliases) { + return; + } + var saveContainer = container; + var saveLastContainer = lastContainer; + var saveBlockScopeContainer = blockScopeContainer; + var saveParent = parent; + var saveCurrentFlow = currentFlow; + for (var _i = 0, delayedTypeAliases_1 = delayedTypeAliases; _i < delayedTypeAliases_1.length; _i++) { + var typeAlias = delayedTypeAliases_1[_i]; + var host = ts.getJSDocHost(typeAlias); + container = ts.findAncestor(host.parent, function (n) { return !!(getContainerFlags(n) & 1 /* IsContainer */); }) || file; + blockScopeContainer = ts.getEnclosingBlockScopeContainer(host) || file; + currentFlow = { flags: 2 /* Start */ }; + parent = typeAlias; + bind(typeAlias.typeExpression); + if (!typeAlias.fullName || typeAlias.fullName.kind === 72 /* Identifier */) { + parent = typeAlias.parent; + bindBlockScopedDeclaration(typeAlias, 524288 /* TypeAlias */, 67897832 /* TypeAliasExcludes */); + } + else { + bind(typeAlias.fullName); + } + } + container = saveContainer; + lastContainer = saveLastContainer; + blockScopeContainer = saveBlockScopeContainer; + parent = saveParent; + currentFlow = saveCurrentFlow; + } + // The binder visits every node in the syntax tree so it is a convenient place to perform a single localized + // check for reserved words used as identifiers in strict mode code. + function checkStrictModeIdentifier(node) { + if (inStrictMode && + node.originalKeywordKind >= 109 /* FirstFutureReservedWord */ && + node.originalKeywordKind <= 117 /* LastFutureReservedWord */ && + !ts.isIdentifierName(node) && + !(node.flags & 4194304 /* Ambient */)) { + // Report error only if there are no parse errors in file + if (!file.parseDiagnostics.length) { + file.bindDiagnostics.push(createDiagnosticForNode(node, getStrictModeIdentifierMessage(node), ts.declarationNameToString(node))); + } + } + } + function getStrictModeIdentifierMessage(node) { + // Provide specialized messages to help the user understand why we think they're in + // strict mode. + if (ts.getContainingClass(node)) { + return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode; + } + if (file.externalModuleIndicator) { + return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode; + } + return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode; + } + function checkStrictModeBinaryExpression(node) { + if (inStrictMode && ts.isLeftHandSideExpression(node.left) && ts.isAssignmentOperator(node.operatorToken.kind)) { + // ECMA 262 (Annex C) The identifier eval or arguments may not appear as the LeftHandSideExpression of an + // Assignment operator(11.13) or of a PostfixExpression(11.3) + checkStrictModeEvalOrArguments(node, node.left); + } + } + function checkStrictModeCatchClause(node) { + // It is a SyntaxError if a TryStatement with a Catch occurs within strict code and the Identifier of the + // Catch production is eval or arguments + if (inStrictMode && node.variableDeclaration) { + checkStrictModeEvalOrArguments(node, node.variableDeclaration.name); + } + } + function checkStrictModeDeleteExpression(node) { + // Grammar checking + if (inStrictMode && node.expression.kind === 72 /* Identifier */) { + // When a delete operator occurs within strict mode code, a SyntaxError is thrown if its + // UnaryExpression is a direct reference to a variable, function argument, or function name + var span = ts.getErrorSpanForNode(file, node.expression); + file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, ts.Diagnostics.delete_cannot_be_called_on_an_identifier_in_strict_mode)); + } + } + function isEvalOrArgumentsIdentifier(node) { + return ts.isIdentifier(node) && (node.escapedText === "eval" || node.escapedText === "arguments"); + } + function checkStrictModeEvalOrArguments(contextNode, name) { + if (name && name.kind === 72 /* Identifier */) { + var identifier = name; + if (isEvalOrArgumentsIdentifier(identifier)) { + // We check first if the name is inside class declaration or class expression; if so give explicit message + // otherwise report generic error message. + var span = ts.getErrorSpanForNode(file, name); + file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, getStrictModeEvalOrArgumentsMessage(contextNode), ts.idText(identifier))); + } + } + } + function getStrictModeEvalOrArgumentsMessage(node) { + // Provide specialized messages to help the user understand why we think they're in + // strict mode. + if (ts.getContainingClass(node)) { + return ts.Diagnostics.Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode; + } + if (file.externalModuleIndicator) { + return ts.Diagnostics.Invalid_use_of_0_Modules_are_automatically_in_strict_mode; + } + return ts.Diagnostics.Invalid_use_of_0_in_strict_mode; + } + function checkStrictModeFunctionName(node) { + if (inStrictMode) { + // It is a SyntaxError if the identifier eval or arguments appears within a FormalParameterList of a strict mode FunctionDeclaration or FunctionExpression (13.1)) + checkStrictModeEvalOrArguments(node, node.name); + } + } + function getStrictModeBlockScopeFunctionDeclarationMessage(node) { + // Provide specialized messages to help the user understand why we think they're in + // strict mode. + if (ts.getContainingClass(node)) { + return ts.Diagnostics.Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_definitions_are_automatically_in_strict_mode; + } + if (file.externalModuleIndicator) { + return ts.Diagnostics.Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_are_automatically_in_strict_mode; + } + return ts.Diagnostics.Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5; + } + function checkStrictModeFunctionDeclaration(node) { + if (languageVersion < 2 /* ES2015 */) { + // Report error if function is not top level function declaration + if (blockScopeContainer.kind !== 279 /* SourceFile */ && + blockScopeContainer.kind !== 244 /* ModuleDeclaration */ && + !ts.isFunctionLike(blockScopeContainer)) { + // We check first if the name is inside class declaration or class expression; if so give explicit message + // otherwise report generic error message. + var errorSpan = ts.getErrorSpanForNode(file, node); + file.bindDiagnostics.push(ts.createFileDiagnostic(file, errorSpan.start, errorSpan.length, getStrictModeBlockScopeFunctionDeclarationMessage(node))); + } + } + } + function checkStrictModeNumericLiteral(node) { + if (inStrictMode && node.numericLiteralFlags & 32 /* Octal */) { + file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Octal_literals_are_not_allowed_in_strict_mode)); + } + } + function checkStrictModePostfixUnaryExpression(node) { + // Grammar checking + // The identifier eval or arguments may not appear as the LeftHandSideExpression of an + // Assignment operator(11.13) or of a PostfixExpression(11.3) or as the UnaryExpression + // operated upon by a Prefix Increment(11.4.4) or a Prefix Decrement(11.4.5) operator. + if (inStrictMode) { + checkStrictModeEvalOrArguments(node, node.operand); + } + } + function checkStrictModePrefixUnaryExpression(node) { + // Grammar checking + if (inStrictMode) { + if (node.operator === 44 /* PlusPlusToken */ || node.operator === 45 /* MinusMinusToken */) { + checkStrictModeEvalOrArguments(node, node.operand); + } + } + } + function checkStrictModeWithStatement(node) { + // Grammar checking for withStatement + if (inStrictMode) { + errorOnFirstToken(node, ts.Diagnostics.with_statements_are_not_allowed_in_strict_mode); + } + } + function checkStrictModeLabeledStatement(node) { + // Grammar checking for labeledStatement + if (inStrictMode && options.target >= 2 /* ES2015 */) { + if (ts.isDeclarationStatement(node.statement) || ts.isVariableStatement(node.statement)) { + errorOnFirstToken(node.label, ts.Diagnostics.A_label_is_not_allowed_here); + } + } + } + function errorOnFirstToken(node, message, arg0, arg1, arg2) { + var span = ts.getSpanOfTokenAtPosition(file, node.pos); + file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, message, arg0, arg1, arg2)); + } + function errorOrSuggestionOnNode(isError, node, message) { + errorOrSuggestionOnRange(isError, node, node, message); + } + function errorOrSuggestionOnRange(isError, startNode, endNode, message) { + addErrorOrSuggestionDiagnostic(isError, { pos: ts.getTokenPosOfNode(startNode, file), end: endNode.end }, message); + } + function addErrorOrSuggestionDiagnostic(isError, range, message) { + var diag = ts.createFileDiagnostic(file, range.pos, range.end - range.pos, message); + if (isError) { + file.bindDiagnostics.push(diag); + } + else { + file.bindSuggestionDiagnostics = ts.append(file.bindSuggestionDiagnostics, __assign({}, diag, { category: ts.DiagnosticCategory.Suggestion })); + } + } + function bind(node) { + if (!node) { + return; + } + node.parent = parent; + var saveInStrictMode = inStrictMode; + // Even though in the AST the jsdoc @typedef node belongs to the current node, + // its symbol might be in the same scope with the current node's symbol. Consider: + // + // /** @typedef {string | number} MyType */ + // function foo(); + // + // Here the current node is "foo", which is a container, but the scope of "MyType" should + // not be inside "foo". Therefore we always bind @typedef before bind the parent node, + // and skip binding this tag later when binding all the other jsdoc tags. + // First we bind declaration nodes to a symbol if possible. We'll both create a symbol + // and then potentially add the symbol to an appropriate symbol table. Possible + // destination symbol tables are: + // + // 1) The 'exports' table of the current container's symbol. + // 2) The 'members' table of the current container's symbol. + // 3) The 'locals' table of the current container. + // + // However, not all symbols will end up in any of these tables. 'Anonymous' symbols + // (like TypeLiterals for example) will not be put in any table. + bindWorker(node); + // Then we recurse into the children of the node to bind them as well. For certain + // symbols we do specialized work when we recurse. For example, we'll keep track of + // the current 'container' node when it changes. This helps us know which symbol table + // a local should go into for example. Since terminal nodes are known not to have + // children, as an optimization we don't process those. + if (node.kind > 147 /* LastToken */) { + var saveParent = parent; + parent = node; + var containerFlags = getContainerFlags(node); + if (containerFlags === 0 /* None */) { + bindChildren(node); + } + else { + bindContainer(node, containerFlags); + } + parent = saveParent; + } + else if (!skipTransformFlagAggregation && (node.transformFlags & 536870912 /* HasComputedFlags */) === 0) { + subtreeTransformFlags |= computeTransformFlagsForNode(node, 0); + var saveParent = parent; + if (node.kind === 1 /* EndOfFileToken */) + parent = node; + bindJSDoc(node); + parent = saveParent; + } + inStrictMode = saveInStrictMode; + } + function bindJSDoc(node) { + if (ts.hasJSDocNodes(node)) { + if (ts.isInJSFile(node)) { + for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { + var j = _a[_i]; + bind(j); + } + } + else { + for (var _b = 0, _c = node.jsDoc; _b < _c.length; _b++) { + var j = _c[_b]; + setParentPointers(node, j); + } + } + } + } + function updateStrictModeStatementList(statements) { + if (!inStrictMode) { + for (var _i = 0, statements_1 = statements; _i < statements_1.length; _i++) { + var statement = statements_1[_i]; + if (!ts.isPrologueDirective(statement)) { + return; + } + if (isUseStrictPrologueDirective(statement)) { + inStrictMode = true; + return; + } + } + } + } + /// Should be called only on prologue directives (isPrologueDirective(node) should be true) + function isUseStrictPrologueDirective(node) { + var nodeText = ts.getSourceTextOfNodeFromSourceFile(file, node.expression); + // Note: the node text must be exactly "use strict" or 'use strict'. It is not ok for the + // string to contain unicode escapes (as per ES5). + return nodeText === '"use strict"' || nodeText === "'use strict'"; + } + function bindWorker(node) { + switch (node.kind) { + /* Strict mode checks */ + case 72 /* Identifier */: + // for typedef type names with namespaces, bind the new jsdoc type symbol here + // because it requires all containing namespaces to be in effect, namely the + // current "blockScopeContainer" needs to be set to its immediate namespace parent. + if (node.isInJSDocNamespace) { + var parentNode = node.parent; + while (parentNode && !ts.isJSDocTypeAlias(parentNode)) { + parentNode = parentNode.parent; + } + bindBlockScopedDeclaration(parentNode, 524288 /* TypeAlias */, 67897832 /* TypeAliasExcludes */); + break; + } + // falls through + case 100 /* ThisKeyword */: + if (currentFlow && (ts.isExpression(node) || parent.kind === 276 /* ShorthandPropertyAssignment */)) { + node.flowNode = currentFlow; + } + return checkStrictModeIdentifier(node); + case 189 /* PropertyAccessExpression */: + case 190 /* ElementAccessExpression */: + if (currentFlow && isNarrowableReference(node)) { + node.flowNode = currentFlow; + } + if (ts.isSpecialPropertyDeclaration(node)) { + bindSpecialPropertyDeclaration(node); + } + if (ts.isInJSFile(node) && + file.commonJsModuleIndicator && + ts.isModuleExportsPropertyAccessExpression(node) && + !lookupSymbolForNameWorker(blockScopeContainer, "module")) { + declareSymbol(file.locals, /*parent*/ undefined, node.expression, 1 /* FunctionScopedVariable */ | 134217728 /* ModuleExports */, 67220414 /* FunctionScopedVariableExcludes */); + } + break; + case 204 /* BinaryExpression */: + var specialKind = ts.getAssignmentDeclarationKind(node); + switch (specialKind) { + case 1 /* ExportsProperty */: + bindExportsPropertyAssignment(node); + break; + case 2 /* ModuleExports */: + bindModuleExportsAssignment(node); + break; + case 3 /* PrototypeProperty */: + bindPrototypePropertyAssignment(node.left, node); + break; + case 6 /* Prototype */: + bindPrototypeAssignment(node); + break; + case 4 /* ThisProperty */: + bindThisPropertyAssignment(node); + break; + case 5 /* Property */: + bindSpecialPropertyAssignment(node); + break; + case 0 /* None */: + // Nothing to do + break; + default: + ts.Debug.fail("Unknown binary expression special property assignment kind"); + } + return checkStrictModeBinaryExpression(node); + case 274 /* CatchClause */: + return checkStrictModeCatchClause(node); + case 198 /* DeleteExpression */: + return checkStrictModeDeleteExpression(node); + case 8 /* NumericLiteral */: + return checkStrictModeNumericLiteral(node); + case 203 /* PostfixUnaryExpression */: + return checkStrictModePostfixUnaryExpression(node); + case 202 /* PrefixUnaryExpression */: + return checkStrictModePrefixUnaryExpression(node); + case 231 /* WithStatement */: + return checkStrictModeWithStatement(node); + case 233 /* LabeledStatement */: + return checkStrictModeLabeledStatement(node); + case 178 /* ThisType */: + seenThisKeyword = true; + return; + case 163 /* TypePredicate */: + break; // Binding the children will handle everything + case 150 /* TypeParameter */: + return bindTypeParameter(node); + case 151 /* Parameter */: + return bindParameter(node); + case 237 /* VariableDeclaration */: + return bindVariableDeclarationOrBindingElement(node); + case 186 /* BindingElement */: + node.flowNode = currentFlow; + return bindVariableDeclarationOrBindingElement(node); + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + return bindPropertyWorker(node); + case 275 /* PropertyAssignment */: + case 276 /* ShorthandPropertyAssignment */: + return bindPropertyOrMethodOrAccessor(node, 4 /* Property */, 0 /* PropertyExcludes */); + case 278 /* EnumMember */: + return bindPropertyOrMethodOrAccessor(node, 8 /* EnumMember */, 68008959 /* EnumMemberExcludes */); + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 162 /* IndexSignature */: + return declareSymbolAndAddToSymbolTable(node, 131072 /* Signature */, 0 /* None */); + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + // If this is an ObjectLiteralExpression method, then it sits in the same space + // as other properties in the object literal. So we use SymbolFlags.PropertyExcludes + // so that it will conflict with any other object literal members with the same + // name. + return bindPropertyOrMethodOrAccessor(node, 8192 /* Method */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), ts.isObjectLiteralMethod(node) ? 0 /* PropertyExcludes */ : 67212223 /* MethodExcludes */); + case 239 /* FunctionDeclaration */: + return bindFunctionDeclaration(node); + case 157 /* Constructor */: + return declareSymbolAndAddToSymbolTable(node, 16384 /* Constructor */, /*symbolExcludes:*/ 0 /* None */); + case 158 /* GetAccessor */: + return bindPropertyOrMethodOrAccessor(node, 32768 /* GetAccessor */, 67154879 /* GetAccessorExcludes */); + case 159 /* SetAccessor */: + return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 67187647 /* SetAccessorExcludes */); + case 165 /* FunctionType */: + case 289 /* JSDocFunctionType */: + case 293 /* JSDocSignature */: + case 166 /* ConstructorType */: + return bindFunctionOrConstructorType(node); + case 168 /* TypeLiteral */: + case 292 /* JSDocTypeLiteral */: + case 181 /* MappedType */: + return bindAnonymousTypeWorker(node); + case 188 /* ObjectLiteralExpression */: + return bindObjectLiteralExpression(node); + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + return bindFunctionExpression(node); + case 191 /* CallExpression */: + var assignmentKind = ts.getAssignmentDeclarationKind(node); + switch (assignmentKind) { + case 7 /* ObjectDefinePropertyValue */: + return bindObjectDefinePropertyAssignment(node); + case 8 /* ObjectDefinePropertyExports */: + return bindObjectDefinePropertyExport(node); + case 9 /* ObjectDefinePrototypeProperty */: + return bindObjectDefinePrototypeProperty(node); + case 0 /* None */: + break; // Nothing to do + default: + return ts.Debug.fail("Unknown call expression assignment declaration kind"); + } + if (ts.isInJSFile(node)) { + bindCallExpression(node); + } + break; + // Members of classes, interfaces, and modules + case 209 /* ClassExpression */: + case 240 /* ClassDeclaration */: + // All classes are automatically in strict mode in ES6. + inStrictMode = true; + return bindClassLikeDeclaration(node); + case 241 /* InterfaceDeclaration */: + return bindBlockScopedDeclaration(node, 64 /* Interface */, 67897736 /* InterfaceExcludes */); + case 242 /* TypeAliasDeclaration */: + return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 67897832 /* TypeAliasExcludes */); + case 243 /* EnumDeclaration */: + return bindEnumDeclaration(node); + case 244 /* ModuleDeclaration */: + return bindModuleDeclaration(node); + // Jsx-attributes + case 268 /* JsxAttributes */: + return bindJsxAttributes(node); + case 267 /* JsxAttribute */: + return bindJsxAttribute(node, 4 /* Property */, 0 /* PropertyExcludes */); + // Imports and exports + case 248 /* ImportEqualsDeclaration */: + case 251 /* NamespaceImport */: + case 253 /* ImportSpecifier */: + case 257 /* ExportSpecifier */: + return declareSymbolAndAddToSymbolTable(node, 2097152 /* Alias */, 2097152 /* AliasExcludes */); + case 247 /* NamespaceExportDeclaration */: + return bindNamespaceExportDeclaration(node); + case 250 /* ImportClause */: + return bindImportClause(node); + case 255 /* ExportDeclaration */: + return bindExportDeclaration(node); + case 254 /* ExportAssignment */: + return bindExportAssignment(node); + case 279 /* SourceFile */: + updateStrictModeStatementList(node.statements); + return bindSourceFileIfExternalModule(); + case 218 /* Block */: + if (!ts.isFunctionLike(node.parent)) { + return; + } + // falls through + case 245 /* ModuleBlock */: + return updateStrictModeStatementList(node.statements); + case 299 /* JSDocParameterTag */: + if (node.parent.kind === 293 /* JSDocSignature */) { + return bindParameter(node); + } + if (node.parent.kind !== 292 /* JSDocTypeLiteral */) { + break; + } + // falls through + case 305 /* JSDocPropertyTag */: + var propTag = node; + var flags = propTag.isBracketed || propTag.typeExpression && propTag.typeExpression.type.kind === 288 /* JSDocOptionalType */ ? + 4 /* Property */ | 16777216 /* Optional */ : + 4 /* Property */; + return declareSymbolAndAddToSymbolTable(propTag, flags, 0 /* PropertyExcludes */); + case 304 /* JSDocTypedefTag */: + case 297 /* JSDocCallbackTag */: + return (delayedTypeAliases || (delayedTypeAliases = [])).push(node); + } + } + function bindPropertyWorker(node) { + return bindPropertyOrMethodOrAccessor(node, 4 /* Property */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), 0 /* PropertyExcludes */); + } + function bindAnonymousTypeWorker(node) { + return bindAnonymousDeclaration(node, 2048 /* TypeLiteral */, "__type" /* Type */); + } + function bindSourceFileIfExternalModule() { + setExportContextFlag(file); + if (ts.isExternalModule(file)) { + bindSourceFileAsExternalModule(); + } + else if (ts.isJsonSourceFile(file)) { + bindSourceFileAsExternalModule(); + // Create symbol equivalent for the module.exports = {} + var originalSymbol = file.symbol; + declareSymbol(file.symbol.exports, file.symbol, file, 4 /* Property */, 67108863 /* All */); + file.symbol = originalSymbol; + } + } + function bindSourceFileAsExternalModule() { + bindAnonymousDeclaration(file, 512 /* ValueModule */, "\"" + ts.removeFileExtension(file.fileName) + "\""); + } + function bindExportAssignment(node) { + if (!container.symbol || !container.symbol.exports) { + // Export assignment in some sort of block construct + bindAnonymousDeclaration(node, 2097152 /* Alias */, getDeclarationName(node)); + } + else { + var flags = ts.exportAssignmentIsAlias(node) + // An export default clause with an EntityNameExpression or a class expression exports all meanings of that identifier or expression; + ? 2097152 /* Alias */ + // An export default clause with any other expression exports a value + : 4 /* Property */; + // If there is an `export default x;` alias declaration, can't `export default` anything else. + // (In contrast, you can still have `export default function f() {}` and `export default interface I {}`.) + var symbol = declareSymbol(container.symbol.exports, container.symbol, node, flags, 67108863 /* All */); + if (node.isExportEquals) { + // Will be an error later, since the module already has other exports. Just make sure this has a valueDeclaration set. + setValueDeclaration(symbol, node); + } + } + } + function bindNamespaceExportDeclaration(node) { + if (node.modifiers && node.modifiers.length) { + file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Modifiers_cannot_appear_here)); + } + var diag = !ts.isSourceFile(node.parent) ? ts.Diagnostics.Global_module_exports_may_only_appear_at_top_level + : !ts.isExternalModule(node.parent) ? ts.Diagnostics.Global_module_exports_may_only_appear_in_module_files + : !node.parent.isDeclarationFile ? ts.Diagnostics.Global_module_exports_may_only_appear_in_declaration_files + : undefined; + if (diag) { + file.bindDiagnostics.push(createDiagnosticForNode(node, diag)); + } + else { + file.symbol.globalExports = file.symbol.globalExports || ts.createSymbolTable(); + declareSymbol(file.symbol.globalExports, file.symbol, node, 2097152 /* Alias */, 2097152 /* AliasExcludes */); + } + } + function bindExportDeclaration(node) { + if (!container.symbol || !container.symbol.exports) { + // Export * in some sort of block construct + bindAnonymousDeclaration(node, 8388608 /* ExportStar */, getDeclarationName(node)); + } + else if (!node.exportClause) { + // All export * declarations are collected in an __export symbol + declareSymbol(container.symbol.exports, container.symbol, node, 8388608 /* ExportStar */, 0 /* None */); + } + } + function bindImportClause(node) { + if (node.name) { + declareSymbolAndAddToSymbolTable(node, 2097152 /* Alias */, 2097152 /* AliasExcludes */); + } + } + function setCommonJsModuleIndicator(node) { + if (file.externalModuleIndicator) { + return false; + } + if (!file.commonJsModuleIndicator) { + file.commonJsModuleIndicator = node; + bindSourceFileAsExternalModule(); + } + return true; + } + function bindObjectDefinePropertyExport(node) { + if (!setCommonJsModuleIndicator(node)) { + return; + } + var symbol = forEachIdentifierInEntityName(node.arguments[0], /*parent*/ undefined, function (id, symbol) { + if (symbol) { + addDeclarationToSymbol(symbol, id, 1536 /* Module */ | 67108864 /* Assignment */); + } + return symbol; + }); + if (symbol) { + var flags = 4 /* Property */ | 1048576 /* ExportValue */; + declareSymbol(symbol.exports, symbol, node, flags, 0 /* None */); + } + } + function bindExportsPropertyAssignment(node) { + // When we create a property via 'exports.foo = bar', the 'exports.foo' property access + // expression is the declaration + if (!setCommonJsModuleIndicator(node)) { + return; + } + var lhs = node.left; + var symbol = forEachIdentifierInEntityName(lhs.expression, /*parent*/ undefined, function (id, symbol) { + if (symbol) { + addDeclarationToSymbol(symbol, id, 1536 /* Module */ | 67108864 /* Assignment */); + } + return symbol; + }); + if (symbol) { + var flags = ts.isClassExpression(node.right) ? + 4 /* Property */ | 1048576 /* ExportValue */ | 32 /* Class */ : + 4 /* Property */ | 1048576 /* ExportValue */; + declareSymbol(symbol.exports, symbol, lhs, flags, 0 /* None */); + } + } + function bindModuleExportsAssignment(node) { + // A common practice in node modules is to set 'export = module.exports = {}', this ensures that 'exports' + // is still pointing to 'module.exports'. + // We do not want to consider this as 'export=' since a module can have only one of these. + // Similarly we do not want to treat 'module.exports = exports' as an 'export='. + if (!setCommonJsModuleIndicator(node)) { + return; + } + var assignedExpression = ts.getRightMostAssignedExpression(node.right); + if (ts.isEmptyObjectLiteral(assignedExpression) || container === file && isExportsOrModuleExportsOrAlias(file, assignedExpression)) { + return; + } + // 'module.exports = expr' assignment + var flags = ts.exportAssignmentIsAlias(node) + ? 2097152 /* Alias */ + : 4 /* Property */ | 1048576 /* ExportValue */ | 512 /* ValueModule */; + declareSymbol(file.symbol.exports, file.symbol, node, flags | 67108864 /* Assignment */, 0 /* None */); + } + function bindThisPropertyAssignment(node) { + ts.Debug.assert(ts.isInJSFile(node)); + var thisContainer = ts.getThisContainer(node, /*includeArrowFunctions*/ false); + switch (thisContainer.kind) { + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + var constructorSymbol = thisContainer.symbol; + // For `f.prototype.m = function() { this.x = 0; }`, `this.x = 0` should modify `f`'s members, not the function expression. + if (ts.isBinaryExpression(thisContainer.parent) && thisContainer.parent.operatorToken.kind === 59 /* EqualsToken */) { + var l = thisContainer.parent.left; + if (ts.isPropertyAccessEntityNameExpression(l) && ts.isPrototypeAccess(l.expression)) { + constructorSymbol = lookupSymbolForPropertyAccess(l.expression.expression, thisParentContainer); + } + } + if (constructorSymbol) { + // Declare a 'member' if the container is an ES5 class or ES6 constructor + constructorSymbol.members = constructorSymbol.members || ts.createSymbolTable(); + // It's acceptable for multiple 'this' assignments of the same identifier to occur + declareSymbol(constructorSymbol.members, constructorSymbol, node, 4 /* Property */, 0 /* PropertyExcludes */ & ~4 /* Property */); + } + break; + case 157 /* Constructor */: + case 154 /* PropertyDeclaration */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + // this.foo assignment in a JavaScript class + // Bind this property to the containing class + var containingClass = thisContainer.parent; + var symbolTable = ts.hasModifier(thisContainer, 32 /* Static */) ? containingClass.symbol.exports : containingClass.symbol.members; + declareSymbol(symbolTable, containingClass.symbol, node, 4 /* Property */, 0 /* None */, /*isReplaceableByMethod*/ true); + break; + case 279 /* SourceFile */: + // this.foo assignment in a source file + // Do not bind. It would be nice to support this someday though. + break; + default: + ts.Debug.fail(ts.Debug.showSyntaxKind(thisContainer)); + } + } + function bindSpecialPropertyDeclaration(node) { + if (node.expression.kind === 100 /* ThisKeyword */) { + bindThisPropertyAssignment(node); + } + else if (ts.isPropertyAccessEntityNameExpression(node) && node.parent.parent.kind === 279 /* SourceFile */) { + if (ts.isPrototypeAccess(node.expression)) { + bindPrototypePropertyAssignment(node, node.parent); + } + else { + bindStaticPropertyAssignment(node); + } + } + } + /** For `x.prototype = { p, ... }`, declare members p,... if `x` is function/class/{}, or not declared. */ + function bindPrototypeAssignment(node) { + node.left.parent = node; + node.right.parent = node; + var lhs = node.left; + bindPropertyAssignment(lhs.expression, lhs, /*isPrototypeProperty*/ false); + } + function bindObjectDefinePrototypeProperty(node) { + var namespaceSymbol = lookupSymbolForPropertyAccess(node.arguments[0].expression); + bindPotentiallyNewExpandoMemberToNamespace(node, namespaceSymbol, /*isPrototypeProperty*/ true); + } + /** + * For `x.prototype.y = z`, declare a member `y` on `x` if `x` is a function or class, or not declared. + * Note that jsdoc preceding an ExpressionStatement like `x.prototype.y;` is also treated as a declaration. + */ + function bindPrototypePropertyAssignment(lhs, parent) { + // Look up the function in the local scope, since prototype assignments should + // follow the function declaration + var classPrototype = lhs.expression; + var constructorFunction = classPrototype.expression; + // Fix up parent pointers since we're going to use these nodes before we bind into them + lhs.parent = parent; + constructorFunction.parent = classPrototype; + classPrototype.parent = lhs; + bindPropertyAssignment(constructorFunction, lhs, /*isPrototypeProperty*/ true); + } + function bindObjectDefinePropertyAssignment(node) { + var namespaceSymbol = lookupSymbolForPropertyAccess(node.arguments[0]); + var isToplevel = node.parent.parent.kind === 279 /* SourceFile */; + namespaceSymbol = bindPotentiallyMissingNamespaces(namespaceSymbol, node.arguments[0], isToplevel, /*isPrototypeProperty*/ false); + bindPotentiallyNewExpandoMemberToNamespace(node, namespaceSymbol, /*isPrototypeProperty*/ false); + } + function bindSpecialPropertyAssignment(node) { + var lhs = node.left; + // Class declarations in Typescript do not allow property declarations + var parentSymbol = lookupSymbolForPropertyAccess(lhs.expression); + if (!ts.isInJSFile(node) && !ts.isFunctionSymbol(parentSymbol)) { + return; + } + // Fix up parent pointers since we're going to use these nodes before we bind into them + node.left.parent = node; + node.right.parent = node; + if (ts.isIdentifier(lhs.expression) && container === file && isNameOfExportsOrModuleExportsAliasDeclaration(file, lhs.expression)) { + // This can be an alias for the 'exports' or 'module.exports' names, e.g. + // var util = module.exports; + // util.property = function ... + bindExportsPropertyAssignment(node); + } + else { + bindStaticPropertyAssignment(lhs); + } + } + /** + * For nodes like `x.y = z`, declare a member 'y' on 'x' if x is a function (or IIFE) or class or {}, or not declared. + * Also works for expression statements preceded by JSDoc, like / ** @type number * / x.y; + */ + function bindStaticPropertyAssignment(node) { + node.expression.parent = node; + bindPropertyAssignment(node.expression, node, /*isPrototypeProperty*/ false); + } + function bindPotentiallyMissingNamespaces(namespaceSymbol, entityName, isToplevel, isPrototypeProperty) { + if (isToplevel && !isPrototypeProperty && (!namespaceSymbol || !(namespaceSymbol.flags & 1920 /* Namespace */))) { + // make symbols or add declarations for intermediate containers + var flags_1 = 1536 /* Module */ | 67108864 /* Assignment */; + var excludeFlags_1 = 110735 /* ValueModuleExcludes */ & ~67108864 /* Assignment */; + namespaceSymbol = forEachIdentifierInEntityName(entityName, namespaceSymbol, function (id, symbol, parent) { + if (symbol) { + addDeclarationToSymbol(symbol, id, flags_1); + return symbol; + } + else { + var table = parent ? parent.exports : + file.jsGlobalAugmentations || (file.jsGlobalAugmentations = ts.createSymbolTable()); + return declareSymbol(table, parent, id, flags_1, excludeFlags_1); + } + }); + } + return namespaceSymbol; + } + function bindPotentiallyNewExpandoMemberToNamespace(declaration, namespaceSymbol, isPrototypeProperty) { + if (!namespaceSymbol || !isExpandoSymbol(namespaceSymbol)) { + return; + } + // Set up the members collection if it doesn't exist already + var symbolTable = isPrototypeProperty ? + (namespaceSymbol.members || (namespaceSymbol.members = ts.createSymbolTable())) : + (namespaceSymbol.exports || (namespaceSymbol.exports = ts.createSymbolTable())); + var isMethod = ts.isFunctionLikeDeclaration(ts.getAssignedExpandoInitializer(declaration)); + var includes = isMethod ? 8192 /* Method */ : 4 /* Property */; + var excludes = isMethod ? 67212223 /* MethodExcludes */ : 0 /* PropertyExcludes */; + declareSymbol(symbolTable, namespaceSymbol, declaration, includes | 67108864 /* Assignment */, excludes & ~67108864 /* Assignment */); + } + function bindPropertyAssignment(name, propertyAccess, isPrototypeProperty) { + var namespaceSymbol = lookupSymbolForPropertyAccess(name); + var isToplevel = ts.isBinaryExpression(propertyAccess.parent) + ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 279 /* SourceFile */ + : propertyAccess.parent.parent.kind === 279 /* SourceFile */; + namespaceSymbol = bindPotentiallyMissingNamespaces(namespaceSymbol, propertyAccess.expression, isToplevel, isPrototypeProperty); + bindPotentiallyNewExpandoMemberToNamespace(propertyAccess, namespaceSymbol, isPrototypeProperty); + } + /** + * Javascript expando values are: + * - Functions + * - classes + * - namespaces + * - variables initialized with function expressions + * - with class expressions + * - with empty object literals + * - with non-empty object literals if assigned to the prototype property + */ + function isExpandoSymbol(symbol) { + if (symbol.flags & (16 /* Function */ | 32 /* Class */ | 1024 /* NamespaceModule */)) { + return true; + } + var node = symbol.valueDeclaration; + if (node && ts.isCallExpression(node)) { + return !!ts.getAssignedExpandoInitializer(node); + } + var init = !node ? undefined : + ts.isVariableDeclaration(node) ? node.initializer : + ts.isBinaryExpression(node) ? node.right : + ts.isPropertyAccessExpression(node) && ts.isBinaryExpression(node.parent) ? node.parent.right : + undefined; + init = init && ts.getRightMostAssignedExpression(init); + if (init) { + var isPrototypeAssignment = ts.isPrototypeAccess(ts.isVariableDeclaration(node) ? node.name : ts.isBinaryExpression(node) ? node.left : node); + return !!ts.getExpandoInitializer(ts.isBinaryExpression(init) && init.operatorToken.kind === 55 /* BarBarToken */ ? init.right : init, isPrototypeAssignment); + } + return false; + } + function getParentOfBinaryExpression(expr) { + while (ts.isBinaryExpression(expr.parent)) { + expr = expr.parent; + } + return expr.parent; + } + function lookupSymbolForPropertyAccess(node, lookupContainer) { + if (lookupContainer === void 0) { lookupContainer = container; } + if (ts.isIdentifier(node)) { + return lookupSymbolForNameWorker(lookupContainer, node.escapedText); + } + else { + var symbol = lookupSymbolForPropertyAccess(node.expression); + return symbol && symbol.exports && symbol.exports.get(node.name.escapedText); + } + } + function forEachIdentifierInEntityName(e, parent, action) { + if (isExportsOrModuleExportsOrAlias(file, e)) { + return file.symbol; + } + else if (ts.isIdentifier(e)) { + return action(e, lookupSymbolForPropertyAccess(e), parent); + } + else { + var s = forEachIdentifierInEntityName(e.expression, parent, action); + if (!s || !s.exports) + return ts.Debug.fail(); + return action(e.name, s.exports.get(e.name.escapedText), s); + } + } + function bindCallExpression(node) { + // We're only inspecting call expressions to detect CommonJS modules, so we can skip + // this check if we've already seen the module indicator + if (!file.commonJsModuleIndicator && ts.isRequireCall(node, /*checkArgumentIsStringLiteralLike*/ false)) { + setCommonJsModuleIndicator(node); + } + } + function bindClassLikeDeclaration(node) { + if (node.kind === 240 /* ClassDeclaration */) { + bindBlockScopedDeclaration(node, 32 /* Class */, 68008383 /* ClassExcludes */); + } + else { + var bindingName = node.name ? node.name.escapedText : "__class" /* Class */; + bindAnonymousDeclaration(node, 32 /* Class */, bindingName); + // Add name of class expression into the map for semantic classifier + if (node.name) { + classifiableNames.set(node.name.escapedText, true); + } + } + var symbol = node.symbol; + // TypeScript 1.0 spec (April 2014): 8.4 + // Every class automatically contains a static property member named 'prototype', the + // type of which is an instantiation of the class type with type Any supplied as a type + // argument for each type parameter. It is an error to explicitly declare a static + // property member with the name 'prototype'. + // + // Note: we check for this here because this class may be merging into a module. The + // module might have an exported variable called 'prototype'. We can't allow that as + // that would clash with the built-in 'prototype' for the class. + var prototypeSymbol = createSymbol(4 /* Property */ | 4194304 /* Prototype */, "prototype"); + var symbolExport = symbol.exports.get(prototypeSymbol.escapedName); + if (symbolExport) { + if (node.name) { + node.name.parent = node; + } + file.bindDiagnostics.push(createDiagnosticForNode(symbolExport.declarations[0], ts.Diagnostics.Duplicate_identifier_0, ts.symbolName(prototypeSymbol))); + } + symbol.exports.set(prototypeSymbol.escapedName, prototypeSymbol); + prototypeSymbol.parent = symbol; + } + function bindEnumDeclaration(node) { + return ts.isEnumConst(node) + ? bindBlockScopedDeclaration(node, 128 /* ConstEnum */, 68008831 /* ConstEnumExcludes */) + : bindBlockScopedDeclaration(node, 256 /* RegularEnum */, 68008191 /* RegularEnumExcludes */); + } + function bindVariableDeclarationOrBindingElement(node) { + if (inStrictMode) { + checkStrictModeEvalOrArguments(node, node.name); + } + if (!ts.isBindingPattern(node.name)) { + var isEnum = ts.isInJSFile(node) && !!ts.getJSDocEnumTag(node); + var enumFlags = (isEnum ? 256 /* RegularEnum */ : 0 /* None */); + var enumExcludes = (isEnum ? 68008191 /* RegularEnumExcludes */ : 0 /* None */); + if (ts.isBlockOrCatchScoped(node)) { + bindBlockScopedDeclaration(node, 2 /* BlockScopedVariable */ | enumFlags, 67220415 /* BlockScopedVariableExcludes */ | enumExcludes); + } + else if (ts.isParameterDeclaration(node)) { + // It is safe to walk up parent chain to find whether the node is a destructuring parameter declaration + // because its parent chain has already been set up, since parents are set before descending into children. + // + // If node is a binding element in parameter declaration, we need to use ParameterExcludes. + // Using ParameterExcludes flag allows the compiler to report an error on duplicate identifiers in Parameter Declaration + // For example: + // function foo([a,a]) {} // Duplicate Identifier error + // function bar(a,a) {} // Duplicate Identifier error, parameter declaration in this case is handled in bindParameter + // // which correctly set excluded symbols + declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67220415 /* ParameterExcludes */); + } + else { + declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */ | enumFlags, 67220414 /* FunctionScopedVariableExcludes */ | enumExcludes); + } + } + } + function bindParameter(node) { + if (node.kind === 299 /* JSDocParameterTag */ && container.kind !== 293 /* JSDocSignature */) { + return; + } + if (inStrictMode && !(node.flags & 4194304 /* Ambient */)) { + // It is a SyntaxError if the identifier eval or arguments appears within a FormalParameterList of a + // strict mode FunctionLikeDeclaration or FunctionExpression(13.1) + checkStrictModeEvalOrArguments(node, node.name); + } + if (ts.isBindingPattern(node.name)) { + bindAnonymousDeclaration(node, 1 /* FunctionScopedVariable */, "__" + node.parent.parameters.indexOf(node)); + } + else { + declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67220415 /* ParameterExcludes */); + } + // If this is a property-parameter, then also declare the property symbol into the + // containing class. + if (ts.isParameterPropertyDeclaration(node)) { + var classDeclaration = node.parent.parent; + declareSymbol(classDeclaration.symbol.members, classDeclaration.symbol, node, 4 /* Property */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), 0 /* PropertyExcludes */); + } + } + function bindFunctionDeclaration(node) { + if (!file.isDeclarationFile && !(node.flags & 4194304 /* Ambient */)) { + if (ts.isAsyncFunction(node)) { + emitFlags |= 1024 /* HasAsyncFunctions */; + } + } + checkStrictModeFunctionName(node); + if (inStrictMode) { + checkStrictModeFunctionDeclaration(node); + bindBlockScopedDeclaration(node, 16 /* Function */, 67219887 /* FunctionExcludes */); + } + else { + declareSymbolAndAddToSymbolTable(node, 16 /* Function */, 67219887 /* FunctionExcludes */); + } + } + function bindFunctionExpression(node) { + if (!file.isDeclarationFile && !(node.flags & 4194304 /* Ambient */)) { + if (ts.isAsyncFunction(node)) { + emitFlags |= 1024 /* HasAsyncFunctions */; + } + } + if (currentFlow) { + node.flowNode = currentFlow; + } + checkStrictModeFunctionName(node); + var bindingName = node.name ? node.name.escapedText : "__function" /* Function */; + return bindAnonymousDeclaration(node, 16 /* Function */, bindingName); + } + function bindPropertyOrMethodOrAccessor(node, symbolFlags, symbolExcludes) { + if (!file.isDeclarationFile && !(node.flags & 4194304 /* Ambient */) && ts.isAsyncFunction(node)) { + emitFlags |= 1024 /* HasAsyncFunctions */; + } + if (currentFlow && ts.isObjectLiteralOrClassExpressionMethod(node)) { + node.flowNode = currentFlow; + } + return ts.hasDynamicName(node) + ? bindAnonymousDeclaration(node, symbolFlags, "__computed" /* Computed */) + : declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes); + } + function getInferTypeContainer(node) { + var extendsType = ts.findAncestor(node, function (n) { return n.parent && ts.isConditionalTypeNode(n.parent) && n.parent.extendsType === n; }); + return extendsType && extendsType.parent; + } + function bindTypeParameter(node) { + if (ts.isJSDocTemplateTag(node.parent)) { + var container_1 = ts.find(node.parent.parent.tags, ts.isJSDocTypeAlias) || ts.getHostSignatureFromJSDoc(node.parent); // TODO: GH#18217 + if (container_1) { + if (!container_1.locals) { + container_1.locals = ts.createSymbolTable(); + } + declareSymbol(container_1.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 67635688 /* TypeParameterExcludes */); + } + else { + declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 67635688 /* TypeParameterExcludes */); + } + } + else if (node.parent.kind === 176 /* InferType */) { + var container_2 = getInferTypeContainer(node.parent); + if (container_2) { + if (!container_2.locals) { + container_2.locals = ts.createSymbolTable(); + } + declareSymbol(container_2.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 67635688 /* TypeParameterExcludes */); + } + else { + bindAnonymousDeclaration(node, 262144 /* TypeParameter */, getDeclarationName(node)); // TODO: GH#18217 + } + } + else { + declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 67635688 /* TypeParameterExcludes */); + } + } + // reachability checks + function shouldReportErrorOnModuleDeclaration(node) { + var instanceState = getModuleInstanceState(node); + return instanceState === 1 /* Instantiated */ || (instanceState === 2 /* ConstEnumOnly */ && !!options.preserveConstEnums); + } + function checkUnreachable(node) { + if (!(currentFlow.flags & 1 /* Unreachable */)) { + return false; + } + if (currentFlow === unreachableFlow) { + var reportError = + // report error on all statements except empty ones + (ts.isStatementButNotDeclaration(node) && node.kind !== 220 /* EmptyStatement */) || + // report error on class declarations + node.kind === 240 /* ClassDeclaration */ || + // report error on instantiated modules or const-enums only modules if preserveConstEnums is set + (node.kind === 244 /* ModuleDeclaration */ && shouldReportErrorOnModuleDeclaration(node)); + if (reportError) { + currentFlow = reportedUnreachableFlow; + if (!options.allowUnreachableCode) { + // unreachable code is reported if + // - user has explicitly asked about it AND + // - statement is in not ambient context (statements in ambient context is already an error + // so we should not report extras) AND + // - node is not variable statement OR + // - node is block scoped variable statement OR + // - node is not block scoped variable statement and at least one variable declaration has initializer + // Rationale: we don't want to report errors on non-initialized var's since they are hoisted + // On the other side we do want to report errors on non-initialized 'lets' because of TDZ + var isError_1 = ts.unreachableCodeIsError(options) && + !(node.flags & 4194304 /* Ambient */) && + (!ts.isVariableStatement(node) || + !!(ts.getCombinedNodeFlags(node.declarationList) & 3 /* BlockScoped */) || + node.declarationList.declarations.some(function (d) { return !!d.initializer; })); + eachUnreachableRange(node, function (start, end) { return errorOrSuggestionOnRange(isError_1, start, end, ts.Diagnostics.Unreachable_code_detected); }); + } + } + } + return true; + } + } + function eachUnreachableRange(node, cb) { + if (ts.isStatement(node) && isExecutableStatement(node) && ts.isBlock(node.parent)) { + var statements = node.parent.statements; + var slice_1 = ts.sliceAfter(statements, node); + ts.getRangesWhere(slice_1, isExecutableStatement, function (start, afterEnd) { return cb(slice_1[start], slice_1[afterEnd - 1]); }); + } + else { + cb(node, node); + } + } + // As opposed to a pure declaration like an `interface` + function isExecutableStatement(s) { + // Don't remove statements that can validly be used before they appear. + return !ts.isFunctionDeclaration(s) && !isPurelyTypeDeclaration(s) && !ts.isEnumDeclaration(s) && + // `var x;` may declare a variable used above + !(ts.isVariableStatement(s) && !(ts.getCombinedNodeFlags(s) & (1 /* Let */ | 2 /* Const */)) && s.declarationList.declarations.some(function (d) { return !d.initializer; })); + } + function isPurelyTypeDeclaration(s) { + switch (s.kind) { + case 241 /* InterfaceDeclaration */: + case 242 /* TypeAliasDeclaration */: + return true; + case 244 /* ModuleDeclaration */: + return getModuleInstanceState(s) !== 1 /* Instantiated */; + case 243 /* EnumDeclaration */: + return ts.hasModifier(s, 2048 /* Const */); + default: + return false; + } + } + function isExportsOrModuleExportsOrAlias(sourceFile, node) { + return ts.isExportsIdentifier(node) || + ts.isModuleExportsPropertyAccessExpression(node) || + ts.isIdentifier(node) && isNameOfExportsOrModuleExportsAliasDeclaration(sourceFile, node); + } + ts.isExportsOrModuleExportsOrAlias = isExportsOrModuleExportsOrAlias; + function isNameOfExportsOrModuleExportsAliasDeclaration(sourceFile, node) { + var symbol = lookupSymbolForNameWorker(sourceFile, node.escapedText); + return !!symbol && !!symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && + !!symbol.valueDeclaration.initializer && isExportsOrModuleExportsOrAliasOrAssignment(sourceFile, symbol.valueDeclaration.initializer); + } + function isExportsOrModuleExportsOrAliasOrAssignment(sourceFile, node) { + return isExportsOrModuleExportsOrAlias(sourceFile, node) || + (ts.isAssignmentExpression(node, /*excludeCompoundAssignment*/ true) && (isExportsOrModuleExportsOrAliasOrAssignment(sourceFile, node.left) || isExportsOrModuleExportsOrAliasOrAssignment(sourceFile, node.right))); + } + function lookupSymbolForNameWorker(container, name) { + var local = container.locals && container.locals.get(name); + if (local) { + return local.exportSymbol || local; + } + if (ts.isSourceFile(container) && container.jsGlobalAugmentations && container.jsGlobalAugmentations.has(name)) { + return container.jsGlobalAugmentations.get(name); + } + return container.symbol && container.symbol.exports && container.symbol.exports.get(name); + } + /** + * Computes the transform flags for a node, given the transform flags of its subtree + * + * @param node The node to analyze + * @param subtreeFlags Transform flags computed for this node's subtree + */ + function computeTransformFlagsForNode(node, subtreeFlags) { + var kind = node.kind; + switch (kind) { + case 191 /* CallExpression */: + return computeCallExpression(node, subtreeFlags); + case 192 /* NewExpression */: + return computeNewExpression(node, subtreeFlags); + case 244 /* ModuleDeclaration */: + return computeModuleDeclaration(node, subtreeFlags); + case 195 /* ParenthesizedExpression */: + return computeParenthesizedExpression(node, subtreeFlags); + case 204 /* BinaryExpression */: + return computeBinaryExpression(node, subtreeFlags); + case 221 /* ExpressionStatement */: + return computeExpressionStatement(node, subtreeFlags); + case 151 /* Parameter */: + return computeParameter(node, subtreeFlags); + case 197 /* ArrowFunction */: + return computeArrowFunction(node, subtreeFlags); + case 196 /* FunctionExpression */: + return computeFunctionExpression(node, subtreeFlags); + case 239 /* FunctionDeclaration */: + return computeFunctionDeclaration(node, subtreeFlags); + case 237 /* VariableDeclaration */: + return computeVariableDeclaration(node, subtreeFlags); + case 238 /* VariableDeclarationList */: + return computeVariableDeclarationList(node, subtreeFlags); + case 219 /* VariableStatement */: + return computeVariableStatement(node, subtreeFlags); + case 233 /* LabeledStatement */: + return computeLabeledStatement(node, subtreeFlags); + case 240 /* ClassDeclaration */: + return computeClassDeclaration(node, subtreeFlags); + case 209 /* ClassExpression */: + return computeClassExpression(node, subtreeFlags); + case 273 /* HeritageClause */: + return computeHeritageClause(node, subtreeFlags); + case 274 /* CatchClause */: + return computeCatchClause(node, subtreeFlags); + case 211 /* ExpressionWithTypeArguments */: + return computeExpressionWithTypeArguments(node, subtreeFlags); + case 157 /* Constructor */: + return computeConstructor(node, subtreeFlags); + case 154 /* PropertyDeclaration */: + return computePropertyDeclaration(node, subtreeFlags); + case 156 /* MethodDeclaration */: + return computeMethod(node, subtreeFlags); + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + return computeAccessor(node, subtreeFlags); + case 248 /* ImportEqualsDeclaration */: + return computeImportEquals(node, subtreeFlags); + case 189 /* PropertyAccessExpression */: + return computePropertyAccess(node, subtreeFlags); + case 190 /* ElementAccessExpression */: + return computeElementAccess(node, subtreeFlags); + default: + return computeOther(node, kind, subtreeFlags); + } + } + ts.computeTransformFlagsForNode = computeTransformFlagsForNode; + function computeCallExpression(node, subtreeFlags) { + var transformFlags = subtreeFlags; + var expression = node.expression; + if (node.typeArguments) { + transformFlags |= 3 /* AssertTypeScript */; + } + if (subtreeFlags & 131072 /* ContainsRestOrSpread */ + || (expression.transformFlags & (33554432 /* Super */ | 67108864 /* ContainsSuper */))) { + // If the this node contains a SpreadExpression, or is a super call, then it is an ES6 + // node. + transformFlags |= 192 /* AssertES2015 */; + // super property or element accesses could be inside lambdas, etc, and need a captured `this`, + // while super keyword for super calls (indicated by TransformFlags.Super) does not (since it can only be top-level in a constructor) + if (expression.transformFlags & 67108864 /* ContainsSuper */) { + transformFlags |= 8192 /* ContainsLexicalThis */; + } + } + if (expression.kind === 92 /* ImportKeyword */) { + transformFlags |= 16777216 /* ContainsDynamicImport */; + // A dynamic 'import()' call that contains a lexical 'this' will + // require a captured 'this' when emitting down-level. + if (subtreeFlags & 8192 /* ContainsLexicalThis */) { + transformFlags |= 16384 /* ContainsCapturedLexicalThis */; + } + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~637666625 /* ArrayLiteralOrCallOrNewExcludes */; + } + function computeNewExpression(node, subtreeFlags) { + var transformFlags = subtreeFlags; + if (node.typeArguments) { + transformFlags |= 3 /* AssertTypeScript */; + } + if (subtreeFlags & 131072 /* ContainsRestOrSpread */) { + // If the this node contains a SpreadElementExpression then it is an ES6 + // node. + transformFlags |= 192 /* AssertES2015 */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~637666625 /* ArrayLiteralOrCallOrNewExcludes */; + } + function computeBinaryExpression(node, subtreeFlags) { + var transformFlags = subtreeFlags; + var operatorTokenKind = node.operatorToken.kind; + var leftKind = node.left.kind; + if (operatorTokenKind === 59 /* EqualsToken */ && leftKind === 188 /* ObjectLiteralExpression */) { + // Destructuring object assignments with are ES2015 syntax + // and possibly ESNext if they contain rest + transformFlags |= 8 /* AssertESNext */ | 192 /* AssertES2015 */ | 3072 /* AssertDestructuringAssignment */; + } + else if (operatorTokenKind === 59 /* EqualsToken */ && leftKind === 187 /* ArrayLiteralExpression */) { + // Destructuring assignments are ES2015 syntax. + transformFlags |= 192 /* AssertES2015 */ | 3072 /* AssertDestructuringAssignment */; + } + else if (operatorTokenKind === 41 /* AsteriskAsteriskToken */ + || operatorTokenKind === 63 /* AsteriskAsteriskEqualsToken */) { + // Exponentiation is ES2016 syntax. + transformFlags |= 32 /* AssertES2016 */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~637535553 /* NodeExcludes */; + } + function computeParameter(node, subtreeFlags) { + var transformFlags = subtreeFlags; + var name = node.name; + var initializer = node.initializer; + var dotDotDotToken = node.dotDotDotToken; + // The '?' token, type annotations, decorators, and 'this' parameters are TypeSCript + // syntax. + if (node.questionToken + || node.type + || (subtreeFlags & 4096 /* ContainsTypeScriptClassSyntax */ && ts.some(node.decorators)) + || ts.isThisIdentifier(name)) { + transformFlags |= 3 /* AssertTypeScript */; + } + // If a parameter has an accessibility modifier, then it is TypeScript syntax. + if (ts.hasModifier(node, 92 /* ParameterPropertyModifier */)) { + transformFlags |= 3 /* AssertTypeScript */ | 4096 /* ContainsTypeScriptClassSyntax */; + } + // parameters with object rest destructuring are ES Next syntax + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { + transformFlags |= 8 /* AssertESNext */; + } + // If a parameter has an initializer, a binding pattern or a dotDotDot token, then + // it is ES6 syntax and its container must emit default value assignments or parameter destructuring downlevel. + if (subtreeFlags & 2097152 /* ContainsBindingPattern */ || initializer || dotDotDotToken) { + transformFlags |= 192 /* AssertES2015 */ | 65536 /* ContainsDefaultValueAssignments */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~637535553 /* ParameterExcludes */; + } + function computeParenthesizedExpression(node, subtreeFlags) { + var transformFlags = subtreeFlags; + var expression = node.expression; + var expressionKind = expression.kind; + var expressionTransformFlags = expression.transformFlags; + // If the node is synthesized, it means the emitter put the parentheses there, + // not the user. If we didn't want them, the emitter would not have put them + // there. + if (expressionKind === 212 /* AsExpression */ + || expressionKind === 194 /* TypeAssertionExpression */) { + transformFlags |= 3 /* AssertTypeScript */; + } + // If the expression of a ParenthesizedExpression is a destructuring assignment, + // then the ParenthesizedExpression is a destructuring assignment. + if (expressionTransformFlags & 1024 /* DestructuringAssignment */) { + transformFlags |= 1024 /* DestructuringAssignment */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~536872257 /* OuterExpressionExcludes */; + } + function computeClassDeclaration(node, subtreeFlags) { + var transformFlags; + if (ts.hasModifier(node, 2 /* Ambient */)) { + // An ambient declaration is TypeScript syntax. + transformFlags = 3 /* AssertTypeScript */; + } + else { + // A ClassDeclaration is ES6 syntax. + transformFlags = subtreeFlags | 192 /* AssertES2015 */; + // A class with a parameter property assignment, property initializer, computed property name, or decorator is + // TypeScript syntax. + // An exported declaration may be TypeScript syntax, but is handled by the visitor + // for a namespace declaration. + if ((subtreeFlags & 4096 /* ContainsTypeScriptClassSyntax */) + || node.typeParameters) { + transformFlags |= 3 /* AssertTypeScript */; + } + if (subtreeFlags & 32768 /* ContainsLexicalThisInComputedPropertyName */) { + // A computed property name containing `this` might need to be rewritten, + // so propagate the ContainsLexicalThis flag upward. + transformFlags |= 8192 /* ContainsLexicalThis */; + } + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~638121281 /* ClassExcludes */; + } + function computeClassExpression(node, subtreeFlags) { + // A ClassExpression is ES6 syntax. + var transformFlags = subtreeFlags | 192 /* AssertES2015 */; + // A class with a parameter property assignment, property initializer, or decorator is + // TypeScript syntax. + if (subtreeFlags & 4096 /* ContainsTypeScriptClassSyntax */ + || node.typeParameters) { + transformFlags |= 3 /* AssertTypeScript */; + } + if (subtreeFlags & 32768 /* ContainsLexicalThisInComputedPropertyName */) { + // A computed property name containing `this` might need to be rewritten, + // so propagate the ContainsLexicalThis flag upward. + transformFlags |= 8192 /* ContainsLexicalThis */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~638121281 /* ClassExcludes */; + } + function computeHeritageClause(node, subtreeFlags) { + var transformFlags = subtreeFlags; + switch (node.token) { + case 86 /* ExtendsKeyword */: + // An `extends` HeritageClause is ES6 syntax. + transformFlags |= 192 /* AssertES2015 */; + break; + case 109 /* ImplementsKeyword */: + // An `implements` HeritageClause is TypeScript syntax. + transformFlags |= 3 /* AssertTypeScript */; + break; + default: + ts.Debug.fail("Unexpected token for heritage clause"); + break; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~637535553 /* NodeExcludes */; + } + function computeCatchClause(node, subtreeFlags) { + var transformFlags = subtreeFlags; + if (!node.variableDeclaration) { + transformFlags |= 8 /* AssertESNext */; + } + else if (ts.isBindingPattern(node.variableDeclaration.name)) { + transformFlags |= 192 /* AssertES2015 */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~637797697 /* CatchClauseExcludes */; + } + function computeExpressionWithTypeArguments(node, subtreeFlags) { + // An ExpressionWithTypeArguments is ES6 syntax, as it is used in the + // extends clause of a class. + var transformFlags = subtreeFlags | 192 /* AssertES2015 */; + // If an ExpressionWithTypeArguments contains type arguments, then it + // is TypeScript syntax. + if (node.typeArguments) { + transformFlags |= 3 /* AssertTypeScript */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~637535553 /* NodeExcludes */; + } + function computeConstructor(node, subtreeFlags) { + var transformFlags = subtreeFlags; + // TypeScript-specific modifiers and overloads are TypeScript syntax + if (ts.hasModifier(node, 2270 /* TypeScriptModifier */) + || !node.body) { + transformFlags |= 3 /* AssertTypeScript */; + } + // function declarations with object rest destructuring are ES Next syntax + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { + transformFlags |= 8 /* AssertESNext */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~653616449 /* ConstructorExcludes */; + } + function computeMethod(node, subtreeFlags) { + // A MethodDeclaration is ES6 syntax. + var transformFlags = subtreeFlags | 192 /* AssertES2015 */; + // Decorators, TypeScript-specific modifiers, type parameters, type annotations, and + // overloads are TypeScript syntax. + if (node.decorators + || ts.hasModifier(node, 2270 /* TypeScriptModifier */) + || node.typeParameters + || node.type + || (node.name && ts.isComputedPropertyName(node.name)) // While computed method names aren't typescript, the TS transform must visit them to emit property declarations correctly + || !node.body) { + transformFlags |= 3 /* AssertTypeScript */; + } + // function declarations with object rest destructuring are ES Next syntax + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { + transformFlags |= 8 /* AssertESNext */; + } + // An async method declaration is ES2017 syntax. + if (ts.hasModifier(node, 256 /* Async */)) { + transformFlags |= node.asteriskToken ? 8 /* AssertESNext */ : 16 /* AssertES2017 */; + } + if (node.asteriskToken) { + transformFlags |= 768 /* AssertGenerator */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~653616449 /* MethodOrAccessorExcludes */; + } + function computeAccessor(node, subtreeFlags) { + var transformFlags = subtreeFlags; + // Decorators, TypeScript-specific modifiers, type annotations, and overloads are + // TypeScript syntax. + if (node.decorators + || ts.hasModifier(node, 2270 /* TypeScriptModifier */) + || node.type + || (node.name && ts.isComputedPropertyName(node.name)) // While computed accessor names aren't typescript, the TS transform must visit them to emit property declarations correctly + || !node.body) { + transformFlags |= 3 /* AssertTypeScript */; + } + // function declarations with object rest destructuring are ES Next syntax + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { + transformFlags |= 8 /* AssertESNext */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~653616449 /* MethodOrAccessorExcludes */; + } + function computePropertyDeclaration(node, subtreeFlags) { + // A PropertyDeclaration is TypeScript syntax. + var transformFlags = subtreeFlags | 3 /* AssertTypeScript */; + // If the PropertyDeclaration has an initializer or a computed name, we need to inform its ancestor + // so that it handle the transformation. + if (node.initializer || ts.isComputedPropertyName(node.name)) { + transformFlags |= 4096 /* ContainsTypeScriptClassSyntax */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~637535553 /* NodeExcludes */; + } + function computeFunctionDeclaration(node, subtreeFlags) { + var transformFlags; + var modifierFlags = ts.getModifierFlags(node); + var body = node.body; + if (!body || (modifierFlags & 2 /* Ambient */)) { + // An ambient declaration is TypeScript syntax. + // A FunctionDeclaration without a body is an overload and is TypeScript syntax. + transformFlags = 3 /* AssertTypeScript */; + } + else { + transformFlags = subtreeFlags | 8388608 /* ContainsHoistedDeclarationOrCompletion */; + // TypeScript-specific modifiers, type parameters, and type annotations are TypeScript + // syntax. + if (modifierFlags & 2270 /* TypeScriptModifier */ + || node.typeParameters + || node.type) { + transformFlags |= 3 /* AssertTypeScript */; + } + // An async function declaration is ES2017 syntax. + if (modifierFlags & 256 /* Async */) { + transformFlags |= node.asteriskToken ? 8 /* AssertESNext */ : 16 /* AssertES2017 */; + } + // function declarations with object rest destructuring are ES Next syntax + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { + transformFlags |= 8 /* AssertESNext */; + } + // If a FunctionDeclaration's subtree has marked the container as needing to capture the + // lexical this, or the function contains parameters with initializers, then this node is + // ES6 syntax. + if (subtreeFlags & 81920 /* ES2015FunctionSyntaxMask */) { + transformFlags |= 192 /* AssertES2015 */; + } + // If a FunctionDeclaration is generator function and is the body of a + // transformed async function, then this node can be transformed to a + // down-level generator. + // Currently we do not support transforming any other generator fucntions + // down level. + if (node.asteriskToken) { + transformFlags |= 768 /* AssertGenerator */; + } + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~653620545 /* FunctionExcludes */; + } + function computeFunctionExpression(node, subtreeFlags) { + var transformFlags = subtreeFlags; + // TypeScript-specific modifiers, type parameters, and type annotations are TypeScript + // syntax. + if (ts.hasModifier(node, 2270 /* TypeScriptModifier */) + || node.typeParameters + || node.type) { + transformFlags |= 3 /* AssertTypeScript */; + } + // An async function expression is ES2017 syntax. + if (ts.hasModifier(node, 256 /* Async */)) { + transformFlags |= node.asteriskToken ? 8 /* AssertESNext */ : 16 /* AssertES2017 */; + } + // function expressions with object rest destructuring are ES Next syntax + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { + transformFlags |= 8 /* AssertESNext */; + } + // If a FunctionExpression's subtree has marked the container as needing to capture the + // lexical this, or the function contains parameters with initializers, then this node is + // ES6 syntax. + if (subtreeFlags & 81920 /* ES2015FunctionSyntaxMask */) { + transformFlags |= 192 /* AssertES2015 */; + } + // If a FunctionExpression is generator function and is the body of a + // transformed async function, then this node can be transformed to a + // down-level generator. + if (node.asteriskToken) { + transformFlags |= 768 /* AssertGenerator */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~653620545 /* FunctionExcludes */; + } + function computeArrowFunction(node, subtreeFlags) { + // An ArrowFunction is ES6 syntax, and excludes markers that should not escape the scope of an ArrowFunction. + var transformFlags = subtreeFlags | 192 /* AssertES2015 */; + // TypeScript-specific modifiers, type parameters, and type annotations are TypeScript + // syntax. + if (ts.hasModifier(node, 2270 /* TypeScriptModifier */) + || node.typeParameters + || node.type) { + transformFlags |= 3 /* AssertTypeScript */; + } + // An async arrow function is ES2017 syntax. + if (ts.hasModifier(node, 256 /* Async */)) { + transformFlags |= 16 /* AssertES2017 */; + } + // arrow functions with object rest destructuring are ES Next syntax + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { + transformFlags |= 8 /* AssertESNext */; + } + // If an ArrowFunction contains a lexical this, its container must capture the lexical this. + if (subtreeFlags & 8192 /* ContainsLexicalThis */) { + transformFlags |= 16384 /* ContainsCapturedLexicalThis */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~653604161 /* ArrowFunctionExcludes */; + } + function computePropertyAccess(node, subtreeFlags) { + var transformFlags = subtreeFlags; + // If a PropertyAccessExpression starts with a super keyword, then it is + // ES6 syntax, and requires a lexical `this` binding. + if (transformFlags & 33554432 /* Super */) { + transformFlags ^= 33554432 /* Super */; + // super inside of an async function requires hoisting the super access (ES2017). + // same for super inside of an async generator, which is ESNext. + transformFlags |= 67108864 /* ContainsSuper */ | 16 /* ContainsES2017 */ | 8 /* ContainsESNext */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~570426689 /* PropertyAccessExcludes */; + } + function computeElementAccess(node, subtreeFlags) { + var transformFlags = subtreeFlags; + var expression = node.expression; + var expressionFlags = expression.transformFlags; // We do not want to aggregate flags from the argument expression for super/this capturing + // If an ElementAccessExpression starts with a super keyword, then it is + // ES6 syntax, and requires a lexical `this` binding. + if (expressionFlags & 33554432 /* Super */) { + transformFlags &= ~33554432 /* Super */; + // super inside of an async function requires hoisting the super access (ES2017). + // same for super inside of an async generator, which is ESNext. + transformFlags |= 67108864 /* ContainsSuper */ | 16 /* ContainsES2017 */ | 8 /* ContainsESNext */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~570426689 /* PropertyAccessExcludes */; + } + function computeVariableDeclaration(node, subtreeFlags) { + var transformFlags = subtreeFlags; + transformFlags |= 192 /* AssertES2015 */ | 2097152 /* ContainsBindingPattern */; + // A VariableDeclaration containing ObjectRest is ESNext syntax + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { + transformFlags |= 8 /* AssertESNext */; + } + // Type annotations are TypeScript syntax. + if (node.type) { + transformFlags |= 3 /* AssertTypeScript */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~637535553 /* NodeExcludes */; + } + function computeVariableStatement(node, subtreeFlags) { + var transformFlags; + var declarationListTransformFlags = node.declarationList.transformFlags; + // An ambient declaration is TypeScript syntax. + if (ts.hasModifier(node, 2 /* Ambient */)) { + transformFlags = 3 /* AssertTypeScript */; + } + else { + transformFlags = subtreeFlags; + if (declarationListTransformFlags & 2097152 /* ContainsBindingPattern */) { + transformFlags |= 192 /* AssertES2015 */; + } + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~637535553 /* NodeExcludes */; + } + function computeLabeledStatement(node, subtreeFlags) { + var transformFlags = subtreeFlags; + // A labeled statement containing a block scoped binding *may* need to be transformed from ES6. + if (subtreeFlags & 1048576 /* ContainsBlockScopedBinding */ + && ts.isIterationStatement(node, /*lookInLabeledStatements*/ true)) { + transformFlags |= 192 /* AssertES2015 */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~637535553 /* NodeExcludes */; + } + function computeImportEquals(node, subtreeFlags) { + var transformFlags = subtreeFlags; + // An ImportEqualsDeclaration with a namespace reference is TypeScript. + if (!ts.isExternalModuleImportEqualsDeclaration(node)) { + transformFlags |= 3 /* AssertTypeScript */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~637535553 /* NodeExcludes */; + } + function computeExpressionStatement(node, subtreeFlags) { + var transformFlags = subtreeFlags; + // If the expression of an expression statement is a destructuring assignment, + // then we treat the statement as ES6 so that we can indicate that we do not + // need to hold on to the right-hand side. + if (node.expression.transformFlags & 1024 /* DestructuringAssignment */) { + transformFlags |= 192 /* AssertES2015 */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~637535553 /* NodeExcludes */; + } + function computeModuleDeclaration(node, subtreeFlags) { + var transformFlags = 3 /* AssertTypeScript */; + var modifierFlags = ts.getModifierFlags(node); + if ((modifierFlags & 2 /* Ambient */) === 0) { + transformFlags |= subtreeFlags; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~647001409 /* ModuleExcludes */; + } + function computeVariableDeclarationList(node, subtreeFlags) { + var transformFlags = subtreeFlags | 8388608 /* ContainsHoistedDeclarationOrCompletion */; + if (subtreeFlags & 2097152 /* ContainsBindingPattern */) { + transformFlags |= 192 /* AssertES2015 */; + } + // If a VariableDeclarationList is `let` or `const`, then it is ES6 syntax. + if (node.flags & 3 /* BlockScoped */) { + transformFlags |= 192 /* AssertES2015 */ | 1048576 /* ContainsBlockScopedBinding */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~639894849 /* VariableDeclarationListExcludes */; + } + function computeOther(node, kind, subtreeFlags) { + // Mark transformations needed for each node + var transformFlags = subtreeFlags; + var excludeFlags = 637535553 /* NodeExcludes */; + switch (kind) { + case 121 /* AsyncKeyword */: + case 201 /* AwaitExpression */: + // async/await is ES2017 syntax, but may be ESNext syntax (for async generators) + transformFlags |= 8 /* AssertESNext */ | 16 /* AssertES2017 */; + break; + case 194 /* TypeAssertionExpression */: + case 212 /* AsExpression */: + case 308 /* PartiallyEmittedExpression */: + // These nodes are TypeScript syntax. + transformFlags |= 3 /* AssertTypeScript */; + excludeFlags = 536872257 /* OuterExpressionExcludes */; + break; + case 115 /* PublicKeyword */: + case 113 /* PrivateKeyword */: + case 114 /* ProtectedKeyword */: + case 118 /* AbstractKeyword */: + case 125 /* DeclareKeyword */: + case 77 /* ConstKeyword */: + case 243 /* EnumDeclaration */: + case 278 /* EnumMember */: + case 213 /* NonNullExpression */: + case 133 /* ReadonlyKeyword */: + // These nodes are TypeScript syntax. + transformFlags |= 3 /* AssertTypeScript */; + break; + case 260 /* JsxElement */: + case 261 /* JsxSelfClosingElement */: + case 262 /* JsxOpeningElement */: + case 11 /* JsxText */: + case 263 /* JsxClosingElement */: + case 264 /* JsxFragment */: + case 265 /* JsxOpeningFragment */: + case 266 /* JsxClosingFragment */: + case 267 /* JsxAttribute */: + case 268 /* JsxAttributes */: + case 269 /* JsxSpreadAttribute */: + case 270 /* JsxExpression */: + // These nodes are Jsx syntax. + transformFlags |= 4 /* AssertJsx */; + break; + case 14 /* NoSubstitutionTemplateLiteral */: + case 15 /* TemplateHead */: + case 16 /* TemplateMiddle */: + case 17 /* TemplateTail */: + case 206 /* TemplateExpression */: + case 193 /* TaggedTemplateExpression */: + case 276 /* ShorthandPropertyAssignment */: + case 116 /* StaticKeyword */: + case 214 /* MetaProperty */: + // These nodes are ES6 syntax. + transformFlags |= 192 /* AssertES2015 */; + break; + case 10 /* StringLiteral */: + if (node.hasExtendedUnicodeEscape) { + transformFlags |= 192 /* AssertES2015 */; + } + break; + case 8 /* NumericLiteral */: + if (node.numericLiteralFlags & 384 /* BinaryOrOctalSpecifier */) { + transformFlags |= 192 /* AssertES2015 */; + } + break; + case 9 /* BigIntLiteral */: + transformFlags |= 8 /* AssertESNext */; + break; + case 227 /* ForOfStatement */: + // This node is either ES2015 syntax or ES2017 syntax (if it is a for-await-of). + if (node.awaitModifier) { + transformFlags |= 8 /* AssertESNext */; + } + transformFlags |= 192 /* AssertES2015 */; + break; + case 207 /* YieldExpression */: + // This node is either ES2015 syntax (in a generator) or ES2017 syntax (in an async + // generator). + transformFlags |= 8 /* AssertESNext */ | 192 /* AssertES2015 */ | 4194304 /* ContainsYield */; + break; + case 120 /* AnyKeyword */: + case 135 /* NumberKeyword */: + case 146 /* BigIntKeyword */: + case 132 /* NeverKeyword */: + case 136 /* ObjectKeyword */: + case 138 /* StringKeyword */: + case 123 /* BooleanKeyword */: + case 139 /* SymbolKeyword */: + case 106 /* VoidKeyword */: + case 150 /* TypeParameter */: + case 153 /* PropertySignature */: + case 155 /* MethodSignature */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 162 /* IndexSignature */: + case 163 /* TypePredicate */: + case 164 /* TypeReference */: + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + case 167 /* TypeQuery */: + case 168 /* TypeLiteral */: + case 169 /* ArrayType */: + case 170 /* TupleType */: + case 171 /* OptionalType */: + case 172 /* RestType */: + case 173 /* UnionType */: + case 174 /* IntersectionType */: + case 175 /* ConditionalType */: + case 176 /* InferType */: + case 177 /* ParenthesizedType */: + case 241 /* InterfaceDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 178 /* ThisType */: + case 179 /* TypeOperator */: + case 180 /* IndexedAccessType */: + case 181 /* MappedType */: + case 182 /* LiteralType */: + case 247 /* NamespaceExportDeclaration */: + // Types and signatures are TypeScript syntax, and exclude all other facts. + transformFlags = 3 /* AssertTypeScript */; + excludeFlags = -3 /* TypeExcludes */; + break; + case 149 /* ComputedPropertyName */: + // Even though computed property names are ES6, we don't treat them as such. + // This is so that they can flow through PropertyName transforms unaffected. + // Instead, we mark the container as ES6, so that it can properly handle the transform. + transformFlags |= 524288 /* ContainsComputedPropertyName */; + if (subtreeFlags & 8192 /* ContainsLexicalThis */) { + // A computed method name like `[this.getName()](x: string) { ... }` needs to + // distinguish itself from the normal case of a method body containing `this`: + // `this` inside a method doesn't need to be rewritten (the method provides `this`), + // whereas `this` inside a computed name *might* need to be rewritten if the class/object + // is inside an arrow function: + // `_this = this; () => class K { [_this.getName()]() { ... } }` + // To make this distinction, use ContainsLexicalThisInComputedPropertyName + // instead of ContainsLexicalThis for computed property names + transformFlags |= 32768 /* ContainsLexicalThisInComputedPropertyName */; + } + break; + case 208 /* SpreadElement */: + transformFlags |= 192 /* AssertES2015 */ | 131072 /* ContainsRestOrSpread */; + break; + case 277 /* SpreadAssignment */: + transformFlags |= 8 /* AssertESNext */ | 262144 /* ContainsObjectRestOrSpread */; + break; + case 98 /* SuperKeyword */: + // This node is ES6 syntax. + transformFlags |= 192 /* AssertES2015 */ | 33554432 /* Super */; + excludeFlags = 536872257 /* OuterExpressionExcludes */; // must be set to persist `Super` + break; + case 100 /* ThisKeyword */: + // Mark this node and its ancestors as containing a lexical `this` keyword. + transformFlags |= 8192 /* ContainsLexicalThis */; + break; + case 184 /* ObjectBindingPattern */: + transformFlags |= 192 /* AssertES2015 */ | 2097152 /* ContainsBindingPattern */; + if (subtreeFlags & 131072 /* ContainsRestOrSpread */) { + transformFlags |= 8 /* AssertESNext */ | 262144 /* ContainsObjectRestOrSpread */; + } + excludeFlags = 637666625 /* BindingPatternExcludes */; + break; + case 185 /* ArrayBindingPattern */: + transformFlags |= 192 /* AssertES2015 */ | 2097152 /* ContainsBindingPattern */; + excludeFlags = 637666625 /* BindingPatternExcludes */; + break; + case 186 /* BindingElement */: + transformFlags |= 192 /* AssertES2015 */; + if (node.dotDotDotToken) { + transformFlags |= 131072 /* ContainsRestOrSpread */; + } + break; + case 152 /* Decorator */: + // This node is TypeScript syntax, and marks its container as also being TypeScript syntax. + transformFlags |= 3 /* AssertTypeScript */ | 4096 /* ContainsTypeScriptClassSyntax */; + break; + case 188 /* ObjectLiteralExpression */: + excludeFlags = 638358849 /* ObjectLiteralExcludes */; + if (subtreeFlags & 524288 /* ContainsComputedPropertyName */) { + // If an ObjectLiteralExpression contains a ComputedPropertyName, then it + // is an ES6 node. + transformFlags |= 192 /* AssertES2015 */; + } + if (subtreeFlags & 32768 /* ContainsLexicalThisInComputedPropertyName */) { + // A computed property name containing `this` might need to be rewritten, + // so propagate the ContainsLexicalThis flag upward. + transformFlags |= 8192 /* ContainsLexicalThis */; + } + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { + // If an ObjectLiteralExpression contains a spread element, then it + // is an ES next node. + transformFlags |= 8 /* AssertESNext */; + } + break; + case 187 /* ArrayLiteralExpression */: + case 192 /* NewExpression */: + excludeFlags = 637666625 /* ArrayLiteralOrCallOrNewExcludes */; + if (subtreeFlags & 131072 /* ContainsRestOrSpread */) { + // If the this node contains a SpreadExpression, then it is an ES6 + // node. + transformFlags |= 192 /* AssertES2015 */; + } + break; + case 223 /* DoStatement */: + case 224 /* WhileStatement */: + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + // A loop containing a block scoped binding *may* need to be transformed from ES6. + if (subtreeFlags & 1048576 /* ContainsBlockScopedBinding */) { + transformFlags |= 192 /* AssertES2015 */; + } + break; + case 279 /* SourceFile */: + if (subtreeFlags & 16384 /* ContainsCapturedLexicalThis */) { + transformFlags |= 192 /* AssertES2015 */; + } + break; + case 230 /* ReturnStatement */: + // Return statements may require an `await` in ESNext. + transformFlags |= 8388608 /* ContainsHoistedDeclarationOrCompletion */ | 8 /* AssertESNext */; + break; + case 228 /* ContinueStatement */: + case 229 /* BreakStatement */: + transformFlags |= 8388608 /* ContainsHoistedDeclarationOrCompletion */; + break; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~excludeFlags; + } + /** + * Gets the transform flags to exclude when unioning the transform flags of a subtree. + * + * NOTE: This needs to be kept up-to-date with the exclusions used in `computeTransformFlagsForNode`. + * For performance reasons, `computeTransformFlagsForNode` uses local constant values rather + * than calling this function. + */ + function getTransformFlagsSubtreeExclusions(kind) { + if (kind >= 163 /* FirstTypeNode */ && kind <= 183 /* LastTypeNode */) { + return -3 /* TypeExcludes */; + } + switch (kind) { + case 191 /* CallExpression */: + case 192 /* NewExpression */: + case 187 /* ArrayLiteralExpression */: + return 637666625 /* ArrayLiteralOrCallOrNewExcludes */; + case 244 /* ModuleDeclaration */: + return 647001409 /* ModuleExcludes */; + case 151 /* Parameter */: + return 637535553 /* ParameterExcludes */; + case 197 /* ArrowFunction */: + return 653604161 /* ArrowFunctionExcludes */; + case 196 /* FunctionExpression */: + case 239 /* FunctionDeclaration */: + return 653620545 /* FunctionExcludes */; + case 238 /* VariableDeclarationList */: + return 639894849 /* VariableDeclarationListExcludes */; + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + return 638121281 /* ClassExcludes */; + case 157 /* Constructor */: + return 653616449 /* ConstructorExcludes */; + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + return 653616449 /* MethodOrAccessorExcludes */; + case 120 /* AnyKeyword */: + case 135 /* NumberKeyword */: + case 146 /* BigIntKeyword */: + case 132 /* NeverKeyword */: + case 138 /* StringKeyword */: + case 136 /* ObjectKeyword */: + case 123 /* BooleanKeyword */: + case 139 /* SymbolKeyword */: + case 106 /* VoidKeyword */: + case 150 /* TypeParameter */: + case 153 /* PropertySignature */: + case 155 /* MethodSignature */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 162 /* IndexSignature */: + case 241 /* InterfaceDeclaration */: + case 242 /* TypeAliasDeclaration */: + return -3 /* TypeExcludes */; + case 188 /* ObjectLiteralExpression */: + return 638358849 /* ObjectLiteralExcludes */; + case 274 /* CatchClause */: + return 637797697 /* CatchClauseExcludes */; + case 184 /* ObjectBindingPattern */: + case 185 /* ArrayBindingPattern */: + return 637666625 /* BindingPatternExcludes */; + case 194 /* TypeAssertionExpression */: + case 212 /* AsExpression */: + case 308 /* PartiallyEmittedExpression */: + case 195 /* ParenthesizedExpression */: + case 98 /* SuperKeyword */: + return 536872257 /* OuterExpressionExcludes */; + case 189 /* PropertyAccessExpression */: + case 190 /* ElementAccessExpression */: + return 570426689 /* PropertyAccessExcludes */; + default: + return 637535553 /* NodeExcludes */; + } + } + ts.getTransformFlagsSubtreeExclusions = getTransformFlagsSubtreeExclusions; + /** + * "Binds" JSDoc nodes in TypeScript code. + * Since we will never create symbols for JSDoc, we just set parent pointers instead. + */ + function setParentPointers(parent, child) { + child.parent = parent; + ts.forEachChild(child, function (grandchild) { return setParentPointers(child, grandchild); }); + } +})(ts || (ts = {})); +/** @internal */ +var ts; +(function (ts) { + function createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintOfTypeParameter, getFirstIdentifier) { + return getSymbolWalker; + function getSymbolWalker(accept) { + if (accept === void 0) { accept = function () { return true; }; } + var visitedTypes = []; // Sparse array from id to type + var visitedSymbols = []; // Sparse array from id to symbol + return { + walkType: function (type) { + try { + visitType(type); + return { visitedTypes: ts.getOwnValues(visitedTypes), visitedSymbols: ts.getOwnValues(visitedSymbols) }; + } + finally { + ts.clear(visitedTypes); + ts.clear(visitedSymbols); + } + }, + walkSymbol: function (symbol) { + try { + visitSymbol(symbol); + return { visitedTypes: ts.getOwnValues(visitedTypes), visitedSymbols: ts.getOwnValues(visitedSymbols) }; + } + finally { + ts.clear(visitedTypes); + ts.clear(visitedSymbols); + } + }, + }; + function visitType(type) { + if (!type) { + return; + } + if (visitedTypes[type.id]) { + return; + } + visitedTypes[type.id] = type; + // Reuse visitSymbol to visit the type's symbol, + // but be sure to bail on recuring into the type if accept declines the symbol. + var shouldBail = visitSymbol(type.symbol); + if (shouldBail) + return; + // Visit the type's related types, if any + if (type.flags & 524288 /* Object */) { + var objectType = type; + var objectFlags = objectType.objectFlags; + if (objectFlags & 4 /* Reference */) { + visitTypeReference(type); + } + if (objectFlags & 32 /* Mapped */) { + visitMappedType(type); + } + if (objectFlags & (1 /* Class */ | 2 /* Interface */)) { + visitInterfaceType(type); + } + if (objectFlags & (8 /* Tuple */ | 16 /* Anonymous */)) { + visitObjectType(objectType); + } + } + if (type.flags & 262144 /* TypeParameter */) { + visitTypeParameter(type); + } + if (type.flags & 3145728 /* UnionOrIntersection */) { + visitUnionOrIntersectionType(type); + } + if (type.flags & 4194304 /* Index */) { + visitIndexType(type); + } + if (type.flags & 8388608 /* IndexedAccess */) { + visitIndexedAccessType(type); + } + } + function visitTypeReference(type) { + visitType(type.target); + ts.forEach(type.typeArguments, visitType); + } + function visitTypeParameter(type) { + visitType(getConstraintOfTypeParameter(type)); + } + function visitUnionOrIntersectionType(type) { + ts.forEach(type.types, visitType); + } + function visitIndexType(type) { + visitType(type.type); + } + function visitIndexedAccessType(type) { + visitType(type.objectType); + visitType(type.indexType); + visitType(type.constraint); + } + function visitMappedType(type) { + visitType(type.typeParameter); + visitType(type.constraintType); + visitType(type.templateType); + visitType(type.modifiersType); + } + function visitSignature(signature) { + var typePredicate = getTypePredicateOfSignature(signature); + if (typePredicate) { + visitType(typePredicate.type); + } + ts.forEach(signature.typeParameters, visitType); + for (var _i = 0, _a = signature.parameters; _i < _a.length; _i++) { + var parameter = _a[_i]; + visitSymbol(parameter); + } + visitType(getRestTypeOfSignature(signature)); + visitType(getReturnTypeOfSignature(signature)); + } + function visitInterfaceType(interfaceT) { + visitObjectType(interfaceT); + ts.forEach(interfaceT.typeParameters, visitType); + ts.forEach(getBaseTypes(interfaceT), visitType); + visitType(interfaceT.thisType); + } + function visitObjectType(type) { + var stringIndexType = getIndexTypeOfStructuredType(type, 0 /* String */); + visitType(stringIndexType); + var numberIndexType = getIndexTypeOfStructuredType(type, 1 /* Number */); + visitType(numberIndexType); + // The two checks above *should* have already resolved the type (if needed), so this should be cached + var resolved = resolveStructuredTypeMembers(type); + for (var _i = 0, _a = resolved.callSignatures; _i < _a.length; _i++) { + var signature = _a[_i]; + visitSignature(signature); + } + for (var _b = 0, _c = resolved.constructSignatures; _b < _c.length; _b++) { + var signature = _c[_b]; + visitSignature(signature); + } + for (var _d = 0, _e = resolved.properties; _d < _e.length; _d++) { + var p = _e[_d]; + visitSymbol(p); + } + } + function visitSymbol(symbol) { + if (!symbol) { + return false; + } + var symbolId = ts.getSymbolId(symbol); + if (visitedSymbols[symbolId]) { + return false; + } + visitedSymbols[symbolId] = symbol; + if (!accept(symbol)) { + return true; + } + var t = getTypeOfSymbol(symbol); + visitType(t); // Should handle members on classes and such + if (symbol.exports) { + symbol.exports.forEach(visitSymbol); + } + ts.forEach(symbol.declarations, function (d) { + // Type queries are too far resolved when we just visit the symbol's type + // (their type resolved directly to the member deeply referenced) + // So to get the intervening symbols, we need to check if there's a type + // query node on any of the symbol's declarations and get symbols there + if (d.type && d.type.kind === 167 /* TypeQuery */) { + var query = d.type; + var entity = getResolvedSymbol(getFirstIdentifier(query.exprName)); + visitSymbol(entity); + } + }); + return false; + } + } + } + ts.createGetSymbolWalker = createGetSymbolWalker; +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var ambientModuleSymbolRegex = /^".+"$/; + var nextSymbolId = 1; + var nextNodeId = 1; + var nextMergeId = 1; + var nextFlowId = 1; + function getNodeId(node) { + if (!node.id) { + node.id = nextNodeId; + nextNodeId++; + } + return node.id; + } + ts.getNodeId = getNodeId; + function getSymbolId(symbol) { + if (!symbol.id) { + symbol.id = nextSymbolId; + nextSymbolId++; + } + return symbol.id; + } + ts.getSymbolId = getSymbolId; + function isInstantiatedModule(node, preserveConstEnums) { + var moduleState = ts.getModuleInstanceState(node); + return moduleState === 1 /* Instantiated */ || + (preserveConstEnums && moduleState === 2 /* ConstEnumOnly */); + } + ts.isInstantiatedModule = isInstantiatedModule; + function createTypeChecker(host, produceDiagnostics) { + var getPackagesSet = ts.memoize(function () { + var set = ts.createMap(); + host.getSourceFiles().forEach(function (sf) { + if (!sf.resolvedModules) + return; + ts.forEachEntry(sf.resolvedModules, function (r) { + if (r && r.packageId) + set.set(r.packageId.name, true); + }); + }); + return set; + }); + // Cancellation that controls whether or not we can cancel in the middle of type checking. + // In general cancelling is *not* safe for the type checker. We might be in the middle of + // computing something, and we will leave our internals in an inconsistent state. Callers + // who set the cancellation token should catch if a cancellation exception occurs, and + // should throw away and create a new TypeChecker. + // + // Currently we only support setting the cancellation token when getting diagnostics. This + // is because diagnostics can be quite expensive, and we want to allow hosts to bail out if + // they no longer need the information (for example, if the user started editing again). + var cancellationToken; + var requestedExternalEmitHelpers; + var externalHelpersModule; + // tslint:disable variable-name + var Symbol = ts.objectAllocator.getSymbolConstructor(); + var Type = ts.objectAllocator.getTypeConstructor(); + var Signature = ts.objectAllocator.getSignatureConstructor(); + // tslint:enable variable-name + var typeCount = 0; + var symbolCount = 0; + var enumCount = 0; + var instantiationDepth = 0; + var constraintDepth = 0; + var emptySymbols = ts.createSymbolTable(); + var identityMapper = ts.identity; + var compilerOptions = host.getCompilerOptions(); + var languageVersion = ts.getEmitScriptTarget(compilerOptions); + var moduleKind = ts.getEmitModuleKind(compilerOptions); + var allowSyntheticDefaultImports = ts.getAllowSyntheticDefaultImports(compilerOptions); + var strictNullChecks = ts.getStrictOptionValue(compilerOptions, "strictNullChecks"); + var strictFunctionTypes = ts.getStrictOptionValue(compilerOptions, "strictFunctionTypes"); + var strictBindCallApply = ts.getStrictOptionValue(compilerOptions, "strictBindCallApply"); + var strictPropertyInitialization = ts.getStrictOptionValue(compilerOptions, "strictPropertyInitialization"); + var noImplicitAny = ts.getStrictOptionValue(compilerOptions, "noImplicitAny"); + var noImplicitThis = ts.getStrictOptionValue(compilerOptions, "noImplicitThis"); + var keyofStringsOnly = !!compilerOptions.keyofStringsOnly; + var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 32768 /* FreshLiteral */; + var emitResolver = createResolver(); + var nodeBuilder = createNodeBuilder(); + var undefinedSymbol = createSymbol(4 /* Property */, "undefined"); + undefinedSymbol.declarations = []; + var argumentsSymbol = createSymbol(4 /* Property */, "arguments"); + var requireSymbol = createSymbol(4 /* Property */, "require"); + /** This will be set during calls to `getResolvedSignature` where services determines an apparent number of arguments greater than what is actually provided. */ + var apparentArgumentCount; + // for public members that accept a Node or one of its subtypes, we must guard against + // synthetic nodes created during transformations by calling `getParseTreeNode`. + // for most of these, we perform the guard only on `checker` to avoid any possible + // extra cost of calling `getParseTreeNode` when calling these functions from inside the + // checker. + var checker = { + getNodeCount: function () { return ts.sum(host.getSourceFiles(), "nodeCount"); }, + getIdentifierCount: function () { return ts.sum(host.getSourceFiles(), "identifierCount"); }, + getSymbolCount: function () { return ts.sum(host.getSourceFiles(), "symbolCount") + symbolCount; }, + getTypeCount: function () { return typeCount; }, + isUndefinedSymbol: function (symbol) { return symbol === undefinedSymbol; }, + isArgumentsSymbol: function (symbol) { return symbol === argumentsSymbol; }, + isUnknownSymbol: function (symbol) { return symbol === unknownSymbol; }, + getMergedSymbol: getMergedSymbol, + getDiagnostics: getDiagnostics, + getGlobalDiagnostics: getGlobalDiagnostics, + getTypeOfSymbolAtLocation: function (symbol, location) { + location = ts.getParseTreeNode(location); + return location ? getTypeOfSymbolAtLocation(symbol, location) : errorType; + }, + getSymbolsOfParameterPropertyDeclaration: function (parameterIn, parameterName) { + var parameter = ts.getParseTreeNode(parameterIn, ts.isParameter); + if (parameter === undefined) + return ts.Debug.fail("Cannot get symbols of a synthetic parameter that cannot be resolved to a parse-tree node."); + return getSymbolsOfParameterPropertyDeclaration(parameter, ts.escapeLeadingUnderscores(parameterName)); + }, + getDeclaredTypeOfSymbol: getDeclaredTypeOfSymbol, + getPropertiesOfType: getPropertiesOfType, + getPropertyOfType: function (type, name) { return getPropertyOfType(type, ts.escapeLeadingUnderscores(name)); }, + getTypeOfPropertyOfType: function (type, name) { return getTypeOfPropertyOfType(type, ts.escapeLeadingUnderscores(name)); }, + getIndexInfoOfType: getIndexInfoOfType, + getSignaturesOfType: getSignaturesOfType, + getIndexTypeOfType: getIndexTypeOfType, + getBaseTypes: getBaseTypes, + getBaseTypeOfLiteralType: getBaseTypeOfLiteralType, + getWidenedType: getWidenedType, + getTypeFromTypeNode: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isTypeNode); + return node ? getTypeFromTypeNode(node) : errorType; + }, + getParameterType: getTypeAtPosition, + getPromisedTypeOfPromise: getPromisedTypeOfPromise, + getReturnTypeOfSignature: getReturnTypeOfSignature, + getNullableType: getNullableType, + getNonNullableType: getNonNullableType, + typeToTypeNode: nodeBuilder.typeToTypeNode, + indexInfoToIndexSignatureDeclaration: nodeBuilder.indexInfoToIndexSignatureDeclaration, + signatureToSignatureDeclaration: nodeBuilder.signatureToSignatureDeclaration, + symbolToEntityName: nodeBuilder.symbolToEntityName, + symbolToExpression: nodeBuilder.symbolToExpression, + symbolToTypeParameterDeclarations: nodeBuilder.symbolToTypeParameterDeclarations, + symbolToParameterDeclaration: nodeBuilder.symbolToParameterDeclaration, + typeParameterToDeclaration: nodeBuilder.typeParameterToDeclaration, + getSymbolsInScope: function (location, meaning) { + location = ts.getParseTreeNode(location); + return location ? getSymbolsInScope(location, meaning) : []; + }, + getSymbolAtLocation: function (node) { + node = ts.getParseTreeNode(node); + return node ? getSymbolAtLocation(node) : undefined; + }, + getShorthandAssignmentValueSymbol: function (node) { + node = ts.getParseTreeNode(node); + return node ? getShorthandAssignmentValueSymbol(node) : undefined; + }, + getExportSpecifierLocalTargetSymbol: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isExportSpecifier); + return node ? getExportSpecifierLocalTargetSymbol(node) : undefined; + }, + getExportSymbolOfSymbol: function (symbol) { + return getMergedSymbol(symbol.exportSymbol || symbol); + }, + getTypeAtLocation: function (node) { + node = ts.getParseTreeNode(node); + return node ? getTypeOfNode(node) : errorType; + }, + getPropertySymbolOfDestructuringAssignment: function (locationIn) { + var location = ts.getParseTreeNode(locationIn, ts.isIdentifier); + return location ? getPropertySymbolOfDestructuringAssignment(location) : undefined; + }, + signatureToString: function (signature, enclosingDeclaration, flags, kind) { + return signatureToString(signature, ts.getParseTreeNode(enclosingDeclaration), flags, kind); + }, + typeToString: function (type, enclosingDeclaration, flags) { + return typeToString(type, ts.getParseTreeNode(enclosingDeclaration), flags); + }, + symbolToString: function (symbol, enclosingDeclaration, meaning, flags) { + return symbolToString(symbol, ts.getParseTreeNode(enclosingDeclaration), meaning, flags); + }, + typePredicateToString: function (predicate, enclosingDeclaration, flags) { + return typePredicateToString(predicate, ts.getParseTreeNode(enclosingDeclaration), flags); + }, + writeSignature: function (signature, enclosingDeclaration, flags, kind, writer) { + return signatureToString(signature, ts.getParseTreeNode(enclosingDeclaration), flags, kind, writer); + }, + writeType: function (type, enclosingDeclaration, flags, writer) { + return typeToString(type, ts.getParseTreeNode(enclosingDeclaration), flags, writer); + }, + writeSymbol: function (symbol, enclosingDeclaration, meaning, flags, writer) { + return symbolToString(symbol, ts.getParseTreeNode(enclosingDeclaration), meaning, flags, writer); + }, + writeTypePredicate: function (predicate, enclosingDeclaration, flags, writer) { + return typePredicateToString(predicate, ts.getParseTreeNode(enclosingDeclaration), flags, writer); + }, + getAugmentedPropertiesOfType: getAugmentedPropertiesOfType, + getRootSymbols: getRootSymbols, + getContextualType: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isExpression); + return node ? getContextualType(node) : undefined; + }, + getContextualTypeForObjectLiteralElement: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isObjectLiteralElementLike); + return node ? getContextualTypeForObjectLiteralElement(node) : undefined; + }, + getContextualTypeForArgumentAtIndex: function (nodeIn, argIndex) { + var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression); + return node && getContextualTypeForArgumentAtIndex(node, argIndex); + }, + getContextualTypeForJsxAttribute: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isJsxAttributeLike); + return node && getContextualTypeForJsxAttribute(node); + }, + isContextSensitive: isContextSensitive, + getFullyQualifiedName: getFullyQualifiedName, + getResolvedSignature: function (node, candidatesOutArray, agumentCount) { + return getResolvedSignatureWorker(node, candidatesOutArray, agumentCount, /*isForSignatureHelp*/ false); + }, + getResolvedSignatureForSignatureHelp: function (node, candidatesOutArray, agumentCount) { + return getResolvedSignatureWorker(node, candidatesOutArray, agumentCount, /*isForSignatureHelp*/ true); + }, + getConstantValue: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, canHaveConstantValue); + return node ? getConstantValue(node) : undefined; + }, + isValidPropertyAccess: function (nodeIn, propertyName) { + var node = ts.getParseTreeNode(nodeIn, ts.isPropertyAccessOrQualifiedNameOrImportTypeNode); + return !!node && isValidPropertyAccess(node, ts.escapeLeadingUnderscores(propertyName)); + }, + isValidPropertyAccessForCompletions: function (nodeIn, type, property) { + var node = ts.getParseTreeNode(nodeIn, ts.isPropertyAccessExpression); + return !!node && isValidPropertyAccessForCompletions(node, type, property); + }, + getSignatureFromDeclaration: function (declarationIn) { + var declaration = ts.getParseTreeNode(declarationIn, ts.isFunctionLike); + return declaration ? getSignatureFromDeclaration(declaration) : undefined; + }, + isImplementationOfOverload: function (node) { + var parsed = ts.getParseTreeNode(node, ts.isFunctionLike); + return parsed ? isImplementationOfOverload(parsed) : undefined; + }, + getImmediateAliasedSymbol: getImmediateAliasedSymbol, + getAliasedSymbol: resolveAlias, + getEmitResolver: getEmitResolver, + getExportsOfModule: getExportsOfModuleAsArray, + getExportsAndPropertiesOfModule: getExportsAndPropertiesOfModule, + getSymbolWalker: ts.createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintOfTypeParameter, getFirstIdentifier), + getAmbientModules: getAmbientModules, + getJsxIntrinsicTagNamesAt: getJsxIntrinsicTagNamesAt, + isOptionalParameter: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isParameter); + return node ? isOptionalParameter(node) : false; + }, + tryGetMemberInModuleExports: function (name, symbol) { return tryGetMemberInModuleExports(ts.escapeLeadingUnderscores(name), symbol); }, + tryGetMemberInModuleExportsAndProperties: function (name, symbol) { return tryGetMemberInModuleExportsAndProperties(ts.escapeLeadingUnderscores(name), symbol); }, + tryFindAmbientModuleWithoutAugmentations: function (moduleName) { + // we deliberately exclude augmentations + // since we are only interested in declarations of the module itself + return tryFindAmbientModule(moduleName, /*withAugmentations*/ false); + }, + getApparentType: getApparentType, + getUnionType: getUnionType, + createAnonymousType: createAnonymousType, + createSignature: createSignature, + createSymbol: createSymbol, + createIndexInfo: createIndexInfo, + getAnyType: function () { return anyType; }, + getStringType: function () { return stringType; }, + getNumberType: function () { return numberType; }, + createPromiseType: createPromiseType, + createArrayType: createArrayType, + getElementTypeOfArrayType: getElementTypeOfArrayType, + getBooleanType: function () { return booleanType; }, + getFalseType: function (fresh) { return fresh ? falseType : regularFalseType; }, + getTrueType: function (fresh) { return fresh ? trueType : regularTrueType; }, + getVoidType: function () { return voidType; }, + getUndefinedType: function () { return undefinedType; }, + getNullType: function () { return nullType; }, + getESSymbolType: function () { return esSymbolType; }, + getNeverType: function () { return neverType; }, + isSymbolAccessible: isSymbolAccessible, + getObjectFlags: ts.getObjectFlags, + isArrayLikeType: isArrayLikeType, + isTypeInvalidDueToUnionDiscriminant: isTypeInvalidDueToUnionDiscriminant, + getAllPossiblePropertiesOfTypes: getAllPossiblePropertiesOfTypes, + getSuggestionForNonexistentProperty: function (node, type) { return getSuggestionForNonexistentProperty(node, type); }, + getSuggestionForNonexistentSymbol: function (location, name, meaning) { return getSuggestionForNonexistentSymbol(location, ts.escapeLeadingUnderscores(name), meaning); }, + getSuggestionForNonexistentExport: function (node, target) { return getSuggestionForNonexistentExport(node, target); }, + getBaseConstraintOfType: getBaseConstraintOfType, + getDefaultFromTypeParameter: function (type) { return type && type.flags & 262144 /* TypeParameter */ ? getDefaultFromTypeParameter(type) : undefined; }, + resolveName: function (name, location, meaning, excludeGlobals) { + return resolveName(location, ts.escapeLeadingUnderscores(name), meaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false, excludeGlobals); + }, + getJsxNamespace: function (n) { return ts.unescapeLeadingUnderscores(getJsxNamespace(n)); }, + getAccessibleSymbolChain: getAccessibleSymbolChain, + getTypePredicateOfSignature: getTypePredicateOfSignature, + resolveExternalModuleSymbol: resolveExternalModuleSymbol, + tryGetThisTypeAt: function (node) { + node = ts.getParseTreeNode(node); + return node && tryGetThisTypeAt(node); + }, + getTypeArgumentConstraint: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isTypeNode); + return node && getTypeArgumentConstraint(node); + }, + getSuggestionDiagnostics: function (file, ct) { + if (ts.skipTypeChecking(file, compilerOptions)) { + return ts.emptyArray; + } + var diagnostics; + try { + // Record the cancellation token so it can be checked later on during checkSourceElement. + // Do this in a finally block so we can ensure that it gets reset back to nothing after + // this call is done. + cancellationToken = ct; + // Ensure file is type checked + checkSourceFile(file); + ts.Debug.assert(!!(getNodeLinks(file).flags & 1 /* TypeChecked */)); + diagnostics = ts.addRange(diagnostics, suggestionDiagnostics.get(file.fileName)); + if (!file.isDeclarationFile && (!unusedIsError(0 /* Local */) || !unusedIsError(1 /* Parameter */))) { + addUnusedDiagnostics(); + } + return diagnostics || ts.emptyArray; + } + finally { + cancellationToken = undefined; + } + function addUnusedDiagnostics() { + checkUnusedIdentifiers(getPotentiallyUnusedIdentifiers(file), function (containingNode, kind, diag) { + if (!ts.containsParseError(containingNode) && !unusedIsError(kind)) { + (diagnostics || (diagnostics = [])).push(__assign({}, diag, { category: ts.DiagnosticCategory.Suggestion })); + } + }); + } + }, + runWithCancellationToken: function (token, callback) { + try { + cancellationToken = token; + return callback(checker); + } + finally { + cancellationToken = undefined; + } + }, + getLocalTypeParametersOfClassOrInterfaceOrTypeAlias: getLocalTypeParametersOfClassOrInterfaceOrTypeAlias, + }; + function getResolvedSignatureWorker(nodeIn, candidatesOutArray, argumentCount, isForSignatureHelp) { + var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression); + apparentArgumentCount = argumentCount; + var res = node ? getResolvedSignature(node, candidatesOutArray, isForSignatureHelp) : undefined; + apparentArgumentCount = undefined; + return res; + } + var tupleTypes = ts.createMap(); + var unionTypes = ts.createMap(); + var intersectionTypes = ts.createMap(); + var literalTypes = ts.createMap(); + var indexedAccessTypes = ts.createMap(); + var evolvingArrayTypes = []; + var undefinedProperties = ts.createMap(); + var unknownSymbol = createSymbol(4 /* Property */, "unknown"); + var resolvingSymbol = createSymbol(0, "__resolving__" /* Resolving */); + var anyType = createIntrinsicType(1 /* Any */, "any"); + var autoType = createIntrinsicType(1 /* Any */, "any"); + var wildcardType = createIntrinsicType(1 /* Any */, "any"); + var errorType = createIntrinsicType(1 /* Any */, "error"); + var unknownType = createIntrinsicType(2 /* Unknown */, "unknown"); + var undefinedType = createIntrinsicType(32768 /* Undefined */, "undefined"); + var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(32768 /* Undefined */ | 134217728 /* ContainsWideningType */, "undefined"); + var nullType = createIntrinsicType(65536 /* Null */, "null"); + var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(65536 /* Null */ | 134217728 /* ContainsWideningType */, "null"); + var stringType = createIntrinsicType(4 /* String */, "string"); + var numberType = createIntrinsicType(8 /* Number */, "number"); + var bigintType = createIntrinsicType(64 /* BigInt */, "bigint"); + var falseType = createIntrinsicType(512 /* BooleanLiteral */, "false"); + var regularFalseType = createIntrinsicType(512 /* BooleanLiteral */, "false"); + var trueType = createIntrinsicType(512 /* BooleanLiteral */, "true"); + var regularTrueType = createIntrinsicType(512 /* BooleanLiteral */, "true"); + trueType.regularType = regularTrueType; + trueType.freshType = trueType; + regularTrueType.regularType = regularTrueType; + regularTrueType.freshType = trueType; + falseType.regularType = regularFalseType; + falseType.freshType = falseType; + regularFalseType.regularType = regularFalseType; + regularFalseType.freshType = falseType; + var booleanType = createBooleanType([regularFalseType, regularTrueType]); + // Also mark all combinations of fresh/regular booleans as "Boolean" so they print as `boolean` instead of `true | false` + // (The union is cached, so simply doing the marking here is sufficient) + createBooleanType([regularFalseType, trueType]); + createBooleanType([falseType, regularTrueType]); + createBooleanType([falseType, trueType]); + var esSymbolType = createIntrinsicType(4096 /* ESSymbol */, "symbol"); + var voidType = createIntrinsicType(16384 /* Void */, "void"); + var neverType = createIntrinsicType(131072 /* Never */, "never"); + var silentNeverType = createIntrinsicType(131072 /* Never */, "never"); + var implicitNeverType = createIntrinsicType(131072 /* Never */, "never"); + var nonPrimitiveType = createIntrinsicType(67108864 /* NonPrimitive */, "object"); + var stringNumberSymbolType = getUnionType([stringType, numberType, esSymbolType]); + var keyofConstraintType = keyofStringsOnly ? stringType : stringNumberSymbolType; + var numberOrBigIntType = getUnionType([numberType, bigintType]); + var emptyObjectType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + var emptyJsxObjectType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + emptyJsxObjectType.objectFlags |= 4096 /* JsxAttributes */; + var emptyTypeLiteralSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */); + emptyTypeLiteralSymbol.members = ts.createSymbolTable(); + var emptyTypeLiteralType = createAnonymousType(emptyTypeLiteralSymbol, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + var emptyGenericType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + emptyGenericType.instantiations = ts.createMap(); + var anyFunctionType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + // The anyFunctionType contains the anyFunctionType by definition. The flag is further propagated + // in getPropagatingFlagsOfTypes, and it is checked in inferFromTypes. + anyFunctionType.flags |= 536870912 /* ContainsAnyFunctionType */; + var noConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + var circularConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + var resolvingDefaultType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + var markerSuperType = createType(262144 /* TypeParameter */); + var markerSubType = createType(262144 /* TypeParameter */); + markerSubType.constraint = markerSuperType; + var markerOtherType = createType(262144 /* TypeParameter */); + var noTypePredicate = createIdentifierTypePredicate("<>", 0, anyType); + var anySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + var unknownSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, errorType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + var resolvingSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + var silentNeverSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, silentNeverType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + var enumNumberIndexInfo = createIndexInfo(stringType, /*isReadonly*/ true); + var globals = ts.createSymbolTable(); + /** Key is "/path/to/a.ts|/path/to/b.ts". */ + var amalgamatedDuplicates; + var reverseMappedCache = ts.createMap(); + var ambientModulesCache; + /** + * List of every ambient module with a "*" wildcard. + * Unlike other ambient modules, these can't be stored in `globals` because symbol tables only deal with exact matches. + * This is only used if there is no exact match. + */ + var patternAmbientModules; + var globalObjectType; + var globalFunctionType; + var globalCallableFunctionType; + var globalNewableFunctionType; + var globalArrayType; + var globalReadonlyArrayType; + var globalStringType; + var globalNumberType; + var globalBooleanType; + var globalRegExpType; + var globalThisType; + var anyArrayType; + var autoArrayType; + var anyReadonlyArrayType; + var deferredGlobalNonNullableTypeAlias; + // The library files are only loaded when the feature is used. + // This allows users to just specify library files they want to used through --lib + // and they will not get an error from not having unrelated library files + var deferredGlobalESSymbolConstructorSymbol; + var deferredGlobalESSymbolType; + var deferredGlobalTypedPropertyDescriptorType; + var deferredGlobalPromiseType; + var deferredGlobalPromiseLikeType; + var deferredGlobalPromiseConstructorSymbol; + var deferredGlobalPromiseConstructorLikeType; + var deferredGlobalIterableType; + var deferredGlobalIteratorType; + var deferredGlobalIterableIteratorType; + var deferredGlobalAsyncIterableType; + var deferredGlobalAsyncIteratorType; + var deferredGlobalAsyncIterableIteratorType; + var deferredGlobalTemplateStringsArrayType; + var deferredGlobalImportMetaType; + var deferredGlobalExtractSymbol; + var deferredGlobalExcludeSymbol; + var deferredGlobalPickSymbol; + var deferredGlobalBigIntType; + var allPotentiallyUnusedIdentifiers = ts.createMap(); // key is file name + var flowLoopStart = 0; + var flowLoopCount = 0; + var sharedFlowCount = 0; + var flowAnalysisDisabled = false; + var emptyStringType = getLiteralType(""); + var zeroType = getLiteralType(0); + var zeroBigIntType = getLiteralType({ negative: false, base10Value: "0" }); + var resolutionTargets = []; + var resolutionResults = []; + var resolutionPropertyNames = []; + var suggestionCount = 0; + var maximumSuggestionCount = 10; + var mergedSymbols = []; + var symbolLinks = []; + var nodeLinks = []; + var flowLoopCaches = []; + var flowLoopNodes = []; + var flowLoopKeys = []; + var flowLoopTypes = []; + var sharedFlowNodes = []; + var sharedFlowTypes = []; + var potentialThisCollisions = []; + var potentialNewTargetCollisions = []; + var awaitedTypeStack = []; + var diagnostics = ts.createDiagnosticCollection(); + // Suggestion diagnostics must have a file. Keyed by source file name. + var suggestionDiagnostics = ts.createMultiMap(); + var TypeFacts; + (function (TypeFacts) { + TypeFacts[TypeFacts["None"] = 0] = "None"; + TypeFacts[TypeFacts["TypeofEQString"] = 1] = "TypeofEQString"; + TypeFacts[TypeFacts["TypeofEQNumber"] = 2] = "TypeofEQNumber"; + TypeFacts[TypeFacts["TypeofEQBigInt"] = 4] = "TypeofEQBigInt"; + TypeFacts[TypeFacts["TypeofEQBoolean"] = 8] = "TypeofEQBoolean"; + TypeFacts[TypeFacts["TypeofEQSymbol"] = 16] = "TypeofEQSymbol"; + TypeFacts[TypeFacts["TypeofEQObject"] = 32] = "TypeofEQObject"; + TypeFacts[TypeFacts["TypeofEQFunction"] = 64] = "TypeofEQFunction"; + TypeFacts[TypeFacts["TypeofEQHostObject"] = 128] = "TypeofEQHostObject"; + TypeFacts[TypeFacts["TypeofNEString"] = 256] = "TypeofNEString"; + TypeFacts[TypeFacts["TypeofNENumber"] = 512] = "TypeofNENumber"; + TypeFacts[TypeFacts["TypeofNEBigInt"] = 1024] = "TypeofNEBigInt"; + TypeFacts[TypeFacts["TypeofNEBoolean"] = 2048] = "TypeofNEBoolean"; + TypeFacts[TypeFacts["TypeofNESymbol"] = 4096] = "TypeofNESymbol"; + TypeFacts[TypeFacts["TypeofNEObject"] = 8192] = "TypeofNEObject"; + TypeFacts[TypeFacts["TypeofNEFunction"] = 16384] = "TypeofNEFunction"; + TypeFacts[TypeFacts["TypeofNEHostObject"] = 32768] = "TypeofNEHostObject"; + TypeFacts[TypeFacts["EQUndefined"] = 65536] = "EQUndefined"; + TypeFacts[TypeFacts["EQNull"] = 131072] = "EQNull"; + TypeFacts[TypeFacts["EQUndefinedOrNull"] = 262144] = "EQUndefinedOrNull"; + TypeFacts[TypeFacts["NEUndefined"] = 524288] = "NEUndefined"; + TypeFacts[TypeFacts["NENull"] = 1048576] = "NENull"; + TypeFacts[TypeFacts["NEUndefinedOrNull"] = 2097152] = "NEUndefinedOrNull"; + TypeFacts[TypeFacts["Truthy"] = 4194304] = "Truthy"; + TypeFacts[TypeFacts["Falsy"] = 8388608] = "Falsy"; + TypeFacts[TypeFacts["All"] = 16777215] = "All"; + // The following members encode facts about particular kinds of types for use in the getTypeFacts function. + // The presence of a particular fact means that the given test is true for some (and possibly all) values + // of that kind of type. + TypeFacts[TypeFacts["BaseStringStrictFacts"] = 3735041] = "BaseStringStrictFacts"; + TypeFacts[TypeFacts["BaseStringFacts"] = 12582401] = "BaseStringFacts"; + TypeFacts[TypeFacts["StringStrictFacts"] = 16317953] = "StringStrictFacts"; + TypeFacts[TypeFacts["StringFacts"] = 16776705] = "StringFacts"; + TypeFacts[TypeFacts["EmptyStringStrictFacts"] = 12123649] = "EmptyStringStrictFacts"; + TypeFacts[TypeFacts["EmptyStringFacts"] = 12582401] = "EmptyStringFacts"; + TypeFacts[TypeFacts["NonEmptyStringStrictFacts"] = 7929345] = "NonEmptyStringStrictFacts"; + TypeFacts[TypeFacts["NonEmptyStringFacts"] = 16776705] = "NonEmptyStringFacts"; + TypeFacts[TypeFacts["BaseNumberStrictFacts"] = 3734786] = "BaseNumberStrictFacts"; + TypeFacts[TypeFacts["BaseNumberFacts"] = 12582146] = "BaseNumberFacts"; + TypeFacts[TypeFacts["NumberStrictFacts"] = 16317698] = "NumberStrictFacts"; + TypeFacts[TypeFacts["NumberFacts"] = 16776450] = "NumberFacts"; + TypeFacts[TypeFacts["ZeroNumberStrictFacts"] = 12123394] = "ZeroNumberStrictFacts"; + TypeFacts[TypeFacts["ZeroNumberFacts"] = 12582146] = "ZeroNumberFacts"; + TypeFacts[TypeFacts["NonZeroNumberStrictFacts"] = 7929090] = "NonZeroNumberStrictFacts"; + TypeFacts[TypeFacts["NonZeroNumberFacts"] = 16776450] = "NonZeroNumberFacts"; + TypeFacts[TypeFacts["BaseBigIntStrictFacts"] = 3734276] = "BaseBigIntStrictFacts"; + TypeFacts[TypeFacts["BaseBigIntFacts"] = 12581636] = "BaseBigIntFacts"; + TypeFacts[TypeFacts["BigIntStrictFacts"] = 16317188] = "BigIntStrictFacts"; + TypeFacts[TypeFacts["BigIntFacts"] = 16775940] = "BigIntFacts"; + TypeFacts[TypeFacts["ZeroBigIntStrictFacts"] = 12122884] = "ZeroBigIntStrictFacts"; + TypeFacts[TypeFacts["ZeroBigIntFacts"] = 12581636] = "ZeroBigIntFacts"; + TypeFacts[TypeFacts["NonZeroBigIntStrictFacts"] = 7928580] = "NonZeroBigIntStrictFacts"; + TypeFacts[TypeFacts["NonZeroBigIntFacts"] = 16775940] = "NonZeroBigIntFacts"; + TypeFacts[TypeFacts["BaseBooleanStrictFacts"] = 3733256] = "BaseBooleanStrictFacts"; + TypeFacts[TypeFacts["BaseBooleanFacts"] = 12580616] = "BaseBooleanFacts"; + TypeFacts[TypeFacts["BooleanStrictFacts"] = 16316168] = "BooleanStrictFacts"; + TypeFacts[TypeFacts["BooleanFacts"] = 16774920] = "BooleanFacts"; + TypeFacts[TypeFacts["FalseStrictFacts"] = 12121864] = "FalseStrictFacts"; + TypeFacts[TypeFacts["FalseFacts"] = 12580616] = "FalseFacts"; + TypeFacts[TypeFacts["TrueStrictFacts"] = 7927560] = "TrueStrictFacts"; + TypeFacts[TypeFacts["TrueFacts"] = 16774920] = "TrueFacts"; + TypeFacts[TypeFacts["SymbolStrictFacts"] = 7925520] = "SymbolStrictFacts"; + TypeFacts[TypeFacts["SymbolFacts"] = 16772880] = "SymbolFacts"; + TypeFacts[TypeFacts["ObjectStrictFacts"] = 7888800] = "ObjectStrictFacts"; + TypeFacts[TypeFacts["ObjectFacts"] = 16736160] = "ObjectFacts"; + TypeFacts[TypeFacts["FunctionStrictFacts"] = 7880640] = "FunctionStrictFacts"; + TypeFacts[TypeFacts["FunctionFacts"] = 16728000] = "FunctionFacts"; + TypeFacts[TypeFacts["UndefinedFacts"] = 9830144] = "UndefinedFacts"; + TypeFacts[TypeFacts["NullFacts"] = 9363232] = "NullFacts"; + TypeFacts[TypeFacts["EmptyObjectStrictFacts"] = 16318463] = "EmptyObjectStrictFacts"; + TypeFacts[TypeFacts["EmptyObjectFacts"] = 16777215] = "EmptyObjectFacts"; + })(TypeFacts || (TypeFacts = {})); + var typeofEQFacts = ts.createMapFromTemplate({ + string: 1 /* TypeofEQString */, + number: 2 /* TypeofEQNumber */, + bigint: 4 /* TypeofEQBigInt */, + boolean: 8 /* TypeofEQBoolean */, + symbol: 16 /* TypeofEQSymbol */, + undefined: 65536 /* EQUndefined */, + object: 32 /* TypeofEQObject */, + function: 64 /* TypeofEQFunction */ + }); + var typeofNEFacts = ts.createMapFromTemplate({ + string: 256 /* TypeofNEString */, + number: 512 /* TypeofNENumber */, + bigint: 1024 /* TypeofNEBigInt */, + boolean: 2048 /* TypeofNEBoolean */, + symbol: 4096 /* TypeofNESymbol */, + undefined: 524288 /* NEUndefined */, + object: 8192 /* TypeofNEObject */, + function: 16384 /* TypeofNEFunction */ + }); + var typeofTypesByName = ts.createMapFromTemplate({ + string: stringType, + number: numberType, + bigint: bigintType, + boolean: booleanType, + symbol: esSymbolType, + undefined: undefinedType + }); + var typeofType = createTypeofType(); + var _jsxNamespace; + var _jsxFactoryEntity; + var subtypeRelation = ts.createMap(); + var assignableRelation = ts.createMap(); + var definitelyAssignableRelation = ts.createMap(); + var comparableRelation = ts.createMap(); + var identityRelation = ts.createMap(); + var enumRelation = ts.createMap(); + var TypeSystemPropertyName; + (function (TypeSystemPropertyName) { + TypeSystemPropertyName[TypeSystemPropertyName["Type"] = 0] = "Type"; + TypeSystemPropertyName[TypeSystemPropertyName["ResolvedBaseConstructorType"] = 1] = "ResolvedBaseConstructorType"; + TypeSystemPropertyName[TypeSystemPropertyName["DeclaredType"] = 2] = "DeclaredType"; + TypeSystemPropertyName[TypeSystemPropertyName["ResolvedReturnType"] = 3] = "ResolvedReturnType"; + TypeSystemPropertyName[TypeSystemPropertyName["ImmediateBaseConstraint"] = 4] = "ImmediateBaseConstraint"; + TypeSystemPropertyName[TypeSystemPropertyName["EnumTagType"] = 5] = "EnumTagType"; + TypeSystemPropertyName[TypeSystemPropertyName["JSDocTypeReference"] = 6] = "JSDocTypeReference"; + })(TypeSystemPropertyName || (TypeSystemPropertyName = {})); + var CheckMode; + (function (CheckMode) { + CheckMode[CheckMode["Normal"] = 0] = "Normal"; + CheckMode[CheckMode["SkipContextSensitive"] = 1] = "SkipContextSensitive"; + CheckMode[CheckMode["Inferential"] = 2] = "Inferential"; + CheckMode[CheckMode["Contextual"] = 3] = "Contextual"; + })(CheckMode || (CheckMode = {})); + var CallbackCheck; + (function (CallbackCheck) { + CallbackCheck[CallbackCheck["None"] = 0] = "None"; + CallbackCheck[CallbackCheck["Bivariant"] = 1] = "Bivariant"; + CallbackCheck[CallbackCheck["Strict"] = 2] = "Strict"; + })(CallbackCheck || (CallbackCheck = {})); + var MappedTypeModifiers; + (function (MappedTypeModifiers) { + MappedTypeModifiers[MappedTypeModifiers["IncludeReadonly"] = 1] = "IncludeReadonly"; + MappedTypeModifiers[MappedTypeModifiers["ExcludeReadonly"] = 2] = "ExcludeReadonly"; + MappedTypeModifiers[MappedTypeModifiers["IncludeOptional"] = 4] = "IncludeOptional"; + MappedTypeModifiers[MappedTypeModifiers["ExcludeOptional"] = 8] = "ExcludeOptional"; + })(MappedTypeModifiers || (MappedTypeModifiers = {})); + var ExpandingFlags; + (function (ExpandingFlags) { + ExpandingFlags[ExpandingFlags["None"] = 0] = "None"; + ExpandingFlags[ExpandingFlags["Source"] = 1] = "Source"; + ExpandingFlags[ExpandingFlags["Target"] = 2] = "Target"; + ExpandingFlags[ExpandingFlags["Both"] = 3] = "Both"; + })(ExpandingFlags || (ExpandingFlags = {})); + var MembersOrExportsResolutionKind; + (function (MembersOrExportsResolutionKind) { + MembersOrExportsResolutionKind["resolvedExports"] = "resolvedExports"; + MembersOrExportsResolutionKind["resolvedMembers"] = "resolvedMembers"; + })(MembersOrExportsResolutionKind || (MembersOrExportsResolutionKind = {})); + var UnusedKind; + (function (UnusedKind) { + UnusedKind[UnusedKind["Local"] = 0] = "Local"; + UnusedKind[UnusedKind["Parameter"] = 1] = "Parameter"; + })(UnusedKind || (UnusedKind = {})); + var builtinGlobals = ts.createSymbolTable(); + builtinGlobals.set(undefinedSymbol.escapedName, undefinedSymbol); + var isNotOverloadAndNotAccessor = ts.and(isNotOverload, isNotAccessor); + initializeTypeChecker(); + return checker; + function getJsxNamespace(location) { + if (location) { + var file = ts.getSourceFileOfNode(location); + if (file) { + if (file.localJsxNamespace) { + return file.localJsxNamespace; + } + var jsxPragma = file.pragmas.get("jsx"); + if (jsxPragma) { + var chosenpragma = ts.isArray(jsxPragma) ? jsxPragma[0] : jsxPragma; // TODO: GH#18217 + file.localJsxFactory = ts.parseIsolatedEntityName(chosenpragma.arguments.factory, languageVersion); + if (file.localJsxFactory) { + return file.localJsxNamespace = getFirstIdentifier(file.localJsxFactory).escapedText; + } + } + } + } + if (!_jsxNamespace) { + _jsxNamespace = "React"; + if (compilerOptions.jsxFactory) { + _jsxFactoryEntity = ts.parseIsolatedEntityName(compilerOptions.jsxFactory, languageVersion); + if (_jsxFactoryEntity) { + _jsxNamespace = getFirstIdentifier(_jsxFactoryEntity).escapedText; + } + } + else if (compilerOptions.reactNamespace) { + _jsxNamespace = ts.escapeLeadingUnderscores(compilerOptions.reactNamespace); + } + } + return _jsxNamespace; + } + function getEmitResolver(sourceFile, cancellationToken) { + // Ensure we have all the type information in place for this file so that all the + // emitter questions of this resolver will return the right information. + getDiagnostics(sourceFile, cancellationToken); + return emitResolver; + } + function lookupOrIssueError(location, message, arg0, arg1, arg2, arg3) { + var diagnostic = location + ? ts.createDiagnosticForNode(location, message, arg0, arg1, arg2, arg3) + : ts.createCompilerDiagnostic(message, arg0, arg1, arg2, arg3); + var existing = diagnostics.lookup(diagnostic); + if (existing) { + return existing; + } + else { + diagnostics.add(diagnostic); + return diagnostic; + } + } + function addRelatedInfo(diagnostic) { + var relatedInformation = []; + for (var _i = 1; _i < arguments.length; _i++) { + relatedInformation[_i - 1] = arguments[_i]; + } + var _a; + if (!diagnostic.relatedInformation) { + diagnostic.relatedInformation = []; + } + (_a = diagnostic.relatedInformation).push.apply(_a, relatedInformation); + return diagnostic; + } + function error(location, message, arg0, arg1, arg2, arg3) { + var diagnostic = location + ? ts.createDiagnosticForNode(location, message, arg0, arg1, arg2, arg3) + : ts.createCompilerDiagnostic(message, arg0, arg1, arg2, arg3); + diagnostics.add(diagnostic); + return diagnostic; + } + function addErrorOrSuggestion(isError, diagnostic) { + if (isError) { + diagnostics.add(diagnostic); + } + else { + suggestionDiagnostics.add(diagnostic.file.fileName, __assign({}, diagnostic, { category: ts.DiagnosticCategory.Suggestion })); + } + } + function errorOrSuggestion(isError, location, message, arg0, arg1, arg2, arg3) { + addErrorOrSuggestion(isError, "message" in message ? ts.createDiagnosticForNode(location, message, arg0, arg1, arg2, arg3) : ts.createDiagnosticForNodeFromMessageChain(location, message)); + } + function createSymbol(flags, name, checkFlags) { + symbolCount++; + var symbol = (new Symbol(flags | 33554432 /* Transient */, name)); + symbol.checkFlags = checkFlags || 0; + return symbol; + } + function isTransientSymbol(symbol) { + return (symbol.flags & 33554432 /* Transient */) !== 0; + } + function getExcludedSymbolFlags(flags) { + var result = 0; + if (flags & 2 /* BlockScopedVariable */) + result |= 67220415 /* BlockScopedVariableExcludes */; + if (flags & 1 /* FunctionScopedVariable */) + result |= 67220414 /* FunctionScopedVariableExcludes */; + if (flags & 4 /* Property */) + result |= 0 /* PropertyExcludes */; + if (flags & 8 /* EnumMember */) + result |= 68008959 /* EnumMemberExcludes */; + if (flags & 16 /* Function */) + result |= 67219887 /* FunctionExcludes */; + if (flags & 32 /* Class */) + result |= 68008383 /* ClassExcludes */; + if (flags & 64 /* Interface */) + result |= 67897736 /* InterfaceExcludes */; + if (flags & 256 /* RegularEnum */) + result |= 68008191 /* RegularEnumExcludes */; + if (flags & 128 /* ConstEnum */) + result |= 68008831 /* ConstEnumExcludes */; + if (flags & 512 /* ValueModule */) + result |= 110735 /* ValueModuleExcludes */; + if (flags & 8192 /* Method */) + result |= 67212223 /* MethodExcludes */; + if (flags & 32768 /* GetAccessor */) + result |= 67154879 /* GetAccessorExcludes */; + if (flags & 65536 /* SetAccessor */) + result |= 67187647 /* SetAccessorExcludes */; + if (flags & 262144 /* TypeParameter */) + result |= 67635688 /* TypeParameterExcludes */; + if (flags & 524288 /* TypeAlias */) + result |= 67897832 /* TypeAliasExcludes */; + if (flags & 2097152 /* Alias */) + result |= 2097152 /* AliasExcludes */; + return result; + } + function recordMergedSymbol(target, source) { + if (!source.mergeId) { + source.mergeId = nextMergeId; + nextMergeId++; + } + mergedSymbols[source.mergeId] = target; + } + function cloneSymbol(symbol) { + var result = createSymbol(symbol.flags, symbol.escapedName); + result.declarations = symbol.declarations ? symbol.declarations.slice() : []; + result.parent = symbol.parent; + if (symbol.valueDeclaration) + result.valueDeclaration = symbol.valueDeclaration; + if (symbol.constEnumOnlyModule) + result.constEnumOnlyModule = true; + if (symbol.members) + result.members = ts.cloneMap(symbol.members); + if (symbol.exports) + result.exports = ts.cloneMap(symbol.exports); + recordMergedSymbol(result, symbol); + return result; + } + /** + * Note: if target is transient, then it is mutable, and mergeSymbol with both mutate and return it. + * If target is not transient, mergeSymbol will produce a transient clone, mutate that and return it. + */ + function mergeSymbol(target, source) { + if (!(target.flags & getExcludedSymbolFlags(source.flags)) || + (source.flags | target.flags) & 67108864 /* Assignment */) { + ts.Debug.assert(source !== target); + if (!(target.flags & 33554432 /* Transient */)) { + var resolvedTarget = resolveSymbol(target); + if (resolvedTarget === unknownSymbol) { + return source; + } + target = cloneSymbol(resolvedTarget); + } + // Javascript static-property-assignment declarations always merge, even though they are also values + if (source.flags & 512 /* ValueModule */ && target.flags & 512 /* ValueModule */ && target.constEnumOnlyModule && !source.constEnumOnlyModule) { + // reset flag when merging instantiated module into value module that has only const enums + target.constEnumOnlyModule = false; + } + target.flags |= source.flags; + if (source.valueDeclaration && + (!target.valueDeclaration || + ts.isAssignmentDeclaration(target.valueDeclaration) && !ts.isAssignmentDeclaration(source.valueDeclaration) || + ts.isEffectiveModuleDeclaration(target.valueDeclaration) && !ts.isEffectiveModuleDeclaration(source.valueDeclaration))) { + // other kinds of value declarations take precedence over modules and assignment declarations + target.valueDeclaration = source.valueDeclaration; + } + ts.addRange(target.declarations, source.declarations); + if (source.members) { + if (!target.members) + target.members = ts.createSymbolTable(); + mergeSymbolTable(target.members, source.members); + } + if (source.exports) { + if (!target.exports) + target.exports = ts.createSymbolTable(); + mergeSymbolTable(target.exports, source.exports); + } + recordMergedSymbol(target, source); + } + else if (target.flags & 1024 /* NamespaceModule */) { + error(ts.getNameOfDeclaration(source.declarations[0]), ts.Diagnostics.Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity, symbolToString(target)); + } + else { // error + var isEitherEnum = !!(target.flags & 384 /* Enum */ || source.flags & 384 /* Enum */); + var isEitherBlockScoped_1 = !!(target.flags & 2 /* BlockScopedVariable */ || source.flags & 2 /* BlockScopedVariable */); + var message = isEitherEnum + ? ts.Diagnostics.Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations + : isEitherBlockScoped_1 + ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 + : ts.Diagnostics.Duplicate_identifier_0; + var sourceSymbolFile = source.declarations && ts.getSourceFileOfNode(source.declarations[0]); + var targetSymbolFile = target.declarations && ts.getSourceFileOfNode(target.declarations[0]); + var symbolName_1 = symbolToString(source); + // Collect top-level duplicate identifier errors into one mapping, so we can then merge their diagnostics if there are a bunch + if (sourceSymbolFile && targetSymbolFile && amalgamatedDuplicates && !isEitherEnum && sourceSymbolFile !== targetSymbolFile) { + var firstFile_1 = ts.comparePaths(sourceSymbolFile.path, targetSymbolFile.path) === -1 /* LessThan */ ? sourceSymbolFile : targetSymbolFile; + var secondFile_1 = firstFile_1 === sourceSymbolFile ? targetSymbolFile : sourceSymbolFile; + var filesDuplicates = ts.getOrUpdate(amalgamatedDuplicates, firstFile_1.path + "|" + secondFile_1.path, function () { + return ({ firstFile: firstFile_1, secondFile: secondFile_1, conflictingSymbols: ts.createMap() }); + }); + var conflictingSymbolInfo = ts.getOrUpdate(filesDuplicates.conflictingSymbols, symbolName_1, function () { + return ({ isBlockScoped: isEitherBlockScoped_1, firstFileLocations: [], secondFileLocations: [] }); + }); + addDuplicateLocations(conflictingSymbolInfo.firstFileLocations, source); + addDuplicateLocations(conflictingSymbolInfo.secondFileLocations, target); + } + else { + addDuplicateDeclarationErrorsForSymbols(source, message, symbolName_1, target); + addDuplicateDeclarationErrorsForSymbols(target, message, symbolName_1, source); + } + } + return target; + function addDuplicateLocations(locs, symbol) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + ts.pushIfUnique(locs, (ts.getExpandoInitializer(decl, /*isPrototypeAssignment*/ false) ? ts.getNameOfExpando(decl) : ts.getNameOfDeclaration(decl)) || decl); + } + } + } + function addDuplicateDeclarationErrorsForSymbols(target, message, symbolName, source) { + ts.forEach(target.declarations, function (node) { + var errorNode = (ts.getExpandoInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getNameOfExpando(node) : ts.getNameOfDeclaration(node)) || node; + addDuplicateDeclarationError(errorNode, message, symbolName, source.declarations); + }); + } + function addDuplicateDeclarationError(errorNode, message, symbolName, relatedNodes) { + var err = lookupOrIssueError(errorNode, message, symbolName); + for (var _i = 0, _a = relatedNodes || ts.emptyArray; _i < _a.length; _i++) { + var relatedNode = _a[_i]; + err.relatedInformation = err.relatedInformation || []; + if (ts.length(err.relatedInformation) >= 5) + continue; + addRelatedInfo(err, !ts.length(err.relatedInformation) ? ts.createDiagnosticForNode(relatedNode, ts.Diagnostics._0_was_also_declared_here, symbolName) : ts.createDiagnosticForNode(relatedNode, ts.Diagnostics.and_here)); + } + } + function combineSymbolTables(first, second) { + if (!ts.hasEntries(first)) + return second; + if (!ts.hasEntries(second)) + return first; + var combined = ts.createSymbolTable(); + mergeSymbolTable(combined, first); + mergeSymbolTable(combined, second); + return combined; + } + function mergeSymbolTable(target, source) { + source.forEach(function (sourceSymbol, id) { + var targetSymbol = target.get(id); + target.set(id, targetSymbol ? mergeSymbol(targetSymbol, sourceSymbol) : sourceSymbol); + }); + } + function mergeModuleAugmentation(moduleName) { + var moduleAugmentation = moduleName.parent; + if (moduleAugmentation.symbol.declarations[0] !== moduleAugmentation) { + // this is a combined symbol for multiple augmentations within the same file. + // its symbol already has accumulated information for all declarations + // so we need to add it just once - do the work only for first declaration + ts.Debug.assert(moduleAugmentation.symbol.declarations.length > 1); + return; + } + if (ts.isGlobalScopeAugmentation(moduleAugmentation)) { + mergeSymbolTable(globals, moduleAugmentation.symbol.exports); + } + else { + // find a module that about to be augmented + // do not validate names of augmentations that are defined in ambient context + var moduleNotFoundError = !(moduleName.parent.parent.flags & 4194304 /* Ambient */) + ? ts.Diagnostics.Invalid_module_name_in_augmentation_module_0_cannot_be_found + : undefined; + var mainModule = resolveExternalModuleNameWorker(moduleName, moduleName, moduleNotFoundError, /*isForAugmentation*/ true); + if (!mainModule) { + return; + } + // obtain item referenced by 'export=' + mainModule = resolveExternalModuleSymbol(mainModule); + if (mainModule.flags & 1920 /* Namespace */) { + mainModule = mergeSymbol(mainModule, moduleAugmentation.symbol); + } + else { + // moduleName will be a StringLiteral since this is not `declare global`. + error(moduleName, ts.Diagnostics.Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity, moduleName.text); + } + } + } + function addToSymbolTable(target, source, message) { + source.forEach(function (sourceSymbol, id) { + var targetSymbol = target.get(id); + if (targetSymbol) { + // Error on redeclarations + ts.forEach(targetSymbol.declarations, addDeclarationDiagnostic(ts.unescapeLeadingUnderscores(id), message)); + } + else { + target.set(id, sourceSymbol); + } + }); + function addDeclarationDiagnostic(id, message) { + return function (declaration) { return diagnostics.add(ts.createDiagnosticForNode(declaration, message, id)); }; + } + } + function getSymbolLinks(symbol) { + if (symbol.flags & 33554432 /* Transient */) + return symbol; + var id = getSymbolId(symbol); + return symbolLinks[id] || (symbolLinks[id] = {}); + } + function getNodeLinks(node) { + var nodeId = getNodeId(node); + return nodeLinks[nodeId] || (nodeLinks[nodeId] = { flags: 0 }); + } + function isGlobalSourceFile(node) { + return node.kind === 279 /* SourceFile */ && !ts.isExternalOrCommonJsModule(node); + } + function getSymbol(symbols, name, meaning) { + if (meaning) { + var symbol = symbols.get(name); + if (symbol) { + ts.Debug.assert((ts.getCheckFlags(symbol) & 1 /* Instantiated */) === 0, "Should never get an instantiated symbol here."); + if (symbol.flags & meaning) { + return symbol; + } + if (symbol.flags & 2097152 /* Alias */) { + var target = resolveAlias(symbol); + // Unknown symbol means an error occurred in alias resolution, treat it as positive answer to avoid cascading errors + if (target === unknownSymbol || target.flags & meaning) { + return symbol; + } + } + } + } + // return undefined if we can't find a symbol. + } + /** + * Get symbols that represent parameter-property-declaration as parameter and as property declaration + * @param parameter a parameterDeclaration node + * @param parameterName a name of the parameter to get the symbols for. + * @return a tuple of two symbols + */ + function getSymbolsOfParameterPropertyDeclaration(parameter, parameterName) { + var constructorDeclaration = parameter.parent; + var classDeclaration = parameter.parent.parent; + var parameterSymbol = getSymbol(constructorDeclaration.locals, parameterName, 67220415 /* Value */); + var propertySymbol = getSymbol(getMembersOfSymbol(classDeclaration.symbol), parameterName, 67220415 /* Value */); + if (parameterSymbol && propertySymbol) { + return [parameterSymbol, propertySymbol]; + } + return ts.Debug.fail("There should exist two symbols, one as property declaration and one as parameter declaration"); + } + function isBlockScopedNameDeclaredBeforeUse(declaration, usage) { + var declarationFile = ts.getSourceFileOfNode(declaration); + var useFile = ts.getSourceFileOfNode(usage); + if (declarationFile !== useFile) { + if ((moduleKind && (declarationFile.externalModuleIndicator || useFile.externalModuleIndicator)) || + (!compilerOptions.outFile && !compilerOptions.out) || + isInTypeQuery(usage) || + declaration.flags & 4194304 /* Ambient */) { + // nodes are in different files and order cannot be determined + return true; + } + // declaration is after usage + // can be legal if usage is deferred (i.e. inside function or in initializer of instance property) + if (isUsedInFunctionOrInstanceProperty(usage, declaration)) { + return true; + } + var sourceFiles = host.getSourceFiles(); + return sourceFiles.indexOf(declarationFile) <= sourceFiles.indexOf(useFile); + } + if (declaration.pos <= usage.pos) { + // declaration is before usage + if (declaration.kind === 186 /* BindingElement */) { + // still might be illegal if declaration and usage are both binding elements (eg var [a = b, b = b] = [1, 2]) + var errorBindingElement = ts.getAncestor(usage, 186 /* BindingElement */); + if (errorBindingElement) { + return ts.findAncestor(errorBindingElement, ts.isBindingElement) !== ts.findAncestor(declaration, ts.isBindingElement) || + declaration.pos < errorBindingElement.pos; + } + // or it might be illegal if usage happens before parent variable is declared (eg var [a] = a) + return isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 237 /* VariableDeclaration */), usage); + } + else if (declaration.kind === 237 /* VariableDeclaration */) { + // still might be illegal if usage is in the initializer of the variable declaration (eg var a = a) + return !isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage); + } + else if (ts.isClassDeclaration(declaration)) { + // still might be illegal if the usage is within a computed property name in the class (eg class A { static p = "a"; [A.p]() {} }) + return !ts.findAncestor(usage, function (n) { return ts.isComputedPropertyName(n) && n.parent.parent === declaration; }); + } + return true; + } + // declaration is after usage, but it can still be legal if usage is deferred: + // 1. inside an export specifier + // 2. inside a function + // 3. inside an instance property initializer, a reference to a non-instance property + // 4. inside a static property initializer, a reference to a static method in the same class + // 5. inside a TS export= declaration (since we will move the export statement during emit to avoid TDZ) + // or if usage is in a type context: + // 1. inside a type query (typeof in type position) + // 2. inside a jsdoc comment + if (usage.parent.kind === 257 /* ExportSpecifier */ || (usage.parent.kind === 254 /* ExportAssignment */ && usage.parent.isExportEquals)) { + // export specifiers do not use the variable, they only make it available for use + return true; + } + // When resolving symbols for exports, the `usage` location passed in can be the export site directly + if (usage.kind === 254 /* ExportAssignment */ && usage.isExportEquals) { + return true; + } + var container = ts.getEnclosingBlockScopeContainer(declaration); + return !!(usage.flags & 2097152 /* JSDoc */) || isInTypeQuery(usage) || isUsedInFunctionOrInstanceProperty(usage, declaration, container); + function isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage) { + var container = ts.getEnclosingBlockScopeContainer(declaration); + switch (declaration.parent.parent.kind) { + case 219 /* VariableStatement */: + case 225 /* ForStatement */: + case 227 /* ForOfStatement */: + // variable statement/for/for-of statement case, + // use site should not be inside variable declaration (initializer of declaration or binding element) + if (isSameScopeDescendentOf(usage, declaration, container)) { + return true; + } + break; + } + // ForIn/ForOf case - use site should not be used in expression part + var grandparent = declaration.parent.parent; + return ts.isForInOrOfStatement(grandparent) && isSameScopeDescendentOf(usage, grandparent.expression, container); + } + function isUsedInFunctionOrInstanceProperty(usage, declaration, container) { + return !!ts.findAncestor(usage, function (current) { + if (current === container) { + return "quit"; + } + if (ts.isFunctionLike(current)) { + return true; + } + var initializerOfProperty = current.parent && + current.parent.kind === 154 /* PropertyDeclaration */ && + current.parent.initializer === current; + if (initializerOfProperty) { + if (ts.hasModifier(current.parent, 32 /* Static */)) { + if (declaration.kind === 156 /* MethodDeclaration */) { + return true; + } + } + else { + var isDeclarationInstanceProperty = declaration.kind === 154 /* PropertyDeclaration */ && !ts.hasModifier(declaration, 32 /* Static */); + if (!isDeclarationInstanceProperty || ts.getContainingClass(usage) !== ts.getContainingClass(declaration)) { + return true; + } + } + } + return false; + }); + } + } + /** + * Resolve a given name for a given meaning at a given location. An error is reported if the name was not found and + * the nameNotFoundMessage argument is not undefined. Returns the resolved symbol, or undefined if no symbol with + * the given name can be found. + * + * @param isUse If true, this will count towards --noUnusedLocals / --noUnusedParameters. + */ + function resolveName(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, suggestedNameNotFoundMessage) { + if (excludeGlobals === void 0) { excludeGlobals = false; } + return resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, getSymbol, suggestedNameNotFoundMessage); + } + function resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, lookup, suggestedNameNotFoundMessage) { + var originalLocation = location; // needed for did-you-mean error reporting, which gathers candidates starting from the original location + var result; + var lastLocation; + var lastSelfReferenceLocation; + var propertyWithInvalidInitializer; + var errorLocation = location; + var grandparent; + var isInExternalModule = false; + loop: while (location) { + // Locals of a source file are not in scope (because they get merged into the global symbol table) + if (location.locals && !isGlobalSourceFile(location)) { + if (result = lookup(location.locals, name, meaning)) { + var useResult = true; + if (ts.isFunctionLike(location) && lastLocation && lastLocation !== location.body) { + // symbol lookup restrictions for function-like declarations + // - Type parameters of a function are in scope in the entire function declaration, including the parameter + // list and return type. However, local types are only in scope in the function body. + // - parameters are only in the scope of function body + // This restriction does not apply to JSDoc comment types because they are parented + // at a higher level than type parameters would normally be + if (meaning & result.flags & 67897832 /* Type */ && lastLocation.kind !== 291 /* JSDocComment */) { + useResult = result.flags & 262144 /* TypeParameter */ + // type parameters are visible in parameter list, return type and type parameter list + ? lastLocation === location.type || + lastLocation.kind === 151 /* Parameter */ || + lastLocation.kind === 150 /* TypeParameter */ + // local types not visible outside the function body + : false; + } + if (meaning & result.flags & 3 /* Variable */) { + // expression inside parameter will lookup as normal variable scope when targeting es2015+ + var functionLocation = location; + if (compilerOptions.target && compilerOptions.target >= 2 /* ES2015 */ && ts.isParameter(lastLocation) && + functionLocation.body && result.valueDeclaration.pos >= functionLocation.body.pos && result.valueDeclaration.end <= functionLocation.body.end) { + useResult = false; + } + else if (result.flags & 1 /* FunctionScopedVariable */) { + // parameters are visible only inside function body, parameter list and return type + // technically for parameter list case here we might mix parameters and variables declared in function, + // however it is detected separately when checking initializers of parameters + // to make sure that they reference no variables declared after them. + useResult = + lastLocation.kind === 151 /* Parameter */ || + (lastLocation === location.type && + !!ts.findAncestor(result.valueDeclaration, ts.isParameter)); + } + } + } + else if (location.kind === 175 /* ConditionalType */) { + // A type parameter declared using 'infer T' in a conditional type is visible only in + // the true branch of the conditional type. + useResult = lastLocation === location.trueType; + } + if (useResult) { + break loop; + } + else { + result = undefined; + } + } + } + switch (location.kind) { + case 279 /* SourceFile */: + if (!ts.isExternalOrCommonJsModule(location)) + break; + isInExternalModule = true; + // falls through + case 244 /* ModuleDeclaration */: + var moduleExports = getSymbolOfNode(location).exports; + if (location.kind === 279 /* SourceFile */ || ts.isAmbientModule(location)) { + // It's an external module. First see if the module has an export default and if the local + // name of that export default matches. + if (result = moduleExports.get("default" /* Default */)) { + var localSymbol = ts.getLocalSymbolForExportDefault(result); + if (localSymbol && (result.flags & meaning) && localSymbol.escapedName === name) { + break loop; + } + result = undefined; + } + // Because of module/namespace merging, a module's exports are in scope, + // yet we never want to treat an export specifier as putting a member in scope. + // Therefore, if the name we find is purely an export specifier, it is not actually considered in scope. + // Two things to note about this: + // 1. We have to check this without calling getSymbol. The problem with calling getSymbol + // on an export specifier is that it might find the export specifier itself, and try to + // resolve it as an alias. This will cause the checker to consider the export specifier + // a circular alias reference when it might not be. + // 2. We check === SymbolFlags.Alias in order to check that the symbol is *purely* + // an alias. If we used &, we'd be throwing out symbols that have non alias aspects, + // which is not the desired behavior. + var moduleExport = moduleExports.get(name); + if (moduleExport && + moduleExport.flags === 2097152 /* Alias */ && + ts.getDeclarationOfKind(moduleExport, 257 /* ExportSpecifier */)) { + break; + } + } + // ES6 exports are also visible locally (except for 'default'), but commonjs exports are not (except typedefs) + if (name !== "default" /* Default */ && (result = lookup(moduleExports, name, meaning & 2623475 /* ModuleMember */))) { + if (ts.isSourceFile(location) && location.commonJsModuleIndicator && !result.declarations.some(ts.isJSDocTypeAlias)) { + result = undefined; + } + else { + break loop; + } + } + break; + case 243 /* EnumDeclaration */: + if (result = lookup(getSymbolOfNode(location).exports, name, meaning & 8 /* EnumMember */)) { + break loop; + } + break; + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + // TypeScript 1.0 spec (April 2014): 8.4.1 + // Initializer expressions for instance member variables are evaluated in the scope + // of the class constructor body but are not permitted to reference parameters or + // local variables of the constructor. This effectively means that entities from outer scopes + // by the same name as a constructor parameter or local variable are inaccessible + // in initializer expressions for instance member variables. + if (ts.isClassLike(location.parent) && !ts.hasModifier(location, 32 /* Static */)) { + var ctor = findConstructorDeclaration(location.parent); + if (ctor && ctor.locals) { + if (lookup(ctor.locals, name, meaning & 67220415 /* Value */)) { + // Remember the property node, it will be used later to report appropriate error + propertyWithInvalidInitializer = location; + } + } + } + break; + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 241 /* InterfaceDeclaration */: + // The below is used to lookup type parameters within a class or interface, as they are added to the class/interface locals + // These can never be latebound, so the symbol's raw members are sufficient. `getMembersOfNode` cannot be used, as it would + // trigger resolving late-bound names, which we may already be in the process of doing while we're here! + if (result = lookup(getSymbolOfNode(location).members || emptySymbols, name, meaning & 67897832 /* Type */)) { + if (!isTypeParameterSymbolDeclaredInContainer(result, location)) { + // ignore type parameters not declared in this container + result = undefined; + break; + } + if (lastLocation && ts.hasModifier(lastLocation, 32 /* Static */)) { + // TypeScript 1.0 spec (April 2014): 3.4.1 + // The scope of a type parameter extends over the entire declaration with which the type + // parameter list is associated, with the exception of static member declarations in classes. + error(errorLocation, ts.Diagnostics.Static_members_cannot_reference_class_type_parameters); + return undefined; + } + break loop; + } + if (location.kind === 209 /* ClassExpression */ && meaning & 32 /* Class */) { + var className = location.name; + if (className && name === className.escapedText) { + result = location.symbol; + break loop; + } + } + break; + case 211 /* ExpressionWithTypeArguments */: + // The type parameters of a class are not in scope in the base class expression. + if (lastLocation === location.expression && location.parent.token === 86 /* ExtendsKeyword */) { + var container = location.parent.parent; + if (ts.isClassLike(container) && (result = lookup(getSymbolOfNode(container).members, name, meaning & 67897832 /* Type */))) { + if (nameNotFoundMessage) { + error(errorLocation, ts.Diagnostics.Base_class_expressions_cannot_reference_class_type_parameters); + } + return undefined; + } + } + break; + // It is not legal to reference a class's own type parameters from a computed property name that + // belongs to the class. For example: + // + // function foo() { return '' } + // class C { // <-- Class's own type parameter T + // [foo()]() { } // <-- Reference to T from class's own computed property + // } + // + case 149 /* ComputedPropertyName */: + grandparent = location.parent.parent; + if (ts.isClassLike(grandparent) || grandparent.kind === 241 /* InterfaceDeclaration */) { + // A reference to this grandparent's type parameters would be an error + if (result = lookup(getSymbolOfNode(grandparent).members, name, meaning & 67897832 /* Type */)) { + error(errorLocation, ts.Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type); + return undefined; + } + } + break; + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 239 /* FunctionDeclaration */: + case 197 /* ArrowFunction */: + if (meaning & 3 /* Variable */ && name === "arguments") { + result = argumentsSymbol; + break loop; + } + break; + case 196 /* FunctionExpression */: + if (meaning & 3 /* Variable */ && name === "arguments") { + result = argumentsSymbol; + break loop; + } + if (meaning & 16 /* Function */) { + var functionName = location.name; + if (functionName && name === functionName.escapedText) { + result = location.symbol; + break loop; + } + } + break; + case 152 /* Decorator */: + // Decorators are resolved at the class declaration. Resolving at the parameter + // or member would result in looking up locals in the method. + // + // function y() {} + // class C { + // method(@y x, y) {} // <-- decorator y should be resolved at the class declaration, not the parameter. + // } + // + if (location.parent && location.parent.kind === 151 /* Parameter */) { + location = location.parent; + } + // + // function y() {} + // class C { + // @y method(x, y) {} // <-- decorator y should be resolved at the class declaration, not the method. + // } + // + if (location.parent && ts.isClassElement(location.parent)) { + location = location.parent; + } + break; + case 304 /* JSDocTypedefTag */: + case 297 /* JSDocCallbackTag */: + // js type aliases do not resolve names from their host, so skip past it + location = ts.getJSDocHost(location); + break; + } + if (isSelfReferenceLocation(location)) { + lastSelfReferenceLocation = location; + } + lastLocation = location; + location = location.parent; + } + // We just climbed up parents looking for the name, meaning that we started in a descendant node of `lastLocation`. + // If `result === lastSelfReferenceLocation.symbol`, that means that we are somewhere inside `lastSelfReferenceLocation` looking up a name, and resolving to `lastLocation` itself. + // That means that this is a self-reference of `lastLocation`, and shouldn't count this when considering whether `lastLocation` is used. + if (isUse && result && (!lastSelfReferenceLocation || result !== lastSelfReferenceLocation.symbol)) { + result.isReferenced |= meaning; + } + if (!result) { + if (lastLocation) { + ts.Debug.assert(lastLocation.kind === 279 /* SourceFile */); + if (lastLocation.commonJsModuleIndicator && name === "exports" && meaning & lastLocation.symbol.flags) { + return lastLocation.symbol; + } + } + if (!excludeGlobals) { + result = lookup(globals, name, meaning); + } + } + if (!result) { + if (originalLocation && ts.isInJSFile(originalLocation) && originalLocation.parent) { + if (ts.isRequireCall(originalLocation.parent, /*checkArgumentIsStringLiteralLike*/ false)) { + return requireSymbol; + } + } + } + if (!result) { + if (nameNotFoundMessage) { + if (!errorLocation || + !checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) && // TODO: GH#18217 + !checkAndReportErrorForExtendingInterface(errorLocation) && + !checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) && + !checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) && + !checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning)) { + var suggestion = void 0; + if (suggestedNameNotFoundMessage && suggestionCount < maximumSuggestionCount) { + suggestion = getSuggestedSymbolForNonexistentSymbol(originalLocation, name, meaning); + if (suggestion) { + var suggestionName = symbolToString(suggestion); + var diagnostic = error(errorLocation, suggestedNameNotFoundMessage, diagnosticName(nameArg), suggestionName); + if (suggestion.valueDeclaration) { + addRelatedInfo(diagnostic, ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestionName)); + } + } + } + if (!suggestion) { + error(errorLocation, nameNotFoundMessage, diagnosticName(nameArg)); + } + suggestionCount++; + } + } + return undefined; + } + // Perform extra checks only if error reporting was requested + if (nameNotFoundMessage) { + if (propertyWithInvalidInitializer) { + // We have a match, but the reference occurred within a property initializer and the identifier also binds + // to a local variable in the constructor where the code will be emitted. + var propertyName = propertyWithInvalidInitializer.name; + error(errorLocation, ts.Diagnostics.Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor, ts.declarationNameToString(propertyName), diagnosticName(nameArg)); + return undefined; + } + // Only check for block-scoped variable if we have an error location and are looking for the + // name with variable meaning + // For example, + // declare module foo { + // interface bar {} + // } + // const foo/*1*/: foo/*2*/.bar; + // The foo at /*1*/ and /*2*/ will share same symbol with two meanings: + // block-scoped variable and namespace module. However, only when we + // try to resolve name in /*1*/ which is used in variable position, + // we want to check for block-scoped + if (errorLocation && + (meaning & 2 /* BlockScopedVariable */ || + ((meaning & 32 /* Class */ || meaning & 384 /* Enum */) && (meaning & 67220415 /* Value */) === 67220415 /* Value */))) { + var exportOrLocalSymbol = getExportSymbolOfValueSymbolIfExported(result); + if (exportOrLocalSymbol.flags & 2 /* BlockScopedVariable */ || exportOrLocalSymbol.flags & 32 /* Class */ || exportOrLocalSymbol.flags & 384 /* Enum */) { + checkResolvedBlockScopedVariable(exportOrLocalSymbol, errorLocation); + } + } + // If we're in an external module, we can't reference value symbols created from UMD export declarations + if (result && isInExternalModule && (meaning & 67220415 /* Value */) === 67220415 /* Value */ && !(originalLocation.flags & 2097152 /* JSDoc */)) { + if (ts.some(result.declarations, function (d) { return ts.isNamespaceExportDeclaration(d) || ts.isSourceFile(d) && !!d.symbol.globalExports; })) { + error(errorLocation, ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead, ts.unescapeLeadingUnderscores(name)); // TODO: GH#18217 + } + } + } + return result; + } + function isSelfReferenceLocation(node) { + switch (node.kind) { + case 239 /* FunctionDeclaration */: + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + case 243 /* EnumDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 244 /* ModuleDeclaration */: // For `namespace N { N; }` + return true; + default: + return false; + } + } + function diagnosticName(nameArg) { + return ts.isString(nameArg) ? ts.unescapeLeadingUnderscores(nameArg) : ts.declarationNameToString(nameArg); + } + function isTypeParameterSymbolDeclaredInContainer(symbol, container) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + if (decl.kind === 150 /* TypeParameter */) { + var parent = ts.isJSDocTemplateTag(decl.parent) ? ts.getJSDocHost(decl.parent) : decl.parent; + if (parent === container) { + return !(ts.isJSDocTemplateTag(decl.parent) && ts.find(decl.parent.parent.tags, ts.isJSDocTypeAlias)); // TODO: GH#18217 + } + } + } + return false; + } + function checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) { + if (!ts.isIdentifier(errorLocation) || errorLocation.escapedText !== name || isTypeReferenceIdentifier(errorLocation) || isInTypeQuery(errorLocation)) { + return false; + } + var container = ts.getThisContainer(errorLocation, /*includeArrowFunctions*/ false); + var location = container; + while (location) { + if (ts.isClassLike(location.parent)) { + var classSymbol = getSymbolOfNode(location.parent); + if (!classSymbol) { + break; + } + // Check to see if a static member exists. + var constructorType = getTypeOfSymbol(classSymbol); + if (getPropertyOfType(constructorType, name)) { + error(errorLocation, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_static_member_1_0, diagnosticName(nameArg), symbolToString(classSymbol)); + return true; + } + // No static member is present. + // Check if we're in an instance method and look for a relevant instance member. + if (location === container && !ts.hasModifier(location, 32 /* Static */)) { + var instanceType = getDeclaredTypeOfSymbol(classSymbol).thisType; // TODO: GH#18217 + if (getPropertyOfType(instanceType, name)) { + error(errorLocation, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0, diagnosticName(nameArg)); + return true; + } + } + } + location = location.parent; + } + return false; + } + function checkAndReportErrorForExtendingInterface(errorLocation) { + var expression = getEntityNameForExtendingInterface(errorLocation); + if (expression && resolveEntityName(expression, 64 /* Interface */, /*ignoreErrors*/ true)) { + error(errorLocation, ts.Diagnostics.Cannot_extend_an_interface_0_Did_you_mean_implements, ts.getTextOfNode(expression)); + return true; + } + return false; + } + /** + * Climbs up parents to an ExpressionWithTypeArguments, and returns its expression, + * but returns undefined if that expression is not an EntityNameExpression. + */ + function getEntityNameForExtendingInterface(node) { + switch (node.kind) { + case 72 /* Identifier */: + case 189 /* PropertyAccessExpression */: + return node.parent ? getEntityNameForExtendingInterface(node.parent) : undefined; + case 211 /* ExpressionWithTypeArguments */: + if (ts.isEntityNameExpression(node.expression)) { + return node.expression; + } + // falls through + default: + return undefined; + } + } + function checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) { + var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJSFile(errorLocation) ? 67220415 /* Value */ : 0); + if (meaning === namespaceMeaning) { + var symbol = resolveSymbol(resolveName(errorLocation, name, 67897832 /* Type */ & ~namespaceMeaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + var parent = errorLocation.parent; + if (symbol) { + if (ts.isQualifiedName(parent)) { + ts.Debug.assert(parent.left === errorLocation, "Should only be resolving left side of qualified name as a namespace"); + var propName = parent.right.escapedText; + var propType = getPropertyOfType(getDeclaredTypeOfSymbol(symbol), propName); + if (propType) { + error(parent, ts.Diagnostics.Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_property_1_in_0_with_0_1, ts.unescapeLeadingUnderscores(name), ts.unescapeLeadingUnderscores(propName)); + return true; + } + } + error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here, ts.unescapeLeadingUnderscores(name)); + return true; + } + } + return false; + } + function checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) { + if (meaning & (67220415 /* Value */ & ~1024 /* NamespaceModule */)) { + if (name === "any" || name === "string" || name === "number" || name === "boolean" || name === "never") { + error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, ts.unescapeLeadingUnderscores(name)); + return true; + } + var symbol = resolveSymbol(resolveName(errorLocation, name, 67897832 /* Type */ & ~67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + if (symbol && !(symbol.flags & 1024 /* NamespaceModule */)) { + var message = (name === "Promise" || name === "Symbol") + ? ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later + : ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here; + error(errorLocation, message, ts.unescapeLeadingUnderscores(name)); + return true; + } + } + return false; + } + function checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) { + if (meaning & (67220415 /* Value */ & ~1024 /* NamespaceModule */ & ~67897832 /* Type */)) { + var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 /* NamespaceModule */ & ~67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + if (symbol) { + error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_value, ts.unescapeLeadingUnderscores(name)); + return true; + } + } + else if (meaning & (67897832 /* Type */ & ~1024 /* NamespaceModule */ & ~67220415 /* Value */)) { + var symbol = resolveSymbol(resolveName(errorLocation, name, (512 /* ValueModule */ | 1024 /* NamespaceModule */) & ~67897832 /* Type */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + if (symbol) { + error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_type, ts.unescapeLeadingUnderscores(name)); + return true; + } + } + return false; + } + function checkResolvedBlockScopedVariable(result, errorLocation) { + ts.Debug.assert(!!(result.flags & 2 /* BlockScopedVariable */ || result.flags & 32 /* Class */ || result.flags & 384 /* Enum */)); + // Block-scoped variables cannot be used before their definition + var declaration = ts.find(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) || ts.isClassLike(d) || (d.kind === 243 /* EnumDeclaration */) || ts.isInJSFile(d) && !!ts.getJSDocEnumTag(d); }); + if (declaration === undefined) + return ts.Debug.fail("Declaration to checkResolvedBlockScopedVariable is undefined"); + if (!(declaration.flags & 4194304 /* Ambient */) && !isBlockScopedNameDeclaredBeforeUse(declaration, errorLocation)) { + var diagnosticMessage = void 0; + var declarationName = ts.declarationNameToString(ts.getNameOfDeclaration(declaration)); + if (result.flags & 2 /* BlockScopedVariable */) { + diagnosticMessage = error(errorLocation, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, declarationName); + } + else if (result.flags & 32 /* Class */) { + diagnosticMessage = error(errorLocation, ts.Diagnostics.Class_0_used_before_its_declaration, declarationName); + } + else if (result.flags & 256 /* RegularEnum */) { + diagnosticMessage = error(errorLocation, ts.Diagnostics.Enum_0_used_before_its_declaration, declarationName); + } + else { + ts.Debug.assert(!!(result.flags & 128 /* ConstEnum */)); + if (compilerOptions.preserveConstEnums) { + diagnosticMessage = error(errorLocation, ts.Diagnostics.Class_0_used_before_its_declaration, declarationName); + } + } + if (diagnosticMessage) { + addRelatedInfo(diagnosticMessage, ts.createDiagnosticForNode(declaration, ts.Diagnostics._0_is_declared_here, declarationName)); + } + } + } + /* Starting from 'initial' node walk up the parent chain until 'stopAt' node is reached. + * If at any point current node is equal to 'parent' node - return true. + * Return false if 'stopAt' node is reached or isFunctionLike(current) === true. + */ + function isSameScopeDescendentOf(initial, parent, stopAt) { + return !!parent && !!ts.findAncestor(initial, function (n) { return n === stopAt || ts.isFunctionLike(n) ? "quit" : n === parent; }); + } + function getAnyImportSyntax(node) { + switch (node.kind) { + case 248 /* ImportEqualsDeclaration */: + return node; + case 250 /* ImportClause */: + return node.parent; + case 251 /* NamespaceImport */: + return node.parent.parent; + case 253 /* ImportSpecifier */: + return node.parent.parent.parent; + default: + return undefined; + } + } + function getDeclarationOfAliasSymbol(symbol) { + return ts.find(symbol.declarations, ts.isAliasSymbolDeclaration); + } + function getTargetOfImportEqualsDeclaration(node, dontResolveAlias) { + if (node.moduleReference.kind === 259 /* ExternalModuleReference */) { + return resolveExternalModuleSymbol(resolveExternalModuleName(node, ts.getExternalModuleImportEqualsDeclarationExpression(node))); + } + return getSymbolOfPartOfRightHandSideOfImportEquals(node.moduleReference, dontResolveAlias); + } + function resolveExportByName(moduleSymbol, name, dontResolveAlias) { + var exportValue = moduleSymbol.exports.get("export=" /* ExportEquals */); + return exportValue + ? getPropertyOfType(getTypeOfSymbol(exportValue), name) + : resolveSymbol(moduleSymbol.exports.get(name), dontResolveAlias); + } + function isSyntacticDefault(node) { + return ((ts.isExportAssignment(node) && !node.isExportEquals) || ts.hasModifier(node, 512 /* Default */) || ts.isExportSpecifier(node)); + } + function canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias) { + if (!allowSyntheticDefaultImports) { + return false; + } + // Declaration files (and ambient modules) + if (!file || file.isDeclarationFile) { + // Definitely cannot have a synthetic default if they have a syntactic default member specified + var defaultExportSymbol = resolveExportByName(moduleSymbol, "default" /* Default */, /*dontResolveAlias*/ true); // Dont resolve alias because we want the immediately exported symbol's declaration + if (defaultExportSymbol && ts.some(defaultExportSymbol.declarations, isSyntacticDefault)) { + return false; + } + // It _might_ still be incorrect to assume there is no __esModule marker on the import at runtime, even if there is no `default` member + // So we check a bit more, + if (resolveExportByName(moduleSymbol, ts.escapeLeadingUnderscores("__esModule"), dontResolveAlias)) { + // If there is an `__esModule` specified in the declaration (meaning someone explicitly added it or wrote it in their code), + // it definitely is a module and does not have a synthetic default + return false; + } + // There are _many_ declaration files not written with esmodules in mind that still get compiled into a format with __esModule set + // Meaning there may be no default at runtime - however to be on the permissive side, we allow access to a synthetic default member + // as there is no marker to indicate if the accompanying JS has `__esModule` or not, or is even native esm + return true; + } + // TypeScript files never have a synthetic default (as they are always emitted with an __esModule marker) _unless_ they contain an export= statement + if (!ts.isSourceFileJS(file)) { + return hasExportAssignmentSymbol(moduleSymbol); + } + // JS files have a synthetic default if they do not contain ES2015+ module syntax (export = is not valid in js) _and_ do not have an __esModule marker + return !file.externalModuleIndicator && !resolveExportByName(moduleSymbol, ts.escapeLeadingUnderscores("__esModule"), dontResolveAlias); + } + function getTargetOfImportClause(node, dontResolveAlias) { + var moduleSymbol = resolveExternalModuleName(node, node.parent.moduleSpecifier); + if (moduleSymbol) { + var exportDefaultSymbol = void 0; + if (ts.isShorthandAmbientModuleSymbol(moduleSymbol)) { + exportDefaultSymbol = moduleSymbol; + } + else { + exportDefaultSymbol = resolveExportByName(moduleSymbol, "default" /* Default */, dontResolveAlias); + } + var file = ts.find(moduleSymbol.declarations, ts.isSourceFile); + var hasSyntheticDefault = canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias); + if (!exportDefaultSymbol && !hasSyntheticDefault) { + error(node.name, ts.Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol)); + } + else if (hasSyntheticDefault) { + // per emit behavior, a synthetic default overrides a "real" .default member if `__esModule` is not present + return resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias); + } + return exportDefaultSymbol; + } + } + function getTargetOfNamespaceImport(node, dontResolveAlias) { + var moduleSpecifier = node.parent.parent.moduleSpecifier; + return resolveESModuleSymbol(resolveExternalModuleName(node, moduleSpecifier), moduleSpecifier, dontResolveAlias); + } + // This function creates a synthetic symbol that combines the value side of one symbol with the + // type/namespace side of another symbol. Consider this example: + // + // declare module graphics { + // interface Point { + // x: number; + // y: number; + // } + // } + // declare var graphics: { + // Point: new (x: number, y: number) => graphics.Point; + // } + // declare module "graphics" { + // export = graphics; + // } + // + // An 'import { Point } from "graphics"' needs to create a symbol that combines the value side 'Point' + // property with the type/namespace side interface 'Point'. + function combineValueAndTypeSymbols(valueSymbol, typeSymbol) { + if (valueSymbol === unknownSymbol && typeSymbol === unknownSymbol) { + return unknownSymbol; + } + if (valueSymbol.flags & (67897832 /* Type */ | 1920 /* Namespace */)) { + return valueSymbol; + } + var result = createSymbol(valueSymbol.flags | typeSymbol.flags, valueSymbol.escapedName); + result.declarations = ts.deduplicate(ts.concatenate(valueSymbol.declarations, typeSymbol.declarations), ts.equateValues); + result.parent = valueSymbol.parent || typeSymbol.parent; + if (valueSymbol.valueDeclaration) + result.valueDeclaration = valueSymbol.valueDeclaration; + if (typeSymbol.members) + result.members = typeSymbol.members; + if (valueSymbol.exports) + result.exports = valueSymbol.exports; + return result; + } + function getExportOfModule(symbol, name, dontResolveAlias) { + if (symbol.flags & 1536 /* Module */) { + return resolveSymbol(getExportsOfSymbol(symbol).get(name), dontResolveAlias); + } + } + function getPropertyOfVariable(symbol, name) { + if (symbol.flags & 3 /* Variable */) { + var typeAnnotation = symbol.valueDeclaration.type; + if (typeAnnotation) { + return resolveSymbol(getPropertyOfType(getTypeFromTypeNode(typeAnnotation), name)); + } + } + } + function getExternalModuleMember(node, specifier, dontResolveAlias) { + if (dontResolveAlias === void 0) { dontResolveAlias = false; } + var moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier); // TODO: GH#18217 + var targetSymbol = resolveESModuleSymbol(moduleSymbol, node.moduleSpecifier, dontResolveAlias); + if (targetSymbol) { + var name = specifier.propertyName || specifier.name; + if (name.escapedText) { + if (ts.isShorthandAmbientModuleSymbol(moduleSymbol)) { + return moduleSymbol; + } + var symbolFromVariable = void 0; + // First check if module was specified with "export=". If so, get the member from the resolved type + if (moduleSymbol && moduleSymbol.exports && moduleSymbol.exports.get("export=" /* ExportEquals */)) { + symbolFromVariable = getPropertyOfType(getTypeOfSymbol(targetSymbol), name.escapedText); + } + else { + symbolFromVariable = getPropertyOfVariable(targetSymbol, name.escapedText); + } + // if symbolFromVariable is export - get its final target + symbolFromVariable = resolveSymbol(symbolFromVariable, dontResolveAlias); + var symbolFromModule = getExportOfModule(targetSymbol, name.escapedText, dontResolveAlias); + // If the export member we're looking for is default, and there is no real default but allowSyntheticDefaultImports is on, return the entire module as the default + if (!symbolFromModule && allowSyntheticDefaultImports && name.escapedText === "default" /* Default */) { + symbolFromModule = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias); + } + var symbol = symbolFromModule && symbolFromVariable && symbolFromModule !== symbolFromVariable ? + combineValueAndTypeSymbols(symbolFromVariable, symbolFromModule) : + symbolFromModule || symbolFromVariable; + if (!symbol) { + var moduleName = getFullyQualifiedName(moduleSymbol, node); + var declarationName = ts.declarationNameToString(name); + var suggestion = getSuggestedSymbolForNonexistentModule(name, targetSymbol); + if (suggestion !== undefined) { + var suggestionName = symbolToString(suggestion); + var diagnostic = error(name, ts.Diagnostics.Module_0_has_no_exported_member_1_Did_you_mean_2, moduleName, declarationName, suggestionName); + if (suggestion.valueDeclaration) { + addRelatedInfo(diagnostic, ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestionName)); + } + } + else { + error(name, ts.Diagnostics.Module_0_has_no_exported_member_1, moduleName, declarationName); + } + } + return symbol; + } + } + } + function getTargetOfImportSpecifier(node, dontResolveAlias) { + return getExternalModuleMember(node.parent.parent.parent, node, dontResolveAlias); + } + function getTargetOfNamespaceExportDeclaration(node, dontResolveAlias) { + return resolveExternalModuleSymbol(node.parent.symbol, dontResolveAlias); + } + function getTargetOfExportSpecifier(node, meaning, dontResolveAlias) { + return node.parent.parent.moduleSpecifier ? + getExternalModuleMember(node.parent.parent, node, dontResolveAlias) : + resolveEntityName(node.propertyName || node.name, meaning, /*ignoreErrors*/ false, dontResolveAlias); + } + function getTargetOfExportAssignment(node, dontResolveAlias) { + var expression = (ts.isExportAssignment(node) ? node.expression : node.right); + if (ts.isClassExpression(expression)) { + return checkExpression(expression).symbol; + } + var aliasLike = resolveEntityName(expression, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ true, dontResolveAlias); + if (aliasLike) { + return aliasLike; + } + checkExpression(expression); + return getNodeLinks(expression).resolvedSymbol; + } + function getTargetOfAliasDeclaration(node, dontRecursivelyResolve) { + if (dontRecursivelyResolve === void 0) { dontRecursivelyResolve = false; } + switch (node.kind) { + case 248 /* ImportEqualsDeclaration */: + return getTargetOfImportEqualsDeclaration(node, dontRecursivelyResolve); + case 250 /* ImportClause */: + return getTargetOfImportClause(node, dontRecursivelyResolve); + case 251 /* NamespaceImport */: + return getTargetOfNamespaceImport(node, dontRecursivelyResolve); + case 253 /* ImportSpecifier */: + return getTargetOfImportSpecifier(node, dontRecursivelyResolve); + case 257 /* ExportSpecifier */: + return getTargetOfExportSpecifier(node, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */, dontRecursivelyResolve); + case 254 /* ExportAssignment */: + case 204 /* BinaryExpression */: + return getTargetOfExportAssignment(node, dontRecursivelyResolve); + case 247 /* NamespaceExportDeclaration */: + return getTargetOfNamespaceExportDeclaration(node, dontRecursivelyResolve); + default: + return ts.Debug.fail(); + } + } + /** + * Indicates that a symbol is an alias that does not merge with a local declaration. + * OR Is a JSContainer which may merge an alias with a local declaration + */ + function isNonLocalAlias(symbol, excludes) { + if (excludes === void 0) { excludes = 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */; } + if (!symbol) + return false; + return (symbol.flags & (2097152 /* Alias */ | excludes)) === 2097152 /* Alias */ || !!(symbol.flags & 2097152 /* Alias */ && symbol.flags & 67108864 /* Assignment */); + } + function resolveSymbol(symbol, dontResolveAlias) { + return !dontResolveAlias && isNonLocalAlias(symbol) ? resolveAlias(symbol) : symbol; + } + function resolveAlias(symbol) { + ts.Debug.assert((symbol.flags & 2097152 /* Alias */) !== 0, "Should only get Alias here."); + var links = getSymbolLinks(symbol); + if (!links.target) { + links.target = resolvingSymbol; + var node = getDeclarationOfAliasSymbol(symbol); + if (!node) + return ts.Debug.fail(); + var target = getTargetOfAliasDeclaration(node); + if (links.target === resolvingSymbol) { + links.target = target || unknownSymbol; + } + else { + error(node, ts.Diagnostics.Circular_definition_of_import_alias_0, symbolToString(symbol)); + } + } + else if (links.target === resolvingSymbol) { + links.target = unknownSymbol; + } + return links.target; + } + function markExportAsReferenced(node) { + var symbol = getSymbolOfNode(node); + var target = resolveAlias(symbol); + if (target) { + var markAlias = target === unknownSymbol || + ((target.flags & 67220415 /* Value */) && !isConstEnumOrConstEnumOnlyModule(target)); + if (markAlias) { + markAliasSymbolAsReferenced(symbol); + } + } + } + // When an alias symbol is referenced, we need to mark the entity it references as referenced and in turn repeat that until + // we reach a non-alias or an exported entity (which is always considered referenced). We do this by checking the target of + // the alias as an expression (which recursively takes us back here if the target references another alias). + function markAliasSymbolAsReferenced(symbol) { + var links = getSymbolLinks(symbol); + if (!links.referenced) { + links.referenced = true; + var node = getDeclarationOfAliasSymbol(symbol); + if (!node) + return ts.Debug.fail(); + if (node.kind === 254 /* ExportAssignment */) { + // export default + checkExpressionCached(node.expression); + } + else if (node.kind === 257 /* ExportSpecifier */) { + // export { } or export { as foo } + checkExpressionCached(node.propertyName || node.name); + } + else if (ts.isInternalModuleImportEqualsDeclaration(node)) { + // import foo = + checkExpressionCached(node.moduleReference); + } + } + } + // This function is only for imports with entity names + function getSymbolOfPartOfRightHandSideOfImportEquals(entityName, dontResolveAlias) { + // There are three things we might try to look for. In the following examples, + // the search term is enclosed in |...|: + // + // import a = |b|; // Namespace + // import a = |b.c|; // Value, type, namespace + // import a = |b.c|.d; // Namespace + if (entityName.kind === 72 /* Identifier */ && ts.isRightSideOfQualifiedNameOrPropertyAccess(entityName)) { + entityName = entityName.parent; + } + // Check for case 1 and 3 in the above example + if (entityName.kind === 72 /* Identifier */ || entityName.parent.kind === 148 /* QualifiedName */) { + return resolveEntityName(entityName, 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); + } + else { + // Case 2 in above example + // entityName.kind could be a QualifiedName or a Missing identifier + ts.Debug.assert(entityName.parent.kind === 248 /* ImportEqualsDeclaration */); + return resolveEntityName(entityName, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); + } + } + function getFullyQualifiedName(symbol, containingLocation) { + return symbol.parent ? getFullyQualifiedName(symbol.parent, containingLocation) + "." + symbolToString(symbol) : symbolToString(symbol, containingLocation, /*meaning*/ undefined, 16 /* DoNotIncludeSymbolChain */ | 4 /* AllowAnyNodeKind */); + } + /** + * Resolves a qualified name and any involved aliases. + */ + function resolveEntityName(name, meaning, ignoreErrors, dontResolveAlias, location) { + if (ts.nodeIsMissing(name)) { + return undefined; + } + var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJSFile(name) ? meaning & 67220415 /* Value */ : 0); + var symbol; + if (name.kind === 72 /* Identifier */) { + var message = meaning === namespaceMeaning ? ts.Diagnostics.Cannot_find_namespace_0 : getCannotFindNameDiagnosticForName(getFirstIdentifier(name).escapedText); + var symbolFromJSPrototype = ts.isInJSFile(name) ? resolveEntityNameFromAssignmentDeclaration(name, meaning) : undefined; + symbol = resolveName(location || name, name.escapedText, meaning, ignoreErrors || symbolFromJSPrototype ? undefined : message, name, /*isUse*/ true); + if (!symbol) { + return symbolFromJSPrototype; + } + } + else if (name.kind === 148 /* QualifiedName */ || name.kind === 189 /* PropertyAccessExpression */) { + var left = name.kind === 148 /* QualifiedName */ ? name.left : name.expression; + var right = name.kind === 148 /* QualifiedName */ ? name.right : name.name; + var namespace = resolveEntityName(left, namespaceMeaning, ignoreErrors, /*dontResolveAlias*/ false, location); + if (!namespace || ts.nodeIsMissing(right)) { + return undefined; + } + else if (namespace === unknownSymbol) { + return namespace; + } + if (ts.isInJSFile(name)) { + if (namespace.valueDeclaration && + ts.isVariableDeclaration(namespace.valueDeclaration) && + namespace.valueDeclaration.initializer && + isCommonJsRequire(namespace.valueDeclaration.initializer)) { + var moduleName = namespace.valueDeclaration.initializer.arguments[0]; + var moduleSym = resolveExternalModuleName(moduleName, moduleName); + if (moduleSym) { + var resolvedModuleSymbol = resolveExternalModuleSymbol(moduleSym); + if (resolvedModuleSymbol) { + namespace = resolvedModuleSymbol; + } + } + } + } + symbol = getSymbol(getExportsOfSymbol(namespace), right.escapedText, meaning); + if (!symbol) { + if (!ignoreErrors) { + error(right, ts.Diagnostics.Namespace_0_has_no_exported_member_1, getFullyQualifiedName(namespace), ts.declarationNameToString(right)); + } + return undefined; + } + } + else { + throw ts.Debug.assertNever(name, "Unknown entity name kind."); + } + ts.Debug.assert((ts.getCheckFlags(symbol) & 1 /* Instantiated */) === 0, "Should never get an instantiated symbol here."); + return (symbol.flags & meaning) || dontResolveAlias ? symbol : resolveAlias(symbol); + } + /** + * 1. For prototype-property methods like `A.prototype.m = function () ...`, try to resolve names in the scope of `A` too. + * Note that prototype-property assignment to locations outside the current file (eg globals) doesn't work, so + * name resolution won't work either. + * 2. For property assignments like `{ x: function f () { } }`, try to resolve names in the scope of `f` too. + */ + function resolveEntityNameFromAssignmentDeclaration(name, meaning) { + if (isJSDocTypeReference(name.parent)) { + var secondaryLocation = getAssignmentDeclarationLocation(name.parent); + if (secondaryLocation) { + return resolveName(secondaryLocation, name.escapedText, meaning, /*nameNotFoundMessage*/ undefined, name, /*isUse*/ true); + } + } + } + function getAssignmentDeclarationLocation(node) { + var typeAlias = ts.findAncestor(node, function (node) { return !(ts.isJSDocNode(node) || node.flags & 2097152 /* JSDoc */) ? "quit" : ts.isJSDocTypeAlias(node); }); + if (typeAlias) { + return; + } + var host = ts.getJSDocHost(node); + if (ts.isExpressionStatement(host) && + ts.isBinaryExpression(host.expression) && + ts.getAssignmentDeclarationKind(host.expression) === 3 /* PrototypeProperty */) { + // X.prototype.m = /** @param {K} p */ function () { } <-- look for K on X's declaration + var symbol = getSymbolOfNode(host.expression.left); + if (symbol) { + return getDeclarationOfJSPrototypeContainer(symbol); + } + } + if ((ts.isObjectLiteralMethod(host) || ts.isPropertyAssignment(host)) && + ts.isBinaryExpression(host.parent.parent) && + ts.getAssignmentDeclarationKind(host.parent.parent) === 6 /* Prototype */) { + // X.prototype = { /** @param {K} p */m() { } } <-- look for K on X's declaration + var symbol = getSymbolOfNode(host.parent.parent.left); + if (symbol) { + return getDeclarationOfJSPrototypeContainer(symbol); + } + } + var sig = ts.getHostSignatureFromJSDocHost(host); + if (sig) { + var symbol = getSymbolOfNode(sig); + return symbol && symbol.valueDeclaration; + } + } + function getDeclarationOfJSPrototypeContainer(symbol) { + var decl = symbol.parent.valueDeclaration; + if (!decl) { + return undefined; + } + var initializer = ts.isAssignmentDeclaration(decl) ? ts.getAssignedExpandoInitializer(decl) : + ts.hasOnlyExpressionInitializer(decl) ? ts.getDeclaredExpandoInitializer(decl) : + undefined; + return initializer || decl; + } + function resolveExternalModuleName(location, moduleReferenceExpression, ignoreErrors) { + return resolveExternalModuleNameWorker(location, moduleReferenceExpression, ignoreErrors ? undefined : ts.Diagnostics.Cannot_find_module_0); + } + function resolveExternalModuleNameWorker(location, moduleReferenceExpression, moduleNotFoundError, isForAugmentation) { + if (isForAugmentation === void 0) { isForAugmentation = false; } + return ts.isStringLiteralLike(moduleReferenceExpression) + ? resolveExternalModule(location, moduleReferenceExpression.text, moduleNotFoundError, moduleReferenceExpression, isForAugmentation) + : undefined; + } + function resolveExternalModule(location, moduleReference, moduleNotFoundError, errorNode, isForAugmentation) { + if (isForAugmentation === void 0) { isForAugmentation = false; } + if (moduleReference === undefined) { + return; + } + if (ts.startsWith(moduleReference, "@types/")) { + var diag = ts.Diagnostics.Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1; + var withoutAtTypePrefix = ts.removePrefix(moduleReference, "@types/"); + error(errorNode, diag, withoutAtTypePrefix, moduleReference); + } + var ambientModule = tryFindAmbientModule(moduleReference, /*withAugmentations*/ true); + if (ambientModule) { + return ambientModule; + } + var currentSourceFile = ts.getSourceFileOfNode(location); + var resolvedModule = ts.getResolvedModule(currentSourceFile, moduleReference); // TODO: GH#18217 + var resolutionDiagnostic = resolvedModule && ts.getResolutionDiagnostic(compilerOptions, resolvedModule); + var sourceFile = resolvedModule && !resolutionDiagnostic && host.getSourceFile(resolvedModule.resolvedFileName); + if (sourceFile) { + if (sourceFile.symbol) { + if (resolvedModule.isExternalLibraryImport && !ts.resolutionExtensionIsTSOrJson(resolvedModule.extension)) { + errorOnImplicitAnyModule(/*isError*/ false, errorNode, resolvedModule, moduleReference); + } + // merged symbol is module declaration symbol combined with all augmentations + return getMergedSymbol(sourceFile.symbol); + } + if (moduleNotFoundError) { + // report errors only if it was requested + error(errorNode, ts.Diagnostics.File_0_is_not_a_module, sourceFile.fileName); + } + return undefined; + } + if (patternAmbientModules) { + var pattern = ts.findBestPatternMatch(patternAmbientModules, function (_) { return _.pattern; }, moduleReference); + if (pattern) { + return getMergedSymbol(pattern.symbol); + } + } + // May be an untyped module. If so, ignore resolutionDiagnostic. + if (resolvedModule && !ts.resolutionExtensionIsTSOrJson(resolvedModule.extension) && resolutionDiagnostic === undefined || resolutionDiagnostic === ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type) { + if (isForAugmentation) { + var diag = ts.Diagnostics.Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented; + error(errorNode, diag, moduleReference, resolvedModule.resolvedFileName); + } + else { + errorOnImplicitAnyModule(/*isError*/ noImplicitAny && !!moduleNotFoundError, errorNode, resolvedModule, moduleReference); + } + // Failed imports and untyped modules are both treated in an untyped manner; only difference is whether we give a diagnostic first. + return undefined; + } + if (moduleNotFoundError) { + // For relative paths, see if this was possibly a projectReference redirect + if (ts.pathIsRelative(moduleReference)) { + var sourceFile_1 = ts.getSourceFileOfNode(location); + var redirects = sourceFile_1.redirectedReferences; + if (redirects) { + var normalizedTargetPath = ts.getNormalizedAbsolutePath(moduleReference, ts.getDirectoryPath(sourceFile_1.fileName)); + for (var _i = 0, _a = [".ts" /* Ts */, ".tsx" /* Tsx */]; _i < _a.length; _i++) { + var ext = _a[_i]; + var probePath = normalizedTargetPath + ext; + if (redirects.indexOf(probePath) >= 0) { + error(errorNode, ts.Diagnostics.Output_file_0_has_not_been_built_from_source_file_1, moduleReference, probePath); + return undefined; + } + } + } + } + if (resolutionDiagnostic) { + error(errorNode, resolutionDiagnostic, moduleReference, resolvedModule.resolvedFileName); + } + else { + var tsExtension = ts.tryExtractTSExtension(moduleReference); + if (tsExtension) { + var diag = ts.Diagnostics.An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead; + error(errorNode, diag, tsExtension, ts.removeExtension(moduleReference, tsExtension)); + } + else if (!compilerOptions.resolveJsonModule && + ts.fileExtensionIs(moduleReference, ".json" /* Json */) && + ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs && + ts.hasJsonModuleEmitEnabled(compilerOptions)) { + error(errorNode, ts.Diagnostics.Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension, moduleReference); + } + else { + error(errorNode, moduleNotFoundError, moduleReference); + } + } + } + return undefined; + } + function errorOnImplicitAnyModule(isError, errorNode, _a, moduleReference) { + var packageId = _a.packageId, resolvedFileName = _a.resolvedFileName; + var errorInfo = !ts.isExternalModuleNameRelative(moduleReference) && packageId + ? typesPackageExists(packageId.name) + ? ts.chainDiagnosticMessages( + /*details*/ undefined, ts.Diagnostics.If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1, packageId.name, ts.mangleScopedPackageName(packageId.name)) + : ts.chainDiagnosticMessages( + /*details*/ undefined, ts.Diagnostics.Try_npm_install_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, moduleReference, ts.mangleScopedPackageName(packageId.name)) + : undefined; + errorOrSuggestion(isError, errorNode, ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type, moduleReference, resolvedFileName)); + } + function typesPackageExists(packageName) { + return getPackagesSet().has(ts.getTypesPackageName(packageName)); + } + function resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) { + if (moduleSymbol) { + var exportEquals = resolveSymbol(moduleSymbol.exports.get("export=" /* ExportEquals */), dontResolveAlias); + var exported = getCommonJsExportEquals(exportEquals, moduleSymbol); + return getMergedSymbol(exported) || moduleSymbol; + } + return undefined; + } + function getCommonJsExportEquals(exported, moduleSymbol) { + if (!exported || exported === unknownSymbol || exported === moduleSymbol || moduleSymbol.exports.size === 1 || exported.flags & 2097152 /* Alias */) { + return exported; + } + var merged = cloneSymbol(exported); + if (merged.exports === undefined) { + merged.flags = merged.flags | 512 /* ValueModule */; + merged.exports = ts.createSymbolTable(); + } + moduleSymbol.exports.forEach(function (s, name) { + if (name === "export=" /* ExportEquals */) + return; + merged.exports.set(name, merged.exports.has(name) ? mergeSymbol(merged.exports.get(name), s) : s); + }); + return merged; + } + // An external module with an 'export =' declaration may be referenced as an ES6 module provided the 'export =' + // references a symbol that is at least declared as a module or a variable. The target of the 'export =' may + // combine other declarations with the module or variable (e.g. a class/module, function/module, interface/variable). + function resolveESModuleSymbol(moduleSymbol, referencingLocation, dontResolveAlias) { + var symbol = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias); + if (!dontResolveAlias && symbol) { + if (!(symbol.flags & (1536 /* Module */ | 3 /* Variable */)) && !ts.getDeclarationOfKind(symbol, 279 /* SourceFile */)) { + error(referencingLocation, ts.Diagnostics.Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct, symbolToString(moduleSymbol)); + return symbol; + } + if (compilerOptions.esModuleInterop) { + var referenceParent = referencingLocation.parent; + if ((ts.isImportDeclaration(referenceParent) && ts.getNamespaceDeclarationNode(referenceParent)) || + ts.isImportCall(referenceParent)) { + var type = getTypeOfSymbol(symbol); + var sigs = getSignaturesOfStructuredType(type, 0 /* Call */); + if (!sigs || !sigs.length) { + sigs = getSignaturesOfStructuredType(type, 1 /* Construct */); + } + if (sigs && sigs.length) { + var moduleType = getTypeWithSyntheticDefaultImportType(type, symbol, moduleSymbol); + // Create a new symbol which has the module's type less the call and construct signatures + var result = createSymbol(symbol.flags, symbol.escapedName); + result.declarations = symbol.declarations ? symbol.declarations.slice() : []; + result.parent = symbol.parent; + result.target = symbol; + result.originatingImport = referenceParent; + if (symbol.valueDeclaration) + result.valueDeclaration = symbol.valueDeclaration; + if (symbol.constEnumOnlyModule) + result.constEnumOnlyModule = true; + if (symbol.members) + result.members = ts.cloneMap(symbol.members); + if (symbol.exports) + result.exports = ts.cloneMap(symbol.exports); + var resolvedModuleType = resolveStructuredTypeMembers(moduleType); // Should already be resolved from the signature checks above + result.type = createAnonymousType(result, resolvedModuleType.members, ts.emptyArray, ts.emptyArray, resolvedModuleType.stringIndexInfo, resolvedModuleType.numberIndexInfo); + return result; + } + } + } + } + return symbol; + } + function hasExportAssignmentSymbol(moduleSymbol) { + return moduleSymbol.exports.get("export=" /* ExportEquals */) !== undefined; + } + function getExportsOfModuleAsArray(moduleSymbol) { + return symbolsToArray(getExportsOfModule(moduleSymbol)); + } + function getExportsAndPropertiesOfModule(moduleSymbol) { + var exports = getExportsOfModuleAsArray(moduleSymbol); + var exportEquals = resolveExternalModuleSymbol(moduleSymbol); + if (exportEquals !== moduleSymbol) { + ts.addRange(exports, getPropertiesOfType(getTypeOfSymbol(exportEquals))); + } + return exports; + } + function tryGetMemberInModuleExports(memberName, moduleSymbol) { + var symbolTable = getExportsOfModule(moduleSymbol); + if (symbolTable) { + return symbolTable.get(memberName); + } + } + function tryGetMemberInModuleExportsAndProperties(memberName, moduleSymbol) { + var symbol = tryGetMemberInModuleExports(memberName, moduleSymbol); + if (symbol) { + return symbol; + } + var exportEquals = resolveExternalModuleSymbol(moduleSymbol); + if (exportEquals === moduleSymbol) { + return undefined; + } + var type = getTypeOfSymbol(exportEquals); + return type.flags & 131068 /* Primitive */ ? undefined : getPropertyOfType(type, memberName); + } + function getExportsOfSymbol(symbol) { + return symbol.flags & 32 /* Class */ ? getResolvedMembersOrExportsOfSymbol(symbol, "resolvedExports" /* resolvedExports */) : + symbol.flags & 1536 /* Module */ ? getExportsOfModule(symbol) : + symbol.exports || emptySymbols; + } + function getExportsOfModule(moduleSymbol) { + var links = getSymbolLinks(moduleSymbol); + return links.resolvedExports || (links.resolvedExports = getExportsOfModuleWorker(moduleSymbol)); + } + /** + * Extends one symbol table with another while collecting information on name collisions for error message generation into the `lookupTable` argument + * Not passing `lookupTable` and `exportNode` disables this collection, and just extends the tables + */ + function extendExportSymbols(target, source, lookupTable, exportNode) { + if (!source) + return; + source.forEach(function (sourceSymbol, id) { + if (id === "default" /* Default */) + return; + var targetSymbol = target.get(id); + if (!targetSymbol) { + target.set(id, sourceSymbol); + if (lookupTable && exportNode) { + lookupTable.set(id, { + specifierText: ts.getTextOfNode(exportNode.moduleSpecifier) + }); + } + } + else if (lookupTable && exportNode && targetSymbol && resolveSymbol(targetSymbol) !== resolveSymbol(sourceSymbol)) { + var collisionTracker = lookupTable.get(id); + if (!collisionTracker.exportsWithDuplicate) { + collisionTracker.exportsWithDuplicate = [exportNode]; + } + else { + collisionTracker.exportsWithDuplicate.push(exportNode); + } + } + }); + } + function getExportsOfModuleWorker(moduleSymbol) { + var visitedSymbols = []; + // A module defined by an 'export=' consists of one export that needs to be resolved + moduleSymbol = resolveExternalModuleSymbol(moduleSymbol); + return visit(moduleSymbol) || emptySymbols; + // The ES6 spec permits export * declarations in a module to circularly reference the module itself. For example, + // module 'a' can 'export * from "b"' and 'b' can 'export * from "a"' without error. + function visit(symbol) { + if (!(symbol && symbol.exports && ts.pushIfUnique(visitedSymbols, symbol))) { + return; + } + var symbols = ts.cloneMap(symbol.exports); + // All export * declarations are collected in an __export symbol by the binder + var exportStars = symbol.exports.get("__export" /* ExportStar */); + if (exportStars) { + var nestedSymbols = ts.createSymbolTable(); + var lookupTable_1 = ts.createMap(); + for (var _i = 0, _a = exportStars.declarations; _i < _a.length; _i++) { + var node = _a[_i]; + var resolvedModule = resolveExternalModuleName(node, node.moduleSpecifier); + var exportedSymbols = visit(resolvedModule); + extendExportSymbols(nestedSymbols, exportedSymbols, lookupTable_1, node); + } + lookupTable_1.forEach(function (_a, id) { + var exportsWithDuplicate = _a.exportsWithDuplicate; + // It's not an error if the file with multiple `export *`s with duplicate names exports a member with that name itself + if (id === "export=" || !(exportsWithDuplicate && exportsWithDuplicate.length) || symbols.has(id)) { + return; + } + for (var _i = 0, exportsWithDuplicate_1 = exportsWithDuplicate; _i < exportsWithDuplicate_1.length; _i++) { + var node = exportsWithDuplicate_1[_i]; + diagnostics.add(ts.createDiagnosticForNode(node, ts.Diagnostics.Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambiguity, lookupTable_1.get(id).specifierText, ts.unescapeLeadingUnderscores(id))); + } + }); + extendExportSymbols(symbols, nestedSymbols); + } + return symbols; + } + } + function getMergedSymbol(symbol) { + var merged; + return symbol && symbol.mergeId && (merged = mergedSymbols[symbol.mergeId]) ? merged : symbol; + } + function getSymbolOfNode(node) { + return getMergedSymbol(node.symbol && getLateBoundSymbol(node.symbol)); + } + function getParentOfSymbol(symbol) { + return getMergedSymbol(symbol.parent && getLateBoundSymbol(symbol.parent)); + } + function getAlternativeContainingModules(symbol, enclosingDeclaration) { + var containingFile = ts.getSourceFileOfNode(enclosingDeclaration); + var id = "" + getNodeId(containingFile); + var links = getSymbolLinks(symbol); + var results; + if (links.extendedContainersByFile && (results = links.extendedContainersByFile.get(id))) { + return results; + } + if (containingFile && containingFile.imports) { + // Try to make an import using an import already in the enclosing file, if possible + for (var _i = 0, _a = containingFile.imports; _i < _a.length; _i++) { + var importRef = _a[_i]; + if (ts.nodeIsSynthesized(importRef)) + continue; // Synthetic names can't be resolved by `resolveExternalModuleName` - they'll cause a debug assert if they error + var resolvedModule = resolveExternalModuleName(enclosingDeclaration, importRef, /*ignoreErrors*/ true); + if (!resolvedModule) + continue; + var ref = getAliasForSymbolInContainer(resolvedModule, symbol); + if (!ref) + continue; + results = ts.append(results, resolvedModule); + } + if (ts.length(results)) { + (links.extendedContainersByFile || (links.extendedContainersByFile = ts.createMap())).set(id, results); + return results; + } + } + if (links.extendedContainers) { + return links.extendedContainers; + } + // No results from files already being imported by this file - expand search (expensive, but not location-specific, so cached) + var otherFiles = host.getSourceFiles(); + for (var _b = 0, otherFiles_1 = otherFiles; _b < otherFiles_1.length; _b++) { + var file = otherFiles_1[_b]; + if (!ts.isExternalModule(file)) + continue; + var sym = getSymbolOfNode(file); + var ref = getAliasForSymbolInContainer(sym, symbol); + if (!ref) + continue; + results = ts.append(results, sym); + } + return links.extendedContainers = results || ts.emptyArray; + } + /** + * Attempts to find the symbol corresponding to the container a symbol is in - usually this + * is just its' `.parent`, but for locals, this value is `undefined` + */ + function getContainersOfSymbol(symbol, enclosingDeclaration) { + var container = getParentOfSymbol(symbol); + if (container) { + var additionalContainers = ts.mapDefined(container.declarations, fileSymbolIfFileSymbolExportEqualsContainer); + var reexportContainers = enclosingDeclaration && getAlternativeContainingModules(symbol, enclosingDeclaration); + if (enclosingDeclaration && getAccessibleSymbolChain(container, enclosingDeclaration, 1920 /* Namespace */, /*externalOnly*/ false)) { + return ts.concatenate(ts.concatenate([container], additionalContainers), reexportContainers); // This order expresses a preference for the real container if it is in scope + } + var res = ts.append(additionalContainers, container); + return ts.concatenate(res, reexportContainers); + } + var candidates = ts.mapDefined(symbol.declarations, function (d) { return !ts.isAmbientModule(d) && d.parent && hasNonGlobalAugmentationExternalModuleSymbol(d.parent) ? getSymbolOfNode(d.parent) : undefined; }); + if (!ts.length(candidates)) { + return undefined; + } + return ts.mapDefined(candidates, function (candidate) { return getAliasForSymbolInContainer(candidate, symbol) ? candidate : undefined; }); + function fileSymbolIfFileSymbolExportEqualsContainer(d) { + var fileSymbol = getExternalModuleContainer(d); + var exported = fileSymbol && fileSymbol.exports && fileSymbol.exports.get("export=" /* ExportEquals */); + return resolveSymbol(exported) === resolveSymbol(container) ? fileSymbol : undefined; + } + } + function getAliasForSymbolInContainer(container, symbol) { + if (container === getParentOfSymbol(symbol)) { + // fast path, `symbol` is either already the alias or isn't aliased + return symbol; + } + var exports = getExportsOfSymbol(container); + var quick = exports.get(symbol.escapedName); + if (quick && symbolRefersToTarget(quick)) { + return quick; + } + return ts.forEachEntry(exports, function (exported) { + if (symbolRefersToTarget(exported)) { + return exported; + } + }); + function symbolRefersToTarget(s) { + if (s === symbol || resolveSymbol(s) === symbol || resolveSymbol(s) === resolveSymbol(symbol)) { + return s; + } + } + } + function getExportSymbolOfValueSymbolIfExported(symbol) { + return getMergedSymbol(symbol && (symbol.flags & 1048576 /* ExportValue */) !== 0 ? symbol.exportSymbol : symbol); + } + function symbolIsValue(symbol) { + return !!(symbol.flags & 67220415 /* Value */ || symbol.flags & 2097152 /* Alias */ && resolveAlias(symbol).flags & 67220415 /* Value */); + } + function findConstructorDeclaration(node) { + var members = node.members; + for (var _i = 0, members_2 = members; _i < members_2.length; _i++) { + var member = members_2[_i]; + if (member.kind === 157 /* Constructor */ && ts.nodeIsPresent(member.body)) { + return member; + } + } + } + function createType(flags) { + var result = new Type(checker, flags); + typeCount++; + result.id = typeCount; + return result; + } + function createIntrinsicType(kind, intrinsicName) { + var type = createType(kind); + type.intrinsicName = intrinsicName; + return type; + } + function createBooleanType(trueFalseTypes) { + var type = getUnionType(trueFalseTypes); + type.flags |= 16 /* Boolean */; + type.intrinsicName = "boolean"; + return type; + } + function createObjectType(objectFlags, symbol) { + var type = createType(524288 /* Object */); + type.objectFlags = objectFlags; + type.symbol = symbol; + type.members = undefined; + type.properties = undefined; + type.callSignatures = undefined; + type.constructSignatures = undefined; + type.stringIndexInfo = undefined; + type.numberIndexInfo = undefined; + return type; + } + function createTypeofType() { + return getUnionType(ts.arrayFrom(typeofEQFacts.keys(), getLiteralType)); + } + // A reserved member name starts with two underscores, but the third character cannot be an underscore + // or the @ symbol. A third underscore indicates an escaped form of an identifer that started + // with at least two underscores. The @ character indicates that the name is denoted by a well known ES + // Symbol instance. + function isReservedMemberName(name) { + return name.charCodeAt(0) === 95 /* _ */ && + name.charCodeAt(1) === 95 /* _ */ && + name.charCodeAt(2) !== 95 /* _ */ && + name.charCodeAt(2) !== 64 /* at */; + } + function getNamedMembers(members) { + var result; + members.forEach(function (symbol, id) { + if (!isReservedMemberName(id) && symbolIsValue(symbol)) { + (result || (result = [])).push(symbol); + } + }); + return result || ts.emptyArray; + } + function setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo) { + type.members = members; + type.properties = members === emptySymbols ? ts.emptyArray : getNamedMembers(members); + type.callSignatures = callSignatures; + type.constructSignatures = constructSignatures; + type.stringIndexInfo = stringIndexInfo; + type.numberIndexInfo = numberIndexInfo; + return type; + } + function createAnonymousType(symbol, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo) { + return setStructuredTypeMembers(createObjectType(16 /* Anonymous */, symbol), members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + } + function forEachSymbolTableInScope(enclosingDeclaration, callback) { + var result; + for (var location = enclosingDeclaration; location; location = location.parent) { + // Locals of a source file are not in scope (because they get merged into the global symbol table) + if (location.locals && !isGlobalSourceFile(location)) { + if (result = callback(location.locals)) { + return result; + } + } + switch (location.kind) { + case 279 /* SourceFile */: + if (!ts.isExternalOrCommonJsModule(location)) { + break; + } + // falls through + case 244 /* ModuleDeclaration */: + if (result = callback(getSymbolOfNode(location).exports)) { + return result; + } + break; + } + } + return callback(globals); + } + function getQualifiedLeftMeaning(rightMeaning) { + // If we are looking in value space, the parent meaning is value, other wise it is namespace + return rightMeaning === 67220415 /* Value */ ? 67220415 /* Value */ : 1920 /* Namespace */; + } + function getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, useOnlyExternalAliasing, visitedSymbolTablesMap) { + if (visitedSymbolTablesMap === void 0) { visitedSymbolTablesMap = ts.createMap(); } + if (!(symbol && !isPropertyOrMethodDeclarationSymbol(symbol))) { + return undefined; + } + var id = "" + getSymbolId(symbol); + var visitedSymbolTables = visitedSymbolTablesMap.get(id); + if (!visitedSymbolTables) { + visitedSymbolTablesMap.set(id, visitedSymbolTables = []); + } + return forEachSymbolTableInScope(enclosingDeclaration, getAccessibleSymbolChainFromSymbolTable); + /** + * @param {ignoreQualification} boolean Set when a symbol is being looked for through the exports of another symbol (meaning we have a route to qualify it already) + */ + function getAccessibleSymbolChainFromSymbolTable(symbols, ignoreQualification) { + if (!ts.pushIfUnique(visitedSymbolTables, symbols)) { + return undefined; + } + var result = trySymbolTable(symbols, ignoreQualification); + visitedSymbolTables.pop(); + return result; + } + function canQualifySymbol(symbolFromSymbolTable, meaning) { + // If the symbol is equivalent and doesn't need further qualification, this symbol is accessible + return !needsQualification(symbolFromSymbolTable, enclosingDeclaration, meaning) || + // If symbol needs qualification, make sure that parent is accessible, if it is then this symbol is accessible too + !!getAccessibleSymbolChain(symbolFromSymbolTable.parent, enclosingDeclaration, getQualifiedLeftMeaning(meaning), useOnlyExternalAliasing, visitedSymbolTablesMap); + } + function isAccessible(symbolFromSymbolTable, resolvedAliasSymbol, ignoreQualification) { + return symbol === (resolvedAliasSymbol || symbolFromSymbolTable) && + // if the symbolFromSymbolTable is not external module (it could be if it was determined as ambient external module and would be in globals table) + // and if symbolFromSymbolTable or alias resolution matches the symbol, + // check the symbol can be qualified, it is only then this symbol is accessible + !ts.some(symbolFromSymbolTable.declarations, hasNonGlobalAugmentationExternalModuleSymbol) && + (ignoreQualification || canQualifySymbol(symbolFromSymbolTable, meaning)); + } + function trySymbolTable(symbols, ignoreQualification) { + // If symbol is directly available by its name in the symbol table + if (isAccessible(symbols.get(symbol.escapedName), /*resolvedAliasSymbol*/ undefined, ignoreQualification)) { + return [symbol]; + } + // Check if symbol is any of the alias + return ts.forEachEntry(symbols, function (symbolFromSymbolTable) { + if (symbolFromSymbolTable.flags & 2097152 /* Alias */ + && symbolFromSymbolTable.escapedName !== "export=" /* ExportEquals */ + && symbolFromSymbolTable.escapedName !== "default" /* Default */ + && !(ts.isUMDExportSymbol(symbolFromSymbolTable) && enclosingDeclaration && ts.isExternalModule(ts.getSourceFileOfNode(enclosingDeclaration))) + // If `!useOnlyExternalAliasing`, we can use any type of alias to get the name + && (!useOnlyExternalAliasing || ts.some(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration)) + // While exports are generally considered to be in scope, export-specifier declared symbols are _not_ + // See similar comment in `resolveName` for details + && (ignoreQualification || !ts.getDeclarationOfKind(symbolFromSymbolTable, 257 /* ExportSpecifier */))) { + var resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable); + if (isAccessible(symbolFromSymbolTable, resolvedImportedSymbol, ignoreQualification)) { + return [symbolFromSymbolTable]; + } + // Look in the exported members, if we can find accessibleSymbolChain, symbol is accessible using this chain + // but only if the symbolFromSymbolTable can be qualified + var candidateTable = getExportsOfSymbol(resolvedImportedSymbol); + var accessibleSymbolsFromExports = candidateTable && getAccessibleSymbolChainFromSymbolTable(candidateTable, /*ignoreQualification*/ true); + if (accessibleSymbolsFromExports && canQualifySymbol(symbolFromSymbolTable, getQualifiedLeftMeaning(meaning))) { + return [symbolFromSymbolTable].concat(accessibleSymbolsFromExports); + } + } + if (symbolFromSymbolTable.escapedName === symbol.escapedName && symbolFromSymbolTable.exportSymbol) { + if (isAccessible(getMergedSymbol(symbolFromSymbolTable.exportSymbol), /*aliasSymbol*/ undefined, ignoreQualification)) { + return [symbol]; + } + } + }); + } + } + function needsQualification(symbol, enclosingDeclaration, meaning) { + var qualify = false; + forEachSymbolTableInScope(enclosingDeclaration, function (symbolTable) { + // If symbol of this name is not available in the symbol table we are ok + var symbolFromSymbolTable = getMergedSymbol(symbolTable.get(symbol.escapedName)); + if (!symbolFromSymbolTable) { + // Continue to the next symbol table + return false; + } + // If the symbol with this name is present it should refer to the symbol + if (symbolFromSymbolTable === symbol) { + // No need to qualify + return true; + } + // Qualify if the symbol from symbol table has same meaning as expected + symbolFromSymbolTable = (symbolFromSymbolTable.flags & 2097152 /* Alias */ && !ts.getDeclarationOfKind(symbolFromSymbolTable, 257 /* ExportSpecifier */)) ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable; + if (symbolFromSymbolTable.flags & meaning) { + qualify = true; + return true; + } + // Continue to the next symbol table + return false; + }); + return qualify; + } + function isPropertyOrMethodDeclarationSymbol(symbol) { + if (symbol.declarations && symbol.declarations.length) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + switch (declaration.kind) { + case 154 /* PropertyDeclaration */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + continue; + default: + return false; + } + } + return true; + } + return false; + } + function isTypeSymbolAccessible(typeSymbol, enclosingDeclaration) { + var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67897832 /* Type */, /*shouldComputeAliasesToMakeVisible*/ false); + return access.accessibility === 0 /* Accessible */; + } + function isValueSymbolAccessible(typeSymbol, enclosingDeclaration) { + var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67220415 /* Value */, /*shouldComputeAliasesToMakeVisible*/ false); + return access.accessibility === 0 /* Accessible */; + } + function isAnySymbolAccessible(symbols, enclosingDeclaration, initialSymbol, meaning, shouldComputeAliasesToMakeVisible) { + if (!ts.length(symbols)) + return; + var hadAccessibleChain; + for (var _i = 0, _a = symbols; _i < _a.length; _i++) { + var symbol = _a[_i]; + // Symbol is accessible if it by itself is accessible + var accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, /*useOnlyExternalAliasing*/ false); + if (accessibleSymbolChain) { + hadAccessibleChain = symbol; + var hasAccessibleDeclarations = hasVisibleDeclarations(accessibleSymbolChain[0], shouldComputeAliasesToMakeVisible); + if (hasAccessibleDeclarations) { + return hasAccessibleDeclarations; + } + } + else { + if (ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { + // Any meaning of a module symbol is always accessible via an `import` type + return { + accessibility: 0 /* Accessible */ + }; + } + } + // If we haven't got the accessible symbol, it doesn't mean the symbol is actually inaccessible. + // It could be a qualified symbol and hence verify the path + // e.g.: + // module m { + // export class c { + // } + // } + // const x: typeof m.c + // In the above example when we start with checking if typeof m.c symbol is accessible, + // we are going to see if c can be accessed in scope directly. + // But it can't, hence the accessible is going to be undefined, but that doesn't mean m.c is inaccessible + // It is accessible if the parent m is accessible because then m.c can be accessed through qualification + var containers = getContainersOfSymbol(symbol, enclosingDeclaration); + // If we're trying to reference some object literal in, eg `var a = { x: 1 }`, the symbol for the literal, `__object`, is distinct + // from the symbol of the declaration it is being assigned to. Since we can use the declaration to refer to the literal, however, + // we'd like to make that connection here - potentially causing us to paint the declararation's visibiility, and therefore the literal. + var firstDecl = ts.first(symbol.declarations); + if (!ts.length(containers) && meaning & 67220415 /* Value */ && firstDecl && ts.isObjectLiteralExpression(firstDecl)) { + if (firstDecl.parent && ts.isVariableDeclaration(firstDecl.parent) && firstDecl === firstDecl.parent.initializer) { + containers = [getSymbolOfNode(firstDecl.parent)]; + } + } + var parentResult = isAnySymbolAccessible(containers, enclosingDeclaration, initialSymbol, initialSymbol === symbol ? getQualifiedLeftMeaning(meaning) : meaning, shouldComputeAliasesToMakeVisible); + if (parentResult) { + return parentResult; + } + } + if (hadAccessibleChain) { + return { + accessibility: 1 /* NotAccessible */, + errorSymbolName: symbolToString(initialSymbol, enclosingDeclaration, meaning), + errorModuleName: hadAccessibleChain !== initialSymbol ? symbolToString(hadAccessibleChain, enclosingDeclaration, 1920 /* Namespace */) : undefined, + }; + } + } + /** + * Check if the given symbol in given enclosing declaration is accessible and mark all associated alias to be visible if requested + * + * @param symbol a Symbol to check if accessible + * @param enclosingDeclaration a Node containing reference to the symbol + * @param meaning a SymbolFlags to check if such meaning of the symbol is accessible + * @param shouldComputeAliasToMakeVisible a boolean value to indicate whether to return aliases to be mark visible in case the symbol is accessible + */ + function isSymbolAccessible(symbol, enclosingDeclaration, meaning, shouldComputeAliasesToMakeVisible) { + if (symbol && enclosingDeclaration) { + var result = isAnySymbolAccessible([symbol], enclosingDeclaration, symbol, meaning, shouldComputeAliasesToMakeVisible); + if (result) { + return result; + } + // This could be a symbol that is not exported in the external module + // or it could be a symbol from different external module that is not aliased and hence cannot be named + var symbolExternalModule = ts.forEach(symbol.declarations, getExternalModuleContainer); + if (symbolExternalModule) { + var enclosingExternalModule = getExternalModuleContainer(enclosingDeclaration); + if (symbolExternalModule !== enclosingExternalModule) { + // name from different external module that is not visible + return { + accessibility: 2 /* CannotBeNamed */, + errorSymbolName: symbolToString(symbol, enclosingDeclaration, meaning), + errorModuleName: symbolToString(symbolExternalModule) + }; + } + } + // Just a local name that is not accessible + return { + accessibility: 1 /* NotAccessible */, + errorSymbolName: symbolToString(symbol, enclosingDeclaration, meaning), + }; + } + return { accessibility: 0 /* Accessible */ }; + } + function getExternalModuleContainer(declaration) { + var node = ts.findAncestor(declaration, hasExternalModuleSymbol); + return node && getSymbolOfNode(node); + } + function hasExternalModuleSymbol(declaration) { + return ts.isAmbientModule(declaration) || (declaration.kind === 279 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration)); + } + function hasNonGlobalAugmentationExternalModuleSymbol(declaration) { + return ts.isModuleWithStringLiteralName(declaration) || (declaration.kind === 279 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration)); + } + function hasVisibleDeclarations(symbol, shouldComputeAliasToMakeVisible) { + var aliasesToMakeVisible; + if (!ts.every(symbol.declarations, getIsDeclarationVisible)) { + return undefined; + } + return { accessibility: 0 /* Accessible */, aliasesToMakeVisible: aliasesToMakeVisible }; + function getIsDeclarationVisible(declaration) { + if (!isDeclarationVisible(declaration)) { + // Mark the unexported alias as visible if its parent is visible + // because these kind of aliases can be used to name types in declaration file + var anyImportSyntax = getAnyImportSyntax(declaration); + if (anyImportSyntax && + !ts.hasModifier(anyImportSyntax, 1 /* Export */) && // import clause without export + isDeclarationVisible(anyImportSyntax.parent)) { + return addVisibleAlias(declaration, anyImportSyntax); + } + else if (ts.isVariableDeclaration(declaration) && ts.isVariableStatement(declaration.parent.parent) && + !ts.hasModifier(declaration.parent.parent, 1 /* Export */) && // unexported variable statement + isDeclarationVisible(declaration.parent.parent.parent)) { + return addVisibleAlias(declaration, declaration.parent.parent); + } + else if (ts.isLateVisibilityPaintedStatement(declaration) // unexported top-level statement + && !ts.hasModifier(declaration, 1 /* Export */) + && isDeclarationVisible(declaration.parent)) { + return addVisibleAlias(declaration, declaration); + } + // Declaration is not visible + return false; + } + return true; + } + function addVisibleAlias(declaration, aliasingStatement) { + // In function "buildTypeDisplay" where we decide whether to write type-alias or serialize types, + // we want to just check if type- alias is accessible or not but we don't care about emitting those alias at that time + // since we will do the emitting later in trackSymbol. + if (shouldComputeAliasToMakeVisible) { + getNodeLinks(declaration).isVisible = true; + aliasesToMakeVisible = ts.appendIfUnique(aliasesToMakeVisible, aliasingStatement); + } + return true; + } + } + function isEntityNameVisible(entityName, enclosingDeclaration) { + // get symbol of the first identifier of the entityName + var meaning; + if (entityName.parent.kind === 167 /* TypeQuery */ || + ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent) || + entityName.parent.kind === 149 /* ComputedPropertyName */) { + // Typeof value + meaning = 67220415 /* Value */ | 1048576 /* ExportValue */; + } + else if (entityName.kind === 148 /* QualifiedName */ || entityName.kind === 189 /* PropertyAccessExpression */ || + entityName.parent.kind === 248 /* ImportEqualsDeclaration */) { + // Left identifier from type reference or TypeAlias + // Entity name of the import declaration + meaning = 1920 /* Namespace */; + } + else { + // Type Reference or TypeAlias entity = Identifier + meaning = 67897832 /* Type */; + } + var firstIdentifier = getFirstIdentifier(entityName); + var symbol = resolveName(enclosingDeclaration, firstIdentifier.escapedText, meaning, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); + // Verify if the symbol is accessible + return (symbol && hasVisibleDeclarations(symbol, /*shouldComputeAliasToMakeVisible*/ true)) || { + accessibility: 1 /* NotAccessible */, + errorSymbolName: ts.getTextOfNode(firstIdentifier), + errorNode: firstIdentifier + }; + } + function symbolToString(symbol, enclosingDeclaration, meaning, flags, writer) { + if (flags === void 0) { flags = 4 /* AllowAnyNodeKind */; } + var nodeFlags = 70221824 /* IgnoreErrors */; + if (flags & 2 /* UseOnlyExternalAliasing */) { + nodeFlags |= 128 /* UseOnlyExternalAliasing */; + } + if (flags & 1 /* WriteTypeParametersOrArguments */) { + nodeFlags |= 512 /* WriteTypeParametersInQualifiedName */; + } + if (flags & 8 /* UseAliasDefinedOutsideCurrentScope */) { + nodeFlags |= 16384 /* UseAliasDefinedOutsideCurrentScope */; + } + if (flags & 16 /* DoNotIncludeSymbolChain */) { + nodeFlags |= 134217728 /* DoNotIncludeSymbolChain */; + } + var builder = flags & 4 /* AllowAnyNodeKind */ ? nodeBuilder.symbolToExpression : nodeBuilder.symbolToEntityName; + return writer ? symbolToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(symbolToStringWorker); + function symbolToStringWorker(writer) { + var entity = builder(symbol, meaning, enclosingDeclaration, nodeFlags); // TODO: GH#18217 + var printer = ts.createPrinter({ removeComments: true }); + var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); + printer.writeNode(4 /* Unspecified */, entity, /*sourceFile*/ sourceFile, writer); + return writer; + } + } + function signatureToString(signature, enclosingDeclaration, flags, kind, writer) { + if (flags === void 0) { flags = 0 /* None */; } + return writer ? signatureToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(signatureToStringWorker); + function signatureToStringWorker(writer) { + var sigOutput; + if (flags & 262144 /* WriteArrowStyleSignature */) { + sigOutput = kind === 1 /* Construct */ ? 166 /* ConstructorType */ : 165 /* FunctionType */; + } + else { + sigOutput = kind === 1 /* Construct */ ? 161 /* ConstructSignature */ : 160 /* CallSignature */; + } + var sig = nodeBuilder.signatureToSignatureDeclaration(signature, sigOutput, enclosingDeclaration, toNodeBuilderFlags(flags) | 70221824 /* IgnoreErrors */ | 512 /* WriteTypeParametersInQualifiedName */); + var printer = ts.createPrinter({ removeComments: true, omitTrailingSemicolon: true }); + var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); + printer.writeNode(4 /* Unspecified */, sig, /*sourceFile*/ sourceFile, ts.getTrailingSemicolonOmittingWriter(writer)); // TODO: GH#18217 + return writer; + } + } + function typeToString(type, enclosingDeclaration, flags, writer) { + if (flags === void 0) { flags = 1048576 /* AllowUniqueESSymbolType */ | 16384 /* UseAliasDefinedOutsideCurrentScope */; } + if (writer === void 0) { writer = ts.createTextWriter(""); } + var noTruncation = compilerOptions.noErrorTruncation || flags & 1 /* NoTruncation */; + var typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, toNodeBuilderFlags(flags) | 70221824 /* IgnoreErrors */ | (noTruncation ? 1 /* NoTruncation */ : 0), writer); + if (typeNode === undefined) + return ts.Debug.fail("should always get typenode"); + var options = { removeComments: true }; + var printer = ts.createPrinter(options); + var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); + printer.writeNode(4 /* Unspecified */, typeNode, /*sourceFile*/ sourceFile, writer); + var result = writer.getText(); + var maxLength = noTruncation ? undefined : ts.defaultMaximumTruncationLength * 2; + if (maxLength && result && result.length >= maxLength) { + return result.substr(0, maxLength - "...".length) + "..."; + } + return result; + } + function toNodeBuilderFlags(flags) { + if (flags === void 0) { flags = 0 /* None */; } + return flags & 9469291 /* NodeBuilderFlagsMask */; + } + function createNodeBuilder() { + return { + typeToTypeNode: function (type, enclosingDeclaration, flags, tracker) { + return withContext(enclosingDeclaration, flags, tracker, function (context) { return typeToTypeNodeHelper(type, context); }); + }, + indexInfoToIndexSignatureDeclaration: function (indexInfo, kind, enclosingDeclaration, flags, tracker) { + return withContext(enclosingDeclaration, flags, tracker, function (context) { return indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind, context); }); + }, + signatureToSignatureDeclaration: function (signature, kind, enclosingDeclaration, flags, tracker) { + return withContext(enclosingDeclaration, flags, tracker, function (context) { return signatureToSignatureDeclarationHelper(signature, kind, context); }); + }, + symbolToEntityName: function (symbol, meaning, enclosingDeclaration, flags, tracker) { + return withContext(enclosingDeclaration, flags, tracker, function (context) { return symbolToName(symbol, context, meaning, /*expectsIdentifier*/ false); }); + }, + symbolToExpression: function (symbol, meaning, enclosingDeclaration, flags, tracker) { + return withContext(enclosingDeclaration, flags, tracker, function (context) { return symbolToExpression(symbol, context, meaning); }); + }, + symbolToTypeParameterDeclarations: function (symbol, enclosingDeclaration, flags, tracker) { + return withContext(enclosingDeclaration, flags, tracker, function (context) { return typeParametersToTypeParameterDeclarations(symbol, context); }); + }, + symbolToParameterDeclaration: function (symbol, enclosingDeclaration, flags, tracker) { + return withContext(enclosingDeclaration, flags, tracker, function (context) { return symbolToParameterDeclaration(symbol, context); }); + }, + typeParameterToDeclaration: function (parameter, enclosingDeclaration, flags, tracker) { + return withContext(enclosingDeclaration, flags, tracker, function (context) { return typeParameterToDeclaration(parameter, context); }); + }, + }; + function withContext(enclosingDeclaration, flags, tracker, cb) { + ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8 /* Synthesized */) === 0); + var context = { + enclosingDeclaration: enclosingDeclaration, + flags: flags || 0 /* None */, + // If no full tracker is provided, fake up a dummy one with a basic limited-functionality moduleResolverHost + tracker: tracker && tracker.trackSymbol ? tracker : { trackSymbol: ts.noop, moduleResolverHost: flags & 134217728 /* DoNotIncludeSymbolChain */ ? { + getCommonSourceDirectory: host.getCommonSourceDirectory ? function () { return host.getCommonSourceDirectory(); } : function () { return ""; }, + getSourceFiles: function () { return host.getSourceFiles(); }, + getCurrentDirectory: host.getCurrentDirectory && (function () { return host.getCurrentDirectory(); }) + } : undefined }, + encounteredError: false, + visitedTypes: undefined, + symbolDepth: undefined, + inferTypeParameters: undefined, + approximateLength: 0 + }; + var resultingNode = cb(context); + return context.encounteredError ? undefined : resultingNode; + } + function checkTruncationLength(context) { + if (context.truncating) + return context.truncating; + return context.truncating = !(context.flags & 1 /* NoTruncation */) && context.approximateLength > ts.defaultMaximumTruncationLength; + } + function typeToTypeNodeHelper(type, context) { + if (cancellationToken && cancellationToken.throwIfCancellationRequested) { + cancellationToken.throwIfCancellationRequested(); + } + var inTypeAlias = context.flags & 8388608 /* InTypeAlias */; + context.flags &= ~8388608 /* InTypeAlias */; + if (!type) { + context.encounteredError = true; + return undefined; // TODO: GH#18217 + } + if (type.flags & 1 /* Any */) { + context.approximateLength += 3; + return ts.createKeywordTypeNode(120 /* AnyKeyword */); + } + if (type.flags & 2 /* Unknown */) { + return ts.createKeywordTypeNode(143 /* UnknownKeyword */); + } + if (type.flags & 4 /* String */) { + context.approximateLength += 6; + return ts.createKeywordTypeNode(138 /* StringKeyword */); + } + if (type.flags & 8 /* Number */) { + context.approximateLength += 6; + return ts.createKeywordTypeNode(135 /* NumberKeyword */); + } + if (type.flags & 64 /* BigInt */) { + context.approximateLength += 6; + return ts.createKeywordTypeNode(146 /* BigIntKeyword */); + } + if (type.flags & 16 /* Boolean */) { + context.approximateLength += 7; + return ts.createKeywordTypeNode(123 /* BooleanKeyword */); + } + if (type.flags & 1024 /* EnumLiteral */ && !(type.flags & 1048576 /* Union */)) { + var parentSymbol = getParentOfSymbol(type.symbol); + var parentName = symbolToTypeNode(parentSymbol, context, 67897832 /* Type */); + var enumLiteralName = getDeclaredTypeOfSymbol(parentSymbol) === type + ? parentName + : appendReferenceToType(parentName, ts.createTypeReferenceNode(ts.symbolName(type.symbol), /*typeArguments*/ undefined)); + return enumLiteralName; + } + if (type.flags & 1056 /* EnumLike */) { + return symbolToTypeNode(type.symbol, context, 67897832 /* Type */); + } + if (type.flags & 128 /* StringLiteral */) { + context.approximateLength += (type.value.length + 2); + return ts.createLiteralTypeNode(ts.setEmitFlags(ts.createLiteral(type.value), 16777216 /* NoAsciiEscaping */)); + } + if (type.flags & 256 /* NumberLiteral */) { + context.approximateLength += (("" + type.value).length); + return ts.createLiteralTypeNode((ts.createLiteral(type.value))); + } + if (type.flags & 2048 /* BigIntLiteral */) { + context.approximateLength += (ts.pseudoBigIntToString(type.value).length) + 1; + return ts.createLiteralTypeNode((ts.createLiteral(type.value))); + } + if (type.flags & 512 /* BooleanLiteral */) { + context.approximateLength += type.intrinsicName.length; + return type.intrinsicName === "true" ? ts.createTrue() : ts.createFalse(); + } + if (type.flags & 8192 /* UniqueESSymbol */) { + if (!(context.flags & 1048576 /* AllowUniqueESSymbolType */)) { + if (isValueSymbolAccessible(type.symbol, context.enclosingDeclaration)) { + context.approximateLength += 6; + return symbolToTypeNode(type.symbol, context, 67220415 /* Value */); + } + if (context.tracker.reportInaccessibleUniqueSymbolError) { + context.tracker.reportInaccessibleUniqueSymbolError(); + } + } + context.approximateLength += 13; + return ts.createTypeOperatorNode(142 /* UniqueKeyword */, ts.createKeywordTypeNode(139 /* SymbolKeyword */)); + } + if (type.flags & 16384 /* Void */) { + context.approximateLength += 4; + return ts.createKeywordTypeNode(106 /* VoidKeyword */); + } + if (type.flags & 32768 /* Undefined */) { + context.approximateLength += 9; + return ts.createKeywordTypeNode(141 /* UndefinedKeyword */); + } + if (type.flags & 65536 /* Null */) { + context.approximateLength += 4; + return ts.createKeywordTypeNode(96 /* NullKeyword */); + } + if (type.flags & 131072 /* Never */) { + context.approximateLength += 5; + return ts.createKeywordTypeNode(132 /* NeverKeyword */); + } + if (type.flags & 4096 /* ESSymbol */) { + context.approximateLength += 6; + return ts.createKeywordTypeNode(139 /* SymbolKeyword */); + } + if (type.flags & 67108864 /* NonPrimitive */) { + context.approximateLength += 6; + return ts.createKeywordTypeNode(136 /* ObjectKeyword */); + } + if (type.flags & 262144 /* TypeParameter */ && type.isThisType) { + if (context.flags & 4194304 /* InObjectTypeLiteral */) { + if (!context.encounteredError && !(context.flags & 32768 /* AllowThisInObjectLiteral */)) { + context.encounteredError = true; + } + if (context.tracker.reportInaccessibleThisError) { + context.tracker.reportInaccessibleThisError(); + } + } + context.approximateLength += 4; + return ts.createThis(); + } + var objectFlags = ts.getObjectFlags(type); + if (objectFlags & 4 /* Reference */) { + ts.Debug.assert(!!(type.flags & 524288 /* Object */)); + return typeReferenceToTypeNode(type); + } + if (type.flags & 262144 /* TypeParameter */ || objectFlags & 3 /* ClassOrInterface */) { + if (type.flags & 262144 /* TypeParameter */ && ts.contains(context.inferTypeParameters, type)) { + context.approximateLength += (ts.symbolName(type.symbol).length + 6); + return ts.createInferTypeNode(typeParameterToDeclarationWithConstraint(type, context, /*constraintNode*/ undefined)); + } + if (context.flags & 4 /* GenerateNamesForShadowedTypeParams */ && + type.flags & 262144 /* TypeParameter */ && + ts.length(type.symbol.declarations) && + ts.isTypeParameterDeclaration(type.symbol.declarations[0]) && + typeParameterShadowsNameInScope(type, context) && + !isTypeSymbolAccessible(type.symbol, context.enclosingDeclaration)) { + var name = type.symbol.declarations[0].name; + context.approximateLength += ts.idText(name).length; + return ts.createTypeReferenceNode(ts.getGeneratedNameForNode(name, 16 /* Optimistic */ | 8 /* ReservedInNestedScopes */), /*typeArguments*/ undefined); + } + // Ignore constraint/default when creating a usage (as opposed to declaration) of a type parameter. + return type.symbol + ? symbolToTypeNode(type.symbol, context, 67897832 /* Type */) + : ts.createTypeReferenceNode(ts.createIdentifier("?"), /*typeArguments*/ undefined); + } + if (!inTypeAlias && type.aliasSymbol && (context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */ || isTypeSymbolAccessible(type.aliasSymbol, context.enclosingDeclaration))) { + var typeArgumentNodes = mapToTypeNodes(type.aliasTypeArguments, context); + if (isReservedMemberName(type.aliasSymbol.escapedName) && !(type.aliasSymbol.flags & 32 /* Class */)) + return ts.createTypeReferenceNode(ts.createIdentifier(""), typeArgumentNodes); + return symbolToTypeNode(type.aliasSymbol, context, 67897832 /* Type */, typeArgumentNodes); + } + if (type.flags & (1048576 /* Union */ | 2097152 /* Intersection */)) { + var types = type.flags & 1048576 /* Union */ ? formatUnionTypes(type.types) : type.types; + if (ts.length(types) === 1) { + return typeToTypeNodeHelper(types[0], context); + } + var typeNodes = mapToTypeNodes(types, context, /*isBareList*/ true); + if (typeNodes && typeNodes.length > 0) { + var unionOrIntersectionTypeNode = ts.createUnionOrIntersectionTypeNode(type.flags & 1048576 /* Union */ ? 173 /* UnionType */ : 174 /* IntersectionType */, typeNodes); + return unionOrIntersectionTypeNode; + } + else { + if (!context.encounteredError && !(context.flags & 262144 /* AllowEmptyUnionOrIntersection */)) { + context.encounteredError = true; + } + return undefined; // TODO: GH#18217 + } + } + if (objectFlags & (16 /* Anonymous */ | 32 /* Mapped */)) { + ts.Debug.assert(!!(type.flags & 524288 /* Object */)); + // The type is an object literal type. + return createAnonymousTypeNode(type); + } + if (type.flags & 4194304 /* Index */) { + var indexedType = type.type; + context.approximateLength += 6; + var indexTypeNode = typeToTypeNodeHelper(indexedType, context); + return ts.createTypeOperatorNode(indexTypeNode); + } + if (type.flags & 8388608 /* IndexedAccess */) { + var objectTypeNode = typeToTypeNodeHelper(type.objectType, context); + var indexTypeNode = typeToTypeNodeHelper(type.indexType, context); + context.approximateLength += 2; + return ts.createIndexedAccessTypeNode(objectTypeNode, indexTypeNode); + } + if (type.flags & 16777216 /* Conditional */) { + var checkTypeNode = typeToTypeNodeHelper(type.checkType, context); + var saveInferTypeParameters = context.inferTypeParameters; + context.inferTypeParameters = type.root.inferTypeParameters; + var extendsTypeNode = typeToTypeNodeHelper(type.extendsType, context); + context.inferTypeParameters = saveInferTypeParameters; + var trueTypeNode = typeToTypeNodeHelper(getTrueTypeFromConditionalType(type), context); + var falseTypeNode = typeToTypeNodeHelper(getFalseTypeFromConditionalType(type), context); + context.approximateLength += 15; + return ts.createConditionalTypeNode(checkTypeNode, extendsTypeNode, trueTypeNode, falseTypeNode); + } + if (type.flags & 33554432 /* Substitution */) { + return typeToTypeNodeHelper(type.typeVariable, context); + } + return ts.Debug.fail("Should be unreachable."); + function createMappedTypeNodeFromType(type) { + ts.Debug.assert(!!(type.flags & 524288 /* Object */)); + var readonlyToken = type.declaration.readonlyToken ? ts.createToken(type.declaration.readonlyToken.kind) : undefined; + var questionToken = type.declaration.questionToken ? ts.createToken(type.declaration.questionToken.kind) : undefined; + var appropriateConstraintTypeNode; + if (isMappedTypeWithKeyofConstraintDeclaration(type)) { + // We have a { [P in keyof T]: X } + // We do this to ensure we retain the toplevel keyof-ness of the type which may be lost due to keyof distribution during `getConstraintTypeFromMappedType` + appropriateConstraintTypeNode = ts.createTypeOperatorNode(typeToTypeNodeHelper(getModifiersTypeFromMappedType(type), context)); + } + else { + appropriateConstraintTypeNode = typeToTypeNodeHelper(getConstraintTypeFromMappedType(type), context); + } + var typeParameterNode = typeParameterToDeclarationWithConstraint(getTypeParameterFromMappedType(type), context, appropriateConstraintTypeNode); + var templateTypeNode = typeToTypeNodeHelper(getTemplateTypeFromMappedType(type), context); + var mappedTypeNode = ts.createMappedTypeNode(readonlyToken, typeParameterNode, questionToken, templateTypeNode); + context.approximateLength += 10; + return ts.setEmitFlags(mappedTypeNode, 1 /* SingleLine */); + } + function createAnonymousTypeNode(type) { + var typeId = "" + type.id; + var symbol = type.symbol; + var id; + if (symbol) { + var isConstructorObject = ts.getObjectFlags(type) & 16 /* Anonymous */ && type.symbol && type.symbol.flags & 32 /* Class */; + id = (isConstructorObject ? "+" : "") + getSymbolId(symbol); + if (isJSConstructor(symbol.valueDeclaration)) { + // Instance and static types share the same symbol; only add 'typeof' for the static side. + var isInstanceType = type === getInferredClassType(symbol) ? 67897832 /* Type */ : 67220415 /* Value */; + return symbolToTypeNode(symbol, context, isInstanceType); + } + // Always use 'typeof T' for type of class, enum, and module objects + else if (symbol.flags & 32 /* Class */ && !getBaseTypeVariableOfClass(symbol) && !(symbol.valueDeclaration.kind === 209 /* ClassExpression */ && context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */) || + symbol.flags & (384 /* Enum */ | 512 /* ValueModule */) || + shouldWriteTypeOfFunctionSymbol()) { + return symbolToTypeNode(symbol, context, 67220415 /* Value */); + } + else if (context.visitedTypes && context.visitedTypes.has(typeId)) { + // If type is an anonymous type literal in a type alias declaration, use type alias name + var typeAlias = getTypeAliasForTypeLiteral(type); + if (typeAlias) { + // The specified symbol flags need to be reinterpreted as type flags + return symbolToTypeNode(typeAlias, context, 67897832 /* Type */); + } + else { + return createElidedInformationPlaceholder(context); + } + } + else { + // Since instantiations of the same anonymous type have the same symbol, tracking symbols instead + // of types allows us to catch circular references to instantiations of the same anonymous type + if (!context.visitedTypes) { + context.visitedTypes = ts.createMap(); + } + if (!context.symbolDepth) { + context.symbolDepth = ts.createMap(); + } + var depth = context.symbolDepth.get(id) || 0; + if (depth > 10) { + return createElidedInformationPlaceholder(context); + } + context.symbolDepth.set(id, depth + 1); + context.visitedTypes.set(typeId, true); + var result = createTypeNodeFromObjectType(type); + context.visitedTypes.delete(typeId); + context.symbolDepth.set(id, depth); + return result; + } + } + else { + // Anonymous types without a symbol are never circular. + return createTypeNodeFromObjectType(type); + } + function shouldWriteTypeOfFunctionSymbol() { + var isStaticMethodSymbol = !!(symbol.flags & 8192 /* Method */) && // typeof static method + ts.some(symbol.declarations, function (declaration) { return ts.hasModifier(declaration, 32 /* Static */); }); + var isNonLocalFunctionSymbol = !!(symbol.flags & 16 /* Function */) && + (symbol.parent || // is exported function symbol + ts.forEach(symbol.declarations, function (declaration) { + return declaration.parent.kind === 279 /* SourceFile */ || declaration.parent.kind === 245 /* ModuleBlock */; + })); + if (isStaticMethodSymbol || isNonLocalFunctionSymbol) { + // typeof is allowed only for static/non local functions + return (!!(context.flags & 4096 /* UseTypeOfFunction */) || (context.visitedTypes && context.visitedTypes.has(typeId))) && // it is type of the symbol uses itself recursively + (!(context.flags & 8 /* UseStructuralFallback */) || isValueSymbolAccessible(symbol, context.enclosingDeclaration)); // TODO: GH#18217 // And the build is going to succeed without visibility error or there is no structural fallback allowed + } + } + } + function createTypeNodeFromObjectType(type) { + if (isGenericMappedType(type)) { + return createMappedTypeNodeFromType(type); + } + var resolved = resolveStructuredTypeMembers(type); + if (!resolved.properties.length && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { + if (!resolved.callSignatures.length && !resolved.constructSignatures.length) { + context.approximateLength += 2; + return ts.setEmitFlags(ts.createTypeLiteralNode(/*members*/ undefined), 1 /* SingleLine */); + } + if (resolved.callSignatures.length === 1 && !resolved.constructSignatures.length) { + var signature = resolved.callSignatures[0]; + var signatureNode = signatureToSignatureDeclarationHelper(signature, 165 /* FunctionType */, context); + return signatureNode; + } + if (resolved.constructSignatures.length === 1 && !resolved.callSignatures.length) { + var signature = resolved.constructSignatures[0]; + var signatureNode = signatureToSignatureDeclarationHelper(signature, 166 /* ConstructorType */, context); + return signatureNode; + } + } + var savedFlags = context.flags; + context.flags |= 4194304 /* InObjectTypeLiteral */; + var members = createTypeNodesFromResolvedType(resolved); + context.flags = savedFlags; + var typeLiteralNode = ts.createTypeLiteralNode(members); + context.approximateLength += 2; + return ts.setEmitFlags(typeLiteralNode, (context.flags & 1024 /* MultilineObjectLiterals */) ? 0 : 1 /* SingleLine */); + } + function typeReferenceToTypeNode(type) { + var typeArguments = type.typeArguments || ts.emptyArray; + if (type.target === globalArrayType) { + if (context.flags & 2 /* WriteArrayAsGenericType */) { + var typeArgumentNode = typeToTypeNodeHelper(typeArguments[0], context); + return ts.createTypeReferenceNode("Array", [typeArgumentNode]); + } + var elementType = typeToTypeNodeHelper(typeArguments[0], context); + return ts.createArrayTypeNode(elementType); + } + else if (type.target.objectFlags & 8 /* Tuple */) { + if (typeArguments.length > 0) { + var arity = getTypeReferenceArity(type); + var tupleConstituentNodes = mapToTypeNodes(typeArguments.slice(0, arity), context); + var hasRestElement = type.target.hasRestElement; + if (tupleConstituentNodes) { + for (var i = type.target.minLength; i < Math.min(arity, tupleConstituentNodes.length); i++) { + tupleConstituentNodes[i] = hasRestElement && i === arity - 1 ? + ts.createRestTypeNode(ts.createArrayTypeNode(tupleConstituentNodes[i])) : + ts.createOptionalTypeNode(tupleConstituentNodes[i]); + } + return ts.createTupleTypeNode(tupleConstituentNodes); + } + } + if (context.encounteredError || (context.flags & 524288 /* AllowEmptyTuple */)) { + return ts.createTupleTypeNode([]); + } + context.encounteredError = true; + return undefined; // TODO: GH#18217 + } + else if (context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */ && + type.symbol.valueDeclaration && + ts.isClassLike(type.symbol.valueDeclaration) && + !isValueSymbolAccessible(type.symbol, context.enclosingDeclaration)) { + return createAnonymousTypeNode(type); + } + else { + var outerTypeParameters = type.target.outerTypeParameters; + var i = 0; + var resultType = void 0; + if (outerTypeParameters) { + var length_1 = outerTypeParameters.length; + while (i < length_1) { + // Find group of type arguments for type parameters with the same declaring container. + var start = i; + var parent = getParentSymbolOfTypeParameter(outerTypeParameters[i]); + do { + i++; + } while (i < length_1 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent); + // When type parameters are their own type arguments for the whole group (i.e. we have + // the default outer type arguments), we don't show the group. + if (!ts.rangeEquals(outerTypeParameters, typeArguments, start, i)) { + var typeArgumentSlice = mapToTypeNodes(typeArguments.slice(start, i), context); + var flags_2 = context.flags; + context.flags |= 16 /* ForbidIndexedAccessSymbolReferences */; + var ref = symbolToTypeNode(parent, context, 67897832 /* Type */, typeArgumentSlice); + context.flags = flags_2; + resultType = !resultType ? ref : appendReferenceToType(resultType, ref); + } + } + } + var typeArgumentNodes = void 0; + if (typeArguments.length > 0) { + var typeParameterCount = (type.target.typeParameters || ts.emptyArray).length; + typeArgumentNodes = mapToTypeNodes(typeArguments.slice(i, typeParameterCount), context); + } + var flags = context.flags; + context.flags |= 16 /* ForbidIndexedAccessSymbolReferences */; + var finalRef = symbolToTypeNode(type.symbol, context, 67897832 /* Type */, typeArgumentNodes); + context.flags = flags; + return !resultType ? finalRef : appendReferenceToType(resultType, finalRef); + } + } + function appendReferenceToType(root, ref) { + if (ts.isImportTypeNode(root)) { + // first shift type arguments + var innerParams = root.typeArguments; + if (root.qualifier) { + (ts.isIdentifier(root.qualifier) ? root.qualifier : root.qualifier.right).typeArguments = innerParams; + } + root.typeArguments = ref.typeArguments; + // then move qualifiers + var ids = getAccessStack(ref); + for (var _i = 0, ids_1 = ids; _i < ids_1.length; _i++) { + var id = ids_1[_i]; + root.qualifier = root.qualifier ? ts.createQualifiedName(root.qualifier, id) : id; + } + return root; + } + else { + // first shift type arguments + var innerParams = root.typeArguments; + (ts.isIdentifier(root.typeName) ? root.typeName : root.typeName.right).typeArguments = innerParams; + root.typeArguments = ref.typeArguments; + // then move qualifiers + var ids = getAccessStack(ref); + for (var _a = 0, ids_2 = ids; _a < ids_2.length; _a++) { + var id = ids_2[_a]; + root.typeName = ts.createQualifiedName(root.typeName, id); + } + return root; + } + } + function getAccessStack(ref) { + var state = ref.typeName; + var ids = []; + while (!ts.isIdentifier(state)) { + ids.unshift(state.right); + state = state.left; + } + ids.unshift(state); + return ids; + } + function createTypeNodesFromResolvedType(resolvedType) { + if (checkTruncationLength(context)) { + return [ts.createPropertySignature(/*modifiers*/ undefined, "...", /*questionToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined)]; + } + var typeElements = []; + for (var _i = 0, _a = resolvedType.callSignatures; _i < _a.length; _i++) { + var signature = _a[_i]; + typeElements.push(signatureToSignatureDeclarationHelper(signature, 160 /* CallSignature */, context)); + } + for (var _b = 0, _c = resolvedType.constructSignatures; _b < _c.length; _b++) { + var signature = _c[_b]; + typeElements.push(signatureToSignatureDeclarationHelper(signature, 161 /* ConstructSignature */, context)); + } + if (resolvedType.stringIndexInfo) { + var indexSignature = void 0; + if (resolvedType.objectFlags & 2048 /* ReverseMapped */) { + indexSignature = indexInfoToIndexSignatureDeclarationHelper(createIndexInfo(anyType, resolvedType.stringIndexInfo.isReadonly, resolvedType.stringIndexInfo.declaration), 0 /* String */, context); + indexSignature.type = createElidedInformationPlaceholder(context); + } + else { + indexSignature = indexInfoToIndexSignatureDeclarationHelper(resolvedType.stringIndexInfo, 0 /* String */, context); + } + typeElements.push(indexSignature); + } + if (resolvedType.numberIndexInfo) { + typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.numberIndexInfo, 1 /* Number */, context)); + } + var properties = resolvedType.properties; + if (!properties) { + return typeElements; + } + var i = 0; + for (var _d = 0, properties_1 = properties; _d < properties_1.length; _d++) { + var propertySymbol = properties_1[_d]; + i++; + if (context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */) { + if (propertySymbol.flags & 4194304 /* Prototype */) { + continue; + } + if (ts.getDeclarationModifierFlagsFromSymbol(propertySymbol) & (8 /* Private */ | 16 /* Protected */) && context.tracker.reportPrivateInBaseOfClassExpression) { + context.tracker.reportPrivateInBaseOfClassExpression(ts.unescapeLeadingUnderscores(propertySymbol.escapedName)); + } + } + if (checkTruncationLength(context) && (i + 2 < properties.length - 1)) { + typeElements.push(ts.createPropertySignature(/*modifiers*/ undefined, "... " + (properties.length - i) + " more ...", /*questionToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined)); + addPropertyToElementList(properties[properties.length - 1], context, typeElements); + break; + } + addPropertyToElementList(propertySymbol, context, typeElements); + } + return typeElements.length ? typeElements : undefined; + } + } + function createElidedInformationPlaceholder(context) { + context.approximateLength += 3; + if (!(context.flags & 1 /* NoTruncation */)) { + return ts.createTypeReferenceNode(ts.createIdentifier("..."), /*typeArguments*/ undefined); + } + return ts.createKeywordTypeNode(120 /* AnyKeyword */); + } + function addPropertyToElementList(propertySymbol, context, typeElements) { + var propertyIsReverseMapped = !!(ts.getCheckFlags(propertySymbol) & 2048 /* ReverseMapped */); + var propertyType = propertyIsReverseMapped && context.flags & 33554432 /* InReverseMappedType */ ? + anyType : getTypeOfSymbol(propertySymbol); + var saveEnclosingDeclaration = context.enclosingDeclaration; + context.enclosingDeclaration = undefined; + if (context.tracker.trackSymbol && ts.getCheckFlags(propertySymbol) & 1024 /* Late */) { + var decl = ts.first(propertySymbol.declarations); + if (hasLateBindableName(decl)) { + trackComputedName(decl.name, saveEnclosingDeclaration, context); + } + } + var propertyName = symbolToName(propertySymbol, context, 67220415 /* Value */, /*expectsIdentifier*/ true); + context.approximateLength += (ts.symbolName(propertySymbol).length + 1); + context.enclosingDeclaration = saveEnclosingDeclaration; + var optionalToken = propertySymbol.flags & 16777216 /* Optional */ ? ts.createToken(56 /* QuestionToken */) : undefined; + if (propertySymbol.flags & (16 /* Function */ | 8192 /* Method */) && !getPropertiesOfObjectType(propertyType).length) { + var signatures = getSignaturesOfType(propertyType, 0 /* Call */); + for (var _i = 0, signatures_1 = signatures; _i < signatures_1.length; _i++) { + var signature = signatures_1[_i]; + var methodDeclaration = signatureToSignatureDeclarationHelper(signature, 155 /* MethodSignature */, context); + methodDeclaration.name = propertyName; + methodDeclaration.questionToken = optionalToken; + if (propertySymbol.valueDeclaration) { + // Copy comments to node for declaration emit + ts.setCommentRange(methodDeclaration, propertySymbol.valueDeclaration); + } + typeElements.push(methodDeclaration); + } + } + else { + var savedFlags = context.flags; + context.flags |= propertyIsReverseMapped ? 33554432 /* InReverseMappedType */ : 0; + var propertyTypeNode = void 0; + if (propertyIsReverseMapped && !!(savedFlags & 33554432 /* InReverseMappedType */)) { + propertyTypeNode = createElidedInformationPlaceholder(context); + } + else { + propertyTypeNode = propertyType ? typeToTypeNodeHelper(propertyType, context) : ts.createKeywordTypeNode(120 /* AnyKeyword */); + } + context.flags = savedFlags; + var modifiers = isReadonlySymbol(propertySymbol) ? [ts.createToken(133 /* ReadonlyKeyword */)] : undefined; + if (modifiers) { + context.approximateLength += 9; + } + var propertySignature = ts.createPropertySignature(modifiers, propertyName, optionalToken, propertyTypeNode, + /*initializer*/ undefined); + if (propertySymbol.valueDeclaration) { + // Copy comments to node for declaration emit + ts.setCommentRange(propertySignature, propertySymbol.valueDeclaration); + } + typeElements.push(propertySignature); + } + } + function mapToTypeNodes(types, context, isBareList) { + if (ts.some(types)) { + if (checkTruncationLength(context)) { + if (!isBareList) { + return [ts.createTypeReferenceNode("...", /*typeArguments*/ undefined)]; + } + else if (types.length > 2) { + return [ + typeToTypeNodeHelper(types[0], context), + ts.createTypeReferenceNode("... " + (types.length - 2) + " more ...", /*typeArguments*/ undefined), + typeToTypeNodeHelper(types[types.length - 1], context) + ]; + } + } + var result = []; + var i = 0; + for (var _i = 0, types_1 = types; _i < types_1.length; _i++) { + var type = types_1[_i]; + i++; + if (checkTruncationLength(context) && (i + 2 < types.length - 1)) { + result.push(ts.createTypeReferenceNode("... " + (types.length - i) + " more ...", /*typeArguments*/ undefined)); + var typeNode_1 = typeToTypeNodeHelper(types[types.length - 1], context); + if (typeNode_1) { + result.push(typeNode_1); + } + break; + } + context.approximateLength += 2; // Account for whitespace + separator + var typeNode = typeToTypeNodeHelper(type, context); + if (typeNode) { + result.push(typeNode); + } + } + return result; + } + } + function indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind, context) { + var name = ts.getNameFromIndexInfo(indexInfo) || "x"; + var indexerTypeNode = ts.createKeywordTypeNode(kind === 0 /* String */ ? 138 /* StringKeyword */ : 135 /* NumberKeyword */); + var indexingParameter = ts.createParameter( + /*decorators*/ undefined, + /*modifiers*/ undefined, + /*dotDotDotToken*/ undefined, name, + /*questionToken*/ undefined, indexerTypeNode, + /*initializer*/ undefined); + var typeNode = typeToTypeNodeHelper(indexInfo.type || anyType, context); + if (!indexInfo.type && !(context.flags & 2097152 /* AllowEmptyIndexInfoType */)) { + context.encounteredError = true; + } + context.approximateLength += (name.length + 4); + return ts.createIndexSignature( + /*decorators*/ undefined, indexInfo.isReadonly ? [ts.createToken(133 /* ReadonlyKeyword */)] : undefined, [indexingParameter], typeNode); + } + function signatureToSignatureDeclarationHelper(signature, kind, context) { + var typeParameters; + var typeArguments; + if (context.flags & 32 /* WriteTypeArgumentsOfSignature */ && signature.target && signature.mapper && signature.target.typeParameters) { + typeArguments = signature.target.typeParameters.map(function (parameter) { return typeToTypeNodeHelper(instantiateType(parameter, signature.mapper), context); }); + } + else { + typeParameters = signature.typeParameters && signature.typeParameters.map(function (parameter) { return typeParameterToDeclaration(parameter, context); }); + } + var parameters = getExpandedParameters(signature).map(function (parameter) { return symbolToParameterDeclaration(parameter, context, kind === 157 /* Constructor */); }); + if (signature.thisParameter) { + var thisParameter = symbolToParameterDeclaration(signature.thisParameter, context); + parameters.unshift(thisParameter); + } + var returnTypeNode; + var typePredicate = getTypePredicateOfSignature(signature); + if (typePredicate) { + var parameterName = typePredicate.kind === 1 /* Identifier */ ? + ts.setEmitFlags(ts.createIdentifier(typePredicate.parameterName), 16777216 /* NoAsciiEscaping */) : + ts.createThisTypeNode(); + var typeNode = typeToTypeNodeHelper(typePredicate.type, context); + returnTypeNode = ts.createTypePredicateNode(parameterName, typeNode); + } + else { + var returnType = getReturnTypeOfSignature(signature); + returnTypeNode = returnType && typeToTypeNodeHelper(returnType, context); + } + if (context.flags & 256 /* SuppressAnyReturnType */) { + if (returnTypeNode && returnTypeNode.kind === 120 /* AnyKeyword */) { + returnTypeNode = undefined; + } + } + else if (!returnTypeNode) { + returnTypeNode = ts.createKeywordTypeNode(120 /* AnyKeyword */); + } + context.approximateLength += 3; // Usually a signature contributes a few more characters than this, but 3 is the minimum + return ts.createSignatureDeclaration(kind, typeParameters, parameters, returnTypeNode, typeArguments); + } + function typeParameterShadowsNameInScope(type, context) { + return !!resolveName(context.enclosingDeclaration, type.symbol.escapedName, 67897832 /* Type */, /*nameNotFoundArg*/ undefined, type.symbol.escapedName, /*isUse*/ false); + } + function typeParameterToDeclarationWithConstraint(type, context, constraintNode) { + var savedContextFlags = context.flags; + context.flags &= ~512 /* WriteTypeParametersInQualifiedName */; // Avoids potential infinite loop when building for a claimspace with a generic + var shouldUseGeneratedName = context.flags & 4 /* GenerateNamesForShadowedTypeParams */ && + type.symbol.declarations[0] && + ts.isTypeParameterDeclaration(type.symbol.declarations[0]) && + typeParameterShadowsNameInScope(type, context); + var name = shouldUseGeneratedName + ? ts.getGeneratedNameForNode(type.symbol.declarations[0].name, 16 /* Optimistic */ | 8 /* ReservedInNestedScopes */) + : symbolToName(type.symbol, context, 67897832 /* Type */, /*expectsIdentifier*/ true); + var defaultParameter = getDefaultFromTypeParameter(type); + var defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter, context); + context.flags = savedContextFlags; + return ts.createTypeParameterDeclaration(name, constraintNode, defaultParameterNode); + } + function typeParameterToDeclaration(type, context, constraint) { + if (constraint === void 0) { constraint = getConstraintOfTypeParameter(type); } + var constraintNode = constraint && typeToTypeNodeHelper(constraint, context); + return typeParameterToDeclarationWithConstraint(type, context, constraintNode); + } + function symbolToParameterDeclaration(parameterSymbol, context, preserveModifierFlags) { + var parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 151 /* Parameter */); + if (!parameterDeclaration && !isTransientSymbol(parameterSymbol)) { + parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 299 /* JSDocParameterTag */); + } + var parameterType = getTypeOfSymbol(parameterSymbol); + if (parameterDeclaration && isRequiredInitializedParameter(parameterDeclaration)) { + parameterType = getOptionalType(parameterType); + } + var parameterTypeNode = typeToTypeNodeHelper(parameterType, context); + var modifiers = !(context.flags & 8192 /* OmitParameterModifiers */) && preserveModifierFlags && parameterDeclaration && parameterDeclaration.modifiers ? parameterDeclaration.modifiers.map(ts.getSynthesizedClone) : undefined; + var isRest = parameterDeclaration && ts.isRestParameter(parameterDeclaration) || ts.getCheckFlags(parameterSymbol) & 8192 /* RestParameter */; + var dotDotDotToken = isRest ? ts.createToken(25 /* DotDotDotToken */) : undefined; + var name = parameterDeclaration + ? parameterDeclaration.name ? + parameterDeclaration.name.kind === 72 /* Identifier */ ? ts.setEmitFlags(ts.getSynthesizedClone(parameterDeclaration.name), 16777216 /* NoAsciiEscaping */) : + parameterDeclaration.name.kind === 148 /* QualifiedName */ ? ts.setEmitFlags(ts.getSynthesizedClone(parameterDeclaration.name.right), 16777216 /* NoAsciiEscaping */) : + cloneBindingName(parameterDeclaration.name) : + ts.symbolName(parameterSymbol) + : ts.symbolName(parameterSymbol); + var isOptional = parameterDeclaration && isOptionalParameter(parameterDeclaration) || ts.getCheckFlags(parameterSymbol) & 4096 /* OptionalParameter */; + var questionToken = isOptional ? ts.createToken(56 /* QuestionToken */) : undefined; + var parameterNode = ts.createParameter( + /*decorators*/ undefined, modifiers, dotDotDotToken, name, questionToken, parameterTypeNode, + /*initializer*/ undefined); + context.approximateLength += ts.symbolName(parameterSymbol).length + 3; + return parameterNode; + function cloneBindingName(node) { + return elideInitializerAndSetEmitFlags(node); + function elideInitializerAndSetEmitFlags(node) { + if (context.tracker.trackSymbol && ts.isComputedPropertyName(node) && isLateBindableName(node)) { + trackComputedName(node, context.enclosingDeclaration, context); + } + var visited = ts.visitEachChild(node, elideInitializerAndSetEmitFlags, ts.nullTransformationContext, /*nodesVisitor*/ undefined, elideInitializerAndSetEmitFlags); + var clone = ts.nodeIsSynthesized(visited) ? visited : ts.getSynthesizedClone(visited); + if (clone.kind === 186 /* BindingElement */) { + clone.initializer = undefined; + } + return ts.setEmitFlags(clone, 1 /* SingleLine */ | 16777216 /* NoAsciiEscaping */); + } + } + } + function trackComputedName(node, enclosingDeclaration, context) { + if (!context.tracker.trackSymbol) + return; + // get symbol of the first identifier of the entityName + var firstIdentifier = getFirstIdentifier(node.expression); + var name = resolveName(firstIdentifier, firstIdentifier.escapedText, 67220415 /* Value */ | 1048576 /* ExportValue */, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); + if (name) { + context.tracker.trackSymbol(name, enclosingDeclaration, 67220415 /* Value */); + } + } + function lookupSymbolChain(symbol, context, meaning, yieldModuleSymbol) { + context.tracker.trackSymbol(symbol, context.enclosingDeclaration, meaning); // TODO: GH#18217 + // Try to get qualified name if the symbol is not a type parameter and there is an enclosing declaration. + var chain; + var isTypeParameter = symbol.flags & 262144 /* TypeParameter */; + if (!isTypeParameter && (context.enclosingDeclaration || context.flags & 64 /* UseFullyQualifiedType */) && !(context.flags & 134217728 /* DoNotIncludeSymbolChain */)) { + chain = ts.Debug.assertDefined(getSymbolChain(symbol, meaning, /*endOfChain*/ true)); + ts.Debug.assert(chain && chain.length > 0); + } + else { + chain = [symbol]; + } + return chain; + /** @param endOfChain Set to false for recursive calls; non-recursive calls should always output something. */ + function getSymbolChain(symbol, meaning, endOfChain) { + var accessibleSymbolChain = getAccessibleSymbolChain(symbol, context.enclosingDeclaration, meaning, !!(context.flags & 128 /* UseOnlyExternalAliasing */)); + var parentSpecifiers; + if (!accessibleSymbolChain || + needsQualification(accessibleSymbolChain[0], context.enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) { + // Go up and add our parent. + var parents_1 = getContainersOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol, context.enclosingDeclaration); + if (ts.length(parents_1)) { + parentSpecifiers = parents_1.map(function (symbol) { + return ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol) + ? getSpecifierForModuleSymbol(symbol, context) + : undefined; + }); + var indices = parents_1.map(function (_, i) { return i; }); + indices.sort(sortByBestName); + var sortedParents = indices.map(function (i) { return parents_1[i]; }); + for (var _i = 0, sortedParents_1 = sortedParents; _i < sortedParents_1.length; _i++) { + var parent = sortedParents_1[_i]; + var parentChain = getSymbolChain(parent, getQualifiedLeftMeaning(meaning), /*endOfChain*/ false); + if (parentChain) { + accessibleSymbolChain = parentChain.concat(accessibleSymbolChain || [getAliasForSymbolInContainer(parent, symbol) || symbol]); + break; + } + } + } + } + if (accessibleSymbolChain) { + return accessibleSymbolChain; + } + if ( + // If this is the last part of outputting the symbol, always output. The cases apply only to parent symbols. + endOfChain || + // If a parent symbol is an anonymous type, don't write it. + !(symbol.flags & (2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */))) { + // If a parent symbol is an external module, don't write it. (We prefer just `x` vs `"foo/bar".x`.) + if (!endOfChain && !yieldModuleSymbol && !!ts.forEach(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { + return; + } + return [symbol]; + } + function sortByBestName(a, b) { + var specifierA = parentSpecifiers[a]; + var specifierB = parentSpecifiers[b]; + if (specifierA && specifierB) { + var isBRelative = ts.pathIsRelative(specifierB); + if (ts.pathIsRelative(specifierA) === isBRelative) { + // Both relative or both non-relative, sort by number of parts + return ts.moduleSpecifiers.countPathComponents(specifierA) - ts.moduleSpecifiers.countPathComponents(specifierB); + } + if (isBRelative) { + // A is non-relative, B is relative: prefer A + return -1; + } + // A is relative, B is non-relative: prefer B + return 1; + } + return 0; + } + } + } + function typeParametersToTypeParameterDeclarations(symbol, context) { + var typeParameterNodes; + var targetSymbol = getTargetSymbol(symbol); + if (targetSymbol.flags & (32 /* Class */ | 64 /* Interface */ | 524288 /* TypeAlias */)) { + typeParameterNodes = ts.createNodeArray(ts.map(getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol), function (tp) { return typeParameterToDeclaration(tp, context); })); + } + return typeParameterNodes; + } + function lookupTypeParameterNodes(chain, index, context) { + ts.Debug.assert(chain && 0 <= index && index < chain.length); + var symbol = chain[index]; + var typeParameterNodes; + if (context.flags & 512 /* WriteTypeParametersInQualifiedName */ && index < (chain.length - 1)) { + var parentSymbol = symbol; + var nextSymbol = chain[index + 1]; + if (ts.getCheckFlags(nextSymbol) & 1 /* Instantiated */) { + var params = getTypeParametersOfClassOrInterface(parentSymbol.flags & 2097152 /* Alias */ ? resolveAlias(parentSymbol) : parentSymbol); + typeParameterNodes = mapToTypeNodes(ts.map(params, nextSymbol.mapper), context); + } + else { + typeParameterNodes = typeParametersToTypeParameterDeclarations(symbol, context); + } + } + return typeParameterNodes; + } + /** + * Given A[B][C][D], finds A[B] + */ + function getTopmostIndexedAccessType(top) { + if (ts.isIndexedAccessTypeNode(top.objectType)) { + return getTopmostIndexedAccessType(top.objectType); + } + return top; + } + function getSpecifierForModuleSymbol(symbol, context) { + var file = ts.getDeclarationOfKind(symbol, 279 /* SourceFile */); + if (file && file.moduleName !== undefined) { + // Use the amd name if it is available + return file.moduleName; + } + if (!file) { + if (context.tracker.trackReferencedAmbientModule) { + var ambientDecls = ts.filter(symbol.declarations, ts.isAmbientModule); + if (ts.length(ambientDecls)) { + for (var _i = 0, ambientDecls_1 = ambientDecls; _i < ambientDecls_1.length; _i++) { + var decl = ambientDecls_1[_i]; + context.tracker.trackReferencedAmbientModule(decl, symbol); + } + } + } + if (ambientModuleSymbolRegex.test(symbol.escapedName)) { + return symbol.escapedName.substring(1, symbol.escapedName.length - 1); + } + } + if (!context.enclosingDeclaration || !context.tracker.moduleResolverHost) { + // If there's no context declaration, we can't lookup a non-ambient specifier, so we just use the symbol name + if (ambientModuleSymbolRegex.test(symbol.escapedName)) { + return symbol.escapedName.substring(1, symbol.escapedName.length - 1); + } + return ts.getSourceFileOfNode(ts.getNonAugmentationDeclaration(symbol)).fileName; // A resolver may not be provided for baselines and errors - in those cases we use the fileName in full + } + var contextFile = ts.getSourceFileOfNode(ts.getOriginalNode(context.enclosingDeclaration)); + var links = getSymbolLinks(symbol); + var specifier = links.specifierCache && links.specifierCache.get(contextFile.path); + if (!specifier) { + var isBundle_1 = (compilerOptions.out || compilerOptions.outFile); + // For declaration bundles, we need to generate absolute paths relative to the common source dir for imports, + // just like how the declaration emitter does for the ambient module declarations - we can easily accomplish this + // using the `baseUrl` compiler option (which we would otherwise never use in declaration emit) and a non-relative + // specifier preference + var moduleResolverHost = context.tracker.moduleResolverHost; + var specifierCompilerOptions = isBundle_1 ? __assign({}, compilerOptions, { baseUrl: moduleResolverHost.getCommonSourceDirectory() }) : compilerOptions; + specifier = ts.first(ts.moduleSpecifiers.getModuleSpecifiers(symbol, specifierCompilerOptions, contextFile, moduleResolverHost, host.getSourceFiles(), { importModuleSpecifierPreference: isBundle_1 ? "non-relative" : "relative" }, host.redirectTargetsMap)); + links.specifierCache = links.specifierCache || ts.createMap(); + links.specifierCache.set(contextFile.path, specifier); + } + return specifier; + } + function symbolToTypeNode(symbol, context, meaning, overrideTypeArguments) { + var chain = lookupSymbolChain(symbol, context, meaning, !(context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */)); // If we're using aliases outside the current scope, dont bother with the module + var isTypeOf = meaning === 67220415 /* Value */; + if (ts.some(chain[0].declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { + // module is root, must use `ImportTypeNode` + var nonRootParts = chain.length > 1 ? createAccessFromSymbolChain(chain, chain.length - 1, 1) : undefined; + var typeParameterNodes = overrideTypeArguments || lookupTypeParameterNodes(chain, 0, context); + var specifier = getSpecifierForModuleSymbol(chain[0], context); + if (!(context.flags & 67108864 /* AllowNodeModulesRelativePaths */) && ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs && specifier.indexOf("/node_modules/") >= 0) { + // If ultimately we can only name the symbol with a reference that dives into a `node_modules` folder, we should error + // since declaration files with these kinds of references are liable to fail when published :( + context.encounteredError = true; + if (context.tracker.reportLikelyUnsafeImportRequiredError) { + context.tracker.reportLikelyUnsafeImportRequiredError(specifier); + } + } + var lit = ts.createLiteralTypeNode(ts.createLiteral(specifier)); + if (context.tracker.trackExternalModuleSymbolOfImportTypeNode) + context.tracker.trackExternalModuleSymbolOfImportTypeNode(chain[0]); + context.approximateLength += specifier.length + 10; // specifier + import("") + if (!nonRootParts || ts.isEntityName(nonRootParts)) { + if (nonRootParts) { + var lastId = ts.isIdentifier(nonRootParts) ? nonRootParts : nonRootParts.right; + lastId.typeArguments = undefined; + } + return ts.createImportTypeNode(lit, nonRootParts, typeParameterNodes, isTypeOf); + } + else { + var splitNode = getTopmostIndexedAccessType(nonRootParts); + var qualifier = splitNode.objectType.typeName; + return ts.createIndexedAccessTypeNode(ts.createImportTypeNode(lit, qualifier, typeParameterNodes, isTypeOf), splitNode.indexType); + } + } + var entityName = createAccessFromSymbolChain(chain, chain.length - 1, 0); + if (ts.isIndexedAccessTypeNode(entityName)) { + return entityName; // Indexed accesses can never be `typeof` + } + if (isTypeOf) { + return ts.createTypeQueryNode(entityName); + } + else { + var lastId = ts.isIdentifier(entityName) ? entityName : entityName.right; + var lastTypeArgs = lastId.typeArguments; + lastId.typeArguments = undefined; + return ts.createTypeReferenceNode(entityName, lastTypeArgs); + } + function createAccessFromSymbolChain(chain, index, stopper) { + var typeParameterNodes = index === (chain.length - 1) ? overrideTypeArguments : lookupTypeParameterNodes(chain, index, context); + var symbol = chain[index]; + if (index === 0) { + context.flags |= 16777216 /* InInitialEntityName */; + } + var symbolName = getNameOfSymbolAsWritten(symbol, context); + context.approximateLength += symbolName.length + 1; + if (index === 0) { + context.flags ^= 16777216 /* InInitialEntityName */; + } + var parent = chain[index - 1]; + if (!(context.flags & 16 /* ForbidIndexedAccessSymbolReferences */) && parent && getMembersOfSymbol(parent) && getMembersOfSymbol(parent).get(symbol.escapedName) === symbol) { + // Should use an indexed access + var LHS = createAccessFromSymbolChain(chain, index - 1, stopper); + if (ts.isIndexedAccessTypeNode(LHS)) { + return ts.createIndexedAccessTypeNode(LHS, ts.createLiteralTypeNode(ts.createLiteral(symbolName))); + } + else { + return ts.createIndexedAccessTypeNode(ts.createTypeReferenceNode(LHS, typeParameterNodes), ts.createLiteralTypeNode(ts.createLiteral(symbolName))); + } + } + var identifier = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216 /* NoAsciiEscaping */); + identifier.symbol = symbol; + if (index > stopper) { + var LHS = createAccessFromSymbolChain(chain, index - 1, stopper); + if (!ts.isEntityName(LHS)) { + return ts.Debug.fail("Impossible construct - an export of an indexed access cannot be reachable"); + } + return ts.createQualifiedName(LHS, identifier); + } + return identifier; + } + } + function symbolToName(symbol, context, meaning, expectsIdentifier) { + var chain = lookupSymbolChain(symbol, context, meaning); + if (expectsIdentifier && chain.length !== 1 + && !context.encounteredError + && !(context.flags & 65536 /* AllowQualifedNameInPlaceOfIdentifier */)) { + context.encounteredError = true; + } + return createEntityNameFromSymbolChain(chain, chain.length - 1); + function createEntityNameFromSymbolChain(chain, index) { + var typeParameterNodes = lookupTypeParameterNodes(chain, index, context); + var symbol = chain[index]; + if (index === 0) { + context.flags |= 16777216 /* InInitialEntityName */; + } + var symbolName = getNameOfSymbolAsWritten(symbol, context); + if (index === 0) { + context.flags ^= 16777216 /* InInitialEntityName */; + } + var identifier = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216 /* NoAsciiEscaping */); + identifier.symbol = symbol; + return index > 0 ? ts.createQualifiedName(createEntityNameFromSymbolChain(chain, index - 1), identifier) : identifier; + } + } + function symbolToExpression(symbol, context, meaning) { + var chain = lookupSymbolChain(symbol, context, meaning); + return createExpressionFromSymbolChain(chain, chain.length - 1); + function createExpressionFromSymbolChain(chain, index) { + var typeParameterNodes = lookupTypeParameterNodes(chain, index, context); + var symbol = chain[index]; + if (ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { + return ts.createLiteral(getSpecifierForModuleSymbol(symbol, context)); + } + if (index === 0) { + context.flags |= 16777216 /* InInitialEntityName */; + } + var symbolName = getNameOfSymbolAsWritten(symbol, context); + if (index === 0) { + context.flags ^= 16777216 /* InInitialEntityName */; + } + var firstChar = symbolName.charCodeAt(0); + var canUsePropertyAccess = ts.isIdentifierStart(firstChar, languageVersion); + if (index === 0 || canUsePropertyAccess) { + var identifier = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216 /* NoAsciiEscaping */); + identifier.symbol = symbol; + return index > 0 ? ts.createPropertyAccess(createExpressionFromSymbolChain(chain, index - 1), identifier) : identifier; + } + else { + if (firstChar === 91 /* openBracket */) { + symbolName = symbolName.substring(1, symbolName.length - 1); + firstChar = symbolName.charCodeAt(0); + } + var expression = void 0; + if (ts.isSingleOrDoubleQuote(firstChar)) { + expression = ts.createLiteral(symbolName.substring(1, symbolName.length - 1).replace(/\\./g, function (s) { return s.substring(1); })); + expression.singleQuote = firstChar === 39 /* singleQuote */; + } + else if (("" + +symbolName) === symbolName) { + expression = ts.createLiteral(+symbolName); + } + if (!expression) { + expression = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216 /* NoAsciiEscaping */); + expression.symbol = symbol; + } + return ts.createElementAccess(createExpressionFromSymbolChain(chain, index - 1), expression); + } + } + } + } + function typePredicateToString(typePredicate, enclosingDeclaration, flags, writer) { + if (flags === void 0) { flags = 16384 /* UseAliasDefinedOutsideCurrentScope */; } + return writer ? typePredicateToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(typePredicateToStringWorker); + function typePredicateToStringWorker(writer) { + var predicate = ts.createTypePredicateNode(typePredicate.kind === 1 /* Identifier */ ? ts.createIdentifier(typePredicate.parameterName) : ts.createThisTypeNode(), nodeBuilder.typeToTypeNode(typePredicate.type, enclosingDeclaration, toNodeBuilderFlags(flags) | 70221824 /* IgnoreErrors */ | 512 /* WriteTypeParametersInQualifiedName */)); + var printer = ts.createPrinter({ removeComments: true }); + var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); + printer.writeNode(4 /* Unspecified */, predicate, /*sourceFile*/ sourceFile, writer); + return writer; + } + } + function formatUnionTypes(types) { + var result = []; + var flags = 0; + for (var i = 0; i < types.length; i++) { + var t = types[i]; + flags |= t.flags; + if (!(t.flags & 98304 /* Nullable */)) { + if (t.flags & (512 /* BooleanLiteral */ | 1024 /* EnumLiteral */)) { + var baseType = t.flags & 512 /* BooleanLiteral */ ? booleanType : getBaseTypeOfEnumLiteralType(t); + if (baseType.flags & 1048576 /* Union */) { + var count = baseType.types.length; + if (i + count <= types.length && getRegularTypeOfLiteralType(types[i + count - 1]) === getRegularTypeOfLiteralType(baseType.types[count - 1])) { + result.push(baseType); + i += count - 1; + continue; + } + } + } + result.push(t); + } + } + if (flags & 65536 /* Null */) + result.push(nullType); + if (flags & 32768 /* Undefined */) + result.push(undefinedType); + return result || types; + } + function visibilityToString(flags) { + if (flags === 8 /* Private */) { + return "private"; + } + if (flags === 16 /* Protected */) { + return "protected"; + } + return "public"; + } + function getTypeAliasForTypeLiteral(type) { + if (type.symbol && type.symbol.flags & 2048 /* TypeLiteral */) { + var node = ts.findAncestor(type.symbol.declarations[0].parent, function (n) { return n.kind !== 177 /* ParenthesizedType */; }); + if (node.kind === 242 /* TypeAliasDeclaration */) { + return getSymbolOfNode(node); + } + } + return undefined; + } + function isTopLevelInExternalModuleAugmentation(node) { + return node && node.parent && + node.parent.kind === 245 /* ModuleBlock */ && + ts.isExternalModuleAugmentation(node.parent.parent); + } + function isDefaultBindingContext(location) { + return location.kind === 279 /* SourceFile */ || ts.isAmbientModule(location); + } + /** + * Gets a human-readable name for a symbol. + * Should *not* be used for the right-hand side of a `.` -- use `symbolName(symbol)` for that instead. + * + * Unlike `symbolName(symbol)`, this will include quotes if the name is from a string literal. + * It will also use a representation of a number as written instead of a decimal form, e.g. `0o11` instead of `9`. + */ + function getNameOfSymbolAsWritten(symbol, context) { + if (context && symbol.escapedName === "default" /* Default */ && !(context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */) && + // If it's not the first part of an entity name, it must print as `default` + (!(context.flags & 16777216 /* InInitialEntityName */) || + // if the symbol is synthesized, it will only be referenced externally it must print as `default` + !symbol.declarations || + // if not in the same binding context (source file, module declaration), it must print as `default` + (context.enclosingDeclaration && ts.findAncestor(symbol.declarations[0], isDefaultBindingContext) !== ts.findAncestor(context.enclosingDeclaration, isDefaultBindingContext)))) { + return "default"; + } + if (symbol.declarations && symbol.declarations.length) { + var declaration = symbol.declarations[0]; + var name = ts.getNameOfDeclaration(declaration); + if (name) { + if (ts.isCallExpression(declaration) && ts.isBindableObjectDefinePropertyCall(declaration)) { + return ts.symbolName(symbol); + } + return ts.declarationNameToString(name); + } + if (declaration.parent && declaration.parent.kind === 237 /* VariableDeclaration */) { + return ts.declarationNameToString(declaration.parent.name); + } + switch (declaration.kind) { + case 209 /* ClassExpression */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + if (context && !context.encounteredError && !(context.flags & 131072 /* AllowAnonymousIdentifier */)) { + context.encounteredError = true; + } + return declaration.kind === 209 /* ClassExpression */ ? "(Anonymous class)" : "(Anonymous function)"; + } + } + var nameType = symbol.nameType; + if (nameType) { + if (nameType.flags & 128 /* StringLiteral */ && !ts.isIdentifierText(nameType.value, compilerOptions.target)) { + return "\"" + ts.escapeString(nameType.value, 34 /* doubleQuote */) + "\""; + } + if (nameType && nameType.flags & 8192 /* UniqueESSymbol */) { + return "[" + getNameOfSymbolAsWritten(nameType.symbol, context) + "]"; + } + } + return ts.symbolName(symbol); + } + function isDeclarationVisible(node) { + if (node) { + var links = getNodeLinks(node); + if (links.isVisible === undefined) { + links.isVisible = !!determineIfDeclarationIsVisible(); + } + return links.isVisible; + } + return false; + function determineIfDeclarationIsVisible() { + switch (node.kind) { + case 297 /* JSDocCallbackTag */: + case 304 /* JSDocTypedefTag */: + // Top-level jsdoc type aliases are considered exported + // First parent is comment node, second is hosting declaration or token; we only care about those tokens or declarations whose parent is a source file + return !!(node.parent && node.parent.parent && node.parent.parent.parent && ts.isSourceFile(node.parent.parent.parent)); + case 186 /* BindingElement */: + return isDeclarationVisible(node.parent.parent); + case 237 /* VariableDeclaration */: + if (ts.isBindingPattern(node.name) && + !node.name.elements.length) { + // If the binding pattern is empty, this variable declaration is not visible + return false; + } + // falls through + case 244 /* ModuleDeclaration */: + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 239 /* FunctionDeclaration */: + case 243 /* EnumDeclaration */: + case 248 /* ImportEqualsDeclaration */: + // external module augmentation is always visible + if (ts.isExternalModuleAugmentation(node)) { + return true; + } + var parent = getDeclarationContainer(node); + // If the node is not exported or it is not ambient module element (except import declaration) + if (!(ts.getCombinedModifierFlags(node) & 1 /* Export */) && + !(node.kind !== 248 /* ImportEqualsDeclaration */ && parent.kind !== 279 /* SourceFile */ && parent.flags & 4194304 /* Ambient */)) { + return isGlobalSourceFile(parent); + } + // Exported members/ambient module elements (exception import declaration) are visible if parent is visible + return isDeclarationVisible(parent); + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + if (ts.hasModifier(node, 8 /* Private */ | 16 /* Protected */)) { + // Private/protected properties/methods are not visible + return false; + } + // Public properties/methods are visible if its parents are visible, so: + // falls through + case 157 /* Constructor */: + case 161 /* ConstructSignature */: + case 160 /* CallSignature */: + case 162 /* IndexSignature */: + case 151 /* Parameter */: + case 245 /* ModuleBlock */: + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + case 168 /* TypeLiteral */: + case 164 /* TypeReference */: + case 169 /* ArrayType */: + case 170 /* TupleType */: + case 173 /* UnionType */: + case 174 /* IntersectionType */: + case 177 /* ParenthesizedType */: + return isDeclarationVisible(node.parent); + // Default binding, import specifier and namespace import is visible + // only on demand so by default it is not visible + case 250 /* ImportClause */: + case 251 /* NamespaceImport */: + case 253 /* ImportSpecifier */: + return false; + // Type parameters are always visible + case 150 /* TypeParameter */: + // Source file and namespace export are always visible + case 279 /* SourceFile */: + case 247 /* NamespaceExportDeclaration */: + return true; + // Export assignments do not create name bindings outside the module + case 254 /* ExportAssignment */: + return false; + default: + return false; + } + } + } + function collectLinkedAliases(node, setVisibility) { + var exportSymbol; + if (node.parent && node.parent.kind === 254 /* ExportAssignment */) { + exportSymbol = resolveName(node, node.escapedText, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, node, /*isUse*/ false); + } + else if (node.parent.kind === 257 /* ExportSpecifier */) { + exportSymbol = getTargetOfExportSpecifier(node.parent, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); + } + var result; + if (exportSymbol) { + buildVisibleNodeList(exportSymbol.declarations); + } + return result; + function buildVisibleNodeList(declarations) { + ts.forEach(declarations, function (declaration) { + var resultNode = getAnyImportSyntax(declaration) || declaration; + if (setVisibility) { + getNodeLinks(declaration).isVisible = true; + } + else { + result = result || []; + ts.pushIfUnique(result, resultNode); + } + if (ts.isInternalModuleImportEqualsDeclaration(declaration)) { + // Add the referenced top container visible + var internalModuleReference = declaration.moduleReference; + var firstIdentifier = getFirstIdentifier(internalModuleReference); + var importSymbol = resolveName(declaration, firstIdentifier.escapedText, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */, undefined, undefined, /*isUse*/ false); + if (importSymbol) { + buildVisibleNodeList(importSymbol.declarations); + } + } + }); + } + } + /** + * Push an entry on the type resolution stack. If an entry with the given target and the given property name + * is already on the stack, and no entries in between already have a type, then a circularity has occurred. + * In this case, the result values of the existing entry and all entries pushed after it are changed to false, + * and the value false is returned. Otherwise, the new entry is just pushed onto the stack, and true is returned. + * In order to see if the same query has already been done before, the target object and the propertyName both + * must match the one passed in. + * + * @param target The symbol, type, or signature whose type is being queried + * @param propertyName The property name that should be used to query the target for its type + */ + function pushTypeResolution(target, propertyName) { + var resolutionCycleStartIndex = findResolutionCycleStartIndex(target, propertyName); + if (resolutionCycleStartIndex >= 0) { + // A cycle was found + var length_2 = resolutionTargets.length; + for (var i = resolutionCycleStartIndex; i < length_2; i++) { + resolutionResults[i] = false; + } + return false; + } + resolutionTargets.push(target); + resolutionResults.push(/*items*/ true); + resolutionPropertyNames.push(propertyName); + return true; + } + function findResolutionCycleStartIndex(target, propertyName) { + for (var i = resolutionTargets.length - 1; i >= 0; i--) { + if (hasType(resolutionTargets[i], resolutionPropertyNames[i])) { + return -1; + } + if (resolutionTargets[i] === target && resolutionPropertyNames[i] === propertyName) { + return i; + } + } + return -1; + } + function hasType(target, propertyName) { + switch (propertyName) { + case 0 /* Type */: + return !!getSymbolLinks(target).type; + case 5 /* EnumTagType */: + return !!(getNodeLinks(target).resolvedEnumType); + case 2 /* DeclaredType */: + return !!getSymbolLinks(target).declaredType; + case 1 /* ResolvedBaseConstructorType */: + return !!target.resolvedBaseConstructorType; + case 3 /* ResolvedReturnType */: + return !!target.resolvedReturnType; + case 4 /* ImmediateBaseConstraint */: + return !!target.immediateBaseConstraint; + case 6 /* JSDocTypeReference */: + return !!getSymbolLinks(target).resolvedJSDocType; + } + return ts.Debug.assertNever(propertyName); + } + // Pop an entry from the type resolution stack and return its associated result value. The result value will + // be true if no circularities were detected, or false if a circularity was found. + function popTypeResolution() { + resolutionTargets.pop(); + resolutionPropertyNames.pop(); + return resolutionResults.pop(); + } + function getDeclarationContainer(node) { + return ts.findAncestor(ts.getRootDeclaration(node), function (node) { + switch (node.kind) { + case 237 /* VariableDeclaration */: + case 238 /* VariableDeclarationList */: + case 253 /* ImportSpecifier */: + case 252 /* NamedImports */: + case 251 /* NamespaceImport */: + case 250 /* ImportClause */: + return false; + default: + return true; + } + }).parent; + } + function getTypeOfPrototypeProperty(prototype) { + // TypeScript 1.0 spec (April 2014): 8.4 + // Every class automatically contains a static property member named 'prototype', + // the type of which is an instantiation of the class type with type Any supplied as a type argument for each type parameter. + // It is an error to explicitly declare a static property member with the name 'prototype'. + var classType = getDeclaredTypeOfSymbol(getParentOfSymbol(prototype)); + return classType.typeParameters ? createTypeReference(classType, ts.map(classType.typeParameters, function (_) { return anyType; })) : classType; + } + // Return the type of the given property in the given type, or undefined if no such property exists + function getTypeOfPropertyOfType(type, name) { + var prop = getPropertyOfType(type, name); + return prop ? getTypeOfSymbol(prop) : undefined; + } + function isTypeAny(type) { + return type && (type.flags & 1 /* Any */) !== 0; + } + // Return the type of a binding element parent. We check SymbolLinks first to see if a type has been + // assigned by contextual typing. + function getTypeForBindingElementParent(node) { + var symbol = getSymbolOfNode(node); + return symbol && getSymbolLinks(symbol).type || getTypeForVariableLikeDeclaration(node, /*includeOptionality*/ false); + } + function isComputedNonLiteralName(name) { + return name.kind === 149 /* ComputedPropertyName */ && !ts.isStringOrNumericLiteralLike(name.expression); + } + function getRestType(source, properties, symbol) { + source = filterType(source, function (t) { return !(t.flags & 98304 /* Nullable */); }); + if (source.flags & 131072 /* Never */) { + return emptyObjectType; + } + if (source.flags & 1048576 /* Union */) { + return mapType(source, function (t) { return getRestType(t, properties, symbol); }); + } + var omitKeyType = getUnionType(ts.map(properties, getLiteralTypeFromPropertyName)); + if (isGenericObjectType(source) || isGenericIndexType(omitKeyType)) { + if (omitKeyType.flags & 131072 /* Never */) { + return source; + } + var pickTypeAlias = getGlobalPickSymbol(); + var excludeTypeAlias = getGlobalExcludeSymbol(); + if (!pickTypeAlias || !excludeTypeAlias) { + return errorType; + } + var pickKeys = getTypeAliasInstantiation(excludeTypeAlias, [getIndexType(source), omitKeyType]); + return getTypeAliasInstantiation(pickTypeAlias, [source, pickKeys]); + } + var members = ts.createSymbolTable(); + for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) { + var prop = _a[_i]; + if (!isTypeAssignableTo(getLiteralTypeFromProperty(prop, 8576 /* StringOrNumberLiteralOrUnique */), omitKeyType) + && !(ts.getDeclarationModifierFlagsFromSymbol(prop) & (8 /* Private */ | 16 /* Protected */)) + && isSpreadableProperty(prop)) { + members.set(prop.escapedName, getSpreadSymbol(prop)); + } + } + var stringIndexInfo = getIndexInfoOfType(source, 0 /* String */); + var numberIndexInfo = getIndexInfoOfType(source, 1 /* Number */); + return createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); + } + /** Return the inferred type for a binding element */ + function getTypeForBindingElement(declaration) { + var pattern = declaration.parent; + var parentType = getTypeForBindingElementParent(pattern.parent); + // If parent has the unknown (error) type, then so does this binding element + if (parentType === errorType) { + return errorType; + } + // If no type was specified or inferred for parent, + // infer from the initializer of the binding element if one is present. + // Otherwise, go with the undefined type of the parent. + if (!parentType) { + return declaration.initializer ? checkDeclarationInitializer(declaration) : parentType; + } + if (isTypeAny(parentType)) { + return parentType; + } + // Relax null check on ambient destructuring parameters, since the parameters have no implementation and are just documentation + if (strictNullChecks && declaration.flags & 4194304 /* Ambient */ && ts.isParameterDeclaration(declaration)) { + parentType = getNonNullableType(parentType); + } + var type; + if (pattern.kind === 184 /* ObjectBindingPattern */) { + if (declaration.dotDotDotToken) { + if (parentType.flags & 2 /* Unknown */ || !isValidSpreadType(parentType)) { + error(declaration, ts.Diagnostics.Rest_types_may_only_be_created_from_object_types); + return errorType; + } + var literalMembers = []; + for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (!element.dotDotDotToken) { + literalMembers.push(element.propertyName || element.name); + } + } + type = getRestType(parentType, literalMembers, declaration.symbol); + } + else { + // Use explicitly specified property name ({ p: xxx } form), or otherwise the implied name ({ p } form) + var name = declaration.propertyName || declaration.name; + var exprType = getLiteralTypeFromPropertyName(name); + var declaredType = checkIndexedAccessIndexType(getIndexedAccessType(parentType, exprType, name), name); + type = getFlowTypeOfReference(declaration, getConstraintForLocation(declaredType, declaration.name)); + } + } + else { + // This elementType will be used if the specific property corresponding to this index is not + // present (aka the tuple element property). This call also checks that the parentType is in + // fact an iterable or array (depending on target language). + var elementType = checkIteratedTypeOrElementType(parentType, pattern, /*allowStringInput*/ false, /*allowAsyncIterables*/ false); + var index_1 = pattern.elements.indexOf(declaration); + if (declaration.dotDotDotToken) { + // If the parent is a tuple type, the rest element has a tuple type of the + // remaining tuple element types. Otherwise, the rest element has an array type with same + // element type as the parent type. + type = everyType(parentType, isTupleType) ? + mapType(parentType, function (t) { return sliceTupleType(t, index_1); }) : + createArrayType(elementType); + } + else { + // Use specific property type when parent is a tuple or numeric index type when parent is an array + var index_2 = pattern.elements.indexOf(declaration); + type = everyType(parentType, isTupleLikeType) ? + getTupleElementType(parentType, index_2) || declaration.initializer && checkDeclarationInitializer(declaration) : + elementType; + if (!type) { + if (isTupleType(parentType)) { + error(declaration, ts.Diagnostics.Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2, typeToString(parentType), getTypeReferenceArity(parentType), pattern.elements.length); + } + else { + error(declaration, ts.Diagnostics.Type_0_has_no_property_1, typeToString(parentType), "" + index_2); + } + return errorType; + } + } + } + // In strict null checking mode, if a default value of a non-undefined type is specified, remove + // undefined from the final type. + if (strictNullChecks && declaration.initializer && !(getFalsyFlags(checkDeclarationInitializer(declaration)) & 32768 /* Undefined */)) { + type = getTypeWithFacts(type, 524288 /* NEUndefined */); + } + return declaration.initializer && !ts.getEffectiveTypeAnnotationNode(ts.walkUpBindingElementsAndPatterns(declaration)) ? + getUnionType([type, checkDeclarationInitializer(declaration)], 2 /* Subtype */) : + type; + } + function getTypeForDeclarationFromJSDocComment(declaration) { + var jsdocType = ts.getJSDocType(declaration); + if (jsdocType) { + return getTypeFromTypeNode(jsdocType); + } + return undefined; + } + function isNullOrUndefined(node) { + var expr = ts.skipParentheses(node); + return expr.kind === 96 /* NullKeyword */ || expr.kind === 72 /* Identifier */ && getResolvedSymbol(expr) === undefinedSymbol; + } + function isEmptyArrayLiteral(node) { + var expr = ts.skipParentheses(node); + return expr.kind === 187 /* ArrayLiteralExpression */ && expr.elements.length === 0; + } + function addOptionality(type, optional) { + if (optional === void 0) { optional = true; } + return strictNullChecks && optional ? getOptionalType(type) : type; + } + // Return the inferred type for a variable, parameter, or property declaration + function getTypeForVariableLikeDeclaration(declaration, includeOptionality) { + // A variable declared in a for..in statement is of type string, or of type keyof T when the + // right hand expression is of a type parameter type. + if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 226 /* ForInStatement */) { + var indexType = getIndexType(getNonNullableTypeIfNeeded(checkExpression(declaration.parent.parent.expression))); + return indexType.flags & (262144 /* TypeParameter */ | 4194304 /* Index */) ? getExtractStringType(indexType) : stringType; + } + if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 227 /* ForOfStatement */) { + // checkRightHandSideOfForOf will return undefined if the for-of expression type was + // missing properties/signatures required to get its iteratedType (like + // [Symbol.iterator] or next). This may be because we accessed properties from anyType, + // or it may have led to an error inside getElementTypeOfIterable. + var forOfStatement = declaration.parent.parent; + return checkRightHandSideOfForOf(forOfStatement.expression, forOfStatement.awaitModifier) || anyType; + } + if (ts.isBindingPattern(declaration.parent)) { + return getTypeForBindingElement(declaration); + } + var isOptional = includeOptionality && (ts.isParameter(declaration) && isJSDocOptionalParameter(declaration) + || !ts.isBindingElement(declaration) && !ts.isVariableDeclaration(declaration) && !!declaration.questionToken); + // Use type from type annotation if one is present + var declaredType = tryGetTypeFromEffectiveTypeNode(declaration); + if (declaredType) { + return addOptionality(declaredType, isOptional); + } + if ((noImplicitAny || ts.isInJSFile(declaration)) && + declaration.kind === 237 /* VariableDeclaration */ && !ts.isBindingPattern(declaration.name) && + !(ts.getCombinedModifierFlags(declaration) & 1 /* Export */) && !(declaration.flags & 4194304 /* Ambient */)) { + // If --noImplicitAny is on or the declaration is in a Javascript file, + // use control flow tracked 'any' type for non-ambient, non-exported var or let variables with no + // initializer or a 'null' or 'undefined' initializer. + if (!(ts.getCombinedNodeFlags(declaration) & 2 /* Const */) && (!declaration.initializer || isNullOrUndefined(declaration.initializer))) { + return autoType; + } + // Use control flow tracked 'any[]' type for non-ambient, non-exported variables with an empty array + // literal initializer. + if (declaration.initializer && isEmptyArrayLiteral(declaration.initializer)) { + return autoArrayType; + } + } + if (declaration.kind === 151 /* Parameter */) { + var func = declaration.parent; + // For a parameter of a set accessor, use the type of the get accessor if one is present + if (func.kind === 159 /* SetAccessor */ && !hasNonBindableDynamicName(func)) { + var getter = ts.getDeclarationOfKind(getSymbolOfNode(declaration.parent), 158 /* GetAccessor */); + if (getter) { + var getterSignature = getSignatureFromDeclaration(getter); + var thisParameter = getAccessorThisParameter(func); + if (thisParameter && declaration === thisParameter) { + // Use the type from the *getter* + ts.Debug.assert(!thisParameter.type); + return getTypeOfSymbol(getterSignature.thisParameter); + } + return getReturnTypeOfSignature(getterSignature); + } + } + if (ts.isInJSFile(declaration)) { + var typeTag = ts.getJSDocType(func); + if (typeTag && ts.isFunctionTypeNode(typeTag)) { + return getTypeAtPosition(getSignatureFromDeclaration(typeTag), func.parameters.indexOf(declaration)); + } + } + // Use contextual parameter type if one is available + var type = declaration.symbol.escapedName === "this" /* This */ ? getContextualThisParameterType(func) : getContextuallyTypedParameterType(declaration); + if (type) { + return addOptionality(type, isOptional); + } + } + else if (ts.isInJSFile(declaration)) { + var containerObjectType = getJSContainerObjectType(declaration, getSymbolOfNode(declaration), ts.getDeclaredExpandoInitializer(declaration)); + if (containerObjectType) { + return containerObjectType; + } + } + // Use the type of the initializer expression if one is present + if (declaration.initializer) { + var type = checkDeclarationInitializer(declaration); + return addOptionality(type, isOptional); + } + if (ts.isJsxAttribute(declaration)) { + // if JSX attribute doesn't have initializer, by default the attribute will have boolean value of true. + // I.e is sugar for + return trueType; + } + // If the declaration specifies a binding pattern, use the type implied by the binding pattern + if (ts.isBindingPattern(declaration.name)) { + return getTypeFromBindingPattern(declaration.name, /*includePatternInType*/ false, /*reportErrors*/ true); + } + // No type specified and nothing can be inferred + return undefined; + } + function getWidenedTypeFromAssignmentDeclaration(symbol, resolvedSymbol) { + // function/class/{} initializers are themselves containers, so they won't merge in the same way as other initializers + var container = ts.getAssignedExpandoInitializer(symbol.valueDeclaration); + if (container) { + var tag = ts.getJSDocTypeTag(container); + if (tag && tag.typeExpression) { + return getTypeFromTypeNode(tag.typeExpression); + } + var containerObjectType = getJSContainerObjectType(symbol.valueDeclaration, symbol, container); + return containerObjectType || getWidenedLiteralType(checkExpressionCached(container)); + } + var definedInConstructor = false; + var definedInMethod = false; + var jsdocType; + var types; + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + var expression = (ts.isBinaryExpression(declaration) || ts.isCallExpression(declaration)) ? declaration : + ts.isPropertyAccessExpression(declaration) ? ts.isBinaryExpression(declaration.parent) ? declaration.parent : declaration : + undefined; + if (!expression) { + return errorType; + } + var kind = ts.isPropertyAccessExpression(expression) ? ts.getAssignmentDeclarationPropertyAccessKind(expression) : ts.getAssignmentDeclarationKind(expression); + if (kind === 4 /* ThisProperty */) { + if (isDeclarationInConstructor(expression)) { + definedInConstructor = true; + } + else { + definedInMethod = true; + } + } + if (!ts.isCallExpression(expression)) { + jsdocType = getJSDocTypeFromAssignmentDeclaration(jsdocType, expression, symbol, declaration); + } + if (!jsdocType) { + (types || (types = [])).push((ts.isBinaryExpression(expression) || ts.isCallExpression(expression)) ? getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) : neverType); + } + } + var type = jsdocType; + if (!type) { + var constructorTypes = definedInConstructor ? getConstructorDefinedThisAssignmentTypes(types, symbol.declarations) : undefined; + // use only the constructor types unless they were only assigned null | undefined (including widening variants) + if (definedInMethod) { + var propType = getTypeOfAssignmentDeclarationPropertyOfBaseType(symbol); + if (propType) { + (constructorTypes || (constructorTypes = [])).push(propType); + definedInConstructor = true; + } + } + var sourceTypes = ts.some(constructorTypes, function (t) { return !!(t.flags & ~(98304 /* Nullable */ | 134217728 /* ContainsWideningType */)); }) ? constructorTypes : types; // TODO: GH#18217 + type = getUnionType(sourceTypes, 2 /* Subtype */); + } + var widened = getWidenedType(addOptionality(type, definedInMethod && !definedInConstructor)); + if (filterType(widened, function (t) { return !!(t.flags & ~98304 /* Nullable */); }) === neverType) { + reportImplicitAny(symbol.valueDeclaration, anyType); + return anyType; + } + return widened; + } + function getJSContainerObjectType(decl, symbol, init) { + if (!ts.isInJSFile(decl) || !init || !ts.isObjectLiteralExpression(init) || init.properties.length) { + return undefined; + } + var exports = ts.createSymbolTable(); + while (ts.isBinaryExpression(decl) || ts.isPropertyAccessExpression(decl)) { + var s_1 = getSymbolOfNode(decl); + if (s_1 && ts.hasEntries(s_1.exports)) { + mergeSymbolTable(exports, s_1.exports); + } + decl = ts.isBinaryExpression(decl) ? decl.parent : decl.parent.parent; + } + var s = getSymbolOfNode(decl); + if (s && ts.hasEntries(s.exports)) { + mergeSymbolTable(exports, s.exports); + } + var type = createAnonymousType(symbol, exports, ts.emptyArray, ts.emptyArray, undefined, undefined); + type.objectFlags |= 16384 /* JSLiteral */; + return type; + } + function getJSDocTypeFromAssignmentDeclaration(declaredType, expression, _symbol, declaration) { + var typeNode = ts.getJSDocType(expression.parent); + if (typeNode) { + var type = getWidenedType(getTypeFromTypeNode(typeNode)); + if (!declaredType) { + return type; + } + else if (declaredType !== errorType && type !== errorType && !isTypeIdenticalTo(declaredType, type)) { + errorNextVariableOrPropertyDeclarationMustHaveSameType(declaredType, declaration, type); + } + } + return declaredType; + } + /** If we don't have an explicit JSDoc type, get the type from the initializer. */ + function getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) { + if (ts.isCallExpression(expression)) { + if (resolvedSymbol) { + return getTypeOfSymbol(resolvedSymbol); // This shouldn't happen except under some hopefully forbidden merges of export assignments and object define assignments + } + var objectLitType = checkExpressionCached(expression.arguments[2]); + var valueType = getTypeOfPropertyOfType(objectLitType, "value"); + if (valueType) { + return valueType; + } + var getFunc = getTypeOfPropertyOfType(objectLitType, "get"); + if (getFunc) { + var getSig = getSingleCallSignature(getFunc); + if (getSig) { + return getReturnTypeOfSignature(getSig); + } + } + var setFunc = getTypeOfPropertyOfType(objectLitType, "set"); + if (setFunc) { + var setSig = getSingleCallSignature(setFunc); + if (setSig) { + return getTypeOfFirstParameterOfSignature(setSig); + } + } + return anyType; + } + var type = resolvedSymbol ? getTypeOfSymbol(resolvedSymbol) : getWidenedLiteralType(checkExpressionCached(expression.right)); + if (type.flags & 524288 /* Object */ && + kind === 2 /* ModuleExports */ && + symbol.escapedName === "export=" /* ExportEquals */) { + var exportedType_1 = resolveStructuredTypeMembers(type); + var members_3 = ts.createSymbolTable(); + ts.copyEntries(exportedType_1.members, members_3); + if (resolvedSymbol && !resolvedSymbol.exports) { + resolvedSymbol.exports = ts.createSymbolTable(); + } + (resolvedSymbol || symbol).exports.forEach(function (s, name) { + if (members_3.has(name)) { + var exportedMember = exportedType_1.members.get(name); + var union = createSymbol(s.flags | exportedMember.flags, name); + union.type = getUnionType([getTypeOfSymbol(s), getTypeOfSymbol(exportedMember)]); + members_3.set(name, union); + } + else { + members_3.set(name, s); + } + }); + var result = createAnonymousType(exportedType_1.symbol, members_3, exportedType_1.callSignatures, exportedType_1.constructSignatures, exportedType_1.stringIndexInfo, exportedType_1.numberIndexInfo); + result.objectFlags |= (ts.getObjectFlags(type) & 16384 /* JSLiteral */); // Propagate JSLiteral flag + return result; + } + if (isEmptyArrayLiteralType(type)) { + reportImplicitAny(expression, anyArrayType); + return anyArrayType; + } + return type; + } + function isDeclarationInConstructor(expression) { + var thisContainer = ts.getThisContainer(expression, /*includeArrowFunctions*/ false); + // Properties defined in a constructor (or base constructor, or javascript constructor function) don't get undefined added. + // Function expressions that are assigned to the prototype count as methods. + return thisContainer.kind === 157 /* Constructor */ || + thisContainer.kind === 239 /* FunctionDeclaration */ || + (thisContainer.kind === 196 /* FunctionExpression */ && !ts.isPrototypePropertyAssignment(thisContainer.parent)); + } + function getConstructorDefinedThisAssignmentTypes(types, declarations) { + ts.Debug.assert(types.length === declarations.length); + return types.filter(function (_, i) { + var declaration = declarations[i]; + var expression = ts.isBinaryExpression(declaration) ? declaration : + ts.isBinaryExpression(declaration.parent) ? declaration.parent : undefined; + return expression && isDeclarationInConstructor(expression); + }); + } + /** check for definition in base class if any declaration is in a class */ + function getTypeOfAssignmentDeclarationPropertyOfBaseType(property) { + var parentDeclaration = ts.forEach(property.declarations, function (d) { + var parent = ts.getThisContainer(d, /*includeArrowFunctions*/ false).parent; + return ts.isClassLike(parent) && parent; + }); + if (parentDeclaration) { + var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(parentDeclaration)); + var baseClassType = classType && getBaseTypes(classType)[0]; + if (baseClassType) { + return getTypeOfPropertyOfType(baseClassType, property.escapedName); + } + } + } + // Return the type implied by a binding pattern element. This is the type of the initializer of the element if + // one is present. Otherwise, if the element is itself a binding pattern, it is the type implied by the binding + // pattern. Otherwise, it is the type any. + function getTypeFromBindingElement(element, includePatternInType, reportErrors) { + if (element.initializer) { + return addOptionality(checkDeclarationInitializer(element)); + } + if (ts.isBindingPattern(element.name)) { + return getTypeFromBindingPattern(element.name, includePatternInType, reportErrors); + } + if (reportErrors && !declarationBelongsToPrivateAmbientMember(element)) { + reportImplicitAny(element, anyType); + } + return anyType; + } + // Return the type implied by an object binding pattern + function getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) { + var members = ts.createSymbolTable(); + var stringIndexInfo; + var objectFlags = 128 /* ObjectLiteral */; + ts.forEach(pattern.elements, function (e) { + var name = e.propertyName || e.name; + if (isComputedNonLiteralName(name)) { + // do not include computed properties in the implied type + objectFlags |= 512 /* ObjectLiteralPatternWithComputedProperties */; + return; + } + if (e.dotDotDotToken) { + stringIndexInfo = createIndexInfo(anyType, /*isReadonly*/ false); + return; + } + var text = ts.getTextOfPropertyName(name); + var flags = 4 /* Property */ | (e.initializer ? 16777216 /* Optional */ : 0); + var symbol = createSymbol(flags, text); + symbol.type = getTypeFromBindingElement(e, includePatternInType, reportErrors); + symbol.bindingElement = e; + members.set(symbol.escapedName, symbol); + }); + var result = createAnonymousType(undefined, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, undefined); + result.flags |= 268435456 /* ContainsObjectLiteral */; + result.objectFlags |= objectFlags; + if (includePatternInType) { + result.pattern = pattern; + } + return result; + } + // Return the type implied by an array binding pattern + function getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors) { + var elements = pattern.elements; + var lastElement = ts.lastOrUndefined(elements); + var hasRestElement = !!(lastElement && lastElement.kind === 186 /* BindingElement */ && lastElement.dotDotDotToken); + if (elements.length === 0 || elements.length === 1 && hasRestElement) { + return languageVersion >= 2 /* ES2015 */ ? createIterableType(anyType) : anyArrayType; + } + var elementTypes = ts.map(elements, function (e) { return ts.isOmittedExpression(e) ? anyType : getTypeFromBindingElement(e, includePatternInType, reportErrors); }); + var minLength = ts.findLastIndex(elements, function (e) { return !ts.isOmittedExpression(e) && !hasDefaultValue(e); }, elements.length - (hasRestElement ? 2 : 1)) + 1; + var result = createTupleType(elementTypes, minLength, hasRestElement); + if (includePatternInType) { + result = cloneTypeReference(result); + result.pattern = pattern; + } + return result; + } + // Return the type implied by a binding pattern. This is the type implied purely by the binding pattern itself + // and without regard to its context (i.e. without regard any type annotation or initializer associated with the + // declaration in which the binding pattern is contained). For example, the implied type of [x, y] is [any, any] + // and the implied type of { x, y: z = 1 } is { x: any; y: number; }. The type implied by a binding pattern is + // used as the contextual type of an initializer associated with the binding pattern. Also, for a destructuring + // parameter with no type annotation or initializer, the type implied by the binding pattern becomes the type of + // the parameter. + function getTypeFromBindingPattern(pattern, includePatternInType, reportErrors) { + if (includePatternInType === void 0) { includePatternInType = false; } + if (reportErrors === void 0) { reportErrors = false; } + return pattern.kind === 184 /* ObjectBindingPattern */ + ? getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) + : getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors); + } + // Return the type associated with a variable, parameter, or property declaration. In the simple case this is the type + // specified in a type annotation or inferred from an initializer. However, in the case of a destructuring declaration it + // is a bit more involved. For example: + // + // var [x, s = ""] = [1, "one"]; + // + // Here, the array literal [1, "one"] is contextually typed by the type [any, string], which is the implied type of the + // binding pattern [x, s = ""]. Because the contextual type is a tuple type, the resulting type of [1, "one"] is the + // tuple type [number, string]. Thus, the type inferred for 'x' is number and the type inferred for 's' is string. + function getWidenedTypeForVariableLikeDeclaration(declaration, reportErrors) { + return widenTypeForVariableLikeDeclaration(getTypeForVariableLikeDeclaration(declaration, /*includeOptionality*/ true), declaration, reportErrors); + } + function widenTypeForVariableLikeDeclaration(type, declaration, reportErrors) { + if (type) { + if (reportErrors) { + reportErrorsFromWidening(declaration, type); + } + // always widen a 'unique symbol' type if the type was created for a different declaration. + if (type.flags & 8192 /* UniqueESSymbol */ && (ts.isBindingElement(declaration) || !declaration.type) && type.symbol !== getSymbolOfNode(declaration)) { + type = esSymbolType; + } + return getWidenedType(type); + } + // Rest parameters default to type any[], other parameters default to type any + type = ts.isParameter(declaration) && declaration.dotDotDotToken ? anyArrayType : anyType; + // Report implicit any errors unless this is a private property within an ambient declaration + if (reportErrors) { + if (!declarationBelongsToPrivateAmbientMember(declaration)) { + reportImplicitAny(declaration, type); + } + } + return type; + } + function declarationBelongsToPrivateAmbientMember(declaration) { + var root = ts.getRootDeclaration(declaration); + var memberDeclaration = root.kind === 151 /* Parameter */ ? root.parent : root; + return isPrivateWithinAmbient(memberDeclaration); + } + function tryGetTypeFromEffectiveTypeNode(declaration) { + var typeNode = ts.getEffectiveTypeAnnotationNode(declaration); + if (typeNode) { + return getTypeFromTypeNode(typeNode); + } + } + function getTypeOfVariableOrParameterOrProperty(symbol) { + var links = getSymbolLinks(symbol); + return links.type || (links.type = getTypeOfVariableOrParameterOrPropertyWorker(symbol)); + } + function getTypeOfVariableOrParameterOrPropertyWorker(symbol) { + // Handle prototype property + if (symbol.flags & 4194304 /* Prototype */) { + return getTypeOfPrototypeProperty(symbol); + } + // CommonsJS require and module both have type any. + if (symbol === requireSymbol) { + return anyType; + } + if (symbol.flags & 134217728 /* ModuleExports */) { + var fileSymbol = getSymbolOfNode(ts.getSourceFileOfNode(symbol.valueDeclaration)); + var members = ts.createSymbolTable(); + members.set("exports", fileSymbol); + return createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, undefined, undefined); + } + // Handle catch clause variables + var declaration = symbol.valueDeclaration; + if (ts.isCatchClauseVariableDeclarationOrBindingElement(declaration)) { + return anyType; + } + // Handle export default expressions + if (ts.isSourceFile(declaration)) { + var jsonSourceFile = ts.cast(declaration, ts.isJsonSourceFile); + if (!jsonSourceFile.statements.length) { + return emptyObjectType; + } + var type_1 = getWidenedLiteralType(checkExpression(jsonSourceFile.statements[0].expression)); + if (type_1.flags & 524288 /* Object */) { + return getRegularTypeOfObjectLiteral(type_1); + } + return type_1; + } + if (declaration.kind === 254 /* ExportAssignment */) { + return widenTypeForVariableLikeDeclaration(checkExpressionCached(declaration.expression), declaration); + } + // Handle variable, parameter or property + if (!pushTypeResolution(symbol, 0 /* Type */)) { + return errorType; + } + var type; + if (ts.isInJSFile(declaration) && + (ts.isCallExpression(declaration) || ts.isBinaryExpression(declaration) || ts.isPropertyAccessExpression(declaration) && ts.isBinaryExpression(declaration.parent))) { + type = getWidenedTypeFromAssignmentDeclaration(symbol); + } + else if (ts.isJSDocPropertyLikeTag(declaration) + || ts.isPropertyAccessExpression(declaration) + || ts.isIdentifier(declaration) + || ts.isClassDeclaration(declaration) + || ts.isFunctionDeclaration(declaration) + || (ts.isMethodDeclaration(declaration) && !ts.isObjectLiteralMethod(declaration)) + || ts.isMethodSignature(declaration)) { + // Symbol is property of some kind that is merged with something - should use `getTypeOfFuncClassEnumModule` and not `getTypeOfVariableOrParameterOrProperty` + if (symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 384 /* Enum */ | 512 /* ValueModule */)) { + return getTypeOfFuncClassEnumModule(symbol); + } + type = ts.isBinaryExpression(declaration.parent) ? + getWidenedTypeFromAssignmentDeclaration(symbol) : + tryGetTypeFromEffectiveTypeNode(declaration) || anyType; + } + else if (ts.isPropertyAssignment(declaration)) { + type = tryGetTypeFromEffectiveTypeNode(declaration) || checkPropertyAssignment(declaration); + } + else if (ts.isJsxAttribute(declaration)) { + type = tryGetTypeFromEffectiveTypeNode(declaration) || checkJsxAttribute(declaration); + } + else if (ts.isShorthandPropertyAssignment(declaration)) { + type = tryGetTypeFromEffectiveTypeNode(declaration) || checkExpressionForMutableLocation(declaration.name, 0 /* Normal */); + } + else if (ts.isObjectLiteralMethod(declaration)) { + type = tryGetTypeFromEffectiveTypeNode(declaration) || checkObjectLiteralMethod(declaration, 0 /* Normal */); + } + else if (ts.isParameter(declaration) + || ts.isPropertyDeclaration(declaration) + || ts.isPropertySignature(declaration) + || ts.isVariableDeclaration(declaration) + || ts.isBindingElement(declaration)) { + type = getWidenedTypeForVariableLikeDeclaration(declaration, /*includeOptionality*/ true); + } + // getTypeOfSymbol dispatches some JS merges incorrectly because their symbol flags are not mutually exclusive. + // Re-dispatch based on valueDeclaration.kind instead. + else if (ts.isEnumDeclaration(declaration)) { + type = getTypeOfFuncClassEnumModule(symbol); + } + else if (ts.isEnumMember(declaration)) { + type = getTypeOfEnumMember(symbol); + } + else { + return ts.Debug.fail("Unhandled declaration kind! " + ts.Debug.showSyntaxKind(declaration) + " for " + ts.Debug.showSymbol(symbol)); + } + if (!popTypeResolution()) { + type = reportCircularityError(symbol); + } + return type; + } + function getAnnotatedAccessorTypeNode(accessor) { + if (accessor) { + if (accessor.kind === 158 /* GetAccessor */) { + var getterTypeAnnotation = ts.getEffectiveReturnTypeNode(accessor); + return getterTypeAnnotation; + } + else { + var setterTypeAnnotation = ts.getEffectiveSetAccessorTypeAnnotationNode(accessor); + return setterTypeAnnotation; + } + } + return undefined; + } + function getAnnotatedAccessorType(accessor) { + var node = getAnnotatedAccessorTypeNode(accessor); + return node && getTypeFromTypeNode(node); + } + function getAnnotatedAccessorThisParameter(accessor) { + var parameter = getAccessorThisParameter(accessor); + return parameter && parameter.symbol; + } + function getThisTypeOfDeclaration(declaration) { + return getThisTypeOfSignature(getSignatureFromDeclaration(declaration)); + } + function getTypeOfAccessors(symbol) { + var links = getSymbolLinks(symbol); + return links.type || (links.type = getTypeOfAccessorsWorker(symbol)); + } + function getTypeOfAccessorsWorker(symbol) { + var getter = ts.getDeclarationOfKind(symbol, 158 /* GetAccessor */); + var setter = ts.getDeclarationOfKind(symbol, 159 /* SetAccessor */); + if (getter && ts.isInJSFile(getter)) { + var jsDocType = getTypeForDeclarationFromJSDocComment(getter); + if (jsDocType) { + return jsDocType; + } + } + if (!pushTypeResolution(symbol, 0 /* Type */)) { + return errorType; + } + var type; + // First try to see if the user specified a return type on the get-accessor. + var getterReturnType = getAnnotatedAccessorType(getter); + if (getterReturnType) { + type = getterReturnType; + } + else { + // If the user didn't specify a return type, try to use the set-accessor's parameter type. + var setterParameterType = getAnnotatedAccessorType(setter); + if (setterParameterType) { + type = setterParameterType; + } + else { + // If there are no specified types, try to infer it from the body of the get accessor if it exists. + if (getter && getter.body) { + type = getReturnTypeFromBody(getter); + } + // Otherwise, fall back to 'any'. + else { + if (setter) { + errorOrSuggestion(noImplicitAny, setter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation, symbolToString(symbol)); + } + else { + ts.Debug.assert(!!getter, "there must existed getter as we are current checking either setter or getter in this function"); + errorOrSuggestion(noImplicitAny, getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); + } + type = anyType; + } + } + } + if (!popTypeResolution()) { + type = anyType; + if (noImplicitAny) { + var getter_1 = ts.getDeclarationOfKind(symbol, 158 /* GetAccessor */); + error(getter_1, ts.Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, symbolToString(symbol)); + } + } + return type; + } + function getBaseTypeVariableOfClass(symbol) { + var baseConstructorType = getBaseConstructorTypeOfClass(getDeclaredTypeOfClassOrInterface(symbol)); + return baseConstructorType.flags & 8650752 /* TypeVariable */ ? baseConstructorType : undefined; + } + function getTypeOfFuncClassEnumModule(symbol) { + var links = getSymbolLinks(symbol); + var originalLinks = links; + if (!links.type) { + var jsDeclaration = ts.getDeclarationOfExpando(symbol.valueDeclaration); + if (jsDeclaration) { + var jsSymbol = getSymbolOfNode(jsDeclaration); + if (jsSymbol && (ts.hasEntries(jsSymbol.exports) || ts.hasEntries(jsSymbol.members))) { + symbol = cloneSymbol(symbol); + // note:we overwrite links because we just cloned the symbol + links = symbol; + if (ts.hasEntries(jsSymbol.exports)) { + symbol.exports = symbol.exports || ts.createSymbolTable(); + mergeSymbolTable(symbol.exports, jsSymbol.exports); + } + if (ts.hasEntries(jsSymbol.members)) { + symbol.members = symbol.members || ts.createSymbolTable(); + mergeSymbolTable(symbol.members, jsSymbol.members); + } + } + } + originalLinks.type = links.type = getTypeOfFuncClassEnumModuleWorker(symbol); + } + return links.type; + } + function getTypeOfFuncClassEnumModuleWorker(symbol) { + var declaration = symbol.valueDeclaration; + if (symbol.flags & 1536 /* Module */ && ts.isShorthandAmbientModuleSymbol(symbol)) { + return anyType; + } + else if (declaration.kind === 204 /* BinaryExpression */ || + declaration.kind === 189 /* PropertyAccessExpression */ && declaration.parent.kind === 204 /* BinaryExpression */) { + return getWidenedTypeFromAssignmentDeclaration(symbol); + } + else if (symbol.flags & 512 /* ValueModule */ && declaration && ts.isSourceFile(declaration) && declaration.commonJsModuleIndicator) { + var resolvedModule = resolveExternalModuleSymbol(symbol); + if (resolvedModule !== symbol) { + if (!pushTypeResolution(symbol, 0 /* Type */)) { + return errorType; + } + var exportEquals = getMergedSymbol(symbol.exports.get("export=" /* ExportEquals */)); + var type_2 = getWidenedTypeFromAssignmentDeclaration(exportEquals, exportEquals === resolvedModule ? undefined : resolvedModule); + if (!popTypeResolution()) { + return reportCircularityError(symbol); + } + return type_2; + } + } + var type = createObjectType(16 /* Anonymous */, symbol); + if (symbol.flags & 32 /* Class */) { + var baseTypeVariable = getBaseTypeVariableOfClass(symbol); + return baseTypeVariable ? getIntersectionType([type, baseTypeVariable]) : type; + } + else { + return strictNullChecks && symbol.flags & 16777216 /* Optional */ ? getOptionalType(type) : type; + } + } + function getTypeOfEnumMember(symbol) { + var links = getSymbolLinks(symbol); + return links.type || (links.type = getDeclaredTypeOfEnumMember(symbol)); + } + function getTypeOfAlias(symbol) { + var links = getSymbolLinks(symbol); + if (!links.type) { + var targetSymbol = resolveAlias(symbol); + // It only makes sense to get the type of a value symbol. If the result of resolving + // the alias is not a value, then it has no type. To get the type associated with a + // type symbol, call getDeclaredTypeOfSymbol. + // This check is important because without it, a call to getTypeOfSymbol could end + // up recursively calling getTypeOfAlias, causing a stack overflow. + links.type = targetSymbol.flags & 67220415 /* Value */ + ? getTypeOfSymbol(targetSymbol) + : errorType; + } + return links.type; + } + function getTypeOfInstantiatedSymbol(symbol) { + var links = getSymbolLinks(symbol); + if (!links.type) { + if (!pushTypeResolution(symbol, 0 /* Type */)) { + return links.type = errorType; + } + var type = instantiateType(getTypeOfSymbol(links.target), links.mapper); + if (!popTypeResolution()) { + type = reportCircularityError(symbol); + } + links.type = type; + } + return links.type; + } + function reportCircularityError(symbol) { + // Check if variable has type annotation that circularly references the variable itself + if (ts.getEffectiveTypeAnnotationNode(symbol.valueDeclaration)) { + error(symbol.valueDeclaration, ts.Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_type_annotation, symbolToString(symbol)); + return errorType; + } + // Otherwise variable has initializer that circularly references the variable itself + if (noImplicitAny) { + error(symbol.valueDeclaration, ts.Diagnostics._0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer, symbolToString(symbol)); + } + return anyType; + } + function getTypeOfSymbol(symbol) { + if (ts.getCheckFlags(symbol) & 1 /* Instantiated */) { + return getTypeOfInstantiatedSymbol(symbol); + } + if (ts.getCheckFlags(symbol) & 2048 /* ReverseMapped */) { + return getTypeOfReverseMappedSymbol(symbol); + } + if (symbol.flags & (3 /* Variable */ | 4 /* Property */)) { + return getTypeOfVariableOrParameterOrProperty(symbol); + } + if (symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 384 /* Enum */ | 512 /* ValueModule */)) { + return getTypeOfFuncClassEnumModule(symbol); + } + if (symbol.flags & 8 /* EnumMember */) { + return getTypeOfEnumMember(symbol); + } + if (symbol.flags & 98304 /* Accessor */) { + return getTypeOfAccessors(symbol); + } + if (symbol.flags & 2097152 /* Alias */) { + return getTypeOfAlias(symbol); + } + return errorType; + } + function isReferenceToType(type, target) { + return type !== undefined + && target !== undefined + && (ts.getObjectFlags(type) & 4 /* Reference */) !== 0 + && type.target === target; + } + function getTargetType(type) { + return ts.getObjectFlags(type) & 4 /* Reference */ ? type.target : type; + } + // TODO: GH#18217 If `checkBase` is undefined, we should not call this because this will always return false. + function hasBaseType(type, checkBase) { + return check(type); + function check(type) { + if (ts.getObjectFlags(type) & (3 /* ClassOrInterface */ | 4 /* Reference */)) { + var target = getTargetType(type); + return target === checkBase || ts.some(getBaseTypes(target), check); + } + else if (type.flags & 2097152 /* Intersection */) { + return ts.some(type.types, check); + } + return false; + } + } + // Appends the type parameters given by a list of declarations to a set of type parameters and returns the resulting set. + // The function allocates a new array if the input type parameter set is undefined, but otherwise it modifies the set + // in-place and returns the same array. + function appendTypeParameters(typeParameters, declarations) { + for (var _i = 0, declarations_2 = declarations; _i < declarations_2.length; _i++) { + var declaration = declarations_2[_i]; + typeParameters = ts.appendIfUnique(typeParameters, getDeclaredTypeOfTypeParameter(getSymbolOfNode(declaration))); + } + return typeParameters; + } + // Return the outer type parameters of a node or undefined if the node has no outer type parameters. + function getOuterTypeParameters(node, includeThisTypes) { + while (true) { + node = node.parent; // TODO: GH#18217 Use SourceFile kind check instead + if (!node) { + return undefined; + } + switch (node.kind) { + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 241 /* InterfaceDeclaration */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 155 /* MethodSignature */: + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + case 289 /* JSDocFunctionType */: + case 239 /* FunctionDeclaration */: + case 156 /* MethodDeclaration */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 242 /* TypeAliasDeclaration */: + case 303 /* JSDocTemplateTag */: + case 304 /* JSDocTypedefTag */: + case 297 /* JSDocCallbackTag */: + case 181 /* MappedType */: + case 175 /* ConditionalType */: + var outerTypeParameters = getOuterTypeParameters(node, includeThisTypes); + if (node.kind === 181 /* MappedType */) { + return ts.append(outerTypeParameters, getDeclaredTypeOfTypeParameter(getSymbolOfNode(node.typeParameter))); + } + else if (node.kind === 175 /* ConditionalType */) { + return ts.concatenate(outerTypeParameters, getInferTypeParameters(node)); + } + var outerAndOwnTypeParameters = appendTypeParameters(outerTypeParameters, ts.getEffectiveTypeParameterDeclarations(node)); + var thisType = includeThisTypes && + (node.kind === 240 /* ClassDeclaration */ || node.kind === 209 /* ClassExpression */ || node.kind === 241 /* InterfaceDeclaration */) && + getDeclaredTypeOfClassOrInterface(getSymbolOfNode(node)).thisType; + return thisType ? ts.append(outerAndOwnTypeParameters, thisType) : outerAndOwnTypeParameters; + } + } + } + // The outer type parameters are those defined by enclosing generic classes, methods, or functions. + function getOuterTypeParametersOfClassOrInterface(symbol) { + var declaration = symbol.flags & 32 /* Class */ ? symbol.valueDeclaration : ts.getDeclarationOfKind(symbol, 241 /* InterfaceDeclaration */); + return getOuterTypeParameters(declaration); + } + // The local type parameters are the combined set of type parameters from all declarations of the class, + // interface, or type alias. + function getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) { + var result; + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var node = _a[_i]; + if (node.kind === 241 /* InterfaceDeclaration */ || + node.kind === 240 /* ClassDeclaration */ || + node.kind === 209 /* ClassExpression */ || + ts.isTypeAlias(node)) { + var declaration = node; + result = appendTypeParameters(result, ts.getEffectiveTypeParameterDeclarations(declaration)); + } + } + return result; + } + // The full set of type parameters for a generic class or interface type consists of its outer type parameters plus + // its locally declared type parameters. + function getTypeParametersOfClassOrInterface(symbol) { + return ts.concatenate(getOuterTypeParametersOfClassOrInterface(symbol), getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol)); + } + // A type is a mixin constructor if it has a single construct signature taking no type parameters and a single + // rest parameter of type any[]. + function isMixinConstructorType(type) { + var signatures = getSignaturesOfType(type, 1 /* Construct */); + if (signatures.length === 1) { + var s = signatures[0]; + return !s.typeParameters && s.parameters.length === 1 && s.hasRestParameter && getTypeOfParameter(s.parameters[0]) === anyArrayType; + } + return false; + } + function isConstructorType(type) { + if (isValidBaseType(type) && getSignaturesOfType(type, 1 /* Construct */).length > 0) { + return true; + } + if (type.flags & 8650752 /* TypeVariable */) { + var constraint = getBaseConstraintOfType(type); + return !!constraint && isValidBaseType(constraint) && isMixinConstructorType(constraint); + } + return isJSConstructorType(type); + } + function getBaseTypeNodeOfClass(type) { + return ts.getEffectiveBaseTypeNode(type.symbol.valueDeclaration); + } + function getConstructorsForTypeArguments(type, typeArgumentNodes, location) { + var typeArgCount = ts.length(typeArgumentNodes); + var isJavascript = ts.isInJSFile(location); + return ts.filter(getSignaturesOfType(type, 1 /* Construct */), function (sig) { return (isJavascript || typeArgCount >= getMinTypeArgumentCount(sig.typeParameters)) && typeArgCount <= ts.length(sig.typeParameters); }); + } + function getInstantiatedConstructorsForTypeArguments(type, typeArgumentNodes, location) { + var signatures = getConstructorsForTypeArguments(type, typeArgumentNodes, location); + var typeArguments = ts.map(typeArgumentNodes, getTypeFromTypeNode); + return ts.sameMap(signatures, function (sig) { return ts.some(sig.typeParameters) ? getSignatureInstantiation(sig, typeArguments, ts.isInJSFile(location)) : sig; }); + } + /** + * The base constructor of a class can resolve to + * * undefinedType if the class has no extends clause, + * * unknownType if an error occurred during resolution of the extends expression, + * * nullType if the extends expression is the null value, + * * anyType if the extends expression has type any, or + * * an object type with at least one construct signature. + */ + function getBaseConstructorTypeOfClass(type) { + if (!type.resolvedBaseConstructorType) { + var decl = type.symbol.valueDeclaration; + var extended = ts.getEffectiveBaseTypeNode(decl); + var baseTypeNode = getBaseTypeNodeOfClass(type); + if (!baseTypeNode) { + return type.resolvedBaseConstructorType = undefinedType; + } + if (!pushTypeResolution(type, 1 /* ResolvedBaseConstructorType */)) { + return errorType; + } + var baseConstructorType = checkExpression(baseTypeNode.expression); + if (extended && baseTypeNode !== extended) { + ts.Debug.assert(!extended.typeArguments); // Because this is in a JS file, and baseTypeNode is in an @extends tag + checkExpression(extended.expression); + } + if (baseConstructorType.flags & (524288 /* Object */ | 2097152 /* Intersection */)) { + // Resolving the members of a class requires us to resolve the base class of that class. + // We force resolution here such that we catch circularities now. + resolveStructuredTypeMembers(baseConstructorType); + } + if (!popTypeResolution()) { + error(type.symbol.valueDeclaration, ts.Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_base_expression, symbolToString(type.symbol)); + return type.resolvedBaseConstructorType = errorType; + } + if (!(baseConstructorType.flags & 1 /* Any */) && baseConstructorType !== nullWideningType && !isConstructorType(baseConstructorType)) { + var err = error(baseTypeNode.expression, ts.Diagnostics.Type_0_is_not_a_constructor_function_type, typeToString(baseConstructorType)); + if (baseConstructorType.flags & 262144 /* TypeParameter */) { + var constraint = getConstraintFromTypeParameter(baseConstructorType); + var ctorReturn = unknownType; + if (constraint) { + var ctorSig = getSignaturesOfType(constraint, 1 /* Construct */); + if (ctorSig[0]) { + ctorReturn = getReturnTypeOfSignature(ctorSig[0]); + } + } + addRelatedInfo(err, ts.createDiagnosticForNode(baseConstructorType.symbol.declarations[0], ts.Diagnostics.Did_you_mean_for_0_to_be_constrained_to_type_new_args_Colon_any_1, symbolToString(baseConstructorType.symbol), typeToString(ctorReturn))); + } + return type.resolvedBaseConstructorType = errorType; + } + type.resolvedBaseConstructorType = baseConstructorType; + } + return type.resolvedBaseConstructorType; + } + function getBaseTypes(type) { + if (!type.resolvedBaseTypes) { + if (type.objectFlags & 8 /* Tuple */) { + type.resolvedBaseTypes = [createArrayType(getUnionType(type.typeParameters || ts.emptyArray))]; + } + else if (type.symbol.flags & (32 /* Class */ | 64 /* Interface */)) { + if (type.symbol.flags & 32 /* Class */) { + resolveBaseTypesOfClass(type); + } + if (type.symbol.flags & 64 /* Interface */) { + resolveBaseTypesOfInterface(type); + } + } + else { + ts.Debug.fail("type must be class or interface"); + } + } + return type.resolvedBaseTypes; + } + function resolveBaseTypesOfClass(type) { + type.resolvedBaseTypes = ts.resolvingEmptyArray; + var baseConstructorType = getApparentType(getBaseConstructorTypeOfClass(type)); + if (!(baseConstructorType.flags & (524288 /* Object */ | 2097152 /* Intersection */ | 1 /* Any */))) { + return type.resolvedBaseTypes = ts.emptyArray; + } + var baseTypeNode = getBaseTypeNodeOfClass(type); + var typeArgs = typeArgumentsFromTypeReferenceNode(baseTypeNode); + var baseType; + var originalBaseType = isJSConstructorType(baseConstructorType) ? baseConstructorType : + baseConstructorType.symbol ? getDeclaredTypeOfSymbol(baseConstructorType.symbol) : + undefined; + if (baseConstructorType.symbol && baseConstructorType.symbol.flags & 32 /* Class */ && + areAllOuterTypeParametersApplied(originalBaseType)) { + // When base constructor type is a class with no captured type arguments we know that the constructors all have the same type parameters as the + // class and all return the instance type of the class. There is no need for further checks and we can apply the + // type arguments in the same manner as a type reference to get the same error reporting experience. + baseType = getTypeFromClassOrInterfaceReference(baseTypeNode, baseConstructorType.symbol, typeArgs); + } + else if (baseConstructorType.flags & 1 /* Any */) { + baseType = baseConstructorType; + } + else if (isJSConstructorType(baseConstructorType)) { + baseType = !baseTypeNode.typeArguments && getJSClassType(baseConstructorType.symbol) || anyType; + } + else { + // The class derives from a "class-like" constructor function, check that we have at least one construct signature + // with a matching number of type parameters and use the return type of the first instantiated signature. Elsewhere + // we check that all instantiated signatures return the same type. + var constructors = getInstantiatedConstructorsForTypeArguments(baseConstructorType, baseTypeNode.typeArguments, baseTypeNode); + if (!constructors.length) { + error(baseTypeNode.expression, ts.Diagnostics.No_base_constructor_has_the_specified_number_of_type_arguments); + return type.resolvedBaseTypes = ts.emptyArray; + } + baseType = getReturnTypeOfSignature(constructors[0]); + } + if (baseType === errorType) { + return type.resolvedBaseTypes = ts.emptyArray; + } + if (!isValidBaseType(baseType)) { + error(baseTypeNode.expression, ts.Diagnostics.Base_constructor_return_type_0_is_not_an_object_type_or_intersection_of_object_types_with_statically_known_members, typeToString(baseType)); + return type.resolvedBaseTypes = ts.emptyArray; + } + if (type === baseType || hasBaseType(baseType, type)) { + error(type.symbol.valueDeclaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, /*enclosingDeclaration*/ undefined, 2 /* WriteArrayAsGenericType */)); + return type.resolvedBaseTypes = ts.emptyArray; + } + if (type.resolvedBaseTypes === ts.resolvingEmptyArray) { + // Circular reference, likely through instantiation of default parameters + // (otherwise there'd be an error from hasBaseType) - this is fine, but `.members` should be reset + // as `getIndexedAccessType` via `instantiateType` via `getTypeFromClassOrInterfaceReference` forces a + // partial instantiation of the members without the base types fully resolved + type.members = undefined; + } + return type.resolvedBaseTypes = [baseType]; + } + function areAllOuterTypeParametersApplied(type) { + // An unapplied type parameter has its symbol still the same as the matching argument symbol. + // Since parameters are applied outer-to-inner, only the last outer parameter needs to be checked. + var outerTypeParameters = type.outerTypeParameters; + if (outerTypeParameters) { + var last_1 = outerTypeParameters.length - 1; + var typeArguments = type.typeArguments; + return outerTypeParameters[last_1].symbol !== typeArguments[last_1].symbol; + } + return true; + } + // A valid base type is `any`, any non-generic object type or intersection of non-generic + // object types. + function isValidBaseType(type) { + return !!(type.flags & (524288 /* Object */ | 67108864 /* NonPrimitive */ | 1 /* Any */)) && !isGenericMappedType(type) || + !!(type.flags & 2097152 /* Intersection */) && ts.every(type.types, isValidBaseType); + } + function resolveBaseTypesOfInterface(type) { + type.resolvedBaseTypes = type.resolvedBaseTypes || ts.emptyArray; + for (var _i = 0, _a = type.symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (declaration.kind === 241 /* InterfaceDeclaration */ && ts.getInterfaceBaseTypeNodes(declaration)) { + for (var _b = 0, _c = ts.getInterfaceBaseTypeNodes(declaration); _b < _c.length; _b++) { + var node = _c[_b]; + var baseType = getTypeFromTypeNode(node); + if (baseType !== errorType) { + if (isValidBaseType(baseType)) { + if (type !== baseType && !hasBaseType(baseType, type)) { + if (type.resolvedBaseTypes === ts.emptyArray) { + type.resolvedBaseTypes = [baseType]; + } + else { + type.resolvedBaseTypes.push(baseType); + } + } + else { + error(declaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, /*enclosingDeclaration*/ undefined, 2 /* WriteArrayAsGenericType */)); + } + } + else { + error(node, ts.Diagnostics.An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_members); + } + } + } + } + } + } + /** + * Returns true if the interface given by the symbol is free of "this" references. + * + * Specifically, the result is true if the interface itself contains no references + * to "this" in its body, if all base types are interfaces, + * and if none of the base interfaces have a "this" type. + */ + function isThislessInterface(symbol) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (declaration.kind === 241 /* InterfaceDeclaration */) { + if (declaration.flags & 64 /* ContainsThis */) { + return false; + } + var baseTypeNodes = ts.getInterfaceBaseTypeNodes(declaration); + if (baseTypeNodes) { + for (var _b = 0, baseTypeNodes_1 = baseTypeNodes; _b < baseTypeNodes_1.length; _b++) { + var node = baseTypeNodes_1[_b]; + if (ts.isEntityNameExpression(node.expression)) { + var baseSymbol = resolveEntityName(node.expression, 67897832 /* Type */, /*ignoreErrors*/ true); + if (!baseSymbol || !(baseSymbol.flags & 64 /* Interface */) || getDeclaredTypeOfClassOrInterface(baseSymbol).thisType) { + return false; + } + } + } + } + } + } + return true; + } + function getDeclaredTypeOfClassOrInterface(symbol) { + var links = getSymbolLinks(symbol); + if (!links.declaredType) { + var kind = symbol.flags & 32 /* Class */ ? 1 /* Class */ : 2 /* Interface */; + var type = links.declaredType = createObjectType(kind, symbol); + var outerTypeParameters = getOuterTypeParametersOfClassOrInterface(symbol); + var localTypeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); + // A class or interface is generic if it has type parameters or a "this" type. We always give classes a "this" type + // because it is not feasible to analyze all members to determine if the "this" type escapes the class (in particular, + // property types inferred from initializers and method return types inferred from return statements are very hard + // to exhaustively analyze). We give interfaces a "this" type if we can't definitely determine that they are free of + // "this" references. + if (outerTypeParameters || localTypeParameters || kind === 1 /* Class */ || !isThislessInterface(symbol)) { + type.objectFlags |= 4 /* Reference */; + type.typeParameters = ts.concatenate(outerTypeParameters, localTypeParameters); + type.outerTypeParameters = outerTypeParameters; + type.localTypeParameters = localTypeParameters; + type.instantiations = ts.createMap(); + type.instantiations.set(getTypeListId(type.typeParameters), type); + type.target = type; + type.typeArguments = type.typeParameters; + type.thisType = createType(262144 /* TypeParameter */); + type.thisType.isThisType = true; + type.thisType.symbol = symbol; + type.thisType.constraint = type; + } + } + return links.declaredType; + } + function getDeclaredTypeOfTypeAlias(symbol) { + var links = getSymbolLinks(symbol); + if (!links.declaredType) { + // Note that we use the links object as the target here because the symbol object is used as the unique + // identity for resolution of the 'type' property in SymbolLinks. + if (!pushTypeResolution(symbol, 2 /* DeclaredType */)) { + return errorType; + } + var declaration = ts.find(symbol.declarations, function (d) { + return ts.isJSDocTypeAlias(d) || d.kind === 242 /* TypeAliasDeclaration */; + }); + var typeNode = ts.isJSDocTypeAlias(declaration) ? declaration.typeExpression : declaration.type; + // If typeNode is missing, we will error in checkJSDocTypedefTag. + var type = typeNode ? getTypeFromTypeNode(typeNode) : errorType; + if (popTypeResolution()) { + var typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); + if (typeParameters) { + // Initialize the instantiation cache for generic type aliases. The declared type corresponds to + // an instantiation of the type alias with the type parameters supplied as type arguments. + links.typeParameters = typeParameters; + links.instantiations = ts.createMap(); + links.instantiations.set(getTypeListId(typeParameters), type); + } + } + else { + type = errorType; + error(declaration.name, ts.Diagnostics.Type_alias_0_circularly_references_itself, symbolToString(symbol)); + } + links.declaredType = type; + } + return links.declaredType; + } + function isStringConcatExpression(expr) { + if (expr.kind === 10 /* StringLiteral */) { + return true; + } + else if (expr.kind === 204 /* BinaryExpression */) { + return isStringConcatExpression(expr.left) && isStringConcatExpression(expr.right); + } + return false; + } + function isLiteralEnumMember(member) { + var expr = member.initializer; + if (!expr) { + return !(member.flags & 4194304 /* Ambient */); + } + switch (expr.kind) { + case 10 /* StringLiteral */: + case 8 /* NumericLiteral */: + return true; + case 202 /* PrefixUnaryExpression */: + return expr.operator === 39 /* MinusToken */ && + expr.operand.kind === 8 /* NumericLiteral */; + case 72 /* Identifier */: + return ts.nodeIsMissing(expr) || !!getSymbolOfNode(member.parent).exports.get(expr.escapedText); + case 204 /* BinaryExpression */: + return isStringConcatExpression(expr); + default: + return false; + } + } + function getEnumKind(symbol) { + var links = getSymbolLinks(symbol); + if (links.enumKind !== undefined) { + return links.enumKind; + } + var hasNonLiteralMember = false; + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (declaration.kind === 243 /* EnumDeclaration */) { + for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { + var member = _c[_b]; + if (member.initializer && member.initializer.kind === 10 /* StringLiteral */) { + return links.enumKind = 1 /* Literal */; + } + if (!isLiteralEnumMember(member)) { + hasNonLiteralMember = true; + } + } + } + } + return links.enumKind = hasNonLiteralMember ? 0 /* Numeric */ : 1 /* Literal */; + } + function getBaseTypeOfEnumLiteralType(type) { + return type.flags & 1024 /* EnumLiteral */ && !(type.flags & 1048576 /* Union */) ? getDeclaredTypeOfSymbol(getParentOfSymbol(type.symbol)) : type; + } + function getDeclaredTypeOfEnum(symbol) { + var links = getSymbolLinks(symbol); + if (links.declaredType) { + return links.declaredType; + } + if (getEnumKind(symbol) === 1 /* Literal */) { + enumCount++; + var memberTypeList = []; + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (declaration.kind === 243 /* EnumDeclaration */) { + for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { + var member = _c[_b]; + var memberType = getFreshTypeOfLiteralType(getLiteralType(getEnumMemberValue(member), enumCount, getSymbolOfNode(member))); // TODO: GH#18217 + getSymbolLinks(getSymbolOfNode(member)).declaredType = memberType; + memberTypeList.push(getRegularTypeOfLiteralType(memberType)); + } + } + } + if (memberTypeList.length) { + var enumType_1 = getUnionType(memberTypeList, 1 /* Literal */, symbol, /*aliasTypeArguments*/ undefined); + if (enumType_1.flags & 1048576 /* Union */) { + enumType_1.flags |= 1024 /* EnumLiteral */; + enumType_1.symbol = symbol; + } + return links.declaredType = enumType_1; + } + } + var enumType = createType(32 /* Enum */); + enumType.symbol = symbol; + return links.declaredType = enumType; + } + function getDeclaredTypeOfEnumMember(symbol) { + var links = getSymbolLinks(symbol); + if (!links.declaredType) { + var enumType = getDeclaredTypeOfEnum(getParentOfSymbol(symbol)); + if (!links.declaredType) { + links.declaredType = enumType; + } + } + return links.declaredType; + } + function getDeclaredTypeOfTypeParameter(symbol) { + var links = getSymbolLinks(symbol); + if (!links.declaredType) { + var type = createType(262144 /* TypeParameter */); + type.symbol = symbol; + links.declaredType = type; + } + return links.declaredType; + } + function getDeclaredTypeOfAlias(symbol) { + var links = getSymbolLinks(symbol); + if (!links.declaredType) { + links.declaredType = getDeclaredTypeOfSymbol(resolveAlias(symbol)); + } + return links.declaredType; + } + function getDeclaredTypeOfSymbol(symbol) { + return tryGetDeclaredTypeOfSymbol(symbol) || errorType; + } + function tryGetDeclaredTypeOfSymbol(symbol) { + if (symbol.flags & (32 /* Class */ | 64 /* Interface */)) { + return getDeclaredTypeOfClassOrInterface(symbol); + } + if (symbol.flags & 524288 /* TypeAlias */) { + return getDeclaredTypeOfTypeAlias(symbol); + } + if (symbol.flags & 262144 /* TypeParameter */) { + return getDeclaredTypeOfTypeParameter(symbol); + } + if (symbol.flags & 384 /* Enum */) { + return getDeclaredTypeOfEnum(symbol); + } + if (symbol.flags & 8 /* EnumMember */) { + return getDeclaredTypeOfEnumMember(symbol); + } + if (symbol.flags & 2097152 /* Alias */) { + return getDeclaredTypeOfAlias(symbol); + } + return undefined; + } + /** + * A type is free of this references if it's the any, string, number, boolean, symbol, or void keyword, a string + * literal type, an array with an element type that is free of this references, or a type reference that is + * free of this references. + */ + function isThislessType(node) { + switch (node.kind) { + case 120 /* AnyKeyword */: + case 143 /* UnknownKeyword */: + case 138 /* StringKeyword */: + case 135 /* NumberKeyword */: + case 146 /* BigIntKeyword */: + case 123 /* BooleanKeyword */: + case 139 /* SymbolKeyword */: + case 136 /* ObjectKeyword */: + case 106 /* VoidKeyword */: + case 141 /* UndefinedKeyword */: + case 96 /* NullKeyword */: + case 132 /* NeverKeyword */: + case 182 /* LiteralType */: + return true; + case 169 /* ArrayType */: + return isThislessType(node.elementType); + case 164 /* TypeReference */: + return !node.typeArguments || node.typeArguments.every(isThislessType); + } + return false; + } + /** A type parameter is thisless if its contraint is thisless, or if it has no constraint. */ + function isThislessTypeParameter(node) { + var constraint = ts.getEffectiveConstraintOfTypeParameter(node); + return !constraint || isThislessType(constraint); + } + /** + * A variable-like declaration is free of this references if it has a type annotation + * that is thisless, or if it has no type annotation and no initializer (and is thus of type any). + */ + function isThislessVariableLikeDeclaration(node) { + var typeNode = ts.getEffectiveTypeAnnotationNode(node); + return typeNode ? isThislessType(typeNode) : !ts.hasInitializer(node); + } + /** + * A function-like declaration is considered free of `this` references if it has a return type + * annotation that is free of this references and if each parameter is thisless and if + * each type parameter (if present) is thisless. + */ + function isThislessFunctionLikeDeclaration(node) { + var returnType = ts.getEffectiveReturnTypeNode(node); + var typeParameters = ts.getEffectiveTypeParameterDeclarations(node); + return (node.kind === 157 /* Constructor */ || (!!returnType && isThislessType(returnType))) && + node.parameters.every(isThislessVariableLikeDeclaration) && + typeParameters.every(isThislessTypeParameter); + } + /** + * Returns true if the class or interface member given by the symbol is free of "this" references. The + * function may return false for symbols that are actually free of "this" references because it is not + * feasible to perform a complete analysis in all cases. In particular, property members with types + * inferred from their initializers and function members with inferred return types are conservatively + * assumed not to be free of "this" references. + */ + function isThisless(symbol) { + if (symbol.declarations && symbol.declarations.length === 1) { + var declaration = symbol.declarations[0]; + if (declaration) { + switch (declaration.kind) { + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + return isThislessVariableLikeDeclaration(declaration); + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 157 /* Constructor */: + return isThislessFunctionLikeDeclaration(declaration); + } + } + } + return false; + } + // The mappingThisOnly flag indicates that the only type parameter being mapped is "this". When the flag is true, + // we check symbols to see if we can quickly conclude they are free of "this" references, thus needing no instantiation. + function createInstantiatedSymbolTable(symbols, mapper, mappingThisOnly) { + var result = ts.createSymbolTable(); + for (var _i = 0, symbols_2 = symbols; _i < symbols_2.length; _i++) { + var symbol = symbols_2[_i]; + result.set(symbol.escapedName, mappingThisOnly && isThisless(symbol) ? symbol : instantiateSymbol(symbol, mapper)); + } + return result; + } + function addInheritedMembers(symbols, baseSymbols) { + for (var _i = 0, baseSymbols_1 = baseSymbols; _i < baseSymbols_1.length; _i++) { + var s = baseSymbols_1[_i]; + if (!symbols.has(s.escapedName)) { + symbols.set(s.escapedName, s); + } + } + } + function resolveDeclaredMembers(type) { + if (!type.declaredProperties) { + var symbol = type.symbol; + var members = getMembersOfSymbol(symbol); + type.declaredProperties = getNamedMembers(members); + // Start with signatures at empty array in case of recursive types + type.declaredCallSignatures = ts.emptyArray; + type.declaredConstructSignatures = ts.emptyArray; + type.declaredCallSignatures = getSignaturesOfSymbol(members.get("__call" /* Call */)); + type.declaredConstructSignatures = getSignaturesOfSymbol(members.get("__new" /* New */)); + type.declaredStringIndexInfo = getIndexInfoOfSymbol(symbol, 0 /* String */); + type.declaredNumberIndexInfo = getIndexInfoOfSymbol(symbol, 1 /* Number */); + } + return type; + } + /** + * Indicates whether a type can be used as a late-bound name. + */ + function isTypeUsableAsLateBoundName(type) { + return !!(type.flags & 8576 /* StringOrNumberLiteralOrUnique */); + } + /** + * Indicates whether a declaration name is definitely late-bindable. + * A declaration name is only late-bindable if: + * - It is a `ComputedPropertyName`. + * - Its expression is an `Identifier` or either a `PropertyAccessExpression` an + * `ElementAccessExpression` consisting only of these same three types of nodes. + * - The type of its expression is a string or numeric literal type, or is a `unique symbol` type. + */ + function isLateBindableName(node) { + return ts.isComputedPropertyName(node) + && ts.isEntityNameExpression(node.expression) + && isTypeUsableAsLateBoundName(checkComputedPropertyName(node)); + } + function isLateBoundName(name) { + return name.charCodeAt(0) === 95 /* _ */ && + name.charCodeAt(1) === 95 /* _ */ && + name.charCodeAt(2) === 64 /* at */; + } + /** + * Indicates whether a declaration has a late-bindable dynamic name. + */ + function hasLateBindableName(node) { + var name = ts.getNameOfDeclaration(node); + return !!name && isLateBindableName(name); + } + /** + * Indicates whether a declaration has a dynamic name that cannot be late-bound. + */ + function hasNonBindableDynamicName(node) { + return ts.hasDynamicName(node) && !hasLateBindableName(node); + } + /** + * Indicates whether a declaration name is a dynamic name that cannot be late-bound. + */ + function isNonBindableDynamicName(node) { + return ts.isDynamicName(node) && !isLateBindableName(node); + } + /** + * Gets the symbolic name for a late-bound member from its type. + */ + function getLateBoundNameFromType(type) { + if (type.flags & 8192 /* UniqueESSymbol */) { + return "__@" + type.symbol.escapedName + "@" + getSymbolId(type.symbol); + } + if (type.flags & (128 /* StringLiteral */ | 256 /* NumberLiteral */)) { + return ts.escapeLeadingUnderscores("" + type.value); + } + return ts.Debug.fail(); + } + /** + * Adds a declaration to a late-bound dynamic member. This performs the same function for + * late-bound members that `addDeclarationToSymbol` in binder.ts performs for early-bound + * members. + */ + function addDeclarationToLateBoundSymbol(symbol, member, symbolFlags) { + ts.Debug.assert(!!(ts.getCheckFlags(symbol) & 1024 /* Late */), "Expected a late-bound symbol."); + symbol.flags |= symbolFlags; + getSymbolLinks(member.symbol).lateSymbol = symbol; + if (!symbol.declarations) { + symbol.declarations = [member]; + } + else { + symbol.declarations.push(member); + } + if (symbolFlags & 67220415 /* Value */) { + if (!symbol.valueDeclaration || symbol.valueDeclaration.kind !== member.kind) { + symbol.valueDeclaration = member; + } + } + } + /** + * Performs late-binding of a dynamic member. This performs the same function for + * late-bound members that `declareSymbol` in binder.ts performs for early-bound + * members. + * + * If a symbol is a dynamic name from a computed property, we perform an additional "late" + * binding phase to attempt to resolve the name for the symbol from the type of the computed + * property's expression. If the type of the expression is a string-literal, numeric-literal, + * or unique symbol type, we can use that type as the name of the symbol. + * + * For example, given: + * + * const x = Symbol(); + * + * interface I { + * [x]: number; + * } + * + * The binder gives the property `[x]: number` a special symbol with the name "__computed". + * In the late-binding phase we can type-check the expression `x` and see that it has a + * unique symbol type which we can then use as the name of the member. This allows users + * to define custom symbols that can be used in the members of an object type. + * + * @param parent The containing symbol for the member. + * @param earlySymbols The early-bound symbols of the parent. + * @param lateSymbols The late-bound symbols of the parent. + * @param decl The member to bind. + */ + function lateBindMember(parent, earlySymbols, lateSymbols, decl) { + ts.Debug.assert(!!decl.symbol, "The member is expected to have a symbol."); + var links = getNodeLinks(decl); + if (!links.resolvedSymbol) { + // In the event we attempt to resolve the late-bound name of this member recursively, + // fall back to the early-bound name of this member. + links.resolvedSymbol = decl.symbol; + var type = checkComputedPropertyName(decl.name); + if (isTypeUsableAsLateBoundName(type)) { + var memberName = getLateBoundNameFromType(type); + var symbolFlags = decl.symbol.flags; + // Get or add a late-bound symbol for the member. This allows us to merge late-bound accessor declarations. + var lateSymbol = lateSymbols.get(memberName); + if (!lateSymbol) + lateSymbols.set(memberName, lateSymbol = createSymbol(0 /* None */, memberName, 1024 /* Late */)); + // Report an error if a late-bound member has the same name as an early-bound member, + // or if we have another early-bound symbol declaration with the same name and + // conflicting flags. + var earlySymbol = earlySymbols && earlySymbols.get(memberName); + if (lateSymbol.flags & getExcludedSymbolFlags(symbolFlags) || earlySymbol) { + // If we have an existing early-bound member, combine its declarations so that we can + // report an error at each declaration. + var declarations = earlySymbol ? ts.concatenate(earlySymbol.declarations, lateSymbol.declarations) : lateSymbol.declarations; + var name_2 = ts.declarationNameToString(decl.name); + ts.forEach(declarations, function (declaration) { return error(ts.getNameOfDeclaration(declaration) || declaration, ts.Diagnostics.Duplicate_declaration_0, name_2); }); + error(decl.name || decl, ts.Diagnostics.Duplicate_declaration_0, name_2); + lateSymbol = createSymbol(0 /* None */, memberName, 1024 /* Late */); + } + lateSymbol.nameType = type; + addDeclarationToLateBoundSymbol(lateSymbol, decl, symbolFlags); + if (lateSymbol.parent) { + ts.Debug.assert(lateSymbol.parent === parent, "Existing symbol parent should match new one"); + } + else { + lateSymbol.parent = parent; + } + return links.resolvedSymbol = lateSymbol; + } + } + return links.resolvedSymbol; + } + function getResolvedMembersOrExportsOfSymbol(symbol, resolutionKind) { + var links = getSymbolLinks(symbol); + if (!links[resolutionKind]) { + var isStatic = resolutionKind === "resolvedExports" /* resolvedExports */; + var earlySymbols = !isStatic ? symbol.members : + symbol.flags & 1536 /* Module */ ? getExportsOfModuleWorker(symbol) : + symbol.exports; + // In the event we recursively resolve the members/exports of the symbol, we + // set the initial value of resolvedMembers/resolvedExports to the early-bound + // members/exports of the symbol. + links[resolutionKind] = earlySymbols || emptySymbols; + // fill in any as-yet-unresolved late-bound members. + var lateSymbols = ts.createSymbolTable(); + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + var members = ts.getMembersOfDeclaration(decl); + if (members) { + for (var _b = 0, members_4 = members; _b < members_4.length; _b++) { + var member = members_4[_b]; + if (isStatic === ts.hasStaticModifier(member) && hasLateBindableName(member)) { + lateBindMember(symbol, earlySymbols, lateSymbols, member); + } + } + } + } + links[resolutionKind] = combineSymbolTables(earlySymbols, lateSymbols) || emptySymbols; + } + return links[resolutionKind]; + } + /** + * Gets a SymbolTable containing both the early- and late-bound members of a symbol. + * + * For a description of late-binding, see `lateBindMember`. + */ + function getMembersOfSymbol(symbol) { + return symbol.flags & 6240 /* LateBindingContainer */ + ? getResolvedMembersOrExportsOfSymbol(symbol, "resolvedMembers" /* resolvedMembers */) + : symbol.members || emptySymbols; + } + /** + * If a symbol is the dynamic name of the member of an object type, get the late-bound + * symbol of the member. + * + * For a description of late-binding, see `lateBindMember`. + */ + function getLateBoundSymbol(symbol) { + if (symbol.flags & 106500 /* ClassMember */ && symbol.escapedName === "__computed" /* Computed */) { + var links = getSymbolLinks(symbol); + if (!links.lateSymbol && ts.some(symbol.declarations, hasLateBindableName)) { + // force late binding of members/exports. This will set the late-bound symbol + if (ts.some(symbol.declarations, ts.hasStaticModifier)) { + getExportsOfSymbol(symbol.parent); + } + else { + getMembersOfSymbol(symbol.parent); + } + } + return links.lateSymbol || (links.lateSymbol = symbol); + } + return symbol; + } + function getTypeWithThisArgument(type, thisArgument, needApparentType) { + if (ts.getObjectFlags(type) & 4 /* Reference */) { + var target = type.target; + var typeArguments = type.typeArguments; + if (ts.length(target.typeParameters) === ts.length(typeArguments)) { + var ref = createTypeReference(target, ts.concatenate(typeArguments, [thisArgument || target.thisType])); + return needApparentType ? getApparentType(ref) : ref; + } + } + else if (type.flags & 2097152 /* Intersection */) { + return getIntersectionType(ts.map(type.types, function (t) { return getTypeWithThisArgument(t, thisArgument, needApparentType); })); + } + return needApparentType ? getApparentType(type) : type; + } + function resolveObjectTypeMembers(type, source, typeParameters, typeArguments) { + var mapper; + var members; + var callSignatures; + var constructSignatures; + var stringIndexInfo; + var numberIndexInfo; + if (ts.rangeEquals(typeParameters, typeArguments, 0, typeParameters.length)) { + mapper = identityMapper; + members = source.symbol ? getMembersOfSymbol(source.symbol) : ts.createSymbolTable(source.declaredProperties); + callSignatures = source.declaredCallSignatures; + constructSignatures = source.declaredConstructSignatures; + stringIndexInfo = source.declaredStringIndexInfo; + numberIndexInfo = source.declaredNumberIndexInfo; + } + else { + mapper = createTypeMapper(typeParameters, typeArguments); + members = createInstantiatedSymbolTable(source.declaredProperties, mapper, /*mappingThisOnly*/ typeParameters.length === 1); + callSignatures = instantiateSignatures(source.declaredCallSignatures, mapper); + constructSignatures = instantiateSignatures(source.declaredConstructSignatures, mapper); + stringIndexInfo = instantiateIndexInfo(source.declaredStringIndexInfo, mapper); + numberIndexInfo = instantiateIndexInfo(source.declaredNumberIndexInfo, mapper); + } + var baseTypes = getBaseTypes(source); + if (baseTypes.length) { + if (source.symbol && members === getMembersOfSymbol(source.symbol)) { + members = ts.createSymbolTable(source.declaredProperties); + } + setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + var thisArgument = ts.lastOrUndefined(typeArguments); + for (var _i = 0, baseTypes_1 = baseTypes; _i < baseTypes_1.length; _i++) { + var baseType = baseTypes_1[_i]; + var instantiatedBaseType = thisArgument ? getTypeWithThisArgument(instantiateType(baseType, mapper), thisArgument) : baseType; + addInheritedMembers(members, getPropertiesOfType(instantiatedBaseType)); + callSignatures = ts.concatenate(callSignatures, getSignaturesOfType(instantiatedBaseType, 0 /* Call */)); + constructSignatures = ts.concatenate(constructSignatures, getSignaturesOfType(instantiatedBaseType, 1 /* Construct */)); + if (!stringIndexInfo) { + stringIndexInfo = instantiatedBaseType === anyType ? + createIndexInfo(anyType, /*isReadonly*/ false) : + getIndexInfoOfType(instantiatedBaseType, 0 /* String */); + } + numberIndexInfo = numberIndexInfo || getIndexInfoOfType(instantiatedBaseType, 1 /* Number */); + } + } + setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + } + function resolveClassOrInterfaceMembers(type) { + resolveObjectTypeMembers(type, resolveDeclaredMembers(type), ts.emptyArray, ts.emptyArray); + } + function resolveTypeReferenceMembers(type) { + var source = resolveDeclaredMembers(type.target); + var typeParameters = ts.concatenate(source.typeParameters, [source.thisType]); + var typeArguments = type.typeArguments && type.typeArguments.length === typeParameters.length ? + type.typeArguments : ts.concatenate(type.typeArguments, [type]); + resolveObjectTypeMembers(type, source, typeParameters, typeArguments); + } + function createSignature(declaration, typeParameters, thisParameter, parameters, resolvedReturnType, resolvedTypePredicate, minArgumentCount, hasRestParameter, hasLiteralTypes) { + var sig = new Signature(checker); + sig.declaration = declaration; + sig.typeParameters = typeParameters; + sig.parameters = parameters; + sig.thisParameter = thisParameter; + sig.resolvedReturnType = resolvedReturnType; + sig.resolvedTypePredicate = resolvedTypePredicate; + sig.minArgumentCount = minArgumentCount; + sig.hasRestParameter = hasRestParameter; + sig.hasLiteralTypes = hasLiteralTypes; + sig.target = undefined; + sig.mapper = undefined; + return sig; + } + function cloneSignature(sig) { + return createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, /*resolvedReturnType*/ undefined, + /*resolvedTypePredicate*/ undefined, sig.minArgumentCount, sig.hasRestParameter, sig.hasLiteralTypes); + } + function getExpandedParameters(sig) { + if (sig.hasRestParameter) { + var restIndex_1 = sig.parameters.length - 1; + var restParameter = sig.parameters[restIndex_1]; + var restType = getTypeOfSymbol(restParameter); + if (isTupleType(restType)) { + var elementTypes = restType.typeArguments || ts.emptyArray; + var minLength_1 = restType.target.minLength; + var tupleRestIndex_1 = restType.target.hasRestElement ? elementTypes.length - 1 : -1; + var restParams = ts.map(elementTypes, function (t, i) { + var name = getParameterNameAtPosition(sig, restIndex_1 + i); + var checkFlags = i === tupleRestIndex_1 ? 8192 /* RestParameter */ : + i >= minLength_1 ? 4096 /* OptionalParameter */ : 0; + var symbol = createSymbol(1 /* FunctionScopedVariable */, name, checkFlags); + symbol.type = i === tupleRestIndex_1 ? createArrayType(t) : t; + return symbol; + }); + return ts.concatenate(sig.parameters.slice(0, restIndex_1), restParams); + } + } + return sig.parameters; + } + function getDefaultConstructSignatures(classType) { + var baseConstructorType = getBaseConstructorTypeOfClass(classType); + var baseSignatures = getSignaturesOfType(baseConstructorType, 1 /* Construct */); + if (baseSignatures.length === 0) { + return [createSignature(undefined, classType.localTypeParameters, undefined, ts.emptyArray, classType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false)]; // TODO: GH#18217 + } + var baseTypeNode = getBaseTypeNodeOfClass(classType); + var isJavaScript = ts.isInJSFile(baseTypeNode); + var typeArguments = typeArgumentsFromTypeReferenceNode(baseTypeNode); + var typeArgCount = ts.length(typeArguments); + var result = []; + for (var _i = 0, baseSignatures_1 = baseSignatures; _i < baseSignatures_1.length; _i++) { + var baseSig = baseSignatures_1[_i]; + var minTypeArgumentCount = getMinTypeArgumentCount(baseSig.typeParameters); + var typeParamCount = ts.length(baseSig.typeParameters); + if (isJavaScript || typeArgCount >= minTypeArgumentCount && typeArgCount <= typeParamCount) { + var sig = typeParamCount ? createSignatureInstantiation(baseSig, fillMissingTypeArguments(typeArguments, baseSig.typeParameters, minTypeArgumentCount, isJavaScript)) : cloneSignature(baseSig); + sig.typeParameters = classType.localTypeParameters; + sig.resolvedReturnType = classType; + result.push(sig); + } + } + return result; + } + function findMatchingSignature(signatureList, signature, partialMatch, ignoreThisTypes, ignoreReturnTypes) { + for (var _i = 0, signatureList_1 = signatureList; _i < signatureList_1.length; _i++) { + var s = signatureList_1[_i]; + if (compareSignaturesIdentical(s, signature, partialMatch, ignoreThisTypes, ignoreReturnTypes, partialMatch ? compareTypesSubtypeOf : compareTypesIdentical)) { + return s; + } + } + } + function findMatchingSignatures(signatureLists, signature, listIndex) { + if (signature.typeParameters) { + // We require an exact match for generic signatures, so we only return signatures from the first + // signature list and only if they have exact matches in the other signature lists. + if (listIndex > 0) { + return undefined; + } + for (var i = 1; i < signatureLists.length; i++) { + if (!findMatchingSignature(signatureLists[i], signature, /*partialMatch*/ false, /*ignoreThisTypes*/ false, /*ignoreReturnTypes*/ false)) { + return undefined; + } + } + return [signature]; + } + var result; + for (var i = 0; i < signatureLists.length; i++) { + // Allow matching non-generic signatures to have excess parameters and different return types + var match = i === listIndex ? signature : findMatchingSignature(signatureLists[i], signature, /*partialMatch*/ true, /*ignoreThisTypes*/ true, /*ignoreReturnTypes*/ true); + if (!match) { + return undefined; + } + result = ts.appendIfUnique(result, match); + } + return result; + } + // The signatures of a union type are those signatures that are present in each of the constituent types. + // Generic signatures must match exactly, but non-generic signatures are allowed to have extra optional + // parameters and may differ in return types. When signatures differ in return types, the resulting return + // type is the union of the constituent return types. + function getUnionSignatures(signatureLists) { + var result; + for (var i = 0; i < signatureLists.length; i++) { + for (var _i = 0, _a = signatureLists[i]; _i < _a.length; _i++) { + var signature = _a[_i]; + // Only process signatures with parameter lists that aren't already in the result list + if (!result || !findMatchingSignature(result, signature, /*partialMatch*/ false, /*ignoreThisTypes*/ true, /*ignoreReturnTypes*/ true)) { + var unionSignatures = findMatchingSignatures(signatureLists, signature, i); + if (unionSignatures) { + var s = signature; + // Union the result types when more than one signature matches + if (unionSignatures.length > 1) { + var thisParameter = signature.thisParameter; + if (ts.forEach(unionSignatures, function (sig) { return sig.thisParameter; })) { + // TODO: GH#18217 We tested that *some* has thisParameter and now act as if *all* do + var thisType = getUnionType(ts.map(unionSignatures, function (sig) { return sig.thisParameter ? getTypeOfSymbol(sig.thisParameter) : anyType; }), 2 /* Subtype */); + thisParameter = createSymbolWithType(signature.thisParameter, thisType); + } + s = cloneSignature(signature); + s.thisParameter = thisParameter; + s.unionSignatures = unionSignatures; + } + (result || (result = [])).push(s); + } + } + } + } + return result || ts.emptyArray; + } + function getUnionIndexInfo(types, kind) { + var indexTypes = []; + var isAnyReadonly = false; + for (var _i = 0, types_2 = types; _i < types_2.length; _i++) { + var type = types_2[_i]; + var indexInfo = getIndexInfoOfType(type, kind); + if (!indexInfo) { + return undefined; + } + indexTypes.push(indexInfo.type); + isAnyReadonly = isAnyReadonly || indexInfo.isReadonly; + } + return createIndexInfo(getUnionType(indexTypes, 2 /* Subtype */), isAnyReadonly); + } + function resolveUnionTypeMembers(type) { + // The members and properties collections are empty for union types. To get all properties of a union + // type use getPropertiesOfType (only the language service uses this). + var callSignatures = getUnionSignatures(ts.map(type.types, function (t) { return getSignaturesOfType(t, 0 /* Call */); })); + var constructSignatures = getUnionSignatures(ts.map(type.types, function (t) { return getSignaturesOfType(t, 1 /* Construct */); })); + var stringIndexInfo = getUnionIndexInfo(type.types, 0 /* String */); + var numberIndexInfo = getUnionIndexInfo(type.types, 1 /* Number */); + setStructuredTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + } + function intersectTypes(type1, type2) { + return !type1 ? type2 : !type2 ? type1 : getIntersectionType([type1, type2]); + } + function intersectIndexInfos(info1, info2) { + return !info1 ? info2 : !info2 ? info1 : createIndexInfo(getIntersectionType([info1.type, info2.type]), info1.isReadonly && info2.isReadonly); + } + function unionSpreadIndexInfos(info1, info2) { + return info1 && info2 && createIndexInfo(getUnionType([info1.type, info2.type]), info1.isReadonly || info2.isReadonly); + } + function includeMixinType(type, types, index) { + var mixedTypes = []; + for (var i = 0; i < types.length; i++) { + if (i === index) { + mixedTypes.push(type); + } + else if (isMixinConstructorType(types[i])) { + mixedTypes.push(getReturnTypeOfSignature(getSignaturesOfType(types[i], 1 /* Construct */)[0])); + } + } + return getIntersectionType(mixedTypes); + } + function resolveIntersectionTypeMembers(type) { + // The members and properties collections are empty for intersection types. To get all properties of an + // intersection type use getPropertiesOfType (only the language service uses this). + var callSignatures = ts.emptyArray; + var constructSignatures = ts.emptyArray; + var stringIndexInfo; + var numberIndexInfo; + var types = type.types; + var mixinCount = ts.countWhere(types, isMixinConstructorType); + var _loop_5 = function (i) { + var t = type.types[i]; + // When an intersection type contains mixin constructor types, the construct signatures from + // those types are discarded and their return types are mixed into the return types of all + // other construct signatures in the intersection type. For example, the intersection type + // '{ new(...args: any[]) => A } & { new(s: string) => B }' has a single construct signature + // 'new(s: string) => A & B'. + if (mixinCount === 0 || mixinCount === types.length && i === 0 || !isMixinConstructorType(t)) { + var signatures = getSignaturesOfType(t, 1 /* Construct */); + if (signatures.length && mixinCount > 0) { + signatures = ts.map(signatures, function (s) { + var clone = cloneSignature(s); + clone.resolvedReturnType = includeMixinType(getReturnTypeOfSignature(s), types, i); + return clone; + }); + } + constructSignatures = ts.concatenate(constructSignatures, signatures); + } + callSignatures = ts.concatenate(callSignatures, getSignaturesOfType(t, 0 /* Call */)); + stringIndexInfo = intersectIndexInfos(stringIndexInfo, getIndexInfoOfType(t, 0 /* String */)); + numberIndexInfo = intersectIndexInfos(numberIndexInfo, getIndexInfoOfType(t, 1 /* Number */)); + }; + for (var i = 0; i < types.length; i++) { + _loop_5(i); + } + setStructuredTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + } + /** + * Converts an AnonymousType to a ResolvedType. + */ + function resolveAnonymousTypeMembers(type) { + var symbol = type.symbol; + if (type.target) { + setStructuredTypeMembers(type, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + var members = createInstantiatedSymbolTable(getPropertiesOfObjectType(type.target), type.mapper, /*mappingThisOnly*/ false); + var callSignatures = instantiateSignatures(getSignaturesOfType(type.target, 0 /* Call */), type.mapper); + var constructSignatures = instantiateSignatures(getSignaturesOfType(type.target, 1 /* Construct */), type.mapper); + var stringIndexInfo = instantiateIndexInfo(getIndexInfoOfType(type.target, 0 /* String */), type.mapper); + var numberIndexInfo = instantiateIndexInfo(getIndexInfoOfType(type.target, 1 /* Number */), type.mapper); + setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + } + else if (symbol.flags & 2048 /* TypeLiteral */) { + setStructuredTypeMembers(type, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + var members = getMembersOfSymbol(symbol); + var callSignatures = getSignaturesOfSymbol(members.get("__call" /* Call */)); + var constructSignatures = getSignaturesOfSymbol(members.get("__new" /* New */)); + var stringIndexInfo = getIndexInfoOfSymbol(symbol, 0 /* String */); + var numberIndexInfo = getIndexInfoOfSymbol(symbol, 1 /* Number */); + setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + } + else { + // Combinations of function, class, enum and module + var members = emptySymbols; + var stringIndexInfo = void 0; + if (symbol.exports) { + members = getExportsOfSymbol(symbol); + } + setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, undefined, undefined); + if (symbol.flags & 32 /* Class */) { + var classType = getDeclaredTypeOfClassOrInterface(symbol); + var baseConstructorType = getBaseConstructorTypeOfClass(classType); + if (baseConstructorType.flags & (524288 /* Object */ | 2097152 /* Intersection */ | 8650752 /* TypeVariable */)) { + members = ts.createSymbolTable(getNamedMembers(members)); + addInheritedMembers(members, getPropertiesOfType(baseConstructorType)); + } + else if (baseConstructorType === anyType) { + stringIndexInfo = createIndexInfo(anyType, /*isReadonly*/ false); + } + } + var numberIndexInfo = symbol.flags & 384 /* Enum */ ? enumNumberIndexInfo : undefined; + setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); + // We resolve the members before computing the signatures because a signature may use + // typeof with a qualified name expression that circularly references the type we are + // in the process of resolving (see issue #6072). The temporarily empty signature list + // will never be observed because a qualified name can't reference signatures. + if (symbol.flags & (16 /* Function */ | 8192 /* Method */)) { + type.callSignatures = getSignaturesOfSymbol(symbol); + type.constructSignatures = ts.filter(type.callSignatures, function (sig) { return isJSConstructor(sig.declaration); }); + } + // And likewise for construct signatures for classes + if (symbol.flags & 32 /* Class */) { + var classType = getDeclaredTypeOfClassOrInterface(symbol); + var constructSignatures = getSignaturesOfSymbol(symbol.members.get("__constructor" /* Constructor */)); + if (!constructSignatures.length) { + constructSignatures = getDefaultConstructSignatures(classType); + } + type.constructSignatures = constructSignatures; + } + } + } + function resolveReverseMappedTypeMembers(type) { + var indexInfo = getIndexInfoOfType(type.source, 0 /* String */); + var modifiers = getMappedTypeModifiers(type.mappedType); + var readonlyMask = modifiers & 1 /* IncludeReadonly */ ? false : true; + var optionalMask = modifiers & 4 /* IncludeOptional */ ? 0 : 16777216 /* Optional */; + var stringIndexInfo = indexInfo && createIndexInfo(inferReverseMappedType(indexInfo.type, type.mappedType, type.constraintType), readonlyMask && indexInfo.isReadonly); + var members = ts.createSymbolTable(); + for (var _i = 0, _a = getPropertiesOfType(type.source); _i < _a.length; _i++) { + var prop = _a[_i]; + var checkFlags = 2048 /* ReverseMapped */ | (readonlyMask && isReadonlySymbol(prop) ? 8 /* Readonly */ : 0); + var inferredProp = createSymbol(4 /* Property */ | prop.flags & optionalMask, prop.escapedName, checkFlags); + inferredProp.declarations = prop.declarations; + inferredProp.nameType = prop.nameType; + inferredProp.propertyType = getTypeOfSymbol(prop); + inferredProp.mappedType = type.mappedType; + inferredProp.constraintType = type.constraintType; + members.set(prop.escapedName, inferredProp); + } + setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, undefined); + } + /** Resolve the members of a mapped type { [P in K]: T } */ + function resolveMappedTypeMembers(type) { + var members = ts.createSymbolTable(); + var stringIndexInfo; + var numberIndexInfo; + // Resolve upfront such that recursive references see an empty object type. + setStructuredTypeMembers(type, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + // In { [P in K]: T }, we refer to P as the type parameter type, K as the constraint type, + // and T as the template type. + var typeParameter = getTypeParameterFromMappedType(type); + var constraintType = getConstraintTypeFromMappedType(type); + var templateType = getTemplateTypeFromMappedType(type.target || type); + var modifiersType = getApparentType(getModifiersTypeFromMappedType(type)); // The 'T' in 'keyof T' + var templateModifiers = getMappedTypeModifiers(type); + var include = keyofStringsOnly ? 128 /* StringLiteral */ : 8576 /* StringOrNumberLiteralOrUnique */; + if (isMappedTypeWithKeyofConstraintDeclaration(type)) { + // We have a { [P in keyof T]: X } + for (var _i = 0, _a = getPropertiesOfType(modifiersType); _i < _a.length; _i++) { + var prop = _a[_i]; + addMemberForKeyType(getLiteralTypeFromProperty(prop, include)); + } + if (modifiersType.flags & 1 /* Any */ || getIndexInfoOfType(modifiersType, 0 /* String */)) { + addMemberForKeyType(stringType); + } + if (!keyofStringsOnly && getIndexInfoOfType(modifiersType, 1 /* Number */)) { + addMemberForKeyType(numberType); + } + } + else { + // If the key type is a 'keyof X', obtain 'keyof C' where C is the base constraint of X. + // Then iterate over the constituents of the key type. + var iterationType = constraintType.flags & 4194304 /* Index */ ? getIndexType(getApparentType(constraintType.type)) : constraintType; + forEachType(iterationType, addMemberForKeyType); + } + setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); + function addMemberForKeyType(t) { + // Create a mapper from T to the current iteration type constituent. Then, if the + // mapped type is itself an instantiated type, combine the iteration mapper with the + // instantiation mapper. + var templateMapper = combineTypeMappers(type.mapper, createTypeMapper([typeParameter], [t])); + var propType = instantiateType(templateType, templateMapper); + // If the current iteration type constituent is a string literal type, create a property. + // Otherwise, for type string create a string index signature. + if (t.flags & 8576 /* StringOrNumberLiteralOrUnique */) { + var propName = getLateBoundNameFromType(t); + var modifiersProp = getPropertyOfType(modifiersType, propName); + var isOptional = !!(templateModifiers & 4 /* IncludeOptional */ || + !(templateModifiers & 8 /* ExcludeOptional */) && modifiersProp && modifiersProp.flags & 16777216 /* Optional */); + var isReadonly = !!(templateModifiers & 1 /* IncludeReadonly */ || + !(templateModifiers & 2 /* ExcludeReadonly */) && modifiersProp && isReadonlySymbol(modifiersProp)); + var prop = createSymbol(4 /* Property */ | (isOptional ? 16777216 /* Optional */ : 0), propName, isReadonly ? 8 /* Readonly */ : 0); + // When creating an optional property in strictNullChecks mode, if 'undefined' isn't assignable to the + // type, we include 'undefined' in the type. Similarly, when creating a non-optional property in strictNullChecks + // mode, if the underlying property is optional we remove 'undefined' from the type. + prop.type = strictNullChecks && isOptional && !isTypeAssignableTo(undefinedType, propType) ? getOptionalType(propType) : + strictNullChecks && !isOptional && modifiersProp && modifiersProp.flags & 16777216 /* Optional */ ? getTypeWithFacts(propType, 524288 /* NEUndefined */) : + propType; + if (modifiersProp) { + prop.syntheticOrigin = modifiersProp; + prop.declarations = modifiersProp.declarations; + } + prop.nameType = t; + members.set(propName, prop); + } + else if (t.flags & (1 /* Any */ | 4 /* String */)) { + stringIndexInfo = createIndexInfo(propType, !!(templateModifiers & 1 /* IncludeReadonly */)); + } + else if (t.flags & 8 /* Number */) { + numberIndexInfo = createIndexInfo(propType, !!(templateModifiers & 1 /* IncludeReadonly */)); + } + } + } + function getTypeParameterFromMappedType(type) { + return type.typeParameter || + (type.typeParameter = getDeclaredTypeOfTypeParameter(getSymbolOfNode(type.declaration.typeParameter))); + } + function getConstraintTypeFromMappedType(type) { + return type.constraintType || + (type.constraintType = getConstraintOfTypeParameter(getTypeParameterFromMappedType(type)) || errorType); + } + function getTemplateTypeFromMappedType(type) { + return type.templateType || + (type.templateType = type.declaration.type ? + instantiateType(addOptionality(getTypeFromTypeNode(type.declaration.type), !!(getMappedTypeModifiers(type) & 4 /* IncludeOptional */)), type.mapper || identityMapper) : + errorType); + } + function getConstraintDeclarationForMappedType(type) { + return ts.getEffectiveConstraintOfTypeParameter(type.declaration.typeParameter); + } + function isMappedTypeWithKeyofConstraintDeclaration(type) { + var constraintDeclaration = getConstraintDeclarationForMappedType(type); // TODO: GH#18217 + return constraintDeclaration.kind === 179 /* TypeOperator */ && + constraintDeclaration.operator === 129 /* KeyOfKeyword */; + } + function getModifiersTypeFromMappedType(type) { + if (!type.modifiersType) { + if (isMappedTypeWithKeyofConstraintDeclaration(type)) { + // If the constraint declaration is a 'keyof T' node, the modifiers type is T. We check + // AST nodes here because, when T is a non-generic type, the logic below eagerly resolves + // 'keyof T' to a literal union type and we can't recover T from that type. + type.modifiersType = instantiateType(getTypeFromTypeNode(getConstraintDeclarationForMappedType(type).type), type.mapper || identityMapper); + } + else { + // Otherwise, get the declared constraint type, and if the constraint type is a type parameter, + // get the constraint of that type parameter. If the resulting type is an indexed type 'keyof T', + // the modifiers type is T. Otherwise, the modifiers type is {}. + var declaredType = getTypeFromMappedTypeNode(type.declaration); + var constraint = getConstraintTypeFromMappedType(declaredType); + var extendedConstraint = constraint && constraint.flags & 262144 /* TypeParameter */ ? getConstraintOfTypeParameter(constraint) : constraint; + type.modifiersType = extendedConstraint && extendedConstraint.flags & 4194304 /* Index */ ? instantiateType(extendedConstraint.type, type.mapper || identityMapper) : emptyObjectType; + } + } + return type.modifiersType; + } + function getMappedTypeModifiers(type) { + var declaration = type.declaration; + return (declaration.readonlyToken ? declaration.readonlyToken.kind === 39 /* MinusToken */ ? 2 /* ExcludeReadonly */ : 1 /* IncludeReadonly */ : 0) | + (declaration.questionToken ? declaration.questionToken.kind === 39 /* MinusToken */ ? 8 /* ExcludeOptional */ : 4 /* IncludeOptional */ : 0); + } + function getMappedTypeOptionality(type) { + var modifiers = getMappedTypeModifiers(type); + return modifiers & 8 /* ExcludeOptional */ ? -1 : modifiers & 4 /* IncludeOptional */ ? 1 : 0; + } + function getCombinedMappedTypeOptionality(type) { + var optionality = getMappedTypeOptionality(type); + var modifiersType = getModifiersTypeFromMappedType(type); + return optionality || (isGenericMappedType(modifiersType) ? getMappedTypeOptionality(modifiersType) : 0); + } + function isPartialMappedType(type) { + return !!(ts.getObjectFlags(type) & 32 /* Mapped */ && getMappedTypeModifiers(type) & 4 /* IncludeOptional */); + } + function isGenericMappedType(type) { + return !!(ts.getObjectFlags(type) & 32 /* Mapped */) && isGenericIndexType(getConstraintTypeFromMappedType(type)); + } + function resolveStructuredTypeMembers(type) { + if (!type.members) { + if (type.flags & 524288 /* Object */) { + if (type.objectFlags & 4 /* Reference */) { + resolveTypeReferenceMembers(type); + } + else if (type.objectFlags & 3 /* ClassOrInterface */) { + resolveClassOrInterfaceMembers(type); + } + else if (type.objectFlags & 2048 /* ReverseMapped */) { + resolveReverseMappedTypeMembers(type); + } + else if (type.objectFlags & 16 /* Anonymous */) { + resolveAnonymousTypeMembers(type); + } + else if (type.objectFlags & 32 /* Mapped */) { + resolveMappedTypeMembers(type); + } + } + else if (type.flags & 1048576 /* Union */) { + resolveUnionTypeMembers(type); + } + else if (type.flags & 2097152 /* Intersection */) { + resolveIntersectionTypeMembers(type); + } + } + return type; + } + /** Return properties of an object type or an empty array for other types */ + function getPropertiesOfObjectType(type) { + if (type.flags & 524288 /* Object */) { + return resolveStructuredTypeMembers(type).properties; + } + return ts.emptyArray; + } + /** If the given type is an object type and that type has a property by the given name, + * return the symbol for that property. Otherwise return undefined. + */ + function getPropertyOfObjectType(type, name) { + if (type.flags & 524288 /* Object */) { + var resolved = resolveStructuredTypeMembers(type); + var symbol = resolved.members.get(name); + if (symbol && symbolIsValue(symbol)) { + return symbol; + } + } + } + function getPropertiesOfUnionOrIntersectionType(type) { + if (!type.resolvedProperties) { + var members = ts.createSymbolTable(); + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var current = _a[_i]; + for (var _b = 0, _c = getPropertiesOfType(current); _b < _c.length; _b++) { + var prop = _c[_b]; + if (!members.has(prop.escapedName)) { + var combinedProp = getPropertyOfUnionOrIntersectionType(type, prop.escapedName); + if (combinedProp) { + members.set(prop.escapedName, combinedProp); + } + } + } + // The properties of a union type are those that are present in all constituent types, so + // we only need to check the properties of the first type + if (type.flags & 1048576 /* Union */) { + break; + } + } + type.resolvedProperties = getNamedMembers(members); + } + return type.resolvedProperties; + } + function getPropertiesOfType(type) { + type = getApparentType(type); + return type.flags & 3145728 /* UnionOrIntersection */ ? + getPropertiesOfUnionOrIntersectionType(type) : + getPropertiesOfObjectType(type); + } + function isTypeInvalidDueToUnionDiscriminant(contextualType, obj) { + var list = obj.properties; + return list.some(function (property) { + var name = property.name && ts.getTextOfPropertyName(property.name); + var expected = name === undefined ? undefined : getTypeOfPropertyOfType(contextualType, name); + return !!expected && typeIsLiteralType(expected) && !isTypeIdenticalTo(getTypeOfNode(property), expected); + }); + } + function getAllPossiblePropertiesOfTypes(types) { + var unionType = getUnionType(types); + if (!(unionType.flags & 1048576 /* Union */)) { + return getAugmentedPropertiesOfType(unionType); + } + var props = ts.createSymbolTable(); + for (var _i = 0, types_3 = types; _i < types_3.length; _i++) { + var memberType = types_3[_i]; + for (var _a = 0, _b = getAugmentedPropertiesOfType(memberType); _a < _b.length; _a++) { + var escapedName = _b[_a].escapedName; + if (!props.has(escapedName)) { + var prop = createUnionOrIntersectionProperty(unionType, escapedName); + // May be undefined if the property is private + if (prop) + props.set(escapedName, prop); + } + } + } + return ts.arrayFrom(props.values()); + } + function getConstraintOfType(type) { + return type.flags & 262144 /* TypeParameter */ ? getConstraintOfTypeParameter(type) : + type.flags & 8388608 /* IndexedAccess */ ? getConstraintOfIndexedAccess(type) : + type.flags & 16777216 /* Conditional */ ? getConstraintOfConditionalType(type) : + getBaseConstraintOfType(type); + } + function getConstraintOfTypeParameter(typeParameter) { + return hasNonCircularBaseConstraint(typeParameter) ? getConstraintFromTypeParameter(typeParameter) : undefined; + } + function getConstraintOfIndexedAccess(type) { + var objectType = getConstraintOfType(type.objectType) || type.objectType; + if (objectType !== type.objectType) { + var constraint = getIndexedAccessType(objectType, type.indexType, /*accessNode*/ undefined, errorType); + if (constraint && constraint !== errorType) { + return constraint; + } + } + var baseConstraint = getBaseConstraintOfType(type); + return baseConstraint && baseConstraint !== type ? baseConstraint : undefined; + } + function getDefaultConstraintOfConditionalType(type) { + if (!type.resolvedDefaultConstraint) { + var rootTrueType = type.root.trueType; + var rootTrueConstraint = !(rootTrueType.flags & 33554432 /* Substitution */) + ? rootTrueType + : (rootTrueType.substitute).flags & 3 /* AnyOrUnknown */ + ? rootTrueType.typeVariable + : getIntersectionType([rootTrueType.substitute, rootTrueType.typeVariable]); + type.resolvedDefaultConstraint = getUnionType([instantiateType(rootTrueConstraint, type.combinedMapper || type.mapper), getFalseTypeFromConditionalType(type)]); + } + return type.resolvedDefaultConstraint; + } + function getConstraintOfDistributiveConditionalType(type) { + // Check if we have a conditional type of the form 'T extends U ? X : Y', where T is a constrained + // type parameter. If so, create an instantiation of the conditional type where T is replaced + // with its constraint. We do this because if the constraint is a union type it will be distributed + // over the conditional type and possibly reduced. For example, 'T extends undefined ? never : T' + // removes 'undefined' from T. + if (type.root.isDistributive) { + var simplified = getSimplifiedType(type.checkType); + var constraint = simplified === type.checkType ? getConstraintOfType(simplified) : simplified; + if (constraint) { + var mapper = makeUnaryTypeMapper(type.root.checkType, constraint); + var instantiated = getConditionalTypeInstantiation(type, combineTypeMappers(mapper, type.mapper)); + if (!(instantiated.flags & 131072 /* Never */)) { + return instantiated; + } + } + } + return undefined; + } + function getConstraintOfConditionalType(type) { + return getConstraintOfDistributiveConditionalType(type) || getDefaultConstraintOfConditionalType(type); + } + function getUnionConstraintOfIntersection(type, targetIsUnion) { + var constraints; + var hasDisjointDomainType = false; + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (t.flags & 63176704 /* Instantiable */) { + // We keep following constraints as long as we have an instantiable type that is known + // not to be circular or infinite (hence we stop on index access types). + var constraint = getConstraintOfType(t); + while (constraint && constraint.flags & (262144 /* TypeParameter */ | 4194304 /* Index */ | 16777216 /* Conditional */)) { + constraint = getConstraintOfType(constraint); + } + if (constraint) { + // A constraint that isn't a union type implies that the final type would be a non-union + // type as well. Since non-union constraints are of no interest, we can exit here. + if (!(constraint.flags & 1048576 /* Union */)) { + return undefined; + } + constraints = ts.append(constraints, constraint); + } + } + else if (t.flags & 67238908 /* DisjointDomains */) { + hasDisjointDomainType = true; + } + } + // If the target is a union type or if we are intersecting with types belonging to one of the + // disjoint domans, we may end up producing a constraint that hasn't been examined before. + if (constraints && (targetIsUnion || hasDisjointDomainType)) { + if (hasDisjointDomainType) { + // We add any types belong to one of the disjoint domans because they might cause the final + // intersection operation to reduce the union constraints. + for (var _b = 0, _c = type.types; _b < _c.length; _b++) { + var t = _c[_b]; + if (t.flags & 67238908 /* DisjointDomains */) { + constraints = ts.append(constraints, t); + } + } + } + return getIntersectionType(constraints); + } + return undefined; + } + function getBaseConstraintOfType(type) { + if (type.flags & (58982400 /* InstantiableNonPrimitive */ | 3145728 /* UnionOrIntersection */)) { + var constraint = getResolvedBaseConstraint(type); + return constraint !== noConstraintType && constraint !== circularConstraintType ? constraint : undefined; + } + return type.flags & 4194304 /* Index */ ? keyofConstraintType : undefined; + } + /** + * This is similar to `getBaseConstraintOfType` except it returns the input type if there's no base constraint, instead of `undefined` + * It also doesn't map indexes to `string`, as where this is used this would be unneeded (and likely undesirable) + */ + function getBaseConstraintOrType(type) { + return getBaseConstraintOfType(type) || type; + } + function hasNonCircularBaseConstraint(type) { + return getResolvedBaseConstraint(type) !== circularConstraintType; + } + /** + * Return the resolved base constraint of a type variable. The noConstraintType singleton is returned if the + * type variable has no constraint, and the circularConstraintType singleton is returned if the constraint + * circularly references the type variable. + */ + function getResolvedBaseConstraint(type) { + var nonTerminating = false; + return type.resolvedBaseConstraint || + (type.resolvedBaseConstraint = getTypeWithThisArgument(getImmediateBaseConstraint(type), type)); + function getImmediateBaseConstraint(t) { + if (!t.immediateBaseConstraint) { + if (!pushTypeResolution(t, 4 /* ImmediateBaseConstraint */)) { + return circularConstraintType; + } + if (constraintDepth === 50) { + // We have reached 50 recursive invocations of getImmediateBaseConstraint and there is a + // very high likelyhood we're dealing with an infinite generic type that perpetually generates + // new type identities as we descend into it. We stop the recursion here and mark this type + // and the outer types as having circular constraints. + nonTerminating = true; + return t.immediateBaseConstraint = noConstraintType; + } + constraintDepth++; + var result = computeBaseConstraint(getSimplifiedType(t)); + constraintDepth--; + if (!popTypeResolution() || nonTerminating) { + result = circularConstraintType; + } + t.immediateBaseConstraint = result || noConstraintType; + } + return t.immediateBaseConstraint; + } + function getBaseConstraint(t) { + var c = getImmediateBaseConstraint(t); + return c !== noConstraintType && c !== circularConstraintType ? c : undefined; + } + function computeBaseConstraint(t) { + if (t.flags & 262144 /* TypeParameter */) { + var constraint = getConstraintFromTypeParameter(t); + return t.isThisType || !constraint ? + constraint : + getBaseConstraint(constraint); + } + if (t.flags & 3145728 /* UnionOrIntersection */) { + var types = t.types; + var baseTypes = []; + for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { + var type_3 = types_4[_i]; + var baseType = getBaseConstraint(type_3); + if (baseType) { + baseTypes.push(baseType); + } + } + return t.flags & 1048576 /* Union */ && baseTypes.length === types.length ? getUnionType(baseTypes) : + t.flags & 2097152 /* Intersection */ && baseTypes.length ? getIntersectionType(baseTypes) : + undefined; + } + if (t.flags & 4194304 /* Index */) { + return keyofConstraintType; + } + if (t.flags & 8388608 /* IndexedAccess */) { + var baseObjectType = getBaseConstraint(t.objectType); + var baseIndexType = getBaseConstraint(t.indexType); + var baseIndexedAccess = baseObjectType && baseIndexType ? getIndexedAccessType(baseObjectType, baseIndexType, /*accessNode*/ undefined, errorType) : undefined; + return baseIndexedAccess && baseIndexedAccess !== errorType ? getBaseConstraint(baseIndexedAccess) : undefined; + } + if (t.flags & 16777216 /* Conditional */) { + var constraint = getConstraintOfConditionalType(t); + return constraint && getBaseConstraint(constraint); + } + if (t.flags & 33554432 /* Substitution */) { + return getBaseConstraint(t.substitute); + } + return t; + } + } + function getApparentTypeOfIntersectionType(type) { + return type.resolvedApparentType || (type.resolvedApparentType = getTypeWithThisArgument(type, type, /*apparentType*/ true)); + } + function getResolvedTypeParameterDefault(typeParameter) { + if (!typeParameter.default) { + if (typeParameter.target) { + var targetDefault = getResolvedTypeParameterDefault(typeParameter.target); + typeParameter.default = targetDefault ? instantiateType(targetDefault, typeParameter.mapper) : noConstraintType; + } + else { + // To block recursion, set the initial value to the resolvingDefaultType. + typeParameter.default = resolvingDefaultType; + var defaultDeclaration = typeParameter.symbol && ts.forEach(typeParameter.symbol.declarations, function (decl) { return ts.isTypeParameterDeclaration(decl) && decl.default; }); + var defaultType = defaultDeclaration ? getTypeFromTypeNode(defaultDeclaration) : noConstraintType; + if (typeParameter.default === resolvingDefaultType) { + // If we have not been called recursively, set the correct default type. + typeParameter.default = defaultType; + } + } + } + else if (typeParameter.default === resolvingDefaultType) { + // If we are called recursively for this type parameter, mark the default as circular. + typeParameter.default = circularConstraintType; + } + return typeParameter.default; + } + /** + * Gets the default type for a type parameter. + * + * If the type parameter is the result of an instantiation, this gets the instantiated + * default type of its target. If the type parameter has no default type or the default is + * circular, `undefined` is returned. + */ + function getDefaultFromTypeParameter(typeParameter) { + var defaultType = getResolvedTypeParameterDefault(typeParameter); + return defaultType !== noConstraintType && defaultType !== circularConstraintType ? defaultType : undefined; + } + function hasNonCircularTypeParameterDefault(typeParameter) { + return getResolvedTypeParameterDefault(typeParameter) !== circularConstraintType; + } + /** + * Indicates whether the declaration of a typeParameter has a default type. + */ + function hasTypeParameterDefault(typeParameter) { + return !!(typeParameter.symbol && ts.forEach(typeParameter.symbol.declarations, function (decl) { return ts.isTypeParameterDeclaration(decl) && decl.default; })); + } + function getApparentTypeOfMappedType(type) { + return type.resolvedApparentType || (type.resolvedApparentType = getResolvedApparentTypeOfMappedType(type)); + } + function getResolvedApparentTypeOfMappedType(type) { + var typeVariable = getHomomorphicTypeVariable(type); + if (typeVariable) { + var constraint = getConstraintOfTypeParameter(typeVariable); + if (constraint && (isArrayType(constraint) || isReadonlyArrayType(constraint) || isTupleType(constraint))) { + var mapper = makeUnaryTypeMapper(typeVariable, constraint); + return instantiateType(type, combineTypeMappers(mapper, type.mapper)); + } + } + return type; + } + /** + * For a type parameter, return the base constraint of the type parameter. For the string, number, + * boolean, and symbol primitive types, return the corresponding object types. Otherwise return the + * type itself. Note that the apparent type of a union type is the union type itself. + */ + function getApparentType(type) { + var t = type.flags & 63176704 /* Instantiable */ ? getBaseConstraintOfType(type) || emptyObjectType : type; + return ts.getObjectFlags(t) & 32 /* Mapped */ ? getApparentTypeOfMappedType(t) : + t.flags & 2097152 /* Intersection */ ? getApparentTypeOfIntersectionType(t) : + t.flags & 132 /* StringLike */ ? globalStringType : + t.flags & 296 /* NumberLike */ ? globalNumberType : + t.flags & 2112 /* BigIntLike */ ? getGlobalBigIntType(/*reportErrors*/ languageVersion >= 6 /* ESNext */) : + t.flags & 528 /* BooleanLike */ ? globalBooleanType : + t.flags & 12288 /* ESSymbolLike */ ? getGlobalESSymbolType(/*reportErrors*/ languageVersion >= 2 /* ES2015 */) : + t.flags & 67108864 /* NonPrimitive */ ? emptyObjectType : + t.flags & 4194304 /* Index */ ? keyofConstraintType : + t; + } + function createUnionOrIntersectionProperty(containingType, name) { + var props; + var indexTypes; + var isUnion = containingType.flags & 1048576 /* Union */; + var excludeModifiers = isUnion ? 24 /* NonPublicAccessibilityModifier */ : 0; + // Flags we want to propagate to the result if they exist in all source symbols + var commonFlags = isUnion ? 0 /* None */ : 16777216 /* Optional */; + var syntheticFlag = 4 /* SyntheticMethod */; + var checkFlags = 0; + for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) { + var current = _a[_i]; + var type = getApparentType(current); + if (type !== errorType) { + var prop = getPropertyOfType(type, name); + var modifiers = prop ? ts.getDeclarationModifierFlagsFromSymbol(prop) : 0; + if (prop && !(modifiers & excludeModifiers)) { + commonFlags &= prop.flags; + props = ts.appendIfUnique(props, prop); + checkFlags |= (isReadonlySymbol(prop) ? 8 /* Readonly */ : 0) | + (!(modifiers & 24 /* NonPublicAccessibilityModifier */) ? 64 /* ContainsPublic */ : 0) | + (modifiers & 16 /* Protected */ ? 128 /* ContainsProtected */ : 0) | + (modifiers & 8 /* Private */ ? 256 /* ContainsPrivate */ : 0) | + (modifiers & 32 /* Static */ ? 512 /* ContainsStatic */ : 0); + if (!isPrototypeProperty(prop)) { + syntheticFlag = 2 /* SyntheticProperty */; + } + } + else if (isUnion) { + var indexInfo = !isLateBoundName(name) && (isNumericLiteralName(name) && getIndexInfoOfType(type, 1 /* Number */) || getIndexInfoOfType(type, 0 /* String */)); + if (indexInfo) { + checkFlags |= indexInfo.isReadonly ? 8 /* Readonly */ : 0; + indexTypes = ts.append(indexTypes, isTupleType(type) ? getRestTypeOfTupleType(type) || undefinedType : indexInfo.type); + } + else { + checkFlags |= 16 /* Partial */; + } + } + } + } + if (!props) { + return undefined; + } + if (props.length === 1 && !(checkFlags & 16 /* Partial */) && !indexTypes) { + return props[0]; + } + var declarations; + var commonType; + var nameType; + var propTypes = []; + var first = true; + var commonValueDeclaration; + var hasNonUniformValueDeclaration = false; + for (var _b = 0, props_1 = props; _b < props_1.length; _b++) { + var prop = props_1[_b]; + if (!commonValueDeclaration) { + commonValueDeclaration = prop.valueDeclaration; + } + else if (prop.valueDeclaration !== commonValueDeclaration) { + hasNonUniformValueDeclaration = true; + } + declarations = ts.addRange(declarations, prop.declarations); + var type = getTypeOfSymbol(prop); + if (first) { + commonType = type; + nameType = prop.nameType; + first = false; + } + else { + if (type !== commonType) { + checkFlags |= 32 /* HasNonUniformType */; + } + } + propTypes.push(type); + } + ts.addRange(propTypes, indexTypes); + var result = createSymbol(4 /* Property */ | commonFlags, name, syntheticFlag | checkFlags); + result.containingType = containingType; + if (!hasNonUniformValueDeclaration && commonValueDeclaration) { + result.valueDeclaration = commonValueDeclaration; + } + result.declarations = declarations; + result.nameType = nameType; + result.type = isUnion ? getUnionType(propTypes) : getIntersectionType(propTypes); + return result; + } + // Return the symbol for a given property in a union or intersection type, or undefined if the property + // does not exist in any constituent type. Note that the returned property may only be present in some + // constituents, in which case the isPartial flag is set when the containing type is union type. We need + // these partial properties when identifying discriminant properties, but otherwise they are filtered out + // and do not appear to be present in the union type. + function getUnionOrIntersectionProperty(type, name) { + var properties = type.propertyCache || (type.propertyCache = ts.createSymbolTable()); + var property = properties.get(name); + if (!property) { + property = createUnionOrIntersectionProperty(type, name); + if (property) { + properties.set(name, property); + } + } + return property; + } + function getPropertyOfUnionOrIntersectionType(type, name) { + var property = getUnionOrIntersectionProperty(type, name); + // We need to filter out partial properties in union types + return property && !(ts.getCheckFlags(property) & 16 /* Partial */) ? property : undefined; + } + /** + * Return the symbol for the property with the given name in the given type. Creates synthetic union properties when + * necessary, maps primitive types and type parameters are to their apparent types, and augments with properties from + * Object and Function as appropriate. + * + * @param type a type to look up property from + * @param name a name of property to look up in a given type + */ + function getPropertyOfType(type, name) { + type = getApparentType(type); + if (type.flags & 524288 /* Object */) { + var resolved = resolveStructuredTypeMembers(type); + var symbol = resolved.members.get(name); + if (symbol && symbolIsValue(symbol)) { + return symbol; + } + var functionType = resolved === anyFunctionType ? globalFunctionType : + resolved.callSignatures.length ? globalCallableFunctionType : + resolved.constructSignatures.length ? globalNewableFunctionType : + undefined; + if (functionType) { + var symbol_1 = getPropertyOfObjectType(functionType, name); + if (symbol_1) { + return symbol_1; + } + } + return getPropertyOfObjectType(globalObjectType, name); + } + if (type.flags & 3145728 /* UnionOrIntersection */) { + return getPropertyOfUnionOrIntersectionType(type, name); + } + return undefined; + } + function getSignaturesOfStructuredType(type, kind) { + if (type.flags & 3670016 /* StructuredType */) { + var resolved = resolveStructuredTypeMembers(type); + return kind === 0 /* Call */ ? resolved.callSignatures : resolved.constructSignatures; + } + return ts.emptyArray; + } + /** + * Return the signatures of the given kind in the given type. Creates synthetic union signatures when necessary and + * maps primitive types and type parameters are to their apparent types. + */ + function getSignaturesOfType(type, kind) { + return getSignaturesOfStructuredType(getApparentType(type), kind); + } + function getIndexInfoOfStructuredType(type, kind) { + if (type.flags & 3670016 /* StructuredType */) { + var resolved = resolveStructuredTypeMembers(type); + return kind === 0 /* String */ ? resolved.stringIndexInfo : resolved.numberIndexInfo; + } + } + function getIndexTypeOfStructuredType(type, kind) { + var info = getIndexInfoOfStructuredType(type, kind); + return info && info.type; + } + // Return the indexing info of the given kind in the given type. Creates synthetic union index types when necessary and + // maps primitive types and type parameters are to their apparent types. + function getIndexInfoOfType(type, kind) { + return getIndexInfoOfStructuredType(getApparentType(type), kind); + } + // Return the index type of the given kind in the given type. Creates synthetic union index types when necessary and + // maps primitive types and type parameters are to their apparent types. + function getIndexTypeOfType(type, kind) { + return getIndexTypeOfStructuredType(getApparentType(type), kind); + } + function getImplicitIndexTypeOfType(type, kind) { + if (isObjectTypeWithInferableIndex(type)) { + var propTypes = []; + for (var _i = 0, _a = getPropertiesOfType(type); _i < _a.length; _i++) { + var prop = _a[_i]; + if (kind === 0 /* String */ || isNumericLiteralName(prop.escapedName)) { + propTypes.push(getTypeOfSymbol(prop)); + } + } + if (propTypes.length) { + return getUnionType(propTypes, 2 /* Subtype */); + } + } + return undefined; + } + // Return list of type parameters with duplicates removed (duplicate identifier errors are generated in the actual + // type checking functions). + function getTypeParametersFromDeclaration(declaration) { + var result; + for (var _i = 0, _a = ts.getEffectiveTypeParameterDeclarations(declaration); _i < _a.length; _i++) { + var node = _a[_i]; + result = ts.appendIfUnique(result, getDeclaredTypeOfTypeParameter(node.symbol)); + } + return result; + } + function symbolsToArray(symbols) { + var result = []; + symbols.forEach(function (symbol, id) { + if (!isReservedMemberName(id)) { + result.push(symbol); + } + }); + return result; + } + function isJSDocOptionalParameter(node) { + return ts.isInJSFile(node) && ( + // node.type should only be a JSDocOptionalType when node is a parameter of a JSDocFunctionType + node.type && node.type.kind === 288 /* JSDocOptionalType */ + || ts.getJSDocParameterTags(node).some(function (_a) { + var isBracketed = _a.isBracketed, typeExpression = _a.typeExpression; + return isBracketed || !!typeExpression && typeExpression.type.kind === 288 /* JSDocOptionalType */; + })); + } + function tryFindAmbientModule(moduleName, withAugmentations) { + if (ts.isExternalModuleNameRelative(moduleName)) { + return undefined; + } + var symbol = getSymbol(globals, '"' + moduleName + '"', 512 /* ValueModule */); + // merged symbol is module declaration symbol combined with all augmentations + return symbol && withAugmentations ? getMergedSymbol(symbol) : symbol; + } + function isOptionalParameter(node) { + if (ts.hasQuestionToken(node) || isOptionalJSDocParameterTag(node) || isJSDocOptionalParameter(node)) { + return true; + } + if (node.initializer) { + var signature = getSignatureFromDeclaration(node.parent); + var parameterIndex = node.parent.parameters.indexOf(node); + ts.Debug.assert(parameterIndex >= 0); + return parameterIndex >= getMinArgumentCount(signature); + } + var iife = ts.getImmediatelyInvokedFunctionExpression(node.parent); + if (iife) { + return !node.type && + !node.dotDotDotToken && + node.parent.parameters.indexOf(node) >= iife.arguments.length; + } + return false; + } + function isOptionalJSDocParameterTag(node) { + if (!ts.isJSDocParameterTag(node)) { + return false; + } + var isBracketed = node.isBracketed, typeExpression = node.typeExpression; + return isBracketed || !!typeExpression && typeExpression.type.kind === 288 /* JSDocOptionalType */; + } + function createIdentifierTypePredicate(parameterName, parameterIndex, type) { + return { kind: 1 /* Identifier */, parameterName: parameterName, parameterIndex: parameterIndex, type: type }; + } + function createThisTypePredicate(type) { + return { kind: 0 /* This */, type: type }; + } + /** + * Gets the minimum number of type arguments needed to satisfy all non-optional type + * parameters. + */ + function getMinTypeArgumentCount(typeParameters) { + var minTypeArgumentCount = 0; + if (typeParameters) { + for (var i = 0; i < typeParameters.length; i++) { + if (!hasTypeParameterDefault(typeParameters[i])) { + minTypeArgumentCount = i + 1; + } + } + } + return minTypeArgumentCount; + } + function fillMissingTypeArguments(typeArguments, typeParameters, minTypeArgumentCount, isJavaScriptImplicitAny) { + var numTypeParameters = ts.length(typeParameters); + if (!numTypeParameters) { + return []; + } + var numTypeArguments = ts.length(typeArguments); + if (isJavaScriptImplicitAny || (numTypeArguments >= minTypeArgumentCount && numTypeArguments <= numTypeParameters)) { + var result = typeArguments ? typeArguments.slice() : []; + // Map an unsatisfied type parameter with a default type. + // If a type parameter does not have a default type, or if the default type + // is a forward reference, the empty object type is used. + var baseDefaultType_1 = getDefaultTypeArgumentType(isJavaScriptImplicitAny); + var circularityMapper = createTypeMapper(typeParameters, ts.map(typeParameters, function () { return baseDefaultType_1; })); + for (var i = numTypeArguments; i < numTypeParameters; i++) { + result[i] = instantiateType(getConstraintFromTypeParameter(typeParameters[i]) || baseDefaultType_1, circularityMapper); + } + for (var i = numTypeArguments; i < numTypeParameters; i++) { + var mapper = createTypeMapper(typeParameters, result); + var defaultType = getDefaultFromTypeParameter(typeParameters[i]); + if (isJavaScriptImplicitAny && defaultType && isTypeIdenticalTo(defaultType, emptyObjectType)) { + defaultType = anyType; + } + result[i] = defaultType ? instantiateType(defaultType, mapper) : baseDefaultType_1; + } + result.length = typeParameters.length; + return result; + } + return typeArguments && typeArguments.slice(); + } + function getSignatureFromDeclaration(declaration) { + var links = getNodeLinks(declaration); + if (!links.resolvedSignature) { + var parameters = []; + var hasLiteralTypes = false; + var minArgumentCount = 0; + var thisParameter = void 0; + var hasThisParameter = false; + var iife = ts.getImmediatelyInvokedFunctionExpression(declaration); + var isJSConstructSignature = ts.isJSDocConstructSignature(declaration); + var isUntypedSignatureInJSFile = !iife && + ts.isInJSFile(declaration) && + ts.isValueSignatureDeclaration(declaration) && + !ts.hasJSDocParameterTags(declaration) && + !ts.getJSDocType(declaration); + // If this is a JSDoc construct signature, then skip the first parameter in the + // parameter list. The first parameter represents the return type of the construct + // signature. + for (var i = isJSConstructSignature ? 1 : 0; i < declaration.parameters.length; i++) { + var param = declaration.parameters[i]; + var paramSymbol = param.symbol; + var type = ts.isJSDocParameterTag(param) ? (param.typeExpression && param.typeExpression.type) : param.type; + // Include parameter symbol instead of property symbol in the signature + if (paramSymbol && !!(paramSymbol.flags & 4 /* Property */) && !ts.isBindingPattern(param.name)) { + var resolvedSymbol = resolveName(param, paramSymbol.escapedName, 67220415 /* Value */, undefined, undefined, /*isUse*/ false); + paramSymbol = resolvedSymbol; + } + if (i === 0 && paramSymbol.escapedName === "this" /* This */) { + hasThisParameter = true; + thisParameter = param.symbol; + } + else { + parameters.push(paramSymbol); + } + if (type && type.kind === 182 /* LiteralType */) { + hasLiteralTypes = true; + } + // Record a new minimum argument count if this is not an optional parameter + var isOptionalParameter_1 = isOptionalJSDocParameterTag(param) || + param.initializer || param.questionToken || param.dotDotDotToken || + iife && parameters.length > iife.arguments.length && !type || + isUntypedSignatureInJSFile || + isJSDocOptionalParameter(param); + if (!isOptionalParameter_1) { + minArgumentCount = parameters.length; + } + } + // If only one accessor includes a this-type annotation, the other behaves as if it had the same type annotation + if ((declaration.kind === 158 /* GetAccessor */ || declaration.kind === 159 /* SetAccessor */) && + !hasNonBindableDynamicName(declaration) && + (!hasThisParameter || !thisParameter)) { + var otherKind = declaration.kind === 158 /* GetAccessor */ ? 159 /* SetAccessor */ : 158 /* GetAccessor */; + var other = ts.getDeclarationOfKind(getSymbolOfNode(declaration), otherKind); + if (other) { + thisParameter = getAnnotatedAccessorThisParameter(other); + } + } + var classType = declaration.kind === 157 /* Constructor */ ? + getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)) + : undefined; + var typeParameters = classType ? classType.localTypeParameters : getTypeParametersFromDeclaration(declaration); + var hasRestLikeParameter = ts.hasRestParameter(declaration) || ts.isInJSFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters); + links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, + /*resolvedReturnType*/ undefined, /*resolvedTypePredicate*/ undefined, minArgumentCount, hasRestLikeParameter, hasLiteralTypes); + } + return links.resolvedSignature; + } + /** + * A JS function gets a synthetic rest parameter if it references `arguments` AND: + * 1. It has no parameters but at least one `@param` with a type that starts with `...` + * OR + * 2. It has at least one parameter, and the last parameter has a matching `@param` with a type that starts with `...` + */ + function maybeAddJsSyntheticRestParameter(declaration, parameters) { + if (ts.isJSDocSignature(declaration) || !containsArgumentsReference(declaration)) { + return false; + } + var lastParam = ts.lastOrUndefined(declaration.parameters); + var lastParamTags = lastParam ? ts.getJSDocParameterTags(lastParam) : ts.getJSDocTags(declaration).filter(ts.isJSDocParameterTag); + var lastParamVariadicType = ts.firstDefined(lastParamTags, function (p) { + return p.typeExpression && ts.isJSDocVariadicType(p.typeExpression.type) ? p.typeExpression.type : undefined; + }); + var syntheticArgsSymbol = createSymbol(3 /* Variable */, "args", 8192 /* RestParameter */); + syntheticArgsSymbol.type = lastParamVariadicType ? createArrayType(getTypeFromTypeNode(lastParamVariadicType.type)) : anyArrayType; + if (lastParamVariadicType) { + // Replace the last parameter with a rest parameter. + parameters.pop(); + } + parameters.push(syntheticArgsSymbol); + return true; + } + function getSignatureOfTypeTag(node) { + var typeTag = ts.isInJSFile(node) ? ts.getJSDocTypeTag(node) : undefined; + var signature = typeTag && typeTag.typeExpression && getSingleCallSignature(getTypeFromTypeNode(typeTag.typeExpression)); + return signature && getErasedSignature(signature); + } + function getReturnTypeOfTypeTag(node) { + var signature = getSignatureOfTypeTag(node); + return signature && getReturnTypeOfSignature(signature); + } + function containsArgumentsReference(declaration) { + var links = getNodeLinks(declaration); + if (links.containsArgumentsReference === undefined) { + if (links.flags & 8192 /* CaptureArguments */) { + links.containsArgumentsReference = true; + } + else { + links.containsArgumentsReference = traverse(declaration.body); + } + } + return links.containsArgumentsReference; + function traverse(node) { + if (!node) + return false; + switch (node.kind) { + case 72 /* Identifier */: + return node.escapedText === "arguments" && ts.isExpressionNode(node); + case 154 /* PropertyDeclaration */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + return node.name.kind === 149 /* ComputedPropertyName */ + && traverse(node.name); + default: + return !ts.nodeStartsNewLexicalEnvironment(node) && !ts.isPartOfTypeNode(node) && !!ts.forEachChild(node, traverse); + } + } + } + function getSignaturesOfSymbol(symbol) { + if (!symbol) + return ts.emptyArray; + var result = []; + for (var i = 0; i < symbol.declarations.length; i++) { + var decl = symbol.declarations[i]; + if (!ts.isFunctionLike(decl)) + continue; + // Don't include signature if node is the implementation of an overloaded function. A node is considered + // an implementation node if it has a body and the previous node is of the same kind and immediately + // precedes the implementation node (i.e. has the same parent and ends where the implementation starts). + if (i > 0 && decl.body) { + var previous = symbol.declarations[i - 1]; + if (decl.parent === previous.parent && decl.kind === previous.kind && decl.pos === previous.end) { + continue; + } + } + result.push(getSignatureFromDeclaration(decl)); + } + return result; + } + function resolveExternalModuleTypeByLiteral(name) { + var moduleSym = resolveExternalModuleName(name, name); + if (moduleSym) { + var resolvedModuleSymbol = resolveExternalModuleSymbol(moduleSym); + if (resolvedModuleSymbol) { + return getTypeOfSymbol(resolvedModuleSymbol); + } + } + return anyType; + } + function getThisTypeOfSignature(signature) { + if (signature.thisParameter) { + return getTypeOfSymbol(signature.thisParameter); + } + } + function signatureHasTypePredicate(signature) { + return getTypePredicateOfSignature(signature) !== undefined; + } + function getTypePredicateOfSignature(signature) { + if (!signature.resolvedTypePredicate) { + if (signature.target) { + var targetTypePredicate = getTypePredicateOfSignature(signature.target); + signature.resolvedTypePredicate = targetTypePredicate ? instantiateTypePredicate(targetTypePredicate, signature.mapper) : noTypePredicate; + } + else if (signature.unionSignatures) { + signature.resolvedTypePredicate = getUnionTypePredicate(signature.unionSignatures) || noTypePredicate; + } + else { + var type = signature.declaration && ts.getEffectiveReturnTypeNode(signature.declaration); + var jsdocPredicate = void 0; + if (!type && ts.isInJSFile(signature.declaration)) { + var jsdocSignature = getSignatureOfTypeTag(signature.declaration); + if (jsdocSignature && signature !== jsdocSignature) { + jsdocPredicate = getTypePredicateOfSignature(jsdocSignature); + } + } + signature.resolvedTypePredicate = type && ts.isTypePredicateNode(type) ? + createTypePredicateFromTypePredicateNode(type, signature.declaration) : + jsdocPredicate || noTypePredicate; + } + ts.Debug.assert(!!signature.resolvedTypePredicate); + } + return signature.resolvedTypePredicate === noTypePredicate ? undefined : signature.resolvedTypePredicate; + } + function createTypePredicateFromTypePredicateNode(node, func) { + var parameterName = node.parameterName; + var type = getTypeFromTypeNode(node.type); + if (parameterName.kind === 72 /* Identifier */) { + return createIdentifierTypePredicate(parameterName.escapedText, getTypePredicateParameterIndex(func.parameters, parameterName), type); + } + else { + return createThisTypePredicate(type); + } + } + function getTypePredicateParameterIndex(parameterList, parameter) { + for (var i = 0; i < parameterList.length; i++) { + var param = parameterList[i]; + if (param.name.kind === 72 /* Identifier */ && param.name.escapedText === parameter.escapedText) { + return i; + } + } + return -1; + } + function getReturnTypeOfSignature(signature) { + if (!signature.resolvedReturnType) { + if (!pushTypeResolution(signature, 3 /* ResolvedReturnType */)) { + return errorType; + } + var type = signature.target ? instantiateType(getReturnTypeOfSignature(signature.target), signature.mapper) : + signature.unionSignatures ? getUnionType(ts.map(signature.unionSignatures, getReturnTypeOfSignature), 2 /* Subtype */) : + getReturnTypeFromAnnotation(signature.declaration) || + isJSConstructor(signature.declaration) && getJSClassType(getSymbolOfNode(signature.declaration)) || + (ts.nodeIsMissing(signature.declaration.body) ? anyType : getReturnTypeFromBody(signature.declaration)); + if (!popTypeResolution()) { + if (signature.declaration) { + var typeNode = ts.getEffectiveReturnTypeNode(signature.declaration); + if (typeNode) { + error(typeNode, ts.Diagnostics.Return_type_annotation_circularly_references_itself); + } + else if (noImplicitAny) { + var declaration = signature.declaration; + var name = ts.getNameOfDeclaration(declaration); + if (name) { + error(name, ts.Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, ts.declarationNameToString(name)); + } + else { + error(declaration, ts.Diagnostics.Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions); + } + } + } + type = anyType; + } + signature.resolvedReturnType = type; + } + return signature.resolvedReturnType; + } + function getReturnTypeFromAnnotation(declaration) { + if (declaration.kind === 157 /* Constructor */) { + return getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)); + } + if (ts.isJSDocConstructSignature(declaration)) { + return getTypeFromTypeNode(declaration.parameters[0].type); // TODO: GH#18217 + } + var typeNode = ts.getEffectiveReturnTypeNode(declaration); + if (typeNode) { + return getTypeFromTypeNode(typeNode); + } + if (declaration.kind === 158 /* GetAccessor */ && !hasNonBindableDynamicName(declaration)) { + var jsDocType = ts.isInJSFile(declaration) && getTypeForDeclarationFromJSDocComment(declaration); + if (jsDocType) { + return jsDocType; + } + var setter = ts.getDeclarationOfKind(getSymbolOfNode(declaration), 159 /* SetAccessor */); + var setterType = getAnnotatedAccessorType(setter); + if (setterType) { + return setterType; + } + } + return getReturnTypeOfTypeTag(declaration); + } + function isResolvingReturnTypeOfSignature(signature) { + return !signature.resolvedReturnType && findResolutionCycleStartIndex(signature, 3 /* ResolvedReturnType */) >= 0; + } + function getRestTypeOfSignature(signature) { + return tryGetRestTypeOfSignature(signature) || anyType; + } + function tryGetRestTypeOfSignature(signature) { + if (signature.hasRestParameter) { + var sigRestType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); + var restType = isTupleType(sigRestType) ? getRestTypeOfTupleType(sigRestType) : sigRestType; + return restType && getIndexTypeOfType(restType, 1 /* Number */); + } + return undefined; + } + function getSignatureInstantiation(signature, typeArguments, isJavascript) { + return getSignatureInstantiationWithoutFillingInTypeArguments(signature, fillMissingTypeArguments(typeArguments, signature.typeParameters, getMinTypeArgumentCount(signature.typeParameters), isJavascript)); + } + function getSignatureInstantiationWithoutFillingInTypeArguments(signature, typeArguments) { + var instantiations = signature.instantiations || (signature.instantiations = ts.createMap()); + var id = getTypeListId(typeArguments); + var instantiation = instantiations.get(id); + if (!instantiation) { + instantiations.set(id, instantiation = createSignatureInstantiation(signature, typeArguments)); + } + return instantiation; + } + function createSignatureInstantiation(signature, typeArguments) { + return instantiateSignature(signature, createSignatureTypeMapper(signature, typeArguments), /*eraseTypeParameters*/ true); + } + function createSignatureTypeMapper(signature, typeArguments) { + return createTypeMapper(signature.typeParameters, typeArguments); + } + function getErasedSignature(signature) { + return signature.typeParameters ? + signature.erasedSignatureCache || (signature.erasedSignatureCache = createErasedSignature(signature)) : + signature; + } + function createErasedSignature(signature) { + // Create an instantiation of the signature where all type arguments are the any type. + return instantiateSignature(signature, createTypeEraser(signature.typeParameters), /*eraseTypeParameters*/ true); + } + function getCanonicalSignature(signature) { + return signature.typeParameters ? + signature.canonicalSignatureCache || (signature.canonicalSignatureCache = createCanonicalSignature(signature)) : + signature; + } + function createCanonicalSignature(signature) { + // Create an instantiation of the signature where each unconstrained type parameter is replaced with + // its original. When a generic class or interface is instantiated, each generic method in the class or + // interface is instantiated with a fresh set of cloned type parameters (which we need to handle scenarios + // where different generations of the same type parameter are in scope). This leads to a lot of new type + // identities, and potentially a lot of work comparing those identities, so here we create an instantiation + // that uses the original type identities for all unconstrained type parameters. + return getSignatureInstantiation(signature, ts.map(signature.typeParameters, function (tp) { return tp.target && !getConstraintOfTypeParameter(tp.target) ? tp.target : tp; }), ts.isInJSFile(signature.declaration)); + } + function getBaseSignature(signature) { + var typeParameters = signature.typeParameters; + if (typeParameters) { + var typeEraser_1 = createTypeEraser(typeParameters); + var baseConstraints = ts.map(typeParameters, function (tp) { return instantiateType(getBaseConstraintOfType(tp), typeEraser_1) || emptyObjectType; }); + return instantiateSignature(signature, createTypeMapper(typeParameters, baseConstraints), /*eraseTypeParameters*/ true); + } + return signature; + } + function getOrCreateTypeFromSignature(signature) { + // There are two ways to declare a construct signature, one is by declaring a class constructor + // using the constructor keyword, and the other is declaring a bare construct signature in an + // object type literal or interface (using the new keyword). Each way of declaring a constructor + // will result in a different declaration kind. + if (!signature.isolatedSignatureType) { + var isConstructor = signature.declaration.kind === 157 /* Constructor */ || signature.declaration.kind === 161 /* ConstructSignature */; // TODO: GH#18217 + var type = createObjectType(16 /* Anonymous */); + type.members = emptySymbols; + type.properties = ts.emptyArray; + type.callSignatures = !isConstructor ? [signature] : ts.emptyArray; + type.constructSignatures = isConstructor ? [signature] : ts.emptyArray; + signature.isolatedSignatureType = type; + } + return signature.isolatedSignatureType; + } + function getIndexSymbol(symbol) { + return symbol.members.get("__index" /* Index */); + } + function getIndexDeclarationOfSymbol(symbol, kind) { + var syntaxKind = kind === 1 /* Number */ ? 135 /* NumberKeyword */ : 138 /* StringKeyword */; + var indexSymbol = getIndexSymbol(symbol); + if (indexSymbol) { + for (var _i = 0, _a = indexSymbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + var node = ts.cast(decl, ts.isIndexSignatureDeclaration); + if (node.parameters.length === 1) { + var parameter = node.parameters[0]; + if (parameter.type && parameter.type.kind === syntaxKind) { + return node; + } + } + } + } + return undefined; + } + function createIndexInfo(type, isReadonly, declaration) { + return { type: type, isReadonly: isReadonly, declaration: declaration }; + } + function getIndexInfoOfSymbol(symbol, kind) { + var declaration = getIndexDeclarationOfSymbol(symbol, kind); + if (declaration) { + return createIndexInfo(declaration.type ? getTypeFromTypeNode(declaration.type) : anyType, ts.hasModifier(declaration, 64 /* Readonly */), declaration); + } + return undefined; + } + function getConstraintDeclaration(type) { + var decl = type.symbol && ts.getDeclarationOfKind(type.symbol, 150 /* TypeParameter */); + return decl && ts.getEffectiveConstraintOfTypeParameter(decl); + } + function getInferredTypeParameterConstraint(typeParameter) { + var inferences; + if (typeParameter.symbol) { + for (var _i = 0, _a = typeParameter.symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (declaration.parent.kind === 176 /* InferType */) { + // When an 'infer T' declaration is immediately contained in a type reference node + // (such as 'Foo'), T's constraint is inferred from the constraint of the + // corresponding type parameter in 'Foo'. When multiple 'infer T' declarations are + // present, we form an intersection of the inferred constraint types. + var grandParent = declaration.parent.parent; + if (grandParent.kind === 164 /* TypeReference */) { + var typeReference = grandParent; + var typeParameters = getTypeParametersForTypeReference(typeReference); + if (typeParameters) { + var index = typeReference.typeArguments.indexOf(declaration.parent); + if (index < typeParameters.length) { + var declaredConstraint = getConstraintOfTypeParameter(typeParameters[index]); + if (declaredConstraint) { + // Type parameter constraints can reference other type parameters so + // constraints need to be instantiated. If instantiation produces the + // type parameter itself, we discard that inference. For example, in + // type Foo = [T, U]; + // type Bar = T extends Foo ? Foo : T; + // the instantiated constraint for U is X, so we discard that inference. + var mapper = createTypeMapper(typeParameters, getEffectiveTypeArguments(typeReference, typeParameters)); + var constraint = instantiateType(declaredConstraint, mapper); + if (constraint !== typeParameter) { + inferences = ts.append(inferences, constraint); + } + } + } + } + } + // When an 'infer T' declaration is immediately contained in a rest parameter + // declaration, we infer an 'unknown[]' constraint. + else if (grandParent.kind === 151 /* Parameter */ && grandParent.dotDotDotToken) { + inferences = ts.append(inferences, createArrayType(unknownType)); + } + } + } + } + return inferences && getIntersectionType(inferences); + } + /** This is a worker function. Use getConstraintOfTypeParameter which guards against circular constraints. */ + function getConstraintFromTypeParameter(typeParameter) { + if (!typeParameter.constraint) { + if (typeParameter.target) { + var targetConstraint = getConstraintOfTypeParameter(typeParameter.target); + typeParameter.constraint = targetConstraint ? instantiateType(targetConstraint, typeParameter.mapper) : noConstraintType; + } + else { + var constraintDeclaration = getConstraintDeclaration(typeParameter); + typeParameter.constraint = constraintDeclaration ? getTypeFromTypeNode(constraintDeclaration) : + getInferredTypeParameterConstraint(typeParameter) || noConstraintType; + } + } + return typeParameter.constraint === noConstraintType ? undefined : typeParameter.constraint; + } + function getParentSymbolOfTypeParameter(typeParameter) { + var tp = ts.getDeclarationOfKind(typeParameter.symbol, 150 /* TypeParameter */); + var host = ts.isJSDocTemplateTag(tp.parent) ? ts.getHostSignatureFromJSDoc(tp.parent) : tp.parent; + return host && getSymbolOfNode(host); + } + function getTypeListId(types) { + var result = ""; + if (types) { + var length_3 = types.length; + var i = 0; + while (i < length_3) { + var startId = types[i].id; + var count = 1; + while (i + count < length_3 && types[i + count].id === startId + count) { + count++; + } + if (result.length) { + result += ","; + } + result += startId; + if (count > 1) { + result += ":" + count; + } + i += count; + } + } + return result; + } + // This function is used to propagate certain flags when creating new object type references and union types. + // It is only necessary to do so if a constituent type might be the undefined type, the null type, the type + // of an object literal or the anyFunctionType. This is because there are operations in the type checker + // that care about the presence of such types at arbitrary depth in a containing type. + function getPropagatingFlagsOfTypes(types, excludeKinds) { + var result = 0; + for (var _i = 0, types_5 = types; _i < types_5.length; _i++) { + var type = types_5[_i]; + if (!(type.flags & excludeKinds)) { + result |= type.flags; + } + } + return result & 939524096 /* PropagatingFlags */; + } + function createTypeReference(target, typeArguments) { + var id = getTypeListId(typeArguments); + var type = target.instantiations.get(id); + if (!type) { + type = createObjectType(4 /* Reference */, target.symbol); + target.instantiations.set(id, type); + type.flags |= typeArguments ? getPropagatingFlagsOfTypes(typeArguments, /*excludeKinds*/ 0) : 0; + type.target = target; + type.typeArguments = typeArguments; + } + return type; + } + function cloneTypeReference(source) { + var type = createType(source.flags); + type.symbol = source.symbol; + type.objectFlags = source.objectFlags; + type.target = source.target; + type.typeArguments = source.typeArguments; + return type; + } + function getTypeReferenceArity(type) { + return ts.length(type.target.typeParameters); + } + /** + * Get type from type-reference that reference to class or interface + */ + function getTypeFromClassOrInterfaceReference(node, symbol, typeArgs) { + var type = getDeclaredTypeOfSymbol(getMergedSymbol(symbol)); + var typeParameters = type.localTypeParameters; + if (typeParameters) { + var numTypeArguments = ts.length(node.typeArguments); + var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters); + var isJs = ts.isInJSFile(node); + var isJsImplicitAny = !noImplicitAny && isJs; + if (!isJsImplicitAny && (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length)) { + var missingAugmentsTag = isJs && ts.isExpressionWithTypeArguments(node) && !ts.isJSDocAugmentsTag(node.parent); + var diag = minTypeArgumentCount === typeParameters.length + ? missingAugmentsTag + ? ts.Diagnostics.Expected_0_type_arguments_provide_these_with_an_extends_tag + : ts.Diagnostics.Generic_type_0_requires_1_type_argument_s + : missingAugmentsTag + ? ts.Diagnostics.Expected_0_1_type_arguments_provide_these_with_an_extends_tag + : ts.Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments; + var typeStr = typeToString(type, /*enclosingDeclaration*/ undefined, 2 /* WriteArrayAsGenericType */); + error(node, diag, typeStr, minTypeArgumentCount, typeParameters.length); + if (!isJs) { + // TODO: Adopt same permissive behavior in TS as in JS to reduce follow-on editing experience failures (requires editing fillMissingTypeArguments) + return errorType; + } + } + // In a type reference, the outer type parameters of the referenced class or interface are automatically + // supplied as type arguments and the type reference only specifies arguments for the local type parameters + // of the class or interface. + var typeArguments = ts.concatenate(type.outerTypeParameters, fillMissingTypeArguments(typeArgs, typeParameters, minTypeArgumentCount, isJs)); + return createTypeReference(type, typeArguments); + } + return checkNoTypeArguments(node, symbol) ? type : errorType; + } + function getTypeAliasInstantiation(symbol, typeArguments) { + var type = getDeclaredTypeOfSymbol(symbol); + var links = getSymbolLinks(symbol); + var typeParameters = links.typeParameters; + var id = getTypeListId(typeArguments); + var instantiation = links.instantiations.get(id); + if (!instantiation) { + links.instantiations.set(id, instantiation = instantiateType(type, createTypeMapper(typeParameters, fillMissingTypeArguments(typeArguments, typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJSFile(symbol.valueDeclaration))))); + } + return instantiation; + } + /** + * Get type from reference to type alias. When a type alias is generic, the declared type of the type alias may include + * references to the type parameters of the alias. We replace those with the actual type arguments by instantiating the + * declared type. Instantiations are cached using the type identities of the type arguments as the key. + */ + function getTypeFromTypeAliasReference(node, symbol, typeArguments) { + var type = getDeclaredTypeOfSymbol(symbol); + var typeParameters = getSymbolLinks(symbol).typeParameters; + if (typeParameters) { + var numTypeArguments = ts.length(node.typeArguments); + var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters); + if (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length) { + error(node, minTypeArgumentCount === typeParameters.length + ? ts.Diagnostics.Generic_type_0_requires_1_type_argument_s + : ts.Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments, symbolToString(symbol), minTypeArgumentCount, typeParameters.length); + return errorType; + } + return getTypeAliasInstantiation(symbol, typeArguments); + } + return checkNoTypeArguments(node, symbol) ? type : errorType; + } + function getTypeReferenceName(node) { + switch (node.kind) { + case 164 /* TypeReference */: + return node.typeName; + case 211 /* ExpressionWithTypeArguments */: + // We only support expressions that are simple qualified names. For other + // expressions this produces undefined. + var expr = node.expression; + if (ts.isEntityNameExpression(expr)) { + return expr; + } + // fall through; + } + return undefined; + } + function resolveTypeReferenceName(typeReferenceName, meaning) { + if (!typeReferenceName) { + return unknownSymbol; + } + return resolveEntityName(typeReferenceName, meaning) || unknownSymbol; + } + function getTypeReferenceType(node, symbol) { + var typeArguments = typeArgumentsFromTypeReferenceNode(node); // Do unconditionally so we mark type arguments as referenced. + if (symbol === unknownSymbol) { + return errorType; + } + var type = getTypeReferenceTypeWorker(node, symbol, typeArguments); + if (type) { + return type; + } + // JS enums are 'string' or 'number', not an enum type. + var enumTag = ts.isInJSFile(node) && symbol.valueDeclaration && ts.getJSDocEnumTag(symbol.valueDeclaration); + if (enumTag) { + var links = getNodeLinks(enumTag); + if (!pushTypeResolution(enumTag, 5 /* EnumTagType */)) { + return errorType; + } + var type_4 = enumTag.typeExpression ? getTypeFromTypeNode(enumTag.typeExpression) : errorType; + if (!popTypeResolution()) { + type_4 = errorType; + error(node, ts.Diagnostics.Enum_type_0_circularly_references_itself, symbolToString(symbol)); + } + return (links.resolvedEnumType = type_4); + } + // Get type from reference to named type that cannot be generic (enum or type parameter) + var res = tryGetDeclaredTypeOfSymbol(symbol); + if (res) { + return checkNoTypeArguments(node, symbol) ? + res.flags & 262144 /* TypeParameter */ ? getConstrainedTypeVariable(res, node) : getRegularTypeOfLiteralType(res) : + errorType; + } + if (!(symbol.flags & 67220415 /* Value */ && isJSDocTypeReference(node))) { + return errorType; + } + var jsdocType = getJSDocTypeReference(node, symbol, typeArguments); + if (jsdocType) { + return jsdocType; + } + // Resolve the type reference as a Type for the purpose of reporting errors. + resolveTypeReferenceName(getTypeReferenceName(node), 67897832 /* Type */); + return getTypeOfSymbol(symbol); + } + /** + * A jsdoc TypeReference may have resolved to a value (as opposed to a type). If + * the symbol is a constructor function, return the inferred class type; otherwise, + * the type of this reference is just the type of the value we resolved to. + */ + function getJSDocTypeReference(node, symbol, typeArguments) { + if (!pushTypeResolution(symbol, 6 /* JSDocTypeReference */)) { + return errorType; + } + var assignedType = getAssignedClassType(symbol); + var valueType = getTypeOfSymbol(symbol); + var referenceType = valueType.symbol && valueType.symbol !== symbol && !isInferredClassType(valueType) && getTypeReferenceTypeWorker(node, valueType.symbol, typeArguments); + if (!popTypeResolution()) { + getSymbolLinks(symbol).resolvedJSDocType = errorType; + error(node, ts.Diagnostics.JSDoc_type_0_circularly_references_itself, symbolToString(symbol)); + return errorType; + } + if (referenceType || assignedType) { + // TODO: GH#18217 (should the `|| assignedType` be at a lower precedence?) + var type = (referenceType && assignedType ? getIntersectionType([assignedType, referenceType]) : referenceType || assignedType); + return getSymbolLinks(symbol).resolvedJSDocType = type; + } + } + function getTypeReferenceTypeWorker(node, symbol, typeArguments) { + if (symbol.flags & (32 /* Class */ | 64 /* Interface */)) { + if (symbol.valueDeclaration && ts.isBinaryExpression(symbol.valueDeclaration.parent)) { + var jsdocType = getJSDocTypeReference(node, symbol, typeArguments); + if (jsdocType) { + return jsdocType; + } + } + return getTypeFromClassOrInterfaceReference(node, symbol, typeArguments); + } + if (symbol.flags & 524288 /* TypeAlias */) { + return getTypeFromTypeAliasReference(node, symbol, typeArguments); + } + if (symbol.flags & 16 /* Function */ && + isJSDocTypeReference(node) && + (symbol.members || ts.getJSDocClassTag(symbol.valueDeclaration))) { + return getInferredClassType(symbol); + } + } + function getSubstitutionType(typeVariable, substitute) { + var result = createType(33554432 /* Substitution */); + result.typeVariable = typeVariable; + result.substitute = substitute; + return result; + } + function isUnaryTupleTypeNode(node) { + return node.kind === 170 /* TupleType */ && node.elementTypes.length === 1; + } + function getImpliedConstraint(typeVariable, checkNode, extendsNode) { + return isUnaryTupleTypeNode(checkNode) && isUnaryTupleTypeNode(extendsNode) ? getImpliedConstraint(typeVariable, checkNode.elementTypes[0], extendsNode.elementTypes[0]) : + getActualTypeVariable(getTypeFromTypeNode(checkNode)) === typeVariable ? getTypeFromTypeNode(extendsNode) : + undefined; + } + function getConstrainedTypeVariable(typeVariable, node) { + var constraints; + while (node && !ts.isStatement(node) && node.kind !== 291 /* JSDocComment */) { + var parent = node.parent; + if (parent.kind === 175 /* ConditionalType */ && node === parent.trueType) { + var constraint = getImpliedConstraint(typeVariable, parent.checkType, parent.extendsType); + if (constraint) { + constraints = ts.append(constraints, constraint); + } + } + node = parent; + } + return constraints ? getSubstitutionType(typeVariable, getIntersectionType(ts.append(constraints, typeVariable))) : typeVariable; + } + function isJSDocTypeReference(node) { + return !!(node.flags & 2097152 /* JSDoc */) && (node.kind === 164 /* TypeReference */ || node.kind === 183 /* ImportType */); + } + function checkNoTypeArguments(node, symbol) { + if (node.typeArguments) { + error(node, ts.Diagnostics.Type_0_is_not_generic, symbol ? symbolToString(symbol) : node.typeName ? ts.declarationNameToString(node.typeName) : "(anonymous)"); + return false; + } + return true; + } + function getIntendedTypeFromJSDocTypeReference(node) { + if (ts.isIdentifier(node.typeName)) { + var typeArgs = node.typeArguments; + switch (node.typeName.escapedText) { + case "String": + checkNoTypeArguments(node); + return stringType; + case "Number": + checkNoTypeArguments(node); + return numberType; + case "Boolean": + checkNoTypeArguments(node); + return booleanType; + case "Void": + checkNoTypeArguments(node); + return voidType; + case "Undefined": + checkNoTypeArguments(node); + return undefinedType; + case "Null": + checkNoTypeArguments(node); + return nullType; + case "Function": + case "function": + checkNoTypeArguments(node); + return globalFunctionType; + case "Array": + case "array": + return !typeArgs || !typeArgs.length ? anyArrayType : undefined; + case "Promise": + case "promise": + return !typeArgs || !typeArgs.length ? createPromiseType(anyType) : undefined; + case "Object": + if (typeArgs && typeArgs.length === 2) { + if (ts.isJSDocIndexSignature(node)) { + var indexed = getTypeFromTypeNode(typeArgs[0]); + var target = getTypeFromTypeNode(typeArgs[1]); + var index = createIndexInfo(target, /*isReadonly*/ false); + return createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, indexed === stringType ? index : undefined, indexed === numberType ? index : undefined); + } + return anyType; + } + checkNoTypeArguments(node); + return anyType; + } + } + } + function getTypeFromJSDocNullableTypeNode(node) { + var type = getTypeFromTypeNode(node.type); + return strictNullChecks ? getNullableType(type, 65536 /* Null */) : type; + } + function getTypeFromTypeReference(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + var symbol = void 0; + var type = void 0; + var meaning = 67897832 /* Type */; + if (isJSDocTypeReference(node)) { + type = getIntendedTypeFromJSDocTypeReference(node); + meaning |= 67220415 /* Value */; + } + if (!type) { + symbol = resolveTypeReferenceName(getTypeReferenceName(node), meaning); + type = getTypeReferenceType(node, symbol); + } + // Cache both the resolved symbol and the resolved type. The resolved symbol is needed when we check the + // type reference in checkTypeReferenceNode. + links.resolvedSymbol = symbol; + links.resolvedType = type; + } + return links.resolvedType; + } + function typeArgumentsFromTypeReferenceNode(node) { + return ts.map(node.typeArguments, getTypeFromTypeNode); + } + function getTypeFromTypeQueryNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + // TypeScript 1.0 spec (April 2014): 3.6.3 + // The expression is processed as an identifier expression (section 4.3) + // or property access expression(section 4.10), + // the widened type(section 3.9) of which becomes the result. + links.resolvedType = getRegularTypeOfLiteralType(getWidenedType(checkExpression(node.exprName))); + } + return links.resolvedType; + } + function getTypeOfGlobalSymbol(symbol, arity) { + function getTypeDeclaration(symbol) { + var declarations = symbol.declarations; + for (var _i = 0, declarations_3 = declarations; _i < declarations_3.length; _i++) { + var declaration = declarations_3[_i]; + switch (declaration.kind) { + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + case 243 /* EnumDeclaration */: + return declaration; + } + } + } + if (!symbol) { + return arity ? emptyGenericType : emptyObjectType; + } + var type = getDeclaredTypeOfSymbol(symbol); + if (!(type.flags & 524288 /* Object */)) { + error(getTypeDeclaration(symbol), ts.Diagnostics.Global_type_0_must_be_a_class_or_interface_type, ts.symbolName(symbol)); + return arity ? emptyGenericType : emptyObjectType; + } + if (ts.length(type.typeParameters) !== arity) { + error(getTypeDeclaration(symbol), ts.Diagnostics.Global_type_0_must_have_1_type_parameter_s, ts.symbolName(symbol), arity); + return arity ? emptyGenericType : emptyObjectType; + } + return type; + } + function getGlobalValueSymbol(name, reportErrors) { + return getGlobalSymbol(name, 67220415 /* Value */, reportErrors ? ts.Diagnostics.Cannot_find_global_value_0 : undefined); + } + function getGlobalTypeSymbol(name, reportErrors) { + return getGlobalSymbol(name, 67897832 /* Type */, reportErrors ? ts.Diagnostics.Cannot_find_global_type_0 : undefined); + } + function getGlobalSymbol(name, meaning, diagnostic) { + // Don't track references for global symbols anyway, so value if `isReference` is arbitrary + return resolveName(undefined, name, meaning, diagnostic, name, /*isUse*/ false); + } + function getGlobalType(name, arity, reportErrors) { + var symbol = getGlobalTypeSymbol(name, reportErrors); + return symbol || reportErrors ? getTypeOfGlobalSymbol(symbol, arity) : undefined; + } + function getGlobalTypedPropertyDescriptorType() { + return deferredGlobalTypedPropertyDescriptorType || (deferredGlobalTypedPropertyDescriptorType = getGlobalType("TypedPropertyDescriptor", /*arity*/ 1, /*reportErrors*/ true)) || emptyGenericType; + } + function getGlobalTemplateStringsArrayType() { + return deferredGlobalTemplateStringsArrayType || (deferredGlobalTemplateStringsArrayType = getGlobalType("TemplateStringsArray", /*arity*/ 0, /*reportErrors*/ true)) || emptyObjectType; + } + function getGlobalImportMetaType() { + return deferredGlobalImportMetaType || (deferredGlobalImportMetaType = getGlobalType("ImportMeta", /*arity*/ 0, /*reportErrors*/ true)) || emptyObjectType; + } + function getGlobalESSymbolConstructorSymbol(reportErrors) { + return deferredGlobalESSymbolConstructorSymbol || (deferredGlobalESSymbolConstructorSymbol = getGlobalValueSymbol("Symbol", reportErrors)); + } + function getGlobalESSymbolType(reportErrors) { + return deferredGlobalESSymbolType || (deferredGlobalESSymbolType = getGlobalType("Symbol", /*arity*/ 0, reportErrors)) || emptyObjectType; + } + function getGlobalPromiseType(reportErrors) { + return deferredGlobalPromiseType || (deferredGlobalPromiseType = getGlobalType("Promise", /*arity*/ 1, reportErrors)) || emptyGenericType; + } + function getGlobalPromiseLikeType(reportErrors) { + return deferredGlobalPromiseLikeType || (deferredGlobalPromiseLikeType = getGlobalType("PromiseLike", /*arity*/ 1, reportErrors)) || emptyGenericType; + } + function getGlobalPromiseConstructorSymbol(reportErrors) { + return deferredGlobalPromiseConstructorSymbol || (deferredGlobalPromiseConstructorSymbol = getGlobalValueSymbol("Promise", reportErrors)); + } + function getGlobalPromiseConstructorLikeType(reportErrors) { + return deferredGlobalPromiseConstructorLikeType || (deferredGlobalPromiseConstructorLikeType = getGlobalType("PromiseConstructorLike", /*arity*/ 0, reportErrors)) || emptyObjectType; + } + function getGlobalAsyncIterableType(reportErrors) { + return deferredGlobalAsyncIterableType || (deferredGlobalAsyncIterableType = getGlobalType("AsyncIterable", /*arity*/ 1, reportErrors)) || emptyGenericType; + } + function getGlobalAsyncIteratorType(reportErrors) { + return deferredGlobalAsyncIteratorType || (deferredGlobalAsyncIteratorType = getGlobalType("AsyncIterator", /*arity*/ 1, reportErrors)) || emptyGenericType; + } + function getGlobalAsyncIterableIteratorType(reportErrors) { + return deferredGlobalAsyncIterableIteratorType || (deferredGlobalAsyncIterableIteratorType = getGlobalType("AsyncIterableIterator", /*arity*/ 1, reportErrors)) || emptyGenericType; + } + function getGlobalIterableType(reportErrors) { + return deferredGlobalIterableType || (deferredGlobalIterableType = getGlobalType("Iterable", /*arity*/ 1, reportErrors)) || emptyGenericType; + } + function getGlobalIteratorType(reportErrors) { + return deferredGlobalIteratorType || (deferredGlobalIteratorType = getGlobalType("Iterator", /*arity*/ 1, reportErrors)) || emptyGenericType; + } + function getGlobalIterableIteratorType(reportErrors) { + return deferredGlobalIterableIteratorType || (deferredGlobalIterableIteratorType = getGlobalType("IterableIterator", /*arity*/ 1, reportErrors)) || emptyGenericType; + } + function getGlobalTypeOrUndefined(name, arity) { + if (arity === void 0) { arity = 0; } + var symbol = getGlobalSymbol(name, 67897832 /* Type */, /*diagnostic*/ undefined); + return symbol && getTypeOfGlobalSymbol(symbol, arity); + } + function getGlobalExtractSymbol() { + return deferredGlobalExtractSymbol || (deferredGlobalExtractSymbol = getGlobalSymbol("Extract", 524288 /* TypeAlias */, ts.Diagnostics.Cannot_find_global_type_0)); // TODO: GH#18217 + } + function getGlobalExcludeSymbol() { + return deferredGlobalExcludeSymbol || (deferredGlobalExcludeSymbol = getGlobalSymbol("Exclude", 524288 /* TypeAlias */, ts.Diagnostics.Cannot_find_global_type_0)); // TODO: GH#18217 + } + function getGlobalPickSymbol() { + return deferredGlobalPickSymbol || (deferredGlobalPickSymbol = getGlobalSymbol("Pick", 524288 /* TypeAlias */, ts.Diagnostics.Cannot_find_global_type_0)); // TODO: GH#18217 + } + function getGlobalBigIntType(reportErrors) { + return deferredGlobalBigIntType || (deferredGlobalBigIntType = getGlobalType("BigInt", /*arity*/ 0, reportErrors)) || emptyObjectType; + } + /** + * Instantiates a global type that is generic with some element type, and returns that instantiation. + */ + function createTypeFromGenericGlobalType(genericGlobalType, typeArguments) { + return genericGlobalType !== emptyGenericType ? createTypeReference(genericGlobalType, typeArguments) : emptyObjectType; + } + function createTypedPropertyDescriptorType(propertyType) { + return createTypeFromGenericGlobalType(getGlobalTypedPropertyDescriptorType(), [propertyType]); + } + function createAsyncIterableType(iteratedType) { + return createTypeFromGenericGlobalType(getGlobalAsyncIterableType(/*reportErrors*/ true), [iteratedType]); + } + function createAsyncIterableIteratorType(iteratedType) { + return createTypeFromGenericGlobalType(getGlobalAsyncIterableIteratorType(/*reportErrors*/ true), [iteratedType]); + } + function createIterableType(iteratedType) { + return createTypeFromGenericGlobalType(getGlobalIterableType(/*reportErrors*/ true), [iteratedType]); + } + function createIterableIteratorType(iteratedType) { + return createTypeFromGenericGlobalType(getGlobalIterableIteratorType(/*reportErrors*/ true), [iteratedType]); + } + function createArrayType(elementType) { + return createTypeFromGenericGlobalType(globalArrayType, [elementType]); + } + function createReadonlyArrayType(elementType) { + return createTypeFromGenericGlobalType(globalReadonlyArrayType, [elementType]); + } + function getTypeFromArrayTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + links.resolvedType = createArrayType(getTypeFromTypeNode(node.elementType)); + } + return links.resolvedType; + } + // We represent tuple types as type references to synthesized generic interface types created by + // this function. The types are of the form: + // + // interface Tuple extends Array { 0: T0, 1: T1, 2: T2, ... } + // + // Note that the generic type created by this function has no symbol associated with it. The same + // is true for each of the synthesized type parameters. + function createTupleTypeOfArity(arity, minLength, hasRestElement, associatedNames) { + var typeParameters; + var properties = []; + var maxLength = hasRestElement ? arity - 1 : arity; + if (arity) { + typeParameters = new Array(arity); + for (var i = 0; i < arity; i++) { + var typeParameter = typeParameters[i] = createType(262144 /* TypeParameter */); + if (i < maxLength) { + var property = createSymbol(4 /* Property */ | (i >= minLength ? 16777216 /* Optional */ : 0), "" + i); + property.type = typeParameter; + properties.push(property); + } + } + } + var literalTypes = []; + for (var i = minLength; i <= maxLength; i++) + literalTypes.push(getLiteralType(i)); + var lengthSymbol = createSymbol(4 /* Property */, "length"); + lengthSymbol.type = hasRestElement ? numberType : getUnionType(literalTypes); + properties.push(lengthSymbol); + var type = createObjectType(8 /* Tuple */ | 4 /* Reference */); + type.typeParameters = typeParameters; + type.outerTypeParameters = undefined; + type.localTypeParameters = typeParameters; + type.instantiations = ts.createMap(); + type.instantiations.set(getTypeListId(type.typeParameters), type); + type.target = type; + type.typeArguments = type.typeParameters; + type.thisType = createType(262144 /* TypeParameter */); + type.thisType.isThisType = true; + type.thisType.constraint = type; + type.declaredProperties = properties; + type.declaredCallSignatures = ts.emptyArray; + type.declaredConstructSignatures = ts.emptyArray; + type.declaredStringIndexInfo = undefined; + type.declaredNumberIndexInfo = undefined; + type.minLength = minLength; + type.hasRestElement = hasRestElement; + type.associatedNames = associatedNames; + return type; + } + function getTupleTypeOfArity(arity, minLength, hasRestElement, associatedNames) { + var key = arity + (hasRestElement ? "+" : ",") + minLength + (associatedNames && associatedNames.length ? "," + associatedNames.join(",") : ""); + var type = tupleTypes.get(key); + if (!type) { + tupleTypes.set(key, type = createTupleTypeOfArity(arity, minLength, hasRestElement, associatedNames)); + } + return type; + } + function createTupleType(elementTypes, minLength, hasRestElement, associatedNames) { + if (minLength === void 0) { minLength = elementTypes.length; } + if (hasRestElement === void 0) { hasRestElement = false; } + var arity = elementTypes.length; + if (arity === 1 && hasRestElement) { + return createArrayType(elementTypes[0]); + } + var tupleType = getTupleTypeOfArity(arity, minLength, arity > 0 && hasRestElement, associatedNames); + return elementTypes.length ? createTypeReference(tupleType, elementTypes) : tupleType; + } + function getTypeFromTupleTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + var lastElement = ts.lastOrUndefined(node.elementTypes); + var restElement_1 = lastElement && lastElement.kind === 172 /* RestType */ ? lastElement : undefined; + var minLength = ts.findLastIndex(node.elementTypes, function (n) { return n.kind !== 171 /* OptionalType */ && n !== restElement_1; }) + 1; + var elementTypes = ts.map(node.elementTypes, function (n) { + var type = getTypeFromTypeNode(n); + return n === restElement_1 && getIndexTypeOfType(type, 1 /* Number */) || type; + }); + links.resolvedType = createTupleType(elementTypes, minLength, !!restElement_1); + } + return links.resolvedType; + } + function sliceTupleType(type, index) { + var tuple = type.target; + if (tuple.hasRestElement) { + // don't slice off rest element + index = Math.min(index, getTypeReferenceArity(type) - 1); + } + return createTupleType((type.typeArguments || ts.emptyArray).slice(index), Math.max(0, tuple.minLength - index), tuple.hasRestElement, tuple.associatedNames && tuple.associatedNames.slice(index)); + } + function getTypeFromOptionalTypeNode(node) { + var type = getTypeFromTypeNode(node.type); + return strictNullChecks ? getOptionalType(type) : type; + } + function getTypeId(type) { + return type.id; + } + function containsType(types, type) { + return ts.binarySearch(types, type, getTypeId, ts.compareValues) >= 0; + } + function insertType(types, type) { + var index = ts.binarySearch(types, type, getTypeId, ts.compareValues); + if (index < 0) { + types.splice(~index, 0, type); + return true; + } + return false; + } + // Return true if the given intersection type contains + // more than one unit type or, + // an object type and a nullable type (null or undefined), or + // a string-like type and a type known to be non-string-like, or + // a number-like type and a type known to be non-number-like, or + // a symbol-like type and a type known to be non-symbol-like, or + // a void-like type and a type known to be non-void-like, or + // a non-primitive type and a type known to be primitive. + function isEmptyIntersectionType(type) { + var combined = 0; + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (t.flags & 109440 /* Unit */ && combined & 109440 /* Unit */) { + return true; + } + combined |= t.flags; + if (combined & 98304 /* Nullable */ && combined & (524288 /* Object */ | 67108864 /* NonPrimitive */) || + combined & 67108864 /* NonPrimitive */ && combined & (67238908 /* DisjointDomains */ & ~67108864 /* NonPrimitive */) || + combined & 132 /* StringLike */ && combined & (67238908 /* DisjointDomains */ & ~132 /* StringLike */) || + combined & 296 /* NumberLike */ && combined & (67238908 /* DisjointDomains */ & ~296 /* NumberLike */) || + combined & 2112 /* BigIntLike */ && combined & (67238908 /* DisjointDomains */ & ~2112 /* BigIntLike */) || + combined & 12288 /* ESSymbolLike */ && combined & (67238908 /* DisjointDomains */ & ~12288 /* ESSymbolLike */) || + combined & 49152 /* VoidLike */ && combined & (67238908 /* DisjointDomains */ & ~49152 /* VoidLike */)) { + return true; + } + } + return false; + } + function addTypeToUnion(typeSet, includes, type) { + var flags = type.flags; + if (flags & 1048576 /* Union */) { + return addTypesToUnion(typeSet, includes, type.types); + } + // We ignore 'never' types in unions. Likewise, we ignore intersections of unit types as they are + // another form of 'never' (in that they have an empty value domain). We could in theory turn + // intersections of unit types into 'never' upon construction, but deferring the reduction makes it + // easier to reason about their origin. + if (!(flags & 131072 /* Never */ || flags & 2097152 /* Intersection */ && isEmptyIntersectionType(type))) { + includes |= flags & ~939524096 /* ConstructionFlags */; + if (type === wildcardType) + includes |= 268435456 /* Wildcard */; + if (!strictNullChecks && flags & 98304 /* Nullable */) { + if (!(flags & 134217728 /* ContainsWideningType */)) + includes |= 134217728 /* NonWideningType */; + } + else { + var len = typeSet.length; + var index = len && type.id > typeSet[len - 1].id ? ~len : ts.binarySearch(typeSet, type, getTypeId, ts.compareValues); + if (index < 0) { + typeSet.splice(~index, 0, type); + } + } + } + return includes; + } + // Add the given types to the given type set. Order is preserved, duplicates are removed, + // and nested types of the given kind are flattened into the set. + function addTypesToUnion(typeSet, includes, types) { + for (var _i = 0, types_6 = types; _i < types_6.length; _i++) { + var type = types_6[_i]; + includes = addTypeToUnion(typeSet, includes, type); + } + return includes; + } + function isSubtypeOfAny(source, targets) { + for (var _i = 0, targets_1 = targets; _i < targets_1.length; _i++) { + var target = targets_1[_i]; + if (source !== target && isTypeSubtypeOf(source, target) && (!(ts.getObjectFlags(getTargetType(source)) & 1 /* Class */) || + !(ts.getObjectFlags(getTargetType(target)) & 1 /* Class */) || + isTypeDerivedFrom(source, target))) { + return true; + } + } + return false; + } + function isSetOfLiteralsFromSameEnum(types) { + var first = types[0]; + if (first.flags & 1024 /* EnumLiteral */) { + var firstEnum = getParentOfSymbol(first.symbol); + for (var i = 1; i < types.length; i++) { + var other = types[i]; + if (!(other.flags & 1024 /* EnumLiteral */) || (firstEnum !== getParentOfSymbol(other.symbol))) { + return false; + } + } + return true; + } + return false; + } + function removeSubtypes(types) { + if (types.length === 0 || isSetOfLiteralsFromSameEnum(types)) { + return; + } + var i = types.length; + while (i > 0) { + i--; + if (isSubtypeOfAny(types[i], types)) { + ts.orderedRemoveItemAt(types, i); + } + } + } + function removeRedundantLiteralTypes(types, includes) { + var i = types.length; + while (i > 0) { + i--; + var t = types[i]; + var remove = t.flags & 128 /* StringLiteral */ && includes & 4 /* String */ || + t.flags & 256 /* NumberLiteral */ && includes & 8 /* Number */ || + t.flags & 2048 /* BigIntLiteral */ && includes & 64 /* BigInt */ || + t.flags & 8192 /* UniqueESSymbol */ && includes & 4096 /* ESSymbol */ || + isFreshLiteralType(t) && containsType(types, t.regularType); + if (remove) { + ts.orderedRemoveItemAt(types, i); + } + } + } + // We sort and deduplicate the constituent types based on object identity. If the subtypeReduction + // flag is specified we also reduce the constituent type set to only include types that aren't subtypes + // of other types. Subtype reduction is expensive for large union types and is possible only when union + // types are known not to circularly reference themselves (as is the case with union types created by + // expression constructs such as array literals and the || and ?: operators). Named types can + // circularly reference themselves and therefore cannot be subtype reduced during their declaration. + // For example, "type Item = string | (() => Item" is a named type that circularly references itself. + function getUnionType(types, unionReduction, aliasSymbol, aliasTypeArguments) { + if (unionReduction === void 0) { unionReduction = 1 /* Literal */; } + if (types.length === 0) { + return neverType; + } + if (types.length === 1) { + return types[0]; + } + var typeSet = []; + var includes = addTypesToUnion(typeSet, 0, types); + if (unionReduction !== 0 /* None */) { + if (includes & 3 /* AnyOrUnknown */) { + return includes & 1 /* Any */ ? includes & 268435456 /* Wildcard */ ? wildcardType : anyType : unknownType; + } + switch (unionReduction) { + case 1 /* Literal */: + if (includes & 8576 /* StringOrNumberLiteralOrUnique */ | 512 /* BooleanLiteral */) { + removeRedundantLiteralTypes(typeSet, includes); + } + break; + case 2 /* Subtype */: + removeSubtypes(typeSet); + break; + } + if (typeSet.length === 0) { + return includes & 65536 /* Null */ ? includes & 134217728 /* NonWideningType */ ? nullType : nullWideningType : + includes & 32768 /* Undefined */ ? includes & 134217728 /* NonWideningType */ ? undefinedType : undefinedWideningType : + neverType; + } + } + return getUnionTypeFromSortedList(typeSet, !(includes & 66994211 /* NotPrimitiveUnion */), aliasSymbol, aliasTypeArguments); + } + function getUnionTypePredicate(signatures) { + var first; + var types = []; + for (var _i = 0, signatures_2 = signatures; _i < signatures_2.length; _i++) { + var sig = signatures_2[_i]; + var pred = getTypePredicateOfSignature(sig); + if (!pred) { + continue; + } + if (first) { + if (!typePredicateKindsMatch(first, pred)) { + // No common type predicate. + return undefined; + } + } + else { + first = pred; + } + types.push(pred.type); + } + if (!first) { + // No union signatures had a type predicate. + return undefined; + } + var unionType = getUnionType(types); + return ts.isIdentifierTypePredicate(first) + ? createIdentifierTypePredicate(first.parameterName, first.parameterIndex, unionType) + : createThisTypePredicate(unionType); + } + function typePredicateKindsMatch(a, b) { + return ts.isIdentifierTypePredicate(a) + ? ts.isIdentifierTypePredicate(b) && a.parameterIndex === b.parameterIndex + : !ts.isIdentifierTypePredicate(b); + } + // This function assumes the constituent type list is sorted and deduplicated. + function getUnionTypeFromSortedList(types, primitiveTypesOnly, aliasSymbol, aliasTypeArguments) { + if (types.length === 0) { + return neverType; + } + if (types.length === 1) { + return types[0]; + } + var id = getTypeListId(types); + var type = unionTypes.get(id); + if (!type) { + var propagatedFlags = getPropagatingFlagsOfTypes(types, /*excludeKinds*/ 98304 /* Nullable */); + type = createType(1048576 /* Union */ | propagatedFlags); + unionTypes.set(id, type); + type.types = types; + type.primitiveTypesOnly = primitiveTypesOnly; + /* + Note: This is the alias symbol (or lack thereof) that we see when we first encounter this union type. + For aliases of identical unions, eg `type T = A | B; type U = A | B`, the symbol of the first alias encountered is the aliasSymbol. + (In the language service, the order may depend on the order in which a user takes actions, such as hovering over symbols.) + It's important that we create equivalent union types only once, so that's an unfortunate side effect. + */ + type.aliasSymbol = aliasSymbol; + type.aliasTypeArguments = aliasTypeArguments; + } + return type; + } + function getTypeFromUnionTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + var aliasSymbol = getAliasSymbolForTypeNode(node); + links.resolvedType = getUnionType(ts.map(node.types, getTypeFromTypeNode), 1 /* Literal */, aliasSymbol, getTypeArgumentsForAliasSymbol(aliasSymbol)); + } + return links.resolvedType; + } + function addTypeToIntersection(typeSet, includes, type) { + var flags = type.flags; + if (flags & 2097152 /* Intersection */) { + return addTypesToIntersection(typeSet, includes, type.types); + } + if (isEmptyAnonymousObjectType(type)) { + if (!(includes & 536870912 /* EmptyObject */)) { + includes |= 536870912 /* EmptyObject */; + typeSet.push(type); + } + } + else { + includes |= flags & ~939524096 /* ConstructionFlags */; + if (flags & 3 /* AnyOrUnknown */) { + if (type === wildcardType) + includes |= 268435456 /* Wildcard */; + } + else if ((strictNullChecks || !(flags & 98304 /* Nullable */)) && !ts.contains(typeSet, type)) { + typeSet.push(type); + } + } + return includes; + } + // Add the given types to the given type set. Order is preserved, freshness is removed from literal + // types, duplicates are removed, and nested types of the given kind are flattened into the set. + function addTypesToIntersection(typeSet, includes, types) { + for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { + var type = types_7[_i]; + includes = addTypeToIntersection(typeSet, includes, getRegularTypeOfLiteralType(type)); + } + return includes; + } + function removeRedundantPrimitiveTypes(types, includes) { + var i = types.length; + while (i > 0) { + i--; + var t = types[i]; + var remove = t.flags & 4 /* String */ && includes & 128 /* StringLiteral */ || + t.flags & 8 /* Number */ && includes & 256 /* NumberLiteral */ || + t.flags & 64 /* BigInt */ && includes & 2048 /* BigIntLiteral */ || + t.flags & 4096 /* ESSymbol */ && includes & 8192 /* UniqueESSymbol */; + if (remove) { + ts.orderedRemoveItemAt(types, i); + } + } + } + // Check that the given type has a match in every union. A given type is matched by + // an identical type, and a literal type is additionally matched by its corresponding + // primitive type. + function eachUnionContains(unionTypes, type) { + for (var _i = 0, unionTypes_1 = unionTypes; _i < unionTypes_1.length; _i++) { + var u = unionTypes_1[_i]; + if (!containsType(u.types, type)) { + var primitive = type.flags & 128 /* StringLiteral */ ? stringType : + type.flags & 256 /* NumberLiteral */ ? numberType : + type.flags & 2048 /* BigIntLiteral */ ? bigintType : + type.flags & 8192 /* UniqueESSymbol */ ? esSymbolType : + undefined; + if (!primitive || !containsType(u.types, primitive)) { + return false; + } + } + } + return true; + } + // If the given list of types contains more than one union of primitive types, replace the + // first with a union containing an intersection of those primitive types, then remove the + // other unions and return true. Otherwise, do nothing and return false. + function intersectUnionsOfPrimitiveTypes(types) { + var unionTypes; + var index = ts.findIndex(types, function (t) { return !!(t.flags & 1048576 /* Union */) && t.primitiveTypesOnly; }); + if (index < 0) { + return false; + } + var i = index + 1; + // Remove all but the first union of primitive types and collect them in + // the unionTypes array. + while (i < types.length) { + var t = types[i]; + if (t.flags & 1048576 /* Union */ && t.primitiveTypesOnly) { + (unionTypes || (unionTypes = [types[index]])).push(t); + ts.orderedRemoveItemAt(types, i); + } + else { + i++; + } + } + // Return false if there was only one union of primitive types + if (!unionTypes) { + return false; + } + // We have more than one union of primitive types, now intersect them. For each + // type in each union we check if the type is matched in every union and if so + // we include it in the result. + var checked = []; + var result = []; + for (var _i = 0, unionTypes_2 = unionTypes; _i < unionTypes_2.length; _i++) { + var u = unionTypes_2[_i]; + for (var _a = 0, _b = u.types; _a < _b.length; _a++) { + var t = _b[_a]; + if (insertType(checked, t)) { + if (eachUnionContains(unionTypes, t)) { + insertType(result, t); + } + } + } + } + // Finally replace the first union with the result + types[index] = getUnionTypeFromSortedList(result, /*primitiveTypesOnly*/ true); + return true; + } + // We normalize combinations of intersection and union types based on the distributive property of the '&' + // operator. Specifically, because X & (A | B) is equivalent to X & A | X & B, we can transform intersection + // types with union type constituents into equivalent union types with intersection type constituents and + // effectively ensure that union types are always at the top level in type representations. + // + // We do not perform structural deduplication on intersection types. Intersection types are created only by the & + // type operator and we can't reduce those because we want to support recursive intersection types. For example, + // a type alias of the form "type List = T & { next: List }" cannot be reduced during its declaration. + // Also, unlike union types, the order of the constituent types is preserved in order that overload resolution + // for intersections of types with signatures can be deterministic. + function getIntersectionType(types, aliasSymbol, aliasTypeArguments) { + var typeSet = []; + var includes = addTypesToIntersection(typeSet, 0, types); + if (includes & 131072 /* Never */) { + return neverType; + } + if (includes & 1 /* Any */) { + return includes & 268435456 /* Wildcard */ ? wildcardType : anyType; + } + if (!strictNullChecks && includes & 98304 /* Nullable */) { + return includes & 32768 /* Undefined */ ? undefinedType : nullType; + } + if (includes & 4 /* String */ && includes & 128 /* StringLiteral */ || + includes & 8 /* Number */ && includes & 256 /* NumberLiteral */ || + includes & 64 /* BigInt */ && includes & 2048 /* BigIntLiteral */ || + includes & 4096 /* ESSymbol */ && includes & 8192 /* UniqueESSymbol */) { + removeRedundantPrimitiveTypes(typeSet, includes); + } + if (includes & 536870912 /* EmptyObject */ && includes & 524288 /* Object */) { + ts.orderedRemoveItemAt(typeSet, ts.findIndex(typeSet, isEmptyAnonymousObjectType)); + } + if (typeSet.length === 0) { + return unknownType; + } + if (typeSet.length === 1) { + return typeSet[0]; + } + if (includes & 1048576 /* Union */) { + if (intersectUnionsOfPrimitiveTypes(typeSet)) { + // When the intersection creates a reduced set (which might mean that *all* union types have + // disappeared), we restart the operation to get a new set of combined flags. Once we have + // reduced we'll never reduce again, so this occurs at most once. + return getIntersectionType(typeSet, aliasSymbol, aliasTypeArguments); + } + // We are attempting to construct a type of the form X & (A | B) & Y. Transform this into a type of + // the form X & A & Y | X & B & Y and recursively reduce until no union type constituents remain. + var unionIndex_1 = ts.findIndex(typeSet, function (t) { return (t.flags & 1048576 /* Union */) !== 0; }); + var unionType = typeSet[unionIndex_1]; + return getUnionType(ts.map(unionType.types, function (t) { return getIntersectionType(ts.replaceElement(typeSet, unionIndex_1, t)); }), 1 /* Literal */, aliasSymbol, aliasTypeArguments); + } + var id = getTypeListId(typeSet); + var type = intersectionTypes.get(id); + if (!type) { + var propagatedFlags = getPropagatingFlagsOfTypes(typeSet, /*excludeKinds*/ 98304 /* Nullable */); + type = createType(2097152 /* Intersection */ | propagatedFlags); + intersectionTypes.set(id, type); + type.types = typeSet; + type.aliasSymbol = aliasSymbol; // See comment in `getUnionTypeFromSortedList`. + type.aliasTypeArguments = aliasTypeArguments; + } + return type; + } + function getTypeFromIntersectionTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + var aliasSymbol = getAliasSymbolForTypeNode(node); + links.resolvedType = getIntersectionType(ts.map(node.types, getTypeFromTypeNode), aliasSymbol, getTypeArgumentsForAliasSymbol(aliasSymbol)); + } + return links.resolvedType; + } + function createIndexType(type, stringsOnly) { + var result = createType(4194304 /* Index */); + result.type = type; + result.stringsOnly = stringsOnly; + return result; + } + function getIndexTypeForGenericType(type, stringsOnly) { + return stringsOnly ? + type.resolvedStringIndexType || (type.resolvedStringIndexType = createIndexType(type, /*stringsOnly*/ true)) : + type.resolvedIndexType || (type.resolvedIndexType = createIndexType(type, /*stringsOnly*/ false)); + } + function getLiteralTypeFromPropertyName(name) { + return ts.isIdentifier(name) ? getLiteralType(ts.unescapeLeadingUnderscores(name.escapedText)) : + getRegularTypeOfLiteralType(ts.isComputedPropertyName(name) ? checkComputedPropertyName(name) : checkExpression(name)); + } + function getBigIntLiteralType(node) { + return getLiteralType({ + negative: false, + base10Value: ts.parsePseudoBigInt(node.text) + }); + } + function getLiteralTypeFromProperty(prop, include) { + if (!(ts.getDeclarationModifierFlagsFromSymbol(prop) & 24 /* NonPublicAccessibilityModifier */)) { + var type = getLateBoundSymbol(prop).nameType; + if (!type && !ts.isKnownSymbol(prop)) { + if (prop.escapedName === "default" /* Default */) { + type = getLiteralType("default"); + } + else { + var name = prop.valueDeclaration && ts.getNameOfDeclaration(prop.valueDeclaration); + type = name && getLiteralTypeFromPropertyName(name) || getLiteralType(ts.symbolName(prop)); + } + } + if (type && type.flags & include) { + return type; + } + } + return neverType; + } + function getLiteralTypeFromProperties(type, include) { + return getUnionType(ts.map(getPropertiesOfType(type), function (t) { return getLiteralTypeFromProperty(t, include); })); + } + function getNonEnumNumberIndexInfo(type) { + var numberIndexInfo = getIndexInfoOfType(type, 1 /* Number */); + return numberIndexInfo !== enumNumberIndexInfo ? numberIndexInfo : undefined; + } + function getIndexType(type, stringsOnly) { + if (stringsOnly === void 0) { stringsOnly = keyofStringsOnly; } + return type.flags & 1048576 /* Union */ ? getIntersectionType(ts.map(type.types, function (t) { return getIndexType(t, stringsOnly); })) : + type.flags & 2097152 /* Intersection */ ? getUnionType(ts.map(type.types, function (t) { return getIndexType(t, stringsOnly); })) : + maybeTypeOfKind(type, 58982400 /* InstantiableNonPrimitive */) ? getIndexTypeForGenericType(type, stringsOnly) : + ts.getObjectFlags(type) & 32 /* Mapped */ ? getConstraintTypeFromMappedType(type) : + type === wildcardType ? wildcardType : + type.flags & 1 /* Any */ ? keyofConstraintType : + stringsOnly ? getIndexInfoOfType(type, 0 /* String */) ? stringType : getLiteralTypeFromProperties(type, 128 /* StringLiteral */) : + getIndexInfoOfType(type, 0 /* String */) ? getUnionType([stringType, numberType, getLiteralTypeFromProperties(type, 8192 /* UniqueESSymbol */)]) : + getNonEnumNumberIndexInfo(type) ? getUnionType([numberType, getLiteralTypeFromProperties(type, 128 /* StringLiteral */ | 8192 /* UniqueESSymbol */)]) : + getLiteralTypeFromProperties(type, 8576 /* StringOrNumberLiteralOrUnique */); + } + function getExtractStringType(type) { + if (keyofStringsOnly) { + return type; + } + var extractTypeAlias = getGlobalExtractSymbol(); + return extractTypeAlias ? getTypeAliasInstantiation(extractTypeAlias, [type, stringType]) : stringType; + } + function getIndexTypeOrString(type) { + var indexType = getExtractStringType(getIndexType(type)); + return indexType.flags & 131072 /* Never */ ? stringType : indexType; + } + function getTypeFromTypeOperatorNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + switch (node.operator) { + case 129 /* KeyOfKeyword */: + links.resolvedType = getIndexType(getTypeFromTypeNode(node.type)); + break; + case 142 /* UniqueKeyword */: + links.resolvedType = node.type.kind === 139 /* SymbolKeyword */ + ? getESSymbolLikeTypeForNode(ts.walkUpParenthesizedTypes(node.parent)) + : errorType; + break; + } + } + return links.resolvedType; // TODO: GH#18217 + } + function createIndexedAccessType(objectType, indexType) { + var type = createType(8388608 /* IndexedAccess */); + type.objectType = objectType; + type.indexType = indexType; + return type; + } + /** + * Returns if a type is or consists of a JSLiteral object type + * In addition to objects which are directly literals, + * * unions where every element is a jsliteral + * * intersections where at least one element is a jsliteral + * * and instantiable types constrained to a jsliteral + * Should all count as literals and not print errors on access or assignment of possibly existing properties. + * This mirrors the behavior of the index signature propagation, to which this behaves similarly (but doesn't affect assignability or inference). + */ + function isJSLiteralType(type) { + if (noImplicitAny) { + return false; // Flag is meaningless under `noImplicitAny` mode + } + if (ts.getObjectFlags(type) & 16384 /* JSLiteral */) { + return true; + } + if (type.flags & 1048576 /* Union */) { + return ts.every(type.types, isJSLiteralType); + } + if (type.flags & 2097152 /* Intersection */) { + return ts.some(type.types, isJSLiteralType); + } + if (type.flags & 63176704 /* Instantiable */) { + return isJSLiteralType(getResolvedBaseConstraint(type)); + } + return false; + } + function getPropertyTypeForIndexType(objectType, indexType, accessNode, cacheSymbol, missingType) { + var accessExpression = accessNode && accessNode.kind === 190 /* ElementAccessExpression */ ? accessNode : undefined; + var propName = isTypeUsableAsLateBoundName(indexType) + ? getLateBoundNameFromType(indexType) + : accessExpression && checkThatExpressionIsProperSymbolReference(accessExpression.argumentExpression, indexType, /*reportError*/ false) + ? ts.getPropertyNameForKnownSymbolName(ts.idText(accessExpression.argumentExpression.name)) + : accessNode && ts.isPropertyName(accessNode) + // late bound names are handled in the first branch, so here we only need to handle normal names + ? ts.getPropertyNameForPropertyNameNode(accessNode) + : undefined; + if (propName !== undefined) { + var prop = getPropertyOfType(objectType, propName); + if (prop) { + if (accessExpression) { + markPropertyAsReferenced(prop, accessExpression, /*isThisAccess*/ accessExpression.expression.kind === 100 /* ThisKeyword */); + if (ts.isAssignmentTarget(accessExpression) && (isReferenceToReadonlyEntity(accessExpression, prop) || isReferenceThroughNamespaceImport(accessExpression))) { + error(accessExpression.argumentExpression, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, symbolToString(prop)); + return missingType; + } + if (cacheSymbol) { + getNodeLinks(accessNode).resolvedSymbol = prop; + } + } + var propType = getTypeOfSymbol(prop); + return accessExpression && ts.getAssignmentTargetKind(accessExpression) !== 1 /* Definite */ ? + getFlowTypeOfReference(accessExpression, propType) : + propType; + } + if (everyType(objectType, isTupleType) && isNumericLiteralName(propName) && +propName >= 0) { + if (accessNode && everyType(objectType, function (t) { return !t.target.hasRestElement; })) { + var indexNode = getIndexNodeForAccessExpression(accessNode); + error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(propName), typeToString(objectType)); + } + return mapType(objectType, function (t) { return getRestTypeOfTupleType(t) || undefinedType; }); + } + } + if (!(indexType.flags & 98304 /* Nullable */) && isTypeAssignableToKind(indexType, 132 /* StringLike */ | 296 /* NumberLike */ | 12288 /* ESSymbolLike */)) { + if (objectType.flags & (1 /* Any */ | 131072 /* Never */)) { + return objectType; + } + var indexInfo = isTypeAssignableToKind(indexType, 296 /* NumberLike */) && getIndexInfoOfType(objectType, 1 /* Number */) || + getIndexInfoOfType(objectType, 0 /* String */) || + undefined; + if (indexInfo) { + if (accessNode && !isTypeAssignableToKind(indexType, 4 /* String */ | 8 /* Number */)) { + var indexNode = getIndexNodeForAccessExpression(accessNode); + error(indexNode, ts.Diagnostics.Type_0_cannot_be_used_as_an_index_type, typeToString(indexType)); + } + else if (accessExpression && indexInfo.isReadonly && (ts.isAssignmentTarget(accessExpression) || ts.isDeleteTarget(accessExpression))) { + error(accessExpression, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(objectType)); + } + return indexInfo.type; + } + if (indexType.flags & 131072 /* Never */) { + return neverType; + } + if (isJSLiteralType(objectType)) { + return anyType; + } + if (accessExpression && !isConstEnumObjectType(objectType)) { + if (noImplicitAny && !compilerOptions.suppressImplicitAnyIndexErrors) { + if (propName !== undefined && typeHasStaticProperty(propName, objectType)) { + error(accessExpression, ts.Diagnostics.Property_0_is_a_static_member_of_type_1, propName, typeToString(objectType)); + } + else if (getIndexTypeOfType(objectType, 1 /* Number */)) { + error(accessExpression.argumentExpression, ts.Diagnostics.Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number); + } + else { + var suggestion = void 0; + if (propName !== undefined && (suggestion = getSuggestionForNonexistentProperty(propName, objectType))) { + if (suggestion !== undefined) { + error(accessExpression.argumentExpression, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2, propName, typeToString(objectType), suggestion); + } + } + else { + error(accessExpression, ts.Diagnostics.Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature, typeToString(objectType)); + } + } + } + return missingType; + } + } + if (isJSLiteralType(objectType)) { + return anyType; + } + if (accessNode) { + var indexNode = getIndexNodeForAccessExpression(accessNode); + if (indexType.flags & (128 /* StringLiteral */ | 256 /* NumberLiteral */)) { + error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, "" + indexType.value, typeToString(objectType)); + } + else if (indexType.flags & (4 /* String */ | 8 /* Number */)) { + error(indexNode, ts.Diagnostics.Type_0_has_no_matching_index_signature_for_type_1, typeToString(objectType), typeToString(indexType)); + } + else { + error(indexNode, ts.Diagnostics.Type_0_cannot_be_used_as_an_index_type, typeToString(indexType)); + } + } + if (isTypeAny(indexType)) { + return indexType; + } + return missingType; + } + function getIndexNodeForAccessExpression(accessNode) { + return accessNode.kind === 190 /* ElementAccessExpression */ + ? accessNode.argumentExpression + : accessNode.kind === 180 /* IndexedAccessType */ + ? accessNode.indexType + : accessNode.kind === 149 /* ComputedPropertyName */ + ? accessNode.expression + : accessNode; + } + function isGenericObjectType(type) { + return maybeTypeOfKind(type, 58982400 /* InstantiableNonPrimitive */ | 134217728 /* GenericMappedType */); + } + function isGenericIndexType(type) { + return maybeTypeOfKind(type, 58982400 /* InstantiableNonPrimitive */ | 4194304 /* Index */); + } + function getSimplifiedType(type) { + return type.flags & 8388608 /* IndexedAccess */ ? getSimplifiedIndexedAccessType(type) : type; + } + function distributeIndexOverObjectType(objectType, indexType) { + // (T | U)[K] -> T[K] | U[K] + if (objectType.flags & 1048576 /* Union */) { + return mapType(objectType, function (t) { return getSimplifiedType(getIndexedAccessType(t, indexType)); }); + } + // (T & U)[K] -> T[K] & U[K] + if (objectType.flags & 2097152 /* Intersection */) { + return getIntersectionType(ts.map(objectType.types, function (t) { return getSimplifiedType(getIndexedAccessType(t, indexType)); })); + } + } + // Transform an indexed access to a simpler form, if possible. Return the simpler form, or return + // the type itself if no transformation is possible. + function getSimplifiedIndexedAccessType(type) { + if (type.simplified) { + return type.simplified === circularConstraintType ? type : type.simplified; + } + type.simplified = circularConstraintType; + // We recursively simplify the object type as it may in turn be an indexed access type. For example, with + // '{ [P in T]: { [Q in U]: number } }[T][U]' we want to first simplify the inner indexed access type. + var objectType = getSimplifiedType(type.objectType); + var indexType = getSimplifiedType(type.indexType); + // T[A | B] -> T[A] | T[B] + if (indexType.flags & 1048576 /* Union */) { + return type.simplified = mapType(indexType, function (t) { return getSimplifiedType(getIndexedAccessType(objectType, t)); }); + } + // Only do the inner distributions if the index can no longer be instantiated to cause index distribution again + if (!(indexType.flags & 63176704 /* Instantiable */)) { + var simplified = distributeIndexOverObjectType(objectType, indexType); + if (simplified) { + return type.simplified = simplified; + } + } + // So ultimately: + // ((A & B) | C)[K1 | K2] -> ((A & B) | C)[K1] | ((A & B) | C)[K2] -> (A & B)[K1] | C[K1] | (A & B)[K2] | C[K2] -> (A[K1] & B[K1]) | C[K1] | (A[K2] & B[K2]) | C[K2] + // If the object type is a mapped type { [P in K]: E }, where K is generic, instantiate E using a mapper + // that substitutes the index type for P. For example, for an index access { [P in K]: Box }[X], we + // construct the type Box. We do not further simplify the result because mapped types can be recursive + // and we might never terminate. + if (isGenericMappedType(objectType)) { + return type.simplified = substituteIndexedMappedType(objectType, type); + } + if (objectType.flags & 262144 /* TypeParameter */) { + var constraint = getConstraintOfTypeParameter(objectType); + if (constraint && isGenericMappedType(constraint)) { + return type.simplified = substituteIndexedMappedType(constraint, type); + } + } + return type.simplified = type; + } + function substituteIndexedMappedType(objectType, type) { + var mapper = createTypeMapper([getTypeParameterFromMappedType(objectType)], [type.indexType]); + var templateMapper = combineTypeMappers(objectType.mapper, mapper); + return instantiateType(getTemplateTypeFromMappedType(objectType), templateMapper); + } + function getIndexedAccessType(objectType, indexType, accessNode, missingType) { + if (missingType === void 0) { missingType = accessNode ? errorType : unknownType; } + if (objectType === wildcardType || indexType === wildcardType) { + return wildcardType; + } + // If the index type is generic, or if the object type is generic and doesn't originate in an expression, + // we are performing a higher-order index access where we cannot meaningfully access the properties of the + // object type. Note that for a generic T and a non-generic K, we eagerly resolve T[K] if it originates in + // an expression. This is to preserve backwards compatibility. For example, an element access 'this["foo"]' + // has always been resolved eagerly using the constraint type of 'this' at the given location. + if (isGenericIndexType(indexType) || !(accessNode && accessNode.kind !== 180 /* IndexedAccessType */) && isGenericObjectType(objectType)) { + if (objectType.flags & 3 /* AnyOrUnknown */) { + return objectType; + } + // Defer the operation by creating an indexed access type. + var id = objectType.id + "," + indexType.id; + var type = indexedAccessTypes.get(id); + if (!type) { + indexedAccessTypes.set(id, type = createIndexedAccessType(objectType, indexType)); + } + return type; + } + // In the following we resolve T[K] to the type of the property in T selected by K. + // We treat boolean as different from other unions to improve errors; + // skipping straight to getPropertyTypeForIndexType gives errors with 'boolean' instead of 'true'. + var apparentObjectType = getApparentType(objectType); + if (indexType.flags & 1048576 /* Union */ && !(indexType.flags & 16 /* Boolean */)) { + var propTypes = []; + var wasMissingProp = false; + for (var _i = 0, _a = indexType.types; _i < _a.length; _i++) { + var t = _a[_i]; + var propType = getPropertyTypeForIndexType(apparentObjectType, t, accessNode, /*cacheSymbol*/ false, missingType); + if (propType === missingType) { + if (!accessNode) { + // If there's no error node, we can immeditely stop, since error reporting is off + return missingType; + } + else { + // Otherwise we set a flag and return at the end of the loop so we still mark all errors + wasMissingProp = true; + } + } + propTypes.push(propType); + } + if (wasMissingProp) { + return missingType; + } + return getUnionType(propTypes); + } + return getPropertyTypeForIndexType(apparentObjectType, indexType, accessNode, /*cacheSymbol*/ true, missingType); + } + function getTypeFromIndexedAccessTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + var objectType = getTypeFromTypeNode(node.objectType); + var indexType = getTypeFromTypeNode(node.indexType); + var resolved = getIndexedAccessType(objectType, indexType, node); + links.resolvedType = resolved.flags & 8388608 /* IndexedAccess */ && + resolved.objectType === objectType && + resolved.indexType === indexType ? + getConstrainedTypeVariable(resolved, node) : resolved; + } + return links.resolvedType; + } + function getTypeFromMappedTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + var type = createObjectType(32 /* Mapped */, node.symbol); + type.declaration = node; + type.aliasSymbol = getAliasSymbolForTypeNode(node); + type.aliasTypeArguments = getTypeArgumentsForAliasSymbol(type.aliasSymbol); + links.resolvedType = type; + // Eagerly resolve the constraint type which forces an error if the constraint type circularly + // references itself through one or more type aliases. + getConstraintTypeFromMappedType(type); + } + return links.resolvedType; + } + function getActualTypeVariable(type) { + return type.flags & 33554432 /* Substitution */ ? type.typeVariable : type; + } + function getConditionalType(root, mapper) { + var checkType = instantiateType(root.checkType, mapper); + var extendsType = instantiateType(root.extendsType, mapper); + if (checkType === wildcardType || extendsType === wildcardType) { + return wildcardType; + } + // If this is a distributive conditional type and the check type is generic we need to defer + // resolution of the conditional type such that a later instantiation will properly distribute + // over union types. + var isDeferred = root.isDistributive && maybeTypeOfKind(checkType, 63176704 /* Instantiable */); + var combinedMapper; + if (root.inferTypeParameters) { + var context = createInferenceContext(root.inferTypeParameters, /*signature*/ undefined, 0 /* None */); + if (!isDeferred) { + // We don't want inferences from constraints as they may cause us to eagerly resolve the + // conditional type instead of deferring resolution. Also, we always want strict function + // types rules (i.e. proper contravariance) for inferences. + inferTypes(context.inferences, checkType, extendsType, 32 /* NoConstraints */ | 64 /* AlwaysStrict */); + } + combinedMapper = combineTypeMappers(mapper, context); + } + if (!isDeferred) { + if (extendsType.flags & 3 /* AnyOrUnknown */) { + return instantiateType(root.trueType, mapper); + } + // Return union of trueType and falseType for 'any' since it matches anything + if (checkType.flags & 1 /* Any */) { + return getUnionType([instantiateType(root.trueType, combinedMapper || mapper), instantiateType(root.falseType, mapper)]); + } + // Instantiate the extends type including inferences for 'infer T' type parameters + var inferredExtendsType = combinedMapper ? instantiateType(root.extendsType, combinedMapper) : extendsType; + // Return falseType for a definitely false extends check. We check an instantations of the two + // types with type parameters mapped to the wildcard type, the most permissive instantiations + // possible (the wildcard type is assignable to and from all types). If those are not related, + // then no instatiations will be and we can just return the false branch type. + if (!isTypeAssignableTo(getWildcardInstantiation(checkType), getWildcardInstantiation(inferredExtendsType))) { + return instantiateType(root.falseType, mapper); + } + // Return trueType for a definitely true extends check. The definitely assignable relation excludes + // type variable constraints from consideration. Without the definitely assignable relation, the type + // type Foo = T extends { x: string } ? string : number + // would immediately resolve to 'string' instead of being deferred. + if (checkTypeRelatedTo(checkType, inferredExtendsType, definitelyAssignableRelation, /*errorNode*/ undefined)) { + return instantiateType(root.trueType, combinedMapper || mapper); + } + } + // Return a deferred type for a check that is neither definitely true nor definitely false + var erasedCheckType = getActualTypeVariable(checkType); + var result = createType(16777216 /* Conditional */); + result.root = root; + result.checkType = erasedCheckType; + result.extendsType = extendsType; + result.mapper = mapper; + result.combinedMapper = combinedMapper; + result.aliasSymbol = root.aliasSymbol; + result.aliasTypeArguments = instantiateTypes(root.aliasTypeArguments, mapper); // TODO: GH#18217 + return result; + } + function getTrueTypeFromConditionalType(type) { + return type.resolvedTrueType || (type.resolvedTrueType = instantiateType(type.root.trueType, type.mapper)); + } + function getFalseTypeFromConditionalType(type) { + return type.resolvedFalseType || (type.resolvedFalseType = instantiateType(type.root.falseType, type.mapper)); + } + function getInferTypeParameters(node) { + var result; + if (node.locals) { + node.locals.forEach(function (symbol) { + if (symbol.flags & 262144 /* TypeParameter */) { + result = ts.append(result, getDeclaredTypeOfSymbol(symbol)); + } + }); + } + return result; + } + function isPossiblyReferencedInConditionalType(tp, node) { + if (isTypeParameterPossiblyReferenced(tp, node)) { + return true; + } + while (node) { + if (node.kind === 175 /* ConditionalType */) { + if (isTypeParameterPossiblyReferenced(tp, node.extendsType)) { + return true; + } + } + node = node.parent; + } + return false; + } + function getTypeFromConditionalTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + var checkType = getTypeFromTypeNode(node.checkType); + var aliasSymbol = getAliasSymbolForTypeNode(node); + var aliasTypeArguments = getTypeArgumentsForAliasSymbol(aliasSymbol); + var allOuterTypeParameters = getOuterTypeParameters(node, /*includeThisTypes*/ true); + var outerTypeParameters = aliasTypeArguments ? allOuterTypeParameters : ts.filter(allOuterTypeParameters, function (tp) { return isPossiblyReferencedInConditionalType(tp, node); }); + var root = { + node: node, + checkType: checkType, + extendsType: getTypeFromTypeNode(node.extendsType), + trueType: getTypeFromTypeNode(node.trueType), + falseType: getTypeFromTypeNode(node.falseType), + isDistributive: !!(checkType.flags & 262144 /* TypeParameter */), + inferTypeParameters: getInferTypeParameters(node), + outerTypeParameters: outerTypeParameters, + instantiations: undefined, + aliasSymbol: aliasSymbol, + aliasTypeArguments: aliasTypeArguments + }; + links.resolvedType = getConditionalType(root, /*mapper*/ undefined); + if (outerTypeParameters) { + root.instantiations = ts.createMap(); + root.instantiations.set(getTypeListId(outerTypeParameters), links.resolvedType); + } + } + return links.resolvedType; + } + function getTypeFromInferTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + links.resolvedType = getDeclaredTypeOfTypeParameter(getSymbolOfNode(node.typeParameter)); + } + return links.resolvedType; + } + function getIdentifierChain(node) { + if (ts.isIdentifier(node)) { + return [node]; + } + else { + return ts.append(getIdentifierChain(node.left), node.right); + } + } + function getTypeFromImportTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + if (node.isTypeOf && node.typeArguments) { // Only the non-typeof form can make use of type arguments + error(node, ts.Diagnostics.Type_arguments_cannot_be_used_here); + links.resolvedSymbol = unknownSymbol; + return links.resolvedType = errorType; + } + if (!ts.isLiteralImportTypeNode(node)) { + error(node.argument, ts.Diagnostics.String_literal_expected); + links.resolvedSymbol = unknownSymbol; + return links.resolvedType = errorType; + } + var targetMeaning = node.isTypeOf ? 67220415 /* Value */ : node.flags & 2097152 /* JSDoc */ ? 67220415 /* Value */ | 67897832 /* Type */ : 67897832 /* Type */; + // TODO: Future work: support unions/generics/whatever via a deferred import-type + var innerModuleSymbol = resolveExternalModuleName(node, node.argument.literal); + if (!innerModuleSymbol) { + links.resolvedSymbol = unknownSymbol; + return links.resolvedType = errorType; + } + var moduleSymbol = resolveExternalModuleSymbol(innerModuleSymbol, /*dontResolveAlias*/ false); + if (!ts.nodeIsMissing(node.qualifier)) { + var nameStack = getIdentifierChain(node.qualifier); + var currentNamespace = moduleSymbol; + var current = void 0; + while (current = nameStack.shift()) { + var meaning = nameStack.length ? 1920 /* Namespace */ : targetMeaning; + var next = getSymbol(getExportsOfSymbol(getMergedSymbol(resolveSymbol(currentNamespace))), current.escapedText, meaning); + if (!next) { + error(current, ts.Diagnostics.Namespace_0_has_no_exported_member_1, getFullyQualifiedName(currentNamespace), ts.declarationNameToString(current)); + return links.resolvedType = errorType; + } + getNodeLinks(current).resolvedSymbol = next; + getNodeLinks(current.parent).resolvedSymbol = next; + currentNamespace = next; + } + resolveImportSymbolType(node, links, currentNamespace, targetMeaning); + } + else { + if (moduleSymbol.flags & targetMeaning) { + resolveImportSymbolType(node, links, moduleSymbol, targetMeaning); + } + else { + var errorMessage = targetMeaning === 67220415 /* Value */ + ? ts.Diagnostics.Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here + : ts.Diagnostics.Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0; + error(node, errorMessage, node.argument.literal.text); + links.resolvedSymbol = unknownSymbol; + links.resolvedType = errorType; + } + } + } + return links.resolvedType; // TODO: GH#18217 + } + function resolveImportSymbolType(node, links, symbol, meaning) { + var resolvedSymbol = resolveSymbol(symbol); + links.resolvedSymbol = resolvedSymbol; + if (meaning === 67220415 /* Value */) { + return links.resolvedType = getTypeOfSymbol(symbol); // intentionally doesn't use resolved symbol so type is cached as expected on the alias + } + else { + return links.resolvedType = getTypeReferenceType(node, resolvedSymbol); // getTypeReferenceType doesn't handle aliases - it must get the resolved symbol + } + } + function getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + // Deferred resolution of members is handled by resolveObjectTypeMembers + var aliasSymbol = getAliasSymbolForTypeNode(node); + if (getMembersOfSymbol(node.symbol).size === 0 && !aliasSymbol) { + links.resolvedType = emptyTypeLiteralType; + } + else { + var type = createObjectType(16 /* Anonymous */, node.symbol); + type.aliasSymbol = aliasSymbol; + type.aliasTypeArguments = getTypeArgumentsForAliasSymbol(aliasSymbol); + if (ts.isJSDocTypeLiteral(node) && node.isArrayType) { + type = createArrayType(type); + } + links.resolvedType = type; + } + } + return links.resolvedType; + } + function getAliasSymbolForTypeNode(node) { + return ts.isTypeAlias(node.parent) ? getSymbolOfNode(node.parent) : undefined; + } + function getTypeArgumentsForAliasSymbol(symbol) { + return symbol ? getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) : undefined; + } + function isNonGenericObjectType(type) { + return !!(type.flags & 524288 /* Object */) && !isGenericMappedType(type); + } + /** + * Since the source of spread types are object literals, which are not binary, + * this function should be called in a left folding style, with left = previous result of getSpreadType + * and right = the new element to be spread. + */ + function getSpreadType(left, right, symbol, typeFlags, objectFlags) { + if (left.flags & 1 /* Any */ || right.flags & 1 /* Any */) { + return anyType; + } + if (left.flags & 2 /* Unknown */ || right.flags & 2 /* Unknown */) { + return unknownType; + } + if (left.flags & 131072 /* Never */) { + return right; + } + if (right.flags & 131072 /* Never */) { + return left; + } + if (left.flags & 1048576 /* Union */) { + return mapType(left, function (t) { return getSpreadType(t, right, symbol, typeFlags, objectFlags); }); + } + if (right.flags & 1048576 /* Union */) { + return mapType(right, function (t) { return getSpreadType(left, t, symbol, typeFlags, objectFlags); }); + } + if (right.flags & (528 /* BooleanLike */ | 296 /* NumberLike */ | 2112 /* BigIntLike */ | 132 /* StringLike */ | 1056 /* EnumLike */ | 67108864 /* NonPrimitive */ | 4194304 /* Index */)) { + return left; + } + if (isGenericObjectType(left) || isGenericObjectType(right)) { + if (isEmptyObjectType(left)) { + return right; + } + // When the left type is an intersection, we may need to merge the last constituent of the + // intersection with the right type. For example when the left type is 'T & { a: string }' + // and the right type is '{ b: string }' we produce 'T & { a: string, b: string }'. + if (left.flags & 2097152 /* Intersection */) { + var types = left.types; + var lastLeft = types[types.length - 1]; + if (isNonGenericObjectType(lastLeft) && isNonGenericObjectType(right)) { + return getIntersectionType(ts.concatenate(types.slice(0, types.length - 1), [getSpreadType(lastLeft, right, symbol, typeFlags, objectFlags)])); + } + } + return getIntersectionType([left, right]); + } + var members = ts.createSymbolTable(); + var skippedPrivateMembers = ts.createUnderscoreEscapedMap(); + var stringIndexInfo; + var numberIndexInfo; + if (left === emptyObjectType) { + // for the first spread element, left === emptyObjectType, so take the right's string indexer + stringIndexInfo = getIndexInfoOfType(right, 0 /* String */); + numberIndexInfo = getIndexInfoOfType(right, 1 /* Number */); + } + else { + stringIndexInfo = unionSpreadIndexInfos(getIndexInfoOfType(left, 0 /* String */), getIndexInfoOfType(right, 0 /* String */)); + numberIndexInfo = unionSpreadIndexInfos(getIndexInfoOfType(left, 1 /* Number */), getIndexInfoOfType(right, 1 /* Number */)); + } + for (var _i = 0, _a = getPropertiesOfType(right); _i < _a.length; _i++) { + var rightProp = _a[_i]; + if (ts.getDeclarationModifierFlagsFromSymbol(rightProp) & (8 /* Private */ | 16 /* Protected */)) { + skippedPrivateMembers.set(rightProp.escapedName, true); + } + else if (isSpreadableProperty(rightProp)) { + members.set(rightProp.escapedName, getSpreadSymbol(rightProp)); + } + } + for (var _b = 0, _c = getPropertiesOfType(left); _b < _c.length; _b++) { + var leftProp = _c[_b]; + if (skippedPrivateMembers.has(leftProp.escapedName) || !isSpreadableProperty(leftProp)) { + continue; + } + if (members.has(leftProp.escapedName)) { + var rightProp = members.get(leftProp.escapedName); + var rightType = getTypeOfSymbol(rightProp); + if (rightProp.flags & 16777216 /* Optional */) { + var declarations = ts.concatenate(leftProp.declarations, rightProp.declarations); + var flags = 4 /* Property */ | (leftProp.flags & 16777216 /* Optional */); + var result = createSymbol(flags, leftProp.escapedName); + result.type = getUnionType([getTypeOfSymbol(leftProp), getTypeWithFacts(rightType, 524288 /* NEUndefined */)]); + result.leftSpread = leftProp; + result.rightSpread = rightProp; + result.declarations = declarations; + result.nameType = leftProp.nameType; + members.set(leftProp.escapedName, result); + } + } + else { + members.set(leftProp.escapedName, getSpreadSymbol(leftProp)); + } + } + var spread = createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, getNonReadonlyIndexSignature(stringIndexInfo), getNonReadonlyIndexSignature(numberIndexInfo)); + spread.flags |= 268435456 /* ContainsObjectLiteral */ | typeFlags; + spread.objectFlags |= 128 /* ObjectLiteral */ | 1024 /* ContainsSpread */ | objectFlags; + return spread; + } + /** We approximate own properties as non-methods plus methods that are inside the object literal */ + function isSpreadableProperty(prop) { + return !(prop.flags & (8192 /* Method */ | 32768 /* GetAccessor */ | 65536 /* SetAccessor */)) || + !prop.declarations.some(function (decl) { return ts.isClassLike(decl.parent); }); + } + function getSpreadSymbol(prop) { + var isReadonly = isReadonlySymbol(prop); + var isSetonlyAccessor = prop.flags & 65536 /* SetAccessor */ && !(prop.flags & 32768 /* GetAccessor */); + if (!isReadonly && !isSetonlyAccessor) { + return prop; + } + var flags = 4 /* Property */ | (prop.flags & 16777216 /* Optional */); + var result = createSymbol(flags, prop.escapedName); + result.type = isSetonlyAccessor ? undefinedType : getTypeOfSymbol(prop); + result.declarations = prop.declarations; + result.nameType = prop.nameType; + result.syntheticOrigin = prop; + return result; + } + function getNonReadonlyIndexSignature(index) { + if (index && index.isReadonly) { + return createIndexInfo(index.type, /*isReadonly*/ false, index.declaration); + } + return index; + } + function createLiteralType(flags, value, symbol) { + var type = createType(flags); + type.symbol = symbol; + type.value = value; + return type; + } + function getFreshTypeOfLiteralType(type) { + if (type.flags & 2944 /* Literal */) { + if (!type.freshType) { + var freshType = createLiteralType(type.flags, type.value, type.symbol); + freshType.regularType = type; + freshType.freshType = freshType; + type.freshType = freshType; + } + return type.freshType; + } + return type; + } + function getRegularTypeOfLiteralType(type) { + return type.flags & 2944 /* Literal */ ? type.regularType : + type.flags & 1048576 /* Union */ ? getUnionType(ts.sameMap(type.types, getRegularTypeOfLiteralType)) : + type; + } + function isFreshLiteralType(type) { + return !!(type.flags & 2944 /* Literal */) && type.freshType === type; + } + function getLiteralType(value, enumId, symbol) { + // We store all literal types in a single map with keys of the form '#NNN' and '@SSS', + // where NNN is the text representation of a numeric literal and SSS are the characters + // of a string literal. For literal enum members we use 'EEE#NNN' and 'EEE@SSS', where + // EEE is a unique id for the containing enum type. + var qualifier = typeof value === "number" ? "#" : typeof value === "string" ? "@" : "n"; + var key = (enumId ? enumId : "") + qualifier + (typeof value === "object" ? ts.pseudoBigIntToString(value) : value); + var type = literalTypes.get(key); + if (!type) { + var flags = (typeof value === "number" ? 256 /* NumberLiteral */ : + typeof value === "string" ? 128 /* StringLiteral */ : 2048 /* BigIntLiteral */) | + (enumId ? 1024 /* EnumLiteral */ : 0); + literalTypes.set(key, type = createLiteralType(flags, value, symbol)); + type.regularType = type; + } + return type; + } + function getTypeFromLiteralTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + links.resolvedType = getRegularTypeOfLiteralType(checkExpression(node.literal)); + } + return links.resolvedType; + } + function createUniqueESSymbolType(symbol) { + var type = createType(8192 /* UniqueESSymbol */); + type.symbol = symbol; + return type; + } + function getESSymbolLikeTypeForNode(node) { + if (ts.isValidESSymbolDeclaration(node)) { + var symbol = getSymbolOfNode(node); + var links = getSymbolLinks(symbol); + return links.uniqueESSymbolType || (links.uniqueESSymbolType = createUniqueESSymbolType(symbol)); + } + return esSymbolType; + } + function getThisType(node) { + var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); + var parent = container && container.parent; + if (parent && (ts.isClassLike(parent) || parent.kind === 241 /* InterfaceDeclaration */)) { + if (!ts.hasModifier(container, 32 /* Static */) && + (container.kind !== 157 /* Constructor */ || ts.isNodeDescendantOf(node, container.body))) { + return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(parent)).thisType; + } + } + error(node, ts.Diagnostics.A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface); + return errorType; + } + function getTypeFromThisTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + links.resolvedType = getThisType(node); + } + return links.resolvedType; + } + function getTypeFromTypeNode(node) { + switch (node.kind) { + case 120 /* AnyKeyword */: + case 284 /* JSDocAllType */: + case 285 /* JSDocUnknownType */: + return anyType; + case 143 /* UnknownKeyword */: + return unknownType; + case 138 /* StringKeyword */: + return stringType; + case 135 /* NumberKeyword */: + return numberType; + case 146 /* BigIntKeyword */: + return bigintType; + case 123 /* BooleanKeyword */: + return booleanType; + case 139 /* SymbolKeyword */: + return esSymbolType; + case 106 /* VoidKeyword */: + return voidType; + case 141 /* UndefinedKeyword */: + return undefinedType; + case 96 /* NullKeyword */: + return nullType; + case 132 /* NeverKeyword */: + return neverType; + case 136 /* ObjectKeyword */: + return node.flags & 65536 /* JavaScriptFile */ ? anyType : nonPrimitiveType; + case 178 /* ThisType */: + case 100 /* ThisKeyword */: + return getTypeFromThisTypeNode(node); + case 182 /* LiteralType */: + return getTypeFromLiteralTypeNode(node); + case 164 /* TypeReference */: + return getTypeFromTypeReference(node); + case 163 /* TypePredicate */: + return booleanType; + case 211 /* ExpressionWithTypeArguments */: + return getTypeFromTypeReference(node); + case 167 /* TypeQuery */: + return getTypeFromTypeQueryNode(node); + case 169 /* ArrayType */: + return getTypeFromArrayTypeNode(node); + case 170 /* TupleType */: + return getTypeFromTupleTypeNode(node); + case 171 /* OptionalType */: + return getTypeFromOptionalTypeNode(node); + case 173 /* UnionType */: + return getTypeFromUnionTypeNode(node); + case 174 /* IntersectionType */: + return getTypeFromIntersectionTypeNode(node); + case 286 /* JSDocNullableType */: + return getTypeFromJSDocNullableTypeNode(node); + case 288 /* JSDocOptionalType */: + return addOptionality(getTypeFromTypeNode(node.type)); + case 177 /* ParenthesizedType */: + case 172 /* RestType */: + case 287 /* JSDocNonNullableType */: + case 283 /* JSDocTypeExpression */: + return getTypeFromTypeNode(node.type); + case 290 /* JSDocVariadicType */: + return getTypeFromJSDocVariadicType(node); + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + case 168 /* TypeLiteral */: + case 292 /* JSDocTypeLiteral */: + case 289 /* JSDocFunctionType */: + case 293 /* JSDocSignature */: + return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node); + case 179 /* TypeOperator */: + return getTypeFromTypeOperatorNode(node); + case 180 /* IndexedAccessType */: + return getTypeFromIndexedAccessTypeNode(node); + case 181 /* MappedType */: + return getTypeFromMappedTypeNode(node); + case 175 /* ConditionalType */: + return getTypeFromConditionalTypeNode(node); + case 176 /* InferType */: + return getTypeFromInferTypeNode(node); + case 183 /* ImportType */: + return getTypeFromImportTypeNode(node); + // This function assumes that an identifier or qualified name is a type expression + // Callers should first ensure this by calling isTypeNode + case 72 /* Identifier */: + case 148 /* QualifiedName */: + var symbol = getSymbolAtLocation(node); + return symbol ? getDeclaredTypeOfSymbol(symbol) : errorType; + default: + return errorType; + } + } + function instantiateList(items, mapper, instantiator) { + if (items && items.length) { + for (var i = 0; i < items.length; i++) { + var item = items[i]; + var mapped = instantiator(item, mapper); + if (item !== mapped) { + var result = i === 0 ? [] : items.slice(0, i); + result.push(mapped); + for (i++; i < items.length; i++) { + result.push(instantiator(items[i], mapper)); + } + return result; + } + } + } + return items; + } + function instantiateTypes(types, mapper) { + return instantiateList(types, mapper, instantiateType); + } + function instantiateSignatures(signatures, mapper) { + return instantiateList(signatures, mapper, instantiateSignature); + } + function makeUnaryTypeMapper(source, target) { + return function (t) { return t === source ? target : t; }; + } + function makeBinaryTypeMapper(source1, target1, source2, target2) { + return function (t) { return t === source1 ? target1 : t === source2 ? target2 : t; }; + } + function makeArrayTypeMapper(sources, targets) { + return function (t) { + for (var i = 0; i < sources.length; i++) { + if (t === sources[i]) { + return targets ? targets[i] : anyType; + } + } + return t; + }; + } + function createTypeMapper(sources, targets) { + ts.Debug.assert(targets === undefined || sources.length === targets.length); + return sources.length === 1 ? makeUnaryTypeMapper(sources[0], targets ? targets[0] : anyType) : + sources.length === 2 ? makeBinaryTypeMapper(sources[0], targets ? targets[0] : anyType, sources[1], targets ? targets[1] : anyType) : + makeArrayTypeMapper(sources, targets); + } + function createTypeEraser(sources) { + return createTypeMapper(sources, /*targets*/ undefined); + } + /** + * Maps forward-references to later types parameters to the empty object type. + * This is used during inference when instantiating type parameter defaults. + */ + function createBackreferenceMapper(typeParameters, index) { + return function (t) { return typeParameters.indexOf(t) >= index ? emptyObjectType : t; }; + } + function isInferenceContext(mapper) { + return !!mapper.typeParameters; + } + function cloneTypeMapper(mapper) { + return mapper && isInferenceContext(mapper) ? + createInferenceContext(mapper.typeParameters, mapper.signature, mapper.flags | 1 /* NoDefault */, mapper.compareTypes, mapper.inferences) : + mapper; + } + function combineTypeMappers(mapper1, mapper2) { + if (!mapper1) + return mapper2; + if (!mapper2) + return mapper1; + return function (t) { return instantiateType(mapper1(t), mapper2); }; + } + function createReplacementMapper(source, target, baseMapper) { + return function (t) { return t === source ? target : baseMapper(t); }; + } + function wildcardMapper(type) { + return type.flags & 262144 /* TypeParameter */ ? wildcardType : type; + } + function cloneTypeParameter(typeParameter) { + var result = createType(262144 /* TypeParameter */); + result.symbol = typeParameter.symbol; + result.target = typeParameter; + return result; + } + function instantiateTypePredicate(predicate, mapper) { + if (ts.isIdentifierTypePredicate(predicate)) { + return { + kind: 1 /* Identifier */, + parameterName: predicate.parameterName, + parameterIndex: predicate.parameterIndex, + type: instantiateType(predicate.type, mapper) + }; + } + else { + return { + kind: 0 /* This */, + type: instantiateType(predicate.type, mapper) + }; + } + } + function instantiateSignature(signature, mapper, eraseTypeParameters) { + var freshTypeParameters; + if (signature.typeParameters && !eraseTypeParameters) { + // First create a fresh set of type parameters, then include a mapping from the old to the + // new type parameters in the mapper function. Finally store this mapper in the new type + // parameters such that we can use it when instantiating constraints. + freshTypeParameters = ts.map(signature.typeParameters, cloneTypeParameter); + mapper = combineTypeMappers(createTypeMapper(signature.typeParameters, freshTypeParameters), mapper); + for (var _i = 0, freshTypeParameters_1 = freshTypeParameters; _i < freshTypeParameters_1.length; _i++) { + var tp = freshTypeParameters_1[_i]; + tp.mapper = mapper; + } + } + // Don't compute resolvedReturnType and resolvedTypePredicate now, + // because using `mapper` now could trigger inferences to become fixed. (See `createInferenceContext`.) + // See GH#17600. + var result = createSignature(signature.declaration, freshTypeParameters, signature.thisParameter && instantiateSymbol(signature.thisParameter, mapper), instantiateList(signature.parameters, mapper, instantiateSymbol), + /*resolvedReturnType*/ undefined, + /*resolvedTypePredicate*/ undefined, signature.minArgumentCount, signature.hasRestParameter, signature.hasLiteralTypes); + result.target = signature; + result.mapper = mapper; + return result; + } + function instantiateSymbol(symbol, mapper) { + var links = getSymbolLinks(symbol); + if (links.type && !maybeTypeOfKind(links.type, 524288 /* Object */ | 63176704 /* Instantiable */)) { + // If the type of the symbol is already resolved, and if that type could not possibly + // be affected by instantiation, simply return the symbol itself. + return symbol; + } + if (ts.getCheckFlags(symbol) & 1 /* Instantiated */) { + // If symbol being instantiated is itself a instantiation, fetch the original target and combine the + // type mappers. This ensures that original type identities are properly preserved and that aliases + // always reference a non-aliases. + symbol = links.target; + mapper = combineTypeMappers(links.mapper, mapper); + } + // Keep the flags from the symbol we're instantiating. Mark that is instantiated, and + // also transient so that we can just store data on it directly. + var result = createSymbol(symbol.flags, symbol.escapedName, 1 /* Instantiated */ | ts.getCheckFlags(symbol) & (1024 /* Late */ | 4096 /* OptionalParameter */ | 8192 /* RestParameter */)); + result.declarations = symbol.declarations; + result.parent = symbol.parent; + result.target = symbol; + result.mapper = mapper; + if (symbol.valueDeclaration) { + result.valueDeclaration = symbol.valueDeclaration; + } + if (symbol.nameType) { + result.nameType = symbol.nameType; + } + return result; + } + function getAnonymousTypeInstantiation(type, mapper) { + var target = type.objectFlags & 64 /* Instantiated */ ? type.target : type; + var symbol = target.symbol; + var links = getSymbolLinks(symbol); + var typeParameters = links.outerTypeParameters; + if (!typeParameters) { + // The first time an anonymous type is instantiated we compute and store a list of the type + // parameters that are in scope (and therefore potentially referenced). For type literals that + // aren't the right hand side of a generic type alias declaration we optimize by reducing the + // set of type parameters to those that are possibly referenced in the literal. + var declaration_1 = symbol.declarations[0]; + if (ts.isInJSFile(declaration_1)) { + var paramTag = ts.findAncestor(declaration_1, ts.isJSDocParameterTag); + if (paramTag) { + var paramSymbol = ts.getParameterSymbolFromJSDoc(paramTag); + if (paramSymbol) { + declaration_1 = paramSymbol.valueDeclaration; + } + } + } + var outerTypeParameters = getOuterTypeParameters(declaration_1, /*includeThisTypes*/ true); + if (isJSConstructor(declaration_1)) { + var templateTagParameters = getTypeParametersFromDeclaration(declaration_1); + outerTypeParameters = ts.addRange(outerTypeParameters, templateTagParameters); + } + typeParameters = outerTypeParameters || ts.emptyArray; + typeParameters = symbol.flags & 2048 /* TypeLiteral */ && !target.aliasTypeArguments ? + ts.filter(typeParameters, function (tp) { return isTypeParameterPossiblyReferenced(tp, declaration_1); }) : + typeParameters; + links.outerTypeParameters = typeParameters; + if (typeParameters.length) { + links.instantiations = ts.createMap(); + links.instantiations.set(getTypeListId(typeParameters), target); + } + } + if (typeParameters.length) { + // We are instantiating an anonymous type that has one or more type parameters in scope. Apply the + // mapper to the type parameters to produce the effective list of type arguments, and compute the + // instantiation cache key from the type IDs of the type arguments. + var combinedMapper = type.objectFlags & 64 /* Instantiated */ ? combineTypeMappers(type.mapper, mapper) : mapper; + var typeArguments = ts.map(typeParameters, combinedMapper); + var id = getTypeListId(typeArguments); + var result = links.instantiations.get(id); + if (!result) { + var newMapper = createTypeMapper(typeParameters, typeArguments); + result = target.objectFlags & 32 /* Mapped */ ? instantiateMappedType(target, newMapper) : instantiateAnonymousType(target, newMapper); + links.instantiations.set(id, result); + } + return result; + } + return type; + } + function maybeTypeParameterReference(node) { + return !(node.kind === 148 /* QualifiedName */ || + node.parent.kind === 164 /* TypeReference */ && node.parent.typeArguments && node === node.parent.typeName); + } + function isTypeParameterPossiblyReferenced(tp, node) { + // If the type parameter doesn't have exactly one declaration, if there are invening statement blocks + // between the node and the type parameter declaration, if the node contains actual references to the + // type parameter, or if the node contains type queries, we consider the type parameter possibly referenced. + if (tp.symbol && tp.symbol.declarations && tp.symbol.declarations.length === 1) { + var container_3 = tp.symbol.declarations[0].parent; + if (ts.findAncestor(node, function (n) { return n.kind === 218 /* Block */ ? "quit" : n === container_3; })) { + return !!ts.forEachChild(node, containsReference); + } + } + return true; + function containsReference(node) { + switch (node.kind) { + case 178 /* ThisType */: + return !!tp.isThisType; + case 72 /* Identifier */: + return !tp.isThisType && ts.isPartOfTypeNode(node) && maybeTypeParameterReference(node) && + getTypeFromTypeNode(node) === tp; + case 167 /* TypeQuery */: + return true; + } + return !!ts.forEachChild(node, containsReference); + } + } + function getHomomorphicTypeVariable(type) { + var constraintType = getConstraintTypeFromMappedType(type); + if (constraintType.flags & 4194304 /* Index */) { + var typeVariable = constraintType.type; + if (typeVariable.flags & 262144 /* TypeParameter */) { + return typeVariable; + } + } + return undefined; + } + function instantiateMappedType(type, mapper) { + // For a homomorphic mapped type { [P in keyof T]: X }, where T is some type variable, the mapping + // operation depends on T as follows: + // * If T is a primitive type no mapping is performed and the result is simply T. + // * If T is a union type we distribute the mapped type over the union. + // * If T is an array we map to an array where the element type has been transformed. + // * If T is a tuple we map to a tuple where the element types have been transformed. + // * Otherwise we map to an object type where the type of each property has been transformed. + // For example, when T is instantiated to a union type A | B, we produce { [P in keyof A]: X } | + // { [P in keyof B]: X }, and when when T is instantiated to a union type A | undefined, we produce + // { [P in keyof A]: X } | undefined. + var typeVariable = getHomomorphicTypeVariable(type); + if (typeVariable) { + var mappedTypeVariable = instantiateType(typeVariable, mapper); + if (typeVariable !== mappedTypeVariable) { + // If we are already in the process of creating an instantiation of this mapped type, + // return the error type. This situation only arises if we are instantiating the mapped + // type for an array or tuple type, as we then need to eagerly resolve the (possibly + // circular) element type(s). + if (type.instantiating) { + return errorType; + } + type.instantiating = true; + var result = mapType(mappedTypeVariable, function (t) { + if (t.flags & (3 /* AnyOrUnknown */ | 58982400 /* InstantiableNonPrimitive */ | 524288 /* Object */ | 2097152 /* Intersection */) && t !== wildcardType) { + var replacementMapper = createReplacementMapper(typeVariable, t, mapper); + return isArrayType(t) ? createArrayType(instantiateMappedTypeTemplate(type, numberType, /*isOptional*/ true, replacementMapper)) : + isReadonlyArrayType(t) ? createReadonlyArrayType(instantiateMappedTypeTemplate(type, numberType, /*isOptional*/ true, replacementMapper)) : + isTupleType(t) ? instantiateMappedTupleType(t, type, replacementMapper) : + instantiateAnonymousType(type, replacementMapper); + } + return t; + }); + type.instantiating = false; + return result; + } + } + return instantiateAnonymousType(type, mapper); + } + function instantiateMappedTupleType(tupleType, mappedType, mapper) { + var minLength = tupleType.target.minLength; + var elementTypes = ts.map(tupleType.typeArguments || ts.emptyArray, function (_, i) { + return instantiateMappedTypeTemplate(mappedType, getLiteralType("" + i), i >= minLength, mapper); + }); + var modifiers = getMappedTypeModifiers(mappedType); + var newMinLength = modifiers & 4 /* IncludeOptional */ ? 0 : + modifiers & 8 /* ExcludeOptional */ ? getTypeReferenceArity(tupleType) - (tupleType.target.hasRestElement ? 1 : 0) : + minLength; + return createTupleType(elementTypes, newMinLength, tupleType.target.hasRestElement, tupleType.target.associatedNames); + } + function instantiateMappedTypeTemplate(type, key, isOptional, mapper) { + var templateMapper = combineTypeMappers(mapper, createTypeMapper([getTypeParameterFromMappedType(type)], [key])); + var propType = instantiateType(getTemplateTypeFromMappedType(type.target || type), templateMapper); + var modifiers = getMappedTypeModifiers(type); + return strictNullChecks && modifiers & 4 /* IncludeOptional */ && !isTypeAssignableTo(undefinedType, propType) ? getOptionalType(propType) : + strictNullChecks && modifiers & 8 /* ExcludeOptional */ && isOptional ? getTypeWithFacts(propType, 524288 /* NEUndefined */) : + propType; + } + function instantiateAnonymousType(type, mapper) { + var result = createObjectType(type.objectFlags | 64 /* Instantiated */, type.symbol); + if (type.objectFlags & 32 /* Mapped */) { + result.declaration = type.declaration; + // C.f. instantiateSignature + var origTypeParameter = getTypeParameterFromMappedType(type); + var freshTypeParameter = cloneTypeParameter(origTypeParameter); + result.typeParameter = freshTypeParameter; + mapper = combineTypeMappers(makeUnaryTypeMapper(origTypeParameter, freshTypeParameter), mapper); + freshTypeParameter.mapper = mapper; + } + result.target = type; + result.mapper = mapper; + result.aliasSymbol = type.aliasSymbol; + result.aliasTypeArguments = instantiateTypes(type.aliasTypeArguments, mapper); + return result; + } + function getConditionalTypeInstantiation(type, mapper) { + var root = type.root; + if (root.outerTypeParameters) { + // We are instantiating a conditional type that has one or more type parameters in scope. Apply the + // mapper to the type parameters to produce the effective list of type arguments, and compute the + // instantiation cache key from the type IDs of the type arguments. + var typeArguments = ts.map(root.outerTypeParameters, mapper); + var id = getTypeListId(typeArguments); + var result = root.instantiations.get(id); + if (!result) { + var newMapper = createTypeMapper(root.outerTypeParameters, typeArguments); + result = instantiateConditionalType(root, newMapper); + root.instantiations.set(id, result); + } + return result; + } + return type; + } + function instantiateConditionalType(root, mapper) { + // Check if we have a conditional type where the check type is a naked type parameter. If so, + // the conditional type is distributive over union types and when T is instantiated to a union + // type A | B, we produce (A extends U ? X : Y) | (B extends U ? X : Y). + if (root.isDistributive) { + var checkType_1 = root.checkType; + var instantiatedType = mapper(checkType_1); + if (checkType_1 !== instantiatedType && instantiatedType.flags & (1048576 /* Union */ | 131072 /* Never */)) { + return mapType(instantiatedType, function (t) { return getConditionalType(root, createReplacementMapper(checkType_1, t, mapper)); }); + } + } + return getConditionalType(root, mapper); + } + function instantiateType(type, mapper) { + if (!type || !mapper || mapper === identityMapper) { + return type; + } + if (instantiationDepth === 50) { + // We have reached 50 recursive type instantiations and there is a very high likelyhood we're dealing + // with a combination of infinite generic types that perpetually generate new type identities. We stop + // the recursion here by yielding the error type. + return errorType; + } + instantiationDepth++; + var result = instantiateTypeWorker(type, mapper); + instantiationDepth--; + return result; + } + function instantiateTypeWorker(type, mapper) { + var flags = type.flags; + if (flags & 262144 /* TypeParameter */) { + return mapper(type); + } + if (flags & 524288 /* Object */) { + var objectFlags = type.objectFlags; + if (objectFlags & 16 /* Anonymous */) { + // If the anonymous type originates in a declaration of a function, method, class, or + // interface, in an object type literal, or in an object literal expression, we may need + // to instantiate the type because it might reference a type parameter. + return type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && type.symbol.declarations ? + getAnonymousTypeInstantiation(type, mapper) : type; + } + if (objectFlags & 32 /* Mapped */) { + return getAnonymousTypeInstantiation(type, mapper); + } + if (objectFlags & 4 /* Reference */) { + var typeArguments = type.typeArguments; + var newTypeArguments = instantiateTypes(typeArguments, mapper); + return newTypeArguments !== typeArguments ? createTypeReference(type.target, newTypeArguments) : type; + } + return type; + } + if (flags & 1048576 /* Union */ && !(flags & 131068 /* Primitive */)) { + var types = type.types; + var newTypes = instantiateTypes(types, mapper); + return newTypes !== types ? getUnionType(newTypes, 1 /* Literal */, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type; + } + if (flags & 2097152 /* Intersection */) { + var types = type.types; + var newTypes = instantiateTypes(types, mapper); + return newTypes !== types ? getIntersectionType(newTypes, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type; + } + if (flags & 4194304 /* Index */) { + return getIndexType(instantiateType(type.type, mapper)); + } + if (flags & 8388608 /* IndexedAccess */) { + return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper)); + } + if (flags & 16777216 /* Conditional */) { + return getConditionalTypeInstantiation(type, combineTypeMappers(type.mapper, mapper)); + } + if (flags & 33554432 /* Substitution */) { + return instantiateType(type.typeVariable, mapper); + } + return type; + } + function getWildcardInstantiation(type) { + return type.flags & (131068 /* Primitive */ | 3 /* AnyOrUnknown */ | 131072 /* Never */) ? type : + type.wildcardInstantiation || (type.wildcardInstantiation = instantiateType(type, wildcardMapper)); + } + function instantiateIndexInfo(info, mapper) { + return info && createIndexInfo(instantiateType(info.type, mapper), info.isReadonly, info.declaration); + } + // Returns true if the given expression contains (at any level of nesting) a function or arrow expression + // that is subject to contextual typing. + function isContextSensitive(node) { + ts.Debug.assert(node.kind !== 156 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + switch (node.kind) { + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 156 /* MethodDeclaration */: + return isContextSensitiveFunctionLikeDeclaration(node); + case 188 /* ObjectLiteralExpression */: + return ts.some(node.properties, isContextSensitive); + case 187 /* ArrayLiteralExpression */: + return ts.some(node.elements, isContextSensitive); + case 205 /* ConditionalExpression */: + return isContextSensitive(node.whenTrue) || + isContextSensitive(node.whenFalse); + case 204 /* BinaryExpression */: + return node.operatorToken.kind === 55 /* BarBarToken */ && + (isContextSensitive(node.left) || isContextSensitive(node.right)); + case 275 /* PropertyAssignment */: + return isContextSensitive(node.initializer); + case 195 /* ParenthesizedExpression */: + return isContextSensitive(node.expression); + case 268 /* JsxAttributes */: + return ts.some(node.properties, isContextSensitive) || ts.isJsxOpeningElement(node.parent) && ts.some(node.parent.parent.children, isContextSensitive); + case 267 /* JsxAttribute */: { + // If there is no initializer, JSX attribute has a boolean value of true which is not context sensitive. + var initializer = node.initializer; + return !!initializer && isContextSensitive(initializer); + } + case 270 /* JsxExpression */: { + // It is possible to that node.expression is undefined (e.g
      ) + var expression = node.expression; + return !!expression && isContextSensitive(expression); + } + } + return false; + } + function isContextSensitiveFunctionLikeDeclaration(node) { + // Functions with type parameters are not context sensitive. + if (node.typeParameters) { + return false; + } + // Functions with any parameters that lack type annotations are context sensitive. + if (ts.some(node.parameters, function (p) { return !ts.getEffectiveTypeAnnotationNode(p); })) { + return true; + } + if (node.kind !== 197 /* ArrowFunction */) { + // If the first parameter is not an explicit 'this' parameter, then the function has + // an implicit 'this' parameter which is subject to contextual typing. + var parameter = ts.firstOrUndefined(node.parameters); + if (!(parameter && ts.parameterIsThisKeyword(parameter))) { + return true; + } + } + return hasContextSensitiveReturnExpression(node); + } + function hasContextSensitiveReturnExpression(node) { + // TODO(anhans): A block should be context-sensitive if it has a context-sensitive return value. + var body = node.body; + return body.kind === 218 /* Block */ ? false : isContextSensitive(body); + } + function isContextSensitiveFunctionOrObjectLiteralMethod(func) { + return (ts.isInJSFile(func) && ts.isFunctionDeclaration(func) || isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && + isContextSensitiveFunctionLikeDeclaration(func); + } + function getTypeWithoutSignatures(type) { + if (type.flags & 524288 /* Object */) { + var resolved = resolveStructuredTypeMembers(type); + if (resolved.constructSignatures.length || resolved.callSignatures.length) { + var result = createObjectType(16 /* Anonymous */, type.symbol); + result.members = resolved.members; + result.properties = resolved.properties; + result.callSignatures = ts.emptyArray; + result.constructSignatures = ts.emptyArray; + return result; + } + } + else if (type.flags & 2097152 /* Intersection */) { + return getIntersectionType(ts.map(type.types, getTypeWithoutSignatures)); + } + return type; + } + // TYPE CHECKING + function isTypeIdenticalTo(source, target) { + return isTypeRelatedTo(source, target, identityRelation); + } + function compareTypesIdentical(source, target) { + return isTypeRelatedTo(source, target, identityRelation) ? -1 /* True */ : 0 /* False */; + } + function compareTypesAssignable(source, target) { + return isTypeRelatedTo(source, target, assignableRelation) ? -1 /* True */ : 0 /* False */; + } + function compareTypesSubtypeOf(source, target) { + return isTypeRelatedTo(source, target, subtypeRelation) ? -1 /* True */ : 0 /* False */; + } + function isTypeSubtypeOf(source, target) { + return isTypeRelatedTo(source, target, subtypeRelation); + } + function isTypeAssignableTo(source, target) { + return isTypeRelatedTo(source, target, assignableRelation); + } + // An object type S is considered to be derived from an object type T if + // S is a union type and every constituent of S is derived from T, + // T is a union type and S is derived from at least one constituent of T, or + // S is a type variable with a base constraint that is derived from T, + // T is one of the global types Object and Function and S is a subtype of T, or + // T occurs directly or indirectly in an 'extends' clause of S. + // Note that this check ignores type parameters and only considers the + // inheritance hierarchy. + function isTypeDerivedFrom(source, target) { + return source.flags & 1048576 /* Union */ ? ts.every(source.types, function (t) { return isTypeDerivedFrom(t, target); }) : + target.flags & 1048576 /* Union */ ? ts.some(target.types, function (t) { return isTypeDerivedFrom(source, t); }) : + source.flags & 58982400 /* InstantiableNonPrimitive */ ? isTypeDerivedFrom(getBaseConstraintOfType(source) || emptyObjectType, target) : + target === globalObjectType ? !!(source.flags & (524288 /* Object */ | 67108864 /* NonPrimitive */)) : + target === globalFunctionType ? !!(source.flags & 524288 /* Object */) && isFunctionObjectType(source) : + hasBaseType(source, getTargetType(target)); + } + /** + * This is *not* a bi-directional relationship. + * If one needs to check both directions for comparability, use a second call to this function or 'checkTypeComparableTo'. + * + * A type S is comparable to a type T if some (but not necessarily all) of the possible values of S are also possible values of T. + * It is used to check following cases: + * - the types of the left and right sides of equality/inequality operators (`===`, `!==`, `==`, `!=`). + * - the types of `case` clause expressions and their respective `switch` expressions. + * - the type of an expression in a type assertion with the type being asserted. + */ + function isTypeComparableTo(source, target) { + return isTypeRelatedTo(source, target, comparableRelation); + } + function areTypesComparable(type1, type2) { + return isTypeComparableTo(type1, type2) || isTypeComparableTo(type2, type1); + } + function checkTypeAssignableTo(source, target, errorNode, headMessage, containingMessageChain, errorOutputObject) { + return checkTypeRelatedTo(source, target, assignableRelation, errorNode, headMessage, containingMessageChain, errorOutputObject); + } + /** + * Like `checkTypeAssignableTo`, but if it would issue an error, instead performs structural comparisons of the types using the given expression node to + * attempt to issue more specific errors on, for example, specific object literal properties or tuple members. + */ + function checkTypeAssignableToAndOptionallyElaborate(source, target, errorNode, expr, headMessage, containingMessageChain) { + return checkTypeRelatedToAndOptionallyElaborate(source, target, assignableRelation, errorNode, expr, headMessage, containingMessageChain); + } + function checkTypeRelatedToAndOptionallyElaborate(source, target, relation, errorNode, expr, headMessage, containingMessageChain) { + if (isTypeRelatedTo(source, target, relation)) + return true; + if (!errorNode || !elaborateError(expr, source, target, relation, headMessage)) { + return checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain); + } + return false; + } + function isOrHasGenericConditional(type) { + return !!(type.flags & 16777216 /* Conditional */ || (type.flags & 2097152 /* Intersection */ && ts.some(type.types, isOrHasGenericConditional))); + } + function elaborateError(node, source, target, relation, headMessage) { + if (!node || isOrHasGenericConditional(target)) + return false; + if (!checkTypeRelatedTo(source, target, relation, /*errorNode*/ undefined) && elaborateDidYouMeanToCallOrConstruct(node, source, target, relation, headMessage)) { + return true; + } + switch (node.kind) { + case 270 /* JsxExpression */: + case 195 /* ParenthesizedExpression */: + return elaborateError(node.expression, source, target, relation, headMessage); + case 204 /* BinaryExpression */: + switch (node.operatorToken.kind) { + case 59 /* EqualsToken */: + case 27 /* CommaToken */: + return elaborateError(node.right, source, target, relation, headMessage); + } + break; + case 188 /* ObjectLiteralExpression */: + return elaborateObjectLiteral(node, source, target, relation); + case 187 /* ArrayLiteralExpression */: + return elaborateArrayLiteral(node, source, target, relation); + case 268 /* JsxAttributes */: + return elaborateJsxAttributes(node, source, target, relation); + case 197 /* ArrowFunction */: + return elaborateArrowFunction(node, source, target, relation); + } + return false; + } + function elaborateDidYouMeanToCallOrConstruct(node, source, target, relation, headMessage) { + var callSignatures = getSignaturesOfType(source, 0 /* Call */); + var constructSignatures = getSignaturesOfType(source, 1 /* Construct */); + for (var _i = 0, _a = [constructSignatures, callSignatures]; _i < _a.length; _i++) { + var signatures = _a[_i]; + if (ts.some(signatures, function (s) { + var returnType = getReturnTypeOfSignature(s); + return !(returnType.flags & (1 /* Any */ | 131072 /* Never */)) && checkTypeRelatedTo(returnType, target, relation, /*errorNode*/ undefined); + })) { + var resultObj = {}; + checkTypeAssignableTo(source, target, node, headMessage, /*containingChain*/ undefined, resultObj); + var diagnostic = resultObj.error; + addRelatedInfo(diagnostic, ts.createDiagnosticForNode(node, signatures === constructSignatures ? ts.Diagnostics.Did_you_mean_to_use_new_with_this_expression : ts.Diagnostics.Did_you_mean_to_call_this_expression)); + return true; + } + } + return false; + } + function elaborateArrowFunction(node, source, target, relation) { + // Don't elaborate blocks + if (ts.isBlock(node.body)) { + return false; + } + // Or functions with annotated parameter types + if (ts.some(node.parameters, ts.hasType)) { + return false; + } + var sourceSig = getSingleCallSignature(source); + if (!sourceSig) { + return false; + } + var targetSignatures = getSignaturesOfType(target, 0 /* Call */); + if (!ts.length(targetSignatures)) { + return false; + } + var returnExpression = node.body; + var sourceReturn = getReturnTypeOfSignature(sourceSig); + var targetReturn = getUnionType(ts.map(targetSignatures, getReturnTypeOfSignature)); + if (!checkTypeRelatedTo(sourceReturn, targetReturn, relation, /*errorNode*/ undefined)) { + var elaborated = returnExpression && elaborateError(returnExpression, sourceReturn, targetReturn, relation, /*headMessage*/ undefined); + if (elaborated) { + return elaborated; + } + var resultObj = {}; + checkTypeRelatedTo(sourceReturn, targetReturn, relation, returnExpression, /*message*/ undefined, /*chain*/ undefined, resultObj); + if (resultObj.error) { + if (target.symbol && ts.length(target.symbol.declarations)) { + addRelatedInfo(resultObj.error, ts.createDiagnosticForNode(target.symbol.declarations[0], ts.Diagnostics.The_expected_type_comes_from_the_return_type_of_this_signature)); + } + return true; + } + } + return false; + } + /** + * For every element returned from the iterator, checks that element to issue an error on a property of that element's type + * If that element would issue an error, we first attempt to dive into that element's inner expression and issue a more specific error by recuring into `elaborateError` + * Otherwise, we issue an error on _every_ element which fail the assignability check + */ + function elaborateElementwise(iterator, source, target, relation) { + // Assignability failure - check each prop individually, and if that fails, fall back on the bad error span + var reportedError = false; + for (var status = iterator.next(); !status.done; status = iterator.next()) { + var _a = status.value, prop = _a.errorNode, next = _a.innerExpression, nameType = _a.nameType, errorMessage = _a.errorMessage; + var targetPropType = getIndexedAccessType(target, nameType, /*accessNode*/ undefined, errorType); + if (targetPropType === errorType || targetPropType.flags & 8388608 /* IndexedAccess */) + continue; // Don't elaborate on indexes on generic variables + var sourcePropType = getIndexedAccessType(source, nameType, /*accessNode*/ undefined, errorType); + if (sourcePropType !== errorType && targetPropType !== errorType && !checkTypeRelatedTo(sourcePropType, targetPropType, relation, /*errorNode*/ undefined)) { + var elaborated = next && elaborateError(next, sourcePropType, targetPropType, relation, /*headMessage*/ undefined); + if (elaborated) { + reportedError = true; + } + else { + // Issue error on the prop itself, since the prop couldn't elaborate the error + var resultObj = {}; + // Use the expression type, if available + var specificSource = next ? checkExpressionForMutableLocation(next, 0 /* Normal */, sourcePropType) : sourcePropType; + var result = checkTypeRelatedTo(specificSource, targetPropType, relation, prop, errorMessage, /*containingChain*/ undefined, resultObj); + if (result && specificSource !== sourcePropType) { + // If for whatever reason the expression type doesn't yield an error, make sure we still issue an error on the sourcePropType + checkTypeRelatedTo(sourcePropType, targetPropType, relation, prop, errorMessage, /*containingChain*/ undefined, resultObj); + } + if (resultObj.error) { + var reportedDiag = resultObj.error; + var propertyName = isTypeUsableAsLateBoundName(nameType) ? getLateBoundNameFromType(nameType) : undefined; + var targetProp = propertyName !== undefined ? getPropertyOfType(target, propertyName) : undefined; + var issuedElaboration = false; + if (!targetProp) { + var indexInfo = isTypeAssignableToKind(nameType, 296 /* NumberLike */) && getIndexInfoOfType(target, 1 /* Number */) || + getIndexInfoOfType(target, 0 /* String */) || + undefined; + if (indexInfo && indexInfo.declaration && !ts.getSourceFileOfNode(indexInfo.declaration).hasNoDefaultLib) { + issuedElaboration = true; + addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(indexInfo.declaration, ts.Diagnostics.The_expected_type_comes_from_this_index_signature)); + } + } + if (!issuedElaboration && (targetProp && ts.length(targetProp.declarations) || target.symbol && ts.length(target.symbol.declarations))) { + var targetNode = targetProp && ts.length(targetProp.declarations) ? targetProp.declarations[0] : target.symbol.declarations[0]; + if (!ts.getSourceFileOfNode(targetNode).hasNoDefaultLib) { + addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(targetNode, ts.Diagnostics.The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1, propertyName && !(nameType.flags & 8192 /* UniqueESSymbol */) ? ts.unescapeLeadingUnderscores(propertyName) : typeToString(nameType), typeToString(target))); + } + } + } + reportedError = true; + } + } + } + return reportedError; + } + function generateJsxAttributes(node) { + var _i, _a, prop; + return __generator(this, function (_b) { + switch (_b.label) { + case 0: + if (!ts.length(node.properties)) + return [2 /*return*/]; + _i = 0, _a = node.properties; + _b.label = 1; + case 1: + if (!(_i < _a.length)) return [3 /*break*/, 4]; + prop = _a[_i]; + if (ts.isJsxSpreadAttribute(prop)) + return [3 /*break*/, 3]; + return [4 /*yield*/, { errorNode: prop.name, innerExpression: prop.initializer, nameType: getLiteralType(ts.idText(prop.name)) }]; + case 2: + _b.sent(); + _b.label = 3; + case 3: + _i++; + return [3 /*break*/, 1]; + case 4: return [2 /*return*/]; + } + }); + } + function elaborateJsxAttributes(node, source, target, relation) { + return elaborateElementwise(generateJsxAttributes(node), source, target, relation); + } + function generateLimitedTupleElements(node, target) { + var len, i, elem, nameType; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + len = ts.length(node.elements); + if (!len) + return [2 /*return*/]; + i = 0; + _a.label = 1; + case 1: + if (!(i < len)) return [3 /*break*/, 4]; + // Skip elements which do not exist in the target - a length error on the tuple overall is likely better than an error on a mismatched index signature + if (isTupleLikeType(target) && !getPropertyOfType(target, ("" + i))) + return [3 /*break*/, 3]; + elem = node.elements[i]; + if (ts.isOmittedExpression(elem)) + return [3 /*break*/, 3]; + nameType = getLiteralType(i); + return [4 /*yield*/, { errorNode: elem, innerExpression: elem, nameType: nameType }]; + case 2: + _a.sent(); + _a.label = 3; + case 3: + i++; + return [3 /*break*/, 1]; + case 4: return [2 /*return*/]; + } + }); + } + function elaborateArrayLiteral(node, source, target, relation) { + if (isTupleLikeType(source)) { + return elaborateElementwise(generateLimitedTupleElements(node, target), source, target, relation); + } + // recreate a tuple from the elements, if possible + var tupleizedType = checkArrayLiteral(node, 3 /* Contextual */, /*forceTuple*/ true); + if (isTupleLikeType(tupleizedType)) { + return elaborateElementwise(generateLimitedTupleElements(node, target), tupleizedType, target, relation); + } + return false; + } + function generateObjectLiteralElements(node) { + var _i, _a, prop, type, _b; + return __generator(this, function (_c) { + switch (_c.label) { + case 0: + if (!ts.length(node.properties)) + return [2 /*return*/]; + _i = 0, _a = node.properties; + _c.label = 1; + case 1: + if (!(_i < _a.length)) return [3 /*break*/, 8]; + prop = _a[_i]; + if (ts.isSpreadAssignment(prop)) + return [3 /*break*/, 7]; + type = getLiteralTypeFromProperty(getSymbolOfNode(prop), 8576 /* StringOrNumberLiteralOrUnique */); + if (!type || (type.flags & 131072 /* Never */)) { + return [3 /*break*/, 7]; + } + _b = prop.kind; + switch (_b) { + case 159 /* SetAccessor */: return [3 /*break*/, 2]; + case 158 /* GetAccessor */: return [3 /*break*/, 2]; + case 156 /* MethodDeclaration */: return [3 /*break*/, 2]; + case 276 /* ShorthandPropertyAssignment */: return [3 /*break*/, 2]; + case 275 /* PropertyAssignment */: return [3 /*break*/, 4]; + } + return [3 /*break*/, 6]; + case 2: return [4 /*yield*/, { errorNode: prop.name, innerExpression: undefined, nameType: type }]; + case 3: + _c.sent(); + return [3 /*break*/, 7]; + case 4: return [4 /*yield*/, { errorNode: prop.name, innerExpression: prop.initializer, nameType: type, errorMessage: isComputedNonLiteralName(prop.name) ? ts.Diagnostics.Type_of_computed_property_s_value_is_0_which_is_not_assignable_to_type_1 : undefined }]; + case 5: + _c.sent(); + return [3 /*break*/, 7]; + case 6: + ts.Debug.assertNever(prop); + _c.label = 7; + case 7: + _i++; + return [3 /*break*/, 1]; + case 8: return [2 /*return*/]; + } + }); + } + function elaborateObjectLiteral(node, source, target, relation) { + return elaborateElementwise(generateObjectLiteralElements(node), source, target, relation); + } + /** + * This is *not* a bi-directional relationship. + * If one needs to check both directions for comparability, use a second call to this function or 'isTypeComparableTo'. + */ + function checkTypeComparableTo(source, target, errorNode, headMessage, containingMessageChain) { + return checkTypeRelatedTo(source, target, comparableRelation, errorNode, headMessage, containingMessageChain); + } + function isSignatureAssignableTo(source, target, ignoreReturnTypes) { + return compareSignaturesRelated(source, target, 0 /* None */, ignoreReturnTypes, /*reportErrors*/ false, + /*errorReporter*/ undefined, compareTypesAssignable) !== 0 /* False */; + } + /** + * See signatureRelatedTo, compareSignaturesIdentical + */ + function compareSignaturesRelated(source, target, callbackCheck, ignoreReturnTypes, reportErrors, errorReporter, compareTypes) { + // TODO (drosen): De-duplicate code between related functions. + if (source === target) { + return -1 /* True */; + } + var targetCount = getParameterCount(target); + if (!hasEffectiveRestParameter(target) && getMinArgumentCount(source) > targetCount) { + return 0 /* False */; + } + if (source.typeParameters && source.typeParameters !== target.typeParameters) { + target = getCanonicalSignature(target); + source = instantiateSignatureInContextOf(source, target, /*contextualMapper*/ undefined, compareTypes); + } + var sourceCount = getParameterCount(source); + var sourceRestType = getNonArrayRestType(source); + var targetRestType = getNonArrayRestType(target); + if (sourceRestType && targetRestType && sourceCount !== targetCount) { + // We're not able to relate misaligned complex rest parameters + return 0 /* False */; + } + var kind = target.declaration ? target.declaration.kind : 0 /* Unknown */; + var strictVariance = !callbackCheck && strictFunctionTypes && kind !== 156 /* MethodDeclaration */ && + kind !== 155 /* MethodSignature */ && kind !== 157 /* Constructor */; + var result = -1 /* True */; + var sourceThisType = getThisTypeOfSignature(source); + if (sourceThisType && sourceThisType !== voidType) { + var targetThisType = getThisTypeOfSignature(target); + if (targetThisType) { + // void sources are assignable to anything. + var related = !strictVariance && compareTypes(sourceThisType, targetThisType, /*reportErrors*/ false) + || compareTypes(targetThisType, sourceThisType, reportErrors); + if (!related) { + if (reportErrors) { + errorReporter(ts.Diagnostics.The_this_types_of_each_signature_are_incompatible); + } + return 0 /* False */; + } + result &= related; + } + } + var paramCount = sourceRestType || targetRestType ? Math.min(sourceCount, targetCount) : Math.max(sourceCount, targetCount); + var restIndex = sourceRestType || targetRestType ? paramCount - 1 : -1; + for (var i = 0; i < paramCount; i++) { + var sourceType = i === restIndex ? getRestTypeAtPosition(source, i) : getTypeAtPosition(source, i); + var targetType = i === restIndex ? getRestTypeAtPosition(target, i) : getTypeAtPosition(target, i); + // In order to ensure that any generic type Foo is at least co-variant with respect to T no matter + // how Foo uses T, we need to relate parameters bi-variantly (given that parameters are input positions, + // they naturally relate only contra-variantly). However, if the source and target parameters both have + // function types with a single call signature, we know we are relating two callback parameters. In + // that case it is sufficient to only relate the parameters of the signatures co-variantly because, + // similar to return values, callback parameters are output positions. This means that a Promise, + // where T is used only in callback parameter positions, will be co-variant (as opposed to bi-variant) + // with respect to T. + var sourceSig = callbackCheck ? undefined : getSingleCallSignature(getNonNullableType(sourceType)); + var targetSig = callbackCheck ? undefined : getSingleCallSignature(getNonNullableType(targetType)); + var callbacks = sourceSig && targetSig && !signatureHasTypePredicate(sourceSig) && !signatureHasTypePredicate(targetSig) && + (getFalsyFlags(sourceType) & 98304 /* Nullable */) === (getFalsyFlags(targetType) & 98304 /* Nullable */); + var related = callbacks ? + // TODO: GH#18217 It will work if they're both `undefined`, but not if only one is + compareSignaturesRelated(targetSig, sourceSig, strictVariance ? 2 /* Strict */ : 1 /* Bivariant */, /*ignoreReturnTypes*/ false, reportErrors, errorReporter, compareTypes) : + !callbackCheck && !strictVariance && compareTypes(sourceType, targetType, /*reportErrors*/ false) || compareTypes(targetType, sourceType, reportErrors); + if (!related) { + if (reportErrors) { + errorReporter(ts.Diagnostics.Types_of_parameters_0_and_1_are_incompatible, ts.unescapeLeadingUnderscores(getParameterNameAtPosition(source, i)), ts.unescapeLeadingUnderscores(getParameterNameAtPosition(target, i))); + } + return 0 /* False */; + } + result &= related; + } + if (!ignoreReturnTypes) { + var targetReturnType = (target.declaration && isJSConstructor(target.declaration)) ? + getJSClassType(target.declaration.symbol) : getReturnTypeOfSignature(target); + if (targetReturnType === voidType) { + return result; + } + var sourceReturnType = (source.declaration && isJSConstructor(source.declaration)) ? + getJSClassType(source.declaration.symbol) : getReturnTypeOfSignature(source); + // The following block preserves behavior forbidding boolean returning functions from being assignable to type guard returning functions + var targetTypePredicate = getTypePredicateOfSignature(target); + if (targetTypePredicate) { + var sourceTypePredicate = getTypePredicateOfSignature(source); + if (sourceTypePredicate) { + result &= compareTypePredicateRelatedTo(sourceTypePredicate, targetTypePredicate, source.declaration, target.declaration, reportErrors, errorReporter, compareTypes); // TODO: GH#18217 + } + else if (ts.isIdentifierTypePredicate(targetTypePredicate)) { + if (reportErrors) { + errorReporter(ts.Diagnostics.Signature_0_must_be_a_type_predicate, signatureToString(source)); + } + return 0 /* False */; + } + } + else { + // When relating callback signatures, we still need to relate return types bi-variantly as otherwise + // the containing type wouldn't be co-variant. For example, interface Foo { add(cb: () => T): void } + // wouldn't be co-variant for T without this rule. + result &= callbackCheck === 1 /* Bivariant */ && compareTypes(targetReturnType, sourceReturnType, /*reportErrors*/ false) || + compareTypes(sourceReturnType, targetReturnType, reportErrors); + } + } + return result; + } + function compareTypePredicateRelatedTo(source, target, sourceDeclaration, targetDeclaration, reportErrors, errorReporter, compareTypes) { + if (source.kind !== target.kind) { + if (reportErrors) { + errorReporter(ts.Diagnostics.A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard); + errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target)); + } + return 0 /* False */; + } + if (source.kind === 1 /* Identifier */) { + var targetPredicate = target; + var sourceIndex = source.parameterIndex - (ts.getThisParameter(sourceDeclaration) ? 1 : 0); + var targetIndex = targetPredicate.parameterIndex - (ts.getThisParameter(targetDeclaration) ? 1 : 0); + if (sourceIndex !== targetIndex) { + if (reportErrors) { + errorReporter(ts.Diagnostics.Parameter_0_is_not_in_the_same_position_as_parameter_1, source.parameterName, targetPredicate.parameterName); + errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target)); + } + return 0 /* False */; + } + } + var related = compareTypes(source.type, target.type, reportErrors); + if (related === 0 /* False */ && reportErrors) { + errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target)); + } + return related; + } + function isImplementationCompatibleWithOverload(implementation, overload) { + var erasedSource = getErasedSignature(implementation); + var erasedTarget = getErasedSignature(overload); + // First see if the return types are compatible in either direction. + var sourceReturnType = getReturnTypeOfSignature(erasedSource); + var targetReturnType = getReturnTypeOfSignature(erasedTarget); + if (targetReturnType === voidType + || isTypeRelatedTo(targetReturnType, sourceReturnType, assignableRelation) + || isTypeRelatedTo(sourceReturnType, targetReturnType, assignableRelation)) { + return isSignatureAssignableTo(erasedSource, erasedTarget, /*ignoreReturnTypes*/ true); + } + return false; + } + function isEmptyResolvedType(t) { + return t.properties.length === 0 && + t.callSignatures.length === 0 && + t.constructSignatures.length === 0 && + !t.stringIndexInfo && + !t.numberIndexInfo; + } + function isEmptyObjectType(type) { + return type.flags & 524288 /* Object */ ? isEmptyResolvedType(resolveStructuredTypeMembers(type)) : + type.flags & 67108864 /* NonPrimitive */ ? true : + type.flags & 1048576 /* Union */ ? ts.some(type.types, isEmptyObjectType) : + type.flags & 2097152 /* Intersection */ ? ts.every(type.types, isEmptyObjectType) : + false; + } + function isEmptyAnonymousObjectType(type) { + return !!(ts.getObjectFlags(type) & 16 /* Anonymous */) && isEmptyObjectType(type); + } + function isEnumTypeRelatedTo(sourceSymbol, targetSymbol, errorReporter) { + if (sourceSymbol === targetSymbol) { + return true; + } + var id = getSymbolId(sourceSymbol) + "," + getSymbolId(targetSymbol); + var relation = enumRelation.get(id); + if (relation !== undefined && !(relation === 2 /* Failed */ && errorReporter)) { + return relation === 1 /* Succeeded */; + } + if (sourceSymbol.escapedName !== targetSymbol.escapedName || !(sourceSymbol.flags & 256 /* RegularEnum */) || !(targetSymbol.flags & 256 /* RegularEnum */)) { + enumRelation.set(id, 3 /* FailedAndReported */); + return false; + } + var targetEnumType = getTypeOfSymbol(targetSymbol); + for (var _i = 0, _a = getPropertiesOfType(getTypeOfSymbol(sourceSymbol)); _i < _a.length; _i++) { + var property = _a[_i]; + if (property.flags & 8 /* EnumMember */) { + var targetProperty = getPropertyOfType(targetEnumType, property.escapedName); + if (!targetProperty || !(targetProperty.flags & 8 /* EnumMember */)) { + if (errorReporter) { + errorReporter(ts.Diagnostics.Property_0_is_missing_in_type_1, ts.symbolName(property), typeToString(getDeclaredTypeOfSymbol(targetSymbol), /*enclosingDeclaration*/ undefined, 64 /* UseFullyQualifiedType */)); + enumRelation.set(id, 3 /* FailedAndReported */); + } + else { + enumRelation.set(id, 2 /* Failed */); + } + return false; + } + } + } + enumRelation.set(id, 1 /* Succeeded */); + return true; + } + function isSimpleTypeRelatedTo(source, target, relation, errorReporter) { + var s = source.flags; + var t = target.flags; + if (t & 3 /* AnyOrUnknown */ || s & 131072 /* Never */ || source === wildcardType) + return true; + if (t & 131072 /* Never */) + return false; + if (s & 132 /* StringLike */ && t & 4 /* String */) + return true; + if (s & 128 /* StringLiteral */ && s & 1024 /* EnumLiteral */ && + t & 128 /* StringLiteral */ && !(t & 1024 /* EnumLiteral */) && + source.value === target.value) + return true; + if (s & 296 /* NumberLike */ && t & 8 /* Number */) + return true; + if (s & 256 /* NumberLiteral */ && s & 1024 /* EnumLiteral */ && + t & 256 /* NumberLiteral */ && !(t & 1024 /* EnumLiteral */) && + source.value === target.value) + return true; + if (s & 2112 /* BigIntLike */ && t & 64 /* BigInt */) + return true; + if (s & 528 /* BooleanLike */ && t & 16 /* Boolean */) + return true; + if (s & 12288 /* ESSymbolLike */ && t & 4096 /* ESSymbol */) + return true; + if (s & 32 /* Enum */ && t & 32 /* Enum */ && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) + return true; + if (s & 1024 /* EnumLiteral */ && t & 1024 /* EnumLiteral */) { + if (s & 1048576 /* Union */ && t & 1048576 /* Union */ && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) + return true; + if (s & 2944 /* Literal */ && t & 2944 /* Literal */ && + source.value === target.value && + isEnumTypeRelatedTo(getParentOfSymbol(source.symbol), getParentOfSymbol(target.symbol), errorReporter)) + return true; + } + if (s & 32768 /* Undefined */ && (!strictNullChecks || t & (32768 /* Undefined */ | 16384 /* Void */))) + return true; + if (s & 65536 /* Null */ && (!strictNullChecks || t & 65536 /* Null */)) + return true; + if (s & 524288 /* Object */ && t & 67108864 /* NonPrimitive */) + return true; + if (s & 8192 /* UniqueESSymbol */ || t & 8192 /* UniqueESSymbol */) + return false; + if (relation === assignableRelation || relation === definitelyAssignableRelation || relation === comparableRelation) { + if (s & 1 /* Any */) + return true; + // Type number or any numeric literal type is assignable to any numeric enum type or any + // numeric enum literal type. This rule exists for backwards compatibility reasons because + // bit-flag enum types sometimes look like literal enum types with numeric literal values. + if (s & (8 /* Number */ | 256 /* NumberLiteral */) && !(s & 1024 /* EnumLiteral */) && (t & 32 /* Enum */ || t & 256 /* NumberLiteral */ && t & 1024 /* EnumLiteral */)) + return true; + } + return false; + } + function isTypeRelatedTo(source, target, relation) { + if (isFreshLiteralType(source)) { + source = source.regularType; + } + if (isFreshLiteralType(target)) { + target = target.regularType; + } + if (source === target || + relation === comparableRelation && !(target.flags & 131072 /* Never */) && isSimpleTypeRelatedTo(target, source, relation) || + relation !== identityRelation && isSimpleTypeRelatedTo(source, target, relation)) { + return true; + } + if (source.flags & 524288 /* Object */ && target.flags & 524288 /* Object */) { + var related = relation.get(getRelationKey(source, target, relation)); + if (related !== undefined) { + return related === 1 /* Succeeded */; + } + } + if (source.flags & 66846720 /* StructuredOrInstantiable */ || target.flags & 66846720 /* StructuredOrInstantiable */) { + return checkTypeRelatedTo(source, target, relation, /*errorNode*/ undefined); + } + return false; + } + function isIgnoredJsxProperty(source, sourceProp, targetMemberType) { + return ts.getObjectFlags(source) & 4096 /* JsxAttributes */ && !(isUnhyphenatedJsxName(sourceProp.escapedName) || targetMemberType); + } + /** + * Checks if 'source' is related to 'target' (e.g.: is a assignable to). + * @param source The left-hand-side of the relation. + * @param target The right-hand-side of the relation. + * @param relation The relation considered. One of 'identityRelation', 'subtypeRelation', 'assignableRelation', or 'comparableRelation'. + * Used as both to determine which checks are performed and as a cache of previously computed results. + * @param errorNode The suggested node upon which all errors will be reported, if defined. This may or may not be the actual node used. + * @param headMessage If the error chain should be prepended by a head message, then headMessage will be used. + * @param containingMessageChain A chain of errors to prepend any new errors found. + */ + function checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain, errorOutputContainer) { + var errorInfo; + var relatedInfo; + var maybeKeys; + var sourceStack; + var targetStack; + var maybeCount = 0; + var depth = 0; + var expandingFlags = 0 /* None */; + var overflow = false; + var suppressNextError = false; + ts.Debug.assert(relation !== identityRelation || !errorNode, "no error reporting in identity checking"); + var result = isRelatedTo(source, target, /*reportErrors*/ !!errorNode, headMessage); + if (overflow) { + error(errorNode, ts.Diagnostics.Excessive_stack_depth_comparing_types_0_and_1, typeToString(source), typeToString(target)); + } + else if (errorInfo) { + if (containingMessageChain) { + var chain_1 = containingMessageChain(); + if (chain_1) { + errorInfo = ts.concatenateDiagnosticMessageChains(chain_1, errorInfo); + } + } + var relatedInformation = void 0; + // Check if we should issue an extra diagnostic to produce a quickfix for a slightly incorrect import statement + if (headMessage && errorNode && !result && source.symbol) { + var links = getSymbolLinks(source.symbol); + if (links.originatingImport && !ts.isImportCall(links.originatingImport)) { + var helpfulRetry = checkTypeRelatedTo(getTypeOfSymbol(links.target), target, relation, /*errorNode*/ undefined); + if (helpfulRetry) { + // Likely an incorrect import. Issue a helpful diagnostic to produce a quickfix to change the import + var diag_1 = ts.createDiagnosticForNode(links.originatingImport, ts.Diagnostics.Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_Consider_using_a_default_import_or_import_require_here_instead); + relatedInformation = ts.append(relatedInformation, diag_1); // Cause the error to appear with the error that triggered it + } + } + } + var diag = ts.createDiagnosticForNodeFromMessageChain(errorNode, errorInfo, relatedInformation); + if (relatedInfo) { + addRelatedInfo.apply(void 0, [diag].concat(relatedInfo)); + } + if (errorOutputContainer) { + errorOutputContainer.error = diag; + } + diagnostics.add(diag); // TODO: GH#18217 + } + return result !== 0 /* False */; + function reportError(message, arg0, arg1, arg2, arg3) { + ts.Debug.assert(!!errorNode); + errorInfo = ts.chainDiagnosticMessages(errorInfo, message, arg0, arg1, arg2, arg3); + } + function associateRelatedInfo(info) { + ts.Debug.assert(!!errorInfo); + if (!relatedInfo) { + relatedInfo = [info]; + } + else { + relatedInfo.push(info); + } + } + function reportRelationError(message, source, target) { + var sourceType = typeToString(source); + var targetType = typeToString(target); + if (sourceType === targetType) { + sourceType = typeToString(source, /*enclosingDeclaration*/ undefined, 64 /* UseFullyQualifiedType */); + targetType = typeToString(target, /*enclosingDeclaration*/ undefined, 64 /* UseFullyQualifiedType */); + } + if (!message) { + if (relation === comparableRelation) { + message = ts.Diagnostics.Type_0_is_not_comparable_to_type_1; + } + else if (sourceType === targetType) { + message = ts.Diagnostics.Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated; + } + else { + message = ts.Diagnostics.Type_0_is_not_assignable_to_type_1; + } + } + reportError(message, sourceType, targetType); + } + function tryElaborateErrorsForPrimitivesAndObjects(source, target) { + var sourceType = typeToString(source); + var targetType = typeToString(target); + if ((globalStringType === source && stringType === target) || + (globalNumberType === source && numberType === target) || + (globalBooleanType === source && booleanType === target) || + (getGlobalESSymbolType(/*reportErrors*/ false) === source && esSymbolType === target)) { + reportError(ts.Diagnostics._0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible, targetType, sourceType); + } + } + function isUnionOrIntersectionTypeWithoutNullableConstituents(type) { + if (!(type.flags & 3145728 /* UnionOrIntersection */)) { + return false; + } + // at this point we know that this is union or intersection type possibly with nullable constituents. + // check if we still will have compound type if we ignore nullable components. + var seenNonNullable = false; + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (t.flags & 98304 /* Nullable */) { + continue; + } + if (seenNonNullable) { + return true; + } + seenNonNullable = true; + } + return false; + } + /** + * Compare two types and return + * * Ternary.True if they are related with no assumptions, + * * Ternary.Maybe if they are related with assumptions of other relationships, or + * * Ternary.False if they are not related. + */ + function isRelatedTo(source, target, reportErrors, headMessage, isApparentIntersectionConstituent) { + if (reportErrors === void 0) { reportErrors = false; } + if (isFreshLiteralType(source)) { + source = source.regularType; + } + if (isFreshLiteralType(target)) { + target = target.regularType; + } + if (source.flags & 33554432 /* Substitution */) { + source = relation === definitelyAssignableRelation ? source.typeVariable : source.substitute; + } + if (target.flags & 33554432 /* Substitution */) { + target = target.typeVariable; + } + if (source.flags & 8388608 /* IndexedAccess */) { + source = getSimplifiedType(source); + } + if (target.flags & 8388608 /* IndexedAccess */) { + target = getSimplifiedType(target); + } + // Try to see if we're relating something like `Foo` -> `Bar | null | undefined`. + // If so, reporting the `null` and `undefined` in the type is hardly useful. + // First, see if we're even relating an object type to a union. + // Then see if the target is stripped down to a single non-union type. + // Note + // * We actually want to remove null and undefined naively here (rather than using getNonNullableType), + // since we don't want to end up with a worse error like "`Foo` is not assignable to `NonNullable`" + // when dealing with generics. + // * We also don't deal with primitive source types, since we already halt elaboration below. + if (target.flags & 1048576 /* Union */ && source.flags & 524288 /* Object */ && + target.types.length <= 3 && maybeTypeOfKind(target, 98304 /* Nullable */)) { + var nullStrippedTarget = extractTypesOfKind(target, ~98304 /* Nullable */); + if (!(nullStrippedTarget.flags & (1048576 /* Union */ | 131072 /* Never */))) { + target = nullStrippedTarget; + } + } + // both types are the same - covers 'they are the same primitive type or both are Any' or the same type parameter cases + if (source === target) + return -1 /* True */; + if (relation === identityRelation) { + return isIdenticalTo(source, target); + } + if (relation === comparableRelation && !(target.flags & 131072 /* Never */) && isSimpleTypeRelatedTo(target, source, relation) || + isSimpleTypeRelatedTo(source, target, relation, reportErrors ? reportError : undefined)) + return -1 /* True */; + var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096 /* JsxAttributes */); + if (isObjectLiteralType(source) && ts.getObjectFlags(source) & 32768 /* FreshLiteral */) { + var discriminantType = target.flags & 1048576 /* Union */ ? findMatchingDiscriminantType(source, target) : undefined; + if (hasExcessProperties(source, target, discriminantType, reportErrors)) { + if (reportErrors) { + reportRelationError(headMessage, source, target); + } + return 0 /* False */; + } + // Above we check for excess properties with respect to the entire target type. When union + // and intersection types are further deconstructed on the target side, we don't want to + // make the check again (as it might fail for a partial target type). Therefore we obtain + // the regular source type and proceed with that. + if (isUnionOrIntersectionTypeWithoutNullableConstituents(target) && !discriminantType) { + source = getRegularTypeOfObjectLiteral(source); + } + } + if (relation !== comparableRelation && !isApparentIntersectionConstituent && + source.flags & (131068 /* Primitive */ | 524288 /* Object */ | 2097152 /* Intersection */) && source !== globalObjectType && + target.flags & (524288 /* Object */ | 2097152 /* Intersection */) && isWeakType(target) && + (getPropertiesOfType(source).length > 0 || typeHasCallOrConstructSignatures(source)) && + !hasCommonProperties(source, target, isComparingJsxAttributes)) { + if (reportErrors) { + var calls = getSignaturesOfType(source, 0 /* Call */); + var constructs = getSignaturesOfType(source, 1 /* Construct */); + if (calls.length > 0 && isRelatedTo(getReturnTypeOfSignature(calls[0]), target, /*reportErrors*/ false) || + constructs.length > 0 && isRelatedTo(getReturnTypeOfSignature(constructs[0]), target, /*reportErrors*/ false)) { + reportError(ts.Diagnostics.Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it, typeToString(source), typeToString(target)); + } + else { + reportError(ts.Diagnostics.Type_0_has_no_properties_in_common_with_type_1, typeToString(source), typeToString(target)); + } + } + return 0 /* False */; + } + var result = 0 /* False */; + var saveErrorInfo = errorInfo; + var isIntersectionConstituent = !!isApparentIntersectionConstituent; + // Note that these checks are specifically ordered to produce correct results. In particular, + // we need to deconstruct unions before intersections (because unions are always at the top), + // and we need to handle "each" relations before "some" relations for the same kind of type. + if (source.flags & 1048576 /* Union */) { + result = relation === comparableRelation ? + someTypeRelatedToType(source, target, reportErrors && !(source.flags & 131068 /* Primitive */)) : + eachTypeRelatedToType(source, target, reportErrors && !(source.flags & 131068 /* Primitive */)); + } + else { + if (target.flags & 1048576 /* Union */) { + result = typeRelatedToSomeType(source, target, reportErrors && !(source.flags & 131068 /* Primitive */) && !(target.flags & 131068 /* Primitive */)); + } + else if (target.flags & 2097152 /* Intersection */) { + isIntersectionConstituent = true; // set here to affect the following trio of checks + result = typeRelatedToEachType(source, target, reportErrors); + } + else if (source.flags & 2097152 /* Intersection */) { + // Check to see if any constituents of the intersection are immediately related to the target. + // + // Don't report errors though. Checking whether a constituent is related to the source is not actually + // useful and leads to some confusing error messages. Instead it is better to let the below checks + // take care of this, or to not elaborate at all. For instance, + // + // - For an object type (such as 'C = A & B'), users are usually more interested in structural errors. + // + // - For a union type (such as '(A | B) = (C & D)'), it's better to hold onto the whole intersection + // than to report that 'D' is not assignable to 'A' or 'B'. + // + // - For a primitive type or type parameter (such as 'number = A & B') there is no point in + // breaking the intersection apart. + result = someTypeRelatedToType(source, target, /*reportErrors*/ false); + } + if (!result && (source.flags & 66846720 /* StructuredOrInstantiable */ || target.flags & 66846720 /* StructuredOrInstantiable */)) { + if (result = recursiveTypeRelatedTo(source, target, reportErrors, isIntersectionConstituent)) { + errorInfo = saveErrorInfo; + } + } + } + if (!result && source.flags & 2097152 /* Intersection */) { + // The combined constraint of an intersection type is the intersection of the constraints of + // the constituents. When an intersection type contains instantiable types with union type + // constraints, there are situations where we need to examine the combined constraint. One is + // when the target is a union type. Another is when the intersection contains types belonging + // to one of the disjoint domains. For example, given type variables T and U, each with the + // constraint 'string | number', the combined constraint of 'T & U' is 'string | number' and + // we need to check this constraint against a union on the target side. Also, given a type + // variable V constrained to 'string | number', 'V & number' has a combined constraint of + // 'string & number | number & number' which reduces to just 'number'. + var constraint = getUnionConstraintOfIntersection(source, !!(target.flags & 1048576 /* Union */)); + if (constraint) { + if (result = isRelatedTo(constraint, target, reportErrors, /*headMessage*/ undefined, isIntersectionConstituent)) { + errorInfo = saveErrorInfo; + } + } + } + if (!result && reportErrors) { + var maybeSuppress = suppressNextError; + suppressNextError = false; + if (source.flags & 524288 /* Object */ && target.flags & 131068 /* Primitive */) { + tryElaborateErrorsForPrimitivesAndObjects(source, target); + } + else if (source.symbol && source.flags & 524288 /* Object */ && globalObjectType === source) { + reportError(ts.Diagnostics.The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead); + } + else if (isComparingJsxAttributes && target.flags & 2097152 /* Intersection */) { + var targetTypes = target.types; + var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes, errorNode); + var intrinsicClassAttributes = getJsxType(JsxNames.IntrinsicClassAttributes, errorNode); + if (intrinsicAttributes !== errorType && intrinsicClassAttributes !== errorType && + (ts.contains(targetTypes, intrinsicAttributes) || ts.contains(targetTypes, intrinsicClassAttributes))) { + // do not report top error + return result; + } + } + if (!headMessage && maybeSuppress) { + // Used by, eg, missing property checking to replace the top-level message with a more informative one + return result; + } + reportRelationError(headMessage, source, target); + } + return result; + } + function isIdenticalTo(source, target) { + var result; + var flags = source.flags & target.flags; + if (flags & 524288 /* Object */ || flags & 8388608 /* IndexedAccess */ || flags & 16777216 /* Conditional */ || flags & 4194304 /* Index */ || flags & 33554432 /* Substitution */) { + return recursiveTypeRelatedTo(source, target, /*reportErrors*/ false, /*isIntersectionConstituent*/ false); + } + if (flags & (1048576 /* Union */ | 2097152 /* Intersection */)) { + if (result = eachTypeRelatedToSomeType(source, target)) { + if (result &= eachTypeRelatedToSomeType(target, source)) { + return result; + } + } + } + return 0 /* False */; + } + function hasExcessProperties(source, target, discriminant, reportErrors) { + if (!noImplicitAny && ts.getObjectFlags(target) & 16384 /* JSLiteral */) { + return false; // Disable excess property checks on JS literals to simulate having an implicit "index signature" - but only outside of noImplicitAny + } + if (maybeTypeOfKind(target, 524288 /* Object */) && !(ts.getObjectFlags(target) & 512 /* ObjectLiteralPatternWithComputedProperties */)) { + var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096 /* JsxAttributes */); + if ((relation === assignableRelation || relation === definitelyAssignableRelation || relation === comparableRelation) && + (isTypeSubsetOf(globalObjectType, target) || (!isComparingJsxAttributes && isEmptyObjectType(target)))) { + return false; + } + if (discriminant) { + // check excess properties against discriminant type only, not the entire union + return hasExcessProperties(source, discriminant, /*discriminant*/ undefined, reportErrors); + } + var _loop_6 = function (prop) { + if (shouldCheckAsExcessProperty(prop, source.symbol) && !isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { + if (reportErrors) { + // We know *exactly* where things went wrong when comparing the types. + // Use this property as the error node as this will be more helpful in + // reasoning about what went wrong. + if (!errorNode) + return { value: ts.Debug.fail() }; + if (ts.isJsxAttributes(errorNode) || ts.isJsxOpeningLikeElement(errorNode) || ts.isJsxOpeningLikeElement(errorNode.parent)) { + // JsxAttributes has an object-literal flag and undergo same type-assignablity check as normal object-literal. + // However, using an object-literal error message will be very confusing to the users so we give different a message. + // TODO: Spelling suggestions for excess jsx attributes (needs new diagnostic messages) + reportError(ts.Diagnostics.Property_0_does_not_exist_on_type_1, symbolToString(prop), typeToString(target)); + } + else { + // use the property's value declaration if the property is assigned inside the literal itself + var objectLiteralDeclaration_1 = source.symbol && ts.firstOrUndefined(source.symbol.declarations); + var suggestion = void 0; + if (prop.valueDeclaration && ts.findAncestor(prop.valueDeclaration, function (d) { return d === objectLiteralDeclaration_1; })) { + var propDeclaration = prop.valueDeclaration; + ts.Debug.assertNode(propDeclaration, ts.isObjectLiteralElementLike); + errorNode = propDeclaration; + var name = propDeclaration.name; + if (ts.isIdentifier(name)) { + suggestion = getSuggestionForNonexistentProperty(name, target); + } + } + if (suggestion !== undefined) { + reportError(ts.Diagnostics.Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_write_2, symbolToString(prop), typeToString(target), suggestion); + } + else { + reportError(ts.Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(prop), typeToString(target)); + } + } + } + return { value: true }; + } + }; + for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) { + var prop = _a[_i]; + var state_2 = _loop_6(prop); + if (typeof state_2 === "object") + return state_2.value; + } + } + return false; + } + function shouldCheckAsExcessProperty(prop, container) { + return prop.valueDeclaration && container.valueDeclaration && prop.valueDeclaration.parent === container.valueDeclaration; + } + function eachTypeRelatedToSomeType(source, target) { + var result = -1 /* True */; + var sourceTypes = source.types; + for (var _i = 0, sourceTypes_1 = sourceTypes; _i < sourceTypes_1.length; _i++) { + var sourceType = sourceTypes_1[_i]; + var related = typeRelatedToSomeType(sourceType, target, /*reportErrors*/ false); + if (!related) { + return 0 /* False */; + } + result &= related; + } + return result; + } + function typeRelatedToSomeType(source, target, reportErrors) { + var targetTypes = target.types; + if (target.flags & 1048576 /* Union */ && containsType(targetTypes, source)) { + return -1 /* True */; + } + for (var _i = 0, targetTypes_1 = targetTypes; _i < targetTypes_1.length; _i++) { + var type = targetTypes_1[_i]; + var related = isRelatedTo(source, type, /*reportErrors*/ false); + if (related) { + return related; + } + } + if (reportErrors) { + var bestMatchingType = findMatchingDiscriminantType(source, target) || + findMatchingTypeReferenceOrTypeAliasReference(source, target) || + findBestTypeForObjectLiteral(source, target) || + findBestTypeForInvokable(source, target) || + findMostOverlappyType(source, target); + isRelatedTo(source, bestMatchingType || targetTypes[targetTypes.length - 1], /*reportErrors*/ true); + } + return 0 /* False */; + } + function findMatchingTypeReferenceOrTypeAliasReference(source, unionTarget) { + var sourceObjectFlags = ts.getObjectFlags(source); + if (sourceObjectFlags & (4 /* Reference */ | 16 /* Anonymous */) && unionTarget.flags & 1048576 /* Union */) { + return ts.find(unionTarget.types, function (target) { + if (target.flags & 524288 /* Object */) { + var overlapObjFlags = sourceObjectFlags & ts.getObjectFlags(target); + if (overlapObjFlags & 4 /* Reference */) { + return source.target === target.target; + } + if (overlapObjFlags & 16 /* Anonymous */) { + return !!source.aliasSymbol && source.aliasSymbol === target.aliasSymbol; + } + } + return false; + }); + } + } + function findBestTypeForObjectLiteral(source, unionTarget) { + if (ts.getObjectFlags(source) & 128 /* ObjectLiteral */ && forEachType(unionTarget, isArrayLikeType)) { + return ts.find(unionTarget.types, function (t) { return !isArrayLikeType(t); }); + } + } + function findBestTypeForInvokable(source, unionTarget) { + var signatureKind = 0 /* Call */; + var hasSignatures = getSignaturesOfType(source, signatureKind).length > 0 || + (signatureKind = 1 /* Construct */, getSignaturesOfType(source, signatureKind).length > 0); + if (hasSignatures) { + return ts.find(unionTarget.types, function (t) { return getSignaturesOfType(t, signatureKind).length > 0; }); + } + } + function findMostOverlappyType(source, unionTarget) { + var bestMatch; + var matchingCount = 0; + for (var _i = 0, _a = unionTarget.types; _i < _a.length; _i++) { + var target_1 = _a[_i]; + var overlap = getIntersectionType([getIndexType(source), getIndexType(target_1)]); + if (overlap.flags & 4194304 /* Index */) { + // perfect overlap of keys + bestMatch = target_1; + matchingCount = Infinity; + } + else if (overlap.flags & 1048576 /* Union */) { + // Some subset overlap if we have only string literals. + // If we have a union of index types, it seems likely that we + // needed to elaborate between two generic mapped types anyway. + var len = ts.length(overlap.types); + if (len >= matchingCount) { + bestMatch = target_1; + matchingCount = len; + } + } + else if (!(overlap.flags & 131072 /* Never */) && 1 >= matchingCount) { + bestMatch = target_1; + matchingCount = 1; + } + } + return bestMatch; + } + // Keep this up-to-date with the same logic within `getApparentTypeOfContextualType`, since they should behave similarly + function findMatchingDiscriminantType(source, target) { + if (target.flags & 1048576 /* Union */) { + var sourceProperties = getPropertiesOfObjectType(source); + if (sourceProperties) { + var sourcePropertiesFiltered = findDiscriminantProperties(sourceProperties, target); + if (sourcePropertiesFiltered) { + return discriminateTypeByDiscriminableItems(target, ts.map(sourcePropertiesFiltered, function (p) { return [function () { return getTypeOfSymbol(p); }, p.escapedName]; }), isRelatedTo); + } + } + } + return undefined; + } + function typeRelatedToEachType(source, target, reportErrors) { + var result = -1 /* True */; + var targetTypes = target.types; + for (var _i = 0, targetTypes_2 = targetTypes; _i < targetTypes_2.length; _i++) { + var targetType = targetTypes_2[_i]; + var related = isRelatedTo(source, targetType, reportErrors, /*headMessage*/ undefined, /*isIntersectionConstituent*/ true); + if (!related) { + return 0 /* False */; + } + result &= related; + } + return result; + } + function someTypeRelatedToType(source, target, reportErrors) { + var sourceTypes = source.types; + if (source.flags & 1048576 /* Union */ && containsType(sourceTypes, target)) { + return -1 /* True */; + } + var len = sourceTypes.length; + for (var i = 0; i < len; i++) { + var related = isRelatedTo(sourceTypes[i], target, reportErrors && i === len - 1); + if (related) { + return related; + } + } + return 0 /* False */; + } + function eachTypeRelatedToType(source, target, reportErrors) { + var result = -1 /* True */; + var sourceTypes = source.types; + for (var _i = 0, sourceTypes_2 = sourceTypes; _i < sourceTypes_2.length; _i++) { + var sourceType = sourceTypes_2[_i]; + var related = isRelatedTo(sourceType, target, reportErrors); + if (!related) { + return 0 /* False */; + } + result &= related; + } + return result; + } + function typeArgumentsRelatedTo(sources, targets, variances, reportErrors) { + if (sources === void 0) { sources = ts.emptyArray; } + if (targets === void 0) { targets = ts.emptyArray; } + if (variances === void 0) { variances = ts.emptyArray; } + if (sources.length !== targets.length && relation === identityRelation) { + return 0 /* False */; + } + var length = sources.length <= targets.length ? sources.length : targets.length; + var result = -1 /* True */; + for (var i = 0; i < length; i++) { + // When variance information isn't available we default to covariance. This happens + // in the process of computing variance information for recursive types and when + // comparing 'this' type arguments. + var variance = i < variances.length ? variances[i] : 1 /* Covariant */; + // We ignore arguments for independent type parameters (because they're never witnessed). + if (variance !== 4 /* Independent */) { + var s = sources[i]; + var t = targets[i]; + var related = -1 /* True */; + if (variance === 1 /* Covariant */) { + related = isRelatedTo(s, t, reportErrors); + } + else if (variance === 2 /* Contravariant */) { + related = isRelatedTo(t, s, reportErrors); + } + else if (variance === 3 /* Bivariant */) { + // In the bivariant case we first compare contravariantly without reporting + // errors. Then, if that doesn't succeed, we compare covariantly with error + // reporting. Thus, error elaboration will be based on the the covariant check, + // which is generally easier to reason about. + related = isRelatedTo(t, s, /*reportErrors*/ false); + if (!related) { + related = isRelatedTo(s, t, reportErrors); + } + } + else { + // In the invariant case we first compare covariantly, and only when that + // succeeds do we proceed to compare contravariantly. Thus, error elaboration + // will typically be based on the covariant check. + related = isRelatedTo(s, t, reportErrors); + if (related) { + related &= isRelatedTo(t, s, reportErrors); + } + } + if (!related) { + return 0 /* False */; + } + result &= related; + } + } + return result; + } + // Determine if possibly recursive types are related. First, check if the result is already available in the global cache. + // Second, check if we have already started a comparison of the given two types in which case we assume the result to be true. + // Third, check if both types are part of deeply nested chains of generic type instantiations and if so assume the types are + // equal and infinitely expanding. Fourth, if we have reached a depth of 100 nested comparisons, assume we have runaway recursion + // and issue an error. Otherwise, actually compare the structure of the two types. + function recursiveTypeRelatedTo(source, target, reportErrors, isIntersectionConstituent) { + if (overflow) { + return 0 /* False */; + } + var id = getRelationKey(source, target, relation); + var related = relation.get(id); + if (related !== undefined) { + if (reportErrors && related === 2 /* Failed */) { + // We are elaborating errors and the cached result is an unreported failure. The result will be reported + // as a failure, and should be updated as a reported failure by the bottom of this function. + } + else { + return related === 1 /* Succeeded */ ? -1 /* True */ : 0 /* False */; + } + } + if (!maybeKeys) { + maybeKeys = []; + sourceStack = []; + targetStack = []; + } + else { + for (var i = 0; i < maybeCount; i++) { + // If source and target are already being compared, consider them related with assumptions + if (id === maybeKeys[i]) { + return 1 /* Maybe */; + } + } + if (depth === 100) { + overflow = true; + return 0 /* False */; + } + } + var maybeStart = maybeCount; + maybeKeys[maybeCount] = id; + maybeCount++; + sourceStack[depth] = source; + targetStack[depth] = target; + depth++; + var saveExpandingFlags = expandingFlags; + if (!(expandingFlags & 1 /* Source */) && isDeeplyNestedType(source, sourceStack, depth)) + expandingFlags |= 1 /* Source */; + if (!(expandingFlags & 2 /* Target */) && isDeeplyNestedType(target, targetStack, depth)) + expandingFlags |= 2 /* Target */; + var result = expandingFlags !== 3 /* Both */ ? structuredTypeRelatedTo(source, target, reportErrors, isIntersectionConstituent) : 1 /* Maybe */; + expandingFlags = saveExpandingFlags; + depth--; + if (result) { + if (result === -1 /* True */ || depth === 0) { + // If result is definitely true, record all maybe keys as having succeeded + for (var i = maybeStart; i < maybeCount; i++) { + relation.set(maybeKeys[i], 1 /* Succeeded */); + } + maybeCount = maybeStart; + } + } + else { + // A false result goes straight into global cache (when something is false under + // assumptions it will also be false without assumptions) + relation.set(id, reportErrors ? 3 /* FailedAndReported */ : 2 /* Failed */); + maybeCount = maybeStart; + } + return result; + } + function getConstraintForRelation(type) { + return relation === definitelyAssignableRelation ? undefined : getConstraintOfType(type); + } + function structuredTypeRelatedTo(source, target, reportErrors, isIntersectionConstituent) { + var flags = source.flags & target.flags; + if (relation === identityRelation && !(flags & 524288 /* Object */)) { + if (flags & 4194304 /* Index */) { + return isRelatedTo(source.type, target.type, /*reportErrors*/ false); + } + var result_2 = 0 /* False */; + if (flags & 8388608 /* IndexedAccess */) { + if (result_2 = isRelatedTo(source.objectType, target.objectType, /*reportErrors*/ false)) { + if (result_2 &= isRelatedTo(source.indexType, target.indexType, /*reportErrors*/ false)) { + return result_2; + } + } + } + if (flags & 16777216 /* Conditional */) { + if (source.root.isDistributive === target.root.isDistributive) { + if (result_2 = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) { + if (result_2 &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) { + if (result_2 &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), /*reportErrors*/ false)) { + if (result_2 &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), /*reportErrors*/ false)) { + return result_2; + } + } + } + } + } + } + if (flags & 33554432 /* Substitution */) { + return isRelatedTo(source.substitute, target.substitute, /*reportErrors*/ false); + } + return 0 /* False */; + } + var result; + var originalErrorInfo; + var saveErrorInfo = errorInfo; + // We limit alias variance probing to only object and conditional types since their alias behavior + // is more predictable than other, interned types, which may or may not have an alias depending on + // the order in which things were checked. + if (source.flags & (524288 /* Object */ | 16777216 /* Conditional */) && source.aliasSymbol && + source.aliasTypeArguments && source.aliasSymbol === target.aliasSymbol && + !(source.aliasTypeArgumentsContainsMarker || target.aliasTypeArgumentsContainsMarker)) { + var variances = getAliasVariances(source.aliasSymbol); + if (result = typeArgumentsRelatedTo(source.aliasTypeArguments, target.aliasTypeArguments, variances, reportErrors)) { + return result; + } + originalErrorInfo = errorInfo; + errorInfo = saveErrorInfo; + } + if (target.flags & 262144 /* TypeParameter */) { + // A source type { [P in Q]: X } is related to a target type T if keyof T is related to Q and X is related to T[Q]. + if (ts.getObjectFlags(source) & 32 /* Mapped */ && isRelatedTo(getIndexType(target), getConstraintTypeFromMappedType(source))) { + if (!(getMappedTypeModifiers(source) & 4 /* IncludeOptional */)) { + var templateType = getTemplateTypeFromMappedType(source); + var indexedAccessType = getIndexedAccessType(target, getTypeParameterFromMappedType(source)); + if (result = isRelatedTo(templateType, indexedAccessType, reportErrors)) { + return result; + } + } + } + } + else if (target.flags & 4194304 /* Index */) { + // A keyof S is related to a keyof T if T is related to S. + if (source.flags & 4194304 /* Index */) { + if (result = isRelatedTo(target.type, source.type, /*reportErrors*/ false)) { + return result; + } + } + // A type S is assignable to keyof T if S is assignable to keyof C, where C is the + // simplified form of T or, if T doesn't simplify, the constraint of T. + if (relation !== definitelyAssignableRelation) { + var simplified = getSimplifiedType(target.type); + var constraint = simplified !== target.type ? simplified : getConstraintOfType(target.type); + if (constraint) { + // We require Ternary.True here such that circular constraints don't cause + // false positives. For example, given 'T extends { [K in keyof T]: string }', + // 'keyof T' has itself as its constraint and produces a Ternary.Maybe when + // related to other types. + if (isRelatedTo(source, getIndexType(constraint, target.stringsOnly), reportErrors) === -1 /* True */) { + return -1 /* True */; + } + } + } + } + else if (target.flags & 8388608 /* IndexedAccess */) { + // A type S is related to a type T[K], where T and K aren't both type variables, if S is related to C, + // where C is the base constraint of T[K] + if (relation !== identityRelation && !(isGenericObjectType(target.objectType) && isGenericIndexType(target.indexType))) { + var constraint = getBaseConstraintOfType(target); + if (constraint && constraint !== target) { + if (result = isRelatedTo(source, constraint, reportErrors)) { + return result; + } + } + } + } + else if (isGenericMappedType(target)) { + // A source type T is related to a target type { [P in X]: T[P] } + var template = getTemplateTypeFromMappedType(target); + var modifiers = getMappedTypeModifiers(target); + if (!(modifiers & 8 /* ExcludeOptional */)) { + if (template.flags & 8388608 /* IndexedAccess */ && template.objectType === source && + template.indexType === getTypeParameterFromMappedType(target)) { + return -1 /* True */; + } + // A source type T is related to a target type { [P in Q]: X } if Q is related to keyof T and T[Q] is related to X. + if (!isGenericMappedType(source) && isRelatedTo(getConstraintTypeFromMappedType(target), getIndexType(source))) { + var indexedAccessType = getIndexedAccessType(source, getTypeParameterFromMappedType(target)); + var templateType = getTemplateTypeFromMappedType(target); + if (result = isRelatedTo(indexedAccessType, templateType, reportErrors)) { + return result; + } + } + originalErrorInfo = errorInfo; + errorInfo = saveErrorInfo; + } + } + if (source.flags & 8650752 /* TypeVariable */) { + if (source.flags & 8388608 /* IndexedAccess */ && target.flags & 8388608 /* IndexedAccess */) { + // A type S[K] is related to a type T[J] if S is related to T and K is related to J. + if (result = isRelatedTo(source.objectType, target.objectType, reportErrors)) { + result &= isRelatedTo(source.indexType, target.indexType, reportErrors); + } + if (result) { + errorInfo = saveErrorInfo; + return result; + } + } + var constraint = getConstraintForRelation(source); + if (!constraint || (source.flags & 262144 /* TypeParameter */ && constraint.flags & 3 /* AnyOrUnknown */)) { + // A type variable with no constraint is not related to the non-primitive object type. + if (result = isRelatedTo(emptyObjectType, extractTypesOfKind(target, ~67108864 /* NonPrimitive */))) { + errorInfo = saveErrorInfo; + return result; + } + } + // hi-speed no-this-instantiation check (less accurate, but avoids costly `this`-instantiation when the constraint will suffice), see #28231 for report on why this is needed + else if (result = isRelatedTo(constraint, target, /*reportErrors*/ false, /*headMessage*/ undefined, isIntersectionConstituent)) { + errorInfo = saveErrorInfo; + return result; + } + // slower, fuller, this-instantiated check (necessary when comparing raw `this` types from base classes), see `subclassWithPolymorphicThisIsAssignable.ts` test for example + else if (result = isRelatedTo(getTypeWithThisArgument(constraint, source), target, reportErrors, /*headMessage*/ undefined, isIntersectionConstituent)) { + errorInfo = saveErrorInfo; + return result; + } + } + else if (source.flags & 4194304 /* Index */) { + if (result = isRelatedTo(keyofConstraintType, target, reportErrors)) { + errorInfo = saveErrorInfo; + return result; + } + } + else if (source.flags & 16777216 /* Conditional */) { + if (target.flags & 16777216 /* Conditional */) { + // Two conditional types 'T1 extends U1 ? X1 : Y1' and 'T2 extends U2 ? X2 : Y2' are related if + // one of T1 and T2 is related to the other, U1 and U2 are identical types, X1 is related to X2, + // and Y1 is related to Y2. + if (isTypeIdenticalTo(source.extendsType, target.extendsType) && + (isRelatedTo(source.checkType, target.checkType) || isRelatedTo(target.checkType, source.checkType))) { + if (result = isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), reportErrors)) { + result &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), reportErrors); + } + if (result) { + errorInfo = saveErrorInfo; + return result; + } + } + } + else if (relation !== definitelyAssignableRelation) { + var distributiveConstraint = getConstraintOfDistributiveConditionalType(source); + if (distributiveConstraint) { + if (result = isRelatedTo(distributiveConstraint, target, reportErrors)) { + errorInfo = saveErrorInfo; + return result; + } + } + var defaultConstraint = getDefaultConstraintOfConditionalType(source); + if (defaultConstraint) { + if (result = isRelatedTo(defaultConstraint, target, reportErrors)) { + errorInfo = saveErrorInfo; + return result; + } + } + } + } + else { + // An empty object type is related to any mapped type that includes a '?' modifier. + if (isPartialMappedType(target) && !isGenericMappedType(source) && isEmptyObjectType(source)) { + return -1 /* True */; + } + if (isGenericMappedType(target)) { + if (isGenericMappedType(source)) { + if (result = mappedTypeRelatedTo(source, target, reportErrors)) { + errorInfo = saveErrorInfo; + return result; + } + } + return 0 /* False */; + } + if (relation === definitelyAssignableRelation && isGenericMappedType(source)) { + return 0 /* False */; + } + var sourceIsPrimitive = !!(source.flags & 131068 /* Primitive */); + if (relation !== identityRelation) { + source = getApparentType(source); + } + if (ts.getObjectFlags(source) & 4 /* Reference */ && ts.getObjectFlags(target) & 4 /* Reference */ && source.target === target.target && + !(ts.getObjectFlags(source) & 8192 /* MarkerType */ || ts.getObjectFlags(target) & 8192 /* MarkerType */)) { + // We have type references to the same generic type, and the type references are not marker + // type references (which are intended by be compared structurally). Obtain the variance + // information for the type parameters and relate the type arguments accordingly. + var variances = getVariances(source.target); + if (result = typeArgumentsRelatedTo(source.typeArguments, target.typeArguments, variances, reportErrors)) { + return result; + } + // The type arguments did not relate appropriately, but it may be because we have no variance + // information (in which case typeArgumentsRelatedTo defaulted to covariance for all type + // arguments). It might also be the case that the target type has a 'void' type argument for + // a covariant type parameter that is only used in return positions within the generic type + // (in which case any type argument is permitted on the source side). In those cases we proceed + // with a structural comparison. Otherwise, we know for certain the instantiations aren't + // related and we can return here. + if (variances !== ts.emptyArray && !hasCovariantVoidArgument(target, variances)) { + // In some cases generic types that are covariant in regular type checking mode become + // invariant in --strictFunctionTypes mode because one or more type parameters are used in + // both co- and contravariant positions. In order to make it easier to diagnose *why* such + // types are invariant, if any of the type parameters are invariant we reset the reported + // errors and instead force a structural comparison (which will include elaborations that + // reveal the reason). + if (!(reportErrors && ts.some(variances, function (v) { return v === 0 /* Invariant */; }))) { + return 0 /* False */; + } + // We remember the original error information so we can restore it in case the structural + // comparison unexpectedly succeeds. This can happen when the structural comparison result + // is a Ternary.Maybe for example caused by the recursion depth limiter. + originalErrorInfo = errorInfo; + errorInfo = saveErrorInfo; + } + } + else if (isTupleType(source) && (isArrayType(target) || isReadonlyArrayType(target)) || isArrayType(source) && isReadonlyArrayType(target)) { + return isRelatedTo(getIndexTypeOfType(source, 1 /* Number */) || anyType, getIndexTypeOfType(target, 1 /* Number */) || anyType, reportErrors); + } + // Even if relationship doesn't hold for unions, intersections, or generic type references, + // it may hold in a structural comparison. + // In a check of the form X = A & B, we will have previously checked if A relates to X or B relates + // to X. Failing both of those we want to check if the aggregation of A and B's members structurally + // relates to X. Thus, we include intersection types on the source side here. + if (source.flags & (524288 /* Object */ | 2097152 /* Intersection */) && target.flags & 524288 /* Object */) { + // Report structural errors only if we haven't reported any errors yet + var reportStructuralErrors = reportErrors && errorInfo === saveErrorInfo && !sourceIsPrimitive; + result = propertiesRelatedTo(source, target, reportStructuralErrors); + if (result) { + result &= signaturesRelatedTo(source, target, 0 /* Call */, reportStructuralErrors); + if (result) { + result &= signaturesRelatedTo(source, target, 1 /* Construct */, reportStructuralErrors); + if (result) { + result &= indexTypesRelatedTo(source, target, 0 /* String */, sourceIsPrimitive, reportStructuralErrors); + if (result) { + result &= indexTypesRelatedTo(source, target, 1 /* Number */, sourceIsPrimitive, reportStructuralErrors); + } + } + } + } + if (result) { + if (!originalErrorInfo) { + errorInfo = saveErrorInfo; + return result; + } + errorInfo = originalErrorInfo; + } + } + } + return 0 /* False */; + } + // A type [P in S]: X is related to a type [Q in T]: Y if T is related to S and X' is + // related to Y, where X' is an instantiation of X in which P is replaced with Q. Notice + // that S and T are contra-variant whereas X and Y are co-variant. + function mappedTypeRelatedTo(source, target, reportErrors) { + var modifiersRelated = relation === comparableRelation || (relation === identityRelation ? getMappedTypeModifiers(source) === getMappedTypeModifiers(target) : + getCombinedMappedTypeOptionality(source) <= getCombinedMappedTypeOptionality(target)); + if (modifiersRelated) { + var result_3; + if (result_3 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) { + var mapper = createTypeMapper([getTypeParameterFromMappedType(source)], [getTypeParameterFromMappedType(target)]); + return result_3 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); + } + } + return 0 /* False */; + } + function propertiesRelatedTo(source, target, reportErrors) { + if (relation === identityRelation) { + return propertiesIdenticalTo(source, target); + } + var requireOptionalProperties = relation === subtypeRelation && !isObjectLiteralType(source) && !isEmptyArrayLiteralType(source) && !isTupleType(source); + var unmatchedProperty = getUnmatchedProperty(source, target, requireOptionalProperties); + if (unmatchedProperty) { + if (reportErrors) { + var props = ts.arrayFrom(getUnmatchedProperties(source, target, requireOptionalProperties)); + if (!headMessage || (headMessage.code !== ts.Diagnostics.Class_0_incorrectly_implements_interface_1.code && + headMessage.code !== ts.Diagnostics.Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass.code)) { + suppressNextError = true; // Retain top-level error for interface implementing issues, otherwise omit it + } + if (props.length === 1) { + var propName = symbolToString(unmatchedProperty); + reportError(ts.Diagnostics.Property_0_is_missing_in_type_1_but_required_in_type_2, propName, typeToString(source), typeToString(target)); + if (ts.length(unmatchedProperty.declarations)) { + associateRelatedInfo(ts.createDiagnosticForNode(unmatchedProperty.declarations[0], ts.Diagnostics._0_is_declared_here, propName)); + } + } + else if (props.length > 5) { // arbitrary cutoff for too-long list form + reportError(ts.Diagnostics.Type_0_is_missing_the_following_properties_from_type_1_Colon_2_and_3_more, typeToString(source), typeToString(target), ts.map(props.slice(0, 4), function (p) { return symbolToString(p); }).join(", "), props.length - 4); + } + else { + reportError(ts.Diagnostics.Type_0_is_missing_the_following_properties_from_type_1_Colon_2, typeToString(source), typeToString(target), ts.map(props, function (p) { return symbolToString(p); }).join(", ")); + } + } + return 0 /* False */; + } + if (isObjectLiteralType(target)) { + for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) { + var sourceProp = _a[_i]; + if (!getPropertyOfObjectType(target, sourceProp.escapedName)) { + var sourceType = getTypeOfSymbol(sourceProp); + if (!(sourceType === undefinedType || sourceType === undefinedWideningType)) { + if (reportErrors) { + reportError(ts.Diagnostics.Property_0_does_not_exist_on_type_1, symbolToString(sourceProp), typeToString(target)); + } + return 0 /* False */; + } + } + } + } + var result = -1 /* True */; + if (isTupleType(target)) { + var targetRestType = getRestTypeOfTupleType(target); + if (targetRestType) { + if (!isTupleType(source)) { + return 0 /* False */; + } + var sourceRestType = getRestTypeOfTupleType(source); + if (sourceRestType && !isRelatedTo(sourceRestType, targetRestType, reportErrors)) { + if (reportErrors) { + reportError(ts.Diagnostics.Rest_signatures_are_incompatible); + } + return 0 /* False */; + } + var targetCount = getTypeReferenceArity(target) - 1; + var sourceCount = getTypeReferenceArity(source) - (sourceRestType ? 1 : 0); + for (var i = targetCount; i < sourceCount; i++) { + var related = isRelatedTo(source.typeArguments[i], targetRestType, reportErrors); + if (!related) { + if (reportErrors) { + reportError(ts.Diagnostics.Property_0_is_incompatible_with_rest_element_type, "" + i); + } + return 0 /* False */; + } + result &= related; + } + } + } + var properties = getPropertiesOfObjectType(target); + for (var _b = 0, properties_2 = properties; _b < properties_2.length; _b++) { + var targetProp = properties_2[_b]; + if (!(targetProp.flags & 4194304 /* Prototype */)) { + var sourceProp = getPropertyOfType(source, targetProp.escapedName); + if (sourceProp && sourceProp !== targetProp) { + if (isIgnoredJsxProperty(source, sourceProp, getTypeOfSymbol(targetProp))) { + continue; + } + var sourcePropFlags = ts.getDeclarationModifierFlagsFromSymbol(sourceProp); + var targetPropFlags = ts.getDeclarationModifierFlagsFromSymbol(targetProp); + if (sourcePropFlags & 8 /* Private */ || targetPropFlags & 8 /* Private */) { + var hasDifferingDeclarations = sourceProp.valueDeclaration !== targetProp.valueDeclaration; + if (ts.getCheckFlags(sourceProp) & 256 /* ContainsPrivate */ && hasDifferingDeclarations) { + if (reportErrors) { + reportError(ts.Diagnostics.Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1, symbolToString(sourceProp), typeToString(source)); + } + return 0 /* False */; + } + if (hasDifferingDeclarations) { + if (reportErrors) { + if (sourcePropFlags & 8 /* Private */ && targetPropFlags & 8 /* Private */) { + reportError(ts.Diagnostics.Types_have_separate_declarations_of_a_private_property_0, symbolToString(targetProp)); + } + else { + reportError(ts.Diagnostics.Property_0_is_private_in_type_1_but_not_in_type_2, symbolToString(targetProp), typeToString(sourcePropFlags & 8 /* Private */ ? source : target), typeToString(sourcePropFlags & 8 /* Private */ ? target : source)); + } + } + return 0 /* False */; + } + } + else if (targetPropFlags & 16 /* Protected */) { + if (!isValidOverrideOf(sourceProp, targetProp)) { + if (reportErrors) { + reportError(ts.Diagnostics.Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2, symbolToString(targetProp), typeToString(getDeclaringClass(sourceProp) || source), typeToString(getDeclaringClass(targetProp) || target)); + } + return 0 /* False */; + } + } + else if (sourcePropFlags & 16 /* Protected */) { + if (reportErrors) { + reportError(ts.Diagnostics.Property_0_is_protected_in_type_1_but_public_in_type_2, symbolToString(targetProp), typeToString(source), typeToString(target)); + } + return 0 /* False */; + } + var related = isRelatedTo(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp), reportErrors); + if (!related) { + if (reportErrors) { + reportError(ts.Diagnostics.Types_of_property_0_are_incompatible, symbolToString(targetProp)); + } + return 0 /* False */; + } + result &= related; + // When checking for comparability, be more lenient with optional properties. + if (relation !== comparableRelation && sourceProp.flags & 16777216 /* Optional */ && !(targetProp.flags & 16777216 /* Optional */)) { + // TypeScript 1.0 spec (April 2014): 3.8.3 + // S is a subtype of a type T, and T is a supertype of S if ... + // S' and T are object types and, for each member M in T.. + // M is a property and S' contains a property N where + // if M is a required property, N is also a required property + // (M - property in T) + // (N - property in S) + if (reportErrors) { + reportError(ts.Diagnostics.Property_0_is_optional_in_type_1_but_required_in_type_2, symbolToString(targetProp), typeToString(source), typeToString(target)); + } + return 0 /* False */; + } + } + } + } + return result; + } + function propertiesIdenticalTo(source, target) { + if (!(source.flags & 524288 /* Object */ && target.flags & 524288 /* Object */)) { + return 0 /* False */; + } + var sourceProperties = getPropertiesOfObjectType(source); + var targetProperties = getPropertiesOfObjectType(target); + if (sourceProperties.length !== targetProperties.length) { + return 0 /* False */; + } + var result = -1 /* True */; + for (var _i = 0, sourceProperties_1 = sourceProperties; _i < sourceProperties_1.length; _i++) { + var sourceProp = sourceProperties_1[_i]; + var targetProp = getPropertyOfObjectType(target, sourceProp.escapedName); + if (!targetProp) { + return 0 /* False */; + } + var related = compareProperties(sourceProp, targetProp, isRelatedTo); + if (!related) { + return 0 /* False */; + } + result &= related; + } + return result; + } + function signaturesRelatedTo(source, target, kind, reportErrors) { + if (relation === identityRelation) { + return signaturesIdenticalTo(source, target, kind); + } + if (target === anyFunctionType || source === anyFunctionType) { + return -1 /* True */; + } + var sourceIsJSConstructor = source.symbol && isJSConstructor(source.symbol.valueDeclaration); + var targetIsJSConstructor = target.symbol && isJSConstructor(target.symbol.valueDeclaration); + var sourceSignatures = getSignaturesOfType(source, (sourceIsJSConstructor && kind === 1 /* Construct */) ? + 0 /* Call */ : kind); + var targetSignatures = getSignaturesOfType(target, (targetIsJSConstructor && kind === 1 /* Construct */) ? + 0 /* Call */ : kind); + if (kind === 1 /* Construct */ && sourceSignatures.length && targetSignatures.length) { + if (ts.isAbstractConstructorType(source) && !ts.isAbstractConstructorType(target)) { + // An abstract constructor type is not assignable to a non-abstract constructor type + // as it would otherwise be possible to new an abstract class. Note that the assignability + // check we perform for an extends clause excludes construct signatures from the target, + // so this check never proceeds. + if (reportErrors) { + reportError(ts.Diagnostics.Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type); + } + return 0 /* False */; + } + if (!constructorVisibilitiesAreCompatible(sourceSignatures[0], targetSignatures[0], reportErrors)) { + return 0 /* False */; + } + } + var result = -1 /* True */; + var saveErrorInfo = errorInfo; + if (ts.getObjectFlags(source) & 64 /* Instantiated */ && ts.getObjectFlags(target) & 64 /* Instantiated */ && source.symbol === target.symbol) { + // We have instantiations of the same anonymous type (which typically will be the type of a + // method). Simply do a pairwise comparison of the signatures in the two signature lists instead + // of the much more expensive N * M comparison matrix we explore below. We erase type parameters + // as they are known to always be the same. + for (var i = 0; i < targetSignatures.length; i++) { + var related = signatureRelatedTo(sourceSignatures[i], targetSignatures[i], /*erase*/ true, reportErrors); + if (!related) { + return 0 /* False */; + } + result &= related; + } + } + else if (sourceSignatures.length === 1 && targetSignatures.length === 1) { + // For simple functions (functions with a single signature) we only erase type parameters for + // the comparable relation. Otherwise, if the source signature is generic, we instantiate it + // in the context of the target signature before checking the relationship. Ideally we'd do + // this regardless of the number of signatures, but the potential costs are prohibitive due + // to the quadratic nature of the logic below. + var eraseGenerics = relation === comparableRelation || !!compilerOptions.noStrictGenericChecks; + result = signatureRelatedTo(sourceSignatures[0], targetSignatures[0], eraseGenerics, reportErrors); + } + else { + outer: for (var _i = 0, targetSignatures_1 = targetSignatures; _i < targetSignatures_1.length; _i++) { + var t = targetSignatures_1[_i]; + // Only elaborate errors from the first failure + var shouldElaborateErrors = reportErrors; + for (var _a = 0, sourceSignatures_1 = sourceSignatures; _a < sourceSignatures_1.length; _a++) { + var s = sourceSignatures_1[_a]; + var related = signatureRelatedTo(s, t, /*erase*/ true, shouldElaborateErrors); + if (related) { + result &= related; + errorInfo = saveErrorInfo; + continue outer; + } + shouldElaborateErrors = false; + } + if (shouldElaborateErrors) { + reportError(ts.Diagnostics.Type_0_provides_no_match_for_the_signature_1, typeToString(source), signatureToString(t, /*enclosingDeclaration*/ undefined, /*flags*/ undefined, kind)); + } + return 0 /* False */; + } + } + return result; + } + /** + * See signatureAssignableTo, compareSignaturesIdentical + */ + function signatureRelatedTo(source, target, erase, reportErrors) { + return compareSignaturesRelated(erase ? getErasedSignature(source) : source, erase ? getErasedSignature(target) : target, 0 /* None */, /*ignoreReturnTypes*/ false, reportErrors, reportError, isRelatedTo); + } + function signaturesIdenticalTo(source, target, kind) { + var sourceSignatures = getSignaturesOfType(source, kind); + var targetSignatures = getSignaturesOfType(target, kind); + if (sourceSignatures.length !== targetSignatures.length) { + return 0 /* False */; + } + var result = -1 /* True */; + for (var i = 0; i < sourceSignatures.length; i++) { + var related = compareSignaturesIdentical(sourceSignatures[i], targetSignatures[i], /*partialMatch*/ false, /*ignoreThisTypes*/ false, /*ignoreReturnTypes*/ false, isRelatedTo); + if (!related) { + return 0 /* False */; + } + result &= related; + } + return result; + } + function eachPropertyRelatedTo(source, target, kind, reportErrors) { + var result = -1 /* True */; + for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) { + var prop = _a[_i]; + if (isIgnoredJsxProperty(source, prop, /*targetMemberType*/ undefined)) { + continue; + } + // Skip over symbol-named members + if (prop.nameType && prop.nameType.flags & 8192 /* UniqueESSymbol */) { + continue; + } + if (kind === 0 /* String */ || isNumericLiteralName(prop.escapedName)) { + var related = isRelatedTo(getTypeOfSymbol(prop), target, reportErrors); + if (!related) { + if (reportErrors) { + reportError(ts.Diagnostics.Property_0_is_incompatible_with_index_signature, symbolToString(prop)); + } + return 0 /* False */; + } + result &= related; + } + } + return result; + } + function indexInfoRelatedTo(sourceInfo, targetInfo, reportErrors) { + var related = isRelatedTo(sourceInfo.type, targetInfo.type, reportErrors); + if (!related && reportErrors) { + reportError(ts.Diagnostics.Index_signatures_are_incompatible); + } + return related; + } + function indexTypesRelatedTo(source, target, kind, sourceIsPrimitive, reportErrors) { + if (relation === identityRelation) { + return indexTypesIdenticalTo(source, target, kind); + } + var targetInfo = getIndexInfoOfType(target, kind); + if (!targetInfo || targetInfo.type.flags & 3 /* AnyOrUnknown */ && !sourceIsPrimitive) { + // Index signature of type any permits assignment from everything but primitives + return -1 /* True */; + } + var sourceInfo = getIndexInfoOfType(source, kind) || + kind === 1 /* Number */ && getIndexInfoOfType(source, 0 /* String */); + if (sourceInfo) { + return indexInfoRelatedTo(sourceInfo, targetInfo, reportErrors); + } + if (isGenericMappedType(source)) { + // A generic mapped type { [P in K]: T } is related to an index signature { [x: string]: U } + // if T is related to U. + return (kind === 0 /* String */ && isRelatedTo(getTemplateTypeFromMappedType(source), targetInfo.type, reportErrors)); // TODO: GH#18217 + } + if (isObjectTypeWithInferableIndex(source)) { + var related = -1 /* True */; + if (kind === 0 /* String */) { + var sourceNumberInfo = getIndexInfoOfType(source, 1 /* Number */); + if (sourceNumberInfo) { + related = indexInfoRelatedTo(sourceNumberInfo, targetInfo, reportErrors); + } + } + if (related) { + related &= eachPropertyRelatedTo(source, targetInfo.type, kind, reportErrors); + } + return related; + } + if (reportErrors) { + reportError(ts.Diagnostics.Index_signature_is_missing_in_type_0, typeToString(source)); + } + return 0 /* False */; + } + function indexTypesIdenticalTo(source, target, indexKind) { + var targetInfo = getIndexInfoOfType(target, indexKind); + var sourceInfo = getIndexInfoOfType(source, indexKind); + if (!sourceInfo && !targetInfo) { + return -1 /* True */; + } + if (sourceInfo && targetInfo && sourceInfo.isReadonly === targetInfo.isReadonly) { + return isRelatedTo(sourceInfo.type, targetInfo.type); + } + return 0 /* False */; + } + function constructorVisibilitiesAreCompatible(sourceSignature, targetSignature, reportErrors) { + if (!sourceSignature.declaration || !targetSignature.declaration) { + return true; + } + var sourceAccessibility = ts.getSelectedModifierFlags(sourceSignature.declaration, 24 /* NonPublicAccessibilityModifier */); + var targetAccessibility = ts.getSelectedModifierFlags(targetSignature.declaration, 24 /* NonPublicAccessibilityModifier */); + // A public, protected and private signature is assignable to a private signature. + if (targetAccessibility === 8 /* Private */) { + return true; + } + // A public and protected signature is assignable to a protected signature. + if (targetAccessibility === 16 /* Protected */ && sourceAccessibility !== 8 /* Private */) { + return true; + } + // Only a public signature is assignable to public signature. + if (targetAccessibility !== 16 /* Protected */ && !sourceAccessibility) { + return true; + } + if (reportErrors) { + reportError(ts.Diagnostics.Cannot_assign_a_0_constructor_type_to_a_1_constructor_type, visibilityToString(sourceAccessibility), visibilityToString(targetAccessibility)); + } + return false; + } + } + function discriminateTypeByDiscriminableItems(target, discriminators, related, defaultValue) { + var match; + for (var _i = 0, discriminators_1 = discriminators; _i < discriminators_1.length; _i++) { + var _a = discriminators_1[_i], getDiscriminatingType = _a[0], propertyName = _a[1]; + for (var _b = 0, _c = target.types; _b < _c.length; _b++) { + var type = _c[_b]; + var targetType = getTypeOfPropertyOfType(type, propertyName); + if (targetType && related(getDiscriminatingType(), targetType)) { + if (match) { + if (type === match) + continue; // Finding multiple fields which discriminate to the same type is fine + return defaultValue; + } + match = type; + } + } + } + return match || defaultValue; + } + /** + * A type is 'weak' if it is an object type with at least one optional property + * and no required properties, call/construct signatures or index signatures + */ + function isWeakType(type) { + if (type.flags & 524288 /* Object */) { + var resolved = resolveStructuredTypeMembers(type); + return resolved.callSignatures.length === 0 && resolved.constructSignatures.length === 0 && + !resolved.stringIndexInfo && !resolved.numberIndexInfo && + resolved.properties.length > 0 && + ts.every(resolved.properties, function (p) { return !!(p.flags & 16777216 /* Optional */); }); + } + if (type.flags & 2097152 /* Intersection */) { + return ts.every(type.types, isWeakType); + } + return false; + } + function hasCommonProperties(source, target, isComparingJsxAttributes) { + for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) { + var prop = _a[_i]; + if (isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { + return true; + } + } + return false; + } + // Return a type reference where the source type parameter is replaced with the target marker + // type, and flag the result as a marker type reference. + function getMarkerTypeReference(type, source, target) { + var result = createTypeReference(type, ts.map(type.typeParameters, function (t) { return t === source ? target : t; })); + result.objectFlags |= 8192 /* MarkerType */; + return result; + } + function getAliasVariances(symbol) { + var links = getSymbolLinks(symbol); + return getVariancesWorker(links.typeParameters, links, function (_links, param, marker) { + var type = getTypeAliasInstantiation(symbol, instantiateTypes(links.typeParameters, makeUnaryTypeMapper(param, marker))); + type.aliasTypeArgumentsContainsMarker = true; + return type; + }); + } + // Return an array containing the variance of each type parameter. The variance is effectively + // a digest of the type comparisons that occur for each type argument when instantiations of the + // generic type are structurally compared. We infer the variance information by comparing + // instantiations of the generic type for type arguments with known relations. The function + // returns the emptyArray singleton if we're not in strictFunctionTypes mode or if the function + // has been invoked recursively for the given generic type. + function getVariancesWorker(typeParameters, cache, createMarkerType) { + if (typeParameters === void 0) { typeParameters = ts.emptyArray; } + var variances = cache.variances; + if (!variances) { + // The emptyArray singleton is used to signal a recursive invocation. + cache.variances = ts.emptyArray; + variances = []; + for (var _i = 0, typeParameters_1 = typeParameters; _i < typeParameters_1.length; _i++) { + var tp = typeParameters_1[_i]; + // We first compare instantiations where the type parameter is replaced with + // marker types that have a known subtype relationship. From this we can infer + // invariance, covariance, contravariance or bivariance. + var typeWithSuper = createMarkerType(cache, tp, markerSuperType); + var typeWithSub = createMarkerType(cache, tp, markerSubType); + var variance = (isTypeAssignableTo(typeWithSub, typeWithSuper) ? 1 /* Covariant */ : 0) | + (isTypeAssignableTo(typeWithSuper, typeWithSub) ? 2 /* Contravariant */ : 0); + // If the instantiations appear to be related bivariantly it may be because the + // type parameter is independent (i.e. it isn't witnessed anywhere in the generic + // type). To determine this we compare instantiations where the type parameter is + // replaced with marker types that are known to be unrelated. + if (variance === 3 /* Bivariant */ && isTypeAssignableTo(createMarkerType(cache, tp, markerOtherType), typeWithSuper)) { + variance = 4 /* Independent */; + } + variances.push(variance); + } + cache.variances = variances; + } + return variances; + } + function getVariances(type) { + if (!strictFunctionTypes) { + return ts.emptyArray; + } + if (type === globalArrayType || type === globalReadonlyArrayType) { + // Arrays are known to be covariant, no need to spend time computing this (emptyArray implies covariance for all parameters) + return ts.emptyArray; + } + return getVariancesWorker(type.typeParameters, type, getMarkerTypeReference); + } + // Return true if the given type reference has a 'void' type argument for a covariant type parameter. + // See comment at call in recursiveTypeRelatedTo for when this case matters. + function hasCovariantVoidArgument(type, variances) { + for (var i = 0; i < variances.length; i++) { + if (variances[i] === 1 /* Covariant */ && type.typeArguments[i].flags & 16384 /* Void */) { + return true; + } + } + return false; + } + function isUnconstrainedTypeParameter(type) { + return type.flags & 262144 /* TypeParameter */ && !getConstraintOfTypeParameter(type); + } + function isTypeReferenceWithGenericArguments(type) { + return !!(ts.getObjectFlags(type) & 4 /* Reference */) && ts.some(type.typeArguments, function (t) { return isUnconstrainedTypeParameter(t) || isTypeReferenceWithGenericArguments(t); }); + } + /** + * getTypeReferenceId(A) returns "111=0-12=1" + * where A.id=111 and number.id=12 + */ + function getTypeReferenceId(type, typeParameters, depth) { + if (depth === void 0) { depth = 0; } + var result = "" + type.target.id; + for (var _i = 0, _a = type.typeArguments; _i < _a.length; _i++) { + var t = _a[_i]; + if (isUnconstrainedTypeParameter(t)) { + var index = typeParameters.indexOf(t); + if (index < 0) { + index = typeParameters.length; + typeParameters.push(t); + } + result += "=" + index; + } + else if (depth < 4 && isTypeReferenceWithGenericArguments(t)) { + result += "<" + getTypeReferenceId(t, typeParameters, depth + 1) + ">"; + } + else { + result += "-" + t.id; + } + } + return result; + } + /** + * To improve caching, the relation key for two generic types uses the target's id plus ids of the type parameters. + * For other cases, the types ids are used. + */ + function getRelationKey(source, target, relation) { + if (relation === identityRelation && source.id > target.id) { + var temp = source; + source = target; + target = temp; + } + if (isTypeReferenceWithGenericArguments(source) && isTypeReferenceWithGenericArguments(target)) { + var typeParameters = []; + return getTypeReferenceId(source, typeParameters) + "," + getTypeReferenceId(target, typeParameters); + } + return source.id + "," + target.id; + } + // Invoke the callback for each underlying property symbol of the given symbol and return the first + // value that isn't undefined. + function forEachProperty(prop, callback) { + if (ts.getCheckFlags(prop) & 6 /* Synthetic */) { + for (var _i = 0, _a = prop.containingType.types; _i < _a.length; _i++) { + var t = _a[_i]; + var p = getPropertyOfType(t, prop.escapedName); + var result = p && forEachProperty(p, callback); + if (result) { + return result; + } + } + return undefined; + } + return callback(prop); + } + // Return the declaring class type of a property or undefined if property not declared in class + function getDeclaringClass(prop) { + return prop.parent && prop.parent.flags & 32 /* Class */ ? getDeclaredTypeOfSymbol(getParentOfSymbol(prop)) : undefined; + } + // Return true if some underlying source property is declared in a class that derives + // from the given base class. + function isPropertyInClassDerivedFrom(prop, baseClass) { + return forEachProperty(prop, function (sp) { + var sourceClass = getDeclaringClass(sp); + return sourceClass ? hasBaseType(sourceClass, baseClass) : false; + }); + } + // Return true if source property is a valid override of protected parts of target property. + function isValidOverrideOf(sourceProp, targetProp) { + return !forEachProperty(targetProp, function (tp) { return ts.getDeclarationModifierFlagsFromSymbol(tp) & 16 /* Protected */ ? + !isPropertyInClassDerivedFrom(sourceProp, getDeclaringClass(tp)) : false; }); + } + // Return true if the given class derives from each of the declaring classes of the protected + // constituents of the given property. + function isClassDerivedFromDeclaringClasses(checkClass, prop) { + return forEachProperty(prop, function (p) { return ts.getDeclarationModifierFlagsFromSymbol(p) & 16 /* Protected */ ? + !hasBaseType(checkClass, getDeclaringClass(p)) : false; }) ? undefined : checkClass; + } + // Return true if the given type is deeply nested. We consider this to be the case when structural type comparisons + // for 5 or more occurrences or instantiations of the type have been recorded on the given stack. It is possible, + // though highly unlikely, for this test to be true in a situation where a chain of instantiations is not infinitely + // expanding. Effectively, we will generate a false positive when two types are structurally equal to at least 5 + // levels, but unequal at some level beyond that. + function isDeeplyNestedType(type, stack, depth) { + // We track all object types that have an associated symbol (representing the origin of the type) + if (depth >= 5 && type.flags & 524288 /* Object */) { + var symbol = type.symbol; + if (symbol) { + var count = 0; + for (var i = 0; i < depth; i++) { + var t = stack[i]; + if (t.flags & 524288 /* Object */ && t.symbol === symbol) { + count++; + if (count >= 5) + return true; + } + } + } + } + return false; + } + function isPropertyIdenticalTo(sourceProp, targetProp) { + return compareProperties(sourceProp, targetProp, compareTypesIdentical) !== 0 /* False */; + } + function compareProperties(sourceProp, targetProp, compareTypes) { + // Two members are considered identical when + // - they are public properties with identical names, optionality, and types, + // - they are private or protected properties originating in the same declaration and having identical types + if (sourceProp === targetProp) { + return -1 /* True */; + } + var sourcePropAccessibility = ts.getDeclarationModifierFlagsFromSymbol(sourceProp) & 24 /* NonPublicAccessibilityModifier */; + var targetPropAccessibility = ts.getDeclarationModifierFlagsFromSymbol(targetProp) & 24 /* NonPublicAccessibilityModifier */; + if (sourcePropAccessibility !== targetPropAccessibility) { + return 0 /* False */; + } + if (sourcePropAccessibility) { + if (getTargetSymbol(sourceProp) !== getTargetSymbol(targetProp)) { + return 0 /* False */; + } + } + else { + if ((sourceProp.flags & 16777216 /* Optional */) !== (targetProp.flags & 16777216 /* Optional */)) { + return 0 /* False */; + } + } + if (isReadonlySymbol(sourceProp) !== isReadonlySymbol(targetProp)) { + return 0 /* False */; + } + return compareTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); + } + function isMatchingSignature(source, target, partialMatch) { + var sourceParameterCount = getParameterCount(source); + var targetParameterCount = getParameterCount(target); + var sourceMinArgumentCount = getMinArgumentCount(source); + var targetMinArgumentCount = getMinArgumentCount(target); + var sourceHasRestParameter = hasEffectiveRestParameter(source); + var targetHasRestParameter = hasEffectiveRestParameter(target); + // A source signature matches a target signature if the two signatures have the same number of required, + // optional, and rest parameters. + if (sourceParameterCount === targetParameterCount && + sourceMinArgumentCount === targetMinArgumentCount && + sourceHasRestParameter === targetHasRestParameter) { + return true; + } + // A source signature partially matches a target signature if the target signature has no fewer required + // parameters + if (partialMatch && sourceMinArgumentCount <= targetMinArgumentCount) { + return true; + } + return false; + } + /** + * See signatureRelatedTo, compareSignaturesIdentical + */ + function compareSignaturesIdentical(source, target, partialMatch, ignoreThisTypes, ignoreReturnTypes, compareTypes) { + // TODO (drosen): De-duplicate code between related functions. + if (source === target) { + return -1 /* True */; + } + if (!(isMatchingSignature(source, target, partialMatch))) { + return 0 /* False */; + } + // Check that the two signatures have the same number of type parameters. We might consider + // also checking that any type parameter constraints match, but that would require instantiating + // the constraints with a common set of type arguments to get relatable entities in places where + // type parameters occur in the constraints. The complexity of doing that doesn't seem worthwhile, + // particularly as we're comparing erased versions of the signatures below. + if (ts.length(source.typeParameters) !== ts.length(target.typeParameters)) { + return 0 /* False */; + } + // Spec 1.0 Section 3.8.3 & 3.8.4: + // M and N (the signatures) are instantiated using type Any as the type argument for all type parameters declared by M and N + source = getErasedSignature(source); + target = getErasedSignature(target); + var result = -1 /* True */; + if (!ignoreThisTypes) { + var sourceThisType = getThisTypeOfSignature(source); + if (sourceThisType) { + var targetThisType = getThisTypeOfSignature(target); + if (targetThisType) { + var related = compareTypes(sourceThisType, targetThisType); + if (!related) { + return 0 /* False */; + } + result &= related; + } + } + } + var targetLen = getParameterCount(target); + for (var i = 0; i < targetLen; i++) { + var s = getTypeAtPosition(source, i); + var t = getTypeAtPosition(target, i); + var related = compareTypes(t, s); + if (!related) { + return 0 /* False */; + } + result &= related; + } + if (!ignoreReturnTypes) { + var sourceTypePredicate = getTypePredicateOfSignature(source); + var targetTypePredicate = getTypePredicateOfSignature(target); + result &= sourceTypePredicate !== undefined || targetTypePredicate !== undefined + ? compareTypePredicatesIdentical(sourceTypePredicate, targetTypePredicate, compareTypes) + // If they're both type predicates their return types will both be `boolean`, so no need to compare those. + : compareTypes(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target)); + } + return result; + } + function compareTypePredicatesIdentical(source, target, compareTypes) { + return source === undefined || target === undefined || !typePredicateKindsMatch(source, target) ? 0 /* False */ : compareTypes(source.type, target.type); + } + function literalTypesWithSameBaseType(types) { + var commonBaseType; + for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { + var t = types_8[_i]; + var baseType = getBaseTypeOfLiteralType(t); + if (!commonBaseType) { + commonBaseType = baseType; + } + if (baseType === t || baseType !== commonBaseType) { + return false; + } + } + return true; + } + // When the candidate types are all literal types with the same base type, return a union + // of those literal types. Otherwise, return the leftmost type for which no type to the + // right is a supertype. + function getSupertypeOrUnion(types) { + return literalTypesWithSameBaseType(types) ? + getUnionType(types) : + ts.reduceLeft(types, function (s, t) { return isTypeSubtypeOf(s, t) ? t : s; }); + } + function getCommonSupertype(types) { + if (!strictNullChecks) { + return getSupertypeOrUnion(types); + } + var primaryTypes = ts.filter(types, function (t) { return !(t.flags & 98304 /* Nullable */); }); + return primaryTypes.length ? + getNullableType(getSupertypeOrUnion(primaryTypes), getFalsyFlagsOfTypes(types) & 98304 /* Nullable */) : + getUnionType(types, 2 /* Subtype */); + } + // Return the leftmost type for which no type to the right is a subtype. + function getCommonSubtype(types) { + return ts.reduceLeft(types, function (s, t) { return isTypeSubtypeOf(t, s) ? t : s; }); + } + function isArrayType(type) { + return !!(ts.getObjectFlags(type) & 4 /* Reference */) && type.target === globalArrayType; + } + function isReadonlyArrayType(type) { + return !!(ts.getObjectFlags(type) & 4 /* Reference */) && type.target === globalReadonlyArrayType; + } + function getElementTypeOfArrayType(type) { + return isArrayType(type) && type.typeArguments ? type.typeArguments[0] : undefined; + } + function isArrayLikeType(type) { + // A type is array-like if it is a reference to the global Array or global ReadonlyArray type, + // or if it is not the undefined or null type and if it is assignable to ReadonlyArray + return ts.getObjectFlags(type) & 4 /* Reference */ && (type.target === globalArrayType || type.target === globalReadonlyArrayType) || + !(type.flags & 98304 /* Nullable */) && isTypeAssignableTo(type, anyReadonlyArrayType); + } + function isEmptyArrayLiteralType(type) { + var elementType = isArrayType(type) ? type.typeArguments[0] : undefined; + return elementType === undefinedWideningType || elementType === implicitNeverType; + } + function isTupleLikeType(type) { + return isTupleType(type) || !!getPropertyOfType(type, "0"); + } + function getTupleElementType(type, index) { + var propType = getTypeOfPropertyOfType(type, "" + index); + if (propType) { + return propType; + } + if (everyType(type, isTupleType) && !everyType(type, function (t) { return !t.target.hasRestElement; })) { + return mapType(type, function (t) { return getRestTypeOfTupleType(t) || undefinedType; }); + } + return undefined; + } + function isNeitherUnitTypeNorNever(type) { + return !(type.flags & (109440 /* Unit */ | 131072 /* Never */)); + } + function isUnitType(type) { + return !!(type.flags & 109440 /* Unit */); + } + function isLiteralType(type) { + return type.flags & 16 /* Boolean */ ? true : + type.flags & 1048576 /* Union */ ? type.flags & 1024 /* EnumLiteral */ ? true : ts.every(type.types, isUnitType) : + isUnitType(type); + } + function getBaseTypeOfLiteralType(type) { + return type.flags & 1024 /* EnumLiteral */ ? getBaseTypeOfEnumLiteralType(type) : + type.flags & 128 /* StringLiteral */ ? stringType : + type.flags & 256 /* NumberLiteral */ ? numberType : + type.flags & 2048 /* BigIntLiteral */ ? bigintType : + type.flags & 512 /* BooleanLiteral */ ? booleanType : + type.flags & 1048576 /* Union */ ? getUnionType(ts.sameMap(type.types, getBaseTypeOfLiteralType)) : + type; + } + function getWidenedLiteralType(type) { + return type.flags & 1024 /* EnumLiteral */ && isFreshLiteralType(type) ? getBaseTypeOfEnumLiteralType(type) : + type.flags & 128 /* StringLiteral */ && isFreshLiteralType(type) ? stringType : + type.flags & 256 /* NumberLiteral */ && isFreshLiteralType(type) ? numberType : + type.flags & 2048 /* BigIntLiteral */ && isFreshLiteralType(type) ? bigintType : + type.flags & 512 /* BooleanLiteral */ && isFreshLiteralType(type) ? booleanType : + type.flags & 1048576 /* Union */ ? getUnionType(ts.sameMap(type.types, getWidenedLiteralType)) : + type; + } + function getWidenedUniqueESSymbolType(type) { + return type.flags & 8192 /* UniqueESSymbol */ ? esSymbolType : + type.flags & 1048576 /* Union */ ? getUnionType(ts.sameMap(type.types, getWidenedUniqueESSymbolType)) : + type; + } + function getWidenedLiteralLikeTypeForContextualType(type, contextualType) { + if (!isLiteralOfContextualType(type, contextualType)) { + type = getWidenedUniqueESSymbolType(getWidenedLiteralType(type)); + } + return type; + } + /** + * Check if a Type was written as a tuple type literal. + * Prefer using isTupleLikeType() unless the use of `elementTypes` is required. + */ + function isTupleType(type) { + return !!(ts.getObjectFlags(type) & 4 /* Reference */ && type.target.objectFlags & 8 /* Tuple */); + } + function getRestTypeOfTupleType(type) { + return type.target.hasRestElement ? type.typeArguments[type.target.typeParameters.length - 1] : undefined; + } + function getRestArrayTypeOfTupleType(type) { + var restType = getRestTypeOfTupleType(type); + return restType && createArrayType(restType); + } + function getLengthOfTupleType(type) { + return getTypeReferenceArity(type) - (type.target.hasRestElement ? 1 : 0); + } + function isZeroBigInt(_a) { + var value = _a.value; + return value.base10Value === "0"; + } + function getFalsyFlagsOfTypes(types) { + var result = 0; + for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { + var t = types_9[_i]; + result |= getFalsyFlags(t); + } + return result; + } + // Returns the String, Number, Boolean, StringLiteral, NumberLiteral, BooleanLiteral, Void, Undefined, or Null + // flags for the string, number, boolean, "", 0, false, void, undefined, or null types respectively. Returns + // no flags for all other types (including non-falsy literal types). + function getFalsyFlags(type) { + return type.flags & 1048576 /* Union */ ? getFalsyFlagsOfTypes(type.types) : + type.flags & 128 /* StringLiteral */ ? type.value === "" ? 128 /* StringLiteral */ : 0 : + type.flags & 256 /* NumberLiteral */ ? type.value === 0 ? 256 /* NumberLiteral */ : 0 : + type.flags & 2048 /* BigIntLiteral */ ? isZeroBigInt(type) ? 2048 /* BigIntLiteral */ : 0 : + type.flags & 512 /* BooleanLiteral */ ? (type === falseType || type === regularFalseType) ? 512 /* BooleanLiteral */ : 0 : + type.flags & 117724 /* PossiblyFalsy */; + } + function removeDefinitelyFalsyTypes(type) { + return getFalsyFlags(type) & 117632 /* DefinitelyFalsy */ ? + filterType(type, function (t) { return !(getFalsyFlags(t) & 117632 /* DefinitelyFalsy */); }) : + type; + } + function extractDefinitelyFalsyTypes(type) { + return mapType(type, getDefinitelyFalsyPartOfType); + } + function getDefinitelyFalsyPartOfType(type) { + return type.flags & 4 /* String */ ? emptyStringType : + type.flags & 8 /* Number */ ? zeroType : + type.flags & 64 /* BigInt */ ? zeroBigIntType : + type === regularFalseType || + type === falseType || + type.flags & (16384 /* Void */ | 32768 /* Undefined */ | 65536 /* Null */) || + type.flags & 128 /* StringLiteral */ && type.value === "" || + type.flags & 256 /* NumberLiteral */ && type.value === 0 || + type.flags & 2048 /* BigIntLiteral */ && isZeroBigInt(type) ? type : + neverType; + } + /** + * Add undefined or null or both to a type if they are missing. + * @param type - type to add undefined and/or null to if not present + * @param flags - Either TypeFlags.Undefined or TypeFlags.Null, or both + */ + function getNullableType(type, flags) { + var missing = (flags & ~type.flags) & (32768 /* Undefined */ | 65536 /* Null */); + return missing === 0 ? type : + missing === 32768 /* Undefined */ ? getUnionType([type, undefinedType]) : + missing === 65536 /* Null */ ? getUnionType([type, nullType]) : + getUnionType([type, undefinedType, nullType]); + } + function getOptionalType(type) { + ts.Debug.assert(strictNullChecks); + return type.flags & 32768 /* Undefined */ ? type : getUnionType([type, undefinedType]); + } + function getGlobalNonNullableTypeInstantiation(type) { + if (!deferredGlobalNonNullableTypeAlias) { + deferredGlobalNonNullableTypeAlias = getGlobalSymbol("NonNullable", 524288 /* TypeAlias */, /*diagnostic*/ undefined) || unknownSymbol; + } + // Use NonNullable global type alias if available to improve quick info/declaration emit + if (deferredGlobalNonNullableTypeAlias !== unknownSymbol) { + return getTypeAliasInstantiation(deferredGlobalNonNullableTypeAlias, [type]); + } + return getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */); // Type alias unavailable, fall back to non-higher-order behavior + } + function getNonNullableType(type) { + return strictNullChecks ? getGlobalNonNullableTypeInstantiation(type) : type; + } + /** + * Return true if type was inferred from an object literal, written as an object type literal, or is the shape of a module + * with no call or construct signatures. + */ + function isObjectTypeWithInferableIndex(type) { + return type.symbol && (type.symbol.flags & (4096 /* ObjectLiteral */ | 2048 /* TypeLiteral */ | 512 /* ValueModule */)) !== 0 && + !typeHasCallOrConstructSignatures(type); + } + function createSymbolWithType(source, type) { + var symbol = createSymbol(source.flags, source.escapedName); + symbol.declarations = source.declarations; + symbol.parent = source.parent; + symbol.type = type; + symbol.target = source; + if (source.valueDeclaration) { + symbol.valueDeclaration = source.valueDeclaration; + } + if (source.nameType) { + symbol.nameType = source.nameType; + } + return symbol; + } + function transformTypeOfMembers(type, f) { + var members = ts.createSymbolTable(); + for (var _i = 0, _a = getPropertiesOfObjectType(type); _i < _a.length; _i++) { + var property = _a[_i]; + var original = getTypeOfSymbol(property); + var updated = f(original); + members.set(property.escapedName, updated === original ? property : createSymbolWithType(property, updated)); + } + return members; + } + /** + * If the the provided object literal is subject to the excess properties check, + * create a new that is exempt. Recursively mark object literal members as exempt. + * Leave signatures alone since they are not subject to the check. + */ + function getRegularTypeOfObjectLiteral(type) { + if (!(isObjectLiteralType(type) && ts.getObjectFlags(type) & 32768 /* FreshLiteral */)) { + return type; + } + var regularType = type.regularType; + if (regularType) { + return regularType; + } + var resolved = type; + var members = transformTypeOfMembers(type, getRegularTypeOfObjectLiteral); + var regularNew = createAnonymousType(resolved.symbol, members, resolved.callSignatures, resolved.constructSignatures, resolved.stringIndexInfo, resolved.numberIndexInfo); + regularNew.flags = resolved.flags; + regularNew.objectFlags |= 128 /* ObjectLiteral */ | (ts.getObjectFlags(resolved) & 16384 /* JSLiteral */); + type.regularType = regularNew; + return regularNew; + } + function createWideningContext(parent, propertyName, siblings) { + return { parent: parent, propertyName: propertyName, siblings: siblings, resolvedProperties: undefined }; + } + function getSiblingsOfContext(context) { + if (!context.siblings) { + var siblings_1 = []; + for (var _i = 0, _a = getSiblingsOfContext(context.parent); _i < _a.length; _i++) { + var type = _a[_i]; + if (isObjectLiteralType(type)) { + var prop = getPropertyOfObjectType(type, context.propertyName); + if (prop) { + forEachType(getTypeOfSymbol(prop), function (t) { + siblings_1.push(t); + }); + } + } + } + context.siblings = siblings_1; + } + return context.siblings; + } + function getPropertiesOfContext(context) { + if (!context.resolvedProperties) { + var names = ts.createMap(); + for (var _i = 0, _a = getSiblingsOfContext(context); _i < _a.length; _i++) { + var t = _a[_i]; + if (isObjectLiteralType(t) && !(ts.getObjectFlags(t) & 1024 /* ContainsSpread */)) { + for (var _b = 0, _c = getPropertiesOfType(t); _b < _c.length; _b++) { + var prop = _c[_b]; + names.set(prop.escapedName, prop); + } + } + } + context.resolvedProperties = ts.arrayFrom(names.values()); + } + return context.resolvedProperties; + } + function getWidenedProperty(prop, context) { + if (!(prop.flags & 4 /* Property */)) { + // Since get accessors already widen their return value there is no need to + // widen accessor based properties here. + return prop; + } + var original = getTypeOfSymbol(prop); + var propContext = context && createWideningContext(context, prop.escapedName, /*siblings*/ undefined); + var widened = getWidenedTypeWithContext(original, propContext); + return widened === original ? prop : createSymbolWithType(prop, widened); + } + function getUndefinedProperty(prop) { + var cached = undefinedProperties.get(prop.escapedName); + if (cached) { + return cached; + } + var result = createSymbolWithType(prop, undefinedType); + result.flags |= 16777216 /* Optional */; + undefinedProperties.set(prop.escapedName, result); + return result; + } + function getWidenedTypeOfObjectLiteral(type, context) { + var members = ts.createSymbolTable(); + for (var _i = 0, _a = getPropertiesOfObjectType(type); _i < _a.length; _i++) { + var prop = _a[_i]; + members.set(prop.escapedName, getWidenedProperty(prop, context)); + } + if (context) { + for (var _b = 0, _c = getPropertiesOfContext(context); _b < _c.length; _b++) { + var prop = _c[_b]; + if (!members.has(prop.escapedName)) { + members.set(prop.escapedName, getUndefinedProperty(prop)); + } + } + } + var stringIndexInfo = getIndexInfoOfType(type, 0 /* String */); + var numberIndexInfo = getIndexInfoOfType(type, 1 /* Number */); + var result = createAnonymousType(type.symbol, members, ts.emptyArray, ts.emptyArray, stringIndexInfo && createIndexInfo(getWidenedType(stringIndexInfo.type), stringIndexInfo.isReadonly), numberIndexInfo && createIndexInfo(getWidenedType(numberIndexInfo.type), numberIndexInfo.isReadonly)); + result.objectFlags |= (ts.getObjectFlags(type) & 16384 /* JSLiteral */); // Retain js literal flag through widening + return result; + } + function getWidenedType(type) { + return getWidenedTypeWithContext(type, /*context*/ undefined); + } + function getWidenedTypeWithContext(type, context) { + if (type.flags & 402653184 /* RequiresWidening */) { + if (type.flags & 98304 /* Nullable */) { + return anyType; + } + if (isObjectLiteralType(type)) { + return getWidenedTypeOfObjectLiteral(type, context); + } + if (type.flags & 1048576 /* Union */) { + var unionContext_1 = context || createWideningContext(/*parent*/ undefined, /*propertyName*/ undefined, type.types); + var widenedTypes = ts.sameMap(type.types, function (t) { return t.flags & 98304 /* Nullable */ ? t : getWidenedTypeWithContext(t, unionContext_1); }); + // Widening an empty object literal transitions from a highly restrictive type to + // a highly inclusive one. For that reason we perform subtype reduction here if the + // union includes empty object types (e.g. reducing {} | string to just {}). + return getUnionType(widenedTypes, ts.some(widenedTypes, isEmptyObjectType) ? 2 /* Subtype */ : 1 /* Literal */); + } + if (isArrayType(type) || isTupleType(type)) { + return createTypeReference(type.target, ts.sameMap(type.typeArguments, getWidenedType)); + } + } + return type; + } + /** + * Reports implicit any errors that occur as a result of widening 'null' and 'undefined' + * to 'any'. A call to reportWideningErrorsInType is normally accompanied by a call to + * getWidenedType. But in some cases getWidenedType is called without reporting errors + * (type argument inference is an example). + * + * The return value indicates whether an error was in fact reported. The particular circumstances + * are on a best effort basis. Currently, if the null or undefined that causes widening is inside + * an object literal property (arbitrarily deeply), this function reports an error. If no error is + * reported, reportImplicitAnyError is a suitable fallback to report a general error. + */ + function reportWideningErrorsInType(type) { + var errorReported = false; + if (type.flags & 134217728 /* ContainsWideningType */) { + if (type.flags & 1048576 /* Union */) { + if (ts.some(type.types, isEmptyObjectType)) { + errorReported = true; + } + else { + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (reportWideningErrorsInType(t)) { + errorReported = true; + } + } + } + } + if (isArrayType(type) || isTupleType(type)) { + for (var _b = 0, _c = type.typeArguments; _b < _c.length; _b++) { + var t = _c[_b]; + if (reportWideningErrorsInType(t)) { + errorReported = true; + } + } + } + if (isObjectLiteralType(type)) { + for (var _d = 0, _e = getPropertiesOfObjectType(type); _d < _e.length; _d++) { + var p = _e[_d]; + var t = getTypeOfSymbol(p); + if (t.flags & 134217728 /* ContainsWideningType */) { + if (!reportWideningErrorsInType(t)) { + error(p.valueDeclaration, ts.Diagnostics.Object_literal_s_property_0_implicitly_has_an_1_type, symbolToString(p), typeToString(getWidenedType(t))); + } + errorReported = true; + } + } + } + } + return errorReported; + } + function reportImplicitAny(declaration, type) { + var typeAsString = typeToString(getWidenedType(type)); + if (ts.isInJSFile(declaration) && !ts.isCheckJsEnabledForFile(ts.getSourceFileOfNode(declaration), compilerOptions)) { + // Only report implicit any errors/suggestions in TS and ts-check JS files + return; + } + var diagnostic; + switch (declaration.kind) { + case 204 /* BinaryExpression */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + diagnostic = noImplicitAny ? ts.Diagnostics.Member_0_implicitly_has_an_1_type : ts.Diagnostics.Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage; + break; + case 151 /* Parameter */: + var param = declaration; + if (ts.isIdentifier(param.name) && + (ts.isCallSignatureDeclaration(param.parent) || ts.isMethodSignature(param.parent) || ts.isFunctionTypeNode(param.parent)) && + param.parent.parameters.indexOf(param) > -1 && + (resolveName(param, param.name.escapedText, 67897832 /* Type */, undefined, param.name.escapedText, /*isUse*/ true) || + param.name.originalKeywordKind && ts.isTypeNodeKind(param.name.originalKeywordKind))) { + var newName = "arg" + param.parent.parameters.indexOf(param); + errorOrSuggestion(noImplicitAny, declaration, ts.Diagnostics.Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1, newName, ts.declarationNameToString(param.name)); + return; + } + diagnostic = declaration.dotDotDotToken ? + noImplicitAny ? ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type : ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage : + noImplicitAny ? ts.Diagnostics.Parameter_0_implicitly_has_an_1_type : ts.Diagnostics.Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage; + break; + case 186 /* BindingElement */: + diagnostic = ts.Diagnostics.Binding_element_0_implicitly_has_an_1_type; + break; + case 289 /* JSDocFunctionType */: + error(declaration, ts.Diagnostics.Function_type_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString); + return; + case 239 /* FunctionDeclaration */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + if (noImplicitAny && !declaration.name) { + error(declaration, ts.Diagnostics.Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString); + return; + } + diagnostic = noImplicitAny ? ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type : ts.Diagnostics._0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage; + break; + case 181 /* MappedType */: + if (noImplicitAny) { + error(declaration, ts.Diagnostics.Mapped_object_type_implicitly_has_an_any_template_type); + } + return; + default: + diagnostic = noImplicitAny ? ts.Diagnostics.Variable_0_implicitly_has_an_1_type : ts.Diagnostics.Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage; + } + errorOrSuggestion(noImplicitAny, declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString); + } + function reportErrorsFromWidening(declaration, type) { + if (produceDiagnostics && noImplicitAny && type.flags & 134217728 /* ContainsWideningType */) { + // Report implicit any error within type if possible, otherwise report error on declaration + if (!reportWideningErrorsInType(type)) { + reportImplicitAny(declaration, type); + } + } + } + function forEachMatchingParameterType(source, target, callback) { + var sourceCount = getParameterCount(source); + var targetCount = getParameterCount(target); + var sourceRestType = getEffectiveRestType(source); + var targetRestType = getEffectiveRestType(target); + var targetNonRestCount = targetRestType ? targetCount - 1 : targetCount; + var paramCount = sourceRestType ? targetNonRestCount : Math.min(sourceCount, targetNonRestCount); + var sourceThisType = getThisTypeOfSignature(source); + if (sourceThisType) { + var targetThisType = getThisTypeOfSignature(target); + if (targetThisType) { + callback(sourceThisType, targetThisType); + } + } + for (var i = 0; i < paramCount; i++) { + callback(getTypeAtPosition(source, i), getTypeAtPosition(target, i)); + } + if (targetRestType) { + callback(getRestTypeAtPosition(source, paramCount), targetRestType); + } + } + function createInferenceContext(typeParameters, signature, flags, compareTypes, baseInferences) { + var inferences = baseInferences ? baseInferences.map(cloneInferenceInfo) : typeParameters.map(createInferenceInfo); + var context = mapper; + context.typeParameters = typeParameters; + context.signature = signature; + context.inferences = inferences; + context.flags = flags; + context.compareTypes = compareTypes || compareTypesAssignable; + return context; + function mapper(t) { + for (var i = 0; i < inferences.length; i++) { + if (t === inferences[i].typeParameter) { + inferences[i].isFixed = true; + return getInferredType(context, i); + } + } + return t; + } + } + function createInferenceInfo(typeParameter) { + return { + typeParameter: typeParameter, + candidates: undefined, + contraCandidates: undefined, + inferredType: undefined, + priority: undefined, + topLevel: true, + isFixed: false + }; + } + function cloneInferenceInfo(inference) { + return { + typeParameter: inference.typeParameter, + candidates: inference.candidates && inference.candidates.slice(), + contraCandidates: inference.contraCandidates && inference.contraCandidates.slice(), + inferredType: inference.inferredType, + priority: inference.priority, + topLevel: inference.topLevel, + isFixed: inference.isFixed + }; + } + // Return true if the given type could possibly reference a type parameter for which + // we perform type inference (i.e. a type parameter of a generic function). We cache + // results for union and intersection types for performance reasons. + function couldContainTypeVariables(type) { + var objectFlags = ts.getObjectFlags(type); + return !!(type.flags & 63176704 /* Instantiable */ || + objectFlags & 4 /* Reference */ && ts.forEach(type.typeArguments, couldContainTypeVariables) || + objectFlags & 16 /* Anonymous */ && type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 2048 /* TypeLiteral */ | 32 /* Class */) || + objectFlags & 32 /* Mapped */ || + type.flags & 3145728 /* UnionOrIntersection */ && couldUnionOrIntersectionContainTypeVariables(type)); + } + function couldUnionOrIntersectionContainTypeVariables(type) { + if (type.couldContainTypeVariables === undefined) { + type.couldContainTypeVariables = ts.some(type.types, couldContainTypeVariables); + } + return type.couldContainTypeVariables; + } + function isTypeParameterAtTopLevel(type, typeParameter) { + return type === typeParameter || !!(type.flags & 3145728 /* UnionOrIntersection */) && ts.some(type.types, function (t) { return isTypeParameterAtTopLevel(t, typeParameter); }); + } + /** Create an object with properties named in the string literal type. Every property has type `any` */ + function createEmptyObjectTypeFromStringLiteral(type) { + var members = ts.createSymbolTable(); + forEachType(type, function (t) { + if (!(t.flags & 128 /* StringLiteral */)) { + return; + } + var name = ts.escapeLeadingUnderscores(t.value); + var literalProp = createSymbol(4 /* Property */, name); + literalProp.type = anyType; + if (t.symbol) { + literalProp.declarations = t.symbol.declarations; + literalProp.valueDeclaration = t.symbol.valueDeclaration; + } + members.set(name, literalProp); + }); + var indexInfo = type.flags & 4 /* String */ ? createIndexInfo(emptyObjectType, /*isReadonly*/ false) : undefined; + return createAnonymousType(undefined, members, ts.emptyArray, ts.emptyArray, indexInfo, undefined); + } + /** + * Infer a suitable input type for a homomorphic mapped type { [P in keyof T]: X }. We construct + * an object type with the same set of properties as the source type, where the type of each + * property is computed by inferring from the source property type to X for the type + * variable T[P] (i.e. we treat the type T[P] as the type variable we're inferring for). + */ + function inferTypeForHomomorphicMappedType(source, target, constraint) { + var key = source.id + "," + target.id + "," + constraint.id; + if (reverseMappedCache.has(key)) { + return reverseMappedCache.get(key); + } + reverseMappedCache.set(key, undefined); + var type = createReverseMappedType(source, target, constraint); + reverseMappedCache.set(key, type); + return type; + } + function createReverseMappedType(source, target, constraint) { + var properties = getPropertiesOfType(source); + if (properties.length === 0 && !getIndexInfoOfType(source, 0 /* String */)) { + return undefined; + } + // If any property contains context sensitive functions that have been skipped, the source type + // is incomplete and we can't infer a meaningful input type. + for (var _i = 0, properties_3 = properties; _i < properties_3.length; _i++) { + var prop = properties_3[_i]; + if (getTypeOfSymbol(prop).flags & 536870912 /* ContainsAnyFunctionType */) { + return undefined; + } + } + // For arrays and tuples we infer new arrays and tuples where the reverse mapping has been + // applied to the element type(s). + if (isArrayType(source)) { + return createArrayType(inferReverseMappedType(source.typeArguments[0], target, constraint)); + } + if (isReadonlyArrayType(source)) { + return createReadonlyArrayType(inferReverseMappedType(source.typeArguments[0], target, constraint)); + } + if (isTupleType(source)) { + var elementTypes = ts.map(source.typeArguments || ts.emptyArray, function (t) { return inferReverseMappedType(t, target, constraint); }); + var minLength = getMappedTypeModifiers(target) & 4 /* IncludeOptional */ ? + getTypeReferenceArity(source) - (source.target.hasRestElement ? 1 : 0) : source.target.minLength; + return createTupleType(elementTypes, minLength, source.target.hasRestElement, source.target.associatedNames); + } + // For all other object types we infer a new object type where the reverse mapping has been + // applied to the type of each property. + var reversed = createObjectType(2048 /* ReverseMapped */ | 16 /* Anonymous */, /*symbol*/ undefined); + reversed.source = source; + reversed.mappedType = target; + reversed.constraintType = constraint; + return reversed; + } + function getTypeOfReverseMappedSymbol(symbol) { + return inferReverseMappedType(symbol.propertyType, symbol.mappedType, symbol.constraintType); + } + function inferReverseMappedType(sourceType, target, constraint) { + var typeParameter = getIndexedAccessType(constraint.type, getTypeParameterFromMappedType(target)); + var templateType = getTemplateTypeFromMappedType(target); + var inference = createInferenceInfo(typeParameter); + inferTypes([inference], sourceType, templateType); + return getTypeFromInference(inference); + } + function getUnmatchedProperties(source, target, requireOptionalProperties) { + var properties, _i, properties_4, targetProp, sourceProp; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + properties = target.flags & 2097152 /* Intersection */ ? getPropertiesOfUnionOrIntersectionType(target) : getPropertiesOfObjectType(target); + _i = 0, properties_4 = properties; + _a.label = 1; + case 1: + if (!(_i < properties_4.length)) return [3 /*break*/, 4]; + targetProp = properties_4[_i]; + if (!(requireOptionalProperties || !(targetProp.flags & 16777216 /* Optional */))) return [3 /*break*/, 3]; + sourceProp = getPropertyOfType(source, targetProp.escapedName); + if (!!sourceProp) return [3 /*break*/, 3]; + return [4 /*yield*/, targetProp]; + case 2: + _a.sent(); + _a.label = 3; + case 3: + _i++; + return [3 /*break*/, 1]; + case 4: return [2 /*return*/]; + } + }); + } + function getUnmatchedProperty(source, target, requireOptionalProperties) { + return getUnmatchedProperties(source, target, requireOptionalProperties).next().value; + } + function tupleTypesDefinitelyUnrelated(source, target) { + return target.target.minLength > source.target.minLength || + !getRestTypeOfTupleType(target) && (!!getRestTypeOfTupleType(source) || getLengthOfTupleType(target) < getLengthOfTupleType(source)); + } + function typesDefinitelyUnrelated(source, target) { + // Two tuple types with incompatible arities are definitely unrelated. + // Two object types that each have a property that is unmatched in the other are definitely unrelated. + return isTupleType(source) && isTupleType(target) && tupleTypesDefinitelyUnrelated(source, target) || + !!getUnmatchedProperty(source, target, /*requireOptionalProperties*/ false) && !!getUnmatchedProperty(target, source, /*requireOptionalProperties*/ false); + } + function getTypeFromInference(inference) { + return inference.candidates ? getUnionType(inference.candidates, 2 /* Subtype */) : + inference.contraCandidates ? getIntersectionType(inference.contraCandidates) : + emptyObjectType; + } + function inferTypes(inferences, originalSource, originalTarget, priority) { + if (priority === void 0) { priority = 0; } + var symbolStack; + var visited; + var contravariant = false; + var bivariant = false; + var propagationType; + var allowComplexConstraintInference = true; + inferFromTypes(originalSource, originalTarget); + function inferFromTypes(source, target) { + if (!couldContainTypeVariables(target)) { + return; + } + if (source === wildcardType) { + // We are inferring from an 'any' type. We want to infer this type for every type parameter + // referenced in the target type, so we record it as the propagation type and infer from the + // target to itself. Then, as we find candidates we substitute the propagation type. + var savePropagationType = propagationType; + propagationType = source; + inferFromTypes(target, target); + propagationType = savePropagationType; + return; + } + if (source.aliasSymbol && source.aliasTypeArguments && source.aliasSymbol === target.aliasSymbol) { + // Source and target are types originating in the same generic type alias declaration. + // Simply infer from source type arguments to target type arguments. + var sourceTypes = source.aliasTypeArguments; + var targetTypes = target.aliasTypeArguments; + for (var i = 0; i < sourceTypes.length; i++) { + inferFromTypes(sourceTypes[i], targetTypes[i]); + } + return; + } + if (source.flags & 1048576 /* Union */ && target.flags & 1048576 /* Union */ && !(source.flags & 1024 /* EnumLiteral */ && target.flags & 1024 /* EnumLiteral */) || + source.flags & 2097152 /* Intersection */ && target.flags & 2097152 /* Intersection */) { + // Source and target are both unions or both intersections. If source and target + // are the same type, just relate each constituent type to itself. + if (source === target) { + for (var _i = 0, _a = source.types; _i < _a.length; _i++) { + var t = _a[_i]; + inferFromTypes(t, t); + } + return; + } + // Find each source constituent type that has an identically matching target constituent + // type, and for each such type infer from the type to itself. When inferring from a + // type to itself we effectively find all type parameter occurrences within that type + // and infer themselves as their type arguments. We have special handling for numeric + // and string literals because the number and string types are not represented as unions + // of all their possible values. + var matchingTypes = void 0; + for (var _b = 0, _c = source.types; _b < _c.length; _b++) { + var t = _c[_b]; + if (typeIdenticalToSomeType(t, target.types)) { + (matchingTypes || (matchingTypes = [])).push(t); + inferFromTypes(t, t); + } + else if (t.flags & (256 /* NumberLiteral */ | 128 /* StringLiteral */)) { + var b = getBaseTypeOfLiteralType(t); + if (typeIdenticalToSomeType(b, target.types)) { + (matchingTypes || (matchingTypes = [])).push(t, b); + } + } + } + // Next, to improve the quality of inferences, reduce the source and target types by + // removing the identically matched constituents. For example, when inferring from + // 'string | string[]' to 'string | T' we reduce the types to 'string[]' and 'T'. + if (matchingTypes) { + source = removeTypesFromUnionOrIntersection(source, matchingTypes); + target = removeTypesFromUnionOrIntersection(target, matchingTypes); + } + } + if (target.flags & 8650752 /* TypeVariable */) { + // If target is a type parameter, make an inference, unless the source type contains + // the anyFunctionType (the wildcard type that's used to avoid contextually typing functions). + // Because the anyFunctionType is internal, it should not be exposed to the user by adding + // it as an inference candidate. Hopefully, a better candidate will come along that does + // not contain anyFunctionType when we come back to this argument for its second round + // of inference. Also, we exclude inferences for silentNeverType (which is used as a wildcard + // when constructing types from type parameters that had no inference candidates). + if (source.flags & 536870912 /* ContainsAnyFunctionType */ || source === silentNeverType || (priority & 8 /* ReturnType */ && (source === autoType || source === autoArrayType))) { + return; + } + var inference = getInferenceInfoForType(target); + if (inference) { + if (!inference.isFixed) { + if (inference.priority === undefined || priority < inference.priority) { + inference.candidates = undefined; + inference.contraCandidates = undefined; + inference.priority = priority; + } + if (priority === inference.priority) { + var candidate = propagationType || source; + // We make contravariant inferences only if we are in a pure contravariant position, + // i.e. only if we have not descended into a bivariant position. + if (contravariant && !bivariant) { + inference.contraCandidates = ts.appendIfUnique(inference.contraCandidates, candidate); + } + else { + inference.candidates = ts.appendIfUnique(inference.candidates, candidate); + } + } + if (!(priority & 8 /* ReturnType */) && target.flags & 262144 /* TypeParameter */ && !isTypeParameterAtTopLevel(originalTarget, target)) { + inference.topLevel = false; + } + } + return; + } + else { + // Infer to the simplified version of an indexed access, if possible, to (hopefully) expose more bare type parameters to the inference engine + var simplified = getSimplifiedType(target); + if (simplified !== target) { + inferFromTypesOnce(source, simplified); + } + else if (target.flags & 8388608 /* IndexedAccess */) { + var indexType = getSimplifiedType(target.indexType); + // Generally simplifications of instantiable indexes are avoided to keep relationship checking correct, however if our target is an access, we can consider + // that key of that access to be "instantiated", since we're looking to find the infernce goal in any way we can. + if (indexType.flags & 63176704 /* Instantiable */) { + var simplified_1 = distributeIndexOverObjectType(getSimplifiedType(target.objectType), indexType); + if (simplified_1 && simplified_1 !== target) { + inferFromTypesOnce(source, simplified_1); + } + } + } + } + } + if (ts.getObjectFlags(source) & 4 /* Reference */ && ts.getObjectFlags(target) & 4 /* Reference */ && source.target === target.target) { + // If source and target are references to the same generic type, infer from type arguments + var sourceTypes = source.typeArguments || ts.emptyArray; + var targetTypes = target.typeArguments || ts.emptyArray; + var count = sourceTypes.length < targetTypes.length ? sourceTypes.length : targetTypes.length; + var variances = getVariances(source.target); + for (var i = 0; i < count; i++) { + if (i < variances.length && variances[i] === 2 /* Contravariant */) { + inferFromContravariantTypes(sourceTypes[i], targetTypes[i]); + } + else { + inferFromTypes(sourceTypes[i], targetTypes[i]); + } + } + } + else if (source.flags & 4194304 /* Index */ && target.flags & 4194304 /* Index */) { + contravariant = !contravariant; + inferFromTypes(source.type, target.type); + contravariant = !contravariant; + } + else if ((isLiteralType(source) || source.flags & 4 /* String */) && target.flags & 4194304 /* Index */) { + var empty = createEmptyObjectTypeFromStringLiteral(source); + contravariant = !contravariant; + var savePriority = priority; + priority |= 16 /* LiteralKeyof */; + inferFromTypes(empty, target.type); + priority = savePriority; + contravariant = !contravariant; + } + else if (source.flags & 8388608 /* IndexedAccess */ && target.flags & 8388608 /* IndexedAccess */) { + inferFromTypes(source.objectType, target.objectType); + inferFromTypes(source.indexType, target.indexType); + } + else if (source.flags & 16777216 /* Conditional */ && target.flags & 16777216 /* Conditional */) { + inferFromTypes(source.checkType, target.checkType); + inferFromTypes(source.extendsType, target.extendsType); + inferFromTypes(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target)); + inferFromTypes(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target)); + } + else if (target.flags & 16777216 /* Conditional */) { + inferFromTypes(source, getUnionType([getTrueTypeFromConditionalType(target), getFalseTypeFromConditionalType(target)])); + } + else if (target.flags & 3145728 /* UnionOrIntersection */) { + var targetTypes = target.types; + var typeVariableCount = 0; + var typeVariable = void 0; + // First infer to each type in union or intersection that isn't a type variable + for (var _d = 0, targetTypes_3 = targetTypes; _d < targetTypes_3.length; _d++) { + var t = targetTypes_3[_d]; + if (getInferenceInfoForType(t)) { + typeVariable = t; + typeVariableCount++; + } + else { + inferFromTypes(source, t); + } + } + // Next, if target containings a single naked type variable, make a secondary inference to that type + // variable. This gives meaningful results for union types in co-variant positions and intersection + // types in contra-variant positions (such as callback parameters). + if (typeVariableCount === 1) { + var savePriority = priority; + priority |= 1 /* NakedTypeVariable */; + inferFromTypes(source, typeVariable); + priority = savePriority; + } + } + else if (source.flags & 1048576 /* Union */) { + // Source is a union or intersection type, infer from each constituent type + var sourceTypes = source.types; + for (var _e = 0, sourceTypes_3 = sourceTypes; _e < sourceTypes_3.length; _e++) { + var sourceType = sourceTypes_3[_e]; + inferFromTypes(sourceType, target); + } + } + else { + if (!(priority & 32 /* NoConstraints */ && source.flags & (2097152 /* Intersection */ | 63176704 /* Instantiable */))) { + var apparentSource = getApparentType(source); + // getApparentType can return _any_ type, since an indexed access or conditional may simplify to any other type. + // If that occurs and it doesn't simplify to an object or intersection, we'll need to restart `inferFromTypes` + // with the simplified source. + if (apparentSource !== source && allowComplexConstraintInference && !(apparentSource.flags & (524288 /* Object */ | 2097152 /* Intersection */))) { + // TODO: The `allowComplexConstraintInference` flag is a hack! This forbids inference from complex constraints within constraints! + // This isn't required algorithmically, but rather is used to lower the memory burden caused by performing inference + // that is _too good_ in projects with complicated constraints (eg, fp-ts). In such cases, if we did not limit ourselves + // here, we might produce more valid inferences for types, causing us to do more checks and perform more instantiations + // (in addition to the extra stack depth here) which, in turn, can push the already close process over its limit. + // TL;DR: If we ever become generally more memory efficienct (or our resource budget ever increases), we should just + // remove this `allowComplexConstraintInference` flag. + allowComplexConstraintInference = false; + return inferFromTypes(apparentSource, target); + } + source = apparentSource; + } + if (source.flags & (524288 /* Object */ | 2097152 /* Intersection */)) { + var key = source.id + "," + target.id; + if (visited && visited.get(key)) { + return; + } + (visited || (visited = ts.createMap())).set(key, true); + // If we are already processing another target type with the same associated symbol (such as + // an instantiation of the same generic type), we do not explore this target as it would yield + // no further inferences. We exclude the static side of classes from this check since it shares + // its symbol with the instance side which would lead to false positives. + var isNonConstructorObject = target.flags & 524288 /* Object */ && + !(ts.getObjectFlags(target) & 16 /* Anonymous */ && target.symbol && target.symbol.flags & 32 /* Class */); + var symbol = isNonConstructorObject ? target.symbol : undefined; + if (symbol) { + if (ts.contains(symbolStack, symbol)) { + return; + } + (symbolStack || (symbolStack = [])).push(symbol); + inferFromObjectTypes(source, target); + symbolStack.pop(); + } + else { + inferFromObjectTypes(source, target); + } + } + } + function inferFromTypesOnce(source, target) { + var key = source.id + "," + target.id; + if (!visited || !visited.get(key)) { + (visited || (visited = ts.createMap())).set(key, true); + inferFromTypes(source, target); + } + } + } + function inferFromContravariantTypes(source, target) { + if (strictFunctionTypes || priority & 64 /* AlwaysStrict */) { + contravariant = !contravariant; + inferFromTypes(source, target); + contravariant = !contravariant; + } + else { + inferFromTypes(source, target); + } + } + function getInferenceInfoForType(type) { + if (type.flags & 8650752 /* TypeVariable */) { + for (var _i = 0, inferences_1 = inferences; _i < inferences_1.length; _i++) { + var inference = inferences_1[_i]; + if (type === inference.typeParameter) { + return inference; + } + } + } + return undefined; + } + function inferFromMappedTypeConstraint(source, target, constraintType) { + if (constraintType.flags & 1048576 /* Union */) { + var result = false; + for (var _i = 0, _a = constraintType.types; _i < _a.length; _i++) { + var type = _a[_i]; + result = inferFromMappedTypeConstraint(source, target, type) || result; + } + return result; + } + if (constraintType.flags & 4194304 /* Index */) { + // We're inferring from some source type S to a homomorphic mapped type { [P in keyof T]: X }, + // where T is a type variable. Use inferTypeForHomomorphicMappedType to infer a suitable source + // type and then make a secondary inference from that type to T. We make a secondary inference + // such that direct inferences to T get priority over inferences to Partial, for example. + var inference = getInferenceInfoForType(constraintType.type); + if (inference && !inference.isFixed) { + var inferredType = inferTypeForHomomorphicMappedType(source, target, constraintType); + if (inferredType) { + var savePriority = priority; + priority |= 2 /* HomomorphicMappedType */; + inferFromTypes(inferredType, inference.typeParameter); + priority = savePriority; + } + } + return true; + } + if (constraintType.flags & 262144 /* TypeParameter */) { + // We're inferring from some source type S to a mapped type { [P in T]: X }, where T is a type + // parameter. Infer from 'keyof S' to T and infer from a union of each property type in S to X. + var savePriority = priority; + priority |= 4 /* MappedTypeConstraint */; + inferFromTypes(getIndexType(source), constraintType); + priority = savePriority; + inferFromTypes(getUnionType(ts.map(getPropertiesOfType(source), getTypeOfSymbol)), getTemplateTypeFromMappedType(target)); + return true; + } + return false; + } + function inferFromObjectTypes(source, target) { + if (isGenericMappedType(source) && isGenericMappedType(target)) { + // The source and target types are generic types { [P in S]: X } and { [P in T]: Y }, so we infer + // from S to T and from X to Y. + inferFromTypes(getConstraintTypeFromMappedType(source), getConstraintTypeFromMappedType(target)); + inferFromTypes(getTemplateTypeFromMappedType(source), getTemplateTypeFromMappedType(target)); + } + if (ts.getObjectFlags(target) & 32 /* Mapped */) { + var constraintType = getConstraintTypeFromMappedType(target); + if (inferFromMappedTypeConstraint(source, target, constraintType)) { + return; + } + } + // Infer from the members of source and target only if the two types are possibly related + if (!typesDefinitelyUnrelated(source, target)) { + inferFromProperties(source, target); + inferFromSignatures(source, target, 0 /* Call */); + inferFromSignatures(source, target, 1 /* Construct */); + inferFromIndexTypes(source, target); + } + } + function inferFromProperties(source, target) { + if (isTupleType(source)) { + if (isTupleType(target)) { + var sourceLength = getLengthOfTupleType(source); + var targetLength = getLengthOfTupleType(target); + var sourceRestType = getRestTypeOfTupleType(source); + var targetRestType = getRestTypeOfTupleType(target); + var fixedLength = targetLength < sourceLength || sourceRestType ? targetLength : sourceLength; + for (var i = 0; i < fixedLength; i++) { + inferFromTypes(i < sourceLength ? source.typeArguments[i] : sourceRestType, target.typeArguments[i]); + } + if (targetRestType) { + var types = fixedLength < sourceLength ? source.typeArguments.slice(fixedLength, sourceLength) : []; + if (sourceRestType) { + types.push(sourceRestType); + } + if (types.length) { + inferFromTypes(getUnionType(types), targetRestType); + } + } + return; + } + if (isArrayType(target)) { + inferFromIndexTypes(source, target); + return; + } + } + var properties = getPropertiesOfObjectType(target); + for (var _i = 0, properties_5 = properties; _i < properties_5.length; _i++) { + var targetProp = properties_5[_i]; + var sourceProp = getPropertyOfType(source, targetProp.escapedName); + if (sourceProp) { + inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); + } + } + } + function inferFromSignatures(source, target, kind) { + var sourceSignatures = getSignaturesOfType(source, kind); + var targetSignatures = getSignaturesOfType(target, kind); + var sourceLen = sourceSignatures.length; + var targetLen = targetSignatures.length; + var len = sourceLen < targetLen ? sourceLen : targetLen; + var skipParameters = !!(source.flags & 536870912 /* ContainsAnyFunctionType */); + for (var i = 0; i < len; i++) { + inferFromSignature(getBaseSignature(sourceSignatures[sourceLen - len + i]), getBaseSignature(targetSignatures[targetLen - len + i]), skipParameters); + } + } + function inferFromSignature(source, target, skipParameters) { + if (!skipParameters) { + var saveBivariant = bivariant; + var kind = target.declaration ? target.declaration.kind : 0 /* Unknown */; + // Once we descend into a bivariant signature we remain bivariant for all nested inferences + bivariant = bivariant || kind === 156 /* MethodDeclaration */ || kind === 155 /* MethodSignature */ || kind === 157 /* Constructor */; + forEachMatchingParameterType(source, target, inferFromContravariantTypes); + bivariant = saveBivariant; + } + var sourceTypePredicate = getTypePredicateOfSignature(source); + var targetTypePredicate = getTypePredicateOfSignature(target); + if (sourceTypePredicate && targetTypePredicate && sourceTypePredicate.kind === targetTypePredicate.kind) { + inferFromTypes(sourceTypePredicate.type, targetTypePredicate.type); + } + else { + inferFromTypes(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target)); + } + } + function inferFromIndexTypes(source, target) { + var targetStringIndexType = getIndexTypeOfType(target, 0 /* String */); + if (targetStringIndexType) { + var sourceIndexType = getIndexTypeOfType(source, 0 /* String */) || + getImplicitIndexTypeOfType(source, 0 /* String */); + if (sourceIndexType) { + inferFromTypes(sourceIndexType, targetStringIndexType); + } + } + var targetNumberIndexType = getIndexTypeOfType(target, 1 /* Number */); + if (targetNumberIndexType) { + var sourceIndexType = getIndexTypeOfType(source, 1 /* Number */) || + getIndexTypeOfType(source, 0 /* String */) || + getImplicitIndexTypeOfType(source, 1 /* Number */); + if (sourceIndexType) { + inferFromTypes(sourceIndexType, targetNumberIndexType); + } + } + } + } + function typeIdenticalToSomeType(type, types) { + for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { + var t = types_10[_i]; + if (isTypeIdenticalTo(t, type)) { + return true; + } + } + return false; + } + /** + * Return a new union or intersection type computed by removing a given set of types + * from a given union or intersection type. + */ + function removeTypesFromUnionOrIntersection(type, typesToRemove) { + var reducedTypes = []; + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (!typeIdenticalToSomeType(t, typesToRemove)) { + reducedTypes.push(t); + } + } + return type.flags & 1048576 /* Union */ ? getUnionType(reducedTypes) : getIntersectionType(reducedTypes); + } + function hasPrimitiveConstraint(type) { + var constraint = getConstraintOfTypeParameter(type); + return !!constraint && maybeTypeOfKind(constraint.flags & 16777216 /* Conditional */ ? getDefaultConstraintOfConditionalType(constraint) : constraint, 131068 /* Primitive */ | 4194304 /* Index */); + } + function isObjectLiteralType(type) { + return !!(ts.getObjectFlags(type) & 128 /* ObjectLiteral */); + } + function widenObjectLiteralCandidates(candidates) { + if (candidates.length > 1) { + var objectLiterals = ts.filter(candidates, isObjectLiteralType); + if (objectLiterals.length) { + var objectLiteralsType = getWidenedType(getUnionType(objectLiterals, 2 /* Subtype */)); + return ts.concatenate(ts.filter(candidates, function (t) { return !isObjectLiteralType(t); }), [objectLiteralsType]); + } + } + return candidates; + } + function getContravariantInference(inference) { + return inference.priority & 28 /* PriorityImpliesCombination */ ? getIntersectionType(inference.contraCandidates) : getCommonSubtype(inference.contraCandidates); + } + function getCovariantInference(inference, signature) { + // Extract all object literal types and replace them with a single widened and normalized type. + var candidates = widenObjectLiteralCandidates(inference.candidates); + // We widen inferred literal types if + // all inferences were made to top-level occurrences of the type parameter, and + // the type parameter has no constraint or its constraint includes no primitive or literal types, and + // the type parameter was fixed during inference or does not occur at top-level in the return type. + var primitiveConstraint = hasPrimitiveConstraint(inference.typeParameter); + var widenLiteralTypes = !primitiveConstraint && inference.topLevel && + (inference.isFixed || !isTypeParameterAtTopLevel(getReturnTypeOfSignature(signature), inference.typeParameter)); + var baseCandidates = primitiveConstraint ? ts.sameMap(candidates, getRegularTypeOfLiteralType) : + widenLiteralTypes ? ts.sameMap(candidates, getWidenedLiteralType) : + candidates; + // If all inferences were made from a position that implies a combined result, infer a union type. + // Otherwise, infer a common supertype. + var unwidenedType = inference.priority & 28 /* PriorityImpliesCombination */ ? + getUnionType(baseCandidates, 2 /* Subtype */) : + getCommonSupertype(baseCandidates); + return getWidenedType(unwidenedType); + } + function getInferredType(context, index) { + var inference = context.inferences[index]; + var inferredType = inference.inferredType; + if (!inferredType) { + var signature = context.signature; + if (signature) { + var inferredCovariantType = inference.candidates ? getCovariantInference(inference, signature) : undefined; + if (inference.contraCandidates) { + var inferredContravariantType = getContravariantInference(inference); + // If we have both co- and contra-variant inferences, we prefer the contra-variant inference + // unless the co-variant inference is a subtype and not 'never'. + inferredType = inferredCovariantType && !(inferredCovariantType.flags & 131072 /* Never */) && + isTypeSubtypeOf(inferredCovariantType, inferredContravariantType) ? + inferredCovariantType : inferredContravariantType; + } + else if (inferredCovariantType) { + inferredType = inferredCovariantType; + } + else if (context.flags & 1 /* NoDefault */) { + // We use silentNeverType as the wildcard that signals no inferences. + inferredType = silentNeverType; + } + else { + // Infer either the default or the empty object type when no inferences were + // made. It is important to remember that in this case, inference still + // succeeds, meaning there is no error for not having inference candidates. An + // inference error only occurs when there are *conflicting* candidates, i.e. + // candidates with no common supertype. + var defaultType = getDefaultFromTypeParameter(inference.typeParameter); + if (defaultType) { + // Instantiate the default type. Any forward reference to a type + // parameter should be instantiated to the empty object type. + inferredType = instantiateType(defaultType, combineTypeMappers(createBackreferenceMapper(context.signature.typeParameters, index), context)); + } + else { + inferredType = getDefaultTypeArgumentType(!!(context.flags & 2 /* AnyDefault */)); + } + } + } + else { + inferredType = getTypeFromInference(inference); + } + inference.inferredType = inferredType; + var constraint = getConstraintOfTypeParameter(inference.typeParameter); + if (constraint) { + var instantiatedConstraint = instantiateType(constraint, context); + if (!context.compareTypes(inferredType, getTypeWithThisArgument(instantiatedConstraint, inferredType))) { + inference.inferredType = inferredType = instantiatedConstraint; + } + } + } + return inferredType; + } + function getDefaultTypeArgumentType(isInJavaScriptFile) { + return isInJavaScriptFile ? anyType : emptyObjectType; + } + function getInferredTypes(context) { + var result = []; + for (var i = 0; i < context.inferences.length; i++) { + result.push(getInferredType(context, i)); + } + return result; + } + // EXPRESSION TYPE CHECKING + function getCannotFindNameDiagnosticForName(name) { + switch (name) { + case "document": + case "console": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom; + case "$": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_and_then_add_jquery_to_the_types_field_in_your_tsconfig; + case "describe": + case "suite": + case "it": + case "test": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha_and_then_add_jest_or_mocha_to_the_types_field_in_your_tsconfig; + case "process": + case "require": + case "Buffer": + case "module": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_and_then_add_node_to_the_types_field_in_your_tsconfig; + case "Map": + case "Set": + case "Promise": + case "Symbol": + case "WeakMap": + case "WeakSet": + case "Iterator": + case "AsyncIterator": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later; + default: return ts.Diagnostics.Cannot_find_name_0; + } + } + function getResolvedSymbol(node) { + var links = getNodeLinks(node); + if (!links.resolvedSymbol) { + links.resolvedSymbol = !ts.nodeIsMissing(node) && + resolveName(node, node.escapedText, 67220415 /* Value */ | 1048576 /* ExportValue */, getCannotFindNameDiagnosticForName(node.escapedText), node, !ts.isWriteOnlyAccess(node), + /*excludeGlobals*/ false, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1) || unknownSymbol; + } + return links.resolvedSymbol; + } + function isInTypeQuery(node) { + // TypeScript 1.0 spec (April 2014): 3.6.3 + // A type query consists of the keyword typeof followed by an expression. + // The expression is restricted to a single identifier or a sequence of identifiers separated by periods + return !!ts.findAncestor(node, function (n) { return n.kind === 167 /* TypeQuery */ ? true : n.kind === 72 /* Identifier */ || n.kind === 148 /* QualifiedName */ ? false : "quit"; }); + } + // Return the flow cache key for a "dotted name" (i.e. a sequence of identifiers + // separated by dots). The key consists of the id of the symbol referenced by the + // leftmost identifier followed by zero or more property names separated by dots. + // The result is undefined if the reference isn't a dotted name. We prefix nodes + // occurring in an apparent type position with '@' because the control flow type + // of such nodes may be based on the apparent type instead of the declared type. + function getFlowCacheKey(node) { + if (node.kind === 72 /* Identifier */) { + var symbol = getResolvedSymbol(node); + return symbol !== unknownSymbol ? (isConstraintPosition(node) ? "@" : "") + getSymbolId(symbol) : undefined; + } + if (node.kind === 100 /* ThisKeyword */) { + return "0"; + } + if (node.kind === 189 /* PropertyAccessExpression */) { + var key = getFlowCacheKey(node.expression); + return key && key + "." + ts.idText(node.name); + } + if (node.kind === 186 /* BindingElement */) { + var container = node.parent.parent; + var key = container.kind === 186 /* BindingElement */ ? getFlowCacheKey(container) : (container.initializer && getFlowCacheKey(container.initializer)); + var text = getBindingElementNameText(node); + var result = key && text && (key + "." + text); + return result; + } + return undefined; + } + function getBindingElementNameText(element) { + var parent = element.parent; + if (parent.kind === 184 /* ObjectBindingPattern */) { + var name = element.propertyName || element.name; + switch (name.kind) { + case 72 /* Identifier */: + return ts.idText(name); + case 149 /* ComputedPropertyName */: + return ts.isStringOrNumericLiteralLike(name.expression) ? name.expression.text : undefined; + case 10 /* StringLiteral */: + case 8 /* NumericLiteral */: + return name.text; + default: + // Per types, array and object binding patterns remain, however they should never be present if propertyName is not defined + ts.Debug.fail("Unexpected name kind for binding element name"); + } + } + else { + return "" + parent.elements.indexOf(element); + } + } + function isMatchingReference(source, target) { + switch (source.kind) { + case 72 /* Identifier */: + return target.kind === 72 /* Identifier */ && getResolvedSymbol(source) === getResolvedSymbol(target) || + (target.kind === 237 /* VariableDeclaration */ || target.kind === 186 /* BindingElement */) && + getExportSymbolOfValueSymbolIfExported(getResolvedSymbol(source)) === getSymbolOfNode(target); + case 100 /* ThisKeyword */: + return target.kind === 100 /* ThisKeyword */; + case 98 /* SuperKeyword */: + return target.kind === 98 /* SuperKeyword */; + case 189 /* PropertyAccessExpression */: + case 190 /* ElementAccessExpression */: + return (ts.isPropertyAccessExpression(target) || ts.isElementAccessExpression(target)) && + getAccessedPropertyName(source) === getAccessedPropertyName(target) && + isMatchingReference(source.expression, target.expression); + case 186 /* BindingElement */: + if (target.kind !== 189 /* PropertyAccessExpression */) + return false; + var t = target; + if (t.name.escapedText !== getBindingElementNameText(source)) + return false; + if (source.parent.parent.kind === 186 /* BindingElement */ && isMatchingReference(source.parent.parent, t.expression)) { + return true; + } + if (source.parent.parent.kind === 237 /* VariableDeclaration */) { + var maybeId = source.parent.parent.initializer; + return !!maybeId && isMatchingReference(maybeId, t.expression); + } + } + return false; + } + function getAccessedPropertyName(access) { + return ts.isPropertyAccessExpression(access) ? access.name.escapedText : + ts.isStringLiteral(access.argumentExpression) || ts.isNumericLiteral(access.argumentExpression) ? ts.escapeLeadingUnderscores(access.argumentExpression.text) : + undefined; + } + function containsMatchingReference(source, target) { + while (source.kind === 189 /* PropertyAccessExpression */) { + source = source.expression; + if (isMatchingReference(source, target)) { + return true; + } + } + return false; + } + // Return true if target is a property access xxx.yyy, source is a property access xxx.zzz, the declared + // type of xxx is a union type, and yyy is a property that is possibly a discriminant. We consider a property + // a possible discriminant if its type differs in the constituents of containing union type, and if every + // choice is a unit type or a union of unit types. + function containsMatchingReferenceDiscriminant(source, target) { + return target.kind === 189 /* PropertyAccessExpression */ && + containsMatchingReference(source, target.expression) && + isDiscriminantProperty(getDeclaredTypeOfReference(target.expression), target.name.escapedText); + } + function getDeclaredTypeOfReference(expr) { + if (expr.kind === 72 /* Identifier */) { + return getTypeOfSymbol(getResolvedSymbol(expr)); + } + if (expr.kind === 189 /* PropertyAccessExpression */) { + var type = getDeclaredTypeOfReference(expr.expression); + return type && getTypeOfPropertyOfType(type, expr.name.escapedText); + } + return undefined; + } + function isDiscriminantType(type) { + if (type.flags & 1048576 /* Union */) { + if (type.flags & (16 /* Boolean */ | 1024 /* EnumLiteral */)) { + return true; + } + var combined = 0; + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var t = _a[_i]; + combined |= t.flags; + } + if (combined & 109440 /* Unit */ && !(combined & 63176704 /* Instantiable */)) { + return true; + } + } + return false; + } + function isDiscriminantProperty(type, name) { + if (type && type.flags & 1048576 /* Union */) { + var prop = getUnionOrIntersectionProperty(type, name); + if (prop && ts.getCheckFlags(prop) & 2 /* SyntheticProperty */) { + if (prop.isDiscriminantProperty === undefined) { + prop.isDiscriminantProperty = !!(prop.checkFlags & 32 /* HasNonUniformType */) && isDiscriminantType(getTypeOfSymbol(prop)); + } + return !!prop.isDiscriminantProperty; + } + } + return false; + } + function hasNarrowableDeclaredType(expr) { + var type = getDeclaredTypeOfReference(expr); + return !!(type && type.flags & 1048576 /* Union */); + } + function findDiscriminantProperties(sourceProperties, target) { + var result; + for (var _i = 0, sourceProperties_2 = sourceProperties; _i < sourceProperties_2.length; _i++) { + var sourceProperty = sourceProperties_2[_i]; + if (isDiscriminantProperty(target, sourceProperty.escapedName)) { + if (result) { + result.push(sourceProperty); + continue; + } + result = [sourceProperty]; + } + } + return result; + } + function isOrContainsMatchingReference(source, target) { + return isMatchingReference(source, target) || containsMatchingReference(source, target); + } + function hasMatchingArgument(callExpression, reference) { + if (callExpression.arguments) { + for (var _i = 0, _a = callExpression.arguments; _i < _a.length; _i++) { + var argument = _a[_i]; + if (isOrContainsMatchingReference(reference, argument)) { + return true; + } + } + } + if (callExpression.expression.kind === 189 /* PropertyAccessExpression */ && + isOrContainsMatchingReference(reference, callExpression.expression.expression)) { + return true; + } + return false; + } + function getFlowNodeId(flow) { + if (!flow.id) { + flow.id = nextFlowId; + nextFlowId++; + } + return flow.id; + } + function typeMaybeAssignableTo(source, target) { + if (!(source.flags & 1048576 /* Union */)) { + return isTypeAssignableTo(source, target); + } + for (var _i = 0, _a = source.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (isTypeAssignableTo(t, target)) { + return true; + } + } + return false; + } + // Remove those constituent types of declaredType to which no constituent type of assignedType is assignable. + // For example, when a variable of type number | string | boolean is assigned a value of type number | boolean, + // we remove type string. + function getAssignmentReducedType(declaredType, assignedType) { + if (declaredType !== assignedType) { + if (assignedType.flags & 131072 /* Never */) { + return assignedType; + } + var reducedType = filterType(declaredType, function (t) { return typeMaybeAssignableTo(assignedType, t); }); + if (assignedType.flags & 512 /* BooleanLiteral */ && isFreshLiteralType(assignedType)) { + reducedType = mapType(reducedType, getFreshTypeOfLiteralType); // Ensure that if the assignment is a fresh type, that we narrow to fresh types + } + // Our crude heuristic produces an invalid result in some cases: see GH#26130. + // For now, when that happens, we give up and don't narrow at all. (This also + // means we'll never narrow for erroneous assignments where the assigned type + // is not assignable to the declared type.) + if (isTypeAssignableTo(assignedType, reducedType)) { + return reducedType; + } + } + return declaredType; + } + function getTypeFactsOfTypes(types) { + var result = 0 /* None */; + for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { + var t = types_11[_i]; + result |= getTypeFacts(t); + } + return result; + } + function isFunctionObjectType(type) { + // We do a quick check for a "bind" property before performing the more expensive subtype + // check. This gives us a quicker out in the common case where an object type is not a function. + var resolved = resolveStructuredTypeMembers(type); + return !!(resolved.callSignatures.length || resolved.constructSignatures.length || + resolved.members.get("bind") && isTypeSubtypeOf(type, globalFunctionType)); + } + function getTypeFacts(type) { + var flags = type.flags; + if (flags & 4 /* String */) { + return strictNullChecks ? 16317953 /* StringStrictFacts */ : 16776705 /* StringFacts */; + } + if (flags & 128 /* StringLiteral */) { + var isEmpty = type.value === ""; + return strictNullChecks ? + isEmpty ? 12123649 /* EmptyStringStrictFacts */ : 7929345 /* NonEmptyStringStrictFacts */ : + isEmpty ? 12582401 /* EmptyStringFacts */ : 16776705 /* NonEmptyStringFacts */; + } + if (flags & (8 /* Number */ | 32 /* Enum */)) { + return strictNullChecks ? 16317698 /* NumberStrictFacts */ : 16776450 /* NumberFacts */; + } + if (flags & 256 /* NumberLiteral */) { + var isZero = type.value === 0; + return strictNullChecks ? + isZero ? 12123394 /* ZeroNumberStrictFacts */ : 7929090 /* NonZeroNumberStrictFacts */ : + isZero ? 12582146 /* ZeroNumberFacts */ : 16776450 /* NonZeroNumberFacts */; + } + if (flags & 64 /* BigInt */) { + return strictNullChecks ? 16317188 /* BigIntStrictFacts */ : 16775940 /* BigIntFacts */; + } + if (flags & 2048 /* BigIntLiteral */) { + var isZero = isZeroBigInt(type); + return strictNullChecks ? + isZero ? 12122884 /* ZeroBigIntStrictFacts */ : 7928580 /* NonZeroBigIntStrictFacts */ : + isZero ? 12581636 /* ZeroBigIntFacts */ : 16775940 /* NonZeroBigIntFacts */; + } + if (flags & 16 /* Boolean */) { + return strictNullChecks ? 16316168 /* BooleanStrictFacts */ : 16774920 /* BooleanFacts */; + } + if (flags & 528 /* BooleanLike */) { + return strictNullChecks ? + (type === falseType || type === regularFalseType) ? 12121864 /* FalseStrictFacts */ : 7927560 /* TrueStrictFacts */ : + (type === falseType || type === regularFalseType) ? 12580616 /* FalseFacts */ : 16774920 /* TrueFacts */; + } + if (flags & 524288 /* Object */) { + return ts.getObjectFlags(type) & 16 /* Anonymous */ && isEmptyObjectType(type) ? + strictNullChecks ? 16318463 /* EmptyObjectStrictFacts */ : 16777215 /* EmptyObjectFacts */ : + isFunctionObjectType(type) ? + strictNullChecks ? 7880640 /* FunctionStrictFacts */ : 16728000 /* FunctionFacts */ : + strictNullChecks ? 7888800 /* ObjectStrictFacts */ : 16736160 /* ObjectFacts */; + } + if (flags & (16384 /* Void */ | 32768 /* Undefined */)) { + return 9830144 /* UndefinedFacts */; + } + if (flags & 65536 /* Null */) { + return 9363232 /* NullFacts */; + } + if (flags & 12288 /* ESSymbolLike */) { + return strictNullChecks ? 7925520 /* SymbolStrictFacts */ : 16772880 /* SymbolFacts */; + } + if (flags & 67108864 /* NonPrimitive */) { + return strictNullChecks ? 7888800 /* ObjectStrictFacts */ : 16736160 /* ObjectFacts */; + } + if (flags & 63176704 /* Instantiable */) { + return getTypeFacts(getBaseConstraintOfType(type) || emptyObjectType); + } + if (flags & 3145728 /* UnionOrIntersection */) { + return getTypeFactsOfTypes(type.types); + } + return 16777215 /* All */; + } + function getTypeWithFacts(type, include) { + return filterType(type, function (t) { return (getTypeFacts(t) & include) !== 0; }); + } + function getTypeWithDefault(type, defaultExpression) { + if (defaultExpression) { + var defaultType = getTypeOfExpression(defaultExpression); + return getUnionType([getTypeWithFacts(type, 524288 /* NEUndefined */), defaultType]); + } + return type; + } + function getTypeOfDestructuredProperty(type, name) { + var text = ts.getTextOfPropertyName(name); + return getConstraintForLocation(getTypeOfPropertyOfType(type, text), name) || + isNumericLiteralName(text) && getIndexTypeOfType(type, 1 /* Number */) || + getIndexTypeOfType(type, 0 /* String */) || + errorType; + } + function getTypeOfDestructuredArrayElement(type, index) { + return everyType(type, isTupleLikeType) && getTupleElementType(type, index) || + checkIteratedTypeOrElementType(type, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterables*/ false) || + errorType; + } + function getTypeOfDestructuredSpreadExpression(type) { + return createArrayType(checkIteratedTypeOrElementType(type, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterables*/ false) || errorType); + } + function getAssignedTypeOfBinaryExpression(node) { + var isDestructuringDefaultAssignment = node.parent.kind === 187 /* ArrayLiteralExpression */ && isDestructuringAssignmentTarget(node.parent) || + node.parent.kind === 275 /* PropertyAssignment */ && isDestructuringAssignmentTarget(node.parent.parent); + return isDestructuringDefaultAssignment ? + getTypeWithDefault(getAssignedType(node), node.right) : + getTypeOfExpression(node.right); + } + function isDestructuringAssignmentTarget(parent) { + return parent.parent.kind === 204 /* BinaryExpression */ && parent.parent.left === parent || + parent.parent.kind === 227 /* ForOfStatement */ && parent.parent.initializer === parent; + } + function getAssignedTypeOfArrayLiteralElement(node, element) { + return getTypeOfDestructuredArrayElement(getAssignedType(node), node.elements.indexOf(element)); + } + function getAssignedTypeOfSpreadExpression(node) { + return getTypeOfDestructuredSpreadExpression(getAssignedType(node.parent)); + } + function getAssignedTypeOfPropertyAssignment(node) { + return getTypeOfDestructuredProperty(getAssignedType(node.parent), node.name); + } + function getAssignedTypeOfShorthandPropertyAssignment(node) { + return getTypeWithDefault(getAssignedTypeOfPropertyAssignment(node), node.objectAssignmentInitializer); + } + function getAssignedType(node) { + var parent = node.parent; + switch (parent.kind) { + case 226 /* ForInStatement */: + return stringType; + case 227 /* ForOfStatement */: + return checkRightHandSideOfForOf(parent.expression, parent.awaitModifier) || errorType; + case 204 /* BinaryExpression */: + return getAssignedTypeOfBinaryExpression(parent); + case 198 /* DeleteExpression */: + return undefinedType; + case 187 /* ArrayLiteralExpression */: + return getAssignedTypeOfArrayLiteralElement(parent, node); + case 208 /* SpreadElement */: + return getAssignedTypeOfSpreadExpression(parent); + case 275 /* PropertyAssignment */: + return getAssignedTypeOfPropertyAssignment(parent); + case 276 /* ShorthandPropertyAssignment */: + return getAssignedTypeOfShorthandPropertyAssignment(parent); + } + return errorType; + } + function getInitialTypeOfBindingElement(node) { + var pattern = node.parent; + var parentType = getInitialType(pattern.parent); + var type = pattern.kind === 184 /* ObjectBindingPattern */ ? + getTypeOfDestructuredProperty(parentType, node.propertyName || node.name) : + !node.dotDotDotToken ? + getTypeOfDestructuredArrayElement(parentType, pattern.elements.indexOf(node)) : + getTypeOfDestructuredSpreadExpression(parentType); + return getTypeWithDefault(type, node.initializer); + } + function getTypeOfInitializer(node) { + // Return the cached type if one is available. If the type of the variable was inferred + // from its initializer, we'll already have cached the type. Otherwise we compute it now + // without caching such that transient types are reflected. + var links = getNodeLinks(node); + return links.resolvedType || getTypeOfExpression(node); + } + function getInitialTypeOfVariableDeclaration(node) { + if (node.initializer) { + return getTypeOfInitializer(node.initializer); + } + if (node.parent.parent.kind === 226 /* ForInStatement */) { + return stringType; + } + if (node.parent.parent.kind === 227 /* ForOfStatement */) { + return checkRightHandSideOfForOf(node.parent.parent.expression, node.parent.parent.awaitModifier) || errorType; + } + return errorType; + } + function getInitialType(node) { + return node.kind === 237 /* VariableDeclaration */ ? + getInitialTypeOfVariableDeclaration(node) : + getInitialTypeOfBindingElement(node); + } + function getInitialOrAssignedType(node, reference) { + return getConstraintForLocation(node.kind === 237 /* VariableDeclaration */ || node.kind === 186 /* BindingElement */ ? + getInitialType(node) : + getAssignedType(node), reference); + } + function isEmptyArrayAssignment(node) { + return node.kind === 237 /* VariableDeclaration */ && node.initializer && + isEmptyArrayLiteral(node.initializer) || + node.kind !== 186 /* BindingElement */ && node.parent.kind === 204 /* BinaryExpression */ && + isEmptyArrayLiteral(node.parent.right); + } + function getReferenceCandidate(node) { + switch (node.kind) { + case 195 /* ParenthesizedExpression */: + return getReferenceCandidate(node.expression); + case 204 /* BinaryExpression */: + switch (node.operatorToken.kind) { + case 59 /* EqualsToken */: + return getReferenceCandidate(node.left); + case 27 /* CommaToken */: + return getReferenceCandidate(node.right); + } + } + return node; + } + function getReferenceRoot(node) { + var parent = node.parent; + return parent.kind === 195 /* ParenthesizedExpression */ || + parent.kind === 204 /* BinaryExpression */ && parent.operatorToken.kind === 59 /* EqualsToken */ && parent.left === node || + parent.kind === 204 /* BinaryExpression */ && parent.operatorToken.kind === 27 /* CommaToken */ && parent.right === node ? + getReferenceRoot(parent) : node; + } + function getTypeOfSwitchClause(clause) { + if (clause.kind === 271 /* CaseClause */) { + return getRegularTypeOfLiteralType(getTypeOfExpression(clause.expression)); + } + return neverType; + } + function getSwitchClauseTypes(switchStatement) { + var links = getNodeLinks(switchStatement); + if (!links.switchTypes) { + links.switchTypes = []; + for (var _i = 0, _a = switchStatement.caseBlock.clauses; _i < _a.length; _i++) { + var clause = _a[_i]; + links.switchTypes.push(getTypeOfSwitchClause(clause)); + } + } + return links.switchTypes; + } + // Get the types from all cases in a switch on `typeof`. An + // `undefined` element denotes an explicit `default` clause. + function getSwitchClauseTypeOfWitnesses(switchStatement) { + var witnesses = []; + for (var _i = 0, _a = switchStatement.caseBlock.clauses; _i < _a.length; _i++) { + var clause = _a[_i]; + if (clause.kind === 271 /* CaseClause */) { + if (clause.expression.kind === 10 /* StringLiteral */) { + witnesses.push(clause.expression.text); + continue; + } + return ts.emptyArray; + } + witnesses.push(/*explicitDefaultStatement*/ undefined); + } + return witnesses; + } + function eachTypeContainedIn(source, types) { + return source.flags & 1048576 /* Union */ ? !ts.forEach(source.types, function (t) { return !ts.contains(types, t); }) : ts.contains(types, source); + } + function isTypeSubsetOf(source, target) { + return source === target || target.flags & 1048576 /* Union */ && isTypeSubsetOfUnion(source, target); + } + function isTypeSubsetOfUnion(source, target) { + if (source.flags & 1048576 /* Union */) { + for (var _i = 0, _a = source.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (!containsType(target.types, t)) { + return false; + } + } + return true; + } + if (source.flags & 1024 /* EnumLiteral */ && getBaseTypeOfEnumLiteralType(source) === target) { + return true; + } + return containsType(target.types, source); + } + function forEachType(type, f) { + return type.flags & 1048576 /* Union */ ? ts.forEach(type.types, f) : f(type); + } + function everyType(type, f) { + return type.flags & 1048576 /* Union */ ? ts.every(type.types, f) : f(type); + } + function filterType(type, f) { + if (type.flags & 1048576 /* Union */) { + var types = type.types; + var filtered = ts.filter(types, f); + return filtered === types ? type : getUnionTypeFromSortedList(filtered, type.primitiveTypesOnly); + } + return f(type) ? type : neverType; + } + function mapType(type, mapper, noReductions) { + if (type.flags & 131072 /* Never */) { + return type; + } + if (!(type.flags & 1048576 /* Union */)) { + return mapper(type); + } + var types = type.types; + var mappedType; + var mappedTypes; + for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { + var current = types_12[_i]; + var t = mapper(current); + if (t) { + if (!mappedType) { + mappedType = t; + } + else if (!mappedTypes) { + mappedTypes = [mappedType, t]; + } + else { + mappedTypes.push(t); + } + } + } + return mappedTypes ? getUnionType(mappedTypes, noReductions ? 0 /* None */ : 1 /* Literal */) : mappedType; + } + function extractTypesOfKind(type, kind) { + return filterType(type, function (t) { return (t.flags & kind) !== 0; }); + } + // Return a new type in which occurrences of the string and number primitive types in + // typeWithPrimitives have been replaced with occurrences of string literals and numeric + // literals in typeWithLiterals, respectively. + function replacePrimitivesWithLiterals(typeWithPrimitives, typeWithLiterals) { + if (isTypeSubsetOf(stringType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 128 /* StringLiteral */) || + isTypeSubsetOf(numberType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 256 /* NumberLiteral */) || + isTypeSubsetOf(bigintType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 2048 /* BigIntLiteral */)) { + return mapType(typeWithPrimitives, function (t) { + return t.flags & 4 /* String */ ? extractTypesOfKind(typeWithLiterals, 4 /* String */ | 128 /* StringLiteral */) : + t.flags & 8 /* Number */ ? extractTypesOfKind(typeWithLiterals, 8 /* Number */ | 256 /* NumberLiteral */) : + t.flags & 64 /* BigInt */ ? extractTypesOfKind(typeWithLiterals, 64 /* BigInt */ | 2048 /* BigIntLiteral */) : + t; + }); + } + return typeWithPrimitives; + } + function isIncomplete(flowType) { + return flowType.flags === 0; + } + function getTypeFromFlowType(flowType) { + return flowType.flags === 0 ? flowType.type : flowType; + } + function createFlowType(type, incomplete) { + return incomplete ? { flags: 0, type: type } : type; + } + // An evolving array type tracks the element types that have so far been seen in an + // 'x.push(value)' or 'x[n] = value' operation along the control flow graph. Evolving + // array types are ultimately converted into manifest array types (using getFinalArrayType) + // and never escape the getFlowTypeOfReference function. + function createEvolvingArrayType(elementType) { + var result = createObjectType(256 /* EvolvingArray */); + result.elementType = elementType; + return result; + } + function getEvolvingArrayType(elementType) { + return evolvingArrayTypes[elementType.id] || (evolvingArrayTypes[elementType.id] = createEvolvingArrayType(elementType)); + } + // When adding evolving array element types we do not perform subtype reduction. Instead, + // we defer subtype reduction until the evolving array type is finalized into a manifest + // array type. + function addEvolvingArrayElementType(evolvingArrayType, node) { + var elementType = getBaseTypeOfLiteralType(getContextFreeTypeOfExpression(node)); + return isTypeSubsetOf(elementType, evolvingArrayType.elementType) ? evolvingArrayType : getEvolvingArrayType(getUnionType([evolvingArrayType.elementType, elementType])); + } + function createFinalArrayType(elementType) { + return elementType.flags & 131072 /* Never */ ? + autoArrayType : + createArrayType(elementType.flags & 1048576 /* Union */ ? + getUnionType(elementType.types, 2 /* Subtype */) : + elementType); + } + // We perform subtype reduction upon obtaining the final array type from an evolving array type. + function getFinalArrayType(evolvingArrayType) { + return evolvingArrayType.finalArrayType || (evolvingArrayType.finalArrayType = createFinalArrayType(evolvingArrayType.elementType)); + } + function finalizeEvolvingArrayType(type) { + return ts.getObjectFlags(type) & 256 /* EvolvingArray */ ? getFinalArrayType(type) : type; + } + function getElementTypeOfEvolvingArrayType(type) { + return ts.getObjectFlags(type) & 256 /* EvolvingArray */ ? type.elementType : neverType; + } + function isEvolvingArrayTypeList(types) { + var hasEvolvingArrayType = false; + for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { + var t = types_13[_i]; + if (!(t.flags & 131072 /* Never */)) { + if (!(ts.getObjectFlags(t) & 256 /* EvolvingArray */)) { + return false; + } + hasEvolvingArrayType = true; + } + } + return hasEvolvingArrayType; + } + // At flow control branch or loop junctions, if the type along every antecedent code path + // is an evolving array type, we construct a combined evolving array type. Otherwise we + // finalize all evolving array types. + function getUnionOrEvolvingArrayType(types, subtypeReduction) { + return isEvolvingArrayTypeList(types) ? + getEvolvingArrayType(getUnionType(ts.map(types, getElementTypeOfEvolvingArrayType))) : + getUnionType(ts.sameMap(types, finalizeEvolvingArrayType), subtypeReduction); + } + // Return true if the given node is 'x' in an 'x.length', x.push(value)', 'x.unshift(value)' or + // 'x[n] = value' operation, where 'n' is an expression of type any, undefined, or a number-like type. + function isEvolvingArrayOperationTarget(node) { + var root = getReferenceRoot(node); + var parent = root.parent; + var isLengthPushOrUnshift = parent.kind === 189 /* PropertyAccessExpression */ && (parent.name.escapedText === "length" || + parent.parent.kind === 191 /* CallExpression */ && ts.isPushOrUnshiftIdentifier(parent.name)); + var isElementAssignment = parent.kind === 190 /* ElementAccessExpression */ && + parent.expression === root && + parent.parent.kind === 204 /* BinaryExpression */ && + parent.parent.operatorToken.kind === 59 /* EqualsToken */ && + parent.parent.left === parent && + !ts.isAssignmentTarget(parent.parent) && + isTypeAssignableToKind(getTypeOfExpression(parent.argumentExpression), 296 /* NumberLike */); + return isLengthPushOrUnshift || isElementAssignment; + } + function maybeTypePredicateCall(node) { + var links = getNodeLinks(node); + if (links.maybeTypePredicate === undefined) { + links.maybeTypePredicate = getMaybeTypePredicate(node); + } + return links.maybeTypePredicate; + } + function getMaybeTypePredicate(node) { + if (node.expression.kind !== 98 /* SuperKeyword */) { + var funcType = checkNonNullExpression(node.expression); + if (funcType !== silentNeverType) { + var apparentType = getApparentType(funcType); + return apparentType !== errorType && ts.some(getSignaturesOfType(apparentType, 0 /* Call */), signatureHasTypePredicate); + } + } + return false; + } + function reportFlowControlError(node) { + var block = ts.findAncestor(node, ts.isFunctionOrModuleBlock); + var sourceFile = ts.getSourceFileOfNode(node); + var span = ts.getSpanOfTokenAtPosition(sourceFile, block.statements.pos); + diagnostics.add(ts.createFileDiagnostic(sourceFile, span.start, span.length, ts.Diagnostics.The_containing_function_or_module_body_is_too_large_for_control_flow_analysis)); + } + function getFlowTypeOfReference(reference, declaredType, initialType, flowContainer, couldBeUninitialized) { + if (initialType === void 0) { initialType = declaredType; } + var key; + var flowDepth = 0; + if (flowAnalysisDisabled) { + return errorType; + } + if (!reference.flowNode || !couldBeUninitialized && !(declaredType.flags & 133970943 /* Narrowable */)) { + return declaredType; + } + var sharedFlowStart = sharedFlowCount; + var evolvedType = getTypeFromFlowType(getTypeAtFlowNode(reference.flowNode)); + sharedFlowCount = sharedFlowStart; + // When the reference is 'x' in an 'x.length', 'x.push(value)', 'x.unshift(value)' or x[n] = value' operation, + // we give type 'any[]' to 'x' instead of using the type determined by control flow analysis such that operations + // on empty arrays are possible without implicit any errors and new element types can be inferred without + // type mismatch errors. + var resultType = ts.getObjectFlags(evolvedType) & 256 /* EvolvingArray */ && isEvolvingArrayOperationTarget(reference) ? autoArrayType : finalizeEvolvingArrayType(evolvedType); + if (reference.parent && reference.parent.kind === 213 /* NonNullExpression */ && getTypeWithFacts(resultType, 2097152 /* NEUndefinedOrNull */).flags & 131072 /* Never */) { + return declaredType; + } + return resultType; + function getTypeAtFlowNode(flow) { + if (flowDepth === 2000) { + // We have made 2000 recursive invocations. To avoid overflowing the call stack we report an error + // and disable further control flow analysis in the containing function or module body. + flowAnalysisDisabled = true; + reportFlowControlError(reference); + return errorType; + } + flowDepth++; + while (true) { + var flags = flow.flags; + if (flags & 1024 /* Shared */) { + // We cache results of flow type resolution for shared nodes that were previously visited in + // the same getFlowTypeOfReference invocation. A node is considered shared when it is the + // antecedent of more than one node. + for (var i = sharedFlowStart; i < sharedFlowCount; i++) { + if (sharedFlowNodes[i] === flow) { + flowDepth--; + return sharedFlowTypes[i]; + } + } + } + var type = void 0; + if (flags & 4096 /* AfterFinally */) { + // block flow edge: finally -> pre-try (for larger explanation check comment in binder.ts - bindTryStatement + flow.locked = true; + type = getTypeAtFlowNode(flow.antecedent); + flow.locked = false; + } + else if (flags & 2048 /* PreFinally */) { + // locked pre-finally flows are filtered out in getTypeAtFlowBranchLabel + // so here just redirect to antecedent + flow = flow.antecedent; + continue; + } + else if (flags & 16 /* Assignment */) { + type = getTypeAtFlowAssignment(flow); + if (!type) { + flow = flow.antecedent; + continue; + } + } + else if (flags & 96 /* Condition */) { + type = getTypeAtFlowCondition(flow); + } + else if (flags & 128 /* SwitchClause */) { + type = getTypeAtSwitchClause(flow); + } + else if (flags & 12 /* Label */) { + if (flow.antecedents.length === 1) { + flow = flow.antecedents[0]; + continue; + } + type = flags & 4 /* BranchLabel */ ? + getTypeAtFlowBranchLabel(flow) : + getTypeAtFlowLoopLabel(flow); + } + else if (flags & 256 /* ArrayMutation */) { + type = getTypeAtFlowArrayMutation(flow); + if (!type) { + flow = flow.antecedent; + continue; + } + } + else if (flags & 2 /* Start */) { + // Check if we should continue with the control flow of the containing function. + var container = flow.container; + if (container && container !== flowContainer && + reference.kind !== 189 /* PropertyAccessExpression */ && + reference.kind !== 190 /* ElementAccessExpression */ && + reference.kind !== 100 /* ThisKeyword */) { + flow = container.flowNode; + continue; + } + // At the top of the flow we have the initial type. + type = initialType; + } + else { + // Unreachable code errors are reported in the binding phase. Here we + // simply return the non-auto declared type to reduce follow-on errors. + type = convertAutoToAny(declaredType); + } + if (flags & 1024 /* Shared */) { + // Record visited node and the associated type in the cache. + sharedFlowNodes[sharedFlowCount] = flow; + sharedFlowTypes[sharedFlowCount] = type; + sharedFlowCount++; + } + flowDepth--; + return type; + } + } + function getTypeAtFlowAssignment(flow) { + var node = flow.node; + // Assignments only narrow the computed type if the declared type is a union type. Thus, we + // only need to evaluate the assigned type if the declared type is a union type. + if (isMatchingReference(reference, node)) { + if (ts.getAssignmentTargetKind(node) === 2 /* Compound */) { + var flowType = getTypeAtFlowNode(flow.antecedent); + return createFlowType(getBaseTypeOfLiteralType(getTypeFromFlowType(flowType)), isIncomplete(flowType)); + } + if (declaredType === autoType || declaredType === autoArrayType) { + if (isEmptyArrayAssignment(node)) { + return getEvolvingArrayType(neverType); + } + var assignedType = getBaseTypeOfLiteralType(getInitialOrAssignedType(node, reference)); + return isTypeAssignableTo(assignedType, declaredType) ? assignedType : anyArrayType; + } + if (declaredType.flags & 1048576 /* Union */) { + return getAssignmentReducedType(declaredType, getInitialOrAssignedType(node, reference)); + } + return declaredType; + } + // We didn't have a direct match. However, if the reference is a dotted name, this + // may be an assignment to a left hand part of the reference. For example, for a + // reference 'x.y.z', we may be at an assignment to 'x.y' or 'x'. In that case, + // return the declared type. + if (containsMatchingReference(reference, node)) { + // A matching dotted name might also be an expando property on a function *expression*, + // in which case we continue control flow analysis back to the function's declaration + if (ts.isVariableDeclaration(node) && (ts.isInJSFile(node) || ts.isVarConst(node))) { + var init = ts.getDeclaredExpandoInitializer(node); + if (init && (init.kind === 196 /* FunctionExpression */ || init.kind === 197 /* ArrowFunction */)) { + return getTypeAtFlowNode(flow.antecedent); + } + } + return declaredType; + } + // for (const _ in ref) acts as a nonnull on ref + if (ts.isVariableDeclaration(node) && node.parent.parent.kind === 226 /* ForInStatement */ && isMatchingReference(reference, node.parent.parent.expression)) { + return getNonNullableTypeIfNeeded(getTypeFromFlowType(getTypeAtFlowNode(flow.antecedent))); + } + // Assignment doesn't affect reference + return undefined; + } + function getTypeAtFlowArrayMutation(flow) { + if (declaredType === autoType || declaredType === autoArrayType) { + var node = flow.node; + var expr = node.kind === 191 /* CallExpression */ ? + node.expression.expression : + node.left.expression; + if (isMatchingReference(reference, getReferenceCandidate(expr))) { + var flowType = getTypeAtFlowNode(flow.antecedent); + var type = getTypeFromFlowType(flowType); + if (ts.getObjectFlags(type) & 256 /* EvolvingArray */) { + var evolvedType_1 = type; + if (node.kind === 191 /* CallExpression */) { + for (var _i = 0, _a = node.arguments; _i < _a.length; _i++) { + var arg = _a[_i]; + evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, arg); + } + } + else { + // We must get the context free expression type so as to not recur in an uncached fashion on the LHS (which causes exponential blowup in compile time) + var indexType = getContextFreeTypeOfExpression(node.left.argumentExpression); + if (isTypeAssignableToKind(indexType, 296 /* NumberLike */)) { + evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, node.right); + } + } + return evolvedType_1 === type ? flowType : createFlowType(evolvedType_1, isIncomplete(flowType)); + } + return flowType; + } + } + return undefined; + } + function getTypeAtFlowCondition(flow) { + var flowType = getTypeAtFlowNode(flow.antecedent); + var type = getTypeFromFlowType(flowType); + if (type.flags & 131072 /* Never */) { + return flowType; + } + // If we have an antecedent type (meaning we're reachable in some way), we first + // attempt to narrow the antecedent type. If that produces the never type, and if + // the antecedent type is incomplete (i.e. a transient type in a loop), then we + // take the type guard as an indication that control *could* reach here once we + // have the complete type. We proceed by switching to the silent never type which + // doesn't report errors when operators are applied to it. Note that this is the + // *only* place a silent never type is ever generated. + var assumeTrue = (flow.flags & 32 /* TrueCondition */) !== 0; + var nonEvolvingType = finalizeEvolvingArrayType(type); + var narrowedType = narrowType(nonEvolvingType, flow.expression, assumeTrue); + if (narrowedType === nonEvolvingType) { + return flowType; + } + var incomplete = isIncomplete(flowType); + var resultType = incomplete && narrowedType.flags & 131072 /* Never */ ? silentNeverType : narrowedType; + return createFlowType(resultType, incomplete); + } + function getTypeAtSwitchClause(flow) { + var expr = flow.switchStatement.expression; + if (containsMatchingReferenceDiscriminant(reference, expr)) { + return declaredType; + } + var flowType = getTypeAtFlowNode(flow.antecedent); + var type = getTypeFromFlowType(flowType); + if (isMatchingReference(reference, expr)) { + type = narrowTypeBySwitchOnDiscriminant(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); + } + else if (isMatchingReferenceDiscriminant(expr, type)) { + type = narrowTypeByDiscriminant(type, expr, function (t) { return narrowTypeBySwitchOnDiscriminant(t, flow.switchStatement, flow.clauseStart, flow.clauseEnd); }); + } + else if (expr.kind === 199 /* TypeOfExpression */ && isMatchingReference(reference, expr.expression)) { + type = narrowBySwitchOnTypeOf(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); + } + return createFlowType(type, isIncomplete(flowType)); + } + function getTypeAtFlowBranchLabel(flow) { + var antecedentTypes = []; + var subtypeReduction = false; + var seenIncomplete = false; + for (var _i = 0, _a = flow.antecedents; _i < _a.length; _i++) { + var antecedent = _a[_i]; + if (antecedent.flags & 2048 /* PreFinally */ && antecedent.lock.locked) { + // if flow correspond to branch from pre-try to finally and this branch is locked - this means that + // we initially have started following the flow outside the finally block. + // in this case we should ignore this branch. + continue; + } + var flowType = getTypeAtFlowNode(antecedent); + var type = getTypeFromFlowType(flowType); + // If the type at a particular antecedent path is the declared type and the + // reference is known to always be assigned (i.e. when declared and initial types + // are the same), there is no reason to process more antecedents since the only + // possible outcome is subtypes that will be removed in the final union type anyway. + if (type === declaredType && declaredType === initialType) { + return type; + } + ts.pushIfUnique(antecedentTypes, type); + // If an antecedent type is not a subset of the declared type, we need to perform + // subtype reduction. This happens when a "foreign" type is injected into the control + // flow using the instanceof operator or a user defined type predicate. + if (!isTypeSubsetOf(type, declaredType)) { + subtypeReduction = true; + } + if (isIncomplete(flowType)) { + seenIncomplete = true; + } + } + return createFlowType(getUnionOrEvolvingArrayType(antecedentTypes, subtypeReduction ? 2 /* Subtype */ : 1 /* Literal */), seenIncomplete); + } + function getTypeAtFlowLoopLabel(flow) { + // If we have previously computed the control flow type for the reference at + // this flow loop junction, return the cached type. + var id = getFlowNodeId(flow); + var cache = flowLoopCaches[id] || (flowLoopCaches[id] = ts.createMap()); + if (!key) { + key = getFlowCacheKey(reference); + // No cache key is generated when binding patterns are in unnarrowable situations + if (!key) { + return declaredType; + } + } + var cached = cache.get(key); + if (cached) { + return cached; + } + // If this flow loop junction and reference are already being processed, return + // the union of the types computed for each branch so far, marked as incomplete. + // It is possible to see an empty array in cases where loops are nested and the + // back edge of the outer loop reaches an inner loop that is already being analyzed. + // In such cases we restart the analysis of the inner loop, which will then see + // a non-empty in-process array for the outer loop and eventually terminate because + // the first antecedent of a loop junction is always the non-looping control flow + // path that leads to the top. + for (var i = flowLoopStart; i < flowLoopCount; i++) { + if (flowLoopNodes[i] === flow && flowLoopKeys[i] === key && flowLoopTypes[i].length) { + return createFlowType(getUnionOrEvolvingArrayType(flowLoopTypes[i], 1 /* Literal */), /*incomplete*/ true); + } + } + // Add the flow loop junction and reference to the in-process stack and analyze + // each antecedent code path. + var antecedentTypes = []; + var subtypeReduction = false; + var firstAntecedentType; + flowLoopNodes[flowLoopCount] = flow; + flowLoopKeys[flowLoopCount] = key; + flowLoopTypes[flowLoopCount] = antecedentTypes; + for (var _i = 0, _a = flow.antecedents; _i < _a.length; _i++) { + var antecedent = _a[_i]; + flowLoopCount++; + var flowType = getTypeAtFlowNode(antecedent); + flowLoopCount--; + if (!firstAntecedentType) { + firstAntecedentType = flowType; + } + var type = getTypeFromFlowType(flowType); + // If we see a value appear in the cache it is a sign that control flow analysis + // was restarted and completed by checkExpressionCached. We can simply pick up + // the resulting type and bail out. + var cached_1 = cache.get(key); + if (cached_1) { + return cached_1; + } + ts.pushIfUnique(antecedentTypes, type); + // If an antecedent type is not a subset of the declared type, we need to perform + // subtype reduction. This happens when a "foreign" type is injected into the control + // flow using the instanceof operator or a user defined type predicate. + if (!isTypeSubsetOf(type, declaredType)) { + subtypeReduction = true; + } + // If the type at a particular antecedent path is the declared type there is no + // reason to process more antecedents since the only possible outcome is subtypes + // that will be removed in the final union type anyway. + if (type === declaredType) { + break; + } + } + // The result is incomplete if the first antecedent (the non-looping control flow path) + // is incomplete. + var result = getUnionOrEvolvingArrayType(antecedentTypes, subtypeReduction ? 2 /* Subtype */ : 1 /* Literal */); + if (isIncomplete(firstAntecedentType)) { + return createFlowType(result, /*incomplete*/ true); + } + cache.set(key, result); + return result; + } + function isMatchingReferenceDiscriminant(expr, computedType) { + if (!(computedType.flags & 1048576 /* Union */) || + expr.kind !== 189 /* PropertyAccessExpression */ && expr.kind !== 190 /* ElementAccessExpression */) { + return false; + } + var access = expr; + var name = getAccessedPropertyName(access); + if (!name) { + return false; + } + return isMatchingReference(reference, access.expression) && isDiscriminantProperty(computedType, name); + } + function narrowTypeByDiscriminant(type, access, narrowType) { + var propName = getAccessedPropertyName(access); + if (!propName) { + return type; + } + var propType = getTypeOfPropertyOfType(type, propName); + var narrowedPropType = propType && narrowType(propType); + return propType === narrowedPropType ? type : filterType(type, function (t) { return isTypeComparableTo(getTypeOfPropertyOfType(t, propName), narrowedPropType); }); + } + function narrowTypeByTruthiness(type, expr, assumeTrue) { + if (isMatchingReference(reference, expr)) { + return getTypeWithFacts(type, assumeTrue ? 4194304 /* Truthy */ : 8388608 /* Falsy */); + } + if (isMatchingReferenceDiscriminant(expr, declaredType)) { + return narrowTypeByDiscriminant(type, expr, function (t) { return getTypeWithFacts(t, assumeTrue ? 4194304 /* Truthy */ : 8388608 /* Falsy */); }); + } + if (containsMatchingReferenceDiscriminant(reference, expr)) { + return declaredType; + } + return type; + } + function isTypePresencePossible(type, propName, assumeTrue) { + if (getIndexInfoOfType(type, 0 /* String */)) { + return true; + } + var prop = getPropertyOfType(type, propName); + if (prop) { + return prop.flags & 16777216 /* Optional */ ? true : assumeTrue; + } + return !assumeTrue; + } + function narrowByInKeyword(type, literal, assumeTrue) { + if ((type.flags & (1048576 /* Union */ | 524288 /* Object */)) || (type.flags & 262144 /* TypeParameter */ && type.isThisType)) { + var propName_1 = ts.escapeLeadingUnderscores(literal.text); + return filterType(type, function (t) { return isTypePresencePossible(t, propName_1, assumeTrue); }); + } + return type; + } + function narrowTypeByBinaryExpression(type, expr, assumeTrue) { + switch (expr.operatorToken.kind) { + case 59 /* EqualsToken */: + return narrowTypeByTruthiness(type, expr.left, assumeTrue); + case 33 /* EqualsEqualsToken */: + case 34 /* ExclamationEqualsToken */: + case 35 /* EqualsEqualsEqualsToken */: + case 36 /* ExclamationEqualsEqualsToken */: + var operator_1 = expr.operatorToken.kind; + var left_1 = getReferenceCandidate(expr.left); + var right_1 = getReferenceCandidate(expr.right); + if (left_1.kind === 199 /* TypeOfExpression */ && ts.isStringLiteralLike(right_1)) { + return narrowTypeByTypeof(type, left_1, operator_1, right_1, assumeTrue); + } + if (right_1.kind === 199 /* TypeOfExpression */ && ts.isStringLiteralLike(left_1)) { + return narrowTypeByTypeof(type, right_1, operator_1, left_1, assumeTrue); + } + if (isMatchingReference(reference, left_1)) { + return narrowTypeByEquality(type, operator_1, right_1, assumeTrue); + } + if (isMatchingReference(reference, right_1)) { + return narrowTypeByEquality(type, operator_1, left_1, assumeTrue); + } + if (isMatchingReferenceDiscriminant(left_1, declaredType)) { + return narrowTypeByDiscriminant(type, left_1, function (t) { return narrowTypeByEquality(t, operator_1, right_1, assumeTrue); }); + } + if (isMatchingReferenceDiscriminant(right_1, declaredType)) { + return narrowTypeByDiscriminant(type, right_1, function (t) { return narrowTypeByEquality(t, operator_1, left_1, assumeTrue); }); + } + if (containsMatchingReferenceDiscriminant(reference, left_1) || containsMatchingReferenceDiscriminant(reference, right_1)) { + return declaredType; + } + break; + case 94 /* InstanceOfKeyword */: + return narrowTypeByInstanceof(type, expr, assumeTrue); + case 93 /* InKeyword */: + var target = getReferenceCandidate(expr.right); + if (ts.isStringLiteralLike(expr.left) && isMatchingReference(reference, target)) { + return narrowByInKeyword(type, expr.left, assumeTrue); + } + break; + case 27 /* CommaToken */: + return narrowType(type, expr.right, assumeTrue); + } + return type; + } + function narrowTypeByEquality(type, operator, value, assumeTrue) { + if (type.flags & 1 /* Any */) { + return type; + } + if (operator === 34 /* ExclamationEqualsToken */ || operator === 36 /* ExclamationEqualsEqualsToken */) { + assumeTrue = !assumeTrue; + } + var valueType = getTypeOfExpression(value); + if (valueType.flags & 98304 /* Nullable */) { + if (!strictNullChecks) { + return type; + } + var doubleEquals = operator === 33 /* EqualsEqualsToken */ || operator === 34 /* ExclamationEqualsToken */; + var facts = doubleEquals ? + assumeTrue ? 262144 /* EQUndefinedOrNull */ : 2097152 /* NEUndefinedOrNull */ : + valueType.flags & 65536 /* Null */ ? + assumeTrue ? 131072 /* EQNull */ : 1048576 /* NENull */ : + assumeTrue ? 65536 /* EQUndefined */ : 524288 /* NEUndefined */; + return getTypeWithFacts(type, facts); + } + if (type.flags & 67637251 /* NotUnionOrUnit */) { + return type; + } + if (assumeTrue) { + var narrowedType = filterType(type, function (t) { return areTypesComparable(t, valueType); }); + return narrowedType.flags & 131072 /* Never */ ? type : replacePrimitivesWithLiterals(narrowedType, valueType); + } + if (isUnitType(valueType)) { + var regularType_1 = getRegularTypeOfLiteralType(valueType); + return filterType(type, function (t) { return getRegularTypeOfLiteralType(t) !== regularType_1; }); + } + return type; + } + function narrowTypeByTypeof(type, typeOfExpr, operator, literal, assumeTrue) { + // We have '==', '!=', '====', or !==' operator with 'typeof xxx' and string literal operands + var target = getReferenceCandidate(typeOfExpr.expression); + if (!isMatchingReference(reference, target)) { + // For a reference of the form 'x.y', where 'x' has a narrowable declared type, a + // 'typeof x === ...' type guard resets the narrowed type of 'y' to its declared type. + if (containsMatchingReference(reference, target) && hasNarrowableDeclaredType(target)) { + return declaredType; + } + return type; + } + if (operator === 34 /* ExclamationEqualsToken */ || operator === 36 /* ExclamationEqualsEqualsToken */) { + assumeTrue = !assumeTrue; + } + if (type.flags & 1 /* Any */ && literal.text === "function") { + return type; + } + var facts = assumeTrue ? + typeofEQFacts.get(literal.text) || 128 /* TypeofEQHostObject */ : + typeofNEFacts.get(literal.text) || 32768 /* TypeofNEHostObject */; + return getTypeWithFacts(assumeTrue ? mapType(type, narrowTypeForTypeof) : type, facts); + function narrowTypeForTypeof(type) { + if (type.flags & 2 /* Unknown */ && literal.text === "object") { + return getUnionType([nonPrimitiveType, nullType]); + } + // We narrow a non-union type to an exact primitive type if the non-union type + // is a supertype of that primitive type. For example, type 'any' can be narrowed + // to one of the primitive types. + var targetType = literal.text === "function" ? globalFunctionType : typeofTypesByName.get(literal.text); + if (targetType) { + if (isTypeSubtypeOf(type, targetType)) { + return type; + } + if (isTypeSubtypeOf(targetType, type)) { + return targetType; + } + if (type.flags & 63176704 /* Instantiable */) { + var constraint = getBaseConstraintOfType(type) || anyType; + if (isTypeSubtypeOf(targetType, constraint)) { + return getIntersectionType([type, targetType]); + } + } + } + return type; + } + } + function narrowTypeBySwitchOnDiscriminant(type, switchStatement, clauseStart, clauseEnd) { + // We only narrow if all case expressions specify values with unit types + var switchTypes = getSwitchClauseTypes(switchStatement); + if (!switchTypes.length) { + return type; + } + var clauseTypes = switchTypes.slice(clauseStart, clauseEnd); + var hasDefaultClause = clauseStart === clauseEnd || ts.contains(clauseTypes, neverType); + var discriminantType = getUnionType(clauseTypes); + var caseType = discriminantType.flags & 131072 /* Never */ ? neverType : + replacePrimitivesWithLiterals(filterType(type, function (t) { return areTypesComparable(discriminantType, t); }), discriminantType); + if (!hasDefaultClause) { + return caseType; + } + var defaultType = filterType(type, function (t) { return !(isUnitType(t) && ts.contains(switchTypes, getRegularTypeOfLiteralType(t))); }); + return caseType.flags & 131072 /* Never */ ? defaultType : getUnionType([caseType, defaultType]); + } + function getImpliedTypeFromTypeofCase(type, text) { + switch (text) { + case "function": + return type.flags & 1 /* Any */ ? type : globalFunctionType; + case "object": + return type.flags & 2 /* Unknown */ ? getUnionType([nonPrimitiveType, nullType]) : type; + default: + return typeofTypesByName.get(text) || type; + } + } + function narrowTypeForTypeofSwitch(candidate) { + return function (type) { + if (isTypeSubtypeOf(candidate, type)) { + return candidate; + } + if (type.flags & 63176704 /* Instantiable */) { + var constraint = getBaseConstraintOfType(type) || anyType; + if (isTypeSubtypeOf(candidate, constraint)) { + return getIntersectionType([type, candidate]); + } + } + return type; + }; + } + function narrowBySwitchOnTypeOf(type, switchStatement, clauseStart, clauseEnd) { + var switchWitnesses = getSwitchClauseTypeOfWitnesses(switchStatement); + if (!switchWitnesses.length) { + return type; + } + // Equal start and end denotes implicit fallthrough; undefined marks explicit default clause + var defaultCaseLocation = ts.findIndex(switchWitnesses, function (elem) { return elem === undefined; }); + var hasDefaultClause = clauseStart === clauseEnd || (defaultCaseLocation >= clauseStart && defaultCaseLocation < clauseEnd); + var clauseWitnesses; + var switchFacts; + if (defaultCaseLocation > -1) { + // We no longer need the undefined denoting an + // explicit default case. Remove the undefined and + // fix-up clauseStart and clauseEnd. This means + // that we don't have to worry about undefined + // in the witness array. + var witnesses = switchWitnesses.filter(function (witness) { return witness !== undefined; }); + // The adjusted clause start and end after removing the `default` statement. + var fixedClauseStart = defaultCaseLocation < clauseStart ? clauseStart - 1 : clauseStart; + var fixedClauseEnd = defaultCaseLocation < clauseEnd ? clauseEnd - 1 : clauseEnd; + clauseWitnesses = witnesses.slice(fixedClauseStart, fixedClauseEnd); + switchFacts = getFactsFromTypeofSwitch(fixedClauseStart, fixedClauseEnd, witnesses, hasDefaultClause); + } + else { + clauseWitnesses = switchWitnesses.slice(clauseStart, clauseEnd); + switchFacts = getFactsFromTypeofSwitch(clauseStart, clauseEnd, switchWitnesses, hasDefaultClause); + } + if (hasDefaultClause) { + return filterType(type, function (t) { return (getTypeFacts(t) & switchFacts) === switchFacts; }); + } + /* + The implied type is the raw type suggested by a + value being caught in this clause. + + When the clause contains a default case we ignore + the implied type and try to narrow using any facts + we can learn: see `switchFacts`. + + Example: + switch (typeof x) { + case 'number': + case 'string': break; + default: break; + case 'number': + case 'boolean': break + } + + In the first clause (case `number` and `string`) the + implied type is number | string. + + In the default clause we de not compute an implied type. + + In the third clause (case `number` and `boolean`) + the naive implied type is number | boolean, however + we use the type facts to narrow the implied type to + boolean. We know that number cannot be selected + because it is caught in the first clause. + */ + var impliedType = getTypeWithFacts(getUnionType(clauseWitnesses.map(function (text) { return getImpliedTypeFromTypeofCase(type, text); })), switchFacts); + if (impliedType.flags & 1048576 /* Union */) { + impliedType = getAssignmentReducedType(impliedType, getBaseConstraintOrType(type)); + } + return getTypeWithFacts(mapType(type, narrowTypeForTypeofSwitch(impliedType)), switchFacts); + } + function narrowTypeByInstanceof(type, expr, assumeTrue) { + var left = getReferenceCandidate(expr.left); + if (!isMatchingReference(reference, left)) { + // For a reference of the form 'x.y', where 'x' has a narrowable declared type, an + // 'x instanceof T' type guard resets the narrowed type of 'y' to its declared type. + if (containsMatchingReference(reference, left) && hasNarrowableDeclaredType(left)) { + return declaredType; + } + return type; + } + // Check that right operand is a function type with a prototype property + var rightType = getTypeOfExpression(expr.right); + if (!isTypeDerivedFrom(rightType, globalFunctionType)) { + return type; + } + var targetType; + var prototypeProperty = getPropertyOfType(rightType, "prototype"); + if (prototypeProperty) { + // Target type is type of the prototype property + var prototypePropertyType = getTypeOfSymbol(prototypeProperty); + if (!isTypeAny(prototypePropertyType)) { + targetType = prototypePropertyType; + } + } + // Don't narrow from 'any' if the target type is exactly 'Object' or 'Function' + if (isTypeAny(type) && (targetType === globalObjectType || targetType === globalFunctionType)) { + return type; + } + if (!targetType) { + var constructSignatures = getSignaturesOfType(rightType, 1 /* Construct */); + targetType = constructSignatures.length ? + getUnionType(ts.map(constructSignatures, function (signature) { return getReturnTypeOfSignature(getErasedSignature(signature)); })) : + emptyObjectType; + } + return getNarrowedType(type, targetType, assumeTrue, isTypeDerivedFrom); + } + function getNarrowedType(type, candidate, assumeTrue, isRelated) { + if (!assumeTrue) { + return filterType(type, function (t) { return !isRelated(t, candidate); }); + } + // If the current type is a union type, remove all constituents that couldn't be instances of + // the candidate type. If one or more constituents remain, return a union of those. + if (type.flags & 1048576 /* Union */) { + var assignableType = filterType(type, function (t) { return isRelated(t, candidate); }); + if (!(assignableType.flags & 131072 /* Never */)) { + return assignableType; + } + } + // If the candidate type is a subtype of the target type, narrow to the candidate type. + // Otherwise, if the target type is assignable to the candidate type, keep the target type. + // Otherwise, if the candidate type is assignable to the target type, narrow to the candidate + // type. Otherwise, the types are completely unrelated, so narrow to an intersection of the + // two types. + return isTypeSubtypeOf(candidate, type) ? candidate : + isTypeAssignableTo(type, candidate) ? type : + isTypeAssignableTo(candidate, type) ? candidate : + getIntersectionType([type, candidate]); + } + function narrowTypeByTypePredicate(type, callExpression, assumeTrue) { + if (!hasMatchingArgument(callExpression, reference) || !maybeTypePredicateCall(callExpression)) { + return type; + } + var signature = getResolvedSignature(callExpression); + var predicate = getTypePredicateOfSignature(signature); + if (!predicate) { + return type; + } + // Don't narrow from 'any' if the predicate type is exactly 'Object' or 'Function' + if (isTypeAny(type) && (predicate.type === globalObjectType || predicate.type === globalFunctionType)) { + return type; + } + if (ts.isIdentifierTypePredicate(predicate)) { + var predicateArgument = callExpression.arguments[predicate.parameterIndex - (signature.thisParameter ? 1 : 0)]; + if (predicateArgument) { + if (isMatchingReference(reference, predicateArgument)) { + return getNarrowedType(type, predicate.type, assumeTrue, isTypeSubtypeOf); + } + if (containsMatchingReference(reference, predicateArgument)) { + return declaredType; + } + } + } + else { + var invokedExpression = ts.skipParentheses(callExpression.expression); + if (invokedExpression.kind === 190 /* ElementAccessExpression */ || invokedExpression.kind === 189 /* PropertyAccessExpression */) { + var accessExpression = invokedExpression; + var possibleReference = ts.skipParentheses(accessExpression.expression); + if (isMatchingReference(reference, possibleReference)) { + return getNarrowedType(type, predicate.type, assumeTrue, isTypeSubtypeOf); + } + if (containsMatchingReference(reference, possibleReference)) { + return declaredType; + } + } + } + return type; + } + // Narrow the given type based on the given expression having the assumed boolean value. The returned type + // will be a subtype or the same type as the argument. + function narrowType(type, expr, assumeTrue) { + switch (expr.kind) { + case 72 /* Identifier */: + case 100 /* ThisKeyword */: + case 98 /* SuperKeyword */: + case 189 /* PropertyAccessExpression */: + case 190 /* ElementAccessExpression */: + return narrowTypeByTruthiness(type, expr, assumeTrue); + case 191 /* CallExpression */: + return narrowTypeByTypePredicate(type, expr, assumeTrue); + case 195 /* ParenthesizedExpression */: + return narrowType(type, expr.expression, assumeTrue); + case 204 /* BinaryExpression */: + return narrowTypeByBinaryExpression(type, expr, assumeTrue); + case 202 /* PrefixUnaryExpression */: + if (expr.operator === 52 /* ExclamationToken */) { + return narrowType(type, expr.operand, !assumeTrue); + } + break; + } + return type; + } + } + function getTypeOfSymbolAtLocation(symbol, location) { + symbol = symbol.exportSymbol || symbol; + // If we have an identifier or a property access at the given location, if the location is + // an dotted name expression, and if the location is not an assignment target, obtain the type + // of the expression (which will reflect control flow analysis). If the expression indeed + // resolved to the given symbol, return the narrowed type. + if (location.kind === 72 /* Identifier */) { + if (ts.isRightSideOfQualifiedNameOrPropertyAccess(location)) { + location = location.parent; + } + if (ts.isExpressionNode(location) && !ts.isAssignmentTarget(location)) { + var type = getTypeOfExpression(location); + if (getExportSymbolOfValueSymbolIfExported(getNodeLinks(location).resolvedSymbol) === symbol) { + return type; + } + } + } + // The location isn't a reference to the given symbol, meaning we're being asked + // a hypothetical question of what type the symbol would have if there was a reference + // to it at the given location. Since we have no control flow information for the + // hypothetical reference (control flow information is created and attached by the + // binder), we simply return the declared type of the symbol. + return getTypeOfSymbol(symbol); + } + function getControlFlowContainer(node) { + return ts.findAncestor(node.parent, function (node) { + return ts.isFunctionLike(node) && !ts.getImmediatelyInvokedFunctionExpression(node) || + node.kind === 245 /* ModuleBlock */ || + node.kind === 279 /* SourceFile */ || + node.kind === 154 /* PropertyDeclaration */; + }); + } + // Check if a parameter is assigned anywhere within its declaring function. + function isParameterAssigned(symbol) { + var func = ts.getRootDeclaration(symbol.valueDeclaration).parent; + var links = getNodeLinks(func); + if (!(links.flags & 8388608 /* AssignmentsMarked */)) { + links.flags |= 8388608 /* AssignmentsMarked */; + if (!hasParentWithAssignmentsMarked(func)) { + markParameterAssignments(func); + } + } + return symbol.isAssigned || false; + } + function hasParentWithAssignmentsMarked(node) { + return !!ts.findAncestor(node.parent, function (node) { return ts.isFunctionLike(node) && !!(getNodeLinks(node).flags & 8388608 /* AssignmentsMarked */); }); + } + function markParameterAssignments(node) { + if (node.kind === 72 /* Identifier */) { + if (ts.isAssignmentTarget(node)) { + var symbol = getResolvedSymbol(node); + if (symbol.valueDeclaration && ts.getRootDeclaration(symbol.valueDeclaration).kind === 151 /* Parameter */) { + symbol.isAssigned = true; + } + } + } + else { + ts.forEachChild(node, markParameterAssignments); + } + } + function isConstVariable(symbol) { + return symbol.flags & 3 /* Variable */ && (getDeclarationNodeFlagsFromSymbol(symbol) & 2 /* Const */) !== 0 && getTypeOfSymbol(symbol) !== autoArrayType; + } + /** remove undefined from the annotated type of a parameter when there is an initializer (that doesn't include undefined) */ + function removeOptionalityFromDeclaredType(declaredType, declaration) { + var annotationIncludesUndefined = strictNullChecks && + declaration.kind === 151 /* Parameter */ && + declaration.initializer && + getFalsyFlags(declaredType) & 32768 /* Undefined */ && + !(getFalsyFlags(checkExpression(declaration.initializer)) & 32768 /* Undefined */); + return annotationIncludesUndefined ? getTypeWithFacts(declaredType, 524288 /* NEUndefined */) : declaredType; + } + function isConstraintPosition(node) { + var parent = node.parent; + return parent.kind === 189 /* PropertyAccessExpression */ || + parent.kind === 191 /* CallExpression */ && parent.expression === node || + parent.kind === 190 /* ElementAccessExpression */ && parent.expression === node || + parent.kind === 186 /* BindingElement */ && parent.name === node && !!parent.initializer; + } + function typeHasNullableConstraint(type) { + return type.flags & 58982400 /* InstantiableNonPrimitive */ && maybeTypeOfKind(getBaseConstraintOfType(type) || emptyObjectType, 98304 /* Nullable */); + } + function getConstraintForLocation(type, node) { + // When a node is the left hand expression of a property access, element access, or call expression, + // and the type of the node includes type variables with constraints that are nullable, we fetch the + // apparent type of the node *before* performing control flow analysis such that narrowings apply to + // the constraint type. + if (type && isConstraintPosition(node) && forEachType(type, typeHasNullableConstraint)) { + return mapType(getWidenedType(type), getBaseConstraintOrType); + } + return type; + } + function markAliasReferenced(symbol, location) { + if (isNonLocalAlias(symbol, /*excludes*/ 67220415 /* Value */) && !isInTypeQuery(location) && !isConstEnumOrConstEnumOnlyModule(resolveAlias(symbol))) { + markAliasSymbolAsReferenced(symbol); + } + } + function checkIdentifier(node) { + var symbol = getResolvedSymbol(node); + if (symbol === unknownSymbol) { + return errorType; + } + // As noted in ECMAScript 6 language spec, arrow functions never have an arguments objects. + // Although in down-level emit of arrow function, we emit it using function expression which means that + // arguments objects will be bound to the inner object; emitting arrow function natively in ES6, arguments objects + // will be bound to non-arrow function that contain this arrow function. This results in inconsistent behavior. + // To avoid that we will give an error to users if they use arguments objects in arrow function so that they + // can explicitly bound arguments objects + if (symbol === argumentsSymbol) { + var container = ts.getContainingFunction(node); + if (languageVersion < 2 /* ES2015 */) { + if (container.kind === 197 /* ArrowFunction */) { + error(node, ts.Diagnostics.The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_standard_function_expression); + } + else if (ts.hasModifier(container, 256 /* Async */)) { + error(node, ts.Diagnostics.The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_using_a_standard_function_or_method); + } + } + getNodeLinks(container).flags |= 8192 /* CaptureArguments */; + return getTypeOfSymbol(symbol); + } + // We should only mark aliases as referenced if there isn't a local value declaration + // for the symbol. Also, don't mark any property access expression LHS - checkPropertyAccessExpression will handle that + if (!(node.parent && ts.isPropertyAccessExpression(node.parent) && node.parent.expression === node)) { + markAliasReferenced(symbol, node); + } + var localOrExportSymbol = getExportSymbolOfValueSymbolIfExported(symbol); + var declaration = localOrExportSymbol.valueDeclaration; + if (localOrExportSymbol.flags & 32 /* Class */) { + // Due to the emit for class decorators, any reference to the class from inside of the class body + // must instead be rewritten to point to a temporary variable to avoid issues with the double-bind + // behavior of class names in ES6. + if (declaration.kind === 240 /* ClassDeclaration */ + && ts.nodeIsDecorated(declaration)) { + var container = ts.getContainingClass(node); + while (container !== undefined) { + if (container === declaration && container.name !== node) { + getNodeLinks(declaration).flags |= 16777216 /* ClassWithConstructorReference */; + getNodeLinks(node).flags |= 33554432 /* ConstructorReferenceInClass */; + break; + } + container = ts.getContainingClass(container); + } + } + else if (declaration.kind === 209 /* ClassExpression */) { + // When we emit a class expression with static members that contain a reference + // to the constructor in the initializer, we will need to substitute that + // binding with an alias as the class name is not in scope. + var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); + while (container.kind !== 279 /* SourceFile */) { + if (container.parent === declaration) { + if (container.kind === 154 /* PropertyDeclaration */ && ts.hasModifier(container, 32 /* Static */)) { + getNodeLinks(declaration).flags |= 16777216 /* ClassWithConstructorReference */; + getNodeLinks(node).flags |= 33554432 /* ConstructorReferenceInClass */; + } + break; + } + container = ts.getThisContainer(container, /*includeArrowFunctions*/ false); + } + } + } + checkNestedBlockScopedBinding(node, symbol); + var type = getConstraintForLocation(getTypeOfSymbol(localOrExportSymbol), node); + var assignmentKind = ts.getAssignmentTargetKind(node); + if (assignmentKind) { + if (!(localOrExportSymbol.flags & 3 /* Variable */) && + !(ts.isInJSFile(node) && localOrExportSymbol.flags & 512 /* ValueModule */)) { + error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_not_a_variable, symbolToString(symbol)); + return errorType; + } + if (isReadonlySymbol(localOrExportSymbol)) { + if (localOrExportSymbol.flags & 3 /* Variable */) { + error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant, symbolToString(symbol)); + } + else { + error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, symbolToString(symbol)); + } + return errorType; + } + } + var isAlias = localOrExportSymbol.flags & 2097152 /* Alias */; + // We only narrow variables and parameters occurring in a non-assignment position. For all other + // entities we simply return the declared type. + if (localOrExportSymbol.flags & 3 /* Variable */) { + if (assignmentKind === 1 /* Definite */) { + return type; + } + } + else if (isAlias) { + declaration = ts.find(symbol.declarations, isSomeImportDeclaration); + } + else { + return type; + } + if (!declaration) { + return type; + } + // The declaration container is the innermost function that encloses the declaration of the variable + // or parameter. The flow container is the innermost function starting with which we analyze the control + // flow graph to determine the control flow based type. + var isParameter = ts.getRootDeclaration(declaration).kind === 151 /* Parameter */; + var declarationContainer = getControlFlowContainer(declaration); + var flowContainer = getControlFlowContainer(node); + var isOuterVariable = flowContainer !== declarationContainer; + var isSpreadDestructuringAssignmentTarget = node.parent && node.parent.parent && ts.isSpreadAssignment(node.parent) && isDestructuringAssignmentTarget(node.parent.parent); + var isModuleExports = symbol.flags & 134217728 /* ModuleExports */; + // When the control flow originates in a function expression or arrow function and we are referencing + // a const variable or parameter from an outer function, we extend the origin of the control flow + // analysis to include the immediately enclosing function. + while (flowContainer !== declarationContainer && (flowContainer.kind === 196 /* FunctionExpression */ || + flowContainer.kind === 197 /* ArrowFunction */ || ts.isObjectLiteralOrClassExpressionMethod(flowContainer)) && + (isConstVariable(localOrExportSymbol) || isParameter && !isParameterAssigned(localOrExportSymbol))) { + flowContainer = getControlFlowContainer(flowContainer); + } + // We only look for uninitialized variables in strict null checking mode, and only when we can analyze + // the entire control flow graph from the variable's declaration (i.e. when the flow container and + // declaration container are the same). + var assumeInitialized = isParameter || isAlias || isOuterVariable || isSpreadDestructuringAssignmentTarget || isModuleExports || + type !== autoType && type !== autoArrayType && (!strictNullChecks || (type.flags & 3 /* AnyOrUnknown */) !== 0 || + isInTypeQuery(node) || node.parent.kind === 257 /* ExportSpecifier */) || + node.parent.kind === 213 /* NonNullExpression */ || + declaration.kind === 237 /* VariableDeclaration */ && declaration.exclamationToken || + declaration.flags & 4194304 /* Ambient */; + var initialType = assumeInitialized ? (isParameter ? removeOptionalityFromDeclaredType(type, declaration) : type) : + type === autoType || type === autoArrayType ? undefinedType : + getOptionalType(type); + var flowType = getFlowTypeOfReference(node, type, initialType, flowContainer, !assumeInitialized); + // A variable is considered uninitialized when it is possible to analyze the entire control flow graph + // from declaration to use, and when the variable's declared type doesn't include undefined but the + // control flow based type does include undefined. + if (!isEvolvingArrayOperationTarget(node) && (type === autoType || type === autoArrayType)) { + if (flowType === autoType || flowType === autoArrayType) { + if (noImplicitAny) { + error(ts.getNameOfDeclaration(declaration), ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined, symbolToString(symbol), typeToString(flowType)); + error(node, ts.Diagnostics.Variable_0_implicitly_has_an_1_type, symbolToString(symbol), typeToString(flowType)); + } + return convertAutoToAny(flowType); + } + } + else if (!assumeInitialized && !(getFalsyFlags(type) & 32768 /* Undefined */) && getFalsyFlags(flowType) & 32768 /* Undefined */) { + error(node, ts.Diagnostics.Variable_0_is_used_before_being_assigned, symbolToString(symbol)); + // Return the declared type to reduce follow-on errors + return type; + } + return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType; + } + function isInsideFunction(node, threshold) { + return !!ts.findAncestor(node, function (n) { return n === threshold ? "quit" : ts.isFunctionLike(n); }); + } + function getPartOfForStatementContainingNode(node, container) { + return ts.findAncestor(node, function (n) { return n === container ? "quit" : n === container.initializer || n === container.condition || n === container.incrementor || n === container.statement; }); + } + function checkNestedBlockScopedBinding(node, symbol) { + if (languageVersion >= 2 /* ES2015 */ || + (symbol.flags & (2 /* BlockScopedVariable */ | 32 /* Class */)) === 0 || + symbol.valueDeclaration.parent.kind === 274 /* CatchClause */) { + return; + } + // 1. walk from the use site up to the declaration and check + // if there is anything function like between declaration and use-site (is binding/class is captured in function). + // 2. walk from the declaration up to the boundary of lexical environment and check + // if there is an iteration statement in between declaration and boundary (is binding/class declared inside iteration statement) + var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); + var usedInFunction = isInsideFunction(node.parent, container); + var current = container; + var containedInIterationStatement = false; + while (current && !ts.nodeStartsNewLexicalEnvironment(current)) { + if (ts.isIterationStatement(current, /*lookInLabeledStatements*/ false)) { + containedInIterationStatement = true; + break; + } + current = current.parent; + } + if (containedInIterationStatement) { + if (usedInFunction) { + // mark iteration statement as containing block-scoped binding captured in some function + var capturesBlockScopeBindingInLoopBody = true; + if (ts.isForStatement(container) && + ts.getAncestor(symbol.valueDeclaration, 238 /* VariableDeclarationList */).parent === container) { + var part = getPartOfForStatementContainingNode(node.parent, container); + if (part) { + var links = getNodeLinks(part); + links.flags |= 131072 /* ContainsCapturedBlockScopeBinding */; + var capturedBindings = links.capturedBlockScopeBindings || (links.capturedBlockScopeBindings = []); + ts.pushIfUnique(capturedBindings, symbol); + if (part === container.initializer) { + capturesBlockScopeBindingInLoopBody = false; // Initializer is outside of loop body + } + } + } + if (capturesBlockScopeBindingInLoopBody) { + getNodeLinks(current).flags |= 65536 /* LoopWithCapturedBlockScopedBinding */; + } + } + // mark variables that are declared in loop initializer and reassigned inside the body of ForStatement. + // if body of ForStatement will be converted to function then we'll need a extra machinery to propagate reassigned values back. + if (container.kind === 225 /* ForStatement */ && + ts.getAncestor(symbol.valueDeclaration, 238 /* VariableDeclarationList */).parent === container && + isAssignedInBodyOfForStatement(node, container)) { + getNodeLinks(symbol.valueDeclaration).flags |= 4194304 /* NeedsLoopOutParameter */; + } + // set 'declared inside loop' bit on the block-scoped binding + getNodeLinks(symbol.valueDeclaration).flags |= 524288 /* BlockScopedBindingInLoop */; + } + if (usedInFunction) { + getNodeLinks(symbol.valueDeclaration).flags |= 262144 /* CapturedBlockScopedBinding */; + } + } + function isBindingCapturedByNode(node, decl) { + var links = getNodeLinks(node); + return !!links && ts.contains(links.capturedBlockScopeBindings, getSymbolOfNode(decl)); + } + function isAssignedInBodyOfForStatement(node, container) { + // skip parenthesized nodes + var current = node; + while (current.parent.kind === 195 /* ParenthesizedExpression */) { + current = current.parent; + } + // check if node is used as LHS in some assignment expression + var isAssigned = false; + if (ts.isAssignmentTarget(current)) { + isAssigned = true; + } + else if ((current.parent.kind === 202 /* PrefixUnaryExpression */ || current.parent.kind === 203 /* PostfixUnaryExpression */)) { + var expr = current.parent; + isAssigned = expr.operator === 44 /* PlusPlusToken */ || expr.operator === 45 /* MinusMinusToken */; + } + if (!isAssigned) { + return false; + } + // at this point we know that node is the target of assignment + // now check that modification happens inside the statement part of the ForStatement + return !!ts.findAncestor(current, function (n) { return n === container ? "quit" : n === container.statement; }); + } + function captureLexicalThis(node, container) { + getNodeLinks(node).flags |= 2 /* LexicalThis */; + if (container.kind === 154 /* PropertyDeclaration */ || container.kind === 157 /* Constructor */) { + var classNode = container.parent; + getNodeLinks(classNode).flags |= 4 /* CaptureThis */; + } + else { + getNodeLinks(container).flags |= 4 /* CaptureThis */; + } + } + function findFirstSuperCall(n) { + if (ts.isSuperCall(n)) { + return n; + } + else if (ts.isFunctionLike(n)) { + return undefined; + } + return ts.forEachChild(n, findFirstSuperCall); + } + /** + * Return a cached result if super-statement is already found. + * Otherwise, find a super statement in a given constructor function and cache the result in the node-links of the constructor + * + * @param constructor constructor-function to look for super statement + */ + function getSuperCallInConstructor(constructor) { + var links = getNodeLinks(constructor); + // Only trying to find super-call if we haven't yet tried to find one. Once we try, we will record the result + if (links.hasSuperCall === undefined) { + links.superCall = findFirstSuperCall(constructor.body); + links.hasSuperCall = links.superCall ? true : false; + } + return links.superCall; + } + /** + * Check if the given class-declaration extends null then return true. + * Otherwise, return false + * @param classDecl a class declaration to check if it extends null + */ + function classDeclarationExtendsNull(classDecl) { + var classSymbol = getSymbolOfNode(classDecl); + var classInstanceType = getDeclaredTypeOfSymbol(classSymbol); + var baseConstructorType = getBaseConstructorTypeOfClass(classInstanceType); + return baseConstructorType === nullWideningType; + } + function checkThisBeforeSuper(node, container, diagnosticMessage) { + var containingClassDecl = container.parent; + var baseTypeNode = ts.getEffectiveBaseTypeNode(containingClassDecl); + // If a containing class does not have extends clause or the class extends null + // skip checking whether super statement is called before "this" accessing. + if (baseTypeNode && !classDeclarationExtendsNull(containingClassDecl)) { + var superCall = getSuperCallInConstructor(container); + // We should give an error in the following cases: + // - No super-call + // - "this" is accessing before super-call. + // i.e super(this) + // this.x; super(); + // We want to make sure that super-call is done before accessing "this" so that + // "this" is not accessed as a parameter of the super-call. + if (!superCall || superCall.end > node.pos) { + // In ES6, super inside constructor of class-declaration has to precede "this" accessing + error(node, diagnosticMessage); + } + } + } + function checkThisExpression(node) { + // Stop at the first arrow function so that we can + // tell whether 'this' needs to be captured. + var container = ts.getThisContainer(node, /* includeArrowFunctions */ true); + var capturedByArrowFunction = false; + if (container.kind === 157 /* Constructor */) { + checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class); + } + // Now skip arrow functions to get the "real" owner of 'this'. + if (container.kind === 197 /* ArrowFunction */) { + container = ts.getThisContainer(container, /* includeArrowFunctions */ false); + capturedByArrowFunction = true; + } + switch (container.kind) { + case 244 /* ModuleDeclaration */: + error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_module_or_namespace_body); + // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks + break; + case 243 /* EnumDeclaration */: + error(node, ts.Diagnostics.this_cannot_be_referenced_in_current_location); + // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks + break; + case 157 /* Constructor */: + if (isInConstructorArgumentInitializer(node, container)) { + error(node, ts.Diagnostics.this_cannot_be_referenced_in_constructor_arguments); + // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks + } + break; + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + if (ts.hasModifier(container, 32 /* Static */)) { + error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_static_property_initializer); + // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks + } + break; + case 149 /* ComputedPropertyName */: + error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_computed_property_name); + break; + } + // When targeting es6, mark that we'll need to capture `this` in its lexically bound scope. + if (capturedByArrowFunction && languageVersion < 2 /* ES2015 */) { + captureLexicalThis(node, container); + } + var type = tryGetThisTypeAt(node, container); + if (!type && noImplicitThis) { + // With noImplicitThis, functions may not reference 'this' if it has type 'any' + var diag = error(node, capturedByArrowFunction && container.kind === 279 /* SourceFile */ ? + ts.Diagnostics.The_containing_arrow_function_captures_the_global_value_of_this_which_implicitly_has_type_any : + ts.Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation); + if (!ts.isSourceFile(container)) { + var outsideThis = tryGetThisTypeAt(container); + if (outsideThis) { + addRelatedInfo(diag, ts.createDiagnosticForNode(container, ts.Diagnostics.An_outer_value_of_this_is_shadowed_by_this_container)); + } + } + } + return type || anyType; + } + function tryGetThisTypeAt(node, container) { + if (container === void 0) { container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); } + var isInJS = ts.isInJSFile(node); + if (ts.isFunctionLike(container) && + (!isInParameterInitializerBeforeContainingFunction(node) || ts.getThisParameter(container))) { + // Note: a parameter initializer should refer to class-this unless function-this is explicitly annotated. + // If this is a function in a JS file, it might be a class method. + var className = getClassNameFromPrototypeMethod(container); + if (isInJS && className) { + var classSymbol = checkExpression(className).symbol; + if (classSymbol && classSymbol.members && (classSymbol.flags & 16 /* Function */)) { + var classType = getJSClassType(classSymbol); + if (classType) { + return getFlowTypeOfReference(node, classType); + } + } + } + // Check if it's a constructor definition, can be either a variable decl or function decl + // i.e. + // * /** @constructor */ function [name]() { ... } + // * /** @constructor */ var x = function() { ... } + else if (isInJS && + (container.kind === 196 /* FunctionExpression */ || container.kind === 239 /* FunctionDeclaration */) && + ts.getJSDocClassTag(container)) { + var classType = getJSClassType(container.symbol); + if (classType) { + return getFlowTypeOfReference(node, classType); + } + } + var thisType = getThisTypeOfDeclaration(container) || getContextualThisParameterType(container); + if (thisType) { + return getFlowTypeOfReference(node, thisType); + } + } + if (ts.isClassLike(container.parent)) { + var symbol = getSymbolOfNode(container.parent); + var type = ts.hasModifier(container, 32 /* Static */) ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol).thisType; + return getFlowTypeOfReference(node, type); + } + if (isInJS) { + var type = getTypeForThisExpressionFromJSDoc(container); + if (type && type !== errorType) { + return getFlowTypeOfReference(node, type); + } + } + } + function getClassNameFromPrototypeMethod(container) { + // Check if it's the RHS of a x.prototype.y = function [name]() { .... } + if (container.kind === 196 /* FunctionExpression */ && + ts.isBinaryExpression(container.parent) && + ts.getAssignmentDeclarationKind(container.parent) === 3 /* PrototypeProperty */) { + // Get the 'x' of 'x.prototype.y = container' + return container.parent // x.prototype.y = container + .left // x.prototype.y + .expression // x.prototype + .expression; // x + } + // x.prototype = { method() { } } + else if (container.kind === 156 /* MethodDeclaration */ && + container.parent.kind === 188 /* ObjectLiteralExpression */ && + ts.isBinaryExpression(container.parent.parent) && + ts.getAssignmentDeclarationKind(container.parent.parent) === 6 /* Prototype */) { + return container.parent.parent.left.expression; + } + // x.prototype = { method: function() { } } + else if (container.kind === 196 /* FunctionExpression */ && + container.parent.kind === 275 /* PropertyAssignment */ && + container.parent.parent.kind === 188 /* ObjectLiteralExpression */ && + ts.isBinaryExpression(container.parent.parent.parent) && + ts.getAssignmentDeclarationKind(container.parent.parent.parent) === 6 /* Prototype */) { + return container.parent.parent.parent.left.expression; + } + // Object.defineProperty(x, "method", { value: function() { } }); + // Object.defineProperty(x, "method", { set: (x: () => void) => void }); + // Object.defineProperty(x, "method", { get: () => function() { }) }); + else if (container.kind === 196 /* FunctionExpression */ && + ts.isPropertyAssignment(container.parent) && + ts.isIdentifier(container.parent.name) && + (container.parent.name.escapedText === "value" || container.parent.name.escapedText === "get" || container.parent.name.escapedText === "set") && + ts.isObjectLiteralExpression(container.parent.parent) && + ts.isCallExpression(container.parent.parent.parent) && + container.parent.parent.parent.arguments[2] === container.parent.parent && + ts.getAssignmentDeclarationKind(container.parent.parent.parent) === 9 /* ObjectDefinePrototypeProperty */) { + return container.parent.parent.parent.arguments[0].expression; + } + // Object.defineProperty(x, "method", { value() { } }); + // Object.defineProperty(x, "method", { set(x: () => void) {} }); + // Object.defineProperty(x, "method", { get() { return () => {} } }); + else if (ts.isMethodDeclaration(container) && + ts.isIdentifier(container.name) && + (container.name.escapedText === "value" || container.name.escapedText === "get" || container.name.escapedText === "set") && + ts.isObjectLiteralExpression(container.parent) && + ts.isCallExpression(container.parent.parent) && + container.parent.parent.arguments[2] === container.parent && + ts.getAssignmentDeclarationKind(container.parent.parent) === 9 /* ObjectDefinePrototypeProperty */) { + return container.parent.parent.arguments[0].expression; + } + } + function getTypeForThisExpressionFromJSDoc(node) { + var jsdocType = ts.getJSDocType(node); + if (jsdocType && jsdocType.kind === 289 /* JSDocFunctionType */) { + var jsDocFunctionType = jsdocType; + if (jsDocFunctionType.parameters.length > 0 && + jsDocFunctionType.parameters[0].name && + jsDocFunctionType.parameters[0].name.escapedText === "this" /* This */) { + return getTypeFromTypeNode(jsDocFunctionType.parameters[0].type); + } + } + var thisTag = ts.getJSDocThisTag(node); + if (thisTag && thisTag.typeExpression) { + return getTypeFromTypeNode(thisTag.typeExpression); + } + } + function isInConstructorArgumentInitializer(node, constructorDecl) { + return !!ts.findAncestor(node, function (n) { return n === constructorDecl ? "quit" : n.kind === 151 /* Parameter */; }); + } + function checkSuperExpression(node) { + var isCallExpression = node.parent.kind === 191 /* CallExpression */ && node.parent.expression === node; + var container = ts.getSuperContainer(node, /*stopOnFunctions*/ true); + var needToCaptureLexicalThis = false; + // adjust the container reference in case if super is used inside arrow functions with arbitrarily deep nesting + if (!isCallExpression) { + while (container && container.kind === 197 /* ArrowFunction */) { + container = ts.getSuperContainer(container, /*stopOnFunctions*/ true); + needToCaptureLexicalThis = languageVersion < 2 /* ES2015 */; + } + } + var canUseSuperExpression = isLegalUsageOfSuperExpression(container); + var nodeCheckFlag = 0; + if (!canUseSuperExpression) { + // issue more specific error if super is used in computed property name + // class A { foo() { return "1" }} + // class B { + // [super.foo()]() {} + // } + var current = ts.findAncestor(node, function (n) { return n === container ? "quit" : n.kind === 149 /* ComputedPropertyName */; }); + if (current && current.kind === 149 /* ComputedPropertyName */) { + error(node, ts.Diagnostics.super_cannot_be_referenced_in_a_computed_property_name); + } + else if (isCallExpression) { + error(node, ts.Diagnostics.Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors); + } + else if (!container || !container.parent || !(ts.isClassLike(container.parent) || container.parent.kind === 188 /* ObjectLiteralExpression */)) { + error(node, ts.Diagnostics.super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions); + } + else { + error(node, ts.Diagnostics.super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_derived_class); + } + return errorType; + } + if (!isCallExpression && container.kind === 157 /* Constructor */) { + checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class); + } + if (ts.hasModifier(container, 32 /* Static */) || isCallExpression) { + nodeCheckFlag = 512 /* SuperStatic */; + } + else { + nodeCheckFlag = 256 /* SuperInstance */; + } + getNodeLinks(node).flags |= nodeCheckFlag; + // Due to how we emit async functions, we need to specialize the emit for an async method that contains a `super` reference. + // This is due to the fact that we emit the body of an async function inside of a generator function. As generator + // functions cannot reference `super`, we emit a helper inside of the method body, but outside of the generator. This helper + // uses an arrow function, which is permitted to reference `super`. + // + // There are two primary ways we can access `super` from within an async method. The first is getting the value of a property + // or indexed access on super, either as part of a right-hand-side expression or call expression. The second is when setting the value + // of a property or indexed access, either as part of an assignment expression or destructuring assignment. + // + // The simplest case is reading a value, in which case we will emit something like the following: + // + // // ts + // ... + // async asyncMethod() { + // let x = await super.asyncMethod(); + // return x; + // } + // ... + // + // // js + // ... + // asyncMethod() { + // const _super = Object.create(null, { + // asyncMethod: { get: () => super.asyncMethod }, + // }); + // return __awaiter(this, arguments, Promise, function *() { + // let x = yield _super.asyncMethod.call(this); + // return x; + // }); + // } + // ... + // + // The more complex case is when we wish to assign a value, especially as part of a destructuring assignment. As both cases + // are legal in ES6, but also likely less frequent, we only emit setters if there is an assignment: + // + // // ts + // ... + // async asyncMethod(ar: Promise) { + // [super.a, super.b] = await ar; + // } + // ... + // + // // js + // ... + // asyncMethod(ar) { + // const _super = Object.create(null, { + // a: { get: () => super.a, set: (v) => super.a = v }, + // b: { get: () => super.b, set: (v) => super.b = v } + // }; + // return __awaiter(this, arguments, Promise, function *() { + // [_super.a, _super.b] = yield ar; + // }); + // } + // ... + // + // Creating an object that has getter and setters instead of just an accessor function is required for destructuring assignments + // as a call expression cannot be used as the target of a destructuring assignment while a property access can. + // + // For element access expressions (`super[x]`), we emit a generic helper that forwards the element access in both situations. + if (container.kind === 156 /* MethodDeclaration */ && ts.hasModifier(container, 256 /* Async */)) { + if (ts.isSuperProperty(node.parent) && ts.isAssignmentTarget(node.parent)) { + getNodeLinks(container).flags |= 4096 /* AsyncMethodWithSuperBinding */; + } + else { + getNodeLinks(container).flags |= 2048 /* AsyncMethodWithSuper */; + } + } + if (needToCaptureLexicalThis) { + // call expressions are allowed only in constructors so they should always capture correct 'this' + // super property access expressions can also appear in arrow functions - + // in this case they should also use correct lexical this + captureLexicalThis(node.parent, container); + } + if (container.parent.kind === 188 /* ObjectLiteralExpression */) { + if (languageVersion < 2 /* ES2015 */) { + error(node, ts.Diagnostics.super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_higher); + return errorType; + } + else { + // for object literal assume that type of 'super' is 'any' + return anyType; + } + } + // at this point the only legal case for parent is ClassLikeDeclaration + var classLikeDeclaration = container.parent; + if (!ts.getEffectiveBaseTypeNode(classLikeDeclaration)) { + error(node, ts.Diagnostics.super_can_only_be_referenced_in_a_derived_class); + return errorType; + } + var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(classLikeDeclaration)); + var baseClassType = classType && getBaseTypes(classType)[0]; + if (!baseClassType) { + return errorType; + } + if (container.kind === 157 /* Constructor */ && isInConstructorArgumentInitializer(node, container)) { + // issue custom error message for super property access in constructor arguments (to be aligned with old compiler) + error(node, ts.Diagnostics.super_cannot_be_referenced_in_constructor_arguments); + return errorType; + } + return nodeCheckFlag === 512 /* SuperStatic */ + ? getBaseConstructorTypeOfClass(classType) + : getTypeWithThisArgument(baseClassType, classType.thisType); + function isLegalUsageOfSuperExpression(container) { + if (!container) { + return false; + } + if (isCallExpression) { + // TS 1.0 SPEC (April 2014): 4.8.1 + // Super calls are only permitted in constructors of derived classes + return container.kind === 157 /* Constructor */; + } + else { + // TS 1.0 SPEC (April 2014) + // 'super' property access is allowed + // - In a constructor, instance member function, instance member accessor, or instance member variable initializer where this references a derived class instance + // - In a static member function or static member accessor + // topmost container must be something that is directly nested in the class declaration\object literal expression + if (ts.isClassLike(container.parent) || container.parent.kind === 188 /* ObjectLiteralExpression */) { + if (ts.hasModifier(container, 32 /* Static */)) { + return container.kind === 156 /* MethodDeclaration */ || + container.kind === 155 /* MethodSignature */ || + container.kind === 158 /* GetAccessor */ || + container.kind === 159 /* SetAccessor */; + } + else { + return container.kind === 156 /* MethodDeclaration */ || + container.kind === 155 /* MethodSignature */ || + container.kind === 158 /* GetAccessor */ || + container.kind === 159 /* SetAccessor */ || + container.kind === 154 /* PropertyDeclaration */ || + container.kind === 153 /* PropertySignature */ || + container.kind === 157 /* Constructor */; + } + } + } + return false; + } + } + function getContainingObjectLiteral(func) { + return (func.kind === 156 /* MethodDeclaration */ || + func.kind === 158 /* GetAccessor */ || + func.kind === 159 /* SetAccessor */) && func.parent.kind === 188 /* ObjectLiteralExpression */ ? func.parent : + func.kind === 196 /* FunctionExpression */ && func.parent.kind === 275 /* PropertyAssignment */ ? func.parent.parent : + undefined; + } + function getThisTypeArgument(type) { + return ts.getObjectFlags(type) & 4 /* Reference */ && type.target === globalThisType ? type.typeArguments[0] : undefined; + } + function getThisTypeFromContextualType(type) { + return mapType(type, function (t) { + return t.flags & 2097152 /* Intersection */ ? ts.forEach(t.types, getThisTypeArgument) : getThisTypeArgument(t); + }); + } + function getContextualThisParameterType(func) { + if (func.kind === 197 /* ArrowFunction */) { + return undefined; + } + if (isContextSensitiveFunctionOrObjectLiteralMethod(func)) { + var contextualSignature = getContextualSignature(func); + if (contextualSignature) { + var thisParameter = contextualSignature.thisParameter; + if (thisParameter) { + return getTypeOfSymbol(thisParameter); + } + } + } + var inJs = ts.isInJSFile(func); + if (noImplicitThis || inJs) { + var containingLiteral = getContainingObjectLiteral(func); + if (containingLiteral) { + // We have an object literal method. Check if the containing object literal has a contextual type + // that includes a ThisType. If so, T is the contextual type for 'this'. We continue looking in + // any directly enclosing object literals. + var contextualType = getApparentTypeOfContextualType(containingLiteral); + var literal = containingLiteral; + var type = contextualType; + while (type) { + var thisType = getThisTypeFromContextualType(type); + if (thisType) { + return instantiateType(thisType, getContextualMapper(containingLiteral)); + } + if (literal.parent.kind !== 275 /* PropertyAssignment */) { + break; + } + literal = literal.parent.parent; + type = getApparentTypeOfContextualType(literal); + } + // There was no contextual ThisType for the containing object literal, so the contextual type + // for 'this' is the non-null form of the contextual type for the containing object literal or + // the type of the object literal itself. + return contextualType ? getNonNullableType(contextualType) : checkExpressionCached(containingLiteral); + } + // In an assignment of the form 'obj.xxx = function(...)' or 'obj[xxx] = function(...)', the + // contextual type for 'this' is 'obj'. + var parent = func.parent; + if (parent.kind === 204 /* BinaryExpression */ && parent.operatorToken.kind === 59 /* EqualsToken */) { + var target = parent.left; + if (target.kind === 189 /* PropertyAccessExpression */ || target.kind === 190 /* ElementAccessExpression */) { + var expression = target.expression; + // Don't contextually type `this` as `exports` in `exports.Point = function(x, y) { this.x = x; this.y = y; }` + if (inJs && ts.isIdentifier(expression)) { + var sourceFile = ts.getSourceFileOfNode(parent); + if (sourceFile.commonJsModuleIndicator && getResolvedSymbol(expression) === sourceFile.symbol) { + return undefined; + } + } + return checkExpressionCached(expression); + } + } + } + return undefined; + } + // Return contextual type of parameter or undefined if no contextual type is available + function getContextuallyTypedParameterType(parameter) { + var func = parameter.parent; + if (!isContextSensitiveFunctionOrObjectLiteralMethod(func)) { + return undefined; + } + var iife = ts.getImmediatelyInvokedFunctionExpression(func); + if (iife && iife.arguments) { + var args = getEffectiveCallArguments(iife); + var indexOfParameter = func.parameters.indexOf(parameter); + if (parameter.dotDotDotToken) { + return getSpreadArgumentType(args, indexOfParameter, args.length, anyType, /*context*/ undefined); + } + var links = getNodeLinks(iife); + var cached = links.resolvedSignature; + links.resolvedSignature = anySignature; + var type = indexOfParameter < args.length ? + getWidenedLiteralType(checkExpression(args[indexOfParameter])) : + parameter.initializer ? undefined : undefinedWideningType; + links.resolvedSignature = cached; + return type; + } + var contextualSignature = getContextualSignature(func); + if (contextualSignature) { + var index = func.parameters.indexOf(parameter) - (ts.getThisParameter(func) ? 1 : 0); + return parameter.dotDotDotToken && ts.lastOrUndefined(func.parameters) === parameter ? + getRestTypeAtPosition(contextualSignature, index) : + tryGetTypeAtPosition(contextualSignature, index); + } + } + // In a variable, parameter or property declaration with a type annotation, + // the contextual type of an initializer expression is the type of the variable, parameter or property. + // Otherwise, in a parameter declaration of a contextually typed function expression, + // the contextual type of an initializer expression is the contextual type of the parameter. + // Otherwise, in a variable or parameter declaration with a binding pattern name, + // the contextual type of an initializer expression is the type implied by the binding pattern. + // Otherwise, in a binding pattern inside a variable or parameter declaration, + // the contextual type of an initializer expression is the type annotation of the containing declaration, if present. + function getContextualTypeForInitializerExpression(node) { + var declaration = node.parent; + if (ts.hasInitializer(declaration) && node === declaration.initializer) { + var typeNode = ts.getEffectiveTypeAnnotationNode(declaration); + if (typeNode) { + return getTypeFromTypeNode(typeNode); + } + if (declaration.kind === 151 /* Parameter */) { + var type = getContextuallyTypedParameterType(declaration); + if (type) { + return type; + } + } + if (ts.isBindingPattern(declaration.name)) { + return getTypeFromBindingPattern(declaration.name, /*includePatternInType*/ true, /*reportErrors*/ false); + } + if (ts.isBindingPattern(declaration.parent)) { + var parentDeclaration = declaration.parent.parent; + var name = declaration.propertyName || declaration.name; + if (parentDeclaration.kind !== 186 /* BindingElement */) { + var parentTypeNode = ts.getEffectiveTypeAnnotationNode(parentDeclaration); + if (parentTypeNode && !ts.isBindingPattern(name)) { + var text = ts.getTextOfPropertyName(name); + if (text) { + return getTypeOfPropertyOfType(getTypeFromTypeNode(parentTypeNode), text); + } + } + } + } + } + return undefined; + } + function getContextualTypeForReturnExpression(node) { + var func = ts.getContainingFunction(node); + if (func) { + var functionFlags = ts.getFunctionFlags(func); + if (functionFlags & 1 /* Generator */) { // AsyncGenerator function or Generator function + return undefined; + } + var contextualReturnType = getContextualReturnType(func); + if (contextualReturnType) { + if (functionFlags & 2 /* Async */) { // Async function + var contextualAwaitedType = getAwaitedTypeOfPromise(contextualReturnType); + return contextualAwaitedType && getUnionType([contextualAwaitedType, createPromiseLikeType(contextualAwaitedType)]); + } + return contextualReturnType; // Regular function + } + } + return undefined; + } + function getContextualTypeForAwaitOperand(node) { + var contextualType = getContextualType(node); + if (contextualType) { + var contextualAwaitedType = getAwaitedType(contextualType); + return contextualAwaitedType && getUnionType([contextualAwaitedType, createPromiseLikeType(contextualAwaitedType)]); + } + return undefined; + } + function getContextualTypeForYieldOperand(node) { + var func = ts.getContainingFunction(node); + if (func) { + var functionFlags = ts.getFunctionFlags(func); + var contextualReturnType = getContextualReturnType(func); + if (contextualReturnType) { + return node.asteriskToken + ? contextualReturnType + : getIteratedTypeOfGenerator(contextualReturnType, (functionFlags & 2 /* Async */) !== 0); + } + } + return undefined; + } + function isInParameterInitializerBeforeContainingFunction(node) { + var inBindingInitializer = false; + while (node.parent && !ts.isFunctionLike(node.parent)) { + if (ts.isParameter(node.parent) && (inBindingInitializer || node.parent.initializer === node)) { + return true; + } + if (ts.isBindingElement(node.parent) && node.parent.initializer === node) { + inBindingInitializer = true; + } + node = node.parent; + } + return false; + } + function getContextualReturnType(functionDecl) { + // If the containing function has a return type annotation, is a constructor, or is a get accessor whose + // corresponding set accessor has a type annotation, return statements in the function are contextually typed + var returnType = getReturnTypeFromAnnotation(functionDecl); + if (returnType) { + return returnType; + } + // Otherwise, if the containing function is contextually typed by a function type with exactly one call signature + // and that call signature is non-generic, return statements are contextually typed by the return type of the signature + var signature = getContextualSignatureForFunctionLikeDeclaration(functionDecl); + if (signature && !isResolvingReturnTypeOfSignature(signature)) { + return getReturnTypeOfSignature(signature); + } + return undefined; + } + // In a typed function call, an argument or substitution expression is contextually typed by the type of the corresponding parameter. + function getContextualTypeForArgument(callTarget, arg) { + var args = getEffectiveCallArguments(callTarget); + var argIndex = args.indexOf(arg); // -1 for e.g. the expression of a CallExpression, or the tag of a TaggedTemplateExpression + return argIndex === -1 ? undefined : getContextualTypeForArgumentAtIndex(callTarget, argIndex); + } + function getContextualTypeForArgumentAtIndex(callTarget, argIndex) { + // If we're already in the process of resolving the given signature, don't resolve again as + // that could cause infinite recursion. Instead, return anySignature. + var signature = getNodeLinks(callTarget).resolvedSignature === resolvingSignature ? resolvingSignature : getResolvedSignature(callTarget); + if (ts.isJsxOpeningLikeElement(callTarget) && argIndex === 0) { + return getEffectiveFirstArgumentForJsxSignature(signature, callTarget); + } + return getTypeAtPosition(signature, argIndex); + } + function getContextualTypeForSubstitutionExpression(template, substitutionExpression) { + if (template.parent.kind === 193 /* TaggedTemplateExpression */) { + return getContextualTypeForArgument(template.parent, substitutionExpression); + } + return undefined; + } + function getContextualTypeForBinaryOperand(node) { + var binaryExpression = node.parent; + var left = binaryExpression.left, operatorToken = binaryExpression.operatorToken, right = binaryExpression.right; + switch (operatorToken.kind) { + case 59 /* EqualsToken */: + if (node !== right) { + return undefined; + } + var contextSensitive = getIsContextSensitiveAssignmentOrContextType(binaryExpression); + if (!contextSensitive) { + return undefined; + } + return contextSensitive === true ? getTypeOfExpression(left) : contextSensitive; + case 55 /* BarBarToken */: + // When an || expression has a contextual type, the operands are contextually typed by that type. When an || + // expression has no contextual type, the right operand is contextually typed by the type of the left operand, + // except for the special case of Javascript declarations of the form `namespace.prop = namespace.prop || {}` + var type = getContextualType(binaryExpression); + return !type && node === right && !ts.isDefaultedExpandoInitializer(binaryExpression) ? + getTypeOfExpression(left) : type; + case 54 /* AmpersandAmpersandToken */: + case 27 /* CommaToken */: + return node === right ? getContextualType(binaryExpression) : undefined; + default: + return undefined; + } + } + // In an assignment expression, the right operand is contextually typed by the type of the left operand. + // Don't do this for assignment declarations unless there is a type tag on the assignment, to avoid circularity from checking the right operand. + function getIsContextSensitiveAssignmentOrContextType(binaryExpression) { + var kind = ts.getAssignmentDeclarationKind(binaryExpression); + switch (kind) { + case 0 /* None */: + return true; + case 5 /* Property */: + case 1 /* ExportsProperty */: + case 6 /* Prototype */: + case 3 /* PrototypeProperty */: + // If `binaryExpression.left` was assigned a symbol, then this is a new declaration; otherwise it is an assignment to an existing declaration. + // See `bindStaticPropertyAssignment` in `binder.ts`. + if (!binaryExpression.left.symbol) { + return true; + } + else { + var decl = binaryExpression.left.symbol.valueDeclaration; + if (!decl) { + return false; + } + var lhs = binaryExpression.left; + var overallAnnotation = ts.getEffectiveTypeAnnotationNode(decl); + if (overallAnnotation) { + return getTypeFromTypeNode(overallAnnotation); + } + else if (ts.isIdentifier(lhs.expression)) { + var id = lhs.expression; + var parentSymbol = resolveName(id, id.escapedText, 67220415 /* Value */, undefined, id.escapedText, /*isUse*/ true); + if (parentSymbol) { + var annotated = ts.getEffectiveTypeAnnotationNode(parentSymbol.valueDeclaration); + if (annotated) { + var type = getTypeOfPropertyOfContextualType(getTypeFromTypeNode(annotated), lhs.name.escapedText); + return type || false; + } + return false; + } + } + return !ts.isInJSFile(decl); + } + case 2 /* ModuleExports */: + case 4 /* ThisProperty */: + if (!binaryExpression.symbol) + return true; + if (binaryExpression.symbol.valueDeclaration) { + var annotated = ts.getEffectiveTypeAnnotationNode(binaryExpression.symbol.valueDeclaration); + if (annotated) { + var type = getTypeFromTypeNode(annotated); + if (type) { + return type; + } + } + } + if (kind === 2 /* ModuleExports */) + return false; + var thisAccess = binaryExpression.left; + if (!ts.isObjectLiteralMethod(ts.getThisContainer(thisAccess.expression, /*includeArrowFunctions*/ false))) { + return false; + } + var thisType = checkThisExpression(thisAccess.expression); + return thisType && getTypeOfPropertyOfContextualType(thisType, thisAccess.name.escapedText) || false; + case 7 /* ObjectDefinePropertyValue */: + case 8 /* ObjectDefinePropertyExports */: + case 9 /* ObjectDefinePrototypeProperty */: + return ts.Debug.fail("Does not apply"); + default: + return ts.Debug.assertNever(kind); + } + } + function getTypeOfPropertyOfContextualType(type, name) { + return mapType(type, function (t) { + if (t.flags & 3670016 /* StructuredType */) { + var prop = getPropertyOfType(t, name); + if (prop) { + return getTypeOfSymbol(prop); + } + if (isTupleType(t)) { + var restType = getRestTypeOfTupleType(t); + if (restType && isNumericLiteralName(name) && +name >= 0) { + return restType; + } + } + return isNumericLiteralName(name) && getIndexTypeOfContextualType(t, 1 /* Number */) || + getIndexTypeOfContextualType(t, 0 /* String */); + } + return undefined; + }, /*noReductions*/ true); + } + function getIndexTypeOfContextualType(type, kind) { + return mapType(type, function (t) { return getIndexTypeOfStructuredType(t, kind); }, /*noReductions*/ true); + } + // In an object literal contextually typed by a type T, the contextual type of a property assignment is the type of + // the matching property in T, if one exists. Otherwise, it is the type of the numeric index signature in T, if one + // exists. Otherwise, it is the type of the string index signature in T, if one exists. + function getContextualTypeForObjectLiteralMethod(node) { + ts.Debug.assert(ts.isObjectLiteralMethod(node)); + if (node.flags & 8388608 /* InWithStatement */) { + // We cannot answer semantic questions within a with block, do not proceed any further + return undefined; + } + return getContextualTypeForObjectLiteralElement(node); + } + function getContextualTypeForObjectLiteralElement(element) { + var objectLiteral = element.parent; + var type = getApparentTypeOfContextualType(objectLiteral); + if (type) { + if (!hasNonBindableDynamicName(element)) { + // For a (non-symbol) computed property, there is no reason to look up the name + // in the type. It will just be "__computed", which does not appear in any + // SymbolTable. + var symbolName_2 = getSymbolOfNode(element).escapedName; + var propertyType = getTypeOfPropertyOfContextualType(type, symbolName_2); + if (propertyType) { + return propertyType; + } + } + return isNumericName(element.name) && getIndexTypeOfContextualType(type, 1 /* Number */) || + getIndexTypeOfContextualType(type, 0 /* String */); + } + return undefined; + } + // In an array literal contextually typed by a type T, the contextual type of an element expression at index N is + // the type of the property with the numeric name N in T, if one exists. Otherwise, if T has a numeric index signature, + // it is the type of the numeric index signature in T. Otherwise, in ES6 and higher, the contextual type is the iterated + // type of T. + function getContextualTypeForElementExpression(arrayContextualType, index) { + return arrayContextualType && (getTypeOfPropertyOfContextualType(arrayContextualType, "" + index) + || getIteratedTypeOrElementType(arrayContextualType, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterables*/ false, /*checkAssignability*/ false)); + } + // In a contextually typed conditional expression, the true/false expressions are contextually typed by the same type. + function getContextualTypeForConditionalOperand(node) { + var conditional = node.parent; + return node === conditional.whenTrue || node === conditional.whenFalse ? getContextualType(conditional) : undefined; + } + function getContextualTypeForChildJsxExpression(node) { + var attributesType = getApparentTypeOfContextualType(node.openingElement.tagName); + // JSX expression is in children of JSX Element, we will look for an "children" atttribute (we get the name from JSX.ElementAttributesProperty) + var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(node)); + return attributesType && !isTypeAny(attributesType) && jsxChildrenPropertyName && jsxChildrenPropertyName !== "" ? getTypeOfPropertyOfContextualType(attributesType, jsxChildrenPropertyName) : undefined; + } + function getContextualTypeForJsxExpression(node) { + var exprParent = node.parent; + return ts.isJsxAttributeLike(exprParent) + ? getContextualType(node) + : ts.isJsxElement(exprParent) + ? getContextualTypeForChildJsxExpression(exprParent) + : undefined; + } + function getContextualTypeForJsxAttribute(attribute) { + // When we trying to resolve JsxOpeningLikeElement as a stateless function element, we will already give its attributes a contextual type + // which is a type of the parameter of the signature we are trying out. + // If there is no contextual type (e.g. we are trying to resolve stateful component), get attributes type from resolving element's tagName + if (ts.isJsxAttribute(attribute)) { + var attributesType = getApparentTypeOfContextualType(attribute.parent); + if (!attributesType || isTypeAny(attributesType)) { + return undefined; + } + return getTypeOfPropertyOfContextualType(attributesType, attribute.name.escapedText); + } + else { + return getContextualType(attribute.parent); + } + } + // Return true if the given expression is possibly a discriminant value. We limit the kinds of + // expressions we check to those that don't depend on their contextual type in order not to cause + // recursive (and possibly infinite) invocations of getContextualType. + function isPossiblyDiscriminantValue(node) { + switch (node.kind) { + case 10 /* StringLiteral */: + case 8 /* NumericLiteral */: + case 9 /* BigIntLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: + case 102 /* TrueKeyword */: + case 87 /* FalseKeyword */: + case 96 /* NullKeyword */: + case 72 /* Identifier */: + case 141 /* UndefinedKeyword */: + return true; + case 189 /* PropertyAccessExpression */: + case 195 /* ParenthesizedExpression */: + return isPossiblyDiscriminantValue(node.expression); + case 270 /* JsxExpression */: + return !node.expression || isPossiblyDiscriminantValue(node.expression); + } + return false; + } + function discriminateContextualTypeByObjectMembers(node, contextualType) { + return discriminateTypeByDiscriminableItems(contextualType, ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 275 /* PropertyAssignment */ && isPossiblyDiscriminantValue(p.initializer) && isDiscriminantProperty(contextualType, p.symbol.escapedName); }), function (prop) { return [function () { return checkExpression(prop.initializer); }, prop.symbol.escapedName]; }), isTypeAssignableTo, contextualType); + } + function discriminateContextualTypeByJSXAttributes(node, contextualType) { + return discriminateTypeByDiscriminableItems(contextualType, ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 267 /* JsxAttribute */ && isDiscriminantProperty(contextualType, p.symbol.escapedName) && (!p.initializer || isPossiblyDiscriminantValue(p.initializer)); }), function (prop) { return [!prop.initializer ? (function () { return trueType; }) : (function () { return checkExpression(prop.initializer); }), prop.symbol.escapedName]; }), isTypeAssignableTo, contextualType); + } + // Return the contextual type for a given expression node. During overload resolution, a contextual type may temporarily + // be "pushed" onto a node using the contextualType property. + function getApparentTypeOfContextualType(node) { + var contextualType = getContextualType(node); + contextualType = contextualType && mapType(contextualType, getApparentType); + if (contextualType && contextualType.flags & 1048576 /* Union */) { + if (ts.isObjectLiteralExpression(node)) { + return discriminateContextualTypeByObjectMembers(node, contextualType); + } + else if (ts.isJsxAttributes(node)) { + return discriminateContextualTypeByJSXAttributes(node, contextualType); + } + } + return contextualType; + } + /** + * Woah! Do you really want to use this function? + * + * Unless you're trying to get the *non-apparent* type for a + * value-literal type or you're authoring relevant portions of this algorithm, + * you probably meant to use 'getApparentTypeOfContextualType'. + * Otherwise this may not be very useful. + * + * In cases where you *are* working on this function, you should understand + * when it is appropriate to use 'getContextualType' and 'getApparentTypeOfContextualType'. + * + * - Use 'getContextualType' when you are simply going to propagate the result to the expression. + * - Use 'getApparentTypeOfContextualType' when you're going to need the members of the type. + * + * @param node the expression whose contextual type will be returned. + * @returns the contextual type of an expression. + */ + function getContextualType(node) { + if (node.flags & 8388608 /* InWithStatement */) { + // We cannot answer semantic questions within a with block, do not proceed any further + return undefined; + } + if (node.contextualType) { + return node.contextualType; + } + var parent = node.parent; + switch (parent.kind) { + case 237 /* VariableDeclaration */: + case 151 /* Parameter */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 186 /* BindingElement */: + return getContextualTypeForInitializerExpression(node); + case 197 /* ArrowFunction */: + case 230 /* ReturnStatement */: + return getContextualTypeForReturnExpression(node); + case 207 /* YieldExpression */: + return getContextualTypeForYieldOperand(parent); + case 201 /* AwaitExpression */: + return getContextualTypeForAwaitOperand(parent); + case 191 /* CallExpression */: + case 192 /* NewExpression */: + return getContextualTypeForArgument(parent, node); + case 194 /* TypeAssertionExpression */: + case 212 /* AsExpression */: + return getTypeFromTypeNode(parent.type); + case 204 /* BinaryExpression */: + return getContextualTypeForBinaryOperand(node); + case 275 /* PropertyAssignment */: + case 276 /* ShorthandPropertyAssignment */: + return getContextualTypeForObjectLiteralElement(parent); + case 277 /* SpreadAssignment */: + return getApparentTypeOfContextualType(parent.parent); + case 187 /* ArrayLiteralExpression */: { + var arrayLiteral = parent; + var type = getApparentTypeOfContextualType(arrayLiteral); + return getContextualTypeForElementExpression(type, ts.indexOfNode(arrayLiteral.elements, node)); + } + case 205 /* ConditionalExpression */: + return getContextualTypeForConditionalOperand(node); + case 216 /* TemplateSpan */: + ts.Debug.assert(parent.parent.kind === 206 /* TemplateExpression */); + return getContextualTypeForSubstitutionExpression(parent.parent, node); + case 195 /* ParenthesizedExpression */: { + // Like in `checkParenthesizedExpression`, an `/** @type {xyz} */` comment before a parenthesized expression acts as a type cast. + var tag = ts.isInJSFile(parent) ? ts.getJSDocTypeTag(parent) : undefined; + return tag ? getTypeFromTypeNode(tag.typeExpression.type) : getContextualType(parent); + } + case 270 /* JsxExpression */: + return getContextualTypeForJsxExpression(parent); + case 267 /* JsxAttribute */: + case 269 /* JsxSpreadAttribute */: + return getContextualTypeForJsxAttribute(parent); + case 262 /* JsxOpeningElement */: + case 261 /* JsxSelfClosingElement */: + return getContextualJsxElementAttributesType(parent); + } + return undefined; + } + function getContextualMapper(node) { + var ancestor = ts.findAncestor(node, function (n) { return !!n.contextualMapper; }); + return ancestor ? ancestor.contextualMapper : identityMapper; + } + function getContextualJsxElementAttributesType(node) { + if (ts.isJsxOpeningElement(node) && node.parent.contextualType) { + // Contextually applied type is moved from attributes up to the outer jsx attributes so when walking up from the children they get hit + // _However_ to hit them from the _attributes_ we must look for them here; otherwise we'll used the declared type + // (as below) instead! + return node.parent.contextualType; + } + return getContextualTypeForArgumentAtIndex(node, 0); + } + function getEffectiveFirstArgumentForJsxSignature(signature, node) { + return getJsxReferenceKind(node) !== 0 /* Component */ ? getJsxPropsTypeFromCallSignature(signature, node) : getJsxPropsTypeFromClassType(signature, node); + } + function getJsxPropsTypeFromCallSignature(sig, context) { + var propsType = getTypeOfFirstParameterOfSignatureWithFallback(sig, emptyObjectType); + propsType = getJsxManagedAttributesFromLocatedAttributes(context, getJsxNamespaceAt(context), propsType); + var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes, context); + if (intrinsicAttribs !== errorType) { + propsType = intersectTypes(intrinsicAttribs, propsType); + } + return propsType; + } + function getJsxPropsTypeForSignatureFromMember(sig, forcedLookupLocation) { + var instanceType = getReturnTypeOfSignature(sig); + return isTypeAny(instanceType) ? instanceType : getTypeOfPropertyOfType(instanceType, forcedLookupLocation); + } + function getStaticTypeOfReferencedJsxConstructor(context) { + if (isJsxIntrinsicIdentifier(context.tagName)) { + var result = getIntrinsicAttributesTypeFromJsxOpeningLikeElement(context); + var fakeSignature = createSignatureForJSXIntrinsic(context, result); + return getOrCreateTypeFromSignature(fakeSignature); + } + var tagType = checkExpressionCached(context.tagName); + if (tagType.flags & 128 /* StringLiteral */) { + var result = getIntrinsicAttributesTypeFromStringLiteralType(tagType, context); + if (!result) { + return errorType; + } + var fakeSignature = createSignatureForJSXIntrinsic(context, result); + return getOrCreateTypeFromSignature(fakeSignature); + } + return tagType; + } + function getJsxManagedAttributesFromLocatedAttributes(context, ns, attributesType) { + var managedSym = getJsxLibraryManagedAttributes(ns); + if (managedSym) { + var declaredManagedType = getDeclaredTypeOfSymbol(managedSym); + var ctorType = getStaticTypeOfReferencedJsxConstructor(context); + if (ts.length(declaredManagedType.typeParameters) >= 2) { + var args = fillMissingTypeArguments([ctorType, attributesType], declaredManagedType.typeParameters, 2, ts.isInJSFile(context)); + return createTypeReference(declaredManagedType, args); + } + else if (ts.length(declaredManagedType.aliasTypeArguments) >= 2) { + var args = fillMissingTypeArguments([ctorType, attributesType], declaredManagedType.aliasTypeArguments, 2, ts.isInJSFile(context)); + return getTypeAliasInstantiation(declaredManagedType.aliasSymbol, args); + } + } + return attributesType; + } + function getJsxPropsTypeFromClassType(sig, context) { + var ns = getJsxNamespaceAt(context); + var forcedLookupLocation = getJsxElementPropertiesName(ns); + var attributesType = forcedLookupLocation === undefined + // If there is no type ElementAttributesProperty, return the type of the first parameter of the signature, which should be the props type + ? getTypeOfFirstParameterOfSignatureWithFallback(sig, emptyObjectType) + : forcedLookupLocation === "" + // If there is no e.g. 'props' member in ElementAttributesProperty, use the element class type instead + ? getReturnTypeOfSignature(sig) + // Otherwise get the type of the property on the signature return type + : getJsxPropsTypeForSignatureFromMember(sig, forcedLookupLocation); + if (!attributesType) { + // There is no property named 'props' on this instance type + if (!!forcedLookupLocation && !!ts.length(context.attributes.properties)) { + error(context, ts.Diagnostics.JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property, ts.unescapeLeadingUnderscores(forcedLookupLocation)); + } + return emptyObjectType; + } + attributesType = getJsxManagedAttributesFromLocatedAttributes(context, ns, attributesType); + if (isTypeAny(attributesType)) { + // Props is of type 'any' or unknown + return attributesType; + } + else { + // Normal case -- add in IntrinsicClassElements and IntrinsicElements + var apparentAttributesType = attributesType; + var intrinsicClassAttribs = getJsxType(JsxNames.IntrinsicClassAttributes, context); + if (intrinsicClassAttribs !== errorType) { + var typeParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(intrinsicClassAttribs.symbol); + var hostClassType = getReturnTypeOfSignature(sig); + apparentAttributesType = intersectTypes(typeParams + ? createTypeReference(intrinsicClassAttribs, fillMissingTypeArguments([hostClassType], typeParams, getMinTypeArgumentCount(typeParams), ts.isInJSFile(context))) + : intrinsicClassAttribs, apparentAttributesType); + } + var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes, context); + if (intrinsicAttribs !== errorType) { + apparentAttributesType = intersectTypes(intrinsicAttribs, apparentAttributesType); + } + return apparentAttributesType; + } + } + // If the given type is an object or union type with a single signature, and if that signature has at + // least as many parameters as the given function, return the signature. Otherwise return undefined. + function getContextualCallSignature(type, node) { + var signatures = getSignaturesOfType(type, 0 /* Call */); + if (signatures.length === 1) { + var signature = signatures[0]; + if (!isAritySmaller(signature, node)) { + return signature; + } + } + } + /** If the contextual signature has fewer parameters than the function expression, do not use it */ + function isAritySmaller(signature, target) { + var targetParameterCount = 0; + for (; targetParameterCount < target.parameters.length; targetParameterCount++) { + var param = target.parameters[targetParameterCount]; + if (param.initializer || param.questionToken || param.dotDotDotToken || isJSDocOptionalParameter(param)) { + break; + } + } + if (target.parameters.length && ts.parameterIsThisKeyword(target.parameters[0])) { + targetParameterCount--; + } + return !hasEffectiveRestParameter(signature) && getParameterCount(signature) < targetParameterCount; + } + function isFunctionExpressionOrArrowFunction(node) { + return node.kind === 196 /* FunctionExpression */ || node.kind === 197 /* ArrowFunction */; + } + function getContextualSignatureForFunctionLikeDeclaration(node) { + // Only function expressions, arrow functions, and object literal methods are contextually typed. + return isFunctionExpressionOrArrowFunction(node) || ts.isObjectLiteralMethod(node) + ? getContextualSignature(node) + : undefined; + } + function getContextualTypeForFunctionLikeDeclaration(node) { + return ts.isObjectLiteralMethod(node) ? + getContextualTypeForObjectLiteralMethod(node) : + getApparentTypeOfContextualType(node); + } + // Return the contextual signature for a given expression node. A contextual type provides a + // contextual signature if it has a single call signature and if that call signature is non-generic. + // If the contextual type is a union type, get the signature from each type possible and if they are + // all identical ignoring their return type, the result is same signature but with return type as + // union type of return types from these signatures + function getContextualSignature(node) { + ts.Debug.assert(node.kind !== 156 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + var typeTagSignature = getSignatureOfTypeTag(node); + if (typeTagSignature) { + return typeTagSignature; + } + var type = getContextualTypeForFunctionLikeDeclaration(node); + if (!type) { + return undefined; + } + if (!(type.flags & 1048576 /* Union */)) { + return getContextualCallSignature(type, node); + } + var signatureList; + var types = type.types; + for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { + var current = types_14[_i]; + var signature = getContextualCallSignature(current, node); + if (signature) { + if (!signatureList) { + // This signature will contribute to contextual union signature + signatureList = [signature]; + } + else if (!compareSignaturesIdentical(signatureList[0], signature, /*partialMatch*/ false, /*ignoreThisTypes*/ true, /*ignoreReturnTypes*/ true, compareTypesIdentical)) { + // Signatures aren't identical, do not use + return undefined; + } + else { + // Use this signature for contextual union signature + signatureList.push(signature); + } + } + } + // Result is union of signatures collected (return type is union of return types of this signature set) + var result; + if (signatureList) { + result = cloneSignature(signatureList[0]); + result.unionSignatures = signatureList; + } + return result; + } + function checkSpreadExpression(node, checkMode) { + if (languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) { + checkExternalEmitHelpers(node, 1536 /* SpreadIncludes */); + } + var arrayOrIterableType = checkExpression(node.expression, checkMode); + return checkIteratedTypeOrElementType(arrayOrIterableType, node.expression, /*allowStringInput*/ false, /*allowAsyncIterables*/ false); + } + function hasDefaultValue(node) { + return (node.kind === 186 /* BindingElement */ && !!node.initializer) || + (node.kind === 204 /* BinaryExpression */ && node.operatorToken.kind === 59 /* EqualsToken */); + } + function checkArrayLiteral(node, checkMode, forceTuple) { + var elements = node.elements; + var elementCount = elements.length; + var hasNonEndingSpreadElement = false; + var elementTypes = []; + var inDestructuringPattern = ts.isAssignmentTarget(node); + var contextualType = getApparentTypeOfContextualType(node); + for (var index = 0; index < elementCount; index++) { + var e = elements[index]; + if (inDestructuringPattern && e.kind === 208 /* SpreadElement */) { + // Given the following situation: + // var c: {}; + // [...c] = ["", 0]; + // + // c is represented in the tree as a spread element in an array literal. + // But c really functions as a rest element, and its purpose is to provide + // a contextual type for the right hand side of the assignment. Therefore, + // instead of calling checkExpression on "...c", which will give an error + // if c is not iterable/array-like, we need to act as if we are trying to + // get the contextual element type from it. So we do something similar to + // getContextualTypeForElementExpression, which will crucially not error + // if there is no index type / iterated type. + var restArrayType = checkExpression(e.expression, checkMode, forceTuple); + var restElementType = getIndexTypeOfType(restArrayType, 1 /* Number */) || + getIteratedTypeOrElementType(restArrayType, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterables*/ false, /*checkAssignability*/ false); + if (restElementType) { + elementTypes.push(restElementType); + } + } + else { + var elementContextualType = getContextualTypeForElementExpression(contextualType, index); + var type = checkExpressionForMutableLocation(e, checkMode, elementContextualType, forceTuple); + elementTypes.push(type); + } + if (index < elementCount - 1 && e.kind === 208 /* SpreadElement */) { + hasNonEndingSpreadElement = true; + } + } + if (!hasNonEndingSpreadElement) { + var hasRestElement = elementCount > 0 && elements[elementCount - 1].kind === 208 /* SpreadElement */; + var minLength = elementCount - (hasRestElement ? 1 : 0); + // If array literal is actually a destructuring pattern, mark it as an implied type. We do this such + // that we get the same behavior for "var [x, y] = []" and "[x, y] = []". + var tupleResult = void 0; + if (inDestructuringPattern && minLength > 0) { + var type = cloneTypeReference(createTupleType(elementTypes, minLength, hasRestElement)); + type.pattern = node; + return type; + } + else if (tupleResult = getArrayLiteralTupleTypeIfApplicable(elementTypes, contextualType, hasRestElement, elementCount)) { + return tupleResult; + } + else if (forceTuple) { + return createTupleType(elementTypes, minLength, hasRestElement); + } + } + return getArrayLiteralType(elementTypes, 2 /* Subtype */); + } + function getArrayLiteralTupleTypeIfApplicable(elementTypes, contextualType, hasRestElement, elementCount) { + if (elementCount === void 0) { elementCount = elementTypes.length; } + // Infer a tuple type when the contextual type is or contains a tuple-like type + if (contextualType && forEachType(contextualType, isTupleLikeType)) { + var minLength = elementCount - (hasRestElement ? 1 : 0); + var pattern = contextualType.pattern; + // If array literal is contextually typed by a binding pattern or an assignment pattern, pad the resulting + // tuple type with the corresponding binding or assignment element types to make the lengths equal. + if (!hasRestElement && pattern && (pattern.kind === 185 /* ArrayBindingPattern */ || pattern.kind === 187 /* ArrayLiteralExpression */)) { + var patternElements = pattern.elements; + for (var i = elementCount; i < patternElements.length; i++) { + var e = patternElements[i]; + if (hasDefaultValue(e)) { + elementTypes.push(contextualType.typeArguments[i]); + } + else if (i < patternElements.length - 1 || !(e.kind === 186 /* BindingElement */ && e.dotDotDotToken || e.kind === 208 /* SpreadElement */)) { + if (e.kind !== 210 /* OmittedExpression */) { + error(e, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); + } + elementTypes.push(strictNullChecks ? implicitNeverType : undefinedWideningType); + } + } + } + return createTupleType(elementTypes, minLength, hasRestElement); + } + } + function getArrayLiteralType(elementTypes, unionReduction) { + if (unionReduction === void 0) { unionReduction = 1 /* Literal */; } + return createArrayType(elementTypes.length ? + getUnionType(elementTypes, unionReduction) : + strictNullChecks ? implicitNeverType : undefinedWideningType); + } + function isNumericName(name) { + switch (name.kind) { + case 149 /* ComputedPropertyName */: + return isNumericComputedName(name); + case 72 /* Identifier */: + return isNumericLiteralName(name.escapedText); + case 8 /* NumericLiteral */: + case 10 /* StringLiteral */: + return isNumericLiteralName(name.text); + default: + return false; + } + } + function isNumericComputedName(name) { + // It seems odd to consider an expression of type Any to result in a numeric name, + // but this behavior is consistent with checkIndexedAccess + return isTypeAssignableToKind(checkComputedPropertyName(name), 296 /* NumberLike */); + } + function isInfinityOrNaNString(name) { + return name === "Infinity" || name === "-Infinity" || name === "NaN"; + } + function isNumericLiteralName(name) { + // The intent of numeric names is that + // - they are names with text in a numeric form, and that + // - setting properties/indexing with them is always equivalent to doing so with the numeric literal 'numLit', + // acquired by applying the abstract 'ToNumber' operation on the name's text. + // + // The subtlety is in the latter portion, as we cannot reliably say that anything that looks like a numeric literal is a numeric name. + // In fact, it is the case that the text of the name must be equal to 'ToString(numLit)' for this to hold. + // + // Consider the property name '"0xF00D"'. When one indexes with '0xF00D', they are actually indexing with the value of 'ToString(0xF00D)' + // according to the ECMAScript specification, so it is actually as if the user indexed with the string '"61453"'. + // Thus, the text of all numeric literals equivalent to '61543' such as '0xF00D', '0xf00D', '0170015', etc. are not valid numeric names + // because their 'ToString' representation is not equal to their original text. + // This is motivated by ECMA-262 sections 9.3.1, 9.8.1, 11.1.5, and 11.2.1. + // + // Here, we test whether 'ToString(ToNumber(name))' is exactly equal to 'name'. + // The '+' prefix operator is equivalent here to applying the abstract ToNumber operation. + // Applying the 'toString()' method on a number gives us the abstract ToString operation on a number. + // + // Note that this accepts the values 'Infinity', '-Infinity', and 'NaN', and that this is intentional. + // This is desired behavior, because when indexing with them as numeric entities, you are indexing + // with the strings '"Infinity"', '"-Infinity"', and '"NaN"' respectively. + return (+name).toString() === name; + } + function checkComputedPropertyName(node) { + var links = getNodeLinks(node.expression); + if (!links.resolvedType) { + links.resolvedType = checkExpression(node.expression); + // This will allow types number, string, symbol or any. It will also allow enums, the unknown + // type, and any union of these types (like string | number). + if (links.resolvedType.flags & 98304 /* Nullable */ || + !isTypeAssignableToKind(links.resolvedType, 132 /* StringLike */ | 296 /* NumberLike */ | 12288 /* ESSymbolLike */) && + !isTypeAssignableTo(links.resolvedType, stringNumberSymbolType)) { + error(node, ts.Diagnostics.A_computed_property_name_must_be_of_type_string_number_symbol_or_any); + } + else { + checkThatExpressionIsProperSymbolReference(node.expression, links.resolvedType, /*reportError*/ true); + } + } + return links.resolvedType; + } + function getObjectLiteralIndexInfo(propertyNodes, offset, properties, kind) { + var propTypes = []; + for (var i = 0; i < properties.length; i++) { + if (kind === 0 /* String */ || isNumericName(propertyNodes[i + offset].name)) { + propTypes.push(getTypeOfSymbol(properties[i])); + } + } + var unionType = propTypes.length ? getUnionType(propTypes, 2 /* Subtype */) : undefinedType; + return createIndexInfo(unionType, /*isReadonly*/ false); + } + function getImmediateAliasedSymbol(symbol) { + ts.Debug.assert((symbol.flags & 2097152 /* Alias */) !== 0, "Should only get Alias here."); + var links = getSymbolLinks(symbol); + if (!links.immediateTarget) { + var node = getDeclarationOfAliasSymbol(symbol); + if (!node) + return ts.Debug.fail(); + links.immediateTarget = getTargetOfAliasDeclaration(node, /*dontRecursivelyResolve*/ true); + } + return links.immediateTarget; + } + function checkObjectLiteral(node, checkMode) { + var inDestructuringPattern = ts.isAssignmentTarget(node); + // Grammar checking + checkGrammarObjectLiteralExpression(node, inDestructuringPattern); + var propertiesTable; + var propertiesArray = []; + var spread = emptyObjectType; + var propagatedFlags = 0; + var contextualType = getApparentTypeOfContextualType(node); + var contextualTypeHasPattern = contextualType && contextualType.pattern && + (contextualType.pattern.kind === 184 /* ObjectBindingPattern */ || contextualType.pattern.kind === 188 /* ObjectLiteralExpression */); + var isInJavascript = ts.isInJSFile(node) && !ts.isInJsonFile(node); + var enumTag = ts.getJSDocEnumTag(node); + var isJSObjectLiteral = !contextualType && isInJavascript && !enumTag; + var typeFlags = 0; + var patternWithComputedProperties = false; + var hasComputedStringProperty = false; + var hasComputedNumberProperty = false; + propertiesTable = ts.createSymbolTable(); + var offset = 0; + for (var i = 0; i < node.properties.length; i++) { + var memberDecl = node.properties[i]; + var member = getSymbolOfNode(memberDecl); + var computedNameType = memberDecl.name && memberDecl.name.kind === 149 /* ComputedPropertyName */ && !ts.isWellKnownSymbolSyntactically(memberDecl.name.expression) ? + checkComputedPropertyName(memberDecl.name) : undefined; + if (memberDecl.kind === 275 /* PropertyAssignment */ || + memberDecl.kind === 276 /* ShorthandPropertyAssignment */ || + ts.isObjectLiteralMethod(memberDecl)) { + var type = memberDecl.kind === 275 /* PropertyAssignment */ ? checkPropertyAssignment(memberDecl, checkMode) : + memberDecl.kind === 276 /* ShorthandPropertyAssignment */ ? checkExpressionForMutableLocation(memberDecl.name, checkMode) : + checkObjectLiteralMethod(memberDecl, checkMode); + if (isInJavascript) { + var jsDocType = getTypeForDeclarationFromJSDocComment(memberDecl); + if (jsDocType) { + checkTypeAssignableTo(type, jsDocType, memberDecl); + type = jsDocType; + } + else if (enumTag && enumTag.typeExpression) { + checkTypeAssignableTo(type, getTypeFromTypeNode(enumTag.typeExpression), memberDecl); + } + } + typeFlags |= type.flags; + var nameType = computedNameType && computedNameType.flags & 8576 /* StringOrNumberLiteralOrUnique */ ? + computedNameType : undefined; + var prop = nameType ? + createSymbol(4 /* Property */ | member.flags, getLateBoundNameFromType(nameType), 1024 /* Late */) : + createSymbol(4 /* Property */ | member.flags, member.escapedName); + if (nameType) { + prop.nameType = nameType; + } + if (inDestructuringPattern) { + // If object literal is an assignment pattern and if the assignment pattern specifies a default value + // for the property, make the property optional. + var isOptional = (memberDecl.kind === 275 /* PropertyAssignment */ && hasDefaultValue(memberDecl.initializer)) || + (memberDecl.kind === 276 /* ShorthandPropertyAssignment */ && memberDecl.objectAssignmentInitializer); + if (isOptional) { + prop.flags |= 16777216 /* Optional */; + } + } + else if (contextualTypeHasPattern && !(ts.getObjectFlags(contextualType) & 512 /* ObjectLiteralPatternWithComputedProperties */)) { + // If object literal is contextually typed by the implied type of a binding pattern, and if the + // binding pattern specifies a default value for the property, make the property optional. + var impliedProp = getPropertyOfType(contextualType, member.escapedName); + if (impliedProp) { + prop.flags |= impliedProp.flags & 16777216 /* Optional */; + } + else if (!compilerOptions.suppressExcessPropertyErrors && !getIndexInfoOfType(contextualType, 0 /* String */)) { + error(memberDecl.name, ts.Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(member), typeToString(contextualType)); + } + } + prop.declarations = member.declarations; + prop.parent = member.parent; + if (member.valueDeclaration) { + prop.valueDeclaration = member.valueDeclaration; + } + prop.type = type; + prop.target = member; + member = prop; + } + else if (memberDecl.kind === 277 /* SpreadAssignment */) { + if (languageVersion < 2 /* ES2015 */) { + checkExternalEmitHelpers(memberDecl, 2 /* Assign */); + } + if (propertiesArray.length > 0) { + spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, propagatedFlags, 32768 /* FreshLiteral */); + propertiesArray = []; + propertiesTable = ts.createSymbolTable(); + hasComputedStringProperty = false; + hasComputedNumberProperty = false; + typeFlags = 0; + } + var type = checkExpression(memberDecl.expression); + if (!isValidSpreadType(type)) { + error(memberDecl, ts.Diagnostics.Spread_types_may_only_be_created_from_object_types); + return errorType; + } + spread = getSpreadType(spread, type, node.symbol, propagatedFlags, 32768 /* FreshLiteral */); + offset = i + 1; + continue; + } + else { + // TypeScript 1.0 spec (April 2014) + // A get accessor declaration is processed in the same manner as + // an ordinary function declaration(section 6.1) with no parameters. + // A set accessor declaration is processed in the same manner + // as an ordinary function declaration with a single parameter and a Void return type. + ts.Debug.assert(memberDecl.kind === 158 /* GetAccessor */ || memberDecl.kind === 159 /* SetAccessor */); + checkNodeDeferred(memberDecl); + } + if (computedNameType && !(computedNameType.flags & 8576 /* StringOrNumberLiteralOrUnique */)) { + if (isTypeAssignableTo(computedNameType, stringNumberSymbolType)) { + if (isTypeAssignableTo(computedNameType, numberType)) { + hasComputedNumberProperty = true; + } + else { + hasComputedStringProperty = true; + } + if (inDestructuringPattern) { + patternWithComputedProperties = true; + } + } + } + else { + propertiesTable.set(member.escapedName, member); + } + propertiesArray.push(member); + } + // If object literal is contextually typed by the implied type of a binding pattern, augment the result + // type with those properties for which the binding pattern specifies a default value. + if (contextualTypeHasPattern) { + for (var _i = 0, _a = getPropertiesOfType(contextualType); _i < _a.length; _i++) { + var prop = _a[_i]; + if (!propertiesTable.get(prop.escapedName) && !(spread && getPropertyOfType(spread, prop.escapedName))) { + if (!(prop.flags & 16777216 /* Optional */)) { + error(prop.valueDeclaration || prop.bindingElement, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); + } + propertiesTable.set(prop.escapedName, prop); + propertiesArray.push(prop); + } + } + } + if (spread !== emptyObjectType) { + if (propertiesArray.length > 0) { + spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, propagatedFlags, 32768 /* FreshLiteral */); + } + return spread; + } + return createObjectLiteralType(); + function createObjectLiteralType() { + var stringIndexInfo = hasComputedStringProperty ? getObjectLiteralIndexInfo(node.properties, offset, propertiesArray, 0 /* String */) : undefined; + var numberIndexInfo = hasComputedNumberProperty ? getObjectLiteralIndexInfo(node.properties, offset, propertiesArray, 1 /* Number */) : undefined; + var result = createAnonymousType(node.symbol, propertiesTable, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); + result.flags |= 268435456 /* ContainsObjectLiteral */ | typeFlags & 939524096 /* PropagatingFlags */; + result.objectFlags |= 128 /* ObjectLiteral */ | freshObjectLiteralFlag; + if (isJSObjectLiteral) { + result.objectFlags |= 16384 /* JSLiteral */; + } + if (patternWithComputedProperties) { + result.objectFlags |= 512 /* ObjectLiteralPatternWithComputedProperties */; + } + if (inDestructuringPattern) { + result.pattern = node; + } + propagatedFlags |= result.flags & 939524096 /* PropagatingFlags */; + return result; + } + } + function isValidSpreadType(type) { + return !!(type.flags & (3 /* AnyOrUnknown */ | 67108864 /* NonPrimitive */ | 524288 /* Object */ | 58982400 /* InstantiableNonPrimitive */) || + getFalsyFlags(type) & 117632 /* DefinitelyFalsy */ && isValidSpreadType(removeDefinitelyFalsyTypes(type)) || + type.flags & 3145728 /* UnionOrIntersection */ && ts.every(type.types, isValidSpreadType)); + } + function checkJsxSelfClosingElementDeferred(node) { + checkJsxOpeningLikeElementOrOpeningFragment(node); + } + function checkJsxSelfClosingElement(node, _checkMode) { + checkNodeDeferred(node); + return getJsxElementTypeAt(node) || anyType; + } + function checkJsxElementDeferred(node) { + // Check attributes + checkJsxOpeningLikeElementOrOpeningFragment(node.openingElement); + // Perform resolution on the closing tag so that rename/go to definition/etc work + if (isJsxIntrinsicIdentifier(node.closingElement.tagName)) { + getIntrinsicTagSymbol(node.closingElement); + } + else { + checkExpression(node.closingElement.tagName); + } + checkJsxChildren(node); + } + function checkJsxElement(node, _checkMode) { + checkNodeDeferred(node); + return getJsxElementTypeAt(node) || anyType; + } + function checkJsxFragment(node) { + checkJsxOpeningLikeElementOrOpeningFragment(node.openingFragment); + if (compilerOptions.jsx === 2 /* React */ && (compilerOptions.jsxFactory || ts.getSourceFileOfNode(node).pragmas.has("jsx"))) { + error(node, compilerOptions.jsxFactory + ? ts.Diagnostics.JSX_fragment_is_not_supported_when_using_jsxFactory + : ts.Diagnostics.JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma); + } + checkJsxChildren(node); + return getJsxElementTypeAt(node) || anyType; + } + /** + * Returns true iff the JSX element name would be a valid JS identifier, ignoring restrictions about keywords not being identifiers + */ + function isUnhyphenatedJsxName(name) { + // - is the only character supported in JSX attribute names that isn't valid in JavaScript identifiers + return !ts.stringContains(name, "-"); + } + /** + * Returns true iff React would emit this tag name as a string rather than an identifier or qualified name + */ + function isJsxIntrinsicIdentifier(tagName) { + return tagName.kind === 72 /* Identifier */ && ts.isIntrinsicJsxName(tagName.escapedText); + } + function checkJsxAttribute(node, checkMode) { + return node.initializer + ? checkExpressionForMutableLocation(node.initializer, checkMode) + : trueType; // is sugar for + } + /** + * Get attributes type of the JSX opening-like element. The result is from resolving "attributes" property of the opening-like element. + * + * @param openingLikeElement a JSX opening-like element + * @param filter a function to remove attributes that will not participate in checking whether attributes are assignable + * @return an anonymous type (similar to the one returned by checkObjectLiteral) in which its properties are attributes property. + * @remarks Because this function calls getSpreadType, it needs to use the same checks as checkObjectLiteral, + * which also calls getSpreadType. + */ + function createJsxAttributesTypeFromAttributesProperty(openingLikeElement, checkMode) { + var attributes = openingLikeElement.attributes; + var attributesTable = ts.createSymbolTable(); + var spread = emptyJsxObjectType; + var hasSpreadAnyType = false; + var typeToIntersect; + var explicitlySpecifyChildrenAttribute = false; + var typeFlags = 0; + var objectFlags = 4096 /* JsxAttributes */; + var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(openingLikeElement)); + for (var _i = 0, _a = attributes.properties; _i < _a.length; _i++) { + var attributeDecl = _a[_i]; + var member = attributeDecl.symbol; + if (ts.isJsxAttribute(attributeDecl)) { + var exprType = checkJsxAttribute(attributeDecl, checkMode); + typeFlags |= exprType.flags & 939524096 /* PropagatingFlags */; + var attributeSymbol = createSymbol(4 /* Property */ | 33554432 /* Transient */ | member.flags, member.escapedName); + attributeSymbol.declarations = member.declarations; + attributeSymbol.parent = member.parent; + if (member.valueDeclaration) { + attributeSymbol.valueDeclaration = member.valueDeclaration; + } + attributeSymbol.type = exprType; + attributeSymbol.target = member; + attributesTable.set(attributeSymbol.escapedName, attributeSymbol); + if (attributeDecl.name.escapedText === jsxChildrenPropertyName) { + explicitlySpecifyChildrenAttribute = true; + } + } + else { + ts.Debug.assert(attributeDecl.kind === 269 /* JsxSpreadAttribute */); + if (attributesTable.size > 0) { + spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, typeFlags, objectFlags); + attributesTable = ts.createSymbolTable(); + } + var exprType = checkExpressionCached(attributeDecl.expression, checkMode); + if (isTypeAny(exprType)) { + hasSpreadAnyType = true; + } + if (isValidSpreadType(exprType)) { + spread = getSpreadType(spread, exprType, attributes.symbol, typeFlags, objectFlags); + } + else { + typeToIntersect = typeToIntersect ? getIntersectionType([typeToIntersect, exprType]) : exprType; + } + } + } + if (!hasSpreadAnyType) { + if (attributesTable.size > 0) { + spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, typeFlags, objectFlags); + } + } + // Handle children attribute + var parent = openingLikeElement.parent.kind === 260 /* JsxElement */ ? openingLikeElement.parent : undefined; + // We have to check that openingElement of the parent is the one we are visiting as this may not be true for selfClosingElement + if (parent && parent.openingElement === openingLikeElement && parent.children.length > 0) { + var childrenTypes = checkJsxChildren(parent, checkMode); + if (!hasSpreadAnyType && jsxChildrenPropertyName && jsxChildrenPropertyName !== "") { + // Error if there is a attribute named "children" explicitly specified and children element. + // This is because children element will overwrite the value from attributes. + // Note: we will not warn "children" attribute overwritten if "children" attribute is specified in object spread. + if (explicitlySpecifyChildrenAttribute) { + error(attributes, ts.Diagnostics._0_are_specified_twice_The_attribute_named_0_will_be_overwritten, ts.unescapeLeadingUnderscores(jsxChildrenPropertyName)); + } + var contextualType = getApparentTypeOfContextualType(openingLikeElement.attributes); + var childrenContextualType = contextualType && getTypeOfPropertyOfContextualType(contextualType, jsxChildrenPropertyName); + // If there are children in the body of JSX element, create dummy attribute "children" with the union of children types so that it will pass the attribute checking process + var childrenPropSymbol = createSymbol(4 /* Property */ | 33554432 /* Transient */, jsxChildrenPropertyName); + childrenPropSymbol.type = childrenTypes.length === 1 ? + childrenTypes[0] : + (getArrayLiteralTupleTypeIfApplicable(childrenTypes, childrenContextualType, /*hasRestElement*/ false) || createArrayType(getUnionType(childrenTypes))); + var childPropMap = ts.createSymbolTable(); + childPropMap.set(jsxChildrenPropertyName, childrenPropSymbol); + spread = getSpreadType(spread, createAnonymousType(attributes.symbol, childPropMap, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined), attributes.symbol, typeFlags, objectFlags); + } + } + if (hasSpreadAnyType) { + return anyType; + } + if (typeToIntersect && spread !== emptyJsxObjectType) { + return getIntersectionType([typeToIntersect, spread]); + } + return typeToIntersect || (spread === emptyJsxObjectType ? createJsxAttributesType() : spread); + /** + * Create anonymous type from given attributes symbol table. + * @param symbol a symbol of JsxAttributes containing attributes corresponding to attributesTable + * @param attributesTable a symbol table of attributes property + */ + function createJsxAttributesType() { + objectFlags |= freshObjectLiteralFlag; + var result = createAnonymousType(attributes.symbol, attributesTable, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined); + result.flags |= 268435456 /* ContainsObjectLiteral */ | typeFlags; + result.objectFlags |= 128 /* ObjectLiteral */ | objectFlags; + return result; + } + } + function checkJsxChildren(node, checkMode) { + var childrenTypes = []; + for (var _i = 0, _a = node.children; _i < _a.length; _i++) { + var child = _a[_i]; + // In React, JSX text that contains only whitespaces will be ignored so we don't want to type-check that + // because then type of children property will have constituent of string type. + if (child.kind === 11 /* JsxText */) { + if (!child.containsOnlyWhiteSpaces) { + childrenTypes.push(stringType); + } + } + else { + childrenTypes.push(checkExpressionForMutableLocation(child, checkMode)); + } + } + return childrenTypes; + } + /** + * Check attributes property of opening-like element. This function is called during chooseOverload to get call signature of a JSX opening-like element. + * (See "checkApplicableSignatureForJsxOpeningLikeElement" for how the function is used) + * @param node a JSXAttributes to be resolved of its type + */ + function checkJsxAttributes(node, checkMode) { + return createJsxAttributesTypeFromAttributesProperty(node.parent, checkMode); + } + function getJsxType(name, location) { + var namespace = getJsxNamespaceAt(location); + var exports = namespace && getExportsOfSymbol(namespace); + var typeSymbol = exports && getSymbol(exports, name, 67897832 /* Type */); + return typeSymbol ? getDeclaredTypeOfSymbol(typeSymbol) : errorType; + } + /** + * Looks up an intrinsic tag name and returns a symbol that either points to an intrinsic + * property (in which case nodeLinks.jsxFlags will be IntrinsicNamedElement) or an intrinsic + * string index signature (in which case nodeLinks.jsxFlags will be IntrinsicIndexedElement). + * May also return unknownSymbol if both of these lookups fail. + */ + function getIntrinsicTagSymbol(node) { + var links = getNodeLinks(node); + if (!links.resolvedSymbol) { + var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements, node); + if (intrinsicElementsType !== errorType) { + // Property case + if (!ts.isIdentifier(node.tagName)) + return ts.Debug.fail(); + var intrinsicProp = getPropertyOfType(intrinsicElementsType, node.tagName.escapedText); + if (intrinsicProp) { + links.jsxFlags |= 1 /* IntrinsicNamedElement */; + return links.resolvedSymbol = intrinsicProp; + } + // Intrinsic string indexer case + var indexSignatureType = getIndexTypeOfType(intrinsicElementsType, 0 /* String */); + if (indexSignatureType) { + links.jsxFlags |= 2 /* IntrinsicIndexedElement */; + return links.resolvedSymbol = intrinsicElementsType.symbol; + } + // Wasn't found + error(node, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.idText(node.tagName), "JSX." + JsxNames.IntrinsicElements); + return links.resolvedSymbol = unknownSymbol; + } + else { + if (noImplicitAny) { + error(node, ts.Diagnostics.JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists, ts.unescapeLeadingUnderscores(JsxNames.IntrinsicElements)); + } + return links.resolvedSymbol = unknownSymbol; + } + } + return links.resolvedSymbol; + } + function getJsxNamespaceAt(location) { + var links = location && getNodeLinks(location); + if (links && links.jsxNamespace) { + return links.jsxNamespace; + } + if (!links || links.jsxNamespace !== false) { + var namespaceName = getJsxNamespace(location); + var resolvedNamespace = resolveName(location, namespaceName, 1920 /* Namespace */, /*diagnosticMessage*/ undefined, namespaceName, /*isUse*/ false); + if (resolvedNamespace) { + var candidate = getSymbol(getExportsOfSymbol(resolveSymbol(resolvedNamespace)), JsxNames.JSX, 1920 /* Namespace */); + if (candidate) { + if (links) { + links.jsxNamespace = candidate; + } + return candidate; + } + if (links) { + links.jsxNamespace = false; + } + } + } + // JSX global fallback + return getGlobalSymbol(JsxNames.JSX, 1920 /* Namespace */, /*diagnosticMessage*/ undefined); // TODO: GH#18217 + } + /** + * Look into JSX namespace and then look for container with matching name as nameOfAttribPropContainer. + * Get a single property from that container if existed. Report an error if there are more than one property. + * + * @param nameOfAttribPropContainer a string of value JsxNames.ElementAttributesPropertyNameContainer or JsxNames.ElementChildrenAttributeNameContainer + * if other string is given or the container doesn't exist, return undefined. + */ + function getNameFromJsxElementAttributesContainer(nameOfAttribPropContainer, jsxNamespace) { + // JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute [symbol] + var jsxElementAttribPropInterfaceSym = jsxNamespace && getSymbol(jsxNamespace.exports, nameOfAttribPropContainer, 67897832 /* Type */); + // JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute [type] + var jsxElementAttribPropInterfaceType = jsxElementAttribPropInterfaceSym && getDeclaredTypeOfSymbol(jsxElementAttribPropInterfaceSym); + // The properties of JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute + var propertiesOfJsxElementAttribPropInterface = jsxElementAttribPropInterfaceType && getPropertiesOfType(jsxElementAttribPropInterfaceType); + if (propertiesOfJsxElementAttribPropInterface) { + // Element Attributes has zero properties, so the element attributes type will be the class instance type + if (propertiesOfJsxElementAttribPropInterface.length === 0) { + return ""; + } + // Element Attributes has one property, so the element attributes type will be the type of the corresponding + // property of the class instance type + else if (propertiesOfJsxElementAttribPropInterface.length === 1) { + return propertiesOfJsxElementAttribPropInterface[0].escapedName; + } + else if (propertiesOfJsxElementAttribPropInterface.length > 1) { + // More than one property on ElementAttributesProperty is an error + error(jsxElementAttribPropInterfaceSym.declarations[0], ts.Diagnostics.The_global_type_JSX_0_may_not_have_more_than_one_property, ts.unescapeLeadingUnderscores(nameOfAttribPropContainer)); + } + } + return undefined; + } + function getJsxLibraryManagedAttributes(jsxNamespace) { + // JSX.LibraryManagedAttributes [symbol] + return jsxNamespace && getSymbol(jsxNamespace.exports, JsxNames.LibraryManagedAttributes, 67897832 /* Type */); + } + /// e.g. "props" for React.d.ts, + /// or 'undefined' if ElementAttributesProperty doesn't exist (which means all + /// non-intrinsic elements' attributes type is 'any'), + /// or '' if it has 0 properties (which means every + /// non-intrinsic elements' attributes type is the element instance type) + function getJsxElementPropertiesName(jsxNamespace) { + return getNameFromJsxElementAttributesContainer(JsxNames.ElementAttributesPropertyNameContainer, jsxNamespace); + } + function getJsxElementChildrenPropertyName(jsxNamespace) { + return getNameFromJsxElementAttributesContainer(JsxNames.ElementChildrenAttributeNameContainer, jsxNamespace); + } + function getUninstantiatedJsxSignaturesOfType(elementType, caller) { + if (elementType.flags & 4 /* String */) { + return [anySignature]; + } + else if (elementType.flags & 128 /* StringLiteral */) { + var intrinsicType = getIntrinsicAttributesTypeFromStringLiteralType(elementType, caller); + if (!intrinsicType) { + error(caller, ts.Diagnostics.Property_0_does_not_exist_on_type_1, elementType.value, "JSX." + JsxNames.IntrinsicElements); + return ts.emptyArray; + } + else { + var fakeSignature = createSignatureForJSXIntrinsic(caller, intrinsicType); + return [fakeSignature]; + } + } + var apparentElemType = getApparentType(elementType); + // Resolve the signatures, preferring constructor + var signatures = getSignaturesOfType(apparentElemType, 1 /* Construct */); + if (signatures.length === 0) { + // No construct signatures, try call signatures + signatures = getSignaturesOfType(apparentElemType, 0 /* Call */); + } + if (signatures.length === 0 && apparentElemType.flags & 1048576 /* Union */) { + // If each member has some combination of new/call signatures; make a union signature list for those + signatures = getUnionSignatures(ts.map(apparentElemType.types, function (t) { return getUninstantiatedJsxSignaturesOfType(t, caller); })); + } + return signatures; + } + function getIntrinsicAttributesTypeFromStringLiteralType(type, location) { + // If the elemType is a stringLiteral type, we can then provide a check to make sure that the string literal type is one of the Jsx intrinsic element type + // For example: + // var CustomTag: "h1" = "h1"; + // Hello World + var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements, location); + if (intrinsicElementsType !== errorType) { + var stringLiteralTypeName = type.value; + var intrinsicProp = getPropertyOfType(intrinsicElementsType, ts.escapeLeadingUnderscores(stringLiteralTypeName)); + if (intrinsicProp) { + return getTypeOfSymbol(intrinsicProp); + } + var indexSignatureType = getIndexTypeOfType(intrinsicElementsType, 0 /* String */); + if (indexSignatureType) { + return indexSignatureType; + } + return undefined; + } + // If we need to report an error, we already done so here. So just return any to prevent any more error downstream + return anyType; + } + function checkJsxReturnAssignableToAppropriateBound(refKind, elemInstanceType, openingLikeElement) { + if (refKind === 1 /* Function */) { + var sfcReturnConstraint = getJsxStatelessElementTypeAt(openingLikeElement); + if (sfcReturnConstraint) { + checkTypeRelatedTo(elemInstanceType, sfcReturnConstraint, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); + } + } + else if (refKind === 0 /* Component */) { + var classConstraint = getJsxElementClassTypeAt(openingLikeElement); + if (classConstraint) { + // Issue an error if this return type isn't assignable to JSX.ElementClass or JSX.Element, failing that + checkTypeRelatedTo(elemInstanceType, classConstraint, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); + } + } + else { // Mixed + var sfcReturnConstraint = getJsxStatelessElementTypeAt(openingLikeElement); + var classConstraint = getJsxElementClassTypeAt(openingLikeElement); + if (!sfcReturnConstraint || !classConstraint) { + return; + } + var combined = getUnionType([sfcReturnConstraint, classConstraint]); + checkTypeRelatedTo(elemInstanceType, combined, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); + } + } + /** + * Get attributes type of the given intrinsic opening-like Jsx element by resolving the tag name. + * The function is intended to be called from a function which has checked that the opening element is an intrinsic element. + * @param node an intrinsic JSX opening-like element + */ + function getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node) { + ts.Debug.assert(isJsxIntrinsicIdentifier(node.tagName)); + var links = getNodeLinks(node); + if (!links.resolvedJsxElementAttributesType) { + var symbol = getIntrinsicTagSymbol(node); + if (links.jsxFlags & 1 /* IntrinsicNamedElement */) { + return links.resolvedJsxElementAttributesType = getTypeOfSymbol(symbol); + } + else if (links.jsxFlags & 2 /* IntrinsicIndexedElement */) { + return links.resolvedJsxElementAttributesType = getIndexInfoOfSymbol(symbol, 0 /* String */).type; + } + else { + return links.resolvedJsxElementAttributesType = errorType; + } + } + return links.resolvedJsxElementAttributesType; + } + function getJsxElementClassTypeAt(location) { + var type = getJsxType(JsxNames.ElementClass, location); + if (type === errorType) + return undefined; + return type; + } + function getJsxElementTypeAt(location) { + return getJsxType(JsxNames.Element, location); + } + function getJsxStatelessElementTypeAt(location) { + var jsxElementType = getJsxElementTypeAt(location); + if (jsxElementType) { + return getUnionType([jsxElementType, nullType]); + } + } + /** + * Returns all the properties of the Jsx.IntrinsicElements interface + */ + function getJsxIntrinsicTagNamesAt(location) { + var intrinsics = getJsxType(JsxNames.IntrinsicElements, location); + return intrinsics ? getPropertiesOfType(intrinsics) : ts.emptyArray; + } + function checkJsxPreconditions(errorNode) { + // Preconditions for using JSX + if ((compilerOptions.jsx || 0 /* None */) === 0 /* None */) { + error(errorNode, ts.Diagnostics.Cannot_use_JSX_unless_the_jsx_flag_is_provided); + } + if (getJsxElementTypeAt(errorNode) === undefined) { + if (noImplicitAny) { + error(errorNode, ts.Diagnostics.JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist); + } + } + } + function checkJsxOpeningLikeElementOrOpeningFragment(node) { + var isNodeOpeningLikeElement = ts.isJsxOpeningLikeElement(node); + if (isNodeOpeningLikeElement) { + checkGrammarJsxElement(node); + } + checkJsxPreconditions(node); + // The reactNamespace/jsxFactory's root symbol should be marked as 'used' so we don't incorrectly elide its import. + // And if there is no reactNamespace/jsxFactory's symbol in scope when targeting React emit, we should issue an error. + var reactRefErr = diagnostics && compilerOptions.jsx === 2 /* React */ ? ts.Diagnostics.Cannot_find_name_0 : undefined; + var reactNamespace = getJsxNamespace(node); + var reactLocation = isNodeOpeningLikeElement ? node.tagName : node; + var reactSym = resolveName(reactLocation, reactNamespace, 67220415 /* Value */, reactRefErr, reactNamespace, /*isUse*/ true); + if (reactSym) { + // Mark local symbol as referenced here because it might not have been marked + // if jsx emit was not react as there wont be error being emitted + reactSym.isReferenced = 67108863 /* All */; + // If react symbol is alias, mark it as refereced + if (reactSym.flags & 2097152 /* Alias */ && !isConstEnumOrConstEnumOnlyModule(resolveAlias(reactSym))) { + markAliasSymbolAsReferenced(reactSym); + } + } + if (isNodeOpeningLikeElement) { + var sig = getResolvedSignature(node); + checkJsxReturnAssignableToAppropriateBound(getJsxReferenceKind(node), getReturnTypeOfSignature(sig), node); + } + } + /** + * Check if a property with the given name is known anywhere in the given type. In an object type, a property + * is considered known if + * 1. the object type is empty and the check is for assignability, or + * 2. if the object type has index signatures, or + * 3. if the property is actually declared in the object type + * (this means that 'toString', for example, is not usually a known property). + * 4. In a union or intersection type, + * a property is considered known if it is known in any constituent type. + * @param targetType a type to search a given name in + * @param name a property name to search + * @param isComparingJsxAttributes a boolean flag indicating whether we are searching in JsxAttributesType + */ + function isKnownProperty(targetType, name, isComparingJsxAttributes) { + if (targetType.flags & 524288 /* Object */) { + var resolved = resolveStructuredTypeMembers(targetType); + if (resolved.stringIndexInfo || + resolved.numberIndexInfo && isNumericLiteralName(name) || + getPropertyOfObjectType(targetType, name) || + isComparingJsxAttributes && !isUnhyphenatedJsxName(name)) { + // For JSXAttributes, if the attribute has a hyphenated name, consider that the attribute to be known. + return true; + } + } + else if (targetType.flags & 3145728 /* UnionOrIntersection */) { + for (var _i = 0, _a = targetType.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (isKnownProperty(t, name, isComparingJsxAttributes)) { + return true; + } + } + } + else if (targetType.flags & 16777216 /* Conditional */) { + return isKnownProperty(targetType.root.trueType, name, isComparingJsxAttributes) || + isKnownProperty(targetType.root.falseType, name, isComparingJsxAttributes); + } + return false; + } + function checkJsxExpression(node, checkMode) { + if (node.expression) { + var type = checkExpression(node.expression, checkMode); + if (node.dotDotDotToken && type !== anyType && !isArrayType(type)) { + error(node, ts.Diagnostics.JSX_spread_child_must_be_an_array_type); + } + return type; + } + else { + return errorType; + } + } + function getDeclarationNodeFlagsFromSymbol(s) { + return s.valueDeclaration ? ts.getCombinedNodeFlags(s.valueDeclaration) : 0; + } + /** + * Return whether this symbol is a member of a prototype somewhere + * Note that this is not tracked well within the compiler, so the answer may be incorrect. + */ + function isPrototypeProperty(symbol) { + if (symbol.flags & 8192 /* Method */ || ts.getCheckFlags(symbol) & 4 /* SyntheticMethod */) { + return true; + } + if (ts.isInJSFile(symbol.valueDeclaration)) { + var parent = symbol.valueDeclaration.parent; + return parent && ts.isBinaryExpression(parent) && + ts.getAssignmentDeclarationKind(parent) === 3 /* PrototypeProperty */; + } + } + /** + * Check whether the requested property access is valid. + * Returns true if node is a valid property access, and false otherwise. + * @param node The node to be checked. + * @param isSuper True if the access is from `super.`. + * @param type The type of the object whose property is being accessed. (Not the type of the property.) + * @param prop The symbol for the property being accessed. + */ + function checkPropertyAccessibility(node, isSuper, type, prop) { + var flags = ts.getDeclarationModifierFlagsFromSymbol(prop); + var errorNode = node.kind === 148 /* QualifiedName */ ? node.right : node.kind === 183 /* ImportType */ ? node : node.name; + if (ts.getCheckFlags(prop) & 256 /* ContainsPrivate */) { + // Synthetic property with private constituent property + error(errorNode, ts.Diagnostics.Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1, symbolToString(prop), typeToString(type)); + return false; + } + if (isSuper) { + // TS 1.0 spec (April 2014): 4.8.2 + // - In a constructor, instance member function, instance member accessor, or + // instance member variable initializer where this references a derived class instance, + // a super property access is permitted and must specify a public instance member function of the base class. + // - In a static member function or static member accessor + // where this references the constructor function object of a derived class, + // a super property access is permitted and must specify a public static member function of the base class. + if (languageVersion < 2 /* ES2015 */) { + if (symbolHasNonMethodDeclaration(prop)) { + error(errorNode, ts.Diagnostics.Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword); + return false; + } + } + if (flags & 128 /* Abstract */) { + // A method cannot be accessed in a super property access if the method is abstract. + // This error could mask a private property access error. But, a member + // cannot simultaneously be private and abstract, so this will trigger an + // additional error elsewhere. + error(errorNode, ts.Diagnostics.Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression, symbolToString(prop), typeToString(getDeclaringClass(prop))); + return false; + } + } + // Referencing abstract properties within their own constructors is not allowed + if ((flags & 128 /* Abstract */) && ts.isThisProperty(node) && symbolHasNonMethodDeclaration(prop)) { + var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop)); + if (declaringClassDeclaration && isNodeUsedDuringClassInitialization(node)) { + error(errorNode, ts.Diagnostics.Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor, symbolToString(prop), ts.getTextOfIdentifierOrLiteral(declaringClassDeclaration.name)); // TODO: GH#18217 + return false; + } + } + // Public properties are otherwise accessible. + if (!(flags & 24 /* NonPublicAccessibilityModifier */)) { + return true; + } + // Property is known to be private or protected at this point + // Private property is accessible if the property is within the declaring class + if (flags & 8 /* Private */) { + var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop)); + if (!isNodeWithinClass(node, declaringClassDeclaration)) { + error(errorNode, ts.Diagnostics.Property_0_is_private_and_only_accessible_within_class_1, symbolToString(prop), typeToString(getDeclaringClass(prop))); + return false; + } + return true; + } + // Property is known to be protected at this point + // All protected properties of a supertype are accessible in a super access + if (isSuper) { + return true; + } + // Find the first enclosing class that has the declaring classes of the protected constituents + // of the property as base classes + var enclosingClass = forEachEnclosingClass(node, function (enclosingDeclaration) { + var enclosingClass = getDeclaredTypeOfSymbol(getSymbolOfNode(enclosingDeclaration)); + return isClassDerivedFromDeclaringClasses(enclosingClass, prop) ? enclosingClass : undefined; + }); + // A protected property is accessible if the property is within the declaring class or classes derived from it + if (!enclosingClass) { + // allow PropertyAccessibility if context is in function with this parameter + // static member access is disallow + var thisParameter = void 0; + if (flags & 32 /* Static */ || !(thisParameter = getThisParameterFromNodeContext(node)) || !thisParameter.type) { + error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses, symbolToString(prop), typeToString(getDeclaringClass(prop) || type)); + return false; + } + var thisType = getTypeFromTypeNode(thisParameter.type); + enclosingClass = ((thisType.flags & 262144 /* TypeParameter */) ? getConstraintOfTypeParameter(thisType) : thisType); + } + // No further restrictions for static properties + if (flags & 32 /* Static */) { + return true; + } + if (type.flags & 262144 /* TypeParameter */) { + // get the original type -- represented as the type constraint of the 'this' type + type = type.isThisType ? getConstraintOfTypeParameter(type) : getBaseConstraintOfType(type); // TODO: GH#18217 Use a different variable that's allowed to be undefined + } + if (!type || !hasBaseType(type, enclosingClass)) { + error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1, symbolToString(prop), typeToString(enclosingClass)); + return false; + } + return true; + } + function getThisParameterFromNodeContext(node) { + var thisContainer = ts.getThisContainer(node, /* includeArrowFunctions */ false); + return thisContainer && ts.isFunctionLike(thisContainer) ? ts.getThisParameter(thisContainer) : undefined; + } + function symbolHasNonMethodDeclaration(symbol) { + return !!forEachProperty(symbol, function (prop) { return !(prop.flags & 8192 /* Method */); }); + } + function checkNonNullExpression(node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic) { + return checkNonNullType(checkExpression(node), node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic); + } + function getNonNullableTypeIfNeeded(type) { + var kind = (strictNullChecks ? getFalsyFlags(type) : type.flags) & 98304 /* Nullable */; + if (kind) { + return getNonNullableType(type); + } + return type; + } + function checkNonNullType(type, node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic) { + if (type.flags & 2 /* Unknown */) { + error(node, ts.Diagnostics.Object_is_of_type_unknown); + return errorType; + } + var kind = (strictNullChecks ? getFalsyFlags(type) : type.flags) & 98304 /* Nullable */; + if (kind) { + error(node, kind & 32768 /* Undefined */ ? kind & 65536 /* Null */ ? + (nullOrUndefinedDiagnostic || ts.Diagnostics.Object_is_possibly_null_or_undefined) : + (undefinedDiagnostic || ts.Diagnostics.Object_is_possibly_undefined) : + (nullDiagnostic || ts.Diagnostics.Object_is_possibly_null)); + var t = getNonNullableType(type); + return t.flags & (98304 /* Nullable */ | 131072 /* Never */) ? errorType : t; + } + return type; + } + function checkPropertyAccessExpression(node) { + return checkPropertyAccessExpressionOrQualifiedName(node, node.expression, node.name); + } + function checkQualifiedName(node) { + return checkPropertyAccessExpressionOrQualifiedName(node, node.left, node.right); + } + function checkPropertyAccessExpressionOrQualifiedName(node, left, right) { + var propType; + var leftType = checkNonNullExpression(left); + var parentSymbol = getNodeLinks(left).resolvedSymbol; + var apparentType = getApparentType(getWidenedType(leftType)); + if (isTypeAny(apparentType) || apparentType === silentNeverType) { + if (ts.isIdentifier(left) && parentSymbol) { + markAliasReferenced(parentSymbol, node); + } + return apparentType; + } + var assignmentKind = ts.getAssignmentTargetKind(node); + var prop = getPropertyOfType(apparentType, right.escapedText); + if (ts.isIdentifier(left) && parentSymbol && !(prop && isConstEnumOrConstEnumOnlyModule(prop))) { + markAliasReferenced(parentSymbol, node); + } + if (!prop) { + var indexInfo = getIndexInfoOfType(apparentType, 0 /* String */); + if (!(indexInfo && indexInfo.type)) { + if (isJSLiteralType(leftType)) { + return anyType; + } + if (right.escapedText && !checkAndReportErrorForExtendingInterface(node)) { + reportNonexistentProperty(right, leftType.flags & 262144 /* TypeParameter */ && leftType.isThisType ? apparentType : leftType); + } + return errorType; + } + if (indexInfo.isReadonly && (ts.isAssignmentTarget(node) || ts.isDeleteTarget(node))) { + error(node, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(apparentType)); + } + propType = indexInfo.type; + } + else { + checkPropertyNotUsedBeforeDeclaration(prop, node, right); + markPropertyAsReferenced(prop, node, left.kind === 100 /* ThisKeyword */); + getNodeLinks(node).resolvedSymbol = prop; + checkPropertyAccessibility(node, left.kind === 98 /* SuperKeyword */, apparentType, prop); + if (assignmentKind) { + if (isReferenceToReadonlyEntity(node, prop) || isReferenceThroughNamespaceImport(node)) { + error(right, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, ts.idText(right)); + return errorType; + } + } + propType = getConstraintForLocation(getTypeOfSymbol(prop), node); + } + // Only compute control flow type if this is a property access expression that isn't an + // assignment target, and the referenced property was declared as a variable, property, + // accessor, or optional method. + if (node.kind !== 189 /* PropertyAccessExpression */ || + assignmentKind === 1 /* Definite */ || + prop && !(prop.flags & (3 /* Variable */ | 4 /* Property */ | 98304 /* Accessor */)) && !(prop.flags & 8192 /* Method */ && propType.flags & 1048576 /* Union */)) { + return propType; + } + // If strict null checks and strict property initialization checks are enabled, if we have + // a this.xxx property access, if the property is an instance property without an initializer, + // and if we are in a constructor of the same class as the property declaration, assume that + // the property is uninitialized at the top of the control flow. + var assumeUninitialized = false; + if (strictNullChecks && strictPropertyInitialization && left.kind === 100 /* ThisKeyword */) { + var declaration = prop && prop.valueDeclaration; + if (declaration && isInstancePropertyWithoutInitializer(declaration)) { + var flowContainer = getControlFlowContainer(node); + if (flowContainer.kind === 157 /* Constructor */ && flowContainer.parent === declaration.parent) { + assumeUninitialized = true; + } + } + } + else if (strictNullChecks && prop && prop.valueDeclaration && + ts.isPropertyAccessExpression(prop.valueDeclaration) && + ts.getAssignmentDeclarationPropertyAccessKind(prop.valueDeclaration) && + getControlFlowContainer(node) === getControlFlowContainer(prop.valueDeclaration)) { + assumeUninitialized = true; + } + var flowType = getFlowTypeOfReference(node, propType, assumeUninitialized ? getOptionalType(propType) : propType); + if (assumeUninitialized && !(getFalsyFlags(propType) & 32768 /* Undefined */) && getFalsyFlags(flowType) & 32768 /* Undefined */) { + error(right, ts.Diagnostics.Property_0_is_used_before_being_assigned, symbolToString(prop)); // TODO: GH#18217 + // Return the declared type to reduce follow-on errors + return propType; + } + return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType; + } + function checkPropertyNotUsedBeforeDeclaration(prop, node, right) { + var valueDeclaration = prop.valueDeclaration; + if (!valueDeclaration) { + return; + } + var diagnosticMessage; + var declarationName = ts.idText(right); + if (isInPropertyInitializer(node) && + !isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right) + && !isPropertyDeclaredInAncestorClass(prop)) { + diagnosticMessage = error(right, ts.Diagnostics.Property_0_is_used_before_its_initialization, declarationName); + } + else if (valueDeclaration.kind === 240 /* ClassDeclaration */ && + node.parent.kind !== 164 /* TypeReference */ && + !(valueDeclaration.flags & 4194304 /* Ambient */) && + !isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right)) { + diagnosticMessage = error(right, ts.Diagnostics.Class_0_used_before_its_declaration, declarationName); + } + if (diagnosticMessage) { + addRelatedInfo(diagnosticMessage, ts.createDiagnosticForNode(valueDeclaration, ts.Diagnostics._0_is_declared_here, declarationName)); + } + } + function isInPropertyInitializer(node) { + return !!ts.findAncestor(node, function (node) { + switch (node.kind) { + case 154 /* PropertyDeclaration */: + return true; + case 275 /* PropertyAssignment */: + // We might be in `a = { b: this.b }`, so keep looking. See `tests/cases/compiler/useBeforeDeclaration_propertyAssignment.ts`. + return false; + default: + return ts.isExpressionNode(node) ? false : "quit"; + } + }); + } + /** + * It's possible that "prop.valueDeclaration" is a local declaration, but the property was also declared in a superclass. + * In that case we won't consider it used before its declaration, because it gets its value from the superclass' declaration. + */ + function isPropertyDeclaredInAncestorClass(prop) { + if (!(prop.parent.flags & 32 /* Class */)) { + return false; + } + var classType = getTypeOfSymbol(prop.parent); + while (true) { + classType = classType.symbol && getSuperClass(classType); + if (!classType) { + return false; + } + var superProperty = getPropertyOfType(classType, prop.escapedName); + if (superProperty && superProperty.valueDeclaration) { + return true; + } + } + } + function getSuperClass(classType) { + var x = getBaseTypes(classType); + if (x.length === 0) { + return undefined; + } + return getIntersectionType(x); + } + function reportNonexistentProperty(propNode, containingType) { + var errorInfo; + var relatedInfo; + if (containingType.flags & 1048576 /* Union */ && !(containingType.flags & 131068 /* Primitive */)) { + for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) { + var subtype = _a[_i]; + if (!getPropertyOfType(subtype, propNode.escapedText)) { + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(subtype)); + break; + } + } + } + if (typeHasStaticProperty(propNode.escapedText, containingType)) { + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_is_a_static_member_of_type_1, ts.declarationNameToString(propNode), typeToString(containingType)); + } + else { + var promisedType = getPromisedTypeOfPromise(containingType); + if (promisedType && getPropertyOfType(promisedType, propNode.escapedText)) { + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_forget_to_use_await, ts.declarationNameToString(propNode), typeToString(containingType)); + } + else { + var suggestion = getSuggestedSymbolForNonexistentProperty(propNode, containingType); + if (suggestion !== undefined) { + var suggestedName = ts.symbolName(suggestion); + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2, ts.declarationNameToString(propNode), typeToString(containingType), suggestedName); + relatedInfo = suggestion.valueDeclaration && ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestedName); + } + else { + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(containingType)); + } + } + } + var resultDiagnostic = ts.createDiagnosticForNodeFromMessageChain(propNode, errorInfo); + if (relatedInfo) { + addRelatedInfo(resultDiagnostic, relatedInfo); + } + diagnostics.add(resultDiagnostic); + } + function typeHasStaticProperty(propName, containingType) { + var prop = containingType.symbol && getPropertyOfType(getTypeOfSymbol(containingType.symbol), propName); + return prop !== undefined && prop.valueDeclaration && ts.hasModifier(prop.valueDeclaration, 32 /* Static */); + } + function getSuggestedSymbolForNonexistentProperty(name, containingType) { + return getSpellingSuggestionForName(ts.isString(name) ? name : ts.idText(name), getPropertiesOfType(containingType), 67220415 /* Value */); + } + function getSuggestionForNonexistentProperty(name, containingType) { + var suggestion = getSuggestedSymbolForNonexistentProperty(name, containingType); + return suggestion && ts.symbolName(suggestion); + } + function getSuggestedSymbolForNonexistentSymbol(location, outerName, meaning) { + ts.Debug.assert(outerName !== undefined, "outername should always be defined"); + var result = resolveNameHelper(location, outerName, meaning, /*nameNotFoundMessage*/ undefined, outerName, /*isUse*/ false, /*excludeGlobals*/ false, function (symbols, name, meaning) { + ts.Debug.assertEqual(outerName, name, "name should equal outerName"); + var symbol = getSymbol(symbols, name, meaning); + // Sometimes the symbol is found when location is a return type of a function: `typeof x` and `x` is declared in the body of the function + // So the table *contains* `x` but `x` isn't actually in scope. + // However, resolveNameHelper will continue and call this callback again, so we'll eventually get a correct suggestion. + return symbol || getSpellingSuggestionForName(ts.unescapeLeadingUnderscores(name), ts.arrayFrom(symbols.values()), meaning); + }); + return result; + } + function getSuggestionForNonexistentSymbol(location, outerName, meaning) { + var symbolResult = getSuggestedSymbolForNonexistentSymbol(location, outerName, meaning); + return symbolResult && ts.symbolName(symbolResult); + } + function getSuggestedSymbolForNonexistentModule(name, targetModule) { + return targetModule.exports && getSpellingSuggestionForName(ts.idText(name), getExportsOfModuleAsArray(targetModule), 2623475 /* ModuleMember */); + } + function getSuggestionForNonexistentExport(name, targetModule) { + var suggestion = getSuggestedSymbolForNonexistentModule(name, targetModule); + return suggestion && ts.symbolName(suggestion); + } + /** + * Given a name and a list of symbols whose names are *not* equal to the name, return a spelling suggestion if there is one that is close enough. + * Names less than length 3 only check for case-insensitive equality, not levenshtein distance. + * + * If there is a candidate that's the same except for case, return that. + * If there is a candidate that's within one edit of the name, return that. + * Otherwise, return the candidate with the smallest Levenshtein distance, + * except for candidates: + * * With no name + * * Whose meaning doesn't match the `meaning` parameter. + * * Whose length differs from the target name by more than 0.34 of the length of the name. + * * Whose levenshtein distance is more than 0.4 of the length of the name + * (0.4 allows 1 substitution/transposition for every 5 characters, + * and 1 insertion/deletion at 3 characters) + */ + function getSpellingSuggestionForName(name, symbols, meaning) { + return ts.getSpellingSuggestion(name, symbols, getCandidateName); + function getCandidateName(candidate) { + var candidateName = ts.symbolName(candidate); + return !ts.startsWith(candidateName, "\"") && candidate.flags & meaning ? candidateName : undefined; + } + } + function markPropertyAsReferenced(prop, nodeForCheckWriteOnly, isThisAccess) { + if (!prop || !(prop.flags & 106500 /* ClassMember */) || !prop.valueDeclaration || !ts.hasModifier(prop.valueDeclaration, 8 /* Private */)) { + return; + } + if (nodeForCheckWriteOnly && ts.isWriteOnlyAccess(nodeForCheckWriteOnly) && !(prop.flags & 65536 /* SetAccessor */ && !(prop.flags & 32768 /* GetAccessor */))) { + return; + } + if (isThisAccess) { + // Find any FunctionLikeDeclaration because those create a new 'this' binding. But this should only matter for methods (or getters/setters). + var containingMethod = ts.findAncestor(nodeForCheckWriteOnly, ts.isFunctionLikeDeclaration); + if (containingMethod && containingMethod.symbol === prop) { + return; + } + } + (ts.getCheckFlags(prop) & 1 /* Instantiated */ ? getSymbolLinks(prop).target : prop).isReferenced = 67108863 /* All */; + } + function isValidPropertyAccess(node, propertyName) { + switch (node.kind) { + case 189 /* PropertyAccessExpression */: + return isValidPropertyAccessWithType(node, node.expression.kind === 98 /* SuperKeyword */, propertyName, getWidenedType(checkExpression(node.expression))); + case 148 /* QualifiedName */: + return isValidPropertyAccessWithType(node, /*isSuper*/ false, propertyName, getWidenedType(checkExpression(node.left))); + case 183 /* ImportType */: + return isValidPropertyAccessWithType(node, /*isSuper*/ false, propertyName, getTypeFromTypeNode(node)); + } + } + function isValidPropertyAccessForCompletions(node, type, property) { + return isValidPropertyAccessWithType(node, node.kind !== 183 /* ImportType */ && node.expression.kind === 98 /* SuperKeyword */, property.escapedName, type) + && (!(property.flags & 8192 /* Method */) || isValidMethodAccess(property, type)); + } + function isValidMethodAccess(method, actualThisType) { + var propType = getTypeOfPropertyOfType(actualThisType, method.escapedName); + var signatures = getSignaturesOfType(getNonNullableType(propType), 0 /* Call */); + ts.Debug.assert(signatures.length !== 0); + return signatures.some(function (sig) { + var signatureThisType = getThisTypeOfSignature(sig); + return !signatureThisType || isTypeAssignableTo(actualThisType, getInstantiatedSignatureThisType(sig, signatureThisType, actualThisType)); + }); + } + function getInstantiatedSignatureThisType(sig, signatureThisType, actualThisType) { + if (!sig.typeParameters) { + return signatureThisType; + } + var context = createInferenceContext(sig.typeParameters, sig, 0 /* None */); + inferTypes(context.inferences, actualThisType, signatureThisType); + return instantiateType(signatureThisType, createSignatureTypeMapper(sig, getInferredTypes(context))); + } + function isValidPropertyAccessWithType(node, isSuper, propertyName, type) { + if (type === errorType || isTypeAny(type)) { + return true; + } + var prop = getPropertyOfType(type, propertyName); + return prop ? checkPropertyAccessibility(node, isSuper, type, prop) + // In js files properties of unions are allowed in completion + : ts.isInJSFile(node) && (type.flags & 1048576 /* Union */) !== 0 && type.types.some(function (elementType) { return isValidPropertyAccessWithType(node, isSuper, propertyName, elementType); }); + } + /** + * Return the symbol of the for-in variable declared or referenced by the given for-in statement. + */ + function getForInVariableSymbol(node) { + var initializer = node.initializer; + if (initializer.kind === 238 /* VariableDeclarationList */) { + var variable = initializer.declarations[0]; + if (variable && !ts.isBindingPattern(variable.name)) { + return getSymbolOfNode(variable); + } + } + else if (initializer.kind === 72 /* Identifier */) { + return getResolvedSymbol(initializer); + } + return undefined; + } + /** + * Return true if the given type is considered to have numeric property names. + */ + function hasNumericPropertyNames(type) { + return getIndexTypeOfType(type, 1 /* Number */) && !getIndexTypeOfType(type, 0 /* String */); + } + /** + * Return true if given node is an expression consisting of an identifier (possibly parenthesized) + * that references a for-in variable for an object with numeric property names. + */ + function isForInVariableForNumericPropertyNames(expr) { + var e = ts.skipParentheses(expr); + if (e.kind === 72 /* Identifier */) { + var symbol = getResolvedSymbol(e); + if (symbol.flags & 3 /* Variable */) { + var child = expr; + var node = expr.parent; + while (node) { + if (node.kind === 226 /* ForInStatement */ && + child === node.statement && + getForInVariableSymbol(node) === symbol && + hasNumericPropertyNames(getTypeOfExpression(node.expression))) { + return true; + } + child = node; + node = node.parent; + } + } + } + return false; + } + function checkIndexedAccess(node) { + var objectType = checkNonNullExpression(node.expression); + var indexExpression = node.argumentExpression; + if (!indexExpression) { + var sourceFile = ts.getSourceFileOfNode(node); + if (node.parent.kind === 192 /* NewExpression */ && node.parent.expression === node) { + var start = ts.skipTrivia(sourceFile.text, node.expression.end); + var end = node.end; + grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead); + } + else { + var start = node.end - "]".length; + var end = node.end; + grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.Expression_expected); + } + return errorType; + } + var indexType = checkExpression(indexExpression); + if (objectType === errorType || objectType === silentNeverType) { + return objectType; + } + if (isConstEnumObjectType(objectType) && indexExpression.kind !== 10 /* StringLiteral */) { + error(indexExpression, ts.Diagnostics.A_const_enum_member_can_only_be_accessed_using_a_string_literal); + return errorType; + } + return checkIndexedAccessIndexType(getIndexedAccessType(objectType, isForInVariableForNumericPropertyNames(indexExpression) ? numberType : indexType, node), node); + } + function checkThatExpressionIsProperSymbolReference(expression, expressionType, reportError) { + if (expressionType === errorType) { + // There is already an error, so no need to report one. + return false; + } + if (!ts.isWellKnownSymbolSyntactically(expression)) { + return false; + } + // Make sure the property type is the primitive symbol type + if ((expressionType.flags & 12288 /* ESSymbolLike */) === 0) { + if (reportError) { + error(expression, ts.Diagnostics.A_computed_property_name_of_the_form_0_must_be_of_type_symbol, ts.getTextOfNode(expression)); + } + return false; + } + // The name is Symbol., so make sure Symbol actually resolves to the + // global Symbol object + var leftHandSide = expression.expression; + var leftHandSideSymbol = getResolvedSymbol(leftHandSide); + if (!leftHandSideSymbol) { + return false; + } + var globalESSymbol = getGlobalESSymbolConstructorSymbol(/*reportErrors*/ true); + if (!globalESSymbol) { + // Already errored when we tried to look up the symbol + return false; + } + if (leftHandSideSymbol !== globalESSymbol) { + if (reportError) { + error(leftHandSide, ts.Diagnostics.Symbol_reference_does_not_refer_to_the_global_Symbol_constructor_object); + } + return false; + } + return true; + } + function callLikeExpressionMayHaveTypeArguments(node) { + return ts.isCallOrNewExpression(node) || ts.isTaggedTemplateExpression(node) || ts.isJsxOpeningLikeElement(node); + } + function resolveUntypedCall(node) { + if (callLikeExpressionMayHaveTypeArguments(node)) { + // Check type arguments even though we will give an error that untyped calls may not accept type arguments. + // This gets us diagnostics for the type arguments and marks them as referenced. + ts.forEach(node.typeArguments, checkSourceElement); + } + if (node.kind === 193 /* TaggedTemplateExpression */) { + checkExpression(node.template); + } + else if (ts.isJsxOpeningLikeElement(node)) { + checkExpression(node.attributes); + } + else if (node.kind !== 152 /* Decorator */) { + ts.forEach(node.arguments, function (argument) { + checkExpression(argument); + }); + } + return anySignature; + } + function resolveErrorCall(node) { + resolveUntypedCall(node); + return unknownSignature; + } + // Re-order candidate signatures into the result array. Assumes the result array to be empty. + // The candidate list orders groups in reverse, but within a group signatures are kept in declaration order + // A nit here is that we reorder only signatures that belong to the same symbol, + // so order how inherited signatures are processed is still preserved. + // interface A { (x: string): void } + // interface B extends A { (x: 'foo'): string } + // const b: B; + // b('foo') // <- here overloads should be processed as [(x:'foo'): string, (x: string): void] + function reorderCandidates(signatures, result) { + var lastParent; + var lastSymbol; + var cutoffIndex = 0; + var index; + var specializedIndex = -1; + var spliceIndex; + ts.Debug.assert(!result.length); + for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { + var signature = signatures_3[_i]; + var symbol = signature.declaration && getSymbolOfNode(signature.declaration); + var parent = signature.declaration && signature.declaration.parent; + if (!lastSymbol || symbol === lastSymbol) { + if (lastParent && parent === lastParent) { + index = index + 1; + } + else { + lastParent = parent; + index = cutoffIndex; + } + } + else { + // current declaration belongs to a different symbol + // set cutoffIndex so re-orderings in the future won't change result set from 0 to cutoffIndex + index = cutoffIndex = result.length; + lastParent = parent; + } + lastSymbol = symbol; + // specialized signatures always need to be placed before non-specialized signatures regardless + // of the cutoff position; see GH#1133 + if (signature.hasLiteralTypes) { + specializedIndex++; + spliceIndex = specializedIndex; + // The cutoff index always needs to be greater than or equal to the specialized signature index + // in order to prevent non-specialized signatures from being added before a specialized + // signature. + cutoffIndex++; + } + else { + spliceIndex = index; + } + result.splice(spliceIndex, 0, signature); + } + } + function isSpreadArgument(arg) { + return !!arg && (arg.kind === 208 /* SpreadElement */ || arg.kind === 215 /* SyntheticExpression */ && arg.isSpread); + } + function getSpreadArgumentIndex(args) { + return ts.findIndex(args, isSpreadArgument); + } + function acceptsVoid(t) { + return !!(t.flags & 16384 /* Void */); + } + function hasCorrectArity(node, args, signature, signatureHelpTrailingComma) { + if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; } + var argCount; + var callIsIncomplete = false; // In incomplete call we want to be lenient when we have too few arguments + var effectiveParameterCount = getParameterCount(signature); + var effectiveMinimumArguments = getMinArgumentCount(signature); + if (node.kind === 193 /* TaggedTemplateExpression */) { + argCount = args.length; + if (node.template.kind === 206 /* TemplateExpression */) { + // If a tagged template expression lacks a tail literal, the call is incomplete. + // Specifically, a template only can end in a TemplateTail or a Missing literal. + var lastSpan = ts.last(node.template.templateSpans); // we should always have at least one span. + callIsIncomplete = ts.nodeIsMissing(lastSpan.literal) || !!lastSpan.literal.isUnterminated; + } + else { + // If the template didn't end in a backtick, or its beginning occurred right prior to EOF, + // then this might actually turn out to be a TemplateHead in the future; + // so we consider the call to be incomplete. + var templateLiteral = node.template; + ts.Debug.assert(templateLiteral.kind === 14 /* NoSubstitutionTemplateLiteral */); + callIsIncomplete = !!templateLiteral.isUnterminated; + } + } + else if (node.kind === 152 /* Decorator */) { + argCount = getDecoratorArgumentCount(node, signature); + } + else if (ts.isJsxOpeningLikeElement(node)) { + callIsIncomplete = node.attributes.end === node.end; + if (callIsIncomplete) { + return true; + } + argCount = effectiveMinimumArguments === 0 ? args.length : 1; + effectiveParameterCount = args.length === 0 ? effectiveParameterCount : 1; // class may have argumentless ctor functions - still resolve ctor and compare vs props member type + effectiveMinimumArguments = Math.min(effectiveMinimumArguments, 1); // sfc may specify context argument - handled by framework and not typechecked + } + else { + if (!node.arguments) { + // This only happens when we have something of the form: 'new C' + ts.Debug.assert(node.kind === 192 /* NewExpression */); + return getMinArgumentCount(signature) === 0; + } + argCount = signatureHelpTrailingComma ? args.length + 1 : args.length; + // If we are missing the close parenthesis, the call is incomplete. + callIsIncomplete = node.arguments.end === node.end; + // If a spread argument is present, check that it corresponds to a rest parameter or at least that it's in the valid range. + var spreadArgIndex = getSpreadArgumentIndex(args); + if (spreadArgIndex >= 0) { + return spreadArgIndex >= getMinArgumentCount(signature) && (hasEffectiveRestParameter(signature) || spreadArgIndex < getParameterCount(signature)); + } + } + // Too many arguments implies incorrect arity. + if (!hasEffectiveRestParameter(signature) && argCount > effectiveParameterCount) { + return false; + } + // If the call is incomplete, we should skip the lower bound check. + // JSX signatures can have extra parameters provided by the library which we don't check + if (callIsIncomplete || argCount >= effectiveMinimumArguments) { + return true; + } + for (var i = argCount; i < effectiveMinimumArguments; i++) { + var type = getTypeAtPosition(signature, i); + if (filterType(type, acceptsVoid).flags & 131072 /* Never */) { + return false; + } + } + return true; + } + function hasCorrectTypeArgumentArity(signature, typeArguments) { + // If the user supplied type arguments, but the number of type arguments does not match + // the declared number of type parameters, the call has an incorrect arity. + var numTypeParameters = ts.length(signature.typeParameters); + var minTypeArgumentCount = getMinTypeArgumentCount(signature.typeParameters); + return !typeArguments || + (typeArguments.length >= minTypeArgumentCount && typeArguments.length <= numTypeParameters); + } + // If type has a single call signature and no other members, return that signature. Otherwise, return undefined. + function getSingleCallSignature(type) { + if (type.flags & 524288 /* Object */) { + var resolved = resolveStructuredTypeMembers(type); + if (resolved.callSignatures.length === 1 && resolved.constructSignatures.length === 0 && + resolved.properties.length === 0 && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { + return resolved.callSignatures[0]; + } + } + return undefined; + } + // Instantiate a generic signature in the context of a non-generic signature (section 3.8.5 in TypeScript spec) + function instantiateSignatureInContextOf(signature, contextualSignature, contextualMapper, compareTypes) { + var context = createInferenceContext(signature.typeParameters, signature, 0 /* None */, compareTypes); + var sourceSignature = contextualMapper ? instantiateSignature(contextualSignature, contextualMapper) : contextualSignature; + forEachMatchingParameterType(sourceSignature, signature, function (source, target) { + // Type parameters from outer context referenced by source type are fixed by instantiation of the source type + inferTypes(context.inferences, source, target); + }); + if (!contextualMapper) { + inferTypes(context.inferences, getReturnTypeOfSignature(contextualSignature), getReturnTypeOfSignature(signature), 8 /* ReturnType */); + } + return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJSFile(contextualSignature.declaration)); + } + function inferJsxTypeArguments(node, signature, excludeArgument, context) { + var paramType = getEffectiveFirstArgumentForJsxSignature(signature, node); + var checkAttrType = checkExpressionWithContextualType(node.attributes, paramType, excludeArgument && excludeArgument[0] !== undefined ? identityMapper : context); + inferTypes(context.inferences, checkAttrType, paramType); + return getInferredTypes(context); + } + function inferTypeArguments(node, signature, args, excludeArgument, context) { + // Clear out all the inference results from the last time inferTypeArguments was called on this context + for (var _i = 0, _a = context.inferences; _i < _a.length; _i++) { + var inference = _a[_i]; + // As an optimization, we don't have to clear (and later recompute) inferred types + // for type parameters that have already been fixed on the previous call to inferTypeArguments. + // It would be just as correct to reset all of them. But then we'd be repeating the same work + // for the type parameters that were fixed, namely the work done by getInferredType. + if (!inference.isFixed) { + inference.inferredType = undefined; + } + } + if (ts.isJsxOpeningLikeElement(node)) { + return inferJsxTypeArguments(node, signature, excludeArgument, context); + } + // If a contextual type is available, infer from that type to the return type of the call expression. For + // example, given a 'function wrap(cb: (x: T) => U): (x: T) => U' and a call expression + // 'let f: (x: string) => number = wrap(s => s.length)', we infer from the declared type of 'f' to the + // return type of 'wrap'. + if (node.kind !== 152 /* Decorator */) { + var contextualType = getContextualType(node); + if (contextualType) { + // We clone the contextual mapper to avoid disturbing a resolution in progress for an + // outer call expression. Effectively we just want a snapshot of whatever has been + // inferred for any outer call expression so far. + var instantiatedType = instantiateType(contextualType, cloneTypeMapper(getContextualMapper(node))); + // If the contextual type is a generic function type with a single call signature, we + // instantiate the type with its own type parameters and type arguments. This ensures that + // the type parameters are not erased to type any during type inference such that they can + // be inferred as actual types from the contextual type. For example: + // declare function arrayMap(f: (x: T) => U): (a: T[]) => U[]; + // const boxElements: (a: A[]) => { value: A }[] = arrayMap(value => ({ value })); + // Above, the type of the 'value' parameter is inferred to be 'A'. + var contextualSignature = getSingleCallSignature(instantiatedType); + var inferenceSourceType = contextualSignature && contextualSignature.typeParameters ? + getOrCreateTypeFromSignature(getSignatureInstantiationWithoutFillingInTypeArguments(contextualSignature, contextualSignature.typeParameters)) : + instantiatedType; + var inferenceTargetType = getReturnTypeOfSignature(signature); + // Inferences made from return types have lower priority than all other inferences. + inferTypes(context.inferences, inferenceSourceType, inferenceTargetType, 8 /* ReturnType */); + } + } + var thisType = getThisTypeOfSignature(signature); + if (thisType) { + var thisArgumentNode = getThisArgumentOfCall(node); + var thisArgumentType = thisArgumentNode ? checkExpression(thisArgumentNode) : voidType; + inferTypes(context.inferences, thisArgumentType, thisType); + } + var restType = getNonArrayRestType(signature); + var argCount = restType ? Math.min(getParameterCount(signature) - 1, args.length) : args.length; + for (var i = 0; i < argCount; i++) { + var arg = args[i]; + if (arg.kind !== 210 /* OmittedExpression */) { + var paramType = getTypeAtPosition(signature, i); + // For context sensitive arguments we pass the identityMapper, which is a signal to treat all + // context sensitive function expressions as wildcards + var mapper = excludeArgument && excludeArgument[i] !== undefined ? identityMapper : context; + var argType = checkExpressionWithContextualType(arg, paramType, mapper); + inferTypes(context.inferences, argType, paramType); + } + } + if (restType) { + var spreadType = getSpreadArgumentType(args, argCount, args.length, restType, context); + inferTypes(context.inferences, spreadType, restType); + } + return getInferredTypes(context); + } + function getArrayifiedType(type) { + if (forEachType(type, function (t) { return !(t.flags & (1 /* Any */ | 63176704 /* Instantiable */) || isArrayType(t) || isTupleType(t)); })) { + return createArrayType(getIndexTypeOfType(type, 1 /* Number */) || errorType); + } + return type; + } + function getSpreadArgumentType(args, index, argCount, restType, context) { + if (index >= argCount - 1) { + var arg = args[argCount - 1]; + if (isSpreadArgument(arg)) { + // We are inferring from a spread expression in the last argument position, i.e. both the parameter + // and the argument are ...x forms. + return arg.kind === 215 /* SyntheticExpression */ ? + createArrayType(arg.type) : + getArrayifiedType(checkExpressionWithContextualType(arg.expression, restType, context)); + } + } + var contextualType = getIndexTypeOfType(restType, 1 /* Number */) || anyType; + var hasPrimitiveContextualType = maybeTypeOfKind(contextualType, 131068 /* Primitive */ | 4194304 /* Index */); + var types = []; + var spreadIndex = -1; + for (var i = index; i < argCount; i++) { + var argType = checkExpressionWithContextualType(args[i], contextualType, context); + if (spreadIndex < 0 && isSpreadArgument(args[i])) { + spreadIndex = i - index; + } + types.push(hasPrimitiveContextualType ? getRegularTypeOfLiteralType(argType) : getWidenedLiteralType(argType)); + } + return spreadIndex < 0 ? + createTupleType(types) : + createTupleType(ts.append(types.slice(0, spreadIndex), getUnionType(types.slice(spreadIndex))), spreadIndex, /*hasRestElement*/ true); + } + function checkTypeArguments(signature, typeArgumentNodes, reportErrors, headMessage) { + var isJavascript = ts.isInJSFile(signature.declaration); + var typeParameters = signature.typeParameters; + var typeArgumentTypes = fillMissingTypeArguments(ts.map(typeArgumentNodes, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), isJavascript); + var mapper; + for (var i = 0; i < typeArgumentNodes.length; i++) { + ts.Debug.assert(typeParameters[i] !== undefined, "Should not call checkTypeArguments with too many type arguments"); + var constraint = getConstraintOfTypeParameter(typeParameters[i]); + if (constraint) { + var errorInfo = reportErrors && headMessage ? (function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); }) : undefined; + var typeArgumentHeadMessage = headMessage || ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1; + if (!mapper) { + mapper = createTypeMapper(typeParameters, typeArgumentTypes); + } + var typeArgument = typeArgumentTypes[i]; + if (!checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), reportErrors ? typeArgumentNodes[i] : undefined, typeArgumentHeadMessage, errorInfo)) { + return undefined; + } + } + } + return typeArgumentTypes; + } + function getJsxReferenceKind(node) { + if (isJsxIntrinsicIdentifier(node.tagName)) { + return 2 /* Mixed */; + } + var tagType = getApparentType(checkExpression(node.tagName)); + if (ts.length(getSignaturesOfType(tagType, 1 /* Construct */))) { + return 0 /* Component */; + } + if (ts.length(getSignaturesOfType(tagType, 0 /* Call */))) { + return 1 /* Function */; + } + return 2 /* Mixed */; + } + /** + * Check if the given signature can possibly be a signature called by the JSX opening-like element. + * @param node a JSX opening-like element we are trying to figure its call signature + * @param signature a candidate signature we are trying whether it is a call signature + * @param relation a relationship to check parameter and argument type + * @param excludeArgument + */ + function checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation, excludeArgument, reportErrors) { + // Stateless function components can have maximum of three arguments: "props", "context", and "updater". + // However "context" and "updater" are implicit and can't be specify by users. Only the first parameter, props, + // can be specified by users through attributes property. + var paramType = getEffectiveFirstArgumentForJsxSignature(signature, node); + var attributesType = checkExpressionWithContextualType(node.attributes, paramType, excludeArgument && excludeArgument[0] ? identityMapper : undefined); + return checkTypeRelatedToAndOptionallyElaborate(attributesType, paramType, relation, reportErrors ? node.tagName : undefined, node.attributes); + } + function checkApplicableSignature(node, args, signature, relation, excludeArgument, reportErrors) { + if (ts.isJsxOpeningLikeElement(node)) { + return checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation, excludeArgument, reportErrors); + } + var thisType = getThisTypeOfSignature(signature); + if (thisType && thisType !== voidType && node.kind !== 192 /* NewExpression */) { + // If the called expression is not of the form `x.f` or `x["f"]`, then sourceType = voidType + // If the signature's 'this' type is voidType, then the check is skipped -- anything is compatible. + // If the expression is a new expression, then the check is skipped. + var thisArgumentNode = getThisArgumentOfCall(node); + var thisArgumentType = thisArgumentNode ? checkExpression(thisArgumentNode) : voidType; + var errorNode = reportErrors ? (thisArgumentNode || node) : undefined; + var headMessage_1 = ts.Diagnostics.The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1; + if (!checkTypeRelatedTo(thisArgumentType, thisType, relation, errorNode, headMessage_1)) { + return false; + } + } + var headMessage = ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1; + var restType = getNonArrayRestType(signature); + var argCount = restType ? Math.min(getParameterCount(signature) - 1, args.length) : args.length; + for (var i = 0; i < argCount; i++) { + var arg = args[i]; + if (arg.kind !== 210 /* OmittedExpression */) { + var paramType = getTypeAtPosition(signature, i); + var argType = checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); + // If one or more arguments are still excluded (as indicated by a non-null excludeArgument parameter), + // we obtain the regular type of any object literal arguments because we may not have inferred complete + // parameter types yet and therefore excess property checks may yield false positives (see #17041). + var checkArgType = excludeArgument ? getRegularTypeOfObjectLiteral(argType) : argType; + if (!checkTypeRelatedToAndOptionallyElaborate(checkArgType, paramType, relation, reportErrors ? arg : undefined, arg, headMessage)) { + return false; + } + } + } + if (restType) { + var spreadType = getSpreadArgumentType(args, argCount, args.length, restType, /*context*/ undefined); + var errorNode = reportErrors ? argCount < args.length ? args[argCount] : node : undefined; + return checkTypeRelatedTo(spreadType, restType, relation, errorNode, headMessage); + } + return true; + } + /** + * Returns the this argument in calls like x.f(...) and x[f](...). Undefined otherwise. + */ + function getThisArgumentOfCall(node) { + if (node.kind === 191 /* CallExpression */) { + var callee = ts.skipOuterExpressions(node.expression); + if (callee.kind === 189 /* PropertyAccessExpression */ || callee.kind === 190 /* ElementAccessExpression */) { + return callee.expression; + } + } + } + function createSyntheticExpression(parent, type, isSpread) { + var result = ts.createNode(215 /* SyntheticExpression */, parent.pos, parent.end); + result.parent = parent; + result.type = type; + result.isSpread = isSpread || false; + return result; + } + /** + * Returns the effective arguments for an expression that works like a function invocation. + */ + function getEffectiveCallArguments(node) { + if (node.kind === 193 /* TaggedTemplateExpression */) { + var template = node.template; + var args_4 = [createSyntheticExpression(template, getGlobalTemplateStringsArrayType())]; + if (template.kind === 206 /* TemplateExpression */) { + ts.forEach(template.templateSpans, function (span) { + args_4.push(span.expression); + }); + } + return args_4; + } + if (node.kind === 152 /* Decorator */) { + return getEffectiveDecoratorArguments(node); + } + if (ts.isJsxOpeningLikeElement(node)) { + return node.attributes.properties.length > 0 || (ts.isJsxOpeningElement(node) && node.parent.children.length > 0) ? [node.attributes] : ts.emptyArray; + } + var args = node.arguments || ts.emptyArray; + var length = args.length; + if (length && isSpreadArgument(args[length - 1]) && getSpreadArgumentIndex(args) === length - 1) { + // We have a spread argument in the last position and no other spread arguments. If the type + // of the argument is a tuple type, spread the tuple elements into the argument list. We can + // call checkExpressionCached because spread expressions never have a contextual type. + var spreadArgument_1 = args[length - 1]; + var type = checkExpressionCached(spreadArgument_1.expression); + if (isTupleType(type)) { + var typeArguments = type.typeArguments || ts.emptyArray; + var restIndex_2 = type.target.hasRestElement ? typeArguments.length - 1 : -1; + var syntheticArgs = ts.map(typeArguments, function (t, i) { return createSyntheticExpression(spreadArgument_1, t, /*isSpread*/ i === restIndex_2); }); + return ts.concatenate(args.slice(0, length - 1), syntheticArgs); + } + } + return args; + } + /** + * Returns the synthetic argument list for a decorator invocation. + */ + function getEffectiveDecoratorArguments(node) { + var parent = node.parent; + var expr = node.expression; + switch (parent.kind) { + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + // For a class decorator, the `target` is the type of the class (e.g. the + // "static" or "constructor" side of the class). + return [ + createSyntheticExpression(expr, getTypeOfSymbol(getSymbolOfNode(parent))) + ]; + case 151 /* Parameter */: + // A parameter declaration decorator will have three arguments (see + // `ParameterDecorator` in core.d.ts). + var func = parent.parent; + return [ + createSyntheticExpression(expr, parent.parent.kind === 157 /* Constructor */ ? getTypeOfSymbol(getSymbolOfNode(func)) : errorType), + createSyntheticExpression(expr, anyType), + createSyntheticExpression(expr, numberType) + ]; + case 154 /* PropertyDeclaration */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + // A method or accessor declaration decorator will have two or three arguments (see + // `PropertyDecorator` and `MethodDecorator` in core.d.ts). If we are emitting decorators + // for ES3, we will only pass two arguments. + var hasPropDesc = parent.kind !== 154 /* PropertyDeclaration */ && languageVersion !== 0 /* ES3 */; + return [ + createSyntheticExpression(expr, getParentTypeOfClassElement(parent)), + createSyntheticExpression(expr, getClassElementPropertyKeyType(parent)), + createSyntheticExpression(expr, hasPropDesc ? createTypedPropertyDescriptorType(getTypeOfNode(parent)) : anyType) + ]; + } + return ts.Debug.fail(); + } + /** + * Returns the argument count for a decorator node that works like a function invocation. + */ + function getDecoratorArgumentCount(node, signature) { + switch (node.parent.kind) { + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + return 1; + case 154 /* PropertyDeclaration */: + return 2; + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + // For ES3 or decorators with only two parameters we supply only two arguments + return languageVersion === 0 /* ES3 */ || signature.parameters.length <= 2 ? 2 : 3; + case 151 /* Parameter */: + return 3; + default: + return ts.Debug.fail(); + } + } + function getArgumentArityError(node, signatures, args) { + var min = Number.POSITIVE_INFINITY; + var max = Number.NEGATIVE_INFINITY; + var belowArgCount = Number.NEGATIVE_INFINITY; + var aboveArgCount = Number.POSITIVE_INFINITY; + var argCount = args.length; + var closestSignature; + for (var _i = 0, signatures_4 = signatures; _i < signatures_4.length; _i++) { + var sig = signatures_4[_i]; + var minCount = getMinArgumentCount(sig); + var maxCount = getParameterCount(sig); + if (minCount < argCount && minCount > belowArgCount) + belowArgCount = minCount; + if (argCount < maxCount && maxCount < aboveArgCount) + aboveArgCount = maxCount; + if (minCount < min) { + min = minCount; + closestSignature = sig; + } + max = Math.max(max, maxCount); + } + var hasRestParameter = ts.some(signatures, hasEffectiveRestParameter); + var paramRange = hasRestParameter ? min : + min < max ? min + "-" + max : + min; + var hasSpreadArgument = getSpreadArgumentIndex(args) > -1; + if (argCount <= max && hasSpreadArgument) { + argCount--; + } + var related; + if (closestSignature && getMinArgumentCount(closestSignature) > argCount && closestSignature.declaration) { + var paramDecl = closestSignature.declaration.parameters[closestSignature.thisParameter ? argCount + 1 : argCount]; + if (paramDecl) { + related = ts.createDiagnosticForNode(paramDecl, ts.isBindingPattern(paramDecl.name) ? ts.Diagnostics.An_argument_matching_this_binding_pattern_was_not_provided : ts.Diagnostics.An_argument_for_0_was_not_provided, !paramDecl.name ? argCount : !ts.isBindingPattern(paramDecl.name) ? ts.idText(getFirstIdentifier(paramDecl.name)) : undefined); + } + } + if (hasRestParameter || hasSpreadArgument) { + var error_1 = hasRestParameter && hasSpreadArgument ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1_or_more : + hasRestParameter ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1 : + ts.Diagnostics.Expected_0_arguments_but_got_1_or_more; + var diagnostic_1 = ts.createDiagnosticForNode(node, error_1, paramRange, argCount); + return related ? addRelatedInfo(diagnostic_1, related) : diagnostic_1; + } + if (min < argCount && argCount < max) { + return ts.createDiagnosticForNode(node, ts.Diagnostics.No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments, argCount, belowArgCount, aboveArgCount); + } + var diagnostic = ts.createDiagnosticForNode(node, ts.Diagnostics.Expected_0_arguments_but_got_1, paramRange, argCount); + return related ? addRelatedInfo(diagnostic, related) : diagnostic; + } + function getTypeArgumentArityError(node, signatures, typeArguments) { + var min = Infinity; + var max = -Infinity; + for (var _i = 0, signatures_5 = signatures; _i < signatures_5.length; _i++) { + var sig = signatures_5[_i]; + min = Math.min(min, getMinTypeArgumentCount(sig.typeParameters)); + max = Math.max(max, ts.length(sig.typeParameters)); + } + var paramCount = min === max ? min : min + "-" + max; + return ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), typeArguments, ts.Diagnostics.Expected_0_type_arguments_but_got_1, paramCount, typeArguments.length); + } + function resolveCall(node, signatures, candidatesOutArray, isForSignatureHelp, fallbackError) { + var isTaggedTemplate = node.kind === 193 /* TaggedTemplateExpression */; + var isDecorator = node.kind === 152 /* Decorator */; + var isJsxOpeningOrSelfClosingElement = ts.isJsxOpeningLikeElement(node); + var reportErrors = !candidatesOutArray; + var typeArguments; + if (!isDecorator) { + typeArguments = node.typeArguments; + // We already perform checking on the type arguments on the class declaration itself. + if (isTaggedTemplate || isJsxOpeningOrSelfClosingElement || node.expression.kind !== 98 /* SuperKeyword */) { + ts.forEach(typeArguments, checkSourceElement); + } + } + var candidates = candidatesOutArray || []; + // reorderCandidates fills up the candidates array directly + reorderCandidates(signatures, candidates); + if (!candidates.length) { + if (reportErrors) { + diagnostics.add(ts.createDiagnosticForNode(node, ts.Diagnostics.Call_target_does_not_contain_any_signatures)); + } + return resolveErrorCall(node); + } + var args = getEffectiveCallArguments(node); + // The excludeArgument array contains true for each context sensitive argument (an argument + // is context sensitive it is susceptible to a one-time permanent contextual typing). + // + // The idea is that we will perform type argument inference & assignability checking once + // without using the susceptible parameters that are functions, and once more for those + // parameters, contextually typing each as we go along. + // + // For a tagged template, then the first argument be 'undefined' if necessary because it + // represents a TemplateStringsArray. + // + // For a decorator, no arguments are susceptible to contextual typing due to the fact + // decorators are applied to a declaration by the emitter, and not to an expression. + var isSingleNonGenericCandidate = candidates.length === 1 && !candidates[0].typeParameters; + var excludeArgument = !isDecorator && !isSingleNonGenericCandidate ? getExcludeArgument(args) : undefined; + // The following variables are captured and modified by calls to chooseOverload. + // If overload resolution or type argument inference fails, we want to report the + // best error possible. The best error is one which says that an argument was not + // assignable to a parameter. This implies that everything else about the overload + // was fine. So if there is any overload that is only incorrect because of an + // argument, we will report an error on that one. + // + // function foo(s: string): void; + // function foo(n: number): void; // Report argument error on this overload + // function foo(): void; + // foo(true); + // + // If none of the overloads even made it that far, there are two possibilities. + // There was a problem with type arguments for some overload, in which case + // report an error on that. Or none of the overloads even had correct arity, + // in which case give an arity error. + // + // function foo(x: T): void; // Report type argument error + // function foo(): void; + // foo(0); + // + var candidateForArgumentError; + var candidateForArgumentArityError; + var candidateForTypeArgumentError; + var result; + // If we are in signature help, a trailing comma indicates that we intend to provide another argument, + // so we will only accept overloads with arity at least 1 higher than the current number of provided arguments. + var signatureHelpTrailingComma = isForSignatureHelp && node.kind === 191 /* CallExpression */ && node.arguments.hasTrailingComma; + // Section 4.12.1: + // if the candidate list contains one or more signatures for which the type of each argument + // expression is a subtype of each corresponding parameter type, the return type of the first + // of those signatures becomes the return type of the function call. + // Otherwise, the return type of the first signature in the candidate list becomes the return + // type of the function call. + // + // Whether the call is an error is determined by assignability of the arguments. The subtype pass + // is just important for choosing the best signature. So in the case where there is only one + // signature, the subtype pass is useless. So skipping it is an optimization. + if (candidates.length > 1) { + result = chooseOverload(candidates, subtypeRelation, signatureHelpTrailingComma); + } + if (!result) { + result = chooseOverload(candidates, assignableRelation, signatureHelpTrailingComma); + } + if (result) { + return result; + } + // No signatures were applicable. Now report errors based on the last applicable signature with + // no arguments excluded from assignability checks. + // If candidate is undefined, it means that no candidates had a suitable arity. In that case, + // skip the checkApplicableSignature check. + if (reportErrors) { + if (candidateForArgumentError) { + // excludeArgument is undefined, in this case also equivalent to [undefined, undefined, ...] + // The importance of excludeArgument is to prevent us from typing function expression parameters + // in arguments too early. If possible, we'd like to only type them once we know the correct + // overload. However, this matters for the case where the call is correct. When the call is + // an error, we don't need to exclude any arguments, although it would cause no harm to do so. + checkApplicableSignature(node, args, candidateForArgumentError, assignableRelation, /*excludeArgument*/ undefined, /*reportErrors*/ true); + } + else if (candidateForArgumentArityError) { + diagnostics.add(getArgumentArityError(node, [candidateForArgumentArityError], args)); + } + else if (candidateForTypeArgumentError) { + checkTypeArguments(candidateForTypeArgumentError, node.typeArguments, /*reportErrors*/ true, fallbackError); + } + else { + var signaturesWithCorrectTypeArgumentArity = ts.filter(signatures, function (s) { return hasCorrectTypeArgumentArity(s, typeArguments); }); + if (signaturesWithCorrectTypeArgumentArity.length === 0) { + diagnostics.add(getTypeArgumentArityError(node, signatures, typeArguments)); + } + else if (!isDecorator) { + diagnostics.add(getArgumentArityError(node, signaturesWithCorrectTypeArgumentArity, args)); + } + else if (fallbackError) { + diagnostics.add(ts.createDiagnosticForNode(node, fallbackError)); + } + } + } + return produceDiagnostics || !args ? resolveErrorCall(node) : getCandidateForOverloadFailure(node, candidates, args, !!candidatesOutArray); + function chooseOverload(candidates, relation, signatureHelpTrailingComma) { + if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; } + candidateForArgumentError = undefined; + candidateForArgumentArityError = undefined; + candidateForTypeArgumentError = undefined; + if (isSingleNonGenericCandidate) { + var candidate = candidates[0]; + if (typeArguments || !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) { + return undefined; + } + if (!checkApplicableSignature(node, args, candidate, relation, excludeArgument, /*reportErrors*/ false)) { + candidateForArgumentError = candidate; + return undefined; + } + return candidate; + } + for (var candidateIndex = 0; candidateIndex < candidates.length; candidateIndex++) { + var candidate = candidates[candidateIndex]; + if (!hasCorrectTypeArgumentArity(candidate, typeArguments) || !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) { + continue; + } + var checkCandidate = void 0; + var inferenceContext = void 0; + if (candidate.typeParameters) { + var typeArgumentTypes = void 0; + if (typeArguments) { + typeArgumentTypes = checkTypeArguments(candidate, typeArguments, /*reportErrors*/ false); + if (!typeArgumentTypes) { + candidateForTypeArgumentError = candidate; + continue; + } + } + else { + inferenceContext = createInferenceContext(candidate.typeParameters, candidate, /*flags*/ ts.isInJSFile(node) ? 2 /* AnyDefault */ : 0 /* None */); + typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); + } + checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration)); + // If the original signature has a generic rest type, instantiation may produce a + // signature with different arity and we need to perform another arity check. + if (getNonArrayRestType(candidate) && !hasCorrectArity(node, args, checkCandidate, signatureHelpTrailingComma)) { + candidateForArgumentArityError = checkCandidate; + continue; + } + } + else { + checkCandidate = candidate; + } + if (!checkApplicableSignature(node, args, checkCandidate, relation, excludeArgument, /*reportErrors*/ false)) { + // Give preference to error candidates that have no rest parameters (as they are more specific) + if (!candidateForArgumentError || getEffectiveRestType(candidateForArgumentError) || !getEffectiveRestType(checkCandidate)) { + candidateForArgumentError = checkCandidate; + } + continue; + } + if (excludeArgument) { + // If one or more context sensitive arguments were excluded, we start including + // them now (and keeping do so for any subsequent candidates) and perform a second + // round of type inference and applicability checking for this particular candidate. + excludeArgument = undefined; + if (inferenceContext) { + var typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); + checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration)); + } + if (!checkApplicableSignature(node, args, checkCandidate, relation, excludeArgument, /*reportErrors*/ false)) { + // Give preference to error candidates that have no rest parameters (as they are more specific) + if (!candidateForArgumentError || getEffectiveRestType(candidateForArgumentError) || !getEffectiveRestType(checkCandidate)) { + candidateForArgumentError = checkCandidate; + } + continue; + } + } + candidates[candidateIndex] = checkCandidate; + return checkCandidate; + } + return undefined; + } + } + function getExcludeArgument(args) { + var excludeArgument; + // We do not need to call `getEffectiveArgumentCount` here as it only + // applies when calculating the number of arguments for a decorator. + for (var i = 0; i < args.length; i++) { + if (isContextSensitive(args[i])) { + if (!excludeArgument) { + excludeArgument = new Array(args.length); + } + excludeArgument[i] = true; + } + } + return excludeArgument; + } + // No signature was applicable. We have already reported the errors for the invalid signature. + // If this is a type resolution session, e.g. Language Service, try to get better information than anySignature. + function getCandidateForOverloadFailure(node, candidates, args, hasCandidatesOutArray) { + ts.Debug.assert(candidates.length > 0); // Else should not have called this. + // Normally we will combine overloads. Skip this if they have type parameters since that's hard to combine. + // Don't do this if there is a `candidatesOutArray`, + // because then we want the chosen best candidate to be one of the overloads, not a combination. + return hasCandidatesOutArray || candidates.length === 1 || candidates.some(function (c) { return !!c.typeParameters; }) + ? pickLongestCandidateSignature(node, candidates, args) + : createUnionOfSignaturesForOverloadFailure(candidates); + } + function createUnionOfSignaturesForOverloadFailure(candidates) { + var thisParameters = ts.mapDefined(candidates, function (c) { return c.thisParameter; }); + var thisParameter; + if (thisParameters.length) { + thisParameter = createCombinedSymbolFromTypes(thisParameters, thisParameters.map(getTypeOfParameter)); + } + var _a = ts.minAndMax(candidates, getNumNonRestParameters), minArgumentCount = _a.min, maxNonRestParam = _a.max; + var parameters = []; + var _loop_7 = function (i) { + var symbols = ts.mapDefined(candidates, function (_a) { + var parameters = _a.parameters, hasRestParameter = _a.hasRestParameter; + return hasRestParameter ? + i < parameters.length - 1 ? parameters[i] : ts.last(parameters) : + i < parameters.length ? parameters[i] : undefined; + }); + ts.Debug.assert(symbols.length !== 0); + parameters.push(createCombinedSymbolFromTypes(symbols, ts.mapDefined(candidates, function (candidate) { return tryGetTypeAtPosition(candidate, i); }))); + }; + for (var i = 0; i < maxNonRestParam; i++) { + _loop_7(i); + } + var restParameterSymbols = ts.mapDefined(candidates, function (c) { return c.hasRestParameter ? ts.last(c.parameters) : undefined; }); + var hasRestParameter = restParameterSymbols.length !== 0; + if (hasRestParameter) { + var type = createArrayType(getUnionType(ts.mapDefined(candidates, tryGetRestTypeOfSignature), 2 /* Subtype */)); + parameters.push(createCombinedSymbolForOverloadFailure(restParameterSymbols, type)); + } + return createSignature(candidates[0].declaration, + /*typeParameters*/ undefined, // Before calling this we tested for `!candidates.some(c => !!c.typeParameters)`. + thisParameter, parameters, + /*resolvedReturnType*/ getIntersectionType(candidates.map(getReturnTypeOfSignature)), + /*typePredicate*/ undefined, minArgumentCount, hasRestParameter, + /*hasLiteralTypes*/ candidates.some(function (c) { return c.hasLiteralTypes; })); + } + function getNumNonRestParameters(signature) { + var numParams = signature.parameters.length; + return signature.hasRestParameter ? numParams - 1 : numParams; + } + function createCombinedSymbolFromTypes(sources, types) { + return createCombinedSymbolForOverloadFailure(sources, getUnionType(types, 2 /* Subtype */)); + } + function createCombinedSymbolForOverloadFailure(sources, type) { + // This function is currently only used for erroneous overloads, so it's good enough to just use the first source. + return createSymbolWithType(ts.first(sources), type); + } + function pickLongestCandidateSignature(node, candidates, args) { + // Pick the longest signature. This way we can get a contextual type for cases like: + // declare function f(a: { xa: number; xb: number; }, b: number); + // f({ | + // Also, use explicitly-supplied type arguments if they are provided, so we can get a contextual signature in cases like: + // declare function f(k: keyof T); + // f(" + var bestIndex = getLongestCandidateIndex(candidates, apparentArgumentCount === undefined ? args.length : apparentArgumentCount); + var candidate = candidates[bestIndex]; + var typeParameters = candidate.typeParameters; + if (!typeParameters) { + return candidate; + } + var typeArgumentNodes = callLikeExpressionMayHaveTypeArguments(node) ? node.typeArguments : undefined; + var instantiated = typeArgumentNodes + ? createSignatureInstantiation(candidate, getTypeArgumentsFromNodes(typeArgumentNodes, typeParameters, ts.isInJSFile(node))) + : inferSignatureInstantiationForOverloadFailure(node, typeParameters, candidate, args); + candidates[bestIndex] = instantiated; + return instantiated; + } + function getTypeArgumentsFromNodes(typeArgumentNodes, typeParameters, isJs) { + var typeArguments = typeArgumentNodes.map(getTypeOfNode); + while (typeArguments.length > typeParameters.length) { + typeArguments.pop(); + } + while (typeArguments.length < typeParameters.length) { + typeArguments.push(getConstraintOfTypeParameter(typeParameters[typeArguments.length]) || getDefaultTypeArgumentType(isJs)); + } + return typeArguments; + } + function inferSignatureInstantiationForOverloadFailure(node, typeParameters, candidate, args) { + var inferenceContext = createInferenceContext(typeParameters, candidate, /*flags*/ ts.isInJSFile(node) ? 2 /* AnyDefault */ : 0 /* None */); + var typeArgumentTypes = inferTypeArguments(node, candidate, args, getExcludeArgument(args), inferenceContext); + return createSignatureInstantiation(candidate, typeArgumentTypes); + } + function getLongestCandidateIndex(candidates, argsCount) { + var maxParamsIndex = -1; + var maxParams = -1; + for (var i = 0; i < candidates.length; i++) { + var candidate = candidates[i]; + var paramCount = getParameterCount(candidate); + if (hasEffectiveRestParameter(candidate) || paramCount >= argsCount) { + return i; + } + if (paramCount > maxParams) { + maxParams = paramCount; + maxParamsIndex = i; + } + } + return maxParamsIndex; + } + function resolveCallExpression(node, candidatesOutArray, isForSignatureHelp) { + if (node.expression.kind === 98 /* SuperKeyword */) { + var superType = checkSuperExpression(node.expression); + if (isTypeAny(superType)) { + for (var _i = 0, _a = node.arguments; _i < _a.length; _i++) { + var arg = _a[_i]; + checkExpression(arg); // Still visit arguments so they get marked for visibility, etc + } + return anySignature; + } + if (superType !== errorType) { + // In super call, the candidate signatures are the matching arity signatures of the base constructor function instantiated + // with the type arguments specified in the extends clause. + var baseTypeNode = ts.getEffectiveBaseTypeNode(ts.getContainingClass(node)); + if (baseTypeNode) { + var baseConstructors = getInstantiatedConstructorsForTypeArguments(superType, baseTypeNode.typeArguments, baseTypeNode); + return resolveCall(node, baseConstructors, candidatesOutArray, isForSignatureHelp); + } + } + return resolveUntypedCall(node); + } + var funcType = checkNonNullExpression(node.expression, ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_null, ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_undefined, ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_null_or_undefined); + if (funcType === silentNeverType) { + return silentNeverSignature; + } + var apparentType = getApparentType(funcType); + if (apparentType === errorType) { + // Another error has already been reported + return resolveErrorCall(node); + } + // Technically, this signatures list may be incomplete. We are taking the apparent type, + // but we are not including call signatures that may have been added to the Object or + // Function interface, since they have none by default. This is a bit of a leap of faith + // that the user will not add any. + var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */); + var numConstructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */).length; + // TS 1.0 Spec: 4.12 + // In an untyped function call no TypeArgs are permitted, Args can be any argument list, no contextual + // types are provided for the argument expressions, and the result is always of type Any. + if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, numConstructSignatures)) { + // The unknownType indicates that an error already occurred (and was reported). No + // need to report another error in this case. + if (funcType !== errorType && node.typeArguments) { + error(node, ts.Diagnostics.Untyped_function_calls_may_not_accept_type_arguments); + } + return resolveUntypedCall(node); + } + // If FuncExpr's apparent type(section 3.8.1) is a function type, the call is a typed function call. + // TypeScript employs overload resolution in typed function calls in order to support functions + // with multiple call signatures. + if (!callSignatures.length) { + if (numConstructSignatures) { + error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType)); + } + else { + var relatedInformation = void 0; + if (node.arguments.length === 1) { + var text = ts.getSourceFileOfNode(node).text; + if (ts.isLineBreak(text.charCodeAt(ts.skipTrivia(text, node.expression.end, /* stopAfterLineBreak */ true) - 1))) { + relatedInformation = ts.createDiagnosticForNode(node.expression, ts.Diagnostics.It_is_highly_likely_that_you_are_missing_a_semicolon); + } + } + invocationError(node, apparentType, 0 /* Call */, relatedInformation); + } + return resolveErrorCall(node); + } + // If the function is explicitly marked with `@class`, then it must be constructed. + if (callSignatures.some(function (sig) { return ts.isInJSFile(sig.declaration) && !!ts.getJSDocClassTag(sig.declaration); })) { + error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType)); + return resolveErrorCall(node); + } + return resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp); + } + /** + * TS 1.0 spec: 4.12 + * If FuncExpr is of type Any, or of an object type that has no call or construct signatures + * but is a subtype of the Function interface, the call is an untyped function call. + */ + function isUntypedFunctionCall(funcType, apparentFuncType, numCallSignatures, numConstructSignatures) { + // We exclude union types because we may have a union of function types that happen to have no common signatures. + return isTypeAny(funcType) || isTypeAny(apparentFuncType) && funcType.flags & 262144 /* TypeParameter */ || + !numCallSignatures && !numConstructSignatures && !(apparentFuncType.flags & (1048576 /* Union */ | 131072 /* Never */)) && isTypeAssignableTo(funcType, globalFunctionType); + } + function resolveNewExpression(node, candidatesOutArray, isForSignatureHelp) { + if (node.arguments && languageVersion < 1 /* ES5 */) { + var spreadIndex = getSpreadArgumentIndex(node.arguments); + if (spreadIndex >= 0) { + error(node.arguments[spreadIndex], ts.Diagnostics.Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher); + } + } + var expressionType = checkNonNullExpression(node.expression); + if (expressionType === silentNeverType) { + return silentNeverSignature; + } + // If expressionType's apparent type(section 3.8.1) is an object type with one or + // more construct signatures, the expression is processed in the same manner as a + // function call, but using the construct signatures as the initial set of candidate + // signatures for overload resolution. The result type of the function call becomes + // the result type of the operation. + expressionType = getApparentType(expressionType); + if (expressionType === errorType) { + // Another error has already been reported + return resolveErrorCall(node); + } + // TS 1.0 spec: 4.11 + // If expressionType is of type Any, Args can be any argument + // list and the result of the operation is of type Any. + if (isTypeAny(expressionType)) { + if (node.typeArguments) { + error(node, ts.Diagnostics.Untyped_function_calls_may_not_accept_type_arguments); + } + return resolveUntypedCall(node); + } + // Technically, this signatures list may be incomplete. We are taking the apparent type, + // but we are not including construct signatures that may have been added to the Object or + // Function interface, since they have none by default. This is a bit of a leap of faith + // that the user will not add any. + var constructSignatures = getSignaturesOfType(expressionType, 1 /* Construct */); + if (constructSignatures.length) { + if (!isConstructorAccessible(node, constructSignatures[0])) { + return resolveErrorCall(node); + } + // If the expression is a class of abstract type, then it cannot be instantiated. + // Note, only class declarations can be declared abstract. + // In the case of a merged class-module or class-interface declaration, + // only the class declaration node will have the Abstract flag set. + var valueDecl = expressionType.symbol && ts.getClassLikeDeclarationOfSymbol(expressionType.symbol); + if (valueDecl && ts.hasModifier(valueDecl, 128 /* Abstract */)) { + error(node, ts.Diagnostics.Cannot_create_an_instance_of_an_abstract_class); + return resolveErrorCall(node); + } + return resolveCall(node, constructSignatures, candidatesOutArray, isForSignatureHelp); + } + // If expressionType's apparent type is an object type with no construct signatures but + // one or more call signatures, the expression is processed as a function call. A compile-time + // error occurs if the result of the function call is not Void. The type of the result of the + // operation is Any. It is an error to have a Void this type. + var callSignatures = getSignaturesOfType(expressionType, 0 /* Call */); + if (callSignatures.length) { + var signature = resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp); + if (!noImplicitAny) { + if (signature.declaration && !isJSConstructor(signature.declaration) && getReturnTypeOfSignature(signature) !== voidType) { + error(node, ts.Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword); + } + if (getThisTypeOfSignature(signature) === voidType) { + error(node, ts.Diagnostics.A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void); + } + } + return signature; + } + invocationError(node, expressionType, 1 /* Construct */); + return resolveErrorCall(node); + } + function typeHasProtectedAccessibleBase(target, type) { + var baseTypes = getBaseTypes(type); + if (!ts.length(baseTypes)) { + return false; + } + var firstBase = baseTypes[0]; + if (firstBase.flags & 2097152 /* Intersection */) { + var types = firstBase.types; + var mixinCount = ts.countWhere(types, isMixinConstructorType); + var i = 0; + for (var _i = 0, _a = firstBase.types; _i < _a.length; _i++) { + var intersectionMember = _a[_i]; + i++; + // We want to ignore mixin ctors + if (mixinCount === 0 || mixinCount === types.length && i === 0 || !isMixinConstructorType(intersectionMember)) { + if (ts.getObjectFlags(intersectionMember) & (1 /* Class */ | 2 /* Interface */)) { + if (intersectionMember.symbol === target) { + return true; + } + if (typeHasProtectedAccessibleBase(target, intersectionMember)) { + return true; + } + } + } + } + return false; + } + if (firstBase.symbol === target) { + return true; + } + return typeHasProtectedAccessibleBase(target, firstBase); + } + function isConstructorAccessible(node, signature) { + if (!signature || !signature.declaration) { + return true; + } + var declaration = signature.declaration; + var modifiers = ts.getSelectedModifierFlags(declaration, 24 /* NonPublicAccessibilityModifier */); + // Public constructor is accessible. + if (!modifiers) { + return true; + } + var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(declaration.parent.symbol); + var declaringClass = getDeclaredTypeOfSymbol(declaration.parent.symbol); + // A private or protected constructor can only be instantiated within its own class (or a subclass, for protected) + if (!isNodeWithinClass(node, declaringClassDeclaration)) { + var containingClass = ts.getContainingClass(node); + if (containingClass && modifiers & 16 /* Protected */) { + var containingType = getTypeOfNode(containingClass); + if (typeHasProtectedAccessibleBase(declaration.parent.symbol, containingType)) { + return true; + } + } + if (modifiers & 8 /* Private */) { + error(node, ts.Diagnostics.Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration, typeToString(declaringClass)); + } + if (modifiers & 16 /* Protected */) { + error(node, ts.Diagnostics.Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration, typeToString(declaringClass)); + } + return false; + } + return true; + } + function invocationError(node, apparentType, kind, relatedInformation) { + var diagnostic = error(node, (kind === 0 /* Call */ ? + ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures : + ts.Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature), typeToString(apparentType)); + invocationErrorRecovery(apparentType, kind, relatedInformation ? addRelatedInfo(diagnostic, relatedInformation) : diagnostic); + } + function invocationErrorRecovery(apparentType, kind, diagnostic) { + if (!apparentType.symbol) { + return; + } + var importNode = getSymbolLinks(apparentType.symbol).originatingImport; + // Create a diagnostic on the originating import if possible onto which we can attach a quickfix + // An import call expression cannot be rewritten into another form to correct the error - the only solution is to use `.default` at the use-site + if (importNode && !ts.isImportCall(importNode)) { + var sigs = getSignaturesOfType(getTypeOfSymbol(getSymbolLinks(apparentType.symbol).target), kind); + if (!sigs || !sigs.length) + return; + addRelatedInfo(diagnostic, ts.createDiagnosticForNode(importNode, ts.Diagnostics.Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_Consider_using_a_default_import_or_import_require_here_instead)); + } + } + function resolveTaggedTemplateExpression(node, candidatesOutArray, isForSignatureHelp) { + var tagType = checkExpression(node.tag); + var apparentType = getApparentType(tagType); + if (apparentType === errorType) { + // Another error has already been reported + return resolveErrorCall(node); + } + var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */); + var numConstructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */).length; + if (isUntypedFunctionCall(tagType, apparentType, callSignatures.length, numConstructSignatures)) { + return resolveUntypedCall(node); + } + if (!callSignatures.length) { + invocationError(node, apparentType, 0 /* Call */); + return resolveErrorCall(node); + } + return resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp); + } + /** + * Gets the localized diagnostic head message to use for errors when resolving a decorator as a call expression. + */ + function getDiagnosticHeadMessageForDecoratorResolution(node) { + switch (node.parent.kind) { + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + return ts.Diagnostics.Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression; + case 151 /* Parameter */: + return ts.Diagnostics.Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression; + case 154 /* PropertyDeclaration */: + return ts.Diagnostics.Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression; + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + return ts.Diagnostics.Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression; + default: + return ts.Debug.fail(); + } + } + /** + * Resolves a decorator as if it were a call expression. + */ + function resolveDecorator(node, candidatesOutArray, isForSignatureHelp) { + var funcType = checkExpression(node.expression); + var apparentType = getApparentType(funcType); + if (apparentType === errorType) { + return resolveErrorCall(node); + } + var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */); + var numConstructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */).length; + if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, numConstructSignatures)) { + return resolveUntypedCall(node); + } + if (isPotentiallyUncalledDecorator(node, callSignatures)) { + var nodeStr = ts.getTextOfNode(node.expression, /*includeTrivia*/ false); + error(node, ts.Diagnostics._0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write_0, nodeStr); + return resolveErrorCall(node); + } + var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); + if (!callSignatures.length) { + var errorInfo = ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures, typeToString(apparentType)); + errorInfo = ts.chainDiagnosticMessages(errorInfo, headMessage); + var diag = ts.createDiagnosticForNodeFromMessageChain(node, errorInfo); + diagnostics.add(diag); + invocationErrorRecovery(apparentType, 0 /* Call */, diag); + return resolveErrorCall(node); + } + return resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp, headMessage); + } + function createSignatureForJSXIntrinsic(node, result) { + var namespace = getJsxNamespaceAt(node); + var exports = namespace && getExportsOfSymbol(namespace); + // We fake up a SFC signature for each intrinsic, however a more specific per-element signature drawn from the JSX declaration + // file would probably be preferable. + var typeSymbol = exports && getSymbol(exports, JsxNames.Element, 67897832 /* Type */); + var returnNode = typeSymbol && nodeBuilder.symbolToEntityName(typeSymbol, 67897832 /* Type */, node); + var declaration = ts.createFunctionTypeNode(/*typeParameters*/ undefined, [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotdotdot*/ undefined, "props", /*questionMark*/ undefined, nodeBuilder.typeToTypeNode(result, node))], returnNode ? ts.createTypeReferenceNode(returnNode, /*typeArguments*/ undefined) : ts.createKeywordTypeNode(120 /* AnyKeyword */)); + var parameterSymbol = createSymbol(1 /* FunctionScopedVariable */, "props"); + parameterSymbol.type = result; + return createSignature(declaration, + /*typeParameters*/ undefined, + /*thisParameter*/ undefined, [parameterSymbol], typeSymbol ? getDeclaredTypeOfSymbol(typeSymbol) : errorType, + /*returnTypePredicate*/ undefined, 1, + /*hasRestparameter*/ false, + /*hasLiteralTypes*/ false); + } + function resolveJsxOpeningLikeElement(node, candidatesOutArray, isForSignatureHelp) { + if (isJsxIntrinsicIdentifier(node.tagName)) { + var result = getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node); + var fakeSignature = createSignatureForJSXIntrinsic(node, result); + checkTypeAssignableToAndOptionallyElaborate(checkExpressionWithContextualType(node.attributes, getEffectiveFirstArgumentForJsxSignature(fakeSignature, node), /*mapper*/ undefined), result, node.tagName, node.attributes); + return fakeSignature; + } + var exprTypes = checkExpression(node.tagName); + var apparentType = getApparentType(exprTypes); + if (apparentType === errorType) { + return resolveErrorCall(node); + } + var signatures = getUninstantiatedJsxSignaturesOfType(exprTypes, node); + if (isUntypedFunctionCall(exprTypes, apparentType, signatures.length, /*constructSignatures*/ 0)) { + return resolveUntypedCall(node); + } + if (signatures.length === 0) { + // We found no signatures at all, which is an error + error(node.tagName, ts.Diagnostics.JSX_element_type_0_does_not_have_any_construct_or_call_signatures, ts.getTextOfNode(node.tagName)); + return resolveErrorCall(node); + } + return resolveCall(node, signatures, candidatesOutArray, isForSignatureHelp); + } + /** + * Sometimes, we have a decorator that could accept zero arguments, + * but is receiving too many arguments as part of the decorator invocation. + * In those cases, a user may have meant to *call* the expression before using it as a decorator. + */ + function isPotentiallyUncalledDecorator(decorator, signatures) { + return signatures.length && ts.every(signatures, function (signature) { + return signature.minArgumentCount === 0 && + !signature.hasRestParameter && + signature.parameters.length < getDecoratorArgumentCount(decorator, signature); + }); + } + function resolveSignature(node, candidatesOutArray, isForSignatureHelp) { + switch (node.kind) { + case 191 /* CallExpression */: + return resolveCallExpression(node, candidatesOutArray, isForSignatureHelp); + case 192 /* NewExpression */: + return resolveNewExpression(node, candidatesOutArray, isForSignatureHelp); + case 193 /* TaggedTemplateExpression */: + return resolveTaggedTemplateExpression(node, candidatesOutArray, isForSignatureHelp); + case 152 /* Decorator */: + return resolveDecorator(node, candidatesOutArray, isForSignatureHelp); + case 262 /* JsxOpeningElement */: + case 261 /* JsxSelfClosingElement */: + return resolveJsxOpeningLikeElement(node, candidatesOutArray, isForSignatureHelp); + } + throw ts.Debug.assertNever(node, "Branch in 'resolveSignature' should be unreachable."); + } + /** + * Resolve a signature of a given call-like expression. + * @param node a call-like expression to try resolve a signature for + * @param candidatesOutArray an array of signature to be filled in by the function. It is passed by signature help in the language service; + * the function will fill it up with appropriate candidate signatures + * @return a signature of the call-like expression or undefined if one can't be found + */ + function getResolvedSignature(node, candidatesOutArray, isForSignatureHelp) { + if (isForSignatureHelp === void 0) { isForSignatureHelp = false; } + var links = getNodeLinks(node); + // If getResolvedSignature has already been called, we will have cached the resolvedSignature. + // However, it is possible that either candidatesOutArray was not passed in the first time, + // or that a different candidatesOutArray was passed in. Therefore, we need to redo the work + // to correctly fill the candidatesOutArray. + var cached = links.resolvedSignature; + if (cached && cached !== resolvingSignature && !candidatesOutArray) { + return cached; + } + links.resolvedSignature = resolvingSignature; + var result = resolveSignature(node, candidatesOutArray, isForSignatureHelp); + // If signature resolution originated in control flow type analysis (for example to compute the + // assigned type in a flow assignment) we don't cache the result as it may be based on temporary + // types from the control flow analysis. + links.resolvedSignature = flowLoopStart === flowLoopCount ? result : cached; + return result; + } + /** + * Indicates whether a declaration can be treated as a constructor in a JavaScript + * file. + */ + function isJSConstructor(node) { + if (!node || !ts.isInJSFile(node)) { + return false; + } + var func = ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node) ? node : + ts.isVariableDeclaration(node) && node.initializer && ts.isFunctionExpression(node.initializer) ? node.initializer : + undefined; + if (func) { + // If the node has a @class tag, treat it like a constructor. + if (ts.getJSDocClassTag(node)) + return true; + // If the symbol of the node has members, treat it like a constructor. + var symbol = getSymbolOfNode(func); + return !!symbol && symbol.members !== undefined; + } + return false; + } + function isJSConstructorType(type) { + if (type.flags & 524288 /* Object */) { + var resolved = resolveStructuredTypeMembers(type); + return resolved.callSignatures.length === 1 && isJSConstructor(resolved.callSignatures[0].declaration); + } + return false; + } + function getJSClassType(symbol) { + var inferred; + if (isJSConstructor(symbol.valueDeclaration)) { + inferred = getInferredClassType(symbol); + } + var assigned = getAssignedClassType(symbol); + var valueType = getTypeOfSymbol(symbol); + if (valueType.symbol && !isInferredClassType(valueType) && isJSConstructor(valueType.symbol.valueDeclaration)) { + inferred = getInferredClassType(valueType.symbol); + } + return assigned && inferred ? + getIntersectionType([inferred, assigned]) : + assigned || inferred; + } + function getAssignedClassType(symbol) { + var decl = symbol.valueDeclaration; + var assignmentSymbol = decl && decl.parent && + (ts.isFunctionDeclaration(decl) && getSymbolOfNode(decl) || + ts.isBinaryExpression(decl.parent) && getSymbolOfNode(decl.parent.left) || + ts.isVariableDeclaration(decl.parent) && getSymbolOfNode(decl.parent)); + var prototype = assignmentSymbol && assignmentSymbol.exports && assignmentSymbol.exports.get("prototype"); + var init = prototype && prototype.valueDeclaration && getAssignedJSPrototype(prototype.valueDeclaration); + return init ? checkExpression(init) : undefined; + } + function getAssignedJSPrototype(node) { + if (!node.parent) { + return false; + } + var parent = node.parent; + while (parent && parent.kind === 189 /* PropertyAccessExpression */) { + parent = parent.parent; + } + if (parent && ts.isBinaryExpression(parent) && ts.isPrototypeAccess(parent.left) && parent.operatorToken.kind === 59 /* EqualsToken */) { + var right = ts.getInitializerOfBinaryExpression(parent); + return ts.isObjectLiteralExpression(right) && right; + } + } + function getInferredClassType(symbol) { + var links = getSymbolLinks(symbol); + if (!links.inferredClassType) { + links.inferredClassType = createAnonymousType(symbol, getMembersOfSymbol(symbol) || emptySymbols, ts.emptyArray, ts.emptyArray, /*stringIndexType*/ undefined, /*numberIndexType*/ undefined); + } + return links.inferredClassType; + } + function isInferredClassType(type) { + return type.symbol + && ts.getObjectFlags(type) & 16 /* Anonymous */ + && getSymbolLinks(type.symbol).inferredClassType === type; + } + /** + * Syntactically and semantically checks a call or new expression. + * @param node The call/new expression to be checked. + * @returns On success, the expression's signature's return type. On failure, anyType. + */ + function checkCallExpression(node) { + if (!checkGrammarTypeArguments(node, node.typeArguments)) + checkGrammarArguments(node.arguments); + var signature = getResolvedSignature(node); + if (node.expression.kind === 98 /* SuperKeyword */) { + return voidType; + } + if (node.kind === 192 /* NewExpression */) { + var declaration = signature.declaration; + if (declaration && + declaration.kind !== 157 /* Constructor */ && + declaration.kind !== 161 /* ConstructSignature */ && + declaration.kind !== 166 /* ConstructorType */ && + !ts.isJSDocConstructSignature(declaration)) { + // When resolved signature is a call signature (and not a construct signature) the result type is any, unless + // the declaring function had members created through 'x.prototype.y = expr' or 'this.y = expr' psuedodeclarations + // in a JS file + // Note:JS inferred classes might come from a variable declaration instead of a function declaration. + // In this case, using getResolvedSymbol directly is required to avoid losing the members from the declaration. + var funcSymbol = checkExpression(node.expression).symbol; + if (!funcSymbol && node.expression.kind === 72 /* Identifier */) { + funcSymbol = getResolvedSymbol(node.expression); + } + var type = funcSymbol && getJSClassType(funcSymbol); + if (type) { + return signature.target ? instantiateType(type, signature.mapper) : type; + } + if (noImplicitAny) { + error(node, ts.Diagnostics.new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type); + } + return anyType; + } + } + // In JavaScript files, calls to any identifier 'require' are treated as external module imports + if (ts.isInJSFile(node) && isCommonJsRequire(node)) { + return resolveExternalModuleTypeByLiteral(node.arguments[0]); + } + var returnType = getReturnTypeOfSignature(signature); + // Treat any call to the global 'Symbol' function that is part of a const variable or readonly property + // as a fresh unique symbol literal type. + if (returnType.flags & 12288 /* ESSymbolLike */ && isSymbolOrSymbolForCall(node)) { + return getESSymbolLikeTypeForNode(ts.walkUpParenthesizedExpressions(node.parent)); + } + var jsAssignmentType; + if (ts.isInJSFile(node)) { + var decl = ts.getDeclarationOfExpando(node); + if (decl) { + var jsSymbol = getSymbolOfNode(decl); + if (jsSymbol && ts.hasEntries(jsSymbol.exports)) { + jsAssignmentType = createAnonymousType(jsSymbol, jsSymbol.exports, ts.emptyArray, ts.emptyArray, undefined, undefined); + jsAssignmentType.objectFlags |= 16384 /* JSLiteral */; + } + } + } + return jsAssignmentType ? getIntersectionType([returnType, jsAssignmentType]) : returnType; + } + function isSymbolOrSymbolForCall(node) { + if (!ts.isCallExpression(node)) + return false; + var left = node.expression; + if (ts.isPropertyAccessExpression(left) && left.name.escapedText === "for") { + left = left.expression; + } + if (!ts.isIdentifier(left) || left.escapedText !== "Symbol") { + return false; + } + // make sure `Symbol` is the global symbol + var globalESSymbol = getGlobalESSymbolConstructorSymbol(/*reportErrors*/ false); + if (!globalESSymbol) { + return false; + } + return globalESSymbol === resolveName(left, "Symbol", 67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); + } + function checkImportCallExpression(node) { + // Check grammar of dynamic import + if (!checkGrammarArguments(node.arguments)) + checkGrammarImportCallExpression(node); + if (node.arguments.length === 0) { + return createPromiseReturnType(node, anyType); + } + var specifier = node.arguments[0]; + var specifierType = checkExpressionCached(specifier); + // Even though multiple arguments is grammatically incorrect, type-check extra arguments for completion + for (var i = 1; i < node.arguments.length; ++i) { + checkExpressionCached(node.arguments[i]); + } + if (specifierType.flags & 32768 /* Undefined */ || specifierType.flags & 65536 /* Null */ || !isTypeAssignableTo(specifierType, stringType)) { + error(specifier, ts.Diagnostics.Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0, typeToString(specifierType)); + } + // resolveExternalModuleName will return undefined if the moduleReferenceExpression is not a string literal + var moduleSymbol = resolveExternalModuleName(node, specifier); + if (moduleSymbol) { + var esModuleSymbol = resolveESModuleSymbol(moduleSymbol, specifier, /*dontRecursivelyResolve*/ true); + if (esModuleSymbol) { + return createPromiseReturnType(node, getTypeWithSyntheticDefaultImportType(getTypeOfSymbol(esModuleSymbol), esModuleSymbol, moduleSymbol)); + } + } + return createPromiseReturnType(node, anyType); + } + function getTypeWithSyntheticDefaultImportType(type, symbol, originalSymbol) { + if (allowSyntheticDefaultImports && type && type !== errorType) { + var synthType = type; + if (!synthType.syntheticType) { + var file = ts.find(originalSymbol.declarations, ts.isSourceFile); + var hasSyntheticDefault = canHaveSyntheticDefault(file, originalSymbol, /*dontResolveAlias*/ false); + if (hasSyntheticDefault) { + var memberTable = ts.createSymbolTable(); + var newSymbol = createSymbol(2097152 /* Alias */, "default" /* Default */); + newSymbol.nameType = getLiteralType("default"); + newSymbol.target = resolveSymbol(symbol); + memberTable.set("default" /* Default */, newSymbol); + var anonymousSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */); + var defaultContainingObject = createAnonymousType(anonymousSymbol, memberTable, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined); + anonymousSymbol.type = defaultContainingObject; + synthType.syntheticType = isValidSpreadType(type) ? getSpreadType(type, defaultContainingObject, anonymousSymbol, /*typeFLags*/ 0, /*objectFlags*/ 0) : defaultContainingObject; + } + else { + synthType.syntheticType = type; + } + } + return synthType.syntheticType; + } + return type; + } + function isCommonJsRequire(node) { + if (!ts.isRequireCall(node, /*checkArgumentIsStringLiteralLike*/ true)) { + return false; + } + // Make sure require is not a local function + if (!ts.isIdentifier(node.expression)) + return ts.Debug.fail(); + var resolvedRequire = resolveName(node.expression, node.expression.escapedText, 67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); // TODO: GH#18217 + if (resolvedRequire === requireSymbol) { + return true; + } + // project includes symbol named 'require' - make sure that it is ambient and local non-alias + if (resolvedRequire.flags & 2097152 /* Alias */) { + return false; + } + var targetDeclarationKind = resolvedRequire.flags & 16 /* Function */ + ? 239 /* FunctionDeclaration */ + : resolvedRequire.flags & 3 /* Variable */ + ? 237 /* VariableDeclaration */ + : 0 /* Unknown */; + if (targetDeclarationKind !== 0 /* Unknown */) { + var decl = ts.getDeclarationOfKind(resolvedRequire, targetDeclarationKind); + // function/variable declaration should be ambient + return !!decl && !!(decl.flags & 4194304 /* Ambient */); + } + return false; + } + function checkTaggedTemplateExpression(node) { + checkGrammarTypeArguments(node, node.typeArguments); + if (languageVersion < 2 /* ES2015 */) { + checkExternalEmitHelpers(node, 65536 /* MakeTemplateObject */); + } + return getReturnTypeOfSignature(getResolvedSignature(node)); + } + function checkAssertion(node) { + return checkAssertionWorker(node, node.type, node.expression); + } + function checkAssertionWorker(errNode, type, expression, checkMode) { + var exprType = getRegularTypeOfObjectLiteral(getBaseTypeOfLiteralType(checkExpression(expression, checkMode))); + checkSourceElement(type); + var targetType = getTypeFromTypeNode(type); + if (produceDiagnostics && targetType !== errorType) { + var widenedType = getWidenedType(exprType); + if (!isTypeComparableTo(targetType, widenedType)) { + checkTypeComparableTo(exprType, targetType, errNode, ts.Diagnostics.Conversion_of_type_0_to_type_1_may_be_a_mistake_because_neither_type_sufficiently_overlaps_with_the_other_If_this_was_intentional_convert_the_expression_to_unknown_first); + } + } + return targetType; + } + function checkNonNullAssertion(node) { + return getNonNullableType(checkExpression(node.expression)); + } + function checkMetaProperty(node) { + checkGrammarMetaProperty(node); + if (node.keywordToken === 95 /* NewKeyword */) { + return checkNewTargetMetaProperty(node); + } + if (node.keywordToken === 92 /* ImportKeyword */) { + return checkImportMetaProperty(node); + } + return ts.Debug.assertNever(node.keywordToken); + } + function checkNewTargetMetaProperty(node) { + var container = ts.getNewTargetContainer(node); + if (!container) { + error(node, ts.Diagnostics.Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constructor, "new.target"); + return errorType; + } + else if (container.kind === 157 /* Constructor */) { + var symbol = getSymbolOfNode(container.parent); + return getTypeOfSymbol(symbol); + } + else { + var symbol = getSymbolOfNode(container); + return getTypeOfSymbol(symbol); + } + } + function checkImportMetaProperty(node) { + if (languageVersion < 6 /* ESNext */ || moduleKind < ts.ModuleKind.ESNext) { + error(node, ts.Diagnostics.The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_options); + } + var file = ts.getSourceFileOfNode(node); + ts.Debug.assert(!!(file.flags & 1048576 /* PossiblyContainsImportMeta */), "Containing file is missing import meta node flag."); + ts.Debug.assert(!!file.externalModuleIndicator, "Containing file should be a module."); + return node.name.escapedText === "meta" ? getGlobalImportMetaType() : errorType; + } + function getTypeOfParameter(symbol) { + var type = getTypeOfSymbol(symbol); + if (strictNullChecks) { + var declaration = symbol.valueDeclaration; + if (declaration && ts.hasInitializer(declaration)) { + return getOptionalType(type); + } + } + return type; + } + function getParameterNameAtPosition(signature, pos) { + var paramCount = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); + if (pos < paramCount) { + return signature.parameters[pos].escapedName; + } + var restParameter = signature.parameters[paramCount] || unknownSymbol; + var restType = getTypeOfSymbol(restParameter); + if (isTupleType(restType)) { + var associatedNames = restType.target.associatedNames; + var index = pos - paramCount; + return associatedNames ? associatedNames[index] : restParameter.escapedName + "_" + index; + } + return restParameter.escapedName; + } + function getTypeAtPosition(signature, pos) { + return tryGetTypeAtPosition(signature, pos) || anyType; + } + function tryGetTypeAtPosition(signature, pos) { + var paramCount = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); + if (pos < paramCount) { + return getTypeOfParameter(signature.parameters[pos]); + } + if (signature.hasRestParameter) { + var restType = getTypeOfSymbol(signature.parameters[paramCount]); + if (isTupleType(restType)) { + if (pos - paramCount < getLengthOfTupleType(restType)) { + return restType.typeArguments[pos - paramCount]; + } + return getRestTypeOfTupleType(restType); + } + return getIndexTypeOfType(restType, 1 /* Number */); + } + return undefined; + } + function getRestTypeAtPosition(source, pos) { + var paramCount = getParameterCount(source); + var restType = getEffectiveRestType(source); + if (restType && pos === paramCount - 1) { + return restType; + } + var start = restType ? Math.min(pos, paramCount - 1) : pos; + var types = []; + var names = []; + for (var i = start; i < paramCount; i++) { + types.push(getTypeAtPosition(source, i)); + names.push(getParameterNameAtPosition(source, i)); + } + var minArgumentCount = getMinArgumentCount(source); + var minLength = minArgumentCount < start ? 0 : minArgumentCount - start; + return createTupleType(types, minLength, !!restType, names); + } + function getParameterCount(signature) { + var length = signature.parameters.length; + if (signature.hasRestParameter) { + var restType = getTypeOfSymbol(signature.parameters[length - 1]); + if (isTupleType(restType)) { + return length + (restType.typeArguments || ts.emptyArray).length - 1; + } + } + return length; + } + function getMinArgumentCount(signature) { + if (signature.hasRestParameter) { + var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); + if (isTupleType(restType)) { + var minLength = restType.target.minLength; + if (minLength > 0) { + return signature.parameters.length - 1 + minLength; + } + } + } + return signature.minArgumentCount; + } + function hasEffectiveRestParameter(signature) { + if (signature.hasRestParameter) { + var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); + return !isTupleType(restType) || restType.target.hasRestElement; + } + return false; + } + function getEffectiveRestType(signature) { + if (signature.hasRestParameter) { + var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); + return isTupleType(restType) ? getRestArrayTypeOfTupleType(restType) : restType; + } + return undefined; + } + function getNonArrayRestType(signature) { + var restType = getEffectiveRestType(signature); + return restType && !isArrayType(restType) && !isTypeAny(restType) ? restType : undefined; + } + function getTypeOfFirstParameterOfSignature(signature) { + return getTypeOfFirstParameterOfSignatureWithFallback(signature, neverType); + } + function getTypeOfFirstParameterOfSignatureWithFallback(signature, fallbackType) { + return signature.parameters.length > 0 ? getTypeAtPosition(signature, 0) : fallbackType; + } + function inferFromAnnotatedParameters(signature, context, mapper) { + var len = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); + for (var i = 0; i < len; i++) { + var declaration = signature.parameters[i].valueDeclaration; + if (declaration.type) { + var typeNode = ts.getEffectiveTypeAnnotationNode(declaration); + if (typeNode) { + inferTypes(mapper.inferences, getTypeFromTypeNode(typeNode), getTypeAtPosition(context, i)); + } + } + } + } + function assignContextualParameterTypes(signature, context) { + signature.typeParameters = context.typeParameters; + if (context.thisParameter) { + var parameter = signature.thisParameter; + if (!parameter || parameter.valueDeclaration && !parameter.valueDeclaration.type) { + if (!parameter) { + signature.thisParameter = createSymbolWithType(context.thisParameter, /*type*/ undefined); + } + assignTypeToParameterAndFixTypeParameters(signature.thisParameter, getTypeOfSymbol(context.thisParameter)); + } + } + var len = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); + for (var i = 0; i < len; i++) { + var parameter = signature.parameters[i]; + if (!ts.getEffectiveTypeAnnotationNode(parameter.valueDeclaration)) { + var contextualParameterType = getTypeAtPosition(context, i); + assignTypeToParameterAndFixTypeParameters(parameter, contextualParameterType); + } + } + if (signature.hasRestParameter) { + // parameter might be a transient symbol generated by use of `arguments` in the function body. + var parameter = ts.last(signature.parameters); + if (isTransientSymbol(parameter) || !ts.getEffectiveTypeAnnotationNode(parameter.valueDeclaration)) { + var contextualParameterType = getRestTypeAtPosition(context, len); + assignTypeToParameterAndFixTypeParameters(parameter, contextualParameterType); + } + } + } + // When contextual typing assigns a type to a parameter that contains a binding pattern, we also need to push + // the destructured type into the contained binding elements. + function assignBindingElementTypes(pattern) { + for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (!ts.isOmittedExpression(element)) { + if (element.name.kind === 72 /* Identifier */) { + getSymbolLinks(getSymbolOfNode(element)).type = getTypeForBindingElement(element); + } + else { + assignBindingElementTypes(element.name); + } + } + } + } + function assignTypeToParameterAndFixTypeParameters(parameter, contextualType) { + var links = getSymbolLinks(parameter); + if (!links.type) { + links.type = contextualType; + var decl = parameter.valueDeclaration; + if (decl.name.kind !== 72 /* Identifier */) { + // if inference didn't come up with anything but {}, fall back to the binding pattern if present. + if (links.type === emptyObjectType) { + links.type = getTypeFromBindingPattern(decl.name); + } + assignBindingElementTypes(decl.name); + } + } + } + function createPromiseType(promisedType) { + // creates a `Promise` type where `T` is the promisedType argument + var globalPromiseType = getGlobalPromiseType(/*reportErrors*/ true); + if (globalPromiseType !== emptyGenericType) { + // if the promised type is itself a promise, get the underlying type; otherwise, fallback to the promised type + promisedType = getAwaitedType(promisedType) || emptyObjectType; + return createTypeReference(globalPromiseType, [promisedType]); + } + return emptyObjectType; + } + function createPromiseLikeType(promisedType) { + // creates a `PromiseLike` type where `T` is the promisedType argument + var globalPromiseLikeType = getGlobalPromiseLikeType(/*reportErrors*/ true); + if (globalPromiseLikeType !== emptyGenericType) { + // if the promised type is itself a promise, get the underlying type; otherwise, fallback to the promised type + promisedType = getAwaitedType(promisedType) || emptyObjectType; + return createTypeReference(globalPromiseLikeType, [promisedType]); + } + return emptyObjectType; + } + function createPromiseReturnType(func, promisedType) { + var promiseType = createPromiseType(promisedType); + if (promiseType === emptyObjectType) { + error(func, ts.isImportCall(func) ? + ts.Diagnostics.A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option : + ts.Diagnostics.An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option); + return errorType; + } + else if (!getGlobalPromiseConstructorSymbol(/*reportErrors*/ true)) { + error(func, ts.isImportCall(func) ? + ts.Diagnostics.A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option : + ts.Diagnostics.An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option); + } + return promiseType; + } + function getReturnTypeFromBody(func, checkMode) { + if (!func.body) { + return errorType; + } + var functionFlags = ts.getFunctionFlags(func); + var type; + if (func.body.kind !== 218 /* Block */) { + type = checkExpressionCached(func.body, checkMode); + if (functionFlags & 2 /* Async */) { + // From within an async function you can return either a non-promise value or a promise. Any + // Promise/A+ compatible implementation will always assimilate any foreign promise, so the + // return type of the body should be unwrapped to its awaited type, which we will wrap in + // the native Promise type later in this function. + type = checkAwaitedType(type, /*errorNode*/ func, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); + } + } + else { + var types = checkAndAggregateReturnExpressionTypes(func, checkMode); + if (functionFlags & 1 /* Generator */) { // Generator or AsyncGenerator function + types = ts.concatenate(checkAndAggregateYieldOperandTypes(func, checkMode), types); + if (!types || types.length === 0) { + var iterableIteratorAny = functionFlags & 2 /* Async */ + ? createAsyncIterableIteratorType(anyType) // AsyncGenerator function + : createIterableIteratorType(anyType); // Generator function + if (noImplicitAny) { + error(func.asteriskToken, ts.Diagnostics.Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_type, typeToString(iterableIteratorAny)); + } + return iterableIteratorAny; + } + } + else { + if (!types) { + // For an async function, the return type will not be never, but rather a Promise for never. + return functionFlags & 2 /* Async */ + ? createPromiseReturnType(func, neverType) // Async function + : neverType; // Normal function + } + if (types.length === 0) { + // For an async function, the return type will not be void, but rather a Promise for void. + return functionFlags & 2 /* Async */ + ? createPromiseReturnType(func, voidType) // Async function + : voidType; // Normal function + } + } + // Return a union of the return expression types. + type = getUnionType(types, 2 /* Subtype */); + } + var contextualSignature = getContextualSignatureForFunctionLikeDeclaration(func); + if (!contextualSignature) { + reportErrorsFromWidening(func, type); + } + if (isUnitType(type)) { + var contextualType = !contextualSignature ? undefined : + contextualSignature === getSignatureFromDeclaration(func) ? type : + getReturnTypeOfSignature(contextualSignature); + if (contextualType) { + switch (functionFlags & 3 /* AsyncGenerator */) { + case 3 /* AsyncGenerator */: + contextualType = getIteratedTypeOfGenerator(contextualType, /*isAsyncGenerator*/ true); + break; + case 1 /* Generator */: + contextualType = getIteratedTypeOfGenerator(contextualType, /*isAsyncGenerator*/ false); + break; + case 2 /* Async */: + contextualType = getPromisedTypeOfPromise(contextualType); + break; + } + } + type = getWidenedLiteralLikeTypeForContextualType(type, contextualType); + } + var widenedType = getWidenedType(type); + switch (functionFlags & 3 /* AsyncGenerator */) { + case 3 /* AsyncGenerator */: + return createAsyncIterableIteratorType(widenedType); + case 1 /* Generator */: + return createIterableIteratorType(widenedType); + case 2 /* Async */: + // From within an async function you can return either a non-promise value or a promise. Any + // Promise/A+ compatible implementation will always assimilate any foreign promise, so the + // return type of the body is awaited type of the body, wrapped in a native Promise type. + return createPromiseType(widenedType); + default: + return widenedType; + } + } + function checkAndAggregateYieldOperandTypes(func, checkMode) { + var aggregatedTypes = []; + var isAsync = (ts.getFunctionFlags(func) & 2 /* Async */) !== 0; + ts.forEachYieldExpression(func.body, function (yieldExpression) { + ts.pushIfUnique(aggregatedTypes, getYieldedTypeOfYieldExpression(yieldExpression, isAsync, checkMode)); + }); + return aggregatedTypes; + } + function getYieldedTypeOfYieldExpression(node, isAsync, checkMode) { + var errorNode = node.expression || node; + var expressionType = node.expression ? checkExpression(node.expression, checkMode) : undefinedWideningType; + // A `yield*` expression effectively yields everything that its operand yields + var yieldedType = node.asteriskToken ? checkIteratedTypeOrElementType(expressionType, errorNode, /*allowStringInput*/ false, isAsync) : expressionType; + return !isAsync ? yieldedType : getAwaitedType(yieldedType, errorNode, node.asteriskToken + ? ts.Diagnostics.Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member + : ts.Diagnostics.Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); + } + /** + * Collect the TypeFacts learned from a typeof switch with + * total clauses `witnesses`, and the active clause ranging + * from `start` to `end`. Parameter `hasDefault` denotes + * whether the active clause contains a default clause. + */ + function getFactsFromTypeofSwitch(start, end, witnesses, hasDefault) { + var facts = 0 /* None */; + // When in the default we only collect inequality facts + // because default is 'in theory' a set of infinite + // equalities. + if (hasDefault) { + // Value is not equal to any types after the active clause. + for (var i = end; i < witnesses.length; i++) { + facts |= typeofNEFacts.get(witnesses[i]) || 32768 /* TypeofNEHostObject */; + } + // Remove inequalities for types that appear in the + // active clause because they appear before other + // types collected so far. + for (var i = start; i < end; i++) { + facts &= ~(typeofNEFacts.get(witnesses[i]) || 0); + } + // Add inequalities for types before the active clause unconditionally. + for (var i = 0; i < start; i++) { + facts |= typeofNEFacts.get(witnesses[i]) || 32768 /* TypeofNEHostObject */; + } + } + // When in an active clause without default the set of + // equalities is finite. + else { + // Add equalities for all types in the active clause. + for (var i = start; i < end; i++) { + facts |= typeofEQFacts.get(witnesses[i]) || 128 /* TypeofEQHostObject */; + } + // Remove equalities for types that appear before the + // active clause. + for (var i = 0; i < start; i++) { + facts &= ~(typeofEQFacts.get(witnesses[i]) || 0); + } + } + return facts; + } + function isExhaustiveSwitchStatement(node) { + if (!node.possiblyExhaustive) { + return false; + } + if (node.expression.kind === 199 /* TypeOfExpression */) { + var operandType = getTypeOfExpression(node.expression.expression); + // This cast is safe because the switch is possibly exhaustive and does not contain a default case, so there can be no undefined. + var witnesses = getSwitchClauseTypeOfWitnesses(node); + // notEqualFacts states that the type of the switched value is not equal to every type in the switch. + var notEqualFacts_1 = getFactsFromTypeofSwitch(0, 0, witnesses, /*hasDefault*/ true); + var type_5 = getBaseConstraintOfType(operandType) || operandType; + return !!(filterType(type_5, function (t) { return (getTypeFacts(t) & notEqualFacts_1) === notEqualFacts_1; }).flags & 131072 /* Never */); + } + var type = getTypeOfExpression(node.expression); + if (!isLiteralType(type)) { + return false; + } + var switchTypes = getSwitchClauseTypes(node); + if (!switchTypes.length || ts.some(switchTypes, isNeitherUnitTypeNorNever)) { + return false; + } + return eachTypeContainedIn(mapType(type, getRegularTypeOfLiteralType), switchTypes); + } + function functionHasImplicitReturn(func) { + if (!(func.flags & 128 /* HasImplicitReturn */)) { + return false; + } + if (ts.some(func.body.statements, function (statement) { return statement.kind === 232 /* SwitchStatement */ && isExhaustiveSwitchStatement(statement); })) { + return false; + } + return true; + } + /** NOTE: Return value of `[]` means a different thing than `undefined`. `[]` means func returns `void`, `undefined` means it returns `never`. */ + function checkAndAggregateReturnExpressionTypes(func, checkMode) { + var functionFlags = ts.getFunctionFlags(func); + var aggregatedTypes = []; + var hasReturnWithNoExpression = functionHasImplicitReturn(func); + var hasReturnOfTypeNever = false; + ts.forEachReturnStatement(func.body, function (returnStatement) { + var expr = returnStatement.expression; + if (expr) { + var type = checkExpressionCached(expr, checkMode); + if (functionFlags & 2 /* Async */) { + // From within an async function you can return either a non-promise value or a promise. Any + // Promise/A+ compatible implementation will always assimilate any foreign promise, so the + // return type of the body should be unwrapped to its awaited type, which should be wrapped in + // the native Promise type by the caller. + type = checkAwaitedType(type, func, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); + } + if (type.flags & 131072 /* Never */) { + hasReturnOfTypeNever = true; + } + ts.pushIfUnique(aggregatedTypes, type); + } + else { + hasReturnWithNoExpression = true; + } + }); + if (aggregatedTypes.length === 0 && !hasReturnWithNoExpression && (hasReturnOfTypeNever || mayReturnNever(func))) { + return undefined; + } + if (strictNullChecks && aggregatedTypes.length && hasReturnWithNoExpression && + !(isJSConstructor(func) && aggregatedTypes.some(function (t) { return t.symbol === func.symbol; }))) { + // Javascript "callable constructors", containing eg `if (!(this instanceof A)) return new A()` should not add undefined + ts.pushIfUnique(aggregatedTypes, undefinedType); + } + return aggregatedTypes; + } + function mayReturnNever(func) { + switch (func.kind) { + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + return true; + case 156 /* MethodDeclaration */: + return func.parent.kind === 188 /* ObjectLiteralExpression */; + default: + return false; + } + } + /** + * TypeScript Specification 1.0 (6.3) - July 2014 + * An explicitly typed function whose return type isn't the Void type, + * the Any type, or a union type containing the Void or Any type as a constituent + * must have at least one return statement somewhere in its body. + * An exception to this rule is if the function implementation consists of a single 'throw' statement. + * + * @param returnType - return type of the function, can be undefined if return type is not explicitly specified + */ + function checkAllCodePathsInNonVoidFunctionReturnOrThrow(func, returnType) { + if (!produceDiagnostics) { + return; + } + // Functions with with an explicitly specified 'void' or 'any' return type don't need any return expressions. + if (returnType && maybeTypeOfKind(returnType, 1 /* Any */ | 16384 /* Void */)) { + return; + } + // If all we have is a function signature, or an arrow function with an expression body, then there is nothing to check. + // also if HasImplicitReturn flag is not set this means that all codepaths in function body end with return or throw + if (func.kind === 155 /* MethodSignature */ || ts.nodeIsMissing(func.body) || func.body.kind !== 218 /* Block */ || !functionHasImplicitReturn(func)) { + return; + } + var hasExplicitReturn = func.flags & 256 /* HasExplicitReturn */; + if (returnType && returnType.flags & 131072 /* Never */) { + error(ts.getEffectiveReturnTypeNode(func), ts.Diagnostics.A_function_returning_never_cannot_have_a_reachable_end_point); + } + else if (returnType && !hasExplicitReturn) { + // minimal check: function has syntactic return type annotation and no explicit return statements in the body + // this function does not conform to the specification. + // NOTE: having returnType !== undefined is a precondition for entering this branch so func.type will always be present + error(ts.getEffectiveReturnTypeNode(func), ts.Diagnostics.A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value); + } + else if (returnType && strictNullChecks && !isTypeAssignableTo(undefinedType, returnType)) { + error(ts.getEffectiveReturnTypeNode(func), ts.Diagnostics.Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined); + } + else if (compilerOptions.noImplicitReturns) { + if (!returnType) { + // If return type annotation is omitted check if function has any explicit return statements. + // If it does not have any - its inferred return type is void - don't do any checks. + // Otherwise get inferred return type from function body and report error only if it is not void / anytype + if (!hasExplicitReturn) { + return; + } + var inferredReturnType = getReturnTypeOfSignature(getSignatureFromDeclaration(func)); + if (isUnwrappedReturnTypeVoidOrAny(func, inferredReturnType)) { + return; + } + } + error(ts.getEffectiveReturnTypeNode(func) || func, ts.Diagnostics.Not_all_code_paths_return_a_value); + } + } + function checkFunctionExpressionOrObjectLiteralMethod(node, checkMode) { + ts.Debug.assert(node.kind !== 156 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + checkNodeDeferred(node); + // The identityMapper object is used to indicate that function expressions are wildcards + if (checkMode === 1 /* SkipContextSensitive */ && isContextSensitive(node)) { + // Skip parameters, return signature with return type that retains noncontextual parts so inferences can still be drawn in an early stage + if (!ts.getEffectiveReturnTypeNode(node) && hasContextSensitiveReturnExpression(node)) { + var links_1 = getNodeLinks(node); + if (links_1.contextFreeType) { + return links_1.contextFreeType; + } + var returnType = getReturnTypeFromBody(node, checkMode); + var returnOnlySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, returnType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + var returnOnlyType = createAnonymousType(node.symbol, emptySymbols, [returnOnlySignature], ts.emptyArray, undefined, undefined); + returnOnlyType.flags |= 536870912 /* ContainsAnyFunctionType */; + return links_1.contextFreeType = returnOnlyType; + } + return anyFunctionType; + } + // Grammar checking + var hasGrammarError = checkGrammarFunctionLikeDeclaration(node); + if (!hasGrammarError && node.kind === 196 /* FunctionExpression */) { + checkGrammarForGenerator(node); + } + var links = getNodeLinks(node); + var type = getTypeOfSymbol(getMergedSymbol(node.symbol)); + if (isTypeAny(type)) { + return type; + } + // Check if function expression is contextually typed and assign parameter types if so. + if (!(links.flags & 1024 /* ContextChecked */)) { + var contextualSignature = getContextualSignature(node); + // If a type check is started at a function expression that is an argument of a function call, obtaining the + // contextual type may recursively get back to here during overload resolution of the call. If so, we will have + // already assigned contextual types. + if (!(links.flags & 1024 /* ContextChecked */)) { + links.flags |= 1024 /* ContextChecked */; + if (contextualSignature) { + var signature = getSignaturesOfType(type, 0 /* Call */)[0]; + if (isContextSensitive(node)) { + var contextualMapper = getContextualMapper(node); + if (checkMode === 2 /* Inferential */) { + inferFromAnnotatedParameters(signature, contextualSignature, contextualMapper); + } + var instantiatedContextualSignature = contextualMapper === identityMapper ? + contextualSignature : instantiateSignature(contextualSignature, contextualMapper); + assignContextualParameterTypes(signature, instantiatedContextualSignature); + } + if (!getReturnTypeFromAnnotation(node) && !signature.resolvedReturnType) { + var returnType = getReturnTypeFromBody(node, checkMode); + if (!signature.resolvedReturnType) { + signature.resolvedReturnType = returnType; + } + } + } + checkSignatureDeclaration(node); + } + } + return type; + } + function getReturnOrPromisedType(node, functionFlags) { + var type = getReturnTypeFromAnnotation(node); + return type && ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */) ? + getAwaitedType(type) || errorType : type; + } + function checkFunctionExpressionOrObjectLiteralMethodDeferred(node) { + ts.Debug.assert(node.kind !== 156 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + var functionFlags = ts.getFunctionFlags(node); + var returnOrPromisedType = getReturnOrPromisedType(node, functionFlags); + if ((functionFlags & 1 /* Generator */) === 0) { // Async function or normal function + // return is not necessary in the body of generators + checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnOrPromisedType); + } + if (node.body) { + if (!ts.getEffectiveReturnTypeNode(node)) { + // There are some checks that are only performed in getReturnTypeFromBody, that may produce errors + // we need. An example is the noImplicitAny errors resulting from widening the return expression + // of a function. Because checking of function expression bodies is deferred, there was never an + // appropriate time to do this during the main walk of the file (see the comment at the top of + // checkFunctionExpressionBodies). So it must be done now. + getReturnTypeOfSignature(getSignatureFromDeclaration(node)); + } + if (node.body.kind === 218 /* Block */) { + checkSourceElement(node.body); + } + else { + // From within an async function you can return either a non-promise value or a promise. Any + // Promise/A+ compatible implementation will always assimilate any foreign promise, so we + // should not be checking assignability of a promise to the return type. Instead, we need to + // check assignability of the awaited type of the expression body against the promised type of + // its return type annotation. + var exprType = checkExpression(node.body); + if (returnOrPromisedType) { + if ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */) { // Async function + var awaitedType = checkAwaitedType(exprType, node.body, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); + checkTypeAssignableToAndOptionallyElaborate(awaitedType, returnOrPromisedType, node.body, node.body); + } + else { // Normal function + checkTypeAssignableToAndOptionallyElaborate(exprType, returnOrPromisedType, node.body, node.body); + } + } + } + } + } + function checkArithmeticOperandType(operand, type, diagnostic) { + if (!isTypeAssignableTo(type, numberOrBigIntType)) { + error(operand, diagnostic); + return false; + } + return true; + } + function isReadonlyAssignmentDeclaration(d) { + if (!ts.isCallExpression(d)) { + return false; + } + if (!ts.isBindableObjectDefinePropertyCall(d)) { + return false; + } + var objectLitType = checkExpressionCached(d.arguments[2]); + var valueType = getTypeOfPropertyOfType(objectLitType, "value"); + if (valueType) { + var writableProp = getPropertyOfType(objectLitType, "writable"); + var writableType = writableProp && getTypeOfSymbol(writableProp); + if (!writableType || writableType === falseType || writableType === regularFalseType) { + return true; + } + // We include this definition whereupon we walk back and check the type at the declaration because + // The usual definition of `Object.defineProperty` will _not_ cause literal types to be preserved in the + // argument types, should the type be contextualized by the call itself. + if (writableProp && writableProp.valueDeclaration && ts.isPropertyAssignment(writableProp.valueDeclaration)) { + var initializer = writableProp.valueDeclaration.initializer; + var rawOriginalType = checkExpression(initializer); + if (rawOriginalType === falseType || rawOriginalType === regularFalseType) { + return true; + } + } + return false; + } + var setProp = getPropertyOfType(objectLitType, "set"); + return !setProp; + } + function isReadonlySymbol(symbol) { + // The following symbols are considered read-only: + // Properties with a 'readonly' modifier + // Variables declared with 'const' + // Get accessors without matching set accessors + // Enum members + // Object.defineProperty assignments with writable false or no setter + // Unions and intersections of the above (unions and intersections eagerly set isReadonly on creation) + return !!(ts.getCheckFlags(symbol) & 8 /* Readonly */ || + symbol.flags & 4 /* Property */ && ts.getDeclarationModifierFlagsFromSymbol(symbol) & 64 /* Readonly */ || + symbol.flags & 3 /* Variable */ && getDeclarationNodeFlagsFromSymbol(symbol) & 2 /* Const */ || + symbol.flags & 98304 /* Accessor */ && !(symbol.flags & 65536 /* SetAccessor */) || + symbol.flags & 8 /* EnumMember */ || + ts.some(symbol.declarations, isReadonlyAssignmentDeclaration)); + } + function isReferenceToReadonlyEntity(expr, symbol) { + if (isReadonlySymbol(symbol)) { + // Allow assignments to readonly properties within constructors of the same class declaration. + if (symbol.flags & 4 /* Property */ && + (expr.kind === 189 /* PropertyAccessExpression */ || expr.kind === 190 /* ElementAccessExpression */) && + expr.expression.kind === 100 /* ThisKeyword */) { + // Look for if this is the constructor for the class that `symbol` is a property of. + var func = ts.getContainingFunction(expr); + if (!(func && func.kind === 157 /* Constructor */)) { + return true; + } + // If func.parent is a class and symbol is a (readonly) property of that class, or + // if func is a constructor and symbol is a (readonly) parameter property declared in it, + // then symbol is writeable here. + return !symbol.valueDeclaration || !(func.parent === symbol.valueDeclaration.parent || func === symbol.valueDeclaration.parent); + } + return true; + } + return false; + } + function isReferenceThroughNamespaceImport(expr) { + if (expr.kind === 189 /* PropertyAccessExpression */ || expr.kind === 190 /* ElementAccessExpression */) { + var node = ts.skipParentheses(expr.expression); + if (node.kind === 72 /* Identifier */) { + var symbol = getNodeLinks(node).resolvedSymbol; + if (symbol.flags & 2097152 /* Alias */) { + var declaration = getDeclarationOfAliasSymbol(symbol); + return !!declaration && declaration.kind === 251 /* NamespaceImport */; + } + } + } + return false; + } + function checkReferenceExpression(expr, invalidReferenceMessage) { + // References are combinations of identifiers, parentheses, and property accesses. + var node = ts.skipOuterExpressions(expr, 2 /* Assertions */ | 1 /* Parentheses */); + if (node.kind !== 72 /* Identifier */ && node.kind !== 189 /* PropertyAccessExpression */ && node.kind !== 190 /* ElementAccessExpression */) { + error(expr, invalidReferenceMessage); + return false; + } + return true; + } + function checkDeleteExpression(node) { + checkExpression(node.expression); + var expr = ts.skipParentheses(node.expression); + if (expr.kind !== 189 /* PropertyAccessExpression */ && expr.kind !== 190 /* ElementAccessExpression */) { + error(expr, ts.Diagnostics.The_operand_of_a_delete_operator_must_be_a_property_reference); + return booleanType; + } + var links = getNodeLinks(expr); + var symbol = getExportSymbolOfValueSymbolIfExported(links.resolvedSymbol); + if (symbol && isReadonlySymbol(symbol)) { + error(expr, ts.Diagnostics.The_operand_of_a_delete_operator_cannot_be_a_read_only_property); + } + return booleanType; + } + function checkTypeOfExpression(node) { + checkExpression(node.expression); + return typeofType; + } + function checkVoidExpression(node) { + checkExpression(node.expression); + return undefinedWideningType; + } + function checkAwaitExpression(node) { + // Grammar checking + if (produceDiagnostics) { + if (!(node.flags & 16384 /* AwaitContext */)) { + grammarErrorOnFirstToken(node, ts.Diagnostics.await_expression_is_only_allowed_within_an_async_function); + } + if (isInParameterInitializerBeforeContainingFunction(node)) { + error(node, ts.Diagnostics.await_expressions_cannot_be_used_in_a_parameter_initializer); + } + } + var operandType = checkExpression(node.expression); + return checkAwaitedType(operandType, node, ts.Diagnostics.Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); + } + function checkPrefixUnaryExpression(node) { + var operandType = checkExpression(node.operand); + if (operandType === silentNeverType) { + return silentNeverType; + } + switch (node.operand.kind) { + case 8 /* NumericLiteral */: + switch (node.operator) { + case 39 /* MinusToken */: + return getFreshTypeOfLiteralType(getLiteralType(-node.operand.text)); + case 38 /* PlusToken */: + return getFreshTypeOfLiteralType(getLiteralType(+node.operand.text)); + } + break; + case 9 /* BigIntLiteral */: + if (node.operator === 39 /* MinusToken */) { + return getFreshTypeOfLiteralType(getLiteralType({ + negative: true, + base10Value: ts.parsePseudoBigInt(node.operand.text) + })); + } + } + switch (node.operator) { + case 38 /* PlusToken */: + case 39 /* MinusToken */: + case 53 /* TildeToken */: + checkNonNullType(operandType, node.operand); + if (maybeTypeOfKind(operandType, 12288 /* ESSymbolLike */)) { + error(node.operand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(node.operator)); + } + if (node.operator === 38 /* PlusToken */) { + if (maybeTypeOfKind(operandType, 2112 /* BigIntLike */)) { + error(node.operand, ts.Diagnostics.Operator_0_cannot_be_applied_to_type_1, ts.tokenToString(node.operator), typeToString(operandType)); + } + return numberType; + } + return getUnaryResultType(operandType); + case 52 /* ExclamationToken */: + checkTruthinessExpression(node.operand); + var facts = getTypeFacts(operandType) & (4194304 /* Truthy */ | 8388608 /* Falsy */); + return facts === 4194304 /* Truthy */ ? falseType : + facts === 8388608 /* Falsy */ ? trueType : + booleanType; + case 44 /* PlusPlusToken */: + case 45 /* MinusMinusToken */: + var ok = checkArithmeticOperandType(node.operand, checkNonNullType(operandType, node.operand), ts.Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_bigint_or_an_enum_type); + if (ok) { + // run check only if former checks succeeded to avoid reporting cascading errors + checkReferenceExpression(node.operand, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access); + } + return getUnaryResultType(operandType); + } + return errorType; + } + function checkPostfixUnaryExpression(node) { + var operandType = checkExpression(node.operand); + if (operandType === silentNeverType) { + return silentNeverType; + } + var ok = checkArithmeticOperandType(node.operand, checkNonNullType(operandType, node.operand), ts.Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_bigint_or_an_enum_type); + if (ok) { + // run check only if former checks succeeded to avoid reporting cascading errors + checkReferenceExpression(node.operand, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access); + } + return getUnaryResultType(operandType); + } + function getUnaryResultType(operandType) { + if (maybeTypeOfKind(operandType, 2112 /* BigIntLike */)) { + return isTypeAssignableToKind(operandType, 3 /* AnyOrUnknown */) || maybeTypeOfKind(operandType, 296 /* NumberLike */) + ? numberOrBigIntType + : bigintType; + } + // If it's not a bigint type, implicit coercion will result in a number + return numberType; + } + // Return true if type might be of the given kind. A union or intersection type might be of a given + // kind if at least one constituent type is of the given kind. + function maybeTypeOfKind(type, kind) { + if (type.flags & kind & ~134217728 /* GenericMappedType */ || kind & 134217728 /* GenericMappedType */ && isGenericMappedType(type)) { + return true; + } + if (type.flags & 3145728 /* UnionOrIntersection */) { + var types = type.types; + for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { + var t = types_15[_i]; + if (maybeTypeOfKind(t, kind)) { + return true; + } + } + } + return false; + } + function isTypeAssignableToKind(source, kind, strict) { + if (source.flags & kind) { + return true; + } + if (strict && source.flags & (3 /* AnyOrUnknown */ | 16384 /* Void */ | 32768 /* Undefined */ | 65536 /* Null */)) { + return false; + } + return !!(kind & 296 /* NumberLike */) && isTypeAssignableTo(source, numberType) || + !!(kind & 2112 /* BigIntLike */) && isTypeAssignableTo(source, bigintType) || + !!(kind & 132 /* StringLike */) && isTypeAssignableTo(source, stringType) || + !!(kind & 528 /* BooleanLike */) && isTypeAssignableTo(source, booleanType) || + !!(kind & 16384 /* Void */) && isTypeAssignableTo(source, voidType) || + !!(kind & 131072 /* Never */) && isTypeAssignableTo(source, neverType) || + !!(kind & 65536 /* Null */) && isTypeAssignableTo(source, nullType) || + !!(kind & 32768 /* Undefined */) && isTypeAssignableTo(source, undefinedType) || + !!(kind & 4096 /* ESSymbol */) && isTypeAssignableTo(source, esSymbolType) || + !!(kind & 67108864 /* NonPrimitive */) && isTypeAssignableTo(source, nonPrimitiveType); + } + function allTypesAssignableToKind(source, kind, strict) { + return source.flags & 1048576 /* Union */ ? + ts.every(source.types, function (subType) { return allTypesAssignableToKind(subType, kind, strict); }) : + isTypeAssignableToKind(source, kind, strict); + } + function isConstEnumObjectType(type) { + return !!(ts.getObjectFlags(type) & 16 /* Anonymous */) && !!type.symbol && isConstEnumSymbol(type.symbol); + } + function isConstEnumSymbol(symbol) { + return (symbol.flags & 128 /* ConstEnum */) !== 0; + } + function checkInstanceOfExpression(left, right, leftType, rightType) { + if (leftType === silentNeverType || rightType === silentNeverType) { + return silentNeverType; + } + // TypeScript 1.0 spec (April 2014): 4.15.4 + // The instanceof operator requires the left operand to be of type Any, an object type, or a type parameter type, + // and the right operand to be of type Any, a subtype of the 'Function' interface type, or have a call or construct signature. + // The result is always of the Boolean primitive type. + // NOTE: do not raise error if leftType is unknown as related error was already reported + if (!isTypeAny(leftType) && + allTypesAssignableToKind(leftType, 131068 /* Primitive */)) { + error(left, ts.Diagnostics.The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter); + } + // NOTE: do not raise error if right is unknown as related error was already reported + if (!(isTypeAny(rightType) || typeHasCallOrConstructSignatures(rightType) || isTypeSubtypeOf(rightType, globalFunctionType))) { + error(right, ts.Diagnostics.The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_Function_interface_type); + } + return booleanType; + } + function checkInExpression(left, right, leftType, rightType) { + if (leftType === silentNeverType || rightType === silentNeverType) { + return silentNeverType; + } + leftType = checkNonNullType(leftType, left); + rightType = checkNonNullType(rightType, right); + // TypeScript 1.0 spec (April 2014): 4.15.5 + // The in operator requires the left operand to be of type Any, the String primitive type, or the Number primitive type, + // and the right operand to be of type Any, an object type, or a type parameter type. + // The result is always of the Boolean primitive type. + if (!(isTypeComparableTo(leftType, stringType) || isTypeAssignableToKind(leftType, 296 /* NumberLike */ | 12288 /* ESSymbolLike */))) { + error(left, ts.Diagnostics.The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol); + } + if (!isTypeAssignableToKind(rightType, 67108864 /* NonPrimitive */ | 58982400 /* InstantiableNonPrimitive */)) { + error(right, ts.Diagnostics.The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter); + } + return booleanType; + } + function checkObjectLiteralAssignment(node, sourceType, rightIsThis) { + var properties = node.properties; + if (strictNullChecks && properties.length === 0) { + return checkNonNullType(sourceType, node); + } + for (var _i = 0, properties_6 = properties; _i < properties_6.length; _i++) { + var p = properties_6[_i]; + checkObjectLiteralDestructuringPropertyAssignment(sourceType, p, properties, rightIsThis); + } + return sourceType; + } + /** Note: If property cannot be a SpreadAssignment, then allProperties does not need to be provided */ + function checkObjectLiteralDestructuringPropertyAssignment(objectLiteralType, property, allProperties, rightIsThis) { + if (rightIsThis === void 0) { rightIsThis = false; } + if (property.kind === 275 /* PropertyAssignment */ || property.kind === 276 /* ShorthandPropertyAssignment */) { + var name = property.name; + if (name.kind === 149 /* ComputedPropertyName */) { + checkComputedPropertyName(name); + } + if (isComputedNonLiteralName(name)) { + return undefined; + } + var type = getTypeOfObjectLiteralDestructuringProperty(objectLiteralType, name, property, rightIsThis); + if (type) { + // non-shorthand property assignments should always have initializers + return checkDestructuringAssignment(property.kind === 276 /* ShorthandPropertyAssignment */ ? property : property.initializer, type); + } + else { + error(name, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(objectLiteralType), ts.declarationNameToString(name)); + } + } + else if (property.kind === 277 /* SpreadAssignment */) { + if (languageVersion < 6 /* ESNext */) { + checkExternalEmitHelpers(property, 4 /* Rest */); + } + var nonRestNames = []; + if (allProperties) { + for (var i = 0; i < allProperties.length - 1; i++) { + nonRestNames.push(allProperties[i].name); + } + } + var type = getRestType(objectLiteralType, nonRestNames, objectLiteralType.symbol); + checkGrammarForDisallowedTrailingComma(allProperties, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma); + return checkDestructuringAssignment(property.expression, type); + } + else { + error(property, ts.Diagnostics.Property_assignment_expected); + } + } + function getTypeOfObjectLiteralDestructuringProperty(objectLiteralType, name, property, rightIsThis) { + if (isTypeAny(objectLiteralType)) { + return objectLiteralType; + } + var type; + var text = ts.getTextOfPropertyName(name); + if (text) { // TODO: GH#26379 + var prop = getPropertyOfType(objectLiteralType, text); + if (prop) { + markPropertyAsReferenced(prop, property, rightIsThis); + checkPropertyAccessibility(property, /*isSuper*/ false, objectLiteralType, prop); + type = getTypeOfSymbol(prop); + } + type = type || (isNumericLiteralName(text) ? getIndexTypeOfType(objectLiteralType, 1 /* Number */) : undefined); + } + return type || getIndexTypeOfType(objectLiteralType, 0 /* String */); + } + function checkArrayLiteralAssignment(node, sourceType, checkMode) { + var elements = node.elements; + if (languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) { + checkExternalEmitHelpers(node, 512 /* Read */); + } + // This elementType will be used if the specific property corresponding to this index is not + // present (aka the tuple element property). This call also checks that the parentType is in + // fact an iterable or array (depending on target language). + var elementType = checkIteratedTypeOrElementType(sourceType, node, /*allowStringInput*/ false, /*allowAsyncIterables*/ false) || errorType; + for (var i = 0; i < elements.length; i++) { + checkArrayLiteralDestructuringElementAssignment(node, sourceType, i, elementType, checkMode); + } + return sourceType; + } + function checkArrayLiteralDestructuringElementAssignment(node, sourceType, elementIndex, elementType, checkMode) { + var elements = node.elements; + var element = elements[elementIndex]; + if (element.kind !== 210 /* OmittedExpression */) { + if (element.kind !== 208 /* SpreadElement */) { + var propName = "" + elementIndex; + var type = isTypeAny(sourceType) ? sourceType : + everyType(sourceType, isTupleLikeType) ? getTupleElementType(sourceType, elementIndex) : + elementType; + if (type) { + return checkDestructuringAssignment(element, type, checkMode); + } + // We still need to check element expression here because we may need to set appropriate flag on the expression + // such as NodeCheckFlags.LexicalThis on "this"expression. + checkExpression(element); + if (isTupleType(sourceType)) { + error(element, ts.Diagnostics.Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2, typeToString(sourceType), getTypeReferenceArity(sourceType), elements.length); + } + else { + error(element, ts.Diagnostics.Type_0_has_no_property_1, typeToString(sourceType), propName); + } + } + else { + if (elementIndex < elements.length - 1) { + error(element, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern); + } + else { + var restExpression = element.expression; + if (restExpression.kind === 204 /* BinaryExpression */ && restExpression.operatorToken.kind === 59 /* EqualsToken */) { + error(restExpression.operatorToken, ts.Diagnostics.A_rest_element_cannot_have_an_initializer); + } + else { + checkGrammarForDisallowedTrailingComma(node.elements, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma); + var type = everyType(sourceType, isTupleType) ? + mapType(sourceType, function (t) { return sliceTupleType(t, elementIndex); }) : + createArrayType(elementType); + return checkDestructuringAssignment(restExpression, type, checkMode); + } + } + } + } + return undefined; + } + function checkDestructuringAssignment(exprOrAssignment, sourceType, checkMode, rightIsThis) { + var target; + if (exprOrAssignment.kind === 276 /* ShorthandPropertyAssignment */) { + var prop = exprOrAssignment; + if (prop.objectAssignmentInitializer) { + // In strict null checking mode, if a default value of a non-undefined type is specified, remove + // undefined from the final type. + if (strictNullChecks && + !(getFalsyFlags(checkExpression(prop.objectAssignmentInitializer)) & 32768 /* Undefined */)) { + sourceType = getTypeWithFacts(sourceType, 524288 /* NEUndefined */); + } + checkBinaryLikeExpression(prop.name, prop.equalsToken, prop.objectAssignmentInitializer, checkMode); + } + target = exprOrAssignment.name; + } + else { + target = exprOrAssignment; + } + if (target.kind === 204 /* BinaryExpression */ && target.operatorToken.kind === 59 /* EqualsToken */) { + checkBinaryExpression(target, checkMode); + target = target.left; + } + if (target.kind === 188 /* ObjectLiteralExpression */) { + return checkObjectLiteralAssignment(target, sourceType, rightIsThis); + } + if (target.kind === 187 /* ArrayLiteralExpression */) { + return checkArrayLiteralAssignment(target, sourceType, checkMode); + } + return checkReferenceAssignment(target, sourceType, checkMode); + } + function checkReferenceAssignment(target, sourceType, checkMode) { + var targetType = checkExpression(target, checkMode); + var error = target.parent.kind === 277 /* SpreadAssignment */ ? + ts.Diagnostics.The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access : + ts.Diagnostics.The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access; + if (checkReferenceExpression(target, error)) { + checkTypeAssignableToAndOptionallyElaborate(sourceType, targetType, target, target); + } + return sourceType; + } + /** + * This is a *shallow* check: An expression is side-effect-free if the + * evaluation of the expression *itself* cannot produce side effects. + * For example, x++ / 3 is side-effect free because the / operator + * does not have side effects. + * The intent is to "smell test" an expression for correctness in positions where + * its value is discarded (e.g. the left side of the comma operator). + */ + function isSideEffectFree(node) { + node = ts.skipParentheses(node); + switch (node.kind) { + case 72 /* Identifier */: + case 10 /* StringLiteral */: + case 13 /* RegularExpressionLiteral */: + case 193 /* TaggedTemplateExpression */: + case 206 /* TemplateExpression */: + case 14 /* NoSubstitutionTemplateLiteral */: + case 8 /* NumericLiteral */: + case 9 /* BigIntLiteral */: + case 102 /* TrueKeyword */: + case 87 /* FalseKeyword */: + case 96 /* NullKeyword */: + case 141 /* UndefinedKeyword */: + case 196 /* FunctionExpression */: + case 209 /* ClassExpression */: + case 197 /* ArrowFunction */: + case 187 /* ArrayLiteralExpression */: + case 188 /* ObjectLiteralExpression */: + case 199 /* TypeOfExpression */: + case 213 /* NonNullExpression */: + case 261 /* JsxSelfClosingElement */: + case 260 /* JsxElement */: + return true; + case 205 /* ConditionalExpression */: + return isSideEffectFree(node.whenTrue) && + isSideEffectFree(node.whenFalse); + case 204 /* BinaryExpression */: + if (ts.isAssignmentOperator(node.operatorToken.kind)) { + return false; + } + return isSideEffectFree(node.left) && + isSideEffectFree(node.right); + case 202 /* PrefixUnaryExpression */: + case 203 /* PostfixUnaryExpression */: + // Unary operators ~, !, +, and - have no side effects. + // The rest do. + switch (node.operator) { + case 52 /* ExclamationToken */: + case 38 /* PlusToken */: + case 39 /* MinusToken */: + case 53 /* TildeToken */: + return true; + } + return false; + // Some forms listed here for clarity + case 200 /* VoidExpression */: // Explicit opt-out + case 194 /* TypeAssertionExpression */: // Not SEF, but can produce useful type warnings + case 212 /* AsExpression */: // Not SEF, but can produce useful type warnings + default: + return false; + } + } + function isTypeEqualityComparableTo(source, target) { + return (target.flags & 98304 /* Nullable */) !== 0 || isTypeComparableTo(source, target); + } + function checkBinaryExpression(node, checkMode) { + if (ts.isInJSFile(node) && ts.getAssignedExpandoInitializer(node)) { + return checkExpression(node.right, checkMode); + } + return checkBinaryLikeExpression(node.left, node.operatorToken, node.right, checkMode, node); + } + function checkBinaryLikeExpression(left, operatorToken, right, checkMode, errorNode) { + var operator = operatorToken.kind; + if (operator === 59 /* EqualsToken */ && (left.kind === 188 /* ObjectLiteralExpression */ || left.kind === 187 /* ArrayLiteralExpression */)) { + return checkDestructuringAssignment(left, checkExpression(right, checkMode), checkMode, right.kind === 100 /* ThisKeyword */); + } + var leftType; + if (operator === 54 /* AmpersandAmpersandToken */ || operator === 55 /* BarBarToken */) { + leftType = checkTruthinessExpression(left, checkMode); + } + else { + leftType = checkExpression(left, checkMode); + } + var rightType = checkExpression(right, checkMode); + switch (operator) { + case 40 /* AsteriskToken */: + case 41 /* AsteriskAsteriskToken */: + case 62 /* AsteriskEqualsToken */: + case 63 /* AsteriskAsteriskEqualsToken */: + case 42 /* SlashToken */: + case 64 /* SlashEqualsToken */: + case 43 /* PercentToken */: + case 65 /* PercentEqualsToken */: + case 39 /* MinusToken */: + case 61 /* MinusEqualsToken */: + case 46 /* LessThanLessThanToken */: + case 66 /* LessThanLessThanEqualsToken */: + case 47 /* GreaterThanGreaterThanToken */: + case 67 /* GreaterThanGreaterThanEqualsToken */: + case 48 /* GreaterThanGreaterThanGreaterThanToken */: + case 68 /* GreaterThanGreaterThanGreaterThanEqualsToken */: + case 50 /* BarToken */: + case 70 /* BarEqualsToken */: + case 51 /* CaretToken */: + case 71 /* CaretEqualsToken */: + case 49 /* AmpersandToken */: + case 69 /* AmpersandEqualsToken */: + if (leftType === silentNeverType || rightType === silentNeverType) { + return silentNeverType; + } + leftType = checkNonNullType(leftType, left); + rightType = checkNonNullType(rightType, right); + var suggestedOperator = void 0; + // if a user tries to apply a bitwise operator to 2 boolean operands + // try and return them a helpful suggestion + if ((leftType.flags & 528 /* BooleanLike */) && + (rightType.flags & 528 /* BooleanLike */) && + (suggestedOperator = getSuggestedBooleanOperator(operatorToken.kind)) !== undefined) { + error(errorNode || operatorToken, ts.Diagnostics.The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead, ts.tokenToString(operatorToken.kind), ts.tokenToString(suggestedOperator)); + return numberType; + } + else { + // otherwise just check each operand separately and report errors as normal + var leftOk = checkArithmeticOperandType(left, leftType, ts.Diagnostics.The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type); + var rightOk = checkArithmeticOperandType(right, rightType, ts.Diagnostics.The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type); + var resultType_1; + // If both are any or unknown, allow operation; assume it will resolve to number + if ((isTypeAssignableToKind(leftType, 3 /* AnyOrUnknown */) && isTypeAssignableToKind(rightType, 3 /* AnyOrUnknown */)) || + // Or, if neither could be bigint, implicit coercion results in a number result + !(maybeTypeOfKind(leftType, 2112 /* BigIntLike */) || maybeTypeOfKind(rightType, 2112 /* BigIntLike */))) { + resultType_1 = numberType; + } + // At least one is assignable to bigint, so both should be only assignable to bigint + else if (isTypeAssignableToKind(leftType, 2112 /* BigIntLike */) && isTypeAssignableToKind(rightType, 2112 /* BigIntLike */)) { + switch (operator) { + case 48 /* GreaterThanGreaterThanGreaterThanToken */: + case 68 /* GreaterThanGreaterThanGreaterThanEqualsToken */: + reportOperatorError(); + } + resultType_1 = bigintType; + } + else { + reportOperatorError(); + resultType_1 = errorType; + } + if (leftOk && rightOk) { + checkAssignmentOperator(resultType_1); + } + return resultType_1; + } + case 38 /* PlusToken */: + case 60 /* PlusEqualsToken */: + if (leftType === silentNeverType || rightType === silentNeverType) { + return silentNeverType; + } + if (!isTypeAssignableToKind(leftType, 132 /* StringLike */) && !isTypeAssignableToKind(rightType, 132 /* StringLike */)) { + leftType = checkNonNullType(leftType, left); + rightType = checkNonNullType(rightType, right); + } + var resultType = void 0; + if (isTypeAssignableToKind(leftType, 296 /* NumberLike */, /*strict*/ true) && isTypeAssignableToKind(rightType, 296 /* NumberLike */, /*strict*/ true)) { + // Operands of an enum type are treated as having the primitive type Number. + // If both operands are of the Number primitive type, the result is of the Number primitive type. + resultType = numberType; + } + else if (isTypeAssignableToKind(leftType, 2112 /* BigIntLike */, /*strict*/ true) && isTypeAssignableToKind(rightType, 2112 /* BigIntLike */, /*strict*/ true)) { + // If both operands are of the BigInt primitive type, the result is of the BigInt primitive type. + resultType = bigintType; + } + else if (isTypeAssignableToKind(leftType, 132 /* StringLike */, /*strict*/ true) || isTypeAssignableToKind(rightType, 132 /* StringLike */, /*strict*/ true)) { + // If one or both operands are of the String primitive type, the result is of the String primitive type. + resultType = stringType; + } + else if (isTypeAny(leftType) || isTypeAny(rightType)) { + // Otherwise, the result is of type Any. + // NOTE: unknown type here denotes error type. Old compiler treated this case as any type so do we. + resultType = leftType === errorType || rightType === errorType ? errorType : anyType; + } + // Symbols are not allowed at all in arithmetic expressions + if (resultType && !checkForDisallowedESSymbolOperand(operator)) { + return resultType; + } + if (!resultType) { + reportOperatorError(); + return anyType; + } + if (operator === 60 /* PlusEqualsToken */) { + checkAssignmentOperator(resultType); + } + return resultType; + case 28 /* LessThanToken */: + case 30 /* GreaterThanToken */: + case 31 /* LessThanEqualsToken */: + case 32 /* GreaterThanEqualsToken */: + if (checkForDisallowedESSymbolOperand(operator)) { + leftType = getBaseTypeOfLiteralType(checkNonNullType(leftType, left)); + rightType = getBaseTypeOfLiteralType(checkNonNullType(rightType, right)); + if (!(isTypeComparableTo(leftType, rightType) || isTypeComparableTo(rightType, leftType) || + (isTypeAssignableTo(leftType, numberOrBigIntType) && isTypeAssignableTo(rightType, numberOrBigIntType)))) { + reportOperatorError(); + } + } + return booleanType; + case 33 /* EqualsEqualsToken */: + case 34 /* ExclamationEqualsToken */: + case 35 /* EqualsEqualsEqualsToken */: + case 36 /* ExclamationEqualsEqualsToken */: + var leftIsLiteral = isLiteralType(leftType); + var rightIsLiteral = isLiteralType(rightType); + if (!leftIsLiteral || !rightIsLiteral) { + leftType = leftIsLiteral ? getBaseTypeOfLiteralType(leftType) : leftType; + rightType = rightIsLiteral ? getBaseTypeOfLiteralType(rightType) : rightType; + } + if (!isTypeEqualityComparableTo(leftType, rightType) && !isTypeEqualityComparableTo(rightType, leftType)) { + reportOperatorError(); + } + return booleanType; + case 94 /* InstanceOfKeyword */: + return checkInstanceOfExpression(left, right, leftType, rightType); + case 93 /* InKeyword */: + return checkInExpression(left, right, leftType, rightType); + case 54 /* AmpersandAmpersandToken */: + return getTypeFacts(leftType) & 4194304 /* Truthy */ ? + getUnionType([extractDefinitelyFalsyTypes(strictNullChecks ? leftType : getBaseTypeOfLiteralType(rightType)), rightType]) : + leftType; + case 55 /* BarBarToken */: + return getTypeFacts(leftType) & 8388608 /* Falsy */ ? + getUnionType([removeDefinitelyFalsyTypes(leftType), rightType], 2 /* Subtype */) : + leftType; + case 59 /* EqualsToken */: + var declKind = ts.isBinaryExpression(left.parent) ? ts.getAssignmentDeclarationKind(left.parent) : 0 /* None */; + checkAssignmentDeclaration(declKind, rightType); + if (isAssignmentDeclaration(declKind)) { + if (!(rightType.flags & 524288 /* Object */) || + declKind !== 2 /* ModuleExports */ && + declKind !== 6 /* Prototype */ && + !isEmptyObjectType(rightType) && + !isFunctionObjectType(rightType) && + !(ts.getObjectFlags(rightType) & 1 /* Class */)) { + // don't check assignability of module.exports=, C.prototype=, or expando types because they will necessarily be incomplete + checkAssignmentOperator(rightType); + } + return leftType; + } + else { + checkAssignmentOperator(rightType); + return getRegularTypeOfObjectLiteral(rightType); + } + case 27 /* CommaToken */: + if (!compilerOptions.allowUnreachableCode && isSideEffectFree(left) && !isEvalNode(right)) { + error(left, ts.Diagnostics.Left_side_of_comma_operator_is_unused_and_has_no_side_effects); + } + return rightType; + default: + return ts.Debug.fail(); + } + function checkAssignmentDeclaration(kind, rightType) { + if (kind === 2 /* ModuleExports */) { + for (var _i = 0, _a = getPropertiesOfObjectType(rightType); _i < _a.length; _i++) { + var prop = _a[_i]; + var propType = getTypeOfSymbol(prop); + if (propType.symbol && propType.symbol.flags & 32 /* Class */) { + var name = prop.escapedName; + var symbol = resolveName(prop.valueDeclaration, name, 67897832 /* Type */, undefined, name, /*isUse*/ false); + if (symbol && symbol.declarations.some(ts.isJSDocTypedefTag)) { + grammarErrorOnNode(symbol.declarations[0], ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name)); + return grammarErrorOnNode(prop.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name)); + } + } + } + } + } + function isEvalNode(node) { + return node.kind === 72 /* Identifier */ && node.escapedText === "eval"; + } + // Return true if there was no error, false if there was an error. + function checkForDisallowedESSymbolOperand(operator) { + var offendingSymbolOperand = maybeTypeOfKind(leftType, 12288 /* ESSymbolLike */) ? left : + maybeTypeOfKind(rightType, 12288 /* ESSymbolLike */) ? right : + undefined; + if (offendingSymbolOperand) { + error(offendingSymbolOperand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(operator)); + return false; + } + return true; + } + function getSuggestedBooleanOperator(operator) { + switch (operator) { + case 50 /* BarToken */: + case 70 /* BarEqualsToken */: + return 55 /* BarBarToken */; + case 51 /* CaretToken */: + case 71 /* CaretEqualsToken */: + return 36 /* ExclamationEqualsEqualsToken */; + case 49 /* AmpersandToken */: + case 69 /* AmpersandEqualsToken */: + return 54 /* AmpersandAmpersandToken */; + default: + return undefined; + } + } + function checkAssignmentOperator(valueType) { + if (produceDiagnostics && ts.isAssignmentOperator(operator)) { + // TypeScript 1.0 spec (April 2014): 4.17 + // An assignment of the form + // VarExpr = ValueExpr + // requires VarExpr to be classified as a reference + // A compound assignment furthermore requires VarExpr to be classified as a reference (section 4.1) + // and the type of the non-compound operation to be assignable to the type of VarExpr. + if (checkReferenceExpression(left, ts.Diagnostics.The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access) + && (!ts.isIdentifier(left) || ts.unescapeLeadingUnderscores(left.escapedText) !== "exports")) { + // to avoid cascading errors check assignability only if 'isReference' check succeeded and no errors were reported + checkTypeAssignableToAndOptionallyElaborate(valueType, leftType, left, right); + } + } + } + function isAssignmentDeclaration(kind) { + switch (kind) { + case 2 /* ModuleExports */: + return true; + case 1 /* ExportsProperty */: + case 5 /* Property */: + case 6 /* Prototype */: + case 3 /* PrototypeProperty */: + case 4 /* ThisProperty */: + var symbol = getSymbolOfNode(left); + var init = ts.getAssignedExpandoInitializer(right); + return init && ts.isObjectLiteralExpression(init) && + symbol && ts.hasEntries(symbol.exports); + default: + return false; + } + } + function reportOperatorError() { + var leftStr = typeToString(leftType); + var rightStr = typeToString(rightType); + var errNode = errorNode || operatorToken; + if (!tryGiveBetterPrimaryError(errNode, leftStr, rightStr)) { + error(errNode, ts.Diagnostics.Operator_0_cannot_be_applied_to_types_1_and_2, ts.tokenToString(operatorToken.kind), leftStr, rightStr); + } + } + function tryGiveBetterPrimaryError(errNode, leftStr, rightStr) { + switch (operatorToken.kind) { + case 35 /* EqualsEqualsEqualsToken */: + case 33 /* EqualsEqualsToken */: + return error(errNode, ts.Diagnostics.This_condition_will_always_return_0_since_the_types_1_and_2_have_no_overlap, "false", leftStr, rightStr); + case 36 /* ExclamationEqualsEqualsToken */: + case 34 /* ExclamationEqualsToken */: + return error(errNode, ts.Diagnostics.This_condition_will_always_return_0_since_the_types_1_and_2_have_no_overlap, "true", leftStr, rightStr); + } + return undefined; + } + } + function isYieldExpressionInClass(node) { + var current = node; + var parent = node.parent; + while (parent) { + if (ts.isFunctionLike(parent) && current === parent.body) { + return false; + } + else if (ts.isClassLike(current)) { + return true; + } + current = parent; + parent = parent.parent; + } + return false; + } + function checkYieldExpression(node) { + // Grammar checking + if (produceDiagnostics) { + if (!(node.flags & 4096 /* YieldContext */) || isYieldExpressionInClass(node)) { + grammarErrorOnFirstToken(node, ts.Diagnostics.A_yield_expression_is_only_allowed_in_a_generator_body); + } + if (isInParameterInitializerBeforeContainingFunction(node)) { + error(node, ts.Diagnostics.yield_expressions_cannot_be_used_in_a_parameter_initializer); + } + } + var func = ts.getContainingFunction(node); + if (!func) + return anyType; + var functionFlags = ts.getFunctionFlags(func); + if (!(functionFlags & 1 /* Generator */)) { + // If the user's code is syntactically correct, the func should always have a star. After all, we are in a yield context. + return anyType; + } + if (node.asteriskToken) { + // Async generator functions prior to ESNext require the __await, __asyncDelegator, + // and __asyncValues helpers + if ((functionFlags & 3 /* AsyncGenerator */) === 3 /* AsyncGenerator */ && + languageVersion < 6 /* ESNext */) { + checkExternalEmitHelpers(node, 26624 /* AsyncDelegatorIncludes */); + } + // Generator functions prior to ES2015 require the __values helper + if ((functionFlags & 3 /* AsyncGenerator */) === 1 /* Generator */ && + languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) { + checkExternalEmitHelpers(node, 256 /* Values */); + } + } + var isAsync = (functionFlags & 2 /* Async */) !== 0; + var yieldedType = getYieldedTypeOfYieldExpression(node, isAsync); // TODO: GH#18217 + // There is no point in doing an assignability check if the function + // has no explicit return type because the return type is directly computed + // from the yield expressions. + var returnType = getReturnTypeFromAnnotation(func); + if (returnType) { + var signatureElementType = getIteratedTypeOfGenerator(returnType, isAsync) || anyType; + checkTypeAssignableToAndOptionallyElaborate(yieldedType, signatureElementType, node.expression || node, node.expression); + } + // Both yield and yield* expressions have type 'any' + return anyType; + } + function checkConditionalExpression(node, checkMode) { + checkTruthinessExpression(node.condition); + var type1 = checkExpression(node.whenTrue, checkMode); + var type2 = checkExpression(node.whenFalse, checkMode); + return getUnionType([type1, type2], 2 /* Subtype */); + } + function checkTemplateExpression(node) { + // We just want to check each expressions, but we are unconcerned with + // the type of each expression, as any value may be coerced into a string. + // It is worth asking whether this is what we really want though. + // A place where we actually *are* concerned with the expressions' types are + // in tagged templates. + ts.forEach(node.templateSpans, function (templateSpan) { + if (maybeTypeOfKind(checkExpression(templateSpan.expression), 12288 /* ESSymbolLike */)) { + error(templateSpan.expression, ts.Diagnostics.Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_in_String); + } + }); + return stringType; + } + function getContextNode(node) { + if (node.kind === 268 /* JsxAttributes */ && !ts.isJsxSelfClosingElement(node.parent)) { + return node.parent.parent; // Needs to be the root JsxElement, so it encompasses the attributes _and_ the children (which are essentially part of the attributes) + } + return node; + } + function checkExpressionWithContextualType(node, contextualType, contextualMapper) { + var context = getContextNode(node); + var saveContextualType = context.contextualType; + var saveContextualMapper = context.contextualMapper; + context.contextualType = contextualType; + context.contextualMapper = contextualMapper; + var checkMode = contextualMapper === identityMapper ? 1 /* SkipContextSensitive */ : + contextualMapper ? 2 /* Inferential */ : 3 /* Contextual */; + var result = checkExpression(node, checkMode); + context.contextualType = saveContextualType; + context.contextualMapper = saveContextualMapper; + return result; + } + function checkExpressionCached(node, checkMode) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + if (checkMode) { + return checkExpression(node, checkMode); + } + // When computing a type that we're going to cache, we need to ignore any ongoing control flow + // analysis because variables may have transient types in indeterminable states. Moving flowLoopStart + // to the top of the stack ensures all transient types are computed from a known point. + var saveFlowLoopStart = flowLoopStart; + flowLoopStart = flowLoopCount; + links.resolvedType = checkExpression(node, checkMode); + flowLoopStart = saveFlowLoopStart; + } + return links.resolvedType; + } + function isTypeAssertion(node) { + node = ts.skipParentheses(node); + return node.kind === 194 /* TypeAssertionExpression */ || node.kind === 212 /* AsExpression */; + } + function checkDeclarationInitializer(declaration) { + var initializer = ts.getEffectiveInitializer(declaration); + var type = getTypeOfExpression(initializer, /*cache*/ true); + var widened = ts.getCombinedNodeFlags(declaration) & 2 /* Const */ || + ts.isDeclarationReadonly(declaration) || + isTypeAssertion(initializer) ? type : getWidenedLiteralType(type); + if (ts.isInJSFile(declaration)) { + if (widened.flags & 98304 /* Nullable */) { + reportImplicitAny(declaration, anyType); + return anyType; + } + else if (isEmptyArrayLiteralType(widened)) { + reportImplicitAny(declaration, anyArrayType); + return anyArrayType; + } + } + return widened; + } + function isLiteralOfContextualType(candidateType, contextualType) { + if (contextualType) { + if (contextualType.flags & 3145728 /* UnionOrIntersection */) { + var types = contextualType.types; + return ts.some(types, function (t) { return isLiteralOfContextualType(candidateType, t); }); + } + if (contextualType.flags & 58982400 /* InstantiableNonPrimitive */) { + // If the contextual type is a type variable constrained to a primitive type, consider + // this a literal context for literals of that primitive type. For example, given a + // type parameter 'T extends string', infer string literal types for T. + var constraint = getBaseConstraintOfType(contextualType) || emptyObjectType; + return maybeTypeOfKind(constraint, 4 /* String */) && maybeTypeOfKind(candidateType, 128 /* StringLiteral */) || + maybeTypeOfKind(constraint, 8 /* Number */) && maybeTypeOfKind(candidateType, 256 /* NumberLiteral */) || + maybeTypeOfKind(constraint, 64 /* BigInt */) && maybeTypeOfKind(candidateType, 2048 /* BigIntLiteral */) || + maybeTypeOfKind(constraint, 4096 /* ESSymbol */) && maybeTypeOfKind(candidateType, 8192 /* UniqueESSymbol */) || + isLiteralOfContextualType(candidateType, constraint); + } + // If the contextual type is a literal of a particular primitive type, we consider this a + // literal context for all literals of that primitive type. + return !!(contextualType.flags & (128 /* StringLiteral */ | 4194304 /* Index */) && maybeTypeOfKind(candidateType, 128 /* StringLiteral */) || + contextualType.flags & 256 /* NumberLiteral */ && maybeTypeOfKind(candidateType, 256 /* NumberLiteral */) || + contextualType.flags & 2048 /* BigIntLiteral */ && maybeTypeOfKind(candidateType, 2048 /* BigIntLiteral */) || + contextualType.flags & 512 /* BooleanLiteral */ && maybeTypeOfKind(candidateType, 512 /* BooleanLiteral */) || + contextualType.flags & 8192 /* UniqueESSymbol */ && maybeTypeOfKind(candidateType, 8192 /* UniqueESSymbol */)); + } + return false; + } + function checkExpressionForMutableLocation(node, checkMode, contextualType, forceTuple) { + if (arguments.length === 2) { + contextualType = getContextualType(node); + } + var type = checkExpression(node, checkMode, forceTuple); + return isTypeAssertion(node) ? type : + getWidenedLiteralLikeTypeForContextualType(type, contextualType); + } + function checkPropertyAssignment(node, checkMode) { + // Do not use hasDynamicName here, because that returns false for well known symbols. + // We want to perform checkComputedPropertyName for all computed properties, including + // well known symbols. + if (node.name.kind === 149 /* ComputedPropertyName */) { + checkComputedPropertyName(node.name); + } + return checkExpressionForMutableLocation(node.initializer, checkMode); + } + function checkObjectLiteralMethod(node, checkMode) { + // Grammar checking + checkGrammarMethod(node); + // Do not use hasDynamicName here, because that returns false for well known symbols. + // We want to perform checkComputedPropertyName for all computed properties, including + // well known symbols. + if (node.name.kind === 149 /* ComputedPropertyName */) { + checkComputedPropertyName(node.name); + } + var uninstantiatedType = checkFunctionExpressionOrObjectLiteralMethod(node, checkMode); + return instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode); + } + function instantiateTypeWithSingleGenericCallSignature(node, type, checkMode) { + if (checkMode === 2 /* Inferential */) { + var signature = getSingleCallSignature(type); + if (signature && signature.typeParameters) { + var contextualType = getApparentTypeOfContextualType(node); + if (contextualType) { + var contextualSignature = getSingleCallSignature(getNonNullableType(contextualType)); + if (contextualSignature && !contextualSignature.typeParameters) { + return getOrCreateTypeFromSignature(instantiateSignatureInContextOf(signature, contextualSignature, getContextualMapper(node))); + } + } + } + } + return type; + } + /** + * Returns the type of an expression. Unlike checkExpression, this function is simply concerned + * with computing the type and may not fully check all contained sub-expressions for errors. + * A cache argument of true indicates that if the function performs a full type check, it is ok + * to cache the result. + */ + function getTypeOfExpression(node, cache) { + var expr = ts.skipParentheses(node); + // Optimize for the common case of a call to a function with a single non-generic call + // signature where we can just fetch the return type without checking the arguments. + if (expr.kind === 191 /* CallExpression */ && expr.expression.kind !== 98 /* SuperKeyword */ && !ts.isRequireCall(expr, /*checkArgumentIsStringLiteralLike*/ true) && !isSymbolOrSymbolForCall(expr)) { + var funcType = checkNonNullExpression(expr.expression); + var signature = getSingleCallSignature(funcType); + if (signature && !signature.typeParameters) { + return getReturnTypeOfSignature(signature); + } + } + else if (expr.kind === 194 /* TypeAssertionExpression */ || expr.kind === 212 /* AsExpression */) { + return getTypeFromTypeNode(expr.type); + } + // Otherwise simply call checkExpression. Ideally, the entire family of checkXXX functions + // should have a parameter that indicates whether full error checking is required such that + // we can perform the optimizations locally. + return cache ? checkExpressionCached(node) : checkExpression(node); + } + /** + * Returns the type of an expression. Unlike checkExpression, this function is simply concerned + * with computing the type and may not fully check all contained sub-expressions for errors. + * It is intended for uses where you know there is no contextual type, + * and requesting the contextual type might cause a circularity or other bad behaviour. + * It sets the contextual type of the node to any before calling getTypeOfExpression. + */ + function getContextFreeTypeOfExpression(node) { + var links = getNodeLinks(node); + if (links.contextFreeType) { + return links.contextFreeType; + } + var saveContextualType = node.contextualType; + node.contextualType = anyType; + var type = links.contextFreeType = checkExpression(node, 1 /* SkipContextSensitive */); + node.contextualType = saveContextualType; + return type; + } + // Checks an expression and returns its type. The contextualMapper parameter serves two purposes: When + // contextualMapper is not undefined and not equal to the identityMapper function object it indicates that the + // expression is being inferentially typed (section 4.15.2 in spec) and provides the type mapper to use in + // conjunction with the generic contextual type. When contextualMapper is equal to the identityMapper function + // object, it serves as an indicator that all contained function and arrow expressions should be considered to + // have the wildcard function type; this form of type check is used during overload resolution to exclude + // contextually typed function and arrow expressions in the initial phase. + function checkExpression(node, checkMode, forceTuple) { + var type; + if (node.kind === 148 /* QualifiedName */) { + type = checkQualifiedName(node); + } + else { + var uninstantiatedType = checkExpressionWorker(node, checkMode, forceTuple); + type = instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode); + } + if (isConstEnumObjectType(type)) { + // enum object type for const enums are only permitted in: + // - 'left' in property access + // - 'object' in indexed access + // - target in rhs of import statement + var ok = (node.parent.kind === 189 /* PropertyAccessExpression */ && node.parent.expression === node) || + (node.parent.kind === 190 /* ElementAccessExpression */ && node.parent.expression === node) || + ((node.kind === 72 /* Identifier */ || node.kind === 148 /* QualifiedName */) && isInRightSideOfImportOrExportAssignment(node) || + (node.parent.kind === 167 /* TypeQuery */ && node.parent.exprName === node)); + if (!ok) { + error(node, ts.Diagnostics.const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment_or_type_query); + } + } + return type; + } + function checkParenthesizedExpression(node, checkMode) { + var tag = ts.isInJSFile(node) ? ts.getJSDocTypeTag(node) : undefined; + if (tag) { + return checkAssertionWorker(tag, tag.typeExpression.type, node.expression, checkMode); + } + return checkExpression(node.expression, checkMode); + } + function checkExpressionWorker(node, checkMode, forceTuple) { + switch (node.kind) { + case 72 /* Identifier */: + return checkIdentifier(node); + case 100 /* ThisKeyword */: + return checkThisExpression(node); + case 98 /* SuperKeyword */: + return checkSuperExpression(node); + case 96 /* NullKeyword */: + return nullWideningType; + case 14 /* NoSubstitutionTemplateLiteral */: + case 10 /* StringLiteral */: + return getFreshTypeOfLiteralType(getLiteralType(node.text)); + case 8 /* NumericLiteral */: + checkGrammarNumericLiteral(node); + return getFreshTypeOfLiteralType(getLiteralType(+node.text)); + case 9 /* BigIntLiteral */: + checkGrammarBigIntLiteral(node); + return getFreshTypeOfLiteralType(getBigIntLiteralType(node)); + case 102 /* TrueKeyword */: + return trueType; + case 87 /* FalseKeyword */: + return falseType; + case 206 /* TemplateExpression */: + return checkTemplateExpression(node); + case 13 /* RegularExpressionLiteral */: + return globalRegExpType; + case 187 /* ArrayLiteralExpression */: + return checkArrayLiteral(node, checkMode, forceTuple); + case 188 /* ObjectLiteralExpression */: + return checkObjectLiteral(node, checkMode); + case 189 /* PropertyAccessExpression */: + return checkPropertyAccessExpression(node); + case 190 /* ElementAccessExpression */: + return checkIndexedAccess(node); + case 191 /* CallExpression */: + if (node.expression.kind === 92 /* ImportKeyword */) { + return checkImportCallExpression(node); + } + /* falls through */ + case 192 /* NewExpression */: + return checkCallExpression(node); + case 193 /* TaggedTemplateExpression */: + return checkTaggedTemplateExpression(node); + case 195 /* ParenthesizedExpression */: + return checkParenthesizedExpression(node, checkMode); + case 209 /* ClassExpression */: + return checkClassExpression(node); + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + return checkFunctionExpressionOrObjectLiteralMethod(node, checkMode); + case 199 /* TypeOfExpression */: + return checkTypeOfExpression(node); + case 194 /* TypeAssertionExpression */: + case 212 /* AsExpression */: + return checkAssertion(node); + case 213 /* NonNullExpression */: + return checkNonNullAssertion(node); + case 214 /* MetaProperty */: + return checkMetaProperty(node); + case 198 /* DeleteExpression */: + return checkDeleteExpression(node); + case 200 /* VoidExpression */: + return checkVoidExpression(node); + case 201 /* AwaitExpression */: + return checkAwaitExpression(node); + case 202 /* PrefixUnaryExpression */: + return checkPrefixUnaryExpression(node); + case 203 /* PostfixUnaryExpression */: + return checkPostfixUnaryExpression(node); + case 204 /* BinaryExpression */: + return checkBinaryExpression(node, checkMode); + case 205 /* ConditionalExpression */: + return checkConditionalExpression(node, checkMode); + case 208 /* SpreadElement */: + return checkSpreadExpression(node, checkMode); + case 210 /* OmittedExpression */: + return undefinedWideningType; + case 207 /* YieldExpression */: + return checkYieldExpression(node); + case 215 /* SyntheticExpression */: + return node.type; + case 270 /* JsxExpression */: + return checkJsxExpression(node, checkMode); + case 260 /* JsxElement */: + return checkJsxElement(node, checkMode); + case 261 /* JsxSelfClosingElement */: + return checkJsxSelfClosingElement(node, checkMode); + case 264 /* JsxFragment */: + return checkJsxFragment(node); + case 268 /* JsxAttributes */: + return checkJsxAttributes(node, checkMode); + case 262 /* JsxOpeningElement */: + ts.Debug.fail("Shouldn't ever directly check a JsxOpeningElement"); + } + return errorType; + } + // DECLARATION AND STATEMENT TYPE CHECKING + function checkTypeParameter(node) { + // Grammar Checking + if (node.expression) { + grammarErrorOnFirstToken(node.expression, ts.Diagnostics.Type_expected); + } + checkSourceElement(node.constraint); + checkSourceElement(node.default); + var typeParameter = getDeclaredTypeOfTypeParameter(getSymbolOfNode(node)); + if (!hasNonCircularBaseConstraint(typeParameter)) { + error(ts.getEffectiveConstraintOfTypeParameter(node), ts.Diagnostics.Type_parameter_0_has_a_circular_constraint, typeToString(typeParameter)); + } + if (!hasNonCircularTypeParameterDefault(typeParameter)) { + error(node.default, ts.Diagnostics.Type_parameter_0_has_a_circular_default, typeToString(typeParameter)); + } + var constraintType = getConstraintOfTypeParameter(typeParameter); + var defaultType = getDefaultFromTypeParameter(typeParameter); + if (constraintType && defaultType) { + checkTypeAssignableTo(defaultType, getTypeWithThisArgument(constraintType, defaultType), node.default, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); + } + if (produceDiagnostics) { + checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_parameter_name_cannot_be_0); + } + } + function checkParameter(node) { + // Grammar checking + // It is a SyntaxError if the Identifier "eval" or the Identifier "arguments" occurs as the + // Identifier in a PropertySetParameterList of a PropertyAssignment that is contained in strict code + // or if its FunctionBody is strict code(11.1.5). + checkGrammarDecoratorsAndModifiers(node); + checkVariableLikeDeclaration(node); + var func = ts.getContainingFunction(node); + if (ts.hasModifier(node, 92 /* ParameterPropertyModifier */)) { + if (!(func.kind === 157 /* Constructor */ && ts.nodeIsPresent(func.body))) { + error(node, ts.Diagnostics.A_parameter_property_is_only_allowed_in_a_constructor_implementation); + } + } + if (node.questionToken && ts.isBindingPattern(node.name) && func.body) { + error(node, ts.Diagnostics.A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature); + } + if (node.name && ts.isIdentifier(node.name) && (node.name.escapedText === "this" || node.name.escapedText === "new")) { + if (func.parameters.indexOf(node) !== 0) { + error(node, ts.Diagnostics.A_0_parameter_must_be_the_first_parameter, node.name.escapedText); + } + if (func.kind === 157 /* Constructor */ || func.kind === 161 /* ConstructSignature */ || func.kind === 166 /* ConstructorType */) { + error(node, ts.Diagnostics.A_constructor_cannot_have_a_this_parameter); + } + if (func.kind === 197 /* ArrowFunction */) { + error(node, ts.Diagnostics.An_arrow_function_cannot_have_a_this_parameter); + } + } + // Only check rest parameter type if it's not a binding pattern. Since binding patterns are + // not allowed in a rest parameter, we already have an error from checkGrammarParameterList. + if (node.dotDotDotToken && !ts.isBindingPattern(node.name) && !isTypeAssignableTo(getTypeOfSymbol(node.symbol), anyArrayType)) { + error(node, ts.Diagnostics.A_rest_parameter_must_be_of_an_array_type); + } + } + function checkTypePredicate(node) { + var parent = getTypePredicateParent(node); + if (!parent) { + // The parent must not be valid. + error(node, ts.Diagnostics.A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods); + return; + } + var typePredicate = getTypePredicateOfSignature(getSignatureFromDeclaration(parent)); + if (!typePredicate) { + return; + } + checkSourceElement(node.type); + var parameterName = node.parameterName; + if (ts.isThisTypePredicate(typePredicate)) { + getTypeFromThisTypeNode(parameterName); + } + else { + if (typePredicate.parameterIndex >= 0) { + if (parent.parameters[typePredicate.parameterIndex].dotDotDotToken) { + error(parameterName, ts.Diagnostics.A_type_predicate_cannot_reference_a_rest_parameter); + } + else { + var leadingError = function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type); }; + checkTypeAssignableTo(typePredicate.type, getTypeOfNode(parent.parameters[typePredicate.parameterIndex]), node.type, + /*headMessage*/ undefined, leadingError); + } + } + else if (parameterName) { + var hasReportedError = false; + for (var _i = 0, _a = parent.parameters; _i < _a.length; _i++) { + var name = _a[_i].name; + if (ts.isBindingPattern(name) && + checkIfTypePredicateVariableIsDeclaredInBindingPattern(name, parameterName, typePredicate.parameterName)) { + hasReportedError = true; + break; + } + } + if (!hasReportedError) { + error(node.parameterName, ts.Diagnostics.Cannot_find_parameter_0, typePredicate.parameterName); + } + } + } + } + function getTypePredicateParent(node) { + switch (node.parent.kind) { + case 197 /* ArrowFunction */: + case 160 /* CallSignature */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 165 /* FunctionType */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + var parent = node.parent; + if (node === parent.type) { + return parent; + } + } + } + function checkIfTypePredicateVariableIsDeclaredInBindingPattern(pattern, predicateVariableNode, predicateVariableName) { + for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (ts.isOmittedExpression(element)) { + continue; + } + var name = element.name; + if (name.kind === 72 /* Identifier */ && name.escapedText === predicateVariableName) { + error(predicateVariableNode, ts.Diagnostics.A_type_predicate_cannot_reference_element_0_in_a_binding_pattern, predicateVariableName); + return true; + } + else if (name.kind === 185 /* ArrayBindingPattern */ || name.kind === 184 /* ObjectBindingPattern */) { + if (checkIfTypePredicateVariableIsDeclaredInBindingPattern(name, predicateVariableNode, predicateVariableName)) { + return true; + } + } + } + } + function checkSignatureDeclaration(node) { + // Grammar checking + if (node.kind === 162 /* IndexSignature */) { + checkGrammarIndexSignature(node); + } + // TODO (yuisu): Remove this check in else-if when SyntaxKind.Construct is moved and ambient context is handled + else if (node.kind === 165 /* FunctionType */ || node.kind === 239 /* FunctionDeclaration */ || node.kind === 166 /* ConstructorType */ || + node.kind === 160 /* CallSignature */ || node.kind === 157 /* Constructor */ || + node.kind === 161 /* ConstructSignature */) { + checkGrammarFunctionLikeDeclaration(node); + } + var functionFlags = ts.getFunctionFlags(node); + if (!(functionFlags & 4 /* Invalid */)) { + // Async generators prior to ESNext require the __await and __asyncGenerator helpers + if ((functionFlags & 3 /* AsyncGenerator */) === 3 /* AsyncGenerator */ && languageVersion < 6 /* ESNext */) { + checkExternalEmitHelpers(node, 6144 /* AsyncGeneratorIncludes */); + } + // Async functions prior to ES2017 require the __awaiter helper + if ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */ && languageVersion < 4 /* ES2017 */) { + checkExternalEmitHelpers(node, 64 /* Awaiter */); + } + // Generator functions, Async functions, and Async Generator functions prior to + // ES2015 require the __generator helper + if ((functionFlags & 3 /* AsyncGenerator */) !== 0 /* Normal */ && languageVersion < 2 /* ES2015 */) { + checkExternalEmitHelpers(node, 128 /* Generator */); + } + } + checkTypeParameters(node.typeParameters); + ts.forEach(node.parameters, checkParameter); + // TODO(rbuckton): Should we start checking JSDoc types? + if (node.type) { + checkSourceElement(node.type); + } + if (produceDiagnostics) { + checkCollisionWithArgumentsInGeneratedCode(node); + var returnTypeNode = ts.getEffectiveReturnTypeNode(node); + if (noImplicitAny && !returnTypeNode) { + switch (node.kind) { + case 161 /* ConstructSignature */: + error(node, ts.Diagnostics.Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type); + break; + case 160 /* CallSignature */: + error(node, ts.Diagnostics.Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type); + break; + } + } + if (returnTypeNode) { + var functionFlags_1 = ts.getFunctionFlags(node); + if ((functionFlags_1 & (4 /* Invalid */ | 1 /* Generator */)) === 1 /* Generator */) { + var returnType = getTypeFromTypeNode(returnTypeNode); + if (returnType === voidType) { + error(returnTypeNode, ts.Diagnostics.A_generator_cannot_have_a_void_type_annotation); + } + else { + var generatorElementType = getIteratedTypeOfGenerator(returnType, (functionFlags_1 & 2 /* Async */) !== 0) || anyType; + var iterableIteratorInstantiation = functionFlags_1 & 2 /* Async */ + ? createAsyncIterableIteratorType(generatorElementType) // AsyncGenerator function + : createIterableIteratorType(generatorElementType); // Generator function + // Naively, one could check that IterableIterator is assignable to the return type annotation. + // However, that would not catch the error in the following case. + // + // interface BadGenerator extends Iterable, Iterator { } + // function* g(): BadGenerator { } // Iterable and Iterator have different types! + // + checkTypeAssignableTo(iterableIteratorInstantiation, returnType, returnTypeNode); + } + } + else if ((functionFlags_1 & 3 /* AsyncGenerator */) === 2 /* Async */) { + checkAsyncFunctionReturnType(node, returnTypeNode); + } + } + if (node.kind !== 162 /* IndexSignature */ && node.kind !== 289 /* JSDocFunctionType */) { + registerForUnusedIdentifiersCheck(node); + } + } + } + function checkClassForDuplicateDeclarations(node) { + var Declaration; + (function (Declaration) { + Declaration[Declaration["Getter"] = 1] = "Getter"; + Declaration[Declaration["Setter"] = 2] = "Setter"; + Declaration[Declaration["Method"] = 4] = "Method"; + Declaration[Declaration["Property"] = 3] = "Property"; + })(Declaration || (Declaration = {})); + var instanceNames = ts.createUnderscoreEscapedMap(); + var staticNames = ts.createUnderscoreEscapedMap(); + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + if (member.kind === 157 /* Constructor */) { + for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { + var param = _c[_b]; + if (ts.isParameterPropertyDeclaration(param) && !ts.isBindingPattern(param.name)) { + addName(instanceNames, param.name, param.name.escapedText, 3 /* Property */); + } + } + } + else { + var isStatic = ts.hasModifier(member, 32 /* Static */); + var names = isStatic ? staticNames : instanceNames; + var name = member.name; + var memberName = name && ts.getPropertyNameForPropertyNameNode(name); + if (name && memberName) { + switch (member.kind) { + case 158 /* GetAccessor */: + addName(names, name, memberName, 1 /* Getter */); + break; + case 159 /* SetAccessor */: + addName(names, name, memberName, 2 /* Setter */); + break; + case 154 /* PropertyDeclaration */: + addName(names, name, memberName, 3 /* Property */); + break; + case 156 /* MethodDeclaration */: + addName(names, name, memberName, 4 /* Method */); + break; + } + } + } + } + function addName(names, location, name, meaning) { + var prev = names.get(name); + if (prev) { + if (prev & 4 /* Method */) { + if (meaning !== 4 /* Method */) { + error(location, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(location)); + } + } + else if (prev & meaning) { + error(location, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(location)); + } + else { + names.set(name, prev | meaning); + } + } + else { + names.set(name, meaning); + } + } + } + /** + * Static members being set on a constructor function may conflict with built-in properties + * of Function. Esp. in ECMAScript 5 there are non-configurable and non-writable + * built-in properties. This check issues a transpile error when a class has a static + * member with the same name as a non-writable built-in property. + * + * @see http://www.ecma-international.org/ecma-262/5.1/#sec-15.3.3 + * @see http://www.ecma-international.org/ecma-262/5.1/#sec-15.3.5 + * @see http://www.ecma-international.org/ecma-262/6.0/#sec-properties-of-the-function-constructor + * @see http://www.ecma-international.org/ecma-262/6.0/#sec-function-instances + */ + function checkClassForStaticPropertyNameConflicts(node) { + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + var memberNameNode = member.name; + var isStatic = ts.hasModifier(member, 32 /* Static */); + if (isStatic && memberNameNode) { + var memberName = ts.getPropertyNameForPropertyNameNode(memberNameNode); + switch (memberName) { + case "name": + case "length": + case "caller": + case "arguments": + case "prototype": + var message = ts.Diagnostics.Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1; + var className = getNameOfSymbolAsWritten(getSymbolOfNode(node)); + error(memberNameNode, message, memberName, className); + break; + } + } + } + } + function checkObjectTypeForDuplicateDeclarations(node) { + var names = ts.createMap(); + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + if (member.kind === 153 /* PropertySignature */) { + var memberName = void 0; + var name = member.name; + switch (name.kind) { + case 10 /* StringLiteral */: + case 8 /* NumericLiteral */: + memberName = name.text; + break; + case 72 /* Identifier */: + memberName = ts.idText(name); + break; + default: + continue; + } + if (names.get(memberName)) { + error(ts.getNameOfDeclaration(member.symbol.valueDeclaration), ts.Diagnostics.Duplicate_identifier_0, memberName); + error(member.name, ts.Diagnostics.Duplicate_identifier_0, memberName); + } + else { + names.set(memberName, true); + } + } + } + } + function checkTypeForDuplicateIndexSignatures(node) { + if (node.kind === 241 /* InterfaceDeclaration */) { + var nodeSymbol = getSymbolOfNode(node); + // in case of merging interface declaration it is possible that we'll enter this check procedure several times for every declaration + // to prevent this run check only for the first declaration of a given kind + if (nodeSymbol.declarations.length > 0 && nodeSymbol.declarations[0] !== node) { + return; + } + } + // TypeScript 1.0 spec (April 2014) + // 3.7.4: An object type can contain at most one string index signature and one numeric index signature. + // 8.5: A class declaration can have at most one string index member declaration and one numeric index member declaration + var indexSymbol = getIndexSymbol(getSymbolOfNode(node)); + if (indexSymbol) { + var seenNumericIndexer = false; + var seenStringIndexer = false; + for (var _i = 0, _a = indexSymbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + var declaration = decl; + if (declaration.parameters.length === 1 && declaration.parameters[0].type) { + switch (declaration.parameters[0].type.kind) { + case 138 /* StringKeyword */: + if (!seenStringIndexer) { + seenStringIndexer = true; + } + else { + error(declaration, ts.Diagnostics.Duplicate_string_index_signature); + } + break; + case 135 /* NumberKeyword */: + if (!seenNumericIndexer) { + seenNumericIndexer = true; + } + else { + error(declaration, ts.Diagnostics.Duplicate_number_index_signature); + } + break; + } + } + } + } + } + function checkPropertyDeclaration(node) { + // Grammar checking + if (!checkGrammarDecoratorsAndModifiers(node) && !checkGrammarProperty(node)) + checkGrammarComputedPropertyName(node.name); + checkVariableLikeDeclaration(node); + } + function checkMethodDeclaration(node) { + // Grammar checking + if (!checkGrammarMethod(node)) + checkGrammarComputedPropertyName(node.name); + // Grammar checking for modifiers is done inside the function checkGrammarFunctionLikeDeclaration + checkFunctionOrMethodDeclaration(node); + // Abstract methods cannot have an implementation. + // Extra checks are to avoid reporting multiple errors relating to the "abstractness" of the node. + if (ts.hasModifier(node, 128 /* Abstract */) && node.kind === 156 /* MethodDeclaration */ && node.body) { + error(node, ts.Diagnostics.Method_0_cannot_have_an_implementation_because_it_is_marked_abstract, ts.declarationNameToString(node.name)); + } + } + function checkConstructorDeclaration(node) { + // Grammar check on signature of constructor and modifier of the constructor is done in checkSignatureDeclaration function. + checkSignatureDeclaration(node); + // Grammar check for checking only related to constructorDeclaration + if (!checkGrammarConstructorTypeParameters(node)) + checkGrammarConstructorTypeAnnotation(node); + checkSourceElement(node.body); + var symbol = getSymbolOfNode(node); + var firstDeclaration = ts.getDeclarationOfKind(symbol, node.kind); + // Only type check the symbol once + if (node === firstDeclaration) { + checkFunctionOrConstructorSymbol(symbol); + } + // exit early in the case of signature - super checks are not relevant to them + if (ts.nodeIsMissing(node.body)) { + return; + } + if (!produceDiagnostics) { + return; + } + function isInstancePropertyWithInitializer(n) { + return n.kind === 154 /* PropertyDeclaration */ && + !ts.hasModifier(n, 32 /* Static */) && + !!n.initializer; + } + // TS 1.0 spec (April 2014): 8.3.2 + // Constructors of classes with no extends clause may not contain super calls, whereas + // constructors of derived classes must contain at least one super call somewhere in their function body. + var containingClassDecl = node.parent; + if (ts.getEffectiveBaseTypeNode(containingClassDecl)) { + captureLexicalThis(node.parent, containingClassDecl); + var classExtendsNull = classDeclarationExtendsNull(containingClassDecl); + var superCall = getSuperCallInConstructor(node); + if (superCall) { + if (classExtendsNull) { + error(superCall, ts.Diagnostics.A_constructor_cannot_contain_a_super_call_when_its_class_extends_null); + } + // The first statement in the body of a constructor (excluding prologue directives) must be a super call + // if both of the following are true: + // - The containing class is a derived class. + // - The constructor declares parameter properties + // or the containing class declares instance member variables with initializers. + var superCallShouldBeFirst = ts.some(node.parent.members, isInstancePropertyWithInitializer) || + ts.some(node.parameters, function (p) { return ts.hasModifier(p, 92 /* ParameterPropertyModifier */); }); + // Skip past any prologue directives to find the first statement + // to ensure that it was a super call. + if (superCallShouldBeFirst) { + var statements = node.body.statements; + var superCallStatement = void 0; + for (var _i = 0, statements_2 = statements; _i < statements_2.length; _i++) { + var statement = statements_2[_i]; + if (statement.kind === 221 /* ExpressionStatement */ && ts.isSuperCall(statement.expression)) { + superCallStatement = statement; + break; + } + if (!ts.isPrologueDirective(statement)) { + break; + } + } + if (!superCallStatement) { + error(node, ts.Diagnostics.A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_properties_or_has_parameter_properties); + } + } + } + else if (!classExtendsNull) { + error(node, ts.Diagnostics.Constructors_for_derived_classes_must_contain_a_super_call); + } + } + } + function checkAccessorDeclaration(node) { + if (produceDiagnostics) { + // Grammar checking accessors + if (!checkGrammarFunctionLikeDeclaration(node) && !checkGrammarAccessor(node)) + checkGrammarComputedPropertyName(node.name); + checkDecorators(node); + checkSignatureDeclaration(node); + if (node.kind === 158 /* GetAccessor */) { + if (!(node.flags & 4194304 /* Ambient */) && ts.nodeIsPresent(node.body) && (node.flags & 128 /* HasImplicitReturn */)) { + if (!(node.flags & 256 /* HasExplicitReturn */)) { + error(node.name, ts.Diagnostics.A_get_accessor_must_return_a_value); + } + } + } + // Do not use hasDynamicName here, because that returns false for well known symbols. + // We want to perform checkComputedPropertyName for all computed properties, including + // well known symbols. + if (node.name.kind === 149 /* ComputedPropertyName */) { + checkComputedPropertyName(node.name); + } + if (!hasNonBindableDynamicName(node)) { + // TypeScript 1.0 spec (April 2014): 8.4.3 + // Accessors for the same member name must specify the same accessibility. + var otherKind = node.kind === 158 /* GetAccessor */ ? 159 /* SetAccessor */ : 158 /* GetAccessor */; + var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(node), otherKind); + if (otherAccessor) { + var nodeFlags = ts.getModifierFlags(node); + var otherFlags = ts.getModifierFlags(otherAccessor); + if ((nodeFlags & 28 /* AccessibilityModifier */) !== (otherFlags & 28 /* AccessibilityModifier */)) { + error(node.name, ts.Diagnostics.Getter_and_setter_accessors_do_not_agree_in_visibility); + } + if ((nodeFlags & 128 /* Abstract */) !== (otherFlags & 128 /* Abstract */)) { + error(node.name, ts.Diagnostics.Accessors_must_both_be_abstract_or_non_abstract); + } + // TypeScript 1.0 spec (April 2014): 4.5 + // If both accessors include type annotations, the specified types must be identical. + checkAccessorDeclarationTypesIdentical(node, otherAccessor, getAnnotatedAccessorType, ts.Diagnostics.get_and_set_accessor_must_have_the_same_type); + checkAccessorDeclarationTypesIdentical(node, otherAccessor, getThisTypeOfDeclaration, ts.Diagnostics.get_and_set_accessor_must_have_the_same_this_type); + } + } + var returnType = getTypeOfAccessors(getSymbolOfNode(node)); + if (node.kind === 158 /* GetAccessor */) { + checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnType); + } + } + checkSourceElement(node.body); + } + function checkAccessorDeclarationTypesIdentical(first, second, getAnnotatedType, message) { + var firstType = getAnnotatedType(first); + var secondType = getAnnotatedType(second); + if (firstType && secondType && !isTypeIdenticalTo(firstType, secondType)) { + error(first, message); + } + } + function checkMissingDeclaration(node) { + checkDecorators(node); + } + function getEffectiveTypeArguments(node, typeParameters) { + return fillMissingTypeArguments(ts.map(node.typeArguments, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJSFile(node)); + } + function checkTypeArgumentConstraints(node, typeParameters) { + var typeArguments; + var mapper; + var result = true; + for (var i = 0; i < typeParameters.length; i++) { + var constraint = getConstraintOfTypeParameter(typeParameters[i]); + if (constraint) { + if (!typeArguments) { + typeArguments = getEffectiveTypeArguments(node, typeParameters); + mapper = createTypeMapper(typeParameters, typeArguments); + } + result = result && checkTypeAssignableTo(typeArguments[i], instantiateType(constraint, mapper), node.typeArguments[i], ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); + } + } + return result; + } + function getTypeParametersForTypeReference(node) { + var type = getTypeFromTypeReference(node); + if (type !== errorType) { + var symbol = getNodeLinks(node).resolvedSymbol; + if (symbol) { + return symbol.flags & 524288 /* TypeAlias */ && getSymbolLinks(symbol).typeParameters || + (ts.getObjectFlags(type) & 4 /* Reference */ ? type.target.localTypeParameters : undefined); + } + } + return undefined; + } + function checkTypeReferenceNode(node) { + checkGrammarTypeArguments(node, node.typeArguments); + if (node.kind === 164 /* TypeReference */ && node.typeName.jsdocDotPos !== undefined && !ts.isInJSFile(node) && !ts.isInJSDoc(node)) { + grammarErrorAtPos(node, node.typeName.jsdocDotPos, 1, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments); + } + var type = getTypeFromTypeReference(node); + if (type !== errorType) { + if (node.typeArguments) { + // Do type argument local checks only if referenced type is successfully resolved + ts.forEach(node.typeArguments, checkSourceElement); + if (produceDiagnostics) { + var typeParameters = getTypeParametersForTypeReference(node); + if (typeParameters) { + checkTypeArgumentConstraints(node, typeParameters); + } + } + } + if (type.flags & 32 /* Enum */ && getNodeLinks(node).resolvedSymbol.flags & 8 /* EnumMember */) { + error(node, ts.Diagnostics.Enum_type_0_has_members_with_initializers_that_are_not_literals, typeToString(type)); + } + } + } + function getTypeArgumentConstraint(node) { + var typeReferenceNode = ts.tryCast(node.parent, ts.isTypeReferenceType); + if (!typeReferenceNode) + return undefined; + var typeParameters = getTypeParametersForTypeReference(typeReferenceNode); // TODO: GH#18217 + var constraint = getConstraintOfTypeParameter(typeParameters[typeReferenceNode.typeArguments.indexOf(node)]); + return constraint && instantiateType(constraint, createTypeMapper(typeParameters, getEffectiveTypeArguments(typeReferenceNode, typeParameters))); + } + function checkTypeQuery(node) { + getTypeFromTypeQueryNode(node); + } + function checkTypeLiteral(node) { + ts.forEach(node.members, checkSourceElement); + if (produceDiagnostics) { + var type = getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node); + checkIndexConstraints(type); + checkTypeForDuplicateIndexSignatures(node); + checkObjectTypeForDuplicateDeclarations(node); + } + } + function checkArrayType(node) { + checkSourceElement(node.elementType); + } + function checkTupleType(node) { + var elementTypes = node.elementTypes; + var seenOptionalElement = false; + for (var i = 0; i < elementTypes.length; i++) { + var e = elementTypes[i]; + if (e.kind === 172 /* RestType */) { + if (i !== elementTypes.length - 1) { + grammarErrorOnNode(e, ts.Diagnostics.A_rest_element_must_be_last_in_a_tuple_type); + break; + } + if (!isArrayType(getTypeFromTypeNode(e))) { + error(e, ts.Diagnostics.A_rest_element_type_must_be_an_array_type); + } + } + else if (e.kind === 171 /* OptionalType */) { + seenOptionalElement = true; + } + else if (seenOptionalElement) { + grammarErrorOnNode(e, ts.Diagnostics.A_required_element_cannot_follow_an_optional_element); + break; + } + } + checkGrammarForDisallowedTrailingComma(node.elementTypes); + ts.forEach(node.elementTypes, checkSourceElement); + } + function checkUnionOrIntersectionType(node) { + ts.forEach(node.types, checkSourceElement); + } + function checkIndexedAccessIndexType(type, accessNode) { + if (!(type.flags & 8388608 /* IndexedAccess */)) { + return type; + } + // Check if the index type is assignable to 'keyof T' for the object type. + var objectType = type.objectType; + var indexType = type.indexType; + if (isTypeAssignableTo(indexType, getIndexType(objectType, /*stringsOnly*/ false))) { + if (accessNode.kind === 190 /* ElementAccessExpression */ && ts.isAssignmentTarget(accessNode) && + ts.getObjectFlags(objectType) & 32 /* Mapped */ && getMappedTypeModifiers(objectType) & 1 /* IncludeReadonly */) { + error(accessNode, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(objectType)); + } + return type; + } + // Check if we're indexing with a numeric type and if either object or index types + // is a generic type with a constraint that has a numeric index signature. + if (getIndexInfoOfType(getApparentType(objectType), 1 /* Number */) && isTypeAssignableToKind(indexType, 296 /* NumberLike */)) { + return type; + } + error(accessNode, ts.Diagnostics.Type_0_cannot_be_used_to_index_type_1, typeToString(indexType), typeToString(objectType)); + return type; + } + function checkIndexedAccessType(node) { + checkSourceElement(node.objectType); + checkSourceElement(node.indexType); + checkIndexedAccessIndexType(getTypeFromIndexedAccessTypeNode(node), node); + } + function checkMappedType(node) { + checkSourceElement(node.typeParameter); + checkSourceElement(node.type); + if (!node.type) { + reportImplicitAny(node, anyType); + } + var type = getTypeFromMappedTypeNode(node); + var constraintType = getConstraintTypeFromMappedType(type); + checkTypeAssignableTo(constraintType, keyofConstraintType, ts.getEffectiveConstraintOfTypeParameter(node.typeParameter)); + } + function checkThisType(node) { + getTypeFromThisTypeNode(node); + } + function checkTypeOperator(node) { + checkGrammarTypeOperatorNode(node); + checkSourceElement(node.type); + } + function checkConditionalType(node) { + ts.forEachChild(node, checkSourceElement); + } + function checkInferType(node) { + if (!ts.findAncestor(node, function (n) { return n.parent && n.parent.kind === 175 /* ConditionalType */ && n.parent.extendsType === n; })) { + grammarErrorOnNode(node, ts.Diagnostics.infer_declarations_are_only_permitted_in_the_extends_clause_of_a_conditional_type); + } + checkSourceElement(node.typeParameter); + registerForUnusedIdentifiersCheck(node); + } + function checkImportType(node) { + checkSourceElement(node.argument); + getTypeFromTypeNode(node); + } + function isPrivateWithinAmbient(node) { + return ts.hasModifier(node, 8 /* Private */) && !!(node.flags & 4194304 /* Ambient */); + } + function getEffectiveDeclarationFlags(n, flagsToCheck) { + var flags = ts.getCombinedModifierFlags(n); + // children of classes (even ambient classes) should not be marked as ambient or export + // because those flags have no useful semantics there. + if (n.parent.kind !== 241 /* InterfaceDeclaration */ && + n.parent.kind !== 240 /* ClassDeclaration */ && + n.parent.kind !== 209 /* ClassExpression */ && + n.flags & 4194304 /* Ambient */) { + if (!(flags & 2 /* Ambient */) && !(ts.isModuleBlock(n.parent) && ts.isModuleDeclaration(n.parent.parent) && ts.isGlobalScopeAugmentation(n.parent.parent))) { + // It is nested in an ambient context, which means it is automatically exported + flags |= 1 /* Export */; + } + flags |= 2 /* Ambient */; + } + return flags & flagsToCheck; + } + function checkFunctionOrConstructorSymbol(symbol) { + if (!produceDiagnostics) { + return; + } + function getCanonicalOverload(overloads, implementation) { + // Consider the canonical set of flags to be the flags of the bodyDeclaration or the first declaration + // Error on all deviations from this canonical set of flags + // The caveat is that if some overloads are defined in lib.d.ts, we don't want to + // report the errors on those. To achieve this, we will say that the implementation is + // the canonical signature only if it is in the same container as the first overload + var implementationSharesContainerWithFirstOverload = implementation !== undefined && implementation.parent === overloads[0].parent; + return implementationSharesContainerWithFirstOverload ? implementation : overloads[0]; + } + function checkFlagAgreementBetweenOverloads(overloads, implementation, flagsToCheck, someOverloadFlags, allOverloadFlags) { + // Error if some overloads have a flag that is not shared by all overloads. To find the + // deviations, we XOR someOverloadFlags with allOverloadFlags + var someButNotAllOverloadFlags = someOverloadFlags ^ allOverloadFlags; + if (someButNotAllOverloadFlags !== 0) { + var canonicalFlags_1 = getEffectiveDeclarationFlags(getCanonicalOverload(overloads, implementation), flagsToCheck); + ts.forEach(overloads, function (o) { + var deviation = getEffectiveDeclarationFlags(o, flagsToCheck) ^ canonicalFlags_1; + if (deviation & 1 /* Export */) { + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_exported_or_non_exported); + } + else if (deviation & 2 /* Ambient */) { + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_ambient_or_non_ambient); + } + else if (deviation & (8 /* Private */ | 16 /* Protected */)) { + error(ts.getNameOfDeclaration(o) || o, ts.Diagnostics.Overload_signatures_must_all_be_public_private_or_protected); + } + else if (deviation & 128 /* Abstract */) { + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_abstract_or_non_abstract); + } + }); + } + } + function checkQuestionTokenAgreementBetweenOverloads(overloads, implementation, someHaveQuestionToken, allHaveQuestionToken) { + if (someHaveQuestionToken !== allHaveQuestionToken) { + var canonicalHasQuestionToken_1 = ts.hasQuestionToken(getCanonicalOverload(overloads, implementation)); + ts.forEach(overloads, function (o) { + var deviation = ts.hasQuestionToken(o) !== canonicalHasQuestionToken_1; + if (deviation) { + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_optional_or_required); + } + }); + } + } + var flagsToCheck = 1 /* Export */ | 2 /* Ambient */ | 8 /* Private */ | 16 /* Protected */ | 128 /* Abstract */; + var someNodeFlags = 0 /* None */; + var allNodeFlags = flagsToCheck; + var someHaveQuestionToken = false; + var allHaveQuestionToken = true; + var hasOverloads = false; + var bodyDeclaration; + var lastSeenNonAmbientDeclaration; + var previousDeclaration; + var declarations = symbol.declarations; + var isConstructor = (symbol.flags & 16384 /* Constructor */) !== 0; + function reportImplementationExpectedError(node) { + if (node.name && ts.nodeIsMissing(node.name)) { + return; + } + var seen = false; + var subsequentNode = ts.forEachChild(node.parent, function (c) { + if (seen) { + return c; + } + else { + seen = c === node; + } + }); + // We may be here because of some extra nodes between overloads that could not be parsed into a valid node. + // In this case the subsequent node is not really consecutive (.pos !== node.end), and we must ignore it here. + if (subsequentNode && subsequentNode.pos === node.end) { + if (subsequentNode.kind === node.kind) { + var errorNode_1 = subsequentNode.name || subsequentNode; + // TODO: GH#17345: These are methods, so handle computed name case. (`Always allowing computed property names is *not* the correct behavior!) + var subsequentName = subsequentNode.name; + if (node.name && subsequentName && + (ts.isComputedPropertyName(node.name) && ts.isComputedPropertyName(subsequentName) || + !ts.isComputedPropertyName(node.name) && !ts.isComputedPropertyName(subsequentName) && ts.getEscapedTextOfIdentifierOrLiteral(node.name) === ts.getEscapedTextOfIdentifierOrLiteral(subsequentName))) { + var reportError = (node.kind === 156 /* MethodDeclaration */ || node.kind === 155 /* MethodSignature */) && + ts.hasModifier(node, 32 /* Static */) !== ts.hasModifier(subsequentNode, 32 /* Static */); + // we can get here in two cases + // 1. mixed static and instance class members + // 2. something with the same name was defined before the set of overloads that prevents them from merging + // here we'll report error only for the first case since for second we should already report error in binder + if (reportError) { + var diagnostic = ts.hasModifier(node, 32 /* Static */) ? ts.Diagnostics.Function_overload_must_be_static : ts.Diagnostics.Function_overload_must_not_be_static; + error(errorNode_1, diagnostic); + } + return; + } + else if (ts.nodeIsPresent(subsequentNode.body)) { + error(errorNode_1, ts.Diagnostics.Function_implementation_name_must_be_0, ts.declarationNameToString(node.name)); + return; + } + } + } + var errorNode = node.name || node; + if (isConstructor) { + error(errorNode, ts.Diagnostics.Constructor_implementation_is_missing); + } + else { + // Report different errors regarding non-consecutive blocks of declarations depending on whether + // the node in question is abstract. + if (ts.hasModifier(node, 128 /* Abstract */)) { + error(errorNode, ts.Diagnostics.All_declarations_of_an_abstract_method_must_be_consecutive); + } + else { + error(errorNode, ts.Diagnostics.Function_implementation_is_missing_or_not_immediately_following_the_declaration); + } + } + } + var duplicateFunctionDeclaration = false; + var multipleConstructorImplementation = false; + for (var _i = 0, declarations_4 = declarations; _i < declarations_4.length; _i++) { + var current = declarations_4[_i]; + var node = current; + var inAmbientContext = node.flags & 4194304 /* Ambient */; + var inAmbientContextOrInterface = node.parent.kind === 241 /* InterfaceDeclaration */ || node.parent.kind === 168 /* TypeLiteral */ || inAmbientContext; + if (inAmbientContextOrInterface) { + // check if declarations are consecutive only if they are non-ambient + // 1. ambient declarations can be interleaved + // i.e. this is legal + // declare function foo(); + // declare function bar(); + // declare function foo(); + // 2. mixing ambient and non-ambient declarations is a separate error that will be reported - do not want to report an extra one + previousDeclaration = undefined; + } + if (node.kind === 239 /* FunctionDeclaration */ || node.kind === 156 /* MethodDeclaration */ || node.kind === 155 /* MethodSignature */ || node.kind === 157 /* Constructor */) { + var currentNodeFlags = getEffectiveDeclarationFlags(node, flagsToCheck); + someNodeFlags |= currentNodeFlags; + allNodeFlags &= currentNodeFlags; + someHaveQuestionToken = someHaveQuestionToken || ts.hasQuestionToken(node); + allHaveQuestionToken = allHaveQuestionToken && ts.hasQuestionToken(node); + if (ts.nodeIsPresent(node.body) && bodyDeclaration) { + if (isConstructor) { + multipleConstructorImplementation = true; + } + else { + duplicateFunctionDeclaration = true; + } + } + else if (previousDeclaration && previousDeclaration.parent === node.parent && previousDeclaration.end !== node.pos) { + reportImplementationExpectedError(previousDeclaration); + } + if (ts.nodeIsPresent(node.body)) { + if (!bodyDeclaration) { + bodyDeclaration = node; + } + } + else { + hasOverloads = true; + } + previousDeclaration = node; + if (!inAmbientContextOrInterface) { + lastSeenNonAmbientDeclaration = node; + } + } + } + if (multipleConstructorImplementation) { + ts.forEach(declarations, function (declaration) { + error(declaration, ts.Diagnostics.Multiple_constructor_implementations_are_not_allowed); + }); + } + if (duplicateFunctionDeclaration) { + ts.forEach(declarations, function (declaration) { + error(ts.getNameOfDeclaration(declaration), ts.Diagnostics.Duplicate_function_implementation); + }); + } + // Abstract methods can't have an implementation -- in particular, they don't need one. + if (lastSeenNonAmbientDeclaration && !lastSeenNonAmbientDeclaration.body && + !ts.hasModifier(lastSeenNonAmbientDeclaration, 128 /* Abstract */) && !lastSeenNonAmbientDeclaration.questionToken) { + reportImplementationExpectedError(lastSeenNonAmbientDeclaration); + } + if (hasOverloads) { + checkFlagAgreementBetweenOverloads(declarations, bodyDeclaration, flagsToCheck, someNodeFlags, allNodeFlags); + checkQuestionTokenAgreementBetweenOverloads(declarations, bodyDeclaration, someHaveQuestionToken, allHaveQuestionToken); + if (bodyDeclaration) { + var signatures = getSignaturesOfSymbol(symbol); + var bodySignature = getSignatureFromDeclaration(bodyDeclaration); + for (var _a = 0, signatures_6 = signatures; _a < signatures_6.length; _a++) { + var signature = signatures_6[_a]; + if (!isImplementationCompatibleWithOverload(bodySignature, signature)) { + error(signature.declaration, ts.Diagnostics.Overload_signature_is_not_compatible_with_function_implementation); + break; + } + } + } + } + } + var DeclarationSpaces; + (function (DeclarationSpaces) { + DeclarationSpaces[DeclarationSpaces["None"] = 0] = "None"; + DeclarationSpaces[DeclarationSpaces["ExportValue"] = 1] = "ExportValue"; + DeclarationSpaces[DeclarationSpaces["ExportType"] = 2] = "ExportType"; + DeclarationSpaces[DeclarationSpaces["ExportNamespace"] = 4] = "ExportNamespace"; + })(DeclarationSpaces || (DeclarationSpaces = {})); + function checkExportsOnMergedDeclarations(node) { + if (!produceDiagnostics) { + return; + } + // if localSymbol is defined on node then node itself is exported - check is required + var symbol = node.localSymbol; + if (!symbol) { + // local symbol is undefined => this declaration is non-exported. + // however symbol might contain other declarations that are exported + symbol = getSymbolOfNode(node); + if (!symbol.exportSymbol) { + // this is a pure local symbol (all declarations are non-exported) - no need to check anything + return; + } + } + // run the check only for the first declaration in the list + if (ts.getDeclarationOfKind(symbol, node.kind) !== node) { + return; + } + var exportedDeclarationSpaces = 0 /* None */; + var nonExportedDeclarationSpaces = 0 /* None */; + var defaultExportedDeclarationSpaces = 0 /* None */; + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var d = _a[_i]; + var declarationSpaces = getDeclarationSpaces(d); + var effectiveDeclarationFlags = getEffectiveDeclarationFlags(d, 1 /* Export */ | 512 /* Default */); + if (effectiveDeclarationFlags & 1 /* Export */) { + if (effectiveDeclarationFlags & 512 /* Default */) { + defaultExportedDeclarationSpaces |= declarationSpaces; + } + else { + exportedDeclarationSpaces |= declarationSpaces; + } + } + else { + nonExportedDeclarationSpaces |= declarationSpaces; + } + } + // Spaces for anything not declared a 'default export'. + var nonDefaultExportedDeclarationSpaces = exportedDeclarationSpaces | nonExportedDeclarationSpaces; + var commonDeclarationSpacesForExportsAndLocals = exportedDeclarationSpaces & nonExportedDeclarationSpaces; + var commonDeclarationSpacesForDefaultAndNonDefault = defaultExportedDeclarationSpaces & nonDefaultExportedDeclarationSpaces; + if (commonDeclarationSpacesForExportsAndLocals || commonDeclarationSpacesForDefaultAndNonDefault) { + // declaration spaces for exported and non-exported declarations intersect + for (var _b = 0, _c = symbol.declarations; _b < _c.length; _b++) { + var d = _c[_b]; + var declarationSpaces = getDeclarationSpaces(d); + var name = ts.getNameOfDeclaration(d); + // Only error on the declarations that contributed to the intersecting spaces. + if (declarationSpaces & commonDeclarationSpacesForDefaultAndNonDefault) { + error(name, ts.Diagnostics.Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead, ts.declarationNameToString(name)); + } + else if (declarationSpaces & commonDeclarationSpacesForExportsAndLocals) { + error(name, ts.Diagnostics.Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local, ts.declarationNameToString(name)); + } + } + } + function getDeclarationSpaces(decl) { + var d = decl; + switch (d.kind) { + case 241 /* InterfaceDeclaration */: + case 242 /* TypeAliasDeclaration */: + // A jsdoc typedef and callback are, by definition, type aliases + case 304 /* JSDocTypedefTag */: + case 297 /* JSDocCallbackTag */: + return 2 /* ExportType */; + case 244 /* ModuleDeclaration */: + return ts.isAmbientModule(d) || ts.getModuleInstanceState(d) !== 0 /* NonInstantiated */ + ? 4 /* ExportNamespace */ | 1 /* ExportValue */ + : 4 /* ExportNamespace */; + case 240 /* ClassDeclaration */: + case 243 /* EnumDeclaration */: + return 2 /* ExportType */ | 1 /* ExportValue */; + case 279 /* SourceFile */: + return 2 /* ExportType */ | 1 /* ExportValue */ | 4 /* ExportNamespace */; + case 254 /* ExportAssignment */: + // Export assigned entity name expressions act as aliases and should fall through, otherwise they export values + if (!ts.isEntityNameExpression(d.expression)) { + return 1 /* ExportValue */; + } + d = d.expression; + /* falls through */ + // The below options all declare an Alias, which is allowed to merge with other values within the importing module + case 248 /* ImportEqualsDeclaration */: + case 251 /* NamespaceImport */: + case 250 /* ImportClause */: + var result_4 = 0 /* None */; + var target = resolveAlias(getSymbolOfNode(d)); + ts.forEach(target.declarations, function (d) { result_4 |= getDeclarationSpaces(d); }); + return result_4; + case 237 /* VariableDeclaration */: + case 186 /* BindingElement */: + case 239 /* FunctionDeclaration */: + case 253 /* ImportSpecifier */: // https://github.com/Microsoft/TypeScript/pull/7591 + return 1 /* ExportValue */; + default: + return ts.Debug.fail(ts.Debug.showSyntaxKind(d)); + } + } + } + function getAwaitedTypeOfPromise(type, errorNode, diagnosticMessage) { + var promisedType = getPromisedTypeOfPromise(type, errorNode); + return promisedType && getAwaitedType(promisedType, errorNode, diagnosticMessage); + } + /** + * Gets the "promised type" of a promise. + * @param type The type of the promise. + * @remarks The "promised type" of a type is the type of the "value" parameter of the "onfulfilled" callback. + */ + function getPromisedTypeOfPromise(promise, errorNode) { + // + // { // promise + // then( // thenFunction + // onfulfilled: ( // onfulfilledParameterType + // value: T // valueParameterType + // ) => any + // ): any; + // } + // + if (isTypeAny(promise)) { + return undefined; + } + var typeAsPromise = promise; + if (typeAsPromise.promisedTypeOfPromise) { + return typeAsPromise.promisedTypeOfPromise; + } + if (isReferenceToType(promise, getGlobalPromiseType(/*reportErrors*/ false))) { + return typeAsPromise.promisedTypeOfPromise = promise.typeArguments[0]; + } + var thenFunction = getTypeOfPropertyOfType(promise, "then"); // TODO: GH#18217 + if (isTypeAny(thenFunction)) { + return undefined; + } + var thenSignatures = thenFunction ? getSignaturesOfType(thenFunction, 0 /* Call */) : ts.emptyArray; + if (thenSignatures.length === 0) { + if (errorNode) { + error(errorNode, ts.Diagnostics.A_promise_must_have_a_then_method); + } + return undefined; + } + var onfulfilledParameterType = getTypeWithFacts(getUnionType(ts.map(thenSignatures, getTypeOfFirstParameterOfSignature)), 2097152 /* NEUndefinedOrNull */); + if (isTypeAny(onfulfilledParameterType)) { + return undefined; + } + var onfulfilledParameterSignatures = getSignaturesOfType(onfulfilledParameterType, 0 /* Call */); + if (onfulfilledParameterSignatures.length === 0) { + if (errorNode) { + error(errorNode, ts.Diagnostics.The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback); + } + return undefined; + } + return typeAsPromise.promisedTypeOfPromise = getUnionType(ts.map(onfulfilledParameterSignatures, getTypeOfFirstParameterOfSignature), 2 /* Subtype */); + } + /** + * Gets the "awaited type" of a type. + * @param type The type to await. + * @remarks The "awaited type" of an expression is its "promised type" if the expression is a + * Promise-like type; otherwise, it is the type of the expression. This is used to reflect + * The runtime behavior of the `await` keyword. + */ + function checkAwaitedType(type, errorNode, diagnosticMessage) { + return getAwaitedType(type, errorNode, diagnosticMessage) || errorType; + } + function getAwaitedType(type, errorNode, diagnosticMessage) { + var typeAsAwaitable = type; + if (typeAsAwaitable.awaitedTypeOfType) { + return typeAsAwaitable.awaitedTypeOfType; + } + if (isTypeAny(type)) { + return typeAsAwaitable.awaitedTypeOfType = type; + } + if (type.flags & 1048576 /* Union */) { + var types = void 0; + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var constituentType = _a[_i]; + types = ts.append(types, getAwaitedType(constituentType, errorNode, diagnosticMessage)); + } + if (!types) { + return undefined; + } + return typeAsAwaitable.awaitedTypeOfType = getUnionType(types); + } + var promisedType = getPromisedTypeOfPromise(type); + if (promisedType) { + if (type.id === promisedType.id || awaitedTypeStack.indexOf(promisedType.id) >= 0) { + // Verify that we don't have a bad actor in the form of a promise whose + // promised type is the same as the promise type, or a mutually recursive + // promise. If so, we return undefined as we cannot guess the shape. If this + // were the actual case in the JavaScript, this Promise would never resolve. + // + // An example of a bad actor with a singly-recursive promise type might + // be: + // + // interface BadPromise { + // then( + // onfulfilled: (value: BadPromise) => any, + // onrejected: (error: any) => any): BadPromise; + // } + // The above interface will pass the PromiseLike check, and return a + // promised type of `BadPromise`. Since this is a self reference, we + // don't want to keep recursing ad infinitum. + // + // An example of a bad actor in the form of a mutually-recursive + // promise type might be: + // + // interface BadPromiseA { + // then( + // onfulfilled: (value: BadPromiseB) => any, + // onrejected: (error: any) => any): BadPromiseB; + // } + // + // interface BadPromiseB { + // then( + // onfulfilled: (value: BadPromiseA) => any, + // onrejected: (error: any) => any): BadPromiseA; + // } + // + if (errorNode) { + error(errorNode, ts.Diagnostics.Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method); + } + return undefined; + } + // Keep track of the type we're about to unwrap to avoid bad recursive promise types. + // See the comments above for more information. + awaitedTypeStack.push(type.id); + var awaitedType = getAwaitedType(promisedType, errorNode, diagnosticMessage); + awaitedTypeStack.pop(); + if (!awaitedType) { + return undefined; + } + return typeAsAwaitable.awaitedTypeOfType = awaitedType; + } + // The type was not a promise, so it could not be unwrapped any further. + // As long as the type does not have a callable "then" property, it is + // safe to return the type; otherwise, an error will be reported in + // the call to getNonThenableType and we will return undefined. + // + // An example of a non-promise "thenable" might be: + // + // await { then(): void {} } + // + // The "thenable" does not match the minimal definition for a promise. When + // a Promise/A+-compatible or ES6 promise tries to adopt this value, the promise + // will never settle. We treat this as an error to help flag an early indicator + // of a runtime problem. If the user wants to return this value from an async + // function, they would need to wrap it in some other value. If they want it to + // be treated as a promise, they can cast to . + var thenFunction = getTypeOfPropertyOfType(type, "then"); + if (thenFunction && getSignaturesOfType(thenFunction, 0 /* Call */).length > 0) { + if (errorNode) { + if (!diagnosticMessage) + return ts.Debug.fail(); + error(errorNode, diagnosticMessage); + } + return undefined; + } + return typeAsAwaitable.awaitedTypeOfType = type; + } + /** + * Checks the return type of an async function to ensure it is a compatible + * Promise implementation. + * + * This checks that an async function has a valid Promise-compatible return type. + * An async function has a valid Promise-compatible return type if the resolved value + * of the return type has a construct signature that takes in an `initializer` function + * that in turn supplies a `resolve` function as one of its arguments and results in an + * object with a callable `then` signature. + * + * @param node The signature to check + */ + function checkAsyncFunctionReturnType(node, returnTypeNode) { + // As part of our emit for an async function, we will need to emit the entity name of + // the return type annotation as an expression. To meet the necessary runtime semantics + // for __awaiter, we must also check that the type of the declaration (e.g. the static + // side or "constructor" of the promise type) is compatible `PromiseConstructorLike`. + // + // An example might be (from lib.es6.d.ts): + // + // interface Promise { ... } + // interface PromiseConstructor { + // new (...): Promise; + // } + // declare var Promise: PromiseConstructor; + // + // When an async function declares a return type annotation of `Promise`, we + // need to get the type of the `Promise` variable declaration above, which would + // be `PromiseConstructor`. + // + // The same case applies to a class: + // + // declare class Promise { + // constructor(...); + // then(...): Promise; + // } + // + var returnType = getTypeFromTypeNode(returnTypeNode); + if (languageVersion >= 2 /* ES2015 */) { + if (returnType === errorType) { + return; + } + var globalPromiseType = getGlobalPromiseType(/*reportErrors*/ true); + if (globalPromiseType !== emptyGenericType && !isReferenceToType(returnType, globalPromiseType)) { + // The promise type was not a valid type reference to the global promise type, so we + // report an error and return the unknown type. + error(returnTypeNode, ts.Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type); + return; + } + } + else { + // Always mark the type node as referenced if it points to a value + markTypeNodeAsReferenced(returnTypeNode); + if (returnType === errorType) { + return; + } + var promiseConstructorName = ts.getEntityNameFromTypeNode(returnTypeNode); + if (promiseConstructorName === undefined) { + error(returnTypeNode, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, typeToString(returnType)); + return; + } + var promiseConstructorSymbol = resolveEntityName(promiseConstructorName, 67220415 /* Value */, /*ignoreErrors*/ true); + var promiseConstructorType = promiseConstructorSymbol ? getTypeOfSymbol(promiseConstructorSymbol) : errorType; + if (promiseConstructorType === errorType) { + if (promiseConstructorName.kind === 72 /* Identifier */ && promiseConstructorName.escapedText === "Promise" && getTargetType(returnType) === getGlobalPromiseType(/*reportErrors*/ false)) { + error(returnTypeNode, ts.Diagnostics.An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option); + } + else { + error(returnTypeNode, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, ts.entityNameToString(promiseConstructorName)); + } + return; + } + var globalPromiseConstructorLikeType = getGlobalPromiseConstructorLikeType(/*reportErrors*/ true); + if (globalPromiseConstructorLikeType === emptyObjectType) { + // If we couldn't resolve the global PromiseConstructorLike type we cannot verify + // compatibility with __awaiter. + error(returnTypeNode, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, ts.entityNameToString(promiseConstructorName)); + return; + } + if (!checkTypeAssignableTo(promiseConstructorType, globalPromiseConstructorLikeType, returnTypeNode, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value)) { + return; + } + // Verify there is no local declaration that could collide with the promise constructor. + var rootName = promiseConstructorName && getFirstIdentifier(promiseConstructorName); + var collidingSymbol = getSymbol(node.locals, rootName.escapedText, 67220415 /* Value */); + if (collidingSymbol) { + error(collidingSymbol.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, ts.idText(rootName), ts.entityNameToString(promiseConstructorName)); + return; + } + } + checkAwaitedType(returnType, node, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); + } + /** Check a decorator */ + function checkDecorator(node) { + var signature = getResolvedSignature(node); + var returnType = getReturnTypeOfSignature(signature); + if (returnType.flags & 1 /* Any */) { + return; + } + var expectedReturnType; + var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); + var errorInfo; + switch (node.parent.kind) { + case 240 /* ClassDeclaration */: + var classSymbol = getSymbolOfNode(node.parent); + var classConstructorType = getTypeOfSymbol(classSymbol); + expectedReturnType = getUnionType([classConstructorType, voidType]); + break; + case 151 /* Parameter */: + expectedReturnType = voidType; + errorInfo = ts.chainDiagnosticMessages( + /*details*/ undefined, ts.Diagnostics.The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any); + break; + case 154 /* PropertyDeclaration */: + expectedReturnType = voidType; + errorInfo = ts.chainDiagnosticMessages( + /*details*/ undefined, ts.Diagnostics.The_return_type_of_a_property_decorator_function_must_be_either_void_or_any); + break; + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + var methodType = getTypeOfNode(node.parent); + var descriptorType = createTypedPropertyDescriptorType(methodType); + expectedReturnType = getUnionType([descriptorType, voidType]); + break; + default: + return ts.Debug.fail(); + } + checkTypeAssignableTo(returnType, expectedReturnType, node, headMessage, function () { return errorInfo; }); + } + /** + * If a TypeNode can be resolved to a value symbol imported from an external module, it is + * marked as referenced to prevent import elision. + */ + function markTypeNodeAsReferenced(node) { + markEntityNameOrEntityExpressionAsReference(node && ts.getEntityNameFromTypeNode(node)); + } + function markEntityNameOrEntityExpressionAsReference(typeName) { + if (!typeName) + return; + var rootName = getFirstIdentifier(typeName); + var meaning = (typeName.kind === 72 /* Identifier */ ? 67897832 /* Type */ : 1920 /* Namespace */) | 2097152 /* Alias */; + var rootSymbol = resolveName(rootName, rootName.escapedText, meaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isRefernce*/ true); + if (rootSymbol + && rootSymbol.flags & 2097152 /* Alias */ + && symbolIsValue(rootSymbol) + && !isConstEnumOrConstEnumOnlyModule(resolveAlias(rootSymbol))) { + markAliasSymbolAsReferenced(rootSymbol); + } + } + /** + * This function marks the type used for metadata decorator as referenced if it is import + * from external module. + * This is different from markTypeNodeAsReferenced because it tries to simplify type nodes in + * union and intersection type + * @param node + */ + function markDecoratorMedataDataTypeNodeAsReferenced(node) { + var entityName = getEntityNameForDecoratorMetadata(node); + if (entityName && ts.isEntityName(entityName)) { + markEntityNameOrEntityExpressionAsReference(entityName); + } + } + function getEntityNameForDecoratorMetadata(node) { + if (node) { + switch (node.kind) { + case 174 /* IntersectionType */: + case 173 /* UnionType */: + return getEntityNameForDecoratorMetadataFromTypeList(node.types); + case 175 /* ConditionalType */: + return getEntityNameForDecoratorMetadataFromTypeList([node.trueType, node.falseType]); + case 177 /* ParenthesizedType */: + return getEntityNameForDecoratorMetadata(node.type); + case 164 /* TypeReference */: + return node.typeName; + } + } + } + function getEntityNameForDecoratorMetadataFromTypeList(types) { + var commonEntityName; + for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { + var typeNode = types_16[_i]; + while (typeNode.kind === 177 /* ParenthesizedType */) { + typeNode = typeNode.type; // Skip parens if need be + } + if (typeNode.kind === 132 /* NeverKeyword */) { + continue; // Always elide `never` from the union/intersection if possible + } + if (!strictNullChecks && (typeNode.kind === 96 /* NullKeyword */ || typeNode.kind === 141 /* UndefinedKeyword */)) { + continue; // Elide null and undefined from unions for metadata, just like what we did prior to the implementation of strict null checks + } + var individualEntityName = getEntityNameForDecoratorMetadata(typeNode); + if (!individualEntityName) { + // Individual is something like string number + // So it would be serialized to either that type or object + // Safe to return here + return undefined; + } + if (commonEntityName) { + // Note this is in sync with the transformation that happens for type node. + // Keep this in sync with serializeUnionOrIntersectionType + // Verify if they refer to same entity and is identifier + // return undefined if they dont match because we would emit object + if (!ts.isIdentifier(commonEntityName) || + !ts.isIdentifier(individualEntityName) || + commonEntityName.escapedText !== individualEntityName.escapedText) { + return undefined; + } + } + else { + commonEntityName = individualEntityName; + } + } + return commonEntityName; + } + function getParameterTypeNodeForDecoratorCheck(node) { + var typeNode = ts.getEffectiveTypeAnnotationNode(node); + return ts.isRestParameter(node) ? ts.getRestParameterElementType(typeNode) : typeNode; + } + /** Check the decorators of a node */ + function checkDecorators(node) { + if (!node.decorators) { + return; + } + // skip this check for nodes that cannot have decorators. These should have already had an error reported by + // checkGrammarDecorators. + if (!ts.nodeCanBeDecorated(node, node.parent, node.parent.parent)) { + return; + } + if (!compilerOptions.experimentalDecorators) { + error(node, ts.Diagnostics.Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_to_remove_this_warning); + } + var firstDecorator = node.decorators[0]; + checkExternalEmitHelpers(firstDecorator, 8 /* Decorate */); + if (node.kind === 151 /* Parameter */) { + checkExternalEmitHelpers(firstDecorator, 32 /* Param */); + } + if (compilerOptions.emitDecoratorMetadata) { + checkExternalEmitHelpers(firstDecorator, 16 /* Metadata */); + // we only need to perform these checks if we are emitting serialized type metadata for the target of a decorator. + switch (node.kind) { + case 240 /* ClassDeclaration */: + var constructor = ts.getFirstConstructorWithBody(node); + if (constructor) { + for (var _i = 0, _a = constructor.parameters; _i < _a.length; _i++) { + var parameter = _a[_i]; + markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); + } + } + break; + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + var otherKind = node.kind === 158 /* GetAccessor */ ? 159 /* SetAccessor */ : 158 /* GetAccessor */; + var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(node), otherKind); + markDecoratorMedataDataTypeNodeAsReferenced(getAnnotatedAccessorTypeNode(node) || otherAccessor && getAnnotatedAccessorTypeNode(otherAccessor)); + break; + case 156 /* MethodDeclaration */: + for (var _b = 0, _c = node.parameters; _b < _c.length; _b++) { + var parameter = _c[_b]; + markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); + } + markDecoratorMedataDataTypeNodeAsReferenced(ts.getEffectiveReturnTypeNode(node)); + break; + case 154 /* PropertyDeclaration */: + markDecoratorMedataDataTypeNodeAsReferenced(ts.getEffectiveTypeAnnotationNode(node)); + break; + case 151 /* Parameter */: + markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(node)); + var containingSignature = node.parent; + for (var _d = 0, _e = containingSignature.parameters; _d < _e.length; _d++) { + var parameter = _e[_d]; + markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); + } + break; + } + } + ts.forEach(node.decorators, checkDecorator); + } + function checkFunctionDeclaration(node) { + if (produceDiagnostics) { + checkFunctionOrMethodDeclaration(node); + checkGrammarForGenerator(node); + checkCollisionWithRequireExportsInGeneratedCode(node, node.name); + checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); + } + } + function checkJSDocTypeAliasTag(node) { + if (!node.typeExpression) { + // If the node had `@property` tags, `typeExpression` would have been set to the first property tag. + error(node.name, ts.Diagnostics.JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags); + } + if (node.name) { + checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_alias_name_cannot_be_0); + } + checkSourceElement(node.typeExpression); + } + function checkJSDocTemplateTag(node) { + checkSourceElement(node.constraint); + for (var _i = 0, _a = node.typeParameters; _i < _a.length; _i++) { + var tp = _a[_i]; + checkSourceElement(tp); + } + } + function checkJSDocTypeTag(node) { + checkSourceElement(node.typeExpression); + } + function checkJSDocParameterTag(node) { + checkSourceElement(node.typeExpression); + if (!ts.getParameterSymbolFromJSDoc(node)) { + var decl = ts.getHostSignatureFromJSDoc(node); + // don't issue an error for invalid hosts -- just functions -- + // and give a better error message when the host function mentions `arguments` + // but the tag doesn't have an array type + if (decl) { + var i = ts.getJSDocTags(decl).filter(ts.isJSDocParameterTag).indexOf(node); + if (i > -1 && i < decl.parameters.length && ts.isBindingPattern(decl.parameters[i].name)) { + return; + } + if (!containsArgumentsReference(decl)) { + error(node.name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name, ts.idText(node.name.kind === 148 /* QualifiedName */ ? node.name.right : node.name)); + } + else if (ts.findLast(ts.getJSDocTags(decl), ts.isJSDocParameterTag) === node && + node.typeExpression && node.typeExpression.type && + !isArrayType(getTypeFromTypeNode(node.typeExpression.type))) { + error(node.name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_had_an_array_type, ts.idText(node.name.kind === 148 /* QualifiedName */ ? node.name.right : node.name)); + } + } + } + } + function checkJSDocFunctionType(node) { + if (produceDiagnostics && !node.type && !ts.isJSDocConstructSignature(node)) { + reportImplicitAny(node, anyType); + } + checkSignatureDeclaration(node); + } + function checkJSDocAugmentsTag(node) { + var classLike = ts.getJSDocHost(node); + if (!ts.isClassDeclaration(classLike) && !ts.isClassExpression(classLike)) { + error(classLike, ts.Diagnostics.JSDoc_0_is_not_attached_to_a_class, ts.idText(node.tagName)); + return; + } + var augmentsTags = ts.getJSDocTags(classLike).filter(ts.isJSDocAugmentsTag); + ts.Debug.assert(augmentsTags.length > 0); + if (augmentsTags.length > 1) { + error(augmentsTags[1], ts.Diagnostics.Class_declarations_cannot_have_more_than_one_augments_or_extends_tag); + } + var name = getIdentifierFromEntityNameExpression(node.class.expression); + var extend = ts.getClassExtendsHeritageElement(classLike); + if (extend) { + var className = getIdentifierFromEntityNameExpression(extend.expression); + if (className && name.escapedText !== className.escapedText) { + error(name, ts.Diagnostics.JSDoc_0_1_does_not_match_the_extends_2_clause, ts.idText(node.tagName), ts.idText(name), ts.idText(className)); + } + } + } + function getIdentifierFromEntityNameExpression(node) { + switch (node.kind) { + case 72 /* Identifier */: + return node; + case 189 /* PropertyAccessExpression */: + return node.name; + default: + return undefined; + } + } + function checkFunctionOrMethodDeclaration(node) { + checkDecorators(node); + checkSignatureDeclaration(node); + var functionFlags = ts.getFunctionFlags(node); + // Do not use hasDynamicName here, because that returns false for well known symbols. + // We want to perform checkComputedPropertyName for all computed properties, including + // well known symbols. + if (node.name && node.name.kind === 149 /* ComputedPropertyName */) { + // This check will account for methods in class/interface declarations, + // as well as accessors in classes/object literals + checkComputedPropertyName(node.name); + } + if (!hasNonBindableDynamicName(node)) { + // first we want to check the local symbol that contain this declaration + // - if node.localSymbol !== undefined - this is current declaration is exported and localSymbol points to the local symbol + // - if node.localSymbol === undefined - this node is non-exported so we can just pick the result of getSymbolOfNode + var symbol = getSymbolOfNode(node); + var localSymbol = node.localSymbol || symbol; + // Since the javascript won't do semantic analysis like typescript, + // if the javascript file comes before the typescript file and both contain same name functions, + // checkFunctionOrConstructorSymbol wouldn't be called if we didnt ignore javascript function. + var firstDeclaration = ts.find(localSymbol.declarations, + // Get first non javascript function declaration + function (declaration) { return declaration.kind === node.kind && !(declaration.flags & 65536 /* JavaScriptFile */); }); + // Only type check the symbol once + if (node === firstDeclaration) { + checkFunctionOrConstructorSymbol(localSymbol); + } + if (symbol.parent) { + // run check once for the first declaration + if (ts.getDeclarationOfKind(symbol, node.kind) === node) { + // run check on export symbol to check that modifiers agree across all exported declarations + checkFunctionOrConstructorSymbol(symbol); + } + } + } + var body = node.kind === 155 /* MethodSignature */ ? undefined : node.body; + checkSourceElement(body); + if ((functionFlags & 1 /* Generator */) === 0) { // Async function or normal function + var returnOrPromisedType = getReturnOrPromisedType(node, functionFlags); + checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnOrPromisedType); + } + if (produceDiagnostics && !ts.getEffectiveReturnTypeNode(node)) { + // Report an implicit any error if there is no body, no explicit return type, and node is not a private method + // in an ambient context + if (ts.nodeIsMissing(body) && !isPrivateWithinAmbient(node)) { + reportImplicitAny(node, anyType); + } + if (functionFlags & 1 /* Generator */ && ts.nodeIsPresent(body)) { + // A generator with a body and no type annotation can still cause errors. It can error if the + // yielded values have no common supertype, or it can give an implicit any error if it has no + // yielded values. The only way to trigger these errors is to try checking its return type. + getReturnTypeOfSignature(getSignatureFromDeclaration(node)); + } + } + // A js function declaration can have a @type tag instead of a return type node, but that type must have a call signature + if (ts.isInJSFile(node)) { + var typeTag = ts.getJSDocTypeTag(node); + if (typeTag && typeTag.typeExpression && !getContextualCallSignature(getTypeFromTypeNode(typeTag.typeExpression), node)) { + error(typeTag, ts.Diagnostics.The_type_of_a_function_declaration_must_match_the_function_s_signature); + } + } + } + function registerForUnusedIdentifiersCheck(node) { + // May be in a call such as getTypeOfNode that happened to call this. But potentiallyUnusedIdentifiers is only defined in the scope of `checkSourceFile`. + if (produceDiagnostics && !(node.flags & 4194304 /* Ambient */)) { + var sourceFile = ts.getSourceFileOfNode(node); + var potentiallyUnusedIdentifiers = allPotentiallyUnusedIdentifiers.get(sourceFile.path); + if (!potentiallyUnusedIdentifiers) { + potentiallyUnusedIdentifiers = []; + allPotentiallyUnusedIdentifiers.set(sourceFile.path, potentiallyUnusedIdentifiers); + } + // TODO: GH#22580 + // Debug.assert(addToSeen(seenPotentiallyUnusedIdentifiers, getNodeId(node)), "Adding potentially-unused identifier twice"); + potentiallyUnusedIdentifiers.push(node); + } + } + function checkUnusedIdentifiers(potentiallyUnusedIdentifiers, addDiagnostic) { + for (var _i = 0, potentiallyUnusedIdentifiers_1 = potentiallyUnusedIdentifiers; _i < potentiallyUnusedIdentifiers_1.length; _i++) { + var node = potentiallyUnusedIdentifiers_1[_i]; + switch (node.kind) { + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + checkUnusedClassMembers(node, addDiagnostic); + checkUnusedTypeParameters(node, addDiagnostic); + break; + case 279 /* SourceFile */: + case 244 /* ModuleDeclaration */: + case 218 /* Block */: + case 246 /* CaseBlock */: + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + checkUnusedLocalsAndParameters(node, addDiagnostic); + break; + case 157 /* Constructor */: + case 196 /* FunctionExpression */: + case 239 /* FunctionDeclaration */: + case 197 /* ArrowFunction */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + if (node.body) { // Don't report unused parameters in overloads + checkUnusedLocalsAndParameters(node, addDiagnostic); + } + checkUnusedTypeParameters(node, addDiagnostic); + break; + case 155 /* MethodSignature */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + case 242 /* TypeAliasDeclaration */: + case 241 /* InterfaceDeclaration */: + checkUnusedTypeParameters(node, addDiagnostic); + break; + case 176 /* InferType */: + checkUnusedInferTypeParameter(node, addDiagnostic); + break; + default: + ts.Debug.assertNever(node, "Node should not have been registered for unused identifiers check"); + } + } + } + function errorUnusedLocal(declaration, name, addDiagnostic) { + var node = ts.getNameOfDeclaration(declaration) || declaration; + var message = isTypeDeclaration(declaration) ? ts.Diagnostics._0_is_declared_but_never_used : ts.Diagnostics._0_is_declared_but_its_value_is_never_read; + addDiagnostic(declaration, 0 /* Local */, ts.createDiagnosticForNode(node, message, name)); + } + function isIdentifierThatStartsWithUnderscore(node) { + return ts.isIdentifier(node) && ts.idText(node).charCodeAt(0) === 95 /* _ */; + } + function checkUnusedClassMembers(node, addDiagnostic) { + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + switch (member.kind) { + case 156 /* MethodDeclaration */: + case 154 /* PropertyDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + if (member.kind === 159 /* SetAccessor */ && member.symbol.flags & 32768 /* GetAccessor */) { + // Already would have reported an error on the getter. + break; + } + var symbol = getSymbolOfNode(member); + if (!symbol.isReferenced && ts.hasModifier(member, 8 /* Private */)) { + addDiagnostic(member, 0 /* Local */, ts.createDiagnosticForNode(member.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, symbolToString(symbol))); + } + break; + case 157 /* Constructor */: + for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { + var parameter = _c[_b]; + if (!parameter.symbol.isReferenced && ts.hasModifier(parameter, 8 /* Private */)) { + addDiagnostic(parameter, 0 /* Local */, ts.createDiagnosticForNode(parameter.name, ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read, ts.symbolName(parameter.symbol))); + } + } + break; + case 162 /* IndexSignature */: + case 217 /* SemicolonClassElement */: + // Can't be private + break; + default: + ts.Debug.fail(); + } + } + } + function checkUnusedInferTypeParameter(node, addDiagnostic) { + var typeParameter = node.typeParameter; + if (isTypeParameterUnused(typeParameter)) { + addDiagnostic(node, 1 /* Parameter */, ts.createDiagnosticForNode(node, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(typeParameter.name))); + } + } + function checkUnusedTypeParameters(node, addDiagnostic) { + // Only report errors on the last declaration for the type parameter container; + // this ensures that all uses have been accounted for. + if (ts.last(getSymbolOfNode(node).declarations) !== node) + return; + var typeParameters = ts.getEffectiveTypeParameterDeclarations(node); + var seenParentsWithEveryUnused = new ts.NodeSet(); + for (var _i = 0, typeParameters_2 = typeParameters; _i < typeParameters_2.length; _i++) { + var typeParameter = typeParameters_2[_i]; + if (!isTypeParameterUnused(typeParameter)) + continue; + var name = ts.idText(typeParameter.name); + var parent = typeParameter.parent; + if (parent.kind !== 176 /* InferType */ && parent.typeParameters.every(isTypeParameterUnused)) { + if (seenParentsWithEveryUnused.tryAdd(parent)) { + var range = ts.isJSDocTemplateTag(parent) + // Whole @template tag + ? ts.rangeOfNode(parent) + // Include the `<>` in the error message + : ts.rangeOfTypeParameters(parent.typeParameters); + var only = typeParameters.length === 1; + var message = only ? ts.Diagnostics._0_is_declared_but_its_value_is_never_read : ts.Diagnostics.All_type_parameters_are_unused; + var arg0 = only ? name : undefined; + addDiagnostic(typeParameter, 1 /* Parameter */, ts.createFileDiagnostic(ts.getSourceFileOfNode(parent), range.pos, range.end - range.pos, message, arg0)); + } + } + else { + addDiagnostic(typeParameter, 1 /* Parameter */, ts.createDiagnosticForNode(typeParameter, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, name)); + } + } + } + function isTypeParameterUnused(typeParameter) { + return !(getMergedSymbol(typeParameter.symbol).isReferenced & 262144 /* TypeParameter */) && !isIdentifierThatStartsWithUnderscore(typeParameter.name); + } + function addToGroup(map, key, value, getKey) { + var keyString = String(getKey(key)); + var group = map.get(keyString); + if (group) { + group[1].push(value); + } + else { + map.set(keyString, [key, [value]]); + } + } + function tryGetRootParameterDeclaration(node) { + return ts.tryCast(ts.getRootDeclaration(node), ts.isParameter); + } + function checkUnusedLocalsAndParameters(nodeWithLocals, addDiagnostic) { + if (nodeWithLocals.flags & 4194304 /* Ambient */) + return; + // Ideally we could use the ImportClause directly as a key, but must wait until we have full ES6 maps. So must store key along with value. + var unusedImports = ts.createMap(); + var unusedDestructures = ts.createMap(); + var unusedVariables = ts.createMap(); + nodeWithLocals.locals.forEach(function (local) { + // If it's purely a type parameter, ignore, will be checked in `checkUnusedTypeParameters`. + // If it's a type parameter merged with a parameter, check if the parameter-side is used. + if (local.flags & 262144 /* TypeParameter */ ? !(local.flags & 3 /* Variable */ && !(local.isReferenced & 3 /* Variable */)) : local.isReferenced || local.exportSymbol) { + return; + } + for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (ts.isAmbientModule(declaration) || + (ts.isVariableDeclaration(declaration) && ts.isForInOrOfStatement(declaration.parent.parent) || isImportedDeclaration(declaration)) && isIdentifierThatStartsWithUnderscore(declaration.name)) { + continue; + } + if (isImportedDeclaration(declaration)) { + addToGroup(unusedImports, importClauseFromImported(declaration), declaration, getNodeId); + } + else if (ts.isBindingElement(declaration) && ts.isObjectBindingPattern(declaration.parent)) { + // In `{ a, ...b }, `a` is considered used since it removes a property from `b`. `b` may still be unused though. + var lastElement = ts.last(declaration.parent.elements); + if (declaration === lastElement || !ts.last(declaration.parent.elements).dotDotDotToken) { + addToGroup(unusedDestructures, declaration.parent, declaration, getNodeId); + } + } + else if (ts.isVariableDeclaration(declaration)) { + addToGroup(unusedVariables, declaration.parent, declaration, getNodeId); + } + else { + var parameter = local.valueDeclaration && tryGetRootParameterDeclaration(local.valueDeclaration); + var name = local.valueDeclaration && ts.getNameOfDeclaration(local.valueDeclaration); + if (parameter && name) { + if (!ts.isParameterPropertyDeclaration(parameter) && !ts.parameterIsThisKeyword(parameter) && !isIdentifierThatStartsWithUnderscore(name)) { + addDiagnostic(parameter, 1 /* Parameter */, ts.createDiagnosticForNode(name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.symbolName(local))); + } + } + else { + errorUnusedLocal(declaration, ts.symbolName(local), addDiagnostic); + } + } + } + }); + unusedImports.forEach(function (_a) { + var importClause = _a[0], unuseds = _a[1]; + var importDecl = importClause.parent; + var nDeclarations = (importClause.name ? 1 : 0) + + (importClause.namedBindings ? + (importClause.namedBindings.kind === 251 /* NamespaceImport */ ? 1 : importClause.namedBindings.elements.length) + : 0); + if (nDeclarations === unuseds.length) { + addDiagnostic(importDecl, 0 /* Local */, unuseds.length === 1 + ? ts.createDiagnosticForNode(importDecl, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(ts.first(unuseds).name)) + : ts.createDiagnosticForNode(importDecl, ts.Diagnostics.All_imports_in_import_declaration_are_unused)); + } + else { + for (var _i = 0, unuseds_1 = unuseds; _i < unuseds_1.length; _i++) { + var unused = unuseds_1[_i]; + errorUnusedLocal(unused, ts.idText(unused.name), addDiagnostic); + } + } + }); + unusedDestructures.forEach(function (_a) { + var bindingPattern = _a[0], bindingElements = _a[1]; + var kind = tryGetRootParameterDeclaration(bindingPattern.parent) ? 1 /* Parameter */ : 0 /* Local */; + if (bindingPattern.elements.length === bindingElements.length) { + if (bindingElements.length === 1 && bindingPattern.parent.kind === 237 /* VariableDeclaration */ && bindingPattern.parent.parent.kind === 238 /* VariableDeclarationList */) { + addToGroup(unusedVariables, bindingPattern.parent.parent, bindingPattern.parent, getNodeId); + } + else { + addDiagnostic(bindingPattern, kind, bindingElements.length === 1 + ? ts.createDiagnosticForNode(bindingPattern, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(ts.first(bindingElements).name)) + : ts.createDiagnosticForNode(bindingPattern, ts.Diagnostics.All_destructured_elements_are_unused)); + } + } + else { + for (var _i = 0, bindingElements_1 = bindingElements; _i < bindingElements_1.length; _i++) { + var e = bindingElements_1[_i]; + addDiagnostic(e, kind, ts.createDiagnosticForNode(e, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(e.name))); + } + } + }); + unusedVariables.forEach(function (_a) { + var declarationList = _a[0], declarations = _a[1]; + if (declarationList.declarations.length === declarations.length) { + addDiagnostic(declarationList, 0 /* Local */, declarations.length === 1 + ? ts.createDiagnosticForNode(ts.first(declarations).name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(ts.first(declarations).name)) + : ts.createDiagnosticForNode(declarationList.parent.kind === 219 /* VariableStatement */ ? declarationList.parent : declarationList, ts.Diagnostics.All_variables_are_unused)); + } + else { + for (var _i = 0, declarations_5 = declarations; _i < declarations_5.length; _i++) { + var decl = declarations_5[_i]; + addDiagnostic(decl, 0 /* Local */, ts.createDiagnosticForNode(decl, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(decl.name))); + } + } + }); + } + function bindingNameText(name) { + switch (name.kind) { + case 72 /* Identifier */: + return ts.idText(name); + case 185 /* ArrayBindingPattern */: + case 184 /* ObjectBindingPattern */: + return bindingNameText(ts.cast(ts.first(name.elements), ts.isBindingElement).name); + default: + return ts.Debug.assertNever(name); + } + } + function isImportedDeclaration(node) { + return node.kind === 250 /* ImportClause */ || node.kind === 253 /* ImportSpecifier */ || node.kind === 251 /* NamespaceImport */; + } + function importClauseFromImported(decl) { + return decl.kind === 250 /* ImportClause */ ? decl : decl.kind === 251 /* NamespaceImport */ ? decl.parent : decl.parent.parent; + } + function checkBlock(node) { + // Grammar checking for SyntaxKind.Block + if (node.kind === 218 /* Block */) { + checkGrammarStatementInAmbientContext(node); + } + if (ts.isFunctionOrModuleBlock(node)) { + var saveFlowAnalysisDisabled = flowAnalysisDisabled; + ts.forEach(node.statements, checkSourceElement); + flowAnalysisDisabled = saveFlowAnalysisDisabled; + } + else { + ts.forEach(node.statements, checkSourceElement); + } + if (node.locals) { + registerForUnusedIdentifiersCheck(node); + } + } + function checkCollisionWithArgumentsInGeneratedCode(node) { + // no rest parameters \ declaration context \ overload - no codegen impact + if (languageVersion >= 2 /* ES2015 */ || compilerOptions.noEmit || !ts.hasRestParameter(node) || node.flags & 4194304 /* Ambient */ || ts.nodeIsMissing(node.body)) { + return; + } + ts.forEach(node.parameters, function (p) { + if (p.name && !ts.isBindingPattern(p.name) && p.name.escapedText === argumentsSymbol.escapedName) { + error(p, ts.Diagnostics.Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters); + } + }); + } + function needCollisionCheckForIdentifier(node, identifier, name) { + if (!(identifier && identifier.escapedText === name)) { + return false; + } + if (node.kind === 154 /* PropertyDeclaration */ || + node.kind === 153 /* PropertySignature */ || + node.kind === 156 /* MethodDeclaration */ || + node.kind === 155 /* MethodSignature */ || + node.kind === 158 /* GetAccessor */ || + node.kind === 159 /* SetAccessor */) { + // it is ok to have member named '_super' or '_this' - member access is always qualified + return false; + } + if (node.flags & 4194304 /* Ambient */) { + // ambient context - no codegen impact + return false; + } + var root = ts.getRootDeclaration(node); + if (root.kind === 151 /* Parameter */ && ts.nodeIsMissing(root.parent.body)) { + // just an overload - no codegen impact + return false; + } + return true; + } + // this function will run after checking the source file so 'CaptureThis' is correct for all nodes + function checkIfThisIsCapturedInEnclosingScope(node) { + ts.findAncestor(node, function (current) { + if (getNodeCheckFlags(current) & 4 /* CaptureThis */) { + var isDeclaration_1 = node.kind !== 72 /* Identifier */; + if (isDeclaration_1) { + error(ts.getNameOfDeclaration(node), ts.Diagnostics.Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference); + } + else { + error(node, ts.Diagnostics.Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference); + } + return true; + } + return false; + }); + } + function checkIfNewTargetIsCapturedInEnclosingScope(node) { + ts.findAncestor(node, function (current) { + if (getNodeCheckFlags(current) & 8 /* CaptureNewTarget */) { + var isDeclaration_2 = node.kind !== 72 /* Identifier */; + if (isDeclaration_2) { + error(ts.getNameOfDeclaration(node), ts.Diagnostics.Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference); + } + else { + error(node, ts.Diagnostics.Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta_property_reference); + } + return true; + } + return false; + }); + } + function checkCollisionWithRequireExportsInGeneratedCode(node, name) { + // No need to check for require or exports for ES6 modules and later + if (moduleKind >= ts.ModuleKind.ES2015 || compilerOptions.noEmit) { + return; + } + if (!needCollisionCheckForIdentifier(node, name, "require") && !needCollisionCheckForIdentifier(node, name, "exports")) { + return; + } + // Uninstantiated modules shouldnt do this check + if (ts.isModuleDeclaration(node) && ts.getModuleInstanceState(node) !== 1 /* Instantiated */) { + return; + } + // In case of variable declaration, node.parent is variable statement so look at the variable statement's parent + var parent = getDeclarationContainer(node); + if (parent.kind === 279 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent)) { + // If the declaration happens to be in external module, report error that require and exports are reserved keywords + error(name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module, ts.declarationNameToString(name), ts.declarationNameToString(name)); + } + } + function checkCollisionWithGlobalPromiseInGeneratedCode(node, name) { + if (languageVersion >= 4 /* ES2017 */ || compilerOptions.noEmit || !needCollisionCheckForIdentifier(node, name, "Promise")) { + return; + } + // Uninstantiated modules shouldnt do this check + if (ts.isModuleDeclaration(node) && ts.getModuleInstanceState(node) !== 1 /* Instantiated */) { + return; + } + // In case of variable declaration, node.parent is variable statement so look at the variable statement's parent + var parent = getDeclarationContainer(node); + if (parent.kind === 279 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent) && parent.flags & 1024 /* HasAsyncFunctions */) { + // If the declaration happens to be in external module, report error that Promise is a reserved identifier. + error(name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_functions, ts.declarationNameToString(name), ts.declarationNameToString(name)); + } + } + function checkVarDeclaredNamesNotShadowed(node) { + // - ScriptBody : StatementList + // It is a Syntax Error if any element of the LexicallyDeclaredNames of StatementList + // also occurs in the VarDeclaredNames of StatementList. + // - Block : { StatementList } + // It is a Syntax Error if any element of the LexicallyDeclaredNames of StatementList + // also occurs in the VarDeclaredNames of StatementList. + // Variable declarations are hoisted to the top of their function scope. They can shadow + // block scoped declarations, which bind tighter. this will not be flagged as duplicate definition + // by the binder as the declaration scope is different. + // A non-initialized declaration is a no-op as the block declaration will resolve before the var + // declaration. the problem is if the declaration has an initializer. this will act as a write to the + // block declared value. this is fine for let, but not const. + // Only consider declarations with initializers, uninitialized const declarations will not + // step on a let/const variable. + // Do not consider const and const declarations, as duplicate block-scoped declarations + // are handled by the binder. + // We are only looking for const declarations that step on let\const declarations from a + // different scope. e.g.: + // { + // const x = 0; // localDeclarationSymbol obtained after name resolution will correspond to this declaration + // const x = 0; // symbol for this declaration will be 'symbol' + // } + // skip block-scoped variables and parameters + if ((ts.getCombinedNodeFlags(node) & 3 /* BlockScoped */) !== 0 || ts.isParameterDeclaration(node)) { + return; + } + // skip variable declarations that don't have initializers + // NOTE: in ES6 spec initializer is required in variable declarations where name is binding pattern + // so we'll always treat binding elements as initialized + if (node.kind === 237 /* VariableDeclaration */ && !node.initializer) { + return; + } + var symbol = getSymbolOfNode(node); + if (symbol.flags & 1 /* FunctionScopedVariable */) { + if (!ts.isIdentifier(node.name)) + return ts.Debug.fail(); + var localDeclarationSymbol = resolveName(node, node.name.escapedText, 3 /* Variable */, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); + if (localDeclarationSymbol && + localDeclarationSymbol !== symbol && + localDeclarationSymbol.flags & 2 /* BlockScopedVariable */) { + if (getDeclarationNodeFlagsFromSymbol(localDeclarationSymbol) & 3 /* BlockScoped */) { + var varDeclList = ts.getAncestor(localDeclarationSymbol.valueDeclaration, 238 /* VariableDeclarationList */); + var container = varDeclList.parent.kind === 219 /* VariableStatement */ && varDeclList.parent.parent + ? varDeclList.parent.parent + : undefined; + // names of block-scoped and function scoped variables can collide only + // if block scoped variable is defined in the function\module\source file scope (because of variable hoisting) + var namesShareScope = container && + (container.kind === 218 /* Block */ && ts.isFunctionLike(container.parent) || + container.kind === 245 /* ModuleBlock */ || + container.kind === 244 /* ModuleDeclaration */ || + container.kind === 279 /* SourceFile */); + // here we know that function scoped variable is shadowed by block scoped one + // if they are defined in the same scope - binder has already reported redeclaration error + // otherwise if variable has an initializer - show error that initialization will fail + // since LHS will be block scoped name instead of function scoped + if (!namesShareScope) { + var name = symbolToString(localDeclarationSymbol); + error(node, ts.Diagnostics.Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1, name, name); + } + } + } + } + } + // Check that a parameter initializer contains no references to parameters declared to the right of itself + function checkParameterInitializer(node) { + if (ts.getRootDeclaration(node).kind !== 151 /* Parameter */) { + return; + } + var func = ts.getContainingFunction(node); + visit(node.initializer); + function visit(n) { + if (ts.isTypeNode(n) || ts.isDeclarationName(n)) { + // do not dive in types + // skip declaration names (i.e. in object literal expressions) + return; + } + if (n.kind === 189 /* PropertyAccessExpression */) { + // skip property names in property access expression + return visit(n.expression); + } + else if (n.kind === 72 /* Identifier */) { + // check FunctionLikeDeclaration.locals (stores parameters\function local variable) + // if it contains entry with a specified name + var symbol = resolveName(n, n.escapedText, 67220415 /* Value */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); + if (!symbol || symbol === unknownSymbol || !symbol.valueDeclaration) { + return; + } + if (symbol.valueDeclaration === node) { + error(n, ts.Diagnostics.Parameter_0_cannot_be_referenced_in_its_initializer, ts.declarationNameToString(node.name)); + return; + } + // locals map for function contain both parameters and function locals + // so we need to do a bit of extra work to check if reference is legal + var enclosingContainer = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); + if (enclosingContainer === func) { + if (symbol.valueDeclaration.kind === 151 /* Parameter */ || + symbol.valueDeclaration.kind === 186 /* BindingElement */) { + // it is ok to reference parameter in initializer if either + // - parameter is located strictly on the left of current parameter declaration + if (symbol.valueDeclaration.pos < node.pos) { + return; + } + // - parameter is wrapped in function-like entity + if (ts.findAncestor(n, function (current) { + if (current === node.initializer) { + return "quit"; + } + return ts.isFunctionLike(current.parent) || + // computed property names/initializers in instance property declaration of class like entities + // are executed in constructor and thus deferred + (current.parent.kind === 154 /* PropertyDeclaration */ && + !(ts.hasModifier(current.parent, 32 /* Static */)) && + ts.isClassLike(current.parent.parent)); + })) { + return; + } + // fall through to report error + } + error(n, ts.Diagnostics.Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it, ts.declarationNameToString(node.name), ts.declarationNameToString(n)); + } + } + else { + return ts.forEachChild(n, visit); + } + } + } + function convertAutoToAny(type) { + return type === autoType ? anyType : type === autoArrayType ? anyArrayType : type; + } + // Check variable, parameter, or property declaration + function checkVariableLikeDeclaration(node) { + checkDecorators(node); + if (!ts.isBindingElement(node)) { + checkSourceElement(node.type); + } + // JSDoc `function(string, string): string` syntax results in parameters with no name + if (!node.name) { + return; + } + // For a computed property, just check the initializer and exit + // Do not use hasDynamicName here, because that returns false for well known symbols. + // We want to perform checkComputedPropertyName for all computed properties, including + // well known symbols. + if (node.name.kind === 149 /* ComputedPropertyName */) { + checkComputedPropertyName(node.name); + if (node.initializer) { + checkExpressionCached(node.initializer); + } + } + if (node.kind === 186 /* BindingElement */) { + if (node.parent.kind === 184 /* ObjectBindingPattern */ && languageVersion < 6 /* ESNext */) { + checkExternalEmitHelpers(node, 4 /* Rest */); + } + // check computed properties inside property names of binding elements + if (node.propertyName && node.propertyName.kind === 149 /* ComputedPropertyName */) { + checkComputedPropertyName(node.propertyName); + } + // check private/protected variable access + var parent = node.parent.parent; + var parentType = getTypeForBindingElementParent(parent); + var name = node.propertyName || node.name; + if (!ts.isBindingPattern(name)) { + var nameText = ts.getTextOfPropertyName(name); + if (nameText) { + var property = getPropertyOfType(parentType, nameText); // TODO: GH#18217 + if (property) { + markPropertyAsReferenced(property, /*nodeForCheckWriteOnly*/ undefined, /*isThisAccess*/ false); // A destructuring is never a write-only reference. + checkPropertyAccessibility(parent, !!parent.initializer && parent.initializer.kind === 98 /* SuperKeyword */, parentType, property); + } + } + } + } + // For a binding pattern, check contained binding elements + if (ts.isBindingPattern(node.name)) { + if (node.name.kind === 185 /* ArrayBindingPattern */ && languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) { + checkExternalEmitHelpers(node, 512 /* Read */); + } + ts.forEach(node.name.elements, checkSourceElement); + } + // For a parameter declaration with an initializer, error and exit if the containing function doesn't have a body + if (node.initializer && ts.getRootDeclaration(node).kind === 151 /* Parameter */ && ts.nodeIsMissing(ts.getContainingFunction(node).body)) { + error(node, ts.Diagnostics.A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation); + return; + } + // For a binding pattern, validate the initializer and exit + if (ts.isBindingPattern(node.name)) { + // Don't validate for-in initializer as it is already an error + if (node.initializer && node.parent.parent.kind !== 226 /* ForInStatement */) { + var initializerType = checkExpressionCached(node.initializer); + if (strictNullChecks && node.name.elements.length === 0) { + checkNonNullType(initializerType, node); + } + else { + checkTypeAssignableToAndOptionallyElaborate(initializerType, getWidenedTypeForVariableLikeDeclaration(node), node, node.initializer); + } + checkParameterInitializer(node); + } + return; + } + var symbol = getSymbolOfNode(node); + var type = convertAutoToAny(getTypeOfSymbol(symbol)); + if (node === symbol.valueDeclaration) { + // Node is the primary declaration of the symbol, just validate the initializer + // Don't validate for-in initializer as it is already an error + var initializer = ts.getEffectiveInitializer(node); + if (initializer) { + var isJSObjectLiteralInitializer = ts.isInJSFile(node) && + ts.isObjectLiteralExpression(initializer) && + (initializer.properties.length === 0 || ts.isPrototypeAccess(node.name)) && + ts.hasEntries(symbol.exports); + if (!isJSObjectLiteralInitializer && node.parent.parent.kind !== 226 /* ForInStatement */) { + checkTypeAssignableToAndOptionallyElaborate(checkExpressionCached(initializer), type, node, initializer, /*headMessage*/ undefined); + checkParameterInitializer(node); + } + } + if (symbol.declarations.length > 1) { + if (ts.some(symbol.declarations, function (d) { return d !== node && ts.isVariableLike(d) && !areDeclarationFlagsIdentical(d, node); })) { + error(node.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); + } + } + } + else { + // Node is a secondary declaration, check that type is identical to primary declaration and check that + // initializer is consistent with type associated with the node + var declarationType = convertAutoToAny(getWidenedTypeForVariableLikeDeclaration(node)); + if (type !== errorType && declarationType !== errorType && + !isTypeIdenticalTo(type, declarationType) && + !(symbol.flags & 67108864 /* Assignment */)) { + errorNextVariableOrPropertyDeclarationMustHaveSameType(type, node, declarationType); + } + if (node.initializer) { + checkTypeAssignableToAndOptionallyElaborate(checkExpressionCached(node.initializer), declarationType, node, node.initializer, /*headMessage*/ undefined); + } + if (!areDeclarationFlagsIdentical(node, symbol.valueDeclaration)) { + error(node.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); + } + } + if (node.kind !== 154 /* PropertyDeclaration */ && node.kind !== 153 /* PropertySignature */) { + // We know we don't have a binding pattern or computed name here + checkExportsOnMergedDeclarations(node); + if (node.kind === 237 /* VariableDeclaration */ || node.kind === 186 /* BindingElement */) { + checkVarDeclaredNamesNotShadowed(node); + } + checkCollisionWithRequireExportsInGeneratedCode(node, node.name); + checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); + } + } + function errorNextVariableOrPropertyDeclarationMustHaveSameType(firstType, nextDeclaration, nextType) { + var nextDeclarationName = ts.getNameOfDeclaration(nextDeclaration); + var message = nextDeclaration.kind === 154 /* PropertyDeclaration */ || nextDeclaration.kind === 153 /* PropertySignature */ + ? ts.Diagnostics.Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_type_2 + : ts.Diagnostics.Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2; + error(nextDeclarationName, message, ts.declarationNameToString(nextDeclarationName), typeToString(firstType), typeToString(nextType)); + } + function areDeclarationFlagsIdentical(left, right) { + if ((left.kind === 151 /* Parameter */ && right.kind === 237 /* VariableDeclaration */) || + (left.kind === 237 /* VariableDeclaration */ && right.kind === 151 /* Parameter */)) { + // Differences in optionality between parameters and variables are allowed. + return true; + } + if (ts.hasQuestionToken(left) !== ts.hasQuestionToken(right)) { + return false; + } + var interestingFlags = 8 /* Private */ | + 16 /* Protected */ | + 256 /* Async */ | + 128 /* Abstract */ | + 64 /* Readonly */ | + 32 /* Static */; + return ts.getSelectedModifierFlags(left, interestingFlags) === ts.getSelectedModifierFlags(right, interestingFlags); + } + function checkVariableDeclaration(node) { + checkGrammarVariableDeclaration(node); + return checkVariableLikeDeclaration(node); + } + function checkBindingElement(node) { + checkGrammarBindingElement(node); + return checkVariableLikeDeclaration(node); + } + function checkVariableStatement(node) { + // Grammar checking + if (!checkGrammarDecoratorsAndModifiers(node) && !checkGrammarVariableDeclarationList(node.declarationList)) + checkGrammarForDisallowedLetOrConstStatement(node); + ts.forEach(node.declarationList.declarations, checkSourceElement); + } + function checkExpressionStatement(node) { + // Grammar checking + checkGrammarStatementInAmbientContext(node); + checkExpression(node.expression); + } + function checkIfStatement(node) { + // Grammar checking + checkGrammarStatementInAmbientContext(node); + checkTruthinessExpression(node.expression); + checkSourceElement(node.thenStatement); + if (node.thenStatement.kind === 220 /* EmptyStatement */) { + error(node.thenStatement, ts.Diagnostics.The_body_of_an_if_statement_cannot_be_the_empty_statement); + } + checkSourceElement(node.elseStatement); + } + function checkDoStatement(node) { + // Grammar checking + checkGrammarStatementInAmbientContext(node); + checkSourceElement(node.statement); + checkTruthinessExpression(node.expression); + } + function checkWhileStatement(node) { + // Grammar checking + checkGrammarStatementInAmbientContext(node); + checkTruthinessExpression(node.expression); + checkSourceElement(node.statement); + } + function checkTruthinessExpression(node, checkMode) { + var type = checkExpression(node, checkMode); + if (type.flags & 16384 /* Void */) { + error(node, ts.Diagnostics.An_expression_of_type_void_cannot_be_tested_for_truthiness); + } + return type; + } + function checkForStatement(node) { + // Grammar checking + if (!checkGrammarStatementInAmbientContext(node)) { + if (node.initializer && node.initializer.kind === 238 /* VariableDeclarationList */) { + checkGrammarVariableDeclarationList(node.initializer); + } + } + if (node.initializer) { + if (node.initializer.kind === 238 /* VariableDeclarationList */) { + ts.forEach(node.initializer.declarations, checkVariableDeclaration); + } + else { + checkExpression(node.initializer); + } + } + if (node.condition) + checkTruthinessExpression(node.condition); + if (node.incrementor) + checkExpression(node.incrementor); + checkSourceElement(node.statement); + if (node.locals) { + registerForUnusedIdentifiersCheck(node); + } + } + function checkForOfStatement(node) { + checkGrammarForInOrForOfStatement(node); + if (node.awaitModifier) { + var functionFlags = ts.getFunctionFlags(ts.getContainingFunction(node)); + if ((functionFlags & (4 /* Invalid */ | 2 /* Async */)) === 2 /* Async */ && languageVersion < 6 /* ESNext */) { + // for..await..of in an async function or async generator function prior to ESNext requires the __asyncValues helper + checkExternalEmitHelpers(node, 16384 /* ForAwaitOfIncludes */); + } + } + else if (compilerOptions.downlevelIteration && languageVersion < 2 /* ES2015 */) { + // for..of prior to ES2015 requires the __values helper when downlevelIteration is enabled + checkExternalEmitHelpers(node, 256 /* ForOfIncludes */); + } + // Check the LHS and RHS + // If the LHS is a declaration, just check it as a variable declaration, which will in turn check the RHS + // via checkRightHandSideOfForOf. + // If the LHS is an expression, check the LHS, as a destructuring assignment or as a reference. + // Then check that the RHS is assignable to it. + if (node.initializer.kind === 238 /* VariableDeclarationList */) { + checkForInOrForOfVariableDeclaration(node); + } + else { + var varExpr = node.initializer; + var iteratedType = checkRightHandSideOfForOf(node.expression, node.awaitModifier); + // There may be a destructuring assignment on the left side + if (varExpr.kind === 187 /* ArrayLiteralExpression */ || varExpr.kind === 188 /* ObjectLiteralExpression */) { + // iteratedType may be undefined. In this case, we still want to check the structure of + // varExpr, in particular making sure it's a valid LeftHandSideExpression. But we'd like + // to short circuit the type relation checking as much as possible, so we pass the unknownType. + checkDestructuringAssignment(varExpr, iteratedType || errorType); + } + else { + var leftType = checkExpression(varExpr); + checkReferenceExpression(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access); + // iteratedType will be undefined if the rightType was missing properties/signatures + // required to get its iteratedType (like [Symbol.iterator] or next). This may be + // because we accessed properties from anyType, or it may have led to an error inside + // getElementTypeOfIterable. + if (iteratedType) { + checkTypeAssignableToAndOptionallyElaborate(iteratedType, leftType, varExpr, node.expression); + } + } + } + checkSourceElement(node.statement); + if (node.locals) { + registerForUnusedIdentifiersCheck(node); + } + } + function checkForInStatement(node) { + // Grammar checking + checkGrammarForInOrForOfStatement(node); + var rightType = getNonNullableTypeIfNeeded(checkExpression(node.expression)); + // TypeScript 1.0 spec (April 2014): 5.4 + // In a 'for-in' statement of the form + // for (let VarDecl in Expr) Statement + // VarDecl must be a variable declaration without a type annotation that declares a variable of type Any, + // and Expr must be an expression of type Any, an object type, or a type parameter type. + if (node.initializer.kind === 238 /* VariableDeclarationList */) { + var variable = node.initializer.declarations[0]; + if (variable && ts.isBindingPattern(variable.name)) { + error(variable.name, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern); + } + checkForInOrForOfVariableDeclaration(node); + } + else { + // In a 'for-in' statement of the form + // for (Var in Expr) Statement + // Var must be an expression classified as a reference of type Any or the String primitive type, + // and Expr must be an expression of type Any, an object type, or a type parameter type. + var varExpr = node.initializer; + var leftType = checkExpression(varExpr); + if (varExpr.kind === 187 /* ArrayLiteralExpression */ || varExpr.kind === 188 /* ObjectLiteralExpression */) { + error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern); + } + else if (!isTypeAssignableTo(getIndexTypeOrString(rightType), leftType)) { + error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any); + } + else { + // run check only former check succeeded to avoid cascading errors + checkReferenceExpression(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access); + } + } + // unknownType is returned i.e. if node.expression is identifier whose name cannot be resolved + // in this case error about missing name is already reported - do not report extra one + if (rightType === neverType || !isTypeAssignableToKind(rightType, 67108864 /* NonPrimitive */ | 58982400 /* InstantiableNonPrimitive */)) { + error(node.expression, ts.Diagnostics.The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_but_here_has_type_0, typeToString(rightType)); + } + checkSourceElement(node.statement); + if (node.locals) { + registerForUnusedIdentifiersCheck(node); + } + } + function checkForInOrForOfVariableDeclaration(iterationStatement) { + var variableDeclarationList = iterationStatement.initializer; + // checkGrammarForInOrForOfStatement will check that there is exactly one declaration. + if (variableDeclarationList.declarations.length >= 1) { + var decl = variableDeclarationList.declarations[0]; + checkVariableDeclaration(decl); + } + } + function checkRightHandSideOfForOf(rhsExpression, awaitModifier) { + var expressionType = checkNonNullExpression(rhsExpression); + return checkIteratedTypeOrElementType(expressionType, rhsExpression, /*allowStringInput*/ true, awaitModifier !== undefined); + } + function checkIteratedTypeOrElementType(inputType, errorNode, allowStringInput, allowAsyncIterables) { + if (isTypeAny(inputType)) { + return inputType; + } + return getIteratedTypeOrElementType(inputType, errorNode, allowStringInput, allowAsyncIterables, /*checkAssignability*/ true) || anyType; + } + /** + * When consuming an iterable type in a for..of, spread, or iterator destructuring assignment + * we want to get the iterated type of an iterable for ES2015 or later, or the iterated type + * of a iterable (if defined globally) or element type of an array like for ES2015 or earlier. + */ + function getIteratedTypeOrElementType(inputType, errorNode, allowStringInput, allowAsyncIterables, checkAssignability) { + if (inputType === neverType) { + reportTypeNotIterableError(errorNode, inputType, allowAsyncIterables); // TODO: GH#18217 + return undefined; + } + var uplevelIteration = languageVersion >= 2 /* ES2015 */; + var downlevelIteration = !uplevelIteration && compilerOptions.downlevelIteration; + // Get the iterated type of an `Iterable` or `IterableIterator` only in ES2015 + // or higher, when inside of an async generator or for-await-if, or when + // downlevelIteration is requested. + if (uplevelIteration || downlevelIteration || allowAsyncIterables) { + // We only report errors for an invalid iterable type in ES2015 or higher. + var iteratedType = getIteratedTypeOfIterable(inputType, uplevelIteration ? errorNode : undefined, allowAsyncIterables, /*allowSyncIterables*/ true, checkAssignability); + if (iteratedType || uplevelIteration) { + return iteratedType; + } + } + var arrayType = inputType; + var reportedError = false; + var hasStringConstituent = false; + // If strings are permitted, remove any string-like constituents from the array type. + // This allows us to find other non-string element types from an array unioned with + // a string. + if (allowStringInput) { + if (arrayType.flags & 1048576 /* Union */) { + // After we remove all types that are StringLike, we will know if there was a string constituent + // based on whether the result of filter is a new array. + var arrayTypes = inputType.types; + var filteredTypes = ts.filter(arrayTypes, function (t) { return !(t.flags & 132 /* StringLike */); }); + if (filteredTypes !== arrayTypes) { + arrayType = getUnionType(filteredTypes, 2 /* Subtype */); + } + } + else if (arrayType.flags & 132 /* StringLike */) { + arrayType = neverType; + } + hasStringConstituent = arrayType !== inputType; + if (hasStringConstituent) { + if (languageVersion < 1 /* ES5 */) { + if (errorNode) { + error(errorNode, ts.Diagnostics.Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher); + reportedError = true; + } + } + // Now that we've removed all the StringLike types, if no constituents remain, then the entire + // arrayOrStringType was a string. + if (arrayType.flags & 131072 /* Never */) { + return stringType; + } + } + } + if (!isArrayLikeType(arrayType)) { + if (errorNode && !reportedError) { + // Which error we report depends on whether we allow strings or if there was a + // string constituent. For example, if the input type is number | string, we + // want to say that number is not an array type. But if the input was just + // number and string input is allowed, we want to say that number is not an + // array type or a string type. + var isIterable = !!getIteratedTypeOfIterable(inputType, /* errorNode */ undefined, allowAsyncIterables, /*allowSyncIterables*/ true, checkAssignability); + var diagnostic = !allowStringInput || hasStringConstituent + ? downlevelIteration + ? ts.Diagnostics.Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator + : isIterable + ? ts.Diagnostics.Type_0_is_not_an_array_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators + : ts.Diagnostics.Type_0_is_not_an_array_type + : downlevelIteration + ? ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator + : isIterable + ? ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators + : ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type; + error(errorNode, diagnostic, typeToString(arrayType)); + } + return hasStringConstituent ? stringType : undefined; + } + var arrayElementType = getIndexTypeOfType(arrayType, 1 /* Number */); + if (hasStringConstituent && arrayElementType) { + // This is just an optimization for the case where arrayOrStringType is string | string[] + if (arrayElementType.flags & 132 /* StringLike */) { + return stringType; + } + return getUnionType([arrayElementType, stringType], 2 /* Subtype */); + } + return arrayElementType; + } + /** + * We want to treat type as an iterable, and get the type it is an iterable of. The iterable + * must have the following structure (annotated with the names of the variables below): + * + * { // iterable + * [Symbol.iterator]: { // iteratorMethod + * (): Iterator + * } + * } + * + * For an async iterable, we expect the following structure: + * + * { // iterable + * [Symbol.asyncIterator]: { // iteratorMethod + * (): AsyncIterator + * } + * } + * + * T is the type we are after. At every level that involves analyzing return types + * of signatures, we union the return types of all the signatures. + * + * Another thing to note is that at any step of this process, we could run into a dead end, + * meaning either the property is missing, or we run into the anyType. If either of these things + * happens, we return undefined to signal that we could not find the iterated type. If a property + * is missing, and the previous step did not result in 'any', then we also give an error if the + * caller requested it. Then the caller can decide what to do in the case where there is no iterated + * type. This is different from returning anyType, because that would signify that we have matched the + * whole pattern and that T (above) is 'any'. + * + * For a **for-of** statement, `yield*` (in a normal generator), spread, array + * destructuring, or normal generator we will only ever look for a `[Symbol.iterator]()` + * method. + * + * For an async generator we will only ever look at the `[Symbol.asyncIterator]()` method. + * + * For a **for-await-of** statement or a `yield*` in an async generator we will look for + * the `[Symbol.asyncIterator]()` method first, and then the `[Symbol.iterator]()` method. + */ + function getIteratedTypeOfIterable(type, errorNode, allowAsyncIterables, allowSyncIterables, checkAssignability) { + if (isTypeAny(type)) { + return undefined; + } + return mapType(type, getIteratedType); + function getIteratedType(type) { + var typeAsIterable = type; + if (allowAsyncIterables) { + if (typeAsIterable.iteratedTypeOfAsyncIterable) { + return typeAsIterable.iteratedTypeOfAsyncIterable; + } + // As an optimization, if the type is an instantiation of the global `AsyncIterable` + // or the global `AsyncIterableIterator` then just grab its type argument. + if (isReferenceToType(type, getGlobalAsyncIterableType(/*reportErrors*/ false)) || + isReferenceToType(type, getGlobalAsyncIterableIteratorType(/*reportErrors*/ false))) { + return typeAsIterable.iteratedTypeOfAsyncIterable = type.typeArguments[0]; + } + } + if (allowSyncIterables) { + if (typeAsIterable.iteratedTypeOfIterable) { + return allowAsyncIterables + ? typeAsIterable.iteratedTypeOfAsyncIterable = getAwaitedType(typeAsIterable.iteratedTypeOfIterable) + : typeAsIterable.iteratedTypeOfIterable; + } + // As an optimization, if the type is an instantiation of the global `Iterable` or + // `IterableIterator` then just grab its type argument. + if (isReferenceToType(type, getGlobalIterableType(/*reportErrors*/ false)) || + isReferenceToType(type, getGlobalIterableIteratorType(/*reportErrors*/ false))) { + return allowAsyncIterables + ? typeAsIterable.iteratedTypeOfAsyncIterable = getAwaitedType(type.typeArguments[0]) + : typeAsIterable.iteratedTypeOfIterable = type.typeArguments[0]; + } + } + var asyncMethodType = allowAsyncIterables && getTypeOfPropertyOfType(type, ts.getPropertyNameForKnownSymbolName("asyncIterator")); + var methodType = asyncMethodType || (allowSyncIterables ? getTypeOfPropertyOfType(type, ts.getPropertyNameForKnownSymbolName("iterator")) : undefined); + if (isTypeAny(methodType)) { + return undefined; + } + var signatures = methodType ? getSignaturesOfType(methodType, 0 /* Call */) : undefined; + if (!ts.some(signatures)) { + if (errorNode) { + // only report on the first error + reportTypeNotIterableError(errorNode, type, allowAsyncIterables); + errorNode = undefined; + } + return undefined; + } + var returnType = getUnionType(ts.map(signatures, getReturnTypeOfSignature), 2 /* Subtype */); + var iteratedType = getIteratedTypeOfIterator(returnType, errorNode, /*isAsyncIterator*/ !!asyncMethodType); + if (checkAssignability && errorNode && iteratedType) { + // If `checkAssignability` was specified, we were called from + // `checkIteratedTypeOrElementType`. As such, we need to validate that + // the type passed in is actually an Iterable. + checkTypeAssignableTo(type, asyncMethodType + ? createAsyncIterableType(iteratedType) + : createIterableType(iteratedType), errorNode); + } + if (iteratedType) { + return allowAsyncIterables + ? typeAsIterable.iteratedTypeOfAsyncIterable = asyncMethodType ? iteratedType : getAwaitedType(iteratedType) + : typeAsIterable.iteratedTypeOfIterable = iteratedType; + } + } + } + function reportTypeNotIterableError(errorNode, type, allowAsyncIterables) { + error(errorNode, allowAsyncIterables + ? ts.Diagnostics.Type_0_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator + : ts.Diagnostics.Type_0_must_have_a_Symbol_iterator_method_that_returns_an_iterator, typeToString(type)); + } + /** + * This function has very similar logic as getIteratedTypeOfIterable, except that it operates on + * Iterators instead of Iterables. Here is the structure: + * + * { // iterator + * next: { // nextMethod + * (): { // nextResult + * value: T // nextValue + * } + * } + * } + * + * For an async iterator, we expect the following structure: + * + * { // iterator + * next: { // nextMethod + * (): PromiseLike<{ // nextResult + * value: T // nextValue + * }> + * } + * } + */ + function getIteratedTypeOfIterator(type, errorNode, isAsyncIterator) { + if (isTypeAny(type)) { + return undefined; + } + var typeAsIterator = type; + if (isAsyncIterator ? typeAsIterator.iteratedTypeOfAsyncIterator : typeAsIterator.iteratedTypeOfIterator) { + return isAsyncIterator ? typeAsIterator.iteratedTypeOfAsyncIterator : typeAsIterator.iteratedTypeOfIterator; + } + // As an optimization, if the type is an instantiation of the global `Iterator` (for + // a non-async iterator) or the global `AsyncIterator` (for an async-iterator) then + // just grab its type argument. + var getIteratorType = isAsyncIterator ? getGlobalAsyncIteratorType : getGlobalIteratorType; + if (isReferenceToType(type, getIteratorType(/*reportErrors*/ false))) { + return isAsyncIterator + ? typeAsIterator.iteratedTypeOfAsyncIterator = type.typeArguments[0] + : typeAsIterator.iteratedTypeOfIterator = type.typeArguments[0]; + } + // Both async and non-async iterators must have a `next` method. + var nextMethod = getTypeOfPropertyOfType(type, "next"); + if (isTypeAny(nextMethod)) { + return undefined; + } + var nextMethodSignatures = nextMethod ? getSignaturesOfType(nextMethod, 0 /* Call */) : ts.emptyArray; + if (nextMethodSignatures.length === 0) { + if (errorNode) { + error(errorNode, isAsyncIterator + ? ts.Diagnostics.An_async_iterator_must_have_a_next_method + : ts.Diagnostics.An_iterator_must_have_a_next_method); + } + return undefined; + } + var nextResult = getUnionType(ts.map(nextMethodSignatures, getReturnTypeOfSignature), 2 /* Subtype */); + if (isTypeAny(nextResult)) { + return undefined; + } + // For an async iterator, we must get the awaited type of the return type. + if (isAsyncIterator) { + nextResult = getAwaitedTypeOfPromise(nextResult, errorNode, ts.Diagnostics.The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property); + if (isTypeAny(nextResult)) { + return undefined; + } + } + var nextValue = nextResult && getTypeOfPropertyOfType(nextResult, "value"); + if (!nextValue) { + if (errorNode) { + error(errorNode, isAsyncIterator + ? ts.Diagnostics.The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property + : ts.Diagnostics.The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property); + } + return undefined; + } + return isAsyncIterator + ? typeAsIterator.iteratedTypeOfAsyncIterator = nextValue + : typeAsIterator.iteratedTypeOfIterator = nextValue; + } + /** + * A generator may have a return type of `Iterator`, `Iterable`, or + * `IterableIterator`. An async generator may have a return type of `AsyncIterator`, + * `AsyncIterable`, or `AsyncIterableIterator`. This function can be used to extract + * the iterated type from this return type for contextual typing and verifying signatures. + */ + function getIteratedTypeOfGenerator(returnType, isAsyncGenerator) { + if (isTypeAny(returnType)) { + return undefined; + } + return getIteratedTypeOfIterable(returnType, /*errorNode*/ undefined, /*allowAsyncIterables*/ isAsyncGenerator, /*allowSyncIterables*/ !isAsyncGenerator, /*checkAssignability*/ false) + || getIteratedTypeOfIterator(returnType, /*errorNode*/ undefined, isAsyncGenerator); + } + function checkBreakOrContinueStatement(node) { + // Grammar checking + if (!checkGrammarStatementInAmbientContext(node)) + checkGrammarBreakOrContinueStatement(node); + // TODO: Check that target label is valid + } + function isUnwrappedReturnTypeVoidOrAny(func, returnType) { + var unwrappedReturnType = (ts.getFunctionFlags(func) & 3 /* AsyncGenerator */) === 2 /* Async */ + ? getPromisedTypeOfPromise(returnType) // Async function + : returnType; // AsyncGenerator function, Generator function, or normal function + return !!unwrappedReturnType && maybeTypeOfKind(unwrappedReturnType, 16384 /* Void */ | 3 /* AnyOrUnknown */); + } + function checkReturnStatement(node) { + // Grammar checking + if (checkGrammarStatementInAmbientContext(node)) { + return; + } + var func = ts.getContainingFunction(node); + if (!func) { + grammarErrorOnFirstToken(node, ts.Diagnostics.A_return_statement_can_only_be_used_within_a_function_body); + return; + } + var signature = getSignatureFromDeclaration(func); + var returnType = getReturnTypeOfSignature(signature); + var functionFlags = ts.getFunctionFlags(func); + var isGenerator = functionFlags & 1 /* Generator */; + if (strictNullChecks || node.expression || returnType.flags & 131072 /* Never */) { + var exprType = node.expression ? checkExpressionCached(node.expression) : undefinedType; + if (isGenerator) { // AsyncGenerator function or Generator function + // A generator does not need its return expressions checked against its return type. + // Instead, the yield expressions are checked against the element type. + // TODO: Check return types of generators when return type tracking is added + // for generators. + return; + } + else if (func.kind === 159 /* SetAccessor */) { + if (node.expression) { + error(node, ts.Diagnostics.Setters_cannot_return_a_value); + } + } + else if (func.kind === 157 /* Constructor */) { + if (node.expression && !checkTypeAssignableToAndOptionallyElaborate(exprType, returnType, node, node.expression)) { + error(node, ts.Diagnostics.Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class); + } + } + else if (getReturnTypeFromAnnotation(func)) { + if (functionFlags & 2 /* Async */) { // Async function + var promisedType = getPromisedTypeOfPromise(returnType); + var awaitedType = checkAwaitedType(exprType, node, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); + if (promisedType) { + // If the function has a return type, but promisedType is + // undefined, an error will be reported in checkAsyncFunctionReturnType + // so we don't need to report one here. + checkTypeAssignableTo(awaitedType, promisedType, node); + } + } + else { + checkTypeAssignableToAndOptionallyElaborate(exprType, returnType, node, node.expression); + } + } + } + else if (func.kind !== 157 /* Constructor */ && compilerOptions.noImplicitReturns && !isUnwrappedReturnTypeVoidOrAny(func, returnType) && !isGenerator) { + // The function has a return type, but the return statement doesn't have an expression. + error(node, ts.Diagnostics.Not_all_code_paths_return_a_value); + } + } + function checkWithStatement(node) { + // Grammar checking for withStatement + if (!checkGrammarStatementInAmbientContext(node)) { + if (node.flags & 16384 /* AwaitContext */) { + grammarErrorOnFirstToken(node, ts.Diagnostics.with_statements_are_not_allowed_in_an_async_function_block); + } + } + checkExpression(node.expression); + var sourceFile = ts.getSourceFileOfNode(node); + if (!hasParseDiagnostics(sourceFile)) { + var start = ts.getSpanOfTokenAtPosition(sourceFile, node.pos).start; + var end = node.statement.pos; + grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any); + } + } + function checkSwitchStatement(node) { + // Grammar checking + checkGrammarStatementInAmbientContext(node); + var firstDefaultClause; + var hasDuplicateDefaultClause = false; + var expressionType = checkExpression(node.expression); + var expressionIsLiteral = isLiteralType(expressionType); + ts.forEach(node.caseBlock.clauses, function (clause) { + // Grammar check for duplicate default clauses, skip if we already report duplicate default clause + if (clause.kind === 272 /* DefaultClause */ && !hasDuplicateDefaultClause) { + if (firstDefaultClause === undefined) { + firstDefaultClause = clause; + } + else { + var sourceFile = ts.getSourceFileOfNode(node); + var start = ts.skipTrivia(sourceFile.text, clause.pos); + var end = clause.statements.length > 0 ? clause.statements[0].pos : clause.end; + grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.A_default_clause_cannot_appear_more_than_once_in_a_switch_statement); + hasDuplicateDefaultClause = true; + } + } + if (produceDiagnostics && clause.kind === 271 /* CaseClause */) { + // TypeScript 1.0 spec (April 2014): 5.9 + // In a 'switch' statement, each 'case' expression must be of a type that is comparable + // to or from the type of the 'switch' expression. + var caseType = checkExpression(clause.expression); + var caseIsLiteral = isLiteralType(caseType); + var comparedExpressionType = expressionType; + if (!caseIsLiteral || !expressionIsLiteral) { + caseType = caseIsLiteral ? getBaseTypeOfLiteralType(caseType) : caseType; + comparedExpressionType = getBaseTypeOfLiteralType(expressionType); + } + if (!isTypeEqualityComparableTo(comparedExpressionType, caseType)) { + // expressionType is not comparable to caseType, try the reversed check and report errors if it fails + checkTypeComparableTo(caseType, comparedExpressionType, clause.expression, /*headMessage*/ undefined); + } + } + ts.forEach(clause.statements, checkSourceElement); + }); + if (node.caseBlock.locals) { + registerForUnusedIdentifiersCheck(node.caseBlock); + } + } + function checkLabeledStatement(node) { + // Grammar checking + if (!checkGrammarStatementInAmbientContext(node)) { + ts.findAncestor(node.parent, function (current) { + if (ts.isFunctionLike(current)) { + return "quit"; + } + if (current.kind === 233 /* LabeledStatement */ && current.label.escapedText === node.label.escapedText) { + grammarErrorOnNode(node.label, ts.Diagnostics.Duplicate_label_0, ts.getTextOfNode(node.label)); + return true; + } + return false; + }); + } + // ensure that label is unique + checkSourceElement(node.statement); + } + function checkThrowStatement(node) { + // Grammar checking + if (!checkGrammarStatementInAmbientContext(node)) { + if (node.expression === undefined) { + grammarErrorAfterFirstToken(node, ts.Diagnostics.Line_break_not_permitted_here); + } + } + if (node.expression) { + checkExpression(node.expression); + } + } + function checkTryStatement(node) { + // Grammar checking + checkGrammarStatementInAmbientContext(node); + checkBlock(node.tryBlock); + var catchClause = node.catchClause; + if (catchClause) { + // Grammar checking + if (catchClause.variableDeclaration) { + if (catchClause.variableDeclaration.type) { + grammarErrorOnFirstToken(catchClause.variableDeclaration.type, ts.Diagnostics.Catch_clause_variable_cannot_have_a_type_annotation); + } + else if (catchClause.variableDeclaration.initializer) { + grammarErrorOnFirstToken(catchClause.variableDeclaration.initializer, ts.Diagnostics.Catch_clause_variable_cannot_have_an_initializer); + } + else { + var blockLocals_1 = catchClause.block.locals; + if (blockLocals_1) { + ts.forEachKey(catchClause.locals, function (caughtName) { + var blockLocal = blockLocals_1.get(caughtName); + if (blockLocal && (blockLocal.flags & 2 /* BlockScopedVariable */) !== 0) { + grammarErrorOnNode(blockLocal.valueDeclaration, ts.Diagnostics.Cannot_redeclare_identifier_0_in_catch_clause, caughtName); + } + }); + } + } + } + checkBlock(catchClause.block); + } + if (node.finallyBlock) { + checkBlock(node.finallyBlock); + } + } + function checkIndexConstraints(type) { + var declaredNumberIndexer = getIndexDeclarationOfSymbol(type.symbol, 1 /* Number */); + var declaredStringIndexer = getIndexDeclarationOfSymbol(type.symbol, 0 /* String */); + var stringIndexType = getIndexTypeOfType(type, 0 /* String */); + var numberIndexType = getIndexTypeOfType(type, 1 /* Number */); + if (stringIndexType || numberIndexType) { + ts.forEach(getPropertiesOfObjectType(type), function (prop) { + var propType = getTypeOfSymbol(prop); + checkIndexConstraintForProperty(prop, propType, type, declaredStringIndexer, stringIndexType, 0 /* String */); + checkIndexConstraintForProperty(prop, propType, type, declaredNumberIndexer, numberIndexType, 1 /* Number */); + }); + var classDeclaration = type.symbol.valueDeclaration; + if (ts.getObjectFlags(type) & 1 /* Class */ && ts.isClassLike(classDeclaration)) { + for (var _i = 0, _a = classDeclaration.members; _i < _a.length; _i++) { + var member = _a[_i]; + // Only process instance properties with computed names here. + // Static properties cannot be in conflict with indexers, + // and properties with literal names were already checked. + if (!ts.hasModifier(member, 32 /* Static */) && hasNonBindableDynamicName(member)) { + var symbol = getSymbolOfNode(member); + var propType = getTypeOfSymbol(symbol); + checkIndexConstraintForProperty(symbol, propType, type, declaredStringIndexer, stringIndexType, 0 /* String */); + checkIndexConstraintForProperty(symbol, propType, type, declaredNumberIndexer, numberIndexType, 1 /* Number */); + } + } + } + } + var errorNode; + if (stringIndexType && numberIndexType) { + errorNode = declaredNumberIndexer || declaredStringIndexer; + // condition 'errorNode === undefined' may appear if types does not declare nor string neither number indexer + if (!errorNode && (ts.getObjectFlags(type) & 2 /* Interface */)) { + var someBaseTypeHasBothIndexers = ts.forEach(getBaseTypes(type), function (base) { return getIndexTypeOfType(base, 0 /* String */) && getIndexTypeOfType(base, 1 /* Number */); }); + errorNode = someBaseTypeHasBothIndexers ? undefined : type.symbol.declarations[0]; + } + } + if (errorNode && !isTypeAssignableTo(numberIndexType, stringIndexType)) { // TODO: GH#18217 + error(errorNode, ts.Diagnostics.Numeric_index_type_0_is_not_assignable_to_string_index_type_1, typeToString(numberIndexType), typeToString(stringIndexType)); + } + function checkIndexConstraintForProperty(prop, propertyType, containingType, indexDeclaration, indexType, indexKind) { + // ESSymbol properties apply to neither string nor numeric indexers. + if (!indexType || ts.isKnownSymbol(prop)) { + return; + } + var propDeclaration = prop.valueDeclaration; + var name = propDeclaration && ts.getNameOfDeclaration(propDeclaration); + // index is numeric and property name is not valid numeric literal + if (indexKind === 1 /* Number */ && !(name ? isNumericName(name) : isNumericLiteralName(prop.escapedName))) { + return; + } + // perform property check if property or indexer is declared in 'type' + // this allows us to rule out cases when both property and indexer are inherited from the base class + var errorNode; + if (propDeclaration && name && + (propDeclaration.kind === 204 /* BinaryExpression */ || + name.kind === 149 /* ComputedPropertyName */ || + prop.parent === containingType.symbol)) { + errorNode = propDeclaration; + } + else if (indexDeclaration) { + errorNode = indexDeclaration; + } + else if (ts.getObjectFlags(containingType) & 2 /* Interface */) { + // for interfaces property and indexer might be inherited from different bases + // check if any base class already has both property and indexer. + // check should be performed only if 'type' is the first type that brings property\indexer together + var someBaseClassHasBothPropertyAndIndexer = ts.forEach(getBaseTypes(containingType), function (base) { return getPropertyOfObjectType(base, prop.escapedName) && getIndexTypeOfType(base, indexKind); }); + errorNode = someBaseClassHasBothPropertyAndIndexer ? undefined : containingType.symbol.declarations[0]; + } + if (errorNode && !isTypeAssignableTo(propertyType, indexType)) { + var errorMessage = indexKind === 0 /* String */ + ? ts.Diagnostics.Property_0_of_type_1_is_not_assignable_to_string_index_type_2 + : ts.Diagnostics.Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2; + error(errorNode, errorMessage, symbolToString(prop), typeToString(propertyType), typeToString(indexType)); + } + } + } + function checkTypeNameIsReserved(name, message) { + // TS 1.0 spec (April 2014): 3.6.1 + // The predefined type keywords are reserved and cannot be used as names of user defined types. + switch (name.escapedText) { + case "any": + case "unknown": + case "number": + case "bigint": + case "boolean": + case "string": + case "symbol": + case "void": + case "object": + error(name, message, name.escapedText); + } + } + /** + * The name cannot be used as 'Object' of user defined types with special target. + */ + function checkClassNameCollisionWithObject(name) { + if (languageVersion === 1 /* ES5 */ && name.escapedText === "Object" + && moduleKind !== ts.ModuleKind.ES2015 && moduleKind !== ts.ModuleKind.ESNext) { + error(name, ts.Diagnostics.Class_name_cannot_be_Object_when_targeting_ES5_with_module_0, ts.ModuleKind[moduleKind]); // https://github.com/Microsoft/TypeScript/issues/17494 + } + } + /** + * Check each type parameter and check that type parameters have no duplicate type parameter declarations + */ + function checkTypeParameters(typeParameterDeclarations) { + if (typeParameterDeclarations) { + var seenDefault = false; + for (var i = 0; i < typeParameterDeclarations.length; i++) { + var node = typeParameterDeclarations[i]; + checkTypeParameter(node); + if (produceDiagnostics) { + if (node.default) { + seenDefault = true; + } + else if (seenDefault) { + error(node, ts.Diagnostics.Required_type_parameters_may_not_follow_optional_type_parameters); + } + for (var j = 0; j < i; j++) { + if (typeParameterDeclarations[j].symbol === node.symbol) { + error(node.name, ts.Diagnostics.Duplicate_identifier_0, ts.declarationNameToString(node.name)); + } + } + } + } + } + } + /** Check that type parameter lists are identical across multiple declarations */ + function checkTypeParameterListsIdentical(symbol) { + if (symbol.declarations.length === 1) { + return; + } + var links = getSymbolLinks(symbol); + if (!links.typeParametersChecked) { + links.typeParametersChecked = true; + var declarations = getClassOrInterfaceDeclarationsOfSymbol(symbol); + if (declarations.length <= 1) { + return; + } + var type = getDeclaredTypeOfSymbol(symbol); + if (!areTypeParametersIdentical(declarations, type.localTypeParameters)) { + // Report an error on every conflicting declaration. + var name = symbolToString(symbol); + for (var _i = 0, declarations_6 = declarations; _i < declarations_6.length; _i++) { + var declaration = declarations_6[_i]; + error(declaration.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_type_parameters, name); + } + } + } + } + function areTypeParametersIdentical(declarations, targetParameters) { + var maxTypeArgumentCount = ts.length(targetParameters); + var minTypeArgumentCount = getMinTypeArgumentCount(targetParameters); + for (var _i = 0, declarations_7 = declarations; _i < declarations_7.length; _i++) { + var declaration = declarations_7[_i]; + // If this declaration has too few or too many type parameters, we report an error + var sourceParameters = ts.getEffectiveTypeParameterDeclarations(declaration); + var numTypeParameters = sourceParameters.length; + if (numTypeParameters < minTypeArgumentCount || numTypeParameters > maxTypeArgumentCount) { + return false; + } + for (var i = 0; i < numTypeParameters; i++) { + var source = sourceParameters[i]; + var target = targetParameters[i]; + // If the type parameter node does not have the same as the resolved type + // parameter at this position, we report an error. + if (source.name.escapedText !== target.symbol.escapedName) { + return false; + } + // If the type parameter node does not have an identical constraint as the resolved + // type parameter at this position, we report an error. + var constraint = ts.getEffectiveConstraintOfTypeParameter(source); + var sourceConstraint = constraint && getTypeFromTypeNode(constraint); + var targetConstraint = getConstraintOfTypeParameter(target); + if (sourceConstraint) { + // relax check if later interface augmentation has no constraint + if (!targetConstraint || !isTypeIdenticalTo(sourceConstraint, targetConstraint)) { + return false; + } + } + // If the type parameter node has a default and it is not identical to the default + // for the type parameter at this position, we report an error. + var sourceDefault = source.default && getTypeFromTypeNode(source.default); + var targetDefault = getDefaultFromTypeParameter(target); + if (sourceDefault && targetDefault && !isTypeIdenticalTo(sourceDefault, targetDefault)) { + return false; + } + } + } + return true; + } + function checkClassExpression(node) { + checkClassLikeDeclaration(node); + checkNodeDeferred(node); + return getTypeOfSymbol(getSymbolOfNode(node)); + } + function checkClassExpressionDeferred(node) { + ts.forEach(node.members, checkSourceElement); + registerForUnusedIdentifiersCheck(node); + } + function checkClassDeclaration(node) { + if (!node.name && !ts.hasModifier(node, 512 /* Default */)) { + grammarErrorOnFirstToken(node, ts.Diagnostics.A_class_declaration_without_the_default_modifier_must_have_a_name); + } + checkClassLikeDeclaration(node); + ts.forEach(node.members, checkSourceElement); + registerForUnusedIdentifiersCheck(node); + } + function checkClassLikeDeclaration(node) { + checkGrammarClassLikeDeclaration(node); + checkDecorators(node); + if (node.name) { + checkTypeNameIsReserved(node.name, ts.Diagnostics.Class_name_cannot_be_0); + checkCollisionWithRequireExportsInGeneratedCode(node, node.name); + checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); + if (!(node.flags & 4194304 /* Ambient */)) { + checkClassNameCollisionWithObject(node.name); + } + } + checkTypeParameters(ts.getEffectiveTypeParameterDeclarations(node)); + checkExportsOnMergedDeclarations(node); + var symbol = getSymbolOfNode(node); + var type = getDeclaredTypeOfSymbol(symbol); + var typeWithThis = getTypeWithThisArgument(type); + var staticType = getTypeOfSymbol(symbol); + checkTypeParameterListsIdentical(symbol); + checkClassForDuplicateDeclarations(node); + // Only check for reserved static identifiers on non-ambient context. + if (!(node.flags & 4194304 /* Ambient */)) { + checkClassForStaticPropertyNameConflicts(node); + } + var baseTypeNode = ts.getEffectiveBaseTypeNode(node); + if (baseTypeNode) { + if (languageVersion < 2 /* ES2015 */) { + checkExternalEmitHelpers(baseTypeNode.parent, 1 /* Extends */); + } + var baseTypes = getBaseTypes(type); + if (baseTypes.length && produceDiagnostics) { + var baseType_1 = baseTypes[0]; + var baseConstructorType = getBaseConstructorTypeOfClass(type); + var staticBaseType = getApparentType(baseConstructorType); + checkBaseTypeAccessibility(staticBaseType, baseTypeNode); + checkSourceElement(baseTypeNode.expression); + var extendsNode = ts.getClassExtendsHeritageElement(node); + if (extendsNode && extendsNode !== baseTypeNode) { + checkExpression(extendsNode.expression); + } + if (ts.some(baseTypeNode.typeArguments)) { + ts.forEach(baseTypeNode.typeArguments, checkSourceElement); + for (var _i = 0, _a = getConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments, baseTypeNode); _i < _a.length; _i++) { + var constructor = _a[_i]; + if (!checkTypeArgumentConstraints(baseTypeNode, constructor.typeParameters)) { + break; + } + } + } + var baseWithThis = getTypeWithThisArgument(baseType_1, type.thisType); + if (!checkTypeAssignableTo(typeWithThis, baseWithThis, /*errorNode*/ undefined)) { + issueMemberSpecificError(node, typeWithThis, baseWithThis, ts.Diagnostics.Class_0_incorrectly_extends_base_class_1); + } + else { + // Report static side error only when instance type is assignable + checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, ts.Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1); + } + if (baseConstructorType.flags & 8650752 /* TypeVariable */ && !isMixinConstructorType(staticType)) { + error(node.name || node, ts.Diagnostics.A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any); + } + if (!(staticBaseType.symbol && staticBaseType.symbol.flags & 32 /* Class */) && !(baseConstructorType.flags & 8650752 /* TypeVariable */)) { + // When the static base type is a "class-like" constructor function (but not actually a class), we verify + // that all instantiated base constructor signatures return the same type. We can simply compare the type + // references (as opposed to checking the structure of the types) because elsewhere we have already checked + // that the base type is a class or interface type (and not, for example, an anonymous object type). + // (Javascript constructor functions have this property trivially true since their return type is ignored.) + var constructors = getInstantiatedConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments, baseTypeNode); + if (ts.forEach(constructors, function (sig) { return !isJSConstructor(sig.declaration) && getReturnTypeOfSignature(sig) !== baseType_1; })) { + error(baseTypeNode.expression, ts.Diagnostics.Base_constructors_must_all_have_the_same_return_type); + } + } + checkKindsOfPropertyMemberOverrides(type, baseType_1); + } + } + var implementedTypeNodes = ts.getClassImplementsHeritageClauseElements(node); + if (implementedTypeNodes) { + for (var _b = 0, implementedTypeNodes_1 = implementedTypeNodes; _b < implementedTypeNodes_1.length; _b++) { + var typeRefNode = implementedTypeNodes_1[_b]; + if (!ts.isEntityNameExpression(typeRefNode.expression)) { + error(typeRefNode.expression, ts.Diagnostics.A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments); + } + checkTypeReferenceNode(typeRefNode); + if (produceDiagnostics) { + var t = getTypeFromTypeNode(typeRefNode); + if (t !== errorType) { + if (isValidBaseType(t)) { + var genericDiag = t.symbol && t.symbol.flags & 32 /* Class */ ? + ts.Diagnostics.Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass : + ts.Diagnostics.Class_0_incorrectly_implements_interface_1; + var baseWithThis = getTypeWithThisArgument(t, type.thisType); + if (!checkTypeAssignableTo(typeWithThis, baseWithThis, /*errorNode*/ undefined)) { + issueMemberSpecificError(node, typeWithThis, baseWithThis, genericDiag); + } + } + else { + error(typeRefNode, ts.Diagnostics.A_class_can_only_implement_an_object_type_or_intersection_of_object_types_with_statically_known_members); + } + } + } + } + } + if (produceDiagnostics) { + checkIndexConstraints(type); + checkTypeForDuplicateIndexSignatures(node); + checkPropertyInitialization(node); + } + } + function issueMemberSpecificError(node, typeWithThis, baseWithThis, broadDiag) { + // iterate over all implemented properties and issue errors on each one which isn't compatible, rather than the class as a whole, if possible + var issuedMemberError = false; + var _loop_8 = function (member) { + if (ts.hasStaticModifier(member)) { + return "continue"; + } + var declaredProp = member.name && getSymbolAtLocation(member.name) || getSymbolAtLocation(member); + if (declaredProp) { + var prop = getPropertyOfType(typeWithThis, declaredProp.escapedName); + var baseProp = getPropertyOfType(baseWithThis, declaredProp.escapedName); + if (prop && baseProp) { + var rootChain = function () { return ts.chainDiagnosticMessages( + /*details*/ undefined, ts.Diagnostics.Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2, symbolToString(declaredProp), typeToString(typeWithThis), typeToString(baseWithThis)); }; + if (!checkTypeAssignableTo(getTypeOfSymbol(prop), getTypeOfSymbol(baseProp), member.name || member, /*message*/ undefined, rootChain)) { + issuedMemberError = true; + } + } + } + }; + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + _loop_8(member); + } + if (!issuedMemberError) { + // check again with diagnostics to generate a less-specific error + checkTypeAssignableTo(typeWithThis, baseWithThis, node.name || node, broadDiag); + } + } + function checkBaseTypeAccessibility(type, node) { + var signatures = getSignaturesOfType(type, 1 /* Construct */); + if (signatures.length) { + var declaration = signatures[0].declaration; + if (declaration && ts.hasModifier(declaration, 8 /* Private */)) { + var typeClassDeclaration = ts.getClassLikeDeclarationOfSymbol(type.symbol); + if (!isNodeWithinClass(node, typeClassDeclaration)) { + error(node, ts.Diagnostics.Cannot_extend_a_class_0_Class_constructor_is_marked_as_private, getFullyQualifiedName(type.symbol)); + } + } + } + } + function getTargetSymbol(s) { + // if symbol is instantiated its flags are not copied from the 'target' + // so we'll need to get back original 'target' symbol to work with correct set of flags + return ts.getCheckFlags(s) & 1 /* Instantiated */ ? s.target : s; + } + function getClassOrInterfaceDeclarationsOfSymbol(symbol) { + return ts.filter(symbol.declarations, function (d) { + return d.kind === 240 /* ClassDeclaration */ || d.kind === 241 /* InterfaceDeclaration */; + }); + } + function checkKindsOfPropertyMemberOverrides(type, baseType) { + // TypeScript 1.0 spec (April 2014): 8.2.3 + // A derived class inherits all members from its base class it doesn't override. + // Inheritance means that a derived class implicitly contains all non - overridden members of the base class. + // Both public and private property members are inherited, but only public property members can be overridden. + // A property member in a derived class is said to override a property member in a base class + // when the derived class property member has the same name and kind(instance or static) + // as the base class property member. + // The type of an overriding property member must be assignable(section 3.8.4) + // to the type of the overridden property member, or otherwise a compile - time error occurs. + // Base class instance member functions can be overridden by derived class instance member functions, + // but not by other kinds of members. + // Base class instance member variables and accessors can be overridden by + // derived class instance member variables and accessors, but not by other kinds of members. + // NOTE: assignability is checked in checkClassDeclaration + var baseProperties = getPropertiesOfType(baseType); + for (var _i = 0, baseProperties_1 = baseProperties; _i < baseProperties_1.length; _i++) { + var baseProperty = baseProperties_1[_i]; + var base = getTargetSymbol(baseProperty); + if (base.flags & 4194304 /* Prototype */) { + continue; + } + var derived = getTargetSymbol(getPropertyOfObjectType(type, base.escapedName)); // TODO: GH#18217 + var baseDeclarationFlags = ts.getDeclarationModifierFlagsFromSymbol(base); + ts.Debug.assert(!!derived, "derived should point to something, even if it is the base class' declaration."); + if (derived) { + // In order to resolve whether the inherited method was overridden in the base class or not, + // we compare the Symbols obtained. Since getTargetSymbol returns the symbol on the *uninstantiated* + // type declaration, derived and base resolve to the same symbol even in the case of generic classes. + if (derived === base) { + // derived class inherits base without override/redeclaration + var derivedClassDecl = ts.getClassLikeDeclarationOfSymbol(type.symbol); + // It is an error to inherit an abstract member without implementing it or being declared abstract. + // If there is no declaration for the derived class (as in the case of class expressions), + // then the class cannot be declared abstract. + if (baseDeclarationFlags & 128 /* Abstract */ && (!derivedClassDecl || !ts.hasModifier(derivedClassDecl, 128 /* Abstract */))) { + if (derivedClassDecl.kind === 209 /* ClassExpression */) { + error(derivedClassDecl, ts.Diagnostics.Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1, symbolToString(baseProperty), typeToString(baseType)); + } + else { + error(derivedClassDecl, ts.Diagnostics.Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2, typeToString(type), symbolToString(baseProperty), typeToString(baseType)); + } + } + } + else { + // derived overrides base. + var derivedDeclarationFlags = ts.getDeclarationModifierFlagsFromSymbol(derived); + if (baseDeclarationFlags & 8 /* Private */ || derivedDeclarationFlags & 8 /* Private */) { + // either base or derived property is private - not override, skip it + continue; + } + if (isPrototypeProperty(base) || base.flags & 98308 /* PropertyOrAccessor */ && derived.flags & 98308 /* PropertyOrAccessor */) { + // method is overridden with method or property/accessor is overridden with property/accessor - correct case + continue; + } + var errorMessage = void 0; + if (isPrototypeProperty(base)) { + if (derived.flags & 98304 /* Accessor */) { + errorMessage = ts.Diagnostics.Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor; + } + else { + errorMessage = ts.Diagnostics.Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_property; + } + } + else if (base.flags & 98304 /* Accessor */) { + errorMessage = ts.Diagnostics.Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function; + } + else { + errorMessage = ts.Diagnostics.Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_function; + } + error(ts.getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage, typeToString(baseType), symbolToString(base), typeToString(type)); + } + } + } + } + function checkInheritedPropertiesAreIdentical(type, typeNode) { + var baseTypes = getBaseTypes(type); + if (baseTypes.length < 2) { + return true; + } + var seen = ts.createUnderscoreEscapedMap(); + ts.forEach(resolveDeclaredMembers(type).declaredProperties, function (p) { seen.set(p.escapedName, { prop: p, containingType: type }); }); + var ok = true; + for (var _i = 0, baseTypes_2 = baseTypes; _i < baseTypes_2.length; _i++) { + var base = baseTypes_2[_i]; + var properties = getPropertiesOfType(getTypeWithThisArgument(base, type.thisType)); + for (var _a = 0, properties_7 = properties; _a < properties_7.length; _a++) { + var prop = properties_7[_a]; + var existing = seen.get(prop.escapedName); + if (!existing) { + seen.set(prop.escapedName, { prop: prop, containingType: base }); + } + else { + var isInheritedProperty = existing.containingType !== type; + if (isInheritedProperty && !isPropertyIdenticalTo(existing.prop, prop)) { + ok = false; + var typeName1 = typeToString(existing.containingType); + var typeName2 = typeToString(base); + var errorInfo = ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Named_property_0_of_types_1_and_2_are_not_identical, symbolToString(prop), typeName1, typeName2); + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Interface_0_cannot_simultaneously_extend_types_1_and_2, typeToString(type), typeName1, typeName2); + diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(typeNode, errorInfo)); + } + } + } + } + return ok; + } + function checkPropertyInitialization(node) { + if (!strictNullChecks || !strictPropertyInitialization || node.flags & 4194304 /* Ambient */) { + return; + } + var constructor = findConstructorDeclaration(node); + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + if (isInstancePropertyWithoutInitializer(member)) { + var propName = member.name; + if (ts.isIdentifier(propName)) { + var type = getTypeOfSymbol(getSymbolOfNode(member)); + if (!(type.flags & 3 /* AnyOrUnknown */ || getFalsyFlags(type) & 32768 /* Undefined */)) { + if (!constructor || !isPropertyInitializedInConstructor(propName, type, constructor)) { + error(member.name, ts.Diagnostics.Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor, ts.declarationNameToString(propName)); + } + } + } + } + } + } + function isInstancePropertyWithoutInitializer(node) { + return node.kind === 154 /* PropertyDeclaration */ && + !ts.hasModifier(node, 32 /* Static */ | 128 /* Abstract */) && + !node.exclamationToken && + !node.initializer; + } + function isPropertyInitializedInConstructor(propName, propType, constructor) { + var reference = ts.createPropertyAccess(ts.createThis(), propName); + reference.expression.parent = reference; + reference.parent = constructor; + reference.flowNode = constructor.returnFlowNode; + var flowType = getFlowTypeOfReference(reference, propType, getOptionalType(propType)); + return !(getFalsyFlags(flowType) & 32768 /* Undefined */); + } + function checkInterfaceDeclaration(node) { + // Grammar checking + if (!checkGrammarDecoratorsAndModifiers(node)) + checkGrammarInterfaceDeclaration(node); + checkTypeParameters(node.typeParameters); + if (produceDiagnostics) { + checkTypeNameIsReserved(node.name, ts.Diagnostics.Interface_name_cannot_be_0); + checkExportsOnMergedDeclarations(node); + var symbol = getSymbolOfNode(node); + checkTypeParameterListsIdentical(symbol); + // Only check this symbol once + var firstInterfaceDecl = ts.getDeclarationOfKind(symbol, 241 /* InterfaceDeclaration */); + if (node === firstInterfaceDecl) { + var type = getDeclaredTypeOfSymbol(symbol); + var typeWithThis = getTypeWithThisArgument(type); + // run subsequent checks only if first set succeeded + if (checkInheritedPropertiesAreIdentical(type, node.name)) { + for (var _i = 0, _a = getBaseTypes(type); _i < _a.length; _i++) { + var baseType = _a[_i]; + checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(baseType, type.thisType), node.name, ts.Diagnostics.Interface_0_incorrectly_extends_interface_1); + } + checkIndexConstraints(type); + } + } + checkObjectTypeForDuplicateDeclarations(node); + } + ts.forEach(ts.getInterfaceBaseTypeNodes(node), function (heritageElement) { + if (!ts.isEntityNameExpression(heritageElement.expression)) { + error(heritageElement.expression, ts.Diagnostics.An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments); + } + checkTypeReferenceNode(heritageElement); + }); + ts.forEach(node.members, checkSourceElement); + if (produceDiagnostics) { + checkTypeForDuplicateIndexSignatures(node); + registerForUnusedIdentifiersCheck(node); + } + } + function checkTypeAliasDeclaration(node) { + // Grammar checking + checkGrammarDecoratorsAndModifiers(node); + checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_alias_name_cannot_be_0); + checkTypeParameters(node.typeParameters); + checkSourceElement(node.type); + registerForUnusedIdentifiersCheck(node); + } + function computeEnumMemberValues(node) { + var nodeLinks = getNodeLinks(node); + if (!(nodeLinks.flags & 16384 /* EnumValuesComputed */)) { + nodeLinks.flags |= 16384 /* EnumValuesComputed */; + var autoValue = 0; + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + var value = computeMemberValue(member, autoValue); + getNodeLinks(member).enumMemberValue = value; + autoValue = typeof value === "number" ? value + 1 : undefined; + } + } + } + function computeMemberValue(member, autoValue) { + if (isComputedNonLiteralName(member.name)) { + error(member.name, ts.Diagnostics.Computed_property_names_are_not_allowed_in_enums); + } + else { + var text = ts.getTextOfPropertyName(member.name); + if (isNumericLiteralName(text) && !isInfinityOrNaNString(text)) { + error(member.name, ts.Diagnostics.An_enum_member_cannot_have_a_numeric_name); + } + } + if (member.initializer) { + return computeConstantValue(member); + } + // In ambient enum declarations that specify no const modifier, enum member declarations that omit + // a value are considered computed members (as opposed to having auto-incremented values). + if (member.parent.flags & 4194304 /* Ambient */ && !ts.isEnumConst(member.parent)) { + return undefined; + } + // If the member declaration specifies no value, the member is considered a constant enum member. + // If the member is the first member in the enum declaration, it is assigned the value zero. + // Otherwise, it is assigned the value of the immediately preceding member plus one, and an error + // occurs if the immediately preceding member is not a constant enum member. + if (autoValue !== undefined) { + return autoValue; + } + error(member.name, ts.Diagnostics.Enum_member_must_have_initializer); + return undefined; + } + function computeConstantValue(member) { + var enumKind = getEnumKind(getSymbolOfNode(member.parent)); + var isConstEnum = ts.isEnumConst(member.parent); + var initializer = member.initializer; + var value = enumKind === 1 /* Literal */ && !isLiteralEnumMember(member) ? undefined : evaluate(initializer); + if (value !== undefined) { + if (isConstEnum && typeof value === "number" && !isFinite(value)) { + error(initializer, isNaN(value) ? + ts.Diagnostics.const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN : + ts.Diagnostics.const_enum_member_initializer_was_evaluated_to_a_non_finite_value); + } + } + else if (enumKind === 1 /* Literal */) { + error(initializer, ts.Diagnostics.Computed_values_are_not_permitted_in_an_enum_with_string_valued_members); + return 0; + } + else if (isConstEnum) { + error(initializer, ts.Diagnostics.In_const_enum_declarations_member_initializer_must_be_constant_expression); + } + else if (member.parent.flags & 4194304 /* Ambient */) { + error(initializer, ts.Diagnostics.In_ambient_enum_declarations_member_initializer_must_be_constant_expression); + } + else { + // Only here do we need to check that the initializer is assignable to the enum type. + checkTypeAssignableTo(checkExpression(initializer), getDeclaredTypeOfSymbol(getSymbolOfNode(member.parent)), initializer, /*headMessage*/ undefined); + } + return value; + function evaluate(expr) { + switch (expr.kind) { + case 202 /* PrefixUnaryExpression */: + var value_2 = evaluate(expr.operand); + if (typeof value_2 === "number") { + switch (expr.operator) { + case 38 /* PlusToken */: return value_2; + case 39 /* MinusToken */: return -value_2; + case 53 /* TildeToken */: return ~value_2; + } + } + break; + case 204 /* BinaryExpression */: + var left = evaluate(expr.left); + var right = evaluate(expr.right); + if (typeof left === "number" && typeof right === "number") { + switch (expr.operatorToken.kind) { + case 50 /* BarToken */: return left | right; + case 49 /* AmpersandToken */: return left & right; + case 47 /* GreaterThanGreaterThanToken */: return left >> right; + case 48 /* GreaterThanGreaterThanGreaterThanToken */: return left >>> right; + case 46 /* LessThanLessThanToken */: return left << right; + case 51 /* CaretToken */: return left ^ right; + case 40 /* AsteriskToken */: return left * right; + case 42 /* SlashToken */: return left / right; + case 38 /* PlusToken */: return left + right; + case 39 /* MinusToken */: return left - right; + case 43 /* PercentToken */: return left % right; + case 41 /* AsteriskAsteriskToken */: return Math.pow(left, right); + } + } + else if (typeof left === "string" && typeof right === "string" && expr.operatorToken.kind === 38 /* PlusToken */) { + return left + right; + } + break; + case 10 /* StringLiteral */: + return expr.text; + case 8 /* NumericLiteral */: + checkGrammarNumericLiteral(expr); + return +expr.text; + case 195 /* ParenthesizedExpression */: + return evaluate(expr.expression); + case 72 /* Identifier */: + var identifier = expr; + if (isInfinityOrNaNString(identifier.escapedText)) { + return +(identifier.escapedText); + } + return ts.nodeIsMissing(expr) ? 0 : evaluateEnumMember(expr, getSymbolOfNode(member.parent), identifier.escapedText); + case 190 /* ElementAccessExpression */: + case 189 /* PropertyAccessExpression */: + var ex = expr; + if (isConstantMemberAccess(ex)) { + var type = getTypeOfExpression(ex.expression); + if (type.symbol && type.symbol.flags & 384 /* Enum */) { + var name = void 0; + if (ex.kind === 189 /* PropertyAccessExpression */) { + name = ex.name.escapedText; + } + else { + var argument = ex.argumentExpression; + ts.Debug.assert(ts.isLiteralExpression(argument)); + name = ts.escapeLeadingUnderscores(argument.text); + } + return evaluateEnumMember(expr, type.symbol, name); + } + } + break; + } + return undefined; + } + function evaluateEnumMember(expr, enumSymbol, name) { + var memberSymbol = enumSymbol.exports.get(name); + if (memberSymbol) { + var declaration = memberSymbol.valueDeclaration; + if (declaration !== member) { + if (isBlockScopedNameDeclaredBeforeUse(declaration, member)) { + return getEnumMemberValue(declaration); + } + error(expr, ts.Diagnostics.A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums); + return 0; + } + } + return undefined; + } + } + function isConstantMemberAccess(node) { + return node.kind === 72 /* Identifier */ || + node.kind === 189 /* PropertyAccessExpression */ && isConstantMemberAccess(node.expression) || + node.kind === 190 /* ElementAccessExpression */ && isConstantMemberAccess(node.expression) && + node.argumentExpression.kind === 10 /* StringLiteral */; + } + function checkEnumDeclaration(node) { + if (!produceDiagnostics) { + return; + } + // Grammar checking + checkGrammarDecoratorsAndModifiers(node); + checkTypeNameIsReserved(node.name, ts.Diagnostics.Enum_name_cannot_be_0); + checkCollisionWithRequireExportsInGeneratedCode(node, node.name); + checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); + checkExportsOnMergedDeclarations(node); + computeEnumMemberValues(node); + var enumIsConst = ts.isEnumConst(node); + if (compilerOptions.isolatedModules && enumIsConst && node.flags & 4194304 /* Ambient */) { + error(node.name, ts.Diagnostics.Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided); + } + // Spec 2014 - Section 9.3: + // It isn't possible for one enum declaration to continue the automatic numbering sequence of another, + // and when an enum type has multiple declarations, only one declaration is permitted to omit a value + // for the first member. + // + // Only perform this check once per symbol + var enumSymbol = getSymbolOfNode(node); + var firstDeclaration = ts.getDeclarationOfKind(enumSymbol, node.kind); + if (node === firstDeclaration) { + if (enumSymbol.declarations.length > 1) { + // check that const is placed\omitted on all enum declarations + ts.forEach(enumSymbol.declarations, function (decl) { + if (ts.isEnumDeclaration(decl) && ts.isEnumConst(decl) !== enumIsConst) { + error(ts.getNameOfDeclaration(decl), ts.Diagnostics.Enum_declarations_must_all_be_const_or_non_const); + } + }); + } + var seenEnumMissingInitialInitializer_1 = false; + ts.forEach(enumSymbol.declarations, function (declaration) { + // return true if we hit a violation of the rule, false otherwise + if (declaration.kind !== 243 /* EnumDeclaration */) { + return false; + } + var enumDeclaration = declaration; + if (!enumDeclaration.members.length) { + return false; + } + var firstEnumMember = enumDeclaration.members[0]; + if (!firstEnumMember.initializer) { + if (seenEnumMissingInitialInitializer_1) { + error(firstEnumMember.name, ts.Diagnostics.In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enum_element); + } + else { + seenEnumMissingInitialInitializer_1 = true; + } + } + }); + } + } + function getFirstNonAmbientClassOrFunctionDeclaration(symbol) { + var declarations = symbol.declarations; + for (var _i = 0, declarations_8 = declarations; _i < declarations_8.length; _i++) { + var declaration = declarations_8[_i]; + if ((declaration.kind === 240 /* ClassDeclaration */ || + (declaration.kind === 239 /* FunctionDeclaration */ && ts.nodeIsPresent(declaration.body))) && + !(declaration.flags & 4194304 /* Ambient */)) { + return declaration; + } + } + return undefined; + } + function inSameLexicalScope(node1, node2) { + var container1 = ts.getEnclosingBlockScopeContainer(node1); + var container2 = ts.getEnclosingBlockScopeContainer(node2); + if (isGlobalSourceFile(container1)) { + return isGlobalSourceFile(container2); + } + else if (isGlobalSourceFile(container2)) { + return false; + } + else { + return container1 === container2; + } + } + function checkModuleDeclaration(node) { + if (produceDiagnostics) { + // Grammar checking + var isGlobalAugmentation = ts.isGlobalScopeAugmentation(node); + var inAmbientContext = node.flags & 4194304 /* Ambient */; + if (isGlobalAugmentation && !inAmbientContext) { + error(node.name, ts.Diagnostics.Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambient_context); + } + var isAmbientExternalModule = ts.isAmbientModule(node); + var contextErrorMessage = isAmbientExternalModule + ? ts.Diagnostics.An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file + : ts.Diagnostics.A_namespace_declaration_is_only_allowed_in_a_namespace_or_module; + if (checkGrammarModuleElementContext(node, contextErrorMessage)) { + // If we hit a module declaration in an illegal context, just bail out to avoid cascading errors. + return; + } + if (!checkGrammarDecoratorsAndModifiers(node)) { + if (!inAmbientContext && node.name.kind === 10 /* StringLiteral */) { + grammarErrorOnNode(node.name, ts.Diagnostics.Only_ambient_modules_can_use_quoted_names); + } + } + if (ts.isIdentifier(node.name)) { + checkCollisionWithRequireExportsInGeneratedCode(node, node.name); + checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); + } + checkExportsOnMergedDeclarations(node); + var symbol = getSymbolOfNode(node); + // The following checks only apply on a non-ambient instantiated module declaration. + if (symbol.flags & 512 /* ValueModule */ + && symbol.declarations.length > 1 + && !inAmbientContext + && isInstantiatedModule(node, !!compilerOptions.preserveConstEnums || !!compilerOptions.isolatedModules)) { + var firstNonAmbientClassOrFunc = getFirstNonAmbientClassOrFunctionDeclaration(symbol); + if (firstNonAmbientClassOrFunc) { + if (ts.getSourceFileOfNode(node) !== ts.getSourceFileOfNode(firstNonAmbientClassOrFunc)) { + error(node.name, ts.Diagnostics.A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merged); + } + else if (node.pos < firstNonAmbientClassOrFunc.pos) { + error(node.name, ts.Diagnostics.A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged); + } + } + // if the module merges with a class declaration in the same lexical scope, + // we need to track this to ensure the correct emit. + var mergedClass = ts.getDeclarationOfKind(symbol, 240 /* ClassDeclaration */); + if (mergedClass && + inSameLexicalScope(node, mergedClass)) { + getNodeLinks(node).flags |= 32768 /* LexicalModuleMergesWithClass */; + } + } + if (isAmbientExternalModule) { + if (ts.isExternalModuleAugmentation(node)) { + // body of the augmentation should be checked for consistency only if augmentation was applied to its target (either global scope or module) + // otherwise we'll be swamped in cascading errors. + // We can detect if augmentation was applied using following rules: + // - augmentation for a global scope is always applied + // - augmentation for some external module is applied if symbol for augmentation is merged (it was combined with target module). + var checkBody = isGlobalAugmentation || (getSymbolOfNode(node).flags & 33554432 /* Transient */); + if (checkBody && node.body) { + for (var _i = 0, _a = node.body.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + checkModuleAugmentationElement(statement, isGlobalAugmentation); + } + } + } + else if (isGlobalSourceFile(node.parent)) { + if (isGlobalAugmentation) { + error(node.name, ts.Diagnostics.Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_declarations); + } + else if (ts.isExternalModuleNameRelative(ts.getTextOfIdentifierOrLiteral(node.name))) { + error(node.name, ts.Diagnostics.Ambient_module_declaration_cannot_specify_relative_module_name); + } + } + else { + if (isGlobalAugmentation) { + error(node.name, ts.Diagnostics.Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_declarations); + } + else { + // Node is not an augmentation and is not located on the script level. + // This means that this is declaration of ambient module that is located in other module or namespace which is prohibited. + error(node.name, ts.Diagnostics.Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces); + } + } + } + } + if (node.body) { + checkSourceElement(node.body); + if (!ts.isGlobalScopeAugmentation(node)) { + registerForUnusedIdentifiersCheck(node); + } + } + } + function checkModuleAugmentationElement(node, isGlobalAugmentation) { + switch (node.kind) { + case 219 /* VariableStatement */: + // error each individual name in variable statement instead of marking the entire variable statement + for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + checkModuleAugmentationElement(decl, isGlobalAugmentation); + } + break; + case 254 /* ExportAssignment */: + case 255 /* ExportDeclaration */: + grammarErrorOnFirstToken(node, ts.Diagnostics.Exports_and_export_assignments_are_not_permitted_in_module_augmentations); + break; + case 248 /* ImportEqualsDeclaration */: + case 249 /* ImportDeclaration */: + grammarErrorOnFirstToken(node, ts.Diagnostics.Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_module); + break; + case 186 /* BindingElement */: + case 237 /* VariableDeclaration */: + var name = node.name; + if (ts.isBindingPattern(name)) { + for (var _b = 0, _c = name.elements; _b < _c.length; _b++) { + var el = _c[_b]; + // mark individual names in binding pattern + checkModuleAugmentationElement(el, isGlobalAugmentation); + } + break; + } + // falls through + case 240 /* ClassDeclaration */: + case 243 /* EnumDeclaration */: + case 239 /* FunctionDeclaration */: + case 241 /* InterfaceDeclaration */: + case 244 /* ModuleDeclaration */: + case 242 /* TypeAliasDeclaration */: + if (isGlobalAugmentation) { + return; + } + var symbol = getSymbolOfNode(node); + if (symbol) { + // module augmentations cannot introduce new names on the top level scope of the module + // this is done it two steps + // 1. quick check - if symbol for node is not merged - this is local symbol to this augmentation - report error + // 2. main check - report error if value declaration of the parent symbol is module augmentation) + var reportError = !(symbol.flags & 33554432 /* Transient */); + if (!reportError) { + // symbol should not originate in augmentation + reportError = !!symbol.parent && ts.isExternalModuleAugmentation(symbol.parent.declarations[0]); + } + } + break; + } + } + function getFirstIdentifier(node) { + switch (node.kind) { + case 72 /* Identifier */: + return node; + case 148 /* QualifiedName */: + do { + node = node.left; + } while (node.kind !== 72 /* Identifier */); + return node; + case 189 /* PropertyAccessExpression */: + do { + node = node.expression; + } while (node.kind !== 72 /* Identifier */); + return node; + } + } + function checkExternalImportOrExportDeclaration(node) { + var moduleName = ts.getExternalModuleName(node); + if (!moduleName || ts.nodeIsMissing(moduleName)) { + // Should be a parse error. + return false; + } + if (!ts.isStringLiteral(moduleName)) { + error(moduleName, ts.Diagnostics.String_literal_expected); + return false; + } + var inAmbientExternalModule = node.parent.kind === 245 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent); + if (node.parent.kind !== 279 /* SourceFile */ && !inAmbientExternalModule) { + error(moduleName, node.kind === 255 /* ExportDeclaration */ ? + ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace : + ts.Diagnostics.Import_declarations_in_a_namespace_cannot_reference_a_module); + return false; + } + if (inAmbientExternalModule && ts.isExternalModuleNameRelative(moduleName.text)) { + // we have already reported errors on top level imports\exports in external module augmentations in checkModuleDeclaration + // no need to do this again. + if (!isTopLevelInExternalModuleAugmentation(node)) { + // TypeScript 1.0 spec (April 2013): 12.1.6 + // An ExternalImportDeclaration in an AmbientExternalModuleDeclaration may reference + // other external modules only through top - level external module names. + // Relative external module names are not permitted. + error(node, ts.Diagnostics.Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relative_module_name); + return false; + } + } + return true; + } + function checkAliasSymbol(node) { + var symbol = getSymbolOfNode(node); + var target = resolveAlias(symbol); + if (target !== unknownSymbol) { + // For external modules symbol represent local symbol for an alias. + // This local symbol will merge any other local declarations (excluding other aliases) + // and symbol.flags will contains combined representation for all merged declaration. + // Based on symbol.flags we can compute a set of excluded meanings (meaning that resolved alias should not have, + // otherwise it will conflict with some local declaration). Note that in addition to normal flags we include matching SymbolFlags.Export* + // in order to prevent collisions with declarations that were exported from the current module (they still contribute to local names). + var excludedMeanings = (symbol.flags & (67220415 /* Value */ | 1048576 /* ExportValue */) ? 67220415 /* Value */ : 0) | + (symbol.flags & 67897832 /* Type */ ? 67897832 /* Type */ : 0) | + (symbol.flags & 1920 /* Namespace */ ? 1920 /* Namespace */ : 0); + if (target.flags & excludedMeanings) { + var message = node.kind === 257 /* ExportSpecifier */ ? + ts.Diagnostics.Export_declaration_conflicts_with_exported_declaration_of_0 : + ts.Diagnostics.Import_declaration_conflicts_with_local_declaration_of_0; + error(node, message, symbolToString(symbol)); + } + // Don't allow to re-export something with no value side when `--isolatedModules` is set. + if (compilerOptions.isolatedModules + && node.kind === 257 /* ExportSpecifier */ + && !(target.flags & 67220415 /* Value */) + && !(node.flags & 4194304 /* Ambient */)) { + error(node, ts.Diagnostics.Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided); + } + } + } + function checkImportBinding(node) { + checkCollisionWithRequireExportsInGeneratedCode(node, node.name); + checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); + checkAliasSymbol(node); + } + function checkImportDeclaration(node) { + if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_import_declaration_can_only_be_used_in_a_namespace_or_module)) { + // If we hit an import declaration in an illegal context, just bail out to avoid cascading errors. + return; + } + if (!checkGrammarDecoratorsAndModifiers(node) && ts.hasModifiers(node)) { + grammarErrorOnFirstToken(node, ts.Diagnostics.An_import_declaration_cannot_have_modifiers); + } + if (checkExternalImportOrExportDeclaration(node)) { + var importClause = node.importClause; + if (importClause) { + if (importClause.name) { + checkImportBinding(importClause); + } + if (importClause.namedBindings) { + if (importClause.namedBindings.kind === 251 /* NamespaceImport */) { + checkImportBinding(importClause.namedBindings); + } + else { + var moduleExisted = resolveExternalModuleName(node, node.moduleSpecifier); + if (moduleExisted) { + ts.forEach(importClause.namedBindings.elements, checkImportBinding); + } + } + } + } + } + } + function checkImportEqualsDeclaration(node) { + if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_import_declaration_can_only_be_used_in_a_namespace_or_module)) { + // If we hit an import declaration in an illegal context, just bail out to avoid cascading errors. + return; + } + checkGrammarDecoratorsAndModifiers(node); + if (ts.isInternalModuleImportEqualsDeclaration(node) || checkExternalImportOrExportDeclaration(node)) { + checkImportBinding(node); + if (ts.hasModifier(node, 1 /* Export */)) { + markExportAsReferenced(node); + } + if (node.moduleReference.kind !== 259 /* ExternalModuleReference */) { + var target = resolveAlias(getSymbolOfNode(node)); + if (target !== unknownSymbol) { + if (target.flags & 67220415 /* Value */) { + // Target is a value symbol, check that it is not hidden by a local declaration with the same name + var moduleName = getFirstIdentifier(node.moduleReference); + if (!(resolveEntityName(moduleName, 67220415 /* Value */ | 1920 /* Namespace */).flags & 1920 /* Namespace */)) { + error(moduleName, ts.Diagnostics.Module_0_is_hidden_by_a_local_declaration_with_the_same_name, ts.declarationNameToString(moduleName)); + } + } + if (target.flags & 67897832 /* Type */) { + checkTypeNameIsReserved(node.name, ts.Diagnostics.Import_name_cannot_be_0); + } + } + } + else { + if (moduleKind >= ts.ModuleKind.ES2015 && !(node.flags & 4194304 /* Ambient */)) { + // Import equals declaration is deprecated in es6 or above + grammarErrorOnNode(node, ts.Diagnostics.Import_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_import_Asterisk_as_ns_from_mod_import_a_from_mod_import_d_from_mod_or_another_module_format_instead); + } + } + } + } + function checkExportDeclaration(node) { + if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_export_declaration_can_only_be_used_in_a_module)) { + // If we hit an export in an illegal context, just bail out to avoid cascading errors. + return; + } + if (!checkGrammarDecoratorsAndModifiers(node) && ts.hasModifiers(node)) { + grammarErrorOnFirstToken(node, ts.Diagnostics.An_export_declaration_cannot_have_modifiers); + } + if (!node.moduleSpecifier || checkExternalImportOrExportDeclaration(node)) { + if (node.exportClause) { + // export { x, y } + // export { x, y } from "foo" + ts.forEach(node.exportClause.elements, checkExportSpecifier); + var inAmbientExternalModule = node.parent.kind === 245 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent); + var inAmbientNamespaceDeclaration = !inAmbientExternalModule && node.parent.kind === 245 /* ModuleBlock */ && + !node.moduleSpecifier && node.flags & 4194304 /* Ambient */; + if (node.parent.kind !== 279 /* SourceFile */ && !inAmbientExternalModule && !inAmbientNamespaceDeclaration) { + error(node, ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace); + } + } + else { + // export * from "foo" + var moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier); + if (moduleSymbol && hasExportAssignmentSymbol(moduleSymbol)) { + error(node.moduleSpecifier, ts.Diagnostics.Module_0_uses_export_and_cannot_be_used_with_export_Asterisk, symbolToString(moduleSymbol)); + } + if (moduleKind !== ts.ModuleKind.System && moduleKind !== ts.ModuleKind.ES2015 && moduleKind !== ts.ModuleKind.ESNext) { + checkExternalEmitHelpers(node, 32768 /* ExportStar */); + } + } + } + } + function checkGrammarModuleElementContext(node, errorMessage) { + var isInAppropriateContext = node.parent.kind === 279 /* SourceFile */ || node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 244 /* ModuleDeclaration */; + if (!isInAppropriateContext) { + grammarErrorOnFirstToken(node, errorMessage); + } + return !isInAppropriateContext; + } + function checkExportSpecifier(node) { + checkAliasSymbol(node); + if (ts.getEmitDeclarations(compilerOptions)) { + collectLinkedAliases(node.propertyName || node.name, /*setVisibility*/ true); + } + if (!node.parent.parent.moduleSpecifier) { + var exportedName = node.propertyName || node.name; + // find immediate value referenced by exported name (SymbolFlags.Alias is set so we don't chase down aliases) + var symbol = resolveName(exportedName, exportedName.escapedText, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, + /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); + if (symbol && (symbol === undefinedSymbol || isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { + error(exportedName, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, ts.idText(exportedName)); + } + else { + markExportAsReferenced(node); + } + } + } + function checkExportAssignment(node) { + if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_export_assignment_can_only_be_used_in_a_module)) { + // If we hit an export assignment in an illegal context, just bail out to avoid cascading errors. + return; + } + var container = node.parent.kind === 279 /* SourceFile */ ? node.parent : node.parent.parent; + if (container.kind === 244 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) { + if (node.isExportEquals) { + error(node, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_namespace); + } + else { + error(node, ts.Diagnostics.A_default_export_can_only_be_used_in_an_ECMAScript_style_module); + } + return; + } + // Grammar checking + if (!checkGrammarDecoratorsAndModifiers(node) && ts.hasModifiers(node)) { + grammarErrorOnFirstToken(node, ts.Diagnostics.An_export_assignment_cannot_have_modifiers); + } + if (node.expression.kind === 72 /* Identifier */) { + markExportAsReferenced(node); + if (ts.getEmitDeclarations(compilerOptions)) { + collectLinkedAliases(node.expression, /*setVisibility*/ true); + } + } + else { + checkExpressionCached(node.expression); + } + checkExternalModuleExports(container); + if ((node.flags & 4194304 /* Ambient */) && !ts.isEntityNameExpression(node.expression)) { + grammarErrorOnNode(node.expression, ts.Diagnostics.The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context); + } + if (node.isExportEquals && !(node.flags & 4194304 /* Ambient */)) { + if (moduleKind >= ts.ModuleKind.ES2015) { + // export assignment is not supported in es6 modules + grammarErrorOnNode(node, ts.Diagnostics.Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or_another_module_format_instead); + } + else if (moduleKind === ts.ModuleKind.System) { + // system modules does not support export assignment + grammarErrorOnNode(node, ts.Diagnostics.Export_assignment_is_not_supported_when_module_flag_is_system); + } + } + } + function hasExportedMembers(moduleSymbol) { + return ts.forEachEntry(moduleSymbol.exports, function (_, id) { return id !== "export="; }); + } + function checkExternalModuleExports(node) { + var moduleSymbol = getSymbolOfNode(node); + var links = getSymbolLinks(moduleSymbol); + if (!links.exportsChecked) { + var exportEqualsSymbol = moduleSymbol.exports.get("export="); + if (exportEqualsSymbol && hasExportedMembers(moduleSymbol)) { + var declaration = getDeclarationOfAliasSymbol(exportEqualsSymbol) || exportEqualsSymbol.valueDeclaration; + if (!isTopLevelInExternalModuleAugmentation(declaration) && !ts.isInJSFile(declaration)) { + error(declaration, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements); + } + } + // Checks for export * conflicts + var exports_1 = getExportsOfModule(moduleSymbol); + if (exports_1) { + exports_1.forEach(function (_a, id) { + var declarations = _a.declarations, flags = _a.flags; + if (id === "__export") { + return; + } + // ECMA262: 15.2.1.1 It is a Syntax Error if the ExportedNames of ModuleItemList contains any duplicate entries. + // (TS Exceptions: namespaces, function overloads, enums, and interfaces) + if (flags & (1920 /* Namespace */ | 64 /* Interface */ | 384 /* Enum */)) { + return; + } + var exportedDeclarationsCount = ts.countWhere(declarations, isNotOverloadAndNotAccessor); + if (flags & 524288 /* TypeAlias */ && exportedDeclarationsCount <= 2) { + // it is legal to merge type alias with other values + // so count should be either 1 (just type alias) or 2 (type alias + merged value) + return; + } + if (exportedDeclarationsCount > 1) { + for (var _i = 0, declarations_9 = declarations; _i < declarations_9.length; _i++) { + var declaration = declarations_9[_i]; + if (isNotOverload(declaration)) { + diagnostics.add(ts.createDiagnosticForNode(declaration, ts.Diagnostics.Cannot_redeclare_exported_variable_0, ts.unescapeLeadingUnderscores(id))); + } + } + } + }); + } + links.exportsChecked = true; + } + } + function isNotAccessor(declaration) { + // Accessors check for their own matching duplicates, and in contexts where they are valid, there are already duplicate identifier checks + return !ts.isAccessor(declaration); + } + function isNotOverload(declaration) { + return (declaration.kind !== 239 /* FunctionDeclaration */ && declaration.kind !== 156 /* MethodDeclaration */) || + !!declaration.body; + } + function checkSourceElement(node) { + if (!node) { + return; + } + if (ts.isInJSFile(node)) { + ts.forEach(node.jsDoc, function (_a) { + var tags = _a.tags; + return ts.forEach(tags, checkSourceElement); + }); + } + var kind = node.kind; + if (cancellationToken) { + // Only bother checking on a few construct kinds. We don't want to be excessively + // hitting the cancellation token on every node we check. + switch (kind) { + case 244 /* ModuleDeclaration */: + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + case 239 /* FunctionDeclaration */: + cancellationToken.throwIfCancellationRequested(); + } + } + switch (kind) { + case 150 /* TypeParameter */: + return checkTypeParameter(node); + case 151 /* Parameter */: + return checkParameter(node); + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + return checkPropertyDeclaration(node); + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 162 /* IndexSignature */: + return checkSignatureDeclaration(node); + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + return checkMethodDeclaration(node); + case 157 /* Constructor */: + return checkConstructorDeclaration(node); + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + return checkAccessorDeclaration(node); + case 164 /* TypeReference */: + return checkTypeReferenceNode(node); + case 163 /* TypePredicate */: + return checkTypePredicate(node); + case 167 /* TypeQuery */: + return checkTypeQuery(node); + case 168 /* TypeLiteral */: + return checkTypeLiteral(node); + case 169 /* ArrayType */: + return checkArrayType(node); + case 170 /* TupleType */: + return checkTupleType(node); + case 173 /* UnionType */: + case 174 /* IntersectionType */: + return checkUnionOrIntersectionType(node); + case 177 /* ParenthesizedType */: + case 171 /* OptionalType */: + case 172 /* RestType */: + return checkSourceElement(node.type); + case 178 /* ThisType */: + return checkThisType(node); + case 179 /* TypeOperator */: + return checkTypeOperator(node); + case 175 /* ConditionalType */: + return checkConditionalType(node); + case 176 /* InferType */: + return checkInferType(node); + case 183 /* ImportType */: + return checkImportType(node); + case 295 /* JSDocAugmentsTag */: + return checkJSDocAugmentsTag(node); + case 304 /* JSDocTypedefTag */: + case 297 /* JSDocCallbackTag */: + return checkJSDocTypeAliasTag(node); + case 303 /* JSDocTemplateTag */: + return checkJSDocTemplateTag(node); + case 302 /* JSDocTypeTag */: + return checkJSDocTypeTag(node); + case 299 /* JSDocParameterTag */: + return checkJSDocParameterTag(node); + case 289 /* JSDocFunctionType */: + checkJSDocFunctionType(node); + // falls through + case 287 /* JSDocNonNullableType */: + case 286 /* JSDocNullableType */: + case 284 /* JSDocAllType */: + case 285 /* JSDocUnknownType */: + case 292 /* JSDocTypeLiteral */: + checkJSDocTypeIsInJsFile(node); + ts.forEachChild(node, checkSourceElement); + return; + case 290 /* JSDocVariadicType */: + checkJSDocVariadicType(node); + return; + case 283 /* JSDocTypeExpression */: + return checkSourceElement(node.type); + case 180 /* IndexedAccessType */: + return checkIndexedAccessType(node); + case 181 /* MappedType */: + return checkMappedType(node); + case 239 /* FunctionDeclaration */: + return checkFunctionDeclaration(node); + case 218 /* Block */: + case 245 /* ModuleBlock */: + return checkBlock(node); + case 219 /* VariableStatement */: + return checkVariableStatement(node); + case 221 /* ExpressionStatement */: + return checkExpressionStatement(node); + case 222 /* IfStatement */: + return checkIfStatement(node); + case 223 /* DoStatement */: + return checkDoStatement(node); + case 224 /* WhileStatement */: + return checkWhileStatement(node); + case 225 /* ForStatement */: + return checkForStatement(node); + case 226 /* ForInStatement */: + return checkForInStatement(node); + case 227 /* ForOfStatement */: + return checkForOfStatement(node); + case 228 /* ContinueStatement */: + case 229 /* BreakStatement */: + return checkBreakOrContinueStatement(node); + case 230 /* ReturnStatement */: + return checkReturnStatement(node); + case 231 /* WithStatement */: + return checkWithStatement(node); + case 232 /* SwitchStatement */: + return checkSwitchStatement(node); + case 233 /* LabeledStatement */: + return checkLabeledStatement(node); + case 234 /* ThrowStatement */: + return checkThrowStatement(node); + case 235 /* TryStatement */: + return checkTryStatement(node); + case 237 /* VariableDeclaration */: + return checkVariableDeclaration(node); + case 186 /* BindingElement */: + return checkBindingElement(node); + case 240 /* ClassDeclaration */: + return checkClassDeclaration(node); + case 241 /* InterfaceDeclaration */: + return checkInterfaceDeclaration(node); + case 242 /* TypeAliasDeclaration */: + return checkTypeAliasDeclaration(node); + case 243 /* EnumDeclaration */: + return checkEnumDeclaration(node); + case 244 /* ModuleDeclaration */: + return checkModuleDeclaration(node); + case 249 /* ImportDeclaration */: + return checkImportDeclaration(node); + case 248 /* ImportEqualsDeclaration */: + return checkImportEqualsDeclaration(node); + case 255 /* ExportDeclaration */: + return checkExportDeclaration(node); + case 254 /* ExportAssignment */: + return checkExportAssignment(node); + case 220 /* EmptyStatement */: + case 236 /* DebuggerStatement */: + checkGrammarStatementInAmbientContext(node); + return; + case 258 /* MissingDeclaration */: + return checkMissingDeclaration(node); + } + } + function checkJSDocTypeIsInJsFile(node) { + if (!ts.isInJSFile(node)) { + grammarErrorOnNode(node, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments); + } + } + function checkJSDocVariadicType(node) { + checkJSDocTypeIsInJsFile(node); + checkSourceElement(node.type); + // Only legal location is in the *last* parameter tag or last parameter of a JSDoc function. + var parent = node.parent; + if (ts.isParameter(parent) && ts.isJSDocFunctionType(parent.parent)) { + if (ts.last(parent.parent.parameters) !== parent) { + error(node, ts.Diagnostics.A_rest_parameter_must_be_last_in_a_parameter_list); + } + return; + } + if (!ts.isJSDocTypeExpression(parent)) { + error(node, ts.Diagnostics.JSDoc_may_only_appear_in_the_last_parameter_of_a_signature); + } + var paramTag = node.parent.parent; + if (!ts.isJSDocParameterTag(paramTag)) { + error(node, ts.Diagnostics.JSDoc_may_only_appear_in_the_last_parameter_of_a_signature); + return; + } + var param = ts.getParameterSymbolFromJSDoc(paramTag); + if (!param) { + // We will error in `checkJSDocParameterTag`. + return; + } + var host = ts.getHostSignatureFromJSDoc(paramTag); + if (!host || ts.last(host.parameters).symbol !== param) { + error(node, ts.Diagnostics.A_rest_parameter_must_be_last_in_a_parameter_list); + } + } + function getTypeFromJSDocVariadicType(node) { + var type = getTypeFromTypeNode(node.type); + var parent = node.parent; + var paramTag = node.parent.parent; + if (ts.isJSDocTypeExpression(node.parent) && ts.isJSDocParameterTag(paramTag)) { + // Else we will add a diagnostic, see `checkJSDocVariadicType`. + var host_1 = ts.getHostSignatureFromJSDoc(paramTag); + if (host_1) { + /* + Only return an array type if the corresponding parameter is marked as a rest parameter, or if there are no parameters. + So in the following situation we will not create an array type: + /** @param {...number} a * / + function f(a) {} + Because `a` will just be of type `number | undefined`. A synthetic `...args` will also be added, which *will* get an array type. + */ + var lastParamDeclaration = ts.lastOrUndefined(host_1.parameters); + var symbol = ts.getParameterSymbolFromJSDoc(paramTag); + if (!lastParamDeclaration || + symbol && lastParamDeclaration.symbol === symbol && ts.isRestParameter(lastParamDeclaration)) { + return createArrayType(type); + } + } + } + if (ts.isParameter(parent) && ts.isJSDocFunctionType(parent.parent)) { + return createArrayType(type); + } + return addOptionality(type); + } + // Function and class expression bodies are checked after all statements in the enclosing body. This is + // to ensure constructs like the following are permitted: + // const foo = function () { + // const s = foo(); + // return "hello"; + // } + // Here, performing a full type check of the body of the function expression whilst in the process of + // determining the type of foo would cause foo to be given type any because of the recursive reference. + // Delaying the type check of the body ensures foo has been assigned a type. + function checkNodeDeferred(node) { + var enclosingFile = ts.getSourceFileOfNode(node); + var links = getNodeLinks(enclosingFile); + if (!(links.flags & 1 /* TypeChecked */)) { + links.deferredNodes = links.deferredNodes || ts.createMap(); + var id = "" + getNodeId(node); + links.deferredNodes.set(id, node); + } + } + function checkDeferredNodes(context) { + var links = getNodeLinks(context); + if (!links.deferredNodes) { + return; + } + links.deferredNodes.forEach(function (node) { + switch (node.kind) { + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + checkFunctionExpressionOrObjectLiteralMethodDeferred(node); + break; + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + checkAccessorDeclaration(node); + break; + case 209 /* ClassExpression */: + checkClassExpressionDeferred(node); + break; + case 261 /* JsxSelfClosingElement */: + checkJsxSelfClosingElementDeferred(node); + break; + case 260 /* JsxElement */: + checkJsxElementDeferred(node); + break; + } + }); + } + function checkSourceFile(node) { + ts.performance.mark("beforeCheck"); + checkSourceFileWorker(node); + ts.performance.mark("afterCheck"); + ts.performance.measure("Check", "beforeCheck", "afterCheck"); + } + function unusedIsError(kind) { + switch (kind) { + case 0 /* Local */: + return !!compilerOptions.noUnusedLocals; + case 1 /* Parameter */: + return !!compilerOptions.noUnusedParameters; + default: + return ts.Debug.assertNever(kind); + } + } + function getPotentiallyUnusedIdentifiers(sourceFile) { + return allPotentiallyUnusedIdentifiers.get(sourceFile.path) || ts.emptyArray; + } + // Fully type check a source file and collect the relevant diagnostics. + function checkSourceFileWorker(node) { + var links = getNodeLinks(node); + if (!(links.flags & 1 /* TypeChecked */)) { + if (ts.skipTypeChecking(node, compilerOptions)) { + return; + } + // Grammar checking + checkGrammarSourceFile(node); + ts.clear(potentialThisCollisions); + ts.clear(potentialNewTargetCollisions); + ts.forEach(node.statements, checkSourceElement); + checkSourceElement(node.endOfFileToken); + checkDeferredNodes(node); + if (ts.isExternalOrCommonJsModule(node)) { + registerForUnusedIdentifiersCheck(node); + } + if (!node.isDeclarationFile && (compilerOptions.noUnusedLocals || compilerOptions.noUnusedParameters)) { + checkUnusedIdentifiers(getPotentiallyUnusedIdentifiers(node), function (containingNode, kind, diag) { + if (!ts.containsParseError(containingNode) && unusedIsError(kind)) { + diagnostics.add(diag); + } + }); + } + if (ts.isExternalOrCommonJsModule(node)) { + checkExternalModuleExports(node); + } + if (potentialThisCollisions.length) { + ts.forEach(potentialThisCollisions, checkIfThisIsCapturedInEnclosingScope); + ts.clear(potentialThisCollisions); + } + if (potentialNewTargetCollisions.length) { + ts.forEach(potentialNewTargetCollisions, checkIfNewTargetIsCapturedInEnclosingScope); + ts.clear(potentialNewTargetCollisions); + } + links.flags |= 1 /* TypeChecked */; + } + } + function getDiagnostics(sourceFile, ct) { + try { + // Record the cancellation token so it can be checked later on during checkSourceElement. + // Do this in a finally block so we can ensure that it gets reset back to nothing after + // this call is done. + cancellationToken = ct; + return getDiagnosticsWorker(sourceFile); + } + finally { + cancellationToken = undefined; + } + } + function getDiagnosticsWorker(sourceFile) { + throwIfNonDiagnosticsProducing(); + if (sourceFile) { + // Some global diagnostics are deferred until they are needed and + // may not be reported in the firt call to getGlobalDiagnostics. + // We should catch these changes and report them. + var previousGlobalDiagnostics = diagnostics.getGlobalDiagnostics(); + var previousGlobalDiagnosticsSize = previousGlobalDiagnostics.length; + checkSourceFile(sourceFile); + var semanticDiagnostics = diagnostics.getDiagnostics(sourceFile.fileName); + var currentGlobalDiagnostics = diagnostics.getGlobalDiagnostics(); + if (currentGlobalDiagnostics !== previousGlobalDiagnostics) { + // If the arrays are not the same reference, new diagnostics were added. + var deferredGlobalDiagnostics = ts.relativeComplement(previousGlobalDiagnostics, currentGlobalDiagnostics, ts.compareDiagnostics); + return ts.concatenate(deferredGlobalDiagnostics, semanticDiagnostics); + } + else if (previousGlobalDiagnosticsSize === 0 && currentGlobalDiagnostics.length > 0) { + // If the arrays are the same reference, but the length has changed, a single + // new diagnostic was added as DiagnosticCollection attempts to reuse the + // same array. + return ts.concatenate(currentGlobalDiagnostics, semanticDiagnostics); + } + return semanticDiagnostics; + } + // Global diagnostics are always added when a file is not provided to + // getDiagnostics + ts.forEach(host.getSourceFiles(), checkSourceFile); + return diagnostics.getDiagnostics(); + } + function getGlobalDiagnostics() { + throwIfNonDiagnosticsProducing(); + return diagnostics.getGlobalDiagnostics(); + } + function throwIfNonDiagnosticsProducing() { + if (!produceDiagnostics) { + throw new Error("Trying to get diagnostics from a type checker that does not produce them."); + } + } + // Language service support + function getSymbolsInScope(location, meaning) { + if (location.flags & 8388608 /* InWithStatement */) { + // We cannot answer semantic questions within a with block, do not proceed any further + return []; + } + var symbols = ts.createSymbolTable(); + var isStatic = false; + populateSymbols(); + symbols.delete("this" /* This */); // Not a symbol, a keyword + return symbolsToArray(symbols); + function populateSymbols() { + while (location) { + if (location.locals && !isGlobalSourceFile(location)) { + copySymbols(location.locals, meaning); + } + switch (location.kind) { + case 279 /* SourceFile */: + if (!ts.isExternalOrCommonJsModule(location)) + break; + // falls through + case 244 /* ModuleDeclaration */: + copySymbols(getSymbolOfNode(location).exports, meaning & 2623475 /* ModuleMember */); + break; + case 243 /* EnumDeclaration */: + copySymbols(getSymbolOfNode(location).exports, meaning & 8 /* EnumMember */); + break; + case 209 /* ClassExpression */: + var className = location.name; + if (className) { + copySymbol(location.symbol, meaning); + } + // falls through + // this fall-through is necessary because we would like to handle + // type parameter inside class expression similar to how we handle it in classDeclaration and interface Declaration + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + // If we didn't come from static member of class or interface, + // add the type parameters into the symbol table + // (type parameters of classDeclaration/classExpression and interface are in member property of the symbol. + // Note: that the memberFlags come from previous iteration. + if (!isStatic) { + copySymbols(getMembersOfSymbol(getSymbolOfNode(location)), meaning & 67897832 /* Type */); + } + break; + case 196 /* FunctionExpression */: + var funcName = location.name; + if (funcName) { + copySymbol(location.symbol, meaning); + } + break; + } + if (ts.introducesArgumentsExoticObject(location)) { + copySymbol(argumentsSymbol, meaning); + } + isStatic = ts.hasModifier(location, 32 /* Static */); + location = location.parent; + } + copySymbols(globals, meaning); + } + /** + * Copy the given symbol into symbol tables if the symbol has the given meaning + * and it doesn't already existed in the symbol table + * @param key a key for storing in symbol table; if undefined, use symbol.name + * @param symbol the symbol to be added into symbol table + * @param meaning meaning of symbol to filter by before adding to symbol table + */ + function copySymbol(symbol, meaning) { + if (ts.getCombinedLocalAndExportSymbolFlags(symbol) & meaning) { + var id = symbol.escapedName; + // We will copy all symbol regardless of its reserved name because + // symbolsToArray will check whether the key is a reserved name and + // it will not copy symbol with reserved name to the array + if (!symbols.has(id)) { + symbols.set(id, symbol); + } + } + } + function copySymbols(source, meaning) { + if (meaning) { + source.forEach(function (symbol) { + copySymbol(symbol, meaning); + }); + } + } + } + function isTypeDeclarationName(name) { + return name.kind === 72 /* Identifier */ && + isTypeDeclaration(name.parent) && + name.parent.name === name; + } + function isTypeDeclaration(node) { + switch (node.kind) { + case 150 /* TypeParameter */: + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 243 /* EnumDeclaration */: + return true; + default: + return false; + } + } + // True if the given identifier is part of a type reference + function isTypeReferenceIdentifier(node) { + while (node.parent.kind === 148 /* QualifiedName */) { + node = node.parent; + } + return node.parent.kind === 164 /* TypeReference */; + } + function isHeritageClauseElementIdentifier(node) { + while (node.parent.kind === 189 /* PropertyAccessExpression */) { + node = node.parent; + } + return node.parent.kind === 211 /* ExpressionWithTypeArguments */; + } + function forEachEnclosingClass(node, callback) { + var result; + while (true) { + node = ts.getContainingClass(node); + if (!node) + break; + if (result = callback(node)) + break; + } + return result; + } + function isNodeUsedDuringClassInitialization(node) { + return !!ts.findAncestor(node, function (element) { + if (ts.isConstructorDeclaration(element) && ts.nodeIsPresent(element.body) || ts.isPropertyDeclaration(element)) { + return true; + } + else if (ts.isClassLike(element) || ts.isFunctionLikeDeclaration(element)) { + return "quit"; + } + return false; + }); + } + function isNodeWithinClass(node, classDeclaration) { + return !!forEachEnclosingClass(node, function (n) { return n === classDeclaration; }); + } + function getLeftSideOfImportEqualsOrExportAssignment(nodeOnRightSide) { + while (nodeOnRightSide.parent.kind === 148 /* QualifiedName */) { + nodeOnRightSide = nodeOnRightSide.parent; + } + if (nodeOnRightSide.parent.kind === 248 /* ImportEqualsDeclaration */) { + return nodeOnRightSide.parent.moduleReference === nodeOnRightSide ? nodeOnRightSide.parent : undefined; + } + if (nodeOnRightSide.parent.kind === 254 /* ExportAssignment */) { + return nodeOnRightSide.parent.expression === nodeOnRightSide ? nodeOnRightSide.parent : undefined; + } + return undefined; + } + function isInRightSideOfImportOrExportAssignment(node) { + return getLeftSideOfImportEqualsOrExportAssignment(node) !== undefined; + } + function getSpecialPropertyAssignmentSymbolFromEntityName(entityName) { + var specialPropertyAssignmentKind = ts.getAssignmentDeclarationKind(entityName.parent.parent); + switch (specialPropertyAssignmentKind) { + case 1 /* ExportsProperty */: + case 3 /* PrototypeProperty */: + return getSymbolOfNode(entityName.parent); + case 4 /* ThisProperty */: + case 2 /* ModuleExports */: + case 5 /* Property */: + return getSymbolOfNode(entityName.parent.parent); + } + } + function isImportTypeQualifierPart(node) { + var parent = node.parent; + while (ts.isQualifiedName(parent)) { + node = parent; + parent = parent.parent; + } + if (parent && parent.kind === 183 /* ImportType */ && parent.qualifier === node) { + return parent; + } + return undefined; + } + function getSymbolOfEntityNameOrPropertyAccessExpression(entityName) { + if (ts.isDeclarationName(entityName)) { + return getSymbolOfNode(entityName.parent); + } + if (ts.isInJSFile(entityName) && + entityName.parent.kind === 189 /* PropertyAccessExpression */ && + entityName.parent === entityName.parent.parent.left) { + // Check if this is a special property assignment + var specialPropertyAssignmentSymbol = getSpecialPropertyAssignmentSymbolFromEntityName(entityName); + if (specialPropertyAssignmentSymbol) { + return specialPropertyAssignmentSymbol; + } + } + if (entityName.parent.kind === 254 /* ExportAssignment */ && ts.isEntityNameExpression(entityName)) { + // Even an entity name expression that doesn't resolve as an entityname may still typecheck as a property access expression + var success = resolveEntityName(entityName, + /*all meanings*/ 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*ignoreErrors*/ true); + if (success && success !== unknownSymbol) { + return success; + } + } + else if (!ts.isPropertyAccessExpression(entityName) && isInRightSideOfImportOrExportAssignment(entityName)) { + // Since we already checked for ExportAssignment, this really could only be an Import + var importEqualsDeclaration = ts.getAncestor(entityName, 248 /* ImportEqualsDeclaration */); + ts.Debug.assert(importEqualsDeclaration !== undefined); + return getSymbolOfPartOfRightHandSideOfImportEquals(entityName, /*dontResolveAlias*/ true); + } + if (!ts.isPropertyAccessExpression(entityName)) { + var possibleImportNode = isImportTypeQualifierPart(entityName); + if (possibleImportNode) { + getTypeFromTypeNode(possibleImportNode); + var sym = getNodeLinks(entityName).resolvedSymbol; + return sym === unknownSymbol ? undefined : sym; + } + } + while (ts.isRightSideOfQualifiedNameOrPropertyAccess(entityName)) { + entityName = entityName.parent; + } + if (isHeritageClauseElementIdentifier(entityName)) { + var meaning = 0 /* None */; + // In an interface or class, we're definitely interested in a type. + if (entityName.parent.kind === 211 /* ExpressionWithTypeArguments */) { + meaning = 67897832 /* Type */; + // In a class 'extends' clause we are also looking for a value. + if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent)) { + meaning |= 67220415 /* Value */; + } + } + else { + meaning = 1920 /* Namespace */; + } + meaning |= 2097152 /* Alias */; + var entityNameSymbol = ts.isEntityNameExpression(entityName) ? resolveEntityName(entityName, meaning) : undefined; + if (entityNameSymbol) { + return entityNameSymbol; + } + } + if (entityName.parent.kind === 299 /* JSDocParameterTag */) { + return ts.getParameterSymbolFromJSDoc(entityName.parent); + } + if (entityName.parent.kind === 150 /* TypeParameter */ && entityName.parent.parent.kind === 303 /* JSDocTemplateTag */) { + ts.Debug.assert(!ts.isInJSFile(entityName)); // Otherwise `isDeclarationName` would have been true. + var typeParameter = ts.getTypeParameterFromJsDoc(entityName.parent); + return typeParameter && typeParameter.symbol; + } + if (ts.isExpressionNode(entityName)) { + if (ts.nodeIsMissing(entityName)) { + // Missing entity name. + return undefined; + } + if (entityName.kind === 72 /* Identifier */) { + if (ts.isJSXTagName(entityName) && isJsxIntrinsicIdentifier(entityName)) { + var symbol = getIntrinsicTagSymbol(entityName.parent); + return symbol === unknownSymbol ? undefined : symbol; + } + return resolveEntityName(entityName, 67220415 /* Value */, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); + } + else if (entityName.kind === 189 /* PropertyAccessExpression */ || entityName.kind === 148 /* QualifiedName */) { + var links = getNodeLinks(entityName); + if (links.resolvedSymbol) { + return links.resolvedSymbol; + } + if (entityName.kind === 189 /* PropertyAccessExpression */) { + checkPropertyAccessExpression(entityName); + } + else { + checkQualifiedName(entityName); + } + return links.resolvedSymbol; + } + } + else if (isTypeReferenceIdentifier(entityName)) { + var meaning = entityName.parent.kind === 164 /* TypeReference */ ? 67897832 /* Type */ : 1920 /* Namespace */; + return resolveEntityName(entityName, meaning, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); + } + if (entityName.parent.kind === 163 /* TypePredicate */) { + return resolveEntityName(entityName, /*meaning*/ 1 /* FunctionScopedVariable */); + } + // Do we want to return undefined here? + return undefined; + } + function getSymbolAtLocation(node) { + if (node.kind === 279 /* SourceFile */) { + return ts.isExternalModule(node) ? getMergedSymbol(node.symbol) : undefined; + } + var parent = node.parent; + var grandParent = parent.parent; + if (node.flags & 8388608 /* InWithStatement */) { + // We cannot answer semantic questions within a with block, do not proceed any further + return undefined; + } + if (isDeclarationNameOrImportPropertyName(node)) { + // This is a declaration, call getSymbolOfNode + var parentSymbol = getSymbolOfNode(parent); + return ts.isImportOrExportSpecifier(node.parent) && node.parent.propertyName === node + ? getImmediateAliasedSymbol(parentSymbol) + : parentSymbol; + } + else if (ts.isLiteralComputedPropertyDeclarationName(node)) { + return getSymbolOfNode(parent.parent); + } + if (node.kind === 72 /* Identifier */) { + if (isInRightSideOfImportOrExportAssignment(node)) { + return getSymbolOfEntityNameOrPropertyAccessExpression(node); + } + else if (parent.kind === 186 /* BindingElement */ && + grandParent.kind === 184 /* ObjectBindingPattern */ && + node === parent.propertyName) { + var typeOfPattern = getTypeOfNode(grandParent); + var propertyDeclaration = getPropertyOfType(typeOfPattern, node.escapedText); + if (propertyDeclaration) { + return propertyDeclaration; + } + } + } + switch (node.kind) { + case 72 /* Identifier */: + case 189 /* PropertyAccessExpression */: + case 148 /* QualifiedName */: + return getSymbolOfEntityNameOrPropertyAccessExpression(node); + case 100 /* ThisKeyword */: + var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); + if (ts.isFunctionLike(container)) { + var sig = getSignatureFromDeclaration(container); + if (sig.thisParameter) { + return sig.thisParameter; + } + } + if (ts.isInExpressionContext(node)) { + return checkExpression(node).symbol; + } + // falls through + case 178 /* ThisType */: + return getTypeFromThisTypeNode(node).symbol; + case 98 /* SuperKeyword */: + return checkExpression(node).symbol; + case 124 /* ConstructorKeyword */: + // constructor keyword for an overload, should take us to the definition if it exist + var constructorDeclaration = node.parent; + if (constructorDeclaration && constructorDeclaration.kind === 157 /* Constructor */) { + return constructorDeclaration.parent.symbol; + } + return undefined; + case 10 /* StringLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: + // 1). import x = require("./mo/*gotToDefinitionHere*/d") + // 2). External module name in an import declaration + // 3). Dynamic import call or require in javascript + // 4). type A = import("./f/*gotToDefinitionHere*/oo") + if ((ts.isExternalModuleImportEqualsDeclaration(node.parent.parent) && ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node) || + ((node.parent.kind === 249 /* ImportDeclaration */ || node.parent.kind === 255 /* ExportDeclaration */) && node.parent.moduleSpecifier === node) || + ((ts.isInJSFile(node) && ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteralLike*/ false)) || ts.isImportCall(node.parent)) || + (ts.isLiteralTypeNode(node.parent) && ts.isLiteralImportTypeNode(node.parent.parent) && node.parent.parent.argument === node.parent)) { + return resolveExternalModuleName(node, node); + } + if (ts.isCallExpression(parent) && ts.isBindableObjectDefinePropertyCall(parent) && parent.arguments[1] === node) { + return getSymbolOfNode(parent); + } + // falls through + case 8 /* NumericLiteral */: + // index access + var objectType = ts.isElementAccessExpression(parent) + ? parent.argumentExpression === node ? getTypeOfExpression(parent.expression) : undefined + : ts.isLiteralTypeNode(parent) && ts.isIndexedAccessTypeNode(grandParent) + ? getTypeFromTypeNode(grandParent.objectType) + : undefined; + return objectType && getPropertyOfType(objectType, ts.escapeLeadingUnderscores(node.text)); + case 80 /* DefaultKeyword */: + case 90 /* FunctionKeyword */: + case 37 /* EqualsGreaterThanToken */: + case 76 /* ClassKeyword */: + return getSymbolOfNode(node.parent); + case 183 /* ImportType */: + return ts.isLiteralImportTypeNode(node) ? getSymbolAtLocation(node.argument.literal) : undefined; + case 85 /* ExportKeyword */: + return ts.isExportAssignment(node.parent) ? ts.Debug.assertDefined(node.parent.symbol) : undefined; + default: + return undefined; + } + } + function getShorthandAssignmentValueSymbol(location) { + if (location && location.kind === 276 /* ShorthandPropertyAssignment */) { + return resolveEntityName(location.name, 67220415 /* Value */ | 2097152 /* Alias */); + } + return undefined; + } + /** Returns the target of an export specifier without following aliases */ + function getExportSpecifierLocalTargetSymbol(node) { + return node.parent.parent.moduleSpecifier ? + getExternalModuleMember(node.parent.parent, node) : + resolveEntityName(node.propertyName || node.name, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); + } + function getTypeOfNode(node) { + if (node.flags & 8388608 /* InWithStatement */) { + // We cannot answer semantic questions within a with block, do not proceed any further + return errorType; + } + var classDecl = ts.tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node); + var classType = classDecl && getDeclaredTypeOfClassOrInterface(getSymbolOfNode(classDecl.class)); + if (ts.isPartOfTypeNode(node)) { + var typeFromTypeNode = getTypeFromTypeNode(node); + return classType ? getTypeWithThisArgument(typeFromTypeNode, classType.thisType) : typeFromTypeNode; + } + if (ts.isExpressionNode(node)) { + return getRegularTypeOfExpression(node); + } + if (classType && !classDecl.isImplements) { + // A SyntaxKind.ExpressionWithTypeArguments is considered a type node, except when it occurs in the + // extends clause of a class. We handle that case here. + var baseType = ts.firstOrUndefined(getBaseTypes(classType)); + return baseType ? getTypeWithThisArgument(baseType, classType.thisType) : errorType; + } + if (isTypeDeclaration(node)) { + // In this case, we call getSymbolOfNode instead of getSymbolAtLocation because it is a declaration + var symbol = getSymbolOfNode(node); + return getDeclaredTypeOfSymbol(symbol); + } + if (isTypeDeclarationName(node)) { + var symbol = getSymbolAtLocation(node); + return symbol ? getDeclaredTypeOfSymbol(symbol) : errorType; + } + if (ts.isDeclaration(node)) { + // In this case, we call getSymbolOfNode instead of getSymbolAtLocation because it is a declaration + var symbol = getSymbolOfNode(node); + return getTypeOfSymbol(symbol); + } + if (isDeclarationNameOrImportPropertyName(node)) { + var symbol = getSymbolAtLocation(node); + return symbol ? getTypeOfSymbol(symbol) : errorType; + } + if (ts.isBindingPattern(node)) { + return getTypeForVariableLikeDeclaration(node.parent, /*includeOptionality*/ true) || errorType; + } + if (isInRightSideOfImportOrExportAssignment(node)) { + var symbol = getSymbolAtLocation(node); + if (symbol) { + var declaredType = getDeclaredTypeOfSymbol(symbol); + return declaredType !== errorType ? declaredType : getTypeOfSymbol(symbol); + } + } + return errorType; + } + // Gets the type of object literal or array literal of destructuring assignment. + // { a } from + // for ( { a } of elems) { + // } + // [ a ] from + // [a] = [ some array ...] + function getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr) { + ts.Debug.assert(expr.kind === 188 /* ObjectLiteralExpression */ || expr.kind === 187 /* ArrayLiteralExpression */); + // If this is from "for of" + // for ( { a } of elems) { + // } + if (expr.parent.kind === 227 /* ForOfStatement */) { + var iteratedType = checkRightHandSideOfForOf(expr.parent.expression, expr.parent.awaitModifier); + return checkDestructuringAssignment(expr, iteratedType || errorType); + } + // If this is from "for" initializer + // for ({a } = elems[0];.....) { } + if (expr.parent.kind === 204 /* BinaryExpression */) { + var iteratedType = getTypeOfExpression(expr.parent.right); + return checkDestructuringAssignment(expr, iteratedType || errorType); + } + // If this is from nested object binding pattern + // for ({ skills: { primary, secondary } } = multiRobot, i = 0; i < 1; i++) { + if (expr.parent.kind === 275 /* PropertyAssignment */) { + var typeOfParentObjectLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr.parent.parent); + return checkObjectLiteralDestructuringPropertyAssignment(typeOfParentObjectLiteral || errorType, expr.parent); // TODO: GH#18217 + } + // Array literal assignment - array destructuring pattern + ts.Debug.assert(expr.parent.kind === 187 /* ArrayLiteralExpression */); + // [{ property1: p1, property2 }] = elems; + var typeOfArrayLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr.parent); + var elementType = checkIteratedTypeOrElementType(typeOfArrayLiteral || errorType, expr.parent, /*allowStringInput*/ false, /*allowAsyncIterables*/ false) || errorType; + return checkArrayLiteralDestructuringElementAssignment(expr.parent, typeOfArrayLiteral, expr.parent.elements.indexOf(expr), elementType || errorType); // TODO: GH#18217 + } + // Gets the property symbol corresponding to the property in destructuring assignment + // 'property1' from + // for ( { property1: a } of elems) { + // } + // 'property1' at location 'a' from: + // [a] = [ property1, property2 ] + function getPropertySymbolOfDestructuringAssignment(location) { + // Get the type of the object or array literal and then look for property of given name in the type + var typeOfObjectLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(location.parent.parent); + return typeOfObjectLiteral && getPropertyOfType(typeOfObjectLiteral, location.escapedText); + } + function getRegularTypeOfExpression(expr) { + if (ts.isRightSideOfQualifiedNameOrPropertyAccess(expr)) { + expr = expr.parent; + } + return getRegularTypeOfLiteralType(getTypeOfExpression(expr)); + } + /** + * Gets either the static or instance type of a class element, based on + * whether the element is declared as "static". + */ + function getParentTypeOfClassElement(node) { + var classSymbol = getSymbolOfNode(node.parent); + return ts.hasModifier(node, 32 /* Static */) + ? getTypeOfSymbol(classSymbol) + : getDeclaredTypeOfSymbol(classSymbol); + } + function getClassElementPropertyKeyType(element) { + var name = element.name; + switch (name.kind) { + case 72 /* Identifier */: + return getLiteralType(ts.idText(name)); + case 8 /* NumericLiteral */: + case 10 /* StringLiteral */: + return getLiteralType(name.text); + case 149 /* ComputedPropertyName */: + var nameType = checkComputedPropertyName(name); + return isTypeAssignableToKind(nameType, 12288 /* ESSymbolLike */) ? nameType : stringType; + default: + ts.Debug.fail("Unsupported property name."); + return errorType; + } + } + // Return the list of properties of the given type, augmented with properties from Function + // if the type has call or construct signatures + function getAugmentedPropertiesOfType(type) { + type = getApparentType(type); + var propsByName = ts.createSymbolTable(getPropertiesOfType(type)); + var functionType = getSignaturesOfType(type, 0 /* Call */).length ? globalCallableFunctionType : + getSignaturesOfType(type, 1 /* Construct */).length ? globalNewableFunctionType : + undefined; + if (functionType) { + ts.forEach(getPropertiesOfType(functionType), function (p) { + if (!propsByName.has(p.escapedName)) { + propsByName.set(p.escapedName, p); + } + }); + } + return getNamedMembers(propsByName); + } + function typeHasCallOrConstructSignatures(type) { + return ts.typeHasCallOrConstructSignatures(type, checker); + } + function getRootSymbols(symbol) { + var roots = getImmediateRootSymbols(symbol); + return roots ? ts.flatMap(roots, getRootSymbols) : [symbol]; + } + function getImmediateRootSymbols(symbol) { + if (ts.getCheckFlags(symbol) & 6 /* Synthetic */) { + return ts.mapDefined(getSymbolLinks(symbol).containingType.types, function (type) { return getPropertyOfType(type, symbol.escapedName); }); + } + else if (symbol.flags & 33554432 /* Transient */) { + var _a = symbol, leftSpread = _a.leftSpread, rightSpread = _a.rightSpread, syntheticOrigin = _a.syntheticOrigin; + return leftSpread ? [leftSpread, rightSpread] + : syntheticOrigin ? [syntheticOrigin] + : ts.singleElementArray(tryGetAliasTarget(symbol)); + } + return undefined; + } + function tryGetAliasTarget(symbol) { + var target; + var next = symbol; + while (next = getSymbolLinks(next).target) { + target = next; + } + return target; + } + // Emitter support + function isArgumentsLocalBinding(nodeIn) { + if (!ts.isGeneratedIdentifier(nodeIn)) { + var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier); + if (node) { + var isPropertyName_1 = node.parent.kind === 189 /* PropertyAccessExpression */ && node.parent.name === node; + return !isPropertyName_1 && getReferencedValueSymbol(node) === argumentsSymbol; + } + } + return false; + } + function moduleExportsSomeValue(moduleReferenceExpression) { + var moduleSymbol = resolveExternalModuleName(moduleReferenceExpression.parent, moduleReferenceExpression); + if (!moduleSymbol || ts.isShorthandAmbientModuleSymbol(moduleSymbol)) { + // If the module is not found or is shorthand, assume that it may export a value. + return true; + } + var hasExportAssignment = hasExportAssignmentSymbol(moduleSymbol); + // if module has export assignment then 'resolveExternalModuleSymbol' will return resolved symbol for export assignment + // otherwise it will return moduleSymbol itself + moduleSymbol = resolveExternalModuleSymbol(moduleSymbol); + var symbolLinks = getSymbolLinks(moduleSymbol); + if (symbolLinks.exportsSomeValue === undefined) { + // for export assignments - check if resolved symbol for RHS is itself a value + // otherwise - check if at least one export is value + symbolLinks.exportsSomeValue = hasExportAssignment + ? !!(moduleSymbol.flags & 67220415 /* Value */) + : ts.forEachEntry(getExportsOfModule(moduleSymbol), isValue); + } + return symbolLinks.exportsSomeValue; + function isValue(s) { + s = resolveSymbol(s); + return s && !!(s.flags & 67220415 /* Value */); + } + } + function isNameOfModuleOrEnumDeclaration(node) { + return ts.isModuleOrEnumDeclaration(node.parent) && node === node.parent.name; + } + // When resolved as an expression identifier, if the given node references an exported entity, return the declaration + // node of the exported entity's container. Otherwise, return undefined. + function getReferencedExportContainer(nodeIn, prefixLocals) { + var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier); + if (node) { + // When resolving the export container for the name of a module or enum + // declaration, we need to start resolution at the declaration's container. + // Otherwise, we could incorrectly resolve the export container as the + // declaration if it contains an exported member with the same name. + var symbol = getReferencedValueSymbol(node, /*startInDeclarationContainer*/ isNameOfModuleOrEnumDeclaration(node)); + if (symbol) { + if (symbol.flags & 1048576 /* ExportValue */) { + // If we reference an exported entity within the same module declaration, then whether + // we prefix depends on the kind of entity. SymbolFlags.ExportHasLocal encompasses all the + // kinds that we do NOT prefix. + var exportSymbol = getMergedSymbol(symbol.exportSymbol); + if (!prefixLocals && exportSymbol.flags & 944 /* ExportHasLocal */ && !(exportSymbol.flags & 3 /* Variable */)) { + return undefined; + } + symbol = exportSymbol; + } + var parentSymbol_1 = getParentOfSymbol(symbol); + if (parentSymbol_1) { + if (parentSymbol_1.flags & 512 /* ValueModule */ && parentSymbol_1.valueDeclaration.kind === 279 /* SourceFile */) { + var symbolFile = parentSymbol_1.valueDeclaration; + var referenceFile = ts.getSourceFileOfNode(node); + // If `node` accesses an export and that export isn't in the same file, then symbol is a namespace export, so return undefined. + var symbolIsUmdExport = symbolFile !== referenceFile; + return symbolIsUmdExport ? undefined : symbolFile; + } + return ts.findAncestor(node.parent, function (n) { return ts.isModuleOrEnumDeclaration(n) && getSymbolOfNode(n) === parentSymbol_1; }); + } + } + } + } + // When resolved as an expression identifier, if the given node references an import, return the declaration of + // that import. Otherwise, return undefined. + function getReferencedImportDeclaration(nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier); + if (node) { + var symbol = getReferencedValueSymbol(node); + // We should only get the declaration of an alias if there isn't a local value + // declaration for the symbol + if (isNonLocalAlias(symbol, /*excludes*/ 67220415 /* Value */)) { + return getDeclarationOfAliasSymbol(symbol); + } + } + return undefined; + } + function isSymbolOfDeclarationWithCollidingName(symbol) { + if (symbol.flags & 418 /* BlockScoped */) { + var links = getSymbolLinks(symbol); + if (links.isDeclarationWithCollidingName === undefined) { + var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); + if (ts.isStatementWithLocals(container)) { + var nodeLinks_1 = getNodeLinks(symbol.valueDeclaration); + if (resolveName(container.parent, symbol.escapedName, 67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)) { + // redeclaration - always should be renamed + links.isDeclarationWithCollidingName = true; + } + else if (nodeLinks_1.flags & 262144 /* CapturedBlockScopedBinding */) { + // binding is captured in the function + // should be renamed if: + // - binding is not top level - top level bindings never collide with anything + // AND + // - binding is not declared in loop, should be renamed to avoid name reuse across siblings + // let a, b + // { let x = 1; a = () => x; } + // { let x = 100; b = () => x; } + // console.log(a()); // should print '1' + // console.log(b()); // should print '100' + // OR + // - binding is declared inside loop but not in inside initializer of iteration statement or directly inside loop body + // * variables from initializer are passed to rewritten loop body as parameters so they are not captured directly + // * variables that are declared immediately in loop body will become top level variable after loop is rewritten and thus + // they will not collide with anything + var isDeclaredInLoop = nodeLinks_1.flags & 524288 /* BlockScopedBindingInLoop */; + var inLoopInitializer = ts.isIterationStatement(container, /*lookInLabeledStatements*/ false); + var inLoopBodyBlock = container.kind === 218 /* Block */ && ts.isIterationStatement(container.parent, /*lookInLabeledStatements*/ false); + links.isDeclarationWithCollidingName = !ts.isBlockScopedContainerTopLevel(container) && (!isDeclaredInLoop || (!inLoopInitializer && !inLoopBodyBlock)); + } + else { + links.isDeclarationWithCollidingName = false; + } + } + } + return links.isDeclarationWithCollidingName; + } + return false; + } + // When resolved as an expression identifier, if the given node references a nested block scoped entity with + // a name that either hides an existing name or might hide it when compiled downlevel, + // return the declaration of that entity. Otherwise, return undefined. + function getReferencedDeclarationWithCollidingName(nodeIn) { + if (!ts.isGeneratedIdentifier(nodeIn)) { + var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier); + if (node) { + var symbol = getReferencedValueSymbol(node); + if (symbol && isSymbolOfDeclarationWithCollidingName(symbol)) { + return symbol.valueDeclaration; + } + } + } + return undefined; + } + // Return true if the given node is a declaration of a nested block scoped entity with a name that either hides an + // existing name or might hide a name when compiled downlevel + function isDeclarationWithCollidingName(nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isDeclaration); + if (node) { + var symbol = getSymbolOfNode(node); + if (symbol) { + return isSymbolOfDeclarationWithCollidingName(symbol); + } + } + return false; + } + function isValueAliasDeclaration(node) { + switch (node.kind) { + case 248 /* ImportEqualsDeclaration */: + case 250 /* ImportClause */: + case 251 /* NamespaceImport */: + case 253 /* ImportSpecifier */: + case 257 /* ExportSpecifier */: + return isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol); + case 255 /* ExportDeclaration */: + var exportClause = node.exportClause; + return !!exportClause && ts.some(exportClause.elements, isValueAliasDeclaration); + case 254 /* ExportAssignment */: + return node.expression + && node.expression.kind === 72 /* Identifier */ + ? isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol) + : true; + } + return false; + } + function isTopLevelValueImportEqualsWithEntityName(nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isImportEqualsDeclaration); + if (node === undefined || node.parent.kind !== 279 /* SourceFile */ || !ts.isInternalModuleImportEqualsDeclaration(node)) { + // parent is not source file or it is not reference to internal module + return false; + } + var isValue = isAliasResolvedToValue(getSymbolOfNode(node)); + return isValue && node.moduleReference && !ts.nodeIsMissing(node.moduleReference); + } + function isAliasResolvedToValue(symbol) { + var target = resolveAlias(symbol); + if (target === unknownSymbol) { + return true; + } + // const enums and modules that contain only const enums are not considered values from the emit perspective + // unless 'preserveConstEnums' option is set to true + return !!(target.flags & 67220415 /* Value */) && + (compilerOptions.preserveConstEnums || !isConstEnumOrConstEnumOnlyModule(target)); + } + function isConstEnumOrConstEnumOnlyModule(s) { + return isConstEnumSymbol(s) || !!s.constEnumOnlyModule; + } + function isReferencedAliasDeclaration(node, checkChildren) { + if (ts.isAliasSymbolDeclaration(node)) { + var symbol = getSymbolOfNode(node); + if (symbol && getSymbolLinks(symbol).referenced) { + return true; + } + var target = getSymbolLinks(symbol).target; // TODO: GH#18217 + if (target && ts.getModifierFlags(node) & 1 /* Export */ && + target.flags & 67220415 /* Value */ && (compilerOptions.preserveConstEnums || !isConstEnumOrConstEnumOnlyModule(target))) { + // An `export import ... =` of a value symbol is always considered referenced + return true; + } + } + if (checkChildren) { + return !!ts.forEachChild(node, function (node) { return isReferencedAliasDeclaration(node, checkChildren); }); + } + return false; + } + function isImplementationOfOverload(node) { + if (ts.nodeIsPresent(node.body)) { + if (ts.isGetAccessor(node) || ts.isSetAccessor(node)) + return false; // Get or set accessors can never be overload implementations, but can have up to 2 signatures + var symbol = getSymbolOfNode(node); + var signaturesOfSymbol = getSignaturesOfSymbol(symbol); + // If this function body corresponds to function with multiple signature, it is implementation of overload + // e.g.: function foo(a: string): string; + // function foo(a: number): number; + // function foo(a: any) { // This is implementation of the overloads + // return a; + // } + return signaturesOfSymbol.length > 1 || + // If there is single signature for the symbol, it is overload if that signature isn't coming from the node + // e.g.: function foo(a: string): string; + // function foo(a: any) { // This is implementation of the overloads + // return a; + // } + (signaturesOfSymbol.length === 1 && signaturesOfSymbol[0].declaration !== node); + } + return false; + } + function isRequiredInitializedParameter(parameter) { + return !!strictNullChecks && + !isOptionalParameter(parameter) && + !ts.isJSDocParameterTag(parameter) && + !!parameter.initializer && + !ts.hasModifier(parameter, 92 /* ParameterPropertyModifier */); + } + function isOptionalUninitializedParameterProperty(parameter) { + return strictNullChecks && + isOptionalParameter(parameter) && + !parameter.initializer && + ts.hasModifier(parameter, 92 /* ParameterPropertyModifier */); + } + function isExpandoFunctionDeclaration(node) { + var declaration = ts.getParseTreeNode(node, ts.isFunctionDeclaration); + if (!declaration) { + return false; + } + var symbol = getSymbolOfNode(declaration); + if (!symbol || !(symbol.flags & 16 /* Function */)) { + return false; + } + return !!ts.forEachEntry(getExportsOfSymbol(symbol), function (p) { return p.flags & 67220415 /* Value */ && ts.isPropertyAccessExpression(p.valueDeclaration); }); + } + function getPropertiesOfContainerFunction(node) { + var declaration = ts.getParseTreeNode(node, ts.isFunctionDeclaration); + if (!declaration) { + return ts.emptyArray; + } + var symbol = getSymbolOfNode(declaration); + return symbol && getPropertiesOfType(getTypeOfSymbol(symbol)) || ts.emptyArray; + } + function getNodeCheckFlags(node) { + return getNodeLinks(node).flags || 0; + } + function getEnumMemberValue(node) { + computeEnumMemberValues(node.parent); + return getNodeLinks(node).enumMemberValue; + } + function canHaveConstantValue(node) { + switch (node.kind) { + case 278 /* EnumMember */: + case 189 /* PropertyAccessExpression */: + case 190 /* ElementAccessExpression */: + return true; + } + return false; + } + function getConstantValue(node) { + if (node.kind === 278 /* EnumMember */) { + return getEnumMemberValue(node); + } + var symbol = getNodeLinks(node).resolvedSymbol; + if (symbol && (symbol.flags & 8 /* EnumMember */)) { + // inline property\index accesses only for const enums + var member = symbol.valueDeclaration; + if (ts.isEnumConst(member.parent)) { + return getEnumMemberValue(member); + } + } + return undefined; + } + function isFunctionType(type) { + return !!(type.flags & 524288 /* Object */) && getSignaturesOfType(type, 0 /* Call */).length > 0; + } + function getTypeReferenceSerializationKind(typeNameIn, location) { + // ensure both `typeName` and `location` are parse tree nodes. + var typeName = ts.getParseTreeNode(typeNameIn, ts.isEntityName); + if (!typeName) + return ts.TypeReferenceSerializationKind.Unknown; + if (location) { + location = ts.getParseTreeNode(location); + if (!location) + return ts.TypeReferenceSerializationKind.Unknown; + } + // Resolve the symbol as a value to ensure the type can be reached at runtime during emit. + var valueSymbol = resolveEntityName(typeName, 67220415 /* Value */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location); + // Resolve the symbol as a type so that we can provide a more useful hint for the type serializer. + var typeSymbol = resolveEntityName(typeName, 67897832 /* Type */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location); + if (valueSymbol && valueSymbol === typeSymbol) { + var globalPromiseSymbol = getGlobalPromiseConstructorSymbol(/*reportErrors*/ false); + if (globalPromiseSymbol && valueSymbol === globalPromiseSymbol) { + return ts.TypeReferenceSerializationKind.Promise; + } + var constructorType = getTypeOfSymbol(valueSymbol); + if (constructorType && isConstructorType(constructorType)) { + return ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue; + } + } + // We might not be able to resolve type symbol so use unknown type in that case (eg error case) + if (!typeSymbol) { + return ts.TypeReferenceSerializationKind.Unknown; + } + var type = getDeclaredTypeOfSymbol(typeSymbol); + if (type === errorType) { + return ts.TypeReferenceSerializationKind.Unknown; + } + else if (type.flags & 3 /* AnyOrUnknown */) { + return ts.TypeReferenceSerializationKind.ObjectType; + } + else if (isTypeAssignableToKind(type, 16384 /* Void */ | 98304 /* Nullable */ | 131072 /* Never */)) { + return ts.TypeReferenceSerializationKind.VoidNullableOrNeverType; + } + else if (isTypeAssignableToKind(type, 528 /* BooleanLike */)) { + return ts.TypeReferenceSerializationKind.BooleanType; + } + else if (isTypeAssignableToKind(type, 296 /* NumberLike */)) { + return ts.TypeReferenceSerializationKind.NumberLikeType; + } + else if (isTypeAssignableToKind(type, 2112 /* BigIntLike */)) { + return ts.TypeReferenceSerializationKind.BigIntLikeType; + } + else if (isTypeAssignableToKind(type, 132 /* StringLike */)) { + return ts.TypeReferenceSerializationKind.StringLikeType; + } + else if (isTupleType(type)) { + return ts.TypeReferenceSerializationKind.ArrayLikeType; + } + else if (isTypeAssignableToKind(type, 12288 /* ESSymbolLike */)) { + return ts.TypeReferenceSerializationKind.ESSymbolType; + } + else if (isFunctionType(type)) { + return ts.TypeReferenceSerializationKind.TypeWithCallSignature; + } + else if (isArrayType(type)) { + return ts.TypeReferenceSerializationKind.ArrayLikeType; + } + else { + return ts.TypeReferenceSerializationKind.ObjectType; + } + } + function createTypeOfDeclaration(declarationIn, enclosingDeclaration, flags, tracker, addUndefined) { + var declaration = ts.getParseTreeNode(declarationIn, ts.isVariableLikeOrAccessor); + if (!declaration) { + return ts.createToken(120 /* AnyKeyword */); + } + // Get type of the symbol if this is the valid symbol otherwise get type at location + var symbol = getSymbolOfNode(declaration); + var type = symbol && !(symbol.flags & (2048 /* TypeLiteral */ | 131072 /* Signature */)) + ? getWidenedLiteralType(getTypeOfSymbol(symbol)) + : errorType; + if (type.flags & 8192 /* UniqueESSymbol */ && + type.symbol === symbol) { + flags |= 1048576 /* AllowUniqueESSymbolType */; + } + if (addUndefined) { + type = getOptionalType(type); + } + return nodeBuilder.typeToTypeNode(type, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, tracker); + } + function createReturnTypeOfSignatureDeclaration(signatureDeclarationIn, enclosingDeclaration, flags, tracker) { + var signatureDeclaration = ts.getParseTreeNode(signatureDeclarationIn, ts.isFunctionLike); + if (!signatureDeclaration) { + return ts.createToken(120 /* AnyKeyword */); + } + var signature = getSignatureFromDeclaration(signatureDeclaration); + return nodeBuilder.typeToTypeNode(getReturnTypeOfSignature(signature), enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, tracker); + } + function createTypeOfExpression(exprIn, enclosingDeclaration, flags, tracker) { + var expr = ts.getParseTreeNode(exprIn, ts.isExpression); + if (!expr) { + return ts.createToken(120 /* AnyKeyword */); + } + var type = getWidenedType(getRegularTypeOfExpression(expr)); + return nodeBuilder.typeToTypeNode(type, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, tracker); + } + function hasGlobalName(name) { + return globals.has(ts.escapeLeadingUnderscores(name)); + } + function getReferencedValueSymbol(reference, startInDeclarationContainer) { + var resolvedSymbol = getNodeLinks(reference).resolvedSymbol; + if (resolvedSymbol) { + return resolvedSymbol; + } + var location = reference; + if (startInDeclarationContainer) { + // When resolving the name of a declaration as a value, we need to start resolution + // at a point outside of the declaration. + var parent = reference.parent; + if (ts.isDeclaration(parent) && reference === parent.name) { + location = getDeclarationContainer(parent); + } + } + return resolveName(location, reference.escapedText, 67220415 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */, /*nodeNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); + } + function getReferencedValueDeclaration(referenceIn) { + if (!ts.isGeneratedIdentifier(referenceIn)) { + var reference = ts.getParseTreeNode(referenceIn, ts.isIdentifier); + if (reference) { + var symbol = getReferencedValueSymbol(reference); + if (symbol) { + return getExportSymbolOfValueSymbolIfExported(symbol).valueDeclaration; + } + } + } + return undefined; + } + function isLiteralConstDeclaration(node) { + if (ts.isDeclarationReadonly(node) || ts.isVariableDeclaration(node) && ts.isVarConst(node)) { + return isFreshLiteralType(getTypeOfSymbol(getSymbolOfNode(node))); + } + return false; + } + function literalTypeToNode(type, enclosing, tracker) { + var enumResult = type.flags & 1024 /* EnumLiteral */ ? nodeBuilder.symbolToExpression(type.symbol, 67220415 /* Value */, enclosing, /*flags*/ undefined, tracker) + : type === trueType ? ts.createTrue() : type === falseType && ts.createFalse(); + return enumResult || ts.createLiteral(type.value); + } + function createLiteralConstValue(node, tracker) { + var type = getTypeOfSymbol(getSymbolOfNode(node)); + return literalTypeToNode(type, node, tracker); + } + function createResolver() { + // this variable and functions that use it are deliberately moved here from the outer scope + // to avoid scope pollution + var resolvedTypeReferenceDirectives = host.getResolvedTypeReferenceDirectives(); + var fileToDirective; + if (resolvedTypeReferenceDirectives) { + // populate reverse mapping: file path -> type reference directive that was resolved to this file + fileToDirective = ts.createMap(); + resolvedTypeReferenceDirectives.forEach(function (resolvedDirective, key) { + if (!resolvedDirective || !resolvedDirective.resolvedFileName) { + return; + } + var file = host.getSourceFile(resolvedDirective.resolvedFileName); + fileToDirective.set(file.path, key); + }); + } + return { + getReferencedExportContainer: getReferencedExportContainer, + getReferencedImportDeclaration: getReferencedImportDeclaration, + getReferencedDeclarationWithCollidingName: getReferencedDeclarationWithCollidingName, + isDeclarationWithCollidingName: isDeclarationWithCollidingName, + isValueAliasDeclaration: function (node) { + node = ts.getParseTreeNode(node); + // Synthesized nodes are always treated like values. + return node ? isValueAliasDeclaration(node) : true; + }, + hasGlobalName: hasGlobalName, + isReferencedAliasDeclaration: function (node, checkChildren) { + node = ts.getParseTreeNode(node); + // Synthesized nodes are always treated as referenced. + return node ? isReferencedAliasDeclaration(node, checkChildren) : true; + }, + getNodeCheckFlags: function (node) { + node = ts.getParseTreeNode(node); + return node ? getNodeCheckFlags(node) : 0; + }, + isTopLevelValueImportEqualsWithEntityName: isTopLevelValueImportEqualsWithEntityName, + isDeclarationVisible: isDeclarationVisible, + isImplementationOfOverload: isImplementationOfOverload, + isRequiredInitializedParameter: isRequiredInitializedParameter, + isOptionalUninitializedParameterProperty: isOptionalUninitializedParameterProperty, + isExpandoFunctionDeclaration: isExpandoFunctionDeclaration, + getPropertiesOfContainerFunction: getPropertiesOfContainerFunction, + createTypeOfDeclaration: createTypeOfDeclaration, + createReturnTypeOfSignatureDeclaration: createReturnTypeOfSignatureDeclaration, + createTypeOfExpression: createTypeOfExpression, + createLiteralConstValue: createLiteralConstValue, + isSymbolAccessible: isSymbolAccessible, + isEntityNameVisible: isEntityNameVisible, + getConstantValue: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, canHaveConstantValue); + return node ? getConstantValue(node) : undefined; + }, + collectLinkedAliases: collectLinkedAliases, + getReferencedValueDeclaration: getReferencedValueDeclaration, + getTypeReferenceSerializationKind: getTypeReferenceSerializationKind, + isOptionalParameter: isOptionalParameter, + moduleExportsSomeValue: moduleExportsSomeValue, + isArgumentsLocalBinding: isArgumentsLocalBinding, + getExternalModuleFileFromDeclaration: getExternalModuleFileFromDeclaration, + getTypeReferenceDirectivesForEntityName: getTypeReferenceDirectivesForEntityName, + getTypeReferenceDirectivesForSymbol: getTypeReferenceDirectivesForSymbol, + isLiteralConstDeclaration: isLiteralConstDeclaration, + isLateBound: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isDeclaration); + var symbol = node && getSymbolOfNode(node); + return !!(symbol && ts.getCheckFlags(symbol) & 1024 /* Late */); + }, + getJsxFactoryEntity: function (location) { return location ? (getJsxNamespace(location), (ts.getSourceFileOfNode(location).localJsxFactory || _jsxFactoryEntity)) : _jsxFactoryEntity; }, + getAllAccessorDeclarations: function (accessor) { + accessor = ts.getParseTreeNode(accessor, ts.isGetOrSetAccessorDeclaration); // TODO: GH#18217 + var otherKind = accessor.kind === 159 /* SetAccessor */ ? 158 /* GetAccessor */ : 159 /* SetAccessor */; + var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(accessor), otherKind); + var firstAccessor = otherAccessor && (otherAccessor.pos < accessor.pos) ? otherAccessor : accessor; + var secondAccessor = otherAccessor && (otherAccessor.pos < accessor.pos) ? accessor : otherAccessor; + var setAccessor = accessor.kind === 159 /* SetAccessor */ ? accessor : otherAccessor; + var getAccessor = accessor.kind === 158 /* GetAccessor */ ? accessor : otherAccessor; + return { + firstAccessor: firstAccessor, + secondAccessor: secondAccessor, + setAccessor: setAccessor, + getAccessor: getAccessor + }; + }, + getSymbolOfExternalModuleSpecifier: function (moduleName) { return resolveExternalModuleNameWorker(moduleName, moduleName, /*moduleNotFoundError*/ undefined); }, + isBindingCapturedByNode: function (node, decl) { + var parseNode = ts.getParseTreeNode(node); + var parseDecl = ts.getParseTreeNode(decl); + return !!parseNode && !!parseDecl && (ts.isVariableDeclaration(parseDecl) || ts.isBindingElement(parseDecl)) && isBindingCapturedByNode(parseNode, parseDecl); + } + }; + function isInHeritageClause(node) { + return node.parent && node.parent.kind === 211 /* ExpressionWithTypeArguments */ && node.parent.parent && node.parent.parent.kind === 273 /* HeritageClause */; + } + // defined here to avoid outer scope pollution + function getTypeReferenceDirectivesForEntityName(node) { + // program does not have any files with type reference directives - bail out + if (!fileToDirective) { + return undefined; + } + // property access can only be used as values, or types when within an expression with type arguments inside a heritage clause + // qualified names can only be used as types\namespaces + // identifiers are treated as values only if they appear in type queries + var meaning = 67897832 /* Type */ | 1920 /* Namespace */; + if ((node.kind === 72 /* Identifier */ && isInTypeQuery(node)) || (node.kind === 189 /* PropertyAccessExpression */ && !isInHeritageClause(node))) { + meaning = 67220415 /* Value */ | 1048576 /* ExportValue */; + } + var symbol = resolveEntityName(node, meaning, /*ignoreErrors*/ true); + return symbol && symbol !== unknownSymbol ? getTypeReferenceDirectivesForSymbol(symbol, meaning) : undefined; + } + // defined here to avoid outer scope pollution + function getTypeReferenceDirectivesForSymbol(symbol, meaning) { + // program does not have any files with type reference directives - bail out + if (!fileToDirective) { + return undefined; + } + if (!isSymbolFromTypeDeclarationFile(symbol)) { + return undefined; + } + // check what declarations in the symbol can contribute to the target meaning + var typeReferenceDirectives; + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + // check meaning of the local symbol to see if declaration needs to be analyzed further + if (decl.symbol && decl.symbol.flags & meaning) { + var file = ts.getSourceFileOfNode(decl); + var typeReferenceDirective = fileToDirective.get(file.path); + if (typeReferenceDirective) { + (typeReferenceDirectives || (typeReferenceDirectives = [])).push(typeReferenceDirective); + } + else { + // found at least one entry that does not originate from type reference directive + return undefined; + } + } + } + return typeReferenceDirectives; + } + function isSymbolFromTypeDeclarationFile(symbol) { + // bail out if symbol does not have associated declarations (i.e. this is transient symbol created for property in binding pattern) + if (!symbol.declarations) { + return false; + } + // walk the parent chain for symbols to make sure that top level parent symbol is in the global scope + // external modules cannot define or contribute to type declaration files + var current = symbol; + while (true) { + var parent = getParentOfSymbol(current); + if (parent) { + current = parent; + } + else { + break; + } + } + if (current.valueDeclaration && current.valueDeclaration.kind === 279 /* SourceFile */ && current.flags & 512 /* ValueModule */) { + return false; + } + // check that at least one declaration of top level symbol originates from type declaration file + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + var file = ts.getSourceFileOfNode(decl); + if (fileToDirective.has(file.path)) { + return true; + } + } + return false; + } + } + function getExternalModuleFileFromDeclaration(declaration) { + var specifier = declaration.kind === 244 /* ModuleDeclaration */ ? ts.tryCast(declaration.name, ts.isStringLiteral) : ts.getExternalModuleName(declaration); + var moduleSymbol = resolveExternalModuleNameWorker(specifier, specifier, /*moduleNotFoundError*/ undefined); // TODO: GH#18217 + if (!moduleSymbol) { + return undefined; + } + return ts.getDeclarationOfKind(moduleSymbol, 279 /* SourceFile */); + } + function initializeTypeChecker() { + // Bind all source files and propagate errors + for (var _i = 0, _a = host.getSourceFiles(); _i < _a.length; _i++) { + var file = _a[_i]; + ts.bindSourceFile(file, compilerOptions); + } + amalgamatedDuplicates = ts.createMap(); + // Initialize global symbol table + var augmentations; + for (var _b = 0, _c = host.getSourceFiles(); _b < _c.length; _b++) { + var file = _c[_b]; + if (file.redirectInfo) { + continue; + } + if (!ts.isExternalOrCommonJsModule(file)) { + mergeSymbolTable(globals, file.locals); + } + if (file.jsGlobalAugmentations) { + mergeSymbolTable(globals, file.jsGlobalAugmentations); + } + if (file.patternAmbientModules && file.patternAmbientModules.length) { + patternAmbientModules = ts.concatenate(patternAmbientModules, file.patternAmbientModules); + } + if (file.moduleAugmentations.length) { + (augmentations || (augmentations = [])).push(file.moduleAugmentations); + } + if (file.symbol && file.symbol.globalExports) { + // Merge in UMD exports with first-in-wins semantics (see #9771) + var source = file.symbol.globalExports; + source.forEach(function (sourceSymbol, id) { + if (!globals.has(id)) { + globals.set(id, sourceSymbol); + } + }); + } + } + // We do global augmentations separately from module augmentations (and before creating global types) because they + // 1. Affect global types. We won't have the correct global types until global augmentations are merged. Also, + // 2. Module augmentation instantiation requires creating the type of a module, which, in turn, can require + // checking for an export or property on the module (if export=) which, in turn, can fall back to the + // apparent type of the module - either globalObjectType or globalFunctionType - which wouldn't exist if we + // did module augmentations prior to finalizing the global types. + if (augmentations) { + // merge _global_ module augmentations. + // this needs to be done after global symbol table is initialized to make sure that all ambient modules are indexed + for (var _d = 0, augmentations_1 = augmentations; _d < augmentations_1.length; _d++) { + var list = augmentations_1[_d]; + for (var _e = 0, list_1 = list; _e < list_1.length; _e++) { + var augmentation = list_1[_e]; + if (!ts.isGlobalScopeAugmentation(augmentation.parent)) + continue; + mergeModuleAugmentation(augmentation); + } + } + } + // Setup global builtins + addToSymbolTable(globals, builtinGlobals, ts.Diagnostics.Declaration_name_conflicts_with_built_in_global_identifier_0); + getSymbolLinks(undefinedSymbol).type = undefinedWideningType; + getSymbolLinks(argumentsSymbol).type = getGlobalType("IArguments", /*arity*/ 0, /*reportErrors*/ true); + getSymbolLinks(unknownSymbol).type = errorType; + // Initialize special types + globalArrayType = getGlobalType("Array", /*arity*/ 1, /*reportErrors*/ true); + globalObjectType = getGlobalType("Object", /*arity*/ 0, /*reportErrors*/ true); + globalFunctionType = getGlobalType("Function", /*arity*/ 0, /*reportErrors*/ true); + globalCallableFunctionType = strictBindCallApply && getGlobalType("CallableFunction", /*arity*/ 0, /*reportErrors*/ true) || globalFunctionType; + globalNewableFunctionType = strictBindCallApply && getGlobalType("NewableFunction", /*arity*/ 0, /*reportErrors*/ true) || globalFunctionType; + globalStringType = getGlobalType("String", /*arity*/ 0, /*reportErrors*/ true); + globalNumberType = getGlobalType("Number", /*arity*/ 0, /*reportErrors*/ true); + globalBooleanType = getGlobalType("Boolean", /*arity*/ 0, /*reportErrors*/ true); + globalRegExpType = getGlobalType("RegExp", /*arity*/ 0, /*reportErrors*/ true); + anyArrayType = createArrayType(anyType); + autoArrayType = createArrayType(autoType); + if (autoArrayType === emptyObjectType) { + // autoArrayType is used as a marker, so even if global Array type is not defined, it needs to be a unique type + autoArrayType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + } + globalReadonlyArrayType = getGlobalTypeOrUndefined("ReadonlyArray", /*arity*/ 1); + anyReadonlyArrayType = globalReadonlyArrayType ? createTypeFromGenericGlobalType(globalReadonlyArrayType, [anyType]) : anyArrayType; + globalThisType = getGlobalTypeOrUndefined("ThisType", /*arity*/ 1); + if (augmentations) { + // merge _nonglobal_ module augmentations. + // this needs to be done after global symbol table is initialized to make sure that all ambient modules are indexed + for (var _f = 0, augmentations_2 = augmentations; _f < augmentations_2.length; _f++) { + var list = augmentations_2[_f]; + for (var _g = 0, list_2 = list; _g < list_2.length; _g++) { + var augmentation = list_2[_g]; + if (ts.isGlobalScopeAugmentation(augmentation.parent)) + continue; + mergeModuleAugmentation(augmentation); + } + } + } + amalgamatedDuplicates.forEach(function (_a) { + var firstFile = _a.firstFile, secondFile = _a.secondFile, conflictingSymbols = _a.conflictingSymbols; + // If not many things conflict, issue individual errors + if (conflictingSymbols.size < 8) { + conflictingSymbols.forEach(function (_a, symbolName) { + var isBlockScoped = _a.isBlockScoped, firstFileLocations = _a.firstFileLocations, secondFileLocations = _a.secondFileLocations; + var message = isBlockScoped ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 : ts.Diagnostics.Duplicate_identifier_0; + for (var _i = 0, firstFileLocations_1 = firstFileLocations; _i < firstFileLocations_1.length; _i++) { + var node = firstFileLocations_1[_i]; + addDuplicateDeclarationError(node, message, symbolName, secondFileLocations); + } + for (var _b = 0, secondFileLocations_1 = secondFileLocations; _b < secondFileLocations_1.length; _b++) { + var node = secondFileLocations_1[_b]; + addDuplicateDeclarationError(node, message, symbolName, firstFileLocations); + } + }); + } + else { + // Otherwise issue top-level error since the files appear very identical in terms of what they contain + var list = ts.arrayFrom(conflictingSymbols.keys()).join(", "); + diagnostics.add(addRelatedInfo(ts.createDiagnosticForNode(firstFile, ts.Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list), ts.createDiagnosticForNode(secondFile, ts.Diagnostics.Conflicts_are_in_this_file))); + diagnostics.add(addRelatedInfo(ts.createDiagnosticForNode(secondFile, ts.Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list), ts.createDiagnosticForNode(firstFile, ts.Diagnostics.Conflicts_are_in_this_file))); + } + }); + amalgamatedDuplicates = undefined; + } + function checkExternalEmitHelpers(location, helpers) { + if ((requestedExternalEmitHelpers & helpers) !== helpers && compilerOptions.importHelpers) { + var sourceFile = ts.getSourceFileOfNode(location); + if (ts.isEffectiveExternalModule(sourceFile, compilerOptions) && !(location.flags & 4194304 /* Ambient */)) { + var helpersModule = resolveHelpersModule(sourceFile, location); + if (helpersModule !== unknownSymbol) { + var uncheckedHelpers = helpers & ~requestedExternalEmitHelpers; + for (var helper = 1 /* FirstEmitHelper */; helper <= 65536 /* LastEmitHelper */; helper <<= 1) { + if (uncheckedHelpers & helper) { + var name = getHelperName(helper); + var symbol = getSymbol(helpersModule.exports, ts.escapeLeadingUnderscores(name), 67220415 /* Value */); + if (!symbol) { + error(location, ts.Diagnostics.This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1, ts.externalHelpersModuleNameText, name); + } + } + } + } + requestedExternalEmitHelpers |= helpers; + } + } + } + function getHelperName(helper) { + switch (helper) { + case 1 /* Extends */: return "__extends"; + case 2 /* Assign */: return "__assign"; + case 4 /* Rest */: return "__rest"; + case 8 /* Decorate */: return "__decorate"; + case 16 /* Metadata */: return "__metadata"; + case 32 /* Param */: return "__param"; + case 64 /* Awaiter */: return "__awaiter"; + case 128 /* Generator */: return "__generator"; + case 256 /* Values */: return "__values"; + case 512 /* Read */: return "__read"; + case 1024 /* Spread */: return "__spread"; + case 2048 /* Await */: return "__await"; + case 4096 /* AsyncGenerator */: return "__asyncGenerator"; + case 8192 /* AsyncDelegator */: return "__asyncDelegator"; + case 16384 /* AsyncValues */: return "__asyncValues"; + case 32768 /* ExportStar */: return "__exportStar"; + case 65536 /* MakeTemplateObject */: return "__makeTemplateObject"; + default: return ts.Debug.fail("Unrecognized helper"); + } + } + function resolveHelpersModule(node, errorNode) { + if (!externalHelpersModule) { + externalHelpersModule = resolveExternalModule(node, ts.externalHelpersModuleNameText, ts.Diagnostics.This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found, errorNode) || unknownSymbol; + } + return externalHelpersModule; + } + // GRAMMAR CHECKING + function checkGrammarDecoratorsAndModifiers(node) { + return checkGrammarDecorators(node) || checkGrammarModifiers(node); + } + function checkGrammarDecorators(node) { + if (!node.decorators) { + return false; + } + if (!ts.nodeCanBeDecorated(node, node.parent, node.parent.parent)) { + if (node.kind === 156 /* MethodDeclaration */ && !ts.nodeIsPresent(node.body)) { + return grammarErrorOnFirstToken(node, ts.Diagnostics.A_decorator_can_only_decorate_a_method_implementation_not_an_overload); + } + else { + return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_are_not_valid_here); + } + } + else if (node.kind === 158 /* GetAccessor */ || node.kind === 159 /* SetAccessor */) { + var accessors = ts.getAllAccessorDeclarations(node.parent.members, node); + if (accessors.firstAccessor.decorators && node === accessors.secondAccessor) { + return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name); + } + } + return false; + } + function checkGrammarModifiers(node) { + var quickResult = reportObviousModifierErrors(node); + if (quickResult !== undefined) { + return quickResult; + } + var lastStatic, lastDeclare, lastAsync, lastReadonly; + var flags = 0 /* None */; + for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) { + var modifier = _a[_i]; + if (modifier.kind !== 133 /* ReadonlyKeyword */) { + if (node.kind === 153 /* PropertySignature */ || node.kind === 155 /* MethodSignature */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_type_member, ts.tokenToString(modifier.kind)); + } + if (node.kind === 162 /* IndexSignature */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_an_index_signature, ts.tokenToString(modifier.kind)); + } + } + switch (modifier.kind) { + case 77 /* ConstKeyword */: + if (node.kind !== 243 /* EnumDeclaration */) { + return grammarErrorOnNode(node, ts.Diagnostics.A_class_member_cannot_have_the_0_keyword, ts.tokenToString(77 /* ConstKeyword */)); + } + break; + case 115 /* PublicKeyword */: + case 114 /* ProtectedKeyword */: + case 113 /* PrivateKeyword */: + var text = visibilityToString(ts.modifierToFlag(modifier.kind)); + if (flags & 28 /* AccessibilityModifier */) { + return grammarErrorOnNode(modifier, ts.Diagnostics.Accessibility_modifier_already_seen); + } + else if (flags & 32 /* Static */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "static"); + } + else if (flags & 64 /* Readonly */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "readonly"); + } + else if (flags & 256 /* Async */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "async"); + } + else if (node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 279 /* SourceFile */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, text); + } + else if (flags & 128 /* Abstract */) { + if (modifier.kind === 113 /* PrivateKeyword */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, text, "abstract"); + } + else { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "abstract"); + } + } + flags |= ts.modifierToFlag(modifier.kind); + break; + case 116 /* StaticKeyword */: + if (flags & 32 /* Static */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "static"); + } + else if (flags & 64 /* Readonly */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "readonly"); + } + else if (flags & 256 /* Async */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "async"); + } + else if (node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 279 /* SourceFile */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, "static"); + } + else if (node.kind === 151 /* Parameter */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "static"); + } + else if (flags & 128 /* Abstract */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "abstract"); + } + flags |= 32 /* Static */; + lastStatic = modifier; + break; + case 133 /* ReadonlyKeyword */: + if (flags & 64 /* Readonly */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "readonly"); + } + else if (node.kind !== 154 /* PropertyDeclaration */ && node.kind !== 153 /* PropertySignature */ && node.kind !== 162 /* IndexSignature */ && node.kind !== 151 /* Parameter */) { + // If node.kind === SyntaxKind.Parameter, checkParameter report an error if it's not a parameter property. + return grammarErrorOnNode(modifier, ts.Diagnostics.readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature); + } + flags |= 64 /* Readonly */; + lastReadonly = modifier; + break; + case 85 /* ExportKeyword */: + if (flags & 1 /* Export */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "export"); + } + else if (flags & 2 /* Ambient */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "declare"); + } + else if (flags & 128 /* Abstract */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "abstract"); + } + else if (flags & 256 /* Async */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "async"); + } + else if (node.parent.kind === 240 /* ClassDeclaration */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_class_element, "export"); + } + else if (node.kind === 151 /* Parameter */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "export"); + } + flags |= 1 /* Export */; + break; + case 80 /* DefaultKeyword */: + var container = node.parent.kind === 279 /* SourceFile */ ? node.parent : node.parent.parent; + if (container.kind === 244 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) { + return grammarErrorOnNode(modifier, ts.Diagnostics.A_default_export_can_only_be_used_in_an_ECMAScript_style_module); + } + flags |= 512 /* Default */; + break; + case 125 /* DeclareKeyword */: + if (flags & 2 /* Ambient */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "declare"); + } + else if (flags & 256 /* Async */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async"); + } + else if (node.parent.kind === 240 /* ClassDeclaration */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_class_element, "declare"); + } + else if (node.kind === 151 /* Parameter */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "declare"); + } + else if ((node.parent.flags & 4194304 /* Ambient */) && node.parent.kind === 245 /* ModuleBlock */) { + return grammarErrorOnNode(modifier, ts.Diagnostics.A_declare_modifier_cannot_be_used_in_an_already_ambient_context); + } + flags |= 2 /* Ambient */; + lastDeclare = modifier; + break; + case 118 /* AbstractKeyword */: + if (flags & 128 /* Abstract */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "abstract"); + } + if (node.kind !== 240 /* ClassDeclaration */) { + if (node.kind !== 156 /* MethodDeclaration */ && + node.kind !== 154 /* PropertyDeclaration */ && + node.kind !== 158 /* GetAccessor */ && + node.kind !== 159 /* SetAccessor */) { + return grammarErrorOnNode(modifier, ts.Diagnostics.abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration); + } + if (!(node.parent.kind === 240 /* ClassDeclaration */ && ts.hasModifier(node.parent, 128 /* Abstract */))) { + return grammarErrorOnNode(modifier, ts.Diagnostics.Abstract_methods_can_only_appear_within_an_abstract_class); + } + if (flags & 32 /* Static */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "abstract"); + } + if (flags & 8 /* Private */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "private", "abstract"); + } + } + flags |= 128 /* Abstract */; + break; + case 121 /* AsyncKeyword */: + if (flags & 256 /* Async */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "async"); + } + else if (flags & 2 /* Ambient */ || node.parent.flags & 4194304 /* Ambient */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async"); + } + else if (node.kind === 151 /* Parameter */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "async"); + } + flags |= 256 /* Async */; + lastAsync = modifier; + break; + } + } + if (node.kind === 157 /* Constructor */) { + if (flags & 32 /* Static */) { + return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "static"); + } + if (flags & 128 /* Abstract */) { + return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "abstract"); // TODO: GH#18217 + } + else if (flags & 256 /* Async */) { + return grammarErrorOnNode(lastAsync, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "async"); + } + else if (flags & 64 /* Readonly */) { + return grammarErrorOnNode(lastReadonly, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "readonly"); + } + return false; + } + else if ((node.kind === 249 /* ImportDeclaration */ || node.kind === 248 /* ImportEqualsDeclaration */) && flags & 2 /* Ambient */) { + return grammarErrorOnNode(lastDeclare, ts.Diagnostics.A_0_modifier_cannot_be_used_with_an_import_declaration, "declare"); + } + else if (node.kind === 151 /* Parameter */ && (flags & 92 /* ParameterPropertyModifier */) && ts.isBindingPattern(node.name)) { + return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_may_not_be_declared_using_a_binding_pattern); + } + else if (node.kind === 151 /* Parameter */ && (flags & 92 /* ParameterPropertyModifier */) && node.dotDotDotToken) { + return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_cannot_be_declared_using_a_rest_parameter); + } + if (flags & 256 /* Async */) { + return checkGrammarAsyncModifier(node, lastAsync); + } + return false; + } + /** + * true | false: Early return this value from checkGrammarModifiers. + * undefined: Need to do full checking on the modifiers. + */ + function reportObviousModifierErrors(node) { + return !node.modifiers + ? false + : shouldReportBadModifier(node) + ? grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here) + : undefined; + } + function shouldReportBadModifier(node) { + switch (node.kind) { + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 157 /* Constructor */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 162 /* IndexSignature */: + case 244 /* ModuleDeclaration */: + case 249 /* ImportDeclaration */: + case 248 /* ImportEqualsDeclaration */: + case 255 /* ExportDeclaration */: + case 254 /* ExportAssignment */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 151 /* Parameter */: + return false; + default: + if (node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 279 /* SourceFile */) { + return false; + } + switch (node.kind) { + case 239 /* FunctionDeclaration */: + return nodeHasAnyModifiersExcept(node, 121 /* AsyncKeyword */); + case 240 /* ClassDeclaration */: + return nodeHasAnyModifiersExcept(node, 118 /* AbstractKeyword */); + case 241 /* InterfaceDeclaration */: + case 219 /* VariableStatement */: + case 242 /* TypeAliasDeclaration */: + return true; + case 243 /* EnumDeclaration */: + return nodeHasAnyModifiersExcept(node, 77 /* ConstKeyword */); + default: + ts.Debug.fail(); + return false; + } + } + } + function nodeHasAnyModifiersExcept(node, allowedModifier) { + return node.modifiers.length > 1 || node.modifiers[0].kind !== allowedModifier; + } + function checkGrammarAsyncModifier(node, asyncModifier) { + switch (node.kind) { + case 156 /* MethodDeclaration */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + return false; + } + return grammarErrorOnNode(asyncModifier, ts.Diagnostics._0_modifier_cannot_be_used_here, "async"); + } + function checkGrammarForDisallowedTrailingComma(list, diag) { + if (diag === void 0) { diag = ts.Diagnostics.Trailing_comma_not_allowed; } + if (list && list.hasTrailingComma) { + return grammarErrorAtPos(list[0], list.end - ",".length, ",".length, diag); + } + return false; + } + function checkGrammarTypeParameterList(typeParameters, file) { + if (typeParameters && typeParameters.length === 0) { + var start = typeParameters.pos - "<".length; + var end = ts.skipTrivia(file.text, typeParameters.end) + ">".length; + return grammarErrorAtPos(file, start, end - start, ts.Diagnostics.Type_parameter_list_cannot_be_empty); + } + return false; + } + function checkGrammarParameterList(parameters) { + var seenOptionalParameter = false; + var parameterCount = parameters.length; + for (var i = 0; i < parameterCount; i++) { + var parameter = parameters[i]; + if (parameter.dotDotDotToken) { + if (i !== (parameterCount - 1)) { + return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.A_rest_parameter_must_be_last_in_a_parameter_list); + } + if (!(parameter.flags & 4194304 /* Ambient */)) { // Allow `...foo,` in ambient declarations; see GH#23070 + checkGrammarForDisallowedTrailingComma(parameters, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma); + } + if (ts.isBindingPattern(parameter.name)) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.A_rest_element_cannot_contain_a_binding_pattern); + } + if (parameter.questionToken) { + return grammarErrorOnNode(parameter.questionToken, ts.Diagnostics.A_rest_parameter_cannot_be_optional); + } + if (parameter.initializer) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.A_rest_parameter_cannot_have_an_initializer); + } + } + else if (parameter.questionToken) { + seenOptionalParameter = true; + if (parameter.initializer) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.Parameter_cannot_have_question_mark_and_initializer); + } + } + else if (seenOptionalParameter && !parameter.initializer) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.A_required_parameter_cannot_follow_an_optional_parameter); + } + } + } + function getNonSimpleParameters(parameters) { + return ts.filter(parameters, function (parameter) { return !!parameter.initializer || ts.isBindingPattern(parameter.name) || ts.isRestParameter(parameter); }); + } + function checkGrammarForUseStrictSimpleParameterList(node) { + if (languageVersion >= 3 /* ES2016 */) { + var useStrictDirective_1 = node.body && ts.isBlock(node.body) && ts.findUseStrictPrologue(node.body.statements); + if (useStrictDirective_1) { + var nonSimpleParameters = getNonSimpleParameters(node.parameters); + if (ts.length(nonSimpleParameters)) { + ts.forEach(nonSimpleParameters, function (parameter) { + addRelatedInfo(error(parameter, ts.Diagnostics.This_parameter_is_not_allowed_with_use_strict_directive), ts.createDiagnosticForNode(useStrictDirective_1, ts.Diagnostics.use_strict_directive_used_here)); + }); + var diagnostics_1 = nonSimpleParameters.map(function (parameter, index) { return (index === 0 ? ts.createDiagnosticForNode(parameter, ts.Diagnostics.Non_simple_parameter_declared_here) : ts.createDiagnosticForNode(parameter, ts.Diagnostics.and_here)); }); + addRelatedInfo.apply(void 0, [error(useStrictDirective_1, ts.Diagnostics.use_strict_directive_cannot_be_used_with_non_simple_parameter_list)].concat(diagnostics_1)); + return true; + } + } + } + return false; + } + function checkGrammarFunctionLikeDeclaration(node) { + // Prevent cascading error by short-circuit + var file = ts.getSourceFileOfNode(node); + return checkGrammarDecoratorsAndModifiers(node) || checkGrammarTypeParameterList(node.typeParameters, file) || + checkGrammarParameterList(node.parameters) || checkGrammarArrowFunction(node, file) || + (ts.isFunctionLikeDeclaration(node) && checkGrammarForUseStrictSimpleParameterList(node)); + } + function checkGrammarClassLikeDeclaration(node) { + var file = ts.getSourceFileOfNode(node); + return checkGrammarClassDeclarationHeritageClauses(node) || checkGrammarTypeParameterList(node.typeParameters, file); + } + function checkGrammarArrowFunction(node, file) { + if (!ts.isArrowFunction(node)) { + return false; + } + var equalsGreaterThanToken = node.equalsGreaterThanToken; + var startLine = ts.getLineAndCharacterOfPosition(file, equalsGreaterThanToken.pos).line; + var endLine = ts.getLineAndCharacterOfPosition(file, equalsGreaterThanToken.end).line; + return startLine !== endLine && grammarErrorOnNode(equalsGreaterThanToken, ts.Diagnostics.Line_terminator_not_permitted_before_arrow); + } + function checkGrammarIndexSignatureParameters(node) { + var parameter = node.parameters[0]; + if (node.parameters.length !== 1) { + if (parameter) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_must_have_exactly_one_parameter); + } + else { + return grammarErrorOnNode(node, ts.Diagnostics.An_index_signature_must_have_exactly_one_parameter); + } + } + if (parameter.dotDotDotToken) { + return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.An_index_signature_cannot_have_a_rest_parameter); + } + if (ts.hasModifiers(parameter)) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_cannot_have_an_accessibility_modifier); + } + if (parameter.questionToken) { + return grammarErrorOnNode(parameter.questionToken, ts.Diagnostics.An_index_signature_parameter_cannot_have_a_question_mark); + } + if (parameter.initializer) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_cannot_have_an_initializer); + } + if (!parameter.type) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_must_have_a_type_annotation); + } + if (parameter.type.kind !== 138 /* StringKeyword */ && parameter.type.kind !== 135 /* NumberKeyword */) { + var type = getTypeFromTypeNode(parameter.type); + if (type.flags & 4 /* String */ || type.flags & 8 /* Number */) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead, ts.getTextOfNode(parameter.name), typeToString(type), typeToString(getTypeFromTypeNode(node.type))); + } + if (type.flags & 1048576 /* Union */ && allTypesAssignableToKind(type, 128 /* StringLiteral */, /*strict*/ true)) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead); + } + return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_must_be_string_or_number); + } + if (!node.type) { + return grammarErrorOnNode(node, ts.Diagnostics.An_index_signature_must_have_a_type_annotation); + } + return false; + } + function checkGrammarIndexSignature(node) { + // Prevent cascading error by short-circuit + return checkGrammarDecoratorsAndModifiers(node) || checkGrammarIndexSignatureParameters(node); + } + function checkGrammarForAtLeastOneTypeArgument(node, typeArguments) { + if (typeArguments && typeArguments.length === 0) { + var sourceFile = ts.getSourceFileOfNode(node); + var start = typeArguments.pos - "<".length; + var end = ts.skipTrivia(sourceFile.text, typeArguments.end) + ">".length; + return grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.Type_argument_list_cannot_be_empty); + } + return false; + } + function checkGrammarTypeArguments(node, typeArguments) { + return checkGrammarForDisallowedTrailingComma(typeArguments) || + checkGrammarForAtLeastOneTypeArgument(node, typeArguments); + } + function checkGrammarForOmittedArgument(args) { + if (args) { + for (var _i = 0, args_5 = args; _i < args_5.length; _i++) { + var arg = args_5[_i]; + if (arg.kind === 210 /* OmittedExpression */) { + return grammarErrorAtPos(arg, arg.pos, 0, ts.Diagnostics.Argument_expression_expected); + } + } + } + return false; + } + function checkGrammarArguments(args) { + return checkGrammarForOmittedArgument(args); + } + function checkGrammarHeritageClause(node) { + var types = node.types; + if (checkGrammarForDisallowedTrailingComma(types)) { + return true; + } + if (types && types.length === 0) { + var listType = ts.tokenToString(node.token); + return grammarErrorAtPos(node, types.pos, 0, ts.Diagnostics._0_list_cannot_be_empty, listType); + } + return ts.some(types, checkGrammarExpressionWithTypeArguments); + } + function checkGrammarExpressionWithTypeArguments(node) { + return checkGrammarTypeArguments(node, node.typeArguments); + } + function checkGrammarClassDeclarationHeritageClauses(node) { + var seenExtendsClause = false; + var seenImplementsClause = false; + if (!checkGrammarDecoratorsAndModifiers(node) && node.heritageClauses) { + for (var _i = 0, _a = node.heritageClauses; _i < _a.length; _i++) { + var heritageClause = _a[_i]; + if (heritageClause.token === 86 /* ExtendsKeyword */) { + if (seenExtendsClause) { + return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.extends_clause_already_seen); + } + if (seenImplementsClause) { + return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.extends_clause_must_precede_implements_clause); + } + if (heritageClause.types.length > 1) { + return grammarErrorOnFirstToken(heritageClause.types[1], ts.Diagnostics.Classes_can_only_extend_a_single_class); + } + seenExtendsClause = true; + } + else { + ts.Debug.assert(heritageClause.token === 109 /* ImplementsKeyword */); + if (seenImplementsClause) { + return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.implements_clause_already_seen); + } + seenImplementsClause = true; + } + // Grammar checking heritageClause inside class declaration + checkGrammarHeritageClause(heritageClause); + } + } + } + function checkGrammarInterfaceDeclaration(node) { + var seenExtendsClause = false; + if (node.heritageClauses) { + for (var _i = 0, _a = node.heritageClauses; _i < _a.length; _i++) { + var heritageClause = _a[_i]; + if (heritageClause.token === 86 /* ExtendsKeyword */) { + if (seenExtendsClause) { + return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.extends_clause_already_seen); + } + seenExtendsClause = true; + } + else { + ts.Debug.assert(heritageClause.token === 109 /* ImplementsKeyword */); + return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.Interface_declaration_cannot_have_implements_clause); + } + // Grammar checking heritageClause inside class declaration + checkGrammarHeritageClause(heritageClause); + } + } + return false; + } + function checkGrammarComputedPropertyName(node) { + // If node is not a computedPropertyName, just skip the grammar checking + if (node.kind !== 149 /* ComputedPropertyName */) { + return false; + } + var computedPropertyName = node; + if (computedPropertyName.expression.kind === 204 /* BinaryExpression */ && computedPropertyName.expression.operatorToken.kind === 27 /* CommaToken */) { + return grammarErrorOnNode(computedPropertyName.expression, ts.Diagnostics.A_comma_expression_is_not_allowed_in_a_computed_property_name); + } + return false; + } + function checkGrammarForGenerator(node) { + if (node.asteriskToken) { + ts.Debug.assert(node.kind === 239 /* FunctionDeclaration */ || + node.kind === 196 /* FunctionExpression */ || + node.kind === 156 /* MethodDeclaration */); + if (node.flags & 4194304 /* Ambient */) { + return grammarErrorOnNode(node.asteriskToken, ts.Diagnostics.Generators_are_not_allowed_in_an_ambient_context); + } + if (!node.body) { + return grammarErrorOnNode(node.asteriskToken, ts.Diagnostics.An_overload_signature_cannot_be_declared_as_a_generator); + } + } + } + function checkGrammarForInvalidQuestionMark(questionToken, message) { + return !!questionToken && grammarErrorOnNode(questionToken, message); + } + function checkGrammarForInvalidExclamationToken(exclamationToken, message) { + return !!exclamationToken && grammarErrorOnNode(exclamationToken, message); + } + function checkGrammarObjectLiteralExpression(node, inDestructuring) { + var Flags; + (function (Flags) { + Flags[Flags["Property"] = 1] = "Property"; + Flags[Flags["GetAccessor"] = 2] = "GetAccessor"; + Flags[Flags["SetAccessor"] = 4] = "SetAccessor"; + Flags[Flags["GetOrSetAccessor"] = 6] = "GetOrSetAccessor"; + })(Flags || (Flags = {})); + var seen = ts.createUnderscoreEscapedMap(); + for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { + var prop = _a[_i]; + if (prop.kind === 277 /* SpreadAssignment */) { + continue; + } + var name = prop.name; + if (name.kind === 149 /* ComputedPropertyName */) { + // If the name is not a ComputedPropertyName, the grammar checking will skip it + checkGrammarComputedPropertyName(name); + } + if (prop.kind === 276 /* ShorthandPropertyAssignment */ && !inDestructuring && prop.objectAssignmentInitializer) { + // having objectAssignmentInitializer is only valid in ObjectAssignmentPattern + // outside of destructuring it is a syntax error + return grammarErrorOnNode(prop.equalsToken, ts.Diagnostics.can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment); + } + // Modifiers are never allowed on properties except for 'async' on a method declaration + if (prop.modifiers) { + for (var _b = 0, _c = prop.modifiers; _b < _c.length; _b++) { // TODO: GH#19955 + var mod = _c[_b]; + if (mod.kind !== 121 /* AsyncKeyword */ || prop.kind !== 156 /* MethodDeclaration */) { + grammarErrorOnNode(mod, ts.Diagnostics._0_modifier_cannot_be_used_here, ts.getTextOfNode(mod)); + } + } + } + // ECMA-262 11.1.5 Object Initializer + // If previous is not undefined then throw a SyntaxError exception if any of the following conditions are true + // a.This production is contained in strict code and IsDataDescriptor(previous) is true and + // IsDataDescriptor(propId.descriptor) is true. + // b.IsDataDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true. + // c.IsAccessorDescriptor(previous) is true and IsDataDescriptor(propId.descriptor) is true. + // d.IsAccessorDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true + // and either both previous and propId.descriptor have[[Get]] fields or both previous and propId.descriptor have[[Set]] fields + var currentKind = void 0; + switch (prop.kind) { + case 276 /* ShorthandPropertyAssignment */: + checkGrammarForInvalidExclamationToken(prop.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context); + /* tslint:disable:no-switch-case-fall-through */ + case 275 /* PropertyAssignment */: + // Grammar checking for computedPropertyName and shorthandPropertyAssignment + checkGrammarForInvalidQuestionMark(prop.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional); + if (name.kind === 8 /* NumericLiteral */) { + checkGrammarNumericLiteral(name); + } + // falls through + case 156 /* MethodDeclaration */: + currentKind = 1 /* Property */; + break; + case 158 /* GetAccessor */: + currentKind = 2 /* GetAccessor */; + break; + case 159 /* SetAccessor */: + currentKind = 4 /* SetAccessor */; + break; + default: + throw ts.Debug.assertNever(prop, "Unexpected syntax kind:" + prop.kind); + } + var effectiveName = ts.getPropertyNameForPropertyNameNode(name); + if (effectiveName === undefined) { + continue; + } + var existingKind = seen.get(effectiveName); + if (!existingKind) { + seen.set(effectiveName, currentKind); + } + else { + if (currentKind === 1 /* Property */ && existingKind === 1 /* Property */) { + grammarErrorOnNode(name, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(name)); + } + else if ((currentKind & 6 /* GetOrSetAccessor */) && (existingKind & 6 /* GetOrSetAccessor */)) { + if (existingKind !== 6 /* GetOrSetAccessor */ && currentKind !== existingKind) { + seen.set(effectiveName, currentKind | existingKind); + } + else { + return grammarErrorOnNode(name, ts.Diagnostics.An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name); + } + } + else { + return grammarErrorOnNode(name, ts.Diagnostics.An_object_literal_cannot_have_property_and_accessor_with_the_same_name); + } + } + } + } + function checkGrammarJsxElement(node) { + checkGrammarTypeArguments(node, node.typeArguments); + var seen = ts.createUnderscoreEscapedMap(); + for (var _i = 0, _a = node.attributes.properties; _i < _a.length; _i++) { + var attr = _a[_i]; + if (attr.kind === 269 /* JsxSpreadAttribute */) { + continue; + } + var name = attr.name, initializer = attr.initializer; + if (!seen.get(name.escapedText)) { + seen.set(name.escapedText, true); + } + else { + return grammarErrorOnNode(name, ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name); + } + if (initializer && initializer.kind === 270 /* JsxExpression */ && !initializer.expression) { + return grammarErrorOnNode(initializer, ts.Diagnostics.JSX_attributes_must_only_be_assigned_a_non_empty_expression); + } + } + } + function checkGrammarForInOrForOfStatement(forInOrOfStatement) { + if (checkGrammarStatementInAmbientContext(forInOrOfStatement)) { + return true; + } + if (forInOrOfStatement.kind === 227 /* ForOfStatement */ && forInOrOfStatement.awaitModifier) { + if ((forInOrOfStatement.flags & 16384 /* AwaitContext */) === 0 /* None */) { + return grammarErrorOnNode(forInOrOfStatement.awaitModifier, ts.Diagnostics.A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator); + } + } + if (forInOrOfStatement.initializer.kind === 238 /* VariableDeclarationList */) { + var variableList = forInOrOfStatement.initializer; + if (!checkGrammarVariableDeclarationList(variableList)) { + var declarations = variableList.declarations; + // declarations.length can be zero if there is an error in variable declaration in for-of or for-in + // See http://www.ecma-international.org/ecma-262/6.0/#sec-for-in-and-for-of-statements for details + // For example: + // var let = 10; + // for (let of [1,2,3]) {} // this is invalid ES6 syntax + // for (let in [1,2,3]) {} // this is invalid ES6 syntax + // We will then want to skip on grammar checking on variableList declaration + if (!declarations.length) { + return false; + } + if (declarations.length > 1) { + var diagnostic = forInOrOfStatement.kind === 226 /* ForInStatement */ + ? ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement + : ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement; + return grammarErrorOnFirstToken(variableList.declarations[1], diagnostic); + } + var firstDeclaration = declarations[0]; + if (firstDeclaration.initializer) { + var diagnostic = forInOrOfStatement.kind === 226 /* ForInStatement */ + ? ts.Diagnostics.The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer + : ts.Diagnostics.The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer; + return grammarErrorOnNode(firstDeclaration.name, diagnostic); + } + if (firstDeclaration.type) { + var diagnostic = forInOrOfStatement.kind === 226 /* ForInStatement */ + ? ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation + : ts.Diagnostics.The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation; + return grammarErrorOnNode(firstDeclaration, diagnostic); + } + } + } + return false; + } + function checkGrammarAccessor(accessor) { + var kind = accessor.kind; + if (languageVersion < 1 /* ES5 */) { + return grammarErrorOnNode(accessor.name, ts.Diagnostics.Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher); + } + else if (accessor.flags & 4194304 /* Ambient */) { + return grammarErrorOnNode(accessor.name, ts.Diagnostics.An_accessor_cannot_be_declared_in_an_ambient_context); + } + else if (accessor.body === undefined && !ts.hasModifier(accessor, 128 /* Abstract */)) { + return grammarErrorAtPos(accessor, accessor.end - 1, ";".length, ts.Diagnostics._0_expected, "{"); + } + else if (accessor.body && ts.hasModifier(accessor, 128 /* Abstract */)) { + return grammarErrorOnNode(accessor, ts.Diagnostics.An_abstract_accessor_cannot_have_an_implementation); + } + else if (accessor.typeParameters) { + return grammarErrorOnNode(accessor.name, ts.Diagnostics.An_accessor_cannot_have_type_parameters); + } + else if (!doesAccessorHaveCorrectParameterCount(accessor)) { + return grammarErrorOnNode(accessor.name, kind === 158 /* GetAccessor */ ? + ts.Diagnostics.A_get_accessor_cannot_have_parameters : + ts.Diagnostics.A_set_accessor_must_have_exactly_one_parameter); + } + else if (kind === 159 /* SetAccessor */) { + if (accessor.type) { + return grammarErrorOnNode(accessor.name, ts.Diagnostics.A_set_accessor_cannot_have_a_return_type_annotation); + } + else { + var parameter = accessor.parameters[0]; + if (parameter.dotDotDotToken) { + return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.A_set_accessor_cannot_have_rest_parameter); + } + else if (parameter.questionToken) { + return grammarErrorOnNode(parameter.questionToken, ts.Diagnostics.A_set_accessor_cannot_have_an_optional_parameter); + } + else if (parameter.initializer) { + return grammarErrorOnNode(accessor.name, ts.Diagnostics.A_set_accessor_parameter_cannot_have_an_initializer); + } + } + } + return false; + } + /** Does the accessor have the right number of parameters? + * A get accessor has no parameters or a single `this` parameter. + * A set accessor has one parameter or a `this` parameter and one more parameter. + */ + function doesAccessorHaveCorrectParameterCount(accessor) { + return getAccessorThisParameter(accessor) || accessor.parameters.length === (accessor.kind === 158 /* GetAccessor */ ? 0 : 1); + } + function getAccessorThisParameter(accessor) { + if (accessor.parameters.length === (accessor.kind === 158 /* GetAccessor */ ? 1 : 2)) { + return ts.getThisParameter(accessor); + } + } + function checkGrammarTypeOperatorNode(node) { + if (node.operator === 142 /* UniqueKeyword */) { + if (node.type.kind !== 139 /* SymbolKeyword */) { + return grammarErrorOnNode(node.type, ts.Diagnostics._0_expected, ts.tokenToString(139 /* SymbolKeyword */)); + } + var parent = ts.walkUpParenthesizedTypes(node.parent); + switch (parent.kind) { + case 237 /* VariableDeclaration */: + var decl = parent; + if (decl.name.kind !== 72 /* Identifier */) { + return grammarErrorOnNode(node, ts.Diagnostics.unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name); + } + if (!ts.isVariableDeclarationInVariableStatement(decl)) { + return grammarErrorOnNode(node, ts.Diagnostics.unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement); + } + if (!(decl.parent.flags & 2 /* Const */)) { + return grammarErrorOnNode(parent.name, ts.Diagnostics.A_variable_whose_type_is_a_unique_symbol_type_must_be_const); + } + break; + case 154 /* PropertyDeclaration */: + if (!ts.hasModifier(parent, 32 /* Static */) || + !ts.hasModifier(parent, 64 /* Readonly */)) { + return grammarErrorOnNode(parent.name, ts.Diagnostics.A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly); + } + break; + case 153 /* PropertySignature */: + if (!ts.hasModifier(parent, 64 /* Readonly */)) { + return grammarErrorOnNode(parent.name, ts.Diagnostics.A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly); + } + break; + default: + return grammarErrorOnNode(node, ts.Diagnostics.unique_symbol_types_are_not_allowed_here); + } + } + } + function checkGrammarForInvalidDynamicName(node, message) { + if (isNonBindableDynamicName(node)) { + return grammarErrorOnNode(node, message); + } + } + function checkGrammarMethod(node) { + if (checkGrammarFunctionLikeDeclaration(node)) { + return true; + } + if (node.kind === 156 /* MethodDeclaration */) { + if (node.parent.kind === 188 /* ObjectLiteralExpression */) { + // We only disallow modifier on a method declaration if it is a property of object-literal-expression + if (node.modifiers && !(node.modifiers.length === 1 && ts.first(node.modifiers).kind === 121 /* AsyncKeyword */)) { + return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); + } + else if (checkGrammarForInvalidQuestionMark(node.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional)) { + return true; + } + else if (checkGrammarForInvalidExclamationToken(node.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context)) { + return true; + } + else if (node.body === undefined) { + return grammarErrorAtPos(node, node.end - 1, ";".length, ts.Diagnostics._0_expected, "{"); + } + } + if (checkGrammarForGenerator(node)) { + return true; + } + } + if (ts.isClassLike(node.parent)) { + // Technically, computed properties in ambient contexts is disallowed + // for property declarations and accessors too, not just methods. + // However, property declarations disallow computed names in general, + // and accessors are not allowed in ambient contexts in general, + // so this error only really matters for methods. + if (node.flags & 4194304 /* Ambient */) { + return checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type); + } + else if (node.kind === 156 /* MethodDeclaration */ && !node.body) { + return checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type); + } + } + else if (node.parent.kind === 241 /* InterfaceDeclaration */) { + return checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type); + } + else if (node.parent.kind === 168 /* TypeLiteral */) { + return checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type); + } + } + function checkGrammarBreakOrContinueStatement(node) { + var current = node; + while (current) { + if (ts.isFunctionLike(current)) { + return grammarErrorOnNode(node, ts.Diagnostics.Jump_target_cannot_cross_function_boundary); + } + switch (current.kind) { + case 233 /* LabeledStatement */: + if (node.label && current.label.escapedText === node.label.escapedText) { + // found matching label - verify that label usage is correct + // continue can only target labels that are on iteration statements + var isMisplacedContinueLabel = node.kind === 228 /* ContinueStatement */ + && !ts.isIterationStatement(current.statement, /*lookInLabeledStatement*/ true); + if (isMisplacedContinueLabel) { + return grammarErrorOnNode(node, ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement); + } + return false; + } + break; + case 232 /* SwitchStatement */: + if (node.kind === 229 /* BreakStatement */ && !node.label) { + // unlabeled break within switch statement - ok + return false; + } + break; + default: + if (ts.isIterationStatement(current, /*lookInLabeledStatement*/ false) && !node.label) { + // unlabeled break or continue within iteration statement - ok + return false; + } + break; + } + current = current.parent; + } + if (node.label) { + var message = node.kind === 229 /* BreakStatement */ + ? ts.Diagnostics.A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement + : ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement; + return grammarErrorOnNode(node, message); + } + else { + var message = node.kind === 229 /* BreakStatement */ + ? ts.Diagnostics.A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement + : ts.Diagnostics.A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement; + return grammarErrorOnNode(node, message); + } + } + function checkGrammarBindingElement(node) { + if (node.dotDotDotToken) { + var elements = node.parent.elements; + if (node !== ts.last(elements)) { + return grammarErrorOnNode(node, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern); + } + checkGrammarForDisallowedTrailingComma(elements, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma); + if (node.propertyName) { + return grammarErrorOnNode(node.name, ts.Diagnostics.A_rest_element_cannot_have_a_property_name); + } + if (node.initializer) { + // Error on equals token which immediately precedes the initializer + return grammarErrorAtPos(node, node.initializer.pos - 1, 1, ts.Diagnostics.A_rest_element_cannot_have_an_initializer); + } + } + } + function isStringOrNumberLiteralExpression(expr) { + return expr.kind === 10 /* StringLiteral */ || expr.kind === 8 /* NumericLiteral */ || + expr.kind === 202 /* PrefixUnaryExpression */ && expr.operator === 39 /* MinusToken */ && + expr.operand.kind === 8 /* NumericLiteral */; + } + function isBigIntLiteralExpression(expr) { + return expr.kind === 9 /* BigIntLiteral */ || + expr.kind === 202 /* PrefixUnaryExpression */ && expr.operator === 39 /* MinusToken */ && + expr.operand.kind === 9 /* BigIntLiteral */; + } + function isSimpleLiteralEnumReference(expr) { + if ((ts.isPropertyAccessExpression(expr) || (ts.isElementAccessExpression(expr) && isStringOrNumberLiteralExpression(expr.argumentExpression))) && + ts.isEntityNameExpression(expr.expression)) + return !!(checkExpressionCached(expr).flags & 1024 /* EnumLiteral */); + } + function checkAmbientInitializer(node) { + var initializer = node.initializer; + if (initializer) { + var isInvalidInitializer = !(isStringOrNumberLiteralExpression(initializer) || + isSimpleLiteralEnumReference(initializer) || + initializer.kind === 102 /* TrueKeyword */ || initializer.kind === 87 /* FalseKeyword */ || + isBigIntLiteralExpression(initializer)); + var isConstOrReadonly = ts.isDeclarationReadonly(node) || ts.isVariableDeclaration(node) && ts.isVarConst(node); + if (isConstOrReadonly && !node.type) { + if (isInvalidInitializer) { + return grammarErrorOnNode(initializer, ts.Diagnostics.A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_reference); + } + } + else { + return grammarErrorOnNode(initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); + } + if (!isConstOrReadonly || isInvalidInitializer) { + return grammarErrorOnNode(initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); + } + } + } + function checkGrammarVariableDeclaration(node) { + if (node.parent.parent.kind !== 226 /* ForInStatement */ && node.parent.parent.kind !== 227 /* ForOfStatement */) { + if (node.flags & 4194304 /* Ambient */) { + checkAmbientInitializer(node); + } + else if (!node.initializer) { + if (ts.isBindingPattern(node.name) && !ts.isBindingPattern(node.parent)) { + return grammarErrorOnNode(node, ts.Diagnostics.A_destructuring_declaration_must_have_an_initializer); + } + if (ts.isVarConst(node)) { + return grammarErrorOnNode(node, ts.Diagnostics.const_declarations_must_be_initialized); + } + } + } + if (node.exclamationToken && (node.parent.parent.kind !== 219 /* VariableStatement */ || !node.type || node.initializer || node.flags & 4194304 /* Ambient */)) { + return grammarErrorOnNode(node.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context); + } + if (compilerOptions.module !== ts.ModuleKind.ES2015 && compilerOptions.module !== ts.ModuleKind.ESNext && compilerOptions.module !== ts.ModuleKind.System && !compilerOptions.noEmit && + !(node.parent.parent.flags & 4194304 /* Ambient */) && ts.hasModifier(node.parent.parent, 1 /* Export */)) { + checkESModuleMarker(node.name); + } + var checkLetConstNames = (ts.isLet(node) || ts.isVarConst(node)); + // 1. LexicalDeclaration : LetOrConst BindingList ; + // It is a Syntax Error if the BoundNames of BindingList contains "let". + // 2. ForDeclaration: ForDeclaration : LetOrConst ForBinding + // It is a Syntax Error if the BoundNames of ForDeclaration contains "let". + // It is a SyntaxError if a VariableDeclaration or VariableDeclarationNoIn occurs within strict code + // and its Identifier is eval or arguments + return checkLetConstNames && checkGrammarNameInLetOrConstDeclarations(node.name); + } + function checkESModuleMarker(name) { + if (name.kind === 72 /* Identifier */) { + if (ts.idText(name) === "__esModule") { + return grammarErrorOnNode(name, ts.Diagnostics.Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules); + } + } + else { + var elements = name.elements; + for (var _i = 0, elements_1 = elements; _i < elements_1.length; _i++) { + var element = elements_1[_i]; + if (!ts.isOmittedExpression(element)) { + return checkESModuleMarker(element.name); + } + } + } + return false; + } + function checkGrammarNameInLetOrConstDeclarations(name) { + if (name.kind === 72 /* Identifier */) { + if (name.originalKeywordKind === 111 /* LetKeyword */) { + return grammarErrorOnNode(name, ts.Diagnostics.let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations); + } + } + else { + var elements = name.elements; + for (var _i = 0, elements_2 = elements; _i < elements_2.length; _i++) { + var element = elements_2[_i]; + if (!ts.isOmittedExpression(element)) { + checkGrammarNameInLetOrConstDeclarations(element.name); + } + } + } + return false; + } + function checkGrammarVariableDeclarationList(declarationList) { + var declarations = declarationList.declarations; + if (checkGrammarForDisallowedTrailingComma(declarationList.declarations)) { + return true; + } + if (!declarationList.declarations.length) { + return grammarErrorAtPos(declarationList, declarations.pos, declarations.end - declarations.pos, ts.Diagnostics.Variable_declaration_list_cannot_be_empty); + } + return false; + } + function allowLetAndConstDeclarations(parent) { + switch (parent.kind) { + case 222 /* IfStatement */: + case 223 /* DoStatement */: + case 224 /* WhileStatement */: + case 231 /* WithStatement */: + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + return false; + case 233 /* LabeledStatement */: + return allowLetAndConstDeclarations(parent.parent); + } + return true; + } + function checkGrammarForDisallowedLetOrConstStatement(node) { + if (!allowLetAndConstDeclarations(node.parent)) { + if (ts.isLet(node.declarationList)) { + return grammarErrorOnNode(node, ts.Diagnostics.let_declarations_can_only_be_declared_inside_a_block); + } + else if (ts.isVarConst(node.declarationList)) { + return grammarErrorOnNode(node, ts.Diagnostics.const_declarations_can_only_be_declared_inside_a_block); + } + } + } + function checkGrammarMetaProperty(node) { + var escapedText = node.name.escapedText; + switch (node.keywordToken) { + case 95 /* NewKeyword */: + if (escapedText !== "target") { + return grammarErrorOnNode(node.name, ts.Diagnostics._0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2, node.name.escapedText, ts.tokenToString(node.keywordToken), "target"); + } + break; + case 92 /* ImportKeyword */: + if (escapedText !== "meta") { + return grammarErrorOnNode(node.name, ts.Diagnostics._0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2, node.name.escapedText, ts.tokenToString(node.keywordToken), "meta"); + } + break; + } + } + function hasParseDiagnostics(sourceFile) { + return sourceFile.parseDiagnostics.length > 0; + } + function grammarErrorOnFirstToken(node, message, arg0, arg1, arg2) { + var sourceFile = ts.getSourceFileOfNode(node); + if (!hasParseDiagnostics(sourceFile)) { + var span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos); + diagnostics.add(ts.createFileDiagnostic(sourceFile, span.start, span.length, message, arg0, arg1, arg2)); + return true; + } + return false; + } + function grammarErrorAtPos(nodeForSourceFile, start, length, message, arg0, arg1, arg2) { + var sourceFile = ts.getSourceFileOfNode(nodeForSourceFile); + if (!hasParseDiagnostics(sourceFile)) { + diagnostics.add(ts.createFileDiagnostic(sourceFile, start, length, message, arg0, arg1, arg2)); + return true; + } + return false; + } + function grammarErrorOnNode(node, message, arg0, arg1, arg2) { + var sourceFile = ts.getSourceFileOfNode(node); + if (!hasParseDiagnostics(sourceFile)) { + diagnostics.add(ts.createDiagnosticForNode(node, message, arg0, arg1, arg2)); + return true; + } + return false; + } + function checkGrammarConstructorTypeParameters(node) { + var jsdocTypeParameters = ts.isInJSFile(node) ? ts.getJSDocTypeParameterDeclarations(node) : undefined; + var range = node.typeParameters || jsdocTypeParameters && ts.firstOrUndefined(jsdocTypeParameters); + if (range) { + var pos = range.pos === range.end ? range.pos : ts.skipTrivia(ts.getSourceFileOfNode(node).text, range.pos); + return grammarErrorAtPos(node, pos, range.end - pos, ts.Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration); + } + } + function checkGrammarConstructorTypeAnnotation(node) { + var type = ts.getEffectiveReturnTypeNode(node); + if (type) { + return grammarErrorOnNode(type, ts.Diagnostics.Type_annotation_cannot_appear_on_a_constructor_declaration); + } + } + function checkGrammarProperty(node) { + if (ts.isClassLike(node.parent)) { + if (checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_class_property_declaration_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type)) { + return true; + } + } + else if (node.parent.kind === 241 /* InterfaceDeclaration */) { + if (checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type)) { + return true; + } + if (node.initializer) { + return grammarErrorOnNode(node.initializer, ts.Diagnostics.An_interface_property_cannot_have_an_initializer); + } + } + else if (node.parent.kind === 168 /* TypeLiteral */) { + if (checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type)) { + return true; + } + if (node.initializer) { + return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_type_literal_property_cannot_have_an_initializer); + } + } + if (node.flags & 4194304 /* Ambient */) { + checkAmbientInitializer(node); + } + if (ts.isPropertyDeclaration(node) && node.exclamationToken && (!ts.isClassLike(node.parent) || !node.type || node.initializer || + node.flags & 4194304 /* Ambient */ || ts.hasModifier(node, 32 /* Static */ | 128 /* Abstract */))) { + return grammarErrorOnNode(node.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context); + } + } + function checkGrammarTopLevelElementForRequiredDeclareModifier(node) { + // A declare modifier is required for any top level .d.ts declaration except export=, export default, export as namespace + // interfaces and imports categories: + // + // DeclarationElement: + // ExportAssignment + // export_opt InterfaceDeclaration + // export_opt TypeAliasDeclaration + // export_opt ImportDeclaration + // export_opt ExternalImportDeclaration + // export_opt AmbientDeclaration + // + // TODO: The spec needs to be amended to reflect this grammar. + if (node.kind === 241 /* InterfaceDeclaration */ || + node.kind === 242 /* TypeAliasDeclaration */ || + node.kind === 249 /* ImportDeclaration */ || + node.kind === 248 /* ImportEqualsDeclaration */ || + node.kind === 255 /* ExportDeclaration */ || + node.kind === 254 /* ExportAssignment */ || + node.kind === 247 /* NamespaceExportDeclaration */ || + ts.hasModifier(node, 2 /* Ambient */ | 1 /* Export */ | 512 /* Default */)) { + return false; + } + return grammarErrorOnFirstToken(node, ts.Diagnostics.A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file); + } + function checkGrammarTopLevelElementsForRequiredDeclareModifier(file) { + for (var _i = 0, _a = file.statements; _i < _a.length; _i++) { + var decl = _a[_i]; + if (ts.isDeclaration(decl) || decl.kind === 219 /* VariableStatement */) { + if (checkGrammarTopLevelElementForRequiredDeclareModifier(decl)) { + return true; + } + } + } + return false; + } + function checkGrammarSourceFile(node) { + return !!(node.flags & 4194304 /* Ambient */) && checkGrammarTopLevelElementsForRequiredDeclareModifier(node); + } + function checkGrammarStatementInAmbientContext(node) { + if (node.flags & 4194304 /* Ambient */) { + // An accessors is already reported about the ambient context + if (ts.isAccessor(node.parent)) { + return getNodeLinks(node).hasReportedStatementInAmbientContext = true; + } + // Find containing block which is either Block, ModuleBlock, SourceFile + var links = getNodeLinks(node); + if (!links.hasReportedStatementInAmbientContext && ts.isFunctionLike(node.parent)) { + return getNodeLinks(node).hasReportedStatementInAmbientContext = grammarErrorOnFirstToken(node, ts.Diagnostics.An_implementation_cannot_be_declared_in_ambient_contexts); + } + // We are either parented by another statement, or some sort of block. + // If we're in a block, we only want to really report an error once + // to prevent noisiness. So use a bit on the block to indicate if + // this has already been reported, and don't report if it has. + // + if (node.parent.kind === 218 /* Block */ || node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 279 /* SourceFile */) { + var links_2 = getNodeLinks(node.parent); + // Check if the containing block ever report this error + if (!links_2.hasReportedStatementInAmbientContext) { + return links_2.hasReportedStatementInAmbientContext = grammarErrorOnFirstToken(node, ts.Diagnostics.Statements_are_not_allowed_in_ambient_contexts); + } + } + else { + // We must be parented by a statement. If so, there's no need + // to report the error as our parent will have already done it. + // Debug.assert(isStatement(node.parent)); + } + } + return false; + } + function checkGrammarNumericLiteral(node) { + // Grammar checking + if (node.numericLiteralFlags & 32 /* Octal */) { + var diagnosticMessage = void 0; + if (languageVersion >= 1 /* ES5 */) { + diagnosticMessage = ts.Diagnostics.Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0; + } + else if (ts.isChildOfNodeWithKind(node, 182 /* LiteralType */)) { + diagnosticMessage = ts.Diagnostics.Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0; + } + else if (ts.isChildOfNodeWithKind(node, 278 /* EnumMember */)) { + diagnosticMessage = ts.Diagnostics.Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0; + } + if (diagnosticMessage) { + var withMinus = ts.isPrefixUnaryExpression(node.parent) && node.parent.operator === 39 /* MinusToken */; + var literal = (withMinus ? "-" : "") + "0o" + node.text; + return grammarErrorOnNode(withMinus ? node.parent : node, diagnosticMessage, literal); + } + } + return false; + } + function checkGrammarBigIntLiteral(node) { + var literalType = ts.isLiteralTypeNode(node.parent) || + ts.isPrefixUnaryExpression(node.parent) && ts.isLiteralTypeNode(node.parent.parent); + if (!literalType) { + if (languageVersion < 6 /* ESNext */) { + if (grammarErrorOnNode(node, ts.Diagnostics.BigInt_literals_are_not_available_when_targeting_lower_than_ESNext)) { + return true; + } + } + } + return false; + } + function grammarErrorAfterFirstToken(node, message, arg0, arg1, arg2) { + var sourceFile = ts.getSourceFileOfNode(node); + if (!hasParseDiagnostics(sourceFile)) { + var span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos); + diagnostics.add(ts.createFileDiagnostic(sourceFile, ts.textSpanEnd(span), /*length*/ 0, message, arg0, arg1, arg2)); + return true; + } + return false; + } + function getAmbientModules() { + if (!ambientModulesCache) { + ambientModulesCache = []; + globals.forEach(function (global, sym) { + // No need to `unescapeLeadingUnderscores`, an escaped symbol is never an ambient module. + if (ambientModuleSymbolRegex.test(sym)) { + ambientModulesCache.push(global); + } + }); + } + return ambientModulesCache; + } + function checkGrammarImportCallExpression(node) { + if (moduleKind === ts.ModuleKind.ES2015) { + return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext); + } + if (node.typeArguments) { + return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_import_cannot_have_type_arguments); + } + var nodeArguments = node.arguments; + if (nodeArguments.length !== 1) { + return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_import_must_have_one_specifier_as_an_argument); + } + // see: parseArgumentOrArrayLiteralElement...we use this function which parse arguments of callExpression to parse specifier for dynamic import. + // parseArgumentOrArrayLiteralElement allows spread element to be in an argument list which is not allowed as specifier in dynamic import. + if (ts.isSpreadElement(nodeArguments[0])) { + return grammarErrorOnNode(nodeArguments[0], ts.Diagnostics.Specifier_of_dynamic_import_cannot_be_spread_element); + } + return false; + } + } + ts.createTypeChecker = createTypeChecker; + /** Like 'isDeclarationName', but returns true for LHS of `import { x as y }` or `export { x as y }`. */ + function isDeclarationNameOrImportPropertyName(name) { + switch (name.parent.kind) { + case 253 /* ImportSpecifier */: + case 257 /* ExportSpecifier */: + return ts.isIdentifier(name); + default: + return ts.isDeclarationName(name); + } + } + function isSomeImportDeclaration(decl) { + switch (decl.kind) { + case 250 /* ImportClause */: // For default import + case 248 /* ImportEqualsDeclaration */: + case 251 /* NamespaceImport */: + case 253 /* ImportSpecifier */: // For rename import `x as y` + return true; + case 72 /* Identifier */: + // For regular import, `decl` is an Identifier under the ImportSpecifier. + return decl.parent.kind === 253 /* ImportSpecifier */; + default: + return false; + } + } + var JsxNames; + (function (JsxNames) { + // tslint:disable variable-name + JsxNames.JSX = "JSX"; + JsxNames.IntrinsicElements = "IntrinsicElements"; + JsxNames.ElementClass = "ElementClass"; + JsxNames.ElementAttributesPropertyNameContainer = "ElementAttributesProperty"; // TODO: Deprecate and remove support + JsxNames.ElementChildrenAttributeNameContainer = "ElementChildrenAttribute"; + JsxNames.Element = "Element"; + JsxNames.IntrinsicAttributes = "IntrinsicAttributes"; + JsxNames.IntrinsicClassAttributes = "IntrinsicClassAttributes"; + JsxNames.LibraryManagedAttributes = "LibraryManagedAttributes"; + // tslint:enable variable-name + })(JsxNames || (JsxNames = {})); + function typeIsLiteralType(type) { + return !!(type.flags & 2944 /* Literal */); + } +})(ts || (ts = {})); +var ts; +(function (ts) { + function createSynthesizedNode(kind) { + var node = ts.createNode(kind, -1, -1); + node.flags |= 8 /* Synthesized */; + return node; + } + /* @internal */ + function updateNode(updated, original) { + if (updated !== original) { + setOriginalNode(updated, original); + setTextRange(updated, original); + ts.aggregateTransformFlags(updated); + } + return updated; + } + ts.updateNode = updateNode; + /** + * Make `elements` into a `NodeArray`. If `elements` is `undefined`, returns an empty `NodeArray`. + */ + function createNodeArray(elements, hasTrailingComma) { + if (!elements || elements === ts.emptyArray) { + elements = []; + } + else if (ts.isNodeArray(elements)) { + return elements; + } + var array = elements; + array.pos = -1; + array.end = -1; + array.hasTrailingComma = hasTrailingComma; + return array; + } + ts.createNodeArray = createNodeArray; + /** + * Creates a shallow, memberwise clone of a node with no source map location. + */ + /* @internal */ + function getSynthesizedClone(node) { + // We don't use "clone" from core.ts here, as we need to preserve the prototype chain of + // the original node. We also need to exclude specific properties and only include own- + // properties (to skip members already defined on the shared prototype). + if (node === undefined) { + return node; + } + var clone = createSynthesizedNode(node.kind); + clone.flags |= node.flags; + setOriginalNode(clone, node); + for (var key in node) { + if (clone.hasOwnProperty(key) || !node.hasOwnProperty(key)) { + continue; + } + clone[key] = node[key]; + } + return clone; + } + ts.getSynthesizedClone = getSynthesizedClone; + function createLiteral(value, isSingleQuote) { + if (typeof value === "number") { + return createNumericLiteral(value + ""); + } + if (typeof value === "object" && "base10Value" in value) { // PseudoBigInt + return createBigIntLiteral(ts.pseudoBigIntToString(value) + "n"); + } + if (typeof value === "boolean") { + return value ? createTrue() : createFalse(); + } + if (ts.isString(value)) { + var res = createStringLiteral(value); + if (isSingleQuote) + res.singleQuote = true; + return res; + } + return createLiteralFromNode(value); + } + ts.createLiteral = createLiteral; + function createNumericLiteral(value) { + var node = createSynthesizedNode(8 /* NumericLiteral */); + node.text = value; + node.numericLiteralFlags = 0; + return node; + } + ts.createNumericLiteral = createNumericLiteral; + function createBigIntLiteral(value) { + var node = createSynthesizedNode(9 /* BigIntLiteral */); + node.text = value; + return node; + } + ts.createBigIntLiteral = createBigIntLiteral; + function createStringLiteral(text) { + var node = createSynthesizedNode(10 /* StringLiteral */); + node.text = text; + return node; + } + ts.createStringLiteral = createStringLiteral; + function createRegularExpressionLiteral(text) { + var node = createSynthesizedNode(13 /* RegularExpressionLiteral */); + node.text = text; + return node; + } + ts.createRegularExpressionLiteral = createRegularExpressionLiteral; + function createLiteralFromNode(sourceNode) { + var node = createStringLiteral(ts.getTextOfIdentifierOrLiteral(sourceNode)); + node.textSourceNode = sourceNode; + return node; + } + function createIdentifier(text, typeArguments) { + var node = createSynthesizedNode(72 /* Identifier */); + node.escapedText = ts.escapeLeadingUnderscores(text); + node.originalKeywordKind = text ? ts.stringToToken(text) : 0 /* Unknown */; + node.autoGenerateFlags = 0 /* None */; + node.autoGenerateId = 0; + if (typeArguments) { + node.typeArguments = createNodeArray(typeArguments); + } + return node; + } + ts.createIdentifier = createIdentifier; + function updateIdentifier(node, typeArguments) { + return node.typeArguments !== typeArguments + ? updateNode(createIdentifier(ts.idText(node), typeArguments), node) + : node; + } + ts.updateIdentifier = updateIdentifier; + var nextAutoGenerateId = 0; + function createTempVariable(recordTempVariable, reservedInNestedScopes) { + var name = createIdentifier(""); + name.autoGenerateFlags = 1 /* Auto */; + name.autoGenerateId = nextAutoGenerateId; + nextAutoGenerateId++; + if (recordTempVariable) { + recordTempVariable(name); + } + if (reservedInNestedScopes) { + name.autoGenerateFlags |= 8 /* ReservedInNestedScopes */; + } + return name; + } + ts.createTempVariable = createTempVariable; + /** Create a unique temporary variable for use in a loop. */ + function createLoopVariable() { + var name = createIdentifier(""); + name.autoGenerateFlags = 2 /* Loop */; + name.autoGenerateId = nextAutoGenerateId; + nextAutoGenerateId++; + return name; + } + ts.createLoopVariable = createLoopVariable; + /** Create a unique name based on the supplied text. */ + function createUniqueName(text) { + var name = createIdentifier(text); + name.autoGenerateFlags = 3 /* Unique */; + name.autoGenerateId = nextAutoGenerateId; + nextAutoGenerateId++; + return name; + } + ts.createUniqueName = createUniqueName; + function createOptimisticUniqueName(text) { + var name = createIdentifier(text); + name.autoGenerateFlags = 3 /* Unique */ | 16 /* Optimistic */; + name.autoGenerateId = nextAutoGenerateId; + nextAutoGenerateId++; + return name; + } + ts.createOptimisticUniqueName = createOptimisticUniqueName; + /** Create a unique name based on the supplied text. This does not consider names injected by the transformer. */ + function createFileLevelUniqueName(text) { + var name = createOptimisticUniqueName(text); + name.autoGenerateFlags |= 32 /* FileLevel */; + return name; + } + ts.createFileLevelUniqueName = createFileLevelUniqueName; + function getGeneratedNameForNode(node, flags) { + var name = createIdentifier(node && ts.isIdentifier(node) ? ts.idText(node) : ""); + name.autoGenerateFlags = 4 /* Node */ | flags; + name.autoGenerateId = nextAutoGenerateId; + name.original = node; + nextAutoGenerateId++; + return name; + } + ts.getGeneratedNameForNode = getGeneratedNameForNode; + // Punctuation + function createToken(token) { + return createSynthesizedNode(token); + } + ts.createToken = createToken; + // Reserved words + function createSuper() { + return createSynthesizedNode(98 /* SuperKeyword */); + } + ts.createSuper = createSuper; + function createThis() { + return createSynthesizedNode(100 /* ThisKeyword */); + } + ts.createThis = createThis; + function createNull() { + return createSynthesizedNode(96 /* NullKeyword */); + } + ts.createNull = createNull; + function createTrue() { + return createSynthesizedNode(102 /* TrueKeyword */); + } + ts.createTrue = createTrue; + function createFalse() { + return createSynthesizedNode(87 /* FalseKeyword */); + } + ts.createFalse = createFalse; + // Modifiers + function createModifier(kind) { + return createToken(kind); + } + ts.createModifier = createModifier; + function createModifiersFromModifierFlags(flags) { + var result = []; + if (flags & 1 /* Export */) { + result.push(createModifier(85 /* ExportKeyword */)); + } + if (flags & 2 /* Ambient */) { + result.push(createModifier(125 /* DeclareKeyword */)); + } + if (flags & 512 /* Default */) { + result.push(createModifier(80 /* DefaultKeyword */)); + } + if (flags & 2048 /* Const */) { + result.push(createModifier(77 /* ConstKeyword */)); + } + if (flags & 4 /* Public */) { + result.push(createModifier(115 /* PublicKeyword */)); + } + if (flags & 8 /* Private */) { + result.push(createModifier(113 /* PrivateKeyword */)); + } + if (flags & 16 /* Protected */) { + result.push(createModifier(114 /* ProtectedKeyword */)); + } + if (flags & 128 /* Abstract */) { + result.push(createModifier(118 /* AbstractKeyword */)); + } + if (flags & 32 /* Static */) { + result.push(createModifier(116 /* StaticKeyword */)); + } + if (flags & 64 /* Readonly */) { + result.push(createModifier(133 /* ReadonlyKeyword */)); + } + if (flags & 256 /* Async */) { + result.push(createModifier(121 /* AsyncKeyword */)); + } + return result; + } + ts.createModifiersFromModifierFlags = createModifiersFromModifierFlags; + // Names + function createQualifiedName(left, right) { + var node = createSynthesizedNode(148 /* QualifiedName */); + node.left = left; + node.right = asName(right); + return node; + } + ts.createQualifiedName = createQualifiedName; + function updateQualifiedName(node, left, right) { + return node.left !== left + || node.right !== right + ? updateNode(createQualifiedName(left, right), node) + : node; + } + ts.updateQualifiedName = updateQualifiedName; + function parenthesizeForComputedName(expression) { + return ts.isCommaSequence(expression) + ? createParen(expression) + : expression; + } + function createComputedPropertyName(expression) { + var node = createSynthesizedNode(149 /* ComputedPropertyName */); + node.expression = parenthesizeForComputedName(expression); + return node; + } + ts.createComputedPropertyName = createComputedPropertyName; + function updateComputedPropertyName(node, expression) { + return node.expression !== expression + ? updateNode(createComputedPropertyName(expression), node) + : node; + } + ts.updateComputedPropertyName = updateComputedPropertyName; + // Signature elements + function createTypeParameterDeclaration(name, constraint, defaultType) { + var node = createSynthesizedNode(150 /* TypeParameter */); + node.name = asName(name); + node.constraint = constraint; + node.default = defaultType; + return node; + } + ts.createTypeParameterDeclaration = createTypeParameterDeclaration; + function updateTypeParameterDeclaration(node, name, constraint, defaultType) { + return node.name !== name + || node.constraint !== constraint + || node.default !== defaultType + ? updateNode(createTypeParameterDeclaration(name, constraint, defaultType), node) + : node; + } + ts.updateTypeParameterDeclaration = updateTypeParameterDeclaration; + function createParameter(decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer) { + var node = createSynthesizedNode(151 /* Parameter */); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.dotDotDotToken = dotDotDotToken; + node.name = asName(name); + node.questionToken = questionToken; + node.type = type; + node.initializer = initializer ? ts.parenthesizeExpressionForList(initializer) : undefined; + return node; + } + ts.createParameter = createParameter; + function updateParameter(node, decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.dotDotDotToken !== dotDotDotToken + || node.name !== name + || node.questionToken !== questionToken + || node.type !== type + || node.initializer !== initializer + ? updateNode(createParameter(decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer), node) + : node; + } + ts.updateParameter = updateParameter; + function createDecorator(expression) { + var node = createSynthesizedNode(152 /* Decorator */); + node.expression = ts.parenthesizeForAccess(expression); + return node; + } + ts.createDecorator = createDecorator; + function updateDecorator(node, expression) { + return node.expression !== expression + ? updateNode(createDecorator(expression), node) + : node; + } + ts.updateDecorator = updateDecorator; + // Type Elements + function createPropertySignature(modifiers, name, questionToken, type, initializer) { + var node = createSynthesizedNode(153 /* PropertySignature */); + node.modifiers = asNodeArray(modifiers); + node.name = asName(name); + node.questionToken = questionToken; + node.type = type; + node.initializer = initializer; + return node; + } + ts.createPropertySignature = createPropertySignature; + function updatePropertySignature(node, modifiers, name, questionToken, type, initializer) { + return node.modifiers !== modifiers + || node.name !== name + || node.questionToken !== questionToken + || node.type !== type + || node.initializer !== initializer + ? updateNode(createPropertySignature(modifiers, name, questionToken, type, initializer), node) + : node; + } + ts.updatePropertySignature = updatePropertySignature; + function createProperty(decorators, modifiers, name, questionOrExclamationToken, type, initializer) { + var node = createSynthesizedNode(154 /* PropertyDeclaration */); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.name = asName(name); + node.questionToken = questionOrExclamationToken !== undefined && questionOrExclamationToken.kind === 56 /* QuestionToken */ ? questionOrExclamationToken : undefined; + node.exclamationToken = questionOrExclamationToken !== undefined && questionOrExclamationToken.kind === 52 /* ExclamationToken */ ? questionOrExclamationToken : undefined; + node.type = type; + node.initializer = initializer; + return node; + } + ts.createProperty = createProperty; + function updateProperty(node, decorators, modifiers, name, questionOrExclamationToken, type, initializer) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.name !== name + || node.questionToken !== (questionOrExclamationToken !== undefined && questionOrExclamationToken.kind === 56 /* QuestionToken */ ? questionOrExclamationToken : undefined) + || node.exclamationToken !== (questionOrExclamationToken !== undefined && questionOrExclamationToken.kind === 52 /* ExclamationToken */ ? questionOrExclamationToken : undefined) + || node.type !== type + || node.initializer !== initializer + ? updateNode(createProperty(decorators, modifiers, name, questionOrExclamationToken, type, initializer), node) + : node; + } + ts.updateProperty = updateProperty; + function createMethodSignature(typeParameters, parameters, type, name, questionToken) { + var node = createSignatureDeclaration(155 /* MethodSignature */, typeParameters, parameters, type); + node.name = asName(name); + node.questionToken = questionToken; + return node; + } + ts.createMethodSignature = createMethodSignature; + function updateMethodSignature(node, typeParameters, parameters, type, name, questionToken) { + return node.typeParameters !== typeParameters + || node.parameters !== parameters + || node.type !== type + || node.name !== name + || node.questionToken !== questionToken + ? updateNode(createMethodSignature(typeParameters, parameters, type, name, questionToken), node) + : node; + } + ts.updateMethodSignature = updateMethodSignature; + function createMethod(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { + var node = createSynthesizedNode(156 /* MethodDeclaration */); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.asteriskToken = asteriskToken; + node.name = asName(name); + node.questionToken = questionToken; + node.typeParameters = asNodeArray(typeParameters); + node.parameters = createNodeArray(parameters); + node.type = type; + node.body = body; + return node; + } + ts.createMethod = createMethod; + function updateMethod(node, decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.asteriskToken !== asteriskToken + || node.name !== name + || node.questionToken !== questionToken + || node.typeParameters !== typeParameters + || node.parameters !== parameters + || node.type !== type + || node.body !== body + ? updateNode(createMethod(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body), node) + : node; + } + ts.updateMethod = updateMethod; + function createConstructor(decorators, modifiers, parameters, body) { + var node = createSynthesizedNode(157 /* Constructor */); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.typeParameters = undefined; + node.parameters = createNodeArray(parameters); + node.type = undefined; + node.body = body; + return node; + } + ts.createConstructor = createConstructor; + function updateConstructor(node, decorators, modifiers, parameters, body) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.parameters !== parameters + || node.body !== body + ? updateNode(createConstructor(decorators, modifiers, parameters, body), node) + : node; + } + ts.updateConstructor = updateConstructor; + function createGetAccessor(decorators, modifiers, name, parameters, type, body) { + var node = createSynthesizedNode(158 /* GetAccessor */); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.name = asName(name); + node.typeParameters = undefined; + node.parameters = createNodeArray(parameters); + node.type = type; + node.body = body; + return node; + } + ts.createGetAccessor = createGetAccessor; + function updateGetAccessor(node, decorators, modifiers, name, parameters, type, body) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.name !== name + || node.parameters !== parameters + || node.type !== type + || node.body !== body + ? updateNode(createGetAccessor(decorators, modifiers, name, parameters, type, body), node) + : node; + } + ts.updateGetAccessor = updateGetAccessor; + function createSetAccessor(decorators, modifiers, name, parameters, body) { + var node = createSynthesizedNode(159 /* SetAccessor */); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.name = asName(name); + node.typeParameters = undefined; + node.parameters = createNodeArray(parameters); + node.body = body; + return node; + } + ts.createSetAccessor = createSetAccessor; + function updateSetAccessor(node, decorators, modifiers, name, parameters, body) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.name !== name + || node.parameters !== parameters + || node.body !== body + ? updateNode(createSetAccessor(decorators, modifiers, name, parameters, body), node) + : node; + } + ts.updateSetAccessor = updateSetAccessor; + function createCallSignature(typeParameters, parameters, type) { + return createSignatureDeclaration(160 /* CallSignature */, typeParameters, parameters, type); + } + ts.createCallSignature = createCallSignature; + function updateCallSignature(node, typeParameters, parameters, type) { + return updateSignatureDeclaration(node, typeParameters, parameters, type); + } + ts.updateCallSignature = updateCallSignature; + function createConstructSignature(typeParameters, parameters, type) { + return createSignatureDeclaration(161 /* ConstructSignature */, typeParameters, parameters, type); + } + ts.createConstructSignature = createConstructSignature; + function updateConstructSignature(node, typeParameters, parameters, type) { + return updateSignatureDeclaration(node, typeParameters, parameters, type); + } + ts.updateConstructSignature = updateConstructSignature; + function createIndexSignature(decorators, modifiers, parameters, type) { + var node = createSynthesizedNode(162 /* IndexSignature */); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.parameters = createNodeArray(parameters); + node.type = type; + return node; + } + ts.createIndexSignature = createIndexSignature; + function updateIndexSignature(node, decorators, modifiers, parameters, type) { + return node.parameters !== parameters + || node.type !== type + || node.decorators !== decorators + || node.modifiers !== modifiers + ? updateNode(createIndexSignature(decorators, modifiers, parameters, type), node) + : node; + } + ts.updateIndexSignature = updateIndexSignature; + /* @internal */ + function createSignatureDeclaration(kind, typeParameters, parameters, type, typeArguments) { + var node = createSynthesizedNode(kind); + node.typeParameters = asNodeArray(typeParameters); + node.parameters = asNodeArray(parameters); + node.type = type; + node.typeArguments = asNodeArray(typeArguments); + return node; + } + ts.createSignatureDeclaration = createSignatureDeclaration; + function updateSignatureDeclaration(node, typeParameters, parameters, type) { + return node.typeParameters !== typeParameters + || node.parameters !== parameters + || node.type !== type + ? updateNode(createSignatureDeclaration(node.kind, typeParameters, parameters, type), node) + : node; + } + // Types + function createKeywordTypeNode(kind) { + return createSynthesizedNode(kind); + } + ts.createKeywordTypeNode = createKeywordTypeNode; + function createTypePredicateNode(parameterName, type) { + var node = createSynthesizedNode(163 /* TypePredicate */); + node.parameterName = asName(parameterName); + node.type = type; + return node; + } + ts.createTypePredicateNode = createTypePredicateNode; + function updateTypePredicateNode(node, parameterName, type) { + return node.parameterName !== parameterName + || node.type !== type + ? updateNode(createTypePredicateNode(parameterName, type), node) + : node; + } + ts.updateTypePredicateNode = updateTypePredicateNode; + function createTypeReferenceNode(typeName, typeArguments) { + var node = createSynthesizedNode(164 /* TypeReference */); + node.typeName = asName(typeName); + node.typeArguments = typeArguments && ts.parenthesizeTypeParameters(typeArguments); + return node; + } + ts.createTypeReferenceNode = createTypeReferenceNode; + function updateTypeReferenceNode(node, typeName, typeArguments) { + return node.typeName !== typeName + || node.typeArguments !== typeArguments + ? updateNode(createTypeReferenceNode(typeName, typeArguments), node) + : node; + } + ts.updateTypeReferenceNode = updateTypeReferenceNode; + function createFunctionTypeNode(typeParameters, parameters, type) { + return createSignatureDeclaration(165 /* FunctionType */, typeParameters, parameters, type); + } + ts.createFunctionTypeNode = createFunctionTypeNode; + function updateFunctionTypeNode(node, typeParameters, parameters, type) { + return updateSignatureDeclaration(node, typeParameters, parameters, type); + } + ts.updateFunctionTypeNode = updateFunctionTypeNode; + function createConstructorTypeNode(typeParameters, parameters, type) { + return createSignatureDeclaration(166 /* ConstructorType */, typeParameters, parameters, type); + } + ts.createConstructorTypeNode = createConstructorTypeNode; + function updateConstructorTypeNode(node, typeParameters, parameters, type) { + return updateSignatureDeclaration(node, typeParameters, parameters, type); + } + ts.updateConstructorTypeNode = updateConstructorTypeNode; + function createTypeQueryNode(exprName) { + var node = createSynthesizedNode(167 /* TypeQuery */); + node.exprName = exprName; + return node; + } + ts.createTypeQueryNode = createTypeQueryNode; + function updateTypeQueryNode(node, exprName) { + return node.exprName !== exprName + ? updateNode(createTypeQueryNode(exprName), node) + : node; + } + ts.updateTypeQueryNode = updateTypeQueryNode; + function createTypeLiteralNode(members) { + var node = createSynthesizedNode(168 /* TypeLiteral */); + node.members = createNodeArray(members); + return node; + } + ts.createTypeLiteralNode = createTypeLiteralNode; + function updateTypeLiteralNode(node, members) { + return node.members !== members + ? updateNode(createTypeLiteralNode(members), node) + : node; + } + ts.updateTypeLiteralNode = updateTypeLiteralNode; + function createArrayTypeNode(elementType) { + var node = createSynthesizedNode(169 /* ArrayType */); + node.elementType = ts.parenthesizeArrayTypeMember(elementType); + return node; + } + ts.createArrayTypeNode = createArrayTypeNode; + function updateArrayTypeNode(node, elementType) { + return node.elementType !== elementType + ? updateNode(createArrayTypeNode(elementType), node) + : node; + } + ts.updateArrayTypeNode = updateArrayTypeNode; + function createTupleTypeNode(elementTypes) { + var node = createSynthesizedNode(170 /* TupleType */); + node.elementTypes = createNodeArray(elementTypes); + return node; + } + ts.createTupleTypeNode = createTupleTypeNode; + function updateTupleTypeNode(node, elementTypes) { + return node.elementTypes !== elementTypes + ? updateNode(createTupleTypeNode(elementTypes), node) + : node; + } + ts.updateTupleTypeNode = updateTupleTypeNode; + function createOptionalTypeNode(type) { + var node = createSynthesizedNode(171 /* OptionalType */); + node.type = ts.parenthesizeArrayTypeMember(type); + return node; + } + ts.createOptionalTypeNode = createOptionalTypeNode; + function updateOptionalTypeNode(node, type) { + return node.type !== type + ? updateNode(createOptionalTypeNode(type), node) + : node; + } + ts.updateOptionalTypeNode = updateOptionalTypeNode; + function createRestTypeNode(type) { + var node = createSynthesizedNode(172 /* RestType */); + node.type = type; + return node; + } + ts.createRestTypeNode = createRestTypeNode; + function updateRestTypeNode(node, type) { + return node.type !== type + ? updateNode(createRestTypeNode(type), node) + : node; + } + ts.updateRestTypeNode = updateRestTypeNode; + function createUnionTypeNode(types) { + return createUnionOrIntersectionTypeNode(173 /* UnionType */, types); + } + ts.createUnionTypeNode = createUnionTypeNode; + function updateUnionTypeNode(node, types) { + return updateUnionOrIntersectionTypeNode(node, types); + } + ts.updateUnionTypeNode = updateUnionTypeNode; + function createIntersectionTypeNode(types) { + return createUnionOrIntersectionTypeNode(174 /* IntersectionType */, types); + } + ts.createIntersectionTypeNode = createIntersectionTypeNode; + function updateIntersectionTypeNode(node, types) { + return updateUnionOrIntersectionTypeNode(node, types); + } + ts.updateIntersectionTypeNode = updateIntersectionTypeNode; + function createUnionOrIntersectionTypeNode(kind, types) { + var node = createSynthesizedNode(kind); + node.types = ts.parenthesizeElementTypeMembers(types); + return node; + } + ts.createUnionOrIntersectionTypeNode = createUnionOrIntersectionTypeNode; + function updateUnionOrIntersectionTypeNode(node, types) { + return node.types !== types + ? updateNode(createUnionOrIntersectionTypeNode(node.kind, types), node) + : node; + } + function createConditionalTypeNode(checkType, extendsType, trueType, falseType) { + var node = createSynthesizedNode(175 /* ConditionalType */); + node.checkType = ts.parenthesizeConditionalTypeMember(checkType); + node.extendsType = ts.parenthesizeConditionalTypeMember(extendsType); + node.trueType = trueType; + node.falseType = falseType; + return node; + } + ts.createConditionalTypeNode = createConditionalTypeNode; + function updateConditionalTypeNode(node, checkType, extendsType, trueType, falseType) { + return node.checkType !== checkType + || node.extendsType !== extendsType + || node.trueType !== trueType + || node.falseType !== falseType + ? updateNode(createConditionalTypeNode(checkType, extendsType, trueType, falseType), node) + : node; + } + ts.updateConditionalTypeNode = updateConditionalTypeNode; + function createInferTypeNode(typeParameter) { + var node = createSynthesizedNode(176 /* InferType */); + node.typeParameter = typeParameter; + return node; + } + ts.createInferTypeNode = createInferTypeNode; + function updateInferTypeNode(node, typeParameter) { + return node.typeParameter !== typeParameter + ? updateNode(createInferTypeNode(typeParameter), node) + : node; + } + ts.updateInferTypeNode = updateInferTypeNode; + function createImportTypeNode(argument, qualifier, typeArguments, isTypeOf) { + var node = createSynthesizedNode(183 /* ImportType */); + node.argument = argument; + node.qualifier = qualifier; + node.typeArguments = asNodeArray(typeArguments); + node.isTypeOf = isTypeOf; + return node; + } + ts.createImportTypeNode = createImportTypeNode; + function updateImportTypeNode(node, argument, qualifier, typeArguments, isTypeOf) { + return node.argument !== argument + || node.qualifier !== qualifier + || node.typeArguments !== typeArguments + || node.isTypeOf !== isTypeOf + ? updateNode(createImportTypeNode(argument, qualifier, typeArguments, isTypeOf), node) + : node; + } + ts.updateImportTypeNode = updateImportTypeNode; + function createParenthesizedType(type) { + var node = createSynthesizedNode(177 /* ParenthesizedType */); + node.type = type; + return node; + } + ts.createParenthesizedType = createParenthesizedType; + function updateParenthesizedType(node, type) { + return node.type !== type + ? updateNode(createParenthesizedType(type), node) + : node; + } + ts.updateParenthesizedType = updateParenthesizedType; + function createThisTypeNode() { + return createSynthesizedNode(178 /* ThisType */); + } + ts.createThisTypeNode = createThisTypeNode; + function createTypeOperatorNode(operatorOrType, type) { + var node = createSynthesizedNode(179 /* TypeOperator */); + node.operator = typeof operatorOrType === "number" ? operatorOrType : 129 /* KeyOfKeyword */; + node.type = ts.parenthesizeElementTypeMember(typeof operatorOrType === "number" ? type : operatorOrType); + return node; + } + ts.createTypeOperatorNode = createTypeOperatorNode; + function updateTypeOperatorNode(node, type) { + return node.type !== type ? updateNode(createTypeOperatorNode(node.operator, type), node) : node; + } + ts.updateTypeOperatorNode = updateTypeOperatorNode; + function createIndexedAccessTypeNode(objectType, indexType) { + var node = createSynthesizedNode(180 /* IndexedAccessType */); + node.objectType = ts.parenthesizeElementTypeMember(objectType); + node.indexType = indexType; + return node; + } + ts.createIndexedAccessTypeNode = createIndexedAccessTypeNode; + function updateIndexedAccessTypeNode(node, objectType, indexType) { + return node.objectType !== objectType + || node.indexType !== indexType + ? updateNode(createIndexedAccessTypeNode(objectType, indexType), node) + : node; + } + ts.updateIndexedAccessTypeNode = updateIndexedAccessTypeNode; + function createMappedTypeNode(readonlyToken, typeParameter, questionToken, type) { + var node = createSynthesizedNode(181 /* MappedType */); + node.readonlyToken = readonlyToken; + node.typeParameter = typeParameter; + node.questionToken = questionToken; + node.type = type; + return node; + } + ts.createMappedTypeNode = createMappedTypeNode; + function updateMappedTypeNode(node, readonlyToken, typeParameter, questionToken, type) { + return node.readonlyToken !== readonlyToken + || node.typeParameter !== typeParameter + || node.questionToken !== questionToken + || node.type !== type + ? updateNode(createMappedTypeNode(readonlyToken, typeParameter, questionToken, type), node) + : node; + } + ts.updateMappedTypeNode = updateMappedTypeNode; + function createLiteralTypeNode(literal) { + var node = createSynthesizedNode(182 /* LiteralType */); + node.literal = literal; + return node; + } + ts.createLiteralTypeNode = createLiteralTypeNode; + function updateLiteralTypeNode(node, literal) { + return node.literal !== literal + ? updateNode(createLiteralTypeNode(literal), node) + : node; + } + ts.updateLiteralTypeNode = updateLiteralTypeNode; + // Binding Patterns + function createObjectBindingPattern(elements) { + var node = createSynthesizedNode(184 /* ObjectBindingPattern */); + node.elements = createNodeArray(elements); + return node; + } + ts.createObjectBindingPattern = createObjectBindingPattern; + function updateObjectBindingPattern(node, elements) { + return node.elements !== elements + ? updateNode(createObjectBindingPattern(elements), node) + : node; + } + ts.updateObjectBindingPattern = updateObjectBindingPattern; + function createArrayBindingPattern(elements) { + var node = createSynthesizedNode(185 /* ArrayBindingPattern */); + node.elements = createNodeArray(elements); + return node; + } + ts.createArrayBindingPattern = createArrayBindingPattern; + function updateArrayBindingPattern(node, elements) { + return node.elements !== elements + ? updateNode(createArrayBindingPattern(elements), node) + : node; + } + ts.updateArrayBindingPattern = updateArrayBindingPattern; + function createBindingElement(dotDotDotToken, propertyName, name, initializer) { + var node = createSynthesizedNode(186 /* BindingElement */); + node.dotDotDotToken = dotDotDotToken; + node.propertyName = asName(propertyName); + node.name = asName(name); + node.initializer = initializer; + return node; + } + ts.createBindingElement = createBindingElement; + function updateBindingElement(node, dotDotDotToken, propertyName, name, initializer) { + return node.propertyName !== propertyName + || node.dotDotDotToken !== dotDotDotToken + || node.name !== name + || node.initializer !== initializer + ? updateNode(createBindingElement(dotDotDotToken, propertyName, name, initializer), node) + : node; + } + ts.updateBindingElement = updateBindingElement; + // Expression + function createArrayLiteral(elements, multiLine) { + var node = createSynthesizedNode(187 /* ArrayLiteralExpression */); + node.elements = ts.parenthesizeListElements(createNodeArray(elements)); + if (multiLine) + node.multiLine = true; + return node; + } + ts.createArrayLiteral = createArrayLiteral; + function updateArrayLiteral(node, elements) { + return node.elements !== elements + ? updateNode(createArrayLiteral(elements, node.multiLine), node) + : node; + } + ts.updateArrayLiteral = updateArrayLiteral; + function createObjectLiteral(properties, multiLine) { + var node = createSynthesizedNode(188 /* ObjectLiteralExpression */); + node.properties = createNodeArray(properties); + if (multiLine) + node.multiLine = true; + return node; + } + ts.createObjectLiteral = createObjectLiteral; + function updateObjectLiteral(node, properties) { + return node.properties !== properties + ? updateNode(createObjectLiteral(properties, node.multiLine), node) + : node; + } + ts.updateObjectLiteral = updateObjectLiteral; + function createPropertyAccess(expression, name) { + var node = createSynthesizedNode(189 /* PropertyAccessExpression */); + node.expression = ts.parenthesizeForAccess(expression); + node.name = asName(name); // TODO: GH#18217 + setEmitFlags(node, 131072 /* NoIndentation */); + return node; + } + ts.createPropertyAccess = createPropertyAccess; + function updatePropertyAccess(node, expression, name) { + // Because we are updating existed propertyAccess we want to inherit its emitFlags + // instead of using the default from createPropertyAccess + return node.expression !== expression + || node.name !== name + ? updateNode(setEmitFlags(createPropertyAccess(expression, name), ts.getEmitFlags(node)), node) + : node; + } + ts.updatePropertyAccess = updatePropertyAccess; + function createElementAccess(expression, index) { + var node = createSynthesizedNode(190 /* ElementAccessExpression */); + node.expression = ts.parenthesizeForAccess(expression); + node.argumentExpression = asExpression(index); + return node; + } + ts.createElementAccess = createElementAccess; + function updateElementAccess(node, expression, argumentExpression) { + return node.expression !== expression + || node.argumentExpression !== argumentExpression + ? updateNode(createElementAccess(expression, argumentExpression), node) + : node; + } + ts.updateElementAccess = updateElementAccess; + function createCall(expression, typeArguments, argumentsArray) { + var node = createSynthesizedNode(191 /* CallExpression */); + node.expression = ts.parenthesizeForAccess(expression); + node.typeArguments = asNodeArray(typeArguments); + node.arguments = ts.parenthesizeListElements(createNodeArray(argumentsArray)); + return node; + } + ts.createCall = createCall; + function updateCall(node, expression, typeArguments, argumentsArray) { + return node.expression !== expression + || node.typeArguments !== typeArguments + || node.arguments !== argumentsArray + ? updateNode(createCall(expression, typeArguments, argumentsArray), node) + : node; + } + ts.updateCall = updateCall; + function createNew(expression, typeArguments, argumentsArray) { + var node = createSynthesizedNode(192 /* NewExpression */); + node.expression = ts.parenthesizeForNew(expression); + node.typeArguments = asNodeArray(typeArguments); + node.arguments = argumentsArray ? ts.parenthesizeListElements(createNodeArray(argumentsArray)) : undefined; + return node; + } + ts.createNew = createNew; + function updateNew(node, expression, typeArguments, argumentsArray) { + return node.expression !== expression + || node.typeArguments !== typeArguments + || node.arguments !== argumentsArray + ? updateNode(createNew(expression, typeArguments, argumentsArray), node) + : node; + } + ts.updateNew = updateNew; + function createTaggedTemplate(tag, typeArgumentsOrTemplate, template) { + var node = createSynthesizedNode(193 /* TaggedTemplateExpression */); + node.tag = ts.parenthesizeForAccess(tag); + if (template) { + node.typeArguments = asNodeArray(typeArgumentsOrTemplate); + node.template = template; + } + else { + node.typeArguments = undefined; + node.template = typeArgumentsOrTemplate; + } + return node; + } + ts.createTaggedTemplate = createTaggedTemplate; + function updateTaggedTemplate(node, tag, typeArgumentsOrTemplate, template) { + return node.tag !== tag + || (template + ? node.typeArguments !== typeArgumentsOrTemplate || node.template !== template + : node.typeArguments !== undefined || node.template !== typeArgumentsOrTemplate) + ? updateNode(createTaggedTemplate(tag, typeArgumentsOrTemplate, template), node) + : node; + } + ts.updateTaggedTemplate = updateTaggedTemplate; + function createTypeAssertion(type, expression) { + var node = createSynthesizedNode(194 /* TypeAssertionExpression */); + node.type = type; + node.expression = ts.parenthesizePrefixOperand(expression); + return node; + } + ts.createTypeAssertion = createTypeAssertion; + function updateTypeAssertion(node, type, expression) { + return node.type !== type + || node.expression !== expression + ? updateNode(createTypeAssertion(type, expression), node) + : node; + } + ts.updateTypeAssertion = updateTypeAssertion; + function createParen(expression) { + var node = createSynthesizedNode(195 /* ParenthesizedExpression */); + node.expression = expression; + return node; + } + ts.createParen = createParen; + function updateParen(node, expression) { + return node.expression !== expression + ? updateNode(createParen(expression), node) + : node; + } + ts.updateParen = updateParen; + function createFunctionExpression(modifiers, asteriskToken, name, typeParameters, parameters, type, body) { + var node = createSynthesizedNode(196 /* FunctionExpression */); + node.modifiers = asNodeArray(modifiers); + node.asteriskToken = asteriskToken; + node.name = asName(name); + node.typeParameters = asNodeArray(typeParameters); + node.parameters = createNodeArray(parameters); + node.type = type; + node.body = body; + return node; + } + ts.createFunctionExpression = createFunctionExpression; + function updateFunctionExpression(node, modifiers, asteriskToken, name, typeParameters, parameters, type, body) { + return node.name !== name + || node.modifiers !== modifiers + || node.asteriskToken !== asteriskToken + || node.typeParameters !== typeParameters + || node.parameters !== parameters + || node.type !== type + || node.body !== body + ? updateNode(createFunctionExpression(modifiers, asteriskToken, name, typeParameters, parameters, type, body), node) + : node; + } + ts.updateFunctionExpression = updateFunctionExpression; + function createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body) { + var node = createSynthesizedNode(197 /* ArrowFunction */); + node.modifiers = asNodeArray(modifiers); + node.typeParameters = asNodeArray(typeParameters); + node.parameters = createNodeArray(parameters); + node.type = type; + node.equalsGreaterThanToken = equalsGreaterThanToken || createToken(37 /* EqualsGreaterThanToken */); + node.body = ts.parenthesizeConciseBody(body); + return node; + } + ts.createArrowFunction = createArrowFunction; + function updateArrowFunction(node, modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body) { + return node.modifiers !== modifiers + || node.typeParameters !== typeParameters + || node.parameters !== parameters + || node.type !== type + || node.equalsGreaterThanToken !== equalsGreaterThanToken + || node.body !== body + ? updateNode(createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body), node) + : node; + } + ts.updateArrowFunction = updateArrowFunction; + function createDelete(expression) { + var node = createSynthesizedNode(198 /* DeleteExpression */); + node.expression = ts.parenthesizePrefixOperand(expression); + return node; + } + ts.createDelete = createDelete; + function updateDelete(node, expression) { + return node.expression !== expression + ? updateNode(createDelete(expression), node) + : node; + } + ts.updateDelete = updateDelete; + function createTypeOf(expression) { + var node = createSynthesizedNode(199 /* TypeOfExpression */); + node.expression = ts.parenthesizePrefixOperand(expression); + return node; + } + ts.createTypeOf = createTypeOf; + function updateTypeOf(node, expression) { + return node.expression !== expression + ? updateNode(createTypeOf(expression), node) + : node; + } + ts.updateTypeOf = updateTypeOf; + function createVoid(expression) { + var node = createSynthesizedNode(200 /* VoidExpression */); + node.expression = ts.parenthesizePrefixOperand(expression); + return node; + } + ts.createVoid = createVoid; + function updateVoid(node, expression) { + return node.expression !== expression + ? updateNode(createVoid(expression), node) + : node; + } + ts.updateVoid = updateVoid; + function createAwait(expression) { + var node = createSynthesizedNode(201 /* AwaitExpression */); + node.expression = ts.parenthesizePrefixOperand(expression); + return node; + } + ts.createAwait = createAwait; + function updateAwait(node, expression) { + return node.expression !== expression + ? updateNode(createAwait(expression), node) + : node; + } + ts.updateAwait = updateAwait; + function createPrefix(operator, operand) { + var node = createSynthesizedNode(202 /* PrefixUnaryExpression */); + node.operator = operator; + node.operand = ts.parenthesizePrefixOperand(operand); + return node; + } + ts.createPrefix = createPrefix; + function updatePrefix(node, operand) { + return node.operand !== operand + ? updateNode(createPrefix(node.operator, operand), node) + : node; + } + ts.updatePrefix = updatePrefix; + function createPostfix(operand, operator) { + var node = createSynthesizedNode(203 /* PostfixUnaryExpression */); + node.operand = ts.parenthesizePostfixOperand(operand); + node.operator = operator; + return node; + } + ts.createPostfix = createPostfix; + function updatePostfix(node, operand) { + return node.operand !== operand + ? updateNode(createPostfix(operand, node.operator), node) + : node; + } + ts.updatePostfix = updatePostfix; + function createBinary(left, operator, right) { + var node = createSynthesizedNode(204 /* BinaryExpression */); + var operatorToken = asToken(operator); + var operatorKind = operatorToken.kind; + node.left = ts.parenthesizeBinaryOperand(operatorKind, left, /*isLeftSideOfBinary*/ true, /*leftOperand*/ undefined); + node.operatorToken = operatorToken; + node.right = ts.parenthesizeBinaryOperand(operatorKind, right, /*isLeftSideOfBinary*/ false, node.left); + return node; + } + ts.createBinary = createBinary; + function updateBinary(node, left, right, operator) { + return node.left !== left + || node.right !== right + ? updateNode(createBinary(left, operator || node.operatorToken, right), node) + : node; + } + ts.updateBinary = updateBinary; + function createConditional(condition, questionTokenOrWhenTrue, whenTrueOrWhenFalse, colonToken, whenFalse) { + var node = createSynthesizedNode(205 /* ConditionalExpression */); + node.condition = ts.parenthesizeForConditionalHead(condition); + node.questionToken = whenFalse ? questionTokenOrWhenTrue : createToken(56 /* QuestionToken */); + node.whenTrue = ts.parenthesizeSubexpressionOfConditionalExpression(whenFalse ? whenTrueOrWhenFalse : questionTokenOrWhenTrue); + node.colonToken = whenFalse ? colonToken : createToken(57 /* ColonToken */); + node.whenFalse = ts.parenthesizeSubexpressionOfConditionalExpression(whenFalse ? whenFalse : whenTrueOrWhenFalse); + return node; + } + ts.createConditional = createConditional; + function updateConditional(node, condition, questionToken, whenTrue, colonToken, whenFalse) { + return node.condition !== condition + || node.questionToken !== questionToken + || node.whenTrue !== whenTrue + || node.colonToken !== colonToken + || node.whenFalse !== whenFalse + ? updateNode(createConditional(condition, questionToken, whenTrue, colonToken, whenFalse), node) + : node; + } + ts.updateConditional = updateConditional; + function createTemplateExpression(head, templateSpans) { + var node = createSynthesizedNode(206 /* TemplateExpression */); + node.head = head; + node.templateSpans = createNodeArray(templateSpans); + return node; + } + ts.createTemplateExpression = createTemplateExpression; + function updateTemplateExpression(node, head, templateSpans) { + return node.head !== head + || node.templateSpans !== templateSpans + ? updateNode(createTemplateExpression(head, templateSpans), node) + : node; + } + ts.updateTemplateExpression = updateTemplateExpression; + function createTemplateHead(text) { + var node = createSynthesizedNode(15 /* TemplateHead */); + node.text = text; + return node; + } + ts.createTemplateHead = createTemplateHead; + function createTemplateMiddle(text) { + var node = createSynthesizedNode(16 /* TemplateMiddle */); + node.text = text; + return node; + } + ts.createTemplateMiddle = createTemplateMiddle; + function createTemplateTail(text) { + var node = createSynthesizedNode(17 /* TemplateTail */); + node.text = text; + return node; + } + ts.createTemplateTail = createTemplateTail; + function createNoSubstitutionTemplateLiteral(text) { + var node = createSynthesizedNode(14 /* NoSubstitutionTemplateLiteral */); + node.text = text; + return node; + } + ts.createNoSubstitutionTemplateLiteral = createNoSubstitutionTemplateLiteral; + function createYield(asteriskTokenOrExpression, expression) { + var node = createSynthesizedNode(207 /* YieldExpression */); + node.asteriskToken = asteriskTokenOrExpression && asteriskTokenOrExpression.kind === 40 /* AsteriskToken */ ? asteriskTokenOrExpression : undefined; + node.expression = asteriskTokenOrExpression && asteriskTokenOrExpression.kind !== 40 /* AsteriskToken */ ? asteriskTokenOrExpression : expression; + return node; + } + ts.createYield = createYield; + function updateYield(node, asteriskToken, expression) { + return node.expression !== expression + || node.asteriskToken !== asteriskToken + ? updateNode(createYield(asteriskToken, expression), node) + : node; + } + ts.updateYield = updateYield; + function createSpread(expression) { + var node = createSynthesizedNode(208 /* SpreadElement */); + node.expression = ts.parenthesizeExpressionForList(expression); + return node; + } + ts.createSpread = createSpread; + function updateSpread(node, expression) { + return node.expression !== expression + ? updateNode(createSpread(expression), node) + : node; + } + ts.updateSpread = updateSpread; + function createClassExpression(modifiers, name, typeParameters, heritageClauses, members) { + var node = createSynthesizedNode(209 /* ClassExpression */); + node.decorators = undefined; + node.modifiers = asNodeArray(modifiers); + node.name = asName(name); + node.typeParameters = asNodeArray(typeParameters); + node.heritageClauses = asNodeArray(heritageClauses); + node.members = createNodeArray(members); + return node; + } + ts.createClassExpression = createClassExpression; + function updateClassExpression(node, modifiers, name, typeParameters, heritageClauses, members) { + return node.modifiers !== modifiers + || node.name !== name + || node.typeParameters !== typeParameters + || node.heritageClauses !== heritageClauses + || node.members !== members + ? updateNode(createClassExpression(modifiers, name, typeParameters, heritageClauses, members), node) + : node; + } + ts.updateClassExpression = updateClassExpression; + function createOmittedExpression() { + return createSynthesizedNode(210 /* OmittedExpression */); + } + ts.createOmittedExpression = createOmittedExpression; + function createExpressionWithTypeArguments(typeArguments, expression) { + var node = createSynthesizedNode(211 /* ExpressionWithTypeArguments */); + node.expression = ts.parenthesizeForAccess(expression); + node.typeArguments = asNodeArray(typeArguments); + return node; + } + ts.createExpressionWithTypeArguments = createExpressionWithTypeArguments; + function updateExpressionWithTypeArguments(node, typeArguments, expression) { + return node.typeArguments !== typeArguments + || node.expression !== expression + ? updateNode(createExpressionWithTypeArguments(typeArguments, expression), node) + : node; + } + ts.updateExpressionWithTypeArguments = updateExpressionWithTypeArguments; + function createAsExpression(expression, type) { + var node = createSynthesizedNode(212 /* AsExpression */); + node.expression = expression; + node.type = type; + return node; + } + ts.createAsExpression = createAsExpression; + function updateAsExpression(node, expression, type) { + return node.expression !== expression + || node.type !== type + ? updateNode(createAsExpression(expression, type), node) + : node; + } + ts.updateAsExpression = updateAsExpression; + function createNonNullExpression(expression) { + var node = createSynthesizedNode(213 /* NonNullExpression */); + node.expression = ts.parenthesizeForAccess(expression); + return node; + } + ts.createNonNullExpression = createNonNullExpression; + function updateNonNullExpression(node, expression) { + return node.expression !== expression + ? updateNode(createNonNullExpression(expression), node) + : node; + } + ts.updateNonNullExpression = updateNonNullExpression; + function createMetaProperty(keywordToken, name) { + var node = createSynthesizedNode(214 /* MetaProperty */); + node.keywordToken = keywordToken; + node.name = name; + return node; + } + ts.createMetaProperty = createMetaProperty; + function updateMetaProperty(node, name) { + return node.name !== name + ? updateNode(createMetaProperty(node.keywordToken, name), node) + : node; + } + ts.updateMetaProperty = updateMetaProperty; + // Misc + function createTemplateSpan(expression, literal) { + var node = createSynthesizedNode(216 /* TemplateSpan */); + node.expression = expression; + node.literal = literal; + return node; + } + ts.createTemplateSpan = createTemplateSpan; + function updateTemplateSpan(node, expression, literal) { + return node.expression !== expression + || node.literal !== literal + ? updateNode(createTemplateSpan(expression, literal), node) + : node; + } + ts.updateTemplateSpan = updateTemplateSpan; + function createSemicolonClassElement() { + return createSynthesizedNode(217 /* SemicolonClassElement */); + } + ts.createSemicolonClassElement = createSemicolonClassElement; + // Element + function createBlock(statements, multiLine) { + var block = createSynthesizedNode(218 /* Block */); + block.statements = createNodeArray(statements); + if (multiLine) + block.multiLine = multiLine; + return block; + } + ts.createBlock = createBlock; + function updateBlock(node, statements) { + return node.statements !== statements + ? updateNode(createBlock(statements, node.multiLine), node) + : node; + } + ts.updateBlock = updateBlock; + function createVariableStatement(modifiers, declarationList) { + var node = createSynthesizedNode(219 /* VariableStatement */); + node.decorators = undefined; + node.modifiers = asNodeArray(modifiers); + node.declarationList = ts.isArray(declarationList) ? createVariableDeclarationList(declarationList) : declarationList; + return node; + } + ts.createVariableStatement = createVariableStatement; + function updateVariableStatement(node, modifiers, declarationList) { + return node.modifiers !== modifiers + || node.declarationList !== declarationList + ? updateNode(createVariableStatement(modifiers, declarationList), node) + : node; + } + ts.updateVariableStatement = updateVariableStatement; + function createEmptyStatement() { + return createSynthesizedNode(220 /* EmptyStatement */); + } + ts.createEmptyStatement = createEmptyStatement; + function createExpressionStatement(expression) { + var node = createSynthesizedNode(221 /* ExpressionStatement */); + node.expression = ts.parenthesizeExpressionForExpressionStatement(expression); + return node; + } + ts.createExpressionStatement = createExpressionStatement; + function updateExpressionStatement(node, expression) { + return node.expression !== expression + ? updateNode(createExpressionStatement(expression), node) + : node; + } + ts.updateExpressionStatement = updateExpressionStatement; + /** @deprecated Use `createExpressionStatement` instead. */ + ts.createStatement = createExpressionStatement; + /** @deprecated Use `updateExpressionStatement` instead. */ + ts.updateStatement = updateExpressionStatement; + function createIf(expression, thenStatement, elseStatement) { + var node = createSynthesizedNode(222 /* IfStatement */); + node.expression = expression; + node.thenStatement = thenStatement; + node.elseStatement = elseStatement; + return node; + } + ts.createIf = createIf; + function updateIf(node, expression, thenStatement, elseStatement) { + return node.expression !== expression + || node.thenStatement !== thenStatement + || node.elseStatement !== elseStatement + ? updateNode(createIf(expression, thenStatement, elseStatement), node) + : node; + } + ts.updateIf = updateIf; + function createDo(statement, expression) { + var node = createSynthesizedNode(223 /* DoStatement */); + node.statement = statement; + node.expression = expression; + return node; + } + ts.createDo = createDo; + function updateDo(node, statement, expression) { + return node.statement !== statement + || node.expression !== expression + ? updateNode(createDo(statement, expression), node) + : node; + } + ts.updateDo = updateDo; + function createWhile(expression, statement) { + var node = createSynthesizedNode(224 /* WhileStatement */); + node.expression = expression; + node.statement = statement; + return node; + } + ts.createWhile = createWhile; + function updateWhile(node, expression, statement) { + return node.expression !== expression + || node.statement !== statement + ? updateNode(createWhile(expression, statement), node) + : node; + } + ts.updateWhile = updateWhile; + function createFor(initializer, condition, incrementor, statement) { + var node = createSynthesizedNode(225 /* ForStatement */); + node.initializer = initializer; + node.condition = condition; + node.incrementor = incrementor; + node.statement = statement; + return node; + } + ts.createFor = createFor; + function updateFor(node, initializer, condition, incrementor, statement) { + return node.initializer !== initializer + || node.condition !== condition + || node.incrementor !== incrementor + || node.statement !== statement + ? updateNode(createFor(initializer, condition, incrementor, statement), node) + : node; + } + ts.updateFor = updateFor; + function createForIn(initializer, expression, statement) { + var node = createSynthesizedNode(226 /* ForInStatement */); + node.initializer = initializer; + node.expression = expression; + node.statement = statement; + return node; + } + ts.createForIn = createForIn; + function updateForIn(node, initializer, expression, statement) { + return node.initializer !== initializer + || node.expression !== expression + || node.statement !== statement + ? updateNode(createForIn(initializer, expression, statement), node) + : node; + } + ts.updateForIn = updateForIn; + function createForOf(awaitModifier, initializer, expression, statement) { + var node = createSynthesizedNode(227 /* ForOfStatement */); + node.awaitModifier = awaitModifier; + node.initializer = initializer; + node.expression = expression; + node.statement = statement; + return node; + } + ts.createForOf = createForOf; + function updateForOf(node, awaitModifier, initializer, expression, statement) { + return node.awaitModifier !== awaitModifier + || node.initializer !== initializer + || node.expression !== expression + || node.statement !== statement + ? updateNode(createForOf(awaitModifier, initializer, expression, statement), node) + : node; + } + ts.updateForOf = updateForOf; + function createContinue(label) { + var node = createSynthesizedNode(228 /* ContinueStatement */); + node.label = asName(label); + return node; + } + ts.createContinue = createContinue; + function updateContinue(node, label) { + return node.label !== label + ? updateNode(createContinue(label), node) + : node; + } + ts.updateContinue = updateContinue; + function createBreak(label) { + var node = createSynthesizedNode(229 /* BreakStatement */); + node.label = asName(label); + return node; + } + ts.createBreak = createBreak; + function updateBreak(node, label) { + return node.label !== label + ? updateNode(createBreak(label), node) + : node; + } + ts.updateBreak = updateBreak; + function createReturn(expression) { + var node = createSynthesizedNode(230 /* ReturnStatement */); + node.expression = expression; + return node; + } + ts.createReturn = createReturn; + function updateReturn(node, expression) { + return node.expression !== expression + ? updateNode(createReturn(expression), node) + : node; + } + ts.updateReturn = updateReturn; + function createWith(expression, statement) { + var node = createSynthesizedNode(231 /* WithStatement */); + node.expression = expression; + node.statement = statement; + return node; + } + ts.createWith = createWith; + function updateWith(node, expression, statement) { + return node.expression !== expression + || node.statement !== statement + ? updateNode(createWith(expression, statement), node) + : node; + } + ts.updateWith = updateWith; + function createSwitch(expression, caseBlock) { + var node = createSynthesizedNode(232 /* SwitchStatement */); + node.expression = ts.parenthesizeExpressionForList(expression); + node.caseBlock = caseBlock; + return node; + } + ts.createSwitch = createSwitch; + function updateSwitch(node, expression, caseBlock) { + return node.expression !== expression + || node.caseBlock !== caseBlock + ? updateNode(createSwitch(expression, caseBlock), node) + : node; + } + ts.updateSwitch = updateSwitch; + function createLabel(label, statement) { + var node = createSynthesizedNode(233 /* LabeledStatement */); + node.label = asName(label); + node.statement = statement; + return node; + } + ts.createLabel = createLabel; + function updateLabel(node, label, statement) { + return node.label !== label + || node.statement !== statement + ? updateNode(createLabel(label, statement), node) + : node; + } + ts.updateLabel = updateLabel; + function createThrow(expression) { + var node = createSynthesizedNode(234 /* ThrowStatement */); + node.expression = expression; + return node; + } + ts.createThrow = createThrow; + function updateThrow(node, expression) { + return node.expression !== expression + ? updateNode(createThrow(expression), node) + : node; + } + ts.updateThrow = updateThrow; + function createTry(tryBlock, catchClause, finallyBlock) { + var node = createSynthesizedNode(235 /* TryStatement */); + node.tryBlock = tryBlock; + node.catchClause = catchClause; + node.finallyBlock = finallyBlock; + return node; + } + ts.createTry = createTry; + function updateTry(node, tryBlock, catchClause, finallyBlock) { + return node.tryBlock !== tryBlock + || node.catchClause !== catchClause + || node.finallyBlock !== finallyBlock + ? updateNode(createTry(tryBlock, catchClause, finallyBlock), node) + : node; + } + ts.updateTry = updateTry; + function createDebuggerStatement() { + return createSynthesizedNode(236 /* DebuggerStatement */); + } + ts.createDebuggerStatement = createDebuggerStatement; + function createVariableDeclaration(name, type, initializer) { + var node = createSynthesizedNode(237 /* VariableDeclaration */); + node.name = asName(name); + node.type = type; + node.initializer = initializer !== undefined ? ts.parenthesizeExpressionForList(initializer) : undefined; + return node; + } + ts.createVariableDeclaration = createVariableDeclaration; + function updateVariableDeclaration(node, name, type, initializer) { + return node.name !== name + || node.type !== type + || node.initializer !== initializer + ? updateNode(createVariableDeclaration(name, type, initializer), node) + : node; + } + ts.updateVariableDeclaration = updateVariableDeclaration; + function createVariableDeclarationList(declarations, flags) { + if (flags === void 0) { flags = 0 /* None */; } + var node = createSynthesizedNode(238 /* VariableDeclarationList */); + node.flags |= flags & 3 /* BlockScoped */; + node.declarations = createNodeArray(declarations); + return node; + } + ts.createVariableDeclarationList = createVariableDeclarationList; + function updateVariableDeclarationList(node, declarations) { + return node.declarations !== declarations + ? updateNode(createVariableDeclarationList(declarations, node.flags), node) + : node; + } + ts.updateVariableDeclarationList = updateVariableDeclarationList; + function createFunctionDeclaration(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body) { + var node = createSynthesizedNode(239 /* FunctionDeclaration */); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.asteriskToken = asteriskToken; + node.name = asName(name); + node.typeParameters = asNodeArray(typeParameters); + node.parameters = createNodeArray(parameters); + node.type = type; + node.body = body; + return node; + } + ts.createFunctionDeclaration = createFunctionDeclaration; + function updateFunctionDeclaration(node, decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.asteriskToken !== asteriskToken + || node.name !== name + || node.typeParameters !== typeParameters + || node.parameters !== parameters + || node.type !== type + || node.body !== body + ? updateNode(createFunctionDeclaration(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body), node) + : node; + } + ts.updateFunctionDeclaration = updateFunctionDeclaration; + function createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) { + var node = createSynthesizedNode(240 /* ClassDeclaration */); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.name = asName(name); + node.typeParameters = asNodeArray(typeParameters); + node.heritageClauses = asNodeArray(heritageClauses); + node.members = createNodeArray(members); + return node; + } + ts.createClassDeclaration = createClassDeclaration; + function updateClassDeclaration(node, decorators, modifiers, name, typeParameters, heritageClauses, members) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.name !== name + || node.typeParameters !== typeParameters + || node.heritageClauses !== heritageClauses + || node.members !== members + ? updateNode(createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members), node) + : node; + } + ts.updateClassDeclaration = updateClassDeclaration; + function createInterfaceDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) { + var node = createSynthesizedNode(241 /* InterfaceDeclaration */); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.name = asName(name); + node.typeParameters = asNodeArray(typeParameters); + node.heritageClauses = asNodeArray(heritageClauses); + node.members = createNodeArray(members); + return node; + } + ts.createInterfaceDeclaration = createInterfaceDeclaration; + function updateInterfaceDeclaration(node, decorators, modifiers, name, typeParameters, heritageClauses, members) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.name !== name + || node.typeParameters !== typeParameters + || node.heritageClauses !== heritageClauses + || node.members !== members + ? updateNode(createInterfaceDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members), node) + : node; + } + ts.updateInterfaceDeclaration = updateInterfaceDeclaration; + function createTypeAliasDeclaration(decorators, modifiers, name, typeParameters, type) { + var node = createSynthesizedNode(242 /* TypeAliasDeclaration */); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.name = asName(name); + node.typeParameters = asNodeArray(typeParameters); + node.type = type; + return node; + } + ts.createTypeAliasDeclaration = createTypeAliasDeclaration; + function updateTypeAliasDeclaration(node, decorators, modifiers, name, typeParameters, type) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.name !== name + || node.typeParameters !== typeParameters + || node.type !== type + ? updateNode(createTypeAliasDeclaration(decorators, modifiers, name, typeParameters, type), node) + : node; + } + ts.updateTypeAliasDeclaration = updateTypeAliasDeclaration; + function createEnumDeclaration(decorators, modifiers, name, members) { + var node = createSynthesizedNode(243 /* EnumDeclaration */); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.name = asName(name); + node.members = createNodeArray(members); + return node; + } + ts.createEnumDeclaration = createEnumDeclaration; + function updateEnumDeclaration(node, decorators, modifiers, name, members) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.name !== name + || node.members !== members + ? updateNode(createEnumDeclaration(decorators, modifiers, name, members), node) + : node; + } + ts.updateEnumDeclaration = updateEnumDeclaration; + function createModuleDeclaration(decorators, modifiers, name, body, flags) { + if (flags === void 0) { flags = 0 /* None */; } + var node = createSynthesizedNode(244 /* ModuleDeclaration */); + node.flags |= flags & (16 /* Namespace */ | 4 /* NestedNamespace */ | 512 /* GlobalAugmentation */); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.name = name; + node.body = body; + return node; + } + ts.createModuleDeclaration = createModuleDeclaration; + function updateModuleDeclaration(node, decorators, modifiers, name, body) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.name !== name + || node.body !== body + ? updateNode(createModuleDeclaration(decorators, modifiers, name, body, node.flags), node) + : node; + } + ts.updateModuleDeclaration = updateModuleDeclaration; + function createModuleBlock(statements) { + var node = createSynthesizedNode(245 /* ModuleBlock */); + node.statements = createNodeArray(statements); + return node; + } + ts.createModuleBlock = createModuleBlock; + function updateModuleBlock(node, statements) { + return node.statements !== statements + ? updateNode(createModuleBlock(statements), node) + : node; + } + ts.updateModuleBlock = updateModuleBlock; + function createCaseBlock(clauses) { + var node = createSynthesizedNode(246 /* CaseBlock */); + node.clauses = createNodeArray(clauses); + return node; + } + ts.createCaseBlock = createCaseBlock; + function updateCaseBlock(node, clauses) { + return node.clauses !== clauses + ? updateNode(createCaseBlock(clauses), node) + : node; + } + ts.updateCaseBlock = updateCaseBlock; + function createNamespaceExportDeclaration(name) { + var node = createSynthesizedNode(247 /* NamespaceExportDeclaration */); + node.name = asName(name); + return node; + } + ts.createNamespaceExportDeclaration = createNamespaceExportDeclaration; + function updateNamespaceExportDeclaration(node, name) { + return node.name !== name + ? updateNode(createNamespaceExportDeclaration(name), node) + : node; + } + ts.updateNamespaceExportDeclaration = updateNamespaceExportDeclaration; + function createImportEqualsDeclaration(decorators, modifiers, name, moduleReference) { + var node = createSynthesizedNode(248 /* ImportEqualsDeclaration */); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.name = asName(name); + node.moduleReference = moduleReference; + return node; + } + ts.createImportEqualsDeclaration = createImportEqualsDeclaration; + function updateImportEqualsDeclaration(node, decorators, modifiers, name, moduleReference) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.name !== name + || node.moduleReference !== moduleReference + ? updateNode(createImportEqualsDeclaration(decorators, modifiers, name, moduleReference), node) + : node; + } + ts.updateImportEqualsDeclaration = updateImportEqualsDeclaration; + function createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier) { + var node = createSynthesizedNode(249 /* ImportDeclaration */); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.importClause = importClause; + node.moduleSpecifier = moduleSpecifier; + return node; + } + ts.createImportDeclaration = createImportDeclaration; + function updateImportDeclaration(node, decorators, modifiers, importClause, moduleSpecifier) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.importClause !== importClause + || node.moduleSpecifier !== moduleSpecifier + ? updateNode(createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier), node) + : node; + } + ts.updateImportDeclaration = updateImportDeclaration; + function createImportClause(name, namedBindings) { + var node = createSynthesizedNode(250 /* ImportClause */); + node.name = name; + node.namedBindings = namedBindings; + return node; + } + ts.createImportClause = createImportClause; + function updateImportClause(node, name, namedBindings) { + return node.name !== name + || node.namedBindings !== namedBindings + ? updateNode(createImportClause(name, namedBindings), node) + : node; + } + ts.updateImportClause = updateImportClause; + function createNamespaceImport(name) { + var node = createSynthesizedNode(251 /* NamespaceImport */); + node.name = name; + return node; + } + ts.createNamespaceImport = createNamespaceImport; + function updateNamespaceImport(node, name) { + return node.name !== name + ? updateNode(createNamespaceImport(name), node) + : node; + } + ts.updateNamespaceImport = updateNamespaceImport; + function createNamedImports(elements) { + var node = createSynthesizedNode(252 /* NamedImports */); + node.elements = createNodeArray(elements); + return node; + } + ts.createNamedImports = createNamedImports; + function updateNamedImports(node, elements) { + return node.elements !== elements + ? updateNode(createNamedImports(elements), node) + : node; + } + ts.updateNamedImports = updateNamedImports; + function createImportSpecifier(propertyName, name) { + var node = createSynthesizedNode(253 /* ImportSpecifier */); + node.propertyName = propertyName; + node.name = name; + return node; + } + ts.createImportSpecifier = createImportSpecifier; + function updateImportSpecifier(node, propertyName, name) { + return node.propertyName !== propertyName + || node.name !== name + ? updateNode(createImportSpecifier(propertyName, name), node) + : node; + } + ts.updateImportSpecifier = updateImportSpecifier; + function createExportAssignment(decorators, modifiers, isExportEquals, expression) { + var node = createSynthesizedNode(254 /* ExportAssignment */); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.isExportEquals = isExportEquals; + node.expression = isExportEquals ? ts.parenthesizeBinaryOperand(59 /* EqualsToken */, expression, /*isLeftSideOfBinary*/ false, /*leftOperand*/ undefined) : ts.parenthesizeDefaultExpression(expression); + return node; + } + ts.createExportAssignment = createExportAssignment; + function updateExportAssignment(node, decorators, modifiers, expression) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.expression !== expression + ? updateNode(createExportAssignment(decorators, modifiers, node.isExportEquals, expression), node) + : node; + } + ts.updateExportAssignment = updateExportAssignment; + function createExportDeclaration(decorators, modifiers, exportClause, moduleSpecifier) { + var node = createSynthesizedNode(255 /* ExportDeclaration */); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.exportClause = exportClause; + node.moduleSpecifier = moduleSpecifier; + return node; + } + ts.createExportDeclaration = createExportDeclaration; + function updateExportDeclaration(node, decorators, modifiers, exportClause, moduleSpecifier) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.exportClause !== exportClause + || node.moduleSpecifier !== moduleSpecifier + ? updateNode(createExportDeclaration(decorators, modifiers, exportClause, moduleSpecifier), node) + : node; + } + ts.updateExportDeclaration = updateExportDeclaration; + function createNamedExports(elements) { + var node = createSynthesizedNode(256 /* NamedExports */); + node.elements = createNodeArray(elements); + return node; + } + ts.createNamedExports = createNamedExports; + function updateNamedExports(node, elements) { + return node.elements !== elements + ? updateNode(createNamedExports(elements), node) + : node; + } + ts.updateNamedExports = updateNamedExports; + function createExportSpecifier(propertyName, name) { + var node = createSynthesizedNode(257 /* ExportSpecifier */); + node.propertyName = asName(propertyName); + node.name = asName(name); + return node; + } + ts.createExportSpecifier = createExportSpecifier; + function updateExportSpecifier(node, propertyName, name) { + return node.propertyName !== propertyName + || node.name !== name + ? updateNode(createExportSpecifier(propertyName, name), node) + : node; + } + ts.updateExportSpecifier = updateExportSpecifier; + // Module references + function createExternalModuleReference(expression) { + var node = createSynthesizedNode(259 /* ExternalModuleReference */); + node.expression = expression; + return node; + } + ts.createExternalModuleReference = createExternalModuleReference; + function updateExternalModuleReference(node, expression) { + return node.expression !== expression + ? updateNode(createExternalModuleReference(expression), node) + : node; + } + ts.updateExternalModuleReference = updateExternalModuleReference; + // JSDoc + /* @internal */ + function createJSDocTypeExpression(type) { + var node = createSynthesizedNode(283 /* JSDocTypeExpression */); + node.type = type; + return node; + } + ts.createJSDocTypeExpression = createJSDocTypeExpression; + /* @internal */ + function createJSDocTypeTag(typeExpression, comment) { + var tag = createJSDocTag(302 /* JSDocTypeTag */, "type"); + tag.typeExpression = typeExpression; + tag.comment = comment; + return tag; + } + ts.createJSDocTypeTag = createJSDocTypeTag; + /* @internal */ + function createJSDocReturnTag(typeExpression, comment) { + var tag = createJSDocTag(300 /* JSDocReturnTag */, "returns"); + tag.typeExpression = typeExpression; + tag.comment = comment; + return tag; + } + ts.createJSDocReturnTag = createJSDocReturnTag; + /* @internal */ + function createJSDocParamTag(name, isBracketed, typeExpression, comment) { + var tag = createJSDocTag(299 /* JSDocParameterTag */, "param"); + tag.typeExpression = typeExpression; + tag.name = name; + tag.isBracketed = isBracketed; + tag.comment = comment; + return tag; + } + ts.createJSDocParamTag = createJSDocParamTag; + /* @internal */ + function createJSDocComment(comment, tags) { + var node = createSynthesizedNode(291 /* JSDocComment */); + node.comment = comment; + node.tags = tags; + return node; + } + ts.createJSDocComment = createJSDocComment; + /* @internal */ + function createJSDocTag(kind, tagName) { + var node = createSynthesizedNode(kind); + node.tagName = createIdentifier(tagName); + return node; + } + // JSX + function createJsxElement(openingElement, children, closingElement) { + var node = createSynthesizedNode(260 /* JsxElement */); + node.openingElement = openingElement; + node.children = createNodeArray(children); + node.closingElement = closingElement; + return node; + } + ts.createJsxElement = createJsxElement; + function updateJsxElement(node, openingElement, children, closingElement) { + return node.openingElement !== openingElement + || node.children !== children + || node.closingElement !== closingElement + ? updateNode(createJsxElement(openingElement, children, closingElement), node) + : node; + } + ts.updateJsxElement = updateJsxElement; + function createJsxSelfClosingElement(tagName, typeArguments, attributes) { + var node = createSynthesizedNode(261 /* JsxSelfClosingElement */); + node.tagName = tagName; + node.typeArguments = asNodeArray(typeArguments); + node.attributes = attributes; + return node; + } + ts.createJsxSelfClosingElement = createJsxSelfClosingElement; + function updateJsxSelfClosingElement(node, tagName, typeArguments, attributes) { + return node.tagName !== tagName + || node.typeArguments !== typeArguments + || node.attributes !== attributes + ? updateNode(createJsxSelfClosingElement(tagName, typeArguments, attributes), node) + : node; + } + ts.updateJsxSelfClosingElement = updateJsxSelfClosingElement; + function createJsxOpeningElement(tagName, typeArguments, attributes) { + var node = createSynthesizedNode(262 /* JsxOpeningElement */); + node.tagName = tagName; + node.typeArguments = asNodeArray(typeArguments); + node.attributes = attributes; + return node; + } + ts.createJsxOpeningElement = createJsxOpeningElement; + function updateJsxOpeningElement(node, tagName, typeArguments, attributes) { + return node.tagName !== tagName + || node.typeArguments !== typeArguments + || node.attributes !== attributes + ? updateNode(createJsxOpeningElement(tagName, typeArguments, attributes), node) + : node; + } + ts.updateJsxOpeningElement = updateJsxOpeningElement; + function createJsxClosingElement(tagName) { + var node = createSynthesizedNode(263 /* JsxClosingElement */); + node.tagName = tagName; + return node; + } + ts.createJsxClosingElement = createJsxClosingElement; + function updateJsxClosingElement(node, tagName) { + return node.tagName !== tagName + ? updateNode(createJsxClosingElement(tagName), node) + : node; + } + ts.updateJsxClosingElement = updateJsxClosingElement; + function createJsxFragment(openingFragment, children, closingFragment) { + var node = createSynthesizedNode(264 /* JsxFragment */); + node.openingFragment = openingFragment; + node.children = createNodeArray(children); + node.closingFragment = closingFragment; + return node; + } + ts.createJsxFragment = createJsxFragment; + function updateJsxFragment(node, openingFragment, children, closingFragment) { + return node.openingFragment !== openingFragment + || node.children !== children + || node.closingFragment !== closingFragment + ? updateNode(createJsxFragment(openingFragment, children, closingFragment), node) + : node; + } + ts.updateJsxFragment = updateJsxFragment; + function createJsxAttribute(name, initializer) { + var node = createSynthesizedNode(267 /* JsxAttribute */); + node.name = name; + node.initializer = initializer; + return node; + } + ts.createJsxAttribute = createJsxAttribute; + function updateJsxAttribute(node, name, initializer) { + return node.name !== name + || node.initializer !== initializer + ? updateNode(createJsxAttribute(name, initializer), node) + : node; + } + ts.updateJsxAttribute = updateJsxAttribute; + function createJsxAttributes(properties) { + var node = createSynthesizedNode(268 /* JsxAttributes */); + node.properties = createNodeArray(properties); + return node; + } + ts.createJsxAttributes = createJsxAttributes; + function updateJsxAttributes(node, properties) { + return node.properties !== properties + ? updateNode(createJsxAttributes(properties), node) + : node; + } + ts.updateJsxAttributes = updateJsxAttributes; + function createJsxSpreadAttribute(expression) { + var node = createSynthesizedNode(269 /* JsxSpreadAttribute */); + node.expression = expression; + return node; + } + ts.createJsxSpreadAttribute = createJsxSpreadAttribute; + function updateJsxSpreadAttribute(node, expression) { + return node.expression !== expression + ? updateNode(createJsxSpreadAttribute(expression), node) + : node; + } + ts.updateJsxSpreadAttribute = updateJsxSpreadAttribute; + function createJsxExpression(dotDotDotToken, expression) { + var node = createSynthesizedNode(270 /* JsxExpression */); + node.dotDotDotToken = dotDotDotToken; + node.expression = expression; + return node; + } + ts.createJsxExpression = createJsxExpression; + function updateJsxExpression(node, expression) { + return node.expression !== expression + ? updateNode(createJsxExpression(node.dotDotDotToken, expression), node) + : node; + } + ts.updateJsxExpression = updateJsxExpression; + // Clauses + function createCaseClause(expression, statements) { + var node = createSynthesizedNode(271 /* CaseClause */); + node.expression = ts.parenthesizeExpressionForList(expression); + node.statements = createNodeArray(statements); + return node; + } + ts.createCaseClause = createCaseClause; + function updateCaseClause(node, expression, statements) { + return node.expression !== expression + || node.statements !== statements + ? updateNode(createCaseClause(expression, statements), node) + : node; + } + ts.updateCaseClause = updateCaseClause; + function createDefaultClause(statements) { + var node = createSynthesizedNode(272 /* DefaultClause */); + node.statements = createNodeArray(statements); + return node; + } + ts.createDefaultClause = createDefaultClause; + function updateDefaultClause(node, statements) { + return node.statements !== statements + ? updateNode(createDefaultClause(statements), node) + : node; + } + ts.updateDefaultClause = updateDefaultClause; + function createHeritageClause(token, types) { + var node = createSynthesizedNode(273 /* HeritageClause */); + node.token = token; + node.types = createNodeArray(types); + return node; + } + ts.createHeritageClause = createHeritageClause; + function updateHeritageClause(node, types) { + return node.types !== types + ? updateNode(createHeritageClause(node.token, types), node) + : node; + } + ts.updateHeritageClause = updateHeritageClause; + function createCatchClause(variableDeclaration, block) { + var node = createSynthesizedNode(274 /* CatchClause */); + node.variableDeclaration = ts.isString(variableDeclaration) ? createVariableDeclaration(variableDeclaration) : variableDeclaration; + node.block = block; + return node; + } + ts.createCatchClause = createCatchClause; + function updateCatchClause(node, variableDeclaration, block) { + return node.variableDeclaration !== variableDeclaration + || node.block !== block + ? updateNode(createCatchClause(variableDeclaration, block), node) + : node; + } + ts.updateCatchClause = updateCatchClause; + // Property assignments + function createPropertyAssignment(name, initializer) { + var node = createSynthesizedNode(275 /* PropertyAssignment */); + node.name = asName(name); + node.questionToken = undefined; + node.initializer = ts.parenthesizeExpressionForList(initializer); + return node; + } + ts.createPropertyAssignment = createPropertyAssignment; + function updatePropertyAssignment(node, name, initializer) { + return node.name !== name + || node.initializer !== initializer + ? updateNode(createPropertyAssignment(name, initializer), node) + : node; + } + ts.updatePropertyAssignment = updatePropertyAssignment; + function createShorthandPropertyAssignment(name, objectAssignmentInitializer) { + var node = createSynthesizedNode(276 /* ShorthandPropertyAssignment */); + node.name = asName(name); + node.objectAssignmentInitializer = objectAssignmentInitializer !== undefined ? ts.parenthesizeExpressionForList(objectAssignmentInitializer) : undefined; + return node; + } + ts.createShorthandPropertyAssignment = createShorthandPropertyAssignment; + function updateShorthandPropertyAssignment(node, name, objectAssignmentInitializer) { + return node.name !== name + || node.objectAssignmentInitializer !== objectAssignmentInitializer + ? updateNode(createShorthandPropertyAssignment(name, objectAssignmentInitializer), node) + : node; + } + ts.updateShorthandPropertyAssignment = updateShorthandPropertyAssignment; + function createSpreadAssignment(expression) { + var node = createSynthesizedNode(277 /* SpreadAssignment */); + node.expression = expression !== undefined ? ts.parenthesizeExpressionForList(expression) : undefined; // TODO: GH#18217 + return node; + } + ts.createSpreadAssignment = createSpreadAssignment; + function updateSpreadAssignment(node, expression) { + return node.expression !== expression + ? updateNode(createSpreadAssignment(expression), node) + : node; + } + ts.updateSpreadAssignment = updateSpreadAssignment; + // Enum + function createEnumMember(name, initializer) { + var node = createSynthesizedNode(278 /* EnumMember */); + node.name = asName(name); + node.initializer = initializer && ts.parenthesizeExpressionForList(initializer); + return node; + } + ts.createEnumMember = createEnumMember; + function updateEnumMember(node, name, initializer) { + return node.name !== name + || node.initializer !== initializer + ? updateNode(createEnumMember(name, initializer), node) + : node; + } + ts.updateEnumMember = updateEnumMember; + // Top-level nodes + function updateSourceFileNode(node, statements, isDeclarationFile, referencedFiles, typeReferences, hasNoDefaultLib, libReferences) { + if (node.statements !== statements || + (isDeclarationFile !== undefined && node.isDeclarationFile !== isDeclarationFile) || + (referencedFiles !== undefined && node.referencedFiles !== referencedFiles) || + (typeReferences !== undefined && node.typeReferenceDirectives !== typeReferences) || + (libReferences !== undefined && node.libReferenceDirectives !== libReferences) || + (hasNoDefaultLib !== undefined && node.hasNoDefaultLib !== hasNoDefaultLib)) { + var updated = createSynthesizedNode(279 /* SourceFile */); + updated.flags |= node.flags; + updated.statements = createNodeArray(statements); + updated.endOfFileToken = node.endOfFileToken; + updated.fileName = node.fileName; + updated.path = node.path; + updated.text = node.text; + updated.isDeclarationFile = isDeclarationFile === undefined ? node.isDeclarationFile : isDeclarationFile; + updated.referencedFiles = referencedFiles === undefined ? node.referencedFiles : referencedFiles; + updated.typeReferenceDirectives = typeReferences === undefined ? node.typeReferenceDirectives : typeReferences; + updated.hasNoDefaultLib = hasNoDefaultLib === undefined ? node.hasNoDefaultLib : hasNoDefaultLib; + updated.libReferenceDirectives = libReferences === undefined ? node.libReferenceDirectives : libReferences; + if (node.amdDependencies !== undefined) + updated.amdDependencies = node.amdDependencies; + if (node.moduleName !== undefined) + updated.moduleName = node.moduleName; + if (node.languageVariant !== undefined) + updated.languageVariant = node.languageVariant; + if (node.renamedDependencies !== undefined) + updated.renamedDependencies = node.renamedDependencies; + if (node.languageVersion !== undefined) + updated.languageVersion = node.languageVersion; + if (node.scriptKind !== undefined) + updated.scriptKind = node.scriptKind; + if (node.externalModuleIndicator !== undefined) + updated.externalModuleIndicator = node.externalModuleIndicator; + if (node.commonJsModuleIndicator !== undefined) + updated.commonJsModuleIndicator = node.commonJsModuleIndicator; + if (node.identifiers !== undefined) + updated.identifiers = node.identifiers; + if (node.nodeCount !== undefined) + updated.nodeCount = node.nodeCount; + if (node.identifierCount !== undefined) + updated.identifierCount = node.identifierCount; + if (node.symbolCount !== undefined) + updated.symbolCount = node.symbolCount; + if (node.parseDiagnostics !== undefined) + updated.parseDiagnostics = node.parseDiagnostics; + if (node.bindDiagnostics !== undefined) + updated.bindDiagnostics = node.bindDiagnostics; + if (node.bindSuggestionDiagnostics !== undefined) + updated.bindSuggestionDiagnostics = node.bindSuggestionDiagnostics; + if (node.lineMap !== undefined) + updated.lineMap = node.lineMap; + if (node.classifiableNames !== undefined) + updated.classifiableNames = node.classifiableNames; + if (node.resolvedModules !== undefined) + updated.resolvedModules = node.resolvedModules; + if (node.resolvedTypeReferenceDirectiveNames !== undefined) + updated.resolvedTypeReferenceDirectiveNames = node.resolvedTypeReferenceDirectiveNames; + if (node.imports !== undefined) + updated.imports = node.imports; + if (node.moduleAugmentations !== undefined) + updated.moduleAugmentations = node.moduleAugmentations; + if (node.pragmas !== undefined) + updated.pragmas = node.pragmas; + if (node.localJsxFactory !== undefined) + updated.localJsxFactory = node.localJsxFactory; + if (node.localJsxNamespace !== undefined) + updated.localJsxNamespace = node.localJsxNamespace; + return updateNode(updated, node); + } + return node; + } + ts.updateSourceFileNode = updateSourceFileNode; + /** + * Creates a shallow, memberwise clone of a node for mutation. + */ + function getMutableClone(node) { + var clone = getSynthesizedClone(node); + clone.pos = node.pos; + clone.end = node.end; + clone.parent = node.parent; + return clone; + } + ts.getMutableClone = getMutableClone; + // Transformation nodes + /** + * Creates a synthetic statement to act as a placeholder for a not-emitted statement in + * order to preserve comments. + * + * @param original The original statement. + */ + function createNotEmittedStatement(original) { + var node = createSynthesizedNode(307 /* NotEmittedStatement */); + node.original = original; + setTextRange(node, original); + return node; + } + ts.createNotEmittedStatement = createNotEmittedStatement; + /** + * Creates a synthetic element to act as a placeholder for the end of an emitted declaration in + * order to properly emit exports. + */ + /* @internal */ + function createEndOfDeclarationMarker(original) { + var node = createSynthesizedNode(311 /* EndOfDeclarationMarker */); + node.emitNode = {}; + node.original = original; + return node; + } + ts.createEndOfDeclarationMarker = createEndOfDeclarationMarker; + /** + * Creates a synthetic element to act as a placeholder for the beginning of a merged declaration in + * order to properly emit exports. + */ + /* @internal */ + function createMergeDeclarationMarker(original) { + var node = createSynthesizedNode(310 /* MergeDeclarationMarker */); + node.emitNode = {}; + node.original = original; + return node; + } + ts.createMergeDeclarationMarker = createMergeDeclarationMarker; + /** + * Creates a synthetic expression to act as a placeholder for a not-emitted expression in + * order to preserve comments or sourcemap positions. + * + * @param expression The inner expression to emit. + * @param original The original outer expression. + * @param location The location for the expression. Defaults to the positions from "original" if provided. + */ + function createPartiallyEmittedExpression(expression, original) { + var node = createSynthesizedNode(308 /* PartiallyEmittedExpression */); + node.expression = expression; + node.original = original; + setTextRange(node, original); + return node; + } + ts.createPartiallyEmittedExpression = createPartiallyEmittedExpression; + function updatePartiallyEmittedExpression(node, expression) { + if (node.expression !== expression) { + return updateNode(createPartiallyEmittedExpression(expression, node.original), node); + } + return node; + } + ts.updatePartiallyEmittedExpression = updatePartiallyEmittedExpression; + function flattenCommaElements(node) { + if (ts.nodeIsSynthesized(node) && !ts.isParseTreeNode(node) && !node.original && !node.emitNode && !node.id) { + if (node.kind === 309 /* CommaListExpression */) { + return node.elements; + } + if (ts.isBinaryExpression(node) && node.operatorToken.kind === 27 /* CommaToken */) { + return [node.left, node.right]; + } + } + return node; + } + function createCommaList(elements) { + var node = createSynthesizedNode(309 /* CommaListExpression */); + node.elements = createNodeArray(ts.sameFlatMap(elements, flattenCommaElements)); + return node; + } + ts.createCommaList = createCommaList; + function updateCommaList(node, elements) { + return node.elements !== elements + ? updateNode(createCommaList(elements), node) + : node; + } + ts.updateCommaList = updateCommaList; + function createBundle(sourceFiles, prepends) { + if (prepends === void 0) { prepends = ts.emptyArray; } + var node = ts.createNode(280 /* Bundle */); + node.prepends = prepends; + node.sourceFiles = sourceFiles; + return node; + } + ts.createBundle = createBundle; + function createUnparsedSourceFile(text, mapPath, map) { + var node = ts.createNode(281 /* UnparsedSource */); + node.text = text; + node.sourceMapPath = mapPath; + node.sourceMapText = map; + return node; + } + ts.createUnparsedSourceFile = createUnparsedSourceFile; + function createInputFiles(javascript, declaration, javascriptMapPath, javascriptMapText, declarationMapPath, declarationMapText) { + var node = ts.createNode(282 /* InputFiles */); + node.javascriptText = javascript; + node.javascriptMapPath = javascriptMapPath; + node.javascriptMapText = javascriptMapText; + node.declarationText = declaration; + node.declarationMapPath = declarationMapPath; + node.declarationMapText = declarationMapText; + return node; + } + ts.createInputFiles = createInputFiles; + function updateBundle(node, sourceFiles, prepends) { + if (prepends === void 0) { prepends = ts.emptyArray; } + if (node.sourceFiles !== sourceFiles || node.prepends !== prepends) { + return createBundle(sourceFiles, prepends); + } + return node; + } + ts.updateBundle = updateBundle; + function createImmediatelyInvokedFunctionExpression(statements, param, paramValue) { + return createCall(createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, + /*parameters*/ param ? [param] : [], + /*type*/ undefined, createBlock(statements, /*multiLine*/ true)), + /*typeArguments*/ undefined, + /*argumentsArray*/ paramValue ? [paramValue] : []); + } + ts.createImmediatelyInvokedFunctionExpression = createImmediatelyInvokedFunctionExpression; + function createImmediatelyInvokedArrowFunction(statements, param, paramValue) { + return createCall(createArrowFunction( + /*modifiers*/ undefined, + /*typeParameters*/ undefined, + /*parameters*/ param ? [param] : [], + /*type*/ undefined, + /*equalsGreaterThanToken*/ undefined, createBlock(statements, /*multiLine*/ true)), + /*typeArguments*/ undefined, + /*argumentsArray*/ paramValue ? [paramValue] : []); + } + ts.createImmediatelyInvokedArrowFunction = createImmediatelyInvokedArrowFunction; + function createComma(left, right) { + return createBinary(left, 27 /* CommaToken */, right); + } + ts.createComma = createComma; + function createLessThan(left, right) { + return createBinary(left, 28 /* LessThanToken */, right); + } + ts.createLessThan = createLessThan; + function createAssignment(left, right) { + return createBinary(left, 59 /* EqualsToken */, right); + } + ts.createAssignment = createAssignment; + function createStrictEquality(left, right) { + return createBinary(left, 35 /* EqualsEqualsEqualsToken */, right); + } + ts.createStrictEquality = createStrictEquality; + function createStrictInequality(left, right) { + return createBinary(left, 36 /* ExclamationEqualsEqualsToken */, right); + } + ts.createStrictInequality = createStrictInequality; + function createAdd(left, right) { + return createBinary(left, 38 /* PlusToken */, right); + } + ts.createAdd = createAdd; + function createSubtract(left, right) { + return createBinary(left, 39 /* MinusToken */, right); + } + ts.createSubtract = createSubtract; + function createPostfixIncrement(operand) { + return createPostfix(operand, 44 /* PlusPlusToken */); + } + ts.createPostfixIncrement = createPostfixIncrement; + function createLogicalAnd(left, right) { + return createBinary(left, 54 /* AmpersandAmpersandToken */, right); + } + ts.createLogicalAnd = createLogicalAnd; + function createLogicalOr(left, right) { + return createBinary(left, 55 /* BarBarToken */, right); + } + ts.createLogicalOr = createLogicalOr; + function createLogicalNot(operand) { + return createPrefix(52 /* ExclamationToken */, operand); + } + ts.createLogicalNot = createLogicalNot; + function createVoidZero() { + return createVoid(createLiteral(0)); + } + ts.createVoidZero = createVoidZero; + function createExportDefault(expression) { + return createExportAssignment(/*decorators*/ undefined, /*modifiers*/ undefined, /*isExportEquals*/ false, expression); + } + ts.createExportDefault = createExportDefault; + function createExternalModuleExport(exportName) { + return createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, createNamedExports([createExportSpecifier(/*propertyName*/ undefined, exportName)])); + } + ts.createExternalModuleExport = createExternalModuleExport; + // Utilities + function asName(name) { + return ts.isString(name) ? createIdentifier(name) : name; + } + function asExpression(value) { + return ts.isString(value) || typeof value === "number" ? createLiteral(value) : value; + } + function asNodeArray(array) { + return array ? createNodeArray(array) : undefined; + } + function asToken(value) { + return typeof value === "number" ? createToken(value) : value; + } + /** + * Clears any EmitNode entries from parse-tree nodes. + * @param sourceFile A source file. + */ + function disposeEmitNodes(sourceFile) { + // During transformation we may need to annotate a parse tree node with transient + // transformation properties. As parse tree nodes live longer than transformation + // nodes, we need to make sure we reclaim any memory allocated for custom ranges + // from these nodes to ensure we do not hold onto entire subtrees just for position + // information. We also need to reset these nodes to a pre-transformation state + // for incremental parsing scenarios so that we do not impact later emit. + sourceFile = ts.getSourceFileOfNode(ts.getParseTreeNode(sourceFile)); + var emitNode = sourceFile && sourceFile.emitNode; + var annotatedNodes = emitNode && emitNode.annotatedNodes; + if (annotatedNodes) { + for (var _i = 0, annotatedNodes_1 = annotatedNodes; _i < annotatedNodes_1.length; _i++) { + var node = annotatedNodes_1[_i]; + node.emitNode = undefined; + } + } + } + ts.disposeEmitNodes = disposeEmitNodes; + /** + * Associates a node with the current transformation, initializing + * various transient transformation properties. + */ + /* @internal */ + function getOrCreateEmitNode(node) { + if (!node.emitNode) { + if (ts.isParseTreeNode(node)) { + // To avoid holding onto transformation artifacts, we keep track of any + // parse tree node we are annotating. This allows us to clean them up after + // all transformations have completed. + if (node.kind === 279 /* SourceFile */) { + return node.emitNode = { annotatedNodes: [node] }; + } + var sourceFile = ts.getSourceFileOfNode(node); + getOrCreateEmitNode(sourceFile).annotatedNodes.push(node); + } + node.emitNode = {}; + } + return node.emitNode; + } + ts.getOrCreateEmitNode = getOrCreateEmitNode; + function setTextRange(range, location) { + if (location) { + range.pos = location.pos; + range.end = location.end; + } + return range; + } + ts.setTextRange = setTextRange; + /** + * Sets flags that control emit behavior of a node. + */ + function setEmitFlags(node, emitFlags) { + getOrCreateEmitNode(node).flags = emitFlags; + return node; + } + ts.setEmitFlags = setEmitFlags; + /** + * Sets flags that control emit behavior of a node. + */ + /* @internal */ + function addEmitFlags(node, emitFlags) { + var emitNode = getOrCreateEmitNode(node); + emitNode.flags = emitNode.flags | emitFlags; + return node; + } + ts.addEmitFlags = addEmitFlags; + /** + * Gets a custom text range to use when emitting source maps. + */ + function getSourceMapRange(node) { + var emitNode = node.emitNode; + return (emitNode && emitNode.sourceMapRange) || node; + } + ts.getSourceMapRange = getSourceMapRange; + /** + * Sets a custom text range to use when emitting source maps. + */ + function setSourceMapRange(node, range) { + getOrCreateEmitNode(node).sourceMapRange = range; + return node; + } + ts.setSourceMapRange = setSourceMapRange; + // tslint:disable-next-line variable-name + var SourceMapSource; + /** + * Create an external source map source file reference + */ + function createSourceMapSource(fileName, text, skipTrivia) { + return new (SourceMapSource || (SourceMapSource = ts.objectAllocator.getSourceMapSourceConstructor()))(fileName, text, skipTrivia); + } + ts.createSourceMapSource = createSourceMapSource; + /** + * Gets the TextRange to use for source maps for a token of a node. + */ + function getTokenSourceMapRange(node, token) { + var emitNode = node.emitNode; + var tokenSourceMapRanges = emitNode && emitNode.tokenSourceMapRanges; + return tokenSourceMapRanges && tokenSourceMapRanges[token]; + } + ts.getTokenSourceMapRange = getTokenSourceMapRange; + /** + * Sets the TextRange to use for source maps for a token of a node. + */ + function setTokenSourceMapRange(node, token, range) { + var emitNode = getOrCreateEmitNode(node); + var tokenSourceMapRanges = emitNode.tokenSourceMapRanges || (emitNode.tokenSourceMapRanges = []); + tokenSourceMapRanges[token] = range; + return node; + } + ts.setTokenSourceMapRange = setTokenSourceMapRange; + /** + * Gets a custom text range to use when emitting comments. + */ + /*@internal*/ + function getStartsOnNewLine(node) { + var emitNode = node.emitNode; + return emitNode && emitNode.startsOnNewLine; + } + ts.getStartsOnNewLine = getStartsOnNewLine; + /** + * Sets a custom text range to use when emitting comments. + */ + /*@internal*/ + function setStartsOnNewLine(node, newLine) { + getOrCreateEmitNode(node).startsOnNewLine = newLine; + return node; + } + ts.setStartsOnNewLine = setStartsOnNewLine; + /** + * Gets a custom text range to use when emitting comments. + */ + function getCommentRange(node) { + var emitNode = node.emitNode; + return (emitNode && emitNode.commentRange) || node; + } + ts.getCommentRange = getCommentRange; + /** + * Sets a custom text range to use when emitting comments. + */ + function setCommentRange(node, range) { + getOrCreateEmitNode(node).commentRange = range; + return node; + } + ts.setCommentRange = setCommentRange; + function getSyntheticLeadingComments(node) { + var emitNode = node.emitNode; + return emitNode && emitNode.leadingComments; + } + ts.getSyntheticLeadingComments = getSyntheticLeadingComments; + function setSyntheticLeadingComments(node, comments) { + getOrCreateEmitNode(node).leadingComments = comments; + return node; + } + ts.setSyntheticLeadingComments = setSyntheticLeadingComments; + function addSyntheticLeadingComment(node, kind, text, hasTrailingNewLine) { + return setSyntheticLeadingComments(node, ts.append(getSyntheticLeadingComments(node), { kind: kind, pos: -1, end: -1, hasTrailingNewLine: hasTrailingNewLine, text: text })); + } + ts.addSyntheticLeadingComment = addSyntheticLeadingComment; + function getSyntheticTrailingComments(node) { + var emitNode = node.emitNode; + return emitNode && emitNode.trailingComments; + } + ts.getSyntheticTrailingComments = getSyntheticTrailingComments; + function setSyntheticTrailingComments(node, comments) { + getOrCreateEmitNode(node).trailingComments = comments; + return node; + } + ts.setSyntheticTrailingComments = setSyntheticTrailingComments; + function addSyntheticTrailingComment(node, kind, text, hasTrailingNewLine) { + return setSyntheticTrailingComments(node, ts.append(getSyntheticTrailingComments(node), { kind: kind, pos: -1, end: -1, hasTrailingNewLine: hasTrailingNewLine, text: text })); + } + ts.addSyntheticTrailingComment = addSyntheticTrailingComment; + function moveSyntheticComments(node, original) { + setSyntheticLeadingComments(node, getSyntheticLeadingComments(original)); + setSyntheticTrailingComments(node, getSyntheticTrailingComments(original)); + var emit = getOrCreateEmitNode(original); + emit.leadingComments = undefined; + emit.trailingComments = undefined; + return node; + } + ts.moveSyntheticComments = moveSyntheticComments; + /** + * Gets the constant value to emit for an expression. + */ + function getConstantValue(node) { + var emitNode = node.emitNode; + return emitNode && emitNode.constantValue; + } + ts.getConstantValue = getConstantValue; + /** + * Sets the constant value to emit for an expression. + */ + function setConstantValue(node, value) { + var emitNode = getOrCreateEmitNode(node); + emitNode.constantValue = value; + return node; + } + ts.setConstantValue = setConstantValue; + /** + * Adds an EmitHelper to a node. + */ + function addEmitHelper(node, helper) { + var emitNode = getOrCreateEmitNode(node); + emitNode.helpers = ts.append(emitNode.helpers, helper); + return node; + } + ts.addEmitHelper = addEmitHelper; + /** + * Add EmitHelpers to a node. + */ + function addEmitHelpers(node, helpers) { + if (ts.some(helpers)) { + var emitNode = getOrCreateEmitNode(node); + for (var _i = 0, helpers_1 = helpers; _i < helpers_1.length; _i++) { + var helper = helpers_1[_i]; + emitNode.helpers = ts.appendIfUnique(emitNode.helpers, helper); + } + } + return node; + } + ts.addEmitHelpers = addEmitHelpers; + /** + * Removes an EmitHelper from a node. + */ + function removeEmitHelper(node, helper) { + var emitNode = node.emitNode; + if (emitNode) { + var helpers = emitNode.helpers; + if (helpers) { + return ts.orderedRemoveItem(helpers, helper); + } + } + return false; + } + ts.removeEmitHelper = removeEmitHelper; + /** + * Gets the EmitHelpers of a node. + */ + function getEmitHelpers(node) { + var emitNode = node.emitNode; + return emitNode && emitNode.helpers; + } + ts.getEmitHelpers = getEmitHelpers; + /** + * Moves matching emit helpers from a source node to a target node. + */ + function moveEmitHelpers(source, target, predicate) { + var sourceEmitNode = source.emitNode; + var sourceEmitHelpers = sourceEmitNode && sourceEmitNode.helpers; + if (!ts.some(sourceEmitHelpers)) + return; + var targetEmitNode = getOrCreateEmitNode(target); + var helpersRemoved = 0; + for (var i = 0; i < sourceEmitHelpers.length; i++) { + var helper = sourceEmitHelpers[i]; + if (predicate(helper)) { + helpersRemoved++; + targetEmitNode.helpers = ts.appendIfUnique(targetEmitNode.helpers, helper); + } + else if (helpersRemoved > 0) { + sourceEmitHelpers[i - helpersRemoved] = helper; + } + } + if (helpersRemoved > 0) { + sourceEmitHelpers.length -= helpersRemoved; + } + } + ts.moveEmitHelpers = moveEmitHelpers; + /* @internal */ + function compareEmitHelpers(x, y) { + if (x === y) + return 0 /* EqualTo */; + if (x.priority === y.priority) + return 0 /* EqualTo */; + if (x.priority === undefined) + return 1 /* GreaterThan */; + if (y.priority === undefined) + return -1 /* LessThan */; + return ts.compareValues(x.priority, y.priority); + } + ts.compareEmitHelpers = compareEmitHelpers; + function setOriginalNode(node, original) { + node.original = original; + if (original) { + var emitNode = original.emitNode; + if (emitNode) + node.emitNode = mergeEmitNode(emitNode, node.emitNode); + } + return node; + } + ts.setOriginalNode = setOriginalNode; + function mergeEmitNode(sourceEmitNode, destEmitNode) { + var flags = sourceEmitNode.flags, leadingComments = sourceEmitNode.leadingComments, trailingComments = sourceEmitNode.trailingComments, commentRange = sourceEmitNode.commentRange, sourceMapRange = sourceEmitNode.sourceMapRange, tokenSourceMapRanges = sourceEmitNode.tokenSourceMapRanges, constantValue = sourceEmitNode.constantValue, helpers = sourceEmitNode.helpers, startsOnNewLine = sourceEmitNode.startsOnNewLine; + if (!destEmitNode) + destEmitNode = {}; + // We are using `.slice()` here in case `destEmitNode.leadingComments` is pushed to later. + if (leadingComments) + destEmitNode.leadingComments = ts.addRange(leadingComments.slice(), destEmitNode.leadingComments); + if (trailingComments) + destEmitNode.trailingComments = ts.addRange(trailingComments.slice(), destEmitNode.trailingComments); + if (flags) + destEmitNode.flags = flags; + if (commentRange) + destEmitNode.commentRange = commentRange; + if (sourceMapRange) + destEmitNode.sourceMapRange = sourceMapRange; + if (tokenSourceMapRanges) + destEmitNode.tokenSourceMapRanges = mergeTokenSourceMapRanges(tokenSourceMapRanges, destEmitNode.tokenSourceMapRanges); + if (constantValue !== undefined) + destEmitNode.constantValue = constantValue; + if (helpers) + destEmitNode.helpers = ts.addRange(destEmitNode.helpers, helpers); + if (startsOnNewLine !== undefined) + destEmitNode.startsOnNewLine = startsOnNewLine; + return destEmitNode; + } + function mergeTokenSourceMapRanges(sourceRanges, destRanges) { + if (!destRanges) + destRanges = []; + for (var key in sourceRanges) { + destRanges[key] = sourceRanges[key]; + } + return destRanges; + } +})(ts || (ts = {})); +/* @internal */ +(function (ts) { + ts.nullTransformationContext = { + enableEmitNotification: ts.noop, + enableSubstitution: ts.noop, + endLexicalEnvironment: function () { return undefined; }, + getCompilerOptions: ts.notImplemented, + getEmitHost: ts.notImplemented, + getEmitResolver: ts.notImplemented, + hoistFunctionDeclaration: ts.noop, + hoistVariableDeclaration: ts.noop, + isEmitNotificationEnabled: ts.notImplemented, + isSubstitutionEnabled: ts.notImplemented, + onEmitNode: ts.noop, + onSubstituteNode: ts.notImplemented, + readEmitHelpers: ts.notImplemented, + requestEmitHelper: ts.noop, + resumeLexicalEnvironment: ts.noop, + startLexicalEnvironment: ts.noop, + suspendLexicalEnvironment: ts.noop, + addDiagnostic: ts.noop, + }; + function createTypeCheck(value, tag) { + return tag === "undefined" + ? ts.createStrictEquality(value, ts.createVoidZero()) + : ts.createStrictEquality(ts.createTypeOf(value), ts.createLiteral(tag)); + } + ts.createTypeCheck = createTypeCheck; + function createMemberAccessForPropertyName(target, memberName, location) { + if (ts.isComputedPropertyName(memberName)) { + return ts.setTextRange(ts.createElementAccess(target, memberName.expression), location); + } + else { + var expression = ts.setTextRange(ts.isIdentifier(memberName) + ? ts.createPropertyAccess(target, memberName) + : ts.createElementAccess(target, memberName), memberName); + ts.getOrCreateEmitNode(expression).flags |= 64 /* NoNestedSourceMaps */; + return expression; + } + } + ts.createMemberAccessForPropertyName = createMemberAccessForPropertyName; + function createFunctionCall(func, thisArg, argumentsList, location) { + return ts.setTextRange(ts.createCall(ts.createPropertyAccess(func, "call"), + /*typeArguments*/ undefined, [ + thisArg + ].concat(argumentsList)), location); + } + ts.createFunctionCall = createFunctionCall; + function createFunctionApply(func, thisArg, argumentsExpression, location) { + return ts.setTextRange(ts.createCall(ts.createPropertyAccess(func, "apply"), + /*typeArguments*/ undefined, [ + thisArg, + argumentsExpression + ]), location); + } + ts.createFunctionApply = createFunctionApply; + function createArraySlice(array, start) { + var argumentsList = []; + if (start !== undefined) { + argumentsList.push(typeof start === "number" ? ts.createLiteral(start) : start); + } + return ts.createCall(ts.createPropertyAccess(array, "slice"), /*typeArguments*/ undefined, argumentsList); + } + ts.createArraySlice = createArraySlice; + function createArrayConcat(array, values) { + return ts.createCall(ts.createPropertyAccess(array, "concat"), + /*typeArguments*/ undefined, values); + } + ts.createArrayConcat = createArrayConcat; + function createMathPow(left, right, location) { + return ts.setTextRange(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Math"), "pow"), + /*typeArguments*/ undefined, [left, right]), location); + } + ts.createMathPow = createMathPow; + function createReactNamespace(reactNamespace, parent) { + // To ensure the emit resolver can properly resolve the namespace, we need to + // treat this identifier as if it were a source tree node by clearing the `Synthesized` + // flag and setting a parent node. + var react = ts.createIdentifier(reactNamespace || "React"); + react.flags &= ~8 /* Synthesized */; + // Set the parent that is in parse tree + // this makes sure that parent chain is intact for checker to traverse complete scope tree + react.parent = ts.getParseTreeNode(parent); + return react; + } + function createJsxFactoryExpressionFromEntityName(jsxFactory, parent) { + if (ts.isQualifiedName(jsxFactory)) { + var left = createJsxFactoryExpressionFromEntityName(jsxFactory.left, parent); + var right = ts.createIdentifier(ts.idText(jsxFactory.right)); + right.escapedText = jsxFactory.right.escapedText; + return ts.createPropertyAccess(left, right); + } + else { + return createReactNamespace(ts.idText(jsxFactory), parent); + } + } + function createJsxFactoryExpression(jsxFactoryEntity, reactNamespace, parent) { + return jsxFactoryEntity ? + createJsxFactoryExpressionFromEntityName(jsxFactoryEntity, parent) : + ts.createPropertyAccess(createReactNamespace(reactNamespace, parent), "createElement"); + } + function createExpressionForJsxElement(jsxFactoryEntity, reactNamespace, tagName, props, children, parentElement, location) { + var argumentsList = [tagName]; + if (props) { + argumentsList.push(props); + } + if (children && children.length > 0) { + if (!props) { + argumentsList.push(ts.createNull()); + } + if (children.length > 1) { + for (var _i = 0, children_1 = children; _i < children_1.length; _i++) { + var child = children_1[_i]; + startOnNewLine(child); + argumentsList.push(child); + } + } + else { + argumentsList.push(children[0]); + } + } + return ts.setTextRange(ts.createCall(createJsxFactoryExpression(jsxFactoryEntity, reactNamespace, parentElement), + /*typeArguments*/ undefined, argumentsList), location); + } + ts.createExpressionForJsxElement = createExpressionForJsxElement; + function createExpressionForJsxFragment(jsxFactoryEntity, reactNamespace, children, parentElement, location) { + var tagName = ts.createPropertyAccess(createReactNamespace(reactNamespace, parentElement), "Fragment"); + var argumentsList = [tagName]; + argumentsList.push(ts.createNull()); + if (children && children.length > 0) { + if (children.length > 1) { + for (var _i = 0, children_2 = children; _i < children_2.length; _i++) { + var child = children_2[_i]; + startOnNewLine(child); + argumentsList.push(child); + } + } + else { + argumentsList.push(children[0]); + } + } + return ts.setTextRange(ts.createCall(createJsxFactoryExpression(jsxFactoryEntity, reactNamespace, parentElement), + /*typeArguments*/ undefined, argumentsList), location); + } + ts.createExpressionForJsxFragment = createExpressionForJsxFragment; + // Helpers + function getHelperName(name) { + return ts.setEmitFlags(ts.createIdentifier(name), 4096 /* HelperName */ | 2 /* AdviseOnEmitNode */); + } + ts.getHelperName = getHelperName; + var valuesHelper = { + name: "typescript:values", + scoped: false, + text: "\n var __values = (this && this.__values) || function (o) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator], i = 0;\n if (m) return m.call(o);\n return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n };" + }; + function createValuesHelper(context, expression, location) { + context.requestEmitHelper(valuesHelper); + return ts.setTextRange(ts.createCall(getHelperName("__values"), + /*typeArguments*/ undefined, [expression]), location); + } + ts.createValuesHelper = createValuesHelper; + var readHelper = { + name: "typescript:read", + scoped: false, + text: "\n var __read = (this && this.__read) || function (o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m) return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n }\n catch (error) { e = { error: error }; }\n finally {\n try {\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\n }\n finally { if (e) throw e.error; }\n }\n return ar;\n };" + }; + function createReadHelper(context, iteratorRecord, count, location) { + context.requestEmitHelper(readHelper); + return ts.setTextRange(ts.createCall(getHelperName("__read"), + /*typeArguments*/ undefined, count !== undefined + ? [iteratorRecord, ts.createLiteral(count)] + : [iteratorRecord]), location); + } + ts.createReadHelper = createReadHelper; + var spreadHelper = { + name: "typescript:spread", + scoped: false, + text: "\n var __spread = (this && this.__spread) || function () {\n for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i]));\n return ar;\n };" + }; + function createSpreadHelper(context, argumentList, location) { + context.requestEmitHelper(readHelper); + context.requestEmitHelper(spreadHelper); + return ts.setTextRange(ts.createCall(getHelperName("__spread"), + /*typeArguments*/ undefined, argumentList), location); + } + ts.createSpreadHelper = createSpreadHelper; + // Utilities + function createForOfBindingStatement(node, boundValue) { + if (ts.isVariableDeclarationList(node)) { + var firstDeclaration = ts.first(node.declarations); + var updatedDeclaration = ts.updateVariableDeclaration(firstDeclaration, firstDeclaration.name, + /*typeNode*/ undefined, boundValue); + return ts.setTextRange(ts.createVariableStatement( + /*modifiers*/ undefined, ts.updateVariableDeclarationList(node, [updatedDeclaration])), + /*location*/ node); + } + else { + var updatedExpression = ts.setTextRange(ts.createAssignment(node, boundValue), /*location*/ node); + return ts.setTextRange(ts.createStatement(updatedExpression), /*location*/ node); + } + } + ts.createForOfBindingStatement = createForOfBindingStatement; + function insertLeadingStatement(dest, source) { + if (ts.isBlock(dest)) { + return ts.updateBlock(dest, ts.setTextRange(ts.createNodeArray([source].concat(dest.statements)), dest.statements)); + } + else { + return ts.createBlock(ts.createNodeArray([dest, source]), /*multiLine*/ true); + } + } + ts.insertLeadingStatement = insertLeadingStatement; + function restoreEnclosingLabel(node, outermostLabeledStatement, afterRestoreLabelCallback) { + if (!outermostLabeledStatement) { + return node; + } + var updated = ts.updateLabel(outermostLabeledStatement, outermostLabeledStatement.label, outermostLabeledStatement.statement.kind === 233 /* LabeledStatement */ + ? restoreEnclosingLabel(node, outermostLabeledStatement.statement) + : node); + if (afterRestoreLabelCallback) { + afterRestoreLabelCallback(outermostLabeledStatement); + } + return updated; + } + ts.restoreEnclosingLabel = restoreEnclosingLabel; + function shouldBeCapturedInTempVariable(node, cacheIdentifiers) { + var target = ts.skipParentheses(node); + switch (target.kind) { + case 72 /* Identifier */: + return cacheIdentifiers; + case 100 /* ThisKeyword */: + case 8 /* NumericLiteral */: + case 9 /* BigIntLiteral */: + case 10 /* StringLiteral */: + return false; + case 187 /* ArrayLiteralExpression */: + var elements = target.elements; + if (elements.length === 0) { + return false; + } + return true; + case 188 /* ObjectLiteralExpression */: + return target.properties.length > 0; + default: + return true; + } + } + function createCallBinding(expression, recordTempVariable, languageVersion, cacheIdentifiers) { + if (cacheIdentifiers === void 0) { cacheIdentifiers = false; } + var callee = skipOuterExpressions(expression, 7 /* All */); + var thisArg; + var target; + if (ts.isSuperProperty(callee)) { + thisArg = ts.createThis(); + target = callee; + } + else if (callee.kind === 98 /* SuperKeyword */) { + thisArg = ts.createThis(); + target = languageVersion < 2 /* ES2015 */ + ? ts.setTextRange(ts.createIdentifier("_super"), callee) + : callee; + } + else if (ts.getEmitFlags(callee) & 4096 /* HelperName */) { + thisArg = ts.createVoidZero(); + target = parenthesizeForAccess(callee); + } + else { + switch (callee.kind) { + case 189 /* PropertyAccessExpression */: { + if (shouldBeCapturedInTempVariable(callee.expression, cacheIdentifiers)) { + // for `a.b()` target is `(_a = a).b` and thisArg is `_a` + thisArg = ts.createTempVariable(recordTempVariable); + target = ts.createPropertyAccess(ts.setTextRange(ts.createAssignment(thisArg, callee.expression), callee.expression), callee.name); + ts.setTextRange(target, callee); + } + else { + thisArg = callee.expression; + target = callee; + } + break; + } + case 190 /* ElementAccessExpression */: { + if (shouldBeCapturedInTempVariable(callee.expression, cacheIdentifiers)) { + // for `a[b]()` target is `(_a = a)[b]` and thisArg is `_a` + thisArg = ts.createTempVariable(recordTempVariable); + target = ts.createElementAccess(ts.setTextRange(ts.createAssignment(thisArg, callee.expression), callee.expression), callee.argumentExpression); + ts.setTextRange(target, callee); + } + else { + thisArg = callee.expression; + target = callee; + } + break; + } + default: { + // for `a()` target is `a` and thisArg is `void 0` + thisArg = ts.createVoidZero(); + target = parenthesizeForAccess(expression); + break; + } + } + } + return { target: target, thisArg: thisArg }; + } + ts.createCallBinding = createCallBinding; + function inlineExpressions(expressions) { + // Avoid deeply nested comma expressions as traversing them during emit can result in "Maximum call + // stack size exceeded" errors. + return expressions.length > 10 + ? ts.createCommaList(expressions) + : ts.reduceLeft(expressions, ts.createComma); + } + ts.inlineExpressions = inlineExpressions; + function createExpressionFromEntityName(node) { + if (ts.isQualifiedName(node)) { + var left = createExpressionFromEntityName(node.left); + var right = ts.getMutableClone(node.right); + return ts.setTextRange(ts.createPropertyAccess(left, right), node); + } + else { + return ts.getMutableClone(node); + } + } + ts.createExpressionFromEntityName = createExpressionFromEntityName; + function createExpressionForPropertyName(memberName) { + if (ts.isIdentifier(memberName)) { + return ts.createLiteral(memberName); + } + else if (ts.isComputedPropertyName(memberName)) { + return ts.getMutableClone(memberName.expression); + } + else { + return ts.getMutableClone(memberName); + } + } + ts.createExpressionForPropertyName = createExpressionForPropertyName; + function createExpressionForObjectLiteralElementLike(node, property, receiver) { + switch (property.kind) { + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + return createExpressionForAccessorDeclaration(node.properties, property, receiver, !!node.multiLine); + case 275 /* PropertyAssignment */: + return createExpressionForPropertyAssignment(property, receiver); + case 276 /* ShorthandPropertyAssignment */: + return createExpressionForShorthandPropertyAssignment(property, receiver); + case 156 /* MethodDeclaration */: + return createExpressionForMethodDeclaration(property, receiver); + } + } + ts.createExpressionForObjectLiteralElementLike = createExpressionForObjectLiteralElementLike; + function createExpressionForAccessorDeclaration(properties, property, receiver, multiLine) { + var _a = ts.getAllAccessorDeclarations(properties, property), firstAccessor = _a.firstAccessor, getAccessor = _a.getAccessor, setAccessor = _a.setAccessor; + if (property === firstAccessor) { + var properties_8 = []; + if (getAccessor) { + var getterFunction = ts.createFunctionExpression(getAccessor.modifiers, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, getAccessor.parameters, + /*type*/ undefined, getAccessor.body // TODO: GH#18217 + ); + ts.setTextRange(getterFunction, getAccessor); + ts.setOriginalNode(getterFunction, getAccessor); + var getter = ts.createPropertyAssignment("get", getterFunction); + properties_8.push(getter); + } + if (setAccessor) { + var setterFunction = ts.createFunctionExpression(setAccessor.modifiers, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, setAccessor.parameters, + /*type*/ undefined, setAccessor.body // TODO: GH#18217 + ); + ts.setTextRange(setterFunction, setAccessor); + ts.setOriginalNode(setterFunction, setAccessor); + var setter = ts.createPropertyAssignment("set", setterFunction); + properties_8.push(setter); + } + properties_8.push(ts.createPropertyAssignment("enumerable", ts.createTrue())); + properties_8.push(ts.createPropertyAssignment("configurable", ts.createTrue())); + var expression = ts.setTextRange(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"), + /*typeArguments*/ undefined, [ + receiver, + createExpressionForPropertyName(property.name), + ts.createObjectLiteral(properties_8, multiLine) + ]), + /*location*/ firstAccessor); + return ts.aggregateTransformFlags(expression); + } + return undefined; + } + function createExpressionForPropertyAssignment(property, receiver) { + return ts.aggregateTransformFlags(ts.setOriginalNode(ts.setTextRange(ts.createAssignment(createMemberAccessForPropertyName(receiver, property.name, /*location*/ property.name), property.initializer), property), property)); + } + function createExpressionForShorthandPropertyAssignment(property, receiver) { + return ts.aggregateTransformFlags(ts.setOriginalNode(ts.setTextRange(ts.createAssignment(createMemberAccessForPropertyName(receiver, property.name, /*location*/ property.name), ts.getSynthesizedClone(property.name)), + /*location*/ property), + /*original*/ property)); + } + function createExpressionForMethodDeclaration(method, receiver) { + return ts.aggregateTransformFlags(ts.setOriginalNode(ts.setTextRange(ts.createAssignment(createMemberAccessForPropertyName(receiver, method.name, /*location*/ method.name), ts.setOriginalNode(ts.setTextRange(ts.createFunctionExpression(method.modifiers, method.asteriskToken, + /*name*/ undefined, + /*typeParameters*/ undefined, method.parameters, + /*type*/ undefined, method.body // TODO: GH#18217 + ), + /*location*/ method), + /*original*/ method)), + /*location*/ method), + /*original*/ method)); + } + /** + * Gets the internal name of a declaration. This is primarily used for declarations that can be + * referred to by name in the body of an ES5 class function body. An internal name will *never* + * be prefixed with an module or namespace export modifier like "exports." when emitted as an + * expression. An internal name will also *never* be renamed due to a collision with a block + * scoped variable. + * + * @param node The declaration. + * @param allowComments A value indicating whether comments may be emitted for the name. + * @param allowSourceMaps A value indicating whether source maps may be emitted for the name. + */ + function getInternalName(node, allowComments, allowSourceMaps) { + return getName(node, allowComments, allowSourceMaps, 16384 /* LocalName */ | 32768 /* InternalName */); + } + ts.getInternalName = getInternalName; + /** + * Gets whether an identifier should only be referred to by its internal name. + */ + function isInternalName(node) { + return (ts.getEmitFlags(node) & 32768 /* InternalName */) !== 0; + } + ts.isInternalName = isInternalName; + /** + * Gets the local name of a declaration. This is primarily used for declarations that can be + * referred to by name in the declaration's immediate scope (classes, enums, namespaces). A + * local name will *never* be prefixed with an module or namespace export modifier like + * "exports." when emitted as an expression. + * + * @param node The declaration. + * @param allowComments A value indicating whether comments may be emitted for the name. + * @param allowSourceMaps A value indicating whether source maps may be emitted for the name. + */ + function getLocalName(node, allowComments, allowSourceMaps) { + return getName(node, allowComments, allowSourceMaps, 16384 /* LocalName */); + } + ts.getLocalName = getLocalName; + /** + * Gets whether an identifier should only be referred to by its local name. + */ + function isLocalName(node) { + return (ts.getEmitFlags(node) & 16384 /* LocalName */) !== 0; + } + ts.isLocalName = isLocalName; + /** + * Gets the export name of a declaration. This is primarily used for declarations that can be + * referred to by name in the declaration's immediate scope (classes, enums, namespaces). An + * export name will *always* be prefixed with an module or namespace export modifier like + * `"exports."` when emitted as an expression if the name points to an exported symbol. + * + * @param node The declaration. + * @param allowComments A value indicating whether comments may be emitted for the name. + * @param allowSourceMaps A value indicating whether source maps may be emitted for the name. + */ + function getExportName(node, allowComments, allowSourceMaps) { + return getName(node, allowComments, allowSourceMaps, 8192 /* ExportName */); + } + ts.getExportName = getExportName; + /** + * Gets whether an identifier should only be referred to by its export representation if the + * name points to an exported symbol. + */ + function isExportName(node) { + return (ts.getEmitFlags(node) & 8192 /* ExportName */) !== 0; + } + ts.isExportName = isExportName; + /** + * Gets the name of a declaration for use in declarations. + * + * @param node The declaration. + * @param allowComments A value indicating whether comments may be emitted for the name. + * @param allowSourceMaps A value indicating whether source maps may be emitted for the name. + */ + function getDeclarationName(node, allowComments, allowSourceMaps) { + return getName(node, allowComments, allowSourceMaps); + } + ts.getDeclarationName = getDeclarationName; + function getName(node, allowComments, allowSourceMaps, emitFlags) { + if (emitFlags === void 0) { emitFlags = 0; } + var nodeName = ts.getNameOfDeclaration(node); + if (nodeName && ts.isIdentifier(nodeName) && !ts.isGeneratedIdentifier(nodeName)) { + var name = ts.getMutableClone(nodeName); + emitFlags |= ts.getEmitFlags(nodeName); + if (!allowSourceMaps) + emitFlags |= 48 /* NoSourceMap */; + if (!allowComments) + emitFlags |= 1536 /* NoComments */; + if (emitFlags) + ts.setEmitFlags(name, emitFlags); + return name; + } + return ts.getGeneratedNameForNode(node); + } + /** + * Gets the exported name of a declaration for use in expressions. + * + * An exported name will *always* be prefixed with an module or namespace export modifier like + * "exports." if the name points to an exported symbol. + * + * @param ns The namespace identifier. + * @param node The declaration. + * @param allowComments A value indicating whether comments may be emitted for the name. + * @param allowSourceMaps A value indicating whether source maps may be emitted for the name. + */ + function getExternalModuleOrNamespaceExportName(ns, node, allowComments, allowSourceMaps) { + if (ns && ts.hasModifier(node, 1 /* Export */)) { + return getNamespaceMemberName(ns, getName(node), allowComments, allowSourceMaps); + } + return getExportName(node, allowComments, allowSourceMaps); + } + ts.getExternalModuleOrNamespaceExportName = getExternalModuleOrNamespaceExportName; + /** + * Gets a namespace-qualified name for use in expressions. + * + * @param ns The namespace identifier. + * @param name The name. + * @param allowComments A value indicating whether comments may be emitted for the name. + * @param allowSourceMaps A value indicating whether source maps may be emitted for the name. + */ + function getNamespaceMemberName(ns, name, allowComments, allowSourceMaps) { + var qualifiedName = ts.createPropertyAccess(ns, ts.nodeIsSynthesized(name) ? name : ts.getSynthesizedClone(name)); + ts.setTextRange(qualifiedName, name); + var emitFlags = 0; + if (!allowSourceMaps) + emitFlags |= 48 /* NoSourceMap */; + if (!allowComments) + emitFlags |= 1536 /* NoComments */; + if (emitFlags) + ts.setEmitFlags(qualifiedName, emitFlags); + return qualifiedName; + } + ts.getNamespaceMemberName = getNamespaceMemberName; + function convertToFunctionBody(node, multiLine) { + return ts.isBlock(node) ? node : ts.setTextRange(ts.createBlock([ts.setTextRange(ts.createReturn(node), node)], multiLine), node); + } + ts.convertToFunctionBody = convertToFunctionBody; + function convertFunctionDeclarationToExpression(node) { + if (!node.body) + return ts.Debug.fail(); + var updated = ts.createFunctionExpression(node.modifiers, node.asteriskToken, node.name, node.typeParameters, node.parameters, node.type, node.body); + ts.setOriginalNode(updated, node); + ts.setTextRange(updated, node); + if (ts.getStartsOnNewLine(node)) { + ts.setStartsOnNewLine(updated, /*newLine*/ true); + } + ts.aggregateTransformFlags(updated); + return updated; + } + ts.convertFunctionDeclarationToExpression = convertFunctionDeclarationToExpression; + function isUseStrictPrologue(node) { + return ts.isStringLiteral(node.expression) && node.expression.text === "use strict"; + } + /** + * Add any necessary prologue-directives into target statement-array. + * The function needs to be called during each transformation step. + * This function needs to be called whenever we transform the statement + * list of a source file, namespace, or function-like body. + * + * @param target: result statements array + * @param source: origin statements array + * @param ensureUseStrict: boolean determining whether the function need to add prologue-directives + * @param visitor: Optional callback used to visit any custom prologue directives. + */ + function addPrologue(target, source, ensureUseStrict, visitor) { + var offset = addStandardPrologue(target, source, ensureUseStrict); + return addCustomPrologue(target, source, offset, visitor); + } + ts.addPrologue = addPrologue; + /** + * Add just the standard (string-expression) prologue-directives into target statement-array. + * The function needs to be called during each transformation step. + * This function needs to be called whenever we transform the statement + * list of a source file, namespace, or function-like body. + */ + function addStandardPrologue(target, source, ensureUseStrict) { + ts.Debug.assert(target.length === 0, "Prologue directives should be at the first statement in the target statements array"); + var foundUseStrict = false; + var statementOffset = 0; + var numStatements = source.length; + while (statementOffset < numStatements) { + var statement = source[statementOffset]; + if (ts.isPrologueDirective(statement)) { + if (isUseStrictPrologue(statement)) { + foundUseStrict = true; + } + target.push(statement); + } + else { + break; + } + statementOffset++; + } + if (ensureUseStrict && !foundUseStrict) { + target.push(startOnNewLine(ts.createStatement(ts.createLiteral("use strict")))); + } + return statementOffset; + } + ts.addStandardPrologue = addStandardPrologue; + function addCustomPrologue(target, source, statementOffset, visitor) { + var numStatements = source.length; + while (statementOffset !== undefined && statementOffset < numStatements) { + var statement = source[statementOffset]; + if (ts.getEmitFlags(statement) & 1048576 /* CustomPrologue */) { + ts.append(target, visitor ? ts.visitNode(statement, visitor, ts.isStatement) : statement); + } + else { + break; + } + statementOffset++; + } + return statementOffset; + } + ts.addCustomPrologue = addCustomPrologue; + function findUseStrictPrologue(statements) { + for (var _i = 0, statements_3 = statements; _i < statements_3.length; _i++) { + var statement = statements_3[_i]; + if (ts.isPrologueDirective(statement)) { + if (isUseStrictPrologue(statement)) { + return statement; + } + } + else { + break; + } + } + return undefined; + } + ts.findUseStrictPrologue = findUseStrictPrologue; + function startsWithUseStrict(statements) { + var firstStatement = ts.firstOrUndefined(statements); + return firstStatement !== undefined + && ts.isPrologueDirective(firstStatement) + && isUseStrictPrologue(firstStatement); + } + ts.startsWithUseStrict = startsWithUseStrict; + /** + * Ensures "use strict" directive is added + * + * @param statements An array of statements + */ + function ensureUseStrict(statements) { + var foundUseStrict = findUseStrictPrologue(statements); + if (!foundUseStrict) { + return ts.setTextRange(ts.createNodeArray([ + startOnNewLine(ts.createStatement(ts.createLiteral("use strict"))) + ].concat(statements)), statements); + } + return statements; + } + ts.ensureUseStrict = ensureUseStrict; + /** + * Wraps the operand to a BinaryExpression in parentheses if they are needed to preserve the intended + * order of operations. + * + * @param binaryOperator The operator for the BinaryExpression. + * @param operand The operand for the BinaryExpression. + * @param isLeftSideOfBinary A value indicating whether the operand is the left side of the + * BinaryExpression. + */ + function parenthesizeBinaryOperand(binaryOperator, operand, isLeftSideOfBinary, leftOperand) { + var skipped = ts.skipPartiallyEmittedExpressions(operand); + // If the resulting expression is already parenthesized, we do not need to do any further processing. + if (skipped.kind === 195 /* ParenthesizedExpression */) { + return operand; + } + return binaryOperandNeedsParentheses(binaryOperator, operand, isLeftSideOfBinary, leftOperand) + ? ts.createParen(operand) + : operand; + } + ts.parenthesizeBinaryOperand = parenthesizeBinaryOperand; + /** + * Determines whether the operand to a BinaryExpression needs to be parenthesized. + * + * @param binaryOperator The operator for the BinaryExpression. + * @param operand The operand for the BinaryExpression. + * @param isLeftSideOfBinary A value indicating whether the operand is the left side of the + * BinaryExpression. + */ + function binaryOperandNeedsParentheses(binaryOperator, operand, isLeftSideOfBinary, leftOperand) { + // If the operand has lower precedence, then it needs to be parenthesized to preserve the + // intent of the expression. For example, if the operand is `a + b` and the operator is + // `*`, then we need to parenthesize the operand to preserve the intended order of + // operations: `(a + b) * x`. + // + // If the operand has higher precedence, then it does not need to be parenthesized. For + // example, if the operand is `a * b` and the operator is `+`, then we do not need to + // parenthesize to preserve the intended order of operations: `a * b + x`. + // + // If the operand has the same precedence, then we need to check the associativity of + // the operator based on whether this is the left or right operand of the expression. + // + // For example, if `a / d` is on the right of operator `*`, we need to parenthesize + // to preserve the intended order of operations: `x * (a / d)` + // + // If `a ** d` is on the left of operator `**`, we need to parenthesize to preserve + // the intended order of operations: `(a ** b) ** c` + var binaryOperatorPrecedence = ts.getOperatorPrecedence(204 /* BinaryExpression */, binaryOperator); + var binaryOperatorAssociativity = ts.getOperatorAssociativity(204 /* BinaryExpression */, binaryOperator); + var emittedOperand = ts.skipPartiallyEmittedExpressions(operand); + if (!isLeftSideOfBinary && operand.kind === 197 /* ArrowFunction */ && binaryOperatorPrecedence > 4) { + // We need to parenthesize arrow functions on the right side to avoid it being + // parsed as parenthesized expression: `a && (() => {})` + return true; + } + var operandPrecedence = ts.getExpressionPrecedence(emittedOperand); + switch (ts.compareValues(operandPrecedence, binaryOperatorPrecedence)) { + case -1 /* LessThan */: + // If the operand is the right side of a right-associative binary operation + // and is a yield expression, then we do not need parentheses. + if (!isLeftSideOfBinary + && binaryOperatorAssociativity === 1 /* Right */ + && operand.kind === 207 /* YieldExpression */) { + return false; + } + return true; + case 1 /* GreaterThan */: + return false; + case 0 /* EqualTo */: + if (isLeftSideOfBinary) { + // No need to parenthesize the left operand when the binary operator is + // left associative: + // (a*b)/x -> a*b/x + // (a**b)/x -> a**b/x + // + // Parentheses are needed for the left operand when the binary operator is + // right associative: + // (a/b)**x -> (a/b)**x + // (a**b)**x -> (a**b)**x + return binaryOperatorAssociativity === 1 /* Right */; + } + else { + if (ts.isBinaryExpression(emittedOperand) + && emittedOperand.operatorToken.kind === binaryOperator) { + // No need to parenthesize the right operand when the binary operator and + // operand are the same and one of the following: + // x*(a*b) => x*a*b + // x|(a|b) => x|a|b + // x&(a&b) => x&a&b + // x^(a^b) => x^a^b + if (operatorHasAssociativeProperty(binaryOperator)) { + return false; + } + // No need to parenthesize the right operand when the binary operator + // is plus (+) if both the left and right operands consist solely of either + // literals of the same kind or binary plus (+) expressions for literals of + // the same kind (recursively). + // "a"+(1+2) => "a"+(1+2) + // "a"+("b"+"c") => "a"+"b"+"c" + if (binaryOperator === 38 /* PlusToken */) { + var leftKind = leftOperand ? getLiteralKindOfBinaryPlusOperand(leftOperand) : 0 /* Unknown */; + if (ts.isLiteralKind(leftKind) && leftKind === getLiteralKindOfBinaryPlusOperand(emittedOperand)) { + return false; + } + } + } + // No need to parenthesize the right operand when the operand is right + // associative: + // x/(a**b) -> x/a**b + // x**(a**b) -> x**a**b + // + // Parentheses are needed for the right operand when the operand is left + // associative: + // x/(a*b) -> x/(a*b) + // x**(a/b) -> x**(a/b) + var operandAssociativity = ts.getExpressionAssociativity(emittedOperand); + return operandAssociativity === 0 /* Left */; + } + } + } + /** + * Determines whether a binary operator is mathematically associative. + * + * @param binaryOperator The binary operator. + */ + function operatorHasAssociativeProperty(binaryOperator) { + // The following operators are associative in JavaScript: + // (a*b)*c -> a*(b*c) -> a*b*c + // (a|b)|c -> a|(b|c) -> a|b|c + // (a&b)&c -> a&(b&c) -> a&b&c + // (a^b)^c -> a^(b^c) -> a^b^c + // + // While addition is associative in mathematics, JavaScript's `+` is not + // guaranteed to be associative as it is overloaded with string concatenation. + return binaryOperator === 40 /* AsteriskToken */ + || binaryOperator === 50 /* BarToken */ + || binaryOperator === 49 /* AmpersandToken */ + || binaryOperator === 51 /* CaretToken */; + } + /** + * This function determines whether an expression consists of a homogeneous set of + * literal expressions or binary plus expressions that all share the same literal kind. + * It is used to determine whether the right-hand operand of a binary plus expression can be + * emitted without parentheses. + */ + function getLiteralKindOfBinaryPlusOperand(node) { + node = ts.skipPartiallyEmittedExpressions(node); + if (ts.isLiteralKind(node.kind)) { + return node.kind; + } + if (node.kind === 204 /* BinaryExpression */ && node.operatorToken.kind === 38 /* PlusToken */) { + if (node.cachedLiteralKind !== undefined) { + return node.cachedLiteralKind; + } + var leftKind = getLiteralKindOfBinaryPlusOperand(node.left); + var literalKind = ts.isLiteralKind(leftKind) + && leftKind === getLiteralKindOfBinaryPlusOperand(node.right) + ? leftKind + : 0 /* Unknown */; + node.cachedLiteralKind = literalKind; + return literalKind; + } + return 0 /* Unknown */; + } + function parenthesizeForConditionalHead(condition) { + var conditionalPrecedence = ts.getOperatorPrecedence(205 /* ConditionalExpression */, 56 /* QuestionToken */); + var emittedCondition = ts.skipPartiallyEmittedExpressions(condition); + var conditionPrecedence = ts.getExpressionPrecedence(emittedCondition); + if (ts.compareValues(conditionPrecedence, conditionalPrecedence) === -1 /* LessThan */) { + return ts.createParen(condition); + } + return condition; + } + ts.parenthesizeForConditionalHead = parenthesizeForConditionalHead; + function parenthesizeSubexpressionOfConditionalExpression(e) { + // per ES grammar both 'whenTrue' and 'whenFalse' parts of conditional expression are assignment expressions + // so in case when comma expression is introduced as a part of previous transformations + // if should be wrapped in parens since comma operator has the lowest precedence + var emittedExpression = ts.skipPartiallyEmittedExpressions(e); + return isCommaSequence(emittedExpression) + ? ts.createParen(e) + : e; + } + ts.parenthesizeSubexpressionOfConditionalExpression = parenthesizeSubexpressionOfConditionalExpression; + /** + * [Per the spec](https://tc39.github.io/ecma262/#prod-ExportDeclaration), `export default` accepts _AssigmentExpression_ but + * has a lookahead restriction for `function`, `async function`, and `class`. + * + * Basically, that means we need to parenthesize in the following cases: + * + * - BinaryExpression of CommaToken + * - CommaList (synthetic list of multiple comma expressions) + * - FunctionExpression + * - ClassExpression + */ + function parenthesizeDefaultExpression(e) { + var check = ts.skipPartiallyEmittedExpressions(e); + var needsParens = isCommaSequence(check); + if (!needsParens) { + switch (getLeftmostExpression(check, /*stopAtCallExpression*/ false).kind) { + case 209 /* ClassExpression */: + case 196 /* FunctionExpression */: + needsParens = true; + } + } + return needsParens ? ts.createParen(e) : e; + } + ts.parenthesizeDefaultExpression = parenthesizeDefaultExpression; + /** + * Wraps an expression in parentheses if it is needed in order to use the expression + * as the expression of a NewExpression node. + * + * @param expression The Expression node. + */ + function parenthesizeForNew(expression) { + var leftmostExpr = getLeftmostExpression(expression, /*stopAtCallExpressions*/ true); + switch (leftmostExpr.kind) { + case 191 /* CallExpression */: + return ts.createParen(expression); + case 192 /* NewExpression */: + return !leftmostExpr.arguments + ? ts.createParen(expression) + : expression; + } + return parenthesizeForAccess(expression); + } + ts.parenthesizeForNew = parenthesizeForNew; + /** + * Wraps an expression in parentheses if it is needed in order to use the expression for + * property or element access. + * + * @param expr The expression node. + */ + function parenthesizeForAccess(expression) { + // isLeftHandSideExpression is almost the correct criterion for when it is not necessary + // to parenthesize the expression before a dot. The known exception is: + // + // NewExpression: + // new C.x -> not the same as (new C).x + // + var emittedExpression = ts.skipPartiallyEmittedExpressions(expression); + if (ts.isLeftHandSideExpression(emittedExpression) + && (emittedExpression.kind !== 192 /* NewExpression */ || emittedExpression.arguments)) { + return expression; + } + return ts.setTextRange(ts.createParen(expression), expression); + } + ts.parenthesizeForAccess = parenthesizeForAccess; + function parenthesizePostfixOperand(operand) { + return ts.isLeftHandSideExpression(operand) + ? operand + : ts.setTextRange(ts.createParen(operand), operand); + } + ts.parenthesizePostfixOperand = parenthesizePostfixOperand; + function parenthesizePrefixOperand(operand) { + return ts.isUnaryExpression(operand) + ? operand + : ts.setTextRange(ts.createParen(operand), operand); + } + ts.parenthesizePrefixOperand = parenthesizePrefixOperand; + function parenthesizeListElements(elements) { + var result; + for (var i = 0; i < elements.length; i++) { + var element = parenthesizeExpressionForList(elements[i]); + if (result !== undefined || element !== elements[i]) { + if (result === undefined) { + result = elements.slice(0, i); + } + result.push(element); + } + } + if (result !== undefined) { + return ts.setTextRange(ts.createNodeArray(result, elements.hasTrailingComma), elements); + } + return elements; + } + ts.parenthesizeListElements = parenthesizeListElements; + function parenthesizeExpressionForList(expression) { + var emittedExpression = ts.skipPartiallyEmittedExpressions(expression); + var expressionPrecedence = ts.getExpressionPrecedence(emittedExpression); + var commaPrecedence = ts.getOperatorPrecedence(204 /* BinaryExpression */, 27 /* CommaToken */); + return expressionPrecedence > commaPrecedence + ? expression + : ts.setTextRange(ts.createParen(expression), expression); + } + ts.parenthesizeExpressionForList = parenthesizeExpressionForList; + function parenthesizeExpressionForExpressionStatement(expression) { + var emittedExpression = ts.skipPartiallyEmittedExpressions(expression); + if (ts.isCallExpression(emittedExpression)) { + var callee = emittedExpression.expression; + var kind = ts.skipPartiallyEmittedExpressions(callee).kind; + if (kind === 196 /* FunctionExpression */ || kind === 197 /* ArrowFunction */) { + var mutableCall = ts.getMutableClone(emittedExpression); + mutableCall.expression = ts.setTextRange(ts.createParen(callee), callee); + return recreateOuterExpressions(expression, mutableCall, 4 /* PartiallyEmittedExpressions */); + } + } + var leftmostExpressionKind = getLeftmostExpression(emittedExpression, /*stopAtCallExpressions*/ false).kind; + if (leftmostExpressionKind === 188 /* ObjectLiteralExpression */ || leftmostExpressionKind === 196 /* FunctionExpression */) { + return ts.setTextRange(ts.createParen(expression), expression); + } + return expression; + } + ts.parenthesizeExpressionForExpressionStatement = parenthesizeExpressionForExpressionStatement; + function parenthesizeConditionalTypeMember(member) { + return member.kind === 175 /* ConditionalType */ ? ts.createParenthesizedType(member) : member; + } + ts.parenthesizeConditionalTypeMember = parenthesizeConditionalTypeMember; + function parenthesizeElementTypeMember(member) { + switch (member.kind) { + case 173 /* UnionType */: + case 174 /* IntersectionType */: + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + return ts.createParenthesizedType(member); + } + return parenthesizeConditionalTypeMember(member); + } + ts.parenthesizeElementTypeMember = parenthesizeElementTypeMember; + function parenthesizeArrayTypeMember(member) { + switch (member.kind) { + case 167 /* TypeQuery */: + case 179 /* TypeOperator */: + case 176 /* InferType */: + return ts.createParenthesizedType(member); + } + return parenthesizeElementTypeMember(member); + } + ts.parenthesizeArrayTypeMember = parenthesizeArrayTypeMember; + function parenthesizeElementTypeMembers(members) { + return ts.createNodeArray(ts.sameMap(members, parenthesizeElementTypeMember)); + } + ts.parenthesizeElementTypeMembers = parenthesizeElementTypeMembers; + function parenthesizeTypeParameters(typeParameters) { + if (ts.some(typeParameters)) { + var params = []; + for (var i = 0; i < typeParameters.length; ++i) { + var entry = typeParameters[i]; + params.push(i === 0 && ts.isFunctionOrConstructorTypeNode(entry) && entry.typeParameters ? + ts.createParenthesizedType(entry) : + entry); + } + return ts.createNodeArray(params); + } + } + ts.parenthesizeTypeParameters = parenthesizeTypeParameters; + function getLeftmostExpression(node, stopAtCallExpressions) { + while (true) { + switch (node.kind) { + case 203 /* PostfixUnaryExpression */: + node = node.operand; + continue; + case 204 /* BinaryExpression */: + node = node.left; + continue; + case 205 /* ConditionalExpression */: + node = node.condition; + continue; + case 193 /* TaggedTemplateExpression */: + node = node.tag; + continue; + case 191 /* CallExpression */: + if (stopAtCallExpressions) { + return node; + } + // falls through + case 212 /* AsExpression */: + case 190 /* ElementAccessExpression */: + case 189 /* PropertyAccessExpression */: + case 213 /* NonNullExpression */: + case 308 /* PartiallyEmittedExpression */: + node = node.expression; + continue; + } + return node; + } + } + function parenthesizeConciseBody(body) { + if (!ts.isBlock(body) && (isCommaSequence(body) || getLeftmostExpression(body, /*stopAtCallExpressions*/ false).kind === 188 /* ObjectLiteralExpression */)) { + return ts.setTextRange(ts.createParen(body), body); + } + return body; + } + ts.parenthesizeConciseBody = parenthesizeConciseBody; + function isCommaSequence(node) { + return node.kind === 204 /* BinaryExpression */ && node.operatorToken.kind === 27 /* CommaToken */ || + node.kind === 309 /* CommaListExpression */; + } + ts.isCommaSequence = isCommaSequence; + var OuterExpressionKinds; + (function (OuterExpressionKinds) { + OuterExpressionKinds[OuterExpressionKinds["Parentheses"] = 1] = "Parentheses"; + OuterExpressionKinds[OuterExpressionKinds["Assertions"] = 2] = "Assertions"; + OuterExpressionKinds[OuterExpressionKinds["PartiallyEmittedExpressions"] = 4] = "PartiallyEmittedExpressions"; + OuterExpressionKinds[OuterExpressionKinds["All"] = 7] = "All"; + })(OuterExpressionKinds = ts.OuterExpressionKinds || (ts.OuterExpressionKinds = {})); + function isOuterExpression(node, kinds) { + if (kinds === void 0) { kinds = 7 /* All */; } + switch (node.kind) { + case 195 /* ParenthesizedExpression */: + return (kinds & 1 /* Parentheses */) !== 0; + case 194 /* TypeAssertionExpression */: + case 212 /* AsExpression */: + case 213 /* NonNullExpression */: + return (kinds & 2 /* Assertions */) !== 0; + case 308 /* PartiallyEmittedExpression */: + return (kinds & 4 /* PartiallyEmittedExpressions */) !== 0; + } + return false; + } + ts.isOuterExpression = isOuterExpression; + function skipOuterExpressions(node, kinds) { + if (kinds === void 0) { kinds = 7 /* All */; } + var previousNode; + do { + previousNode = node; + if (kinds & 1 /* Parentheses */) { + node = ts.skipParentheses(node); + } + if (kinds & 2 /* Assertions */) { + node = skipAssertions(node); + } + if (kinds & 4 /* PartiallyEmittedExpressions */) { + node = ts.skipPartiallyEmittedExpressions(node); + } + } while (previousNode !== node); + return node; + } + ts.skipOuterExpressions = skipOuterExpressions; + function skipAssertions(node) { + while (ts.isAssertionExpression(node) || node.kind === 213 /* NonNullExpression */) { + node = node.expression; + } + return node; + } + ts.skipAssertions = skipAssertions; + function updateOuterExpression(outerExpression, expression) { + switch (outerExpression.kind) { + case 195 /* ParenthesizedExpression */: return ts.updateParen(outerExpression, expression); + case 194 /* TypeAssertionExpression */: return ts.updateTypeAssertion(outerExpression, outerExpression.type, expression); + case 212 /* AsExpression */: return ts.updateAsExpression(outerExpression, expression, outerExpression.type); + case 213 /* NonNullExpression */: return ts.updateNonNullExpression(outerExpression, expression); + case 308 /* PartiallyEmittedExpression */: return ts.updatePartiallyEmittedExpression(outerExpression, expression); + } + } + /** + * Determines whether a node is a parenthesized expression that can be ignored when recreating outer expressions. + * + * A parenthesized expression can be ignored when all of the following are true: + * + * - It's `pos` and `end` are not -1 + * - It does not have a custom source map range + * - It does not have a custom comment range + * - It does not have synthetic leading or trailing comments + * + * If an outermost parenthesized expression is ignored, but the containing expression requires a parentheses around + * the expression to maintain precedence, a new parenthesized expression should be created automatically when + * the containing expression is created/updated. + */ + function isIgnorableParen(node) { + return node.kind === 195 /* ParenthesizedExpression */ + && ts.nodeIsSynthesized(node) + && ts.nodeIsSynthesized(ts.getSourceMapRange(node)) + && ts.nodeIsSynthesized(ts.getCommentRange(node)) + && !ts.some(ts.getSyntheticLeadingComments(node)) + && !ts.some(ts.getSyntheticTrailingComments(node)); + } + function recreateOuterExpressions(outerExpression, innerExpression, kinds) { + if (kinds === void 0) { kinds = 7 /* All */; } + if (outerExpression && isOuterExpression(outerExpression, kinds) && !isIgnorableParen(outerExpression)) { + return updateOuterExpression(outerExpression, recreateOuterExpressions(outerExpression.expression, innerExpression)); + } + return innerExpression; + } + ts.recreateOuterExpressions = recreateOuterExpressions; + function startOnNewLine(node) { + return ts.setStartsOnNewLine(node, /*newLine*/ true); + } + ts.startOnNewLine = startOnNewLine; + function getExternalHelpersModuleName(node) { + var parseNode = ts.getOriginalNode(node, ts.isSourceFile); + var emitNode = parseNode && parseNode.emitNode; + return emitNode && emitNode.externalHelpersModuleName; + } + ts.getExternalHelpersModuleName = getExternalHelpersModuleName; + function getOrCreateExternalHelpersModuleNameIfNeeded(node, compilerOptions, hasExportStarsToExportValues, hasImportStarOrImportDefault) { + if (compilerOptions.importHelpers && ts.isEffectiveExternalModule(node, compilerOptions)) { + var externalHelpersModuleName = getExternalHelpersModuleName(node); + if (externalHelpersModuleName) { + return externalHelpersModuleName; + } + var moduleKind = ts.getEmitModuleKind(compilerOptions); + var create = (hasExportStarsToExportValues || (compilerOptions.esModuleInterop && hasImportStarOrImportDefault)) + && moduleKind !== ts.ModuleKind.System + && moduleKind !== ts.ModuleKind.ES2015 + && moduleKind !== ts.ModuleKind.ESNext; + if (!create) { + var helpers = ts.getEmitHelpers(node); + if (helpers) { + for (var _i = 0, helpers_2 = helpers; _i < helpers_2.length; _i++) { + var helper = helpers_2[_i]; + if (!helper.scoped) { + create = true; + break; + } + } + } + } + if (create) { + var parseNode = ts.getOriginalNode(node, ts.isSourceFile); + var emitNode = ts.getOrCreateEmitNode(parseNode); + return emitNode.externalHelpersModuleName || (emitNode.externalHelpersModuleName = ts.createUniqueName(ts.externalHelpersModuleNameText)); + } + } + } + ts.getOrCreateExternalHelpersModuleNameIfNeeded = getOrCreateExternalHelpersModuleNameIfNeeded; + /** + * Get the name of that target module from an import or export declaration + */ + function getLocalNameForExternalImport(node, sourceFile) { + var namespaceDeclaration = ts.getNamespaceDeclarationNode(node); + if (namespaceDeclaration && !ts.isDefaultImport(node)) { + var name = namespaceDeclaration.name; + return ts.isGeneratedIdentifier(name) ? name : ts.createIdentifier(ts.getSourceTextOfNodeFromSourceFile(sourceFile, name) || ts.idText(name)); + } + if (node.kind === 249 /* ImportDeclaration */ && node.importClause) { + return ts.getGeneratedNameForNode(node); + } + if (node.kind === 255 /* ExportDeclaration */ && node.moduleSpecifier) { + return ts.getGeneratedNameForNode(node); + } + return undefined; + } + ts.getLocalNameForExternalImport = getLocalNameForExternalImport; + /** + * Get the name of a target module from an import/export declaration as should be written in the emitted output. + * The emitted output name can be different from the input if: + * 1. The module has a /// + * 2. --out or --outFile is used, making the name relative to the rootDir + * 3- The containing SourceFile has an entry in renamedDependencies for the import as requested by some module loaders (e.g. System). + * Otherwise, a new StringLiteral node representing the module name will be returned. + */ + function getExternalModuleNameLiteral(importNode, sourceFile, host, resolver, compilerOptions) { + var moduleName = ts.getExternalModuleName(importNode); // TODO: GH#18217 + if (moduleName.kind === 10 /* StringLiteral */) { + return tryGetModuleNameFromDeclaration(importNode, host, resolver, compilerOptions) + || tryRenameExternalModule(moduleName, sourceFile) + || ts.getSynthesizedClone(moduleName); + } + return undefined; + } + ts.getExternalModuleNameLiteral = getExternalModuleNameLiteral; + /** + * Some bundlers (SystemJS builder) sometimes want to rename dependencies. + * Here we check if alternative name was provided for a given moduleName and return it if possible. + */ + function tryRenameExternalModule(moduleName, sourceFile) { + var rename = sourceFile.renamedDependencies && sourceFile.renamedDependencies.get(moduleName.text); + return rename && ts.createLiteral(rename); + } + /** + * Get the name of a module as should be written in the emitted output. + * The emitted output name can be different from the input if: + * 1. The module has a /// + * 2. --out or --outFile is used, making the name relative to the rootDir + * Otherwise, a new StringLiteral node representing the module name will be returned. + */ + function tryGetModuleNameFromFile(file, host, options) { + if (!file) { + return undefined; + } + if (file.moduleName) { + return ts.createLiteral(file.moduleName); + } + if (!file.isDeclarationFile && (options.out || options.outFile)) { + return ts.createLiteral(ts.getExternalModuleNameFromPath(host, file.fileName)); + } + return undefined; + } + ts.tryGetModuleNameFromFile = tryGetModuleNameFromFile; + function tryGetModuleNameFromDeclaration(declaration, host, resolver, compilerOptions) { + return tryGetModuleNameFromFile(resolver.getExternalModuleFileFromDeclaration(declaration), host, compilerOptions); + } + /** + * Gets the initializer of an BindingOrAssignmentElement. + */ + function getInitializerOfBindingOrAssignmentElement(bindingElement) { + if (ts.isDeclarationBindingElement(bindingElement)) { + // `1` in `let { a = 1 } = ...` + // `1` in `let { a: b = 1 } = ...` + // `1` in `let { a: {b} = 1 } = ...` + // `1` in `let { a: [b] = 1 } = ...` + // `1` in `let [a = 1] = ...` + // `1` in `let [{a} = 1] = ...` + // `1` in `let [[a] = 1] = ...` + return bindingElement.initializer; + } + if (ts.isPropertyAssignment(bindingElement)) { + // `1` in `({ a: b = 1 } = ...)` + // `1` in `({ a: {b} = 1 } = ...)` + // `1` in `({ a: [b] = 1 } = ...)` + var initializer = bindingElement.initializer; + return ts.isAssignmentExpression(initializer, /*excludeCompoundAssignment*/ true) + ? initializer.right + : undefined; + } + if (ts.isShorthandPropertyAssignment(bindingElement)) { + // `1` in `({ a = 1 } = ...)` + return bindingElement.objectAssignmentInitializer; + } + if (ts.isAssignmentExpression(bindingElement, /*excludeCompoundAssignment*/ true)) { + // `1` in `[a = 1] = ...` + // `1` in `[{a} = 1] = ...` + // `1` in `[[a] = 1] = ...` + return bindingElement.right; + } + if (ts.isSpreadElement(bindingElement)) { + // Recovery consistent with existing emit. + return getInitializerOfBindingOrAssignmentElement(bindingElement.expression); + } + } + ts.getInitializerOfBindingOrAssignmentElement = getInitializerOfBindingOrAssignmentElement; + /** + * Gets the name of an BindingOrAssignmentElement. + */ + function getTargetOfBindingOrAssignmentElement(bindingElement) { + if (ts.isDeclarationBindingElement(bindingElement)) { + // `a` in `let { a } = ...` + // `a` in `let { a = 1 } = ...` + // `b` in `let { a: b } = ...` + // `b` in `let { a: b = 1 } = ...` + // `a` in `let { ...a } = ...` + // `{b}` in `let { a: {b} } = ...` + // `{b}` in `let { a: {b} = 1 } = ...` + // `[b]` in `let { a: [b] } = ...` + // `[b]` in `let { a: [b] = 1 } = ...` + // `a` in `let [a] = ...` + // `a` in `let [a = 1] = ...` + // `a` in `let [...a] = ...` + // `{a}` in `let [{a}] = ...` + // `{a}` in `let [{a} = 1] = ...` + // `[a]` in `let [[a]] = ...` + // `[a]` in `let [[a] = 1] = ...` + return bindingElement.name; + } + if (ts.isObjectLiteralElementLike(bindingElement)) { + switch (bindingElement.kind) { + case 275 /* PropertyAssignment */: + // `b` in `({ a: b } = ...)` + // `b` in `({ a: b = 1 } = ...)` + // `{b}` in `({ a: {b} } = ...)` + // `{b}` in `({ a: {b} = 1 } = ...)` + // `[b]` in `({ a: [b] } = ...)` + // `[b]` in `({ a: [b] = 1 } = ...)` + // `b.c` in `({ a: b.c } = ...)` + // `b.c` in `({ a: b.c = 1 } = ...)` + // `b[0]` in `({ a: b[0] } = ...)` + // `b[0]` in `({ a: b[0] = 1 } = ...)` + return getTargetOfBindingOrAssignmentElement(bindingElement.initializer); + case 276 /* ShorthandPropertyAssignment */: + // `a` in `({ a } = ...)` + // `a` in `({ a = 1 } = ...)` + return bindingElement.name; + case 277 /* SpreadAssignment */: + // `a` in `({ ...a } = ...)` + return getTargetOfBindingOrAssignmentElement(bindingElement.expression); + } + // no target + return undefined; + } + if (ts.isAssignmentExpression(bindingElement, /*excludeCompoundAssignment*/ true)) { + // `a` in `[a = 1] = ...` + // `{a}` in `[{a} = 1] = ...` + // `[a]` in `[[a] = 1] = ...` + // `a.b` in `[a.b = 1] = ...` + // `a[0]` in `[a[0] = 1] = ...` + return getTargetOfBindingOrAssignmentElement(bindingElement.left); + } + if (ts.isSpreadElement(bindingElement)) { + // `a` in `[...a] = ...` + return getTargetOfBindingOrAssignmentElement(bindingElement.expression); + } + // `a` in `[a] = ...` + // `{a}` in `[{a}] = ...` + // `[a]` in `[[a]] = ...` + // `a.b` in `[a.b] = ...` + // `a[0]` in `[a[0]] = ...` + return bindingElement; + } + ts.getTargetOfBindingOrAssignmentElement = getTargetOfBindingOrAssignmentElement; + /** + * Determines whether an BindingOrAssignmentElement is a rest element. + */ + function getRestIndicatorOfBindingOrAssignmentElement(bindingElement) { + switch (bindingElement.kind) { + case 151 /* Parameter */: + case 186 /* BindingElement */: + // `...` in `let [...a] = ...` + return bindingElement.dotDotDotToken; + case 208 /* SpreadElement */: + case 277 /* SpreadAssignment */: + // `...` in `[...a] = ...` + return bindingElement; + } + return undefined; + } + ts.getRestIndicatorOfBindingOrAssignmentElement = getRestIndicatorOfBindingOrAssignmentElement; + /** + * Gets the property name of a BindingOrAssignmentElement + */ + function getPropertyNameOfBindingOrAssignmentElement(bindingElement) { + switch (bindingElement.kind) { + case 186 /* BindingElement */: + // `a` in `let { a: b } = ...` + // `[a]` in `let { [a]: b } = ...` + // `"a"` in `let { "a": b } = ...` + // `1` in `let { 1: b } = ...` + if (bindingElement.propertyName) { + var propertyName = bindingElement.propertyName; + return ts.isComputedPropertyName(propertyName) && isStringOrNumericLiteral(propertyName.expression) + ? propertyName.expression + : propertyName; + } + break; + case 275 /* PropertyAssignment */: + // `a` in `({ a: b } = ...)` + // `[a]` in `({ [a]: b } = ...)` + // `"a"` in `({ "a": b } = ...)` + // `1` in `({ 1: b } = ...)` + if (bindingElement.name) { + var propertyName = bindingElement.name; + return ts.isComputedPropertyName(propertyName) && isStringOrNumericLiteral(propertyName.expression) + ? propertyName.expression + : propertyName; + } + break; + case 277 /* SpreadAssignment */: + // `a` in `({ ...a } = ...)` + return bindingElement.name; + } + var target = getTargetOfBindingOrAssignmentElement(bindingElement); + if (target && ts.isPropertyName(target)) { + return ts.isComputedPropertyName(target) && isStringOrNumericLiteral(target.expression) + ? target.expression + : target; + } + ts.Debug.fail("Invalid property name for binding element."); + } + ts.getPropertyNameOfBindingOrAssignmentElement = getPropertyNameOfBindingOrAssignmentElement; + function isStringOrNumericLiteral(node) { + var kind = node.kind; + return kind === 10 /* StringLiteral */ + || kind === 8 /* NumericLiteral */; + } + /** + * Gets the elements of a BindingOrAssignmentPattern + */ + function getElementsOfBindingOrAssignmentPattern(name) { + switch (name.kind) { + case 184 /* ObjectBindingPattern */: + case 185 /* ArrayBindingPattern */: + case 187 /* ArrayLiteralExpression */: + // `a` in `{a}` + // `a` in `[a]` + return name.elements; + case 188 /* ObjectLiteralExpression */: + // `a` in `{a}` + return name.properties; + } + } + ts.getElementsOfBindingOrAssignmentPattern = getElementsOfBindingOrAssignmentPattern; + function convertToArrayAssignmentElement(element) { + if (ts.isBindingElement(element)) { + if (element.dotDotDotToken) { + ts.Debug.assertNode(element.name, ts.isIdentifier); + return ts.setOriginalNode(ts.setTextRange(ts.createSpread(element.name), element), element); + } + var expression = convertToAssignmentElementTarget(element.name); + return element.initializer + ? ts.setOriginalNode(ts.setTextRange(ts.createAssignment(expression, element.initializer), element), element) + : expression; + } + ts.Debug.assertNode(element, ts.isExpression); + return element; + } + ts.convertToArrayAssignmentElement = convertToArrayAssignmentElement; + function convertToObjectAssignmentElement(element) { + if (ts.isBindingElement(element)) { + if (element.dotDotDotToken) { + ts.Debug.assertNode(element.name, ts.isIdentifier); + return ts.setOriginalNode(ts.setTextRange(ts.createSpreadAssignment(element.name), element), element); + } + if (element.propertyName) { + var expression = convertToAssignmentElementTarget(element.name); + return ts.setOriginalNode(ts.setTextRange(ts.createPropertyAssignment(element.propertyName, element.initializer ? ts.createAssignment(expression, element.initializer) : expression), element), element); + } + ts.Debug.assertNode(element.name, ts.isIdentifier); + return ts.setOriginalNode(ts.setTextRange(ts.createShorthandPropertyAssignment(element.name, element.initializer), element), element); + } + ts.Debug.assertNode(element, ts.isObjectLiteralElementLike); + return element; + } + ts.convertToObjectAssignmentElement = convertToObjectAssignmentElement; + function convertToAssignmentPattern(node) { + switch (node.kind) { + case 185 /* ArrayBindingPattern */: + case 187 /* ArrayLiteralExpression */: + return convertToArrayAssignmentPattern(node); + case 184 /* ObjectBindingPattern */: + case 188 /* ObjectLiteralExpression */: + return convertToObjectAssignmentPattern(node); + } + } + ts.convertToAssignmentPattern = convertToAssignmentPattern; + function convertToObjectAssignmentPattern(node) { + if (ts.isObjectBindingPattern(node)) { + return ts.setOriginalNode(ts.setTextRange(ts.createObjectLiteral(ts.map(node.elements, convertToObjectAssignmentElement)), node), node); + } + ts.Debug.assertNode(node, ts.isObjectLiteralExpression); + return node; + } + ts.convertToObjectAssignmentPattern = convertToObjectAssignmentPattern; + function convertToArrayAssignmentPattern(node) { + if (ts.isArrayBindingPattern(node)) { + return ts.setOriginalNode(ts.setTextRange(ts.createArrayLiteral(ts.map(node.elements, convertToArrayAssignmentElement)), node), node); + } + ts.Debug.assertNode(node, ts.isArrayLiteralExpression); + return node; + } + ts.convertToArrayAssignmentPattern = convertToArrayAssignmentPattern; + function convertToAssignmentElementTarget(node) { + if (ts.isBindingPattern(node)) { + return convertToAssignmentPattern(node); + } + ts.Debug.assertNode(node, ts.isExpression); + return node; + } + ts.convertToAssignmentElementTarget = convertToAssignmentElementTarget; +})(ts || (ts = {})); +var ts; +(function (ts) { + var isTypeNodeOrTypeParameterDeclaration = ts.or(ts.isTypeNode, ts.isTypeParameterDeclaration); + function visitNode(node, visitor, test, lift) { + if (node === undefined || visitor === undefined) { + return node; + } + ts.aggregateTransformFlags(node); + var visited = visitor(node); + if (visited === node) { + return node; + } + var visitedNode; + if (visited === undefined) { + return undefined; + } + else if (ts.isArray(visited)) { + visitedNode = (lift || extractSingleNode)(visited); + } + else { + visitedNode = visited; + } + ts.Debug.assertNode(visitedNode, test); + ts.aggregateTransformFlags(visitedNode); + return visitedNode; + } + ts.visitNode = visitNode; + /** + * Visits a NodeArray using the supplied visitor, possibly returning a new NodeArray in its place. + * + * @param nodes The NodeArray to visit. + * @param visitor The callback used to visit a Node. + * @param test A node test to execute for each node. + * @param start An optional value indicating the starting offset at which to start visiting. + * @param count An optional value indicating the maximum number of nodes to visit. + */ + function visitNodes(nodes, visitor, test, start, count) { + if (nodes === undefined || visitor === undefined) { + return nodes; + } + var updated; + // Ensure start and count have valid values + var length = nodes.length; + if (start === undefined || start < 0) { + start = 0; + } + if (count === undefined || count > length - start) { + count = length - start; + } + if (start > 0 || count < length) { + // If we are not visiting all of the original nodes, we must always create a new array. + // Since this is a fragment of a node array, we do not copy over the previous location + // and will only copy over `hasTrailingComma` if we are including the last element. + updated = ts.createNodeArray([], /*hasTrailingComma*/ nodes.hasTrailingComma && start + count === length); + } + // Visit each original node. + for (var i = 0; i < count; i++) { + var node = nodes[i + start]; + ts.aggregateTransformFlags(node); + var visited = node !== undefined ? visitor(node) : undefined; + if (updated !== undefined || visited === undefined || visited !== node) { + if (updated === undefined) { + // Ensure we have a copy of `nodes`, up to the current index. + updated = ts.createNodeArray(nodes.slice(0, i), nodes.hasTrailingComma); + ts.setTextRange(updated, nodes); + } + if (visited) { + if (ts.isArray(visited)) { + for (var _i = 0, visited_1 = visited; _i < visited_1.length; _i++) { + var visitedNode = visited_1[_i]; + ts.Debug.assertNode(visitedNode, test); + ts.aggregateTransformFlags(visitedNode); + updated.push(visitedNode); + } + } + else { + ts.Debug.assertNode(visited, test); + ts.aggregateTransformFlags(visited); + updated.push(visited); + } + } + } + } + return updated || nodes; + } + ts.visitNodes = visitNodes; + /** + * Starts a new lexical environment and visits a statement list, ending the lexical environment + * and merging hoisted declarations upon completion. + */ + function visitLexicalEnvironment(statements, visitor, context, start, ensureUseStrict) { + context.startLexicalEnvironment(); + statements = visitNodes(statements, visitor, ts.isStatement, start); + if (ensureUseStrict && !ts.startsWithUseStrict(statements)) { + statements = ts.setTextRange(ts.createNodeArray([ts.createExpressionStatement(ts.createLiteral("use strict"))].concat(statements)), statements); + } + var declarations = context.endLexicalEnvironment(); + return ts.setTextRange(ts.createNodeArray(ts.concatenate(declarations, statements)), statements); + } + ts.visitLexicalEnvironment = visitLexicalEnvironment; + /** + * Starts a new lexical environment and visits a parameter list, suspending the lexical + * environment upon completion. + */ + function visitParameterList(nodes, visitor, context, nodesVisitor) { + if (nodesVisitor === void 0) { nodesVisitor = visitNodes; } + context.startLexicalEnvironment(); + var updated = nodesVisitor(nodes, visitor, ts.isParameterDeclaration); + context.suspendLexicalEnvironment(); + return updated; + } + ts.visitParameterList = visitParameterList; + function visitFunctionBody(node, visitor, context) { + context.resumeLexicalEnvironment(); + var updated = visitNode(node, visitor, ts.isConciseBody); + var declarations = context.endLexicalEnvironment(); + if (ts.some(declarations)) { + var block = ts.convertToFunctionBody(updated); + var statements = ts.mergeLexicalEnvironment(block.statements, declarations); + return ts.updateBlock(block, statements); + } + return updated; + } + ts.visitFunctionBody = visitFunctionBody; + function visitEachChild(node, visitor, context, nodesVisitor, tokenVisitor) { + if (nodesVisitor === void 0) { nodesVisitor = visitNodes; } + if (node === undefined) { + return undefined; + } + var kind = node.kind; + // No need to visit nodes with no children. + if ((kind > 0 /* FirstToken */ && kind <= 147 /* LastToken */) || kind === 178 /* ThisType */) { + return node; + } + switch (kind) { + // Names + case 72 /* Identifier */: + return ts.updateIdentifier(node, nodesVisitor(node.typeArguments, visitor, isTypeNodeOrTypeParameterDeclaration)); + case 148 /* QualifiedName */: + return ts.updateQualifiedName(node, visitNode(node.left, visitor, ts.isEntityName), visitNode(node.right, visitor, ts.isIdentifier)); + case 149 /* ComputedPropertyName */: + return ts.updateComputedPropertyName(node, visitNode(node.expression, visitor, ts.isExpression)); + // Signature elements + case 150 /* TypeParameter */: + return ts.updateTypeParameterDeclaration(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.constraint, visitor, ts.isTypeNode), visitNode(node.default, visitor, ts.isTypeNode)); + case 151 /* Parameter */: + return ts.updateParameter(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.dotDotDotToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isBindingName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); + case 152 /* Decorator */: + return ts.updateDecorator(node, visitNode(node.expression, visitor, ts.isExpression)); + // Type elements + case 153 /* PropertySignature */: + return ts.updatePropertySignature(node, nodesVisitor(node.modifiers, visitor, ts.isToken), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); + case 154 /* PropertyDeclaration */: + return ts.updateProperty(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); + case 155 /* MethodSignature */: + return ts.updateMethodSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken)); + case 156 /* MethodDeclaration */: + return ts.updateMethod(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); + case 157 /* Constructor */: + return ts.updateConstructor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context)); + case 158 /* GetAccessor */: + return ts.updateGetAccessor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); + case 159 /* SetAccessor */: + return ts.updateSetAccessor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context)); + case 160 /* CallSignature */: + return ts.updateCallSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); + case 161 /* ConstructSignature */: + return ts.updateConstructSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); + case 162 /* IndexSignature */: + return ts.updateIndexSignature(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); + // Types + case 163 /* TypePredicate */: + return ts.updateTypePredicateNode(node, visitNode(node.parameterName, visitor), visitNode(node.type, visitor, ts.isTypeNode)); + case 164 /* TypeReference */: + return ts.updateTypeReferenceNode(node, visitNode(node.typeName, visitor, ts.isEntityName), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode)); + case 165 /* FunctionType */: + return ts.updateFunctionTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); + case 166 /* ConstructorType */: + return ts.updateConstructorTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); + case 167 /* TypeQuery */: + return ts.updateTypeQueryNode(node, visitNode(node.exprName, visitor, ts.isEntityName)); + case 168 /* TypeLiteral */: + return ts.updateTypeLiteralNode(node, nodesVisitor(node.members, visitor, ts.isTypeElement)); + case 169 /* ArrayType */: + return ts.updateArrayTypeNode(node, visitNode(node.elementType, visitor, ts.isTypeNode)); + case 170 /* TupleType */: + return ts.updateTupleTypeNode(node, nodesVisitor(node.elementTypes, visitor, ts.isTypeNode)); + case 171 /* OptionalType */: + return ts.updateOptionalTypeNode(node, visitNode(node.type, visitor, ts.isTypeNode)); + case 172 /* RestType */: + return ts.updateRestTypeNode(node, visitNode(node.type, visitor, ts.isTypeNode)); + case 173 /* UnionType */: + return ts.updateUnionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode)); + case 174 /* IntersectionType */: + return ts.updateIntersectionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode)); + case 175 /* ConditionalType */: + return ts.updateConditionalTypeNode(node, visitNode(node.checkType, visitor, ts.isTypeNode), visitNode(node.extendsType, visitor, ts.isTypeNode), visitNode(node.trueType, visitor, ts.isTypeNode), visitNode(node.falseType, visitor, ts.isTypeNode)); + case 176 /* InferType */: + return ts.updateInferTypeNode(node, visitNode(node.typeParameter, visitor, ts.isTypeParameterDeclaration)); + case 183 /* ImportType */: + return ts.updateImportTypeNode(node, visitNode(node.argument, visitor, ts.isTypeNode), visitNode(node.qualifier, visitor, ts.isEntityName), visitNodes(node.typeArguments, visitor, ts.isTypeNode), node.isTypeOf); + case 177 /* ParenthesizedType */: + return ts.updateParenthesizedType(node, visitNode(node.type, visitor, ts.isTypeNode)); + case 179 /* TypeOperator */: + return ts.updateTypeOperatorNode(node, visitNode(node.type, visitor, ts.isTypeNode)); + case 180 /* IndexedAccessType */: + return ts.updateIndexedAccessTypeNode(node, visitNode(node.objectType, visitor, ts.isTypeNode), visitNode(node.indexType, visitor, ts.isTypeNode)); + case 181 /* MappedType */: + return ts.updateMappedTypeNode(node, visitNode(node.readonlyToken, tokenVisitor, ts.isToken), visitNode(node.typeParameter, visitor, ts.isTypeParameterDeclaration), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode)); + case 182 /* LiteralType */: + return ts.updateLiteralTypeNode(node, visitNode(node.literal, visitor, ts.isExpression)); + // Binding patterns + case 184 /* ObjectBindingPattern */: + return ts.updateObjectBindingPattern(node, nodesVisitor(node.elements, visitor, ts.isBindingElement)); + case 185 /* ArrayBindingPattern */: + return ts.updateArrayBindingPattern(node, nodesVisitor(node.elements, visitor, ts.isArrayBindingElement)); + case 186 /* BindingElement */: + return ts.updateBindingElement(node, visitNode(node.dotDotDotToken, tokenVisitor, ts.isToken), visitNode(node.propertyName, visitor, ts.isPropertyName), visitNode(node.name, visitor, ts.isBindingName), visitNode(node.initializer, visitor, ts.isExpression)); + // Expression + case 187 /* ArrayLiteralExpression */: + return ts.updateArrayLiteral(node, nodesVisitor(node.elements, visitor, ts.isExpression)); + case 188 /* ObjectLiteralExpression */: + return ts.updateObjectLiteral(node, nodesVisitor(node.properties, visitor, ts.isObjectLiteralElementLike)); + case 189 /* PropertyAccessExpression */: + return ts.updatePropertyAccess(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.name, visitor, ts.isIdentifier)); + case 190 /* ElementAccessExpression */: + return ts.updateElementAccess(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.argumentExpression, visitor, ts.isExpression)); + case 191 /* CallExpression */: + return ts.updateCall(node, visitNode(node.expression, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression)); + case 192 /* NewExpression */: + return ts.updateNew(node, visitNode(node.expression, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression)); + case 193 /* TaggedTemplateExpression */: + return ts.updateTaggedTemplate(node, visitNode(node.tag, visitor, ts.isExpression), visitNodes(node.typeArguments, visitor, ts.isExpression), visitNode(node.template, visitor, ts.isTemplateLiteral)); + case 194 /* TypeAssertionExpression */: + return ts.updateTypeAssertion(node, visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.expression, visitor, ts.isExpression)); + case 195 /* ParenthesizedExpression */: + return ts.updateParen(node, visitNode(node.expression, visitor, ts.isExpression)); + case 196 /* FunctionExpression */: + return ts.updateFunctionExpression(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); + case 197 /* ArrowFunction */: + return ts.updateArrowFunction(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.equalsGreaterThanToken, visitor, ts.isToken), visitFunctionBody(node.body, visitor, context)); + case 198 /* DeleteExpression */: + return ts.updateDelete(node, visitNode(node.expression, visitor, ts.isExpression)); + case 199 /* TypeOfExpression */: + return ts.updateTypeOf(node, visitNode(node.expression, visitor, ts.isExpression)); + case 200 /* VoidExpression */: + return ts.updateVoid(node, visitNode(node.expression, visitor, ts.isExpression)); + case 201 /* AwaitExpression */: + return ts.updateAwait(node, visitNode(node.expression, visitor, ts.isExpression)); + case 202 /* PrefixUnaryExpression */: + return ts.updatePrefix(node, visitNode(node.operand, visitor, ts.isExpression)); + case 203 /* PostfixUnaryExpression */: + return ts.updatePostfix(node, visitNode(node.operand, visitor, ts.isExpression)); + case 204 /* BinaryExpression */: + return ts.updateBinary(node, visitNode(node.left, visitor, ts.isExpression), visitNode(node.right, visitor, ts.isExpression), visitNode(node.operatorToken, visitor, ts.isToken)); + case 205 /* ConditionalExpression */: + return ts.updateConditional(node, visitNode(node.condition, visitor, ts.isExpression), visitNode(node.questionToken, visitor, ts.isToken), visitNode(node.whenTrue, visitor, ts.isExpression), visitNode(node.colonToken, visitor, ts.isToken), visitNode(node.whenFalse, visitor, ts.isExpression)); + case 206 /* TemplateExpression */: + return ts.updateTemplateExpression(node, visitNode(node.head, visitor, ts.isTemplateHead), nodesVisitor(node.templateSpans, visitor, ts.isTemplateSpan)); + case 207 /* YieldExpression */: + return ts.updateYield(node, visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.expression, visitor, ts.isExpression)); + case 208 /* SpreadElement */: + return ts.updateSpread(node, visitNode(node.expression, visitor, ts.isExpression)); + case 209 /* ClassExpression */: + return ts.updateClassExpression(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement)); + case 211 /* ExpressionWithTypeArguments */: + return ts.updateExpressionWithTypeArguments(node, nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), visitNode(node.expression, visitor, ts.isExpression)); + case 212 /* AsExpression */: + return ts.updateAsExpression(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.type, visitor, ts.isTypeNode)); + case 213 /* NonNullExpression */: + return ts.updateNonNullExpression(node, visitNode(node.expression, visitor, ts.isExpression)); + case 214 /* MetaProperty */: + return ts.updateMetaProperty(node, visitNode(node.name, visitor, ts.isIdentifier)); + // Misc + case 216 /* TemplateSpan */: + return ts.updateTemplateSpan(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.literal, visitor, ts.isTemplateMiddleOrTemplateTail)); + // Element + case 218 /* Block */: + return ts.updateBlock(node, nodesVisitor(node.statements, visitor, ts.isStatement)); + case 219 /* VariableStatement */: + return ts.updateVariableStatement(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.declarationList, visitor, ts.isVariableDeclarationList)); + case 221 /* ExpressionStatement */: + return ts.updateExpressionStatement(node, visitNode(node.expression, visitor, ts.isExpression)); + case 222 /* IfStatement */: + return ts.updateIf(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.thenStatement, visitor, ts.isStatement, ts.liftToBlock), visitNode(node.elseStatement, visitor, ts.isStatement, ts.liftToBlock)); + case 223 /* DoStatement */: + return ts.updateDo(node, visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock), visitNode(node.expression, visitor, ts.isExpression)); + case 224 /* WhileStatement */: + return ts.updateWhile(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); + case 225 /* ForStatement */: + return ts.updateFor(node, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.condition, visitor, ts.isExpression), visitNode(node.incrementor, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); + case 226 /* ForInStatement */: + return ts.updateForIn(node, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); + case 227 /* ForOfStatement */: + return ts.updateForOf(node, visitNode(node.awaitModifier, visitor, ts.isToken), visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); + case 228 /* ContinueStatement */: + return ts.updateContinue(node, visitNode(node.label, visitor, ts.isIdentifier)); + case 229 /* BreakStatement */: + return ts.updateBreak(node, visitNode(node.label, visitor, ts.isIdentifier)); + case 230 /* ReturnStatement */: + return ts.updateReturn(node, visitNode(node.expression, visitor, ts.isExpression)); + case 231 /* WithStatement */: + return ts.updateWith(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); + case 232 /* SwitchStatement */: + return ts.updateSwitch(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.caseBlock, visitor, ts.isCaseBlock)); + case 233 /* LabeledStatement */: + return ts.updateLabel(node, visitNode(node.label, visitor, ts.isIdentifier), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); + case 234 /* ThrowStatement */: + return ts.updateThrow(node, visitNode(node.expression, visitor, ts.isExpression)); + case 235 /* TryStatement */: + return ts.updateTry(node, visitNode(node.tryBlock, visitor, ts.isBlock), visitNode(node.catchClause, visitor, ts.isCatchClause), visitNode(node.finallyBlock, visitor, ts.isBlock)); + case 237 /* VariableDeclaration */: + return ts.updateVariableDeclaration(node, visitNode(node.name, visitor, ts.isBindingName), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); + case 238 /* VariableDeclarationList */: + return ts.updateVariableDeclarationList(node, nodesVisitor(node.declarations, visitor, ts.isVariableDeclaration)); + case 239 /* FunctionDeclaration */: + return ts.updateFunctionDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); + case 240 /* ClassDeclaration */: + return ts.updateClassDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement)); + case 241 /* InterfaceDeclaration */: + return ts.updateInterfaceDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isTypeElement)); + case 242 /* TypeAliasDeclaration */: + return ts.updateTypeAliasDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); + case 243 /* EnumDeclaration */: + return ts.updateEnumDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.members, visitor, ts.isEnumMember)); + case 244 /* ModuleDeclaration */: + return ts.updateModuleDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.body, visitor, ts.isModuleBody)); + case 245 /* ModuleBlock */: + return ts.updateModuleBlock(node, nodesVisitor(node.statements, visitor, ts.isStatement)); + case 246 /* CaseBlock */: + return ts.updateCaseBlock(node, nodesVisitor(node.clauses, visitor, ts.isCaseOrDefaultClause)); + case 247 /* NamespaceExportDeclaration */: + return ts.updateNamespaceExportDeclaration(node, visitNode(node.name, visitor, ts.isIdentifier)); + case 248 /* ImportEqualsDeclaration */: + return ts.updateImportEqualsDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.moduleReference, visitor, ts.isModuleReference)); + case 249 /* ImportDeclaration */: + return ts.updateImportDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.importClause, visitor, ts.isImportClause), visitNode(node.moduleSpecifier, visitor, ts.isExpression)); + case 250 /* ImportClause */: + return ts.updateImportClause(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.namedBindings, visitor, ts.isNamedImportBindings)); + case 251 /* NamespaceImport */: + return ts.updateNamespaceImport(node, visitNode(node.name, visitor, ts.isIdentifier)); + case 252 /* NamedImports */: + return ts.updateNamedImports(node, nodesVisitor(node.elements, visitor, ts.isImportSpecifier)); + case 253 /* ImportSpecifier */: + return ts.updateImportSpecifier(node, visitNode(node.propertyName, visitor, ts.isIdentifier), visitNode(node.name, visitor, ts.isIdentifier)); + case 254 /* ExportAssignment */: + return ts.updateExportAssignment(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.expression, visitor, ts.isExpression)); + case 255 /* ExportDeclaration */: + return ts.updateExportDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.exportClause, visitor, ts.isNamedExports), visitNode(node.moduleSpecifier, visitor, ts.isExpression)); + case 256 /* NamedExports */: + return ts.updateNamedExports(node, nodesVisitor(node.elements, visitor, ts.isExportSpecifier)); + case 257 /* ExportSpecifier */: + return ts.updateExportSpecifier(node, visitNode(node.propertyName, visitor, ts.isIdentifier), visitNode(node.name, visitor, ts.isIdentifier)); + // Module references + case 259 /* ExternalModuleReference */: + return ts.updateExternalModuleReference(node, visitNode(node.expression, visitor, ts.isExpression)); + // JSX + case 260 /* JsxElement */: + return ts.updateJsxElement(node, visitNode(node.openingElement, visitor, ts.isJsxOpeningElement), nodesVisitor(node.children, visitor, ts.isJsxChild), visitNode(node.closingElement, visitor, ts.isJsxClosingElement)); + case 261 /* JsxSelfClosingElement */: + return ts.updateJsxSelfClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), visitNode(node.attributes, visitor, ts.isJsxAttributes)); + case 262 /* JsxOpeningElement */: + return ts.updateJsxOpeningElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), visitNode(node.attributes, visitor, ts.isJsxAttributes)); + case 263 /* JsxClosingElement */: + return ts.updateJsxClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression)); + case 264 /* JsxFragment */: + return ts.updateJsxFragment(node, visitNode(node.openingFragment, visitor, ts.isJsxOpeningFragment), nodesVisitor(node.children, visitor, ts.isJsxChild), visitNode(node.closingFragment, visitor, ts.isJsxClosingFragment)); + case 267 /* JsxAttribute */: + return ts.updateJsxAttribute(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.initializer, visitor, ts.isStringLiteralOrJsxExpression)); + case 268 /* JsxAttributes */: + return ts.updateJsxAttributes(node, nodesVisitor(node.properties, visitor, ts.isJsxAttributeLike)); + case 269 /* JsxSpreadAttribute */: + return ts.updateJsxSpreadAttribute(node, visitNode(node.expression, visitor, ts.isExpression)); + case 270 /* JsxExpression */: + return ts.updateJsxExpression(node, visitNode(node.expression, visitor, ts.isExpression)); + // Clauses + case 271 /* CaseClause */: + return ts.updateCaseClause(node, visitNode(node.expression, visitor, ts.isExpression), nodesVisitor(node.statements, visitor, ts.isStatement)); + case 272 /* DefaultClause */: + return ts.updateDefaultClause(node, nodesVisitor(node.statements, visitor, ts.isStatement)); + case 273 /* HeritageClause */: + return ts.updateHeritageClause(node, nodesVisitor(node.types, visitor, ts.isExpressionWithTypeArguments)); + case 274 /* CatchClause */: + return ts.updateCatchClause(node, visitNode(node.variableDeclaration, visitor, ts.isVariableDeclaration), visitNode(node.block, visitor, ts.isBlock)); + // Property assignments + case 275 /* PropertyAssignment */: + return ts.updatePropertyAssignment(node, visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.initializer, visitor, ts.isExpression)); + case 276 /* ShorthandPropertyAssignment */: + return ts.updateShorthandPropertyAssignment(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.objectAssignmentInitializer, visitor, ts.isExpression)); + case 277 /* SpreadAssignment */: + return ts.updateSpreadAssignment(node, visitNode(node.expression, visitor, ts.isExpression)); + // Enum + case 278 /* EnumMember */: + return ts.updateEnumMember(node, visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.initializer, visitor, ts.isExpression)); + // Top-level nodes + case 279 /* SourceFile */: + return ts.updateSourceFileNode(node, visitLexicalEnvironment(node.statements, visitor, context)); + // Transformation nodes + case 308 /* PartiallyEmittedExpression */: + return ts.updatePartiallyEmittedExpression(node, visitNode(node.expression, visitor, ts.isExpression)); + case 309 /* CommaListExpression */: + return ts.updateCommaList(node, nodesVisitor(node.elements, visitor, ts.isExpression)); + default: + // No need to visit nodes with no children. + return node; + } + } + ts.visitEachChild = visitEachChild; + /** + * Extracts the single node from a NodeArray. + * + * @param nodes The NodeArray. + */ + function extractSingleNode(nodes) { + ts.Debug.assert(nodes.length <= 1, "Too many nodes written to output."); + return ts.singleOrUndefined(nodes); + } +})(ts || (ts = {})); +/* @internal */ +(function (ts) { + function reduceNode(node, f, initial) { + return node ? f(initial, node) : initial; + } + function reduceNodeArray(nodes, f, initial) { + return nodes ? f(initial, nodes) : initial; + } + /** + * Similar to `reduceLeft`, performs a reduction against each child of a node. + * NOTE: Unlike `forEachChild`, this does *not* visit every node. + * + * @param node The node containing the children to reduce. + * @param initial The initial value to supply to the reduction. + * @param f The callback function + */ + function reduceEachChild(node, initial, cbNode, cbNodeArray) { + if (node === undefined) { + return initial; + } + var reduceNodes = cbNodeArray ? reduceNodeArray : ts.reduceLeft; + var cbNodes = cbNodeArray || cbNode; + var kind = node.kind; + // No need to visit nodes with no children. + if ((kind > 0 /* FirstToken */ && kind <= 147 /* LastToken */)) { + return initial; + } + // We do not yet support types. + if ((kind >= 163 /* TypePredicate */ && kind <= 182 /* LiteralType */)) { + return initial; + } + var result = initial; + switch (node.kind) { + // Leaf nodes + case 217 /* SemicolonClassElement */: + case 220 /* EmptyStatement */: + case 210 /* OmittedExpression */: + case 236 /* DebuggerStatement */: + case 307 /* NotEmittedStatement */: + // No need to visit nodes with no children. + break; + // Names + case 148 /* QualifiedName */: + result = reduceNode(node.left, cbNode, result); + result = reduceNode(node.right, cbNode, result); + break; + case 149 /* ComputedPropertyName */: + result = reduceNode(node.expression, cbNode, result); + break; + // Signature elements + case 151 /* Parameter */: + result = reduceNodes(node.decorators, cbNodes, result); + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.type, cbNode, result); + result = reduceNode(node.initializer, cbNode, result); + break; + case 152 /* Decorator */: + result = reduceNode(node.expression, cbNode, result); + break; + // Type member + case 153 /* PropertySignature */: + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.questionToken, cbNode, result); + result = reduceNode(node.type, cbNode, result); + result = reduceNode(node.initializer, cbNode, result); + break; + case 154 /* PropertyDeclaration */: + result = reduceNodes(node.decorators, cbNodes, result); + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.type, cbNode, result); + result = reduceNode(node.initializer, cbNode, result); + break; + case 156 /* MethodDeclaration */: + result = reduceNodes(node.decorators, cbNodes, result); + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNodes(node.typeParameters, cbNodes, result); + result = reduceNodes(node.parameters, cbNodes, result); + result = reduceNode(node.type, cbNode, result); + result = reduceNode(node.body, cbNode, result); + break; + case 157 /* Constructor */: + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNodes(node.parameters, cbNodes, result); + result = reduceNode(node.body, cbNode, result); + break; + case 158 /* GetAccessor */: + result = reduceNodes(node.decorators, cbNodes, result); + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNodes(node.parameters, cbNodes, result); + result = reduceNode(node.type, cbNode, result); + result = reduceNode(node.body, cbNode, result); + break; + case 159 /* SetAccessor */: + result = reduceNodes(node.decorators, cbNodes, result); + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNodes(node.parameters, cbNodes, result); + result = reduceNode(node.body, cbNode, result); + break; + // Binding patterns + case 184 /* ObjectBindingPattern */: + case 185 /* ArrayBindingPattern */: + result = reduceNodes(node.elements, cbNodes, result); + break; + case 186 /* BindingElement */: + result = reduceNode(node.propertyName, cbNode, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.initializer, cbNode, result); + break; + // Expression + case 187 /* ArrayLiteralExpression */: + result = reduceNodes(node.elements, cbNodes, result); + break; + case 188 /* ObjectLiteralExpression */: + result = reduceNodes(node.properties, cbNodes, result); + break; + case 189 /* PropertyAccessExpression */: + result = reduceNode(node.expression, cbNode, result); + result = reduceNode(node.name, cbNode, result); + break; + case 190 /* ElementAccessExpression */: + result = reduceNode(node.expression, cbNode, result); + result = reduceNode(node.argumentExpression, cbNode, result); + break; + case 191 /* CallExpression */: + result = reduceNode(node.expression, cbNode, result); + result = reduceNodes(node.typeArguments, cbNodes, result); + result = reduceNodes(node.arguments, cbNodes, result); + break; + case 192 /* NewExpression */: + result = reduceNode(node.expression, cbNode, result); + result = reduceNodes(node.typeArguments, cbNodes, result); + result = reduceNodes(node.arguments, cbNodes, result); + break; + case 193 /* TaggedTemplateExpression */: + result = reduceNode(node.tag, cbNode, result); + result = reduceNodes(node.typeArguments, cbNodes, result); + result = reduceNode(node.template, cbNode, result); + break; + case 194 /* TypeAssertionExpression */: + result = reduceNode(node.type, cbNode, result); + result = reduceNode(node.expression, cbNode, result); + break; + case 196 /* FunctionExpression */: + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNodes(node.typeParameters, cbNodes, result); + result = reduceNodes(node.parameters, cbNodes, result); + result = reduceNode(node.type, cbNode, result); + result = reduceNode(node.body, cbNode, result); + break; + case 197 /* ArrowFunction */: + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNodes(node.typeParameters, cbNodes, result); + result = reduceNodes(node.parameters, cbNodes, result); + result = reduceNode(node.type, cbNode, result); + result = reduceNode(node.body, cbNode, result); + break; + case 195 /* ParenthesizedExpression */: + case 198 /* DeleteExpression */: + case 199 /* TypeOfExpression */: + case 200 /* VoidExpression */: + case 201 /* AwaitExpression */: + case 207 /* YieldExpression */: + case 208 /* SpreadElement */: + case 213 /* NonNullExpression */: + result = reduceNode(node.expression, cbNode, result); + break; + case 202 /* PrefixUnaryExpression */: + case 203 /* PostfixUnaryExpression */: + result = reduceNode(node.operand, cbNode, result); + break; + case 204 /* BinaryExpression */: + result = reduceNode(node.left, cbNode, result); + result = reduceNode(node.right, cbNode, result); + break; + case 205 /* ConditionalExpression */: + result = reduceNode(node.condition, cbNode, result); + result = reduceNode(node.whenTrue, cbNode, result); + result = reduceNode(node.whenFalse, cbNode, result); + break; + case 206 /* TemplateExpression */: + result = reduceNode(node.head, cbNode, result); + result = reduceNodes(node.templateSpans, cbNodes, result); + break; + case 209 /* ClassExpression */: + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNodes(node.typeParameters, cbNodes, result); + result = reduceNodes(node.heritageClauses, cbNodes, result); + result = reduceNodes(node.members, cbNodes, result); + break; + case 211 /* ExpressionWithTypeArguments */: + result = reduceNode(node.expression, cbNode, result); + result = reduceNodes(node.typeArguments, cbNodes, result); + break; + case 212 /* AsExpression */: + result = reduceNode(node.expression, cbNode, result); + result = reduceNode(node.type, cbNode, result); + break; + // Misc + case 216 /* TemplateSpan */: + result = reduceNode(node.expression, cbNode, result); + result = reduceNode(node.literal, cbNode, result); + break; + // Element + case 218 /* Block */: + result = reduceNodes(node.statements, cbNodes, result); + break; + case 219 /* VariableStatement */: + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.declarationList, cbNode, result); + break; + case 221 /* ExpressionStatement */: + result = reduceNode(node.expression, cbNode, result); + break; + case 222 /* IfStatement */: + result = reduceNode(node.expression, cbNode, result); + result = reduceNode(node.thenStatement, cbNode, result); + result = reduceNode(node.elseStatement, cbNode, result); + break; + case 223 /* DoStatement */: + result = reduceNode(node.statement, cbNode, result); + result = reduceNode(node.expression, cbNode, result); + break; + case 224 /* WhileStatement */: + case 231 /* WithStatement */: + result = reduceNode(node.expression, cbNode, result); + result = reduceNode(node.statement, cbNode, result); + break; + case 225 /* ForStatement */: + result = reduceNode(node.initializer, cbNode, result); + result = reduceNode(node.condition, cbNode, result); + result = reduceNode(node.incrementor, cbNode, result); + result = reduceNode(node.statement, cbNode, result); + break; + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + result = reduceNode(node.initializer, cbNode, result); + result = reduceNode(node.expression, cbNode, result); + result = reduceNode(node.statement, cbNode, result); + break; + case 230 /* ReturnStatement */: + case 234 /* ThrowStatement */: + result = reduceNode(node.expression, cbNode, result); + break; + case 232 /* SwitchStatement */: + result = reduceNode(node.expression, cbNode, result); + result = reduceNode(node.caseBlock, cbNode, result); + break; + case 233 /* LabeledStatement */: + result = reduceNode(node.label, cbNode, result); + result = reduceNode(node.statement, cbNode, result); + break; + case 235 /* TryStatement */: + result = reduceNode(node.tryBlock, cbNode, result); + result = reduceNode(node.catchClause, cbNode, result); + result = reduceNode(node.finallyBlock, cbNode, result); + break; + case 237 /* VariableDeclaration */: + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.type, cbNode, result); + result = reduceNode(node.initializer, cbNode, result); + break; + case 238 /* VariableDeclarationList */: + result = reduceNodes(node.declarations, cbNodes, result); + break; + case 239 /* FunctionDeclaration */: + result = reduceNodes(node.decorators, cbNodes, result); + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNodes(node.typeParameters, cbNodes, result); + result = reduceNodes(node.parameters, cbNodes, result); + result = reduceNode(node.type, cbNode, result); + result = reduceNode(node.body, cbNode, result); + break; + case 240 /* ClassDeclaration */: + result = reduceNodes(node.decorators, cbNodes, result); + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNodes(node.typeParameters, cbNodes, result); + result = reduceNodes(node.heritageClauses, cbNodes, result); + result = reduceNodes(node.members, cbNodes, result); + break; + case 243 /* EnumDeclaration */: + result = reduceNodes(node.decorators, cbNodes, result); + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNodes(node.members, cbNodes, result); + break; + case 244 /* ModuleDeclaration */: + result = reduceNodes(node.decorators, cbNodes, result); + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.body, cbNode, result); + break; + case 245 /* ModuleBlock */: + result = reduceNodes(node.statements, cbNodes, result); + break; + case 246 /* CaseBlock */: + result = reduceNodes(node.clauses, cbNodes, result); + break; + case 248 /* ImportEqualsDeclaration */: + result = reduceNodes(node.decorators, cbNodes, result); + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.moduleReference, cbNode, result); + break; + case 249 /* ImportDeclaration */: + result = reduceNodes(node.decorators, cbNodes, result); + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.importClause, cbNode, result); + result = reduceNode(node.moduleSpecifier, cbNode, result); + break; + case 250 /* ImportClause */: + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.namedBindings, cbNode, result); + break; + case 251 /* NamespaceImport */: + result = reduceNode(node.name, cbNode, result); + break; + case 252 /* NamedImports */: + case 256 /* NamedExports */: + result = reduceNodes(node.elements, cbNodes, result); + break; + case 253 /* ImportSpecifier */: + case 257 /* ExportSpecifier */: + result = reduceNode(node.propertyName, cbNode, result); + result = reduceNode(node.name, cbNode, result); + break; + case 254 /* ExportAssignment */: + result = ts.reduceLeft(node.decorators, cbNode, result); + result = ts.reduceLeft(node.modifiers, cbNode, result); + result = reduceNode(node.expression, cbNode, result); + break; + case 255 /* ExportDeclaration */: + result = ts.reduceLeft(node.decorators, cbNode, result); + result = ts.reduceLeft(node.modifiers, cbNode, result); + result = reduceNode(node.exportClause, cbNode, result); + result = reduceNode(node.moduleSpecifier, cbNode, result); + break; + // Module references + case 259 /* ExternalModuleReference */: + result = reduceNode(node.expression, cbNode, result); + break; + // JSX + case 260 /* JsxElement */: + result = reduceNode(node.openingElement, cbNode, result); + result = ts.reduceLeft(node.children, cbNode, result); + result = reduceNode(node.closingElement, cbNode, result); + break; + case 264 /* JsxFragment */: + result = reduceNode(node.openingFragment, cbNode, result); + result = ts.reduceLeft(node.children, cbNode, result); + result = reduceNode(node.closingFragment, cbNode, result); + break; + case 261 /* JsxSelfClosingElement */: + case 262 /* JsxOpeningElement */: + result = reduceNode(node.tagName, cbNode, result); + result = reduceNodes(node.typeArguments, cbNode, result); + result = reduceNode(node.attributes, cbNode, result); + break; + case 268 /* JsxAttributes */: + result = reduceNodes(node.properties, cbNodes, result); + break; + case 263 /* JsxClosingElement */: + result = reduceNode(node.tagName, cbNode, result); + break; + case 267 /* JsxAttribute */: + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.initializer, cbNode, result); + break; + case 269 /* JsxSpreadAttribute */: + result = reduceNode(node.expression, cbNode, result); + break; + case 270 /* JsxExpression */: + result = reduceNode(node.expression, cbNode, result); + break; + // Clauses + case 271 /* CaseClause */: + result = reduceNode(node.expression, cbNode, result); + // falls through + case 272 /* DefaultClause */: + result = reduceNodes(node.statements, cbNodes, result); + break; + case 273 /* HeritageClause */: + result = reduceNodes(node.types, cbNodes, result); + break; + case 274 /* CatchClause */: + result = reduceNode(node.variableDeclaration, cbNode, result); + result = reduceNode(node.block, cbNode, result); + break; + // Property assignments + case 275 /* PropertyAssignment */: + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.initializer, cbNode, result); + break; + case 276 /* ShorthandPropertyAssignment */: + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.objectAssignmentInitializer, cbNode, result); + break; + case 277 /* SpreadAssignment */: + result = reduceNode(node.expression, cbNode, result); + break; + // Enum + case 278 /* EnumMember */: + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.initializer, cbNode, result); + break; + // Top-level nodes + case 279 /* SourceFile */: + result = reduceNodes(node.statements, cbNodes, result); + break; + // Transformation nodes + case 308 /* PartiallyEmittedExpression */: + result = reduceNode(node.expression, cbNode, result); + break; + case 309 /* CommaListExpression */: + result = reduceNodes(node.elements, cbNodes, result); + break; + default: + break; + } + return result; + } + ts.reduceEachChild = reduceEachChild; + function mergeLexicalEnvironment(statements, declarations) { + if (!ts.some(declarations)) { + return statements; + } + return ts.isNodeArray(statements) + ? ts.setTextRange(ts.createNodeArray(ts.addStatementsAfterPrologue(statements.slice(), declarations)), statements) + : ts.addStatementsAfterPrologue(statements, declarations); + } + ts.mergeLexicalEnvironment = mergeLexicalEnvironment; + /** + * Lifts a NodeArray containing only Statement nodes to a block. + * + * @param nodes The NodeArray. + */ + function liftToBlock(nodes) { + Debug.assert(ts.every(nodes, ts.isStatement), "Cannot lift nodes to a Block."); + return ts.singleOrUndefined(nodes) || ts.createBlock(nodes); + } + ts.liftToBlock = liftToBlock; + /** + * Aggregates the TransformFlags for a Node and its subtree. + */ + function aggregateTransformFlags(node) { + aggregateTransformFlagsForNode(node); + return node; + } + ts.aggregateTransformFlags = aggregateTransformFlags; + /** + * Aggregates the TransformFlags for a Node and its subtree. The flags for the subtree are + * computed first, then the transform flags for the current node are computed from the subtree + * flags and the state of the current node. Finally, the transform flags of the node are + * returned, excluding any flags that should not be included in its parent node's subtree + * flags. + */ + function aggregateTransformFlagsForNode(node) { + if (node === undefined) { + return 0 /* None */; + } + if (node.transformFlags & 536870912 /* HasComputedFlags */) { + return node.transformFlags & ~ts.getTransformFlagsSubtreeExclusions(node.kind); + } + var subtreeFlags = aggregateTransformFlagsForSubtree(node); + return ts.computeTransformFlagsForNode(node, subtreeFlags); + } + function aggregateTransformFlagsForNodeArray(nodes) { + if (nodes === undefined) { + return 0 /* None */; + } + var subtreeFlags = 0 /* None */; + var nodeArrayFlags = 0 /* None */; + for (var _i = 0, nodes_3 = nodes; _i < nodes_3.length; _i++) { + var node = nodes_3[_i]; + subtreeFlags |= aggregateTransformFlagsForNode(node); + nodeArrayFlags |= node.transformFlags & ~536870912 /* HasComputedFlags */; + } + nodes.transformFlags = nodeArrayFlags | 536870912 /* HasComputedFlags */; + return subtreeFlags; + } + /** + * Aggregates the transform flags for the subtree of a node. + */ + function aggregateTransformFlagsForSubtree(node) { + // We do not transform ambient declarations or types, so there is no need to + // recursively aggregate transform flags. + if (ts.hasModifier(node, 2 /* Ambient */) || (ts.isTypeNode(node) && node.kind !== 211 /* ExpressionWithTypeArguments */)) { + return 0 /* None */; + } + // Aggregate the transform flags of each child. + return reduceEachChild(node, 0 /* None */, aggregateTransformFlagsForChildNode, aggregateTransformFlagsForChildNodes); + } + /** + * Aggregates the TransformFlags of a child node with the TransformFlags of its + * siblings. + */ + function aggregateTransformFlagsForChildNode(transformFlags, node) { + return transformFlags | aggregateTransformFlagsForNode(node); + } + function aggregateTransformFlagsForChildNodes(transformFlags, nodes) { + return transformFlags | aggregateTransformFlagsForNodeArray(nodes); + } + var Debug; + (function (Debug) { + var isDebugInfoEnabled = false; + function failBadSyntaxKind(node, message) { + return Debug.fail((message || "Unexpected node.") + "\r\nNode " + ts.formatSyntaxKind(node.kind) + " was unexpected.", failBadSyntaxKind); + } + Debug.failBadSyntaxKind = failBadSyntaxKind; + Debug.assertEachNode = Debug.shouldAssert(1 /* Normal */) + ? function (nodes, test, message) { return Debug.assert(test === undefined || ts.every(nodes, test), message || "Unexpected node.", function () { return "Node array did not pass test '" + Debug.getFunctionName(test) + "'."; }, Debug.assertEachNode); } + : ts.noop; + Debug.assertNode = Debug.shouldAssert(1 /* Normal */) + ? function (node, test, message) { return Debug.assert(test === undefined || test(node), message || "Unexpected node.", function () { return "Node " + ts.formatSyntaxKind(node.kind) + " did not pass test '" + Debug.getFunctionName(test) + "'."; }, Debug.assertNode); } + : ts.noop; + Debug.assertOptionalNode = Debug.shouldAssert(1 /* Normal */) + ? function (node, test, message) { return Debug.assert(test === undefined || node === undefined || test(node), message || "Unexpected node.", function () { return "Node " + ts.formatSyntaxKind(node.kind) + " did not pass test '" + Debug.getFunctionName(test) + "'."; }, Debug.assertOptionalNode); } + : ts.noop; + Debug.assertOptionalToken = Debug.shouldAssert(1 /* Normal */) + ? function (node, kind, message) { return Debug.assert(kind === undefined || node === undefined || node.kind === kind, message || "Unexpected node.", function () { return "Node " + ts.formatSyntaxKind(node.kind) + " was not a '" + ts.formatSyntaxKind(kind) + "' token."; }, Debug.assertOptionalToken); } + : ts.noop; + Debug.assertMissingNode = Debug.shouldAssert(1 /* Normal */) + ? function (node, message) { return Debug.assert(node === undefined, message || "Unexpected node.", function () { return "Node " + ts.formatSyntaxKind(node.kind) + " was unexpected'."; }, Debug.assertMissingNode); } + : ts.noop; + /** + * Injects debug information into frequently used types. + */ + function enableDebugInfo() { + if (isDebugInfoEnabled) + return; + // Add additional properties in debug mode to assist with debugging. + Object.defineProperties(ts.objectAllocator.getSymbolConstructor().prototype, { + __debugFlags: { get: function () { return ts.formatSymbolFlags(this.flags); } } + }); + Object.defineProperties(ts.objectAllocator.getTypeConstructor().prototype, { + __debugFlags: { get: function () { return ts.formatTypeFlags(this.flags); } }, + __debugObjectFlags: { get: function () { return this.flags & 524288 /* Object */ ? ts.formatObjectFlags(this.objectFlags) : ""; } }, + __debugTypeToString: { value: function () { return this.checker.typeToString(this); } }, + }); + var nodeConstructors = [ + ts.objectAllocator.getNodeConstructor(), + ts.objectAllocator.getIdentifierConstructor(), + ts.objectAllocator.getTokenConstructor(), + ts.objectAllocator.getSourceFileConstructor() + ]; + for (var _i = 0, nodeConstructors_1 = nodeConstructors; _i < nodeConstructors_1.length; _i++) { + var ctor = nodeConstructors_1[_i]; + if (!ctor.prototype.hasOwnProperty("__debugKind")) { + Object.defineProperties(ctor.prototype, { + __debugKind: { get: function () { return ts.formatSyntaxKind(this.kind); } }, + __debugModifierFlags: { get: function () { return ts.formatModifierFlags(ts.getModifierFlagsNoCache(this)); } }, + __debugTransformFlags: { get: function () { return ts.formatTransformFlags(this.transformFlags); } }, + __debugEmitFlags: { get: function () { return ts.formatEmitFlags(ts.getEmitFlags(this)); } }, + __debugGetText: { + value: function (includeTrivia) { + if (ts.nodeIsSynthesized(this)) + return ""; + var parseNode = ts.getParseTreeNode(this); + var sourceFile = parseNode && ts.getSourceFileOfNode(parseNode); + return sourceFile ? ts.getSourceTextOfNodeFromSourceFile(sourceFile, parseNode, includeTrivia) : ""; + } + } + }); + } + } + isDebugInfoEnabled = true; + } + Debug.enableDebugInfo = enableDebugInfo; + })(Debug = ts.Debug || (ts.Debug = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + function createSourceMapGenerator(host, file, sourceRoot, sourcesDirectoryPath, generatorOptions) { + var _a = generatorOptions.extendedDiagnostics + ? ts.performance.createTimer("Source Map", "beforeSourcemap", "afterSourcemap") + : ts.performance.nullTimer, enter = _a.enter, exit = _a.exit; + // Current source map file and its index in the sources list + var rawSources = []; + var sources = []; + var sourceToSourceIndexMap = ts.createMap(); + var sourcesContent; + var names = []; + var nameToNameIndexMap; + var mappings = ""; + // Last recorded and encoded mappings + var lastGeneratedLine = 0; + var lastGeneratedCharacter = 0; + var lastSourceIndex = 0; + var lastSourceLine = 0; + var lastSourceCharacter = 0; + var lastNameIndex = 0; + var hasLast = false; + var pendingGeneratedLine = 0; + var pendingGeneratedCharacter = 0; + var pendingSourceIndex = 0; + var pendingSourceLine = 0; + var pendingSourceCharacter = 0; + var pendingNameIndex = 0; + var hasPending = false; + var hasPendingSource = false; + var hasPendingName = false; + return { + getSources: function () { return rawSources; }, + addSource: addSource, + setSourceContent: setSourceContent, + addName: addName, + addMapping: addMapping, + appendSourceMap: appendSourceMap, + toJSON: toJSON, + toString: function () { return JSON.stringify(toJSON()); } + }; + function addSource(fileName) { + enter(); + var source = ts.getRelativePathToDirectoryOrUrl(sourcesDirectoryPath, fileName, host.getCurrentDirectory(), host.getCanonicalFileName, + /*isAbsolutePathAnUrl*/ true); + var sourceIndex = sourceToSourceIndexMap.get(source); + if (sourceIndex === undefined) { + sourceIndex = sources.length; + sources.push(source); + rawSources.push(fileName); + sourceToSourceIndexMap.set(source, sourceIndex); + } + exit(); + return sourceIndex; + } + function setSourceContent(sourceIndex, content) { + enter(); + if (content !== null) { + if (!sourcesContent) + sourcesContent = []; + while (sourcesContent.length < sourceIndex) { + // tslint:disable-next-line:no-null-keyword boolean-trivia + sourcesContent.push(null); + } + sourcesContent[sourceIndex] = content; + } + exit(); + } + function addName(name) { + enter(); + if (!nameToNameIndexMap) + nameToNameIndexMap = ts.createMap(); + var nameIndex = nameToNameIndexMap.get(name); + if (nameIndex === undefined) { + nameIndex = names.length; + names.push(name); + nameToNameIndexMap.set(name, nameIndex); + } + exit(); + return nameIndex; + } + function isNewGeneratedPosition(generatedLine, generatedCharacter) { + return !hasPending + || pendingGeneratedLine !== generatedLine + || pendingGeneratedCharacter !== generatedCharacter; + } + function isBacktrackingSourcePosition(sourceIndex, sourceLine, sourceCharacter) { + return sourceIndex !== undefined + && sourceLine !== undefined + && sourceCharacter !== undefined + && pendingSourceIndex === sourceIndex + && (pendingSourceLine > sourceLine + || pendingSourceLine === sourceLine && pendingSourceCharacter > sourceCharacter); + } + function addMapping(generatedLine, generatedCharacter, sourceIndex, sourceLine, sourceCharacter, nameIndex) { + ts.Debug.assert(generatedLine >= pendingGeneratedLine, "generatedLine cannot backtrack"); + ts.Debug.assert(generatedCharacter >= 0, "generatedCharacter cannot be negative"); + ts.Debug.assert(sourceIndex === undefined || sourceIndex >= 0, "sourceIndex cannot be negative"); + ts.Debug.assert(sourceLine === undefined || sourceLine >= 0, "sourceLine cannot be negative"); + ts.Debug.assert(sourceCharacter === undefined || sourceCharacter >= 0, "sourceCharacter cannot be negative"); + enter(); + // If this location wasn't recorded or the location in source is going backwards, record the mapping + if (isNewGeneratedPosition(generatedLine, generatedCharacter) || + isBacktrackingSourcePosition(sourceIndex, sourceLine, sourceCharacter)) { + commitPendingMapping(); + pendingGeneratedLine = generatedLine; + pendingGeneratedCharacter = generatedCharacter; + hasPendingSource = false; + hasPendingName = false; + hasPending = true; + } + if (sourceIndex !== undefined && sourceLine !== undefined && sourceCharacter !== undefined) { + pendingSourceIndex = sourceIndex; + pendingSourceLine = sourceLine; + pendingSourceCharacter = sourceCharacter; + hasPendingSource = true; + if (nameIndex !== undefined) { + pendingNameIndex = nameIndex; + hasPendingName = true; + } + } + exit(); + } + function appendSourceMap(generatedLine, generatedCharacter, map, sourceMapPath) { + var _a; + ts.Debug.assert(generatedLine >= pendingGeneratedLine, "generatedLine cannot backtrack"); + ts.Debug.assert(generatedCharacter >= 0, "generatedCharacter cannot be negative"); + enter(); + // First, decode the old component sourcemap + var sourceIndexToNewSourceIndexMap = []; + var nameIndexToNewNameIndexMap; + var mappingIterator = decodeMappings(map.mappings); + for (var _b = mappingIterator.next(), raw = _b.value, done = _b.done; !done; _a = mappingIterator.next(), raw = _a.value, done = _a.done, _a) { + // Then reencode all the updated mappings into the overall map + var newSourceIndex = void 0; + var newSourceLine = void 0; + var newSourceCharacter = void 0; + var newNameIndex = void 0; + if (raw.sourceIndex !== undefined) { + newSourceIndex = sourceIndexToNewSourceIndexMap[raw.sourceIndex]; + if (newSourceIndex === undefined) { + // Apply offsets to each position and fixup source entries + var rawPath = map.sources[raw.sourceIndex]; + var relativePath = map.sourceRoot ? ts.combinePaths(map.sourceRoot, rawPath) : rawPath; + var combinedPath = ts.combinePaths(ts.getDirectoryPath(sourceMapPath), relativePath); + sourceIndexToNewSourceIndexMap[raw.sourceIndex] = newSourceIndex = addSource(combinedPath); + if (map.sourcesContent && typeof map.sourcesContent[raw.sourceIndex] === "string") { + setSourceContent(newSourceIndex, map.sourcesContent[raw.sourceIndex]); + } + } + newSourceLine = raw.sourceLine; + newSourceCharacter = raw.sourceCharacter; + if (map.names && raw.nameIndex !== undefined) { + if (!nameIndexToNewNameIndexMap) + nameIndexToNewNameIndexMap = []; + newNameIndex = nameIndexToNewNameIndexMap[raw.nameIndex]; + if (newNameIndex === undefined) { + nameIndexToNewNameIndexMap[raw.nameIndex] = newNameIndex = addName(map.names[raw.nameIndex]); + } + } + } + var newGeneratedLine = raw.generatedLine + generatedLine; + var newGeneratedCharacter = raw.generatedLine === 0 ? raw.generatedCharacter + generatedCharacter : raw.generatedCharacter; + addMapping(newGeneratedLine, newGeneratedCharacter, newSourceIndex, newSourceLine, newSourceCharacter, newNameIndex); + } + exit(); + } + function shouldCommitMapping() { + return !hasLast + || lastGeneratedLine !== pendingGeneratedLine + || lastGeneratedCharacter !== pendingGeneratedCharacter + || lastSourceIndex !== pendingSourceIndex + || lastSourceLine !== pendingSourceLine + || lastSourceCharacter !== pendingSourceCharacter + || lastNameIndex !== pendingNameIndex; + } + function commitPendingMapping() { + if (!hasPending || !shouldCommitMapping()) { + return; + } + enter(); + // Line/Comma delimiters + if (lastGeneratedLine < pendingGeneratedLine) { + // Emit line delimiters + do { + mappings += ";"; + lastGeneratedLine++; + lastGeneratedCharacter = 0; + } while (lastGeneratedLine < pendingGeneratedLine); + } + else { + ts.Debug.assertEqual(lastGeneratedLine, pendingGeneratedLine, "generatedLine cannot backtrack"); + // Emit comma to separate the entry + if (hasLast) { + mappings += ","; + } + } + // 1. Relative generated character + mappings += base64VLQFormatEncode(pendingGeneratedCharacter - lastGeneratedCharacter); + lastGeneratedCharacter = pendingGeneratedCharacter; + if (hasPendingSource) { + // 2. Relative sourceIndex + mappings += base64VLQFormatEncode(pendingSourceIndex - lastSourceIndex); + lastSourceIndex = pendingSourceIndex; + // 3. Relative source line + mappings += base64VLQFormatEncode(pendingSourceLine - lastSourceLine); + lastSourceLine = pendingSourceLine; + // 4. Relative source character + mappings += base64VLQFormatEncode(pendingSourceCharacter - lastSourceCharacter); + lastSourceCharacter = pendingSourceCharacter; + if (hasPendingName) { + // 5. Relative nameIndex + mappings += base64VLQFormatEncode(pendingNameIndex - lastNameIndex); + lastNameIndex = pendingNameIndex; + } + } + hasLast = true; + exit(); + } + function toJSON() { + commitPendingMapping(); + return { + version: 3, + file: file, + sourceRoot: sourceRoot, + sources: sources, + names: names, + mappings: mappings, + sourcesContent: sourcesContent, + }; + } + } + ts.createSourceMapGenerator = createSourceMapGenerator; + // Sometimes tools can see the following line as a source mapping url comment, so we mangle it a bit (the [M]) + var sourceMapCommentRegExp = /^\/\/[@#] source[M]appingURL=(.+)\s*$/; + var whitespaceOrMapCommentRegExp = /^\s*(\/\/[@#] .*)?$/; + /** + * Tries to find the sourceMappingURL comment at the end of a file. + * @param text The source text of the file. + * @param lineStarts The line starts of the file. + */ + function tryGetSourceMappingURL(text, lineStarts) { + if (lineStarts === void 0) { lineStarts = ts.computeLineStarts(text); } + for (var index = lineStarts.length - 1; index >= 0; index--) { + var line = text.substring(lineStarts[index], lineStarts[index + 1]); + var comment = sourceMapCommentRegExp.exec(line); + if (comment) { + return comment[1]; + } + // If we see a non-whitespace/map comment-like line, break, to avoid scanning up the entire file + else if (!line.match(whitespaceOrMapCommentRegExp)) { + break; + } + } + } + ts.tryGetSourceMappingURL = tryGetSourceMappingURL; + function isStringOrNull(x) { + // tslint:disable-next-line:no-null-keyword + return typeof x === "string" || x === null; + } + function isRawSourceMap(x) { + // tslint:disable-next-line:no-null-keyword + return x !== null + && typeof x === "object" + && x.version === 3 + && typeof x.file === "string" + && typeof x.mappings === "string" + && ts.isArray(x.sources) && ts.every(x.sources, ts.isString) + && (x.sourceRoot === undefined || x.sourceRoot === null || typeof x.sourceRoot === "string") + && (x.sourcesContent === undefined || x.sourcesContent === null || ts.isArray(x.sourcesContent) && ts.every(x.sourcesContent, isStringOrNull)) + && (x.names === undefined || x.names === null || ts.isArray(x.names) && ts.every(x.names, ts.isString)); + } + ts.isRawSourceMap = isRawSourceMap; + function tryParseRawSourceMap(text) { + try { + var parsed = JSON.parse(text); + if (isRawSourceMap(parsed)) { + return parsed; + } + } + catch (_a) { + // empty + } + return undefined; + } + ts.tryParseRawSourceMap = tryParseRawSourceMap; + function decodeMappings(mappings) { + var done = false; + var pos = 0; + var generatedLine = 0; + var generatedCharacter = 0; + var sourceIndex = 0; + var sourceLine = 0; + var sourceCharacter = 0; + var nameIndex = 0; + var error; + return { + get pos() { return pos; }, + get error() { return error; }, + get state() { return captureMapping(/*hasSource*/ true, /*hasName*/ true); }, + next: function () { + while (!done && pos < mappings.length) { + var ch = mappings.charCodeAt(pos); + if (ch === 59 /* semicolon */) { + // new line + generatedLine++; + generatedCharacter = 0; + pos++; + continue; + } + if (ch === 44 /* comma */) { + // Next entry is on same line - no action needed + pos++; + continue; + } + var hasSource = false; + var hasName = false; + generatedCharacter += base64VLQFormatDecode(); + if (hasReportedError()) + return stopIterating(); + if (generatedCharacter < 0) + return setErrorAndStopIterating("Invalid generatedCharacter found"); + if (!isSourceMappingSegmentEnd()) { + hasSource = true; + sourceIndex += base64VLQFormatDecode(); + if (hasReportedError()) + return stopIterating(); + if (sourceIndex < 0) + return setErrorAndStopIterating("Invalid sourceIndex found"); + if (isSourceMappingSegmentEnd()) + return setErrorAndStopIterating("Unsupported Format: No entries after sourceIndex"); + sourceLine += base64VLQFormatDecode(); + if (hasReportedError()) + return stopIterating(); + if (sourceLine < 0) + return setErrorAndStopIterating("Invalid sourceLine found"); + if (isSourceMappingSegmentEnd()) + return setErrorAndStopIterating("Unsupported Format: No entries after sourceLine"); + sourceCharacter += base64VLQFormatDecode(); + if (hasReportedError()) + return stopIterating(); + if (sourceCharacter < 0) + return setErrorAndStopIterating("Invalid sourceCharacter found"); + if (!isSourceMappingSegmentEnd()) { + hasName = true; + nameIndex += base64VLQFormatDecode(); + if (hasReportedError()) + return stopIterating(); + if (nameIndex < 0) + return setErrorAndStopIterating("Invalid nameIndex found"); + if (!isSourceMappingSegmentEnd()) + return setErrorAndStopIterating("Unsupported Error Format: Entries after nameIndex"); + } + } + return { value: captureMapping(hasSource, hasName), done: done }; + } + return stopIterating(); + } + }; + function captureMapping(hasSource, hasName) { + return { + generatedLine: generatedLine, + generatedCharacter: generatedCharacter, + sourceIndex: hasSource ? sourceIndex : undefined, + sourceLine: hasSource ? sourceLine : undefined, + sourceCharacter: hasSource ? sourceCharacter : undefined, + nameIndex: hasName ? nameIndex : undefined + }; + } + function stopIterating() { + done = true; + return { value: undefined, done: true }; + } + function setError(message) { + if (error === undefined) { + error = message; + } + } + function setErrorAndStopIterating(message) { + setError(message); + return stopIterating(); + } + function hasReportedError() { + return error !== undefined; + } + function isSourceMappingSegmentEnd() { + return (pos === mappings.length || + mappings.charCodeAt(pos) === 44 /* comma */ || + mappings.charCodeAt(pos) === 59 /* semicolon */); + } + function base64VLQFormatDecode() { + var moreDigits = true; + var shiftCount = 0; + var value = 0; + for (; moreDigits; pos++) { + if (pos >= mappings.length) + return setError("Error in decoding base64VLQFormatDecode, past the mapping string"), -1; + // 6 digit number + var currentByte = base64FormatDecode(mappings.charCodeAt(pos)); + if (currentByte === -1) + return setError("Invalid character in VLQ"), -1; + // If msb is set, we still have more bits to continue + moreDigits = (currentByte & 32) !== 0; + // least significant 5 bits are the next msbs in the final value. + value = value | ((currentByte & 31) << shiftCount); + shiftCount += 5; + } + // Least significant bit if 1 represents negative and rest of the msb is actual absolute value + if ((value & 1) === 0) { + // + number + value = value >> 1; + } + else { + // - number + value = value >> 1; + value = -value; + } + return value; + } + } + ts.decodeMappings = decodeMappings; + function sameMapping(left, right) { + return left === right + || left.generatedLine === right.generatedLine + && left.generatedCharacter === right.generatedCharacter + && left.sourceIndex === right.sourceIndex + && left.sourceLine === right.sourceLine + && left.sourceCharacter === right.sourceCharacter + && left.nameIndex === right.nameIndex; + } + ts.sameMapping = sameMapping; + function isSourceMapping(mapping) { + return mapping.sourceIndex !== undefined + && mapping.sourceLine !== undefined + && mapping.sourceCharacter !== undefined; + } + ts.isSourceMapping = isSourceMapping; + function base64FormatEncode(value) { + return value >= 0 && value < 26 ? 65 /* A */ + value : + value >= 26 && value < 52 ? 97 /* a */ + value - 26 : + value >= 52 && value < 62 ? 48 /* _0 */ + value - 52 : + value === 62 ? 43 /* plus */ : + value === 63 ? 47 /* slash */ : + ts.Debug.fail(value + ": not a base64 value"); + } + function base64FormatDecode(ch) { + return ch >= 65 /* A */ && ch <= 90 /* Z */ ? ch - 65 /* A */ : + ch >= 97 /* a */ && ch <= 122 /* z */ ? ch - 97 /* a */ + 26 : + ch >= 48 /* _0 */ && ch <= 57 /* _9 */ ? ch - 48 /* _0 */ + 52 : + ch === 43 /* plus */ ? 62 : + ch === 47 /* slash */ ? 63 : + -1; + } + function base64VLQFormatEncode(inValue) { + // Add a new least significant bit that has the sign of the value. + // if negative number the least significant bit that gets added to the number has value 1 + // else least significant bit value that gets added is 0 + // eg. -1 changes to binary : 01 [1] => 3 + // +1 changes to binary : 01 [0] => 2 + if (inValue < 0) { + inValue = ((-inValue) << 1) + 1; + } + else { + inValue = inValue << 1; + } + // Encode 5 bits at a time starting from least significant bits + var encodedStr = ""; + do { + var currentDigit = inValue & 31; // 11111 + inValue = inValue >> 5; + if (inValue > 0) { + // There are still more digits to decode, set the msb (6th bit) + currentDigit = currentDigit | 32; + } + encodedStr = encodedStr + String.fromCharCode(base64FormatEncode(currentDigit)); + } while (inValue > 0); + return encodedStr; + } + function isSourceMappedPosition(value) { + return value.sourceIndex !== undefined + && value.sourcePosition !== undefined; + } + function sameMappedPosition(left, right) { + return left.generatedPosition === right.generatedPosition + && left.sourceIndex === right.sourceIndex + && left.sourcePosition === right.sourcePosition; + } + function compareSourcePositions(left, right) { + return ts.compareValues(left.sourceIndex, right.sourceIndex); + } + function compareGeneratedPositions(left, right) { + return ts.compareValues(left.generatedPosition, right.generatedPosition); + } + function getSourcePositionOfMapping(value) { + return value.sourcePosition; + } + function getGeneratedPositionOfMapping(value) { + return value.generatedPosition; + } + function createDocumentPositionMapper(host, map, mapPath) { + var mapDirectory = ts.getDirectoryPath(mapPath); + var sourceRoot = map.sourceRoot ? ts.getNormalizedAbsolutePath(map.sourceRoot, mapDirectory) : mapDirectory; + var generatedAbsoluteFilePath = ts.getNormalizedAbsolutePath(map.file, mapDirectory); + var generatedCanonicalFilePath = host.getCanonicalFileName(generatedAbsoluteFilePath); + var generatedFile = host.getSourceFileLike(generatedCanonicalFilePath); + var sourceFileAbsolutePaths = map.sources.map(function (source) { return ts.getNormalizedAbsolutePath(source, sourceRoot); }); + var sourceFileCanonicalPaths = sourceFileAbsolutePaths.map(function (source) { return host.getCanonicalFileName(source); }); + var sourceToSourceIndexMap = ts.createMapFromEntries(sourceFileCanonicalPaths.map(function (source, i) { return [source, i]; })); + var decodedMappings; + var generatedMappings; + var sourceMappings; + return { + getSourcePosition: getSourcePosition, + getGeneratedPosition: getGeneratedPosition + }; + function processMapping(mapping) { + var generatedPosition = generatedFile !== undefined + ? ts.getPositionOfLineAndCharacterWithEdits(generatedFile, mapping.generatedLine, mapping.generatedCharacter) + : -1; + var source; + var sourcePosition; + if (isSourceMapping(mapping)) { + var sourceFilePath = sourceFileCanonicalPaths[mapping.sourceIndex]; + var sourceFile = host.getSourceFileLike(sourceFilePath); + source = map.sources[mapping.sourceIndex]; + sourcePosition = sourceFile !== undefined + ? ts.getPositionOfLineAndCharacterWithEdits(sourceFile, mapping.sourceLine, mapping.sourceCharacter) + : -1; + } + return { + generatedPosition: generatedPosition, + source: source, + sourceIndex: mapping.sourceIndex, + sourcePosition: sourcePosition, + nameIndex: mapping.nameIndex + }; + } + function getDecodedMappings() { + if (decodedMappings === undefined) { + var decoder = decodeMappings(map.mappings); + var mappings = ts.arrayFrom(decoder, processMapping); + if (decoder.error !== undefined) { + if (host.log) { + host.log("Encountered error while decoding sourcemap: " + decoder.error); + } + decodedMappings = ts.emptyArray; + } + else { + decodedMappings = mappings; + } + } + return decodedMappings; + } + function getSourceMappings(sourceIndex) { + if (sourceMappings === undefined) { + var lists = []; + for (var _i = 0, _a = getDecodedMappings(); _i < _a.length; _i++) { + var mapping = _a[_i]; + if (!isSourceMappedPosition(mapping)) + continue; + var list = lists[mapping.sourceIndex]; + if (!list) + lists[mapping.sourceIndex] = list = []; + list.push(mapping); + } + sourceMappings = lists.map(function (list) { return ts.sortAndDeduplicate(list, compareSourcePositions, sameMappedPosition); }); + } + return sourceMappings[sourceIndex]; + } + function getGeneratedMappings() { + if (generatedMappings === undefined) { + var list = []; + for (var _i = 0, _a = getDecodedMappings(); _i < _a.length; _i++) { + var mapping = _a[_i]; + list.push(mapping); + } + generatedMappings = ts.sortAndDeduplicate(list, compareGeneratedPositions, sameMappedPosition); + } + return generatedMappings; + } + function getGeneratedPosition(loc) { + var sourceIndex = sourceToSourceIndexMap.get(host.getCanonicalFileName(loc.fileName)); + if (sourceIndex === undefined) + return loc; + var sourceMappings = getSourceMappings(sourceIndex); + if (!ts.some(sourceMappings)) + return loc; + var targetIndex = ts.binarySearchKey(sourceMappings, loc.pos, getSourcePositionOfMapping, ts.compareValues); + if (targetIndex < 0) { + // if no exact match, closest is 2's complement of result + targetIndex = ~targetIndex; + } + var mapping = sourceMappings[targetIndex]; + if (mapping === undefined || mapping.sourceIndex !== sourceIndex) { + return loc; + } + return { fileName: generatedAbsoluteFilePath, pos: mapping.generatedPosition }; // Closest pos + } + function getSourcePosition(loc) { + var generatedMappings = getGeneratedMappings(); + if (!ts.some(generatedMappings)) + return loc; + var targetIndex = ts.binarySearchKey(generatedMappings, loc.pos, getGeneratedPositionOfMapping, ts.compareValues); + if (targetIndex < 0) { + // if no exact match, closest is 2's complement of result + targetIndex = ~targetIndex; + } + var mapping = generatedMappings[targetIndex]; + if (mapping === undefined || !isSourceMappedPosition(mapping)) { + return loc; + } + return { fileName: sourceFileAbsolutePaths[mapping.sourceIndex], pos: mapping.sourcePosition }; // Closest pos + } + } + ts.createDocumentPositionMapper = createDocumentPositionMapper; + ts.identitySourceMapConsumer = { + getSourcePosition: ts.identity, + getGeneratedPosition: ts.identity + }; +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + function getOriginalNodeId(node) { + node = ts.getOriginalNode(node); + return node ? ts.getNodeId(node) : 0; + } + ts.getOriginalNodeId = getOriginalNodeId; + function containsDefaultReference(node) { + if (!node) + return false; + if (!ts.isNamedImports(node)) + return false; + return ts.some(node.elements, isNamedDefaultReference); + } + function isNamedDefaultReference(e) { + return e.propertyName !== undefined && e.propertyName.escapedText === "default" /* Default */; + } + function chainBundle(transformSourceFile) { + return transformSourceFileOrBundle; + function transformSourceFileOrBundle(node) { + return node.kind === 279 /* SourceFile */ ? transformSourceFile(node) : transformBundle(node); + } + function transformBundle(node) { + return ts.createBundle(ts.map(node.sourceFiles, transformSourceFile), node.prepends); + } + } + ts.chainBundle = chainBundle; + function getImportNeedsImportStarHelper(node) { + if (!!ts.getNamespaceDeclarationNode(node)) { + return true; + } + var bindings = node.importClause && node.importClause.namedBindings; + if (!bindings) { + return false; + } + if (!ts.isNamedImports(bindings)) + return false; + var defaultRefCount = 0; + for (var _i = 0, _a = bindings.elements; _i < _a.length; _i++) { + var binding = _a[_i]; + if (isNamedDefaultReference(binding)) { + defaultRefCount++; + } + } + // Import star is required if there's default named refs mixed with non-default refs, or if theres non-default refs and it has a default import + return (defaultRefCount > 0 && defaultRefCount !== bindings.elements.length) || (!!(bindings.elements.length - defaultRefCount) && ts.isDefaultImport(node)); + } + ts.getImportNeedsImportStarHelper = getImportNeedsImportStarHelper; + function getImportNeedsImportDefaultHelper(node) { + // Import default is needed if there's a default import or a default ref and no other refs (meaning an import star helper wasn't requested) + return !getImportNeedsImportStarHelper(node) && (ts.isDefaultImport(node) || (!!node.importClause && ts.isNamedImports(node.importClause.namedBindings) && containsDefaultReference(node.importClause.namedBindings))); // TODO: GH#18217 + } + ts.getImportNeedsImportDefaultHelper = getImportNeedsImportDefaultHelper; + function collectExternalModuleInfo(sourceFile, resolver, compilerOptions) { + var externalImports = []; + var exportSpecifiers = ts.createMultiMap(); + var exportedBindings = []; + var uniqueExports = ts.createMap(); + var exportedNames; + var hasExportDefault = false; + var exportEquals; + var hasExportStarsToExportValues = false; + var hasImportStarOrImportDefault = false; + for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { + var node = _a[_i]; + switch (node.kind) { + case 249 /* ImportDeclaration */: + // import "mod" + // import x from "mod" + // import * as x from "mod" + // import { x, y } from "mod" + externalImports.push(node); + hasImportStarOrImportDefault = hasImportStarOrImportDefault || getImportNeedsImportStarHelper(node) || getImportNeedsImportDefaultHelper(node); + break; + case 248 /* ImportEqualsDeclaration */: + if (node.moduleReference.kind === 259 /* ExternalModuleReference */) { + // import x = require("mod") + externalImports.push(node); + } + break; + case 255 /* ExportDeclaration */: + if (node.moduleSpecifier) { + if (!node.exportClause) { + // export * from "mod" + externalImports.push(node); + hasExportStarsToExportValues = true; + } + else { + // export { x, y } from "mod" + externalImports.push(node); + } + } + else { + // export { x, y } + for (var _b = 0, _c = node.exportClause.elements; _b < _c.length; _b++) { + var specifier = _c[_b]; + if (!uniqueExports.get(ts.idText(specifier.name))) { + var name = specifier.propertyName || specifier.name; + exportSpecifiers.add(ts.idText(name), specifier); + var decl = resolver.getReferencedImportDeclaration(name) + || resolver.getReferencedValueDeclaration(name); + if (decl) { + multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(decl), specifier.name); + } + uniqueExports.set(ts.idText(specifier.name), true); + exportedNames = ts.append(exportedNames, specifier.name); + } + } + } + break; + case 254 /* ExportAssignment */: + if (node.isExportEquals && !exportEquals) { + // export = x + exportEquals = node; + } + break; + case 219 /* VariableStatement */: + if (ts.hasModifier(node, 1 /* Export */)) { + for (var _d = 0, _e = node.declarationList.declarations; _d < _e.length; _d++) { + var decl = _e[_d]; + exportedNames = collectExportedVariableInfo(decl, uniqueExports, exportedNames); + } + } + break; + case 239 /* FunctionDeclaration */: + if (ts.hasModifier(node, 1 /* Export */)) { + if (ts.hasModifier(node, 512 /* Default */)) { + // export default function() { } + if (!hasExportDefault) { + multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), ts.getDeclarationName(node)); + hasExportDefault = true; + } + } + else { + // export function x() { } + var name = node.name; + if (!uniqueExports.get(ts.idText(name))) { + multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), name); + uniqueExports.set(ts.idText(name), true); + exportedNames = ts.append(exportedNames, name); + } + } + } + break; + case 240 /* ClassDeclaration */: + if (ts.hasModifier(node, 1 /* Export */)) { + if (ts.hasModifier(node, 512 /* Default */)) { + // export default class { } + if (!hasExportDefault) { + multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), ts.getDeclarationName(node)); + hasExportDefault = true; + } + } + else { + // export class x { } + var name = node.name; + if (name && !uniqueExports.get(ts.idText(name))) { + multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), name); + uniqueExports.set(ts.idText(name), true); + exportedNames = ts.append(exportedNames, name); + } + } + } + break; + } + } + var externalHelpersModuleName = ts.getOrCreateExternalHelpersModuleNameIfNeeded(sourceFile, compilerOptions, hasExportStarsToExportValues, hasImportStarOrImportDefault); + var externalHelpersImportDeclaration = externalHelpersModuleName && ts.createImportDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(externalHelpersModuleName)), ts.createLiteral(ts.externalHelpersModuleNameText)); + if (externalHelpersImportDeclaration) { + ts.addEmitFlags(externalHelpersImportDeclaration, 67108864 /* NeverApplyImportHelper */); + externalImports.unshift(externalHelpersImportDeclaration); + } + return { externalImports: externalImports, exportSpecifiers: exportSpecifiers, exportEquals: exportEquals, hasExportStarsToExportValues: hasExportStarsToExportValues, exportedBindings: exportedBindings, exportedNames: exportedNames, externalHelpersImportDeclaration: externalHelpersImportDeclaration }; + } + ts.collectExternalModuleInfo = collectExternalModuleInfo; + function collectExportedVariableInfo(decl, uniqueExports, exportedNames) { + if (ts.isBindingPattern(decl.name)) { + for (var _i = 0, _a = decl.name.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (!ts.isOmittedExpression(element)) { + exportedNames = collectExportedVariableInfo(element, uniqueExports, exportedNames); + } + } + } + else if (!ts.isGeneratedIdentifier(decl.name)) { + var text = ts.idText(decl.name); + if (!uniqueExports.get(text)) { + uniqueExports.set(text, true); + exportedNames = ts.append(exportedNames, decl.name); + } + } + return exportedNames; + } + /** Use a sparse array as a multi-map. */ + function multiMapSparseArrayAdd(map, key, value) { + var values = map[key]; + if (values) { + values.push(value); + } + else { + map[key] = values = [value]; + } + return values; + } + /** + * Used in the module transformer to check if an expression is reasonably without sideeffect, + * and thus better to copy into multiple places rather than to cache in a temporary variable + * - this is mostly subjective beyond the requirement that the expression not be sideeffecting + */ + function isSimpleCopiableExpression(expression) { + return ts.isStringLiteralLike(expression) || + expression.kind === 8 /* NumericLiteral */ || + ts.isKeyword(expression.kind) || + ts.isIdentifier(expression); + } + ts.isSimpleCopiableExpression = isSimpleCopiableExpression; + /** + * @param input Template string input strings + * @param args Names which need to be made file-level unique + */ + function helperString(input) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + return function (uniqueName) { + var result = ""; + for (var i = 0; i < args.length; i++) { + result += input[i]; + result += uniqueName(args[i]); + } + result += input[input.length - 1]; + return result; + }; + } + ts.helperString = helperString; +})(ts || (ts = {})); +/*@internal*/ +var ts; +(function (ts) { + var FlattenLevel; + (function (FlattenLevel) { + FlattenLevel[FlattenLevel["All"] = 0] = "All"; + FlattenLevel[FlattenLevel["ObjectRest"] = 1] = "ObjectRest"; + })(FlattenLevel = ts.FlattenLevel || (ts.FlattenLevel = {})); + /** + * Flattens a DestructuringAssignment or a VariableDeclaration to an expression. + * + * @param node The node to flatten. + * @param visitor An optional visitor used to visit initializers. + * @param context The transformation context. + * @param level Indicates the extent to which flattening should occur. + * @param needsValue An optional value indicating whether the value from the right-hand-side of + * the destructuring assignment is needed as part of a larger expression. + * @param createAssignmentCallback An optional callback used to create the assignment expression. + */ + function flattenDestructuringAssignment(node, visitor, context, level, needsValue, createAssignmentCallback) { + var location = node; + var value; + if (ts.isDestructuringAssignment(node)) { + value = node.right; + while (ts.isEmptyArrayLiteral(node.left) || ts.isEmptyObjectLiteral(node.left)) { + if (ts.isDestructuringAssignment(value)) { + location = node = value; + value = node.right; + } + else { + return ts.visitNode(value, visitor, ts.isExpression); + } + } + } + var expressions; + var flattenContext = { + context: context, + level: level, + downlevelIteration: !!context.getCompilerOptions().downlevelIteration, + hoistTempVariables: true, + emitExpression: emitExpression, + emitBindingOrAssignment: emitBindingOrAssignment, + createArrayBindingOrAssignmentPattern: makeArrayAssignmentPattern, + createObjectBindingOrAssignmentPattern: makeObjectAssignmentPattern, + createArrayBindingOrAssignmentElement: makeAssignmentElement, + visitor: visitor + }; + if (value) { + value = ts.visitNode(value, visitor, ts.isExpression); + if (ts.isIdentifier(value) && bindingOrAssignmentElementAssignsToName(node, value.escapedText)) { + // If the right-hand value of the assignment is also an assignment target then + // we need to cache the right-hand value. + value = ensureIdentifier(flattenContext, value, /*reuseIdentifierExpressions*/ false, location); + } + else if (needsValue) { + // If the right-hand value of the destructuring assignment needs to be preserved (as + // is the case when the destructuring assignment is part of a larger expression), + // then we need to cache the right-hand value. + // + // The source map location for the assignment should point to the entire binary + // expression. + value = ensureIdentifier(flattenContext, value, /*reuseIdentifierExpressions*/ true, location); + } + else if (ts.nodeIsSynthesized(node)) { + // Generally, the source map location for a destructuring assignment is the root + // expression. + // + // However, if the root expression is synthesized (as in the case + // of the initializer when transforming a ForOfStatement), then the source map + // location should point to the right-hand value of the expression. + location = value; + } + } + flattenBindingOrAssignmentElement(flattenContext, node, value, location, /*skipInitializer*/ ts.isDestructuringAssignment(node)); + if (value && needsValue) { + if (!ts.some(expressions)) { + return value; + } + expressions.push(value); + } + return ts.aggregateTransformFlags(ts.inlineExpressions(expressions)) || ts.createOmittedExpression(); + function emitExpression(expression) { + // NOTE: this completely disables source maps, but aligns with the behavior of + // `emitAssignment` in the old emitter. + ts.setEmitFlags(expression, 64 /* NoNestedSourceMaps */); + ts.aggregateTransformFlags(expression); + expressions = ts.append(expressions, expression); + } + function emitBindingOrAssignment(target, value, location, original) { + ts.Debug.assertNode(target, createAssignmentCallback ? ts.isIdentifier : ts.isExpression); + var expression = createAssignmentCallback + ? createAssignmentCallback(target, value, location) + : ts.setTextRange(ts.createAssignment(ts.visitNode(target, visitor, ts.isExpression), value), location); + expression.original = original; + emitExpression(expression); + } + } + ts.flattenDestructuringAssignment = flattenDestructuringAssignment; + function bindingOrAssignmentElementAssignsToName(element, escapedName) { + var target = ts.getTargetOfBindingOrAssignmentElement(element); // TODO: GH#18217 + if (ts.isBindingOrAssignmentPattern(target)) { + return bindingOrAssignmentPatternAssignsToName(target, escapedName); + } + else if (ts.isIdentifier(target)) { + return target.escapedText === escapedName; + } + return false; + } + function bindingOrAssignmentPatternAssignsToName(pattern, escapedName) { + var elements = ts.getElementsOfBindingOrAssignmentPattern(pattern); + for (var _i = 0, elements_3 = elements; _i < elements_3.length; _i++) { + var element = elements_3[_i]; + if (bindingOrAssignmentElementAssignsToName(element, escapedName)) { + return true; + } + } + return false; + } + /** + * Flattens a VariableDeclaration or ParameterDeclaration to one or more variable declarations. + * + * @param node The node to flatten. + * @param visitor An optional visitor used to visit initializers. + * @param context The transformation context. + * @param boundValue The value bound to the declaration. + * @param skipInitializer A value indicating whether to ignore the initializer of `node`. + * @param hoistTempVariables Indicates whether temporary variables should not be recorded in-line. + * @param level Indicates the extent to which flattening should occur. + */ + function flattenDestructuringBinding(node, visitor, context, level, rval, hoistTempVariables, skipInitializer) { + if (hoistTempVariables === void 0) { hoistTempVariables = false; } + var pendingExpressions; + var pendingDeclarations = []; + var declarations = []; + var flattenContext = { + context: context, + level: level, + downlevelIteration: !!context.getCompilerOptions().downlevelIteration, + hoistTempVariables: hoistTempVariables, + emitExpression: emitExpression, + emitBindingOrAssignment: emitBindingOrAssignment, + createArrayBindingOrAssignmentPattern: makeArrayBindingPattern, + createObjectBindingOrAssignmentPattern: makeObjectBindingPattern, + createArrayBindingOrAssignmentElement: makeBindingElement, + visitor: visitor + }; + if (ts.isVariableDeclaration(node)) { + var initializer = ts.getInitializerOfBindingOrAssignmentElement(node); + if (initializer && ts.isIdentifier(initializer) && bindingOrAssignmentElementAssignsToName(node, initializer.escapedText)) { + // If the right-hand value of the assignment is also an assignment target then + // we need to cache the right-hand value. + initializer = ensureIdentifier(flattenContext, initializer, /*reuseIdentifierExpressions*/ false, initializer); + node = ts.updateVariableDeclaration(node, node.name, node.type, initializer); + } + } + flattenBindingOrAssignmentElement(flattenContext, node, rval, node, skipInitializer); + if (pendingExpressions) { + var temp = ts.createTempVariable(/*recordTempVariable*/ undefined); + if (hoistTempVariables) { + var value = ts.inlineExpressions(pendingExpressions); + pendingExpressions = undefined; + emitBindingOrAssignment(temp, value, /*location*/ undefined, /*original*/ undefined); + } + else { + context.hoistVariableDeclaration(temp); + var pendingDeclaration = ts.last(pendingDeclarations); + pendingDeclaration.pendingExpressions = ts.append(pendingDeclaration.pendingExpressions, ts.createAssignment(temp, pendingDeclaration.value)); + ts.addRange(pendingDeclaration.pendingExpressions, pendingExpressions); + pendingDeclaration.value = temp; + } + } + for (var _i = 0, pendingDeclarations_1 = pendingDeclarations; _i < pendingDeclarations_1.length; _i++) { + var _a = pendingDeclarations_1[_i], pendingExpressions_1 = _a.pendingExpressions, name = _a.name, value = _a.value, location = _a.location, original = _a.original; + var variable = ts.createVariableDeclaration(name, + /*type*/ undefined, pendingExpressions_1 ? ts.inlineExpressions(ts.append(pendingExpressions_1, value)) : value); + variable.original = original; + ts.setTextRange(variable, location); + if (ts.isIdentifier(name)) { + ts.setEmitFlags(variable, 64 /* NoNestedSourceMaps */); + } + ts.aggregateTransformFlags(variable); + declarations.push(variable); + } + return declarations; + function emitExpression(value) { + pendingExpressions = ts.append(pendingExpressions, value); + } + function emitBindingOrAssignment(target, value, location, original) { + ts.Debug.assertNode(target, ts.isBindingName); + if (pendingExpressions) { + value = ts.inlineExpressions(ts.append(pendingExpressions, value)); + pendingExpressions = undefined; + } + pendingDeclarations.push({ pendingExpressions: pendingExpressions, name: target, value: value, location: location, original: original }); + } + } + ts.flattenDestructuringBinding = flattenDestructuringBinding; + /** + * Flattens a BindingOrAssignmentElement into zero or more bindings or assignments. + * + * @param flattenContext Options used to control flattening. + * @param element The element to flatten. + * @param value The current RHS value to assign to the element. + * @param location The location to use for source maps and comments. + * @param skipInitializer An optional value indicating whether to include the initializer + * for the element. + */ + function flattenBindingOrAssignmentElement(flattenContext, element, value, location, skipInitializer) { + if (!skipInitializer) { + var initializer = ts.visitNode(ts.getInitializerOfBindingOrAssignmentElement(element), flattenContext.visitor, ts.isExpression); + if (initializer) { + // Combine value and initializer + value = value ? createDefaultValueCheck(flattenContext, value, initializer, location) : initializer; + } + else if (!value) { + // Use 'void 0' in absence of value and initializer + value = ts.createVoidZero(); + } + } + var bindingTarget = ts.getTargetOfBindingOrAssignmentElement(element); // TODO: GH#18217 + if (ts.isObjectBindingOrAssignmentPattern(bindingTarget)) { + flattenObjectBindingOrAssignmentPattern(flattenContext, element, bindingTarget, value, location); + } + else if (ts.isArrayBindingOrAssignmentPattern(bindingTarget)) { + flattenArrayBindingOrAssignmentPattern(flattenContext, element, bindingTarget, value, location); + } + else { + flattenContext.emitBindingOrAssignment(bindingTarget, value, location, /*original*/ element); // TODO: GH#18217 + } + } + /** + * Flattens an ObjectBindingOrAssignmentPattern into zero or more bindings or assignments. + * + * @param flattenContext Options used to control flattening. + * @param parent The parent element of the pattern. + * @param pattern The ObjectBindingOrAssignmentPattern to flatten. + * @param value The current RHS value to assign to the element. + * @param location The location to use for source maps and comments. + */ + function flattenObjectBindingOrAssignmentPattern(flattenContext, parent, pattern, value, location) { + var elements = ts.getElementsOfBindingOrAssignmentPattern(pattern); + var numElements = elements.length; + if (numElements !== 1) { + // For anything other than a single-element destructuring we need to generate a temporary + // to ensure value is evaluated exactly once. Additionally, if we have zero elements + // we need to emit *something* to ensure that in case a 'var' keyword was already emitted, + // so in that case, we'll intentionally create that temporary. + var reuseIdentifierExpressions = !ts.isDeclarationBindingElement(parent) || numElements !== 0; + value = ensureIdentifier(flattenContext, value, reuseIdentifierExpressions, location); + } + var bindingElements; + var computedTempVariables; + for (var i = 0; i < numElements; i++) { + var element = elements[i]; + if (!ts.getRestIndicatorOfBindingOrAssignmentElement(element)) { + var propertyName = ts.getPropertyNameOfBindingOrAssignmentElement(element); + if (flattenContext.level >= 1 /* ObjectRest */ + && !(element.transformFlags & (131072 /* ContainsRestOrSpread */ | 262144 /* ContainsObjectRestOrSpread */)) + && !(ts.getTargetOfBindingOrAssignmentElement(element).transformFlags & (131072 /* ContainsRestOrSpread */ | 262144 /* ContainsObjectRestOrSpread */)) + && !ts.isComputedPropertyName(propertyName)) { + bindingElements = ts.append(bindingElements, element); + } + else { + if (bindingElements) { + flattenContext.emitBindingOrAssignment(flattenContext.createObjectBindingOrAssignmentPattern(bindingElements), value, location, pattern); + bindingElements = undefined; + } + var rhsValue = createDestructuringPropertyAccess(flattenContext, value, propertyName); + if (ts.isComputedPropertyName(propertyName)) { + computedTempVariables = ts.append(computedTempVariables, rhsValue.argumentExpression); + } + flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, /*location*/ element); + } + } + else if (i === numElements - 1) { + if (bindingElements) { + flattenContext.emitBindingOrAssignment(flattenContext.createObjectBindingOrAssignmentPattern(bindingElements), value, location, pattern); + bindingElements = undefined; + } + var rhsValue = createRestCall(flattenContext.context, value, elements, computedTempVariables, pattern); // TODO: GH#18217 + flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, element); + } + } + if (bindingElements) { + flattenContext.emitBindingOrAssignment(flattenContext.createObjectBindingOrAssignmentPattern(bindingElements), value, location, pattern); + } + } + /** + * Flattens an ArrayBindingOrAssignmentPattern into zero or more bindings or assignments. + * + * @param flattenContext Options used to control flattening. + * @param parent The parent element of the pattern. + * @param pattern The ArrayBindingOrAssignmentPattern to flatten. + * @param value The current RHS value to assign to the element. + * @param location The location to use for source maps and comments. + */ + function flattenArrayBindingOrAssignmentPattern(flattenContext, parent, pattern, value, location) { + var elements = ts.getElementsOfBindingOrAssignmentPattern(pattern); + var numElements = elements.length; + if (flattenContext.level < 1 /* ObjectRest */ && flattenContext.downlevelIteration) { + // Read the elements of the iterable into an array + value = ensureIdentifier(flattenContext, ts.createReadHelper(flattenContext.context, value, numElements > 0 && ts.getRestIndicatorOfBindingOrAssignmentElement(elements[numElements - 1]) + ? undefined + : numElements, location), + /*reuseIdentifierExpressions*/ false, location); + } + else if (numElements !== 1 && (flattenContext.level < 1 /* ObjectRest */ || numElements === 0) + || ts.every(elements, ts.isOmittedExpression)) { + // For anything other than a single-element destructuring we need to generate a temporary + // to ensure value is evaluated exactly once. Additionally, if we have zero elements + // we need to emit *something* to ensure that in case a 'var' keyword was already emitted, + // so in that case, we'll intentionally create that temporary. + // Or all the elements of the binding pattern are omitted expression such as "var [,] = [1,2]", + // then we will create temporary variable. + var reuseIdentifierExpressions = !ts.isDeclarationBindingElement(parent) || numElements !== 0; + value = ensureIdentifier(flattenContext, value, reuseIdentifierExpressions, location); + } + var bindingElements; + var restContainingElements; + for (var i = 0; i < numElements; i++) { + var element = elements[i]; + if (flattenContext.level >= 1 /* ObjectRest */) { + // If an array pattern contains an ObjectRest, we must cache the result so that we + // can perform the ObjectRest destructuring in a different declaration + if (element.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { + var temp = ts.createTempVariable(/*recordTempVariable*/ undefined); + if (flattenContext.hoistTempVariables) { + flattenContext.context.hoistVariableDeclaration(temp); + } + restContainingElements = ts.append(restContainingElements, [temp, element]); + bindingElements = ts.append(bindingElements, flattenContext.createArrayBindingOrAssignmentElement(temp)); + } + else { + bindingElements = ts.append(bindingElements, element); + } + } + else if (ts.isOmittedExpression(element)) { + continue; + } + else if (!ts.getRestIndicatorOfBindingOrAssignmentElement(element)) { + var rhsValue = ts.createElementAccess(value, i); + flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, /*location*/ element); + } + else if (i === numElements - 1) { + var rhsValue = ts.createArraySlice(value, i); + flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, /*location*/ element); + } + } + if (bindingElements) { + flattenContext.emitBindingOrAssignment(flattenContext.createArrayBindingOrAssignmentPattern(bindingElements), value, location, pattern); + } + if (restContainingElements) { + for (var _i = 0, restContainingElements_1 = restContainingElements; _i < restContainingElements_1.length; _i++) { + var _a = restContainingElements_1[_i], id = _a[0], element = _a[1]; + flattenBindingOrAssignmentElement(flattenContext, element, id, element); + } + } + } + /** + * Creates an expression used to provide a default value if a value is `undefined` at runtime. + * + * @param flattenContext Options used to control flattening. + * @param value The RHS value to test. + * @param defaultValue The default value to use if `value` is `undefined` at runtime. + * @param location The location to use for source maps and comments. + */ + function createDefaultValueCheck(flattenContext, value, defaultValue, location) { + value = ensureIdentifier(flattenContext, value, /*reuseIdentifierExpressions*/ true, location); + return ts.createConditional(ts.createTypeCheck(value, "undefined"), defaultValue, value); + } + /** + * Creates either a PropertyAccessExpression or an ElementAccessExpression for the + * right-hand side of a transformed destructuring assignment. + * + * @link https://tc39.github.io/ecma262/#sec-runtime-semantics-keyeddestructuringassignmentevaluation + * + * @param flattenContext Options used to control flattening. + * @param value The RHS value that is the source of the property. + * @param propertyName The destructuring property name. + */ + function createDestructuringPropertyAccess(flattenContext, value, propertyName) { + if (ts.isComputedPropertyName(propertyName)) { + var argumentExpression = ensureIdentifier(flattenContext, ts.visitNode(propertyName.expression, flattenContext.visitor), /*reuseIdentifierExpressions*/ false, /*location*/ propertyName); + return ts.createElementAccess(value, argumentExpression); + } + else if (ts.isStringOrNumericLiteralLike(propertyName)) { + var argumentExpression = ts.getSynthesizedClone(propertyName); + argumentExpression.text = argumentExpression.text; + return ts.createElementAccess(value, argumentExpression); + } + else { + var name = ts.createIdentifier(ts.idText(propertyName)); + return ts.createPropertyAccess(value, name); + } + } + /** + * Ensures that there exists a declared identifier whose value holds the given expression. + * This function is useful to ensure that the expression's value can be read from in subsequent expressions. + * Unless 'reuseIdentifierExpressions' is false, 'value' will be returned if it is just an identifier. + * + * @param flattenContext Options used to control flattening. + * @param value the expression whose value needs to be bound. + * @param reuseIdentifierExpressions true if identifier expressions can simply be returned; + * false if it is necessary to always emit an identifier. + * @param location The location to use for source maps and comments. + */ + function ensureIdentifier(flattenContext, value, reuseIdentifierExpressions, location) { + if (ts.isIdentifier(value) && reuseIdentifierExpressions) { + return value; + } + else { + var temp = ts.createTempVariable(/*recordTempVariable*/ undefined); + if (flattenContext.hoistTempVariables) { + flattenContext.context.hoistVariableDeclaration(temp); + flattenContext.emitExpression(ts.setTextRange(ts.createAssignment(temp, value), location)); + } + else { + flattenContext.emitBindingOrAssignment(temp, value, location, /*original*/ undefined); + } + return temp; + } + } + function makeArrayBindingPattern(elements) { + ts.Debug.assertEachNode(elements, ts.isArrayBindingElement); + return ts.createArrayBindingPattern(elements); + } + function makeArrayAssignmentPattern(elements) { + return ts.createArrayLiteral(ts.map(elements, ts.convertToArrayAssignmentElement)); + } + function makeObjectBindingPattern(elements) { + ts.Debug.assertEachNode(elements, ts.isBindingElement); + return ts.createObjectBindingPattern(elements); + } + function makeObjectAssignmentPattern(elements) { + return ts.createObjectLiteral(ts.map(elements, ts.convertToObjectAssignmentElement)); + } + function makeBindingElement(name) { + return ts.createBindingElement(/*dotDotDotToken*/ undefined, /*propertyName*/ undefined, name); + } + function makeAssignmentElement(name) { + return name; + } + var restHelper = { + name: "typescript:rest", + scoped: false, + text: "\n var __rest = (this && this.__rest) || function (s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) if (e.indexOf(p[i]) < 0)\n t[p[i]] = s[p[i]];\n return t;\n };" + }; + /** Given value: o, propName: p, pattern: { a, b, ...p } from the original statement + * `{ a, b, ...p } = o`, create `p = __rest(o, ["a", "b"]);` + */ + function createRestCall(context, value, elements, computedTempVariables, location) { + context.requestEmitHelper(restHelper); + var propertyNames = []; + var computedTempVariableOffset = 0; + for (var i = 0; i < elements.length - 1; i++) { + var propertyName = ts.getPropertyNameOfBindingOrAssignmentElement(elements[i]); + if (propertyName) { + if (ts.isComputedPropertyName(propertyName)) { + var temp = computedTempVariables[computedTempVariableOffset]; + computedTempVariableOffset++; + // typeof _tmp === "symbol" ? _tmp : _tmp + "" + propertyNames.push(ts.createConditional(ts.createTypeCheck(temp, "symbol"), temp, ts.createAdd(temp, ts.createLiteral("")))); + } + else { + propertyNames.push(ts.createLiteral(propertyName)); + } + } + } + return ts.createCall(ts.getHelperName("__rest"), + /*typeArguments*/ undefined, [ + value, + ts.setTextRange(ts.createArrayLiteral(propertyNames), location) + ]); + } +})(ts || (ts = {})); +/*@internal*/ +var ts; +(function (ts) { + /** + * Indicates whether to emit type metadata in the new format. + */ + var USE_NEW_TYPE_METADATA_FORMAT = false; + var TypeScriptSubstitutionFlags; + (function (TypeScriptSubstitutionFlags) { + /** Enables substitutions for decorated classes. */ + TypeScriptSubstitutionFlags[TypeScriptSubstitutionFlags["ClassAliases"] = 1] = "ClassAliases"; + /** Enables substitutions for namespace exports. */ + TypeScriptSubstitutionFlags[TypeScriptSubstitutionFlags["NamespaceExports"] = 2] = "NamespaceExports"; + /* Enables substitutions for unqualified enum members */ + TypeScriptSubstitutionFlags[TypeScriptSubstitutionFlags["NonQualifiedEnumMembers"] = 8] = "NonQualifiedEnumMembers"; + })(TypeScriptSubstitutionFlags || (TypeScriptSubstitutionFlags = {})); + var ClassFacts; + (function (ClassFacts) { + ClassFacts[ClassFacts["None"] = 0] = "None"; + ClassFacts[ClassFacts["HasStaticInitializedProperties"] = 1] = "HasStaticInitializedProperties"; + ClassFacts[ClassFacts["HasConstructorDecorators"] = 2] = "HasConstructorDecorators"; + ClassFacts[ClassFacts["HasMemberDecorators"] = 4] = "HasMemberDecorators"; + ClassFacts[ClassFacts["IsExportOfNamespace"] = 8] = "IsExportOfNamespace"; + ClassFacts[ClassFacts["IsNamedExternalExport"] = 16] = "IsNamedExternalExport"; + ClassFacts[ClassFacts["IsDefaultExternalExport"] = 32] = "IsDefaultExternalExport"; + ClassFacts[ClassFacts["IsDerivedClass"] = 64] = "IsDerivedClass"; + ClassFacts[ClassFacts["UseImmediatelyInvokedFunctionExpression"] = 128] = "UseImmediatelyInvokedFunctionExpression"; + ClassFacts[ClassFacts["HasAnyDecorators"] = 6] = "HasAnyDecorators"; + ClassFacts[ClassFacts["NeedsName"] = 5] = "NeedsName"; + ClassFacts[ClassFacts["MayNeedImmediatelyInvokedFunctionExpression"] = 7] = "MayNeedImmediatelyInvokedFunctionExpression"; + ClassFacts[ClassFacts["IsExported"] = 56] = "IsExported"; + })(ClassFacts || (ClassFacts = {})); + function transformTypeScript(context) { + var startLexicalEnvironment = context.startLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; + var resolver = context.getEmitResolver(); + var compilerOptions = context.getCompilerOptions(); + var strictNullChecks = ts.getStrictOptionValue(compilerOptions, "strictNullChecks"); + var languageVersion = ts.getEmitScriptTarget(compilerOptions); + var moduleKind = ts.getEmitModuleKind(compilerOptions); + // Save the previous transformation hooks. + var previousOnEmitNode = context.onEmitNode; + var previousOnSubstituteNode = context.onSubstituteNode; + // Set new transformation hooks. + context.onEmitNode = onEmitNode; + context.onSubstituteNode = onSubstituteNode; + // Enable substitution for property/element access to emit const enum values. + context.enableSubstitution(189 /* PropertyAccessExpression */); + context.enableSubstitution(190 /* ElementAccessExpression */); + // These variables contain state that changes as we descend into the tree. + var currentSourceFile; + var currentNamespace; + var currentNamespaceContainerName; + var currentLexicalScope; + var currentNameScope; + var currentScopeFirstDeclarationsOfName; + /** + * Keeps track of whether expression substitution has been enabled for specific edge cases. + * They are persisted between each SourceFile transformation and should not be reset. + */ + var enabledSubstitutions; + /** + * A map that keeps track of aliases created for classes with decorators to avoid issues + * with the double-binding behavior of classes. + */ + var classAliases; + /** + * Keeps track of whether we are within any containing namespaces when performing + * just-in-time substitution while printing an expression identifier. + */ + var applicableSubstitutions; + /** + * Tracks what computed name expressions originating from elided names must be inlined + * at the next execution site, in document order + */ + var pendingExpressions; + return transformSourceFileOrBundle; + function transformSourceFileOrBundle(node) { + if (node.kind === 280 /* Bundle */) { + return transformBundle(node); + } + return transformSourceFile(node); + } + function transformBundle(node) { + return ts.createBundle(node.sourceFiles.map(transformSourceFile), ts.mapDefined(node.prepends, function (prepend) { + if (prepend.kind === 282 /* InputFiles */) { + return ts.createUnparsedSourceFile(prepend.javascriptText, prepend.javascriptMapPath, prepend.javascriptMapText); + } + return prepend; + })); + } + /** + * Transform TypeScript-specific syntax in a SourceFile. + * + * @param node A SourceFile node. + */ + function transformSourceFile(node) { + if (node.isDeclarationFile) { + return node; + } + currentSourceFile = node; + var visited = saveStateAndInvoke(node, visitSourceFile); + ts.addEmitHelpers(visited, context.readEmitHelpers()); + currentSourceFile = undefined; + return visited; + } + /** + * Visits a node, saving and restoring state variables on the stack. + * + * @param node The node to visit. + */ + function saveStateAndInvoke(node, f) { + // Save state + var savedCurrentScope = currentLexicalScope; + var savedCurrentNameScope = currentNameScope; + var savedCurrentScopeFirstDeclarationsOfName = currentScopeFirstDeclarationsOfName; + // Handle state changes before visiting a node. + onBeforeVisitNode(node); + var visited = f(node); + // Restore state + if (currentLexicalScope !== savedCurrentScope) { + currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName; + } + currentLexicalScope = savedCurrentScope; + currentNameScope = savedCurrentNameScope; + return visited; + } + /** + * Performs actions that should always occur immediately before visiting a node. + * + * @param node The node to visit. + */ + function onBeforeVisitNode(node) { + switch (node.kind) { + case 279 /* SourceFile */: + case 246 /* CaseBlock */: + case 245 /* ModuleBlock */: + case 218 /* Block */: + currentLexicalScope = node; + currentNameScope = undefined; + currentScopeFirstDeclarationsOfName = undefined; + break; + case 240 /* ClassDeclaration */: + case 239 /* FunctionDeclaration */: + if (ts.hasModifier(node, 2 /* Ambient */)) { + break; + } + // Record these declarations provided that they have a name. + if (node.name) { + recordEmittedDeclarationInScope(node); + } + else { + // These nodes should always have names unless they are default-exports; + // however, class declaration parsing allows for undefined names, so syntactically invalid + // programs may also have an undefined name. + ts.Debug.assert(node.kind === 240 /* ClassDeclaration */ || ts.hasModifier(node, 512 /* Default */)); + } + if (ts.isClassDeclaration(node)) { + // XXX: should probably also cover interfaces and type aliases that can have type variables? + currentNameScope = node; + } + break; + } + } + /** + * General-purpose node visitor. + * + * @param node The node to visit. + */ + function visitor(node) { + return saveStateAndInvoke(node, visitorWorker); + } + /** + * Visits and possibly transforms any node. + * + * @param node The node to visit. + */ + function visitorWorker(node) { + if (node.transformFlags & 1 /* TypeScript */) { + // This node is explicitly marked as TypeScript, so we should transform the node. + return visitTypeScript(node); + } + else if (node.transformFlags & 2 /* ContainsTypeScript */) { + // This node contains TypeScript, so we should visit its children. + return ts.visitEachChild(node, visitor, context); + } + return node; + } + /** + * Specialized visitor that visits the immediate children of a SourceFile. + * + * @param node The node to visit. + */ + function sourceElementVisitor(node) { + return saveStateAndInvoke(node, sourceElementVisitorWorker); + } + /** + * Specialized visitor that visits the immediate children of a SourceFile. + * + * @param node The node to visit. + */ + function sourceElementVisitorWorker(node) { + switch (node.kind) { + case 249 /* ImportDeclaration */: + case 248 /* ImportEqualsDeclaration */: + case 254 /* ExportAssignment */: + case 255 /* ExportDeclaration */: + return visitEllidableStatement(node); + default: + return visitorWorker(node); + } + } + function visitEllidableStatement(node) { + var parsed = ts.getParseTreeNode(node); + if (parsed !== node) { + // If the node has been transformed by a `before` transformer, perform no ellision on it + // As the type information we would attempt to lookup to perform ellision is potentially unavailable for the synthesized nodes + // We do not reuse `visitorWorker`, as the ellidable statement syntax kinds are technically unrecognized by the switch-case in `visitTypeScript`, + // and will trigger debug failures when debug verbosity is turned up + if (node.transformFlags & 2 /* ContainsTypeScript */) { + // This node contains TypeScript, so we should visit its children. + return ts.visitEachChild(node, visitor, context); + } + // Otherwise, we can just return the node + return node; + } + switch (node.kind) { + case 249 /* ImportDeclaration */: + return visitImportDeclaration(node); + case 248 /* ImportEqualsDeclaration */: + return visitImportEqualsDeclaration(node); + case 254 /* ExportAssignment */: + return visitExportAssignment(node); + case 255 /* ExportDeclaration */: + return visitExportDeclaration(node); + default: + ts.Debug.fail("Unhandled ellided statement"); + } + } + /** + * Specialized visitor that visits the immediate children of a namespace. + * + * @param node The node to visit. + */ + function namespaceElementVisitor(node) { + return saveStateAndInvoke(node, namespaceElementVisitorWorker); + } + /** + * Specialized visitor that visits the immediate children of a namespace. + * + * @param node The node to visit. + */ + function namespaceElementVisitorWorker(node) { + if (node.kind === 255 /* ExportDeclaration */ || + node.kind === 249 /* ImportDeclaration */ || + node.kind === 250 /* ImportClause */ || + (node.kind === 248 /* ImportEqualsDeclaration */ && + node.moduleReference.kind === 259 /* ExternalModuleReference */)) { + // do not emit ES6 imports and exports since they are illegal inside a namespace + return undefined; + } + else if (node.transformFlags & 1 /* TypeScript */ || ts.hasModifier(node, 1 /* Export */)) { + // This node is explicitly marked as TypeScript, or is exported at the namespace + // level, so we should transform the node. + return visitTypeScript(node); + } + else if (node.transformFlags & 2 /* ContainsTypeScript */) { + // This node contains TypeScript, so we should visit its children. + return ts.visitEachChild(node, visitor, context); + } + return node; + } + /** + * Specialized visitor that visits the immediate children of a class with TypeScript syntax. + * + * @param node The node to visit. + */ + function classElementVisitor(node) { + return saveStateAndInvoke(node, classElementVisitorWorker); + } + /** + * Specialized visitor that visits the immediate children of a class with TypeScript syntax. + * + * @param node The node to visit. + */ + function classElementVisitorWorker(node) { + switch (node.kind) { + case 157 /* Constructor */: + // TypeScript constructors are transformed in `visitClassDeclaration`. + // We elide them here as `visitorWorker` checks transform flags, which could + // erronously include an ES6 constructor without TypeScript syntax. + return undefined; + case 154 /* PropertyDeclaration */: + case 162 /* IndexSignature */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 156 /* MethodDeclaration */: + // Fallback to the default visit behavior. + return visitorWorker(node); + case 217 /* SemicolonClassElement */: + return node; + default: + return ts.Debug.failBadSyntaxKind(node); + } + } + function modifierVisitor(node) { + if (ts.modifierToFlag(node.kind) & 2270 /* TypeScriptModifier */) { + return undefined; + } + else if (currentNamespace && node.kind === 85 /* ExportKeyword */) { + return undefined; + } + return node; + } + /** + * Branching visitor, visits a TypeScript syntax node. + * + * @param node The node to visit. + */ + function visitTypeScript(node) { + if (ts.hasModifier(node, 2 /* Ambient */) && ts.isStatement(node)) { + // TypeScript ambient declarations are elided, but some comments may be preserved. + // See the implementation of `getLeadingComments` in comments.ts for more details. + return ts.createNotEmittedStatement(node); + } + switch (node.kind) { + case 85 /* ExportKeyword */: + case 80 /* DefaultKeyword */: + // ES6 export and default modifiers are elided when inside a namespace. + return currentNamespace ? undefined : node; + case 115 /* PublicKeyword */: + case 113 /* PrivateKeyword */: + case 114 /* ProtectedKeyword */: + case 118 /* AbstractKeyword */: + case 77 /* ConstKeyword */: + case 125 /* DeclareKeyword */: + case 133 /* ReadonlyKeyword */: + // TypeScript accessibility and readonly modifiers are elided. + case 169 /* ArrayType */: + case 170 /* TupleType */: + case 171 /* OptionalType */: + case 172 /* RestType */: + case 168 /* TypeLiteral */: + case 163 /* TypePredicate */: + case 150 /* TypeParameter */: + case 120 /* AnyKeyword */: + case 143 /* UnknownKeyword */: + case 123 /* BooleanKeyword */: + case 138 /* StringKeyword */: + case 135 /* NumberKeyword */: + case 132 /* NeverKeyword */: + case 106 /* VoidKeyword */: + case 139 /* SymbolKeyword */: + case 166 /* ConstructorType */: + case 165 /* FunctionType */: + case 167 /* TypeQuery */: + case 164 /* TypeReference */: + case 173 /* UnionType */: + case 174 /* IntersectionType */: + case 175 /* ConditionalType */: + case 177 /* ParenthesizedType */: + case 178 /* ThisType */: + case 179 /* TypeOperator */: + case 180 /* IndexedAccessType */: + case 181 /* MappedType */: + case 182 /* LiteralType */: + // TypeScript type nodes are elided. + case 162 /* IndexSignature */: + // TypeScript index signatures are elided. + case 152 /* Decorator */: + // TypeScript decorators are elided. They will be emitted as part of visitClassDeclaration. + case 242 /* TypeAliasDeclaration */: + // TypeScript type-only declarations are elided. + return undefined; + case 154 /* PropertyDeclaration */: + // TypeScript property declarations are elided. However their names are still visited, and can potentially be retained if they could have sideeffects + return visitPropertyDeclaration(node); + case 247 /* NamespaceExportDeclaration */: + // TypeScript namespace export declarations are elided. + return undefined; + case 157 /* Constructor */: + return visitConstructor(node); + case 241 /* InterfaceDeclaration */: + // TypeScript interfaces are elided, but some comments may be preserved. + // See the implementation of `getLeadingComments` in comments.ts for more details. + return ts.createNotEmittedStatement(node); + case 240 /* ClassDeclaration */: + // This is a class declaration with TypeScript syntax extensions. + // + // TypeScript class syntax extensions include: + // - decorators + // - optional `implements` heritage clause + // - parameter property assignments in the constructor + // - property declarations + // - index signatures + // - method overload signatures + return visitClassDeclaration(node); + case 209 /* ClassExpression */: + // This is a class expression with TypeScript syntax extensions. + // + // TypeScript class syntax extensions include: + // - decorators + // - optional `implements` heritage clause + // - parameter property assignments in the constructor + // - property declarations + // - index signatures + // - method overload signatures + return visitClassExpression(node); + case 273 /* HeritageClause */: + // This is a heritage clause with TypeScript syntax extensions. + // + // TypeScript heritage clause extensions include: + // - `implements` clause + return visitHeritageClause(node); + case 211 /* ExpressionWithTypeArguments */: + // TypeScript supports type arguments on an expression in an `extends` heritage clause. + return visitExpressionWithTypeArguments(node); + case 156 /* MethodDeclaration */: + // TypeScript method declarations may have decorators, modifiers + // or type annotations. + return visitMethodDeclaration(node); + case 158 /* GetAccessor */: + // Get Accessors can have TypeScript modifiers, decorators, and type annotations. + return visitGetAccessor(node); + case 159 /* SetAccessor */: + // Set Accessors can have TypeScript modifiers and type annotations. + return visitSetAccessor(node); + case 239 /* FunctionDeclaration */: + // Typescript function declarations can have modifiers, decorators, and type annotations. + return visitFunctionDeclaration(node); + case 196 /* FunctionExpression */: + // TypeScript function expressions can have modifiers and type annotations. + return visitFunctionExpression(node); + case 197 /* ArrowFunction */: + // TypeScript arrow functions can have modifiers and type annotations. + return visitArrowFunction(node); + case 151 /* Parameter */: + // This is a parameter declaration with TypeScript syntax extensions. + // + // TypeScript parameter declaration syntax extensions include: + // - decorators + // - accessibility modifiers + // - the question mark (?) token for optional parameters + // - type annotations + // - this parameters + return visitParameter(node); + case 195 /* ParenthesizedExpression */: + // ParenthesizedExpressions are TypeScript if their expression is a + // TypeAssertion or AsExpression + return visitParenthesizedExpression(node); + case 194 /* TypeAssertionExpression */: + case 212 /* AsExpression */: + // TypeScript type assertions are removed, but their subtrees are preserved. + return visitAssertionExpression(node); + case 191 /* CallExpression */: + return visitCallExpression(node); + case 192 /* NewExpression */: + return visitNewExpression(node); + case 193 /* TaggedTemplateExpression */: + return visitTaggedTemplateExpression(node); + case 213 /* NonNullExpression */: + // TypeScript non-null expressions are removed, but their subtrees are preserved. + return visitNonNullExpression(node); + case 243 /* EnumDeclaration */: + // TypeScript enum declarations do not exist in ES6 and must be rewritten. + return visitEnumDeclaration(node); + case 219 /* VariableStatement */: + // TypeScript namespace exports for variable statements must be transformed. + return visitVariableStatement(node); + case 237 /* VariableDeclaration */: + return visitVariableDeclaration(node); + case 244 /* ModuleDeclaration */: + // TypeScript namespace declarations must be transformed. + return visitModuleDeclaration(node); + case 248 /* ImportEqualsDeclaration */: + // TypeScript namespace or external module import. + return visitImportEqualsDeclaration(node); + default: + return ts.Debug.failBadSyntaxKind(node); + } + } + function visitSourceFile(node) { + var alwaysStrict = ts.getStrictOptionValue(compilerOptions, "alwaysStrict") && + !(ts.isExternalModule(node) && moduleKind >= ts.ModuleKind.ES2015) && + !ts.isJsonSourceFile(node); + return ts.updateSourceFileNode(node, ts.visitLexicalEnvironment(node.statements, sourceElementVisitor, context, /*start*/ 0, alwaysStrict)); + } + /** + * Tests whether we should emit a __decorate call for a class declaration. + */ + function shouldEmitDecorateCallForClass(node) { + if (node.decorators && node.decorators.length > 0) { + return true; + } + var constructor = ts.getFirstConstructorWithBody(node); + if (constructor) { + return ts.forEach(constructor.parameters, shouldEmitDecorateCallForParameter); + } + return false; + } + /** + * Tests whether we should emit a __decorate call for a parameter declaration. + */ + function shouldEmitDecorateCallForParameter(parameter) { + return parameter.decorators !== undefined && parameter.decorators.length > 0; + } + function getClassFacts(node, staticProperties) { + var facts = 0 /* None */; + if (ts.some(staticProperties)) + facts |= 1 /* HasStaticInitializedProperties */; + var extendsClauseElement = ts.getEffectiveBaseTypeNode(node); + if (extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 96 /* NullKeyword */) + facts |= 64 /* IsDerivedClass */; + if (shouldEmitDecorateCallForClass(node)) + facts |= 2 /* HasConstructorDecorators */; + if (ts.childIsDecorated(node)) + facts |= 4 /* HasMemberDecorators */; + if (isExportOfNamespace(node)) + facts |= 8 /* IsExportOfNamespace */; + else if (isDefaultExternalModuleExport(node)) + facts |= 32 /* IsDefaultExternalExport */; + else if (isNamedExternalModuleExport(node)) + facts |= 16 /* IsNamedExternalExport */; + if (languageVersion <= 1 /* ES5 */ && (facts & 7 /* MayNeedImmediatelyInvokedFunctionExpression */)) + facts |= 128 /* UseImmediatelyInvokedFunctionExpression */; + return facts; + } + /** + * Transforms a class declaration with TypeScript syntax into compatible ES6. + * + * This function will only be called when one of the following conditions are met: + * - The class has decorators. + * - The class has property declarations with initializers. + * - The class contains a constructor that contains parameters with accessibility modifiers. + * - The class is an export in a TypeScript namespace. + * + * @param node The node to transform. + */ + function visitClassDeclaration(node) { + var savedPendingExpressions = pendingExpressions; + pendingExpressions = undefined; + var staticProperties = getInitializedProperties(node, /*isStatic*/ true); + var facts = getClassFacts(node, staticProperties); + if (facts & 128 /* UseImmediatelyInvokedFunctionExpression */) { + context.startLexicalEnvironment(); + } + var name = node.name || (facts & 5 /* NeedsName */ ? ts.getGeneratedNameForNode(node) : undefined); + var classStatement = facts & 2 /* HasConstructorDecorators */ + ? createClassDeclarationHeadWithDecorators(node, name, facts) + : createClassDeclarationHeadWithoutDecorators(node, name, facts); + var statements = [classStatement]; + // Write any pending expressions from elided or moved computed property names + if (ts.some(pendingExpressions)) { + statements.push(ts.createExpressionStatement(ts.inlineExpressions(pendingExpressions))); + } + pendingExpressions = savedPendingExpressions; + // Emit static property assignment. Because classDeclaration is lexically evaluated, + // it is safe to emit static property assignment after classDeclaration + // From ES6 specification: + // HasLexicalDeclaration (N) : Determines if the argument identifier has a binding in this environment record that was created using + // a lexical declaration such as a LexicalDeclaration or a ClassDeclaration. + if (facts & 1 /* HasStaticInitializedProperties */) { + addInitializedPropertyStatements(statements, staticProperties, facts & 128 /* UseImmediatelyInvokedFunctionExpression */ ? ts.getInternalName(node) : ts.getLocalName(node)); + } + // Write any decorators of the node. + addClassElementDecorationStatements(statements, node, /*isStatic*/ false); + addClassElementDecorationStatements(statements, node, /*isStatic*/ true); + addConstructorDecorationStatement(statements, node); + if (facts & 128 /* UseImmediatelyInvokedFunctionExpression */) { + // When we emit a TypeScript class down to ES5, we must wrap it in an IIFE so that the + // 'es2015' transformer can properly nest static initializers and decorators. The result + // looks something like: + // + // var C = function () { + // class C { + // } + // C.static_prop = 1; + // return C; + // }(); + // + var closingBraceLocation = ts.createTokenRange(ts.skipTrivia(currentSourceFile.text, node.members.end), 19 /* CloseBraceToken */); + var localName = ts.getInternalName(node); + // The following partially-emitted expression exists purely to align our sourcemap + // emit with the original emitter. + var outer = ts.createPartiallyEmittedExpression(localName); + outer.end = closingBraceLocation.end; + ts.setEmitFlags(outer, 1536 /* NoComments */); + var statement = ts.createReturn(outer); + statement.pos = closingBraceLocation.pos; + ts.setEmitFlags(statement, 1536 /* NoComments */ | 384 /* NoTokenSourceMaps */); + statements.push(statement); + ts.addStatementsAfterPrologue(statements, context.endLexicalEnvironment()); + var iife = ts.createImmediatelyInvokedArrowFunction(statements); + ts.setEmitFlags(iife, 33554432 /* TypeScriptClassWrapper */); + var varStatement = ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ false), + /*type*/ undefined, iife) + ])); + ts.setOriginalNode(varStatement, node); + ts.setCommentRange(varStatement, node); + ts.setSourceMapRange(varStatement, ts.moveRangePastDecorators(node)); + ts.startOnNewLine(varStatement); + statements = [varStatement]; + } + // If the class is exported as part of a TypeScript namespace, emit the namespace export. + // Otherwise, if the class was exported at the top level and was decorated, emit an export + // declaration or export default for the class. + if (facts & 8 /* IsExportOfNamespace */) { + addExportMemberAssignment(statements, node); + } + else if (facts & 128 /* UseImmediatelyInvokedFunctionExpression */ || facts & 2 /* HasConstructorDecorators */) { + if (facts & 32 /* IsDefaultExternalExport */) { + statements.push(ts.createExportDefault(ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true))); + } + else if (facts & 16 /* IsNamedExternalExport */) { + statements.push(ts.createExternalModuleExport(ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true))); + } + } + if (statements.length > 1) { + // Add a DeclarationMarker as a marker for the end of the declaration + statements.push(ts.createEndOfDeclarationMarker(node)); + ts.setEmitFlags(classStatement, ts.getEmitFlags(classStatement) | 4194304 /* HasEndOfDeclarationMarker */); + } + return ts.singleOrMany(statements); + } + /** + * Transforms a non-decorated class declaration and appends the resulting statements. + * + * @param node A ClassDeclaration node. + * @param name The name of the class. + * @param facts Precomputed facts about the class. + */ + function createClassDeclarationHeadWithoutDecorators(node, name, facts) { + // ${modifiers} class ${name} ${heritageClauses} { + // ${members} + // } + // we do not emit modifiers on the declaration if we are emitting an IIFE + var modifiers = !(facts & 128 /* UseImmediatelyInvokedFunctionExpression */) + ? ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier) + : undefined; + var classDeclaration = ts.createClassDeclaration( + /*decorators*/ undefined, modifiers, name, + /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node, (facts & 64 /* IsDerivedClass */) !== 0)); + // To better align with the old emitter, we should not emit a trailing source map + // entry if the class has static properties. + var emitFlags = ts.getEmitFlags(node); + if (facts & 1 /* HasStaticInitializedProperties */) { + emitFlags |= 32 /* NoTrailingSourceMap */; + } + ts.setTextRange(classDeclaration, node); + ts.setOriginalNode(classDeclaration, node); + ts.setEmitFlags(classDeclaration, emitFlags); + return classDeclaration; + } + /** + * Transforms a decorated class declaration and appends the resulting statements. If + * the class requires an alias to avoid issues with double-binding, the alias is returned. + */ + function createClassDeclarationHeadWithDecorators(node, name, facts) { + // When we emit an ES6 class that has a class decorator, we must tailor the + // emit to certain specific cases. + // + // In the simplest case, we emit the class declaration as a let declaration, and + // evaluate decorators after the close of the class body: + // + // [Example 1] + // --------------------------------------------------------------------- + // TypeScript | Javascript + // --------------------------------------------------------------------- + // @dec | let C = class C { + // class C { | } + // } | C = __decorate([dec], C); + // --------------------------------------------------------------------- + // @dec | let C = class C { + // export class C { | } + // } | C = __decorate([dec], C); + // | export { C }; + // --------------------------------------------------------------------- + // + // If a class declaration contains a reference to itself *inside* of the class body, + // this introduces two bindings to the class: One outside of the class body, and one + // inside of the class body. If we apply decorators as in [Example 1] above, there + // is the possibility that the decorator `dec` will return a new value for the + // constructor, which would result in the binding inside of the class no longer + // pointing to the same reference as the binding outside of the class. + // + // As a result, we must instead rewrite all references to the class *inside* of the + // class body to instead point to a local temporary alias for the class: + // + // [Example 2] + // --------------------------------------------------------------------- + // TypeScript | Javascript + // --------------------------------------------------------------------- + // @dec | let C = C_1 = class C { + // class C { | static x() { return C_1.y; } + // static x() { return C.y; } | } + // static y = 1; | C.y = 1; + // } | C = C_1 = __decorate([dec], C); + // | var C_1; + // --------------------------------------------------------------------- + // @dec | let C = class C { + // export class C { | static x() { return C_1.y; } + // static x() { return C.y; } | } + // static y = 1; | C.y = 1; + // } | C = C_1 = __decorate([dec], C); + // | export { C }; + // | var C_1; + // --------------------------------------------------------------------- + // + // If a class declaration is the default export of a module, we instead emit + // the export after the decorated declaration: + // + // [Example 3] + // --------------------------------------------------------------------- + // TypeScript | Javascript + // --------------------------------------------------------------------- + // @dec | let default_1 = class { + // export default class { | } + // } | default_1 = __decorate([dec], default_1); + // | export default default_1; + // --------------------------------------------------------------------- + // @dec | let C = class C { + // export default class C { | } + // } | C = __decorate([dec], C); + // | export default C; + // --------------------------------------------------------------------- + // + // If the class declaration is the default export and a reference to itself + // inside of the class body, we must emit both an alias for the class *and* + // move the export after the declaration: + // + // [Example 4] + // --------------------------------------------------------------------- + // TypeScript | Javascript + // --------------------------------------------------------------------- + // @dec | let C = class C { + // export default class C { | static x() { return C_1.y; } + // static x() { return C.y; } | } + // static y = 1; | C.y = 1; + // } | C = C_1 = __decorate([dec], C); + // | export default C; + // | var C_1; + // --------------------------------------------------------------------- + // + var location = ts.moveRangePastDecorators(node); + var classAlias = getClassAliasIfNeeded(node); + var declName = ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true); + // ... = class ${name} ${heritageClauses} { + // ${members} + // } + var heritageClauses = ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause); + var members = transformClassMembers(node, (facts & 64 /* IsDerivedClass */) !== 0); + var classExpression = ts.createClassExpression(/*modifiers*/ undefined, name, /*typeParameters*/ undefined, heritageClauses, members); + ts.setOriginalNode(classExpression, node); + ts.setTextRange(classExpression, location); + // let ${name} = ${classExpression} where name is either declaredName if the class doesn't contain self-reference + // or decoratedClassAlias if the class contain self-reference. + var statement = ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(declName, + /*type*/ undefined, classAlias ? ts.createAssignment(classAlias, classExpression) : classExpression) + ], 1 /* Let */)); + ts.setOriginalNode(statement, node); + ts.setTextRange(statement, location); + ts.setCommentRange(statement, node); + return statement; + } + /** + * Transforms a class expression with TypeScript syntax into compatible ES6. + * + * This function will only be called when one of the following conditions are met: + * - The class has property declarations with initializers. + * - The class contains a constructor that contains parameters with accessibility modifiers. + * + * @param node The node to transform. + */ + function visitClassExpression(node) { + var savedPendingExpressions = pendingExpressions; + pendingExpressions = undefined; + var staticProperties = getInitializedProperties(node, /*isStatic*/ true); + var heritageClauses = ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause); + var members = transformClassMembers(node, ts.some(heritageClauses, function (c) { return c.token === 86 /* ExtendsKeyword */; })); + var classExpression = ts.createClassExpression( + /*modifiers*/ undefined, node.name, + /*typeParameters*/ undefined, heritageClauses, members); + ts.setOriginalNode(classExpression, node); + ts.setTextRange(classExpression, node); + if (ts.some(staticProperties) || ts.some(pendingExpressions)) { + var expressions = []; + var isClassWithConstructorReference = resolver.getNodeCheckFlags(node) & 16777216 /* ClassWithConstructorReference */; + var temp = ts.createTempVariable(hoistVariableDeclaration, !!isClassWithConstructorReference); + if (isClassWithConstructorReference) { + // record an alias as the class name is not in scope for statics. + enableSubstitutionForClassAliases(); + var alias = ts.getSynthesizedClone(temp); + alias.autoGenerateFlags &= ~8 /* ReservedInNestedScopes */; + classAliases[ts.getOriginalNodeId(node)] = alias; + } + // To preserve the behavior of the old emitter, we explicitly indent + // the body of a class with static initializers. + ts.setEmitFlags(classExpression, 65536 /* Indented */ | ts.getEmitFlags(classExpression)); + expressions.push(ts.startOnNewLine(ts.createAssignment(temp, classExpression))); + // Add any pending expressions leftover from elided or relocated computed property names + ts.addRange(expressions, ts.map(pendingExpressions, ts.startOnNewLine)); + pendingExpressions = savedPendingExpressions; + ts.addRange(expressions, generateInitializedPropertyExpressions(staticProperties, temp)); + expressions.push(ts.startOnNewLine(temp)); + return ts.inlineExpressions(expressions); + } + pendingExpressions = savedPendingExpressions; + return classExpression; + } + /** + * Transforms the members of a class. + * + * @param node The current class. + * @param isDerivedClass A value indicating whether the class has an extends clause that does not extend 'null'. + */ + function transformClassMembers(node, isDerivedClass) { + var members = []; + var constructor = transformConstructor(node, isDerivedClass); + if (constructor) { + members.push(constructor); + } + ts.addRange(members, ts.visitNodes(node.members, classElementVisitor, ts.isClassElement)); + return ts.setTextRange(ts.createNodeArray(members), /*location*/ node.members); + } + /** + * Transforms (or creates) a constructor for a class. + * + * @param node The current class. + * @param isDerivedClass A value indicating whether the class has an extends clause that does not extend 'null'. + */ + function transformConstructor(node, isDerivedClass) { + // Check if we have property assignment inside class declaration. + // If there is a property assignment, we need to emit constructor whether users define it or not + // If there is no property assignment, we can omit constructor if users do not define it + var constructor = ts.getFirstConstructorWithBody(node); + var hasInstancePropertyWithInitializer = ts.forEach(node.members, isInstanceInitializedProperty); + var hasParameterPropertyAssignments = constructor && + constructor.transformFlags & 4096 /* ContainsTypeScriptClassSyntax */ && + ts.forEach(constructor.parameters, isParameterWithPropertyAssignment); + // If the class does not contain nodes that require a synthesized constructor, + // accept the current constructor if it exists. + if (!hasInstancePropertyWithInitializer && !hasParameterPropertyAssignments) { + return ts.visitEachChild(constructor, visitor, context); + } + var parameters = transformConstructorParameters(constructor); + var body = transformConstructorBody(node, constructor, isDerivedClass); + // constructor(${parameters}) { + // ${body} + // } + return ts.startOnNewLine(ts.setOriginalNode(ts.setTextRange(ts.createConstructor( + /*decorators*/ undefined, + /*modifiers*/ undefined, parameters, body), constructor || node), constructor)); + } + /** + * Transforms (or creates) the parameters for the constructor of a class with + * parameter property assignments or instance property initializers. + * + * @param constructor The constructor declaration. + */ + function transformConstructorParameters(constructor) { + // The ES2015 spec specifies in 14.5.14. Runtime Semantics: ClassDefinitionEvaluation: + // If constructor is empty, then + // If ClassHeritag_eopt is present and protoParent is not null, then + // Let constructor be the result of parsing the source text + // constructor(...args) { super (...args);} + // using the syntactic grammar with the goal symbol MethodDefinition[~Yield]. + // Else, + // Let constructor be the result of parsing the source text + // constructor( ){ } + // using the syntactic grammar with the goal symbol MethodDefinition[~Yield]. + // + // While we could emit the '...args' rest parameter, certain later tools in the pipeline might + // downlevel the '...args' portion less efficiently by naively copying the contents of 'arguments' to an array. + // Instead, we'll avoid using a rest parameter and spread into the super call as + // 'super(...arguments)' instead of 'super(...args)', as you can see in "transformConstructorBody". + return ts.visitParameterList(constructor && constructor.parameters, visitor, context) + || []; + } + /** + * Transforms (or creates) a constructor body for a class with parameter property + * assignments or instance property initializers. + * + * @param node The current class. + * @param constructor The current class constructor. + * @param isDerivedClass A value indicating whether the class has an extends clause that does not extend 'null'. + */ + function transformConstructorBody(node, constructor, isDerivedClass) { + var statements = []; + var indexOfFirstStatement = 0; + resumeLexicalEnvironment(); + if (constructor) { + indexOfFirstStatement = addPrologueDirectivesAndInitialSuperCall(constructor, statements); + // Add parameters with property assignments. Transforms this: + // + // constructor (public x, public y) { + // } + // + // Into this: + // + // constructor (x, y) { + // this.x = x; + // this.y = y; + // } + // + var propertyAssignments = getParametersWithPropertyAssignments(constructor); + ts.addRange(statements, ts.map(propertyAssignments, transformParameterWithPropertyAssignment)); + } + else if (isDerivedClass) { + // Add a synthetic `super` call: + // + // super(...arguments); + // + statements.push(ts.createExpressionStatement(ts.createCall(ts.createSuper(), + /*typeArguments*/ undefined, [ts.createSpread(ts.createIdentifier("arguments"))]))); + } + // Add the property initializers. Transforms this: + // + // public x = 1; + // + // Into this: + // + // constructor() { + // this.x = 1; + // } + // + var properties = getInitializedProperties(node, /*isStatic*/ false); + addInitializedPropertyStatements(statements, properties, ts.createThis()); + if (constructor) { + // The class already had a constructor, so we should add the existing statements, skipping the initial super call. + ts.addRange(statements, ts.visitNodes(constructor.body.statements, visitor, ts.isStatement, indexOfFirstStatement)); + } + // End the lexical environment. + statements = ts.mergeLexicalEnvironment(statements, endLexicalEnvironment()); + return ts.setTextRange(ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), + /*location*/ constructor ? constructor.body.statements : node.members), + /*multiLine*/ true), + /*location*/ constructor ? constructor.body : undefined); + } + /** + * Adds super call and preceding prologue directives into the list of statements. + * + * @param ctor The constructor node. + * @returns index of the statement that follows super call + */ + function addPrologueDirectivesAndInitialSuperCall(ctor, result) { + if (ctor.body) { + var statements = ctor.body.statements; + // add prologue directives to the list (if any) + var index = ts.addPrologue(result, statements, /*ensureUseStrict*/ false, visitor); + if (index === statements.length) { + // list contains nothing but prologue directives (or empty) - exit + return index; + } + var statement = statements[index]; + if (statement.kind === 221 /* ExpressionStatement */ && ts.isSuperCall(statement.expression)) { + result.push(ts.visitNode(statement, visitor, ts.isStatement)); + return index + 1; + } + return index; + } + return 0; + } + /** + * Gets all parameters of a constructor that should be transformed into property assignments. + * + * @param node The constructor node. + */ + function getParametersWithPropertyAssignments(node) { + return ts.filter(node.parameters, isParameterWithPropertyAssignment); + } + /** + * Determines whether a parameter should be transformed into a property assignment. + * + * @param parameter The parameter node. + */ + function isParameterWithPropertyAssignment(parameter) { + return ts.hasModifier(parameter, 92 /* ParameterPropertyModifier */) + && ts.isIdentifier(parameter.name); + } + /** + * Transforms a parameter into a property assignment statement. + * + * @param node The parameter declaration. + */ + function transformParameterWithPropertyAssignment(node) { + ts.Debug.assert(ts.isIdentifier(node.name)); + var name = node.name; + var propertyName = ts.getMutableClone(name); + ts.setEmitFlags(propertyName, 1536 /* NoComments */ | 48 /* NoSourceMap */); + var localName = ts.getMutableClone(name); + ts.setEmitFlags(localName, 1536 /* NoComments */); + return ts.startOnNewLine(ts.setEmitFlags(ts.setTextRange(ts.createExpressionStatement(ts.createAssignment(ts.setTextRange(ts.createPropertyAccess(ts.createThis(), propertyName), node.name), localName)), ts.moveRangePos(node, -1)), 1536 /* NoComments */)); + } + /** + * Gets all property declarations with initializers on either the static or instance side of a class. + * + * @param node The class node. + * @param isStatic A value indicating whether to get properties from the static or instance side of the class. + */ + function getInitializedProperties(node, isStatic) { + return ts.filter(node.members, isStatic ? isStaticInitializedProperty : isInstanceInitializedProperty); + } + /** + * Gets a value indicating whether a class element is a static property declaration with an initializer. + * + * @param member The class element node. + */ + function isStaticInitializedProperty(member) { + return isInitializedProperty(member, /*isStatic*/ true); + } + /** + * Gets a value indicating whether a class element is an instance property declaration with an initializer. + * + * @param member The class element node. + */ + function isInstanceInitializedProperty(member) { + return isInitializedProperty(member, /*isStatic*/ false); + } + /** + * Gets a value indicating whether a class element is either a static or an instance property declaration with an initializer. + * + * @param member The class element node. + * @param isStatic A value indicating whether the member should be a static or instance member. + */ + function isInitializedProperty(member, isStatic) { + return member.kind === 154 /* PropertyDeclaration */ + && isStatic === ts.hasModifier(member, 32 /* Static */) + && member.initializer !== undefined; + } + /** + * Generates assignment statements for property initializers. + * + * @param properties An array of property declarations to transform. + * @param receiver The receiver on which each property should be assigned. + */ + function addInitializedPropertyStatements(statements, properties, receiver) { + for (var _i = 0, properties_9 = properties; _i < properties_9.length; _i++) { + var property = properties_9[_i]; + var statement = ts.createExpressionStatement(transformInitializedProperty(property, receiver)); + ts.setSourceMapRange(statement, ts.moveRangePastModifiers(property)); + ts.setCommentRange(statement, property); + ts.setOriginalNode(statement, property); + statements.push(statement); + } + } + /** + * Generates assignment expressions for property initializers. + * + * @param properties An array of property declarations to transform. + * @param receiver The receiver on which each property should be assigned. + */ + function generateInitializedPropertyExpressions(properties, receiver) { + var expressions = []; + for (var _i = 0, properties_10 = properties; _i < properties_10.length; _i++) { + var property = properties_10[_i]; + var expression = transformInitializedProperty(property, receiver); + ts.startOnNewLine(expression); + ts.setSourceMapRange(expression, ts.moveRangePastModifiers(property)); + ts.setCommentRange(expression, property); + ts.setOriginalNode(expression, property); + expressions.push(expression); + } + return expressions; + } + /** + * Transforms a property initializer into an assignment statement. + * + * @param property The property declaration. + * @param receiver The object receiving the property assignment. + */ + function transformInitializedProperty(property, receiver) { + // We generate a name here in order to reuse the value cached by the relocated computed name expression (which uses the same generated name) + var propertyName = ts.isComputedPropertyName(property.name) && !isSimpleInlineableExpression(property.name.expression) + ? ts.updateComputedPropertyName(property.name, ts.getGeneratedNameForNode(property.name)) + : property.name; + var initializer = ts.visitNode(property.initializer, visitor, ts.isExpression); + var memberAccess = ts.createMemberAccessForPropertyName(receiver, propertyName, /*location*/ propertyName); + return ts.createAssignment(memberAccess, initializer); + } + /** + * Gets either the static or instance members of a class that are decorated, or have + * parameters that are decorated. + * + * @param node The class containing the member. + * @param isStatic A value indicating whether to retrieve static or instance members of + * the class. + */ + function getDecoratedClassElements(node, isStatic) { + return ts.filter(node.members, isStatic ? function (m) { return isStaticDecoratedClassElement(m, node); } : function (m) { return isInstanceDecoratedClassElement(m, node); }); + } + /** + * Determines whether a class member is a static member of a class that is decorated, or + * has parameters that are decorated. + * + * @param member The class member. + */ + function isStaticDecoratedClassElement(member, parent) { + return isDecoratedClassElement(member, /*isStatic*/ true, parent); + } + /** + * Determines whether a class member is an instance member of a class that is decorated, + * or has parameters that are decorated. + * + * @param member The class member. + */ + function isInstanceDecoratedClassElement(member, parent) { + return isDecoratedClassElement(member, /*isStatic*/ false, parent); + } + /** + * Determines whether a class member is either a static or an instance member of a class + * that is decorated, or has parameters that are decorated. + * + * @param member The class member. + */ + function isDecoratedClassElement(member, isStatic, parent) { + return ts.nodeOrChildIsDecorated(member, parent) + && isStatic === ts.hasModifier(member, 32 /* Static */); + } + /** + * Gets an array of arrays of decorators for the parameters of a function-like node. + * The offset into the result array should correspond to the offset of the parameter. + * + * @param node The function-like node. + */ + function getDecoratorsOfParameters(node) { + var decorators; + if (node) { + var parameters = node.parameters; + for (var i = 0; i < parameters.length; i++) { + var parameter = parameters[i]; + if (decorators || parameter.decorators) { + if (!decorators) { + decorators = new Array(parameters.length); + } + decorators[i] = parameter.decorators; + } + } + } + return decorators; + } + /** + * Gets an AllDecorators object containing the decorators for the class and the decorators for the + * parameters of the constructor of the class. + * + * @param node The class node. + */ + function getAllDecoratorsOfConstructor(node) { + var decorators = node.decorators; + var parameters = getDecoratorsOfParameters(ts.getFirstConstructorWithBody(node)); + if (!decorators && !parameters) { + return undefined; + } + return { + decorators: decorators, + parameters: parameters + }; + } + /** + * Gets an AllDecorators object containing the decorators for the member and its parameters. + * + * @param node The class node that contains the member. + * @param member The class member. + */ + function getAllDecoratorsOfClassElement(node, member) { + switch (member.kind) { + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + return getAllDecoratorsOfAccessors(node, member); + case 156 /* MethodDeclaration */: + return getAllDecoratorsOfMethod(member); + case 154 /* PropertyDeclaration */: + return getAllDecoratorsOfProperty(member); + default: + return undefined; + } + } + /** + * Gets an AllDecorators object containing the decorators for the accessor and its parameters. + * + * @param node The class node that contains the accessor. + * @param accessor The class accessor member. + */ + function getAllDecoratorsOfAccessors(node, accessor) { + if (!accessor.body) { + return undefined; + } + var _a = ts.getAllAccessorDeclarations(node.members, accessor), firstAccessor = _a.firstAccessor, secondAccessor = _a.secondAccessor, setAccessor = _a.setAccessor; + var firstAccessorWithDecorators = firstAccessor.decorators ? firstAccessor : secondAccessor && secondAccessor.decorators ? secondAccessor : undefined; + if (!firstAccessorWithDecorators || accessor !== firstAccessorWithDecorators) { + return undefined; + } + var decorators = firstAccessorWithDecorators.decorators; + var parameters = getDecoratorsOfParameters(setAccessor); + if (!decorators && !parameters) { + return undefined; + } + return { decorators: decorators, parameters: parameters }; + } + /** + * Gets an AllDecorators object containing the decorators for the method and its parameters. + * + * @param method The class method member. + */ + function getAllDecoratorsOfMethod(method) { + if (!method.body) { + return undefined; + } + var decorators = method.decorators; + var parameters = getDecoratorsOfParameters(method); + if (!decorators && !parameters) { + return undefined; + } + return { decorators: decorators, parameters: parameters }; + } + /** + * Gets an AllDecorators object containing the decorators for the property. + * + * @param property The class property member. + */ + function getAllDecoratorsOfProperty(property) { + var decorators = property.decorators; + if (!decorators) { + return undefined; + } + return { decorators: decorators }; + } + /** + * Transforms all of the decorators for a declaration into an array of expressions. + * + * @param node The declaration node. + * @param allDecorators An object containing all of the decorators for the declaration. + */ + function transformAllDecoratorsOfDeclaration(node, container, allDecorators) { + if (!allDecorators) { + return undefined; + } + var decoratorExpressions = []; + ts.addRange(decoratorExpressions, ts.map(allDecorators.decorators, transformDecorator)); + ts.addRange(decoratorExpressions, ts.flatMap(allDecorators.parameters, transformDecoratorsOfParameter)); + addTypeMetadata(node, container, decoratorExpressions); + return decoratorExpressions; + } + /** + * Generates statements used to apply decorators to either the static or instance members + * of a class. + * + * @param node The class node. + * @param isStatic A value indicating whether to generate statements for static or + * instance members. + */ + function addClassElementDecorationStatements(statements, node, isStatic) { + ts.addRange(statements, ts.map(generateClassElementDecorationExpressions(node, isStatic), expressionToStatement)); + } + /** + * Generates expressions used to apply decorators to either the static or instance members + * of a class. + * + * @param node The class node. + * @param isStatic A value indicating whether to generate expressions for static or + * instance members. + */ + function generateClassElementDecorationExpressions(node, isStatic) { + var members = getDecoratedClassElements(node, isStatic); + var expressions; + for (var _i = 0, members_5 = members; _i < members_5.length; _i++) { + var member = members_5[_i]; + var expression = generateClassElementDecorationExpression(node, member); + if (expression) { + if (!expressions) { + expressions = [expression]; + } + else { + expressions.push(expression); + } + } + } + return expressions; + } + /** + * Generates an expression used to evaluate class element decorators at runtime. + * + * @param node The class node that contains the member. + * @param member The class member. + */ + function generateClassElementDecorationExpression(node, member) { + var allDecorators = getAllDecoratorsOfClassElement(node, member); + var decoratorExpressions = transformAllDecoratorsOfDeclaration(member, node, allDecorators); + if (!decoratorExpressions) { + return undefined; + } + // Emit the call to __decorate. Given the following: + // + // class C { + // @dec method(@dec2 x) {} + // @dec get accessor() {} + // @dec prop; + // } + // + // The emit for a method is: + // + // __decorate([ + // dec, + // __param(0, dec2), + // __metadata("design:type", Function), + // __metadata("design:paramtypes", [Object]), + // __metadata("design:returntype", void 0) + // ], C.prototype, "method", null); + // + // The emit for an accessor is: + // + // __decorate([ + // dec + // ], C.prototype, "accessor", null); + // + // The emit for a property is: + // + // __decorate([ + // dec + // ], C.prototype, "prop"); + // + var prefix = getClassMemberPrefix(node, member); + var memberName = getExpressionForPropertyName(member, /*generateNameForComputedPropertyName*/ true); + var descriptor = languageVersion > 0 /* ES3 */ + ? member.kind === 154 /* PropertyDeclaration */ + // We emit `void 0` here to indicate to `__decorate` that it can invoke `Object.defineProperty` directly, but that it + // should not invoke `Object.getOwnPropertyDescriptor`. + ? ts.createVoidZero() + // We emit `null` here to indicate to `__decorate` that it can invoke `Object.getOwnPropertyDescriptor` directly. + // We have this extra argument here so that we can inject an explicit property descriptor at a later date. + : ts.createNull() + : undefined; + var helper = createDecorateHelper(context, decoratorExpressions, prefix, memberName, descriptor, ts.moveRangePastDecorators(member)); + ts.setEmitFlags(helper, 1536 /* NoComments */); + return helper; + } + /** + * Generates a __decorate helper call for a class constructor. + * + * @param node The class node. + */ + function addConstructorDecorationStatement(statements, node) { + var expression = generateConstructorDecorationExpression(node); + if (expression) { + statements.push(ts.setOriginalNode(ts.createExpressionStatement(expression), node)); + } + } + /** + * Generates a __decorate helper call for a class constructor. + * + * @param node The class node. + */ + function generateConstructorDecorationExpression(node) { + var allDecorators = getAllDecoratorsOfConstructor(node); + var decoratorExpressions = transformAllDecoratorsOfDeclaration(node, node, allDecorators); + if (!decoratorExpressions) { + return undefined; + } + var classAlias = classAliases && classAliases[ts.getOriginalNodeId(node)]; + var localName = ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true); + var decorate = createDecorateHelper(context, decoratorExpressions, localName); + var expression = ts.createAssignment(localName, classAlias ? ts.createAssignment(classAlias, decorate) : decorate); + ts.setEmitFlags(expression, 1536 /* NoComments */); + ts.setSourceMapRange(expression, ts.moveRangePastDecorators(node)); + return expression; + } + /** + * Transforms a decorator into an expression. + * + * @param decorator The decorator node. + */ + function transformDecorator(decorator) { + return ts.visitNode(decorator.expression, visitor, ts.isExpression); + } + /** + * Transforms the decorators of a parameter. + * + * @param decorators The decorators for the parameter at the provided offset. + * @param parameterOffset The offset of the parameter. + */ + function transformDecoratorsOfParameter(decorators, parameterOffset) { + var expressions; + if (decorators) { + expressions = []; + for (var _i = 0, decorators_1 = decorators; _i < decorators_1.length; _i++) { + var decorator = decorators_1[_i]; + var helper = createParamHelper(context, transformDecorator(decorator), parameterOffset, + /*location*/ decorator.expression); + ts.setEmitFlags(helper, 1536 /* NoComments */); + expressions.push(helper); + } + } + return expressions; + } + /** + * Adds optional type metadata for a declaration. + * + * @param node The declaration node. + * @param decoratorExpressions The destination array to which to add new decorator expressions. + */ + function addTypeMetadata(node, container, decoratorExpressions) { + if (USE_NEW_TYPE_METADATA_FORMAT) { + addNewTypeMetadata(node, container, decoratorExpressions); + } + else { + addOldTypeMetadata(node, container, decoratorExpressions); + } + } + function addOldTypeMetadata(node, container, decoratorExpressions) { + if (compilerOptions.emitDecoratorMetadata) { + if (shouldAddTypeMetadata(node)) { + decoratorExpressions.push(createMetadataHelper(context, "design:type", serializeTypeOfNode(node))); + } + if (shouldAddParamTypesMetadata(node)) { + decoratorExpressions.push(createMetadataHelper(context, "design:paramtypes", serializeParameterTypesOfNode(node, container))); + } + if (shouldAddReturnTypeMetadata(node)) { + decoratorExpressions.push(createMetadataHelper(context, "design:returntype", serializeReturnTypeOfNode(node))); + } + } + } + function addNewTypeMetadata(node, container, decoratorExpressions) { + if (compilerOptions.emitDecoratorMetadata) { + var properties = void 0; + if (shouldAddTypeMetadata(node)) { + (properties || (properties = [])).push(ts.createPropertyAssignment("type", ts.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, ts.createToken(37 /* EqualsGreaterThanToken */), serializeTypeOfNode(node)))); + } + if (shouldAddParamTypesMetadata(node)) { + (properties || (properties = [])).push(ts.createPropertyAssignment("paramTypes", ts.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, ts.createToken(37 /* EqualsGreaterThanToken */), serializeParameterTypesOfNode(node, container)))); + } + if (shouldAddReturnTypeMetadata(node)) { + (properties || (properties = [])).push(ts.createPropertyAssignment("returnType", ts.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, ts.createToken(37 /* EqualsGreaterThanToken */), serializeReturnTypeOfNode(node)))); + } + if (properties) { + decoratorExpressions.push(createMetadataHelper(context, "design:typeinfo", ts.createObjectLiteral(properties, /*multiLine*/ true))); + } + } + } + /** + * Determines whether to emit the "design:type" metadata based on the node's kind. + * The caller should have already tested whether the node has decorators and whether the + * emitDecoratorMetadata compiler option is set. + * + * @param node The node to test. + */ + function shouldAddTypeMetadata(node) { + var kind = node.kind; + return kind === 156 /* MethodDeclaration */ + || kind === 158 /* GetAccessor */ + || kind === 159 /* SetAccessor */ + || kind === 154 /* PropertyDeclaration */; + } + /** + * Determines whether to emit the "design:returntype" metadata based on the node's kind. + * The caller should have already tested whether the node has decorators and whether the + * emitDecoratorMetadata compiler option is set. + * + * @param node The node to test. + */ + function shouldAddReturnTypeMetadata(node) { + return node.kind === 156 /* MethodDeclaration */; + } + /** + * Determines whether to emit the "design:paramtypes" metadata based on the node's kind. + * The caller should have already tested whether the node has decorators and whether the + * emitDecoratorMetadata compiler option is set. + * + * @param node The node to test. + */ + function shouldAddParamTypesMetadata(node) { + switch (node.kind) { + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + return ts.getFirstConstructorWithBody(node) !== undefined; + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + return true; + } + return false; + } + function getAccessorTypeNode(node) { + var accessors = resolver.getAllAccessorDeclarations(node); + return accessors.setAccessor && ts.getSetAccessorTypeAnnotationNode(accessors.setAccessor) + || accessors.getAccessor && ts.getEffectiveReturnTypeNode(accessors.getAccessor); + } + /** + * Serializes the type of a node for use with decorator type metadata. + * + * @param node The node that should have its type serialized. + */ + function serializeTypeOfNode(node) { + switch (node.kind) { + case 154 /* PropertyDeclaration */: + case 151 /* Parameter */: + return serializeTypeNode(node.type); + case 159 /* SetAccessor */: + case 158 /* GetAccessor */: + return serializeTypeNode(getAccessorTypeNode(node)); + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 156 /* MethodDeclaration */: + return ts.createIdentifier("Function"); + default: + return ts.createVoidZero(); + } + } + /** + * Serializes the types of the parameters of a node for use with decorator type metadata. + * + * @param node The node that should have its parameter types serialized. + */ + function serializeParameterTypesOfNode(node, container) { + var valueDeclaration = ts.isClassLike(node) + ? ts.getFirstConstructorWithBody(node) + : ts.isFunctionLike(node) && ts.nodeIsPresent(node.body) + ? node + : undefined; + var expressions = []; + if (valueDeclaration) { + var parameters = getParametersOfDecoratedDeclaration(valueDeclaration, container); + var numParameters = parameters.length; + for (var i = 0; i < numParameters; i++) { + var parameter = parameters[i]; + if (i === 0 && ts.isIdentifier(parameter.name) && parameter.name.escapedText === "this") { + continue; + } + if (parameter.dotDotDotToken) { + expressions.push(serializeTypeNode(ts.getRestParameterElementType(parameter.type))); + } + else { + expressions.push(serializeTypeOfNode(parameter)); + } + } + } + return ts.createArrayLiteral(expressions); + } + function getParametersOfDecoratedDeclaration(node, container) { + if (container && node.kind === 158 /* GetAccessor */) { + var setAccessor = ts.getAllAccessorDeclarations(container.members, node).setAccessor; + if (setAccessor) { + return setAccessor.parameters; + } + } + return node.parameters; + } + /** + * Serializes the return type of a node for use with decorator type metadata. + * + * @param node The node that should have its return type serialized. + */ + function serializeReturnTypeOfNode(node) { + if (ts.isFunctionLike(node) && node.type) { + return serializeTypeNode(node.type); + } + else if (ts.isAsyncFunction(node)) { + return ts.createIdentifier("Promise"); + } + return ts.createVoidZero(); + } + /** + * Serializes a type node for use with decorator type metadata. + * + * Types are serialized in the following fashion: + * - Void types point to "undefined" (e.g. "void 0") + * - Function and Constructor types point to the global "Function" constructor. + * - Interface types with a call or construct signature types point to the global + * "Function" constructor. + * - Array and Tuple types point to the global "Array" constructor. + * - Type predicates and booleans point to the global "Boolean" constructor. + * - String literal types and strings point to the global "String" constructor. + * - Enum and number types point to the global "Number" constructor. + * - Symbol types point to the global "Symbol" constructor. + * - Type references to classes (or class-like variables) point to the constructor for the class. + * - Anything else points to the global "Object" constructor. + * + * @param node The type node to serialize. + */ + function serializeTypeNode(node) { + if (node === undefined) { + return ts.createIdentifier("Object"); + } + switch (node.kind) { + case 106 /* VoidKeyword */: + case 141 /* UndefinedKeyword */: + case 96 /* NullKeyword */: + case 132 /* NeverKeyword */: + return ts.createVoidZero(); + case 177 /* ParenthesizedType */: + return serializeTypeNode(node.type); + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + return ts.createIdentifier("Function"); + case 169 /* ArrayType */: + case 170 /* TupleType */: + return ts.createIdentifier("Array"); + case 163 /* TypePredicate */: + case 123 /* BooleanKeyword */: + return ts.createIdentifier("Boolean"); + case 138 /* StringKeyword */: + return ts.createIdentifier("String"); + case 136 /* ObjectKeyword */: + return ts.createIdentifier("Object"); + case 182 /* LiteralType */: + switch (node.literal.kind) { + case 10 /* StringLiteral */: + return ts.createIdentifier("String"); + case 8 /* NumericLiteral */: + return ts.createIdentifier("Number"); + case 9 /* BigIntLiteral */: + return getGlobalBigIntNameWithFallback(); + case 102 /* TrueKeyword */: + case 87 /* FalseKeyword */: + return ts.createIdentifier("Boolean"); + default: + return ts.Debug.failBadSyntaxKind(node.literal); + } + case 135 /* NumberKeyword */: + return ts.createIdentifier("Number"); + case 146 /* BigIntKeyword */: + return getGlobalBigIntNameWithFallback(); + case 139 /* SymbolKeyword */: + return languageVersion < 2 /* ES2015 */ + ? getGlobalSymbolNameWithFallback() + : ts.createIdentifier("Symbol"); + case 164 /* TypeReference */: + return serializeTypeReferenceNode(node); + case 174 /* IntersectionType */: + case 173 /* UnionType */: + return serializeTypeList(node.types); + case 175 /* ConditionalType */: + return serializeTypeList([node.trueType, node.falseType]); + case 167 /* TypeQuery */: + case 179 /* TypeOperator */: + case 180 /* IndexedAccessType */: + case 181 /* MappedType */: + case 168 /* TypeLiteral */: + case 120 /* AnyKeyword */: + case 143 /* UnknownKeyword */: + case 178 /* ThisType */: + case 183 /* ImportType */: + break; + default: + return ts.Debug.failBadSyntaxKind(node); + } + return ts.createIdentifier("Object"); + } + function serializeTypeList(types) { + // Note when updating logic here also update getEntityNameForDecoratorMetadata + // so that aliases can be marked as referenced + var serializedUnion; + for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { + var typeNode = types_17[_i]; + while (typeNode.kind === 177 /* ParenthesizedType */) { + typeNode = typeNode.type; // Skip parens if need be + } + if (typeNode.kind === 132 /* NeverKeyword */) { + continue; // Always elide `never` from the union/intersection if possible + } + if (!strictNullChecks && (typeNode.kind === 96 /* NullKeyword */ || typeNode.kind === 141 /* UndefinedKeyword */)) { + continue; // Elide null and undefined from unions for metadata, just like what we did prior to the implementation of strict null checks + } + var serializedIndividual = serializeTypeNode(typeNode); + if (ts.isIdentifier(serializedIndividual) && serializedIndividual.escapedText === "Object") { + // One of the individual is global object, return immediately + return serializedIndividual; + } + // If there exists union that is not void 0 expression, check if the the common type is identifier. + // anything more complex and we will just default to Object + else if (serializedUnion) { + // Different types + if (!ts.isIdentifier(serializedUnion) || + !ts.isIdentifier(serializedIndividual) || + serializedUnion.escapedText !== serializedIndividual.escapedText) { + return ts.createIdentifier("Object"); + } + } + else { + // Initialize the union type + serializedUnion = serializedIndividual; + } + } + // If we were able to find common type, use it + return serializedUnion || ts.createVoidZero(); // Fallback is only hit if all union constituients are null/undefined/never + } + /** + * Serializes a TypeReferenceNode to an appropriate JS constructor value for use with + * decorator type metadata. + * + * @param node The type reference node. + */ + function serializeTypeReferenceNode(node) { + var kind = resolver.getTypeReferenceSerializationKind(node.typeName, currentNameScope || currentLexicalScope); + switch (kind) { + case ts.TypeReferenceSerializationKind.Unknown: + // From conditional type type reference that cannot be resolved is Similar to any or unknown + if (ts.findAncestor(node, function (n) { return n.parent && ts.isConditionalTypeNode(n.parent) && (n.parent.trueType === n || n.parent.falseType === n); })) { + return ts.createIdentifier("Object"); + } + var serialized = serializeEntityNameAsExpressionFallback(node.typeName); + var temp = ts.createTempVariable(hoistVariableDeclaration); + return ts.createConditional(ts.createTypeCheck(ts.createAssignment(temp, serialized), "function"), temp, ts.createIdentifier("Object")); + case ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue: + return serializeEntityNameAsExpression(node.typeName); + case ts.TypeReferenceSerializationKind.VoidNullableOrNeverType: + return ts.createVoidZero(); + case ts.TypeReferenceSerializationKind.BigIntLikeType: + return getGlobalBigIntNameWithFallback(); + case ts.TypeReferenceSerializationKind.BooleanType: + return ts.createIdentifier("Boolean"); + case ts.TypeReferenceSerializationKind.NumberLikeType: + return ts.createIdentifier("Number"); + case ts.TypeReferenceSerializationKind.StringLikeType: + return ts.createIdentifier("String"); + case ts.TypeReferenceSerializationKind.ArrayLikeType: + return ts.createIdentifier("Array"); + case ts.TypeReferenceSerializationKind.ESSymbolType: + return languageVersion < 2 /* ES2015 */ + ? getGlobalSymbolNameWithFallback() + : ts.createIdentifier("Symbol"); + case ts.TypeReferenceSerializationKind.TypeWithCallSignature: + return ts.createIdentifier("Function"); + case ts.TypeReferenceSerializationKind.Promise: + return ts.createIdentifier("Promise"); + case ts.TypeReferenceSerializationKind.ObjectType: + return ts.createIdentifier("Object"); + default: + return ts.Debug.assertNever(kind); + } + } + function createCheckedValue(left, right) { + return ts.createLogicalAnd(ts.createStrictInequality(ts.createTypeOf(left), ts.createLiteral("undefined")), right); + } + /** + * Serializes an entity name which may not exist at runtime, but whose access shouldn't throw + * + * @param node The entity name to serialize. + */ + function serializeEntityNameAsExpressionFallback(node) { + if (node.kind === 72 /* Identifier */) { + // A -> typeof A !== undefined && A + var copied = serializeEntityNameAsExpression(node); + return createCheckedValue(copied, copied); + } + if (node.left.kind === 72 /* Identifier */) { + // A.B -> typeof A !== undefined && A.B + return createCheckedValue(serializeEntityNameAsExpression(node.left), serializeEntityNameAsExpression(node)); + } + // A.B.C -> typeof A !== undefined && (_a = A.B) !== void 0 && _a.C + var left = serializeEntityNameAsExpressionFallback(node.left); + var temp = ts.createTempVariable(hoistVariableDeclaration); + return ts.createLogicalAnd(ts.createLogicalAnd(left.left, ts.createStrictInequality(ts.createAssignment(temp, left.right), ts.createVoidZero())), ts.createPropertyAccess(temp, node.right)); + } + /** + * Serializes an entity name as an expression for decorator type metadata. + * + * @param node The entity name to serialize. + */ + function serializeEntityNameAsExpression(node) { + switch (node.kind) { + case 72 /* Identifier */: + // Create a clone of the name with a new parent, and treat it as if it were + // a source tree node for the purposes of the checker. + var name = ts.getMutableClone(node); + name.flags &= ~8 /* Synthesized */; + name.original = undefined; + name.parent = ts.getParseTreeNode(currentLexicalScope); // ensure the parent is set to a parse tree node. + return name; + case 148 /* QualifiedName */: + return serializeQualifiedNameAsExpression(node); + } + } + /** + * Serializes an qualified name as an expression for decorator type metadata. + * + * @param node The qualified name to serialize. + * @param useFallback A value indicating whether to use logical operators to test for the + * qualified name at runtime. + */ + function serializeQualifiedNameAsExpression(node) { + return ts.createPropertyAccess(serializeEntityNameAsExpression(node.left), node.right); + } + /** + * Gets an expression that points to the global "Symbol" constructor at runtime if it is + * available. + */ + function getGlobalSymbolNameWithFallback() { + return ts.createConditional(ts.createTypeCheck(ts.createIdentifier("Symbol"), "function"), ts.createIdentifier("Symbol"), ts.createIdentifier("Object")); + } + /** + * Gets an expression that points to the global "BigInt" constructor at runtime if it is + * available. + */ + function getGlobalBigIntNameWithFallback() { + return languageVersion < 6 /* ESNext */ + ? ts.createConditional(ts.createTypeCheck(ts.createIdentifier("BigInt"), "function"), ts.createIdentifier("BigInt"), ts.createIdentifier("Object")) + : ts.createIdentifier("BigInt"); + } + /** + * A simple inlinable expression is an expression which can be copied into multiple locations + * without risk of repeating any sideeffects and whose value could not possibly change between + * any such locations + */ + function isSimpleInlineableExpression(expression) { + return !ts.isIdentifier(expression) && ts.isSimpleCopiableExpression(expression) || + ts.isWellKnownSymbolSyntactically(expression); + } + /** + * Gets an expression that represents a property name. For a computed property, a + * name is generated for the node. + * + * @param member The member whose name should be converted into an expression. + */ + function getExpressionForPropertyName(member, generateNameForComputedPropertyName) { + var name = member.name; + if (ts.isComputedPropertyName(name)) { + return generateNameForComputedPropertyName && !isSimpleInlineableExpression(name.expression) + ? ts.getGeneratedNameForNode(name) + : name.expression; + } + else if (ts.isIdentifier(name)) { + return ts.createLiteral(ts.idText(name)); + } + else { + return ts.getSynthesizedClone(name); + } + } + /** + * If the name is a computed property, this function transforms it, then either returns an expression which caches the + * value of the result or the expression itself if the value is either unused or safe to inline into multiple locations + * @param shouldHoist Does the expression need to be reused? (ie, for an initializer or a decorator) + * @param omitSimple Should expressions with no observable side-effects be elided? (ie, the expression is not hoisted for a decorator or initializer and is a literal) + */ + function getPropertyNameExpressionIfNeeded(name, shouldHoist, omitSimple) { + if (ts.isComputedPropertyName(name)) { + var expression = ts.visitNode(name.expression, visitor, ts.isExpression); + var innerExpression = ts.skipPartiallyEmittedExpressions(expression); + var inlinable = isSimpleInlineableExpression(innerExpression); + if (!inlinable && shouldHoist) { + var generatedName = ts.getGeneratedNameForNode(name); + hoistVariableDeclaration(generatedName); + return ts.createAssignment(generatedName, expression); + } + return (omitSimple && (inlinable || ts.isIdentifier(innerExpression))) ? undefined : expression; + } + } + /** + * Visits the property name of a class element, for use when emitting property + * initializers. For a computed property on a node with decorators, a temporary + * value is stored for later use. + * + * @param member The member whose name should be visited. + */ + function visitPropertyNameOfClassElement(member) { + var name = member.name; + var expr = getPropertyNameExpressionIfNeeded(name, ts.some(member.decorators), /*omitSimple*/ false); + if (expr) { // expr only exists if `name` is a computed property name + // Inline any pending expressions from previous elided or relocated computed property name expressions in order to preserve execution order + if (ts.some(pendingExpressions)) { + expr = ts.inlineExpressions(pendingExpressions.concat([expr])); + pendingExpressions.length = 0; + } + return ts.updateComputedPropertyName(name, expr); + } + else { + return name; + } + } + /** + * Transforms a HeritageClause with TypeScript syntax. + * + * This function will only be called when one of the following conditions are met: + * - The node is a non-`extends` heritage clause that should be elided. + * - The node is an `extends` heritage clause that should be visited, but only allow a single type. + * + * @param node The HeritageClause to transform. + */ + function visitHeritageClause(node) { + if (node.token === 86 /* ExtendsKeyword */) { + var types = ts.visitNodes(node.types, visitor, ts.isExpressionWithTypeArguments, 0, 1); + return ts.setTextRange(ts.createHeritageClause(86 /* ExtendsKeyword */, types), node); + } + return undefined; + } + /** + * Transforms an ExpressionWithTypeArguments with TypeScript syntax. + * + * This function will only be called when one of the following conditions are met: + * - The node contains type arguments that should be elided. + * + * @param node The ExpressionWithTypeArguments to transform. + */ + function visitExpressionWithTypeArguments(node) { + return ts.updateExpressionWithTypeArguments(node, + /*typeArguments*/ undefined, ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression)); + } + /** + * Determines whether to emit a function-like declaration. We should not emit the + * declaration if it does not have a body. + * + * @param node The declaration node. + */ + function shouldEmitFunctionLikeDeclaration(node) { + return !ts.nodeIsMissing(node.body); + } + function visitPropertyDeclaration(node) { + var expr = getPropertyNameExpressionIfNeeded(node.name, ts.some(node.decorators) || !!node.initializer, /*omitSimple*/ true); + if (expr && !isSimpleInlineableExpression(expr)) { + (pendingExpressions || (pendingExpressions = [])).push(expr); + } + return undefined; + } + function visitConstructor(node) { + if (!shouldEmitFunctionLikeDeclaration(node)) { + return undefined; + } + return ts.updateConstructor(node, ts.visitNodes(node.decorators, visitor, ts.isDecorator), ts.visitNodes(node.modifiers, visitor, ts.isModifier), ts.visitParameterList(node.parameters, visitor, context), ts.visitFunctionBody(node.body, visitor, context)); + } + /** + * Visits a method declaration of a class. + * + * This function will be called when one of the following conditions are met: + * - The node is an overload + * - The node is marked as abstract, public, private, protected, or readonly + * - The node has a computed property name + * + * @param node The method node. + */ + function visitMethodDeclaration(node) { + if (!shouldEmitFunctionLikeDeclaration(node)) { + return undefined; + } + var updated = ts.updateMethod(node, + /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, visitPropertyNameOfClassElement(node), + /*questionToken*/ undefined, + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context)); + if (updated !== node) { + // While we emit the source map for the node after skipping decorators and modifiers, + // we need to emit the comments for the original range. + ts.setCommentRange(updated, node); + ts.setSourceMapRange(updated, ts.moveRangePastDecorators(node)); + } + return updated; + } + /** + * Determines whether to emit an accessor declaration. We should not emit the + * declaration if it does not have a body and is abstract. + * + * @param node The declaration node. + */ + function shouldEmitAccessorDeclaration(node) { + return !(ts.nodeIsMissing(node.body) && ts.hasModifier(node, 128 /* Abstract */)); + } + /** + * Visits a get accessor declaration of a class. + * + * This function will be called when one of the following conditions are met: + * - The node is marked as abstract, public, private, or protected + * - The node has a computed property name + * + * @param node The get accessor node. + */ + function visitGetAccessor(node) { + if (!shouldEmitAccessorDeclaration(node)) { + return undefined; + } + var updated = ts.updateGetAccessor(node, + /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), visitPropertyNameOfClassElement(node), ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context) || ts.createBlock([])); + if (updated !== node) { + // While we emit the source map for the node after skipping decorators and modifiers, + // we need to emit the comments for the original range. + ts.setCommentRange(updated, node); + ts.setSourceMapRange(updated, ts.moveRangePastDecorators(node)); + } + return updated; + } + /** + * Visits a set accessor declaration of a class. + * + * This function will be called when one of the following conditions are met: + * - The node is marked as abstract, public, private, or protected + * - The node has a computed property name + * + * @param node The set accessor node. + */ + function visitSetAccessor(node) { + if (!shouldEmitAccessorDeclaration(node)) { + return undefined; + } + var updated = ts.updateSetAccessor(node, + /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), visitPropertyNameOfClassElement(node), ts.visitParameterList(node.parameters, visitor, context), ts.visitFunctionBody(node.body, visitor, context) || ts.createBlock([])); + if (updated !== node) { + // While we emit the source map for the node after skipping decorators and modifiers, + // we need to emit the comments for the original range. + ts.setCommentRange(updated, node); + ts.setSourceMapRange(updated, ts.moveRangePastDecorators(node)); + } + return updated; + } + /** + * Visits a function declaration. + * + * This function will be called when one of the following conditions are met: + * - The node is an overload + * - The node is exported from a TypeScript namespace + * - The node has decorators + * + * @param node The function node. + */ + function visitFunctionDeclaration(node) { + if (!shouldEmitFunctionLikeDeclaration(node)) { + return ts.createNotEmittedStatement(node); + } + var updated = ts.updateFunctionDeclaration(node, + /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, node.name, + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context) || ts.createBlock([])); + if (isExportOfNamespace(node)) { + var statements = [updated]; + addExportMemberAssignment(statements, node); + return statements; + } + return updated; + } + /** + * Visits a function expression node. + * + * This function will be called when one of the following conditions are met: + * - The node has type annotations + * + * @param node The function expression node. + */ + function visitFunctionExpression(node) { + if (!shouldEmitFunctionLikeDeclaration(node)) { + return ts.createOmittedExpression(); + } + var updated = ts.updateFunctionExpression(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, node.name, + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context) || ts.createBlock([])); + return updated; + } + /** + * @remarks + * This function will be called when one of the following conditions are met: + * - The node has type annotations + */ + function visitArrowFunction(node) { + var updated = ts.updateArrowFunction(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, node.equalsGreaterThanToken, ts.visitFunctionBody(node.body, visitor, context)); + return updated; + } + /** + * Visits a parameter declaration node. + * + * This function will be called when one of the following conditions are met: + * - The node has an accessibility modifier. + * - The node has a questionToken. + * - The node's kind is ThisKeyword. + * + * @param node The parameter declaration node. + */ + function visitParameter(node) { + if (ts.parameterIsThisKeyword(node)) { + return undefined; + } + var parameter = ts.createParameter( + /*decorators*/ undefined, + /*modifiers*/ undefined, node.dotDotDotToken, ts.visitNode(node.name, visitor, ts.isBindingName), + /*questionToken*/ undefined, + /*type*/ undefined, ts.visitNode(node.initializer, visitor, ts.isExpression)); + // While we emit the source map for the node after skipping decorators and modifiers, + // we need to emit the comments for the original range. + ts.setOriginalNode(parameter, node); + ts.setTextRange(parameter, ts.moveRangePastModifiers(node)); + ts.setCommentRange(parameter, node); + ts.setSourceMapRange(parameter, ts.moveRangePastModifiers(node)); + ts.setEmitFlags(parameter.name, 32 /* NoTrailingSourceMap */); + return parameter; + } + /** + * Visits a variable statement in a namespace. + * + * This function will be called when one of the following conditions are met: + * - The node is exported from a TypeScript namespace. + */ + function visitVariableStatement(node) { + if (isExportOfNamespace(node)) { + var variables = ts.getInitializedVariables(node.declarationList); + if (variables.length === 0) { + // elide statement if there are no initialized variables. + return undefined; + } + return ts.setTextRange(ts.createExpressionStatement(ts.inlineExpressions(ts.map(variables, transformInitializedVariable))), node); + } + else { + return ts.visitEachChild(node, visitor, context); + } + } + function transformInitializedVariable(node) { + var name = node.name; + if (ts.isBindingPattern(name)) { + return ts.flattenDestructuringAssignment(node, visitor, context, 0 /* All */, + /*needsValue*/ false, createNamespaceExportExpression); + } + else { + return ts.setTextRange(ts.createAssignment(getNamespaceMemberNameWithSourceMapsAndWithoutComments(name), ts.visitNode(node.initializer, visitor, ts.isExpression)), + /*location*/ node); + } + } + function visitVariableDeclaration(node) { + return ts.updateVariableDeclaration(node, ts.visitNode(node.name, visitor, ts.isBindingName), + /*type*/ undefined, ts.visitNode(node.initializer, visitor, ts.isExpression)); + } + /** + * Visits a parenthesized expression that contains either a type assertion or an `as` + * expression. + * + * @param node The parenthesized expression node. + */ + function visitParenthesizedExpression(node) { + var innerExpression = ts.skipOuterExpressions(node.expression, ~2 /* Assertions */); + if (ts.isAssertionExpression(innerExpression)) { + // Make sure we consider all nested cast expressions, e.g.: + // (-A).x; + var expression = ts.visitNode(node.expression, visitor, ts.isExpression); + // We have an expression of the form: (SubExpr). Emitting this as (SubExpr) + // is really not desirable. We would like to emit the subexpression as-is. Omitting + // the parentheses, however, could cause change in the semantics of the generated + // code if the casted expression has a lower precedence than the rest of the + // expression. + // + // To preserve comments, we return a "PartiallyEmittedExpression" here which will + // preserve the position information of the original expression. + // + // Due to the auto-parenthesization rules used by the visitor and factory functions + // we can safely elide the parentheses here, as a new synthetic + // ParenthesizedExpression will be inserted if we remove parentheses too + // aggressively. + // HOWEVER - if there are leading comments on the expression itself, to handle ASI + // correctly for return and throw, we must keep the parenthesis + if (ts.length(ts.getLeadingCommentRangesOfNode(expression, currentSourceFile))) { + return ts.updateParen(node, expression); + } + return ts.createPartiallyEmittedExpression(expression, node); + } + return ts.visitEachChild(node, visitor, context); + } + function visitAssertionExpression(node) { + var expression = ts.visitNode(node.expression, visitor, ts.isExpression); + return ts.createPartiallyEmittedExpression(expression, node); + } + function visitNonNullExpression(node) { + var expression = ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression); + return ts.createPartiallyEmittedExpression(expression, node); + } + function visitCallExpression(node) { + return ts.updateCall(node, ts.visitNode(node.expression, visitor, ts.isExpression), + /*typeArguments*/ undefined, ts.visitNodes(node.arguments, visitor, ts.isExpression)); + } + function visitNewExpression(node) { + return ts.updateNew(node, ts.visitNode(node.expression, visitor, ts.isExpression), + /*typeArguments*/ undefined, ts.visitNodes(node.arguments, visitor, ts.isExpression)); + } + function visitTaggedTemplateExpression(node) { + return ts.updateTaggedTemplate(node, ts.visitNode(node.tag, visitor, ts.isExpression), + /*typeArguments*/ undefined, ts.visitNode(node.template, visitor, ts.isExpression)); + } + /** + * Determines whether to emit an enum declaration. + * + * @param node The enum declaration node. + */ + function shouldEmitEnumDeclaration(node) { + return !ts.isEnumConst(node) + || compilerOptions.preserveConstEnums + || compilerOptions.isolatedModules; + } + /** + * Visits an enum declaration. + * + * This function will be called any time a TypeScript enum is encountered. + * + * @param node The enum declaration node. + */ + function visitEnumDeclaration(node) { + if (!shouldEmitEnumDeclaration(node)) { + return undefined; + } + var statements = []; + // We request to be advised when the printer is about to print this node. This allows + // us to set up the correct state for later substitutions. + var emitFlags = 2 /* AdviseOnEmitNode */; + // If needed, we should emit a variable declaration for the enum. If we emit + // a leading variable declaration, we should not emit leading comments for the + // enum body. + var varAdded = addVarForEnumOrModuleDeclaration(statements, node); + if (varAdded) { + // We should still emit the comments if we are emitting a system module. + if (moduleKind !== ts.ModuleKind.System || currentLexicalScope !== currentSourceFile) { + emitFlags |= 512 /* NoLeadingComments */; + } + } + // `parameterName` is the declaration name used inside of the enum. + var parameterName = getNamespaceParameterName(node); + // `containerName` is the expression used inside of the enum for assignments. + var containerName = getNamespaceContainerName(node); + // `exportName` is the expression used within this node's container for any exported references. + var exportName = ts.hasModifier(node, 1 /* Export */) + ? ts.getExternalModuleOrNamespaceExportName(currentNamespaceContainerName, node, /*allowComments*/ false, /*allowSourceMaps*/ true) + : ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true); + // x || (x = {}) + // exports.x || (exports.x = {}) + var moduleArg = ts.createLogicalOr(exportName, ts.createAssignment(exportName, ts.createObjectLiteral())); + if (hasNamespaceQualifiedExportName(node)) { + // `localName` is the expression used within this node's containing scope for any local references. + var localName = ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true); + // x = (exports.x || (exports.x = {})) + moduleArg = ts.createAssignment(localName, moduleArg); + } + // (function (x) { + // x[x["y"] = 0] = "y"; + // ... + // })(x || (x = {})); + var enumStatement = ts.createExpressionStatement(ts.createCall(ts.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, parameterName)], + /*type*/ undefined, transformEnumBody(node, containerName)), + /*typeArguments*/ undefined, [moduleArg])); + ts.setOriginalNode(enumStatement, node); + if (varAdded) { + // If a variable was added, synthetic comments are emitted on it, not on the moduleStatement. + ts.setSyntheticLeadingComments(enumStatement, undefined); + ts.setSyntheticTrailingComments(enumStatement, undefined); + } + ts.setTextRange(enumStatement, node); + ts.addEmitFlags(enumStatement, emitFlags); + statements.push(enumStatement); + // Add a DeclarationMarker for the enum to preserve trailing comments and mark + // the end of the declaration. + statements.push(ts.createEndOfDeclarationMarker(node)); + return statements; + } + /** + * Transforms the body of an enum declaration. + * + * @param node The enum declaration node. + */ + function transformEnumBody(node, localName) { + var savedCurrentNamespaceLocalName = currentNamespaceContainerName; + currentNamespaceContainerName = localName; + var statements = []; + startLexicalEnvironment(); + var members = ts.map(node.members, transformEnumMember); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + ts.addRange(statements, members); + currentNamespaceContainerName = savedCurrentNamespaceLocalName; + return ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), /*location*/ node.members), + /*multiLine*/ true); + } + /** + * Transforms an enum member into a statement. + * + * @param member The enum member node. + */ + function transformEnumMember(member) { + // enums don't support computed properties + // we pass false as 'generateNameForComputedPropertyName' for a backward compatibility purposes + // old emitter always generate 'expression' part of the name as-is. + var name = getExpressionForPropertyName(member, /*generateNameForComputedPropertyName*/ false); + var valueExpression = transformEnumMemberDeclarationValue(member); + var innerAssignment = ts.createAssignment(ts.createElementAccess(currentNamespaceContainerName, name), valueExpression); + var outerAssignment = valueExpression.kind === 10 /* StringLiteral */ ? + innerAssignment : + ts.createAssignment(ts.createElementAccess(currentNamespaceContainerName, innerAssignment), name); + return ts.setTextRange(ts.createExpressionStatement(ts.setTextRange(outerAssignment, member)), member); + } + /** + * Transforms the value of an enum member. + * + * @param member The enum member node. + */ + function transformEnumMemberDeclarationValue(member) { + var value = resolver.getConstantValue(member); + if (value !== undefined) { + return ts.createLiteral(value); + } + else { + enableSubstitutionForNonQualifiedEnumMembers(); + if (member.initializer) { + return ts.visitNode(member.initializer, visitor, ts.isExpression); + } + else { + return ts.createVoidZero(); + } + } + } + /** + * Determines whether to elide a module declaration. + * + * @param node The module declaration node. + */ + function shouldEmitModuleDeclaration(node) { + return ts.isInstantiatedModule(node, !!compilerOptions.preserveConstEnums || !!compilerOptions.isolatedModules); + } + /** + * Determines whether an exported declaration will have a qualified export name (e.g. `f.x` + * or `exports.x`). + */ + function hasNamespaceQualifiedExportName(node) { + return isExportOfNamespace(node) + || (isExternalModuleExport(node) + && moduleKind !== ts.ModuleKind.ES2015 + && moduleKind !== ts.ModuleKind.ESNext + && moduleKind !== ts.ModuleKind.System); + } + /** + * Records that a declaration was emitted in the current scope, if it was the first + * declaration for the provided symbol. + */ + function recordEmittedDeclarationInScope(node) { + if (!currentScopeFirstDeclarationsOfName) { + currentScopeFirstDeclarationsOfName = ts.createUnderscoreEscapedMap(); + } + var name = declaredNameInScope(node); + if (!currentScopeFirstDeclarationsOfName.has(name)) { + currentScopeFirstDeclarationsOfName.set(name, node); + } + } + /** + * Determines whether a declaration is the first declaration with + * the same name emitted in the current scope. + */ + function isFirstEmittedDeclarationInScope(node) { + if (currentScopeFirstDeclarationsOfName) { + var name = declaredNameInScope(node); + return currentScopeFirstDeclarationsOfName.get(name) === node; + } + return true; + } + function declaredNameInScope(node) { + ts.Debug.assertNode(node.name, ts.isIdentifier); + return node.name.escapedText; + } + /** + * Adds a leading VariableStatement for a enum or module declaration. + */ + function addVarForEnumOrModuleDeclaration(statements, node) { + // Emit a variable statement for the module. We emit top-level enums as a `var` + // declaration to avoid static errors in global scripts scripts due to redeclaration. + // enums in any other scope are emitted as a `let` declaration. + var statement = ts.createVariableStatement(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.createVariableDeclarationList([ + ts.createVariableDeclaration(ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true)) + ], currentLexicalScope.kind === 279 /* SourceFile */ ? 0 /* None */ : 1 /* Let */)); + ts.setOriginalNode(statement, node); + recordEmittedDeclarationInScope(node); + if (isFirstEmittedDeclarationInScope(node)) { + // Adjust the source map emit to match the old emitter. + if (node.kind === 243 /* EnumDeclaration */) { + ts.setSourceMapRange(statement.declarationList, node); + } + else { + ts.setSourceMapRange(statement, node); + } + // Trailing comments for module declaration should be emitted after the function closure + // instead of the variable statement: + // + // /** Module comment*/ + // module m1 { + // function foo4Export() { + // } + // } // trailing comment module + // + // Should emit: + // + // /** Module comment*/ + // var m1; + // (function (m1) { + // function foo4Export() { + // } + // })(m1 || (m1 = {})); // trailing comment module + // + ts.setCommentRange(statement, node); + ts.addEmitFlags(statement, 1024 /* NoTrailingComments */ | 4194304 /* HasEndOfDeclarationMarker */); + statements.push(statement); + return true; + } + else { + // For an EnumDeclaration or ModuleDeclaration that merges with a preceeding + // declaration we do not emit a leading variable declaration. To preserve the + // begin/end semantics of the declararation and to properly handle exports + // we wrap the leading variable declaration in a `MergeDeclarationMarker`. + var mergeMarker = ts.createMergeDeclarationMarker(statement); + ts.setEmitFlags(mergeMarker, 1536 /* NoComments */ | 4194304 /* HasEndOfDeclarationMarker */); + statements.push(mergeMarker); + return false; + } + } + /** + * Visits a module declaration node. + * + * This function will be called any time a TypeScript namespace (ModuleDeclaration) is encountered. + * + * @param node The module declaration node. + */ + function visitModuleDeclaration(node) { + if (!shouldEmitModuleDeclaration(node)) { + return ts.createNotEmittedStatement(node); + } + ts.Debug.assertNode(node.name, ts.isIdentifier, "A TypeScript namespace should have an Identifier name."); + enableSubstitutionForNamespaceExports(); + var statements = []; + // We request to be advised when the printer is about to print this node. This allows + // us to set up the correct state for later substitutions. + var emitFlags = 2 /* AdviseOnEmitNode */; + // If needed, we should emit a variable declaration for the module. If we emit + // a leading variable declaration, we should not emit leading comments for the + // module body. + var varAdded = addVarForEnumOrModuleDeclaration(statements, node); + if (varAdded) { + // We should still emit the comments if we are emitting a system module. + if (moduleKind !== ts.ModuleKind.System || currentLexicalScope !== currentSourceFile) { + emitFlags |= 512 /* NoLeadingComments */; + } + } + // `parameterName` is the declaration name used inside of the namespace. + var parameterName = getNamespaceParameterName(node); + // `containerName` is the expression used inside of the namespace for exports. + var containerName = getNamespaceContainerName(node); + // `exportName` is the expression used within this node's container for any exported references. + var exportName = ts.hasModifier(node, 1 /* Export */) + ? ts.getExternalModuleOrNamespaceExportName(currentNamespaceContainerName, node, /*allowComments*/ false, /*allowSourceMaps*/ true) + : ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true); + // x || (x = {}) + // exports.x || (exports.x = {}) + var moduleArg = ts.createLogicalOr(exportName, ts.createAssignment(exportName, ts.createObjectLiteral())); + if (hasNamespaceQualifiedExportName(node)) { + // `localName` is the expression used within this node's containing scope for any local references. + var localName = ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true); + // x = (exports.x || (exports.x = {})) + moduleArg = ts.createAssignment(localName, moduleArg); + } + // (function (x_1) { + // x_1.y = ...; + // })(x || (x = {})); + var moduleStatement = ts.createExpressionStatement(ts.createCall(ts.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, parameterName)], + /*type*/ undefined, transformModuleBody(node, containerName)), + /*typeArguments*/ undefined, [moduleArg])); + ts.setOriginalNode(moduleStatement, node); + if (varAdded) { + // If a variable was added, synthetic comments are emitted on it, not on the moduleStatement. + ts.setSyntheticLeadingComments(moduleStatement, undefined); + ts.setSyntheticTrailingComments(moduleStatement, undefined); + } + ts.setTextRange(moduleStatement, node); + ts.addEmitFlags(moduleStatement, emitFlags); + statements.push(moduleStatement); + // Add a DeclarationMarker for the namespace to preserve trailing comments and mark + // the end of the declaration. + statements.push(ts.createEndOfDeclarationMarker(node)); + return statements; + } + /** + * Transforms the body of a module declaration. + * + * @param node The module declaration node. + */ + function transformModuleBody(node, namespaceLocalName) { + var savedCurrentNamespaceContainerName = currentNamespaceContainerName; + var savedCurrentNamespace = currentNamespace; + var savedCurrentScopeFirstDeclarationsOfName = currentScopeFirstDeclarationsOfName; + currentNamespaceContainerName = namespaceLocalName; + currentNamespace = node; + currentScopeFirstDeclarationsOfName = undefined; + var statements = []; + startLexicalEnvironment(); + var statementsLocation; + var blockLocation; + var body = node.body; + if (body.kind === 245 /* ModuleBlock */) { + saveStateAndInvoke(body, function (body) { return ts.addRange(statements, ts.visitNodes(body.statements, namespaceElementVisitor, ts.isStatement)); }); + statementsLocation = body.statements; + blockLocation = body; + } + else { + var result = visitModuleDeclaration(body); + if (result) { + if (ts.isArray(result)) { + ts.addRange(statements, result); + } + else { + statements.push(result); + } + } + var moduleBlock = getInnerMostModuleDeclarationFromDottedModule(node).body; + statementsLocation = ts.moveRangePos(moduleBlock.statements, -1); + } + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + currentNamespaceContainerName = savedCurrentNamespaceContainerName; + currentNamespace = savedCurrentNamespace; + currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName; + var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), + /*location*/ statementsLocation), + /*multiLine*/ true); + ts.setTextRange(block, blockLocation); + // namespace hello.hi.world { + // function foo() {} + // + // // TODO, blah + // } + // + // should be emitted as + // + // var hello; + // (function (hello) { + // var hi; + // (function (hi) { + // var world; + // (function (world) { + // function foo() { } + // // TODO, blah + // })(world = hi.world || (hi.world = {})); + // })(hi = hello.hi || (hello.hi = {})); + // })(hello || (hello = {})); + // We only want to emit comment on the namespace which contains block body itself, not the containing namespaces. + if (body.kind !== 245 /* ModuleBlock */) { + ts.setEmitFlags(block, ts.getEmitFlags(block) | 1536 /* NoComments */); + } + return block; + } + function getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration) { + if (moduleDeclaration.body.kind === 244 /* ModuleDeclaration */) { + var recursiveInnerModule = getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration.body); + return recursiveInnerModule || moduleDeclaration.body; + } + } + /** + * Visits an import declaration, eliding it if it is not referenced. + * + * @param node The import declaration node. + */ + function visitImportDeclaration(node) { + if (!node.importClause) { + // Do not elide a side-effect only import declaration. + // import "foo"; + return node; + } + // Elide the declaration if the import clause was elided. + var importClause = ts.visitNode(node.importClause, visitImportClause, ts.isImportClause); + return importClause + ? ts.updateImportDeclaration(node, + /*decorators*/ undefined, + /*modifiers*/ undefined, importClause, node.moduleSpecifier) + : undefined; + } + /** + * Visits an import clause, eliding it if it is not referenced. + * + * @param node The import clause node. + */ + function visitImportClause(node) { + // Elide the import clause if we elide both its name and its named bindings. + var name = resolver.isReferencedAliasDeclaration(node) ? node.name : undefined; + var namedBindings = ts.visitNode(node.namedBindings, visitNamedImportBindings, ts.isNamedImportBindings); + return (name || namedBindings) ? ts.updateImportClause(node, name, namedBindings) : undefined; + } + /** + * Visits named import bindings, eliding it if it is not referenced. + * + * @param node The named import bindings node. + */ + function visitNamedImportBindings(node) { + if (node.kind === 251 /* NamespaceImport */) { + // Elide a namespace import if it is not referenced. + return resolver.isReferencedAliasDeclaration(node) ? node : undefined; + } + else { + // Elide named imports if all of its import specifiers are elided. + var elements = ts.visitNodes(node.elements, visitImportSpecifier, ts.isImportSpecifier); + return ts.some(elements) ? ts.updateNamedImports(node, elements) : undefined; + } + } + /** + * Visits an import specifier, eliding it if it is not referenced. + * + * @param node The import specifier node. + */ + function visitImportSpecifier(node) { + // Elide an import specifier if it is not referenced. + return resolver.isReferencedAliasDeclaration(node) ? node : undefined; + } + /** + * Visits an export assignment, eliding it if it does not contain a clause that resolves + * to a value. + * + * @param node The export assignment node. + */ + function visitExportAssignment(node) { + // Elide the export assignment if it does not reference a value. + return resolver.isValueAliasDeclaration(node) + ? ts.visitEachChild(node, visitor, context) + : undefined; + } + /** + * Visits an export declaration, eliding it if it does not contain a clause that resolves + * to a value. + * + * @param node The export declaration node. + */ + function visitExportDeclaration(node) { + if (!node.exportClause) { + // Elide a star export if the module it references does not export a value. + return compilerOptions.isolatedModules || resolver.moduleExportsSomeValue(node.moduleSpecifier) ? node : undefined; + } + if (!resolver.isValueAliasDeclaration(node)) { + // Elide the export declaration if it does not export a value. + return undefined; + } + // Elide the export declaration if all of its named exports are elided. + var exportClause = ts.visitNode(node.exportClause, visitNamedExports, ts.isNamedExports); + return exportClause + ? ts.updateExportDeclaration(node, + /*decorators*/ undefined, + /*modifiers*/ undefined, exportClause, node.moduleSpecifier) + : undefined; + } + /** + * Visits named exports, eliding it if it does not contain an export specifier that + * resolves to a value. + * + * @param node The named exports node. + */ + function visitNamedExports(node) { + // Elide the named exports if all of its export specifiers were elided. + var elements = ts.visitNodes(node.elements, visitExportSpecifier, ts.isExportSpecifier); + return ts.some(elements) ? ts.updateNamedExports(node, elements) : undefined; + } + /** + * Visits an export specifier, eliding it if it does not resolve to a value. + * + * @param node The export specifier node. + */ + function visitExportSpecifier(node) { + // Elide an export specifier if it does not reference a value. + return resolver.isValueAliasDeclaration(node) ? node : undefined; + } + /** + * Determines whether to emit an import equals declaration. + * + * @param node The import equals declaration node. + */ + function shouldEmitImportEqualsDeclaration(node) { + // preserve old compiler's behavior: emit 'var' for import declaration (even if we do not consider them referenced) when + // - current file is not external module + // - import declaration is top level and target is value imported by entity name + return resolver.isReferencedAliasDeclaration(node) + || (!ts.isExternalModule(currentSourceFile) + && resolver.isTopLevelValueImportEqualsWithEntityName(node)); + } + /** + * Visits an import equals declaration. + * + * @param node The import equals declaration node. + */ + function visitImportEqualsDeclaration(node) { + if (ts.isExternalModuleImportEqualsDeclaration(node)) { + // Elide external module `import=` if it is not referenced. + return resolver.isReferencedAliasDeclaration(node) + ? ts.visitEachChild(node, visitor, context) + : undefined; + } + if (!shouldEmitImportEqualsDeclaration(node)) { + return undefined; + } + var moduleReference = ts.createExpressionFromEntityName(node.moduleReference); + ts.setEmitFlags(moduleReference, 1536 /* NoComments */ | 2048 /* NoNestedComments */); + if (isNamedExternalModuleExport(node) || !isExportOfNamespace(node)) { + // export var ${name} = ${moduleReference}; + // var ${name} = ${moduleReference}; + return ts.setOriginalNode(ts.setTextRange(ts.createVariableStatement(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.createVariableDeclarationList([ + ts.setOriginalNode(ts.createVariableDeclaration(node.name, + /*type*/ undefined, moduleReference), node) + ])), node), node); + } + else { + // exports.${name} = ${moduleReference}; + return ts.setOriginalNode(createNamespaceExport(node.name, moduleReference, node), node); + } + } + /** + * Gets a value indicating whether the node is exported from a namespace. + * + * @param node The node to test. + */ + function isExportOfNamespace(node) { + return currentNamespace !== undefined && ts.hasModifier(node, 1 /* Export */); + } + /** + * Gets a value indicating whether the node is exported from an external module. + * + * @param node The node to test. + */ + function isExternalModuleExport(node) { + return currentNamespace === undefined && ts.hasModifier(node, 1 /* Export */); + } + /** + * Gets a value indicating whether the node is a named export from an external module. + * + * @param node The node to test. + */ + function isNamedExternalModuleExport(node) { + return isExternalModuleExport(node) + && !ts.hasModifier(node, 512 /* Default */); + } + /** + * Gets a value indicating whether the node is the default export of an external module. + * + * @param node The node to test. + */ + function isDefaultExternalModuleExport(node) { + return isExternalModuleExport(node) + && ts.hasModifier(node, 512 /* Default */); + } + /** + * Creates a statement for the provided expression. This is used in calls to `map`. + */ + function expressionToStatement(expression) { + return ts.createExpressionStatement(expression); + } + function addExportMemberAssignment(statements, node) { + var expression = ts.createAssignment(ts.getExternalModuleOrNamespaceExportName(currentNamespaceContainerName, node, /*allowComments*/ false, /*allowSourceMaps*/ true), ts.getLocalName(node)); + ts.setSourceMapRange(expression, ts.createRange(node.name ? node.name.pos : node.pos, node.end)); + var statement = ts.createExpressionStatement(expression); + ts.setSourceMapRange(statement, ts.createRange(-1, node.end)); + statements.push(statement); + } + function createNamespaceExport(exportName, exportValue, location) { + return ts.setTextRange(ts.createExpressionStatement(ts.createAssignment(ts.getNamespaceMemberName(currentNamespaceContainerName, exportName, /*allowComments*/ false, /*allowSourceMaps*/ true), exportValue)), location); + } + function createNamespaceExportExpression(exportName, exportValue, location) { + return ts.setTextRange(ts.createAssignment(getNamespaceMemberNameWithSourceMapsAndWithoutComments(exportName), exportValue), location); + } + function getNamespaceMemberNameWithSourceMapsAndWithoutComments(name) { + return ts.getNamespaceMemberName(currentNamespaceContainerName, name, /*allowComments*/ false, /*allowSourceMaps*/ true); + } + /** + * Gets the declaration name used inside of a namespace or enum. + */ + function getNamespaceParameterName(node) { + var name = ts.getGeneratedNameForNode(node); + ts.setSourceMapRange(name, node.name); + return name; + } + /** + * Gets the expression used to refer to a namespace or enum within the body + * of its declaration. + */ + function getNamespaceContainerName(node) { + return ts.getGeneratedNameForNode(node); + } + /** + * Gets a local alias for a class declaration if it is a decorated class with an internal + * reference to the static side of the class. This is necessary to avoid issues with + * double-binding semantics for the class name. + */ + function getClassAliasIfNeeded(node) { + if (resolver.getNodeCheckFlags(node) & 16777216 /* ClassWithConstructorReference */) { + enableSubstitutionForClassAliases(); + var classAlias = ts.createUniqueName(node.name && !ts.isGeneratedIdentifier(node.name) ? ts.idText(node.name) : "default"); + classAliases[ts.getOriginalNodeId(node)] = classAlias; + hoistVariableDeclaration(classAlias); + return classAlias; + } + } + function getClassPrototype(node) { + return ts.createPropertyAccess(ts.getDeclarationName(node), "prototype"); + } + function getClassMemberPrefix(node, member) { + return ts.hasModifier(member, 32 /* Static */) + ? ts.getDeclarationName(node) + : getClassPrototype(node); + } + function enableSubstitutionForNonQualifiedEnumMembers() { + if ((enabledSubstitutions & 8 /* NonQualifiedEnumMembers */) === 0) { + enabledSubstitutions |= 8 /* NonQualifiedEnumMembers */; + context.enableSubstitution(72 /* Identifier */); + } + } + function enableSubstitutionForClassAliases() { + if ((enabledSubstitutions & 1 /* ClassAliases */) === 0) { + enabledSubstitutions |= 1 /* ClassAliases */; + // We need to enable substitutions for identifiers. This allows us to + // substitute class names inside of a class declaration. + context.enableSubstitution(72 /* Identifier */); + // Keep track of class aliases. + classAliases = []; + } + } + function enableSubstitutionForNamespaceExports() { + if ((enabledSubstitutions & 2 /* NamespaceExports */) === 0) { + enabledSubstitutions |= 2 /* NamespaceExports */; + // We need to enable substitutions for identifiers and shorthand property assignments. This allows us to + // substitute the names of exported members of a namespace. + context.enableSubstitution(72 /* Identifier */); + context.enableSubstitution(276 /* ShorthandPropertyAssignment */); + // We need to be notified when entering and exiting namespaces. + context.enableEmitNotification(244 /* ModuleDeclaration */); + } + } + function isTransformedModuleDeclaration(node) { + return ts.getOriginalNode(node).kind === 244 /* ModuleDeclaration */; + } + function isTransformedEnumDeclaration(node) { + return ts.getOriginalNode(node).kind === 243 /* EnumDeclaration */; + } + /** + * Hook for node emit. + * + * @param hint A hint as to the intended usage of the node. + * @param node The node to emit. + * @param emit A callback used to emit the node in the printer. + */ + function onEmitNode(hint, node, emitCallback) { + var savedApplicableSubstitutions = applicableSubstitutions; + var savedCurrentSourceFile = currentSourceFile; + if (ts.isSourceFile(node)) { + currentSourceFile = node; + } + if (enabledSubstitutions & 2 /* NamespaceExports */ && isTransformedModuleDeclaration(node)) { + applicableSubstitutions |= 2 /* NamespaceExports */; + } + if (enabledSubstitutions & 8 /* NonQualifiedEnumMembers */ && isTransformedEnumDeclaration(node)) { + applicableSubstitutions |= 8 /* NonQualifiedEnumMembers */; + } + previousOnEmitNode(hint, node, emitCallback); + applicableSubstitutions = savedApplicableSubstitutions; + currentSourceFile = savedCurrentSourceFile; + } + /** + * Hooks node substitutions. + * + * @param hint A hint as to the intended usage of the node. + * @param node The node to substitute. + */ + function onSubstituteNode(hint, node) { + node = previousOnSubstituteNode(hint, node); + if (hint === 1 /* Expression */) { + return substituteExpression(node); + } + else if (ts.isShorthandPropertyAssignment(node)) { + return substituteShorthandPropertyAssignment(node); + } + return node; + } + function substituteShorthandPropertyAssignment(node) { + if (enabledSubstitutions & 2 /* NamespaceExports */) { + var name = node.name; + var exportedName = trySubstituteNamespaceExportedName(name); + if (exportedName) { + // A shorthand property with an assignment initializer is probably part of a + // destructuring assignment + if (node.objectAssignmentInitializer) { + var initializer = ts.createAssignment(exportedName, node.objectAssignmentInitializer); + return ts.setTextRange(ts.createPropertyAssignment(name, initializer), node); + } + return ts.setTextRange(ts.createPropertyAssignment(name, exportedName), node); + } + } + return node; + } + function substituteExpression(node) { + switch (node.kind) { + case 72 /* Identifier */: + return substituteExpressionIdentifier(node); + case 189 /* PropertyAccessExpression */: + return substitutePropertyAccessExpression(node); + case 190 /* ElementAccessExpression */: + return substituteElementAccessExpression(node); + } + return node; + } + function substituteExpressionIdentifier(node) { + return trySubstituteClassAlias(node) + || trySubstituteNamespaceExportedName(node) + || node; + } + function trySubstituteClassAlias(node) { + if (enabledSubstitutions & 1 /* ClassAliases */) { + if (resolver.getNodeCheckFlags(node) & 33554432 /* ConstructorReferenceInClass */) { + // Due to the emit for class decorators, any reference to the class from inside of the class body + // must instead be rewritten to point to a temporary variable to avoid issues with the double-bind + // behavior of class names in ES6. + // Also, when emitting statics for class expressions, we must substitute a class alias for + // constructor references in static property initializers. + var declaration = resolver.getReferencedValueDeclaration(node); + if (declaration) { + var classAlias = classAliases[declaration.id]; // TODO: GH#18217 + if (classAlias) { + var clone_1 = ts.getSynthesizedClone(classAlias); + ts.setSourceMapRange(clone_1, node); + ts.setCommentRange(clone_1, node); + return clone_1; + } + } + } + } + return undefined; + } + function trySubstituteNamespaceExportedName(node) { + // If this is explicitly a local name, do not substitute. + if (enabledSubstitutions & applicableSubstitutions && !ts.isGeneratedIdentifier(node) && !ts.isLocalName(node)) { + // If we are nested within a namespace declaration, we may need to qualifiy + // an identifier that is exported from a merged namespace. + var container = resolver.getReferencedExportContainer(node, /*prefixLocals*/ false); + if (container && container.kind !== 279 /* SourceFile */) { + var substitute = (applicableSubstitutions & 2 /* NamespaceExports */ && container.kind === 244 /* ModuleDeclaration */) || + (applicableSubstitutions & 8 /* NonQualifiedEnumMembers */ && container.kind === 243 /* EnumDeclaration */); + if (substitute) { + return ts.setTextRange(ts.createPropertyAccess(ts.getGeneratedNameForNode(container), node), + /*location*/ node); + } + } + } + return undefined; + } + function substitutePropertyAccessExpression(node) { + return substituteConstantValue(node); + } + function substituteElementAccessExpression(node) { + return substituteConstantValue(node); + } + function substituteConstantValue(node) { + var constantValue = tryGetConstEnumValue(node); + if (constantValue !== undefined) { + // track the constant value on the node for the printer in needsDotDotForPropertyAccess + ts.setConstantValue(node, constantValue); + var substitute = ts.createLiteral(constantValue); + if (!compilerOptions.removeComments) { + var propertyName = ts.isPropertyAccessExpression(node) + ? ts.declarationNameToString(node.name) + : ts.getTextOfNode(node.argumentExpression); + ts.addSyntheticTrailingComment(substitute, 3 /* MultiLineCommentTrivia */, " " + propertyName + " "); + } + return substitute; + } + return node; + } + function tryGetConstEnumValue(node) { + if (compilerOptions.isolatedModules) { + return undefined; + } + return ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node) ? resolver.getConstantValue(node) : undefined; + } + } + ts.transformTypeScript = transformTypeScript; + function createDecorateHelper(context, decoratorExpressions, target, memberName, descriptor, location) { + var argumentsArray = []; + argumentsArray.push(ts.createArrayLiteral(decoratorExpressions, /*multiLine*/ true)); + argumentsArray.push(target); + if (memberName) { + argumentsArray.push(memberName); + if (descriptor) { + argumentsArray.push(descriptor); + } + } + context.requestEmitHelper(decorateHelper); + return ts.setTextRange(ts.createCall(ts.getHelperName("__decorate"), + /*typeArguments*/ undefined, argumentsArray), location); + } + var decorateHelper = { + name: "typescript:decorate", + scoped: false, + priority: 2, + text: "\n var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n };" + }; + function createMetadataHelper(context, metadataKey, metadataValue) { + context.requestEmitHelper(metadataHelper); + return ts.createCall(ts.getHelperName("__metadata"), + /*typeArguments*/ undefined, [ + ts.createLiteral(metadataKey), + metadataValue + ]); + } + var metadataHelper = { + name: "typescript:metadata", + scoped: false, + priority: 3, + text: "\n var __metadata = (this && this.__metadata) || function (k, v) {\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(k, v);\n };" + }; + function createParamHelper(context, expression, parameterOffset, location) { + context.requestEmitHelper(paramHelper); + return ts.setTextRange(ts.createCall(ts.getHelperName("__param"), + /*typeArguments*/ undefined, [ + ts.createLiteral(parameterOffset), + expression + ]), location); + } + var paramHelper = { + name: "typescript:param", + scoped: false, + priority: 4, + text: "\n var __param = (this && this.__param) || function (paramIndex, decorator) {\n return function (target, key) { decorator(target, key, paramIndex); }\n };" + }; +})(ts || (ts = {})); +/*@internal*/ +var ts; +(function (ts) { + var ES2017SubstitutionFlags; + (function (ES2017SubstitutionFlags) { + /** Enables substitutions for async methods with `super` calls. */ + ES2017SubstitutionFlags[ES2017SubstitutionFlags["AsyncMethodsWithSuper"] = 1] = "AsyncMethodsWithSuper"; + })(ES2017SubstitutionFlags || (ES2017SubstitutionFlags = {})); + function transformES2017(context) { + var resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; + var resolver = context.getEmitResolver(); + var compilerOptions = context.getCompilerOptions(); + var languageVersion = ts.getEmitScriptTarget(compilerOptions); + /** + * Keeps track of whether expression substitution has been enabled for specific edge cases. + * They are persisted between each SourceFile transformation and should not be reset. + */ + var enabledSubstitutions; + /** + * This keeps track of containers where `super` is valid, for use with + * just-in-time substitution for `super` expressions inside of async methods. + */ + var enclosingSuperContainerFlags = 0; + var enclosingFunctionParameterNames; + /** + * Keeps track of property names accessed on super (`super.x`) within async functions. + */ + var capturedSuperProperties; + /** Whether the async function contains an element access on super (`super[x]`). */ + var hasSuperElementAccess; + /** A set of node IDs for generated super accessors (variable statements). */ + var substitutedSuperAccessors = []; + // Save the previous transformation hooks. + var previousOnEmitNode = context.onEmitNode; + var previousOnSubstituteNode = context.onSubstituteNode; + // Set new transformation hooks. + context.onEmitNode = onEmitNode; + context.onSubstituteNode = onSubstituteNode; + return ts.chainBundle(transformSourceFile); + function transformSourceFile(node) { + if (node.isDeclarationFile) { + return node; + } + var visited = ts.visitEachChild(node, visitor, context); + ts.addEmitHelpers(visited, context.readEmitHelpers()); + return visited; + } + function visitor(node) { + if ((node.transformFlags & 16 /* ContainsES2017 */) === 0) { + return node; + } + switch (node.kind) { + case 121 /* AsyncKeyword */: + // ES2017 async modifier should be elided for targets < ES2017 + return undefined; + case 201 /* AwaitExpression */: + return visitAwaitExpression(node); + case 156 /* MethodDeclaration */: + return visitMethodDeclaration(node); + case 239 /* FunctionDeclaration */: + return visitFunctionDeclaration(node); + case 196 /* FunctionExpression */: + return visitFunctionExpression(node); + case 197 /* ArrowFunction */: + return visitArrowFunction(node); + case 189 /* PropertyAccessExpression */: + if (capturedSuperProperties && ts.isPropertyAccessExpression(node) && node.expression.kind === 98 /* SuperKeyword */) { + capturedSuperProperties.set(node.name.escapedText, true); + } + return ts.visitEachChild(node, visitor, context); + case 190 /* ElementAccessExpression */: + if (capturedSuperProperties && node.expression.kind === 98 /* SuperKeyword */) { + hasSuperElementAccess = true; + } + return ts.visitEachChild(node, visitor, context); + default: + return ts.visitEachChild(node, visitor, context); + } + } + function asyncBodyVisitor(node) { + if (ts.isNodeWithPossibleHoistedDeclaration(node)) { + switch (node.kind) { + case 219 /* VariableStatement */: + return visitVariableStatementInAsyncBody(node); + case 225 /* ForStatement */: + return visitForStatementInAsyncBody(node); + case 226 /* ForInStatement */: + return visitForInStatementInAsyncBody(node); + case 227 /* ForOfStatement */: + return visitForOfStatementInAsyncBody(node); + case 274 /* CatchClause */: + return visitCatchClauseInAsyncBody(node); + case 218 /* Block */: + case 232 /* SwitchStatement */: + case 246 /* CaseBlock */: + case 271 /* CaseClause */: + case 272 /* DefaultClause */: + case 235 /* TryStatement */: + case 223 /* DoStatement */: + case 224 /* WhileStatement */: + case 222 /* IfStatement */: + case 231 /* WithStatement */: + case 233 /* LabeledStatement */: + return ts.visitEachChild(node, asyncBodyVisitor, context); + default: + return ts.Debug.assertNever(node, "Unhandled node."); + } + } + return visitor(node); + } + function visitCatchClauseInAsyncBody(node) { + var catchClauseNames = ts.createUnderscoreEscapedMap(); + recordDeclarationName(node.variableDeclaration, catchClauseNames); // TODO: GH#18217 + // names declared in a catch variable are block scoped + var catchClauseUnshadowedNames; + catchClauseNames.forEach(function (_, escapedName) { + if (enclosingFunctionParameterNames.has(escapedName)) { + if (!catchClauseUnshadowedNames) { + catchClauseUnshadowedNames = ts.cloneMap(enclosingFunctionParameterNames); + } + catchClauseUnshadowedNames.delete(escapedName); + } + }); + if (catchClauseUnshadowedNames) { + var savedEnclosingFunctionParameterNames = enclosingFunctionParameterNames; + enclosingFunctionParameterNames = catchClauseUnshadowedNames; + var result = ts.visitEachChild(node, asyncBodyVisitor, context); + enclosingFunctionParameterNames = savedEnclosingFunctionParameterNames; + return result; + } + else { + return ts.visitEachChild(node, asyncBodyVisitor, context); + } + } + function visitVariableStatementInAsyncBody(node) { + if (isVariableDeclarationListWithCollidingName(node.declarationList)) { + var expression = visitVariableDeclarationListWithCollidingNames(node.declarationList, /*hasReceiver*/ false); + return expression ? ts.createExpressionStatement(expression) : undefined; + } + return ts.visitEachChild(node, visitor, context); + } + function visitForInStatementInAsyncBody(node) { + return ts.updateForIn(node, isVariableDeclarationListWithCollidingName(node.initializer) + ? visitVariableDeclarationListWithCollidingNames(node.initializer, /*hasReceiver*/ true) + : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitNode(node.statement, asyncBodyVisitor, ts.isStatement, ts.liftToBlock)); + } + function visitForOfStatementInAsyncBody(node) { + return ts.updateForOf(node, ts.visitNode(node.awaitModifier, visitor, ts.isToken), isVariableDeclarationListWithCollidingName(node.initializer) + ? visitVariableDeclarationListWithCollidingNames(node.initializer, /*hasReceiver*/ true) + : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitNode(node.statement, asyncBodyVisitor, ts.isStatement, ts.liftToBlock)); + } + function visitForStatementInAsyncBody(node) { + var initializer = node.initializer; // TODO: GH#18217 + return ts.updateFor(node, isVariableDeclarationListWithCollidingName(initializer) + ? visitVariableDeclarationListWithCollidingNames(initializer, /*hasReceiver*/ false) + : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.condition, visitor, ts.isExpression), ts.visitNode(node.incrementor, visitor, ts.isExpression), ts.visitNode(node.statement, asyncBodyVisitor, ts.isStatement, ts.liftToBlock)); + } + /** + * Visits an AwaitExpression node. + * + * This function will be called any time a ES2017 await expression is encountered. + * + * @param node The node to visit. + */ + function visitAwaitExpression(node) { + return ts.setOriginalNode(ts.setTextRange(ts.createYield( + /*asteriskToken*/ undefined, ts.visitNode(node.expression, visitor, ts.isExpression)), node), node); + } + /** + * Visits a MethodDeclaration node. + * + * This function will be called when one of the following conditions are met: + * - The node is marked as async + * + * @param node The node to visit. + */ + function visitMethodDeclaration(node) { + return ts.updateMethod(node, + /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, node.name, + /*questionToken*/ undefined, + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, ts.getFunctionFlags(node) & 2 /* Async */ + ? transformAsyncFunctionBody(node) + : ts.visitFunctionBody(node.body, visitor, context)); + } + /** + * Visits a FunctionDeclaration node. + * + * This function will be called when one of the following conditions are met: + * - The node is marked async + * + * @param node The node to visit. + */ + function visitFunctionDeclaration(node) { + return ts.updateFunctionDeclaration(node, + /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, node.name, + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, ts.getFunctionFlags(node) & 2 /* Async */ + ? transformAsyncFunctionBody(node) + : ts.visitFunctionBody(node.body, visitor, context)); + } + /** + * Visits a FunctionExpression node. + * + * This function will be called when one of the following conditions are met: + * - The node is marked async + * + * @param node The node to visit. + */ + function visitFunctionExpression(node) { + return ts.updateFunctionExpression(node, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, node.name, + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, ts.getFunctionFlags(node) & 2 /* Async */ + ? transformAsyncFunctionBody(node) + : ts.visitFunctionBody(node.body, visitor, context)); + } + /** + * Visits an ArrowFunction. + * + * This function will be called when one of the following conditions are met: + * - The node is marked async + * + * @param node The node to visit. + */ + function visitArrowFunction(node) { + return ts.updateArrowFunction(node, ts.visitNodes(node.modifiers, visitor, ts.isModifier), + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, node.equalsGreaterThanToken, ts.getFunctionFlags(node) & 2 /* Async */ + ? transformAsyncFunctionBody(node) + : ts.visitFunctionBody(node.body, visitor, context)); + } + function recordDeclarationName(_a, names) { + var name = _a.name; + if (ts.isIdentifier(name)) { + names.set(name.escapedText, true); + } + else { + for (var _i = 0, _b = name.elements; _i < _b.length; _i++) { + var element = _b[_i]; + if (!ts.isOmittedExpression(element)) { + recordDeclarationName(element, names); + } + } + } + } + function isVariableDeclarationListWithCollidingName(node) { + return !!node + && ts.isVariableDeclarationList(node) + && !(node.flags & 3 /* BlockScoped */) + && node.declarations.some(collidesWithParameterName); + } + function visitVariableDeclarationListWithCollidingNames(node, hasReceiver) { + hoistVariableDeclarationList(node); + var variables = ts.getInitializedVariables(node); + if (variables.length === 0) { + if (hasReceiver) { + return ts.visitNode(ts.convertToAssignmentElementTarget(node.declarations[0].name), visitor, ts.isExpression); + } + return undefined; + } + return ts.inlineExpressions(ts.map(variables, transformInitializedVariable)); + } + function hoistVariableDeclarationList(node) { + ts.forEach(node.declarations, hoistVariable); + } + function hoistVariable(_a) { + var name = _a.name; + if (ts.isIdentifier(name)) { + hoistVariableDeclaration(name); + } + else { + for (var _i = 0, _b = name.elements; _i < _b.length; _i++) { + var element = _b[_i]; + if (!ts.isOmittedExpression(element)) { + hoistVariable(element); + } + } + } + } + function transformInitializedVariable(node) { + var converted = ts.setSourceMapRange(ts.createAssignment(ts.convertToAssignmentElementTarget(node.name), node.initializer), node); + return ts.visitNode(converted, visitor, ts.isExpression); + } + function collidesWithParameterName(_a) { + var name = _a.name; + if (ts.isIdentifier(name)) { + return enclosingFunctionParameterNames.has(name.escapedText); + } + else { + for (var _i = 0, _b = name.elements; _i < _b.length; _i++) { + var element = _b[_i]; + if (!ts.isOmittedExpression(element) && collidesWithParameterName(element)) { + return true; + } + } + } + return false; + } + function transformAsyncFunctionBody(node) { + resumeLexicalEnvironment(); + var original = ts.getOriginalNode(node, ts.isFunctionLike); + var nodeType = original.type; + var promiseConstructor = languageVersion < 2 /* ES2015 */ ? getPromiseConstructor(nodeType) : undefined; + var isArrowFunction = node.kind === 197 /* ArrowFunction */; + var hasLexicalArguments = (resolver.getNodeCheckFlags(node) & 8192 /* CaptureArguments */) !== 0; + // An async function is emit as an outer function that calls an inner + // generator function. To preserve lexical bindings, we pass the current + // `this` and `arguments` objects to `__awaiter`. The generator function + // passed to `__awaiter` is executed inside of the callback to the + // promise constructor. + var savedEnclosingFunctionParameterNames = enclosingFunctionParameterNames; + enclosingFunctionParameterNames = ts.createUnderscoreEscapedMap(); + for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { + var parameter = _a[_i]; + recordDeclarationName(parameter, enclosingFunctionParameterNames); + } + var savedCapturedSuperProperties = capturedSuperProperties; + var savedHasSuperElementAccess = hasSuperElementAccess; + capturedSuperProperties = ts.createUnderscoreEscapedMap(); + hasSuperElementAccess = false; + var result; + if (!isArrowFunction) { + var statements = []; + var statementOffset = ts.addPrologue(statements, node.body.statements, /*ensureUseStrict*/ false, visitor); + statements.push(ts.createReturn(createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, transformAsyncFunctionBodyWorker(node.body, statementOffset)))); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + // Minor optimization, emit `_super` helper to capture `super` access in an arrow. + // This step isn't needed if we eventually transform this to ES5. + var emitSuperHelpers = languageVersion >= 2 /* ES2015 */ && resolver.getNodeCheckFlags(node) & (4096 /* AsyncMethodWithSuperBinding */ | 2048 /* AsyncMethodWithSuper */); + if (emitSuperHelpers) { + enableSubstitutionForAsyncMethodsWithSuper(); + var variableStatement = createSuperAccessVariableStatement(resolver, node, capturedSuperProperties); + substitutedSuperAccessors[ts.getNodeId(variableStatement)] = true; + ts.addStatementsAfterPrologue(statements, [variableStatement]); + } + var block = ts.createBlock(statements, /*multiLine*/ true); + ts.setTextRange(block, node.body); + if (emitSuperHelpers && hasSuperElementAccess) { + // Emit helpers for super element access expressions (`super[x]`). + if (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) { + ts.addEmitHelper(block, ts.advancedAsyncSuperHelper); + } + else if (resolver.getNodeCheckFlags(node) & 2048 /* AsyncMethodWithSuper */) { + ts.addEmitHelper(block, ts.asyncSuperHelper); + } + } + result = block; + } + else { + var expression = createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, transformAsyncFunctionBodyWorker(node.body)); + var declarations = endLexicalEnvironment(); + if (ts.some(declarations)) { + var block = ts.convertToFunctionBody(expression); + result = ts.updateBlock(block, ts.setTextRange(ts.createNodeArray(ts.concatenate(declarations, block.statements)), block.statements)); + } + else { + result = expression; + } + } + enclosingFunctionParameterNames = savedEnclosingFunctionParameterNames; + capturedSuperProperties = savedCapturedSuperProperties; + hasSuperElementAccess = savedHasSuperElementAccess; + return result; + } + function transformAsyncFunctionBodyWorker(body, start) { + if (ts.isBlock(body)) { + return ts.updateBlock(body, ts.visitNodes(body.statements, asyncBodyVisitor, ts.isStatement, start)); + } + else { + return ts.convertToFunctionBody(ts.visitNode(body, asyncBodyVisitor, ts.isConciseBody)); + } + } + function getPromiseConstructor(type) { + var typeName = type && ts.getEntityNameFromTypeNode(type); + if (typeName && ts.isEntityName(typeName)) { + var serializationKind = resolver.getTypeReferenceSerializationKind(typeName); + if (serializationKind === ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue + || serializationKind === ts.TypeReferenceSerializationKind.Unknown) { + return typeName; + } + } + return undefined; + } + function enableSubstitutionForAsyncMethodsWithSuper() { + if ((enabledSubstitutions & 1 /* AsyncMethodsWithSuper */) === 0) { + enabledSubstitutions |= 1 /* AsyncMethodsWithSuper */; + // We need to enable substitutions for call, property access, and element access + // if we need to rewrite super calls. + context.enableSubstitution(191 /* CallExpression */); + context.enableSubstitution(189 /* PropertyAccessExpression */); + context.enableSubstitution(190 /* ElementAccessExpression */); + // We need to be notified when entering and exiting declarations that bind super. + context.enableEmitNotification(240 /* ClassDeclaration */); + context.enableEmitNotification(156 /* MethodDeclaration */); + context.enableEmitNotification(158 /* GetAccessor */); + context.enableEmitNotification(159 /* SetAccessor */); + context.enableEmitNotification(157 /* Constructor */); + // We need to be notified when entering the generated accessor arrow functions. + context.enableEmitNotification(219 /* VariableStatement */); + } + } + /** + * Hook for node emit. + * + * @param hint A hint as to the intended usage of the node. + * @param node The node to emit. + * @param emit A callback used to emit the node in the printer. + */ + function onEmitNode(hint, node, emitCallback) { + // If we need to support substitutions for `super` in an async method, + // we should track it here. + if (enabledSubstitutions & 1 /* AsyncMethodsWithSuper */ && isSuperContainer(node)) { + var superContainerFlags = resolver.getNodeCheckFlags(node) & (2048 /* AsyncMethodWithSuper */ | 4096 /* AsyncMethodWithSuperBinding */); + if (superContainerFlags !== enclosingSuperContainerFlags) { + var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags; + enclosingSuperContainerFlags = superContainerFlags; + previousOnEmitNode(hint, node, emitCallback); + enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags; + return; + } + } + // Disable substitution in the generated super accessor itself. + else if (enabledSubstitutions && substitutedSuperAccessors[ts.getNodeId(node)]) { + var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags; + enclosingSuperContainerFlags = 0; + previousOnEmitNode(hint, node, emitCallback); + enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags; + return; + } + previousOnEmitNode(hint, node, emitCallback); + } + /** + * Hooks node substitutions. + * + * @param hint A hint as to the intended usage of the node. + * @param node The node to substitute. + */ + function onSubstituteNode(hint, node) { + node = previousOnSubstituteNode(hint, node); + if (hint === 1 /* Expression */ && enclosingSuperContainerFlags) { + return substituteExpression(node); + } + return node; + } + function substituteExpression(node) { + switch (node.kind) { + case 189 /* PropertyAccessExpression */: + return substitutePropertyAccessExpression(node); + case 190 /* ElementAccessExpression */: + return substituteElementAccessExpression(node); + case 191 /* CallExpression */: + return substituteCallExpression(node); + } + return node; + } + function substitutePropertyAccessExpression(node) { + if (node.expression.kind === 98 /* SuperKeyword */) { + return ts.setTextRange(ts.createPropertyAccess(ts.createFileLevelUniqueName("_super"), node.name), node); + } + return node; + } + function substituteElementAccessExpression(node) { + if (node.expression.kind === 98 /* SuperKeyword */) { + return createSuperElementAccessInAsyncMethod(node.argumentExpression, node); + } + return node; + } + function substituteCallExpression(node) { + var expression = node.expression; + if (ts.isSuperProperty(expression)) { + var argumentExpression = ts.isPropertyAccessExpression(expression) + ? substitutePropertyAccessExpression(expression) + : substituteElementAccessExpression(expression); + return ts.createCall(ts.createPropertyAccess(argumentExpression, "call"), + /*typeArguments*/ undefined, [ + ts.createThis() + ].concat(node.arguments)); + } + return node; + } + function isSuperContainer(node) { + var kind = node.kind; + return kind === 240 /* ClassDeclaration */ + || kind === 157 /* Constructor */ + || kind === 156 /* MethodDeclaration */ + || kind === 158 /* GetAccessor */ + || kind === 159 /* SetAccessor */; + } + function createSuperElementAccessInAsyncMethod(argumentExpression, location) { + if (enclosingSuperContainerFlags & 4096 /* AsyncMethodWithSuperBinding */) { + return ts.setTextRange(ts.createPropertyAccess(ts.createCall(ts.createFileLevelUniqueName("_superIndex"), + /*typeArguments*/ undefined, [argumentExpression]), "value"), location); + } + else { + return ts.setTextRange(ts.createCall(ts.createFileLevelUniqueName("_superIndex"), + /*typeArguments*/ undefined, [argumentExpression]), location); + } + } + } + ts.transformES2017 = transformES2017; + /** Creates a variable named `_super` with accessor properties for the given property names. */ + function createSuperAccessVariableStatement(resolver, node, names) { + // Create a variable declaration with a getter/setter (if binding) definition for each name: + // const _super = Object.create(null, { x: { get: () => super.x, set: (v) => super.x = v }, ... }); + var hasBinding = (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) !== 0; + var accessors = []; + names.forEach(function (_, key) { + var name = ts.unescapeLeadingUnderscores(key); + var getterAndSetter = []; + getterAndSetter.push(ts.createPropertyAssignment("get", ts.createArrowFunction( + /* modifiers */ undefined, + /* typeParameters */ undefined, + /* parameters */ [], + /* type */ undefined, + /* equalsGreaterThanToken */ undefined, ts.createPropertyAccess(ts.createSuper(), name)))); + if (hasBinding) { + getterAndSetter.push(ts.createPropertyAssignment("set", ts.createArrowFunction( + /* modifiers */ undefined, + /* typeParameters */ undefined, + /* parameters */ [ + ts.createParameter( + /* decorators */ undefined, + /* modifiers */ undefined, + /* dotDotDotToken */ undefined, "v", + /* questionToken */ undefined, + /* type */ undefined, + /* initializer */ undefined) + ], + /* type */ undefined, + /* equalsGreaterThanToken */ undefined, ts.createAssignment(ts.createPropertyAccess(ts.createSuper(), name), ts.createIdentifier("v"))))); + } + accessors.push(ts.createPropertyAssignment(name, ts.createObjectLiteral(getterAndSetter))); + }); + return ts.createVariableStatement( + /* modifiers */ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(ts.createFileLevelUniqueName("_super"), + /* type */ undefined, ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "create"), + /* typeArguments */ undefined, [ + ts.createNull(), + ts.createObjectLiteral(accessors, /* multiline */ true) + ])) + ], 2 /* Const */)); + } + ts.createSuperAccessVariableStatement = createSuperAccessVariableStatement; + var awaiterHelper = { + name: "typescript:awaiter", + scoped: false, + priority: 5, + text: "\n var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n };" + }; + function createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, body) { + context.requestEmitHelper(awaiterHelper); + var generatorFunc = ts.createFunctionExpression( + /*modifiers*/ undefined, ts.createToken(40 /* AsteriskToken */), + /*name*/ undefined, + /*typeParameters*/ undefined, + /*parameters*/ [], + /*type*/ undefined, body); + // Mark this node as originally an async function + (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 262144 /* AsyncFunctionBody */ | 524288 /* ReuseTempVariableScope */; + return ts.createCall(ts.getHelperName("__awaiter"), + /*typeArguments*/ undefined, [ + ts.createThis(), + hasLexicalArguments ? ts.createIdentifier("arguments") : ts.createVoidZero(), + promiseConstructor ? ts.createExpressionFromEntityName(promiseConstructor) : ts.createVoidZero(), + generatorFunc + ]); + } + ts.asyncSuperHelper = { + name: "typescript:async-super", + scoped: true, + text: ts.helperString(__makeTemplateObject(["\n const ", " = name => super[name];"], ["\n const ", " = name => super[name];"]), "_superIndex") + }; + ts.advancedAsyncSuperHelper = { + name: "typescript:advanced-async-super", + scoped: true, + text: ts.helperString(__makeTemplateObject(["\n const ", " = (function (geti, seti) {\n const cache = Object.create(null);\n return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } });\n })(name => super[name], (name, value) => super[name] = value);"], ["\n const ", " = (function (geti, seti) {\n const cache = Object.create(null);\n return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } });\n })(name => super[name], (name, value) => super[name] = value);"]), "_superIndex") + }; +})(ts || (ts = {})); +/*@internal*/ +var ts; +(function (ts) { + var ESNextSubstitutionFlags; + (function (ESNextSubstitutionFlags) { + /** Enables substitutions for async methods with `super` calls. */ + ESNextSubstitutionFlags[ESNextSubstitutionFlags["AsyncMethodsWithSuper"] = 1] = "AsyncMethodsWithSuper"; + })(ESNextSubstitutionFlags || (ESNextSubstitutionFlags = {})); + function transformESNext(context) { + var resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; + var resolver = context.getEmitResolver(); + var compilerOptions = context.getCompilerOptions(); + var languageVersion = ts.getEmitScriptTarget(compilerOptions); + var previousOnEmitNode = context.onEmitNode; + context.onEmitNode = onEmitNode; + var previousOnSubstituteNode = context.onSubstituteNode; + context.onSubstituteNode = onSubstituteNode; + var enabledSubstitutions; + var enclosingFunctionFlags; + var enclosingSuperContainerFlags = 0; + /** Keeps track of property names accessed on super (`super.x`) within async functions. */ + var capturedSuperProperties; + /** Whether the async function contains an element access on super (`super[x]`). */ + var hasSuperElementAccess; + /** A set of node IDs for generated super accessors. */ + var substitutedSuperAccessors = []; + return ts.chainBundle(transformSourceFile); + function transformSourceFile(node) { + if (node.isDeclarationFile) { + return node; + } + var visited = ts.visitEachChild(node, visitor, context); + ts.addEmitHelpers(visited, context.readEmitHelpers()); + return visited; + } + function visitor(node) { + return visitorWorker(node, /*noDestructuringValue*/ false); + } + function visitorNoDestructuringValue(node) { + return visitorWorker(node, /*noDestructuringValue*/ true); + } + function visitorNoAsyncModifier(node) { + if (node.kind === 121 /* AsyncKeyword */) { + return undefined; + } + return node; + } + function visitorWorker(node, noDestructuringValue) { + if ((node.transformFlags & 8 /* ContainsESNext */) === 0) { + return node; + } + switch (node.kind) { + case 201 /* AwaitExpression */: + return visitAwaitExpression(node); + case 207 /* YieldExpression */: + return visitYieldExpression(node); + case 230 /* ReturnStatement */: + return visitReturnStatement(node); + case 233 /* LabeledStatement */: + return visitLabeledStatement(node); + case 188 /* ObjectLiteralExpression */: + return visitObjectLiteralExpression(node); + case 204 /* BinaryExpression */: + return visitBinaryExpression(node, noDestructuringValue); + case 237 /* VariableDeclaration */: + return visitVariableDeclaration(node); + case 227 /* ForOfStatement */: + return visitForOfStatement(node, /*outermostLabeledStatement*/ undefined); + case 225 /* ForStatement */: + return visitForStatement(node); + case 200 /* VoidExpression */: + return visitVoidExpression(node); + case 157 /* Constructor */: + return visitConstructorDeclaration(node); + case 156 /* MethodDeclaration */: + return visitMethodDeclaration(node); + case 158 /* GetAccessor */: + return visitGetAccessorDeclaration(node); + case 159 /* SetAccessor */: + return visitSetAccessorDeclaration(node); + case 239 /* FunctionDeclaration */: + return visitFunctionDeclaration(node); + case 196 /* FunctionExpression */: + return visitFunctionExpression(node); + case 197 /* ArrowFunction */: + return visitArrowFunction(node); + case 151 /* Parameter */: + return visitParameter(node); + case 221 /* ExpressionStatement */: + return visitExpressionStatement(node); + case 195 /* ParenthesizedExpression */: + return visitParenthesizedExpression(node, noDestructuringValue); + case 274 /* CatchClause */: + return visitCatchClause(node); + case 189 /* PropertyAccessExpression */: + if (capturedSuperProperties && ts.isPropertyAccessExpression(node) && node.expression.kind === 98 /* SuperKeyword */) { + capturedSuperProperties.set(node.name.escapedText, true); + } + return ts.visitEachChild(node, visitor, context); + case 190 /* ElementAccessExpression */: + if (capturedSuperProperties && node.expression.kind === 98 /* SuperKeyword */) { + hasSuperElementAccess = true; + } + return ts.visitEachChild(node, visitor, context); + default: + return ts.visitEachChild(node, visitor, context); + } + } + function visitAwaitExpression(node) { + if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */) { + return ts.setOriginalNode(ts.setTextRange(ts.createYield(createAwaitHelper(context, ts.visitNode(node.expression, visitor, ts.isExpression))), + /*location*/ node), node); + } + return ts.visitEachChild(node, visitor, context); + } + function visitYieldExpression(node) { + if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */) { + if (node.asteriskToken) { + var expression = ts.visitNode(node.expression, visitor, ts.isExpression); + return ts.setOriginalNode(ts.setTextRange(ts.createYield(createAwaitHelper(context, ts.updateYield(node, node.asteriskToken, createAsyncDelegatorHelper(context, createAsyncValuesHelper(context, expression, expression), expression)))), node), node); + } + return ts.setOriginalNode(ts.setTextRange(ts.createYield(createDownlevelAwait(node.expression + ? ts.visitNode(node.expression, visitor, ts.isExpression) + : ts.createVoidZero())), node), node); + } + return ts.visitEachChild(node, visitor, context); + } + function visitReturnStatement(node) { + if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */) { + return ts.updateReturn(node, createDownlevelAwait(node.expression ? ts.visitNode(node.expression, visitor, ts.isExpression) : ts.createVoidZero())); + } + return ts.visitEachChild(node, visitor, context); + } + function visitLabeledStatement(node) { + if (enclosingFunctionFlags & 2 /* Async */) { + var statement = ts.unwrapInnermostStatementOfLabel(node); + if (statement.kind === 227 /* ForOfStatement */ && statement.awaitModifier) { + return visitForOfStatement(statement, node); + } + return ts.restoreEnclosingLabel(ts.visitEachChild(statement, visitor, context), node); + } + return ts.visitEachChild(node, visitor, context); + } + function chunkObjectLiteralElements(elements) { + var chunkObject; + var objects = []; + for (var _i = 0, elements_4 = elements; _i < elements_4.length; _i++) { + var e = elements_4[_i]; + if (e.kind === 277 /* SpreadAssignment */) { + if (chunkObject) { + objects.push(ts.createObjectLiteral(chunkObject)); + chunkObject = undefined; + } + var target = e.expression; + objects.push(ts.visitNode(target, visitor, ts.isExpression)); + } + else { + chunkObject = ts.append(chunkObject, e.kind === 275 /* PropertyAssignment */ + ? ts.createPropertyAssignment(e.name, ts.visitNode(e.initializer, visitor, ts.isExpression)) + : ts.visitNode(e, visitor, ts.isObjectLiteralElementLike)); + } + } + if (chunkObject) { + objects.push(ts.createObjectLiteral(chunkObject)); + } + return objects; + } + function visitObjectLiteralExpression(node) { + if (node.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { + // spread elements emit like so: + // non-spread elements are chunked together into object literals, and then all are passed to __assign: + // { a, ...o, b } => __assign({a}, o, {b}); + // If the first element is a spread element, then the first argument to __assign is {}: + // { ...o, a, b, ...o2 } => __assign({}, o, {a, b}, o2) + var objects = chunkObjectLiteralElements(node.properties); + if (objects.length && objects[0].kind !== 188 /* ObjectLiteralExpression */) { + objects.unshift(ts.createObjectLiteral()); + } + return createAssignHelper(context, objects); + } + return ts.visitEachChild(node, visitor, context); + } + function visitExpressionStatement(node) { + return ts.visitEachChild(node, visitorNoDestructuringValue, context); + } + function visitParenthesizedExpression(node, noDestructuringValue) { + return ts.visitEachChild(node, noDestructuringValue ? visitorNoDestructuringValue : visitor, context); + } + function visitCatchClause(node) { + if (!node.variableDeclaration) { + return ts.updateCatchClause(node, ts.createVariableDeclaration(ts.createTempVariable(/*recordTempVariable*/ undefined)), ts.visitNode(node.block, visitor, ts.isBlock)); + } + return ts.visitEachChild(node, visitor, context); + } + /** + * Visits a BinaryExpression that contains a destructuring assignment. + * + * @param node A BinaryExpression node. + */ + function visitBinaryExpression(node, noDestructuringValue) { + if (ts.isDestructuringAssignment(node) && node.left.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { + return ts.flattenDestructuringAssignment(node, visitor, context, 1 /* ObjectRest */, !noDestructuringValue); + } + else if (node.operatorToken.kind === 27 /* CommaToken */) { + return ts.updateBinary(node, ts.visitNode(node.left, visitorNoDestructuringValue, ts.isExpression), ts.visitNode(node.right, noDestructuringValue ? visitorNoDestructuringValue : visitor, ts.isExpression)); + } + return ts.visitEachChild(node, visitor, context); + } + /** + * Visits a VariableDeclaration node with a binding pattern. + * + * @param node A VariableDeclaration node. + */ + function visitVariableDeclaration(node) { + // If we are here it is because the name contains a binding pattern with a rest somewhere in it. + if (ts.isBindingPattern(node.name) && node.name.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { + return ts.flattenDestructuringBinding(node, visitor, context, 1 /* ObjectRest */); + } + return ts.visitEachChild(node, visitor, context); + } + function visitForStatement(node) { + return ts.updateFor(node, ts.visitNode(node.initializer, visitorNoDestructuringValue, ts.isForInitializer), ts.visitNode(node.condition, visitor, ts.isExpression), ts.visitNode(node.incrementor, visitor, ts.isExpression), ts.visitNode(node.statement, visitor, ts.isStatement)); + } + function visitVoidExpression(node) { + return ts.visitEachChild(node, visitorNoDestructuringValue, context); + } + /** + * Visits a ForOfStatement and converts it into a ES2015-compatible ForOfStatement. + * + * @param node A ForOfStatement. + */ + function visitForOfStatement(node, outermostLabeledStatement) { + if (node.initializer.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { + node = transformForOfStatementWithObjectRest(node); + } + if (node.awaitModifier) { + return transformForAwaitOfStatement(node, outermostLabeledStatement); + } + else { + return ts.restoreEnclosingLabel(ts.visitEachChild(node, visitor, context), outermostLabeledStatement); + } + } + function transformForOfStatementWithObjectRest(node) { + var initializerWithoutParens = ts.skipParentheses(node.initializer); + if (ts.isVariableDeclarationList(initializerWithoutParens) || ts.isAssignmentPattern(initializerWithoutParens)) { + var bodyLocation = void 0; + var statementsLocation = void 0; + var temp = ts.createTempVariable(/*recordTempVariable*/ undefined); + var statements = [ts.createForOfBindingStatement(initializerWithoutParens, temp)]; + if (ts.isBlock(node.statement)) { + ts.addRange(statements, node.statement.statements); + bodyLocation = node.statement; + statementsLocation = node.statement.statements; + } + else if (node.statement) { + ts.append(statements, node.statement); + bodyLocation = node.statement; + statementsLocation = node.statement; + } + return ts.updateForOf(node, node.awaitModifier, ts.setTextRange(ts.createVariableDeclarationList([ + ts.setTextRange(ts.createVariableDeclaration(temp), node.initializer) + ], 1 /* Let */), node.initializer), node.expression, ts.setTextRange(ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), statementsLocation), + /*multiLine*/ true), bodyLocation)); + } + return node; + } + function convertForOfStatementHead(node, boundValue) { + var binding = ts.createForOfBindingStatement(node.initializer, boundValue); + var bodyLocation; + var statementsLocation; + var statements = [ts.visitNode(binding, visitor, ts.isStatement)]; + var statement = ts.visitNode(node.statement, visitor, ts.isStatement); + if (ts.isBlock(statement)) { + ts.addRange(statements, statement.statements); + bodyLocation = statement; + statementsLocation = statement.statements; + } + else { + statements.push(statement); + } + return ts.setEmitFlags(ts.setTextRange(ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), statementsLocation), + /*multiLine*/ true), bodyLocation), 48 /* NoSourceMap */ | 384 /* NoTokenSourceMaps */); + } + function createDownlevelAwait(expression) { + return enclosingFunctionFlags & 1 /* Generator */ + ? ts.createYield(/*asteriskToken*/ undefined, createAwaitHelper(context, expression)) + : ts.createAwait(expression); + } + function transformForAwaitOfStatement(node, outermostLabeledStatement) { + var expression = ts.visitNode(node.expression, visitor, ts.isExpression); + var iterator = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(expression) : ts.createTempVariable(/*recordTempVariable*/ undefined); + var result = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(iterator) : ts.createTempVariable(/*recordTempVariable*/ undefined); + var errorRecord = ts.createUniqueName("e"); + var catchVariable = ts.getGeneratedNameForNode(errorRecord); + var returnMethod = ts.createTempVariable(/*recordTempVariable*/ undefined); + var callValues = createAsyncValuesHelper(context, expression, /*location*/ node.expression); + var callNext = ts.createCall(ts.createPropertyAccess(iterator, "next"), /*typeArguments*/ undefined, []); + var getDone = ts.createPropertyAccess(result, "done"); + var getValue = ts.createPropertyAccess(result, "value"); + var callReturn = ts.createFunctionCall(returnMethod, iterator, []); + hoistVariableDeclaration(errorRecord); + hoistVariableDeclaration(returnMethod); + var forStatement = ts.setEmitFlags(ts.setTextRange(ts.createFor( + /*initializer*/ ts.setEmitFlags(ts.setTextRange(ts.createVariableDeclarationList([ + ts.setTextRange(ts.createVariableDeclaration(iterator, /*type*/ undefined, callValues), node.expression), + ts.createVariableDeclaration(result) + ]), node.expression), 2097152 /* NoHoisting */), + /*condition*/ ts.createComma(ts.createAssignment(result, createDownlevelAwait(callNext)), ts.createLogicalNot(getDone)), + /*incrementor*/ undefined, + /*statement*/ convertForOfStatementHead(node, getValue)), + /*location*/ node), 256 /* NoTokenTrailingSourceMaps */); + return ts.createTry(ts.createBlock([ + ts.restoreEnclosingLabel(forStatement, outermostLabeledStatement) + ]), ts.createCatchClause(ts.createVariableDeclaration(catchVariable), ts.setEmitFlags(ts.createBlock([ + ts.createExpressionStatement(ts.createAssignment(errorRecord, ts.createObjectLiteral([ + ts.createPropertyAssignment("error", catchVariable) + ]))) + ]), 1 /* SingleLine */)), ts.createBlock([ + ts.createTry( + /*tryBlock*/ ts.createBlock([ + ts.setEmitFlags(ts.createIf(ts.createLogicalAnd(ts.createLogicalAnd(result, ts.createLogicalNot(getDone)), ts.createAssignment(returnMethod, ts.createPropertyAccess(iterator, "return"))), ts.createExpressionStatement(createDownlevelAwait(callReturn))), 1 /* SingleLine */) + ]), + /*catchClause*/ undefined, + /*finallyBlock*/ ts.setEmitFlags(ts.createBlock([ + ts.setEmitFlags(ts.createIf(errorRecord, ts.createThrow(ts.createPropertyAccess(errorRecord, "error"))), 1 /* SingleLine */) + ]), 1 /* SingleLine */)) + ])); + } + function visitParameter(node) { + if (node.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { + // Binding patterns are converted into a generated name and are + // evaluated inside the function body. + return ts.updateParameter(node, + /*decorators*/ undefined, + /*modifiers*/ undefined, node.dotDotDotToken, ts.getGeneratedNameForNode(node), + /*questionToken*/ undefined, + /*type*/ undefined, ts.visitNode(node.initializer, visitor, ts.isExpression)); + } + return ts.visitEachChild(node, visitor, context); + } + function visitConstructorDeclaration(node) { + var savedEnclosingFunctionFlags = enclosingFunctionFlags; + enclosingFunctionFlags = 0 /* Normal */; + var updated = ts.updateConstructor(node, + /*decorators*/ undefined, node.modifiers, ts.visitParameterList(node.parameters, visitor, context), transformFunctionBody(node)); + enclosingFunctionFlags = savedEnclosingFunctionFlags; + return updated; + } + function visitGetAccessorDeclaration(node) { + var savedEnclosingFunctionFlags = enclosingFunctionFlags; + enclosingFunctionFlags = 0 /* Normal */; + var updated = ts.updateGetAccessor(node, + /*decorators*/ undefined, node.modifiers, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, transformFunctionBody(node)); + enclosingFunctionFlags = savedEnclosingFunctionFlags; + return updated; + } + function visitSetAccessorDeclaration(node) { + var savedEnclosingFunctionFlags = enclosingFunctionFlags; + enclosingFunctionFlags = 0 /* Normal */; + var updated = ts.updateSetAccessor(node, + /*decorators*/ undefined, node.modifiers, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitParameterList(node.parameters, visitor, context), transformFunctionBody(node)); + enclosingFunctionFlags = savedEnclosingFunctionFlags; + return updated; + } + function visitMethodDeclaration(node) { + var savedEnclosingFunctionFlags = enclosingFunctionFlags; + enclosingFunctionFlags = ts.getFunctionFlags(node); + var updated = ts.updateMethod(node, + /*decorators*/ undefined, enclosingFunctionFlags & 1 /* Generator */ + ? ts.visitNodes(node.modifiers, visitorNoAsyncModifier, ts.isModifier) + : node.modifiers, enclosingFunctionFlags & 2 /* Async */ + ? undefined + : node.asteriskToken, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitNode(/*questionToken*/ undefined, visitor, ts.isToken), + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */ + ? transformAsyncGeneratorFunctionBody(node) + : transformFunctionBody(node)); + enclosingFunctionFlags = savedEnclosingFunctionFlags; + return updated; + } + function visitFunctionDeclaration(node) { + var savedEnclosingFunctionFlags = enclosingFunctionFlags; + enclosingFunctionFlags = ts.getFunctionFlags(node); + var updated = ts.updateFunctionDeclaration(node, + /*decorators*/ undefined, enclosingFunctionFlags & 1 /* Generator */ + ? ts.visitNodes(node.modifiers, visitorNoAsyncModifier, ts.isModifier) + : node.modifiers, enclosingFunctionFlags & 2 /* Async */ + ? undefined + : node.asteriskToken, node.name, + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */ + ? transformAsyncGeneratorFunctionBody(node) + : transformFunctionBody(node)); + enclosingFunctionFlags = savedEnclosingFunctionFlags; + return updated; + } + function visitArrowFunction(node) { + var savedEnclosingFunctionFlags = enclosingFunctionFlags; + enclosingFunctionFlags = ts.getFunctionFlags(node); + var updated = ts.updateArrowFunction(node, node.modifiers, + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, node.equalsGreaterThanToken, transformFunctionBody(node)); + enclosingFunctionFlags = savedEnclosingFunctionFlags; + return updated; + } + function visitFunctionExpression(node) { + var savedEnclosingFunctionFlags = enclosingFunctionFlags; + enclosingFunctionFlags = ts.getFunctionFlags(node); + var updated = ts.updateFunctionExpression(node, enclosingFunctionFlags & 1 /* Generator */ + ? ts.visitNodes(node.modifiers, visitorNoAsyncModifier, ts.isModifier) + : node.modifiers, enclosingFunctionFlags & 2 /* Async */ + ? undefined + : node.asteriskToken, node.name, + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */ + ? transformAsyncGeneratorFunctionBody(node) + : transformFunctionBody(node)); + enclosingFunctionFlags = savedEnclosingFunctionFlags; + return updated; + } + function transformAsyncGeneratorFunctionBody(node) { + resumeLexicalEnvironment(); + var statements = []; + var statementOffset = ts.addPrologue(statements, node.body.statements, /*ensureUseStrict*/ false, visitor); + appendObjectRestAssignmentsIfNeeded(statements, node); + var savedCapturedSuperProperties = capturedSuperProperties; + var savedHasSuperElementAccess = hasSuperElementAccess; + capturedSuperProperties = ts.createUnderscoreEscapedMap(); + hasSuperElementAccess = false; + var returnStatement = ts.createReturn(createAsyncGeneratorHelper(context, ts.createFunctionExpression( + /*modifiers*/ undefined, ts.createToken(40 /* AsteriskToken */), node.name && ts.getGeneratedNameForNode(node.name), + /*typeParameters*/ undefined, + /*parameters*/ [], + /*type*/ undefined, ts.updateBlock(node.body, ts.visitLexicalEnvironment(node.body.statements, visitor, context, statementOffset))))); + // Minor optimization, emit `_super` helper to capture `super` access in an arrow. + // This step isn't needed if we eventually transform this to ES5. + var emitSuperHelpers = languageVersion >= 2 /* ES2015 */ && resolver.getNodeCheckFlags(node) & (4096 /* AsyncMethodWithSuperBinding */ | 2048 /* AsyncMethodWithSuper */); + if (emitSuperHelpers) { + enableSubstitutionForAsyncMethodsWithSuper(); + var variableStatement = ts.createSuperAccessVariableStatement(resolver, node, capturedSuperProperties); + substitutedSuperAccessors[ts.getNodeId(variableStatement)] = true; + ts.addStatementsAfterPrologue(statements, [variableStatement]); + } + statements.push(returnStatement); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + var block = ts.updateBlock(node.body, statements); + if (emitSuperHelpers && hasSuperElementAccess) { + if (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) { + ts.addEmitHelper(block, ts.advancedAsyncSuperHelper); + } + else if (resolver.getNodeCheckFlags(node) & 2048 /* AsyncMethodWithSuper */) { + ts.addEmitHelper(block, ts.asyncSuperHelper); + } + } + capturedSuperProperties = savedCapturedSuperProperties; + hasSuperElementAccess = savedHasSuperElementAccess; + return block; + } + function transformFunctionBody(node) { + resumeLexicalEnvironment(); + var statementOffset = 0; + var statements = []; + var body = ts.visitNode(node.body, visitor, ts.isConciseBody); + if (ts.isBlock(body)) { + statementOffset = ts.addPrologue(statements, body.statements, /*ensureUseStrict*/ false, visitor); + } + ts.addRange(statements, appendObjectRestAssignmentsIfNeeded(/*statements*/ undefined, node)); + var leadingStatements = endLexicalEnvironment(); + if (statementOffset > 0 || ts.some(statements) || ts.some(leadingStatements)) { + var block = ts.convertToFunctionBody(body, /*multiLine*/ true); + ts.addStatementsAfterPrologue(statements, leadingStatements); + ts.addRange(statements, block.statements.slice(statementOffset)); + return ts.updateBlock(block, ts.setTextRange(ts.createNodeArray(statements), block.statements)); + } + return body; + } + function appendObjectRestAssignmentsIfNeeded(statements, node) { + for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { + var parameter = _a[_i]; + if (parameter.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { + var temp = ts.getGeneratedNameForNode(parameter); + var declarations = ts.flattenDestructuringBinding(parameter, visitor, context, 1 /* ObjectRest */, temp, + /*doNotRecordTempVariablesInLine*/ false, + /*skipInitializer*/ true); + if (ts.some(declarations)) { + var statement = ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList(declarations)); + ts.setEmitFlags(statement, 1048576 /* CustomPrologue */); + statements = ts.append(statements, statement); + } + } + } + return statements; + } + function enableSubstitutionForAsyncMethodsWithSuper() { + if ((enabledSubstitutions & 1 /* AsyncMethodsWithSuper */) === 0) { + enabledSubstitutions |= 1 /* AsyncMethodsWithSuper */; + // We need to enable substitutions for call, property access, and element access + // if we need to rewrite super calls. + context.enableSubstitution(191 /* CallExpression */); + context.enableSubstitution(189 /* PropertyAccessExpression */); + context.enableSubstitution(190 /* ElementAccessExpression */); + // We need to be notified when entering and exiting declarations that bind super. + context.enableEmitNotification(240 /* ClassDeclaration */); + context.enableEmitNotification(156 /* MethodDeclaration */); + context.enableEmitNotification(158 /* GetAccessor */); + context.enableEmitNotification(159 /* SetAccessor */); + context.enableEmitNotification(157 /* Constructor */); + // We need to be notified when entering the generated accessor arrow functions. + context.enableEmitNotification(219 /* VariableStatement */); + } + } + /** + * Called by the printer just before a node is printed. + * + * @param hint A hint as to the intended usage of the node. + * @param node The node to be printed. + * @param emitCallback The callback used to emit the node. + */ + function onEmitNode(hint, node, emitCallback) { + // If we need to support substitutions for `super` in an async method, + // we should track it here. + if (enabledSubstitutions & 1 /* AsyncMethodsWithSuper */ && isSuperContainer(node)) { + var superContainerFlags = resolver.getNodeCheckFlags(node) & (2048 /* AsyncMethodWithSuper */ | 4096 /* AsyncMethodWithSuperBinding */); + if (superContainerFlags !== enclosingSuperContainerFlags) { + var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags; + enclosingSuperContainerFlags = superContainerFlags; + previousOnEmitNode(hint, node, emitCallback); + enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags; + return; + } + } + // Disable substitution in the generated super accessor itself. + else if (enabledSubstitutions && substitutedSuperAccessors[ts.getNodeId(node)]) { + var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags; + enclosingSuperContainerFlags = 0; + previousOnEmitNode(hint, node, emitCallback); + enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags; + return; + } + previousOnEmitNode(hint, node, emitCallback); + } + /** + * Hooks node substitutions. + * + * @param hint The context for the emitter. + * @param node The node to substitute. + */ + function onSubstituteNode(hint, node) { + node = previousOnSubstituteNode(hint, node); + if (hint === 1 /* Expression */ && enclosingSuperContainerFlags) { + return substituteExpression(node); + } + return node; + } + function substituteExpression(node) { + switch (node.kind) { + case 189 /* PropertyAccessExpression */: + return substitutePropertyAccessExpression(node); + case 190 /* ElementAccessExpression */: + return substituteElementAccessExpression(node); + case 191 /* CallExpression */: + return substituteCallExpression(node); + } + return node; + } + function substitutePropertyAccessExpression(node) { + if (node.expression.kind === 98 /* SuperKeyword */) { + return ts.setTextRange(ts.createPropertyAccess(ts.createFileLevelUniqueName("_super"), node.name), node); + } + return node; + } + function substituteElementAccessExpression(node) { + if (node.expression.kind === 98 /* SuperKeyword */) { + return createSuperElementAccessInAsyncMethod(node.argumentExpression, node); + } + return node; + } + function substituteCallExpression(node) { + var expression = node.expression; + if (ts.isSuperProperty(expression)) { + var argumentExpression = ts.isPropertyAccessExpression(expression) + ? substitutePropertyAccessExpression(expression) + : substituteElementAccessExpression(expression); + return ts.createCall(ts.createPropertyAccess(argumentExpression, "call"), + /*typeArguments*/ undefined, [ + ts.createThis() + ].concat(node.arguments)); + } + return node; + } + function isSuperContainer(node) { + var kind = node.kind; + return kind === 240 /* ClassDeclaration */ + || kind === 157 /* Constructor */ + || kind === 156 /* MethodDeclaration */ + || kind === 158 /* GetAccessor */ + || kind === 159 /* SetAccessor */; + } + function createSuperElementAccessInAsyncMethod(argumentExpression, location) { + if (enclosingSuperContainerFlags & 4096 /* AsyncMethodWithSuperBinding */) { + return ts.setTextRange(ts.createPropertyAccess(ts.createCall(ts.createIdentifier("_superIndex"), + /*typeArguments*/ undefined, [argumentExpression]), "value"), location); + } + else { + return ts.setTextRange(ts.createCall(ts.createIdentifier("_superIndex"), + /*typeArguments*/ undefined, [argumentExpression]), location); + } + } + } + ts.transformESNext = transformESNext; + var assignHelper = { + name: "typescript:assign", + scoped: false, + priority: 1, + text: "\n var __assign = (this && this.__assign) || function () {\n __assign = Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n };\n return __assign.apply(this, arguments);\n };" + }; + function createAssignHelper(context, attributesSegments) { + if (context.getCompilerOptions().target >= 2 /* ES2015 */) { + return ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "assign"), + /*typeArguments*/ undefined, attributesSegments); + } + context.requestEmitHelper(assignHelper); + return ts.createCall(ts.getHelperName("__assign"), + /*typeArguments*/ undefined, attributesSegments); + } + ts.createAssignHelper = createAssignHelper; + var awaitHelper = { + name: "typescript:await", + scoped: false, + text: "\n var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }" + }; + function createAwaitHelper(context, expression) { + context.requestEmitHelper(awaitHelper); + return ts.createCall(ts.getHelperName("__await"), /*typeArguments*/ undefined, [expression]); + } + var asyncGeneratorHelper = { + name: "typescript:asyncGenerator", + scoped: false, + text: "\n var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\n function fulfill(value) { resume(\"next\", value); }\n function reject(value) { resume(\"throw\", value); }\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\n };" + }; + function createAsyncGeneratorHelper(context, generatorFunc) { + context.requestEmitHelper(awaitHelper); + context.requestEmitHelper(asyncGeneratorHelper); + // Mark this node as originally an async function + (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 262144 /* AsyncFunctionBody */; + return ts.createCall(ts.getHelperName("__asyncGenerator"), + /*typeArguments*/ undefined, [ + ts.createThis(), + ts.createIdentifier("arguments"), + generatorFunc + ]); + } + var asyncDelegator = { + name: "typescript:asyncDelegator", + scoped: false, + text: "\n var __asyncDelegator = (this && this.__asyncDelegator) || function (o) {\n var i, p;\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; } : f; }\n };" + }; + function createAsyncDelegatorHelper(context, expression, location) { + context.requestEmitHelper(awaitHelper); + context.requestEmitHelper(asyncDelegator); + return ts.setTextRange(ts.createCall(ts.getHelperName("__asyncDelegator"), + /*typeArguments*/ undefined, [expression]), location); + } + var asyncValues = { + name: "typescript:asyncValues", + scoped: false, + text: "\n var __asyncValues = (this && this.__asyncValues) || function (o) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var m = o[Symbol.asyncIterator], i;\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\n };" + }; + function createAsyncValuesHelper(context, expression, location) { + context.requestEmitHelper(asyncValues); + return ts.setTextRange(ts.createCall(ts.getHelperName("__asyncValues"), + /*typeArguments*/ undefined, [expression]), location); + } +})(ts || (ts = {})); +/*@internal*/ +var ts; +(function (ts) { + function transformJsx(context) { + var compilerOptions = context.getCompilerOptions(); + var currentSourceFile; + return ts.chainBundle(transformSourceFile); + /** + * Transform JSX-specific syntax in a SourceFile. + * + * @param node A SourceFile node. + */ + function transformSourceFile(node) { + if (node.isDeclarationFile) { + return node; + } + currentSourceFile = node; + var visited = ts.visitEachChild(node, visitor, context); + ts.addEmitHelpers(visited, context.readEmitHelpers()); + return visited; + } + function visitor(node) { + if (node.transformFlags & 4 /* ContainsJsx */) { + return visitorWorker(node); + } + else { + return node; + } + } + function visitorWorker(node) { + switch (node.kind) { + case 260 /* JsxElement */: + return visitJsxElement(node, /*isChild*/ false); + case 261 /* JsxSelfClosingElement */: + return visitJsxSelfClosingElement(node, /*isChild*/ false); + case 264 /* JsxFragment */: + return visitJsxFragment(node, /*isChild*/ false); + case 270 /* JsxExpression */: + return visitJsxExpression(node); + default: + return ts.visitEachChild(node, visitor, context); + } + } + function transformJsxChildToExpression(node) { + switch (node.kind) { + case 11 /* JsxText */: + return visitJsxText(node); + case 270 /* JsxExpression */: + return visitJsxExpression(node); + case 260 /* JsxElement */: + return visitJsxElement(node, /*isChild*/ true); + case 261 /* JsxSelfClosingElement */: + return visitJsxSelfClosingElement(node, /*isChild*/ true); + case 264 /* JsxFragment */: + return visitJsxFragment(node, /*isChild*/ true); + default: + return ts.Debug.failBadSyntaxKind(node); + } + } + function visitJsxElement(node, isChild) { + return visitJsxOpeningLikeElement(node.openingElement, node.children, isChild, /*location*/ node); + } + function visitJsxSelfClosingElement(node, isChild) { + return visitJsxOpeningLikeElement(node, /*children*/ undefined, isChild, /*location*/ node); + } + function visitJsxFragment(node, isChild) { + return visitJsxOpeningFragment(node.openingFragment, node.children, isChild, /*location*/ node); + } + function visitJsxOpeningLikeElement(node, children, isChild, location) { + var tagName = getTagName(node); + var objectProperties; + var attrs = node.attributes.properties; + if (attrs.length === 0) { + // When there are no attributes, React wants "null" + objectProperties = ts.createNull(); + } + else { + // Map spans of JsxAttribute nodes into object literals and spans + // of JsxSpreadAttribute nodes into expressions. + var segments = ts.flatten(ts.spanMap(attrs, ts.isJsxSpreadAttribute, function (attrs, isSpread) { return isSpread + ? ts.map(attrs, transformJsxSpreadAttributeToExpression) + : ts.createObjectLiteral(ts.map(attrs, transformJsxAttributeToObjectLiteralElement)); })); + if (ts.isJsxSpreadAttribute(attrs[0])) { + // We must always emit at least one object literal before a spread + // argument. + segments.unshift(ts.createObjectLiteral()); + } + // Either emit one big object literal (no spread attribs), or + // a call to the __assign helper. + objectProperties = ts.singleOrUndefined(segments); + if (!objectProperties) { + objectProperties = ts.createAssignHelper(context, segments); + } + } + var element = ts.createExpressionForJsxElement(context.getEmitResolver().getJsxFactoryEntity(currentSourceFile), compilerOptions.reactNamespace, // TODO: GH#18217 + tagName, objectProperties, ts.mapDefined(children, transformJsxChildToExpression), node, location); + if (isChild) { + ts.startOnNewLine(element); + } + return element; + } + function visitJsxOpeningFragment(node, children, isChild, location) { + var element = ts.createExpressionForJsxFragment(context.getEmitResolver().getJsxFactoryEntity(currentSourceFile), compilerOptions.reactNamespace, // TODO: GH#18217 + ts.mapDefined(children, transformJsxChildToExpression), node, location); + if (isChild) { + ts.startOnNewLine(element); + } + return element; + } + function transformJsxSpreadAttributeToExpression(node) { + return ts.visitNode(node.expression, visitor, ts.isExpression); + } + function transformJsxAttributeToObjectLiteralElement(node) { + var name = getAttributeName(node); + var expression = transformJsxAttributeInitializer(node.initializer); + return ts.createPropertyAssignment(name, expression); + } + function transformJsxAttributeInitializer(node) { + if (node === undefined) { + return ts.createTrue(); + } + else if (node.kind === 10 /* StringLiteral */) { + // Always recreate the literal to escape any escape sequences or newlines which may be in the original jsx string and which + // Need to be escaped to be handled correctly in a normal string + var literal = ts.createLiteral(tryDecodeEntities(node.text) || node.text); + literal.singleQuote = node.singleQuote !== undefined ? node.singleQuote : !ts.isStringDoubleQuoted(node, currentSourceFile); + return ts.setTextRange(literal, node); + } + else if (node.kind === 270 /* JsxExpression */) { + if (node.expression === undefined) { + return ts.createTrue(); + } + return visitJsxExpression(node); + } + else { + return ts.Debug.failBadSyntaxKind(node); + } + } + function visitJsxText(node) { + var fixed = fixupWhitespaceAndDecodeEntities(ts.getTextOfNode(node, /*includeTrivia*/ true)); + return fixed === undefined ? undefined : ts.createLiteral(fixed); + } + /** + * JSX trims whitespace at the end and beginning of lines, except that the + * start/end of a tag is considered a start/end of a line only if that line is + * on the same line as the closing tag. See examples in + * tests/cases/conformance/jsx/tsxReactEmitWhitespace.tsx + * See also https://www.w3.org/TR/html4/struct/text.html#h-9.1 and https://www.w3.org/TR/CSS2/text.html#white-space-model + * + * An equivalent algorithm would be: + * - If there is only one line, return it. + * - If there is only whitespace (but multiple lines), return `undefined`. + * - Split the text into lines. + * - 'trimRight' the first line, 'trimLeft' the last line, 'trim' middle lines. + * - Decode entities on each line (individually). + * - Remove empty lines and join the rest with " ". + */ + function fixupWhitespaceAndDecodeEntities(text) { + var acc; + // First non-whitespace character on this line. + var firstNonWhitespace = 0; + // Last non-whitespace character on this line. + var lastNonWhitespace = -1; + // These initial values are special because the first line is: + // firstNonWhitespace = 0 to indicate that we want leading whitsepace, + // but lastNonWhitespace = -1 as a special flag to indicate that we *don't* include the line if it's all whitespace. + for (var i = 0; i < text.length; i++) { + var c = text.charCodeAt(i); + if (ts.isLineBreak(c)) { + // If we've seen any non-whitespace characters on this line, add the 'trim' of the line. + // (lastNonWhitespace === -1 is a special flag to detect whether the first line is all whitespace.) + if (firstNonWhitespace !== -1 && lastNonWhitespace !== -1) { + acc = addLineOfJsxText(acc, text.substr(firstNonWhitespace, lastNonWhitespace - firstNonWhitespace + 1)); + } + // Reset firstNonWhitespace for the next line. + // Don't bother to reset lastNonWhitespace because we ignore it if firstNonWhitespace = -1. + firstNonWhitespace = -1; + } + else if (!ts.isWhiteSpaceSingleLine(c)) { + lastNonWhitespace = i; + if (firstNonWhitespace === -1) { + firstNonWhitespace = i; + } + } + } + return firstNonWhitespace !== -1 + // Last line had a non-whitespace character. Emit the 'trimLeft', meaning keep trailing whitespace. + ? addLineOfJsxText(acc, text.substr(firstNonWhitespace)) + // Last line was all whitespace, so ignore it + : acc; + } + function addLineOfJsxText(acc, trimmedLine) { + // We do not escape the string here as that is handled by the printer + // when it emits the literal. We do, however, need to decode JSX entities. + var decoded = decodeEntities(trimmedLine); + return acc === undefined ? decoded : acc + " " + decoded; + } + /** + * Replace entities like " ", "{", and "�" with the characters they encode. + * See https://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references + */ + function decodeEntities(text) { + return text.replace(/&((#((\d+)|x([\da-fA-F]+)))|(\w+));/g, function (match, _all, _number, _digits, decimal, hex, word) { + if (decimal) { + return String.fromCharCode(parseInt(decimal, 10)); + } + else if (hex) { + return String.fromCharCode(parseInt(hex, 16)); + } + else { + var ch = entities.get(word); + // If this is not a valid entity, then just use `match` (replace it with itself, i.e. don't replace) + return ch ? String.fromCharCode(ch) : match; + } + }); + } + /** Like `decodeEntities` but returns `undefined` if there were no entities to decode. */ + function tryDecodeEntities(text) { + var decoded = decodeEntities(text); + return decoded === text ? undefined : decoded; + } + function getTagName(node) { + if (node.kind === 260 /* JsxElement */) { + return getTagName(node.openingElement); + } + else { + var name = node.tagName; + if (ts.isIdentifier(name) && ts.isIntrinsicJsxName(name.escapedText)) { + return ts.createLiteral(ts.idText(name)); + } + else { + return ts.createExpressionFromEntityName(name); + } + } + } + /** + * Emit an attribute name, which is quoted if it needs to be quoted. Because + * these emit into an object literal property name, we don't need to be worried + * about keywords, just non-identifier characters + */ + function getAttributeName(node) { + var name = node.name; + var text = ts.idText(name); + if (/^[A-Za-z_]\w*$/.test(text)) { + return name; + } + else { + return ts.createLiteral(text); + } + } + function visitJsxExpression(node) { + return ts.visitNode(node.expression, visitor, ts.isExpression); + } + } + ts.transformJsx = transformJsx; + var entities = ts.createMapFromTemplate({ + quot: 0x0022, + amp: 0x0026, + apos: 0x0027, + lt: 0x003C, + gt: 0x003E, + nbsp: 0x00A0, + iexcl: 0x00A1, + cent: 0x00A2, + pound: 0x00A3, + curren: 0x00A4, + yen: 0x00A5, + brvbar: 0x00A6, + sect: 0x00A7, + uml: 0x00A8, + copy: 0x00A9, + ordf: 0x00AA, + laquo: 0x00AB, + not: 0x00AC, + shy: 0x00AD, + reg: 0x00AE, + macr: 0x00AF, + deg: 0x00B0, + plusmn: 0x00B1, + sup2: 0x00B2, + sup3: 0x00B3, + acute: 0x00B4, + micro: 0x00B5, + para: 0x00B6, + middot: 0x00B7, + cedil: 0x00B8, + sup1: 0x00B9, + ordm: 0x00BA, + raquo: 0x00BB, + frac14: 0x00BC, + frac12: 0x00BD, + frac34: 0x00BE, + iquest: 0x00BF, + Agrave: 0x00C0, + Aacute: 0x00C1, + Acirc: 0x00C2, + Atilde: 0x00C3, + Auml: 0x00C4, + Aring: 0x00C5, + AElig: 0x00C6, + Ccedil: 0x00C7, + Egrave: 0x00C8, + Eacute: 0x00C9, + Ecirc: 0x00CA, + Euml: 0x00CB, + Igrave: 0x00CC, + Iacute: 0x00CD, + Icirc: 0x00CE, + Iuml: 0x00CF, + ETH: 0x00D0, + Ntilde: 0x00D1, + Ograve: 0x00D2, + Oacute: 0x00D3, + Ocirc: 0x00D4, + Otilde: 0x00D5, + Ouml: 0x00D6, + times: 0x00D7, + Oslash: 0x00D8, + Ugrave: 0x00D9, + Uacute: 0x00DA, + Ucirc: 0x00DB, + Uuml: 0x00DC, + Yacute: 0x00DD, + THORN: 0x00DE, + szlig: 0x00DF, + agrave: 0x00E0, + aacute: 0x00E1, + acirc: 0x00E2, + atilde: 0x00E3, + auml: 0x00E4, + aring: 0x00E5, + aelig: 0x00E6, + ccedil: 0x00E7, + egrave: 0x00E8, + eacute: 0x00E9, + ecirc: 0x00EA, + euml: 0x00EB, + igrave: 0x00EC, + iacute: 0x00ED, + icirc: 0x00EE, + iuml: 0x00EF, + eth: 0x00F0, + ntilde: 0x00F1, + ograve: 0x00F2, + oacute: 0x00F3, + ocirc: 0x00F4, + otilde: 0x00F5, + ouml: 0x00F6, + divide: 0x00F7, + oslash: 0x00F8, + ugrave: 0x00F9, + uacute: 0x00FA, + ucirc: 0x00FB, + uuml: 0x00FC, + yacute: 0x00FD, + thorn: 0x00FE, + yuml: 0x00FF, + OElig: 0x0152, + oelig: 0x0153, + Scaron: 0x0160, + scaron: 0x0161, + Yuml: 0x0178, + fnof: 0x0192, + circ: 0x02C6, + tilde: 0x02DC, + Alpha: 0x0391, + Beta: 0x0392, + Gamma: 0x0393, + Delta: 0x0394, + Epsilon: 0x0395, + Zeta: 0x0396, + Eta: 0x0397, + Theta: 0x0398, + Iota: 0x0399, + Kappa: 0x039A, + Lambda: 0x039B, + Mu: 0x039C, + Nu: 0x039D, + Xi: 0x039E, + Omicron: 0x039F, + Pi: 0x03A0, + Rho: 0x03A1, + Sigma: 0x03A3, + Tau: 0x03A4, + Upsilon: 0x03A5, + Phi: 0x03A6, + Chi: 0x03A7, + Psi: 0x03A8, + Omega: 0x03A9, + alpha: 0x03B1, + beta: 0x03B2, + gamma: 0x03B3, + delta: 0x03B4, + epsilon: 0x03B5, + zeta: 0x03B6, + eta: 0x03B7, + theta: 0x03B8, + iota: 0x03B9, + kappa: 0x03BA, + lambda: 0x03BB, + mu: 0x03BC, + nu: 0x03BD, + xi: 0x03BE, + omicron: 0x03BF, + pi: 0x03C0, + rho: 0x03C1, + sigmaf: 0x03C2, + sigma: 0x03C3, + tau: 0x03C4, + upsilon: 0x03C5, + phi: 0x03C6, + chi: 0x03C7, + psi: 0x03C8, + omega: 0x03C9, + thetasym: 0x03D1, + upsih: 0x03D2, + piv: 0x03D6, + ensp: 0x2002, + emsp: 0x2003, + thinsp: 0x2009, + zwnj: 0x200C, + zwj: 0x200D, + lrm: 0x200E, + rlm: 0x200F, + ndash: 0x2013, + mdash: 0x2014, + lsquo: 0x2018, + rsquo: 0x2019, + sbquo: 0x201A, + ldquo: 0x201C, + rdquo: 0x201D, + bdquo: 0x201E, + dagger: 0x2020, + Dagger: 0x2021, + bull: 0x2022, + hellip: 0x2026, + permil: 0x2030, + prime: 0x2032, + Prime: 0x2033, + lsaquo: 0x2039, + rsaquo: 0x203A, + oline: 0x203E, + frasl: 0x2044, + euro: 0x20AC, + image: 0x2111, + weierp: 0x2118, + real: 0x211C, + trade: 0x2122, + alefsym: 0x2135, + larr: 0x2190, + uarr: 0x2191, + rarr: 0x2192, + darr: 0x2193, + harr: 0x2194, + crarr: 0x21B5, + lArr: 0x21D0, + uArr: 0x21D1, + rArr: 0x21D2, + dArr: 0x21D3, + hArr: 0x21D4, + forall: 0x2200, + part: 0x2202, + exist: 0x2203, + empty: 0x2205, + nabla: 0x2207, + isin: 0x2208, + notin: 0x2209, + ni: 0x220B, + prod: 0x220F, + sum: 0x2211, + minus: 0x2212, + lowast: 0x2217, + radic: 0x221A, + prop: 0x221D, + infin: 0x221E, + ang: 0x2220, + and: 0x2227, + or: 0x2228, + cap: 0x2229, + cup: 0x222A, + int: 0x222B, + there4: 0x2234, + sim: 0x223C, + cong: 0x2245, + asymp: 0x2248, + ne: 0x2260, + equiv: 0x2261, + le: 0x2264, + ge: 0x2265, + sub: 0x2282, + sup: 0x2283, + nsub: 0x2284, + sube: 0x2286, + supe: 0x2287, + oplus: 0x2295, + otimes: 0x2297, + perp: 0x22A5, + sdot: 0x22C5, + lceil: 0x2308, + rceil: 0x2309, + lfloor: 0x230A, + rfloor: 0x230B, + lang: 0x2329, + rang: 0x232A, + loz: 0x25CA, + spades: 0x2660, + clubs: 0x2663, + hearts: 0x2665, + diams: 0x2666 + }); +})(ts || (ts = {})); +/*@internal*/ +var ts; +(function (ts) { + function transformES2016(context) { + var hoistVariableDeclaration = context.hoistVariableDeclaration; + return ts.chainBundle(transformSourceFile); + function transformSourceFile(node) { + if (node.isDeclarationFile) { + return node; + } + return ts.visitEachChild(node, visitor, context); + } + function visitor(node) { + if ((node.transformFlags & 32 /* ContainsES2016 */) === 0) { + return node; + } + switch (node.kind) { + case 204 /* BinaryExpression */: + return visitBinaryExpression(node); + default: + return ts.visitEachChild(node, visitor, context); + } + } + function visitBinaryExpression(node) { + switch (node.operatorToken.kind) { + case 63 /* AsteriskAsteriskEqualsToken */: + return visitExponentiationAssignmentExpression(node); + case 41 /* AsteriskAsteriskToken */: + return visitExponentiationExpression(node); + default: + return ts.visitEachChild(node, visitor, context); + } + } + function visitExponentiationAssignmentExpression(node) { + var target; + var value; + var left = ts.visitNode(node.left, visitor, ts.isExpression); + var right = ts.visitNode(node.right, visitor, ts.isExpression); + if (ts.isElementAccessExpression(left)) { + // Transforms `a[x] **= b` into `(_a = a)[_x = x] = Math.pow(_a[_x], b)` + var expressionTemp = ts.createTempVariable(hoistVariableDeclaration); + var argumentExpressionTemp = ts.createTempVariable(hoistVariableDeclaration); + target = ts.setTextRange(ts.createElementAccess(ts.setTextRange(ts.createAssignment(expressionTemp, left.expression), left.expression), ts.setTextRange(ts.createAssignment(argumentExpressionTemp, left.argumentExpression), left.argumentExpression)), left); + value = ts.setTextRange(ts.createElementAccess(expressionTemp, argumentExpressionTemp), left); + } + else if (ts.isPropertyAccessExpression(left)) { + // Transforms `a.x **= b` into `(_a = a).x = Math.pow(_a.x, b)` + var expressionTemp = ts.createTempVariable(hoistVariableDeclaration); + target = ts.setTextRange(ts.createPropertyAccess(ts.setTextRange(ts.createAssignment(expressionTemp, left.expression), left.expression), left.name), left); + value = ts.setTextRange(ts.createPropertyAccess(expressionTemp, left.name), left); + } + else { + // Transforms `a **= b` into `a = Math.pow(a, b)` + target = left; + value = left; + } + return ts.setTextRange(ts.createAssignment(target, ts.createMathPow(value, right, /*location*/ node)), node); + } + function visitExponentiationExpression(node) { + // Transforms `a ** b` into `Math.pow(a, b)` + var left = ts.visitNode(node.left, visitor, ts.isExpression); + var right = ts.visitNode(node.right, visitor, ts.isExpression); + return ts.createMathPow(left, right, /*location*/ node); + } + } + ts.transformES2016 = transformES2016; +})(ts || (ts = {})); +/*@internal*/ +var ts; +(function (ts) { + var ES2015SubstitutionFlags; + (function (ES2015SubstitutionFlags) { + /** Enables substitutions for captured `this` */ + ES2015SubstitutionFlags[ES2015SubstitutionFlags["CapturedThis"] = 1] = "CapturedThis"; + /** Enables substitutions for block-scoped bindings. */ + ES2015SubstitutionFlags[ES2015SubstitutionFlags["BlockScopedBindings"] = 2] = "BlockScopedBindings"; + })(ES2015SubstitutionFlags || (ES2015SubstitutionFlags = {})); + var LoopOutParameterFlags; + (function (LoopOutParameterFlags) { + LoopOutParameterFlags[LoopOutParameterFlags["Body"] = 1] = "Body"; + LoopOutParameterFlags[LoopOutParameterFlags["Initializer"] = 2] = "Initializer"; + })(LoopOutParameterFlags || (LoopOutParameterFlags = {})); + var CopyDirection; + (function (CopyDirection) { + CopyDirection[CopyDirection["ToOriginal"] = 0] = "ToOriginal"; + CopyDirection[CopyDirection["ToOutParameter"] = 1] = "ToOutParameter"; + })(CopyDirection || (CopyDirection = {})); + var Jump; + (function (Jump) { + Jump[Jump["Break"] = 2] = "Break"; + Jump[Jump["Continue"] = 4] = "Continue"; + Jump[Jump["Return"] = 8] = "Return"; + })(Jump || (Jump = {})); + var SuperCaptureResult; + (function (SuperCaptureResult) { + /** + * A capture may have been added for calls to 'super', but + * the caller should emit subsequent statements normally. + */ + SuperCaptureResult[SuperCaptureResult["NoReplacement"] = 0] = "NoReplacement"; + /** + * A call to 'super()' got replaced with a capturing statement like: + * + * var _this = _super.call(...) || this; + * + * Callers should skip the current statement. + */ + SuperCaptureResult[SuperCaptureResult["ReplaceSuperCapture"] = 1] = "ReplaceSuperCapture"; + /** + * A call to 'super()' got replaced with a capturing statement like: + * + * return _super.call(...) || this; + * + * Callers should skip the current statement and avoid any returns of '_this'. + */ + SuperCaptureResult[SuperCaptureResult["ReplaceWithReturn"] = 2] = "ReplaceWithReturn"; + })(SuperCaptureResult || (SuperCaptureResult = {})); + // Facts we track as we traverse the tree + var HierarchyFacts; + (function (HierarchyFacts) { + HierarchyFacts[HierarchyFacts["None"] = 0] = "None"; + // + // Ancestor facts + // + HierarchyFacts[HierarchyFacts["Function"] = 1] = "Function"; + HierarchyFacts[HierarchyFacts["ArrowFunction"] = 2] = "ArrowFunction"; + HierarchyFacts[HierarchyFacts["AsyncFunctionBody"] = 4] = "AsyncFunctionBody"; + HierarchyFacts[HierarchyFacts["NonStaticClassElement"] = 8] = "NonStaticClassElement"; + HierarchyFacts[HierarchyFacts["CapturesThis"] = 16] = "CapturesThis"; + HierarchyFacts[HierarchyFacts["ExportedVariableStatement"] = 32] = "ExportedVariableStatement"; + HierarchyFacts[HierarchyFacts["TopLevel"] = 64] = "TopLevel"; + HierarchyFacts[HierarchyFacts["Block"] = 128] = "Block"; + HierarchyFacts[HierarchyFacts["IterationStatement"] = 256] = "IterationStatement"; + HierarchyFacts[HierarchyFacts["IterationStatementBlock"] = 512] = "IterationStatementBlock"; + HierarchyFacts[HierarchyFacts["ForStatement"] = 1024] = "ForStatement"; + HierarchyFacts[HierarchyFacts["ForInOrForOfStatement"] = 2048] = "ForInOrForOfStatement"; + HierarchyFacts[HierarchyFacts["ConstructorWithCapturedSuper"] = 4096] = "ConstructorWithCapturedSuper"; + HierarchyFacts[HierarchyFacts["ComputedPropertyName"] = 8192] = "ComputedPropertyName"; + // NOTE: do not add more ancestor flags without also updating AncestorFactsMask below. + // + // Ancestor masks + // + HierarchyFacts[HierarchyFacts["AncestorFactsMask"] = 16383] = "AncestorFactsMask"; + // We are always in *some* kind of block scope, but only specific block-scope containers are + // top-level or Blocks. + HierarchyFacts[HierarchyFacts["BlockScopeIncludes"] = 0] = "BlockScopeIncludes"; + HierarchyFacts[HierarchyFacts["BlockScopeExcludes"] = 4032] = "BlockScopeExcludes"; + // A source file is a top-level block scope. + HierarchyFacts[HierarchyFacts["SourceFileIncludes"] = 64] = "SourceFileIncludes"; + HierarchyFacts[HierarchyFacts["SourceFileExcludes"] = 3968] = "SourceFileExcludes"; + // Functions, methods, and accessors are both new lexical scopes and new block scopes. + HierarchyFacts[HierarchyFacts["FunctionIncludes"] = 65] = "FunctionIncludes"; + HierarchyFacts[HierarchyFacts["FunctionExcludes"] = 16286] = "FunctionExcludes"; + HierarchyFacts[HierarchyFacts["AsyncFunctionBodyIncludes"] = 69] = "AsyncFunctionBodyIncludes"; + HierarchyFacts[HierarchyFacts["AsyncFunctionBodyExcludes"] = 16278] = "AsyncFunctionBodyExcludes"; + // Arrow functions are lexically scoped to their container, but are new block scopes. + HierarchyFacts[HierarchyFacts["ArrowFunctionIncludes"] = 66] = "ArrowFunctionIncludes"; + HierarchyFacts[HierarchyFacts["ArrowFunctionExcludes"] = 16256] = "ArrowFunctionExcludes"; + // Constructors are both new lexical scopes and new block scopes. Constructors are also + // always considered non-static members of a class. + HierarchyFacts[HierarchyFacts["ConstructorIncludes"] = 73] = "ConstructorIncludes"; + HierarchyFacts[HierarchyFacts["ConstructorExcludes"] = 16278] = "ConstructorExcludes"; + // 'do' and 'while' statements are not block scopes. We track that the subtree is contained + // within an IterationStatement to indicate whether the embedded statement is an + // IterationStatementBlock. + HierarchyFacts[HierarchyFacts["DoOrWhileStatementIncludes"] = 256] = "DoOrWhileStatementIncludes"; + HierarchyFacts[HierarchyFacts["DoOrWhileStatementExcludes"] = 0] = "DoOrWhileStatementExcludes"; + // 'for' statements are new block scopes and have special handling for 'let' declarations. + HierarchyFacts[HierarchyFacts["ForStatementIncludes"] = 1280] = "ForStatementIncludes"; + HierarchyFacts[HierarchyFacts["ForStatementExcludes"] = 3008] = "ForStatementExcludes"; + // 'for-in' and 'for-of' statements are new block scopes and have special handling for + // 'let' declarations. + HierarchyFacts[HierarchyFacts["ForInOrForOfStatementIncludes"] = 2304] = "ForInOrForOfStatementIncludes"; + HierarchyFacts[HierarchyFacts["ForInOrForOfStatementExcludes"] = 1984] = "ForInOrForOfStatementExcludes"; + // Blocks (other than function bodies) are new block scopes. + HierarchyFacts[HierarchyFacts["BlockIncludes"] = 128] = "BlockIncludes"; + HierarchyFacts[HierarchyFacts["BlockExcludes"] = 3904] = "BlockExcludes"; + HierarchyFacts[HierarchyFacts["IterationStatementBlockIncludes"] = 512] = "IterationStatementBlockIncludes"; + HierarchyFacts[HierarchyFacts["IterationStatementBlockExcludes"] = 4032] = "IterationStatementBlockExcludes"; + // Computed property names track subtree flags differently than their containing members. + HierarchyFacts[HierarchyFacts["ComputedPropertyNameIncludes"] = 8192] = "ComputedPropertyNameIncludes"; + HierarchyFacts[HierarchyFacts["ComputedPropertyNameExcludes"] = 0] = "ComputedPropertyNameExcludes"; + // + // Subtree facts + // + HierarchyFacts[HierarchyFacts["NewTarget"] = 16384] = "NewTarget"; + HierarchyFacts[HierarchyFacts["NewTargetInComputedPropertyName"] = 32768] = "NewTargetInComputedPropertyName"; + // + // Subtree masks + // + HierarchyFacts[HierarchyFacts["SubtreeFactsMask"] = -16384] = "SubtreeFactsMask"; + HierarchyFacts[HierarchyFacts["PropagateNewTargetMask"] = 49152] = "PropagateNewTargetMask"; + })(HierarchyFacts || (HierarchyFacts = {})); + function transformES2015(context) { + var startLexicalEnvironment = context.startLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; + var compilerOptions = context.getCompilerOptions(); + var resolver = context.getEmitResolver(); + var previousOnSubstituteNode = context.onSubstituteNode; + var previousOnEmitNode = context.onEmitNode; + context.onEmitNode = onEmitNode; + context.onSubstituteNode = onSubstituteNode; + var currentSourceFile; + var currentText; + var hierarchyFacts; + var taggedTemplateStringDeclarations; + function recordTaggedTemplateString(temp) { + taggedTemplateStringDeclarations = ts.append(taggedTemplateStringDeclarations, ts.createVariableDeclaration(temp)); + } + /** + * Used to track if we are emitting body of the converted loop + */ + var convertedLoopState; + /** + * Keeps track of whether substitutions have been enabled for specific cases. + * They are persisted between each SourceFile transformation and should not + * be reset. + */ + var enabledSubstitutions; + return ts.chainBundle(transformSourceFile); + function transformSourceFile(node) { + if (node.isDeclarationFile) { + return node; + } + currentSourceFile = node; + currentText = node.text; + var visited = visitSourceFile(node); + ts.addEmitHelpers(visited, context.readEmitHelpers()); + currentSourceFile = undefined; + currentText = undefined; + taggedTemplateStringDeclarations = undefined; + hierarchyFacts = 0 /* None */; + return visited; + } + /** + * Sets the `HierarchyFacts` for this node prior to visiting this node's subtree, returning the facts set prior to modification. + * @param excludeFacts The existing `HierarchyFacts` to reset before visiting the subtree. + * @param includeFacts The new `HierarchyFacts` to set before visiting the subtree. + */ + function enterSubtree(excludeFacts, includeFacts) { + var ancestorFacts = hierarchyFacts; + hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & 16383 /* AncestorFactsMask */; + return ancestorFacts; + } + /** + * Restores the `HierarchyFacts` for this node's ancestor after visiting this node's + * subtree, propagating specific facts from the subtree. + * @param ancestorFacts The `HierarchyFacts` of the ancestor to restore after visiting the subtree. + * @param excludeFacts The existing `HierarchyFacts` of the subtree that should not be propagated. + * @param includeFacts The new `HierarchyFacts` of the subtree that should be propagated. + */ + function exitSubtree(ancestorFacts, excludeFacts, includeFacts) { + hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & -16384 /* SubtreeFactsMask */ | ancestorFacts; + } + function isReturnVoidStatementInConstructorWithCapturedSuper(node) { + return (hierarchyFacts & 4096 /* ConstructorWithCapturedSuper */) !== 0 + && node.kind === 230 /* ReturnStatement */ + && !node.expression; + } + function shouldVisitNode(node) { + return (node.transformFlags & 128 /* ContainsES2015 */) !== 0 + || convertedLoopState !== undefined + || (hierarchyFacts & 4096 /* ConstructorWithCapturedSuper */ && (ts.isStatement(node) || (node.kind === 218 /* Block */))) + || (ts.isIterationStatement(node, /*lookInLabeledStatements*/ false) && shouldConvertIterationStatement(node)) + || (ts.getEmitFlags(node) & 33554432 /* TypeScriptClassWrapper */) !== 0; + } + function visitor(node) { + if (shouldVisitNode(node)) { + return visitJavaScript(node); + } + else { + return node; + } + } + function functionBodyVisitor(node) { + if (shouldVisitNode(node)) { + return visitBlock(node, /*isFunctionBody*/ true); + } + return node; + } + function callExpressionVisitor(node) { + if (node.kind === 98 /* SuperKeyword */) { + return visitSuperKeyword(/*isExpressionOfCall*/ true); + } + return visitor(node); + } + function visitJavaScript(node) { + switch (node.kind) { + case 116 /* StaticKeyword */: + return undefined; // elide static keyword + case 240 /* ClassDeclaration */: + return visitClassDeclaration(node); + case 209 /* ClassExpression */: + return visitClassExpression(node); + case 151 /* Parameter */: + return visitParameter(node); + case 239 /* FunctionDeclaration */: + return visitFunctionDeclaration(node); + case 197 /* ArrowFunction */: + return visitArrowFunction(node); + case 196 /* FunctionExpression */: + return visitFunctionExpression(node); + case 237 /* VariableDeclaration */: + return visitVariableDeclaration(node); + case 72 /* Identifier */: + return visitIdentifier(node); + case 238 /* VariableDeclarationList */: + return visitVariableDeclarationList(node); + case 232 /* SwitchStatement */: + return visitSwitchStatement(node); + case 246 /* CaseBlock */: + return visitCaseBlock(node); + case 218 /* Block */: + return visitBlock(node, /*isFunctionBody*/ false); + case 229 /* BreakStatement */: + case 228 /* ContinueStatement */: + return visitBreakOrContinueStatement(node); + case 233 /* LabeledStatement */: + return visitLabeledStatement(node); + case 223 /* DoStatement */: + case 224 /* WhileStatement */: + return visitDoOrWhileStatement(node, /*outermostLabeledStatement*/ undefined); + case 225 /* ForStatement */: + return visitForStatement(node, /*outermostLabeledStatement*/ undefined); + case 226 /* ForInStatement */: + return visitForInStatement(node, /*outermostLabeledStatement*/ undefined); + case 227 /* ForOfStatement */: + return visitForOfStatement(node, /*outermostLabeledStatement*/ undefined); + case 221 /* ExpressionStatement */: + return visitExpressionStatement(node); + case 188 /* ObjectLiteralExpression */: + return visitObjectLiteralExpression(node); + case 274 /* CatchClause */: + return visitCatchClause(node); + case 276 /* ShorthandPropertyAssignment */: + return visitShorthandPropertyAssignment(node); + case 149 /* ComputedPropertyName */: + return visitComputedPropertyName(node); + case 187 /* ArrayLiteralExpression */: + return visitArrayLiteralExpression(node); + case 191 /* CallExpression */: + return visitCallExpression(node); + case 192 /* NewExpression */: + return visitNewExpression(node); + case 195 /* ParenthesizedExpression */: + return visitParenthesizedExpression(node, /*needsDestructuringValue*/ true); + case 204 /* BinaryExpression */: + return visitBinaryExpression(node, /*needsDestructuringValue*/ true); + case 14 /* NoSubstitutionTemplateLiteral */: + case 15 /* TemplateHead */: + case 16 /* TemplateMiddle */: + case 17 /* TemplateTail */: + return visitTemplateLiteral(node); + case 10 /* StringLiteral */: + return visitStringLiteral(node); + case 8 /* NumericLiteral */: + return visitNumericLiteral(node); + case 193 /* TaggedTemplateExpression */: + return visitTaggedTemplateExpression(node); + case 206 /* TemplateExpression */: + return visitTemplateExpression(node); + case 207 /* YieldExpression */: + return visitYieldExpression(node); + case 208 /* SpreadElement */: + return visitSpreadElement(node); + case 98 /* SuperKeyword */: + return visitSuperKeyword(/*isExpressionOfCall*/ false); + case 100 /* ThisKeyword */: + return visitThisKeyword(node); + case 214 /* MetaProperty */: + return visitMetaProperty(node); + case 156 /* MethodDeclaration */: + return visitMethodDeclaration(node); + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + return visitAccessorDeclaration(node); + case 219 /* VariableStatement */: + return visitVariableStatement(node); + case 230 /* ReturnStatement */: + return visitReturnStatement(node); + default: + return ts.visitEachChild(node, visitor, context); + } + } + function visitSourceFile(node) { + var ancestorFacts = enterSubtree(3968 /* SourceFileExcludes */, 64 /* SourceFileIncludes */); + var statements = []; + startLexicalEnvironment(); + var statementOffset = ts.addStandardPrologue(statements, node.statements, /*ensureUseStrict*/ false); + addCaptureThisForNodeIfNeeded(statements, node); + statementOffset = ts.addCustomPrologue(statements, node.statements, statementOffset, visitor); + ts.addRange(statements, ts.visitNodes(node.statements, visitor, ts.isStatement, statementOffset)); + if (taggedTemplateStringDeclarations) { + statements.push(ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList(taggedTemplateStringDeclarations))); + } + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */); + return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements)); + } + function visitSwitchStatement(node) { + if (convertedLoopState !== undefined) { + var savedAllowedNonLabeledJumps = convertedLoopState.allowedNonLabeledJumps; + // for switch statement allow only non-labeled break + convertedLoopState.allowedNonLabeledJumps |= 2 /* Break */; + var result = ts.visitEachChild(node, visitor, context); + convertedLoopState.allowedNonLabeledJumps = savedAllowedNonLabeledJumps; + return result; + } + return ts.visitEachChild(node, visitor, context); + } + function visitCaseBlock(node) { + var ancestorFacts = enterSubtree(4032 /* BlockScopeExcludes */, 0 /* BlockScopeIncludes */); + var updated = ts.visitEachChild(node, visitor, context); + exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */); + return updated; + } + function returnCapturedThis(node) { + return ts.setOriginalNode(ts.createReturn(ts.createFileLevelUniqueName("_this")), node); + } + function visitReturnStatement(node) { + if (convertedLoopState) { + convertedLoopState.nonLocalJumps |= 8 /* Return */; + if (isReturnVoidStatementInConstructorWithCapturedSuper(node)) { + node = returnCapturedThis(node); + } + return ts.createReturn(ts.createObjectLiteral([ + ts.createPropertyAssignment(ts.createIdentifier("value"), node.expression + ? ts.visitNode(node.expression, visitor, ts.isExpression) + : ts.createVoidZero()) + ])); + } + else if (isReturnVoidStatementInConstructorWithCapturedSuper(node)) { + return returnCapturedThis(node); + } + return ts.visitEachChild(node, visitor, context); + } + function visitThisKeyword(node) { + if (convertedLoopState) { + if (hierarchyFacts & 2 /* ArrowFunction */) { + // if the enclosing function is an ArrowFunction then we use the captured 'this' keyword. + convertedLoopState.containsLexicalThis = true; + return node; + } + return convertedLoopState.thisName || (convertedLoopState.thisName = ts.createUniqueName("this")); + } + return node; + } + function visitIdentifier(node) { + if (!convertedLoopState) { + return node; + } + if (ts.isGeneratedIdentifier(node)) { + return node; + } + if (node.escapedText !== "arguments" || !resolver.isArgumentsLocalBinding(node)) { + return node; + } + return convertedLoopState.argumentsName || (convertedLoopState.argumentsName = ts.createUniqueName("arguments")); + } + function visitBreakOrContinueStatement(node) { + if (convertedLoopState) { + // check if we can emit break/continue as is + // it is possible if either + // - break/continue is labeled and label is located inside the converted loop + // - break/continue is non-labeled and located in non-converted loop/switch statement + var jump = node.kind === 229 /* BreakStatement */ ? 2 /* Break */ : 4 /* Continue */; + var canUseBreakOrContinue = (node.label && convertedLoopState.labels && convertedLoopState.labels.get(ts.idText(node.label))) || + (!node.label && (convertedLoopState.allowedNonLabeledJumps & jump)); + if (!canUseBreakOrContinue) { + var labelMarker = void 0; + var label = node.label; + if (!label) { + if (node.kind === 229 /* BreakStatement */) { + convertedLoopState.nonLocalJumps |= 2 /* Break */; + labelMarker = "break"; + } + else { + convertedLoopState.nonLocalJumps |= 4 /* Continue */; + // note: return value is emitted only to simplify debugging, call to converted loop body does not do any dispatching on it. + labelMarker = "continue"; + } + } + else { + if (node.kind === 229 /* BreakStatement */) { + labelMarker = "break-" + label.escapedText; + setLabeledJump(convertedLoopState, /*isBreak*/ true, ts.idText(label), labelMarker); + } + else { + labelMarker = "continue-" + label.escapedText; + setLabeledJump(convertedLoopState, /*isBreak*/ false, ts.idText(label), labelMarker); + } + } + var returnExpression = ts.createLiteral(labelMarker); + if (convertedLoopState.loopOutParameters.length) { + var outParams = convertedLoopState.loopOutParameters; + var expr = void 0; + for (var i = 0; i < outParams.length; i++) { + var copyExpr = copyOutParameter(outParams[i], 1 /* ToOutParameter */); + if (i === 0) { + expr = copyExpr; + } + else { + expr = ts.createBinary(expr, 27 /* CommaToken */, copyExpr); + } + } + returnExpression = ts.createBinary(expr, 27 /* CommaToken */, returnExpression); + } + return ts.createReturn(returnExpression); + } + } + return ts.visitEachChild(node, visitor, context); + } + /** + * Visits a ClassDeclaration and transforms it into a variable statement. + * + * @param node A ClassDeclaration node. + */ + function visitClassDeclaration(node) { + // [source] + // class C { } + // + // [output] + // var C = (function () { + // function C() { + // } + // return C; + // }()); + var variable = ts.createVariableDeclaration(ts.getLocalName(node, /*allowComments*/ true), + /*type*/ undefined, transformClassLikeDeclarationToExpression(node)); + ts.setOriginalNode(variable, node); + var statements = []; + var statement = ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([variable])); + ts.setOriginalNode(statement, node); + ts.setTextRange(statement, node); + ts.startOnNewLine(statement); + statements.push(statement); + // Add an `export default` statement for default exports (for `--target es5 --module es6`) + if (ts.hasModifier(node, 1 /* Export */)) { + var exportStatement = ts.hasModifier(node, 512 /* Default */) + ? ts.createExportDefault(ts.getLocalName(node)) + : ts.createExternalModuleExport(ts.getLocalName(node)); + ts.setOriginalNode(exportStatement, statement); + statements.push(exportStatement); + } + var emitFlags = ts.getEmitFlags(node); + if ((emitFlags & 4194304 /* HasEndOfDeclarationMarker */) === 0) { + // Add a DeclarationMarker as a marker for the end of the declaration + statements.push(ts.createEndOfDeclarationMarker(node)); + ts.setEmitFlags(statement, emitFlags | 4194304 /* HasEndOfDeclarationMarker */); + } + return ts.singleOrMany(statements); + } + /** + * Visits a ClassExpression and transforms it into an expression. + * + * @param node A ClassExpression node. + */ + function visitClassExpression(node) { + // [source] + // C = class { } + // + // [output] + // C = (function () { + // function class_1() { + // } + // return class_1; + // }()) + return transformClassLikeDeclarationToExpression(node); + } + /** + * Transforms a ClassExpression or ClassDeclaration into an expression. + * + * @param node A ClassExpression or ClassDeclaration node. + */ + function transformClassLikeDeclarationToExpression(node) { + // [source] + // class C extends D { + // constructor() {} + // method() {} + // get prop() {} + // set prop(v) {} + // } + // + // [output] + // (function (_super) { + // __extends(C, _super); + // function C() { + // } + // C.prototype.method = function () {} + // Object.defineProperty(C.prototype, "prop", { + // get: function() {}, + // set: function() {}, + // enumerable: true, + // configurable: true + // }); + // return C; + // }(D)) + if (node.name) { + enableSubstitutionsForBlockScopedBindings(); + } + var extendsClauseElement = ts.getEffectiveBaseTypeNode(node); + var classFunction = ts.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, extendsClauseElement ? [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, ts.createFileLevelUniqueName("_super"))] : [], + /*type*/ undefined, transformClassBody(node, extendsClauseElement)); + // To preserve the behavior of the old emitter, we explicitly indent + // the body of the function here if it was requested in an earlier + // transformation. + ts.setEmitFlags(classFunction, (ts.getEmitFlags(node) & 65536 /* Indented */) | 524288 /* ReuseTempVariableScope */); + // "inner" and "outer" below are added purely to preserve source map locations from + // the old emitter + var inner = ts.createPartiallyEmittedExpression(classFunction); + inner.end = node.end; + ts.setEmitFlags(inner, 1536 /* NoComments */); + var outer = ts.createPartiallyEmittedExpression(inner); + outer.end = ts.skipTrivia(currentText, node.pos); + ts.setEmitFlags(outer, 1536 /* NoComments */); + var result = ts.createParen(ts.createCall(outer, + /*typeArguments*/ undefined, extendsClauseElement + ? [ts.visitNode(extendsClauseElement.expression, visitor, ts.isExpression)] + : [])); + ts.addSyntheticLeadingComment(result, 3 /* MultiLineCommentTrivia */, "* @class "); + return result; + } + /** + * Transforms a ClassExpression or ClassDeclaration into a function body. + * + * @param node A ClassExpression or ClassDeclaration node. + * @param extendsClauseElement The expression for the class `extends` clause. + */ + function transformClassBody(node, extendsClauseElement) { + var statements = []; + startLexicalEnvironment(); + addExtendsHelperIfNeeded(statements, node, extendsClauseElement); + addConstructor(statements, node, extendsClauseElement); + addClassMembers(statements, node); + // Create a synthetic text range for the return statement. + var closingBraceLocation = ts.createTokenRange(ts.skipTrivia(currentText, node.members.end), 19 /* CloseBraceToken */); + var localName = ts.getInternalName(node); + // The following partially-emitted expression exists purely to align our sourcemap + // emit with the original emitter. + var outer = ts.createPartiallyEmittedExpression(localName); + outer.end = closingBraceLocation.end; + ts.setEmitFlags(outer, 1536 /* NoComments */); + var statement = ts.createReturn(outer); + statement.pos = closingBraceLocation.pos; + ts.setEmitFlags(statement, 1536 /* NoComments */ | 384 /* NoTokenSourceMaps */); + statements.push(statement); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), /*location*/ node.members), /*multiLine*/ true); + ts.setEmitFlags(block, 1536 /* NoComments */); + return block; + } + /** + * Adds a call to the `__extends` helper if needed for a class. + * + * @param statements The statements of the class body function. + * @param node The ClassExpression or ClassDeclaration node. + * @param extendsClauseElement The expression for the class `extends` clause. + */ + function addExtendsHelperIfNeeded(statements, node, extendsClauseElement) { + if (extendsClauseElement) { + statements.push(ts.setTextRange(ts.createExpressionStatement(createExtendsHelper(context, ts.getInternalName(node))), + /*location*/ extendsClauseElement)); + } + } + /** + * Adds the constructor of the class to a class body function. + * + * @param statements The statements of the class body function. + * @param node The ClassExpression or ClassDeclaration node. + * @param extendsClauseElement The expression for the class `extends` clause. + */ + function addConstructor(statements, node, extendsClauseElement) { + var savedConvertedLoopState = convertedLoopState; + convertedLoopState = undefined; + var ancestorFacts = enterSubtree(16278 /* ConstructorExcludes */, 73 /* ConstructorIncludes */); + var constructor = ts.getFirstConstructorWithBody(node); + var hasSynthesizedSuper = hasSynthesizedDefaultSuperCall(constructor, extendsClauseElement !== undefined); + var constructorFunction = ts.createFunctionDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, ts.getInternalName(node), + /*typeParameters*/ undefined, transformConstructorParameters(constructor, hasSynthesizedSuper), + /*type*/ undefined, transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper)); + ts.setTextRange(constructorFunction, constructor || node); + if (extendsClauseElement) { + ts.setEmitFlags(constructorFunction, 8 /* CapturesThis */); + } + statements.push(constructorFunction); + exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, 0 /* None */); + convertedLoopState = savedConvertedLoopState; + } + /** + * Transforms the parameters of the constructor declaration of a class. + * + * @param constructor The constructor for the class. + * @param hasSynthesizedSuper A value indicating whether the constructor starts with a + * synthesized `super` call. + */ + function transformConstructorParameters(constructor, hasSynthesizedSuper) { + // If the TypeScript transformer needed to synthesize a constructor for property + // initializers, it would have also added a synthetic `...args` parameter and + // `super` call. + // If this is the case, we do not include the synthetic `...args` parameter and + // will instead use the `arguments` object in ES5/3. + return ts.visitParameterList(constructor && !hasSynthesizedSuper ? constructor.parameters : undefined, visitor, context) + || []; + } + /** + * Transforms the body of a constructor declaration of a class. + * + * @param constructor The constructor for the class. + * @param node The node which contains the constructor. + * @param extendsClauseElement The expression for the class `extends` clause. + * @param hasSynthesizedSuper A value indicating whether the constructor starts with a + * synthesized `super` call. + */ + function transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper) { + var statements = []; + resumeLexicalEnvironment(); + var statementOffset = -1; + if (hasSynthesizedSuper) { + // If a super call has already been synthesized, + // we're going to assume that we should just transform everything after that. + // The assumption is that no prior step in the pipeline has added any prologue directives. + statementOffset = 0; + } + else if (constructor) { + statementOffset = ts.addStandardPrologue(statements, constructor.body.statements, /*ensureUseStrict*/ false); + } + if (constructor) { + addDefaultValueAssignmentsIfNeeded(statements, constructor); + addRestParameterIfNeeded(statements, constructor, hasSynthesizedSuper); + if (!hasSynthesizedSuper) { + // If no super call has been synthesized, emit custom prologue directives. + statementOffset = ts.addCustomPrologue(statements, constructor.body.statements, statementOffset, visitor); + } + ts.Debug.assert(statementOffset >= 0, "statementOffset not initialized correctly!"); + } + // determine whether the class is known syntactically to be a derived class (e.g. a + // class that extends a value that is not syntactically known to be `null`). + var isDerivedClass = !!extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 96 /* NullKeyword */; + var superCaptureStatus = declareOrCaptureOrReturnThisForConstructorIfNeeded(statements, constructor, isDerivedClass, hasSynthesizedSuper, statementOffset); + // The last statement expression was replaced. Skip it. + if (superCaptureStatus === 1 /* ReplaceSuperCapture */ || superCaptureStatus === 2 /* ReplaceWithReturn */) { + statementOffset++; + } + if (constructor) { + if (superCaptureStatus === 1 /* ReplaceSuperCapture */) { + hierarchyFacts |= 4096 /* ConstructorWithCapturedSuper */; + } + ts.addRange(statements, ts.visitNodes(constructor.body.statements, visitor, ts.isStatement, /*start*/ statementOffset)); + } + // Return `_this` unless we're sure enough that it would be pointless to add a return statement. + // If there's a constructor that we can tell returns in enough places, then we *do not* want to add a return. + if (isDerivedClass + && superCaptureStatus !== 2 /* ReplaceWithReturn */ + && !(constructor && isSufficientlyCoveredByReturnStatements(constructor.body))) { + statements.push(ts.createReturn(ts.createFileLevelUniqueName("_this"))); + } + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + if (constructor) { + prependCaptureNewTargetIfNeeded(statements, constructor, /*copyOnWrite*/ false); + } + var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), + /*location*/ constructor ? constructor.body.statements : node.members), + /*multiLine*/ true); + ts.setTextRange(block, constructor ? constructor.body : node); + if (!constructor) { + ts.setEmitFlags(block, 1536 /* NoComments */); + } + return block; + } + /** + * We want to try to avoid emitting a return statement in certain cases if a user already returned something. + * It would generate obviously dead code, so we'll try to make things a little bit prettier + * by doing a minimal check on whether some common patterns always explicitly return. + */ + function isSufficientlyCoveredByReturnStatements(statement) { + // A return statement is considered covered. + if (statement.kind === 230 /* ReturnStatement */) { + return true; + } + // An if-statement with two covered branches is covered. + else if (statement.kind === 222 /* IfStatement */) { + var ifStatement = statement; + if (ifStatement.elseStatement) { + return isSufficientlyCoveredByReturnStatements(ifStatement.thenStatement) && + isSufficientlyCoveredByReturnStatements(ifStatement.elseStatement); + } + } + // A block is covered if it has a last statement which is covered. + else if (statement.kind === 218 /* Block */) { + var lastStatement = ts.lastOrUndefined(statement.statements); + if (lastStatement && isSufficientlyCoveredByReturnStatements(lastStatement)) { + return true; + } + } + return false; + } + /** + * Declares a `_this` variable for derived classes and for when arrow functions capture `this`. + * + * @returns The new statement offset into the `statements` array. + */ + function declareOrCaptureOrReturnThisForConstructorIfNeeded(statements, ctor, isDerivedClass, hasSynthesizedSuper, statementOffset) { + // If this isn't a derived class, just capture 'this' for arrow functions if necessary. + if (!isDerivedClass) { + if (ctor) { + addCaptureThisForNodeIfNeeded(statements, ctor); + } + return 0 /* NoReplacement */; + } + // We must be here because the user didn't write a constructor + // but we needed to call 'super(...args)' anyway as per 14.5.14 of the ES2016 spec. + // If that's the case we can just immediately return the result of a 'super()' call. + if (!ctor) { + statements.push(ts.createReturn(createDefaultSuperCallOrThis())); + return 2 /* ReplaceWithReturn */; + } + // The constructor exists, but it and the 'super()' call it contains were generated + // for something like property initializers. + // Create a captured '_this' variable and assume it will subsequently be used. + if (hasSynthesizedSuper) { + captureThisForNode(statements, ctor, createDefaultSuperCallOrThis()); + enableSubstitutionsForCapturedThis(); + return 1 /* ReplaceSuperCapture */; + } + // Most of the time, a 'super' call will be the first real statement in a constructor body. + // In these cases, we'd like to transform these into a *single* statement instead of a declaration + // followed by an assignment statement for '_this'. For instance, if we emitted without an initializer, + // we'd get: + // + // var _this; + // _this = _super.call(...) || this; + // + // instead of + // + // var _this = _super.call(...) || this; + // + // Additionally, if the 'super()' call is the last statement, we should just avoid capturing + // entirely and immediately return the result like so: + // + // return _super.call(...) || this; + // + var firstStatement; + var superCallExpression; + var ctorStatements = ctor.body.statements; + if (statementOffset < ctorStatements.length) { + firstStatement = ctorStatements[statementOffset]; + if (firstStatement.kind === 221 /* ExpressionStatement */ && ts.isSuperCall(firstStatement.expression)) { + superCallExpression = visitImmediateSuperCallInBody(firstStatement.expression); + } + } + // Return the result if we have an immediate super() call on the last statement, + // but only if the constructor itself doesn't use 'this' elsewhere. + if (superCallExpression + && statementOffset === ctorStatements.length - 1 + && !(ctor.transformFlags & (8192 /* ContainsLexicalThis */ | 16384 /* ContainsCapturedLexicalThis */))) { + var returnStatement = ts.createReturn(superCallExpression); + if (superCallExpression.kind !== 204 /* BinaryExpression */ + || superCallExpression.left.kind !== 191 /* CallExpression */) { + ts.Debug.fail("Assumed generated super call would have form 'super.call(...) || this'."); + } + // Shift comments from the original super call to the return statement. + ts.setCommentRange(returnStatement, ts.getCommentRange(ts.setEmitFlags(superCallExpression.left, 1536 /* NoComments */))); + statements.push(returnStatement); + return 2 /* ReplaceWithReturn */; + } + // Perform the capture. + captureThisForNode(statements, ctor, superCallExpression || createActualThis()); + // If we're actually replacing the original statement, we need to signal this to the caller. + if (superCallExpression) { + return 1 /* ReplaceSuperCapture */; + } + return 0 /* NoReplacement */; + } + function createActualThis() { + return ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */); + } + function createDefaultSuperCallOrThis() { + return ts.createLogicalOr(ts.createLogicalAnd(ts.createStrictInequality(ts.createFileLevelUniqueName("_super"), ts.createNull()), ts.createFunctionApply(ts.createFileLevelUniqueName("_super"), createActualThis(), ts.createIdentifier("arguments"))), createActualThis()); + } + /** + * Visits a parameter declaration. + * + * @param node A ParameterDeclaration node. + */ + function visitParameter(node) { + if (node.dotDotDotToken) { + // rest parameters are elided + return undefined; + } + else if (ts.isBindingPattern(node.name)) { + // Binding patterns are converted into a generated name and are + // evaluated inside the function body. + return ts.setOriginalNode(ts.setTextRange(ts.createParameter( + /*decorators*/ undefined, + /*modifiers*/ undefined, + /*dotDotDotToken*/ undefined, ts.getGeneratedNameForNode(node), + /*questionToken*/ undefined, + /*type*/ undefined, + /*initializer*/ undefined), + /*location*/ node), + /*original*/ node); + } + else if (node.initializer) { + // Initializers are elided + return ts.setOriginalNode(ts.setTextRange(ts.createParameter( + /*decorators*/ undefined, + /*modifiers*/ undefined, + /*dotDotDotToken*/ undefined, node.name, + /*questionToken*/ undefined, + /*type*/ undefined, + /*initializer*/ undefined), + /*location*/ node), + /*original*/ node); + } + else { + return node; + } + } + /** + * Gets a value indicating whether we need to add default value assignments for a + * function-like node. + * + * @param node A function-like node. + */ + function shouldAddDefaultValueAssignments(node) { + return (node.transformFlags & 65536 /* ContainsDefaultValueAssignments */) !== 0; + } + /** + * Adds statements to the body of a function-like node if it contains parameters with + * binding patterns or initializers. + * + * @param statements The statements for the new function body. + * @param node A function-like node. + */ + function addDefaultValueAssignmentsIfNeeded(statements, node) { + if (!shouldAddDefaultValueAssignments(node)) { + return; + } + for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { + var parameter = _a[_i]; + var name = parameter.name, initializer = parameter.initializer, dotDotDotToken = parameter.dotDotDotToken; + // A rest parameter cannot have a binding pattern or an initializer, + // so let's just ignore it. + if (dotDotDotToken) { + continue; + } + if (ts.isBindingPattern(name)) { + addDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer); + } + else if (initializer) { + addDefaultValueAssignmentForInitializer(statements, parameter, name, initializer); + } + } + } + /** + * Adds statements to the body of a function-like node for parameters with binding patterns + * + * @param statements The statements for the new function body. + * @param parameter The parameter for the function. + * @param name The name of the parameter. + * @param initializer The initializer for the parameter. + */ + function addDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer) { + var temp = ts.getGeneratedNameForNode(parameter); + // In cases where a binding pattern is simply '[]' or '{}', + // we usually don't want to emit a var declaration; however, in the presence + // of an initializer, we must emit that expression to preserve side effects. + if (name.elements.length > 0) { + statements.push(ts.setEmitFlags(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList(ts.flattenDestructuringBinding(parameter, visitor, context, 0 /* All */, temp))), 1048576 /* CustomPrologue */)); + } + else if (initializer) { + statements.push(ts.setEmitFlags(ts.createExpressionStatement(ts.createAssignment(temp, ts.visitNode(initializer, visitor, ts.isExpression))), 1048576 /* CustomPrologue */)); + } + } + /** + * Adds statements to the body of a function-like node for parameters with initializers. + * + * @param statements The statements for the new function body. + * @param parameter The parameter for the function. + * @param name The name of the parameter. + * @param initializer The initializer for the parameter. + */ + function addDefaultValueAssignmentForInitializer(statements, parameter, name, initializer) { + initializer = ts.visitNode(initializer, visitor, ts.isExpression); + var statement = ts.createIf(ts.createTypeCheck(ts.getSynthesizedClone(name), "undefined"), ts.setEmitFlags(ts.setTextRange(ts.createBlock([ + ts.createExpressionStatement(ts.setEmitFlags(ts.setTextRange(ts.createAssignment(ts.setEmitFlags(ts.getMutableClone(name), 48 /* NoSourceMap */), ts.setEmitFlags(initializer, 48 /* NoSourceMap */ | ts.getEmitFlags(initializer) | 1536 /* NoComments */)), parameter), 1536 /* NoComments */)) + ]), parameter), 1 /* SingleLine */ | 32 /* NoTrailingSourceMap */ | 384 /* NoTokenSourceMaps */ | 1536 /* NoComments */)); + ts.startOnNewLine(statement); + ts.setTextRange(statement, parameter); + ts.setEmitFlags(statement, 384 /* NoTokenSourceMaps */ | 32 /* NoTrailingSourceMap */ | 1048576 /* CustomPrologue */ | 1536 /* NoComments */); + statements.push(statement); + } + /** + * Gets a value indicating whether we need to add statements to handle a rest parameter. + * + * @param node A ParameterDeclaration node. + * @param inConstructorWithSynthesizedSuper A value indicating whether the parameter is + * part of a constructor declaration with a + * synthesized call to `super` + */ + function shouldAddRestParameter(node, inConstructorWithSynthesizedSuper) { + return node && node.dotDotDotToken && node.name.kind === 72 /* Identifier */ && !inConstructorWithSynthesizedSuper; + } + /** + * Adds statements to the body of a function-like node if it contains a rest parameter. + * + * @param statements The statements for the new function body. + * @param node A function-like node. + * @param inConstructorWithSynthesizedSuper A value indicating whether the parameter is + * part of a constructor declaration with a + * synthesized call to `super` + */ + function addRestParameterIfNeeded(statements, node, inConstructorWithSynthesizedSuper) { + var parameter = ts.lastOrUndefined(node.parameters); + if (!shouldAddRestParameter(parameter, inConstructorWithSynthesizedSuper)) { + return; + } + // `declarationName` is the name of the local declaration for the parameter. + var declarationName = ts.getMutableClone(parameter.name); + ts.setEmitFlags(declarationName, 48 /* NoSourceMap */); + // `expressionName` is the name of the parameter used in expressions. + var expressionName = ts.getSynthesizedClone(parameter.name); + var restIndex = node.parameters.length - 1; + var temp = ts.createLoopVariable(); + // var param = []; + statements.push(ts.setEmitFlags(ts.setTextRange(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(declarationName, + /*type*/ undefined, ts.createArrayLiteral([])) + ])), + /*location*/ parameter), 1048576 /* CustomPrologue */)); + // for (var _i = restIndex; _i < arguments.length; _i++) { + // param[_i - restIndex] = arguments[_i]; + // } + var forStatement = ts.createFor(ts.setTextRange(ts.createVariableDeclarationList([ + ts.createVariableDeclaration(temp, /*type*/ undefined, ts.createLiteral(restIndex)) + ]), parameter), ts.setTextRange(ts.createLessThan(temp, ts.createPropertyAccess(ts.createIdentifier("arguments"), "length")), parameter), ts.setTextRange(ts.createPostfixIncrement(temp), parameter), ts.createBlock([ + ts.startOnNewLine(ts.setTextRange(ts.createExpressionStatement(ts.createAssignment(ts.createElementAccess(expressionName, restIndex === 0 + ? temp + : ts.createSubtract(temp, ts.createLiteral(restIndex))), ts.createElementAccess(ts.createIdentifier("arguments"), temp))), + /*location*/ parameter)) + ])); + ts.setEmitFlags(forStatement, 1048576 /* CustomPrologue */); + ts.startOnNewLine(forStatement); + statements.push(forStatement); + } + /** + * Adds a statement to capture the `this` of a function declaration if it is needed. + * + * @param statements The statements for the new function body. + * @param node A node. + */ + function addCaptureThisForNodeIfNeeded(statements, node) { + if (node.transformFlags & 16384 /* ContainsCapturedLexicalThis */ && node.kind !== 197 /* ArrowFunction */) { + captureThisForNode(statements, node, ts.createThis()); + } + } + function captureThisForNode(statements, node, initializer) { + enableSubstitutionsForCapturedThis(); + var captureThisStatement = ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(ts.createFileLevelUniqueName("_this"), + /*type*/ undefined, initializer) + ])); + ts.setEmitFlags(captureThisStatement, 1536 /* NoComments */ | 1048576 /* CustomPrologue */); + ts.setSourceMapRange(captureThisStatement, node); + statements.push(captureThisStatement); + } + function prependCaptureNewTargetIfNeeded(statements, node, copyOnWrite) { + if (hierarchyFacts & 16384 /* NewTarget */) { + var newTarget = void 0; + switch (node.kind) { + case 197 /* ArrowFunction */: + return statements; + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + // Methods and accessors cannot be constructors, so 'new.target' will + // always return 'undefined'. + newTarget = ts.createVoidZero(); + break; + case 157 /* Constructor */: + // Class constructors can only be called with `new`, so `this.constructor` + // should be relatively safe to use. + newTarget = ts.createPropertyAccess(ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */), "constructor"); + break; + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + // Functions can be called or constructed, and may have a `this` due to + // being a member or when calling an imported function via `other_1.f()`. + newTarget = ts.createConditional(ts.createLogicalAnd(ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */), ts.createBinary(ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */), 94 /* InstanceOfKeyword */, ts.getLocalName(node))), ts.createPropertyAccess(ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */), "constructor"), ts.createVoidZero()); + break; + default: + return ts.Debug.failBadSyntaxKind(node); + } + var captureNewTargetStatement = ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(ts.createFileLevelUniqueName("_newTarget"), + /*type*/ undefined, newTarget) + ])); + if (copyOnWrite) { + return [captureNewTargetStatement].concat(statements); + } + statements.unshift(captureNewTargetStatement); + } + return statements; + } + /** + * Adds statements to the class body function for a class to define the members of the + * class. + * + * @param statements The statements for the class body function. + * @param node The ClassExpression or ClassDeclaration node. + */ + function addClassMembers(statements, node) { + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + switch (member.kind) { + case 217 /* SemicolonClassElement */: + statements.push(transformSemicolonClassElementToStatement(member)); + break; + case 156 /* MethodDeclaration */: + statements.push(transformClassMethodDeclarationToStatement(getClassMemberPrefix(node, member), member, node)); + break; + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + var accessors = ts.getAllAccessorDeclarations(node.members, member); + if (member === accessors.firstAccessor) { + statements.push(transformAccessorsToStatement(getClassMemberPrefix(node, member), accessors, node)); + } + break; + case 157 /* Constructor */: + // Constructors are handled in visitClassExpression/visitClassDeclaration + break; + default: + ts.Debug.failBadSyntaxKind(node); + break; + } + } + } + /** + * Transforms a SemicolonClassElement into a statement for a class body function. + * + * @param member The SemicolonClassElement node. + */ + function transformSemicolonClassElementToStatement(member) { + return ts.setTextRange(ts.createEmptyStatement(), member); + } + /** + * Transforms a MethodDeclaration into a statement for a class body function. + * + * @param receiver The receiver for the member. + * @param member The MethodDeclaration node. + */ + function transformClassMethodDeclarationToStatement(receiver, member, container) { + var ancestorFacts = enterSubtree(0 /* None */, 0 /* None */); + var commentRange = ts.getCommentRange(member); + var sourceMapRange = ts.getSourceMapRange(member); + var memberName = ts.createMemberAccessForPropertyName(receiver, ts.visitNode(member.name, visitor, ts.isPropertyName), /*location*/ member.name); + var memberFunction = transformFunctionLikeToExpression(member, /*location*/ member, /*name*/ undefined, container); + ts.setEmitFlags(memberFunction, 1536 /* NoComments */); + ts.setSourceMapRange(memberFunction, sourceMapRange); + var statement = ts.setTextRange(ts.createExpressionStatement(ts.createAssignment(memberName, memberFunction)), + /*location*/ member); + ts.setOriginalNode(statement, member); + ts.setCommentRange(statement, commentRange); + // The location for the statement is used to emit comments only. + // No source map should be emitted for this statement to align with the + // old emitter. + ts.setEmitFlags(statement, 48 /* NoSourceMap */); + exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, hierarchyFacts & 49152 /* PropagateNewTargetMask */ ? 16384 /* NewTarget */ : 0 /* None */); + return statement; + } + /** + * Transforms a set of related of get/set accessors into a statement for a class body function. + * + * @param receiver The receiver for the member. + * @param accessors The set of related get/set accessors. + */ + function transformAccessorsToStatement(receiver, accessors, container) { + var statement = ts.createExpressionStatement(transformAccessorsToExpression(receiver, accessors, container, /*startsOnNewLine*/ false)); + // The location for the statement is used to emit source maps only. + // No comments should be emitted for this statement to align with the + // old emitter. + ts.setEmitFlags(statement, 1536 /* NoComments */); + ts.setSourceMapRange(statement, ts.getSourceMapRange(accessors.firstAccessor)); + return statement; + } + /** + * Transforms a set of related get/set accessors into an expression for either a class + * body function or an ObjectLiteralExpression with computed properties. + * + * @param receiver The receiver for the member. + */ + function transformAccessorsToExpression(receiver, _a, container, startsOnNewLine) { + var firstAccessor = _a.firstAccessor, getAccessor = _a.getAccessor, setAccessor = _a.setAccessor; + var ancestorFacts = enterSubtree(0 /* None */, 0 /* None */); + // To align with source maps in the old emitter, the receiver and property name + // arguments are both mapped contiguously to the accessor name. + var target = ts.getMutableClone(receiver); + ts.setEmitFlags(target, 1536 /* NoComments */ | 32 /* NoTrailingSourceMap */); + ts.setSourceMapRange(target, firstAccessor.name); // TODO: GH#18217 + var propertyName = ts.createExpressionForPropertyName(ts.visitNode(firstAccessor.name, visitor, ts.isPropertyName)); + ts.setEmitFlags(propertyName, 1536 /* NoComments */ | 16 /* NoLeadingSourceMap */); + ts.setSourceMapRange(propertyName, firstAccessor.name); + var properties = []; + if (getAccessor) { + var getterFunction = transformFunctionLikeToExpression(getAccessor, /*location*/ undefined, /*name*/ undefined, container); + ts.setSourceMapRange(getterFunction, ts.getSourceMapRange(getAccessor)); + ts.setEmitFlags(getterFunction, 512 /* NoLeadingComments */); + var getter = ts.createPropertyAssignment("get", getterFunction); + ts.setCommentRange(getter, ts.getCommentRange(getAccessor)); + properties.push(getter); + } + if (setAccessor) { + var setterFunction = transformFunctionLikeToExpression(setAccessor, /*location*/ undefined, /*name*/ undefined, container); + ts.setSourceMapRange(setterFunction, ts.getSourceMapRange(setAccessor)); + ts.setEmitFlags(setterFunction, 512 /* NoLeadingComments */); + var setter = ts.createPropertyAssignment("set", setterFunction); + ts.setCommentRange(setter, ts.getCommentRange(setAccessor)); + properties.push(setter); + } + properties.push(ts.createPropertyAssignment("enumerable", ts.createTrue()), ts.createPropertyAssignment("configurable", ts.createTrue())); + var call = ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"), + /*typeArguments*/ undefined, [ + target, + propertyName, + ts.createObjectLiteral(properties, /*multiLine*/ true) + ]); + if (startsOnNewLine) { + ts.startOnNewLine(call); + } + exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, hierarchyFacts & 49152 /* PropagateNewTargetMask */ ? 16384 /* NewTarget */ : 0 /* None */); + return call; + } + /** + * Visits an ArrowFunction and transforms it into a FunctionExpression. + * + * @param node An ArrowFunction node. + */ + function visitArrowFunction(node) { + if (node.transformFlags & 8192 /* ContainsLexicalThis */) { + enableSubstitutionsForCapturedThis(); + } + var savedConvertedLoopState = convertedLoopState; + convertedLoopState = undefined; + var ancestorFacts = enterSubtree(16256 /* ArrowFunctionExcludes */, 66 /* ArrowFunctionIncludes */); + var func = ts.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, transformFunctionBody(node)); + ts.setTextRange(func, node); + ts.setOriginalNode(func, node); + ts.setEmitFlags(func, 8 /* CapturesThis */); + exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */); + convertedLoopState = savedConvertedLoopState; + return func; + } + /** + * Visits a FunctionExpression node. + * + * @param node a FunctionExpression node. + */ + function visitFunctionExpression(node) { + var ancestorFacts = ts.getEmitFlags(node) & 262144 /* AsyncFunctionBody */ + ? enterSubtree(16278 /* AsyncFunctionBodyExcludes */, 69 /* AsyncFunctionBodyIncludes */) + : enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */); + var savedConvertedLoopState = convertedLoopState; + convertedLoopState = undefined; + var parameters = ts.visitParameterList(node.parameters, visitor, context); + var body = node.transformFlags & 64 /* ES2015 */ + ? transformFunctionBody(node) + : visitFunctionBodyDownLevel(node); + var name = hierarchyFacts & 16384 /* NewTarget */ + ? ts.getLocalName(node) + : node.name; + exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, 0 /* None */); + convertedLoopState = savedConvertedLoopState; + return ts.updateFunctionExpression(node, + /*modifiers*/ undefined, node.asteriskToken, name, + /*typeParameters*/ undefined, parameters, + /*type*/ undefined, body); + } + /** + * Visits a FunctionDeclaration node. + * + * @param node a FunctionDeclaration node. + */ + function visitFunctionDeclaration(node) { + var savedConvertedLoopState = convertedLoopState; + convertedLoopState = undefined; + var ancestorFacts = enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */); + var parameters = ts.visitParameterList(node.parameters, visitor, context); + var body = node.transformFlags & 64 /* ES2015 */ + ? transformFunctionBody(node) + : visitFunctionBodyDownLevel(node); + var name = hierarchyFacts & 16384 /* NewTarget */ + ? ts.getLocalName(node) + : node.name; + exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, 0 /* None */); + convertedLoopState = savedConvertedLoopState; + return ts.updateFunctionDeclaration(node, + /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, name, + /*typeParameters*/ undefined, parameters, + /*type*/ undefined, body); + } + /** + * Transforms a function-like node into a FunctionExpression. + * + * @param node The function-like node to transform. + * @param location The source-map location for the new FunctionExpression. + * @param name The name of the new FunctionExpression. + */ + function transformFunctionLikeToExpression(node, location, name, container) { + var savedConvertedLoopState = convertedLoopState; + convertedLoopState = undefined; + var ancestorFacts = container && ts.isClassLike(container) && !ts.hasModifier(node, 32 /* Static */) + ? enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */ | 8 /* NonStaticClassElement */) + : enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */); + var parameters = ts.visitParameterList(node.parameters, visitor, context); + var body = transformFunctionBody(node); + if (hierarchyFacts & 16384 /* NewTarget */ && !name && (node.kind === 239 /* FunctionDeclaration */ || node.kind === 196 /* FunctionExpression */)) { + name = ts.getGeneratedNameForNode(node); + } + exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, 0 /* None */); + convertedLoopState = savedConvertedLoopState; + return ts.setOriginalNode(ts.setTextRange(ts.createFunctionExpression( + /*modifiers*/ undefined, node.asteriskToken, name, + /*typeParameters*/ undefined, parameters, + /*type*/ undefined, body), location), + /*original*/ node); + } + /** + * Transforms the body of a function-like node. + * + * @param node A function-like node. + */ + function transformFunctionBody(node) { + var multiLine = false; // indicates whether the block *must* be emitted as multiple lines + var singleLine = false; // indicates whether the block *may* be emitted as a single line + var statementsLocation; + var closeBraceLocation; + var leadingStatements = []; + var statements = []; + var body = node.body; + var statementOffset; + resumeLexicalEnvironment(); + if (ts.isBlock(body)) { + // ensureUseStrict is false because no new prologue-directive should be added. + // addStandardPrologue will put already-existing directives at the beginning of the target statement-array + statementOffset = ts.addStandardPrologue(leadingStatements, body.statements, /*ensureUseStrict*/ false); + } + addCaptureThisForNodeIfNeeded(leadingStatements, node); + addDefaultValueAssignmentsIfNeeded(leadingStatements, node); + addRestParameterIfNeeded(leadingStatements, node, /*inConstructorWithSynthesizedSuper*/ false); + if (ts.isBlock(body)) { + // addCustomPrologue puts already-existing directives at the beginning of the target statement-array + statementOffset = ts.addCustomPrologue(leadingStatements, body.statements, statementOffset, visitor); + statementsLocation = body.statements; + ts.addRange(statements, ts.visitNodes(body.statements, visitor, ts.isStatement, statementOffset)); + // If the original body was a multi-line block, this must be a multi-line block. + if (!multiLine && body.multiLine) { + multiLine = true; + } + } + else { + ts.Debug.assert(node.kind === 197 /* ArrowFunction */); + // To align with the old emitter, we use a synthetic end position on the location + // for the statement list we synthesize when we down-level an arrow function with + // an expression function body. This prevents both comments and source maps from + // being emitted for the end position only. + statementsLocation = ts.moveRangeEnd(body, -1); + var equalsGreaterThanToken = node.equalsGreaterThanToken; + if (!ts.nodeIsSynthesized(equalsGreaterThanToken) && !ts.nodeIsSynthesized(body)) { + if (ts.rangeEndIsOnSameLineAsRangeStart(equalsGreaterThanToken, body, currentSourceFile)) { + singleLine = true; + } + else { + multiLine = true; + } + } + var expression = ts.visitNode(body, visitor, ts.isExpression); + var returnStatement = ts.createReturn(expression); + ts.setTextRange(returnStatement, body); + ts.moveSyntheticComments(returnStatement, body); + ts.setEmitFlags(returnStatement, 384 /* NoTokenSourceMaps */ | 32 /* NoTrailingSourceMap */ | 1024 /* NoTrailingComments */); + statements.push(returnStatement); + // To align with the source map emit for the old emitter, we set a custom + // source map location for the close brace. + closeBraceLocation = body; + } + var lexicalEnvironment = context.endLexicalEnvironment(); + ts.addStatementsAfterPrologue(statements, lexicalEnvironment); + prependCaptureNewTargetIfNeeded(statements, node, /*copyOnWrite*/ false); + // If we added any final generated statements, this must be a multi-line block + if (ts.some(leadingStatements) || ts.some(lexicalEnvironment)) { + multiLine = true; + } + var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(leadingStatements.concat(statements)), statementsLocation), multiLine); + ts.setTextRange(block, node.body); + if (!multiLine && singleLine) { + ts.setEmitFlags(block, 1 /* SingleLine */); + } + if (closeBraceLocation) { + ts.setTokenSourceMapRange(block, 19 /* CloseBraceToken */, closeBraceLocation); + } + ts.setOriginalNode(block, node.body); + return block; + } + function visitFunctionBodyDownLevel(node) { + var updated = ts.visitFunctionBody(node.body, functionBodyVisitor, context); + return ts.updateBlock(updated, ts.setTextRange(ts.createNodeArray(prependCaptureNewTargetIfNeeded(updated.statements, node, /*copyOnWrite*/ true)), + /*location*/ updated.statements)); + } + function visitBlock(node, isFunctionBody) { + if (isFunctionBody) { + // A function body is not a block scope. + return ts.visitEachChild(node, visitor, context); + } + var ancestorFacts = hierarchyFacts & 256 /* IterationStatement */ + ? enterSubtree(4032 /* IterationStatementBlockExcludes */, 512 /* IterationStatementBlockIncludes */) + : enterSubtree(3904 /* BlockExcludes */, 128 /* BlockIncludes */); + var updated = ts.visitEachChild(node, visitor, context); + exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */); + return updated; + } + /** + * Visits an ExpressionStatement that contains a destructuring assignment. + * + * @param node An ExpressionStatement node. + */ + function visitExpressionStatement(node) { + // If we are here it is most likely because our expression is a destructuring assignment. + switch (node.expression.kind) { + case 195 /* ParenthesizedExpression */: + return ts.updateExpressionStatement(node, visitParenthesizedExpression(node.expression, /*needsDestructuringValue*/ false)); + case 204 /* BinaryExpression */: + return ts.updateExpressionStatement(node, visitBinaryExpression(node.expression, /*needsDestructuringValue*/ false)); + } + return ts.visitEachChild(node, visitor, context); + } + /** + * Visits a ParenthesizedExpression that may contain a destructuring assignment. + * + * @param node A ParenthesizedExpression node. + * @param needsDestructuringValue A value indicating whether we need to hold onto the rhs + * of a destructuring assignment. + */ + function visitParenthesizedExpression(node, needsDestructuringValue) { + // If we are here it is most likely because our expression is a destructuring assignment. + if (!needsDestructuringValue) { + // By default we always emit the RHS at the end of a flattened destructuring + // expression. If we are in a state where we do not need the destructuring value, + // we pass that information along to the children that care about it. + switch (node.expression.kind) { + case 195 /* ParenthesizedExpression */: + return ts.updateParen(node, visitParenthesizedExpression(node.expression, /*needsDestructuringValue*/ false)); + case 204 /* BinaryExpression */: + return ts.updateParen(node, visitBinaryExpression(node.expression, /*needsDestructuringValue*/ false)); + } + } + return ts.visitEachChild(node, visitor, context); + } + /** + * Visits a BinaryExpression that contains a destructuring assignment. + * + * @param node A BinaryExpression node. + * @param needsDestructuringValue A value indicating whether we need to hold onto the rhs + * of a destructuring assignment. + */ + function visitBinaryExpression(node, needsDestructuringValue) { + // If we are here it is because this is a destructuring assignment. + if (ts.isDestructuringAssignment(node)) { + return ts.flattenDestructuringAssignment(node, visitor, context, 0 /* All */, needsDestructuringValue); + } + return ts.visitEachChild(node, visitor, context); + } + function visitVariableStatement(node) { + var ancestorFacts = enterSubtree(0 /* None */, ts.hasModifier(node, 1 /* Export */) ? 32 /* ExportedVariableStatement */ : 0 /* None */); + var updated; + if (convertedLoopState && (node.declarationList.flags & 3 /* BlockScoped */) === 0) { + // we are inside a converted loop - hoist variable declarations + var assignments = void 0; + for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + hoistVariableDeclarationDeclaredInConvertedLoop(convertedLoopState, decl); + if (decl.initializer) { + var assignment = void 0; + if (ts.isBindingPattern(decl.name)) { + assignment = ts.flattenDestructuringAssignment(decl, visitor, context, 0 /* All */); + } + else { + assignment = ts.createBinary(decl.name, 59 /* EqualsToken */, ts.visitNode(decl.initializer, visitor, ts.isExpression)); + ts.setTextRange(assignment, decl); + } + assignments = ts.append(assignments, assignment); + } + } + if (assignments) { + updated = ts.setTextRange(ts.createExpressionStatement(ts.inlineExpressions(assignments)), node); + } + else { + // none of declarations has initializer - the entire variable statement can be deleted + updated = undefined; + } + } + else { + updated = ts.visitEachChild(node, visitor, context); + } + exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */); + return updated; + } + /** + * Visits a VariableDeclarationList that is block scoped (e.g. `let` or `const`). + * + * @param node A VariableDeclarationList node. + */ + function visitVariableDeclarationList(node) { + if (node.transformFlags & 64 /* ES2015 */) { + if (node.flags & 3 /* BlockScoped */) { + enableSubstitutionsForBlockScopedBindings(); + } + var declarations = ts.flatMap(node.declarations, node.flags & 1 /* Let */ + ? visitVariableDeclarationInLetDeclarationList + : visitVariableDeclaration); + var declarationList = ts.createVariableDeclarationList(declarations); + ts.setOriginalNode(declarationList, node); + ts.setTextRange(declarationList, node); + ts.setCommentRange(declarationList, node); + // If the first or last declaration is a binding pattern, we need to modify + // the source map range for the declaration list. + if (node.transformFlags & 2097152 /* ContainsBindingPattern */ + && (ts.isBindingPattern(node.declarations[0].name) || ts.isBindingPattern(ts.last(node.declarations).name))) { + ts.setSourceMapRange(declarationList, getRangeUnion(declarations)); + } + return declarationList; + } + return ts.visitEachChild(node, visitor, context); + } + function getRangeUnion(declarations) { + // declarations may not be sorted by position. + // pos should be the minimum* position over all nodes (that's not -1), end should be the maximum end over all nodes. + var pos = -1, end = -1; + for (var _i = 0, declarations_10 = declarations; _i < declarations_10.length; _i++) { + var node = declarations_10[_i]; + pos = pos === -1 ? node.pos : node.pos === -1 ? pos : Math.min(pos, node.pos); + end = Math.max(end, node.end); + } + return ts.createRange(pos, end); + } + /** + * Gets a value indicating whether we should emit an explicit initializer for a variable + * declaration in a `let` declaration list. + * + * @param node A VariableDeclaration node. + */ + function shouldEmitExplicitInitializerForLetDeclaration(node) { + // Nested let bindings might need to be initialized explicitly to preserve + // ES6 semantic: + // + // { let x = 1; } + // { let x; } // x here should be undefined. not 1 + // + // Top level bindings never collide with anything and thus don't require + // explicit initialization. As for nested let bindings there are two cases: + // + // - Nested let bindings that were not renamed definitely should be + // initialized explicitly: + // + // { let x = 1; } + // { let x; if (some-condition) { x = 1}; if (x) { /*1*/ } } + // + // Without explicit initialization code in /*1*/ can be executed even if + // some-condition is evaluated to false. + // + // - Renaming introduces fresh name that should not collide with any + // existing names, however renamed bindings sometimes also should be + // explicitly initialized. One particular case: non-captured binding + // declared inside loop body (but not in loop initializer): + // + // let x; + // for (;;) { + // let x; + // } + // + // In downlevel codegen inner 'x' will be renamed so it won't collide + // with outer 'x' however it will should be reset on every iteration as + // if it was declared anew. + // + // * Why non-captured binding? + // - Because if loop contains block scoped binding captured in some + // function then loop body will be rewritten to have a fresh scope + // on every iteration so everything will just work. + // + // * Why loop initializer is excluded? + // - Since we've introduced a fresh name it already will be undefined. + var flags = resolver.getNodeCheckFlags(node); + var isCapturedInFunction = flags & 262144 /* CapturedBlockScopedBinding */; + var isDeclaredInLoop = flags & 524288 /* BlockScopedBindingInLoop */; + var emittedAsTopLevel = (hierarchyFacts & 64 /* TopLevel */) !== 0 + || (isCapturedInFunction + && isDeclaredInLoop + && (hierarchyFacts & 512 /* IterationStatementBlock */) !== 0); + var emitExplicitInitializer = !emittedAsTopLevel + && (hierarchyFacts & 2048 /* ForInOrForOfStatement */) === 0 + && (!resolver.isDeclarationWithCollidingName(node) + || (isDeclaredInLoop + && !isCapturedInFunction + && (hierarchyFacts & (1024 /* ForStatement */ | 2048 /* ForInOrForOfStatement */)) === 0)); + return emitExplicitInitializer; + } + /** + * Visits a VariableDeclaration in a `let` declaration list. + * + * @param node A VariableDeclaration node. + */ + function visitVariableDeclarationInLetDeclarationList(node) { + // For binding pattern names that lack initializers there is no point to emit + // explicit initializer since downlevel codegen for destructuring will fail + // in the absence of initializer so all binding elements will say uninitialized + var name = node.name; + if (ts.isBindingPattern(name)) { + return visitVariableDeclaration(node); + } + if (!node.initializer && shouldEmitExplicitInitializerForLetDeclaration(node)) { + var clone_2 = ts.getMutableClone(node); + clone_2.initializer = ts.createVoidZero(); + return clone_2; + } + return ts.visitEachChild(node, visitor, context); + } + /** + * Visits a VariableDeclaration node with a binding pattern. + * + * @param node A VariableDeclaration node. + */ + function visitVariableDeclaration(node) { + var ancestorFacts = enterSubtree(32 /* ExportedVariableStatement */, 0 /* None */); + var updated; + if (ts.isBindingPattern(node.name)) { + updated = ts.flattenDestructuringBinding(node, visitor, context, 0 /* All */, + /*value*/ undefined, (ancestorFacts & 32 /* ExportedVariableStatement */) !== 0); + } + else { + updated = ts.visitEachChild(node, visitor, context); + } + exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */); + return updated; + } + function recordLabel(node) { + convertedLoopState.labels.set(ts.idText(node.label), true); + } + function resetLabel(node) { + convertedLoopState.labels.set(ts.idText(node.label), false); + } + function visitLabeledStatement(node) { + if (convertedLoopState && !convertedLoopState.labels) { + convertedLoopState.labels = ts.createMap(); + } + var statement = ts.unwrapInnermostStatementOfLabel(node, convertedLoopState && recordLabel); + return ts.isIterationStatement(statement, /*lookInLabeledStatements*/ false) + ? visitIterationStatement(statement, /*outermostLabeledStatement*/ node) + : ts.restoreEnclosingLabel(ts.visitNode(statement, visitor, ts.isStatement, ts.liftToBlock), node, convertedLoopState && resetLabel); + } + function visitIterationStatement(node, outermostLabeledStatement) { + switch (node.kind) { + case 223 /* DoStatement */: + case 224 /* WhileStatement */: + return visitDoOrWhileStatement(node, outermostLabeledStatement); + case 225 /* ForStatement */: + return visitForStatement(node, outermostLabeledStatement); + case 226 /* ForInStatement */: + return visitForInStatement(node, outermostLabeledStatement); + case 227 /* ForOfStatement */: + return visitForOfStatement(node, outermostLabeledStatement); + } + } + function visitIterationStatementWithFacts(excludeFacts, includeFacts, node, outermostLabeledStatement, convert) { + var ancestorFacts = enterSubtree(excludeFacts, includeFacts); + var updated = convertIterationStatementBodyIfNecessary(node, outermostLabeledStatement, convert); + exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */); + return updated; + } + function visitDoOrWhileStatement(node, outermostLabeledStatement) { + return visitIterationStatementWithFacts(0 /* DoOrWhileStatementExcludes */, 256 /* DoOrWhileStatementIncludes */, node, outermostLabeledStatement); + } + function visitForStatement(node, outermostLabeledStatement) { + return visitIterationStatementWithFacts(3008 /* ForStatementExcludes */, 1280 /* ForStatementIncludes */, node, outermostLabeledStatement); + } + function visitForInStatement(node, outermostLabeledStatement) { + return visitIterationStatementWithFacts(1984 /* ForInOrForOfStatementExcludes */, 2304 /* ForInOrForOfStatementIncludes */, node, outermostLabeledStatement); + } + function visitForOfStatement(node, outermostLabeledStatement) { + return visitIterationStatementWithFacts(1984 /* ForInOrForOfStatementExcludes */, 2304 /* ForInOrForOfStatementIncludes */, node, outermostLabeledStatement, compilerOptions.downlevelIteration ? convertForOfStatementForIterable : convertForOfStatementForArray); + } + function convertForOfStatementHead(node, boundValue, convertedLoopBodyStatements) { + var statements = []; + var initializer = node.initializer; + if (ts.isVariableDeclarationList(initializer)) { + if (node.initializer.flags & 3 /* BlockScoped */) { + enableSubstitutionsForBlockScopedBindings(); + } + var firstOriginalDeclaration = ts.firstOrUndefined(initializer.declarations); + if (firstOriginalDeclaration && ts.isBindingPattern(firstOriginalDeclaration.name)) { + // This works whether the declaration is a var, let, or const. + // It will use rhsIterationValue _a[_i] as the initializer. + var declarations = ts.flattenDestructuringBinding(firstOriginalDeclaration, visitor, context, 0 /* All */, boundValue); + var declarationList = ts.setTextRange(ts.createVariableDeclarationList(declarations), node.initializer); + ts.setOriginalNode(declarationList, node.initializer); + // Adjust the source map range for the first declaration to align with the old + // emitter. + ts.setSourceMapRange(declarationList, ts.createRange(declarations[0].pos, ts.last(declarations).end)); + statements.push(ts.createVariableStatement( + /*modifiers*/ undefined, declarationList)); + } + else { + // The following call does not include the initializer, so we have + // to emit it separately. + statements.push(ts.setTextRange(ts.createVariableStatement( + /*modifiers*/ undefined, ts.setOriginalNode(ts.setTextRange(ts.createVariableDeclarationList([ + ts.createVariableDeclaration(firstOriginalDeclaration ? firstOriginalDeclaration.name : ts.createTempVariable(/*recordTempVariable*/ undefined), + /*type*/ undefined, boundValue) + ]), ts.moveRangePos(initializer, -1)), initializer)), ts.moveRangeEnd(initializer, -1))); + } + } + else { + // Initializer is an expression. Emit the expression in the body, so that it's + // evaluated on every iteration. + var assignment = ts.createAssignment(initializer, boundValue); + if (ts.isDestructuringAssignment(assignment)) { + ts.aggregateTransformFlags(assignment); + statements.push(ts.createExpressionStatement(visitBinaryExpression(assignment, /*needsDestructuringValue*/ false))); + } + else { + assignment.end = initializer.end; + statements.push(ts.setTextRange(ts.createExpressionStatement(ts.visitNode(assignment, visitor, ts.isExpression)), ts.moveRangeEnd(initializer, -1))); + } + } + if (convertedLoopBodyStatements) { + return createSyntheticBlockForConvertedStatements(ts.addRange(statements, convertedLoopBodyStatements)); + } + else { + var statement = ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock); + if (ts.isBlock(statement)) { + return ts.updateBlock(statement, ts.setTextRange(ts.createNodeArray(ts.concatenate(statements, statement.statements)), statement.statements)); + } + else { + statements.push(statement); + return createSyntheticBlockForConvertedStatements(statements); + } + } + } + function createSyntheticBlockForConvertedStatements(statements) { + return ts.setEmitFlags(ts.createBlock(ts.createNodeArray(statements), + /*multiLine*/ true), 48 /* NoSourceMap */ | 384 /* NoTokenSourceMaps */); + } + function convertForOfStatementForArray(node, outermostLabeledStatement, convertedLoopBodyStatements) { + // The following ES6 code: + // + // for (let v of expr) { } + // + // should be emitted as + // + // for (var _i = 0, _a = expr; _i < _a.length; _i++) { + // var v = _a[_i]; + // } + // + // where _a and _i are temps emitted to capture the RHS and the counter, + // respectively. + // When the left hand side is an expression instead of a let declaration, + // the "let v" is not emitted. + // When the left hand side is a let/const, the v is renamed if there is + // another v in scope. + // Note that all assignments to the LHS are emitted in the body, including + // all destructuring. + // Note also that because an extra statement is needed to assign to the LHS, + // for-of bodies are always emitted as blocks. + var expression = ts.visitNode(node.expression, visitor, ts.isExpression); + // In the case where the user wrote an identifier as the RHS, like this: + // + // for (let v of arr) { } + // + // we don't want to emit a temporary variable for the RHS, just use it directly. + var counter = ts.createLoopVariable(); + var rhsReference = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(expression) : ts.createTempVariable(/*recordTempVariable*/ undefined); + // The old emitter does not emit source maps for the expression + ts.setEmitFlags(expression, 48 /* NoSourceMap */ | ts.getEmitFlags(expression)); + var forStatement = ts.setTextRange(ts.createFor( + /*initializer*/ ts.setEmitFlags(ts.setTextRange(ts.createVariableDeclarationList([ + ts.setTextRange(ts.createVariableDeclaration(counter, /*type*/ undefined, ts.createLiteral(0)), ts.moveRangePos(node.expression, -1)), + ts.setTextRange(ts.createVariableDeclaration(rhsReference, /*type*/ undefined, expression), node.expression) + ]), node.expression), 2097152 /* NoHoisting */), + /*condition*/ ts.setTextRange(ts.createLessThan(counter, ts.createPropertyAccess(rhsReference, "length")), node.expression), + /*incrementor*/ ts.setTextRange(ts.createPostfixIncrement(counter), node.expression), + /*statement*/ convertForOfStatementHead(node, ts.createElementAccess(rhsReference, counter), convertedLoopBodyStatements)), + /*location*/ node); + // Disable trailing source maps for the OpenParenToken to align source map emit with the old emitter. + ts.setEmitFlags(forStatement, 256 /* NoTokenTrailingSourceMaps */); + ts.setTextRange(forStatement, node); + return ts.restoreEnclosingLabel(forStatement, outermostLabeledStatement, convertedLoopState && resetLabel); + } + function convertForOfStatementForIterable(node, outermostLabeledStatement, convertedLoopBodyStatements) { + var expression = ts.visitNode(node.expression, visitor, ts.isExpression); + var iterator = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(expression) : ts.createTempVariable(/*recordTempVariable*/ undefined); + var result = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(iterator) : ts.createTempVariable(/*recordTempVariable*/ undefined); + var errorRecord = ts.createUniqueName("e"); + var catchVariable = ts.getGeneratedNameForNode(errorRecord); + var returnMethod = ts.createTempVariable(/*recordTempVariable*/ undefined); + var values = ts.createValuesHelper(context, expression, node.expression); + var next = ts.createCall(ts.createPropertyAccess(iterator, "next"), /*typeArguments*/ undefined, []); + hoistVariableDeclaration(errorRecord); + hoistVariableDeclaration(returnMethod); + var forStatement = ts.setEmitFlags(ts.setTextRange(ts.createFor( + /*initializer*/ ts.setEmitFlags(ts.setTextRange(ts.createVariableDeclarationList([ + ts.setTextRange(ts.createVariableDeclaration(iterator, /*type*/ undefined, values), node.expression), + ts.createVariableDeclaration(result, /*type*/ undefined, next) + ]), node.expression), 2097152 /* NoHoisting */), + /*condition*/ ts.createLogicalNot(ts.createPropertyAccess(result, "done")), + /*incrementor*/ ts.createAssignment(result, next), + /*statement*/ convertForOfStatementHead(node, ts.createPropertyAccess(result, "value"), convertedLoopBodyStatements)), + /*location*/ node), 256 /* NoTokenTrailingSourceMaps */); + return ts.createTry(ts.createBlock([ + ts.restoreEnclosingLabel(forStatement, outermostLabeledStatement, convertedLoopState && resetLabel) + ]), ts.createCatchClause(ts.createVariableDeclaration(catchVariable), ts.setEmitFlags(ts.createBlock([ + ts.createExpressionStatement(ts.createAssignment(errorRecord, ts.createObjectLiteral([ + ts.createPropertyAssignment("error", catchVariable) + ]))) + ]), 1 /* SingleLine */)), ts.createBlock([ + ts.createTry( + /*tryBlock*/ ts.createBlock([ + ts.setEmitFlags(ts.createIf(ts.createLogicalAnd(ts.createLogicalAnd(result, ts.createLogicalNot(ts.createPropertyAccess(result, "done"))), ts.createAssignment(returnMethod, ts.createPropertyAccess(iterator, "return"))), ts.createExpressionStatement(ts.createFunctionCall(returnMethod, iterator, []))), 1 /* SingleLine */), + ]), + /*catchClause*/ undefined, + /*finallyBlock*/ ts.setEmitFlags(ts.createBlock([ + ts.setEmitFlags(ts.createIf(errorRecord, ts.createThrow(ts.createPropertyAccess(errorRecord, "error"))), 1 /* SingleLine */) + ]), 1 /* SingleLine */)) + ])); + } + /** + * Visits an ObjectLiteralExpression with computed property names. + * + * @param node An ObjectLiteralExpression node. + */ + function visitObjectLiteralExpression(node) { + // We are here because a ComputedPropertyName was used somewhere in the expression. + var properties = node.properties; + var numProperties = properties.length; + // Find the first computed property. + // Everything until that point can be emitted as part of the initial object literal. + var numInitialProperties = numProperties; + var numInitialPropertiesWithoutYield = numProperties; + for (var i = 0; i < numProperties; i++) { + var property = properties[i]; + if ((property.transformFlags & 4194304 /* ContainsYield */ && hierarchyFacts & 4 /* AsyncFunctionBody */) + && i < numInitialPropertiesWithoutYield) { + numInitialPropertiesWithoutYield = i; + } + if (property.name.kind === 149 /* ComputedPropertyName */) { + numInitialProperties = i; + break; + } + } + if (numInitialProperties !== numProperties) { + if (numInitialPropertiesWithoutYield < numInitialProperties) { + numInitialProperties = numInitialPropertiesWithoutYield; + } + // For computed properties, we need to create a unique handle to the object + // literal so we can modify it without risking internal assignments tainting the object. + var temp = ts.createTempVariable(hoistVariableDeclaration); + // Write out the first non-computed properties, then emit the rest through indexing on the temp variable. + var expressions = []; + var assignment = ts.createAssignment(temp, ts.setEmitFlags(ts.createObjectLiteral(ts.visitNodes(properties, visitor, ts.isObjectLiteralElementLike, 0, numInitialProperties), node.multiLine), 65536 /* Indented */)); + if (node.multiLine) { + ts.startOnNewLine(assignment); + } + expressions.push(assignment); + addObjectLiteralMembers(expressions, node, temp, numInitialProperties); + // We need to clone the temporary identifier so that we can write it on a + // new line + expressions.push(node.multiLine ? ts.startOnNewLine(ts.getMutableClone(temp)) : temp); + return ts.inlineExpressions(expressions); + } + return ts.visitEachChild(node, visitor, context); + } + function shouldConvertPartOfIterationStatement(node) { + return (resolver.getNodeCheckFlags(node) & 131072 /* ContainsCapturedBlockScopeBinding */) !== 0; + } + function shouldConvertInitializerOfForStatement(node) { + return ts.isForStatement(node) && !!node.initializer && shouldConvertPartOfIterationStatement(node.initializer); + } + function shouldConvertConditionOfForStatement(node) { + return ts.isForStatement(node) && !!node.condition && shouldConvertPartOfIterationStatement(node.condition); + } + function shouldConvertIncrementorOfForStatement(node) { + return ts.isForStatement(node) && !!node.incrementor && shouldConvertPartOfIterationStatement(node.incrementor); + } + function shouldConvertIterationStatement(node) { + return shouldConvertBodyOfIterationStatement(node) + || shouldConvertInitializerOfForStatement(node); + } + function shouldConvertBodyOfIterationStatement(node) { + return (resolver.getNodeCheckFlags(node) & 65536 /* LoopWithCapturedBlockScopedBinding */) !== 0; + } + /** + * Records constituents of name for the given variable to be hoisted in the outer scope. + */ + function hoistVariableDeclarationDeclaredInConvertedLoop(state, node) { + if (!state.hoistedLocalVariables) { + state.hoistedLocalVariables = []; + } + visit(node.name); + function visit(node) { + if (node.kind === 72 /* Identifier */) { + state.hoistedLocalVariables.push(node); + } + else { + for (var _i = 0, _a = node.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (!ts.isOmittedExpression(element)) { + visit(element.name); + } + } + } + } + } + function convertIterationStatementBodyIfNecessary(node, outermostLabeledStatement, convert) { + if (!shouldConvertIterationStatement(node)) { + var saveAllowedNonLabeledJumps = void 0; + if (convertedLoopState) { + // we get here if we are trying to emit normal loop loop inside converted loop + // set allowedNonLabeledJumps to Break | Continue to mark that break\continue inside the loop should be emitted as is + saveAllowedNonLabeledJumps = convertedLoopState.allowedNonLabeledJumps; + convertedLoopState.allowedNonLabeledJumps = 2 /* Break */ | 4 /* Continue */; + } + var result = convert + ? convert(node, outermostLabeledStatement, /*convertedLoopBodyStatements*/ undefined) + : ts.restoreEnclosingLabel(ts.visitEachChild(node, visitor, context), outermostLabeledStatement, convertedLoopState && resetLabel); + if (convertedLoopState) { + convertedLoopState.allowedNonLabeledJumps = saveAllowedNonLabeledJumps; + } + return result; + } + var currentState = createConvertedLoopState(node); + var statements = []; + var outerConvertedLoopState = convertedLoopState; + convertedLoopState = currentState; + var initializerFunction = shouldConvertInitializerOfForStatement(node) ? createFunctionForInitializerOfForStatement(node, currentState) : undefined; + var bodyFunction = shouldConvertBodyOfIterationStatement(node) ? createFunctionForBodyOfIterationStatement(node, currentState, outerConvertedLoopState) : undefined; + convertedLoopState = outerConvertedLoopState; + if (initializerFunction) + statements.push(initializerFunction.functionDeclaration); + if (bodyFunction) + statements.push(bodyFunction.functionDeclaration); + addExtraDeclarationsForConvertedLoop(statements, currentState, outerConvertedLoopState); + if (initializerFunction) { + statements.push(generateCallToConvertedLoopInitializer(initializerFunction.functionName, initializerFunction.containsYield)); + } + var loop; + if (bodyFunction) { + if (convert) { + loop = convert(node, outermostLabeledStatement, bodyFunction.part); + } + else { + var clone_3 = convertIterationStatementCore(node, initializerFunction, ts.createBlock(bodyFunction.part, /*multiLine*/ true)); + ts.aggregateTransformFlags(clone_3); + loop = ts.restoreEnclosingLabel(clone_3, outermostLabeledStatement, convertedLoopState && resetLabel); + } + } + else { + var clone_4 = convertIterationStatementCore(node, initializerFunction, ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); + ts.aggregateTransformFlags(clone_4); + loop = ts.restoreEnclosingLabel(clone_4, outermostLabeledStatement, convertedLoopState && resetLabel); + } + statements.push(loop); + return statements; + } + function convertIterationStatementCore(node, initializerFunction, convertedLoopBody) { + switch (node.kind) { + case 225 /* ForStatement */: return convertForStatement(node, initializerFunction, convertedLoopBody); + case 226 /* ForInStatement */: return convertForInStatement(node, convertedLoopBody); + case 227 /* ForOfStatement */: return convertForOfStatement(node, convertedLoopBody); + case 223 /* DoStatement */: return convertDoStatement(node, convertedLoopBody); + case 224 /* WhileStatement */: return convertWhileStatement(node, convertedLoopBody); + default: return ts.Debug.failBadSyntaxKind(node, "IterationStatement expected"); + } + } + function convertForStatement(node, initializerFunction, convertedLoopBody) { + var shouldConvertCondition = node.condition && shouldConvertPartOfIterationStatement(node.condition); + var shouldConvertIncrementor = shouldConvertCondition || node.incrementor && shouldConvertPartOfIterationStatement(node.incrementor); + return ts.updateFor(node, ts.visitNode(initializerFunction ? initializerFunction.part : node.initializer, visitor, ts.isForInitializer), ts.visitNode(shouldConvertCondition ? undefined : node.condition, visitor, ts.isExpression), ts.visitNode(shouldConvertIncrementor ? undefined : node.incrementor, visitor, ts.isExpression), convertedLoopBody); + } + function convertForOfStatement(node, convertedLoopBody) { + return ts.updateForOf(node, + /*awaitModifier*/ undefined, ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), convertedLoopBody); + } + function convertForInStatement(node, convertedLoopBody) { + return ts.updateForIn(node, ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), convertedLoopBody); + } + function convertDoStatement(node, convertedLoopBody) { + return ts.updateDo(node, convertedLoopBody, ts.visitNode(node.expression, visitor, ts.isExpression)); + } + function convertWhileStatement(node, convertedLoopBody) { + return ts.updateWhile(node, ts.visitNode(node.expression, visitor, ts.isExpression), convertedLoopBody); + } + function createConvertedLoopState(node) { + var loopInitializer; + switch (node.kind) { + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + var initializer = node.initializer; + if (initializer && initializer.kind === 238 /* VariableDeclarationList */) { + loopInitializer = initializer; + } + break; + } + // variables that will be passed to the loop as parameters + var loopParameters = []; + // variables declared in the loop initializer that will be changed inside the loop + var loopOutParameters = []; + if (loopInitializer && (ts.getCombinedNodeFlags(loopInitializer) & 3 /* BlockScoped */)) { + var hasCapturedBindingsInForInitializer = shouldConvertInitializerOfForStatement(node); + for (var _i = 0, _a = loopInitializer.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + processLoopVariableDeclaration(node, decl, loopParameters, loopOutParameters, hasCapturedBindingsInForInitializer); + } + } + var currentState = { loopParameters: loopParameters, loopOutParameters: loopOutParameters }; + if (convertedLoopState) { + // convertedOuterLoopState !== undefined means that this converted loop is nested in another converted loop. + // if outer converted loop has already accumulated some state - pass it through + if (convertedLoopState.argumentsName) { + // outer loop has already used 'arguments' so we've already have some name to alias it + // use the same name in all nested loops + currentState.argumentsName = convertedLoopState.argumentsName; + } + if (convertedLoopState.thisName) { + // outer loop has already used 'this' so we've already have some name to alias it + // use the same name in all nested loops + currentState.thisName = convertedLoopState.thisName; + } + if (convertedLoopState.hoistedLocalVariables) { + // we've already collected some non-block scoped variable declarations in enclosing loop + // use the same storage in nested loop + currentState.hoistedLocalVariables = convertedLoopState.hoistedLocalVariables; + } + } + return currentState; + } + function addExtraDeclarationsForConvertedLoop(statements, state, outerState) { + var extraVariableDeclarations; + // propagate state from the inner loop to the outer loop if necessary + if (state.argumentsName) { + // if alias for arguments is set + if (outerState) { + // pass it to outer converted loop + outerState.argumentsName = state.argumentsName; + } + else { + // this is top level converted loop and we need to create an alias for 'arguments' object + (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(state.argumentsName, + /*type*/ undefined, ts.createIdentifier("arguments"))); + } + } + if (state.thisName) { + // if alias for this is set + if (outerState) { + // pass it to outer converted loop + outerState.thisName = state.thisName; + } + else { + // this is top level converted loop so we need to create an alias for 'this' here + // NOTE: + // if converted loops were all nested in arrow function then we'll always emit '_this' so convertedLoopState.thisName will not be set. + // If it is set this means that all nested loops are not nested in arrow function and it is safe to capture 'this'. + (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(state.thisName, + /*type*/ undefined, ts.createIdentifier("this"))); + } + } + if (state.hoistedLocalVariables) { + // if hoistedLocalVariables !== undefined this means that we've possibly collected some variable declarations to be hoisted later + if (outerState) { + // pass them to outer converted loop + outerState.hoistedLocalVariables = state.hoistedLocalVariables; + } + else { + if (!extraVariableDeclarations) { + extraVariableDeclarations = []; + } + // hoist collected variable declarations + for (var _i = 0, _a = state.hoistedLocalVariables; _i < _a.length; _i++) { + var identifier = _a[_i]; + extraVariableDeclarations.push(ts.createVariableDeclaration(identifier)); + } + } + } + // add extra variables to hold out parameters if necessary + if (state.loopOutParameters.length) { + if (!extraVariableDeclarations) { + extraVariableDeclarations = []; + } + for (var _b = 0, _c = state.loopOutParameters; _b < _c.length; _b++) { + var outParam = _c[_b]; + extraVariableDeclarations.push(ts.createVariableDeclaration(outParam.outParamName)); + } + } + if (state.conditionVariable) { + if (!extraVariableDeclarations) { + extraVariableDeclarations = []; + } + extraVariableDeclarations.push(ts.createVariableDeclaration(state.conditionVariable, /*type*/ undefined, ts.createFalse())); + } + // create variable statement to hold all introduced variable declarations + if (extraVariableDeclarations) { + statements.push(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList(extraVariableDeclarations))); + } + } + function createOutVariable(p) { + return ts.createVariableDeclaration(p.originalName, /*type*/ undefined, p.outParamName); + } + /** + * Creates a `_loop_init` function for a `ForStatement` with a block-scoped initializer + * that is captured in a closure inside of the initializer. The `_loop_init` function is + * used to preserve the per-iteration environment semantics of + * [13.7.4.8 RS: ForBodyEvaluation](https://tc39.github.io/ecma262/#sec-forbodyevaluation). + */ + function createFunctionForInitializerOfForStatement(node, currentState) { + var functionName = ts.createUniqueName("_loop_init"); + var containsYield = (node.initializer.transformFlags & 4194304 /* ContainsYield */) !== 0; + var emitFlags = 0 /* None */; + if (currentState.containsLexicalThis) + emitFlags |= 8 /* CapturesThis */; + if (containsYield && hierarchyFacts & 4 /* AsyncFunctionBody */) + emitFlags |= 262144 /* AsyncFunctionBody */; + var statements = []; + statements.push(ts.createVariableStatement(/*modifiers*/ undefined, node.initializer)); + copyOutParameters(currentState.loopOutParameters, 2 /* Initializer */, 1 /* ToOutParameter */, statements); + // This transforms the following ES2015 syntax: + // + // for (let i = (setImmediate(() => console.log(i)), 0); i < 2; i++) { + // // loop body + // } + // + // Into the following ES5 syntax: + // + // var _loop_init_1 = function () { + // var i = (setImmediate(() => console.log(i)), 0); + // out_i_1 = i; + // }; + // var out_i_1; + // _loop_init_1(); + // for (var i = out_i_1; i < 2; i++) { + // // loop body + // } + // + // Which prevents mutations to `i` in the per-iteration environment of the body + // from affecting the initial value for `i` outside of the per-iteration environment. + var functionDeclaration = ts.createVariableStatement( + /*modifiers*/ undefined, ts.setEmitFlags(ts.createVariableDeclarationList([ + ts.createVariableDeclaration(functionName, + /*type*/ undefined, ts.setEmitFlags(ts.createFunctionExpression( + /*modifiers*/ undefined, containsYield ? ts.createToken(40 /* AsteriskToken */) : undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, + /*parameters*/ undefined, + /*type*/ undefined, ts.visitNode(ts.createBlock(statements, /*multiLine*/ true), visitor, ts.isBlock)), emitFlags)) + ]), 2097152 /* NoHoisting */)); + var part = ts.createVariableDeclarationList(ts.map(currentState.loopOutParameters, createOutVariable)); + return { functionName: functionName, containsYield: containsYield, functionDeclaration: functionDeclaration, part: part }; + } + /** + * Creates a `_loop` function for an `IterationStatement` with a block-scoped initializer + * that is captured in a closure inside of the loop body. The `_loop` function is used to + * preserve the per-iteration environment semantics of + * [13.7.4.8 RS: ForBodyEvaluation](https://tc39.github.io/ecma262/#sec-forbodyevaluation). + */ + function createFunctionForBodyOfIterationStatement(node, currentState, outerState) { + var functionName = ts.createUniqueName("_loop"); + startLexicalEnvironment(); + var statement = ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock); + var lexicalEnvironment = endLexicalEnvironment(); + var statements = []; + if (shouldConvertConditionOfForStatement(node) || shouldConvertIncrementorOfForStatement(node)) { + // If a block-scoped variable declared in the initializer of `node` is captured in + // the condition or incrementor, we must move the condition and incrementor into + // the body of the for loop. + // + // This transforms the following ES2015 syntax: + // + // for (let i = 0; setImmediate(() => console.log(i)), i < 2; setImmediate(() => console.log(i)), i++) { + // // loop body + // } + // + // Into the following ES5 syntax: + // + // var _loop_1 = function (i) { + // if (inc_1) + // setImmediate(() => console.log(i)), i++; + // else + // inc_1 = true; + // if (!(setImmediate(() => console.log(i)), i < 2)) + // return out_i_1 = i, "break"; + // // loop body + // out_i_1 = i; + // } + // var out_i_1, inc_1 = false; + // for (var i = 0;;) { + // var state_1 = _loop_1(i); + // i = out_i_1; + // if (state_1 === "break") + // break; + // } + // + // Which prevents mutations to `i` in the per-iteration environment of the body + // from affecting the value of `i` in the previous per-iteration environment. + // + // Note that the incrementor of a `for` loop is evaluated in a *new* per-iteration + // environment that is carried over to the next iteration of the loop. As a result, + // we must indicate whether this is the first evaluation of the loop body so that + // we only evaluate the incrementor on subsequent evaluations. + currentState.conditionVariable = ts.createUniqueName("inc"); + statements.push(ts.createIf(currentState.conditionVariable, ts.createStatement(ts.visitNode(node.incrementor, visitor, ts.isExpression)), ts.createStatement(ts.createAssignment(currentState.conditionVariable, ts.createTrue())))); + if (shouldConvertConditionOfForStatement(node)) { + statements.push(ts.createIf(ts.createPrefix(52 /* ExclamationToken */, ts.visitNode(node.condition, visitor, ts.isExpression)), ts.visitNode(ts.createBreak(), visitor, ts.isStatement))); + } + } + if (ts.isBlock(statement)) { + ts.addRange(statements, statement.statements); + } + else { + statements.push(statement); + } + copyOutParameters(currentState.loopOutParameters, 1 /* Body */, 1 /* ToOutParameter */, statements); + ts.addStatementsAfterPrologue(statements, lexicalEnvironment); + var loopBody = ts.createBlock(statements, /*multiLine*/ true); + if (ts.isBlock(statement)) + ts.setOriginalNode(loopBody, statement); + var containsYield = (node.statement.transformFlags & 4194304 /* ContainsYield */) !== 0; + var emitFlags = 0; + if (currentState.containsLexicalThis) + emitFlags |= 8 /* CapturesThis */; + if (containsYield && (hierarchyFacts & 4 /* AsyncFunctionBody */) !== 0) + emitFlags |= 262144 /* AsyncFunctionBody */; + // This transforms the following ES2015 syntax (in addition to other variations): + // + // for (let i = 0; i < 2; i++) { + // setImmediate(() => console.log(i)); + // } + // + // Into the following ES5 syntax: + // + // var _loop_1 = function (i) { + // setImmediate(() => console.log(i)); + // }; + // for (var i = 0; i < 2; i++) { + // _loop_1(i); + // } + var functionDeclaration = ts.createVariableStatement( + /*modifiers*/ undefined, ts.setEmitFlags(ts.createVariableDeclarationList([ + ts.createVariableDeclaration(functionName, + /*type*/ undefined, ts.setEmitFlags(ts.createFunctionExpression( + /*modifiers*/ undefined, containsYield ? ts.createToken(40 /* AsteriskToken */) : undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, currentState.loopParameters, + /*type*/ undefined, loopBody), emitFlags)) + ]), 2097152 /* NoHoisting */)); + var part = generateCallToConvertedLoop(functionName, currentState, outerState, containsYield); + return { functionName: functionName, containsYield: containsYield, functionDeclaration: functionDeclaration, part: part }; + } + function copyOutParameter(outParam, copyDirection) { + var source = copyDirection === 0 /* ToOriginal */ ? outParam.outParamName : outParam.originalName; + var target = copyDirection === 0 /* ToOriginal */ ? outParam.originalName : outParam.outParamName; + return ts.createBinary(target, 59 /* EqualsToken */, source); + } + function copyOutParameters(outParams, partFlags, copyDirection, statements) { + for (var _i = 0, outParams_1 = outParams; _i < outParams_1.length; _i++) { + var outParam = outParams_1[_i]; + if (outParam.flags & partFlags) { + statements.push(ts.createExpressionStatement(copyOutParameter(outParam, copyDirection))); + } + } + } + function generateCallToConvertedLoopInitializer(initFunctionExpressionName, containsYield) { + var call = ts.createCall(initFunctionExpressionName, /*typeArguments*/ undefined, []); + var callResult = containsYield + ? ts.createYield(ts.createToken(40 /* AsteriskToken */), ts.setEmitFlags(call, 8388608 /* Iterator */)) + : call; + return ts.createStatement(callResult); + } + function generateCallToConvertedLoop(loopFunctionExpressionName, state, outerState, containsYield) { + var statements = []; + // loop is considered simple if it does not have any return statements or break\continue that transfer control outside of the loop + // simple loops are emitted as just 'loop()'; + // NOTE: if loop uses only 'continue' it still will be emitted as simple loop + var isSimpleLoop = !(state.nonLocalJumps & ~4 /* Continue */) && + !state.labeledNonLocalBreaks && + !state.labeledNonLocalContinues; + var call = ts.createCall(loopFunctionExpressionName, /*typeArguments*/ undefined, ts.map(state.loopParameters, function (p) { return p.name; })); + var callResult = containsYield + ? ts.createYield(ts.createToken(40 /* AsteriskToken */), ts.setEmitFlags(call, 8388608 /* Iterator */)) + : call; + if (isSimpleLoop) { + statements.push(ts.createExpressionStatement(callResult)); + copyOutParameters(state.loopOutParameters, 1 /* Body */, 0 /* ToOriginal */, statements); + } + else { + var loopResultName = ts.createUniqueName("state"); + var stateVariable = ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(loopResultName, /*type*/ undefined, callResult)])); + statements.push(stateVariable); + copyOutParameters(state.loopOutParameters, 1 /* Body */, 0 /* ToOriginal */, statements); + if (state.nonLocalJumps & 8 /* Return */) { + var returnStatement = void 0; + if (outerState) { + outerState.nonLocalJumps |= 8 /* Return */; + returnStatement = ts.createReturn(loopResultName); + } + else { + returnStatement = ts.createReturn(ts.createPropertyAccess(loopResultName, "value")); + } + statements.push(ts.createIf(ts.createBinary(ts.createTypeOf(loopResultName), 35 /* EqualsEqualsEqualsToken */, ts.createLiteral("object")), returnStatement)); + } + if (state.nonLocalJumps & 2 /* Break */) { + statements.push(ts.createIf(ts.createBinary(loopResultName, 35 /* EqualsEqualsEqualsToken */, ts.createLiteral("break")), ts.createBreak())); + } + if (state.labeledNonLocalBreaks || state.labeledNonLocalContinues) { + var caseClauses = []; + processLabeledJumps(state.labeledNonLocalBreaks, /*isBreak*/ true, loopResultName, outerState, caseClauses); + processLabeledJumps(state.labeledNonLocalContinues, /*isBreak*/ false, loopResultName, outerState, caseClauses); + statements.push(ts.createSwitch(loopResultName, ts.createCaseBlock(caseClauses))); + } + } + return statements; + } + function setLabeledJump(state, isBreak, labelText, labelMarker) { + if (isBreak) { + if (!state.labeledNonLocalBreaks) { + state.labeledNonLocalBreaks = ts.createMap(); + } + state.labeledNonLocalBreaks.set(labelText, labelMarker); + } + else { + if (!state.labeledNonLocalContinues) { + state.labeledNonLocalContinues = ts.createMap(); + } + state.labeledNonLocalContinues.set(labelText, labelMarker); + } + } + function processLabeledJumps(table, isBreak, loopResultName, outerLoop, caseClauses) { + if (!table) { + return; + } + table.forEach(function (labelMarker, labelText) { + var statements = []; + // if there are no outer converted loop or outer label in question is located inside outer converted loop + // then emit labeled break\continue + // otherwise propagate pair 'label -> marker' to outer converted loop and emit 'return labelMarker' so outer loop can later decide what to do + if (!outerLoop || (outerLoop.labels && outerLoop.labels.get(labelText))) { + var label = ts.createIdentifier(labelText); + statements.push(isBreak ? ts.createBreak(label) : ts.createContinue(label)); + } + else { + setLabeledJump(outerLoop, isBreak, labelText, labelMarker); + statements.push(ts.createReturn(loopResultName)); + } + caseClauses.push(ts.createCaseClause(ts.createLiteral(labelMarker), statements)); + }); + } + function processLoopVariableDeclaration(container, decl, loopParameters, loopOutParameters, hasCapturedBindingsInForInitializer) { + var name = decl.name; + if (ts.isBindingPattern(name)) { + for (var _i = 0, _a = name.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (!ts.isOmittedExpression(element)) { + processLoopVariableDeclaration(container, element, loopParameters, loopOutParameters, hasCapturedBindingsInForInitializer); + } + } + } + else { + loopParameters.push(ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, name)); + var checkFlags = resolver.getNodeCheckFlags(decl); + if (checkFlags & 4194304 /* NeedsLoopOutParameter */ || hasCapturedBindingsInForInitializer) { + var outParamName = ts.createUniqueName("out_" + ts.idText(name)); + var flags = 0; + if (checkFlags & 4194304 /* NeedsLoopOutParameter */) { + flags |= 1 /* Body */; + } + if (ts.isForStatement(container) && container.initializer && resolver.isBindingCapturedByNode(container.initializer, decl)) { + flags |= 2 /* Initializer */; + } + loopOutParameters.push({ flags: flags, originalName: name, outParamName: outParamName }); + } + } + } + /** + * Adds the members of an object literal to an array of expressions. + * + * @param expressions An array of expressions. + * @param node An ObjectLiteralExpression node. + * @param receiver The receiver for members of the ObjectLiteralExpression. + * @param numInitialNonComputedProperties The number of initial properties without + * computed property names. + */ + function addObjectLiteralMembers(expressions, node, receiver, start) { + var properties = node.properties; + var numProperties = properties.length; + for (var i = start; i < numProperties; i++) { + var property = properties[i]; + switch (property.kind) { + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + var accessors = ts.getAllAccessorDeclarations(node.properties, property); + if (property === accessors.firstAccessor) { + expressions.push(transformAccessorsToExpression(receiver, accessors, node, !!node.multiLine)); + } + break; + case 156 /* MethodDeclaration */: + expressions.push(transformObjectLiteralMethodDeclarationToExpression(property, receiver, node, node.multiLine)); + break; + case 275 /* PropertyAssignment */: + expressions.push(transformPropertyAssignmentToExpression(property, receiver, node.multiLine)); + break; + case 276 /* ShorthandPropertyAssignment */: + expressions.push(transformShorthandPropertyAssignmentToExpression(property, receiver, node.multiLine)); + break; + default: + ts.Debug.failBadSyntaxKind(node); + break; + } + } + } + /** + * Transforms a PropertyAssignment node into an expression. + * + * @param node The ObjectLiteralExpression that contains the PropertyAssignment. + * @param property The PropertyAssignment node. + * @param receiver The receiver for the assignment. + */ + function transformPropertyAssignmentToExpression(property, receiver, startsOnNewLine) { + var expression = ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(property.name, visitor, ts.isPropertyName)), ts.visitNode(property.initializer, visitor, ts.isExpression)); + ts.setTextRange(expression, property); + if (startsOnNewLine) { + ts.startOnNewLine(expression); + } + return expression; + } + /** + * Transforms a ShorthandPropertyAssignment node into an expression. + * + * @param node The ObjectLiteralExpression that contains the ShorthandPropertyAssignment. + * @param property The ShorthandPropertyAssignment node. + * @param receiver The receiver for the assignment. + */ + function transformShorthandPropertyAssignmentToExpression(property, receiver, startsOnNewLine) { + var expression = ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(property.name, visitor, ts.isPropertyName)), ts.getSynthesizedClone(property.name)); + ts.setTextRange(expression, property); + if (startsOnNewLine) { + ts.startOnNewLine(expression); + } + return expression; + } + /** + * Transforms a MethodDeclaration of an ObjectLiteralExpression into an expression. + * + * @param node The ObjectLiteralExpression that contains the MethodDeclaration. + * @param method The MethodDeclaration node. + * @param receiver The receiver for the assignment. + */ + function transformObjectLiteralMethodDeclarationToExpression(method, receiver, container, startsOnNewLine) { + var ancestorFacts = enterSubtree(0 /* None */, 0 /* None */); + var expression = ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(method.name, visitor, ts.isPropertyName)), transformFunctionLikeToExpression(method, /*location*/ method, /*name*/ undefined, container)); + ts.setTextRange(expression, method); + if (startsOnNewLine) { + ts.startOnNewLine(expression); + } + exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, hierarchyFacts & 49152 /* PropagateNewTargetMask */ ? 16384 /* NewTarget */ : 0 /* None */); + return expression; + } + function visitCatchClause(node) { + var ancestorFacts = enterSubtree(4032 /* BlockScopeExcludes */, 0 /* BlockScopeIncludes */); + var updated; + ts.Debug.assert(!!node.variableDeclaration, "Catch clause variable should always be present when downleveling ES2015."); + if (ts.isBindingPattern(node.variableDeclaration.name)) { + var temp = ts.createTempVariable(/*recordTempVariable*/ undefined); + var newVariableDeclaration = ts.createVariableDeclaration(temp); + ts.setTextRange(newVariableDeclaration, node.variableDeclaration); + var vars = ts.flattenDestructuringBinding(node.variableDeclaration, visitor, context, 0 /* All */, temp); + var list = ts.createVariableDeclarationList(vars); + ts.setTextRange(list, node.variableDeclaration); + var destructure = ts.createVariableStatement(/*modifiers*/ undefined, list); + updated = ts.updateCatchClause(node, newVariableDeclaration, addStatementToStartOfBlock(node.block, destructure)); + } + else { + updated = ts.visitEachChild(node, visitor, context); + } + exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */); + return updated; + } + function addStatementToStartOfBlock(block, statement) { + var transformedStatements = ts.visitNodes(block.statements, visitor, ts.isStatement); + return ts.updateBlock(block, [statement].concat(transformedStatements)); + } + /** + * Visits a MethodDeclaration of an ObjectLiteralExpression and transforms it into a + * PropertyAssignment. + * + * @param node A MethodDeclaration node. + */ + function visitMethodDeclaration(node) { + // We should only get here for methods on an object literal with regular identifier names. + // Methods on classes are handled in visitClassDeclaration/visitClassExpression. + // Methods with computed property names are handled in visitObjectLiteralExpression. + ts.Debug.assert(!ts.isComputedPropertyName(node.name)); + var functionExpression = transformFunctionLikeToExpression(node, /*location*/ ts.moveRangePos(node, -1), /*name*/ undefined, /*container*/ undefined); + ts.setEmitFlags(functionExpression, 512 /* NoLeadingComments */ | ts.getEmitFlags(functionExpression)); + return ts.setTextRange(ts.createPropertyAssignment(node.name, functionExpression), + /*location*/ node); + } + /** + * Visits an AccessorDeclaration of an ObjectLiteralExpression. + * + * @param node An AccessorDeclaration node. + */ + function visitAccessorDeclaration(node) { + ts.Debug.assert(!ts.isComputedPropertyName(node.name)); + var savedConvertedLoopState = convertedLoopState; + convertedLoopState = undefined; + var ancestorFacts = enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */); + var updated; + var parameters = ts.visitParameterList(node.parameters, visitor, context); + var body = node.transformFlags & (16384 /* ContainsCapturedLexicalThis */ | 128 /* ContainsES2015 */) + ? transformFunctionBody(node) + : visitFunctionBodyDownLevel(node); + if (node.kind === 158 /* GetAccessor */) { + updated = ts.updateGetAccessor(node, node.decorators, node.modifiers, node.name, parameters, node.type, body); + } + else { + updated = ts.updateSetAccessor(node, node.decorators, node.modifiers, node.name, parameters, body); + } + exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, 0 /* None */); + convertedLoopState = savedConvertedLoopState; + return updated; + } + /** + * Visits a ShorthandPropertyAssignment and transforms it into a PropertyAssignment. + * + * @param node A ShorthandPropertyAssignment node. + */ + function visitShorthandPropertyAssignment(node) { + return ts.setTextRange(ts.createPropertyAssignment(node.name, ts.getSynthesizedClone(node.name)), + /*location*/ node); + } + function visitComputedPropertyName(node) { + var ancestorFacts = enterSubtree(0 /* ComputedPropertyNameExcludes */, 8192 /* ComputedPropertyNameIncludes */); + var updated = ts.visitEachChild(node, visitor, context); + exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, hierarchyFacts & 49152 /* PropagateNewTargetMask */ ? 32768 /* NewTargetInComputedPropertyName */ : 0 /* None */); + return updated; + } + /** + * Visits a YieldExpression node. + * + * @param node A YieldExpression node. + */ + function visitYieldExpression(node) { + // `yield` expressions are transformed using the generators transformer. + return ts.visitEachChild(node, visitor, context); + } + /** + * Visits an ArrayLiteralExpression that contains a spread element. + * + * @param node An ArrayLiteralExpression node. + */ + function visitArrayLiteralExpression(node) { + if (node.transformFlags & 64 /* ES2015 */) { + // We are here because we contain a SpreadElementExpression. + return transformAndSpreadElements(node.elements, /*needsUniqueCopy*/ true, !!node.multiLine, /*hasTrailingComma*/ !!node.elements.hasTrailingComma); + } + return ts.visitEachChild(node, visitor, context); + } + /** + * Visits a CallExpression that contains either a spread element or `super`. + * + * @param node a CallExpression. + */ + function visitCallExpression(node) { + if (ts.getEmitFlags(node) & 33554432 /* TypeScriptClassWrapper */) { + return visitTypeScriptClassWrapper(node); + } + if (node.transformFlags & 64 /* ES2015 */) { + return visitCallExpressionWithPotentialCapturedThisAssignment(node, /*assignToCapturedThis*/ true); + } + return ts.updateCall(node, ts.visitNode(node.expression, callExpressionVisitor, ts.isExpression), + /*typeArguments*/ undefined, ts.visitNodes(node.arguments, visitor, ts.isExpression)); + } + function visitTypeScriptClassWrapper(node) { + // This is a call to a class wrapper function (an IIFE) created by the 'ts' transformer. + // The wrapper has a form similar to: + // + // (function() { + // class C { // 1 + // } + // C.x = 1; // 2 + // return C; + // }()) + // + // When we transform the class, we end up with something like this: + // + // (function () { + // var C = (function () { // 3 + // function C() { + // } + // return C; // 4 + // }()); + // C.x = 1; + // return C; + // }()) + // + // We want to simplify the two nested IIFEs to end up with something like this: + // + // (function () { + // function C() { + // } + // C.x = 1; + // return C; + // }()) + // We skip any outer expressions in a number of places to get to the innermost + // expression, but we will restore them later to preserve comments and source maps. + var body = ts.cast(ts.cast(ts.skipOuterExpressions(node.expression), ts.isArrowFunction).body, ts.isBlock); + // The class statements are the statements generated by visiting the first statement with initializer of the + // body (1), while all other statements are added to remainingStatements (2) + var isVariableStatementWithInitializer = function (stmt) { return ts.isVariableStatement(stmt) && !!ts.first(stmt.declarationList.declarations).initializer; }; + var bodyStatements = ts.visitNodes(body.statements, visitor, ts.isStatement); + var classStatements = ts.filter(bodyStatements, isVariableStatementWithInitializer); + var remainingStatements = ts.filter(bodyStatements, function (stmt) { return !isVariableStatementWithInitializer(stmt); }); + var varStatement = ts.cast(ts.first(classStatements), ts.isVariableStatement); + // We know there is only one variable declaration here as we verified this in an + // earlier call to isTypeScriptClassWrapper + var variable = varStatement.declarationList.declarations[0]; + var initializer = ts.skipOuterExpressions(variable.initializer); + // Under certain conditions, the 'ts' transformer may introduce a class alias, which + // we see as an assignment, for example: + // + // (function () { + // var C_1; + // var C = C_1 = (function () { + // function C() { + // } + // C.x = function () { return C_1; } + // return C; + // }()); + // C = C_1 = __decorate([dec], C); + // return C; + // }()) + // + var aliasAssignment = ts.tryCast(initializer, ts.isAssignmentExpression); + // The underlying call (3) is another IIFE that may contain a '_super' argument. + var call = ts.cast(aliasAssignment ? ts.skipOuterExpressions(aliasAssignment.right) : initializer, ts.isCallExpression); + var func = ts.cast(ts.skipOuterExpressions(call.expression), ts.isFunctionExpression); + var funcStatements = func.body.statements; + var classBodyStart = 0; + var classBodyEnd = -1; + var statements = []; + if (aliasAssignment) { + // If we have a class alias assignment, we need to move it to the down-level constructor + // function we generated for the class. + var extendsCall = ts.tryCast(funcStatements[classBodyStart], ts.isExpressionStatement); + if (extendsCall) { + statements.push(extendsCall); + classBodyStart++; + } + // The next statement is the function declaration. + statements.push(funcStatements[classBodyStart]); + classBodyStart++; + // Add the class alias following the declaration. + statements.push(ts.createExpressionStatement(ts.createAssignment(aliasAssignment.left, ts.cast(variable.name, ts.isIdentifier)))); + } + // Find the trailing 'return' statement (4) + while (!ts.isReturnStatement(ts.elementAt(funcStatements, classBodyEnd))) { + classBodyEnd--; + } + // When we extract the statements of the inner IIFE, we exclude the 'return' statement (4) + // as we already have one that has been introduced by the 'ts' transformer. + ts.addRange(statements, funcStatements, classBodyStart, classBodyEnd); + if (classBodyEnd < -1) { + // If there were any hoisted declarations following the return statement, we should + // append them. + ts.addRange(statements, funcStatements, classBodyEnd + 1); + } + // Add the remaining statements of the outer wrapper. + ts.addRange(statements, remainingStatements); + // The 'es2015' class transform may add an end-of-declaration marker. If so we will add it + // after the remaining statements from the 'ts' transformer. + ts.addRange(statements, classStatements, /*start*/ 1); + // Recreate any outer parentheses or partially-emitted expressions to preserve source map + // and comment locations. + return ts.recreateOuterExpressions(node.expression, ts.recreateOuterExpressions(variable.initializer, ts.recreateOuterExpressions(aliasAssignment && aliasAssignment.right, ts.updateCall(call, ts.recreateOuterExpressions(call.expression, ts.updateFunctionExpression(func, + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, func.parameters, + /*type*/ undefined, ts.updateBlock(func.body, statements))), + /*typeArguments*/ undefined, call.arguments)))); + } + function visitImmediateSuperCallInBody(node) { + return visitCallExpressionWithPotentialCapturedThisAssignment(node, /*assignToCapturedThis*/ false); + } + function visitCallExpressionWithPotentialCapturedThisAssignment(node, assignToCapturedThis) { + // We are here either because SuperKeyword was used somewhere in the expression, or + // because we contain a SpreadElementExpression. + if (node.transformFlags & 131072 /* ContainsRestOrSpread */ || + node.expression.kind === 98 /* SuperKeyword */ || + ts.isSuperProperty(ts.skipOuterExpressions(node.expression))) { + var _a = ts.createCallBinding(node.expression, hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg; + if (node.expression.kind === 98 /* SuperKeyword */) { + ts.setEmitFlags(thisArg, 4 /* NoSubstitution */); + } + var resultingCall = void 0; + if (node.transformFlags & 131072 /* ContainsRestOrSpread */) { + // [source] + // f(...a, b) + // x.m(...a, b) + // super(...a, b) + // super.m(...a, b) // in static + // super.m(...a, b) // in instance + // + // [output] + // f.apply(void 0, a.concat([b])) + // (_a = x).m.apply(_a, a.concat([b])) + // _super.apply(this, a.concat([b])) + // _super.m.apply(this, a.concat([b])) + // _super.prototype.m.apply(this, a.concat([b])) + resultingCall = ts.createFunctionApply(ts.visitNode(target, callExpressionVisitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), transformAndSpreadElements(node.arguments, /*needsUniqueCopy*/ false, /*multiLine*/ false, /*hasTrailingComma*/ false)); + } + else { + // [source] + // super(a) + // super.m(a) // in static + // super.m(a) // in instance + // + // [output] + // _super.call(this, a) + // _super.m.call(this, a) + // _super.prototype.m.call(this, a) + resultingCall = ts.createFunctionCall(ts.visitNode(target, callExpressionVisitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), ts.visitNodes(node.arguments, visitor, ts.isExpression), + /*location*/ node); + } + if (node.expression.kind === 98 /* SuperKeyword */) { + var actualThis = ts.createThis(); + ts.setEmitFlags(actualThis, 4 /* NoSubstitution */); + var initializer = ts.createLogicalOr(resultingCall, actualThis); + resultingCall = assignToCapturedThis + ? ts.createAssignment(ts.createFileLevelUniqueName("_this"), initializer) + : initializer; + } + return ts.setOriginalNode(resultingCall, node); + } + return ts.visitEachChild(node, visitor, context); + } + /** + * Visits a NewExpression that contains a spread element. + * + * @param node A NewExpression node. + */ + function visitNewExpression(node) { + if (node.transformFlags & 131072 /* ContainsRestOrSpread */) { + // We are here because we contain a SpreadElementExpression. + // [source] + // new C(...a) + // + // [output] + // new ((_a = C).bind.apply(_a, [void 0].concat(a)))() + var _a = ts.createCallBinding(ts.createPropertyAccess(node.expression, "bind"), hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg; + return ts.createNew(ts.createFunctionApply(ts.visitNode(target, visitor, ts.isExpression), thisArg, transformAndSpreadElements(ts.createNodeArray([ts.createVoidZero()].concat(node.arguments)), /*needsUniqueCopy*/ false, /*multiLine*/ false, /*hasTrailingComma*/ false)), + /*typeArguments*/ undefined, []); + } + return ts.visitEachChild(node, visitor, context); + } + /** + * Transforms an array of Expression nodes that contains a SpreadExpression. + * + * @param elements The array of Expression nodes. + * @param needsUniqueCopy A value indicating whether to ensure that the result is a fresh array. + * @param multiLine A value indicating whether the result should be emitted on multiple lines. + */ + function transformAndSpreadElements(elements, needsUniqueCopy, multiLine, hasTrailingComma) { + // [source] + // [a, ...b, c] + // + // [output] + // [a].concat(b, [c]) + // Map spans of spread expressions into their expressions and spans of other + // expressions into an array literal. + var numElements = elements.length; + var segments = ts.flatten(ts.spanMap(elements, partitionSpread, function (partition, visitPartition, _start, end) { + return visitPartition(partition, multiLine, hasTrailingComma && end === numElements); + })); + if (compilerOptions.downlevelIteration) { + if (segments.length === 1) { + var firstSegment = segments[0]; + if (ts.isCallExpression(firstSegment) + && ts.isIdentifier(firstSegment.expression) + && (ts.getEmitFlags(firstSegment.expression) & 4096 /* HelperName */) + && firstSegment.expression.escapedText === "___spread") { + return segments[0]; + } + } + return ts.createSpreadHelper(context, segments); + } + else { + if (segments.length === 1) { + var firstElement = elements[0]; + return needsUniqueCopy && ts.isSpreadElement(firstElement) && firstElement.expression.kind !== 187 /* ArrayLiteralExpression */ + ? ts.createArraySlice(segments[0]) + : segments[0]; + } + // Rewrite using the pattern .concat(, , ...) + return ts.createArrayConcat(segments.shift(), segments); + } + } + function partitionSpread(node) { + return ts.isSpreadElement(node) + ? visitSpanOfSpreads + : visitSpanOfNonSpreads; + } + function visitSpanOfSpreads(chunk) { + return ts.map(chunk, visitExpressionOfSpread); + } + function visitSpanOfNonSpreads(chunk, multiLine, hasTrailingComma) { + return ts.createArrayLiteral(ts.visitNodes(ts.createNodeArray(chunk, hasTrailingComma), visitor, ts.isExpression), multiLine); + } + function visitSpreadElement(node) { + return ts.visitNode(node.expression, visitor, ts.isExpression); + } + /** + * Transforms the expression of a SpreadExpression node. + * + * @param node A SpreadExpression node. + */ + function visitExpressionOfSpread(node) { + return ts.visitNode(node.expression, visitor, ts.isExpression); + } + /** + * Visits a template literal. + * + * @param node A template literal. + */ + function visitTemplateLiteral(node) { + return ts.setTextRange(ts.createLiteral(node.text), node); + } + /** + * Visits a string literal with an extended unicode escape. + * + * @param node A string literal. + */ + function visitStringLiteral(node) { + if (node.hasExtendedUnicodeEscape) { + return ts.setTextRange(ts.createLiteral(node.text), node); + } + return node; + } + /** + * Visits a binary or octal (ES6) numeric literal. + * + * @param node A string literal. + */ + function visitNumericLiteral(node) { + if (node.numericLiteralFlags & 384 /* BinaryOrOctalSpecifier */) { + return ts.setTextRange(ts.createNumericLiteral(node.text), node); + } + return node; + } + /** + * Visits a TaggedTemplateExpression node. + * + * @param node A TaggedTemplateExpression node. + */ + function visitTaggedTemplateExpression(node) { + // Visit the tag expression + var tag = ts.visitNode(node.tag, visitor, ts.isExpression); + // Build up the template arguments and the raw and cooked strings for the template. + // We start out with 'undefined' for the first argument and revisit later + // to avoid walking over the template string twice and shifting all our arguments over after the fact. + var templateArguments = [undefined]; + var cookedStrings = []; + var rawStrings = []; + var template = node.template; + if (ts.isNoSubstitutionTemplateLiteral(template)) { + cookedStrings.push(ts.createLiteral(template.text)); + rawStrings.push(getRawLiteral(template)); + } + else { + cookedStrings.push(ts.createLiteral(template.head.text)); + rawStrings.push(getRawLiteral(template.head)); + for (var _i = 0, _a = template.templateSpans; _i < _a.length; _i++) { + var templateSpan = _a[_i]; + cookedStrings.push(ts.createLiteral(templateSpan.literal.text)); + rawStrings.push(getRawLiteral(templateSpan.literal)); + templateArguments.push(ts.visitNode(templateSpan.expression, visitor, ts.isExpression)); + } + } + var helperCall = createTemplateObjectHelper(context, ts.createArrayLiteral(cookedStrings), ts.createArrayLiteral(rawStrings)); + // Create a variable to cache the template object if we're in a module. + // Do not do this in the global scope, as any variable we currently generate could conflict with + // variables from outside of the current compilation. In the future, we can revisit this behavior. + if (ts.isExternalModule(currentSourceFile)) { + var tempVar = ts.createUniqueName("templateObject"); + recordTaggedTemplateString(tempVar); + templateArguments[0] = ts.createLogicalOr(tempVar, ts.createAssignment(tempVar, helperCall)); + } + else { + templateArguments[0] = helperCall; + } + return ts.createCall(tag, /*typeArguments*/ undefined, templateArguments); + } + /** + * Creates an ES5 compatible literal from an ES6 template literal. + * + * @param node The ES6 template literal. + */ + function getRawLiteral(node) { + // Find original source text, since we need to emit the raw strings of the tagged template. + // The raw strings contain the (escaped) strings of what the user wrote. + // Examples: `\n` is converted to "\\n", a template string with a newline to "\n". + var text = ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node); + // text contains the original source, it will also contain quotes ("`"), dolar signs and braces ("${" and "}"), + // thus we need to remove those characters. + // First template piece starts with "`", others with "}" + // Last template piece ends with "`", others with "${" + var isLast = node.kind === 14 /* NoSubstitutionTemplateLiteral */ || node.kind === 17 /* TemplateTail */; + text = text.substring(1, text.length - (isLast ? 1 : 2)); + // Newline normalization: + // ES6 Spec 11.8.6.1 - Static Semantics of TV's and TRV's + // and LineTerminatorSequences are normalized to for both TV and TRV. + text = text.replace(/\r\n?/g, "\n"); + return ts.setTextRange(ts.createLiteral(text), node); + } + /** + * Visits a TemplateExpression node. + * + * @param node A TemplateExpression node. + */ + function visitTemplateExpression(node) { + var expressions = []; + addTemplateHead(expressions, node); + addTemplateSpans(expressions, node); + // createAdd will check if each expression binds less closely than binary '+'. + // If it does, it wraps the expression in parentheses. Otherwise, something like + // `abc${ 1 << 2 }` + // becomes + // "abc" + 1 << 2 + "" + // which is really + // ("abc" + 1) << (2 + "") + // rather than + // "abc" + (1 << 2) + "" + var expression = ts.reduceLeft(expressions, ts.createAdd); + if (ts.nodeIsSynthesized(expression)) { + expression.pos = node.pos; + expression.end = node.end; + } + return expression; + } + /** + * Gets a value indicating whether we need to include the head of a TemplateExpression. + * + * @param node A TemplateExpression node. + */ + function shouldAddTemplateHead(node) { + // If this expression has an empty head literal and the first template span has a non-empty + // literal, then emitting the empty head literal is not necessary. + // `${ foo } and ${ bar }` + // can be emitted as + // foo + " and " + bar + // This is because it is only required that one of the first two operands in the emit + // output must be a string literal, so that the other operand and all following operands + // are forced into strings. + // + // If the first template span has an empty literal, then the head must still be emitted. + // `${ foo }${ bar }` + // must still be emitted as + // "" + foo + bar + // There is always atleast one templateSpan in this code path, since + // NoSubstitutionTemplateLiterals are directly emitted via emitLiteral() + ts.Debug.assert(node.templateSpans.length !== 0); + return node.head.text.length !== 0 || node.templateSpans[0].literal.text.length === 0; + } + /** + * Adds the head of a TemplateExpression to an array of expressions. + * + * @param expressions An array of expressions. + * @param node A TemplateExpression node. + */ + function addTemplateHead(expressions, node) { + if (!shouldAddTemplateHead(node)) { + return; + } + expressions.push(ts.createLiteral(node.head.text)); + } + /** + * Visits and adds the template spans of a TemplateExpression to an array of expressions. + * + * @param expressions An array of expressions. + * @param node A TemplateExpression node. + */ + function addTemplateSpans(expressions, node) { + for (var _i = 0, _a = node.templateSpans; _i < _a.length; _i++) { + var span = _a[_i]; + expressions.push(ts.visitNode(span.expression, visitor, ts.isExpression)); + // Only emit if the literal is non-empty. + // The binary '+' operator is left-associative, so the first string concatenation + // with the head will force the result up to this point to be a string. + // Emitting a '+ ""' has no semantic effect for middles and tails. + if (span.literal.text.length !== 0) { + expressions.push(ts.createLiteral(span.literal.text)); + } + } + } + /** + * Visits the `super` keyword + */ + function visitSuperKeyword(isExpressionOfCall) { + return hierarchyFacts & 8 /* NonStaticClassElement */ + && !isExpressionOfCall + ? ts.createPropertyAccess(ts.createFileLevelUniqueName("_super"), "prototype") + : ts.createFileLevelUniqueName("_super"); + } + function visitMetaProperty(node) { + if (node.keywordToken === 95 /* NewKeyword */ && node.name.escapedText === "target") { + if (hierarchyFacts & 8192 /* ComputedPropertyName */) { + hierarchyFacts |= 32768 /* NewTargetInComputedPropertyName */; + } + else { + hierarchyFacts |= 16384 /* NewTarget */; + } + return ts.createFileLevelUniqueName("_newTarget"); + } + return node; + } + /** + * Called by the printer just before a node is printed. + * + * @param hint A hint as to the intended usage of the node. + * @param node The node to be printed. + * @param emitCallback The callback used to emit the node. + */ + function onEmitNode(hint, node, emitCallback) { + if (enabledSubstitutions & 1 /* CapturedThis */ && ts.isFunctionLike(node)) { + // If we are tracking a captured `this`, keep track of the enclosing function. + var ancestorFacts = enterSubtree(16286 /* FunctionExcludes */, ts.getEmitFlags(node) & 8 /* CapturesThis */ + ? 65 /* FunctionIncludes */ | 16 /* CapturesThis */ + : 65 /* FunctionIncludes */); + previousOnEmitNode(hint, node, emitCallback); + exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */); + return; + } + previousOnEmitNode(hint, node, emitCallback); + } + /** + * Enables a more costly code path for substitutions when we determine a source file + * contains block-scoped bindings (e.g. `let` or `const`). + */ + function enableSubstitutionsForBlockScopedBindings() { + if ((enabledSubstitutions & 2 /* BlockScopedBindings */) === 0) { + enabledSubstitutions |= 2 /* BlockScopedBindings */; + context.enableSubstitution(72 /* Identifier */); + } + } + /** + * Enables a more costly code path for substitutions when we determine a source file + * contains a captured `this`. + */ + function enableSubstitutionsForCapturedThis() { + if ((enabledSubstitutions & 1 /* CapturedThis */) === 0) { + enabledSubstitutions |= 1 /* CapturedThis */; + context.enableSubstitution(100 /* ThisKeyword */); + context.enableEmitNotification(157 /* Constructor */); + context.enableEmitNotification(156 /* MethodDeclaration */); + context.enableEmitNotification(158 /* GetAccessor */); + context.enableEmitNotification(159 /* SetAccessor */); + context.enableEmitNotification(197 /* ArrowFunction */); + context.enableEmitNotification(196 /* FunctionExpression */); + context.enableEmitNotification(239 /* FunctionDeclaration */); + } + } + /** + * Hooks node substitutions. + * + * @param hint The context for the emitter. + * @param node The node to substitute. + */ + function onSubstituteNode(hint, node) { + node = previousOnSubstituteNode(hint, node); + if (hint === 1 /* Expression */) { + return substituteExpression(node); + } + if (ts.isIdentifier(node)) { + return substituteIdentifier(node); + } + return node; + } + /** + * Hooks substitutions for non-expression identifiers. + */ + function substituteIdentifier(node) { + // Only substitute the identifier if we have enabled substitutions for block-scoped + // bindings. + if (enabledSubstitutions & 2 /* BlockScopedBindings */ && !ts.isInternalName(node)) { + var original = ts.getParseTreeNode(node, ts.isIdentifier); + if (original && isNameOfDeclarationWithCollidingName(original)) { + return ts.setTextRange(ts.getGeneratedNameForNode(original), node); + } + } + return node; + } + /** + * Determines whether a name is the name of a declaration with a colliding name. + * NOTE: This function expects to be called with an original source tree node. + * + * @param node An original source tree node. + */ + function isNameOfDeclarationWithCollidingName(node) { + switch (node.parent.kind) { + case 186 /* BindingElement */: + case 240 /* ClassDeclaration */: + case 243 /* EnumDeclaration */: + case 237 /* VariableDeclaration */: + return node.parent.name === node + && resolver.isDeclarationWithCollidingName(node.parent); + } + return false; + } + /** + * Substitutes an expression. + * + * @param node An Expression node. + */ + function substituteExpression(node) { + switch (node.kind) { + case 72 /* Identifier */: + return substituteExpressionIdentifier(node); + case 100 /* ThisKeyword */: + return substituteThisKeyword(node); + } + return node; + } + /** + * Substitutes an expression identifier. + * + * @param node An Identifier node. + */ + function substituteExpressionIdentifier(node) { + if (enabledSubstitutions & 2 /* BlockScopedBindings */ && !ts.isInternalName(node)) { + var declaration = resolver.getReferencedDeclarationWithCollidingName(node); + if (declaration && !(ts.isClassLike(declaration) && isPartOfClassBody(declaration, node))) { + return ts.setTextRange(ts.getGeneratedNameForNode(ts.getNameOfDeclaration(declaration)), node); + } + } + return node; + } + function isPartOfClassBody(declaration, node) { + var currentNode = ts.getParseTreeNode(node); + if (!currentNode || currentNode === declaration || currentNode.end <= declaration.pos || currentNode.pos >= declaration.end) { + // if the node has no correlation to a parse tree node, its definitely not + // part of the body. + // if the node is outside of the document range of the declaration, its + // definitely not part of the body. + return false; + } + var blockScope = ts.getEnclosingBlockScopeContainer(declaration); + while (currentNode) { + if (currentNode === blockScope || currentNode === declaration) { + // if we are in the enclosing block scope of the declaration, we are definitely + // not inside the class body. + return false; + } + if (ts.isClassElement(currentNode) && currentNode.parent === declaration) { + return true; + } + currentNode = currentNode.parent; + } + return false; + } + /** + * Substitutes `this` when contained within an arrow function. + * + * @param node The ThisKeyword node. + */ + function substituteThisKeyword(node) { + if (enabledSubstitutions & 1 /* CapturedThis */ + && hierarchyFacts & 16 /* CapturesThis */) { + return ts.setTextRange(ts.createFileLevelUniqueName("_this"), node); + } + return node; + } + function getClassMemberPrefix(node, member) { + return ts.hasModifier(member, 32 /* Static */) + ? ts.getInternalName(node) + : ts.createPropertyAccess(ts.getInternalName(node), "prototype"); + } + function hasSynthesizedDefaultSuperCall(constructor, hasExtendsClause) { + if (!constructor || !hasExtendsClause) { + return false; + } + if (ts.some(constructor.parameters)) { + return false; + } + var statement = ts.firstOrUndefined(constructor.body.statements); + if (!statement || !ts.nodeIsSynthesized(statement) || statement.kind !== 221 /* ExpressionStatement */) { + return false; + } + var statementExpression = statement.expression; + if (!ts.nodeIsSynthesized(statementExpression) || statementExpression.kind !== 191 /* CallExpression */) { + return false; + } + var callTarget = statementExpression.expression; + if (!ts.nodeIsSynthesized(callTarget) || callTarget.kind !== 98 /* SuperKeyword */) { + return false; + } + var callArgument = ts.singleOrUndefined(statementExpression.arguments); + if (!callArgument || !ts.nodeIsSynthesized(callArgument) || callArgument.kind !== 208 /* SpreadElement */) { + return false; + } + var expression = callArgument.expression; + return ts.isIdentifier(expression) && expression.escapedText === "arguments"; + } + } + ts.transformES2015 = transformES2015; + function createExtendsHelper(context, name) { + context.requestEmitHelper(extendsHelper); + return ts.createCall(ts.getHelperName("__extends"), + /*typeArguments*/ undefined, [ + name, + ts.createFileLevelUniqueName("_super") + ]); + } + function createTemplateObjectHelper(context, cooked, raw) { + context.requestEmitHelper(templateObjectHelper); + return ts.createCall(ts.getHelperName("__makeTemplateObject"), + /*typeArguments*/ undefined, [ + cooked, + raw + ]); + } + var extendsHelper = { + name: "typescript:extends", + scoped: false, + priority: 0, + text: "\n var __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return extendStatics(d, b);\n };\n\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n })();" + }; + var templateObjectHelper = { + name: "typescript:makeTemplateObject", + scoped: false, + priority: 0, + text: "\n var __makeTemplateObject = (this && this.__makeTemplateObject) || function (cooked, raw) {\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\n return cooked;\n };" + }; +})(ts || (ts = {})); +/*@internal*/ +var ts; +(function (ts) { + /** + * Transforms ES5 syntax into ES3 syntax. + * + * @param context Context and state information for the transformation. + */ + function transformES5(context) { + var compilerOptions = context.getCompilerOptions(); + // enable emit notification only if using --jsx preserve or react-native + var previousOnEmitNode; + var noSubstitution; + if (compilerOptions.jsx === 1 /* Preserve */ || compilerOptions.jsx === 3 /* ReactNative */) { + previousOnEmitNode = context.onEmitNode; + context.onEmitNode = onEmitNode; + context.enableEmitNotification(262 /* JsxOpeningElement */); + context.enableEmitNotification(263 /* JsxClosingElement */); + context.enableEmitNotification(261 /* JsxSelfClosingElement */); + noSubstitution = []; + } + var previousOnSubstituteNode = context.onSubstituteNode; + context.onSubstituteNode = onSubstituteNode; + context.enableSubstitution(189 /* PropertyAccessExpression */); + context.enableSubstitution(275 /* PropertyAssignment */); + return ts.chainBundle(transformSourceFile); + /** + * Transforms an ES5 source file to ES3. + * + * @param node A SourceFile + */ + function transformSourceFile(node) { + return node; + } + /** + * Called by the printer just before a node is printed. + * + * @param hint A hint as to the intended usage of the node. + * @param node The node to emit. + * @param emitCallback A callback used to emit the node. + */ + function onEmitNode(hint, node, emitCallback) { + switch (node.kind) { + case 262 /* JsxOpeningElement */: + case 263 /* JsxClosingElement */: + case 261 /* JsxSelfClosingElement */: + var tagName = node.tagName; + noSubstitution[ts.getOriginalNodeId(tagName)] = true; + break; + } + previousOnEmitNode(hint, node, emitCallback); + } + /** + * Hooks node substitutions. + * + * @param hint A hint as to the intended usage of the node. + * @param node The node to substitute. + */ + function onSubstituteNode(hint, node) { + if (node.id && noSubstitution && noSubstitution[node.id]) { + return previousOnSubstituteNode(hint, node); + } + node = previousOnSubstituteNode(hint, node); + if (ts.isPropertyAccessExpression(node)) { + return substitutePropertyAccessExpression(node); + } + else if (ts.isPropertyAssignment(node)) { + return substitutePropertyAssignment(node); + } + return node; + } + /** + * Substitutes a PropertyAccessExpression whose name is a reserved word. + * + * @param node A PropertyAccessExpression + */ + function substitutePropertyAccessExpression(node) { + var literalName = trySubstituteReservedName(node.name); + if (literalName) { + return ts.setTextRange(ts.createElementAccess(node.expression, literalName), node); + } + return node; + } + /** + * Substitutes a PropertyAssignment whose name is a reserved word. + * + * @param node A PropertyAssignment + */ + function substitutePropertyAssignment(node) { + var literalName = ts.isIdentifier(node.name) && trySubstituteReservedName(node.name); + if (literalName) { + return ts.updatePropertyAssignment(node, literalName, node.initializer); + } + return node; + } + /** + * If an identifier name is a reserved word, returns a string literal for the name. + * + * @param name An Identifier + */ + function trySubstituteReservedName(name) { + var token = name.originalKeywordKind || (ts.nodeIsSynthesized(name) ? ts.stringToToken(ts.idText(name)) : undefined); + if (token !== undefined && token >= 73 /* FirstReservedWord */ && token <= 108 /* LastReservedWord */) { + return ts.setTextRange(ts.createLiteral(name), name); + } + return undefined; + } + } + ts.transformES5 = transformES5; +})(ts || (ts = {})); +// Transforms generator functions into a compatible ES5 representation with similar runtime +// semantics. This is accomplished by first transforming the body of each generator +// function into an intermediate representation that is the compiled into a JavaScript +// switch statement. +// +// Many functions in this transformer will contain comments indicating the expected +// intermediate representation. For illustrative purposes, the following intermediate +// language is used to define this intermediate representation: +// +// .nop - Performs no operation. +// .local NAME, ... - Define local variable declarations. +// .mark LABEL - Mark the location of a label. +// .br LABEL - Jump to a label. If jumping out of a protected +// region, all .finally blocks are executed. +// .brtrue LABEL, (x) - Jump to a label IIF the expression `x` is truthy. +// If jumping out of a protected region, all .finally +// blocks are executed. +// .brfalse LABEL, (x) - Jump to a label IIF the expression `x` is falsey. +// If jumping out of a protected region, all .finally +// blocks are executed. +// .yield (x) - Yield the value of the optional expression `x`. +// Resume at the next label. +// .yieldstar (x) - Delegate yield to the value of the optional +// expression `x`. Resume at the next label. +// NOTE: `x` must be an Iterator, not an Iterable. +// .loop CONTINUE, BREAK - Marks the beginning of a loop. Any "continue" or +// "break" abrupt completions jump to the CONTINUE or +// BREAK labels, respectively. +// .endloop - Marks the end of a loop. +// .with (x) - Marks the beginning of a WithStatement block, using +// the supplied expression. +// .endwith - Marks the end of a WithStatement. +// .switch - Marks the beginning of a SwitchStatement. +// .endswitch - Marks the end of a SwitchStatement. +// .labeled NAME - Marks the beginning of a LabeledStatement with the +// supplied name. +// .endlabeled - Marks the end of a LabeledStatement. +// .try TRY, CATCH, FINALLY, END - Marks the beginning of a protected region, and the +// labels for each block. +// .catch (x) - Marks the beginning of a catch block. +// .finally - Marks the beginning of a finally block. +// .endfinally - Marks the end of a finally block. +// .endtry - Marks the end of a protected region. +// .throw (x) - Throws the value of the expression `x`. +// .return (x) - Returns the value of the expression `x`. +// +// In addition, the illustrative intermediate representation introduces some special +// variables: +// +// %sent% - Either returns the next value sent to the generator, +// returns the result of a delegated yield, or throws +// the exception sent to the generator. +// %error% - Returns the value of the current exception in a +// catch block. +// +// This intermediate representation is then compiled into JavaScript syntax. The resulting +// compilation output looks something like the following: +// +// function f() { +// var /*locals*/; +// /*functions*/ +// return __generator(function (state) { +// switch (state.label) { +// /*cases per label*/ +// } +// }); +// } +// +// Each of the above instructions corresponds to JavaScript emit similar to the following: +// +// .local NAME | var NAME; +// -------------------------------|---------------------------------------------- +// .mark LABEL | case LABEL: +// -------------------------------|---------------------------------------------- +// .br LABEL | return [3 /*break*/, LABEL]; +// -------------------------------|---------------------------------------------- +// .brtrue LABEL, (x) | if (x) return [3 /*break*/, LABEL]; +// -------------------------------|---------------------------------------------- +// .brfalse LABEL, (x) | if (!(x)) return [3, /*break*/, LABEL]; +// -------------------------------|---------------------------------------------- +// .yield (x) | return [4 /*yield*/, x]; +// .mark RESUME | case RESUME: +// a = %sent%; | a = state.sent(); +// -------------------------------|---------------------------------------------- +// .yieldstar (x) | return [5 /*yield**/, x]; +// .mark RESUME | case RESUME: +// a = %sent%; | a = state.sent(); +// -------------------------------|---------------------------------------------- +// .with (_a) | with (_a) { +// a(); | a(); +// | } +// | state.label = LABEL; +// .mark LABEL | case LABEL: +// | with (_a) { +// b(); | b(); +// | } +// .endwith | +// -------------------------------|---------------------------------------------- +// | case 0: +// | state.trys = []; +// | ... +// .try TRY, CATCH, FINALLY, END | +// .mark TRY | case TRY: +// | state.trys.push([TRY, CATCH, FINALLY, END]); +// .nop | +// a(); | a(); +// .br END | return [3 /*break*/, END]; +// .catch (e) | +// .mark CATCH | case CATCH: +// | e = state.sent(); +// b(); | b(); +// .br END | return [3 /*break*/, END]; +// .finally | +// .mark FINALLY | case FINALLY: +// c(); | c(); +// .endfinally | return [7 /*endfinally*/]; +// .endtry | +// .mark END | case END: +/*@internal*/ +var ts; +(function (ts) { + var OpCode; + (function (OpCode) { + OpCode[OpCode["Nop"] = 0] = "Nop"; + OpCode[OpCode["Statement"] = 1] = "Statement"; + OpCode[OpCode["Assign"] = 2] = "Assign"; + OpCode[OpCode["Break"] = 3] = "Break"; + OpCode[OpCode["BreakWhenTrue"] = 4] = "BreakWhenTrue"; + OpCode[OpCode["BreakWhenFalse"] = 5] = "BreakWhenFalse"; + OpCode[OpCode["Yield"] = 6] = "Yield"; + OpCode[OpCode["YieldStar"] = 7] = "YieldStar"; + OpCode[OpCode["Return"] = 8] = "Return"; + OpCode[OpCode["Throw"] = 9] = "Throw"; + OpCode[OpCode["Endfinally"] = 10] = "Endfinally"; // Marks the end of a `finally` block + })(OpCode || (OpCode = {})); + // whether a generated code block is opening or closing at the current operation for a FunctionBuilder + var BlockAction; + (function (BlockAction) { + BlockAction[BlockAction["Open"] = 0] = "Open"; + BlockAction[BlockAction["Close"] = 1] = "Close"; + })(BlockAction || (BlockAction = {})); + // the kind for a generated code block in a FunctionBuilder + var CodeBlockKind; + (function (CodeBlockKind) { + CodeBlockKind[CodeBlockKind["Exception"] = 0] = "Exception"; + CodeBlockKind[CodeBlockKind["With"] = 1] = "With"; + CodeBlockKind[CodeBlockKind["Switch"] = 2] = "Switch"; + CodeBlockKind[CodeBlockKind["Loop"] = 3] = "Loop"; + CodeBlockKind[CodeBlockKind["Labeled"] = 4] = "Labeled"; + })(CodeBlockKind || (CodeBlockKind = {})); + // the state for a generated code exception block + var ExceptionBlockState; + (function (ExceptionBlockState) { + ExceptionBlockState[ExceptionBlockState["Try"] = 0] = "Try"; + ExceptionBlockState[ExceptionBlockState["Catch"] = 1] = "Catch"; + ExceptionBlockState[ExceptionBlockState["Finally"] = 2] = "Finally"; + ExceptionBlockState[ExceptionBlockState["Done"] = 3] = "Done"; + })(ExceptionBlockState || (ExceptionBlockState = {})); + // NOTE: changes to this enum should be reflected in the __generator helper. + var Instruction; + (function (Instruction) { + Instruction[Instruction["Next"] = 0] = "Next"; + Instruction[Instruction["Throw"] = 1] = "Throw"; + Instruction[Instruction["Return"] = 2] = "Return"; + Instruction[Instruction["Break"] = 3] = "Break"; + Instruction[Instruction["Yield"] = 4] = "Yield"; + Instruction[Instruction["YieldStar"] = 5] = "YieldStar"; + Instruction[Instruction["Catch"] = 6] = "Catch"; + Instruction[Instruction["Endfinally"] = 7] = "Endfinally"; + })(Instruction || (Instruction = {})); + function getInstructionName(instruction) { + switch (instruction) { + case 2 /* Return */: return "return"; + case 3 /* Break */: return "break"; + case 4 /* Yield */: return "yield"; + case 5 /* YieldStar */: return "yield*"; + case 7 /* Endfinally */: return "endfinally"; + default: return undefined; // TODO: GH#18217 + } + } + function transformGenerators(context) { + var resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistFunctionDeclaration = context.hoistFunctionDeclaration, hoistVariableDeclaration = context.hoistVariableDeclaration; + var compilerOptions = context.getCompilerOptions(); + var languageVersion = ts.getEmitScriptTarget(compilerOptions); + var resolver = context.getEmitResolver(); + var previousOnSubstituteNode = context.onSubstituteNode; + context.onSubstituteNode = onSubstituteNode; + var renamedCatchVariables; + var renamedCatchVariableDeclarations; + var inGeneratorFunctionBody; + var inStatementContainingYield; + // The following three arrays store information about generated code blocks. + // All three arrays are correlated by their index. This approach is used over allocating + // objects to store the same information to avoid GC overhead. + // + var blocks; // Information about the code block + var blockOffsets; // The operation offset at which a code block begins or ends + var blockActions; // Whether the code block is opened or closed + var blockStack; // A stack of currently open code blocks + // Labels are used to mark locations in the code that can be the target of a Break (jump) + // operation. These are translated into case clauses in a switch statement. + // The following two arrays are correlated by their index. This approach is used over + // allocating objects to store the same information to avoid GC overhead. + // + var labelOffsets; // The operation offset at which the label is defined. + var labelExpressions; // The NumericLiteral nodes bound to each label. + var nextLabelId = 1; // The next label id to use. + // Operations store information about generated code for the function body. This + // Includes things like statements, assignments, breaks (jumps), and yields. + // The following three arrays are correlated by their index. This approach is used over + // allocating objects to store the same information to avoid GC overhead. + // + var operations; // The operation to perform. + var operationArguments; // The arguments to the operation. + var operationLocations; // The source map location for the operation. + var state; // The name of the state object used by the generator at runtime. + // The following variables store information used by the `build` function: + // + var blockIndex = 0; // The index of the current block. + var labelNumber = 0; // The current label number. + var labelNumbers; + var lastOperationWasAbrupt; // Indicates whether the last operation was abrupt (break/continue). + var lastOperationWasCompletion; // Indicates whether the last operation was a completion (return/throw). + var clauses; // The case clauses generated for labels. + var statements; // The statements for the current label. + var exceptionBlockStack; // A stack of containing exception blocks. + var currentExceptionBlock; // The current exception block. + var withBlockStack; // A stack containing `with` blocks. + return ts.chainBundle(transformSourceFile); + function transformSourceFile(node) { + if (node.isDeclarationFile || (node.transformFlags & 512 /* ContainsGenerator */) === 0) { + return node; + } + var visited = ts.visitEachChild(node, visitor, context); + ts.addEmitHelpers(visited, context.readEmitHelpers()); + return visited; + } + /** + * Visits a node. + * + * @param node The node to visit. + */ + function visitor(node) { + var transformFlags = node.transformFlags; + if (inStatementContainingYield) { + return visitJavaScriptInStatementContainingYield(node); + } + else if (inGeneratorFunctionBody) { + return visitJavaScriptInGeneratorFunctionBody(node); + } + else if (transformFlags & 256 /* Generator */) { + return visitGenerator(node); + } + else if (transformFlags & 512 /* ContainsGenerator */) { + return ts.visitEachChild(node, visitor, context); + } + else { + return node; + } + } + /** + * Visits a node that is contained within a statement that contains yield. + * + * @param node The node to visit. + */ + function visitJavaScriptInStatementContainingYield(node) { + switch (node.kind) { + case 223 /* DoStatement */: + return visitDoStatement(node); + case 224 /* WhileStatement */: + return visitWhileStatement(node); + case 232 /* SwitchStatement */: + return visitSwitchStatement(node); + case 233 /* LabeledStatement */: + return visitLabeledStatement(node); + default: + return visitJavaScriptInGeneratorFunctionBody(node); + } + } + /** + * Visits a node that is contained within a generator function. + * + * @param node The node to visit. + */ + function visitJavaScriptInGeneratorFunctionBody(node) { + switch (node.kind) { + case 239 /* FunctionDeclaration */: + return visitFunctionDeclaration(node); + case 196 /* FunctionExpression */: + return visitFunctionExpression(node); + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + return visitAccessorDeclaration(node); + case 219 /* VariableStatement */: + return visitVariableStatement(node); + case 225 /* ForStatement */: + return visitForStatement(node); + case 226 /* ForInStatement */: + return visitForInStatement(node); + case 229 /* BreakStatement */: + return visitBreakStatement(node); + case 228 /* ContinueStatement */: + return visitContinueStatement(node); + case 230 /* ReturnStatement */: + return visitReturnStatement(node); + default: + if (node.transformFlags & 4194304 /* ContainsYield */) { + return visitJavaScriptContainingYield(node); + } + else if (node.transformFlags & (512 /* ContainsGenerator */ | 8388608 /* ContainsHoistedDeclarationOrCompletion */)) { + return ts.visitEachChild(node, visitor, context); + } + else { + return node; + } + } + } + /** + * Visits a node that contains a YieldExpression. + * + * @param node The node to visit. + */ + function visitJavaScriptContainingYield(node) { + switch (node.kind) { + case 204 /* BinaryExpression */: + return visitBinaryExpression(node); + case 205 /* ConditionalExpression */: + return visitConditionalExpression(node); + case 207 /* YieldExpression */: + return visitYieldExpression(node); + case 187 /* ArrayLiteralExpression */: + return visitArrayLiteralExpression(node); + case 188 /* ObjectLiteralExpression */: + return visitObjectLiteralExpression(node); + case 190 /* ElementAccessExpression */: + return visitElementAccessExpression(node); + case 191 /* CallExpression */: + return visitCallExpression(node); + case 192 /* NewExpression */: + return visitNewExpression(node); + default: + return ts.visitEachChild(node, visitor, context); + } + } + /** + * Visits a generator function. + * + * @param node The node to visit. + */ + function visitGenerator(node) { + switch (node.kind) { + case 239 /* FunctionDeclaration */: + return visitFunctionDeclaration(node); + case 196 /* FunctionExpression */: + return visitFunctionExpression(node); + default: + return ts.Debug.failBadSyntaxKind(node); + } + } + /** + * Visits a function declaration. + * + * This will be called when one of the following conditions are met: + * - The function declaration is a generator function. + * - The function declaration is contained within the body of a generator function. + * + * @param node The node to visit. + */ + function visitFunctionDeclaration(node) { + // Currently, we only support generators that were originally async functions. + if (node.asteriskToken) { + node = ts.setOriginalNode(ts.setTextRange(ts.createFunctionDeclaration( + /*decorators*/ undefined, node.modifiers, + /*asteriskToken*/ undefined, node.name, + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, transformGeneratorFunctionBody(node.body)), + /*location*/ node), node); + } + else { + var savedInGeneratorFunctionBody = inGeneratorFunctionBody; + var savedInStatementContainingYield = inStatementContainingYield; + inGeneratorFunctionBody = false; + inStatementContainingYield = false; + node = ts.visitEachChild(node, visitor, context); + inGeneratorFunctionBody = savedInGeneratorFunctionBody; + inStatementContainingYield = savedInStatementContainingYield; + } + if (inGeneratorFunctionBody) { + // Function declarations in a generator function body are hoisted + // to the top of the lexical scope and elided from the current statement. + hoistFunctionDeclaration(node); + return undefined; + } + else { + return node; + } + } + /** + * Visits a function expression. + * + * This will be called when one of the following conditions are met: + * - The function expression is a generator function. + * - The function expression is contained within the body of a generator function. + * + * @param node The node to visit. + */ + function visitFunctionExpression(node) { + // Currently, we only support generators that were originally async functions. + if (node.asteriskToken) { + node = ts.setOriginalNode(ts.setTextRange(ts.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, node.name, + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, transformGeneratorFunctionBody(node.body)), + /*location*/ node), node); + } + else { + var savedInGeneratorFunctionBody = inGeneratorFunctionBody; + var savedInStatementContainingYield = inStatementContainingYield; + inGeneratorFunctionBody = false; + inStatementContainingYield = false; + node = ts.visitEachChild(node, visitor, context); + inGeneratorFunctionBody = savedInGeneratorFunctionBody; + inStatementContainingYield = savedInStatementContainingYield; + } + return node; + } + /** + * Visits a get or set accessor declaration. + * + * This will be called when one of the following conditions are met: + * - The accessor is contained within the body of a generator function. + * + * @param node The node to visit. + */ + function visitAccessorDeclaration(node) { + var savedInGeneratorFunctionBody = inGeneratorFunctionBody; + var savedInStatementContainingYield = inStatementContainingYield; + inGeneratorFunctionBody = false; + inStatementContainingYield = false; + node = ts.visitEachChild(node, visitor, context); + inGeneratorFunctionBody = savedInGeneratorFunctionBody; + inStatementContainingYield = savedInStatementContainingYield; + return node; + } + /** + * Transforms the body of a generator function declaration. + * + * @param node The function body to transform. + */ + function transformGeneratorFunctionBody(body) { + // Save existing generator state + var statements = []; + var savedInGeneratorFunctionBody = inGeneratorFunctionBody; + var savedInStatementContainingYield = inStatementContainingYield; + var savedBlocks = blocks; + var savedBlockOffsets = blockOffsets; + var savedBlockActions = blockActions; + var savedBlockStack = blockStack; + var savedLabelOffsets = labelOffsets; + var savedLabelExpressions = labelExpressions; + var savedNextLabelId = nextLabelId; + var savedOperations = operations; + var savedOperationArguments = operationArguments; + var savedOperationLocations = operationLocations; + var savedState = state; + // Initialize generator state + inGeneratorFunctionBody = true; + inStatementContainingYield = false; + blocks = undefined; + blockOffsets = undefined; + blockActions = undefined; + blockStack = undefined; + labelOffsets = undefined; + labelExpressions = undefined; + nextLabelId = 1; + operations = undefined; + operationArguments = undefined; + operationLocations = undefined; + state = ts.createTempVariable(/*recordTempVariable*/ undefined); + // Build the generator + resumeLexicalEnvironment(); + var statementOffset = ts.addPrologue(statements, body.statements, /*ensureUseStrict*/ false, visitor); + transformAndEmitStatements(body.statements, statementOffset); + var buildResult = build(); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + statements.push(ts.createReturn(buildResult)); + // Restore previous generator state + inGeneratorFunctionBody = savedInGeneratorFunctionBody; + inStatementContainingYield = savedInStatementContainingYield; + blocks = savedBlocks; + blockOffsets = savedBlockOffsets; + blockActions = savedBlockActions; + blockStack = savedBlockStack; + labelOffsets = savedLabelOffsets; + labelExpressions = savedLabelExpressions; + nextLabelId = savedNextLabelId; + operations = savedOperations; + operationArguments = savedOperationArguments; + operationLocations = savedOperationLocations; + state = savedState; + return ts.setTextRange(ts.createBlock(statements, body.multiLine), body); + } + /** + * Visits a variable statement. + * + * This will be called when one of the following conditions are met: + * - The variable statement is contained within the body of a generator function. + * + * @param node The node to visit. + */ + function visitVariableStatement(node) { + if (node.transformFlags & 4194304 /* ContainsYield */) { + transformAndEmitVariableDeclarationList(node.declarationList); + return undefined; + } + else { + // Do not hoist custom prologues. + if (ts.getEmitFlags(node) & 1048576 /* CustomPrologue */) { + return node; + } + for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { + var variable = _a[_i]; + hoistVariableDeclaration(variable.name); + } + var variables = ts.getInitializedVariables(node.declarationList); + if (variables.length === 0) { + return undefined; + } + return ts.setSourceMapRange(ts.createExpressionStatement(ts.inlineExpressions(ts.map(variables, transformInitializedVariable))), node); + } + } + /** + * Visits a binary expression. + * + * This will be called when one of the following conditions are met: + * - The node contains a YieldExpression. + * + * @param node The node to visit. + */ + function visitBinaryExpression(node) { + var assoc = ts.getExpressionAssociativity(node); + switch (assoc) { + case 0 /* Left */: + return visitLeftAssociativeBinaryExpression(node); + case 1 /* Right */: + return visitRightAssociativeBinaryExpression(node); + default: + return ts.Debug.assertNever(assoc); + } + } + function isCompoundAssignment(kind) { + return kind >= 60 /* FirstCompoundAssignment */ + && kind <= 71 /* LastCompoundAssignment */; + } + function getOperatorForCompoundAssignment(kind) { + switch (kind) { + case 60 /* PlusEqualsToken */: return 38 /* PlusToken */; + case 61 /* MinusEqualsToken */: return 39 /* MinusToken */; + case 62 /* AsteriskEqualsToken */: return 40 /* AsteriskToken */; + case 63 /* AsteriskAsteriskEqualsToken */: return 41 /* AsteriskAsteriskToken */; + case 64 /* SlashEqualsToken */: return 42 /* SlashToken */; + case 65 /* PercentEqualsToken */: return 43 /* PercentToken */; + case 66 /* LessThanLessThanEqualsToken */: return 46 /* LessThanLessThanToken */; + case 67 /* GreaterThanGreaterThanEqualsToken */: return 47 /* GreaterThanGreaterThanToken */; + case 68 /* GreaterThanGreaterThanGreaterThanEqualsToken */: return 48 /* GreaterThanGreaterThanGreaterThanToken */; + case 69 /* AmpersandEqualsToken */: return 49 /* AmpersandToken */; + case 70 /* BarEqualsToken */: return 50 /* BarToken */; + case 71 /* CaretEqualsToken */: return 51 /* CaretToken */; + } + } + /** + * Visits a right-associative binary expression containing `yield`. + * + * @param node The node to visit. + */ + function visitRightAssociativeBinaryExpression(node) { + var left = node.left, right = node.right; + if (containsYield(right)) { + var target = void 0; + switch (left.kind) { + case 189 /* PropertyAccessExpression */: + // [source] + // a.b = yield; + // + // [intermediate] + // .local _a + // _a = a; + // .yield resumeLabel + // .mark resumeLabel + // _a.b = %sent%; + target = ts.updatePropertyAccess(left, cacheExpression(ts.visitNode(left.expression, visitor, ts.isLeftHandSideExpression)), left.name); + break; + case 190 /* ElementAccessExpression */: + // [source] + // a[b] = yield; + // + // [intermediate] + // .local _a, _b + // _a = a; + // _b = b; + // .yield resumeLabel + // .mark resumeLabel + // _a[_b] = %sent%; + target = ts.updateElementAccess(left, cacheExpression(ts.visitNode(left.expression, visitor, ts.isLeftHandSideExpression)), cacheExpression(ts.visitNode(left.argumentExpression, visitor, ts.isExpression))); + break; + default: + target = ts.visitNode(left, visitor, ts.isExpression); + break; + } + var operator = node.operatorToken.kind; + if (isCompoundAssignment(operator)) { + return ts.setTextRange(ts.createAssignment(target, ts.setTextRange(ts.createBinary(cacheExpression(target), getOperatorForCompoundAssignment(operator), ts.visitNode(right, visitor, ts.isExpression)), node)), node); + } + else { + return ts.updateBinary(node, target, ts.visitNode(right, visitor, ts.isExpression)); + } + } + return ts.visitEachChild(node, visitor, context); + } + function visitLeftAssociativeBinaryExpression(node) { + if (containsYield(node.right)) { + if (ts.isLogicalOperator(node.operatorToken.kind)) { + return visitLogicalBinaryExpression(node); + } + else if (node.operatorToken.kind === 27 /* CommaToken */) { + return visitCommaExpression(node); + } + // [source] + // a() + (yield) + c() + // + // [intermediate] + // .local _a + // _a = a(); + // .yield resumeLabel + // _a + %sent% + c() + var clone_5 = ts.getMutableClone(node); + clone_5.left = cacheExpression(ts.visitNode(node.left, visitor, ts.isExpression)); + clone_5.right = ts.visitNode(node.right, visitor, ts.isExpression); + return clone_5; + } + return ts.visitEachChild(node, visitor, context); + } + /** + * Visits a logical binary expression containing `yield`. + * + * @param node A node to visit. + */ + function visitLogicalBinaryExpression(node) { + // Logical binary expressions (`&&` and `||`) are shortcutting expressions and need + // to be transformed as such: + // + // [source] + // x = a() && yield; + // + // [intermediate] + // .local _a + // _a = a(); + // .brfalse resultLabel, (_a) + // .yield resumeLabel + // .mark resumeLabel + // _a = %sent%; + // .mark resultLabel + // x = _a; + // + // [source] + // x = a() || yield; + // + // [intermediate] + // .local _a + // _a = a(); + // .brtrue resultLabel, (_a) + // .yield resumeLabel + // .mark resumeLabel + // _a = %sent%; + // .mark resultLabel + // x = _a; + var resultLabel = defineLabel(); + var resultLocal = declareLocal(); + emitAssignment(resultLocal, ts.visitNode(node.left, visitor, ts.isExpression), /*location*/ node.left); + if (node.operatorToken.kind === 54 /* AmpersandAmpersandToken */) { + // Logical `&&` shortcuts when the left-hand operand is falsey. + emitBreakWhenFalse(resultLabel, resultLocal, /*location*/ node.left); + } + else { + // Logical `||` shortcuts when the left-hand operand is truthy. + emitBreakWhenTrue(resultLabel, resultLocal, /*location*/ node.left); + } + emitAssignment(resultLocal, ts.visitNode(node.right, visitor, ts.isExpression), /*location*/ node.right); + markLabel(resultLabel); + return resultLocal; + } + /** + * Visits a comma expression containing `yield`. + * + * @param node The node to visit. + */ + function visitCommaExpression(node) { + // [source] + // x = a(), yield, b(); + // + // [intermediate] + // a(); + // .yield resumeLabel + // .mark resumeLabel + // x = %sent%, b(); + var pendingExpressions = []; + visit(node.left); + visit(node.right); + return ts.inlineExpressions(pendingExpressions); + function visit(node) { + if (ts.isBinaryExpression(node) && node.operatorToken.kind === 27 /* CommaToken */) { + visit(node.left); + visit(node.right); + } + else { + if (containsYield(node) && pendingExpressions.length > 0) { + emitWorker(1 /* Statement */, [ts.createExpressionStatement(ts.inlineExpressions(pendingExpressions))]); + pendingExpressions = []; + } + pendingExpressions.push(ts.visitNode(node, visitor, ts.isExpression)); + } + } + } + /** + * Visits a conditional expression containing `yield`. + * + * @param node The node to visit. + */ + function visitConditionalExpression(node) { + // [source] + // x = a() ? yield : b(); + // + // [intermediate] + // .local _a + // .brfalse whenFalseLabel, (a()) + // .yield resumeLabel + // .mark resumeLabel + // _a = %sent%; + // .br resultLabel + // .mark whenFalseLabel + // _a = b(); + // .mark resultLabel + // x = _a; + // We only need to perform a specific transformation if a `yield` expression exists + // in either the `whenTrue` or `whenFalse` branches. + // A `yield` in the condition will be handled by the normal visitor. + if (containsYield(node.whenTrue) || containsYield(node.whenFalse)) { + var whenFalseLabel = defineLabel(); + var resultLabel = defineLabel(); + var resultLocal = declareLocal(); + emitBreakWhenFalse(whenFalseLabel, ts.visitNode(node.condition, visitor, ts.isExpression), /*location*/ node.condition); + emitAssignment(resultLocal, ts.visitNode(node.whenTrue, visitor, ts.isExpression), /*location*/ node.whenTrue); + emitBreak(resultLabel); + markLabel(whenFalseLabel); + emitAssignment(resultLocal, ts.visitNode(node.whenFalse, visitor, ts.isExpression), /*location*/ node.whenFalse); + markLabel(resultLabel); + return resultLocal; + } + return ts.visitEachChild(node, visitor, context); + } + /** + * Visits a `yield` expression. + * + * @param node The node to visit. + */ + function visitYieldExpression(node) { + // [source] + // x = yield a(); + // + // [intermediate] + // .yield resumeLabel, (a()) + // .mark resumeLabel + // x = %sent%; + var resumeLabel = defineLabel(); + var expression = ts.visitNode(node.expression, visitor, ts.isExpression); + if (node.asteriskToken) { + var iterator = (ts.getEmitFlags(node.expression) & 8388608 /* Iterator */) === 0 + ? ts.createValuesHelper(context, expression, /*location*/ node) + : expression; + emitYieldStar(iterator, /*location*/ node); + } + else { + emitYield(expression, /*location*/ node); + } + markLabel(resumeLabel); + return createGeneratorResume(/*location*/ node); + } + /** + * Visits an ArrayLiteralExpression that contains a YieldExpression. + * + * @param node The node to visit. + */ + function visitArrayLiteralExpression(node) { + return visitElements(node.elements, /*leadingElement*/ undefined, /*location*/ undefined, node.multiLine); + } + /** + * Visits an array of expressions containing one or more YieldExpression nodes + * and returns an expression for the resulting value. + * + * @param elements The elements to visit. + * @param multiLine Whether array literals created should be emitted on multiple lines. + */ + function visitElements(elements, leadingElement, location, multiLine) { + // [source] + // ar = [1, yield, 2]; + // + // [intermediate] + // .local _a + // _a = [1]; + // .yield resumeLabel + // .mark resumeLabel + // ar = _a.concat([%sent%, 2]); + var numInitialElements = countInitialNodesWithoutYield(elements); + var temp; + if (numInitialElements > 0) { + temp = declareLocal(); + var initialElements = ts.visitNodes(elements, visitor, ts.isExpression, 0, numInitialElements); + emitAssignment(temp, ts.createArrayLiteral(leadingElement + ? [leadingElement].concat(initialElements) : initialElements)); + leadingElement = undefined; + } + var expressions = ts.reduceLeft(elements, reduceElement, [], numInitialElements); + return temp + ? ts.createArrayConcat(temp, [ts.createArrayLiteral(expressions, multiLine)]) + : ts.setTextRange(ts.createArrayLiteral(leadingElement ? [leadingElement].concat(expressions) : expressions, multiLine), location); + function reduceElement(expressions, element) { + if (containsYield(element) && expressions.length > 0) { + var hasAssignedTemp = temp !== undefined; + if (!temp) { + temp = declareLocal(); + } + emitAssignment(temp, hasAssignedTemp + ? ts.createArrayConcat(temp, [ts.createArrayLiteral(expressions, multiLine)]) + : ts.createArrayLiteral(leadingElement ? [leadingElement].concat(expressions) : expressions, multiLine)); + leadingElement = undefined; + expressions = []; + } + expressions.push(ts.visitNode(element, visitor, ts.isExpression)); + return expressions; + } + } + function visitObjectLiteralExpression(node) { + // [source] + // o = { + // a: 1, + // b: yield, + // c: 2 + // }; + // + // [intermediate] + // .local _a + // _a = { + // a: 1 + // }; + // .yield resumeLabel + // .mark resumeLabel + // o = (_a.b = %sent%, + // _a.c = 2, + // _a); + var properties = node.properties; + var multiLine = node.multiLine; + var numInitialProperties = countInitialNodesWithoutYield(properties); + var temp = declareLocal(); + emitAssignment(temp, ts.createObjectLiteral(ts.visitNodes(properties, visitor, ts.isObjectLiteralElementLike, 0, numInitialProperties), multiLine)); + var expressions = ts.reduceLeft(properties, reduceProperty, [], numInitialProperties); + expressions.push(multiLine ? ts.startOnNewLine(ts.getMutableClone(temp)) : temp); + return ts.inlineExpressions(expressions); + function reduceProperty(expressions, property) { + if (containsYield(property) && expressions.length > 0) { + emitStatement(ts.createExpressionStatement(ts.inlineExpressions(expressions))); + expressions = []; + } + var expression = ts.createExpressionForObjectLiteralElementLike(node, property, temp); + var visited = ts.visitNode(expression, visitor, ts.isExpression); + if (visited) { + if (multiLine) { + ts.startOnNewLine(visited); + } + expressions.push(visited); + } + return expressions; + } + } + /** + * Visits an ElementAccessExpression that contains a YieldExpression. + * + * @param node The node to visit. + */ + function visitElementAccessExpression(node) { + if (containsYield(node.argumentExpression)) { + // [source] + // a = x[yield]; + // + // [intermediate] + // .local _a + // _a = x; + // .yield resumeLabel + // .mark resumeLabel + // a = _a[%sent%] + var clone_6 = ts.getMutableClone(node); + clone_6.expression = cacheExpression(ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression)); + clone_6.argumentExpression = ts.visitNode(node.argumentExpression, visitor, ts.isExpression); + return clone_6; + } + return ts.visitEachChild(node, visitor, context); + } + function visitCallExpression(node) { + if (!ts.isImportCall(node) && ts.forEach(node.arguments, containsYield)) { + // [source] + // a.b(1, yield, 2); + // + // [intermediate] + // .local _a, _b, _c + // _b = (_a = a).b; + // _c = [1]; + // .yield resumeLabel + // .mark resumeLabel + // _b.apply(_a, _c.concat([%sent%, 2])); + var _a = ts.createCallBinding(node.expression, hoistVariableDeclaration, languageVersion, /*cacheIdentifiers*/ true), target = _a.target, thisArg = _a.thisArg; + return ts.setOriginalNode(ts.createFunctionApply(cacheExpression(ts.visitNode(target, visitor, ts.isLeftHandSideExpression)), thisArg, visitElements(node.arguments), + /*location*/ node), node); + } + return ts.visitEachChild(node, visitor, context); + } + function visitNewExpression(node) { + if (ts.forEach(node.arguments, containsYield)) { + // [source] + // new a.b(1, yield, 2); + // + // [intermediate] + // .local _a, _b, _c + // _b = (_a = a.b).bind; + // _c = [1]; + // .yield resumeLabel + // .mark resumeLabel + // new (_b.apply(_a, _c.concat([%sent%, 2]))); + var _a = ts.createCallBinding(ts.createPropertyAccess(node.expression, "bind"), hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg; + return ts.setOriginalNode(ts.setTextRange(ts.createNew(ts.createFunctionApply(cacheExpression(ts.visitNode(target, visitor, ts.isExpression)), thisArg, visitElements(node.arguments, + /*leadingElement*/ ts.createVoidZero())), + /*typeArguments*/ undefined, []), node), node); + } + return ts.visitEachChild(node, visitor, context); + } + function transformAndEmitStatements(statements, start) { + if (start === void 0) { start = 0; } + var numStatements = statements.length; + for (var i = start; i < numStatements; i++) { + transformAndEmitStatement(statements[i]); + } + } + function transformAndEmitEmbeddedStatement(node) { + if (ts.isBlock(node)) { + transformAndEmitStatements(node.statements); + } + else { + transformAndEmitStatement(node); + } + } + function transformAndEmitStatement(node) { + var savedInStatementContainingYield = inStatementContainingYield; + if (!inStatementContainingYield) { + inStatementContainingYield = containsYield(node); + } + transformAndEmitStatementWorker(node); + inStatementContainingYield = savedInStatementContainingYield; + } + function transformAndEmitStatementWorker(node) { + switch (node.kind) { + case 218 /* Block */: + return transformAndEmitBlock(node); + case 221 /* ExpressionStatement */: + return transformAndEmitExpressionStatement(node); + case 222 /* IfStatement */: + return transformAndEmitIfStatement(node); + case 223 /* DoStatement */: + return transformAndEmitDoStatement(node); + case 224 /* WhileStatement */: + return transformAndEmitWhileStatement(node); + case 225 /* ForStatement */: + return transformAndEmitForStatement(node); + case 226 /* ForInStatement */: + return transformAndEmitForInStatement(node); + case 228 /* ContinueStatement */: + return transformAndEmitContinueStatement(node); + case 229 /* BreakStatement */: + return transformAndEmitBreakStatement(node); + case 230 /* ReturnStatement */: + return transformAndEmitReturnStatement(node); + case 231 /* WithStatement */: + return transformAndEmitWithStatement(node); + case 232 /* SwitchStatement */: + return transformAndEmitSwitchStatement(node); + case 233 /* LabeledStatement */: + return transformAndEmitLabeledStatement(node); + case 234 /* ThrowStatement */: + return transformAndEmitThrowStatement(node); + case 235 /* TryStatement */: + return transformAndEmitTryStatement(node); + default: + return emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + } + function transformAndEmitBlock(node) { + if (containsYield(node)) { + transformAndEmitStatements(node.statements); + } + else { + emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + } + function transformAndEmitExpressionStatement(node) { + emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + function transformAndEmitVariableDeclarationList(node) { + for (var _i = 0, _a = node.declarations; _i < _a.length; _i++) { + var variable = _a[_i]; + var name = ts.getSynthesizedClone(variable.name); + ts.setCommentRange(name, variable.name); + hoistVariableDeclaration(name); + } + var variables = ts.getInitializedVariables(node); + var numVariables = variables.length; + var variablesWritten = 0; + var pendingExpressions = []; + while (variablesWritten < numVariables) { + for (var i = variablesWritten; i < numVariables; i++) { + var variable = variables[i]; + if (containsYield(variable.initializer) && pendingExpressions.length > 0) { + break; + } + pendingExpressions.push(transformInitializedVariable(variable)); + } + if (pendingExpressions.length) { + emitStatement(ts.createExpressionStatement(ts.inlineExpressions(pendingExpressions))); + variablesWritten += pendingExpressions.length; + pendingExpressions = []; + } + } + return undefined; + } + function transformInitializedVariable(node) { + return ts.setSourceMapRange(ts.createAssignment(ts.setSourceMapRange(ts.getSynthesizedClone(node.name), node.name), ts.visitNode(node.initializer, visitor, ts.isExpression)), node); + } + function transformAndEmitIfStatement(node) { + if (containsYield(node)) { + // [source] + // if (x) + // /*thenStatement*/ + // else + // /*elseStatement*/ + // + // [intermediate] + // .brfalse elseLabel, (x) + // /*thenStatement*/ + // .br endLabel + // .mark elseLabel + // /*elseStatement*/ + // .mark endLabel + if (containsYield(node.thenStatement) || containsYield(node.elseStatement)) { + var endLabel = defineLabel(); + var elseLabel = node.elseStatement ? defineLabel() : undefined; + emitBreakWhenFalse(node.elseStatement ? elseLabel : endLabel, ts.visitNode(node.expression, visitor, ts.isExpression), /*location*/ node.expression); + transformAndEmitEmbeddedStatement(node.thenStatement); + if (node.elseStatement) { + emitBreak(endLabel); + markLabel(elseLabel); + transformAndEmitEmbeddedStatement(node.elseStatement); + } + markLabel(endLabel); + } + else { + emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + } + else { + emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + } + function transformAndEmitDoStatement(node) { + if (containsYield(node)) { + // [source] + // do { + // /*body*/ + // } + // while (i < 10); + // + // [intermediate] + // .loop conditionLabel, endLabel + // .mark loopLabel + // /*body*/ + // .mark conditionLabel + // .brtrue loopLabel, (i < 10) + // .endloop + // .mark endLabel + var conditionLabel = defineLabel(); + var loopLabel = defineLabel(); + beginLoopBlock(/*continueLabel*/ conditionLabel); + markLabel(loopLabel); + transformAndEmitEmbeddedStatement(node.statement); + markLabel(conditionLabel); + emitBreakWhenTrue(loopLabel, ts.visitNode(node.expression, visitor, ts.isExpression)); + endLoopBlock(); + } + else { + emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + } + function visitDoStatement(node) { + if (inStatementContainingYield) { + beginScriptLoopBlock(); + node = ts.visitEachChild(node, visitor, context); + endLoopBlock(); + return node; + } + else { + return ts.visitEachChild(node, visitor, context); + } + } + function transformAndEmitWhileStatement(node) { + if (containsYield(node)) { + // [source] + // while (i < 10) { + // /*body*/ + // } + // + // [intermediate] + // .loop loopLabel, endLabel + // .mark loopLabel + // .brfalse endLabel, (i < 10) + // /*body*/ + // .br loopLabel + // .endloop + // .mark endLabel + var loopLabel = defineLabel(); + var endLabel = beginLoopBlock(loopLabel); + markLabel(loopLabel); + emitBreakWhenFalse(endLabel, ts.visitNode(node.expression, visitor, ts.isExpression)); + transformAndEmitEmbeddedStatement(node.statement); + emitBreak(loopLabel); + endLoopBlock(); + } + else { + emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + } + function visitWhileStatement(node) { + if (inStatementContainingYield) { + beginScriptLoopBlock(); + node = ts.visitEachChild(node, visitor, context); + endLoopBlock(); + return node; + } + else { + return ts.visitEachChild(node, visitor, context); + } + } + function transformAndEmitForStatement(node) { + if (containsYield(node)) { + // [source] + // for (var i = 0; i < 10; i++) { + // /*body*/ + // } + // + // [intermediate] + // .local i + // i = 0; + // .loop incrementLabel, endLoopLabel + // .mark conditionLabel + // .brfalse endLoopLabel, (i < 10) + // /*body*/ + // .mark incrementLabel + // i++; + // .br conditionLabel + // .endloop + // .mark endLoopLabel + var conditionLabel = defineLabel(); + var incrementLabel = defineLabel(); + var endLabel = beginLoopBlock(incrementLabel); + if (node.initializer) { + var initializer = node.initializer; + if (ts.isVariableDeclarationList(initializer)) { + transformAndEmitVariableDeclarationList(initializer); + } + else { + emitStatement(ts.setTextRange(ts.createExpressionStatement(ts.visitNode(initializer, visitor, ts.isExpression)), initializer)); + } + } + markLabel(conditionLabel); + if (node.condition) { + emitBreakWhenFalse(endLabel, ts.visitNode(node.condition, visitor, ts.isExpression)); + } + transformAndEmitEmbeddedStatement(node.statement); + markLabel(incrementLabel); + if (node.incrementor) { + emitStatement(ts.setTextRange(ts.createExpressionStatement(ts.visitNode(node.incrementor, visitor, ts.isExpression)), node.incrementor)); + } + emitBreak(conditionLabel); + endLoopBlock(); + } + else { + emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + } + function visitForStatement(node) { + if (inStatementContainingYield) { + beginScriptLoopBlock(); + } + var initializer = node.initializer; + if (initializer && ts.isVariableDeclarationList(initializer)) { + for (var _i = 0, _a = initializer.declarations; _i < _a.length; _i++) { + var variable = _a[_i]; + hoistVariableDeclaration(variable.name); + } + var variables = ts.getInitializedVariables(initializer); + node = ts.updateFor(node, variables.length > 0 + ? ts.inlineExpressions(ts.map(variables, transformInitializedVariable)) + : undefined, ts.visitNode(node.condition, visitor, ts.isExpression), ts.visitNode(node.incrementor, visitor, ts.isExpression), ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); + } + else { + node = ts.visitEachChild(node, visitor, context); + } + if (inStatementContainingYield) { + endLoopBlock(); + } + return node; + } + function transformAndEmitForInStatement(node) { + // TODO(rbuckton): Source map locations + if (containsYield(node)) { + // [source] + // for (var p in o) { + // /*body*/ + // } + // + // [intermediate] + // .local _a, _b, _i + // _a = []; + // for (_b in o) _a.push(_b); + // _i = 0; + // .loop incrementLabel, endLoopLabel + // .mark conditionLabel + // .brfalse endLoopLabel, (_i < _a.length) + // p = _a[_i]; + // /*body*/ + // .mark incrementLabel + // _b++; + // .br conditionLabel + // .endloop + // .mark endLoopLabel + var keysArray = declareLocal(); // _a + var key = declareLocal(); // _b + var keysIndex = ts.createLoopVariable(); // _i + var initializer = node.initializer; + hoistVariableDeclaration(keysIndex); + emitAssignment(keysArray, ts.createArrayLiteral()); + emitStatement(ts.createForIn(key, ts.visitNode(node.expression, visitor, ts.isExpression), ts.createExpressionStatement(ts.createCall(ts.createPropertyAccess(keysArray, "push"), + /*typeArguments*/ undefined, [key])))); + emitAssignment(keysIndex, ts.createLiteral(0)); + var conditionLabel = defineLabel(); + var incrementLabel = defineLabel(); + var endLabel = beginLoopBlock(incrementLabel); + markLabel(conditionLabel); + emitBreakWhenFalse(endLabel, ts.createLessThan(keysIndex, ts.createPropertyAccess(keysArray, "length"))); + var variable = void 0; + if (ts.isVariableDeclarationList(initializer)) { + for (var _i = 0, _a = initializer.declarations; _i < _a.length; _i++) { + var variable_1 = _a[_i]; + hoistVariableDeclaration(variable_1.name); + } + variable = ts.getSynthesizedClone(initializer.declarations[0].name); + } + else { + variable = ts.visitNode(initializer, visitor, ts.isExpression); + ts.Debug.assert(ts.isLeftHandSideExpression(variable)); + } + emitAssignment(variable, ts.createElementAccess(keysArray, keysIndex)); + transformAndEmitEmbeddedStatement(node.statement); + markLabel(incrementLabel); + emitStatement(ts.createExpressionStatement(ts.createPostfixIncrement(keysIndex))); + emitBreak(conditionLabel); + endLoopBlock(); + } + else { + emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + } + function visitForInStatement(node) { + // [source] + // for (var x in a) { + // /*body*/ + // } + // + // [intermediate] + // .local x + // .loop + // for (x in a) { + // /*body*/ + // } + // .endloop + if (inStatementContainingYield) { + beginScriptLoopBlock(); + } + var initializer = node.initializer; + if (ts.isVariableDeclarationList(initializer)) { + for (var _i = 0, _a = initializer.declarations; _i < _a.length; _i++) { + var variable = _a[_i]; + hoistVariableDeclaration(variable.name); + } + node = ts.updateForIn(node, initializer.declarations[0].name, ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); + } + else { + node = ts.visitEachChild(node, visitor, context); + } + if (inStatementContainingYield) { + endLoopBlock(); + } + return node; + } + function transformAndEmitContinueStatement(node) { + var label = findContinueTarget(node.label ? ts.idText(node.label) : undefined); + if (label > 0) { + emitBreak(label, /*location*/ node); + } + else { + // invalid continue without a containing loop. Leave the node as is, per #17875. + emitStatement(node); + } + } + function visitContinueStatement(node) { + if (inStatementContainingYield) { + var label = findContinueTarget(node.label && ts.idText(node.label)); + if (label > 0) { + return createInlineBreak(label, /*location*/ node); + } + } + return ts.visitEachChild(node, visitor, context); + } + function transformAndEmitBreakStatement(node) { + var label = findBreakTarget(node.label ? ts.idText(node.label) : undefined); + if (label > 0) { + emitBreak(label, /*location*/ node); + } + else { + // invalid break without a containing loop, switch, or labeled statement. Leave the node as is, per #17875. + emitStatement(node); + } + } + function visitBreakStatement(node) { + if (inStatementContainingYield) { + var label = findBreakTarget(node.label && ts.idText(node.label)); + if (label > 0) { + return createInlineBreak(label, /*location*/ node); + } + } + return ts.visitEachChild(node, visitor, context); + } + function transformAndEmitReturnStatement(node) { + emitReturn(ts.visitNode(node.expression, visitor, ts.isExpression), + /*location*/ node); + } + function visitReturnStatement(node) { + return createInlineReturn(ts.visitNode(node.expression, visitor, ts.isExpression), + /*location*/ node); + } + function transformAndEmitWithStatement(node) { + if (containsYield(node)) { + // [source] + // with (x) { + // /*body*/ + // } + // + // [intermediate] + // .with (x) + // /*body*/ + // .endwith + beginWithBlock(cacheExpression(ts.visitNode(node.expression, visitor, ts.isExpression))); + transformAndEmitEmbeddedStatement(node.statement); + endWithBlock(); + } + else { + emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + } + function transformAndEmitSwitchStatement(node) { + if (containsYield(node.caseBlock)) { + // [source] + // switch (x) { + // case a: + // /*caseStatements*/ + // case b: + // /*caseStatements*/ + // default: + // /*defaultStatements*/ + // } + // + // [intermediate] + // .local _a + // .switch endLabel + // _a = x; + // switch (_a) { + // case a: + // .br clauseLabels[0] + // } + // switch (_a) { + // case b: + // .br clauseLabels[1] + // } + // .br clauseLabels[2] + // .mark clauseLabels[0] + // /*caseStatements*/ + // .mark clauseLabels[1] + // /*caseStatements*/ + // .mark clauseLabels[2] + // /*caseStatements*/ + // .endswitch + // .mark endLabel + var caseBlock = node.caseBlock; + var numClauses = caseBlock.clauses.length; + var endLabel = beginSwitchBlock(); + var expression = cacheExpression(ts.visitNode(node.expression, visitor, ts.isExpression)); + // Create labels for each clause and find the index of the first default clause. + var clauseLabels = []; + var defaultClauseIndex = -1; + for (var i = 0; i < numClauses; i++) { + var clause = caseBlock.clauses[i]; + clauseLabels.push(defineLabel()); + if (clause.kind === 272 /* DefaultClause */ && defaultClauseIndex === -1) { + defaultClauseIndex = i; + } + } + // Emit switch statements for each run of case clauses either from the first case + // clause or the next case clause with a `yield` in its expression, up to the next + // case clause with a `yield` in its expression. + var clausesWritten = 0; + var pendingClauses = []; + while (clausesWritten < numClauses) { + var defaultClausesSkipped = 0; + for (var i = clausesWritten; i < numClauses; i++) { + var clause = caseBlock.clauses[i]; + if (clause.kind === 271 /* CaseClause */) { + if (containsYield(clause.expression) && pendingClauses.length > 0) { + break; + } + pendingClauses.push(ts.createCaseClause(ts.visitNode(clause.expression, visitor, ts.isExpression), [ + createInlineBreak(clauseLabels[i], /*location*/ clause.expression) + ])); + } + else { + defaultClausesSkipped++; + } + } + if (pendingClauses.length) { + emitStatement(ts.createSwitch(expression, ts.createCaseBlock(pendingClauses))); + clausesWritten += pendingClauses.length; + pendingClauses = []; + } + if (defaultClausesSkipped > 0) { + clausesWritten += defaultClausesSkipped; + defaultClausesSkipped = 0; + } + } + if (defaultClauseIndex >= 0) { + emitBreak(clauseLabels[defaultClauseIndex]); + } + else { + emitBreak(endLabel); + } + for (var i = 0; i < numClauses; i++) { + markLabel(clauseLabels[i]); + transformAndEmitStatements(caseBlock.clauses[i].statements); + } + endSwitchBlock(); + } + else { + emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + } + function visitSwitchStatement(node) { + if (inStatementContainingYield) { + beginScriptSwitchBlock(); + } + node = ts.visitEachChild(node, visitor, context); + if (inStatementContainingYield) { + endSwitchBlock(); + } + return node; + } + function transformAndEmitLabeledStatement(node) { + if (containsYield(node)) { + // [source] + // x: { + // /*body*/ + // } + // + // [intermediate] + // .labeled "x", endLabel + // /*body*/ + // .endlabeled + // .mark endLabel + beginLabeledBlock(ts.idText(node.label)); + transformAndEmitEmbeddedStatement(node.statement); + endLabeledBlock(); + } + else { + emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + } + function visitLabeledStatement(node) { + if (inStatementContainingYield) { + beginScriptLabeledBlock(ts.idText(node.label)); + } + node = ts.visitEachChild(node, visitor, context); + if (inStatementContainingYield) { + endLabeledBlock(); + } + return node; + } + function transformAndEmitThrowStatement(node) { + emitThrow(ts.visitNode(node.expression, visitor, ts.isExpression), + /*location*/ node); + } + function transformAndEmitTryStatement(node) { + if (containsYield(node)) { + // [source] + // try { + // /*tryBlock*/ + // } + // catch (e) { + // /*catchBlock*/ + // } + // finally { + // /*finallyBlock*/ + // } + // + // [intermediate] + // .local _a + // .try tryLabel, catchLabel, finallyLabel, endLabel + // .mark tryLabel + // .nop + // /*tryBlock*/ + // .br endLabel + // .catch + // .mark catchLabel + // _a = %error%; + // /*catchBlock*/ + // .br endLabel + // .finally + // .mark finallyLabel + // /*finallyBlock*/ + // .endfinally + // .endtry + // .mark endLabel + beginExceptionBlock(); + transformAndEmitEmbeddedStatement(node.tryBlock); + if (node.catchClause) { + beginCatchBlock(node.catchClause.variableDeclaration); // TODO: GH#18217 + transformAndEmitEmbeddedStatement(node.catchClause.block); + } + if (node.finallyBlock) { + beginFinallyBlock(); + transformAndEmitEmbeddedStatement(node.finallyBlock); + } + endExceptionBlock(); + } + else { + emitStatement(ts.visitEachChild(node, visitor, context)); + } + } + function containsYield(node) { + return !!node && (node.transformFlags & 4194304 /* ContainsYield */) !== 0; + } + function countInitialNodesWithoutYield(nodes) { + var numNodes = nodes.length; + for (var i = 0; i < numNodes; i++) { + if (containsYield(nodes[i])) { + return i; + } + } + return -1; + } + function onSubstituteNode(hint, node) { + node = previousOnSubstituteNode(hint, node); + if (hint === 1 /* Expression */) { + return substituteExpression(node); + } + return node; + } + function substituteExpression(node) { + if (ts.isIdentifier(node)) { + return substituteExpressionIdentifier(node); + } + return node; + } + function substituteExpressionIdentifier(node) { + if (!ts.isGeneratedIdentifier(node) && renamedCatchVariables && renamedCatchVariables.has(ts.idText(node))) { + var original = ts.getOriginalNode(node); + if (ts.isIdentifier(original) && original.parent) { + var declaration = resolver.getReferencedValueDeclaration(original); + if (declaration) { + var name = renamedCatchVariableDeclarations[ts.getOriginalNodeId(declaration)]; + if (name) { + var clone_7 = ts.getMutableClone(name); + ts.setSourceMapRange(clone_7, node); + ts.setCommentRange(clone_7, node); + return clone_7; + } + } + } + } + return node; + } + function cacheExpression(node) { + var temp; + if (ts.isGeneratedIdentifier(node) || ts.getEmitFlags(node) & 4096 /* HelperName */) { + return node; + } + temp = ts.createTempVariable(hoistVariableDeclaration); + emitAssignment(temp, node, /*location*/ node); + return temp; + } + function declareLocal(name) { + var temp = name + ? ts.createUniqueName(name) + : ts.createTempVariable(/*recordTempVariable*/ undefined); + hoistVariableDeclaration(temp); + return temp; + } + /** + * Defines a label, uses as the target of a Break operation. + */ + function defineLabel() { + if (!labelOffsets) { + labelOffsets = []; + } + var label = nextLabelId; + nextLabelId++; + labelOffsets[label] = -1; + return label; + } + /** + * Marks the current operation with the specified label. + */ + function markLabel(label) { + ts.Debug.assert(labelOffsets !== undefined, "No labels were defined."); + labelOffsets[label] = operations ? operations.length : 0; + } + /** + * Begins a block operation (With, Break/Continue, Try/Catch/Finally) + * + * @param block Information about the block. + */ + function beginBlock(block) { + if (!blocks) { + blocks = []; + blockActions = []; + blockOffsets = []; + blockStack = []; + } + var index = blockActions.length; + blockActions[index] = 0 /* Open */; + blockOffsets[index] = operations ? operations.length : 0; + blocks[index] = block; + blockStack.push(block); + return index; + } + /** + * Ends the current block operation. + */ + function endBlock() { + var block = peekBlock(); + if (block === undefined) + return ts.Debug.fail("beginBlock was never called."); + var index = blockActions.length; + blockActions[index] = 1 /* Close */; + blockOffsets[index] = operations ? operations.length : 0; + blocks[index] = block; + blockStack.pop(); + return block; + } + /** + * Gets the current open block. + */ + function peekBlock() { + return ts.lastOrUndefined(blockStack); + } + /** + * Gets the kind of the current open block. + */ + function peekBlockKind() { + var block = peekBlock(); + return block && block.kind; + } + /** + * Begins a code block for a generated `with` statement. + * + * @param expression An identifier representing expression for the `with` block. + */ + function beginWithBlock(expression) { + var startLabel = defineLabel(); + var endLabel = defineLabel(); + markLabel(startLabel); + beginBlock({ + kind: 1 /* With */, + expression: expression, + startLabel: startLabel, + endLabel: endLabel + }); + } + /** + * Ends a code block for a generated `with` statement. + */ + function endWithBlock() { + ts.Debug.assert(peekBlockKind() === 1 /* With */); + var block = endBlock(); + markLabel(block.endLabel); + } + /** + * Begins a code block for a generated `try` statement. + */ + function beginExceptionBlock() { + var startLabel = defineLabel(); + var endLabel = defineLabel(); + markLabel(startLabel); + beginBlock({ + kind: 0 /* Exception */, + state: 0 /* Try */, + startLabel: startLabel, + endLabel: endLabel + }); + emitNop(); + return endLabel; + } + /** + * Enters the `catch` clause of a generated `try` statement. + * + * @param variable The catch variable. + */ + function beginCatchBlock(variable) { + ts.Debug.assert(peekBlockKind() === 0 /* Exception */); + // generated identifiers should already be unique within a file + var name; + if (ts.isGeneratedIdentifier(variable.name)) { + name = variable.name; + hoistVariableDeclaration(variable.name); + } + else { + var text = ts.idText(variable.name); + name = declareLocal(text); + if (!renamedCatchVariables) { + renamedCatchVariables = ts.createMap(); + renamedCatchVariableDeclarations = []; + context.enableSubstitution(72 /* Identifier */); + } + renamedCatchVariables.set(text, true); + renamedCatchVariableDeclarations[ts.getOriginalNodeId(variable)] = name; + } + var exception = peekBlock(); + ts.Debug.assert(exception.state < 1 /* Catch */); + var endLabel = exception.endLabel; + emitBreak(endLabel); + var catchLabel = defineLabel(); + markLabel(catchLabel); + exception.state = 1 /* Catch */; + exception.catchVariable = name; + exception.catchLabel = catchLabel; + emitAssignment(name, ts.createCall(ts.createPropertyAccess(state, "sent"), /*typeArguments*/ undefined, [])); + emitNop(); + } + /** + * Enters the `finally` block of a generated `try` statement. + */ + function beginFinallyBlock() { + ts.Debug.assert(peekBlockKind() === 0 /* Exception */); + var exception = peekBlock(); + ts.Debug.assert(exception.state < 2 /* Finally */); + var endLabel = exception.endLabel; + emitBreak(endLabel); + var finallyLabel = defineLabel(); + markLabel(finallyLabel); + exception.state = 2 /* Finally */; + exception.finallyLabel = finallyLabel; + } + /** + * Ends the code block for a generated `try` statement. + */ + function endExceptionBlock() { + ts.Debug.assert(peekBlockKind() === 0 /* Exception */); + var exception = endBlock(); + var state = exception.state; + if (state < 2 /* Finally */) { + emitBreak(exception.endLabel); + } + else { + emitEndfinally(); + } + markLabel(exception.endLabel); + emitNop(); + exception.state = 3 /* Done */; + } + /** + * Begins a code block that supports `break` or `continue` statements that are defined in + * the source tree and not from generated code. + * + * @param labelText Names from containing labeled statements. + */ + function beginScriptLoopBlock() { + beginBlock({ + kind: 3 /* Loop */, + isScript: true, + breakLabel: -1, + continueLabel: -1 + }); + } + /** + * Begins a code block that supports `break` or `continue` statements that are defined in + * generated code. Returns a label used to mark the operation to which to jump when a + * `break` statement targets this block. + * + * @param continueLabel A Label used to mark the operation to which to jump when a + * `continue` statement targets this block. + */ + function beginLoopBlock(continueLabel) { + var breakLabel = defineLabel(); + beginBlock({ + kind: 3 /* Loop */, + isScript: false, + breakLabel: breakLabel, + continueLabel: continueLabel, + }); + return breakLabel; + } + /** + * Ends a code block that supports `break` or `continue` statements that are defined in + * generated code or in the source tree. + */ + function endLoopBlock() { + ts.Debug.assert(peekBlockKind() === 3 /* Loop */); + var block = endBlock(); + var breakLabel = block.breakLabel; + if (!block.isScript) { + markLabel(breakLabel); + } + } + /** + * Begins a code block that supports `break` statements that are defined in the source + * tree and not from generated code. + * + */ + function beginScriptSwitchBlock() { + beginBlock({ + kind: 2 /* Switch */, + isScript: true, + breakLabel: -1 + }); + } + /** + * Begins a code block that supports `break` statements that are defined in generated code. + * Returns a label used to mark the operation to which to jump when a `break` statement + * targets this block. + */ + function beginSwitchBlock() { + var breakLabel = defineLabel(); + beginBlock({ + kind: 2 /* Switch */, + isScript: false, + breakLabel: breakLabel, + }); + return breakLabel; + } + /** + * Ends a code block that supports `break` statements that are defined in generated code. + */ + function endSwitchBlock() { + ts.Debug.assert(peekBlockKind() === 2 /* Switch */); + var block = endBlock(); + var breakLabel = block.breakLabel; + if (!block.isScript) { + markLabel(breakLabel); + } + } + function beginScriptLabeledBlock(labelText) { + beginBlock({ + kind: 4 /* Labeled */, + isScript: true, + labelText: labelText, + breakLabel: -1 + }); + } + function beginLabeledBlock(labelText) { + var breakLabel = defineLabel(); + beginBlock({ + kind: 4 /* Labeled */, + isScript: false, + labelText: labelText, + breakLabel: breakLabel + }); + } + function endLabeledBlock() { + ts.Debug.assert(peekBlockKind() === 4 /* Labeled */); + var block = endBlock(); + if (!block.isScript) { + markLabel(block.breakLabel); + } + } + /** + * Indicates whether the provided block supports `break` statements. + * + * @param block A code block. + */ + function supportsUnlabeledBreak(block) { + return block.kind === 2 /* Switch */ + || block.kind === 3 /* Loop */; + } + /** + * Indicates whether the provided block supports `break` statements with labels. + * + * @param block A code block. + */ + function supportsLabeledBreakOrContinue(block) { + return block.kind === 4 /* Labeled */; + } + /** + * Indicates whether the provided block supports `continue` statements. + * + * @param block A code block. + */ + function supportsUnlabeledContinue(block) { + return block.kind === 3 /* Loop */; + } + function hasImmediateContainingLabeledBlock(labelText, start) { + for (var j = start; j >= 0; j--) { + var containingBlock = blockStack[j]; + if (supportsLabeledBreakOrContinue(containingBlock)) { + if (containingBlock.labelText === labelText) { + return true; + } + } + else { + break; + } + } + return false; + } + /** + * Finds the label that is the target for a `break` statement. + * + * @param labelText An optional name of a containing labeled statement. + */ + function findBreakTarget(labelText) { + if (blockStack) { + if (labelText) { + for (var i = blockStack.length - 1; i >= 0; i--) { + var block = blockStack[i]; + if (supportsLabeledBreakOrContinue(block) && block.labelText === labelText) { + return block.breakLabel; + } + else if (supportsUnlabeledBreak(block) && hasImmediateContainingLabeledBlock(labelText, i - 1)) { + return block.breakLabel; + } + } + } + else { + for (var i = blockStack.length - 1; i >= 0; i--) { + var block = blockStack[i]; + if (supportsUnlabeledBreak(block)) { + return block.breakLabel; + } + } + } + } + return 0; + } + /** + * Finds the label that is the target for a `continue` statement. + * + * @param labelText An optional name of a containing labeled statement. + */ + function findContinueTarget(labelText) { + if (blockStack) { + if (labelText) { + for (var i = blockStack.length - 1; i >= 0; i--) { + var block = blockStack[i]; + if (supportsUnlabeledContinue(block) && hasImmediateContainingLabeledBlock(labelText, i - 1)) { + return block.continueLabel; + } + } + } + else { + for (var i = blockStack.length - 1; i >= 0; i--) { + var block = blockStack[i]; + if (supportsUnlabeledContinue(block)) { + return block.continueLabel; + } + } + } + } + return 0; + } + /** + * Creates an expression that can be used to indicate the value for a label. + * + * @param label A label. + */ + function createLabel(label) { + if (label !== undefined && label > 0) { + if (labelExpressions === undefined) { + labelExpressions = []; + } + var expression = ts.createLiteral(-1); + if (labelExpressions[label] === undefined) { + labelExpressions[label] = [expression]; + } + else { + labelExpressions[label].push(expression); + } + return expression; + } + return ts.createOmittedExpression(); + } + /** + * Creates a numeric literal for the provided instruction. + */ + function createInstruction(instruction) { + var literal = ts.createLiteral(instruction); + ts.addSyntheticTrailingComment(literal, 3 /* MultiLineCommentTrivia */, getInstructionName(instruction)); + return literal; + } + /** + * Creates a statement that can be used indicate a Break operation to the provided label. + * + * @param label A label. + * @param location An optional source map location for the statement. + */ + function createInlineBreak(label, location) { + ts.Debug.assertLessThan(0, label, "Invalid label"); + return ts.setTextRange(ts.createReturn(ts.createArrayLiteral([ + createInstruction(3 /* Break */), + createLabel(label) + ])), location); + } + /** + * Creates a statement that can be used indicate a Return operation. + * + * @param expression The expression for the return statement. + * @param location An optional source map location for the statement. + */ + function createInlineReturn(expression, location) { + return ts.setTextRange(ts.createReturn(ts.createArrayLiteral(expression + ? [createInstruction(2 /* Return */), expression] + : [createInstruction(2 /* Return */)])), location); + } + /** + * Creates an expression that can be used to resume from a Yield operation. + */ + function createGeneratorResume(location) { + return ts.setTextRange(ts.createCall(ts.createPropertyAccess(state, "sent"), + /*typeArguments*/ undefined, []), location); + } + /** + * Emits an empty instruction. + */ + function emitNop() { + emitWorker(0 /* Nop */); + } + /** + * Emits a Statement. + * + * @param node A statement. + */ + function emitStatement(node) { + if (node) { + emitWorker(1 /* Statement */, [node]); + } + else { + emitNop(); + } + } + /** + * Emits an Assignment operation. + * + * @param left The left-hand side of the assignment. + * @param right The right-hand side of the assignment. + * @param location An optional source map location for the assignment. + */ + function emitAssignment(left, right, location) { + emitWorker(2 /* Assign */, [left, right], location); + } + /** + * Emits a Break operation to the specified label. + * + * @param label A label. + * @param location An optional source map location for the assignment. + */ + function emitBreak(label, location) { + emitWorker(3 /* Break */, [label], location); + } + /** + * Emits a Break operation to the specified label when a condition evaluates to a truthy + * value at runtime. + * + * @param label A label. + * @param condition The condition. + * @param location An optional source map location for the assignment. + */ + function emitBreakWhenTrue(label, condition, location) { + emitWorker(4 /* BreakWhenTrue */, [label, condition], location); + } + /** + * Emits a Break to the specified label when a condition evaluates to a falsey value at + * runtime. + * + * @param label A label. + * @param condition The condition. + * @param location An optional source map location for the assignment. + */ + function emitBreakWhenFalse(label, condition, location) { + emitWorker(5 /* BreakWhenFalse */, [label, condition], location); + } + /** + * Emits a YieldStar operation for the provided expression. + * + * @param expression An optional value for the yield operation. + * @param location An optional source map location for the assignment. + */ + function emitYieldStar(expression, location) { + emitWorker(7 /* YieldStar */, [expression], location); + } + /** + * Emits a Yield operation for the provided expression. + * + * @param expression An optional value for the yield operation. + * @param location An optional source map location for the assignment. + */ + function emitYield(expression, location) { + emitWorker(6 /* Yield */, [expression], location); + } + /** + * Emits a Return operation for the provided expression. + * + * @param expression An optional value for the operation. + * @param location An optional source map location for the assignment. + */ + function emitReturn(expression, location) { + emitWorker(8 /* Return */, [expression], location); + } + /** + * Emits a Throw operation for the provided expression. + * + * @param expression A value for the operation. + * @param location An optional source map location for the assignment. + */ + function emitThrow(expression, location) { + emitWorker(9 /* Throw */, [expression], location); + } + /** + * Emits an Endfinally operation. This is used to handle `finally` block semantics. + */ + function emitEndfinally() { + emitWorker(10 /* Endfinally */); + } + /** + * Emits an operation. + * + * @param code The OpCode for the operation. + * @param args The optional arguments for the operation. + */ + function emitWorker(code, args, location) { + if (operations === undefined) { + operations = []; + operationArguments = []; + operationLocations = []; + } + if (labelOffsets === undefined) { + // mark entry point + markLabel(defineLabel()); + } + var operationIndex = operations.length; + operations[operationIndex] = code; + operationArguments[operationIndex] = args; + operationLocations[operationIndex] = location; + } + /** + * Builds the generator function body. + */ + function build() { + blockIndex = 0; + labelNumber = 0; + labelNumbers = undefined; + lastOperationWasAbrupt = false; + lastOperationWasCompletion = false; + clauses = undefined; + statements = undefined; + exceptionBlockStack = undefined; + currentExceptionBlock = undefined; + withBlockStack = undefined; + var buildResult = buildStatements(); + return createGeneratorHelper(context, ts.setEmitFlags(ts.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, state)], + /*type*/ undefined, ts.createBlock(buildResult, + /*multiLine*/ buildResult.length > 0)), 524288 /* ReuseTempVariableScope */)); + } + /** + * Builds the statements for the generator function body. + */ + function buildStatements() { + if (operations) { + for (var operationIndex = 0; operationIndex < operations.length; operationIndex++) { + writeOperation(operationIndex); + } + flushFinalLabel(operations.length); + } + else { + flushFinalLabel(0); + } + if (clauses) { + var labelExpression = ts.createPropertyAccess(state, "label"); + var switchStatement = ts.createSwitch(labelExpression, ts.createCaseBlock(clauses)); + return [ts.startOnNewLine(switchStatement)]; + } + if (statements) { + return statements; + } + return []; + } + /** + * Flush the current label and advance to a new label. + */ + function flushLabel() { + if (!statements) { + return; + } + appendLabel(/*markLabelEnd*/ !lastOperationWasAbrupt); + lastOperationWasAbrupt = false; + lastOperationWasCompletion = false; + labelNumber++; + } + /** + * Flush the final label of the generator function body. + */ + function flushFinalLabel(operationIndex) { + if (isFinalLabelReachable(operationIndex)) { + tryEnterLabel(operationIndex); + withBlockStack = undefined; + writeReturn(/*expression*/ undefined, /*operationLocation*/ undefined); + } + if (statements && clauses) { + appendLabel(/*markLabelEnd*/ false); + } + updateLabelExpressions(); + } + /** + * Tests whether the final label of the generator function body + * is reachable by user code. + */ + function isFinalLabelReachable(operationIndex) { + // if the last operation was *not* a completion (return/throw) then + // the final label is reachable. + if (!lastOperationWasCompletion) { + return true; + } + // if there are no labels defined or referenced, then the final label is + // not reachable. + if (!labelOffsets || !labelExpressions) { + return false; + } + // if the label for this offset is referenced, then the final label + // is reachable. + for (var label = 0; label < labelOffsets.length; label++) { + if (labelOffsets[label] === operationIndex && labelExpressions[label]) { + return true; + } + } + return false; + } + /** + * Appends a case clause for the last label and sets the new label. + * + * @param markLabelEnd Indicates that the transition between labels was a fall-through + * from a previous case clause and the change in labels should be + * reflected on the `state` object. + */ + function appendLabel(markLabelEnd) { + if (!clauses) { + clauses = []; + } + if (statements) { + if (withBlockStack) { + // The previous label was nested inside one or more `with` blocks, so we + // surround the statements in generated `with` blocks to create the same environment. + for (var i = withBlockStack.length - 1; i >= 0; i--) { + var withBlock = withBlockStack[i]; + statements = [ts.createWith(withBlock.expression, ts.createBlock(statements))]; + } + } + if (currentExceptionBlock) { + // The previous label was nested inside of an exception block, so we must + // indicate entry into a protected region by pushing the label numbers + // for each block in the protected region. + var startLabel = currentExceptionBlock.startLabel, catchLabel = currentExceptionBlock.catchLabel, finallyLabel = currentExceptionBlock.finallyLabel, endLabel = currentExceptionBlock.endLabel; + statements.unshift(ts.createExpressionStatement(ts.createCall(ts.createPropertyAccess(ts.createPropertyAccess(state, "trys"), "push"), + /*typeArguments*/ undefined, [ + ts.createArrayLiteral([ + createLabel(startLabel), + createLabel(catchLabel), + createLabel(finallyLabel), + createLabel(endLabel) + ]) + ]))); + currentExceptionBlock = undefined; + } + if (markLabelEnd) { + // The case clause for the last label falls through to this label, so we + // add an assignment statement to reflect the change in labels. + statements.push(ts.createExpressionStatement(ts.createAssignment(ts.createPropertyAccess(state, "label"), ts.createLiteral(labelNumber + 1)))); + } + } + clauses.push(ts.createCaseClause(ts.createLiteral(labelNumber), statements || [])); + statements = undefined; + } + /** + * Tries to enter into a new label at the current operation index. + */ + function tryEnterLabel(operationIndex) { + if (!labelOffsets) { + return; + } + for (var label = 0; label < labelOffsets.length; label++) { + if (labelOffsets[label] === operationIndex) { + flushLabel(); + if (labelNumbers === undefined) { + labelNumbers = []; + } + if (labelNumbers[labelNumber] === undefined) { + labelNumbers[labelNumber] = [label]; + } + else { + labelNumbers[labelNumber].push(label); + } + } + } + } + /** + * Updates literal expressions for labels with actual label numbers. + */ + function updateLabelExpressions() { + if (labelExpressions !== undefined && labelNumbers !== undefined) { + for (var labelNumber_1 = 0; labelNumber_1 < labelNumbers.length; labelNumber_1++) { + var labels = labelNumbers[labelNumber_1]; + if (labels !== undefined) { + for (var _i = 0, labels_1 = labels; _i < labels_1.length; _i++) { + var label = labels_1[_i]; + var expressions = labelExpressions[label]; + if (expressions !== undefined) { + for (var _a = 0, expressions_1 = expressions; _a < expressions_1.length; _a++) { + var expression = expressions_1[_a]; + expression.text = String(labelNumber_1); + } + } + } + } + } + } + } + /** + * Tries to enter or leave a code block. + */ + function tryEnterOrLeaveBlock(operationIndex) { + if (blocks) { + for (; blockIndex < blockActions.length && blockOffsets[blockIndex] <= operationIndex; blockIndex++) { + var block = blocks[blockIndex]; + var blockAction = blockActions[blockIndex]; + switch (block.kind) { + case 0 /* Exception */: + if (blockAction === 0 /* Open */) { + if (!exceptionBlockStack) { + exceptionBlockStack = []; + } + if (!statements) { + statements = []; + } + exceptionBlockStack.push(currentExceptionBlock); + currentExceptionBlock = block; + } + else if (blockAction === 1 /* Close */) { + currentExceptionBlock = exceptionBlockStack.pop(); + } + break; + case 1 /* With */: + if (blockAction === 0 /* Open */) { + if (!withBlockStack) { + withBlockStack = []; + } + withBlockStack.push(block); + } + else if (blockAction === 1 /* Close */) { + withBlockStack.pop(); + } + break; + // default: do nothing + } + } + } + } + /** + * Writes an operation as a statement to the current label's statement list. + * + * @param operation The OpCode of the operation + */ + function writeOperation(operationIndex) { + tryEnterLabel(operationIndex); + tryEnterOrLeaveBlock(operationIndex); + // early termination, nothing else to process in this label + if (lastOperationWasAbrupt) { + return; + } + lastOperationWasAbrupt = false; + lastOperationWasCompletion = false; + var opcode = operations[operationIndex]; + if (opcode === 0 /* Nop */) { + return; + } + else if (opcode === 10 /* Endfinally */) { + return writeEndfinally(); + } + var args = operationArguments[operationIndex]; + if (opcode === 1 /* Statement */) { + return writeStatement(args[0]); + } + var location = operationLocations[operationIndex]; + switch (opcode) { + case 2 /* Assign */: + return writeAssign(args[0], args[1], location); + case 3 /* Break */: + return writeBreak(args[0], location); + case 4 /* BreakWhenTrue */: + return writeBreakWhenTrue(args[0], args[1], location); + case 5 /* BreakWhenFalse */: + return writeBreakWhenFalse(args[0], args[1], location); + case 6 /* Yield */: + return writeYield(args[0], location); + case 7 /* YieldStar */: + return writeYieldStar(args[0], location); + case 8 /* Return */: + return writeReturn(args[0], location); + case 9 /* Throw */: + return writeThrow(args[0], location); + } + } + /** + * Writes a statement to the current label's statement list. + * + * @param statement A statement to write. + */ + function writeStatement(statement) { + if (statement) { + if (!statements) { + statements = [statement]; + } + else { + statements.push(statement); + } + } + } + /** + * Writes an Assign operation to the current label's statement list. + * + * @param left The left-hand side of the assignment. + * @param right The right-hand side of the assignment. + * @param operationLocation The source map location for the operation. + */ + function writeAssign(left, right, operationLocation) { + writeStatement(ts.setTextRange(ts.createExpressionStatement(ts.createAssignment(left, right)), operationLocation)); + } + /** + * Writes a Throw operation to the current label's statement list. + * + * @param expression The value to throw. + * @param operationLocation The source map location for the operation. + */ + function writeThrow(expression, operationLocation) { + lastOperationWasAbrupt = true; + lastOperationWasCompletion = true; + writeStatement(ts.setTextRange(ts.createThrow(expression), operationLocation)); + } + /** + * Writes a Return operation to the current label's statement list. + * + * @param expression The value to return. + * @param operationLocation The source map location for the operation. + */ + function writeReturn(expression, operationLocation) { + lastOperationWasAbrupt = true; + lastOperationWasCompletion = true; + writeStatement(ts.setEmitFlags(ts.setTextRange(ts.createReturn(ts.createArrayLiteral(expression + ? [createInstruction(2 /* Return */), expression] + : [createInstruction(2 /* Return */)])), operationLocation), 384 /* NoTokenSourceMaps */)); + } + /** + * Writes a Break operation to the current label's statement list. + * + * @param label The label for the Break. + * @param operationLocation The source map location for the operation. + */ + function writeBreak(label, operationLocation) { + lastOperationWasAbrupt = true; + writeStatement(ts.setEmitFlags(ts.setTextRange(ts.createReturn(ts.createArrayLiteral([ + createInstruction(3 /* Break */), + createLabel(label) + ])), operationLocation), 384 /* NoTokenSourceMaps */)); + } + /** + * Writes a BreakWhenTrue operation to the current label's statement list. + * + * @param label The label for the Break. + * @param condition The condition for the Break. + * @param operationLocation The source map location for the operation. + */ + function writeBreakWhenTrue(label, condition, operationLocation) { + writeStatement(ts.setEmitFlags(ts.createIf(condition, ts.setEmitFlags(ts.setTextRange(ts.createReturn(ts.createArrayLiteral([ + createInstruction(3 /* Break */), + createLabel(label) + ])), operationLocation), 384 /* NoTokenSourceMaps */)), 1 /* SingleLine */)); + } + /** + * Writes a BreakWhenFalse operation to the current label's statement list. + * + * @param label The label for the Break. + * @param condition The condition for the Break. + * @param operationLocation The source map location for the operation. + */ + function writeBreakWhenFalse(label, condition, operationLocation) { + writeStatement(ts.setEmitFlags(ts.createIf(ts.createLogicalNot(condition), ts.setEmitFlags(ts.setTextRange(ts.createReturn(ts.createArrayLiteral([ + createInstruction(3 /* Break */), + createLabel(label) + ])), operationLocation), 384 /* NoTokenSourceMaps */)), 1 /* SingleLine */)); + } + /** + * Writes a Yield operation to the current label's statement list. + * + * @param expression The expression to yield. + * @param operationLocation The source map location for the operation. + */ + function writeYield(expression, operationLocation) { + lastOperationWasAbrupt = true; + writeStatement(ts.setEmitFlags(ts.setTextRange(ts.createReturn(ts.createArrayLiteral(expression + ? [createInstruction(4 /* Yield */), expression] + : [createInstruction(4 /* Yield */)])), operationLocation), 384 /* NoTokenSourceMaps */)); + } + /** + * Writes a YieldStar instruction to the current label's statement list. + * + * @param expression The expression to yield. + * @param operationLocation The source map location for the operation. + */ + function writeYieldStar(expression, operationLocation) { + lastOperationWasAbrupt = true; + writeStatement(ts.setEmitFlags(ts.setTextRange(ts.createReturn(ts.createArrayLiteral([ + createInstruction(5 /* YieldStar */), + expression + ])), operationLocation), 384 /* NoTokenSourceMaps */)); + } + /** + * Writes an Endfinally instruction to the current label's statement list. + */ + function writeEndfinally() { + lastOperationWasAbrupt = true; + writeStatement(ts.createReturn(ts.createArrayLiteral([ + createInstruction(7 /* Endfinally */) + ]))); + } + } + ts.transformGenerators = transformGenerators; + function createGeneratorHelper(context, body) { + context.requestEmitHelper(generatorHelper); + return ts.createCall(ts.getHelperName("__generator"), + /*typeArguments*/ undefined, [ts.createThis(), body]); + } + // The __generator helper is used by down-level transformations to emulate the runtime + // semantics of an ES2015 generator function. When called, this helper returns an + // object that implements the Iterator protocol, in that it has `next`, `return`, and + // `throw` methods that step through the generator when invoked. + // + // parameters: + // @param thisArg The value to use as the `this` binding for the transformed generator body. + // @param body A function that acts as the transformed generator body. + // + // variables: + // _ Persistent state for the generator that is shared between the helper and the + // generator body. The state object has the following members: + // sent() - A method that returns or throws the current completion value. + // label - The next point at which to resume evaluation of the generator body. + // trys - A stack of protected regions (try/catch/finally blocks). + // ops - A stack of pending instructions when inside of a finally block. + // f A value indicating whether the generator is executing. + // y An iterator to delegate for a yield*. + // t A temporary variable that holds one of the following values (note that these + // cases do not overlap): + // - The completion value when resuming from a `yield` or `yield*`. + // - The error value for a catch block. + // - The current protected region (array of try/catch/finally/end labels). + // - The verb (`next`, `throw`, or `return` method) to delegate to the expression + // of a `yield*`. + // - The result of evaluating the verb delegated to the expression of a `yield*`. + // + // functions: + // verb(n) Creates a bound callback to the `step` function for opcode `n`. + // step(op) Evaluates opcodes in a generator body until execution is suspended or + // completed. + // + // The __generator helper understands a limited set of instructions: + // 0: next(value?) - Start or resume the generator with the specified value. + // 1: throw(error) - Resume the generator with an exception. If the generator is + // suspended inside of one or more protected regions, evaluates + // any intervening finally blocks between the current label and + // the nearest catch block or function boundary. If uncaught, the + // exception is thrown to the caller. + // 2: return(value?) - Resume the generator as if with a return. If the generator is + // suspended inside of one or more protected regions, evaluates any + // intervening finally blocks. + // 3: break(label) - Jump to the specified label. If the label is outside of the + // current protected region, evaluates any intervening finally + // blocks. + // 4: yield(value?) - Yield execution to the caller with an optional value. When + // resumed, the generator will continue at the next label. + // 5: yield*(value) - Delegates evaluation to the supplied iterator. When + // delegation completes, the generator will continue at the next + // label. + // 6: catch(error) - Handles an exception thrown from within the generator body. If + // the current label is inside of one or more protected regions, + // evaluates any intervening finally blocks between the current + // label and the nearest catch block or function boundary. If + // uncaught, the exception is thrown to the caller. + // 7: endfinally - Ends a finally block, resuming the last instruction prior to + // entering a finally block. + // + // For examples of how these are used, see the comments in ./transformers/generators.ts + var generatorHelper = { + name: "typescript:generator", + scoped: false, + priority: 6, + text: "\n var __generator = (this && this.__generator) || function (thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (_) try {\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [op[0] & 2, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n };" + }; +})(ts || (ts = {})); +/*@internal*/ +var ts; +(function (ts) { + function transformModule(context) { + function getTransformModuleDelegate(moduleKind) { + switch (moduleKind) { + case ts.ModuleKind.AMD: return transformAMDModule; + case ts.ModuleKind.UMD: return transformUMDModule; + default: return transformCommonJSModule; + } + } + var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; + var compilerOptions = context.getCompilerOptions(); + var resolver = context.getEmitResolver(); + var host = context.getEmitHost(); + var languageVersion = ts.getEmitScriptTarget(compilerOptions); + var moduleKind = ts.getEmitModuleKind(compilerOptions); + var previousOnSubstituteNode = context.onSubstituteNode; + var previousOnEmitNode = context.onEmitNode; + context.onSubstituteNode = onSubstituteNode; + context.onEmitNode = onEmitNode; + context.enableSubstitution(72 /* Identifier */); // Substitutes expression identifiers with imported/exported symbols. + context.enableSubstitution(204 /* BinaryExpression */); // Substitutes assignments to exported symbols. + context.enableSubstitution(202 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols. + context.enableSubstitution(203 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols. + context.enableSubstitution(276 /* ShorthandPropertyAssignment */); // Substitutes shorthand property assignments for imported/exported symbols. + context.enableEmitNotification(279 /* SourceFile */); // Restore state when substituting nodes in a file. + var moduleInfoMap = []; // The ExternalModuleInfo for each file. + var deferredExports = []; // Exports to defer until an EndOfDeclarationMarker is found. + var currentSourceFile; // The current file. + var currentModuleInfo; // The ExternalModuleInfo for the current file. + var noSubstitution; // Set of nodes for which substitution rules should be ignored. + var needUMDDynamicImportHelper; + return ts.chainBundle(transformSourceFile); + /** + * Transforms the module aspects of a SourceFile. + * + * @param node The SourceFile node. + */ + function transformSourceFile(node) { + if (node.isDeclarationFile || + !(ts.isEffectiveExternalModule(node, compilerOptions) || + node.transformFlags & 16777216 /* ContainsDynamicImport */ || + (ts.isJsonSourceFile(node) && ts.hasJsonModuleEmitEnabled(compilerOptions) && (compilerOptions.out || compilerOptions.outFile)))) { + return node; + } + currentSourceFile = node; + currentModuleInfo = ts.collectExternalModuleInfo(node, resolver, compilerOptions); + moduleInfoMap[ts.getOriginalNodeId(node)] = currentModuleInfo; + // Perform the transformation. + var transformModule = getTransformModuleDelegate(moduleKind); + var updated = transformModule(node); + currentSourceFile = undefined; + currentModuleInfo = undefined; + needUMDDynamicImportHelper = false; + return ts.aggregateTransformFlags(updated); + } + function shouldEmitUnderscoreUnderscoreESModule() { + if (!currentModuleInfo.exportEquals && ts.isExternalModule(currentSourceFile)) { + return true; + } + return false; + } + /** + * Transforms a SourceFile into a CommonJS module. + * + * @param node The SourceFile node. + */ + function transformCommonJSModule(node) { + startLexicalEnvironment(); + var statements = []; + var ensureUseStrict = ts.getStrictOptionValue(compilerOptions, "alwaysStrict") || (!compilerOptions.noImplicitUseStrict && ts.isExternalModule(currentSourceFile)); + var statementOffset = ts.addPrologue(statements, node.statements, ensureUseStrict, sourceElementVisitor); + if (shouldEmitUnderscoreUnderscoreESModule()) { + ts.append(statements, createUnderscoreUnderscoreESModule()); + } + ts.append(statements, ts.visitNode(currentModuleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement)); + ts.addRange(statements, ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset)); + addExportEqualsIfNeeded(statements, /*emitAsReturn*/ false); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + var updated = ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements)); + if (currentModuleInfo.hasExportStarsToExportValues && !compilerOptions.importHelpers) { + // If we have any `export * from ...` declarations + // we need to inform the emitter to add the __export helper. + ts.addEmitHelper(updated, exportStarHelper); + } + ts.addEmitHelpers(updated, context.readEmitHelpers()); + return updated; + } + /** + * Transforms a SourceFile into an AMD module. + * + * @param node The SourceFile node. + */ + function transformAMDModule(node) { + var define = ts.createIdentifier("define"); + var moduleName = ts.tryGetModuleNameFromFile(node, host, compilerOptions); + var jsonSourceFile = ts.isJsonSourceFile(node) && node; + // An AMD define function has the following shape: + // + // define(id?, dependencies?, factory); + // + // This has the shape of the following: + // + // define(name, ["module1", "module2"], function (module1Alias) { ... } + // + // The location of the alias in the parameter list in the factory function needs to + // match the position of the module name in the dependency list. + // + // To ensure this is true in cases of modules with no aliases, e.g.: + // + // import "module" + // + // or + // + // /// + // + // we need to add modules without alias names to the end of the dependencies list + var _a = collectAsynchronousDependencies(node, /*includeNonAmdDependencies*/ true), aliasedModuleNames = _a.aliasedModuleNames, unaliasedModuleNames = _a.unaliasedModuleNames, importAliasNames = _a.importAliasNames; + // Create an updated SourceFile: + // + // define(moduleName?, ["module1", "module2"], function ... + var updated = ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray([ + ts.createExpressionStatement(ts.createCall(define, + /*typeArguments*/ undefined, (moduleName ? [moduleName] : []).concat([ + // Add the dependency array argument: + // + // ["require", "exports", module1", "module2", ...] + ts.createArrayLiteral(jsonSourceFile ? ts.emptyArray : [ + ts.createLiteral("require"), + ts.createLiteral("exports") + ].concat(aliasedModuleNames, unaliasedModuleNames)), + // Add the module body function argument: + // + // function (require, exports, module1, module2) ... + jsonSourceFile ? + jsonSourceFile.statements.length ? jsonSourceFile.statements[0].expression : ts.createObjectLiteral() : + ts.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, [ + ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "require"), + ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "exports") + ].concat(importAliasNames), + /*type*/ undefined, transformAsynchronousModuleBody(node)) + ]))) + ]), + /*location*/ node.statements)); + ts.addEmitHelpers(updated, context.readEmitHelpers()); + return updated; + } + /** + * Transforms a SourceFile into a UMD module. + * + * @param node The SourceFile node. + */ + function transformUMDModule(node) { + var _a = collectAsynchronousDependencies(node, /*includeNonAmdDependencies*/ false), aliasedModuleNames = _a.aliasedModuleNames, unaliasedModuleNames = _a.unaliasedModuleNames, importAliasNames = _a.importAliasNames; + var moduleName = ts.tryGetModuleNameFromFile(node, host, compilerOptions); + var umdHeader = ts.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "factory")], + /*type*/ undefined, ts.setTextRange(ts.createBlock([ + ts.createIf(ts.createLogicalAnd(ts.createTypeCheck(ts.createIdentifier("module"), "object"), ts.createTypeCheck(ts.createPropertyAccess(ts.createIdentifier("module"), "exports"), "object")), ts.createBlock([ + ts.createVariableStatement( + /*modifiers*/ undefined, [ + ts.createVariableDeclaration("v", + /*type*/ undefined, ts.createCall(ts.createIdentifier("factory"), + /*typeArguments*/ undefined, [ + ts.createIdentifier("require"), + ts.createIdentifier("exports") + ])) + ]), + ts.setEmitFlags(ts.createIf(ts.createStrictInequality(ts.createIdentifier("v"), ts.createIdentifier("undefined")), ts.createExpressionStatement(ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier("module"), "exports"), ts.createIdentifier("v")))), 1 /* SingleLine */) + ]), ts.createIf(ts.createLogicalAnd(ts.createTypeCheck(ts.createIdentifier("define"), "function"), ts.createPropertyAccess(ts.createIdentifier("define"), "amd")), ts.createBlock([ + ts.createExpressionStatement(ts.createCall(ts.createIdentifier("define"), + /*typeArguments*/ undefined, (moduleName ? [moduleName] : []).concat([ + ts.createArrayLiteral([ + ts.createLiteral("require"), + ts.createLiteral("exports") + ].concat(aliasedModuleNames, unaliasedModuleNames)), + ts.createIdentifier("factory") + ]))) + ]))) + ], + /*multiLine*/ true), + /*location*/ undefined)); + // Create an updated SourceFile: + // + // (function (factory) { + // if (typeof module === "object" && typeof module.exports === "object") { + // var v = factory(require, exports); + // if (v !== undefined) module.exports = v; + // } + // else if (typeof define === 'function' && define.amd) { + // define(["require", "exports"], factory); + // } + // })(function ...) + var updated = ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray([ + ts.createExpressionStatement(ts.createCall(umdHeader, + /*typeArguments*/ undefined, [ + // Add the module body function argument: + // + // function (require, exports) ... + ts.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, [ + ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "require"), + ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "exports") + ].concat(importAliasNames), + /*type*/ undefined, transformAsynchronousModuleBody(node)) + ])) + ]), + /*location*/ node.statements)); + ts.addEmitHelpers(updated, context.readEmitHelpers()); + return updated; + } + /** + * Collect the additional asynchronous dependencies for the module. + * + * @param node The source file. + * @param includeNonAmdDependencies A value indicating whether to include non-AMD dependencies. + */ + function collectAsynchronousDependencies(node, includeNonAmdDependencies) { + // names of modules with corresponding parameter in the factory function + var aliasedModuleNames = []; + // names of modules with no corresponding parameters in factory function + var unaliasedModuleNames = []; + // names of the parameters in the factory function; these + // parameters need to match the indexes of the corresponding + // module names in aliasedModuleNames. + var importAliasNames = []; + // Fill in amd-dependency tags + for (var _i = 0, _a = node.amdDependencies; _i < _a.length; _i++) { + var amdDependency = _a[_i]; + if (amdDependency.name) { + aliasedModuleNames.push(ts.createLiteral(amdDependency.path)); + importAliasNames.push(ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, amdDependency.name)); + } + else { + unaliasedModuleNames.push(ts.createLiteral(amdDependency.path)); + } + } + for (var _b = 0, _c = currentModuleInfo.externalImports; _b < _c.length; _b++) { + var importNode = _c[_b]; + // Find the name of the external module + var externalModuleName = ts.getExternalModuleNameLiteral(importNode, currentSourceFile, host, resolver, compilerOptions); + // Find the name of the module alias, if there is one + var importAliasName = ts.getLocalNameForExternalImport(importNode, currentSourceFile); + // It is possible that externalModuleName is undefined if it is not string literal. + // This can happen in the invalid import syntax. + // E.g : "import * from alias from 'someLib';" + if (externalModuleName) { + if (includeNonAmdDependencies && importAliasName) { + // Set emitFlags on the name of the classDeclaration + // This is so that when printer will not substitute the identifier + ts.setEmitFlags(importAliasName, 4 /* NoSubstitution */); + aliasedModuleNames.push(externalModuleName); + importAliasNames.push(ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, importAliasName)); + } + else { + unaliasedModuleNames.push(externalModuleName); + } + } + } + return { aliasedModuleNames: aliasedModuleNames, unaliasedModuleNames: unaliasedModuleNames, importAliasNames: importAliasNames }; + } + function getAMDImportExpressionForImport(node) { + if (ts.isImportEqualsDeclaration(node) || ts.isExportDeclaration(node) || !ts.getExternalModuleNameLiteral(node, currentSourceFile, host, resolver, compilerOptions)) { + return undefined; + } + var name = ts.getLocalNameForExternalImport(node, currentSourceFile); // TODO: GH#18217 + var expr = getHelperExpressionForImport(node, name); + if (expr === name) { + return undefined; + } + return ts.createExpressionStatement(ts.createAssignment(name, expr)); + } + /** + * Transforms a SourceFile into an AMD or UMD module body. + * + * @param node The SourceFile node. + */ + function transformAsynchronousModuleBody(node) { + startLexicalEnvironment(); + var statements = []; + var statementOffset = ts.addPrologue(statements, node.statements, /*ensureUseStrict*/ !compilerOptions.noImplicitUseStrict, sourceElementVisitor); + if (shouldEmitUnderscoreUnderscoreESModule()) { + ts.append(statements, createUnderscoreUnderscoreESModule()); + } + // Visit each statement of the module body. + ts.append(statements, ts.visitNode(currentModuleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement)); + if (moduleKind === ts.ModuleKind.AMD) { + ts.addRange(statements, ts.mapDefined(currentModuleInfo.externalImports, getAMDImportExpressionForImport)); + } + ts.addRange(statements, ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset)); + // Append the 'export =' statement if provided. + addExportEqualsIfNeeded(statements, /*emitAsReturn*/ true); + // End the lexical environment for the module body + // and merge any new lexical declarations. + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + var body = ts.createBlock(statements, /*multiLine*/ true); + if (currentModuleInfo.hasExportStarsToExportValues && !compilerOptions.importHelpers) { + // If we have any `export * from ...` declarations + // we need to inform the emitter to add the __export helper. + ts.addEmitHelper(body, exportStarHelper); + } + if (needUMDDynamicImportHelper) { + ts.addEmitHelper(body, dynamicImportUMDHelper); + } + return body; + } + /** + * Adds the down-level representation of `export=` to the statement list if one exists + * in the source file. + * + * @param statements The Statement list to modify. + * @param emitAsReturn A value indicating whether to emit the `export=` statement as a + * return statement. + */ + function addExportEqualsIfNeeded(statements, emitAsReturn) { + if (currentModuleInfo.exportEquals) { + var expressionResult = ts.visitNode(currentModuleInfo.exportEquals.expression, moduleExpressionElementVisitor); + if (expressionResult) { + if (emitAsReturn) { + var statement = ts.createReturn(expressionResult); + ts.setTextRange(statement, currentModuleInfo.exportEquals); + ts.setEmitFlags(statement, 384 /* NoTokenSourceMaps */ | 1536 /* NoComments */); + statements.push(statement); + } + else { + var statement = ts.createExpressionStatement(ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier("module"), "exports"), expressionResult)); + ts.setTextRange(statement, currentModuleInfo.exportEquals); + ts.setEmitFlags(statement, 1536 /* NoComments */); + statements.push(statement); + } + } + } + } + // + // Top-Level Source Element Visitors + // + /** + * Visits a node at the top level of the source file. + * + * @param node The node to visit. + */ + function sourceElementVisitor(node) { + switch (node.kind) { + case 249 /* ImportDeclaration */: + return visitImportDeclaration(node); + case 248 /* ImportEqualsDeclaration */: + return visitImportEqualsDeclaration(node); + case 255 /* ExportDeclaration */: + return visitExportDeclaration(node); + case 254 /* ExportAssignment */: + return visitExportAssignment(node); + case 219 /* VariableStatement */: + return visitVariableStatement(node); + case 239 /* FunctionDeclaration */: + return visitFunctionDeclaration(node); + case 240 /* ClassDeclaration */: + return visitClassDeclaration(node); + case 310 /* MergeDeclarationMarker */: + return visitMergeDeclarationMarker(node); + case 311 /* EndOfDeclarationMarker */: + return visitEndOfDeclarationMarker(node); + default: + return ts.visitEachChild(node, moduleExpressionElementVisitor, context); + } + } + function moduleExpressionElementVisitor(node) { + // This visitor does not need to descend into the tree if there is no dynamic import or destructuring assignment, + // as export/import statements are only transformed at the top level of a file. + if (!(node.transformFlags & 16777216 /* ContainsDynamicImport */) && !(node.transformFlags & 2048 /* ContainsDestructuringAssignment */)) { + return node; + } + if (ts.isImportCall(node)) { + return visitImportCallExpression(node); + } + else if (node.transformFlags & 1024 /* DestructuringAssignment */ && ts.isBinaryExpression(node)) { + return visitDestructuringAssignment(node); + } + else { + return ts.visitEachChild(node, moduleExpressionElementVisitor, context); + } + } + function destructuringNeedsFlattening(node) { + if (ts.isObjectLiteralExpression(node)) { + for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { + var elem = _a[_i]; + switch (elem.kind) { + case 275 /* PropertyAssignment */: + if (destructuringNeedsFlattening(elem.initializer)) { + return true; + } + break; + case 276 /* ShorthandPropertyAssignment */: + if (destructuringNeedsFlattening(elem.name)) { + return true; + } + break; + case 277 /* SpreadAssignment */: + if (destructuringNeedsFlattening(elem.expression)) { + return true; + } + break; + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + return false; + default: ts.Debug.assertNever(elem, "Unhandled object member kind"); + } + } + } + else if (ts.isArrayLiteralExpression(node)) { + for (var _b = 0, _c = node.elements; _b < _c.length; _b++) { + var elem = _c[_b]; + if (ts.isSpreadElement(elem)) { + if (destructuringNeedsFlattening(elem.expression)) { + return true; + } + } + else if (destructuringNeedsFlattening(elem)) { + return true; + } + } + } + else if (ts.isIdentifier(node)) { + return ts.length(getExports(node)) > (ts.isExportName(node) ? 1 : 0); + } + return false; + } + function visitDestructuringAssignment(node) { + if (destructuringNeedsFlattening(node.left)) { + return ts.flattenDestructuringAssignment(node, moduleExpressionElementVisitor, context, 0 /* All */, /*needsValue*/ false, createAllExportExpressions); + } + return ts.visitEachChild(node, moduleExpressionElementVisitor, context); + } + function visitImportCallExpression(node) { + var argument = ts.visitNode(ts.firstOrUndefined(node.arguments), moduleExpressionElementVisitor); + var containsLexicalThis = !!(node.transformFlags & 8192 /* ContainsLexicalThis */); + switch (compilerOptions.module) { + case ts.ModuleKind.AMD: + return createImportCallExpressionAMD(argument, containsLexicalThis); + case ts.ModuleKind.UMD: + return createImportCallExpressionUMD(argument, containsLexicalThis); + case ts.ModuleKind.CommonJS: + default: + return createImportCallExpressionCommonJS(argument, containsLexicalThis); + } + } + function createImportCallExpressionUMD(arg, containsLexicalThis) { + // (function (factory) { + // ... (regular UMD) + // } + // })(function (require, exports, useSyncRequire) { + // "use strict"; + // Object.defineProperty(exports, "__esModule", { value: true }); + // var __syncRequire = typeof module === "object" && typeof module.exports === "object"; + // var __resolved = new Promise(function (resolve) { resolve(); }); + // ..... + // __syncRequire + // ? __resolved.then(function () { return require(x); }) /*CommonJs Require*/ + // : new Promise(function (_a, _b) { require([x], _a, _b); }); /*Amd Require*/ + // }); + needUMDDynamicImportHelper = true; + if (ts.isSimpleCopiableExpression(arg)) { + var argClone = ts.isGeneratedIdentifier(arg) ? arg : ts.isStringLiteral(arg) ? ts.createLiteral(arg) : ts.setEmitFlags(ts.setTextRange(ts.getSynthesizedClone(arg), arg), 1536 /* NoComments */); + return ts.createConditional( + /*condition*/ ts.createIdentifier("__syncRequire"), + /*whenTrue*/ createImportCallExpressionCommonJS(arg, containsLexicalThis), + /*whenFalse*/ createImportCallExpressionAMD(argClone, containsLexicalThis)); + } + else { + var temp = ts.createTempVariable(hoistVariableDeclaration); + return ts.createComma(ts.createAssignment(temp, arg), ts.createConditional( + /*condition*/ ts.createIdentifier("__syncRequire"), + /*whenTrue*/ createImportCallExpressionCommonJS(temp, containsLexicalThis), + /*whenFalse*/ createImportCallExpressionAMD(temp, containsLexicalThis))); + } + } + function createImportCallExpressionAMD(arg, containsLexicalThis) { + // improt("./blah") + // emit as + // define(["require", "exports", "blah"], function (require, exports) { + // ... + // new Promise(function (_a, _b) { require([x], _a, _b); }); /*Amd Require*/ + // }); + var resolve = ts.createUniqueName("resolve"); + var reject = ts.createUniqueName("reject"); + var parameters = [ + ts.createParameter(/*decorator*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, /*name*/ resolve), + ts.createParameter(/*decorator*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, /*name*/ reject) + ]; + var body = ts.createBlock([ + ts.createExpressionStatement(ts.createCall(ts.createIdentifier("require"), + /*typeArguments*/ undefined, [ts.createArrayLiteral([arg || ts.createOmittedExpression()]), resolve, reject])) + ]); + var func; + if (languageVersion >= 2 /* ES2015 */) { + func = ts.createArrowFunction( + /*modifiers*/ undefined, + /*typeParameters*/ undefined, parameters, + /*type*/ undefined, + /*equalsGreaterThanToken*/ undefined, body); + } + else { + func = ts.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, parameters, + /*type*/ undefined, body); + // if there is a lexical 'this' in the import call arguments, ensure we indicate + // that this new function expression indicates it captures 'this' so that the + // es2015 transformer will properly substitute 'this' with '_this'. + if (containsLexicalThis) { + ts.setEmitFlags(func, 8 /* CapturesThis */); + } + } + var promise = ts.createNew(ts.createIdentifier("Promise"), /*typeArguments*/ undefined, [func]); + if (compilerOptions.esModuleInterop) { + context.requestEmitHelper(importStarHelper); + return ts.createCall(ts.createPropertyAccess(promise, ts.createIdentifier("then")), /*typeArguments*/ undefined, [ts.getHelperName("__importStar")]); + } + return promise; + } + function createImportCallExpressionCommonJS(arg, containsLexicalThis) { + // import("./blah") + // emit as + // Promise.resolve().then(function () { return require(x); }) /*CommonJs Require*/ + // We have to wrap require in then callback so that require is done in asynchronously + // if we simply do require in resolve callback in Promise constructor. We will execute the loading immediately + var promiseResolveCall = ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Promise"), "resolve"), /*typeArguments*/ undefined, /*argumentsArray*/ []); + var requireCall = ts.createCall(ts.createIdentifier("require"), /*typeArguments*/ undefined, arg ? [arg] : []); + if (compilerOptions.esModuleInterop) { + context.requestEmitHelper(importStarHelper); + requireCall = ts.createCall(ts.getHelperName("__importStar"), /*typeArguments*/ undefined, [requireCall]); + } + var func; + if (languageVersion >= 2 /* ES2015 */) { + func = ts.createArrowFunction( + /*modifiers*/ undefined, + /*typeParameters*/ undefined, + /*parameters*/ [], + /*type*/ undefined, + /*equalsGreaterThanToken*/ undefined, requireCall); + } + else { + func = ts.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, + /*parameters*/ [], + /*type*/ undefined, ts.createBlock([ts.createReturn(requireCall)])); + // if there is a lexical 'this' in the import call arguments, ensure we indicate + // that this new function expression indicates it captures 'this' so that the + // es2015 transformer will properly substitute 'this' with '_this'. + if (containsLexicalThis) { + ts.setEmitFlags(func, 8 /* CapturesThis */); + } + } + return ts.createCall(ts.createPropertyAccess(promiseResolveCall, "then"), /*typeArguments*/ undefined, [func]); + } + function getHelperExpressionForImport(node, innerExpr) { + if (!compilerOptions.esModuleInterop || ts.getEmitFlags(node) & 67108864 /* NeverApplyImportHelper */) { + return innerExpr; + } + if (ts.getImportNeedsImportStarHelper(node)) { + context.requestEmitHelper(importStarHelper); + return ts.createCall(ts.getHelperName("__importStar"), /*typeArguments*/ undefined, [innerExpr]); + } + if (ts.getImportNeedsImportDefaultHelper(node)) { + context.requestEmitHelper(importDefaultHelper); + return ts.createCall(ts.getHelperName("__importDefault"), /*typeArguments*/ undefined, [innerExpr]); + } + return innerExpr; + } + /** + * Visits an ImportDeclaration node. + * + * @param node The node to visit. + */ + function visitImportDeclaration(node) { + var statements; + var namespaceDeclaration = ts.getNamespaceDeclarationNode(node); + if (moduleKind !== ts.ModuleKind.AMD) { + if (!node.importClause) { + // import "mod"; + return ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(createRequireCall(node)), node), node); + } + else { + var variables = []; + if (namespaceDeclaration && !ts.isDefaultImport(node)) { + // import * as n from "mod"; + variables.push(ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name), + /*type*/ undefined, getHelperExpressionForImport(node, createRequireCall(node)))); + } + else { + // import d from "mod"; + // import { x, y } from "mod"; + // import d, { x, y } from "mod"; + // import d, * as n from "mod"; + variables.push(ts.createVariableDeclaration(ts.getGeneratedNameForNode(node), + /*type*/ undefined, getHelperExpressionForImport(node, createRequireCall(node)))); + if (namespaceDeclaration && ts.isDefaultImport(node)) { + variables.push(ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name), + /*type*/ undefined, ts.getGeneratedNameForNode(node))); + } + } + statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList(variables, languageVersion >= 2 /* ES2015 */ ? 2 /* Const */ : 0 /* None */)), + /*location*/ node), + /*original*/ node)); + } + } + else if (namespaceDeclaration && ts.isDefaultImport(node)) { + // import d, * as n from "mod"; + statements = ts.append(statements, ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ + ts.setOriginalNode(ts.setTextRange(ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name), + /*type*/ undefined, ts.getGeneratedNameForNode(node)), + /*location*/ node), + /*original*/ node) + ], languageVersion >= 2 /* ES2015 */ ? 2 /* Const */ : 0 /* None */))); + } + if (hasAssociatedEndOfDeclarationMarker(node)) { + // Defer exports until we encounter an EndOfDeclarationMarker node + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportsOfImportDeclaration(deferredExports[id], node); + } + else { + statements = appendExportsOfImportDeclaration(statements, node); + } + return ts.singleOrMany(statements); + } + /** + * Creates a `require()` call to import an external module. + * + * @param importNode The declararation to import. + */ + function createRequireCall(importNode) { + var moduleName = ts.getExternalModuleNameLiteral(importNode, currentSourceFile, host, resolver, compilerOptions); + var args = []; + if (moduleName) { + args.push(moduleName); + } + return ts.createCall(ts.createIdentifier("require"), /*typeArguments*/ undefined, args); + } + /** + * Visits an ImportEqualsDeclaration node. + * + * @param node The node to visit. + */ + function visitImportEqualsDeclaration(node) { + ts.Debug.assert(ts.isExternalModuleImportEqualsDeclaration(node), "import= for internal module references should be handled in an earlier transformer."); + var statements; + if (moduleKind !== ts.ModuleKind.AMD) { + if (ts.hasModifier(node, 1 /* Export */)) { + statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(createExportExpression(node.name, createRequireCall(node))), node), node)); + } + else { + statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(ts.getSynthesizedClone(node.name), + /*type*/ undefined, createRequireCall(node)) + ], + /*flags*/ languageVersion >= 2 /* ES2015 */ ? 2 /* Const */ : 0 /* None */)), node), node)); + } + } + else { + if (ts.hasModifier(node, 1 /* Export */)) { + statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(createExportExpression(ts.getExportName(node), ts.getLocalName(node))), node), node)); + } + } + if (hasAssociatedEndOfDeclarationMarker(node)) { + // Defer exports until we encounter an EndOfDeclarationMarker node + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportsOfImportEqualsDeclaration(deferredExports[id], node); + } + else { + statements = appendExportsOfImportEqualsDeclaration(statements, node); + } + return ts.singleOrMany(statements); + } + /** + * Visits an ExportDeclaration node. + * + * @param The node to visit. + */ + function visitExportDeclaration(node) { + if (!node.moduleSpecifier) { + // Elide export declarations with no module specifier as they are handled + // elsewhere. + return undefined; + } + var generatedName = ts.getGeneratedNameForNode(node); + if (node.exportClause) { + var statements = []; + // export { x, y } from "mod"; + if (moduleKind !== ts.ModuleKind.AMD) { + statements.push(ts.setOriginalNode(ts.setTextRange(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(generatedName, + /*type*/ undefined, createRequireCall(node)) + ])), + /*location*/ node), + /* original */ node)); + } + for (var _i = 0, _a = node.exportClause.elements; _i < _a.length; _i++) { + var specifier = _a[_i]; + var exportedValue = ts.createPropertyAccess(generatedName, specifier.propertyName || specifier.name); + statements.push(ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(createExportExpression(ts.getExportName(specifier), exportedValue)), specifier), specifier)); + } + return ts.singleOrMany(statements); + } + else { + // export * from "mod"; + return ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(createExportStarHelper(context, moduleKind !== ts.ModuleKind.AMD ? createRequireCall(node) : generatedName)), node), node); + } + } + /** + * Visits an ExportAssignment node. + * + * @param node The node to visit. + */ + function visitExportAssignment(node) { + if (node.isExportEquals) { + return undefined; + } + var statements; + var original = node.original; + if (original && hasAssociatedEndOfDeclarationMarker(original)) { + // Defer exports until we encounter an EndOfDeclarationMarker node + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportStatement(deferredExports[id], ts.createIdentifier("default"), ts.visitNode(node.expression, moduleExpressionElementVisitor), /*location*/ node, /*allowComments*/ true); + } + else { + statements = appendExportStatement(statements, ts.createIdentifier("default"), ts.visitNode(node.expression, moduleExpressionElementVisitor), /*location*/ node, /*allowComments*/ true); + } + return ts.singleOrMany(statements); + } + /** + * Visits a FunctionDeclaration node. + * + * @param node The node to visit. + */ + function visitFunctionDeclaration(node) { + var statements; + if (ts.hasModifier(node, 1 /* Export */)) { + statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createFunctionDeclaration( + /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, ts.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true), + /*typeParameters*/ undefined, ts.visitNodes(node.parameters, moduleExpressionElementVisitor), + /*type*/ undefined, ts.visitEachChild(node.body, moduleExpressionElementVisitor, context)), + /*location*/ node), + /*original*/ node)); + } + else { + statements = ts.append(statements, ts.visitEachChild(node, moduleExpressionElementVisitor, context)); + } + if (hasAssociatedEndOfDeclarationMarker(node)) { + // Defer exports until we encounter an EndOfDeclarationMarker node + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node); + } + else { + statements = appendExportsOfHoistedDeclaration(statements, node); + } + return ts.singleOrMany(statements); + } + /** + * Visits a ClassDeclaration node. + * + * @param node The node to visit. + */ + function visitClassDeclaration(node) { + var statements; + if (ts.hasModifier(node, 1 /* Export */)) { + statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createClassDeclaration( + /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true), + /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, moduleExpressionElementVisitor), ts.visitNodes(node.members, moduleExpressionElementVisitor)), node), node)); + } + else { + statements = ts.append(statements, ts.visitEachChild(node, moduleExpressionElementVisitor, context)); + } + if (hasAssociatedEndOfDeclarationMarker(node)) { + // Defer exports until we encounter an EndOfDeclarationMarker node + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node); + } + else { + statements = appendExportsOfHoistedDeclaration(statements, node); + } + return ts.singleOrMany(statements); + } + /** + * Visits a VariableStatement node. + * + * @param node The node to visit. + */ + function visitVariableStatement(node) { + var statements; + var variables; + var expressions; + if (ts.hasModifier(node, 1 /* Export */)) { + var modifiers = void 0; + // If we're exporting these variables, then these just become assignments to 'exports.x'. + // We only want to emit assignments for variables with initializers. + for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { + var variable = _a[_i]; + if (ts.isIdentifier(variable.name) && ts.isLocalName(variable.name)) { + if (!modifiers) { + modifiers = ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier); + } + variables = ts.append(variables, variable); + } + else if (variable.initializer) { + expressions = ts.append(expressions, transformInitializedVariable(variable)); + } + } + if (variables) { + statements = ts.append(statements, ts.updateVariableStatement(node, modifiers, ts.updateVariableDeclarationList(node.declarationList, variables))); + } + if (expressions) { + statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(ts.inlineExpressions(expressions)), node), node)); + } + } + else { + statements = ts.append(statements, ts.visitEachChild(node, moduleExpressionElementVisitor, context)); + } + if (hasAssociatedEndOfDeclarationMarker(node)) { + // Defer exports until we encounter an EndOfDeclarationMarker node + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node); + } + else { + statements = appendExportsOfVariableStatement(statements, node); + } + return ts.singleOrMany(statements); + } + function createAllExportExpressions(name, value, location) { + var exportedNames = getExports(name); + if (exportedNames) { + // For each additional export of the declaration, apply an export assignment. + var expression = ts.isExportName(name) ? value : ts.createAssignment(name, value); + for (var _i = 0, exportedNames_1 = exportedNames; _i < exportedNames_1.length; _i++) { + var exportName = exportedNames_1[_i]; + // Mark the node to prevent triggering substitution. + ts.setEmitFlags(expression, 4 /* NoSubstitution */); + expression = createExportExpression(exportName, expression, /*location*/ location); + } + return expression; + } + return ts.createAssignment(name, value); + } + /** + * Transforms an exported variable with an initializer into an expression. + * + * @param node The node to transform. + */ + function transformInitializedVariable(node) { + if (ts.isBindingPattern(node.name)) { + return ts.flattenDestructuringAssignment(ts.visitNode(node, moduleExpressionElementVisitor), + /*visitor*/ undefined, context, 0 /* All */, + /*needsValue*/ false, createAllExportExpressions); + } + else { + return ts.createAssignment(ts.setTextRange(ts.createPropertyAccess(ts.createIdentifier("exports"), node.name), + /*location*/ node.name), ts.visitNode(node.initializer, moduleExpressionElementVisitor)); + } + } + /** + * Visits a MergeDeclarationMarker used as a placeholder for the beginning of a merged + * and transformed declaration. + * + * @param node The node to visit. + */ + function visitMergeDeclarationMarker(node) { + // For an EnumDeclaration or ModuleDeclaration that merges with a preceeding + // declaration we do not emit a leading variable declaration. To preserve the + // begin/end semantics of the declararation and to properly handle exports + // we wrapped the leading variable declaration in a `MergeDeclarationMarker`. + // + // To balance the declaration, add the exports of the elided variable + // statement. + if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 219 /* VariableStatement */) { + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node.original); + } + return node; + } + /** + * Determines whether a node has an associated EndOfDeclarationMarker. + * + * @param node The node to test. + */ + function hasAssociatedEndOfDeclarationMarker(node) { + return (ts.getEmitFlags(node) & 4194304 /* HasEndOfDeclarationMarker */) !== 0; + } + /** + * Visits a DeclarationMarker used as a placeholder for the end of a transformed + * declaration. + * + * @param node The node to visit. + */ + function visitEndOfDeclarationMarker(node) { + // For some transformations we emit an `EndOfDeclarationMarker` to mark the actual + // end of the transformed declaration. We use this marker to emit any deferred exports + // of the declaration. + var id = ts.getOriginalNodeId(node); + var statements = deferredExports[id]; + if (statements) { + delete deferredExports[id]; + return ts.append(statements, node); + } + return node; + } + /** + * Appends the exports of an ImportDeclaration to a statement list, returning the + * statement list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param decl The declaration whose exports are to be recorded. + */ + function appendExportsOfImportDeclaration(statements, decl) { + if (currentModuleInfo.exportEquals) { + return statements; + } + var importClause = decl.importClause; + if (!importClause) { + return statements; + } + if (importClause.name) { + statements = appendExportsOfDeclaration(statements, importClause); + } + var namedBindings = importClause.namedBindings; + if (namedBindings) { + switch (namedBindings.kind) { + case 251 /* NamespaceImport */: + statements = appendExportsOfDeclaration(statements, namedBindings); + break; + case 252 /* NamedImports */: + for (var _i = 0, _a = namedBindings.elements; _i < _a.length; _i++) { + var importBinding = _a[_i]; + statements = appendExportsOfDeclaration(statements, importBinding); + } + break; + } + } + return statements; + } + /** + * Appends the exports of an ImportEqualsDeclaration to a statement list, returning the + * statement list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param decl The declaration whose exports are to be recorded. + */ + function appendExportsOfImportEqualsDeclaration(statements, decl) { + if (currentModuleInfo.exportEquals) { + return statements; + } + return appendExportsOfDeclaration(statements, decl); + } + /** + * Appends the exports of a VariableStatement to a statement list, returning the statement + * list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param node The VariableStatement whose exports are to be recorded. + */ + function appendExportsOfVariableStatement(statements, node) { + if (currentModuleInfo.exportEquals) { + return statements; + } + for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + statements = appendExportsOfBindingElement(statements, decl); + } + return statements; + } + /** + * Appends the exports of a VariableDeclaration or BindingElement to a statement list, + * returning the statement list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param decl The declaration whose exports are to be recorded. + */ + function appendExportsOfBindingElement(statements, decl) { + if (currentModuleInfo.exportEquals) { + return statements; + } + if (ts.isBindingPattern(decl.name)) { + for (var _i = 0, _a = decl.name.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (!ts.isOmittedExpression(element)) { + statements = appendExportsOfBindingElement(statements, element); + } + } + } + else if (!ts.isGeneratedIdentifier(decl.name)) { + statements = appendExportsOfDeclaration(statements, decl); + } + return statements; + } + /** + * Appends the exports of a ClassDeclaration or FunctionDeclaration to a statement list, + * returning the statement list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param decl The declaration whose exports are to be recorded. + */ + function appendExportsOfHoistedDeclaration(statements, decl) { + if (currentModuleInfo.exportEquals) { + return statements; + } + if (ts.hasModifier(decl, 1 /* Export */)) { + var exportName = ts.hasModifier(decl, 512 /* Default */) ? ts.createIdentifier("default") : ts.getDeclarationName(decl); + statements = appendExportStatement(statements, exportName, ts.getLocalName(decl), /*location*/ decl); + } + if (decl.name) { + statements = appendExportsOfDeclaration(statements, decl); + } + return statements; + } + /** + * Appends the exports of a declaration to a statement list, returning the statement list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param decl The declaration to export. + */ + function appendExportsOfDeclaration(statements, decl) { + var name = ts.getDeclarationName(decl); + var exportSpecifiers = currentModuleInfo.exportSpecifiers.get(ts.idText(name)); + if (exportSpecifiers) { + for (var _i = 0, exportSpecifiers_1 = exportSpecifiers; _i < exportSpecifiers_1.length; _i++) { + var exportSpecifier = exportSpecifiers_1[_i]; + statements = appendExportStatement(statements, exportSpecifier.name, name, /*location*/ exportSpecifier.name); + } + } + return statements; + } + /** + * Appends the down-level representation of an export to a statement list, returning the + * statement list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param exportName The name of the export. + * @param expression The expression to export. + * @param location The location to use for source maps and comments for the export. + * @param allowComments Whether to allow comments on the export. + */ + function appendExportStatement(statements, exportName, expression, location, allowComments) { + statements = ts.append(statements, createExportStatement(exportName, expression, location, allowComments)); + return statements; + } + function createUnderscoreUnderscoreESModule() { + var statement; + if (languageVersion === 0 /* ES3 */) { + statement = ts.createExpressionStatement(createExportExpression(ts.createIdentifier("__esModule"), ts.createLiteral(/*value*/ true))); + } + else { + statement = ts.createExpressionStatement(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"), + /*typeArguments*/ undefined, [ + ts.createIdentifier("exports"), + ts.createLiteral("__esModule"), + ts.createObjectLiteral([ + ts.createPropertyAssignment("value", ts.createLiteral(/*value*/ true)) + ]) + ])); + } + ts.setEmitFlags(statement, 1048576 /* CustomPrologue */); + return statement; + } + /** + * Creates a call to the current file's export function to export a value. + * + * @param name The bound name of the export. + * @param value The exported value. + * @param location The location to use for source maps and comments for the export. + * @param allowComments An optional value indicating whether to emit comments for the statement. + */ + function createExportStatement(name, value, location, allowComments) { + var statement = ts.setTextRange(ts.createExpressionStatement(createExportExpression(name, value)), location); + ts.startOnNewLine(statement); + if (!allowComments) { + ts.setEmitFlags(statement, 1536 /* NoComments */); + } + return statement; + } + /** + * Creates a call to the current file's export function to export a value. + * + * @param name The bound name of the export. + * @param value The exported value. + * @param location The location to use for source maps and comments for the export. + */ + function createExportExpression(name, value, location) { + return ts.setTextRange(ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier("exports"), ts.getSynthesizedClone(name)), value), location); + } + // + // Modifier Visitors + // + /** + * Visit nodes to elide module-specific modifiers. + * + * @param node The node to visit. + */ + function modifierVisitor(node) { + // Elide module-specific modifiers. + switch (node.kind) { + case 85 /* ExportKeyword */: + case 80 /* DefaultKeyword */: + return undefined; + } + return node; + } + // + // Emit Notification + // + /** + * Hook for node emit notifications. + * + * @param hint A hint as to the intended usage of the node. + * @param node The node to emit. + * @param emit A callback used to emit the node in the printer. + */ + function onEmitNode(hint, node, emitCallback) { + if (node.kind === 279 /* SourceFile */) { + currentSourceFile = node; + currentModuleInfo = moduleInfoMap[ts.getOriginalNodeId(currentSourceFile)]; + noSubstitution = []; + previousOnEmitNode(hint, node, emitCallback); + currentSourceFile = undefined; + currentModuleInfo = undefined; + noSubstitution = undefined; + } + else { + previousOnEmitNode(hint, node, emitCallback); + } + } + // + // Substitutions + // + /** + * Hooks node substitutions. + * + * @param hint A hint as to the intended usage of the node. + * @param node The node to substitute. + */ + function onSubstituteNode(hint, node) { + node = previousOnSubstituteNode(hint, node); + if (node.id && noSubstitution[node.id]) { + return node; + } + if (hint === 1 /* Expression */) { + return substituteExpression(node); + } + else if (ts.isShorthandPropertyAssignment(node)) { + return substituteShorthandPropertyAssignment(node); + } + return node; + } + /** + * Substitution for a ShorthandPropertyAssignment whose declaration name is an imported + * or exported symbol. + * + * @param node The node to substitute. + */ + function substituteShorthandPropertyAssignment(node) { + var name = node.name; + var exportedOrImportedName = substituteExpressionIdentifier(name); + if (exportedOrImportedName !== name) { + // A shorthand property with an assignment initializer is probably part of a + // destructuring assignment + if (node.objectAssignmentInitializer) { + var initializer = ts.createAssignment(exportedOrImportedName, node.objectAssignmentInitializer); + return ts.setTextRange(ts.createPropertyAssignment(name, initializer), node); + } + return ts.setTextRange(ts.createPropertyAssignment(name, exportedOrImportedName), node); + } + return node; + } + /** + * Substitution for an Expression that may contain an imported or exported symbol. + * + * @param node The node to substitute. + */ + function substituteExpression(node) { + switch (node.kind) { + case 72 /* Identifier */: + return substituteExpressionIdentifier(node); + case 204 /* BinaryExpression */: + return substituteBinaryExpression(node); + case 203 /* PostfixUnaryExpression */: + case 202 /* PrefixUnaryExpression */: + return substituteUnaryExpression(node); + } + return node; + } + /** + * Substitution for an Identifier expression that may contain an imported or exported + * symbol. + * + * @param node The node to substitute. + */ + function substituteExpressionIdentifier(node) { + if (ts.getEmitFlags(node) & 4096 /* HelperName */) { + var externalHelpersModuleName = ts.getExternalHelpersModuleName(currentSourceFile); + if (externalHelpersModuleName) { + return ts.createPropertyAccess(externalHelpersModuleName, node); + } + return node; + } + if (!ts.isGeneratedIdentifier(node) && !ts.isLocalName(node)) { + var exportContainer = resolver.getReferencedExportContainer(node, ts.isExportName(node)); + if (exportContainer && exportContainer.kind === 279 /* SourceFile */) { + return ts.setTextRange(ts.createPropertyAccess(ts.createIdentifier("exports"), ts.getSynthesizedClone(node)), + /*location*/ node); + } + var importDeclaration = resolver.getReferencedImportDeclaration(node); + if (importDeclaration) { + if (ts.isImportClause(importDeclaration)) { + return ts.setTextRange(ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent), ts.createIdentifier("default")), + /*location*/ node); + } + else if (ts.isImportSpecifier(importDeclaration)) { + var name = importDeclaration.propertyName || importDeclaration.name; + return ts.setTextRange(ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent.parent.parent), ts.getSynthesizedClone(name)), + /*location*/ node); + } + } + } + return node; + } + /** + * Substitution for a BinaryExpression that may contain an imported or exported symbol. + * + * @param node The node to substitute. + */ + function substituteBinaryExpression(node) { + // When we see an assignment expression whose left-hand side is an exported symbol, + // we should ensure all exports of that symbol are updated with the correct value. + // + // - We do not substitute generated identifiers for any reason. + // - We do not substitute identifiers tagged with the LocalName flag. + // - We do not substitute identifiers that were originally the name of an enum or + // namespace due to how they are transformed in TypeScript. + // - We only substitute identifiers that are exported at the top level. + if (ts.isAssignmentOperator(node.operatorToken.kind) + && ts.isIdentifier(node.left) + && !ts.isGeneratedIdentifier(node.left) + && !ts.isLocalName(node.left) + && !ts.isDeclarationNameOfEnumOrNamespace(node.left)) { + var exportedNames = getExports(node.left); + if (exportedNames) { + // For each additional export of the declaration, apply an export assignment. + var expression = node; + for (var _i = 0, exportedNames_2 = exportedNames; _i < exportedNames_2.length; _i++) { + var exportName = exportedNames_2[_i]; + // Mark the node to prevent triggering this rule again. + noSubstitution[ts.getNodeId(expression)] = true; + expression = createExportExpression(exportName, expression, /*location*/ node); + } + return expression; + } + } + return node; + } + /** + * Substitution for a UnaryExpression that may contain an imported or exported symbol. + * + * @param node The node to substitute. + */ + function substituteUnaryExpression(node) { + // When we see a prefix or postfix increment expression whose operand is an exported + // symbol, we should ensure all exports of that symbol are updated with the correct + // value. + // + // - We do not substitute generated identifiers for any reason. + // - We do not substitute identifiers tagged with the LocalName flag. + // - We do not substitute identifiers that were originally the name of an enum or + // namespace due to how they are transformed in TypeScript. + // - We only substitute identifiers that are exported at the top level. + if ((node.operator === 44 /* PlusPlusToken */ || node.operator === 45 /* MinusMinusToken */) + && ts.isIdentifier(node.operand) + && !ts.isGeneratedIdentifier(node.operand) + && !ts.isLocalName(node.operand) + && !ts.isDeclarationNameOfEnumOrNamespace(node.operand)) { + var exportedNames = getExports(node.operand); + if (exportedNames) { + var expression = node.kind === 203 /* PostfixUnaryExpression */ + ? ts.setTextRange(ts.createBinary(node.operand, ts.createToken(node.operator === 44 /* PlusPlusToken */ ? 60 /* PlusEqualsToken */ : 61 /* MinusEqualsToken */), ts.createLiteral(1)), + /*location*/ node) + : node; + for (var _i = 0, exportedNames_3 = exportedNames; _i < exportedNames_3.length; _i++) { + var exportName = exportedNames_3[_i]; + // Mark the node to prevent triggering this rule again. + noSubstitution[ts.getNodeId(expression)] = true; + expression = createExportExpression(exportName, expression); + } + return expression; + } + } + return node; + } + /** + * Gets the additional exports of a name. + * + * @param name The name. + */ + function getExports(name) { + if (!ts.isGeneratedIdentifier(name)) { + var valueDeclaration = resolver.getReferencedImportDeclaration(name) + || resolver.getReferencedValueDeclaration(name); + if (valueDeclaration) { + return currentModuleInfo + && currentModuleInfo.exportedBindings[ts.getOriginalNodeId(valueDeclaration)]; + } + } + } + } + ts.transformModule = transformModule; + // emit output for the __export helper function + var exportStarHelper = { + name: "typescript:export-star", + scoped: true, + text: "\n function __export(m) {\n for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\n }" + }; + function createExportStarHelper(context, module) { + var compilerOptions = context.getCompilerOptions(); + return compilerOptions.importHelpers + ? ts.createCall(ts.getHelperName("__exportStar"), /*typeArguments*/ undefined, [module, ts.createIdentifier("exports")]) + : ts.createCall(ts.createIdentifier("__export"), /*typeArguments*/ undefined, [module]); + } + // emit helper for dynamic import + var dynamicImportUMDHelper = { + name: "typescript:dynamicimport-sync-require", + scoped: true, + text: "\n var __syncRequire = typeof module === \"object\" && typeof module.exports === \"object\";" + }; + // emit helper for `import * as Name from "foo"` + var importStarHelper = { + name: "typescript:commonjsimportstar", + scoped: false, + text: "\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];\n result[\"default\"] = mod;\n return result;\n};" + }; + // emit helper for `import Name from "foo"` + var importDefaultHelper = { + name: "typescript:commonjsimportdefault", + scoped: false, + text: "\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};" + }; +})(ts || (ts = {})); +/*@internal*/ +var ts; +(function (ts) { + function transformSystemModule(context) { + var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; + var compilerOptions = context.getCompilerOptions(); + var resolver = context.getEmitResolver(); + var host = context.getEmitHost(); + var previousOnSubstituteNode = context.onSubstituteNode; + var previousOnEmitNode = context.onEmitNode; + context.onSubstituteNode = onSubstituteNode; + context.onEmitNode = onEmitNode; + context.enableSubstitution(72 /* Identifier */); // Substitutes expression identifiers for imported symbols. + context.enableSubstitution(276 /* ShorthandPropertyAssignment */); // Substitutes expression identifiers for imported symbols + context.enableSubstitution(204 /* BinaryExpression */); // Substitutes assignments to exported symbols. + context.enableSubstitution(202 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols. + context.enableSubstitution(203 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols. + context.enableEmitNotification(279 /* SourceFile */); // Restore state when substituting nodes in a file. + var moduleInfoMap = []; // The ExternalModuleInfo for each file. + var deferredExports = []; // Exports to defer until an EndOfDeclarationMarker is found. + var exportFunctionsMap = []; // The export function associated with a source file. + var noSubstitutionMap = []; // Set of nodes for which substitution rules should be ignored for each file. + var currentSourceFile; // The current file. + var moduleInfo; // ExternalModuleInfo for the current file. + var exportFunction; // The export function for the current file. + var contextObject; // The context object for the current file. + var hoistedStatements; + var enclosingBlockScopedContainer; + var noSubstitution; // Set of nodes for which substitution rules should be ignored. + return ts.chainBundle(transformSourceFile); + /** + * Transforms the module aspects of a SourceFile. + * + * @param node The SourceFile node. + */ + function transformSourceFile(node) { + if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 16777216 /* ContainsDynamicImport */)) { + return node; + } + var id = ts.getOriginalNodeId(node); + currentSourceFile = node; + enclosingBlockScopedContainer = node; + // System modules have the following shape: + // + // System.register(['dep-1', ... 'dep-n'], function(exports) {/* module body function */}) + // + // The parameter 'exports' here is a callback '(name: string, value: T) => T' that + // is used to publish exported values. 'exports' returns its 'value' argument so in + // most cases expressions that mutate exported values can be rewritten as: + // + // expr -> exports('name', expr) + // + // The only exception in this rule is postfix unary operators, + // see comment to 'substitutePostfixUnaryExpression' for more details + // Collect information about the external module and dependency groups. + moduleInfo = moduleInfoMap[id] = ts.collectExternalModuleInfo(node, resolver, compilerOptions); + // Make sure that the name of the 'exports' function does not conflict with + // existing identifiers. + exportFunction = ts.createUniqueName("exports"); + exportFunctionsMap[id] = exportFunction; + contextObject = ts.createUniqueName("context"); + // Add the body of the module. + var dependencyGroups = collectDependencyGroups(moduleInfo.externalImports); + var moduleBodyBlock = createSystemModuleBody(node, dependencyGroups); + var moduleBodyFunction = ts.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, [ + ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, exportFunction), + ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, contextObject) + ], + /*type*/ undefined, moduleBodyBlock); + // Write the call to `System.register` + // Clear the emit-helpers flag for later passes since we'll have already used it in the module body + // So the helper will be emit at the correct position instead of at the top of the source-file + var moduleName = ts.tryGetModuleNameFromFile(node, host, compilerOptions); + var dependencies = ts.createArrayLiteral(ts.map(dependencyGroups, function (dependencyGroup) { return dependencyGroup.name; })); + var updated = ts.setEmitFlags(ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray([ + ts.createExpressionStatement(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("System"), "register"), + /*typeArguments*/ undefined, moduleName + ? [moduleName, dependencies, moduleBodyFunction] + : [dependencies, moduleBodyFunction])) + ]), node.statements)), 1024 /* NoTrailingComments */); + if (!(compilerOptions.outFile || compilerOptions.out)) { + ts.moveEmitHelpers(updated, moduleBodyBlock, function (helper) { return !helper.scoped; }); + } + if (noSubstitution) { + noSubstitutionMap[id] = noSubstitution; + noSubstitution = undefined; + } + currentSourceFile = undefined; + moduleInfo = undefined; + exportFunction = undefined; + contextObject = undefined; + hoistedStatements = undefined; + enclosingBlockScopedContainer = undefined; + return ts.aggregateTransformFlags(updated); + } + /** + * Collects the dependency groups for this files imports. + * + * @param externalImports The imports for the file. + */ + function collectDependencyGroups(externalImports) { + var groupIndices = ts.createMap(); + var dependencyGroups = []; + for (var _i = 0, externalImports_1 = externalImports; _i < externalImports_1.length; _i++) { + var externalImport = externalImports_1[_i]; + var externalModuleName = ts.getExternalModuleNameLiteral(externalImport, currentSourceFile, host, resolver, compilerOptions); + if (externalModuleName) { + var text = externalModuleName.text; + var groupIndex = groupIndices.get(text); + if (groupIndex !== undefined) { + // deduplicate/group entries in dependency list by the dependency name + dependencyGroups[groupIndex].externalImports.push(externalImport); + } + else { + groupIndices.set(text, dependencyGroups.length); + dependencyGroups.push({ + name: externalModuleName, + externalImports: [externalImport] + }); + } + } + } + return dependencyGroups; + } + /** + * Adds the statements for the module body function for the source file. + * + * @param node The source file for the module. + * @param dependencyGroups The grouped dependencies of the module. + */ + function createSystemModuleBody(node, dependencyGroups) { + // Shape of the body in system modules: + // + // function (exports) { + // + // + // + // return { + // setters: [ + // + // ], + // execute: function() { + // + // } + // } + // + // } + // + // i.e: + // + // import {x} from 'file1' + // var y = 1; + // export function foo() { return y + x(); } + // console.log(y); + // + // Will be transformed to: + // + // function(exports) { + // function foo() { return y + file_1.x(); } + // exports("foo", foo); + // var file_1, y; + // return { + // setters: [ + // function(v) { file_1 = v } + // ], + // execute(): function() { + // y = 1; + // console.log(y); + // } + // }; + // } + var statements = []; + // We start a new lexical environment in this function body, but *not* in the + // body of the execute function. This allows us to emit temporary declarations + // only in the outer module body and not in the inner one. + startLexicalEnvironment(); + // Add any prologue directives. + var ensureUseStrict = ts.getStrictOptionValue(compilerOptions, "alwaysStrict") || (!compilerOptions.noImplicitUseStrict && ts.isExternalModule(currentSourceFile)); + var statementOffset = ts.addPrologue(statements, node.statements, ensureUseStrict, sourceElementVisitor); + // var __moduleName = context_1 && context_1.id; + statements.push(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration("__moduleName", + /*type*/ undefined, ts.createLogicalAnd(contextObject, ts.createPropertyAccess(contextObject, "id"))) + ]))); + // Visit the synthetic external helpers import declaration if present + ts.visitNode(moduleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement); + // Visit the statements of the source file, emitting any transformations into + // the `executeStatements` array. We do this *before* we fill the `setters` array + // as we both emit transformations as well as aggregate some data used when creating + // setters. This allows us to reduce the number of times we need to loop through the + // statements of the source file. + var executeStatements = ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset); + // Emit early exports for function declarations. + ts.addRange(statements, hoistedStatements); + // We emit hoisted variables early to align roughly with our previous emit output. + // Two key differences in this approach are: + // - Temporary variables will appear at the top rather than at the bottom of the file + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + var exportStarFunction = addExportStarIfNeeded(statements); // TODO: GH#18217 + var moduleObject = ts.createObjectLiteral([ + ts.createPropertyAssignment("setters", createSettersArray(exportStarFunction, dependencyGroups)), + ts.createPropertyAssignment("execute", ts.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, + /*parameters*/ [], + /*type*/ undefined, ts.createBlock(executeStatements, /*multiLine*/ true))) + ]); + moduleObject.multiLine = true; + statements.push(ts.createReturn(moduleObject)); + return ts.createBlock(statements, /*multiLine*/ true); + } + /** + * Adds an exportStar function to a statement list if it is needed for the file. + * + * @param statements A statement list. + */ + function addExportStarIfNeeded(statements) { + if (!moduleInfo.hasExportStarsToExportValues) { + return; + } + // when resolving exports local exported entries/indirect exported entries in the module + // should always win over entries with similar names that were added via star exports + // to support this we store names of local/indirect exported entries in a set. + // this set is used to filter names brought by star expors. + // local names set should only be added if we have anything exported + if (!moduleInfo.exportedNames && moduleInfo.exportSpecifiers.size === 0) { + // no exported declarations (export var ...) or export specifiers (export {x}) + // check if we have any non star export declarations. + var hasExportDeclarationWithExportClause = false; + for (var _i = 0, _a = moduleInfo.externalImports; _i < _a.length; _i++) { + var externalImport = _a[_i]; + if (externalImport.kind === 255 /* ExportDeclaration */ && externalImport.exportClause) { + hasExportDeclarationWithExportClause = true; + break; + } + } + if (!hasExportDeclarationWithExportClause) { + // we still need to emit exportStar helper + var exportStarFunction_1 = createExportStarFunction(/*localNames*/ undefined); + statements.push(exportStarFunction_1); + return exportStarFunction_1.name; + } + } + var exportedNames = []; + if (moduleInfo.exportedNames) { + for (var _b = 0, _c = moduleInfo.exportedNames; _b < _c.length; _b++) { + var exportedLocalName = _c[_b]; + if (exportedLocalName.escapedText === "default") { + continue; + } + // write name of exported declaration, i.e 'export var x...' + exportedNames.push(ts.createPropertyAssignment(ts.createLiteral(exportedLocalName), ts.createTrue())); + } + } + for (var _d = 0, _e = moduleInfo.externalImports; _d < _e.length; _d++) { + var externalImport = _e[_d]; + if (externalImport.kind !== 255 /* ExportDeclaration */) { + continue; + } + if (!externalImport.exportClause) { + // export * from ... + continue; + } + for (var _f = 0, _g = externalImport.exportClause.elements; _f < _g.length; _f++) { + var element = _g[_f]; + // write name of indirectly exported entry, i.e. 'export {x} from ...' + exportedNames.push(ts.createPropertyAssignment(ts.createLiteral(ts.idText(element.name || element.propertyName)), ts.createTrue())); + } + } + var exportedNamesStorageRef = ts.createUniqueName("exportedNames"); + statements.push(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(exportedNamesStorageRef, + /*type*/ undefined, ts.createObjectLiteral(exportedNames, /*multiline*/ true)) + ]))); + var exportStarFunction = createExportStarFunction(exportedNamesStorageRef); + statements.push(exportStarFunction); + return exportStarFunction.name; + } + /** + * Creates an exportStar function for the file, with an optional set of excluded local + * names. + * + * @param localNames An optional reference to an object containing a set of excluded local + * names. + */ + function createExportStarFunction(localNames) { + var exportStarFunction = ts.createUniqueName("exportStar"); + var m = ts.createIdentifier("m"); + var n = ts.createIdentifier("n"); + var exports = ts.createIdentifier("exports"); + var condition = ts.createStrictInequality(n, ts.createLiteral("default")); + if (localNames) { + condition = ts.createLogicalAnd(condition, ts.createLogicalNot(ts.createCall(ts.createPropertyAccess(localNames, "hasOwnProperty"), + /*typeArguments*/ undefined, [n]))); + } + return ts.createFunctionDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, exportStarFunction, + /*typeParameters*/ undefined, [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, m)], + /*type*/ undefined, ts.createBlock([ + ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(exports, + /*type*/ undefined, ts.createObjectLiteral([])) + ])), + ts.createForIn(ts.createVariableDeclarationList([ + ts.createVariableDeclaration(n, /*type*/ undefined) + ]), m, ts.createBlock([ + ts.setEmitFlags(ts.createIf(condition, ts.createExpressionStatement(ts.createAssignment(ts.createElementAccess(exports, n), ts.createElementAccess(m, n)))), 1 /* SingleLine */) + ])), + ts.createExpressionStatement(ts.createCall(exportFunction, + /*typeArguments*/ undefined, [exports])) + ], /*multiline*/ true)); + } + /** + * Creates an array setter callbacks for each dependency group. + * + * @param exportStarFunction A reference to an exportStarFunction for the file. + * @param dependencyGroups An array of grouped dependencies. + */ + function createSettersArray(exportStarFunction, dependencyGroups) { + var setters = []; + for (var _i = 0, dependencyGroups_1 = dependencyGroups; _i < dependencyGroups_1.length; _i++) { + var group_1 = dependencyGroups_1[_i]; + // derive a unique name for parameter from the first named entry in the group + var localName = ts.forEach(group_1.externalImports, function (i) { return ts.getLocalNameForExternalImport(i, currentSourceFile); }); + var parameterName = localName ? ts.getGeneratedNameForNode(localName) : ts.createUniqueName(""); + var statements = []; + for (var _a = 0, _b = group_1.externalImports; _a < _b.length; _a++) { + var entry = _b[_a]; + var importVariableName = ts.getLocalNameForExternalImport(entry, currentSourceFile); // TODO: GH#18217 + switch (entry.kind) { + case 249 /* ImportDeclaration */: + if (!entry.importClause) { + // 'import "..."' case + // module is imported only for side-effects, no emit required + break; + } + // falls through + case 248 /* ImportEqualsDeclaration */: + ts.Debug.assert(importVariableName !== undefined); + // save import into the local + statements.push(ts.createExpressionStatement(ts.createAssignment(importVariableName, parameterName))); + break; + case 255 /* ExportDeclaration */: + ts.Debug.assert(importVariableName !== undefined); + if (entry.exportClause) { + // export {a, b as c} from 'foo' + // + // emit as: + // + // exports_({ + // "a": _["a"], + // "c": _["b"] + // }); + var properties = []; + for (var _c = 0, _d = entry.exportClause.elements; _c < _d.length; _c++) { + var e = _d[_c]; + properties.push(ts.createPropertyAssignment(ts.createLiteral(ts.idText(e.name)), ts.createElementAccess(parameterName, ts.createLiteral(ts.idText(e.propertyName || e.name))))); + } + statements.push(ts.createExpressionStatement(ts.createCall(exportFunction, + /*typeArguments*/ undefined, [ts.createObjectLiteral(properties, /*multiline*/ true)]))); + } + else { + // export * from 'foo' + // + // emit as: + // + // exportStar(foo_1_1); + statements.push(ts.createExpressionStatement(ts.createCall(exportStarFunction, + /*typeArguments*/ undefined, [parameterName]))); + } + break; + } + } + setters.push(ts.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, parameterName)], + /*type*/ undefined, ts.createBlock(statements, /*multiLine*/ true))); + } + return ts.createArrayLiteral(setters, /*multiLine*/ true); + } + // + // Top-level Source Element Visitors + // + /** + * Visit source elements at the top-level of a module. + * + * @param node The node to visit. + */ + function sourceElementVisitor(node) { + switch (node.kind) { + case 249 /* ImportDeclaration */: + return visitImportDeclaration(node); + case 248 /* ImportEqualsDeclaration */: + return visitImportEqualsDeclaration(node); + case 255 /* ExportDeclaration */: + // ExportDeclarations are elided as they are handled via + // `appendExportsOfDeclaration`. + return undefined; + case 254 /* ExportAssignment */: + return visitExportAssignment(node); + default: + return nestedElementVisitor(node); + } + } + /** + * Visits an ImportDeclaration node. + * + * @param node The node to visit. + */ + function visitImportDeclaration(node) { + var statements; + if (node.importClause) { + hoistVariableDeclaration(ts.getLocalNameForExternalImport(node, currentSourceFile)); // TODO: GH#18217 + } + if (hasAssociatedEndOfDeclarationMarker(node)) { + // Defer exports until we encounter an EndOfDeclarationMarker node + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportsOfImportDeclaration(deferredExports[id], node); + } + else { + statements = appendExportsOfImportDeclaration(statements, node); + } + return ts.singleOrMany(statements); + } + /** + * Visits an ImportEqualsDeclaration node. + * + * @param node The node to visit. + */ + function visitImportEqualsDeclaration(node) { + ts.Debug.assert(ts.isExternalModuleImportEqualsDeclaration(node), "import= for internal module references should be handled in an earlier transformer."); + var statements; + hoistVariableDeclaration(ts.getLocalNameForExternalImport(node, currentSourceFile)); // TODO: GH#18217 + if (hasAssociatedEndOfDeclarationMarker(node)) { + // Defer exports until we encounter an EndOfDeclarationMarker node + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportsOfImportEqualsDeclaration(deferredExports[id], node); + } + else { + statements = appendExportsOfImportEqualsDeclaration(statements, node); + } + return ts.singleOrMany(statements); + } + /** + * Visits an ExportAssignment node. + * + * @param node The node to visit. + */ + function visitExportAssignment(node) { + if (node.isExportEquals) { + // Elide `export=` as it is illegal in a SystemJS module. + return undefined; + } + var expression = ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression); + var original = node.original; + if (original && hasAssociatedEndOfDeclarationMarker(original)) { + // Defer exports until we encounter an EndOfDeclarationMarker node + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportStatement(deferredExports[id], ts.createIdentifier("default"), expression, /*allowComments*/ true); + } + else { + return createExportStatement(ts.createIdentifier("default"), expression, /*allowComments*/ true); + } + } + /** + * Visits a FunctionDeclaration, hoisting it to the outer module body function. + * + * @param node The node to visit. + */ + function visitFunctionDeclaration(node) { + if (ts.hasModifier(node, 1 /* Export */)) { + hoistedStatements = ts.append(hoistedStatements, ts.updateFunctionDeclaration(node, node.decorators, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, ts.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true), + /*typeParameters*/ undefined, ts.visitNodes(node.parameters, destructuringAndImportCallVisitor, ts.isParameterDeclaration), + /*type*/ undefined, ts.visitNode(node.body, destructuringAndImportCallVisitor, ts.isBlock))); + } + else { + hoistedStatements = ts.append(hoistedStatements, ts.visitEachChild(node, destructuringAndImportCallVisitor, context)); + } + if (hasAssociatedEndOfDeclarationMarker(node)) { + // Defer exports until we encounter an EndOfDeclarationMarker node + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node); + } + else { + hoistedStatements = appendExportsOfHoistedDeclaration(hoistedStatements, node); + } + return undefined; + } + /** + * Visits a ClassDeclaration, hoisting its name to the outer module body function. + * + * @param node The node to visit. + */ + function visitClassDeclaration(node) { + var statements; + // Hoist the name of the class declaration to the outer module body function. + var name = ts.getLocalName(node); + hoistVariableDeclaration(name); + // Rewrite the class declaration into an assignment of a class expression. + statements = ts.append(statements, ts.setTextRange(ts.createExpressionStatement(ts.createAssignment(name, ts.setTextRange(ts.createClassExpression( + /*modifiers*/ undefined, node.name, + /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, destructuringAndImportCallVisitor, ts.isHeritageClause), ts.visitNodes(node.members, destructuringAndImportCallVisitor, ts.isClassElement)), node))), node)); + if (hasAssociatedEndOfDeclarationMarker(node)) { + // Defer exports until we encounter an EndOfDeclarationMarker node + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node); + } + else { + statements = appendExportsOfHoistedDeclaration(statements, node); + } + return ts.singleOrMany(statements); + } + /** + * Visits a variable statement, hoisting declared names to the top-level module body. + * Each declaration is rewritten into an assignment expression. + * + * @param node The node to visit. + */ + function visitVariableStatement(node) { + if (!shouldHoistVariableDeclarationList(node.declarationList)) { + return ts.visitNode(node, destructuringAndImportCallVisitor, ts.isStatement); + } + var expressions; + var isExportedDeclaration = ts.hasModifier(node, 1 /* Export */); + var isMarkedDeclaration = hasAssociatedEndOfDeclarationMarker(node); + for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { + var variable = _a[_i]; + if (variable.initializer) { + expressions = ts.append(expressions, transformInitializedVariable(variable, isExportedDeclaration && !isMarkedDeclaration)); + } + else { + hoistBindingElement(variable); + } + } + var statements; + if (expressions) { + statements = ts.append(statements, ts.setTextRange(ts.createExpressionStatement(ts.inlineExpressions(expressions)), node)); + } + if (isMarkedDeclaration) { + // Defer exports until we encounter an EndOfDeclarationMarker node + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node, isExportedDeclaration); + } + else { + statements = appendExportsOfVariableStatement(statements, node, /*exportSelf*/ false); + } + return ts.singleOrMany(statements); + } + /** + * Hoists the declared names of a VariableDeclaration or BindingElement. + * + * @param node The declaration to hoist. + */ + function hoistBindingElement(node) { + if (ts.isBindingPattern(node.name)) { + for (var _i = 0, _a = node.name.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (!ts.isOmittedExpression(element)) { + hoistBindingElement(element); + } + } + } + else { + hoistVariableDeclaration(ts.getSynthesizedClone(node.name)); + } + } + /** + * Determines whether a VariableDeclarationList should be hoisted. + * + * @param node The node to test. + */ + function shouldHoistVariableDeclarationList(node) { + // hoist only non-block scoped declarations or block scoped declarations parented by source file + return (ts.getEmitFlags(node) & 2097152 /* NoHoisting */) === 0 + && (enclosingBlockScopedContainer.kind === 279 /* SourceFile */ + || (ts.getOriginalNode(node).flags & 3 /* BlockScoped */) === 0); + } + /** + * Transform an initialized variable declaration into an expression. + * + * @param node The node to transform. + * @param isExportedDeclaration A value indicating whether the variable is exported. + */ + function transformInitializedVariable(node, isExportedDeclaration) { + var createAssignment = isExportedDeclaration ? createExportedVariableAssignment : createNonExportedVariableAssignment; + return ts.isBindingPattern(node.name) + ? ts.flattenDestructuringAssignment(node, destructuringAndImportCallVisitor, context, 0 /* All */, + /*needsValue*/ false, createAssignment) + : node.initializer ? createAssignment(node.name, ts.visitNode(node.initializer, destructuringAndImportCallVisitor, ts.isExpression)) : node.name; + } + /** + * Creates an assignment expression for an exported variable declaration. + * + * @param name The name of the variable. + * @param value The value of the variable's initializer. + * @param location The source map location for the assignment. + */ + function createExportedVariableAssignment(name, value, location) { + return createVariableAssignment(name, value, location, /*isExportedDeclaration*/ true); + } + /** + * Creates an assignment expression for a non-exported variable declaration. + * + * @param name The name of the variable. + * @param value The value of the variable's initializer. + * @param location The source map location for the assignment. + */ + function createNonExportedVariableAssignment(name, value, location) { + return createVariableAssignment(name, value, location, /*isExportedDeclaration*/ false); + } + /** + * Creates an assignment expression for a variable declaration. + * + * @param name The name of the variable. + * @param value The value of the variable's initializer. + * @param location The source map location for the assignment. + * @param isExportedDeclaration A value indicating whether the variable is exported. + */ + function createVariableAssignment(name, value, location, isExportedDeclaration) { + hoistVariableDeclaration(ts.getSynthesizedClone(name)); + return isExportedDeclaration + ? createExportExpression(name, preventSubstitution(ts.setTextRange(ts.createAssignment(name, value), location))) + : preventSubstitution(ts.setTextRange(ts.createAssignment(name, value), location)); + } + /** + * Visits a MergeDeclarationMarker used as a placeholder for the beginning of a merged + * and transformed declaration. + * + * @param node The node to visit. + */ + function visitMergeDeclarationMarker(node) { + // For an EnumDeclaration or ModuleDeclaration that merges with a preceeding + // declaration we do not emit a leading variable declaration. To preserve the + // begin/end semantics of the declararation and to properly handle exports + // we wrapped the leading variable declaration in a `MergeDeclarationMarker`. + // + // To balance the declaration, we defer the exports of the elided variable + // statement until we visit this declaration's `EndOfDeclarationMarker`. + if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 219 /* VariableStatement */) { + var id = ts.getOriginalNodeId(node); + var isExportedDeclaration = ts.hasModifier(node.original, 1 /* Export */); + deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node.original, isExportedDeclaration); + } + return node; + } + /** + * Determines whether a node has an associated EndOfDeclarationMarker. + * + * @param node The node to test. + */ + function hasAssociatedEndOfDeclarationMarker(node) { + return (ts.getEmitFlags(node) & 4194304 /* HasEndOfDeclarationMarker */) !== 0; + } + /** + * Visits a DeclarationMarker used as a placeholder for the end of a transformed + * declaration. + * + * @param node The node to visit. + */ + function visitEndOfDeclarationMarker(node) { + // For some transformations we emit an `EndOfDeclarationMarker` to mark the actual + // end of the transformed declaration. We use this marker to emit any deferred exports + // of the declaration. + var id = ts.getOriginalNodeId(node); + var statements = deferredExports[id]; + if (statements) { + delete deferredExports[id]; + return ts.append(statements, node); + } + else { + var original = ts.getOriginalNode(node); + if (ts.isModuleOrEnumDeclaration(original)) { + return ts.append(appendExportsOfDeclaration(statements, original), node); + } + } + return node; + } + /** + * Appends the exports of an ImportDeclaration to a statement list, returning the + * statement list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param decl The declaration whose exports are to be recorded. + */ + function appendExportsOfImportDeclaration(statements, decl) { + if (moduleInfo.exportEquals) { + return statements; + } + var importClause = decl.importClause; + if (!importClause) { + return statements; + } + if (importClause.name) { + statements = appendExportsOfDeclaration(statements, importClause); + } + var namedBindings = importClause.namedBindings; + if (namedBindings) { + switch (namedBindings.kind) { + case 251 /* NamespaceImport */: + statements = appendExportsOfDeclaration(statements, namedBindings); + break; + case 252 /* NamedImports */: + for (var _i = 0, _a = namedBindings.elements; _i < _a.length; _i++) { + var importBinding = _a[_i]; + statements = appendExportsOfDeclaration(statements, importBinding); + } + break; + } + } + return statements; + } + /** + * Appends the export of an ImportEqualsDeclaration to a statement list, returning the + * statement list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param decl The declaration whose exports are to be recorded. + */ + function appendExportsOfImportEqualsDeclaration(statements, decl) { + if (moduleInfo.exportEquals) { + return statements; + } + return appendExportsOfDeclaration(statements, decl); + } + /** + * Appends the exports of a VariableStatement to a statement list, returning the statement + * list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param node The VariableStatement whose exports are to be recorded. + * @param exportSelf A value indicating whether to also export each VariableDeclaration of + * `nodes` declaration list. + */ + function appendExportsOfVariableStatement(statements, node, exportSelf) { + if (moduleInfo.exportEquals) { + return statements; + } + for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + if (decl.initializer || exportSelf) { + statements = appendExportsOfBindingElement(statements, decl, exportSelf); + } + } + return statements; + } + /** + * Appends the exports of a VariableDeclaration or BindingElement to a statement list, + * returning the statement list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param decl The declaration whose exports are to be recorded. + * @param exportSelf A value indicating whether to also export the declaration itself. + */ + function appendExportsOfBindingElement(statements, decl, exportSelf) { + if (moduleInfo.exportEquals) { + return statements; + } + if (ts.isBindingPattern(decl.name)) { + for (var _i = 0, _a = decl.name.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (!ts.isOmittedExpression(element)) { + statements = appendExportsOfBindingElement(statements, element, exportSelf); + } + } + } + else if (!ts.isGeneratedIdentifier(decl.name)) { + var excludeName = void 0; + if (exportSelf) { + statements = appendExportStatement(statements, decl.name, ts.getLocalName(decl)); + excludeName = ts.idText(decl.name); + } + statements = appendExportsOfDeclaration(statements, decl, excludeName); + } + return statements; + } + /** + * Appends the exports of a ClassDeclaration or FunctionDeclaration to a statement list, + * returning the statement list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param decl The declaration whose exports are to be recorded. + */ + function appendExportsOfHoistedDeclaration(statements, decl) { + if (moduleInfo.exportEquals) { + return statements; + } + var excludeName; + if (ts.hasModifier(decl, 1 /* Export */)) { + var exportName = ts.hasModifier(decl, 512 /* Default */) ? ts.createLiteral("default") : decl.name; + statements = appendExportStatement(statements, exportName, ts.getLocalName(decl)); + excludeName = ts.getTextOfIdentifierOrLiteral(exportName); + } + if (decl.name) { + statements = appendExportsOfDeclaration(statements, decl, excludeName); + } + return statements; + } + /** + * Appends the exports of a declaration to a statement list, returning the statement list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param decl The declaration to export. + * @param excludeName An optional name to exclude from exports. + */ + function appendExportsOfDeclaration(statements, decl, excludeName) { + if (moduleInfo.exportEquals) { + return statements; + } + var name = ts.getDeclarationName(decl); + var exportSpecifiers = moduleInfo.exportSpecifiers.get(ts.idText(name)); + if (exportSpecifiers) { + for (var _i = 0, exportSpecifiers_2 = exportSpecifiers; _i < exportSpecifiers_2.length; _i++) { + var exportSpecifier = exportSpecifiers_2[_i]; + if (exportSpecifier.name.escapedText !== excludeName) { + statements = appendExportStatement(statements, exportSpecifier.name, name); + } + } + } + return statements; + } + /** + * Appends the down-level representation of an export to a statement list, returning the + * statement list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param exportName The name of the export. + * @param expression The expression to export. + * @param allowComments Whether to allow comments on the export. + */ + function appendExportStatement(statements, exportName, expression, allowComments) { + statements = ts.append(statements, createExportStatement(exportName, expression, allowComments)); + return statements; + } + /** + * Creates a call to the current file's export function to export a value. + * + * @param name The bound name of the export. + * @param value The exported value. + * @param allowComments An optional value indicating whether to emit comments for the statement. + */ + function createExportStatement(name, value, allowComments) { + var statement = ts.createExpressionStatement(createExportExpression(name, value)); + ts.startOnNewLine(statement); + if (!allowComments) { + ts.setEmitFlags(statement, 1536 /* NoComments */); + } + return statement; + } + /** + * Creates a call to the current file's export function to export a value. + * + * @param name The bound name of the export. + * @param value The exported value. + */ + function createExportExpression(name, value) { + var exportName = ts.isIdentifier(name) ? ts.createLiteral(name) : name; + ts.setEmitFlags(value, ts.getEmitFlags(value) | 1536 /* NoComments */); + return ts.setCommentRange(ts.createCall(exportFunction, /*typeArguments*/ undefined, [exportName, value]), value); + } + // + // Top-Level or Nested Source Element Visitors + // + /** + * Visit nested elements at the top-level of a module. + * + * @param node The node to visit. + */ + function nestedElementVisitor(node) { + switch (node.kind) { + case 219 /* VariableStatement */: + return visitVariableStatement(node); + case 239 /* FunctionDeclaration */: + return visitFunctionDeclaration(node); + case 240 /* ClassDeclaration */: + return visitClassDeclaration(node); + case 225 /* ForStatement */: + return visitForStatement(node); + case 226 /* ForInStatement */: + return visitForInStatement(node); + case 227 /* ForOfStatement */: + return visitForOfStatement(node); + case 223 /* DoStatement */: + return visitDoStatement(node); + case 224 /* WhileStatement */: + return visitWhileStatement(node); + case 233 /* LabeledStatement */: + return visitLabeledStatement(node); + case 231 /* WithStatement */: + return visitWithStatement(node); + case 232 /* SwitchStatement */: + return visitSwitchStatement(node); + case 246 /* CaseBlock */: + return visitCaseBlock(node); + case 271 /* CaseClause */: + return visitCaseClause(node); + case 272 /* DefaultClause */: + return visitDefaultClause(node); + case 235 /* TryStatement */: + return visitTryStatement(node); + case 274 /* CatchClause */: + return visitCatchClause(node); + case 218 /* Block */: + return visitBlock(node); + case 310 /* MergeDeclarationMarker */: + return visitMergeDeclarationMarker(node); + case 311 /* EndOfDeclarationMarker */: + return visitEndOfDeclarationMarker(node); + default: + return destructuringAndImportCallVisitor(node); + } + } + /** + * Visits the body of a ForStatement to hoist declarations. + * + * @param node The node to visit. + */ + function visitForStatement(node) { + var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; + enclosingBlockScopedContainer = node; + node = ts.updateFor(node, node.initializer && visitForInitializer(node.initializer), ts.visitNode(node.condition, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.incrementor, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement)); + enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; + return node; + } + /** + * Visits the body of a ForInStatement to hoist declarations. + * + * @param node The node to visit. + */ + function visitForInStatement(node) { + var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; + enclosingBlockScopedContainer = node; + node = ts.updateForIn(node, visitForInitializer(node.initializer), ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock)); + enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; + return node; + } + /** + * Visits the body of a ForOfStatement to hoist declarations. + * + * @param node The node to visit. + */ + function visitForOfStatement(node) { + var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; + enclosingBlockScopedContainer = node; + node = ts.updateForOf(node, node.awaitModifier, visitForInitializer(node.initializer), ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock)); + enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; + return node; + } + /** + * Determines whether to hoist the initializer of a ForStatement, ForInStatement, or + * ForOfStatement. + * + * @param node The node to test. + */ + function shouldHoistForInitializer(node) { + return ts.isVariableDeclarationList(node) + && shouldHoistVariableDeclarationList(node); + } + /** + * Visits the initializer of a ForStatement, ForInStatement, or ForOfStatement + * + * @param node The node to visit. + */ + function visitForInitializer(node) { + if (shouldHoistForInitializer(node)) { + var expressions = void 0; + for (var _i = 0, _a = node.declarations; _i < _a.length; _i++) { + var variable = _a[_i]; + expressions = ts.append(expressions, transformInitializedVariable(variable, /*isExportedDeclaration*/ false)); + if (!variable.initializer) { + hoistBindingElement(variable); + } + } + return expressions ? ts.inlineExpressions(expressions) : ts.createOmittedExpression(); + } + else { + return ts.visitEachChild(node, nestedElementVisitor, context); + } + } + /** + * Visits the body of a DoStatement to hoist declarations. + * + * @param node The node to visit. + */ + function visitDoStatement(node) { + return ts.updateDo(node, ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock), ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression)); + } + /** + * Visits the body of a WhileStatement to hoist declarations. + * + * @param node The node to visit. + */ + function visitWhileStatement(node) { + return ts.updateWhile(node, ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock)); + } + /** + * Visits the body of a LabeledStatement to hoist declarations. + * + * @param node The node to visit. + */ + function visitLabeledStatement(node) { + return ts.updateLabel(node, node.label, ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock)); + } + /** + * Visits the body of a WithStatement to hoist declarations. + * + * @param node The node to visit. + */ + function visitWithStatement(node) { + return ts.updateWith(node, ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock)); + } + /** + * Visits the body of a SwitchStatement to hoist declarations. + * + * @param node The node to visit. + */ + function visitSwitchStatement(node) { + return ts.updateSwitch(node, ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.caseBlock, nestedElementVisitor, ts.isCaseBlock)); + } + /** + * Visits the body of a CaseBlock to hoist declarations. + * + * @param node The node to visit. + */ + function visitCaseBlock(node) { + var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; + enclosingBlockScopedContainer = node; + node = ts.updateCaseBlock(node, ts.visitNodes(node.clauses, nestedElementVisitor, ts.isCaseOrDefaultClause)); + enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; + return node; + } + /** + * Visits the body of a CaseClause to hoist declarations. + * + * @param node The node to visit. + */ + function visitCaseClause(node) { + return ts.updateCaseClause(node, ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNodes(node.statements, nestedElementVisitor, ts.isStatement)); + } + /** + * Visits the body of a DefaultClause to hoist declarations. + * + * @param node The node to visit. + */ + function visitDefaultClause(node) { + return ts.visitEachChild(node, nestedElementVisitor, context); + } + /** + * Visits the body of a TryStatement to hoist declarations. + * + * @param node The node to visit. + */ + function visitTryStatement(node) { + return ts.visitEachChild(node, nestedElementVisitor, context); + } + /** + * Visits the body of a CatchClause to hoist declarations. + * + * @param node The node to visit. + */ + function visitCatchClause(node) { + var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; + enclosingBlockScopedContainer = node; + node = ts.updateCatchClause(node, node.variableDeclaration, ts.visitNode(node.block, nestedElementVisitor, ts.isBlock)); + enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; + return node; + } + /** + * Visits the body of a Block to hoist declarations. + * + * @param node The node to visit. + */ + function visitBlock(node) { + var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; + enclosingBlockScopedContainer = node; + node = ts.visitEachChild(node, nestedElementVisitor, context); + enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; + return node; + } + // + // Destructuring Assignment Visitors + // + /** + * Visit nodes to flatten destructuring assignments to exported symbols. + * + * @param node The node to visit. + */ + function destructuringAndImportCallVisitor(node) { + if (node.transformFlags & 1024 /* DestructuringAssignment */ + && node.kind === 204 /* BinaryExpression */) { + return visitDestructuringAssignment(node); + } + else if (ts.isImportCall(node)) { + return visitImportCallExpression(node); + } + else if ((node.transformFlags & 2048 /* ContainsDestructuringAssignment */) || (node.transformFlags & 16777216 /* ContainsDynamicImport */)) { + return ts.visitEachChild(node, destructuringAndImportCallVisitor, context); + } + else { + return node; + } + } + function visitImportCallExpression(node) { + // import("./blah") + // emit as + // System.register([], function (_export, _context) { + // return { + // setters: [], + // execute: () => { + // _context.import('./blah'); + // } + // }; + // }); + return ts.createCall(ts.createPropertyAccess(contextObject, ts.createIdentifier("import")), + /*typeArguments*/ undefined, ts.some(node.arguments) ? [ts.visitNode(node.arguments[0], destructuringAndImportCallVisitor)] : []); + } + /** + * Visits a DestructuringAssignment to flatten destructuring to exported symbols. + * + * @param node The node to visit. + */ + function visitDestructuringAssignment(node) { + if (hasExportedReferenceInDestructuringTarget(node.left)) { + return ts.flattenDestructuringAssignment(node, destructuringAndImportCallVisitor, context, 0 /* All */, + /*needsValue*/ true); + } + return ts.visitEachChild(node, destructuringAndImportCallVisitor, context); + } + /** + * Determines whether the target of a destructuring assigment refers to an exported symbol. + * + * @param node The destructuring target. + */ + function hasExportedReferenceInDestructuringTarget(node) { + if (ts.isAssignmentExpression(node, /*excludeCompoundAssignment*/ true)) { + return hasExportedReferenceInDestructuringTarget(node.left); + } + else if (ts.isSpreadElement(node)) { + return hasExportedReferenceInDestructuringTarget(node.expression); + } + else if (ts.isObjectLiteralExpression(node)) { + return ts.some(node.properties, hasExportedReferenceInDestructuringTarget); + } + else if (ts.isArrayLiteralExpression(node)) { + return ts.some(node.elements, hasExportedReferenceInDestructuringTarget); + } + else if (ts.isShorthandPropertyAssignment(node)) { + return hasExportedReferenceInDestructuringTarget(node.name); + } + else if (ts.isPropertyAssignment(node)) { + return hasExportedReferenceInDestructuringTarget(node.initializer); + } + else if (ts.isIdentifier(node)) { + var container = resolver.getReferencedExportContainer(node); + return container !== undefined && container.kind === 279 /* SourceFile */; + } + else { + return false; + } + } + // + // Modifier Visitors + // + /** + * Visit nodes to elide module-specific modifiers. + * + * @param node The node to visit. + */ + function modifierVisitor(node) { + switch (node.kind) { + case 85 /* ExportKeyword */: + case 80 /* DefaultKeyword */: + return undefined; + } + return node; + } + // + // Emit Notification + // + /** + * Hook for node emit notifications. + * + * @param hint A hint as to the intended usage of the node. + * @param node The node to emit. + * @param emitCallback A callback used to emit the node in the printer. + */ + function onEmitNode(hint, node, emitCallback) { + if (node.kind === 279 /* SourceFile */) { + var id = ts.getOriginalNodeId(node); + currentSourceFile = node; + moduleInfo = moduleInfoMap[id]; + exportFunction = exportFunctionsMap[id]; + noSubstitution = noSubstitutionMap[id]; + if (noSubstitution) { + delete noSubstitutionMap[id]; + } + previousOnEmitNode(hint, node, emitCallback); + currentSourceFile = undefined; + moduleInfo = undefined; + exportFunction = undefined; + noSubstitution = undefined; + } + else { + previousOnEmitNode(hint, node, emitCallback); + } + } + // + // Substitutions + // + /** + * Hooks node substitutions. + * + * @param hint A hint as to the intended usage of the node. + * @param node The node to substitute. + */ + function onSubstituteNode(hint, node) { + node = previousOnSubstituteNode(hint, node); + if (isSubstitutionPrevented(node)) { + return node; + } + if (hint === 1 /* Expression */) { + return substituteExpression(node); + } + else if (hint === 4 /* Unspecified */) { + return substituteUnspecified(node); + } + return node; + } + /** + * Substitute the node, if necessary. + * + * @param node The node to substitute. + */ + function substituteUnspecified(node) { + switch (node.kind) { + case 276 /* ShorthandPropertyAssignment */: + return substituteShorthandPropertyAssignment(node); + } + return node; + } + /** + * Substitution for a ShorthandPropertyAssignment whose name that may contain an imported or exported symbol. + * + * @param node The node to substitute. + */ + function substituteShorthandPropertyAssignment(node) { + var name = node.name; + if (!ts.isGeneratedIdentifier(name) && !ts.isLocalName(name)) { + var importDeclaration = resolver.getReferencedImportDeclaration(name); + if (importDeclaration) { + if (ts.isImportClause(importDeclaration)) { + return ts.setTextRange(ts.createPropertyAssignment(ts.getSynthesizedClone(name), ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent), ts.createIdentifier("default"))), + /*location*/ node); + } + else if (ts.isImportSpecifier(importDeclaration)) { + return ts.setTextRange(ts.createPropertyAssignment(ts.getSynthesizedClone(name), ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent.parent.parent), ts.getSynthesizedClone(importDeclaration.propertyName || importDeclaration.name))), + /*location*/ node); + } + } + } + return node; + } + /** + * Substitute the expression, if necessary. + * + * @param node The node to substitute. + */ + function substituteExpression(node) { + switch (node.kind) { + case 72 /* Identifier */: + return substituteExpressionIdentifier(node); + case 204 /* BinaryExpression */: + return substituteBinaryExpression(node); + case 202 /* PrefixUnaryExpression */: + case 203 /* PostfixUnaryExpression */: + return substituteUnaryExpression(node); + } + return node; + } + /** + * Substitution for an Identifier expression that may contain an imported or exported symbol. + * + * @param node The node to substitute. + */ + function substituteExpressionIdentifier(node) { + if (ts.getEmitFlags(node) & 4096 /* HelperName */) { + var externalHelpersModuleName = ts.getExternalHelpersModuleName(currentSourceFile); + if (externalHelpersModuleName) { + return ts.createPropertyAccess(externalHelpersModuleName, node); + } + return node; + } + // When we see an identifier in an expression position that + // points to an imported symbol, we should substitute a qualified + // reference to the imported symbol if one is needed. + // + // - We do not substitute generated identifiers for any reason. + // - We do not substitute identifiers tagged with the LocalName flag. + if (!ts.isGeneratedIdentifier(node) && !ts.isLocalName(node)) { + var importDeclaration = resolver.getReferencedImportDeclaration(node); + if (importDeclaration) { + if (ts.isImportClause(importDeclaration)) { + return ts.setTextRange(ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent), ts.createIdentifier("default")), + /*location*/ node); + } + else if (ts.isImportSpecifier(importDeclaration)) { + return ts.setTextRange(ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent.parent.parent), ts.getSynthesizedClone(importDeclaration.propertyName || importDeclaration.name)), + /*location*/ node); + } + } + } + return node; + } + /** + * Substitution for a BinaryExpression that may contain an imported or exported symbol. + * + * @param node The node to substitute. + */ + function substituteBinaryExpression(node) { + // When we see an assignment expression whose left-hand side is an exported symbol, + // we should ensure all exports of that symbol are updated with the correct value. + // + // - We do not substitute generated identifiers for any reason. + // - We do not substitute identifiers tagged with the LocalName flag. + // - We do not substitute identifiers that were originally the name of an enum or + // namespace due to how they are transformed in TypeScript. + // - We only substitute identifiers that are exported at the top level. + if (ts.isAssignmentOperator(node.operatorToken.kind) + && ts.isIdentifier(node.left) + && !ts.isGeneratedIdentifier(node.left) + && !ts.isLocalName(node.left) + && !ts.isDeclarationNameOfEnumOrNamespace(node.left)) { + var exportedNames = getExports(node.left); + if (exportedNames) { + // For each additional export of the declaration, apply an export assignment. + var expression = node; + for (var _i = 0, exportedNames_4 = exportedNames; _i < exportedNames_4.length; _i++) { + var exportName = exportedNames_4[_i]; + expression = createExportExpression(exportName, preventSubstitution(expression)); + } + return expression; + } + } + return node; + } + /** + * Substitution for a UnaryExpression that may contain an imported or exported symbol. + * + * @param node The node to substitute. + */ + function substituteUnaryExpression(node) { + // When we see a prefix or postfix increment expression whose operand is an exported + // symbol, we should ensure all exports of that symbol are updated with the correct + // value. + // + // - We do not substitute generated identifiers for any reason. + // - We do not substitute identifiers tagged with the LocalName flag. + // - We do not substitute identifiers that were originally the name of an enum or + // namespace due to how they are transformed in TypeScript. + // - We only substitute identifiers that are exported at the top level. + if ((node.operator === 44 /* PlusPlusToken */ || node.operator === 45 /* MinusMinusToken */) + && ts.isIdentifier(node.operand) + && !ts.isGeneratedIdentifier(node.operand) + && !ts.isLocalName(node.operand) + && !ts.isDeclarationNameOfEnumOrNamespace(node.operand)) { + var exportedNames = getExports(node.operand); + if (exportedNames) { + var expression = node.kind === 203 /* PostfixUnaryExpression */ + ? ts.setTextRange(ts.createPrefix(node.operator, node.operand), node) + : node; + for (var _i = 0, exportedNames_5 = exportedNames; _i < exportedNames_5.length; _i++) { + var exportName = exportedNames_5[_i]; + expression = createExportExpression(exportName, preventSubstitution(expression)); + } + if (node.kind === 203 /* PostfixUnaryExpression */) { + expression = node.operator === 44 /* PlusPlusToken */ + ? ts.createSubtract(preventSubstitution(expression), ts.createLiteral(1)) + : ts.createAdd(preventSubstitution(expression), ts.createLiteral(1)); + } + return expression; + } + } + return node; + } + /** + * Gets the exports of a name. + * + * @param name The name. + */ + function getExports(name) { + var exportedNames; + if (!ts.isGeneratedIdentifier(name)) { + var valueDeclaration = resolver.getReferencedImportDeclaration(name) + || resolver.getReferencedValueDeclaration(name); + if (valueDeclaration) { + var exportContainer = resolver.getReferencedExportContainer(name, /*prefixLocals*/ false); + if (exportContainer && exportContainer.kind === 279 /* SourceFile */) { + exportedNames = ts.append(exportedNames, ts.getDeclarationName(valueDeclaration)); + } + exportedNames = ts.addRange(exportedNames, moduleInfo && moduleInfo.exportedBindings[ts.getOriginalNodeId(valueDeclaration)]); + } + } + return exportedNames; + } + /** + * Prevent substitution of a node for this transformer. + * + * @param node The node which should not be substituted. + */ + function preventSubstitution(node) { + if (noSubstitution === undefined) + noSubstitution = []; + noSubstitution[ts.getNodeId(node)] = true; + return node; + } + /** + * Determines whether a node should not be substituted. + * + * @param node The node to test. + */ + function isSubstitutionPrevented(node) { + return noSubstitution && node.id && noSubstitution[node.id]; + } + } + ts.transformSystemModule = transformSystemModule; +})(ts || (ts = {})); +/*@internal*/ +var ts; +(function (ts) { + function transformES2015Module(context) { + var compilerOptions = context.getCompilerOptions(); + var previousOnEmitNode = context.onEmitNode; + var previousOnSubstituteNode = context.onSubstituteNode; + context.onEmitNode = onEmitNode; + context.onSubstituteNode = onSubstituteNode; + context.enableEmitNotification(279 /* SourceFile */); + context.enableSubstitution(72 /* Identifier */); + var currentSourceFile; + return ts.chainBundle(transformSourceFile); + function transformSourceFile(node) { + if (node.isDeclarationFile) { + return node; + } + if (ts.isExternalModule(node) || compilerOptions.isolatedModules) { + var externalHelpersModuleName = ts.getOrCreateExternalHelpersModuleNameIfNeeded(node, compilerOptions); + if (externalHelpersModuleName) { + var statements = []; + var statementOffset = ts.addPrologue(statements, node.statements); + var tslibImport = ts.createImportDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(externalHelpersModuleName)), ts.createLiteral(ts.externalHelpersModuleNameText)); + ts.addEmitFlags(tslibImport, 67108864 /* NeverApplyImportHelper */); + ts.append(statements, tslibImport); + ts.addRange(statements, ts.visitNodes(node.statements, visitor, ts.isStatement, statementOffset)); + return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements)); + } + else { + return ts.visitEachChild(node, visitor, context); + } + } + return node; + } + function visitor(node) { + switch (node.kind) { + case 248 /* ImportEqualsDeclaration */: + // Elide `import=` as it is not legal with --module ES6 + return undefined; + case 254 /* ExportAssignment */: + return visitExportAssignment(node); + } + return node; + } + function visitExportAssignment(node) { + // Elide `export=` as it is not legal with --module ES6 + return node.isExportEquals ? undefined : node; + } + // + // Emit Notification + // + /** + * Hook for node emit. + * + * @param hint A hint as to the intended usage of the node. + * @param node The node to emit. + * @param emit A callback used to emit the node in the printer. + */ + function onEmitNode(hint, node, emitCallback) { + if (ts.isSourceFile(node)) { + currentSourceFile = node; + previousOnEmitNode(hint, node, emitCallback); + currentSourceFile = undefined; + } + else { + previousOnEmitNode(hint, node, emitCallback); + } + } + // + // Substitutions + // + /** + * Hooks node substitutions. + * + * @param hint A hint as to the intended usage of the node. + * @param node The node to substitute. + */ + function onSubstituteNode(hint, node) { + node = previousOnSubstituteNode(hint, node); + if (ts.isIdentifier(node) && hint === 1 /* Expression */) { + return substituteExpressionIdentifier(node); + } + return node; + } + function substituteExpressionIdentifier(node) { + if (ts.getEmitFlags(node) & 4096 /* HelperName */) { + var externalHelpersModuleName = ts.getExternalHelpersModuleName(currentSourceFile); + if (externalHelpersModuleName) { + return ts.createPropertyAccess(externalHelpersModuleName, node); + } + } + return node; + } + } + ts.transformES2015Module = transformES2015Module; +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + function canProduceDiagnostics(node) { + return ts.isVariableDeclaration(node) || + ts.isPropertyDeclaration(node) || + ts.isPropertySignature(node) || + ts.isBindingElement(node) || + ts.isSetAccessor(node) || + ts.isGetAccessor(node) || + ts.isConstructSignatureDeclaration(node) || + ts.isCallSignatureDeclaration(node) || + ts.isMethodDeclaration(node) || + ts.isMethodSignature(node) || + ts.isFunctionDeclaration(node) || + ts.isParameter(node) || + ts.isTypeParameterDeclaration(node) || + ts.isExpressionWithTypeArguments(node) || + ts.isImportEqualsDeclaration(node) || + ts.isTypeAliasDeclaration(node) || + ts.isConstructorDeclaration(node) || + ts.isIndexSignatureDeclaration(node); + } + ts.canProduceDiagnostics = canProduceDiagnostics; + function createGetSymbolAccessibilityDiagnosticForNodeName(node) { + if (ts.isSetAccessor(node) || ts.isGetAccessor(node)) { + return getAccessorNameVisibilityError; + } + else if (ts.isMethodSignature(node) || ts.isMethodDeclaration(node)) { + return getMethodNameVisibilityError; + } + else { + return createGetSymbolAccessibilityDiagnosticForNode(node); + } + function getAccessorNameVisibilityError(symbolAccessibilityResult) { + var diagnosticMessage = getAccessorNameVisibilityDiagnosticMessage(symbolAccessibilityResult); + return diagnosticMessage !== undefined ? { + diagnosticMessage: diagnosticMessage, + errorNode: node, + typeName: node.name + } : undefined; + } + function getAccessorNameVisibilityDiagnosticMessage(symbolAccessibilityResult) { + if (ts.hasModifier(node, 32 /* Static */)) { + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1; + } + else if (node.parent.kind === 240 /* ClassDeclaration */) { + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_private_name_1; + } + else { + return symbolAccessibilityResult.errorModuleName ? + ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_private_name_1; + } + } + function getMethodNameVisibilityError(symbolAccessibilityResult) { + var diagnosticMessage = getMethodNameVisibilityDiagnosticMessage(symbolAccessibilityResult); + return diagnosticMessage !== undefined ? { + diagnosticMessage: diagnosticMessage, + errorNode: node, + typeName: node.name + } : undefined; + } + function getMethodNameVisibilityDiagnosticMessage(symbolAccessibilityResult) { + if (ts.hasModifier(node, 32 /* Static */)) { + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_private_name_1; + } + else if (node.parent.kind === 240 /* ClassDeclaration */) { + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Public_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Public_method_0_of_exported_class_has_or_is_using_private_name_1; + } + else { + return symbolAccessibilityResult.errorModuleName ? + ts.Diagnostics.Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Method_0_of_exported_interface_has_or_is_using_private_name_1; + } + } + } + ts.createGetSymbolAccessibilityDiagnosticForNodeName = createGetSymbolAccessibilityDiagnosticForNodeName; + function createGetSymbolAccessibilityDiagnosticForNode(node) { + if (ts.isVariableDeclaration(node) || ts.isPropertyDeclaration(node) || ts.isPropertySignature(node) || ts.isBindingElement(node) || ts.isConstructorDeclaration(node)) { + return getVariableDeclarationTypeVisibilityError; + } + else if (ts.isSetAccessor(node) || ts.isGetAccessor(node)) { + return getAccessorDeclarationTypeVisibilityError; + } + else if (ts.isConstructSignatureDeclaration(node) || ts.isCallSignatureDeclaration(node) || ts.isMethodDeclaration(node) || ts.isMethodSignature(node) || ts.isFunctionDeclaration(node) || ts.isIndexSignatureDeclaration(node)) { + return getReturnTypeVisibilityError; + } + else if (ts.isParameter(node)) { + if (ts.isParameterPropertyDeclaration(node) && ts.hasModifier(node.parent, 8 /* Private */)) { + return getVariableDeclarationTypeVisibilityError; + } + return getParameterDeclarationTypeVisibilityError; + } + else if (ts.isTypeParameterDeclaration(node)) { + return getTypeParameterConstraintVisibilityError; + } + else if (ts.isExpressionWithTypeArguments(node)) { + return getHeritageClauseVisibilityError; + } + else if (ts.isImportEqualsDeclaration(node)) { + return getImportEntityNameVisibilityError; + } + else if (ts.isTypeAliasDeclaration(node)) { + return getTypeAliasDeclarationVisibilityError; + } + else { + return ts.Debug.assertNever(node, "Attempted to set a declaration diagnostic context for unhandled node kind: " + ts.SyntaxKind[node.kind]); + } + function getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) { + if (node.kind === 237 /* VariableDeclaration */ || node.kind === 186 /* BindingElement */) { + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Exported_variable_0_has_or_is_using_private_name_1; + } + // This check is to ensure we don't report error on constructor parameter property as that error would be reported during parameter emit + // The only exception here is if the constructor was marked as private. we are not emitting the constructor parameters at all. + else if (node.kind === 154 /* PropertyDeclaration */ || node.kind === 153 /* PropertySignature */ || + (node.kind === 151 /* Parameter */ && ts.hasModifier(node.parent, 8 /* Private */))) { + // TODO(jfreeman): Deal with computed properties in error reporting. + if (ts.hasModifier(node, 32 /* Static */)) { + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1; + } + else if (node.parent.kind === 240 /* ClassDeclaration */ || node.kind === 151 /* Parameter */) { + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_private_name_1; + } + else { + // Interfaces cannot have types that cannot be named + return symbolAccessibilityResult.errorModuleName ? + ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_private_name_1; + } + } + } + function getVariableDeclarationTypeVisibilityError(symbolAccessibilityResult) { + var diagnosticMessage = getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult); + return diagnosticMessage !== undefined ? { + diagnosticMessage: diagnosticMessage, + errorNode: node, + typeName: node.name + } : undefined; + } + function getAccessorDeclarationTypeVisibilityError(symbolAccessibilityResult) { + var diagnosticMessage; + if (node.kind === 159 /* SetAccessor */) { + // Getters can infer the return type from the returned expression, but setters cannot, so the + // "_from_external_module_1_but_cannot_be_named" case cannot occur. + if (ts.hasModifier(node, 32 /* Static */)) { + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + ts.Diagnostics.Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1; + } + else { + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + ts.Diagnostics.Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_private_name_1; + } + } + else { + if (ts.hasModifier(node, 32 /* Static */)) { + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_private_name_1; + } + else { + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Return_type_of_public_getter_0_from_exported_class_has_or_is_using_private_name_1; + } + } + return { + diagnosticMessage: diagnosticMessage, + errorNode: node.name, + typeName: node.name + }; + } + function getReturnTypeVisibilityError(symbolAccessibilityResult) { + var diagnosticMessage; + switch (node.kind) { + case 161 /* ConstructSignature */: + // Interfaces cannot have return types that cannot be named + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + ts.Diagnostics.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : + ts.Diagnostics.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0; + break; + case 160 /* CallSignature */: + // Interfaces cannot have return types that cannot be named + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + ts.Diagnostics.Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : + ts.Diagnostics.Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0; + break; + case 162 /* IndexSignature */: + // Interfaces cannot have return types that cannot be named + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + ts.Diagnostics.Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : + ts.Diagnostics.Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0; + break; + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + if (ts.hasModifier(node, 32 /* Static */)) { + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : + ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1 : + ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0; + } + else if (node.parent.kind === 240 /* ClassDeclaration */) { + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : + ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1 : + ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0; + } + else { + // Interfaces cannot have return types that cannot be named + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + ts.Diagnostics.Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : + ts.Diagnostics.Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0; + } + break; + case 239 /* FunctionDeclaration */: + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : + ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1 : + ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_private_name_0; + break; + default: + return ts.Debug.fail("This is unknown kind for signature: " + node.kind); + } + return { + diagnosticMessage: diagnosticMessage, + errorNode: node.name || node + }; + } + function getParameterDeclarationTypeVisibilityError(symbolAccessibilityResult) { + var diagnosticMessage = getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult); + return diagnosticMessage !== undefined ? { + diagnosticMessage: diagnosticMessage, + errorNode: node, + typeName: node.name + } : undefined; + } + function getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) { + switch (node.parent.kind) { + case 157 /* Constructor */: + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1; + case 161 /* ConstructSignature */: + case 166 /* ConstructorType */: + // Interfaces cannot have parameter types that cannot be named + return symbolAccessibilityResult.errorModuleName ? + ts.Diagnostics.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1; + case 160 /* CallSignature */: + // Interfaces cannot have parameter types that cannot be named + return symbolAccessibilityResult.errorModuleName ? + ts.Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1; + case 162 /* IndexSignature */: + // Interfaces cannot have parameter types that cannot be named + return symbolAccessibilityResult.errorModuleName ? + ts.Diagnostics.Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1; + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + if (ts.hasModifier(node.parent, 32 /* Static */)) { + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1; + } + else if (node.parent.parent.kind === 240 /* ClassDeclaration */) { + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1; + } + else { + // Interfaces cannot have parameter types that cannot be named + return symbolAccessibilityResult.errorModuleName ? + ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1; + } + case 239 /* FunctionDeclaration */: + case 165 /* FunctionType */: + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_private_name_1; + default: + return ts.Debug.fail("Unknown parent for parameter: " + ts.SyntaxKind[node.parent.kind]); + } + } + function getTypeParameterConstraintVisibilityError() { + // Type parameter constraints are named by user so we should always be able to name it + var diagnosticMessage; + switch (node.parent.kind) { + case 240 /* ClassDeclaration */: + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_class_has_or_is_using_private_name_1; + break; + case 241 /* InterfaceDeclaration */: + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1; + break; + case 161 /* ConstructSignature */: + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1; + break; + case 160 /* CallSignature */: + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1; + break; + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + if (ts.hasModifier(node.parent, 32 /* Static */)) { + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1; + } + else if (node.parent.parent.kind === 240 /* ClassDeclaration */) { + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1; + } + else { + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1; + } + break; + case 239 /* FunctionDeclaration */: + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_function_has_or_is_using_private_name_1; + break; + case 242 /* TypeAliasDeclaration */: + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1; + break; + default: + return ts.Debug.fail("This is unknown parent for type parameter: " + node.parent.kind); + } + return { + diagnosticMessage: diagnosticMessage, + errorNode: node, + typeName: node.name + }; + } + function getHeritageClauseVisibilityError() { + var diagnosticMessage; + // Heritage clause is written by user so it can always be named + if (node.parent.parent.kind === 240 /* ClassDeclaration */) { + // Class or Interface implemented/extended is inaccessible + diagnosticMessage = ts.isHeritageClause(node.parent) && node.parent.token === 109 /* ImplementsKeyword */ ? + ts.Diagnostics.Implements_clause_of_exported_class_0_has_or_is_using_private_name_1 : + ts.Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1; + } + else { + // interface is inaccessible + diagnosticMessage = ts.Diagnostics.extends_clause_of_exported_interface_0_has_or_is_using_private_name_1; + } + return { + diagnosticMessage: diagnosticMessage, + errorNode: node, + typeName: ts.getNameOfDeclaration(node.parent.parent) + }; + } + function getImportEntityNameVisibilityError() { + return { + diagnosticMessage: ts.Diagnostics.Import_declaration_0_is_using_private_name_1, + errorNode: node, + typeName: node.name + }; + } + function getTypeAliasDeclarationVisibilityError() { + return { + diagnosticMessage: ts.Diagnostics.Exported_type_alias_0_has_or_is_using_private_name_1, + errorNode: node.type, + typeName: node.name + }; + } + } + ts.createGetSymbolAccessibilityDiagnosticForNode = createGetSymbolAccessibilityDiagnosticForNode; +})(ts || (ts = {})); +/*@internal*/ +var ts; +(function (ts) { + function getDeclarationDiagnostics(host, resolver, file) { + if (file && ts.isSourceFileJS(file)) { + return []; // No declaration diagnostics for js for now + } + var compilerOptions = host.getCompilerOptions(); + var result = ts.transformNodes(resolver, host, compilerOptions, file ? [file] : ts.filter(host.getSourceFiles(), ts.isSourceFileNotJS), [transformDeclarations], /*allowDtsFiles*/ false); + return result.diagnostics; + } + ts.getDeclarationDiagnostics = getDeclarationDiagnostics; + var declarationEmitNodeBuilderFlags = 1024 /* MultilineObjectLiterals */ | + 2048 /* WriteClassExpressionAsTypeLiteral */ | + 4096 /* UseTypeOfFunction */ | + 8 /* UseStructuralFallback */ | + 524288 /* AllowEmptyTuple */ | + 4 /* GenerateNamesForShadowedTypeParams */ | + 1 /* NoTruncation */; + /** + * Transforms a ts file into a .d.ts file + * This process requires type information, which is retrieved through the emit resolver. Because of this, + * in many places this transformer assumes it will be operating on parse tree nodes directly. + * This means that _no transforms should be allowed to occur before this one_. + */ + function transformDeclarations(context) { + var throwDiagnostic = function () { return ts.Debug.fail("Diagnostic emitted without context"); }; + var getSymbolAccessibilityDiagnostic = throwDiagnostic; + var needsDeclare = true; + var isBundledEmit = false; + var resultHasExternalModuleIndicator = false; + var needsScopeFixMarker = false; + var resultHasScopeMarker = false; + var enclosingDeclaration; + var necessaryTypeReferences; + var lateMarkedStatements; + var lateStatementReplacementMap; + var suppressNewDiagnosticContexts; + var exportedModulesFromDeclarationEmit; + var host = context.getEmitHost(); + var symbolTracker = { + trackSymbol: trackSymbol, + reportInaccessibleThisError: reportInaccessibleThisError, + reportInaccessibleUniqueSymbolError: reportInaccessibleUniqueSymbolError, + reportPrivateInBaseOfClassExpression: reportPrivateInBaseOfClassExpression, + reportLikelyUnsafeImportRequiredError: reportLikelyUnsafeImportRequiredError, + moduleResolverHost: host, + trackReferencedAmbientModule: trackReferencedAmbientModule, + trackExternalModuleSymbolOfImportTypeNode: trackExternalModuleSymbolOfImportTypeNode + }; + var errorNameNode; + var currentSourceFile; + var refs; + var libs; + var resolver = context.getEmitResolver(); + var options = context.getCompilerOptions(); + var newLine = ts.getNewLineCharacter(options); + var noResolve = options.noResolve, stripInternal = options.stripInternal; + return transformRoot; + function recordTypeReferenceDirectivesIfNecessary(typeReferenceDirectives) { + if (!typeReferenceDirectives) { + return; + } + necessaryTypeReferences = necessaryTypeReferences || ts.createMap(); + for (var _i = 0, typeReferenceDirectives_2 = typeReferenceDirectives; _i < typeReferenceDirectives_2.length; _i++) { + var ref = typeReferenceDirectives_2[_i]; + necessaryTypeReferences.set(ref, true); + } + } + function trackReferencedAmbientModule(node, symbol) { + // If it is visible via `// `, then we should just use that + var directives = resolver.getTypeReferenceDirectivesForSymbol(symbol, 67108863 /* All */); + if (ts.length(directives)) { + return recordTypeReferenceDirectivesIfNecessary(directives); + } + // Otherwise we should emit a path-based reference + var container = ts.getSourceFileOfNode(node); + refs.set("" + ts.getOriginalNodeId(container), container); + } + function handleSymbolAccessibilityError(symbolAccessibilityResult) { + if (symbolAccessibilityResult.accessibility === 0 /* Accessible */) { + // Add aliases back onto the possible imports list if they're not there so we can try them again with updated visibility info + if (symbolAccessibilityResult && symbolAccessibilityResult.aliasesToMakeVisible) { + if (!lateMarkedStatements) { + lateMarkedStatements = symbolAccessibilityResult.aliasesToMakeVisible; + } + else { + for (var _i = 0, _a = symbolAccessibilityResult.aliasesToMakeVisible; _i < _a.length; _i++) { + var ref = _a[_i]; + ts.pushIfUnique(lateMarkedStatements, ref); + } + } + } + // TODO: Do all these accessibility checks inside/after the first pass in the checker when declarations are enabled, if possible + } + else { + // Report error + var errorInfo = getSymbolAccessibilityDiagnostic(symbolAccessibilityResult); + if (errorInfo) { + if (errorInfo.typeName) { + context.addDiagnostic(ts.createDiagnosticForNode(symbolAccessibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, ts.getTextOfNode(errorInfo.typeName), symbolAccessibilityResult.errorSymbolName, symbolAccessibilityResult.errorModuleName)); + } + else { + context.addDiagnostic(ts.createDiagnosticForNode(symbolAccessibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, symbolAccessibilityResult.errorSymbolName, symbolAccessibilityResult.errorModuleName)); + } + } + } + } + function trackExternalModuleSymbolOfImportTypeNode(symbol) { + if (!isBundledEmit) { + (exportedModulesFromDeclarationEmit || (exportedModulesFromDeclarationEmit = [])).push(symbol); + } + } + function trackSymbol(symbol, enclosingDeclaration, meaning) { + if (symbol.flags & 262144 /* TypeParameter */) + return; + handleSymbolAccessibilityError(resolver.isSymbolAccessible(symbol, enclosingDeclaration, meaning, /*shouldComputeAliasesToMakeVisible*/ true)); + recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForSymbol(symbol, meaning)); + } + function reportPrivateInBaseOfClassExpression(propertyName) { + if (errorNameNode) { + context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.Property_0_of_exported_class_expression_may_not_be_private_or_protected, propertyName)); + } + } + function reportInaccessibleUniqueSymbolError() { + if (errorNameNode) { + context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary, ts.declarationNameToString(errorNameNode), "unique symbol")); + } + } + function reportInaccessibleThisError() { + if (errorNameNode) { + context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary, ts.declarationNameToString(errorNameNode), "this")); + } + } + function reportLikelyUnsafeImportRequiredError(specifier) { + if (errorNameNode) { + context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_annotation_is_necessary, ts.declarationNameToString(errorNameNode), specifier)); + } + } + function transformRoot(node) { + if (node.kind === 279 /* SourceFile */ && (node.isDeclarationFile || ts.isSourceFileJS(node))) { + return node; + } + if (node.kind === 280 /* Bundle */) { + isBundledEmit = true; + refs = ts.createMap(); + libs = ts.createMap(); + var hasNoDefaultLib_1 = false; + var bundle = ts.createBundle(ts.map(node.sourceFiles, function (sourceFile) { + if (sourceFile.isDeclarationFile || ts.isSourceFileJS(sourceFile)) + return undefined; // Omit declaration files from bundle results, too // TODO: GH#18217 + hasNoDefaultLib_1 = hasNoDefaultLib_1 || sourceFile.hasNoDefaultLib; + currentSourceFile = sourceFile; + enclosingDeclaration = sourceFile; + lateMarkedStatements = undefined; + suppressNewDiagnosticContexts = false; + lateStatementReplacementMap = ts.createMap(); + getSymbolAccessibilityDiagnostic = throwDiagnostic; + needsScopeFixMarker = false; + resultHasScopeMarker = false; + collectReferences(sourceFile, refs); + collectLibs(sourceFile, libs); + if (ts.isExternalModule(sourceFile)) { + resultHasExternalModuleIndicator = false; // unused in external module bundle emit (all external modules are within module blocks, therefore are known to be modules) + needsDeclare = false; + var statements_4 = ts.visitNodes(sourceFile.statements, visitDeclarationStatements); + var newFile = ts.updateSourceFileNode(sourceFile, [ts.createModuleDeclaration([], [ts.createModifier(125 /* DeclareKeyword */)], ts.createLiteral(ts.getResolvedExternalModuleName(context.getEmitHost(), sourceFile)), ts.createModuleBlock(ts.setTextRange(ts.createNodeArray(transformAndReplaceLatePaintedStatements(statements_4)), sourceFile.statements)))], /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false, /*libReferences*/ []); + return newFile; + } + needsDeclare = true; + var updated = ts.visitNodes(sourceFile.statements, visitDeclarationStatements); + return ts.updateSourceFileNode(sourceFile, transformAndReplaceLatePaintedStatements(updated), /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false, /*libReferences*/ []); + }), ts.mapDefined(node.prepends, function (prepend) { + if (prepend.kind === 282 /* InputFiles */) { + return ts.createUnparsedSourceFile(prepend.declarationText, prepend.declarationMapPath, prepend.declarationMapText); + } + })); + bundle.syntheticFileReferences = []; + bundle.syntheticTypeReferences = getFileReferencesForUsedTypeReferences(); + bundle.syntheticLibReferences = getLibReferences(); + bundle.hasNoDefaultLib = hasNoDefaultLib_1; + var outputFilePath_1 = ts.getDirectoryPath(ts.normalizeSlashes(ts.getOutputPathsFor(node, host, /*forceDtsPaths*/ true).declarationFilePath)); + var referenceVisitor_1 = mapReferencesIntoArray(bundle.syntheticFileReferences, outputFilePath_1); + refs.forEach(referenceVisitor_1); + return bundle; + } + // Single source file + needsDeclare = true; + needsScopeFixMarker = false; + resultHasScopeMarker = false; + enclosingDeclaration = node; + currentSourceFile = node; + getSymbolAccessibilityDiagnostic = throwDiagnostic; + isBundledEmit = false; + resultHasExternalModuleIndicator = false; + suppressNewDiagnosticContexts = false; + lateMarkedStatements = undefined; + lateStatementReplacementMap = ts.createMap(); + necessaryTypeReferences = undefined; + refs = collectReferences(currentSourceFile, ts.createMap()); + libs = collectLibs(currentSourceFile, ts.createMap()); + var references = []; + var outputFilePath = ts.getDirectoryPath(ts.normalizeSlashes(ts.getOutputPathsFor(node, host, /*forceDtsPaths*/ true).declarationFilePath)); + var referenceVisitor = mapReferencesIntoArray(references, outputFilePath); + var statements = ts.visitNodes(node.statements, visitDeclarationStatements); + var combinedStatements = ts.setTextRange(ts.createNodeArray(transformAndReplaceLatePaintedStatements(statements)), node.statements); + refs.forEach(referenceVisitor); + var emittedImports = ts.filter(combinedStatements, ts.isAnyImportSyntax); + if (ts.isExternalModule(node) && (!resultHasExternalModuleIndicator || (needsScopeFixMarker && !resultHasScopeMarker))) { + combinedStatements = ts.setTextRange(ts.createNodeArray(combinedStatements.concat([ts.createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createNamedExports([]), /*moduleSpecifier*/ undefined)])), combinedStatements); + } + var updated = ts.updateSourceFileNode(node, combinedStatements, /*isDeclarationFile*/ true, references, getFileReferencesForUsedTypeReferences(), node.hasNoDefaultLib, getLibReferences()); + updated.exportedModulesFromDeclarationEmit = exportedModulesFromDeclarationEmit; + return updated; + function getLibReferences() { + return ts.map(ts.arrayFrom(libs.keys()), function (lib) { return ({ fileName: lib, pos: -1, end: -1 }); }); + } + function getFileReferencesForUsedTypeReferences() { + return necessaryTypeReferences ? ts.mapDefined(ts.arrayFrom(necessaryTypeReferences.keys()), getFileReferenceForTypeName) : []; + } + function getFileReferenceForTypeName(typeName) { + // Elide type references for which we have imports + if (emittedImports) { + for (var _i = 0, emittedImports_1 = emittedImports; _i < emittedImports_1.length; _i++) { + var importStatement = emittedImports_1[_i]; + if (ts.isImportEqualsDeclaration(importStatement) && ts.isExternalModuleReference(importStatement.moduleReference)) { + var expr = importStatement.moduleReference.expression; + if (ts.isStringLiteralLike(expr) && expr.text === typeName) { + return undefined; + } + } + else if (ts.isImportDeclaration(importStatement) && ts.isStringLiteral(importStatement.moduleSpecifier) && importStatement.moduleSpecifier.text === typeName) { + return undefined; + } + } + } + return { fileName: typeName, pos: -1, end: -1 }; + } + function mapReferencesIntoArray(references, outputFilePath) { + return function (file) { + var declFileName; + if (file.isDeclarationFile) { // Neither decl files or js should have their refs changed + declFileName = file.fileName; + } + else { + if (isBundledEmit && ts.contains(node.sourceFiles, file)) + return; // Omit references to files which are being merged + var paths = ts.getOutputPathsFor(file, host, /*forceDtsPaths*/ true); + declFileName = paths.declarationFilePath || paths.jsFilePath || file.fileName; + } + if (declFileName) { + var fileName = ts.getRelativePathToDirectoryOrUrl(outputFilePath, declFileName, host.getCurrentDirectory(), host.getCanonicalFileName, + /*isAbsolutePathAnUrl*/ false); + if (ts.startsWith(fileName, "./") && ts.hasExtension(fileName)) { + fileName = fileName.substring(2); + } + // omit references to files from node_modules (npm may disambiguate module + // references when installing this package, making the path is unreliable). + if (ts.startsWith(fileName, "node_modules/") || fileName.indexOf("/node_modules/") !== -1) { + return; + } + references.push({ pos: -1, end: -1, fileName: fileName }); + } + }; + } + } + function collectReferences(sourceFile, ret) { + if (noResolve || ts.isSourceFileJS(sourceFile)) + return ret; + ts.forEach(sourceFile.referencedFiles, function (f) { + var elem = ts.tryResolveScriptReference(host, sourceFile, f); + if (elem) { + ret.set("" + ts.getOriginalNodeId(elem), elem); + } + }); + return ret; + } + function collectLibs(sourceFile, ret) { + ts.forEach(sourceFile.libReferenceDirectives, function (ref) { + var lib = host.getLibFileFromReference(ref); + if (lib) { + ret.set(ref.fileName.toLocaleLowerCase(), true); + } + }); + return ret; + } + function filterBindingPatternInitializers(name) { + if (name.kind === 72 /* Identifier */) { + return name; + } + else { + if (name.kind === 185 /* ArrayBindingPattern */) { + return ts.updateArrayBindingPattern(name, ts.visitNodes(name.elements, visitBindingElement)); + } + else { + return ts.updateObjectBindingPattern(name, ts.visitNodes(name.elements, visitBindingElement)); + } + } + function visitBindingElement(elem) { + if (elem.kind === 210 /* OmittedExpression */) { + return elem; + } + return ts.updateBindingElement(elem, elem.dotDotDotToken, elem.propertyName, filterBindingPatternInitializers(elem.name), shouldPrintWithInitializer(elem) ? elem.initializer : undefined); + } + } + function ensureParameter(p, modifierMask) { + var oldDiag; + if (!suppressNewDiagnosticContexts) { + oldDiag = getSymbolAccessibilityDiagnostic; + getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(p); + } + var newParam = ts.updateParameter(p, + /*decorators*/ undefined, maskModifiers(p, modifierMask), p.dotDotDotToken, filterBindingPatternInitializers(p.name), resolver.isOptionalParameter(p) ? (p.questionToken || ts.createToken(56 /* QuestionToken */)) : undefined, ensureType(p, p.type, /*ignorePrivate*/ true), // Ignore private param props, since this type is going straight back into a param + ensureNoInitializer(p)); + if (!suppressNewDiagnosticContexts) { + getSymbolAccessibilityDiagnostic = oldDiag; + } + return newParam; + } + function shouldPrintWithInitializer(node) { + return canHaveLiteralInitializer(node) && resolver.isLiteralConstDeclaration(ts.getParseTreeNode(node)); // TODO: Make safe + } + function ensureNoInitializer(node) { + if (shouldPrintWithInitializer(node)) { + return resolver.createLiteralConstValue(ts.getParseTreeNode(node), symbolTracker); // TODO: Make safe + } + return undefined; + } + function ensureType(node, type, ignorePrivate) { + if (!ignorePrivate && ts.hasModifier(node, 8 /* Private */)) { + // Private nodes emit no types (except private parameter properties, whose parameter types are actually visible) + return; + } + if (shouldPrintWithInitializer(node)) { + // Literal const declarations will have an initializer ensured rather than a type + return; + } + var shouldUseResolverType = node.kind === 151 /* Parameter */ && + (resolver.isRequiredInitializedParameter(node) || + resolver.isOptionalUninitializedParameterProperty(node)); + if (type && !shouldUseResolverType) { + return ts.visitNode(type, visitDeclarationSubtree); + } + if (!ts.getParseTreeNode(node)) { + return type ? ts.visitNode(type, visitDeclarationSubtree) : ts.createKeywordTypeNode(120 /* AnyKeyword */); + } + if (node.kind === 159 /* SetAccessor */) { + // Set accessors with no associated type node (from it's param or get accessor return) are `any` since they are never contextually typed right now + // (The inferred type here will be void, but the old declaration emitter printed `any`, so this replicates that) + return ts.createKeywordTypeNode(120 /* AnyKeyword */); + } + errorNameNode = node.name; + var oldDiag; + if (!suppressNewDiagnosticContexts) { + oldDiag = getSymbolAccessibilityDiagnostic; + getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(node); + } + if (node.kind === 237 /* VariableDeclaration */ || node.kind === 186 /* BindingElement */) { + return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker)); + } + if (node.kind === 151 /* Parameter */ + || node.kind === 154 /* PropertyDeclaration */ + || node.kind === 153 /* PropertySignature */) { + if (!node.initializer) + return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker, shouldUseResolverType)); + return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker, shouldUseResolverType) || resolver.createTypeOfExpression(node.initializer, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker)); + } + return cleanup(resolver.createReturnTypeOfSignatureDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker)); + function cleanup(returnValue) { + errorNameNode = undefined; + if (!suppressNewDiagnosticContexts) { + getSymbolAccessibilityDiagnostic = oldDiag; + } + return returnValue || ts.createKeywordTypeNode(120 /* AnyKeyword */); + } + } + function isDeclarationAndNotVisible(node) { + node = ts.getParseTreeNode(node); + switch (node.kind) { + case 239 /* FunctionDeclaration */: + case 244 /* ModuleDeclaration */: + case 241 /* InterfaceDeclaration */: + case 240 /* ClassDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 243 /* EnumDeclaration */: + return !resolver.isDeclarationVisible(node); + // The following should be doing their own visibility checks based on filtering their members + case 237 /* VariableDeclaration */: + return !getBindingNameVisible(node); + case 248 /* ImportEqualsDeclaration */: + case 249 /* ImportDeclaration */: + case 255 /* ExportDeclaration */: + case 254 /* ExportAssignment */: + return false; + } + return false; + } + function getBindingNameVisible(elem) { + if (ts.isOmittedExpression(elem)) { + return false; + } + if (ts.isBindingPattern(elem.name)) { + // If any child binding pattern element has been marked visible (usually by collect linked aliases), then this is visible + return ts.some(elem.name.elements, getBindingNameVisible); + } + else { + return resolver.isDeclarationVisible(elem); + } + } + function updateParamsList(node, params, modifierMask) { + if (ts.hasModifier(node, 8 /* Private */)) { + return undefined; // TODO: GH#18217 + } + var newParams = ts.map(params, function (p) { return ensureParameter(p, modifierMask); }); + if (!newParams) { + return undefined; // TODO: GH#18217 + } + return ts.createNodeArray(newParams, params.hasTrailingComma); + } + function ensureTypeParams(node, params) { + return ts.hasModifier(node, 8 /* Private */) ? undefined : ts.visitNodes(params, visitDeclarationSubtree); + } + function isEnclosingDeclaration(node) { + return ts.isSourceFile(node) + || ts.isTypeAliasDeclaration(node) + || ts.isModuleDeclaration(node) + || ts.isClassDeclaration(node) + || ts.isInterfaceDeclaration(node) + || ts.isFunctionLike(node) + || ts.isIndexSignatureDeclaration(node) + || ts.isMappedTypeNode(node); + } + function checkEntityNameVisibility(entityName, enclosingDeclaration) { + var visibilityResult = resolver.isEntityNameVisible(entityName, enclosingDeclaration); + handleSymbolAccessibilityError(visibilityResult); + recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForEntityName(entityName)); + } + function preserveJsDoc(updated, original) { + if (ts.hasJSDocNodes(updated) && ts.hasJSDocNodes(original)) { + updated.jsDoc = original.jsDoc; + } + return ts.setCommentRange(updated, ts.getCommentRange(original)); + } + function rewriteModuleSpecifier(parent, input) { + if (!input) + return undefined; // TODO: GH#18217 + resultHasExternalModuleIndicator = resultHasExternalModuleIndicator || (parent.kind !== 244 /* ModuleDeclaration */ && parent.kind !== 183 /* ImportType */); + if (ts.isStringLiteralLike(input)) { + if (isBundledEmit) { + var newName = ts.getExternalModuleNameFromDeclaration(context.getEmitHost(), resolver, parent); + if (newName) { + return ts.createLiteral(newName); + } + } + else { + var symbol = resolver.getSymbolOfExternalModuleSpecifier(input); + if (symbol) { + (exportedModulesFromDeclarationEmit || (exportedModulesFromDeclarationEmit = [])).push(symbol); + } + } + } + return input; + } + function transformImportEqualsDeclaration(decl) { + if (!resolver.isDeclarationVisible(decl)) + return; + if (decl.moduleReference.kind === 259 /* ExternalModuleReference */) { + // Rewrite external module names if necessary + var specifier = ts.getExternalModuleImportEqualsDeclarationExpression(decl); + return ts.updateImportEqualsDeclaration(decl, + /*decorators*/ undefined, decl.modifiers, decl.name, ts.updateExternalModuleReference(decl.moduleReference, rewriteModuleSpecifier(decl, specifier))); + } + else { + var oldDiag = getSymbolAccessibilityDiagnostic; + getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(decl); + checkEntityNameVisibility(decl.moduleReference, enclosingDeclaration); + getSymbolAccessibilityDiagnostic = oldDiag; + return decl; + } + } + function transformImportDeclaration(decl) { + if (!decl.importClause) { + // import "mod" - possibly needed for side effects? (global interface patches, module augmentations, etc) + return ts.updateImportDeclaration(decl, + /*decorators*/ undefined, decl.modifiers, decl.importClause, rewriteModuleSpecifier(decl, decl.moduleSpecifier)); + } + // The `importClause` visibility corresponds to the default's visibility. + var visibleDefaultBinding = decl.importClause && decl.importClause.name && resolver.isDeclarationVisible(decl.importClause) ? decl.importClause.name : undefined; + if (!decl.importClause.namedBindings) { + // No named bindings (either namespace or list), meaning the import is just default or should be elided + return visibleDefaultBinding && ts.updateImportDeclaration(decl, /*decorators*/ undefined, decl.modifiers, ts.updateImportClause(decl.importClause, visibleDefaultBinding, + /*namedBindings*/ undefined), rewriteModuleSpecifier(decl, decl.moduleSpecifier)); + } + if (decl.importClause.namedBindings.kind === 251 /* NamespaceImport */) { + // Namespace import (optionally with visible default) + var namedBindings = resolver.isDeclarationVisible(decl.importClause.namedBindings) ? decl.importClause.namedBindings : /*namedBindings*/ undefined; + return visibleDefaultBinding || namedBindings ? ts.updateImportDeclaration(decl, /*decorators*/ undefined, decl.modifiers, ts.updateImportClause(decl.importClause, visibleDefaultBinding, namedBindings), rewriteModuleSpecifier(decl, decl.moduleSpecifier)) : undefined; + } + // Named imports (optionally with visible default) + var bindingList = ts.mapDefined(decl.importClause.namedBindings.elements, function (b) { return resolver.isDeclarationVisible(b) ? b : undefined; }); + if ((bindingList && bindingList.length) || visibleDefaultBinding) { + return ts.updateImportDeclaration(decl, + /*decorators*/ undefined, decl.modifiers, ts.updateImportClause(decl.importClause, visibleDefaultBinding, bindingList && bindingList.length ? ts.updateNamedImports(decl.importClause.namedBindings, bindingList) : undefined), rewriteModuleSpecifier(decl, decl.moduleSpecifier)); + } + // Nothing visible + } + function transformAndReplaceLatePaintedStatements(statements) { + // This is a `while` loop because `handleSymbolAccessibilityError` can see additional import aliases marked as visible during + // error handling which must now be included in the output and themselves checked for errors. + // For example: + // ``` + // module A { + // export module Q {} + // import B = Q; + // import C = B; + // export import D = C; + // } + // ``` + // In such a scenario, only Q and D are initially visible, but we don't consider imports as private names - instead we say they if they are referenced they must + // be recorded. So while checking D's visibility we mark C as visible, then we must check C which in turn marks B, completing the chain of + // dependent imports and allowing a valid declaration file output. Today, this dependent alias marking only happens for internal import aliases. + while (ts.length(lateMarkedStatements)) { + var i = lateMarkedStatements.shift(); + if (!ts.isLateVisibilityPaintedStatement(i)) { + return ts.Debug.fail("Late replaced statement was found which is not handled by the declaration transformer!: " + (ts.SyntaxKind ? ts.SyntaxKind[i.kind] : i.kind)); + } + var result = transformTopLevelDeclaration(i, /*privateDeclaration*/ true); + lateStatementReplacementMap.set("" + ts.getOriginalNodeId(i), result); + } + // And lastly, we need to get the final form of all those indetermine import declarations from before and add them to the output list + // (and remove them from the set to examine for outter declarations) + return ts.visitNodes(statements, visitLateVisibilityMarkedStatements); + function visitLateVisibilityMarkedStatements(statement) { + if (ts.isLateVisibilityPaintedStatement(statement)) { + var key = "" + ts.getOriginalNodeId(statement); + if (lateStatementReplacementMap.has(key)) { + var result = lateStatementReplacementMap.get(key); + lateStatementReplacementMap.delete(key); + if (result && ts.isSourceFile(statement.parent)) { + if (ts.isArray(result) ? ts.some(result, needsScopeMarker) : needsScopeMarker(result)) { + // Top-level declarations in .d.ts files are always considered exported even without a modifier unless there's an export assignment or specifier + needsScopeFixMarker = true; + } + if (ts.isArray(result) ? ts.some(result, isExternalModuleIndicator) : isExternalModuleIndicator(result)) { + resultHasExternalModuleIndicator = true; + } + } + return result; + } + } + return statement; + } + } + function isExternalModuleIndicator(result) { + // Exported top-level member indicates moduleness + return ts.isAnyImportOrReExport(result) || ts.isExportAssignment(result) || ts.hasModifier(result, 1 /* Export */); + } + function needsScopeMarker(result) { + return !ts.isAnyImportOrReExport(result) && !ts.isExportAssignment(result) && !ts.hasModifier(result, 1 /* Export */) && !ts.isAmbientModule(result); + } + function visitDeclarationSubtree(input) { + if (shouldStripInternal(input)) + return; + if (ts.isDeclaration(input)) { + if (isDeclarationAndNotVisible(input)) + return; + if (ts.hasDynamicName(input) && !resolver.isLateBound(ts.getParseTreeNode(input))) { + return; + } + } + // Elide implementation signatures from overload sets + if (ts.isFunctionLike(input) && resolver.isImplementationOfOverload(input)) + return; + // Elide semicolon class statements + if (ts.isSemicolonClassElement(input)) + return; + var previousEnclosingDeclaration; + if (isEnclosingDeclaration(input)) { + previousEnclosingDeclaration = enclosingDeclaration; + enclosingDeclaration = input; + } + var oldDiag = getSymbolAccessibilityDiagnostic; + // Emit methods which are private as properties with no type information + if (ts.isMethodDeclaration(input) || ts.isMethodSignature(input)) { + if (ts.hasModifier(input, 8 /* Private */)) { + if (input.symbol && input.symbol.declarations && input.symbol.declarations[0] !== input) + return; // Elide all but the first overload + return cleanup(ts.createProperty(/*decorators*/ undefined, ensureModifiers(input), input.name, /*questionToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined)); + } + } + var canProdiceDiagnostic = ts.canProduceDiagnostics(input); + if (canProdiceDiagnostic && !suppressNewDiagnosticContexts) { + getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(input); + } + if (ts.isTypeQueryNode(input)) { + checkEntityNameVisibility(input.exprName, enclosingDeclaration); + } + var oldWithinObjectLiteralType = suppressNewDiagnosticContexts; + var shouldEnterSuppressNewDiagnosticsContextContext = ((input.kind === 168 /* TypeLiteral */ || input.kind === 181 /* MappedType */) && input.parent.kind !== 242 /* TypeAliasDeclaration */); + if (shouldEnterSuppressNewDiagnosticsContextContext) { + // We stop making new diagnostic contexts within object literal types. Unless it's an object type on the RHS of a type alias declaration. Then we do. + suppressNewDiagnosticContexts = true; + } + if (isProcessedComponent(input)) { + switch (input.kind) { + case 211 /* ExpressionWithTypeArguments */: { + if ((ts.isEntityName(input.expression) || ts.isEntityNameExpression(input.expression))) { + checkEntityNameVisibility(input.expression, enclosingDeclaration); + } + var node = ts.visitEachChild(input, visitDeclarationSubtree, context); + return cleanup(ts.updateExpressionWithTypeArguments(node, ts.parenthesizeTypeParameters(node.typeArguments), node.expression)); + } + case 164 /* TypeReference */: { + checkEntityNameVisibility(input.typeName, enclosingDeclaration); + var node = ts.visitEachChild(input, visitDeclarationSubtree, context); + return cleanup(ts.updateTypeReferenceNode(node, node.typeName, ts.parenthesizeTypeParameters(node.typeArguments))); + } + case 161 /* ConstructSignature */: + return cleanup(ts.updateConstructSignature(input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type))); + case 157 /* Constructor */: { + var isPrivate = ts.hasModifier(input, 8 /* Private */); + // A constructor declaration may not have a type annotation + var ctor = ts.createSignatureDeclaration(157 /* Constructor */, isPrivate ? undefined : ensureTypeParams(input, input.typeParameters), + // TODO: GH#18217 + isPrivate ? undefined : updateParamsList(input, input.parameters, 0 /* None */), + /*type*/ undefined); + ctor.modifiers = ts.createNodeArray(ensureModifiers(input)); + return cleanup(ctor); + } + case 156 /* MethodDeclaration */: { + var sig = ts.createSignatureDeclaration(155 /* MethodSignature */, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type)); + sig.name = input.name; + sig.modifiers = ts.createNodeArray(ensureModifiers(input)); + sig.questionToken = input.questionToken; + return cleanup(sig); + } + case 158 /* GetAccessor */: { + var newNode = ensureAccessor(input); + return cleanup(newNode); + } + case 159 /* SetAccessor */: { + var newNode = ensureAccessor(input); + return cleanup(newNode); + } + case 154 /* PropertyDeclaration */: + return cleanup(ts.updateProperty(input, + /*decorators*/ undefined, ensureModifiers(input), input.name, input.questionToken, !ts.hasModifier(input, 8 /* Private */) ? ensureType(input, input.type) : undefined, ensureNoInitializer(input))); + case 153 /* PropertySignature */: + return cleanup(ts.updatePropertySignature(input, ensureModifiers(input), input.name, input.questionToken, !ts.hasModifier(input, 8 /* Private */) ? ensureType(input, input.type) : undefined, ensureNoInitializer(input))); + case 155 /* MethodSignature */: { + return cleanup(ts.updateMethodSignature(input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type), input.name, input.questionToken)); + } + case 160 /* CallSignature */: { + return cleanup(ts.updateCallSignature(input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type))); + } + case 162 /* IndexSignature */: { + return cleanup(ts.updateIndexSignature(input, + /*decorators*/ undefined, ensureModifiers(input), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree) || ts.createKeywordTypeNode(120 /* AnyKeyword */))); + } + case 237 /* VariableDeclaration */: { + if (ts.isBindingPattern(input.name)) { + return recreateBindingPattern(input.name); + } + shouldEnterSuppressNewDiagnosticsContextContext = true; + suppressNewDiagnosticContexts = true; // Variable declaration types also suppress new diagnostic contexts, provided the contexts wouldn't be made for binding pattern types + return cleanup(ts.updateVariableDeclaration(input, input.name, ensureType(input, input.type), ensureNoInitializer(input))); + } + case 150 /* TypeParameter */: { + if (isPrivateMethodTypeParameter(input) && (input.default || input.constraint)) { + return cleanup(ts.updateTypeParameterDeclaration(input, input.name, /*constraint*/ undefined, /*defaultType*/ undefined)); + } + return cleanup(ts.visitEachChild(input, visitDeclarationSubtree, context)); + } + case 175 /* ConditionalType */: { + // We have to process conditional types in a special way because for visibility purposes we need to push a new enclosingDeclaration + // just for the `infer` types in the true branch. It's an implicit declaration scope that only applies to _part_ of the type. + var checkType = ts.visitNode(input.checkType, visitDeclarationSubtree); + var extendsType = ts.visitNode(input.extendsType, visitDeclarationSubtree); + var oldEnclosingDecl = enclosingDeclaration; + enclosingDeclaration = input.trueType; + var trueType = ts.visitNode(input.trueType, visitDeclarationSubtree); + enclosingDeclaration = oldEnclosingDecl; + var falseType = ts.visitNode(input.falseType, visitDeclarationSubtree); + return cleanup(ts.updateConditionalTypeNode(input, checkType, extendsType, trueType, falseType)); + } + case 165 /* FunctionType */: { + return cleanup(ts.updateFunctionTypeNode(input, ts.visitNodes(input.typeParameters, visitDeclarationSubtree), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree))); + } + case 166 /* ConstructorType */: { + return cleanup(ts.updateConstructorTypeNode(input, ts.visitNodes(input.typeParameters, visitDeclarationSubtree), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree))); + } + case 183 /* ImportType */: { + if (!ts.isLiteralImportTypeNode(input)) + return cleanup(input); + return cleanup(ts.updateImportTypeNode(input, ts.updateLiteralTypeNode(input.argument, rewriteModuleSpecifier(input, input.argument.literal)), input.qualifier, ts.visitNodes(input.typeArguments, visitDeclarationSubtree, ts.isTypeNode), input.isTypeOf)); + } + default: ts.Debug.assertNever(input, "Attempted to process unhandled node kind: " + ts.SyntaxKind[input.kind]); + } + } + return cleanup(ts.visitEachChild(input, visitDeclarationSubtree, context)); + function cleanup(returnValue) { + if (returnValue && canProdiceDiagnostic && ts.hasDynamicName(input)) { + checkName(input); + } + if (isEnclosingDeclaration(input)) { + enclosingDeclaration = previousEnclosingDeclaration; + } + if (canProdiceDiagnostic && !suppressNewDiagnosticContexts) { + getSymbolAccessibilityDiagnostic = oldDiag; + } + if (shouldEnterSuppressNewDiagnosticsContextContext) { + suppressNewDiagnosticContexts = oldWithinObjectLiteralType; + } + if (returnValue === input) { + return returnValue; + } + return returnValue && ts.setOriginalNode(preserveJsDoc(returnValue, input), input); + } + } + function isPrivateMethodTypeParameter(node) { + return node.parent.kind === 156 /* MethodDeclaration */ && ts.hasModifier(node.parent, 8 /* Private */); + } + function visitDeclarationStatements(input) { + if (!isPreservedDeclarationStatement(input)) { + // return undefined for unmatched kinds to omit them from the tree + return; + } + if (shouldStripInternal(input)) + return; + switch (input.kind) { + case 255 /* ExportDeclaration */: { + if (ts.isSourceFile(input.parent)) { + resultHasExternalModuleIndicator = true; + resultHasScopeMarker = true; + } + // Always visible if the parent node isn't dropped for being not visible + // Rewrite external module names if necessary + return ts.updateExportDeclaration(input, /*decorators*/ undefined, input.modifiers, input.exportClause, rewriteModuleSpecifier(input, input.moduleSpecifier)); + } + case 254 /* ExportAssignment */: { + // Always visible if the parent node isn't dropped for being not visible + if (ts.isSourceFile(input.parent)) { + resultHasExternalModuleIndicator = true; + resultHasScopeMarker = true; + } + if (input.expression.kind === 72 /* Identifier */) { + return input; + } + else { + var newId = ts.createOptimisticUniqueName("_default"); + getSymbolAccessibilityDiagnostic = function () { return ({ + diagnosticMessage: ts.Diagnostics.Default_export_of_the_module_has_or_is_using_private_name_0, + errorNode: input + }); }; + var varDecl = ts.createVariableDeclaration(newId, resolver.createTypeOfExpression(input.expression, input, declarationEmitNodeBuilderFlags, symbolTracker), /*initializer*/ undefined); + var statement = ts.createVariableStatement(needsDeclare ? [ts.createModifier(125 /* DeclareKeyword */)] : [], ts.createVariableDeclarationList([varDecl], 2 /* Const */)); + return [statement, ts.updateExportAssignment(input, input.decorators, input.modifiers, newId)]; + } + } + } + var result = transformTopLevelDeclaration(input); + // Don't actually transform yet; just leave as original node - will be elided/swapped by late pass + lateStatementReplacementMap.set("" + ts.getOriginalNodeId(input), result); + return input; + } + function transformTopLevelDeclaration(input, isPrivate) { + if (shouldStripInternal(input)) + return; + switch (input.kind) { + case 248 /* ImportEqualsDeclaration */: { + return transformImportEqualsDeclaration(input); + } + case 249 /* ImportDeclaration */: { + return transformImportDeclaration(input); + } + } + if (ts.isDeclaration(input) && isDeclarationAndNotVisible(input)) + return; + // Elide implementation signatures from overload sets + if (ts.isFunctionLike(input) && resolver.isImplementationOfOverload(input)) + return; + var previousEnclosingDeclaration; + if (isEnclosingDeclaration(input)) { + previousEnclosingDeclaration = enclosingDeclaration; + enclosingDeclaration = input; + } + var canProdiceDiagnostic = ts.canProduceDiagnostics(input); + var oldDiag = getSymbolAccessibilityDiagnostic; + if (canProdiceDiagnostic) { + getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(input); + } + var previousNeedsDeclare = needsDeclare; + switch (input.kind) { + case 242 /* TypeAliasDeclaration */: // Type aliases get `declare`d if need be (for legacy support), but that's all + return cleanup(ts.updateTypeAliasDeclaration(input, + /*decorators*/ undefined, ensureModifiers(input, isPrivate), input.name, ts.visitNodes(input.typeParameters, visitDeclarationSubtree, ts.isTypeParameterDeclaration), ts.visitNode(input.type, visitDeclarationSubtree, ts.isTypeNode))); + case 241 /* InterfaceDeclaration */: { + return cleanup(ts.updateInterfaceDeclaration(input, + /*decorators*/ undefined, ensureModifiers(input, isPrivate), input.name, ensureTypeParams(input, input.typeParameters), transformHeritageClauses(input.heritageClauses), ts.visitNodes(input.members, visitDeclarationSubtree))); + } + case 239 /* FunctionDeclaration */: { + // Generators lose their generator-ness, excepting their return type + var clean = cleanup(ts.updateFunctionDeclaration(input, + /*decorators*/ undefined, ensureModifiers(input, isPrivate), + /*asteriskToken*/ undefined, input.name, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type), + /*body*/ undefined)); + if (clean && resolver.isExpandoFunctionDeclaration(input)) { + var declarations = ts.mapDefined(resolver.getPropertiesOfContainerFunction(input), function (p) { + if (!ts.isPropertyAccessExpression(p.valueDeclaration)) { + return undefined; + } + var type = resolver.createTypeOfDeclaration(p.valueDeclaration, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker); + var varDecl = ts.createVariableDeclaration(ts.unescapeLeadingUnderscores(p.escapedName), type, /*initializer*/ undefined); + return ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([varDecl])); + }); + var namespaceDecl = ts.createModuleDeclaration(/*decorators*/ undefined, ensureModifiers(input, isPrivate), input.name, ts.createModuleBlock(declarations), 16 /* Namespace */); + return [clean, namespaceDecl]; + } + else { + return clean; + } + } + case 244 /* ModuleDeclaration */: { + needsDeclare = false; + var inner = input.body; + if (inner && inner.kind === 245 /* ModuleBlock */) { + var statements = ts.visitNodes(inner.statements, visitDeclarationStatements); + var body = ts.updateModuleBlock(inner, transformAndReplaceLatePaintedStatements(statements)); + needsDeclare = previousNeedsDeclare; + var mods = ensureModifiers(input, isPrivate); + return cleanup(ts.updateModuleDeclaration(input, + /*decorators*/ undefined, mods, ts.isExternalModuleAugmentation(input) ? rewriteModuleSpecifier(input, input.name) : input.name, body)); + } + else { + needsDeclare = previousNeedsDeclare; + var mods = ensureModifiers(input, isPrivate); + needsDeclare = false; + ts.visitNode(inner, visitDeclarationStatements); + // eagerly transform nested namespaces (the nesting doesn't need any elision or painting done) + var id = "" + ts.getOriginalNodeId(inner); // TODO: GH#18217 + var body = lateStatementReplacementMap.get(id); + lateStatementReplacementMap.delete(id); + return cleanup(ts.updateModuleDeclaration(input, + /*decorators*/ undefined, mods, input.name, body)); + } + } + case 240 /* ClassDeclaration */: { + var modifiers = ts.createNodeArray(ensureModifiers(input, isPrivate)); + var typeParameters = ensureTypeParams(input, input.typeParameters); + var ctor = ts.getFirstConstructorWithBody(input); + var parameterProperties = void 0; + if (ctor) { + var oldDiag_1 = getSymbolAccessibilityDiagnostic; + parameterProperties = ts.compact(ts.flatMap(ctor.parameters, function (param) { + if (!ts.hasModifier(param, 92 /* ParameterPropertyModifier */)) + return; + getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(param); + if (param.name.kind === 72 /* Identifier */) { + return preserveJsDoc(ts.createProperty( + /*decorators*/ undefined, ensureModifiers(param), param.name, param.questionToken, ensureType(param, param.type), ensureNoInitializer(param)), param); + } + else { + // Pattern - this is currently an error, but we emit declarations for it somewhat correctly + return walkBindingPattern(param.name); + } + function walkBindingPattern(pattern) { + var elems; + for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) { + var elem = _a[_i]; + if (ts.isOmittedExpression(elem)) + continue; + if (ts.isBindingPattern(elem.name)) { + elems = ts.concatenate(elems, walkBindingPattern(elem.name)); + } + elems = elems || []; + elems.push(ts.createProperty( + /*decorators*/ undefined, ensureModifiers(param), elem.name, + /*questionToken*/ undefined, ensureType(elem, /*type*/ undefined), + /*initializer*/ undefined)); + } + return elems; + } + })); + getSymbolAccessibilityDiagnostic = oldDiag_1; + } + var members = ts.createNodeArray(ts.concatenate(parameterProperties, ts.visitNodes(input.members, visitDeclarationSubtree))); + var extendsClause_1 = ts.getEffectiveBaseTypeNode(input); + if (extendsClause_1 && !ts.isEntityNameExpression(extendsClause_1.expression) && extendsClause_1.expression.kind !== 96 /* NullKeyword */) { + // We must add a temporary declaration for the extends clause expression + var newId_1 = ts.createOptimisticUniqueName(ts.unescapeLeadingUnderscores(input.name.escapedText) + "_base"); // TODO: GH#18217 + getSymbolAccessibilityDiagnostic = function () { return ({ + diagnosticMessage: ts.Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1, + errorNode: extendsClause_1, + typeName: input.name + }); }; + var varDecl = ts.createVariableDeclaration(newId_1, resolver.createTypeOfExpression(extendsClause_1.expression, input, declarationEmitNodeBuilderFlags, symbolTracker), /*initializer*/ undefined); + var statement = ts.createVariableStatement(needsDeclare ? [ts.createModifier(125 /* DeclareKeyword */)] : [], ts.createVariableDeclarationList([varDecl], 2 /* Const */)); + var heritageClauses = ts.createNodeArray(ts.map(input.heritageClauses, function (clause) { + if (clause.token === 86 /* ExtendsKeyword */) { + var oldDiag_2 = getSymbolAccessibilityDiagnostic; + getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(clause.types[0]); + var newClause = ts.updateHeritageClause(clause, ts.map(clause.types, function (t) { return ts.updateExpressionWithTypeArguments(t, ts.visitNodes(t.typeArguments, visitDeclarationSubtree), newId_1); })); + getSymbolAccessibilityDiagnostic = oldDiag_2; + return newClause; + } + return ts.updateHeritageClause(clause, ts.visitNodes(ts.createNodeArray(ts.filter(clause.types, function (t) { return ts.isEntityNameExpression(t.expression) || t.expression.kind === 96 /* NullKeyword */; })), visitDeclarationSubtree)); + })); + return [statement, cleanup(ts.updateClassDeclaration(input, + /*decorators*/ undefined, modifiers, input.name, typeParameters, heritageClauses, members))]; // TODO: GH#18217 + } + else { + var heritageClauses = transformHeritageClauses(input.heritageClauses); + return cleanup(ts.updateClassDeclaration(input, + /*decorators*/ undefined, modifiers, input.name, typeParameters, heritageClauses, members)); + } + } + case 219 /* VariableStatement */: { + return cleanup(transformVariableStatement(input, isPrivate)); + } + case 243 /* EnumDeclaration */: { + return cleanup(ts.updateEnumDeclaration(input, /*decorators*/ undefined, ts.createNodeArray(ensureModifiers(input, isPrivate)), input.name, ts.createNodeArray(ts.mapDefined(input.members, function (m) { + if (shouldStripInternal(m)) + return; + // Rewrite enum values to their constants, if available + var constValue = resolver.getConstantValue(m); + return preserveJsDoc(ts.updateEnumMember(m, m.name, constValue !== undefined ? ts.createLiteral(constValue) : undefined), m); + })))); + } + } + // Anything left unhandled is an error, so this should be unreachable + return ts.Debug.assertNever(input, "Unhandled top-level node in declaration emit: " + ts.SyntaxKind[input.kind]); + function cleanup(node) { + if (isEnclosingDeclaration(input)) { + enclosingDeclaration = previousEnclosingDeclaration; + } + if (canProdiceDiagnostic) { + getSymbolAccessibilityDiagnostic = oldDiag; + } + if (input.kind === 244 /* ModuleDeclaration */) { + needsDeclare = previousNeedsDeclare; + } + if (node === input) { + return node; + } + return node && ts.setOriginalNode(preserveJsDoc(node, input), input); + } + } + function transformVariableStatement(input, privateDeclaration) { + if (!ts.forEach(input.declarationList.declarations, getBindingNameVisible)) + return; + var nodes = ts.visitNodes(input.declarationList.declarations, visitDeclarationSubtree); + if (!ts.length(nodes)) + return; + return ts.updateVariableStatement(input, ts.createNodeArray(ensureModifiers(input, privateDeclaration)), ts.updateVariableDeclarationList(input.declarationList, nodes)); + } + function recreateBindingPattern(d) { + return ts.flatten(ts.mapDefined(d.elements, function (e) { return recreateBindingElement(e); })); + } + function recreateBindingElement(e) { + if (e.kind === 210 /* OmittedExpression */) { + return; + } + if (e.name) { + if (!getBindingNameVisible(e)) + return; + if (ts.isBindingPattern(e.name)) { + return recreateBindingPattern(e.name); + } + else { + return ts.createVariableDeclaration(e.name, ensureType(e, /*type*/ undefined), /*initializer*/ undefined); + } + } + } + function checkName(node) { + var oldDiag; + if (!suppressNewDiagnosticContexts) { + oldDiag = getSymbolAccessibilityDiagnostic; + getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNodeName(node); + } + errorNameNode = node.name; + ts.Debug.assert(resolver.isLateBound(ts.getParseTreeNode(node))); // Should only be called with dynamic names + var decl = node; + var entityName = decl.name.expression; + checkEntityNameVisibility(entityName, enclosingDeclaration); + if (!suppressNewDiagnosticContexts) { + getSymbolAccessibilityDiagnostic = oldDiag; + } + errorNameNode = undefined; + } + function hasInternalAnnotation(range) { + var comment = currentSourceFile.text.substring(range.pos, range.end); + return ts.stringContains(comment, "@internal"); + } + function shouldStripInternal(node) { + if (stripInternal && node) { + var leadingCommentRanges = ts.getLeadingCommentRangesOfNode(ts.getParseTreeNode(node), currentSourceFile); + if (ts.forEach(leadingCommentRanges, hasInternalAnnotation)) { + return true; + } + } + return false; + } + function isScopeMarker(node) { + return ts.isExportAssignment(node) || ts.isExportDeclaration(node); + } + function hasScopeMarker(node) { + if (ts.isModuleBlock(node)) { + return ts.some(node.statements, isScopeMarker); + } + return false; + } + function ensureModifiers(node, privateDeclaration) { + var currentFlags = ts.getModifierFlags(node); + var newFlags = ensureModifierFlags(node, privateDeclaration); + if (currentFlags === newFlags) { + return node.modifiers; + } + return ts.createModifiersFromModifierFlags(newFlags); + } + function ensureModifierFlags(node, privateDeclaration) { + var mask = 3071 /* All */ ^ (4 /* Public */ | 256 /* Async */); // No async modifiers in declaration files + var additions = (needsDeclare && !isAlwaysType(node)) ? 2 /* Ambient */ : 0 /* None */; + var parentIsFile = node.parent.kind === 279 /* SourceFile */; + if (!parentIsFile || (isBundledEmit && parentIsFile && ts.isExternalModule(node.parent))) { + mask ^= ((privateDeclaration || (isBundledEmit && parentIsFile) || hasScopeMarker(node.parent) ? 0 : 1 /* Export */) | 2 /* Ambient */); + additions = 0 /* None */; + } + return maskModifierFlags(node, mask, additions); + } + function ensureAccessor(node) { + var accessors = resolver.getAllAccessorDeclarations(node); + if (node.kind !== accessors.firstAccessor.kind) { + return; + } + var accessorType = getTypeAnnotationFromAccessor(node); + if (!accessorType && accessors.secondAccessor) { + accessorType = getTypeAnnotationFromAccessor(accessors.secondAccessor); + // If we end up pulling the type from the second accessor, we also need to change the diagnostic context to get the expected error message + getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(accessors.secondAccessor); + } + var prop = ts.createProperty(/*decorators*/ undefined, maskModifiers(node, /*mask*/ undefined, (!accessors.setAccessor) ? 64 /* Readonly */ : 0 /* None */), node.name, node.questionToken, ensureType(node, accessorType), /*initializer*/ undefined); + var leadingsSyntheticCommentRanges = accessors.secondAccessor && ts.getLeadingCommentRangesOfNode(accessors.secondAccessor, currentSourceFile); + if (leadingsSyntheticCommentRanges) { + var _loop_9 = function (range) { + if (range.kind === 3 /* MultiLineCommentTrivia */) { + var text = currentSourceFile.text.slice(range.pos + 2, range.end - 2); + var lines = text.split(/\r\n?|\n/g); + if (lines.length > 1) { + var lastLines = lines.slice(1); + var indentation_1 = ts.guessIndentation(lastLines); + text = [lines[0]].concat(ts.map(lastLines, function (l) { return l.slice(indentation_1); })).join(newLine); + } + ts.addSyntheticLeadingComment(prop, range.kind, text, range.hasTrailingNewLine); + } + }; + for (var _i = 0, leadingsSyntheticCommentRanges_1 = leadingsSyntheticCommentRanges; _i < leadingsSyntheticCommentRanges_1.length; _i++) { + var range = leadingsSyntheticCommentRanges_1[_i]; + _loop_9(range); + } + } + return prop; + } + function transformHeritageClauses(nodes) { + return ts.createNodeArray(ts.filter(ts.map(nodes, function (clause) { return ts.updateHeritageClause(clause, ts.visitNodes(ts.createNodeArray(ts.filter(clause.types, function (t) { + return ts.isEntityNameExpression(t.expression) || (clause.token === 86 /* ExtendsKeyword */ && t.expression.kind === 96 /* NullKeyword */); + })), visitDeclarationSubtree)); }), function (clause) { return clause.types && !!clause.types.length; })); + } + } + ts.transformDeclarations = transformDeclarations; + function isAlwaysType(node) { + if (node.kind === 241 /* InterfaceDeclaration */) { + return true; + } + return false; + } + // Elide "public" modifier, as it is the default + function maskModifiers(node, modifierMask, modifierAdditions) { + return ts.createModifiersFromModifierFlags(maskModifierFlags(node, modifierMask, modifierAdditions)); + } + function maskModifierFlags(node, modifierMask, modifierAdditions) { + if (modifierMask === void 0) { modifierMask = 3071 /* All */ ^ 4 /* Public */; } + if (modifierAdditions === void 0) { modifierAdditions = 0 /* None */; } + var flags = (ts.getModifierFlags(node) & modifierMask) | modifierAdditions; + if (flags & 512 /* Default */ && !(flags & 1 /* Export */)) { + // A non-exported default is a nonsequitor - we usually try to remove all export modifiers + // from statements in ambient declarations; but a default export must retain its export modifier to be syntactically valid + flags ^= 1 /* Export */; + } + if (flags & 512 /* Default */ && flags & 2 /* Ambient */) { + flags ^= 2 /* Ambient */; // `declare` is never required alongside `default` (and would be an error if printed) + } + return flags; + } + function getTypeAnnotationFromAccessor(accessor) { + if (accessor) { + return accessor.kind === 158 /* GetAccessor */ + ? accessor.type // Getter - return type + : accessor.parameters.length > 0 + ? accessor.parameters[0].type // Setter parameter type + : undefined; + } + } + function canHaveLiteralInitializer(node) { + switch (node.kind) { + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + return !ts.hasModifier(node, 8 /* Private */); + case 151 /* Parameter */: + case 237 /* VariableDeclaration */: + return true; + } + return false; + } + function isPreservedDeclarationStatement(node) { + switch (node.kind) { + case 239 /* FunctionDeclaration */: + case 244 /* ModuleDeclaration */: + case 248 /* ImportEqualsDeclaration */: + case 241 /* InterfaceDeclaration */: + case 240 /* ClassDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 243 /* EnumDeclaration */: + case 219 /* VariableStatement */: + case 249 /* ImportDeclaration */: + case 255 /* ExportDeclaration */: + case 254 /* ExportAssignment */: + return true; + } + return false; + } + function isProcessedComponent(node) { + switch (node.kind) { + case 161 /* ConstructSignature */: + case 157 /* Constructor */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 155 /* MethodSignature */: + case 160 /* CallSignature */: + case 162 /* IndexSignature */: + case 237 /* VariableDeclaration */: + case 150 /* TypeParameter */: + case 211 /* ExpressionWithTypeArguments */: + case 164 /* TypeReference */: + case 175 /* ConditionalType */: + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + case 183 /* ImportType */: + return true; + } + return false; + } +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + function getModuleTransformer(moduleKind) { + switch (moduleKind) { + case ts.ModuleKind.ESNext: + case ts.ModuleKind.ES2015: + return ts.transformES2015Module; + case ts.ModuleKind.System: + return ts.transformSystemModule; + default: + return ts.transformModule; + } + } + var TransformationState; + (function (TransformationState) { + TransformationState[TransformationState["Uninitialized"] = 0] = "Uninitialized"; + TransformationState[TransformationState["Initialized"] = 1] = "Initialized"; + TransformationState[TransformationState["Completed"] = 2] = "Completed"; + TransformationState[TransformationState["Disposed"] = 3] = "Disposed"; + })(TransformationState || (TransformationState = {})); + var SyntaxKindFeatureFlags; + (function (SyntaxKindFeatureFlags) { + SyntaxKindFeatureFlags[SyntaxKindFeatureFlags["Substitution"] = 1] = "Substitution"; + SyntaxKindFeatureFlags[SyntaxKindFeatureFlags["EmitNotifications"] = 2] = "EmitNotifications"; + })(SyntaxKindFeatureFlags || (SyntaxKindFeatureFlags = {})); + function getTransformers(compilerOptions, customTransformers) { + var jsx = compilerOptions.jsx; + var languageVersion = ts.getEmitScriptTarget(compilerOptions); + var moduleKind = ts.getEmitModuleKind(compilerOptions); + var transformers = []; + ts.addRange(transformers, customTransformers && customTransformers.before); + transformers.push(ts.transformTypeScript); + if (jsx === 2 /* React */) { + transformers.push(ts.transformJsx); + } + if (languageVersion < 6 /* ESNext */) { + transformers.push(ts.transformESNext); + } + if (languageVersion < 4 /* ES2017 */) { + transformers.push(ts.transformES2017); + } + if (languageVersion < 3 /* ES2016 */) { + transformers.push(ts.transformES2016); + } + if (languageVersion < 2 /* ES2015 */) { + transformers.push(ts.transformES2015); + transformers.push(ts.transformGenerators); + } + transformers.push(getModuleTransformer(moduleKind)); + // The ES5 transformer is last so that it can substitute expressions like `exports.default` + // for ES3. + if (languageVersion < 1 /* ES5 */) { + transformers.push(ts.transformES5); + } + ts.addRange(transformers, customTransformers && customTransformers.after); + return transformers; + } + ts.getTransformers = getTransformers; + function noEmitSubstitution(_hint, node) { + return node; + } + ts.noEmitSubstitution = noEmitSubstitution; + function noEmitNotification(hint, node, callback) { + callback(hint, node); + } + ts.noEmitNotification = noEmitNotification; + /** + * Transforms an array of SourceFiles by passing them through each transformer. + * + * @param resolver The emit resolver provided by the checker. + * @param host The emit host object used to interact with the file system. + * @param options Compiler options to surface in the `TransformationContext`. + * @param nodes An array of nodes to transform. + * @param transforms An array of `TransformerFactory` callbacks. + * @param allowDtsFiles A value indicating whether to allow the transformation of .d.ts files. + */ + function transformNodes(resolver, host, options, nodes, transformers, allowDtsFiles) { + var enabledSyntaxKindFeatures = new Array(312 /* Count */); + var lexicalEnvironmentVariableDeclarations; + var lexicalEnvironmentFunctionDeclarations; + var lexicalEnvironmentVariableDeclarationsStack = []; + var lexicalEnvironmentFunctionDeclarationsStack = []; + var lexicalEnvironmentStackOffset = 0; + var lexicalEnvironmentSuspended = false; + var emitHelpers; + var onSubstituteNode = noEmitSubstitution; + var onEmitNode = noEmitNotification; + var state = 0 /* Uninitialized */; + var diagnostics = []; + // The transformation context is provided to each transformer as part of transformer + // initialization. + var context = { + getCompilerOptions: function () { return options; }, + getEmitResolver: function () { return resolver; }, + getEmitHost: function () { return host; }, + startLexicalEnvironment: startLexicalEnvironment, + suspendLexicalEnvironment: suspendLexicalEnvironment, + resumeLexicalEnvironment: resumeLexicalEnvironment, + endLexicalEnvironment: endLexicalEnvironment, + hoistVariableDeclaration: hoistVariableDeclaration, + hoistFunctionDeclaration: hoistFunctionDeclaration, + requestEmitHelper: requestEmitHelper, + readEmitHelpers: readEmitHelpers, + enableSubstitution: enableSubstitution, + enableEmitNotification: enableEmitNotification, + isSubstitutionEnabled: isSubstitutionEnabled, + isEmitNotificationEnabled: isEmitNotificationEnabled, + get onSubstituteNode() { return onSubstituteNode; }, + set onSubstituteNode(value) { + ts.Debug.assert(state < 1 /* Initialized */, "Cannot modify transformation hooks after initialization has completed."); + ts.Debug.assert(value !== undefined, "Value must not be 'undefined'"); + onSubstituteNode = value; + }, + get onEmitNode() { return onEmitNode; }, + set onEmitNode(value) { + ts.Debug.assert(state < 1 /* Initialized */, "Cannot modify transformation hooks after initialization has completed."); + ts.Debug.assert(value !== undefined, "Value must not be 'undefined'"); + onEmitNode = value; + }, + addDiagnostic: function (diag) { + diagnostics.push(diag); + } + }; + // Ensure the parse tree is clean before applying transformations + for (var _i = 0, nodes_4 = nodes; _i < nodes_4.length; _i++) { + var node = nodes_4[_i]; + ts.disposeEmitNodes(ts.getSourceFileOfNode(ts.getParseTreeNode(node))); + } + ts.performance.mark("beforeTransform"); + // Chain together and initialize each transformer. + var transformation = ts.chain.apply(void 0, transformers)(context); + // prevent modification of transformation hooks. + state = 1 /* Initialized */; + // Transform each node. + var transformed = ts.map(nodes, allowDtsFiles ? transformation : transformRoot); + // prevent modification of the lexical environment. + state = 2 /* Completed */; + ts.performance.mark("afterTransform"); + ts.performance.measure("transformTime", "beforeTransform", "afterTransform"); + return { + transformed: transformed, + substituteNode: substituteNode, + emitNodeWithNotification: emitNodeWithNotification, + dispose: dispose, + diagnostics: diagnostics + }; + function transformRoot(node) { + return node && (!ts.isSourceFile(node) || !node.isDeclarationFile) ? transformation(node) : node; + } + /** + * Enables expression substitutions in the pretty printer for the provided SyntaxKind. + */ + function enableSubstitution(kind) { + ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the transformation context after transformation has completed."); + enabledSyntaxKindFeatures[kind] |= 1 /* Substitution */; + } + /** + * Determines whether expression substitutions are enabled for the provided node. + */ + function isSubstitutionEnabled(node) { + return (enabledSyntaxKindFeatures[node.kind] & 1 /* Substitution */) !== 0 + && (ts.getEmitFlags(node) & 4 /* NoSubstitution */) === 0; + } + /** + * Emits a node with possible substitution. + * + * @param hint A hint as to the intended usage of the node. + * @param node The node to emit. + * @param emitCallback The callback used to emit the node or its substitute. + */ + function substituteNode(hint, node) { + ts.Debug.assert(state < 3 /* Disposed */, "Cannot substitute a node after the result is disposed."); + return node && isSubstitutionEnabled(node) && onSubstituteNode(hint, node) || node; + } + /** + * Enables before/after emit notifications in the pretty printer for the provided SyntaxKind. + */ + function enableEmitNotification(kind) { + ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the transformation context after transformation has completed."); + enabledSyntaxKindFeatures[kind] |= 2 /* EmitNotifications */; + } + /** + * Determines whether before/after emit notifications should be raised in the pretty + * printer when it emits a node. + */ + function isEmitNotificationEnabled(node) { + return (enabledSyntaxKindFeatures[node.kind] & 2 /* EmitNotifications */) !== 0 + || (ts.getEmitFlags(node) & 2 /* AdviseOnEmitNode */) !== 0; + } + /** + * Emits a node with possible emit notification. + * + * @param hint A hint as to the intended usage of the node. + * @param node The node to emit. + * @param emitCallback The callback used to emit the node. + */ + function emitNodeWithNotification(hint, node, emitCallback) { + ts.Debug.assert(state < 3 /* Disposed */, "Cannot invoke TransformationResult callbacks after the result is disposed."); + if (node) { + if (isEmitNotificationEnabled(node)) { + onEmitNode(hint, node, emitCallback); + } + else { + emitCallback(hint, node); + } + } + } + /** + * Records a hoisted variable declaration for the provided name within a lexical environment. + */ + function hoistVariableDeclaration(name) { + ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization."); + ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed."); + var decl = ts.setEmitFlags(ts.createVariableDeclaration(name), 64 /* NoNestedSourceMaps */); + if (!lexicalEnvironmentVariableDeclarations) { + lexicalEnvironmentVariableDeclarations = [decl]; + } + else { + lexicalEnvironmentVariableDeclarations.push(decl); + } + } + /** + * Records a hoisted function declaration within a lexical environment. + */ + function hoistFunctionDeclaration(func) { + ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization."); + ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed."); + if (!lexicalEnvironmentFunctionDeclarations) { + lexicalEnvironmentFunctionDeclarations = [func]; + } + else { + lexicalEnvironmentFunctionDeclarations.push(func); + } + } + /** + * Starts a new lexical environment. Any existing hoisted variable or function declarations + * are pushed onto a stack, and the related storage variables are reset. + */ + function startLexicalEnvironment() { + ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization."); + ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed."); + ts.Debug.assert(!lexicalEnvironmentSuspended, "Lexical environment is suspended."); + // Save the current lexical environment. Rather than resizing the array we adjust the + // stack size variable. This allows us to reuse existing array slots we've + // already allocated between transformations to avoid allocation and GC overhead during + // transformation. + lexicalEnvironmentVariableDeclarationsStack[lexicalEnvironmentStackOffset] = lexicalEnvironmentVariableDeclarations; + lexicalEnvironmentFunctionDeclarationsStack[lexicalEnvironmentStackOffset] = lexicalEnvironmentFunctionDeclarations; + lexicalEnvironmentStackOffset++; + lexicalEnvironmentVariableDeclarations = undefined; + lexicalEnvironmentFunctionDeclarations = undefined; + } + /** Suspends the current lexical environment, usually after visiting a parameter list. */ + function suspendLexicalEnvironment() { + ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization."); + ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed."); + ts.Debug.assert(!lexicalEnvironmentSuspended, "Lexical environment is already suspended."); + lexicalEnvironmentSuspended = true; + } + /** Resumes a suspended lexical environment, usually before visiting a function body. */ + function resumeLexicalEnvironment() { + ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization."); + ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed."); + ts.Debug.assert(lexicalEnvironmentSuspended, "Lexical environment is not suspended."); + lexicalEnvironmentSuspended = false; + } + /** + * Ends a lexical environment. The previous set of hoisted declarations are restored and + * any hoisted declarations added in this environment are returned. + */ + function endLexicalEnvironment() { + ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization."); + ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed."); + ts.Debug.assert(!lexicalEnvironmentSuspended, "Lexical environment is suspended."); + var statements; + if (lexicalEnvironmentVariableDeclarations || lexicalEnvironmentFunctionDeclarations) { + if (lexicalEnvironmentFunctionDeclarations) { + statements = lexicalEnvironmentFunctionDeclarations.slice(); + } + if (lexicalEnvironmentVariableDeclarations) { + var statement = ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList(lexicalEnvironmentVariableDeclarations)); + if (!statements) { + statements = [statement]; + } + else { + statements.push(statement); + } + } + } + // Restore the previous lexical environment. + lexicalEnvironmentStackOffset--; + lexicalEnvironmentVariableDeclarations = lexicalEnvironmentVariableDeclarationsStack[lexicalEnvironmentStackOffset]; + lexicalEnvironmentFunctionDeclarations = lexicalEnvironmentFunctionDeclarationsStack[lexicalEnvironmentStackOffset]; + if (lexicalEnvironmentStackOffset === 0) { + lexicalEnvironmentVariableDeclarationsStack = []; + lexicalEnvironmentFunctionDeclarationsStack = []; + } + return statements; + } + function requestEmitHelper(helper) { + ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the transformation context during initialization."); + ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the transformation context after transformation has completed."); + ts.Debug.assert(!helper.scoped, "Cannot request a scoped emit helper."); + emitHelpers = ts.append(emitHelpers, helper); + } + function readEmitHelpers() { + ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the transformation context during initialization."); + ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the transformation context after transformation has completed."); + var helpers = emitHelpers; + emitHelpers = undefined; + return helpers; + } + function dispose() { + if (state < 3 /* Disposed */) { + // Clean up emit nodes on parse tree + for (var _i = 0, nodes_5 = nodes; _i < nodes_5.length; _i++) { + var node = nodes_5[_i]; + ts.disposeEmitNodes(ts.getSourceFileOfNode(ts.getParseTreeNode(node))); + } + // Release references to external entries for GC purposes. + lexicalEnvironmentVariableDeclarations = undefined; + lexicalEnvironmentVariableDeclarationsStack = undefined; + lexicalEnvironmentFunctionDeclarations = undefined; + lexicalEnvironmentFunctionDeclarationsStack = undefined; + onSubstituteNode = undefined; + onEmitNode = undefined; + emitHelpers = undefined; + // Prevent further use of the transformation result. + state = 3 /* Disposed */; + } + } + } + ts.transformNodes = transformNodes; +})(ts || (ts = {})); +var ts; +(function (ts) { + var infoExtension = ".tsbundleinfo"; + var brackets = createBracketsMap(); + var syntheticParent = { pos: -1, end: -1 }; + /*@internal*/ + /** + * Iterates over the source files that are expected to have an emit output. + * + * @param host An EmitHost. + * @param action The action to execute. + * @param sourceFilesOrTargetSourceFile + * If an array, the full list of source files to emit. + * Else, calls `getSourceFilesToEmit` with the (optional) target source file to determine the list of source files to emit. + */ + function forEachEmittedFile(host, action, sourceFilesOrTargetSourceFile, emitOnlyDtsFiles) { + if (emitOnlyDtsFiles === void 0) { emitOnlyDtsFiles = false; } + var sourceFiles = ts.isArray(sourceFilesOrTargetSourceFile) ? sourceFilesOrTargetSourceFile : ts.getSourceFilesToEmit(host, sourceFilesOrTargetSourceFile); + var options = host.getCompilerOptions(); + if (options.outFile || options.out) { + if (sourceFiles.length) { + var bundle = ts.createBundle(sourceFiles, host.getPrependNodes()); + var result = action(getOutputPathsFor(bundle, host, emitOnlyDtsFiles), bundle); + if (result) { + return result; + } + } + } + else { + for (var _a = 0, sourceFiles_1 = sourceFiles; _a < sourceFiles_1.length; _a++) { + var sourceFile = sourceFiles_1[_a]; + var result = action(getOutputPathsFor(sourceFile, host, emitOnlyDtsFiles), sourceFile); + if (result) { + return result; + } + } + } + } + ts.forEachEmittedFile = forEachEmittedFile; + /*@internal*/ + function getOutputPathsFor(sourceFile, host, forceDtsPaths) { + var options = host.getCompilerOptions(); + if (sourceFile.kind === 280 /* Bundle */) { + var outPath = options.outFile || options.out; + var jsFilePath = options.emitDeclarationOnly ? undefined : outPath; + var sourceMapFilePath = jsFilePath && getSourceMapFilePath(jsFilePath, options); + var declarationFilePath = (forceDtsPaths || ts.getEmitDeclarations(options)) ? ts.removeFileExtension(outPath) + ".d.ts" /* Dts */ : undefined; + var declarationMapPath = declarationFilePath && ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; + var bundleInfoPath = options.references && jsFilePath ? (ts.removeFileExtension(jsFilePath) + infoExtension) : undefined; + return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, bundleInfoPath: bundleInfoPath }; + } + else { + var ownOutputFilePath = ts.getOwnEmitOutputFilePath(sourceFile.fileName, host, getOutputExtension(sourceFile, options)); + // If json file emits to the same location skip writing it, if emitDeclarationOnly skip writing it + var isJsonEmittedToSameLocation = ts.isJsonSourceFile(sourceFile) && + ts.comparePaths(sourceFile.fileName, ownOutputFilePath, host.getCurrentDirectory(), !host.useCaseSensitiveFileNames()) === 0 /* EqualTo */; + var jsFilePath = options.emitDeclarationOnly || isJsonEmittedToSameLocation ? undefined : ownOutputFilePath; + var sourceMapFilePath = !jsFilePath || ts.isJsonSourceFile(sourceFile) ? undefined : getSourceMapFilePath(jsFilePath, options); + // For legacy reasons (ie, we have baselines capturing the behavior), js files don't report a .d.ts output path - this would only matter if `declaration` and `allowJs` were both on, which is currently an error + var isJs = ts.isSourceFileJS(sourceFile); + var declarationFilePath = ((forceDtsPaths || ts.getEmitDeclarations(options)) && !isJs) ? ts.getDeclarationEmitOutputFilePath(sourceFile.fileName, host) : undefined; + var declarationMapPath = declarationFilePath && ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; + return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, bundleInfoPath: undefined }; + } + } + ts.getOutputPathsFor = getOutputPathsFor; + function getSourceMapFilePath(jsFilePath, options) { + return (options.sourceMap && !options.inlineSourceMap) ? jsFilePath + ".map" : undefined; + } + function createDefaultBundleInfo() { + return { + originalOffset: -1, + totalLength: -1 + }; + } + // JavaScript files are always LanguageVariant.JSX, as JSX syntax is allowed in .js files also. + // So for JavaScript files, '.jsx' is only emitted if the input was '.jsx', and JsxEmit.Preserve. + // For TypeScript, the only time to emit with a '.jsx' extension, is on JSX input, and JsxEmit.Preserve + /* @internal */ + function getOutputExtension(sourceFile, options) { + if (ts.isJsonSourceFile(sourceFile)) { + return ".json" /* Json */; + } + if (options.jsx === 1 /* Preserve */) { + if (ts.isSourceFileJS(sourceFile)) { + if (ts.fileExtensionIs(sourceFile.fileName, ".jsx" /* Jsx */)) { + return ".jsx" /* Jsx */; + } + } + else if (sourceFile.languageVariant === 1 /* JSX */) { + // TypeScript source file preserving JSX syntax + return ".jsx" /* Jsx */; + } + } + return ".js" /* Js */; + } + ts.getOutputExtension = getOutputExtension; + /*@internal*/ + // targetSourceFile is when users only want one file in entire project to be emitted. This is used in compileOnSave feature + function emitFiles(resolver, host, targetSourceFile, emitOnlyDtsFiles, transformers, declarationTransformers) { + var compilerOptions = host.getCompilerOptions(); + var sourceMapDataList = (compilerOptions.sourceMap || compilerOptions.inlineSourceMap || ts.getAreDeclarationMapsEnabled(compilerOptions)) ? [] : undefined; + var emittedFilesList = compilerOptions.listEmittedFiles ? [] : undefined; + var emitterDiagnostics = ts.createDiagnosticCollection(); + var newLine = ts.getNewLineCharacter(compilerOptions, function () { return host.getNewLine(); }); + var writer = ts.createTextWriter(newLine); + var _a = ts.performance.createTimer("printTime", "beforePrint", "afterPrint"), enter = _a.enter, exit = _a.exit; + var bundleInfo = createDefaultBundleInfo(); + var emitSkipped = false; + var exportedModulesFromDeclarationEmit; + // Emit each output file + enter(); + forEachEmittedFile(host, emitSourceFileOrBundle, ts.getSourceFilesToEmit(host, targetSourceFile), emitOnlyDtsFiles); + exit(); + return { + emitSkipped: emitSkipped, + diagnostics: emitterDiagnostics.getDiagnostics(), + emittedFiles: emittedFilesList, + sourceMaps: sourceMapDataList, + exportedModulesFromDeclarationEmit: exportedModulesFromDeclarationEmit + }; + function emitSourceFileOrBundle(_a, sourceFileOrBundle) { + var jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, bundleInfoPath = _a.bundleInfoPath; + emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, bundleInfoPath); + emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath); + if (!emitSkipped && emittedFilesList) { + if (!emitOnlyDtsFiles) { + if (jsFilePath) { + emittedFilesList.push(jsFilePath); + } + if (sourceMapFilePath) { + emittedFilesList.push(sourceMapFilePath); + } + if (bundleInfoPath) { + emittedFilesList.push(bundleInfoPath); + } + } + if (declarationFilePath) { + emittedFilesList.push(declarationFilePath); + } + if (declarationMapPath) { + emittedFilesList.push(declarationMapPath); + } + } + } + function emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, bundleInfoPath) { + if (emitOnlyDtsFiles || !jsFilePath) { + return; + } + // Make sure not to write js file and source map file if any of them cannot be written + if ((jsFilePath && host.isEmitBlocked(jsFilePath)) || compilerOptions.noEmit) { + emitSkipped = true; + return; + } + // Transform the source files + var transform = ts.transformNodes(resolver, host, compilerOptions, [sourceFileOrBundle], transformers, /*allowDtsFiles*/ false); + var printerOptions = { + removeComments: compilerOptions.removeComments, + newLine: compilerOptions.newLine, + noEmitHelpers: compilerOptions.noEmitHelpers, + module: compilerOptions.module, + target: compilerOptions.target, + sourceMap: compilerOptions.sourceMap, + inlineSourceMap: compilerOptions.inlineSourceMap, + inlineSources: compilerOptions.inlineSources, + extendedDiagnostics: compilerOptions.extendedDiagnostics, + }; + // Create a printer to print the nodes + var printer = createPrinter(printerOptions, { + // resolver hooks + hasGlobalName: resolver.hasGlobalName, + // transform hooks + onEmitNode: transform.emitNodeWithNotification, + substituteNode: transform.substituteNode, + }); + ts.Debug.assert(transform.transformed.length === 1, "Should only see one output from the transform"); + printSourceFileOrBundle(jsFilePath, sourceMapFilePath, transform.transformed[0], bundleInfoPath, printer, compilerOptions); + // Clean up emit nodes on parse tree + transform.dispose(); + } + function emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath) { + if (!(declarationFilePath && !ts.isInJSFile(sourceFileOrBundle))) { + return; + } + var sourceFiles = ts.isSourceFile(sourceFileOrBundle) ? [sourceFileOrBundle] : sourceFileOrBundle.sourceFiles; + // Setup and perform the transformation to retrieve declarations from the input files + var nonJsFiles = ts.filter(sourceFiles, ts.isSourceFileNotJS); + var inputListOrBundle = (compilerOptions.outFile || compilerOptions.out) ? [ts.createBundle(nonJsFiles, !ts.isSourceFile(sourceFileOrBundle) ? sourceFileOrBundle.prepends : undefined)] : nonJsFiles; + if (emitOnlyDtsFiles && !ts.getEmitDeclarations(compilerOptions)) { + // Checker wont collect the linked aliases since thats only done when declaration is enabled. + // Do that here when emitting only dts files + nonJsFiles.forEach(collectLinkedAliases); + } + var declarationTransform = ts.transformNodes(resolver, host, compilerOptions, inputListOrBundle, ts.concatenate([ts.transformDeclarations], declarationTransformers), /*allowDtsFiles*/ false); + if (ts.length(declarationTransform.diagnostics)) { + for (var _a = 0, _b = declarationTransform.diagnostics; _a < _b.length; _a++) { + var diagnostic = _b[_a]; + emitterDiagnostics.add(diagnostic); + } + } + var printerOptions = { + removeComments: compilerOptions.removeComments, + newLine: compilerOptions.newLine, + noEmitHelpers: true, + module: compilerOptions.module, + target: compilerOptions.target, + sourceMap: compilerOptions.sourceMap, + inlineSourceMap: compilerOptions.inlineSourceMap, + extendedDiagnostics: compilerOptions.extendedDiagnostics, + onlyPrintJsDocStyle: true, + }; + var declarationPrinter = createPrinter(printerOptions, { + // resolver hooks + hasGlobalName: resolver.hasGlobalName, + // transform hooks + onEmitNode: declarationTransform.emitNodeWithNotification, + substituteNode: declarationTransform.substituteNode, + }); + var declBlocked = (!!declarationTransform.diagnostics && !!declarationTransform.diagnostics.length) || !!host.isEmitBlocked(declarationFilePath) || !!compilerOptions.noEmit; + emitSkipped = emitSkipped || declBlocked; + if (!declBlocked || emitOnlyDtsFiles) { + ts.Debug.assert(declarationTransform.transformed.length === 1, "Should only see one output from the decl transform"); + printSourceFileOrBundle(declarationFilePath, declarationMapPath, declarationTransform.transformed[0], /* bundleInfopath*/ undefined, declarationPrinter, { + sourceMap: compilerOptions.declarationMap, + sourceRoot: compilerOptions.sourceRoot, + mapRoot: compilerOptions.mapRoot, + extendedDiagnostics: compilerOptions.extendedDiagnostics, + }); + if (emitOnlyDtsFiles && declarationTransform.transformed[0].kind === 279 /* SourceFile */) { + var sourceFile = declarationTransform.transformed[0]; + exportedModulesFromDeclarationEmit = sourceFile.exportedModulesFromDeclarationEmit; + } + } + declarationTransform.dispose(); + } + function collectLinkedAliases(node) { + if (ts.isExportAssignment(node)) { + if (node.expression.kind === 72 /* Identifier */) { + resolver.collectLinkedAliases(node.expression, /*setVisibility*/ true); + } + return; + } + else if (ts.isExportSpecifier(node)) { + resolver.collectLinkedAliases(node.propertyName || node.name, /*setVisibility*/ true); + return; + } + ts.forEachChild(node, collectLinkedAliases); + } + function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle, bundleInfoPath, printer, mapOptions) { + var bundle = sourceFileOrBundle.kind === 280 /* Bundle */ ? sourceFileOrBundle : undefined; + var sourceFile = sourceFileOrBundle.kind === 279 /* SourceFile */ ? sourceFileOrBundle : undefined; + var sourceFiles = bundle ? bundle.sourceFiles : [sourceFile]; + var sourceMapGenerator; + if (shouldEmitSourceMaps(mapOptions, sourceFileOrBundle)) { + sourceMapGenerator = ts.createSourceMapGenerator(host, ts.getBaseFileName(ts.normalizeSlashes(jsFilePath)), getSourceRoot(mapOptions), getSourceMapDirectory(mapOptions, jsFilePath, sourceFile), mapOptions); + } + if (bundle) { + printer.writeBundle(bundle, bundleInfo, writer, sourceMapGenerator); + } + else { + printer.writeFile(sourceFile, writer, sourceMapGenerator); + } + if (sourceMapGenerator) { + if (sourceMapDataList) { + sourceMapDataList.push({ + inputSourceFileNames: sourceMapGenerator.getSources(), + sourceMap: sourceMapGenerator.toJSON() + }); + } + var sourceMappingURL = getSourceMappingURL(mapOptions, sourceMapGenerator, jsFilePath, sourceMapFilePath, sourceFile); + if (sourceMappingURL) { + if (!writer.isAtStartOfLine()) + writer.rawWrite(newLine); + writer.writeComment("//# " + "sourceMappingURL" + "=" + sourceMappingURL); // Tools can sometimes see this line as a source mapping url comment + } + // Write the source map + if (sourceMapFilePath) { + var sourceMap = sourceMapGenerator.toString(); + ts.writeFile(host, emitterDiagnostics, sourceMapFilePath, sourceMap, /*writeByteOrderMark*/ false, sourceFiles); + } + } + else { + writer.writeLine(); + } + // Write the output file + ts.writeFile(host, emitterDiagnostics, jsFilePath, writer.getText(), !!compilerOptions.emitBOM, sourceFiles); + // Write bundled offset information if applicable + if (bundleInfoPath) { + bundleInfo.totalLength = writer.getTextPos(); + ts.writeFile(host, emitterDiagnostics, bundleInfoPath, JSON.stringify(bundleInfo, undefined, 2), /*writeByteOrderMark*/ false); + } + // Reset state + writer.clear(); + bundleInfo = createDefaultBundleInfo(); + } + function shouldEmitSourceMaps(mapOptions, sourceFileOrBundle) { + return (mapOptions.sourceMap || mapOptions.inlineSourceMap) + && (sourceFileOrBundle.kind !== 279 /* SourceFile */ || !ts.fileExtensionIs(sourceFileOrBundle.fileName, ".json" /* Json */)); + } + function getSourceRoot(mapOptions) { + // Normalize source root and make sure it has trailing "/" so that it can be used to combine paths with the + // relative paths of the sources list in the sourcemap + var sourceRoot = ts.normalizeSlashes(mapOptions.sourceRoot || ""); + return sourceRoot ? ts.ensureTrailingDirectorySeparator(sourceRoot) : sourceRoot; + } + function getSourceMapDirectory(mapOptions, filePath, sourceFile) { + if (mapOptions.sourceRoot) + return host.getCommonSourceDirectory(); + if (mapOptions.mapRoot) { + var sourceMapDir = ts.normalizeSlashes(mapOptions.mapRoot); + if (sourceFile) { + // For modules or multiple emit files the mapRoot will have directory structure like the sources + // So if src\a.ts and src\lib\b.ts are compiled together user would be moving the maps into mapRoot\a.js.map and mapRoot\lib\b.js.map + sourceMapDir = ts.getDirectoryPath(ts.getSourceFilePathInNewDir(sourceFile.fileName, host, sourceMapDir)); + } + if (ts.getRootLength(sourceMapDir) === 0) { + // The relative paths are relative to the common directory + sourceMapDir = ts.combinePaths(host.getCommonSourceDirectory(), sourceMapDir); + } + return sourceMapDir; + } + return ts.getDirectoryPath(ts.normalizePath(filePath)); + } + function getSourceMappingURL(mapOptions, sourceMapGenerator, filePath, sourceMapFilePath, sourceFile) { + if (mapOptions.inlineSourceMap) { + // Encode the sourceMap into the sourceMap url + var sourceMapText = sourceMapGenerator.toString(); + var base64SourceMapText = ts.base64encode(ts.sys, sourceMapText); + return "data:application/json;base64," + base64SourceMapText; + } + var sourceMapFile = ts.getBaseFileName(ts.normalizeSlashes(ts.Debug.assertDefined(sourceMapFilePath))); + if (mapOptions.mapRoot) { + var sourceMapDir = ts.normalizeSlashes(mapOptions.mapRoot); + if (sourceFile) { + // For modules or multiple emit files the mapRoot will have directory structure like the sources + // So if src\a.ts and src\lib\b.ts are compiled together user would be moving the maps into mapRoot\a.js.map and mapRoot\lib\b.js.map + sourceMapDir = ts.getDirectoryPath(ts.getSourceFilePathInNewDir(sourceFile.fileName, host, sourceMapDir)); + } + if (ts.getRootLength(sourceMapDir) === 0) { + // The relative paths are relative to the common directory + sourceMapDir = ts.combinePaths(host.getCommonSourceDirectory(), sourceMapDir); + return ts.getRelativePathToDirectoryOrUrl(ts.getDirectoryPath(ts.normalizePath(filePath)), // get the relative sourceMapDir path based on jsFilePath + ts.combinePaths(sourceMapDir, sourceMapFile), // this is where user expects to see sourceMap + host.getCurrentDirectory(), host.getCanonicalFileName, + /*isAbsolutePathAnUrl*/ true); + } + else { + return ts.combinePaths(sourceMapDir, sourceMapFile); + } + } + return sourceMapFile; + } + } + ts.emitFiles = emitFiles; + var PipelinePhase; + (function (PipelinePhase) { + PipelinePhase[PipelinePhase["Notification"] = 0] = "Notification"; + PipelinePhase[PipelinePhase["Substitution"] = 1] = "Substitution"; + PipelinePhase[PipelinePhase["Comments"] = 2] = "Comments"; + PipelinePhase[PipelinePhase["SourceMaps"] = 3] = "SourceMaps"; + PipelinePhase[PipelinePhase["Emit"] = 4] = "Emit"; + })(PipelinePhase || (PipelinePhase = {})); + function createPrinter(printerOptions, handlers) { + if (printerOptions === void 0) { printerOptions = {}; } + if (handlers === void 0) { handlers = {}; } + var hasGlobalName = handlers.hasGlobalName, _a = handlers.onEmitNode, onEmitNode = _a === void 0 ? ts.noEmitNotification : _a, _b = handlers.substituteNode, substituteNode = _b === void 0 ? ts.noEmitSubstitution : _b, onBeforeEmitNodeArray = handlers.onBeforeEmitNodeArray, onAfterEmitNodeArray = handlers.onAfterEmitNodeArray, onBeforeEmitToken = handlers.onBeforeEmitToken, onAfterEmitToken = handlers.onAfterEmitToken; + var extendedDiagnostics = !!printerOptions.extendedDiagnostics; + var newLine = ts.getNewLineCharacter(printerOptions); + var moduleKind = ts.getEmitModuleKind(printerOptions); + var bundledHelpers = ts.createMap(); + var currentSourceFile; + var nodeIdToGeneratedName; // Map of generated names for specific nodes. + var autoGeneratedIdToGeneratedName; // Map of generated names for temp and loop variables. + var generatedNames; // Set of names generated by the NameGenerator. + var tempFlagsStack; // Stack of enclosing name generation scopes. + var tempFlags; // TempFlags for the current name generation scope. + var reservedNamesStack; // Stack of TempFlags reserved in enclosing name generation scopes. + var reservedNames; // TempFlags to reserve in nested name generation scopes. + var writer; + var ownWriter; // Reusable `EmitTextWriter` for basic printing. + var write = writeBase; + var isOwnFileEmit; + // Source Maps + var sourceMapsDisabled = true; + var sourceMapGenerator; + var sourceMapSource; + var sourceMapSourceIndex = -1; + // Comments + var containerPos = -1; + var containerEnd = -1; + var declarationListContainerEnd = -1; + var currentLineMap; + var detachedCommentsInfo; + var hasWrittenComment = false; + var commentsDisabled = !!printerOptions.removeComments; + var _c = ts.performance.createTimerIf(extendedDiagnostics, "commentTime", "beforeComment", "afterComment"), enterComment = _c.enter, exitComment = _c.exit; + reset(); + return { + // public API + printNode: printNode, + printList: printList, + printFile: printFile, + printBundle: printBundle, + // internal API + writeNode: writeNode, + writeList: writeList, + writeFile: writeFile, + writeBundle: writeBundle + }; + function printNode(hint, node, sourceFile) { + switch (hint) { + case 0 /* SourceFile */: + ts.Debug.assert(ts.isSourceFile(node), "Expected a SourceFile node."); + break; + case 2 /* IdentifierName */: + ts.Debug.assert(ts.isIdentifier(node), "Expected an Identifier node."); + break; + case 1 /* Expression */: + ts.Debug.assert(ts.isExpression(node), "Expected an Expression node."); + break; + } + switch (node.kind) { + case 279 /* SourceFile */: return printFile(node); + case 280 /* Bundle */: return printBundle(node); + case 281 /* UnparsedSource */: return printUnparsedSource(node); + } + writeNode(hint, node, sourceFile, beginPrint()); + return endPrint(); + } + function printList(format, nodes, sourceFile) { + writeList(format, nodes, sourceFile, beginPrint()); + return endPrint(); + } + function printBundle(bundle) { + writeBundle(bundle, /*bundleInfo*/ undefined, beginPrint(), /*sourceMapEmitter*/ undefined); + return endPrint(); + } + function printFile(sourceFile) { + writeFile(sourceFile, beginPrint(), /*sourceMapEmitter*/ undefined); + return endPrint(); + } + function printUnparsedSource(unparsed) { + writeUnparsedSource(unparsed, beginPrint()); + return endPrint(); + } + function writeNode(hint, node, sourceFile, output) { + var previousWriter = writer; + setWriter(output, /*_sourceMapGenerator*/ undefined); + print(hint, node, sourceFile); + reset(); + writer = previousWriter; + } + function writeList(format, nodes, sourceFile, output) { + var previousWriter = writer; + setWriter(output, /*_sourceMapGenerator*/ undefined); + if (sourceFile) { + setSourceFile(sourceFile); + } + emitList(syntheticParent, nodes, format); + reset(); + writer = previousWriter; + } + function writeBundle(bundle, bundleInfo, output, sourceMapGenerator) { + isOwnFileEmit = false; + var previousWriter = writer; + setWriter(output, sourceMapGenerator); + emitShebangIfNeeded(bundle); + emitPrologueDirectivesIfNeeded(bundle); + emitHelpers(bundle); + emitSyntheticTripleSlashReferencesIfNeeded(bundle); + for (var _a = 0, _b = bundle.prepends; _a < _b.length; _a++) { + var prepend = _b[_a]; + writeLine(); + print(4 /* Unspecified */, prepend, /*sourceFile*/ undefined); + } + if (bundleInfo) { + bundleInfo.originalOffset = writer.getTextPos(); + } + for (var _c = 0, _d = bundle.sourceFiles; _c < _d.length; _c++) { + var sourceFile = _d[_c]; + print(0 /* SourceFile */, sourceFile, sourceFile); + } + reset(); + writer = previousWriter; + } + function writeUnparsedSource(unparsed, output) { + var previousWriter = writer; + setWriter(output, /*_sourceMapGenerator*/ undefined); + print(4 /* Unspecified */, unparsed, /*sourceFile*/ undefined); + reset(); + writer = previousWriter; + } + function writeFile(sourceFile, output, sourceMapGenerator) { + isOwnFileEmit = true; + var previousWriter = writer; + setWriter(output, sourceMapGenerator); + emitShebangIfNeeded(sourceFile); + emitPrologueDirectivesIfNeeded(sourceFile); + print(0 /* SourceFile */, sourceFile, sourceFile); + reset(); + writer = previousWriter; + } + function beginPrint() { + return ownWriter || (ownWriter = ts.createTextWriter(newLine)); + } + function endPrint() { + var text = ownWriter.getText(); + ownWriter.clear(); + return text; + } + function print(hint, node, sourceFile) { + if (sourceFile) { + setSourceFile(sourceFile); + } + var pipelinePhase = getPipelinePhase(0 /* Notification */, node); + pipelinePhase(hint, node); + } + function setSourceFile(sourceFile) { + currentSourceFile = sourceFile; + currentLineMap = undefined; + detachedCommentsInfo = undefined; + if (sourceFile) { + setSourceMapSource(sourceFile); + } + } + function setWriter(_writer, _sourceMapGenerator) { + if (_writer && printerOptions.omitTrailingSemicolon) { + _writer = ts.getTrailingSemicolonOmittingWriter(_writer); + } + writer = _writer; // TODO: GH#18217 + sourceMapGenerator = _sourceMapGenerator; + sourceMapsDisabled = !writer || !sourceMapGenerator; + } + function reset() { + nodeIdToGeneratedName = []; + autoGeneratedIdToGeneratedName = []; + generatedNames = ts.createMap(); + tempFlagsStack = []; + tempFlags = 0 /* Auto */; + reservedNamesStack = []; + currentSourceFile = undefined; + currentLineMap = undefined; + detachedCommentsInfo = undefined; + setWriter(/*output*/ undefined, /*_sourceMapGenerator*/ undefined); + } + function getCurrentLineMap() { + return currentLineMap || (currentLineMap = ts.getLineStarts(currentSourceFile)); + } + function emit(node) { + if (node === undefined) + return; + var pipelinePhase = getPipelinePhase(0 /* Notification */, node); + pipelinePhase(4 /* Unspecified */, node); + } + function emitIdentifierName(node) { + if (node === undefined) + return; + var pipelinePhase = getPipelinePhase(0 /* Notification */, node); + pipelinePhase(2 /* IdentifierName */, node); + } + function emitExpression(node) { + if (node === undefined) + return; + var pipelinePhase = getPipelinePhase(0 /* Notification */, node); + pipelinePhase(1 /* Expression */, node); + } + function getPipelinePhase(phase, node) { + switch (phase) { + case 0 /* Notification */: + if (onEmitNode !== ts.noEmitNotification) { + return pipelineEmitWithNotification; + } + // falls through + case 1 /* Substitution */: + if (substituteNode !== ts.noEmitSubstitution) { + return pipelineEmitWithSubstitution; + } + // falls through + case 2 /* Comments */: + if (!commentsDisabled && node.kind !== 279 /* SourceFile */) { + return pipelineEmitWithComments; + } + // falls through + case 3 /* SourceMaps */: + if (!sourceMapsDisabled && node.kind !== 279 /* SourceFile */ && !ts.isInJsonFile(node)) { + return pipelineEmitWithSourceMap; + } + // falls through + case 4 /* Emit */: + return pipelineEmitWithHint; + default: + return ts.Debug.assertNever(phase); + } + } + function getNextPipelinePhase(currentPhase, node) { + return getPipelinePhase(currentPhase + 1, node); + } + function pipelineEmitWithNotification(hint, node) { + var pipelinePhase = getNextPipelinePhase(0 /* Notification */, node); + onEmitNode(hint, node, pipelinePhase); + } + function pipelineEmitWithHint(hint, node) { + if (hint === 0 /* SourceFile */) + return emitSourceFile(ts.cast(node, ts.isSourceFile)); + if (hint === 2 /* IdentifierName */) + return emitIdentifier(ts.cast(node, ts.isIdentifier)); + if (hint === 3 /* MappedTypeParameter */) + return emitMappedTypeParameter(ts.cast(node, ts.isTypeParameterDeclaration)); + if (hint === 5 /* EmbeddedStatement */) { + ts.Debug.assertNode(node, ts.isEmptyStatement); + return emitEmptyStatement(/*isEmbeddedStatement*/ true); + } + if (hint === 4 /* Unspecified */) { + if (ts.isKeyword(node.kind)) + return writeTokenNode(node, writeKeyword); + switch (node.kind) { + // Pseudo-literals + case 15 /* TemplateHead */: + case 16 /* TemplateMiddle */: + case 17 /* TemplateTail */: + return emitLiteral(node); + case 281 /* UnparsedSource */: + return emitUnparsedSource(node); + // Identifiers + case 72 /* Identifier */: + return emitIdentifier(node); + // Parse tree nodes + // Names + case 148 /* QualifiedName */: + return emitQualifiedName(node); + case 149 /* ComputedPropertyName */: + return emitComputedPropertyName(node); + // Signature elements + case 150 /* TypeParameter */: + return emitTypeParameter(node); + case 151 /* Parameter */: + return emitParameter(node); + case 152 /* Decorator */: + return emitDecorator(node); + // Type members + case 153 /* PropertySignature */: + return emitPropertySignature(node); + case 154 /* PropertyDeclaration */: + return emitPropertyDeclaration(node); + case 155 /* MethodSignature */: + return emitMethodSignature(node); + case 156 /* MethodDeclaration */: + return emitMethodDeclaration(node); + case 157 /* Constructor */: + return emitConstructor(node); + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + return emitAccessorDeclaration(node); + case 160 /* CallSignature */: + return emitCallSignature(node); + case 161 /* ConstructSignature */: + return emitConstructSignature(node); + case 162 /* IndexSignature */: + return emitIndexSignature(node); + // Types + case 163 /* TypePredicate */: + return emitTypePredicate(node); + case 164 /* TypeReference */: + return emitTypeReference(node); + case 165 /* FunctionType */: + return emitFunctionType(node); + case 289 /* JSDocFunctionType */: + return emitJSDocFunctionType(node); + case 166 /* ConstructorType */: + return emitConstructorType(node); + case 167 /* TypeQuery */: + return emitTypeQuery(node); + case 168 /* TypeLiteral */: + return emitTypeLiteral(node); + case 169 /* ArrayType */: + return emitArrayType(node); + case 170 /* TupleType */: + return emitTupleType(node); + case 171 /* OptionalType */: + return emitOptionalType(node); + case 173 /* UnionType */: + return emitUnionType(node); + case 174 /* IntersectionType */: + return emitIntersectionType(node); + case 175 /* ConditionalType */: + return emitConditionalType(node); + case 176 /* InferType */: + return emitInferType(node); + case 177 /* ParenthesizedType */: + return emitParenthesizedType(node); + case 211 /* ExpressionWithTypeArguments */: + return emitExpressionWithTypeArguments(node); + case 178 /* ThisType */: + return emitThisType(); + case 179 /* TypeOperator */: + return emitTypeOperator(node); + case 180 /* IndexedAccessType */: + return emitIndexedAccessType(node); + case 181 /* MappedType */: + return emitMappedType(node); + case 182 /* LiteralType */: + return emitLiteralType(node); + case 183 /* ImportType */: + return emitImportTypeNode(node); + case 284 /* JSDocAllType */: + writePunctuation("*"); + return; + case 285 /* JSDocUnknownType */: + writePunctuation("?"); + return; + case 286 /* JSDocNullableType */: + return emitJSDocNullableType(node); + case 287 /* JSDocNonNullableType */: + return emitJSDocNonNullableType(node); + case 288 /* JSDocOptionalType */: + return emitJSDocOptionalType(node); + case 172 /* RestType */: + case 290 /* JSDocVariadicType */: + return emitRestOrJSDocVariadicType(node); + // Binding patterns + case 184 /* ObjectBindingPattern */: + return emitObjectBindingPattern(node); + case 185 /* ArrayBindingPattern */: + return emitArrayBindingPattern(node); + case 186 /* BindingElement */: + return emitBindingElement(node); + // Misc + case 216 /* TemplateSpan */: + return emitTemplateSpan(node); + case 217 /* SemicolonClassElement */: + return emitSemicolonClassElement(); + // Statements + case 218 /* Block */: + return emitBlock(node); + case 219 /* VariableStatement */: + return emitVariableStatement(node); + case 220 /* EmptyStatement */: + return emitEmptyStatement(/*isEmbeddedStatement*/ false); + case 221 /* ExpressionStatement */: + return emitExpressionStatement(node); + case 222 /* IfStatement */: + return emitIfStatement(node); + case 223 /* DoStatement */: + return emitDoStatement(node); + case 224 /* WhileStatement */: + return emitWhileStatement(node); + case 225 /* ForStatement */: + return emitForStatement(node); + case 226 /* ForInStatement */: + return emitForInStatement(node); + case 227 /* ForOfStatement */: + return emitForOfStatement(node); + case 228 /* ContinueStatement */: + return emitContinueStatement(node); + case 229 /* BreakStatement */: + return emitBreakStatement(node); + case 230 /* ReturnStatement */: + return emitReturnStatement(node); + case 231 /* WithStatement */: + return emitWithStatement(node); + case 232 /* SwitchStatement */: + return emitSwitchStatement(node); + case 233 /* LabeledStatement */: + return emitLabeledStatement(node); + case 234 /* ThrowStatement */: + return emitThrowStatement(node); + case 235 /* TryStatement */: + return emitTryStatement(node); + case 236 /* DebuggerStatement */: + return emitDebuggerStatement(node); + // Declarations + case 237 /* VariableDeclaration */: + return emitVariableDeclaration(node); + case 238 /* VariableDeclarationList */: + return emitVariableDeclarationList(node); + case 239 /* FunctionDeclaration */: + return emitFunctionDeclaration(node); + case 240 /* ClassDeclaration */: + return emitClassDeclaration(node); + case 241 /* InterfaceDeclaration */: + return emitInterfaceDeclaration(node); + case 242 /* TypeAliasDeclaration */: + return emitTypeAliasDeclaration(node); + case 243 /* EnumDeclaration */: + return emitEnumDeclaration(node); + case 244 /* ModuleDeclaration */: + return emitModuleDeclaration(node); + case 245 /* ModuleBlock */: + return emitModuleBlock(node); + case 246 /* CaseBlock */: + return emitCaseBlock(node); + case 247 /* NamespaceExportDeclaration */: + return emitNamespaceExportDeclaration(node); + case 248 /* ImportEqualsDeclaration */: + return emitImportEqualsDeclaration(node); + case 249 /* ImportDeclaration */: + return emitImportDeclaration(node); + case 250 /* ImportClause */: + return emitImportClause(node); + case 251 /* NamespaceImport */: + return emitNamespaceImport(node); + case 252 /* NamedImports */: + return emitNamedImports(node); + case 253 /* ImportSpecifier */: + return emitImportSpecifier(node); + case 254 /* ExportAssignment */: + return emitExportAssignment(node); + case 255 /* ExportDeclaration */: + return emitExportDeclaration(node); + case 256 /* NamedExports */: + return emitNamedExports(node); + case 257 /* ExportSpecifier */: + return emitExportSpecifier(node); + case 258 /* MissingDeclaration */: + return; + // Module references + case 259 /* ExternalModuleReference */: + return emitExternalModuleReference(node); + // JSX (non-expression) + case 11 /* JsxText */: + return emitJsxText(node); + case 262 /* JsxOpeningElement */: + case 265 /* JsxOpeningFragment */: + return emitJsxOpeningElementOrFragment(node); + case 263 /* JsxClosingElement */: + case 266 /* JsxClosingFragment */: + return emitJsxClosingElementOrFragment(node); + case 267 /* JsxAttribute */: + return emitJsxAttribute(node); + case 268 /* JsxAttributes */: + return emitJsxAttributes(node); + case 269 /* JsxSpreadAttribute */: + return emitJsxSpreadAttribute(node); + case 270 /* JsxExpression */: + return emitJsxExpression(node); + // Clauses + case 271 /* CaseClause */: + return emitCaseClause(node); + case 272 /* DefaultClause */: + return emitDefaultClause(node); + case 273 /* HeritageClause */: + return emitHeritageClause(node); + case 274 /* CatchClause */: + return emitCatchClause(node); + // Property assignments + case 275 /* PropertyAssignment */: + return emitPropertyAssignment(node); + case 276 /* ShorthandPropertyAssignment */: + return emitShorthandPropertyAssignment(node); + case 277 /* SpreadAssignment */: + return emitSpreadAssignment(node); + // Enum + case 278 /* EnumMember */: + return emitEnumMember(node); + // JSDoc nodes (only used in codefixes currently) + case 299 /* JSDocParameterTag */: + case 305 /* JSDocPropertyTag */: + return emitJSDocPropertyLikeTag(node); + case 300 /* JSDocReturnTag */: + case 302 /* JSDocTypeTag */: + case 301 /* JSDocThisTag */: + case 298 /* JSDocEnumTag */: + return emitJSDocSimpleTypedTag(node); + case 295 /* JSDocAugmentsTag */: + return emitJSDocAugmentsTag(node); + case 303 /* JSDocTemplateTag */: + return emitJSDocTemplateTag(node); + case 304 /* JSDocTypedefTag */: + return emitJSDocTypedefTag(node); + case 297 /* JSDocCallbackTag */: + return emitJSDocCallbackTag(node); + case 293 /* JSDocSignature */: + return emitJSDocSignature(node); + case 292 /* JSDocTypeLiteral */: + return emitJSDocTypeLiteral(node); + case 296 /* JSDocClassTag */: + case 294 /* JSDocTag */: + return emitJSDocSimpleTag(node); + case 291 /* JSDocComment */: + return emitJSDoc(node); + // Transformation nodes (ignored) + } + if (ts.isExpression(node)) { + hint = 1 /* Expression */; + if (substituteNode !== ts.noEmitSubstitution) { + node = substituteNode(hint, node); + } + } + else if (ts.isToken(node)) { + return writeTokenNode(node, writePunctuation); + } + } + if (hint === 1 /* Expression */) { + switch (node.kind) { + // Literals + case 8 /* NumericLiteral */: + case 9 /* BigIntLiteral */: + return emitNumericOrBigIntLiteral(node); + case 10 /* StringLiteral */: + case 13 /* RegularExpressionLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: + return emitLiteral(node); + // Identifiers + case 72 /* Identifier */: + return emitIdentifier(node); + // Reserved words + case 87 /* FalseKeyword */: + case 96 /* NullKeyword */: + case 98 /* SuperKeyword */: + case 102 /* TrueKeyword */: + case 100 /* ThisKeyword */: + case 92 /* ImportKeyword */: + writeTokenNode(node, writeKeyword); + return; + // Expressions + case 187 /* ArrayLiteralExpression */: + return emitArrayLiteralExpression(node); + case 188 /* ObjectLiteralExpression */: + return emitObjectLiteralExpression(node); + case 189 /* PropertyAccessExpression */: + return emitPropertyAccessExpression(node); + case 190 /* ElementAccessExpression */: + return emitElementAccessExpression(node); + case 191 /* CallExpression */: + return emitCallExpression(node); + case 192 /* NewExpression */: + return emitNewExpression(node); + case 193 /* TaggedTemplateExpression */: + return emitTaggedTemplateExpression(node); + case 194 /* TypeAssertionExpression */: + return emitTypeAssertionExpression(node); + case 195 /* ParenthesizedExpression */: + return emitParenthesizedExpression(node); + case 196 /* FunctionExpression */: + return emitFunctionExpression(node); + case 197 /* ArrowFunction */: + return emitArrowFunction(node); + case 198 /* DeleteExpression */: + return emitDeleteExpression(node); + case 199 /* TypeOfExpression */: + return emitTypeOfExpression(node); + case 200 /* VoidExpression */: + return emitVoidExpression(node); + case 201 /* AwaitExpression */: + return emitAwaitExpression(node); + case 202 /* PrefixUnaryExpression */: + return emitPrefixUnaryExpression(node); + case 203 /* PostfixUnaryExpression */: + return emitPostfixUnaryExpression(node); + case 204 /* BinaryExpression */: + return emitBinaryExpression(node); + case 205 /* ConditionalExpression */: + return emitConditionalExpression(node); + case 206 /* TemplateExpression */: + return emitTemplateExpression(node); + case 207 /* YieldExpression */: + return emitYieldExpression(node); + case 208 /* SpreadElement */: + return emitSpreadExpression(node); + case 209 /* ClassExpression */: + return emitClassExpression(node); + case 210 /* OmittedExpression */: + return; + case 212 /* AsExpression */: + return emitAsExpression(node); + case 213 /* NonNullExpression */: + return emitNonNullExpression(node); + case 214 /* MetaProperty */: + return emitMetaProperty(node); + // JSX + case 260 /* JsxElement */: + return emitJsxElement(node); + case 261 /* JsxSelfClosingElement */: + return emitJsxSelfClosingElement(node); + case 264 /* JsxFragment */: + return emitJsxFragment(node); + // Transformation nodes + case 308 /* PartiallyEmittedExpression */: + return emitPartiallyEmittedExpression(node); + case 309 /* CommaListExpression */: + return emitCommaList(node); + } + } + } + function emitMappedTypeParameter(node) { + emit(node.name); + writeSpace(); + writeKeyword("in"); + writeSpace(); + emit(node.constraint); + } + function pipelineEmitWithSubstitution(hint, node) { + var pipelinePhase = getNextPipelinePhase(1 /* Substitution */, node); + pipelinePhase(hint, substituteNode(hint, node)); + } + function emitHelpers(node) { + var helpersEmitted = false; + var bundle = node.kind === 280 /* Bundle */ ? node : undefined; + if (bundle && moduleKind === ts.ModuleKind.None) { + return; + } + var numNodes = bundle ? bundle.sourceFiles.length : 1; + for (var i = 0; i < numNodes; i++) { + var currentNode = bundle ? bundle.sourceFiles[i] : node; + var sourceFile = ts.isSourceFile(currentNode) ? currentNode : currentSourceFile; + var shouldSkip = printerOptions.noEmitHelpers || ts.getExternalHelpersModuleName(sourceFile) !== undefined; + var shouldBundle = ts.isSourceFile(currentNode) && !isOwnFileEmit; + var helpers = ts.getEmitHelpers(currentNode); + if (helpers) { + for (var _a = 0, _b = ts.stableSort(helpers, ts.compareEmitHelpers); _a < _b.length; _a++) { + var helper = _b[_a]; + if (!helper.scoped) { + // Skip the helper if it can be skipped and the noEmitHelpers compiler + // option is set, or if it can be imported and the importHelpers compiler + // option is set. + if (shouldSkip) + continue; + // Skip the helper if it can be bundled but hasn't already been emitted and we + // are emitting a bundled module. + if (shouldBundle) { + if (bundledHelpers.get(helper.name)) { + continue; + } + bundledHelpers.set(helper.name, true); + } + } + else if (bundle) { + // Skip the helper if it is scoped and we are emitting bundled helpers + continue; + } + if (typeof helper.text === "string") { + writeLines(helper.text); + } + else { + writeLines(helper.text(makeFileLevelOptimisticUniqueName)); + } + helpersEmitted = true; + } + } + } + return helpersEmitted; + } + // + // Literals/Pseudo-literals + // + // SyntaxKind.NumericLiteral + // SyntaxKind.BigIntLiteral + function emitNumericOrBigIntLiteral(node) { + emitLiteral(node); + } + // SyntaxKind.StringLiteral + // SyntaxKind.RegularExpressionLiteral + // SyntaxKind.NoSubstitutionTemplateLiteral + // SyntaxKind.TemplateHead + // SyntaxKind.TemplateMiddle + // SyntaxKind.TemplateTail + function emitLiteral(node) { + var text = getLiteralTextOfNode(node, printerOptions.neverAsciiEscape); + if ((printerOptions.sourceMap || printerOptions.inlineSourceMap) + && (node.kind === 10 /* StringLiteral */ || ts.isTemplateLiteralKind(node.kind))) { + writeLiteral(text); + } + else { + // Quick info expects all literals to be called with writeStringLiteral, as there's no specific type for numberLiterals + writeStringLiteral(text); + } + } + // SyntaxKind.UnparsedSource + function emitUnparsedSource(unparsed) { + writer.rawWrite(unparsed.text); + } + // + // Identifiers + // + function emitIdentifier(node) { + var writeText = node.symbol ? writeSymbol : write; + writeText(getTextOfNode(node, /*includeTrivia*/ false), node.symbol); + emitList(node, node.typeArguments, 53776 /* TypeParameters */); // Call emitList directly since it could be an array of TypeParameterDeclarations _or_ type arguments + } + // + // Names + // + function emitQualifiedName(node) { + emitEntityName(node.left); + writePunctuation("."); + emit(node.right); + } + function emitEntityName(node) { + if (node.kind === 72 /* Identifier */) { + emitExpression(node); + } + else { + emit(node); + } + } + function emitComputedPropertyName(node) { + writePunctuation("["); + emitExpression(node.expression); + writePunctuation("]"); + } + // + // Signature elements + // + function emitTypeParameter(node) { + emit(node.name); + if (node.constraint) { + writeSpace(); + writeKeyword("extends"); + writeSpace(); + emit(node.constraint); + } + if (node.default) { + writeSpace(); + writeOperator("="); + writeSpace(); + emit(node.default); + } + } + function emitParameter(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + emit(node.dotDotDotToken); + emitNodeWithWriter(node.name, writeParameter); + emit(node.questionToken); + if (node.parent && node.parent.kind === 289 /* JSDocFunctionType */ && !node.name) { + emit(node.type); + } + else { + emitTypeAnnotation(node.type); + } + // The comment position has to fallback to any present node within the parameterdeclaration because as it turns out, the parser can make parameter declarations with _just_ an initializer. + emitInitializer(node.initializer, node.type ? node.type.end : node.questionToken ? node.questionToken.end : node.name ? node.name.end : node.modifiers ? node.modifiers.end : node.decorators ? node.decorators.end : node.pos, node); + } + function emitDecorator(decorator) { + writePunctuation("@"); + emitExpression(decorator.expression); + } + // + // Type members + // + function emitPropertySignature(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + emitNodeWithWriter(node.name, writeProperty); + emit(node.questionToken); + emitTypeAnnotation(node.type); + writeTrailingSemicolon(); + } + function emitPropertyDeclaration(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + emit(node.name); + emit(node.questionToken); + emit(node.exclamationToken); + emitTypeAnnotation(node.type); + emitInitializer(node.initializer, node.type ? node.type.end : node.questionToken ? node.questionToken.end : node.name.end, node); + writeTrailingSemicolon(); + } + function emitMethodSignature(node) { + pushNameGenerationScope(node); + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + emit(node.name); + emit(node.questionToken); + emitTypeParameters(node, node.typeParameters); + emitParameters(node, node.parameters); + emitTypeAnnotation(node.type); + writeTrailingSemicolon(); + popNameGenerationScope(node); + } + function emitMethodDeclaration(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + emit(node.asteriskToken); + emit(node.name); + emit(node.questionToken); + emitSignatureAndBody(node, emitSignatureHead); + } + function emitConstructor(node) { + emitModifiers(node, node.modifiers); + writeKeyword("constructor"); + emitSignatureAndBody(node, emitSignatureHead); + } + function emitAccessorDeclaration(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + writeKeyword(node.kind === 158 /* GetAccessor */ ? "get" : "set"); + writeSpace(); + emit(node.name); + emitSignatureAndBody(node, emitSignatureHead); + } + function emitCallSignature(node) { + pushNameGenerationScope(node); + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + emitTypeParameters(node, node.typeParameters); + emitParameters(node, node.parameters); + emitTypeAnnotation(node.type); + writeTrailingSemicolon(); + popNameGenerationScope(node); + } + function emitConstructSignature(node) { + pushNameGenerationScope(node); + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + writeKeyword("new"); + writeSpace(); + emitTypeParameters(node, node.typeParameters); + emitParameters(node, node.parameters); + emitTypeAnnotation(node.type); + writeTrailingSemicolon(); + popNameGenerationScope(node); + } + function emitIndexSignature(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + emitParametersForIndexSignature(node, node.parameters); + emitTypeAnnotation(node.type); + writeTrailingSemicolon(); + } + function emitSemicolonClassElement() { + writeTrailingSemicolon(); + } + // + // Types + // + function emitTypePredicate(node) { + emit(node.parameterName); + writeSpace(); + writeKeyword("is"); + writeSpace(); + emit(node.type); + } + function emitTypeReference(node) { + emit(node.typeName); + emitTypeArguments(node, node.typeArguments); + } + function emitFunctionType(node) { + pushNameGenerationScope(node); + emitTypeParameters(node, node.typeParameters); + emitParametersForArrow(node, node.parameters); + writeSpace(); + writePunctuation("=>"); + writeSpace(); + emit(node.type); + popNameGenerationScope(node); + } + function emitJSDocFunctionType(node) { + writeKeyword("function"); + emitParameters(node, node.parameters); + writePunctuation(":"); + emit(node.type); + } + function emitJSDocNullableType(node) { + writePunctuation("?"); + emit(node.type); + } + function emitJSDocNonNullableType(node) { + writePunctuation("!"); + emit(node.type); + } + function emitJSDocOptionalType(node) { + emit(node.type); + writePunctuation("="); + } + function emitConstructorType(node) { + pushNameGenerationScope(node); + writeKeyword("new"); + writeSpace(); + emitTypeParameters(node, node.typeParameters); + emitParameters(node, node.parameters); + writeSpace(); + writePunctuation("=>"); + writeSpace(); + emit(node.type); + popNameGenerationScope(node); + } + function emitTypeQuery(node) { + writeKeyword("typeof"); + writeSpace(); + emit(node.exprName); + } + function emitTypeLiteral(node) { + writePunctuation("{"); + var flags = ts.getEmitFlags(node) & 1 /* SingleLine */ ? 768 /* SingleLineTypeLiteralMembers */ : 32897 /* MultiLineTypeLiteralMembers */; + emitList(node, node.members, flags | 524288 /* NoSpaceIfEmpty */); + writePunctuation("}"); + } + function emitArrayType(node) { + emit(node.elementType); + writePunctuation("["); + writePunctuation("]"); + } + function emitRestOrJSDocVariadicType(node) { + writePunctuation("..."); + emit(node.type); + } + function emitTupleType(node) { + writePunctuation("["); + emitList(node, node.elementTypes, 528 /* TupleTypeElements */); + writePunctuation("]"); + } + function emitOptionalType(node) { + emit(node.type); + writePunctuation("?"); + } + function emitUnionType(node) { + emitList(node, node.types, 516 /* UnionTypeConstituents */); + } + function emitIntersectionType(node) { + emitList(node, node.types, 520 /* IntersectionTypeConstituents */); + } + function emitConditionalType(node) { + emit(node.checkType); + writeSpace(); + writeKeyword("extends"); + writeSpace(); + emit(node.extendsType); + writeSpace(); + writePunctuation("?"); + writeSpace(); + emit(node.trueType); + writeSpace(); + writePunctuation(":"); + writeSpace(); + emit(node.falseType); + } + function emitInferType(node) { + writeKeyword("infer"); + writeSpace(); + emit(node.typeParameter); + } + function emitParenthesizedType(node) { + writePunctuation("("); + emit(node.type); + writePunctuation(")"); + } + function emitThisType() { + writeKeyword("this"); + } + function emitTypeOperator(node) { + writeTokenText(node.operator, writeKeyword); + writeSpace(); + emit(node.type); + } + function emitIndexedAccessType(node) { + emit(node.objectType); + writePunctuation("["); + emit(node.indexType); + writePunctuation("]"); + } + function emitMappedType(node) { + var emitFlags = ts.getEmitFlags(node); + writePunctuation("{"); + if (emitFlags & 1 /* SingleLine */) { + writeSpace(); + } + else { + writeLine(); + increaseIndent(); + } + if (node.readonlyToken) { + emit(node.readonlyToken); + if (node.readonlyToken.kind !== 133 /* ReadonlyKeyword */) { + writeKeyword("readonly"); + } + writeSpace(); + } + writePunctuation("["); + var pipelinePhase = getPipelinePhase(0 /* Notification */, node.typeParameter); + pipelinePhase(3 /* MappedTypeParameter */, node.typeParameter); + writePunctuation("]"); + if (node.questionToken) { + emit(node.questionToken); + if (node.questionToken.kind !== 56 /* QuestionToken */) { + writePunctuation("?"); + } + } + writePunctuation(":"); + writeSpace(); + emit(node.type); + writeTrailingSemicolon(); + if (emitFlags & 1 /* SingleLine */) { + writeSpace(); + } + else { + writeLine(); + decreaseIndent(); + } + writePunctuation("}"); + } + function emitLiteralType(node) { + emitExpression(node.literal); + } + function emitImportTypeNode(node) { + if (node.isTypeOf) { + writeKeyword("typeof"); + writeSpace(); + } + writeKeyword("import"); + writePunctuation("("); + emit(node.argument); + writePunctuation(")"); + if (node.qualifier) { + writePunctuation("."); + emit(node.qualifier); + } + emitTypeArguments(node, node.typeArguments); + } + // + // Binding patterns + // + function emitObjectBindingPattern(node) { + writePunctuation("{"); + emitList(node, node.elements, 525136 /* ObjectBindingPatternElements */); + writePunctuation("}"); + } + function emitArrayBindingPattern(node) { + writePunctuation("["); + emitList(node, node.elements, 524880 /* ArrayBindingPatternElements */); + writePunctuation("]"); + } + function emitBindingElement(node) { + emit(node.dotDotDotToken); + if (node.propertyName) { + emit(node.propertyName); + writePunctuation(":"); + writeSpace(); + } + emit(node.name); + emitInitializer(node.initializer, node.name.end, node); + } + // + // Expressions + // + function emitArrayLiteralExpression(node) { + var elements = node.elements; + var preferNewLine = node.multiLine ? 65536 /* PreferNewLine */ : 0 /* None */; + emitExpressionList(node, elements, 8914 /* ArrayLiteralExpressionElements */ | preferNewLine); + } + function emitObjectLiteralExpression(node) { + ts.forEach(node.properties, generateMemberNames); + var indentedFlag = ts.getEmitFlags(node) & 65536 /* Indented */; + if (indentedFlag) { + increaseIndent(); + } + var preferNewLine = node.multiLine ? 65536 /* PreferNewLine */ : 0 /* None */; + var allowTrailingComma = currentSourceFile.languageVersion >= 1 /* ES5 */ && !ts.isJsonSourceFile(currentSourceFile) ? 64 /* AllowTrailingComma */ : 0 /* None */; + emitList(node, node.properties, 526226 /* ObjectLiteralExpressionProperties */ | allowTrailingComma | preferNewLine); + if (indentedFlag) { + decreaseIndent(); + } + } + function emitPropertyAccessExpression(node) { + var indentBeforeDot = false; + var indentAfterDot = false; + if (!(ts.getEmitFlags(node) & 131072 /* NoIndentation */)) { + var dotRangeStart = node.expression.end; + var dotRangeEnd = ts.skipTrivia(currentSourceFile.text, node.expression.end) + 1; + var dotToken = ts.createToken(24 /* DotToken */); + dotToken.pos = dotRangeStart; + dotToken.end = dotRangeEnd; + indentBeforeDot = needsIndentation(node, node.expression, dotToken); + indentAfterDot = needsIndentation(node, dotToken, node.name); + } + emitExpression(node.expression); + increaseIndentIf(indentBeforeDot, /*writeSpaceIfNotIndenting*/ false); + var shouldEmitDotDot = !indentBeforeDot && needsDotDotForPropertyAccess(node.expression); + if (shouldEmitDotDot) { + writePunctuation("."); + } + emitTokenWithComment(24 /* DotToken */, node.expression.end, writePunctuation, node); + increaseIndentIf(indentAfterDot, /*writeSpaceIfNotIndenting*/ false); + emit(node.name); + decreaseIndentIf(indentBeforeDot, indentAfterDot); + } + // 1..toString is a valid property access, emit a dot after the literal + // Also emit a dot if expression is a integer const enum value - it will appear in generated code as numeric literal + function needsDotDotForPropertyAccess(expression) { + expression = ts.skipPartiallyEmittedExpressions(expression); + if (ts.isNumericLiteral(expression)) { + // check if numeric literal is a decimal literal that was originally written with a dot + var text = getLiteralTextOfNode(expression, /*neverAsciiEscape*/ true); + return !expression.numericLiteralFlags + && !ts.stringContains(text, ts.tokenToString(24 /* DotToken */)); + } + else if (ts.isPropertyAccessExpression(expression) || ts.isElementAccessExpression(expression)) { + // check if constant enum value is integer + var constantValue = ts.getConstantValue(expression); + // isFinite handles cases when constantValue is undefined + return typeof constantValue === "number" && isFinite(constantValue) + && Math.floor(constantValue) === constantValue + && printerOptions.removeComments; + } + } + function emitElementAccessExpression(node) { + emitExpression(node.expression); + emitTokenWithComment(22 /* OpenBracketToken */, node.expression.end, writePunctuation, node); + emitExpression(node.argumentExpression); + emitTokenWithComment(23 /* CloseBracketToken */, node.argumentExpression.end, writePunctuation, node); + } + function emitCallExpression(node) { + emitExpression(node.expression); + emitTypeArguments(node, node.typeArguments); + emitExpressionList(node, node.arguments, 2576 /* CallExpressionArguments */); + } + function emitNewExpression(node) { + emitTokenWithComment(95 /* NewKeyword */, node.pos, writeKeyword, node); + writeSpace(); + emitExpression(node.expression); + emitTypeArguments(node, node.typeArguments); + emitExpressionList(node, node.arguments, 18960 /* NewExpressionArguments */); + } + function emitTaggedTemplateExpression(node) { + emitExpression(node.tag); + emitTypeArguments(node, node.typeArguments); + writeSpace(); + emitExpression(node.template); + } + function emitTypeAssertionExpression(node) { + writePunctuation("<"); + emit(node.type); + writePunctuation(">"); + emitExpression(node.expression); + } + function emitParenthesizedExpression(node) { + var openParenPos = emitTokenWithComment(20 /* OpenParenToken */, node.pos, writePunctuation, node); + emitExpression(node.expression); + emitTokenWithComment(21 /* CloseParenToken */, node.expression ? node.expression.end : openParenPos, writePunctuation, node); + } + function emitFunctionExpression(node) { + generateNameIfNeeded(node.name); + emitFunctionDeclarationOrExpression(node); + } + function emitArrowFunction(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + emitSignatureAndBody(node, emitArrowFunctionHead); + } + function emitArrowFunctionHead(node) { + emitTypeParameters(node, node.typeParameters); + emitParametersForArrow(node, node.parameters); + emitTypeAnnotation(node.type); + writeSpace(); + emit(node.equalsGreaterThanToken); + } + function emitDeleteExpression(node) { + emitTokenWithComment(81 /* DeleteKeyword */, node.pos, writeKeyword, node); + writeSpace(); + emitExpression(node.expression); + } + function emitTypeOfExpression(node) { + emitTokenWithComment(104 /* TypeOfKeyword */, node.pos, writeKeyword, node); + writeSpace(); + emitExpression(node.expression); + } + function emitVoidExpression(node) { + emitTokenWithComment(106 /* VoidKeyword */, node.pos, writeKeyword, node); + writeSpace(); + emitExpression(node.expression); + } + function emitAwaitExpression(node) { + emitTokenWithComment(122 /* AwaitKeyword */, node.pos, writeKeyword, node); + writeSpace(); + emitExpression(node.expression); + } + function emitPrefixUnaryExpression(node) { + writeTokenText(node.operator, writeOperator); + if (shouldEmitWhitespaceBeforeOperand(node)) { + writeSpace(); + } + emitExpression(node.operand); + } + function shouldEmitWhitespaceBeforeOperand(node) { + // In some cases, we need to emit a space between the operator and the operand. One obvious case + // is when the operator is an identifier, like delete or typeof. We also need to do this for plus + // and minus expressions in certain cases. Specifically, consider the following two cases (parens + // are just for clarity of exposition, and not part of the source code): + // + // (+(+1)) + // (+(++1)) + // + // We need to emit a space in both cases. In the first case, the absence of a space will make + // the resulting expression a prefix increment operation. And in the second, it will make the resulting + // expression a prefix increment whose operand is a plus expression - (++(+x)) + // The same is true of minus of course. + var operand = node.operand; + return operand.kind === 202 /* PrefixUnaryExpression */ + && ((node.operator === 38 /* PlusToken */ && (operand.operator === 38 /* PlusToken */ || operand.operator === 44 /* PlusPlusToken */)) + || (node.operator === 39 /* MinusToken */ && (operand.operator === 39 /* MinusToken */ || operand.operator === 45 /* MinusMinusToken */))); + } + function emitPostfixUnaryExpression(node) { + emitExpression(node.operand); + writeTokenText(node.operator, writeOperator); + } + function emitBinaryExpression(node) { + var isCommaOperator = node.operatorToken.kind !== 27 /* CommaToken */; + var indentBeforeOperator = needsIndentation(node, node.left, node.operatorToken); + var indentAfterOperator = needsIndentation(node, node.operatorToken, node.right); + emitExpression(node.left); + increaseIndentIf(indentBeforeOperator, isCommaOperator); + emitLeadingCommentsOfPosition(node.operatorToken.pos); + writeTokenNode(node.operatorToken, node.operatorToken.kind === 93 /* InKeyword */ ? writeKeyword : writeOperator); + emitTrailingCommentsOfPosition(node.operatorToken.end, /*prefixSpace*/ true); // Binary operators should have a space before the comment starts + increaseIndentIf(indentAfterOperator, /*writeSpaceIfNotIndenting*/ true); + emitExpression(node.right); + decreaseIndentIf(indentBeforeOperator, indentAfterOperator); + } + function emitConditionalExpression(node) { + var indentBeforeQuestion = needsIndentation(node, node.condition, node.questionToken); + var indentAfterQuestion = needsIndentation(node, node.questionToken, node.whenTrue); + var indentBeforeColon = needsIndentation(node, node.whenTrue, node.colonToken); + var indentAfterColon = needsIndentation(node, node.colonToken, node.whenFalse); + emitExpression(node.condition); + increaseIndentIf(indentBeforeQuestion, /*writeSpaceIfNotIndenting*/ true); + emit(node.questionToken); + increaseIndentIf(indentAfterQuestion, /*writeSpaceIfNotIndenting*/ true); + emitExpression(node.whenTrue); + decreaseIndentIf(indentBeforeQuestion, indentAfterQuestion); + increaseIndentIf(indentBeforeColon, /*writeSpaceIfNotIndenting*/ true); + emit(node.colonToken); + increaseIndentIf(indentAfterColon, /*writeSpaceIfNotIndenting*/ true); + emitExpression(node.whenFalse); + decreaseIndentIf(indentBeforeColon, indentAfterColon); + } + function emitTemplateExpression(node) { + emit(node.head); + emitList(node, node.templateSpans, 262144 /* TemplateExpressionSpans */); + } + function emitYieldExpression(node) { + emitTokenWithComment(117 /* YieldKeyword */, node.pos, writeKeyword, node); + emit(node.asteriskToken); + emitExpressionWithLeadingSpace(node.expression); + } + function emitSpreadExpression(node) { + emitTokenWithComment(25 /* DotDotDotToken */, node.pos, writePunctuation, node); + emitExpression(node.expression); + } + function emitClassExpression(node) { + generateNameIfNeeded(node.name); + emitClassDeclarationOrExpression(node); + } + function emitExpressionWithTypeArguments(node) { + emitExpression(node.expression); + emitTypeArguments(node, node.typeArguments); + } + function emitAsExpression(node) { + emitExpression(node.expression); + if (node.type) { + writeSpace(); + writeKeyword("as"); + writeSpace(); + emit(node.type); + } + } + function emitNonNullExpression(node) { + emitExpression(node.expression); + writeOperator("!"); + } + function emitMetaProperty(node) { + writeToken(node.keywordToken, node.pos, writePunctuation); + writePunctuation("."); + emit(node.name); + } + // + // Misc + // + function emitTemplateSpan(node) { + emitExpression(node.expression); + emit(node.literal); + } + // + // Statements + // + function emitBlock(node) { + emitBlockStatements(node, /*forceSingleLine*/ !node.multiLine && isEmptyBlock(node)); + } + function emitBlockStatements(node, forceSingleLine) { + emitTokenWithComment(18 /* OpenBraceToken */, node.pos, writePunctuation, /*contextNode*/ node); + var format = forceSingleLine || ts.getEmitFlags(node) & 1 /* SingleLine */ ? 768 /* SingleLineBlockStatements */ : 129 /* MultiLineBlockStatements */; + emitList(node, node.statements, format); + emitTokenWithComment(19 /* CloseBraceToken */, node.statements.end, writePunctuation, /*contextNode*/ node, /*indentLeading*/ !!(format & 1 /* MultiLine */)); + } + function emitVariableStatement(node) { + emitModifiers(node, node.modifiers); + emit(node.declarationList); + writeTrailingSemicolon(); + } + function emitEmptyStatement(isEmbeddedStatement) { + // While most trailing semicolons are possibly insignificant, an embedded "empty" + // statement is significant and cannot be elided by a trailing-semicolon-omitting writer. + if (isEmbeddedStatement) { + writePunctuation(";"); + } + else { + writeTrailingSemicolon(); + } + } + function emitExpressionStatement(node) { + emitExpression(node.expression); + // Emit semicolon in non json files + // or if json file that created synthesized expression(eg.define expression statement when --out and amd code generation) + if (!ts.isJsonSourceFile(currentSourceFile) || ts.nodeIsSynthesized(node.expression)) { + writeTrailingSemicolon(); + } + } + function emitIfStatement(node) { + var openParenPos = emitTokenWithComment(91 /* IfKeyword */, node.pos, writeKeyword, node); + writeSpace(); + emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node); + emitExpression(node.expression); + emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node); + emitEmbeddedStatement(node, node.thenStatement); + if (node.elseStatement) { + writeLineOrSpace(node); + emitTokenWithComment(83 /* ElseKeyword */, node.thenStatement.end, writeKeyword, node); + if (node.elseStatement.kind === 222 /* IfStatement */) { + writeSpace(); + emit(node.elseStatement); + } + else { + emitEmbeddedStatement(node, node.elseStatement); + } + } + } + function emitWhileClause(node, startPos) { + var openParenPos = emitTokenWithComment(107 /* WhileKeyword */, startPos, writeKeyword, node); + writeSpace(); + emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node); + emitExpression(node.expression); + emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node); + } + function emitDoStatement(node) { + emitTokenWithComment(82 /* DoKeyword */, node.pos, writeKeyword, node); + emitEmbeddedStatement(node, node.statement); + if (ts.isBlock(node.statement)) { + writeSpace(); + } + else { + writeLineOrSpace(node); + } + emitWhileClause(node, node.statement.end); + writePunctuation(";"); + } + function emitWhileStatement(node) { + emitWhileClause(node, node.pos); + emitEmbeddedStatement(node, node.statement); + } + function emitForStatement(node) { + var openParenPos = emitTokenWithComment(89 /* ForKeyword */, node.pos, writeKeyword, node); + writeSpace(); + var pos = emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, /*contextNode*/ node); + emitForBinding(node.initializer); + pos = emitTokenWithComment(26 /* SemicolonToken */, node.initializer ? node.initializer.end : pos, writePunctuation, node); + emitExpressionWithLeadingSpace(node.condition); + pos = emitTokenWithComment(26 /* SemicolonToken */, node.condition ? node.condition.end : pos, writePunctuation, node); + emitExpressionWithLeadingSpace(node.incrementor); + emitTokenWithComment(21 /* CloseParenToken */, node.incrementor ? node.incrementor.end : pos, writePunctuation, node); + emitEmbeddedStatement(node, node.statement); + } + function emitForInStatement(node) { + var openParenPos = emitTokenWithComment(89 /* ForKeyword */, node.pos, writeKeyword, node); + writeSpace(); + emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node); + emitForBinding(node.initializer); + writeSpace(); + emitTokenWithComment(93 /* InKeyword */, node.initializer.end, writeKeyword, node); + writeSpace(); + emitExpression(node.expression); + emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node); + emitEmbeddedStatement(node, node.statement); + } + function emitForOfStatement(node) { + var openParenPos = emitTokenWithComment(89 /* ForKeyword */, node.pos, writeKeyword, node); + writeSpace(); + emitWithTrailingSpace(node.awaitModifier); + emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node); + emitForBinding(node.initializer); + writeSpace(); + emitTokenWithComment(147 /* OfKeyword */, node.initializer.end, writeKeyword, node); + writeSpace(); + emitExpression(node.expression); + emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node); + emitEmbeddedStatement(node, node.statement); + } + function emitForBinding(node) { + if (node !== undefined) { + if (node.kind === 238 /* VariableDeclarationList */) { + emit(node); + } + else { + emitExpression(node); + } + } + } + function emitContinueStatement(node) { + emitTokenWithComment(78 /* ContinueKeyword */, node.pos, writeKeyword, node); + emitWithLeadingSpace(node.label); + writeTrailingSemicolon(); + } + function emitBreakStatement(node) { + emitTokenWithComment(73 /* BreakKeyword */, node.pos, writeKeyword, node); + emitWithLeadingSpace(node.label); + writeTrailingSemicolon(); + } + function emitTokenWithComment(token, pos, writer, contextNode, indentLeading) { + var node = ts.getParseTreeNode(contextNode); + var isSimilarNode = node && node.kind === contextNode.kind; + var startPos = pos; + if (isSimilarNode) { + pos = ts.skipTrivia(currentSourceFile.text, pos); + } + if (emitLeadingCommentsOfPosition && isSimilarNode && contextNode.pos !== startPos) { + var needsIndent = indentLeading && !ts.positionsAreOnSameLine(startPos, pos, currentSourceFile); + if (needsIndent) { + increaseIndent(); + } + emitLeadingCommentsOfPosition(startPos); + if (needsIndent) { + decreaseIndent(); + } + } + pos = writeTokenText(token, writer, pos); + if (emitTrailingCommentsOfPosition && isSimilarNode && contextNode.end !== pos) { + emitTrailingCommentsOfPosition(pos, /*prefixSpace*/ true); + } + return pos; + } + function emitReturnStatement(node) { + emitTokenWithComment(97 /* ReturnKeyword */, node.pos, writeKeyword, /*contextNode*/ node); + emitExpressionWithLeadingSpace(node.expression); + writeTrailingSemicolon(); + } + function emitWithStatement(node) { + var openParenPos = emitTokenWithComment(108 /* WithKeyword */, node.pos, writeKeyword, node); + writeSpace(); + emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node); + emitExpression(node.expression); + emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node); + emitEmbeddedStatement(node, node.statement); + } + function emitSwitchStatement(node) { + var openParenPos = emitTokenWithComment(99 /* SwitchKeyword */, node.pos, writeKeyword, node); + writeSpace(); + emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node); + emitExpression(node.expression); + emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node); + writeSpace(); + emit(node.caseBlock); + } + function emitLabeledStatement(node) { + emit(node.label); + emitTokenWithComment(57 /* ColonToken */, node.label.end, writePunctuation, node); + writeSpace(); + emit(node.statement); + } + function emitThrowStatement(node) { + emitTokenWithComment(101 /* ThrowKeyword */, node.pos, writeKeyword, node); + emitExpressionWithLeadingSpace(node.expression); + writeTrailingSemicolon(); + } + function emitTryStatement(node) { + emitTokenWithComment(103 /* TryKeyword */, node.pos, writeKeyword, node); + writeSpace(); + emit(node.tryBlock); + if (node.catchClause) { + writeLineOrSpace(node); + emit(node.catchClause); + } + if (node.finallyBlock) { + writeLineOrSpace(node); + emitTokenWithComment(88 /* FinallyKeyword */, (node.catchClause || node.tryBlock).end, writeKeyword, node); + writeSpace(); + emit(node.finallyBlock); + } + } + function emitDebuggerStatement(node) { + writeToken(79 /* DebuggerKeyword */, node.pos, writeKeyword); + writeTrailingSemicolon(); + } + // + // Declarations + // + function emitVariableDeclaration(node) { + emit(node.name); + emitTypeAnnotation(node.type); + emitInitializer(node.initializer, node.type ? node.type.end : node.name.end, node); + } + function emitVariableDeclarationList(node) { + writeKeyword(ts.isLet(node) ? "let" : ts.isVarConst(node) ? "const" : "var"); + writeSpace(); + emitList(node, node.declarations, 528 /* VariableDeclarationList */); + } + function emitFunctionDeclaration(node) { + emitFunctionDeclarationOrExpression(node); + } + function emitFunctionDeclarationOrExpression(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + writeKeyword("function"); + emit(node.asteriskToken); + writeSpace(); + emitIdentifierName(node.name); // TODO: GH#18217 + emitSignatureAndBody(node, emitSignatureHead); + } + function emitBlockCallback(_hint, body) { + emitBlockFunctionBody(body); + } + function emitSignatureAndBody(node, emitSignatureHead) { + var body = node.body; + if (body) { + if (ts.isBlock(body)) { + var indentedFlag = ts.getEmitFlags(node) & 65536 /* Indented */; + if (indentedFlag) { + increaseIndent(); + } + pushNameGenerationScope(node); + ts.forEach(node.parameters, generateNames); + generateNames(node.body); + emitSignatureHead(node); + if (onEmitNode) { + onEmitNode(4 /* Unspecified */, body, emitBlockCallback); + } + else { + emitBlockFunctionBody(body); + } + popNameGenerationScope(node); + if (indentedFlag) { + decreaseIndent(); + } + } + else { + emitSignatureHead(node); + writeSpace(); + emitExpression(body); + } + } + else { + emitSignatureHead(node); + writeTrailingSemicolon(); + } + } + function emitSignatureHead(node) { + emitTypeParameters(node, node.typeParameters); + emitParameters(node, node.parameters); + emitTypeAnnotation(node.type); + } + function shouldEmitBlockFunctionBodyOnSingleLine(body) { + // We must emit a function body as a single-line body in the following case: + // * The body has NodeEmitFlags.SingleLine specified. + // We must emit a function body as a multi-line body in the following cases: + // * The body is explicitly marked as multi-line. + // * A non-synthesized body's start and end position are on different lines. + // * Any statement in the body starts on a new line. + if (ts.getEmitFlags(body) & 1 /* SingleLine */) { + return true; + } + if (body.multiLine) { + return false; + } + if (!ts.nodeIsSynthesized(body) && !ts.rangeIsOnSingleLine(body, currentSourceFile)) { + return false; + } + if (shouldWriteLeadingLineTerminator(body, body.statements, 2 /* PreserveLines */) + || shouldWriteClosingLineTerminator(body, body.statements, 2 /* PreserveLines */)) { + return false; + } + var previousStatement; + for (var _a = 0, _b = body.statements; _a < _b.length; _a++) { + var statement = _b[_a]; + if (shouldWriteSeparatingLineTerminator(previousStatement, statement, 2 /* PreserveLines */)) { + return false; + } + previousStatement = statement; + } + return true; + } + function emitBlockFunctionBody(body) { + writeSpace(); + writePunctuation("{"); + increaseIndent(); + var emitBlockFunctionBody = shouldEmitBlockFunctionBodyOnSingleLine(body) + ? emitBlockFunctionBodyOnSingleLine + : emitBlockFunctionBodyWorker; + if (emitBodyWithDetachedComments) { + emitBodyWithDetachedComments(body, body.statements, emitBlockFunctionBody); + } + else { + emitBlockFunctionBody(body); + } + decreaseIndent(); + writeToken(19 /* CloseBraceToken */, body.statements.end, writePunctuation, body); + } + function emitBlockFunctionBodyOnSingleLine(body) { + emitBlockFunctionBodyWorker(body, /*emitBlockFunctionBodyOnSingleLine*/ true); + } + function emitBlockFunctionBodyWorker(body, emitBlockFunctionBodyOnSingleLine) { + // Emit all the prologue directives (like "use strict"). + var statementOffset = emitPrologueDirectives(body.statements, /*startWithNewLine*/ true); + var pos = writer.getTextPos(); + emitHelpers(body); + if (statementOffset === 0 && pos === writer.getTextPos() && emitBlockFunctionBodyOnSingleLine) { + decreaseIndent(); + emitList(body, body.statements, 768 /* SingleLineFunctionBodyStatements */); + increaseIndent(); + } + else { + emitList(body, body.statements, 1 /* MultiLineFunctionBodyStatements */, statementOffset); + } + } + function emitClassDeclaration(node) { + emitClassDeclarationOrExpression(node); + } + function emitClassDeclarationOrExpression(node) { + ts.forEach(node.members, generateMemberNames); + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + writeKeyword("class"); + if (node.name) { + writeSpace(); + emitIdentifierName(node.name); + } + var indentedFlag = ts.getEmitFlags(node) & 65536 /* Indented */; + if (indentedFlag) { + increaseIndent(); + } + emitTypeParameters(node, node.typeParameters); + emitList(node, node.heritageClauses, 0 /* ClassHeritageClauses */); + writeSpace(); + writePunctuation("{"); + emitList(node, node.members, 129 /* ClassMembers */); + writePunctuation("}"); + if (indentedFlag) { + decreaseIndent(); + } + } + function emitInterfaceDeclaration(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + writeKeyword("interface"); + writeSpace(); + emit(node.name); + emitTypeParameters(node, node.typeParameters); + emitList(node, node.heritageClauses, 512 /* HeritageClauses */); + writeSpace(); + writePunctuation("{"); + emitList(node, node.members, 129 /* InterfaceMembers */); + writePunctuation("}"); + } + function emitTypeAliasDeclaration(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + writeKeyword("type"); + writeSpace(); + emit(node.name); + emitTypeParameters(node, node.typeParameters); + writeSpace(); + writePunctuation("="); + writeSpace(); + emit(node.type); + writeTrailingSemicolon(); + } + function emitEnumDeclaration(node) { + emitModifiers(node, node.modifiers); + writeKeyword("enum"); + writeSpace(); + emit(node.name); + writeSpace(); + writePunctuation("{"); + emitList(node, node.members, 145 /* EnumMembers */); + writePunctuation("}"); + } + function emitModuleDeclaration(node) { + emitModifiers(node, node.modifiers); + if (~node.flags & 512 /* GlobalAugmentation */) { + writeKeyword(node.flags & 16 /* Namespace */ ? "namespace" : "module"); + writeSpace(); + } + emit(node.name); + var body = node.body; + if (!body) + return writeTrailingSemicolon(); + while (body.kind === 244 /* ModuleDeclaration */) { + writePunctuation("."); + emit(body.name); + body = body.body; + } + writeSpace(); + emit(body); + } + function emitModuleBlock(node) { + pushNameGenerationScope(node); + ts.forEach(node.statements, generateNames); + emitBlockStatements(node, /*forceSingleLine*/ isEmptyBlock(node)); + popNameGenerationScope(node); + } + function emitCaseBlock(node) { + emitTokenWithComment(18 /* OpenBraceToken */, node.pos, writePunctuation, node); + emitList(node, node.clauses, 129 /* CaseBlockClauses */); + emitTokenWithComment(19 /* CloseBraceToken */, node.clauses.end, writePunctuation, node, /*indentLeading*/ true); + } + function emitImportEqualsDeclaration(node) { + emitModifiers(node, node.modifiers); + emitTokenWithComment(92 /* ImportKeyword */, node.modifiers ? node.modifiers.end : node.pos, writeKeyword, node); + writeSpace(); + emit(node.name); + writeSpace(); + emitTokenWithComment(59 /* EqualsToken */, node.name.end, writePunctuation, node); + writeSpace(); + emitModuleReference(node.moduleReference); + writeTrailingSemicolon(); + } + function emitModuleReference(node) { + if (node.kind === 72 /* Identifier */) { + emitExpression(node); + } + else { + emit(node); + } + } + function emitImportDeclaration(node) { + emitModifiers(node, node.modifiers); + emitTokenWithComment(92 /* ImportKeyword */, node.modifiers ? node.modifiers.end : node.pos, writeKeyword, node); + writeSpace(); + if (node.importClause) { + emit(node.importClause); + writeSpace(); + emitTokenWithComment(144 /* FromKeyword */, node.importClause.end, writeKeyword, node); + writeSpace(); + } + emitExpression(node.moduleSpecifier); + writeTrailingSemicolon(); + } + function emitImportClause(node) { + emit(node.name); + if (node.name && node.namedBindings) { + emitTokenWithComment(27 /* CommaToken */, node.name.end, writePunctuation, node); + writeSpace(); + } + emit(node.namedBindings); + } + function emitNamespaceImport(node) { + var asPos = emitTokenWithComment(40 /* AsteriskToken */, node.pos, writePunctuation, node); + writeSpace(); + emitTokenWithComment(119 /* AsKeyword */, asPos, writeKeyword, node); + writeSpace(); + emit(node.name); + } + function emitNamedImports(node) { + emitNamedImportsOrExports(node); + } + function emitImportSpecifier(node) { + emitImportOrExportSpecifier(node); + } + function emitExportAssignment(node) { + var nextPos = emitTokenWithComment(85 /* ExportKeyword */, node.pos, writeKeyword, node); + writeSpace(); + if (node.isExportEquals) { + emitTokenWithComment(59 /* EqualsToken */, nextPos, writeOperator, node); + } + else { + emitTokenWithComment(80 /* DefaultKeyword */, nextPos, writeKeyword, node); + } + writeSpace(); + emitExpression(node.expression); + writeTrailingSemicolon(); + } + function emitExportDeclaration(node) { + var nextPos = emitTokenWithComment(85 /* ExportKeyword */, node.pos, writeKeyword, node); + writeSpace(); + if (node.exportClause) { + emit(node.exportClause); + } + else { + nextPos = emitTokenWithComment(40 /* AsteriskToken */, nextPos, writePunctuation, node); + } + if (node.moduleSpecifier) { + writeSpace(); + var fromPos = node.exportClause ? node.exportClause.end : nextPos; + emitTokenWithComment(144 /* FromKeyword */, fromPos, writeKeyword, node); + writeSpace(); + emitExpression(node.moduleSpecifier); + } + writeTrailingSemicolon(); + } + function emitNamespaceExportDeclaration(node) { + var nextPos = emitTokenWithComment(85 /* ExportKeyword */, node.pos, writeKeyword, node); + writeSpace(); + nextPos = emitTokenWithComment(119 /* AsKeyword */, nextPos, writeKeyword, node); + writeSpace(); + nextPos = emitTokenWithComment(131 /* NamespaceKeyword */, nextPos, writeKeyword, node); + writeSpace(); + emit(node.name); + writeTrailingSemicolon(); + } + function emitNamedExports(node) { + emitNamedImportsOrExports(node); + } + function emitExportSpecifier(node) { + emitImportOrExportSpecifier(node); + } + function emitNamedImportsOrExports(node) { + writePunctuation("{"); + emitList(node, node.elements, 525136 /* NamedImportsOrExportsElements */); + writePunctuation("}"); + } + function emitImportOrExportSpecifier(node) { + if (node.propertyName) { + emit(node.propertyName); + writeSpace(); + emitTokenWithComment(119 /* AsKeyword */, node.propertyName.end, writeKeyword, node); + writeSpace(); + } + emit(node.name); + } + // + // Module references + // + function emitExternalModuleReference(node) { + writeKeyword("require"); + writePunctuation("("); + emitExpression(node.expression); + writePunctuation(")"); + } + // + // JSX + // + function emitJsxElement(node) { + emit(node.openingElement); + emitList(node, node.children, 262144 /* JsxElementOrFragmentChildren */); + emit(node.closingElement); + } + function emitJsxSelfClosingElement(node) { + writePunctuation("<"); + emitJsxTagName(node.tagName); + writeSpace(); + emit(node.attributes); + writePunctuation("/>"); + } + function emitJsxFragment(node) { + emit(node.openingFragment); + emitList(node, node.children, 262144 /* JsxElementOrFragmentChildren */); + emit(node.closingFragment); + } + function emitJsxOpeningElementOrFragment(node) { + writePunctuation("<"); + if (ts.isJsxOpeningElement(node)) { + emitJsxTagName(node.tagName); + if (node.attributes.properties && node.attributes.properties.length > 0) { + writeSpace(); + } + emit(node.attributes); + } + writePunctuation(">"); + } + function emitJsxText(node) { + writer.writeLiteral(getTextOfNode(node, /*includeTrivia*/ true)); + } + function emitJsxClosingElementOrFragment(node) { + writePunctuation(""); + } + function emitJsxAttributes(node) { + emitList(node, node.properties, 262656 /* JsxElementAttributes */); + } + function emitJsxAttribute(node) { + emit(node.name); + emitNodeWithPrefix("=", writePunctuation, node.initializer, emit); // TODO: GH#18217 + } + function emitJsxSpreadAttribute(node) { + writePunctuation("{..."); + emitExpression(node.expression); + writePunctuation("}"); + } + function emitJsxExpression(node) { + if (node.expression) { + writePunctuation("{"); + emit(node.dotDotDotToken); + emitExpression(node.expression); + writePunctuation("}"); + } + } + function emitJsxTagName(node) { + if (node.kind === 72 /* Identifier */) { + emitExpression(node); + } + else { + emit(node); + } + } + // + // Clauses + // + function emitCaseClause(node) { + emitTokenWithComment(74 /* CaseKeyword */, node.pos, writeKeyword, node); + writeSpace(); + emitExpression(node.expression); + emitCaseOrDefaultClauseRest(node, node.statements, node.expression.end); + } + function emitDefaultClause(node) { + var pos = emitTokenWithComment(80 /* DefaultKeyword */, node.pos, writeKeyword, node); + emitCaseOrDefaultClauseRest(node, node.statements, pos); + } + function emitCaseOrDefaultClauseRest(parentNode, statements, colonPos) { + var emitAsSingleStatement = statements.length === 1 && + ( + // treat synthesized nodes as located on the same line for emit purposes + ts.nodeIsSynthesized(parentNode) || + ts.nodeIsSynthesized(statements[0]) || + ts.rangeStartPositionsAreOnSameLine(parentNode, statements[0], currentSourceFile)); + var format = 163969 /* CaseOrDefaultClauseStatements */; + if (emitAsSingleStatement) { + writeToken(57 /* ColonToken */, colonPos, writePunctuation, parentNode); + writeSpace(); + format &= ~(1 /* MultiLine */ | 128 /* Indented */); + } + else { + emitTokenWithComment(57 /* ColonToken */, colonPos, writePunctuation, parentNode); + } + emitList(parentNode, statements, format); + } + function emitHeritageClause(node) { + writeSpace(); + writeTokenText(node.token, writeKeyword); + writeSpace(); + emitList(node, node.types, 528 /* HeritageClauseTypes */); + } + function emitCatchClause(node) { + var openParenPos = emitTokenWithComment(75 /* CatchKeyword */, node.pos, writeKeyword, node); + writeSpace(); + if (node.variableDeclaration) { + emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node); + emit(node.variableDeclaration); + emitTokenWithComment(21 /* CloseParenToken */, node.variableDeclaration.end, writePunctuation, node); + writeSpace(); + } + emit(node.block); + } + // + // Property assignments + // + function emitPropertyAssignment(node) { + emit(node.name); + writePunctuation(":"); + writeSpace(); + // This is to ensure that we emit comment in the following case: + // For example: + // obj = { + // id: /*comment1*/ ()=>void + // } + // "comment1" is not considered to be leading comment for node.initializer + // but rather a trailing comment on the previous node. + var initializer = node.initializer; + if (emitTrailingCommentsOfPosition && (ts.getEmitFlags(initializer) & 512 /* NoLeadingComments */) === 0) { + var commentRange = ts.getCommentRange(initializer); + emitTrailingCommentsOfPosition(commentRange.pos); + } + emitExpression(initializer); + } + function emitShorthandPropertyAssignment(node) { + emit(node.name); + if (node.objectAssignmentInitializer) { + writeSpace(); + writePunctuation("="); + writeSpace(); + emitExpression(node.objectAssignmentInitializer); + } + } + function emitSpreadAssignment(node) { + if (node.expression) { + emitTokenWithComment(25 /* DotDotDotToken */, node.pos, writePunctuation, node); + emitExpression(node.expression); + } + } + // + // Enum + // + function emitEnumMember(node) { + emit(node.name); + emitInitializer(node.initializer, node.name.end, node); + } + // + // JSDoc + // + function emitJSDoc(node) { + write("/**"); + if (node.comment) { + var lines = node.comment.split(/\r\n?|\n/g); + for (var _a = 0, lines_2 = lines; _a < lines_2.length; _a++) { + var line = lines_2[_a]; + writeLine(); + writeSpace(); + writePunctuation("*"); + writeSpace(); + write(line); + } + } + if (node.tags) { + if (node.tags.length === 1 && node.tags[0].kind === 302 /* JSDocTypeTag */ && !node.comment) { + writeSpace(); + emit(node.tags[0]); + } + else { + emitList(node, node.tags, 33 /* JSDocComment */); + } + } + writeSpace(); + write("*/"); + } + function emitJSDocSimpleTypedTag(tag) { + emitJSDocTagName(tag.tagName); + emitJSDocTypeExpression(tag.typeExpression); + emitJSDocComment(tag.comment); + } + function emitJSDocAugmentsTag(tag) { + emitJSDocTagName(tag.tagName); + writeSpace(); + writePunctuation("{"); + emit(tag.class); + writePunctuation("}"); + emitJSDocComment(tag.comment); + } + function emitJSDocTemplateTag(tag) { + emitJSDocTagName(tag.tagName); + emitJSDocTypeExpression(tag.constraint); + writeSpace(); + emitList(tag, tag.typeParameters, 528 /* CommaListElements */); + emitJSDocComment(tag.comment); + } + function emitJSDocTypedefTag(tag) { + emitJSDocTagName(tag.tagName); + if (tag.typeExpression) { + if (tag.typeExpression.kind === 283 /* JSDocTypeExpression */) { + emitJSDocTypeExpression(tag.typeExpression); + } + else { + writeSpace(); + writePunctuation("{"); + write("Object"); + if (tag.typeExpression.isArrayType) { + writePunctuation("["); + writePunctuation("]"); + } + writePunctuation("}"); + } + } + if (tag.fullName) { + writeSpace(); + emit(tag.fullName); + } + emitJSDocComment(tag.comment); + if (tag.typeExpression && tag.typeExpression.kind === 292 /* JSDocTypeLiteral */) { + emitJSDocTypeLiteral(tag.typeExpression); + } + } + function emitJSDocCallbackTag(tag) { + emitJSDocTagName(tag.tagName); + if (tag.name) { + writeSpace(); + emit(tag.name); + } + emitJSDocComment(tag.comment); + emitJSDocSignature(tag.typeExpression); + } + function emitJSDocSimpleTag(tag) { + emitJSDocTagName(tag.tagName); + emitJSDocComment(tag.comment); + } + function emitJSDocTypeLiteral(lit) { + emitList(lit, ts.createNodeArray(lit.jsDocPropertyTags), 33 /* JSDocComment */); + } + function emitJSDocSignature(sig) { + if (sig.typeParameters) { + emitList(sig, ts.createNodeArray(sig.typeParameters), 33 /* JSDocComment */); + } + if (sig.parameters) { + emitList(sig, ts.createNodeArray(sig.parameters), 33 /* JSDocComment */); + } + if (sig.type) { + writeLine(); + writeSpace(); + writePunctuation("*"); + writeSpace(); + emit(sig.type); + } + } + function emitJSDocPropertyLikeTag(param) { + emitJSDocTagName(param.tagName); + emitJSDocTypeExpression(param.typeExpression); + writeSpace(); + if (param.isBracketed) { + writePunctuation("["); + } + emit(param.name); + if (param.isBracketed) { + writePunctuation("]"); + } + emitJSDocComment(param.comment); + } + function emitJSDocTagName(tagName) { + writePunctuation("@"); + emit(tagName); + } + function emitJSDocComment(comment) { + if (comment) { + writeSpace(); + write(comment); + } + } + function emitJSDocTypeExpression(typeExpression) { + if (typeExpression) { + writeSpace(); + writePunctuation("{"); + emit(typeExpression.type); + writePunctuation("}"); + } + } + // + // Top-level nodes + // + function emitSourceFile(node) { + writeLine(); + var statements = node.statements; + if (emitBodyWithDetachedComments) { + // Emit detached comment if there are no prologue directives or if the first node is synthesized. + // The synthesized node will have no leading comment so some comments may be missed. + var shouldEmitDetachedComment = statements.length === 0 || + !ts.isPrologueDirective(statements[0]) || + ts.nodeIsSynthesized(statements[0]); + if (shouldEmitDetachedComment) { + emitBodyWithDetachedComments(node, statements, emitSourceFileWorker); + return; + } + } + emitSourceFileWorker(node); + } + function emitSyntheticTripleSlashReferencesIfNeeded(node) { + emitTripleSlashDirectives(!!node.hasNoDefaultLib, node.syntheticFileReferences || [], node.syntheticTypeReferences || [], node.syntheticLibReferences || []); + } + function emitTripleSlashDirectivesIfNeeded(node) { + if (node.isDeclarationFile) + emitTripleSlashDirectives(node.hasNoDefaultLib, node.referencedFiles, node.typeReferenceDirectives, node.libReferenceDirectives); + } + function emitTripleSlashDirectives(hasNoDefaultLib, files, types, libs) { + if (hasNoDefaultLib) { + writeComment("/// "); + writeLine(); + } + if (currentSourceFile && currentSourceFile.moduleName) { + writeComment("/// "); + writeLine(); + } + if (currentSourceFile && currentSourceFile.amdDependencies) { + for (var _a = 0, _b = currentSourceFile.amdDependencies; _a < _b.length; _a++) { + var dep = _b[_a]; + if (dep.name) { + writeComment("/// "); + } + else { + writeComment("/// "); + } + writeLine(); + } + } + for (var _c = 0, files_1 = files; _c < files_1.length; _c++) { + var directive = files_1[_c]; + writeComment("/// "); + writeLine(); + } + for (var _d = 0, types_18 = types; _d < types_18.length; _d++) { + var directive = types_18[_d]; + writeComment("/// "); + writeLine(); + } + for (var _e = 0, libs_1 = libs; _e < libs_1.length; _e++) { + var directive = libs_1[_e]; + writeComment("/// "); + writeLine(); + } + } + function emitSourceFileWorker(node) { + var statements = node.statements; + pushNameGenerationScope(node); + ts.forEach(node.statements, generateNames); + emitHelpers(node); + var index = ts.findIndex(statements, function (statement) { return !ts.isPrologueDirective(statement); }); + emitTripleSlashDirectivesIfNeeded(node); + emitList(node, statements, 1 /* MultiLine */, index === -1 ? statements.length : index); + popNameGenerationScope(node); + } + // Transformation nodes + function emitPartiallyEmittedExpression(node) { + emitExpression(node.expression); + } + function emitCommaList(node) { + emitExpressionList(node, node.elements, 528 /* CommaListElements */); + } + /** + * Emits any prologue directives at the start of a Statement list, returning the + * number of prologue directives written to the output. + */ + function emitPrologueDirectives(statements, startWithNewLine, seenPrologueDirectives) { + for (var i = 0; i < statements.length; i++) { + var statement = statements[i]; + if (ts.isPrologueDirective(statement)) { + var shouldEmitPrologueDirective = seenPrologueDirectives ? !seenPrologueDirectives.has(statement.expression.text) : true; + if (shouldEmitPrologueDirective) { + if (startWithNewLine || i > 0) { + writeLine(); + } + emit(statement); + if (seenPrologueDirectives) { + seenPrologueDirectives.set(statement.expression.text, true); + } + } + } + else { + // return index of the first non prologue directive + return i; + } + } + return statements.length; + } + function emitPrologueDirectivesIfNeeded(sourceFileOrBundle) { + if (ts.isSourceFile(sourceFileOrBundle)) { + setSourceFile(sourceFileOrBundle); + emitPrologueDirectives(sourceFileOrBundle.statements); + } + else { + var seenPrologueDirectives = ts.createMap(); + for (var _a = 0, _b = sourceFileOrBundle.sourceFiles; _a < _b.length; _a++) { + var sourceFile = _b[_a]; + setSourceFile(sourceFile); + emitPrologueDirectives(sourceFile.statements, /*startWithNewLine*/ true, seenPrologueDirectives); + } + setSourceFile(undefined); + } + } + function emitShebangIfNeeded(sourceFileOrBundle) { + if (ts.isSourceFile(sourceFileOrBundle)) { + var shebang = ts.getShebang(sourceFileOrBundle.text); + if (shebang) { + writeComment(shebang); + writeLine(); + return true; + } + } + else { + for (var _a = 0, _b = sourceFileOrBundle.sourceFiles; _a < _b.length; _a++) { + var sourceFile = _b[_a]; + // Emit only the first encountered shebang + if (emitShebangIfNeeded(sourceFile)) { + break; + } + } + } + } + // + // Helpers + // + function emitNodeWithWriter(node, writer) { + if (!node) + return; + var savedWrite = write; + write = writer; + emit(node); + write = savedWrite; + } + function emitModifiers(node, modifiers) { + if (modifiers && modifiers.length) { + emitList(node, modifiers, 262656 /* Modifiers */); + writeSpace(); + } + } + function emitTypeAnnotation(node) { + if (node) { + writePunctuation(":"); + writeSpace(); + emit(node); + } + } + function emitInitializer(node, equalCommentStartPos, container) { + if (node) { + writeSpace(); + emitTokenWithComment(59 /* EqualsToken */, equalCommentStartPos, writeOperator, container); + writeSpace(); + emitExpression(node); + } + } + function emitNodeWithPrefix(prefix, prefixWriter, node, emit) { + if (node) { + prefixWriter(prefix); + emit(node); + } + } + function emitWithLeadingSpace(node) { + if (node) { + writeSpace(); + emit(node); + } + } + function emitExpressionWithLeadingSpace(node) { + if (node) { + writeSpace(); + emitExpression(node); + } + } + function emitWithTrailingSpace(node) { + if (node) { + emit(node); + writeSpace(); + } + } + function emitEmbeddedStatement(parent, node) { + if (ts.isBlock(node) || ts.getEmitFlags(parent) & 1 /* SingleLine */) { + writeSpace(); + emit(node); + } + else { + writeLine(); + increaseIndent(); + if (ts.isEmptyStatement(node)) { + var pipelinePhase = getPipelinePhase(0 /* Notification */, node); + pipelinePhase(5 /* EmbeddedStatement */, node); + } + else { + emit(node); + } + decreaseIndent(); + } + } + function emitDecorators(parentNode, decorators) { + emitList(parentNode, decorators, 49153 /* Decorators */); + } + function emitTypeArguments(parentNode, typeArguments) { + emitList(parentNode, typeArguments, 53776 /* TypeArguments */); + } + function emitTypeParameters(parentNode, typeParameters) { + if (ts.isFunctionLike(parentNode) && parentNode.typeArguments) { // Quick info uses type arguments in place of type parameters on instantiated signatures + return emitTypeArguments(parentNode, parentNode.typeArguments); + } + emitList(parentNode, typeParameters, 53776 /* TypeParameters */); + } + function emitParameters(parentNode, parameters) { + emitList(parentNode, parameters, 2576 /* Parameters */); + } + function canEmitSimpleArrowHead(parentNode, parameters) { + var parameter = ts.singleOrUndefined(parameters); + return parameter + && parameter.pos === parentNode.pos // may not have parsed tokens between parent and parameter + && ts.isArrowFunction(parentNode) // only arrow functions may have simple arrow head + && !parentNode.type // arrow function may not have return type annotation + && !ts.some(parentNode.decorators) // parent may not have decorators + && !ts.some(parentNode.modifiers) // parent may not have modifiers + && !ts.some(parentNode.typeParameters) // parent may not have type parameters + && !ts.some(parameter.decorators) // parameter may not have decorators + && !ts.some(parameter.modifiers) // parameter may not have modifiers + && !parameter.dotDotDotToken // parameter may not be rest + && !parameter.questionToken // parameter may not be optional + && !parameter.type // parameter may not have a type annotation + && !parameter.initializer // parameter may not have an initializer + && ts.isIdentifier(parameter.name); // parameter name must be identifier + } + function emitParametersForArrow(parentNode, parameters) { + if (canEmitSimpleArrowHead(parentNode, parameters)) { + emitList(parentNode, parameters, 2576 /* Parameters */ & ~2048 /* Parenthesis */); + } + else { + emitParameters(parentNode, parameters); + } + } + function emitParametersForIndexSignature(parentNode, parameters) { + emitList(parentNode, parameters, 8848 /* IndexSignatureParameters */); + } + function emitList(parentNode, children, format, start, count) { + emitNodeList(emit, parentNode, children, format, start, count); + } + function emitExpressionList(parentNode, children, format, start, count) { + emitNodeList(emitExpression, parentNode, children, format, start, count); // TODO: GH#18217 + } + function writeDelimiter(format) { + switch (format & 60 /* DelimitersMask */) { + case 0 /* None */: + break; + case 16 /* CommaDelimited */: + writePunctuation(","); + break; + case 4 /* BarDelimited */: + writeSpace(); + writePunctuation("|"); + break; + case 32 /* AsteriskDelimited */: + writeSpace(); + writePunctuation("*"); + writeSpace(); + break; + case 8 /* AmpersandDelimited */: + writeSpace(); + writePunctuation("&"); + break; + } + } + function emitNodeList(emit, parentNode, children, format, start, count) { + if (start === void 0) { start = 0; } + if (count === void 0) { count = children ? children.length - start : 0; } + var isUndefined = children === undefined; + if (isUndefined && format & 16384 /* OptionalIfUndefined */) { + return; + } + var isEmpty = children === undefined || start >= children.length || count === 0; + if (isEmpty && format & 32768 /* OptionalIfEmpty */) { + if (onBeforeEmitNodeArray) { + onBeforeEmitNodeArray(children); + } + if (onAfterEmitNodeArray) { + onAfterEmitNodeArray(children); + } + return; + } + if (format & 15360 /* BracketsMask */) { + writePunctuation(getOpeningBracket(format)); + if (isEmpty && !isUndefined) { + // TODO: GH#18217 + emitTrailingCommentsOfPosition(children.pos, /*prefixSpace*/ true); // Emit comments within empty bracketed lists + } + } + if (onBeforeEmitNodeArray) { + onBeforeEmitNodeArray(children); + } + if (isEmpty) { + // Write a line terminator if the parent node was multi-line + if (format & 1 /* MultiLine */) { + writeLine(); + } + else if (format & 256 /* SpaceBetweenBraces */ && !(format & 524288 /* NoSpaceIfEmpty */)) { + writeSpace(); + } + } + else { + // Write the opening line terminator or leading whitespace. + var mayEmitInterveningComments = (format & 262144 /* NoInterveningComments */) === 0; + var shouldEmitInterveningComments = mayEmitInterveningComments; + if (shouldWriteLeadingLineTerminator(parentNode, children, format)) { // TODO: GH#18217 + writeLine(); + shouldEmitInterveningComments = false; + } + else if (format & 256 /* SpaceBetweenBraces */) { + writeSpace(); + } + // Increase the indent, if requested. + if (format & 128 /* Indented */) { + increaseIndent(); + } + // Emit each child. + var previousSibling = void 0; + var shouldDecreaseIndentAfterEmit = false; + for (var i = 0; i < count; i++) { + var child = children[start + i]; + // Write the delimiter if this is not the first node. + if (format & 32 /* AsteriskDelimited */) { + // always write JSDoc in the format "\n *" + writeLine(); + writeDelimiter(format); + } + else if (previousSibling) { + // i.e + // function commentedParameters( + // /* Parameter a */ + // a + // /* End of parameter a */ -> this comment isn't considered to be trailing comment of parameter "a" due to newline + // , + if (format & 60 /* DelimitersMask */ && previousSibling.end !== parentNode.end) { + emitLeadingCommentsOfPosition(previousSibling.end); + } + writeDelimiter(format); + // Write either a line terminator or whitespace to separate the elements. + if (shouldWriteSeparatingLineTerminator(previousSibling, child, format)) { + // If a synthesized node in a single-line list starts on a new + // line, we should increase the indent. + if ((format & (3 /* LinesMask */ | 128 /* Indented */)) === 0 /* SingleLine */) { + increaseIndent(); + shouldDecreaseIndentAfterEmit = true; + } + writeLine(); + shouldEmitInterveningComments = false; + } + else if (previousSibling && format & 512 /* SpaceBetweenSiblings */) { + writeSpace(); + } + } + // Emit this child. + if (shouldEmitInterveningComments) { + if (emitTrailingCommentsOfPosition) { + var commentRange = ts.getCommentRange(child); + emitTrailingCommentsOfPosition(commentRange.pos); + } + } + else { + shouldEmitInterveningComments = mayEmitInterveningComments; + } + emit(child); + if (shouldDecreaseIndentAfterEmit) { + decreaseIndent(); + shouldDecreaseIndentAfterEmit = false; + } + previousSibling = child; + } + // Write a trailing comma, if requested. + var hasTrailingComma = (format & 64 /* AllowTrailingComma */) && children.hasTrailingComma; + if (format & 16 /* CommaDelimited */ && hasTrailingComma) { + writePunctuation(","); + } + // Emit any trailing comment of the last element in the list + // i.e + // var array = [... + // 2 + // /* end of element 2 */ + // ]; + if (previousSibling && format & 60 /* DelimitersMask */ && previousSibling.end !== parentNode.end && !(ts.getEmitFlags(previousSibling) & 1024 /* NoTrailingComments */)) { + emitLeadingCommentsOfPosition(previousSibling.end); + } + // Decrease the indent, if requested. + if (format & 128 /* Indented */) { + decreaseIndent(); + } + // Write the closing line terminator or closing whitespace. + if (shouldWriteClosingLineTerminator(parentNode, children, format)) { + writeLine(); + } + else if (format & 256 /* SpaceBetweenBraces */) { + writeSpace(); + } + } + if (onAfterEmitNodeArray) { + onAfterEmitNodeArray(children); + } + if (format & 15360 /* BracketsMask */) { + if (isEmpty && !isUndefined) { + // TODO: GH#18217 + emitLeadingCommentsOfPosition(children.end); // Emit leading comments within empty lists + } + writePunctuation(getClosingBracket(format)); + } + } + // Writers + function writeLiteral(s) { + writer.writeLiteral(s); + } + function writeStringLiteral(s) { + writer.writeStringLiteral(s); + } + function writeBase(s) { + writer.write(s); + } + function writeSymbol(s, sym) { + writer.writeSymbol(s, sym); + } + function writePunctuation(s) { + writer.writePunctuation(s); + } + function writeTrailingSemicolon() { + writer.writeTrailingSemicolon(";"); + } + function writeKeyword(s) { + writer.writeKeyword(s); + } + function writeOperator(s) { + writer.writeOperator(s); + } + function writeParameter(s) { + writer.writeParameter(s); + } + function writeComment(s) { + writer.writeComment(s); + } + function writeSpace() { + writer.writeSpace(" "); + } + function writeProperty(s) { + writer.writeProperty(s); + } + function writeLine() { + writer.writeLine(); + } + function increaseIndent() { + writer.increaseIndent(); + } + function decreaseIndent() { + writer.decreaseIndent(); + } + function writeToken(token, pos, writer, contextNode) { + return !sourceMapsDisabled + ? emitTokenWithSourceMap(contextNode, token, writer, pos, writeTokenText) + : writeTokenText(token, writer, pos); + } + function writeTokenNode(node, writer) { + if (onBeforeEmitToken) { + onBeforeEmitToken(node); + } + writer(ts.tokenToString(node.kind)); + if (onAfterEmitToken) { + onAfterEmitToken(node); + } + } + function writeTokenText(token, writer, pos) { + var tokenString = ts.tokenToString(token); + writer(tokenString); + return pos < 0 ? pos : pos + tokenString.length; + } + function writeLineOrSpace(node) { + if (ts.getEmitFlags(node) & 1 /* SingleLine */) { + writeSpace(); + } + else { + writeLine(); + } + } + function writeLines(text) { + var lines = text.split(/\r\n?|\n/g); + var indentation = ts.guessIndentation(lines); + for (var _a = 0, lines_3 = lines; _a < lines_3.length; _a++) { + var lineText = lines_3[_a]; + var line = indentation ? lineText.slice(indentation) : lineText; + if (line.length) { + writeLine(); + write(line); + writer.rawWrite(newLine); + } + } + } + function increaseIndentIf(value, writeSpaceIfNotIndenting) { + if (value) { + increaseIndent(); + writeLine(); + } + else if (writeSpaceIfNotIndenting) { + writeSpace(); + } + } + // Helper function to decrease the indent if we previously indented. Allows multiple + // previous indent values to be considered at a time. This also allows caller to just + // call this once, passing in all their appropriate indent values, instead of needing + // to call this helper function multiple times. + function decreaseIndentIf(value1, value2) { + if (value1) { + decreaseIndent(); + } + if (value2) { + decreaseIndent(); + } + } + function shouldWriteLeadingLineTerminator(parentNode, children, format) { + if (format & 1 /* MultiLine */) { + return true; + } + if (format & 2 /* PreserveLines */) { + if (format & 65536 /* PreferNewLine */) { + return true; + } + var firstChild = children[0]; + if (firstChild === undefined) { + return !ts.rangeIsOnSingleLine(parentNode, currentSourceFile); + } + else if (ts.positionIsSynthesized(parentNode.pos) || ts.nodeIsSynthesized(firstChild)) { + return synthesizedNodeStartsOnNewLine(firstChild, format); + } + else { + return !ts.rangeStartPositionsAreOnSameLine(parentNode, firstChild, currentSourceFile); + } + } + else { + return false; + } + } + function shouldWriteSeparatingLineTerminator(previousNode, nextNode, format) { + if (format & 1 /* MultiLine */) { + return true; + } + else if (format & 2 /* PreserveLines */) { + if (previousNode === undefined || nextNode === undefined) { + return false; + } + else if (ts.nodeIsSynthesized(previousNode) || ts.nodeIsSynthesized(nextNode)) { + return synthesizedNodeStartsOnNewLine(previousNode, format) || synthesizedNodeStartsOnNewLine(nextNode, format); + } + else { + return !ts.rangeEndIsOnSameLineAsRangeStart(previousNode, nextNode, currentSourceFile); + } + } + else { + return ts.getStartsOnNewLine(nextNode); + } + } + function shouldWriteClosingLineTerminator(parentNode, children, format) { + if (format & 1 /* MultiLine */) { + return (format & 131072 /* NoTrailingNewLine */) === 0; + } + else if (format & 2 /* PreserveLines */) { + if (format & 65536 /* PreferNewLine */) { + return true; + } + var lastChild = ts.lastOrUndefined(children); + if (lastChild === undefined) { + return !ts.rangeIsOnSingleLine(parentNode, currentSourceFile); + } + else if (ts.positionIsSynthesized(parentNode.pos) || ts.nodeIsSynthesized(lastChild)) { + return synthesizedNodeStartsOnNewLine(lastChild, format); + } + else { + return !ts.rangeEndPositionsAreOnSameLine(parentNode, lastChild, currentSourceFile); + } + } + else { + return false; + } + } + function synthesizedNodeStartsOnNewLine(node, format) { + if (ts.nodeIsSynthesized(node)) { + var startsOnNewLine = ts.getStartsOnNewLine(node); + if (startsOnNewLine === undefined) { + return (format & 65536 /* PreferNewLine */) !== 0; + } + return startsOnNewLine; + } + return (format & 65536 /* PreferNewLine */) !== 0; + } + function needsIndentation(parent, node1, node2) { + parent = skipSynthesizedParentheses(parent); + node1 = skipSynthesizedParentheses(node1); + node2 = skipSynthesizedParentheses(node2); + // Always use a newline for synthesized code if the synthesizer desires it. + if (ts.getStartsOnNewLine(node2)) { + return true; + } + return !ts.nodeIsSynthesized(parent) + && !ts.nodeIsSynthesized(node1) + && !ts.nodeIsSynthesized(node2) + && !ts.rangeEndIsOnSameLineAsRangeStart(node1, node2, currentSourceFile); + } + function isEmptyBlock(block) { + return block.statements.length === 0 + && ts.rangeEndIsOnSameLineAsRangeStart(block, block, currentSourceFile); + } + function skipSynthesizedParentheses(node) { + while (node.kind === 195 /* ParenthesizedExpression */ && ts.nodeIsSynthesized(node)) { + node = node.expression; + } + return node; + } + function getTextOfNode(node, includeTrivia) { + if (ts.isGeneratedIdentifier(node)) { + return generateName(node); + } + else if (ts.isIdentifier(node) && (ts.nodeIsSynthesized(node) || !node.parent || !currentSourceFile || (node.parent && currentSourceFile && ts.getSourceFileOfNode(node) !== ts.getOriginalNode(currentSourceFile)))) { + return ts.idText(node); + } + else if (node.kind === 10 /* StringLiteral */ && node.textSourceNode) { + return getTextOfNode(node.textSourceNode, includeTrivia); + } + else if (ts.isLiteralExpression(node) && (ts.nodeIsSynthesized(node) || !node.parent)) { + return node.text; + } + return ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node, includeTrivia); + } + function getLiteralTextOfNode(node, neverAsciiEscape) { + if (node.kind === 10 /* StringLiteral */ && node.textSourceNode) { + var textSourceNode = node.textSourceNode; + if (ts.isIdentifier(textSourceNode)) { + return neverAsciiEscape || (ts.getEmitFlags(node) & 16777216 /* NoAsciiEscaping */) ? + "\"" + ts.escapeString(getTextOfNode(textSourceNode)) + "\"" : + "\"" + ts.escapeNonAsciiString(getTextOfNode(textSourceNode)) + "\""; + } + else { + return getLiteralTextOfNode(textSourceNode, neverAsciiEscape); + } + } + return ts.getLiteralText(node, currentSourceFile, neverAsciiEscape); + } + /** + * Push a new name generation scope. + */ + function pushNameGenerationScope(node) { + if (node && ts.getEmitFlags(node) & 524288 /* ReuseTempVariableScope */) { + return; + } + tempFlagsStack.push(tempFlags); + tempFlags = 0; + reservedNamesStack.push(reservedNames); + } + /** + * Pop the current name generation scope. + */ + function popNameGenerationScope(node) { + if (node && ts.getEmitFlags(node) & 524288 /* ReuseTempVariableScope */) { + return; + } + tempFlags = tempFlagsStack.pop(); + reservedNames = reservedNamesStack.pop(); + } + function reserveNameInNestedScopes(name) { + if (!reservedNames || reservedNames === ts.lastOrUndefined(reservedNamesStack)) { + reservedNames = ts.createMap(); + } + reservedNames.set(name, true); + } + function generateNames(node) { + if (!node) + return; + switch (node.kind) { + case 218 /* Block */: + ts.forEach(node.statements, generateNames); + break; + case 233 /* LabeledStatement */: + case 231 /* WithStatement */: + case 223 /* DoStatement */: + case 224 /* WhileStatement */: + generateNames(node.statement); + break; + case 222 /* IfStatement */: + generateNames(node.thenStatement); + generateNames(node.elseStatement); + break; + case 225 /* ForStatement */: + case 227 /* ForOfStatement */: + case 226 /* ForInStatement */: + generateNames(node.initializer); + generateNames(node.statement); + break; + case 232 /* SwitchStatement */: + generateNames(node.caseBlock); + break; + case 246 /* CaseBlock */: + ts.forEach(node.clauses, generateNames); + break; + case 271 /* CaseClause */: + case 272 /* DefaultClause */: + ts.forEach(node.statements, generateNames); + break; + case 235 /* TryStatement */: + generateNames(node.tryBlock); + generateNames(node.catchClause); + generateNames(node.finallyBlock); + break; + case 274 /* CatchClause */: + generateNames(node.variableDeclaration); + generateNames(node.block); + break; + case 219 /* VariableStatement */: + generateNames(node.declarationList); + break; + case 238 /* VariableDeclarationList */: + ts.forEach(node.declarations, generateNames); + break; + case 237 /* VariableDeclaration */: + case 151 /* Parameter */: + case 186 /* BindingElement */: + case 240 /* ClassDeclaration */: + generateNameIfNeeded(node.name); + break; + case 239 /* FunctionDeclaration */: + generateNameIfNeeded(node.name); + if (ts.getEmitFlags(node) & 524288 /* ReuseTempVariableScope */) { + ts.forEach(node.parameters, generateNames); + generateNames(node.body); + } + break; + case 184 /* ObjectBindingPattern */: + case 185 /* ArrayBindingPattern */: + ts.forEach(node.elements, generateNames); + break; + case 249 /* ImportDeclaration */: + generateNames(node.importClause); + break; + case 250 /* ImportClause */: + generateNameIfNeeded(node.name); + generateNames(node.namedBindings); + break; + case 251 /* NamespaceImport */: + generateNameIfNeeded(node.name); + break; + case 252 /* NamedImports */: + ts.forEach(node.elements, generateNames); + break; + case 253 /* ImportSpecifier */: + generateNameIfNeeded(node.propertyName || node.name); + break; + } + } + function generateMemberNames(node) { + if (!node) + return; + switch (node.kind) { + case 275 /* PropertyAssignment */: + case 276 /* ShorthandPropertyAssignment */: + case 154 /* PropertyDeclaration */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + generateNameIfNeeded(node.name); + break; + } + } + function generateNameIfNeeded(name) { + if (name) { + if (ts.isGeneratedIdentifier(name)) { + generateName(name); + } + else if (ts.isBindingPattern(name)) { + generateNames(name); + } + } + } + /** + * Generate the text for a generated identifier. + */ + function generateName(name) { + if ((name.autoGenerateFlags & 7 /* KindMask */) === 4 /* Node */) { + // Node names generate unique names based on their original node + // and are cached based on that node's id. + return generateNameCached(getNodeForGeneratedName(name), name.autoGenerateFlags); + } + else { + // Auto, Loop, and Unique names are cached based on their unique + // autoGenerateId. + var autoGenerateId = name.autoGenerateId; + return autoGeneratedIdToGeneratedName[autoGenerateId] || (autoGeneratedIdToGeneratedName[autoGenerateId] = makeName(name)); + } + } + function generateNameCached(node, flags) { + var nodeId = ts.getNodeId(node); + return nodeIdToGeneratedName[nodeId] || (nodeIdToGeneratedName[nodeId] = generateNameForNode(node, flags)); + } + /** + * Returns a value indicating whether a name is unique globally, within the current file, + * or within the NameGenerator. + */ + function isUniqueName(name) { + return isFileLevelUniqueName(name) + && !generatedNames.has(name) + && !(reservedNames && reservedNames.has(name)); + } + /** + * Returns a value indicating whether a name is unique globally or within the current file. + */ + function isFileLevelUniqueName(name) { + return currentSourceFile ? ts.isFileLevelUniqueName(currentSourceFile, name, hasGlobalName) : true; + } + /** + * Returns a value indicating whether a name is unique within a container. + */ + function isUniqueLocalName(name, container) { + for (var node = container; ts.isNodeDescendantOf(node, container); node = node.nextContainer) { + if (node.locals) { + var local = node.locals.get(ts.escapeLeadingUnderscores(name)); + // We conservatively include alias symbols to cover cases where they're emitted as locals + if (local && local.flags & (67220415 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */)) { + return false; + } + } + } + return true; + } + /** + * Return the next available name in the pattern _a ... _z, _0, _1, ... + * TempFlags._i or TempFlags._n may be used to express a preference for that dedicated name. + * Note that names generated by makeTempVariableName and makeUniqueName will never conflict. + */ + function makeTempVariableName(flags, reservedInNestedScopes) { + if (flags && !(tempFlags & flags)) { + var name = flags === 268435456 /* _i */ ? "_i" : "_n"; + if (isUniqueName(name)) { + tempFlags |= flags; + if (reservedInNestedScopes) { + reserveNameInNestedScopes(name); + } + return name; + } + } + while (true) { + var count = tempFlags & 268435455 /* CountMask */; + tempFlags++; + // Skip over 'i' and 'n' + if (count !== 8 && count !== 13) { + var name = count < 26 + ? "_" + String.fromCharCode(97 /* a */ + count) + : "_" + (count - 26); + if (isUniqueName(name)) { + if (reservedInNestedScopes) { + reserveNameInNestedScopes(name); + } + return name; + } + } + } + } + /** + * Generate a name that is unique within the current file and doesn't conflict with any names + * in global scope. The name is formed by adding an '_n' suffix to the specified base name, + * where n is a positive integer. Note that names generated by makeTempVariableName and + * makeUniqueName are guaranteed to never conflict. + * If `optimistic` is set, the first instance will use 'baseName' verbatim instead of 'baseName_1' + */ + function makeUniqueName(baseName, checkFn, optimistic, scoped) { + if (checkFn === void 0) { checkFn = isUniqueName; } + if (optimistic) { + if (checkFn(baseName)) { + if (scoped) { + reserveNameInNestedScopes(baseName); + } + else { + generatedNames.set(baseName, true); + } + return baseName; + } + } + // Find the first unique 'name_n', where n is a positive number + if (baseName.charCodeAt(baseName.length - 1) !== 95 /* _ */) { + baseName += "_"; + } + var i = 1; + while (true) { + var generatedName = baseName + i; + if (checkFn(generatedName)) { + if (scoped) { + reserveNameInNestedScopes(generatedName); + } + else { + generatedNames.set(generatedName, true); + } + return generatedName; + } + i++; + } + } + function makeFileLevelOptimisticUniqueName(name) { + return makeUniqueName(name, isFileLevelUniqueName, /*optimistic*/ true); + } + /** + * Generates a unique name for a ModuleDeclaration or EnumDeclaration. + */ + function generateNameForModuleOrEnum(node) { + var name = getTextOfNode(node.name); + // Use module/enum name itself if it is unique, otherwise make a unique variation + return isUniqueLocalName(name, node) ? name : makeUniqueName(name); + } + /** + * Generates a unique name for an ImportDeclaration or ExportDeclaration. + */ + function generateNameForImportOrExportDeclaration(node) { + var expr = ts.getExternalModuleName(node); // TODO: GH#18217 + var baseName = ts.isStringLiteral(expr) ? + ts.makeIdentifierFromModuleName(expr.text) : "module"; + return makeUniqueName(baseName); + } + /** + * Generates a unique name for a default export. + */ + function generateNameForExportDefault() { + return makeUniqueName("default"); + } + /** + * Generates a unique name for a class expression. + */ + function generateNameForClassExpression() { + return makeUniqueName("class"); + } + function generateNameForMethodOrAccessor(node) { + if (ts.isIdentifier(node.name)) { + return generateNameCached(node.name); + } + return makeTempVariableName(0 /* Auto */); + } + /** + * Generates a unique name from a node. + */ + function generateNameForNode(node, flags) { + switch (node.kind) { + case 72 /* Identifier */: + return makeUniqueName(getTextOfNode(node), isUniqueName, !!(flags & 16 /* Optimistic */), !!(flags & 8 /* ReservedInNestedScopes */)); + case 244 /* ModuleDeclaration */: + case 243 /* EnumDeclaration */: + return generateNameForModuleOrEnum(node); + case 249 /* ImportDeclaration */: + case 255 /* ExportDeclaration */: + return generateNameForImportOrExportDeclaration(node); + case 239 /* FunctionDeclaration */: + case 240 /* ClassDeclaration */: + case 254 /* ExportAssignment */: + return generateNameForExportDefault(); + case 209 /* ClassExpression */: + return generateNameForClassExpression(); + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + return generateNameForMethodOrAccessor(node); + default: + return makeTempVariableName(0 /* Auto */); + } + } + /** + * Generates a unique identifier for a node. + */ + function makeName(name) { + switch (name.autoGenerateFlags & 7 /* KindMask */) { + case 1 /* Auto */: + return makeTempVariableName(0 /* Auto */, !!(name.autoGenerateFlags & 8 /* ReservedInNestedScopes */)); + case 2 /* Loop */: + return makeTempVariableName(268435456 /* _i */, !!(name.autoGenerateFlags & 8 /* ReservedInNestedScopes */)); + case 3 /* Unique */: + return makeUniqueName(ts.idText(name), (name.autoGenerateFlags & 32 /* FileLevel */) ? isFileLevelUniqueName : isUniqueName, !!(name.autoGenerateFlags & 16 /* Optimistic */), !!(name.autoGenerateFlags & 8 /* ReservedInNestedScopes */)); + } + return ts.Debug.fail("Unsupported GeneratedIdentifierKind."); + } + /** + * Gets the node from which a name should be generated. + */ + function getNodeForGeneratedName(name) { + var autoGenerateId = name.autoGenerateId; + var node = name; + var original = node.original; + while (original) { + node = original; + // if "node" is a different generated name (having a different + // "autoGenerateId"), use it and stop traversing. + if (ts.isIdentifier(node) + && !!(node.autoGenerateFlags & 4 /* Node */) + && node.autoGenerateId !== autoGenerateId) { + break; + } + original = node.original; + } + // otherwise, return the original node for the source; + return node; + } + // Comments + function pipelineEmitWithComments(hint, node) { + enterComment(); + hasWrittenComment = false; + var emitFlags = ts.getEmitFlags(node); + var _a = ts.getCommentRange(node), pos = _a.pos, end = _a.end; + var isEmittedNode = node.kind !== 307 /* NotEmittedStatement */; + // We have to explicitly check that the node is JsxText because if the compilerOptions.jsx is "preserve" we will not do any transformation. + // It is expensive to walk entire tree just to set one kind of node to have no comments. + var skipLeadingComments = pos < 0 || (emitFlags & 512 /* NoLeadingComments */) !== 0 || node.kind === 11 /* JsxText */; + var skipTrailingComments = end < 0 || (emitFlags & 1024 /* NoTrailingComments */) !== 0 || node.kind === 11 /* JsxText */; + // Save current container state on the stack. + var savedContainerPos = containerPos; + var savedContainerEnd = containerEnd; + var savedDeclarationListContainerEnd = declarationListContainerEnd; + if ((pos > 0 || end > 0) && pos !== end) { + // Emit leading comments if the position is not synthesized and the node + // has not opted out from emitting leading comments. + if (!skipLeadingComments) { + emitLeadingComments(pos, isEmittedNode); + } + if (!skipLeadingComments || (pos >= 0 && (emitFlags & 512 /* NoLeadingComments */) !== 0)) { + // Advance the container position if comments get emitted or if they've been disabled explicitly using NoLeadingComments. + containerPos = pos; + } + if (!skipTrailingComments || (end >= 0 && (emitFlags & 1024 /* NoTrailingComments */) !== 0)) { + // As above. + containerEnd = end; + // To avoid invalid comment emit in a down-level binding pattern, we + // keep track of the last declaration list container's end + if (node.kind === 238 /* VariableDeclarationList */) { + declarationListContainerEnd = end; + } + } + } + ts.forEach(ts.getSyntheticLeadingComments(node), emitLeadingSynthesizedComment); + exitComment(); + var pipelinePhase = getNextPipelinePhase(2 /* Comments */, node); + if (emitFlags & 2048 /* NoNestedComments */) { + commentsDisabled = true; + pipelinePhase(hint, node); + commentsDisabled = false; + } + else { + pipelinePhase(hint, node); + } + enterComment(); + ts.forEach(ts.getSyntheticTrailingComments(node), emitTrailingSynthesizedComment); + if ((pos > 0 || end > 0) && pos !== end) { + // Restore previous container state. + containerPos = savedContainerPos; + containerEnd = savedContainerEnd; + declarationListContainerEnd = savedDeclarationListContainerEnd; + // Emit trailing comments if the position is not synthesized and the node + // has not opted out from emitting leading comments and is an emitted node. + if (!skipTrailingComments && isEmittedNode) { + emitTrailingComments(end); + } + } + exitComment(); + } + function emitLeadingSynthesizedComment(comment) { + if (comment.kind === 2 /* SingleLineCommentTrivia */) { + writer.writeLine(); + } + writeSynthesizedComment(comment); + if (comment.hasTrailingNewLine || comment.kind === 2 /* SingleLineCommentTrivia */) { + writer.writeLine(); + } + else { + writer.writeSpace(" "); + } + } + function emitTrailingSynthesizedComment(comment) { + if (!writer.isAtStartOfLine()) { + writer.writeSpace(" "); + } + writeSynthesizedComment(comment); + if (comment.hasTrailingNewLine) { + writer.writeLine(); + } + } + function writeSynthesizedComment(comment) { + var text = formatSynthesizedComment(comment); + var lineMap = comment.kind === 3 /* MultiLineCommentTrivia */ ? ts.computeLineStarts(text) : undefined; + ts.writeCommentRange(text, lineMap, writer, 0, text.length, newLine); + } + function formatSynthesizedComment(comment) { + return comment.kind === 3 /* MultiLineCommentTrivia */ + ? "/*" + comment.text + "*/" + : "//" + comment.text; + } + function emitBodyWithDetachedComments(node, detachedRange, emitCallback) { + enterComment(); + var pos = detachedRange.pos, end = detachedRange.end; + var emitFlags = ts.getEmitFlags(node); + var skipLeadingComments = pos < 0 || (emitFlags & 512 /* NoLeadingComments */) !== 0; + var skipTrailingComments = commentsDisabled || end < 0 || (emitFlags & 1024 /* NoTrailingComments */) !== 0; + if (!skipLeadingComments) { + emitDetachedCommentsAndUpdateCommentsInfo(detachedRange); + } + exitComment(); + if (emitFlags & 2048 /* NoNestedComments */ && !commentsDisabled) { + commentsDisabled = true; + emitCallback(node); + commentsDisabled = false; + } + else { + emitCallback(node); + } + enterComment(); + if (!skipTrailingComments) { + emitLeadingComments(detachedRange.end, /*isEmittedNode*/ true); + if (hasWrittenComment && !writer.isAtStartOfLine()) { + writer.writeLine(); + } + } + exitComment(); + } + function emitLeadingComments(pos, isEmittedNode) { + hasWrittenComment = false; + if (isEmittedNode) { + forEachLeadingCommentToEmit(pos, emitLeadingComment); + } + else if (pos === 0) { + // If the node will not be emitted in JS, remove all the comments(normal, pinned and ///) associated with the node, + // unless it is a triple slash comment at the top of the file. + // For Example: + // /// + // declare var x; + // /// + // interface F {} + // The first /// will NOT be removed while the second one will be removed even though both node will not be emitted + forEachLeadingCommentToEmit(pos, emitTripleSlashLeadingComment); + } + } + function emitTripleSlashLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos) { + if (isTripleSlashComment(commentPos, commentEnd)) { + emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos); + } + } + function shouldWriteComment(text, pos) { + if (printerOptions.onlyPrintJsDocStyle) { + return (ts.isJSDocLikeText(text, pos) || ts.isPinnedComment(text, pos)); + } + return true; + } + function emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos) { + if (!shouldWriteComment(currentSourceFile.text, commentPos)) + return; + if (!hasWrittenComment) { + ts.emitNewLineBeforeLeadingCommentOfPosition(getCurrentLineMap(), writer, rangePos, commentPos); + hasWrittenComment = true; + } + // Leading comments are emitted at /*leading comment1 */space/*leading comment*/space + emitPos(commentPos); + ts.writeCommentRange(currentSourceFile.text, getCurrentLineMap(), writer, commentPos, commentEnd, newLine); + emitPos(commentEnd); + if (hasTrailingNewLine) { + writer.writeLine(); + } + else if (kind === 3 /* MultiLineCommentTrivia */) { + writer.writeSpace(" "); + } + } + function emitLeadingCommentsOfPosition(pos) { + if (commentsDisabled || pos === -1) { + return; + } + emitLeadingComments(pos, /*isEmittedNode*/ true); + } + function emitTrailingComments(pos) { + forEachTrailingCommentToEmit(pos, emitTrailingComment); + } + function emitTrailingComment(commentPos, commentEnd, _kind, hasTrailingNewLine) { + if (!shouldWriteComment(currentSourceFile.text, commentPos)) + return; + // trailing comments are emitted at space/*trailing comment1 */space/*trailing comment2*/ + if (!writer.isAtStartOfLine()) { + writer.writeSpace(" "); + } + emitPos(commentPos); + ts.writeCommentRange(currentSourceFile.text, getCurrentLineMap(), writer, commentPos, commentEnd, newLine); + emitPos(commentEnd); + if (hasTrailingNewLine) { + writer.writeLine(); + } + } + function emitTrailingCommentsOfPosition(pos, prefixSpace) { + if (commentsDisabled) { + return; + } + enterComment(); + forEachTrailingCommentToEmit(pos, prefixSpace ? emitTrailingComment : emitTrailingCommentOfPosition); + exitComment(); + } + function emitTrailingCommentOfPosition(commentPos, commentEnd, _kind, hasTrailingNewLine) { + // trailing comments of a position are emitted at /*trailing comment1 */space/*trailing comment*/space + emitPos(commentPos); + ts.writeCommentRange(currentSourceFile.text, getCurrentLineMap(), writer, commentPos, commentEnd, newLine); + emitPos(commentEnd); + if (hasTrailingNewLine) { + writer.writeLine(); + } + else { + writer.writeSpace(" "); + } + } + function forEachLeadingCommentToEmit(pos, cb) { + // Emit the leading comments only if the container's pos doesn't match because the container should take care of emitting these comments + if (currentSourceFile && (containerPos === -1 || pos !== containerPos)) { + if (hasDetachedComments(pos)) { + forEachLeadingCommentWithoutDetachedComments(cb); + } + else { + ts.forEachLeadingCommentRange(currentSourceFile.text, pos, cb, /*state*/ pos); + } + } + } + function forEachTrailingCommentToEmit(end, cb) { + // Emit the trailing comments only if the container's end doesn't match because the container should take care of emitting these comments + if (currentSourceFile && (containerEnd === -1 || (end !== containerEnd && end !== declarationListContainerEnd))) { + ts.forEachTrailingCommentRange(currentSourceFile.text, end, cb); + } + } + function hasDetachedComments(pos) { + return detachedCommentsInfo !== undefined && ts.last(detachedCommentsInfo).nodePos === pos; + } + function forEachLeadingCommentWithoutDetachedComments(cb) { + // get the leading comments from detachedPos + var pos = ts.last(detachedCommentsInfo).detachedCommentEndPos; + if (detachedCommentsInfo.length - 1) { + detachedCommentsInfo.pop(); + } + else { + detachedCommentsInfo = undefined; + } + ts.forEachLeadingCommentRange(currentSourceFile.text, pos, cb, /*state*/ pos); + } + function emitDetachedCommentsAndUpdateCommentsInfo(range) { + var currentDetachedCommentInfo = ts.emitDetachedComments(currentSourceFile.text, getCurrentLineMap(), writer, emitComment, range, newLine, commentsDisabled); + if (currentDetachedCommentInfo) { + if (detachedCommentsInfo) { + detachedCommentsInfo.push(currentDetachedCommentInfo); + } + else { + detachedCommentsInfo = [currentDetachedCommentInfo]; + } + } + } + function emitComment(text, lineMap, writer, commentPos, commentEnd, newLine) { + if (!shouldWriteComment(currentSourceFile.text, commentPos)) + return; + emitPos(commentPos); + ts.writeCommentRange(text, lineMap, writer, commentPos, commentEnd, newLine); + emitPos(commentEnd); + } + /** + * Determine if the given comment is a triple-slash + * + * @return true if the comment is a triple-slash comment else false + */ + function isTripleSlashComment(commentPos, commentEnd) { + return ts.isRecognizedTripleSlashComment(currentSourceFile.text, commentPos, commentEnd); + } + // Source Maps + function pipelineEmitWithSourceMap(hint, node) { + var pipelinePhase = getNextPipelinePhase(3 /* SourceMaps */, node); + if (ts.isUnparsedSource(node) && node.sourceMapText !== undefined) { + var parsed = ts.tryParseRawSourceMap(node.sourceMapText); + if (parsed) { + sourceMapGenerator.appendSourceMap(writer.getLine(), writer.getColumn(), parsed, node.sourceMapPath); + } + pipelinePhase(hint, node); + } + else { + var _a = ts.getSourceMapRange(node), pos = _a.pos, end = _a.end, _b = _a.source, source = _b === void 0 ? sourceMapSource : _b; + var emitFlags = ts.getEmitFlags(node); + if (node.kind !== 307 /* NotEmittedStatement */ + && (emitFlags & 16 /* NoLeadingSourceMap */) === 0 + && pos >= 0) { + emitSourcePos(source, skipSourceTrivia(source, pos)); + } + if (emitFlags & 64 /* NoNestedSourceMaps */) { + sourceMapsDisabled = true; + pipelinePhase(hint, node); + sourceMapsDisabled = false; + } + else { + pipelinePhase(hint, node); + } + if (node.kind !== 307 /* NotEmittedStatement */ + && (emitFlags & 32 /* NoTrailingSourceMap */) === 0 + && end >= 0) { + emitSourcePos(source, end); + } + } + } + /** + * Skips trivia such as comments and white-space that can optionally overriden by the source map source + */ + function skipSourceTrivia(source, pos) { + return source.skipTrivia ? source.skipTrivia(pos) : ts.skipTrivia(sourceMapSource.text, pos); + } + /** + * Emits a mapping. + * + * If the position is synthetic (undefined or a negative value), no mapping will be + * created. + * + * @param pos The position. + */ + function emitPos(pos) { + if (sourceMapsDisabled || ts.positionIsSynthesized(pos) || isJsonSourceMapSource(sourceMapSource)) { + return; + } + var _a = ts.getLineAndCharacterOfPosition(currentSourceFile, pos), sourceLine = _a.line, sourceCharacter = _a.character; + sourceMapGenerator.addMapping(writer.getLine(), writer.getColumn(), sourceMapSourceIndex, sourceLine, sourceCharacter, + /*nameIndex*/ undefined); + } + function emitSourcePos(source, pos) { + if (source !== sourceMapSource) { + var savedSourceMapSource = sourceMapSource; + setSourceMapSource(source); + emitPos(pos); + setSourceMapSource(savedSourceMapSource); + } + else { + emitPos(pos); + } + } + /** + * Emits a token of a node with possible leading and trailing source maps. + * + * @param node The node containing the token. + * @param token The token to emit. + * @param tokenStartPos The start pos of the token. + * @param emitCallback The callback used to emit the token. + */ + function emitTokenWithSourceMap(node, token, writer, tokenPos, emitCallback) { + if (sourceMapsDisabled || node && ts.isInJsonFile(node)) { + return emitCallback(token, writer, tokenPos); + } + var emitNode = node && node.emitNode; + var emitFlags = emitNode && emitNode.flags || 0 /* None */; + var range = emitNode && emitNode.tokenSourceMapRanges && emitNode.tokenSourceMapRanges[token]; + var source = range && range.source || sourceMapSource; + tokenPos = skipSourceTrivia(source, range ? range.pos : tokenPos); + if ((emitFlags & 128 /* NoTokenLeadingSourceMaps */) === 0 && tokenPos >= 0) { + emitSourcePos(source, tokenPos); + } + tokenPos = emitCallback(token, writer, tokenPos); + if (range) + tokenPos = range.end; + if ((emitFlags & 256 /* NoTokenTrailingSourceMaps */) === 0 && tokenPos >= 0) { + emitSourcePos(source, tokenPos); + } + return tokenPos; + } + function setSourceMapSource(source) { + if (sourceMapsDisabled) { + return; + } + sourceMapSource = source; + if (isJsonSourceMapSource(source)) { + return; + } + sourceMapSourceIndex = sourceMapGenerator.addSource(source.fileName); + if (printerOptions.inlineSources) { + sourceMapGenerator.setSourceContent(sourceMapSourceIndex, source.text); + } + } + function isJsonSourceMapSource(sourceFile) { + return ts.fileExtensionIs(sourceFile.fileName, ".json" /* Json */); + } + } + ts.createPrinter = createPrinter; + function createBracketsMap() { + var brackets = []; + brackets[1024 /* Braces */] = ["{", "}"]; + brackets[2048 /* Parenthesis */] = ["(", ")"]; + brackets[4096 /* AngleBrackets */] = ["<", ">"]; + brackets[8192 /* SquareBrackets */] = ["[", "]"]; + return brackets; + } + function getOpeningBracket(format) { + return brackets[format & 15360 /* BracketsMask */][0]; + } + function getClosingBracket(format) { + return brackets[format & 15360 /* BracketsMask */][1]; + } + // Flags enum to track count of temp variables and a few dedicated names + var TempFlags; + (function (TempFlags) { + TempFlags[TempFlags["Auto"] = 0] = "Auto"; + TempFlags[TempFlags["CountMask"] = 268435455] = "CountMask"; + TempFlags[TempFlags["_i"] = 268435456] = "_i"; + })(TempFlags || (TempFlags = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + function createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensitiveFileNames) { + if (!host.getDirectories || !host.readDirectory) { + return undefined; + } + var cachedReadDirectoryResult = ts.createMap(); + var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); + return { + useCaseSensitiveFileNames: useCaseSensitiveFileNames, + fileExists: fileExists, + readFile: function (path, encoding) { return host.readFile(path, encoding); }, + directoryExists: host.directoryExists && directoryExists, + getDirectories: getDirectories, + readDirectory: readDirectory, + createDirectory: host.createDirectory && createDirectory, + writeFile: host.writeFile && writeFile, + addOrDeleteFileOrDirectory: addOrDeleteFileOrDirectory, + addOrDeleteFile: addOrDeleteFile, + clearCache: clearCache + }; + function toPath(fileName) { + return ts.toPath(fileName, currentDirectory, getCanonicalFileName); + } + function getCachedFileSystemEntries(rootDirPath) { + return cachedReadDirectoryResult.get(ts.ensureTrailingDirectorySeparator(rootDirPath)); + } + function getCachedFileSystemEntriesForBaseDir(path) { + return getCachedFileSystemEntries(ts.getDirectoryPath(path)); + } + function getBaseNameOfFileName(fileName) { + return ts.getBaseFileName(ts.normalizePath(fileName)); + } + function createCachedFileSystemEntries(rootDir, rootDirPath) { + var resultFromHost = { + files: ts.map(host.readDirectory(rootDir, /*extensions*/ undefined, /*exclude*/ undefined, /*include*/ ["*.*"]), getBaseNameOfFileName) || [], + directories: host.getDirectories(rootDir) || [] + }; + cachedReadDirectoryResult.set(ts.ensureTrailingDirectorySeparator(rootDirPath), resultFromHost); + return resultFromHost; + } + /** + * If the readDirectory result was already cached, it returns that + * Otherwise gets result from host and caches it. + * The host request is done under try catch block to avoid caching incorrect result + */ + function tryReadDirectory(rootDir, rootDirPath) { + rootDirPath = ts.ensureTrailingDirectorySeparator(rootDirPath); + var cachedResult = getCachedFileSystemEntries(rootDirPath); + if (cachedResult) { + return cachedResult; + } + try { + return createCachedFileSystemEntries(rootDir, rootDirPath); + } + catch (_e) { + // If there is exception to read directories, dont cache the result and direct the calls to host + ts.Debug.assert(!cachedReadDirectoryResult.has(ts.ensureTrailingDirectorySeparator(rootDirPath))); + return undefined; + } + } + function fileNameEqual(name1, name2) { + return getCanonicalFileName(name1) === getCanonicalFileName(name2); + } + function hasEntry(entries, name) { + return ts.some(entries, function (file) { return fileNameEqual(file, name); }); + } + function updateFileSystemEntry(entries, baseName, isValid) { + if (hasEntry(entries, baseName)) { + if (!isValid) { + return ts.filterMutate(entries, function (entry) { return !fileNameEqual(entry, baseName); }); + } + } + else if (isValid) { + return entries.push(baseName); + } + } + function writeFile(fileName, data, writeByteOrderMark) { + var path = toPath(fileName); + var result = getCachedFileSystemEntriesForBaseDir(path); + if (result) { + updateFilesOfFileSystemEntry(result, getBaseNameOfFileName(fileName), /*fileExists*/ true); + } + return host.writeFile(fileName, data, writeByteOrderMark); + } + function fileExists(fileName) { + var path = toPath(fileName); + var result = getCachedFileSystemEntriesForBaseDir(path); + return result && hasEntry(result.files, getBaseNameOfFileName(fileName)) || + host.fileExists(fileName); + } + function directoryExists(dirPath) { + var path = toPath(dirPath); + return cachedReadDirectoryResult.has(ts.ensureTrailingDirectorySeparator(path)) || host.directoryExists(dirPath); + } + function createDirectory(dirPath) { + var path = toPath(dirPath); + var result = getCachedFileSystemEntriesForBaseDir(path); + var baseFileName = getBaseNameOfFileName(dirPath); + if (result) { + updateFileSystemEntry(result.directories, baseFileName, /*isValid*/ true); + } + host.createDirectory(dirPath); + } + function getDirectories(rootDir) { + var rootDirPath = toPath(rootDir); + var result = tryReadDirectory(rootDir, rootDirPath); + if (result) { + return result.directories.slice(); + } + return host.getDirectories(rootDir); + } + function readDirectory(rootDir, extensions, excludes, includes, depth) { + var rootDirPath = toPath(rootDir); + var result = tryReadDirectory(rootDir, rootDirPath); + if (result) { + return ts.matchFiles(rootDir, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries); + } + return host.readDirectory(rootDir, extensions, excludes, includes, depth); + function getFileSystemEntries(dir) { + var path = toPath(dir); + if (path === rootDirPath) { + return result; + } + return tryReadDirectory(dir, path) || ts.emptyFileSystemEntries; + } + } + function addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath) { + var existingResult = getCachedFileSystemEntries(fileOrDirectoryPath); + if (existingResult) { + // Just clear the cache for now + // For now just clear the cache, since this could mean that multiple level entries might need to be re-evaluated + clearCache(); + return undefined; + } + var parentResult = getCachedFileSystemEntriesForBaseDir(fileOrDirectoryPath); + if (!parentResult) { + return undefined; + } + // This was earlier a file (hence not in cached directory contents) + // or we never cached the directory containing it + if (!host.directoryExists) { + // Since host doesnt support directory exists, clear the cache as otherwise it might not be same + clearCache(); + return undefined; + } + var baseName = getBaseNameOfFileName(fileOrDirectory); + var fsQueryResult = { + fileExists: host.fileExists(fileOrDirectoryPath), + directoryExists: host.directoryExists(fileOrDirectoryPath) + }; + if (fsQueryResult.directoryExists || hasEntry(parentResult.directories, baseName)) { + // Folder added or removed, clear the cache instead of updating the folder and its structure + clearCache(); + } + else { + // No need to update the directory structure, just files + updateFilesOfFileSystemEntry(parentResult, baseName, fsQueryResult.fileExists); + } + return fsQueryResult; + } + function addOrDeleteFile(fileName, filePath, eventKind) { + if (eventKind === ts.FileWatcherEventKind.Changed) { + return; + } + var parentResult = getCachedFileSystemEntriesForBaseDir(filePath); + if (parentResult) { + updateFilesOfFileSystemEntry(parentResult, getBaseNameOfFileName(fileName), eventKind === ts.FileWatcherEventKind.Created); + } + } + function updateFilesOfFileSystemEntry(parentResult, baseName, fileExists) { + updateFileSystemEntry(parentResult.files, baseName, fileExists); + } + function clearCache() { + cachedReadDirectoryResult.clear(); + } + } + ts.createCachedDirectoryStructureHost = createCachedDirectoryStructureHost; + var ConfigFileProgramReloadLevel; + (function (ConfigFileProgramReloadLevel) { + ConfigFileProgramReloadLevel[ConfigFileProgramReloadLevel["None"] = 0] = "None"; + /** Update the file name list from the disk */ + ConfigFileProgramReloadLevel[ConfigFileProgramReloadLevel["Partial"] = 1] = "Partial"; + /** Reload completely by re-reading contents of config file from disk and updating program */ + ConfigFileProgramReloadLevel[ConfigFileProgramReloadLevel["Full"] = 2] = "Full"; + })(ConfigFileProgramReloadLevel = ts.ConfigFileProgramReloadLevel || (ts.ConfigFileProgramReloadLevel = {})); + /** + * Updates the existing missing file watches with the new set of missing files after new program is created + */ + function updateMissingFilePathsWatch(program, missingFileWatches, createMissingFileWatch) { + var missingFilePaths = program.getMissingFilePaths(); + var newMissingFilePathMap = ts.arrayToSet(missingFilePaths); + // Update the missing file paths watcher + ts.mutateMap(missingFileWatches, newMissingFilePathMap, { + // Watch the missing files + createNewValue: createMissingFileWatch, + // Files that are no longer missing (e.g. because they are no longer required) + // should no longer be watched. + onDeleteValue: ts.closeFileWatcher + }); + } + ts.updateMissingFilePathsWatch = updateMissingFilePathsWatch; + /** + * Updates the existing wild card directory watches with the new set of wild card directories from the config file + * after new program is created because the config file was reloaded or program was created first time from the config file + * Note that there is no need to call this function when the program is updated with additional files without reloading config files, + * as wildcard directories wont change unless reloading config file + */ + function updateWatchingWildcardDirectories(existingWatchedForWildcards, wildcardDirectories, watchDirectory) { + ts.mutateMap(existingWatchedForWildcards, wildcardDirectories, { + // Create new watch and recursive info + createNewValue: createWildcardDirectoryWatcher, + // Close existing watch thats not needed any more + onDeleteValue: closeFileWatcherOf, + // Close existing watch that doesnt match in the flags + onExistingValue: updateWildcardDirectoryWatcher + }); + function createWildcardDirectoryWatcher(directory, flags) { + // Create new watch and recursive info + return { + watcher: watchDirectory(directory, flags), + flags: flags + }; + } + function updateWildcardDirectoryWatcher(existingWatcher, flags, directory) { + // Watcher needs to be updated if the recursive flags dont match + if (existingWatcher.flags === flags) { + return; + } + existingWatcher.watcher.close(); + existingWatchedForWildcards.set(directory, createWildcardDirectoryWatcher(directory, flags)); + } + } + ts.updateWatchingWildcardDirectories = updateWatchingWildcardDirectories; + function isEmittedFileOfProgram(program, file) { + if (!program) { + return false; + } + return program.isEmittedFile(file); + } + ts.isEmittedFileOfProgram = isEmittedFileOfProgram; + var WatchLogLevel; + (function (WatchLogLevel) { + WatchLogLevel[WatchLogLevel["None"] = 0] = "None"; + WatchLogLevel[WatchLogLevel["TriggerOnly"] = 1] = "TriggerOnly"; + WatchLogLevel[WatchLogLevel["Verbose"] = 2] = "Verbose"; + })(WatchLogLevel = ts.WatchLogLevel || (ts.WatchLogLevel = {})); + function getWatchFactory(watchLogLevel, log, getDetailWatchInfo) { + return getWatchFactoryWith(watchLogLevel, log, getDetailWatchInfo, watchFile, watchDirectory); + } + ts.getWatchFactory = getWatchFactory; + function getWatchFactoryWith(watchLogLevel, log, getDetailWatchInfo, watchFile, watchDirectory) { + var createFileWatcher = getCreateFileWatcher(watchLogLevel, watchFile); + var createFilePathWatcher = watchLogLevel === WatchLogLevel.None ? watchFilePath : createFileWatcher; + var createDirectoryWatcher = getCreateFileWatcher(watchLogLevel, watchDirectory); + return { + watchFile: function (host, file, callback, pollingInterval, detailInfo1, detailInfo2) { + return createFileWatcher(host, file, callback, pollingInterval, /*passThrough*/ undefined, detailInfo1, detailInfo2, watchFile, log, "FileWatcher", getDetailWatchInfo); + }, + watchFilePath: function (host, file, callback, pollingInterval, path, detailInfo1, detailInfo2) { + return createFilePathWatcher(host, file, callback, pollingInterval, path, detailInfo1, detailInfo2, watchFile, log, "FileWatcher", getDetailWatchInfo); + }, + watchDirectory: function (host, directory, callback, flags, detailInfo1, detailInfo2) { + return createDirectoryWatcher(host, directory, callback, flags, /*passThrough*/ undefined, detailInfo1, detailInfo2, watchDirectory, log, "DirectoryWatcher", getDetailWatchInfo); + } + }; + function watchFilePath(host, file, callback, pollingInterval, path) { + return watchFile(host, file, function (fileName, eventKind) { return callback(fileName, eventKind, path); }, pollingInterval); + } + } + function watchFile(host, file, callback, pollingInterval) { + return host.watchFile(file, callback, pollingInterval); + } + function watchDirectory(host, directory, callback, flags) { + return host.watchDirectory(directory, callback, (flags & 1 /* Recursive */) !== 0); + } + function getCreateFileWatcher(watchLogLevel, addWatch) { + switch (watchLogLevel) { + case WatchLogLevel.None: + return addWatch; + case WatchLogLevel.TriggerOnly: + return createFileWatcherWithTriggerLogging; + case WatchLogLevel.Verbose: + return addWatch === watchDirectory ? createDirectoryWatcherWithLogging : createFileWatcherWithLogging; + } + } + function createFileWatcherWithLogging(host, file, cb, flags, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo) { + log(watchCaption + ":: Added:: " + getWatchInfo(file, flags, detailInfo1, detailInfo2, getDetailWatchInfo)); + var watcher = createFileWatcherWithTriggerLogging(host, file, cb, flags, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo); + return { + close: function () { + log(watchCaption + ":: Close:: " + getWatchInfo(file, flags, detailInfo1, detailInfo2, getDetailWatchInfo)); + watcher.close(); + } + }; + } + function createDirectoryWatcherWithLogging(host, file, cb, flags, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo) { + var watchInfo = watchCaption + ":: Added:: " + getWatchInfo(file, flags, detailInfo1, detailInfo2, getDetailWatchInfo); + log(watchInfo); + var start = ts.timestamp(); + var watcher = createFileWatcherWithTriggerLogging(host, file, cb, flags, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo); + var elapsed = ts.timestamp() - start; + log("Elapsed:: " + elapsed + "ms " + watchInfo); + return { + close: function () { + var watchInfo = watchCaption + ":: Close:: " + getWatchInfo(file, flags, detailInfo1, detailInfo2, getDetailWatchInfo); + log(watchInfo); + var start = ts.timestamp(); + watcher.close(); + var elapsed = ts.timestamp() - start; + log("Elapsed:: " + elapsed + "ms " + watchInfo); + } + }; + } + function createFileWatcherWithTriggerLogging(host, file, cb, flags, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo) { + return addWatch(host, file, function (fileName, cbOptional) { + var triggerredInfo = watchCaption + ":: Triggered with " + fileName + " " + (cbOptional !== undefined ? cbOptional : "") + ":: " + getWatchInfo(file, flags, detailInfo1, detailInfo2, getDetailWatchInfo); + log(triggerredInfo); + var start = ts.timestamp(); + cb(fileName, cbOptional, passThrough); + var elapsed = ts.timestamp() - start; + log("Elapsed:: " + elapsed + "ms " + triggerredInfo); + }, flags); + } + function getWatchInfo(file, flags, detailInfo1, detailInfo2, getDetailWatchInfo) { + return "WatchInfo: " + file + " " + flags + " " + (getDetailWatchInfo ? getDetailWatchInfo(detailInfo1, detailInfo2) : detailInfo1); + } + function closeFileWatcherOf(objWithWatcher) { + objWithWatcher.watcher.close(); + } + ts.closeFileWatcherOf = closeFileWatcherOf; +})(ts || (ts = {})); +var ts; +(function (ts) { + var ignoreDiagnosticCommentRegEx = /(^\s*$)|(^\s*\/\/\/?\s*(@ts-ignore)?)/; + function findConfigFile(searchPath, fileExists, configName) { + if (configName === void 0) { configName = "tsconfig.json"; } + return ts.forEachAncestorDirectory(searchPath, function (ancestor) { + var fileName = ts.combinePaths(ancestor, configName); + return fileExists(fileName) ? fileName : undefined; + }); + } + ts.findConfigFile = findConfigFile; + function resolveTripleslashReference(moduleName, containingFile) { + var basePath = ts.getDirectoryPath(containingFile); + var referencedFileName = ts.isRootedDiskPath(moduleName) ? moduleName : ts.combinePaths(basePath, moduleName); + return ts.normalizePath(referencedFileName); + } + ts.resolveTripleslashReference = resolveTripleslashReference; + /* @internal */ + function computeCommonSourceDirectoryOfFilenames(fileNames, currentDirectory, getCanonicalFileName) { + var commonPathComponents; + var failed = ts.forEach(fileNames, function (sourceFile) { + // Each file contributes into common source file path + var sourcePathComponents = ts.getNormalizedPathComponents(sourceFile, currentDirectory); + sourcePathComponents.pop(); // The base file name is not part of the common directory path + if (!commonPathComponents) { + // first file + commonPathComponents = sourcePathComponents; + return; + } + var n = Math.min(commonPathComponents.length, sourcePathComponents.length); + for (var i = 0; i < n; i++) { + if (getCanonicalFileName(commonPathComponents[i]) !== getCanonicalFileName(sourcePathComponents[i])) { + if (i === 0) { + // Failed to find any common path component + return true; + } + // New common path found that is 0 -> i-1 + commonPathComponents.length = i; + break; + } + } + // If the sourcePathComponents was shorter than the commonPathComponents, truncate to the sourcePathComponents + if (sourcePathComponents.length < commonPathComponents.length) { + commonPathComponents.length = sourcePathComponents.length; + } + }); + // A common path can not be found when paths span multiple drives on windows, for example + if (failed) { + return ""; + } + if (!commonPathComponents) { // Can happen when all input files are .d.ts files + return currentDirectory; + } + return ts.getPathFromPathComponents(commonPathComponents); + } + ts.computeCommonSourceDirectoryOfFilenames = computeCommonSourceDirectoryOfFilenames; + function createCompilerHost(options, setParentNodes) { + return createCompilerHostWorker(options, setParentNodes); + } + ts.createCompilerHost = createCompilerHost; + /*@internal*/ + // TODO(shkamat): update this after reworking ts build API + function createCompilerHostWorker(options, setParentNodes, system) { + if (system === void 0) { system = ts.sys; } + var existingDirectories = ts.createMap(); + function getCanonicalFileName(fileName) { + // if underlying system can distinguish between two files whose names differs only in cases then file name already in canonical form. + // otherwise use toLowerCase as a canonical form. + return system.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); + } + function getSourceFile(fileName, languageVersion, onError) { + var text; + try { + ts.performance.mark("beforeIORead"); + text = compilerHost.readFile(fileName); + ts.performance.mark("afterIORead"); + ts.performance.measure("I/O Read", "beforeIORead", "afterIORead"); + } + catch (e) { + if (onError) { + onError(e.message); + } + text = ""; + } + return text !== undefined ? ts.createSourceFile(fileName, text, languageVersion, setParentNodes) : undefined; + } + function directoryExists(directoryPath) { + if (existingDirectories.has(directoryPath)) { + return true; + } + if (system.directoryExists(directoryPath)) { + existingDirectories.set(directoryPath, true); + return true; + } + return false; + } + function ensureDirectoriesExist(directoryPath) { + if (directoryPath.length > ts.getRootLength(directoryPath) && !directoryExists(directoryPath)) { + var parentDirectory = ts.getDirectoryPath(directoryPath); + ensureDirectoriesExist(parentDirectory); + if (compilerHost.createDirectory) { + compilerHost.createDirectory(directoryPath); + } + else { + system.createDirectory(directoryPath); + } + } + } + var outputFingerprints; + function writeFileIfUpdated(fileName, data, writeByteOrderMark) { + if (!outputFingerprints) { + outputFingerprints = ts.createMap(); + } + var hash = system.createHash(data); // TODO: GH#18217 + var mtimeBefore = system.getModifiedTime(fileName); // TODO: GH#18217 + if (mtimeBefore) { + var fingerprint = outputFingerprints.get(fileName); + // If output has not been changed, and the file has no external modification + if (fingerprint && + fingerprint.byteOrderMark === writeByteOrderMark && + fingerprint.hash === hash && + fingerprint.mtime.getTime() === mtimeBefore.getTime()) { + return; + } + } + system.writeFile(fileName, data, writeByteOrderMark); + var mtimeAfter = system.getModifiedTime(fileName) || ts.missingFileModifiedTime; // TODO: GH#18217 + outputFingerprints.set(fileName, { + hash: hash, + byteOrderMark: writeByteOrderMark, + mtime: mtimeAfter + }); + } + function writeFile(fileName, data, writeByteOrderMark, onError) { + try { + ts.performance.mark("beforeIOWrite"); + ensureDirectoriesExist(ts.getDirectoryPath(ts.normalizePath(fileName))); + if (ts.isWatchSet(options) && system.createHash && system.getModifiedTime) { + writeFileIfUpdated(fileName, data, writeByteOrderMark); + } + else { + system.writeFile(fileName, data, writeByteOrderMark); + } + ts.performance.mark("afterIOWrite"); + ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite"); + } + catch (e) { + if (onError) { + onError(e.message); + } + } + } + function getDefaultLibLocation() { + return ts.getDirectoryPath(ts.normalizePath(system.getExecutingFilePath())); + } + var newLine = ts.getNewLineCharacter(options, function () { return system.newLine; }); + var realpath = system.realpath && (function (path) { return system.realpath(path); }); + var compilerHost = { + getSourceFile: getSourceFile, + getDefaultLibLocation: getDefaultLibLocation, + getDefaultLibFileName: function (options) { return ts.combinePaths(getDefaultLibLocation(), ts.getDefaultLibFileName(options)); }, + writeFile: writeFile, + getCurrentDirectory: ts.memoize(function () { return system.getCurrentDirectory(); }), + useCaseSensitiveFileNames: function () { return system.useCaseSensitiveFileNames; }, + getCanonicalFileName: getCanonicalFileName, + getNewLine: function () { return newLine; }, + fileExists: function (fileName) { return system.fileExists(fileName); }, + readFile: function (fileName) { return system.readFile(fileName); }, + trace: function (s) { return system.write(s + newLine); }, + directoryExists: function (directoryName) { return system.directoryExists(directoryName); }, + getEnvironmentVariable: function (name) { return system.getEnvironmentVariable ? system.getEnvironmentVariable(name) : ""; }, + getDirectories: function (path) { return system.getDirectories(path); }, + realpath: realpath, + readDirectory: function (path, extensions, include, exclude, depth) { return system.readDirectory(path, extensions, include, exclude, depth); }, + createDirectory: function (d) { return system.createDirectory(d); } + }; + return compilerHost; + } + ts.createCompilerHostWorker = createCompilerHostWorker; + /*@internal*/ + function changeCompilerHostToUseCache(host, toPath, useCacheForSourceFile) { + var originalReadFile = host.readFile; + var originalFileExists = host.fileExists; + var originalDirectoryExists = host.directoryExists; + var originalCreateDirectory = host.createDirectory; + var originalWriteFile = host.writeFile; + var originalGetSourceFile = host.getSourceFile; + var readFileCache = ts.createMap(); + var fileExistsCache = ts.createMap(); + var directoryExistsCache = ts.createMap(); + var sourceFileCache = ts.createMap(); + var readFileWithCache = function (fileName) { + var key = toPath(fileName); + var value = readFileCache.get(key); + if (value !== undefined) + return value || undefined; + return setReadFileCache(key, fileName); + }; + var setReadFileCache = function (key, fileName) { + var newValue = originalReadFile.call(host, fileName); + readFileCache.set(key, newValue || false); + return newValue; + }; + host.readFile = function (fileName) { + var key = toPath(fileName); + var value = readFileCache.get(key); + if (value !== undefined) + return value; // could be .d.ts from output + if (!ts.fileExtensionIs(fileName, ".json" /* Json */)) { + return originalReadFile.call(host, fileName); + } + return setReadFileCache(key, fileName); + }; + if (useCacheForSourceFile) { + host.getSourceFile = function (fileName, languageVersion, onError, shouldCreateNewSourceFile) { + var key = toPath(fileName); + var value = sourceFileCache.get(key); + if (value) + return value; + var sourceFile = originalGetSourceFile.call(host, fileName, languageVersion, onError, shouldCreateNewSourceFile); + if (sourceFile && (ts.isDeclarationFileName(fileName) || ts.fileExtensionIs(fileName, ".json" /* Json */))) { + sourceFileCache.set(key, sourceFile); + } + return sourceFile; + }; + } + // fileExists for any kind of extension + host.fileExists = function (fileName) { + var key = toPath(fileName); + var value = fileExistsCache.get(key); + if (value !== undefined) + return value; + var newValue = originalFileExists.call(host, fileName); + fileExistsCache.set(key, !!newValue); + return newValue; + }; + host.writeFile = function (fileName, data, writeByteOrderMark, onError, sourceFiles) { + var key = toPath(fileName); + fileExistsCache.delete(key); + var value = readFileCache.get(key); + if (value && value !== data) { + readFileCache.delete(key); + sourceFileCache.delete(key); + } + else if (useCacheForSourceFile) { + var sourceFile = sourceFileCache.get(key); + if (sourceFile && sourceFile.text !== data) { + sourceFileCache.delete(key); + } + } + originalWriteFile.call(host, fileName, data, writeByteOrderMark, onError, sourceFiles); + }; + // directoryExists + if (originalDirectoryExists && originalCreateDirectory) { + host.directoryExists = function (directory) { + var key = toPath(directory); + var value = directoryExistsCache.get(key); + if (value !== undefined) + return value; + var newValue = originalDirectoryExists.call(host, directory); + directoryExistsCache.set(key, !!newValue); + return newValue; + }; + host.createDirectory = function (directory) { + var key = toPath(directory); + directoryExistsCache.delete(key); + originalCreateDirectory.call(host, directory); + }; + } + return { + originalReadFile: originalReadFile, + originalFileExists: originalFileExists, + originalDirectoryExists: originalDirectoryExists, + originalCreateDirectory: originalCreateDirectory, + originalWriteFile: originalWriteFile, + originalGetSourceFile: originalGetSourceFile, + readFileWithCache: readFileWithCache + }; + } + ts.changeCompilerHostToUseCache = changeCompilerHostToUseCache; + function getPreEmitDiagnostics(program, sourceFile, cancellationToken) { + var diagnostics = program.getConfigFileParsingDiagnostics().concat(program.getOptionsDiagnostics(cancellationToken), program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken)); + if (ts.getEmitDeclarations(program.getCompilerOptions())) { + ts.addRange(diagnostics, program.getDeclarationDiagnostics(sourceFile, cancellationToken)); + } + return ts.sortAndDeduplicateDiagnostics(diagnostics); + } + ts.getPreEmitDiagnostics = getPreEmitDiagnostics; + function formatDiagnostics(diagnostics, host) { + var output = ""; + for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { + var diagnostic = diagnostics_2[_i]; + output += formatDiagnostic(diagnostic, host); + } + return output; + } + ts.formatDiagnostics = formatDiagnostics; + function formatDiagnostic(diagnostic, host) { + var errorMessage = ts.diagnosticCategoryName(diagnostic) + " TS" + diagnostic.code + ": " + flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine()) + host.getNewLine(); + if (diagnostic.file) { + var _a = ts.getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start), line = _a.line, character = _a.character; // TODO: GH#18217 + var fileName = diagnostic.file.fileName; + var relativeFileName = ts.convertToRelativePath(fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); }); + return relativeFileName + "(" + (line + 1) + "," + (character + 1) + "): " + errorMessage; + } + return errorMessage; + } + ts.formatDiagnostic = formatDiagnostic; + /** @internal */ + var ForegroundColorEscapeSequences; + (function (ForegroundColorEscapeSequences) { + ForegroundColorEscapeSequences["Grey"] = "\u001B[90m"; + ForegroundColorEscapeSequences["Red"] = "\u001B[91m"; + ForegroundColorEscapeSequences["Yellow"] = "\u001B[93m"; + ForegroundColorEscapeSequences["Blue"] = "\u001B[94m"; + ForegroundColorEscapeSequences["Cyan"] = "\u001B[96m"; + })(ForegroundColorEscapeSequences = ts.ForegroundColorEscapeSequences || (ts.ForegroundColorEscapeSequences = {})); + var gutterStyleSequence = "\u001b[7m"; + var gutterSeparator = " "; + var resetEscapeSequence = "\u001b[0m"; + var ellipsis = "..."; + var halfIndent = " "; + var indent = " "; + function getCategoryFormat(category) { + switch (category) { + case ts.DiagnosticCategory.Error: return ForegroundColorEscapeSequences.Red; + case ts.DiagnosticCategory.Warning: return ForegroundColorEscapeSequences.Yellow; + case ts.DiagnosticCategory.Suggestion: return ts.Debug.fail("Should never get an Info diagnostic on the command line."); + case ts.DiagnosticCategory.Message: return ForegroundColorEscapeSequences.Blue; + } + } + /** @internal */ + function formatColorAndReset(text, formatStyle) { + return formatStyle + text + resetEscapeSequence; + } + ts.formatColorAndReset = formatColorAndReset; + function padLeft(s, length) { + while (s.length < length) { + s = " " + s; + } + return s; + } + function formatCodeSpan(file, start, length, indent, squiggleColor, host) { + var _a = ts.getLineAndCharacterOfPosition(file, start), firstLine = _a.line, firstLineChar = _a.character; + var _b = ts.getLineAndCharacterOfPosition(file, start + length), lastLine = _b.line, lastLineChar = _b.character; + var lastLineInFile = ts.getLineAndCharacterOfPosition(file, file.text.length).line; + var hasMoreThanFiveLines = (lastLine - firstLine) >= 4; + var gutterWidth = (lastLine + 1 + "").length; + if (hasMoreThanFiveLines) { + gutterWidth = Math.max(ellipsis.length, gutterWidth); + } + var context = ""; + for (var i = firstLine; i <= lastLine; i++) { + context += host.getNewLine(); + // If the error spans over 5 lines, we'll only show the first 2 and last 2 lines, + // so we'll skip ahead to the second-to-last line. + if (hasMoreThanFiveLines && firstLine + 1 < i && i < lastLine - 1) { + context += indent + formatColorAndReset(padLeft(ellipsis, gutterWidth), gutterStyleSequence) + gutterSeparator + host.getNewLine(); + i = lastLine - 1; + } + var lineStart = ts.getPositionOfLineAndCharacter(file, i, 0); + var lineEnd = i < lastLineInFile ? ts.getPositionOfLineAndCharacter(file, i + 1, 0) : file.text.length; + var lineContent = file.text.slice(lineStart, lineEnd); + lineContent = lineContent.replace(/\s+$/g, ""); // trim from end + lineContent = lineContent.replace("\t", " "); // convert tabs to single spaces + // Output the gutter and the actual contents of the line. + context += indent + formatColorAndReset(padLeft(i + 1 + "", gutterWidth), gutterStyleSequence) + gutterSeparator; + context += lineContent + host.getNewLine(); + // Output the gutter and the error span for the line using tildes. + context += indent + formatColorAndReset(padLeft("", gutterWidth), gutterStyleSequence) + gutterSeparator; + context += squiggleColor; + if (i === firstLine) { + // If we're on the last line, then limit it to the last character of the last line. + // Otherwise, we'll just squiggle the rest of the line, giving 'slice' no end position. + var lastCharForLine = i === lastLine ? lastLineChar : undefined; + context += lineContent.slice(0, firstLineChar).replace(/\S/g, " "); + context += lineContent.slice(firstLineChar, lastCharForLine).replace(/./g, "~"); + } + else if (i === lastLine) { + context += lineContent.slice(0, lastLineChar).replace(/./g, "~"); + } + else { + // Squiggle the entire line. + context += lineContent.replace(/./g, "~"); + } + context += resetEscapeSequence; + } + return context; + } + /* @internal */ + function formatLocation(file, start, host, color) { + if (color === void 0) { color = formatColorAndReset; } + var _a = ts.getLineAndCharacterOfPosition(file, start), firstLine = _a.line, firstLineChar = _a.character; // TODO: GH#18217 + var relativeFileName = host ? ts.convertToRelativePath(file.fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); }) : file.fileName; + var output = ""; + output += color(relativeFileName, ForegroundColorEscapeSequences.Cyan); + output += ":"; + output += color("" + (firstLine + 1), ForegroundColorEscapeSequences.Yellow); + output += ":"; + output += color("" + (firstLineChar + 1), ForegroundColorEscapeSequences.Yellow); + return output; + } + ts.formatLocation = formatLocation; + function formatDiagnosticsWithColorAndContext(diagnostics, host) { + var output = ""; + for (var _i = 0, diagnostics_3 = diagnostics; _i < diagnostics_3.length; _i++) { + var diagnostic = diagnostics_3[_i]; + if (diagnostic.file) { + var file = diagnostic.file, start = diagnostic.start; + output += formatLocation(file, start, host); // TODO: GH#18217 + output += " - "; + } + output += formatColorAndReset(ts.diagnosticCategoryName(diagnostic), getCategoryFormat(diagnostic.category)); + output += formatColorAndReset(" TS" + diagnostic.code + ": ", ForegroundColorEscapeSequences.Grey); + output += flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine()); + if (diagnostic.file) { + output += host.getNewLine(); + output += formatCodeSpan(diagnostic.file, diagnostic.start, diagnostic.length, "", getCategoryFormat(diagnostic.category), host); // TODO: GH#18217 + if (diagnostic.relatedInformation) { + output += host.getNewLine(); + for (var _a = 0, _b = diagnostic.relatedInformation; _a < _b.length; _a++) { + var _c = _b[_a], file = _c.file, start = _c.start, length_4 = _c.length, messageText = _c.messageText; + if (file) { + output += host.getNewLine(); + output += halfIndent + formatLocation(file, start, host); // TODO: GH#18217 + output += formatCodeSpan(file, start, length_4, indent, ForegroundColorEscapeSequences.Cyan, host); // TODO: GH#18217 + } + output += host.getNewLine(); + output += indent + flattenDiagnosticMessageText(messageText, host.getNewLine()); + } + } + } + output += host.getNewLine(); + } + return output; + } + ts.formatDiagnosticsWithColorAndContext = formatDiagnosticsWithColorAndContext; + function flattenDiagnosticMessageText(messageText, newLine) { + if (ts.isString(messageText)) { + return messageText; + } + else { + var diagnosticChain = messageText; + var result = ""; + var indent_1 = 0; + while (diagnosticChain) { + if (indent_1) { + result += newLine; + for (var i = 0; i < indent_1; i++) { + result += " "; + } + } + result += diagnosticChain.messageText; + indent_1++; + diagnosticChain = diagnosticChain.next; + } + return result; + } + } + ts.flattenDiagnosticMessageText = flattenDiagnosticMessageText; + function loadWithLocalCache(names, containingFile, redirectedReference, loader) { + if (names.length === 0) { + return []; + } + var resolutions = []; + var cache = ts.createMap(); + for (var _i = 0, names_1 = names; _i < names_1.length; _i++) { + var name = names_1[_i]; + var result = void 0; + if (cache.has(name)) { + result = cache.get(name); + } + else { + cache.set(name, result = loader(name, containingFile, redirectedReference)); + } + resolutions.push(result); + } + return resolutions; + } + /** + * Determines if program structure is upto date or needs to be recreated + */ + /* @internal */ + function isProgramUptoDate(program, rootFileNames, newOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, projectReferences) { + // If we haven't created a program yet or have changed automatic type directives, then it is not up-to-date + if (!program || hasChangedAutomaticTypeDirectiveNames) { + return false; + } + // If number of files in the program do not match, it is not up-to-date + if (program.getRootFileNames().length !== rootFileNames.length) { + return false; + } + var seenResolvedRefs; + // If project references dont match + if (!ts.arrayIsEqualTo(program.getProjectReferences(), projectReferences, projectReferenceUptoDate)) { + return false; + } + // If any file is not up-to-date, then the whole program is not up-to-date + if (program.getSourceFiles().some(sourceFileNotUptoDate)) { + return false; + } + // If any of the missing file paths are now created + if (program.getMissingFilePaths().some(fileExists)) { + return false; + } + var currentOptions = program.getCompilerOptions(); + // If the compilation settings do no match, then the program is not up-to-date + if (!ts.compareDataObjects(currentOptions, newOptions)) { + return false; + } + // If everything matches but the text of config file is changed, + // error locations can change for program options, so update the program + if (currentOptions.configFile && newOptions.configFile) { + return currentOptions.configFile.text === newOptions.configFile.text; + } + return true; + function sourceFileNotUptoDate(sourceFile) { + return !sourceFileVersionUptoDate(sourceFile) || + hasInvalidatedResolution(sourceFile.path); + } + function sourceFileVersionUptoDate(sourceFile) { + return sourceFile.version === getSourceVersion(sourceFile.resolvedPath); + } + function projectReferenceUptoDate(oldRef, newRef, index) { + if (!ts.projectReferenceIsEqualTo(oldRef, newRef)) { + return false; + } + return resolvedProjectReferenceUptoDate(program.getResolvedProjectReferences()[index], oldRef); + } + function resolvedProjectReferenceUptoDate(oldResolvedRef, oldRef) { + if (oldResolvedRef) { + if (ts.contains(seenResolvedRefs, oldResolvedRef)) { + // Assume true + return true; + } + // If sourceFile for the oldResolvedRef existed, check the version for uptodate + if (!sourceFileVersionUptoDate(oldResolvedRef.sourceFile)) { + return false; + } + // Add to seen before checking the referenced paths of this config file + (seenResolvedRefs || (seenResolvedRefs = [])).push(oldResolvedRef); + // If child project references are upto date, this project reference is uptodate + return !ts.forEach(oldResolvedRef.references, function (childResolvedRef, index) { + return !resolvedProjectReferenceUptoDate(childResolvedRef, oldResolvedRef.commandLine.projectReferences[index]); + }); + } + // In old program, not able to resolve project reference path, + // so if config file doesnt exist, it is uptodate. + return !fileExists(resolveProjectReferencePath(oldRef)); + } + } + ts.isProgramUptoDate = isProgramUptoDate; + function getConfigFileParsingDiagnostics(configFileParseResult) { + return configFileParseResult.options.configFile ? configFileParseResult.options.configFile.parseDiagnostics.concat(configFileParseResult.errors) : + configFileParseResult.errors; + } + ts.getConfigFileParsingDiagnostics = getConfigFileParsingDiagnostics; + /** + * Determine if source file needs to be re-created even if its text hasn't changed + */ + function shouldProgramCreateNewSourceFiles(program, newOptions) { + if (!program) + return false; + // If any compiler options change, we can't reuse old source file even if version match + // The change in options like these could result in change in syntax tree or `sourceFile.bindDiagnostics`. + var oldOptions = program.getCompilerOptions(); + return !!ts.sourceFileAffectingCompilerOptions.some(function (option) { + return !ts.isJsonEqual(ts.getCompilerOptionValue(oldOptions, option), ts.getCompilerOptionValue(newOptions, option)); + }); + } + function createCreateProgramOptions(rootNames, options, host, oldProgram, configFileParsingDiagnostics) { + return { + rootNames: rootNames, + options: options, + host: host, + oldProgram: oldProgram, + configFileParsingDiagnostics: configFileParsingDiagnostics + }; + } + function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _configFileParsingDiagnostics) { + var createProgramOptions = ts.isArray(rootNamesOrOptions) ? createCreateProgramOptions(rootNamesOrOptions, _options, _host, _oldProgram, _configFileParsingDiagnostics) : rootNamesOrOptions; // TODO: GH#18217 + var rootNames = createProgramOptions.rootNames, options = createProgramOptions.options, configFileParsingDiagnostics = createProgramOptions.configFileParsingDiagnostics, projectReferences = createProgramOptions.projectReferences; + var oldProgram = createProgramOptions.oldProgram; + var program; + var processingDefaultLibFiles; + var processingOtherFiles; + var files; + var commonSourceDirectory; + var diagnosticsProducingTypeChecker; + var noDiagnosticsTypeChecker; + var classifiableNames; + var ambientModuleNameToUnmodifiedFileName = ts.createMap(); + var cachedSemanticDiagnosticsForFile = {}; + var cachedDeclarationDiagnosticsForFile = {}; + var resolvedTypeReferenceDirectives = ts.createMap(); + var fileProcessingDiagnostics = ts.createDiagnosticCollection(); + // The below settings are to track if a .js file should be add to the program if loaded via searching under node_modules. + // This works as imported modules are discovered recursively in a depth first manner, specifically: + // - For each root file, findSourceFile is called. + // - This calls processImportedModules for each module imported in the source file. + // - This calls resolveModuleNames, and then calls findSourceFile for each resolved module. + // As all these operations happen - and are nested - within the createProgram call, they close over the below variables. + // The current resolution depth is tracked by incrementing/decrementing as the depth first search progresses. + var maxNodeModuleJsDepth = typeof options.maxNodeModuleJsDepth === "number" ? options.maxNodeModuleJsDepth : 0; + var currentNodeModulesDepth = 0; + // If a module has some of its imports skipped due to being at the depth limit under node_modules, then track + // this, as it may be imported at a shallower depth later, and then it will need its skipped imports processed. + var modulesWithElidedImports = ts.createMap(); + // Track source files that are source files found by searching under node_modules, as these shouldn't be compiled. + var sourceFilesFoundSearchingNodeModules = ts.createMap(); + ts.performance.mark("beforeProgram"); + var host = createProgramOptions.host || createCompilerHost(options); + var configParsingHost = parseConfigHostFromCompilerHost(host); + var skipDefaultLib = options.noLib; + var getDefaultLibraryFileName = ts.memoize(function () { return host.getDefaultLibFileName(options); }); + var defaultLibraryPath = host.getDefaultLibLocation ? host.getDefaultLibLocation() : ts.getDirectoryPath(getDefaultLibraryFileName()); + var programDiagnostics = ts.createDiagnosticCollection(); + var currentDirectory = host.getCurrentDirectory(); + var supportedExtensions = ts.getSupportedExtensions(options); + var supportedExtensionsWithJsonIfResolveJsonModule = ts.getSuppoertedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions); + // Map storing if there is emit blocking diagnostics for given input + var hasEmitBlockingDiagnostics = ts.createMap(); + var _compilerOptionsObjectLiteralSyntax; + var moduleResolutionCache; + var resolveModuleNamesWorker; + var hasInvalidatedResolution = host.hasInvalidatedResolution || ts.returnFalse; + if (host.resolveModuleNames) { + resolveModuleNamesWorker = function (moduleNames, containingFile, reusedNames, redirectedReference) { return host.resolveModuleNames(ts.Debug.assertEachDefined(moduleNames), containingFile, reusedNames, redirectedReference).map(function (resolved) { + // An older host may have omitted extension, in which case we should infer it from the file extension of resolvedFileName. + if (!resolved || resolved.extension !== undefined) { + return resolved; + } + var withExtension = ts.clone(resolved); + withExtension.extension = ts.extensionFromPath(resolved.resolvedFileName); + return withExtension; + }); }; + } + else { + moduleResolutionCache = ts.createModuleResolutionCache(currentDirectory, function (x) { return host.getCanonicalFileName(x); }); + var loader_1 = function (moduleName, containingFile, redirectedReference) { return ts.resolveModuleName(moduleName, containingFile, options, host, moduleResolutionCache, redirectedReference).resolvedModule; }; // TODO: GH#18217 + resolveModuleNamesWorker = function (moduleNames, containingFile, _reusedNames, redirectedReference) { return loadWithLocalCache(ts.Debug.assertEachDefined(moduleNames), containingFile, redirectedReference, loader_1); }; + } + var resolveTypeReferenceDirectiveNamesWorker; + if (host.resolveTypeReferenceDirectives) { + resolveTypeReferenceDirectiveNamesWorker = function (typeDirectiveNames, containingFile, redirectedReference) { return host.resolveTypeReferenceDirectives(ts.Debug.assertEachDefined(typeDirectiveNames), containingFile, redirectedReference); }; + } + else { + var loader_2 = function (typesRef, containingFile, redirectedReference) { return ts.resolveTypeReferenceDirective(typesRef, containingFile, options, host, redirectedReference).resolvedTypeReferenceDirective; }; // TODO: GH#18217 + resolveTypeReferenceDirectiveNamesWorker = function (typeReferenceDirectiveNames, containingFile, redirectedReference) { return loadWithLocalCache(ts.Debug.assertEachDefined(typeReferenceDirectiveNames), containingFile, redirectedReference, loader_2); }; + } + // Map from a stringified PackageId to the source file with that id. + // Only one source file may have a given packageId. Others become redirects (see createRedirectSourceFile). + // `packageIdToSourceFile` is only used while building the program, while `sourceFileToPackageName` and `isSourceFileTargetOfRedirect` are kept around. + var packageIdToSourceFile = ts.createMap(); + // Maps from a SourceFile's `.path` to the name of the package it was imported with. + var sourceFileToPackageName = ts.createMap(); + // Key is a file name. Value is the (non-empty, or undefined) list of files that redirect to it. + var redirectTargetsMap = ts.createMultiMap(); + var filesByName = ts.createMap(); + var missingFilePaths; + // stores 'filename -> file association' ignoring case + // used to track cases when two file names differ only in casing + var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createMap() : undefined; + // A parallel array to projectReferences storing the results of reading in the referenced tsconfig files + var resolvedProjectReferences; + var projectReferenceRedirects; + var mapFromFileToProjectReferenceRedirects; + var shouldCreateNewSourceFile = shouldProgramCreateNewSourceFiles(oldProgram, options); + var structuralIsReused = tryReuseStructureFromOldProgram(); + if (structuralIsReused !== 2 /* Completely */) { + processingDefaultLibFiles = []; + processingOtherFiles = []; + if (projectReferences) { + if (!resolvedProjectReferences) { + resolvedProjectReferences = projectReferences.map(parseProjectReferenceConfigFile); + } + if (rootNames.length) { + for (var _i = 0, resolvedProjectReferences_1 = resolvedProjectReferences; _i < resolvedProjectReferences_1.length; _i++) { + var parsedRef = resolvedProjectReferences_1[_i]; + if (parsedRef) { + var out = parsedRef.commandLine.options.outFile || parsedRef.commandLine.options.out; + if (out) { + var dtsOutfile = ts.changeExtension(out, ".d.ts"); + processSourceFile(dtsOutfile, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined); + } + } + } + } + } + ts.forEach(rootNames, function (name) { return processRootFile(name, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false); }); + // load type declarations specified via 'types' argument or implicitly from types/ and node_modules/@types folders + var typeReferences = rootNames.length ? ts.getAutomaticTypeDirectiveNames(options, host) : ts.emptyArray; + if (typeReferences.length) { + // This containingFilename needs to match with the one used in managed-side + var containingDirectory = options.configFilePath ? ts.getDirectoryPath(options.configFilePath) : host.getCurrentDirectory(); + var containingFilename = ts.combinePaths(containingDirectory, "__inferred type names__.ts"); + var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeReferences, containingFilename); + for (var i = 0; i < typeReferences.length; i++) { + processTypeReferenceDirective(typeReferences[i], resolutions[i]); + } + } + // Do not process the default library if: + // - The '--noLib' flag is used. + // - A 'no-default-lib' reference comment is encountered in + // processing the root files. + if (rootNames.length && !skipDefaultLib) { + // If '--lib' is not specified, include default library file according to '--target' + // otherwise, using options specified in '--lib' instead of '--target' default library file + var defaultLibraryFileName = getDefaultLibraryFileName(); + if (!options.lib && defaultLibraryFileName) { + processRootFile(defaultLibraryFileName, /*isDefaultLib*/ true, /*ignoreNoDefaultLib*/ false); + } + else { + ts.forEach(options.lib, function (libFileName) { + processRootFile(ts.combinePaths(defaultLibraryPath, libFileName), /*isDefaultLib*/ true, /*ignoreNoDefaultLib*/ false); + }); + } + } + missingFilePaths = ts.arrayFrom(filesByName.keys(), function (p) { return p; }).filter(function (p) { return !filesByName.get(p); }); + files = ts.stableSort(processingDefaultLibFiles, compareDefaultLibFiles).concat(processingOtherFiles); + processingDefaultLibFiles = undefined; + processingOtherFiles = undefined; + } + ts.Debug.assert(!!missingFilePaths); + // Release any files we have acquired in the old program but are + // not part of the new program. + if (oldProgram && host.onReleaseOldSourceFile) { + var oldSourceFiles = oldProgram.getSourceFiles(); + for (var _a = 0, oldSourceFiles_1 = oldSourceFiles; _a < oldSourceFiles_1.length; _a++) { + var oldSourceFile = oldSourceFiles_1[_a]; + var newFile = getSourceFileByPath(oldSourceFile.resolvedPath); + if (shouldCreateNewSourceFile || !newFile || + // old file wasnt redirect but new file is + (oldSourceFile.resolvedPath === oldSourceFile.path && newFile.resolvedPath !== oldSourceFile.path)) { + host.onReleaseOldSourceFile(oldSourceFile, oldProgram.getCompilerOptions(), !!getSourceFileByPath(oldSourceFile.path)); + } + } + oldProgram.forEachResolvedProjectReference(function (resolvedProjectReference, resolvedProjectReferencePath) { + if (resolvedProjectReference && !getResolvedProjectReferenceByPath(resolvedProjectReferencePath)) { + host.onReleaseOldSourceFile(resolvedProjectReference.sourceFile, oldProgram.getCompilerOptions(), /*hasSourceFileByPath*/ false); + } + }); + } + // unconditionally set oldProgram to undefined to prevent it from being captured in closure + oldProgram = undefined; + program = { + getRootFileNames: function () { return rootNames; }, + getSourceFile: getSourceFile, + getSourceFileByPath: getSourceFileByPath, + getSourceFiles: function () { return files; }, + getMissingFilePaths: function () { return missingFilePaths; }, + getCompilerOptions: function () { return options; }, + getSyntacticDiagnostics: getSyntacticDiagnostics, + getOptionsDiagnostics: getOptionsDiagnostics, + getGlobalDiagnostics: getGlobalDiagnostics, + getSemanticDiagnostics: getSemanticDiagnostics, + getSuggestionDiagnostics: getSuggestionDiagnostics, + getDeclarationDiagnostics: getDeclarationDiagnostics, + getTypeChecker: getTypeChecker, + getClassifiableNames: getClassifiableNames, + getDiagnosticsProducingTypeChecker: getDiagnosticsProducingTypeChecker, + getCommonSourceDirectory: getCommonSourceDirectory, + emit: emit, + getCurrentDirectory: function () { return currentDirectory; }, + getNodeCount: function () { return getDiagnosticsProducingTypeChecker().getNodeCount(); }, + getIdentifierCount: function () { return getDiagnosticsProducingTypeChecker().getIdentifierCount(); }, + getSymbolCount: function () { return getDiagnosticsProducingTypeChecker().getSymbolCount(); }, + getTypeCount: function () { return getDiagnosticsProducingTypeChecker().getTypeCount(); }, + getFileProcessingDiagnostics: function () { return fileProcessingDiagnostics; }, + getResolvedTypeReferenceDirectives: function () { return resolvedTypeReferenceDirectives; }, + isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary, + isSourceFileDefaultLibrary: isSourceFileDefaultLibrary, + dropDiagnosticsProducingTypeChecker: dropDiagnosticsProducingTypeChecker, + getSourceFileFromReference: getSourceFileFromReference, + getLibFileFromReference: getLibFileFromReference, + sourceFileToPackageName: sourceFileToPackageName, + redirectTargetsMap: redirectTargetsMap, + isEmittedFile: isEmittedFile, + getConfigFileParsingDiagnostics: getConfigFileParsingDiagnostics, + getResolvedModuleWithFailedLookupLocationsFromCache: getResolvedModuleWithFailedLookupLocationsFromCache, + getProjectReferences: getProjectReferences, + getResolvedProjectReferences: getResolvedProjectReferences, + getProjectReferenceRedirect: getProjectReferenceRedirect, + getResolvedProjectReferenceToRedirect: getResolvedProjectReferenceToRedirect, + getResolvedProjectReferenceByPath: getResolvedProjectReferenceByPath, + forEachResolvedProjectReference: forEachResolvedProjectReference + }; + verifyCompilerOptions(); + ts.performance.mark("afterProgram"); + ts.performance.measure("Program", "beforeProgram", "afterProgram"); + return program; + function compareDefaultLibFiles(a, b) { + return ts.compareValues(getDefaultLibFilePriority(a), getDefaultLibFilePriority(b)); + } + function getDefaultLibFilePriority(a) { + if (ts.containsPath(defaultLibraryPath, a.fileName, /*ignoreCase*/ false)) { + var basename = ts.getBaseFileName(a.fileName); + if (basename === "lib.d.ts" || basename === "lib.es6.d.ts") + return 0; + var name = ts.removeSuffix(ts.removePrefix(basename, "lib."), ".d.ts"); + var index = ts.libs.indexOf(name); + if (index !== -1) + return index + 1; + } + return ts.libs.length + 2; + } + function getResolvedModuleWithFailedLookupLocationsFromCache(moduleName, containingFile) { + return moduleResolutionCache && ts.resolveModuleNameFromCache(moduleName, containingFile, moduleResolutionCache); + } + function toPath(fileName) { + return ts.toPath(fileName, currentDirectory, getCanonicalFileName); + } + function getCommonSourceDirectory() { + if (commonSourceDirectory === undefined) { + var emittedFiles = ts.filter(files, function (file) { return ts.sourceFileMayBeEmitted(file, options, isSourceFileFromExternalLibrary); }); + if (options.rootDir && checkSourceFilesBelongToPath(emittedFiles, options.rootDir)) { + // If a rootDir is specified use it as the commonSourceDirectory + commonSourceDirectory = ts.getNormalizedAbsolutePath(options.rootDir, currentDirectory); + } + else if (options.composite && options.configFilePath) { + // Project compilations never infer their root from the input source paths + commonSourceDirectory = ts.getDirectoryPath(ts.normalizeSlashes(options.configFilePath)); + checkSourceFilesBelongToPath(emittedFiles, commonSourceDirectory); + } + else { + commonSourceDirectory = computeCommonSourceDirectory(emittedFiles); + } + if (commonSourceDirectory && commonSourceDirectory[commonSourceDirectory.length - 1] !== ts.directorySeparator) { + // Make sure directory path ends with directory separator so this string can directly + // used to replace with "" to get the relative path of the source file and the relative path doesn't + // start with / making it rooted path + commonSourceDirectory += ts.directorySeparator; + } + } + return commonSourceDirectory; + } + function getClassifiableNames() { + if (!classifiableNames) { + // Initialize a checker so that all our files are bound. + getTypeChecker(); + classifiableNames = ts.createUnderscoreEscapedMap(); + for (var _i = 0, files_2 = files; _i < files_2.length; _i++) { + var sourceFile = files_2[_i]; + ts.copyEntries(sourceFile.classifiableNames, classifiableNames); + } + } + return classifiableNames; + } + function resolveModuleNamesReusingOldState(moduleNames, containingFile, file) { + if (structuralIsReused === 0 /* Not */ && !file.ambientModuleNames.length) { + // If the old program state does not permit reusing resolutions and `file` does not contain locally defined ambient modules, + // the best we can do is fallback to the default logic. + return resolveModuleNamesWorker(moduleNames, containingFile, /*reusedNames*/ undefined, getResolvedProjectReferenceToRedirect(file.originalFileName)); + } + var oldSourceFile = oldProgram && oldProgram.getSourceFile(containingFile); + if (oldSourceFile !== file && file.resolvedModules) { + // `file` was created for the new program. + // + // We only set `file.resolvedModules` via work from the current function, + // so it is defined iff we already called the current function on `file`. + // That call happened no later than the creation of the `file` object, + // which per above occurred during the current program creation. + // Since we assume the filesystem does not change during program creation, + // it is safe to reuse resolutions from the earlier call. + var result_5 = []; + for (var _i = 0, moduleNames_1 = moduleNames; _i < moduleNames_1.length; _i++) { + var moduleName = moduleNames_1[_i]; + var resolvedModule = file.resolvedModules.get(moduleName); + result_5.push(resolvedModule); + } + return result_5; + } + // At this point, we know at least one of the following hold: + // - file has local declarations for ambient modules + // - old program state is available + // With this information, we can infer some module resolutions without performing resolution. + /** An ordered list of module names for which we cannot recover the resolution. */ + var unknownModuleNames; + /** + * The indexing of elements in this list matches that of `moduleNames`. + * + * Before combining results, result[i] is in one of the following states: + * * undefined: needs to be recomputed, + * * predictedToResolveToAmbientModuleMarker: known to be an ambient module. + * Needs to be reset to undefined before returning, + * * ResolvedModuleFull instance: can be reused. + */ + var result; + var reusedNames; + /** A transient placeholder used to mark predicted resolution in the result list. */ + var predictedToResolveToAmbientModuleMarker = {}; + for (var i = 0; i < moduleNames.length; i++) { + var moduleName = moduleNames[i]; + // If the source file is unchanged and doesnt have invalidated resolution, reuse the module resolutions + if (file === oldSourceFile && !hasInvalidatedResolution(oldSourceFile.path)) { + var oldResolvedModule = oldSourceFile && oldSourceFile.resolvedModules.get(moduleName); + if (oldResolvedModule) { + if (ts.isTraceEnabled(options, host)) { + ts.trace(host, ts.Diagnostics.Reusing_resolution_of_module_0_to_file_1_from_old_program, moduleName, containingFile); + } + (result || (result = new Array(moduleNames.length)))[i] = oldResolvedModule; + (reusedNames || (reusedNames = [])).push(moduleName); + continue; + } + } + // We know moduleName resolves to an ambient module provided that moduleName: + // - is in the list of ambient modules locally declared in the current source file. + // - resolved to an ambient module in the old program whose declaration is in an unmodified file + // (so the same module declaration will land in the new program) + var resolvesToAmbientModuleInNonModifiedFile = false; + if (ts.contains(file.ambientModuleNames, moduleName)) { + resolvesToAmbientModuleInNonModifiedFile = true; + if (ts.isTraceEnabled(options, host)) { + ts.trace(host, ts.Diagnostics.Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1, moduleName, containingFile); + } + } + else { + resolvesToAmbientModuleInNonModifiedFile = moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName); + } + if (resolvesToAmbientModuleInNonModifiedFile) { + (result || (result = new Array(moduleNames.length)))[i] = predictedToResolveToAmbientModuleMarker; + } + else { + // Resolution failed in the old program, or resolved to an ambient module for which we can't reuse the result. + (unknownModuleNames || (unknownModuleNames = [])).push(moduleName); + } + } + var resolutions = unknownModuleNames && unknownModuleNames.length + ? resolveModuleNamesWorker(unknownModuleNames, containingFile, reusedNames, getResolvedProjectReferenceToRedirect(file.originalFileName)) + : ts.emptyArray; + // Combine results of resolutions and predicted results + if (!result) { + // There were no unresolved/ambient resolutions. + ts.Debug.assert(resolutions.length === moduleNames.length); + return resolutions; + } + var j = 0; + for (var i = 0; i < result.length; i++) { + if (result[i]) { + // `result[i]` is either a `ResolvedModuleFull` or a marker. + // If it is the former, we can leave it as is. + if (result[i] === predictedToResolveToAmbientModuleMarker) { + result[i] = undefined; // TODO: GH#18217 + } + } + else { + result[i] = resolutions[j]; + j++; + } + } + ts.Debug.assert(j === resolutions.length); + return result; + // If we change our policy of rechecking failed lookups on each program create, + // we should adjust the value returned here. + function moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName) { + var resolutionToFile = ts.getResolvedModule(oldSourceFile, moduleName); + var resolvedFile = resolutionToFile && oldProgram.getSourceFile(resolutionToFile.resolvedFileName); + if (resolutionToFile && resolvedFile && !resolvedFile.externalModuleIndicator) { + // In the old program, we resolved to an ambient module that was in the same + // place as we expected to find an actual module file. + // We actually need to return 'false' here even though this seems like a 'true' case + // because the normal module resolution algorithm will find this anyway. + return false; + } + // at least one of declarations should come from non-modified source file + var unmodifiedFile = ambientModuleNameToUnmodifiedFileName.get(moduleName); + if (!unmodifiedFile) { + return false; + } + if (ts.isTraceEnabled(options, host)) { + ts.trace(host, ts.Diagnostics.Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified, moduleName, unmodifiedFile); + } + return true; + } + } + function canReuseProjectReferences() { + return !forEachProjectReference(oldProgram.getProjectReferences(), oldProgram.getResolvedProjectReferences(), function (oldResolvedRef, index, parent) { + var newRef = (parent ? parent.commandLine.projectReferences : projectReferences)[index]; + var newResolvedRef = parseProjectReferenceConfigFile(newRef); + if (oldResolvedRef) { + // Resolved project reference has gone missing or changed + return !newResolvedRef || newResolvedRef.sourceFile !== oldResolvedRef.sourceFile; + } + else { + // A previously-unresolved reference may be resolved now + return newResolvedRef !== undefined; + } + }, function (oldProjectReferences, parent) { + // If array of references is changed, we cant resue old program + var newReferences = parent ? getResolvedProjectReferenceByPath(parent.sourceFile.path).commandLine.projectReferences : projectReferences; + return !ts.arrayIsEqualTo(oldProjectReferences, newReferences, ts.projectReferenceIsEqualTo); + }); + } + function tryReuseStructureFromOldProgram() { + if (!oldProgram) { + return 0 /* Not */; + } + // check properties that can affect structure of the program or module resolution strategy + // if any of these properties has changed - structure cannot be reused + var oldOptions = oldProgram.getCompilerOptions(); + if (ts.changesAffectModuleResolution(oldOptions, options)) { + return oldProgram.structureIsReused = 0 /* Not */; + } + ts.Debug.assert(!(oldProgram.structureIsReused & (2 /* Completely */ | 1 /* SafeModules */))); + // there is an old program, check if we can reuse its structure + var oldRootNames = oldProgram.getRootFileNames(); + if (!ts.arrayIsEqualTo(oldRootNames, rootNames)) { + return oldProgram.structureIsReused = 0 /* Not */; + } + if (!ts.arrayIsEqualTo(options.types, oldOptions.types)) { + return oldProgram.structureIsReused = 0 /* Not */; + } + // Check if any referenced project tsconfig files are different + if (!canReuseProjectReferences()) { + return oldProgram.structureIsReused = 0 /* Not */; + } + if (projectReferences) { + resolvedProjectReferences = projectReferences.map(parseProjectReferenceConfigFile); + } + // check if program source files has changed in the way that can affect structure of the program + var newSourceFiles = []; + var modifiedSourceFiles = []; + oldProgram.structureIsReused = 2 /* Completely */; + // If the missing file paths are now present, it can change the progam structure, + // and hence cant reuse the structure. + // This is same as how we dont reuse the structure if one of the file from old program is now missing + if (oldProgram.getMissingFilePaths().some(function (missingFilePath) { return host.fileExists(missingFilePath); })) { + return oldProgram.structureIsReused = 0 /* Not */; + } + var oldSourceFiles = oldProgram.getSourceFiles(); + var SeenPackageName; + (function (SeenPackageName) { + SeenPackageName[SeenPackageName["Exists"] = 0] = "Exists"; + SeenPackageName[SeenPackageName["Modified"] = 1] = "Modified"; + })(SeenPackageName || (SeenPackageName = {})); + var seenPackageNames = ts.createMap(); + for (var _i = 0, oldSourceFiles_2 = oldSourceFiles; _i < oldSourceFiles_2.length; _i++) { + var oldSourceFile = oldSourceFiles_2[_i]; + var newSourceFile = host.getSourceFileByPath + ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.resolvedPath, options.target, /*onError*/ undefined, shouldCreateNewSourceFile) + : host.getSourceFile(oldSourceFile.fileName, options.target, /*onError*/ undefined, shouldCreateNewSourceFile); // TODO: GH#18217 + if (!newSourceFile) { + return oldProgram.structureIsReused = 0 /* Not */; + } + ts.Debug.assert(!newSourceFile.redirectInfo, "Host should not return a redirect source file from `getSourceFile`"); + var fileChanged = void 0; + if (oldSourceFile.redirectInfo) { + // We got `newSourceFile` by path, so it is actually for the unredirected file. + // This lets us know if the unredirected file has changed. If it has we should break the redirect. + if (newSourceFile !== oldSourceFile.redirectInfo.unredirected) { + // Underlying file has changed. Might not redirect anymore. Must rebuild program. + return oldProgram.structureIsReused = 0 /* Not */; + } + fileChanged = false; + newSourceFile = oldSourceFile; // Use the redirect. + } + else if (oldProgram.redirectTargetsMap.has(oldSourceFile.path)) { + // If a redirected-to source file changes, the redirect may be broken. + if (newSourceFile !== oldSourceFile) { + return oldProgram.structureIsReused = 0 /* Not */; + } + fileChanged = false; + } + else { + fileChanged = newSourceFile !== oldSourceFile; + } + // Since the project references havent changed, its right to set originalFileName and resolvedPath here + newSourceFile.path = oldSourceFile.path; + newSourceFile.originalFileName = oldSourceFile.originalFileName; + newSourceFile.resolvedPath = oldSourceFile.resolvedPath; + newSourceFile.fileName = oldSourceFile.fileName; + var packageName = oldProgram.sourceFileToPackageName.get(oldSourceFile.path); + if (packageName !== undefined) { + // If there are 2 different source files for the same package name and at least one of them changes, + // they might become redirects. So we must rebuild the program. + var prevKind = seenPackageNames.get(packageName); + var newKind = fileChanged ? 1 /* Modified */ : 0 /* Exists */; + if ((prevKind !== undefined && newKind === 1 /* Modified */) || prevKind === 1 /* Modified */) { + return oldProgram.structureIsReused = 0 /* Not */; + } + seenPackageNames.set(packageName, newKind); + } + if (fileChanged) { + // The `newSourceFile` object was created for the new program. + if (!ts.arrayIsEqualTo(oldSourceFile.libReferenceDirectives, newSourceFile.libReferenceDirectives, fileReferenceIsEqualTo)) { + // 'lib' references has changed. Matches behavior in changesAffectModuleResolution + return oldProgram.structureIsReused = 0 /* Not */; + } + if (oldSourceFile.hasNoDefaultLib !== newSourceFile.hasNoDefaultLib) { + // value of no-default-lib has changed + // this will affect if default library is injected into the list of files + oldProgram.structureIsReused = 1 /* SafeModules */; + } + // check tripleslash references + if (!ts.arrayIsEqualTo(oldSourceFile.referencedFiles, newSourceFile.referencedFiles, fileReferenceIsEqualTo)) { + // tripleslash references has changed + oldProgram.structureIsReused = 1 /* SafeModules */; + } + // check imports and module augmentations + collectExternalModuleReferences(newSourceFile); + if (!ts.arrayIsEqualTo(oldSourceFile.imports, newSourceFile.imports, moduleNameIsEqualTo)) { + // imports has changed + oldProgram.structureIsReused = 1 /* SafeModules */; + } + if (!ts.arrayIsEqualTo(oldSourceFile.moduleAugmentations, newSourceFile.moduleAugmentations, moduleNameIsEqualTo)) { + // moduleAugmentations has changed + oldProgram.structureIsReused = 1 /* SafeModules */; + } + if ((oldSourceFile.flags & 1572864 /* PermanentlySetIncrementalFlags */) !== (newSourceFile.flags & 1572864 /* PermanentlySetIncrementalFlags */)) { + // dynamicImport has changed + oldProgram.structureIsReused = 1 /* SafeModules */; + } + if (!ts.arrayIsEqualTo(oldSourceFile.typeReferenceDirectives, newSourceFile.typeReferenceDirectives, fileReferenceIsEqualTo)) { + // 'types' references has changed + oldProgram.structureIsReused = 1 /* SafeModules */; + } + // tentatively approve the file + modifiedSourceFiles.push({ oldFile: oldSourceFile, newFile: newSourceFile }); + } + else if (hasInvalidatedResolution(oldSourceFile.path)) { + // 'module/types' references could have changed + oldProgram.structureIsReused = 1 /* SafeModules */; + // add file to the modified list so that we will resolve it later + modifiedSourceFiles.push({ oldFile: oldSourceFile, newFile: newSourceFile }); + } + // if file has passed all checks it should be safe to reuse it + newSourceFiles.push(newSourceFile); + } + if (oldProgram.structureIsReused !== 2 /* Completely */) { + return oldProgram.structureIsReused; + } + var modifiedFiles = modifiedSourceFiles.map(function (f) { return f.oldFile; }); + for (var _a = 0, oldSourceFiles_3 = oldSourceFiles; _a < oldSourceFiles_3.length; _a++) { + var oldFile = oldSourceFiles_3[_a]; + if (!ts.contains(modifiedFiles, oldFile)) { + for (var _b = 0, _c = oldFile.ambientModuleNames; _b < _c.length; _b++) { + var moduleName = _c[_b]; + ambientModuleNameToUnmodifiedFileName.set(moduleName, oldFile.fileName); + } + } + } + // try to verify results of module resolution + for (var _d = 0, modifiedSourceFiles_1 = modifiedSourceFiles; _d < modifiedSourceFiles_1.length; _d++) { + var _e = modifiedSourceFiles_1[_d], oldSourceFile = _e.oldFile, newSourceFile = _e.newFile; + var newSourceFilePath = ts.getNormalizedAbsolutePath(newSourceFile.originalFileName, currentDirectory); + if (resolveModuleNamesWorker) { + var moduleNames = getModuleNames(newSourceFile); + var resolutions = resolveModuleNamesReusingOldState(moduleNames, newSourceFilePath, newSourceFile); + // ensure that module resolution results are still correct + var resolutionsChanged = ts.hasChangesInResolutions(moduleNames, resolutions, oldSourceFile.resolvedModules, ts.moduleResolutionIsEqualTo); + if (resolutionsChanged) { + oldProgram.structureIsReused = 1 /* SafeModules */; + newSourceFile.resolvedModules = ts.zipToMap(moduleNames, resolutions); + } + else { + newSourceFile.resolvedModules = oldSourceFile.resolvedModules; + } + } + if (resolveTypeReferenceDirectiveNamesWorker) { + // We lower-case all type references because npm automatically lowercases all packages. See GH#9824. + var typesReferenceDirectives = ts.map(newSourceFile.typeReferenceDirectives, function (ref) { return ref.fileName.toLocaleLowerCase(); }); + var resolutions = resolveTypeReferenceDirectiveNamesWorker(typesReferenceDirectives, newSourceFilePath, getResolvedProjectReferenceToRedirect(newSourceFile.originalFileName)); + // ensure that types resolutions are still correct + var resolutionsChanged = ts.hasChangesInResolutions(typesReferenceDirectives, resolutions, oldSourceFile.resolvedTypeReferenceDirectiveNames, ts.typeDirectiveIsEqualTo); + if (resolutionsChanged) { + oldProgram.structureIsReused = 1 /* SafeModules */; + newSourceFile.resolvedTypeReferenceDirectiveNames = ts.zipToMap(typesReferenceDirectives, resolutions); + } + else { + newSourceFile.resolvedTypeReferenceDirectiveNames = oldSourceFile.resolvedTypeReferenceDirectiveNames; + } + } + } + if (oldProgram.structureIsReused !== 2 /* Completely */) { + return oldProgram.structureIsReused; + } + if (host.hasChangedAutomaticTypeDirectiveNames) { + return oldProgram.structureIsReused = 1 /* SafeModules */; + } + missingFilePaths = oldProgram.getMissingFilePaths(); + // update fileName -> file mapping + for (var _f = 0, newSourceFiles_1 = newSourceFiles; _f < newSourceFiles_1.length; _f++) { + var newSourceFile = newSourceFiles_1[_f]; + var filePath = newSourceFile.path; + addFileToFilesByName(newSourceFile, filePath, newSourceFile.resolvedPath); + // Set the file as found during node modules search if it was found that way in old progra, + if (oldProgram.isSourceFileFromExternalLibrary(oldProgram.getSourceFileByPath(filePath))) { + sourceFilesFoundSearchingNodeModules.set(filePath, true); + } + } + files = newSourceFiles; + fileProcessingDiagnostics = oldProgram.getFileProcessingDiagnostics(); + for (var _g = 0, modifiedSourceFiles_2 = modifiedSourceFiles; _g < modifiedSourceFiles_2.length; _g++) { + var modifiedFile = modifiedSourceFiles_2[_g]; + fileProcessingDiagnostics.reattachFileDiagnostics(modifiedFile.newFile); + } + resolvedTypeReferenceDirectives = oldProgram.getResolvedTypeReferenceDirectives(); + sourceFileToPackageName = oldProgram.sourceFileToPackageName; + redirectTargetsMap = oldProgram.redirectTargetsMap; + return oldProgram.structureIsReused = 2 /* Completely */; + } + function getEmitHost(writeFileCallback) { + return __assign({ getPrependNodes: getPrependNodes, + getCanonicalFileName: getCanonicalFileName, getCommonSourceDirectory: program.getCommonSourceDirectory, getCompilerOptions: program.getCompilerOptions, getCurrentDirectory: function () { return currentDirectory; }, getNewLine: function () { return host.getNewLine(); }, getSourceFile: program.getSourceFile, getSourceFileByPath: program.getSourceFileByPath, getSourceFiles: program.getSourceFiles, getLibFileFromReference: program.getLibFileFromReference, isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary, writeFile: writeFileCallback || (function (fileName, data, writeByteOrderMark, onError, sourceFiles) { return host.writeFile(fileName, data, writeByteOrderMark, onError, sourceFiles); }), isEmitBlocked: isEmitBlocked, readFile: function (f) { return host.readFile(f); }, fileExists: function (f) { + // Use local caches + var path = toPath(f); + if (getSourceFileByPath(path)) + return true; + if (ts.contains(missingFilePaths, path)) + return false; + // Before falling back to the host + return host.fileExists(f); + } }, (host.directoryExists ? { directoryExists: function (f) { return host.directoryExists(f); } } : {}), { useCaseSensitiveFileNames: function () { return host.useCaseSensitiveFileNames(); } }); + } + function getResolvedProjectReferences() { + return resolvedProjectReferences; + } + function getProjectReferences() { + return projectReferences; + } + function getPrependNodes() { + if (!projectReferences) { + return ts.emptyArray; + } + var nodes = []; + for (var i = 0; i < projectReferences.length; i++) { + var ref = projectReferences[i]; + var resolvedRefOpts = resolvedProjectReferences[i].commandLine; + if (ref.prepend && resolvedRefOpts && resolvedRefOpts.options) { + var out = resolvedRefOpts.options.outFile || resolvedRefOpts.options.out; + // Upstream project didn't have outFile set -- skip (error will have been issued earlier) + if (!out) + continue; + var dtsFilename = ts.changeExtension(out, ".d.ts"); + var js = host.readFile(out) || "/* Input file " + out + " was missing */\r\n"; + var jsMapPath = out + ".map"; // TODO: try to read sourceMappingUrl comment from the file + var jsMap = host.readFile(jsMapPath); + var dts = host.readFile(dtsFilename) || "/* Input file " + dtsFilename + " was missing */\r\n"; + var dtsMapPath = dtsFilename + ".map"; + var dtsMap = host.readFile(dtsMapPath); + var node = ts.createInputFiles(js, dts, jsMap && jsMapPath, jsMap, dtsMap && dtsMapPath, dtsMap); + nodes.push(node); + } + } + return nodes; + } + function isSourceFileFromExternalLibrary(file) { + return !!sourceFilesFoundSearchingNodeModules.get(file.path); + } + function isSourceFileDefaultLibrary(file) { + if (file.hasNoDefaultLib) { + return true; + } + if (!options.noLib) { + return false; + } + // If '--lib' is not specified, include default library file according to '--target' + // otherwise, using options specified in '--lib' instead of '--target' default library file + var equalityComparer = host.useCaseSensitiveFileNames() ? ts.equateStringsCaseSensitive : ts.equateStringsCaseInsensitive; + if (!options.lib) { + return equalityComparer(file.fileName, getDefaultLibraryFileName()); + } + else { + return ts.some(options.lib, function (libFileName) { return equalityComparer(file.fileName, ts.combinePaths(defaultLibraryPath, libFileName)); }); + } + } + function getDiagnosticsProducingTypeChecker() { + return diagnosticsProducingTypeChecker || (diagnosticsProducingTypeChecker = ts.createTypeChecker(program, /*produceDiagnostics:*/ true)); + } + function dropDiagnosticsProducingTypeChecker() { + diagnosticsProducingTypeChecker = undefined; + } + function getTypeChecker() { + return noDiagnosticsTypeChecker || (noDiagnosticsTypeChecker = ts.createTypeChecker(program, /*produceDiagnostics:*/ false)); + } + function emit(sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles, transformers) { + return runWithCancellationToken(function () { return emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles, transformers); }); + } + function isEmitBlocked(emitFileName) { + return hasEmitBlockingDiagnostics.has(toPath(emitFileName)); + } + function emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles, customTransformers) { + var declarationDiagnostics = []; + if (!emitOnlyDtsFiles) { + if (options.noEmit) { + return { diagnostics: declarationDiagnostics, sourceMaps: undefined, emittedFiles: undefined, emitSkipped: true }; + } + // If the noEmitOnError flag is set, then check if we have any errors so far. If so, + // immediately bail out. Note that we pass 'undefined' for 'sourceFile' so that we + // get any preEmit diagnostics, not just the ones + if (options.noEmitOnError) { + var diagnostics = program.getOptionsDiagnostics(cancellationToken).concat(program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken)); + if (diagnostics.length === 0 && ts.getEmitDeclarations(program.getCompilerOptions())) { + declarationDiagnostics = program.getDeclarationDiagnostics(/*sourceFile*/ undefined, cancellationToken); + } + if (diagnostics.length > 0 || declarationDiagnostics.length > 0) { + return { + diagnostics: ts.concatenate(diagnostics, declarationDiagnostics), + sourceMaps: undefined, + emittedFiles: undefined, + emitSkipped: true + }; + } + } + } + // Create the emit resolver outside of the "emitTime" tracking code below. That way + // any cost associated with it (like type checking) are appropriate associated with + // the type-checking counter. + // + // If the -out option is specified, we should not pass the source file to getEmitResolver. + // This is because in the -out scenario all files need to be emitted, and therefore all + // files need to be type checked. And the way to specify that all files need to be type + // checked is to not pass the file to getEmitResolver. + var emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile, cancellationToken); + ts.performance.mark("beforeEmit"); + var transformers = emitOnlyDtsFiles ? [] : ts.getTransformers(options, customTransformers); + var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile, // TODO: GH#18217 + emitOnlyDtsFiles, transformers, customTransformers && customTransformers.afterDeclarations); + ts.performance.mark("afterEmit"); + ts.performance.measure("Emit", "beforeEmit", "afterEmit"); + return emitResult; + } + function getSourceFile(fileName) { + return getSourceFileByPath(toPath(fileName)); + } + function getSourceFileByPath(path) { + return filesByName.get(path); + } + function getDiagnosticsHelper(sourceFile, getDiagnostics, cancellationToken) { + if (sourceFile) { + return getDiagnostics(sourceFile, cancellationToken); + } + return ts.sortAndDeduplicateDiagnostics(ts.flatMap(program.getSourceFiles(), function (sourceFile) { + if (cancellationToken) { + cancellationToken.throwIfCancellationRequested(); + } + return getDiagnostics(sourceFile, cancellationToken); + })); + } + function getSyntacticDiagnostics(sourceFile, cancellationToken) { + return getDiagnosticsHelper(sourceFile, getSyntacticDiagnosticsForFile, cancellationToken); + } + function getSemanticDiagnostics(sourceFile, cancellationToken) { + return getDiagnosticsHelper(sourceFile, getSemanticDiagnosticsForFile, cancellationToken); + } + function getDeclarationDiagnostics(sourceFile, cancellationToken) { + var options = program.getCompilerOptions(); + // collect diagnostics from the program only once if either no source file was specified or out/outFile is set (bundled emit) + if (!sourceFile || options.out || options.outFile) { + return getDeclarationDiagnosticsWorker(sourceFile, cancellationToken); + } + else { + return getDiagnosticsHelper(sourceFile, getDeclarationDiagnosticsForFile, cancellationToken); + } + } + function getSyntacticDiagnosticsForFile(sourceFile) { + // For JavaScript files, we report semantic errors for using TypeScript-only + // constructs from within a JavaScript file as syntactic errors. + if (ts.isSourceFileJS(sourceFile)) { + if (!sourceFile.additionalSyntacticDiagnostics) { + sourceFile.additionalSyntacticDiagnostics = getJSSyntacticDiagnosticsForFile(sourceFile); + } + return ts.concatenate(sourceFile.additionalSyntacticDiagnostics, sourceFile.parseDiagnostics); + } + return sourceFile.parseDiagnostics; + } + function runWithCancellationToken(func) { + try { + return func(); + } + catch (e) { + if (e instanceof ts.OperationCanceledException) { + // We were canceled while performing the operation. Because our type checker + // might be a bad state, we need to throw it away. + // + // Note: we are overly aggressive here. We do not actually *have* to throw away + // the "noDiagnosticsTypeChecker". However, for simplicity, i'd like to keep + // the lifetimes of these two TypeCheckers the same. Also, we generally only + // cancel when the user has made a change anyways. And, in that case, we (the + // program instance) will get thrown away anyways. So trying to keep one of + // these type checkers alive doesn't serve much purpose. + noDiagnosticsTypeChecker = undefined; + diagnosticsProducingTypeChecker = undefined; + } + throw e; + } + } + function getSemanticDiagnosticsForFile(sourceFile, cancellationToken) { + return getAndCacheDiagnostics(sourceFile, cancellationToken, cachedSemanticDiagnosticsForFile, getSemanticDiagnosticsForFileNoCache); + } + function getSemanticDiagnosticsForFileNoCache(sourceFile, cancellationToken) { + return runWithCancellationToken(function () { + if (ts.skipTypeChecking(sourceFile, options)) { + return ts.emptyArray; + } + var typeChecker = getDiagnosticsProducingTypeChecker(); + ts.Debug.assert(!!sourceFile.bindDiagnostics); + var isCheckJs = ts.isCheckJsEnabledForFile(sourceFile, options); + // By default, only type-check .ts, .tsx, 'Deferred' and 'External' files (external files are added by plugins) + var includeBindAndCheckDiagnostics = sourceFile.scriptKind === 3 /* TS */ || sourceFile.scriptKind === 4 /* TSX */ || + sourceFile.scriptKind === 5 /* External */ || isCheckJs || sourceFile.scriptKind === 7 /* Deferred */; + var bindDiagnostics = includeBindAndCheckDiagnostics ? sourceFile.bindDiagnostics : ts.emptyArray; + var checkDiagnostics = includeBindAndCheckDiagnostics ? typeChecker.getDiagnostics(sourceFile, cancellationToken) : ts.emptyArray; + var fileProcessingDiagnosticsInFile = fileProcessingDiagnostics.getDiagnostics(sourceFile.fileName); + var programDiagnosticsInFile = programDiagnostics.getDiagnostics(sourceFile.fileName); + var diagnostics; + for (var _i = 0, _a = [bindDiagnostics, checkDiagnostics, fileProcessingDiagnosticsInFile, programDiagnosticsInFile, isCheckJs ? sourceFile.jsDocDiagnostics : undefined]; _i < _a.length; _i++) { + var diags = _a[_i]; + if (diags) { + for (var _b = 0, diags_1 = diags; _b < diags_1.length; _b++) { + var diag = diags_1[_b]; + if (shouldReportDiagnostic(diag)) { + diagnostics = ts.append(diagnostics, diag); + } + } + } + } + return diagnostics; + }); + } + function getSuggestionDiagnostics(sourceFile, cancellationToken) { + return runWithCancellationToken(function () { + return getDiagnosticsProducingTypeChecker().getSuggestionDiagnostics(sourceFile, cancellationToken); + }); + } + /** + * Skip errors if previous line start with '// @ts-ignore' comment, not counting non-empty non-comment lines + */ + function shouldReportDiagnostic(diagnostic) { + var file = diagnostic.file, start = diagnostic.start; + if (file) { + var lineStarts = ts.getLineStarts(file); + var line = ts.computeLineAndCharacterOfPosition(lineStarts, start).line; // TODO: GH#18217 + while (line > 0) { + var previousLineText = file.text.slice(lineStarts[line - 1], lineStarts[line]); + var result = ignoreDiagnosticCommentRegEx.exec(previousLineText); + if (!result) { + // non-empty line + return true; + } + if (result[3]) { + // @ts-ignore + return false; + } + line--; + } + } + return true; + } + function getJSSyntacticDiagnosticsForFile(sourceFile) { + return runWithCancellationToken(function () { + var diagnostics = []; + var parent = sourceFile; + walk(sourceFile); + return diagnostics; + function walk(node) { + // Return directly from the case if the given node doesnt want to visit each child + // Otherwise break to visit each child + switch (parent.kind) { + case 151 /* Parameter */: + case 154 /* PropertyDeclaration */: + if (parent.questionToken === node) { + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, "?")); + return; + } + // falls through + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 196 /* FunctionExpression */: + case 239 /* FunctionDeclaration */: + case 197 /* ArrowFunction */: + case 237 /* VariableDeclaration */: + // type annotation + if (parent.type === node) { + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.types_can_only_be_used_in_a_ts_file)); + return; + } + } + switch (node.kind) { + case 248 /* ImportEqualsDeclaration */: + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.import_can_only_be_used_in_a_ts_file)); + return; + case 254 /* ExportAssignment */: + if (node.isExportEquals) { + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.export_can_only_be_used_in_a_ts_file)); + return; + } + break; + case 273 /* HeritageClause */: + var heritageClause = node; + if (heritageClause.token === 109 /* ImplementsKeyword */) { + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.implements_clauses_can_only_be_used_in_a_ts_file)); + return; + } + break; + case 241 /* InterfaceDeclaration */: + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.interface_declarations_can_only_be_used_in_a_ts_file)); + return; + case 244 /* ModuleDeclaration */: + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.module_declarations_can_only_be_used_in_a_ts_file)); + return; + case 242 /* TypeAliasDeclaration */: + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.type_aliases_can_only_be_used_in_a_ts_file)); + return; + case 243 /* EnumDeclaration */: + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.enum_declarations_can_only_be_used_in_a_ts_file)); + return; + case 213 /* NonNullExpression */: + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.non_null_assertions_can_only_be_used_in_a_ts_file)); + return; + case 212 /* AsExpression */: + diagnostics.push(createDiagnosticForNode(node.type, ts.Diagnostics.type_assertion_expressions_can_only_be_used_in_a_ts_file)); + return; + case 194 /* TypeAssertionExpression */: + ts.Debug.fail(); // Won't parse these in a JS file anyway, as they are interpreted as JSX. + } + var prevParent = parent; + parent = node; + ts.forEachChild(node, walk, walkArray); + parent = prevParent; + } + function walkArray(nodes) { + if (parent.decorators === nodes && !options.experimentalDecorators) { + diagnostics.push(createDiagnosticForNode(parent, ts.Diagnostics.Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_to_remove_this_warning)); + } + switch (parent.kind) { + case 240 /* ClassDeclaration */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 196 /* FunctionExpression */: + case 239 /* FunctionDeclaration */: + case 197 /* ArrowFunction */: + // Check type parameters + if (nodes === parent.typeParameters) { + diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.type_parameter_declarations_can_only_be_used_in_a_ts_file)); + return; + } + // falls through + case 219 /* VariableStatement */: + // Check modifiers + if (nodes === parent.modifiers) { + return checkModifiers(nodes, parent.kind === 219 /* VariableStatement */); + } + break; + case 154 /* PropertyDeclaration */: + // Check modifiers of property declaration + if (nodes === parent.modifiers) { + for (var _i = 0, _a = nodes; _i < _a.length; _i++) { + var modifier = _a[_i]; + if (modifier.kind !== 116 /* StaticKeyword */) { + diagnostics.push(createDiagnosticForNode(modifier, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, ts.tokenToString(modifier.kind))); + } + } + return; + } + break; + case 151 /* Parameter */: + // Check modifiers of parameter declaration + if (nodes === parent.modifiers) { + diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.parameter_modifiers_can_only_be_used_in_a_ts_file)); + return; + } + break; + case 191 /* CallExpression */: + case 192 /* NewExpression */: + case 211 /* ExpressionWithTypeArguments */: + case 261 /* JsxSelfClosingElement */: + case 262 /* JsxOpeningElement */: + // Check type arguments + if (nodes === parent.typeArguments) { + diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.type_arguments_can_only_be_used_in_a_ts_file)); + return; + } + break; + } + for (var _b = 0, nodes_6 = nodes; _b < nodes_6.length; _b++) { + var node = nodes_6[_b]; + walk(node); + } + } + function checkModifiers(modifiers, isConstValid) { + for (var _i = 0, modifiers_1 = modifiers; _i < modifiers_1.length; _i++) { + var modifier = modifiers_1[_i]; + switch (modifier.kind) { + case 77 /* ConstKeyword */: + if (isConstValid) { + continue; + } + // to report error, + // falls through + case 115 /* PublicKeyword */: + case 113 /* PrivateKeyword */: + case 114 /* ProtectedKeyword */: + case 133 /* ReadonlyKeyword */: + case 125 /* DeclareKeyword */: + case 118 /* AbstractKeyword */: + diagnostics.push(createDiagnosticForNode(modifier, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, ts.tokenToString(modifier.kind))); + break; + // These are all legal modifiers. + case 116 /* StaticKeyword */: + case 85 /* ExportKeyword */: + case 80 /* DefaultKeyword */: + } + } + } + function createDiagnosticForNodeArray(nodes, message, arg0, arg1, arg2) { + var start = nodes.pos; + return ts.createFileDiagnostic(sourceFile, start, nodes.end - start, message, arg0, arg1, arg2); + } + // Since these are syntactic diagnostics, parent might not have been set + // this means the sourceFile cannot be infered from the node + function createDiagnosticForNode(node, message, arg0, arg1, arg2) { + return ts.createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2); + } + }); + } + function getDeclarationDiagnosticsWorker(sourceFile, cancellationToken) { + return getAndCacheDiagnostics(sourceFile, cancellationToken, cachedDeclarationDiagnosticsForFile, getDeclarationDiagnosticsForFileNoCache); + } + function getDeclarationDiagnosticsForFileNoCache(sourceFile, cancellationToken) { + return runWithCancellationToken(function () { + var resolver = getDiagnosticsProducingTypeChecker().getEmitResolver(sourceFile, cancellationToken); + // Don't actually write any files since we're just getting diagnostics. + return ts.getDeclarationDiagnostics(getEmitHost(ts.noop), resolver, sourceFile); + }); + } + function getAndCacheDiagnostics(sourceFile, cancellationToken, cache, getDiagnostics) { + var cachedResult = sourceFile + ? cache.perFile && cache.perFile.get(sourceFile.path) + : cache.allDiagnostics; + if (cachedResult) { + return cachedResult; + } + var result = getDiagnostics(sourceFile, cancellationToken) || ts.emptyArray; // TODO: GH#18217 + if (sourceFile) { + if (!cache.perFile) { + cache.perFile = ts.createMap(); + } + cache.perFile.set(sourceFile.path, result); + } + else { + cache.allDiagnostics = result; + } + return result; + } + function getDeclarationDiagnosticsForFile(sourceFile, cancellationToken) { + return sourceFile.isDeclarationFile ? [] : getDeclarationDiagnosticsWorker(sourceFile, cancellationToken); + } + function getOptionsDiagnostics() { + return ts.sortAndDeduplicateDiagnostics(ts.concatenate(fileProcessingDiagnostics.getGlobalDiagnostics(), ts.concatenate(programDiagnostics.getGlobalDiagnostics(), getOptionsDiagnosticsOfConfigFile()))); + } + function getOptionsDiagnosticsOfConfigFile() { + if (!options.configFile) { + return ts.emptyArray; + } + var diagnostics = programDiagnostics.getDiagnostics(options.configFile.fileName); + forEachResolvedProjectReference(function (resolvedRef) { + if (resolvedRef) { + diagnostics = ts.concatenate(diagnostics, programDiagnostics.getDiagnostics(resolvedRef.sourceFile.fileName)); + } + }); + return diagnostics; + } + function getGlobalDiagnostics() { + return rootNames.length ? ts.sortAndDeduplicateDiagnostics(getDiagnosticsProducingTypeChecker().getGlobalDiagnostics().slice()) : ts.emptyArray; + } + function getConfigFileParsingDiagnostics() { + return configFileParsingDiagnostics || ts.emptyArray; + } + function processRootFile(fileName, isDefaultLib, ignoreNoDefaultLib) { + processSourceFile(ts.normalizePath(fileName), isDefaultLib, ignoreNoDefaultLib, /*packageId*/ undefined); + } + function fileReferenceIsEqualTo(a, b) { + return a.fileName === b.fileName; + } + function moduleNameIsEqualTo(a, b) { + return a.kind === 72 /* Identifier */ + ? b.kind === 72 /* Identifier */ && a.escapedText === b.escapedText + : b.kind === 10 /* StringLiteral */ && a.text === b.text; + } + function collectExternalModuleReferences(file) { + if (file.imports) { + return; + } + var isJavaScriptFile = ts.isSourceFileJS(file); + var isExternalModuleFile = ts.isExternalModule(file); + // file.imports may not be undefined if there exists dynamic import + var imports; + var moduleAugmentations; + var ambientModules; + // If we are importing helpers, we need to add a synthetic reference to resolve the + // helpers library. + if (options.importHelpers + && (options.isolatedModules || isExternalModuleFile) + && !file.isDeclarationFile) { + // synthesize 'import "tslib"' declaration + var externalHelpersModuleReference = ts.createLiteral(ts.externalHelpersModuleNameText); + var importDecl = ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*importClause*/ undefined, externalHelpersModuleReference); + ts.addEmitFlags(importDecl, 67108864 /* NeverApplyImportHelper */); + externalHelpersModuleReference.parent = importDecl; + importDecl.parent = file; + imports = [externalHelpersModuleReference]; + } + for (var _i = 0, _a = file.statements; _i < _a.length; _i++) { + var node = _a[_i]; + collectModuleReferences(node, /*inAmbientModule*/ false); + } + if ((file.flags & 524288 /* PossiblyContainsDynamicImport */) || isJavaScriptFile) { + collectDynamicImportOrRequireCalls(file); + } + file.imports = imports || ts.emptyArray; + file.moduleAugmentations = moduleAugmentations || ts.emptyArray; + file.ambientModuleNames = ambientModules || ts.emptyArray; + return; + function collectModuleReferences(node, inAmbientModule) { + if (ts.isAnyImportOrReExport(node)) { + var moduleNameExpr = ts.getExternalModuleName(node); + // TypeScript 1.0 spec (April 2014): 12.1.6 + // An ExternalImportDeclaration in an AmbientExternalModuleDeclaration may reference other external modules + // only through top - level external module names. Relative external module names are not permitted. + if (moduleNameExpr && ts.isStringLiteral(moduleNameExpr) && moduleNameExpr.text && (!inAmbientModule || !ts.isExternalModuleNameRelative(moduleNameExpr.text))) { + imports = ts.append(imports, moduleNameExpr); + } + } + else if (ts.isModuleDeclaration(node)) { + if (ts.isAmbientModule(node) && (inAmbientModule || ts.hasModifier(node, 2 /* Ambient */) || file.isDeclarationFile)) { + var nameText = ts.getTextOfIdentifierOrLiteral(node.name); + // Ambient module declarations can be interpreted as augmentations for some existing external modules. + // This will happen in two cases: + // - if current file is external module then module augmentation is a ambient module declaration defined in the top level scope + // - if current file is not external module then module augmentation is an ambient module declaration with non-relative module name + // immediately nested in top level ambient module declaration . + if (isExternalModuleFile || (inAmbientModule && !ts.isExternalModuleNameRelative(nameText))) { + (moduleAugmentations || (moduleAugmentations = [])).push(node.name); + } + else if (!inAmbientModule) { + if (file.isDeclarationFile) { + // for global .d.ts files record name of ambient module + (ambientModules || (ambientModules = [])).push(nameText); + } + // An AmbientExternalModuleDeclaration declares an external module. + // This type of declaration is permitted only in the global module. + // The StringLiteral must specify a top - level external module name. + // Relative external module names are not permitted + // NOTE: body of ambient module is always a module block, if it exists + var body = node.body; + if (body) { + for (var _i = 0, _a = body.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + collectModuleReferences(statement, /*inAmbientModule*/ true); + } + } + } + } + } + } + function collectDynamicImportOrRequireCalls(file) { + var r = /import|require/g; + while (r.exec(file.text) !== null) { + var node = getNodeAtPosition(file, r.lastIndex); + if (ts.isRequireCall(node, /*checkArgumentIsStringLiteralLike*/ true)) { + imports = ts.append(imports, node.arguments[0]); + } + // we have to check the argument list has length of 1. We will still have to process these even though we have parsing error. + else if (ts.isImportCall(node) && node.arguments.length === 1 && ts.isStringLiteralLike(node.arguments[0])) { + imports = ts.append(imports, node.arguments[0]); + } + else if (ts.isLiteralImportTypeNode(node)) { + imports = ts.append(imports, node.argument.literal); + } + } + } + /** Returns a token if position is in [start-of-leading-trivia, end), includes JSDoc only in JS files */ + function getNodeAtPosition(sourceFile, position) { + var current = sourceFile; + var getContainingChild = function (child) { + if (child.pos <= position && (position < child.end || (position === child.end && (child.kind === 1 /* EndOfFileToken */)))) { + return child; + } + }; + while (true) { + var child = isJavaScriptFile && ts.hasJSDocNodes(current) && ts.forEach(current.jsDoc, getContainingChild) || ts.forEachChild(current, getContainingChild); + if (!child) { + return current; + } + current = child; + } + } + } + function getLibFileFromReference(ref) { + var libName = ref.fileName.toLocaleLowerCase(); + var libFileName = ts.libMap.get(libName); + if (libFileName) { + return getSourceFile(ts.combinePaths(defaultLibraryPath, libFileName)); + } + } + /** This should have similar behavior to 'processSourceFile' without diagnostics or mutation. */ + function getSourceFileFromReference(referencingFile, ref) { + return getSourceFileFromReferenceWorker(resolveTripleslashReference(ref.fileName, referencingFile.fileName), function (fileName) { return filesByName.get(toPath(fileName)); }); + } + function getSourceFileFromReferenceWorker(fileName, getSourceFile, fail, refFile) { + if (ts.hasExtension(fileName)) { + if (!options.allowNonTsExtensions && !ts.forEach(supportedExtensionsWithJsonIfResolveJsonModule, function (extension) { return ts.fileExtensionIs(host.getCanonicalFileName(fileName), extension); })) { + if (fail) + fail(ts.Diagnostics.File_0_has_unsupported_extension_The_only_supported_extensions_are_1, fileName, "'" + supportedExtensions.join("', '") + "'"); + return undefined; + } + var sourceFile = getSourceFile(fileName); + if (fail) { + if (!sourceFile) { + var redirect = getProjectReferenceRedirect(fileName); + if (redirect) { + fail(ts.Diagnostics.Output_file_0_has_not_been_built_from_source_file_1, redirect, fileName); + } + else { + fail(ts.Diagnostics.File_0_not_found, fileName); + } + } + else if (refFile && host.getCanonicalFileName(fileName) === host.getCanonicalFileName(refFile.fileName)) { + fail(ts.Diagnostics.A_file_cannot_have_a_reference_to_itself); + } + } + return sourceFile; + } + else { + var sourceFileNoExtension = options.allowNonTsExtensions && getSourceFile(fileName); + if (sourceFileNoExtension) + return sourceFileNoExtension; + if (fail && options.allowNonTsExtensions) { + fail(ts.Diagnostics.File_0_not_found, fileName); + return undefined; + } + var sourceFileWithAddedExtension = ts.forEach(supportedExtensions, function (extension) { return getSourceFile(fileName + extension); }); + if (fail && !sourceFileWithAddedExtension) + fail(ts.Diagnostics.File_0_not_found, fileName + ".ts" /* Ts */); + return sourceFileWithAddedExtension; + } + } + /** This has side effects through `findSourceFile`. */ + function processSourceFile(fileName, isDefaultLib, ignoreNoDefaultLib, packageId, refFile, refPos, refEnd) { + getSourceFileFromReferenceWorker(fileName, function (fileName) { return findSourceFile(fileName, toPath(fileName), isDefaultLib, ignoreNoDefaultLib, refFile, refPos, refEnd, packageId); }, // TODO: GH#18217 + function (diagnostic) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + fileProcessingDiagnostics.add(refFile !== undefined && refEnd !== undefined && refPos !== undefined + ? ts.createFileDiagnostic.apply(void 0, [refFile, refPos, refEnd - refPos, diagnostic].concat(args)) : ts.createCompilerDiagnostic.apply(void 0, [diagnostic].concat(args))); + }, refFile); + } + function reportFileNamesDifferOnlyInCasingError(fileName, existingFileName, refFile, refPos, refEnd) { + if (refFile !== undefined && refPos !== undefined && refEnd !== undefined) { + fileProcessingDiagnostics.add(ts.createFileDiagnostic(refFile, refPos, refEnd - refPos, ts.Diagnostics.File_name_0_differs_from_already_included_file_name_1_only_in_casing, fileName, existingFileName)); + } + else { + fileProcessingDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_name_0_differs_from_already_included_file_name_1_only_in_casing, fileName, existingFileName)); + } + } + function createRedirectSourceFile(redirectTarget, unredirected, fileName, path, resolvedPath, originalFileName) { + var redirect = Object.create(redirectTarget); + redirect.fileName = fileName; + redirect.path = path; + redirect.resolvedPath = resolvedPath; + redirect.originalFileName = originalFileName; + redirect.redirectInfo = { redirectTarget: redirectTarget, unredirected: unredirected }; + sourceFilesFoundSearchingNodeModules.set(path, currentNodeModulesDepth > 0); + Object.defineProperties(redirect, { + id: { + get: function () { return this.redirectInfo.redirectTarget.id; }, + set: function (value) { this.redirectInfo.redirectTarget.id = value; }, + }, + symbol: { + get: function () { return this.redirectInfo.redirectTarget.symbol; }, + set: function (value) { this.redirectInfo.redirectTarget.symbol = value; }, + }, + }); + return redirect; + } + // Get source file from normalized fileName + function findSourceFile(fileName, path, isDefaultLib, ignoreNoDefaultLib, refFile, refPos, refEnd, packageId) { + var originalFileName = fileName; + if (filesByName.has(path)) { + var file_1 = filesByName.get(path); + // try to check if we've already seen this file but with a different casing in path + // NOTE: this only makes sense for case-insensitive file systems, and only on files which are not redirected + if (file_1 && options.forceConsistentCasingInFileNames) { + var inputName = fileName; + var checkedName = file_1.fileName; + var isRedirect = toPath(checkedName) !== toPath(inputName); + if (isRedirect) { + inputName = getProjectReferenceRedirect(fileName) || fileName; + } + if (ts.getNormalizedAbsolutePath(checkedName, currentDirectory) !== ts.getNormalizedAbsolutePath(inputName, currentDirectory)) { + reportFileNamesDifferOnlyInCasingError(inputName, checkedName, refFile, refPos, refEnd); + } + } + // If the file was previously found via a node_modules search, but is now being processed as a root file, + // then everything it sucks in may also be marked incorrectly, and needs to be checked again. + if (file_1 && sourceFilesFoundSearchingNodeModules.get(file_1.path) && currentNodeModulesDepth === 0) { + sourceFilesFoundSearchingNodeModules.set(file_1.path, false); + if (!options.noResolve) { + processReferencedFiles(file_1, isDefaultLib); + processTypeReferenceDirectives(file_1); + } + processLibReferenceDirectives(file_1); + modulesWithElidedImports.set(file_1.path, false); + processImportedModules(file_1); + } + // See if we need to reprocess the imports due to prior skipped imports + else if (file_1 && modulesWithElidedImports.get(file_1.path)) { + if (currentNodeModulesDepth < maxNodeModuleJsDepth) { + modulesWithElidedImports.set(file_1.path, false); + processImportedModules(file_1); + } + } + return file_1; + } + var redirectedPath; + if (refFile) { + var redirect = getProjectReferenceRedirect(fileName); + if (redirect) { + (refFile.redirectedReferences || (refFile.redirectedReferences = [])).push(fileName); + fileName = redirect; + // Once we start redirecting to a file, we can potentially come back to it + // via a back-reference from another file in the .d.ts folder. If that happens we'll + // end up trying to add it to the program *again* because we were tracking it via its + // original (un-redirected) name. So we have to map both the original path and the redirected path + // to the source file we're about to find/create + redirectedPath = toPath(redirect); + } + } + // We haven't looked for this file, do so now and cache result + var file = host.getSourceFile(fileName, options.target, function (hostErrorMessage) { + if (refFile !== undefined && refPos !== undefined && refEnd !== undefined) { + fileProcessingDiagnostics.add(ts.createFileDiagnostic(refFile, refPos, refEnd - refPos, ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, hostErrorMessage)); + } + else { + fileProcessingDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, hostErrorMessage)); + } + }, shouldCreateNewSourceFile); + if (packageId) { + var packageIdKey = ts.packageIdToString(packageId); + var fileFromPackageId = packageIdToSourceFile.get(packageIdKey); + if (fileFromPackageId) { + // Some other SourceFile already exists with this package name and version. + // Instead of creating a duplicate, just redirect to the existing one. + var dupFile = createRedirectSourceFile(fileFromPackageId, file, fileName, path, toPath(fileName), originalFileName); // TODO: GH#18217 + redirectTargetsMap.add(fileFromPackageId.path, fileName); + addFileToFilesByName(dupFile, path, redirectedPath); + sourceFileToPackageName.set(path, packageId.name); + processingOtherFiles.push(dupFile); + return dupFile; + } + else if (file) { + // This is the first source file to have this packageId. + packageIdToSourceFile.set(packageIdKey, file); + sourceFileToPackageName.set(path, packageId.name); + } + } + addFileToFilesByName(file, path, redirectedPath); + if (file) { + sourceFilesFoundSearchingNodeModules.set(path, currentNodeModulesDepth > 0); + file.path = path; + file.resolvedPath = toPath(fileName); + file.originalFileName = originalFileName; + if (host.useCaseSensitiveFileNames()) { + var pathLowerCase = path.toLowerCase(); + // for case-sensitive file systems check if we've already seen some file with similar filename ignoring case + var existingFile = filesByNameIgnoreCase.get(pathLowerCase); + if (existingFile) { + reportFileNamesDifferOnlyInCasingError(fileName, existingFile.fileName, refFile, refPos, refEnd); + } + else { + filesByNameIgnoreCase.set(pathLowerCase, file); + } + } + skipDefaultLib = skipDefaultLib || (file.hasNoDefaultLib && !ignoreNoDefaultLib); + if (!options.noResolve) { + processReferencedFiles(file, isDefaultLib); + processTypeReferenceDirectives(file); + } + processLibReferenceDirectives(file); + // always process imported modules to record module name resolutions + processImportedModules(file); + if (isDefaultLib) { + processingDefaultLibFiles.push(file); + } + else { + processingOtherFiles.push(file); + } + } + return file; + } + function addFileToFilesByName(file, path, redirectedPath) { + filesByName.set(path, file); + if (redirectedPath) { + filesByName.set(redirectedPath, file); + } + } + function getProjectReferenceRedirect(fileName) { + // Ignore dts or any of the non ts files + if (!resolvedProjectReferences || !resolvedProjectReferences.length || ts.fileExtensionIs(fileName, ".d.ts" /* Dts */) || !ts.fileExtensionIsOneOf(fileName, ts.supportedTSExtensions)) { + return undefined; + } + // If this file is produced by a referenced project, we need to rewrite it to + // look in the output folder of the referenced project rather than the input + var referencedProject = getResolvedProjectReferenceToRedirect(fileName); + if (!referencedProject) { + return undefined; + } + var out = referencedProject.commandLine.options.outFile || referencedProject.commandLine.options.out; + return out ? + ts.changeExtension(out, ".d.ts" /* Dts */) : + ts.getOutputDeclarationFileName(fileName, referencedProject.commandLine); + } + /** + * Get the referenced project if the file is input file from that reference project + */ + function getResolvedProjectReferenceToRedirect(fileName) { + if (mapFromFileToProjectReferenceRedirects === undefined) { + mapFromFileToProjectReferenceRedirects = ts.createMap(); + forEachResolvedProjectReference(function (referencedProject, referenceProjectPath) { + // not input file from the referenced project, ignore + if (referencedProject && + toPath(options.configFilePath) !== referenceProjectPath) { + referencedProject.commandLine.fileNames.forEach(function (f) { + return mapFromFileToProjectReferenceRedirects.set(toPath(f), referenceProjectPath); + }); + } + }); + } + var referencedProjectPath = mapFromFileToProjectReferenceRedirects.get(toPath(fileName)); + return referencedProjectPath && getResolvedProjectReferenceByPath(referencedProjectPath); + } + function forEachResolvedProjectReference(cb) { + return forEachProjectReference(projectReferences, resolvedProjectReferences, function (resolvedRef, index, parent) { + var ref = (parent ? parent.commandLine.projectReferences : projectReferences)[index]; + var resolvedRefPath = toPath(resolveProjectReferencePath(ref)); + return cb(resolvedRef, resolvedRefPath); + }); + } + function forEachProjectReference(projectReferences, resolvedProjectReferences, cbResolvedRef, cbRef) { + var seenResolvedRefs; + return worker(projectReferences, resolvedProjectReferences, /*parent*/ undefined, cbResolvedRef, cbRef); + function worker(projectReferences, resolvedProjectReferences, parent, cbResolvedRef, cbRef) { + // Visit project references first + if (cbRef) { + var result = cbRef(projectReferences, parent); + if (result) { + return result; + } + } + return ts.forEach(resolvedProjectReferences, function (resolvedRef, index) { + if (ts.contains(seenResolvedRefs, resolvedRef)) { + // ignore recursives + return undefined; + } + var result = cbResolvedRef(resolvedRef, index, parent); + if (result) { + return result; + } + if (!resolvedRef) + return undefined; + (seenResolvedRefs || (seenResolvedRefs = [])).push(resolvedRef); + return worker(resolvedRef.commandLine.projectReferences, resolvedRef.references, resolvedRef, cbResolvedRef, cbRef); + }); + } + } + function getResolvedProjectReferenceByPath(projectReferencePath) { + if (!projectReferenceRedirects) { + return undefined; + } + return projectReferenceRedirects.get(projectReferencePath) || undefined; + } + function processReferencedFiles(file, isDefaultLib) { + ts.forEach(file.referencedFiles, function (ref) { + var referencedFileName = resolveTripleslashReference(ref.fileName, file.originalFileName); + processSourceFile(referencedFileName, isDefaultLib, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined, file, ref.pos, ref.end); + }); + } + function processTypeReferenceDirectives(file) { + // We lower-case all type references because npm automatically lowercases all packages. See GH#9824. + var typeDirectives = ts.map(file.typeReferenceDirectives, function (ref) { return ref.fileName.toLocaleLowerCase(); }); + if (!typeDirectives) { + return; + } + var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeDirectives, file.originalFileName, getResolvedProjectReferenceToRedirect(file.originalFileName)); + for (var i = 0; i < typeDirectives.length; i++) { + var ref = file.typeReferenceDirectives[i]; + var resolvedTypeReferenceDirective = resolutions[i]; + // store resolved type directive on the file + var fileName = ref.fileName.toLocaleLowerCase(); + ts.setResolvedTypeReferenceDirective(file, fileName, resolvedTypeReferenceDirective); + processTypeReferenceDirective(fileName, resolvedTypeReferenceDirective, file, ref.pos, ref.end); + } + } + function processTypeReferenceDirective(typeReferenceDirective, resolvedTypeReferenceDirective, refFile, refPos, refEnd) { + // If we already found this library as a primary reference - nothing to do + var previousResolution = resolvedTypeReferenceDirectives.get(typeReferenceDirective); + if (previousResolution && previousResolution.primary) { + return; + } + var saveResolution = true; + if (resolvedTypeReferenceDirective) { + if (resolvedTypeReferenceDirective.isExternalLibraryImport) + currentNodeModulesDepth++; + if (resolvedTypeReferenceDirective.primary) { + // resolved from the primary path + processSourceFile(resolvedTypeReferenceDirective.resolvedFileName, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, resolvedTypeReferenceDirective.packageId, refFile, refPos, refEnd); // TODO: GH#18217 + } + else { + // If we already resolved to this file, it must have been a secondary reference. Check file contents + // for sameness and possibly issue an error + if (previousResolution) { + // Don't bother reading the file again if it's the same file. + if (resolvedTypeReferenceDirective.resolvedFileName !== previousResolution.resolvedFileName) { + var otherFileText = host.readFile(resolvedTypeReferenceDirective.resolvedFileName); + if (otherFileText !== getSourceFile(previousResolution.resolvedFileName).text) { + fileProcessingDiagnostics.add(createDiagnostic(refFile, refPos, refEnd, // TODO: GH#18217 + ts.Diagnostics.Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict, typeReferenceDirective, resolvedTypeReferenceDirective.resolvedFileName, previousResolution.resolvedFileName)); + } + } + // don't overwrite previous resolution result + saveResolution = false; + } + else { + // First resolution of this library + processSourceFile(resolvedTypeReferenceDirective.resolvedFileName, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, resolvedTypeReferenceDirective.packageId, refFile, refPos, refEnd); + } + } + if (resolvedTypeReferenceDirective.isExternalLibraryImport) + currentNodeModulesDepth--; + } + else { + fileProcessingDiagnostics.add(createDiagnostic(refFile, refPos, refEnd, ts.Diagnostics.Cannot_find_type_definition_file_for_0, typeReferenceDirective)); // TODO: GH#18217 + } + if (saveResolution) { + resolvedTypeReferenceDirectives.set(typeReferenceDirective, resolvedTypeReferenceDirective); + } + } + function processLibReferenceDirectives(file) { + ts.forEach(file.libReferenceDirectives, function (libReference) { + var libName = libReference.fileName.toLocaleLowerCase(); + var libFileName = ts.libMap.get(libName); + if (libFileName) { + // we ignore any 'no-default-lib' reference set on this file. + processRootFile(ts.combinePaths(defaultLibraryPath, libFileName), /*isDefaultLib*/ true, /*ignoreNoDefaultLib*/ true); + } + else { + var unqualifiedLibName = ts.removeSuffix(ts.removePrefix(libName, "lib."), ".d.ts"); + var suggestion = ts.getSpellingSuggestion(unqualifiedLibName, ts.libs, ts.identity); + var message = suggestion ? ts.Diagnostics.Cannot_find_lib_definition_for_0_Did_you_mean_1 : ts.Diagnostics.Cannot_find_lib_definition_for_0; + fileProcessingDiagnostics.add(createDiagnostic(file, libReference.pos, libReference.end, message, libName, suggestion)); + } + }); + } + function createDiagnostic(refFile, refPos, refEnd, message) { + var args = []; + for (var _i = 4; _i < arguments.length; _i++) { + args[_i - 4] = arguments[_i]; + } + if (refFile === undefined || refPos === undefined || refEnd === undefined) { + return ts.createCompilerDiagnostic.apply(void 0, [message].concat(args)); + } + else { + return ts.createFileDiagnostic.apply(void 0, [refFile, refPos, refEnd - refPos, message].concat(args)); + } + } + function getCanonicalFileName(fileName) { + return host.getCanonicalFileName(fileName); + } + function processImportedModules(file) { + collectExternalModuleReferences(file); + if (file.imports.length || file.moduleAugmentations.length) { + // Because global augmentation doesn't have string literal name, we can check for global augmentation as such. + var moduleNames = getModuleNames(file); + var resolutions = resolveModuleNamesReusingOldState(moduleNames, ts.getNormalizedAbsolutePath(file.originalFileName, currentDirectory), file); + ts.Debug.assert(resolutions.length === moduleNames.length); + for (var i = 0; i < moduleNames.length; i++) { + var resolution = resolutions[i]; + ts.setResolvedModule(file, moduleNames[i], resolution); + if (!resolution) { + continue; + } + var isFromNodeModulesSearch = resolution.isExternalLibraryImport; + var isJsFile = !ts.resolutionExtensionIsTSOrJson(resolution.extension); + var isJsFileFromNodeModules = isFromNodeModulesSearch && isJsFile; + var resolvedFileName = resolution.resolvedFileName; + if (isFromNodeModulesSearch) { + currentNodeModulesDepth++; + } + // add file to program only if: + // - resolution was successful + // - noResolve is falsy + // - module name comes from the list of imports + // - it's not a top level JavaScript module that exceeded the search max + var elideImport = isJsFileFromNodeModules && currentNodeModulesDepth > maxNodeModuleJsDepth; + // Don't add the file if it has a bad extension (e.g. 'tsx' if we don't have '--allowJs') + // This may still end up being an untyped module -- the file won't be included but imports will be allowed. + var shouldAddFile = resolvedFileName + && !getResolutionDiagnostic(options, resolution) + && !options.noResolve + && i < file.imports.length + && !elideImport + && !(isJsFile && !options.allowJs) + && (ts.isInJSFile(file.imports[i]) || !(file.imports[i].flags & 2097152 /* JSDoc */)); + if (elideImport) { + modulesWithElidedImports.set(file.path, true); + } + else if (shouldAddFile) { + var path = toPath(resolvedFileName); + var pos = ts.skipTrivia(file.text, file.imports[i].pos); + findSourceFile(resolvedFileName, path, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, file, pos, file.imports[i].end, resolution.packageId); + } + if (isFromNodeModulesSearch) { + currentNodeModulesDepth--; + } + } + } + else { + // no imports - drop cached module resolutions + file.resolvedModules = undefined; + } + } + function computeCommonSourceDirectory(sourceFiles) { + var fileNames = ts.mapDefined(sourceFiles, function (file) { return file.isDeclarationFile ? undefined : file.fileName; }); + return computeCommonSourceDirectoryOfFilenames(fileNames, currentDirectory, getCanonicalFileName); + } + function checkSourceFilesBelongToPath(sourceFiles, rootDirectory) { + var allFilesBelongToPath = true; + var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory)); + for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) { + var sourceFile = sourceFiles_2[_i]; + if (!sourceFile.isDeclarationFile) { + var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); + if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, sourceFile.fileName, rootDirectory)); + allFilesBelongToPath = false; + } + } + } + return allFilesBelongToPath; + } + function parseProjectReferenceConfigFile(ref) { + if (!projectReferenceRedirects) { + projectReferenceRedirects = ts.createMap(); + } + // The actual filename (i.e. add "/tsconfig.json" if necessary) + var refPath = resolveProjectReferencePath(ref); + var sourceFilePath = toPath(refPath); + var fromCache = projectReferenceRedirects.get(sourceFilePath); + if (fromCache !== undefined) { + return fromCache || undefined; + } + // An absolute path pointing to the containing directory of the config file + var basePath = ts.getNormalizedAbsolutePath(ts.getDirectoryPath(refPath), host.getCurrentDirectory()); + var sourceFile = host.getSourceFile(refPath, 100 /* JSON */); + addFileToFilesByName(sourceFile, sourceFilePath, /*redirectedPath*/ undefined); + if (sourceFile === undefined) { + projectReferenceRedirects.set(sourceFilePath, false); + return undefined; + } + sourceFile.path = sourceFilePath; + sourceFile.resolvedPath = sourceFilePath; + sourceFile.originalFileName = refPath; + var commandLine = ts.parseJsonSourceFileConfigFileContent(sourceFile, configParsingHost, basePath, /*existingOptions*/ undefined, refPath); + var resolvedRef = { commandLine: commandLine, sourceFile: sourceFile }; + projectReferenceRedirects.set(sourceFilePath, resolvedRef); + if (commandLine.projectReferences) { + resolvedRef.references = commandLine.projectReferences.map(parseProjectReferenceConfigFile); + } + return resolvedRef; + } + function verifyCompilerOptions() { + if (options.strictPropertyInitialization && !ts.getStrictOptionValue(options, "strictNullChecks")) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "strictPropertyInitialization", "strictNullChecks"); + } + if (options.isolatedModules) { + if (ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, getEmitDeclarationOptionName(options), "isolatedModules"); + } + if (options.noEmitOnError) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmitOnError", "isolatedModules"); + } + if (options.out) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "out", "isolatedModules"); + } + if (options.outFile) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "outFile", "isolatedModules"); + } + } + if (options.inlineSourceMap) { + if (options.sourceMap) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "sourceMap", "inlineSourceMap"); + } + if (options.mapRoot) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "mapRoot", "inlineSourceMap"); + } + } + if (options.paths && options.baseUrl === undefined) { + createDiagnosticForOptionName(ts.Diagnostics.Option_paths_cannot_be_used_without_specifying_baseUrl_option, "paths"); + } + if (options.composite) { + if (options.declaration === false) { + createDiagnosticForOptionName(ts.Diagnostics.Composite_projects_may_not_disable_declaration_emit, "declaration"); + } + } + verifyProjectReferences(); + // List of collected files is complete; validate exhautiveness if this is a project with a file list + if (options.composite) { + var sourceFiles = files.filter(function (f) { return !f.isDeclarationFile; }); + if (rootNames.length < sourceFiles.length) { + var normalizedRootNames = rootNames.map(function (r) { return ts.normalizePath(r).toLowerCase(); }); + for (var _i = 0, _a = sourceFiles.map(function (f) { return ts.normalizePath(f.path).toLowerCase(); }); _i < _a.length; _i++) { + var file = _a[_i]; + if (normalizedRootNames.indexOf(file) === -1) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern, file)); + } + } + } + } + if (options.paths) { + for (var key in options.paths) { + if (!ts.hasProperty(options.paths, key)) { + continue; + } + if (!ts.hasZeroOrOneAsteriskCharacter(key)) { + createDiagnosticForOptionPaths(/*onKey*/ true, key, ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, key); + } + if (ts.isArray(options.paths[key])) { + var len = options.paths[key].length; + if (len === 0) { + createDiagnosticForOptionPaths(/*onKey*/ false, key, ts.Diagnostics.Substitutions_for_pattern_0_shouldn_t_be_an_empty_array, key); + } + for (var i = 0; i < len; i++) { + var subst = options.paths[key][i]; + var typeOfSubst = typeof subst; + if (typeOfSubst === "string") { + if (!ts.hasZeroOrOneAsteriskCharacter(subst)) { + createDiagnosticForOptionPathKeyValue(key, i, ts.Diagnostics.Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character, subst, key); + } + } + else { + createDiagnosticForOptionPathKeyValue(key, i, ts.Diagnostics.Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2, subst, key, typeOfSubst); + } + } + } + else { + createDiagnosticForOptionPaths(/*onKey*/ false, key, ts.Diagnostics.Substitutions_for_pattern_0_should_be_an_array, key); + } + } + } + if (!options.sourceMap && !options.inlineSourceMap) { + if (options.inlineSources) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided, "inlineSources"); + } + if (options.sourceRoot) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided, "sourceRoot"); + } + } + if (options.out && options.outFile) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "out", "outFile"); + } + if (options.mapRoot && !(options.sourceMap || options.declarationMap)) { + // Error to specify --mapRoot without --sourcemap + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "mapRoot", "sourceMap", "declarationMap"); + } + if (options.declarationDir) { + if (!ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "declarationDir", "declaration", "composite"); + } + if (options.out || options.outFile) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "declarationDir", options.out ? "out" : "outFile"); + } + } + if (options.declarationMap && !ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "declarationMap", "declaration", "composite"); + } + if (options.lib && options.noLib) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "lib", "noLib"); + } + if (options.noImplicitUseStrict && ts.getStrictOptionValue(options, "alwaysStrict")) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noImplicitUseStrict", "alwaysStrict"); + } + var languageVersion = options.target || 0 /* ES3 */; + var outFile = options.outFile || options.out; + var firstNonAmbientExternalModuleSourceFile = ts.find(files, function (f) { return ts.isExternalModule(f) && !f.isDeclarationFile; }); + if (options.isolatedModules) { + if (options.module === ts.ModuleKind.None && languageVersion < 2 /* ES2015 */) { + createDiagnosticForOptionName(ts.Diagnostics.Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher, "isolatedModules", "target"); + } + var firstNonExternalModuleSourceFile = ts.find(files, function (f) { return !ts.isExternalModule(f) && !f.isDeclarationFile && f.scriptKind !== 6 /* JSON */; }); + if (firstNonExternalModuleSourceFile) { + var span = ts.getErrorSpanForNode(firstNonExternalModuleSourceFile, firstNonExternalModuleSourceFile); + programDiagnostics.add(ts.createFileDiagnostic(firstNonExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided)); + } + } + else if (firstNonAmbientExternalModuleSourceFile && languageVersion < 2 /* ES2015 */ && options.module === ts.ModuleKind.None) { + // We cannot use createDiagnosticFromNode because nodes do not have parents yet + var span = ts.getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, firstNonAmbientExternalModuleSourceFile.externalModuleIndicator); + programDiagnostics.add(ts.createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_use_imports_exports_or_module_augmentations_when_module_is_none)); + } + // Cannot specify module gen that isn't amd or system with --out + if (outFile && !options.emitDeclarationOnly) { + if (options.module && !(options.module === ts.ModuleKind.AMD || options.module === ts.ModuleKind.System)) { + createDiagnosticForOptionName(ts.Diagnostics.Only_amd_and_system_modules_are_supported_alongside_0, options.out ? "out" : "outFile", "module"); + } + else if (options.module === undefined && firstNonAmbientExternalModuleSourceFile) { + var span = ts.getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, firstNonAmbientExternalModuleSourceFile.externalModuleIndicator); + programDiagnostics.add(ts.createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system, options.out ? "out" : "outFile")); + } + } + if (options.resolveJsonModule) { + if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { + createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy, "resolveJsonModule"); + } + // Any emit other than common js, amd, es2015 or esnext is error + else if (!ts.hasJsonModuleEmitEnabled(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_esNext, "resolveJsonModule", "module"); + } + } + // there has to be common source directory if user specified --outdir || --sourceRoot + // if user specified --mapRoot, there needs to be common source directory if there would be multiple files being emitted + if (options.outDir || // there is --outDir specified + options.sourceRoot || // there is --sourceRoot specified + options.mapRoot) { // there is --mapRoot specified + // Precalculate and cache the common source directory + var dir = getCommonSourceDirectory(); + // If we failed to find a good common directory, but outDir is specified and at least one of our files is on a windows drive/URL/other resource, add a failure + if (options.outDir && dir === "" && files.some(function (file) { return ts.getRootLength(file.fileName) > 1; })) { + createDiagnosticForOptionName(ts.Diagnostics.Cannot_find_the_common_subdirectory_path_for_the_input_files, "outDir"); + } + } + if (!options.noEmit && options.allowJs && ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "allowJs", getEmitDeclarationOptionName(options)); + } + if (options.checkJs && !options.allowJs) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "checkJs", "allowJs")); + } + if (options.emitDeclarationOnly) { + if (!ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "emitDeclarationOnly", "declaration", "composite"); + } + if (options.noEmit) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "emitDeclarationOnly", "noEmit"); + } + } + if (options.emitDecoratorMetadata && + !options.experimentalDecorators) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDecoratorMetadata", "experimentalDecorators"); + } + if (options.jsxFactory) { + if (options.reactNamespace) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "reactNamespace", "jsxFactory"); + } + if (!ts.parseIsolatedEntityName(options.jsxFactory, languageVersion)) { + createOptionValueDiagnostic("jsxFactory", ts.Diagnostics.Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name, options.jsxFactory); + } + } + else if (options.reactNamespace && !ts.isIdentifierText(options.reactNamespace, languageVersion)) { + createOptionValueDiagnostic("reactNamespace", ts.Diagnostics.Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier, options.reactNamespace); + } + // If the emit is enabled make sure that every output file is unique and not overwriting any of the input files + if (!options.noEmit && !options.suppressOutputPathCheck) { + var emitHost = getEmitHost(); + var emitFilesSeen_1 = ts.createMap(); + ts.forEachEmittedFile(emitHost, function (emitFileNames) { + if (!options.emitDeclarationOnly) { + verifyEmitFilePath(emitFileNames.jsFilePath, emitFilesSeen_1); + } + verifyEmitFilePath(emitFileNames.declarationFilePath, emitFilesSeen_1); + }); + } + // Verify that all the emit files are unique and don't overwrite input files + function verifyEmitFilePath(emitFileName, emitFilesSeen) { + if (emitFileName) { + var emitFilePath = toPath(emitFileName); + // Report error if the output overwrites input file + if (filesByName.has(emitFilePath)) { + var chain_2; + if (!options.configFilePath) { + // The program is from either an inferred project or an external project + chain_2 = ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig); + } + chain_2 = ts.chainDiagnosticMessages(chain_2, ts.Diagnostics.Cannot_write_file_0_because_it_would_overwrite_input_file, emitFileName); + blockEmittingOfFile(emitFileName, ts.createCompilerDiagnosticFromMessageChain(chain_2)); + } + var emitFileKey = !host.useCaseSensitiveFileNames() ? emitFilePath.toLocaleLowerCase() : emitFilePath; + // Report error if multiple files write into same file + if (emitFilesSeen.has(emitFileKey)) { + // Already seen the same emit file - report error + blockEmittingOfFile(emitFileName, ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files, emitFileName)); + } + else { + emitFilesSeen.set(emitFileKey, true); + } + } + } + } + function verifyProjectReferences() { + forEachProjectReference(projectReferences, resolvedProjectReferences, function (resolvedRef, index, parent) { + var ref = (parent ? parent.commandLine.projectReferences : projectReferences)[index]; + var parentFile = parent && parent.sourceFile; + if (!resolvedRef) { + createDiagnosticForReference(parentFile, index, ts.Diagnostics.File_0_not_found, ref.path); + return; + } + var options = resolvedRef.commandLine.options; + if (!options.composite) { + // ok to not have composite if the current program is container only + var inputs = parent ? parent.commandLine.fileNames : rootNames; + if (inputs.length) { + createDiagnosticForReference(parentFile, index, ts.Diagnostics.Referenced_project_0_must_have_setting_composite_Colon_true, ref.path); + } + } + if (ref.prepend) { + var out = options.outFile || options.out; + if (out) { + if (!host.fileExists(out)) { + createDiagnosticForReference(parentFile, index, ts.Diagnostics.Output_file_0_from_project_1_does_not_exist, out, ref.path); + } + } + else { + createDiagnosticForReference(parentFile, index, ts.Diagnostics.Cannot_prepend_project_0_because_it_does_not_have_outFile_set, ref.path); + } + } + }); + } + function createDiagnosticForOptionPathKeyValue(key, valueIndex, message, arg0, arg1, arg2) { + var needCompilerDiagnostic = true; + var pathsSyntax = getOptionPathsSyntax(); + for (var _i = 0, pathsSyntax_1 = pathsSyntax; _i < pathsSyntax_1.length; _i++) { + var pathProp = pathsSyntax_1[_i]; + if (ts.isObjectLiteralExpression(pathProp.initializer)) { + for (var _a = 0, _b = ts.getPropertyAssignment(pathProp.initializer, key); _a < _b.length; _a++) { + var keyProps = _b[_a]; + var initializer = keyProps.initializer; + if (ts.isArrayLiteralExpression(initializer) && initializer.elements.length > valueIndex) { + programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(options.configFile, initializer.elements[valueIndex], message, arg0, arg1, arg2)); + needCompilerDiagnostic = false; + } + } + } + } + if (needCompilerDiagnostic) { + programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1, arg2)); + } + } + function createDiagnosticForOptionPaths(onKey, key, message, arg0) { + var needCompilerDiagnostic = true; + var pathsSyntax = getOptionPathsSyntax(); + for (var _i = 0, pathsSyntax_2 = pathsSyntax; _i < pathsSyntax_2.length; _i++) { + var pathProp = pathsSyntax_2[_i]; + if (ts.isObjectLiteralExpression(pathProp.initializer) && + createOptionDiagnosticInObjectLiteralSyntax(pathProp.initializer, onKey, key, /*key2*/ undefined, message, arg0)) { + needCompilerDiagnostic = false; + } + } + if (needCompilerDiagnostic) { + programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0)); + } + } + function getOptionsSyntaxByName(name) { + var compilerOptionsObjectLiteralSyntax = getCompilerOptionsObjectLiteralSyntax(); + if (compilerOptionsObjectLiteralSyntax) { + return ts.getPropertyAssignment(compilerOptionsObjectLiteralSyntax, name); + } + return undefined; + } + function getOptionPathsSyntax() { + return getOptionsSyntaxByName("paths") || ts.emptyArray; + } + function createDiagnosticForOptionName(message, option1, option2, option3) { + createDiagnosticForOption(/*onKey*/ true, option1, option2, message, option1, option2, option3); + } + function createOptionValueDiagnostic(option1, message, arg0) { + createDiagnosticForOption(/*onKey*/ false, option1, /*option2*/ undefined, message, arg0); + } + function createDiagnosticForReference(sourceFile, index, message, arg0, arg1) { + var referencesSyntax = ts.firstDefined(ts.getTsConfigPropArray(sourceFile || options.configFile, "references"), function (property) { return ts.isArrayLiteralExpression(property.initializer) ? property.initializer : undefined; }); + if (referencesSyntax && referencesSyntax.elements.length > index) { + programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(sourceFile || options.configFile, referencesSyntax.elements[index], message, arg0, arg1)); + } + else { + programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1)); + } + } + function createDiagnosticForOption(onKey, option1, option2, message, arg0, arg1, arg2) { + var compilerOptionsObjectLiteralSyntax = getCompilerOptionsObjectLiteralSyntax(); + var needCompilerDiagnostic = !compilerOptionsObjectLiteralSyntax || + !createOptionDiagnosticInObjectLiteralSyntax(compilerOptionsObjectLiteralSyntax, onKey, option1, option2, message, arg0, arg1, arg2); + if (needCompilerDiagnostic) { + programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1, arg2)); + } + } + function getCompilerOptionsObjectLiteralSyntax() { + if (_compilerOptionsObjectLiteralSyntax === undefined) { + _compilerOptionsObjectLiteralSyntax = null; // tslint:disable-line:no-null-keyword + var jsonObjectLiteral = ts.getTsConfigObjectLiteralExpression(options.configFile); + if (jsonObjectLiteral) { + for (var _i = 0, _a = ts.getPropertyAssignment(jsonObjectLiteral, "compilerOptions"); _i < _a.length; _i++) { + var prop = _a[_i]; + if (ts.isObjectLiteralExpression(prop.initializer)) { + _compilerOptionsObjectLiteralSyntax = prop.initializer; + break; + } + } + } + } + return _compilerOptionsObjectLiteralSyntax; + } + function createOptionDiagnosticInObjectLiteralSyntax(objectLiteral, onKey, key1, key2, message, arg0, arg1, arg2) { + var props = ts.getPropertyAssignment(objectLiteral, key1, key2); + for (var _i = 0, props_2 = props; _i < props_2.length; _i++) { + var prop = props_2[_i]; + programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(options.configFile, onKey ? prop.name : prop.initializer, message, arg0, arg1, arg2)); + } + return !!props.length; + } + function blockEmittingOfFile(emitFileName, diag) { + hasEmitBlockingDiagnostics.set(toPath(emitFileName), true); + programDiagnostics.add(diag); + } + function isEmittedFile(file) { + if (options.noEmit) { + return false; + } + // If this is source file, its not emitted file + var filePath = toPath(file); + if (getSourceFileByPath(filePath)) { + return false; + } + // If options have --outFile or --out just check that + var out = options.outFile || options.out; + if (out) { + return isSameFile(filePath, out) || isSameFile(filePath, ts.removeFileExtension(out) + ".d.ts" /* Dts */); + } + // If declarationDir is specified, return if its a file in that directory + if (options.declarationDir && ts.containsPath(options.declarationDir, filePath, currentDirectory, !host.useCaseSensitiveFileNames())) { + return true; + } + // If --outDir, check if file is in that directory + if (options.outDir) { + return ts.containsPath(options.outDir, filePath, currentDirectory, !host.useCaseSensitiveFileNames()); + } + if (ts.fileExtensionIsOneOf(filePath, ts.supportedJSExtensions) || ts.fileExtensionIs(filePath, ".d.ts" /* Dts */)) { + // Otherwise just check if sourceFile with the name exists + var filePathWithoutExtension = ts.removeFileExtension(filePath); + return !!getSourceFileByPath((filePathWithoutExtension + ".ts" /* Ts */)) || + !!getSourceFileByPath((filePathWithoutExtension + ".tsx" /* Tsx */)); + } + return false; + } + function isSameFile(file1, file2) { + return ts.comparePaths(file1, file2, currentDirectory, !host.useCaseSensitiveFileNames()) === 0 /* EqualTo */; + } + } + ts.createProgram = createProgram; + /* @internal */ + function parseConfigHostFromCompilerHost(host) { + return { + fileExists: function (f) { return host.fileExists(f); }, + readDirectory: function (root, extensions, excludes, includes, depth) { + ts.Debug.assertDefined(host.readDirectory, "'CompilerHost.readDirectory' must be implemented to correctly process 'projectReferences'"); + return host.readDirectory(root, extensions, excludes, includes, depth); + }, + readFile: function (f) { return host.readFile(f); }, + useCaseSensitiveFileNames: host.useCaseSensitiveFileNames(), + getCurrentDirectory: function () { return host.getCurrentDirectory(); }, + onUnRecoverableConfigFileDiagnostic: function () { return undefined; }, + trace: host.trace ? function (s) { return host.trace(s); } : undefined + }; + } + ts.parseConfigHostFromCompilerHost = parseConfigHostFromCompilerHost; + function resolveProjectReferencePath(hostOrRef, ref) { + var passedInRef = ref ? ref : hostOrRef; + return ts.resolveConfigFileProjectName(passedInRef.path); + } + ts.resolveProjectReferencePath = resolveProjectReferencePath; + function getEmitDeclarationOptionName(options) { + return options.declaration ? "declaration" : "composite"; + } + /* @internal */ + /** + * Returns a DiagnosticMessage if we won't include a resolved module due to its extension. + * The DiagnosticMessage's parameters are the imported module name, and the filename it resolved to. + * This returns a diagnostic even if the module will be an untyped module. + */ + function getResolutionDiagnostic(options, _a) { + var extension = _a.extension; + switch (extension) { + case ".ts" /* Ts */: + case ".d.ts" /* Dts */: + // These are always allowed. + return undefined; + case ".tsx" /* Tsx */: + return needJsx(); + case ".jsx" /* Jsx */: + return needJsx() || needAllowJs(); + case ".js" /* Js */: + return needAllowJs(); + case ".json" /* Json */: + return needResolveJsonModule(); + } + function needJsx() { + return options.jsx ? undefined : ts.Diagnostics.Module_0_was_resolved_to_1_but_jsx_is_not_set; + } + function needAllowJs() { + return options.allowJs || !ts.getStrictOptionValue(options, "noImplicitAny") ? undefined : ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type; + } + function needResolveJsonModule() { + return options.resolveJsonModule ? undefined : ts.Diagnostics.Module_0_was_resolved_to_1_but_resolveJsonModule_is_not_used; + } + } + ts.getResolutionDiagnostic = getResolutionDiagnostic; + function getModuleNames(_a) { + var imports = _a.imports, moduleAugmentations = _a.moduleAugmentations; + var res = imports.map(function (i) { return i.text; }); + for (var _i = 0, moduleAugmentations_1 = moduleAugmentations; _i < moduleAugmentations_1.length; _i++) { + var aug = moduleAugmentations_1[_i]; + if (aug.kind === 10 /* StringLiteral */) { + res.push(aug.text); + } + // Do nothing if it's an Identifier; we don't need to do module resolution for `declare global`. + } + return res; + } +})(ts || (ts = {})); +/*@internal*/ +var ts; +(function (ts) { + function getFileEmitOutput(program, sourceFile, emitOnlyDtsFiles, cancellationToken, customTransformers) { + var outputFiles = []; + var emitResult = program.emit(sourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); + return { outputFiles: outputFiles, emitSkipped: emitResult.emitSkipped, exportedModulesFromDeclarationEmit: emitResult.exportedModulesFromDeclarationEmit }; + function writeFile(fileName, text, writeByteOrderMark) { + outputFiles.push({ name: fileName, writeByteOrderMark: writeByteOrderMark, text: text }); + } + } + ts.getFileEmitOutput = getFileEmitOutput; +})(ts || (ts = {})); +/*@internal*/ +(function (ts) { + var BuilderState; + (function (BuilderState) { + /** + * Get the referencedFile from the imported module symbol + */ + function getReferencedFileFromImportedModuleSymbol(symbol) { + if (symbol.declarations && symbol.declarations[0]) { + var declarationSourceFile = ts.getSourceFileOfNode(symbol.declarations[0]); + return declarationSourceFile && declarationSourceFile.resolvedPath; + } + } + /** + * Get the referencedFile from the import name node from file + */ + function getReferencedFileFromImportLiteral(checker, importName) { + var symbol = checker.getSymbolAtLocation(importName); + return symbol && getReferencedFileFromImportedModuleSymbol(symbol); + } + /** + * Gets the path to reference file from file name, it could be resolvedPath if present otherwise path + */ + function getReferencedFileFromFileName(program, fileName, sourceFileDirectory, getCanonicalFileName) { + return ts.toPath(program.getProjectReferenceRedirect(fileName) || fileName, sourceFileDirectory, getCanonicalFileName); + } + /** + * Gets the referenced files for a file from the program with values for the keys as referenced file's path to be true + */ + function getReferencedFiles(program, sourceFile, getCanonicalFileName) { + var referencedFiles; + // We need to use a set here since the code can contain the same import twice, + // but that will only be one dependency. + // To avoid invernal conversion, the key of the referencedFiles map must be of type Path + if (sourceFile.imports && sourceFile.imports.length > 0) { + var checker = program.getTypeChecker(); + for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { + var importName = _a[_i]; + var declarationSourceFilePath = getReferencedFileFromImportLiteral(checker, importName); + if (declarationSourceFilePath) { + addReferencedFile(declarationSourceFilePath); + } + } + } + var sourceFileDirectory = ts.getDirectoryPath(sourceFile.path); + // Handle triple slash references + if (sourceFile.referencedFiles && sourceFile.referencedFiles.length > 0) { + for (var _b = 0, _c = sourceFile.referencedFiles; _b < _c.length; _b++) { + var referencedFile = _c[_b]; + var referencedPath = getReferencedFileFromFileName(program, referencedFile.fileName, sourceFileDirectory, getCanonicalFileName); + addReferencedFile(referencedPath); + } + } + // Handle type reference directives + if (sourceFile.resolvedTypeReferenceDirectiveNames) { + sourceFile.resolvedTypeReferenceDirectiveNames.forEach(function (resolvedTypeReferenceDirective) { + if (!resolvedTypeReferenceDirective) { + return; + } + var fileName = resolvedTypeReferenceDirective.resolvedFileName; // TODO: GH#18217 + var typeFilePath = getReferencedFileFromFileName(program, fileName, sourceFileDirectory, getCanonicalFileName); + addReferencedFile(typeFilePath); + }); + } + // Add module augmentation as references + if (sourceFile.moduleAugmentations.length) { + var checker = program.getTypeChecker(); + for (var _d = 0, _e = sourceFile.moduleAugmentations; _d < _e.length; _d++) { + var moduleName = _e[_d]; + if (!ts.isStringLiteral(moduleName)) { + continue; + } + var symbol = checker.getSymbolAtLocation(moduleName); + if (!symbol) { + continue; + } + // Add any file other than our own as reference + addReferenceFromAmbientModule(symbol); + } + } + // From ambient modules + for (var _f = 0, _g = program.getTypeChecker().getAmbientModules(); _f < _g.length; _f++) { + var ambientModule = _g[_f]; + if (ambientModule.declarations.length > 1) { + addReferenceFromAmbientModule(ambientModule); + } + } + return referencedFiles; + function addReferenceFromAmbientModule(symbol) { + // Add any file other than our own as reference + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + var declarationSourceFile = ts.getSourceFileOfNode(declaration); + if (declarationSourceFile && + declarationSourceFile !== sourceFile) { + addReferencedFile(declarationSourceFile.resolvedPath); + } + } + } + function addReferencedFile(referencedPath) { + if (!referencedFiles) { + referencedFiles = ts.createMap(); + } + referencedFiles.set(referencedPath, true); + } + } + /** + * Returns true if oldState is reusable, that is the emitKind = module/non module has not changed + */ + function canReuseOldState(newReferencedMap, oldState) { + return oldState && !oldState.referencedMap === !newReferencedMap; + } + BuilderState.canReuseOldState = canReuseOldState; + /** + * Creates the state of file references and signature for the new program from oldState if it is safe + */ + function create(newProgram, getCanonicalFileName, oldState) { + var fileInfos = ts.createMap(); + var referencedMap = newProgram.getCompilerOptions().module !== ts.ModuleKind.None ? ts.createMap() : undefined; + var exportedModulesMap = referencedMap ? ts.createMap() : undefined; + var hasCalledUpdateShapeSignature = ts.createMap(); + var useOldState = canReuseOldState(referencedMap, oldState); + // Create the reference map, and set the file infos + for (var _i = 0, _a = newProgram.getSourceFiles(); _i < _a.length; _i++) { + var sourceFile = _a[_i]; + var version_1 = sourceFile.version; + var oldInfo = useOldState ? oldState.fileInfos.get(sourceFile.path) : undefined; + if (referencedMap) { + var newReferences = getReferencedFiles(newProgram, sourceFile, getCanonicalFileName); + if (newReferences) { + referencedMap.set(sourceFile.path, newReferences); + } + // Copy old visible to outside files map + if (useOldState) { + var exportedModules = oldState.exportedModulesMap.get(sourceFile.path); + if (exportedModules) { + exportedModulesMap.set(sourceFile.path, exportedModules); + } + } + } + fileInfos.set(sourceFile.path, { version: version_1, signature: oldInfo && oldInfo.signature }); + } + return { + fileInfos: fileInfos, + referencedMap: referencedMap, + exportedModulesMap: exportedModulesMap, + hasCalledUpdateShapeSignature: hasCalledUpdateShapeSignature, + allFilesExcludingDefaultLibraryFile: undefined, + allFileNames: undefined + }; + } + BuilderState.create = create; + /** + * Gets the files affected by the path from the program + */ + function getFilesAffectedBy(state, programOfThisState, path, cancellationToken, computeHash, cacheToUpdateSignature, exportedModulesMapCache) { + // Since the operation could be cancelled, the signatures are always stored in the cache + // They will be commited once it is safe to use them + // eg when calling this api from tsserver, if there is no cancellation of the operation + // In the other cases the affected files signatures are commited only after the iteration through the result is complete + var signatureCache = cacheToUpdateSignature || ts.createMap(); + var sourceFile = programOfThisState.getSourceFileByPath(path); + if (!sourceFile) { + return ts.emptyArray; + } + if (!updateShapeSignature(state, programOfThisState, sourceFile, signatureCache, cancellationToken, computeHash, exportedModulesMapCache)) { + return [sourceFile]; + } + var result = (state.referencedMap ? getFilesAffectedByUpdatedShapeWhenModuleEmit : getFilesAffectedByUpdatedShapeWhenNonModuleEmit)(state, programOfThisState, sourceFile, signatureCache, cancellationToken, computeHash, exportedModulesMapCache); + if (!cacheToUpdateSignature) { + // Commit all the signatures in the signature cache + updateSignaturesFromCache(state, signatureCache); + } + return result; + } + BuilderState.getFilesAffectedBy = getFilesAffectedBy; + /** + * Updates the signatures from the cache into state's fileinfo signatures + * This should be called whenever it is safe to commit the state of the builder + */ + function updateSignaturesFromCache(state, signatureCache) { + signatureCache.forEach(function (signature, path) { + state.fileInfos.get(path).signature = signature; + state.hasCalledUpdateShapeSignature.set(path, true); + }); + } + BuilderState.updateSignaturesFromCache = updateSignaturesFromCache; + /** + * Returns if the shape of the signature has changed since last emit + */ + function updateShapeSignature(state, programOfThisState, sourceFile, cacheToUpdateSignature, cancellationToken, computeHash, exportedModulesMapCache) { + ts.Debug.assert(!!sourceFile); + ts.Debug.assert(!exportedModulesMapCache || !!state.exportedModulesMap, "Compute visible to outside map only if visibleToOutsideReferencedMap present in the state"); + // If we have cached the result for this file, that means hence forth we should assume file shape is uptodate + if (state.hasCalledUpdateShapeSignature.has(sourceFile.path) || cacheToUpdateSignature.has(sourceFile.path)) { + return false; + } + var info = state.fileInfos.get(sourceFile.path); + if (!info) + return ts.Debug.fail(); + var prevSignature = info.signature; + var latestSignature; + if (sourceFile.isDeclarationFile) { + latestSignature = sourceFile.version; + if (exportedModulesMapCache && latestSignature !== prevSignature) { + // All the references in this file are exported + var references = state.referencedMap ? state.referencedMap.get(sourceFile.path) : undefined; + exportedModulesMapCache.set(sourceFile.path, references || false); + } + } + else { + var emitOutput = ts.getFileEmitOutput(programOfThisState, sourceFile, /*emitOnlyDtsFiles*/ true, cancellationToken); + if (emitOutput.outputFiles && emitOutput.outputFiles.length > 0) { + latestSignature = computeHash(emitOutput.outputFiles[0].text); + if (exportedModulesMapCache && latestSignature !== prevSignature) { + updateExportedModules(sourceFile, emitOutput.exportedModulesFromDeclarationEmit, exportedModulesMapCache); + } + } + else { + latestSignature = prevSignature; // TODO: GH#18217 + } + } + cacheToUpdateSignature.set(sourceFile.path, latestSignature); + return !prevSignature || latestSignature !== prevSignature; + } + /** + * Coverts the declaration emit result into exported modules map + */ + function updateExportedModules(sourceFile, exportedModulesFromDeclarationEmit, exportedModulesMapCache) { + if (!exportedModulesFromDeclarationEmit) { + exportedModulesMapCache.set(sourceFile.path, false); + return; + } + var exportedModules; + exportedModulesFromDeclarationEmit.forEach(function (symbol) { return addExportedModule(getReferencedFileFromImportedModuleSymbol(symbol)); }); + exportedModulesMapCache.set(sourceFile.path, exportedModules || false); + function addExportedModule(exportedModulePath) { + if (exportedModulePath) { + if (!exportedModules) { + exportedModules = ts.createMap(); + } + exportedModules.set(exportedModulePath, true); + } + } + } + /** + * Updates the exported modules from cache into state's exported modules map + * This should be called whenever it is safe to commit the state of the builder + */ + function updateExportedFilesMapFromCache(state, exportedModulesMapCache) { + if (exportedModulesMapCache) { + ts.Debug.assert(!!state.exportedModulesMap); + exportedModulesMapCache.forEach(function (exportedModules, path) { + if (exportedModules) { + state.exportedModulesMap.set(path, exportedModules); + } + else { + state.exportedModulesMap.delete(path); + } + }); + } + } + BuilderState.updateExportedFilesMapFromCache = updateExportedFilesMapFromCache; + /** + * Get all the dependencies of the sourceFile + */ + function getAllDependencies(state, programOfThisState, sourceFile) { + var _a; + var compilerOptions = programOfThisState.getCompilerOptions(); + // With --out or --outFile all outputs go into single file, all files depend on each other + if (compilerOptions.outFile || compilerOptions.out) { + return getAllFileNames(state, programOfThisState); + } + // If this is non module emit, or its a global file, it depends on all the source files + if (!state.referencedMap || isFileAffectingGlobalScope(sourceFile)) { + return getAllFileNames(state, programOfThisState); + } + // Get the references, traversing deep from the referenceMap + var seenMap = ts.createMap(); + var queue = [sourceFile.path]; + while (queue.length) { + var path = queue.pop(); + if (!seenMap.has(path)) { + seenMap.set(path, true); + var references = state.referencedMap.get(path); + if (references) { + var iterator = references.keys(); + for (var _b = iterator.next(), value = _b.value, done = _b.done; !done; _a = iterator.next(), value = _a.value, done = _a.done, _a) { + queue.push(value); + } + } + } + } + return ts.arrayFrom(ts.mapDefinedIterator(seenMap.keys(), function (path) { + var file = programOfThisState.getSourceFileByPath(path); + return file ? file.fileName : path; + })); + } + BuilderState.getAllDependencies = getAllDependencies; + /** + * Gets the names of all files from the program + */ + function getAllFileNames(state, programOfThisState) { + if (!state.allFileNames) { + var sourceFiles = programOfThisState.getSourceFiles(); + state.allFileNames = sourceFiles === ts.emptyArray ? ts.emptyArray : sourceFiles.map(function (file) { return file.fileName; }); + } + return state.allFileNames; + } + /** + * Gets the files referenced by the the file path + */ + function getReferencedByPaths(state, referencedFilePath) { + return ts.arrayFrom(ts.mapDefinedIterator(state.referencedMap.entries(), function (_a) { + var filePath = _a[0], referencesInFile = _a[1]; + return referencesInFile.has(referencedFilePath) ? filePath : undefined; + })); + } + /** + * For script files that contains only ambient external modules, although they are not actually external module files, + * they can only be consumed via importing elements from them. Regular script files cannot consume them. Therefore, + * there are no point to rebuild all script files if these special files have changed. However, if any statement + * in the file is not ambient external module, we treat it as a regular script file. + */ + function containsOnlyAmbientModules(sourceFile) { + for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + if (!ts.isModuleWithStringLiteralName(statement)) { + return false; + } + } + return true; + } + /** + * Return true if file contains anything that augments to global scope we need to build them as if + * they are global files as well as module + */ + function containsGlobalScopeAugmentation(sourceFile) { + return ts.some(sourceFile.moduleAugmentations, function (augmentation) { return ts.isGlobalScopeAugmentation(augmentation.parent); }); + } + /** + * Return true if the file will invalidate all files because it affectes global scope + */ + function isFileAffectingGlobalScope(sourceFile) { + return containsGlobalScopeAugmentation(sourceFile) || + !ts.isExternalModule(sourceFile) && !containsOnlyAmbientModules(sourceFile); + } + /** + * Gets all files of the program excluding the default library file + */ + function getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, firstSourceFile) { + // Use cached result + if (state.allFilesExcludingDefaultLibraryFile) { + return state.allFilesExcludingDefaultLibraryFile; + } + var result; + addSourceFile(firstSourceFile); + for (var _i = 0, _a = programOfThisState.getSourceFiles(); _i < _a.length; _i++) { + var sourceFile = _a[_i]; + if (sourceFile !== firstSourceFile) { + addSourceFile(sourceFile); + } + } + state.allFilesExcludingDefaultLibraryFile = result || ts.emptyArray; + return state.allFilesExcludingDefaultLibraryFile; + function addSourceFile(sourceFile) { + if (!programOfThisState.isSourceFileDefaultLibrary(sourceFile)) { + (result || (result = [])).push(sourceFile); + } + } + } + /** + * When program emits non modular code, gets the files affected by the sourceFile whose shape has changed + */ + function getFilesAffectedByUpdatedShapeWhenNonModuleEmit(state, programOfThisState, sourceFileWithUpdatedShape) { + var compilerOptions = programOfThisState.getCompilerOptions(); + // If `--out` or `--outFile` is specified, any new emit will result in re-emitting the entire project, + // so returning the file itself is good enough. + if (compilerOptions && (compilerOptions.out || compilerOptions.outFile)) { + return [sourceFileWithUpdatedShape]; + } + return getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, sourceFileWithUpdatedShape); + } + /** + * When program emits modular code, gets the files affected by the sourceFile whose shape has changed + */ + function getFilesAffectedByUpdatedShapeWhenModuleEmit(state, programOfThisState, sourceFileWithUpdatedShape, cacheToUpdateSignature, cancellationToken, computeHash, exportedModulesMapCache) { + if (isFileAffectingGlobalScope(sourceFileWithUpdatedShape)) { + return getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, sourceFileWithUpdatedShape); + } + var compilerOptions = programOfThisState.getCompilerOptions(); + if (compilerOptions && (compilerOptions.isolatedModules || compilerOptions.out || compilerOptions.outFile)) { + return [sourceFileWithUpdatedShape]; + } + // Now we need to if each file in the referencedBy list has a shape change as well. + // Because if so, its own referencedBy files need to be saved as well to make the + // emitting result consistent with files on disk. + var seenFileNamesMap = ts.createMap(); + // Start with the paths this file was referenced by + seenFileNamesMap.set(sourceFileWithUpdatedShape.path, sourceFileWithUpdatedShape); + var queue = getReferencedByPaths(state, sourceFileWithUpdatedShape.path); + while (queue.length > 0) { + var currentPath = queue.pop(); + if (!seenFileNamesMap.has(currentPath)) { + var currentSourceFile = programOfThisState.getSourceFileByPath(currentPath); + seenFileNamesMap.set(currentPath, currentSourceFile); + if (currentSourceFile && updateShapeSignature(state, programOfThisState, currentSourceFile, cacheToUpdateSignature, cancellationToken, computeHash, exportedModulesMapCache)) { // TODO: GH#18217 + queue.push.apply(// TODO: GH#18217 + queue, getReferencedByPaths(state, currentPath)); + } + } + } + // Return array of values that needs emit + // Return array of values that needs emit + return ts.arrayFrom(ts.mapDefinedIterator(seenFileNamesMap.values(), function (value) { return value; })); + } + })(BuilderState = ts.BuilderState || (ts.BuilderState = {})); +})(ts || (ts = {})); +/*@internal*/ +var ts; +(function (ts) { + function hasSameKeys(map1, map2) { + // Has same size and every key is present in both maps + return map1 === map2 || map1 !== undefined && map2 !== undefined && map1.size === map2.size && !ts.forEachKey(map1, function (key) { return !map2.has(key); }); + } + /** + * Create the state so that we can iterate on changedFiles/affected files + */ + function createBuilderProgramState(newProgram, getCanonicalFileName, oldState) { + var state = ts.BuilderState.create(newProgram, getCanonicalFileName, oldState); + state.program = newProgram; + var compilerOptions = newProgram.getCompilerOptions(); + if (!compilerOptions.outFile && !compilerOptions.out) { + state.semanticDiagnosticsPerFile = ts.createMap(); + } + state.changedFilesSet = ts.createMap(); + var useOldState = ts.BuilderState.canReuseOldState(state.referencedMap, oldState); + var oldCompilerOptions = useOldState ? oldState.program.getCompilerOptions() : undefined; + var canCopySemanticDiagnostics = useOldState && oldState.semanticDiagnosticsPerFile && !!state.semanticDiagnosticsPerFile && + !ts.compilerOptionsAffectSemanticDiagnostics(compilerOptions, oldCompilerOptions); + if (useOldState) { + // Verify the sanity of old state + if (!oldState.currentChangedFilePath) { + ts.Debug.assert(!oldState.affectedFiles && (!oldState.currentAffectedFilesSignatures || !oldState.currentAffectedFilesSignatures.size), "Cannot reuse if only few affected files of currentChangedFile were iterated"); + } + if (canCopySemanticDiagnostics) { + ts.Debug.assert(!ts.forEachKey(oldState.changedFilesSet, function (path) { return oldState.semanticDiagnosticsPerFile.has(path); }), "Semantic diagnostics shouldnt be available for changed files"); + } + // Copy old state's changed files set + ts.copyEntries(oldState.changedFilesSet, state.changedFilesSet); + } + // Update changed files and copy semantic diagnostics if we can + var referencedMap = state.referencedMap; + var oldReferencedMap = useOldState ? oldState.referencedMap : undefined; + var copyDeclarationFileDiagnostics = canCopySemanticDiagnostics && !compilerOptions.skipLibCheck === !oldCompilerOptions.skipLibCheck; + var copyLibFileDiagnostics = copyDeclarationFileDiagnostics && !compilerOptions.skipDefaultLibCheck === !oldCompilerOptions.skipDefaultLibCheck; + state.fileInfos.forEach(function (info, sourceFilePath) { + var oldInfo; + var newReferences; + // if not using old state, every file is changed + if (!useOldState || + // File wasnt present in old state + !(oldInfo = oldState.fileInfos.get(sourceFilePath)) || + // versions dont match + oldInfo.version !== info.version || + // Referenced files changed + !hasSameKeys(newReferences = referencedMap && referencedMap.get(sourceFilePath), oldReferencedMap && oldReferencedMap.get(sourceFilePath)) || + // Referenced file was deleted in the new program + newReferences && ts.forEachKey(newReferences, function (path) { return !state.fileInfos.has(path) && oldState.fileInfos.has(path); })) { + // Register file as changed file and do not copy semantic diagnostics, since all changed files need to be re-evaluated + state.changedFilesSet.set(sourceFilePath, true); + } + else if (canCopySemanticDiagnostics) { + var sourceFile = state.program.getSourceFileByPath(sourceFilePath); + if (sourceFile.isDeclarationFile && !copyDeclarationFileDiagnostics) { + return; + } + if (sourceFile.hasNoDefaultLib && !copyLibFileDiagnostics) { + return; + } + // Unchanged file copy diagnostics + var diagnostics = oldState.semanticDiagnosticsPerFile.get(sourceFilePath); + if (diagnostics) { + state.semanticDiagnosticsPerFile.set(sourceFilePath, diagnostics); + if (!state.semanticDiagnosticsFromOldState) { + state.semanticDiagnosticsFromOldState = ts.createMap(); + } + state.semanticDiagnosticsFromOldState.set(sourceFilePath, true); + } + } + }); + return state; + } + /** + * Verifies that source file is ok to be used in calls that arent handled by next + */ + function assertSourceFileOkWithoutNextAffectedCall(state, sourceFile) { + ts.Debug.assert(!sourceFile || !state.affectedFiles || state.affectedFiles[state.affectedFilesIndex - 1] !== sourceFile || !state.semanticDiagnosticsPerFile.has(sourceFile.path)); + } + /** + * This function returns the next affected file to be processed. + * Note that until doneAffected is called it would keep reporting same result + * This is to allow the callers to be able to actually remove affected file only when the operation is complete + * eg. if during diagnostics check cancellation token ends up cancelling the request, the affected file should be retained + */ + function getNextAffectedFile(state, cancellationToken, computeHash) { + while (true) { + var affectedFiles = state.affectedFiles; + if (affectedFiles) { + var seenAffectedFiles = state.seenAffectedFiles; + var affectedFilesIndex = state.affectedFilesIndex; // TODO: GH#18217 + while (affectedFilesIndex < affectedFiles.length) { + var affectedFile = affectedFiles[affectedFilesIndex]; + if (!seenAffectedFiles.has(affectedFile.path)) { + // Set the next affected file as seen and remove the cached semantic diagnostics + state.affectedFilesIndex = affectedFilesIndex; + cleanSemanticDiagnosticsOfAffectedFile(state, affectedFile); + return affectedFile; + } + seenAffectedFiles.set(affectedFile.path, true); + affectedFilesIndex++; + } + // Remove the changed file from the change set + state.changedFilesSet.delete(state.currentChangedFilePath); + state.currentChangedFilePath = undefined; + // Commit the changes in file signature + ts.BuilderState.updateSignaturesFromCache(state, state.currentAffectedFilesSignatures); + state.currentAffectedFilesSignatures.clear(); + ts.BuilderState.updateExportedFilesMapFromCache(state, state.currentAffectedFilesExportedModulesMap); + state.affectedFiles = undefined; + } + // Get next changed file + var nextKey = state.changedFilesSet.keys().next(); + if (nextKey.done) { + // Done + return undefined; + } + // With --out or --outFile all outputs go into single file + // so operations are performed directly on program, return program + var compilerOptions = state.program.getCompilerOptions(); + if (compilerOptions.outFile || compilerOptions.out) { + ts.Debug.assert(!state.semanticDiagnosticsPerFile); + return state.program; + } + // Get next batch of affected files + state.currentAffectedFilesSignatures = state.currentAffectedFilesSignatures || ts.createMap(); + if (state.exportedModulesMap) { + state.currentAffectedFilesExportedModulesMap = state.currentAffectedFilesExportedModulesMap || ts.createMap(); + } + state.affectedFiles = ts.BuilderState.getFilesAffectedBy(state, state.program, nextKey.value, cancellationToken, computeHash, state.currentAffectedFilesSignatures, state.currentAffectedFilesExportedModulesMap); + state.currentChangedFilePath = nextKey.value; + state.affectedFilesIndex = 0; + state.seenAffectedFiles = state.seenAffectedFiles || ts.createMap(); + } + } + /** + * Remove the semantic diagnostics cached from old state for affected File and the files that are referencing modules that export entities from affected file + */ + function cleanSemanticDiagnosticsOfAffectedFile(state, affectedFile) { + if (removeSemanticDiagnosticsOf(state, affectedFile.path)) { + // If there are no more diagnostics from old cache, done + return; + } + // Clean lib file diagnostics if its all files excluding default files to emit + if (state.allFilesExcludingDefaultLibraryFile === state.affectedFiles && !state.cleanedDiagnosticsOfLibFiles) { + state.cleanedDiagnosticsOfLibFiles = true; + var options_2 = state.program.getCompilerOptions(); + if (ts.forEach(state.program.getSourceFiles(), function (f) { + return state.program.isSourceFileDefaultLibrary(f) && + !ts.skipTypeChecking(f, options_2) && + removeSemanticDiagnosticsOf(state, f.path); + })) { + return; + } + } + // If there was change in signature for the changed file, + // then delete the semantic diagnostics for files that are affected by using exports of this module + if (!state.exportedModulesMap || state.affectedFiles.length === 1 || !state.changedFilesSet.has(affectedFile.path)) { + return; + } + ts.Debug.assert(!!state.currentAffectedFilesExportedModulesMap); + var seenFileAndExportsOfFile = ts.createMap(); + // Go through exported modules from cache first + // If exported modules has path, all files referencing file exported from are affected + if (ts.forEachEntry(state.currentAffectedFilesExportedModulesMap, function (exportedModules, exportedFromPath) { + return exportedModules && + exportedModules.has(affectedFile.path) && + removeSemanticDiagnosticsOfFilesReferencingPath(state, exportedFromPath, seenFileAndExportsOfFile); + })) { + return; + } + // If exported from path is not from cache and exported modules has path, all files referencing file exported from are affected + ts.forEachEntry(state.exportedModulesMap, function (exportedModules, exportedFromPath) { + return !state.currentAffectedFilesExportedModulesMap.has(exportedFromPath) && // If we already iterated this through cache, ignore it + exportedModules.has(affectedFile.path) && + removeSemanticDiagnosticsOfFilesReferencingPath(state, exportedFromPath, seenFileAndExportsOfFile); + }); + } + /** + * removes the semantic diagnostics of files referencing referencedPath and + * returns true if there are no more semantic diagnostics from old state + */ + function removeSemanticDiagnosticsOfFilesReferencingPath(state, referencedPath, seenFileAndExportsOfFile) { + return ts.forEachEntry(state.referencedMap, function (referencesInFile, filePath) { + return referencesInFile.has(referencedPath) && removeSemanticDiagnosticsOfFileAndExportsOfFile(state, filePath, seenFileAndExportsOfFile); + }); + } + /** + * Removes semantic diagnostics of file and anything that exports this file + */ + function removeSemanticDiagnosticsOfFileAndExportsOfFile(state, filePath, seenFileAndExportsOfFile) { + if (!ts.addToSeen(seenFileAndExportsOfFile, filePath)) { + return false; + } + if (removeSemanticDiagnosticsOf(state, filePath)) { + // If there are no more diagnostics from old cache, done + return true; + } + ts.Debug.assert(!!state.currentAffectedFilesExportedModulesMap); + // Go through exported modules from cache first + // If exported modules has path, all files referencing file exported from are affected + if (ts.forEachEntry(state.currentAffectedFilesExportedModulesMap, function (exportedModules, exportedFromPath) { + return exportedModules && + exportedModules.has(filePath) && + removeSemanticDiagnosticsOfFileAndExportsOfFile(state, exportedFromPath, seenFileAndExportsOfFile); + })) { + return true; + } + // If exported from path is not from cache and exported modules has path, all files referencing file exported from are affected + return !!ts.forEachEntry(state.exportedModulesMap, function (exportedModules, exportedFromPath) { + return !state.currentAffectedFilesExportedModulesMap.has(exportedFromPath) && // If we already iterated this through cache, ignore it + exportedModules.has(filePath) && + removeSemanticDiagnosticsOfFileAndExportsOfFile(state, exportedFromPath, seenFileAndExportsOfFile); + }); + } + /** + * Removes semantic diagnostics for path and + * returns true if there are no more semantic diagnostics from the old state + */ + function removeSemanticDiagnosticsOf(state, path) { + if (!state.semanticDiagnosticsFromOldState) { + return true; + } + state.semanticDiagnosticsFromOldState.delete(path); + state.semanticDiagnosticsPerFile.delete(path); + return !state.semanticDiagnosticsFromOldState.size; + } + /** + * This is called after completing operation on the next affected file. + * The operations here are postponed to ensure that cancellation during the iteration is handled correctly + */ + function doneWithAffectedFile(state, affected) { + if (affected === state.program) { + state.changedFilesSet.clear(); + } + else { + state.seenAffectedFiles.set(affected.path, true); + state.affectedFilesIndex++; + } + } + /** + * Returns the result with affected file + */ + function toAffectedFileResult(state, result, affected) { + doneWithAffectedFile(state, affected); + return { result: result, affected: affected }; + } + /** + * Gets the semantic diagnostics either from cache if present, or otherwise from program and caches it + * Note that it is assumed that the when asked about semantic diagnostics, the file has been taken out of affected files/changed file set + */ + function getSemanticDiagnosticsOfFile(state, sourceFile, cancellationToken) { + var path = sourceFile.path; + var cachedDiagnostics = state.semanticDiagnosticsPerFile.get(path); + // Report the semantic diagnostics from the cache if we already have those diagnostics present + if (cachedDiagnostics) { + return cachedDiagnostics; + } + // Diagnostics werent cached, get them from program, and cache the result + var diagnostics = state.program.getSemanticDiagnostics(sourceFile, cancellationToken); + state.semanticDiagnosticsPerFile.set(path, diagnostics); + return diagnostics; + } + var BuilderProgramKind; + (function (BuilderProgramKind) { + BuilderProgramKind[BuilderProgramKind["SemanticDiagnosticsBuilderProgram"] = 0] = "SemanticDiagnosticsBuilderProgram"; + BuilderProgramKind[BuilderProgramKind["EmitAndSemanticDiagnosticsBuilderProgram"] = 1] = "EmitAndSemanticDiagnosticsBuilderProgram"; + })(BuilderProgramKind = ts.BuilderProgramKind || (ts.BuilderProgramKind = {})); + function getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { + var host; + var newProgram; + var oldProgram; + if (newProgramOrRootNames === undefined) { + ts.Debug.assert(hostOrOptions === undefined); + host = oldProgramOrHost; + oldProgram = configFileParsingDiagnosticsOrOldProgram; + ts.Debug.assert(!!oldProgram); + newProgram = oldProgram.getProgram(); + } + else if (ts.isArray(newProgramOrRootNames)) { + oldProgram = configFileParsingDiagnosticsOrOldProgram; + newProgram = ts.createProgram({ + rootNames: newProgramOrRootNames, + options: hostOrOptions, + host: oldProgramOrHost, + oldProgram: oldProgram && oldProgram.getProgram(), + configFileParsingDiagnostics: configFileParsingDiagnostics, + projectReferences: projectReferences + }); + host = oldProgramOrHost; + } + else { + newProgram = newProgramOrRootNames; + host = hostOrOptions; + oldProgram = oldProgramOrHost; + configFileParsingDiagnostics = configFileParsingDiagnosticsOrOldProgram; + } + return { host: host, newProgram: newProgram, oldProgram: oldProgram, configFileParsingDiagnostics: configFileParsingDiagnostics || ts.emptyArray }; + } + ts.getBuilderCreationParameters = getBuilderCreationParameters; + function createBuilderProgram(kind, _a) { + var newProgram = _a.newProgram, host = _a.host, oldProgram = _a.oldProgram, configFileParsingDiagnostics = _a.configFileParsingDiagnostics; + // Return same program if underlying program doesnt change + var oldState = oldProgram && oldProgram.getState(); + if (oldState && newProgram === oldState.program && configFileParsingDiagnostics === newProgram.getConfigFileParsingDiagnostics()) { + newProgram = undefined; // TODO: GH#18217 + oldState = undefined; + return oldProgram; + } + /** + * Create the canonical file name for identity + */ + var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames()); + /** + * Computing hash to for signature verification + */ + var computeHash = host.createHash || ts.identity; + var state = createBuilderProgramState(newProgram, getCanonicalFileName, oldState); + // To ensure that we arent storing any references to old program or new program without state + newProgram = undefined; // TODO: GH#18217 + oldProgram = undefined; + oldState = undefined; + var result = { + getState: function () { return state; }, + getProgram: function () { return state.program; }, + getCompilerOptions: function () { return state.program.getCompilerOptions(); }, + getSourceFile: function (fileName) { return state.program.getSourceFile(fileName); }, + getSourceFiles: function () { return state.program.getSourceFiles(); }, + getOptionsDiagnostics: function (cancellationToken) { return state.program.getOptionsDiagnostics(cancellationToken); }, + getGlobalDiagnostics: function (cancellationToken) { return state.program.getGlobalDiagnostics(cancellationToken); }, + getConfigFileParsingDiagnostics: function () { return configFileParsingDiagnostics || state.program.getConfigFileParsingDiagnostics(); }, + getSyntacticDiagnostics: function (sourceFile, cancellationToken) { return state.program.getSyntacticDiagnostics(sourceFile, cancellationToken); }, + getSemanticDiagnostics: getSemanticDiagnostics, + emit: emit, + getAllDependencies: function (sourceFile) { return ts.BuilderState.getAllDependencies(state, state.program, sourceFile); }, + getCurrentDirectory: function () { return state.program.getCurrentDirectory(); } + }; + if (kind === BuilderProgramKind.SemanticDiagnosticsBuilderProgram) { + result.getSemanticDiagnosticsOfNextAffectedFile = getSemanticDiagnosticsOfNextAffectedFile; + } + else if (kind === BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram) { + result.emitNextAffectedFile = emitNextAffectedFile; + } + else { + ts.notImplemented(); + } + return result; + /** + * Emits the next affected file's emit result (EmitResult and sourceFiles emitted) or returns undefined if iteration is complete + * The first of writeFile if provided, writeFile of BuilderProgramHost if provided, writeFile of compiler host + * in that order would be used to write the files + */ + function emitNextAffectedFile(writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) { + var affected = getNextAffectedFile(state, cancellationToken, computeHash); + if (!affected) { + // Done + return undefined; + } + return toAffectedFileResult(state, + // When whole program is affected, do emit only once (eg when --out or --outFile is specified) + // Otherwise just affected file + state.program.emit(affected === state.program ? undefined : affected, writeFile || host.writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers), affected); + } + /** + * Emits the JavaScript and declaration files. + * When targetSource file is specified, emits the files corresponding to that source file, + * otherwise for the whole program. + * In case of EmitAndSemanticDiagnosticsBuilderProgram, when targetSourceFile is specified, + * it is assumed that that file is handled from affected file list. If targetSourceFile is not specified, + * it will only emit all the affected files instead of whole program + * + * The first of writeFile if provided, writeFile of BuilderProgramHost if provided, writeFile of compiler host + * in that order would be used to write the files + */ + function emit(targetSourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) { + if (kind === BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram) { + assertSourceFileOkWithoutNextAffectedCall(state, targetSourceFile); + if (!targetSourceFile) { + // Emit and report any errors we ran into. + var sourceMaps = []; + var emitSkipped = false; + var diagnostics = void 0; + var emittedFiles = []; + var affectedEmitResult = void 0; + while (affectedEmitResult = emitNextAffectedFile(writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers)) { + emitSkipped = emitSkipped || affectedEmitResult.result.emitSkipped; + diagnostics = ts.addRange(diagnostics, affectedEmitResult.result.diagnostics); + emittedFiles = ts.addRange(emittedFiles, affectedEmitResult.result.emittedFiles); + sourceMaps = ts.addRange(sourceMaps, affectedEmitResult.result.sourceMaps); + } + return { + emitSkipped: emitSkipped, + diagnostics: diagnostics || ts.emptyArray, + emittedFiles: emittedFiles, + sourceMaps: sourceMaps + }; + } + } + return state.program.emit(targetSourceFile, writeFile || host.writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); + } + /** + * Return the semantic diagnostics for the next affected file or undefined if iteration is complete + * If provided ignoreSourceFile would be called before getting the diagnostics and would ignore the sourceFile if the returned value was true + */ + function getSemanticDiagnosticsOfNextAffectedFile(cancellationToken, ignoreSourceFile) { + while (true) { + var affected = getNextAffectedFile(state, cancellationToken, computeHash); + if (!affected) { + // Done + return undefined; + } + else if (affected === state.program) { + // When whole program is affected, get all semantic diagnostics (eg when --out or --outFile is specified) + return toAffectedFileResult(state, state.program.getSemanticDiagnostics(/*targetSourceFile*/ undefined, cancellationToken), affected); + } + // Get diagnostics for the affected file if its not ignored + if (ignoreSourceFile && ignoreSourceFile(affected)) { + // Get next affected file + doneWithAffectedFile(state, affected); + continue; + } + return toAffectedFileResult(state, getSemanticDiagnosticsOfFile(state, affected, cancellationToken), affected); + } + } + /** + * Gets the semantic diagnostics from the program corresponding to this state of file (if provided) or whole program + * The semantic diagnostics are cached and managed here + * Note that it is assumed that when asked about semantic diagnostics through this API, + * the file has been taken out of affected files so it is safe to use cache or get from program and cache the diagnostics + * In case of SemanticDiagnosticsBuilderProgram if the source file is not provided, + * it will iterate through all the affected files, to ensure that cache stays valid and yet provide a way to get all semantic diagnostics + */ + function getSemanticDiagnostics(sourceFile, cancellationToken) { + assertSourceFileOkWithoutNextAffectedCall(state, sourceFile); + var compilerOptions = state.program.getCompilerOptions(); + if (compilerOptions.outFile || compilerOptions.out) { + ts.Debug.assert(!state.semanticDiagnosticsPerFile); + // We dont need to cache the diagnostics just return them from program + return state.program.getSemanticDiagnostics(sourceFile, cancellationToken); + } + if (sourceFile) { + return getSemanticDiagnosticsOfFile(state, sourceFile, cancellationToken); + } + if (kind === BuilderProgramKind.SemanticDiagnosticsBuilderProgram) { + // When semantic builder asks for diagnostics of the whole program, + // ensure that all the affected files are handled + var affected = void 0; + while (affected = getNextAffectedFile(state, cancellationToken, computeHash)) { + doneWithAffectedFile(state, affected); + } + } + var diagnostics; + for (var _i = 0, _a = state.program.getSourceFiles(); _i < _a.length; _i++) { + var sourceFile_2 = _a[_i]; + diagnostics = ts.addRange(diagnostics, getSemanticDiagnosticsOfFile(state, sourceFile_2, cancellationToken)); + } + return diagnostics || ts.emptyArray; + } + } + ts.createBuilderProgram = createBuilderProgram; +})(ts || (ts = {})); +(function (ts) { + function createSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { + return ts.createBuilderProgram(ts.BuilderProgramKind.SemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences)); + } + ts.createSemanticDiagnosticsBuilderProgram = createSemanticDiagnosticsBuilderProgram; + function createEmitAndSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { + return ts.createBuilderProgram(ts.BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences)); + } + ts.createEmitAndSemanticDiagnosticsBuilderProgram = createEmitAndSemanticDiagnosticsBuilderProgram; + function createAbstractBuilder(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { + var program = ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences).newProgram; + return { + // Only return program, all other methods are not implemented + getProgram: function () { return program; }, + getState: ts.notImplemented, + getCompilerOptions: ts.notImplemented, + getSourceFile: ts.notImplemented, + getSourceFiles: ts.notImplemented, + getOptionsDiagnostics: ts.notImplemented, + getGlobalDiagnostics: ts.notImplemented, + getConfigFileParsingDiagnostics: ts.notImplemented, + getSyntacticDiagnostics: ts.notImplemented, + getSemanticDiagnostics: ts.notImplemented, + emit: ts.notImplemented, + getAllDependencies: ts.notImplemented, + getCurrentDirectory: ts.notImplemented + }; + } + ts.createAbstractBuilder = createAbstractBuilder; +})(ts || (ts = {})); +/*@internal*/ +var ts; +(function (ts) { + function isPathInNodeModulesStartingWithDot(path) { + return ts.stringContains(path, "/node_modules/."); + } + ts.isPathInNodeModulesStartingWithDot = isPathInNodeModulesStartingWithDot; + ts.maxNumberOfFilesToIterateForInvalidation = 256; + function createResolutionCache(resolutionHost, rootDirForResolution, logChangesWhenResolvingModule) { + var filesWithChangedSetOfUnresolvedImports; + var filesWithInvalidatedResolutions; + var filesWithInvalidatedNonRelativeUnresolvedImports; + var allFilesHaveInvalidatedResolution = false; + var nonRelativeExternalModuleResolutions = ts.createMultiMap(); + var getCurrentDirectory = ts.memoize(function () { return resolutionHost.getCurrentDirectory(); }); // TODO: GH#18217 + var cachedDirectoryStructureHost = resolutionHost.getCachedDirectoryStructureHost(); + // The resolvedModuleNames and resolvedTypeReferenceDirectives are the cache of resolutions per file. + // The key in the map is source file's path. + // The values are Map of resolutions with key being name lookedup. + var resolvedModuleNames = ts.createMap(); + var perDirectoryResolvedModuleNames = ts.createCacheWithRedirects(); + var nonRelativeModuleNameCache = ts.createCacheWithRedirects(); + var moduleResolutionCache = ts.createModuleResolutionCacheWithMaps(perDirectoryResolvedModuleNames, nonRelativeModuleNameCache, getCurrentDirectory(), resolutionHost.getCanonicalFileName); + var resolvedTypeReferenceDirectives = ts.createMap(); + var perDirectoryResolvedTypeReferenceDirectives = ts.createCacheWithRedirects(); + /** + * These are the extensions that failed lookup files will have by default, + * any other extension of failed lookup will be store that path in custom failed lookup path + * This helps in not having to comb through all resolutions when files are added/removed + * Note that .d.ts file also has .d.ts extension hence will be part of default extensions + */ + var failedLookupDefaultExtensions = [".ts" /* Ts */, ".tsx" /* Tsx */, ".js" /* Js */, ".jsx" /* Jsx */, ".json" /* Json */]; + var customFailedLookupPaths = ts.createMap(); + var directoryWatchesOfFailedLookups = ts.createMap(); + var rootDir = rootDirForResolution && ts.removeTrailingDirectorySeparator(ts.getNormalizedAbsolutePath(rootDirForResolution, getCurrentDirectory())); + var rootPath = (rootDir && resolutionHost.toPath(rootDir)); // TODO: GH#18217 + // TypeRoot watches for the types that get added as part of getAutomaticTypeDirectiveNames + var typeRootsWatches = ts.createMap(); + return { + startRecordingFilesWithChangedResolutions: startRecordingFilesWithChangedResolutions, + finishRecordingFilesWithChangedResolutions: finishRecordingFilesWithChangedResolutions, + // perDirectoryResolvedModuleNames and perDirectoryResolvedTypeReferenceDirectives could be non empty if there was exception during program update + // (between startCachingPerDirectoryResolution and finishCachingPerDirectoryResolution) + startCachingPerDirectoryResolution: clearPerDirectoryResolutions, + finishCachingPerDirectoryResolution: finishCachingPerDirectoryResolution, + resolveModuleNames: resolveModuleNames, + getResolvedModuleWithFailedLookupLocationsFromCache: getResolvedModuleWithFailedLookupLocationsFromCache, + resolveTypeReferenceDirectives: resolveTypeReferenceDirectives, + removeResolutionsFromProjectReferenceRedirects: removeResolutionsFromProjectReferenceRedirects, + removeResolutionsOfFile: removeResolutionsOfFile, + invalidateResolutionOfFile: invalidateResolutionOfFile, + setFilesWithInvalidatedNonRelativeUnresolvedImports: setFilesWithInvalidatedNonRelativeUnresolvedImports, + createHasInvalidatedResolution: createHasInvalidatedResolution, + updateTypeRootsWatch: updateTypeRootsWatch, + closeTypeRootsWatch: closeTypeRootsWatch, + clear: clear + }; + function getResolvedModule(resolution) { + return resolution.resolvedModule; + } + function getResolvedTypeReferenceDirective(resolution) { + return resolution.resolvedTypeReferenceDirective; + } + function isInDirectoryPath(dir, file) { + if (dir === undefined || file.length <= dir.length) { + return false; + } + return ts.startsWith(file, dir) && file[dir.length] === ts.directorySeparator; + } + function clear() { + ts.clearMap(directoryWatchesOfFailedLookups, ts.closeFileWatcherOf); + customFailedLookupPaths.clear(); + nonRelativeExternalModuleResolutions.clear(); + closeTypeRootsWatch(); + resolvedModuleNames.clear(); + resolvedTypeReferenceDirectives.clear(); + allFilesHaveInvalidatedResolution = false; + // perDirectoryResolvedModuleNames and perDirectoryResolvedTypeReferenceDirectives could be non empty if there was exception during program update + // (between startCachingPerDirectoryResolution and finishCachingPerDirectoryResolution) + clearPerDirectoryResolutions(); + } + function startRecordingFilesWithChangedResolutions() { + filesWithChangedSetOfUnresolvedImports = []; + } + function finishRecordingFilesWithChangedResolutions() { + var collected = filesWithChangedSetOfUnresolvedImports; + filesWithChangedSetOfUnresolvedImports = undefined; + return collected; + } + function isFileWithInvalidatedNonRelativeUnresolvedImports(path) { + if (!filesWithInvalidatedNonRelativeUnresolvedImports) { + return false; + } + // Invalidated if file has unresolved imports + var value = filesWithInvalidatedNonRelativeUnresolvedImports.get(path); + return !!value && !!value.length; + } + function createHasInvalidatedResolution(forceAllFilesAsInvalidated) { + if (allFilesHaveInvalidatedResolution || forceAllFilesAsInvalidated) { + // Any file asked would have invalidated resolution + filesWithInvalidatedResolutions = undefined; + return ts.returnTrue; + } + var collected = filesWithInvalidatedResolutions; + filesWithInvalidatedResolutions = undefined; + return function (path) { return (!!collected && collected.has(path)) || + isFileWithInvalidatedNonRelativeUnresolvedImports(path); }; + } + function clearPerDirectoryResolutions() { + perDirectoryResolvedModuleNames.clear(); + nonRelativeModuleNameCache.clear(); + perDirectoryResolvedTypeReferenceDirectives.clear(); + nonRelativeExternalModuleResolutions.forEach(watchFailedLookupLocationOfNonRelativeModuleResolutions); + nonRelativeExternalModuleResolutions.clear(); + } + function finishCachingPerDirectoryResolution() { + allFilesHaveInvalidatedResolution = false; + filesWithInvalidatedNonRelativeUnresolvedImports = undefined; + clearPerDirectoryResolutions(); + directoryWatchesOfFailedLookups.forEach(function (watcher, path) { + if (watcher.refCount === 0) { + directoryWatchesOfFailedLookups.delete(path); + watcher.watcher.close(); + } + }); + } + function resolveModuleName(moduleName, containingFile, compilerOptions, host, redirectedReference) { + var primaryResult = ts.resolveModuleName(moduleName, containingFile, compilerOptions, host, moduleResolutionCache, redirectedReference); + // return result immediately only if global cache support is not enabled or if it is .ts, .tsx or .d.ts + if (!resolutionHost.getGlobalCache) { + return primaryResult; + } + // otherwise try to load typings from @types + var globalCache = resolutionHost.getGlobalCache(); + if (globalCache !== undefined && !ts.isExternalModuleNameRelative(moduleName) && !(primaryResult.resolvedModule && ts.extensionIsTS(primaryResult.resolvedModule.extension))) { + // create different collection of failed lookup locations for second pass + // if it will fail and we've already found something during the first pass - we don't want to pollute its results + var _a = ts.loadModuleFromGlobalCache(moduleName, resolutionHost.projectName, compilerOptions, host, globalCache), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; + if (resolvedModule) { + return { resolvedModule: resolvedModule, failedLookupLocations: ts.addRange(primaryResult.failedLookupLocations, failedLookupLocations) }; + } + } + // Default return the result from the first pass + return primaryResult; + } + function resolveNamesWithLocalCache(names, containingFile, redirectedReference, cache, perDirectoryCacheWithRedirects, loader, getResolutionWithResolvedFileName, shouldRetryResolution, reusedNames, logChanges) { + var path = resolutionHost.toPath(containingFile); + var resolutionsInFile = cache.get(path) || cache.set(path, ts.createMap()).get(path); + var dirPath = ts.getDirectoryPath(path); + var perDirectoryCache = perDirectoryCacheWithRedirects.getOrCreateMapOfCacheRedirects(redirectedReference); + var perDirectoryResolution = perDirectoryCache.get(dirPath); + if (!perDirectoryResolution) { + perDirectoryResolution = ts.createMap(); + perDirectoryCache.set(dirPath, perDirectoryResolution); + } + var resolvedModules = []; + var compilerOptions = resolutionHost.getCompilationSettings(); + var hasInvalidatedNonRelativeUnresolvedImport = logChanges && isFileWithInvalidatedNonRelativeUnresolvedImports(path); + // All the resolutions in this file are invalidated if this file wasnt resolved using same redirect + var program = resolutionHost.getCurrentProgram(); + var oldRedirect = program && program.getResolvedProjectReferenceToRedirect(containingFile); + var unmatchedRedirects = oldRedirect ? + !redirectedReference || redirectedReference.sourceFile.path !== oldRedirect.sourceFile.path : + !!redirectedReference; + var seenNamesInFile = ts.createMap(); + for (var _i = 0, names_2 = names; _i < names_2.length; _i++) { + var name = names_2[_i]; + var resolution = resolutionsInFile.get(name); + // Resolution is valid if it is present and not invalidated + if (!seenNamesInFile.has(name) && + allFilesHaveInvalidatedResolution || unmatchedRedirects || !resolution || resolution.isInvalidated || + // If the name is unresolved import that was invalidated, recalculate + (hasInvalidatedNonRelativeUnresolvedImport && !ts.isExternalModuleNameRelative(name) && shouldRetryResolution(resolution))) { + var existingResolution = resolution; + var resolutionInDirectory = perDirectoryResolution.get(name); + if (resolutionInDirectory) { + resolution = resolutionInDirectory; + } + else { + resolution = loader(name, containingFile, compilerOptions, resolutionHost, redirectedReference); + perDirectoryResolution.set(name, resolution); + } + resolutionsInFile.set(name, resolution); + watchFailedLookupLocationsOfExternalModuleResolutions(name, resolution); + if (existingResolution) { + stopWatchFailedLookupLocationOfResolution(existingResolution); + } + if (logChanges && filesWithChangedSetOfUnresolvedImports && !resolutionIsEqualTo(existingResolution, resolution)) { + filesWithChangedSetOfUnresolvedImports.push(path); + // reset log changes to avoid recording the same file multiple times + logChanges = false; + } + } + ts.Debug.assert(resolution !== undefined && !resolution.isInvalidated); + seenNamesInFile.set(name, true); + resolvedModules.push(getResolutionWithResolvedFileName(resolution)); + } + // Stop watching and remove the unused name + resolutionsInFile.forEach(function (resolution, name) { + if (!seenNamesInFile.has(name) && !ts.contains(reusedNames, name)) { + stopWatchFailedLookupLocationOfResolution(resolution); + resolutionsInFile.delete(name); + } + }); + return resolvedModules; + function resolutionIsEqualTo(oldResolution, newResolution) { + if (oldResolution === newResolution) { + return true; + } + if (!oldResolution || !newResolution) { + return false; + } + var oldResult = getResolutionWithResolvedFileName(oldResolution); + var newResult = getResolutionWithResolvedFileName(newResolution); + if (oldResult === newResult) { + return true; + } + if (!oldResult || !newResult) { + return false; + } + return oldResult.resolvedFileName === newResult.resolvedFileName; + } + } + function resolveTypeReferenceDirectives(typeDirectiveNames, containingFile, redirectedReference) { + return resolveNamesWithLocalCache(typeDirectiveNames, containingFile, redirectedReference, resolvedTypeReferenceDirectives, perDirectoryResolvedTypeReferenceDirectives, ts.resolveTypeReferenceDirective, getResolvedTypeReferenceDirective, + /*shouldRetryResolution*/ function (resolution) { return resolution.resolvedTypeReferenceDirective === undefined; }, + /*reusedNames*/ undefined, /*logChanges*/ false); + } + function resolveModuleNames(moduleNames, containingFile, reusedNames, redirectedReference) { + return resolveNamesWithLocalCache(moduleNames, containingFile, redirectedReference, resolvedModuleNames, perDirectoryResolvedModuleNames, resolveModuleName, getResolvedModule, + /*shouldRetryResolution*/ function (resolution) { return !resolution.resolvedModule || !ts.resolutionExtensionIsTSOrJson(resolution.resolvedModule.extension); }, reusedNames, logChangesWhenResolvingModule); + } + function getResolvedModuleWithFailedLookupLocationsFromCache(moduleName, containingFile) { + var cache = resolvedModuleNames.get(resolutionHost.toPath(containingFile)); + return cache && cache.get(moduleName); + } + function isNodeModulesDirectory(dirPath) { + return ts.endsWith(dirPath, "/node_modules"); + } + function isNodeModulesAtTypesDirectory(dirPath) { + return ts.endsWith(dirPath, "/node_modules/@types"); + } + /** + * Filter out paths like + * "/", "/user", "/user/username", "/user/username/folderAtRoot", + * "c:/", "c:/users", "c:/users/username", "c:/users/username/folderAtRoot", "c:/folderAtRoot" + * @param dirPath + */ + function canWatchDirectory(dirPath) { + var rootLength = ts.getRootLength(dirPath); + if (dirPath.length === rootLength) { + // Ignore "/", "c:/" + return false; + } + var nextDirectorySeparator = dirPath.indexOf(ts.directorySeparator, rootLength); + if (nextDirectorySeparator === -1) { + // ignore "/user", "c:/users" or "c:/folderAtRoot" + return false; + } + if (dirPath.charCodeAt(0) !== 47 /* slash */ && + dirPath.substr(rootLength, nextDirectorySeparator).search(/users/i) === -1) { + // Paths like c:/folderAtRoot/subFolder are allowed + return true; + } + for (var searchIndex = nextDirectorySeparator + 1, searchLevels = 2; searchLevels > 0; searchLevels--) { + searchIndex = dirPath.indexOf(ts.directorySeparator, searchIndex) + 1; + if (searchIndex === 0) { + // Folder isnt at expected minimun levels + return false; + } + } + return true; + } + function getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath) { + if (isInDirectoryPath(rootPath, failedLookupLocationPath)) { + // Ensure failed look up is normalized path + failedLookupLocation = ts.isRootedDiskPath(failedLookupLocation) ? ts.normalizePath(failedLookupLocation) : ts.getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory()); + ts.Debug.assert(failedLookupLocation.length === failedLookupLocationPath.length, "FailedLookup: " + failedLookupLocation + " failedLookupLocationPath: " + failedLookupLocationPath); // tslint:disable-line + var subDirectoryInRoot = failedLookupLocationPath.indexOf(ts.directorySeparator, rootPath.length + 1); + if (subDirectoryInRoot !== -1) { + // Instead of watching root, watch directory in root to avoid watching excluded directories not needed for module resolution + return { dir: failedLookupLocation.substr(0, subDirectoryInRoot), dirPath: failedLookupLocationPath.substr(0, subDirectoryInRoot) }; + } + else { + // Always watch root directory non recursively + return { dir: rootDir, dirPath: rootPath, nonRecursive: false }; // TODO: GH#18217 + } + } + return getDirectoryToWatchFromFailedLookupLocationDirectory(ts.getDirectoryPath(ts.getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory())), ts.getDirectoryPath(failedLookupLocationPath)); + } + function getDirectoryToWatchFromFailedLookupLocationDirectory(dir, dirPath) { + // If directory path contains node module, get the most parent node_modules directory for watching + while (ts.pathContainsNodeModules(dirPath)) { + dir = ts.getDirectoryPath(dir); + dirPath = ts.getDirectoryPath(dirPath); + } + // If the directory is node_modules use it to watch, always watch it recursively + if (isNodeModulesDirectory(dirPath)) { + return canWatchDirectory(ts.getDirectoryPath(dirPath)) ? { dir: dir, dirPath: dirPath } : undefined; + } + var nonRecursive = true; + // Use some ancestor of the root directory + var subDirectoryPath, subDirectory; + if (rootPath !== undefined) { + while (!isInDirectoryPath(dirPath, rootPath)) { + var parentPath = ts.getDirectoryPath(dirPath); + if (parentPath === dirPath) { + break; + } + nonRecursive = false; + subDirectoryPath = dirPath; + subDirectory = dir; + dirPath = parentPath; + dir = ts.getDirectoryPath(dir); + } + } + return canWatchDirectory(dirPath) ? { dir: subDirectory || dir, dirPath: subDirectoryPath || dirPath, nonRecursive: nonRecursive } : undefined; + } + function isPathWithDefaultFailedLookupExtension(path) { + return ts.fileExtensionIsOneOf(path, failedLookupDefaultExtensions); + } + function watchFailedLookupLocationsOfExternalModuleResolutions(name, resolution) { + // No need to set the resolution refCount + if (resolution.failedLookupLocations && resolution.failedLookupLocations.length) { + if (resolution.refCount) { + resolution.refCount++; + } + else { + resolution.refCount = 1; + if (ts.isExternalModuleNameRelative(name)) { + watchFailedLookupLocationOfResolution(resolution); + } + else { + nonRelativeExternalModuleResolutions.add(name, resolution); + } + } + } + } + function watchFailedLookupLocationOfResolution(resolution) { + ts.Debug.assert(!!resolution.refCount); + var failedLookupLocations = resolution.failedLookupLocations; + var setAtRoot = false; + for (var _i = 0, failedLookupLocations_1 = failedLookupLocations; _i < failedLookupLocations_1.length; _i++) { + var failedLookupLocation = failedLookupLocations_1[_i]; + var failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation); + var toWatch = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath); + if (toWatch) { + var dir = toWatch.dir, dirPath = toWatch.dirPath, nonRecursive = toWatch.nonRecursive; + // If the failed lookup location path is not one of the supported extensions, + // store it in the custom path + if (!isPathWithDefaultFailedLookupExtension(failedLookupLocationPath)) { + var refCount = customFailedLookupPaths.get(failedLookupLocationPath) || 0; + customFailedLookupPaths.set(failedLookupLocationPath, refCount + 1); + } + if (dirPath === rootPath) { + ts.Debug.assert(!nonRecursive); + setAtRoot = true; + } + else { + setDirectoryWatcher(dir, dirPath, nonRecursive); + } + } + } + if (setAtRoot) { + // This is always non recursive + setDirectoryWatcher(rootDir, rootPath, /*nonRecursive*/ true); // TODO: GH#18217 + } + } + function setRefCountToUndefined(resolution) { + resolution.refCount = undefined; + } + function watchFailedLookupLocationOfNonRelativeModuleResolutions(resolutions, name) { + var program = resolutionHost.getCurrentProgram(); + var updateResolution = program && program.getTypeChecker().tryFindAmbientModuleWithoutAugmentations(name) ? + setRefCountToUndefined : watchFailedLookupLocationOfResolution; + resolutions.forEach(updateResolution); + } + function setDirectoryWatcher(dir, dirPath, nonRecursive) { + var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath); + if (dirWatcher) { + ts.Debug.assert(!!nonRecursive === !!dirWatcher.nonRecursive); + dirWatcher.refCount++; + } + else { + directoryWatchesOfFailedLookups.set(dirPath, { watcher: createDirectoryWatcher(dir, dirPath, nonRecursive), refCount: 1, nonRecursive: nonRecursive }); + } + } + function stopWatchFailedLookupLocationOfResolution(resolution) { + if (!resolution.refCount) { + return; + } + resolution.refCount--; + if (resolution.refCount) { + return; + } + var failedLookupLocations = resolution.failedLookupLocations; + var removeAtRoot = false; + for (var _i = 0, failedLookupLocations_2 = failedLookupLocations; _i < failedLookupLocations_2.length; _i++) { + var failedLookupLocation = failedLookupLocations_2[_i]; + var failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation); + var toWatch = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath); + if (toWatch) { + var dirPath = toWatch.dirPath; + var refCount = customFailedLookupPaths.get(failedLookupLocationPath); + if (refCount) { + if (refCount === 1) { + customFailedLookupPaths.delete(failedLookupLocationPath); + } + else { + ts.Debug.assert(refCount > 1); + customFailedLookupPaths.set(failedLookupLocationPath, refCount - 1); + } + } + if (dirPath === rootPath) { + removeAtRoot = true; + } + else { + removeDirectoryWatcher(dirPath); + } + } + } + if (removeAtRoot) { + removeDirectoryWatcher(rootPath); + } + } + function removeDirectoryWatcher(dirPath) { + var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath); + // Do not close the watcher yet since it might be needed by other failed lookup locations. + dirWatcher.refCount--; + } + function createDirectoryWatcher(directory, dirPath, nonRecursive) { + return resolutionHost.watchDirectoryOfFailedLookupLocation(directory, function (fileOrDirectory) { + var fileOrDirectoryPath = resolutionHost.toPath(fileOrDirectory); + if (cachedDirectoryStructureHost) { + // Since the file existence changed, update the sourceFiles cache + cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); + } + if (!allFilesHaveInvalidatedResolution && invalidateResolutionOfFailedLookupLocation(fileOrDirectoryPath, dirPath === fileOrDirectoryPath)) { + resolutionHost.onInvalidatedResolution(); + } + }, nonRecursive ? 0 /* None */ : 1 /* Recursive */); + } + function removeResolutionsOfFileFromCache(cache, filePath) { + // Deleted file, stop watching failed lookups for all the resolutions in the file + var resolutions = cache.get(filePath); + if (resolutions) { + resolutions.forEach(stopWatchFailedLookupLocationOfResolution); + cache.delete(filePath); + } + } + function removeResolutionsFromProjectReferenceRedirects(filePath) { + if (!ts.fileExtensionIs(filePath, ".json" /* Json */)) { + return; + } + var program = resolutionHost.getCurrentProgram(); + if (!program) { + return; + } + // If this file is input file for the referenced project, get it + var resolvedProjectReference = program.getResolvedProjectReferenceByPath(filePath); + if (!resolvedProjectReference) { + return; + } + // filePath is for the projectReference and the containing file is from this project reference, invalidate the resolution + resolvedProjectReference.commandLine.fileNames.forEach(function (f) { return removeResolutionsOfFile(resolutionHost.toPath(f)); }); + } + function removeResolutionsOfFile(filePath) { + removeResolutionsOfFileFromCache(resolvedModuleNames, filePath); + removeResolutionsOfFileFromCache(resolvedTypeReferenceDirectives, filePath); + } + function invalidateResolutionCache(cache, isInvalidatedResolution, getResolutionWithResolvedFileName) { + var seen = ts.createMap(); + cache.forEach(function (resolutions, containingFilePath) { + var dirPath = ts.getDirectoryPath(containingFilePath); + var seenInDir = seen.get(dirPath); + if (!seenInDir) { + seenInDir = ts.createMap(); + seen.set(dirPath, seenInDir); + } + resolutions.forEach(function (resolution, name) { + if (seenInDir.has(name)) { + return; + } + seenInDir.set(name, true); + if (!resolution.isInvalidated && isInvalidatedResolution(resolution, getResolutionWithResolvedFileName)) { + // Mark the file as needing re-evaluation of module resolution instead of using it blindly. + resolution.isInvalidated = true; + (filesWithInvalidatedResolutions || (filesWithInvalidatedResolutions = ts.createMap())).set(containingFilePath, true); + } + }); + }); + } + function hasReachedResolutionIterationLimit() { + var maxSize = resolutionHost.maxNumberOfFilesToIterateForInvalidation || ts.maxNumberOfFilesToIterateForInvalidation; + return resolvedModuleNames.size > maxSize || resolvedTypeReferenceDirectives.size > maxSize; + } + function invalidateResolutions(isInvalidatedResolution) { + // If more than maxNumberOfFilesToIterateForInvalidation present, + // just invalidated all files and recalculate the resolutions for files instead + if (hasReachedResolutionIterationLimit()) { + allFilesHaveInvalidatedResolution = true; + return; + } + invalidateResolutionCache(resolvedModuleNames, isInvalidatedResolution, getResolvedModule); + invalidateResolutionCache(resolvedTypeReferenceDirectives, isInvalidatedResolution, getResolvedTypeReferenceDirective); + } + function invalidateResolutionOfFile(filePath) { + removeResolutionsOfFile(filePath); + invalidateResolutions( + // Resolution is invalidated if the resulting file name is same as the deleted file path + function (resolution, getResolutionWithResolvedFileName) { + var result = getResolutionWithResolvedFileName(resolution); + return !!result && resolutionHost.toPath(result.resolvedFileName) === filePath; // TODO: GH#18217 + }); + } + function setFilesWithInvalidatedNonRelativeUnresolvedImports(filesMap) { + ts.Debug.assert(filesWithInvalidatedNonRelativeUnresolvedImports === filesMap || filesWithInvalidatedNonRelativeUnresolvedImports === undefined); + filesWithInvalidatedNonRelativeUnresolvedImports = filesMap; + } + function invalidateResolutionOfFailedLookupLocation(fileOrDirectoryPath, isCreatingWatchedDirectory) { + var isChangedFailedLookupLocation; + if (isCreatingWatchedDirectory) { + // Watching directory is created + // Invalidate any resolution has failed lookup in this directory + isChangedFailedLookupLocation = function (location) { return isInDirectoryPath(fileOrDirectoryPath, resolutionHost.toPath(location)); }; + } + else { + // If something to do with folder/file starting with "." in node_modules folder, skip it + if (isPathInNodeModulesStartingWithDot(fileOrDirectoryPath)) + return false; + // Some file or directory in the watching directory is created + // Return early if it does not have any of the watching extension or not the custom failed lookup path + var dirOfFileOrDirectory = ts.getDirectoryPath(fileOrDirectoryPath); + if (isNodeModulesAtTypesDirectory(fileOrDirectoryPath) || isNodeModulesDirectory(fileOrDirectoryPath) || + isNodeModulesAtTypesDirectory(dirOfFileOrDirectory) || isNodeModulesDirectory(dirOfFileOrDirectory)) { + // Invalidate any resolution from this directory + isChangedFailedLookupLocation = function (location) { + var locationPath = resolutionHost.toPath(location); + return locationPath === fileOrDirectoryPath || ts.startsWith(resolutionHost.toPath(location), fileOrDirectoryPath); + }; + } + else { + if (!isPathWithDefaultFailedLookupExtension(fileOrDirectoryPath) && !customFailedLookupPaths.has(fileOrDirectoryPath)) { + return false; + } + // Ignore emits from the program + if (ts.isEmittedFileOfProgram(resolutionHost.getCurrentProgram(), fileOrDirectoryPath)) { + return false; + } + // Resolution need to be invalidated if failed lookup location is same as the file or directory getting created + isChangedFailedLookupLocation = function (location) { return resolutionHost.toPath(location) === fileOrDirectoryPath; }; + } + } + var hasChangedFailedLookupLocation = function (resolution) { return ts.some(resolution.failedLookupLocations, isChangedFailedLookupLocation); }; + var invalidatedFilesCount = filesWithInvalidatedResolutions && filesWithInvalidatedResolutions.size; + invalidateResolutions( + // Resolution is invalidated if the resulting file name is same as the deleted file path + hasChangedFailedLookupLocation); + return allFilesHaveInvalidatedResolution || filesWithInvalidatedResolutions && filesWithInvalidatedResolutions.size !== invalidatedFilesCount; + } + function closeTypeRootsWatch() { + ts.clearMap(typeRootsWatches, ts.closeFileWatcher); + } + function getDirectoryToWatchFailedLookupLocationFromTypeRoot(typeRoot, typeRootPath) { + if (allFilesHaveInvalidatedResolution) { + return undefined; + } + if (isInDirectoryPath(rootPath, typeRootPath)) { + return rootPath; + } + var toWatch = getDirectoryToWatchFromFailedLookupLocationDirectory(typeRoot, typeRootPath); + return toWatch && directoryWatchesOfFailedLookups.has(toWatch.dirPath) ? toWatch.dirPath : undefined; + } + function createTypeRootsWatch(typeRootPath, typeRoot) { + // Create new watch and recursive info + return resolutionHost.watchTypeRootsDirectory(typeRoot, function (fileOrDirectory) { + var fileOrDirectoryPath = resolutionHost.toPath(fileOrDirectory); + if (cachedDirectoryStructureHost) { + // Since the file existence changed, update the sourceFiles cache + cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); + } + // For now just recompile + // We could potentially store more data here about whether it was/would be really be used or not + // and with that determine to trigger compilation but for now this is enough + resolutionHost.onChangedAutomaticTypeDirectiveNames(); + // Since directory watchers invoked are flaky, the failed lookup location events might not be triggered + // So handle to failed lookup locations here as well to ensure we are invalidating resolutions + var dirPath = getDirectoryToWatchFailedLookupLocationFromTypeRoot(typeRoot, typeRootPath); + if (dirPath && invalidateResolutionOfFailedLookupLocation(fileOrDirectoryPath, dirPath === fileOrDirectoryPath)) { + resolutionHost.onInvalidatedResolution(); + } + }, 1 /* Recursive */); + } + /** + * Watches the types that would get added as part of getAutomaticTypeDirectiveNames + * To be called when compiler options change + */ + function updateTypeRootsWatch() { + var options = resolutionHost.getCompilationSettings(); + if (options.types) { + // No need to do any watch since resolution cache is going to handle the failed lookups + // for the types added by this + closeTypeRootsWatch(); + return; + } + // we need to assume the directories exist to ensure that we can get all the type root directories that get included + // But filter directories that are at root level to say directory doesnt exist, so that we arent watching them + var typeRoots = ts.getEffectiveTypeRoots(options, { directoryExists: directoryExistsForTypeRootWatch, getCurrentDirectory: getCurrentDirectory }); + if (typeRoots) { + ts.mutateMap(typeRootsWatches, ts.arrayToMap(typeRoots, function (tr) { return resolutionHost.toPath(tr); }), { + createNewValue: createTypeRootsWatch, + onDeleteValue: ts.closeFileWatcher + }); + } + else { + closeTypeRootsWatch(); + } + } + /** + * Use this function to return if directory exists to get type roots to watch + * If we return directory exists then only the paths will be added to type roots + * Hence return true for all directories except root directories which are filtered from watching + */ + function directoryExistsForTypeRootWatch(nodeTypesDirectory) { + var dir = ts.getDirectoryPath(ts.getDirectoryPath(nodeTypesDirectory)); + var dirPath = resolutionHost.toPath(dir); + return dirPath === rootPath || canWatchDirectory(dirPath); + } + } + ts.createResolutionCache = createResolutionCache; +})(ts || (ts = {})); +// Used by importFixes, getEditsForFileRename, and declaration emit to synthesize import module specifiers. +/* @internal */ +var ts; +(function (ts) { + var moduleSpecifiers; + (function (moduleSpecifiers) { + var RelativePreference; + (function (RelativePreference) { + RelativePreference[RelativePreference["Relative"] = 0] = "Relative"; + RelativePreference[RelativePreference["NonRelative"] = 1] = "NonRelative"; + RelativePreference[RelativePreference["Auto"] = 2] = "Auto"; + })(RelativePreference || (RelativePreference = {})); + // See UserPreferences#importPathEnding + var Ending; + (function (Ending) { + Ending[Ending["Minimal"] = 0] = "Minimal"; + Ending[Ending["Index"] = 1] = "Index"; + Ending[Ending["JsExtension"] = 2] = "JsExtension"; + })(Ending || (Ending = {})); + function getPreferences(_a, compilerOptions, importingSourceFile) { + var importModuleSpecifierPreference = _a.importModuleSpecifierPreference, importModuleSpecifierEnding = _a.importModuleSpecifierEnding; + return { + relativePreference: importModuleSpecifierPreference === "relative" ? 0 /* Relative */ : importModuleSpecifierPreference === "non-relative" ? 1 /* NonRelative */ : 2 /* Auto */, + ending: getEnding(), + }; + function getEnding() { + switch (importModuleSpecifierEnding) { + case "minimal": return 0 /* Minimal */; + case "index": return 1 /* Index */; + case "js": return 2 /* JsExtension */; + default: return usesJsExtensionOnImports(importingSourceFile) ? 2 /* JsExtension */ + : ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.NodeJs ? 1 /* Index */ : 0 /* Minimal */; + } + } + } + function getPreferencesForUpdate(compilerOptions, oldImportSpecifier) { + return { + relativePreference: ts.isExternalModuleNameRelative(oldImportSpecifier) ? 0 /* Relative */ : 1 /* NonRelative */, + ending: ts.hasJSOrJsonFileExtension(oldImportSpecifier) ? 2 /* JsExtension */ + : ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.NodeJs || ts.endsWith(oldImportSpecifier, "index") ? 1 /* Index */ : 0 /* Minimal */, + }; + } + function updateModuleSpecifier(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, oldImportSpecifier) { + var res = getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, getPreferencesForUpdate(compilerOptions, oldImportSpecifier)); + if (res === oldImportSpecifier) + return undefined; + return res; + } + moduleSpecifiers.updateModuleSpecifier = updateModuleSpecifier; + // Note: importingSourceFile is just for usesJsExtensionOnImports + function getModuleSpecifier(compilerOptions, importingSourceFile, importingSourceFileName, toFileName, host, files, preferences, redirectTargetsMap) { + if (preferences === void 0) { preferences = {}; } + return getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, getPreferences(preferences, compilerOptions, importingSourceFile)); + } + moduleSpecifiers.getModuleSpecifier = getModuleSpecifier; + function getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, preferences) { + var info = getInfo(importingSourceFileName, host); + var modulePaths = getAllModulePaths(files, importingSourceFileName, toFileName, info.getCanonicalFileName, host, redirectTargetsMap); + return ts.firstDefined(modulePaths, function (moduleFileName) { return tryGetModuleNameAsNodeModule(moduleFileName, info, host, compilerOptions); }) || + getLocalModuleSpecifier(toFileName, info, compilerOptions, preferences); + } + // Returns an import for each symlink and for the realpath. + function getModuleSpecifiers(moduleSymbol, compilerOptions, importingSourceFile, host, files, userPreferences, redirectTargetsMap) { + var ambient = tryGetModuleNameFromAmbientModule(moduleSymbol); + if (ambient) + return [ambient]; + var info = getInfo(importingSourceFile.path, host); + var moduleSourceFile = ts.getSourceFileOfNode(moduleSymbol.valueDeclaration || ts.getNonAugmentationDeclaration(moduleSymbol)); + var modulePaths = getAllModulePaths(files, importingSourceFile.path, moduleSourceFile.fileName, info.getCanonicalFileName, host, redirectTargetsMap); + var preferences = getPreferences(userPreferences, compilerOptions, importingSourceFile); + var global = ts.mapDefined(modulePaths, function (moduleFileName) { return tryGetModuleNameAsNodeModule(moduleFileName, info, host, compilerOptions); }); + return global.length ? global : modulePaths.map(function (moduleFileName) { return getLocalModuleSpecifier(moduleFileName, info, compilerOptions, preferences); }); + } + moduleSpecifiers.getModuleSpecifiers = getModuleSpecifiers; + // importingSourceFileName is separate because getEditsForFileRename may need to specify an updated path + function getInfo(importingSourceFileName, host) { + var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames ? host.useCaseSensitiveFileNames() : true); + var sourceDirectory = ts.getDirectoryPath(importingSourceFileName); + return { getCanonicalFileName: getCanonicalFileName, sourceDirectory: sourceDirectory }; + } + function getLocalModuleSpecifier(moduleFileName, _a, compilerOptions, _b) { + var getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory; + var ending = _b.ending, relativePreference = _b.relativePreference; + var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths, rootDirs = compilerOptions.rootDirs; + var relativePath = rootDirs && tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName) || + removeExtensionAndIndexPostFix(ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, moduleFileName, getCanonicalFileName)), ending, compilerOptions); + if (!baseUrl || relativePreference === 0 /* Relative */) { + return relativePath; + } + var relativeToBaseUrl = getRelativePathIfInDirectory(moduleFileName, baseUrl, getCanonicalFileName); + if (!relativeToBaseUrl) { + return relativePath; + } + var importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, ending, compilerOptions); + var fromPaths = paths && tryGetModuleNameFromPaths(ts.removeFileExtension(relativeToBaseUrl), importRelativeToBaseUrl, paths); + var nonRelative = fromPaths === undefined ? importRelativeToBaseUrl : fromPaths; + if (relativePreference === 1 /* NonRelative */) { + return nonRelative; + } + if (relativePreference !== 2 /* Auto */) + ts.Debug.assertNever(relativePreference); + // Prefer a relative import over a baseUrl import if it has fewer components. + return isPathRelativeToParent(nonRelative) || countPathComponents(relativePath) < countPathComponents(nonRelative) ? relativePath : nonRelative; + } + function countPathComponents(path) { + var count = 0; + for (var i = ts.startsWith(path, "./") ? 2 : 0; i < path.length; i++) { + if (path.charCodeAt(i) === 47 /* slash */) + count++; + } + return count; + } + moduleSpecifiers.countPathComponents = countPathComponents; + function usesJsExtensionOnImports(_a) { + var imports = _a.imports; + return ts.firstDefined(imports, function (_a) { + var text = _a.text; + return ts.pathIsRelative(text) ? ts.hasJSOrJsonFileExtension(text) : undefined; + }) || false; + } + function stringsEqual(a, b, getCanonicalFileName) { + return getCanonicalFileName(a) === getCanonicalFileName(b); + } + // KLUDGE: Don't assume one 'node_modules' links to another. More likely a single directory inside the node_modules is the symlink. + // ALso, don't assume that an `@foo` directory is linked. More likely the contents of that are linked. + function isNodeModulesOrScopedPackageDirectory(s, getCanonicalFileName) { + return getCanonicalFileName(s) === "node_modules" || ts.startsWith(s, "@"); + } + function guessDirectorySymlink(a, b, cwd, getCanonicalFileName) { + var aParts = ts.getPathComponents(ts.toPath(a, cwd, getCanonicalFileName)); + var bParts = ts.getPathComponents(ts.toPath(b, cwd, getCanonicalFileName)); + while (!isNodeModulesOrScopedPackageDirectory(aParts[aParts.length - 2], getCanonicalFileName) && + !isNodeModulesOrScopedPackageDirectory(bParts[bParts.length - 2], getCanonicalFileName) && + stringsEqual(aParts[aParts.length - 1], bParts[bParts.length - 1], getCanonicalFileName)) { + aParts.pop(); + bParts.pop(); + } + return [ts.getPathFromPathComponents(aParts), ts.getPathFromPathComponents(bParts)]; + } + function discoverProbableSymlinks(files, getCanonicalFileName, cwd) { + var result = ts.createMap(); + var symlinks = ts.mapDefined(files, function (sf) { + return sf.resolvedModules && ts.firstDefinedIterator(sf.resolvedModules.values(), function (res) { + return res && res.originalPath && res.resolvedFileName !== res.originalPath ? [res.resolvedFileName, res.originalPath] : undefined; + }); + }); + for (var _i = 0, symlinks_1 = symlinks; _i < symlinks_1.length; _i++) { + var _a = symlinks_1[_i], resolvedPath = _a[0], originalPath = _a[1]; + var _b = guessDirectorySymlink(resolvedPath, originalPath, cwd, getCanonicalFileName), commonResolved = _b[0], commonOriginal = _b[1]; + result.set(commonOriginal, commonResolved); + } + return result; + } + /** + * Looks for existing imports that use symlinks to this module. + * Symlinks will be returned first so they are preferred over the real path. + */ + function getAllModulePaths(files, importingFileName, importedFileName, getCanonicalFileName, host, redirectTargetsMap) { + var redirects = redirectTargetsMap.get(importedFileName); + var importedFileNames = redirects ? redirects.concat([importedFileName]) : [importedFileName]; + var cwd = host.getCurrentDirectory ? host.getCurrentDirectory() : ""; + var targets = importedFileNames.map(function (f) { return ts.getNormalizedAbsolutePath(f, cwd); }); + var links = discoverProbableSymlinks(files, getCanonicalFileName, cwd); + var result = []; + var compareStrings = (!host.useCaseSensitiveFileNames || host.useCaseSensitiveFileNames()) ? ts.compareStringsCaseSensitive : ts.compareStringsCaseInsensitive; + links.forEach(function (resolved, path) { + if (ts.startsWithDirectory(importingFileName, resolved, getCanonicalFileName)) { + return; // Don't want to a package to globally import from itself + } + var target = targets.find(function (t) { return compareStrings(t.slice(0, resolved.length + 1), resolved + "/") === 0 /* EqualTo */; }); + if (target === undefined) + return; + var relative = ts.getRelativePathFromDirectory(resolved, target, getCanonicalFileName); + var option = ts.resolvePath(path, relative); + if (!host.fileExists || host.fileExists(option)) { + result.push(option); + } + }); + result.push.apply(result, targets); + return result; + } + function tryGetModuleNameFromAmbientModule(moduleSymbol) { + var decl = ts.find(moduleSymbol.declarations, function (d) { return ts.isNonGlobalAmbientModule(d) && (!ts.isExternalModuleAugmentation(d) || !ts.isExternalModuleNameRelative(ts.getTextOfIdentifierOrLiteral(d.name))); }); + if (decl) { + return decl.name.text; + } + } + function tryGetModuleNameFromPaths(relativeToBaseUrlWithIndex, relativeToBaseUrl, paths) { + for (var key in paths) { + for (var _i = 0, _a = paths[key]; _i < _a.length; _i++) { + var patternText_1 = _a[_i]; + var pattern = ts.removeFileExtension(ts.normalizePath(patternText_1)); + var indexOfStar = pattern.indexOf("*"); + if (indexOfStar !== -1) { + var prefix = pattern.substr(0, indexOfStar); + var suffix = pattern.substr(indexOfStar + 1); + if (relativeToBaseUrl.length >= prefix.length + suffix.length && + ts.startsWith(relativeToBaseUrl, prefix) && + ts.endsWith(relativeToBaseUrl, suffix) || + !suffix && relativeToBaseUrl === ts.removeTrailingDirectorySeparator(prefix)) { + var matchedStar = relativeToBaseUrl.substr(prefix.length, relativeToBaseUrl.length - suffix.length); + return key.replace("*", matchedStar); + } + } + else if (pattern === relativeToBaseUrl || pattern === relativeToBaseUrlWithIndex) { + return key; + } + } + } + } + function tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName) { + var normalizedTargetPath = getPathRelativeToRootDirs(moduleFileName, rootDirs, getCanonicalFileName); + if (normalizedTargetPath === undefined) { + return undefined; + } + var normalizedSourcePath = getPathRelativeToRootDirs(sourceDirectory, rootDirs, getCanonicalFileName); + var relativePath = normalizedSourcePath !== undefined ? ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(normalizedSourcePath, normalizedTargetPath, getCanonicalFileName)) : normalizedTargetPath; + return ts.removeFileExtension(relativePath); + } + function tryGetModuleNameAsNodeModule(moduleFileName, _a, host, options) { + var getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory; + if (!host.fileExists || !host.readFile) { + return undefined; + } + var parts = getNodeModulePathParts(moduleFileName); + if (!parts) { + return undefined; + } + var packageRootPath = moduleFileName.substring(0, parts.packageRootIndex); + var packageJsonPath = ts.combinePaths(packageRootPath, "package.json"); + var packageJsonContent = host.fileExists(packageJsonPath) + ? JSON.parse(host.readFile(packageJsonPath)) + : undefined; + var versionPaths = packageJsonContent && packageJsonContent.typesVersions + ? ts.getPackageJsonTypesVersionsPaths(packageJsonContent.typesVersions) + : undefined; + if (versionPaths) { + var subModuleName = moduleFileName.slice(parts.packageRootIndex + 1); + var fromPaths = tryGetModuleNameFromPaths(ts.removeFileExtension(subModuleName), removeExtensionAndIndexPostFix(subModuleName, 0 /* Minimal */, options), versionPaths.paths); + if (fromPaths !== undefined) { + moduleFileName = ts.combinePaths(moduleFileName.slice(0, parts.packageRootIndex), fromPaths); + } + } + // Simplify the full file path to something that can be resolved by Node. + // If the module could be imported by a directory name, use that directory's name + var moduleSpecifier = getDirectoryOrExtensionlessFileName(moduleFileName); + // Get a path that's relative to node_modules or the importing file's path + // if node_modules folder is in this folder or any of its parent folders, no need to keep it. + if (!ts.startsWith(sourceDirectory, getCanonicalFileName(moduleSpecifier.substring(0, parts.topLevelNodeModulesIndex)))) + return undefined; + // If the module was found in @types, get the actual Node package name + var nodeModulesDirectoryName = moduleSpecifier.substring(parts.topLevelPackageNameIndex + 1); + var packageName = ts.getPackageNameFromTypesPackageName(nodeModulesDirectoryName); + // For classic resolution, only allow importing from node_modules/@types, not other node_modules + return ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs && packageName === nodeModulesDirectoryName ? undefined : packageName; + function getDirectoryOrExtensionlessFileName(path) { + // If the file is the main module, it can be imported by the package name + if (packageJsonContent) { + var mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main; + if (mainFileRelative) { + var mainExportFile = ts.toPath(mainFileRelative, packageRootPath, getCanonicalFileName); + if (ts.removeFileExtension(mainExportFile) === ts.removeFileExtension(getCanonicalFileName(path))) { + return packageRootPath; + } + } + } + // We still have a file name - remove the extension + var fullModulePathWithoutExtension = ts.removeFileExtension(path); + // If the file is /index, it can be imported by its directory name + // IFF there is not _also_ a file by the same name + if (getCanonicalFileName(fullModulePathWithoutExtension.substring(parts.fileNameIndex)) === "/index" && !tryGetAnyFileFromPath(host, fullModulePathWithoutExtension.substring(0, parts.fileNameIndex))) { + return fullModulePathWithoutExtension.substring(0, parts.fileNameIndex); + } + return fullModulePathWithoutExtension; + } + } + function tryGetAnyFileFromPath(host, path) { + if (!host.fileExists) + return; + // We check all js, `node` and `json` extensions in addition to TS, since node module resolution would also choose those over the directory + var extensions = ts.getSupportedExtensions({ allowJs: true }, [{ extension: "node", isMixedContent: false }, { extension: "json", isMixedContent: false, scriptKind: 6 /* JSON */ }]); + for (var _i = 0, extensions_3 = extensions; _i < extensions_3.length; _i++) { + var e = extensions_3[_i]; + var fullPath = path + e; + if (host.fileExists(fullPath)) { + return fullPath; + } + } + } + function getNodeModulePathParts(fullPath) { + // If fullPath can't be valid module file within node_modules, returns undefined. + // Example of expected pattern: /base/path/node_modules/[@scope/otherpackage/@otherscope/node_modules/]package/[subdirectory/]file.js + // Returns indices: ^ ^ ^ ^ + var topLevelNodeModulesIndex = 0; + var topLevelPackageNameIndex = 0; + var packageRootIndex = 0; + var fileNameIndex = 0; + var States; + (function (States) { + States[States["BeforeNodeModules"] = 0] = "BeforeNodeModules"; + States[States["NodeModules"] = 1] = "NodeModules"; + States[States["Scope"] = 2] = "Scope"; + States[States["PackageContent"] = 3] = "PackageContent"; + })(States || (States = {})); + var partStart = 0; + var partEnd = 0; + var state = 0 /* BeforeNodeModules */; + while (partEnd >= 0) { + partStart = partEnd; + partEnd = fullPath.indexOf("/", partStart + 1); + switch (state) { + case 0 /* BeforeNodeModules */: + if (fullPath.indexOf(ts.nodeModulesPathPart, partStart) === partStart) { + topLevelNodeModulesIndex = partStart; + topLevelPackageNameIndex = partEnd; + state = 1 /* NodeModules */; + } + break; + case 1 /* NodeModules */: + case 2 /* Scope */: + if (state === 1 /* NodeModules */ && fullPath.charAt(partStart + 1) === "@") { + state = 2 /* Scope */; + } + else { + packageRootIndex = partEnd; + state = 3 /* PackageContent */; + } + break; + case 3 /* PackageContent */: + if (fullPath.indexOf(ts.nodeModulesPathPart, partStart) === partStart) { + state = 1 /* NodeModules */; + } + else { + state = 3 /* PackageContent */; + } + break; + } + } + fileNameIndex = partStart; + return state > 1 /* NodeModules */ ? { topLevelNodeModulesIndex: topLevelNodeModulesIndex, topLevelPackageNameIndex: topLevelPackageNameIndex, packageRootIndex: packageRootIndex, fileNameIndex: fileNameIndex } : undefined; + } + function getPathRelativeToRootDirs(path, rootDirs, getCanonicalFileName) { + return ts.firstDefined(rootDirs, function (rootDir) { + var relativePath = getRelativePathIfInDirectory(path, rootDir, getCanonicalFileName); // TODO: GH#18217 + return isPathRelativeToParent(relativePath) ? undefined : relativePath; + }); + } + function removeExtensionAndIndexPostFix(fileName, ending, options) { + if (ts.fileExtensionIs(fileName, ".json" /* Json */)) + return fileName; + var noExtension = ts.removeFileExtension(fileName); + switch (ending) { + case 0 /* Minimal */: + return ts.removeSuffix(noExtension, "/index"); + case 1 /* Index */: + return noExtension; + case 2 /* JsExtension */: + return noExtension + getJSExtensionForFile(fileName, options); + default: + return ts.Debug.assertNever(ending); + } + } + function getJSExtensionForFile(fileName, options) { + var ext = ts.extensionFromPath(fileName); + switch (ext) { + case ".ts" /* Ts */: + case ".d.ts" /* Dts */: + return ".js" /* Js */; + case ".tsx" /* Tsx */: + return options.jsx === 1 /* Preserve */ ? ".jsx" /* Jsx */ : ".js" /* Js */; + case ".js" /* Js */: + case ".jsx" /* Jsx */: + case ".json" /* Json */: + return ext; + default: + return ts.Debug.assertNever(ext); + } + } + function getRelativePathIfInDirectory(path, directoryPath, getCanonicalFileName) { + var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); + return ts.isRootedDiskPath(relativePath) ? undefined : relativePath; + } + function isPathRelativeToParent(path) { + return ts.startsWith(path, ".."); + } + })(moduleSpecifiers = ts.moduleSpecifiers || (ts.moduleSpecifiers = {})); +})(ts || (ts = {})); +/*@internal*/ +var ts; +(function (ts) { + var sysFormatDiagnosticsHost = ts.sys ? { + getCurrentDirectory: function () { return ts.sys.getCurrentDirectory(); }, + getNewLine: function () { return ts.sys.newLine; }, + getCanonicalFileName: ts.createGetCanonicalFileName(ts.sys.useCaseSensitiveFileNames) + } : undefined; // TODO: GH#18217 + /** + * Create a function that reports error by writing to the system and handles the formating of the diagnostic + */ + function createDiagnosticReporter(system, pretty) { + var host = system === ts.sys ? sysFormatDiagnosticsHost : { + getCurrentDirectory: function () { return system.getCurrentDirectory(); }, + getNewLine: function () { return system.newLine; }, + getCanonicalFileName: ts.createGetCanonicalFileName(system.useCaseSensitiveFileNames), + }; + if (!pretty) { + return function (diagnostic) { return system.write(ts.formatDiagnostic(diagnostic, host)); }; + } + var diagnostics = new Array(1); + return function (diagnostic) { + diagnostics[0] = diagnostic; + system.write(ts.formatDiagnosticsWithColorAndContext(diagnostics, host) + host.getNewLine()); + diagnostics[0] = undefined; // TODO: GH#18217 + }; + } + ts.createDiagnosticReporter = createDiagnosticReporter; + /** + * @returns Whether the screen was cleared. + */ + function clearScreenIfNotWatchingForFileChanges(system, diagnostic, options) { + if (system.clearScreen && + !options.preserveWatchOutput && + !options.extendedDiagnostics && + !options.diagnostics && + ts.contains(ts.screenStartingMessageCodes, diagnostic.code)) { + system.clearScreen(); + return true; + } + return false; + } + ts.screenStartingMessageCodes = [ + ts.Diagnostics.Starting_compilation_in_watch_mode.code, + ts.Diagnostics.File_change_detected_Starting_incremental_compilation.code, + ]; + function getPlainDiagnosticFollowingNewLines(diagnostic, newLine) { + return ts.contains(ts.screenStartingMessageCodes, diagnostic.code) + ? newLine + newLine + : newLine; + } + /** + * Create a function that reports watch status by writing to the system and handles the formating of the diagnostic + */ + function createWatchStatusReporter(system, pretty) { + return pretty ? + function (diagnostic, newLine, options) { + clearScreenIfNotWatchingForFileChanges(system, diagnostic, options); + var output = "[" + ts.formatColorAndReset(new Date().toLocaleTimeString(), ts.ForegroundColorEscapeSequences.Grey) + "] "; + output += "" + ts.flattenDiagnosticMessageText(diagnostic.messageText, system.newLine) + (newLine + newLine); + system.write(output); + } : + function (diagnostic, newLine, options) { + var output = ""; + if (!clearScreenIfNotWatchingForFileChanges(system, diagnostic, options)) { + output += newLine; + } + output += new Date().toLocaleTimeString() + " - "; + output += "" + ts.flattenDiagnosticMessageText(diagnostic.messageText, system.newLine) + getPlainDiagnosticFollowingNewLines(diagnostic, newLine); + system.write(output); + }; + } + ts.createWatchStatusReporter = createWatchStatusReporter; + /** Parses config file using System interface */ + function parseConfigFileWithSystem(configFileName, optionsToExtend, system, reportDiagnostic) { + var host = system; + host.onUnRecoverableConfigFileDiagnostic = function (diagnostic) { return reportUnrecoverableDiagnostic(ts.sys, reportDiagnostic, diagnostic); }; + var result = ts.getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host); + host.onUnRecoverableConfigFileDiagnostic = undefined; // TODO: GH#18217 + return result; + } + ts.parseConfigFileWithSystem = parseConfigFileWithSystem; + function getErrorCountForSummary(diagnostics) { + return ts.countWhere(diagnostics, function (diagnostic) { return diagnostic.category === ts.DiagnosticCategory.Error; }); + } + ts.getErrorCountForSummary = getErrorCountForSummary; + function getWatchErrorSummaryDiagnosticMessage(errorCount) { + return errorCount === 1 ? + ts.Diagnostics.Found_1_error_Watching_for_file_changes : + ts.Diagnostics.Found_0_errors_Watching_for_file_changes; + } + ts.getWatchErrorSummaryDiagnosticMessage = getWatchErrorSummaryDiagnosticMessage; + function getErrorSummaryText(errorCount, newLine) { + if (errorCount === 0) + return ""; + var d = ts.createCompilerDiagnostic(errorCount === 1 ? ts.Diagnostics.Found_1_error : ts.Diagnostics.Found_0_errors, errorCount); + return "" + newLine + ts.flattenDiagnosticMessageText(d.messageText, newLine) + newLine + newLine; + } + ts.getErrorSummaryText = getErrorSummaryText; + /** + * Helper that emit files, report diagnostics and lists emitted and/or source files depending on compiler options + */ + function emitFilesAndReportErrors(program, reportDiagnostic, writeFileName, reportSummary, writeFile) { + // First get and report any syntactic errors. + var diagnostics = program.getConfigFileParsingDiagnostics().slice(); + var configFileParsingDiagnosticsLength = diagnostics.length; + ts.addRange(diagnostics, program.getSyntacticDiagnostics()); + var reportSemanticDiagnostics = false; + // If we didn't have any syntactic errors, then also try getting the global and + // semantic errors. + if (diagnostics.length === configFileParsingDiagnosticsLength) { + ts.addRange(diagnostics, program.getOptionsDiagnostics()); + ts.addRange(diagnostics, program.getGlobalDiagnostics()); + if (diagnostics.length === configFileParsingDiagnosticsLength) { + reportSemanticDiagnostics = true; + } + } + // Emit and report any errors we ran into. + var _a = program.emit(/*targetSourceFile*/ undefined, writeFile), emittedFiles = _a.emittedFiles, emitSkipped = _a.emitSkipped, emitDiagnostics = _a.diagnostics; + ts.addRange(diagnostics, emitDiagnostics); + if (reportSemanticDiagnostics) { + ts.addRange(diagnostics, program.getSemanticDiagnostics()); + } + ts.sortAndDeduplicateDiagnostics(diagnostics).forEach(reportDiagnostic); + if (writeFileName) { + var currentDir_1 = program.getCurrentDirectory(); + ts.forEach(emittedFiles, function (file) { + var filepath = ts.getNormalizedAbsolutePath(file, currentDir_1); + writeFileName("TSFILE: " + filepath); + }); + if (program.getCompilerOptions().listFiles) { + ts.forEach(program.getSourceFiles(), function (file) { + writeFileName(file.fileName); + }); + } + } + if (reportSummary) { + reportSummary(getErrorCountForSummary(diagnostics)); + } + if (emitSkipped && diagnostics.length > 0) { + // If the emitter didn't emit anything, then pass that value along. + return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; + } + else if (diagnostics.length > 0) { + // The emitter emitted something, inform the caller if that happened in the presence + // of diagnostics or not. + return ts.ExitStatus.DiagnosticsPresent_OutputsGenerated; + } + return ts.ExitStatus.Success; + } + ts.emitFilesAndReportErrors = emitFilesAndReportErrors; + var noopFileWatcher = { close: ts.noop }; + function createWatchHost(system, reportWatchStatus) { + if (system === void 0) { system = ts.sys; } + var onWatchStatusChange = reportWatchStatus || createWatchStatusReporter(system); + return { + onWatchStatusChange: onWatchStatusChange, + watchFile: system.watchFile ? (function (path, callback, pollingInterval) { return system.watchFile(path, callback, pollingInterval); }) : function () { return noopFileWatcher; }, + watchDirectory: system.watchDirectory ? (function (path, callback, recursive) { return system.watchDirectory(path, callback, recursive); }) : function () { return noopFileWatcher; }, + setTimeout: system.setTimeout ? (function (callback, ms) { + var args = []; + for (var _i = 2; _i < arguments.length; _i++) { + args[_i - 2] = arguments[_i]; + } + var _a; + return (_a = system.setTimeout).call.apply(_a, [system, callback, ms].concat(args)); + }) : ts.noop, + clearTimeout: system.clearTimeout ? (function (timeoutId) { return system.clearTimeout(timeoutId); }) : ts.noop + }; + } + ts.createWatchHost = createWatchHost; + /** + * Creates the watch compiler host that can be extended with config file or root file names and options host + */ + function createWatchCompilerHost(system, createProgram, reportDiagnostic, reportWatchStatus) { + if (system === void 0) { system = ts.sys; } + if (!createProgram) { + createProgram = ts.createEmitAndSemanticDiagnosticsBuilderProgram; + } + var host = system; + host; // tslint:disable-line no-unused-expression (TODO: `host` is unused!) + var useCaseSensitiveFileNames = function () { return system.useCaseSensitiveFileNames; }; + var writeFileName = function (s) { return system.write(s + system.newLine); }; + var _a = createWatchHost(system, reportWatchStatus), onWatchStatusChange = _a.onWatchStatusChange, watchFile = _a.watchFile, watchDirectory = _a.watchDirectory, setTimeout = _a.setTimeout, clearTimeout = _a.clearTimeout; + return { + useCaseSensitiveFileNames: useCaseSensitiveFileNames, + getNewLine: function () { return system.newLine; }, + getCurrentDirectory: function () { return system.getCurrentDirectory(); }, + getDefaultLibLocation: getDefaultLibLocation, + getDefaultLibFileName: function (options) { return ts.combinePaths(getDefaultLibLocation(), ts.getDefaultLibFileName(options)); }, + fileExists: function (path) { return system.fileExists(path); }, + readFile: function (path, encoding) { return system.readFile(path, encoding); }, + directoryExists: function (path) { return system.directoryExists(path); }, + getDirectories: function (path) { return system.getDirectories(path); }, + readDirectory: function (path, extensions, exclude, include, depth) { return system.readDirectory(path, extensions, exclude, include, depth); }, + realpath: system.realpath && (function (path) { return system.realpath(path); }), + getEnvironmentVariable: system.getEnvironmentVariable && (function (name) { return system.getEnvironmentVariable(name); }), + watchFile: watchFile, + watchDirectory: watchDirectory, + setTimeout: setTimeout, + clearTimeout: clearTimeout, + trace: function (s) { return system.write(s); }, + onWatchStatusChange: onWatchStatusChange, + createDirectory: function (path) { return system.createDirectory(path); }, + writeFile: function (path, data, writeByteOrderMark) { return system.writeFile(path, data, writeByteOrderMark); }, + onCachedDirectoryStructureHostCreate: function (cacheHost) { return host = cacheHost || system; }, + createHash: system.createHash && (function (s) { return system.createHash(s); }), + createProgram: createProgram, + afterProgramCreate: emitFilesAndReportErrorUsingBuilder + }; + function getDefaultLibLocation() { + return ts.getDirectoryPath(ts.normalizePath(system.getExecutingFilePath())); + } + function emitFilesAndReportErrorUsingBuilder(builderProgram) { + var compilerOptions = builderProgram.getCompilerOptions(); + var newLine = ts.getNewLineCharacter(compilerOptions, function () { return system.newLine; }); + emitFilesAndReportErrors(builderProgram, reportDiagnostic, writeFileName, function (errorCount) { return onWatchStatusChange(ts.createCompilerDiagnostic(getWatchErrorSummaryDiagnosticMessage(errorCount), errorCount), newLine, compilerOptions); }); + } + } + /** + * Report error and exit + */ + function reportUnrecoverableDiagnostic(system, reportDiagnostic, diagnostic) { + reportDiagnostic(diagnostic); + system.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); + } + /** + * Creates the watch compiler host from system for config file in watch mode + */ + function createWatchCompilerHostOfConfigFile(configFileName, optionsToExtend, system, createProgram, reportDiagnostic, reportWatchStatus) { + var diagnosticReporter = reportDiagnostic || createDiagnosticReporter(system); + var host = createWatchCompilerHost(system, createProgram, diagnosticReporter, reportWatchStatus); + host.onUnRecoverableConfigFileDiagnostic = function (diagnostic) { return reportUnrecoverableDiagnostic(system, diagnosticReporter, diagnostic); }; + host.configFileName = configFileName; + host.optionsToExtend = optionsToExtend; + return host; + } + ts.createWatchCompilerHostOfConfigFile = createWatchCompilerHostOfConfigFile; + /** + * Creates the watch compiler host from system for compiling root files and options in watch mode + */ + function createWatchCompilerHostOfFilesAndCompilerOptions(rootFiles, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences) { + var host = createWatchCompilerHost(system, createProgram, reportDiagnostic || createDiagnosticReporter(system), reportWatchStatus); + host.rootFiles = rootFiles; + host.options = options; + host.projectReferences = projectReferences; + return host; + } + ts.createWatchCompilerHostOfFilesAndCompilerOptions = createWatchCompilerHostOfFilesAndCompilerOptions; +})(ts || (ts = {})); +(function (ts) { + function createWatchCompilerHost(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences) { + if (ts.isArray(rootFilesOrConfigFileName)) { + return ts.createWatchCompilerHostOfFilesAndCompilerOptions(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences); // TODO: GH#18217 + } + else { + return ts.createWatchCompilerHostOfConfigFile(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus); + } + } + ts.createWatchCompilerHost = createWatchCompilerHost; + var initialVersion = 1; + function createWatchProgram(host) { + var builderProgram; + var reloadLevel; // level to indicate if the program needs to be reloaded from config file/just filenames etc + var missingFilesMap; // Map of file watchers for the missing files + var watchedWildcardDirectories; // map of watchers for the wild card directories in the config file + var timerToUpdateProgram; // timer callback to recompile the program + var sourceFilesCache = ts.createMap(); // Cache that stores the source file and version info + var missingFilePathsRequestedForRelease; // These paths are held temparirly so that we can remove the entry from source file cache if the file is not tracked by missing files + var hasChangedCompilerOptions = false; // True if the compiler options have changed between compilations + var hasChangedAutomaticTypeDirectiveNames = false; // True if the automatic type directives have changed + var useCaseSensitiveFileNames = host.useCaseSensitiveFileNames(); + var currentDirectory = host.getCurrentDirectory(); + var getCurrentDirectory = function () { return currentDirectory; }; + var readFile = function (path, encoding) { return host.readFile(path, encoding); }; + var configFileName = host.configFileName, _a = host.optionsToExtend, optionsToExtendForConfigFile = _a === void 0 ? {} : _a, createProgram = host.createProgram; + var rootFileNames = host.rootFiles, compilerOptions = host.options, projectReferences = host.projectReferences; + var configFileSpecs; + var configFileParsingDiagnostics; + var canConfigFileJsonReportNoInputFiles = false; + var hasChangedConfigFileParsingErrors = false; + var cachedDirectoryStructureHost = configFileName === undefined ? undefined : ts.createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensitiveFileNames); + if (cachedDirectoryStructureHost && host.onCachedDirectoryStructureHostCreate) { + host.onCachedDirectoryStructureHostCreate(cachedDirectoryStructureHost); + } + var directoryStructureHost = cachedDirectoryStructureHost || host; + var parseConfigFileHost = { + useCaseSensitiveFileNames: useCaseSensitiveFileNames, + readDirectory: function (path, extensions, exclude, include, depth) { return directoryStructureHost.readDirectory(path, extensions, exclude, include, depth); }, + fileExists: function (path) { return host.fileExists(path); }, + readFile: readFile, + getCurrentDirectory: getCurrentDirectory, + onUnRecoverableConfigFileDiagnostic: host.onUnRecoverableConfigFileDiagnostic, + trace: host.trace ? function (s) { return host.trace(s); } : undefined + }; + // From tsc we want to get already parsed result and hence check for rootFileNames + var newLine = updateNewLine(); + if (configFileName && host.configFileParsingResult) { + setConfigFileParsingResult(host.configFileParsingResult); + newLine = updateNewLine(); + } + reportWatchDiagnostic(ts.Diagnostics.Starting_compilation_in_watch_mode); + if (configFileName && !host.configFileParsingResult) { + newLine = ts.getNewLineCharacter(optionsToExtendForConfigFile, function () { return host.getNewLine(); }); + ts.Debug.assert(!rootFileNames); + parseConfigFile(); + newLine = updateNewLine(); + } + var trace = host.trace && (function (s) { host.trace(s + newLine); }); + var watchLogLevel = trace ? compilerOptions.extendedDiagnostics ? ts.WatchLogLevel.Verbose : + compilerOptions.diagnostics ? ts.WatchLogLevel.TriggerOnly : ts.WatchLogLevel.None : ts.WatchLogLevel.None; + var writeLog = watchLogLevel !== ts.WatchLogLevel.None ? trace : ts.noop; // TODO: GH#18217 + var _b = ts.getWatchFactory(watchLogLevel, writeLog), watchFile = _b.watchFile, watchFilePath = _b.watchFilePath, watchDirectory = _b.watchDirectory; + var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); + writeLog("Current directory: " + currentDirectory + " CaseSensitiveFileNames: " + useCaseSensitiveFileNames); + if (configFileName) { + watchFile(host, configFileName, scheduleProgramReload, ts.PollingInterval.High, "Config file"); + } + var compilerHost = { + // Members for CompilerHost + getSourceFile: function (fileName, languageVersion, onError, shouldCreateNewSourceFile) { return getVersionedSourceFileByPath(fileName, toPath(fileName), languageVersion, onError, shouldCreateNewSourceFile); }, + getSourceFileByPath: getVersionedSourceFileByPath, + getDefaultLibLocation: host.getDefaultLibLocation && (function () { return host.getDefaultLibLocation(); }), + getDefaultLibFileName: function (options) { return host.getDefaultLibFileName(options); }, + writeFile: writeFile, + getCurrentDirectory: getCurrentDirectory, + useCaseSensitiveFileNames: function () { return useCaseSensitiveFileNames; }, + getCanonicalFileName: getCanonicalFileName, + getNewLine: function () { return newLine; }, + fileExists: fileExists, + readFile: readFile, + trace: trace, + directoryExists: directoryStructureHost.directoryExists && (function (path) { return directoryStructureHost.directoryExists(path); }), + getDirectories: (directoryStructureHost.getDirectories && (function (path) { return directoryStructureHost.getDirectories(path); })), + realpath: host.realpath && (function (s) { return host.realpath(s); }), + getEnvironmentVariable: host.getEnvironmentVariable ? (function (name) { return host.getEnvironmentVariable(name); }) : (function () { return ""; }), + onReleaseOldSourceFile: onReleaseOldSourceFile, + createHash: host.createHash && (function (data) { return host.createHash(data); }), + // Members for ResolutionCacheHost + toPath: toPath, + getCompilationSettings: function () { return compilerOptions; }, + watchDirectoryOfFailedLookupLocation: function (dir, cb, flags) { return watchDirectory(host, dir, cb, flags, "Failed Lookup Locations"); }, + watchTypeRootsDirectory: function (dir, cb, flags) { return watchDirectory(host, dir, cb, flags, "Type roots"); }, + getCachedDirectoryStructureHost: function () { return cachedDirectoryStructureHost; }, + onInvalidatedResolution: scheduleProgramUpdate, + onChangedAutomaticTypeDirectiveNames: function () { + hasChangedAutomaticTypeDirectiveNames = true; + scheduleProgramUpdate(); + }, + maxNumberOfFilesToIterateForInvalidation: host.maxNumberOfFilesToIterateForInvalidation, + getCurrentProgram: getCurrentProgram, + writeLog: writeLog, + readDirectory: function (path, extensions, exclude, include, depth) { return directoryStructureHost.readDirectory(path, extensions, exclude, include, depth); }, + }; + // Cache for the module resolution + var resolutionCache = ts.createResolutionCache(compilerHost, configFileName ? + ts.getDirectoryPath(ts.getNormalizedAbsolutePath(configFileName, currentDirectory)) : + currentDirectory, + /*logChangesWhenResolvingModule*/ false); + // Resolve module using host module resolution strategy if provided otherwise use resolution cache to resolve module names + compilerHost.resolveModuleNames = host.resolveModuleNames ? + (function (moduleNames, containingFile, reusedNames, redirectedReference) { return host.resolveModuleNames(moduleNames, containingFile, reusedNames, redirectedReference); }) : + (function (moduleNames, containingFile, reusedNames, redirectedReference) { return resolutionCache.resolveModuleNames(moduleNames, containingFile, reusedNames, redirectedReference); }); + compilerHost.resolveTypeReferenceDirectives = host.resolveTypeReferenceDirectives ? + (function (typeDirectiveNames, containingFile, redirectedReference) { return host.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile, redirectedReference); }) : + (function (typeDirectiveNames, containingFile, redirectedReference) { return resolutionCache.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile, redirectedReference); }); + var userProvidedResolution = !!host.resolveModuleNames || !!host.resolveTypeReferenceDirectives; + synchronizeProgram(); + // Update the wild card directory watch + watchConfigFileWildCardDirectories(); + return configFileName ? + { getCurrentProgram: getCurrentBuilderProgram, getProgram: synchronizeProgram } : + { getCurrentProgram: getCurrentBuilderProgram, getProgram: synchronizeProgram, updateRootFileNames: updateRootFileNames }; + function getCurrentBuilderProgram() { + return builderProgram; + } + function getCurrentProgram() { + return builderProgram && builderProgram.getProgram(); + } + function synchronizeProgram() { + writeLog("Synchronizing program"); + var program = getCurrentProgram(); + if (hasChangedCompilerOptions) { + newLine = updateNewLine(); + if (program && ts.changesAffectModuleResolution(program.getCompilerOptions(), compilerOptions)) { + resolutionCache.clear(); + } + } + // All resolutions are invalid if user provided resolutions + var hasInvalidatedResolution = resolutionCache.createHasInvalidatedResolution(userProvidedResolution); + if (ts.isProgramUptoDate(getCurrentProgram(), rootFileNames, compilerOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, projectReferences)) { + if (hasChangedConfigFileParsingErrors) { + builderProgram = createProgram(/*rootNames*/ undefined, /*options*/ undefined, compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences); + hasChangedConfigFileParsingErrors = false; + } + } + else { + createNewProgram(program, hasInvalidatedResolution); + } + if (host.afterProgramCreate) { + host.afterProgramCreate(builderProgram); + } + return builderProgram; + } + function createNewProgram(program, hasInvalidatedResolution) { + // Compile the program + if (watchLogLevel !== ts.WatchLogLevel.None) { + writeLog("CreatingProgramWith::"); + writeLog(" roots: " + JSON.stringify(rootFileNames)); + writeLog(" options: " + JSON.stringify(compilerOptions)); + } + var needsUpdateInTypeRootWatch = hasChangedCompilerOptions || !program; + hasChangedCompilerOptions = false; + hasChangedConfigFileParsingErrors = false; + resolutionCache.startCachingPerDirectoryResolution(); + compilerHost.hasInvalidatedResolution = hasInvalidatedResolution; + compilerHost.hasChangedAutomaticTypeDirectiveNames = hasChangedAutomaticTypeDirectiveNames; + builderProgram = createProgram(rootFileNames, compilerOptions, compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences); + resolutionCache.finishCachingPerDirectoryResolution(); + // Update watches + ts.updateMissingFilePathsWatch(builderProgram.getProgram(), missingFilesMap || (missingFilesMap = ts.createMap()), watchMissingFilePath); + if (needsUpdateInTypeRootWatch) { + resolutionCache.updateTypeRootsWatch(); + } + if (missingFilePathsRequestedForRelease) { + // These are the paths that program creater told us as not in use any more but were missing on the disk. + // We didnt remove the entry for them from sourceFiles cache so that we dont have to do File IO, + // if there is already watcher for it (for missing files) + // At this point our watches were updated, hence now we know that these paths are not tracked and need to be removed + // so that at later time we have correct result of their presence + for (var _i = 0, missingFilePathsRequestedForRelease_1 = missingFilePathsRequestedForRelease; _i < missingFilePathsRequestedForRelease_1.length; _i++) { + var missingFilePath = missingFilePathsRequestedForRelease_1[_i]; + if (!missingFilesMap.has(missingFilePath)) { + sourceFilesCache.delete(missingFilePath); + } + } + missingFilePathsRequestedForRelease = undefined; + } + } + function updateRootFileNames(files) { + ts.Debug.assert(!configFileName, "Cannot update root file names with config file watch mode"); + rootFileNames = files; + scheduleProgramUpdate(); + } + function updateNewLine() { + return ts.getNewLineCharacter(compilerOptions || optionsToExtendForConfigFile, function () { return host.getNewLine(); }); + } + function toPath(fileName) { + return ts.toPath(fileName, currentDirectory, getCanonicalFileName); + } + function isFileMissingOnHost(hostSourceFile) { + return typeof hostSourceFile === "number"; + } + function isFilePresentOnHost(hostSourceFile) { + return !!hostSourceFile.sourceFile; + } + function fileExists(fileName) { + var path = toPath(fileName); + // If file is missing on host from cache, we can definitely say file doesnt exist + // otherwise we need to ensure from the disk + if (isFileMissingOnHost(sourceFilesCache.get(path))) { + return true; + } + return directoryStructureHost.fileExists(fileName); + } + function getVersionedSourceFileByPath(fileName, path, languageVersion, onError, shouldCreateNewSourceFile) { + var hostSourceFile = sourceFilesCache.get(path); + // No source file on the host + if (isFileMissingOnHost(hostSourceFile)) { + return undefined; + } + // Create new source file if requested or the versions dont match + if (!hostSourceFile || shouldCreateNewSourceFile || !isFilePresentOnHost(hostSourceFile) || hostSourceFile.version.toString() !== hostSourceFile.sourceFile.version) { + var sourceFile = getNewSourceFile(); + if (hostSourceFile) { + if (shouldCreateNewSourceFile) { + hostSourceFile.version++; + } + if (sourceFile) { + // Set the source file and create file watcher now that file was present on the disk + hostSourceFile.sourceFile = sourceFile; + sourceFile.version = hostSourceFile.version.toString(); + if (!hostSourceFile.fileWatcher) { + hostSourceFile.fileWatcher = watchFilePath(host, fileName, onSourceFileChange, ts.PollingInterval.Low, path, "Source file"); + } + } + else { + // There is no source file on host any more, close the watch, missing file paths will track it + if (isFilePresentOnHost(hostSourceFile)) { + hostSourceFile.fileWatcher.close(); + } + sourceFilesCache.set(path, hostSourceFile.version); + } + } + else { + if (sourceFile) { + sourceFile.version = initialVersion.toString(); + var fileWatcher = watchFilePath(host, fileName, onSourceFileChange, ts.PollingInterval.Low, path, "Source file"); + sourceFilesCache.set(path, { sourceFile: sourceFile, version: initialVersion, fileWatcher: fileWatcher }); + } + else { + sourceFilesCache.set(path, initialVersion); + } + } + return sourceFile; + } + return hostSourceFile.sourceFile; + function getNewSourceFile() { + var text; + try { + ts.performance.mark("beforeIORead"); + text = host.readFile(fileName, compilerOptions.charset); + ts.performance.mark("afterIORead"); + ts.performance.measure("I/O Read", "beforeIORead", "afterIORead"); + } + catch (e) { + if (onError) { + onError(e.message); + } + } + return text !== undefined ? ts.createSourceFile(fileName, text, languageVersion) : undefined; + } + } + function nextSourceFileVersion(path) { + var hostSourceFile = sourceFilesCache.get(path); + if (hostSourceFile !== undefined) { + if (isFileMissingOnHost(hostSourceFile)) { + // The next version, lets set it as presence unknown file + sourceFilesCache.set(path, { version: Number(hostSourceFile) + 1 }); + } + else { + hostSourceFile.version++; + } + } + } + function getSourceVersion(path) { + var hostSourceFile = sourceFilesCache.get(path); + return !hostSourceFile || isFileMissingOnHost(hostSourceFile) ? undefined : hostSourceFile.version.toString(); + } + function onReleaseOldSourceFile(oldSourceFile, _oldOptions, hasSourceFileByPath) { + var hostSourceFileInfo = sourceFilesCache.get(oldSourceFile.resolvedPath); + // If this is the source file thats in the cache and new program doesnt need it, + // remove the cached entry. + // Note we arent deleting entry if file became missing in new program or + // there was version update and new source file was created. + if (hostSourceFileInfo) { + // record the missing file paths so they can be removed later if watchers arent tracking them + if (isFileMissingOnHost(hostSourceFileInfo)) { + (missingFilePathsRequestedForRelease || (missingFilePathsRequestedForRelease = [])).push(oldSourceFile.path); + } + else if (hostSourceFileInfo.sourceFile === oldSourceFile) { + if (hostSourceFileInfo.fileWatcher) { + hostSourceFileInfo.fileWatcher.close(); + } + sourceFilesCache.delete(oldSourceFile.resolvedPath); + if (!hasSourceFileByPath) { + resolutionCache.removeResolutionsOfFile(oldSourceFile.path); + } + } + } + } + function reportWatchDiagnostic(message) { + if (host.onWatchStatusChange) { + host.onWatchStatusChange(ts.createCompilerDiagnostic(message), newLine, compilerOptions || optionsToExtendForConfigFile); + } + } + // Upon detecting a file change, wait for 250ms and then perform a recompilation. This gives batch + // operations (such as saving all modified files in an editor) a chance to complete before we kick + // off a new compilation. + function scheduleProgramUpdate() { + if (!host.setTimeout || !host.clearTimeout) { + return; + } + if (timerToUpdateProgram) { + host.clearTimeout(timerToUpdateProgram); + } + writeLog("Scheduling update"); + timerToUpdateProgram = host.setTimeout(updateProgram, 250); + } + function scheduleProgramReload() { + ts.Debug.assert(!!configFileName); + reloadLevel = ts.ConfigFileProgramReloadLevel.Full; + scheduleProgramUpdate(); + } + function updateProgram() { + timerToUpdateProgram = undefined; + reportWatchDiagnostic(ts.Diagnostics.File_change_detected_Starting_incremental_compilation); + switch (reloadLevel) { + case ts.ConfigFileProgramReloadLevel.Partial: + return reloadFileNamesFromConfigFile(); + case ts.ConfigFileProgramReloadLevel.Full: + return reloadConfigFile(); + default: + synchronizeProgram(); + return; + } + } + function reloadFileNamesFromConfigFile() { + writeLog("Reloading new file names and options"); + var result = ts.getFileNamesFromConfigSpecs(configFileSpecs, ts.getDirectoryPath(configFileName), compilerOptions, parseConfigFileHost); + if (ts.updateErrorForNoInputFiles(result, configFileName, configFileSpecs, configFileParsingDiagnostics, canConfigFileJsonReportNoInputFiles)) { + hasChangedConfigFileParsingErrors = true; + } + rootFileNames = result.fileNames; + // Update the program + synchronizeProgram(); + } + function reloadConfigFile() { + writeLog("Reloading config file: " + configFileName); + reloadLevel = ts.ConfigFileProgramReloadLevel.None; + if (cachedDirectoryStructureHost) { + cachedDirectoryStructureHost.clearCache(); + } + parseConfigFile(); + hasChangedCompilerOptions = true; + synchronizeProgram(); + // Update the wild card directory watch + watchConfigFileWildCardDirectories(); + } + function parseConfigFile() { + setConfigFileParsingResult(ts.getParsedCommandLineOfConfigFile(configFileName, optionsToExtendForConfigFile, parseConfigFileHost)); // TODO: GH#18217 + } + function setConfigFileParsingResult(configFileParseResult) { + rootFileNames = configFileParseResult.fileNames; + compilerOptions = configFileParseResult.options; + configFileSpecs = configFileParseResult.configFileSpecs; // TODO: GH#18217 + projectReferences = configFileParseResult.projectReferences; + configFileParsingDiagnostics = ts.getConfigFileParsingDiagnostics(configFileParseResult).slice(); + canConfigFileJsonReportNoInputFiles = ts.canJsonReportNoInutFiles(configFileParseResult.raw); + hasChangedConfigFileParsingErrors = true; + } + function onSourceFileChange(fileName, eventKind, path) { + updateCachedSystemWithFile(fileName, path, eventKind); + // Update the source file cache + if (eventKind === ts.FileWatcherEventKind.Deleted && sourceFilesCache.get(path)) { + resolutionCache.invalidateResolutionOfFile(path); + } + resolutionCache.removeResolutionsFromProjectReferenceRedirects(path); + nextSourceFileVersion(path); + // Update the program + scheduleProgramUpdate(); + } + function updateCachedSystemWithFile(fileName, path, eventKind) { + if (cachedDirectoryStructureHost) { + cachedDirectoryStructureHost.addOrDeleteFile(fileName, path, eventKind); + } + } + function watchMissingFilePath(missingFilePath) { + return watchFilePath(host, missingFilePath, onMissingFileChange, ts.PollingInterval.Medium, missingFilePath, "Missing file"); + } + function onMissingFileChange(fileName, eventKind, missingFilePath) { + updateCachedSystemWithFile(fileName, missingFilePath, eventKind); + if (eventKind === ts.FileWatcherEventKind.Created && missingFilesMap.has(missingFilePath)) { + missingFilesMap.get(missingFilePath).close(); + missingFilesMap.delete(missingFilePath); + // Delete the entry in the source files cache so that new source file is created + nextSourceFileVersion(missingFilePath); + // When a missing file is created, we should update the graph. + scheduleProgramUpdate(); + } + } + function watchConfigFileWildCardDirectories() { + if (configFileSpecs) { + ts.updateWatchingWildcardDirectories(watchedWildcardDirectories || (watchedWildcardDirectories = ts.createMap()), ts.createMapFromTemplate(configFileSpecs.wildcardDirectories), watchWildcardDirectory); + } + else if (watchedWildcardDirectories) { + ts.clearMap(watchedWildcardDirectories, ts.closeFileWatcherOf); + } + } + function watchWildcardDirectory(directory, flags) { + return watchDirectory(host, directory, function (fileOrDirectory) { + ts.Debug.assert(!!configFileName); + var fileOrDirectoryPath = toPath(fileOrDirectory); + // Since the file existance changed, update the sourceFiles cache + if (cachedDirectoryStructureHost) { + cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); + } + nextSourceFileVersion(fileOrDirectoryPath); + if (ts.isPathInNodeModulesStartingWithDot(fileOrDirectoryPath)) + return; + // If the the added or created file or directory is not supported file name, ignore the file + // But when watched directory is added/removed, we need to reload the file list + if (fileOrDirectoryPath !== directory && ts.hasExtension(fileOrDirectoryPath) && !ts.isSupportedSourceFileName(fileOrDirectory, compilerOptions)) { + writeLog("Project: " + configFileName + " Detected file add/remove of non supported extension: " + fileOrDirectory); + return; + } + // Reload is pending, do the reload + if (reloadLevel !== ts.ConfigFileProgramReloadLevel.Full) { + reloadLevel = ts.ConfigFileProgramReloadLevel.Partial; + // Schedule Update the program + scheduleProgramUpdate(); + } + }, flags, "Wild card directories"); + } + function ensureDirectoriesExist(directoryPath) { + if (directoryPath.length > ts.getRootLength(directoryPath) && !host.directoryExists(directoryPath)) { + var parentDirectory = ts.getDirectoryPath(directoryPath); + ensureDirectoriesExist(parentDirectory); + host.createDirectory(directoryPath); + } + } + function writeFile(fileName, text, writeByteOrderMark, onError) { + try { + ts.performance.mark("beforeIOWrite"); + ensureDirectoriesExist(ts.getDirectoryPath(ts.normalizePath(fileName))); + host.writeFile(fileName, text, writeByteOrderMark); + ts.performance.mark("afterIOWrite"); + ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite"); + } + catch (e) { + if (onError) { + onError(e.message); + } + } + } + } + ts.createWatchProgram = createWatchProgram; +})(ts || (ts = {})); +// Currently we do not want to expose API for build, we should work out the API, and then expose it just like we did for builder/watch +/*@internal*/ +var ts; +(function (ts) { + var minimumDate = new Date(-8640000000000000); + var maximumDate = new Date(8640000000000000); + var BuildResultFlags; + (function (BuildResultFlags) { + BuildResultFlags[BuildResultFlags["None"] = 0] = "None"; + /** + * No errors of any kind occurred during build + */ + BuildResultFlags[BuildResultFlags["Success"] = 1] = "Success"; + /** + * None of the .d.ts files emitted by this build were + * different from the existing files on disk + */ + BuildResultFlags[BuildResultFlags["DeclarationOutputUnchanged"] = 2] = "DeclarationOutputUnchanged"; + BuildResultFlags[BuildResultFlags["ConfigFileErrors"] = 4] = "ConfigFileErrors"; + BuildResultFlags[BuildResultFlags["SyntaxErrors"] = 8] = "SyntaxErrors"; + BuildResultFlags[BuildResultFlags["TypeErrors"] = 16] = "TypeErrors"; + BuildResultFlags[BuildResultFlags["DeclarationEmitErrors"] = 32] = "DeclarationEmitErrors"; + BuildResultFlags[BuildResultFlags["EmitErrors"] = 64] = "EmitErrors"; + BuildResultFlags[BuildResultFlags["AnyErrors"] = 124] = "AnyErrors"; + })(BuildResultFlags || (BuildResultFlags = {})); + var UpToDateStatusType; + (function (UpToDateStatusType) { + UpToDateStatusType[UpToDateStatusType["Unbuildable"] = 0] = "Unbuildable"; + UpToDateStatusType[UpToDateStatusType["UpToDate"] = 1] = "UpToDate"; + /** + * The project appears out of date because its upstream inputs are newer than its outputs, + * but all of its outputs are actually newer than the previous identical outputs of its (.d.ts) inputs. + * This means we can Pseudo-build (just touch timestamps), as if we had actually built this project. + */ + UpToDateStatusType[UpToDateStatusType["UpToDateWithUpstreamTypes"] = 2] = "UpToDateWithUpstreamTypes"; + UpToDateStatusType[UpToDateStatusType["OutputMissing"] = 3] = "OutputMissing"; + UpToDateStatusType[UpToDateStatusType["OutOfDateWithSelf"] = 4] = "OutOfDateWithSelf"; + UpToDateStatusType[UpToDateStatusType["OutOfDateWithUpstream"] = 5] = "OutOfDateWithUpstream"; + UpToDateStatusType[UpToDateStatusType["UpstreamOutOfDate"] = 6] = "UpstreamOutOfDate"; + UpToDateStatusType[UpToDateStatusType["UpstreamBlocked"] = 7] = "UpstreamBlocked"; + UpToDateStatusType[UpToDateStatusType["ComputingUpstream"] = 8] = "ComputingUpstream"; + /** + * Projects with no outputs (i.e. "solution" files) + */ + UpToDateStatusType[UpToDateStatusType["ContainerOnly"] = 9] = "ContainerOnly"; + })(UpToDateStatusType = ts.UpToDateStatusType || (ts.UpToDateStatusType = {})); + function createFileMap(toPath) { + // tslint:disable-next-line:no-null-keyword + var lookup = ts.createMap(); + return { + setValue: setValue, + getValue: getValue, + removeKey: removeKey, + forEach: forEach, + hasKey: hasKey, + getSize: getSize, + clear: clear + }; + function forEach(action) { + lookup.forEach(action); + } + function hasKey(fileName) { + return lookup.has(toPath(fileName)); + } + function removeKey(fileName) { + lookup.delete(toPath(fileName)); + } + function setValue(fileName, value) { + lookup.set(toPath(fileName), value); + } + function getValue(fileName) { + return lookup.get(toPath(fileName)); + } + function getSize() { + return lookup.size; + } + function clear() { + lookup.clear(); + } + } + function getOrCreateValueFromConfigFileMap(configFileMap, resolved, createT) { + var existingValue = configFileMap.getValue(resolved); + var newValue; + if (!existingValue) { + newValue = createT(); + configFileMap.setValue(resolved, newValue); + } + return existingValue || newValue; + } + function getOrCreateValueMapFromConfigFileMap(configFileMap, resolved) { + return getOrCreateValueFromConfigFileMap(configFileMap, resolved, ts.createMap); + } + function getOutputDeclarationFileName(inputFileName, configFile) { + var relativePath = ts.getRelativePathFromDirectory(rootDirOfOptions(configFile.options, configFile.options.configFilePath), inputFileName, /*ignoreCase*/ true); + var outputPath = ts.resolvePath(configFile.options.declarationDir || configFile.options.outDir || ts.getDirectoryPath(configFile.options.configFilePath), relativePath); + return ts.changeExtension(outputPath, ".d.ts" /* Dts */); + } + ts.getOutputDeclarationFileName = getOutputDeclarationFileName; + function getOutputJSFileName(inputFileName, configFile) { + var relativePath = ts.getRelativePathFromDirectory(rootDirOfOptions(configFile.options, configFile.options.configFilePath), inputFileName, /*ignoreCase*/ true); + var outputPath = ts.resolvePath(configFile.options.outDir || ts.getDirectoryPath(configFile.options.configFilePath), relativePath); + var newExtension = ts.fileExtensionIs(inputFileName, ".json" /* Json */) ? ".json" /* Json */ : + ts.fileExtensionIs(inputFileName, ".tsx" /* Tsx */) && configFile.options.jsx === 1 /* Preserve */ ? ".jsx" /* Jsx */ : ".js" /* Js */; + return ts.changeExtension(outputPath, newExtension); + } + function getOutputFileNames(inputFileName, configFile) { + // outFile is handled elsewhere; .d.ts files don't generate outputs + if (configFile.options.outFile || configFile.options.out || ts.fileExtensionIs(inputFileName, ".d.ts" /* Dts */)) { + return ts.emptyArray; + } + var outputs = []; + var js = getOutputJSFileName(inputFileName, configFile); + outputs.push(js); + if (configFile.options.sourceMap) { + outputs.push(js + ".map"); + } + if (ts.getEmitDeclarations(configFile.options) && !ts.fileExtensionIs(inputFileName, ".json" /* Json */)) { + var dts = getOutputDeclarationFileName(inputFileName, configFile); + outputs.push(dts); + if (configFile.options.declarationMap) { + outputs.push(dts + ".map"); + } + } + return outputs; + } + function getOutFileOutputs(project) { + var out = project.options.outFile || project.options.out; + if (!out) { + return ts.Debug.fail("outFile must be set"); + } + var outputs = []; + outputs.push(out); + if (project.options.sourceMap) { + outputs.push(out + ".map"); + } + if (ts.getEmitDeclarations(project.options)) { + var dts = ts.changeExtension(out, ".d.ts" /* Dts */); + outputs.push(dts); + if (project.options.declarationMap) { + outputs.push(dts + ".map"); + } + } + return outputs; + } + function rootDirOfOptions(opts, configFileName) { + return opts.rootDir || ts.getDirectoryPath(configFileName); + } + function newer(date1, date2) { + return date2 > date1 ? date2 : date1; + } + function isDeclarationFile(fileName) { + return ts.fileExtensionIs(fileName, ".d.ts" /* Dts */); + } + /** + * Create a function that reports watch status by writing to the system and handles the formating of the diagnostic + */ + function createBuilderStatusReporter(system, pretty) { + return function (diagnostic) { + var output = pretty ? "[" + ts.formatColorAndReset(new Date().toLocaleTimeString(), ts.ForegroundColorEscapeSequences.Grey) + "] " : new Date().toLocaleTimeString() + " - "; + output += "" + ts.flattenDiagnosticMessageText(diagnostic.messageText, system.newLine) + (system.newLine + system.newLine); + system.write(output); + }; + } + ts.createBuilderStatusReporter = createBuilderStatusReporter; + function createSolutionBuilderHostBase(system, reportDiagnostic, reportSolutionBuilderStatus) { + if (system === void 0) { system = ts.sys; } + var host = ts.createCompilerHostWorker({}, /*setParentNodes*/ undefined, system); + host.getModifiedTime = system.getModifiedTime ? function (path) { return system.getModifiedTime(path); } : function () { return undefined; }; + host.setModifiedTime = system.setModifiedTime ? function (path, date) { return system.setModifiedTime(path, date); } : ts.noop; + host.deleteFile = system.deleteFile ? function (path) { return system.deleteFile(path); } : ts.noop; + host.reportDiagnostic = reportDiagnostic || ts.createDiagnosticReporter(system); + host.reportSolutionBuilderStatus = reportSolutionBuilderStatus || createBuilderStatusReporter(system); + return host; + } + function createSolutionBuilderHost(system, reportDiagnostic, reportSolutionBuilderStatus, reportErrorSummary) { + if (system === void 0) { system = ts.sys; } + var host = createSolutionBuilderHostBase(system, reportDiagnostic, reportSolutionBuilderStatus); + host.reportErrorSummary = reportErrorSummary; + return host; + } + ts.createSolutionBuilderHost = createSolutionBuilderHost; + function createSolutionBuilderWithWatchHost(system, reportDiagnostic, reportSolutionBuilderStatus, reportWatchStatus) { + var host = createSolutionBuilderHostBase(system, reportDiagnostic, reportSolutionBuilderStatus); + var watchHost = ts.createWatchHost(system, reportWatchStatus); + host.onWatchStatusChange = watchHost.onWatchStatusChange; + host.watchFile = watchHost.watchFile; + host.watchDirectory = watchHost.watchDirectory; + host.setTimeout = watchHost.setTimeout; + host.clearTimeout = watchHost.clearTimeout; + return host; + } + ts.createSolutionBuilderWithWatchHost = createSolutionBuilderWithWatchHost; + function getCompilerOptionsOfBuildOptions(buildOptions) { + var result = {}; + ts.commonOptionsWithBuild.forEach(function (option) { + result[option.name] = buildOptions[option.name]; + }); + return result; + } + function createSolutionBuilder(host, rootNames, defaultOptions) { + var hostWithWatch = host; + var currentDirectory = host.getCurrentDirectory(); + var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames()); + var parseConfigFileHost = ts.parseConfigHostFromCompilerHost(host); + // State of the solution + var options = defaultOptions; + var baseCompilerOptions = getCompilerOptionsOfBuildOptions(options); + var configFileCache = createFileMap(toPath); + /** Map from output file name to its pre-build timestamp */ + var unchangedOutputs = createFileMap(toPath); + /** Map from config file name to up-to-date status */ + var projectStatus = createFileMap(toPath); + var missingRoots = ts.createMap(); + var globalDependencyGraph; + var writeFileName = function (s) { return host.trace && host.trace(s); }; + var readFileWithCache = function (f) { return host.readFile(f); }; + // Watch state + var diagnostics = createFileMap(toPath); + var projectPendingBuild = createFileMap(toPath); + var projectErrorsReported = createFileMap(toPath); + var invalidatedProjectQueue = []; + var nextProjectToBuild = 0; + var timerToBuildInvalidatedProject; + var reportFileChangeDetected = false; + // Watches for the solution + var allWatchedWildcardDirectories = createFileMap(toPath); + var allWatchedInputFiles = createFileMap(toPath); + var allWatchedConfigFiles = createFileMap(toPath); + return { + buildAllProjects: buildAllProjects, + getUpToDateStatusOfFile: getUpToDateStatusOfFile, + cleanAllProjects: cleanAllProjects, + resetBuildContext: resetBuildContext, + getBuildGraph: getBuildGraph, + invalidateProject: invalidateProject, + buildInvalidatedProject: buildInvalidatedProject, + resolveProjectName: resolveProjectName, + startWatching: startWatching + }; + function toPath(fileName) { + return ts.toPath(fileName, currentDirectory, getCanonicalFileName); + } + function resetBuildContext(opts) { + if (opts === void 0) { opts = defaultOptions; } + options = opts; + baseCompilerOptions = getCompilerOptionsOfBuildOptions(options); + configFileCache.clear(); + unchangedOutputs.clear(); + projectStatus.clear(); + missingRoots.clear(); + globalDependencyGraph = undefined; + diagnostics.clear(); + projectPendingBuild.clear(); + projectErrorsReported.clear(); + invalidatedProjectQueue.length = 0; + nextProjectToBuild = 0; + if (timerToBuildInvalidatedProject) { + clearTimeout(timerToBuildInvalidatedProject); + timerToBuildInvalidatedProject = undefined; + } + reportFileChangeDetected = false; + ts.clearMap(allWatchedWildcardDirectories, function (wildCardWatches) { return ts.clearMap(wildCardWatches, ts.closeFileWatcherOf); }); + ts.clearMap(allWatchedInputFiles, function (inputFileWatches) { return ts.clearMap(inputFileWatches, ts.closeFileWatcher); }); + ts.clearMap(allWatchedConfigFiles, ts.closeFileWatcher); + } + function isParsedCommandLine(entry) { + return !!entry.options; + } + function parseConfigFile(configFilePath) { + var value = configFileCache.getValue(configFilePath); + if (value) { + return isParsedCommandLine(value) ? value : undefined; + } + var diagnostic; + parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = function (d) { return diagnostic = d; }; + var parsed = ts.getParsedCommandLineOfConfigFile(configFilePath, baseCompilerOptions, parseConfigFileHost); + parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = ts.noop; + configFileCache.setValue(configFilePath, parsed || diagnostic); + return parsed; + } + function reportStatus(message) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + host.reportSolutionBuilderStatus(ts.createCompilerDiagnostic.apply(void 0, [message].concat(args))); + } + function reportWatchStatus(message) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + if (hostWithWatch.onWatchStatusChange) { + hostWithWatch.onWatchStatusChange(ts.createCompilerDiagnostic.apply(void 0, [message].concat(args)), host.getNewLine(), baseCompilerOptions); + } + } + function startWatching() { + var graph = getGlobalDependencyGraph(); + for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { + var resolved = _a[_i]; + // Watch this file + watchConfigFile(resolved); + var cfg = parseConfigFile(resolved); + if (cfg) { + // Update watchers for wildcard directories + watchWildCardDirectories(resolved, cfg); + // Watch input files + watchInputFiles(resolved, cfg); + } + } + } + function watchConfigFile(resolved) { + if (options.watch && !allWatchedConfigFiles.hasKey(resolved)) { + allWatchedConfigFiles.setValue(resolved, hostWithWatch.watchFile(resolved, function () { + invalidateProjectAndScheduleBuilds(resolved, ts.ConfigFileProgramReloadLevel.Full); + })); + } + } + function watchWildCardDirectories(resolved, parsed) { + if (!options.watch) + return; + ts.updateWatchingWildcardDirectories(getOrCreateValueMapFromConfigFileMap(allWatchedWildcardDirectories, resolved), ts.createMapFromTemplate(parsed.configFileSpecs.wildcardDirectories), function (dir, flags) { + return hostWithWatch.watchDirectory(dir, function (fileOrDirectory) { + var fileOrDirectoryPath = toPath(fileOrDirectory); + if (fileOrDirectoryPath !== toPath(dir) && ts.hasExtension(fileOrDirectoryPath) && !ts.isSupportedSourceFileName(fileOrDirectory, parsed.options)) { + // writeLog(`Project: ${configFileName} Detected file add/remove of non supported extension: ${fileOrDirectory}`); + return; + } + if (isOutputFile(fileOrDirectory, parsed)) { + // writeLog(`${fileOrDirectory} is output file`); + return; + } + invalidateProjectAndScheduleBuilds(resolved, ts.ConfigFileProgramReloadLevel.Partial); + }, !!(flags & 1 /* Recursive */)); + }); + } + function watchInputFiles(resolved, parsed) { + if (!options.watch) + return; + ts.mutateMap(getOrCreateValueMapFromConfigFileMap(allWatchedInputFiles, resolved), ts.arrayToMap(parsed.fileNames, toPath), { + createNewValue: function (_key, input) { return hostWithWatch.watchFile(input, function () { + invalidateProjectAndScheduleBuilds(resolved, ts.ConfigFileProgramReloadLevel.None); + }); }, + onDeleteValue: ts.closeFileWatcher, + }); + } + function isOutputFile(fileName, configFile) { + if (configFile.options.noEmit) + return false; + // ts or tsx files are not output + if (!ts.fileExtensionIs(fileName, ".d.ts" /* Dts */) && + (ts.fileExtensionIs(fileName, ".ts" /* Ts */) || ts.fileExtensionIs(fileName, ".tsx" /* Tsx */))) { + return false; + } + // If options have --outFile or --out, check if its that + var out = configFile.options.outFile || configFile.options.out; + if (out && (isSameFile(fileName, out) || isSameFile(fileName, ts.removeFileExtension(out) + ".d.ts" /* Dts */))) { + return true; + } + // If declarationDir is specified, return if its a file in that directory + if (configFile.options.declarationDir && ts.containsPath(configFile.options.declarationDir, fileName, currentDirectory, !host.useCaseSensitiveFileNames())) { + return true; + } + // If --outDir, check if file is in that directory + if (configFile.options.outDir && ts.containsPath(configFile.options.outDir, fileName, currentDirectory, !host.useCaseSensitiveFileNames())) { + return true; + } + return !ts.forEach(configFile.fileNames, function (inputFile) { return isSameFile(fileName, inputFile); }); + } + function isSameFile(file1, file2) { + return ts.comparePaths(file1, file2, currentDirectory, !host.useCaseSensitiveFileNames()) === 0 /* EqualTo */; + } + function invalidateProjectAndScheduleBuilds(resolved, reloadLevel) { + reportFileChangeDetected = true; + invalidateResolvedProject(resolved, reloadLevel); + scheduleBuildInvalidatedProject(); + } + function getUpToDateStatusOfFile(configFileName) { + return getUpToDateStatus(parseConfigFile(configFileName)); + } + function getBuildGraph(configFileNames) { + return createDependencyGraph(resolveProjectNames(configFileNames)); + } + function getGlobalDependencyGraph() { + return globalDependencyGraph || (globalDependencyGraph = getBuildGraph(rootNames)); + } + function getUpToDateStatus(project) { + if (project === undefined) { + return { type: UpToDateStatusType.Unbuildable, reason: "File deleted mid-build" }; + } + var prior = projectStatus.getValue(project.options.configFilePath); + if (prior !== undefined) { + return prior; + } + var actual = getUpToDateStatusWorker(project); + projectStatus.setValue(project.options.configFilePath, actual); + return actual; + } + function getUpToDateStatusWorker(project) { + var newestInputFileName = undefined; + var newestInputFileTime = minimumDate; + // Get timestamps of input files + for (var _i = 0, _a = project.fileNames; _i < _a.length; _i++) { + var inputFile = _a[_i]; + if (!host.fileExists(inputFile)) { + return { + type: UpToDateStatusType.Unbuildable, + reason: inputFile + " does not exist" + }; + } + var inputTime = host.getModifiedTime(inputFile) || ts.missingFileModifiedTime; + if (inputTime > newestInputFileTime) { + newestInputFileName = inputFile; + newestInputFileTime = inputTime; + } + } + // Collect the expected outputs of this project + var outputs = getAllProjectOutputs(project); + if (outputs.length === 0) { + return { + type: UpToDateStatusType.ContainerOnly + }; + } + // Now see if all outputs are newer than the newest input + var oldestOutputFileName = "(none)"; + var oldestOutputFileTime = maximumDate; + var newestOutputFileName = "(none)"; + var newestOutputFileTime = minimumDate; + var missingOutputFileName; + var newestDeclarationFileContentChangedTime = minimumDate; + var isOutOfDateWithInputs = false; + for (var _b = 0, outputs_1 = outputs; _b < outputs_1.length; _b++) { + var output = outputs_1[_b]; + // Output is missing; can stop checking + // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status + if (!host.fileExists(output)) { + missingOutputFileName = output; + break; + } + var outputTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; + if (outputTime < oldestOutputFileTime) { + oldestOutputFileTime = outputTime; + oldestOutputFileName = output; + } + // If an output is older than the newest input, we can stop checking + // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status + if (outputTime < newestInputFileTime) { + isOutOfDateWithInputs = true; + break; + } + if (outputTime > newestOutputFileTime) { + newestOutputFileTime = outputTime; + newestOutputFileName = output; + } + // Keep track of when the most recent time a .d.ts file was changed. + // In addition to file timestamps, we also keep track of when a .d.ts file + // had its file touched but not had its contents changed - this allows us + // to skip a downstream typecheck + if (isDeclarationFile(output)) { + var unchangedTime = unchangedOutputs.getValue(output); + if (unchangedTime !== undefined) { + newestDeclarationFileContentChangedTime = newer(unchangedTime, newestDeclarationFileContentChangedTime); + } + else { + var outputModifiedTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; + newestDeclarationFileContentChangedTime = newer(newestDeclarationFileContentChangedTime, outputModifiedTime); + } + } + } + var pseudoUpToDate = false; + var usesPrepend = false; + var upstreamChangedProject; + if (project.projectReferences) { + projectStatus.setValue(project.options.configFilePath, { type: UpToDateStatusType.ComputingUpstream }); + for (var _c = 0, _d = project.projectReferences; _c < _d.length; _c++) { + var ref = _d[_c]; + usesPrepend = usesPrepend || !!(ref.prepend); + var resolvedRef = ts.resolveProjectReferencePath(ref); + var refStatus = getUpToDateStatus(parseConfigFile(resolvedRef)); + // Its a circular reference ignore the status of this project + if (refStatus.type === UpToDateStatusType.ComputingUpstream) { + continue; + } + // An upstream project is blocked + if (refStatus.type === UpToDateStatusType.Unbuildable) { + return { + type: UpToDateStatusType.UpstreamBlocked, + upstreamProjectName: ref.path + }; + } + // If the upstream project is out of date, then so are we (someone shouldn't have asked, though?) + if (refStatus.type !== UpToDateStatusType.UpToDate) { + return { + type: UpToDateStatusType.UpstreamOutOfDate, + upstreamProjectName: ref.path + }; + } + // If the upstream project's newest file is older than our oldest output, we + // can't be out of date because of it + if (refStatus.newestInputFileTime && refStatus.newestInputFileTime <= oldestOutputFileTime) { + continue; + } + // If the upstream project has only change .d.ts files, and we've built + // *after* those files, then we're "psuedo up to date" and eligible for a fast rebuild + if (refStatus.newestDeclarationFileContentChangedTime && refStatus.newestDeclarationFileContentChangedTime <= oldestOutputFileTime) { + pseudoUpToDate = true; + upstreamChangedProject = ref.path; + continue; + } + // We have an output older than an upstream output - we are out of date + ts.Debug.assert(oldestOutputFileName !== undefined, "Should have an oldest output filename here"); + return { + type: UpToDateStatusType.OutOfDateWithUpstream, + outOfDateOutputFileName: oldestOutputFileName, + newerProjectName: ref.path + }; + } + } + if (missingOutputFileName !== undefined) { + return { + type: UpToDateStatusType.OutputMissing, + missingOutputFileName: missingOutputFileName + }; + } + if (isOutOfDateWithInputs) { + return { + type: UpToDateStatusType.OutOfDateWithSelf, + outOfDateOutputFileName: oldestOutputFileName, + newerInputFileName: newestInputFileName + }; + } + if (usesPrepend && pseudoUpToDate) { + return { + type: UpToDateStatusType.OutOfDateWithUpstream, + outOfDateOutputFileName: oldestOutputFileName, + newerProjectName: upstreamChangedProject + }; + } + // Up to date + return { + type: pseudoUpToDate ? UpToDateStatusType.UpToDateWithUpstreamTypes : UpToDateStatusType.UpToDate, + newestDeclarationFileContentChangedTime: newestDeclarationFileContentChangedTime, + newestInputFileTime: newestInputFileTime, + newestOutputFileTime: newestOutputFileTime, + newestInputFileName: newestInputFileName, + newestOutputFileName: newestOutputFileName, + oldestOutputFileName: oldestOutputFileName + }; + } + function invalidateProject(configFileName, reloadLevel) { + invalidateResolvedProject(resolveProjectName(configFileName), reloadLevel); + } + function invalidateResolvedProject(resolved, reloadLevel) { + if (reloadLevel === ts.ConfigFileProgramReloadLevel.Full) { + configFileCache.removeKey(resolved); + globalDependencyGraph = undefined; + } + projectStatus.removeKey(resolved); + diagnostics.removeKey(resolved); + addProjToQueue(resolved, reloadLevel); + } + /** + * return true if new addition + */ + function addProjToQueue(proj, reloadLevel) { + var value = projectPendingBuild.getValue(proj); + if (value === undefined) { + projectPendingBuild.setValue(proj, reloadLevel || ts.ConfigFileProgramReloadLevel.None); + invalidatedProjectQueue.push(proj); + } + else if (value < (reloadLevel || ts.ConfigFileProgramReloadLevel.None)) { + projectPendingBuild.setValue(proj, reloadLevel || ts.ConfigFileProgramReloadLevel.None); + } + } + function getNextInvalidatedProject() { + if (nextProjectToBuild < invalidatedProjectQueue.length) { + var project = invalidatedProjectQueue[nextProjectToBuild]; + nextProjectToBuild++; + var reloadLevel = projectPendingBuild.getValue(project); + projectPendingBuild.removeKey(project); + if (!projectPendingBuild.getSize()) { + invalidatedProjectQueue.length = 0; + nextProjectToBuild = 0; + } + return { project: project, reloadLevel: reloadLevel }; + } + } + function hasPendingInvalidatedProjects() { + return !!projectPendingBuild.getSize(); + } + function scheduleBuildInvalidatedProject() { + if (!hostWithWatch.setTimeout || !hostWithWatch.clearTimeout) { + return; + } + if (timerToBuildInvalidatedProject) { + hostWithWatch.clearTimeout(timerToBuildInvalidatedProject); + } + timerToBuildInvalidatedProject = hostWithWatch.setTimeout(buildInvalidatedProject, 250); + } + function buildInvalidatedProject() { + timerToBuildInvalidatedProject = undefined; + if (reportFileChangeDetected) { + reportFileChangeDetected = false; + projectErrorsReported.clear(); + reportWatchStatus(ts.Diagnostics.File_change_detected_Starting_incremental_compilation); + } + var buildProject = getNextInvalidatedProject(); + if (buildProject) { + buildSingleInvalidatedProject(buildProject.project, buildProject.reloadLevel); + if (hasPendingInvalidatedProjects()) { + if (options.watch && !timerToBuildInvalidatedProject) { + scheduleBuildInvalidatedProject(); + } + } + else { + reportErrorSummary(); + } + } + } + function reportErrorSummary() { + if (options.watch || host.reportErrorSummary) { + // Report errors from the other projects + getGlobalDependencyGraph().buildQueue.forEach(function (project) { + if (!projectErrorsReported.hasKey(project)) { + reportErrors(diagnostics.getValue(project) || ts.emptyArray); + } + }); + var totalErrors_1 = 0; + diagnostics.forEach(function (singleProjectErrors) { return totalErrors_1 += ts.getErrorCountForSummary(singleProjectErrors); }); + if (options.watch) { + reportWatchStatus(ts.getWatchErrorSummaryDiagnosticMessage(totalErrors_1), totalErrors_1); + } + else { + host.reportErrorSummary(totalErrors_1); + } + } + } + function buildSingleInvalidatedProject(resolved, reloadLevel) { + var proj = parseConfigFile(resolved); + if (!proj) { + reportParseConfigFileDiagnostic(resolved); + return; + } + if (reloadLevel === ts.ConfigFileProgramReloadLevel.Full) { + watchConfigFile(resolved); + watchWildCardDirectories(resolved, proj); + watchInputFiles(resolved, proj); + } + else if (reloadLevel === ts.ConfigFileProgramReloadLevel.Partial) { + // Update file names + var result = ts.getFileNamesFromConfigSpecs(proj.configFileSpecs, ts.getDirectoryPath(resolved), proj.options, parseConfigFileHost); + ts.updateErrorForNoInputFiles(result, resolved, proj.configFileSpecs, proj.errors, ts.canJsonReportNoInutFiles(proj.raw)); + proj.fileNames = result.fileNames; + watchInputFiles(resolved, proj); + } + var status = getUpToDateStatus(proj); + verboseReportProjectStatus(resolved, status); + if (status.type === UpToDateStatusType.UpstreamBlocked) { + if (options.verbose) + reportStatus(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, resolved, status.upstreamProjectName); + return; + } + var buildResult = buildSingleProject(resolved); + var dependencyGraph = getGlobalDependencyGraph(); + var referencingProjects = dependencyGraph.referencingProjectsMap.getValue(resolved); + if (!referencingProjects) + return; + // Always use build order to queue projects + for (var _i = 0, _a = dependencyGraph.buildQueue; _i < _a.length; _i++) { + var project = _a[_i]; + var prepend = referencingProjects.getValue(project); + // If the project is referenced with prepend, always build downstream projectm, + // otherwise queue it only if declaration output changed + if (prepend || (prepend !== undefined && !(buildResult & BuildResultFlags.DeclarationOutputUnchanged))) { + addProjToQueue(project); + } + } + } + function createDependencyGraph(roots) { + var temporaryMarks = createFileMap(toPath); + var permanentMarks = createFileMap(toPath); + var circularityReportStack = []; + var buildOrder = []; + var referencingProjectsMap = createFileMap(toPath); + for (var _i = 0, roots_1 = roots; _i < roots_1.length; _i++) { + var root = roots_1[_i]; + visit(root); + } + return { + buildQueue: buildOrder, + referencingProjectsMap: referencingProjectsMap + }; + function visit(projPath, inCircularContext) { + // Already visited + if (permanentMarks.hasKey(projPath)) + return; + // Circular + if (temporaryMarks.hasKey(projPath)) { + if (!inCircularContext) { + // TODO:: Do we report this as error? + reportStatus(ts.Diagnostics.Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0, circularityReportStack.join("\r\n")); + } + return; + } + temporaryMarks.setValue(projPath, true); + circularityReportStack.push(projPath); + var parsed = parseConfigFile(projPath); + if (parsed && parsed.projectReferences) { + for (var _i = 0, _a = parsed.projectReferences; _i < _a.length; _i++) { + var ref = _a[_i]; + var resolvedRefPath = resolveProjectName(ref.path); + visit(resolvedRefPath, inCircularContext || ref.circular); + // Get projects referencing resolvedRefPath and add projPath to it + var referencingProjects = getOrCreateValueFromConfigFileMap(referencingProjectsMap, resolvedRefPath, function () { return createFileMap(toPath); }); + referencingProjects.setValue(projPath, !!ref.prepend); + } + } + circularityReportStack.pop(); + permanentMarks.setValue(projPath, true); + buildOrder.push(projPath); + } + } + function buildSingleProject(proj) { + if (options.dry) { + reportStatus(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj); + return BuildResultFlags.Success; + } + if (options.verbose) + reportStatus(ts.Diagnostics.Building_project_0, proj); + var resultFlags = BuildResultFlags.None; + resultFlags |= BuildResultFlags.DeclarationOutputUnchanged; + var configFile = parseConfigFile(proj); + if (!configFile) { + // Failed to read the config file + resultFlags |= BuildResultFlags.ConfigFileErrors; + reportParseConfigFileDiagnostic(proj); + projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Config file errors" }); + return resultFlags; + } + if (configFile.fileNames.length === 0) { + reportAndStoreErrors(proj, configFile.errors); + // Nothing to build - must be a solution file, basically + return BuildResultFlags.None; + } + var programOptions = { + projectReferences: configFile.projectReferences, + host: host, + rootNames: configFile.fileNames, + options: configFile.options, + configFileParsingDiagnostics: configFile.errors + }; + if (host.beforeCreateProgram) { + host.beforeCreateProgram(options); + } + var program = ts.createProgram(programOptions); + // Don't emit anything in the presence of syntactic errors or options diagnostics + var syntaxDiagnostics = program.getOptionsDiagnostics().concat(program.getConfigFileParsingDiagnostics(), program.getSyntacticDiagnostics()); + if (syntaxDiagnostics.length) { + return buildErrors(syntaxDiagnostics, BuildResultFlags.SyntaxErrors, "Syntactic"); + } + // Same as above but now for semantic diagnostics + var semanticDiagnostics = program.getSemanticDiagnostics(); + if (semanticDiagnostics.length) { + return buildErrors(semanticDiagnostics, BuildResultFlags.TypeErrors, "Semantic"); + } + var newestDeclarationFileContentChangedTime = minimumDate; + var anyDtsChanged = false; + var declDiagnostics; + var reportDeclarationDiagnostics = function (d) { return (declDiagnostics || (declDiagnostics = [])).push(d); }; + var outputFiles = []; + ts.emitFilesAndReportErrors(program, reportDeclarationDiagnostics, writeFileName, /*reportSummary*/ undefined, function (name, text, writeByteOrderMark) { return outputFiles.push({ name: name, text: text, writeByteOrderMark: writeByteOrderMark }); }); + // Don't emit .d.ts if there are decl file errors + if (declDiagnostics) { + return buildErrors(declDiagnostics, BuildResultFlags.DeclarationEmitErrors, "Declaration file"); + } + // Actual Emit + var emitterDiagnostics = ts.createDiagnosticCollection(); + outputFiles.forEach(function (_a) { + var name = _a.name, text = _a.text, writeByteOrderMark = _a.writeByteOrderMark; + var priorChangeTime; + if (!anyDtsChanged && isDeclarationFile(name)) { + // Check for unchanged .d.ts files + if (host.fileExists(name) && readFileWithCache(name) === text) { + priorChangeTime = host.getModifiedTime(name); + } + else { + resultFlags &= ~BuildResultFlags.DeclarationOutputUnchanged; + anyDtsChanged = true; + } + } + ts.writeFile(host, emitterDiagnostics, name, text, writeByteOrderMark); + if (priorChangeTime !== undefined) { + newestDeclarationFileContentChangedTime = newer(priorChangeTime, newestDeclarationFileContentChangedTime); + unchangedOutputs.setValue(name, priorChangeTime); + } + }); + var emitDiagnostics = emitterDiagnostics.getDiagnostics(); + if (emitDiagnostics.length) { + return buildErrors(emitDiagnostics, BuildResultFlags.EmitErrors, "Emit"); + } + var status = { + type: UpToDateStatusType.UpToDate, + newestDeclarationFileContentChangedTime: anyDtsChanged ? maximumDate : newestDeclarationFileContentChangedTime + }; + diagnostics.removeKey(proj); + projectStatus.setValue(proj, status); + if (host.afterProgramEmitAndDiagnostics) { + host.afterProgramEmitAndDiagnostics(program); + } + return resultFlags; + function buildErrors(diagnostics, errorFlags, errorType) { + resultFlags |= errorFlags; + reportAndStoreErrors(proj, diagnostics); + projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: errorType + " errors" }); + if (host.afterProgramEmitAndDiagnostics) { + host.afterProgramEmitAndDiagnostics(program); + } + return resultFlags; + } + } + function updateOutputTimestamps(proj) { + if (options.dry) { + return reportStatus(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj.options.configFilePath); + } + if (options.verbose) { + reportStatus(ts.Diagnostics.Updating_output_timestamps_of_project_0, proj.options.configFilePath); + } + var now = new Date(); + var outputs = getAllProjectOutputs(proj); + var priorNewestUpdateTime = minimumDate; + for (var _i = 0, outputs_2 = outputs; _i < outputs_2.length; _i++) { + var file = outputs_2[_i]; + if (isDeclarationFile(file)) { + priorNewestUpdateTime = newer(priorNewestUpdateTime, host.getModifiedTime(file) || ts.missingFileModifiedTime); + } + host.setModifiedTime(file, now); + } + projectStatus.setValue(proj.options.configFilePath, { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: priorNewestUpdateTime }); + } + function getFilesToClean() { + // Get the same graph for cleaning we'd use for building + var graph = getGlobalDependencyGraph(); + var filesToDelete = []; + for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { + var proj = _a[_i]; + var parsed = parseConfigFile(proj); + if (parsed === undefined) { + // File has gone missing; fine to ignore here + reportParseConfigFileDiagnostic(proj); + continue; + } + var outputs = getAllProjectOutputs(parsed); + for (var _b = 0, outputs_3 = outputs; _b < outputs_3.length; _b++) { + var output = outputs_3[_b]; + if (host.fileExists(output)) { + filesToDelete.push(output); + } + } + } + return filesToDelete; + } + function cleanAllProjects() { + var filesToDelete = getFilesToClean(); + if (options.dry) { + reportStatus(ts.Diagnostics.A_non_dry_build_would_delete_the_following_files_Colon_0, filesToDelete.map(function (f) { return "\r\n * " + f; }).join("")); + return ts.ExitStatus.Success; + } + for (var _i = 0, filesToDelete_1 = filesToDelete; _i < filesToDelete_1.length; _i++) { + var output = filesToDelete_1[_i]; + host.deleteFile(output); + } + return ts.ExitStatus.Success; + } + function resolveProjectName(name) { + return resolveConfigFileProjectName(ts.resolvePath(host.getCurrentDirectory(), name)); + } + function resolveProjectNames(configFileNames) { + return configFileNames.map(resolveProjectName); + } + function buildAllProjects() { + if (options.watch) { + reportWatchStatus(ts.Diagnostics.Starting_compilation_in_watch_mode); + } + // TODO:: In watch mode as well to use caches for incremental build once we can invalidate caches correctly and have right api + // Override readFile for json files and output .d.ts to cache the text + var _a = ts.changeCompilerHostToUseCache(host, toPath, /*useCacheForSourceFile*/ true), originalReadFile = _a.originalReadFile, originalFileExists = _a.originalFileExists, originalDirectoryExists = _a.originalDirectoryExists, originalCreateDirectory = _a.originalCreateDirectory, originalWriteFile = _a.originalWriteFile, originalGetSourceFile = _a.originalGetSourceFile, newReadFileWithCache = _a.readFileWithCache; + var savedReadFileWithCache = readFileWithCache; + readFileWithCache = newReadFileWithCache; + var graph = getGlobalDependencyGraph(); + reportBuildQueue(graph); + var anyFailed = false; + for (var _i = 0, _b = graph.buildQueue; _i < _b.length; _i++) { + var next = _b[_i]; + var proj = parseConfigFile(next); + if (proj === undefined) { + reportParseConfigFileDiagnostic(next); + anyFailed = true; + break; + } + // report errors early when using continue or break statements + var errors = proj.errors; + var status = getUpToDateStatus(proj); + verboseReportProjectStatus(next, status); + var projName = proj.options.configFilePath; + if (status.type === UpToDateStatusType.UpToDate && !options.force) { + reportAndStoreErrors(next, errors); + // Up to date, skip + if (defaultOptions.dry) { + // In a dry build, inform the user of this fact + reportStatus(ts.Diagnostics.Project_0_is_up_to_date, projName); + } + continue; + } + if (status.type === UpToDateStatusType.UpToDateWithUpstreamTypes && !options.force) { + reportAndStoreErrors(next, errors); + // Fake build + updateOutputTimestamps(proj); + continue; + } + if (status.type === UpToDateStatusType.UpstreamBlocked) { + reportAndStoreErrors(next, errors); + if (options.verbose) + reportStatus(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, projName, status.upstreamProjectName); + continue; + } + if (status.type === UpToDateStatusType.ContainerOnly) { + reportAndStoreErrors(next, errors); + // Do nothing + continue; + } + var buildResult = buildSingleProject(next); + anyFailed = anyFailed || !!(buildResult & BuildResultFlags.AnyErrors); + } + reportErrorSummary(); + host.readFile = originalReadFile; + host.fileExists = originalFileExists; + host.directoryExists = originalDirectoryExists; + host.createDirectory = originalCreateDirectory; + host.writeFile = originalWriteFile; + readFileWithCache = savedReadFileWithCache; + host.getSourceFile = originalGetSourceFile; + return anyFailed ? ts.ExitStatus.DiagnosticsPresent_OutputsSkipped : ts.ExitStatus.Success; + } + function reportParseConfigFileDiagnostic(proj) { + reportAndStoreErrors(proj, [configFileCache.getValue(proj)]); + } + function reportAndStoreErrors(proj, errors) { + reportErrors(errors); + projectErrorsReported.setValue(proj, true); + diagnostics.setValue(proj, errors); + } + function reportErrors(errors) { + errors.forEach(function (err) { return host.reportDiagnostic(err); }); + } + /** + * Report the build ordering inferred from the current project graph if we're in verbose mode + */ + function reportBuildQueue(graph) { + if (options.verbose) { + reportStatus(ts.Diagnostics.Projects_in_this_build_Colon_0, graph.buildQueue.map(function (s) { return "\r\n * " + relName(s); }).join("")); + } + } + function relName(path) { + return ts.convertToRelativePath(path, host.getCurrentDirectory(), function (f) { return host.getCanonicalFileName(f); }); + } + /** + * Report the up-to-date status of a project if we're in verbose mode + */ + function verboseReportProjectStatus(configFileName, status) { + if (!options.verbose) + return; + return formatUpToDateStatus(configFileName, status, relName, reportStatus); + } + } + ts.createSolutionBuilder = createSolutionBuilder; + function resolveConfigFileProjectName(project) { + if (ts.fileExtensionIs(project, ".json" /* Json */)) { + return project; + } + return ts.combinePaths(project, "tsconfig.json"); + } + ts.resolveConfigFileProjectName = resolveConfigFileProjectName; + function getAllProjectOutputs(project) { + if (project.options.outFile || project.options.out) { + return getOutFileOutputs(project); + } + else { + var outputs = []; + for (var _i = 0, _a = project.fileNames; _i < _a.length; _i++) { + var inputFile = _a[_i]; + outputs.push.apply(outputs, getOutputFileNames(inputFile, project)); + } + return outputs; + } + } + ts.getAllProjectOutputs = getAllProjectOutputs; + function formatUpToDateStatus(configFileName, status, relName, formatMessage) { + switch (status.type) { + case UpToDateStatusType.OutOfDateWithSelf: + return formatMessage(ts.Diagnostics.Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2, relName(configFileName), relName(status.outOfDateOutputFileName), relName(status.newerInputFileName)); + case UpToDateStatusType.OutOfDateWithUpstream: + return formatMessage(ts.Diagnostics.Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2, relName(configFileName), relName(status.outOfDateOutputFileName), relName(status.newerProjectName)); + case UpToDateStatusType.OutputMissing: + return formatMessage(ts.Diagnostics.Project_0_is_out_of_date_because_output_file_1_does_not_exist, relName(configFileName), relName(status.missingOutputFileName)); + case UpToDateStatusType.UpToDate: + if (status.newestInputFileTime !== undefined) { + return formatMessage(ts.Diagnostics.Project_0_is_up_to_date_because_newest_input_1_is_older_than_oldest_output_2, relName(configFileName), relName(status.newestInputFileName || ""), relName(status.oldestOutputFileName || "")); + } + // Don't report anything for "up to date because it was already built" -- too verbose + break; + case UpToDateStatusType.UpToDateWithUpstreamTypes: + return formatMessage(ts.Diagnostics.Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies, relName(configFileName)); + case UpToDateStatusType.UpstreamOutOfDate: + return formatMessage(ts.Diagnostics.Project_0_is_out_of_date_because_its_dependency_1_is_out_of_date, relName(configFileName), relName(status.upstreamProjectName)); + case UpToDateStatusType.UpstreamBlocked: + return formatMessage(ts.Diagnostics.Project_0_can_t_be_built_because_its_dependency_1_has_errors, relName(configFileName), relName(status.upstreamProjectName)); + case UpToDateStatusType.Unbuildable: + return formatMessage(ts.Diagnostics.Failed_to_parse_file_0_Colon_1, relName(configFileName), status.reason); + case UpToDateStatusType.ContainerOnly: + // Don't report status on "solution" projects + case UpToDateStatusType.ComputingUpstream: + // Should never leak from getUptoDateStatusWorker + break; + default: + ts.assertType(status); + } + } + ts.formatUpToDateStatus = formatUpToDateStatus; +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var ValueKind; + (function (ValueKind) { + ValueKind[ValueKind["Const"] = 0] = "Const"; + ValueKind[ValueKind["Array"] = 1] = "Array"; + ValueKind[ValueKind["FunctionOrClass"] = 2] = "FunctionOrClass"; + ValueKind[ValueKind["Object"] = 3] = "Object"; + })(ValueKind = ts.ValueKind || (ts.ValueKind = {})); + function inspectModule(fileNameToRequire) { + return inspectValue(ts.removeFileExtension(ts.getBaseFileName(fileNameToRequire)), tryRequire(fileNameToRequire)); + } + ts.inspectModule = inspectModule; + function inspectValue(name, value) { + return getValueInfo(name, value, getRecurser()); + } + ts.inspectValue = inspectValue; + function getRecurser() { + var seen = new Set(); + var nameStack = []; + return function (obj, name, cbOk, cbFail) { + if (seen.has(obj) || nameStack.length > 4) { + return cbFail(seen.has(obj), nameStack); + } + seen.add(obj); + nameStack.push(name); + var res = cbOk(); + nameStack.pop(); + seen.delete(obj); + return res; + }; + } + function getValueInfo(name, value, recurser) { + return recurser(value, name, function () { + if (typeof value === "function") + return getFunctionOrClassInfo(value, name, recurser); + if (typeof value === "object") { + var builtin = getBuiltinType(name, value, recurser); + if (builtin !== undefined) + return builtin; + var entries = getEntriesOfObject(value); + var hasNontrivialPrototype = Object.getPrototypeOf(value) !== Object.prototype; + var members = ts.flatMap(entries, function (_a) { + var key = _a.key, value = _a.value; + return getValueInfo(key, value, recurser); + }); + return { kind: 3 /* Object */, name: name, hasNontrivialPrototype: hasNontrivialPrototype, members: members }; + } + return { kind: 0 /* Const */, name: name, typeName: isNullOrUndefined(value) ? "any" : typeof value }; + }, function (isCircularReference, keyStack) { return anyValue(name, " " + (isCircularReference ? "Circular reference" : "Too-deep object hierarchy") + " from " + keyStack.join(".")); }); + } + function getFunctionOrClassInfo(fn, name, recurser) { + var prototypeMembers = getPrototypeMembers(fn, recurser); + var namespaceMembers = ts.flatMap(getEntriesOfObject(fn), function (_a) { + var key = _a.key, value = _a.value; + return getValueInfo(key, value, recurser); + }); + var toString = ts.cast(Function.prototype.toString.call(fn), ts.isString); + var source = ts.stringContains(toString, "{ [native code] }") ? getFunctionLength(fn) : toString; + return { kind: 2 /* FunctionOrClass */, name: name, source: source, namespaceMembers: namespaceMembers, prototypeMembers: prototypeMembers }; + } + var builtins = ts.memoize(function () { + var map = ts.createMap(); + for (var _i = 0, _a = getEntriesOfObject(global); _i < _a.length; _i++) { + var _b = _a[_i], key = _b.key, value = _b.value; + if (typeof value === "function" && typeof value.prototype === "object" && value !== Object) { + map.set(key, value); + } + } + return map; + }); + function getBuiltinType(name, value, recurser) { + return ts.isArray(value) + ? { name: name, kind: 1 /* Array */, inner: value.length && getValueInfo("element", ts.first(value), recurser) || anyValue(name) } + : ts.forEachEntry(builtins(), function (builtin, builtinName) { + return value instanceof builtin ? { kind: 0 /* Const */, name: name, typeName: builtinName } : undefined; + }); + } + function getPrototypeMembers(fn, recurser) { + var prototype = fn.prototype; + // tslint:disable-next-line no-unnecessary-type-assertion (TODO: update LKG and it will really be unnecessary) + return typeof prototype !== "object" || prototype === null ? ts.emptyArray : ts.mapDefined(getEntriesOfObject(prototype), function (_a) { + var key = _a.key, value = _a.value; + return key === "constructor" ? undefined : getValueInfo(key, value, recurser); + }); + } + var ignoredProperties = new Set(["arguments", "caller", "constructor", "eval", "super_"]); + var reservedFunctionProperties = new Set(Object.getOwnPropertyNames(ts.noop)); + function getEntriesOfObject(obj) { + var seen = ts.createMap(); + var entries = []; + var chain = obj; + while (!isNullOrUndefined(chain) && chain !== Object.prototype && chain !== Function.prototype) { + for (var _i = 0, _a = Object.getOwnPropertyNames(chain); _i < _a.length; _i++) { + var key = _a[_i]; + if (!isJsPrivate(key) && + !ignoredProperties.has(key) && + (typeof obj !== "function" || !reservedFunctionProperties.has(key)) && + // Don't add property from a higher prototype if it already exists in a lower one + ts.addToSeen(seen, key)) { + var value = safeGetPropertyOfObject(chain, key); + // Don't repeat "toString" that matches signature from Object.prototype + if (!(key === "toString" && typeof value === "function" && value.length === 0)) { + entries.push({ key: key, value: value }); + } + } + } + chain = Object.getPrototypeOf(chain); + } + return entries.sort(function (e1, e2) { return ts.compareStringsCaseSensitive(e1.key, e2.key); }); + } + function getFunctionLength(fn) { + return ts.tryCast(safeGetPropertyOfObject(fn, "length"), ts.isNumber) || 0; + } + function safeGetPropertyOfObject(obj, key) { + var desc = Object.getOwnPropertyDescriptor(obj, key); + return desc && desc.value; + } + function isNullOrUndefined(value) { + return value == null; // tslint:disable-line + } + function anyValue(name, comment) { + return { kind: 0 /* Const */, name: name, typeName: "any", comment: comment }; + } + function isJsPrivate(name) { + return name.startsWith("_"); + } + ts.isJsPrivate = isJsPrivate; + function tryRequire(fileNameToRequire) { + try { + return require(fileNameToRequire); + } + catch (_a) { + return undefined; + } + } +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var server; + (function (server) { + // tslint:disable variable-name + server.ActionSet = "action::set"; + server.ActionInvalidate = "action::invalidate"; + server.ActionPackageInstalled = "action::packageInstalled"; + server.ActionValueInspected = "action::valueInspected"; + server.EventTypesRegistry = "event::typesRegistry"; + server.EventBeginInstallTypes = "event::beginInstallTypes"; + server.EventEndInstallTypes = "event::endInstallTypes"; + server.EventInitializationFailed = "event::initializationFailed"; + var Arguments; + (function (Arguments) { + Arguments.GlobalCacheLocation = "--globalTypingsCacheLocation"; + Arguments.LogFile = "--logFile"; + Arguments.EnableTelemetry = "--enableTelemetry"; + Arguments.TypingSafeListLocation = "--typingSafeListLocation"; + Arguments.TypesMapLocation = "--typesMapLocation"; + /** + * This argument specifies the location of the NPM executable. + * typingsInstaller will run the command with `${npmLocation} install ...`. + */ + Arguments.NpmLocation = "--npmLocation"; + })(Arguments = server.Arguments || (server.Arguments = {})); + function hasArgument(argumentName) { + return ts.sys.args.indexOf(argumentName) >= 0; + } + server.hasArgument = hasArgument; + function findArgument(argumentName) { + var index = ts.sys.args.indexOf(argumentName); + return index >= 0 && index < ts.sys.args.length - 1 + ? ts.sys.args[index + 1] + : undefined; + } + server.findArgument = findArgument; + function nowString() { + // E.g. "12:34:56.789" + var d = new Date(); + return d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds() + "." + d.getMilliseconds(); + } + server.nowString = nowString; + })(server = ts.server || (ts.server = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var JsTyping; + (function (JsTyping) { + function isTypingUpToDate(cachedTyping, availableTypingVersions) { + var availableVersion = new ts.Version(ts.getProperty(availableTypingVersions, "ts" + ts.versionMajorMinor) || ts.getProperty(availableTypingVersions, "latest")); + return availableVersion.compareTo(cachedTyping.version) <= 0; + } + JsTyping.isTypingUpToDate = isTypingUpToDate; + JsTyping.nodeCoreModuleList = [ + "assert", + "async_hooks", + "buffer", + "child_process", + "cluster", + "console", + "constants", + "crypto", + "dgram", + "dns", + "domain", + "events", + "fs", + "http", + "https", + "http2", + "inspector", + "net", + "os", + "path", + "perf_hooks", + "process", + "punycode", + "querystring", + "readline", + "repl", + "stream", + "string_decoder", + "timers", + "tls", + "tty", + "url", + "util", + "v8", + "vm", + "zlib" + ]; + JsTyping.nodeCoreModules = ts.arrayToSet(JsTyping.nodeCoreModuleList); + function loadSafeList(host, safeListPath) { + var result = ts.readConfigFile(safeListPath, function (path) { return host.readFile(path); }); + return ts.createMapFromTemplate(result.config); + } + JsTyping.loadSafeList = loadSafeList; + function loadTypesMap(host, typesMapPath) { + var result = ts.readConfigFile(typesMapPath, function (path) { return host.readFile(path); }); + if (result.config) { + return ts.createMapFromTemplate(result.config.simpleMap); + } + return undefined; + } + JsTyping.loadTypesMap = loadTypesMap; + /** + * @param host is the object providing I/O related operations. + * @param fileNames are the file names that belong to the same project + * @param projectRootPath is the path to the project root directory + * @param safeListPath is the path used to retrieve the safe list + * @param packageNameToTypingLocation is the map of package names to their cached typing locations and installed versions + * @param typeAcquisition is used to customize the typing acquisition process + * @param compilerOptions are used as a source for typing inference + */ + function discoverTypings(host, log, fileNames, projectRootPath, safeList, packageNameToTypingLocation, typeAcquisition, unresolvedImports, typesRegistry) { + if (!typeAcquisition || !typeAcquisition.enable) { + return { cachedTypingPaths: [], newTypingNames: [], filesToWatch: [] }; + } + // A typing name to typing file path mapping + var inferredTypings = ts.createMap(); + // Only infer typings for .js and .jsx files + fileNames = ts.mapDefined(fileNames, function (fileName) { + var path = ts.normalizePath(fileName); + if (ts.hasJSFileExtension(path)) { + return path; + } + }); + var filesToWatch = []; + if (typeAcquisition.include) + addInferredTypings(typeAcquisition.include, "Explicitly included types"); + var exclude = typeAcquisition.exclude || []; + // Directories to search for package.json, bower.json and other typing information + var possibleSearchDirs = ts.arrayToSet(fileNames, ts.getDirectoryPath); + possibleSearchDirs.set(projectRootPath, true); + possibleSearchDirs.forEach(function (_true, searchDir) { + var packageJsonPath = ts.combinePaths(searchDir, "package.json"); + getTypingNamesFromJson(packageJsonPath, filesToWatch); + var bowerJsonPath = ts.combinePaths(searchDir, "bower.json"); + getTypingNamesFromJson(bowerJsonPath, filesToWatch); + var bowerComponentsPath = ts.combinePaths(searchDir, "bower_components"); + getTypingNamesFromPackagesFolder(bowerComponentsPath, filesToWatch); + var nodeModulesPath = ts.combinePaths(searchDir, "node_modules"); + getTypingNamesFromPackagesFolder(nodeModulesPath, filesToWatch); + }); + getTypingNamesFromSourceFileNames(fileNames); + // add typings for unresolved imports + if (unresolvedImports) { + var module_1 = ts.deduplicate(unresolvedImports.map(function (moduleId) { return JsTyping.nodeCoreModules.has(moduleId) ? "node" : moduleId; }), ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive); + addInferredTypings(module_1, "Inferred typings from unresolved imports"); + } + // Add the cached typing locations for inferred typings that are already installed + packageNameToTypingLocation.forEach(function (typing, name) { + var registryEntry = typesRegistry.get(name); + if (inferredTypings.has(name) && inferredTypings.get(name) === undefined && registryEntry !== undefined && isTypingUpToDate(typing, registryEntry)) { + inferredTypings.set(name, typing.typingLocation); + } + }); + // Remove typings that the user has added to the exclude list + for (var _i = 0, exclude_1 = exclude; _i < exclude_1.length; _i++) { + var excludeTypingName = exclude_1[_i]; + var didDelete = inferredTypings.delete(excludeTypingName); + if (didDelete && log) + log("Typing for " + excludeTypingName + " is in exclude list, will be ignored."); + } + var newTypingNames = []; + var cachedTypingPaths = []; + inferredTypings.forEach(function (inferred, typing) { + if (inferred !== undefined) { + cachedTypingPaths.push(inferred); + } + else { + newTypingNames.push(typing); + } + }); + var result = { cachedTypingPaths: cachedTypingPaths, newTypingNames: newTypingNames, filesToWatch: filesToWatch }; + if (log) + log("Result: " + JSON.stringify(result)); + return result; + function addInferredTyping(typingName) { + if (!inferredTypings.has(typingName)) { + inferredTypings.set(typingName, undefined); // TODO: GH#18217 + } + } + function addInferredTypings(typingNames, message) { + if (log) + log(message + ": " + JSON.stringify(typingNames)); + ts.forEach(typingNames, addInferredTyping); + } + /** + * Get the typing info from common package manager json files like package.json or bower.json + */ + function getTypingNamesFromJson(jsonPath, filesToWatch) { + if (!host.fileExists(jsonPath)) { + return; + } + filesToWatch.push(jsonPath); + var jsonConfig = ts.readConfigFile(jsonPath, function (path) { return host.readFile(path); }).config; + var jsonTypingNames = ts.flatMap([jsonConfig.dependencies, jsonConfig.devDependencies, jsonConfig.optionalDependencies, jsonConfig.peerDependencies], ts.getOwnKeys); + addInferredTypings(jsonTypingNames, "Typing names in '" + jsonPath + "' dependencies"); + } + /** + * Infer typing names from given file names. For example, the file name "jquery-min.2.3.4.js" + * should be inferred to the 'jquery' typing name; and "angular-route.1.2.3.js" should be inferred + * to the 'angular-route' typing name. + * @param fileNames are the names for source files in the project + */ + function getTypingNamesFromSourceFileNames(fileNames) { + var fromFileNames = ts.mapDefined(fileNames, function (j) { + if (!ts.hasJSFileExtension(j)) + return undefined; + var inferredTypingName = ts.removeFileExtension(ts.getBaseFileName(j.toLowerCase())); + var cleanedTypingName = ts.removeMinAndVersionNumbers(inferredTypingName); + return safeList.get(cleanedTypingName); + }); + if (fromFileNames.length) { + addInferredTypings(fromFileNames, "Inferred typings from file names"); + } + var hasJsxFile = ts.some(fileNames, function (f) { return ts.fileExtensionIs(f, ".jsx" /* Jsx */); }); + if (hasJsxFile) { + if (log) + log("Inferred 'react' typings due to presence of '.jsx' extension"); + addInferredTyping("react"); + } + } + /** + * Infer typing names from packages folder (ex: node_module, bower_components) + * @param packagesFolderPath is the path to the packages folder + */ + function getTypingNamesFromPackagesFolder(packagesFolderPath, filesToWatch) { + filesToWatch.push(packagesFolderPath); + // Todo: add support for ModuleResolutionHost too + if (!host.directoryExists(packagesFolderPath)) { + return; + } + // depth of 2, so we access `node_modules/foo` but not `node_modules/foo/bar` + var fileNames = host.readDirectory(packagesFolderPath, [".json" /* Json */], /*excludes*/ undefined, /*includes*/ undefined, /*depth*/ 2); + if (log) + log("Searching for typing names in " + packagesFolderPath + "; all files: " + JSON.stringify(fileNames)); + var packageNames = []; + for (var _i = 0, fileNames_1 = fileNames; _i < fileNames_1.length; _i++) { + var fileName = fileNames_1[_i]; + var normalizedFileName = ts.normalizePath(fileName); + var baseFileName = ts.getBaseFileName(normalizedFileName); + if (baseFileName !== "package.json" && baseFileName !== "bower.json") { + continue; + } + var result_6 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); }); + var packageJson = result_6.config; + // npm 3's package.json contains a "_requiredBy" field + // we should include all the top level module names for npm 2, and only module names whose + // "_requiredBy" field starts with "#" or equals "/" for npm 3. + if (baseFileName === "package.json" && packageJson._requiredBy && + ts.filter(packageJson._requiredBy, function (r) { return r[0] === "#" || r === "/"; }).length === 0) { + continue; + } + // If the package has its own d.ts typings, those will take precedence. Otherwise the package name will be used + // to download d.ts files from DefinitelyTyped + if (!packageJson.name) { + continue; + } + var ownTypes = packageJson.types || packageJson.typings; + if (ownTypes) { + var absolutePath = ts.getNormalizedAbsolutePath(ownTypes, ts.getDirectoryPath(normalizedFileName)); + if (log) + log(" Package '" + packageJson.name + "' provides its own types."); + inferredTypings.set(packageJson.name, absolutePath); + } + else { + packageNames.push(packageJson.name); + } + } + addInferredTypings(packageNames, " Found package names"); + } + } + JsTyping.discoverTypings = discoverTypings; + var PackageNameValidationResult; + (function (PackageNameValidationResult) { + PackageNameValidationResult[PackageNameValidationResult["Ok"] = 0] = "Ok"; + PackageNameValidationResult[PackageNameValidationResult["ScopedPackagesNotSupported"] = 1] = "ScopedPackagesNotSupported"; + PackageNameValidationResult[PackageNameValidationResult["EmptyName"] = 2] = "EmptyName"; + PackageNameValidationResult[PackageNameValidationResult["NameTooLong"] = 3] = "NameTooLong"; + PackageNameValidationResult[PackageNameValidationResult["NameStartsWithDot"] = 4] = "NameStartsWithDot"; + PackageNameValidationResult[PackageNameValidationResult["NameStartsWithUnderscore"] = 5] = "NameStartsWithUnderscore"; + PackageNameValidationResult[PackageNameValidationResult["NameContainsNonURISafeCharacters"] = 6] = "NameContainsNonURISafeCharacters"; + })(PackageNameValidationResult = JsTyping.PackageNameValidationResult || (JsTyping.PackageNameValidationResult = {})); + var maxPackageNameLength = 214; + /** + * Validates package name using rules defined at https://docs.npmjs.com/files/package.json + */ + function validatePackageName(packageName) { + if (!packageName) { + return 2 /* EmptyName */; + } + if (packageName.length > maxPackageNameLength) { + return 3 /* NameTooLong */; + } + if (packageName.charCodeAt(0) === 46 /* dot */) { + return 4 /* NameStartsWithDot */; + } + if (packageName.charCodeAt(0) === 95 /* _ */) { + return 5 /* NameStartsWithUnderscore */; + } + // check if name is scope package like: starts with @ and has one '/' in the middle + // scoped packages are not currently supported + // TODO: when support will be added we'll need to split and check both scope and package name + if (/^@[^/]+\/[^/]+$/.test(packageName)) { + return 1 /* ScopedPackagesNotSupported */; + } + if (encodeURIComponent(packageName) !== packageName) { + return 6 /* NameContainsNonURISafeCharacters */; + } + return 0 /* Ok */; + } + JsTyping.validatePackageName = validatePackageName; + function renderPackageNameValidationFailure(result, typing) { + switch (result) { + case 2 /* EmptyName */: + return "Package name '" + typing + "' cannot be empty"; + case 3 /* NameTooLong */: + return "Package name '" + typing + "' should be less than " + maxPackageNameLength + " characters"; + case 4 /* NameStartsWithDot */: + return "Package name '" + typing + "' cannot start with '.'"; + case 5 /* NameStartsWithUnderscore */: + return "Package name '" + typing + "' cannot start with '_'"; + case 1 /* ScopedPackagesNotSupported */: + return "Package '" + typing + "' is scoped and currently is not supported"; + case 6 /* NameContainsNonURISafeCharacters */: + return "Package name '" + typing + "' contains non URI safe characters"; + case 0 /* Ok */: + return ts.Debug.fail(); // Shouldn't have called this. + default: + throw ts.Debug.assertNever(result); + } + } + JsTyping.renderPackageNameValidationFailure = renderPackageNameValidationFailure; + })(JsTyping = ts.JsTyping || (ts.JsTyping = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + var ScriptSnapshot; + (function (ScriptSnapshot) { + var StringScriptSnapshot = /** @class */ (function () { + function StringScriptSnapshot(text) { + this.text = text; + } + StringScriptSnapshot.prototype.getText = function (start, end) { + return start === 0 && end === this.text.length + ? this.text + : this.text.substring(start, end); + }; + StringScriptSnapshot.prototype.getLength = function () { + return this.text.length; + }; + StringScriptSnapshot.prototype.getChangeRange = function () { + // Text-based snapshots do not support incremental parsing. Return undefined + // to signal that to the caller. + return undefined; + }; + return StringScriptSnapshot; + }()); + function fromString(text) { + return new StringScriptSnapshot(text); + } + ScriptSnapshot.fromString = fromString; + })(ScriptSnapshot = ts.ScriptSnapshot || (ts.ScriptSnapshot = {})); + /* @internal */ + ts.emptyOptions = {}; + var HighlightSpanKind; + (function (HighlightSpanKind) { + HighlightSpanKind["none"] = "none"; + HighlightSpanKind["definition"] = "definition"; + HighlightSpanKind["reference"] = "reference"; + HighlightSpanKind["writtenReference"] = "writtenReference"; + })(HighlightSpanKind = ts.HighlightSpanKind || (ts.HighlightSpanKind = {})); + var IndentStyle; + (function (IndentStyle) { + IndentStyle[IndentStyle["None"] = 0] = "None"; + IndentStyle[IndentStyle["Block"] = 1] = "Block"; + IndentStyle[IndentStyle["Smart"] = 2] = "Smart"; + })(IndentStyle = ts.IndentStyle || (ts.IndentStyle = {})); + function getDefaultFormatCodeSettings(newLineCharacter) { + return { + indentSize: 4, + tabSize: 4, + newLineCharacter: newLineCharacter || "\n", + convertTabsToSpaces: true, + indentStyle: IndentStyle.Smart, + insertSpaceAfterConstructor: false, + insertSpaceAfterCommaDelimiter: true, + insertSpaceAfterSemicolonInForStatements: true, + insertSpaceBeforeAndAfterBinaryOperators: true, + insertSpaceAfterKeywordsInControlFlowStatements: true, + insertSpaceAfterFunctionKeywordForAnonymousFunctions: false, + insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: false, + insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: false, + insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces: true, + insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: false, + insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces: false, + insertSpaceBeforeFunctionParenthesis: false, + placeOpenBraceOnNewLineForFunctions: false, + placeOpenBraceOnNewLineForControlBlocks: false, + }; + } + ts.getDefaultFormatCodeSettings = getDefaultFormatCodeSettings; + /* @internal */ + ts.testFormatSettings = getDefaultFormatCodeSettings("\n"); + var SymbolDisplayPartKind; + (function (SymbolDisplayPartKind) { + SymbolDisplayPartKind[SymbolDisplayPartKind["aliasName"] = 0] = "aliasName"; + SymbolDisplayPartKind[SymbolDisplayPartKind["className"] = 1] = "className"; + SymbolDisplayPartKind[SymbolDisplayPartKind["enumName"] = 2] = "enumName"; + SymbolDisplayPartKind[SymbolDisplayPartKind["fieldName"] = 3] = "fieldName"; + SymbolDisplayPartKind[SymbolDisplayPartKind["interfaceName"] = 4] = "interfaceName"; + SymbolDisplayPartKind[SymbolDisplayPartKind["keyword"] = 5] = "keyword"; + SymbolDisplayPartKind[SymbolDisplayPartKind["lineBreak"] = 6] = "lineBreak"; + SymbolDisplayPartKind[SymbolDisplayPartKind["numericLiteral"] = 7] = "numericLiteral"; + SymbolDisplayPartKind[SymbolDisplayPartKind["stringLiteral"] = 8] = "stringLiteral"; + SymbolDisplayPartKind[SymbolDisplayPartKind["localName"] = 9] = "localName"; + SymbolDisplayPartKind[SymbolDisplayPartKind["methodName"] = 10] = "methodName"; + SymbolDisplayPartKind[SymbolDisplayPartKind["moduleName"] = 11] = "moduleName"; + SymbolDisplayPartKind[SymbolDisplayPartKind["operator"] = 12] = "operator"; + SymbolDisplayPartKind[SymbolDisplayPartKind["parameterName"] = 13] = "parameterName"; + SymbolDisplayPartKind[SymbolDisplayPartKind["propertyName"] = 14] = "propertyName"; + SymbolDisplayPartKind[SymbolDisplayPartKind["punctuation"] = 15] = "punctuation"; + SymbolDisplayPartKind[SymbolDisplayPartKind["space"] = 16] = "space"; + SymbolDisplayPartKind[SymbolDisplayPartKind["text"] = 17] = "text"; + SymbolDisplayPartKind[SymbolDisplayPartKind["typeParameterName"] = 18] = "typeParameterName"; + SymbolDisplayPartKind[SymbolDisplayPartKind["enumMemberName"] = 19] = "enumMemberName"; + SymbolDisplayPartKind[SymbolDisplayPartKind["functionName"] = 20] = "functionName"; + SymbolDisplayPartKind[SymbolDisplayPartKind["regularExpressionLiteral"] = 21] = "regularExpressionLiteral"; + })(SymbolDisplayPartKind = ts.SymbolDisplayPartKind || (ts.SymbolDisplayPartKind = {})); + var OutliningSpanKind; + (function (OutliningSpanKind) { + /** Single or multi-line comments */ + OutliningSpanKind["Comment"] = "comment"; + /** Sections marked by '// #region' and '// #endregion' comments */ + OutliningSpanKind["Region"] = "region"; + /** Declarations and expressions */ + OutliningSpanKind["Code"] = "code"; + /** Contiguous blocks of import declarations */ + OutliningSpanKind["Imports"] = "imports"; + })(OutliningSpanKind = ts.OutliningSpanKind || (ts.OutliningSpanKind = {})); + var OutputFileType; + (function (OutputFileType) { + OutputFileType[OutputFileType["JavaScript"] = 0] = "JavaScript"; + OutputFileType[OutputFileType["SourceMap"] = 1] = "SourceMap"; + OutputFileType[OutputFileType["Declaration"] = 2] = "Declaration"; + })(OutputFileType = ts.OutputFileType || (ts.OutputFileType = {})); + var EndOfLineState; + (function (EndOfLineState) { + EndOfLineState[EndOfLineState["None"] = 0] = "None"; + EndOfLineState[EndOfLineState["InMultiLineCommentTrivia"] = 1] = "InMultiLineCommentTrivia"; + EndOfLineState[EndOfLineState["InSingleQuoteStringLiteral"] = 2] = "InSingleQuoteStringLiteral"; + EndOfLineState[EndOfLineState["InDoubleQuoteStringLiteral"] = 3] = "InDoubleQuoteStringLiteral"; + EndOfLineState[EndOfLineState["InTemplateHeadOrNoSubstitutionTemplate"] = 4] = "InTemplateHeadOrNoSubstitutionTemplate"; + EndOfLineState[EndOfLineState["InTemplateMiddleOrTail"] = 5] = "InTemplateMiddleOrTail"; + EndOfLineState[EndOfLineState["InTemplateSubstitutionPosition"] = 6] = "InTemplateSubstitutionPosition"; + })(EndOfLineState = ts.EndOfLineState || (ts.EndOfLineState = {})); + var TokenClass; + (function (TokenClass) { + TokenClass[TokenClass["Punctuation"] = 0] = "Punctuation"; + TokenClass[TokenClass["Keyword"] = 1] = "Keyword"; + TokenClass[TokenClass["Operator"] = 2] = "Operator"; + TokenClass[TokenClass["Comment"] = 3] = "Comment"; + TokenClass[TokenClass["Whitespace"] = 4] = "Whitespace"; + TokenClass[TokenClass["Identifier"] = 5] = "Identifier"; + TokenClass[TokenClass["NumberLiteral"] = 6] = "NumberLiteral"; + TokenClass[TokenClass["BigIntLiteral"] = 7] = "BigIntLiteral"; + TokenClass[TokenClass["StringLiteral"] = 8] = "StringLiteral"; + TokenClass[TokenClass["RegExpLiteral"] = 9] = "RegExpLiteral"; + })(TokenClass = ts.TokenClass || (ts.TokenClass = {})); + var ScriptElementKind; + (function (ScriptElementKind) { + ScriptElementKind["unknown"] = ""; + ScriptElementKind["warning"] = "warning"; + /** predefined type (void) or keyword (class) */ + ScriptElementKind["keyword"] = "keyword"; + /** top level script node */ + ScriptElementKind["scriptElement"] = "script"; + /** module foo {} */ + ScriptElementKind["moduleElement"] = "module"; + /** class X {} */ + ScriptElementKind["classElement"] = "class"; + /** var x = class X {} */ + ScriptElementKind["localClassElement"] = "local class"; + /** interface Y {} */ + ScriptElementKind["interfaceElement"] = "interface"; + /** type T = ... */ + ScriptElementKind["typeElement"] = "type"; + /** enum E */ + ScriptElementKind["enumElement"] = "enum"; + ScriptElementKind["enumMemberElement"] = "enum member"; + /** + * Inside module and script only + * const v = .. + */ + ScriptElementKind["variableElement"] = "var"; + /** Inside function */ + ScriptElementKind["localVariableElement"] = "local var"; + /** + * Inside module and script only + * function f() { } + */ + ScriptElementKind["functionElement"] = "function"; + /** Inside function */ + ScriptElementKind["localFunctionElement"] = "local function"; + /** class X { [public|private]* foo() {} } */ + ScriptElementKind["memberFunctionElement"] = "method"; + /** class X { [public|private]* [get|set] foo:number; } */ + ScriptElementKind["memberGetAccessorElement"] = "getter"; + ScriptElementKind["memberSetAccessorElement"] = "setter"; + /** + * class X { [public|private]* foo:number; } + * interface Y { foo:number; } + */ + ScriptElementKind["memberVariableElement"] = "property"; + /** class X { constructor() { } } */ + ScriptElementKind["constructorImplementationElement"] = "constructor"; + /** interface Y { ():number; } */ + ScriptElementKind["callSignatureElement"] = "call"; + /** interface Y { []:number; } */ + ScriptElementKind["indexSignatureElement"] = "index"; + /** interface Y { new():Y; } */ + ScriptElementKind["constructSignatureElement"] = "construct"; + /** function foo(*Y*: string) */ + ScriptElementKind["parameterElement"] = "parameter"; + ScriptElementKind["typeParameterElement"] = "type parameter"; + ScriptElementKind["primitiveType"] = "primitive type"; + ScriptElementKind["label"] = "label"; + ScriptElementKind["alias"] = "alias"; + ScriptElementKind["constElement"] = "const"; + ScriptElementKind["letElement"] = "let"; + ScriptElementKind["directory"] = "directory"; + ScriptElementKind["externalModuleName"] = "external module name"; + /** + * + */ + ScriptElementKind["jsxAttribute"] = "JSX attribute"; + /** String literal */ + ScriptElementKind["string"] = "string"; + })(ScriptElementKind = ts.ScriptElementKind || (ts.ScriptElementKind = {})); + var ScriptElementKindModifier; + (function (ScriptElementKindModifier) { + ScriptElementKindModifier["none"] = ""; + ScriptElementKindModifier["publicMemberModifier"] = "public"; + ScriptElementKindModifier["privateMemberModifier"] = "private"; + ScriptElementKindModifier["protectedMemberModifier"] = "protected"; + ScriptElementKindModifier["exportedModifier"] = "export"; + ScriptElementKindModifier["ambientModifier"] = "declare"; + ScriptElementKindModifier["staticModifier"] = "static"; + ScriptElementKindModifier["abstractModifier"] = "abstract"; + ScriptElementKindModifier["optionalModifier"] = "optional"; + ScriptElementKindModifier["dtsModifier"] = ".d.ts"; + ScriptElementKindModifier["tsModifier"] = ".ts"; + ScriptElementKindModifier["tsxModifier"] = ".tsx"; + ScriptElementKindModifier["jsModifier"] = ".js"; + ScriptElementKindModifier["jsxModifier"] = ".jsx"; + ScriptElementKindModifier["jsonModifier"] = ".json"; + })(ScriptElementKindModifier = ts.ScriptElementKindModifier || (ts.ScriptElementKindModifier = {})); + var ClassificationTypeNames; + (function (ClassificationTypeNames) { + ClassificationTypeNames["comment"] = "comment"; + ClassificationTypeNames["identifier"] = "identifier"; + ClassificationTypeNames["keyword"] = "keyword"; + ClassificationTypeNames["numericLiteral"] = "number"; + ClassificationTypeNames["bigintLiteral"] = "bigint"; + ClassificationTypeNames["operator"] = "operator"; + ClassificationTypeNames["stringLiteral"] = "string"; + ClassificationTypeNames["whiteSpace"] = "whitespace"; + ClassificationTypeNames["text"] = "text"; + ClassificationTypeNames["punctuation"] = "punctuation"; + ClassificationTypeNames["className"] = "class name"; + ClassificationTypeNames["enumName"] = "enum name"; + ClassificationTypeNames["interfaceName"] = "interface name"; + ClassificationTypeNames["moduleName"] = "module name"; + ClassificationTypeNames["typeParameterName"] = "type parameter name"; + ClassificationTypeNames["typeAliasName"] = "type alias name"; + ClassificationTypeNames["parameterName"] = "parameter name"; + ClassificationTypeNames["docCommentTagName"] = "doc comment tag name"; + ClassificationTypeNames["jsxOpenTagName"] = "jsx open tag name"; + ClassificationTypeNames["jsxCloseTagName"] = "jsx close tag name"; + ClassificationTypeNames["jsxSelfClosingTagName"] = "jsx self closing tag name"; + ClassificationTypeNames["jsxAttribute"] = "jsx attribute"; + ClassificationTypeNames["jsxText"] = "jsx text"; + ClassificationTypeNames["jsxAttributeStringLiteralValue"] = "jsx attribute string literal value"; + })(ClassificationTypeNames = ts.ClassificationTypeNames || (ts.ClassificationTypeNames = {})); + var ClassificationType; + (function (ClassificationType) { + ClassificationType[ClassificationType["comment"] = 1] = "comment"; + ClassificationType[ClassificationType["identifier"] = 2] = "identifier"; + ClassificationType[ClassificationType["keyword"] = 3] = "keyword"; + ClassificationType[ClassificationType["numericLiteral"] = 4] = "numericLiteral"; + ClassificationType[ClassificationType["operator"] = 5] = "operator"; + ClassificationType[ClassificationType["stringLiteral"] = 6] = "stringLiteral"; + ClassificationType[ClassificationType["regularExpressionLiteral"] = 7] = "regularExpressionLiteral"; + ClassificationType[ClassificationType["whiteSpace"] = 8] = "whiteSpace"; + ClassificationType[ClassificationType["text"] = 9] = "text"; + ClassificationType[ClassificationType["punctuation"] = 10] = "punctuation"; + ClassificationType[ClassificationType["className"] = 11] = "className"; + ClassificationType[ClassificationType["enumName"] = 12] = "enumName"; + ClassificationType[ClassificationType["interfaceName"] = 13] = "interfaceName"; + ClassificationType[ClassificationType["moduleName"] = 14] = "moduleName"; + ClassificationType[ClassificationType["typeParameterName"] = 15] = "typeParameterName"; + ClassificationType[ClassificationType["typeAliasName"] = 16] = "typeAliasName"; + ClassificationType[ClassificationType["parameterName"] = 17] = "parameterName"; + ClassificationType[ClassificationType["docCommentTagName"] = 18] = "docCommentTagName"; + ClassificationType[ClassificationType["jsxOpenTagName"] = 19] = "jsxOpenTagName"; + ClassificationType[ClassificationType["jsxCloseTagName"] = 20] = "jsxCloseTagName"; + ClassificationType[ClassificationType["jsxSelfClosingTagName"] = 21] = "jsxSelfClosingTagName"; + ClassificationType[ClassificationType["jsxAttribute"] = 22] = "jsxAttribute"; + ClassificationType[ClassificationType["jsxText"] = 23] = "jsxText"; + ClassificationType[ClassificationType["jsxAttributeStringLiteralValue"] = 24] = "jsxAttributeStringLiteralValue"; + ClassificationType[ClassificationType["bigintLiteral"] = 25] = "bigintLiteral"; + })(ClassificationType = ts.ClassificationType || (ts.ClassificationType = {})); +})(ts || (ts = {})); +// These utilities are common to multiple language service features. +/* @internal */ +var ts; +(function (ts) { + ts.scanner = ts.createScanner(6 /* Latest */, /*skipTrivia*/ true); + var SemanticMeaning; + (function (SemanticMeaning) { + SemanticMeaning[SemanticMeaning["None"] = 0] = "None"; + SemanticMeaning[SemanticMeaning["Value"] = 1] = "Value"; + SemanticMeaning[SemanticMeaning["Type"] = 2] = "Type"; + SemanticMeaning[SemanticMeaning["Namespace"] = 4] = "Namespace"; + SemanticMeaning[SemanticMeaning["All"] = 7] = "All"; + })(SemanticMeaning = ts.SemanticMeaning || (ts.SemanticMeaning = {})); + function getMeaningFromDeclaration(node) { + switch (node.kind) { + case 237 /* VariableDeclaration */: + return ts.isInJSFile(node) && ts.getJSDocEnumTag(node) ? 7 /* All */ : 1 /* Value */; + case 151 /* Parameter */: + case 186 /* BindingElement */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 275 /* PropertyAssignment */: + case 276 /* ShorthandPropertyAssignment */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 274 /* CatchClause */: + case 267 /* JsxAttribute */: + return 1 /* Value */; + case 150 /* TypeParameter */: + case 241 /* InterfaceDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 168 /* TypeLiteral */: + return 2 /* Type */; + case 304 /* JSDocTypedefTag */: + // If it has no name node, it shares the name with the value declaration below it. + return node.name === undefined ? 1 /* Value */ | 2 /* Type */ : 2 /* Type */; + case 278 /* EnumMember */: + case 240 /* ClassDeclaration */: + return 1 /* Value */ | 2 /* Type */; + case 244 /* ModuleDeclaration */: + if (ts.isAmbientModule(node)) { + return 4 /* Namespace */ | 1 /* Value */; + } + else if (ts.getModuleInstanceState(node) === 1 /* Instantiated */) { + return 4 /* Namespace */ | 1 /* Value */; + } + else { + return 4 /* Namespace */; + } + case 243 /* EnumDeclaration */: + case 252 /* NamedImports */: + case 253 /* ImportSpecifier */: + case 248 /* ImportEqualsDeclaration */: + case 249 /* ImportDeclaration */: + case 254 /* ExportAssignment */: + case 255 /* ExportDeclaration */: + return 7 /* All */; + // An external module can be a Value + case 279 /* SourceFile */: + return 4 /* Namespace */ | 1 /* Value */; + } + return 7 /* All */; + } + ts.getMeaningFromDeclaration = getMeaningFromDeclaration; + function getMeaningFromLocation(node) { + if (node.kind === 279 /* SourceFile */) { + return 1 /* Value */; + } + else if (node.parent.kind === 254 /* ExportAssignment */ || node.parent.kind === 259 /* ExternalModuleReference */) { + return 7 /* All */; + } + else if (isInRightSideOfInternalImportEqualsDeclaration(node)) { + return getMeaningFromRightHandSideOfImportEquals(node); + } + else if (ts.isDeclarationName(node)) { + return getMeaningFromDeclaration(node.parent); + } + else if (isTypeReference(node)) { + return 2 /* Type */; + } + else if (isNamespaceReference(node)) { + return 4 /* Namespace */; + } + else if (ts.isTypeParameterDeclaration(node.parent)) { + ts.Debug.assert(ts.isJSDocTemplateTag(node.parent.parent)); // Else would be handled by isDeclarationName + return 2 /* Type */; + } + else if (ts.isLiteralTypeNode(node.parent)) { + // This might be T["name"], which is actually referencing a property and not a type. So allow both meanings. + return 2 /* Type */ | 1 /* Value */; + } + else { + return 1 /* Value */; + } + } + ts.getMeaningFromLocation = getMeaningFromLocation; + function getMeaningFromRightHandSideOfImportEquals(node) { + // import a = |b|; // Namespace + // import a = |b.c|; // Value, type, namespace + // import a = |b.c|.d; // Namespace + var name = node.kind === 148 /* QualifiedName */ ? node : ts.isQualifiedName(node.parent) && node.parent.right === node ? node.parent : undefined; + return name && name.parent.kind === 248 /* ImportEqualsDeclaration */ ? 7 /* All */ : 4 /* Namespace */; + } + function isInRightSideOfInternalImportEqualsDeclaration(node) { + while (node.parent.kind === 148 /* QualifiedName */) { + node = node.parent; + } + return ts.isInternalModuleImportEqualsDeclaration(node.parent) && node.parent.moduleReference === node; + } + ts.isInRightSideOfInternalImportEqualsDeclaration = isInRightSideOfInternalImportEqualsDeclaration; + function isNamespaceReference(node) { + return isQualifiedNameNamespaceReference(node) || isPropertyAccessNamespaceReference(node); + } + function isQualifiedNameNamespaceReference(node) { + var root = node; + var isLastClause = true; + if (root.parent.kind === 148 /* QualifiedName */) { + while (root.parent && root.parent.kind === 148 /* QualifiedName */) { + root = root.parent; + } + isLastClause = root.right === node; + } + return root.parent.kind === 164 /* TypeReference */ && !isLastClause; + } + function isPropertyAccessNamespaceReference(node) { + var root = node; + var isLastClause = true; + if (root.parent.kind === 189 /* PropertyAccessExpression */) { + while (root.parent && root.parent.kind === 189 /* PropertyAccessExpression */) { + root = root.parent; + } + isLastClause = root.name === node; + } + if (!isLastClause && root.parent.kind === 211 /* ExpressionWithTypeArguments */ && root.parent.parent.kind === 273 /* HeritageClause */) { + var decl = root.parent.parent.parent; + return (decl.kind === 240 /* ClassDeclaration */ && root.parent.parent.token === 109 /* ImplementsKeyword */) || + (decl.kind === 241 /* InterfaceDeclaration */ && root.parent.parent.token === 86 /* ExtendsKeyword */); + } + return false; + } + function isTypeReference(node) { + if (ts.isRightSideOfQualifiedNameOrPropertyAccess(node)) { + node = node.parent; + } + switch (node.kind) { + case 100 /* ThisKeyword */: + return !ts.isExpressionNode(node); + case 178 /* ThisType */: + return true; + } + switch (node.parent.kind) { + case 164 /* TypeReference */: + return true; + case 183 /* ImportType */: + return !node.parent.isTypeOf; + case 211 /* ExpressionWithTypeArguments */: + return !ts.isExpressionWithTypeArgumentsInClassExtendsClause(node.parent); + } + return false; + } + function isCallExpressionTarget(node) { + return isCallOrNewExpressionTargetWorker(node, ts.isCallExpression); + } + ts.isCallExpressionTarget = isCallExpressionTarget; + function isNewExpressionTarget(node) { + return isCallOrNewExpressionTargetWorker(node, ts.isNewExpression); + } + ts.isNewExpressionTarget = isNewExpressionTarget; + function isCallOrNewExpressionTarget(node) { + return isCallOrNewExpressionTargetWorker(node, ts.isCallOrNewExpression); + } + ts.isCallOrNewExpressionTarget = isCallOrNewExpressionTarget; + function isCallOrNewExpressionTargetWorker(node, pred) { + var target = climbPastPropertyAccess(node); + return !!target && !!target.parent && pred(target.parent) && target.parent.expression === target; + } + function climbPastPropertyAccess(node) { + return isRightSideOfPropertyAccess(node) ? node.parent : node; + } + ts.climbPastPropertyAccess = climbPastPropertyAccess; + function getTargetLabel(referenceNode, labelName) { + while (referenceNode) { + if (referenceNode.kind === 233 /* LabeledStatement */ && referenceNode.label.escapedText === labelName) { + return referenceNode.label; + } + referenceNode = referenceNode.parent; + } + return undefined; + } + ts.getTargetLabel = getTargetLabel; + function hasPropertyAccessExpressionWithName(node, funcName) { + if (!ts.isPropertyAccessExpression(node.expression)) { + return false; + } + return node.expression.name.text === funcName; + } + ts.hasPropertyAccessExpressionWithName = hasPropertyAccessExpressionWithName; + function isJumpStatementTarget(node) { + return node.kind === 72 /* Identifier */ && ts.isBreakOrContinueStatement(node.parent) && node.parent.label === node; + } + ts.isJumpStatementTarget = isJumpStatementTarget; + function isLabelOfLabeledStatement(node) { + return node.kind === 72 /* Identifier */ && ts.isLabeledStatement(node.parent) && node.parent.label === node; + } + ts.isLabelOfLabeledStatement = isLabelOfLabeledStatement; + function isLabelName(node) { + return isLabelOfLabeledStatement(node) || isJumpStatementTarget(node); + } + ts.isLabelName = isLabelName; + function isTagName(node) { + return ts.isJSDocTag(node.parent) && node.parent.tagName === node; + } + ts.isTagName = isTagName; + function isRightSideOfQualifiedName(node) { + return node.parent.kind === 148 /* QualifiedName */ && node.parent.right === node; + } + ts.isRightSideOfQualifiedName = isRightSideOfQualifiedName; + function isRightSideOfPropertyAccess(node) { + return node && node.parent && node.parent.kind === 189 /* PropertyAccessExpression */ && node.parent.name === node; + } + ts.isRightSideOfPropertyAccess = isRightSideOfPropertyAccess; + function isNameOfModuleDeclaration(node) { + return node.parent.kind === 244 /* ModuleDeclaration */ && node.parent.name === node; + } + ts.isNameOfModuleDeclaration = isNameOfModuleDeclaration; + function isNameOfFunctionDeclaration(node) { + return node.kind === 72 /* Identifier */ && + ts.isFunctionLike(node.parent) && node.parent.name === node; + } + ts.isNameOfFunctionDeclaration = isNameOfFunctionDeclaration; + function isLiteralNameOfPropertyDeclarationOrIndexAccess(node) { + switch (node.parent.kind) { + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 275 /* PropertyAssignment */: + case 278 /* EnumMember */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 244 /* ModuleDeclaration */: + return ts.getNameOfDeclaration(node.parent) === node; + case 190 /* ElementAccessExpression */: + return node.parent.argumentExpression === node; + case 149 /* ComputedPropertyName */: + return true; + case 182 /* LiteralType */: + return node.parent.parent.kind === 180 /* IndexedAccessType */; + default: + return false; + } + } + ts.isLiteralNameOfPropertyDeclarationOrIndexAccess = isLiteralNameOfPropertyDeclarationOrIndexAccess; + function isExpressionOfExternalModuleImportEqualsDeclaration(node) { + return ts.isExternalModuleImportEqualsDeclaration(node.parent.parent) && + ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node; + } + ts.isExpressionOfExternalModuleImportEqualsDeclaration = isExpressionOfExternalModuleImportEqualsDeclaration; + function getContainerNode(node) { + if (ts.isJSDocTypeAlias(node)) { + // This doesn't just apply to the node immediately under the comment, but to everything in its parent's scope. + // node.parent = the JSDoc comment, node.parent.parent = the node having the comment. + // Then we get parent again in the loop. + node = node.parent.parent; + } + while (true) { + node = node.parent; + if (!node) { + return undefined; + } + switch (node.kind) { + case 279 /* SourceFile */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + case 243 /* EnumDeclaration */: + case 244 /* ModuleDeclaration */: + return node; + } + } + } + ts.getContainerNode = getContainerNode; + function getNodeKind(node) { + switch (node.kind) { + case 279 /* SourceFile */: + return ts.isExternalModule(node) ? "module" /* moduleElement */ : "script" /* scriptElement */; + case 244 /* ModuleDeclaration */: + return "module" /* moduleElement */; + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + return "class" /* classElement */; + case 241 /* InterfaceDeclaration */: return "interface" /* interfaceElement */; + case 242 /* TypeAliasDeclaration */: + case 297 /* JSDocCallbackTag */: + case 304 /* JSDocTypedefTag */: + return "type" /* typeElement */; + case 243 /* EnumDeclaration */: return "enum" /* enumElement */; + case 237 /* VariableDeclaration */: + return getKindOfVariableDeclaration(node); + case 186 /* BindingElement */: + return getKindOfVariableDeclaration(ts.getRootDeclaration(node)); + case 197 /* ArrowFunction */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + return "function" /* functionElement */; + case 158 /* GetAccessor */: return "getter" /* memberGetAccessorElement */; + case 159 /* SetAccessor */: return "setter" /* memberSetAccessorElement */; + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + return "method" /* memberFunctionElement */; + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + return "property" /* memberVariableElement */; + case 162 /* IndexSignature */: return "index" /* indexSignatureElement */; + case 161 /* ConstructSignature */: return "construct" /* constructSignatureElement */; + case 160 /* CallSignature */: return "call" /* callSignatureElement */; + case 157 /* Constructor */: return "constructor" /* constructorImplementationElement */; + case 150 /* TypeParameter */: return "type parameter" /* typeParameterElement */; + case 278 /* EnumMember */: return "enum member" /* enumMemberElement */; + case 151 /* Parameter */: return ts.hasModifier(node, 92 /* ParameterPropertyModifier */) ? "property" /* memberVariableElement */ : "parameter" /* parameterElement */; + case 248 /* ImportEqualsDeclaration */: + case 253 /* ImportSpecifier */: + case 257 /* ExportSpecifier */: + case 251 /* NamespaceImport */: + return "alias" /* alias */; + case 204 /* BinaryExpression */: + var kind = ts.getAssignmentDeclarationKind(node); + var right = node.right; + switch (kind) { + case 7 /* ObjectDefinePropertyValue */: + case 8 /* ObjectDefinePropertyExports */: + case 9 /* ObjectDefinePrototypeProperty */: + case 0 /* None */: + return "" /* unknown */; + case 1 /* ExportsProperty */: + case 2 /* ModuleExports */: + var rightKind = getNodeKind(right); + return rightKind === "" /* unknown */ ? "const" /* constElement */ : rightKind; + case 3 /* PrototypeProperty */: + return ts.isFunctionExpression(right) ? "method" /* memberFunctionElement */ : "property" /* memberVariableElement */; + case 4 /* ThisProperty */: + return "property" /* memberVariableElement */; // property + case 5 /* Property */: + // static method / property + return ts.isFunctionExpression(right) ? "method" /* memberFunctionElement */ : "property" /* memberVariableElement */; + case 6 /* Prototype */: + return "local class" /* localClassElement */; + default: { + ts.assertType(kind); + return "" /* unknown */; + } + } + case 72 /* Identifier */: + return ts.isImportClause(node.parent) ? "alias" /* alias */ : "" /* unknown */; + default: + return "" /* unknown */; + } + function getKindOfVariableDeclaration(v) { + return ts.isVarConst(v) + ? "const" /* constElement */ + : ts.isLet(v) + ? "let" /* letElement */ + : "var" /* variableElement */; + } + } + ts.getNodeKind = getNodeKind; + function isThis(node) { + switch (node.kind) { + case 100 /* ThisKeyword */: + // case SyntaxKind.ThisType: TODO: GH#9267 + return true; + case 72 /* Identifier */: + // 'this' as a parameter + return ts.identifierIsThisKeyword(node) && node.parent.kind === 151 /* Parameter */; + default: + return false; + } + } + ts.isThis = isThis; + // Matches the beginning of a triple slash directive + var tripleSlashDirectivePrefixRegex = /^\/\/\/\s*= range.end; + } + ts.startEndContainsRange = startEndContainsRange; + function rangeContainsStartEnd(range, start, end) { + return range.pos <= start && range.end >= end; + } + ts.rangeContainsStartEnd = rangeContainsStartEnd; + function rangeOverlapsWithStartEnd(r1, start, end) { + return startEndOverlapsWithStartEnd(r1.pos, r1.end, start, end); + } + ts.rangeOverlapsWithStartEnd = rangeOverlapsWithStartEnd; + function nodeOverlapsWithStartEnd(node, sourceFile, start, end) { + return startEndOverlapsWithStartEnd(node.getStart(sourceFile), node.end, start, end); + } + ts.nodeOverlapsWithStartEnd = nodeOverlapsWithStartEnd; + function startEndOverlapsWithStartEnd(start1, end1, start2, end2) { + var start = Math.max(start1, start2); + var end = Math.min(end1, end2); + return start < end; + } + ts.startEndOverlapsWithStartEnd = startEndOverlapsWithStartEnd; + /** + * Assumes `candidate.start <= position` holds. + */ + function positionBelongsToNode(candidate, position, sourceFile) { + ts.Debug.assert(candidate.pos <= position); + return position < candidate.end || !isCompletedNode(candidate, sourceFile); + } + ts.positionBelongsToNode = positionBelongsToNode; + function isCompletedNode(n, sourceFile) { + if (n === undefined || ts.nodeIsMissing(n)) { + return false; + } + switch (n.kind) { + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + case 243 /* EnumDeclaration */: + case 188 /* ObjectLiteralExpression */: + case 184 /* ObjectBindingPattern */: + case 168 /* TypeLiteral */: + case 218 /* Block */: + case 245 /* ModuleBlock */: + case 246 /* CaseBlock */: + case 252 /* NamedImports */: + case 256 /* NamedExports */: + return nodeEndsWith(n, 19 /* CloseBraceToken */, sourceFile); + case 274 /* CatchClause */: + return isCompletedNode(n.block, sourceFile); + case 192 /* NewExpression */: + if (!n.arguments) { + return true; + } + // falls through + case 191 /* CallExpression */: + case 195 /* ParenthesizedExpression */: + case 177 /* ParenthesizedType */: + return nodeEndsWith(n, 21 /* CloseParenToken */, sourceFile); + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + return isCompletedNode(n.type, sourceFile); + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 161 /* ConstructSignature */: + case 160 /* CallSignature */: + case 197 /* ArrowFunction */: + if (n.body) { + return isCompletedNode(n.body, sourceFile); + } + if (n.type) { + return isCompletedNode(n.type, sourceFile); + } + // Even though type parameters can be unclosed, we can get away with + // having at least a closing paren. + return hasChildOfKind(n, 21 /* CloseParenToken */, sourceFile); + case 244 /* ModuleDeclaration */: + return !!n.body && isCompletedNode(n.body, sourceFile); + case 222 /* IfStatement */: + if (n.elseStatement) { + return isCompletedNode(n.elseStatement, sourceFile); + } + return isCompletedNode(n.thenStatement, sourceFile); + case 221 /* ExpressionStatement */: + return isCompletedNode(n.expression, sourceFile) || + hasChildOfKind(n, 26 /* SemicolonToken */, sourceFile); + case 187 /* ArrayLiteralExpression */: + case 185 /* ArrayBindingPattern */: + case 190 /* ElementAccessExpression */: + case 149 /* ComputedPropertyName */: + case 170 /* TupleType */: + return nodeEndsWith(n, 23 /* CloseBracketToken */, sourceFile); + case 162 /* IndexSignature */: + if (n.type) { + return isCompletedNode(n.type, sourceFile); + } + return hasChildOfKind(n, 23 /* CloseBracketToken */, sourceFile); + case 271 /* CaseClause */: + case 272 /* DefaultClause */: + // there is no such thing as terminator token for CaseClause/DefaultClause so for simplicity always consider them non-completed + return false; + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + case 224 /* WhileStatement */: + return isCompletedNode(n.statement, sourceFile); + case 223 /* DoStatement */: + // rough approximation: if DoStatement has While keyword - then if node is completed is checking the presence of ')'; + return hasChildOfKind(n, 107 /* WhileKeyword */, sourceFile) + ? nodeEndsWith(n, 21 /* CloseParenToken */, sourceFile) + : isCompletedNode(n.statement, sourceFile); + case 167 /* TypeQuery */: + return isCompletedNode(n.exprName, sourceFile); + case 199 /* TypeOfExpression */: + case 198 /* DeleteExpression */: + case 200 /* VoidExpression */: + case 207 /* YieldExpression */: + case 208 /* SpreadElement */: + var unaryWordExpression = n; + return isCompletedNode(unaryWordExpression.expression, sourceFile); + case 193 /* TaggedTemplateExpression */: + return isCompletedNode(n.template, sourceFile); + case 206 /* TemplateExpression */: + var lastSpan = ts.lastOrUndefined(n.templateSpans); + return isCompletedNode(lastSpan, sourceFile); + case 216 /* TemplateSpan */: + return ts.nodeIsPresent(n.literal); + case 255 /* ExportDeclaration */: + case 249 /* ImportDeclaration */: + return ts.nodeIsPresent(n.moduleSpecifier); + case 202 /* PrefixUnaryExpression */: + return isCompletedNode(n.operand, sourceFile); + case 204 /* BinaryExpression */: + return isCompletedNode(n.right, sourceFile); + case 205 /* ConditionalExpression */: + return isCompletedNode(n.whenFalse, sourceFile); + default: + return true; + } + } + /* + * Checks if node ends with 'expectedLastToken'. + * If child at position 'length - 1' is 'SemicolonToken' it is skipped and 'expectedLastToken' is compared with child at position 'length - 2'. + */ + function nodeEndsWith(n, expectedLastToken, sourceFile) { + var children = n.getChildren(sourceFile); + if (children.length) { + var lastChild = ts.last(children); + if (lastChild.kind === expectedLastToken) { + return true; + } + else if (lastChild.kind === 26 /* SemicolonToken */ && children.length !== 1) { + return children[children.length - 2].kind === expectedLastToken; + } + } + return false; + } + function findListItemInfo(node) { + var list = findContainingList(node); + // It is possible at this point for syntaxList to be undefined, either if + // node.parent had no list child, or if none of its list children contained + // the span of node. If this happens, return undefined. The caller should + // handle this case. + if (!list) { + return undefined; + } + var children = list.getChildren(); + var listItemIndex = ts.indexOfNode(children, node); + return { + listItemIndex: listItemIndex, + list: list + }; + } + ts.findListItemInfo = findListItemInfo; + function hasChildOfKind(n, kind, sourceFile) { + return !!findChildOfKind(n, kind, sourceFile); + } + ts.hasChildOfKind = hasChildOfKind; + function findChildOfKind(n, kind, sourceFile) { + return ts.find(n.getChildren(sourceFile), function (c) { return c.kind === kind; }); + } + ts.findChildOfKind = findChildOfKind; + function findContainingList(node) { + // The node might be a list element (nonsynthetic) or a comma (synthetic). Either way, it will + // be parented by the container of the SyntaxList, not the SyntaxList itself. + // In order to find the list item index, we first need to locate SyntaxList itself and then search + // for the position of the relevant node (or comma). + var syntaxList = ts.find(node.parent.getChildren(), function (c) { return ts.isSyntaxList(c) && rangeContainsRange(c, node); }); + // Either we didn't find an appropriate list, or the list must contain us. + ts.Debug.assert(!syntaxList || ts.contains(syntaxList.getChildren(), node)); + return syntaxList; + } + ts.findContainingList = findContainingList; + /** + * Gets the token whose text has range [start, end) and + * position >= start and (position < end or (position === end && token is literal or keyword or identifier)) + */ + function getTouchingPropertyName(sourceFile, position) { + return getTouchingToken(sourceFile, position, function (n) { return ts.isPropertyNameLiteral(n) || ts.isKeyword(n.kind); }); + } + ts.getTouchingPropertyName = getTouchingPropertyName; + /** + * Returns the token if position is in [start, end). + * If position === end, returns the preceding token if includeItemAtEndPosition(previousToken) === true + */ + function getTouchingToken(sourceFile, position, includePrecedingTokenAtEndPosition) { + return getTokenAtPositionWorker(sourceFile, position, /*allowPositionInLeadingTrivia*/ false, includePrecedingTokenAtEndPosition, /*includeEndPosition*/ false); + } + ts.getTouchingToken = getTouchingToken; + /** Returns a token if position is in [start-of-leading-trivia, end) */ + function getTokenAtPosition(sourceFile, position) { + return getTokenAtPositionWorker(sourceFile, position, /*allowPositionInLeadingTrivia*/ true, /*includePrecedingTokenAtEndPosition*/ undefined, /*includeEndPosition*/ false); + } + ts.getTokenAtPosition = getTokenAtPosition; + /** Get the token whose text contains the position */ + function getTokenAtPositionWorker(sourceFile, position, allowPositionInLeadingTrivia, includePrecedingTokenAtEndPosition, includeEndPosition) { + var current = sourceFile; + outer: while (true) { + // find the child that contains 'position' + for (var _i = 0, _a = current.getChildren(sourceFile); _i < _a.length; _i++) { + var child = _a[_i]; + var start = allowPositionInLeadingTrivia ? child.getFullStart() : child.getStart(sourceFile, /*includeJsDoc*/ true); + if (start > position) { + // If this child begins after position, then all subsequent children will as well. + break; + } + var end = child.getEnd(); + if (position < end || (position === end && (child.kind === 1 /* EndOfFileToken */ || includeEndPosition))) { + current = child; + continue outer; + } + else if (includePrecedingTokenAtEndPosition && end === position) { + var previousToken = findPrecedingToken(position, sourceFile, child); + if (previousToken && includePrecedingTokenAtEndPosition(previousToken)) { + return previousToken; + } + } + } + return current; + } + } + /** + * The token on the left of the position is the token that strictly includes the position + * or sits to the left of the cursor if it is on a boundary. For example + * + * fo|o -> will return foo + * foo |bar -> will return foo + * + */ + function findTokenOnLeftOfPosition(file, position) { + // Ideally, getTokenAtPosition should return a token. However, it is currently + // broken, so we do a check to make sure the result was indeed a token. + var tokenAtPosition = getTokenAtPosition(file, position); + if (ts.isToken(tokenAtPosition) && position > tokenAtPosition.getStart(file) && position < tokenAtPosition.getEnd()) { + return tokenAtPosition; + } + return findPrecedingToken(position, file); + } + ts.findTokenOnLeftOfPosition = findTokenOnLeftOfPosition; + function findNextToken(previousToken, parent, sourceFile) { + return find(parent); + function find(n) { + if (ts.isToken(n) && n.pos === previousToken.end) { + // this is token that starts at the end of previous token - return it + return n; + } + return ts.firstDefined(n.getChildren(), function (child) { + var shouldDiveInChildNode = + // previous token is enclosed somewhere in the child + (child.pos <= previousToken.pos && child.end > previousToken.end) || + // previous token ends exactly at the beginning of child + (child.pos === previousToken.end); + return shouldDiveInChildNode && nodeHasTokens(child, sourceFile) ? find(child) : undefined; + }); + } + } + ts.findNextToken = findNextToken; + /** + * Finds the rightmost token satisfying `token.end <= position`, + * excluding `JsxText` tokens containing only whitespace. + */ + function findPrecedingToken(position, sourceFile, startNode, excludeJsdoc) { + var result = find(startNode || sourceFile); + ts.Debug.assert(!(result && isWhiteSpaceOnlyJsxText(result))); + return result; + function find(n) { + if (isNonWhitespaceToken(n) && n.kind !== 1 /* EndOfFileToken */) { + return n; + } + var children = n.getChildren(sourceFile); + for (var i = 0; i < children.length; i++) { + var child = children[i]; + // Note that the span of a node's tokens is [node.getStart(...), node.end). + // Given that `position < child.end` and child has constituent tokens, we distinguish these cases: + // 1) `position` precedes `child`'s tokens or `child` has no tokens (ie: in a comment or whitespace preceding `child`): + // we need to find the last token in a previous child. + // 2) `position` is within the same span: we recurse on `child`. + if (position < child.end) { + var start = child.getStart(sourceFile, /*includeJsDoc*/ !excludeJsdoc); + var lookInPreviousChild = (start >= position) || // cursor in the leading trivia + !nodeHasTokens(child, sourceFile) || + isWhiteSpaceOnlyJsxText(child); + if (lookInPreviousChild) { + // actual start of the node is past the position - previous token should be at the end of previous child + var candidate_2 = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ i, sourceFile); + return candidate_2 && findRightmostToken(candidate_2, sourceFile); + } + else { + // candidate should be in this node + return find(child); + } + } + } + ts.Debug.assert(startNode !== undefined || n.kind === 279 /* SourceFile */ || n.kind === 1 /* EndOfFileToken */ || ts.isJSDocCommentContainingNode(n)); + // Here we know that none of child token nodes embrace the position, + // the only known case is when position is at the end of the file. + // Try to find the rightmost token in the file without filtering. + // Namely we are skipping the check: 'position < node.end' + var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ children.length, sourceFile); + return candidate && findRightmostToken(candidate, sourceFile); + } + } + ts.findPrecedingToken = findPrecedingToken; + function isNonWhitespaceToken(n) { + return ts.isToken(n) && !isWhiteSpaceOnlyJsxText(n); + } + function findRightmostToken(n, sourceFile) { + if (isNonWhitespaceToken(n)) { + return n; + } + var children = n.getChildren(sourceFile); + var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ children.length, sourceFile); + return candidate && findRightmostToken(candidate, sourceFile); + } + /** + * Finds the rightmost child to the left of `children[exclusiveStartPosition]` which is a non-all-whitespace token or has constituent tokens. + */ + function findRightmostChildNodeWithTokens(children, exclusiveStartPosition, sourceFile) { + for (var i = exclusiveStartPosition - 1; i >= 0; i--) { + var child = children[i]; + if (isWhiteSpaceOnlyJsxText(child)) { + ts.Debug.assert(i > 0, "`JsxText` tokens should not be the first child of `JsxElement | JsxSelfClosingElement`"); + } + else if (nodeHasTokens(children[i], sourceFile)) { + return children[i]; + } + } + } + function isInString(sourceFile, position, previousToken) { + if (previousToken === void 0) { previousToken = findPrecedingToken(position, sourceFile); } + if (previousToken && ts.isStringTextContainingNode(previousToken)) { + var start = previousToken.getStart(sourceFile); + var end = previousToken.getEnd(); + // To be "in" one of these literals, the position has to be: + // 1. entirely within the token text. + // 2. at the end position of an unterminated token. + // 3. at the end of a regular expression (due to trailing flags like '/foo/g'). + if (start < position && position < end) { + return true; + } + if (position === end) { + return !!previousToken.isUnterminated; + } + } + return false; + } + ts.isInString = isInString; + /** + * returns true if the position is in between the open and close elements of an JSX expression. + */ + function isInsideJsxElementOrAttribute(sourceFile, position) { + var token = getTokenAtPosition(sourceFile, position); + if (!token) { + return false; + } + if (token.kind === 11 /* JsxText */) { + return true; + } + //
      Hello |
      + if (token.kind === 28 /* LessThanToken */ && token.parent.kind === 11 /* JsxText */) { + return true; + } + //
      { |
      or
      + if (token.kind === 28 /* LessThanToken */ && token.parent.kind === 270 /* JsxExpression */) { + return true; + } + //
      { + // | + // } < /div> + if (token && token.kind === 19 /* CloseBraceToken */ && token.parent.kind === 270 /* JsxExpression */) { + return true; + } + //
      |
      + if (token.kind === 28 /* LessThanToken */ && token.parent.kind === 263 /* JsxClosingElement */) { + return true; + } + return false; + } + ts.isInsideJsxElementOrAttribute = isInsideJsxElementOrAttribute; + function isWhiteSpaceOnlyJsxText(node) { + return ts.isJsxText(node) && node.containsOnlyWhiteSpaces; + } + function isInTemplateString(sourceFile, position) { + var token = getTokenAtPosition(sourceFile, position); + return ts.isTemplateLiteralKind(token.kind) && position > token.getStart(sourceFile); + } + ts.isInTemplateString = isInTemplateString; + function isInJSXText(sourceFile, position) { + var token = getTokenAtPosition(sourceFile, position); + if (ts.isJsxText(token)) { + return true; + } + if (token.kind === 18 /* OpenBraceToken */ && ts.isJsxExpression(token.parent) && ts.isJsxElement(token.parent.parent)) { + return true; + } + if (token.kind === 28 /* LessThanToken */ && ts.isJsxOpeningLikeElement(token.parent) && ts.isJsxElement(token.parent.parent)) { + return true; + } + return false; + } + ts.isInJSXText = isInJSXText; + function findPrecedingMatchingToken(token, matchingTokenKind, sourceFile) { + var tokenKind = token.kind; + var remainingMatchingTokens = 0; + while (true) { + var preceding = findPrecedingToken(token.getFullStart(), sourceFile); + if (!preceding) { + return undefined; + } + token = preceding; + if (token.kind === matchingTokenKind) { + if (remainingMatchingTokens === 0) { + return token; + } + remainingMatchingTokens--; + } + else if (token.kind === tokenKind) { + remainingMatchingTokens++; + } + } + } + ts.findPrecedingMatchingToken = findPrecedingMatchingToken; + function isPossiblyTypeArgumentPosition(token, sourceFile, checker) { + var info = getPossibleTypeArgumentsInfo(token, sourceFile); + return info !== undefined && (ts.isPartOfTypeNode(info.called) || + getPossibleGenericSignatures(info.called, info.nTypeArguments, checker).length !== 0 || + isPossiblyTypeArgumentPosition(info.called, sourceFile, checker)); + } + ts.isPossiblyTypeArgumentPosition = isPossiblyTypeArgumentPosition; + function getPossibleGenericSignatures(called, typeArgumentCount, checker) { + var type = checker.getTypeAtLocation(called); + var signatures = ts.isNewExpression(called.parent) ? type.getConstructSignatures() : type.getCallSignatures(); + return signatures.filter(function (candidate) { return !!candidate.typeParameters && candidate.typeParameters.length >= typeArgumentCount; }); + } + ts.getPossibleGenericSignatures = getPossibleGenericSignatures; + // Get info for an expression like `f <` that may be the start of type arguments. + function getPossibleTypeArgumentsInfo(tokenIn, sourceFile) { + var token = tokenIn; + // This function determines if the node could be type argument position + // Since during editing, when type argument list is not complete, + // the tree could be of any shape depending on the tokens parsed before current node, + // scanning of the previous identifier followed by "<" before current node would give us better result + // Note that we also balance out the already provided type arguments, arrays, object literals while doing so + var remainingLessThanTokens = 0; + var nTypeArguments = 0; + while (token) { + switch (token.kind) { + case 28 /* LessThanToken */: + // Found the beginning of the generic argument expression + token = findPrecedingToken(token.getFullStart(), sourceFile); + if (!token || !ts.isIdentifier(token)) + return undefined; + if (!remainingLessThanTokens) { + return ts.isDeclarationName(token) ? undefined : { called: token, nTypeArguments: nTypeArguments }; + } + remainingLessThanTokens--; + break; + case 48 /* GreaterThanGreaterThanGreaterThanToken */: + remainingLessThanTokens = +3; + break; + case 47 /* GreaterThanGreaterThanToken */: + remainingLessThanTokens = +2; + break; + case 30 /* GreaterThanToken */: + remainingLessThanTokens++; + break; + case 19 /* CloseBraceToken */: + // This can be object type, skip until we find the matching open brace token + // Skip until the matching open brace token + token = findPrecedingMatchingToken(token, 18 /* OpenBraceToken */, sourceFile); + if (!token) + return undefined; + break; + case 21 /* CloseParenToken */: + // This can be object type, skip until we find the matching open brace token + // Skip until the matching open brace token + token = findPrecedingMatchingToken(token, 20 /* OpenParenToken */, sourceFile); + if (!token) + return undefined; + break; + case 23 /* CloseBracketToken */: + // This can be object type, skip until we find the matching open brace token + // Skip until the matching open brace token + token = findPrecedingMatchingToken(token, 22 /* OpenBracketToken */, sourceFile); + if (!token) + return undefined; + break; + // Valid tokens in a type name. Skip. + case 27 /* CommaToken */: + nTypeArguments++; + break; + case 37 /* EqualsGreaterThanToken */: + case 72 /* Identifier */: + case 10 /* StringLiteral */: + case 8 /* NumericLiteral */: + case 9 /* BigIntLiteral */: + case 102 /* TrueKeyword */: + case 87 /* FalseKeyword */: + case 104 /* TypeOfKeyword */: + case 86 /* ExtendsKeyword */: + case 129 /* KeyOfKeyword */: + case 24 /* DotToken */: + case 50 /* BarToken */: + case 56 /* QuestionToken */: + case 57 /* ColonToken */: + break; + default: + if (ts.isTypeNode(token)) { + break; + } + // Invalid token in type + return undefined; + } + token = findPrecedingToken(token.getFullStart(), sourceFile); + } + return undefined; + } + ts.getPossibleTypeArgumentsInfo = getPossibleTypeArgumentsInfo; + /** + * Returns true if the cursor at position in sourceFile is within a comment. + * + * @param tokenAtPosition Must equal `getTokenAtPosition(sourceFile, position) + * @param predicate Additional predicate to test on the comment range. + */ + function isInComment(sourceFile, position, tokenAtPosition) { + return ts.formatting.getRangeOfEnclosingComment(sourceFile, position, /*precedingToken*/ undefined, tokenAtPosition); + } + ts.isInComment = isInComment; + function hasDocComment(sourceFile, position) { + var token = getTokenAtPosition(sourceFile, position); + return !!ts.findAncestor(token, ts.isJSDoc); + } + ts.hasDocComment = hasDocComment; + function nodeHasTokens(n, sourceFile) { + // If we have a token or node that has a non-zero width, it must have tokens. + // Note: getWidth() does not take trivia into account. + return n.kind === 1 /* EndOfFileToken */ ? !!n.jsDoc : n.getWidth(sourceFile) !== 0; + } + function getNodeModifiers(node) { + var flags = ts.isDeclaration(node) ? ts.getCombinedModifierFlags(node) : 0 /* None */; + var result = []; + if (flags & 8 /* Private */) + result.push("private" /* privateMemberModifier */); + if (flags & 16 /* Protected */) + result.push("protected" /* protectedMemberModifier */); + if (flags & 4 /* Public */) + result.push("public" /* publicMemberModifier */); + if (flags & 32 /* Static */) + result.push("static" /* staticModifier */); + if (flags & 128 /* Abstract */) + result.push("abstract" /* abstractModifier */); + if (flags & 1 /* Export */) + result.push("export" /* exportedModifier */); + if (node.flags & 4194304 /* Ambient */) + result.push("declare" /* ambientModifier */); + return result.length > 0 ? result.join(",") : "" /* none */; + } + ts.getNodeModifiers = getNodeModifiers; + function getTypeArgumentOrTypeParameterList(node) { + if (node.kind === 164 /* TypeReference */ || node.kind === 191 /* CallExpression */) { + return node.typeArguments; + } + if (ts.isFunctionLike(node) || node.kind === 240 /* ClassDeclaration */ || node.kind === 241 /* InterfaceDeclaration */) { + return node.typeParameters; + } + return undefined; + } + ts.getTypeArgumentOrTypeParameterList = getTypeArgumentOrTypeParameterList; + function isComment(kind) { + return kind === 2 /* SingleLineCommentTrivia */ || kind === 3 /* MultiLineCommentTrivia */; + } + ts.isComment = isComment; + function isStringOrRegularExpressionOrTemplateLiteral(kind) { + if (kind === 10 /* StringLiteral */ + || kind === 13 /* RegularExpressionLiteral */ + || ts.isTemplateLiteralKind(kind)) { + return true; + } + return false; + } + ts.isStringOrRegularExpressionOrTemplateLiteral = isStringOrRegularExpressionOrTemplateLiteral; + function isPunctuation(kind) { + return 18 /* FirstPunctuation */ <= kind && kind <= 71 /* LastPunctuation */; + } + ts.isPunctuation = isPunctuation; + function isInsideTemplateLiteral(node, position, sourceFile) { + return ts.isTemplateLiteralKind(node.kind) + && (node.getStart(sourceFile) < position && position < node.end) || (!!node.isUnterminated && position === node.end); + } + ts.isInsideTemplateLiteral = isInsideTemplateLiteral; + function isAccessibilityModifier(kind) { + switch (kind) { + case 115 /* PublicKeyword */: + case 113 /* PrivateKeyword */: + case 114 /* ProtectedKeyword */: + return true; + } + return false; + } + ts.isAccessibilityModifier = isAccessibilityModifier; + function cloneCompilerOptions(options) { + var result = ts.clone(options); + ts.setConfigFileInOptions(result, options && options.configFile); + return result; + } + ts.cloneCompilerOptions = cloneCompilerOptions; + function isArrayLiteralOrObjectLiteralDestructuringPattern(node) { + if (node.kind === 187 /* ArrayLiteralExpression */ || + node.kind === 188 /* ObjectLiteralExpression */) { + // [a,b,c] from: + // [a, b, c] = someExpression; + if (node.parent.kind === 204 /* BinaryExpression */ && + node.parent.left === node && + node.parent.operatorToken.kind === 59 /* EqualsToken */) { + return true; + } + // [a, b, c] from: + // for([a, b, c] of expression) + if (node.parent.kind === 227 /* ForOfStatement */ && + node.parent.initializer === node) { + return true; + } + // [a, b, c] of + // [x, [a, b, c] ] = someExpression + // or + // {x, a: {a, b, c} } = someExpression + if (isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent.kind === 275 /* PropertyAssignment */ ? node.parent.parent : node.parent)) { + return true; + } + } + return false; + } + ts.isArrayLiteralOrObjectLiteralDestructuringPattern = isArrayLiteralOrObjectLiteralDestructuringPattern; + function isInReferenceComment(sourceFile, position) { + return isInReferenceCommentWorker(sourceFile, position, /*shouldBeReference*/ true); + } + ts.isInReferenceComment = isInReferenceComment; + function isInNonReferenceComment(sourceFile, position) { + return isInReferenceCommentWorker(sourceFile, position, /*shouldBeReference*/ false); + } + ts.isInNonReferenceComment = isInNonReferenceComment; + function isInReferenceCommentWorker(sourceFile, position, shouldBeReference) { + var range = isInComment(sourceFile, position, /*tokenAtPosition*/ undefined); + return !!range && shouldBeReference === tripleSlashDirectivePrefixRegex.test(sourceFile.text.substring(range.pos, range.end)); + } + function createTextSpanFromNode(node, sourceFile) { + return ts.createTextSpanFromBounds(node.getStart(sourceFile), node.getEnd()); + } + ts.createTextSpanFromNode = createTextSpanFromNode; + function createTextRangeFromNode(node, sourceFile) { + return ts.createRange(node.getStart(sourceFile), node.end); + } + ts.createTextRangeFromNode = createTextRangeFromNode; + function createTextSpanFromRange(range) { + return ts.createTextSpanFromBounds(range.pos, range.end); + } + ts.createTextSpanFromRange = createTextSpanFromRange; + function createTextRangeFromSpan(span) { + return ts.createRange(span.start, span.start + span.length); + } + ts.createTextRangeFromSpan = createTextRangeFromSpan; + function createTextChangeFromStartLength(start, length, newText) { + return createTextChange(ts.createTextSpan(start, length), newText); + } + ts.createTextChangeFromStartLength = createTextChangeFromStartLength; + function createTextChange(span, newText) { + return { span: span, newText: newText }; + } + ts.createTextChange = createTextChange; + ts.typeKeywords = [ + 120 /* AnyKeyword */, + 146 /* BigIntKeyword */, + 123 /* BooleanKeyword */, + 87 /* FalseKeyword */, + 129 /* KeyOfKeyword */, + 132 /* NeverKeyword */, + 96 /* NullKeyword */, + 135 /* NumberKeyword */, + 136 /* ObjectKeyword */, + 138 /* StringKeyword */, + 139 /* SymbolKeyword */, + 102 /* TrueKeyword */, + 106 /* VoidKeyword */, + 141 /* UndefinedKeyword */, + 142 /* UniqueKeyword */, + 143 /* UnknownKeyword */, + ]; + function isTypeKeyword(kind) { + return ts.contains(ts.typeKeywords, kind); + } + ts.isTypeKeyword = isTypeKeyword; + /** True if the symbol is for an external module, as opposed to a namespace. */ + function isExternalModuleSymbol(moduleSymbol) { + return !!(moduleSymbol.flags & 1536 /* Module */) && moduleSymbol.name.charCodeAt(0) === 34 /* doubleQuote */; + } + ts.isExternalModuleSymbol = isExternalModuleSymbol; + function nodeSeenTracker() { + var seen = []; + return function (node) { + var id = ts.getNodeId(node); + return !seen[id] && (seen[id] = true); + }; + } + ts.nodeSeenTracker = nodeSeenTracker; + function getSnapshotText(snap) { + return snap.getText(0, snap.getLength()); + } + ts.getSnapshotText = getSnapshotText; + function repeatString(str, count) { + var result = ""; + for (var i = 0; i < count; i++) { + result += str; + } + return result; + } + ts.repeatString = repeatString; + function skipConstraint(type) { + return type.isTypeParameter() ? type.getConstraint() || type : type; + } + ts.skipConstraint = skipConstraint; + function getNameFromPropertyName(name) { + return name.kind === 149 /* ComputedPropertyName */ + // treat computed property names where expression is string/numeric literal as just string/numeric literal + ? ts.isStringOrNumericLiteralLike(name.expression) ? name.expression.text : undefined + : ts.getTextOfIdentifierOrLiteral(name); + } + ts.getNameFromPropertyName = getNameFromPropertyName; + function programContainsEs6Modules(program) { + return program.getSourceFiles().some(function (s) { return !s.isDeclarationFile && !program.isSourceFileFromExternalLibrary(s) && !!s.externalModuleIndicator; }); + } + ts.programContainsEs6Modules = programContainsEs6Modules; + function compilerOptionsIndicateEs6Modules(compilerOptions) { + return !!compilerOptions.module || compilerOptions.target >= 2 /* ES2015 */ || !!compilerOptions.noEmit; + } + ts.compilerOptionsIndicateEs6Modules = compilerOptionsIndicateEs6Modules; + function hostUsesCaseSensitiveFileNames(host) { + return host.useCaseSensitiveFileNames ? host.useCaseSensitiveFileNames() : false; + } + ts.hostUsesCaseSensitiveFileNames = hostUsesCaseSensitiveFileNames; + function hostGetCanonicalFileName(host) { + return ts.createGetCanonicalFileName(hostUsesCaseSensitiveFileNames(host)); + } + ts.hostGetCanonicalFileName = hostGetCanonicalFileName; + function makeImportIfNecessary(defaultImport, namedImports, moduleSpecifier, quotePreference) { + return defaultImport || namedImports && namedImports.length ? makeImport(defaultImport, namedImports, moduleSpecifier, quotePreference) : undefined; + } + ts.makeImportIfNecessary = makeImportIfNecessary; + function makeImport(defaultImport, namedImports, moduleSpecifier, quotePreference) { + return ts.createImportDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, defaultImport || namedImports + ? ts.createImportClause(defaultImport, namedImports && namedImports.length ? ts.createNamedImports(namedImports) : undefined) + : undefined, typeof moduleSpecifier === "string" ? makeStringLiteral(moduleSpecifier, quotePreference) : moduleSpecifier); + } + ts.makeImport = makeImport; + function makeStringLiteral(text, quotePreference) { + return ts.createLiteral(text, quotePreference === 0 /* Single */); + } + ts.makeStringLiteral = makeStringLiteral; + var QuotePreference; + (function (QuotePreference) { + QuotePreference[QuotePreference["Single"] = 0] = "Single"; + QuotePreference[QuotePreference["Double"] = 1] = "Double"; + })(QuotePreference = ts.QuotePreference || (ts.QuotePreference = {})); + function quotePreferenceFromString(str, sourceFile) { + return ts.isStringDoubleQuoted(str, sourceFile) ? 1 /* Double */ : 0 /* Single */; + } + ts.quotePreferenceFromString = quotePreferenceFromString; + function getQuotePreference(sourceFile, preferences) { + if (preferences.quotePreference) { + return preferences.quotePreference === "single" ? 0 /* Single */ : 1 /* Double */; + } + else { + var firstModuleSpecifier = sourceFile.imports && ts.find(sourceFile.imports, ts.isStringLiteral); + return firstModuleSpecifier ? quotePreferenceFromString(firstModuleSpecifier, sourceFile) : 1 /* Double */; + } + } + ts.getQuotePreference = getQuotePreference; + function getQuoteFromPreference(qp) { + switch (qp) { + case 0 /* Single */: return "'"; + case 1 /* Double */: return '"'; + default: return ts.Debug.assertNever(qp); + } + } + ts.getQuoteFromPreference = getQuoteFromPreference; + function symbolNameNoDefault(symbol) { + var escaped = symbolEscapedNameNoDefault(symbol); + return escaped === undefined ? undefined : ts.unescapeLeadingUnderscores(escaped); + } + ts.symbolNameNoDefault = symbolNameNoDefault; + function symbolEscapedNameNoDefault(symbol) { + if (symbol.escapedName !== "default" /* Default */) { + return symbol.escapedName; + } + return ts.firstDefined(symbol.declarations, function (decl) { + var name = ts.getNameOfDeclaration(decl); + return name && name.kind === 72 /* Identifier */ ? name.escapedText : undefined; + }); + } + ts.symbolEscapedNameNoDefault = symbolEscapedNameNoDefault; + function isObjectBindingElementWithoutPropertyName(bindingElement) { + return ts.isBindingElement(bindingElement) && + ts.isObjectBindingPattern(bindingElement.parent) && + ts.isIdentifier(bindingElement.name) && + !bindingElement.propertyName; + } + ts.isObjectBindingElementWithoutPropertyName = isObjectBindingElementWithoutPropertyName; + function getPropertySymbolFromBindingElement(checker, bindingElement) { + var typeOfPattern = checker.getTypeAtLocation(bindingElement.parent); + return typeOfPattern && checker.getPropertyOfType(typeOfPattern, bindingElement.name.text); + } + ts.getPropertySymbolFromBindingElement = getPropertySymbolFromBindingElement; + /** + * Find symbol of the given property-name and add the symbol to the given result array + * @param symbol a symbol to start searching for the given propertyName + * @param propertyName a name of property to search for + * @param result an array of symbol of found property symbols + * @param previousIterationSymbolsCache a cache of symbol from previous iterations of calling this function to prevent infinite revisiting of the same symbol. + * The value of previousIterationSymbol is undefined when the function is first called. + */ + function getPropertySymbolsFromBaseTypes(symbol, propertyName, checker, cb) { + var seen = ts.createMap(); + return recur(symbol); + function recur(symbol) { + // Use `addToSeen` to ensure we don't infinitely recurse in this situation: + // interface C extends C { + // /*findRef*/propName: string; + // } + if (!(symbol.flags & (32 /* Class */ | 64 /* Interface */)) || !ts.addToSeen(seen, ts.getSymbolId(symbol))) + return; + return ts.firstDefined(symbol.declarations, function (declaration) { return ts.firstDefined(ts.getAllSuperTypeNodes(declaration), function (typeReference) { + var type = checker.getTypeAtLocation(typeReference); + var propertySymbol = type && type.symbol && checker.getPropertyOfType(type, propertyName); + // Visit the typeReference as well to see if it directly or indirectly uses that property + return type && propertySymbol && (ts.firstDefined(checker.getRootSymbols(propertySymbol), cb) || recur(type.symbol)); + }); }); + } + } + ts.getPropertySymbolsFromBaseTypes = getPropertySymbolsFromBaseTypes; + function isMemberSymbolInBaseType(memberSymbol, checker) { + return getPropertySymbolsFromBaseTypes(memberSymbol.parent, memberSymbol.name, checker, function (_) { return true; }) || false; + } + ts.isMemberSymbolInBaseType = isMemberSymbolInBaseType; + function getParentNodeInSpan(node, file, span) { + if (!node) + return undefined; + while (node.parent) { + if (ts.isSourceFile(node.parent) || !spanContainsNode(span, node.parent, file)) { + return node; + } + node = node.parent; + } + } + ts.getParentNodeInSpan = getParentNodeInSpan; + function spanContainsNode(span, node, file) { + return ts.textSpanContainsPosition(span, node.getStart(file)) && + node.getEnd() <= ts.textSpanEnd(span); + } + function findModifier(node, kind) { + return node.modifiers && ts.find(node.modifiers, function (m) { return m.kind === kind; }); + } + ts.findModifier = findModifier; + function insertImport(changes, sourceFile, importDecl) { + var lastImportDeclaration = ts.findLast(sourceFile.statements, ts.isAnyImportSyntax); + if (lastImportDeclaration) { + changes.insertNodeAfter(sourceFile, lastImportDeclaration, importDecl); + } + else { + changes.insertNodeAtTopOfFile(sourceFile, importDecl, /*blankLineBetween*/ true); + } + } + ts.insertImport = insertImport; + function textSpansEqual(a, b) { + return !!a && !!b && a.start === b.start && a.length === b.length; + } + ts.textSpansEqual = textSpansEqual; + function documentSpansEqual(a, b) { + return a.fileName === b.fileName && textSpansEqual(a.textSpan, b.textSpan); + } + ts.documentSpansEqual = documentSpansEqual; +})(ts || (ts = {})); +// Display-part writer helpers +/* @internal */ +(function (ts) { + function isFirstDeclarationOfSymbolParameter(symbol) { + return symbol.declarations && symbol.declarations.length > 0 && symbol.declarations[0].kind === 151 /* Parameter */; + } + ts.isFirstDeclarationOfSymbolParameter = isFirstDeclarationOfSymbolParameter; + var displayPartWriter = getDisplayPartWriter(); + function getDisplayPartWriter() { + var absoluteMaximumLength = ts.defaultMaximumTruncationLength * 10; // A hard cutoff to avoid overloading the messaging channel in worst-case scenarios + var displayParts; + var lineStart; + var indent; + var length; + resetWriter(); + var unknownWrite = function (text) { return writeKind(text, ts.SymbolDisplayPartKind.text); }; + return { + displayParts: function () { + var finalText = displayParts.length && displayParts[displayParts.length - 1].text; + if (length > absoluteMaximumLength && finalText && finalText !== "...") { + if (!ts.isWhiteSpaceLike(finalText.charCodeAt(finalText.length - 1))) { + displayParts.push(displayPart(" ", ts.SymbolDisplayPartKind.space)); + } + displayParts.push(displayPart("...", ts.SymbolDisplayPartKind.punctuation)); + } + return displayParts; + }, + writeKeyword: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.keyword); }, + writeOperator: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.operator); }, + writePunctuation: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.punctuation); }, + writeTrailingSemicolon: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.punctuation); }, + writeSpace: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.space); }, + writeStringLiteral: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.stringLiteral); }, + writeParameter: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.parameterName); }, + writeProperty: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.propertyName); }, + writeLiteral: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.stringLiteral); }, + writeSymbol: writeSymbol, + writeLine: writeLine, + write: unknownWrite, + writeComment: unknownWrite, + getText: function () { return ""; }, + getTextPos: function () { return 0; }, + getColumn: function () { return 0; }, + getLine: function () { return 0; }, + isAtStartOfLine: function () { return false; }, + rawWrite: ts.notImplemented, + getIndent: function () { return indent; }, + increaseIndent: function () { indent++; }, + decreaseIndent: function () { indent--; }, + clear: resetWriter, + trackSymbol: ts.noop, + reportInaccessibleThisError: ts.noop, + reportInaccessibleUniqueSymbolError: ts.noop, + reportPrivateInBaseOfClassExpression: ts.noop, + }; + function writeIndent() { + if (length > absoluteMaximumLength) + return; + if (lineStart) { + var indentString = ts.getIndentString(indent); + if (indentString) { + length += indentString.length; + displayParts.push(displayPart(indentString, ts.SymbolDisplayPartKind.space)); + } + lineStart = false; + } + } + function writeKind(text, kind) { + if (length > absoluteMaximumLength) + return; + writeIndent(); + length += text.length; + displayParts.push(displayPart(text, kind)); + } + function writeSymbol(text, symbol) { + if (length > absoluteMaximumLength) + return; + writeIndent(); + length += text.length; + displayParts.push(symbolPart(text, symbol)); + } + function writeLine() { + if (length > absoluteMaximumLength) + return; + length += 1; + displayParts.push(lineBreakPart()); + lineStart = true; + } + function resetWriter() { + displayParts = []; + lineStart = true; + indent = 0; + length = 0; + } + } + function symbolPart(text, symbol) { + return displayPart(text, displayPartKind(symbol)); + function displayPartKind(symbol) { + var flags = symbol.flags; + if (flags & 3 /* Variable */) { + return isFirstDeclarationOfSymbolParameter(symbol) ? ts.SymbolDisplayPartKind.parameterName : ts.SymbolDisplayPartKind.localName; + } + else if (flags & 4 /* Property */) { + return ts.SymbolDisplayPartKind.propertyName; + } + else if (flags & 32768 /* GetAccessor */) { + return ts.SymbolDisplayPartKind.propertyName; + } + else if (flags & 65536 /* SetAccessor */) { + return ts.SymbolDisplayPartKind.propertyName; + } + else if (flags & 8 /* EnumMember */) { + return ts.SymbolDisplayPartKind.enumMemberName; + } + else if (flags & 16 /* Function */) { + return ts.SymbolDisplayPartKind.functionName; + } + else if (flags & 32 /* Class */) { + return ts.SymbolDisplayPartKind.className; + } + else if (flags & 64 /* Interface */) { + return ts.SymbolDisplayPartKind.interfaceName; + } + else if (flags & 384 /* Enum */) { + return ts.SymbolDisplayPartKind.enumName; + } + else if (flags & 1536 /* Module */) { + return ts.SymbolDisplayPartKind.moduleName; + } + else if (flags & 8192 /* Method */) { + return ts.SymbolDisplayPartKind.methodName; + } + else if (flags & 262144 /* TypeParameter */) { + return ts.SymbolDisplayPartKind.typeParameterName; + } + else if (flags & 524288 /* TypeAlias */) { + return ts.SymbolDisplayPartKind.aliasName; + } + else if (flags & 2097152 /* Alias */) { + return ts.SymbolDisplayPartKind.aliasName; + } + return ts.SymbolDisplayPartKind.text; + } + } + ts.symbolPart = symbolPart; + function displayPart(text, kind) { + return { text: text, kind: ts.SymbolDisplayPartKind[kind] }; + } + ts.displayPart = displayPart; + function spacePart() { + return displayPart(" ", ts.SymbolDisplayPartKind.space); + } + ts.spacePart = spacePart; + function keywordPart(kind) { + return displayPart(ts.tokenToString(kind), ts.SymbolDisplayPartKind.keyword); + } + ts.keywordPart = keywordPart; + function punctuationPart(kind) { + return displayPart(ts.tokenToString(kind), ts.SymbolDisplayPartKind.punctuation); + } + ts.punctuationPart = punctuationPart; + function operatorPart(kind) { + return displayPart(ts.tokenToString(kind), ts.SymbolDisplayPartKind.operator); + } + ts.operatorPart = operatorPart; + function textOrKeywordPart(text) { + var kind = ts.stringToToken(text); + return kind === undefined + ? textPart(text) + : keywordPart(kind); + } + ts.textOrKeywordPart = textOrKeywordPart; + function textPart(text) { + return displayPart(text, ts.SymbolDisplayPartKind.text); + } + ts.textPart = textPart; + var carriageReturnLineFeed = "\r\n"; + /** + * The default is CRLF. + */ + function getNewLineOrDefaultFromHost(host, formatSettings) { + return (formatSettings && formatSettings.newLineCharacter) || + (host.getNewLine && host.getNewLine()) || + carriageReturnLineFeed; + } + ts.getNewLineOrDefaultFromHost = getNewLineOrDefaultFromHost; + function lineBreakPart() { + return displayPart("\n", ts.SymbolDisplayPartKind.lineBreak); + } + ts.lineBreakPart = lineBreakPart; + function mapToDisplayParts(writeDisplayParts) { + try { + writeDisplayParts(displayPartWriter); + return displayPartWriter.displayParts(); + } + finally { + displayPartWriter.clear(); + } + } + ts.mapToDisplayParts = mapToDisplayParts; + function typeToDisplayParts(typechecker, type, enclosingDeclaration, flags) { + if (flags === void 0) { flags = 0 /* None */; } + return mapToDisplayParts(function (writer) { + typechecker.writeType(type, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */ | 16384 /* UseAliasDefinedOutsideCurrentScope */, writer); + }); + } + ts.typeToDisplayParts = typeToDisplayParts; + function symbolToDisplayParts(typeChecker, symbol, enclosingDeclaration, meaning, flags) { + if (flags === void 0) { flags = 0 /* None */; } + return mapToDisplayParts(function (writer) { + typeChecker.writeSymbol(symbol, enclosingDeclaration, meaning, flags | 8 /* UseAliasDefinedOutsideCurrentScope */, writer); + }); + } + ts.symbolToDisplayParts = symbolToDisplayParts; + function signatureToDisplayParts(typechecker, signature, enclosingDeclaration, flags) { + if (flags === void 0) { flags = 0 /* None */; } + flags |= 16384 /* UseAliasDefinedOutsideCurrentScope */ | 1024 /* MultilineObjectLiterals */ | 32 /* WriteTypeArgumentsOfSignature */ | 8192 /* OmitParameterModifiers */; + return mapToDisplayParts(function (writer) { + typechecker.writeSignature(signature, enclosingDeclaration, flags, /*signatureKind*/ undefined, writer); + }); + } + ts.signatureToDisplayParts = signatureToDisplayParts; + function isImportOrExportSpecifierName(location) { + return !!location.parent && ts.isImportOrExportSpecifier(location.parent) && location.parent.propertyName === location; + } + ts.isImportOrExportSpecifierName = isImportOrExportSpecifierName; + /** + * Strip off existed single quotes or double quotes from a given string + * + * @return non-quoted string + */ + function stripQuotes(name) { + var length = name.length; + if (length >= 2 && name.charCodeAt(0) === name.charCodeAt(length - 1) && startsWithQuote(name)) { + return name.substring(1, length - 1); + } + return name; + } + ts.stripQuotes = stripQuotes; + function startsWithQuote(name) { + return ts.isSingleOrDoubleQuote(name.charCodeAt(0)); + } + ts.startsWithQuote = startsWithQuote; + function scriptKindIs(fileName, host) { + var scriptKinds = []; + for (var _i = 2; _i < arguments.length; _i++) { + scriptKinds[_i - 2] = arguments[_i]; + } + var scriptKind = getScriptKind(fileName, host); + return ts.some(scriptKinds, function (k) { return k === scriptKind; }); + } + ts.scriptKindIs = scriptKindIs; + function getScriptKind(fileName, host) { + // First check to see if the script kind was specified by the host. Chances are the host + // may override the default script kind for the file extension. + return ts.ensureScriptKind(fileName, host && host.getScriptKind && host.getScriptKind(fileName)); + } + ts.getScriptKind = getScriptKind; + function getUniqueSymbolId(symbol, checker) { + return ts.getSymbolId(ts.skipAlias(symbol, checker)); + } + ts.getUniqueSymbolId = getUniqueSymbolId; + function getFirstNonSpaceCharacterPosition(text, position) { + while (ts.isWhiteSpaceLike(text.charCodeAt(position))) { + position += 1; + } + return position; + } + ts.getFirstNonSpaceCharacterPosition = getFirstNonSpaceCharacterPosition; + function getPrecedingNonSpaceCharacterPosition(text, position) { + while (position > -1 && ts.isWhiteSpaceSingleLine(text.charCodeAt(position))) { + position -= 1; + } + return position + 1; + } + ts.getPrecedingNonSpaceCharacterPosition = getPrecedingNonSpaceCharacterPosition; + /** + * Creates a deep, memberwise clone of a node with no source map location. + * + * WARNING: This is an expensive operation and is only intended to be used in refactorings + * and code fixes (because those are triggered by explicit user actions). + */ + function getSynthesizedDeepClone(node, includeTrivia) { + if (includeTrivia === void 0) { includeTrivia = true; } + var clone = node && getSynthesizedDeepCloneWorker(node); + if (clone && !includeTrivia) + suppressLeadingAndTrailingTrivia(clone); + return clone; + } + ts.getSynthesizedDeepClone = getSynthesizedDeepClone; + function getSynthesizedDeepCloneWithRenames(node, includeTrivia, renameMap, checker, callback) { + if (includeTrivia === void 0) { includeTrivia = true; } + var clone; + if (ts.isIdentifier(node) && renameMap && checker) { + var symbol = checker.getSymbolAtLocation(node); + var renameInfo = symbol && renameMap.get(String(ts.getSymbolId(symbol))); + if (renameInfo) { + clone = ts.createIdentifier(renameInfo.text); + } + } + if (!clone) { + clone = getSynthesizedDeepCloneWorker(node, renameMap, checker, callback); + } + if (clone && !includeTrivia) + suppressLeadingAndTrailingTrivia(clone); + if (callback && clone) + callback(node, clone); + return clone; + } + ts.getSynthesizedDeepCloneWithRenames = getSynthesizedDeepCloneWithRenames; + function getSynthesizedDeepCloneWorker(node, renameMap, checker, callback) { + var visited = (renameMap || checker || callback) ? + ts.visitEachChild(node, wrapper, ts.nullTransformationContext) : + ts.visitEachChild(node, getSynthesizedDeepClone, ts.nullTransformationContext); + if (visited === node) { + // This only happens for leaf nodes - internal nodes always see their children change. + var clone_8 = ts.getSynthesizedClone(node); + if (ts.isStringLiteral(clone_8)) { + clone_8.textSourceNode = node; + } + else if (ts.isNumericLiteral(clone_8)) { + clone_8.numericLiteralFlags = node.numericLiteralFlags; + } + return ts.setTextRange(clone_8, node); + } + // PERF: As an optimization, rather than calling getSynthesizedClone, we'll update + // the new node created by visitEachChild with the extra changes getSynthesizedClone + // would have made. + visited.parent = undefined; + return visited; + function wrapper(node) { + return getSynthesizedDeepCloneWithRenames(node, /*includeTrivia*/ true, renameMap, checker, callback); + } + } + function getSynthesizedDeepClones(nodes, includeTrivia) { + if (includeTrivia === void 0) { includeTrivia = true; } + return nodes && ts.createNodeArray(nodes.map(function (n) { return getSynthesizedDeepClone(n, includeTrivia); }), nodes.hasTrailingComma); + } + ts.getSynthesizedDeepClones = getSynthesizedDeepClones; + /** + * Sets EmitFlags to suppress leading and trailing trivia on the node. + */ + function suppressLeadingAndTrailingTrivia(node) { + suppressLeadingTrivia(node); + suppressTrailingTrivia(node); + } + ts.suppressLeadingAndTrailingTrivia = suppressLeadingAndTrailingTrivia; + /** + * Sets EmitFlags to suppress leading trivia on the node. + */ + function suppressLeadingTrivia(node) { + addEmitFlagsRecursively(node, 512 /* NoLeadingComments */, getFirstChild); + } + ts.suppressLeadingTrivia = suppressLeadingTrivia; + /** + * Sets EmitFlags to suppress trailing trivia on the node. + */ + function suppressTrailingTrivia(node) { + addEmitFlagsRecursively(node, 1024 /* NoTrailingComments */, ts.getLastChild); + } + ts.suppressTrailingTrivia = suppressTrailingTrivia; + function addEmitFlagsRecursively(node, flag, getChild) { + ts.addEmitFlags(node, flag); + var child = getChild(node); + if (child) + addEmitFlagsRecursively(child, flag, getChild); + } + function getFirstChild(node) { + return node.forEachChild(function (child) { return child; }); + } + function getUniqueName(baseName, sourceFile) { + var nameText = baseName; + for (var i = 1; !ts.isFileLevelUniqueName(sourceFile, nameText); i++) { + nameText = baseName + "_" + i; + } + return nameText; + } + ts.getUniqueName = getUniqueName; + /** + * @return The index of the (only) reference to the extracted symbol. We want the cursor + * to be on the reference, rather than the declaration, because it's closer to where the + * user was before extracting it. + */ + function getRenameLocation(edits, renameFilename, name, preferLastLocation) { + var delta = 0; + var lastPos = -1; + for (var _i = 0, edits_1 = edits; _i < edits_1.length; _i++) { + var _a = edits_1[_i], fileName = _a.fileName, textChanges_2 = _a.textChanges; + ts.Debug.assert(fileName === renameFilename); + for (var _b = 0, textChanges_1 = textChanges_2; _b < textChanges_1.length; _b++) { + var change = textChanges_1[_b]; + var span = change.span, newText = change.newText; + var index = indexInTextChange(newText, name); + if (index !== -1) { + lastPos = span.start + delta + index; + // If the reference comes first, return immediately. + if (!preferLastLocation) { + return lastPos; + } + } + delta += newText.length - span.length; + } + } + // If the declaration comes first, return the position of the last occurrence. + ts.Debug.assert(preferLastLocation); + ts.Debug.assert(lastPos >= 0); + return lastPos; + } + ts.getRenameLocation = getRenameLocation; + function copyComments(sourceNode, targetNode, sourceFile, commentKind, hasTrailingNewLine) { + ts.forEachLeadingCommentRange(sourceFile.text, sourceNode.pos, function (pos, end, kind, htnl) { + if (kind === 3 /* MultiLineCommentTrivia */) { + // Remove leading /* + pos += 2; + // Remove trailing */ + end -= 2; + } + else { + // Remove leading // + pos += 2; + } + ts.addSyntheticLeadingComment(targetNode, commentKind || kind, sourceFile.text.slice(pos, end), hasTrailingNewLine !== undefined ? hasTrailingNewLine : htnl); + }); + } + ts.copyComments = copyComments; + function indexInTextChange(change, name) { + if (ts.startsWith(change, name)) + return 0; + // Add a " " to avoid references inside words + var idx = change.indexOf(" " + name); + if (idx === -1) + idx = change.indexOf("." + name); + if (idx === -1) + idx = change.indexOf('"' + name); + return idx === -1 ? -1 : idx + 1; + } + function getContextualTypeFromParent(node, checker) { + var parent = node.parent; + switch (parent.kind) { + case 192 /* NewExpression */: + return checker.getContextualType(parent); + case 204 /* BinaryExpression */: { + var _a = parent, left = _a.left, operatorToken = _a.operatorToken, right = _a.right; + return isEqualityOperatorKind(operatorToken.kind) + ? checker.getTypeAtLocation(node === right ? left : right) + : checker.getContextualType(node); + } + case 271 /* CaseClause */: + return parent.expression === node ? getSwitchedType(parent, checker) : undefined; + default: + return checker.getContextualType(node); + } + } + ts.getContextualTypeFromParent = getContextualTypeFromParent; + function quote(text, preferences) { + if (/^\d+$/.test(text)) { + return text; + } + var quoted = JSON.stringify(text); + switch (preferences.quotePreference) { + case undefined: + case "double": + return quoted; + case "single": + return "'" + stripQuotes(quoted).replace("'", "\\'").replace('\\"', '"') + "'"; + default: + return ts.Debug.assertNever(preferences.quotePreference); + } + } + ts.quote = quote; + function isEqualityOperatorKind(kind) { + switch (kind) { + case 35 /* EqualsEqualsEqualsToken */: + case 33 /* EqualsEqualsToken */: + case 36 /* ExclamationEqualsEqualsToken */: + case 34 /* ExclamationEqualsToken */: + return true; + default: + return false; + } + } + ts.isEqualityOperatorKind = isEqualityOperatorKind; + function isStringLiteralOrTemplate(node) { + switch (node.kind) { + case 10 /* StringLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: + case 206 /* TemplateExpression */: + case 193 /* TaggedTemplateExpression */: + return true; + default: + return false; + } + } + ts.isStringLiteralOrTemplate = isStringLiteralOrTemplate; + function hasIndexSignature(type) { + return !!type.getStringIndexType() || !!type.getNumberIndexType(); + } + ts.hasIndexSignature = hasIndexSignature; + function getSwitchedType(caseClause, checker) { + return checker.getTypeAtLocation(caseClause.parent.parent.expression); + } + ts.getSwitchedType = getSwitchedType; +})(ts || (ts = {})); +var ts; +(function (ts) { + function createClassifier() { + var scanner = ts.createScanner(6 /* Latest */, /*skipTrivia*/ false); + function getClassificationsForLine(text, lexState, syntacticClassifierAbsent) { + return convertClassificationsToResult(getEncodedLexicalClassifications(text, lexState, syntacticClassifierAbsent), text); + } + // If there is a syntactic classifier ('syntacticClassifierAbsent' is false), + // we will be more conservative in order to avoid conflicting with the syntactic classifier. + function getEncodedLexicalClassifications(text, lexState, syntacticClassifierAbsent) { + var token = 0 /* Unknown */; + var lastNonTriviaToken = 0 /* Unknown */; + // Just a stack of TemplateHeads and OpenCurlyBraces, used to perform rudimentary (inexact) + // classification on template strings. Because of the context free nature of templates, + // the only precise way to classify a template portion would be by propagating the stack across + // lines, just as we do with the end-of-line state. However, this is a burden for implementers, + // and the behavior is entirely subsumed by the syntactic classifier anyway, so we instead + // flatten any nesting when the template stack is non-empty and encode it in the end-of-line state. + // Situations in which this fails are + // 1) When template strings are nested across different lines: + // `hello ${ `world + // ` }` + // + // Where on the second line, you will get the closing of a template, + // a closing curly, and a new template. + // + // 2) When substitution expressions have curly braces and the curly brace falls on the next line: + // `hello ${ () => { + // return "world" } } ` + // + // Where on the second line, you will get the 'return' keyword, + // a string literal, and a template end consisting of '} } `'. + var templateStack = []; + var _a = getPrefixFromLexState(lexState), prefix = _a.prefix, pushTemplate = _a.pushTemplate; + text = prefix + text; + var offset = prefix.length; + if (pushTemplate) { + templateStack.push(15 /* TemplateHead */); + } + scanner.setText(text); + var endOfLineState = 0 /* None */; + var spans = []; + // We can run into an unfortunate interaction between the lexical and syntactic classifier + // when the user is typing something generic. Consider the case where the user types: + // + // Foo tokens. It's a weak heuristic, but should + // work well enough in practice. + var angleBracketStack = 0; + do { + token = scanner.scan(); + if (!ts.isTrivia(token)) { + handleToken(); + lastNonTriviaToken = token; + } + var end = scanner.getTextPos(); + pushEncodedClassification(scanner.getTokenPos(), end, offset, classFromKind(token), spans); + if (end >= text.length) { + var end_1 = getNewEndOfLineState(scanner, token, ts.lastOrUndefined(templateStack)); + if (end_1 !== undefined) { + endOfLineState = end_1; + } + } + } while (token !== 1 /* EndOfFileToken */); + function handleToken() { + switch (token) { + case 42 /* SlashToken */: + case 64 /* SlashEqualsToken */: + if (!noRegexTable[lastNonTriviaToken] && scanner.reScanSlashToken() === 13 /* RegularExpressionLiteral */) { + token = 13 /* RegularExpressionLiteral */; + } + break; + case 28 /* LessThanToken */: + if (lastNonTriviaToken === 72 /* Identifier */) { + // Could be the start of something generic. Keep track of that by bumping + // up the current count of generic contexts we may be in. + angleBracketStack++; + } + break; + case 30 /* GreaterThanToken */: + if (angleBracketStack > 0) { + // If we think we're currently in something generic, then mark that that + // generic entity is complete. + angleBracketStack--; + } + break; + case 120 /* AnyKeyword */: + case 138 /* StringKeyword */: + case 135 /* NumberKeyword */: + case 123 /* BooleanKeyword */: + case 139 /* SymbolKeyword */: + if (angleBracketStack > 0 && !syntacticClassifierAbsent) { + // If it looks like we're could be in something generic, don't classify this + // as a keyword. We may just get overwritten by the syntactic classifier, + // causing a noisy experience for the user. + token = 72 /* Identifier */; + } + break; + case 15 /* TemplateHead */: + templateStack.push(token); + break; + case 18 /* OpenBraceToken */: + // If we don't have anything on the template stack, + // then we aren't trying to keep track of a previously scanned template head. + if (templateStack.length > 0) { + templateStack.push(token); + } + break; + case 19 /* CloseBraceToken */: + // If we don't have anything on the template stack, + // then we aren't trying to keep track of a previously scanned template head. + if (templateStack.length > 0) { + var lastTemplateStackToken = ts.lastOrUndefined(templateStack); + if (lastTemplateStackToken === 15 /* TemplateHead */) { + token = scanner.reScanTemplateToken(); + // Only pop on a TemplateTail; a TemplateMiddle indicates there is more for us. + if (token === 17 /* TemplateTail */) { + templateStack.pop(); + } + else { + ts.Debug.assertEqual(token, 16 /* TemplateMiddle */, "Should have been a template middle."); + } + } + else { + ts.Debug.assertEqual(lastTemplateStackToken, 18 /* OpenBraceToken */, "Should have been an open brace"); + templateStack.pop(); + } + } + break; + default: + if (!ts.isKeyword(token)) { + break; + } + if (lastNonTriviaToken === 24 /* DotToken */) { + token = 72 /* Identifier */; + } + else if (ts.isKeyword(lastNonTriviaToken) && ts.isKeyword(token) && !canFollow(lastNonTriviaToken, token)) { + // We have two keywords in a row. Only treat the second as a keyword if + // it's a sequence that could legally occur in the language. Otherwise + // treat it as an identifier. This way, if someone writes "private var" + // we recognize that 'var' is actually an identifier here. + token = 72 /* Identifier */; + } + } + } + return { endOfLineState: endOfLineState, spans: spans }; + } + return { getClassificationsForLine: getClassificationsForLine, getEncodedLexicalClassifications: getEncodedLexicalClassifications }; + } + ts.createClassifier = createClassifier; + /// We do not have a full parser support to know when we should parse a regex or not + /// If we consider every slash token to be a regex, we could be missing cases like "1/2/3", where + /// we have a series of divide operator. this list allows us to be more accurate by ruling out + /// locations where a regexp cannot exist. + var noRegexTable = ts.arrayToNumericMap([ + 72 /* Identifier */, + 10 /* StringLiteral */, + 8 /* NumericLiteral */, + 9 /* BigIntLiteral */, + 13 /* RegularExpressionLiteral */, + 100 /* ThisKeyword */, + 44 /* PlusPlusToken */, + 45 /* MinusMinusToken */, + 21 /* CloseParenToken */, + 23 /* CloseBracketToken */, + 19 /* CloseBraceToken */, + 102 /* TrueKeyword */, + 87 /* FalseKeyword */, + ], function (token) { return token; }, function () { return true; }); + function getNewEndOfLineState(scanner, token, lastOnTemplateStack) { + switch (token) { + case 10 /* StringLiteral */: { + // Check to see if we finished up on a multiline string literal. + if (!scanner.isUnterminated()) + return undefined; + var tokenText = scanner.getTokenText(); + var lastCharIndex = tokenText.length - 1; + var numBackslashes = 0; + while (tokenText.charCodeAt(lastCharIndex - numBackslashes) === 92 /* backslash */) { + numBackslashes++; + } + // If we have an odd number of backslashes, then the multiline string is unclosed + if ((numBackslashes & 1) === 0) + return undefined; + return tokenText.charCodeAt(0) === 34 /* doubleQuote */ ? 3 /* InDoubleQuoteStringLiteral */ : 2 /* InSingleQuoteStringLiteral */; + } + case 3 /* MultiLineCommentTrivia */: + // Check to see if the multiline comment was unclosed. + return scanner.isUnterminated() ? 1 /* InMultiLineCommentTrivia */ : undefined; + default: + if (ts.isTemplateLiteralKind(token)) { + if (!scanner.isUnterminated()) { + return undefined; + } + switch (token) { + case 17 /* TemplateTail */: + return 5 /* InTemplateMiddleOrTail */; + case 14 /* NoSubstitutionTemplateLiteral */: + return 4 /* InTemplateHeadOrNoSubstitutionTemplate */; + default: + return ts.Debug.fail("Only 'NoSubstitutionTemplateLiteral's and 'TemplateTail's can be unterminated; got SyntaxKind #" + token); + } + } + return lastOnTemplateStack === 15 /* TemplateHead */ ? 6 /* InTemplateSubstitutionPosition */ : undefined; + } + } + function pushEncodedClassification(start, end, offset, classification, result) { + if (classification === 8 /* whiteSpace */) { + // Don't bother with whitespace classifications. They're not needed. + return; + } + if (start === 0 && offset > 0) { + // We're classifying the first token, and this was a case where we prepended text. + // We should consider the start of this token to be at the start of the original text. + start += offset; + } + var length = end - start; + if (length > 0) { + // All our tokens are in relation to the augmented text. Move them back to be + // relative to the original text. + result.push(start - offset, length, classification); + } + } + function convertClassificationsToResult(classifications, text) { + var entries = []; + var dense = classifications.spans; + var lastEnd = 0; + for (var i = 0; i < dense.length; i += 3) { + var start = dense[i]; + var length_5 = dense[i + 1]; + var type = dense[i + 2]; + // Make a whitespace entry between the last item and this one. + if (lastEnd >= 0) { + var whitespaceLength_1 = start - lastEnd; + if (whitespaceLength_1 > 0) { + entries.push({ length: whitespaceLength_1, classification: ts.TokenClass.Whitespace }); + } + } + entries.push({ length: length_5, classification: convertClassification(type) }); + lastEnd = start + length_5; + } + var whitespaceLength = text.length - lastEnd; + if (whitespaceLength > 0) { + entries.push({ length: whitespaceLength, classification: ts.TokenClass.Whitespace }); + } + return { entries: entries, finalLexState: classifications.endOfLineState }; + } + function convertClassification(type) { + switch (type) { + case 1 /* comment */: return ts.TokenClass.Comment; + case 3 /* keyword */: return ts.TokenClass.Keyword; + case 4 /* numericLiteral */: return ts.TokenClass.NumberLiteral; + case 25 /* bigintLiteral */: return ts.TokenClass.BigIntLiteral; + case 5 /* operator */: return ts.TokenClass.Operator; + case 6 /* stringLiteral */: return ts.TokenClass.StringLiteral; + case 8 /* whiteSpace */: return ts.TokenClass.Whitespace; + case 10 /* punctuation */: return ts.TokenClass.Punctuation; + case 2 /* identifier */: + case 11 /* className */: + case 12 /* enumName */: + case 13 /* interfaceName */: + case 14 /* moduleName */: + case 15 /* typeParameterName */: + case 16 /* typeAliasName */: + case 9 /* text */: + case 17 /* parameterName */: + return ts.TokenClass.Identifier; + default: + return undefined; // TODO: GH#18217 Debug.assertNever(type); + } + } + /** Returns true if 'keyword2' can legally follow 'keyword1' in any language construct. */ + function canFollow(keyword1, keyword2) { + if (!ts.isAccessibilityModifier(keyword1)) { + // Assume any other keyword combination is legal. + // This can be refined in the future if there are more cases we want the classifier to be better at. + return true; + } + switch (keyword2) { + case 126 /* GetKeyword */: + case 137 /* SetKeyword */: + case 124 /* ConstructorKeyword */: + case 116 /* StaticKeyword */: + return true; // Allow things like "public get", "public constructor" and "public static". + default: + return false; // Any other keyword following "public" is actually an identifier, not a real keyword. + } + } + function getPrefixFromLexState(lexState) { + // If we're in a string literal, then prepend: "\ + // (and a newline). That way when we lex we'll think we're still in a string literal. + // + // If we're in a multiline comment, then prepend: /* + // (and a newline). That way when we lex we'll think we're still in a multiline comment. + switch (lexState) { + case 3 /* InDoubleQuoteStringLiteral */: + return { prefix: "\"\\\n" }; + case 2 /* InSingleQuoteStringLiteral */: + return { prefix: "'\\\n" }; + case 1 /* InMultiLineCommentTrivia */: + return { prefix: "/*\n" }; + case 4 /* InTemplateHeadOrNoSubstitutionTemplate */: + return { prefix: "`\n" }; + case 5 /* InTemplateMiddleOrTail */: + return { prefix: "}\n", pushTemplate: true }; + case 6 /* InTemplateSubstitutionPosition */: + return { prefix: "", pushTemplate: true }; + case 0 /* None */: + return { prefix: "" }; + default: + return ts.Debug.assertNever(lexState); + } + } + function isBinaryExpressionOperatorToken(token) { + switch (token) { + case 40 /* AsteriskToken */: + case 42 /* SlashToken */: + case 43 /* PercentToken */: + case 38 /* PlusToken */: + case 39 /* MinusToken */: + case 46 /* LessThanLessThanToken */: + case 47 /* GreaterThanGreaterThanToken */: + case 48 /* GreaterThanGreaterThanGreaterThanToken */: + case 28 /* LessThanToken */: + case 30 /* GreaterThanToken */: + case 31 /* LessThanEqualsToken */: + case 32 /* GreaterThanEqualsToken */: + case 94 /* InstanceOfKeyword */: + case 93 /* InKeyword */: + case 119 /* AsKeyword */: + case 33 /* EqualsEqualsToken */: + case 34 /* ExclamationEqualsToken */: + case 35 /* EqualsEqualsEqualsToken */: + case 36 /* ExclamationEqualsEqualsToken */: + case 49 /* AmpersandToken */: + case 51 /* CaretToken */: + case 50 /* BarToken */: + case 54 /* AmpersandAmpersandToken */: + case 55 /* BarBarToken */: + case 70 /* BarEqualsToken */: + case 69 /* AmpersandEqualsToken */: + case 71 /* CaretEqualsToken */: + case 66 /* LessThanLessThanEqualsToken */: + case 67 /* GreaterThanGreaterThanEqualsToken */: + case 68 /* GreaterThanGreaterThanGreaterThanEqualsToken */: + case 60 /* PlusEqualsToken */: + case 61 /* MinusEqualsToken */: + case 62 /* AsteriskEqualsToken */: + case 64 /* SlashEqualsToken */: + case 65 /* PercentEqualsToken */: + case 59 /* EqualsToken */: + case 27 /* CommaToken */: + return true; + default: + return false; + } + } + function isPrefixUnaryExpressionOperatorToken(token) { + switch (token) { + case 38 /* PlusToken */: + case 39 /* MinusToken */: + case 53 /* TildeToken */: + case 52 /* ExclamationToken */: + case 44 /* PlusPlusToken */: + case 45 /* MinusMinusToken */: + return true; + default: + return false; + } + } + function classFromKind(token) { + if (ts.isKeyword(token)) { + return 3 /* keyword */; + } + else if (isBinaryExpressionOperatorToken(token) || isPrefixUnaryExpressionOperatorToken(token)) { + return 5 /* operator */; + } + else if (token >= 18 /* FirstPunctuation */ && token <= 71 /* LastPunctuation */) { + return 10 /* punctuation */; + } + switch (token) { + case 8 /* NumericLiteral */: + return 4 /* numericLiteral */; + case 9 /* BigIntLiteral */: + return 25 /* bigintLiteral */; + case 10 /* StringLiteral */: + return 6 /* stringLiteral */; + case 13 /* RegularExpressionLiteral */: + return 7 /* regularExpressionLiteral */; + case 7 /* ConflictMarkerTrivia */: + case 3 /* MultiLineCommentTrivia */: + case 2 /* SingleLineCommentTrivia */: + return 1 /* comment */; + case 5 /* WhitespaceTrivia */: + case 4 /* NewLineTrivia */: + return 8 /* whiteSpace */; + case 72 /* Identifier */: + default: + if (ts.isTemplateLiteralKind(token)) { + return 6 /* stringLiteral */; + } + return 2 /* identifier */; + } + } + /* @internal */ + function getSemanticClassifications(typeChecker, cancellationToken, sourceFile, classifiableNames, span) { + return convertClassificationsToSpans(getEncodedSemanticClassifications(typeChecker, cancellationToken, sourceFile, classifiableNames, span)); + } + ts.getSemanticClassifications = getSemanticClassifications; + function checkForClassificationCancellation(cancellationToken, kind) { + // We don't want to actually call back into our host on every node to find out if we've + // been canceled. That would be an enormous amount of chattyness, along with the all + // the overhead of marshalling the data to/from the host. So instead we pick a few + // reasonable node kinds to bother checking on. These node kinds represent high level + // constructs that we would expect to see commonly, but just at a far less frequent + // interval. + // + // For example, in checker.ts (around 750k) we only have around 600 of these constructs. + // That means we're calling back into the host around every 1.2k of the file we process. + // Lib.d.ts has similar numbers. + switch (kind) { + case 244 /* ModuleDeclaration */: + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + case 239 /* FunctionDeclaration */: + cancellationToken.throwIfCancellationRequested(); + } + } + /* @internal */ + function getEncodedSemanticClassifications(typeChecker, cancellationToken, sourceFile, classifiableNames, span) { + var spans = []; + sourceFile.forEachChild(function cb(node) { + // Only walk into nodes that intersect the requested span. + if (!node || !ts.textSpanIntersectsWith(span, node.pos, node.getFullWidth())) { + return; + } + checkForClassificationCancellation(cancellationToken, node.kind); + // Only bother calling into the typechecker if this is an identifier that + // could possibly resolve to a type name. This makes classification run + // in a third of the time it would normally take. + if (ts.isIdentifier(node) && !ts.nodeIsMissing(node) && classifiableNames.has(node.escapedText)) { + var symbol = typeChecker.getSymbolAtLocation(node); + var type = symbol && classifySymbol(symbol, ts.getMeaningFromLocation(node), typeChecker); + if (type) { + pushClassification(node.getStart(sourceFile), node.getEnd(), type); + } + } + node.forEachChild(cb); + }); + return { spans: spans, endOfLineState: 0 /* None */ }; + function pushClassification(start, end, type) { + spans.push(start); + spans.push(end - start); + spans.push(type); + } + } + ts.getEncodedSemanticClassifications = getEncodedSemanticClassifications; + function classifySymbol(symbol, meaningAtPosition, checker) { + var flags = symbol.getFlags(); + if ((flags & 2885600 /* Classifiable */) === 0 /* None */) { + return undefined; + } + else if (flags & 32 /* Class */) { + return 11 /* className */; + } + else if (flags & 384 /* Enum */) { + return 12 /* enumName */; + } + else if (flags & 524288 /* TypeAlias */) { + return 16 /* typeAliasName */; + } + else if (flags & 1536 /* Module */) { + // Only classify a module as such if + // - It appears in a namespace context. + // - There exists a module declaration which actually impacts the value side. + return meaningAtPosition & 4 /* Namespace */ || meaningAtPosition & 1 /* Value */ && hasValueSideModule(symbol) ? 14 /* moduleName */ : undefined; + } + else if (flags & 2097152 /* Alias */) { + return classifySymbol(checker.getAliasedSymbol(symbol), meaningAtPosition, checker); + } + else if (meaningAtPosition & 2 /* Type */) { + return flags & 64 /* Interface */ ? 13 /* interfaceName */ : flags & 262144 /* TypeParameter */ ? 15 /* typeParameterName */ : undefined; + } + else { + return undefined; + } + } + /** Returns true if there exists a module that introduces entities on the value side. */ + function hasValueSideModule(symbol) { + return ts.some(symbol.declarations, function (declaration) { + return ts.isModuleDeclaration(declaration) && ts.getModuleInstanceState(declaration) === 1 /* Instantiated */; + }); + } + function getClassificationTypeName(type) { + switch (type) { + case 1 /* comment */: return "comment" /* comment */; + case 2 /* identifier */: return "identifier" /* identifier */; + case 3 /* keyword */: return "keyword" /* keyword */; + case 4 /* numericLiteral */: return "number" /* numericLiteral */; + case 25 /* bigintLiteral */: return "bigint" /* bigintLiteral */; + case 5 /* operator */: return "operator" /* operator */; + case 6 /* stringLiteral */: return "string" /* stringLiteral */; + case 8 /* whiteSpace */: return "whitespace" /* whiteSpace */; + case 9 /* text */: return "text" /* text */; + case 10 /* punctuation */: return "punctuation" /* punctuation */; + case 11 /* className */: return "class name" /* className */; + case 12 /* enumName */: return "enum name" /* enumName */; + case 13 /* interfaceName */: return "interface name" /* interfaceName */; + case 14 /* moduleName */: return "module name" /* moduleName */; + case 15 /* typeParameterName */: return "type parameter name" /* typeParameterName */; + case 16 /* typeAliasName */: return "type alias name" /* typeAliasName */; + case 17 /* parameterName */: return "parameter name" /* parameterName */; + case 18 /* docCommentTagName */: return "doc comment tag name" /* docCommentTagName */; + case 19 /* jsxOpenTagName */: return "jsx open tag name" /* jsxOpenTagName */; + case 20 /* jsxCloseTagName */: return "jsx close tag name" /* jsxCloseTagName */; + case 21 /* jsxSelfClosingTagName */: return "jsx self closing tag name" /* jsxSelfClosingTagName */; + case 22 /* jsxAttribute */: return "jsx attribute" /* jsxAttribute */; + case 23 /* jsxText */: return "jsx text" /* jsxText */; + case 24 /* jsxAttributeStringLiteralValue */: return "jsx attribute string literal value" /* jsxAttributeStringLiteralValue */; + default: return undefined; // TODO: GH#18217 throw Debug.assertNever(type); + } + } + function convertClassificationsToSpans(classifications) { + ts.Debug.assert(classifications.spans.length % 3 === 0); + var dense = classifications.spans; + var result = []; + for (var i = 0; i < dense.length; i += 3) { + result.push({ + textSpan: ts.createTextSpan(dense[i], dense[i + 1]), + classificationType: getClassificationTypeName(dense[i + 2]) + }); + } + return result; + } + /* @internal */ + function getSyntacticClassifications(cancellationToken, sourceFile, span) { + return convertClassificationsToSpans(getEncodedSyntacticClassifications(cancellationToken, sourceFile, span)); + } + ts.getSyntacticClassifications = getSyntacticClassifications; + /* @internal */ + function getEncodedSyntacticClassifications(cancellationToken, sourceFile, span) { + var spanStart = span.start; + var spanLength = span.length; + // Make a scanner we can get trivia from. + var triviaScanner = ts.createScanner(6 /* Latest */, /*skipTrivia*/ false, sourceFile.languageVariant, sourceFile.text); + var mergeConflictScanner = ts.createScanner(6 /* Latest */, /*skipTrivia*/ false, sourceFile.languageVariant, sourceFile.text); + var result = []; + processElement(sourceFile); + return { spans: result, endOfLineState: 0 /* None */ }; + function pushClassification(start, length, type) { + result.push(start); + result.push(length); + result.push(type); + } + function classifyLeadingTriviaAndGetTokenStart(token) { + triviaScanner.setTextPos(token.pos); + while (true) { + var start = triviaScanner.getTextPos(); + // only bother scanning if we have something that could be trivia. + if (!ts.couldStartTrivia(sourceFile.text, start)) { + return start; + } + var kind = triviaScanner.scan(); + var end = triviaScanner.getTextPos(); + var width = end - start; + // The moment we get something that isn't trivia, then stop processing. + if (!ts.isTrivia(kind)) { + return start; + } + switch (kind) { + case 4 /* NewLineTrivia */: + case 5 /* WhitespaceTrivia */: + // Don't bother with newlines/whitespace. + continue; + case 2 /* SingleLineCommentTrivia */: + case 3 /* MultiLineCommentTrivia */: + // Only bother with the trivia if it at least intersects the span of interest. + classifyComment(token, kind, start, width); + // Classifying a comment might cause us to reuse the trivia scanner + // (because of jsdoc comments). So after we classify the comment make + // sure we set the scanner position back to where it needs to be. + triviaScanner.setTextPos(end); + continue; + case 7 /* ConflictMarkerTrivia */: + var text = sourceFile.text; + var ch = text.charCodeAt(start); + // for the <<<<<<< and >>>>>>> markers, we just add them in as comments + // in the classification stream. + if (ch === 60 /* lessThan */ || ch === 62 /* greaterThan */) { + pushClassification(start, width, 1 /* comment */); + continue; + } + // for the ||||||| and ======== markers, add a comment for the first line, + // and then lex all subsequent lines up until the end of the conflict marker. + ts.Debug.assert(ch === 124 /* bar */ || ch === 61 /* equals */); + classifyDisabledMergeCode(text, start, end); + break; + case 6 /* ShebangTrivia */: + // TODO: Maybe we should classify these. + break; + default: + ts.Debug.assertNever(kind); + } + } + } + function classifyComment(token, kind, start, width) { + if (kind === 3 /* MultiLineCommentTrivia */) { + // See if this is a doc comment. If so, we'll classify certain portions of it + // specially. + var docCommentAndDiagnostics = ts.parseIsolatedJSDocComment(sourceFile.text, start, width); + if (docCommentAndDiagnostics && docCommentAndDiagnostics.jsDoc) { + // TODO: This should be predicated on `token["kind"]` being compatible with `HasJSDoc["kind"]` + docCommentAndDiagnostics.jsDoc.parent = token; + classifyJSDocComment(docCommentAndDiagnostics.jsDoc); + return; + } + } + // Simple comment. Just add as is. + pushCommentRange(start, width); + } + function pushCommentRange(start, width) { + pushClassification(start, width, 1 /* comment */); + } + function classifyJSDocComment(docComment) { + var pos = docComment.pos; + if (docComment.tags) { + for (var _i = 0, _a = docComment.tags; _i < _a.length; _i++) { + var tag = _a[_i]; + // As we walk through each tag, classify the portion of text from the end of + // the last tag (or the start of the entire doc comment) as 'comment'. + if (tag.pos !== pos) { + pushCommentRange(pos, tag.pos - pos); + } + pushClassification(tag.pos, 1, 10 /* punctuation */); // "@" + pushClassification(tag.tagName.pos, tag.tagName.end - tag.tagName.pos, 18 /* docCommentTagName */); // e.g. "param" + pos = tag.tagName.end; + switch (tag.kind) { + case 299 /* JSDocParameterTag */: + processJSDocParameterTag(tag); + break; + case 303 /* JSDocTemplateTag */: + processJSDocTemplateTag(tag); + pos = tag.end; + break; + case 302 /* JSDocTypeTag */: + processElement(tag.typeExpression); + pos = tag.end; + break; + case 300 /* JSDocReturnTag */: + processElement(tag.typeExpression); + pos = tag.end; + break; + } + } + } + if (pos !== docComment.end) { + pushCommentRange(pos, docComment.end - pos); + } + return; + function processJSDocParameterTag(tag) { + if (tag.isNameFirst) { + pushCommentRange(pos, tag.name.pos - pos); + pushClassification(tag.name.pos, tag.name.end - tag.name.pos, 17 /* parameterName */); + pos = tag.name.end; + } + if (tag.typeExpression) { + pushCommentRange(pos, tag.typeExpression.pos - pos); + processElement(tag.typeExpression); + pos = tag.typeExpression.end; + } + if (!tag.isNameFirst) { + pushCommentRange(pos, tag.name.pos - pos); + pushClassification(tag.name.pos, tag.name.end - tag.name.pos, 17 /* parameterName */); + pos = tag.name.end; + } + } + } + function processJSDocTemplateTag(tag) { + for (var _i = 0, _a = tag.getChildren(); _i < _a.length; _i++) { + var child = _a[_i]; + processElement(child); + } + } + function classifyDisabledMergeCode(text, start, end) { + // Classify the line that the ||||||| or ======= marker is on as a comment. + // Then just lex all further tokens and add them to the result. + var i; + for (i = start; i < end; i++) { + if (ts.isLineBreak(text.charCodeAt(i))) { + break; + } + } + pushClassification(start, i - start, 1 /* comment */); + mergeConflictScanner.setTextPos(i); + while (mergeConflictScanner.getTextPos() < end) { + classifyDisabledCodeToken(); + } + } + function classifyDisabledCodeToken() { + var start = mergeConflictScanner.getTextPos(); + var tokenKind = mergeConflictScanner.scan(); + var end = mergeConflictScanner.getTextPos(); + var type = classifyTokenType(tokenKind); + if (type) { + pushClassification(start, end - start, type); + } + } + /** + * Returns true if node should be treated as classified and no further processing is required. + * False will mean that node is not classified and traverse routine should recurse into node contents. + */ + function tryClassifyNode(node) { + if (ts.isJSDoc(node)) { + return true; + } + if (ts.nodeIsMissing(node)) { + return true; + } + var classifiedElementName = tryClassifyJsxElementName(node); + if (!ts.isToken(node) && node.kind !== 11 /* JsxText */ && classifiedElementName === undefined) { + return false; + } + var tokenStart = node.kind === 11 /* JsxText */ ? node.pos : classifyLeadingTriviaAndGetTokenStart(node); + var tokenWidth = node.end - tokenStart; + ts.Debug.assert(tokenWidth >= 0); + if (tokenWidth > 0) { + var type = classifiedElementName || classifyTokenType(node.kind, node); + if (type) { + pushClassification(tokenStart, tokenWidth, type); + } + } + return true; + } + function tryClassifyJsxElementName(token) { + switch (token.parent && token.parent.kind) { + case 262 /* JsxOpeningElement */: + if (token.parent.tagName === token) { + return 19 /* jsxOpenTagName */; + } + break; + case 263 /* JsxClosingElement */: + if (token.parent.tagName === token) { + return 20 /* jsxCloseTagName */; + } + break; + case 261 /* JsxSelfClosingElement */: + if (token.parent.tagName === token) { + return 21 /* jsxSelfClosingTagName */; + } + break; + case 267 /* JsxAttribute */: + if (token.parent.name === token) { + return 22 /* jsxAttribute */; + } + break; + } + return undefined; + } + // for accurate classification, the actual token should be passed in. however, for + // cases like 'disabled merge code' classification, we just get the token kind and + // classify based on that instead. + function classifyTokenType(tokenKind, token) { + if (ts.isKeyword(tokenKind)) { + return 3 /* keyword */; + } + // Special case `<` and `>`: If they appear in a generic context they are punctuation, + // not operators. + if (tokenKind === 28 /* LessThanToken */ || tokenKind === 30 /* GreaterThanToken */) { + // If the node owning the token has a type argument list or type parameter list, then + // we can effectively assume that a '<' and '>' belong to those lists. + if (token && ts.getTypeArgumentOrTypeParameterList(token.parent)) { + return 10 /* punctuation */; + } + } + if (ts.isPunctuation(tokenKind)) { + if (token) { + var parent = token.parent; + if (tokenKind === 59 /* EqualsToken */) { + // the '=' in a variable declaration is special cased here. + if (parent.kind === 237 /* VariableDeclaration */ || + parent.kind === 154 /* PropertyDeclaration */ || + parent.kind === 151 /* Parameter */ || + parent.kind === 267 /* JsxAttribute */) { + return 5 /* operator */; + } + } + if (parent.kind === 204 /* BinaryExpression */ || + parent.kind === 202 /* PrefixUnaryExpression */ || + parent.kind === 203 /* PostfixUnaryExpression */ || + parent.kind === 205 /* ConditionalExpression */) { + return 5 /* operator */; + } + } + return 10 /* punctuation */; + } + else if (tokenKind === 8 /* NumericLiteral */) { + return 4 /* numericLiteral */; + } + else if (tokenKind === 9 /* BigIntLiteral */) { + return 25 /* bigintLiteral */; + } + else if (tokenKind === 10 /* StringLiteral */) { + // TODO: GH#18217 + return token.parent.kind === 267 /* JsxAttribute */ ? 24 /* jsxAttributeStringLiteralValue */ : 6 /* stringLiteral */; + } + else if (tokenKind === 13 /* RegularExpressionLiteral */) { + // TODO: we should get another classification type for these literals. + return 6 /* stringLiteral */; + } + else if (ts.isTemplateLiteralKind(tokenKind)) { + // TODO (drosen): we should *also* get another classification type for these literals. + return 6 /* stringLiteral */; + } + else if (tokenKind === 11 /* JsxText */) { + return 23 /* jsxText */; + } + else if (tokenKind === 72 /* Identifier */) { + if (token) { + switch (token.parent.kind) { + case 240 /* ClassDeclaration */: + if (token.parent.name === token) { + return 11 /* className */; + } + return; + case 150 /* TypeParameter */: + if (token.parent.name === token) { + return 15 /* typeParameterName */; + } + return; + case 241 /* InterfaceDeclaration */: + if (token.parent.name === token) { + return 13 /* interfaceName */; + } + return; + case 243 /* EnumDeclaration */: + if (token.parent.name === token) { + return 12 /* enumName */; + } + return; + case 244 /* ModuleDeclaration */: + if (token.parent.name === token) { + return 14 /* moduleName */; + } + return; + case 151 /* Parameter */: + if (token.parent.name === token) { + return ts.isThisIdentifier(token) ? 3 /* keyword */ : 17 /* parameterName */; + } + return; + } + } + return 2 /* identifier */; + } + } + function processElement(element) { + if (!element) { + return; + } + // Ignore nodes that don't intersect the original span to classify. + if (ts.decodedTextSpanIntersectsWith(spanStart, spanLength, element.pos, element.getFullWidth())) { + checkForClassificationCancellation(cancellationToken, element.kind); + for (var _i = 0, _a = element.getChildren(sourceFile); _i < _a.length; _i++) { + var child = _a[_i]; + if (!tryClassifyNode(child)) { + // Recurse into our child nodes. + processElement(child); + } + } + } + } + } + ts.getEncodedSyntacticClassifications = getEncodedSyntacticClassifications; +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var Completions; + (function (Completions) { + var StringCompletions; + (function (StringCompletions) { + function getStringLiteralCompletions(sourceFile, position, contextToken, checker, options, host, log, preferences) { + if (ts.isInReferenceComment(sourceFile, position)) { + var entries = getTripleSlashReferenceCompletion(sourceFile, position, options, host); + return entries && convertPathCompletions(entries); + } + if (ts.isInString(sourceFile, position, contextToken)) { + return !contextToken || !ts.isStringLiteralLike(contextToken) + ? undefined + : convertStringLiteralCompletions(getStringLiteralCompletionEntries(sourceFile, contextToken, position, checker, options, host), sourceFile, checker, log, preferences); + } + } + StringCompletions.getStringLiteralCompletions = getStringLiteralCompletions; + function convertStringLiteralCompletions(completion, sourceFile, checker, log, preferences) { + if (completion === undefined) { + return undefined; + } + switch (completion.kind) { + case 0 /* Paths */: + return convertPathCompletions(completion.paths); + case 1 /* Properties */: { + var entries = []; + Completions.getCompletionEntriesFromSymbols(completion.symbols, entries, sourceFile, sourceFile, checker, 6 /* ESNext */, log, 4 /* String */, preferences); // Target will not be used, so arbitrary + return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: completion.hasIndexSignature, entries: entries }; + } + case 2 /* Types */: { + var entries = completion.types.map(function (type) { return ({ name: type.value, kindModifiers: "" /* none */, kind: "string" /* string */, sortText: "0" }); }); + return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: completion.isNewIdentifier, entries: entries }; + } + default: + return ts.Debug.assertNever(completion); + } + } + function getStringLiteralCompletionDetails(name, sourceFile, position, contextToken, checker, options, host, cancellationToken) { + if (!contextToken || !ts.isStringLiteralLike(contextToken)) + return undefined; + var completions = getStringLiteralCompletionEntries(sourceFile, contextToken, position, checker, options, host); + return completions && stringLiteralCompletionDetails(name, contextToken, completions, sourceFile, checker, cancellationToken); + } + StringCompletions.getStringLiteralCompletionDetails = getStringLiteralCompletionDetails; + function stringLiteralCompletionDetails(name, location, completion, sourceFile, checker, cancellationToken) { + switch (completion.kind) { + case 0 /* Paths */: { + var match = ts.find(completion.paths, function (p) { return p.name === name; }); + return match && Completions.createCompletionDetails(name, kindModifiersFromExtension(match.extension), match.kind, [ts.textPart(name)]); + } + case 1 /* Properties */: { + var match = ts.find(completion.symbols, function (s) { return s.name === name; }); + return match && Completions.createCompletionDetailsForSymbol(match, checker, sourceFile, location, cancellationToken); + } + case 2 /* Types */: + return ts.find(completion.types, function (t) { return t.value === name; }) ? Completions.createCompletionDetails(name, "" /* none */, "type" /* typeElement */, [ts.textPart(name)]) : undefined; + default: + return ts.Debug.assertNever(completion); + } + } + function convertPathCompletions(pathCompletions) { + var isGlobalCompletion = false; // We don't want the editor to offer any other completions, such as snippets, inside a comment. + var isNewIdentifierLocation = true; // The user may type in a path that doesn't yet exist, creating a "new identifier" with respect to the collection of identifiers the server is aware of. + var entries = pathCompletions.map(function (_a) { + var name = _a.name, kind = _a.kind, span = _a.span, extension = _a.extension; + return ({ name: name, kind: kind, kindModifiers: kindModifiersFromExtension(extension), sortText: "0", replacementSpan: span }); + }); + return { isGlobalCompletion: isGlobalCompletion, isMemberCompletion: false, isNewIdentifierLocation: isNewIdentifierLocation, entries: entries }; + } + function kindModifiersFromExtension(extension) { + switch (extension) { + case ".d.ts" /* Dts */: return ".d.ts" /* dtsModifier */; + case ".js" /* Js */: return ".js" /* jsModifier */; + case ".json" /* Json */: return ".json" /* jsonModifier */; + case ".jsx" /* Jsx */: return ".jsx" /* jsxModifier */; + case ".ts" /* Ts */: return ".ts" /* tsModifier */; + case ".tsx" /* Tsx */: return ".tsx" /* tsxModifier */; + case undefined: return "" /* none */; + default: + return ts.Debug.assertNever(extension); + } + } + var StringLiteralCompletionKind; + (function (StringLiteralCompletionKind) { + StringLiteralCompletionKind[StringLiteralCompletionKind["Paths"] = 0] = "Paths"; + StringLiteralCompletionKind[StringLiteralCompletionKind["Properties"] = 1] = "Properties"; + StringLiteralCompletionKind[StringLiteralCompletionKind["Types"] = 2] = "Types"; + })(StringLiteralCompletionKind || (StringLiteralCompletionKind = {})); + function getStringLiteralCompletionEntries(sourceFile, node, position, typeChecker, compilerOptions, host) { + var parent = node.parent; + switch (parent.kind) { + case 182 /* LiteralType */: + switch (parent.parent.kind) { + case 164 /* TypeReference */: + return { kind: 2 /* Types */, types: getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(parent)), isNewIdentifier: false }; + case 180 /* IndexedAccessType */: + // Get all apparent property names + // i.e. interface Foo { + // foo: string; + // bar: string; + // } + // let x: Foo["/*completion position*/"] + return stringLiteralCompletionsFromProperties(typeChecker.getTypeFromTypeNode(parent.parent.objectType)); + case 183 /* ImportType */: + return { kind: 0 /* Paths */, paths: getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker) }; + case 173 /* UnionType */: { + if (!ts.isTypeReferenceNode(parent.parent.parent)) + return undefined; + var alreadyUsedTypes_1 = getAlreadyUsedTypesInStringLiteralUnion(parent.parent, parent); + var types = getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(parent.parent)).filter(function (t) { return !ts.contains(alreadyUsedTypes_1, t.value); }); + return { kind: 2 /* Types */, types: types, isNewIdentifier: false }; + } + default: + return undefined; + } + case 275 /* PropertyAssignment */: + if (ts.isObjectLiteralExpression(parent.parent) && parent.name === node) { + // Get quoted name of properties of the object literal expression + // i.e. interface ConfigFiles { + // 'jspm:dev': string + // } + // let files: ConfigFiles = { + // '/*completion position*/' + // } + // + // function foo(c: ConfigFiles) {} + // foo({ + // '/*completion position*/' + // }); + return stringLiteralCompletionsFromProperties(typeChecker.getContextualType(parent.parent)); + } + return fromContextualType(); + case 190 /* ElementAccessExpression */: { + var _a = parent, expression = _a.expression, argumentExpression = _a.argumentExpression; + if (node === argumentExpression) { + // Get all names of properties on the expression + // i.e. interface A { + // 'prop1': string + // } + // let a: A; + // a['/*completion position*/'] + return stringLiteralCompletionsFromProperties(typeChecker.getTypeAtLocation(expression)); + } + return undefined; + } + case 191 /* CallExpression */: + case 192 /* NewExpression */: + if (!ts.isRequireCall(parent, /*checkArgumentIsStringLiteralLike*/ false) && !ts.isImportCall(parent)) { + var argumentInfo = ts.SignatureHelp.getArgumentInfoForCompletions(node, position, sourceFile); + // Get string literal completions from specialized signatures of the target + // i.e. declare function f(a: 'A'); + // f("/*completion position*/") + return argumentInfo ? getStringLiteralCompletionsFromSignature(argumentInfo, typeChecker) : fromContextualType(); + } + // falls through (is `require("")` or `import("")`) + case 249 /* ImportDeclaration */: + case 255 /* ExportDeclaration */: + case 259 /* ExternalModuleReference */: + // Get all known external module names or complete a path to a module + // i.e. import * as ns from "/*completion position*/"; + // var y = import("/*completion position*/"); + // import x = require("/*completion position*/"); + // var y = require("/*completion position*/"); + // export * from "/*completion position*/"; + return { kind: 0 /* Paths */, paths: getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker) }; + default: + return fromContextualType(); + } + function fromContextualType() { + // Get completion for string literal from string literal type + // i.e. var x: "hi" | "hello" = "/*completion position*/" + return { kind: 2 /* Types */, types: getStringLiteralTypes(ts.getContextualTypeFromParent(node, typeChecker)), isNewIdentifier: false }; + } + } + function getAlreadyUsedTypesInStringLiteralUnion(union, current) { + return ts.mapDefined(union.types, function (type) { + return type !== current && ts.isLiteralTypeNode(type) && ts.isStringLiteral(type.literal) ? type.literal.text : undefined; + }); + } + function getStringLiteralCompletionsFromSignature(argumentInfo, checker) { + var isNewIdentifier = false; + var uniques = ts.createMap(); + var candidates = []; + checker.getResolvedSignature(argumentInfo.invocation, candidates, argumentInfo.argumentCount); + var types = ts.flatMap(candidates, function (candidate) { + if (!candidate.hasRestParameter && argumentInfo.argumentCount > candidate.parameters.length) + return; + var type = checker.getParameterType(candidate, argumentInfo.argumentIndex); + isNewIdentifier = isNewIdentifier || !!(type.flags & 4 /* String */); + return getStringLiteralTypes(type, uniques); + }); + return { kind: 2 /* Types */, types: types, isNewIdentifier: isNewIdentifier }; + } + function stringLiteralCompletionsFromProperties(type) { + return type && { kind: 1 /* Properties */, symbols: type.getApparentProperties(), hasIndexSignature: ts.hasIndexSignature(type) }; + } + function getStringLiteralTypes(type, uniques) { + if (uniques === void 0) { uniques = ts.createMap(); } + if (!type) + return ts.emptyArray; + type = ts.skipConstraint(type); + return type.isUnion() + ? ts.flatMap(type.types, function (t) { return getStringLiteralTypes(t, uniques); }) + : type.isStringLiteral() && !(type.flags & 1024 /* EnumLiteral */) && ts.addToSeen(uniques, type.value) + ? [type] + : ts.emptyArray; + } + function nameAndKind(name, kind, extension) { + return { name: name, kind: kind, extension: extension }; + } + function directoryResult(name) { + return nameAndKind(name, "directory" /* directory */, /*extension*/ undefined); + } + function addReplacementSpans(text, textStart, names) { + var span = getDirectoryFragmentTextSpan(text, textStart); + return names.map(function (_a) { + var name = _a.name, kind = _a.kind, extension = _a.extension; + return ({ name: name, kind: kind, extension: extension, span: span }); + }); + } + function getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker) { + return addReplacementSpans(node.text, node.getStart(sourceFile) + 1, getStringLiteralCompletionsFromModuleNamesWorker(sourceFile, node, compilerOptions, host, typeChecker)); + } + function getStringLiteralCompletionsFromModuleNamesWorker(sourceFile, node, compilerOptions, host, typeChecker) { + var literalValue = ts.normalizeSlashes(node.text); + var scriptPath = sourceFile.path; + var scriptDirectory = ts.getDirectoryPath(scriptPath); + return isPathRelativeToScript(literalValue) || !compilerOptions.baseUrl && (ts.isRootedDiskPath(literalValue) || ts.isUrl(literalValue)) + ? getCompletionEntriesForRelativeModules(literalValue, scriptDirectory, compilerOptions, host, scriptPath) + : getCompletionEntriesForNonRelativeModules(literalValue, scriptDirectory, compilerOptions, host, typeChecker); + } + function getExtensionOptions(compilerOptions, includeExtensions) { + if (includeExtensions === void 0) { includeExtensions = false; } + return { extensions: getSupportedExtensionsForModuleResolution(compilerOptions), includeExtensions: includeExtensions }; + } + function getCompletionEntriesForRelativeModules(literalValue, scriptDirectory, compilerOptions, host, scriptPath) { + var extensionOptions = getExtensionOptions(compilerOptions); + if (compilerOptions.rootDirs) { + return getCompletionEntriesForDirectoryFragmentWithRootDirs(compilerOptions.rootDirs, literalValue, scriptDirectory, extensionOptions, compilerOptions, host, scriptPath); + } + else { + return getCompletionEntriesForDirectoryFragment(literalValue, scriptDirectory, extensionOptions, host, scriptPath); + } + } + function getSupportedExtensionsForModuleResolution(compilerOptions) { + var extensions = ts.getSupportedExtensions(compilerOptions); + return compilerOptions.resolveJsonModule && ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs ? + extensions.concat(".json" /* Json */) : + extensions; + } + /** + * Takes a script path and returns paths for all potential folders that could be merged with its + * containing folder via the "rootDirs" compiler option + */ + function getBaseDirectoriesFromRootDirs(rootDirs, basePath, scriptDirectory, ignoreCase) { + // Make all paths absolute/normalized if they are not already + rootDirs = rootDirs.map(function (rootDirectory) { return ts.normalizePath(ts.isRootedDiskPath(rootDirectory) ? rootDirectory : ts.combinePaths(basePath, rootDirectory)); }); + // Determine the path to the directory containing the script relative to the root directory it is contained within + var relativeDirectory = ts.firstDefined(rootDirs, function (rootDirectory) { + return ts.containsPath(rootDirectory, scriptDirectory, basePath, ignoreCase) ? scriptDirectory.substr(rootDirectory.length) : undefined; + }); // TODO: GH#18217 + // Now find a path for each potential directory that is to be merged with the one containing the script + return ts.deduplicate(rootDirs.map(function (rootDirectory) { return ts.combinePaths(rootDirectory, relativeDirectory); }).concat([scriptDirectory]), ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive); + } + function getCompletionEntriesForDirectoryFragmentWithRootDirs(rootDirs, fragment, scriptDirectory, extensionOptions, compilerOptions, host, exclude) { + var basePath = compilerOptions.project || host.getCurrentDirectory(); + var ignoreCase = !(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames()); + var baseDirectories = getBaseDirectoriesFromRootDirs(rootDirs, basePath, scriptDirectory, ignoreCase); + return ts.flatMap(baseDirectories, function (baseDirectory) { return getCompletionEntriesForDirectoryFragment(fragment, baseDirectory, extensionOptions, host, exclude); }); + } + /** + * Given a path ending at a directory, gets the completions for the path, and filters for those entries containing the basename. + */ + function getCompletionEntriesForDirectoryFragment(fragment, scriptPath, _a, host, exclude, result) { + var extensions = _a.extensions, includeExtensions = _a.includeExtensions; + if (result === void 0) { result = []; } + if (fragment === undefined) { + fragment = ""; + } + fragment = ts.normalizeSlashes(fragment); + /** + * Remove the basename from the path. Note that we don't use the basename to filter completions; + * the client is responsible for refining completions. + */ + if (!ts.hasTrailingDirectorySeparator(fragment)) { + fragment = ts.getDirectoryPath(fragment); + } + if (fragment === "") { + fragment = "." + ts.directorySeparator; + } + fragment = ts.ensureTrailingDirectorySeparator(fragment); + // const absolutePath = normalizeAndPreserveTrailingSlash(isRootedDiskPath(fragment) ? fragment : combinePaths(scriptPath, fragment)); // TODO(rbuckton): should use resolvePaths + var absolutePath = ts.resolvePath(scriptPath, fragment); + var baseDirectory = ts.hasTrailingDirectorySeparator(absolutePath) ? absolutePath : ts.getDirectoryPath(absolutePath); + var ignoreCase = !(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames()); + if (!tryDirectoryExists(host, baseDirectory)) + return result; + // Enumerate the available files if possible + var files = tryReadDirectory(host, baseDirectory, extensions, /*exclude*/ undefined, /*include*/ ["./*"]); + if (files) { + /** + * Multiple file entries might map to the same truncated name once we remove extensions + * (happens iff includeExtensions === false)so we use a set-like data structure. Eg: + * + * both foo.ts and foo.tsx become foo + */ + var foundFiles = ts.createMap(); // maps file to its extension + for (var _i = 0, files_3 = files; _i < files_3.length; _i++) { + var filePath = files_3[_i]; + filePath = ts.normalizePath(filePath); + if (exclude && ts.comparePaths(filePath, exclude, scriptPath, ignoreCase) === 0 /* EqualTo */) { + continue; + } + var foundFileName = includeExtensions || ts.fileExtensionIs(filePath, ".json" /* Json */) ? ts.getBaseFileName(filePath) : ts.removeFileExtension(ts.getBaseFileName(filePath)); + foundFiles.set(foundFileName, ts.tryGetExtensionFromPath(filePath)); + } + foundFiles.forEach(function (ext, foundFile) { + result.push(nameAndKind(foundFile, "script" /* scriptElement */, ext)); + }); + } + // If possible, get folder completion as well + var directories = tryGetDirectories(host, baseDirectory); + if (directories) { + for (var _b = 0, directories_1 = directories; _b < directories_1.length; _b++) { + var directory = directories_1[_b]; + var directoryName = ts.getBaseFileName(ts.normalizePath(directory)); + if (directoryName !== "@types") { + result.push(directoryResult(directoryName)); + } + } + } + // check for a version redirect + var packageJsonPath = findPackageJson(baseDirectory, host); + if (packageJsonPath) { + var packageJson = ts.readJson(packageJsonPath, host); + var typesVersions = packageJson.typesVersions; + if (typeof typesVersions === "object") { + var versionResult = ts.getPackageJsonTypesVersionsPaths(typesVersions); + var versionPaths = versionResult && versionResult.paths; + var rest = absolutePath.slice(ts.ensureTrailingDirectorySeparator(baseDirectory).length); + if (versionPaths) { + addCompletionEntriesFromPaths(result, rest, baseDirectory, extensions, versionPaths, host); + } + } + } + return result; + } + function addCompletionEntriesFromPaths(result, fragment, baseDirectory, fileExtensions, paths, host) { + for (var path in paths) { + if (!ts.hasProperty(paths, path)) + continue; + var patterns = paths[path]; + if (patterns) { + var _loop_10 = function (name, kind, extension) { + // Path mappings may provide a duplicate way to get to something we've already added, so don't add again. + if (!result.some(function (entry) { return entry.name === name; })) { + result.push(nameAndKind(name, kind, extension)); + } + }; + for (var _i = 0, _a = getCompletionsForPathMapping(path, patterns, fragment, baseDirectory, fileExtensions, host); _i < _a.length; _i++) { + var _b = _a[_i], name = _b.name, kind = _b.kind, extension = _b.extension; + _loop_10(name, kind, extension); + } + } + } + } + /** + * Check all of the declared modules and those in node modules. Possible sources of modules: + * Modules that are found by the type checker + * Modules found relative to "baseUrl" compliler options (including patterns from "paths" compiler option) + * Modules from node_modules (i.e. those listed in package.json) + * This includes all files that are found in node_modules/moduleName/ with acceptable file extensions + */ + function getCompletionEntriesForNonRelativeModules(fragment, scriptPath, compilerOptions, host, typeChecker) { + var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths; + var result = []; + var extensionOptions = getExtensionOptions(compilerOptions); + if (baseUrl) { + var projectDir = compilerOptions.project || host.getCurrentDirectory(); + var absolute = ts.normalizePath(ts.combinePaths(projectDir, baseUrl)); + getCompletionEntriesForDirectoryFragment(fragment, absolute, extensionOptions, host, /*exclude*/ undefined, result); + if (paths) { + addCompletionEntriesFromPaths(result, fragment, absolute, extensionOptions.extensions, paths, host); + } + } + var fragmentDirectory = getFragmentDirectory(fragment); + for (var _i = 0, _a = getAmbientModuleCompletions(fragment, fragmentDirectory, typeChecker); _i < _a.length; _i++) { + var ambientName = _a[_i]; + result.push(nameAndKind(ambientName, "external module name" /* externalModuleName */, /*extension*/ undefined)); + } + getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, fragmentDirectory, extensionOptions, result); + if (ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs) { + // If looking for a global package name, don't just include everything in `node_modules` because that includes dependencies' own dependencies. + // (But do if we didn't find anything, e.g. 'package.json' missing.) + var foundGlobal = false; + if (fragmentDirectory === undefined) { + var _loop_11 = function (moduleName) { + if (!result.some(function (entry) { return entry.name === moduleName; })) { + foundGlobal = true; + result.push(nameAndKind(moduleName, "external module name" /* externalModuleName */, /*extension*/ undefined)); + } + }; + for (var _b = 0, _c = enumerateNodeModulesVisibleToScript(host, scriptPath); _b < _c.length; _b++) { + var moduleName = _c[_b]; + _loop_11(moduleName); + } + } + if (!foundGlobal) { + ts.forEachAncestorDirectory(scriptPath, function (ancestor) { + var nodeModules = ts.combinePaths(ancestor, "node_modules"); + if (tryDirectoryExists(host, nodeModules)) { + getCompletionEntriesForDirectoryFragment(fragment, nodeModules, extensionOptions, host, /*exclude*/ undefined, result); + } + }); + } + } + return result; + } + function getFragmentDirectory(fragment) { + return containsSlash(fragment) ? ts.hasTrailingDirectorySeparator(fragment) ? fragment : ts.getDirectoryPath(fragment) : undefined; + } + function getCompletionsForPathMapping(path, patterns, fragment, baseUrl, fileExtensions, host) { + if (!ts.endsWith(path, "*")) { + // For a path mapping "foo": ["/x/y/z.ts"], add "foo" itself as a completion. + return !ts.stringContains(path, "*") ? justPathMappingName(path) : ts.emptyArray; + } + var pathPrefix = path.slice(0, path.length - 1); + var remainingFragment = ts.tryRemovePrefix(fragment, pathPrefix); + return remainingFragment === undefined ? justPathMappingName(pathPrefix) : ts.flatMap(patterns, function (pattern) { + return getModulesForPathsPattern(remainingFragment, baseUrl, pattern, fileExtensions, host); + }); + function justPathMappingName(name) { + return ts.startsWith(name, fragment) ? [directoryResult(name)] : ts.emptyArray; + } + } + function getModulesForPathsPattern(fragment, baseUrl, pattern, fileExtensions, host) { + if (!host.readDirectory) { + return undefined; + } + var parsed = ts.hasZeroOrOneAsteriskCharacter(pattern) ? ts.tryParsePattern(pattern) : undefined; + if (!parsed) { + return undefined; + } + // The prefix has two effective parts: the directory path and the base component after the filepath that is not a + // full directory component. For example: directory/path/of/prefix/base* + var normalizedPrefix = ts.resolvePath(parsed.prefix); + var normalizedPrefixDirectory = ts.hasTrailingDirectorySeparator(parsed.prefix) ? normalizedPrefix : ts.getDirectoryPath(normalizedPrefix); + var normalizedPrefixBase = ts.hasTrailingDirectorySeparator(parsed.prefix) ? "" : ts.getBaseFileName(normalizedPrefix); + var fragmentHasPath = containsSlash(fragment); + var fragmentDirectory = fragmentHasPath ? ts.hasTrailingDirectorySeparator(fragment) ? fragment : ts.getDirectoryPath(fragment) : undefined; + // Try and expand the prefix to include any path from the fragment so that we can limit the readDirectory call + var expandedPrefixDirectory = fragmentHasPath ? ts.combinePaths(normalizedPrefixDirectory, normalizedPrefixBase + fragmentDirectory) : normalizedPrefixDirectory; + var normalizedSuffix = ts.normalizePath(parsed.suffix); + // Need to normalize after combining: If we combinePaths("a", "../b"), we want "b" and not "a/../b". + var baseDirectory = ts.normalizePath(ts.combinePaths(baseUrl, expandedPrefixDirectory)); + var completePrefix = fragmentHasPath ? baseDirectory : ts.ensureTrailingDirectorySeparator(baseDirectory) + normalizedPrefixBase; + // If we have a suffix, then we need to read the directory all the way down. We could create a glob + // that encodes the suffix, but we would have to escape the character "?" which readDirectory + // doesn't support. For now, this is safer but slower + var includeGlob = normalizedSuffix ? "**/*" : "./*"; + var matches = ts.mapDefined(tryReadDirectory(host, baseDirectory, fileExtensions, /*exclude*/ undefined, [includeGlob]), function (match) { + var extension = ts.tryGetExtensionFromPath(match); + var name = trimPrefixAndSuffix(match); + return name === undefined ? undefined : nameAndKind(ts.removeFileExtension(name), "script" /* scriptElement */, extension); + }); + var directories = ts.mapDefined(tryGetDirectories(host, baseDirectory).map(function (d) { return ts.combinePaths(baseDirectory, d); }), function (dir) { + var name = trimPrefixAndSuffix(dir); + return name === undefined ? undefined : directoryResult(name); + }); + return matches.concat(directories); + function trimPrefixAndSuffix(path) { + var inner = withoutStartAndEnd(ts.normalizePath(path), completePrefix, normalizedSuffix); + return inner === undefined ? undefined : removeLeadingDirectorySeparator(inner); + } + } + function withoutStartAndEnd(s, start, end) { + return ts.startsWith(s, start) && ts.endsWith(s, end) ? s.slice(start.length, s.length - end.length) : undefined; + } + function removeLeadingDirectorySeparator(path) { + return path[0] === ts.directorySeparator ? path.slice(1) : path; + } + function getAmbientModuleCompletions(fragment, fragmentDirectory, checker) { + // Get modules that the type checker picked up + var ambientModules = checker.getAmbientModules().map(function (sym) { return ts.stripQuotes(sym.name); }); + var nonRelativeModuleNames = ambientModules.filter(function (moduleName) { return ts.startsWith(moduleName, fragment); }); + // Nested modules of the form "module-name/sub" need to be adjusted to only return the string + // after the last '/' that appears in the fragment because that's where the replacement span + // starts + if (fragmentDirectory !== undefined) { + var moduleNameWithSeparator_1 = ts.ensureTrailingDirectorySeparator(fragmentDirectory); + return nonRelativeModuleNames.map(function (nonRelativeModuleName) { return ts.removePrefix(nonRelativeModuleName, moduleNameWithSeparator_1); }); + } + return nonRelativeModuleNames; + } + function getTripleSlashReferenceCompletion(sourceFile, position, compilerOptions, host) { + var token = ts.getTokenAtPosition(sourceFile, position); + var commentRanges = ts.getLeadingCommentRanges(sourceFile.text, token.pos); + var range = commentRanges && ts.find(commentRanges, function (commentRange) { return position >= commentRange.pos && position <= commentRange.end; }); + if (!range) { + return undefined; + } + var text = sourceFile.text.slice(range.pos, position); + var match = tripleSlashDirectiveFragmentRegex.exec(text); + if (!match) { + return undefined; + } + var prefix = match[1], kind = match[2], toComplete = match[3]; + var scriptPath = ts.getDirectoryPath(sourceFile.path); + var names = kind === "path" ? getCompletionEntriesForDirectoryFragment(toComplete, scriptPath, getExtensionOptions(compilerOptions, /*includeExtensions*/ true), host, sourceFile.path) + : kind === "types" ? getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, getFragmentDirectory(toComplete), getExtensionOptions(compilerOptions)) + : ts.Debug.fail(); + return addReplacementSpans(toComplete, range.pos + prefix.length, names); + } + function getCompletionEntriesFromTypings(host, options, scriptPath, fragmentDirectory, extensionOptions, result) { + if (result === void 0) { result = []; } + // Check for typings specified in compiler options + var seen = ts.createMap(); + var typeRoots = tryAndIgnoreErrors(function () { return ts.getEffectiveTypeRoots(options, host); }) || ts.emptyArray; + for (var _i = 0, typeRoots_2 = typeRoots; _i < typeRoots_2.length; _i++) { + var root = typeRoots_2[_i]; + getCompletionEntriesFromDirectories(root); + } + // Also get all @types typings installed in visible node_modules directories + for (var _a = 0, _b = findPackageJsons(scriptPath, host); _a < _b.length; _a++) { + var packageJson = _b[_a]; + var typesDir = ts.combinePaths(ts.getDirectoryPath(packageJson), "node_modules/@types"); + getCompletionEntriesFromDirectories(typesDir); + } + return result; + function getCompletionEntriesFromDirectories(directory) { + if (!tryDirectoryExists(host, directory)) + return; + for (var _i = 0, _a = tryGetDirectories(host, directory); _i < _a.length; _i++) { + var typeDirectoryName = _a[_i]; + var packageName = ts.unmangleScopedPackageName(typeDirectoryName); + if (options.types && !ts.contains(options.types, packageName)) + continue; + if (fragmentDirectory === undefined) { + if (!seen.has(packageName)) { + result.push(nameAndKind(packageName, "external module name" /* externalModuleName */, /*extension*/ undefined)); + seen.set(packageName, true); + } + } + else { + var baseDirectory = ts.combinePaths(directory, typeDirectoryName); + var remainingFragment = ts.tryRemoveDirectoryPrefix(fragmentDirectory, packageName, ts.hostGetCanonicalFileName(host)); + if (remainingFragment !== undefined) { + getCompletionEntriesForDirectoryFragment(remainingFragment, baseDirectory, extensionOptions, host, /*exclude*/ undefined, result); + } + } + } + } + } + function findPackageJsons(directory, host) { + var paths = []; + ts.forEachAncestorDirectory(directory, function (ancestor) { + var currentConfigPath = ts.findConfigFile(ancestor, function (f) { return tryFileExists(host, f); }, "package.json"); + if (!currentConfigPath) { + return true; // break out + } + paths.push(currentConfigPath); + }); + return paths; + } + function findPackageJson(directory, host) { + var packageJson; + ts.forEachAncestorDirectory(directory, function (ancestor) { + if (ancestor === "node_modules") + return true; + packageJson = ts.findConfigFile(ancestor, function (f) { return tryFileExists(host, f); }, "package.json"); + if (packageJson) { + return true; // break out + } + }); + return packageJson; + } + function enumerateNodeModulesVisibleToScript(host, scriptPath) { + if (!host.readFile || !host.fileExists) + return ts.emptyArray; + var result = []; + for (var _i = 0, _a = findPackageJsons(scriptPath, host); _i < _a.length; _i++) { + var packageJson = _a[_i]; + var contents = ts.readJson(packageJson, host); // Cast to assert that readFile is defined + // Provide completions for all non @types dependencies + for (var _b = 0, nodeModulesDependencyKeys_1 = nodeModulesDependencyKeys; _b < nodeModulesDependencyKeys_1.length; _b++) { + var key = nodeModulesDependencyKeys_1[_b]; + var dependencies = contents[key]; + if (!dependencies) + continue; + for (var dep in dependencies) { + if (dependencies.hasOwnProperty(dep) && !ts.startsWith(dep, "@types/")) { + result.push(dep); + } + } + } + } + return result; + } + // Replace everything after the last directory separator that appears + function getDirectoryFragmentTextSpan(text, textStart) { + var index = Math.max(text.lastIndexOf(ts.directorySeparator), text.lastIndexOf("\\")); + var offset = index !== -1 ? index + 1 : 0; + // If the range is an identifier, span is unnecessary. + var length = text.length - offset; + return length === 0 || ts.isIdentifierText(text.substr(offset, length), 6 /* ESNext */) ? undefined : ts.createTextSpan(textStart + offset, length); + } + // Returns true if the path is explicitly relative to the script (i.e. relative to . or ..) + function isPathRelativeToScript(path) { + if (path && path.length >= 2 && path.charCodeAt(0) === 46 /* dot */) { + var slashIndex = path.length >= 3 && path.charCodeAt(1) === 46 /* dot */ ? 2 : 1; + var slashCharCode = path.charCodeAt(slashIndex); + return slashCharCode === 47 /* slash */ || slashCharCode === 92 /* backslash */; + } + return false; + } + /** + * Matches a triple slash reference directive with an incomplete string literal for its path. Used + * to determine if the caret is currently within the string literal and capture the literal fragment + * for completions. + * For example, this matches + * + * /// " with type any + // And at `
      ` (with a closing `>`), the completion list will contain "div". + var tagName = location.parent.parent.openingElement.tagName; + var hasClosingAngleBracket = !!ts.findChildOfKind(location.parent, 30 /* GreaterThanToken */, sourceFile); + var entry = { + name: tagName.getFullText(sourceFile) + (hasClosingAngleBracket ? "" : ">"), + kind: "class" /* classElement */, + kindModifiers: undefined, + sortText: "0", + }; + return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: false, entries: [entry] }; + } + var entries = []; + if (isUncheckedFile(sourceFile, compilerOptions)) { + var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, preferences, propertyAccessToConvert, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap); + getJSCompletionEntries(sourceFile, location.pos, uniqueNames, compilerOptions.target, entries); // TODO: GH#18217 + } + else { + if ((!symbols || symbols.length === 0) && keywordFilters === 0 /* None */) { + return undefined; + } + getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, preferences, propertyAccessToConvert, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap); + } + if (keywordFilters !== 0 /* None */) { + var entryNames = ts.arrayToSet(entries, function (e) { return e.name; }); + for (var _i = 0, _a = getKeywordCompletions(keywordFilters); _i < _a.length; _i++) { + var keywordEntry = _a[_i]; + if (!entryNames.has(keywordEntry.name)) { + entries.push(keywordEntry); + } + } + } + for (var _b = 0, literals_1 = literals; _b < literals_1.length; _b++) { + var literal = literals_1[_b]; + entries.push(createCompletionEntryForLiteral(literal)); + } + return { isGlobalCompletion: isInSnippetScope, isMemberCompletion: isMemberCompletionKind(completionKind), isNewIdentifierLocation: isNewIdentifierLocation, entries: entries }; + } + function isUncheckedFile(sourceFile, compilerOptions) { + return ts.isSourceFileJS(sourceFile) && !ts.isCheckJsEnabledForFile(sourceFile, compilerOptions); + } + function isMemberCompletionKind(kind) { + switch (kind) { + case 0 /* ObjectPropertyDeclaration */: + case 3 /* MemberLike */: + case 2 /* PropertyAccess */: + return true; + default: + return false; + } + } + function getJSCompletionEntries(sourceFile, position, uniqueNames, target, entries) { + ts.getNameTable(sourceFile).forEach(function (pos, name) { + // Skip identifiers produced only from the current location + if (pos === position) { + return; + } + var realName = ts.unescapeLeadingUnderscores(name); + if (ts.addToSeen(uniqueNames, realName) && ts.isIdentifierText(realName, target)) { + entries.push({ + name: realName, + kind: "warning" /* warning */, + kindModifiers: "", + sortText: "1" + }); + } + }); + } + var completionNameForLiteral = function (literal) { + return typeof literal === "object" ? ts.pseudoBigIntToString(literal) + "n" : JSON.stringify(literal); + }; + function createCompletionEntryForLiteral(literal) { + return { name: completionNameForLiteral(literal), kind: "string" /* string */, kindModifiers: "" /* none */, sortText: "0" }; + } + function createCompletionEntry(symbol, location, sourceFile, typeChecker, target, kind, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, preferences) { + var info = getCompletionEntryDisplayNameForSymbol(symbol, target, origin, kind); + if (!info) { + return undefined; + } + var name = info.name, needsConvertPropertyAccess = info.needsConvertPropertyAccess; + var insertText; + var replacementSpan; + if (origin && origin.kind === 0 /* ThisType */) { + insertText = needsConvertPropertyAccess ? "this[" + ts.quote(name, preferences) + "]" : "this." + name; + } + // We should only have needsConvertPropertyAccess if there's a property access to convert. But see #21790. + // Somehow there was a global with a non-identifier name. Hopefully someone will complain about getting a "foo bar" global completion and provide a repro. + else if ((origin && originIsSymbolMember(origin) || needsConvertPropertyAccess) && propertyAccessToConvert) { + insertText = needsConvertPropertyAccess ? "[" + ts.quote(name, preferences) + "]" : "[" + name + "]"; + var dot = ts.findChildOfKind(propertyAccessToConvert, 24 /* DotToken */, sourceFile); + // If the text after the '.' starts with this name, write over it. Else, add new text. + var end = ts.startsWith(name, propertyAccessToConvert.name.text) ? propertyAccessToConvert.name.end : dot.end; + replacementSpan = ts.createTextSpanFromBounds(dot.getStart(sourceFile), end); + } + if (isJsxInitializer) { + if (insertText === undefined) + insertText = name; + insertText = "{" + insertText + "}"; + if (typeof isJsxInitializer !== "boolean") { + replacementSpan = ts.createTextSpanFromNode(isJsxInitializer, sourceFile); + } + } + if (insertText !== undefined && !preferences.includeCompletionsWithInsertText) { + return undefined; + } + // TODO(drosen): Right now we just permit *all* semantic meanings when calling + // 'getSymbolKind' which is permissible given that it is backwards compatible; but + // really we should consider passing the meaning for the node so that we don't report + // that a suggestion for a value is an interface. We COULD also just do what + // 'getSymbolModifiers' does, which is to use the first declaration. + // Use a 'sortText' of 0' so that all symbol completion entries come before any other + // entries (like JavaScript identifier entries). + return { + name: name, + kind: ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, location), + kindModifiers: ts.SymbolDisplay.getSymbolModifiers(symbol), + sortText: "0", + source: getSourceFromOrigin(origin), + hasAction: trueOrUndefined(!!origin && originIsExport(origin)), + isRecommended: trueOrUndefined(isRecommendedCompletionMatch(symbol, recommendedCompletion, typeChecker)), + insertText: insertText, + replacementSpan: replacementSpan, + }; + } + function isRecommendedCompletionMatch(localSymbol, recommendedCompletion, checker) { + return localSymbol === recommendedCompletion || + !!(localSymbol.flags & 1048576 /* ExportValue */) && checker.getExportSymbolOfSymbol(localSymbol) === recommendedCompletion; + } + function trueOrUndefined(b) { + return b ? true : undefined; + } + function getSourceFromOrigin(origin) { + return origin && originIsExport(origin) ? ts.stripQuotes(origin.moduleSymbol.name) : undefined; + } + function getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, target, log, kind, preferences, propertyAccessToConvert, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap) { + var start = ts.timestamp(); + // Tracks unique names. + // We don't set this for global variables or completions from external module exports, because we can have multiple of those. + // Based on the order we add things we will always see locals first, then globals, then module exports. + // So adding a completion for a local will prevent us from adding completions for external module exports sharing the same name. + var uniques = ts.createMap(); + for (var _i = 0, symbols_3 = symbols; _i < symbols_3.length; _i++) { + var symbol = symbols_3[_i]; + var origin = symbolToOriginInfoMap ? symbolToOriginInfoMap[ts.getSymbolId(symbol)] : undefined; + var entry = createCompletionEntry(symbol, location, sourceFile, typeChecker, target, kind, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, preferences); + if (!entry) { + continue; + } + var name = entry.name; + if (uniques.has(name)) { + continue; + } + // Latter case tests whether this is a global variable. + if (!origin && !(symbol.parent === undefined && !ts.some(symbol.declarations, function (d) { return d.getSourceFile() === location.getSourceFile(); }))) { // TODO: GH#18217 + uniques.set(name, true); + } + entries.push(entry); + } + log("getCompletionsAtPosition: getCompletionEntriesFromSymbols: " + (ts.timestamp() - start)); + return uniques; + } + Completions.getCompletionEntriesFromSymbols = getCompletionEntriesFromSymbols; + function getLabelCompletionAtPosition(node) { + var entries = getLabelStatementCompletions(node); + if (entries.length) { + return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries }; + } + } + function getLabelStatementCompletions(node) { + var entries = []; + var uniques = ts.createMap(); + var current = node; + while (current) { + if (ts.isFunctionLike(current)) { + break; + } + if (ts.isLabeledStatement(current)) { + var name = current.label.text; + if (!uniques.has(name)) { + uniques.set(name, true); + entries.push({ + name: name, + kindModifiers: "" /* none */, + kind: "label" /* label */, + sortText: "0" + }); + } + } + current = current.parent; + } + return entries; + } + function getSymbolCompletionFromEntryId(program, log, sourceFile, position, entryId) { + var compilerOptions = program.getCompilerOptions(); + var completionData = getCompletionData(program, log, sourceFile, isUncheckedFile(sourceFile, compilerOptions), position, { includeCompletionsForModuleExports: true, includeCompletionsWithInsertText: true }, entryId); + if (!completionData) { + return { type: "none" }; + } + if (completionData.kind !== 0 /* Data */) { + return { type: "request", request: completionData }; + } + var symbols = completionData.symbols, literals = completionData.literals, location = completionData.location, completionKind = completionData.completionKind, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap, previousToken = completionData.previousToken, isJsxInitializer = completionData.isJsxInitializer; + var literal = ts.find(literals, function (l) { return completionNameForLiteral(l) === entryId.name; }); + if (literal !== undefined) + return { type: "literal", literal: literal }; + // Find the symbol with the matching entry name. + // We don't need to perform character checks here because we're only comparing the + // name against 'entryName' (which is known to be good), not building a new + // completion entry. + return ts.firstDefined(symbols, function (symbol) { + var origin = symbolToOriginInfoMap[ts.getSymbolId(symbol)]; + var info = getCompletionEntryDisplayNameForSymbol(symbol, compilerOptions.target, origin, completionKind); + return info && info.name === entryId.name && getSourceFromOrigin(origin) === entryId.source + ? { type: "symbol", symbol: symbol, location: location, symbolToOriginInfoMap: symbolToOriginInfoMap, previousToken: previousToken, isJsxInitializer: isJsxInitializer } + : undefined; + }) || { type: "none" }; + } + function getSymbolName(symbol, origin, target) { + return origin && originIsExport(origin) && origin.isDefaultExport && symbol.escapedName === "default" /* Default */ + // Name of "export default foo;" is "foo". Name of "export default 0" is the filename converted to camelCase. + ? ts.firstDefined(symbol.declarations, function (d) { return ts.isExportAssignment(d) && ts.isIdentifier(d.expression) ? d.expression.text : undefined; }) + || ts.codefix.moduleSymbolToValidIdentifier(origin.moduleSymbol, target) + : symbol.name; + } + function getCompletionEntryDetails(program, log, sourceFile, position, entryId, host, formatContext, preferences, cancellationToken) { + var typeChecker = program.getTypeChecker(); + var compilerOptions = program.getCompilerOptions(); + var name = entryId.name; + var contextToken = ts.findPrecedingToken(position, sourceFile); + if (ts.isInString(sourceFile, position, contextToken)) { + return Completions.StringCompletions.getStringLiteralCompletionDetails(name, sourceFile, position, contextToken, typeChecker, compilerOptions, host, cancellationToken); + } + // Compute all the completion symbols again. + var symbolCompletion = getSymbolCompletionFromEntryId(program, log, sourceFile, position, entryId); + switch (symbolCompletion.type) { + case "request": { + var request = symbolCompletion.request; + switch (request.kind) { + case 1 /* JsDocTagName */: + return ts.JsDoc.getJSDocTagNameCompletionDetails(name); + case 2 /* JsDocTag */: + return ts.JsDoc.getJSDocTagCompletionDetails(name); + case 3 /* JsDocParameterName */: + return ts.JsDoc.getJSDocParameterNameCompletionDetails(name); + default: + return ts.Debug.assertNever(request); + } + } + case "symbol": { + var symbol = symbolCompletion.symbol, location = symbolCompletion.location, symbolToOriginInfoMap = symbolCompletion.symbolToOriginInfoMap, previousToken = symbolCompletion.previousToken; + var _a = getCompletionEntryCodeActionsAndSourceDisplay(symbolToOriginInfoMap, symbol, program, typeChecker, host, compilerOptions, sourceFile, position, previousToken, formatContext, preferences), codeActions = _a.codeActions, sourceDisplay = _a.sourceDisplay; + return createCompletionDetailsForSymbol(symbol, typeChecker, sourceFile, location, cancellationToken, codeActions, sourceDisplay); // TODO: GH#18217 + } + case "literal": { + var literal = symbolCompletion.literal; + return createSimpleDetails(completionNameForLiteral(literal), "string" /* string */, typeof literal === "string" ? ts.SymbolDisplayPartKind.stringLiteral : ts.SymbolDisplayPartKind.numericLiteral); + } + case "none": + // Didn't find a symbol with this name. See if we can find a keyword instead. + return allKeywordsCompletions().some(function (c) { return c.name === name; }) ? createSimpleDetails(name, "keyword" /* keyword */, ts.SymbolDisplayPartKind.keyword) : undefined; + default: + ts.Debug.assertNever(symbolCompletion); + } + } + Completions.getCompletionEntryDetails = getCompletionEntryDetails; + function createSimpleDetails(name, kind, kind2) { + return createCompletionDetails(name, "" /* none */, kind, [ts.displayPart(name, kind2)]); + } + function createCompletionDetailsForSymbol(symbol, checker, sourceFile, location, cancellationToken, codeActions, sourceDisplay) { + var _a = checker.runWithCancellationToken(cancellationToken, function (checker) { + return ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, sourceFile, location, location, 7 /* All */); + }), displayParts = _a.displayParts, documentation = _a.documentation, symbolKind = _a.symbolKind, tags = _a.tags; + return createCompletionDetails(symbol.name, ts.SymbolDisplay.getSymbolModifiers(symbol), symbolKind, displayParts, documentation, tags, codeActions, sourceDisplay); + } + Completions.createCompletionDetailsForSymbol = createCompletionDetailsForSymbol; + function createCompletionDetails(name, kindModifiers, kind, displayParts, documentation, tags, codeActions, source) { + return { name: name, kindModifiers: kindModifiers, kind: kind, displayParts: displayParts, documentation: documentation, tags: tags, codeActions: codeActions, source: source }; + } + Completions.createCompletionDetails = createCompletionDetails; + function getCompletionEntryCodeActionsAndSourceDisplay(symbolToOriginInfoMap, symbol, program, checker, host, compilerOptions, sourceFile, position, previousToken, formatContext, preferences) { + var symbolOriginInfo = symbolToOriginInfoMap[ts.getSymbolId(symbol)]; + if (!symbolOriginInfo || !originIsExport(symbolOriginInfo)) { + return { codeActions: undefined, sourceDisplay: undefined }; + } + var moduleSymbol = symbolOriginInfo.moduleSymbol; + var exportedSymbol = checker.getMergedSymbol(ts.skipAlias(symbol.exportSymbol || symbol, checker)); + var _a = ts.codefix.getImportCompletionAction(exportedSymbol, moduleSymbol, sourceFile, getSymbolName(symbol, symbolOriginInfo, compilerOptions.target), host, program, formatContext, previousToken && ts.isIdentifier(previousToken) ? previousToken.getStart(sourceFile) : position, preferences), moduleSpecifier = _a.moduleSpecifier, codeAction = _a.codeAction; + return { sourceDisplay: [ts.textPart(moduleSpecifier)], codeActions: [codeAction] }; + } + function getCompletionEntrySymbol(program, log, sourceFile, position, entryId) { + var completion = getSymbolCompletionFromEntryId(program, log, sourceFile, position, entryId); + return completion.type === "symbol" ? completion.symbol : undefined; + } + Completions.getCompletionEntrySymbol = getCompletionEntrySymbol; + var CompletionDataKind; + (function (CompletionDataKind) { + CompletionDataKind[CompletionDataKind["Data"] = 0] = "Data"; + CompletionDataKind[CompletionDataKind["JsDocTagName"] = 1] = "JsDocTagName"; + CompletionDataKind[CompletionDataKind["JsDocTag"] = 2] = "JsDocTag"; + CompletionDataKind[CompletionDataKind["JsDocParameterName"] = 3] = "JsDocParameterName"; + })(CompletionDataKind || (CompletionDataKind = {})); + var CompletionKind; + (function (CompletionKind) { + CompletionKind[CompletionKind["ObjectPropertyDeclaration"] = 0] = "ObjectPropertyDeclaration"; + CompletionKind[CompletionKind["Global"] = 1] = "Global"; + CompletionKind[CompletionKind["PropertyAccess"] = 2] = "PropertyAccess"; + CompletionKind[CompletionKind["MemberLike"] = 3] = "MemberLike"; + CompletionKind[CompletionKind["String"] = 4] = "String"; + CompletionKind[CompletionKind["None"] = 5] = "None"; + })(CompletionKind = Completions.CompletionKind || (Completions.CompletionKind = {})); + function getRecommendedCompletion(previousToken, contextualType, checker) { + // For a union, return the first one with a recommended completion. + return ts.firstDefined(contextualType && (contextualType.isUnion() ? contextualType.types : [contextualType]), function (type) { + var symbol = type && type.symbol; + // Don't include make a recommended completion for an abstract class + return symbol && (symbol.flags & (8 /* EnumMember */ | 384 /* Enum */ | 32 /* Class */) && !ts.isAbstractConstructorSymbol(symbol)) + ? getFirstSymbolInChain(symbol, previousToken, checker) + : undefined; + }); + } + function getContextualType(previousToken, position, sourceFile, checker) { + var parent = previousToken.parent; + switch (previousToken.kind) { + case 72 /* Identifier */: + return ts.getContextualTypeFromParent(previousToken, checker); + case 59 /* EqualsToken */: + switch (parent.kind) { + case 237 /* VariableDeclaration */: + return checker.getContextualType(parent.initializer); // TODO: GH#18217 + case 204 /* BinaryExpression */: + return checker.getTypeAtLocation(parent.left); + case 267 /* JsxAttribute */: + return checker.getContextualTypeForJsxAttribute(parent); + default: + return undefined; + } + case 95 /* NewKeyword */: + return checker.getContextualType(parent); + case 74 /* CaseKeyword */: + return ts.getSwitchedType(ts.cast(parent, ts.isCaseClause), checker); + case 18 /* OpenBraceToken */: + return ts.isJsxExpression(parent) && parent.parent.kind !== 260 /* JsxElement */ ? checker.getContextualTypeForJsxAttribute(parent.parent) : undefined; + default: + var argInfo = ts.SignatureHelp.getArgumentInfoForCompletions(previousToken, position, sourceFile); + return argInfo + // At `,`, treat this as the next argument after the comma. + ? checker.getContextualTypeForArgumentAtIndex(argInfo.invocation, argInfo.argumentIndex + (previousToken.kind === 27 /* CommaToken */ ? 1 : 0)) + : ts.isEqualityOperatorKind(previousToken.kind) && ts.isBinaryExpression(parent) && ts.isEqualityOperatorKind(parent.operatorToken.kind) + // completion at `x ===/**/` should be for the right side + ? checker.getTypeAtLocation(parent.left) + : checker.getContextualType(previousToken); + } + } + function getFirstSymbolInChain(symbol, enclosingDeclaration, checker) { + var chain = checker.getAccessibleSymbolChain(symbol, enclosingDeclaration, /*meaning*/ 67108863 /* All */, /*useOnlyExternalAliasing*/ false); + if (chain) + return ts.first(chain); + return symbol.parent && (isModuleSymbol(symbol.parent) ? symbol : getFirstSymbolInChain(symbol.parent, enclosingDeclaration, checker)); + } + function isModuleSymbol(symbol) { + return symbol.declarations.some(function (d) { return d.kind === 279 /* SourceFile */; }); + } + function getCompletionData(program, log, sourceFile, isUncheckedFile, position, preferences, detailsEntryId) { + var typeChecker = program.getTypeChecker(); + var start = ts.timestamp(); + var currentToken = ts.getTokenAtPosition(sourceFile, position); // TODO: GH#15853 + // We will check for jsdoc comments with insideComment and getJsDocTagAtPosition. (TODO: that seems rather inefficient to check the same thing so many times.) + log("getCompletionData: Get current token: " + (ts.timestamp() - start)); + start = ts.timestamp(); + var insideComment = ts.isInComment(sourceFile, position, currentToken); + log("getCompletionData: Is inside comment: " + (ts.timestamp() - start)); + var insideJsDocTagTypeExpression = false; + var isInSnippetScope = false; + if (insideComment) { + if (ts.hasDocComment(sourceFile, position)) { + if (sourceFile.text.charCodeAt(position - 1) === 64 /* at */) { + // The current position is next to the '@' sign, when no tag name being provided yet. + // Provide a full list of tag names + return { kind: 1 /* JsDocTagName */ }; + } + else { + // When completion is requested without "@", we will have check to make sure that + // there are no comments prefix the request position. We will only allow "*" and space. + // e.g + // /** |c| /* + // + // /** + // |c| + // */ + // + // /** + // * |c| + // */ + // + // /** + // * |c| + // */ + var lineStart = ts.getLineStartPositionForPosition(position, sourceFile); + if (!(sourceFile.text.substring(lineStart, position).match(/[^\*|\s|(/\*\*)]/))) { + return { kind: 2 /* JsDocTag */ }; + } + } + } + // Completion should work inside certain JsDoc tags. For example: + // /** @type {number | string} */ + // Completion should work in the brackets + var tag = getJsDocTagAtPosition(currentToken, position); + if (tag) { + if (tag.tagName.pos <= position && position <= tag.tagName.end) { + return { kind: 1 /* JsDocTagName */ }; + } + if (isTagWithTypeExpression(tag) && tag.typeExpression && tag.typeExpression.kind === 283 /* JSDocTypeExpression */) { + currentToken = ts.getTokenAtPosition(sourceFile, position); + if (!currentToken || + (!ts.isDeclarationName(currentToken) && + (currentToken.parent.kind !== 305 /* JSDocPropertyTag */ || + currentToken.parent.name !== currentToken))) { + // Use as type location if inside tag's type expression + insideJsDocTagTypeExpression = isCurrentlyEditingNode(tag.typeExpression); + } + } + if (ts.isJSDocParameterTag(tag) && (ts.nodeIsMissing(tag.name) || tag.name.pos <= position && position <= tag.name.end)) { + return { kind: 3 /* JsDocParameterName */, tag: tag }; + } + } + if (!insideJsDocTagTypeExpression) { + // Proceed if the current position is in jsDoc tag expression; otherwise it is a normal + // comment or the plain text part of a jsDoc comment, so no completion should be available + log("Returning an empty list because completion was inside a regular comment or plain text part of a JsDoc comment."); + return undefined; + } + } + start = ts.timestamp(); + var previousToken = ts.findPrecedingToken(position, sourceFile, /*startNode*/ undefined); // TODO: GH#18217 + log("getCompletionData: Get previous token 1: " + (ts.timestamp() - start)); + // The decision to provide completion depends on the contextToken, which is determined through the previousToken. + // Note: 'previousToken' (and thus 'contextToken') can be undefined if we are the beginning of the file + var contextToken = previousToken; + // Check if the caret is at the end of an identifier; this is a partial identifier that we want to complete: e.g. a.toS| + // Skip this partial identifier and adjust the contextToken to the token that precedes it. + if (contextToken && position <= contextToken.end && (ts.isIdentifier(contextToken) || ts.isKeyword(contextToken.kind))) { + var start_3 = ts.timestamp(); + contextToken = ts.findPrecedingToken(contextToken.getFullStart(), sourceFile, /*startNode*/ undefined); // TODO: GH#18217 + log("getCompletionData: Get previous token 2: " + (ts.timestamp() - start_3)); + } + // Find the node where completion is requested on. + // Also determine whether we are trying to complete with members of that node + // or attributes of a JSX tag. + var node = currentToken; + var propertyAccessToConvert; + var isRightOfDot = false; + var isRightOfOpenTag = false; + var isStartingCloseTag = false; + var isJsxInitializer = false; + var location = ts.getTouchingPropertyName(sourceFile, position); + if (contextToken) { + // Bail out if this is a known invalid completion location + if (isCompletionListBlocker(contextToken)) { + log("Returning an empty list because completion was requested in an invalid position."); + return undefined; + } + var parent = contextToken.parent; + if (contextToken.kind === 24 /* DotToken */) { + isRightOfDot = true; + switch (parent.kind) { + case 189 /* PropertyAccessExpression */: + propertyAccessToConvert = parent; + node = propertyAccessToConvert.expression; + break; + case 148 /* QualifiedName */: + node = parent.left; + break; + case 244 /* ModuleDeclaration */: + node = parent.name; + break; + case 183 /* ImportType */: + case 214 /* MetaProperty */: + node = parent; + break; + default: + // There is nothing that precedes the dot, so this likely just a stray character + // or leading into a '...' token. Just bail out instead. + return undefined; + } + } + else if (sourceFile.languageVariant === 1 /* JSX */) { + // + // If the tagname is a property access expression, we will then walk up to the top most of property access expression. + // Then, try to get a JSX container and its associated attributes type. + if (parent && parent.kind === 189 /* PropertyAccessExpression */) { + contextToken = parent; + parent = parent.parent; + } + // Fix location + if (currentToken.parent === location) { + switch (currentToken.kind) { + case 30 /* GreaterThanToken */: + if (currentToken.parent.kind === 260 /* JsxElement */ || currentToken.parent.kind === 262 /* JsxOpeningElement */) { + location = currentToken; + } + break; + case 42 /* SlashToken */: + if (currentToken.parent.kind === 261 /* JsxSelfClosingElement */) { + location = currentToken; + } + break; + } + } + switch (parent.kind) { + case 263 /* JsxClosingElement */: + if (contextToken.kind === 42 /* SlashToken */) { + isStartingCloseTag = true; + location = contextToken; + } + break; + case 204 /* BinaryExpression */: + if (!binaryExpressionMayBeOpenTag(parent)) { + break; + } + // falls through + case 261 /* JsxSelfClosingElement */: + case 260 /* JsxElement */: + case 262 /* JsxOpeningElement */: + if (contextToken.kind === 28 /* LessThanToken */) { + isRightOfOpenTag = true; + location = contextToken; + } + break; + case 267 /* JsxAttribute */: + switch (previousToken.kind) { + case 59 /* EqualsToken */: + isJsxInitializer = true; + break; + case 72 /* Identifier */: + // For `
      ` we don't want to treat this as a jsx inializer, instead it's the attribute name. + if (parent !== previousToken.parent && + !parent.initializer && + ts.findChildOfKind(parent, 59 /* EqualsToken */, sourceFile)) { + isJsxInitializer = previousToken; + } + } + break; + } + } + } + var semanticStart = ts.timestamp(); + var completionKind = 5 /* None */; + var isNewIdentifierLocation = false; + var keywordFilters = 0 /* None */; + var symbols = []; + var symbolToOriginInfoMap = []; + if (isRightOfDot) { + getTypeScriptMemberSymbols(); + } + else if (isRightOfOpenTag) { + var tagSymbols = ts.Debug.assertEachDefined(typeChecker.getJsxIntrinsicTagNamesAt(location), "getJsxIntrinsicTagNames() should all be defined"); + tryGetGlobalSymbols(); + symbols = tagSymbols.concat(symbols); + completionKind = 3 /* MemberLike */; + keywordFilters = 0 /* None */; + } + else if (isStartingCloseTag) { + var tagName = contextToken.parent.parent.openingElement.tagName; + var tagSymbol = typeChecker.getSymbolAtLocation(tagName); + if (tagSymbol) { + symbols = [tagSymbol]; + } + completionKind = 3 /* MemberLike */; + keywordFilters = 0 /* None */; + } + else { + // For JavaScript or TypeScript, if we're not after a dot, then just try to get the + // global symbols in scope. These results should be valid for either language as + // the set of symbols that can be referenced from this location. + if (!tryGetGlobalSymbols()) { + return undefined; + } + } + log("getCompletionData: Semantic work: " + (ts.timestamp() - semanticStart)); + var contextualType = previousToken && getContextualType(previousToken, position, sourceFile, typeChecker); + var literals = ts.mapDefined(contextualType && (contextualType.isUnion() ? contextualType.types : [contextualType]), function (t) { return t.isLiteral() ? t.value : undefined; }); + var recommendedCompletion = previousToken && contextualType && getRecommendedCompletion(previousToken, contextualType, typeChecker); + return { kind: 0 /* Data */, symbols: symbols, completionKind: completionKind, isInSnippetScope: isInSnippetScope, propertyAccessToConvert: propertyAccessToConvert, isNewIdentifierLocation: isNewIdentifierLocation, location: location, keywordFilters: keywordFilters, literals: literals, symbolToOriginInfoMap: symbolToOriginInfoMap, recommendedCompletion: recommendedCompletion, previousToken: previousToken, isJsxInitializer: isJsxInitializer }; + function isTagWithTypeExpression(tag) { + switch (tag.kind) { + case 299 /* JSDocParameterTag */: + case 305 /* JSDocPropertyTag */: + case 300 /* JSDocReturnTag */: + case 302 /* JSDocTypeTag */: + case 304 /* JSDocTypedefTag */: + return true; + default: + return false; + } + } + function getTypeScriptMemberSymbols() { + // Right of dot member completion list + completionKind = 2 /* PropertyAccess */; + // Since this is qualified name check its a type node location + var isImportType = ts.isLiteralImportTypeNode(node); + var isTypeLocation = insideJsDocTagTypeExpression || (isImportType && !node.isTypeOf) || ts.isPartOfTypeNode(node.parent); + var isRhsOfImportDeclaration = ts.isInRightSideOfInternalImportEqualsDeclaration(node); + var allowTypeOrValue = isRhsOfImportDeclaration || (!isTypeLocation && ts.isPossiblyTypeArgumentPosition(contextToken, sourceFile, typeChecker)); + if (ts.isEntityName(node) || isImportType) { + var isNamespaceName = ts.isModuleDeclaration(node.parent); + if (isNamespaceName) + isNewIdentifierLocation = true; + var symbol = typeChecker.getSymbolAtLocation(node); + if (symbol) { + symbol = ts.skipAlias(symbol, typeChecker); + if (symbol.flags & (1536 /* Module */ | 384 /* Enum */)) { + // Extract module or enum members + var exportedSymbols = ts.Debug.assertEachDefined(typeChecker.getExportsOfModule(symbol), "getExportsOfModule() should all be defined"); + var isValidValueAccess_1 = function (symbol) { return typeChecker.isValidPropertyAccess(isImportType ? node : (node.parent), symbol.name); }; + var isValidTypeAccess_1 = function (symbol) { return symbolCanBeReferencedAtTypeLocation(symbol); }; + var isValidAccess = isNamespaceName + // At `namespace N.M/**/`, if this is the only declaration of `M`, don't include `M` as a completion. + ? function (symbol) { return !!(symbol.flags & 1920 /* Namespace */) && !symbol.declarations.every(function (d) { return d.parent === node.parent; }); } + : allowTypeOrValue ? + // Any kind is allowed when dotting off namespace in internal import equals declaration + function (symbol) { return isValidTypeAccess_1(symbol) || isValidValueAccess_1(symbol); } : + isTypeLocation ? isValidTypeAccess_1 : isValidValueAccess_1; + for (var _i = 0, exportedSymbols_1 = exportedSymbols; _i < exportedSymbols_1.length; _i++) { + var exportedSymbol = exportedSymbols_1[_i]; + if (isValidAccess(exportedSymbol)) { + symbols.push(exportedSymbol); + } + } + // If the module is merged with a value, we must get the type of the class and add its propertes (for inherited static methods). + if (!isTypeLocation && symbol.declarations.some(function (d) { return d.kind !== 279 /* SourceFile */ && d.kind !== 244 /* ModuleDeclaration */ && d.kind !== 243 /* EnumDeclaration */; })) { + addTypeProperties(typeChecker.getTypeOfSymbolAtLocation(symbol, node)); + } + return; + } + } + } + if (ts.isMetaProperty(node) && (node.keywordToken === 95 /* NewKeyword */ || node.keywordToken === 92 /* ImportKeyword */)) { + var completion = (node.keywordToken === 95 /* NewKeyword */) ? "target" : "meta"; + symbols.push(typeChecker.createSymbol(4 /* Property */, ts.escapeLeadingUnderscores(completion))); + return; + } + if (!isTypeLocation) { + addTypeProperties(typeChecker.getTypeAtLocation(node)); + } + } + function addTypeProperties(type) { + isNewIdentifierLocation = !!type.getStringIndexType(); + if (isUncheckedFile) { + // In javascript files, for union types, we don't just get the members that + // the individual types have in common, we also include all the members that + // each individual type has. This is because we're going to add all identifiers + // anyways. So we might as well elevate the members that were at least part + // of the individual types to a higher status since we know what they are. + symbols.push.apply(symbols, getPropertiesForCompletion(type, typeChecker)); + } + else { + for (var _i = 0, _a = type.getApparentProperties(); _i < _a.length; _i++) { + var symbol = _a[_i]; + if (typeChecker.isValidPropertyAccessForCompletions(node.kind === 183 /* ImportType */ ? node : node.parent, type, symbol)) { + addPropertySymbol(symbol); + } + } + } + } + function addPropertySymbol(symbol) { + // For a computed property with an accessible name like `Symbol.iterator`, + // we'll add a completion for the *name* `Symbol` instead of for the property. + // If this is e.g. [Symbol.iterator], add a completion for `Symbol`. + var computedPropertyName = ts.firstDefined(symbol.declarations, function (decl) { return ts.tryCast(ts.getNameOfDeclaration(decl), ts.isComputedPropertyName); }); + if (computedPropertyName) { + var leftMostName = getLeftMostName(computedPropertyName.expression); // The completion is for `Symbol`, not `iterator`. + var nameSymbol = leftMostName && typeChecker.getSymbolAtLocation(leftMostName); + // If this is nested like for `namespace N { export const sym = Symbol(); }`, we'll add the completion for `N`. + var firstAccessibleSymbol = nameSymbol && getFirstSymbolInChain(nameSymbol, contextToken, typeChecker); + if (firstAccessibleSymbol && !symbolToOriginInfoMap[ts.getSymbolId(firstAccessibleSymbol)]) { + symbols.push(firstAccessibleSymbol); + var moduleSymbol = firstAccessibleSymbol.parent; + symbolToOriginInfoMap[ts.getSymbolId(firstAccessibleSymbol)] = + !moduleSymbol || !ts.isExternalModuleSymbol(moduleSymbol) ? { kind: 1 /* SymbolMemberNoExport */ } : { kind: 2 /* SymbolMemberExport */, moduleSymbol: moduleSymbol, isDefaultExport: false }; + } + } + else { + symbols.push(symbol); + } + } + /** Given 'a.b.c', returns 'a'. */ + function getLeftMostName(e) { + return ts.isIdentifier(e) ? e : ts.isPropertyAccessExpression(e) ? getLeftMostName(e.expression) : undefined; + } + function tryGetGlobalSymbols() { + var result = tryGetObjectLikeCompletionSymbols() + || tryGetImportOrExportClauseCompletionSymbols() + || tryGetConstructorCompletion() + || tryGetClassLikeCompletionSymbols() + || tryGetJsxCompletionSymbols() + || (getGlobalCompletions(), 1 /* Success */); + return result === 1 /* Success */; + } + function tryGetConstructorCompletion() { + if (!tryGetConstructorLikeCompletionContainer(contextToken)) + return 0 /* Continue */; + // no members, only keywords + completionKind = 5 /* None */; + // Declaring new property/method/accessor + isNewIdentifierLocation = true; + // Has keywords for constructor parameter + keywordFilters = 4 /* ConstructorParameterKeywords */; + return 1 /* Success */; + } + function tryGetJsxCompletionSymbols() { + var jsxContainer = tryGetContainingJsxElement(contextToken); + // Cursor is inside a JSX self-closing element or opening element + var attrsType = jsxContainer && typeChecker.getContextualType(jsxContainer.attributes); + if (!attrsType) + return 0 /* Continue */; + symbols = filterJsxAttributes(getPropertiesForObjectExpression(attrsType, jsxContainer.attributes, typeChecker), jsxContainer.attributes.properties); + completionKind = 3 /* MemberLike */; + isNewIdentifierLocation = false; + return 1 /* Success */; + } + function getGlobalCompletions() { + keywordFilters = tryGetFunctionLikeBodyCompletionContainer(contextToken) ? 5 /* FunctionLikeBodyKeywords */ : 1 /* All */; + // Get all entities in the current scope. + completionKind = 1 /* Global */; + isNewIdentifierLocation = isNewIdentifierDefinitionLocation(contextToken); + if (previousToken !== contextToken) { + ts.Debug.assert(!!previousToken, "Expected 'contextToken' to be defined when different from 'previousToken'."); + } + // We need to find the node that will give us an appropriate scope to begin + // aggregating completion candidates. This is achieved in 'getScopeNode' + // by finding the first node that encompasses a position, accounting for whether a node + // is "complete" to decide whether a position belongs to the node. + // + // However, at the end of an identifier, we are interested in the scope of the identifier + // itself, but fall outside of the identifier. For instance: + // + // xyz => x$ + // + // the cursor is outside of both the 'x' and the arrow function 'xyz => x', + // so 'xyz' is not returned in our results. + // + // We define 'adjustedPosition' so that we may appropriately account for + // being at the end of an identifier. The intention is that if requesting completion + // at the end of an identifier, it should be effectively equivalent to requesting completion + // anywhere inside/at the beginning of the identifier. So in the previous case, the + // 'adjustedPosition' will work as if requesting completion in the following: + // + // xyz => $x + // + // If previousToken !== contextToken, then + // - 'contextToken' was adjusted to the token prior to 'previousToken' + // because we were at the end of an identifier. + // - 'previousToken' is defined. + var adjustedPosition = previousToken !== contextToken ? + previousToken.getStart() : + position; + var scopeNode = getScopeNode(contextToken, adjustedPosition, sourceFile) || sourceFile; + isInSnippetScope = isSnippetScope(scopeNode); + var isTypeOnly = isTypeOnlyCompletion(); + var symbolMeanings = (isTypeOnly ? 0 /* None */ : 67220415 /* Value */) | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */; + symbols = ts.Debug.assertEachDefined(typeChecker.getSymbolsInScope(scopeNode, symbolMeanings), "getSymbolsInScope() should all be defined"); + // Need to insert 'this.' before properties of `this` type, so only do that if `includeInsertTextCompletions` + if (preferences.includeCompletionsWithInsertText && scopeNode.kind !== 279 /* SourceFile */) { + var thisType = typeChecker.tryGetThisTypeAt(scopeNode); + if (thisType) { + for (var _i = 0, _a = getPropertiesForCompletion(thisType, typeChecker); _i < _a.length; _i++) { + var symbol = _a[_i]; + symbolToOriginInfoMap[ts.getSymbolId(symbol)] = { kind: 0 /* ThisType */ }; + symbols.push(symbol); + } + } + } + if (shouldOfferImportCompletions()) { + getSymbolsFromOtherSourceFileExports(symbols, previousToken && ts.isIdentifier(previousToken) ? previousToken.text : "", program.getCompilerOptions().target); + } + filterGlobalCompletion(symbols); + } + function shouldOfferImportCompletions() { + // If not already a module, must have modules enabled and not currently be in a commonjs module. (TODO: import completions for commonjs) + if (!preferences.includeCompletionsForModuleExports) + return false; + // If already using ES6 modules, OK to continue using them. + if (sourceFile.externalModuleIndicator) + return true; + // If already using commonjs, don't introduce ES6. + if (sourceFile.commonJsModuleIndicator) + return false; + // If module transpilation is enabled or we're targeting es6 or above, or not emitting, OK. + if (ts.compilerOptionsIndicateEs6Modules(program.getCompilerOptions())) + return true; + // If some file is using ES6 modules, assume that it's OK to add more. + return ts.programContainsEs6Modules(program); + } + function isSnippetScope(scopeNode) { + switch (scopeNode.kind) { + case 279 /* SourceFile */: + case 206 /* TemplateExpression */: + case 270 /* JsxExpression */: + case 218 /* Block */: + return true; + default: + return ts.isStatement(scopeNode); + } + } + function filterGlobalCompletion(symbols) { + var isTypeOnly = isTypeOnlyCompletion(); + var allowTypes = isTypeOnly || !isContextTokenValueLocation(contextToken) && ts.isPossiblyTypeArgumentPosition(contextToken, sourceFile, typeChecker); + if (isTypeOnly) + keywordFilters = 6 /* TypeKeywords */; + ts.filterMutate(symbols, function (symbol) { + if (!ts.isSourceFile(location)) { + // export = /**/ here we want to get all meanings, so any symbol is ok + if (ts.isExportAssignment(location.parent)) { + return true; + } + symbol = ts.skipAlias(symbol, typeChecker); + // import m = /**/ <-- It can only access namespace (if typing import = x. this would get member symbols and not namespace) + if (ts.isInRightSideOfInternalImportEqualsDeclaration(location)) { + return !!(symbol.flags & 1920 /* Namespace */); + } + if (allowTypes) { + // Its a type, but you can reach it by namespace.type as well + var symbolAllowedAsType = symbolCanBeReferencedAtTypeLocation(symbol); + if (symbolAllowedAsType || isTypeOnly) { + return symbolAllowedAsType; + } + } + } + // expressions are value space (which includes the value namespaces) + return !!(ts.getCombinedLocalAndExportSymbolFlags(symbol) & 67220415 /* Value */); + }); + } + function isTypeOnlyCompletion() { + return insideJsDocTagTypeExpression || !isContextTokenValueLocation(contextToken) && (ts.isPartOfTypeNode(location) || isContextTokenTypeLocation(contextToken)); + } + function isContextTokenValueLocation(contextToken) { + return contextToken && + contextToken.kind === 104 /* TypeOfKeyword */ && + (contextToken.parent.kind === 167 /* TypeQuery */ || ts.isTypeOfExpression(contextToken.parent)); + } + function isContextTokenTypeLocation(contextToken) { + if (contextToken) { + var parentKind = contextToken.parent.kind; + switch (contextToken.kind) { + case 57 /* ColonToken */: + return parentKind === 154 /* PropertyDeclaration */ || + parentKind === 153 /* PropertySignature */ || + parentKind === 151 /* Parameter */ || + parentKind === 237 /* VariableDeclaration */ || + ts.isFunctionLikeKind(parentKind); + case 59 /* EqualsToken */: + return parentKind === 242 /* TypeAliasDeclaration */; + case 119 /* AsKeyword */: + return parentKind === 212 /* AsExpression */; + } + } + return false; + } + /** True if symbol is a type or a module containing at least one type. */ + function symbolCanBeReferencedAtTypeLocation(symbol, seenModules) { + if (seenModules === void 0) { seenModules = ts.createMap(); } + var sym = ts.skipAlias(symbol.exportSymbol || symbol, typeChecker); + return !!(sym.flags & 67897832 /* Type */) || + !!(sym.flags & 1536 /* Module */) && + ts.addToSeen(seenModules, ts.getSymbolId(sym)) && + typeChecker.getExportsOfModule(sym).some(function (e) { return symbolCanBeReferencedAtTypeLocation(e, seenModules); }); + } + function getSymbolsFromOtherSourceFileExports(symbols, tokenText, target) { + var tokenTextLowerCase = tokenText.toLowerCase(); + var seenResolvedModules = ts.createMap(); + ts.codefix.forEachExternalModuleToImportFrom(typeChecker, sourceFile, program.getSourceFiles(), function (moduleSymbol) { + // Perf -- ignore other modules if this is a request for details + if (detailsEntryId && detailsEntryId.source && ts.stripQuotes(moduleSymbol.name) !== detailsEntryId.source) { + return; + } + var resolvedModuleSymbol = typeChecker.resolveExternalModuleSymbol(moduleSymbol); + // resolvedModuleSymbol may be a namespace. A namespace may be `export =` by multiple module declarations, but only keep the first one. + if (!ts.addToSeen(seenResolvedModules, ts.getSymbolId(resolvedModuleSymbol))) { + return; + } + if (resolvedModuleSymbol !== moduleSymbol && + // Don't add another completion for `export =` of a symbol that's already global. + // So in `declare namespace foo {} declare module "foo" { export = foo; }`, there will just be the global completion for `foo`. + ts.some(resolvedModuleSymbol.declarations, function (d) { return !!d.getSourceFile().externalModuleIndicator; })) { + symbols.push(resolvedModuleSymbol); + symbolToOriginInfoMap[ts.getSymbolId(resolvedModuleSymbol)] = { kind: 3 /* Export */, moduleSymbol: moduleSymbol, isDefaultExport: false }; + } + for (var _i = 0, _a = typeChecker.getExportsOfModule(moduleSymbol); _i < _a.length; _i++) { + var symbol = _a[_i]; + // Don't add a completion for a re-export, only for the original. + // The actual import fix might end up coming from a re-export -- we don't compute that until getting completion details. + // This is just to avoid adding duplicate completion entries. + // + // If `symbol.parent !== ...`, this is an `export * from "foo"` re-export. Those don't create new symbols. + if (typeChecker.getMergedSymbol(symbol.parent) !== resolvedModuleSymbol + || ts.some(symbol.declarations, function (d) { + // If `!!d.name.originalKeywordKind`, this is `export { _break as break };` -- skip this and prefer the keyword completion. + // If `!!d.parent.parent.moduleSpecifier`, this is `export { foo } from "foo"` re-export, which creates a new symbol (thus isn't caught by the first check). + return ts.isExportSpecifier(d) && (d.propertyName ? ts.isIdentifierANonContextualKeyword(d.name) : !!d.parent.parent.moduleSpecifier); + })) { + continue; + } + var isDefaultExport = symbol.escapedName === "default" /* Default */; + if (isDefaultExport) { + symbol = ts.getLocalSymbolForExportDefault(symbol) || symbol; + } + var origin = { kind: 3 /* Export */, moduleSymbol: moduleSymbol, isDefaultExport: isDefaultExport }; + if (detailsEntryId || stringContainsCharactersInOrder(getSymbolName(symbol, origin, target).toLowerCase(), tokenTextLowerCase)) { + symbols.push(symbol); + symbolToOriginInfoMap[ts.getSymbolId(symbol)] = origin; + } + } + }); + } + /** + * True if you could remove some characters in `a` to get `b`. + * E.g., true for "abcdef" and "bdf". + * But not true for "abcdef" and "dbf". + */ + function stringContainsCharactersInOrder(str, characters) { + if (characters.length === 0) { + return true; + } + var characterIndex = 0; + for (var strIndex = 0; strIndex < str.length; strIndex++) { + if (str.charCodeAt(strIndex) === characters.charCodeAt(characterIndex)) { + characterIndex++; + if (characterIndex === characters.length) { + return true; + } + } + } + // Did not find all characters + return false; + } + /** + * Finds the first node that "embraces" the position, so that one may + * accurately aggregate locals from the closest containing scope. + */ + function getScopeNode(initialToken, position, sourceFile) { + var scope = initialToken; + while (scope && !ts.positionBelongsToNode(scope, position, sourceFile)) { + scope = scope.parent; + } + return scope; + } + function isCompletionListBlocker(contextToken) { + var start = ts.timestamp(); + var result = isInStringOrRegularExpressionOrTemplateLiteral(contextToken) || + isSolelyIdentifierDefinitionLocation(contextToken) || + isDotOfNumericLiteral(contextToken) || + isInJsxText(contextToken); + log("getCompletionsAtPosition: isCompletionListBlocker: " + (ts.timestamp() - start)); + return result; + } + function isInJsxText(contextToken) { + if (contextToken.kind === 11 /* JsxText */) { + return true; + } + if (contextToken.kind === 30 /* GreaterThanToken */ && contextToken.parent) { + if (contextToken.parent.kind === 262 /* JsxOpeningElement */) { + return true; + } + if (contextToken.parent.kind === 263 /* JsxClosingElement */ || contextToken.parent.kind === 261 /* JsxSelfClosingElement */) { + return !!contextToken.parent.parent && contextToken.parent.parent.kind === 260 /* JsxElement */; + } + } + return false; + } + function isNewIdentifierDefinitionLocation(previousToken) { + if (previousToken) { + var containingNodeKind = previousToken.parent.kind; + // Previous token may have been a keyword that was converted to an identifier. + switch (keywordForNode(previousToken)) { + case 27 /* CommaToken */: + return containingNodeKind === 191 /* CallExpression */ // func( a, | + || containingNodeKind === 157 /* Constructor */ // constructor( a, | /* public, protected, private keywords are allowed here, so show completion */ + || containingNodeKind === 192 /* NewExpression */ // new C(a, | + || containingNodeKind === 187 /* ArrayLiteralExpression */ // [a, | + || containingNodeKind === 204 /* BinaryExpression */ // const x = (a, | + || containingNodeKind === 165 /* FunctionType */; // var x: (s: string, list| + case 20 /* OpenParenToken */: + return containingNodeKind === 191 /* CallExpression */ // func( | + || containingNodeKind === 157 /* Constructor */ // constructor( | + || containingNodeKind === 192 /* NewExpression */ // new C(a| + || containingNodeKind === 195 /* ParenthesizedExpression */ // const x = (a| + || containingNodeKind === 177 /* ParenthesizedType */; // function F(pred: (a| /* this can become an arrow function, where 'a' is the argument */ + case 22 /* OpenBracketToken */: + return containingNodeKind === 187 /* ArrayLiteralExpression */ // [ | + || containingNodeKind === 162 /* IndexSignature */ // [ | : string ] + || containingNodeKind === 149 /* ComputedPropertyName */; // [ | /* this can become an index signature */ + case 130 /* ModuleKeyword */: // module | + case 131 /* NamespaceKeyword */: // namespace | + return true; + case 24 /* DotToken */: + return containingNodeKind === 244 /* ModuleDeclaration */; // module A.| + case 18 /* OpenBraceToken */: + return containingNodeKind === 240 /* ClassDeclaration */; // class A{ | + case 59 /* EqualsToken */: + return containingNodeKind === 237 /* VariableDeclaration */ // const x = a| + || containingNodeKind === 204 /* BinaryExpression */; // x = a| + case 15 /* TemplateHead */: + return containingNodeKind === 206 /* TemplateExpression */; // `aa ${| + case 16 /* TemplateMiddle */: + return containingNodeKind === 216 /* TemplateSpan */; // `aa ${10} dd ${| + case 115 /* PublicKeyword */: + case 113 /* PrivateKeyword */: + case 114 /* ProtectedKeyword */: + return containingNodeKind === 154 /* PropertyDeclaration */; // class A{ public | + } + } + return false; + } + function isInStringOrRegularExpressionOrTemplateLiteral(contextToken) { + // To be "in" one of these literals, the position has to be: + // 1. entirely within the token text. + // 2. at the end position of an unterminated token. + // 3. at the end of a regular expression (due to trailing flags like '/foo/g'). + return (ts.isRegularExpressionLiteral(contextToken) || ts.isStringTextContainingNode(contextToken)) && (ts.rangeContainsPositionExclusive(ts.createTextRangeFromSpan(ts.createTextSpanFromNode(contextToken)), position) || + position === contextToken.end && (!!contextToken.isUnterminated || ts.isRegularExpressionLiteral(contextToken))); + } + /** + * Aggregates relevant symbols for completion in object literals and object binding patterns. + * Relevant symbols are stored in the captured 'symbols' variable. + * + * @returns true if 'symbols' was successfully populated; false otherwise. + */ + function tryGetObjectLikeCompletionSymbols() { + var objectLikeContainer = tryGetObjectLikeCompletionContainer(contextToken); + if (!objectLikeContainer) + return 0 /* Continue */; + // We're looking up possible property names from contextual/inferred/declared type. + completionKind = 0 /* ObjectPropertyDeclaration */; + var typeMembers; + var existingMembers; + if (objectLikeContainer.kind === 188 /* ObjectLiteralExpression */) { + var typeForObject = typeChecker.getContextualType(objectLikeContainer); + if (!typeForObject) + return 2 /* Fail */; + isNewIdentifierLocation = ts.hasIndexSignature(typeForObject); + typeMembers = getPropertiesForObjectExpression(typeForObject, objectLikeContainer, typeChecker); + existingMembers = objectLikeContainer.properties; + } + else { + ts.Debug.assert(objectLikeContainer.kind === 184 /* ObjectBindingPattern */); + // We are *only* completing on properties from the type being destructured. + isNewIdentifierLocation = false; + var rootDeclaration = ts.getRootDeclaration(objectLikeContainer.parent); + if (!ts.isVariableLike(rootDeclaration)) + return ts.Debug.fail("Root declaration is not variable-like."); + // We don't want to complete using the type acquired by the shape + // of the binding pattern; we are only interested in types acquired + // through type declaration or inference. + // Also proceed if rootDeclaration is a parameter and if its containing function expression/arrow function is contextually typed - + // type of parameter will flow in from the contextual type of the function + var canGetType = ts.hasInitializer(rootDeclaration) || ts.hasType(rootDeclaration) || rootDeclaration.parent.parent.kind === 227 /* ForOfStatement */; + if (!canGetType && rootDeclaration.kind === 151 /* Parameter */) { + if (ts.isExpression(rootDeclaration.parent)) { + canGetType = !!typeChecker.getContextualType(rootDeclaration.parent); + } + else if (rootDeclaration.parent.kind === 156 /* MethodDeclaration */ || rootDeclaration.parent.kind === 159 /* SetAccessor */) { + canGetType = ts.isExpression(rootDeclaration.parent.parent) && !!typeChecker.getContextualType(rootDeclaration.parent.parent); + } + } + if (canGetType) { + var typeForObject = typeChecker.getTypeAtLocation(objectLikeContainer); + if (!typeForObject) + return 2 /* Fail */; + // In a binding pattern, get only known properties. Everywhere else we will get all possible properties. + typeMembers = typeChecker.getPropertiesOfType(typeForObject).filter(function (symbol) { return !(ts.getDeclarationModifierFlagsFromSymbol(symbol) & 24 /* NonPublicAccessibilityModifier */); }); + existingMembers = objectLikeContainer.elements; + } + } + if (typeMembers && typeMembers.length > 0) { + // Add filtered items to the completion list + symbols = filterObjectMembersList(typeMembers, ts.Debug.assertDefined(existingMembers)); + } + return 1 /* Success */; + } + /** + * Aggregates relevant symbols for completion in import clauses and export clauses + * whose declarations have a module specifier; for instance, symbols will be aggregated for + * + * import { | } from "moduleName"; + * export { a as foo, | } from "moduleName"; + * + * but not for + * + * export { | }; + * + * Relevant symbols are stored in the captured 'symbols' variable. + * + * @returns true if 'symbols' was successfully populated; false otherwise. + */ + function tryGetImportOrExportClauseCompletionSymbols() { + // `import { |` or `import { a as 0, | }` + var namedImportsOrExports = contextToken && (contextToken.kind === 18 /* OpenBraceToken */ || contextToken.kind === 27 /* CommaToken */) + ? ts.tryCast(contextToken.parent, ts.isNamedImportsOrExports) : undefined; + if (!namedImportsOrExports) + return 0 /* Continue */; + // cursor is in an import clause + // try to show exported member for imported module + var moduleSpecifier = (namedImportsOrExports.kind === 252 /* NamedImports */ ? namedImportsOrExports.parent.parent : namedImportsOrExports.parent).moduleSpecifier; + var moduleSpecifierSymbol = typeChecker.getSymbolAtLocation(moduleSpecifier); // TODO: GH#18217 + if (!moduleSpecifierSymbol) + return 2 /* Fail */; + completionKind = 3 /* MemberLike */; + isNewIdentifierLocation = false; + var exports = typeChecker.getExportsAndPropertiesOfModule(moduleSpecifierSymbol); + var existing = ts.arrayToSet(namedImportsOrExports.elements, function (n) { return isCurrentlyEditingNode(n) ? undefined : (n.propertyName || n.name).escapedText; }); + symbols = exports.filter(function (e) { return e.escapedName !== "default" /* Default */ && !existing.get(e.escapedName); }); + return 1 /* Success */; + } + /** + * Aggregates relevant symbols for completion in class declaration + * Relevant symbols are stored in the captured 'symbols' variable. + */ + function tryGetClassLikeCompletionSymbols() { + var decl = tryGetObjectTypeDeclarationCompletionContainer(sourceFile, contextToken, location); + if (!decl) + return 0 /* Continue */; + // We're looking up possible property names from parent type. + completionKind = 3 /* MemberLike */; + // Declaring new property/method/accessor + isNewIdentifierLocation = true; + keywordFilters = contextToken.kind === 40 /* AsteriskToken */ ? 0 /* None */ : + ts.isClassLike(decl) ? 2 /* ClassElementKeywords */ : 3 /* InterfaceElementKeywords */; + // If you're in an interface you don't want to repeat things from super-interface. So just stop here. + if (!ts.isClassLike(decl)) + return 1 /* Success */; + var classElement = contextToken.parent; + var classElementModifierFlags = ts.isClassElement(classElement) ? ts.getModifierFlags(classElement) : 0 /* None */; + // If this is context token is not something we are editing now, consider if this would lead to be modifier + if (contextToken.kind === 72 /* Identifier */ && !isCurrentlyEditingNode(contextToken)) { + switch (contextToken.getText()) { + case "private": + classElementModifierFlags = classElementModifierFlags | 8 /* Private */; + break; + case "static": + classElementModifierFlags = classElementModifierFlags | 32 /* Static */; + break; + } + } + // No member list for private methods + if (!(classElementModifierFlags & 8 /* Private */)) { + // List of property symbols of base type that are not private and already implemented + var baseSymbols = ts.flatMap(ts.getAllSuperTypeNodes(decl), function (baseTypeNode) { + var type = typeChecker.getTypeAtLocation(baseTypeNode); + return type && typeChecker.getPropertiesOfType(classElementModifierFlags & 32 /* Static */ ? typeChecker.getTypeOfSymbolAtLocation(type.symbol, decl) : type); + }); + symbols = filterClassMembersList(baseSymbols, decl.members, classElementModifierFlags); + } + return 1 /* Success */; + } + /** + * Returns the immediate owning object literal or binding pattern of a context token, + * on the condition that one exists and that the context implies completion should be given. + */ + function tryGetObjectLikeCompletionContainer(contextToken) { + if (contextToken) { + var parent = contextToken.parent; + switch (contextToken.kind) { + case 18 /* OpenBraceToken */: // const x = { | + case 27 /* CommaToken */: // const x = { a: 0, | + if (ts.isObjectLiteralExpression(parent) || ts.isObjectBindingPattern(parent)) { + return parent; + } + break; + case 40 /* AsteriskToken */: + return ts.isMethodDeclaration(parent) ? ts.tryCast(parent.parent, ts.isObjectLiteralExpression) : undefined; + case 72 /* Identifier */: + return contextToken.text === "async" && ts.isShorthandPropertyAssignment(contextToken.parent) + ? contextToken.parent.parent : undefined; + } + } + return undefined; + } + function isConstructorParameterCompletion(node) { + return !!node.parent && ts.isParameter(node.parent) && ts.isConstructorDeclaration(node.parent.parent) + && (ts.isParameterPropertyModifier(node.kind) || ts.isDeclarationName(node)); + } + /** + * Returns the immediate owning class declaration of a context token, + * on the condition that one exists and that the context implies completion should be given. + */ + function tryGetConstructorLikeCompletionContainer(contextToken) { + if (contextToken) { + var parent = contextToken.parent; + switch (contextToken.kind) { + case 20 /* OpenParenToken */: + case 27 /* CommaToken */: + return ts.isConstructorDeclaration(contextToken.parent) ? contextToken.parent : undefined; + default: + if (isConstructorParameterCompletion(contextToken)) { + return parent.parent; + } + } + } + return undefined; + } + function tryGetFunctionLikeBodyCompletionContainer(contextToken) { + if (contextToken) { + var prev_1; + var container = ts.findAncestor(contextToken.parent, function (node) { + if (ts.isClassLike(node)) { + return "quit"; + } + if (ts.isFunctionLikeDeclaration(node) && prev_1 === node.body) { + return true; + } + prev_1 = node; + return false; + }); + return container && container; + } + } + function tryGetContainingJsxElement(contextToken) { + if (contextToken) { + var parent = contextToken.parent; + switch (contextToken.kind) { + case 30 /* GreaterThanToken */: // End of a type argument list + case 29 /* LessThanSlashToken */: + case 42 /* SlashToken */: + case 72 /* Identifier */: + case 189 /* PropertyAccessExpression */: + case 268 /* JsxAttributes */: + case 267 /* JsxAttribute */: + case 269 /* JsxSpreadAttribute */: + if (parent && (parent.kind === 261 /* JsxSelfClosingElement */ || parent.kind === 262 /* JsxOpeningElement */)) { + if (contextToken.kind === 30 /* GreaterThanToken */) { + var precedingToken = ts.findPrecedingToken(contextToken.pos, sourceFile, /*startNode*/ undefined); + if (!parent.typeArguments || (precedingToken && precedingToken.kind === 42 /* SlashToken */)) + break; + } + return parent; + } + else if (parent.kind === 267 /* JsxAttribute */) { + // Currently we parse JsxOpeningLikeElement as: + // JsxOpeningLikeElement + // attributes: JsxAttributes + // properties: NodeArray + return parent.parent.parent; + } + break; + // The context token is the closing } or " of an attribute, which means + // its parent is a JsxExpression, whose parent is a JsxAttribute, + // whose parent is a JsxOpeningLikeElement + case 10 /* StringLiteral */: + if (parent && ((parent.kind === 267 /* JsxAttribute */) || (parent.kind === 269 /* JsxSpreadAttribute */))) { + // Currently we parse JsxOpeningLikeElement as: + // JsxOpeningLikeElement + // attributes: JsxAttributes + // properties: NodeArray + return parent.parent.parent; + } + break; + case 19 /* CloseBraceToken */: + if (parent && + parent.kind === 270 /* JsxExpression */ && + parent.parent && parent.parent.kind === 267 /* JsxAttribute */) { + // Currently we parse JsxOpeningLikeElement as: + // JsxOpeningLikeElement + // attributes: JsxAttributes + // properties: NodeArray + // each JsxAttribute can have initializer as JsxExpression + return parent.parent.parent.parent; + } + if (parent && parent.kind === 269 /* JsxSpreadAttribute */) { + // Currently we parse JsxOpeningLikeElement as: + // JsxOpeningLikeElement + // attributes: JsxAttributes + // properties: NodeArray + return parent.parent.parent; + } + break; + } + } + return undefined; + } + /** + * @returns true if we are certain that the currently edited location must define a new location; false otherwise. + */ + function isSolelyIdentifierDefinitionLocation(contextToken) { + var parent = contextToken.parent; + var containingNodeKind = parent.kind; + switch (contextToken.kind) { + case 27 /* CommaToken */: + return containingNodeKind === 237 /* VariableDeclaration */ || + containingNodeKind === 238 /* VariableDeclarationList */ || + containingNodeKind === 219 /* VariableStatement */ || + containingNodeKind === 243 /* EnumDeclaration */ || // enum a { foo, | + isFunctionLikeButNotConstructor(containingNodeKind) || + containingNodeKind === 241 /* InterfaceDeclaration */ || // interface A= contextToken.pos); + case 24 /* DotToken */: + return containingNodeKind === 185 /* ArrayBindingPattern */; // var [.| + case 57 /* ColonToken */: + return containingNodeKind === 186 /* BindingElement */; // var {x :html| + case 22 /* OpenBracketToken */: + return containingNodeKind === 185 /* ArrayBindingPattern */; // var [x| + case 20 /* OpenParenToken */: + return containingNodeKind === 274 /* CatchClause */ || + isFunctionLikeButNotConstructor(containingNodeKind); + case 18 /* OpenBraceToken */: + return containingNodeKind === 243 /* EnumDeclaration */; // enum a { | + case 28 /* LessThanToken */: + return containingNodeKind === 240 /* ClassDeclaration */ || // class A< | + containingNodeKind === 209 /* ClassExpression */ || // var C = class D< | + containingNodeKind === 241 /* InterfaceDeclaration */ || // interface A< | + containingNodeKind === 242 /* TypeAliasDeclaration */ || // type List< | + ts.isFunctionLikeKind(containingNodeKind); + case 116 /* StaticKeyword */: + return containingNodeKind === 154 /* PropertyDeclaration */ && !ts.isClassLike(parent.parent); + case 25 /* DotDotDotToken */: + return containingNodeKind === 151 /* Parameter */ || + (!!parent.parent && parent.parent.kind === 185 /* ArrayBindingPattern */); // var [...z| + case 115 /* PublicKeyword */: + case 113 /* PrivateKeyword */: + case 114 /* ProtectedKeyword */: + return containingNodeKind === 151 /* Parameter */ && !ts.isConstructorDeclaration(parent.parent); + case 119 /* AsKeyword */: + return containingNodeKind === 253 /* ImportSpecifier */ || + containingNodeKind === 257 /* ExportSpecifier */ || + containingNodeKind === 251 /* NamespaceImport */; + case 126 /* GetKeyword */: + case 137 /* SetKeyword */: + return !isFromObjectTypeDeclaration(contextToken); + case 76 /* ClassKeyword */: + case 84 /* EnumKeyword */: + case 110 /* InterfaceKeyword */: + case 90 /* FunctionKeyword */: + case 105 /* VarKeyword */: + case 92 /* ImportKeyword */: + case 111 /* LetKeyword */: + case 77 /* ConstKeyword */: + case 117 /* YieldKeyword */: + case 140 /* TypeKeyword */: // type htm| + return true; + case 40 /* AsteriskToken */: + return ts.isFunctionLike(contextToken.parent) && !ts.isMethodDeclaration(contextToken.parent); + } + // If the previous token is keyword correspoding to class member completion keyword + // there will be completion available here + if (isClassMemberCompletionKeyword(keywordForNode(contextToken)) && isFromObjectTypeDeclaration(contextToken)) { + return false; + } + if (isConstructorParameterCompletion(contextToken)) { + // constructor parameter completion is available only if + // - its modifier of the constructor parameter or + // - its name of the parameter and not being edited + // eg. constructor(a |<- this shouldnt show completion + if (!ts.isIdentifier(contextToken) || + ts.isParameterPropertyModifier(keywordForNode(contextToken)) || + isCurrentlyEditingNode(contextToken)) { + return false; + } + } + // Previous token may have been a keyword that was converted to an identifier. + switch (keywordForNode(contextToken)) { + case 118 /* AbstractKeyword */: + case 76 /* ClassKeyword */: + case 77 /* ConstKeyword */: + case 125 /* DeclareKeyword */: + case 84 /* EnumKeyword */: + case 90 /* FunctionKeyword */: + case 110 /* InterfaceKeyword */: + case 111 /* LetKeyword */: + case 113 /* PrivateKeyword */: + case 114 /* ProtectedKeyword */: + case 115 /* PublicKeyword */: + case 116 /* StaticKeyword */: + case 105 /* VarKeyword */: + case 117 /* YieldKeyword */: + return true; + case 121 /* AsyncKeyword */: + return ts.isPropertyDeclaration(contextToken.parent); + } + return ts.isDeclarationName(contextToken) + && !ts.isJsxAttribute(contextToken.parent) + // Don't block completions if we're in `class C /**/`, because we're *past* the end of the identifier and might want to complete `extends`. + // If `contextToken !== previousToken`, this is `class C ex/**/`. + && !(ts.isClassLike(contextToken.parent) && (contextToken !== previousToken || position > previousToken.end)); + } + function isFunctionLikeButNotConstructor(kind) { + return ts.isFunctionLikeKind(kind) && kind !== 157 /* Constructor */; + } + function isDotOfNumericLiteral(contextToken) { + if (contextToken.kind === 8 /* NumericLiteral */) { + var text = contextToken.getFullText(); + return text.charAt(text.length - 1) === "."; + } + return false; + } + /** + * Filters out completion suggestions for named imports or exports. + * + * @returns Symbols to be suggested in an object binding pattern or object literal expression, barring those whose declarations + * do not occur at the current position and have not otherwise been typed. + */ + function filterObjectMembersList(contextualMemberSymbols, existingMembers) { + if (existingMembers.length === 0) { + return contextualMemberSymbols; + } + var existingMemberNames = ts.createUnderscoreEscapedMap(); + for (var _i = 0, existingMembers_1 = existingMembers; _i < existingMembers_1.length; _i++) { + var m = existingMembers_1[_i]; + // Ignore omitted expressions for missing members + if (m.kind !== 275 /* PropertyAssignment */ && + m.kind !== 276 /* ShorthandPropertyAssignment */ && + m.kind !== 186 /* BindingElement */ && + m.kind !== 156 /* MethodDeclaration */ && + m.kind !== 158 /* GetAccessor */ && + m.kind !== 159 /* SetAccessor */) { + continue; + } + // If this is the current item we are editing right now, do not filter it out + if (isCurrentlyEditingNode(m)) { + continue; + } + var existingName = void 0; + if (ts.isBindingElement(m) && m.propertyName) { + // include only identifiers in completion list + if (m.propertyName.kind === 72 /* Identifier */) { + existingName = m.propertyName.escapedText; + } + } + else { + // TODO: Account for computed property name + // NOTE: if one only performs this step when m.name is an identifier, + // things like '__proto__' are not filtered out. + var name = ts.getNameOfDeclaration(m); + existingName = name && ts.isPropertyNameLiteral(name) ? ts.getEscapedTextOfIdentifierOrLiteral(name) : undefined; + } + existingMemberNames.set(existingName, true); // TODO: GH#18217 + } + return contextualMemberSymbols.filter(function (m) { return !existingMemberNames.get(m.escapedName); }); + } + /** + * Filters out completion suggestions for class elements. + * + * @returns Symbols to be suggested in an class element depending on existing memebers and symbol flags + */ + function filterClassMembersList(baseSymbols, existingMembers, currentClassElementModifierFlags) { + var existingMemberNames = ts.createUnderscoreEscapedMap(); + for (var _i = 0, existingMembers_2 = existingMembers; _i < existingMembers_2.length; _i++) { + var m = existingMembers_2[_i]; + // Ignore omitted expressions for missing members + if (m.kind !== 154 /* PropertyDeclaration */ && + m.kind !== 156 /* MethodDeclaration */ && + m.kind !== 158 /* GetAccessor */ && + m.kind !== 159 /* SetAccessor */) { + continue; + } + // If this is the current item we are editing right now, do not filter it out + if (isCurrentlyEditingNode(m)) { + continue; + } + // Dont filter member even if the name matches if it is declared private in the list + if (ts.hasModifier(m, 8 /* Private */)) { + continue; + } + // do not filter it out if the static presence doesnt match + if (ts.hasModifier(m, 32 /* Static */) !== !!(currentClassElementModifierFlags & 32 /* Static */)) { + continue; + } + var existingName = ts.getPropertyNameForPropertyNameNode(m.name); + if (existingName) { + existingMemberNames.set(existingName, true); + } + } + return baseSymbols.filter(function (propertySymbol) { + return !existingMemberNames.has(propertySymbol.escapedName) && + !!propertySymbol.declarations && + !(ts.getDeclarationModifierFlagsFromSymbol(propertySymbol) & 8 /* Private */); + }); + } + /** + * Filters out completion suggestions from 'symbols' according to existing JSX attributes. + * + * @returns Symbols to be suggested in a JSX element, barring those whose attributes + * do not occur at the current position and have not otherwise been typed. + */ + function filterJsxAttributes(symbols, attributes) { + var seenNames = ts.createUnderscoreEscapedMap(); + for (var _i = 0, attributes_1 = attributes; _i < attributes_1.length; _i++) { + var attr = attributes_1[_i]; + // If this is the current item we are editing right now, do not filter it out + if (isCurrentlyEditingNode(attr)) { + continue; + } + if (attr.kind === 267 /* JsxAttribute */) { + seenNames.set(attr.name.escapedText, true); + } + } + return symbols.filter(function (a) { return !seenNames.get(a.escapedName); }); + } + function isCurrentlyEditingNode(node) { + return node.getStart(sourceFile) <= position && position <= node.getEnd(); + } + } + function getCompletionEntryDisplayNameForSymbol(symbol, target, origin, kind) { + var name = getSymbolName(symbol, origin, target); + if (name === undefined + // If the symbol is external module, don't show it in the completion list + // (i.e declare module "http" { const x; } | // <= request completion here, "http" should not be there) + || symbol.flags & 1536 /* Module */ && ts.startsWithQuote(name) + // If the symbol is the internal name of an ES symbol, it is not a valid entry. Internal names for ES symbols start with "__@" + || ts.isKnownSymbol(symbol)) { + return undefined; + } + var validIdentiferResult = { name: name, needsConvertPropertyAccess: false }; + if (ts.isIdentifierText(name, target)) + return validIdentiferResult; + switch (kind) { + case 3 /* MemberLike */: + return undefined; + case 0 /* ObjectPropertyDeclaration */: + // TODO: GH#18169 + return { name: JSON.stringify(name), needsConvertPropertyAccess: false }; + case 2 /* PropertyAccess */: + case 1 /* Global */: // For a 'this.' completion it will be in a global context, but may have a non-identifier name. + // Don't add a completion for a name starting with a space. See https://github.com/Microsoft/TypeScript/pull/20547 + return name.charCodeAt(0) === 32 /* space */ ? undefined : { name: name, needsConvertPropertyAccess: true }; + case 5 /* None */: + case 4 /* String */: + return validIdentiferResult; + default: + ts.Debug.assertNever(kind); + } + } + // A cache of completion entries for keywords, these do not change between sessions + var _keywordCompletions = []; + var allKeywordsCompletions = ts.memoize(function () { + var res = []; + for (var i = 73 /* FirstKeyword */; i <= 147 /* LastKeyword */; i++) { + res.push({ + name: ts.tokenToString(i), + kind: "keyword" /* keyword */, + kindModifiers: "" /* none */, + sortText: "0" + }); + } + return res; + }); + function getKeywordCompletions(keywordFilter) { + return _keywordCompletions[keywordFilter] || (_keywordCompletions[keywordFilter] = allKeywordsCompletions().filter(function (entry) { + var kind = ts.stringToToken(entry.name); + switch (keywordFilter) { + case 0 /* None */: + return false; + case 1 /* All */: + return kind === 121 /* AsyncKeyword */ || 122 /* AwaitKeyword */ || !ts.isContextualKeyword(kind) && !isClassMemberCompletionKeyword(kind) || kind === 125 /* DeclareKeyword */ || kind === 130 /* ModuleKeyword */ + || ts.isTypeKeyword(kind) && kind !== 141 /* UndefinedKeyword */; + case 2 /* ClassElementKeywords */: + return isClassMemberCompletionKeyword(kind); + case 3 /* InterfaceElementKeywords */: + return isInterfaceOrTypeLiteralCompletionKeyword(kind); + case 4 /* ConstructorParameterKeywords */: + return ts.isParameterPropertyModifier(kind); + case 5 /* FunctionLikeBodyKeywords */: + return isFunctionLikeBodyKeyword(kind); + case 6 /* TypeKeywords */: + return ts.isTypeKeyword(kind); + default: + return ts.Debug.assertNever(keywordFilter); + } + })); + } + function isInterfaceOrTypeLiteralCompletionKeyword(kind) { + return kind === 133 /* ReadonlyKeyword */; + } + function isClassMemberCompletionKeyword(kind) { + switch (kind) { + case 118 /* AbstractKeyword */: + case 124 /* ConstructorKeyword */: + case 126 /* GetKeyword */: + case 137 /* SetKeyword */: + case 121 /* AsyncKeyword */: + return true; + default: + return ts.isClassMemberModifier(kind); + } + } + function isFunctionLikeBodyKeyword(kind) { + return kind === 121 /* AsyncKeyword */ || kind === 122 /* AwaitKeyword */ || !ts.isContextualKeyword(kind) && !isClassMemberCompletionKeyword(kind); + } + function keywordForNode(node) { + return ts.isIdentifier(node) ? node.originalKeywordKind || 0 /* Unknown */ : node.kind; + } + /** Get the corresponding JSDocTag node if the position is in a jsDoc comment */ + function getJsDocTagAtPosition(node, position) { + var jsdoc = ts.findAncestor(node, ts.isJSDoc); + return jsdoc && jsdoc.tags && (ts.rangeContainsPosition(jsdoc, position) ? ts.findLast(jsdoc.tags, function (tag) { return tag.pos < position; }) : undefined); + } + function getPropertiesForObjectExpression(contextualType, obj, checker) { + return contextualType.isUnion() + ? checker.getAllPossiblePropertiesOfTypes(contextualType.types.filter(function (memberType) { + // If we're providing completions for an object literal, skip primitive, array-like, or callable types since those shouldn't be implemented by object literals. + return !(memberType.flags & 131068 /* Primitive */ || + checker.isArrayLikeType(memberType) || + ts.typeHasCallOrConstructSignatures(memberType, checker) || + checker.isTypeInvalidDueToUnionDiscriminant(memberType, obj)); + })) + : contextualType.getApparentProperties(); + } + /** + * Gets all properties on a type, but if that type is a union of several types, + * excludes array-like types or callable/constructable types. + */ + function getPropertiesForCompletion(type, checker) { + return type.isUnion() + ? ts.Debug.assertEachDefined(checker.getAllPossiblePropertiesOfTypes(type.types), "getAllPossiblePropertiesOfTypes() should all be defined") + : ts.Debug.assertEachDefined(type.getApparentProperties(), "getApparentProperties() should all be defined"); + } + /** + * Returns the immediate owning class declaration of a context token, + * on the condition that one exists and that the context implies completion should be given. + */ + function tryGetObjectTypeDeclarationCompletionContainer(sourceFile, contextToken, location) { + // class c { method() { } | method2() { } } + switch (location.kind) { + case 306 /* SyntaxList */: + return ts.tryCast(location.parent, ts.isObjectTypeDeclaration); + case 1 /* EndOfFileToken */: + var cls = ts.tryCast(ts.lastOrUndefined(ts.cast(location.parent, ts.isSourceFile).statements), ts.isObjectTypeDeclaration); + if (cls && !ts.findChildOfKind(cls, 19 /* CloseBraceToken */, sourceFile)) { + return cls; + } + } + if (!contextToken) + return undefined; + switch (contextToken.kind) { + case 26 /* SemicolonToken */: // class c {getValue(): number; | } + case 19 /* CloseBraceToken */: // class c { method() { } | } + // class c { method() { } b| } + return isFromObjectTypeDeclaration(location) && location.parent.name === location + ? location.parent.parent + : ts.tryCast(location, ts.isObjectTypeDeclaration); + case 18 /* OpenBraceToken */: // class c { | + case 27 /* CommaToken */: // class c {getValue(): number, | } + return ts.tryCast(contextToken.parent, ts.isObjectTypeDeclaration); + default: + if (!isFromObjectTypeDeclaration(contextToken)) + return undefined; + var isValidKeyword = ts.isClassLike(contextToken.parent.parent) ? isClassMemberCompletionKeyword : isInterfaceOrTypeLiteralCompletionKeyword; + return (isValidKeyword(contextToken.kind) || contextToken.kind === 40 /* AsteriskToken */ || ts.isIdentifier(contextToken) && isValidKeyword(ts.stringToToken(contextToken.text))) // TODO: GH#18217 + ? contextToken.parent.parent : undefined; + } + } + // TODO: GH#19856 Would like to return `node is Node & { parent: (ClassElement | TypeElement) & { parent: ObjectTypeDeclaration } }` but then compilation takes > 10 minutes + function isFromObjectTypeDeclaration(node) { + return node.parent && ts.isClassOrTypeElement(node.parent) && ts.isObjectTypeDeclaration(node.parent.parent); + } + function isValidTrigger(sourceFile, triggerCharacter, contextToken, position) { + switch (triggerCharacter) { + case ".": + case "@": + return true; + case '"': + case "'": + case "`": + // Only automatically bring up completions if this is an opening quote. + return !!contextToken && ts.isStringLiteralOrTemplate(contextToken) && position === contextToken.getStart(sourceFile) + 1; + case "<": + // Opening JSX tag + return !!contextToken && contextToken.kind === 28 /* LessThanToken */ && (!ts.isBinaryExpression(contextToken.parent) || binaryExpressionMayBeOpenTag(contextToken.parent)); + case "/": + return !!contextToken && (ts.isStringLiteralLike(contextToken) + ? !!ts.tryGetImportFromModuleSpecifier(contextToken) + : contextToken.kind === 42 /* SlashToken */ && ts.isJsxClosingElement(contextToken.parent)); + default: + return ts.Debug.assertNever(triggerCharacter); + } + } + function binaryExpressionMayBeOpenTag(_a) { + var left = _a.left; + return ts.nodeIsMissing(left); + } + })(Completions = ts.Completions || (ts.Completions = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var DocumentHighlights; + (function (DocumentHighlights) { + function getDocumentHighlights(program, cancellationToken, sourceFile, position, sourceFilesToSearch) { + var node = ts.getTouchingPropertyName(sourceFile, position); + if (node.parent && (ts.isJsxOpeningElement(node.parent) && node.parent.tagName === node || ts.isJsxClosingElement(node.parent))) { + // For a JSX element, just highlight the matching tag, not all references. + var _a = node.parent.parent, openingElement = _a.openingElement, closingElement = _a.closingElement; + var highlightSpans = [openingElement, closingElement].map(function (_a) { + var tagName = _a.tagName; + return getHighlightSpanForNode(tagName, sourceFile); + }); + return [{ fileName: sourceFile.fileName, highlightSpans: highlightSpans }]; + } + return getSemanticDocumentHighlights(position, node, program, cancellationToken, sourceFilesToSearch) || getSyntacticDocumentHighlights(node, sourceFile); + } + DocumentHighlights.getDocumentHighlights = getDocumentHighlights; + function getHighlightSpanForNode(node, sourceFile) { + return { + fileName: sourceFile.fileName, + textSpan: ts.createTextSpanFromNode(node, sourceFile), + kind: "none" /* none */ + }; + } + function getSemanticDocumentHighlights(position, node, program, cancellationToken, sourceFilesToSearch) { + var sourceFilesSet = ts.arrayToSet(sourceFilesToSearch, function (f) { return f.fileName; }); + var referenceEntries = ts.FindAllReferences.getReferenceEntriesForNode(position, node, program, sourceFilesToSearch, cancellationToken, /*options*/ undefined, sourceFilesSet); + if (!referenceEntries) + return undefined; + var map = ts.arrayToMultiMap(referenceEntries.map(ts.FindAllReferences.toHighlightSpan), function (e) { return e.fileName; }, function (e) { return e.span; }); + return ts.arrayFrom(map.entries(), function (_a) { + var fileName = _a[0], highlightSpans = _a[1]; + if (!sourceFilesSet.has(fileName)) { + ts.Debug.assert(program.redirectTargetsMap.has(fileName)); + var redirectTarget_1 = program.getSourceFile(fileName); + var redirect = ts.find(sourceFilesToSearch, function (f) { return !!f.redirectInfo && f.redirectInfo.redirectTarget === redirectTarget_1; }); + fileName = redirect.fileName; + ts.Debug.assert(sourceFilesSet.has(fileName)); + } + return { fileName: fileName, highlightSpans: highlightSpans }; + }); + } + function getSyntacticDocumentHighlights(node, sourceFile) { + var highlightSpans = getHighlightSpans(node, sourceFile); + return highlightSpans && [{ fileName: sourceFile.fileName, highlightSpans: highlightSpans }]; + } + function getHighlightSpans(node, sourceFile) { + switch (node.kind) { + case 91 /* IfKeyword */: + case 83 /* ElseKeyword */: + return ts.isIfStatement(node.parent) ? getIfElseOccurrences(node.parent, sourceFile) : undefined; + case 97 /* ReturnKeyword */: + return useParent(node.parent, ts.isReturnStatement, getReturnOccurrences); + case 101 /* ThrowKeyword */: + return useParent(node.parent, ts.isThrowStatement, getThrowOccurrences); + case 103 /* TryKeyword */: + case 75 /* CatchKeyword */: + case 88 /* FinallyKeyword */: + var tryStatement = node.kind === 75 /* CatchKeyword */ ? node.parent.parent : node.parent; + return useParent(tryStatement, ts.isTryStatement, getTryCatchFinallyOccurrences); + case 99 /* SwitchKeyword */: + return useParent(node.parent, ts.isSwitchStatement, getSwitchCaseDefaultOccurrences); + case 74 /* CaseKeyword */: + case 80 /* DefaultKeyword */: + return useParent(node.parent.parent.parent, ts.isSwitchStatement, getSwitchCaseDefaultOccurrences); + case 73 /* BreakKeyword */: + case 78 /* ContinueKeyword */: + return useParent(node.parent, ts.isBreakOrContinueStatement, getBreakOrContinueStatementOccurrences); + case 89 /* ForKeyword */: + case 107 /* WhileKeyword */: + case 82 /* DoKeyword */: + return useParent(node.parent, function (n) { return ts.isIterationStatement(n, /*lookInLabeledStatements*/ true); }, getLoopBreakContinueOccurrences); + case 124 /* ConstructorKeyword */: + return getFromAllDeclarations(ts.isConstructorDeclaration, [124 /* ConstructorKeyword */]); + case 126 /* GetKeyword */: + case 137 /* SetKeyword */: + return getFromAllDeclarations(ts.isAccessor, [126 /* GetKeyword */, 137 /* SetKeyword */]); + case 122 /* AwaitKeyword */: + return useParent(node.parent, ts.isAwaitExpression, getAsyncAndAwaitOccurrences); + case 121 /* AsyncKeyword */: + return highlightSpans(getAsyncAndAwaitOccurrences(node)); + case 117 /* YieldKeyword */: + return highlightSpans(getYieldOccurrences(node)); + default: + return ts.isModifierKind(node.kind) && (ts.isDeclaration(node.parent) || ts.isVariableStatement(node.parent)) + ? highlightSpans(getModifierOccurrences(node.kind, node.parent)) + : undefined; + } + function getFromAllDeclarations(nodeTest, keywords) { + return useParent(node.parent, nodeTest, function (decl) { return ts.mapDefined(decl.symbol.declarations, function (d) { + return nodeTest(d) ? ts.find(d.getChildren(sourceFile), function (c) { return ts.contains(keywords, c.kind); }) : undefined; + }); }); + } + function useParent(node, nodeTest, getNodes) { + return nodeTest(node) ? highlightSpans(getNodes(node, sourceFile)) : undefined; + } + function highlightSpans(nodes) { + return nodes && nodes.map(function (node) { return getHighlightSpanForNode(node, sourceFile); }); + } + } + /** + * Aggregates all throw-statements within this node *without* crossing + * into function boundaries and try-blocks with catch-clauses. + */ + function aggregateOwnedThrowStatements(node) { + if (ts.isThrowStatement(node)) { + return [node]; + } + else if (ts.isTryStatement(node)) { + // Exceptions thrown within a try block lacking a catch clause are "owned" in the current context. + return ts.concatenate(node.catchClause ? aggregateOwnedThrowStatements(node.catchClause) : node.tryBlock && aggregateOwnedThrowStatements(node.tryBlock), node.finallyBlock && aggregateOwnedThrowStatements(node.finallyBlock)); + } + // Do not cross function boundaries. + return ts.isFunctionLike(node) ? undefined : flatMapChildren(node, aggregateOwnedThrowStatements); + } + /** + * For lack of a better name, this function takes a throw statement and returns the + * nearest ancestor that is a try-block (whose try statement has a catch clause), + * function-block, or source file. + */ + function getThrowStatementOwner(throwStatement) { + var child = throwStatement; + while (child.parent) { + var parent = child.parent; + if (ts.isFunctionBlock(parent) || parent.kind === 279 /* SourceFile */) { + return parent; + } + // A throw-statement is only owned by a try-statement if the try-statement has + // a catch clause, and if the throw-statement occurs within the try block. + if (ts.isTryStatement(parent) && parent.tryBlock === child && parent.catchClause) { + return child; + } + child = parent; + } + return undefined; + } + function aggregateAllBreakAndContinueStatements(node) { + return ts.isBreakOrContinueStatement(node) ? [node] : ts.isFunctionLike(node) ? undefined : flatMapChildren(node, aggregateAllBreakAndContinueStatements); + } + function flatMapChildren(node, cb) { + var result = []; + node.forEachChild(function (child) { + var value = cb(child); + if (value !== undefined) { + result.push.apply(result, ts.toArray(value)); + } + }); + return result; + } + function ownsBreakOrContinueStatement(owner, statement) { + var actualOwner = getBreakOrContinueOwner(statement); + return !!actualOwner && actualOwner === owner; + } + function getBreakOrContinueOwner(statement) { + return ts.findAncestor(statement, function (node) { + switch (node.kind) { + case 232 /* SwitchStatement */: + if (statement.kind === 228 /* ContinueStatement */) { + return false; + } + // falls through + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + case 224 /* WhileStatement */: + case 223 /* DoStatement */: + return !statement.label || isLabeledBy(node, statement.label.escapedText); + default: + // Don't cross function boundaries. + // TODO: GH#20090 + return ts.isFunctionLike(node) && "quit"; + } + }); + } + function getModifierOccurrences(modifier, declaration) { + return ts.mapDefined(getNodesToSearchForModifier(declaration, ts.modifierToFlag(modifier)), function (node) { return ts.findModifier(node, modifier); }); + } + function getNodesToSearchForModifier(declaration, modifierFlag) { + // Types of node whose children might have modifiers. + var container = declaration.parent; + switch (container.kind) { + case 245 /* ModuleBlock */: + case 279 /* SourceFile */: + case 218 /* Block */: + case 271 /* CaseClause */: + case 272 /* DefaultClause */: + // Container is either a class declaration or the declaration is a classDeclaration + if (modifierFlag & 128 /* Abstract */ && ts.isClassDeclaration(declaration)) { + return declaration.members.concat([declaration]); + } + else { + return container.statements; + } + case 157 /* Constructor */: + case 156 /* MethodDeclaration */: + case 239 /* FunctionDeclaration */: + return container.parameters.concat((ts.isClassLike(container.parent) ? container.parent.members : [])); + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + var nodes = container.members; + // If we're an accessibility modifier, we're in an instance member and should search + // the constructor's parameter list for instance members as well. + if (modifierFlag & 28 /* AccessibilityModifier */) { + var constructor = ts.find(container.members, ts.isConstructorDeclaration); + if (constructor) { + return nodes.concat(constructor.parameters); + } + } + else if (modifierFlag & 128 /* Abstract */) { + return nodes.concat([container]); + } + return nodes; + default: + ts.Debug.assertNever(container, "Invalid container kind."); + } + } + function pushKeywordIf(keywordList, token) { + var expected = []; + for (var _i = 2; _i < arguments.length; _i++) { + expected[_i - 2] = arguments[_i]; + } + if (token && ts.contains(expected, token.kind)) { + keywordList.push(token); + return true; + } + return false; + } + function getLoopBreakContinueOccurrences(loopNode) { + var keywords = []; + if (pushKeywordIf(keywords, loopNode.getFirstToken(), 89 /* ForKeyword */, 107 /* WhileKeyword */, 82 /* DoKeyword */)) { + // If we succeeded and got a do-while loop, then start looking for a 'while' keyword. + if (loopNode.kind === 223 /* DoStatement */) { + var loopTokens = loopNode.getChildren(); + for (var i = loopTokens.length - 1; i >= 0; i--) { + if (pushKeywordIf(keywords, loopTokens[i], 107 /* WhileKeyword */)) { + break; + } + } + } + } + ts.forEach(aggregateAllBreakAndContinueStatements(loopNode.statement), function (statement) { + if (ownsBreakOrContinueStatement(loopNode, statement)) { + pushKeywordIf(keywords, statement.getFirstToken(), 73 /* BreakKeyword */, 78 /* ContinueKeyword */); + } + }); + return keywords; + } + function getBreakOrContinueStatementOccurrences(breakOrContinueStatement) { + var owner = getBreakOrContinueOwner(breakOrContinueStatement); + if (owner) { + switch (owner.kind) { + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + case 223 /* DoStatement */: + case 224 /* WhileStatement */: + return getLoopBreakContinueOccurrences(owner); + case 232 /* SwitchStatement */: + return getSwitchCaseDefaultOccurrences(owner); + } + } + return undefined; + } + function getSwitchCaseDefaultOccurrences(switchStatement) { + var keywords = []; + pushKeywordIf(keywords, switchStatement.getFirstToken(), 99 /* SwitchKeyword */); + // Go through each clause in the switch statement, collecting the 'case'/'default' keywords. + ts.forEach(switchStatement.caseBlock.clauses, function (clause) { + pushKeywordIf(keywords, clause.getFirstToken(), 74 /* CaseKeyword */, 80 /* DefaultKeyword */); + ts.forEach(aggregateAllBreakAndContinueStatements(clause), function (statement) { + if (ownsBreakOrContinueStatement(switchStatement, statement)) { + pushKeywordIf(keywords, statement.getFirstToken(), 73 /* BreakKeyword */); + } + }); + }); + return keywords; + } + function getTryCatchFinallyOccurrences(tryStatement, sourceFile) { + var keywords = []; + pushKeywordIf(keywords, tryStatement.getFirstToken(), 103 /* TryKeyword */); + if (tryStatement.catchClause) { + pushKeywordIf(keywords, tryStatement.catchClause.getFirstToken(), 75 /* CatchKeyword */); + } + if (tryStatement.finallyBlock) { + var finallyKeyword = ts.findChildOfKind(tryStatement, 88 /* FinallyKeyword */, sourceFile); + pushKeywordIf(keywords, finallyKeyword, 88 /* FinallyKeyword */); + } + return keywords; + } + function getThrowOccurrences(throwStatement, sourceFile) { + var owner = getThrowStatementOwner(throwStatement); + if (!owner) { + return undefined; + } + var keywords = []; + ts.forEach(aggregateOwnedThrowStatements(owner), function (throwStatement) { + keywords.push(ts.findChildOfKind(throwStatement, 101 /* ThrowKeyword */, sourceFile)); + }); + // If the "owner" is a function, then we equate 'return' and 'throw' statements in their + // ability to "jump out" of the function, and include occurrences for both. + if (ts.isFunctionBlock(owner)) { + ts.forEachReturnStatement(owner, function (returnStatement) { + keywords.push(ts.findChildOfKind(returnStatement, 97 /* ReturnKeyword */, sourceFile)); + }); + } + return keywords; + } + function getReturnOccurrences(returnStatement, sourceFile) { + var func = ts.getContainingFunction(returnStatement); + if (!func) { + return undefined; + } + var keywords = []; + ts.forEachReturnStatement(ts.cast(func.body, ts.isBlock), function (returnStatement) { + keywords.push(ts.findChildOfKind(returnStatement, 97 /* ReturnKeyword */, sourceFile)); + }); + // Include 'throw' statements that do not occur within a try block. + ts.forEach(aggregateOwnedThrowStatements(func.body), function (throwStatement) { + keywords.push(ts.findChildOfKind(throwStatement, 101 /* ThrowKeyword */, sourceFile)); + }); + return keywords; + } + function getAsyncAndAwaitOccurrences(node) { + var func = ts.getContainingFunction(node); + if (!func) { + return undefined; + } + var keywords = []; + if (func.modifiers) { + func.modifiers.forEach(function (modifier) { + pushKeywordIf(keywords, modifier, 121 /* AsyncKeyword */); + }); + } + ts.forEachChild(func, function (child) { + traverseWithoutCrossingFunction(child, function (node) { + if (ts.isAwaitExpression(node)) { + pushKeywordIf(keywords, node.getFirstToken(), 122 /* AwaitKeyword */); + } + }); + }); + return keywords; + } + function getYieldOccurrences(node) { + var func = ts.getContainingFunction(node); + if (!func) { + return undefined; + } + var keywords = []; + ts.forEachChild(func, function (child) { + traverseWithoutCrossingFunction(child, function (node) { + if (ts.isYieldExpression(node)) { + pushKeywordIf(keywords, node.getFirstToken(), 117 /* YieldKeyword */); + } + }); + }); + return keywords; + } + // Do not cross function/class/interface/module/type boundaries. + function traverseWithoutCrossingFunction(node, cb) { + cb(node); + if (!ts.isFunctionLike(node) && !ts.isClassLike(node) && !ts.isInterfaceDeclaration(node) && !ts.isModuleDeclaration(node) && !ts.isTypeAliasDeclaration(node) && !ts.isTypeNode(node)) { + ts.forEachChild(node, function (child) { return traverseWithoutCrossingFunction(child, cb); }); + } + } + function getIfElseOccurrences(ifStatement, sourceFile) { + var keywords = getIfElseKeywords(ifStatement, sourceFile); + var result = []; + // We'd like to highlight else/ifs together if they are only separated by whitespace + // (i.e. the keywords are separated by no comments, no newlines). + for (var i = 0; i < keywords.length; i++) { + if (keywords[i].kind === 83 /* ElseKeyword */ && i < keywords.length - 1) { + var elseKeyword = keywords[i]; + var ifKeyword = keywords[i + 1]; // this *should* always be an 'if' keyword. + var shouldCombineElseAndIf = true; + // Avoid recalculating getStart() by iterating backwards. + for (var j = ifKeyword.getStart(sourceFile) - 1; j >= elseKeyword.end; j--) { + if (!ts.isWhiteSpaceSingleLine(sourceFile.text.charCodeAt(j))) { + shouldCombineElseAndIf = false; + break; + } + } + if (shouldCombineElseAndIf) { + result.push({ + fileName: sourceFile.fileName, + textSpan: ts.createTextSpanFromBounds(elseKeyword.getStart(), ifKeyword.end), + kind: "reference" /* reference */ + }); + i++; // skip the next keyword + continue; + } + } + // Ordinary case: just highlight the keyword. + result.push(getHighlightSpanForNode(keywords[i], sourceFile)); + } + return result; + } + function getIfElseKeywords(ifStatement, sourceFile) { + var keywords = []; + // Traverse upwards through all parent if-statements linked by their else-branches. + while (ts.isIfStatement(ifStatement.parent) && ifStatement.parent.elseStatement === ifStatement) { + ifStatement = ifStatement.parent; + } + // Now traverse back down through the else branches, aggregating if/else keywords of if-statements. + while (true) { + var children = ifStatement.getChildren(sourceFile); + pushKeywordIf(keywords, children[0], 91 /* IfKeyword */); + // Generally the 'else' keyword is second-to-last, so we traverse backwards. + for (var i = children.length - 1; i >= 0; i--) { + if (pushKeywordIf(keywords, children[i], 83 /* ElseKeyword */)) { + break; + } + } + if (!ifStatement.elseStatement || !ts.isIfStatement(ifStatement.elseStatement)) { + break; + } + ifStatement = ifStatement.elseStatement; + } + return keywords; + } + /** + * Whether or not a 'node' is preceded by a label of the given string. + * Note: 'node' cannot be a SourceFile. + */ + function isLabeledBy(node, labelName) { + return !!ts.findAncestor(node.parent, function (owner) { return !ts.isLabeledStatement(owner) ? "quit" : owner.label.escapedText === labelName; }); + } + })(DocumentHighlights = ts.DocumentHighlights || (ts.DocumentHighlights = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + function createDocumentRegistry(useCaseSensitiveFileNames, currentDirectory) { + return createDocumentRegistryInternal(useCaseSensitiveFileNames, currentDirectory); + } + ts.createDocumentRegistry = createDocumentRegistry; + /*@internal*/ + function createDocumentRegistryInternal(useCaseSensitiveFileNames, currentDirectory, externalCache) { + if (currentDirectory === void 0) { currentDirectory = ""; } + // Maps from compiler setting target (ES3, ES5, etc.) to all the cached documents we have + // for those settings. + var buckets = ts.createMap(); + var getCanonicalFileName = ts.createGetCanonicalFileName(!!useCaseSensitiveFileNames); + function reportStats() { + var bucketInfoArray = ts.arrayFrom(buckets.keys()).filter(function (name) { return name && name.charAt(0) === "_"; }).map(function (name) { + var entries = buckets.get(name); + var sourceFiles = []; + entries.forEach(function (entry, name) { + sourceFiles.push({ + name: name, + refCount: entry.languageServiceRefCount + }); + }); + sourceFiles.sort(function (x, y) { return y.refCount - x.refCount; }); + return { + bucket: name, + sourceFiles: sourceFiles + }; + }); + return JSON.stringify(bucketInfoArray, undefined, 2); + } + function acquireDocument(fileName, compilationSettings, scriptSnapshot, version, scriptKind) { + var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); + var key = getKeyForCompilationSettings(compilationSettings); + return acquireDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind); + } + function acquireDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind) { + return acquireOrUpdateDocument(fileName, path, compilationSettings, key, scriptSnapshot, version, /*acquiring*/ true, scriptKind); + } + function updateDocument(fileName, compilationSettings, scriptSnapshot, version, scriptKind) { + var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); + var key = getKeyForCompilationSettings(compilationSettings); + return updateDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind); + } + function updateDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind) { + return acquireOrUpdateDocument(fileName, path, compilationSettings, key, scriptSnapshot, version, /*acquiring*/ false, scriptKind); + } + function acquireOrUpdateDocument(fileName, path, compilationSettings, key, scriptSnapshot, version, acquiring, scriptKind) { + var bucket = ts.getOrUpdate(buckets, key, ts.createMap); + var entry = bucket.get(path); + var scriptTarget = scriptKind === 6 /* JSON */ ? 100 /* JSON */ : compilationSettings.target || 1 /* ES5 */; + if (!entry && externalCache) { + var sourceFile = externalCache.getDocument(key, path); + if (sourceFile) { + ts.Debug.assert(acquiring); + entry = { + sourceFile: sourceFile, + languageServiceRefCount: 0 + }; + bucket.set(path, entry); + } + } + if (!entry) { + // Have never seen this file with these settings. Create a new source file for it. + var sourceFile = ts.createLanguageServiceSourceFile(fileName, scriptSnapshot, scriptTarget, version, /*setNodeParents*/ false, scriptKind); + if (externalCache) { + externalCache.setDocument(key, path, sourceFile); + } + entry = { + sourceFile: sourceFile, + languageServiceRefCount: 1, + }; + bucket.set(path, entry); + } + else { + // We have an entry for this file. However, it may be for a different version of + // the script snapshot. If so, update it appropriately. Otherwise, we can just + // return it as is. + if (entry.sourceFile.version !== version) { + entry.sourceFile = ts.updateLanguageServiceSourceFile(entry.sourceFile, scriptSnapshot, version, scriptSnapshot.getChangeRange(entry.sourceFile.scriptSnapshot)); // TODO: GH#18217 + if (externalCache) { + externalCache.setDocument(key, path, entry.sourceFile); + } + } + // If we're acquiring, then this is the first time this LS is asking for this document. + // Increase our ref count so we know there's another LS using the document. If we're + // not acquiring, then that means the LS is 'updating' the file instead, and that means + // it has already acquired the document previously. As such, we do not need to increase + // the ref count. + if (acquiring) { + entry.languageServiceRefCount++; + } + } + ts.Debug.assert(entry.languageServiceRefCount !== 0); + return entry.sourceFile; + } + function releaseDocument(fileName, compilationSettings) { + var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); + var key = getKeyForCompilationSettings(compilationSettings); + return releaseDocumentWithKey(path, key); + } + function releaseDocumentWithKey(path, key) { + var bucket = ts.Debug.assertDefined(buckets.get(key)); + var entry = bucket.get(path); + entry.languageServiceRefCount--; + ts.Debug.assert(entry.languageServiceRefCount >= 0); + if (entry.languageServiceRefCount === 0) { + bucket.delete(path); + } + } + function getLanguageServiceRefCounts(path) { + return ts.arrayFrom(buckets.entries(), function (_a) { + var key = _a[0], bucket = _a[1]; + var entry = bucket.get(path); + return [key, entry && entry.languageServiceRefCount]; + }); + } + return { + acquireDocument: acquireDocument, + acquireDocumentWithKey: acquireDocumentWithKey, + updateDocument: updateDocument, + updateDocumentWithKey: updateDocumentWithKey, + releaseDocument: releaseDocument, + releaseDocumentWithKey: releaseDocumentWithKey, + getLanguageServiceRefCounts: getLanguageServiceRefCounts, + reportStats: reportStats, + getKeyForCompilationSettings: getKeyForCompilationSettings + }; + } + ts.createDocumentRegistryInternal = createDocumentRegistryInternal; + function getKeyForCompilationSettings(settings) { + return ts.sourceFileAffectingCompilerOptions.map(function (option) { return ts.getCompilerOptionValue(settings, option); }).join("|"); + } +})(ts || (ts = {})); +/* Code for finding imports of an exported symbol. Used only by FindAllReferences. */ +/* @internal */ +var ts; +(function (ts) { + var FindAllReferences; + (function (FindAllReferences) { + /** Creates the imports map and returns an ImportTracker that uses it. Call this lazily to avoid calling `getDirectImportsMap` unnecessarily. */ + function createImportTracker(sourceFiles, sourceFilesSet, checker, cancellationToken) { + var allDirectImports = getDirectImportsMap(sourceFiles, checker, cancellationToken); + return function (exportSymbol, exportInfo, isForRename) { + var _a = getImportersForExport(sourceFiles, sourceFilesSet, allDirectImports, exportInfo, checker, cancellationToken), directImports = _a.directImports, indirectUsers = _a.indirectUsers; + return __assign({ indirectUsers: indirectUsers }, getSearchesFromDirectImports(directImports, exportSymbol, exportInfo.exportKind, checker, isForRename)); + }; + } + FindAllReferences.createImportTracker = createImportTracker; + var ExportKind; + (function (ExportKind) { + ExportKind[ExportKind["Named"] = 0] = "Named"; + ExportKind[ExportKind["Default"] = 1] = "Default"; + ExportKind[ExportKind["ExportEquals"] = 2] = "ExportEquals"; + })(ExportKind = FindAllReferences.ExportKind || (FindAllReferences.ExportKind = {})); + var ImportExport; + (function (ImportExport) { + ImportExport[ImportExport["Import"] = 0] = "Import"; + ImportExport[ImportExport["Export"] = 1] = "Export"; + })(ImportExport = FindAllReferences.ImportExport || (FindAllReferences.ImportExport = {})); + /** Returns import statements that directly reference the exporting module, and a list of files that may access the module through a namespace. */ + function getImportersForExport(sourceFiles, sourceFilesSet, allDirectImports, _a, checker, cancellationToken) { + var exportingModuleSymbol = _a.exportingModuleSymbol, exportKind = _a.exportKind; + var markSeenDirectImport = ts.nodeSeenTracker(); + var markSeenIndirectUser = ts.nodeSeenTracker(); + var directImports = []; + var isAvailableThroughGlobal = !!exportingModuleSymbol.globalExports; + var indirectUserDeclarations = isAvailableThroughGlobal ? undefined : []; + handleDirectImports(exportingModuleSymbol); + return { directImports: directImports, indirectUsers: getIndirectUsers() }; + function getIndirectUsers() { + if (isAvailableThroughGlobal) { + // It has `export as namespace`, so anything could potentially use it. + return sourceFiles; + } + // Module augmentations may use this module's exports without importing it. + for (var _i = 0, _a = exportingModuleSymbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + if (ts.isExternalModuleAugmentation(decl) && sourceFilesSet.has(decl.getSourceFile().fileName)) { + addIndirectUser(decl); + } + } + // This may return duplicates (if there are multiple module declarations in a single source file, all importing the same thing as a namespace), but `State.markSearchedSymbol` will handle that. + return indirectUserDeclarations.map(ts.getSourceFileOfNode); + } + function handleDirectImports(exportingModuleSymbol) { + var theseDirectImports = getDirectImports(exportingModuleSymbol); + if (theseDirectImports) { + for (var _i = 0, theseDirectImports_1 = theseDirectImports; _i < theseDirectImports_1.length; _i++) { + var direct = theseDirectImports_1[_i]; + if (!markSeenDirectImport(direct)) { + continue; + } + if (cancellationToken) + cancellationToken.throwIfCancellationRequested(); + switch (direct.kind) { + case 191 /* CallExpression */: + if (!isAvailableThroughGlobal) { + var parent = direct.parent; + if (exportKind === 2 /* ExportEquals */ && parent.kind === 237 /* VariableDeclaration */) { + var name = parent.name; + if (name.kind === 72 /* Identifier */) { + directImports.push(name); + break; + } + } + // Don't support re-exporting 'require()' calls, so just add a single indirect user. + addIndirectUser(direct.getSourceFile()); + } + break; + case 72 /* Identifier */: // for 'const x = require("y"); + break; // TODO: GH#23879 + case 248 /* ImportEqualsDeclaration */: + handleNamespaceImport(direct, direct.name, ts.hasModifier(direct, 1 /* Export */), /*alreadyAddedDirect*/ false); + break; + case 249 /* ImportDeclaration */: + directImports.push(direct); + var namedBindings = direct.importClause && direct.importClause.namedBindings; + if (namedBindings && namedBindings.kind === 251 /* NamespaceImport */) { + handleNamespaceImport(direct, namedBindings.name, /*isReExport*/ false, /*alreadyAddedDirect*/ true); + } + else if (!isAvailableThroughGlobal && ts.isDefaultImport(direct)) { + addIndirectUser(getSourceFileLikeForImportDeclaration(direct)); // Add a check for indirect uses to handle synthetic default imports + } + break; + case 255 /* ExportDeclaration */: + if (!direct.exportClause) { + // This is `export * from "foo"`, so imports of this module may import the export too. + handleDirectImports(getContainingModuleSymbol(direct, checker)); + } + else { + // This is `export { foo } from "foo"` and creates an alias symbol, so recursive search will get handle re-exports. + directImports.push(direct); + } + break; + case 183 /* ImportType */: + directImports.push(direct); + break; + default: + ts.Debug.assertNever(direct, "Unexpected import kind: " + ts.Debug.showSyntaxKind(direct)); + } + } + } + } + function handleNamespaceImport(importDeclaration, name, isReExport, alreadyAddedDirect) { + if (exportKind === 2 /* ExportEquals */) { + // This is a direct import, not import-as-namespace. + if (!alreadyAddedDirect) + directImports.push(importDeclaration); + } + else if (!isAvailableThroughGlobal) { + var sourceFileLike = getSourceFileLikeForImportDeclaration(importDeclaration); + ts.Debug.assert(sourceFileLike.kind === 279 /* SourceFile */ || sourceFileLike.kind === 244 /* ModuleDeclaration */); + if (isReExport || findNamespaceReExports(sourceFileLike, name, checker)) { + addIndirectUsers(sourceFileLike); + } + else { + addIndirectUser(sourceFileLike); + } + } + } + function addIndirectUser(sourceFileLike) { + ts.Debug.assert(!isAvailableThroughGlobal); + var isNew = markSeenIndirectUser(sourceFileLike); + if (isNew) { + indirectUserDeclarations.push(sourceFileLike); // TODO: GH#18217 + } + return isNew; + } + /** Adds a module and all of its transitive dependencies as possible indirect users. */ + function addIndirectUsers(sourceFileLike) { + if (!addIndirectUser(sourceFileLike)) { + return; + } + var moduleSymbol = checker.getMergedSymbol(sourceFileLike.symbol); + ts.Debug.assert(!!(moduleSymbol.flags & 1536 /* Module */)); + var directImports = getDirectImports(moduleSymbol); + if (directImports) { + for (var _i = 0, directImports_1 = directImports; _i < directImports_1.length; _i++) { + var directImport = directImports_1[_i]; + addIndirectUsers(getSourceFileLikeForImportDeclaration(directImport)); + } + } + } + function getDirectImports(moduleSymbol) { + return allDirectImports.get(ts.getSymbolId(moduleSymbol).toString()); + } + } + /** + * Given the set of direct imports of a module, we need to find which ones import the particular exported symbol. + * The returned `importSearches` will result in the entire source file being searched. + * But re-exports will be placed in 'singleReferences' since they cannot be locally referenced. + */ + function getSearchesFromDirectImports(directImports, exportSymbol, exportKind, checker, isForRename) { + var importSearches = []; + var singleReferences = []; + function addSearch(location, symbol) { + importSearches.push([location, symbol]); + } + if (directImports) { + for (var _i = 0, directImports_2 = directImports; _i < directImports_2.length; _i++) { + var decl = directImports_2[_i]; + handleImport(decl); + } + } + return { importSearches: importSearches, singleReferences: singleReferences }; + function handleImport(decl) { + if (decl.kind === 248 /* ImportEqualsDeclaration */) { + if (isExternalModuleImportEquals(decl)) { + handleNamespaceImportLike(decl.name); + } + return; + } + if (decl.kind === 72 /* Identifier */) { + handleNamespaceImportLike(decl); + return; + } + if (decl.kind === 183 /* ImportType */) { + if (decl.qualifier) { + if (ts.isIdentifier(decl.qualifier) && decl.qualifier.escapedText === ts.symbolName(exportSymbol)) { + singleReferences.push(decl.qualifier); + } + } + else if (exportKind === 2 /* ExportEquals */) { + singleReferences.push(decl.argument.literal); + } + return; + } + // Ignore if there's a grammar error + if (decl.moduleSpecifier.kind !== 10 /* StringLiteral */) { + return; + } + if (decl.kind === 255 /* ExportDeclaration */) { + searchForNamedImport(decl.exportClause); + return; + } + var _a = decl.importClause || { name: undefined, namedBindings: undefined }, name = _a.name, namedBindings = _a.namedBindings; + if (namedBindings) { + switch (namedBindings.kind) { + case 251 /* NamespaceImport */: + handleNamespaceImportLike(namedBindings.name); + break; + case 252 /* NamedImports */: + // 'default' might be accessed as a named import `{ default as foo }`. + if (exportKind === 0 /* Named */ || exportKind === 1 /* Default */) { + searchForNamedImport(namedBindings); + } + break; + default: + ts.Debug.assertNever(namedBindings); + } + } + // `export =` might be imported by a default import if `--allowSyntheticDefaultImports` is on, so this handles both ExportKind.Default and ExportKind.ExportEquals. + // If a default import has the same name as the default export, allow to rename it. + // Given `import f` and `export default function f`, we will rename both, but for `import g` we will rename just that. + if (name && (exportKind === 1 /* Default */ || exportKind === 2 /* ExportEquals */) && (!isForRename || name.escapedText === ts.symbolEscapedNameNoDefault(exportSymbol))) { + var defaultImportAlias = checker.getSymbolAtLocation(name); + addSearch(name, defaultImportAlias); + } + } + /** + * `import x = require("./x") or `import * as x from "./x"`. + * An `export =` may be imported by this syntax, so it may be a direct import. + * If it's not a direct import, it will be in `indirectUsers`, so we don't have to do anything here. + */ + function handleNamespaceImportLike(importName) { + // Don't rename an import that already has a different name than the export. + if (exportKind === 2 /* ExportEquals */ && (!isForRename || isNameMatch(importName.escapedText))) { + addSearch(importName, checker.getSymbolAtLocation(importName)); + } + } + function searchForNamedImport(namedBindings) { + if (!namedBindings) { + return; + } + for (var _i = 0, _a = namedBindings.elements; _i < _a.length; _i++) { + var element = _a[_i]; + var name = element.name, propertyName = element.propertyName; + if (!isNameMatch((propertyName || name).escapedText)) { + continue; + } + if (propertyName) { + // This is `import { foo as bar } from "./a"` or `export { foo as bar } from "./a"`. `foo` isn't a local in the file, so just add it as a single reference. + singleReferences.push(propertyName); + // If renaming `{ foo as bar }`, don't touch `bar`, just `foo`. + // But do rename `foo` in ` { default as foo }` if that's the original export name. + if (!isForRename || name.escapedText === exportSymbol.escapedName) { + // Search locally for `bar`. + addSearch(name, checker.getSymbolAtLocation(name)); + } + } + else { + var localSymbol = element.kind === 257 /* ExportSpecifier */ && element.propertyName + ? checker.getExportSpecifierLocalTargetSymbol(element) // For re-exporting under a different name, we want to get the re-exported symbol. + : checker.getSymbolAtLocation(name); + addSearch(name, localSymbol); + } + } + } + function isNameMatch(name) { + // Use name of "default" even in `export =` case because we may have allowSyntheticDefaultImports + return name === exportSymbol.escapedName || exportKind !== 0 /* Named */ && name === "default" /* Default */; + } + } + /** Returns 'true' is the namespace 'name' is re-exported from this module, and 'false' if it is only used locally. */ + function findNamespaceReExports(sourceFileLike, name, checker) { + var namespaceImportSymbol = checker.getSymbolAtLocation(name); + return !!forEachPossibleImportOrExportStatement(sourceFileLike, function (statement) { + if (!ts.isExportDeclaration(statement)) + return; + var exportClause = statement.exportClause, moduleSpecifier = statement.moduleSpecifier; + return !moduleSpecifier && exportClause && + exportClause.elements.some(function (element) { return checker.getExportSpecifierLocalTargetSymbol(element) === namespaceImportSymbol; }); + }); + } + function findModuleReferences(program, sourceFiles, searchModuleSymbol) { + var refs = []; + var checker = program.getTypeChecker(); + for (var _i = 0, sourceFiles_3 = sourceFiles; _i < sourceFiles_3.length; _i++) { + var referencingFile = sourceFiles_3[_i]; + var searchSourceFile = searchModuleSymbol.valueDeclaration; + if (searchSourceFile.kind === 279 /* SourceFile */) { + for (var _a = 0, _b = referencingFile.referencedFiles; _a < _b.length; _a++) { + var ref = _b[_a]; + if (program.getSourceFileFromReference(referencingFile, ref) === searchSourceFile) { + refs.push({ kind: "reference", referencingFile: referencingFile, ref: ref }); + } + } + for (var _c = 0, _d = referencingFile.typeReferenceDirectives; _c < _d.length; _c++) { + var ref = _d[_c]; + var referenced = program.getResolvedTypeReferenceDirectives().get(ref.fileName); + if (referenced !== undefined && referenced.resolvedFileName === searchSourceFile.fileName) { + refs.push({ kind: "reference", referencingFile: referencingFile, ref: ref }); + } + } + } + forEachImport(referencingFile, function (_importDecl, moduleSpecifier) { + var moduleSymbol = checker.getSymbolAtLocation(moduleSpecifier); + if (moduleSymbol === searchModuleSymbol) { + refs.push({ kind: "import", literal: moduleSpecifier }); + } + }); + } + return refs; + } + FindAllReferences.findModuleReferences = findModuleReferences; + /** Returns a map from a module symbol Id to all import statements that directly reference the module. */ + function getDirectImportsMap(sourceFiles, checker, cancellationToken) { + var map = ts.createMap(); + for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) { + var sourceFile = sourceFiles_4[_i]; + if (cancellationToken) + cancellationToken.throwIfCancellationRequested(); + forEachImport(sourceFile, function (importDecl, moduleSpecifier) { + var moduleSymbol = checker.getSymbolAtLocation(moduleSpecifier); + if (moduleSymbol) { + var id = ts.getSymbolId(moduleSymbol).toString(); + var imports = map.get(id); + if (!imports) { + map.set(id, imports = []); + } + imports.push(importDecl); + } + }); + } + return map; + } + /** Iterates over all statements at the top level or in module declarations. Returns the first truthy result. */ + function forEachPossibleImportOrExportStatement(sourceFileLike, action) { + return ts.forEach(sourceFileLike.kind === 279 /* SourceFile */ ? sourceFileLike.statements : sourceFileLike.body.statements, function (statement) { + return action(statement) || (isAmbientModuleDeclaration(statement) && ts.forEach(statement.body && statement.body.statements, action)); + }); + } + /** Calls `action` for each import, re-export, or require() in a file. */ + function forEachImport(sourceFile, action) { + if (sourceFile.externalModuleIndicator || sourceFile.imports !== undefined) { + for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { + var i = _a[_i]; + action(ts.importFromModuleSpecifier(i), i); + } + } + else { + forEachPossibleImportOrExportStatement(sourceFile, function (statement) { + switch (statement.kind) { + case 255 /* ExportDeclaration */: + case 249 /* ImportDeclaration */: { + var decl = statement; + if (decl.moduleSpecifier && ts.isStringLiteral(decl.moduleSpecifier)) { + action(decl, decl.moduleSpecifier); + } + break; + } + case 248 /* ImportEqualsDeclaration */: { + var decl = statement; + if (isExternalModuleImportEquals(decl)) { + action(decl, decl.moduleReference.expression); + } + break; + } + } + }); + } + } + /** + * Given a local reference, we might notice that it's an import/export and recursively search for references of that. + * If at an import, look locally for the symbol it imports. + * If an an export, look for all imports of it. + * This doesn't handle export specifiers; that is done in `getReferencesAtExportSpecifier`. + * @param comingFromExport If we are doing a search for all exports, don't bother looking backwards for the imported symbol, since that's the reason we're here. + */ + function getImportOrExportSymbol(node, symbol, checker, comingFromExport) { + return comingFromExport ? getExport() : getExport() || getImport(); + function getExport() { + var parent = node.parent; + var grandParent = parent.parent; + if (symbol.exportSymbol) { + if (parent.kind === 189 /* PropertyAccessExpression */) { + // When accessing an export of a JS module, there's no alias. The symbol will still be flagged as an export even though we're at the use. + // So check that we are at the declaration. + return symbol.declarations.some(function (d) { return d === parent; }) && ts.isBinaryExpression(grandParent) + ? getSpecialPropertyExport(grandParent, /*useLhsSymbol*/ false) + : undefined; + } + else { + return exportInfo(symbol.exportSymbol, getExportKindForDeclaration(parent)); + } + } + else { + var exportNode = getExportNode(parent, node); + if (exportNode && ts.hasModifier(exportNode, 1 /* Export */)) { + if (ts.isImportEqualsDeclaration(exportNode) && exportNode.moduleReference === node) { + // We're at `Y` in `export import X = Y`. This is not the exported symbol, the left-hand-side is. So treat this as an import statement. + if (comingFromExport) { + return undefined; + } + var lhsSymbol = checker.getSymbolAtLocation(exportNode.name); + return { kind: 0 /* Import */, symbol: lhsSymbol }; + } + else { + return exportInfo(symbol, getExportKindForDeclaration(exportNode)); + } + } + // If we are in `export = a;` or `export default a;`, `parent` is the export assignment. + else if (ts.isExportAssignment(parent)) { + return getExportAssignmentExport(parent); + } + // If we are in `export = class A {};` (or `export = class A {};`) at `A`, `parent.parent` is the export assignment. + else if (ts.isExportAssignment(grandParent)) { + return getExportAssignmentExport(grandParent); + } + // Similar for `module.exports =` and `exports.A =`. + else if (ts.isBinaryExpression(parent)) { + return getSpecialPropertyExport(parent, /*useLhsSymbol*/ true); + } + else if (ts.isBinaryExpression(grandParent)) { + return getSpecialPropertyExport(grandParent, /*useLhsSymbol*/ true); + } + else if (ts.isJSDocTypedefTag(parent)) { + return exportInfo(symbol, 0 /* Named */); + } + } + function getExportAssignmentExport(ex) { + // Get the symbol for the `export =` node; its parent is the module it's the export of. + var exportingModuleSymbol = ts.Debug.assertDefined(ex.symbol.parent, "Expected export symbol to have a parent"); + var exportKind = ex.isExportEquals ? 2 /* ExportEquals */ : 1 /* Default */; + return { kind: 1 /* Export */, symbol: symbol, exportInfo: { exportingModuleSymbol: exportingModuleSymbol, exportKind: exportKind } }; + } + function getSpecialPropertyExport(node, useLhsSymbol) { + var kind; + switch (ts.getAssignmentDeclarationKind(node)) { + case 1 /* ExportsProperty */: + kind = 0 /* Named */; + break; + case 2 /* ModuleExports */: + kind = 2 /* ExportEquals */; + break; + default: + return undefined; + } + var sym = useLhsSymbol ? checker.getSymbolAtLocation(ts.cast(node.left, ts.isPropertyAccessExpression).name) : symbol; + // Better detection for GH#20803 + if (sym && !(checker.getMergedSymbol(sym.parent).flags & 1536 /* Module */)) { + ts.Debug.fail("Special property assignment kind does not have a module as its parent. Assignment is " + ts.Debug.showSymbol(sym) + ", parent is " + ts.Debug.showSymbol(sym.parent)); + } + return sym && exportInfo(sym, kind); + } + } + function getImport() { + var isImport = isNodeImport(node); + if (!isImport) + return undefined; + // A symbol being imported is always an alias. So get what that aliases to find the local symbol. + var importedSymbol = checker.getImmediateAliasedSymbol(symbol); + if (!importedSymbol) + return undefined; + // Search on the local symbol in the exporting module, not the exported symbol. + importedSymbol = skipExportSpecifierSymbol(importedSymbol, checker); + // Similarly, skip past the symbol for 'export =' + if (importedSymbol.escapedName === "export=") { + importedSymbol = getExportEqualsLocalSymbol(importedSymbol, checker); + } + // If the import has a different name than the export, do not continue searching. + // If `importedName` is undefined, do continue searching as the export is anonymous. + // (All imports returned from this function will be ignored anyway if we are in rename and this is a not a named export.) + var importedName = ts.symbolEscapedNameNoDefault(importedSymbol); + if (importedName === undefined || importedName === "default" /* Default */ || importedName === symbol.escapedName) { + return { kind: 0 /* Import */, symbol: importedSymbol }; + } + } + function exportInfo(symbol, kind) { + var exportInfo = getExportInfo(symbol, kind, checker); + return exportInfo && { kind: 1 /* Export */, symbol: symbol, exportInfo: exportInfo }; + } + // Not meant for use with export specifiers or export assignment. + function getExportKindForDeclaration(node) { + return ts.hasModifier(node, 512 /* Default */) ? 1 /* Default */ : 0 /* Named */; + } + } + FindAllReferences.getImportOrExportSymbol = getImportOrExportSymbol; + function getExportEqualsLocalSymbol(importedSymbol, checker) { + if (importedSymbol.flags & 2097152 /* Alias */) { + return ts.Debug.assertDefined(checker.getImmediateAliasedSymbol(importedSymbol)); + } + var decl = importedSymbol.valueDeclaration; + if (ts.isExportAssignment(decl)) { // `export = class {}` + return ts.Debug.assertDefined(decl.expression.symbol); + } + else if (ts.isBinaryExpression(decl)) { // `module.exports = class {}` + return ts.Debug.assertDefined(decl.right.symbol); + } + else if (ts.isSourceFile(decl)) { // json module + return ts.Debug.assertDefined(decl.symbol); + } + return ts.Debug.fail(); + } + // If a reference is a class expression, the exported node would be its parent. + // If a reference is a variable declaration, the exported node would be the variable statement. + function getExportNode(parent, node) { + if (parent.kind === 237 /* VariableDeclaration */) { + var p = parent; + return p.name !== node ? undefined : + p.parent.kind === 274 /* CatchClause */ ? undefined : p.parent.parent.kind === 219 /* VariableStatement */ ? p.parent.parent : undefined; + } + else { + return parent; + } + } + function isNodeImport(node) { + var parent = node.parent; + switch (parent.kind) { + case 248 /* ImportEqualsDeclaration */: + return parent.name === node && isExternalModuleImportEquals(parent); + case 253 /* ImportSpecifier */: + // For a rename import `{ foo as bar }`, don't search for the imported symbol. Just find local uses of `bar`. + return !parent.propertyName; + case 250 /* ImportClause */: + case 251 /* NamespaceImport */: + ts.Debug.assert(parent.name === node); + return true; + default: + return false; + } + } + function getExportInfo(exportSymbol, exportKind, checker) { + var moduleSymbol = exportSymbol.parent; + if (!moduleSymbol) + return undefined; // This can happen if an `export` is not at the top-level (which is a compile error). + var exportingModuleSymbol = checker.getMergedSymbol(moduleSymbol); // Need to get merged symbol in case there's an augmentation. + // `export` may appear in a namespace. In that case, just rely on global search. + return ts.isExternalModuleSymbol(exportingModuleSymbol) ? { exportingModuleSymbol: exportingModuleSymbol, exportKind: exportKind } : undefined; + } + FindAllReferences.getExportInfo = getExportInfo; + /** If at an export specifier, go to the symbol it refers to. */ + function skipExportSpecifierSymbol(symbol, checker) { + // For `export { foo } from './bar", there's nothing to skip, because it does not create a new alias. But `export { foo } does. + if (symbol.declarations) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (ts.isExportSpecifier(declaration) && !declaration.propertyName && !declaration.parent.parent.moduleSpecifier) { + return checker.getExportSpecifierLocalTargetSymbol(declaration); + } + } + } + return symbol; + } + function getContainingModuleSymbol(importer, checker) { + return checker.getMergedSymbol(getSourceFileLikeForImportDeclaration(importer).symbol); + } + function getSourceFileLikeForImportDeclaration(node) { + if (node.kind === 191 /* CallExpression */) { + return node.getSourceFile(); + } + var parent = node.parent; + if (parent.kind === 279 /* SourceFile */) { + return parent; + } + ts.Debug.assert(parent.kind === 245 /* ModuleBlock */); + return ts.cast(parent.parent, isAmbientModuleDeclaration); + } + function isAmbientModuleDeclaration(node) { + return node.kind === 244 /* ModuleDeclaration */ && node.name.kind === 10 /* StringLiteral */; + } + function isExternalModuleImportEquals(eq) { + return eq.moduleReference.kind === 259 /* ExternalModuleReference */ && eq.moduleReference.expression.kind === 10 /* StringLiteral */; + } + })(FindAllReferences = ts.FindAllReferences || (ts.FindAllReferences = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var FindAllReferences; + (function (FindAllReferences) { + var DefinitionKind; + (function (DefinitionKind) { + DefinitionKind[DefinitionKind["Symbol"] = 0] = "Symbol"; + DefinitionKind[DefinitionKind["Label"] = 1] = "Label"; + DefinitionKind[DefinitionKind["Keyword"] = 2] = "Keyword"; + DefinitionKind[DefinitionKind["This"] = 3] = "This"; + DefinitionKind[DefinitionKind["String"] = 4] = "String"; + })(DefinitionKind = FindAllReferences.DefinitionKind || (FindAllReferences.DefinitionKind = {})); + var EntryKind; + (function (EntryKind) { + EntryKind[EntryKind["Span"] = 0] = "Span"; + EntryKind[EntryKind["Node"] = 1] = "Node"; + EntryKind[EntryKind["StringLiteral"] = 2] = "StringLiteral"; + EntryKind[EntryKind["SearchedLocalFoundProperty"] = 3] = "SearchedLocalFoundProperty"; + EntryKind[EntryKind["SearchedPropertyFoundLocal"] = 4] = "SearchedPropertyFoundLocal"; + })(EntryKind = FindAllReferences.EntryKind || (FindAllReferences.EntryKind = {})); + function nodeEntry(node, kind) { + if (kind === void 0) { kind = 1 /* Node */; } + return { kind: kind, node: node.name || node }; + } + FindAllReferences.nodeEntry = nodeEntry; + function findReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position) { + var node = ts.getTouchingPropertyName(sourceFile, position); + var referencedSymbols = FindAllReferences.Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken); + var checker = program.getTypeChecker(); + return !referencedSymbols || !referencedSymbols.length ? undefined : ts.mapDefined(referencedSymbols, function (_a) { + var definition = _a.definition, references = _a.references; + // Only include referenced symbols that have a valid definition. + return definition && { + definition: checker.runWithCancellationToken(cancellationToken, function (checker) { return definitionToReferencedSymbolDefinitionInfo(definition, checker, node); }), + references: references.map(toReferenceEntry) + }; + }); + } + FindAllReferences.findReferencedSymbols = findReferencedSymbols; + function getImplementationsAtPosition(program, cancellationToken, sourceFiles, sourceFile, position) { + var node = ts.getTouchingPropertyName(sourceFile, position); + var referenceEntries = getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node, position); + var checker = program.getTypeChecker(); + return ts.map(referenceEntries, function (entry) { return toImplementationLocation(entry, checker); }); + } + FindAllReferences.getImplementationsAtPosition = getImplementationsAtPosition; + function getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node, position) { + if (node.kind === 279 /* SourceFile */) { + return undefined; + } + var checker = program.getTypeChecker(); + // If invoked directly on a shorthand property assignment, then return + // the declaration of the symbol being assigned (not the symbol being assigned to). + if (node.parent.kind === 276 /* ShorthandPropertyAssignment */) { + var result_7 = []; + FindAllReferences.Core.getReferenceEntriesForShorthandPropertyAssignment(node, checker, function (node) { return result_7.push(nodeEntry(node)); }); + return result_7; + } + else if (node.kind === 98 /* SuperKeyword */ || ts.isSuperProperty(node.parent)) { + // References to and accesses on the super keyword only have one possible implementation, so no + // need to "Find all References" + var symbol = checker.getSymbolAtLocation(node); + return symbol.valueDeclaration && [nodeEntry(symbol.valueDeclaration)]; + } + else { + // Perform "Find all References" and retrieve only those that are implementations + return getReferenceEntriesForNode(position, node, program, sourceFiles, cancellationToken, { implementations: true }); + } + } + function findReferenceOrRenameEntries(program, cancellationToken, sourceFiles, node, position, options, convertEntry) { + return ts.map(flattenEntries(FindAllReferences.Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options)), function (entry) { return convertEntry(entry, node, program.getTypeChecker()); }); + } + FindAllReferences.findReferenceOrRenameEntries = findReferenceOrRenameEntries; + function getReferenceEntriesForNode(position, node, program, sourceFiles, cancellationToken, options, sourceFilesSet) { + if (options === void 0) { options = {}; } + if (sourceFilesSet === void 0) { sourceFilesSet = ts.arrayToSet(sourceFiles, function (f) { return f.fileName; }); } + return flattenEntries(FindAllReferences.Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options, sourceFilesSet)); + } + FindAllReferences.getReferenceEntriesForNode = getReferenceEntriesForNode; + function flattenEntries(referenceSymbols) { + return referenceSymbols && ts.flatMap(referenceSymbols, function (r) { return r.references; }); + } + function definitionToReferencedSymbolDefinitionInfo(def, checker, originalNode) { + var info = (function () { + switch (def.type) { + case 0 /* Symbol */: { + var symbol = def.symbol; + var _a = getDefinitionKindAndDisplayParts(symbol, checker, originalNode), displayParts_1 = _a.displayParts, kind_1 = _a.kind; + var name_3 = displayParts_1.map(function (p) { return p.text; }).join(""); + return { node: symbol.declarations ? ts.getNameOfDeclaration(ts.first(symbol.declarations)) || ts.first(symbol.declarations) : originalNode, name: name_3, kind: kind_1, displayParts: displayParts_1 }; + } + case 1 /* Label */: { + var node_3 = def.node; + return { node: node_3, name: node_3.text, kind: "label" /* label */, displayParts: [ts.displayPart(node_3.text, ts.SymbolDisplayPartKind.text)] }; + } + case 2 /* Keyword */: { + var node_4 = def.node; + var name_4 = ts.tokenToString(node_4.kind); + return { node: node_4, name: name_4, kind: "keyword" /* keyword */, displayParts: [{ text: name_4, kind: "keyword" /* keyword */ }] }; + } + case 3 /* This */: { + var node_5 = def.node; + var symbol = checker.getSymbolAtLocation(node_5); + var displayParts_2 = symbol && ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, node_5.getSourceFile(), ts.getContainerNode(node_5), node_5).displayParts || [ts.textPart("this")]; + return { node: node_5, name: "this", kind: "var" /* variableElement */, displayParts: displayParts_2 }; + } + case 4 /* String */: { + var node_6 = def.node; + return { node: node_6, name: node_6.text, kind: "var" /* variableElement */, displayParts: [ts.displayPart(ts.getTextOfNode(node_6), ts.SymbolDisplayPartKind.stringLiteral)] }; + } + default: + return ts.Debug.assertNever(def); + } + })(); + var node = info.node, name = info.name, kind = info.kind, displayParts = info.displayParts; + var sourceFile = node.getSourceFile(); + return { containerKind: "" /* unknown */, containerName: "", fileName: sourceFile.fileName, kind: kind, name: name, textSpan: getTextSpan(ts.isComputedPropertyName(node) ? node.expression : node, sourceFile), displayParts: displayParts }; + } + function getDefinitionKindAndDisplayParts(symbol, checker, node) { + var meaning = FindAllReferences.Core.getIntersectingMeaningFromDeclarations(node, symbol); + var enclosingDeclaration = symbol.declarations && ts.firstOrUndefined(symbol.declarations) || node; + var _a = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, enclosingDeclaration.getSourceFile(), enclosingDeclaration, enclosingDeclaration, meaning), displayParts = _a.displayParts, symbolKind = _a.symbolKind; + return { displayParts: displayParts, kind: symbolKind }; + } + function toRenameLocation(entry, originalNode, checker) { + return __assign({}, entryToDocumentSpan(entry), getPrefixAndSuffixText(entry, originalNode, checker)); + } + FindAllReferences.toRenameLocation = toRenameLocation; + function toReferenceEntry(entry) { + var _a = entryToDocumentSpan(entry), textSpan = _a.textSpan, fileName = _a.fileName; + if (entry.kind === 0 /* Span */) { + return { textSpan: textSpan, fileName: fileName, isWriteAccess: false, isDefinition: false }; + } + var kind = entry.kind, node = entry.node; + return { + textSpan: textSpan, + fileName: fileName, + isWriteAccess: isWriteAccessForReference(node), + isDefinition: node.kind === 80 /* DefaultKeyword */ + || !!ts.getDeclarationFromName(node) + || ts.isLiteralComputedPropertyDeclarationName(node), + isInString: kind === 2 /* StringLiteral */ ? true : undefined, + }; + } + FindAllReferences.toReferenceEntry = toReferenceEntry; + function entryToDocumentSpan(entry) { + if (entry.kind === 0 /* Span */) { + return { textSpan: entry.textSpan, fileName: entry.fileName }; + } + else { + var sourceFile = entry.node.getSourceFile(); + return { textSpan: getTextSpan(entry.node, sourceFile), fileName: sourceFile.fileName }; + } + } + function getPrefixAndSuffixText(entry, originalNode, checker) { + if (entry.kind !== 0 /* Span */ && ts.isIdentifier(originalNode)) { + var node = entry.node, kind = entry.kind; + var name = originalNode.text; + var isShorthandAssignment = ts.isShorthandPropertyAssignment(node.parent); + if (isShorthandAssignment || ts.isObjectBindingElementWithoutPropertyName(node.parent)) { + var prefixColon = { prefixText: name + ": " }; + var suffixColon = { suffixText: ": " + name }; + return kind === 3 /* SearchedLocalFoundProperty */ ? prefixColon + : kind === 4 /* SearchedPropertyFoundLocal */ ? suffixColon + // In `const o = { x }; o.x`, symbolAtLocation at `x` in `{ x }` is the property symbol. + // For a binding element `const { x } = o;`, symbolAtLocation at `x` is the property symbol. + : isShorthandAssignment ? suffixColon : prefixColon; + } + else if (ts.isImportSpecifier(entry.node.parent) && !entry.node.parent.propertyName) { + // If the original symbol was using this alias, just rename the alias. + var originalSymbol = ts.isExportSpecifier(originalNode.parent) ? checker.getExportSpecifierLocalTargetSymbol(originalNode.parent) : checker.getSymbolAtLocation(originalNode); + return ts.contains(originalSymbol.declarations, entry.node.parent) ? { prefixText: name + " as " } : ts.emptyOptions; + } + else if (ts.isExportSpecifier(entry.node.parent) && !entry.node.parent.propertyName) { + return originalNode === entry.node ? { prefixText: name + " as " } : { suffixText: " as " + name }; + } + } + return ts.emptyOptions; + } + function toImplementationLocation(entry, checker) { + if (entry.kind !== 0 /* Span */) { + var node = entry.node; + var sourceFile = node.getSourceFile(); + return __assign({ textSpan: getTextSpan(node, sourceFile), fileName: sourceFile.fileName }, implementationKindDisplayParts(node, checker)); + } + else { + var textSpan = entry.textSpan, fileName = entry.fileName; + return { textSpan: textSpan, fileName: fileName, kind: "" /* unknown */, displayParts: [] }; + } + } + function implementationKindDisplayParts(node, checker) { + var symbol = checker.getSymbolAtLocation(ts.isDeclaration(node) && node.name ? node.name : node); + if (symbol) { + return getDefinitionKindAndDisplayParts(symbol, checker, node); + } + else if (node.kind === 188 /* ObjectLiteralExpression */) { + return { + kind: "interface" /* interfaceElement */, + displayParts: [ts.punctuationPart(20 /* OpenParenToken */), ts.textPart("object literal"), ts.punctuationPart(21 /* CloseParenToken */)] + }; + } + else if (node.kind === 209 /* ClassExpression */) { + return { + kind: "local class" /* localClassElement */, + displayParts: [ts.punctuationPart(20 /* OpenParenToken */), ts.textPart("anonymous local class"), ts.punctuationPart(21 /* CloseParenToken */)] + }; + } + else { + return { kind: ts.getNodeKind(node), displayParts: [] }; + } + } + function toHighlightSpan(entry) { + if (entry.kind === 0 /* Span */) { + var fileName = entry.fileName, textSpan = entry.textSpan; + return { fileName: fileName, span: { textSpan: textSpan, kind: "reference" /* reference */ } }; + } + var node = entry.node, kind = entry.kind; + var sourceFile = node.getSourceFile(); + var writeAccess = isWriteAccessForReference(node); + var span = { + textSpan: getTextSpan(node, sourceFile), + kind: writeAccess ? "writtenReference" /* writtenReference */ : "reference" /* reference */, + isInString: kind === 2 /* StringLiteral */ ? true : undefined, + }; + return { fileName: sourceFile.fileName, span: span }; + } + FindAllReferences.toHighlightSpan = toHighlightSpan; + function getTextSpan(node, sourceFile) { + var start = node.getStart(sourceFile); + var end = node.getEnd(); + if (node.kind === 10 /* StringLiteral */) { + start += 1; + end -= 1; + } + return ts.createTextSpanFromBounds(start, end); + } + /** A node is considered a writeAccess iff it is a name of a declaration or a target of an assignment */ + function isWriteAccessForReference(node) { + var decl = ts.getDeclarationFromName(node); + return !!decl && declarationIsWriteAccess(decl) || node.kind === 80 /* DefaultKeyword */ || ts.isWriteAccess(node); + } + /** + * True if 'decl' provides a value, as in `function f() {}`; + * false if 'decl' is just a location for a future write, as in 'let x;' + */ + function declarationIsWriteAccess(decl) { + // Consider anything in an ambient declaration to be a write access since it may be coming from JS. + if (!!(decl.flags & 4194304 /* Ambient */)) + return true; + switch (decl.kind) { + case 204 /* BinaryExpression */: + case 186 /* BindingElement */: + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 80 /* DefaultKeyword */: + case 243 /* EnumDeclaration */: + case 278 /* EnumMember */: + case 257 /* ExportSpecifier */: + case 250 /* ImportClause */: // default import + case 248 /* ImportEqualsDeclaration */: + case 253 /* ImportSpecifier */: + case 241 /* InterfaceDeclaration */: + case 297 /* JSDocCallbackTag */: + case 304 /* JSDocTypedefTag */: + case 267 /* JsxAttribute */: + case 244 /* ModuleDeclaration */: + case 247 /* NamespaceExportDeclaration */: + case 251 /* NamespaceImport */: + case 151 /* Parameter */: + case 276 /* ShorthandPropertyAssignment */: + case 242 /* TypeAliasDeclaration */: + case 150 /* TypeParameter */: + return true; + case 275 /* PropertyAssignment */: + // In `({ x: y } = 0);`, `x` is not a write access. (Won't call this function for `y`.) + return !ts.isArrayLiteralOrObjectLiteralDestructuringPattern(decl.parent); + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 157 /* Constructor */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + return !!decl.body; + case 237 /* VariableDeclaration */: + case 154 /* PropertyDeclaration */: + return !!decl.initializer || ts.isCatchClause(decl.parent); + case 155 /* MethodSignature */: + case 153 /* PropertySignature */: + case 305 /* JSDocPropertyTag */: + case 299 /* JSDocParameterTag */: + return false; + default: + return ts.Debug.failBadSyntaxKind(decl); + } + } + })(FindAllReferences = ts.FindAllReferences || (ts.FindAllReferences = {})); +})(ts || (ts = {})); +/** Encapsulates the core find-all-references algorithm. */ +/* @internal */ +(function (ts) { + var FindAllReferences; + (function (FindAllReferences) { + var Core; + (function (Core) { + /** Core find-all-references algorithm. Handles special cases before delegating to `getReferencedSymbolsForSymbol`. */ + function getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options, sourceFilesSet) { + if (options === void 0) { options = {}; } + if (sourceFilesSet === void 0) { sourceFilesSet = ts.arrayToSet(sourceFiles, function (f) { return f.fileName; }); } + if (ts.isSourceFile(node)) { + var reference = ts.GoToDefinition.getReferenceAtPosition(node, position, program); + var moduleSymbol = reference && program.getTypeChecker().getMergedSymbol(reference.file.symbol); + return moduleSymbol && getReferencedSymbolsForModule(program, moduleSymbol, /*excludeImportTypeOfExportEquals*/ false, sourceFiles, sourceFilesSet); + } + if (!options.implementations) { + var special = getReferencedSymbolsSpecial(node, sourceFiles, cancellationToken); + if (special) { + return special; + } + } + var checker = program.getTypeChecker(); + var symbol = checker.getSymbolAtLocation(node); + // Could not find a symbol e.g. unknown identifier + if (!symbol) { + // String literal might be a property (and thus have a symbol), so do this here rather than in getReferencedSymbolsSpecial. + return !options.implementations && ts.isStringLiteral(node) ? getReferencesForStringLiteral(node, sourceFiles, cancellationToken) : undefined; + } + if (symbol.escapedName === "export=" /* ExportEquals */) { + return getReferencedSymbolsForModule(program, symbol.parent, /*excludeImportTypeOfExportEquals*/ false, sourceFiles, sourceFilesSet); + } + var moduleReferences = ts.emptyArray; + var moduleSourceFile = isModuleSymbol(symbol); + var referencedNode = node; + if (moduleSourceFile) { + var exportEquals = symbol.exports.get("export=" /* ExportEquals */); + // If !!exportEquals, we're about to add references to `import("mod")` anyway, so don't double-count them. + moduleReferences = getReferencedSymbolsForModule(program, symbol, !!exportEquals, sourceFiles, sourceFilesSet); + if (!exportEquals || !sourceFilesSet.has(moduleSourceFile.fileName)) + return moduleReferences; + // Continue to get references to 'export ='. + symbol = ts.skipAlias(exportEquals, checker); + referencedNode = undefined; + } + return ts.concatenate(moduleReferences, getReferencedSymbolsForSymbol(symbol, referencedNode, sourceFiles, sourceFilesSet, checker, cancellationToken, options)); + } + Core.getReferencedSymbolsForNode = getReferencedSymbolsForNode; + function isModuleSymbol(symbol) { + return symbol.flags & 1536 /* Module */ ? ts.find(symbol.declarations, ts.isSourceFile) : undefined; + } + function getReferencedSymbolsForModule(program, symbol, excludeImportTypeOfExportEquals, sourceFiles, sourceFilesSet) { + ts.Debug.assert(!!symbol.valueDeclaration); + var references = ts.mapDefined(FindAllReferences.findModuleReferences(program, sourceFiles, symbol), function (reference) { + if (reference.kind === "import") { + var parent = reference.literal.parent; + if (ts.isLiteralTypeNode(parent)) { + var importType = ts.cast(parent.parent, ts.isImportTypeNode); + if (excludeImportTypeOfExportEquals && !importType.qualifier) { + return undefined; + } + } + // import("foo") with no qualifier will reference the `export =` of the module, which may be referenced anyway. + return FindAllReferences.nodeEntry(reference.literal); + } + else { + return { + kind: 0 /* Span */, + fileName: reference.referencingFile.fileName, + textSpan: ts.createTextSpanFromRange(reference.ref), + }; + } + }); + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + switch (decl.kind) { + case 279 /* SourceFile */: + // Don't include the source file itself. (This may not be ideal behavior, but awkward to include an entire file as a reference.) + break; + case 244 /* ModuleDeclaration */: + if (sourceFilesSet.has(decl.getSourceFile().fileName)) { + references.push(FindAllReferences.nodeEntry(decl.name)); + } + break; + default: + // This may be merged with something. + ts.Debug.fail("Expected a module symbol to be declared by a SourceFile or ModuleDeclaration."); + } + } + var exported = symbol.exports.get("export=" /* ExportEquals */); + if (exported) { + for (var _b = 0, _c = exported.declarations; _b < _c.length; _b++) { + var decl = _c[_b]; + var sourceFile = decl.getSourceFile(); + if (sourceFilesSet.has(sourceFile.fileName)) { + // At `module.exports = ...`, reference node is `module` + var node = ts.isBinaryExpression(decl) && ts.isPropertyAccessExpression(decl.left) + ? decl.left.expression + : ts.isExportAssignment(decl) + ? ts.Debug.assertDefined(ts.findChildOfKind(decl, 85 /* ExportKeyword */, sourceFile)) + : ts.getNameOfDeclaration(decl) || decl; + references.push(FindAllReferences.nodeEntry(node)); + } + } + } + return references.length ? [{ definition: { type: 0 /* Symbol */, symbol: symbol }, references: references }] : ts.emptyArray; + } + /** getReferencedSymbols for special node kinds. */ + function getReferencedSymbolsSpecial(node, sourceFiles, cancellationToken) { + if (ts.isTypeKeyword(node.kind)) { + return getAllReferencesForKeyword(sourceFiles, node.kind, cancellationToken); + } + // Labels + if (ts.isJumpStatementTarget(node)) { + var labelDefinition = ts.getTargetLabel(node.parent, node.text); + // if we have a label definition, look within its statement for references, if not, then + // the label is undefined and we have no results.. + return labelDefinition && getLabelReferencesInNode(labelDefinition.parent, labelDefinition); + } + else if (ts.isLabelOfLabeledStatement(node)) { + // it is a label definition and not a target, search within the parent labeledStatement + return getLabelReferencesInNode(node.parent, node); + } + if (ts.isThis(node)) { + return getReferencesForThisKeyword(node, sourceFiles, cancellationToken); + } + if (node.kind === 98 /* SuperKeyword */) { + return getReferencesForSuperKeyword(node); + } + return undefined; + } + /** Core find-all-references algorithm for a normal symbol. */ + function getReferencedSymbolsForSymbol(originalSymbol, node, sourceFiles, sourceFilesSet, checker, cancellationToken, options) { + var symbol = node && skipPastExportOrImportSpecifierOrUnion(originalSymbol, node, checker, !!options.isForRename) || originalSymbol; + // Compute the meaning from the location and the symbol it references + var searchMeaning = node ? getIntersectingMeaningFromDeclarations(node, symbol) : 7 /* All */; + var result = []; + var state = new State(sourceFiles, sourceFilesSet, node ? getSpecialSearchKind(node) : 0 /* None */, checker, cancellationToken, searchMeaning, options, result); + var exportSpecifier = !options.isForRename ? undefined : ts.find(symbol.declarations, ts.isExportSpecifier); + if (exportSpecifier) { + // When renaming at an export specifier, rename the export and not the thing being exported. + getReferencesAtExportSpecifier(exportSpecifier.name, symbol, exportSpecifier, state.createSearch(node, originalSymbol, /*comingFrom*/ undefined), state, /*addReferencesHere*/ true, /*alwaysGetReferences*/ true); + } + else if (node && node.kind === 80 /* DefaultKeyword */) { + addReference(node, symbol, state); + searchForImportsOfExport(node, symbol, { exportingModuleSymbol: ts.Debug.assertDefined(symbol.parent, "Expected export symbol to have a parent"), exportKind: 1 /* Default */ }, state); + } + else { + var search = state.createSearch(node, symbol, /*comingFrom*/ undefined, { allSearchSymbols: node ? populateSearchSymbolSet(symbol, node, checker, !!options.isForRename, !!options.implementations) : [symbol] }); + // Try to get the smallest valid scope that we can limit our search to; + // otherwise we'll need to search globally (i.e. include each file). + var scope = getSymbolScope(symbol); + if (scope) { + getReferencesInContainer(scope, scope.getSourceFile(), search, state, /*addReferencesHere*/ !(ts.isSourceFile(scope) && !ts.contains(sourceFiles, scope))); + } + else { + // Global search + for (var _i = 0, _a = state.sourceFiles; _i < _a.length; _i++) { + var sourceFile = _a[_i]; + state.cancellationToken.throwIfCancellationRequested(); + searchForName(sourceFile, search, state); + } + } + } + return result; + } + function getSpecialSearchKind(node) { + switch (node.kind) { + case 124 /* ConstructorKeyword */: + return 1 /* Constructor */; + case 72 /* Identifier */: + if (ts.isClassLike(node.parent)) { + ts.Debug.assert(node.parent.name === node); + return 2 /* Class */; + } + // falls through + default: + return 0 /* None */; + } + } + /** Handle a few special cases relating to export/import specifiers. */ + function skipPastExportOrImportSpecifierOrUnion(symbol, node, checker, isForRename) { + var parent = node.parent; + if (ts.isExportSpecifier(parent) && !isForRename) { + return getLocalSymbolForExportSpecifier(node, symbol, parent, checker); + } + // If the symbol is declared as part of a declaration like `{ type: "a" } | { type: "b" }`, use the property on the union type to get more references. + return ts.firstDefined(symbol.declarations, function (decl) { + if (!decl.parent) { + // Assertions for GH#21814. We should be handling SourceFile symbols in `getReferencedSymbolsForModule` instead of getting here. + ts.Debug.fail("Unexpected symbol at " + ts.Debug.showSyntaxKind(node) + ": " + ts.Debug.showSymbol(symbol)); + } + return ts.isTypeLiteralNode(decl.parent) && ts.isUnionTypeNode(decl.parent.parent) + ? checker.getPropertyOfType(checker.getTypeFromTypeNode(decl.parent.parent), symbol.name) + : undefined; + }); + } + var SpecialSearchKind; + (function (SpecialSearchKind) { + SpecialSearchKind[SpecialSearchKind["None"] = 0] = "None"; + SpecialSearchKind[SpecialSearchKind["Constructor"] = 1] = "Constructor"; + SpecialSearchKind[SpecialSearchKind["Class"] = 2] = "Class"; + })(SpecialSearchKind || (SpecialSearchKind = {})); + /** + * Holds all state needed for the finding references. + * Unlike `Search`, there is only one `State`. + */ + var State = /** @class */ (function () { + function State(sourceFiles, sourceFilesSet, + /** True if we're searching for constructor references. */ + specialSearchKind, checker, cancellationToken, searchMeaning, options, result) { + this.sourceFiles = sourceFiles; + this.sourceFilesSet = sourceFilesSet; + this.specialSearchKind = specialSearchKind; + this.checker = checker; + this.cancellationToken = cancellationToken; + this.searchMeaning = searchMeaning; + this.options = options; + this.result = result; + /** Cache for `explicitlyinheritsFrom`. */ + this.inheritsFromCache = ts.createMap(); + /** + * Type nodes can contain multiple references to the same type. For example: + * let x: Foo & (Foo & Bar) = ... + * Because we are returning the implementation locations and not the identifier locations, + * duplicate entries would be returned here as each of the type references is part of + * the same implementation. For that reason, check before we add a new entry. + */ + this.markSeenContainingTypeReference = ts.nodeSeenTracker(); + /** + * It's possible that we will encounter the right side of `export { foo as bar } from "x";` more than once. + * For example: + * // b.ts + * export { foo as bar } from "./a"; + * import { bar } from "./b"; + * + * Normally at `foo as bar` we directly add `foo` and do not locally search for it (since it doesn't declare a local). + * But another reference to it may appear in the same source file. + * See `tests/cases/fourslash/transitiveExportImports3.ts`. + */ + this.markSeenReExportRHS = ts.nodeSeenTracker(); + this.symbolIdToReferences = []; + // Source file ID → symbol ID → Whether the symbol has been searched for in the source file. + this.sourceFileToSeenSymbols = []; + } + State.prototype.includesSourceFile = function (sourceFile) { + return this.sourceFilesSet.has(sourceFile.fileName); + }; + /** Gets every place to look for references of an exported symbols. See `ImportsResult` in `importTracker.ts` for more documentation. */ + State.prototype.getImportSearches = function (exportSymbol, exportInfo) { + if (!this.importTracker) + this.importTracker = FindAllReferences.createImportTracker(this.sourceFiles, this.sourceFilesSet, this.checker, this.cancellationToken); + return this.importTracker(exportSymbol, exportInfo, !!this.options.isForRename); + }; + /** @param allSearchSymbols set of additional symbols for use by `includes`. */ + State.prototype.createSearch = function (location, symbol, comingFrom, searchOptions) { + if (searchOptions === void 0) { searchOptions = {}; } + // Note: if this is an external module symbol, the name doesn't include quotes. + // Note: getLocalSymbolForExportDefault handles `export default class C {}`, but not `export default C` or `export { C as default }`. + // The other two forms seem to be handled downstream (e.g. in `skipPastExportOrImportSpecifier`), so special-casing the first form + // here appears to be intentional). + var _a = searchOptions.text, text = _a === void 0 ? ts.stripQuotes(ts.unescapeLeadingUnderscores((ts.getLocalSymbolForExportDefault(symbol) || symbol).escapedName)) : _a, _b = searchOptions.allSearchSymbols, allSearchSymbols = _b === void 0 ? [symbol] : _b; + var escapedText = ts.escapeLeadingUnderscores(text); + var parents = this.options.implementations && location ? getParentSymbolsOfPropertyAccess(location, symbol, this.checker) : undefined; + return { symbol: symbol, comingFrom: comingFrom, text: text, escapedText: escapedText, parents: parents, allSearchSymbols: allSearchSymbols, includes: function (sym) { return ts.contains(allSearchSymbols, sym); } }; + }; + /** + * Callback to add references for a particular searched symbol. + * This initializes a reference group, so only call this if you will add at least one reference. + */ + State.prototype.referenceAdder = function (searchSymbol) { + var symbolId = ts.getSymbolId(searchSymbol); + var references = this.symbolIdToReferences[symbolId]; + if (!references) { + references = this.symbolIdToReferences[symbolId] = []; + this.result.push({ definition: { type: 0 /* Symbol */, symbol: searchSymbol }, references: references }); + } + return function (node, kind) { return references.push(FindAllReferences.nodeEntry(node, kind)); }; + }; + /** Add a reference with no associated definition. */ + State.prototype.addStringOrCommentReference = function (fileName, textSpan) { + this.result.push({ + definition: undefined, + references: [{ kind: 0 /* Span */, fileName: fileName, textSpan: textSpan }] + }); + }; + /** Returns `true` the first time we search for a symbol in a file and `false` afterwards. */ + State.prototype.markSearchedSymbols = function (sourceFile, symbols) { + var sourceId = ts.getNodeId(sourceFile); + var seenSymbols = this.sourceFileToSeenSymbols[sourceId] || (this.sourceFileToSeenSymbols[sourceId] = ts.createMap()); + var anyNewSymbols = false; + for (var _i = 0, symbols_4 = symbols; _i < symbols_4.length; _i++) { + var sym = symbols_4[_i]; + anyNewSymbols = ts.addToSeen(seenSymbols, ts.getSymbolId(sym)) || anyNewSymbols; + } + return anyNewSymbols; + }; + return State; + }()); + /** Search for all imports of a given exported symbol using `State.getImportSearches`. */ + function searchForImportsOfExport(exportLocation, exportSymbol, exportInfo, state) { + var _a = state.getImportSearches(exportSymbol, exportInfo), importSearches = _a.importSearches, singleReferences = _a.singleReferences, indirectUsers = _a.indirectUsers; + // For `import { foo as bar }` just add the reference to `foo`, and don't otherwise search in the file. + if (singleReferences.length) { + var addRef = state.referenceAdder(exportSymbol); + for (var _i = 0, singleReferences_1 = singleReferences; _i < singleReferences_1.length; _i++) { + var singleRef = singleReferences_1[_i]; + if (shouldAddSingleReference(singleRef, state)) + addRef(singleRef); + } + } + // For each import, find all references to that import in its source file. + for (var _b = 0, importSearches_1 = importSearches; _b < importSearches_1.length; _b++) { + var _c = importSearches_1[_b], importLocation = _c[0], importSymbol = _c[1]; + getReferencesInSourceFile(importLocation.getSourceFile(), state.createSearch(importLocation, importSymbol, 1 /* Export */), state); + } + if (indirectUsers.length) { + var indirectSearch = void 0; + switch (exportInfo.exportKind) { + case 0 /* Named */: + indirectSearch = state.createSearch(exportLocation, exportSymbol, 1 /* Export */); + break; + case 1 /* Default */: + // Search for a property access to '.default'. This can't be renamed. + indirectSearch = state.options.isForRename ? undefined : state.createSearch(exportLocation, exportSymbol, 1 /* Export */, { text: "default" }); + break; + case 2 /* ExportEquals */: + break; + } + if (indirectSearch) { + for (var _d = 0, indirectUsers_1 = indirectUsers; _d < indirectUsers_1.length; _d++) { + var indirectUser = indirectUsers_1[_d]; + searchForName(indirectUser, indirectSearch, state); + } + } + } + } + function eachExportReference(sourceFiles, checker, cancellationToken, exportSymbol, exportingModuleSymbol, exportName, isDefaultExport, cb) { + var importTracker = FindAllReferences.createImportTracker(sourceFiles, ts.arrayToSet(sourceFiles, function (f) { return f.fileName; }), checker, cancellationToken); + var _a = importTracker(exportSymbol, { exportKind: isDefaultExport ? 1 /* Default */ : 0 /* Named */, exportingModuleSymbol: exportingModuleSymbol }, /*isForRename*/ false), importSearches = _a.importSearches, indirectUsers = _a.indirectUsers; + for (var _i = 0, importSearches_2 = importSearches; _i < importSearches_2.length; _i++) { + var importLocation = importSearches_2[_i][0]; + cb(importLocation); + } + for (var _b = 0, indirectUsers_2 = indirectUsers; _b < indirectUsers_2.length; _b++) { + var indirectUser = indirectUsers_2[_b]; + for (var _c = 0, _d = getPossibleSymbolReferenceNodes(indirectUser, isDefaultExport ? "default" : exportName); _c < _d.length; _c++) { + var node = _d[_c]; + // Import specifiers should be handled by importSearches + if (ts.isIdentifier(node) && !ts.isImportOrExportSpecifier(node.parent) && checker.getSymbolAtLocation(node) === exportSymbol) { + cb(node); + } + } + } + } + Core.eachExportReference = eachExportReference; + function shouldAddSingleReference(singleRef, state) { + if (!hasMatchingMeaning(singleRef, state)) + return false; + if (!state.options.isForRename) + return true; + // Don't rename an import type `import("./module-name")` when renaming `name` in `export = name;` + if (!ts.isIdentifier(singleRef)) + return false; + // At `default` in `import { default as x }` or `export { default as x }`, do add a reference, but do not rename. + return !(ts.isImportOrExportSpecifier(singleRef.parent) && singleRef.escapedText === "default" /* Default */); + } + // Go to the symbol we imported from and find references for it. + function searchForImportedSymbol(symbol, state) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + var exportingFile = declaration.getSourceFile(); + // Need to search in the file even if it's not in the search-file set, because it might export the symbol. + getReferencesInSourceFile(exportingFile, state.createSearch(declaration, symbol, 0 /* Import */), state, state.includesSourceFile(exportingFile)); + } + } + /** Search for all occurences of an identifier in a source file (and filter out the ones that match). */ + function searchForName(sourceFile, search, state) { + if (ts.getNameTable(sourceFile).get(search.escapedText) !== undefined) { + getReferencesInSourceFile(sourceFile, search, state); + } + } + function getPropertySymbolOfDestructuringAssignment(location, checker) { + return ts.isArrayLiteralOrObjectLiteralDestructuringPattern(location.parent.parent) + ? checker.getPropertySymbolOfDestructuringAssignment(location) + : undefined; + } + /** + * Determines the smallest scope in which a symbol may have named references. + * Note that not every construct has been accounted for. This function can + * probably be improved. + * + * @returns undefined if the scope cannot be determined, implying that + * a reference to a symbol can occur anywhere. + */ + function getSymbolScope(symbol) { + // If this is the symbol of a named function expression or named class expression, + // then named references are limited to its own scope. + var declarations = symbol.declarations, flags = symbol.flags, parent = symbol.parent, valueDeclaration = symbol.valueDeclaration; + if (valueDeclaration && (valueDeclaration.kind === 196 /* FunctionExpression */ || valueDeclaration.kind === 209 /* ClassExpression */)) { + return valueDeclaration; + } + if (!declarations) { + return undefined; + } + // If this is private property or method, the scope is the containing class + if (flags & (4 /* Property */ | 8192 /* Method */)) { + var privateDeclaration = ts.find(declarations, function (d) { return ts.hasModifier(d, 8 /* Private */); }); + if (privateDeclaration) { + return ts.getAncestor(privateDeclaration, 240 /* ClassDeclaration */); + } + // Else this is a public property and could be accessed from anywhere. + return undefined; + } + // If symbol is of object binding pattern element without property name we would want to + // look for property too and that could be anywhere + if (declarations.some(ts.isObjectBindingElementWithoutPropertyName)) { + return undefined; + } + /* + If the symbol has a parent, it's globally visible unless: + - It's a private property (handled above). + - It's a type parameter. + - The parent is an external module: then we should only search in the module (and recurse on the export later). + - But if the parent has `export as namespace`, the symbol is globally visible through that namespace. + */ + var exposedByParent = parent && !(symbol.flags & 262144 /* TypeParameter */); + if (exposedByParent && !(ts.isExternalModuleSymbol(parent) && !parent.globalExports)) { + return undefined; + } + var scope; + for (var _i = 0, declarations_11 = declarations; _i < declarations_11.length; _i++) { + var declaration = declarations_11[_i]; + var container = ts.getContainerNode(declaration); + if (scope && scope !== container) { + // Different declarations have different containers, bail out + return undefined; + } + if (!container || container.kind === 279 /* SourceFile */ && !ts.isExternalOrCommonJsModule(container)) { + // This is a global variable and not an external module, any declaration defined + // within this scope is visible outside the file + return undefined; + } + // The search scope is the container node + scope = container; + } + // If symbol.parent, this means we are in an export of an external module. (Otherwise we would have returned `undefined` above.) + // For an export of a module, we may be in a declaration file, and it may be accessed elsewhere. E.g.: + // declare module "a" { export type T = number; } + // declare module "b" { import { T } from "a"; export const x: T; } + // So we must search the whole source file. (Because we will mark the source file as seen, we we won't return to it when searching for imports.) + return exposedByParent ? scope.getSourceFile() : scope; // TODO: GH#18217 + } + /** Used as a quick check for whether a symbol is used at all in a file (besides its definition). */ + function isSymbolReferencedInFile(definition, checker, sourceFile) { + return eachSymbolReferenceInFile(definition, checker, sourceFile, function () { return true; }) || false; + } + Core.isSymbolReferencedInFile = isSymbolReferencedInFile; + function eachSymbolReferenceInFile(definition, checker, sourceFile, cb) { + var symbol = ts.isParameterPropertyDeclaration(definition.parent) + ? ts.first(checker.getSymbolsOfParameterPropertyDeclaration(definition.parent, definition.text)) + : checker.getSymbolAtLocation(definition); + if (!symbol) + return undefined; + for (var _i = 0, _a = getPossibleSymbolReferenceNodes(sourceFile, symbol.name); _i < _a.length; _i++) { + var token = _a[_i]; + if (!ts.isIdentifier(token) || token === definition || token.escapedText !== definition.escapedText) + continue; + var referenceSymbol = checker.getSymbolAtLocation(token); // See GH#19955 for why the type annotation is necessary + if (referenceSymbol === symbol + || checker.getShorthandAssignmentValueSymbol(token.parent) === symbol + || ts.isExportSpecifier(token.parent) && getLocalSymbolForExportSpecifier(token, referenceSymbol, token.parent, checker) === symbol) { + var res = cb(token); + if (res) + return res; + } + } + } + Core.eachSymbolReferenceInFile = eachSymbolReferenceInFile; + function eachSignatureCall(signature, sourceFiles, checker, cb) { + if (!signature.name || !ts.isIdentifier(signature.name)) + return; + var symbol = ts.Debug.assertDefined(checker.getSymbolAtLocation(signature.name)); + for (var _i = 0, sourceFiles_5 = sourceFiles; _i < sourceFiles_5.length; _i++) { + var sourceFile = sourceFiles_5[_i]; + for (var _a = 0, _b = getPossibleSymbolReferenceNodes(sourceFile, symbol.name); _a < _b.length; _a++) { + var name = _b[_a]; + if (!ts.isIdentifier(name) || name === signature.name || name.escapedText !== signature.name.escapedText) + continue; + var called = ts.climbPastPropertyAccess(name); + var call = called.parent; + if (!ts.isCallExpression(call) || call.expression !== called) + continue; + var referenceSymbol = checker.getSymbolAtLocation(name); + if (referenceSymbol && checker.getRootSymbols(referenceSymbol).some(function (s) { return s === symbol; })) { + cb(call); + } + } + } + } + Core.eachSignatureCall = eachSignatureCall; + function getPossibleSymbolReferenceNodes(sourceFile, symbolName, container) { + if (container === void 0) { container = sourceFile; } + return getPossibleSymbolReferencePositions(sourceFile, symbolName, container).map(function (pos) { return ts.getTouchingPropertyName(sourceFile, pos); }); + } + function getPossibleSymbolReferencePositions(sourceFile, symbolName, container) { + if (container === void 0) { container = sourceFile; } + var positions = []; + /// TODO: Cache symbol existence for files to save text search + // Also, need to make this work for unicode escapes. + // Be resilient in the face of a symbol with no name or zero length name + if (!symbolName || !symbolName.length) { + return positions; + } + var text = sourceFile.text; + var sourceLength = text.length; + var symbolNameLength = symbolName.length; + var position = text.indexOf(symbolName, container.pos); + while (position >= 0) { + // If we are past the end, stop looking + if (position > container.end) + break; + // We found a match. Make sure it's not part of a larger word (i.e. the char + // before and after it have to be a non-identifier char). + var endPosition = position + symbolNameLength; + if ((position === 0 || !ts.isIdentifierPart(text.charCodeAt(position - 1), 6 /* Latest */)) && + (endPosition === sourceLength || !ts.isIdentifierPart(text.charCodeAt(endPosition), 6 /* Latest */))) { + // Found a real match. Keep searching. + positions.push(position); + } + position = text.indexOf(symbolName, position + symbolNameLength + 1); + } + return positions; + } + function getLabelReferencesInNode(container, targetLabel) { + var sourceFile = container.getSourceFile(); + var labelName = targetLabel.text; + var references = ts.mapDefined(getPossibleSymbolReferenceNodes(sourceFile, labelName, container), function (node) { + // Only pick labels that are either the target label, or have a target that is the target label + return node === targetLabel || (ts.isJumpStatementTarget(node) && ts.getTargetLabel(node, labelName) === targetLabel) ? FindAllReferences.nodeEntry(node) : undefined; + }); + return [{ definition: { type: 1 /* Label */, node: targetLabel }, references: references }]; + } + function isValidReferencePosition(node, searchSymbolName) { + // Compare the length so we filter out strict superstrings of the symbol we are looking for + switch (node.kind) { + case 72 /* Identifier */: + return node.text.length === searchSymbolName.length; + case 10 /* StringLiteral */: { + var str = node; + return (ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(str) || ts.isNameOfModuleDeclaration(node) || ts.isExpressionOfExternalModuleImportEqualsDeclaration(node) || (ts.isCallExpression(node.parent) && ts.isBindableObjectDefinePropertyCall(node.parent) && node.parent.arguments[1] === node)) && + str.text.length === searchSymbolName.length; + } + case 8 /* NumericLiteral */: + return ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node) && node.text.length === searchSymbolName.length; + case 80 /* DefaultKeyword */: + return "default".length === searchSymbolName.length; + default: + return false; + } + } + function getAllReferencesForKeyword(sourceFiles, keywordKind, cancellationToken) { + var references = ts.flatMap(sourceFiles, function (sourceFile) { + cancellationToken.throwIfCancellationRequested(); + return ts.mapDefined(getPossibleSymbolReferenceNodes(sourceFile, ts.tokenToString(keywordKind), sourceFile), function (referenceLocation) { + return referenceLocation.kind === keywordKind ? FindAllReferences.nodeEntry(referenceLocation) : undefined; + }); + }); + return references.length ? [{ definition: { type: 2 /* Keyword */, node: references[0].node }, references: references }] : undefined; + } + function getReferencesInSourceFile(sourceFile, search, state, addReferencesHere) { + if (addReferencesHere === void 0) { addReferencesHere = true; } + state.cancellationToken.throwIfCancellationRequested(); + return getReferencesInContainer(sourceFile, sourceFile, search, state, addReferencesHere); + } + /** + * Search within node "container" for references for a search value, where the search value is defined as a + * tuple of(searchSymbol, searchText, searchLocation, and searchMeaning). + * searchLocation: a node where the search value + */ + function getReferencesInContainer(container, sourceFile, search, state, addReferencesHere) { + if (!state.markSearchedSymbols(sourceFile, search.allSearchSymbols)) { + return; + } + for (var _i = 0, _a = getPossibleSymbolReferencePositions(sourceFile, search.text, container); _i < _a.length; _i++) { + var position = _a[_i]; + getReferencesAtLocation(sourceFile, position, search, state, addReferencesHere); + } + } + function hasMatchingMeaning(referenceLocation, state) { + return !!(ts.getMeaningFromLocation(referenceLocation) & state.searchMeaning); + } + function getReferencesAtLocation(sourceFile, position, search, state, addReferencesHere) { + var referenceLocation = ts.getTouchingPropertyName(sourceFile, position); + if (!isValidReferencePosition(referenceLocation, search.text)) { + // This wasn't the start of a token. Check to see if it might be a + // match in a comment or string if that's what the caller is asking + // for. + if (!state.options.implementations && (state.options.findInStrings && ts.isInString(sourceFile, position) || state.options.findInComments && ts.isInNonReferenceComment(sourceFile, position))) { + // In the case where we're looking inside comments/strings, we don't have + // an actual definition. So just use 'undefined' here. Features like + // 'Rename' won't care (as they ignore the definitions), and features like + // 'FindReferences' will just filter out these results. + state.addStringOrCommentReference(sourceFile.fileName, ts.createTextSpan(position, search.text.length)); + } + return; + } + if (!hasMatchingMeaning(referenceLocation, state)) + return; + var referenceSymbol = state.checker.getSymbolAtLocation(referenceLocation); + if (!referenceSymbol) { + return; + } + var parent = referenceLocation.parent; + if (ts.isImportSpecifier(parent) && parent.propertyName === referenceLocation) { + // This is added through `singleReferences` in ImportsResult. If we happen to see it again, don't add it again. + return; + } + if (ts.isExportSpecifier(parent)) { + ts.Debug.assert(referenceLocation.kind === 72 /* Identifier */); + getReferencesAtExportSpecifier(referenceLocation, referenceSymbol, parent, search, state, addReferencesHere); + return; + } + var relatedSymbol = getRelatedSymbol(search, referenceSymbol, referenceLocation, state); + if (!relatedSymbol) { + getReferenceForShorthandProperty(referenceSymbol, search, state); + return; + } + switch (state.specialSearchKind) { + case 0 /* None */: + if (addReferencesHere) + addReference(referenceLocation, relatedSymbol, state); + break; + case 1 /* Constructor */: + addConstructorReferences(referenceLocation, sourceFile, search, state); + break; + case 2 /* Class */: + addClassStaticThisReferences(referenceLocation, search, state); + break; + default: + ts.Debug.assertNever(state.specialSearchKind); + } + getImportOrExportReferences(referenceLocation, referenceSymbol, search, state); + } + function getReferencesAtExportSpecifier(referenceLocation, referenceSymbol, exportSpecifier, search, state, addReferencesHere, alwaysGetReferences) { + var parent = exportSpecifier.parent, propertyName = exportSpecifier.propertyName, name = exportSpecifier.name; + var exportDeclaration = parent.parent; + var localSymbol = getLocalSymbolForExportSpecifier(referenceLocation, referenceSymbol, exportSpecifier, state.checker); + if (!alwaysGetReferences && !search.includes(localSymbol)) { + return; + } + if (!propertyName) { + // Don't rename at `export { default } from "m";`. (but do continue to search for imports of the re-export) + if (!(state.options.isForRename && (name.escapedText === "default" /* Default */))) { + addRef(); + } + } + else if (referenceLocation === propertyName) { + // For `export { foo as bar } from "baz"`, "`foo`" will be added from the singleReferences for import searches of the original export. + // For `export { foo as bar };`, where `foo` is a local, so add it now. + if (!exportDeclaration.moduleSpecifier) { + addRef(); + } + if (addReferencesHere && !state.options.isForRename && state.markSeenReExportRHS(name)) { + addReference(name, ts.Debug.assertDefined(exportSpecifier.symbol), state); + } + } + else { + if (state.markSeenReExportRHS(referenceLocation)) { + addRef(); + } + } + // For `export { foo as bar }`, rename `foo`, but not `bar`. + if (!state.options.isForRename || alwaysGetReferences) { + var exportKind = referenceLocation.originalKeywordKind === 80 /* DefaultKeyword */ ? 1 /* Default */ : 0 /* Named */; + var exportSymbol = ts.Debug.assertDefined(exportSpecifier.symbol); + var exportInfo = ts.Debug.assertDefined(FindAllReferences.getExportInfo(exportSymbol, exportKind, state.checker)); + searchForImportsOfExport(referenceLocation, exportSymbol, exportInfo, state); + } + // At `export { x } from "foo"`, also search for the imported symbol `"foo".x`. + if (search.comingFrom !== 1 /* Export */ && exportDeclaration.moduleSpecifier && !propertyName && !state.options.isForRename) { + var imported = state.checker.getExportSpecifierLocalTargetSymbol(exportSpecifier); + if (imported) + searchForImportedSymbol(imported, state); + } + function addRef() { + if (addReferencesHere) + addReference(referenceLocation, localSymbol, state); + } + } + function getLocalSymbolForExportSpecifier(referenceLocation, referenceSymbol, exportSpecifier, checker) { + return isExportSpecifierAlias(referenceLocation, exportSpecifier) && checker.getExportSpecifierLocalTargetSymbol(exportSpecifier) || referenceSymbol; + } + function isExportSpecifierAlias(referenceLocation, exportSpecifier) { + var parent = exportSpecifier.parent, propertyName = exportSpecifier.propertyName, name = exportSpecifier.name; + ts.Debug.assert(propertyName === referenceLocation || name === referenceLocation); + if (propertyName) { + // Given `export { foo as bar } [from "someModule"]`: It's an alias at `foo`, but at `bar` it's a new symbol. + return propertyName === referenceLocation; + } + else { + // `export { foo } from "foo"` is a re-export. + // `export { foo };` is not a re-export, it creates an alias for the local variable `foo`. + return !parent.parent.moduleSpecifier; + } + } + function getImportOrExportReferences(referenceLocation, referenceSymbol, search, state) { + var importOrExport = FindAllReferences.getImportOrExportSymbol(referenceLocation, referenceSymbol, state.checker, search.comingFrom === 1 /* Export */); + if (!importOrExport) + return; + var symbol = importOrExport.symbol; + if (importOrExport.kind === 0 /* Import */) { + if (!state.options.isForRename) { + searchForImportedSymbol(symbol, state); + } + } + else { + searchForImportsOfExport(referenceLocation, symbol, importOrExport.exportInfo, state); + } + } + function getReferenceForShorthandProperty(_a, search, state) { + var flags = _a.flags, valueDeclaration = _a.valueDeclaration; + var shorthandValueSymbol = state.checker.getShorthandAssignmentValueSymbol(valueDeclaration); + var name = valueDeclaration && ts.getNameOfDeclaration(valueDeclaration); + /* + * Because in short-hand property assignment, an identifier which stored as name of the short-hand property assignment + * has two meanings: property name and property value. Therefore when we do findAllReference at the position where + * an identifier is declared, the language service should return the position of the variable declaration as well as + * the position in short-hand property assignment excluding property accessing. However, if we do findAllReference at the + * position of property accessing, the referenceEntry of such position will be handled in the first case. + */ + if (!(flags & 33554432 /* Transient */) && name && search.includes(shorthandValueSymbol)) { + addReference(name, shorthandValueSymbol, state); + } + } + function addReference(referenceLocation, relatedSymbol, state) { + var _a = "kind" in relatedSymbol ? relatedSymbol : { kind: undefined, symbol: relatedSymbol }, kind = _a.kind, symbol = _a.symbol; + var addRef = state.referenceAdder(symbol); + if (state.options.implementations) { + addImplementationReferences(referenceLocation, addRef, state); + } + else { + addRef(referenceLocation, kind); + } + } + /** Adds references when a constructor is used with `new this()` in its own class and `super()` calls in subclasses. */ + function addConstructorReferences(referenceLocation, sourceFile, search, state) { + if (ts.isNewExpressionTarget(referenceLocation)) { + addReference(referenceLocation, search.symbol, state); + } + var pusher = function () { return state.referenceAdder(search.symbol); }; + if (ts.isClassLike(referenceLocation.parent)) { + ts.Debug.assert(referenceLocation.kind === 80 /* DefaultKeyword */ || referenceLocation.parent.name === referenceLocation); + // This is the class declaration containing the constructor. + findOwnConstructorReferences(search.symbol, sourceFile, pusher()); + } + else { + // If this class appears in `extends C`, then the extending class' "super" calls are references. + var classExtending = tryGetClassByExtendingIdentifier(referenceLocation); + if (classExtending) { + findSuperConstructorAccesses(classExtending, pusher()); + } + } + } + function addClassStaticThisReferences(referenceLocation, search, state) { + addReference(referenceLocation, search.symbol, state); + var classLike = referenceLocation.parent; + if (state.options.isForRename || !ts.isClassLike(classLike)) + return; + ts.Debug.assert(classLike.name === referenceLocation); + var addRef = state.referenceAdder(search.symbol); + for (var _i = 0, _a = classLike.members; _i < _a.length; _i++) { + var member = _a[_i]; + if (!(ts.isMethodOrAccessor(member) && ts.hasModifier(member, 32 /* Static */))) { + continue; + } + if (member.body) { + member.body.forEachChild(function cb(node) { + if (node.kind === 100 /* ThisKeyword */) { + addRef(node); + } + else if (!ts.isFunctionLike(node) && !ts.isClassLike(node)) { + node.forEachChild(cb); + } + }); + } + } + } + /** + * `classSymbol` is the class where the constructor was defined. + * Reference the constructor and all calls to `new this()`. + */ + function findOwnConstructorReferences(classSymbol, sourceFile, addNode) { + for (var _i = 0, _a = classSymbol.members.get("__constructor" /* Constructor */).declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + var ctrKeyword = ts.findChildOfKind(decl, 124 /* ConstructorKeyword */, sourceFile); + ts.Debug.assert(decl.kind === 157 /* Constructor */ && !!ctrKeyword); + addNode(ctrKeyword); + } + classSymbol.exports.forEach(function (member) { + var decl = member.valueDeclaration; + if (decl && decl.kind === 156 /* MethodDeclaration */) { + var body = decl.body; + if (body) { + forEachDescendantOfKind(body, 100 /* ThisKeyword */, function (thisKeyword) { + if (ts.isNewExpressionTarget(thisKeyword)) { + addNode(thisKeyword); + } + }); + } + } + }); + } + /** Find references to `super` in the constructor of an extending class. */ + function findSuperConstructorAccesses(cls, addNode) { + var ctr = cls.symbol.members.get("__constructor" /* Constructor */); + if (!ctr) { + return; + } + for (var _i = 0, _a = ctr.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + ts.Debug.assert(decl.kind === 157 /* Constructor */); + var body = decl.body; + if (body) { + forEachDescendantOfKind(body, 98 /* SuperKeyword */, function (node) { + if (ts.isCallExpressionTarget(node)) { + addNode(node); + } + }); + } + } + } + function addImplementationReferences(refNode, addReference, state) { + // Check if we found a function/propertyAssignment/method with an implementation or initializer + if (ts.isDeclarationName(refNode) && isImplementation(refNode.parent)) { + addReference(refNode); + return; + } + if (refNode.kind !== 72 /* Identifier */) { + return; + } + if (refNode.parent.kind === 276 /* ShorthandPropertyAssignment */) { + // Go ahead and dereference the shorthand assignment by going to its definition + getReferenceEntriesForShorthandPropertyAssignment(refNode, state.checker, addReference); + } + // Check if the node is within an extends or implements clause + var containingClass = getContainingClassIfInHeritageClause(refNode); + if (containingClass) { + addReference(containingClass); + return; + } + // If we got a type reference, try and see if the reference applies to any expressions that can implement an interface + // Find the first node whose parent isn't a type node -- i.e., the highest type node. + var typeNode = ts.findAncestor(refNode, function (a) { return !ts.isQualifiedName(a.parent) && !ts.isTypeNode(a.parent) && !ts.isTypeElement(a.parent); }); + var typeHavingNode = typeNode.parent; + if (ts.hasType(typeHavingNode) && typeHavingNode.type === typeNode && state.markSeenContainingTypeReference(typeHavingNode)) { + if (ts.hasInitializer(typeHavingNode)) { + addIfImplementation(typeHavingNode.initializer); + } + else if (ts.isFunctionLike(typeHavingNode) && typeHavingNode.body) { + var body = typeHavingNode.body; + if (body.kind === 218 /* Block */) { + ts.forEachReturnStatement(body, function (returnStatement) { + if (returnStatement.expression) + addIfImplementation(returnStatement.expression); + }); + } + else { + addIfImplementation(body); + } + } + else if (ts.isAssertionExpression(typeHavingNode)) { + addIfImplementation(typeHavingNode.expression); + } + } + function addIfImplementation(e) { + if (isImplementationExpression(e)) + addReference(e); + } + } + function getContainingClassIfInHeritageClause(node) { + return ts.isIdentifier(node) || ts.isPropertyAccessExpression(node) ? getContainingClassIfInHeritageClause(node.parent) + : ts.isExpressionWithTypeArguments(node) ? ts.tryCast(node.parent.parent, ts.isClassLike) : undefined; + } + /** + * Returns true if this is an expression that can be considered an implementation + */ + function isImplementationExpression(node) { + switch (node.kind) { + case 195 /* ParenthesizedExpression */: + return isImplementationExpression(node.expression); + case 197 /* ArrowFunction */: + case 196 /* FunctionExpression */: + case 188 /* ObjectLiteralExpression */: + case 209 /* ClassExpression */: + case 187 /* ArrayLiteralExpression */: + return true; + default: + return false; + } + } + /** + * Determines if the parent symbol occurs somewhere in the child's ancestry. If the parent symbol + * is an interface, determines if some ancestor of the child symbol extends or inherits from it. + * Also takes in a cache of previous results which makes this slightly more efficient and is + * necessary to avoid potential loops like so: + * class A extends B { } + * class B extends A { } + * + * We traverse the AST rather than using the type checker because users are typically only interested + * in explicit implementations of an interface/class when calling "Go to Implementation". Sibling + * implementations of types that share a common ancestor with the type whose implementation we are + * searching for need to be filtered out of the results. The type checker doesn't let us make the + * distinction between structurally compatible implementations and explicit implementations, so we + * must use the AST. + * + * @param symbol A class or interface Symbol + * @param parent Another class or interface Symbol + * @param cachedResults A map of symbol id pairs (i.e. "child,parent") to booleans indicating previous results + */ + function explicitlyInheritsFrom(symbol, parent, cachedResults, checker) { + if (symbol === parent) { + return true; + } + var key = ts.getSymbolId(symbol) + "," + ts.getSymbolId(parent); + var cached = cachedResults.get(key); + if (cached !== undefined) { + return cached; + } + // Set the key so that we don't infinitely recurse + cachedResults.set(key, false); + var inherits = symbol.declarations.some(function (declaration) { + return ts.getAllSuperTypeNodes(declaration).some(function (typeReference) { + var type = checker.getTypeAtLocation(typeReference); + return !!type && !!type.symbol && explicitlyInheritsFrom(type.symbol, parent, cachedResults, checker); + }); + }); + cachedResults.set(key, inherits); + return inherits; + } + function getReferencesForSuperKeyword(superKeyword) { + var searchSpaceNode = ts.getSuperContainer(superKeyword, /*stopOnFunctions*/ false); + if (!searchSpaceNode) { + return undefined; + } + // Whether 'super' occurs in a static context within a class. + var staticFlag = 32 /* Static */; + switch (searchSpaceNode.kind) { + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + staticFlag &= ts.getModifierFlags(searchSpaceNode); + searchSpaceNode = searchSpaceNode.parent; // re-assign to be the owning class + break; + default: + return undefined; + } + var sourceFile = searchSpaceNode.getSourceFile(); + var references = ts.mapDefined(getPossibleSymbolReferenceNodes(sourceFile, "super", searchSpaceNode), function (node) { + if (node.kind !== 98 /* SuperKeyword */) { + return; + } + var container = ts.getSuperContainer(node, /*stopOnFunctions*/ false); + // If we have a 'super' container, we must have an enclosing class. + // Now make sure the owning class is the same as the search-space + // and has the same static qualifier as the original 'super's owner. + return container && (32 /* Static */ & ts.getModifierFlags(container)) === staticFlag && container.parent.symbol === searchSpaceNode.symbol ? FindAllReferences.nodeEntry(node) : undefined; + }); + return [{ definition: { type: 0 /* Symbol */, symbol: searchSpaceNode.symbol }, references: references }]; + } + function getReferencesForThisKeyword(thisOrSuperKeyword, sourceFiles, cancellationToken) { + var searchSpaceNode = ts.getThisContainer(thisOrSuperKeyword, /* includeArrowFunctions */ false); + // Whether 'this' occurs in a static context within a class. + var staticFlag = 32 /* Static */; + switch (searchSpaceNode.kind) { + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + if (ts.isObjectLiteralMethod(searchSpaceNode)) { + break; + } + // falls through + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + staticFlag &= ts.getModifierFlags(searchSpaceNode); + searchSpaceNode = searchSpaceNode.parent; // re-assign to be the owning class + break; + case 279 /* SourceFile */: + if (ts.isExternalModule(searchSpaceNode)) { + return undefined; + } + // falls through + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + break; + // Computed properties in classes are not handled here because references to this are illegal, + // so there is no point finding references to them. + default: + return undefined; + } + var references = ts.flatMap(searchSpaceNode.kind === 279 /* SourceFile */ ? sourceFiles : [searchSpaceNode.getSourceFile()], function (sourceFile) { + cancellationToken.throwIfCancellationRequested(); + return getPossibleSymbolReferenceNodes(sourceFile, "this", ts.isSourceFile(searchSpaceNode) ? sourceFile : searchSpaceNode).filter(function (node) { + if (!ts.isThis(node)) { + return false; + } + var container = ts.getThisContainer(node, /* includeArrowFunctions */ false); + switch (searchSpaceNode.kind) { + case 196 /* FunctionExpression */: + case 239 /* FunctionDeclaration */: + return searchSpaceNode.symbol === container.symbol; + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + return ts.isObjectLiteralMethod(searchSpaceNode) && searchSpaceNode.symbol === container.symbol; + case 209 /* ClassExpression */: + case 240 /* ClassDeclaration */: + // Make sure the container belongs to the same class + // and has the appropriate static modifier from the original container. + return container.parent && searchSpaceNode.symbol === container.parent.symbol && (ts.getModifierFlags(container) & 32 /* Static */) === staticFlag; + case 279 /* SourceFile */: + return container.kind === 279 /* SourceFile */ && !ts.isExternalModule(container); + } + }); + }).map(function (n) { return FindAllReferences.nodeEntry(n); }); + var thisParameter = ts.firstDefined(references, function (r) { return ts.isParameter(r.node.parent) ? r.node : undefined; }); + return [{ + definition: { type: 3 /* This */, node: thisParameter || thisOrSuperKeyword }, + references: references + }]; + } + function getReferencesForStringLiteral(node, sourceFiles, cancellationToken) { + var references = ts.flatMap(sourceFiles, function (sourceFile) { + cancellationToken.throwIfCancellationRequested(); + return ts.mapDefined(getPossibleSymbolReferenceNodes(sourceFile, node.text), function (ref) { + return ts.isStringLiteral(ref) && ref.text === node.text ? FindAllReferences.nodeEntry(ref, 2 /* StringLiteral */) : undefined; + }); + }); + return [{ + definition: { type: 4 /* String */, node: node }, + references: references + }]; + } + // For certain symbol kinds, we need to include other symbols in the search set. + // This is not needed when searching for re-exports. + function populateSearchSymbolSet(symbol, location, checker, isForRename, implementations) { + var result = []; + forEachRelatedSymbol(symbol, location, checker, isForRename, function (sym, root, base) { result.push(base || root || sym); }, + /*allowBaseTypes*/ function () { return !implementations; }); + return result; + } + function forEachRelatedSymbol(symbol, location, checker, isForRenamePopulateSearchSymbolSet, cbSymbol, allowBaseTypes) { + var containingObjectLiteralElement = ts.getContainingObjectLiteralElement(location); + if (containingObjectLiteralElement) { + /* Because in short-hand property assignment, location has two meaning : property name and as value of the property + * When we do findAllReference at the position of the short-hand property assignment, we would want to have references to position of + * property name and variable declaration of the identifier. + * Like in below example, when querying for all references for an identifier 'name', of the property assignment, the language service + * should show both 'name' in 'obj' and 'name' in variable declaration + * const name = "Foo"; + * const obj = { name }; + * In order to do that, we will populate the search set with the value symbol of the identifier as a value of the property assignment + * so that when matching with potential reference symbol, both symbols from property declaration and variable declaration + * will be included correctly. + */ + var shorthandValueSymbol = checker.getShorthandAssignmentValueSymbol(location.parent); // gets the local symbol + if (shorthandValueSymbol && isForRenamePopulateSearchSymbolSet) { + // When renaming 'x' in `const o = { x }`, just rename the local variable, not the property. + return cbSymbol(shorthandValueSymbol, /*rootSymbol*/ undefined, /*baseSymbol*/ undefined, 3 /* SearchedLocalFoundProperty */); + } + // If the location is in a context sensitive location (i.e. in an object literal) try + // to get a contextual type for it, and add the property symbol from the contextual + // type to the search set + var contextualType = checker.getContextualType(containingObjectLiteralElement.parent); + var res_1 = contextualType && ts.firstDefined(ts.getPropertySymbolsFromContextualType(containingObjectLiteralElement, checker, contextualType, /*unionSymbolOk*/ true), function (sym) { return fromRoot(sym, 4 /* SearchedPropertyFoundLocal */); }); + if (res_1) + return res_1; + // If the location is name of property symbol from object literal destructuring pattern + // Search the property symbol + // for ( { property: p2 } of elems) { } + var propertySymbol = getPropertySymbolOfDestructuringAssignment(location, checker); + var res1 = propertySymbol && cbSymbol(propertySymbol, /*rootSymbol*/ undefined, /*baseSymbol*/ undefined, 4 /* SearchedPropertyFoundLocal */); + if (res1) + return res1; + var res2 = shorthandValueSymbol && cbSymbol(shorthandValueSymbol, /*rootSymbol*/ undefined, /*baseSymbol*/ undefined, 3 /* SearchedLocalFoundProperty */); + if (res2) + return res2; + } + var res = fromRoot(symbol); + if (res) + return res; + if (symbol.valueDeclaration && ts.isParameterPropertyDeclaration(symbol.valueDeclaration)) { + // For a parameter property, now try on the other symbol (property if this was a parameter, parameter if this was a property). + var paramProps = checker.getSymbolsOfParameterPropertyDeclaration(ts.cast(symbol.valueDeclaration, ts.isParameter), symbol.name); + ts.Debug.assert(paramProps.length === 2 && !!(paramProps[0].flags & 1 /* FunctionScopedVariable */) && !!(paramProps[1].flags & 4 /* Property */)); // is [parameter, property] + return fromRoot(symbol.flags & 1 /* FunctionScopedVariable */ ? paramProps[1] : paramProps[0]); + } + // symbolAtLocation for a binding element is the local symbol. See if the search symbol is the property. + // Don't do this when populating search set for a rename -- just rename the local. + if (!isForRenamePopulateSearchSymbolSet) { + var bindingElementPropertySymbol = ts.isObjectBindingElementWithoutPropertyName(location.parent) ? ts.getPropertySymbolFromBindingElement(checker, location.parent) : undefined; + return bindingElementPropertySymbol && fromRoot(bindingElementPropertySymbol, 4 /* SearchedPropertyFoundLocal */); + } + function fromRoot(sym, kind) { + // If this is a union property: + // - In populateSearchSymbolsSet we will add all the symbols from all its source symbols in all unioned types. + // - In findRelatedSymbol, we will just use the union symbol if any source symbol is included in the search. + // If the symbol is an instantiation from a another symbol (e.g. widened symbol): + // - In populateSearchSymbolsSet, add the root the list + // - In findRelatedSymbol, return the source symbol if that is in the search. (Do not return the instantiation symbol.) + return ts.firstDefined(checker.getRootSymbols(sym), function (rootSymbol) { + return cbSymbol(sym, rootSymbol, /*baseSymbol*/ undefined, kind) + // Add symbol of properties/methods of the same name in base classes and implemented interfaces definitions + || (rootSymbol.parent && rootSymbol.parent.flags & (32 /* Class */ | 64 /* Interface */) && allowBaseTypes(rootSymbol) + ? ts.getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.name, checker, function (base) { return cbSymbol(sym, rootSymbol, base, kind); }) + : undefined); + }); + } + } + function getRelatedSymbol(search, referenceSymbol, referenceLocation, state) { + var checker = state.checker; + return forEachRelatedSymbol(referenceSymbol, referenceLocation, checker, /*isForRenamePopulateSearchSymbolSet*/ false, function (sym, rootSymbol, baseSymbol, kind) { return search.includes(baseSymbol || rootSymbol || sym) + // For a base type, use the symbol for the derived type. For a synthetic (e.g. union) property, use the union symbol. + ? { symbol: rootSymbol && !(ts.getCheckFlags(sym) & 6 /* Synthetic */) ? rootSymbol : sym, kind: kind } + : undefined; }, + /*allowBaseTypes*/ function (rootSymbol) { + return !(search.parents && !search.parents.some(function (parent) { return explicitlyInheritsFrom(rootSymbol.parent, parent, state.inheritsFromCache, checker); })); + }); + } + /** + * Given an initial searchMeaning, extracted from a location, widen the search scope based on the declarations + * of the corresponding symbol. e.g. if we are searching for "Foo" in value position, but "Foo" references a class + * then we need to widen the search to include type positions as well. + * On the contrary, if we are searching for "Bar" in type position and we trace bar to an interface, and an uninstantiated + * module, we want to keep the search limited to only types, as the two declarations (interface and uninstantiated module) + * do not intersect in any of the three spaces. + */ + function getIntersectingMeaningFromDeclarations(node, symbol) { + var meaning = ts.getMeaningFromLocation(node); + var declarations = symbol.declarations; + if (declarations) { + var lastIterationMeaning = void 0; + do { + // The result is order-sensitive, for instance if initialMeaning === Namespace, and declarations = [class, instantiated module] + // we need to consider both as they initialMeaning intersects with the module in the namespace space, and the module + // intersects with the class in the value space. + // To achieve that we will keep iterating until the result stabilizes. + // Remember the last meaning + lastIterationMeaning = meaning; + for (var _i = 0, declarations_12 = declarations; _i < declarations_12.length; _i++) { + var declaration = declarations_12[_i]; + var declarationMeaning = ts.getMeaningFromDeclaration(declaration); + if (declarationMeaning & meaning) { + meaning |= declarationMeaning; + } + } + } while (meaning !== lastIterationMeaning); + } + return meaning; + } + Core.getIntersectingMeaningFromDeclarations = getIntersectingMeaningFromDeclarations; + function isImplementation(node) { + return !!(node.flags & 4194304 /* Ambient */) + || (ts.isVariableLike(node) ? ts.hasInitializer(node) + : ts.isFunctionLikeDeclaration(node) ? !!node.body + : ts.isClassLike(node) || ts.isModuleOrEnumDeclaration(node)); + } + function getReferenceEntriesForShorthandPropertyAssignment(node, checker, addReference) { + var refSymbol = checker.getSymbolAtLocation(node); + var shorthandSymbol = checker.getShorthandAssignmentValueSymbol(refSymbol.valueDeclaration); + if (shorthandSymbol) { + for (var _i = 0, _a = shorthandSymbol.getDeclarations(); _i < _a.length; _i++) { + var declaration = _a[_i]; + if (ts.getMeaningFromDeclaration(declaration) & 1 /* Value */) { + addReference(declaration); + } + } + } + } + Core.getReferenceEntriesForShorthandPropertyAssignment = getReferenceEntriesForShorthandPropertyAssignment; + function forEachDescendantOfKind(node, kind, action) { + ts.forEachChild(node, function (child) { + if (child.kind === kind) { + action(child); + } + forEachDescendantOfKind(child, kind, action); + }); + } + /** Get `C` given `N` if `N` is in the position `class C extends N` or `class C extends foo.N` where `N` is an identifier. */ + function tryGetClassByExtendingIdentifier(node) { + return ts.tryGetClassExtendingExpressionWithTypeArguments(ts.climbPastPropertyAccess(node).parent); + } + /** + * If we are just looking for implementations and this is a property access expression, we need to get the + * symbol of the local type of the symbol the property is being accessed on. This is because our search + * symbol may have a different parent symbol if the local type's symbol does not declare the property + * being accessed (i.e. it is declared in some parent class or interface) + */ + function getParentSymbolsOfPropertyAccess(location, symbol, checker) { + var propertyAccessExpression = ts.isRightSideOfPropertyAccess(location) ? location.parent : undefined; + var lhsType = propertyAccessExpression && checker.getTypeAtLocation(propertyAccessExpression.expression); + var res = ts.mapDefined(lhsType && (lhsType.isUnionOrIntersection() ? lhsType.types : lhsType.symbol === symbol.parent ? undefined : [lhsType]), function (t) { + return t.symbol && t.symbol.flags & (32 /* Class */ | 64 /* Interface */) ? t.symbol : undefined; + }); + return res.length === 0 ? undefined : res; + } + })(Core = FindAllReferences.Core || (FindAllReferences.Core = {})); + })(FindAllReferences = ts.FindAllReferences || (ts.FindAllReferences = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + function getEditsForFileRename(program, oldFileOrDirPath, newFileOrDirPath, host, formatContext, _preferences, sourceMapper) { + var useCaseSensitiveFileNames = ts.hostUsesCaseSensitiveFileNames(host); + var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); + var oldToNew = getPathUpdater(oldFileOrDirPath, newFileOrDirPath, getCanonicalFileName, sourceMapper); + var newToOld = getPathUpdater(newFileOrDirPath, oldFileOrDirPath, getCanonicalFileName, sourceMapper); + return ts.textChanges.ChangeTracker.with({ host: host, formatContext: formatContext }, function (changeTracker) { + updateTsconfigFiles(program, changeTracker, oldToNew, oldFileOrDirPath, newFileOrDirPath, host.getCurrentDirectory(), useCaseSensitiveFileNames); + updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName); + }); + } + ts.getEditsForFileRename = getEditsForFileRename; + // exported for tests + function getPathUpdater(oldFileOrDirPath, newFileOrDirPath, getCanonicalFileName, sourceMapper) { + var canonicalOldPath = getCanonicalFileName(oldFileOrDirPath); + return function (path) { + var originalPath = sourceMapper && sourceMapper.tryGetSourcePosition({ fileName: path, pos: 0 }); + var updatedPath = getUpdatedPath(originalPath ? originalPath.fileName : path); + return originalPath + ? updatedPath === undefined ? undefined : makeCorrespondingRelativeChange(originalPath.fileName, updatedPath, path, getCanonicalFileName) + : updatedPath; + }; + function getUpdatedPath(pathToUpdate) { + if (getCanonicalFileName(pathToUpdate) === canonicalOldPath) + return newFileOrDirPath; + var suffix = ts.tryRemoveDirectoryPrefix(pathToUpdate, canonicalOldPath, getCanonicalFileName); + return suffix === undefined ? undefined : newFileOrDirPath + "/" + suffix; + } + } + ts.getPathUpdater = getPathUpdater; + // Relative path from a0 to b0 should be same as relative path from a1 to b1. Returns b1. + function makeCorrespondingRelativeChange(a0, b0, a1, getCanonicalFileName) { + var rel = ts.getRelativePathFromFile(a0, b0, getCanonicalFileName); + return combinePathsSafe(ts.getDirectoryPath(a1), rel); + } + function updateTsconfigFiles(program, changeTracker, oldToNew, oldFileOrDirPath, newFileOrDirPath, currentDirectory, useCaseSensitiveFileNames) { + var configFile = program.getCompilerOptions().configFile; + if (!configFile) + return; + var configDir = ts.getDirectoryPath(configFile.fileName); + var jsonObjectLiteral = ts.getTsConfigObjectLiteralExpression(configFile); + if (!jsonObjectLiteral) + return; + forEachProperty(jsonObjectLiteral, function (property, propertyName) { + switch (propertyName) { + case "files": + case "include": + case "exclude": { + var foundExactMatch = updatePaths(property); + if (!foundExactMatch && propertyName === "include" && ts.isArrayLiteralExpression(property.initializer)) { + var includes = ts.mapDefined(property.initializer.elements, function (e) { return ts.isStringLiteral(e) ? e.text : undefined; }); + var matchers = ts.getFileMatcherPatterns(configDir, /*excludes*/ [], includes, useCaseSensitiveFileNames, currentDirectory); + // If there isn't some include for this, add a new one. + if (ts.getRegexFromPattern(ts.Debug.assertDefined(matchers.includeFilePattern), useCaseSensitiveFileNames).test(oldFileOrDirPath) && + !ts.getRegexFromPattern(ts.Debug.assertDefined(matchers.includeFilePattern), useCaseSensitiveFileNames).test(newFileOrDirPath)) { + changeTracker.insertNodeAfter(configFile, ts.last(property.initializer.elements), ts.createStringLiteral(relativePath(newFileOrDirPath))); + } + } + break; + } + case "compilerOptions": + forEachProperty(property.initializer, function (property, propertyName) { + var option = ts.getOptionFromName(propertyName); + if (option && (option.isFilePath || option.type === "list" && option.element.isFilePath)) { + updatePaths(property); + } + else if (propertyName === "paths") { + forEachProperty(property.initializer, function (pathsProperty) { + if (!ts.isArrayLiteralExpression(pathsProperty.initializer)) + return; + for (var _i = 0, _a = pathsProperty.initializer.elements; _i < _a.length; _i++) { + var e = _a[_i]; + tryUpdateString(e); + } + }); + } + }); + break; + } + }); + function updatePaths(property) { + // Type annotation needed due to #7294 + var elements = ts.isArrayLiteralExpression(property.initializer) ? property.initializer.elements : [property.initializer]; + var foundExactMatch = false; + for (var _i = 0, elements_5 = elements; _i < elements_5.length; _i++) { + var element = elements_5[_i]; + foundExactMatch = tryUpdateString(element) || foundExactMatch; + } + return foundExactMatch; + } + function tryUpdateString(element) { + if (!ts.isStringLiteral(element)) + return false; + var elementFileName = combinePathsSafe(configDir, element.text); + var updated = oldToNew(elementFileName); + if (updated !== undefined) { + changeTracker.replaceRangeWithText(configFile, createStringRange(element, configFile), relativePath(updated)); + return true; + } + return false; + } + function relativePath(path) { + return ts.getRelativePathFromDirectory(configDir, path, /*ignoreCase*/ !useCaseSensitiveFileNames); + } + } + function updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName) { + var allFiles = program.getSourceFiles(); + var _loop_12 = function (sourceFile) { + var newFromOld = oldToNew(sourceFile.path); + var newImportFromPath = newFromOld !== undefined ? newFromOld : sourceFile.path; + var newImportFromDirectory = ts.getDirectoryPath(newImportFromPath); + var oldFromNew = newToOld(sourceFile.fileName); + var oldImportFromPath = oldFromNew || sourceFile.fileName; + var oldImportFromDirectory = ts.getDirectoryPath(oldImportFromPath); + var importingSourceFileMoved = newFromOld !== undefined || oldFromNew !== undefined; + updateImportsWorker(sourceFile, changeTracker, function (referenceText) { + if (!ts.pathIsRelative(referenceText)) + return undefined; + var oldAbsolute = combinePathsSafe(oldImportFromDirectory, referenceText); + var newAbsolute = oldToNew(oldAbsolute); + return newAbsolute === undefined ? undefined : ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(newImportFromDirectory, newAbsolute, getCanonicalFileName)); + }, function (importLiteral) { + var importedModuleSymbol = program.getTypeChecker().getSymbolAtLocation(importLiteral); + // No need to update if it's an ambient module^M + if (importedModuleSymbol && importedModuleSymbol.declarations.some(function (d) { return ts.isAmbientModule(d); })) + return undefined; + var toImport = oldFromNew !== undefined + // If we're at the new location (file was already renamed), need to redo module resolution starting from the old location. + // TODO:GH#18217 + ? getSourceFileToImportFromResolved(ts.resolveModuleName(importLiteral.text, oldImportFromPath, program.getCompilerOptions(), host), oldToNew, host) + : getSourceFileToImport(importedModuleSymbol, importLiteral, sourceFile, program, host, oldToNew); + // Need an update if the imported file moved, or the importing file moved and was using a relative path. + return toImport !== undefined && (toImport.updated || (importingSourceFileMoved && ts.pathIsRelative(importLiteral.text))) + ? ts.moduleSpecifiers.updateModuleSpecifier(program.getCompilerOptions(), newImportFromPath, toImport.newFileName, host, allFiles, program.redirectTargetsMap, importLiteral.text) + : undefined; + }); + }; + for (var _i = 0, allFiles_1 = allFiles; _i < allFiles_1.length; _i++) { + var sourceFile = allFiles_1[_i]; + _loop_12(sourceFile); + } + } + function combineNormal(pathA, pathB) { + return ts.normalizePath(ts.combinePaths(pathA, pathB)); + } + function combinePathsSafe(pathA, pathB) { + return ts.ensurePathIsNonModuleName(combineNormal(pathA, pathB)); + } + function getSourceFileToImport(importedModuleSymbol, importLiteral, importingSourceFile, program, host, oldToNew) { + if (importedModuleSymbol) { + // `find` should succeed because we checked for ambient modules before calling this function. + var oldFileName = ts.find(importedModuleSymbol.declarations, ts.isSourceFile).fileName; + var newFileName = oldToNew(oldFileName); + return newFileName === undefined ? { newFileName: oldFileName, updated: false } : { newFileName: newFileName, updated: true }; + } + else { + var resolved = host.resolveModuleNames + ? host.getResolvedModuleWithFailedLookupLocationsFromCache && host.getResolvedModuleWithFailedLookupLocationsFromCache(importLiteral.text, importingSourceFile.fileName) + : program.getResolvedModuleWithFailedLookupLocationsFromCache(importLiteral.text, importingSourceFile.fileName); + return getSourceFileToImportFromResolved(resolved, oldToNew, host); + } + } + function getSourceFileToImportFromResolved(resolved, oldToNew, host) { + // Search through all locations looking for a moved file, and only then test already existing files. + // This is because if `a.ts` is compiled to `a.js` and `a.ts` is moved, we don't want to resolve anything to `a.js`, but to `a.ts`'s new location. + return tryEach(tryGetNewFile) || tryEach(tryGetOldFile); + function tryEach(cb) { + return resolved && ((resolved.resolvedModule && cb(resolved.resolvedModule.resolvedFileName)) || ts.firstDefined(resolved.failedLookupLocations, cb)); + } + function tryGetNewFile(oldFileName) { + var newFileName = oldToNew(oldFileName); + return newFileName !== undefined && host.fileExists(newFileName) ? { newFileName: newFileName, updated: true } : undefined; // TODO: GH#18217 + } + function tryGetOldFile(oldFileName) { + var newFileName = oldToNew(oldFileName); + return host.fileExists(oldFileName) ? newFileName !== undefined ? { newFileName: newFileName, updated: true } : { newFileName: oldFileName, updated: false } : undefined; // TODO: GH#18217 + } + } + function updateImportsWorker(sourceFile, changeTracker, updateRef, updateImport) { + for (var _i = 0, _a = sourceFile.referencedFiles || ts.emptyArray; _i < _a.length; _i++) { // TODO: GH#26162 + var ref = _a[_i]; + var updated = updateRef(ref.fileName); + if (updated !== undefined && updated !== sourceFile.text.slice(ref.pos, ref.end)) + changeTracker.replaceRangeWithText(sourceFile, ref, updated); + } + for (var _b = 0, _c = sourceFile.imports; _b < _c.length; _b++) { + var importStringLiteral = _c[_b]; + var updated = updateImport(importStringLiteral); + if (updated !== undefined && updated !== importStringLiteral.text) + changeTracker.replaceRangeWithText(sourceFile, createStringRange(importStringLiteral, sourceFile), updated); + } + } + function createStringRange(node, sourceFile) { + return ts.createRange(node.getStart(sourceFile) + 1, node.end - 1); + } + function forEachProperty(objectLiteral, cb) { + if (!ts.isObjectLiteralExpression(objectLiteral)) + return; + for (var _i = 0, _a = objectLiteral.properties; _i < _a.length; _i++) { + var property = _a[_i]; + if (ts.isPropertyAssignment(property) && ts.isStringLiteral(property.name)) { + cb(property, property.name.text); + } + } + } +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var GoToDefinition; + (function (GoToDefinition) { + function getDefinitionAtPosition(program, sourceFile, position) { + var reference = getReferenceAtPosition(sourceFile, position, program); + if (reference) { + return [getDefinitionInfoForFileReference(reference.fileName, reference.file.fileName)]; + } + var node = ts.getTouchingPropertyName(sourceFile, position); + if (node === sourceFile) { + return undefined; + } + var parent = node.parent; + // Labels + if (ts.isJumpStatementTarget(node)) { + var label = ts.getTargetLabel(node.parent, node.text); + return label ? [createDefinitionInfoFromName(label, "label" /* label */, node.text, /*containerName*/ undefined)] : undefined; // TODO: GH#18217 + } + var typeChecker = program.getTypeChecker(); + var symbol = getSymbol(node, typeChecker); + // Could not find a symbol e.g. node is string or number keyword, + // or the symbol was an internal symbol and does not have a declaration e.g. undefined symbol + if (!symbol) { + return getDefinitionInfoForIndexSignatures(node, typeChecker); + } + var calledDeclaration = tryGetSignatureDeclaration(typeChecker, node); + // Don't go to the component constructor definition for a JSX element, just go to the component definition. + if (calledDeclaration && !(ts.isJsxOpeningLikeElement(node.parent) && isConstructorLike(calledDeclaration))) { + var sigInfo = createDefinitionFromSignatureDeclaration(typeChecker, calledDeclaration); + // For a function, if this is the original function definition, return just sigInfo. + // If this is the original constructor definition, parent is the class. + if (typeChecker.getRootSymbols(symbol).some(function (s) { return symbolMatchesSignature(s, calledDeclaration); }) || + // TODO: GH#25533 Following check shouldn't be necessary if 'require' is an alias + symbol.declarations && symbol.declarations.some(function (d) { return ts.isVariableDeclaration(d) && !!d.initializer && ts.isRequireCall(d.initializer, /*checkArgumentIsStringLiteralLike*/ false); })) { + return [sigInfo]; + } + else { + var defs = getDefinitionFromSymbol(typeChecker, symbol, node) || ts.emptyArray; + // For a 'super()' call, put the signature first, else put the variable first. + return node.kind === 98 /* SuperKeyword */ ? [sigInfo].concat(defs) : defs.concat([sigInfo]); + } + } + // Because name in short-hand property assignment has two different meanings: property name and property value, + // using go-to-definition at such position should go to the variable declaration of the property value rather than + // go to the declaration of the property name (in this case stay at the same position). However, if go-to-definition + // is performed at the location of property access, we would like to go to definition of the property in the short-hand + // assignment. This case and others are handled by the following code. + if (node.parent.kind === 276 /* ShorthandPropertyAssignment */) { + var shorthandSymbol_1 = typeChecker.getShorthandAssignmentValueSymbol(symbol.valueDeclaration); + return shorthandSymbol_1 ? shorthandSymbol_1.declarations.map(function (decl) { return createDefinitionInfo(decl, typeChecker, shorthandSymbol_1, node); }) : []; + } + // If the node is the name of a BindingElement within an ObjectBindingPattern instead of just returning the + // declaration the symbol (which is itself), we should try to get to the original type of the ObjectBindingPattern + // and return the property declaration for the referenced property. + // For example: + // import('./foo').then(({ b/*goto*/ar }) => undefined); => should get use to the declaration in file "./foo" + // + // function bar(onfulfilled: (value: T) => void) { //....} + // interface Test { + // pr/*destination*/op1: number + // } + // bar(({pr/*goto*/op1})=>{}); + if (ts.isPropertyName(node) && ts.isBindingElement(parent) && ts.isObjectBindingPattern(parent.parent) && + (node === (parent.propertyName || parent.name))) { + var name_5 = ts.getNameFromPropertyName(node); + var type = typeChecker.getTypeAtLocation(parent.parent); + return name_5 === undefined ? ts.emptyArray : ts.flatMap(type.isUnion() ? type.types : [type], function (t) { + var prop = t.getProperty(name_5); + return prop && getDefinitionFromSymbol(typeChecker, prop, node); + }); + } + // If the current location we want to find its definition is in an object literal, try to get the contextual type for the + // object literal, lookup the property symbol in the contextual type, and use this for goto-definition. + // For example + // interface Props{ + // /*first*/prop1: number + // prop2: boolean + // } + // function Foo(arg: Props) {} + // Foo( { pr/*1*/op1: 10, prop2: true }) + var element = ts.getContainingObjectLiteralElement(node); + if (element) { + var contextualType = element && typeChecker.getContextualType(element.parent); + if (contextualType) { + return ts.flatMap(ts.getPropertySymbolsFromContextualType(element, typeChecker, contextualType, /*unionSymbolOk*/ false), function (propertySymbol) { + return getDefinitionFromSymbol(typeChecker, propertySymbol, node); + }); + } + } + return getDefinitionFromSymbol(typeChecker, symbol, node); + } + GoToDefinition.getDefinitionAtPosition = getDefinitionAtPosition; + /** + * True if we should not add definitions for both the signature symbol and the definition symbol. + * True for `const |f = |() => 0`, false for `function |f() {} const |g = f;`. + */ + function symbolMatchesSignature(s, calledDeclaration) { + return s === calledDeclaration.symbol || s === calledDeclaration.symbol.parent || + !ts.isCallLikeExpression(calledDeclaration.parent) && s === calledDeclaration.parent.symbol; + } + function getReferenceAtPosition(sourceFile, position, program) { + var referencePath = findReferenceInPosition(sourceFile.referencedFiles, position); + if (referencePath) { + var file = ts.tryResolveScriptReference(program, sourceFile, referencePath); + return file && { fileName: referencePath.fileName, file: file }; + } + var typeReferenceDirective = findReferenceInPosition(sourceFile.typeReferenceDirectives, position); + if (typeReferenceDirective) { + var reference = program.getResolvedTypeReferenceDirectives().get(typeReferenceDirective.fileName); + var file = reference && program.getSourceFile(reference.resolvedFileName); // TODO:GH#18217 + return file && { fileName: typeReferenceDirective.fileName, file: file }; + } + var libReferenceDirective = findReferenceInPosition(sourceFile.libReferenceDirectives, position); + if (libReferenceDirective) { + var file = program.getLibFileFromReference(libReferenceDirective); + return file && { fileName: libReferenceDirective.fileName, file: file }; + } + return undefined; + } + GoToDefinition.getReferenceAtPosition = getReferenceAtPosition; + /// Goto type + function getTypeDefinitionAtPosition(typeChecker, sourceFile, position) { + var node = ts.getTouchingPropertyName(sourceFile, position); + if (node === sourceFile) { + return undefined; + } + var symbol = typeChecker.getSymbolAtLocation(node); + if (!symbol) + return undefined; + var typeAtLocation = typeChecker.getTypeOfSymbolAtLocation(symbol, node); + var returnType = tryGetReturnTypeOfFunction(symbol, typeAtLocation, typeChecker); + var fromReturnType = returnType && definitionFromType(returnType, typeChecker, node); + // If a function returns 'void' or some other type with no definition, just return the function definition. + return fromReturnType && fromReturnType.length !== 0 ? fromReturnType : definitionFromType(typeAtLocation, typeChecker, node); + } + GoToDefinition.getTypeDefinitionAtPosition = getTypeDefinitionAtPosition; + function definitionFromType(type, checker, node) { + return ts.flatMap(type.isUnion() && !(type.flags & 32 /* Enum */) ? type.types : [type], function (t) { + return t.symbol && getDefinitionFromSymbol(checker, t.symbol, node); + }); + } + function tryGetReturnTypeOfFunction(symbol, type, checker) { + // If the type is just a function's inferred type, + // go-to-type should go to the return type instead, since go-to-definition takes you to the function anyway. + if (type.symbol === symbol || + // At `const f = () => {}`, the symbol is `f` and the type symbol is at `() => {}` + symbol.valueDeclaration && type.symbol && ts.isVariableDeclaration(symbol.valueDeclaration) && symbol.valueDeclaration.initializer === type.symbol.valueDeclaration) { + var sigs = type.getCallSignatures(); + if (sigs.length === 1) + return checker.getReturnTypeOfSignature(ts.first(sigs)); + } + return undefined; + } + function getDefinitionAndBoundSpan(program, sourceFile, position) { + var definitions = getDefinitionAtPosition(program, sourceFile, position); + if (!definitions || definitions.length === 0) { + return undefined; + } + // Check if position is on triple slash reference. + var comment = findReferenceInPosition(sourceFile.referencedFiles, position) || + findReferenceInPosition(sourceFile.typeReferenceDirectives, position) || + findReferenceInPosition(sourceFile.libReferenceDirectives, position); + if (comment) { + return { definitions: definitions, textSpan: ts.createTextSpanFromRange(comment) }; + } + var node = ts.getTouchingPropertyName(sourceFile, position); + var textSpan = ts.createTextSpan(node.getStart(), node.getWidth()); + return { definitions: definitions, textSpan: textSpan }; + } + GoToDefinition.getDefinitionAndBoundSpan = getDefinitionAndBoundSpan; + // At 'x.foo', see if the type of 'x' has an index signature, and if so find its declarations. + function getDefinitionInfoForIndexSignatures(node, checker) { + if (!ts.isPropertyAccessExpression(node.parent) || node.parent.name !== node) + return; + var type = checker.getTypeAtLocation(node.parent.expression); + return ts.mapDefined(type.isUnionOrIntersection() ? type.types : [type], function (nonUnionType) { + var info = checker.getIndexInfoOfType(nonUnionType, 0 /* String */); + return info && info.declaration && createDefinitionFromSignatureDeclaration(checker, info.declaration); + }); + } + function getSymbol(node, checker) { + var symbol = checker.getSymbolAtLocation(node); + // If this is an alias, and the request came at the declaration location + // get the aliased symbol instead. This allows for goto def on an import e.g. + // import {A, B} from "mod"; + // to jump to the implementation directly. + if (symbol && symbol.flags & 2097152 /* Alias */ && shouldSkipAlias(node, symbol.declarations[0])) { + var aliased = checker.getAliasedSymbol(symbol); + if (aliased.declarations) { + return aliased; + } + } + return symbol; + } + // Go to the original declaration for cases: + // + // (1) when the aliased symbol was declared in the location(parent). + // (2) when the aliased symbol is originating from an import. + // + function shouldSkipAlias(node, declaration) { + if (node.kind !== 72 /* Identifier */) { + return false; + } + if (node.parent === declaration) { + return true; + } + switch (declaration.kind) { + case 250 /* ImportClause */: + case 248 /* ImportEqualsDeclaration */: + return true; + case 253 /* ImportSpecifier */: + return declaration.parent.kind === 252 /* NamedImports */; + default: + return false; + } + } + function getDefinitionFromSymbol(typeChecker, symbol, node) { + return getConstructSignatureDefinition() || getCallSignatureDefinition() || ts.map(symbol.declarations, function (declaration) { return createDefinitionInfo(declaration, typeChecker, symbol, node); }); + function getConstructSignatureDefinition() { + // Applicable only if we are in a new expression, or we are on a constructor declaration + // and in either case the symbol has a construct signature definition, i.e. class + if (symbol.flags & 32 /* Class */ && (ts.isNewExpressionTarget(node) || node.kind === 124 /* ConstructorKeyword */)) { + var cls = ts.find(symbol.declarations, ts.isClassLike) || ts.Debug.fail("Expected declaration to have at least one class-like declaration"); + return getSignatureDefinition(cls.members, /*selectConstructors*/ true); + } + } + function getCallSignatureDefinition() { + return ts.isCallOrNewExpressionTarget(node) || ts.isNameOfFunctionDeclaration(node) + ? getSignatureDefinition(symbol.declarations, /*selectConstructors*/ false) + : undefined; + } + function getSignatureDefinition(signatureDeclarations, selectConstructors) { + if (!signatureDeclarations) { + return undefined; + } + var declarations = signatureDeclarations.filter(selectConstructors ? ts.isConstructorDeclaration : ts.isFunctionLike); + return declarations.length + ? [createDefinitionInfo(ts.find(declarations, function (d) { return !!d.body; }) || ts.last(declarations), typeChecker, symbol, node)] + : undefined; + } + } + /** Creates a DefinitionInfo from a Declaration, using the declaration's name if possible. */ + function createDefinitionInfo(declaration, checker, symbol, node) { + var symbolName = checker.symbolToString(symbol); // Do not get scoped name, just the name of the symbol + var symbolKind = ts.SymbolDisplay.getSymbolKind(checker, symbol, node); + var containerName = symbol.parent ? checker.symbolToString(symbol.parent, node) : ""; + return createDefinitionInfoFromName(declaration, symbolKind, symbolName, containerName); + } + /** Creates a DefinitionInfo directly from the name of a declaration. */ + function createDefinitionInfoFromName(declaration, symbolKind, symbolName, containerName) { + var name = ts.getNameOfDeclaration(declaration) || declaration; + var sourceFile = name.getSourceFile(); + return { + fileName: sourceFile.fileName, + textSpan: ts.createTextSpanFromNode(name, sourceFile), + kind: symbolKind, + name: symbolName, + containerKind: undefined, + containerName: containerName + }; + } + function createDefinitionFromSignatureDeclaration(typeChecker, decl) { + return createDefinitionInfo(decl, typeChecker, decl.symbol, decl); + } + function findReferenceInPosition(refs, pos) { + return ts.find(refs, function (ref) { return ts.textRangeContainsPositionInclusive(ref, pos); }); + } + GoToDefinition.findReferenceInPosition = findReferenceInPosition; + function getDefinitionInfoForFileReference(name, targetFileName) { + return { + fileName: targetFileName, + textSpan: ts.createTextSpanFromBounds(0, 0), + kind: "script" /* scriptElement */, + name: name, + containerName: undefined, + containerKind: undefined, + }; + } + /** Returns a CallLikeExpression where `node` is the target being invoked. */ + function getAncestorCallLikeExpression(node) { + var target = climbPastManyPropertyAccesses(node); + var callLike = target.parent; + return callLike && ts.isCallLikeExpression(callLike) && ts.getInvokedExpression(callLike) === target ? callLike : undefined; + } + function climbPastManyPropertyAccesses(node) { + return ts.isRightSideOfPropertyAccess(node) ? climbPastManyPropertyAccesses(node.parent) : node; + } + function tryGetSignatureDeclaration(typeChecker, node) { + var callLike = getAncestorCallLikeExpression(node); + var signature = callLike && typeChecker.getResolvedSignature(callLike); + // Don't go to a function type, go to the value having that type. + return ts.tryCast(signature && signature.declaration, function (d) { return ts.isFunctionLike(d) && !ts.isFunctionTypeNode(d); }); + } + function isConstructorLike(node) { + switch (node.kind) { + case 157 /* Constructor */: + case 166 /* ConstructorType */: + case 161 /* ConstructSignature */: + return true; + default: + return false; + } + } + })(GoToDefinition = ts.GoToDefinition || (ts.GoToDefinition = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var JsDoc; + (function (JsDoc) { + var jsDocTagNames = [ + "abstract", + "access", + "alias", + "argument", + "async", + "augments", + "author", + "borrows", + "callback", + "class", + "classdesc", + "constant", + "constructor", + "constructs", + "copyright", + "default", + "deprecated", + "description", + "emits", + "enum", + "event", + "example", + "exports", + "extends", + "external", + "field", + "file", + "fileoverview", + "fires", + "function", + "generator", + "global", + "hideconstructor", + "host", + "ignore", + "implements", + "inheritdoc", + "inner", + "instance", + "interface", + "kind", + "lends", + "license", + "listens", + "member", + "memberof", + "method", + "mixes", + "module", + "name", + "namespace", + "override", + "package", + "param", + "private", + "property", + "protected", + "public", + "readonly", + "requires", + "returns", + "see", + "since", + "static", + "summary", + "template", + "this", + "throws", + "todo", + "tutorial", + "type", + "typedef", + "var", + "variation", + "version", + "virtual", + "yields" + ]; + var jsDocTagNameCompletionEntries; + var jsDocTagCompletionEntries; + function getJsDocCommentsFromDeclarations(declarations) { + // Only collect doc comments from duplicate declarations once: + // In case of a union property there might be same declaration multiple times + // which only varies in type parameter + // Eg. const a: Array | Array; a.length + // The property length will have two declarations of property length coming + // from Array - Array and Array + var documentationComment = []; + forEachUnique(declarations, function (declaration) { + for (var _i = 0, _a = getCommentHavingNodes(declaration); _i < _a.length; _i++) { + var comment = _a[_i].comment; + if (comment === undefined) + continue; + if (documentationComment.length) { + documentationComment.push(ts.lineBreakPart()); + } + documentationComment.push(ts.textPart(comment)); + } + }); + return documentationComment; + } + JsDoc.getJsDocCommentsFromDeclarations = getJsDocCommentsFromDeclarations; + function getCommentHavingNodes(declaration) { + switch (declaration.kind) { + case 299 /* JSDocParameterTag */: + case 305 /* JSDocPropertyTag */: + return [declaration]; + case 297 /* JSDocCallbackTag */: + case 304 /* JSDocTypedefTag */: + return [declaration, declaration.parent]; + default: + return ts.getJSDocCommentsAndTags(declaration); + } + } + function getJsDocTagsFromDeclarations(declarations) { + // Only collect doc comments from duplicate declarations once. + var tags = []; + forEachUnique(declarations, function (declaration) { + for (var _i = 0, _a = ts.getJSDocTags(declaration); _i < _a.length; _i++) { + var tag = _a[_i]; + tags.push({ name: tag.tagName.text, text: getCommentText(tag) }); + } + }); + return tags; + } + JsDoc.getJsDocTagsFromDeclarations = getJsDocTagsFromDeclarations; + function getCommentText(tag) { + var comment = tag.comment; + switch (tag.kind) { + case 295 /* JSDocAugmentsTag */: + return withNode(tag.class); + case 303 /* JSDocTemplateTag */: + return withList(tag.typeParameters); + case 302 /* JSDocTypeTag */: + return withNode(tag.typeExpression); + case 304 /* JSDocTypedefTag */: + case 297 /* JSDocCallbackTag */: + case 305 /* JSDocPropertyTag */: + case 299 /* JSDocParameterTag */: + var name = tag.name; + return name ? withNode(name) : comment; + default: + return comment; + } + function withNode(node) { + return addComment(node.getText()); + } + function withList(list) { + return addComment(list.map(function (x) { return x.getText(); }).join(", ")); + } + function addComment(s) { + return comment === undefined ? s : s + " " + comment; + } + } + /** + * Iterates through 'array' by index and performs the callback on each element of array until the callback + * returns a truthy value, then returns that value. + * If no such value is found, the callback is applied to each element of array and undefined is returned. + */ + function forEachUnique(array, callback) { + if (array) { + for (var i = 0; i < array.length; i++) { + if (array.indexOf(array[i]) === i) { + var result = callback(array[i], i); + if (result) { + return result; + } + } + } + } + return undefined; + } + function getJSDocTagNameCompletions() { + return jsDocTagNameCompletionEntries || (jsDocTagNameCompletionEntries = ts.map(jsDocTagNames, function (tagName) { + return { + name: tagName, + kind: "keyword" /* keyword */, + kindModifiers: "", + sortText: "0", + }; + })); + } + JsDoc.getJSDocTagNameCompletions = getJSDocTagNameCompletions; + JsDoc.getJSDocTagNameCompletionDetails = getJSDocTagCompletionDetails; + function getJSDocTagCompletions() { + return jsDocTagCompletionEntries || (jsDocTagCompletionEntries = ts.map(jsDocTagNames, function (tagName) { + return { + name: "@" + tagName, + kind: "keyword" /* keyword */, + kindModifiers: "", + sortText: "0" + }; + })); + } + JsDoc.getJSDocTagCompletions = getJSDocTagCompletions; + function getJSDocTagCompletionDetails(name) { + return { + name: name, + kind: "" /* unknown */, + kindModifiers: "", + displayParts: [ts.textPart(name)], + documentation: ts.emptyArray, + tags: undefined, + codeActions: undefined, + }; + } + JsDoc.getJSDocTagCompletionDetails = getJSDocTagCompletionDetails; + function getJSDocParameterNameCompletions(tag) { + if (!ts.isIdentifier(tag.name)) { + return ts.emptyArray; + } + var nameThusFar = tag.name.text; + var jsdoc = tag.parent; + var fn = jsdoc.parent; + if (!ts.isFunctionLike(fn)) + return []; + return ts.mapDefined(fn.parameters, function (param) { + if (!ts.isIdentifier(param.name)) + return undefined; + var name = param.name.text; + if (jsdoc.tags.some(function (t) { return t !== tag && ts.isJSDocParameterTag(t) && ts.isIdentifier(t.name) && t.name.escapedText === name; }) // TODO: GH#18217 + || nameThusFar !== undefined && !ts.startsWith(name, nameThusFar)) { + return undefined; + } + return { name: name, kind: "parameter" /* parameterElement */, kindModifiers: "", sortText: "0" }; + }); + } + JsDoc.getJSDocParameterNameCompletions = getJSDocParameterNameCompletions; + function getJSDocParameterNameCompletionDetails(name) { + return { + name: name, + kind: "parameter" /* parameterElement */, + kindModifiers: "", + displayParts: [ts.textPart(name)], + documentation: ts.emptyArray, + tags: undefined, + codeActions: undefined, + }; + } + JsDoc.getJSDocParameterNameCompletionDetails = getJSDocParameterNameCompletionDetails; + /** + * Checks if position points to a valid position to add JSDoc comments, and if so, + * returns the appropriate template. Otherwise returns an empty string. + * Valid positions are + * - outside of comments, statements, and expressions, and + * - preceding a: + * - function/constructor/method declaration + * - class declarations + * - variable statements + * - namespace declarations + * - interface declarations + * - method signatures + * - type alias declarations + * + * Hosts should ideally check that: + * - The line is all whitespace up to 'position' before performing the insertion. + * - If the keystroke sequence "/\*\*" induced the call, we also check that the next + * non-whitespace character is '*', which (approximately) indicates whether we added + * the second '*' to complete an existing (JSDoc) comment. + * @param fileName The file in which to perform the check. + * @param position The (character-indexed) position in the file where the check should + * be performed. + */ + function getDocCommentTemplateAtPosition(newLine, sourceFile, position) { + var tokenAtPos = ts.getTokenAtPosition(sourceFile, position); + var existingDocComment = ts.findAncestor(tokenAtPos, ts.isJSDoc); + if (existingDocComment && (existingDocComment.comment !== undefined || ts.length(existingDocComment.tags))) { + // Non-empty comment already exists. + return undefined; + } + var tokenStart = tokenAtPos.getStart(sourceFile); + // Don't provide a doc comment template based on a *previous* node. (But an existing empty jsdoc comment will likely start before `position`.) + if (!existingDocComment && tokenStart < position) { + return undefined; + } + var commentOwnerInfo = getCommentOwnerInfo(tokenAtPos); + if (!commentOwnerInfo) { + return undefined; + } + var commentOwner = commentOwnerInfo.commentOwner, parameters = commentOwnerInfo.parameters; + if (commentOwner.getStart(sourceFile) < position) { + return undefined; + } + if (!parameters || parameters.length === 0) { + // if there are no parameters, just complete to a single line JSDoc comment + var singleLineResult = "/** */"; + return { newText: singleLineResult, caretOffset: 3 }; + } + var indentationStr = getIndentationStringAtPosition(sourceFile, position); + // A doc comment consists of the following + // * The opening comment line + // * the first line (without a param) for the object's untagged info (this is also where the caret ends up) + // * the '@param'-tagged lines + // * TODO: other tags. + // * the closing comment line + // * if the caret was directly in front of the object, then we add an extra line and indentation. + var preamble = "/**" + newLine + indentationStr + " * "; + var result = preamble + newLine + + parameterDocComments(parameters, ts.hasJSFileExtension(sourceFile.fileName), indentationStr, newLine) + + indentationStr + " */" + + (tokenStart === position ? newLine + indentationStr : ""); + return { newText: result, caretOffset: preamble.length }; + } + JsDoc.getDocCommentTemplateAtPosition = getDocCommentTemplateAtPosition; + function getIndentationStringAtPosition(sourceFile, position) { + var text = sourceFile.text; + var lineStart = ts.getLineStartPositionForPosition(position, sourceFile); + var pos = lineStart; + for (; pos <= position && ts.isWhiteSpaceSingleLine(text.charCodeAt(pos)); pos++) + ; + return text.slice(lineStart, pos); + } + function parameterDocComments(parameters, isJavaScriptFile, indentationStr, newLine) { + return parameters.map(function (_a, i) { + var name = _a.name, dotDotDotToken = _a.dotDotDotToken; + var paramName = name.kind === 72 /* Identifier */ ? name.text : "param" + i; + var type = isJavaScriptFile ? (dotDotDotToken ? "{...any} " : "{any} ") : ""; + return indentationStr + " * @param " + type + paramName + newLine; + }).join(""); + } + function getCommentOwnerInfo(tokenAtPos) { + return ts.forEachAncestor(tokenAtPos, getCommentOwnerInfoWorker); + } + function getCommentOwnerInfoWorker(commentOwner) { + switch (commentOwner.kind) { + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 156 /* MethodDeclaration */: + case 157 /* Constructor */: + case 155 /* MethodSignature */: + var parameters = commentOwner.parameters; + return { commentOwner: commentOwner, parameters: parameters }; + case 275 /* PropertyAssignment */: + return getCommentOwnerInfoWorker(commentOwner.initializer); + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + case 153 /* PropertySignature */: + case 243 /* EnumDeclaration */: + case 278 /* EnumMember */: + case 242 /* TypeAliasDeclaration */: + return { commentOwner: commentOwner }; + case 219 /* VariableStatement */: { + var varStatement = commentOwner; + var varDeclarations = varStatement.declarationList.declarations; + var parameters_1 = varDeclarations.length === 1 && varDeclarations[0].initializer + ? getParametersFromRightHandSideOfAssignment(varDeclarations[0].initializer) + : undefined; + return { commentOwner: commentOwner, parameters: parameters_1 }; + } + case 279 /* SourceFile */: + return "quit"; + case 244 /* ModuleDeclaration */: + // If in walking up the tree, we hit a a nested namespace declaration, + // then we must be somewhere within a dotted namespace name; however we don't + // want to give back a JSDoc template for the 'b' or 'c' in 'namespace a.b.c { }'. + return commentOwner.parent.kind === 244 /* ModuleDeclaration */ ? undefined : { commentOwner: commentOwner }; + case 204 /* BinaryExpression */: { + var be = commentOwner; + if (ts.getAssignmentDeclarationKind(be) === 0 /* None */) { + return "quit"; + } + var parameters_2 = ts.isFunctionLike(be.right) ? be.right.parameters : ts.emptyArray; + return { commentOwner: commentOwner, parameters: parameters_2 }; + } + } + } + /** + * Digs into an an initializer or RHS operand of an assignment operation + * to get the parameters of an apt signature corresponding to a + * function expression or a class expression. + * + * @param rightHandSide the expression which may contain an appropriate set of parameters + * @returns the parameters of a signature found on the RHS if one exists; otherwise 'emptyArray'. + */ + function getParametersFromRightHandSideOfAssignment(rightHandSide) { + while (rightHandSide.kind === 195 /* ParenthesizedExpression */) { + rightHandSide = rightHandSide.expression; + } + switch (rightHandSide.kind) { + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + return rightHandSide.parameters; + case 209 /* ClassExpression */: { + var ctr = ts.find(rightHandSide.members, ts.isConstructorDeclaration); + return ctr ? ctr.parameters : ts.emptyArray; + } + } + return ts.emptyArray; + } + })(JsDoc = ts.JsDoc || (ts.JsDoc = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var NavigateTo; + (function (NavigateTo) { + function getNavigateToItems(sourceFiles, checker, cancellationToken, searchValue, maxResultCount, excludeDtsFiles) { + var patternMatcher = ts.createPatternMatcher(searchValue); + if (!patternMatcher) + return ts.emptyArray; + var rawItems = []; + var _loop_13 = function (sourceFile) { + cancellationToken.throwIfCancellationRequested(); + if (excludeDtsFiles && sourceFile.isDeclarationFile) { + return "continue"; + } + sourceFile.getNamedDeclarations().forEach(function (declarations, name) { + getItemsFromNamedDeclaration(patternMatcher, name, declarations, checker, sourceFile.fileName, rawItems); + }); + }; + // Search the declarations in all files and output matched NavigateToItem into array of NavigateToItem[] + for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) { + var sourceFile = sourceFiles_6[_i]; + _loop_13(sourceFile); + } + rawItems.sort(compareNavigateToItems); + return (maxResultCount === undefined ? rawItems : rawItems.slice(0, maxResultCount)).map(createNavigateToItem); + } + NavigateTo.getNavigateToItems = getNavigateToItems; + function getItemsFromNamedDeclaration(patternMatcher, name, declarations, checker, fileName, rawItems) { + // First do a quick check to see if the name of the declaration matches the + // last portion of the (possibly) dotted name they're searching for. + var match = patternMatcher.getMatchForLastSegmentOfPattern(name); + if (!match) { + return; // continue to next named declarations + } + for (var _i = 0, declarations_13 = declarations; _i < declarations_13.length; _i++) { + var declaration = declarations_13[_i]; + if (!shouldKeepItem(declaration, checker)) + continue; + if (patternMatcher.patternContainsDots) { + // If the pattern has dots in it, then also see if the declaration container matches as well. + var fullMatch = patternMatcher.getFullMatch(getContainers(declaration), name); + if (fullMatch) { + rawItems.push({ name: name, fileName: fileName, matchKind: fullMatch.kind, isCaseSensitive: fullMatch.isCaseSensitive, declaration: declaration }); + } + } + else { + rawItems.push({ name: name, fileName: fileName, matchKind: match.kind, isCaseSensitive: match.isCaseSensitive, declaration: declaration }); + } + } + } + function shouldKeepItem(declaration, checker) { + switch (declaration.kind) { + case 250 /* ImportClause */: + case 253 /* ImportSpecifier */: + case 248 /* ImportEqualsDeclaration */: + var importer = checker.getSymbolAtLocation(declaration.name); // TODO: GH#18217 + var imported = checker.getAliasedSymbol(importer); + return importer.escapedName !== imported.escapedName; + default: + return true; + } + } + function tryAddSingleDeclarationName(declaration, containers) { + var name = ts.getNameOfDeclaration(declaration); + return !!name && (pushLiteral(name, containers) || name.kind === 149 /* ComputedPropertyName */ && tryAddComputedPropertyName(name.expression, containers)); + } + // Only added the names of computed properties if they're simple dotted expressions, like: + // + // [X.Y.Z]() { } + function tryAddComputedPropertyName(expression, containers) { + return pushLiteral(expression, containers) + || ts.isPropertyAccessExpression(expression) && (containers.push(expression.name.text), true) && tryAddComputedPropertyName(expression.expression, containers); + } + function pushLiteral(node, containers) { + return ts.isPropertyNameLiteral(node) && (containers.push(ts.getTextOfIdentifierOrLiteral(node)), true); + } + function getContainers(declaration) { + var containers = []; + // First, if we started with a computed property name, then add all but the last + // portion into the container array. + var name = ts.getNameOfDeclaration(declaration); + if (name && name.kind === 149 /* ComputedPropertyName */ && !tryAddComputedPropertyName(name.expression, containers)) { + return ts.emptyArray; + } + // Don't include the last portion. + containers.shift(); + // Now, walk up our containers, adding all their names to the container array. + var container = ts.getContainerNode(declaration); + while (container) { + if (!tryAddSingleDeclarationName(container, containers)) { + return ts.emptyArray; + } + container = ts.getContainerNode(container); + } + return containers.reverse(); + } + function compareNavigateToItems(i1, i2) { + // TODO(cyrusn): get the gamut of comparisons that VS already uses here. + return ts.compareValues(i1.matchKind, i2.matchKind) + || ts.compareStringsCaseSensitiveUI(i1.name, i2.name); + } + function createNavigateToItem(rawItem) { + var declaration = rawItem.declaration; + var container = ts.getContainerNode(declaration); + var containerName = container && ts.getNameOfDeclaration(container); + return { + name: rawItem.name, + kind: ts.getNodeKind(declaration), + kindModifiers: ts.getNodeModifiers(declaration), + matchKind: ts.PatternMatchKind[rawItem.matchKind], + isCaseSensitive: rawItem.isCaseSensitive, + fileName: rawItem.fileName, + textSpan: ts.createTextSpanFromNode(declaration), + // TODO(jfreeman): What should be the containerName when the container has a computed name? + containerName: containerName ? containerName.text : "", + containerKind: containerName ? ts.getNodeKind(container) : "" /* unknown */, + }; + } + })(NavigateTo = ts.NavigateTo || (ts.NavigateTo = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var NavigationBar; + (function (NavigationBar) { + /** + * Matches all whitespace characters in a string. Eg: + * + * "app. + * + * onactivated" + * + * matches because of the newline, whereas + * + * "app.onactivated" + * + * does not match. + */ + var whiteSpaceRegex = /\s+/g; + // Keep sourceFile handy so we don't have to search for it every time we need to call `getText`. + var curCancellationToken; + var curSourceFile; + /** + * For performance, we keep navigation bar parents on a stack rather than passing them through each recursion. + * `parent` is the current parent and is *not* stored in parentsStack. + * `startNode` sets a new parent and `endNode` returns to the previous parent. + */ + var parentsStack = []; + var parent; + // NavigationBarItem requires an array, but will not mutate it, so just give it this for performance. + var emptyChildItemArray = []; + function getNavigationBarItems(sourceFile, cancellationToken) { + curCancellationToken = cancellationToken; + curSourceFile = sourceFile; + try { + return ts.map(topLevelItems(rootNavigationBarNode(sourceFile)), convertToTopLevelItem); + } + finally { + reset(); + } + } + NavigationBar.getNavigationBarItems = getNavigationBarItems; + function getNavigationTree(sourceFile, cancellationToken) { + curCancellationToken = cancellationToken; + curSourceFile = sourceFile; + try { + return convertToTree(rootNavigationBarNode(sourceFile)); + } + finally { + reset(); + } + } + NavigationBar.getNavigationTree = getNavigationTree; + function reset() { + curSourceFile = undefined; + curCancellationToken = undefined; + parentsStack = []; + parent = undefined; + emptyChildItemArray = []; + } + function nodeText(node) { + return node.getText(curSourceFile); + } + function navigationBarNodeKind(n) { + return n.node.kind; + } + function pushChild(parent, child) { + if (parent.children) { + parent.children.push(child); + } + else { + parent.children = [child]; + } + } + function rootNavigationBarNode(sourceFile) { + ts.Debug.assert(!parentsStack.length); + var root = { node: sourceFile, name: undefined, additionalNodes: undefined, parent: undefined, children: undefined, indent: 0 }; + parent = root; + for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + addChildrenRecursively(statement); + } + endNode(); + ts.Debug.assert(!parent && !parentsStack.length); + return root; + } + function addLeafNode(node) { + pushChild(parent, emptyNavigationBarNode(node)); + } + function emptyNavigationBarNode(node) { + return { + node: node, + name: ts.isDeclaration(node) || ts.isExpression(node) ? ts.getNameOfDeclaration(node) : undefined, + additionalNodes: undefined, + parent: parent, + children: undefined, + indent: parent.indent + 1 + }; + } + /** + * Add a new level of NavigationBarNodes. + * This pushes to the stack, so you must call `endNode` when you are done adding to this node. + */ + function startNode(node) { + var navNode = emptyNavigationBarNode(node); + pushChild(parent, navNode); + // Save the old parent + parentsStack.push(parent); + parent = navNode; + } + /** Call after calling `startNode` and adding children to it. */ + function endNode() { + if (parent.children) { + mergeChildren(parent.children, parent); + sortChildren(parent.children); + } + parent = parentsStack.pop(); + } + function addNodeWithRecursiveChild(node, child) { + startNode(node); + addChildrenRecursively(child); + endNode(); + } + /** Look for navigation bar items in node's subtree, adding them to the current `parent`. */ + function addChildrenRecursively(node) { + curCancellationToken.throwIfCancellationRequested(); + if (!node || ts.isToken(node)) { + return; + } + switch (node.kind) { + case 157 /* Constructor */: + // Get parameter properties, and treat them as being on the *same* level as the constructor, not under it. + var ctr = node; + addNodeWithRecursiveChild(ctr, ctr.body); + // Parameter properties are children of the class, not the constructor. + for (var _i = 0, _a = ctr.parameters; _i < _a.length; _i++) { + var param = _a[_i]; + if (ts.isParameterPropertyDeclaration(param)) { + addLeafNode(param); + } + } + break; + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 155 /* MethodSignature */: + if (!ts.hasDynamicName(node)) { + addNodeWithRecursiveChild(node, node.body); + } + break; + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + if (!ts.hasDynamicName(node)) { + addLeafNode(node); + } + break; + case 250 /* ImportClause */: + var importClause = node; + // Handle default import case e.g.: + // import d from "mod"; + if (importClause.name) { + addLeafNode(importClause.name); + } + // Handle named bindings in imports e.g.: + // import * as NS from "mod"; + // import {a, b as B} from "mod"; + var namedBindings = importClause.namedBindings; + if (namedBindings) { + if (namedBindings.kind === 251 /* NamespaceImport */) { + addLeafNode(namedBindings); + } + else { + for (var _b = 0, _c = namedBindings.elements; _b < _c.length; _b++) { + var element = _c[_b]; + addLeafNode(element); + } + } + } + break; + case 186 /* BindingElement */: + case 237 /* VariableDeclaration */: + var _d = node, name = _d.name, initializer = _d.initializer; + if (ts.isBindingPattern(name)) { + addChildrenRecursively(name); + } + else if (initializer && isFunctionOrClassExpression(initializer)) { + if (initializer.name) { + // Don't add a node for the VariableDeclaration, just for the initializer. + addChildrenRecursively(initializer); + } + else { + // Add a node for the VariableDeclaration, but not for the initializer. + startNode(node); + ts.forEachChild(initializer, addChildrenRecursively); + endNode(); + } + } + else { + addNodeWithRecursiveChild(node, initializer); + } + break; + case 197 /* ArrowFunction */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + addNodeWithRecursiveChild(node, node.body); + break; + case 243 /* EnumDeclaration */: + startNode(node); + for (var _e = 0, _f = node.members; _e < _f.length; _e++) { + var member = _f[_e]; + if (!isComputedProperty(member)) { + addLeafNode(member); + } + } + endNode(); + break; + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 241 /* InterfaceDeclaration */: + startNode(node); + for (var _g = 0, _h = node.members; _g < _h.length; _g++) { + var member = _h[_g]; + addChildrenRecursively(member); + } + endNode(); + break; + case 244 /* ModuleDeclaration */: + addNodeWithRecursiveChild(node, getInteriorModule(node).body); + break; + case 257 /* ExportSpecifier */: + case 248 /* ImportEqualsDeclaration */: + case 162 /* IndexSignature */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 242 /* TypeAliasDeclaration */: + addLeafNode(node); + break; + case 204 /* BinaryExpression */: { + var special = ts.getAssignmentDeclarationKind(node); + switch (special) { + case 1 /* ExportsProperty */: + case 2 /* ModuleExports */: + case 3 /* PrototypeProperty */: + case 6 /* Prototype */: + addNodeWithRecursiveChild(node, node.right); + return; + case 4 /* ThisProperty */: + case 5 /* Property */: + case 0 /* None */: + case 7 /* ObjectDefinePropertyValue */: + case 8 /* ObjectDefinePropertyExports */: + case 9 /* ObjectDefinePrototypeProperty */: + break; + default: + ts.Debug.assertNever(special); + } + } + // falls through + default: + if (ts.hasJSDocNodes(node)) { + ts.forEach(node.jsDoc, function (jsDoc) { + ts.forEach(jsDoc.tags, function (tag) { + if (ts.isJSDocTypeAlias(tag)) { + addLeafNode(tag); + } + }); + }); + } + ts.forEachChild(node, addChildrenRecursively); + } + } + /** Merge declarations of the same kind. */ + function mergeChildren(children, node) { + var nameToItems = ts.createMap(); + ts.filterMutate(children, function (child) { + var declName = ts.getNameOfDeclaration(child.node); + var name = declName && nodeText(declName); + if (!name) { + // Anonymous items are never merged. + return true; + } + var itemsWithSameName = nameToItems.get(name); + if (!itemsWithSameName) { + nameToItems.set(name, child); + return true; + } + if (itemsWithSameName instanceof Array) { + for (var _i = 0, itemsWithSameName_1 = itemsWithSameName; _i < itemsWithSameName_1.length; _i++) { + var itemWithSameName = itemsWithSameName_1[_i]; + if (tryMerge(itemWithSameName, child, node)) { + return false; + } + } + itemsWithSameName.push(child); + return true; + } + else { + var itemWithSameName = itemsWithSameName; + if (tryMerge(itemWithSameName, child, node)) { + return false; + } + nameToItems.set(name, [itemWithSameName, child]); + return true; + } + }); + } + function tryMerge(a, b, parent) { + if (shouldReallyMerge(a.node, b.node, parent)) { + merge(a, b); + return true; + } + return false; + } + /** a and b have the same name, but they may not be mergeable. */ + function shouldReallyMerge(a, b, parent) { + if (a.kind !== b.kind || a.parent !== b.parent && !(isOwnChild(a, parent) && isOwnChild(b, parent))) { + return false; + } + switch (a.kind) { + case 154 /* PropertyDeclaration */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + return ts.hasModifier(a, 32 /* Static */) === ts.hasModifier(b, 32 /* Static */); + case 244 /* ModuleDeclaration */: + return areSameModule(a, b); + default: + return true; + } + } + // We want to merge own children like `I` in in `module A { interface I {} } module A { interface I {} }` + // We don't want to merge unrelated children like `m` in `const o = { a: { m() {} }, b: { m() {} } };` + function isOwnChild(n, parent) { + var par = ts.isModuleBlock(n.parent) ? n.parent.parent : n.parent; + return par === parent.node || ts.contains(parent.additionalNodes, par); + } + // We use 1 NavNode to represent 'A.B.C', but there are multiple source nodes. + // Only merge module nodes that have the same chain. Don't merge 'A.B.C' with 'A'! + function areSameModule(a, b) { + // TODO: GH#18217 + return a.body.kind === b.body.kind && (a.body.kind !== 244 /* ModuleDeclaration */ || areSameModule(a.body, b.body)); + } + /** Merge source into target. Source should be thrown away after this is called. */ + function merge(target, source) { + var _a; + target.additionalNodes = target.additionalNodes || []; + target.additionalNodes.push(source.node); + if (source.additionalNodes) { + (_a = target.additionalNodes).push.apply(_a, source.additionalNodes); + } + target.children = ts.concatenate(target.children, source.children); + if (target.children) { + mergeChildren(target.children, target); + sortChildren(target.children); + } + } + /** Recursively ensure that each NavNode's children are in sorted order. */ + function sortChildren(children) { + children.sort(compareChildren); + } + function compareChildren(child1, child2) { + return ts.compareStringsCaseSensitiveUI(tryGetName(child1.node), tryGetName(child2.node)) // TODO: GH#18217 + || ts.compareValues(navigationBarNodeKind(child1), navigationBarNodeKind(child2)); + } + /** + * This differs from getItemName because this is just used for sorting. + * We only sort nodes by name that have a more-or-less "direct" name, as opposed to `new()` and the like. + * So `new()` can still come before an `aardvark` method. + */ + function tryGetName(node) { + if (node.kind === 244 /* ModuleDeclaration */) { + return getModuleName(node); + } + var declName = ts.getNameOfDeclaration(node); + if (declName && ts.isPropertyName(declName)) { + return ts.unescapeLeadingUnderscores(ts.getPropertyNameForPropertyNameNode(declName)); // TODO: GH#18217 + } + switch (node.kind) { + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 209 /* ClassExpression */: + return getFunctionOrClassName(node); + default: + return undefined; + } + } + function getItemName(node, name) { + if (node.kind === 244 /* ModuleDeclaration */) { + return getModuleName(node); + } + if (name) { + var text = nodeText(name); + if (text.length > 0) { + return text; + } + } + switch (node.kind) { + case 279 /* SourceFile */: + var sourceFile = node; + return ts.isExternalModule(sourceFile) + ? "\"" + ts.escapeString(ts.getBaseFileName(ts.removeFileExtension(ts.normalizePath(sourceFile.fileName)))) + "\"" + : ""; + case 197 /* ArrowFunction */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + if (ts.getModifierFlags(node) & 512 /* Default */) { + return "default"; + } + // We may get a string with newlines or other whitespace in the case of an object dereference + // (eg: "app\n.onactivated"), so we should remove the whitespace for readabiltiy in the + // navigation bar. + return getFunctionOrClassName(node); + case 157 /* Constructor */: + return "constructor"; + case 161 /* ConstructSignature */: + return "new()"; + case 160 /* CallSignature */: + return "()"; + case 162 /* IndexSignature */: + return "[]"; + default: + return ""; + } + } + /** Flattens the NavNode tree to a list, keeping only the top-level items. */ + function topLevelItems(root) { + var topLevel = []; + function recur(item) { + if (isTopLevel(item)) { + topLevel.push(item); + if (item.children) { + for (var _i = 0, _a = item.children; _i < _a.length; _i++) { + var child = _a[_i]; + recur(child); + } + } + } + } + recur(root); + return topLevel; + function isTopLevel(item) { + switch (navigationBarNodeKind(item)) { + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 243 /* EnumDeclaration */: + case 241 /* InterfaceDeclaration */: + case 244 /* ModuleDeclaration */: + case 279 /* SourceFile */: + case 242 /* TypeAliasDeclaration */: + case 304 /* JSDocTypedefTag */: + case 297 /* JSDocCallbackTag */: + return true; + case 157 /* Constructor */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 237 /* VariableDeclaration */: + return hasSomeImportantChild(item); + case 197 /* ArrowFunction */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + return isTopLevelFunctionDeclaration(item); + default: + return false; + } + function isTopLevelFunctionDeclaration(item) { + if (!item.node.body) { + return false; + } + switch (navigationBarNodeKind(item.parent)) { + case 245 /* ModuleBlock */: + case 279 /* SourceFile */: + case 156 /* MethodDeclaration */: + case 157 /* Constructor */: + return true; + default: + return hasSomeImportantChild(item); + } + } + function hasSomeImportantChild(item) { + return ts.some(item.children, function (child) { + var childKind = navigationBarNodeKind(child); + return childKind !== 237 /* VariableDeclaration */ && childKind !== 186 /* BindingElement */; + }); + } + } + } + function convertToTree(n) { + return { + text: getItemName(n.node, n.name), + kind: ts.getNodeKind(n.node), + kindModifiers: getModifiers(n.node), + spans: getSpans(n), + nameSpan: n.name && getNodeSpan(n.name), + childItems: ts.map(n.children, convertToTree) + }; + } + function convertToTopLevelItem(n) { + return { + text: getItemName(n.node, n.name), + kind: ts.getNodeKind(n.node), + kindModifiers: getModifiers(n.node), + spans: getSpans(n), + childItems: ts.map(n.children, convertToChildItem) || emptyChildItemArray, + indent: n.indent, + bolded: false, + grayed: false + }; + function convertToChildItem(n) { + return { + text: getItemName(n.node, n.name), + kind: ts.getNodeKind(n.node), + kindModifiers: ts.getNodeModifiers(n.node), + spans: getSpans(n), + childItems: emptyChildItemArray, + indent: 0, + bolded: false, + grayed: false + }; + } + } + function getSpans(n) { + var spans = [getNodeSpan(n.node)]; + if (n.additionalNodes) { + for (var _i = 0, _a = n.additionalNodes; _i < _a.length; _i++) { + var node = _a[_i]; + spans.push(getNodeSpan(node)); + } + } + return spans; + } + function getModuleName(moduleDeclaration) { + // We want to maintain quotation marks. + if (ts.isAmbientModule(moduleDeclaration)) { + return ts.getTextOfNode(moduleDeclaration.name); + } + // Otherwise, we need to aggregate each identifier to build up the qualified name. + var result = []; + result.push(ts.getTextOfIdentifierOrLiteral(moduleDeclaration.name)); + while (moduleDeclaration.body && moduleDeclaration.body.kind === 244 /* ModuleDeclaration */) { + moduleDeclaration = moduleDeclaration.body; + result.push(ts.getTextOfIdentifierOrLiteral(moduleDeclaration.name)); + } + return result.join("."); + } + /** + * For 'module A.B.C', we want to get the node for 'C'. + * We store 'A' as associated with a NavNode, and use getModuleName to traverse down again. + */ + function getInteriorModule(decl) { + return decl.body && ts.isModuleDeclaration(decl.body) ? getInteriorModule(decl.body) : decl; + } + function isComputedProperty(member) { + return !member.name || member.name.kind === 149 /* ComputedPropertyName */; + } + function getNodeSpan(node) { + return node.kind === 279 /* SourceFile */ ? ts.createTextSpanFromRange(node) : ts.createTextSpanFromNode(node, curSourceFile); + } + function getModifiers(node) { + if (node.parent && node.parent.kind === 237 /* VariableDeclaration */) { + node = node.parent; + } + return ts.getNodeModifiers(node); + } + function getFunctionOrClassName(node) { + var parent = node.parent; + if (node.name && ts.getFullWidth(node.name) > 0) { + return ts.declarationNameToString(node.name); + } + // See if it is a var initializer. If so, use the var name. + else if (ts.isVariableDeclaration(parent)) { + return ts.declarationNameToString(parent.name); + } + // See if it is of the form " = function(){...}". If so, use the text from the left-hand side. + else if (ts.isBinaryExpression(parent) && parent.operatorToken.kind === 59 /* EqualsToken */) { + return nodeText(parent.left).replace(whiteSpaceRegex, ""); + } + // See if it is a property assignment, and if so use the property name + else if (ts.isPropertyAssignment(parent)) { + return nodeText(parent.name); + } + // Default exports are named "default" + else if (ts.getModifierFlags(node) & 512 /* Default */) { + return "default"; + } + else if (ts.isClassLike(node)) { + return ""; + } + else if (ts.isCallExpression(parent)) { + var name = getCalledExpressionName(parent.expression); + if (name !== undefined) { + var args = ts.mapDefined(parent.arguments, function (a) { return ts.isStringLiteral(a) ? a.getText(curSourceFile) : undefined; }).join(", "); + return name + "(" + args + ") callback"; + } + } + return ""; + } + function getCalledExpressionName(expr) { + if (ts.isIdentifier(expr)) { + return expr.text; + } + else if (ts.isPropertyAccessExpression(expr)) { + var left = getCalledExpressionName(expr.expression); + var right = expr.name.text; + return left === undefined ? right : left + "." + right; + } + else { + return undefined; + } + } + function isFunctionOrClassExpression(node) { + switch (node.kind) { + case 197 /* ArrowFunction */: + case 196 /* FunctionExpression */: + case 209 /* ClassExpression */: + return true; + default: + return false; + } + } + })(NavigationBar = ts.NavigationBar || (ts.NavigationBar = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var OrganizeImports; + (function (OrganizeImports) { + /** + * Organize imports by: + * 1) Removing unused imports + * 2) Coalescing imports from the same module + * 3) Sorting imports + */ + function organizeImports(sourceFile, formatContext, host, program, _preferences) { + var changeTracker = ts.textChanges.ChangeTracker.fromContext({ host: host, formatContext: formatContext }); + var coalesceAndOrganizeImports = function (importGroup) { return coalesceImports(removeUnusedImports(importGroup, sourceFile, program)); }; + // All of the old ImportDeclarations in the file, in syntactic order. + var topLevelImportDecls = sourceFile.statements.filter(ts.isImportDeclaration); + organizeImportsWorker(topLevelImportDecls, coalesceAndOrganizeImports); + // All of the old ExportDeclarations in the file, in syntactic order. + var topLevelExportDecls = sourceFile.statements.filter(ts.isExportDeclaration); + organizeImportsWorker(topLevelExportDecls, coalesceExports); + for (var _i = 0, _a = sourceFile.statements.filter(ts.isAmbientModule); _i < _a.length; _i++) { + var ambientModule = _a[_i]; + var ambientModuleBody = getModuleBlock(ambientModule); // TODO: GH#18217 + var ambientModuleImportDecls = ambientModuleBody.statements.filter(ts.isImportDeclaration); + organizeImportsWorker(ambientModuleImportDecls, coalesceAndOrganizeImports); + var ambientModuleExportDecls = ambientModuleBody.statements.filter(ts.isExportDeclaration); + organizeImportsWorker(ambientModuleExportDecls, coalesceExports); + } + return changeTracker.getChanges(); + function organizeImportsWorker(oldImportDecls, coalesce) { + if (ts.length(oldImportDecls) === 0) { + return; + } + // Special case: normally, we'd expect leading and trailing trivia to follow each import + // around as it's sorted. However, we do not want this to happen for leading trivia + // on the first import because it is probably the header comment for the file. + // Consider: we could do a more careful check that this trivia is actually a header, + // but the consequences of being wrong are very minor. + ts.suppressLeadingTrivia(oldImportDecls[0]); + var oldImportGroups = ts.group(oldImportDecls, function (importDecl) { return getExternalModuleName(importDecl.moduleSpecifier); }); + var sortedImportGroups = ts.stableSort(oldImportGroups, function (group1, group2) { return compareModuleSpecifiers(group1[0].moduleSpecifier, group2[0].moduleSpecifier); }); + var newImportDecls = ts.flatMap(sortedImportGroups, function (importGroup) { + return getExternalModuleName(importGroup[0].moduleSpecifier) + ? coalesce(importGroup) + : importGroup; + }); + // Delete or replace the first import. + if (newImportDecls.length === 0) { + changeTracker.delete(sourceFile, oldImportDecls[0]); + } + else { + // Note: Delete the surrounding trivia because it will have been retained in newImportDecls. + changeTracker.replaceNodeWithNodes(sourceFile, oldImportDecls[0], newImportDecls, { + useNonAdjustedStartPosition: true, + useNonAdjustedEndPosition: false, + suffix: ts.getNewLineOrDefaultFromHost(host, formatContext.options), + }); + } + // Delete any subsequent imports. + for (var i = 1; i < oldImportDecls.length; i++) { + changeTracker.delete(sourceFile, oldImportDecls[i]); + } + } + } + OrganizeImports.organizeImports = organizeImports; + function getModuleBlock(moduleDecl) { + var body = moduleDecl.body; + return body && !ts.isIdentifier(body) ? (ts.isModuleBlock(body) ? body : getModuleBlock(body)) : undefined; + } + function removeUnusedImports(oldImports, sourceFile, program) { + var typeChecker = program.getTypeChecker(); + var jsxNamespace = typeChecker.getJsxNamespace(); + var jsxElementsPresent = !!(sourceFile.transformFlags & 4 /* ContainsJsx */); + var usedImports = []; + for (var _i = 0, oldImports_1 = oldImports; _i < oldImports_1.length; _i++) { + var importDecl = oldImports_1[_i]; + var importClause = importDecl.importClause; + if (!importClause) { + // Imports without import clauses are assumed to be included for their side effects and are not removed. + usedImports.push(importDecl); + continue; + } + var name = importClause.name, namedBindings = importClause.namedBindings; + // Default import + if (name && !isDeclarationUsed(name)) { + name = undefined; + } + if (namedBindings) { + if (ts.isNamespaceImport(namedBindings)) { + // Namespace import + if (!isDeclarationUsed(namedBindings.name)) { + namedBindings = undefined; + } + } + else { + // List of named imports + var newElements = namedBindings.elements.filter(function (e) { return isDeclarationUsed(e.name); }); + if (newElements.length < namedBindings.elements.length) { + namedBindings = newElements.length + ? ts.updateNamedImports(namedBindings, newElements) + : undefined; + } + } + } + if (name || namedBindings) { + usedImports.push(updateImportDeclarationAndClause(importDecl, name, namedBindings)); + } + } + return usedImports; + function isDeclarationUsed(identifier) { + // The JSX factory symbol is always used if JSX elements are present - even if they are not allowed. + return jsxElementsPresent && (identifier.text === jsxNamespace) || ts.FindAllReferences.Core.isSymbolReferencedInFile(identifier, typeChecker, sourceFile); + } + } + function getExternalModuleName(specifier) { + return specifier !== undefined && ts.isStringLiteralLike(specifier) + ? specifier.text + : undefined; + } + // Internal for testing + /** + * @param importGroup a list of ImportDeclarations, all with the same module name. + */ + function coalesceImports(importGroup) { + if (importGroup.length === 0) { + return importGroup; + } + var _a = getCategorizedImports(importGroup), importWithoutClause = _a.importWithoutClause, defaultImports = _a.defaultImports, namespaceImports = _a.namespaceImports, namedImports = _a.namedImports; + var coalescedImports = []; + if (importWithoutClause) { + coalescedImports.push(importWithoutClause); + } + // Normally, we don't combine default and namespace imports, but it would be silly to + // produce two import declarations in this special case. + if (defaultImports.length === 1 && namespaceImports.length === 1 && namedImports.length === 0) { + // Add the namespace import to the existing default ImportDeclaration. + var defaultImport = defaultImports[0]; + coalescedImports.push(updateImportDeclarationAndClause(defaultImport, defaultImport.importClause.name, namespaceImports[0].importClause.namedBindings)); // TODO: GH#18217 + return coalescedImports; + } + var sortedNamespaceImports = ts.stableSort(namespaceImports, function (i1, i2) { + return compareIdentifiers(i1.importClause.namedBindings.name, i2.importClause.namedBindings.name); + }); // TODO: GH#18217 + for (var _i = 0, sortedNamespaceImports_1 = sortedNamespaceImports; _i < sortedNamespaceImports_1.length; _i++) { + var namespaceImport = sortedNamespaceImports_1[_i]; + // Drop the name, if any + coalescedImports.push(updateImportDeclarationAndClause(namespaceImport, /*name*/ undefined, namespaceImport.importClause.namedBindings)); // TODO: GH#18217 + } + if (defaultImports.length === 0 && namedImports.length === 0) { + return coalescedImports; + } + var newDefaultImport; + var newImportSpecifiers = []; + if (defaultImports.length === 1) { + newDefaultImport = defaultImports[0].importClause.name; + } + else { + for (var _b = 0, defaultImports_1 = defaultImports; _b < defaultImports_1.length; _b++) { + var defaultImport = defaultImports_1[_b]; + newImportSpecifiers.push(ts.createImportSpecifier(ts.createIdentifier("default"), defaultImport.importClause.name)); // TODO: GH#18217 + } + } + newImportSpecifiers.push.apply(newImportSpecifiers, ts.flatMap(namedImports, function (i) { return i.importClause.namedBindings.elements; })); // TODO: GH#18217 + var sortedImportSpecifiers = sortSpecifiers(newImportSpecifiers); + var importDecl = defaultImports.length > 0 + ? defaultImports[0] + : namedImports[0]; + var newNamedImports = sortedImportSpecifiers.length === 0 + ? newDefaultImport + ? undefined + : ts.createNamedImports(ts.emptyArray) + : namedImports.length === 0 + ? ts.createNamedImports(sortedImportSpecifiers) + : ts.updateNamedImports(namedImports[0].importClause.namedBindings, sortedImportSpecifiers); // TODO: GH#18217 + coalescedImports.push(updateImportDeclarationAndClause(importDecl, newDefaultImport, newNamedImports)); + return coalescedImports; + /* + * Returns entire import declarations because they may already have been rewritten and + * may lack parent pointers. The desired parts can easily be recovered based on the + * categorization. + * + * NB: There may be overlap between `defaultImports` and `namespaceImports`/`namedImports`. + */ + function getCategorizedImports(importGroup) { + var importWithoutClause; + var defaultImports = []; + var namespaceImports = []; + var namedImports = []; + for (var _i = 0, importGroup_1 = importGroup; _i < importGroup_1.length; _i++) { + var importDeclaration = importGroup_1[_i]; + if (importDeclaration.importClause === undefined) { + // Only the first such import is interesting - the others are redundant. + // Note: Unfortunately, we will lose trivia that was on this node. + importWithoutClause = importWithoutClause || importDeclaration; + continue; + } + var _a = importDeclaration.importClause, name = _a.name, namedBindings = _a.namedBindings; + if (name) { + defaultImports.push(importDeclaration); + } + if (namedBindings) { + if (ts.isNamespaceImport(namedBindings)) { + namespaceImports.push(importDeclaration); + } + else { + namedImports.push(importDeclaration); + } + } + } + return { + importWithoutClause: importWithoutClause, + defaultImports: defaultImports, + namespaceImports: namespaceImports, + namedImports: namedImports, + }; + } + } + OrganizeImports.coalesceImports = coalesceImports; + // Internal for testing + /** + * @param exportGroup a list of ExportDeclarations, all with the same module name. + */ + function coalesceExports(exportGroup) { + if (exportGroup.length === 0) { + return exportGroup; + } + var _a = getCategorizedExports(exportGroup), exportWithoutClause = _a.exportWithoutClause, namedExports = _a.namedExports; + var coalescedExports = []; + if (exportWithoutClause) { + coalescedExports.push(exportWithoutClause); + } + if (namedExports.length === 0) { + return coalescedExports; + } + var newExportSpecifiers = []; + newExportSpecifiers.push.apply(newExportSpecifiers, ts.flatMap(namedExports, function (i) { return (i.exportClause).elements; })); + var sortedExportSpecifiers = sortSpecifiers(newExportSpecifiers); + var exportDecl = namedExports[0]; + coalescedExports.push(ts.updateExportDeclaration(exportDecl, exportDecl.decorators, exportDecl.modifiers, ts.updateNamedExports(exportDecl.exportClause, sortedExportSpecifiers), exportDecl.moduleSpecifier)); + return coalescedExports; + /* + * Returns entire export declarations because they may already have been rewritten and + * may lack parent pointers. The desired parts can easily be recovered based on the + * categorization. + */ + function getCategorizedExports(exportGroup) { + var exportWithoutClause; + var namedExports = []; + for (var _i = 0, exportGroup_1 = exportGroup; _i < exportGroup_1.length; _i++) { + var exportDeclaration = exportGroup_1[_i]; + if (exportDeclaration.exportClause === undefined) { + // Only the first such export is interesting - the others are redundant. + // Note: Unfortunately, we will lose trivia that was on this node. + exportWithoutClause = exportWithoutClause || exportDeclaration; + } + else { + namedExports.push(exportDeclaration); + } + } + return { + exportWithoutClause: exportWithoutClause, + namedExports: namedExports, + }; + } + } + OrganizeImports.coalesceExports = coalesceExports; + function updateImportDeclarationAndClause(importDeclaration, name, namedBindings) { + return ts.updateImportDeclaration(importDeclaration, importDeclaration.decorators, importDeclaration.modifiers, ts.updateImportClause(importDeclaration.importClause, name, namedBindings), // TODO: GH#18217 + importDeclaration.moduleSpecifier); + } + function sortSpecifiers(specifiers) { + return ts.stableSort(specifiers, function (s1, s2) { + return compareIdentifiers(s1.propertyName || s1.name, s2.propertyName || s2.name) || + compareIdentifiers(s1.name, s2.name); + }); + } + /* internal */ // Exported for testing + function compareModuleSpecifiers(m1, m2) { + var name1 = getExternalModuleName(m1); + var name2 = getExternalModuleName(m2); + return ts.compareBooleans(name1 === undefined, name2 === undefined) || + ts.compareBooleans(ts.isExternalModuleNameRelative(name1), ts.isExternalModuleNameRelative(name2)) || + ts.compareStringsCaseInsensitive(name1, name2); + } + OrganizeImports.compareModuleSpecifiers = compareModuleSpecifiers; + function compareIdentifiers(s1, s2) { + return ts.compareStringsCaseInsensitive(s1.text, s2.text); + } + })(OrganizeImports = ts.OrganizeImports || (ts.OrganizeImports = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var OutliningElementsCollector; + (function (OutliningElementsCollector) { + function collectElements(sourceFile, cancellationToken) { + var res = []; + addNodeOutliningSpans(sourceFile, cancellationToken, res); + addRegionOutliningSpans(sourceFile, res); + return res.sort(function (span1, span2) { return span1.textSpan.start - span2.textSpan.start; }); + } + OutliningElementsCollector.collectElements = collectElements; + function addNodeOutliningSpans(sourceFile, cancellationToken, out) { + var depthRemaining = 40; + var current = 0; + var statements = sourceFile.statements; + var n = statements.length; + while (current < n) { + while (current < n && !ts.isAnyImportSyntax(statements[current])) { + visitNonImportNode(statements[current]); + current++; + } + if (current === n) + break; + var firstImport = current; + while (current < n && ts.isAnyImportSyntax(statements[current])) { + addOutliningForLeadingCommentsForNode(statements[current], sourceFile, cancellationToken, out); + current++; + } + var lastImport = current - 1; + if (lastImport !== firstImport) { + out.push(createOutliningSpanFromBounds(ts.findChildOfKind(statements[firstImport], 92 /* ImportKeyword */, sourceFile).getStart(sourceFile), statements[lastImport].getEnd(), "imports" /* Imports */)); + } + } + function visitNonImportNode(n) { + if (depthRemaining === 0) + return; + cancellationToken.throwIfCancellationRequested(); + if (ts.isDeclaration(n)) { + addOutliningForLeadingCommentsForNode(n, sourceFile, cancellationToken, out); + } + var span = getOutliningSpanForNode(n, sourceFile); + if (span) + out.push(span); + depthRemaining--; + if (ts.isIfStatement(n) && n.elseStatement && ts.isIfStatement(n.elseStatement)) { + // Consider an 'else if' to be on the same depth as the 'if'. + visitNonImportNode(n.expression); + visitNonImportNode(n.thenStatement); + depthRemaining++; + visitNonImportNode(n.elseStatement); + depthRemaining--; + } + else { + n.forEachChild(visitNonImportNode); + } + depthRemaining++; + } + } + function addRegionOutliningSpans(sourceFile, out) { + var regions = []; + var lineStarts = sourceFile.getLineStarts(); + for (var i = 0; i < lineStarts.length; i++) { + var currentLineStart = lineStarts[i]; + var lineEnd = i + 1 === lineStarts.length ? sourceFile.getEnd() : lineStarts[i + 1] - 1; + var lineText = sourceFile.text.substring(currentLineStart, lineEnd); + var result = isRegionDelimiter(lineText); + if (!result || ts.isInComment(sourceFile, currentLineStart)) { + continue; + } + if (!result[1]) { + var span = ts.createTextSpanFromBounds(sourceFile.text.indexOf("//", currentLineStart), lineEnd); + regions.push(createOutliningSpan(span, "region" /* Region */, span, /*autoCollapse*/ false, result[2] || "#region")); + } + else { + var region = regions.pop(); + if (region) { + region.textSpan.length = lineEnd - region.textSpan.start; + region.hintSpan.length = lineEnd - region.textSpan.start; + out.push(region); + } + } + } + } + var regionDelimiterRegExp = /^\s*\/\/\s*#(end)?region(?:\s+(.*))?(?:\r)?$/; + function isRegionDelimiter(lineText) { + return regionDelimiterRegExp.exec(lineText); + } + function addOutliningForLeadingCommentsForNode(n, sourceFile, cancellationToken, out) { + var comments = ts.getLeadingCommentRangesOfNode(n, sourceFile); + if (!comments) + return; + var firstSingleLineCommentStart = -1; + var lastSingleLineCommentEnd = -1; + var singleLineCommentCount = 0; + var sourceText = sourceFile.getFullText(); + for (var _i = 0, comments_2 = comments; _i < comments_2.length; _i++) { + var _a = comments_2[_i], kind = _a.kind, pos = _a.pos, end = _a.end; + cancellationToken.throwIfCancellationRequested(); + switch (kind) { + case 2 /* SingleLineCommentTrivia */: + // never fold region delimiters into single-line comment regions + var commentText = sourceText.slice(pos, end); + if (isRegionDelimiter(commentText)) { + combineAndAddMultipleSingleLineComments(); + singleLineCommentCount = 0; + break; + } + // For single line comments, combine consecutive ones (2 or more) into + // a single span from the start of the first till the end of the last + if (singleLineCommentCount === 0) { + firstSingleLineCommentStart = pos; + } + lastSingleLineCommentEnd = end; + singleLineCommentCount++; + break; + case 3 /* MultiLineCommentTrivia */: + combineAndAddMultipleSingleLineComments(); + out.push(createOutliningSpanFromBounds(pos, end, "comment" /* Comment */)); + singleLineCommentCount = 0; + break; + default: + ts.Debug.assertNever(kind); + } + } + combineAndAddMultipleSingleLineComments(); + function combineAndAddMultipleSingleLineComments() { + // Only outline spans of two or more consecutive single line comments + if (singleLineCommentCount > 1) { + out.push(createOutliningSpanFromBounds(firstSingleLineCommentStart, lastSingleLineCommentEnd, "comment" /* Comment */)); + } + } + } + function createOutliningSpanFromBounds(pos, end, kind) { + return createOutliningSpan(ts.createTextSpanFromBounds(pos, end), kind); + } + function getOutliningSpanForNode(n, sourceFile) { + switch (n.kind) { + case 218 /* Block */: + if (ts.isFunctionBlock(n)) { + return spanForNode(n.parent, /*autoCollapse*/ n.parent.kind !== 197 /* ArrowFunction */); + } + // Check if the block is standalone, or 'attached' to some parent statement. + // If the latter, we want to collapse the block, but consider its hint span + // to be the entire span of the parent. + switch (n.parent.kind) { + case 223 /* DoStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + case 225 /* ForStatement */: + case 222 /* IfStatement */: + case 224 /* WhileStatement */: + case 231 /* WithStatement */: + case 274 /* CatchClause */: + return spanForNode(n.parent); + case 235 /* TryStatement */: + // Could be the try-block, or the finally-block. + var tryStatement = n.parent; + if (tryStatement.tryBlock === n) { + return spanForNode(n.parent); + } + else if (tryStatement.finallyBlock === n) { + return spanForNode(ts.findChildOfKind(tryStatement, 88 /* FinallyKeyword */, sourceFile)); + } + // falls through + default: + // Block was a standalone block. In this case we want to only collapse + // the span of the block, independent of any parent span. + return createOutliningSpan(ts.createTextSpanFromNode(n, sourceFile), "code" /* Code */); + } + case 245 /* ModuleBlock */: + return spanForNode(n.parent); + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + case 243 /* EnumDeclaration */: + case 246 /* CaseBlock */: + return spanForNode(n); + case 188 /* ObjectLiteralExpression */: + return spanForObjectOrArrayLiteral(n); + case 187 /* ArrayLiteralExpression */: + return spanForObjectOrArrayLiteral(n, 22 /* OpenBracketToken */); + case 260 /* JsxElement */: + return spanForJSXElement(n); + case 261 /* JsxSelfClosingElement */: + case 262 /* JsxOpeningElement */: + return spanForJSXAttributes(n.attributes); + } + function spanForJSXElement(node) { + var textSpan = ts.createTextSpanFromBounds(node.openingElement.getStart(sourceFile), node.closingElement.getEnd()); + var tagName = node.openingElement.tagName.getText(sourceFile); + var bannerText = "<" + tagName + ">..."; + return createOutliningSpan(textSpan, "code" /* Code */, textSpan, /*autoCollapse*/ false, bannerText); + } + function spanForJSXAttributes(node) { + if (node.properties.length === 0) { + return undefined; + } + return createOutliningSpanFromBounds(node.getStart(sourceFile), node.getEnd(), "code" /* Code */); + } + function spanForObjectOrArrayLiteral(node, open) { + if (open === void 0) { open = 18 /* OpenBraceToken */; } + // If the block has no leading keywords and is inside an array literal, + // we only want to collapse the span of the block. + // Otherwise, the collapsed section will include the end of the previous line. + return spanForNode(node, /*autoCollapse*/ false, /*useFullStart*/ !ts.isArrayLiteralExpression(node.parent), open); + } + function spanForNode(hintSpanNode, autoCollapse, useFullStart, open) { + if (autoCollapse === void 0) { autoCollapse = false; } + if (useFullStart === void 0) { useFullStart = true; } + if (open === void 0) { open = 18 /* OpenBraceToken */; } + var openToken = ts.findChildOfKind(n, open, sourceFile); + var close = open === 18 /* OpenBraceToken */ ? 19 /* CloseBraceToken */ : 23 /* CloseBracketToken */; + var closeToken = ts.findChildOfKind(n, close, sourceFile); + if (!openToken || !closeToken) { + return undefined; + } + var textSpan = ts.createTextSpanFromBounds(useFullStart ? openToken.getFullStart() : openToken.getStart(sourceFile), closeToken.getEnd()); + return createOutliningSpan(textSpan, "code" /* Code */, ts.createTextSpanFromNode(hintSpanNode, sourceFile), autoCollapse); + } + } + function createOutliningSpan(textSpan, kind, hintSpan, autoCollapse, bannerText) { + if (hintSpan === void 0) { hintSpan = textSpan; } + if (autoCollapse === void 0) { autoCollapse = false; } + if (bannerText === void 0) { bannerText = "..."; } + return { textSpan: textSpan, kind: kind, hintSpan: hintSpan, bannerText: bannerText, autoCollapse: autoCollapse }; + } + })(OutliningElementsCollector = ts.OutliningElementsCollector || (ts.OutliningElementsCollector = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + // Note(cyrusn): this enum is ordered from strongest match type to weakest match type. + var PatternMatchKind; + (function (PatternMatchKind) { + PatternMatchKind[PatternMatchKind["exact"] = 0] = "exact"; + PatternMatchKind[PatternMatchKind["prefix"] = 1] = "prefix"; + PatternMatchKind[PatternMatchKind["substring"] = 2] = "substring"; + PatternMatchKind[PatternMatchKind["camelCase"] = 3] = "camelCase"; + })(PatternMatchKind = ts.PatternMatchKind || (ts.PatternMatchKind = {})); + function createPatternMatch(kind, isCaseSensitive) { + return { + kind: kind, + isCaseSensitive: isCaseSensitive + }; + } + function createPatternMatcher(pattern) { + // We'll often see the same candidate string many times when searching (For example, when + // we see the name of a module that is used everywhere, or the name of an overload). As + // such, we cache the information we compute about the candidate for the life of this + // pattern matcher so we don't have to compute it multiple times. + var stringToWordSpans = ts.createMap(); + var dotSeparatedSegments = pattern.trim().split(".").map(function (p) { return createSegment(p.trim()); }); + // A segment is considered invalid if we couldn't find any words in it. + if (dotSeparatedSegments.some(function (segment) { return !segment.subWordTextChunks.length; })) + return undefined; + return { + getFullMatch: function (containers, candidate) { return getFullMatch(containers, candidate, dotSeparatedSegments, stringToWordSpans); }, + getMatchForLastSegmentOfPattern: function (candidate) { return matchSegment(candidate, ts.last(dotSeparatedSegments), stringToWordSpans); }, + patternContainsDots: dotSeparatedSegments.length > 1 + }; + } + ts.createPatternMatcher = createPatternMatcher; + function getFullMatch(candidateContainers, candidate, dotSeparatedSegments, stringToWordSpans) { + // First, check that the last part of the dot separated pattern matches the name of the + // candidate. If not, then there's no point in proceeding and doing the more + // expensive work. + var candidateMatch = matchSegment(candidate, ts.last(dotSeparatedSegments), stringToWordSpans); + if (!candidateMatch) { + return undefined; + } + // -1 because the last part was checked against the name, and only the rest + // of the parts are checked against the container. + if (dotSeparatedSegments.length - 1 > candidateContainers.length) { + // There weren't enough container parts to match against the pattern parts. + // So this definitely doesn't match. + return undefined; + } + var bestMatch; + for (var i = dotSeparatedSegments.length - 2, j = candidateContainers.length - 1; i >= 0; i -= 1, j -= 1) { + bestMatch = betterMatch(bestMatch, matchSegment(candidateContainers[j], dotSeparatedSegments[i], stringToWordSpans)); + } + return bestMatch; + } + function getWordSpans(word, stringToWordSpans) { + var spans = stringToWordSpans.get(word); + if (!spans) { + stringToWordSpans.set(word, spans = breakIntoWordSpans(word)); + } + return spans; + } + function matchTextChunk(candidate, chunk, stringToWordSpans) { + var index = indexOfIgnoringCase(candidate, chunk.textLowerCase); + if (index === 0) { + // a) Check if the word is a prefix of the candidate, in a case insensitive or + // sensitive manner. If it does, return that there was an exact match if the word and candidate are the same length, else a prefix match. + return createPatternMatch(chunk.text.length === candidate.length ? PatternMatchKind.exact : PatternMatchKind.prefix, /*isCaseSensitive:*/ ts.startsWith(candidate, chunk.text)); + } + if (chunk.isLowerCase) { + if (index === -1) + return undefined; + // b) If the part is entirely lowercase, then check if it is contained anywhere in the + // candidate in a case insensitive manner. If so, return that there was a substring + // match. + // + // Note: We only have a substring match if the lowercase part is prefix match of some + // word part. That way we don't match something like 'Class' when the user types 'a'. + // But we would match 'FooAttribute' (since 'Attribute' starts with 'a'). + var wordSpans = getWordSpans(candidate, stringToWordSpans); + for (var _i = 0, wordSpans_1 = wordSpans; _i < wordSpans_1.length; _i++) { + var span = wordSpans_1[_i]; + if (partStartsWith(candidate, span, chunk.text, /*ignoreCase:*/ true)) { + return createPatternMatch(PatternMatchKind.substring, /*isCaseSensitive:*/ partStartsWith(candidate, span, chunk.text, /*ignoreCase:*/ false)); + } + } + // c) Is the pattern a substring of the candidate starting on one of the candidate's word boundaries? + // We could check every character boundary start of the candidate for the pattern. However, that's + // an m * n operation in the wost case. Instead, find the first instance of the pattern + // substring, and see if it starts on a capital letter. It seems unlikely that the user will try to + // filter the list based on a substring that starts on a capital letter and also with a lowercase one. + // (Pattern: fogbar, Candidate: quuxfogbarFogBar). + if (chunk.text.length < candidate.length && isUpperCaseLetter(candidate.charCodeAt(index))) { + return createPatternMatch(PatternMatchKind.substring, /*isCaseSensitive:*/ false); + } + } + else { + // d) If the part was not entirely lowercase, then check if it is contained in the + // candidate in a case *sensitive* manner. If so, return that there was a substring + // match. + if (candidate.indexOf(chunk.text) > 0) { + return createPatternMatch(PatternMatchKind.substring, /*isCaseSensitive:*/ true); + } + // e) If the part was not entirely lowercase, then attempt a camel cased match as well. + if (chunk.characterSpans.length > 0) { + var candidateParts = getWordSpans(candidate, stringToWordSpans); + var isCaseSensitive = tryCamelCaseMatch(candidate, candidateParts, chunk, /*ignoreCase:*/ false) ? true + : tryCamelCaseMatch(candidate, candidateParts, chunk, /*ignoreCase:*/ true) ? false : undefined; + if (isCaseSensitive !== undefined) { + return createPatternMatch(PatternMatchKind.camelCase, isCaseSensitive); + } + } + } + } + function matchSegment(candidate, segment, stringToWordSpans) { + // First check if the segment matches as is. This is also useful if the segment contains + // characters we would normally strip when splitting into parts that we also may want to + // match in the candidate. For example if the segment is "@int" and the candidate is + // "@int", then that will show up as an exact match here. + // + // Note: if the segment contains a space or an asterisk then we must assume that it's a + // multi-word segment. + if (every(segment.totalTextChunk.text, function (ch) { return ch !== 32 /* space */ && ch !== 42 /* asterisk */; })) { + var match = matchTextChunk(candidate, segment.totalTextChunk, stringToWordSpans); + if (match) + return match; + } + // The logic for pattern matching is now as follows: + // + // 1) Break the segment passed in into words. Breaking is rather simple and a + // good way to think about it that if gives you all the individual alphanumeric words + // of the pattern. + // + // 2) For each word try to match the word against the candidate value. + // + // 3) Matching is as follows: + // + // a) Check if the word is a prefix of the candidate, in a case insensitive or + // sensitive manner. If it does, return that there was an exact match if the word and candidate are the same length, else a prefix match. + // + // If the word is entirely lowercase: + // b) Then check if it is contained anywhere in the + // candidate in a case insensitive manner. If so, return that there was a substring + // match. + // + // Note: We only have a substring match if the lowercase part is prefix match of + // some word part. That way we don't match something like 'Class' when the user + // types 'a'. But we would match 'FooAttribute' (since 'Attribute' starts with + // 'a'). + // + // c) The word is all lower case. Is it a case insensitive substring of the candidate starting + // on a part boundary of the candidate? + // + // Else: + // d) If the word was not entirely lowercase, then check if it is contained in the + // candidate in a case *sensitive* manner. If so, return that there was a substring + // match. + // + // e) If the word was not entirely lowercase, then attempt a camel cased match as + // well. + // + // Only if all words have some sort of match is the pattern considered matched. + var subWordTextChunks = segment.subWordTextChunks; + var bestMatch; + for (var _i = 0, subWordTextChunks_1 = subWordTextChunks; _i < subWordTextChunks_1.length; _i++) { + var subWordTextChunk = subWordTextChunks_1[_i]; + bestMatch = betterMatch(bestMatch, matchTextChunk(candidate, subWordTextChunk, stringToWordSpans)); + } + return bestMatch; + } + function betterMatch(a, b) { + return ts.min(a, b, compareMatches); + } + function compareMatches(a, b) { + return a === undefined ? 1 /* GreaterThan */ : b === undefined ? -1 /* LessThan */ + : ts.compareValues(a.kind, b.kind) || ts.compareBooleans(!a.isCaseSensitive, !b.isCaseSensitive); + } + function partStartsWith(candidate, candidateSpan, pattern, ignoreCase, patternSpan) { + if (patternSpan === void 0) { patternSpan = { start: 0, length: pattern.length }; } + return patternSpan.length <= candidateSpan.length // If pattern part is longer than the candidate part there can never be a match. + && everyInRange(0, patternSpan.length, function (i) { return equalChars(pattern.charCodeAt(patternSpan.start + i), candidate.charCodeAt(candidateSpan.start + i), ignoreCase); }); + } + function equalChars(ch1, ch2, ignoreCase) { + return ignoreCase ? toLowerCase(ch1) === toLowerCase(ch2) : ch1 === ch2; + } + function tryCamelCaseMatch(candidate, candidateParts, chunk, ignoreCase) { + var chunkCharacterSpans = chunk.characterSpans; + // Note: we may have more pattern parts than candidate parts. This is because multiple + // pattern parts may match a candidate part. For example "SiUI" against "SimpleUI". + // We'll have 3 pattern parts Si/U/I against two candidate parts Simple/UI. However, U + // and I will both match in UI. + var currentCandidate = 0; + var currentChunkSpan = 0; + var firstMatch; + var contiguous; + while (true) { + // Let's consider our termination cases + if (currentChunkSpan === chunkCharacterSpans.length) { + return true; + } + else if (currentCandidate === candidateParts.length) { + // No match, since we still have more of the pattern to hit + return false; + } + var candidatePart = candidateParts[currentCandidate]; + var gotOneMatchThisCandidate = false; + // Consider the case of matching SiUI against SimpleUIElement. The candidate parts + // will be Simple/UI/Element, and the pattern parts will be Si/U/I. We'll match 'Si' + // against 'Simple' first. Then we'll match 'U' against 'UI'. However, we want to + // still keep matching pattern parts against that candidate part. + for (; currentChunkSpan < chunkCharacterSpans.length; currentChunkSpan++) { + var chunkCharacterSpan = chunkCharacterSpans[currentChunkSpan]; + if (gotOneMatchThisCandidate) { + // We've already gotten one pattern part match in this candidate. We will + // only continue trying to consumer pattern parts if the last part and this + // part are both upper case. + if (!isUpperCaseLetter(chunk.text.charCodeAt(chunkCharacterSpans[currentChunkSpan - 1].start)) || + !isUpperCaseLetter(chunk.text.charCodeAt(chunkCharacterSpans[currentChunkSpan].start))) { + break; + } + } + if (!partStartsWith(candidate, candidatePart, chunk.text, ignoreCase, chunkCharacterSpan)) { + break; + } + gotOneMatchThisCandidate = true; + firstMatch = firstMatch === undefined ? currentCandidate : firstMatch; + // If we were contiguous, then keep that value. If we weren't, then keep that + // value. If we don't know, then set the value to 'true' as an initial match is + // obviously contiguous. + contiguous = contiguous === undefined ? true : contiguous; + candidatePart = ts.createTextSpan(candidatePart.start + chunkCharacterSpan.length, candidatePart.length - chunkCharacterSpan.length); + } + // Check if we matched anything at all. If we didn't, then we need to unset the + // contiguous bit if we currently had it set. + // If we haven't set the bit yet, then that means we haven't matched anything so + // far, and we don't want to change that. + if (!gotOneMatchThisCandidate && contiguous !== undefined) { + contiguous = false; + } + // Move onto the next candidate. + currentCandidate++; + } + } + function createSegment(text) { + return { + totalTextChunk: createTextChunk(text), + subWordTextChunks: breakPatternIntoTextChunks(text) + }; + } + function isUpperCaseLetter(ch) { + // Fast check for the ascii range. + if (ch >= 65 /* A */ && ch <= 90 /* Z */) { + return true; + } + if (ch < 127 /* maxAsciiCharacter */ || !ts.isUnicodeIdentifierStart(ch, 6 /* Latest */)) { + return false; + } + // TODO: find a way to determine this for any unicode characters in a + // non-allocating manner. + var str = String.fromCharCode(ch); + return str === str.toUpperCase(); + } + function isLowerCaseLetter(ch) { + // Fast check for the ascii range. + if (ch >= 97 /* a */ && ch <= 122 /* z */) { + return true; + } + if (ch < 127 /* maxAsciiCharacter */ || !ts.isUnicodeIdentifierStart(ch, 6 /* Latest */)) { + return false; + } + // TODO: find a way to determine this for any unicode characters in a + // non-allocating manner. + var str = String.fromCharCode(ch); + return str === str.toLowerCase(); + } + // Assumes 'value' is already lowercase. + function indexOfIgnoringCase(str, value) { + var n = str.length - value.length; + var _loop_14 = function (start) { + if (every(value, function (valueChar, i) { return toLowerCase(str.charCodeAt(i + start)) === valueChar; })) { + return { value: start }; + } + }; + for (var start = 0; start <= n; start++) { + var state_3 = _loop_14(start); + if (typeof state_3 === "object") + return state_3.value; + } + return -1; + } + function toLowerCase(ch) { + // Fast convert for the ascii range. + if (ch >= 65 /* A */ && ch <= 90 /* Z */) { + return 97 /* a */ + (ch - 65 /* A */); + } + if (ch < 127 /* maxAsciiCharacter */) { + return ch; + } + // TODO: find a way to compute this for any unicode characters in a + // non-allocating manner. + return String.fromCharCode(ch).toLowerCase().charCodeAt(0); + } + function isDigit(ch) { + // TODO(cyrusn): Find a way to support this for unicode digits. + return ch >= 48 /* _0 */ && ch <= 57 /* _9 */; + } + function isWordChar(ch) { + return isUpperCaseLetter(ch) || isLowerCaseLetter(ch) || isDigit(ch) || ch === 95 /* _ */ || ch === 36 /* $ */; + } + function breakPatternIntoTextChunks(pattern) { + var result = []; + var wordStart = 0; + var wordLength = 0; + for (var i = 0; i < pattern.length; i++) { + var ch = pattern.charCodeAt(i); + if (isWordChar(ch)) { + if (wordLength === 0) { + wordStart = i; + } + wordLength++; + } + else { + if (wordLength > 0) { + result.push(createTextChunk(pattern.substr(wordStart, wordLength))); + wordLength = 0; + } + } + } + if (wordLength > 0) { + result.push(createTextChunk(pattern.substr(wordStart, wordLength))); + } + return result; + } + function createTextChunk(text) { + var textLowerCase = text.toLowerCase(); + return { + text: text, + textLowerCase: textLowerCase, + isLowerCase: text === textLowerCase, + characterSpans: breakIntoCharacterSpans(text) + }; + } + function breakIntoCharacterSpans(identifier) { + return breakIntoSpans(identifier, /*word:*/ false); + } + ts.breakIntoCharacterSpans = breakIntoCharacterSpans; + function breakIntoWordSpans(identifier) { + return breakIntoSpans(identifier, /*word:*/ true); + } + ts.breakIntoWordSpans = breakIntoWordSpans; + function breakIntoSpans(identifier, word) { + var result = []; + var wordStart = 0; + for (var i = 1; i < identifier.length; i++) { + var lastIsDigit = isDigit(identifier.charCodeAt(i - 1)); + var currentIsDigit = isDigit(identifier.charCodeAt(i)); + var hasTransitionFromLowerToUpper = transitionFromLowerToUpper(identifier, word, i); + var hasTransitionFromUpperToLower = word && transitionFromUpperToLower(identifier, i, wordStart); + if (charIsPunctuation(identifier.charCodeAt(i - 1)) || + charIsPunctuation(identifier.charCodeAt(i)) || + lastIsDigit !== currentIsDigit || + hasTransitionFromLowerToUpper || + hasTransitionFromUpperToLower) { + if (!isAllPunctuation(identifier, wordStart, i)) { + result.push(ts.createTextSpan(wordStart, i - wordStart)); + } + wordStart = i; + } + } + if (!isAllPunctuation(identifier, wordStart, identifier.length)) { + result.push(ts.createTextSpan(wordStart, identifier.length - wordStart)); + } + return result; + } + function charIsPunctuation(ch) { + switch (ch) { + case 33 /* exclamation */: + case 34 /* doubleQuote */: + case 35 /* hash */: + case 37 /* percent */: + case 38 /* ampersand */: + case 39 /* singleQuote */: + case 40 /* openParen */: + case 41 /* closeParen */: + case 42 /* asterisk */: + case 44 /* comma */: + case 45 /* minus */: + case 46 /* dot */: + case 47 /* slash */: + case 58 /* colon */: + case 59 /* semicolon */: + case 63 /* question */: + case 64 /* at */: + case 91 /* openBracket */: + case 92 /* backslash */: + case 93 /* closeBracket */: + case 95 /* _ */: + case 123 /* openBrace */: + case 125 /* closeBrace */: + return true; + } + return false; + } + function isAllPunctuation(identifier, start, end) { + return every(identifier, function (ch) { return charIsPunctuation(ch) && ch !== 95 /* _ */; }, start, end); + } + function transitionFromUpperToLower(identifier, index, wordStart) { + // Cases this supports: + // 1) IDisposable -> I, Disposable + // 2) UIElement -> UI, Element + // 3) HTMLDocument -> HTML, Document + // + // etc. + // We have a transition from an upper to a lower letter here. But we only + // want to break if all the letters that preceded are uppercase. i.e. if we + // have "Foo" we don't want to break that into "F, oo". But if we have + // "IFoo" or "UIFoo", then we want to break that into "I, Foo" and "UI, + // Foo". i.e. the last uppercase letter belongs to the lowercase letters + // that follows. Note: this will make the following not split properly: + // "HELLOthere". However, these sorts of names do not show up in .Net + // programs. + return index !== wordStart + && index + 1 < identifier.length + && isUpperCaseLetter(identifier.charCodeAt(index)) + && isLowerCaseLetter(identifier.charCodeAt(index + 1)) + && every(identifier, isUpperCaseLetter, wordStart, index); + } + function transitionFromLowerToUpper(identifier, word, index) { + var lastIsUpper = isUpperCaseLetter(identifier.charCodeAt(index - 1)); + var currentIsUpper = isUpperCaseLetter(identifier.charCodeAt(index)); + // See if the casing indicates we're starting a new word. Note: if we're breaking on + // words, then just seeing an upper case character isn't enough. Instead, it has to + // be uppercase and the previous character can't be uppercase. + // + // For example, breaking "AddMetadata" on words would make: Add Metadata + // + // on characters would be: A dd M etadata + // + // Break "AM" on words would be: AM + // + // on characters would be: A M + // + // We break the search string on characters. But we break the symbol name on words. + return currentIsUpper && (!word || !lastIsUpper); + } + function everyInRange(start, end, pred) { + for (var i = start; i < end; i++) { + if (!pred(i)) { + return false; + } + } + return true; + } + function every(s, pred, start, end) { + if (start === void 0) { start = 0; } + if (end === void 0) { end = s.length; } + return everyInRange(start, end, function (i) { return pred(s.charCodeAt(i), i); }); + } +})(ts || (ts = {})); +var ts; +(function (ts) { + function preProcessFile(sourceText, readImportFiles, detectJavaScriptImports) { + if (readImportFiles === void 0) { readImportFiles = true; } + if (detectJavaScriptImports === void 0) { detectJavaScriptImports = false; } + var pragmaContext = { + languageVersion: 1 /* ES5 */, + pragmas: undefined, + checkJsDirective: undefined, + referencedFiles: [], + typeReferenceDirectives: [], + libReferenceDirectives: [], + amdDependencies: [], + hasNoDefaultLib: undefined, + moduleName: undefined + }; + var importedFiles = []; + var ambientExternalModules; + var lastToken; + var currentToken; + var braceNesting = 0; + // assume that text represent an external module if it contains at least one top level import/export + // ambient modules that are found inside external modules are interpreted as module augmentations + var externalModule = false; + function nextToken() { + lastToken = currentToken; + currentToken = ts.scanner.scan(); + if (currentToken === 18 /* OpenBraceToken */) { + braceNesting++; + } + else if (currentToken === 19 /* CloseBraceToken */) { + braceNesting--; + } + return currentToken; + } + function getFileReference() { + var fileName = ts.scanner.getTokenValue(); + var pos = ts.scanner.getTokenPos(); + return { fileName: fileName, pos: pos, end: pos + fileName.length }; + } + function recordAmbientExternalModule() { + if (!ambientExternalModules) { + ambientExternalModules = []; + } + ambientExternalModules.push({ ref: getFileReference(), depth: braceNesting }); + } + function recordModuleName() { + importedFiles.push(getFileReference()); + markAsExternalModuleIfTopLevel(); + } + function markAsExternalModuleIfTopLevel() { + if (braceNesting === 0) { + externalModule = true; + } + } + /** + * Returns true if at least one token was consumed from the stream + */ + function tryConsumeDeclare() { + var token = ts.scanner.getToken(); + if (token === 125 /* DeclareKeyword */) { + // declare module "mod" + token = nextToken(); + if (token === 130 /* ModuleKeyword */) { + token = nextToken(); + if (token === 10 /* StringLiteral */) { + recordAmbientExternalModule(); + } + } + return true; + } + return false; + } + /** + * Returns true if at least one token was consumed from the stream + */ + function tryConsumeImport() { + if (lastToken === 24 /* DotToken */) { + return false; + } + var token = ts.scanner.getToken(); + if (token === 92 /* ImportKeyword */) { + token = nextToken(); + if (token === 20 /* OpenParenToken */) { + token = nextToken(); + if (token === 10 /* StringLiteral */) { + // import("mod"); + recordModuleName(); + return true; + } + } + else if (token === 10 /* StringLiteral */) { + // import "mod"; + recordModuleName(); + return true; + } + else { + if (token === 72 /* Identifier */ || ts.isKeyword(token)) { + token = nextToken(); + if (token === 144 /* FromKeyword */) { + token = nextToken(); + if (token === 10 /* StringLiteral */) { + // import d from "mod"; + recordModuleName(); + return true; + } + } + else if (token === 59 /* EqualsToken */) { + if (tryConsumeRequireCall(/*skipCurrentToken*/ true)) { + return true; + } + } + else if (token === 27 /* CommaToken */) { + // consume comma and keep going + token = nextToken(); + } + else { + // unknown syntax + return true; + } + } + if (token === 18 /* OpenBraceToken */) { + token = nextToken(); + // consume "{ a as B, c, d as D}" clauses + // make sure that it stops on EOF + while (token !== 19 /* CloseBraceToken */ && token !== 1 /* EndOfFileToken */) { + token = nextToken(); + } + if (token === 19 /* CloseBraceToken */) { + token = nextToken(); + if (token === 144 /* FromKeyword */) { + token = nextToken(); + if (token === 10 /* StringLiteral */) { + // import {a as A} from "mod"; + // import d, {a, b as B} from "mod" + recordModuleName(); + } + } + } + } + else if (token === 40 /* AsteriskToken */) { + token = nextToken(); + if (token === 119 /* AsKeyword */) { + token = nextToken(); + if (token === 72 /* Identifier */ || ts.isKeyword(token)) { + token = nextToken(); + if (token === 144 /* FromKeyword */) { + token = nextToken(); + if (token === 10 /* StringLiteral */) { + // import * as NS from "mod" + // import d, * as NS from "mod" + recordModuleName(); + } + } + } + } + } + } + return true; + } + return false; + } + function tryConsumeExport() { + var token = ts.scanner.getToken(); + if (token === 85 /* ExportKeyword */) { + markAsExternalModuleIfTopLevel(); + token = nextToken(); + if (token === 18 /* OpenBraceToken */) { + token = nextToken(); + // consume "{ a as B, c, d as D}" clauses + // make sure it stops on EOF + while (token !== 19 /* CloseBraceToken */ && token !== 1 /* EndOfFileToken */) { + token = nextToken(); + } + if (token === 19 /* CloseBraceToken */) { + token = nextToken(); + if (token === 144 /* FromKeyword */) { + token = nextToken(); + if (token === 10 /* StringLiteral */) { + // export {a as A} from "mod"; + // export {a, b as B} from "mod" + recordModuleName(); + } + } + } + } + else if (token === 40 /* AsteriskToken */) { + token = nextToken(); + if (token === 144 /* FromKeyword */) { + token = nextToken(); + if (token === 10 /* StringLiteral */) { + // export * from "mod" + recordModuleName(); + } + } + } + else if (token === 92 /* ImportKeyword */) { + token = nextToken(); + if (token === 72 /* Identifier */ || ts.isKeyword(token)) { + token = nextToken(); + if (token === 59 /* EqualsToken */) { + if (tryConsumeRequireCall(/*skipCurrentToken*/ true)) { + return true; + } + } + } + } + return true; + } + return false; + } + function tryConsumeRequireCall(skipCurrentToken) { + var token = skipCurrentToken ? nextToken() : ts.scanner.getToken(); + if (token === 134 /* RequireKeyword */) { + token = nextToken(); + if (token === 20 /* OpenParenToken */) { + token = nextToken(); + if (token === 10 /* StringLiteral */) { + // require("mod"); + recordModuleName(); + } + } + return true; + } + return false; + } + function tryConsumeDefine() { + var token = ts.scanner.getToken(); + if (token === 72 /* Identifier */ && ts.scanner.getTokenValue() === "define") { + token = nextToken(); + if (token !== 20 /* OpenParenToken */) { + return true; + } + token = nextToken(); + if (token === 10 /* StringLiteral */) { + // looks like define ("modname", ... - skip string literal and comma + token = nextToken(); + if (token === 27 /* CommaToken */) { + token = nextToken(); + } + else { + // unexpected token + return true; + } + } + // should be start of dependency list + if (token !== 22 /* OpenBracketToken */) { + return true; + } + // skip open bracket + token = nextToken(); + // scan until ']' or EOF + while (token !== 23 /* CloseBracketToken */ && token !== 1 /* EndOfFileToken */) { + // record string literals as module names + if (token === 10 /* StringLiteral */) { + recordModuleName(); + } + token = nextToken(); + } + return true; + } + return false; + } + function processImports() { + ts.scanner.setText(sourceText); + nextToken(); + // Look for: + // import "mod"; + // import d from "mod" + // import {a as A } from "mod"; + // import * as NS from "mod" + // import d, {a, b as B} from "mod" + // import i = require("mod"); + // import("mod"); + // export * from "mod" + // export {a as b} from "mod" + // export import i = require("mod") + // (for JavaScript files) require("mod") + // Do not look for: + // AnySymbol.import("mod") + // AnySymbol.nested.import("mod") + while (true) { + if (ts.scanner.getToken() === 1 /* EndOfFileToken */) { + break; + } + // check if at least one of alternative have moved scanner forward + if (tryConsumeDeclare() || + tryConsumeImport() || + tryConsumeExport() || + (detectJavaScriptImports && (tryConsumeRequireCall(/*skipCurrentToken*/ false) || tryConsumeDefine()))) { + continue; + } + else { + nextToken(); + } + } + ts.scanner.setText(undefined); + } + if (readImportFiles) { + processImports(); + } + ts.processCommentPragmas(pragmaContext, sourceText); + ts.processPragmasIntoFields(pragmaContext, ts.noop); + if (externalModule) { + // for external modules module all nested ambient modules are augmentations + if (ambientExternalModules) { + // move all detected ambient modules to imported files since they need to be resolved + for (var _i = 0, ambientExternalModules_1 = ambientExternalModules; _i < ambientExternalModules_1.length; _i++) { + var decl = ambientExternalModules_1[_i]; + importedFiles.push(decl.ref); + } + } + return { referencedFiles: pragmaContext.referencedFiles, typeReferenceDirectives: pragmaContext.typeReferenceDirectives, libReferenceDirectives: pragmaContext.libReferenceDirectives, importedFiles: importedFiles, isLibFile: !!pragmaContext.hasNoDefaultLib, ambientExternalModules: undefined }; + } + else { + // for global scripts ambient modules still can have augmentations - look for ambient modules with depth > 0 + var ambientModuleNames = void 0; + if (ambientExternalModules) { + for (var _a = 0, ambientExternalModules_2 = ambientExternalModules; _a < ambientExternalModules_2.length; _a++) { + var decl = ambientExternalModules_2[_a]; + if (decl.depth === 0) { + if (!ambientModuleNames) { + ambientModuleNames = []; + } + ambientModuleNames.push(decl.ref.fileName); + } + else { + importedFiles.push(decl.ref); + } + } + } + return { referencedFiles: pragmaContext.referencedFiles, typeReferenceDirectives: pragmaContext.typeReferenceDirectives, libReferenceDirectives: pragmaContext.libReferenceDirectives, importedFiles: importedFiles, isLibFile: !!pragmaContext.hasNoDefaultLib, ambientExternalModules: ambientModuleNames }; + } + } + ts.preProcessFile = preProcessFile; +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var Rename; + (function (Rename) { + function getRenameInfo(program, sourceFile, position) { + var node = ts.getTouchingPropertyName(sourceFile, position); + var renameInfo = node && nodeIsEligibleForRename(node) + ? getRenameInfoForNode(node, program.getTypeChecker(), sourceFile, function (declaration) { return program.isSourceFileDefaultLibrary(declaration.getSourceFile()); }) + : undefined; + return renameInfo || getRenameInfoError(ts.Diagnostics.You_cannot_rename_this_element); + } + Rename.getRenameInfo = getRenameInfo; + function getRenameInfoForNode(node, typeChecker, sourceFile, isDefinedInLibraryFile) { + var symbol = typeChecker.getSymbolAtLocation(node); + if (!symbol) + return; + // Only allow a symbol to be renamed if it actually has at least one declaration. + var declarations = symbol.declarations; + if (!declarations || declarations.length === 0) + return; + // Disallow rename for elements that are defined in the standard TypeScript library. + if (declarations.some(isDefinedInLibraryFile)) { + return getRenameInfoError(ts.Diagnostics.You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library); + } + // Cannot rename `default` as in `import { default as foo } from "./someModule"; + if (ts.isIdentifier(node) && node.originalKeywordKind === 80 /* DefaultKeyword */ && symbol.parent.flags & 1536 /* Module */) { + return undefined; + } + if (ts.isStringLiteralLike(node) && ts.tryGetImportFromModuleSpecifier(node)) { + return getRenameInfoForModule(node, sourceFile, symbol); + } + var kind = ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, node); + var specifierName = (ts.isImportOrExportSpecifierName(node) || ts.isStringOrNumericLiteralLike(node) && node.parent.kind === 149 /* ComputedPropertyName */) + ? ts.stripQuotes(ts.getTextOfIdentifierOrLiteral(node)) + : undefined; + var displayName = specifierName || typeChecker.symbolToString(symbol); + var fullDisplayName = specifierName || typeChecker.getFullyQualifiedName(symbol); + return getRenameInfoSuccess(displayName, fullDisplayName, kind, ts.SymbolDisplay.getSymbolModifiers(symbol), node, sourceFile); + } + function getRenameInfoForModule(node, sourceFile, moduleSymbol) { + if (!ts.isExternalModuleNameRelative(node.text)) { + return getRenameInfoError(ts.Diagnostics.You_cannot_rename_a_module_via_a_global_import); + } + var moduleSourceFile = ts.find(moduleSymbol.declarations, ts.isSourceFile); + if (!moduleSourceFile) + return undefined; + var withoutIndex = node.text.endsWith("/index") || node.text.endsWith("/index.js") ? undefined : ts.tryRemoveSuffix(ts.removeFileExtension(moduleSourceFile.fileName), "/index"); + var name = withoutIndex === undefined ? moduleSourceFile.fileName : withoutIndex; + var kind = withoutIndex === undefined ? "module" /* moduleElement */ : "directory" /* directory */; + var indexAfterLastSlash = node.text.lastIndexOf("/") + 1; + // Span should only be the last component of the path. + 1 to account for the quote character. + var triggerSpan = ts.createTextSpan(node.getStart(sourceFile) + 1 + indexAfterLastSlash, node.text.length - indexAfterLastSlash); + return { + canRename: true, + fileToRename: name, + kind: kind, + displayName: name, + fullDisplayName: name, + kindModifiers: "" /* none */, + triggerSpan: triggerSpan, + }; + } + function getRenameInfoSuccess(displayName, fullDisplayName, kind, kindModifiers, node, sourceFile) { + return { + canRename: true, + fileToRename: undefined, + kind: kind, + displayName: displayName, + fullDisplayName: fullDisplayName, + kindModifiers: kindModifiers, + triggerSpan: createTriggerSpanForNode(node, sourceFile) + }; + } + function getRenameInfoError(diagnostic) { + return { canRename: false, localizedErrorMessage: ts.getLocaleSpecificMessage(diagnostic) }; + } + function createTriggerSpanForNode(node, sourceFile) { + var start = node.getStart(sourceFile); + var width = node.getWidth(sourceFile); + if (node.kind === 10 /* StringLiteral */) { + // Exclude the quotes + start += 1; + width -= 2; + } + return ts.createTextSpan(start, width); + } + function nodeIsEligibleForRename(node) { + switch (node.kind) { + case 72 /* Identifier */: + case 10 /* StringLiteral */: + case 100 /* ThisKeyword */: + return true; + case 8 /* NumericLiteral */: + return ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node); + default: + return false; + } + } + })(Rename = ts.Rename || (ts.Rename = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var SignatureHelp; + (function (SignatureHelp) { + var InvocationKind; + (function (InvocationKind) { + InvocationKind[InvocationKind["Call"] = 0] = "Call"; + InvocationKind[InvocationKind["TypeArgs"] = 1] = "TypeArgs"; + InvocationKind[InvocationKind["Contextual"] = 2] = "Contextual"; + })(InvocationKind || (InvocationKind = {})); + function getSignatureHelpItems(program, sourceFile, position, triggerReason, cancellationToken) { + var typeChecker = program.getTypeChecker(); + // Decide whether to show signature help + var startingToken = ts.findTokenOnLeftOfPosition(sourceFile, position); + if (!startingToken) { + // We are at the beginning of the file + return undefined; + } + // Only need to be careful if the user typed a character and signature help wasn't showing. + var onlyUseSyntacticOwners = !!triggerReason && triggerReason.kind === "characterTyped"; + // Bail out quickly in the middle of a string or comment, don't provide signature help unless the user explicitly requested it. + if (onlyUseSyntacticOwners && (ts.isInString(sourceFile, position, startingToken) || ts.isInComment(sourceFile, position))) { + return undefined; + } + var isManuallyInvoked = !!triggerReason && triggerReason.kind === "invoked"; + var argumentInfo = getContainingArgumentInfo(startingToken, position, sourceFile, typeChecker, isManuallyInvoked); + if (!argumentInfo) + return undefined; + cancellationToken.throwIfCancellationRequested(); + // Extra syntactic and semantic filtering of signature help + var candidateInfo = getCandidateOrTypeInfo(argumentInfo, typeChecker, sourceFile, startingToken, onlyUseSyntacticOwners); + cancellationToken.throwIfCancellationRequested(); + if (!candidateInfo) { + // We didn't have any sig help items produced by the TS compiler. If this is a JS + // file, then see if we can figure out anything better. + return ts.isSourceFileJS(sourceFile) ? createJSSignatureHelpItems(argumentInfo, program, cancellationToken) : undefined; + } + return typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { + return candidateInfo.kind === 0 /* Candidate */ + ? createSignatureHelpItems(candidateInfo.candidates, candidateInfo.resolvedSignature, argumentInfo, sourceFile, typeChecker) + : createTypeHelpItems(candidateInfo.symbol, argumentInfo, sourceFile, typeChecker); + }); + } + SignatureHelp.getSignatureHelpItems = getSignatureHelpItems; + var CandidateOrTypeKind; + (function (CandidateOrTypeKind) { + CandidateOrTypeKind[CandidateOrTypeKind["Candidate"] = 0] = "Candidate"; + CandidateOrTypeKind[CandidateOrTypeKind["Type"] = 1] = "Type"; + })(CandidateOrTypeKind || (CandidateOrTypeKind = {})); + function getCandidateOrTypeInfo(_a, checker, sourceFile, startingToken, onlyUseSyntacticOwners) { + var invocation = _a.invocation, argumentCount = _a.argumentCount; + switch (invocation.kind) { + case 0 /* Call */: { + if (onlyUseSyntacticOwners && !isSyntacticOwner(startingToken, invocation.node, sourceFile)) { + return undefined; + } + var candidates = []; + var resolvedSignature = checker.getResolvedSignatureForSignatureHelp(invocation.node, candidates, argumentCount); // TODO: GH#18217 + return candidates.length === 0 ? undefined : { kind: 0 /* Candidate */, candidates: candidates, resolvedSignature: resolvedSignature }; + } + case 1 /* TypeArgs */: { + var called = invocation.called; + if (onlyUseSyntacticOwners && !containsPrecedingToken(startingToken, sourceFile, ts.isIdentifier(called) ? called.parent : called)) { + return undefined; + } + var candidates = ts.getPossibleGenericSignatures(called, argumentCount, checker); + if (candidates.length !== 0) + return { kind: 0 /* Candidate */, candidates: candidates, resolvedSignature: ts.first(candidates) }; + var symbol = checker.getSymbolAtLocation(called); + return symbol && { kind: 1 /* Type */, symbol: symbol }; + } + case 2 /* Contextual */: + return { kind: 0 /* Candidate */, candidates: [invocation.signature], resolvedSignature: invocation.signature }; + default: + return ts.Debug.assertNever(invocation); + } + } + function isSyntacticOwner(startingToken, node, sourceFile) { + if (!ts.isCallOrNewExpression(node)) + return false; + var invocationChildren = node.getChildren(sourceFile); + switch (startingToken.kind) { + case 20 /* OpenParenToken */: + return ts.contains(invocationChildren, startingToken); + case 27 /* CommaToken */: { + var containingList = ts.findContainingList(startingToken); + return !!containingList && ts.contains(invocationChildren, containingList); + } + case 28 /* LessThanToken */: + return containsPrecedingToken(startingToken, sourceFile, node.expression); + default: + return false; + } + } + function createJSSignatureHelpItems(argumentInfo, program, cancellationToken) { + if (argumentInfo.invocation.kind === 2 /* Contextual */) + return undefined; + // See if we can find some symbol with the call expression name that has call signatures. + var expression = getExpressionFromInvocation(argumentInfo.invocation); + var name = ts.isIdentifier(expression) ? expression.text : ts.isPropertyAccessExpression(expression) ? expression.name.text : undefined; + var typeChecker = program.getTypeChecker(); + return name === undefined ? undefined : ts.firstDefined(program.getSourceFiles(), function (sourceFile) { + return ts.firstDefined(sourceFile.getNamedDeclarations().get(name), function (declaration) { + var type = declaration.symbol && typeChecker.getTypeOfSymbolAtLocation(declaration.symbol, declaration); + var callSignatures = type && type.getCallSignatures(); + if (callSignatures && callSignatures.length) { + return typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { return createSignatureHelpItems(callSignatures, callSignatures[0], argumentInfo, sourceFile, typeChecker); }); + } + }); + }); + } + function containsPrecedingToken(startingToken, sourceFile, container) { + var precedingToken = ts.Debug.assertDefined(ts.findPrecedingToken(startingToken.getFullStart(), sourceFile, startingToken.parent, /*excludeJsdoc*/ true)); + return ts.rangeContainsRange(container, precedingToken); + } + function getArgumentInfoForCompletions(node, position, sourceFile) { + var info = getImmediatelyContainingArgumentInfo(node, position, sourceFile); + return !info || info.isTypeParameterList || info.invocation.kind !== 0 /* Call */ ? undefined + : { invocation: info.invocation.node, argumentCount: info.argumentCount, argumentIndex: info.argumentIndex }; + } + SignatureHelp.getArgumentInfoForCompletions = getArgumentInfoForCompletions; + function getArgumentOrParameterListInfo(node, sourceFile) { + var info = getArgumentOrParameterListAndIndex(node, sourceFile); + if (!info) + return undefined; + var list = info.list, argumentIndex = info.argumentIndex; + var argumentCount = getArgumentCount(list); + if (argumentIndex !== 0) { + ts.Debug.assertLessThan(argumentIndex, argumentCount); + } + var argumentsSpan = getApplicableSpanForArguments(list, sourceFile); + return { list: list, argumentIndex: argumentIndex, argumentCount: argumentCount, argumentsSpan: argumentsSpan }; + } + function getArgumentOrParameterListAndIndex(node, sourceFile) { + if (node.kind === 28 /* LessThanToken */ || node.kind === 20 /* OpenParenToken */) { + // Find the list that starts right *after* the < or ( token. + // If the user has just opened a list, consider this item 0. + return { list: getChildListThatStartsWithOpenerToken(node.parent, node, sourceFile), argumentIndex: 0 }; + } + else { + // findListItemInfo can return undefined if we are not in parent's argument list + // or type argument list. This includes cases where the cursor is: + // - To the right of the closing parenthesis, non-substitution template, or template tail. + // - Between the type arguments and the arguments (greater than token) + // - On the target of the call (parent.func) + // - On the 'new' keyword in a 'new' expression + var list = ts.findContainingList(node); + return list && { list: list, argumentIndex: getArgumentIndex(list, node) }; + } + } + /** + * Returns relevant information for the argument list and the current argument if we are + * in the argument of an invocation; returns undefined otherwise. + */ + function getImmediatelyContainingArgumentInfo(node, position, sourceFile) { + var parent = node.parent; + if (ts.isCallOrNewExpression(parent)) { + var invocation = parent; + // There are 3 cases to handle: + // 1. The token introduces a list, and should begin a signature help session + // 2. The token is either not associated with a list, or ends a list, so the session should end + // 3. The token is buried inside a list, and should give signature help + // + // The following are examples of each: + // + // Case 1: + // foo<#T, U>(#a, b) -> The token introduces a list, and should begin a signature help session + // Case 2: + // fo#o#(a, b)# -> The token is either not associated with a list, or ends a list, so the session should end + // Case 3: + // foo(a#, #b#) -> The token is buried inside a list, and should give signature help + // Find out if 'node' is an argument, a type argument, or neither + var info = getArgumentOrParameterListInfo(node, sourceFile); + if (!info) + return undefined; + var list = info.list, argumentIndex = info.argumentIndex, argumentCount = info.argumentCount, argumentsSpan = info.argumentsSpan; + var isTypeParameterList = !!parent.typeArguments && parent.typeArguments.pos === list.pos; + return { isTypeParameterList: isTypeParameterList, invocation: { kind: 0 /* Call */, node: invocation }, argumentsSpan: argumentsSpan, argumentIndex: argumentIndex, argumentCount: argumentCount }; + } + else if (ts.isNoSubstitutionTemplateLiteral(node) && ts.isTaggedTemplateExpression(parent)) { + // Check if we're actually inside the template; + // otherwise we'll fall out and return undefined. + if (ts.isInsideTemplateLiteral(node, position, sourceFile)) { + return getArgumentListInfoForTemplate(parent, /*argumentIndex*/ 0, sourceFile); + } + return undefined; + } + else if (ts.isTemplateHead(node) && parent.parent.kind === 193 /* TaggedTemplateExpression */) { + var templateExpression = parent; + var tagExpression = templateExpression.parent; + ts.Debug.assert(templateExpression.kind === 206 /* TemplateExpression */); + var argumentIndex = ts.isInsideTemplateLiteral(node, position, sourceFile) ? 0 : 1; + return getArgumentListInfoForTemplate(tagExpression, argumentIndex, sourceFile); + } + else if (ts.isTemplateSpan(parent) && ts.isTaggedTemplateExpression(parent.parent.parent)) { + var templateSpan = parent; + var tagExpression = parent.parent.parent; + // If we're just after a template tail, don't show signature help. + if (ts.isTemplateTail(node) && !ts.isInsideTemplateLiteral(node, position, sourceFile)) { + return undefined; + } + var spanIndex = templateSpan.parent.templateSpans.indexOf(templateSpan); + var argumentIndex = getArgumentIndexForTemplatePiece(spanIndex, node, position, sourceFile); + return getArgumentListInfoForTemplate(tagExpression, argumentIndex, sourceFile); + } + else if (ts.isJsxOpeningLikeElement(parent)) { + // Provide a signature help for JSX opening element or JSX self-closing element. + // This is not guarantee that JSX tag-name is resolved into stateless function component. (that is done in "getSignatureHelpItems") + // i.e + // export function MainButton(props: ButtonProps, context: any): JSX.Element { ... } + // ' 'b'. So, in this case the arg count will be 2. However, there + // is a small subtlety. If you have "Foo(a,)", then the child list will just have + // 'a' ''. So, in the case where the last child is a comma, we increase the + // arg count by one to compensate. + // + // Note: this subtlety only applies to the last comma. If you had "Foo(a,," then + // we'll have: 'a' '' '' + // That will give us 2 non-commas. We then add one for the last comma, giving us an + // arg count of 3. + var listChildren = argumentsList.getChildren(); + var argumentCount = ts.countWhere(listChildren, function (arg) { return arg.kind !== 27 /* CommaToken */; }); + if (listChildren.length > 0 && ts.last(listChildren).kind === 27 /* CommaToken */) { + argumentCount++; + } + return argumentCount; + } + // spanIndex is either the index for a given template span. + // This does not give appropriate results for a NoSubstitutionTemplateLiteral + function getArgumentIndexForTemplatePiece(spanIndex, node, position, sourceFile) { + // Because the TemplateStringsArray is the first argument, we have to offset each substitution expression by 1. + // There are three cases we can encounter: + // 1. We are precisely in the template literal (argIndex = 0). + // 2. We are in or to the right of the substitution expression (argIndex = spanIndex + 1). + // 3. We are directly to the right of the template literal, but because we look for the token on the left, + // not enough to put us in the substitution expression; we should consider ourselves part of + // the *next* span's expression by offsetting the index (argIndex = (spanIndex + 1) + 1). + // + // tslint:disable no-double-space + // Example: f `# abcd $#{# 1 + 1# }# efghi ${ #"#hello"# } # ` + // ^ ^ ^ ^ ^ ^ ^ ^ ^ + // Case: 1 1 3 2 1 3 2 2 1 + // tslint:enable no-double-space + ts.Debug.assert(position >= node.getStart(), "Assumed 'position' could not occur before node."); + if (ts.isTemplateLiteralToken(node)) { + if (ts.isInsideTemplateLiteral(node, position, sourceFile)) { + return 0; + } + return spanIndex + 2; + } + return spanIndex + 1; + } + function getArgumentListInfoForTemplate(tagExpression, argumentIndex, sourceFile) { + // argumentCount is either 1 or (numSpans + 1) to account for the template strings array argument. + var argumentCount = ts.isNoSubstitutionTemplateLiteral(tagExpression.template) ? 1 : tagExpression.template.templateSpans.length + 1; + if (argumentIndex !== 0) { + ts.Debug.assertLessThan(argumentIndex, argumentCount); + } + return { + isTypeParameterList: false, + invocation: { kind: 0 /* Call */, node: tagExpression }, + argumentsSpan: getApplicableSpanForTaggedTemplate(tagExpression, sourceFile), + argumentIndex: argumentIndex, + argumentCount: argumentCount + }; + } + function getApplicableSpanForArguments(argumentsList, sourceFile) { + // We use full start and skip trivia on the end because we want to include trivia on + // both sides. For example, + // + // foo( /*comment */ a, b, c /*comment*/ ) + // | | + // + // The applicable span is from the first bar to the second bar (inclusive, + // but not including parentheses) + var applicableSpanStart = argumentsList.getFullStart(); + var applicableSpanEnd = ts.skipTrivia(sourceFile.text, argumentsList.getEnd(), /*stopAfterLineBreak*/ false); + return ts.createTextSpan(applicableSpanStart, applicableSpanEnd - applicableSpanStart); + } + function getApplicableSpanForTaggedTemplate(taggedTemplate, sourceFile) { + var template = taggedTemplate.template; + var applicableSpanStart = template.getStart(); + var applicableSpanEnd = template.getEnd(); + // We need to adjust the end position for the case where the template does not have a tail. + // Otherwise, we will not show signature help past the expression. + // For example, + // + // ` ${ 1 + 1 foo(10) + // | | + // This is because a Missing node has no width. However, what we actually want is to include trivia + // leading up to the next token in case the user is about to type in a TemplateMiddle or TemplateTail. + if (template.kind === 206 /* TemplateExpression */) { + var lastSpan = ts.last(template.templateSpans); + if (lastSpan.literal.getFullWidth() === 0) { + applicableSpanEnd = ts.skipTrivia(sourceFile.text, applicableSpanEnd, /*stopAfterLineBreak*/ false); + } + } + return ts.createTextSpan(applicableSpanStart, applicableSpanEnd - applicableSpanStart); + } + function getContainingArgumentInfo(node, position, sourceFile, checker, isManuallyInvoked) { + var _loop_15 = function (n) { + // If the node is not a subspan of its parent, this is a big problem. + // There have been crashes that might be caused by this violation. + ts.Debug.assert(ts.rangeContainsRange(n.parent, n), "Not a subspan", function () { return "Child: " + ts.Debug.showSyntaxKind(n) + ", parent: " + ts.Debug.showSyntaxKind(n.parent); }); + var argumentInfo = getImmediatelyContainingArgumentOrContextualParameterInfo(n, position, sourceFile, checker); + if (argumentInfo) { + return { value: argumentInfo }; + } + }; + for (var n = node; isManuallyInvoked || (!ts.isBlock(n) && !ts.isSourceFile(n)); n = n.parent) { + var state_4 = _loop_15(n); + if (typeof state_4 === "object") + return state_4.value; + } + return undefined; + } + function getChildListThatStartsWithOpenerToken(parent, openerToken, sourceFile) { + var children = parent.getChildren(sourceFile); + var indexOfOpenerToken = children.indexOf(openerToken); + ts.Debug.assert(indexOfOpenerToken >= 0 && children.length > indexOfOpenerToken + 1); + return children[indexOfOpenerToken + 1]; + } + function getExpressionFromInvocation(invocation) { + return invocation.kind === 0 /* Call */ ? ts.getInvokedExpression(invocation.node) : invocation.called; + } + function getEnclosingDeclarationFromInvocation(invocation) { + return invocation.kind === 0 /* Call */ ? invocation.node : invocation.kind === 1 /* TypeArgs */ ? invocation.called : invocation.node; + } + var signatureHelpNodeBuilderFlags = 8192 /* OmitParameterModifiers */ | 70221824 /* IgnoreErrors */ | 16384 /* UseAliasDefinedOutsideCurrentScope */; + function createSignatureHelpItems(candidates, resolvedSignature, _a, sourceFile, typeChecker) { + var isTypeParameterList = _a.isTypeParameterList, argumentCount = _a.argumentCount, applicableSpan = _a.argumentsSpan, invocation = _a.invocation, argumentIndex = _a.argumentIndex; + var enclosingDeclaration = getEnclosingDeclarationFromInvocation(invocation); + var callTargetSymbol = invocation.kind === 2 /* Contextual */ ? invocation.symbol : typeChecker.getSymbolAtLocation(getExpressionFromInvocation(invocation)); + var callTargetDisplayParts = callTargetSymbol ? ts.symbolToDisplayParts(typeChecker, callTargetSymbol, /*enclosingDeclaration*/ undefined, /*meaning*/ undefined) : ts.emptyArray; + var items = candidates.map(function (candidateSignature) { return getSignatureHelpItem(candidateSignature, callTargetDisplayParts, isTypeParameterList, typeChecker, enclosingDeclaration, sourceFile); }); + if (argumentIndex !== 0) { + ts.Debug.assertLessThan(argumentIndex, argumentCount); + } + var selectedItemIndex = candidates.indexOf(resolvedSignature); + ts.Debug.assert(selectedItemIndex !== -1); // If candidates is non-empty it should always include bestSignature. We check for an empty candidates before calling this function. + return { items: items, applicableSpan: applicableSpan, selectedItemIndex: selectedItemIndex, argumentIndex: argumentIndex, argumentCount: argumentCount }; + } + function createTypeHelpItems(symbol, _a, sourceFile, checker) { + var argumentCount = _a.argumentCount, applicableSpan = _a.argumentsSpan, invocation = _a.invocation, argumentIndex = _a.argumentIndex; + var typeParameters = checker.getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); + if (!typeParameters) + return undefined; + var items = [getTypeHelpItem(symbol, typeParameters, checker, getEnclosingDeclarationFromInvocation(invocation), sourceFile)]; + return { items: items, applicableSpan: applicableSpan, selectedItemIndex: 0, argumentIndex: argumentIndex, argumentCount: argumentCount }; + } + function getTypeHelpItem(symbol, typeParameters, checker, enclosingDeclaration, sourceFile) { + var typeSymbolDisplay = ts.symbolToDisplayParts(checker, symbol); + var printer = ts.createPrinter({ removeComments: true }); + var parameters = typeParameters.map(function (t) { return createSignatureHelpParameterForTypeParameter(t, checker, enclosingDeclaration, sourceFile, printer); }); + var documentation = symbol.getDocumentationComment(checker); + var tags = symbol.getJsDocTags(); + var prefixDisplayParts = typeSymbolDisplay.concat([ts.punctuationPart(28 /* LessThanToken */)]); + return { isVariadic: false, prefixDisplayParts: prefixDisplayParts, suffixDisplayParts: [ts.punctuationPart(30 /* GreaterThanToken */)], separatorDisplayParts: separatorDisplayParts, parameters: parameters, documentation: documentation, tags: tags }; + } + var separatorDisplayParts = [ts.punctuationPart(27 /* CommaToken */), ts.spacePart()]; + function getSignatureHelpItem(candidateSignature, callTargetDisplayParts, isTypeParameterList, checker, enclosingDeclaration, sourceFile) { + var _a = (isTypeParameterList ? itemInfoForTypeParameters : itemInfoForParameters)(candidateSignature, checker, enclosingDeclaration, sourceFile), isVariadic = _a.isVariadic, parameters = _a.parameters, prefix = _a.prefix, suffix = _a.suffix; + var prefixDisplayParts = callTargetDisplayParts.concat(prefix); + var suffixDisplayParts = suffix.concat(returnTypeToDisplayParts(candidateSignature, enclosingDeclaration, checker)); + var documentation = candidateSignature.getDocumentationComment(checker); + var tags = candidateSignature.getJsDocTags(); + return { isVariadic: isVariadic, prefixDisplayParts: prefixDisplayParts, suffixDisplayParts: suffixDisplayParts, separatorDisplayParts: separatorDisplayParts, parameters: parameters, documentation: documentation, tags: tags }; + } + function returnTypeToDisplayParts(candidateSignature, enclosingDeclaration, checker) { + return ts.mapToDisplayParts(function (writer) { + writer.writePunctuation(":"); + writer.writeSpace(" "); + var predicate = checker.getTypePredicateOfSignature(candidateSignature); + if (predicate) { + checker.writeTypePredicate(predicate, enclosingDeclaration, /*flags*/ undefined, writer); + } + else { + checker.writeType(checker.getReturnTypeOfSignature(candidateSignature), enclosingDeclaration, /*flags*/ undefined, writer); + } + }); + } + function itemInfoForTypeParameters(candidateSignature, checker, enclosingDeclaration, sourceFile) { + var typeParameters = (candidateSignature.target || candidateSignature).typeParameters; + var printer = ts.createPrinter({ removeComments: true }); + var parameters = (typeParameters || ts.emptyArray).map(function (t) { return createSignatureHelpParameterForTypeParameter(t, checker, enclosingDeclaration, sourceFile, printer); }); + var parameterParts = ts.mapToDisplayParts(function (writer) { + var thisParameter = candidateSignature.thisParameter ? [checker.symbolToParameterDeclaration(candidateSignature.thisParameter, enclosingDeclaration, signatureHelpNodeBuilderFlags)] : []; + var params = ts.createNodeArray(thisParameter.concat(candidateSignature.parameters.map(function (param) { return checker.symbolToParameterDeclaration(param, enclosingDeclaration, signatureHelpNodeBuilderFlags); }))); + printer.writeList(2576 /* CallExpressionArguments */, params, sourceFile, writer); + }); + return { isVariadic: false, parameters: parameters, prefix: [ts.punctuationPart(28 /* LessThanToken */)], suffix: [ts.punctuationPart(30 /* GreaterThanToken */)].concat(parameterParts) }; + } + function itemInfoForParameters(candidateSignature, checker, enclosingDeclaration, sourceFile) { + var isVariadic = candidateSignature.hasRestParameter; + var printer = ts.createPrinter({ removeComments: true }); + var typeParameterParts = ts.mapToDisplayParts(function (writer) { + if (candidateSignature.typeParameters && candidateSignature.typeParameters.length) { + var args = ts.createNodeArray(candidateSignature.typeParameters.map(function (p) { return checker.typeParameterToDeclaration(p, enclosingDeclaration); })); + printer.writeList(53776 /* TypeParameters */, args, sourceFile, writer); + } + }); + var parameters = candidateSignature.parameters.map(function (p) { return createSignatureHelpParameterForParameter(p, checker, enclosingDeclaration, sourceFile, printer); }); + return { isVariadic: isVariadic, parameters: parameters, prefix: typeParameterParts.concat([ts.punctuationPart(20 /* OpenParenToken */)]), suffix: [ts.punctuationPart(21 /* CloseParenToken */)] }; + } + function createSignatureHelpParameterForParameter(parameter, checker, enclosingDeclaration, sourceFile, printer) { + var displayParts = ts.mapToDisplayParts(function (writer) { + var param = checker.symbolToParameterDeclaration(parameter, enclosingDeclaration, signatureHelpNodeBuilderFlags); + printer.writeNode(4 /* Unspecified */, param, sourceFile, writer); + }); + var isOptional = checker.isOptionalParameter(parameter.valueDeclaration); + return { name: parameter.name, documentation: parameter.getDocumentationComment(checker), displayParts: displayParts, isOptional: isOptional }; + } + function createSignatureHelpParameterForTypeParameter(typeParameter, checker, enclosingDeclaration, sourceFile, printer) { + var displayParts = ts.mapToDisplayParts(function (writer) { + var param = checker.typeParameterToDeclaration(typeParameter, enclosingDeclaration); + printer.writeNode(4 /* Unspecified */, param, sourceFile, writer); + }); + return { name: typeParameter.symbol.name, documentation: typeParameter.symbol.getDocumentationComment(checker), displayParts: displayParts, isOptional: false }; + } + })(SignatureHelp = ts.SignatureHelp || (ts.SignatureHelp = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var base64UrlRegExp = /^data:(?:application\/json(?:;charset=[uU][tT][fF]-8);base64,([A-Za-z0-9+\/=]+)$)?/; + function getSourceMapper(useCaseSensitiveFileNames, currentDirectory, log, host, getProgram) { + var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); + var sourcemappedFileCache; + return { tryGetSourcePosition: tryGetSourcePosition, tryGetGeneratedPosition: tryGetGeneratedPosition, toLineColumnOffset: toLineColumnOffset, clearCache: clearCache }; + function toPath(fileName) { + return ts.toPath(fileName, currentDirectory, getCanonicalFileName); + } + function scanForSourcemapURL(fileName) { + var mappedFile = sourcemappedFileCache.get(toPath(fileName)); + if (!mappedFile) { + return; + } + return ts.tryGetSourceMappingURL(mappedFile.text, ts.getLineStarts(mappedFile)); + } + function convertDocumentToSourceMapper(file, contents, mapFileName) { + var map = ts.tryParseRawSourceMap(contents); + if (!map || !map.sources || !map.file || !map.mappings) { + // obviously invalid map + return file.sourceMapper = ts.identitySourceMapConsumer; + } + var program = getProgram(); + return file.sourceMapper = ts.createDocumentPositionMapper({ + getSourceFileLike: function (s) { + // Lookup file in program, if provided + var file = program && program.getSourceFileByPath(s); + // file returned here could be .d.ts when asked for .ts file if projectReferences and module resolution created this source file + if (file === undefined || file.resolvedPath !== s) { + // Otherwise check the cache (which may hit disk) + return sourcemappedFileCache.get(s); + } + return file; + }, + getCanonicalFileName: getCanonicalFileName, + log: log, + }, map, mapFileName); + } + function getSourceMapper(fileName, file) { + if (!host.readFile || !host.fileExists) { + return file.sourceMapper = ts.identitySourceMapConsumer; + } + if (file.sourceMapper) { + return file.sourceMapper; + } + var mapFileName = scanForSourcemapURL(fileName); + if (mapFileName) { + var match = base64UrlRegExp.exec(mapFileName); + if (match) { + if (match[1]) { + var base64Object = match[1]; + return convertDocumentToSourceMapper(file, ts.base64decode(ts.sys, base64Object), fileName); + } + // Not a data URL we can parse, skip it + mapFileName = undefined; + } + } + var possibleMapLocations = []; + if (mapFileName) { + possibleMapLocations.push(mapFileName); + } + possibleMapLocations.push(fileName + ".map"); + for (var _i = 0, possibleMapLocations_1 = possibleMapLocations; _i < possibleMapLocations_1.length; _i++) { + var location = possibleMapLocations_1[_i]; + var mapPath = ts.toPath(location, ts.getDirectoryPath(fileName), getCanonicalFileName); + if (host.fileExists(mapPath)) { + return convertDocumentToSourceMapper(file, host.readFile(mapPath), mapPath); // TODO: GH#18217 + } + } + return file.sourceMapper = ts.identitySourceMapConsumer; + } + function tryGetSourcePosition(info) { + if (!ts.isDeclarationFileName(info.fileName)) + return undefined; + var file = getFile(info.fileName); + if (!file) + return undefined; + var newLoc = getSourceMapper(info.fileName, file).getSourcePosition(info); + return newLoc === info ? undefined : tryGetSourcePosition(newLoc) || newLoc; + } + function tryGetGeneratedPosition(info) { + var program = getProgram(); + var options = program.getCompilerOptions(); + var outPath = options.outFile || options.out; + var declarationPath = outPath ? + ts.removeFileExtension(outPath) + ".d.ts" /* Dts */ : + ts.getDeclarationEmitOutputFilePathWorker(info.fileName, program.getCompilerOptions(), currentDirectory, program.getCommonSourceDirectory(), getCanonicalFileName); + if (declarationPath === undefined) + return undefined; + var declarationFile = getFile(declarationPath); + if (!declarationFile) + return undefined; + var newLoc = getSourceMapper(declarationPath, declarationFile).getGeneratedPosition(info); + return newLoc === info ? undefined : newLoc; + } + function getFile(fileName) { + var path = toPath(fileName); + var file = getProgram().getSourceFileByPath(path); + if (file && file.resolvedPath === path) { + return file; + } + return sourcemappedFileCache.get(path); + } + function toLineColumnOffset(fileName, position) { + var file = getFile(fileName); // TODO: GH#18217 + return file.getLineAndCharacterOfPosition(position); + } + function clearCache() { + sourcemappedFileCache = createSourceFileLikeCache(host); + } + } + ts.getSourceMapper = getSourceMapper; + function createSourceFileLikeCache(host) { + var cached = ts.createMap(); + return { + get: function (path) { + if (cached.has(path)) { + return cached.get(path); + } + if (!host.fileExists || !host.readFile || !host.fileExists(path)) + return; + // And failing that, check the disk + var text = host.readFile(path); // TODO: GH#18217 + var file = { + text: text, + lineMap: undefined, + getLineAndCharacterOfPosition: function (pos) { + return ts.computeLineAndCharacterOfPosition(ts.getLineStarts(this), pos); + } + }; + cached.set(path, file); + return file; + } + }; + } +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + function computeSuggestionDiagnostics(sourceFile, program, cancellationToken) { + program.getSemanticDiagnostics(sourceFile, cancellationToken); + var diags = []; + var checker = program.getTypeChecker(); + if (sourceFile.commonJsModuleIndicator && + (ts.programContainsEs6Modules(program) || ts.compilerOptionsIndicateEs6Modules(program.getCompilerOptions())) && + containsTopLevelCommonjs(sourceFile)) { + diags.push(ts.createDiagnosticForNode(getErrorNodeFromCommonJsIndicator(sourceFile.commonJsModuleIndicator), ts.Diagnostics.File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module)); + } + var isJsFile = ts.isSourceFileJS(sourceFile); + check(sourceFile); + if (ts.getAllowSyntheticDefaultImports(program.getCompilerOptions())) { + for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { + var moduleSpecifier = _a[_i]; + var importNode = ts.importFromModuleSpecifier(moduleSpecifier); + var name = importNameForConvertToDefaultImport(importNode); + if (!name) + continue; + var module_2 = ts.getResolvedModule(sourceFile, moduleSpecifier.text); + var resolvedFile = module_2 && program.getSourceFile(module_2.resolvedFileName); + if (resolvedFile && resolvedFile.externalModuleIndicator && ts.isExportAssignment(resolvedFile.externalModuleIndicator) && resolvedFile.externalModuleIndicator.isExportEquals) { + diags.push(ts.createDiagnosticForNode(name, ts.Diagnostics.Import_may_be_converted_to_a_default_import)); + } + } + } + ts.addRange(diags, sourceFile.bindSuggestionDiagnostics); + ts.addRange(diags, program.getSuggestionDiagnostics(sourceFile, cancellationToken)); + return diags.sort(function (d1, d2) { return d1.start - d2.start; }); + function check(node) { + if (isJsFile) { + switch (node.kind) { + case 196 /* FunctionExpression */: + var decl = ts.getDeclarationOfExpando(node); + if (decl) { + var symbol_2 = decl.symbol; + if (symbol_2 && (symbol_2.exports && symbol_2.exports.size || symbol_2.members && symbol_2.members.size)) { + diags.push(ts.createDiagnosticForNode(ts.isVariableDeclaration(node.parent) ? node.parent.name : node, ts.Diagnostics.This_constructor_function_may_be_converted_to_a_class_declaration)); + break; + } + } + // falls through if no diagnostic was created + case 239 /* FunctionDeclaration */: + var symbol = node.symbol; + if (symbol.members && (symbol.members.size > 0)) { + diags.push(ts.createDiagnosticForNode(ts.isVariableDeclaration(node.parent) ? node.parent.name : node, ts.Diagnostics.This_constructor_function_may_be_converted_to_a_class_declaration)); + } + break; + } + } + else { + if (ts.isVariableStatement(node) && + node.parent === sourceFile && + node.declarationList.flags & 2 /* Const */ && + node.declarationList.declarations.length === 1) { + var init = node.declarationList.declarations[0].initializer; + if (init && ts.isRequireCall(init, /*checkArgumentIsStringLiteralLike*/ true)) { + diags.push(ts.createDiagnosticForNode(init, ts.Diagnostics.require_call_may_be_converted_to_an_import)); + } + } + if (ts.codefix.parameterShouldGetTypeFromJSDoc(node)) { + diags.push(ts.createDiagnosticForNode(node.name || node, ts.Diagnostics.JSDoc_types_may_be_moved_to_TypeScript_types)); + } + } + if (ts.isFunctionLikeDeclaration(node)) { + addConvertToAsyncFunctionDiagnostics(node, checker, diags); + } + node.forEachChild(check); + } + } + ts.computeSuggestionDiagnostics = computeSuggestionDiagnostics; + // convertToEs6Module only works on top-level, so don't trigger it if commonjs code only appears in nested scopes. + function containsTopLevelCommonjs(sourceFile) { + return sourceFile.statements.some(function (statement) { + switch (statement.kind) { + case 219 /* VariableStatement */: + return statement.declarationList.declarations.some(function (decl) { + return !!decl.initializer && ts.isRequireCall(propertyAccessLeftHandSide(decl.initializer), /*checkArgumentIsStringLiteralLike*/ true); + }); + case 221 /* ExpressionStatement */: { + var expression = statement.expression; + if (!ts.isBinaryExpression(expression)) + return ts.isRequireCall(expression, /*checkArgumentIsStringLiteralLike*/ true); + var kind = ts.getAssignmentDeclarationKind(expression); + return kind === 1 /* ExportsProperty */ || kind === 2 /* ModuleExports */; + } + default: + return false; + } + }); + } + function propertyAccessLeftHandSide(node) { + return ts.isPropertyAccessExpression(node) ? propertyAccessLeftHandSide(node.expression) : node; + } + function importNameForConvertToDefaultImport(node) { + switch (node.kind) { + case 249 /* ImportDeclaration */: + var importClause = node.importClause, moduleSpecifier = node.moduleSpecifier; + return importClause && !importClause.name && importClause.namedBindings && importClause.namedBindings.kind === 251 /* NamespaceImport */ && ts.isStringLiteral(moduleSpecifier) + ? importClause.namedBindings.name + : undefined; + case 248 /* ImportEqualsDeclaration */: + return node.name; + default: + return undefined; + } + } + function addConvertToAsyncFunctionDiagnostics(node, checker, diags) { + if (!ts.isAsyncFunction(node) && + node.body && + ts.isBlock(node.body) && + hasReturnStatementWithPromiseHandler(node.body) && + returnsPromise(node, checker)) { + diags.push(ts.createDiagnosticForNode(!node.name && ts.isVariableDeclaration(node.parent) && ts.isIdentifier(node.parent.name) ? node.parent.name : node, ts.Diagnostics.This_may_be_converted_to_an_async_function)); + } + } + function returnsPromise(node, checker) { + var functionType = checker.getTypeAtLocation(node); + var callSignatures = checker.getSignaturesOfType(functionType, 0 /* Call */); + var returnType = callSignatures.length ? checker.getReturnTypeOfSignature(callSignatures[0]) : undefined; + return !!returnType && !!checker.getPromisedTypeOfPromise(returnType); + } + function getErrorNodeFromCommonJsIndicator(commonJsModuleIndicator) { + return ts.isBinaryExpression(commonJsModuleIndicator) ? commonJsModuleIndicator.left : commonJsModuleIndicator; + } + function hasReturnStatementWithPromiseHandler(body) { + return !!ts.forEachReturnStatement(body, isReturnStatementWithFixablePromiseHandler); + } + function isReturnStatementWithFixablePromiseHandler(node) { + return ts.isReturnStatement(node) && !!node.expression && isFixablePromiseHandler(node.expression); + } + ts.isReturnStatementWithFixablePromiseHandler = isReturnStatementWithFixablePromiseHandler; + // Should be kept up to date with transformExpression in convertToAsyncFunction.ts + function isFixablePromiseHandler(node) { + // ensure outermost call exists and is a promise handler + if (!isPromiseHandler(node) || !node.arguments.every(isFixablePromiseArgument)) { + return false; + } + // ensure all chained calls are valid + var currentNode = node.expression; + while (isPromiseHandler(currentNode) || ts.isPropertyAccessExpression(currentNode)) { + if (ts.isCallExpression(currentNode) && !currentNode.arguments.every(isFixablePromiseArgument)) { + return false; + } + currentNode = currentNode.expression; + } + return true; + } + ts.isFixablePromiseHandler = isFixablePromiseHandler; + function isPromiseHandler(node) { + return ts.isCallExpression(node) && (ts.hasPropertyAccessExpressionWithName(node, "then") || ts.hasPropertyAccessExpressionWithName(node, "catch")); + } + // should be kept up to date with getTransformationBody in convertToAsyncFunction.ts + function isFixablePromiseArgument(arg) { + switch (arg.kind) { + case 96 /* NullKeyword */: + case 72 /* Identifier */: // identifier includes undefined + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + return true; + default: + return false; + } + } +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var SymbolDisplay; + (function (SymbolDisplay) { + // TODO(drosen): use contextual SemanticMeaning. + function getSymbolKind(typeChecker, symbol, location) { + var result = getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, location); + if (result !== "" /* unknown */) { + return result; + } + var flags = ts.getCombinedLocalAndExportSymbolFlags(symbol); + if (flags & 32 /* Class */) { + return ts.getDeclarationOfKind(symbol, 209 /* ClassExpression */) ? + "local class" /* localClassElement */ : "class" /* classElement */; + } + if (flags & 384 /* Enum */) + return "enum" /* enumElement */; + if (flags & 524288 /* TypeAlias */) + return "type" /* typeElement */; + if (flags & 64 /* Interface */) + return "interface" /* interfaceElement */; + if (flags & 262144 /* TypeParameter */) + return "type parameter" /* typeParameterElement */; + if (flags & 262144 /* TypeParameter */) + return "type parameter" /* typeParameterElement */; + if (flags & 8 /* EnumMember */) + return "enum member" /* enumMemberElement */; + if (flags & 2097152 /* Alias */) + return "alias" /* alias */; + if (flags & 1536 /* Module */) + return "module" /* moduleElement */; + return result; + } + SymbolDisplay.getSymbolKind = getSymbolKind; + function getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, location) { + var roots = typeChecker.getRootSymbols(symbol); + // If this is a method from a mapped type, leave as a method so long as it still has a call signature. + if (roots.length === 1 + && ts.first(roots).flags & 8192 /* Method */ + // Ensure the mapped version is still a method, as opposed to `{ [K in keyof I]: number }`. + && typeChecker.getTypeOfSymbolAtLocation(symbol, location).getNonNullableType().getCallSignatures().length !== 0) { + return "method" /* memberFunctionElement */; + } + if (typeChecker.isUndefinedSymbol(symbol)) { + return "var" /* variableElement */; + } + if (typeChecker.isArgumentsSymbol(symbol)) { + return "local var" /* localVariableElement */; + } + if (location.kind === 100 /* ThisKeyword */ && ts.isExpression(location)) { + return "parameter" /* parameterElement */; + } + var flags = ts.getCombinedLocalAndExportSymbolFlags(symbol); + if (flags & 3 /* Variable */) { + if (ts.isFirstDeclarationOfSymbolParameter(symbol)) { + return "parameter" /* parameterElement */; + } + else if (symbol.valueDeclaration && ts.isVarConst(symbol.valueDeclaration)) { + return "const" /* constElement */; + } + else if (ts.forEach(symbol.declarations, ts.isLet)) { + return "let" /* letElement */; + } + return isLocalVariableOrFunction(symbol) ? "local var" /* localVariableElement */ : "var" /* variableElement */; + } + if (flags & 16 /* Function */) + return isLocalVariableOrFunction(symbol) ? "local function" /* localFunctionElement */ : "function" /* functionElement */; + if (flags & 32768 /* GetAccessor */) + return "getter" /* memberGetAccessorElement */; + if (flags & 65536 /* SetAccessor */) + return "setter" /* memberSetAccessorElement */; + if (flags & 8192 /* Method */) + return "method" /* memberFunctionElement */; + if (flags & 16384 /* Constructor */) + return "constructor" /* constructorImplementationElement */; + if (flags & 4 /* Property */) { + if (flags & 33554432 /* Transient */ && symbol.checkFlags & 6 /* Synthetic */) { + // If union property is result of union of non method (property/accessors/variables), it is labeled as property + var unionPropertyKind = ts.forEach(typeChecker.getRootSymbols(symbol), function (rootSymbol) { + var rootSymbolFlags = rootSymbol.getFlags(); + if (rootSymbolFlags & (98308 /* PropertyOrAccessor */ | 3 /* Variable */)) { + return "property" /* memberVariableElement */; + } + // May be a Function if this was from `typeof N` with `namespace N { function f();. }`. + ts.Debug.assert(!!(rootSymbolFlags & (8192 /* Method */ | 16 /* Function */))); + }); + if (!unionPropertyKind) { + // If this was union of all methods, + // make sure it has call signatures before we can label it as method + var typeOfUnionProperty = typeChecker.getTypeOfSymbolAtLocation(symbol, location); + if (typeOfUnionProperty.getCallSignatures().length) { + return "method" /* memberFunctionElement */; + } + return "property" /* memberVariableElement */; + } + return unionPropertyKind; + } + // If we requested completions after `x.` at the top-level, we may be at a source file location. + switch (location.parent && location.parent.kind) { + // If we've typed a character of the attribute name, will be 'JsxAttribute', else will be 'JsxOpeningElement'. + case 262 /* JsxOpeningElement */: + case 260 /* JsxElement */: + case 261 /* JsxSelfClosingElement */: + return location.kind === 72 /* Identifier */ ? "property" /* memberVariableElement */ : "JSX attribute" /* jsxAttribute */; + case 267 /* JsxAttribute */: + return "JSX attribute" /* jsxAttribute */; + default: + return "property" /* memberVariableElement */; + } + } + return "" /* unknown */; + } + function getSymbolModifiers(symbol) { + var nodeModifiers = symbol && symbol.declarations && symbol.declarations.length > 0 + ? ts.getNodeModifiers(symbol.declarations[0]) + : "" /* none */; + var symbolModifiers = symbol && symbol.flags & 16777216 /* Optional */ ? + "optional" /* optionalModifier */ + : "" /* none */; + return nodeModifiers && symbolModifiers ? nodeModifiers + "," + symbolModifiers : nodeModifiers || symbolModifiers; + } + SymbolDisplay.getSymbolModifiers = getSymbolModifiers; + // TODO(drosen): Currently completion entry details passes the SemanticMeaning.All instead of using semanticMeaning of location + function getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, enclosingDeclaration, location, semanticMeaning, alias) { + if (semanticMeaning === void 0) { semanticMeaning = ts.getMeaningFromLocation(location); } + var displayParts = []; + var documentation; + var tags; + var symbolFlags = ts.getCombinedLocalAndExportSymbolFlags(symbol); + var symbolKind = semanticMeaning & 1 /* Value */ ? getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, location) : "" /* unknown */; + var hasAddedSymbolInfo = false; + var isThisExpression = location.kind === 100 /* ThisKeyword */ && ts.isInExpressionContext(location); + var type; + var printer; + var documentationFromAlias; + var tagsFromAlias; + if (location.kind === 100 /* ThisKeyword */ && !isThisExpression) { + return { displayParts: [ts.keywordPart(100 /* ThisKeyword */)], documentation: [], symbolKind: "primitive type" /* primitiveType */, tags: undefined }; + } + // Class at constructor site need to be shown as constructor apart from property,method, vars + if (symbolKind !== "" /* unknown */ || symbolFlags & 32 /* Class */ || symbolFlags & 2097152 /* Alias */) { + // If it is accessor they are allowed only if location is at name of the accessor + if (symbolKind === "getter" /* memberGetAccessorElement */ || symbolKind === "setter" /* memberSetAccessorElement */) { + symbolKind = "property" /* memberVariableElement */; + } + var signature = void 0; + type = isThisExpression ? typeChecker.getTypeAtLocation(location) : typeChecker.getTypeOfSymbolAtLocation(symbol.exportSymbol || symbol, location); + if (location.parent && location.parent.kind === 189 /* PropertyAccessExpression */) { + var right = location.parent.name; + // Either the location is on the right of a property access, or on the left and the right is missing + if (right === location || (right && right.getFullWidth() === 0)) { + location = location.parent; + } + } + // try get the call/construct signature from the type if it matches + var callExpressionLike = void 0; + if (ts.isCallOrNewExpression(location)) { + callExpressionLike = location; + } + else if (ts.isCallExpressionTarget(location) || ts.isNewExpressionTarget(location)) { + callExpressionLike = location.parent; + } + else if (location.parent && ts.isJsxOpeningLikeElement(location.parent) && ts.isFunctionLike(symbol.valueDeclaration)) { + callExpressionLike = location.parent; + } + if (callExpressionLike) { + var candidateSignatures = []; + signature = typeChecker.getResolvedSignature(callExpressionLike, candidateSignatures); // TODO: GH#18217 + var useConstructSignatures = callExpressionLike.kind === 192 /* NewExpression */ || (ts.isCallExpression(callExpressionLike) && callExpressionLike.expression.kind === 98 /* SuperKeyword */); + var allSignatures = useConstructSignatures ? type.getConstructSignatures() : type.getCallSignatures(); + if (!ts.contains(allSignatures, signature.target) && !ts.contains(allSignatures, signature)) { + // Get the first signature if there is one -- allSignatures may contain + // either the original signature or its target, so check for either + signature = allSignatures.length ? allSignatures[0] : undefined; + } + if (signature) { + if (useConstructSignatures && (symbolFlags & 32 /* Class */)) { + // Constructor + symbolKind = "constructor" /* constructorImplementationElement */; + addPrefixForAnyFunctionOrVar(type.symbol, symbolKind); + } + else if (symbolFlags & 2097152 /* Alias */) { + symbolKind = "alias" /* alias */; + pushSymbolKind(symbolKind); + displayParts.push(ts.spacePart()); + if (useConstructSignatures) { + displayParts.push(ts.keywordPart(95 /* NewKeyword */)); + displayParts.push(ts.spacePart()); + } + addFullSymbolName(symbol); + } + else { + addPrefixForAnyFunctionOrVar(symbol, symbolKind); + } + switch (symbolKind) { + case "JSX attribute" /* jsxAttribute */: + case "property" /* memberVariableElement */: + case "var" /* variableElement */: + case "const" /* constElement */: + case "let" /* letElement */: + case "parameter" /* parameterElement */: + case "local var" /* localVariableElement */: + // If it is call or construct signature of lambda's write type name + displayParts.push(ts.punctuationPart(57 /* ColonToken */)); + displayParts.push(ts.spacePart()); + if (!(ts.getObjectFlags(type) & 16 /* Anonymous */) && type.symbol) { + ts.addRange(displayParts, ts.symbolToDisplayParts(typeChecker, type.symbol, enclosingDeclaration, /*meaning*/ undefined, 4 /* AllowAnyNodeKind */ | 1 /* WriteTypeParametersOrArguments */)); + displayParts.push(ts.lineBreakPart()); + } + if (useConstructSignatures) { + displayParts.push(ts.keywordPart(95 /* NewKeyword */)); + displayParts.push(ts.spacePart()); + } + addSignatureDisplayParts(signature, allSignatures, 262144 /* WriteArrowStyleSignature */); + break; + default: + // Just signature + addSignatureDisplayParts(signature, allSignatures); + } + hasAddedSymbolInfo = true; + } + } + else if ((ts.isNameOfFunctionDeclaration(location) && !(symbolFlags & 98304 /* Accessor */)) || // name of function declaration + (location.kind === 124 /* ConstructorKeyword */ && location.parent.kind === 157 /* Constructor */)) { // At constructor keyword of constructor declaration + // get the signature from the declaration and write it + var functionDeclaration_1 = location.parent; + // Use function declaration to write the signatures only if the symbol corresponding to this declaration + var locationIsSymbolDeclaration = ts.find(symbol.declarations, function (declaration) { + return declaration === (location.kind === 124 /* ConstructorKeyword */ ? functionDeclaration_1.parent : functionDeclaration_1); + }); + if (locationIsSymbolDeclaration) { + var allSignatures = functionDeclaration_1.kind === 157 /* Constructor */ ? type.getNonNullableType().getConstructSignatures() : type.getNonNullableType().getCallSignatures(); + if (!typeChecker.isImplementationOfOverload(functionDeclaration_1)) { + signature = typeChecker.getSignatureFromDeclaration(functionDeclaration_1); // TODO: GH#18217 + } + else { + signature = allSignatures[0]; + } + if (functionDeclaration_1.kind === 157 /* Constructor */) { + // show (constructor) Type(...) signature + symbolKind = "constructor" /* constructorImplementationElement */; + addPrefixForAnyFunctionOrVar(type.symbol, symbolKind); + } + else { + // (function/method) symbol(..signature) + addPrefixForAnyFunctionOrVar(functionDeclaration_1.kind === 160 /* CallSignature */ && + !(type.symbol.flags & 2048 /* TypeLiteral */ || type.symbol.flags & 4096 /* ObjectLiteral */) ? type.symbol : symbol, symbolKind); + } + addSignatureDisplayParts(signature, allSignatures); + hasAddedSymbolInfo = true; + } + } + } + if (symbolFlags & 32 /* Class */ && !hasAddedSymbolInfo && !isThisExpression) { + addAliasPrefixIfNecessary(); + if (ts.getDeclarationOfKind(symbol, 209 /* ClassExpression */)) { + // Special case for class expressions because we would like to indicate that + // the class name is local to the class body (similar to function expression) + // (local class) class + pushSymbolKind("local class" /* localClassElement */); + } + else { + // Class declaration has name which is not local. + displayParts.push(ts.keywordPart(76 /* ClassKeyword */)); + } + displayParts.push(ts.spacePart()); + addFullSymbolName(symbol); + writeTypeParametersOfSymbol(symbol, sourceFile); + } + if ((symbolFlags & 64 /* Interface */) && (semanticMeaning & 2 /* Type */)) { + prefixNextMeaning(); + displayParts.push(ts.keywordPart(110 /* InterfaceKeyword */)); + displayParts.push(ts.spacePart()); + addFullSymbolName(symbol); + writeTypeParametersOfSymbol(symbol, sourceFile); + } + if ((symbolFlags & 524288 /* TypeAlias */) && (semanticMeaning & 2 /* Type */)) { + prefixNextMeaning(); + displayParts.push(ts.keywordPart(140 /* TypeKeyword */)); + displayParts.push(ts.spacePart()); + addFullSymbolName(symbol); + writeTypeParametersOfSymbol(symbol, sourceFile); + displayParts.push(ts.spacePart()); + displayParts.push(ts.operatorPart(59 /* EqualsToken */)); + displayParts.push(ts.spacePart()); + ts.addRange(displayParts, ts.typeToDisplayParts(typeChecker, typeChecker.getDeclaredTypeOfSymbol(symbol), enclosingDeclaration, 8388608 /* InTypeAlias */)); + } + if (symbolFlags & 384 /* Enum */) { + prefixNextMeaning(); + if (ts.some(symbol.declarations, function (d) { return ts.isEnumDeclaration(d) && ts.isEnumConst(d); })) { + displayParts.push(ts.keywordPart(77 /* ConstKeyword */)); + displayParts.push(ts.spacePart()); + } + displayParts.push(ts.keywordPart(84 /* EnumKeyword */)); + displayParts.push(ts.spacePart()); + addFullSymbolName(symbol); + } + if (symbolFlags & 1536 /* Module */) { + prefixNextMeaning(); + var declaration = ts.getDeclarationOfKind(symbol, 244 /* ModuleDeclaration */); + var isNamespace = declaration && declaration.name && declaration.name.kind === 72 /* Identifier */; + displayParts.push(ts.keywordPart(isNamespace ? 131 /* NamespaceKeyword */ : 130 /* ModuleKeyword */)); + displayParts.push(ts.spacePart()); + addFullSymbolName(symbol); + } + if ((symbolFlags & 262144 /* TypeParameter */) && (semanticMeaning & 2 /* Type */)) { + prefixNextMeaning(); + displayParts.push(ts.punctuationPart(20 /* OpenParenToken */)); + displayParts.push(ts.textPart("type parameter")); + displayParts.push(ts.punctuationPart(21 /* CloseParenToken */)); + displayParts.push(ts.spacePart()); + addFullSymbolName(symbol); + if (symbol.parent) { + // Class/Interface type parameter + addInPrefix(); + addFullSymbolName(symbol.parent, enclosingDeclaration); + writeTypeParametersOfSymbol(symbol.parent, enclosingDeclaration); + } + else { + // Method/function type parameter + var decl = ts.getDeclarationOfKind(symbol, 150 /* TypeParameter */); + if (decl === undefined) + return ts.Debug.fail(); + var declaration = decl.parent; + if (declaration) { + if (ts.isFunctionLikeKind(declaration.kind)) { + addInPrefix(); + var signature = typeChecker.getSignatureFromDeclaration(declaration); // TODO: GH#18217 + if (declaration.kind === 161 /* ConstructSignature */) { + displayParts.push(ts.keywordPart(95 /* NewKeyword */)); + displayParts.push(ts.spacePart()); + } + else if (declaration.kind !== 160 /* CallSignature */ && declaration.name) { + addFullSymbolName(declaration.symbol); + } + ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, sourceFile, 32 /* WriteTypeArgumentsOfSignature */)); + } + else if (declaration.kind === 242 /* TypeAliasDeclaration */) { + // Type alias type parameter + // For example + // type list = T[]; // Both T will go through same code path + addInPrefix(); + displayParts.push(ts.keywordPart(140 /* TypeKeyword */)); + displayParts.push(ts.spacePart()); + addFullSymbolName(declaration.symbol); + writeTypeParametersOfSymbol(declaration.symbol, sourceFile); + } + } + } + } + if (symbolFlags & 8 /* EnumMember */) { + symbolKind = "enum member" /* enumMemberElement */; + addPrefixForAnyFunctionOrVar(symbol, "enum member"); + var declaration = symbol.declarations[0]; + if (declaration.kind === 278 /* EnumMember */) { + var constantValue = typeChecker.getConstantValue(declaration); + if (constantValue !== undefined) { + displayParts.push(ts.spacePart()); + displayParts.push(ts.operatorPart(59 /* EqualsToken */)); + displayParts.push(ts.spacePart()); + displayParts.push(ts.displayPart(ts.getTextOfConstantValue(constantValue), typeof constantValue === "number" ? ts.SymbolDisplayPartKind.numericLiteral : ts.SymbolDisplayPartKind.stringLiteral)); + } + } + } + if (symbolFlags & 2097152 /* Alias */) { + prefixNextMeaning(); + if (!hasAddedSymbolInfo) { + var resolvedSymbol = typeChecker.getAliasedSymbol(symbol); + if (resolvedSymbol !== symbol && resolvedSymbol.declarations && resolvedSymbol.declarations.length > 0) { + var resolvedNode = resolvedSymbol.declarations[0]; + var declarationName = ts.getNameOfDeclaration(resolvedNode); + if (declarationName) { + var isExternalModuleDeclaration = ts.isModuleWithStringLiteralName(resolvedNode) && + ts.hasModifier(resolvedNode, 2 /* Ambient */); + var shouldUseAliasName = symbol.name !== "default" && !isExternalModuleDeclaration; + var resolvedInfo = getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, resolvedSymbol, ts.getSourceFileOfNode(resolvedNode), resolvedNode, declarationName, semanticMeaning, shouldUseAliasName ? symbol : resolvedSymbol); + displayParts.push.apply(displayParts, resolvedInfo.displayParts); + displayParts.push(ts.lineBreakPart()); + documentationFromAlias = resolvedInfo.documentation; + tagsFromAlias = resolvedInfo.tags; + } + } + } + switch (symbol.declarations[0].kind) { + case 247 /* NamespaceExportDeclaration */: + displayParts.push(ts.keywordPart(85 /* ExportKeyword */)); + displayParts.push(ts.spacePart()); + displayParts.push(ts.keywordPart(131 /* NamespaceKeyword */)); + break; + case 254 /* ExportAssignment */: + displayParts.push(ts.keywordPart(85 /* ExportKeyword */)); + displayParts.push(ts.spacePart()); + displayParts.push(ts.keywordPart(symbol.declarations[0].isExportEquals ? 59 /* EqualsToken */ : 80 /* DefaultKeyword */)); + break; + case 257 /* ExportSpecifier */: + displayParts.push(ts.keywordPart(85 /* ExportKeyword */)); + break; + default: + displayParts.push(ts.keywordPart(92 /* ImportKeyword */)); + } + displayParts.push(ts.spacePart()); + addFullSymbolName(symbol); + ts.forEach(symbol.declarations, function (declaration) { + if (declaration.kind === 248 /* ImportEqualsDeclaration */) { + var importEqualsDeclaration = declaration; + if (ts.isExternalModuleImportEqualsDeclaration(importEqualsDeclaration)) { + displayParts.push(ts.spacePart()); + displayParts.push(ts.operatorPart(59 /* EqualsToken */)); + displayParts.push(ts.spacePart()); + displayParts.push(ts.keywordPart(134 /* RequireKeyword */)); + displayParts.push(ts.punctuationPart(20 /* OpenParenToken */)); + displayParts.push(ts.displayPart(ts.getTextOfNode(ts.getExternalModuleImportEqualsDeclarationExpression(importEqualsDeclaration)), ts.SymbolDisplayPartKind.stringLiteral)); + displayParts.push(ts.punctuationPart(21 /* CloseParenToken */)); + } + else { + var internalAliasSymbol = typeChecker.getSymbolAtLocation(importEqualsDeclaration.moduleReference); + if (internalAliasSymbol) { + displayParts.push(ts.spacePart()); + displayParts.push(ts.operatorPart(59 /* EqualsToken */)); + displayParts.push(ts.spacePart()); + addFullSymbolName(internalAliasSymbol, enclosingDeclaration); + } + } + return true; + } + }); + } + if (!hasAddedSymbolInfo) { + if (symbolKind !== "" /* unknown */) { + if (type) { + if (isThisExpression) { + prefixNextMeaning(); + displayParts.push(ts.keywordPart(100 /* ThisKeyword */)); + } + else { + addPrefixForAnyFunctionOrVar(symbol, symbolKind); + } + // For properties, variables and local vars: show the type + if (symbolKind === "property" /* memberVariableElement */ || + symbolKind === "JSX attribute" /* jsxAttribute */ || + symbolFlags & 3 /* Variable */ || + symbolKind === "local var" /* localVariableElement */ || + isThisExpression) { + displayParts.push(ts.punctuationPart(57 /* ColonToken */)); + displayParts.push(ts.spacePart()); + // If the type is type parameter, format it specially + if (type.symbol && type.symbol.flags & 262144 /* TypeParameter */) { + var typeParameterParts = ts.mapToDisplayParts(function (writer) { + var param = typeChecker.typeParameterToDeclaration(type, enclosingDeclaration); + getPrinter().writeNode(4 /* Unspecified */, param, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosingDeclaration)), writer); + }); + ts.addRange(displayParts, typeParameterParts); + } + else { + ts.addRange(displayParts, ts.typeToDisplayParts(typeChecker, type, enclosingDeclaration)); + } + } + else if (symbolFlags & 16 /* Function */ || + symbolFlags & 8192 /* Method */ || + symbolFlags & 16384 /* Constructor */ || + symbolFlags & 131072 /* Signature */ || + symbolFlags & 98304 /* Accessor */ || + symbolKind === "method" /* memberFunctionElement */) { + var allSignatures = type.getNonNullableType().getCallSignatures(); + if (allSignatures.length) { + addSignatureDisplayParts(allSignatures[0], allSignatures); + } + } + } + } + else { + symbolKind = getSymbolKind(typeChecker, symbol, location); + } + } + if (!documentation) { + documentation = symbol.getDocumentationComment(typeChecker); + tags = symbol.getJsDocTags(); + if (documentation.length === 0 && symbolFlags & 4 /* Property */) { + // For some special property access expressions like `exports.foo = foo` or `module.exports.foo = foo` + // there documentation comments might be attached to the right hand side symbol of their declarations. + // The pattern of such special property access is that the parent symbol is the symbol of the file. + if (symbol.parent && ts.forEach(symbol.parent.declarations, function (declaration) { return declaration.kind === 279 /* SourceFile */; })) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (!declaration.parent || declaration.parent.kind !== 204 /* BinaryExpression */) { + continue; + } + var rhsSymbol = typeChecker.getSymbolAtLocation(declaration.parent.right); + if (!rhsSymbol) { + continue; + } + documentation = rhsSymbol.getDocumentationComment(typeChecker); + tags = rhsSymbol.getJsDocTags(); + if (documentation.length > 0) { + break; + } + } + } + } + } + if (documentation.length === 0 && documentationFromAlias) { + documentation = documentationFromAlias; + } + if (tags.length === 0 && tagsFromAlias) { + tags = tagsFromAlias; + } + return { displayParts: displayParts, documentation: documentation, symbolKind: symbolKind, tags: tags.length === 0 ? undefined : tags }; + function getPrinter() { + if (!printer) { + printer = ts.createPrinter({ removeComments: true }); + } + return printer; + } + function prefixNextMeaning() { + if (displayParts.length) { + displayParts.push(ts.lineBreakPart()); + } + addAliasPrefixIfNecessary(); + } + function addAliasPrefixIfNecessary() { + if (alias) { + pushSymbolKind("alias" /* alias */); + displayParts.push(ts.spacePart()); + } + } + function addInPrefix() { + displayParts.push(ts.spacePart()); + displayParts.push(ts.keywordPart(93 /* InKeyword */)); + displayParts.push(ts.spacePart()); + } + function addFullSymbolName(symbolToDisplay, enclosingDeclaration) { + if (alias && symbolToDisplay === symbol) { + symbolToDisplay = alias; + } + var fullSymbolDisplayParts = ts.symbolToDisplayParts(typeChecker, symbolToDisplay, enclosingDeclaration || sourceFile, /*meaning*/ undefined, 1 /* WriteTypeParametersOrArguments */ | 2 /* UseOnlyExternalAliasing */ | 4 /* AllowAnyNodeKind */); + ts.addRange(displayParts, fullSymbolDisplayParts); + if (symbol.flags & 16777216 /* Optional */) { + displayParts.push(ts.punctuationPart(56 /* QuestionToken */)); + } + } + function addPrefixForAnyFunctionOrVar(symbol, symbolKind) { + prefixNextMeaning(); + if (symbolKind) { + pushSymbolKind(symbolKind); + if (symbol && !ts.some(symbol.declarations, function (d) { return ts.isArrowFunction(d) || (ts.isFunctionExpression(d) || ts.isClassExpression(d)) && !d.name; })) { + displayParts.push(ts.spacePart()); + addFullSymbolName(symbol); + } + } + } + function pushSymbolKind(symbolKind) { + switch (symbolKind) { + case "var" /* variableElement */: + case "function" /* functionElement */: + case "let" /* letElement */: + case "const" /* constElement */: + case "constructor" /* constructorImplementationElement */: + displayParts.push(ts.textOrKeywordPart(symbolKind)); + return; + default: + displayParts.push(ts.punctuationPart(20 /* OpenParenToken */)); + displayParts.push(ts.textOrKeywordPart(symbolKind)); + displayParts.push(ts.punctuationPart(21 /* CloseParenToken */)); + return; + } + } + function addSignatureDisplayParts(signature, allSignatures, flags) { + if (flags === void 0) { flags = 0 /* None */; } + ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, enclosingDeclaration, flags | 32 /* WriteTypeArgumentsOfSignature */)); + if (allSignatures.length > 1) { + displayParts.push(ts.spacePart()); + displayParts.push(ts.punctuationPart(20 /* OpenParenToken */)); + displayParts.push(ts.operatorPart(38 /* PlusToken */)); + displayParts.push(ts.displayPart((allSignatures.length - 1).toString(), ts.SymbolDisplayPartKind.numericLiteral)); + displayParts.push(ts.spacePart()); + displayParts.push(ts.textPart(allSignatures.length === 2 ? "overload" : "overloads")); + displayParts.push(ts.punctuationPart(21 /* CloseParenToken */)); + } + var docComment = signature.getDocumentationComment(typeChecker); + documentation = docComment.length === 0 ? undefined : docComment; + tags = signature.getJsDocTags(); + } + function writeTypeParametersOfSymbol(symbol, enclosingDeclaration) { + var typeParameterParts = ts.mapToDisplayParts(function (writer) { + var params = typeChecker.symbolToTypeParameterDeclarations(symbol, enclosingDeclaration); + getPrinter().writeList(53776 /* TypeParameters */, params, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosingDeclaration)), writer); + }); + ts.addRange(displayParts, typeParameterParts); + } + } + SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind = getSymbolDisplayPartsDocumentationAndSymbolKind; + function isLocalVariableOrFunction(symbol) { + if (symbol.parent) { + return false; // This is exported symbol + } + return ts.forEach(symbol.declarations, function (declaration) { + // Function expressions are local + if (declaration.kind === 196 /* FunctionExpression */) { + return true; + } + if (declaration.kind !== 237 /* VariableDeclaration */ && declaration.kind !== 239 /* FunctionDeclaration */) { + return false; + } + // If the parent is not sourceFile or module block it is local variable + for (var parent = declaration.parent; !ts.isFunctionBlock(parent); parent = parent.parent) { + // Reached source file or module block + if (parent.kind === 279 /* SourceFile */ || parent.kind === 245 /* ModuleBlock */) { + return false; + } + } + // parent is in function block + return true; + }); + } + })(SymbolDisplay = ts.SymbolDisplay || (ts.SymbolDisplay = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + /* + * This function will compile source text from 'input' argument using specified compiler options. + * If not options are provided - it will use a set of default compiler options. + * Extra compiler options that will unconditionally be used by this function are: + * - isolatedModules = true + * - allowNonTsExtensions = true + * - noLib = true + * - noResolve = true + */ + function transpileModule(input, transpileOptions) { + var diagnostics = []; + var options = transpileOptions.compilerOptions ? fixupCompilerOptions(transpileOptions.compilerOptions, diagnostics) : ts.getDefaultCompilerOptions(); + options.isolatedModules = true; + // transpileModule does not write anything to disk so there is no need to verify that there are no conflicts between input and output paths. + options.suppressOutputPathCheck = true; + // Filename can be non-ts file. + options.allowNonTsExtensions = true; + // We are not returning a sourceFile for lib file when asked by the program, + // so pass --noLib to avoid reporting a file not found error. + options.noLib = true; + // Clear out other settings that would not be used in transpiling this module + options.lib = undefined; + options.types = undefined; + options.noEmit = undefined; + options.noEmitOnError = undefined; + options.paths = undefined; + options.rootDirs = undefined; + options.declaration = undefined; + options.composite = undefined; + options.declarationDir = undefined; + options.out = undefined; + options.outFile = undefined; + // We are not doing a full typecheck, we are not resolving the whole context, + // so pass --noResolve to avoid reporting missing file errors. + options.noResolve = true; + // if jsx is specified then treat file as .tsx + var inputFileName = transpileOptions.fileName || (options.jsx ? "module.tsx" : "module.ts"); + var sourceFile = ts.createSourceFile(inputFileName, input, options.target); // TODO: GH#18217 + if (transpileOptions.moduleName) { + sourceFile.moduleName = transpileOptions.moduleName; + } + if (transpileOptions.renamedDependencies) { + sourceFile.renamedDependencies = ts.createMapFromTemplate(transpileOptions.renamedDependencies); + } + var newLine = ts.getNewLineCharacter(options); + // Output + var outputText; + var sourceMapText; + // Create a compilerHost object to allow the compiler to read and write files + var compilerHost = { + getSourceFile: function (fileName) { return fileName === ts.normalizePath(inputFileName) ? sourceFile : undefined; }, + writeFile: function (name, text) { + if (ts.fileExtensionIs(name, ".map")) { + ts.Debug.assertEqual(sourceMapText, undefined, "Unexpected multiple source map outputs, file:", name); + sourceMapText = text; + } + else { + ts.Debug.assertEqual(outputText, undefined, "Unexpected multiple outputs, file:", name); + outputText = text; + } + }, + getDefaultLibFileName: function () { return "lib.d.ts"; }, + useCaseSensitiveFileNames: function () { return false; }, + getCanonicalFileName: function (fileName) { return fileName; }, + getCurrentDirectory: function () { return ""; }, + getNewLine: function () { return newLine; }, + fileExists: function (fileName) { return fileName === inputFileName; }, + readFile: function () { return ""; }, + directoryExists: function () { return true; }, + getDirectories: function () { return []; } + }; + var program = ts.createProgram([inputFileName], options, compilerHost); + if (transpileOptions.reportDiagnostics) { + ts.addRange(/*to*/ diagnostics, /*from*/ program.getSyntacticDiagnostics(sourceFile)); + ts.addRange(/*to*/ diagnostics, /*from*/ program.getOptionsDiagnostics()); + } + // Emit + program.emit(/*targetSourceFile*/ undefined, /*writeFile*/ undefined, /*cancellationToken*/ undefined, /*emitOnlyDtsFiles*/ undefined, transpileOptions.transformers); + if (outputText === undefined) + return ts.Debug.fail("Output generation failed"); + return { outputText: outputText, diagnostics: diagnostics, sourceMapText: sourceMapText }; + } + ts.transpileModule = transpileModule; + /* + * This is a shortcut function for transpileModule - it accepts transpileOptions as parameters and returns only outputText part of the result. + */ + function transpile(input, compilerOptions, fileName, diagnostics, moduleName) { + var output = transpileModule(input, { compilerOptions: compilerOptions, fileName: fileName, reportDiagnostics: !!diagnostics, moduleName: moduleName }); + // addRange correctly handles cases when wither 'from' or 'to' argument is missing + ts.addRange(diagnostics, output.diagnostics); + return output.outputText; + } + ts.transpile = transpile; + var commandLineOptionsStringToEnum; + /** JS users may pass in string values for enum compiler options (such as ModuleKind), so convert. */ + /*@internal*/ + function fixupCompilerOptions(options, diagnostics) { + // Lazily create this value to fix module loading errors. + commandLineOptionsStringToEnum = commandLineOptionsStringToEnum || ts.filter(ts.optionDeclarations, function (o) { + return typeof o.type === "object" && !ts.forEachEntry(o.type, function (v) { return typeof v !== "number"; }); + }); + options = ts.cloneCompilerOptions(options); + var _loop_16 = function (opt) { + if (!ts.hasProperty(options, opt.name)) { + return "continue"; + } + var value = options[opt.name]; + // Value should be a key of opt.type + if (ts.isString(value)) { + // If value is not a string, this will fail + options[opt.name] = ts.parseCustomTypeOption(opt, value, diagnostics); + } + else { + if (!ts.forEachEntry(opt.type, function (v) { return v === value; })) { + // Supplied value isn't a valid enum value. + diagnostics.push(ts.createCompilerDiagnosticForInvalidCustomType(opt)); + } + } + }; + for (var _i = 0, commandLineOptionsStringToEnum_1 = commandLineOptionsStringToEnum; _i < commandLineOptionsStringToEnum_1.length; _i++) { + var opt = commandLineOptionsStringToEnum_1[_i]; + _loop_16(opt); + } + return options; + } + ts.fixupCompilerOptions = fixupCompilerOptions; +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var formatting; + (function (formatting) { + var FormattingRequestKind; + (function (FormattingRequestKind) { + FormattingRequestKind[FormattingRequestKind["FormatDocument"] = 0] = "FormatDocument"; + FormattingRequestKind[FormattingRequestKind["FormatSelection"] = 1] = "FormatSelection"; + FormattingRequestKind[FormattingRequestKind["FormatOnEnter"] = 2] = "FormatOnEnter"; + FormattingRequestKind[FormattingRequestKind["FormatOnSemicolon"] = 3] = "FormatOnSemicolon"; + FormattingRequestKind[FormattingRequestKind["FormatOnOpeningCurlyBrace"] = 4] = "FormatOnOpeningCurlyBrace"; + FormattingRequestKind[FormattingRequestKind["FormatOnClosingCurlyBrace"] = 5] = "FormatOnClosingCurlyBrace"; + })(FormattingRequestKind = formatting.FormattingRequestKind || (formatting.FormattingRequestKind = {})); + var FormattingContext = /** @class */ (function () { + function FormattingContext(sourceFile, formattingRequestKind, options) { + this.sourceFile = sourceFile; + this.formattingRequestKind = formattingRequestKind; + this.options = options; + } + FormattingContext.prototype.updateContext = function (currentRange, currentTokenParent, nextRange, nextTokenParent, commonParent) { + this.currentTokenSpan = ts.Debug.assertDefined(currentRange); + this.currentTokenParent = ts.Debug.assertDefined(currentTokenParent); + this.nextTokenSpan = ts.Debug.assertDefined(nextRange); + this.nextTokenParent = ts.Debug.assertDefined(nextTokenParent); + this.contextNode = ts.Debug.assertDefined(commonParent); + // drop cached results + this.contextNodeAllOnSameLine = undefined; + this.nextNodeAllOnSameLine = undefined; + this.tokensAreOnSameLine = undefined; + this.contextNodeBlockIsOnOneLine = undefined; + this.nextNodeBlockIsOnOneLine = undefined; + }; + FormattingContext.prototype.ContextNodeAllOnSameLine = function () { + if (this.contextNodeAllOnSameLine === undefined) { + this.contextNodeAllOnSameLine = this.NodeIsOnOneLine(this.contextNode); + } + return this.contextNodeAllOnSameLine; + }; + FormattingContext.prototype.NextNodeAllOnSameLine = function () { + if (this.nextNodeAllOnSameLine === undefined) { + this.nextNodeAllOnSameLine = this.NodeIsOnOneLine(this.nextTokenParent); + } + return this.nextNodeAllOnSameLine; + }; + FormattingContext.prototype.TokensAreOnSameLine = function () { + if (this.tokensAreOnSameLine === undefined) { + var startLine = this.sourceFile.getLineAndCharacterOfPosition(this.currentTokenSpan.pos).line; + var endLine = this.sourceFile.getLineAndCharacterOfPosition(this.nextTokenSpan.pos).line; + this.tokensAreOnSameLine = (startLine === endLine); + } + return this.tokensAreOnSameLine; + }; + FormattingContext.prototype.ContextNodeBlockIsOnOneLine = function () { + if (this.contextNodeBlockIsOnOneLine === undefined) { + this.contextNodeBlockIsOnOneLine = this.BlockIsOnOneLine(this.contextNode); + } + return this.contextNodeBlockIsOnOneLine; + }; + FormattingContext.prototype.NextNodeBlockIsOnOneLine = function () { + if (this.nextNodeBlockIsOnOneLine === undefined) { + this.nextNodeBlockIsOnOneLine = this.BlockIsOnOneLine(this.nextTokenParent); + } + return this.nextNodeBlockIsOnOneLine; + }; + FormattingContext.prototype.NodeIsOnOneLine = function (node) { + var startLine = this.sourceFile.getLineAndCharacterOfPosition(node.getStart(this.sourceFile)).line; + var endLine = this.sourceFile.getLineAndCharacterOfPosition(node.getEnd()).line; + return startLine === endLine; + }; + FormattingContext.prototype.BlockIsOnOneLine = function (node) { + var openBrace = ts.findChildOfKind(node, 18 /* OpenBraceToken */, this.sourceFile); + var closeBrace = ts.findChildOfKind(node, 19 /* CloseBraceToken */, this.sourceFile); + if (openBrace && closeBrace) { + var startLine = this.sourceFile.getLineAndCharacterOfPosition(openBrace.getEnd()).line; + var endLine = this.sourceFile.getLineAndCharacterOfPosition(closeBrace.getStart(this.sourceFile)).line; + return startLine === endLine; + } + return false; + }; + return FormattingContext; + }()); + formatting.FormattingContext = FormattingContext; + })(formatting = ts.formatting || (ts.formatting = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var formatting; + (function (formatting) { + var standardScanner = ts.createScanner(6 /* Latest */, /*skipTrivia*/ false, 0 /* Standard */); + var jsxScanner = ts.createScanner(6 /* Latest */, /*skipTrivia*/ false, 1 /* JSX */); + var ScanAction; + (function (ScanAction) { + ScanAction[ScanAction["Scan"] = 0] = "Scan"; + ScanAction[ScanAction["RescanGreaterThanToken"] = 1] = "RescanGreaterThanToken"; + ScanAction[ScanAction["RescanSlashToken"] = 2] = "RescanSlashToken"; + ScanAction[ScanAction["RescanTemplateToken"] = 3] = "RescanTemplateToken"; + ScanAction[ScanAction["RescanJsxIdentifier"] = 4] = "RescanJsxIdentifier"; + ScanAction[ScanAction["RescanJsxText"] = 5] = "RescanJsxText"; + })(ScanAction || (ScanAction = {})); + function getFormattingScanner(text, languageVariant, startPos, endPos, cb) { + var scanner = languageVariant === 1 /* JSX */ ? jsxScanner : standardScanner; + scanner.setText(text); + scanner.setTextPos(startPos); + var wasNewLine = true; + var leadingTrivia; + var trailingTrivia; + var savedPos; + var lastScanAction; + var lastTokenInfo; + var res = cb({ + advance: advance, + readTokenInfo: readTokenInfo, + isOnToken: isOnToken, + getCurrentLeadingTrivia: function () { return leadingTrivia; }, + lastTrailingTriviaWasNewLine: function () { return wasNewLine; }, + skipToEndOf: skipToEndOf, + }); + lastTokenInfo = undefined; + scanner.setText(undefined); + return res; + function advance() { + lastTokenInfo = undefined; + var isStarted = scanner.getStartPos() !== startPos; + if (isStarted) { + wasNewLine = !!trailingTrivia && ts.last(trailingTrivia).kind === 4 /* NewLineTrivia */; + } + else { + scanner.scan(); + } + leadingTrivia = undefined; + trailingTrivia = undefined; + var pos = scanner.getStartPos(); + // Read leading trivia and token + while (pos < endPos) { + var t = scanner.getToken(); + if (!ts.isTrivia(t)) { + break; + } + // consume leading trivia + scanner.scan(); + var item = { + pos: pos, + end: scanner.getStartPos(), + kind: t + }; + pos = scanner.getStartPos(); + leadingTrivia = ts.append(leadingTrivia, item); + } + savedPos = scanner.getStartPos(); + } + function shouldRescanGreaterThanToken(node) { + switch (node.kind) { + case 32 /* GreaterThanEqualsToken */: + case 67 /* GreaterThanGreaterThanEqualsToken */: + case 68 /* GreaterThanGreaterThanGreaterThanEqualsToken */: + case 48 /* GreaterThanGreaterThanGreaterThanToken */: + case 47 /* GreaterThanGreaterThanToken */: + return true; + } + return false; + } + function shouldRescanJsxIdentifier(node) { + if (node.parent) { + switch (node.parent.kind) { + case 267 /* JsxAttribute */: + case 262 /* JsxOpeningElement */: + case 263 /* JsxClosingElement */: + case 261 /* JsxSelfClosingElement */: + // May parse an identifier like `module-layout`; that will be scanned as a keyword at first, but we should parse the whole thing to get an identifier. + return ts.isKeyword(node.kind) || node.kind === 72 /* Identifier */; + } + } + return false; + } + function shouldRescanJsxText(node) { + return node.kind === 11 /* JsxText */; + } + function shouldRescanSlashToken(container) { + return container.kind === 13 /* RegularExpressionLiteral */; + } + function shouldRescanTemplateToken(container) { + return container.kind === 16 /* TemplateMiddle */ || + container.kind === 17 /* TemplateTail */; + } + function startsWithSlashToken(t) { + return t === 42 /* SlashToken */ || t === 64 /* SlashEqualsToken */; + } + function readTokenInfo(n) { + ts.Debug.assert(isOnToken()); + // normally scanner returns the smallest available token + // check the kind of context node to determine if scanner should have more greedy behavior and consume more text. + var expectedScanAction = shouldRescanGreaterThanToken(n) + ? 1 /* RescanGreaterThanToken */ + : shouldRescanSlashToken(n) + ? 2 /* RescanSlashToken */ + : shouldRescanTemplateToken(n) + ? 3 /* RescanTemplateToken */ + : shouldRescanJsxIdentifier(n) + ? 4 /* RescanJsxIdentifier */ + : shouldRescanJsxText(n) + ? 5 /* RescanJsxText */ + : 0 /* Scan */; + if (lastTokenInfo && expectedScanAction === lastScanAction) { + // readTokenInfo was called before with the same expected scan action. + // No need to re-scan text, return existing 'lastTokenInfo' + // it is ok to call fixTokenKind here since it does not affect + // what portion of text is consumed. In contrast rescanning can change it, + // i.e. for '>=' when originally scanner eats just one character + // and rescanning forces it to consume more. + return fixTokenKind(lastTokenInfo, n); + } + if (scanner.getStartPos() !== savedPos) { + ts.Debug.assert(lastTokenInfo !== undefined); + // readTokenInfo was called before but scan action differs - rescan text + scanner.setTextPos(savedPos); + scanner.scan(); + } + var currentToken = getNextToken(n, expectedScanAction); + var token = { + pos: scanner.getStartPos(), + end: scanner.getTextPos(), + kind: currentToken + }; + // consume trailing trivia + if (trailingTrivia) { + trailingTrivia = undefined; + } + while (scanner.getStartPos() < endPos) { + currentToken = scanner.scan(); + if (!ts.isTrivia(currentToken)) { + break; + } + var trivia = { + pos: scanner.getStartPos(), + end: scanner.getTextPos(), + kind: currentToken + }; + if (!trailingTrivia) { + trailingTrivia = []; + } + trailingTrivia.push(trivia); + if (currentToken === 4 /* NewLineTrivia */) { + // move past new line + scanner.scan(); + break; + } + } + lastTokenInfo = { leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia, token: token }; + return fixTokenKind(lastTokenInfo, n); + } + function getNextToken(n, expectedScanAction) { + var token = scanner.getToken(); + lastScanAction = 0 /* Scan */; + switch (expectedScanAction) { + case 1 /* RescanGreaterThanToken */: + if (token === 30 /* GreaterThanToken */) { + lastScanAction = 1 /* RescanGreaterThanToken */; + var newToken = scanner.reScanGreaterToken(); + ts.Debug.assert(n.kind === newToken); + return newToken; + } + break; + case 2 /* RescanSlashToken */: + if (startsWithSlashToken(token)) { + lastScanAction = 2 /* RescanSlashToken */; + var newToken = scanner.reScanSlashToken(); + ts.Debug.assert(n.kind === newToken); + return newToken; + } + break; + case 3 /* RescanTemplateToken */: + if (token === 19 /* CloseBraceToken */) { + lastScanAction = 3 /* RescanTemplateToken */; + return scanner.reScanTemplateToken(); + } + break; + case 4 /* RescanJsxIdentifier */: + lastScanAction = 4 /* RescanJsxIdentifier */; + return scanner.scanJsxIdentifier(); + case 5 /* RescanJsxText */: + lastScanAction = 5 /* RescanJsxText */; + return scanner.reScanJsxToken(); + case 0 /* Scan */: + break; + default: + ts.Debug.assertNever(expectedScanAction); + } + return token; + } + function isOnToken() { + var current = lastTokenInfo ? lastTokenInfo.token.kind : scanner.getToken(); + var startPos = lastTokenInfo ? lastTokenInfo.token.pos : scanner.getStartPos(); + return startPos < endPos && current !== 1 /* EndOfFileToken */ && !ts.isTrivia(current); + } + // when containing node in the tree is token + // but its kind differs from the kind that was returned by the scanner, + // then kind needs to be fixed. This might happen in cases + // when parser interprets token differently, i.e keyword treated as identifier + function fixTokenKind(tokenInfo, container) { + if (ts.isToken(container) && tokenInfo.token.kind !== container.kind) { + tokenInfo.token.kind = container.kind; + } + return tokenInfo; + } + function skipToEndOf(node) { + scanner.setTextPos(node.end); + savedPos = scanner.getStartPos(); + lastScanAction = undefined; + lastTokenInfo = undefined; + wasNewLine = false; + leadingTrivia = undefined; + trailingTrivia = undefined; + } + } + formatting.getFormattingScanner = getFormattingScanner; + })(formatting = ts.formatting || (ts.formatting = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var formatting; + (function (formatting) { + formatting.anyContext = ts.emptyArray; + var RuleAction; + (function (RuleAction) { + RuleAction[RuleAction["Ignore"] = 1] = "Ignore"; + RuleAction[RuleAction["Space"] = 2] = "Space"; + RuleAction[RuleAction["NewLine"] = 4] = "NewLine"; + RuleAction[RuleAction["Delete"] = 8] = "Delete"; + })(RuleAction = formatting.RuleAction || (formatting.RuleAction = {})); + var RuleFlags; + (function (RuleFlags) { + RuleFlags[RuleFlags["None"] = 0] = "None"; + RuleFlags[RuleFlags["CanDeleteNewLines"] = 1] = "CanDeleteNewLines"; + })(RuleFlags = formatting.RuleFlags || (formatting.RuleFlags = {})); + })(formatting = ts.formatting || (ts.formatting = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var formatting; + (function (formatting) { + function getAllRules() { + var allTokens = []; + for (var token = 0 /* FirstToken */; token <= 147 /* LastToken */; token++) { + allTokens.push(token); + } + function anyTokenExcept() { + var tokens = []; + for (var _i = 0; _i < arguments.length; _i++) { + tokens[_i] = arguments[_i]; + } + return { tokens: allTokens.filter(function (t) { return !tokens.some(function (t2) { return t2 === t; }); }), isSpecific: false }; + } + var anyToken = { tokens: allTokens, isSpecific: false }; + var anyTokenIncludingMultilineComments = tokenRangeFrom(allTokens.concat([3 /* MultiLineCommentTrivia */])); + var keywords = tokenRangeFromRange(73 /* FirstKeyword */, 147 /* LastKeyword */); + var binaryOperators = tokenRangeFromRange(28 /* FirstBinaryOperator */, 71 /* LastBinaryOperator */); + var binaryKeywordOperators = [93 /* InKeyword */, 94 /* InstanceOfKeyword */, 147 /* OfKeyword */, 119 /* AsKeyword */, 128 /* IsKeyword */]; + var unaryPrefixOperators = [44 /* PlusPlusToken */, 45 /* MinusMinusToken */, 53 /* TildeToken */, 52 /* ExclamationToken */]; + var unaryPrefixExpressions = [ + 8 /* NumericLiteral */, 9 /* BigIntLiteral */, 72 /* Identifier */, 20 /* OpenParenToken */, + 22 /* OpenBracketToken */, 18 /* OpenBraceToken */, 100 /* ThisKeyword */, 95 /* NewKeyword */ + ]; + var unaryPreincrementExpressions = [72 /* Identifier */, 20 /* OpenParenToken */, 100 /* ThisKeyword */, 95 /* NewKeyword */]; + var unaryPostincrementExpressions = [72 /* Identifier */, 21 /* CloseParenToken */, 23 /* CloseBracketToken */, 95 /* NewKeyword */]; + var unaryPredecrementExpressions = [72 /* Identifier */, 20 /* OpenParenToken */, 100 /* ThisKeyword */, 95 /* NewKeyword */]; + var unaryPostdecrementExpressions = [72 /* Identifier */, 21 /* CloseParenToken */, 23 /* CloseBracketToken */, 95 /* NewKeyword */]; + var comments = [2 /* SingleLineCommentTrivia */, 3 /* MultiLineCommentTrivia */]; + var typeNames = [72 /* Identifier */].concat(ts.typeKeywords); + // Place a space before open brace in a function declaration + // TypeScript: Function can have return types, which can be made of tons of different token kinds + var functionOpenBraceLeftTokenRange = anyTokenIncludingMultilineComments; + // Place a space before open brace in a TypeScript declaration that has braces as children (class, module, enum, etc) + var typeScriptOpenBraceLeftTokenRange = tokenRangeFrom([72 /* Identifier */, 3 /* MultiLineCommentTrivia */, 76 /* ClassKeyword */, 85 /* ExportKeyword */, 92 /* ImportKeyword */]); + // Place a space before open brace in a control flow construct + var controlOpenBraceLeftTokenRange = tokenRangeFrom([21 /* CloseParenToken */, 3 /* MultiLineCommentTrivia */, 82 /* DoKeyword */, 103 /* TryKeyword */, 88 /* FinallyKeyword */, 83 /* ElseKeyword */]); + // These rules are higher in priority than user-configurable + var highPriorityCommonRules = [ + // Leave comments alone + rule("IgnoreBeforeComment", anyToken, comments, formatting.anyContext, 1 /* Ignore */), + rule("IgnoreAfterLineComment", 2 /* SingleLineCommentTrivia */, anyToken, formatting.anyContext, 1 /* Ignore */), + rule("NotSpaceBeforeColon", anyToken, 57 /* ColonToken */, [isNonJsxSameLineTokenContext, isNotBinaryOpContext, isNotTypeAnnotationContext], 8 /* Delete */), + rule("SpaceAfterColon", 57 /* ColonToken */, anyToken, [isNonJsxSameLineTokenContext, isNotBinaryOpContext], 2 /* Space */), + rule("NoSpaceBeforeQuestionMark", anyToken, 56 /* QuestionToken */, [isNonJsxSameLineTokenContext, isNotBinaryOpContext], 8 /* Delete */), + // insert space after '?' only when it is used in conditional operator + rule("SpaceAfterQuestionMarkInConditionalOperator", 56 /* QuestionToken */, anyToken, [isNonJsxSameLineTokenContext, isConditionalOperatorContext], 2 /* Space */), + // in other cases there should be no space between '?' and next token + rule("NoSpaceAfterQuestionMark", 56 /* QuestionToken */, anyToken, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceBeforeDot", anyToken, 24 /* DotToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceAfterDot", 24 /* DotToken */, anyToken, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceBetweenImportParenInImportType", 92 /* ImportKeyword */, 20 /* OpenParenToken */, [isNonJsxSameLineTokenContext, isImportTypeContext], 8 /* Delete */), + // Special handling of unary operators. + // Prefix operators generally shouldn't have a space between + // them and their target unary expression. + rule("NoSpaceAfterUnaryPrefixOperator", unaryPrefixOperators, unaryPrefixExpressions, [isNonJsxSameLineTokenContext, isNotBinaryOpContext], 8 /* Delete */), + rule("NoSpaceAfterUnaryPreincrementOperator", 44 /* PlusPlusToken */, unaryPreincrementExpressions, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceAfterUnaryPredecrementOperator", 45 /* MinusMinusToken */, unaryPredecrementExpressions, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceBeforeUnaryPostincrementOperator", unaryPostincrementExpressions, 44 /* PlusPlusToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceBeforeUnaryPostdecrementOperator", unaryPostdecrementExpressions, 45 /* MinusMinusToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + // More unary operator special-casing. + // DevDiv 181814: Be careful when removing leading whitespace + // around unary operators. Examples: + // 1 - -2 --X--> 1--2 + // a + ++b --X--> a+++b + rule("SpaceAfterPostincrementWhenFollowedByAdd", 44 /* PlusPlusToken */, 38 /* PlusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), + rule("SpaceAfterAddWhenFollowedByUnaryPlus", 38 /* PlusToken */, 38 /* PlusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), + rule("SpaceAfterAddWhenFollowedByPreincrement", 38 /* PlusToken */, 44 /* PlusPlusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), + rule("SpaceAfterPostdecrementWhenFollowedBySubtract", 45 /* MinusMinusToken */, 39 /* MinusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), + rule("SpaceAfterSubtractWhenFollowedByUnaryMinus", 39 /* MinusToken */, 39 /* MinusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), + rule("SpaceAfterSubtractWhenFollowedByPredecrement", 39 /* MinusToken */, 45 /* MinusMinusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), + rule("NoSpaceAfterCloseBrace", 19 /* CloseBraceToken */, [27 /* CommaToken */, 26 /* SemicolonToken */], [isNonJsxSameLineTokenContext], 8 /* Delete */), + // For functions and control block place } on a new line [multi-line rule] + rule("NewLineBeforeCloseBraceInBlockContext", anyTokenIncludingMultilineComments, 19 /* CloseBraceToken */, [isMultilineBlockContext], 4 /* NewLine */), + // Space/new line after }. + rule("SpaceAfterCloseBrace", 19 /* CloseBraceToken */, anyTokenExcept(21 /* CloseParenToken */), [isNonJsxSameLineTokenContext, isAfterCodeBlockContext], 2 /* Space */), + // Special case for (}, else) and (}, while) since else & while tokens are not part of the tree which makes SpaceAfterCloseBrace rule not applied + // Also should not apply to }) + rule("SpaceBetweenCloseBraceAndElse", 19 /* CloseBraceToken */, 83 /* ElseKeyword */, [isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceBetweenCloseBraceAndWhile", 19 /* CloseBraceToken */, 107 /* WhileKeyword */, [isNonJsxSameLineTokenContext], 2 /* Space */), + rule("NoSpaceBetweenEmptyBraceBrackets", 18 /* OpenBraceToken */, 19 /* CloseBraceToken */, [isNonJsxSameLineTokenContext, isObjectContext], 8 /* Delete */), + // Add a space after control dec context if the next character is an open bracket ex: 'if (false)[a, b] = [1, 2];' -> 'if (false) [a, b] = [1, 2];' + rule("SpaceAfterConditionalClosingParen", 21 /* CloseParenToken */, 22 /* OpenBracketToken */, [isControlDeclContext], 2 /* Space */), + rule("NoSpaceBetweenFunctionKeywordAndStar", 90 /* FunctionKeyword */, 40 /* AsteriskToken */, [isFunctionDeclarationOrFunctionExpressionContext], 8 /* Delete */), + rule("SpaceAfterStarInGeneratorDeclaration", 40 /* AsteriskToken */, [72 /* Identifier */, 20 /* OpenParenToken */], [isFunctionDeclarationOrFunctionExpressionContext], 2 /* Space */), + rule("SpaceAfterFunctionInFuncDecl", 90 /* FunctionKeyword */, anyToken, [isFunctionDeclContext], 2 /* Space */), + // Insert new line after { and before } in multi-line contexts. + rule("NewLineAfterOpenBraceInBlockContext", 18 /* OpenBraceToken */, anyToken, [isMultilineBlockContext], 4 /* NewLine */), + // For get/set members, we check for (identifier,identifier) since get/set don't have tokens and they are represented as just an identifier token. + // Though, we do extra check on the context to make sure we are dealing with get/set node. Example: + // get x() {} + // set x(val) {} + rule("SpaceAfterGetSetInMember", [126 /* GetKeyword */, 137 /* SetKeyword */], 72 /* Identifier */, [isFunctionDeclContext], 2 /* Space */), + rule("NoSpaceBetweenYieldKeywordAndStar", 117 /* YieldKeyword */, 40 /* AsteriskToken */, [isNonJsxSameLineTokenContext, isYieldOrYieldStarWithOperand], 8 /* Delete */), + rule("SpaceBetweenYieldOrYieldStarAndOperand", [117 /* YieldKeyword */, 40 /* AsteriskToken */], anyToken, [isNonJsxSameLineTokenContext, isYieldOrYieldStarWithOperand], 2 /* Space */), + rule("NoSpaceBetweenReturnAndSemicolon", 97 /* ReturnKeyword */, 26 /* SemicolonToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("SpaceAfterCertainKeywords", [105 /* VarKeyword */, 101 /* ThrowKeyword */, 95 /* NewKeyword */, 81 /* DeleteKeyword */, 97 /* ReturnKeyword */, 104 /* TypeOfKeyword */, 122 /* AwaitKeyword */], anyToken, [isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceAfterLetConstInVariableDeclaration", [111 /* LetKeyword */, 77 /* ConstKeyword */], anyToken, [isNonJsxSameLineTokenContext, isStartOfVariableDeclarationList], 2 /* Space */), + rule("NoSpaceBeforeOpenParenInFuncCall", anyToken, 20 /* OpenParenToken */, [isNonJsxSameLineTokenContext, isFunctionCallOrNewContext, isPreviousTokenNotComma], 8 /* Delete */), + // Special case for binary operators (that are keywords). For these we have to add a space and shouldn't follow any user options. + rule("SpaceBeforeBinaryKeywordOperator", anyToken, binaryKeywordOperators, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), + rule("SpaceAfterBinaryKeywordOperator", binaryKeywordOperators, anyToken, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), + rule("SpaceAfterVoidOperator", 106 /* VoidKeyword */, anyToken, [isNonJsxSameLineTokenContext, isVoidOpContext], 2 /* Space */), + // Async-await + rule("SpaceBetweenAsyncAndOpenParen", 121 /* AsyncKeyword */, 20 /* OpenParenToken */, [isArrowFunctionContext, isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceBetweenAsyncAndFunctionKeyword", 121 /* AsyncKeyword */, 90 /* FunctionKeyword */, [isNonJsxSameLineTokenContext], 2 /* Space */), + // Template string + rule("NoSpaceBetweenTagAndTemplateString", [72 /* Identifier */, 21 /* CloseParenToken */], [14 /* NoSubstitutionTemplateLiteral */, 15 /* TemplateHead */], [isNonJsxSameLineTokenContext], 8 /* Delete */), + // JSX opening elements + rule("SpaceBeforeJsxAttribute", anyToken, 72 /* Identifier */, [isNextTokenParentJsxAttribute, isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceBeforeSlashInJsxOpeningElement", anyToken, 42 /* SlashToken */, [isJsxSelfClosingElementContext, isNonJsxSameLineTokenContext], 2 /* Space */), + rule("NoSpaceBeforeGreaterThanTokenInJsxOpeningElement", 42 /* SlashToken */, 30 /* GreaterThanToken */, [isJsxSelfClosingElementContext, isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceBeforeEqualInJsxAttribute", anyToken, 59 /* EqualsToken */, [isJsxAttributeContext, isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceAfterEqualInJsxAttribute", 59 /* EqualsToken */, anyToken, [isJsxAttributeContext, isNonJsxSameLineTokenContext], 8 /* Delete */), + // TypeScript-specific rules + // Use of module as a function call. e.g.: import m2 = module("m2"); + rule("NoSpaceAfterModuleImport", [130 /* ModuleKeyword */, 134 /* RequireKeyword */], 20 /* OpenParenToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + // Add a space around certain TypeScript keywords + rule("SpaceAfterCertainTypeScriptKeywords", [ + 118 /* AbstractKeyword */, + 76 /* ClassKeyword */, + 125 /* DeclareKeyword */, + 80 /* DefaultKeyword */, + 84 /* EnumKeyword */, + 85 /* ExportKeyword */, + 86 /* ExtendsKeyword */, + 126 /* GetKeyword */, + 109 /* ImplementsKeyword */, + 92 /* ImportKeyword */, + 110 /* InterfaceKeyword */, + 130 /* ModuleKeyword */, + 131 /* NamespaceKeyword */, + 113 /* PrivateKeyword */, + 115 /* PublicKeyword */, + 114 /* ProtectedKeyword */, + 133 /* ReadonlyKeyword */, + 137 /* SetKeyword */, + 116 /* StaticKeyword */, + 140 /* TypeKeyword */, + 144 /* FromKeyword */, + 129 /* KeyOfKeyword */, + 127 /* InferKeyword */, + ], anyToken, [isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceBeforeCertainTypeScriptKeywords", anyToken, [86 /* ExtendsKeyword */, 109 /* ImplementsKeyword */, 144 /* FromKeyword */], [isNonJsxSameLineTokenContext], 2 /* Space */), + // Treat string literals in module names as identifiers, and add a space between the literal and the opening Brace braces, e.g.: module "m2" { + rule("SpaceAfterModuleName", 10 /* StringLiteral */, 18 /* OpenBraceToken */, [isModuleDeclContext], 2 /* Space */), + // Lambda expressions + rule("SpaceBeforeArrow", anyToken, 37 /* EqualsGreaterThanToken */, [isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceAfterArrow", 37 /* EqualsGreaterThanToken */, anyToken, [isNonJsxSameLineTokenContext], 2 /* Space */), + // Optional parameters and let args + rule("NoSpaceAfterEllipsis", 25 /* DotDotDotToken */, 72 /* Identifier */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceAfterOptionalParameters", 56 /* QuestionToken */, [21 /* CloseParenToken */, 27 /* CommaToken */], [isNonJsxSameLineTokenContext, isNotBinaryOpContext], 8 /* Delete */), + // Remove spaces in empty interface literals. e.g.: x: {} + rule("NoSpaceBetweenEmptyInterfaceBraceBrackets", 18 /* OpenBraceToken */, 19 /* CloseBraceToken */, [isNonJsxSameLineTokenContext, isObjectTypeContext], 8 /* Delete */), + // generics and type assertions + rule("NoSpaceBeforeOpenAngularBracket", typeNames, 28 /* LessThanToken */, [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext], 8 /* Delete */), + rule("NoSpaceBetweenCloseParenAndAngularBracket", 21 /* CloseParenToken */, 28 /* LessThanToken */, [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext], 8 /* Delete */), + rule("NoSpaceAfterOpenAngularBracket", 28 /* LessThanToken */, anyToken, [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext], 8 /* Delete */), + rule("NoSpaceBeforeCloseAngularBracket", anyToken, 30 /* GreaterThanToken */, [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext], 8 /* Delete */), + rule("NoSpaceAfterCloseAngularBracket", 30 /* GreaterThanToken */, [20 /* OpenParenToken */, 22 /* OpenBracketToken */, 30 /* GreaterThanToken */, 27 /* CommaToken */], [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext, isNotFunctionDeclContext /*To prevent an interference with the SpaceBeforeOpenParenInFuncDecl rule*/], 8 /* Delete */), + // decorators + rule("SpaceBeforeAt", [21 /* CloseParenToken */, 72 /* Identifier */], 58 /* AtToken */, [isNonJsxSameLineTokenContext], 2 /* Space */), + rule("NoSpaceAfterAt", 58 /* AtToken */, anyToken, [isNonJsxSameLineTokenContext], 8 /* Delete */), + // Insert space after @ in decorator + rule("SpaceAfterDecorator", anyToken, [ + 118 /* AbstractKeyword */, + 72 /* Identifier */, + 85 /* ExportKeyword */, + 80 /* DefaultKeyword */, + 76 /* ClassKeyword */, + 116 /* StaticKeyword */, + 115 /* PublicKeyword */, + 113 /* PrivateKeyword */, + 114 /* ProtectedKeyword */, + 126 /* GetKeyword */, + 137 /* SetKeyword */, + 22 /* OpenBracketToken */, + 40 /* AsteriskToken */, + ], [isEndOfDecoratorContextOnSameLine], 2 /* Space */), + rule("NoSpaceBeforeNonNullAssertionOperator", anyToken, 52 /* ExclamationToken */, [isNonJsxSameLineTokenContext, isNonNullAssertionContext], 8 /* Delete */), + rule("NoSpaceAfterNewKeywordOnConstructorSignature", 95 /* NewKeyword */, 20 /* OpenParenToken */, [isNonJsxSameLineTokenContext, isConstructorSignatureContext], 8 /* Delete */), + ]; + // These rules are applied after high priority + var userConfigurableRules = [ + // Treat constructor as an identifier in a function declaration, and remove spaces between constructor and following left parentheses + rule("SpaceAfterConstructor", 124 /* ConstructorKeyword */, 20 /* OpenParenToken */, [isOptionEnabled("insertSpaceAfterConstructor"), isNonJsxSameLineTokenContext], 2 /* Space */), + rule("NoSpaceAfterConstructor", 124 /* ConstructorKeyword */, 20 /* OpenParenToken */, [isOptionDisabledOrUndefined("insertSpaceAfterConstructor"), isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("SpaceAfterComma", 27 /* CommaToken */, anyToken, [isOptionEnabled("insertSpaceAfterCommaDelimiter"), isNonJsxSameLineTokenContext, isNonJsxElementOrFragmentContext, isNextTokenNotCloseBracket], 2 /* Space */), + rule("NoSpaceAfterComma", 27 /* CommaToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterCommaDelimiter"), isNonJsxSameLineTokenContext, isNonJsxElementOrFragmentContext], 8 /* Delete */), + // Insert space after function keyword for anonymous functions + rule("SpaceAfterAnonymousFunctionKeyword", 90 /* FunctionKeyword */, 20 /* OpenParenToken */, [isOptionEnabled("insertSpaceAfterFunctionKeywordForAnonymousFunctions"), isFunctionDeclContext], 2 /* Space */), + rule("NoSpaceAfterAnonymousFunctionKeyword", 90 /* FunctionKeyword */, 20 /* OpenParenToken */, [isOptionDisabledOrUndefined("insertSpaceAfterFunctionKeywordForAnonymousFunctions"), isFunctionDeclContext], 8 /* Delete */), + // Insert space after keywords in control flow statements + rule("SpaceAfterKeywordInControl", keywords, 20 /* OpenParenToken */, [isOptionEnabled("insertSpaceAfterKeywordsInControlFlowStatements"), isControlDeclContext], 2 /* Space */), + rule("NoSpaceAfterKeywordInControl", keywords, 20 /* OpenParenToken */, [isOptionDisabledOrUndefined("insertSpaceAfterKeywordsInControlFlowStatements"), isControlDeclContext], 8 /* Delete */), + // Insert space after opening and before closing nonempty parenthesis + rule("SpaceAfterOpenParen", 20 /* OpenParenToken */, anyToken, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceBeforeCloseParen", anyToken, 21 /* CloseParenToken */, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceBetweenOpenParens", 20 /* OpenParenToken */, 20 /* OpenParenToken */, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext], 2 /* Space */), + rule("NoSpaceBetweenParens", 20 /* OpenParenToken */, 21 /* CloseParenToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceAfterOpenParen", 20 /* OpenParenToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceBeforeCloseParen", anyToken, 21 /* CloseParenToken */, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext], 8 /* Delete */), + // Insert space after opening and before closing nonempty brackets + rule("SpaceAfterOpenBracket", 22 /* OpenBracketToken */, anyToken, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceBeforeCloseBracket", anyToken, 23 /* CloseBracketToken */, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), isNonJsxSameLineTokenContext], 2 /* Space */), + rule("NoSpaceBetweenBrackets", 22 /* OpenBracketToken */, 23 /* CloseBracketToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceAfterOpenBracket", 22 /* OpenBracketToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceBeforeCloseBracket", anyToken, 23 /* CloseBracketToken */, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), isNonJsxSameLineTokenContext], 8 /* Delete */), + // Insert a space after { and before } in single-line contexts, but remove space from empty object literals {}. + rule("SpaceAfterOpenBrace", 18 /* OpenBraceToken */, anyToken, [isOptionEnabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), isBraceWrappedContext], 2 /* Space */), + rule("SpaceBeforeCloseBrace", anyToken, 19 /* CloseBraceToken */, [isOptionEnabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), isBraceWrappedContext], 2 /* Space */), + rule("NoSpaceBetweenEmptyBraceBrackets", 18 /* OpenBraceToken */, 19 /* CloseBraceToken */, [isNonJsxSameLineTokenContext, isObjectContext], 8 /* Delete */), + rule("NoSpaceAfterOpenBrace", 18 /* OpenBraceToken */, anyToken, [isOptionDisabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceBeforeCloseBrace", anyToken, 19 /* CloseBraceToken */, [isOptionDisabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), isNonJsxSameLineTokenContext], 8 /* Delete */), + // Insert space after opening and before closing template string braces + rule("SpaceAfterTemplateHeadAndMiddle", [15 /* TemplateHead */, 16 /* TemplateMiddle */], anyToken, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceBeforeTemplateMiddleAndTail", anyToken, [16 /* TemplateMiddle */, 17 /* TemplateTail */], [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), isNonJsxSameLineTokenContext], 2 /* Space */), + rule("NoSpaceAfterTemplateHeadAndMiddle", [15 /* TemplateHead */, 16 /* TemplateMiddle */], anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceBeforeTemplateMiddleAndTail", anyToken, [16 /* TemplateMiddle */, 17 /* TemplateTail */], [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), isNonJsxSameLineTokenContext], 8 /* Delete */), + // No space after { and before } in JSX expression + rule("SpaceAfterOpenBraceInJsxExpression", 18 /* OpenBraceToken */, anyToken, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), isNonJsxSameLineTokenContext, isJsxExpressionContext], 2 /* Space */), + rule("SpaceBeforeCloseBraceInJsxExpression", anyToken, 19 /* CloseBraceToken */, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), isNonJsxSameLineTokenContext, isJsxExpressionContext], 2 /* Space */), + rule("NoSpaceAfterOpenBraceInJsxExpression", 18 /* OpenBraceToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), isNonJsxSameLineTokenContext, isJsxExpressionContext], 8 /* Delete */), + rule("NoSpaceBeforeCloseBraceInJsxExpression", anyToken, 19 /* CloseBraceToken */, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), isNonJsxSameLineTokenContext, isJsxExpressionContext], 8 /* Delete */), + // Insert space after semicolon in for statement + rule("SpaceAfterSemicolonInFor", 26 /* SemicolonToken */, anyToken, [isOptionEnabled("insertSpaceAfterSemicolonInForStatements"), isNonJsxSameLineTokenContext, isForContext], 2 /* Space */), + rule("NoSpaceAfterSemicolonInFor", 26 /* SemicolonToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterSemicolonInForStatements"), isNonJsxSameLineTokenContext, isForContext], 8 /* Delete */), + // Insert space before and after binary operators + rule("SpaceBeforeBinaryOperator", anyToken, binaryOperators, [isOptionEnabled("insertSpaceBeforeAndAfterBinaryOperators"), isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), + rule("SpaceAfterBinaryOperator", binaryOperators, anyToken, [isOptionEnabled("insertSpaceBeforeAndAfterBinaryOperators"), isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), + rule("NoSpaceBeforeBinaryOperator", anyToken, binaryOperators, [isOptionDisabledOrUndefined("insertSpaceBeforeAndAfterBinaryOperators"), isNonJsxSameLineTokenContext, isBinaryOpContext], 8 /* Delete */), + rule("NoSpaceAfterBinaryOperator", binaryOperators, anyToken, [isOptionDisabledOrUndefined("insertSpaceBeforeAndAfterBinaryOperators"), isNonJsxSameLineTokenContext, isBinaryOpContext], 8 /* Delete */), + rule("SpaceBeforeOpenParenInFuncDecl", anyToken, 20 /* OpenParenToken */, [isOptionEnabled("insertSpaceBeforeFunctionParenthesis"), isNonJsxSameLineTokenContext, isFunctionDeclContext], 2 /* Space */), + rule("NoSpaceBeforeOpenParenInFuncDecl", anyToken, 20 /* OpenParenToken */, [isOptionDisabledOrUndefined("insertSpaceBeforeFunctionParenthesis"), isNonJsxSameLineTokenContext, isFunctionDeclContext], 8 /* Delete */), + // Open Brace braces after control block + rule("NewLineBeforeOpenBraceInControl", controlOpenBraceLeftTokenRange, 18 /* OpenBraceToken */, [isOptionEnabled("placeOpenBraceOnNewLineForControlBlocks"), isControlDeclContext, isBeforeMultilineBlockContext], 4 /* NewLine */, 1 /* CanDeleteNewLines */), + // Open Brace braces after function + // TypeScript: Function can have return types, which can be made of tons of different token kinds + rule("NewLineBeforeOpenBraceInFunction", functionOpenBraceLeftTokenRange, 18 /* OpenBraceToken */, [isOptionEnabled("placeOpenBraceOnNewLineForFunctions"), isFunctionDeclContext, isBeforeMultilineBlockContext], 4 /* NewLine */, 1 /* CanDeleteNewLines */), + // Open Brace braces after TypeScript module/class/interface + rule("NewLineBeforeOpenBraceInTypeScriptDeclWithBlock", typeScriptOpenBraceLeftTokenRange, 18 /* OpenBraceToken */, [isOptionEnabled("placeOpenBraceOnNewLineForFunctions"), isTypeScriptDeclWithBlockContext, isBeforeMultilineBlockContext], 4 /* NewLine */, 1 /* CanDeleteNewLines */), + rule("SpaceAfterTypeAssertion", 30 /* GreaterThanToken */, anyToken, [isOptionEnabled("insertSpaceAfterTypeAssertion"), isNonJsxSameLineTokenContext, isTypeAssertionContext], 2 /* Space */), + rule("NoSpaceAfterTypeAssertion", 30 /* GreaterThanToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterTypeAssertion"), isNonJsxSameLineTokenContext, isTypeAssertionContext], 8 /* Delete */), + rule("SpaceBeforeTypeAnnotation", anyToken, 57 /* ColonToken */, [isOptionEnabled("insertSpaceBeforeTypeAnnotation"), isNonJsxSameLineTokenContext, isTypeAnnotationContext], 2 /* Space */), + rule("NoSpaceBeforeTypeAnnotation", anyToken, 57 /* ColonToken */, [isOptionDisabledOrUndefined("insertSpaceBeforeTypeAnnotation"), isNonJsxSameLineTokenContext, isTypeAnnotationContext], 8 /* Delete */), + ]; + // These rules are lower in priority than user-configurable. Rules earlier in this list have priority over rules later in the list. + var lowPriorityCommonRules = [ + // Space after keyword but not before ; or : or ? + rule("NoSpaceBeforeSemicolon", anyToken, 26 /* SemicolonToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("SpaceBeforeOpenBraceInControl", controlOpenBraceLeftTokenRange, 18 /* OpenBraceToken */, [isOptionDisabledOrUndefinedOrTokensOnSameLine("placeOpenBraceOnNewLineForControlBlocks"), isControlDeclContext, isNotFormatOnEnter, isSameLineTokenOrBeforeBlockContext], 2 /* Space */, 1 /* CanDeleteNewLines */), + rule("SpaceBeforeOpenBraceInFunction", functionOpenBraceLeftTokenRange, 18 /* OpenBraceToken */, [isOptionDisabledOrUndefinedOrTokensOnSameLine("placeOpenBraceOnNewLineForFunctions"), isFunctionDeclContext, isBeforeBlockContext, isNotFormatOnEnter, isSameLineTokenOrBeforeBlockContext], 2 /* Space */, 1 /* CanDeleteNewLines */), + rule("SpaceBeforeOpenBraceInTypeScriptDeclWithBlock", typeScriptOpenBraceLeftTokenRange, 18 /* OpenBraceToken */, [isOptionDisabledOrUndefinedOrTokensOnSameLine("placeOpenBraceOnNewLineForFunctions"), isTypeScriptDeclWithBlockContext, isNotFormatOnEnter, isSameLineTokenOrBeforeBlockContext], 2 /* Space */, 1 /* CanDeleteNewLines */), + rule("NoSpaceBeforeComma", anyToken, 27 /* CommaToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + // No space before and after indexer `x[]` + rule("NoSpaceBeforeOpenBracket", anyTokenExcept(121 /* AsyncKeyword */, 74 /* CaseKeyword */), 22 /* OpenBracketToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceAfterCloseBracket", 23 /* CloseBracketToken */, anyToken, [isNonJsxSameLineTokenContext, isNotBeforeBlockInFunctionDeclarationContext], 8 /* Delete */), + rule("SpaceAfterSemicolon", 26 /* SemicolonToken */, anyToken, [isNonJsxSameLineTokenContext], 2 /* Space */), + // Remove extra space between for and await + rule("SpaceBetweenForAndAwaitKeyword", 89 /* ForKeyword */, 122 /* AwaitKeyword */, [isNonJsxSameLineTokenContext], 2 /* Space */), + // Add a space between statements. All keywords except (do,else,case) has open/close parens after them. + // So, we have a rule to add a space for [),Any], [do,Any], [else,Any], and [case,Any] + rule("SpaceBetweenStatements", [21 /* CloseParenToken */, 82 /* DoKeyword */, 83 /* ElseKeyword */, 74 /* CaseKeyword */], anyToken, [isNonJsxSameLineTokenContext, isNonJsxElementOrFragmentContext, isNotForContext], 2 /* Space */), + // This low-pri rule takes care of "try {" and "finally {" in case the rule SpaceBeforeOpenBraceInControl didn't execute on FormatOnEnter. + rule("SpaceAfterTryFinally", [103 /* TryKeyword */, 88 /* FinallyKeyword */], 18 /* OpenBraceToken */, [isNonJsxSameLineTokenContext], 2 /* Space */), + ]; + return highPriorityCommonRules.concat(userConfigurableRules, lowPriorityCommonRules); + } + formatting.getAllRules = getAllRules; + function rule(debugName, left, right, context, action, flags) { + if (flags === void 0) { flags = 0 /* None */; } + return { leftTokenRange: toTokenRange(left), rightTokenRange: toTokenRange(right), rule: { debugName: debugName, context: context, action: action, flags: flags } }; + } + function tokenRangeFrom(tokens) { + return { tokens: tokens, isSpecific: true }; + } + function toTokenRange(arg) { + return typeof arg === "number" ? tokenRangeFrom([arg]) : ts.isArray(arg) ? tokenRangeFrom(arg) : arg; + } + function tokenRangeFromRange(from, to, except) { + if (except === void 0) { except = []; } + var tokens = []; + for (var token = from; token <= to; token++) { + if (!ts.contains(except, token)) { + tokens.push(token); + } + } + return tokenRangeFrom(tokens); + } + /// + /// Contexts + /// + function isOptionEnabled(optionName) { + return function (context) { return context.options && context.options.hasOwnProperty(optionName) && !!context.options[optionName]; }; + } + function isOptionDisabled(optionName) { + return function (context) { return context.options && context.options.hasOwnProperty(optionName) && !context.options[optionName]; }; + } + function isOptionDisabledOrUndefined(optionName) { + return function (context) { return !context.options || !context.options.hasOwnProperty(optionName) || !context.options[optionName]; }; + } + function isOptionDisabledOrUndefinedOrTokensOnSameLine(optionName) { + return function (context) { return !context.options || !context.options.hasOwnProperty(optionName) || !context.options[optionName] || context.TokensAreOnSameLine(); }; + } + function isOptionEnabledOrUndefined(optionName) { + return function (context) { return !context.options || !context.options.hasOwnProperty(optionName) || !!context.options[optionName]; }; + } + function isForContext(context) { + return context.contextNode.kind === 225 /* ForStatement */; + } + function isNotForContext(context) { + return !isForContext(context); + } + function isBinaryOpContext(context) { + switch (context.contextNode.kind) { + case 204 /* BinaryExpression */: + case 205 /* ConditionalExpression */: + case 175 /* ConditionalType */: + case 212 /* AsExpression */: + case 257 /* ExportSpecifier */: + case 253 /* ImportSpecifier */: + case 163 /* TypePredicate */: + case 173 /* UnionType */: + case 174 /* IntersectionType */: + return true; + // equals in binding elements: function foo([[x, y] = [1, 2]]) + case 186 /* BindingElement */: + // equals in type X = ... + case 242 /* TypeAliasDeclaration */: + // equal in import a = module('a'); + case 248 /* ImportEqualsDeclaration */: + // equal in let a = 0; + case 237 /* VariableDeclaration */: + // equal in p = 0; + case 151 /* Parameter */: + case 278 /* EnumMember */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + return context.currentTokenSpan.kind === 59 /* EqualsToken */ || context.nextTokenSpan.kind === 59 /* EqualsToken */; + // "in" keyword in for (let x in []) { } + case 226 /* ForInStatement */: + // "in" keyword in [P in keyof T]: T[P] + case 150 /* TypeParameter */: + return context.currentTokenSpan.kind === 93 /* InKeyword */ || context.nextTokenSpan.kind === 93 /* InKeyword */; + // Technically, "of" is not a binary operator, but format it the same way as "in" + case 227 /* ForOfStatement */: + return context.currentTokenSpan.kind === 147 /* OfKeyword */ || context.nextTokenSpan.kind === 147 /* OfKeyword */; + } + return false; + } + function isNotBinaryOpContext(context) { + return !isBinaryOpContext(context); + } + function isNotTypeAnnotationContext(context) { + return !isTypeAnnotationContext(context); + } + function isTypeAnnotationContext(context) { + var contextKind = context.contextNode.kind; + return contextKind === 154 /* PropertyDeclaration */ || + contextKind === 153 /* PropertySignature */ || + contextKind === 151 /* Parameter */ || + contextKind === 237 /* VariableDeclaration */ || + ts.isFunctionLikeKind(contextKind); + } + function isConditionalOperatorContext(context) { + return context.contextNode.kind === 205 /* ConditionalExpression */ || + context.contextNode.kind === 175 /* ConditionalType */; + } + function isSameLineTokenOrBeforeBlockContext(context) { + return context.TokensAreOnSameLine() || isBeforeBlockContext(context); + } + function isBraceWrappedContext(context) { + return context.contextNode.kind === 184 /* ObjectBindingPattern */ || + context.contextNode.kind === 181 /* MappedType */ || + isSingleLineBlockContext(context); + } + // This check is done before an open brace in a control construct, a function, or a typescript block declaration + function isBeforeMultilineBlockContext(context) { + return isBeforeBlockContext(context) && !(context.NextNodeAllOnSameLine() || context.NextNodeBlockIsOnOneLine()); + } + function isMultilineBlockContext(context) { + return isBlockContext(context) && !(context.ContextNodeAllOnSameLine() || context.ContextNodeBlockIsOnOneLine()); + } + function isSingleLineBlockContext(context) { + return isBlockContext(context) && (context.ContextNodeAllOnSameLine() || context.ContextNodeBlockIsOnOneLine()); + } + function isBlockContext(context) { + return nodeIsBlockContext(context.contextNode); + } + function isBeforeBlockContext(context) { + return nodeIsBlockContext(context.nextTokenParent); + } + // IMPORTANT!!! This method must return true ONLY for nodes with open and close braces as immediate children + function nodeIsBlockContext(node) { + if (nodeIsTypeScriptDeclWithBlockContext(node)) { + // This means we are in a context that looks like a block to the user, but in the grammar is actually not a node (it's a class, module, enum, object type literal, etc). + return true; + } + switch (node.kind) { + case 218 /* Block */: + case 246 /* CaseBlock */: + case 188 /* ObjectLiteralExpression */: + case 245 /* ModuleBlock */: + return true; + } + return false; + } + function isFunctionDeclContext(context) { + switch (context.contextNode.kind) { + case 239 /* FunctionDeclaration */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + // case SyntaxKind.MemberFunctionDeclaration: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + // case SyntaxKind.MethodSignature: + case 160 /* CallSignature */: + case 196 /* FunctionExpression */: + case 157 /* Constructor */: + case 197 /* ArrowFunction */: + // case SyntaxKind.ConstructorDeclaration: + // case SyntaxKind.SimpleArrowFunctionExpression: + // case SyntaxKind.ParenthesizedArrowFunctionExpression: + case 241 /* InterfaceDeclaration */: // This one is not truly a function, but for formatting purposes, it acts just like one + return true; + } + return false; + } + function isNotFunctionDeclContext(context) { + return !isFunctionDeclContext(context); + } + function isFunctionDeclarationOrFunctionExpressionContext(context) { + return context.contextNode.kind === 239 /* FunctionDeclaration */ || context.contextNode.kind === 196 /* FunctionExpression */; + } + function isTypeScriptDeclWithBlockContext(context) { + return nodeIsTypeScriptDeclWithBlockContext(context.contextNode); + } + function nodeIsTypeScriptDeclWithBlockContext(node) { + switch (node.kind) { + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 241 /* InterfaceDeclaration */: + case 243 /* EnumDeclaration */: + case 168 /* TypeLiteral */: + case 244 /* ModuleDeclaration */: + case 255 /* ExportDeclaration */: + case 256 /* NamedExports */: + case 249 /* ImportDeclaration */: + case 252 /* NamedImports */: + return true; + } + return false; + } + function isAfterCodeBlockContext(context) { + switch (context.currentTokenParent.kind) { + case 240 /* ClassDeclaration */: + case 244 /* ModuleDeclaration */: + case 243 /* EnumDeclaration */: + case 274 /* CatchClause */: + case 245 /* ModuleBlock */: + case 232 /* SwitchStatement */: + return true; + case 218 /* Block */: { + var blockParent = context.currentTokenParent.parent; + // In a codefix scenario, we can't rely on parents being set. So just always return true. + if (!blockParent || blockParent.kind !== 197 /* ArrowFunction */ && blockParent.kind !== 196 /* FunctionExpression */) { + return true; + } + } + } + return false; + } + function isControlDeclContext(context) { + switch (context.contextNode.kind) { + case 222 /* IfStatement */: + case 232 /* SwitchStatement */: + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + case 224 /* WhileStatement */: + case 235 /* TryStatement */: + case 223 /* DoStatement */: + case 231 /* WithStatement */: + // TODO + // case SyntaxKind.ElseClause: + case 274 /* CatchClause */: + return true; + default: + return false; + } + } + function isObjectContext(context) { + return context.contextNode.kind === 188 /* ObjectLiteralExpression */; + } + function isFunctionCallContext(context) { + return context.contextNode.kind === 191 /* CallExpression */; + } + function isNewContext(context) { + return context.contextNode.kind === 192 /* NewExpression */; + } + function isFunctionCallOrNewContext(context) { + return isFunctionCallContext(context) || isNewContext(context); + } + function isPreviousTokenNotComma(context) { + return context.currentTokenSpan.kind !== 27 /* CommaToken */; + } + function isNextTokenNotCloseBracket(context) { + return context.nextTokenSpan.kind !== 23 /* CloseBracketToken */; + } + function isArrowFunctionContext(context) { + return context.contextNode.kind === 197 /* ArrowFunction */; + } + function isImportTypeContext(context) { + return context.contextNode.kind === 183 /* ImportType */; + } + function isNonJsxSameLineTokenContext(context) { + return context.TokensAreOnSameLine() && context.contextNode.kind !== 11 /* JsxText */; + } + function isNonJsxElementOrFragmentContext(context) { + return context.contextNode.kind !== 260 /* JsxElement */ && context.contextNode.kind !== 264 /* JsxFragment */; + } + function isJsxExpressionContext(context) { + return context.contextNode.kind === 270 /* JsxExpression */ || context.contextNode.kind === 269 /* JsxSpreadAttribute */; + } + function isNextTokenParentJsxAttribute(context) { + return context.nextTokenParent.kind === 267 /* JsxAttribute */; + } + function isJsxAttributeContext(context) { + return context.contextNode.kind === 267 /* JsxAttribute */; + } + function isJsxSelfClosingElementContext(context) { + return context.contextNode.kind === 261 /* JsxSelfClosingElement */; + } + function isNotBeforeBlockInFunctionDeclarationContext(context) { + return !isFunctionDeclContext(context) && !isBeforeBlockContext(context); + } + function isEndOfDecoratorContextOnSameLine(context) { + return context.TokensAreOnSameLine() && + !!context.contextNode.decorators && + nodeIsInDecoratorContext(context.currentTokenParent) && + !nodeIsInDecoratorContext(context.nextTokenParent); + } + function nodeIsInDecoratorContext(node) { + while (ts.isExpressionNode(node)) { + node = node.parent; + } + return node.kind === 152 /* Decorator */; + } + function isStartOfVariableDeclarationList(context) { + return context.currentTokenParent.kind === 238 /* VariableDeclarationList */ && + context.currentTokenParent.getStart(context.sourceFile) === context.currentTokenSpan.pos; + } + function isNotFormatOnEnter(context) { + return context.formattingRequestKind !== 2 /* FormatOnEnter */; + } + function isModuleDeclContext(context) { + return context.contextNode.kind === 244 /* ModuleDeclaration */; + } + function isObjectTypeContext(context) { + return context.contextNode.kind === 168 /* TypeLiteral */; // && context.contextNode.parent.kind !== SyntaxKind.InterfaceDeclaration; + } + function isConstructorSignatureContext(context) { + return context.contextNode.kind === 161 /* ConstructSignature */; + } + function isTypeArgumentOrParameterOrAssertion(token, parent) { + if (token.kind !== 28 /* LessThanToken */ && token.kind !== 30 /* GreaterThanToken */) { + return false; + } + switch (parent.kind) { + case 164 /* TypeReference */: + case 194 /* TypeAssertionExpression */: + case 242 /* TypeAliasDeclaration */: + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 241 /* InterfaceDeclaration */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 191 /* CallExpression */: + case 192 /* NewExpression */: + case 211 /* ExpressionWithTypeArguments */: + return true; + default: + return false; + } + } + function isTypeArgumentOrParameterOrAssertionContext(context) { + return isTypeArgumentOrParameterOrAssertion(context.currentTokenSpan, context.currentTokenParent) || + isTypeArgumentOrParameterOrAssertion(context.nextTokenSpan, context.nextTokenParent); + } + function isTypeAssertionContext(context) { + return context.contextNode.kind === 194 /* TypeAssertionExpression */; + } + function isVoidOpContext(context) { + return context.currentTokenSpan.kind === 106 /* VoidKeyword */ && context.currentTokenParent.kind === 200 /* VoidExpression */; + } + function isYieldOrYieldStarWithOperand(context) { + return context.contextNode.kind === 207 /* YieldExpression */ && context.contextNode.expression !== undefined; + } + function isNonNullAssertionContext(context) { + return context.contextNode.kind === 213 /* NonNullExpression */; + } + })(formatting = ts.formatting || (ts.formatting = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var formatting; + (function (formatting) { + function getFormatContext(options) { + return { options: options, getRule: getRulesMap() }; + } + formatting.getFormatContext = getFormatContext; + var rulesMapCache; + function getRulesMap() { + if (rulesMapCache === undefined) { + rulesMapCache = createRulesMap(formatting.getAllRules()); + } + return rulesMapCache; + } + function createRulesMap(rules) { + var map = buildMap(rules); + return function (context) { + var bucket = map[getRuleBucketIndex(context.currentTokenSpan.kind, context.nextTokenSpan.kind)]; + return bucket && ts.find(bucket, function (rule) { return ts.every(rule.context, function (c) { return c(context); }); }); + }; + } + function buildMap(rules) { + // Map from bucket index to array of rules + var map = new Array(mapRowLength * mapRowLength); + // This array is used only during construction of the rulesbucket in the map + var rulesBucketConstructionStateList = new Array(map.length); + for (var _i = 0, rules_1 = rules; _i < rules_1.length; _i++) { + var rule = rules_1[_i]; + var specificRule = rule.leftTokenRange.isSpecific && rule.rightTokenRange.isSpecific; + for (var _a = 0, _b = rule.leftTokenRange.tokens; _a < _b.length; _a++) { + var left = _b[_a]; + for (var _c = 0, _d = rule.rightTokenRange.tokens; _c < _d.length; _c++) { + var right = _d[_c]; + var index = getRuleBucketIndex(left, right); + var rulesBucket = map[index]; + if (rulesBucket === undefined) { + rulesBucket = map[index] = []; + } + addRule(rulesBucket, rule.rule, specificRule, rulesBucketConstructionStateList, index); + } + } + } + return map; + } + function getRuleBucketIndex(row, column) { + ts.Debug.assert(row <= 147 /* LastKeyword */ && column <= 147 /* LastKeyword */, "Must compute formatting context from tokens"); + return (row * mapRowLength) + column; + } + var maskBitSize = 5; + var mask = 31; // MaskBitSize bits + var mapRowLength = 147 /* LastToken */ + 1; + var RulesPosition; + (function (RulesPosition) { + RulesPosition[RulesPosition["IgnoreRulesSpecific"] = 0] = "IgnoreRulesSpecific"; + RulesPosition[RulesPosition["IgnoreRulesAny"] = maskBitSize * 1] = "IgnoreRulesAny"; + RulesPosition[RulesPosition["ContextRulesSpecific"] = maskBitSize * 2] = "ContextRulesSpecific"; + RulesPosition[RulesPosition["ContextRulesAny"] = maskBitSize * 3] = "ContextRulesAny"; + RulesPosition[RulesPosition["NoContextRulesSpecific"] = maskBitSize * 4] = "NoContextRulesSpecific"; + RulesPosition[RulesPosition["NoContextRulesAny"] = maskBitSize * 5] = "NoContextRulesAny"; + })(RulesPosition || (RulesPosition = {})); + // The Rules list contains all the inserted rules into a rulebucket in the following order: + // 1- Ignore rules with specific token combination + // 2- Ignore rules with any token combination + // 3- Context rules with specific token combination + // 4- Context rules with any token combination + // 5- Non-context rules with specific token combination + // 6- Non-context rules with any token combination + // + // The member rulesInsertionIndexBitmap is used to describe the number of rules + // in each sub-bucket (above) hence can be used to know the index of where to insert + // the next rule. It's a bitmap which contains 6 different sections each is given 5 bits. + // + // Example: + // In order to insert a rule to the end of sub-bucket (3), we get the index by adding + // the values in the bitmap segments 3rd, 2nd, and 1st. + function addRule(rules, rule, specificTokens, constructionState, rulesBucketIndex) { + var position = rule.action === 1 /* Ignore */ + ? specificTokens ? RulesPosition.IgnoreRulesSpecific : RulesPosition.IgnoreRulesAny + : rule.context !== formatting.anyContext + ? specificTokens ? RulesPosition.ContextRulesSpecific : RulesPosition.ContextRulesAny + : specificTokens ? RulesPosition.NoContextRulesSpecific : RulesPosition.NoContextRulesAny; + var state = constructionState[rulesBucketIndex] || 0; + rules.splice(getInsertionIndex(state, position), 0, rule); + constructionState[rulesBucketIndex] = increaseInsertionIndex(state, position); + } + function getInsertionIndex(indexBitmap, maskPosition) { + var index = 0; + for (var pos = 0; pos <= maskPosition; pos += maskBitSize) { + index += indexBitmap & mask; + indexBitmap >>= maskBitSize; + } + return index; + } + function increaseInsertionIndex(indexBitmap, maskPosition) { + var value = ((indexBitmap >> maskPosition) & mask) + 1; + ts.Debug.assert((value & mask) === value, "Adding more rules into the sub-bucket than allowed. Maximum allowed is 32 rules."); + return (indexBitmap & ~(mask << maskPosition)) | (value << maskPosition); + } + })(formatting = ts.formatting || (ts.formatting = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var formatting; + (function (formatting) { + var Constants; + (function (Constants) { + Constants[Constants["Unknown"] = -1] = "Unknown"; + })(Constants || (Constants = {})); + function formatOnEnter(position, sourceFile, formatContext) { + var line = sourceFile.getLineAndCharacterOfPosition(position).line; + if (line === 0) { + return []; + } + // After the enter key, the cursor is now at a new line. The new line may or may not contain non-whitespace characters. + // If the new line has only whitespaces, we won't want to format this line, because that would remove the indentation as + // trailing whitespaces. So the end of the formatting span should be the later one between: + // 1. the end of the previous line + // 2. the last non-whitespace character in the current line + var endOfFormatSpan = ts.getEndLinePosition(line, sourceFile); + while (ts.isWhiteSpaceSingleLine(sourceFile.text.charCodeAt(endOfFormatSpan))) { + endOfFormatSpan--; + } + // if the character at the end of the span is a line break, we shouldn't include it, because it indicates we don't want to + // touch the current line at all. Also, on some OSes the line break consists of two characters (\r\n), we should test if the + // previous character before the end of format span is line break character as well. + if (ts.isLineBreak(sourceFile.text.charCodeAt(endOfFormatSpan))) { + endOfFormatSpan--; + } + var span = { + // get start position for the previous line + pos: ts.getStartPositionOfLine(line - 1, sourceFile), + // end value is exclusive so add 1 to the result + end: endOfFormatSpan + 1 + }; + return formatSpan(span, sourceFile, formatContext, 2 /* FormatOnEnter */); + } + formatting.formatOnEnter = formatOnEnter; + function formatOnSemicolon(position, sourceFile, formatContext) { + var semicolon = findImmediatelyPrecedingTokenOfKind(position, 26 /* SemicolonToken */, sourceFile); + return formatNodeLines(findOutermostNodeWithinListLevel(semicolon), sourceFile, formatContext, 3 /* FormatOnSemicolon */); + } + formatting.formatOnSemicolon = formatOnSemicolon; + function formatOnOpeningCurly(position, sourceFile, formatContext) { + var openingCurly = findImmediatelyPrecedingTokenOfKind(position, 18 /* OpenBraceToken */, sourceFile); + if (!openingCurly) { + return []; + } + var curlyBraceRange = openingCurly.parent; + var outermostNode = findOutermostNodeWithinListLevel(curlyBraceRange); + /** + * We limit the span to end at the opening curly to handle the case where + * the brace matched to that just typed will be incorrect after further edits. + * For example, we could type the opening curly for the following method + * body without brace-matching activated: + * ``` + * class C { + * foo() + * } + * ``` + * and we wouldn't want to move the closing brace. + */ + var textRange = { + pos: ts.getLineStartPositionForPosition(outermostNode.getStart(sourceFile), sourceFile), + end: position + }; + return formatSpan(textRange, sourceFile, formatContext, 4 /* FormatOnOpeningCurlyBrace */); + } + formatting.formatOnOpeningCurly = formatOnOpeningCurly; + function formatOnClosingCurly(position, sourceFile, formatContext) { + var precedingToken = findImmediatelyPrecedingTokenOfKind(position, 19 /* CloseBraceToken */, sourceFile); + return formatNodeLines(findOutermostNodeWithinListLevel(precedingToken), sourceFile, formatContext, 5 /* FormatOnClosingCurlyBrace */); + } + formatting.formatOnClosingCurly = formatOnClosingCurly; + function formatDocument(sourceFile, formatContext) { + var span = { + pos: 0, + end: sourceFile.text.length + }; + return formatSpan(span, sourceFile, formatContext, 0 /* FormatDocument */); + } + formatting.formatDocument = formatDocument; + function formatSelection(start, end, sourceFile, formatContext) { + // format from the beginning of the line + var span = { + pos: ts.getLineStartPositionForPosition(start, sourceFile), + end: end, + }; + return formatSpan(span, sourceFile, formatContext, 1 /* FormatSelection */); + } + formatting.formatSelection = formatSelection; + /** + * Validating `expectedTokenKind` ensures the token was typed in the context we expect (eg: not a comment). + * @param expectedTokenKind The kind of the last token constituting the desired parent node. + */ + function findImmediatelyPrecedingTokenOfKind(end, expectedTokenKind, sourceFile) { + var precedingToken = ts.findPrecedingToken(end, sourceFile); + return precedingToken && precedingToken.kind === expectedTokenKind && end === precedingToken.getEnd() ? + precedingToken : + undefined; + } + /** + * Finds the highest node enclosing `node` at the same list level as `node` + * and whose end does not exceed `node.end`. + * + * Consider typing the following + * ``` + * let x = 1; + * while (true) { + * } + * ``` + * Upon typing the closing curly, we want to format the entire `while`-statement, but not the preceding + * variable declaration. + */ + function findOutermostNodeWithinListLevel(node) { + var current = node; + while (current && + current.parent && + current.parent.end === node.end && + !isListElement(current.parent, current)) { + current = current.parent; + } + return current; + } + // Returns true if node is a element in some list in parent + // i.e. parent is class declaration with the list of members and node is one of members. + function isListElement(parent, node) { + switch (parent.kind) { + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + return ts.rangeContainsRange(parent.members, node); + case 244 /* ModuleDeclaration */: + var body = parent.body; + return !!body && body.kind === 245 /* ModuleBlock */ && ts.rangeContainsRange(body.statements, node); + case 279 /* SourceFile */: + case 218 /* Block */: + case 245 /* ModuleBlock */: + return ts.rangeContainsRange(parent.statements, node); + case 274 /* CatchClause */: + return ts.rangeContainsRange(parent.block.statements, node); + } + return false; + } + /** find node that fully contains given text range */ + function findEnclosingNode(range, sourceFile) { + return find(sourceFile); + function find(n) { + var candidate = ts.forEachChild(n, function (c) { return ts.startEndContainsRange(c.getStart(sourceFile), c.end, range) && c; }); + if (candidate) { + var result = find(candidate); + if (result) { + return result; + } + } + return n; + } + } + /** formatting is not applied to ranges that contain parse errors. + * This function will return a predicate that for a given text range will tell + * if there are any parse errors that overlap with the range. + */ + function prepareRangeContainsErrorFunction(errors, originalRange) { + if (!errors.length) { + return rangeHasNoErrors; + } + // pick only errors that fall in range + var sorted = errors + .filter(function (d) { return ts.rangeOverlapsWithStartEnd(originalRange, d.start, d.start + d.length); }) // TODO: GH#18217 + .sort(function (e1, e2) { return e1.start - e2.start; }); + if (!sorted.length) { + return rangeHasNoErrors; + } + var index = 0; + return function (r) { + // in current implementation sequence of arguments [r1, r2...] is monotonically increasing. + // 'index' tracks the index of the most recent error that was checked. + while (true) { + if (index >= sorted.length) { + // all errors in the range were already checked -> no error in specified range + return false; + } + var error = sorted[index]; + if (r.end <= error.start) { + // specified range ends before the error refered by 'index' - no error in range + return false; + } + if (ts.startEndOverlapsWithStartEnd(r.pos, r.end, error.start, error.start + error.length)) { + // specified range overlaps with error range + return true; + } + index++; + } + }; + function rangeHasNoErrors() { + return false; + } + } + /** + * Start of the original range might fall inside the comment - scanner will not yield appropriate results + * This function will look for token that is located before the start of target range + * and return its end as start position for the scanner. + */ + function getScanStartPosition(enclosingNode, originalRange, sourceFile) { + var start = enclosingNode.getStart(sourceFile); + if (start === originalRange.pos && enclosingNode.end === originalRange.end) { + return start; + } + var precedingToken = ts.findPrecedingToken(originalRange.pos, sourceFile); + if (!precedingToken) { + // no preceding token found - start from the beginning of enclosing node + return enclosingNode.pos; + } + // preceding token ends after the start of original range (i.e when originalRange.pos falls in the middle of literal) + // start from the beginning of enclosingNode to handle the entire 'originalRange' + if (precedingToken.end >= originalRange.pos) { + return enclosingNode.pos; + } + return precedingToken.end; + } + /* + * For cases like + * if (a || + * b ||$ + * c) {...} + * If we hit Enter at $ we want line ' b ||' to be indented. + * Formatting will be applied to the last two lines. + * Node that fully encloses these lines is binary expression 'a ||...'. + * Initial indentation for this node will be 0. + * Binary expressions don't introduce new indentation scopes, however it is possible + * that some parent node on the same line does - like if statement in this case. + * Note that we are considering parents only from the same line with initial node - + * if parent is on the different line - its delta was already contributed + * to the initial indentation. + */ + function getOwnOrInheritedDelta(n, options, sourceFile) { + var previousLine = -1 /* Unknown */; + var child; + while (n) { + var line = sourceFile.getLineAndCharacterOfPosition(n.getStart(sourceFile)).line; + if (previousLine !== -1 /* Unknown */ && line !== previousLine) { + break; + } + if (formatting.SmartIndenter.shouldIndentChildNode(options, n, child, sourceFile)) { + return options.indentSize; + } + previousLine = line; + child = n; + n = n.parent; + } + return 0; + } + function formatNodeGivenIndentation(node, sourceFileLike, languageVariant, initialIndentation, delta, formatContext) { + var range = { pos: 0, end: sourceFileLike.text.length }; + return formatting.getFormattingScanner(sourceFileLike.text, languageVariant, range.pos, range.end, function (scanner) { return formatSpanWorker(range, node, initialIndentation, delta, scanner, formatContext, 1 /* FormatSelection */, function (_) { return false; }, // assume that node does not have any errors + sourceFileLike); }); + } + formatting.formatNodeGivenIndentation = formatNodeGivenIndentation; + function formatNodeLines(node, sourceFile, formatContext, requestKind) { + if (!node) { + return []; + } + var span = { + pos: ts.getLineStartPositionForPosition(node.getStart(sourceFile), sourceFile), + end: node.end + }; + return formatSpan(span, sourceFile, formatContext, requestKind); + } + function formatSpan(originalRange, sourceFile, formatContext, requestKind) { + // find the smallest node that fully wraps the range and compute the initial indentation for the node + var enclosingNode = findEnclosingNode(originalRange, sourceFile); + return formatting.getFormattingScanner(sourceFile.text, sourceFile.languageVariant, getScanStartPosition(enclosingNode, originalRange, sourceFile), originalRange.end, function (scanner) { return formatSpanWorker(originalRange, enclosingNode, formatting.SmartIndenter.getIndentationForNode(enclosingNode, originalRange, sourceFile, formatContext.options), getOwnOrInheritedDelta(enclosingNode, formatContext.options, sourceFile), scanner, formatContext, requestKind, prepareRangeContainsErrorFunction(sourceFile.parseDiagnostics, originalRange), sourceFile); }); + } + function formatSpanWorker(originalRange, enclosingNode, initialIndentation, delta, formattingScanner, _a, requestKind, rangeContainsError, sourceFile) { + var options = _a.options, getRule = _a.getRule; + // formatting context is used by rules provider + var formattingContext = new formatting.FormattingContext(sourceFile, requestKind, options); + var previousRange; + var previousParent; + var previousRangeStartLine; + var lastIndentedLine; + var indentationOnLastIndentedLine = -1 /* Unknown */; + var edits = []; + formattingScanner.advance(); + if (formattingScanner.isOnToken()) { + var startLine = sourceFile.getLineAndCharacterOfPosition(enclosingNode.getStart(sourceFile)).line; + var undecoratedStartLine = startLine; + if (enclosingNode.decorators) { + undecoratedStartLine = sourceFile.getLineAndCharacterOfPosition(ts.getNonDecoratorTokenPosOfNode(enclosingNode, sourceFile)).line; + } + processNode(enclosingNode, enclosingNode, startLine, undecoratedStartLine, initialIndentation, delta); + } + if (!formattingScanner.isOnToken()) { + var leadingTrivia = formattingScanner.getCurrentLeadingTrivia(); + if (leadingTrivia) { + indentTriviaItems(leadingTrivia, initialIndentation, /*indentNextTokenOrTrivia*/ false, function (item) { return processRange(item, sourceFile.getLineAndCharacterOfPosition(item.pos), enclosingNode, enclosingNode, /*dynamicIndentation*/ undefined); }); + trimTrailingWhitespacesForRemainingRange(); + } + } + return edits; + // local functions + /** Tries to compute the indentation for a list element. + * If list element is not in range then + * function will pick its actual indentation + * so it can be pushed downstream as inherited indentation. + * If list element is in the range - its indentation will be equal + * to inherited indentation from its predecessors. + */ + function tryComputeIndentationForListItem(startPos, endPos, parentStartLine, range, inheritedIndentation) { + if (ts.rangeOverlapsWithStartEnd(range, startPos, endPos) || + ts.rangeContainsStartEnd(range, startPos, endPos) /* Not to miss zero-range nodes e.g. JsxText */) { + if (inheritedIndentation !== -1 /* Unknown */) { + return inheritedIndentation; + } + } + else { + var startLine = sourceFile.getLineAndCharacterOfPosition(startPos).line; + var startLinePosition = ts.getLineStartPositionForPosition(startPos, sourceFile); + var column = formatting.SmartIndenter.findFirstNonWhitespaceColumn(startLinePosition, startPos, sourceFile, options); + if (startLine !== parentStartLine || startPos === column) { + // Use the base indent size if it is greater than + // the indentation of the inherited predecessor. + var baseIndentSize = formatting.SmartIndenter.getBaseIndentation(options); + return baseIndentSize > column ? baseIndentSize : column; + } + } + return -1 /* Unknown */; + } + function computeIndentation(node, startLine, inheritedIndentation, parent, parentDynamicIndentation, effectiveParentStartLine) { + var delta = formatting.SmartIndenter.shouldIndentChildNode(options, node) ? options.indentSize : 0; + if (effectiveParentStartLine === startLine) { + // if node is located on the same line with the parent + // - inherit indentation from the parent + // - push children if either parent of node itself has non-zero delta + return { + indentation: startLine === lastIndentedLine ? indentationOnLastIndentedLine : parentDynamicIndentation.getIndentation(), + delta: Math.min(options.indentSize, parentDynamicIndentation.getDelta(node) + delta) + }; + } + else if (inheritedIndentation === -1 /* Unknown */) { + if (node.kind === 20 /* OpenParenToken */ && startLine === lastIndentedLine) { + // the is used for chaining methods formatting + // - we need to get the indentation on last line and the delta of parent + return { indentation: indentationOnLastIndentedLine, delta: parentDynamicIndentation.getDelta(node) }; + } + else if (formatting.SmartIndenter.childStartsOnTheSameLineWithElseInIfStatement(parent, node, startLine, sourceFile)) { + return { indentation: parentDynamicIndentation.getIndentation(), delta: delta }; + } + else { + return { indentation: parentDynamicIndentation.getIndentation() + parentDynamicIndentation.getDelta(node), delta: delta }; + } + } + else { + return { indentation: inheritedIndentation, delta: delta }; + } + } + function getFirstNonDecoratorTokenOfNode(node) { + if (node.modifiers && node.modifiers.length) { + return node.modifiers[0].kind; + } + switch (node.kind) { + case 240 /* ClassDeclaration */: return 76 /* ClassKeyword */; + case 241 /* InterfaceDeclaration */: return 110 /* InterfaceKeyword */; + case 239 /* FunctionDeclaration */: return 90 /* FunctionKeyword */; + case 243 /* EnumDeclaration */: return 243 /* EnumDeclaration */; + case 158 /* GetAccessor */: return 126 /* GetKeyword */; + case 159 /* SetAccessor */: return 137 /* SetKeyword */; + case 156 /* MethodDeclaration */: + if (node.asteriskToken) { + return 40 /* AsteriskToken */; + } + // falls through + case 154 /* PropertyDeclaration */: + case 151 /* Parameter */: + var name = ts.getNameOfDeclaration(node); + if (name) { + return name.kind; + } + } + } + function getDynamicIndentation(node, nodeStartLine, indentation, delta) { + return { + getIndentationForComment: function (kind, tokenIndentation, container) { + switch (kind) { + // preceding comment to the token that closes the indentation scope inherits the indentation from the scope + // .. { + // // comment + // } + case 19 /* CloseBraceToken */: + case 23 /* CloseBracketToken */: + case 21 /* CloseParenToken */: + return indentation + getDelta(container); + } + return tokenIndentation !== -1 /* Unknown */ ? tokenIndentation : indentation; + }, + // if list end token is LessThanToken '>' then its delta should be explicitly suppressed + // so that LessThanToken as a binary operator can still be indented. + // foo.then + // < + // number, + // string, + // >(); + // vs + // var a = xValue + // > yValue; + getIndentationForToken: function (line, kind, container, suppressDelta) { + return !suppressDelta && shouldAddDelta(line, kind, container) ? indentation + getDelta(container) : indentation; + }, + getIndentation: function () { return indentation; }, + getDelta: getDelta, + recomputeIndentation: function (lineAdded) { + if (node.parent && formatting.SmartIndenter.shouldIndentChildNode(options, node.parent, node, sourceFile)) { + indentation += lineAdded ? options.indentSize : -options.indentSize; + delta = formatting.SmartIndenter.shouldIndentChildNode(options, node) ? options.indentSize : 0; + } + } + }; + function shouldAddDelta(line, kind, container) { + switch (kind) { + // open and close brace, 'else' and 'while' (in do statement) tokens has indentation of the parent + case 18 /* OpenBraceToken */: + case 19 /* CloseBraceToken */: + case 21 /* CloseParenToken */: + case 83 /* ElseKeyword */: + case 107 /* WhileKeyword */: + case 58 /* AtToken */: + return false; + case 42 /* SlashToken */: + case 30 /* GreaterThanToken */: + switch (container.kind) { + case 262 /* JsxOpeningElement */: + case 263 /* JsxClosingElement */: + case 261 /* JsxSelfClosingElement */: + return false; + } + break; + case 22 /* OpenBracketToken */: + case 23 /* CloseBracketToken */: + if (container.kind !== 181 /* MappedType */) { + return false; + } + break; + } + // if token line equals to the line of containing node (this is a first token in the node) - use node indentation + return nodeStartLine !== line + // if this token is the first token following the list of decorators, we do not need to indent + && !(node.decorators && kind === getFirstNonDecoratorTokenOfNode(node)); + } + function getDelta(child) { + // Delta value should be zero when the node explicitly prevents indentation of the child node + return formatting.SmartIndenter.nodeWillIndentChild(options, node, child, sourceFile, /*indentByDefault*/ true) ? delta : 0; + } + } + function processNode(node, contextNode, nodeStartLine, undecoratedNodeStartLine, indentation, delta) { + if (!ts.rangeOverlapsWithStartEnd(originalRange, node.getStart(sourceFile), node.getEnd())) { + return; + } + var nodeDynamicIndentation = getDynamicIndentation(node, nodeStartLine, indentation, delta); + // a useful observations when tracking context node + // / + // [a] + // / | \ + // [b] [c] [d] + // node 'a' is a context node for nodes 'b', 'c', 'd' + // except for the leftmost leaf token in [b] - in this case context node ('e') is located somewhere above 'a' + // this rule can be applied recursively to child nodes of 'a'. + // + // context node is set to parent node value after processing every child node + // context node is set to parent of the token after processing every token + var childContextNode = contextNode; + // if there are any tokens that logically belong to node and interleave child nodes + // such tokens will be consumed in processChildNode for the child that follows them + ts.forEachChild(node, function (child) { + processChildNode(child, /*inheritedIndentation*/ -1 /* Unknown */, node, nodeDynamicIndentation, nodeStartLine, undecoratedNodeStartLine, /*isListItem*/ false); + }, function (nodes) { + processChildNodes(nodes, node, nodeStartLine, nodeDynamicIndentation); + }); + // proceed any tokens in the node that are located after child nodes + while (formattingScanner.isOnToken()) { + var tokenInfo = formattingScanner.readTokenInfo(node); + if (tokenInfo.token.end > node.end) { + break; + } + consumeTokenAndAdvanceScanner(tokenInfo, node, nodeDynamicIndentation, node); + } + function processChildNode(child, inheritedIndentation, parent, parentDynamicIndentation, parentStartLine, undecoratedParentStartLine, isListItem, isFirstListItem) { + var childStartPos = child.getStart(sourceFile); + var childStartLine = sourceFile.getLineAndCharacterOfPosition(childStartPos).line; + var undecoratedChildStartLine = childStartLine; + if (child.decorators) { + undecoratedChildStartLine = sourceFile.getLineAndCharacterOfPosition(ts.getNonDecoratorTokenPosOfNode(child, sourceFile)).line; + } + // if child is a list item - try to get its indentation, only if parent is within the original range. + var childIndentationAmount = -1 /* Unknown */; + if (isListItem && ts.rangeContainsRange(originalRange, parent)) { + childIndentationAmount = tryComputeIndentationForListItem(childStartPos, child.end, parentStartLine, originalRange, inheritedIndentation); + if (childIndentationAmount !== -1 /* Unknown */) { + inheritedIndentation = childIndentationAmount; + } + } + // child node is outside the target range - do not dive inside + if (!ts.rangeOverlapsWithStartEnd(originalRange, child.pos, child.end)) { + if (child.end < originalRange.pos) { + formattingScanner.skipToEndOf(child); + } + return inheritedIndentation; + } + if (child.getFullWidth() === 0) { + return inheritedIndentation; + } + while (formattingScanner.isOnToken()) { + // proceed any parent tokens that are located prior to child.getStart() + var tokenInfo = formattingScanner.readTokenInfo(node); + if (tokenInfo.token.end > childStartPos) { + // stop when formatting scanner advances past the beginning of the child + break; + } + consumeTokenAndAdvanceScanner(tokenInfo, node, parentDynamicIndentation, node); + } + if (!formattingScanner.isOnToken()) { + return inheritedIndentation; + } + // JSX text shouldn't affect indenting + if (ts.isToken(child) && child.kind !== 11 /* JsxText */) { + // if child node is a token, it does not impact indentation, proceed it using parent indentation scope rules + var tokenInfo = formattingScanner.readTokenInfo(child); + ts.Debug.assert(tokenInfo.token.end === child.end, "Token end is child end"); + consumeTokenAndAdvanceScanner(tokenInfo, node, parentDynamicIndentation, child); + return inheritedIndentation; + } + var effectiveParentStartLine = child.kind === 152 /* Decorator */ ? childStartLine : undecoratedParentStartLine; + var childIndentation = computeIndentation(child, childStartLine, childIndentationAmount, node, parentDynamicIndentation, effectiveParentStartLine); + processNode(child, childContextNode, childStartLine, undecoratedChildStartLine, childIndentation.indentation, childIndentation.delta); + if (child.kind === 11 /* JsxText */) { + var range = { pos: child.getStart(), end: child.getEnd() }; + indentMultilineCommentOrJsxText(range, childIndentation.indentation, /*firstLineIsIndented*/ true, /*indentFinalLine*/ false); + } + childContextNode = node; + if (isFirstListItem && parent.kind === 187 /* ArrayLiteralExpression */ && inheritedIndentation === -1 /* Unknown */) { + inheritedIndentation = childIndentation.indentation; + } + return inheritedIndentation; + } + function processChildNodes(nodes, parent, parentStartLine, parentDynamicIndentation) { + ts.Debug.assert(ts.isNodeArray(nodes)); + var listStartToken = getOpenTokenForList(parent, nodes); + var listDynamicIndentation = parentDynamicIndentation; + var startLine = parentStartLine; + if (listStartToken !== 0 /* Unknown */) { + // introduce a new indentation scope for lists (including list start and end tokens) + while (formattingScanner.isOnToken()) { + var tokenInfo = formattingScanner.readTokenInfo(parent); + if (tokenInfo.token.end > nodes.pos) { + // stop when formatting scanner moves past the beginning of node list + break; + } + else if (tokenInfo.token.kind === listStartToken) { + // consume list start token + startLine = sourceFile.getLineAndCharacterOfPosition(tokenInfo.token.pos).line; + consumeTokenAndAdvanceScanner(tokenInfo, parent, parentDynamicIndentation, parent); + var indentationOnListStartToken = void 0; + if (indentationOnLastIndentedLine !== -1 /* Unknown */) { + // scanner just processed list start token so consider last indentation as list indentation + // function foo(): { // last indentation was 0, list item will be indented based on this value + // foo: number; + // }: {}; + indentationOnListStartToken = indentationOnLastIndentedLine; + } + else { + var startLinePosition = ts.getLineStartPositionForPosition(tokenInfo.token.pos, sourceFile); + indentationOnListStartToken = formatting.SmartIndenter.findFirstNonWhitespaceColumn(startLinePosition, tokenInfo.token.pos, sourceFile, options); + } + listDynamicIndentation = getDynamicIndentation(parent, parentStartLine, indentationOnListStartToken, options.indentSize); // TODO: GH#18217 + } + else { + // consume any tokens that precede the list as child elements of 'node' using its indentation scope + consumeTokenAndAdvanceScanner(tokenInfo, parent, parentDynamicIndentation, parent); + } + } + } + var inheritedIndentation = -1 /* Unknown */; + for (var i = 0; i < nodes.length; i++) { + var child = nodes[i]; + inheritedIndentation = processChildNode(child, inheritedIndentation, node, listDynamicIndentation, startLine, startLine, /*isListItem*/ true, /*isFirstListItem*/ i === 0); + } + var listEndToken = getCloseTokenForOpenToken(listStartToken); + if (listEndToken !== 0 /* Unknown */ && formattingScanner.isOnToken()) { + var tokenInfo = formattingScanner.readTokenInfo(parent); + if (tokenInfo.token.kind === 27 /* CommaToken */ && ts.isCallLikeExpression(parent)) { + formattingScanner.advance(); + tokenInfo = formattingScanner.isOnToken() ? formattingScanner.readTokenInfo(parent) : undefined; + } + // consume the list end token only if it is still belong to the parent + // there might be the case when current token matches end token but does not considered as one + // function (x: function) <-- + // without this check close paren will be interpreted as list end token for function expression which is wrong + if (tokenInfo && tokenInfo.token.kind === listEndToken && ts.rangeContainsRange(parent, tokenInfo.token)) { + // consume list end token + consumeTokenAndAdvanceScanner(tokenInfo, parent, listDynamicIndentation, parent, /*isListEndToken*/ true); + } + } + } + function consumeTokenAndAdvanceScanner(currentTokenInfo, parent, dynamicIndentation, container, isListEndToken) { + ts.Debug.assert(ts.rangeContainsRange(parent, currentTokenInfo.token)); + var lastTriviaWasNewLine = formattingScanner.lastTrailingTriviaWasNewLine(); + var indentToken = false; + if (currentTokenInfo.leadingTrivia) { + processTrivia(currentTokenInfo.leadingTrivia, parent, childContextNode, dynamicIndentation); + } + var lineAction = 0 /* None */; + var isTokenInRange = ts.rangeContainsRange(originalRange, currentTokenInfo.token); + var tokenStart = sourceFile.getLineAndCharacterOfPosition(currentTokenInfo.token.pos); + if (isTokenInRange) { + var rangeHasError = rangeContainsError(currentTokenInfo.token); + // save previousRange since processRange will overwrite this value with current one + var savePreviousRange = previousRange; + lineAction = processRange(currentTokenInfo.token, tokenStart, parent, childContextNode, dynamicIndentation); + // do not indent comments\token if token range overlaps with some error + if (!rangeHasError) { + if (lineAction === 0 /* None */) { + // indent token only if end line of previous range does not match start line of the token + var prevEndLine = savePreviousRange && sourceFile.getLineAndCharacterOfPosition(savePreviousRange.end).line; + indentToken = lastTriviaWasNewLine && tokenStart.line !== prevEndLine; + } + else { + indentToken = lineAction === 1 /* LineAdded */; + } + } + } + if (currentTokenInfo.trailingTrivia) { + processTrivia(currentTokenInfo.trailingTrivia, parent, childContextNode, dynamicIndentation); + } + if (indentToken) { + var tokenIndentation = (isTokenInRange && !rangeContainsError(currentTokenInfo.token)) ? + dynamicIndentation.getIndentationForToken(tokenStart.line, currentTokenInfo.token.kind, container, !!isListEndToken) : + -1 /* Unknown */; + var indentNextTokenOrTrivia = true; + if (currentTokenInfo.leadingTrivia) { + var commentIndentation_1 = dynamicIndentation.getIndentationForComment(currentTokenInfo.token.kind, tokenIndentation, container); + indentNextTokenOrTrivia = indentTriviaItems(currentTokenInfo.leadingTrivia, commentIndentation_1, indentNextTokenOrTrivia, function (item) { return insertIndentation(item.pos, commentIndentation_1, /*lineAdded*/ false); }); + } + // indent token only if is it is in target range and does not overlap with any error ranges + if (tokenIndentation !== -1 /* Unknown */ && indentNextTokenOrTrivia) { + insertIndentation(currentTokenInfo.token.pos, tokenIndentation, lineAction === 1 /* LineAdded */); + lastIndentedLine = tokenStart.line; + indentationOnLastIndentedLine = tokenIndentation; + } + } + formattingScanner.advance(); + childContextNode = parent; + } + } + function indentTriviaItems(trivia, commentIndentation, indentNextTokenOrTrivia, indentSingleLine) { + for (var _i = 0, trivia_1 = trivia; _i < trivia_1.length; _i++) { + var triviaItem = trivia_1[_i]; + var triviaInRange = ts.rangeContainsRange(originalRange, triviaItem); + switch (triviaItem.kind) { + case 3 /* MultiLineCommentTrivia */: + if (triviaInRange) { + indentMultilineCommentOrJsxText(triviaItem, commentIndentation, /*firstLineIsIndented*/ !indentNextTokenOrTrivia); + } + indentNextTokenOrTrivia = false; + break; + case 2 /* SingleLineCommentTrivia */: + if (indentNextTokenOrTrivia && triviaInRange) { + indentSingleLine(triviaItem); + } + indentNextTokenOrTrivia = false; + break; + case 4 /* NewLineTrivia */: + indentNextTokenOrTrivia = true; + break; + } + } + return indentNextTokenOrTrivia; + } + function processTrivia(trivia, parent, contextNode, dynamicIndentation) { + for (var _i = 0, trivia_2 = trivia; _i < trivia_2.length; _i++) { + var triviaItem = trivia_2[_i]; + if (ts.isComment(triviaItem.kind) && ts.rangeContainsRange(originalRange, triviaItem)) { + var triviaItemStart = sourceFile.getLineAndCharacterOfPosition(triviaItem.pos); + processRange(triviaItem, triviaItemStart, parent, contextNode, dynamicIndentation); + } + } + } + function processRange(range, rangeStart, parent, contextNode, dynamicIndentation) { + var rangeHasError = rangeContainsError(range); + var lineAction = 0 /* None */; + if (!rangeHasError) { + if (!previousRange) { + // trim whitespaces starting from the beginning of the span up to the current line + var originalStart = sourceFile.getLineAndCharacterOfPosition(originalRange.pos); + trimTrailingWhitespacesForLines(originalStart.line, rangeStart.line); + } + else { + lineAction = + processPair(range, rangeStart.line, parent, previousRange, previousRangeStartLine, previousParent, contextNode, dynamicIndentation); + } + } + previousRange = range; + previousParent = parent; + previousRangeStartLine = rangeStart.line; + return lineAction; + } + function processPair(currentItem, currentStartLine, currentParent, previousItem, previousStartLine, previousParent, contextNode, dynamicIndentation) { + formattingContext.updateContext(previousItem, previousParent, currentItem, currentParent, contextNode); + var rule = getRule(formattingContext); + var trimTrailingWhitespaces; + var lineAction = 0 /* None */; + if (rule) { + lineAction = applyRuleEdits(rule, previousItem, previousStartLine, currentItem, currentStartLine); + switch (lineAction) { + case 2 /* LineRemoved */: + // Handle the case where the next line is moved to be the end of this line. + // In this case we don't indent the next line in the next pass. + if (currentParent.getStart(sourceFile) === currentItem.pos) { + dynamicIndentation.recomputeIndentation(/*lineAddedByFormatting*/ false); + } + break; + case 1 /* LineAdded */: + // Handle the case where token2 is moved to the new line. + // In this case we indent token2 in the next pass but we set + // sameLineIndent flag to notify the indenter that the indentation is within the line. + if (currentParent.getStart(sourceFile) === currentItem.pos) { + dynamicIndentation.recomputeIndentation(/*lineAddedByFormatting*/ true); + } + break; + default: + ts.Debug.assert(lineAction === 0 /* None */); + } + // We need to trim trailing whitespace between the tokens if they were on different lines, and no rule was applied to put them on the same line + trimTrailingWhitespaces = !(rule.action & 8 /* Delete */) && rule.flags !== 1 /* CanDeleteNewLines */; + } + else { + trimTrailingWhitespaces = true; + } + if (currentStartLine !== previousStartLine && trimTrailingWhitespaces) { + // We need to trim trailing whitespace between the tokens if they were on different lines, and no rule was applied to put them on the same line + trimTrailingWhitespacesForLines(previousStartLine, currentStartLine, previousItem); + } + return lineAction; + } + function insertIndentation(pos, indentation, lineAdded) { + var indentationString = getIndentationString(indentation, options); + if (lineAdded) { + // new line is added before the token by the formatting rules + // insert indentation string at the very beginning of the token + recordReplace(pos, 0, indentationString); + } + else { + var tokenStart = sourceFile.getLineAndCharacterOfPosition(pos); + var startLinePosition = ts.getStartPositionOfLine(tokenStart.line, sourceFile); + if (indentation !== characterToColumn(startLinePosition, tokenStart.character) || indentationIsDifferent(indentationString, startLinePosition)) { + recordReplace(startLinePosition, tokenStart.character, indentationString); + } + } + } + function characterToColumn(startLinePosition, characterInLine) { + var column = 0; + for (var i = 0; i < characterInLine; i++) { + if (sourceFile.text.charCodeAt(startLinePosition + i) === 9 /* tab */) { + column += options.tabSize - column % options.tabSize; + } + else { + column++; + } + } + return column; + } + function indentationIsDifferent(indentationString, startLinePosition) { + return indentationString !== sourceFile.text.substr(startLinePosition, indentationString.length); + } + function indentMultilineCommentOrJsxText(commentRange, indentation, firstLineIsIndented, indentFinalLine) { + if (indentFinalLine === void 0) { indentFinalLine = true; } + // split comment in lines + var startLine = sourceFile.getLineAndCharacterOfPosition(commentRange.pos).line; + var endLine = sourceFile.getLineAndCharacterOfPosition(commentRange.end).line; + if (startLine === endLine) { + if (!firstLineIsIndented) { + // treat as single line comment + insertIndentation(commentRange.pos, indentation, /*lineAdded*/ false); + } + return; + } + var parts = []; + var startPos = commentRange.pos; + for (var line = startLine; line < endLine; line++) { + var endOfLine = ts.getEndLinePosition(line, sourceFile); + parts.push({ pos: startPos, end: endOfLine }); + startPos = ts.getStartPositionOfLine(line + 1, sourceFile); + } + if (indentFinalLine) { + parts.push({ pos: startPos, end: commentRange.end }); + } + if (parts.length === 0) + return; + var startLinePos = ts.getStartPositionOfLine(startLine, sourceFile); + var nonWhitespaceColumnInFirstPart = formatting.SmartIndenter.findFirstNonWhitespaceCharacterAndColumn(startLinePos, parts[0].pos, sourceFile, options); + if (indentation === nonWhitespaceColumnInFirstPart.column) { + return; + } + var startIndex = 0; + if (firstLineIsIndented) { + startIndex = 1; + startLine++; + } + // shift all parts on the delta size + var delta = indentation - nonWhitespaceColumnInFirstPart.column; + for (var i = startIndex; i < parts.length; i++, startLine++) { + var startLinePos_1 = ts.getStartPositionOfLine(startLine, sourceFile); + var nonWhitespaceCharacterAndColumn = i === 0 + ? nonWhitespaceColumnInFirstPart + : formatting.SmartIndenter.findFirstNonWhitespaceCharacterAndColumn(parts[i].pos, parts[i].end, sourceFile, options); + var newIndentation = nonWhitespaceCharacterAndColumn.column + delta; + if (newIndentation > 0) { + var indentationString = getIndentationString(newIndentation, options); + recordReplace(startLinePos_1, nonWhitespaceCharacterAndColumn.character, indentationString); + } + else { + recordDelete(startLinePos_1, nonWhitespaceCharacterAndColumn.character); + } + } + } + function trimTrailingWhitespacesForLines(line1, line2, range) { + for (var line = line1; line < line2; line++) { + var lineStartPosition = ts.getStartPositionOfLine(line, sourceFile); + var lineEndPosition = ts.getEndLinePosition(line, sourceFile); + // do not trim whitespaces in comments or template expression + if (range && (ts.isComment(range.kind) || ts.isStringOrRegularExpressionOrTemplateLiteral(range.kind)) && range.pos <= lineEndPosition && range.end > lineEndPosition) { + continue; + } + var whitespaceStart = getTrailingWhitespaceStartPosition(lineStartPosition, lineEndPosition); + if (whitespaceStart !== -1) { + ts.Debug.assert(whitespaceStart === lineStartPosition || !ts.isWhiteSpaceSingleLine(sourceFile.text.charCodeAt(whitespaceStart - 1))); + recordDelete(whitespaceStart, lineEndPosition + 1 - whitespaceStart); + } + } + } + /** + * @param start The position of the first character in range + * @param end The position of the last character in range + */ + function getTrailingWhitespaceStartPosition(start, end) { + var pos = end; + while (pos >= start && ts.isWhiteSpaceSingleLine(sourceFile.text.charCodeAt(pos))) { + pos--; + } + if (pos !== end) { + return pos + 1; + } + return -1; + } + /** + * Trimming will be done for lines after the previous range + */ + function trimTrailingWhitespacesForRemainingRange() { + var startPosition = previousRange ? previousRange.end : originalRange.pos; + var startLine = sourceFile.getLineAndCharacterOfPosition(startPosition).line; + var endLine = sourceFile.getLineAndCharacterOfPosition(originalRange.end).line; + trimTrailingWhitespacesForLines(startLine, endLine + 1, previousRange); + } + function recordDelete(start, len) { + if (len) { + edits.push(ts.createTextChangeFromStartLength(start, len, "")); + } + } + function recordReplace(start, len, newText) { + if (len || newText) { + edits.push(ts.createTextChangeFromStartLength(start, len, newText)); + } + } + function applyRuleEdits(rule, previousRange, previousStartLine, currentRange, currentStartLine) { + var onLaterLine = currentStartLine !== previousStartLine; + switch (rule.action) { + case 1 /* Ignore */: + // no action required + return 0 /* None */; + case 8 /* Delete */: + if (previousRange.end !== currentRange.pos) { + // delete characters starting from t1.end up to t2.pos exclusive + recordDelete(previousRange.end, currentRange.pos - previousRange.end); + return onLaterLine ? 2 /* LineRemoved */ : 0 /* None */; + } + break; + case 4 /* NewLine */: + // exit early if we on different lines and rule cannot change number of newlines + // if line1 and line2 are on subsequent lines then no edits are required - ok to exit + // if line1 and line2 are separated with more than one newline - ok to exit since we cannot delete extra new lines + if (rule.flags !== 1 /* CanDeleteNewLines */ && previousStartLine !== currentStartLine) { + return 0 /* None */; + } + // edit should not be applied if we have one line feed between elements + var lineDelta = currentStartLine - previousStartLine; + if (lineDelta !== 1) { + recordReplace(previousRange.end, currentRange.pos - previousRange.end, options.newLineCharacter); + return onLaterLine ? 0 /* None */ : 1 /* LineAdded */; + } + break; + case 2 /* Space */: + // exit early if we on different lines and rule cannot change number of newlines + if (rule.flags !== 1 /* CanDeleteNewLines */ && previousStartLine !== currentStartLine) { + return 0 /* None */; + } + var posDelta = currentRange.pos - previousRange.end; + if (posDelta !== 1 || sourceFile.text.charCodeAt(previousRange.end) !== 32 /* space */) { + recordReplace(previousRange.end, currentRange.pos - previousRange.end, " "); + return onLaterLine ? 2 /* LineRemoved */ : 0 /* None */; + } + } + return 0 /* None */; + } + } + var LineAction; + (function (LineAction) { + LineAction[LineAction["None"] = 0] = "None"; + LineAction[LineAction["LineAdded"] = 1] = "LineAdded"; + LineAction[LineAction["LineRemoved"] = 2] = "LineRemoved"; + })(LineAction || (LineAction = {})); + /** + * @param precedingToken pass `null` if preceding token was already computed and result was `undefined`. + */ + function getRangeOfEnclosingComment(sourceFile, position, precedingToken, // tslint:disable-line:no-null-keyword + tokenAtPosition) { + if (tokenAtPosition === void 0) { tokenAtPosition = ts.getTokenAtPosition(sourceFile, position); } + var jsdoc = ts.findAncestor(tokenAtPosition, ts.isJSDoc); + if (jsdoc) + tokenAtPosition = jsdoc.parent; + var tokenStart = tokenAtPosition.getStart(sourceFile); + if (tokenStart <= position && position < tokenAtPosition.getEnd()) { + return undefined; + } + precedingToken = precedingToken === null ? undefined : precedingToken === undefined ? ts.findPrecedingToken(position, sourceFile) : precedingToken; + // Between two consecutive tokens, all comments are either trailing on the former + // or leading on the latter (and none are in both lists). + var trailingRangesOfPreviousToken = precedingToken && ts.getTrailingCommentRanges(sourceFile.text, precedingToken.end); + var leadingCommentRangesOfNextToken = ts.getLeadingCommentRangesOfNode(tokenAtPosition, sourceFile); + var commentRanges = ts.concatenate(trailingRangesOfPreviousToken, leadingCommentRangesOfNextToken); + return commentRanges && ts.find(commentRanges, function (range) { return ts.rangeContainsPositionExclusive(range, position) || + // The end marker of a single-line comment does not include the newline character. + // With caret at `^`, in the following case, we are inside a comment (^ denotes the cursor position): + // + // // asdf ^\n + // + // But for closed multi-line comments, we don't want to be inside the comment in the following case: + // + // /* asdf */^ + // + // However, unterminated multi-line comments *do* contain their end. + // + // Internally, we represent the end of the comment at the newline and closing '/', respectively. + // + position === range.end && (range.kind === 2 /* SingleLineCommentTrivia */ || position === sourceFile.getFullWidth()); }); + } + formatting.getRangeOfEnclosingComment = getRangeOfEnclosingComment; + function getOpenTokenForList(node, list) { + switch (node.kind) { + case 157 /* Constructor */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 197 /* ArrowFunction */: + if (node.typeParameters === list) { + return 28 /* LessThanToken */; + } + else if (node.parameters === list) { + return 20 /* OpenParenToken */; + } + break; + case 191 /* CallExpression */: + case 192 /* NewExpression */: + if (node.typeArguments === list) { + return 28 /* LessThanToken */; + } + else if (node.arguments === list) { + return 20 /* OpenParenToken */; + } + break; + case 164 /* TypeReference */: + if (node.typeArguments === list) { + return 28 /* LessThanToken */; + } + break; + case 168 /* TypeLiteral */: + return 18 /* OpenBraceToken */; + } + return 0 /* Unknown */; + } + function getCloseTokenForOpenToken(kind) { + switch (kind) { + case 20 /* OpenParenToken */: + return 21 /* CloseParenToken */; + case 28 /* LessThanToken */: + return 30 /* GreaterThanToken */; + case 18 /* OpenBraceToken */: + return 19 /* CloseBraceToken */; + } + return 0 /* Unknown */; + } + var internedSizes; + var internedTabsIndentation; + var internedSpacesIndentation; + function getIndentationString(indentation, options) { + // reset interned strings if FormatCodeOptions were changed + var resetInternedStrings = !internedSizes || (internedSizes.tabSize !== options.tabSize || internedSizes.indentSize !== options.indentSize); + if (resetInternedStrings) { + internedSizes = { tabSize: options.tabSize, indentSize: options.indentSize }; + internedTabsIndentation = internedSpacesIndentation = undefined; + } + if (!options.convertTabsToSpaces) { + var tabs = Math.floor(indentation / options.tabSize); + var spaces = indentation - tabs * options.tabSize; + var tabString = void 0; + if (!internedTabsIndentation) { + internedTabsIndentation = []; + } + if (internedTabsIndentation[tabs] === undefined) { + internedTabsIndentation[tabs] = tabString = ts.repeatString("\t", tabs); + } + else { + tabString = internedTabsIndentation[tabs]; + } + return spaces ? tabString + ts.repeatString(" ", spaces) : tabString; + } + else { + var spacesString = void 0; + var quotient = Math.floor(indentation / options.indentSize); + var remainder = indentation % options.indentSize; + if (!internedSpacesIndentation) { + internedSpacesIndentation = []; + } + if (internedSpacesIndentation[quotient] === undefined) { + spacesString = ts.repeatString(" ", options.indentSize * quotient); + internedSpacesIndentation[quotient] = spacesString; + } + else { + spacesString = internedSpacesIndentation[quotient]; + } + return remainder ? spacesString + ts.repeatString(" ", remainder) : spacesString; + } + } + formatting.getIndentationString = getIndentationString; + })(formatting = ts.formatting || (ts.formatting = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var formatting; + (function (formatting) { + var SmartIndenter; + (function (SmartIndenter) { + var Value; + (function (Value) { + Value[Value["Unknown"] = -1] = "Unknown"; + })(Value || (Value = {})); + /** + * @param assumeNewLineBeforeCloseBrace + * `false` when called on text from a real source file. + * `true` when we need to assume `position` is on a newline. + * + * This is useful for codefixes. Consider + * ``` + * function f() { + * |} + * ``` + * with `position` at `|`. + * + * When inserting some text after an open brace, we would like to get indentation as if a newline was already there. + * By default indentation at `position` will be 0 so 'assumeNewLineBeforeCloseBrace' overrides this behavior. + */ + function getIndentation(position, sourceFile, options, assumeNewLineBeforeCloseBrace) { + if (assumeNewLineBeforeCloseBrace === void 0) { assumeNewLineBeforeCloseBrace = false; } + if (position > sourceFile.text.length) { + return getBaseIndentation(options); // past EOF + } + // no indentation when the indent style is set to none, + // so we can return fast + if (options.indentStyle === ts.IndentStyle.None) { + return 0; + } + var precedingToken = ts.findPrecedingToken(position, sourceFile, /*startNode*/ undefined, /*excludeJsdoc*/ true); + var enclosingCommentRange = formatting.getRangeOfEnclosingComment(sourceFile, position, precedingToken || null); // tslint:disable-line:no-null-keyword + if (enclosingCommentRange && enclosingCommentRange.kind === 3 /* MultiLineCommentTrivia */) { + return getCommentIndent(sourceFile, position, options, enclosingCommentRange); + } + if (!precedingToken) { + return getBaseIndentation(options); + } + // no indentation in string \regex\template literals + var precedingTokenIsLiteral = ts.isStringOrRegularExpressionOrTemplateLiteral(precedingToken.kind); + if (precedingTokenIsLiteral && precedingToken.getStart(sourceFile) <= position && position < precedingToken.end) { + return 0; + } + var lineAtPosition = sourceFile.getLineAndCharacterOfPosition(position).line; + // indentation is first non-whitespace character in a previous line + // for block indentation, we should look for a line which contains something that's not + // whitespace. + if (options.indentStyle === ts.IndentStyle.Block) { + return getBlockIndent(sourceFile, position, options); + } + if (precedingToken.kind === 27 /* CommaToken */ && precedingToken.parent.kind !== 204 /* BinaryExpression */) { + // previous token is comma that separates items in list - find the previous item and try to derive indentation from it + var actualIndentation = getActualIndentationForListItemBeforeComma(precedingToken, sourceFile, options); + if (actualIndentation !== -1 /* Unknown */) { + return actualIndentation; + } + } + var containerList = getListByPosition(position, precedingToken.parent, sourceFile); + // use list position if the preceding token is before any list items + if (containerList && !ts.rangeContainsRange(containerList, precedingToken)) { + return getActualIndentationForListStartLine(containerList, sourceFile, options) + options.indentSize; // TODO: GH#18217 + } + return getSmartIndent(sourceFile, position, precedingToken, lineAtPosition, assumeNewLineBeforeCloseBrace, options); + } + SmartIndenter.getIndentation = getIndentation; + function getCommentIndent(sourceFile, position, options, enclosingCommentRange) { + var previousLine = ts.getLineAndCharacterOfPosition(sourceFile, position).line - 1; + var commentStartLine = ts.getLineAndCharacterOfPosition(sourceFile, enclosingCommentRange.pos).line; + ts.Debug.assert(commentStartLine >= 0); + if (previousLine <= commentStartLine) { + return findFirstNonWhitespaceColumn(ts.getStartPositionOfLine(commentStartLine, sourceFile), position, sourceFile, options); + } + var startPositionOfLine = ts.getStartPositionOfLine(previousLine, sourceFile); + var _a = findFirstNonWhitespaceCharacterAndColumn(startPositionOfLine, position, sourceFile, options), column = _a.column, character = _a.character; + if (column === 0) { + return column; + } + var firstNonWhitespaceCharacterCode = sourceFile.text.charCodeAt(startPositionOfLine + character); + return firstNonWhitespaceCharacterCode === 42 /* asterisk */ ? column - 1 : column; + } + function getBlockIndent(sourceFile, position, options) { + // move backwards until we find a line with a non-whitespace character, + // then find the first non-whitespace character for that line. + var current = position; + while (current > 0) { + var char = sourceFile.text.charCodeAt(current); + if (!ts.isWhiteSpaceLike(char)) { + break; + } + current--; + } + var lineStart = ts.getLineStartPositionForPosition(current, sourceFile); + return findFirstNonWhitespaceColumn(lineStart, current, sourceFile, options); + } + function getSmartIndent(sourceFile, position, precedingToken, lineAtPosition, assumeNewLineBeforeCloseBrace, options) { + // try to find node that can contribute to indentation and includes 'position' starting from 'precedingToken' + // if such node is found - compute initial indentation for 'position' inside this node + var previous; + var current = precedingToken; + while (current) { + if (ts.positionBelongsToNode(current, position, sourceFile) && shouldIndentChildNode(options, current, previous, sourceFile, /*isNextChild*/ true)) { + var currentStart = getStartLineAndCharacterForNode(current, sourceFile); + var nextTokenKind = nextTokenIsCurlyBraceOnSameLineAsCursor(precedingToken, current, lineAtPosition, sourceFile); + var indentationDelta = nextTokenKind !== 0 /* Unknown */ + // handle cases when codefix is about to be inserted before the close brace + ? assumeNewLineBeforeCloseBrace && nextTokenKind === 2 /* CloseBrace */ ? options.indentSize : 0 + : lineAtPosition !== currentStart.line ? options.indentSize : 0; + return getIndentationForNodeWorker(current, currentStart, /*ignoreActualIndentationRange*/ undefined, indentationDelta, sourceFile, /*isNextChild*/ true, options); // TODO: GH#18217 + } + // check if current node is a list item - if yes, take indentation from it + // do not consider parent-child line sharing yet: + // function foo(a + // | preceding node 'a' does share line with its parent but indentation is expected + var actualIndentation = getActualIndentationForListItem(current, sourceFile, options, /*listIndentsChild*/ true); + if (actualIndentation !== -1 /* Unknown */) { + return actualIndentation; + } + previous = current; + current = current.parent; + } + // no parent was found - return the base indentation of the SourceFile + return getBaseIndentation(options); + } + function getIndentationForNode(n, ignoreActualIndentationRange, sourceFile, options) { + var start = sourceFile.getLineAndCharacterOfPosition(n.getStart(sourceFile)); + return getIndentationForNodeWorker(n, start, ignoreActualIndentationRange, /*indentationDelta*/ 0, sourceFile, /*isNextChild*/ false, options); + } + SmartIndenter.getIndentationForNode = getIndentationForNode; + function getBaseIndentation(options) { + return options.baseIndentSize || 0; + } + SmartIndenter.getBaseIndentation = getBaseIndentation; + function getIndentationForNodeWorker(current, currentStart, ignoreActualIndentationRange, indentationDelta, sourceFile, isNextChild, options) { + var parent = current.parent; + // Walk up the tree and collect indentation for parent-child node pairs. Indentation is not added if + // * parent and child nodes start on the same line, or + // * parent is an IfStatement and child starts on the same line as an 'else clause'. + while (parent) { + var useActualIndentation = true; + if (ignoreActualIndentationRange) { + var start = current.getStart(sourceFile); + useActualIndentation = start < ignoreActualIndentationRange.pos || start > ignoreActualIndentationRange.end; + } + var containingListOrParentStart = getContainingListOrParentStart(parent, current, sourceFile); + var parentAndChildShareLine = containingListOrParentStart.line === currentStart.line || + childStartsOnTheSameLineWithElseInIfStatement(parent, current, currentStart.line, sourceFile); + if (useActualIndentation) { + // check if current node is a list item - if yes, take indentation from it + var actualIndentation = getActualIndentationForListItem(current, sourceFile, options, !parentAndChildShareLine); + if (actualIndentation !== -1 /* Unknown */) { + return actualIndentation + indentationDelta; + } + // try to fetch actual indentation for current node from source text + actualIndentation = getActualIndentationForNode(current, parent, currentStart, parentAndChildShareLine, sourceFile, options); + if (actualIndentation !== -1 /* Unknown */) { + return actualIndentation + indentationDelta; + } + } + // increase indentation if parent node wants its content to be indented and parent and child nodes don't start on the same line + if (shouldIndentChildNode(options, parent, current, sourceFile, isNextChild) && !parentAndChildShareLine) { + indentationDelta += options.indentSize; + } + // In our AST, a call argument's `parent` is the call-expression, not the argument list. + // We would like to increase indentation based on the relationship between an argument and its argument-list, + // so we spoof the starting position of the (parent) call-expression to match the (non-parent) argument-list. + // But, the spoofed start-value could then cause a problem when comparing the start position of the call-expression + // to *its* parent (in the case of an iife, an expression statement), adding an extra level of indentation. + // + // Instead, when at an argument, we unspoof the starting position of the enclosing call expression + // *after* applying indentation for the argument. + var useTrueStart = isArgumentAndStartLineOverlapsExpressionBeingCalled(parent, current, currentStart.line, sourceFile); + current = parent; + parent = current.parent; + currentStart = useTrueStart ? sourceFile.getLineAndCharacterOfPosition(current.getStart(sourceFile)) : containingListOrParentStart; + } + return indentationDelta + getBaseIndentation(options); + } + function getContainingListOrParentStart(parent, child, sourceFile) { + var containingList = getContainingList(child, sourceFile); + var startPos = containingList ? containingList.pos : parent.getStart(sourceFile); + return sourceFile.getLineAndCharacterOfPosition(startPos); + } + /* + * Function returns Value.Unknown if indentation cannot be determined + */ + function getActualIndentationForListItemBeforeComma(commaToken, sourceFile, options) { + // previous token is comma that separates items in list - find the previous item and try to derive indentation from it + var commaItemInfo = ts.findListItemInfo(commaToken); + if (commaItemInfo && commaItemInfo.listItemIndex > 0) { + return deriveActualIndentationFromList(commaItemInfo.list.getChildren(), commaItemInfo.listItemIndex - 1, sourceFile, options); + } + else { + // handle broken code gracefully + return -1 /* Unknown */; + } + } + /* + * Function returns Value.Unknown if actual indentation for node should not be used (i.e because node is nested expression) + */ + function getActualIndentationForNode(current, parent, currentLineAndChar, parentAndChildShareLine, sourceFile, options) { + // actual indentation is used for statements\declarations if one of cases below is true: + // - parent is SourceFile - by default immediate children of SourceFile are not indented except when user indents them manually + // - parent and child are not on the same line + var useActualIndentation = (ts.isDeclaration(current) || ts.isStatementButNotDeclaration(current)) && + (parent.kind === 279 /* SourceFile */ || !parentAndChildShareLine); + if (!useActualIndentation) { + return -1 /* Unknown */; + } + return findColumnForFirstNonWhitespaceCharacterInLine(currentLineAndChar, sourceFile, options); + } + var NextTokenKind; + (function (NextTokenKind) { + NextTokenKind[NextTokenKind["Unknown"] = 0] = "Unknown"; + NextTokenKind[NextTokenKind["OpenBrace"] = 1] = "OpenBrace"; + NextTokenKind[NextTokenKind["CloseBrace"] = 2] = "CloseBrace"; + })(NextTokenKind || (NextTokenKind = {})); + function nextTokenIsCurlyBraceOnSameLineAsCursor(precedingToken, current, lineAtPosition, sourceFile) { + var nextToken = ts.findNextToken(precedingToken, current, sourceFile); + if (!nextToken) { + return 0 /* Unknown */; + } + if (nextToken.kind === 18 /* OpenBraceToken */) { + // open braces are always indented at the parent level + return 1 /* OpenBrace */; + } + else if (nextToken.kind === 19 /* CloseBraceToken */) { + // close braces are indented at the parent level if they are located on the same line with cursor + // this means that if new line will be added at $ position, this case will be indented + // class A { + // $ + // } + /// and this one - not + // class A { + // $} + var nextTokenStartLine = getStartLineAndCharacterForNode(nextToken, sourceFile).line; + return lineAtPosition === nextTokenStartLine ? 2 /* CloseBrace */ : 0 /* Unknown */; + } + return 0 /* Unknown */; + } + function getStartLineAndCharacterForNode(n, sourceFile) { + return sourceFile.getLineAndCharacterOfPosition(n.getStart(sourceFile)); + } + function isArgumentAndStartLineOverlapsExpressionBeingCalled(parent, child, childStartLine, sourceFile) { + if (!(ts.isCallExpression(parent) && ts.contains(parent.arguments, child))) { + return false; + } + var expressionOfCallExpressionEnd = parent.expression.getEnd(); + var expressionOfCallExpressionEndLine = ts.getLineAndCharacterOfPosition(sourceFile, expressionOfCallExpressionEnd).line; + return expressionOfCallExpressionEndLine === childStartLine; + } + SmartIndenter.isArgumentAndStartLineOverlapsExpressionBeingCalled = isArgumentAndStartLineOverlapsExpressionBeingCalled; + function childStartsOnTheSameLineWithElseInIfStatement(parent, child, childStartLine, sourceFile) { + if (parent.kind === 222 /* IfStatement */ && parent.elseStatement === child) { + var elseKeyword = ts.findChildOfKind(parent, 83 /* ElseKeyword */, sourceFile); + ts.Debug.assert(elseKeyword !== undefined); + var elseKeywordStartLine = getStartLineAndCharacterForNode(elseKeyword, sourceFile).line; + return elseKeywordStartLine === childStartLine; + } + return false; + } + SmartIndenter.childStartsOnTheSameLineWithElseInIfStatement = childStartsOnTheSameLineWithElseInIfStatement; + function getContainingList(node, sourceFile) { + return node.parent && getListByRange(node.getStart(sourceFile), node.getEnd(), node.parent, sourceFile); + } + SmartIndenter.getContainingList = getContainingList; + function getListByPosition(pos, node, sourceFile) { + return node && getListByRange(pos, pos, node, sourceFile); + } + function getListByRange(start, end, node, sourceFile) { + switch (node.kind) { + case 164 /* TypeReference */: + return getList(node.typeArguments); + case 188 /* ObjectLiteralExpression */: + return getList(node.properties); + case 187 /* ArrayLiteralExpression */: + return getList(node.elements); + case 168 /* TypeLiteral */: + return getList(node.members); + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 160 /* CallSignature */: + case 157 /* Constructor */: + case 166 /* ConstructorType */: + case 161 /* ConstructSignature */: + return getList(node.typeParameters) || getList(node.parameters); + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 241 /* InterfaceDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 303 /* JSDocTemplateTag */: + return getList(node.typeParameters); + case 192 /* NewExpression */: + case 191 /* CallExpression */: + return getList(node.typeArguments) || getList(node.arguments); + case 238 /* VariableDeclarationList */: + return getList(node.declarations); + case 252 /* NamedImports */: + case 256 /* NamedExports */: + return getList(node.elements); + case 184 /* ObjectBindingPattern */: + case 185 /* ArrayBindingPattern */: + return getList(node.elements); + } + function getList(list) { + return list && ts.rangeContainsStartEnd(getVisualListRange(node, list, sourceFile), start, end) ? list : undefined; + } + } + function getVisualListRange(node, list, sourceFile) { + var children = node.getChildren(sourceFile); + for (var i = 1; i < children.length - 1; i++) { + if (children[i].pos === list.pos && children[i].end === list.end) { + return { pos: children[i - 1].end, end: children[i + 1].getStart(sourceFile) }; + } + } + return list; + } + function getActualIndentationForListStartLine(list, sourceFile, options) { + if (!list) { + return -1 /* Unknown */; + } + return findColumnForFirstNonWhitespaceCharacterInLine(sourceFile.getLineAndCharacterOfPosition(list.pos), sourceFile, options); + } + function getActualIndentationForListItem(node, sourceFile, options, listIndentsChild) { + if (node.parent && node.parent.kind === 238 /* VariableDeclarationList */) { + // VariableDeclarationList has no wrapping tokens + return -1 /* Unknown */; + } + var containingList = getContainingList(node, sourceFile); + if (containingList) { + var index = containingList.indexOf(node); + if (index !== -1) { + var result = deriveActualIndentationFromList(containingList, index, sourceFile, options); + if (result !== -1 /* Unknown */) { + return result; + } + } + return getActualIndentationForListStartLine(containingList, sourceFile, options) + (listIndentsChild ? options.indentSize : 0); // TODO: GH#18217 + } + return -1 /* Unknown */; + } + function deriveActualIndentationFromList(list, index, sourceFile, options) { + ts.Debug.assert(index >= 0 && index < list.length); + var node = list[index]; + // walk toward the start of the list starting from current node and check if the line is the same for all items. + // if end line for item [i - 1] differs from the start line for item [i] - find column of the first non-whitespace character on the line of item [i] + var lineAndCharacter = getStartLineAndCharacterForNode(node, sourceFile); + for (var i = index - 1; i >= 0; i--) { + if (list[i].kind === 27 /* CommaToken */) { + continue; + } + // skip list items that ends on the same line with the current list element + var prevEndLine = sourceFile.getLineAndCharacterOfPosition(list[i].end).line; + if (prevEndLine !== lineAndCharacter.line) { + return findColumnForFirstNonWhitespaceCharacterInLine(lineAndCharacter, sourceFile, options); + } + lineAndCharacter = getStartLineAndCharacterForNode(list[i], sourceFile); + } + return -1 /* Unknown */; + } + function findColumnForFirstNonWhitespaceCharacterInLine(lineAndCharacter, sourceFile, options) { + var lineStart = sourceFile.getPositionOfLineAndCharacter(lineAndCharacter.line, 0); + return findFirstNonWhitespaceColumn(lineStart, lineStart + lineAndCharacter.character, sourceFile, options); + } + /** + * Character is the actual index of the character since the beginning of the line. + * Column - position of the character after expanding tabs to spaces. + * "0\t2$" + * value of 'character' for '$' is 3 + * value of 'column' for '$' is 6 (assuming that tab size is 4) + */ + function findFirstNonWhitespaceCharacterAndColumn(startPos, endPos, sourceFile, options) { + var character = 0; + var column = 0; + for (var pos = startPos; pos < endPos; pos++) { + var ch = sourceFile.text.charCodeAt(pos); + if (!ts.isWhiteSpaceSingleLine(ch)) { + break; + } + if (ch === 9 /* tab */) { + column += options.tabSize + (column % options.tabSize); + } + else { + column++; + } + character++; + } + return { column: column, character: character }; + } + SmartIndenter.findFirstNonWhitespaceCharacterAndColumn = findFirstNonWhitespaceCharacterAndColumn; + function findFirstNonWhitespaceColumn(startPos, endPos, sourceFile, options) { + return findFirstNonWhitespaceCharacterAndColumn(startPos, endPos, sourceFile, options).column; + } + SmartIndenter.findFirstNonWhitespaceColumn = findFirstNonWhitespaceColumn; + function nodeWillIndentChild(settings, parent, child, sourceFile, indentByDefault) { + var childKind = child ? child.kind : 0 /* Unknown */; + switch (parent.kind) { + case 221 /* ExpressionStatement */: + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 241 /* InterfaceDeclaration */: + case 243 /* EnumDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 187 /* ArrayLiteralExpression */: + case 218 /* Block */: + case 245 /* ModuleBlock */: + case 188 /* ObjectLiteralExpression */: + case 168 /* TypeLiteral */: + case 181 /* MappedType */: + case 170 /* TupleType */: + case 246 /* CaseBlock */: + case 272 /* DefaultClause */: + case 271 /* CaseClause */: + case 195 /* ParenthesizedExpression */: + case 189 /* PropertyAccessExpression */: + case 191 /* CallExpression */: + case 192 /* NewExpression */: + case 219 /* VariableStatement */: + case 254 /* ExportAssignment */: + case 230 /* ReturnStatement */: + case 205 /* ConditionalExpression */: + case 185 /* ArrayBindingPattern */: + case 184 /* ObjectBindingPattern */: + case 262 /* JsxOpeningElement */: + case 265 /* JsxOpeningFragment */: + case 261 /* JsxSelfClosingElement */: + case 270 /* JsxExpression */: + case 155 /* MethodSignature */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 151 /* Parameter */: + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + case 177 /* ParenthesizedType */: + case 193 /* TaggedTemplateExpression */: + case 201 /* AwaitExpression */: + case 256 /* NamedExports */: + case 252 /* NamedImports */: + case 257 /* ExportSpecifier */: + case 253 /* ImportSpecifier */: + case 154 /* PropertyDeclaration */: + return true; + case 237 /* VariableDeclaration */: + case 275 /* PropertyAssignment */: + if (!settings.indentMultiLineObjectLiteralBeginningOnBlankLine && sourceFile && childKind === 188 /* ObjectLiteralExpression */) { // TODO: GH#18217 + return rangeIsOnOneLine(sourceFile, child); + } + return true; + case 223 /* DoStatement */: + case 224 /* WhileStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + case 225 /* ForStatement */: + case 222 /* IfStatement */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 156 /* MethodDeclaration */: + case 197 /* ArrowFunction */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + return childKind !== 218 /* Block */; + case 255 /* ExportDeclaration */: + return childKind !== 256 /* NamedExports */; + case 249 /* ImportDeclaration */: + return childKind !== 250 /* ImportClause */ || + (!!child.namedBindings && child.namedBindings.kind !== 252 /* NamedImports */); + case 260 /* JsxElement */: + return childKind !== 263 /* JsxClosingElement */; + case 264 /* JsxFragment */: + return childKind !== 266 /* JsxClosingFragment */; + case 174 /* IntersectionType */: + case 173 /* UnionType */: + if (childKind === 168 /* TypeLiteral */) { + return false; + } + // falls through + } + // No explicit rule for given nodes so the result will follow the default value argument + return indentByDefault; + } + SmartIndenter.nodeWillIndentChild = nodeWillIndentChild; + function isControlFlowEndingStatement(kind, parent) { + switch (kind) { + case 230 /* ReturnStatement */: + case 234 /* ThrowStatement */: + case 228 /* ContinueStatement */: + case 229 /* BreakStatement */: + return parent.kind !== 218 /* Block */; + default: + return false; + } + } + /** + * True when the parent node should indent the given child by an explicit rule. + * @param isNextChild If true, we are judging indent of a hypothetical child *after* this one, not the current child. + */ + function shouldIndentChildNode(settings, parent, child, sourceFile, isNextChild) { + if (isNextChild === void 0) { isNextChild = false; } + return nodeWillIndentChild(settings, parent, child, sourceFile, /*indentByDefault*/ false) + && !(isNextChild && child && isControlFlowEndingStatement(child.kind, parent)); + } + SmartIndenter.shouldIndentChildNode = shouldIndentChildNode; + function rangeIsOnOneLine(sourceFile, range) { + var rangeStart = ts.skipTrivia(sourceFile.text, range.pos); + var startLine = sourceFile.getLineAndCharacterOfPosition(rangeStart).line; + var endLine = sourceFile.getLineAndCharacterOfPosition(range.end).line; + return startLine === endLine; + } + })(SmartIndenter = formatting.SmartIndenter || (formatting.SmartIndenter = {})); + })(formatting = ts.formatting || (ts.formatting = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var textChanges; + (function (textChanges_3) { + /** + * Currently for simplicity we store recovered positions on the node itself. + * It can be changed to side-table later if we decide that current design is too invasive. + */ + function getPos(n) { + var result = n.__pos; + ts.Debug.assert(typeof result === "number"); + return result; + } + function setPos(n, pos) { + ts.Debug.assert(typeof pos === "number"); + n.__pos = pos; + } + function getEnd(n) { + var result = n.__end; + ts.Debug.assert(typeof result === "number"); + return result; + } + function setEnd(n, end) { + ts.Debug.assert(typeof end === "number"); + n.__end = end; + } + var Position; + (function (Position) { + Position[Position["FullStart"] = 0] = "FullStart"; + Position[Position["Start"] = 1] = "Start"; + })(Position = textChanges_3.Position || (textChanges_3.Position = {})); + function skipWhitespacesAndLineBreaks(text, start) { + return ts.skipTrivia(text, start, /*stopAfterLineBreak*/ false, /*stopAtComments*/ true); + } + function hasCommentsBeforeLineBreak(text, start) { + var i = start; + while (i < text.length) { + var ch = text.charCodeAt(i); + if (ts.isWhiteSpaceSingleLine(ch)) { + i++; + continue; + } + return ch === 47 /* slash */; + } + return false; + } + textChanges_3.useNonAdjustedPositions = { + useNonAdjustedStartPosition: true, + useNonAdjustedEndPosition: true, + }; + var ChangeKind; + (function (ChangeKind) { + ChangeKind[ChangeKind["Remove"] = 0] = "Remove"; + ChangeKind[ChangeKind["ReplaceWithSingleNode"] = 1] = "ReplaceWithSingleNode"; + ChangeKind[ChangeKind["ReplaceWithMultipleNodes"] = 2] = "ReplaceWithMultipleNodes"; + ChangeKind[ChangeKind["Text"] = 3] = "Text"; + })(ChangeKind || (ChangeKind = {})); + function getAdjustedRange(sourceFile, startNode, endNode, options) { + return { pos: getAdjustedStartPosition(sourceFile, startNode, options, Position.Start), end: getAdjustedEndPosition(sourceFile, endNode, options) }; + } + function getAdjustedStartPosition(sourceFile, node, options, position) { + if (options.useNonAdjustedStartPosition) { + return node.getStart(sourceFile); + } + var fullStart = node.getFullStart(); + var start = node.getStart(sourceFile); + if (fullStart === start) { + return start; + } + var fullStartLine = ts.getLineStartPositionForPosition(fullStart, sourceFile); + var startLine = ts.getLineStartPositionForPosition(start, sourceFile); + if (startLine === fullStartLine) { + // full start and start of the node are on the same line + // a, b; + // ^ ^ + // | start + // fullstart + // when b is replaced - we usually want to keep the leading trvia + // when b is deleted - we delete it + return position === Position.Start ? start : fullStart; + } + // get start position of the line following the line that contains fullstart position + // (but only if the fullstart isn't the very beginning of the file) + var nextLineStart = fullStart > 0 ? 1 : 0; + var adjustedStartPosition = ts.getStartPositionOfLine(ts.getLineOfLocalPosition(sourceFile, fullStartLine) + nextLineStart, sourceFile); + // skip whitespaces/newlines + adjustedStartPosition = skipWhitespacesAndLineBreaks(sourceFile.text, adjustedStartPosition); + return ts.getStartPositionOfLine(ts.getLineOfLocalPosition(sourceFile, adjustedStartPosition), sourceFile); + } + function getAdjustedEndPosition(sourceFile, node, options) { + var end = node.end; + if (options.useNonAdjustedEndPosition || ts.isExpression(node)) { + return end; + } + var newEnd = ts.skipTrivia(sourceFile.text, end, /*stopAfterLineBreak*/ true); + return newEnd !== end && ts.isLineBreak(sourceFile.text.charCodeAt(newEnd - 1)) + ? newEnd + : end; + } + /** + * Checks if 'candidate' argument is a legal separator in the list that contains 'node' as an element + */ + function isSeparator(node, candidate) { + return !!candidate && !!node.parent && (candidate.kind === 27 /* CommaToken */ || (candidate.kind === 26 /* SemicolonToken */ && node.parent.kind === 188 /* ObjectLiteralExpression */)); + } + function spaces(count) { + var s = ""; + for (var i = 0; i < count; i++) { + s += " "; + } + return s; + } + var ChangeTracker = /** @class */ (function () { + /** Public for tests only. Other callers should use `ChangeTracker.with`. */ + function ChangeTracker(newLineCharacter, formatContext) { + this.newLineCharacter = newLineCharacter; + this.formatContext = formatContext; + this.changes = []; + this.newFiles = []; + this.classesWithNodesInsertedAtStart = ts.createMap(); // Set implemented as Map + this.deletedNodes = []; + } + ChangeTracker.fromContext = function (context) { + return new ChangeTracker(ts.getNewLineOrDefaultFromHost(context.host, context.formatContext.options), context.formatContext); + }; + ChangeTracker.with = function (context, cb) { + var tracker = ChangeTracker.fromContext(context); + cb(tracker); + return tracker.getChanges(); + }; + ChangeTracker.prototype.deleteRange = function (sourceFile, range) { + this.changes.push({ kind: ChangeKind.Remove, sourceFile: sourceFile, range: range }); + }; + ChangeTracker.prototype.delete = function (sourceFile, node) { + this.deletedNodes.push({ sourceFile: sourceFile, node: node }); + }; + ChangeTracker.prototype.deleteModifier = function (sourceFile, modifier) { + this.deleteRange(sourceFile, { pos: modifier.getStart(sourceFile), end: ts.skipTrivia(sourceFile.text, modifier.end, /*stopAfterLineBreak*/ true) }); + }; + ChangeTracker.prototype.deleteNodeRange = function (sourceFile, startNode, endNode, options) { + if (options === void 0) { options = {}; } + var startPosition = getAdjustedStartPosition(sourceFile, startNode, options, Position.FullStart); + var endPosition = getAdjustedEndPosition(sourceFile, endNode, options); + this.deleteRange(sourceFile, { pos: startPosition, end: endPosition }); + }; + ChangeTracker.prototype.deleteNodeRangeExcludingEnd = function (sourceFile, startNode, afterEndNode, options) { + if (options === void 0) { options = {}; } + var startPosition = getAdjustedStartPosition(sourceFile, startNode, options, Position.FullStart); + var endPosition = afterEndNode === undefined ? sourceFile.text.length : getAdjustedStartPosition(sourceFile, afterEndNode, options, Position.FullStart); + this.deleteRange(sourceFile, { pos: startPosition, end: endPosition }); + }; + ChangeTracker.prototype.replaceRange = function (sourceFile, range, newNode, options) { + if (options === void 0) { options = {}; } + this.changes.push({ kind: ChangeKind.ReplaceWithSingleNode, sourceFile: sourceFile, range: range, options: options, node: newNode }); + }; + ChangeTracker.prototype.replaceNode = function (sourceFile, oldNode, newNode, options) { + if (options === void 0) { options = textChanges_3.useNonAdjustedPositions; } + this.replaceRange(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, options), newNode, options); + }; + ChangeTracker.prototype.replaceNodeRange = function (sourceFile, startNode, endNode, newNode, options) { + if (options === void 0) { options = textChanges_3.useNonAdjustedPositions; } + this.replaceRange(sourceFile, getAdjustedRange(sourceFile, startNode, endNode, options), newNode, options); + }; + ChangeTracker.prototype.replaceRangeWithNodes = function (sourceFile, range, newNodes, options) { + if (options === void 0) { options = {}; } + this.changes.push({ kind: ChangeKind.ReplaceWithMultipleNodes, sourceFile: sourceFile, range: range, options: options, nodes: newNodes }); + }; + ChangeTracker.prototype.replaceNodeWithNodes = function (sourceFile, oldNode, newNodes, options) { + if (options === void 0) { options = textChanges_3.useNonAdjustedPositions; } + this.replaceRangeWithNodes(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, options), newNodes, options); + }; + ChangeTracker.prototype.replaceNodeWithText = function (sourceFile, oldNode, text) { + this.replaceRangeWithText(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, textChanges_3.useNonAdjustedPositions), text); + }; + ChangeTracker.prototype.replaceNodeRangeWithNodes = function (sourceFile, startNode, endNode, newNodes, options) { + if (options === void 0) { options = textChanges_3.useNonAdjustedPositions; } + this.replaceRangeWithNodes(sourceFile, getAdjustedRange(sourceFile, startNode, endNode, options), newNodes, options); + }; + ChangeTracker.prototype.nextCommaToken = function (sourceFile, node) { + var next = ts.findNextToken(node, node.parent, sourceFile); + return next && next.kind === 27 /* CommaToken */ ? next : undefined; + }; + ChangeTracker.prototype.replacePropertyAssignment = function (sourceFile, oldNode, newNode) { + var suffix = this.nextCommaToken(sourceFile, oldNode) ? "" : ("," + this.newLineCharacter); + this.replaceNode(sourceFile, oldNode, newNode, { suffix: suffix }); + }; + ChangeTracker.prototype.insertNodeAt = function (sourceFile, pos, newNode, options) { + if (options === void 0) { options = {}; } + this.replaceRange(sourceFile, ts.createRange(pos), newNode, options); + }; + ChangeTracker.prototype.insertNodesAt = function (sourceFile, pos, newNodes, options) { + if (options === void 0) { options = {}; } + this.replaceRangeWithNodes(sourceFile, ts.createRange(pos), newNodes, options); + }; + ChangeTracker.prototype.insertNodeAtTopOfFile = function (sourceFile, newNode, blankLineBetween) { + var pos = getInsertionPositionAtSourceFileTop(sourceFile); + this.insertNodeAt(sourceFile, pos, newNode, { + prefix: pos === 0 ? undefined : this.newLineCharacter, + suffix: (ts.isLineBreak(sourceFile.text.charCodeAt(pos)) ? "" : this.newLineCharacter) + (blankLineBetween ? this.newLineCharacter : ""), + }); + }; + ChangeTracker.prototype.insertNodeBefore = function (sourceFile, before, newNode, blankLineBetween) { + if (blankLineBetween === void 0) { blankLineBetween = false; } + this.insertNodeAt(sourceFile, getAdjustedStartPosition(sourceFile, before, {}, Position.Start), newNode, this.getOptionsForInsertNodeBefore(before, blankLineBetween)); + }; + ChangeTracker.prototype.insertModifierBefore = function (sourceFile, modifier, before) { + var pos = before.getStart(sourceFile); + this.insertNodeAt(sourceFile, pos, ts.createToken(modifier), { suffix: " " }); + }; + ChangeTracker.prototype.insertLastModifierBefore = function (sourceFile, modifier, before) { + if (!before.modifiers) { + this.insertModifierBefore(sourceFile, modifier, before); + return; + } + var pos = before.modifiers.end; + this.insertNodeAt(sourceFile, pos, ts.createToken(modifier), { prefix: " " }); + }; + ChangeTracker.prototype.insertCommentBeforeLine = function (sourceFile, lineNumber, position, commentText) { + var lineStartPosition = ts.getStartPositionOfLine(lineNumber, sourceFile); + var startPosition = ts.getFirstNonSpaceCharacterPosition(sourceFile.text, lineStartPosition); + // First try to see if we can put the comment on the previous line. + // We need to make sure that we are not in the middle of a string literal or a comment. + // If so, we do not want to separate the node from its comment if we can. + // Otherwise, add an extra new line immediately before the error span. + var insertAtLineStart = isValidLocationToAddComment(sourceFile, startPosition); + var token = ts.getTouchingToken(sourceFile, insertAtLineStart ? startPosition : position); + var indent = sourceFile.text.slice(lineStartPosition, startPosition); + var text = (insertAtLineStart ? "" : this.newLineCharacter) + "//" + commentText + this.newLineCharacter + indent; + this.insertText(sourceFile, token.getStart(sourceFile), text); + }; + ChangeTracker.prototype.insertJsdocCommentBefore = function (sourceFile, node, tag) { + var fnStart = node.getStart(sourceFile); + if (node.jsDoc) { + for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { + var jsdoc = _a[_i]; + this.deleteRange(sourceFile, { + pos: ts.getLineStartPositionForPosition(jsdoc.getStart(sourceFile), sourceFile), + end: getAdjustedEndPosition(sourceFile, jsdoc, /*options*/ {}) + }); + } + } + var startPosition = ts.getPrecedingNonSpaceCharacterPosition(sourceFile.text, fnStart - 1); + var indent = sourceFile.text.slice(startPosition, fnStart); + this.insertNodeAt(sourceFile, fnStart, tag, { preserveLeadingWhitespace: false, suffix: this.newLineCharacter + indent }); + }; + ChangeTracker.prototype.replaceRangeWithText = function (sourceFile, range, text) { + this.changes.push({ kind: ChangeKind.Text, sourceFile: sourceFile, range: range, text: text }); + }; + ChangeTracker.prototype.insertText = function (sourceFile, pos, text) { + this.replaceRangeWithText(sourceFile, ts.createRange(pos), text); + }; + /** Prefer this over replacing a node with another that has a type annotation, as it avoids reformatting the other parts of the node. */ + ChangeTracker.prototype.tryInsertTypeAnnotation = function (sourceFile, node, type) { + var endNode; + if (ts.isFunctionLike(node)) { + endNode = ts.findChildOfKind(node, 21 /* CloseParenToken */, sourceFile); + if (!endNode) { + if (!ts.isArrowFunction(node)) + return; // Function missing parentheses, give up + // If no `)`, is an arrow function `x => x`, so use the end of the first parameter + endNode = ts.first(node.parameters); + } + } + else { + endNode = node.kind !== 237 /* VariableDeclaration */ && node.questionToken ? node.questionToken : node.name; + } + this.insertNodeAt(sourceFile, endNode.end, type, { prefix: ": " }); + }; + ChangeTracker.prototype.insertTypeParameters = function (sourceFile, node, typeParameters) { + // If no `(`, is an arrow function `x => x`, so use the pos of the first parameter + var start = (ts.findChildOfKind(node, 20 /* OpenParenToken */, sourceFile) || ts.first(node.parameters)).getStart(sourceFile); + this.insertNodesAt(sourceFile, start, typeParameters, { prefix: "<", suffix: ">" }); + }; + ChangeTracker.prototype.getOptionsForInsertNodeBefore = function (before, doubleNewlines) { + if (ts.isStatement(before) || ts.isClassElement(before)) { + return { suffix: doubleNewlines ? this.newLineCharacter + this.newLineCharacter : this.newLineCharacter }; + } + else if (ts.isVariableDeclaration(before)) { // insert `x = 1, ` into `const x = 1, y = 2; + return { suffix: ", " }; + } + else if (ts.isParameter(before)) { + return {}; + } + else if (ts.isStringLiteral(before) && ts.isImportDeclaration(before.parent) || ts.isNamedImports(before)) { + return { suffix: ", " }; + } + return ts.Debug.failBadSyntaxKind(before); // We haven't handled this kind of node yet -- add it + }; + ChangeTracker.prototype.insertNodeAtConstructorStart = function (sourceFile, ctr, newStatement) { + var firstStatement = ts.firstOrUndefined(ctr.body.statements); + if (!firstStatement || !ctr.body.multiLine) { + this.replaceConstructorBody(sourceFile, ctr, [newStatement].concat(ctr.body.statements)); + } + else { + this.insertNodeBefore(sourceFile, firstStatement, newStatement); + } + }; + ChangeTracker.prototype.insertNodeAtConstructorEnd = function (sourceFile, ctr, newStatement) { + var lastStatement = ts.lastOrUndefined(ctr.body.statements); + if (!lastStatement || !ctr.body.multiLine) { + this.replaceConstructorBody(sourceFile, ctr, ctr.body.statements.concat([newStatement])); + } + else { + this.insertNodeAfter(sourceFile, lastStatement, newStatement); + } + }; + ChangeTracker.prototype.replaceConstructorBody = function (sourceFile, ctr, statements) { + this.replaceNode(sourceFile, ctr.body, ts.createBlock(statements, /*multiLine*/ true)); + }; + ChangeTracker.prototype.insertNodeAtEndOfScope = function (sourceFile, scope, newNode) { + var pos = getAdjustedStartPosition(sourceFile, scope.getLastToken(), {}, Position.Start); + this.insertNodeAt(sourceFile, pos, newNode, { + prefix: ts.isLineBreak(sourceFile.text.charCodeAt(scope.getLastToken().pos)) ? this.newLineCharacter : this.newLineCharacter + this.newLineCharacter, + suffix: this.newLineCharacter + }); + }; + ChangeTracker.prototype.insertNodeAtClassStart = function (sourceFile, cls, newElement) { + this.insertNodeAtStartWorker(sourceFile, cls, newElement); + }; + ChangeTracker.prototype.insertNodeAtObjectStart = function (sourceFile, obj, newElement) { + this.insertNodeAtStartWorker(sourceFile, obj, newElement); + }; + ChangeTracker.prototype.insertNodeAtStartWorker = function (sourceFile, cls, newElement) { + var clsStart = cls.getStart(sourceFile); + var indentation = ts.formatting.SmartIndenter.findFirstNonWhitespaceColumn(ts.getLineStartPositionForPosition(clsStart, sourceFile), clsStart, sourceFile, this.formatContext.options) + + this.formatContext.options.indentSize; + this.insertNodeAt(sourceFile, getMembersOrProperties(cls).pos, newElement, __assign({ indentation: indentation }, this.getInsertNodeAtStartPrefixSuffix(sourceFile, cls))); + }; + ChangeTracker.prototype.getInsertNodeAtStartPrefixSuffix = function (sourceFile, cls) { + var comma = ts.isObjectLiteralExpression(cls) ? "," : ""; + if (getMembersOrProperties(cls).length === 0) { + if (ts.addToSeen(this.classesWithNodesInsertedAtStart, ts.getNodeId(cls), { node: cls, sourceFile: sourceFile })) { + // For `class C {\n}`, don't add the trailing "\n" + var shouldSuffix = ts.positionsAreOnSameLine.apply(void 0, getClassOrObjectBraceEnds(cls, sourceFile).concat([sourceFile])); // TODO: GH#4130 remove 'as any' + return { prefix: this.newLineCharacter, suffix: comma + (shouldSuffix ? this.newLineCharacter : "") }; + } + else { + return { prefix: "", suffix: comma + this.newLineCharacter }; + } + } + else { + return { prefix: this.newLineCharacter, suffix: comma }; + } + }; + ChangeTracker.prototype.insertNodeAfterComma = function (sourceFile, after, newNode) { + var endPosition = this.insertNodeAfterWorker(sourceFile, this.nextCommaToken(sourceFile, after) || after, newNode); + this.insertNodeAt(sourceFile, endPosition, newNode, this.getInsertNodeAfterOptions(sourceFile, after)); + }; + ChangeTracker.prototype.insertNodeAfter = function (sourceFile, after, newNode) { + var endPosition = this.insertNodeAfterWorker(sourceFile, after, newNode); + this.insertNodeAt(sourceFile, endPosition, newNode, this.getInsertNodeAfterOptions(sourceFile, after)); + }; + ChangeTracker.prototype.insertNodeAtEndOfList = function (sourceFile, list, newNode) { + this.insertNodeAt(sourceFile, list.end, newNode, { prefix: ", " }); + }; + ChangeTracker.prototype.insertNodesAfter = function (sourceFile, after, newNodes) { + var endPosition = this.insertNodeAfterWorker(sourceFile, after, ts.first(newNodes)); + this.insertNodesAt(sourceFile, endPosition, newNodes, this.getInsertNodeAfterOptions(sourceFile, after)); + }; + ChangeTracker.prototype.insertNodeAfterWorker = function (sourceFile, after, newNode) { + if (needSemicolonBetween(after, newNode)) { + // check if previous statement ends with semicolon + // if not - insert semicolon to preserve the code from changing the meaning due to ASI + if (sourceFile.text.charCodeAt(after.end - 1) !== 59 /* semicolon */) { + this.replaceRange(sourceFile, ts.createRange(after.end), ts.createToken(26 /* SemicolonToken */)); + } + } + var endPosition = getAdjustedEndPosition(sourceFile, after, {}); + return endPosition; + }; + ChangeTracker.prototype.getInsertNodeAfterOptions = function (sourceFile, after) { + var options = this.getInsertNodeAfterOptionsWorker(after); + return __assign({}, options, { prefix: after.end === sourceFile.end && ts.isStatement(after) ? (options.prefix ? "\n" + options.prefix : "\n") : options.prefix }); + }; + ChangeTracker.prototype.getInsertNodeAfterOptionsWorker = function (node) { + switch (node.kind) { + case 240 /* ClassDeclaration */: + case 244 /* ModuleDeclaration */: + return { prefix: this.newLineCharacter, suffix: this.newLineCharacter }; + case 237 /* VariableDeclaration */: + case 10 /* StringLiteral */: + case 72 /* Identifier */: + return { prefix: ", " }; + case 275 /* PropertyAssignment */: + return { suffix: "," + this.newLineCharacter }; + case 85 /* ExportKeyword */: + return { prefix: " " }; + case 151 /* Parameter */: + return {}; + default: + ts.Debug.assert(ts.isStatement(node) || ts.isClassOrTypeElement(node)); // Else we haven't handled this kind of node yet -- add it + return { suffix: this.newLineCharacter }; + } + }; + ChangeTracker.prototype.insertName = function (sourceFile, node, name) { + ts.Debug.assert(!node.name); + if (node.kind === 197 /* ArrowFunction */) { + var arrow = ts.findChildOfKind(node, 37 /* EqualsGreaterThanToken */, sourceFile); + var lparen = ts.findChildOfKind(node, 20 /* OpenParenToken */, sourceFile); + if (lparen) { + // `() => {}` --> `function f() {}` + this.insertNodesAt(sourceFile, lparen.getStart(sourceFile), [ts.createToken(90 /* FunctionKeyword */), ts.createIdentifier(name)], { joiner: " " }); + deleteNode(this, sourceFile, arrow); + } + else { + // `x => {}` -> `function f(x) {}` + this.insertText(sourceFile, ts.first(node.parameters).getStart(sourceFile), "function " + name + "("); + // Replacing full range of arrow to get rid of the leading space -- replace ` =>` with `)` + this.replaceRange(sourceFile, arrow, ts.createToken(21 /* CloseParenToken */)); + } + if (node.body.kind !== 218 /* Block */) { + // `() => 0` => `function f() { return 0; }` + this.insertNodesAt(sourceFile, node.body.getStart(sourceFile), [ts.createToken(18 /* OpenBraceToken */), ts.createToken(97 /* ReturnKeyword */)], { joiner: " ", suffix: " " }); + this.insertNodesAt(sourceFile, node.body.end, [ts.createToken(26 /* SemicolonToken */), ts.createToken(19 /* CloseBraceToken */)], { joiner: " " }); + } + } + else { + var pos = ts.findChildOfKind(node, node.kind === 196 /* FunctionExpression */ ? 90 /* FunctionKeyword */ : 76 /* ClassKeyword */, sourceFile).end; + this.insertNodeAt(sourceFile, pos, ts.createIdentifier(name), { prefix: " " }); + } + }; + ChangeTracker.prototype.insertExportModifier = function (sourceFile, node) { + this.insertText(sourceFile, node.getStart(sourceFile), "export "); + }; + /** + * This function should be used to insert nodes in lists when nodes don't carry separators as the part of the node range, + * i.e. arguments in arguments lists, parameters in parameter lists etc. + * Note that separators are part of the node in statements and class elements. + */ + ChangeTracker.prototype.insertNodeInListAfter = function (sourceFile, after, newNode, containingList) { + if (containingList === void 0) { containingList = ts.formatting.SmartIndenter.getContainingList(after, sourceFile); } + if (!containingList) { + ts.Debug.fail("node is not a list element"); + return; + } + var index = ts.indexOfNode(containingList, after); + if (index < 0) { + return; + } + var end = after.getEnd(); + if (index !== containingList.length - 1) { + // any element except the last one + // use next sibling as an anchor + var nextToken = ts.getTokenAtPosition(sourceFile, after.end); + if (nextToken && isSeparator(after, nextToken)) { + // for list + // a, b, c + // create change for adding 'e' after 'a' as + // - find start of next element after a (it is b) + // - use this start as start and end position in final change + // - build text of change by formatting the text of node + separator + whitespace trivia of b + // in multiline case it will work as + // a, + // b, + // c, + // result - '*' denotes leading trivia that will be inserted after new text (displayed as '#') + // a,* + // ***insertedtext# + // ###b, + // c, + // find line and character of the next element + var lineAndCharOfNextElement = ts.getLineAndCharacterOfPosition(sourceFile, skipWhitespacesAndLineBreaks(sourceFile.text, containingList[index + 1].getFullStart())); + // find line and character of the token that precedes next element (usually it is separator) + var lineAndCharOfNextToken = ts.getLineAndCharacterOfPosition(sourceFile, nextToken.end); + var prefix = void 0; + var startPos = void 0; + if (lineAndCharOfNextToken.line === lineAndCharOfNextElement.line) { + // next element is located on the same line with separator: + // a,$$$$b + // ^ ^ + // | |-next element + // |-separator + // where $$$ is some leading trivia + // for a newly inserted node we'll maintain the same relative position comparing to separator and replace leading trivia with spaces + // a, x,$$$$b + // ^ ^ ^ + // | | |-next element + // | |-new inserted node padded with spaces + // |-separator + startPos = nextToken.end; + prefix = spaces(lineAndCharOfNextElement.character - lineAndCharOfNextToken.character); + } + else { + // next element is located on different line that separator + // let insert position be the beginning of the line that contains next element + startPos = ts.getStartPositionOfLine(lineAndCharOfNextElement.line, sourceFile); + } + // write separator and leading trivia of the next element as suffix + var suffix = "" + ts.tokenToString(nextToken.kind) + sourceFile.text.substring(nextToken.end, containingList[index + 1].getStart(sourceFile)); + this.replaceRange(sourceFile, ts.createRange(startPos, containingList[index + 1].getStart(sourceFile)), newNode, { prefix: prefix, suffix: suffix }); + } + } + else { + var afterStart = after.getStart(sourceFile); + var afterStartLinePosition = ts.getLineStartPositionForPosition(afterStart, sourceFile); + var separator = void 0; + var multilineList = false; + // insert element after the last element in the list that has more than one item + // pick the element preceding the after element to: + // - pick the separator + // - determine if list is a multiline + if (containingList.length === 1) { + // if list has only one element then we'll format is as multiline if node has comment in trailing trivia, or as singleline otherwise + // i.e. var x = 1 // this is x + // | new element will be inserted at this position + separator = 27 /* CommaToken */; + } + else { + // element has more than one element, pick separator from the list + var tokenBeforeInsertPosition = ts.findPrecedingToken(after.pos, sourceFile); + separator = isSeparator(after, tokenBeforeInsertPosition) ? tokenBeforeInsertPosition.kind : 27 /* CommaToken */; + // determine if list is multiline by checking lines of after element and element that precedes it. + var afterMinusOneStartLinePosition = ts.getLineStartPositionForPosition(containingList[index - 1].getStart(sourceFile), sourceFile); + multilineList = afterMinusOneStartLinePosition !== afterStartLinePosition; + } + if (hasCommentsBeforeLineBreak(sourceFile.text, after.end)) { + // in this case we'll always treat containing list as multiline + multilineList = true; + } + if (multilineList) { + // insert separator immediately following the 'after' node to preserve comments in trailing trivia + this.replaceRange(sourceFile, ts.createRange(end), ts.createToken(separator)); + // use the same indentation as 'after' item + var indentation = ts.formatting.SmartIndenter.findFirstNonWhitespaceColumn(afterStartLinePosition, afterStart, sourceFile, this.formatContext.options); + // insert element before the line break on the line that contains 'after' element + var insertPos = ts.skipTrivia(sourceFile.text, end, /*stopAfterLineBreak*/ true, /*stopAtComments*/ false); + if (insertPos !== end && ts.isLineBreak(sourceFile.text.charCodeAt(insertPos - 1))) { + insertPos--; + } + this.replaceRange(sourceFile, ts.createRange(insertPos), newNode, { indentation: indentation, prefix: this.newLineCharacter }); + } + else { + this.replaceRange(sourceFile, ts.createRange(end), newNode, { prefix: ts.tokenToString(separator) + " " }); + } + } + }; + ChangeTracker.prototype.finishClassesWithNodesInsertedAtStart = function () { + var _this = this; + this.classesWithNodesInsertedAtStart.forEach(function (_a) { + var node = _a.node, sourceFile = _a.sourceFile; + var _b = getClassOrObjectBraceEnds(node, sourceFile), openBraceEnd = _b[0], closeBraceEnd = _b[1]; + // For `class C { }` remove the whitespace inside the braces. + if (ts.positionsAreOnSameLine(openBraceEnd, closeBraceEnd, sourceFile) && openBraceEnd !== closeBraceEnd - 1) { + _this.deleteRange(sourceFile, ts.createRange(openBraceEnd, closeBraceEnd - 1)); + } + }); + }; + ChangeTracker.prototype.finishDeleteDeclarations = function () { + var _this = this; + var deletedNodesInLists = new ts.NodeSet(); // Stores nodes in lists that we already deleted. Used to avoid deleting `, ` twice in `a, b`. + var _loop_17 = function (sourceFile, node) { + if (!this_1.deletedNodes.some(function (d) { return d.sourceFile === sourceFile && ts.rangeContainsRangeExclusive(d.node, node); })) { + if (ts.isArray(node)) { + this_1.deleteRange(sourceFile, ts.rangeOfTypeParameters(node)); + } + else { + deleteDeclaration.deleteDeclaration(this_1, deletedNodesInLists, sourceFile, node); + } + } + }; + var this_1 = this; + for (var _i = 0, _a = this.deletedNodes; _i < _a.length; _i++) { + var _b = _a[_i], sourceFile = _b.sourceFile, node = _b.node; + _loop_17(sourceFile, node); + } + deletedNodesInLists.forEach(function (node) { + var sourceFile = node.getSourceFile(); + var list = ts.formatting.SmartIndenter.getContainingList(node, sourceFile); + if (node !== ts.last(list)) + return; + var lastNonDeletedIndex = ts.findLastIndex(list, function (n) { return !deletedNodesInLists.has(n); }, list.length - 2); + if (lastNonDeletedIndex !== -1) { + _this.deleteRange(sourceFile, { pos: list[lastNonDeletedIndex].end, end: startPositionToDeleteNodeInList(sourceFile, list[lastNonDeletedIndex + 1]) }); + } + }); + }; + /** + * Note: after calling this, the TextChanges object must be discarded! + * @param validate only for tests + * The reason we must validate as part of this method is that `getNonFormattedText` changes the node's positions, + * so we can only call this once and can't get the non-formatted text separately. + */ + ChangeTracker.prototype.getChanges = function (validate) { + this.finishDeleteDeclarations(); + this.finishClassesWithNodesInsertedAtStart(); + var changes = changesToText.getTextChangesFromChanges(this.changes, this.newLineCharacter, this.formatContext, validate); + for (var _i = 0, _a = this.newFiles; _i < _a.length; _i++) { + var _b = _a[_i], oldFile = _b.oldFile, fileName = _b.fileName, statements = _b.statements; + changes.push(changesToText.newFileChanges(oldFile, fileName, statements, this.newLineCharacter, this.formatContext)); + } + return changes; + }; + ChangeTracker.prototype.createNewFile = function (oldFile, fileName, statements) { + this.newFiles.push({ oldFile: oldFile, fileName: fileName, statements: statements }); + }; + return ChangeTracker; + }()); + textChanges_3.ChangeTracker = ChangeTracker; + // find first non-whitespace position in the leading trivia of the node + function startPositionToDeleteNodeInList(sourceFile, node) { + return ts.skipTrivia(sourceFile.text, getAdjustedStartPosition(sourceFile, node, {}, Position.FullStart), /*stopAfterLineBreak*/ false, /*stopAtComments*/ true); + } + function getClassOrObjectBraceEnds(cls, sourceFile) { + return [ts.findChildOfKind(cls, 18 /* OpenBraceToken */, sourceFile).end, ts.findChildOfKind(cls, 19 /* CloseBraceToken */, sourceFile).end]; + } + function getMembersOrProperties(cls) { + return ts.isObjectLiteralExpression(cls) ? cls.properties : cls.members; + } + function getNewFileText(statements, scriptKind, newLineCharacter, formatContext) { + return changesToText.newFileChangesWorker(/*oldFile*/ undefined, scriptKind, statements, newLineCharacter, formatContext); + } + textChanges_3.getNewFileText = getNewFileText; + var changesToText; + (function (changesToText) { + function getTextChangesFromChanges(changes, newLineCharacter, formatContext, validate) { + return ts.group(changes, function (c) { return c.sourceFile.path; }).map(function (changesInFile) { + var sourceFile = changesInFile[0].sourceFile; + // order changes by start position + // If the start position is the same, put the shorter range first, since an empty range (x, x) may precede (x, y) but not vice-versa. + var normalized = ts.stableSort(changesInFile, function (a, b) { return (a.range.pos - b.range.pos) || (a.range.end - b.range.end); }); + var _loop_18 = function (i) { + ts.Debug.assert(normalized[i].range.end <= normalized[i + 1].range.pos, "Changes overlap", function () { + return JSON.stringify(normalized[i].range) + " and " + JSON.stringify(normalized[i + 1].range); + }); + }; + // verify that change intervals do not overlap, except possibly at end points. + for (var i = 0; i < normalized.length - 1; i++) { + _loop_18(i); + } + var textChanges = normalized.map(function (c) { + return ts.createTextChange(ts.createTextSpanFromRange(c.range), computeNewText(c, sourceFile, newLineCharacter, formatContext, validate)); + }); + return { fileName: sourceFile.fileName, textChanges: textChanges }; + }); + } + changesToText.getTextChangesFromChanges = getTextChangesFromChanges; + function newFileChanges(oldFile, fileName, statements, newLineCharacter, formatContext) { + var text = newFileChangesWorker(oldFile, ts.getScriptKindFromFileName(fileName), statements, newLineCharacter, formatContext); + return { fileName: fileName, textChanges: [ts.createTextChange(ts.createTextSpan(0, 0), text)], isNewFile: true }; + } + changesToText.newFileChanges = newFileChanges; + function newFileChangesWorker(oldFile, scriptKind, statements, newLineCharacter, formatContext) { + // TODO: this emits the file, parses it back, then formats it that -- may be a less roundabout way to do this + var nonFormattedText = statements.map(function (s) { return getNonformattedText(s, oldFile, newLineCharacter).text; }).join(newLineCharacter); + var sourceFile = ts.createSourceFile("any file name", nonFormattedText, 6 /* ESNext */, /*setParentNodes*/ true, scriptKind); + var changes = ts.formatting.formatDocument(sourceFile, formatContext); + return applyChanges(nonFormattedText, changes) + newLineCharacter; + } + changesToText.newFileChangesWorker = newFileChangesWorker; + function computeNewText(change, sourceFile, newLineCharacter, formatContext, validate) { + if (change.kind === ChangeKind.Remove) { + return ""; + } + if (change.kind === ChangeKind.Text) { + return change.text; + } + var _a = change.options, options = _a === void 0 ? {} : _a, pos = change.range.pos; + var format = function (n) { return getFormattedTextOfNode(n, sourceFile, pos, options, newLineCharacter, formatContext, validate); }; + var text = change.kind === ChangeKind.ReplaceWithMultipleNodes + ? change.nodes.map(function (n) { return ts.removeSuffix(format(n), newLineCharacter); }).join(change.options.joiner || newLineCharacter) // TODO: GH#18217 + : format(change.node); + // strip initial indentation (spaces or tabs) if text will be inserted in the middle of the line + var noIndent = (options.preserveLeadingWhitespace || options.indentation !== undefined || ts.getLineStartPositionForPosition(pos, sourceFile) === pos) ? text : text.replace(/^\s+/, ""); + return (options.prefix || "") + noIndent + (options.suffix || ""); + } + /** Note: this may mutate `nodeIn`. */ + function getFormattedTextOfNode(nodeIn, sourceFile, pos, _a, newLineCharacter, formatContext, validate) { + var indentation = _a.indentation, prefix = _a.prefix, delta = _a.delta; + var _b = getNonformattedText(nodeIn, sourceFile, newLineCharacter), node = _b.node, text = _b.text; + if (validate) + validate(node, text); + var formatOptions = formatContext.options; + var initialIndentation = indentation !== undefined + ? indentation + : ts.formatting.SmartIndenter.getIndentation(pos, sourceFile, formatOptions, prefix === newLineCharacter || ts.getLineStartPositionForPosition(pos, sourceFile) === pos); + if (delta === undefined) { + delta = ts.formatting.SmartIndenter.shouldIndentChildNode(formatContext.options, nodeIn) ? (formatOptions.indentSize || 0) : 0; + } + var file = { text: text, getLineAndCharacterOfPosition: function (pos) { return ts.getLineAndCharacterOfPosition(this, pos); } }; + var changes = ts.formatting.formatNodeGivenIndentation(node, file, sourceFile.languageVariant, initialIndentation, delta, formatContext); + return applyChanges(text, changes); + } + /** Note: output node may be mutated input node. */ + function getNonformattedText(node, sourceFile, newLineCharacter) { + var writer = new Writer(newLineCharacter); + var newLine = newLineCharacter === "\n" ? 1 /* LineFeed */ : 0 /* CarriageReturnLineFeed */; + ts.createPrinter({ newLine: newLine, neverAsciiEscape: true }, writer).writeNode(4 /* Unspecified */, node, sourceFile, writer); + return { text: writer.getText(), node: assignPositionsToNode(node) }; + } + changesToText.getNonformattedText = getNonformattedText; + })(changesToText || (changesToText = {})); + function applyChanges(text, changes) { + for (var i = changes.length - 1; i >= 0; i--) { + var _a = changes[i], span = _a.span, newText = _a.newText; + text = "" + text.substring(0, span.start) + newText + text.substring(ts.textSpanEnd(span)); + } + return text; + } + textChanges_3.applyChanges = applyChanges; + function isTrivia(s) { + return ts.skipTrivia(s, 0) === s.length; + } + function assignPositionsToNode(node) { + var visited = ts.visitEachChild(node, assignPositionsToNode, ts.nullTransformationContext, assignPositionsToNodeArray, assignPositionsToNode); // TODO: GH#18217 + // create proxy node for non synthesized nodes + var newNode = ts.nodeIsSynthesized(visited) ? visited : Object.create(visited); + newNode.pos = getPos(node); + newNode.end = getEnd(node); + return newNode; + } + function assignPositionsToNodeArray(nodes, visitor, test, start, count) { + var visited = ts.visitNodes(nodes, visitor, test, start, count); + if (!visited) { + return visited; + } + // clone nodearray if necessary + var nodeArray = visited === nodes ? ts.createNodeArray(visited.slice(0)) : visited; + nodeArray.pos = getPos(nodes); + nodeArray.end = getEnd(nodes); + return nodeArray; + } + var Writer = /** @class */ (function () { + function Writer(newLine) { + var _this = this; + this.lastNonTriviaPosition = 0; + this.writer = ts.createTextWriter(newLine); + this.onEmitNode = function (hint, node, printCallback) { + if (node) { + setPos(node, _this.lastNonTriviaPosition); + } + printCallback(hint, node); + if (node) { + setEnd(node, _this.lastNonTriviaPosition); + } + }; + this.onBeforeEmitNodeArray = function (nodes) { + if (nodes) { + setPos(nodes, _this.lastNonTriviaPosition); + } + }; + this.onAfterEmitNodeArray = function (nodes) { + if (nodes) { + setEnd(nodes, _this.lastNonTriviaPosition); + } + }; + this.onBeforeEmitToken = function (node) { + if (node) { + setPos(node, _this.lastNonTriviaPosition); + } + }; + this.onAfterEmitToken = function (node) { + if (node) { + setEnd(node, _this.lastNonTriviaPosition); + } + }; + } + Writer.prototype.setLastNonTriviaPosition = function (s, force) { + if (force || !isTrivia(s)) { + this.lastNonTriviaPosition = this.writer.getTextPos(); + var i = 0; + while (ts.isWhiteSpaceLike(s.charCodeAt(s.length - i - 1))) { + i++; + } + // trim trailing whitespaces + this.lastNonTriviaPosition -= i; + } + }; + Writer.prototype.write = function (s) { + this.writer.write(s); + this.setLastNonTriviaPosition(s, /*force*/ false); + }; + Writer.prototype.writeComment = function (s) { + this.writer.writeComment(s); + }; + Writer.prototype.writeKeyword = function (s) { + this.writer.writeKeyword(s); + this.setLastNonTriviaPosition(s, /*force*/ false); + }; + Writer.prototype.writeOperator = function (s) { + this.writer.writeOperator(s); + this.setLastNonTriviaPosition(s, /*force*/ false); + }; + Writer.prototype.writePunctuation = function (s) { + this.writer.writePunctuation(s); + this.setLastNonTriviaPosition(s, /*force*/ false); + }; + Writer.prototype.writeTrailingSemicolon = function (s) { + this.writer.writeTrailingSemicolon(s); + this.setLastNonTriviaPosition(s, /*force*/ false); + }; + Writer.prototype.writeParameter = function (s) { + this.writer.writeParameter(s); + this.setLastNonTriviaPosition(s, /*force*/ false); + }; + Writer.prototype.writeProperty = function (s) { + this.writer.writeProperty(s); + this.setLastNonTriviaPosition(s, /*force*/ false); + }; + Writer.prototype.writeSpace = function (s) { + this.writer.writeSpace(s); + this.setLastNonTriviaPosition(s, /*force*/ false); + }; + Writer.prototype.writeStringLiteral = function (s) { + this.writer.writeStringLiteral(s); + this.setLastNonTriviaPosition(s, /*force*/ false); + }; + Writer.prototype.writeSymbol = function (s, sym) { + this.writer.writeSymbol(s, sym); + this.setLastNonTriviaPosition(s, /*force*/ false); + }; + Writer.prototype.writeLine = function () { + this.writer.writeLine(); + }; + Writer.prototype.increaseIndent = function () { + this.writer.increaseIndent(); + }; + Writer.prototype.decreaseIndent = function () { + this.writer.decreaseIndent(); + }; + Writer.prototype.getText = function () { + return this.writer.getText(); + }; + Writer.prototype.rawWrite = function (s) { + this.writer.rawWrite(s); + this.setLastNonTriviaPosition(s, /*force*/ false); + }; + Writer.prototype.writeLiteral = function (s) { + this.writer.writeLiteral(s); + this.setLastNonTriviaPosition(s, /*force*/ true); + }; + Writer.prototype.getTextPos = function () { + return this.writer.getTextPos(); + }; + Writer.prototype.getLine = function () { + return this.writer.getLine(); + }; + Writer.prototype.getColumn = function () { + return this.writer.getColumn(); + }; + Writer.prototype.getIndent = function () { + return this.writer.getIndent(); + }; + Writer.prototype.isAtStartOfLine = function () { + return this.writer.isAtStartOfLine(); + }; + Writer.prototype.clear = function () { + this.writer.clear(); + this.lastNonTriviaPosition = 0; + }; + return Writer; + }()); + function getInsertionPositionAtSourceFileTop(sourceFile) { + var lastPrologue; + for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { + var node = _a[_i]; + if (ts.isPrologueDirective(node)) { + lastPrologue = node; + } + else { + break; + } + } + var position = 0; + var text = sourceFile.text; + if (lastPrologue) { + position = lastPrologue.end; + advancePastLineBreak(); + return position; + } + var shebang = ts.getShebang(text); + if (shebang !== undefined) { + position = shebang.length; + advancePastLineBreak(); + } + // For a source file, it is possible there are detached comments we should not skip + var ranges = ts.getLeadingCommentRanges(text, position); + if (!ranges) + return position; + // However we should still skip a pinned comment at the top + if (ranges.length && ranges[0].kind === 3 /* MultiLineCommentTrivia */ && ts.isPinnedComment(text, ranges[0].pos)) { + position = ranges[0].end; + advancePastLineBreak(); + ranges = ranges.slice(1); + } + // As well as any triple slash references + for (var _b = 0, ranges_1 = ranges; _b < ranges_1.length; _b++) { + var range = ranges_1[_b]; + if (range.kind === 2 /* SingleLineCommentTrivia */ && ts.isRecognizedTripleSlashComment(text, range.pos, range.end)) { + position = range.end; + advancePastLineBreak(); + continue; + } + break; + } + return position; + function advancePastLineBreak() { + if (position < text.length) { + var charCode = text.charCodeAt(position); + if (ts.isLineBreak(charCode)) { + position++; + if (position < text.length && charCode === 13 /* carriageReturn */ && text.charCodeAt(position) === 10 /* lineFeed */) { + position++; + } + } + } + } + } + function isValidLocationToAddComment(sourceFile, position) { + return !ts.isInComment(sourceFile, position) && !ts.isInString(sourceFile, position) && !ts.isInTemplateString(sourceFile, position) && !ts.isInJSXText(sourceFile, position); + } + textChanges_3.isValidLocationToAddComment = isValidLocationToAddComment; + function needSemicolonBetween(a, b) { + return (ts.isPropertySignature(a) || ts.isPropertyDeclaration(a)) && ts.isClassOrTypeElement(b) && b.name.kind === 149 /* ComputedPropertyName */ + || ts.isStatementButNotDeclaration(a) && ts.isStatementButNotDeclaration(b); // TODO: only if b would start with a `(` or `[` + } + var deleteDeclaration; + (function (deleteDeclaration_1) { + function deleteDeclaration(changes, deletedNodesInLists, sourceFile, node) { + switch (node.kind) { + case 151 /* Parameter */: { + var oldFunction = node.parent; + if (ts.isArrowFunction(oldFunction) && + oldFunction.parameters.length === 1 && + !ts.findChildOfKind(oldFunction, 20 /* OpenParenToken */, sourceFile)) { + // Lambdas with exactly one parameter are special because, after removal, there + // must be an empty parameter list (i.e. `()`) and this won't necessarily be the + // case if the parameter is simply removed (e.g. in `x => 1`). + changes.replaceNodeWithText(sourceFile, node, "()"); + } + else { + deleteNodeInList(changes, deletedNodesInLists, sourceFile, node); + } + break; + } + case 249 /* ImportDeclaration */: + deleteNode(changes, sourceFile, node, + // For first import, leave header comment in place + node === sourceFile.imports[0].parent ? { useNonAdjustedStartPosition: true, useNonAdjustedEndPosition: false } : undefined); + break; + case 186 /* BindingElement */: + var pattern = node.parent; + var preserveComma = pattern.kind === 185 /* ArrayBindingPattern */ && node !== ts.last(pattern.elements); + if (preserveComma) { + deleteNode(changes, sourceFile, node); + } + else { + deleteNodeInList(changes, deletedNodesInLists, sourceFile, node); + } + break; + case 237 /* VariableDeclaration */: + deleteVariableDeclaration(changes, deletedNodesInLists, sourceFile, node); + break; + case 150 /* TypeParameter */: + deleteNodeInList(changes, deletedNodesInLists, sourceFile, node); + break; + case 253 /* ImportSpecifier */: + var namedImports = node.parent; + if (namedImports.elements.length === 1) { + deleteImportBinding(changes, sourceFile, namedImports); + } + else { + deleteNodeInList(changes, deletedNodesInLists, sourceFile, node); + } + break; + case 251 /* NamespaceImport */: + deleteImportBinding(changes, sourceFile, node); + break; + default: + if (ts.isImportClause(node.parent) && node.parent.name === node) { + deleteDefaultImport(changes, sourceFile, node.parent); + } + else if (ts.isCallLikeExpression(node.parent)) { + deleteNodeInList(changes, deletedNodesInLists, sourceFile, node); + } + else { + deleteNode(changes, sourceFile, node, node.kind === 26 /* SemicolonToken */ ? { useNonAdjustedEndPosition: true } : undefined); + } + } + } + deleteDeclaration_1.deleteDeclaration = deleteDeclaration; + function deleteDefaultImport(changes, sourceFile, importClause) { + if (!importClause.namedBindings) { + // Delete the whole import + deleteNode(changes, sourceFile, importClause.parent); + } + else { + // import |d,| * as ns from './file' + var start = importClause.name.getStart(sourceFile); + var nextToken = ts.getTokenAtPosition(sourceFile, importClause.name.end); + if (nextToken && nextToken.kind === 27 /* CommaToken */) { + // shift first non-whitespace position after comma to the start position of the node + var end = ts.skipTrivia(sourceFile.text, nextToken.end, /*stopAfterLineBreaks*/ false, /*stopAtComments*/ true); + changes.deleteRange(sourceFile, { pos: start, end: end }); + } + else { + deleteNode(changes, sourceFile, importClause.name); + } + } + } + function deleteImportBinding(changes, sourceFile, node) { + if (node.parent.name) { + // Delete named imports while preserving the default import + // import d|, * as ns| from './file' + // import d|, { a }| from './file' + var previousToken = ts.Debug.assertDefined(ts.getTokenAtPosition(sourceFile, node.pos - 1)); + changes.deleteRange(sourceFile, { pos: previousToken.getStart(sourceFile), end: node.end }); + } + else { + // Delete the entire import declaration + // |import * as ns from './file'| + // |import { a } from './file'| + var importDecl = ts.getAncestor(node, 249 /* ImportDeclaration */); + deleteNode(changes, sourceFile, importDecl); + } + } + function deleteVariableDeclaration(changes, deletedNodesInLists, sourceFile, node) { + var parent = node.parent; + if (parent.kind === 274 /* CatchClause */) { + // TODO: There's currently no unused diagnostic for this, could be a suggestion + changes.deleteNodeRange(sourceFile, ts.findChildOfKind(parent, 20 /* OpenParenToken */, sourceFile), ts.findChildOfKind(parent, 21 /* CloseParenToken */, sourceFile)); + return; + } + if (parent.declarations.length !== 1) { + deleteNodeInList(changes, deletedNodesInLists, sourceFile, node); + return; + } + var gp = parent.parent; + switch (gp.kind) { + case 227 /* ForOfStatement */: + case 226 /* ForInStatement */: + changes.replaceNode(sourceFile, node, ts.createObjectLiteral()); + break; + case 225 /* ForStatement */: + deleteNode(changes, sourceFile, parent); + break; + case 219 /* VariableStatement */: + deleteNode(changes, sourceFile, gp); + break; + default: + ts.Debug.assertNever(gp); + } + } + })(deleteDeclaration || (deleteDeclaration = {})); + /** Warning: This deletes comments too. See `copyComments` in `convertFunctionToEs6Class`. */ + // Exported for tests only! (TODO: improve tests to not need this) + function deleteNode(changes, sourceFile, node, options) { + if (options === void 0) { options = {}; } + var startPosition = getAdjustedStartPosition(sourceFile, node, options, Position.FullStart); + var endPosition = getAdjustedEndPosition(sourceFile, node, options); + changes.deleteRange(sourceFile, { pos: startPosition, end: endPosition }); + } + textChanges_3.deleteNode = deleteNode; + function deleteNodeInList(changes, deletedNodesInLists, sourceFile, node) { + var containingList = ts.Debug.assertDefined(ts.formatting.SmartIndenter.getContainingList(node, sourceFile)); + var index = ts.indexOfNode(containingList, node); + ts.Debug.assert(index !== -1); + if (containingList.length === 1) { + deleteNode(changes, sourceFile, node); + return; + } + // Note: We will only delete a comma *after* a node. This will leave a trailing comma if we delete the last node. + // That's handled in the end by `finishTrailingCommaAfterDeletingNodesInList`. + ts.Debug.assert(!deletedNodesInLists.has(node), "Deleting a node twice"); + deletedNodesInLists.add(node); + changes.deleteRange(sourceFile, { + pos: startPositionToDeleteNodeInList(sourceFile, node), + end: index === containingList.length - 1 ? getAdjustedEndPosition(sourceFile, node, {}) : startPositionToDeleteNodeInList(sourceFile, containingList[index + 1]), + }); + } + })(textChanges = ts.textChanges || (ts.textChanges = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var errorCodeToFixes = ts.createMultiMap(); + var fixIdToRegistration = ts.createMap(); + function diagnosticToString(diag) { + return ts.isArray(diag) + ? ts.formatStringFromArgs(ts.getLocaleSpecificMessage(diag[0]), diag.slice(1)) + : ts.getLocaleSpecificMessage(diag); + } + function createCodeFixActionNoFixId(fixName, changes, description) { + return createCodeFixActionWorker(fixName, diagnosticToString(description), changes, /*fixId*/ undefined, /*fixAllDescription*/ undefined); + } + codefix.createCodeFixActionNoFixId = createCodeFixActionNoFixId; + function createCodeFixAction(fixName, changes, description, fixId, fixAllDescription, command) { + return createCodeFixActionWorker(fixName, diagnosticToString(description), changes, fixId, diagnosticToString(fixAllDescription), command); + } + codefix.createCodeFixAction = createCodeFixAction; + function createCodeFixActionWorker(fixName, description, changes, fixId, fixAllDescription, command) { + return { fixName: fixName, description: description, changes: changes, fixId: fixId, fixAllDescription: fixAllDescription, commands: command ? [command] : undefined }; + } + function registerCodeFix(reg) { + for (var _i = 0, _a = reg.errorCodes; _i < _a.length; _i++) { + var error = _a[_i]; + errorCodeToFixes.add(String(error), reg); + } + if (reg.fixIds) { + for (var _b = 0, _c = reg.fixIds; _b < _c.length; _b++) { + var fixId = _c[_b]; + ts.Debug.assert(!fixIdToRegistration.has(fixId)); + fixIdToRegistration.set(fixId, reg); + } + } + } + codefix.registerCodeFix = registerCodeFix; + function getSupportedErrorCodes() { + return ts.arrayFrom(errorCodeToFixes.keys()); + } + codefix.getSupportedErrorCodes = getSupportedErrorCodes; + function getFixes(context) { + return ts.flatMap(errorCodeToFixes.get(String(context.errorCode)) || ts.emptyArray, function (f) { return f.getCodeActions(context); }); + } + codefix.getFixes = getFixes; + function getAllFixes(context) { + // Currently fixId is always a string. + return fixIdToRegistration.get(ts.cast(context.fixId, ts.isString)).getAllCodeActions(context); + } + codefix.getAllFixes = getAllFixes; + function createCombinedCodeActions(changes, commands) { + return { changes: changes, commands: commands }; + } + codefix.createCombinedCodeActions = createCombinedCodeActions; + function createFileTextChanges(fileName, textChanges) { + return { fileName: fileName, textChanges: textChanges }; + } + codefix.createFileTextChanges = createFileTextChanges; + function codeFixAll(context, errorCodes, use) { + var commands = []; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return eachDiagnostic(context, errorCodes, function (diag) { return use(t, diag, commands); }); }); + return createCombinedCodeActions(changes, commands.length === 0 ? undefined : commands); + } + codefix.codeFixAll = codeFixAll; + function eachDiagnostic(_a, errorCodes, cb) { + var program = _a.program, sourceFile = _a.sourceFile, cancellationToken = _a.cancellationToken; + for (var _i = 0, _b = program.getSemanticDiagnostics(sourceFile, cancellationToken).concat(ts.computeSuggestionDiagnostics(sourceFile, program, cancellationToken)); _i < _b.length; _i++) { + var diag = _b[_i]; + if (ts.contains(errorCodes, diag.code)) { + cb(diag); + } + } + } + codefix.eachDiagnostic = eachDiagnostic; + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var refactor; + (function (refactor_1) { + // A map with the refactor code as key, the refactor itself as value + // e.g. nonSuggestableRefactors[refactorCode] -> the refactor you want + var refactors = ts.createMap(); + /** @param name An unique code associated with each refactor. Does not have to be human-readable. */ + function registerRefactor(name, refactor) { + refactors.set(name, refactor); + } + refactor_1.registerRefactor = registerRefactor; + function getApplicableRefactors(context) { + return ts.arrayFrom(ts.flatMapIterator(refactors.values(), function (refactor) { + return context.cancellationToken && context.cancellationToken.isCancellationRequested() ? undefined : refactor.getAvailableActions(context); + })); + } + refactor_1.getApplicableRefactors = getApplicableRefactors; + function getEditsForRefactor(context, refactorName, actionName) { + var refactor = refactors.get(refactorName); + return refactor && refactor.getEditsForAction(context, actionName); + } + refactor_1.getEditsForRefactor = getEditsForRefactor; + })(refactor = ts.refactor || (ts.refactor = {})); + function getRefactorContextSpan(_a) { + var startPosition = _a.startPosition, endPosition = _a.endPosition; + return ts.createTextSpanFromBounds(startPosition, endPosition === undefined ? startPosition : endPosition); + } + ts.getRefactorContextSpan = getRefactorContextSpan; +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "addConvertToUnknownForNonOverlappingTypes"; + var errorCodes = [ts.Diagnostics.Conversion_of_type_0_to_type_1_may_be_a_mistake_because_neither_type_sufficiently_overlaps_with_the_other_If_this_was_intentional_convert_the_expression_to_unknown_first.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return makeChange(t, context.sourceFile, context.span.start); }); + return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Add_unknown_conversion_for_non_overlapping_types, fixId, ts.Diagnostics.Add_unknown_to_all_conversions_of_non_overlapping_types)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { return makeChange(changes, diag.file, diag.start); }); }, + }); + function makeChange(changeTracker, sourceFile, pos) { + var token = ts.getTokenAtPosition(sourceFile, pos); + var assertion = ts.Debug.assertDefined(ts.findAncestor(token, function (n) { return ts.isAsExpression(n) || ts.isTypeAssertion(n); })); + var replacement = ts.isAsExpression(assertion) + ? ts.createAsExpression(assertion.expression, ts.createKeywordTypeNode(143 /* UnknownKeyword */)) + : ts.createTypeAssertion(ts.createKeywordTypeNode(143 /* UnknownKeyword */), assertion.expression); + changeTracker.replaceNode(sourceFile, assertion.expression, replacement); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "addMissingInvocationForDecorator"; + var errorCodes = [ts.Diagnostics._0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write_0.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return makeChange(t, context.sourceFile, context.span.start); }); + return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Call_decorator_expression, fixId, ts.Diagnostics.Add_to_all_uncalled_decorators)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { return makeChange(changes, diag.file, diag.start); }); }, + }); + function makeChange(changeTracker, sourceFile, pos) { + var token = ts.getTokenAtPosition(sourceFile, pos); + var decorator = ts.findAncestor(token, ts.isDecorator); + ts.Debug.assert(!!decorator, "Expected position to be owned by a decorator."); + var replacement = ts.createCall(decorator.expression, /*typeArguments*/ undefined, /*argumentsArray*/ undefined); + changeTracker.replaceNode(sourceFile, decorator.expression, replacement); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "annotateWithTypeFromJSDoc"; + var errorCodes = [ts.Diagnostics.JSDoc_types_may_be_moved_to_TypeScript_types.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var decl = getDeclaration(context.sourceFile, context.span.start); + if (!decl) + return; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, context.sourceFile, decl); }); + return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Annotate_with_type_from_JSDoc, fixId, ts.Diagnostics.Annotate_everything_with_types_from_JSDoc)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var decl = getDeclaration(diag.file, diag.start); + if (decl) + doChange(changes, diag.file, decl); + }); }, + }); + function getDeclaration(file, pos) { + var name = ts.getTokenAtPosition(file, pos); + // For an arrow function with no name, 'name' lands on the first parameter. + return ts.tryCast(ts.isParameter(name.parent) ? name.parent.parent : name.parent, parameterShouldGetTypeFromJSDoc); + } + function parameterShouldGetTypeFromJSDoc(node) { + return isDeclarationWithType(node) && hasUsableJSDoc(node); + } + codefix.parameterShouldGetTypeFromJSDoc = parameterShouldGetTypeFromJSDoc; + function hasUsableJSDoc(decl) { + return ts.isFunctionLikeDeclaration(decl) + ? decl.parameters.some(hasUsableJSDoc) || (!decl.type && !!ts.getJSDocReturnType(decl)) + : !decl.type && !!ts.getJSDocType(decl); + } + function doChange(changes, sourceFile, decl) { + if (ts.isFunctionLikeDeclaration(decl) && (ts.getJSDocReturnType(decl) || decl.parameters.some(function (p) { return !!ts.getJSDocType(p); }))) { + if (!decl.typeParameters) { + var typeParameters = ts.getJSDocTypeParameterDeclarations(decl); + if (typeParameters.length) + changes.insertTypeParameters(sourceFile, decl, typeParameters); + } + var needParens = ts.isArrowFunction(decl) && !ts.findChildOfKind(decl, 20 /* OpenParenToken */, sourceFile); + if (needParens) + changes.insertNodeBefore(sourceFile, ts.first(decl.parameters), ts.createToken(20 /* OpenParenToken */)); + for (var _i = 0, _a = decl.parameters; _i < _a.length; _i++) { + var param = _a[_i]; + if (!param.type) { + var paramType = ts.getJSDocType(param); + if (paramType) + changes.tryInsertTypeAnnotation(sourceFile, param, transformJSDocType(paramType)); + } + } + if (needParens) + changes.insertNodeAfter(sourceFile, ts.last(decl.parameters), ts.createToken(21 /* CloseParenToken */)); + if (!decl.type) { + var returnType = ts.getJSDocReturnType(decl); + if (returnType) + changes.tryInsertTypeAnnotation(sourceFile, decl, transformJSDocType(returnType)); + } + } + else { + var jsdocType = ts.Debug.assertDefined(ts.getJSDocType(decl)); // If not defined, shouldn't have been an error to fix + ts.Debug.assert(!decl.type); // If defined, shouldn't have been an error to fix. + changes.tryInsertTypeAnnotation(sourceFile, decl, transformJSDocType(jsdocType)); + } + } + function isDeclarationWithType(node) { + return ts.isFunctionLikeDeclaration(node) || + node.kind === 237 /* VariableDeclaration */ || + node.kind === 153 /* PropertySignature */ || + node.kind === 154 /* PropertyDeclaration */; + } + function transformJSDocType(node) { + switch (node.kind) { + case 284 /* JSDocAllType */: + case 285 /* JSDocUnknownType */: + return ts.createTypeReferenceNode("any", ts.emptyArray); + case 288 /* JSDocOptionalType */: + return transformJSDocOptionalType(node); + case 287 /* JSDocNonNullableType */: + return transformJSDocType(node.type); + case 286 /* JSDocNullableType */: + return transformJSDocNullableType(node); + case 290 /* JSDocVariadicType */: + return transformJSDocVariadicType(node); + case 289 /* JSDocFunctionType */: + return transformJSDocFunctionType(node); + case 164 /* TypeReference */: + return transformJSDocTypeReference(node); + default: + var visited = ts.visitEachChild(node, transformJSDocType, /*context*/ undefined); // TODO: GH#18217 + ts.setEmitFlags(visited, 1 /* SingleLine */); + return visited; + } + } + function transformJSDocOptionalType(node) { + return ts.createUnionTypeNode([ts.visitNode(node.type, transformJSDocType), ts.createTypeReferenceNode("undefined", ts.emptyArray)]); + } + function transformJSDocNullableType(node) { + return ts.createUnionTypeNode([ts.visitNode(node.type, transformJSDocType), ts.createTypeReferenceNode("null", ts.emptyArray)]); + } + function transformJSDocVariadicType(node) { + return ts.createArrayTypeNode(ts.visitNode(node.type, transformJSDocType)); + } + function transformJSDocFunctionType(node) { + return ts.createFunctionTypeNode(ts.emptyArray, node.parameters.map(transformJSDocParameter), node.type); + } + function transformJSDocParameter(node) { + var index = node.parent.parameters.indexOf(node); + var isRest = node.type.kind === 290 /* JSDocVariadicType */ && index === node.parent.parameters.length - 1; // TODO: GH#18217 + var name = node.name || (isRest ? "rest" : "arg" + index); + var dotdotdot = isRest ? ts.createToken(25 /* DotDotDotToken */) : node.dotDotDotToken; + return ts.createParameter(node.decorators, node.modifiers, dotdotdot, name, node.questionToken, ts.visitNode(node.type, transformJSDocType), node.initializer); + } + function transformJSDocTypeReference(node) { + var name = node.typeName; + var args = node.typeArguments; + if (ts.isIdentifier(node.typeName)) { + if (ts.isJSDocIndexSignature(node)) { + return transformJSDocIndexSignature(node); + } + var text = node.typeName.text; + switch (node.typeName.text) { + case "String": + case "Boolean": + case "Object": + case "Number": + text = text.toLowerCase(); + break; + case "array": + case "date": + case "promise": + text = text[0].toUpperCase() + text.slice(1); + break; + } + name = ts.createIdentifier(text); + if ((text === "Array" || text === "Promise") && !node.typeArguments) { + args = ts.createNodeArray([ts.createTypeReferenceNode("any", ts.emptyArray)]); + } + else { + args = ts.visitNodes(node.typeArguments, transformJSDocType); + } + } + return ts.createTypeReferenceNode(name, args); + } + function transformJSDocIndexSignature(node) { + var index = ts.createParameter( + /*decorators*/ undefined, + /*modifiers*/ undefined, + /*dotDotDotToken*/ undefined, node.typeArguments[0].kind === 135 /* NumberKeyword */ ? "n" : "s", + /*questionToken*/ undefined, ts.createTypeReferenceNode(node.typeArguments[0].kind === 135 /* NumberKeyword */ ? "number" : "string", []), + /*initializer*/ undefined); + var indexSignature = ts.createTypeLiteralNode([ts.createIndexSignature(/*decorators*/ undefined, /*modifiers*/ undefined, [index], node.typeArguments[1])]); + ts.setEmitFlags(indexSignature, 1 /* SingleLine */); + return indexSignature; + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "inferFromUsage"; + var errorCodes = [ + // Variable declarations + ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code, + // Variable uses + ts.Diagnostics.Variable_0_implicitly_has_an_1_type.code, + // Parameter declarations + ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code, + ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code, + // Get Accessor declarations + ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation.code, + ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type.code, + // Set Accessor declarations + ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code, + // Property declarations + ts.Diagnostics.Member_0_implicitly_has_an_1_type.code, + //// Suggestions + // Variable declarations + ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_but_a_better_type_may_be_inferred_from_usage.code, + // Variable uses + ts.Diagnostics.Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code, + // Parameter declarations + ts.Diagnostics.Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code, + ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage.code, + // Get Accessor declarations + ts.Diagnostics.Property_0_implicitly_has_type_any_but_a_better_type_for_its_get_accessor_may_be_inferred_from_usage.code, + ts.Diagnostics._0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage.code, + // Set Accessor declarations + ts.Diagnostics.Property_0_implicitly_has_type_any_but_a_better_type_for_its_set_accessor_may_be_inferred_from_usage.code, + // Property declarations + ts.Diagnostics.Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code, + ]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var sourceFile = context.sourceFile, program = context.program, start = context.span.start, errorCode = context.errorCode, cancellationToken = context.cancellationToken, host = context.host; + var token = ts.getTokenAtPosition(sourceFile, start); + var declaration; + var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { declaration = doChange(changes, sourceFile, token, errorCode, program, cancellationToken, /*markSeen*/ ts.returnTrue, host); }); + var name = declaration && ts.getNameOfDeclaration(declaration); + return !name || changes.length === 0 ? undefined + : [codefix.createCodeFixAction(fixId, changes, [getDiagnostic(errorCode, token), name.getText(sourceFile)], fixId, ts.Diagnostics.Infer_all_types_from_usage)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { + var sourceFile = context.sourceFile, program = context.program, cancellationToken = context.cancellationToken, host = context.host; + var markSeen = ts.nodeSeenTracker(); + return codefix.codeFixAll(context, errorCodes, function (changes, err) { + doChange(changes, sourceFile, ts.getTokenAtPosition(err.file, err.start), err.code, program, cancellationToken, markSeen, host); + }); + }, + }); + function getDiagnostic(errorCode, token) { + switch (errorCode) { + case ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code: + case ts.Diagnostics.Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code: + return ts.isSetAccessorDeclaration(ts.getContainingFunction(token)) ? ts.Diagnostics.Infer_type_of_0_from_usage : ts.Diagnostics.Infer_parameter_types_from_usage; // TODO: GH#18217 + case ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code: + case ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage.code: + return ts.Diagnostics.Infer_parameter_types_from_usage; + default: + return ts.Diagnostics.Infer_type_of_0_from_usage; + } + } + /** Map suggestion code to error code */ + function mapSuggestionDiagnostic(errorCode) { + switch (errorCode) { + case ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_but_a_better_type_may_be_inferred_from_usage.code: + return ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code; + case ts.Diagnostics.Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code: + return ts.Diagnostics.Variable_0_implicitly_has_an_1_type.code; + case ts.Diagnostics.Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code: + return ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code; + case ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage.code: + return ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code; + case ts.Diagnostics.Property_0_implicitly_has_type_any_but_a_better_type_for_its_get_accessor_may_be_inferred_from_usage.code: + return ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation.code; + case ts.Diagnostics._0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage.code: + return ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type.code; + case ts.Diagnostics.Property_0_implicitly_has_type_any_but_a_better_type_for_its_set_accessor_may_be_inferred_from_usage.code: + return ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code; + case ts.Diagnostics.Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code: + return ts.Diagnostics.Member_0_implicitly_has_an_1_type.code; + } + return errorCode; + } + function doChange(changes, sourceFile, token, errorCode, program, cancellationToken, markSeen, host) { + if (!ts.isParameterPropertyModifier(token.kind) && token.kind !== 72 /* Identifier */ && token.kind !== 25 /* DotDotDotToken */ && token.kind !== 100 /* ThisKeyword */) { + return undefined; + } + var parent = token.parent; + errorCode = mapSuggestionDiagnostic(errorCode); + switch (errorCode) { + // Variable and Property declarations + case ts.Diagnostics.Member_0_implicitly_has_an_1_type.code: + case ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code: + if ((ts.isVariableDeclaration(parent) && markSeen(parent)) || ts.isPropertyDeclaration(parent) || ts.isPropertySignature(parent)) { // handle bad location + annotateVariableDeclaration(changes, sourceFile, parent, program, host, cancellationToken); + return parent; + } + if (ts.isPropertyAccessExpression(parent)) { + var type = inferTypeForVariableFromUsage(parent.name, program, cancellationToken); + var typeNode = getTypeNodeIfAccessible(type, parent, program, host); + if (typeNode) { + // Note that the codefix will never fire with an existing `@type` tag, so there is no need to merge tags + var typeTag = ts.createJSDocTypeTag(ts.createJSDocTypeExpression(typeNode), /*comment*/ ""); + addJSDocTags(changes, sourceFile, ts.cast(parent.parent.parent, ts.isExpressionStatement), [typeTag]); + } + return parent; + } + return undefined; + case ts.Diagnostics.Variable_0_implicitly_has_an_1_type.code: { + var symbol = program.getTypeChecker().getSymbolAtLocation(token); + if (symbol && symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && markSeen(symbol.valueDeclaration)) { + annotateVariableDeclaration(changes, sourceFile, symbol.valueDeclaration, program, host, cancellationToken); + return symbol.valueDeclaration; + } + return undefined; + } + } + var containingFunction = ts.getContainingFunction(token); + if (containingFunction === undefined) { + return undefined; + } + switch (errorCode) { + // Parameter declarations + case ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code: + if (ts.isSetAccessorDeclaration(containingFunction)) { + annotateSetAccessor(changes, sourceFile, containingFunction, program, host, cancellationToken); + return containingFunction; + } + // falls through + case ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code: + if (markSeen(containingFunction)) { + var param = ts.cast(parent, ts.isParameter); + annotateParameters(changes, sourceFile, param, containingFunction, program, host, cancellationToken); + return param; + } + return undefined; + // Get Accessor declarations + case ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation.code: + case ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type.code: + if (ts.isGetAccessorDeclaration(containingFunction) && ts.isIdentifier(containingFunction.name)) { + annotate(changes, sourceFile, containingFunction, inferTypeForVariableFromUsage(containingFunction.name, program, cancellationToken), program, host); + return containingFunction; + } + return undefined; + // Set Accessor declarations + case ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code: + if (ts.isSetAccessorDeclaration(containingFunction)) { + annotateSetAccessor(changes, sourceFile, containingFunction, program, host, cancellationToken); + return containingFunction; + } + return undefined; + default: + return ts.Debug.fail(String(errorCode)); + } + } + function annotateVariableDeclaration(changes, sourceFile, declaration, program, host, cancellationToken) { + if (ts.isIdentifier(declaration.name)) { + annotate(changes, sourceFile, declaration, inferTypeForVariableFromUsage(declaration.name, program, cancellationToken), program, host); + } + } + function annotateParameters(changes, sourceFile, parameterDeclaration, containingFunction, program, host, cancellationToken) { + if (!ts.isIdentifier(parameterDeclaration.name)) { + return; + } + var parameterInferences = inferTypeForParametersFromUsage(containingFunction, sourceFile, program, cancellationToken) || + containingFunction.parameters.map(function (p) { return ({ + declaration: p, + type: ts.isIdentifier(p.name) ? inferTypeForVariableFromUsage(p.name, program, cancellationToken) : program.getTypeChecker().getAnyType() + }); }); + ts.Debug.assert(containingFunction.parameters.length === parameterInferences.length); + if (ts.isInJSFile(containingFunction)) { + annotateJSDocParameters(changes, sourceFile, parameterInferences, program, host); + } + else { + var needParens = ts.isArrowFunction(containingFunction) && !ts.findChildOfKind(containingFunction, 20 /* OpenParenToken */, sourceFile); + if (needParens) + changes.insertNodeBefore(sourceFile, ts.first(containingFunction.parameters), ts.createToken(20 /* OpenParenToken */)); + for (var _i = 0, parameterInferences_1 = parameterInferences; _i < parameterInferences_1.length; _i++) { + var _a = parameterInferences_1[_i], declaration = _a.declaration, type = _a.type; + if (declaration && !declaration.type && !declaration.initializer) { + annotate(changes, sourceFile, declaration, type, program, host); + } + } + if (needParens) + changes.insertNodeAfter(sourceFile, ts.last(containingFunction.parameters), ts.createToken(21 /* CloseParenToken */)); + } + } + function annotateSetAccessor(changes, sourceFile, setAccessorDeclaration, program, host, cancellationToken) { + var param = ts.firstOrUndefined(setAccessorDeclaration.parameters); + if (param && ts.isIdentifier(setAccessorDeclaration.name) && ts.isIdentifier(param.name)) { + var type = inferTypeForVariableFromUsage(setAccessorDeclaration.name, program, cancellationToken); + if (type === program.getTypeChecker().getAnyType()) { + type = inferTypeForVariableFromUsage(param.name, program, cancellationToken); + } + if (ts.isInJSFile(setAccessorDeclaration)) { + annotateJSDocParameters(changes, sourceFile, [{ declaration: param, type: type }], program, host); + } + else { + annotate(changes, sourceFile, param, type, program, host); + } + } + } + function annotate(changes, sourceFile, declaration, type, program, host) { + var typeNode = getTypeNodeIfAccessible(type, declaration, program, host); + if (typeNode) { + if (ts.isInJSFile(sourceFile) && declaration.kind !== 153 /* PropertySignature */) { + var parent = ts.isVariableDeclaration(declaration) ? ts.tryCast(declaration.parent.parent, ts.isVariableStatement) : declaration; + if (!parent) { + return; + } + var typeExpression = ts.createJSDocTypeExpression(typeNode); + var typeTag = ts.isGetAccessorDeclaration(declaration) ? ts.createJSDocReturnTag(typeExpression, "") : ts.createJSDocTypeTag(typeExpression, ""); + addJSDocTags(changes, sourceFile, parent, [typeTag]); + } + else { + changes.tryInsertTypeAnnotation(sourceFile, declaration, typeNode); + } + } + } + function annotateJSDocParameters(changes, sourceFile, parameterInferences, program, host) { + var signature = parameterInferences.length && parameterInferences[0].declaration.parent; + if (!signature) { + return; + } + var paramTags = ts.mapDefined(parameterInferences, function (inference) { + var param = inference.declaration; + // only infer parameters that have (1) no type and (2) an accessible inferred type + if (param.initializer || ts.getJSDocType(param) || !ts.isIdentifier(param.name)) + return; + var typeNode = inference.type && getTypeNodeIfAccessible(inference.type, param, program, host); + var name = ts.getSynthesizedClone(param.name); + ts.setEmitFlags(name, 1536 /* NoComments */ | 2048 /* NoNestedComments */); + return typeNode && ts.createJSDocParamTag(name, !!inference.isOptional, ts.createJSDocTypeExpression(typeNode), ""); + }); + addJSDocTags(changes, sourceFile, signature, paramTags); + } + function addJSDocTags(changes, sourceFile, parent, newTags) { + var comments = ts.mapDefined(parent.jsDoc, function (j) { return j.comment; }); + var oldTags = ts.flatMapToMutable(parent.jsDoc, function (j) { return j.tags; }); + var unmergedNewTags = newTags.filter(function (newTag) { return !oldTags || !oldTags.some(function (tag, i) { + var merged = tryMergeJsdocTags(tag, newTag); + if (merged) + oldTags[i] = merged; + return !!merged; + }); }); + var tag = ts.createJSDocComment(comments.join("\n"), ts.createNodeArray((oldTags || ts.emptyArray).concat(unmergedNewTags))); + changes.insertJsdocCommentBefore(sourceFile, parent, tag); + } + function tryMergeJsdocTags(oldTag, newTag) { + if (oldTag.kind !== newTag.kind) { + return undefined; + } + switch (oldTag.kind) { + case 299 /* JSDocParameterTag */: { + var oldParam = oldTag; + var newParam = newTag; + return ts.isIdentifier(oldParam.name) && ts.isIdentifier(newParam.name) && oldParam.name.escapedText === newParam.name.escapedText + ? ts.createJSDocParamTag(newParam.name, newParam.isBracketed, newParam.typeExpression, oldParam.comment) + : undefined; + } + case 300 /* JSDocReturnTag */: + return ts.createJSDocReturnTag(newTag.typeExpression, oldTag.comment); + } + } + function getTypeNodeIfAccessible(type, enclosingScope, program, host) { + var checker = program.getTypeChecker(); + var typeIsAccessible = true; + var notAccessible = function () { typeIsAccessible = false; }; + var res = checker.typeToTypeNode(type, enclosingScope, /*flags*/ undefined, { + trackSymbol: function (symbol, declaration, meaning) { + // TODO: GH#18217 + typeIsAccessible = typeIsAccessible && checker.isSymbolAccessible(symbol, declaration, meaning, /*shouldComputeAliasToMarkVisible*/ false).accessibility === 0 /* Accessible */; + }, + reportInaccessibleThisError: notAccessible, + reportPrivateInBaseOfClassExpression: notAccessible, + reportInaccessibleUniqueSymbolError: notAccessible, + moduleResolverHost: { + readFile: host.readFile, + fileExists: host.fileExists, + directoryExists: host.directoryExists, + getSourceFiles: program.getSourceFiles, + getCurrentDirectory: program.getCurrentDirectory, + getCommonSourceDirectory: program.getCommonSourceDirectory, + } + }); + return typeIsAccessible ? res : undefined; + } + function getReferences(token, program, cancellationToken) { + // Position shouldn't matter since token is not a SourceFile. + return ts.mapDefined(ts.FindAllReferences.getReferenceEntriesForNode(-1, token, program, program.getSourceFiles(), cancellationToken), function (entry) { + return entry.kind !== 0 /* Span */ ? ts.tryCast(entry.node, ts.isIdentifier) : undefined; + }); + } + function inferTypeForVariableFromUsage(token, program, cancellationToken) { + var references = getReferences(token, program, cancellationToken); + var checker = program.getTypeChecker(); + var types = InferFromReference.inferTypesFromReferences(references, checker, cancellationToken); + return InferFromReference.unifyFromContext(types, checker); + } + function inferTypeForParametersFromUsage(containingFunction, sourceFile, program, cancellationToken) { + var searchToken; + switch (containingFunction.kind) { + case 157 /* Constructor */: + searchToken = ts.findChildOfKind(containingFunction, 124 /* ConstructorKeyword */, sourceFile); + break; + case 197 /* ArrowFunction */: + case 196 /* FunctionExpression */: + var parent = containingFunction.parent; + searchToken = ts.isVariableDeclaration(parent) && ts.isIdentifier(parent.name) ? + parent.name : + containingFunction.name; + break; + case 239 /* FunctionDeclaration */: + case 156 /* MethodDeclaration */: + searchToken = containingFunction.name; + break; + } + if (searchToken) { + return InferFromReference.inferTypeForParametersFromReferences(getReferences(searchToken, program, cancellationToken), containingFunction, program, cancellationToken); + } + } + var InferFromReference; + (function (InferFromReference) { + function inferTypesFromReferences(references, checker, cancellationToken) { + var usageContext = {}; + for (var _i = 0, references_1 = references; _i < references_1.length; _i++) { + var reference = references_1[_i]; + cancellationToken.throwIfCancellationRequested(); + inferTypeFromContext(reference, checker, usageContext); + } + return inferFromContext(usageContext, checker); + } + InferFromReference.inferTypesFromReferences = inferTypesFromReferences; + function inferTypeForParametersFromReferences(references, declaration, program, cancellationToken) { + var checker = program.getTypeChecker(); + if (references.length === 0) { + return undefined; + } + if (!declaration.parameters) { + return undefined; + } + var usageContext = {}; + for (var _i = 0, references_2 = references; _i < references_2.length; _i++) { + var reference = references_2[_i]; + cancellationToken.throwIfCancellationRequested(); + inferTypeFromContext(reference, checker, usageContext); + } + var callContexts = (usageContext.constructContexts || []).concat(usageContext.callContexts || []); + return declaration.parameters.map(function (parameter, parameterIndex) { + var types = []; + var isRest = ts.isRestParameter(parameter); + var isOptional = false; + for (var _i = 0, callContexts_1 = callContexts; _i < callContexts_1.length; _i++) { + var callContext = callContexts_1[_i]; + if (callContext.argumentTypes.length <= parameterIndex) { + isOptional = ts.isInJSFile(declaration); + types.push(checker.getUndefinedType()); + } + else if (isRest) { + for (var i = parameterIndex; i < callContext.argumentTypes.length; i++) { + types.push(checker.getBaseTypeOfLiteralType(callContext.argumentTypes[i])); + } + } + else { + types.push(checker.getBaseTypeOfLiteralType(callContext.argumentTypes[parameterIndex])); + } + } + if (ts.isIdentifier(parameter.name)) { + var inferred = inferTypesFromReferences(getReferences(parameter.name, program, cancellationToken), checker, cancellationToken); + types.push.apply(types, (isRest ? ts.mapDefined(inferred, checker.getElementTypeOfArrayType) : inferred)); + } + var type = unifyFromContext(types, checker); + return { + type: isRest ? checker.createArrayType(type) : type, + isOptional: isOptional && !isRest, + declaration: parameter + }; + }); + } + InferFromReference.inferTypeForParametersFromReferences = inferTypeForParametersFromReferences; + function inferTypeFromContext(node, checker, usageContext) { + while (ts.isRightSideOfQualifiedNameOrPropertyAccess(node)) { + node = node.parent; + } + switch (node.parent.kind) { + case 203 /* PostfixUnaryExpression */: + usageContext.isNumber = true; + break; + case 202 /* PrefixUnaryExpression */: + inferTypeFromPrefixUnaryExpressionContext(node.parent, usageContext); + break; + case 204 /* BinaryExpression */: + inferTypeFromBinaryExpressionContext(node, node.parent, checker, usageContext); + break; + case 271 /* CaseClause */: + case 272 /* DefaultClause */: + inferTypeFromSwitchStatementLabelContext(node.parent, checker, usageContext); + break; + case 191 /* CallExpression */: + case 192 /* NewExpression */: + if (node.parent.expression === node) { + inferTypeFromCallExpressionContext(node.parent, checker, usageContext); + } + else { + inferTypeFromContextualType(node, checker, usageContext); + } + break; + case 189 /* PropertyAccessExpression */: + inferTypeFromPropertyAccessExpressionContext(node.parent, checker, usageContext); + break; + case 190 /* ElementAccessExpression */: + inferTypeFromPropertyElementExpressionContext(node.parent, node, checker, usageContext); + break; + case 237 /* VariableDeclaration */: { + var _a = node.parent, name = _a.name, initializer = _a.initializer; + if (node === name) { + if (initializer) { // This can happen for `let x = null;` which still has an implicit-any error. + addCandidateType(usageContext, checker.getTypeAtLocation(initializer)); + } + break; + } + } + // falls through + default: + return inferTypeFromContextualType(node, checker, usageContext); + } + } + function inferTypeFromContextualType(node, checker, usageContext) { + if (ts.isExpressionNode(node)) { + addCandidateType(usageContext, checker.getContextualType(node)); + } + } + function inferTypeFromPrefixUnaryExpressionContext(node, usageContext) { + switch (node.operator) { + case 44 /* PlusPlusToken */: + case 45 /* MinusMinusToken */: + case 39 /* MinusToken */: + case 53 /* TildeToken */: + usageContext.isNumber = true; + break; + case 38 /* PlusToken */: + usageContext.isNumberOrString = true; + break; + // case SyntaxKind.ExclamationToken: + // no inferences here; + } + } + function inferTypeFromBinaryExpressionContext(node, parent, checker, usageContext) { + switch (parent.operatorToken.kind) { + // ExponentiationOperator + case 41 /* AsteriskAsteriskToken */: + // MultiplicativeOperator + case 40 /* AsteriskToken */: + case 42 /* SlashToken */: + case 43 /* PercentToken */: + // ShiftOperator + case 46 /* LessThanLessThanToken */: + case 47 /* GreaterThanGreaterThanToken */: + case 48 /* GreaterThanGreaterThanGreaterThanToken */: + // BitwiseOperator + case 49 /* AmpersandToken */: + case 50 /* BarToken */: + case 51 /* CaretToken */: + // CompoundAssignmentOperator + case 61 /* MinusEqualsToken */: + case 63 /* AsteriskAsteriskEqualsToken */: + case 62 /* AsteriskEqualsToken */: + case 64 /* SlashEqualsToken */: + case 65 /* PercentEqualsToken */: + case 69 /* AmpersandEqualsToken */: + case 70 /* BarEqualsToken */: + case 71 /* CaretEqualsToken */: + case 66 /* LessThanLessThanEqualsToken */: + case 68 /* GreaterThanGreaterThanGreaterThanEqualsToken */: + case 67 /* GreaterThanGreaterThanEqualsToken */: + // AdditiveOperator + case 39 /* MinusToken */: + // RelationalOperator + case 28 /* LessThanToken */: + case 31 /* LessThanEqualsToken */: + case 30 /* GreaterThanToken */: + case 32 /* GreaterThanEqualsToken */: + var operandType = checker.getTypeAtLocation(parent.left === node ? parent.right : parent.left); + if (operandType.flags & 1056 /* EnumLike */) { + addCandidateType(usageContext, operandType); + } + else { + usageContext.isNumber = true; + } + break; + case 60 /* PlusEqualsToken */: + case 38 /* PlusToken */: + var otherOperandType = checker.getTypeAtLocation(parent.left === node ? parent.right : parent.left); + if (otherOperandType.flags & 1056 /* EnumLike */) { + addCandidateType(usageContext, otherOperandType); + } + else if (otherOperandType.flags & 296 /* NumberLike */) { + usageContext.isNumber = true; + } + else if (otherOperandType.flags & 132 /* StringLike */) { + usageContext.isString = true; + } + else { + usageContext.isNumberOrString = true; + } + break; + // AssignmentOperators + case 59 /* EqualsToken */: + case 33 /* EqualsEqualsToken */: + case 35 /* EqualsEqualsEqualsToken */: + case 36 /* ExclamationEqualsEqualsToken */: + case 34 /* ExclamationEqualsToken */: + addCandidateType(usageContext, checker.getTypeAtLocation(parent.left === node ? parent.right : parent.left)); + break; + case 93 /* InKeyword */: + if (node === parent.left) { + usageContext.isString = true; + } + break; + // LogicalOperator + case 55 /* BarBarToken */: + if (node === parent.left && + (node.parent.parent.kind === 237 /* VariableDeclaration */ || ts.isAssignmentExpression(node.parent.parent, /*excludeCompoundAssignment*/ true))) { + // var x = x || {}; + // TODO: use getFalsyflagsOfType + addCandidateType(usageContext, checker.getTypeAtLocation(parent.right)); + } + break; + case 54 /* AmpersandAmpersandToken */: + case 27 /* CommaToken */: + case 94 /* InstanceOfKeyword */: + // nothing to infer here + break; + } + } + function inferTypeFromSwitchStatementLabelContext(parent, checker, usageContext) { + addCandidateType(usageContext, checker.getTypeAtLocation(parent.parent.parent.expression)); + } + function inferTypeFromCallExpressionContext(parent, checker, usageContext) { + var callContext = { + argumentTypes: [], + returnType: {} + }; + if (parent.arguments) { + for (var _i = 0, _a = parent.arguments; _i < _a.length; _i++) { + var argument = _a[_i]; + callContext.argumentTypes.push(checker.getTypeAtLocation(argument)); + } + } + inferTypeFromContext(parent, checker, callContext.returnType); + if (parent.kind === 191 /* CallExpression */) { + (usageContext.callContexts || (usageContext.callContexts = [])).push(callContext); + } + else { + (usageContext.constructContexts || (usageContext.constructContexts = [])).push(callContext); + } + } + function inferTypeFromPropertyAccessExpressionContext(parent, checker, usageContext) { + var name = ts.escapeLeadingUnderscores(parent.name.text); + if (!usageContext.properties) { + usageContext.properties = ts.createUnderscoreEscapedMap(); + } + var propertyUsageContext = usageContext.properties.get(name) || {}; + inferTypeFromContext(parent, checker, propertyUsageContext); + usageContext.properties.set(name, propertyUsageContext); + } + function inferTypeFromPropertyElementExpressionContext(parent, node, checker, usageContext) { + if (node === parent.argumentExpression) { + usageContext.isNumberOrString = true; + return; + } + else { + var indexType = checker.getTypeAtLocation(parent.argumentExpression); + var indexUsageContext = {}; + inferTypeFromContext(parent, checker, indexUsageContext); + if (indexType.flags & 296 /* NumberLike */) { + usageContext.numberIndexContext = indexUsageContext; + } + else { + usageContext.stringIndexContext = indexUsageContext; + } + } + } + function removeLowPriorityInferences(inferences, priorities) { + var toRemove = []; + for (var _i = 0, inferences_2 = inferences; _i < inferences_2.length; _i++) { + var i = inferences_2[_i]; + for (var _a = 0, priorities_1 = priorities; _a < priorities_1.length; _a++) { + var _b = priorities_1[_a], high = _b.high, low = _b.low; + if (high(i)) { + ts.Debug.assert(!low(i)); + toRemove.push(low); + } + } + } + return inferences.filter(function (i) { return toRemove.every(function (f) { return !f(i); }); }); + } + function unifyFromContext(inferences, checker, fallback) { + if (fallback === void 0) { fallback = checker.getAnyType(); } + if (!inferences.length) + return fallback; + // 1. string or number individually override string | number + // 2. non-any, non-void overrides any or void + // 3. non-nullable, non-any, non-void, non-anonymous overrides anonymous types + var stringNumber = checker.getUnionType([checker.getStringType(), checker.getNumberType()]); + var priorities = [ + { + high: function (t) { return t === checker.getStringType() || t === checker.getNumberType(); }, + low: function (t) { return t === stringNumber; } + }, + { + high: function (t) { return !(t.flags & (1 /* Any */ | 16384 /* Void */)); }, + low: function (t) { return !!(t.flags & (1 /* Any */ | 16384 /* Void */)); } + }, + { + high: function (t) { return !(t.flags & (98304 /* Nullable */ | 1 /* Any */ | 16384 /* Void */)) && !(checker.getObjectFlags(t) & 16 /* Anonymous */); }, + low: function (t) { return !!(checker.getObjectFlags(t) & 16 /* Anonymous */); } + } + ]; + var good = removeLowPriorityInferences(inferences, priorities); + var anons = good.filter(function (i) { return checker.getObjectFlags(i) & 16 /* Anonymous */; }); + if (anons.length) { + good = good.filter(function (i) { return !(checker.getObjectFlags(i) & 16 /* Anonymous */); }); + good.push(unifyAnonymousTypes(anons, checker)); + } + return checker.getWidenedType(checker.getUnionType(good)); + } + InferFromReference.unifyFromContext = unifyFromContext; + function unifyAnonymousTypes(anons, checker) { + if (anons.length === 1) { + return anons[0]; + } + var calls = []; + var constructs = []; + var stringIndices = []; + var numberIndices = []; + var stringIndexReadonly = false; + var numberIndexReadonly = false; + var props = ts.createMultiMap(); + for (var _i = 0, anons_1 = anons; _i < anons_1.length; _i++) { + var anon = anons_1[_i]; + for (var _a = 0, _b = checker.getPropertiesOfType(anon); _a < _b.length; _a++) { + var p = _b[_a]; + props.add(p.name, checker.getTypeOfSymbolAtLocation(p, p.valueDeclaration)); + } + calls.push.apply(calls, checker.getSignaturesOfType(anon, 0 /* Call */)); + constructs.push.apply(constructs, checker.getSignaturesOfType(anon, 1 /* Construct */)); + if (anon.stringIndexInfo) { + stringIndices.push(anon.stringIndexInfo.type); + stringIndexReadonly = stringIndexReadonly || anon.stringIndexInfo.isReadonly; + } + if (anon.numberIndexInfo) { + numberIndices.push(anon.numberIndexInfo.type); + numberIndexReadonly = numberIndexReadonly || anon.numberIndexInfo.isReadonly; + } + } + var members = ts.mapEntries(props, function (name, types) { + var isOptional = types.length < anons.length ? 16777216 /* Optional */ : 0; + var s = checker.createSymbol(4 /* Property */ | isOptional, name); + s.type = checker.getUnionType(types); + return [name, s]; + }); + return checker.createAnonymousType(anons[0].symbol, members, calls, constructs, stringIndices.length ? checker.createIndexInfo(checker.getUnionType(stringIndices), stringIndexReadonly) : undefined, numberIndices.length ? checker.createIndexInfo(checker.getUnionType(numberIndices), numberIndexReadonly) : undefined); + } + function inferFromContext(usageContext, checker) { + var types = []; + if (usageContext.isNumber) { + types.push(checker.getNumberType()); + } + if (usageContext.isString) { + types.push(checker.getStringType()); + } + if (usageContext.isNumberOrString) { + types.push(checker.getUnionType([checker.getStringType(), checker.getNumberType()])); + } + types.push.apply(types, (usageContext.candidateTypes || []).map(function (t) { return checker.getBaseTypeOfLiteralType(t); })); + if (usageContext.properties && hasCallContext(usageContext.properties.get("then"))) { + var paramType = getParameterTypeFromCallContexts(0, usageContext.properties.get("then").callContexts, /*isRestParameter*/ false, checker); // TODO: GH#18217 + var types_19 = paramType.getCallSignatures().map(function (c) { return c.getReturnType(); }); + types_19.push(checker.createPromiseType(types_19.length ? checker.getUnionType(types_19, 2 /* Subtype */) : checker.getAnyType())); + } + else if (usageContext.properties && hasCallContext(usageContext.properties.get("push"))) { + types.push(checker.createArrayType(getParameterTypeFromCallContexts(0, usageContext.properties.get("push").callContexts, /*isRestParameter*/ false, checker))); + } + if (usageContext.numberIndexContext) { + types.push(checker.createArrayType(recur(usageContext.numberIndexContext))); + } + else if (usageContext.properties || usageContext.callContexts || usageContext.constructContexts || usageContext.stringIndexContext) { + var members_6 = ts.createUnderscoreEscapedMap(); + var callSignatures = []; + var constructSignatures = []; + var stringIndexInfo = void 0; + if (usageContext.properties) { + usageContext.properties.forEach(function (context, name) { + var symbol = checker.createSymbol(4 /* Property */, name); + symbol.type = recur(context); + members_6.set(name, symbol); + }); + } + if (usageContext.callContexts) { + for (var _i = 0, _a = usageContext.callContexts; _i < _a.length; _i++) { + var callContext = _a[_i]; + callSignatures.push(getSignatureFromCallContext(callContext, checker)); + } + } + if (usageContext.constructContexts) { + for (var _b = 0, _c = usageContext.constructContexts; _b < _c.length; _b++) { + var constructContext = _c[_b]; + constructSignatures.push(getSignatureFromCallContext(constructContext, checker)); + } + } + if (usageContext.stringIndexContext) { + stringIndexInfo = checker.createIndexInfo(recur(usageContext.stringIndexContext), /*isReadonly*/ false); + } + types.push(checker.createAnonymousType(/*symbol*/ undefined, members_6, callSignatures, constructSignatures, stringIndexInfo, /*numberIndexInfo*/ undefined)); // TODO: GH#18217 + } + return types; + function recur(innerContext) { + return unifyFromContext(inferFromContext(innerContext, checker), checker); + } + } + function getParameterTypeFromCallContexts(parameterIndex, callContexts, isRestParameter, checker) { + var types = []; + if (callContexts) { + for (var _i = 0, callContexts_2 = callContexts; _i < callContexts_2.length; _i++) { + var callContext = callContexts_2[_i]; + if (callContext.argumentTypes.length > parameterIndex) { + if (isRestParameter) { + types = ts.concatenate(types, ts.map(callContext.argumentTypes.slice(parameterIndex), function (a) { return checker.getBaseTypeOfLiteralType(a); })); + } + else { + types.push(checker.getBaseTypeOfLiteralType(callContext.argumentTypes[parameterIndex])); + } + } + } + } + if (types.length) { + var type = checker.getWidenedType(checker.getUnionType(types, 2 /* Subtype */)); + return isRestParameter ? checker.createArrayType(type) : type; + } + return undefined; + } + function getSignatureFromCallContext(callContext, checker) { + var parameters = []; + for (var i = 0; i < callContext.argumentTypes.length; i++) { + var symbol = checker.createSymbol(1 /* FunctionScopedVariable */, ts.escapeLeadingUnderscores("arg" + i)); + symbol.type = checker.getWidenedType(checker.getBaseTypeOfLiteralType(callContext.argumentTypes[i])); + parameters.push(symbol); + } + var returnType = unifyFromContext(inferFromContext(callContext.returnType, checker), checker, checker.getVoidType()); + // TODO: GH#18217 + return checker.createSignature(/*declaration*/ undefined, /*typeParameters*/ undefined, /*thisParameter*/ undefined, parameters, returnType, /*typePredicate*/ undefined, callContext.argumentTypes.length, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + } + function addCandidateType(context, type) { + if (type && !(type.flags & 1 /* Any */) && !(type.flags & 131072 /* Never */)) { + (context.candidateTypes || (context.candidateTypes = [])).push(type); + } + } + function hasCallContext(usageContext) { + return !!usageContext && !!usageContext.callContexts; + } + })(InferFromReference || (InferFromReference = {})); + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "convertFunctionToEs6Class"; + var errorCodes = [ts.Diagnostics.This_constructor_function_may_be_converted_to_a_class_declaration.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, context.sourceFile, context.span.start, context.program.getTypeChecker()); }); + return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Convert_function_to_an_ES2015_class, fixId, ts.Diagnostics.Convert_all_constructor_functions_to_classes)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, err) { return doChange(changes, err.file, err.start, context.program.getTypeChecker()); }); }, + }); + function doChange(changes, sourceFile, position, checker) { + var ctorSymbol = checker.getSymbolAtLocation(ts.getTokenAtPosition(sourceFile, position)); + if (!ctorSymbol || !(ctorSymbol.flags & (16 /* Function */ | 3 /* Variable */))) { + // Bad input + return undefined; + } + var ctorDeclaration = ctorSymbol.valueDeclaration; + var precedingNode; + var newClassDeclaration; + switch (ctorDeclaration.kind) { + case 239 /* FunctionDeclaration */: + precedingNode = ctorDeclaration; + changes.delete(sourceFile, ctorDeclaration); + newClassDeclaration = createClassFromFunctionDeclaration(ctorDeclaration); + break; + case 237 /* VariableDeclaration */: + precedingNode = ctorDeclaration.parent.parent; + newClassDeclaration = createClassFromVariableDeclaration(ctorDeclaration); + if (ctorDeclaration.parent.declarations.length === 1) { + ts.copyComments(precedingNode, newClassDeclaration, sourceFile); // TODO: GH#18217 + changes.delete(sourceFile, precedingNode); + } + else { + changes.delete(sourceFile, ctorDeclaration); + } + break; + } + if (!newClassDeclaration) { + return undefined; + } + ts.copyComments(ctorDeclaration, newClassDeclaration, sourceFile); + // Because the preceding node could be touched, we need to insert nodes before delete nodes. + changes.insertNodeAfter(sourceFile, precedingNode, newClassDeclaration); + function createClassElementsFromSymbol(symbol) { + var memberElements = []; + // all instance members are stored in the "member" array of symbol + if (symbol.members) { + symbol.members.forEach(function (member) { + var memberElement = createClassElement(member, /*modifiers*/ undefined); + if (memberElement) { + memberElements.push(memberElement); + } + }); + } + // all static members are stored in the "exports" array of symbol + if (symbol.exports) { + symbol.exports.forEach(function (member) { + var memberElement = createClassElement(member, [ts.createToken(116 /* StaticKeyword */)]); + if (memberElement) { + memberElements.push(memberElement); + } + }); + } + return memberElements; + function shouldConvertDeclaration(_target, source) { + // Right now the only thing we can convert are function expressions - other values shouldn't get + // transformed. We can update this once ES public class properties are available. + return ts.isFunctionLike(source); + } + function createClassElement(symbol, modifiers) { + // Right now the only thing we can convert are function expressions, which are marked as methods + if (!(symbol.flags & 8192 /* Method */)) { + return; + } + var memberDeclaration = symbol.valueDeclaration; + var assignmentBinaryExpression = memberDeclaration.parent; + if (!shouldConvertDeclaration(memberDeclaration, assignmentBinaryExpression.right)) { + return; + } + // delete the entire statement if this expression is the sole expression to take care of the semicolon at the end + var nodeToDelete = assignmentBinaryExpression.parent && assignmentBinaryExpression.parent.kind === 221 /* ExpressionStatement */ + ? assignmentBinaryExpression.parent : assignmentBinaryExpression; + changes.delete(sourceFile, nodeToDelete); + if (!assignmentBinaryExpression.right) { + return ts.createProperty([], modifiers, symbol.name, /*questionToken*/ undefined, + /*type*/ undefined, /*initializer*/ undefined); + } + switch (assignmentBinaryExpression.right.kind) { + case 196 /* FunctionExpression */: { + var functionExpression = assignmentBinaryExpression.right; + var fullModifiers = ts.concatenate(modifiers, getModifierKindFromSource(functionExpression, 121 /* AsyncKeyword */)); + var method = ts.createMethod(/*decorators*/ undefined, fullModifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined, + /*typeParameters*/ undefined, functionExpression.parameters, /*type*/ undefined, functionExpression.body); + ts.copyComments(assignmentBinaryExpression, method, sourceFile); + return method; + } + case 197 /* ArrowFunction */: { + var arrowFunction = assignmentBinaryExpression.right; + var arrowFunctionBody = arrowFunction.body; + var bodyBlock = void 0; + // case 1: () => { return [1,2,3] } + if (arrowFunctionBody.kind === 218 /* Block */) { + bodyBlock = arrowFunctionBody; + } + // case 2: () => [1,2,3] + else { + bodyBlock = ts.createBlock([ts.createReturn(arrowFunctionBody)]); + } + var fullModifiers = ts.concatenate(modifiers, getModifierKindFromSource(arrowFunction, 121 /* AsyncKeyword */)); + var method = ts.createMethod(/*decorators*/ undefined, fullModifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined, + /*typeParameters*/ undefined, arrowFunction.parameters, /*type*/ undefined, bodyBlock); + ts.copyComments(assignmentBinaryExpression, method, sourceFile); + return method; + } + default: { + // Don't try to declare members in JavaScript files + if (ts.isSourceFileJS(sourceFile)) { + return; + } + var prop = ts.createProperty(/*decorators*/ undefined, modifiers, memberDeclaration.name, /*questionToken*/ undefined, + /*type*/ undefined, assignmentBinaryExpression.right); + ts.copyComments(assignmentBinaryExpression.parent, prop, sourceFile); + return prop; + } + } + } + } + function createClassFromVariableDeclaration(node) { + var initializer = node.initializer; + if (!initializer || initializer.kind !== 196 /* FunctionExpression */) { + return undefined; + } + if (node.name.kind !== 72 /* Identifier */) { + return undefined; + } + var memberElements = createClassElementsFromSymbol(node.symbol); + if (initializer.body) { + memberElements.unshift(ts.createConstructor(/*decorators*/ undefined, /*modifiers*/ undefined, initializer.parameters, initializer.body)); + } + var modifiers = getModifierKindFromSource(precedingNode, 85 /* ExportKeyword */); + var cls = ts.createClassDeclaration(/*decorators*/ undefined, modifiers, node.name, + /*typeParameters*/ undefined, /*heritageClauses*/ undefined, memberElements); + // Don't call copyComments here because we'll already leave them in place + return cls; + } + function createClassFromFunctionDeclaration(node) { + var memberElements = createClassElementsFromSymbol(ctorSymbol); + if (node.body) { + memberElements.unshift(ts.createConstructor(/*decorators*/ undefined, /*modifiers*/ undefined, node.parameters, node.body)); + } + var modifiers = getModifierKindFromSource(node, 85 /* ExportKeyword */); + var cls = ts.createClassDeclaration(/*decorators*/ undefined, modifiers, node.name, + /*typeParameters*/ undefined, /*heritageClauses*/ undefined, memberElements); + // Don't call copyComments here because we'll already leave them in place + return cls; + } + } + function getModifierKindFromSource(source, kind) { + return ts.filter(source.modifiers, function (modifier) { return modifier.kind === kind; }); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "convertToAsyncFunction"; + var errorCodes = [ts.Diagnostics.This_may_be_converted_to_an_async_function.code]; + var codeActionSucceeded = true; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + codeActionSucceeded = true; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return convertToAsyncFunction(t, context.sourceFile, context.span.start, context.program.getTypeChecker(), context); }); + return codeActionSucceeded ? [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Convert_to_async_function, fixId, ts.Diagnostics.Convert_all_to_async_functions)] : []; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, err) { return convertToAsyncFunction(changes, err.file, err.start, context.program.getTypeChecker(), context); }); }, + }); + function convertToAsyncFunction(changes, sourceFile, position, checker, context) { + // get the function declaration - returns a promise + var tokenAtPosition = ts.getTokenAtPosition(sourceFile, position); + var functionToConvert; + // if the parent of a FunctionLikeDeclaration is a variable declaration, the convertToAsync diagnostic will be reported on the variable name + if (ts.isIdentifier(tokenAtPosition) && ts.isVariableDeclaration(tokenAtPosition.parent) && + tokenAtPosition.parent.initializer && ts.isFunctionLikeDeclaration(tokenAtPosition.parent.initializer)) { + functionToConvert = tokenAtPosition.parent.initializer; + } + else { + functionToConvert = ts.tryCast(ts.getContainingFunction(ts.getTokenAtPosition(sourceFile, position)), ts.isFunctionLikeDeclaration); + } + if (!functionToConvert) { + return; + } + var synthNamesMap = ts.createMap(); + var originalTypeMap = ts.createMap(); + var allVarNames = []; + var isInJavascript = ts.isInJSFile(functionToConvert); + var setOfExpressionsToReturn = getAllPromiseExpressionsToReturn(functionToConvert, checker); + var functionToConvertRenamed = renameCollidingVarNames(functionToConvert, checker, synthNamesMap, context, setOfExpressionsToReturn, originalTypeMap, allVarNames); + var constIdentifiers = getConstIdentifiers(synthNamesMap); + var returnStatements = functionToConvertRenamed.body && ts.isBlock(functionToConvertRenamed.body) ? getReturnStatementsWithPromiseHandlers(functionToConvertRenamed.body) : ts.emptyArray; + var transformer = { checker: checker, synthNamesMap: synthNamesMap, allVarNames: allVarNames, setOfExpressionsToReturn: setOfExpressionsToReturn, constIdentifiers: constIdentifiers, originalTypeMap: originalTypeMap, isInJSFile: isInJavascript }; + if (!returnStatements.length) { + return; + } + // add the async keyword + changes.insertLastModifierBefore(sourceFile, 121 /* AsyncKeyword */, functionToConvert); + function startTransformation(node, nodeToReplace) { + var newNodes = transformExpression(node, transformer, node); + changes.replaceNodeWithNodes(sourceFile, nodeToReplace, newNodes); + } + var _loop_19 = function (statement) { + ts.forEachChild(statement, function visit(node) { + if (ts.isCallExpression(node)) { + startTransformation(node, statement); + } + else if (!ts.isFunctionLike(node)) { + ts.forEachChild(node, visit); + } + }); + }; + for (var _i = 0, returnStatements_1 = returnStatements; _i < returnStatements_1.length; _i++) { + var statement = returnStatements_1[_i]; + _loop_19(statement); + } + } + function getReturnStatementsWithPromiseHandlers(body) { + var res = []; + ts.forEachReturnStatement(body, function (ret) { + if (ts.isReturnStatementWithFixablePromiseHandler(ret)) + res.push(ret); + }); + return res; + } + // Returns the identifiers that are never reassigned in the refactor + function getConstIdentifiers(synthNamesMap) { + var constIdentifiers = []; + synthNamesMap.forEach(function (val) { + if (val.numberOfAssignmentsOriginal === 0) { + constIdentifiers.push(val.identifier); + } + }); + return constIdentifiers; + } + /* + Finds all of the expressions of promise type that should not be saved in a variable during the refactor + */ + function getAllPromiseExpressionsToReturn(func, checker) { + if (!func.body) { + return ts.createMap(); + } + var setOfExpressionsToReturn = ts.createMap(); + ts.forEachChild(func.body, function visit(node) { + if (isPromiseReturningExpression(node, checker, "then")) { + setOfExpressionsToReturn.set(ts.getNodeId(node).toString(), true); + ts.forEach(node.arguments, visit); + } + else if (isPromiseReturningExpression(node, checker, "catch")) { + setOfExpressionsToReturn.set(ts.getNodeId(node).toString(), true); + // if .catch() is the last call in the chain, move leftward in the chain until we hit something else that should be returned + ts.forEachChild(node, visit); + } + else if (isPromiseReturningExpression(node, checker)) { + setOfExpressionsToReturn.set(ts.getNodeId(node).toString(), true); + // don't recurse here, since we won't refactor any children or arguments of the expression + } + else { + ts.forEachChild(node, visit); + } + }); + return setOfExpressionsToReturn; + } + /* + Returns true if node is a promise returning expression + If name is not undefined, node is a promise returning call of name + */ + function isPromiseReturningExpression(node, checker, name) { + var isNodeExpression = name ? ts.isCallExpression(node) : ts.isExpression(node); + var isExpressionOfName = isNodeExpression && (!name || ts.hasPropertyAccessExpressionWithName(node, name)); + var nodeType = isExpressionOfName && checker.getTypeAtLocation(node); + return !!(nodeType && checker.getPromisedTypeOfPromise(nodeType)); + } + function declaredInFile(symbol, sourceFile) { + return symbol.valueDeclaration && symbol.valueDeclaration.getSourceFile() === sourceFile; + } + /* + Renaming of identifiers may be neccesary as the refactor changes scopes - + This function collects all existing identifier names and names of identifiers that will be created in the refactor. + It then checks for any collisions and renames them through getSynthesizedDeepClone + */ + function renameCollidingVarNames(nodeToRename, checker, synthNamesMap, context, setOfAllExpressionsToReturn, originalType, allVarNames) { + var identsToRenameMap = ts.createMap(); // key is the symbol id + var collidingSymbolMap = ts.createMap(); + ts.forEachChild(nodeToRename, function visit(node) { + if (!ts.isIdentifier(node)) { + ts.forEachChild(node, visit); + return; + } + var symbol = checker.getSymbolAtLocation(node); + var isDefinedInFile = symbol && declaredInFile(symbol, context.sourceFile); + if (symbol && isDefinedInFile) { + var type = checker.getTypeAtLocation(node); + var lastCallSignature = getLastCallSignature(type, checker); + var symbolIdString = ts.getSymbolId(symbol).toString(); + // if the identifier refers to a function we want to add the new synthesized variable for the declaration (ex. blob in let blob = res(arg)) + // Note - the choice of the last call signature is arbitrary + if (lastCallSignature && !ts.isFunctionLikeDeclaration(node.parent) && !synthNamesMap.has(symbolIdString)) { + var firstParameter = ts.firstOrUndefined(lastCallSignature.parameters); + var ident = firstParameter && ts.isParameter(firstParameter.valueDeclaration) && ts.tryCast(firstParameter.valueDeclaration.name, ts.isIdentifier) || ts.createOptimisticUniqueName("result"); + var synthName = getNewNameIfConflict(ident, collidingSymbolMap); + synthNamesMap.set(symbolIdString, synthName); + allVarNames.push({ identifier: synthName.identifier, symbol: symbol }); + addNameToFrequencyMap(collidingSymbolMap, ident.text, symbol); + } + // we only care about identifiers that are parameters and declarations (don't care about other uses) + else if (node.parent && (ts.isParameter(node.parent) || ts.isVariableDeclaration(node.parent))) { + var originalName = node.text; + var collidingSymbols = collidingSymbolMap.get(originalName); + // if the identifier name conflicts with a different identifier that we've already seen + if (collidingSymbols && collidingSymbols.some(function (prevSymbol) { return prevSymbol !== symbol; })) { + var newName = getNewNameIfConflict(node, collidingSymbolMap); + identsToRenameMap.set(symbolIdString, newName.identifier); + synthNamesMap.set(symbolIdString, newName); + allVarNames.push({ identifier: newName.identifier, symbol: symbol }); + addNameToFrequencyMap(collidingSymbolMap, originalName, symbol); + } + else { + var identifier = ts.getSynthesizedDeepClone(node); + identsToRenameMap.set(symbolIdString, identifier); + synthNamesMap.set(symbolIdString, { identifier: identifier, types: [], numberOfAssignmentsOriginal: allVarNames.filter(function (elem) { return elem.identifier.text === node.text; }).length /*, numberOfAssignmentsSynthesized: 0*/ }); + if ((ts.isParameter(node.parent) && isExpressionOrCallOnTypePromise(node.parent.parent)) || ts.isVariableDeclaration(node.parent)) { + allVarNames.push({ identifier: identifier, symbol: symbol }); + addNameToFrequencyMap(collidingSymbolMap, originalName, symbol); + } + } + } + } + }); + return ts.getSynthesizedDeepCloneWithRenames(nodeToRename, /*includeTrivia*/ true, identsToRenameMap, checker, deepCloneCallback); + function isExpressionOrCallOnTypePromise(child) { + var node = child.parent; + if (ts.isCallExpression(node) || ts.isIdentifier(node) && !setOfAllExpressionsToReturn.get(ts.getNodeId(node).toString())) { + var nodeType = checker.getTypeAtLocation(node); + var isPromise = nodeType && checker.getPromisedTypeOfPromise(nodeType); + return !!isPromise; + } + return false; + } + function deepCloneCallback(node, clone) { + if (ts.isIdentifier(node)) { + var symbol = checker.getSymbolAtLocation(node); + var symboldIdString = symbol && ts.getSymbolId(symbol).toString(); + var renameInfo = symbol && synthNamesMap.get(symboldIdString); + if (renameInfo) { + var type = checker.getTypeAtLocation(node); + originalType.set(ts.getNodeId(clone).toString(), type); + } + } + var val = setOfAllExpressionsToReturn.get(ts.getNodeId(node).toString()); + if (val !== undefined) { + setOfAllExpressionsToReturn.delete(ts.getNodeId(node).toString()); + setOfAllExpressionsToReturn.set(ts.getNodeId(clone).toString(), val); + } + } + } + function addNameToFrequencyMap(renamedVarNameFrequencyMap, originalName, symbol) { + if (renamedVarNameFrequencyMap.has(originalName)) { + renamedVarNameFrequencyMap.get(originalName).push(symbol); + } + else { + renamedVarNameFrequencyMap.set(originalName, [symbol]); + } + } + function getNewNameIfConflict(name, originalNames) { + var numVarsSameName = (originalNames.get(name.text) || ts.emptyArray).length; + var numberOfAssignmentsOriginal = 0; + var identifier = numVarsSameName === 0 ? name : ts.createIdentifier(name.text + "_" + numVarsSameName); + return { identifier: identifier, types: [], numberOfAssignmentsOriginal: numberOfAssignmentsOriginal }; + } + // dispatch function to recursively build the refactoring + // should be kept up to date with isFixablePromiseHandler in suggestionDiagnostics.ts + function transformExpression(node, transformer, outermostParent, prevArgName) { + if (!node) { + return ts.emptyArray; + } + var originalType = ts.isIdentifier(node) && transformer.originalTypeMap.get(ts.getNodeId(node).toString()); + var nodeType = originalType || transformer.checker.getTypeAtLocation(node); + if (ts.isCallExpression(node) && ts.hasPropertyAccessExpressionWithName(node, "then") && nodeType && !!transformer.checker.getPromisedTypeOfPromise(nodeType)) { + return transformThen(node, transformer, outermostParent, prevArgName); + } + else if (ts.isCallExpression(node) && ts.hasPropertyAccessExpressionWithName(node, "catch") && nodeType && !!transformer.checker.getPromisedTypeOfPromise(nodeType)) { + return transformCatch(node, transformer, prevArgName); + } + else if (ts.isPropertyAccessExpression(node)) { + return transformExpression(node.expression, transformer, outermostParent, prevArgName); + } + else if (nodeType && transformer.checker.getPromisedTypeOfPromise(nodeType)) { + return transformPromiseCall(node, transformer, prevArgName); + } + codeActionSucceeded = false; + return ts.emptyArray; + } + function transformCatch(node, transformer, prevArgName) { + var func = node.arguments[0]; + var argName = getArgName(func, transformer); + var shouldReturn = transformer.setOfExpressionsToReturn.get(ts.getNodeId(node).toString()); + /* + If there is another call in the chain after the .catch() we are transforming, we will need to save the result of both paths (try block and catch block) + To do this, we will need to synthesize a variable that we were not aware of while we were adding identifiers to the synthNamesMap + We will use the prevArgName and then update the synthNamesMap with a new variable name for the next transformation step + */ + if (prevArgName && !shouldReturn) { + prevArgName.numberOfAssignmentsOriginal = 2; // Try block and catch block + transformer.synthNamesMap.forEach(function (val, key) { + if (val.identifier.text === prevArgName.identifier.text) { + var newSynthName = createUniqueSynthName(prevArgName); + transformer.synthNamesMap.set(key, newSynthName); + } + }); + // update the constIdentifiers list + if (transformer.constIdentifiers.some(function (elem) { return elem.text === prevArgName.identifier.text; })) { + transformer.constIdentifiers.push(createUniqueSynthName(prevArgName).identifier); + } + } + var tryBlock = ts.createBlock(transformExpression(node.expression, transformer, node, prevArgName)); + var transformationBody = getTransformationBody(func, prevArgName, argName, node, transformer); + var catchArg = argName ? argName.identifier.text : "e"; + var catchClause = ts.createCatchClause(catchArg, ts.createBlock(transformationBody)); + /* + In order to avoid an implicit any, we will synthesize a type for the declaration using the unions of the types of both paths (try block and catch block) + */ + var varDeclList; + if (prevArgName && !shouldReturn) { + var typeArray = prevArgName.types; + var unionType = transformer.checker.getUnionType(typeArray, 2 /* Subtype */); + var unionTypeNode = transformer.isInJSFile ? undefined : transformer.checker.typeToTypeNode(unionType); + var varDecl = [ts.createVariableDeclaration(ts.getSynthesizedDeepClone(prevArgName.identifier), unionTypeNode)]; + varDeclList = ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList(varDecl, 1 /* Let */)); + } + var tryStatement = ts.createTry(tryBlock, catchClause, /*finallyBlock*/ undefined); + return varDeclList ? [varDeclList, tryStatement] : [tryStatement]; + } + function createUniqueSynthName(prevArgName) { + var renamedPrevArg = ts.createOptimisticUniqueName(prevArgName.identifier.text); + var newSynthName = { identifier: renamedPrevArg, types: [], numberOfAssignmentsOriginal: 0 }; + return newSynthName; + } + function transformThen(node, transformer, outermostParent, prevArgName) { + var _a = node.arguments, res = _a[0], rej = _a[1]; + if (!res) { + return transformExpression(node.expression, transformer, outermostParent); + } + var argNameRes = getArgName(res, transformer); + var transformationBody = getTransformationBody(res, prevArgName, argNameRes, node, transformer); + if (rej) { + var argNameRej = getArgName(rej, transformer); + var tryBlock = ts.createBlock(transformExpression(node.expression, transformer, node, argNameRes).concat(transformationBody)); + var transformationBody2 = getTransformationBody(rej, prevArgName, argNameRej, node, transformer); + var catchArg = argNameRej ? argNameRej.identifier.text : "e"; + var catchClause = ts.createCatchClause(catchArg, ts.createBlock(transformationBody2)); + return [ts.createTry(tryBlock, catchClause, /* finallyBlock */ undefined)]; + } + return transformExpression(node.expression, transformer, node, argNameRes).concat(transformationBody); + } + function getFlagOfIdentifier(node, constIdentifiers) { + var inArr = constIdentifiers.some(function (elem) { return elem.text === node.text; }); + return inArr ? 2 /* Const */ : 1 /* Let */; + } + function transformPromiseCall(node, transformer, prevArgName) { + var shouldReturn = transformer.setOfExpressionsToReturn.get(ts.getNodeId(node).toString()); + // the identifier is empty when the handler (.then()) ignores the argument - In this situation we do not need to save the result of the promise returning call + var originalNodeParent = node.original ? node.original.parent : node.parent; + if (prevArgName && !shouldReturn && (!originalNodeParent || ts.isPropertyAccessExpression(originalNodeParent))) { + return createTransformedStatement(prevArgName, ts.createAwait(node), transformer); + } + else if (!prevArgName && !shouldReturn && (!originalNodeParent || ts.isPropertyAccessExpression(originalNodeParent))) { + return [ts.createStatement(ts.createAwait(node))]; + } + return [ts.createReturn(ts.getSynthesizedDeepClone(node))]; + } + function createTransformedStatement(prevArgName, rightHandSide, transformer) { + if (!prevArgName || prevArgName.identifier.text.length === 0) { + // if there's no argName to assign to, there still might be side effects + return [ts.createStatement(rightHandSide)]; + } + if (prevArgName.types.length < prevArgName.numberOfAssignmentsOriginal) { + // if the variable has already been declared, we don't need "let" or "const" + return [ts.createStatement(ts.createAssignment(ts.getSynthesizedDeepClone(prevArgName.identifier), rightHandSide))]; + } + return [ts.createVariableStatement(/*modifiers*/ undefined, (ts.createVariableDeclarationList([ts.createVariableDeclaration(ts.getSynthesizedDeepClone(prevArgName.identifier), /*type*/ undefined, rightHandSide)], getFlagOfIdentifier(prevArgName.identifier, transformer.constIdentifiers))))]; + } + // should be kept up to date with isFixablePromiseArgument in suggestionDiagnostics.ts + function getTransformationBody(func, prevArgName, argName, parent, transformer) { + var shouldReturn = transformer.setOfExpressionsToReturn.get(ts.getNodeId(parent).toString()); + switch (func.kind) { + case 96 /* NullKeyword */: + // do not produce a transformed statement for a null argument + break; + case 72 /* Identifier */: // identifier includes undefined + if (!argName) { + // undefined was argument passed to promise handler + break; + } + var synthCall = ts.createCall(ts.getSynthesizedDeepClone(func), /*typeArguments*/ undefined, [argName.identifier]); + if (shouldReturn) { + return [ts.createReturn(synthCall)]; + } + var type = transformer.originalTypeMap.get(ts.getNodeId(func).toString()) || transformer.checker.getTypeAtLocation(func); + var callSignatures = transformer.checker.getSignaturesOfType(type, 0 /* Call */); + if (!callSignatures.length) { + // if identifier in handler has no call signatures, it's invalid + codeActionSucceeded = false; + break; + } + var returnType = callSignatures[0].getReturnType(); + var varDeclOrAssignment = createTransformedStatement(prevArgName, ts.createAwait(synthCall), transformer); + if (prevArgName) { + prevArgName.types.push(returnType); + } + return varDeclOrAssignment; + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: { + var funcBody = func.body; + // Arrow functions with block bodies { } will enter this control flow + if (ts.isBlock(funcBody)) { + var refactoredStmts = []; + var seenReturnStatement = false; + for (var _i = 0, _a = funcBody.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + if (ts.isReturnStatement(statement)) { + seenReturnStatement = true; + } + if (ts.isReturnStatementWithFixablePromiseHandler(statement)) { + refactoredStmts = refactoredStmts.concat(getInnerTransformationBody(transformer, [statement], prevArgName)); + } + else { + refactoredStmts.push(statement); + } + } + return shouldReturn ? refactoredStmts.map(function (s) { return ts.getSynthesizedDeepClone(s); }) : + removeReturns(refactoredStmts, prevArgName === undefined ? undefined : prevArgName.identifier, transformer, seenReturnStatement); + } + else { + var innerRetStmts = ts.isFixablePromiseHandler(funcBody) ? [ts.createReturn(funcBody)] : ts.emptyArray; + var innerCbBody = getInnerTransformationBody(transformer, innerRetStmts, prevArgName); + if (innerCbBody.length > 0) { + return innerCbBody; + } + var type_6 = transformer.checker.getTypeAtLocation(func); + var returnType_1 = getLastCallSignature(type_6, transformer.checker).getReturnType(); + var rightHandSide = ts.getSynthesizedDeepClone(funcBody); + var possiblyAwaitedRightHandSide = !!transformer.checker.getPromisedTypeOfPromise(returnType_1) ? ts.createAwait(rightHandSide) : rightHandSide; + if (!shouldReturn) { + var transformedStatement = createTransformedStatement(prevArgName, possiblyAwaitedRightHandSide, transformer); + if (prevArgName) { + prevArgName.types.push(returnType_1); + } + return transformedStatement; + } + else { + return [ts.createReturn(possiblyAwaitedRightHandSide)]; + } + } + } + default: + // If no cases apply, we've found a transformation body we don't know how to handle, so the refactoring should no-op to avoid deleting code. + codeActionSucceeded = false; + break; + } + return ts.emptyArray; + } + function getLastCallSignature(type, checker) { + var callSignatures = checker.getSignaturesOfType(type, 0 /* Call */); + return ts.lastOrUndefined(callSignatures); + } + function removeReturns(stmts, prevArgName, transformer, seenReturnStatement) { + var ret = []; + for (var _i = 0, stmts_1 = stmts; _i < stmts_1.length; _i++) { + var stmt = stmts_1[_i]; + if (ts.isReturnStatement(stmt)) { + if (stmt.expression) { + var possiblyAwaitedExpression = isPromiseReturningExpression(stmt.expression, transformer.checker) ? ts.createAwait(stmt.expression) : stmt.expression; + if (prevArgName === undefined) { + ret.push(ts.createExpressionStatement(possiblyAwaitedExpression)); + } + else { + ret.push(ts.createVariableStatement(/*modifiers*/ undefined, (ts.createVariableDeclarationList([ts.createVariableDeclaration(prevArgName, /*type*/ undefined, possiblyAwaitedExpression)], getFlagOfIdentifier(prevArgName, transformer.constIdentifiers))))); + } + } + } + else { + ret.push(ts.getSynthesizedDeepClone(stmt)); + } + } + // if block has no return statement, need to define prevArgName as undefined to prevent undeclared variables + if (!seenReturnStatement && prevArgName !== undefined) { + ret.push(ts.createVariableStatement(/*modifiers*/ undefined, (ts.createVariableDeclarationList([ts.createVariableDeclaration(prevArgName, /*type*/ undefined, ts.createIdentifier("undefined"))], getFlagOfIdentifier(prevArgName, transformer.constIdentifiers))))); + } + return ret; + } + function getInnerTransformationBody(transformer, innerRetStmts, prevArgName) { + var innerCbBody = []; + for (var _i = 0, innerRetStmts_1 = innerRetStmts; _i < innerRetStmts_1.length; _i++) { + var stmt = innerRetStmts_1[_i]; + ts.forEachChild(stmt, function visit(node) { + if (ts.isCallExpression(node)) { + var temp = transformExpression(node, transformer, node, prevArgName); + innerCbBody = innerCbBody.concat(temp); + if (innerCbBody.length > 0) { + return; + } + } + else if (!ts.isFunctionLike(node)) { + ts.forEachChild(node, visit); + } + }); + } + return innerCbBody; + } + function getArgName(funcNode, transformer) { + var numberOfAssignmentsOriginal = 0; + var types = []; + var name; + if (ts.isFunctionLikeDeclaration(funcNode)) { + if (funcNode.parameters.length > 0) { + var param = funcNode.parameters[0].name; + name = getMapEntryOrDefault(param); + } + } + else if (ts.isIdentifier(funcNode)) { + name = getMapEntryOrDefault(funcNode); + } + // return undefined argName when arg is null or undefined + if (!name || name.identifier.text === "undefined") { + return undefined; + } + return name; + function getMapEntryOrDefault(identifier) { + var originalNode = getOriginalNode(identifier); + var symbol = getSymbol(originalNode); + if (!symbol) { + return { identifier: identifier, types: types, numberOfAssignmentsOriginal: numberOfAssignmentsOriginal }; + } + var mapEntry = transformer.synthNamesMap.get(ts.getSymbolId(symbol).toString()); + return mapEntry || { identifier: identifier, types: types, numberOfAssignmentsOriginal: numberOfAssignmentsOriginal }; + } + function getSymbol(node) { + return node.symbol ? node.symbol : transformer.checker.getSymbolAtLocation(node); + } + function getOriginalNode(node) { + return node.original ? node.original : node; + } + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + codefix.registerCodeFix({ + errorCodes: [ts.Diagnostics.File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module.code], + getCodeActions: function (context) { + var sourceFile = context.sourceFile, program = context.program, preferences = context.preferences; + var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { + var moduleExportsChangedToDefault = convertFileToEs6Module(sourceFile, program.getTypeChecker(), changes, program.getCompilerOptions().target, ts.getQuotePreference(sourceFile, preferences)); + if (moduleExportsChangedToDefault) { + for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { + var importingFile = _a[_i]; + fixImportOfModuleExports(importingFile, sourceFile, changes, ts.getQuotePreference(importingFile, preferences)); + } + } + }); + // No support for fix-all since this applies to the whole file at once anyway. + return [codefix.createCodeFixActionNoFixId("convertToEs6Module", changes, ts.Diagnostics.Convert_to_ES6_module)]; + }, + }); + function fixImportOfModuleExports(importingFile, exportingFile, changes, quotePreference) { + for (var _i = 0, _a = importingFile.imports; _i < _a.length; _i++) { + var moduleSpecifier = _a[_i]; + var imported = ts.getResolvedModule(importingFile, moduleSpecifier.text); + if (!imported || imported.resolvedFileName !== exportingFile.fileName) { + continue; + } + var importNode = ts.importFromModuleSpecifier(moduleSpecifier); + switch (importNode.kind) { + case 248 /* ImportEqualsDeclaration */: + changes.replaceNode(importingFile, importNode, ts.makeImport(importNode.name, /*namedImports*/ undefined, moduleSpecifier, quotePreference)); + break; + case 191 /* CallExpression */: + if (ts.isRequireCall(importNode, /*checkArgumentIsStringLiteralLike*/ false)) { + changes.replaceNode(importingFile, importNode, ts.createPropertyAccess(ts.getSynthesizedDeepClone(importNode), "default")); + } + break; + } + } + } + /** @returns Whether we converted a `module.exports =` to a default export. */ + function convertFileToEs6Module(sourceFile, checker, changes, target, quotePreference) { + var identifiers = { original: collectFreeIdentifiers(sourceFile), additional: ts.createMap() }; + var exports = collectExportRenames(sourceFile, checker, identifiers); + convertExportsAccesses(sourceFile, exports, changes); + var moduleExportsChangedToDefault = false; + for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + var moduleExportsChanged = convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports, quotePreference); + moduleExportsChangedToDefault = moduleExportsChangedToDefault || moduleExportsChanged; + } + return moduleExportsChangedToDefault; + } + function collectExportRenames(sourceFile, checker, identifiers) { + var res = ts.createMap(); + forEachExportReference(sourceFile, function (node) { + var _a = node.name, text = _a.text, originalKeywordKind = _a.originalKeywordKind; + if (!res.has(text) && (originalKeywordKind !== undefined && ts.isNonContextualKeyword(originalKeywordKind) + || checker.resolveName(node.name.text, node, 67220415 /* Value */, /*excludeGlobals*/ true))) { + // Unconditionally add an underscore in case `text` is a keyword. + res.set(text, makeUniqueName("_" + text, identifiers)); + } + }); + return res; + } + function convertExportsAccesses(sourceFile, exports, changes) { + forEachExportReference(sourceFile, function (node, isAssignmentLhs) { + if (isAssignmentLhs) { + return; + } + var text = node.name.text; + changes.replaceNode(sourceFile, node, ts.createIdentifier(exports.get(text) || text)); + }); + } + function forEachExportReference(sourceFile, cb) { + sourceFile.forEachChild(function recur(node) { + if (ts.isPropertyAccessExpression(node) && ts.isExportsOrModuleExportsOrAlias(sourceFile, node.expression)) { + var parent = node.parent; + cb(node, ts.isBinaryExpression(parent) && parent.left === node && parent.operatorToken.kind === 59 /* EqualsToken */); + } + node.forEachChild(recur); + }); + } + function convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports, quotePreference) { + switch (statement.kind) { + case 219 /* VariableStatement */: + convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target, quotePreference); + return false; + case 221 /* ExpressionStatement */: { + var expression = statement.expression; + switch (expression.kind) { + case 191 /* CallExpression */: { + if (ts.isRequireCall(expression, /*checkArgumentIsStringLiteralLike*/ true)) { + // For side-effecting require() call, just make a side-effecting import. + changes.replaceNode(sourceFile, statement, ts.makeImport(/*name*/ undefined, /*namedImports*/ undefined, expression.arguments[0], quotePreference)); + } + return false; + } + case 204 /* BinaryExpression */: { + var operatorToken = expression.operatorToken; + return operatorToken.kind === 59 /* EqualsToken */ && convertAssignment(sourceFile, checker, expression, changes, exports); + } + } + } + // falls through + default: + return false; + } + } + function convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target, quotePreference) { + var declarationList = statement.declarationList; + var foundImport = false; + var newNodes = ts.flatMap(declarationList.declarations, function (decl) { + var name = decl.name, initializer = decl.initializer; + if (initializer) { + if (ts.isExportsOrModuleExportsOrAlias(sourceFile, initializer)) { + // `const alias = module.exports;` can be removed. + foundImport = true; + return []; + } + else if (ts.isRequireCall(initializer, /*checkArgumentIsStringLiteralLike*/ true)) { + foundImport = true; + return convertSingleImport(sourceFile, name, initializer.arguments[0], changes, checker, identifiers, target, quotePreference); + } + else if (ts.isPropertyAccessExpression(initializer) && ts.isRequireCall(initializer.expression, /*checkArgumentIsStringLiteralLike*/ true)) { + foundImport = true; + return convertPropertyAccessImport(name, initializer.name.text, initializer.expression.arguments[0], identifiers, quotePreference); + } + } + // Move it out to its own variable statement. (This will not be used if `!foundImport`) + return ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([decl], declarationList.flags)); + }); + if (foundImport) { + // useNonAdjustedEndPosition to ensure we don't eat the newline after the statement. + changes.replaceNodeWithNodes(sourceFile, statement, newNodes); + } + } + /** Converts `const name = require("moduleSpecifier").propertyName` */ + function convertPropertyAccessImport(name, propertyName, moduleSpecifier, identifiers, quotePreference) { + switch (name.kind) { + case 184 /* ObjectBindingPattern */: + case 185 /* ArrayBindingPattern */: { + // `const [a, b] = require("c").d` --> `import { d } from "c"; const [a, b] = d;` + var tmp = makeUniqueName(propertyName, identifiers); + return [ + makeSingleImport(tmp, propertyName, moduleSpecifier, quotePreference), + makeConst(/*modifiers*/ undefined, name, ts.createIdentifier(tmp)), + ]; + } + case 72 /* Identifier */: + // `const a = require("b").c` --> `import { c as a } from "./b"; + return [makeSingleImport(name.text, propertyName, moduleSpecifier, quotePreference)]; + default: + return ts.Debug.assertNever(name); + } + } + function convertAssignment(sourceFile, checker, assignment, changes, exports) { + var left = assignment.left, right = assignment.right; + if (!ts.isPropertyAccessExpression(left)) { + return false; + } + if (ts.isExportsOrModuleExportsOrAlias(sourceFile, left)) { + if (ts.isExportsOrModuleExportsOrAlias(sourceFile, right)) { + // `const alias = module.exports;` or `module.exports = alias;` can be removed. + changes.delete(sourceFile, assignment.parent); + } + else { + var replacement = ts.isObjectLiteralExpression(right) ? tryChangeModuleExportsObject(right) + : ts.isRequireCall(right, /*checkArgumentIsStringLiteralLike*/ true) ? convertReExportAll(right.arguments[0], checker) + : undefined; + if (replacement) { + changes.replaceNodeWithNodes(sourceFile, assignment.parent, replacement[0]); + return replacement[1]; + } + else { + changes.replaceRangeWithText(sourceFile, ts.createRange(left.getStart(sourceFile), right.pos), "export default"); + return true; + } + } + } + else if (ts.isExportsOrModuleExportsOrAlias(sourceFile, left.expression)) { + convertNamedExport(sourceFile, assignment, changes, exports); + } + return false; + } + /** + * Convert `module.exports = { ... }` to individual exports.. + * We can't always do this if the module has interesting members -- then it will be a default export instead. + */ + function tryChangeModuleExportsObject(object) { + var statements = ts.mapAllOrFail(object.properties, function (prop) { + switch (prop.kind) { + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + // TODO: Maybe we should handle this? See fourslash test `refactorConvertToEs6Module_export_object_shorthand.ts`. + case 276 /* ShorthandPropertyAssignment */: + case 277 /* SpreadAssignment */: + return undefined; + case 275 /* PropertyAssignment */: + return !ts.isIdentifier(prop.name) ? undefined : convertExportsDotXEquals_replaceNode(prop.name.text, prop.initializer); + case 156 /* MethodDeclaration */: + return !ts.isIdentifier(prop.name) ? undefined : functionExpressionToDeclaration(prop.name.text, [ts.createToken(85 /* ExportKeyword */)], prop); + default: + ts.Debug.assertNever(prop); + } + }); + return statements && [statements, false]; + } + function convertNamedExport(sourceFile, assignment, changes, exports) { + // If "originalKeywordKind" was set, this is e.g. `exports. + var text = assignment.left.name.text; + var rename = exports.get(text); + if (rename !== undefined) { + /* + const _class = 0; + export { _class as class }; + */ + var newNodes = [ + makeConst(/*modifiers*/ undefined, rename, assignment.right), + makeExportDeclaration([ts.createExportSpecifier(rename, text)]), + ]; + changes.replaceNodeWithNodes(sourceFile, assignment.parent, newNodes); + } + else { + convertExportsPropertyAssignment(assignment, sourceFile, changes); + } + } + function convertReExportAll(reExported, checker) { + // `module.exports = require("x");` ==> `export * from "x"; export { default } from "x";` + var moduleSpecifier = reExported.text; + var moduleSymbol = checker.getSymbolAtLocation(reExported); + var exports = moduleSymbol ? moduleSymbol.exports : ts.emptyUnderscoreEscapedMap; + return exports.has("export=") + ? [[reExportDefault(moduleSpecifier)], true] + : !exports.has("default") + ? [[reExportStar(moduleSpecifier)], false] + // If there's some non-default export, must include both `export *` and `export default`. + : exports.size > 1 ? [[reExportStar(moduleSpecifier), reExportDefault(moduleSpecifier)], true] : [[reExportDefault(moduleSpecifier)], true]; + } + function reExportStar(moduleSpecifier) { + return makeExportDeclaration(/*exportClause*/ undefined, moduleSpecifier); + } + function reExportDefault(moduleSpecifier) { + return makeExportDeclaration([ts.createExportSpecifier(/*propertyName*/ undefined, "default")], moduleSpecifier); + } + function convertExportsPropertyAssignment(_a, sourceFile, changes) { + var left = _a.left, right = _a.right, parent = _a.parent; + var name = left.name.text; + if ((ts.isFunctionExpression(right) || ts.isArrowFunction(right) || ts.isClassExpression(right)) && (!right.name || right.name.text === name)) { + // `exports.f = function() {}` -> `export function f() {}` -- Replace `exports.f = ` with `export `, and insert the name after `function`. + changes.replaceRange(sourceFile, { pos: left.getStart(sourceFile), end: right.getStart(sourceFile) }, ts.createToken(85 /* ExportKeyword */), { suffix: " " }); + if (!right.name) + changes.insertName(sourceFile, right, name); + var semi = ts.findChildOfKind(parent, 26 /* SemicolonToken */, sourceFile); + if (semi) + changes.delete(sourceFile, semi); + } + else { + // `exports.f = function g() {}` -> `export const f = function g() {}` -- just replace `exports.` with `export const ` + changes.replaceNodeRangeWithNodes(sourceFile, left.expression, ts.findChildOfKind(left, 24 /* DotToken */, sourceFile), [ts.createToken(85 /* ExportKeyword */), ts.createToken(77 /* ConstKeyword */)], { joiner: " ", suffix: " " }); + } + } + // TODO: GH#22492 this will cause an error if a change has been made inside the body of the node. + function convertExportsDotXEquals_replaceNode(name, exported) { + var modifiers = [ts.createToken(85 /* ExportKeyword */)]; + switch (exported.kind) { + case 196 /* FunctionExpression */: { + var expressionName = exported.name; + if (expressionName && expressionName.text !== name) { + // `exports.f = function g() {}` -> `export const f = function g() {}` + return exportConst(); + } + } + // falls through + case 197 /* ArrowFunction */: + // `exports.f = function() {}` --> `export function f() {}` + return functionExpressionToDeclaration(name, modifiers, exported); + case 209 /* ClassExpression */: + // `exports.C = class {}` --> `export class C {}` + return classExpressionToDeclaration(name, modifiers, exported); + default: + return exportConst(); + } + function exportConst() { + // `exports.x = 0;` --> `export const x = 0;` + return makeConst(modifiers, ts.createIdentifier(name), exported); // TODO: GH#18217 + } + } + /** + * Converts `const <> = require("x");`. + * Returns nodes that will replace the variable declaration for the commonjs import. + * May also make use `changes` to remove qualifiers at the use sites of imports, to change `mod.x` to `x`. + */ + function convertSingleImport(file, name, moduleSpecifier, changes, checker, identifiers, target, quotePreference) { + switch (name.kind) { + case 184 /* ObjectBindingPattern */: { + var importSpecifiers = ts.mapAllOrFail(name.elements, function (e) { + return e.dotDotDotToken || e.initializer || e.propertyName && !ts.isIdentifier(e.propertyName) || !ts.isIdentifier(e.name) + ? undefined + : makeImportSpecifier(e.propertyName && e.propertyName.text, e.name.text); + }); // tslint:disable-line no-unnecessary-type-assertion (TODO: GH#18217) + if (importSpecifiers) { + return [ts.makeImport(/*name*/ undefined, importSpecifiers, moduleSpecifier, quotePreference)]; + } + } + // falls through -- object destructuring has an interesting pattern and must be a variable declaration + case 185 /* ArrayBindingPattern */: { + /* + import x from "x"; + const [a, b, c] = x; + */ + var tmp = makeUniqueName(codefix.moduleSpecifierToValidIdentifier(moduleSpecifier.text, target), identifiers); + return [ + ts.makeImport(ts.createIdentifier(tmp), /*namedImports*/ undefined, moduleSpecifier, quotePreference), + makeConst(/*modifiers*/ undefined, ts.getSynthesizedDeepClone(name), ts.createIdentifier(tmp)), + ]; + } + case 72 /* Identifier */: + return convertSingleIdentifierImport(file, name, moduleSpecifier, changes, checker, identifiers, quotePreference); + default: + return ts.Debug.assertNever(name); + } + } + /** + * Convert `import x = require("x").` + * Also converts uses like `x.y()` to `y()` and uses a named import. + */ + function convertSingleIdentifierImport(file, name, moduleSpecifier, changes, checker, identifiers, quotePreference) { + var nameSymbol = checker.getSymbolAtLocation(name); + // Maps from module property name to name actually used. (The same if there isn't shadowing.) + var namedBindingsNames = ts.createMap(); + // True if there is some non-property use like `x()` or `f(x)`. + var needDefaultImport = false; + for (var _i = 0, _a = identifiers.original.get(name.text); _i < _a.length; _i++) { + var use = _a[_i]; + if (checker.getSymbolAtLocation(use) !== nameSymbol || use === name) { + // This was a use of a different symbol with the same name, due to shadowing. Ignore. + continue; + } + var parent = use.parent; + if (ts.isPropertyAccessExpression(parent)) { + var expression = parent.expression, propertyName = parent.name.text; + ts.Debug.assert(expression === use); // Else shouldn't have been in `collectIdentifiers` + var idName = namedBindingsNames.get(propertyName); + if (idName === undefined) { + idName = makeUniqueName(propertyName, identifiers); + namedBindingsNames.set(propertyName, idName); + } + changes.replaceNode(file, parent, ts.createIdentifier(idName)); + } + else { + needDefaultImport = true; + } + } + var namedBindings = namedBindingsNames.size === 0 ? undefined : ts.arrayFrom(ts.mapIterator(namedBindingsNames.entries(), function (_a) { + var propertyName = _a[0], idName = _a[1]; + return ts.createImportSpecifier(propertyName === idName ? undefined : ts.createIdentifier(propertyName), ts.createIdentifier(idName)); + })); + if (!namedBindings) { + // If it was unused, ensure that we at least import *something*. + needDefaultImport = true; + } + return [ts.makeImport(needDefaultImport ? ts.getSynthesizedDeepClone(name) : undefined, namedBindings, moduleSpecifier, quotePreference)]; + } + // Identifiers helpers + function makeUniqueName(name, identifiers) { + while (identifiers.original.has(name) || identifiers.additional.has(name)) { + name = "_" + name; + } + identifiers.additional.set(name, true); + return name; + } + function collectFreeIdentifiers(file) { + var map = ts.createMultiMap(); + forEachFreeIdentifier(file, function (id) { return map.add(id.text, id); }); + return map; + } + /** + * A free identifier is an identifier that can be accessed through name lookup as a local variable. + * In the expression `x.y`, `x` is a free identifier, but `y` is not. + */ + function forEachFreeIdentifier(node, cb) { + if (ts.isIdentifier(node) && isFreeIdentifier(node)) + cb(node); + node.forEachChild(function (child) { return forEachFreeIdentifier(child, cb); }); + } + function isFreeIdentifier(node) { + var parent = node.parent; + switch (parent.kind) { + case 189 /* PropertyAccessExpression */: + return parent.name !== node; + case 186 /* BindingElement */: + return parent.propertyName !== node; + case 253 /* ImportSpecifier */: + return parent.propertyName !== node; + default: + return true; + } + } + // Node helpers + function functionExpressionToDeclaration(name, additionalModifiers, fn) { + return ts.createFunctionDeclaration(ts.getSynthesizedDeepClones(fn.decorators), // TODO: GH#19915 Don't think this is even legal. + ts.concatenate(additionalModifiers, ts.getSynthesizedDeepClones(fn.modifiers)), ts.getSynthesizedDeepClone(fn.asteriskToken), name, ts.getSynthesizedDeepClones(fn.typeParameters), ts.getSynthesizedDeepClones(fn.parameters), ts.getSynthesizedDeepClone(fn.type), ts.convertToFunctionBody(ts.getSynthesizedDeepClone(fn.body))); + } + function classExpressionToDeclaration(name, additionalModifiers, cls) { + return ts.createClassDeclaration(ts.getSynthesizedDeepClones(cls.decorators), // TODO: GH#19915 Don't think this is even legal. + ts.concatenate(additionalModifiers, ts.getSynthesizedDeepClones(cls.modifiers)), name, ts.getSynthesizedDeepClones(cls.typeParameters), ts.getSynthesizedDeepClones(cls.heritageClauses), ts.getSynthesizedDeepClones(cls.members)); + } + function makeSingleImport(localName, propertyName, moduleSpecifier, quotePreference) { + return propertyName === "default" + ? ts.makeImport(ts.createIdentifier(localName), /*namedImports*/ undefined, moduleSpecifier, quotePreference) + : ts.makeImport(/*name*/ undefined, [makeImportSpecifier(propertyName, localName)], moduleSpecifier, quotePreference); + } + function makeImportSpecifier(propertyName, name) { + return ts.createImportSpecifier(propertyName !== undefined && propertyName !== name ? ts.createIdentifier(propertyName) : undefined, ts.createIdentifier(name)); + } + function makeConst(modifiers, name, init) { + return ts.createVariableStatement(modifiers, ts.createVariableDeclarationList([ts.createVariableDeclaration(name, /*type*/ undefined, init)], 2 /* Const */)); + } + function makeExportDeclaration(exportSpecifiers, moduleSpecifier) { + return ts.createExportDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, exportSpecifiers && ts.createNamedExports(exportSpecifiers), moduleSpecifier === undefined ? undefined : ts.createLiteral(moduleSpecifier)); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "correctQualifiedNameToIndexedAccessType"; + var errorCodes = [ts.Diagnostics.Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_property_1_in_0_with_0_1.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var qualifiedName = getQualifiedName(context.sourceFile, context.span.start); + if (!qualifiedName) + return undefined; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, context.sourceFile, qualifiedName); }); + var newText = qualifiedName.left.text + "[\"" + qualifiedName.right.text + "\"]"; + return [codefix.createCodeFixAction(fixId, changes, [ts.Diagnostics.Rewrite_as_the_indexed_access_type_0, newText], fixId, ts.Diagnostics.Rewrite_all_as_indexed_access_types)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var q = getQualifiedName(diag.file, diag.start); + if (q) { + doChange(changes, diag.file, q); + } + }); }, + }); + function getQualifiedName(sourceFile, pos) { + var qualifiedName = ts.findAncestor(ts.getTokenAtPosition(sourceFile, pos), ts.isQualifiedName); + ts.Debug.assert(!!qualifiedName, "Expected position to be owned by a qualified name."); + return ts.isIdentifier(qualifiedName.left) ? qualifiedName : undefined; + } + function doChange(changeTracker, sourceFile, qualifiedName) { + var rightText = qualifiedName.right.text; + var replacement = ts.createIndexedAccessTypeNode(ts.createTypeReferenceNode(qualifiedName.left, /*typeArguments*/ undefined), ts.createLiteralTypeNode(ts.createLiteral(rightText))); + changeTracker.replaceNode(sourceFile, qualifiedName, replacement); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var errorCodes = [ts.Diagnostics.Class_0_incorrectly_implements_interface_1.code, + ts.Diagnostics.Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass.code]; + var fixId = "fixClassIncorrectlyImplementsInterface"; // TODO: share a group with fixClassDoesntImplementInheritedAbstractMember? + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var program = context.program, sourceFile = context.sourceFile, span = context.span; + var classDeclaration = getClass(sourceFile, span.start); + var checker = program.getTypeChecker(); + return ts.mapDefined(ts.getClassImplementsHeritageClauseElements(classDeclaration), function (implementedTypeNode) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMissingDeclarations(checker, implementedTypeNode, sourceFile, classDeclaration, t, context.preferences); }); + return changes.length === 0 ? undefined : codefix.createCodeFixAction(fixId, changes, [ts.Diagnostics.Implement_interface_0, implementedTypeNode.getText(sourceFile)], fixId, ts.Diagnostics.Implement_all_unimplemented_interfaces); + }); + }, + fixIds: [fixId], + getAllCodeActions: function (context) { + var seenClassDeclarations = ts.createMap(); + return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var classDeclaration = getClass(diag.file, diag.start); + if (ts.addToSeen(seenClassDeclarations, ts.getNodeId(classDeclaration))) { + for (var _i = 0, _a = ts.getClassImplementsHeritageClauseElements(classDeclaration); _i < _a.length; _i++) { + var implementedTypeNode = _a[_i]; + addMissingDeclarations(context.program.getTypeChecker(), implementedTypeNode, diag.file, classDeclaration, changes, context.preferences); + } + } + }); + }, + }); + function getClass(sourceFile, pos) { + return ts.Debug.assertDefined(ts.getContainingClass(ts.getTokenAtPosition(sourceFile, pos))); + } + function symbolPointsToNonPrivateMember(symbol) { + return !(ts.getModifierFlags(symbol.valueDeclaration) & 8 /* Private */); + } + function addMissingDeclarations(checker, implementedTypeNode, sourceFile, classDeclaration, changeTracker, preferences) { + var maybeHeritageClauseSymbol = getHeritageClauseSymbolTable(classDeclaration, checker); + // Note that this is ultimately derived from a map indexed by symbol names, + // so duplicates cannot occur. + var implementedType = checker.getTypeAtLocation(implementedTypeNode); + var implementedTypeSymbols = checker.getPropertiesOfType(implementedType); + var nonPrivateAndNotExistedInHeritageClauseMembers = implementedTypeSymbols.filter(ts.and(symbolPointsToNonPrivateMember, function (symbol) { return !maybeHeritageClauseSymbol.has(symbol.escapedName); })); + var classType = checker.getTypeAtLocation(classDeclaration); + if (!classType.getNumberIndexType()) { + createMissingIndexSignatureDeclaration(implementedType, 1 /* Number */); + } + if (!classType.getStringIndexType()) { + createMissingIndexSignatureDeclaration(implementedType, 0 /* String */); + } + codefix.createMissingMemberNodes(classDeclaration, nonPrivateAndNotExistedInHeritageClauseMembers, checker, preferences, function (member) { return changeTracker.insertNodeAtClassStart(sourceFile, classDeclaration, member); }); + function createMissingIndexSignatureDeclaration(type, kind) { + var indexInfoOfKind = checker.getIndexInfoOfType(type, kind); + if (indexInfoOfKind) { + changeTracker.insertNodeAtClassStart(sourceFile, classDeclaration, checker.indexInfoToIndexSignatureDeclaration(indexInfoOfKind, kind, classDeclaration)); + } + } + } + function getHeritageClauseSymbolTable(classDeclaration, checker) { + var heritageClauseNode = ts.getEffectiveBaseTypeNode(classDeclaration); + if (!heritageClauseNode) + return ts.createSymbolTable(); + var heritageClauseType = checker.getTypeAtLocation(heritageClauseNode); + var heritageClauseTypeSymbols = checker.getPropertiesOfType(heritageClauseType); + return ts.createSymbolTable(heritageClauseTypeSymbols.filter(symbolPointsToNonPrivateMember)); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + codefix.importFixId = "fixMissingImport"; + var errorCodes = [ + ts.Diagnostics.Cannot_find_name_0.code, + ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1.code, + ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0.code, + ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_static_member_1_0.code, + ts.Diagnostics.Cannot_find_namespace_0.code, + ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code, + ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here.code, + ]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var errorCode = context.errorCode, preferences = context.preferences, sourceFile = context.sourceFile, span = context.span; + var info = getFixesInfo(context, errorCode, span.start); + if (!info) + return undefined; + var fixes = info.fixes, symbolName = info.symbolName; + var quotePreference = ts.getQuotePreference(sourceFile, preferences); + return fixes.map(function (fix) { return codeActionForFix(context, sourceFile, symbolName, fix, quotePreference); }); + }, + fixIds: [codefix.importFixId], + getAllCodeActions: function (context) { + var sourceFile = context.sourceFile, preferences = context.preferences; + // Namespace fixes don't conflict, so just build a list. + var addToNamespace = []; + var importType = []; + // Keys are import clause node IDs. + var addToExisting = ts.createMap(); + // Keys are module specifiers. + var newImports = ts.createMap(); + codefix.eachDiagnostic(context, errorCodes, function (diag) { + var info = getFixesInfo(context, diag.code, diag.start); + if (!info || !info.fixes.length) + return; + var fixes = info.fixes, symbolName = info.symbolName; + var fix = ts.first(fixes); + switch (fix.kind) { + case 0 /* UseNamespace */: + addToNamespace.push(fix); + break; + case 1 /* ImportType */: + importType.push(fix); + break; + case 2 /* AddToExisting */: { + var importClause = fix.importClause, importKind = fix.importKind; + var key = String(ts.getNodeId(importClause)); + var entry = addToExisting.get(key); + if (!entry) { + addToExisting.set(key, entry = { importClause: importClause, defaultImport: undefined, namedImports: [] }); + } + if (importKind === 0 /* Named */) { + ts.pushIfUnique(entry.namedImports, symbolName); + } + else { + ts.Debug.assert(entry.defaultImport === undefined || entry.defaultImport === symbolName); + entry.defaultImport = symbolName; + } + break; + } + case 3 /* AddNew */: { + var moduleSpecifier = fix.moduleSpecifier, importKind = fix.importKind; + var entry = newImports.get(moduleSpecifier); + if (!entry) { + newImports.set(moduleSpecifier, entry = { defaultImport: undefined, namedImports: [], namespaceLikeImport: undefined }); + } + switch (importKind) { + case 1 /* Default */: + ts.Debug.assert(entry.defaultImport === undefined || entry.defaultImport === symbolName); + entry.defaultImport = symbolName; + break; + case 0 /* Named */: + ts.pushIfUnique(entry.namedImports, symbolName); + break; + case 3 /* Equals */: + case 2 /* Namespace */: + ts.Debug.assert(entry.namespaceLikeImport === undefined || entry.namespaceLikeImport.name === symbolName); + entry.namespaceLikeImport = { importKind: importKind, name: symbolName }; + break; + } + break; + } + default: + ts.Debug.assertNever(fix); + } + }); + return codefix.createCombinedCodeActions(ts.textChanges.ChangeTracker.with(context, function (changes) { + var quotePreference = ts.getQuotePreference(sourceFile, preferences); + for (var _i = 0, addToNamespace_1 = addToNamespace; _i < addToNamespace_1.length; _i++) { + var fix = addToNamespace_1[_i]; + addNamespaceQualifier(changes, sourceFile, fix); + } + for (var _a = 0, importType_1 = importType; _a < importType_1.length; _a++) { + var fix = importType_1[_a]; + addImportType(changes, sourceFile, fix, quotePreference); + } + addToExisting.forEach(function (_a) { + var importClause = _a.importClause, defaultImport = _a.defaultImport, namedImports = _a.namedImports; + doAddExistingFix(changes, sourceFile, importClause, defaultImport, namedImports); + }); + newImports.forEach(function (imports, moduleSpecifier) { + addNewImports(changes, sourceFile, moduleSpecifier, quotePreference, imports); + }); + })); + }, + }); + // Sorted with the preferred fix coming first. + var ImportFixKind; + (function (ImportFixKind) { + ImportFixKind[ImportFixKind["UseNamespace"] = 0] = "UseNamespace"; + ImportFixKind[ImportFixKind["ImportType"] = 1] = "ImportType"; + ImportFixKind[ImportFixKind["AddToExisting"] = 2] = "AddToExisting"; + ImportFixKind[ImportFixKind["AddNew"] = 3] = "AddNew"; + })(ImportFixKind || (ImportFixKind = {})); + var ImportKind; + (function (ImportKind) { + ImportKind[ImportKind["Named"] = 0] = "Named"; + ImportKind[ImportKind["Default"] = 1] = "Default"; + ImportKind[ImportKind["Namespace"] = 2] = "Namespace"; + ImportKind[ImportKind["Equals"] = 3] = "Equals"; + })(ImportKind || (ImportKind = {})); + function getImportCompletionAction(exportedSymbol, moduleSymbol, sourceFile, symbolName, host, program, formatContext, position, preferences) { + var exportInfos = getAllReExportingModules(exportedSymbol, moduleSymbol, symbolName, sourceFile, program.getCompilerOptions(), program.getTypeChecker(), program.getSourceFiles()); + ts.Debug.assert(exportInfos.some(function (info) { return info.moduleSymbol === moduleSymbol; })); + // We sort the best codefixes first, so taking `first` is best for completions. + var moduleSpecifier = ts.first(getNewImportInfos(program, sourceFile, position, exportInfos, host, preferences)).moduleSpecifier; + var fix = ts.first(getFixForImport(exportInfos, symbolName, position, program, sourceFile, host, preferences)); + return { moduleSpecifier: moduleSpecifier, codeAction: codeFixActionToCodeAction(codeActionForFix({ host: host, formatContext: formatContext }, sourceFile, symbolName, fix, ts.getQuotePreference(sourceFile, preferences))) }; + } + codefix.getImportCompletionAction = getImportCompletionAction; + function codeFixActionToCodeAction(_a) { + var description = _a.description, changes = _a.changes, commands = _a.commands; + return { description: description, changes: changes, commands: commands }; + } + function getAllReExportingModules(exportedSymbol, exportingModuleSymbol, symbolName, sourceFile, compilerOptions, checker, allSourceFiles) { + var result = []; + forEachExternalModule(checker, allSourceFiles, function (moduleSymbol, moduleFile) { + // Don't import from a re-export when looking "up" like to `./index` or `../index`. + if (moduleFile && moduleSymbol !== exportingModuleSymbol && ts.startsWith(sourceFile.fileName, ts.getDirectoryPath(moduleFile.fileName))) { + return; + } + var defaultInfo = getDefaultLikeExportInfo(moduleSymbol, checker, compilerOptions); + if (defaultInfo && defaultInfo.name === symbolName && ts.skipAlias(defaultInfo.symbol, checker) === exportedSymbol) { + result.push({ moduleSymbol: moduleSymbol, importKind: defaultInfo.kind, exportedSymbolIsTypeOnly: isTypeOnlySymbol(defaultInfo.symbol, checker) }); + } + for (var _i = 0, _a = checker.getExportsOfModule(moduleSymbol); _i < _a.length; _i++) { + var exported = _a[_i]; + if (exported.name === symbolName && ts.skipAlias(exported, checker) === exportedSymbol) { + result.push({ moduleSymbol: moduleSymbol, importKind: 0 /* Named */, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exported, checker) }); + } + } + }); + return result; + } + function isTypeOnlySymbol(s, checker) { + return !(ts.skipAlias(s, checker).flags & 67220415 /* Value */); + } + function getFixForImport(exportInfos, symbolName, position, program, sourceFile, host, preferences) { + var checker = program.getTypeChecker(); + var existingImports = ts.flatMap(exportInfos, function (info) { return getExistingImportDeclarations(info, checker, sourceFile); }); + var useNamespace = position === undefined ? undefined : tryUseExistingNamespaceImport(existingImports, symbolName, position, checker); + var addToExisting = tryAddToExistingImport(existingImports); + // Don't bother providing an action to add a new import if we can add to an existing one. + var addImport = addToExisting ? [addToExisting] : getFixesForAddImport(exportInfos, existingImports, program, sourceFile, position, host, preferences); + return (useNamespace ? [useNamespace] : ts.emptyArray).concat(addImport); + } + function tryUseExistingNamespaceImport(existingImports, symbolName, position, checker) { + // It is possible that multiple import statements with the same specifier exist in the file. + // e.g. + // + // import * as ns from "foo"; + // import { member1, member2 } from "foo"; + // + // member3/**/ <-- cusor here + // + // in this case we should provie 2 actions: + // 1. change "member3" to "ns.member3" + // 2. add "member3" to the second import statement's import list + // and it is up to the user to decide which one fits best. + return ts.firstDefined(existingImports, function (_a) { + var declaration = _a.declaration; + var namespace = getNamespaceImportName(declaration); + if (namespace) { + var moduleSymbol = checker.getAliasedSymbol(checker.getSymbolAtLocation(namespace)); + if (moduleSymbol && moduleSymbol.exports.has(ts.escapeLeadingUnderscores(symbolName))) { + return { kind: 0 /* UseNamespace */, namespacePrefix: namespace.text, position: position }; + } + } + }); + } + function tryAddToExistingImport(existingImports) { + return ts.firstDefined(existingImports, function (_a) { + var declaration = _a.declaration, importKind = _a.importKind; + if (declaration.kind !== 249 /* ImportDeclaration */) + return undefined; + var importClause = declaration.importClause; + if (!importClause) + return undefined; + var name = importClause.name, namedBindings = importClause.namedBindings; + return importKind === 1 /* Default */ && !name || importKind === 0 /* Named */ && (!namedBindings || namedBindings.kind === 252 /* NamedImports */) + ? { kind: 2 /* AddToExisting */, importClause: importClause, importKind: importKind } + : undefined; + }); + } + function getNamespaceImportName(declaration) { + if (declaration.kind === 249 /* ImportDeclaration */) { + var namedBindings = declaration.importClause && ts.isImportClause(declaration.importClause) && declaration.importClause.namedBindings; + return namedBindings && namedBindings.kind === 251 /* NamespaceImport */ ? namedBindings.name : undefined; + } + else { + return declaration.name; + } + } + function getExistingImportDeclarations(_a, checker, sourceFile) { + var moduleSymbol = _a.moduleSymbol, importKind = _a.importKind, exportedSymbolIsTypeOnly = _a.exportedSymbolIsTypeOnly; + // Can't use an es6 import for a type in JS. + return exportedSymbolIsTypeOnly && ts.isSourceFileJS(sourceFile) ? ts.emptyArray : ts.mapDefined(sourceFile.imports, function (moduleSpecifier) { + var i = ts.importFromModuleSpecifier(moduleSpecifier); + return (i.kind === 249 /* ImportDeclaration */ || i.kind === 248 /* ImportEqualsDeclaration */) + && checker.getSymbolAtLocation(moduleSpecifier) === moduleSymbol ? { declaration: i, importKind: importKind } : undefined; + }); + } + function getNewImportInfos(program, sourceFile, position, moduleSymbols, host, preferences) { + var isJs = ts.isSourceFileJS(sourceFile); + var choicesForEachExportingModule = ts.flatMap(moduleSymbols, function (_a) { + var moduleSymbol = _a.moduleSymbol, importKind = _a.importKind, exportedSymbolIsTypeOnly = _a.exportedSymbolIsTypeOnly; + return ts.moduleSpecifiers.getModuleSpecifiers(moduleSymbol, program.getCompilerOptions(), sourceFile, host, program.getSourceFiles(), preferences, program.redirectTargetsMap) + .map(function (moduleSpecifier) { + // `position` should only be undefined at a missing jsx namespace, in which case we shouldn't be looking for pure types. + return exportedSymbolIsTypeOnly && isJs ? { kind: 1 /* ImportType */, moduleSpecifier: moduleSpecifier, position: ts.Debug.assertDefined(position) } : { kind: 3 /* AddNew */, moduleSpecifier: moduleSpecifier, importKind: importKind }; + }); + }); + // Sort to keep the shortest paths first + return ts.sort(choicesForEachExportingModule, function (a, b) { return a.moduleSpecifier.length - b.moduleSpecifier.length; }); + } + function getFixesForAddImport(exportInfos, existingImports, program, sourceFile, position, host, preferences) { + var existingDeclaration = ts.firstDefined(existingImports, newImportInfoFromExistingSpecifier); + return existingDeclaration ? [existingDeclaration] : getNewImportInfos(program, sourceFile, position, exportInfos, host, preferences); + } + function newImportInfoFromExistingSpecifier(_a) { + var declaration = _a.declaration, importKind = _a.importKind; + var expression = declaration.kind === 249 /* ImportDeclaration */ + ? declaration.moduleSpecifier + : declaration.moduleReference.kind === 259 /* ExternalModuleReference */ + ? declaration.moduleReference.expression + : undefined; + return expression && ts.isStringLiteral(expression) ? { kind: 3 /* AddNew */, moduleSpecifier: expression.text, importKind: importKind } : undefined; + } + function getFixesInfo(context, errorCode, pos) { + var symbolToken = ts.getTokenAtPosition(context.sourceFile, pos); + var info = errorCode === ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code + ? getFixesInfoForUMDImport(context, symbolToken) + : ts.isIdentifier(symbolToken) ? getFixesInfoForNonUMDImport(context, symbolToken) : undefined; + return info && __assign({}, info, { fixes: ts.sort(info.fixes, function (a, b) { return a.kind - b.kind; }) }); + } + function getFixesInfoForUMDImport(_a, token) { + var sourceFile = _a.sourceFile, program = _a.program, host = _a.host, preferences = _a.preferences; + var checker = program.getTypeChecker(); + var umdSymbol = getUmdSymbol(token, checker); + if (!umdSymbol) + return undefined; + var symbol = checker.getAliasedSymbol(umdSymbol); + var symbolName = umdSymbol.name; + var exportInfos = [{ moduleSymbol: symbol, importKind: getUmdImportKind(program.getCompilerOptions()), exportedSymbolIsTypeOnly: false }]; + var fixes = getFixForImport(exportInfos, symbolName, ts.isIdentifier(token) ? token.getStart(sourceFile) : undefined, program, sourceFile, host, preferences); + return { fixes: fixes, symbolName: symbolName }; + } + function getUmdSymbol(token, checker) { + // try the identifier to see if it is the umd symbol + var umdSymbol = ts.isIdentifier(token) ? checker.getSymbolAtLocation(token) : undefined; + if (ts.isUMDExportSymbol(umdSymbol)) + return umdSymbol; + // The error wasn't for the symbolAtLocation, it was for the JSX tag itself, which needs access to e.g. `React`. + var parent = token.parent; + return (ts.isJsxOpeningLikeElement(parent) && parent.tagName === token) || ts.isJsxOpeningFragment(parent) + ? ts.tryCast(checker.resolveName(checker.getJsxNamespace(parent), ts.isJsxOpeningLikeElement(parent) ? token : parent, 67220415 /* Value */, /*excludeGlobals*/ false), ts.isUMDExportSymbol) + : undefined; + } + function getUmdImportKind(compilerOptions) { + // Import a synthetic `default` if enabled. + if (ts.getAllowSyntheticDefaultImports(compilerOptions)) { + return 1 /* Default */; + } + // When a synthetic `default` is unavailable, use `import..require` if the module kind supports it. + var moduleKind = ts.getEmitModuleKind(compilerOptions); + switch (moduleKind) { + case ts.ModuleKind.AMD: + case ts.ModuleKind.CommonJS: + case ts.ModuleKind.UMD: + return 3 /* Equals */; + case ts.ModuleKind.System: + case ts.ModuleKind.ES2015: + case ts.ModuleKind.ESNext: + case ts.ModuleKind.None: + // Fall back to the `import * as ns` style import. + return 2 /* Namespace */; + default: + return ts.Debug.assertNever(moduleKind); + } + } + function getFixesInfoForNonUMDImport(_a, symbolToken) { + var sourceFile = _a.sourceFile, program = _a.program, cancellationToken = _a.cancellationToken, host = _a.host, preferences = _a.preferences; + var checker = program.getTypeChecker(); + // If we're at ``, we must check if `Foo` is already in scope, and if so, get an import for `React` instead. + var symbolName = ts.isJsxOpeningLikeElement(symbolToken.parent) + && symbolToken.parent.tagName === symbolToken + && (ts.isIntrinsicJsxName(symbolToken.text) || checker.resolveName(symbolToken.text, symbolToken, 67108863 /* All */, /*excludeGlobals*/ false)) + ? checker.getJsxNamespace() + : symbolToken.text; + // "default" is a keyword and not a legal identifier for the import, so we don't expect it here + ts.Debug.assert(symbolName !== "default" /* Default */); + var fixes = ts.arrayFrom(ts.flatMapIterator(getExportInfos(symbolName, ts.getMeaningFromLocation(symbolToken), cancellationToken, sourceFile, checker, program).entries(), function (_a) { + var _ = _a[0], exportInfos = _a[1]; + return getFixForImport(exportInfos, symbolName, symbolToken.getStart(sourceFile), program, sourceFile, host, preferences); + })); + return { fixes: fixes, symbolName: symbolName }; + } + // Returns a map from an exported symbol's ID to a list of every way it's (re-)exported. + function getExportInfos(symbolName, currentTokenMeaning, cancellationToken, sourceFile, checker, program) { + // For each original symbol, keep all re-exports of that symbol together so we can call `getCodeActionsForImport` on the whole group at once. + // Maps symbol id to info for modules providing that symbol (original export + re-exports). + var originalSymbolToExportInfos = ts.createMultiMap(); + function addSymbol(moduleSymbol, exportedSymbol, importKind) { + originalSymbolToExportInfos.add(ts.getUniqueSymbolId(exportedSymbol, checker).toString(), { moduleSymbol: moduleSymbol, importKind: importKind, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exportedSymbol, checker) }); + } + forEachExternalModuleToImportFrom(checker, sourceFile, program.getSourceFiles(), function (moduleSymbol) { + cancellationToken.throwIfCancellationRequested(); + var defaultInfo = getDefaultLikeExportInfo(moduleSymbol, checker, program.getCompilerOptions()); + if (defaultInfo && defaultInfo.name === symbolName && symbolHasMeaning(defaultInfo.symbolForMeaning, currentTokenMeaning)) { + addSymbol(moduleSymbol, defaultInfo.symbol, defaultInfo.kind); + } + // check exports with the same name + var exportSymbolWithIdenticalName = checker.tryGetMemberInModuleExportsAndProperties(symbolName, moduleSymbol); + if (exportSymbolWithIdenticalName && symbolHasMeaning(exportSymbolWithIdenticalName, currentTokenMeaning)) { + addSymbol(moduleSymbol, exportSymbolWithIdenticalName, 0 /* Named */); + } + }); + return originalSymbolToExportInfos; + } + function getDefaultLikeExportInfo(moduleSymbol, checker, compilerOptions) { + var exported = getDefaultLikeExportWorker(moduleSymbol, checker); + if (!exported) + return undefined; + var symbol = exported.symbol, kind = exported.kind; + var info = getDefaultExportInfoWorker(symbol, moduleSymbol, checker, compilerOptions); + return info && __assign({ symbol: symbol, kind: kind }, info); + } + function getDefaultLikeExportWorker(moduleSymbol, checker) { + var defaultExport = checker.tryGetMemberInModuleExports("default" /* Default */, moduleSymbol); + if (defaultExport) + return { symbol: defaultExport, kind: 1 /* Default */ }; + var exportEquals = checker.resolveExternalModuleSymbol(moduleSymbol); + return exportEquals === moduleSymbol ? undefined : { symbol: exportEquals, kind: 3 /* Equals */ }; + } + function getDefaultExportInfoWorker(defaultExport, moduleSymbol, checker, compilerOptions) { + var localSymbol = ts.getLocalSymbolForExportDefault(defaultExport); + if (localSymbol) + return { symbolForMeaning: localSymbol, name: localSymbol.name }; + var name = getNameForExportDefault(defaultExport); + if (name !== undefined) + return { symbolForMeaning: defaultExport, name: name }; + if (defaultExport.flags & 2097152 /* Alias */) { + var aliased = checker.getImmediateAliasedSymbol(defaultExport); + return aliased && getDefaultExportInfoWorker(aliased, ts.Debug.assertDefined(aliased.parent), checker, compilerOptions); + } + else { + return { symbolForMeaning: defaultExport, name: moduleSymbolToValidIdentifier(moduleSymbol, compilerOptions.target) }; + } + } + function getNameForExportDefault(symbol) { + return symbol.declarations && ts.firstDefined(symbol.declarations, function (declaration) { + if (ts.isExportAssignment(declaration)) { + if (ts.isIdentifier(declaration.expression)) { + return declaration.expression.text; + } + } + else if (ts.isExportSpecifier(declaration)) { + ts.Debug.assert(declaration.name.text === "default" /* Default */); + return declaration.propertyName && declaration.propertyName.text; + } + }); + } + function codeActionForFix(context, sourceFile, symbolName, fix, quotePreference) { + var diag; + var changes = ts.textChanges.ChangeTracker.with(context, function (tracker) { + diag = codeActionForFixWorker(tracker, sourceFile, symbolName, fix, quotePreference); + }); + return codefix.createCodeFixAction("import", changes, diag, codefix.importFixId, ts.Diagnostics.Add_all_missing_imports); + } + function codeActionForFixWorker(changes, sourceFile, symbolName, fix, quotePreference) { + switch (fix.kind) { + case 0 /* UseNamespace */: + addNamespaceQualifier(changes, sourceFile, fix); + return [ts.Diagnostics.Change_0_to_1, symbolName, fix.namespacePrefix + "." + symbolName]; + case 1 /* ImportType */: + addImportType(changes, sourceFile, fix, quotePreference); + return [ts.Diagnostics.Change_0_to_1, symbolName, getImportTypePrefix(fix.moduleSpecifier, quotePreference) + symbolName]; + case 2 /* AddToExisting */: { + var importClause = fix.importClause, importKind = fix.importKind; + doAddExistingFix(changes, sourceFile, importClause, importKind === 1 /* Default */ ? symbolName : undefined, importKind === 0 /* Named */ ? [symbolName] : ts.emptyArray); + var moduleSpecifierWithoutQuotes = ts.stripQuotes(importClause.parent.moduleSpecifier.getText()); + return [importKind === 1 /* Default */ ? ts.Diagnostics.Add_default_import_0_to_existing_import_declaration_from_1 : ts.Diagnostics.Add_0_to_existing_import_declaration_from_1, symbolName, moduleSpecifierWithoutQuotes]; // you too! + } + case 3 /* AddNew */: { + var importKind = fix.importKind, moduleSpecifier = fix.moduleSpecifier; + addNewImports(changes, sourceFile, moduleSpecifier, quotePreference, importKind === 1 /* Default */ ? { defaultImport: symbolName, namedImports: ts.emptyArray, namespaceLikeImport: undefined } + : importKind === 0 /* Named */ ? { defaultImport: undefined, namedImports: [symbolName], namespaceLikeImport: undefined } + : { defaultImport: undefined, namedImports: ts.emptyArray, namespaceLikeImport: { importKind: importKind, name: symbolName } }); + return [importKind === 1 /* Default */ ? ts.Diagnostics.Import_default_0_from_module_1 : ts.Diagnostics.Import_0_from_module_1, symbolName, moduleSpecifier]; + } + default: + return ts.Debug.assertNever(fix); + } + } + function doAddExistingFix(changes, sourceFile, clause, defaultImport, namedImports) { + if (defaultImport) { + ts.Debug.assert(!clause.name); + changes.insertNodeAt(sourceFile, clause.getStart(sourceFile), ts.createIdentifier(defaultImport), { suffix: ", " }); + } + if (namedImports.length) { + var specifiers = namedImports.map(function (name) { return ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(name)); }); + if (clause.namedBindings && ts.cast(clause.namedBindings, ts.isNamedImports).elements.length) { + for (var _i = 0, specifiers_1 = specifiers; _i < specifiers_1.length; _i++) { + var spec = specifiers_1[_i]; + changes.insertNodeInListAfter(sourceFile, ts.last(ts.cast(clause.namedBindings, ts.isNamedImports).elements), spec); + } + } + else { + if (specifiers.length) { + var namedImports_1 = ts.createNamedImports(specifiers); + if (clause.namedBindings) { + changes.replaceNode(sourceFile, clause.namedBindings, namedImports_1); + } + else { + changes.insertNodeAfter(sourceFile, ts.Debug.assertDefined(clause.name), namedImports_1); + } + } + } + } + } + function addNamespaceQualifier(changes, sourceFile, _a) { + var namespacePrefix = _a.namespacePrefix, position = _a.position; + changes.insertText(sourceFile, position, namespacePrefix + "."); + } + function addImportType(changes, sourceFile, _a, quotePreference) { + var moduleSpecifier = _a.moduleSpecifier, position = _a.position; + changes.insertText(sourceFile, position, getImportTypePrefix(moduleSpecifier, quotePreference)); + } + function getImportTypePrefix(moduleSpecifier, quotePreference) { + var quote = ts.getQuoteFromPreference(quotePreference); + return "import(" + quote + moduleSpecifier + quote + ")."; + } + function addNewImports(changes, sourceFile, moduleSpecifier, quotePreference, _a) { + var defaultImport = _a.defaultImport, namedImports = _a.namedImports, namespaceLikeImport = _a.namespaceLikeImport; + var quotedModuleSpecifier = ts.makeStringLiteral(moduleSpecifier, quotePreference); + if (defaultImport !== undefined || namedImports.length) { + ts.insertImport(changes, sourceFile, ts.makeImport(defaultImport === undefined ? undefined : ts.createIdentifier(defaultImport), namedImports.map(function (n) { return ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(n)); }), moduleSpecifier, quotePreference)); + } + if (namespaceLikeImport) { + ts.insertImport(changes, sourceFile, namespaceLikeImport.importKind === 3 /* Equals */ + ? ts.createImportEqualsDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createIdentifier(namespaceLikeImport.name), ts.createExternalModuleReference(quotedModuleSpecifier)) + : ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(ts.createIdentifier(namespaceLikeImport.name))), quotedModuleSpecifier)); + } + } + function symbolHasMeaning(_a, meaning) { + var declarations = _a.declarations; + return ts.some(declarations, function (decl) { return !!(ts.getMeaningFromDeclaration(decl) & meaning); }); + } + function forEachExternalModuleToImportFrom(checker, from, allSourceFiles, cb) { + forEachExternalModule(checker, allSourceFiles, function (module, sourceFile) { + if (sourceFile === undefined || sourceFile !== from && isImportablePath(from.fileName, sourceFile.fileName)) { + cb(module); + } + }); + } + codefix.forEachExternalModuleToImportFrom = forEachExternalModuleToImportFrom; + function forEachExternalModule(checker, allSourceFiles, cb) { + for (var _i = 0, _a = checker.getAmbientModules(); _i < _a.length; _i++) { + var ambient = _a[_i]; + cb(ambient, /*sourceFile*/ undefined); + } + for (var _b = 0, allSourceFiles_1 = allSourceFiles; _b < allSourceFiles_1.length; _b++) { + var sourceFile = allSourceFiles_1[_b]; + if (ts.isExternalOrCommonJsModule(sourceFile)) { + cb(checker.getMergedSymbol(sourceFile.symbol), sourceFile); + } + } + } + /** + * Don't include something from a `node_modules` that isn't actually reachable by a global import. + * A relative import to node_modules is usually a bad idea. + */ + function isImportablePath(fromPath, toPath) { + // If it's in a `node_modules` but is not reachable from here via a global import, don't bother. + var toNodeModules = ts.forEachAncestorDirectory(toPath, function (ancestor) { return ts.getBaseFileName(ancestor) === "node_modules" ? ancestor : undefined; }); + return toNodeModules === undefined || ts.startsWith(fromPath, ts.getDirectoryPath(toNodeModules)); + } + function moduleSymbolToValidIdentifier(moduleSymbol, target) { + return moduleSpecifierToValidIdentifier(ts.removeFileExtension(ts.stripQuotes(moduleSymbol.name)), target); + } + codefix.moduleSymbolToValidIdentifier = moduleSymbolToValidIdentifier; + function moduleSpecifierToValidIdentifier(moduleSpecifier, target) { + var baseName = ts.getBaseFileName(ts.removeSuffix(moduleSpecifier, "/index")); + var res = ""; + var lastCharWasValid = true; + var firstCharCode = baseName.charCodeAt(0); + if (ts.isIdentifierStart(firstCharCode, target)) { + res += String.fromCharCode(firstCharCode); + } + else { + lastCharWasValid = false; + } + for (var i = 1; i < baseName.length; i++) { + var ch = baseName.charCodeAt(i); + var isValid = ts.isIdentifierPart(ch, target); + if (isValid) { + var char = String.fromCharCode(ch); + if (!lastCharWasValid) { + char = char.toUpperCase(); + } + res += char; + } + lastCharWasValid = isValid; + } + // Need `|| "_"` to ensure result isn't empty. + return !ts.isStringANonContextualKeyword(res) ? res || "_" : "_" + res; + } + codefix.moduleSpecifierToValidIdentifier = moduleSpecifierToValidIdentifier; + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "fixSpelling"; + var errorCodes = [ + ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2.code, + ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1.code, + ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0.code, + ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_static_member_1_0.code, + ts.Diagnostics.Module_0_has_no_exported_member_1_Did_you_mean_2.code, + ]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var sourceFile = context.sourceFile; + var info = getInfo(sourceFile, context.span.start, context); + if (!info) + return undefined; + var node = info.node, suggestion = info.suggestion; + var target = context.host.getCompilationSettings().target; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, node, suggestion, target); }); + return [codefix.createCodeFixAction("spelling", changes, [ts.Diagnostics.Change_spelling_to_0, suggestion], fixId, ts.Diagnostics.Fix_all_detected_spelling_errors)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var info = getInfo(diag.file, diag.start, context); + var target = context.host.getCompilationSettings().target; + if (info) + doChange(changes, context.sourceFile, info.node, info.suggestion, target); + }); }, + }); + function getInfo(sourceFile, pos, context) { + // This is the identifier of the misspelled word. eg: + // this.speling = 1; + // ^^^^^^^ + var node = ts.getTokenAtPosition(sourceFile, pos); + var checker = context.program.getTypeChecker(); + var suggestion; + if (ts.isPropertyAccessExpression(node.parent) && node.parent.name === node) { + ts.Debug.assert(node.kind === 72 /* Identifier */); + var containingType = checker.getTypeAtLocation(node.parent.expression); + suggestion = checker.getSuggestionForNonexistentProperty(node, containingType); + } + else if (ts.isImportSpecifier(node.parent) && node.parent.name === node) { + ts.Debug.assert(node.kind === 72 /* Identifier */); + var importDeclaration = ts.findAncestor(node, ts.isImportDeclaration); + var resolvedSourceFile = getResolvedSourceFileFromImportDeclaration(sourceFile, context, importDeclaration); + if (resolvedSourceFile && resolvedSourceFile.symbol) { + suggestion = checker.getSuggestionForNonexistentExport(node, resolvedSourceFile.symbol); + } + } + else { + var meaning = ts.getMeaningFromLocation(node); + var name = ts.getTextOfNode(node); + ts.Debug.assert(name !== undefined, "name should be defined"); + suggestion = checker.getSuggestionForNonexistentSymbol(node, name, convertSemanticMeaningToSymbolFlags(meaning)); + } + return suggestion === undefined ? undefined : { node: node, suggestion: suggestion }; + } + function doChange(changes, sourceFile, node, suggestion, target) { + if (!ts.isIdentifierText(suggestion, target) && ts.isPropertyAccessExpression(node.parent)) { + changes.replaceNode(sourceFile, node.parent, ts.createElementAccess(node.parent.expression, ts.createLiteral(suggestion))); + } + else { + changes.replaceNode(sourceFile, node, ts.createIdentifier(suggestion)); + } + } + function convertSemanticMeaningToSymbolFlags(meaning) { + var flags = 0; + if (meaning & 4 /* Namespace */) { + flags |= 1920 /* Namespace */; + } + if (meaning & 2 /* Type */) { + flags |= 67897832 /* Type */; + } + if (meaning & 1 /* Value */) { + flags |= 67220415 /* Value */; + } + return flags; + } + function getResolvedSourceFileFromImportDeclaration(sourceFile, context, importDeclaration) { + if (!importDeclaration || !ts.isStringLiteralLike(importDeclaration.moduleSpecifier)) + return undefined; + var resolvedModule = ts.getResolvedModule(sourceFile, importDeclaration.moduleSpecifier.text); + if (!resolvedModule) + return undefined; + return context.program.getSourceFile(resolvedModule.resolvedFileName); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixName = "addMissingMember"; + var errorCodes = [ + ts.Diagnostics.Property_0_does_not_exist_on_type_1.code, + ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2.code, + ts.Diagnostics.Property_0_is_missing_in_type_1_but_required_in_type_2.code, + ts.Diagnostics.Type_0_is_missing_the_following_properties_from_type_1_Colon_2.code, + ts.Diagnostics.Type_0_is_missing_the_following_properties_from_type_1_Colon_2_and_3_more.code + ]; + var fixId = "addMissingMember"; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var info = getInfo(context.sourceFile, context.span.start, context.program.getTypeChecker()); + if (!info) + return undefined; + if (info.kind === 0 /* Enum */) { + var token_1 = info.token, parentDeclaration_1 = info.parentDeclaration; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addEnumMemberDeclaration(t, context.program.getTypeChecker(), token_1, parentDeclaration_1); }); + return [codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Add_missing_enum_member_0, token_1.text], fixId, ts.Diagnostics.Add_all_missing_members)]; + } + var parentDeclaration = info.parentDeclaration, declSourceFile = info.declSourceFile, inJs = info.inJs, makeStatic = info.makeStatic, token = info.token, call = info.call; + var methodCodeAction = call && getActionForMethodDeclaration(context, declSourceFile, parentDeclaration, token, call, makeStatic, inJs, context.preferences); + var addMember = inJs && !ts.isInterfaceDeclaration(parentDeclaration) ? + ts.singleElementArray(getActionsForAddMissingMemberInJavascriptFile(context, declSourceFile, parentDeclaration, token.text, makeStatic)) : + getActionsForAddMissingMemberInTypeScriptFile(context, declSourceFile, parentDeclaration, token, makeStatic); + return ts.concatenate(ts.singleElementArray(methodCodeAction), addMember); + }, + fixIds: [fixId], + getAllCodeActions: function (context) { + var program = context.program, preferences = context.preferences; + var checker = program.getTypeChecker(); + var seen = ts.createMap(); + var typeDeclToMembers = new ts.NodeMap(); + return codefix.createCombinedCodeActions(ts.textChanges.ChangeTracker.with(context, function (changes) { + codefix.eachDiagnostic(context, errorCodes, function (diag) { + var info = getInfo(diag.file, diag.start, checker); + if (!info || !ts.addToSeen(seen, ts.getNodeId(info.parentDeclaration) + "#" + info.token.text)) { + return; + } + if (info.kind === 0 /* Enum */) { + var token = info.token, parentDeclaration = info.parentDeclaration; + addEnumMemberDeclaration(changes, checker, token, parentDeclaration); + } + else { + var parentDeclaration = info.parentDeclaration, token_2 = info.token; + var infos = typeDeclToMembers.getOrUpdate(parentDeclaration, function () { return []; }); + if (!infos.some(function (i) { return i.token.text === token_2.text; })) + infos.push(info); + } + }); + typeDeclToMembers.forEach(function (infos, classDeclaration) { + var supers = getAllSupers(classDeclaration, checker); + var _loop_20 = function (info) { + // If some superclass added this property, don't add it again. + if (supers.some(function (superClassOrInterface) { + var superInfos = typeDeclToMembers.get(superClassOrInterface); + return !!superInfos && superInfos.some(function (_a) { + var token = _a.token; + return token.text === info.token.text; + }); + })) + return "continue"; + var parentDeclaration = info.parentDeclaration, declSourceFile = info.declSourceFile, inJs = info.inJs, makeStatic = info.makeStatic, token = info.token, call = info.call; + // Always prefer to add a method declaration if possible. + if (call) { + addMethodDeclaration(context, changes, declSourceFile, parentDeclaration, token, call, makeStatic, inJs, preferences); + } + else { + if (inJs && !ts.isInterfaceDeclaration(parentDeclaration)) { + addMissingMemberInJs(changes, declSourceFile, parentDeclaration, token.text, makeStatic); + } + else { + var typeNode = getTypeNode(program.getTypeChecker(), parentDeclaration, token); + addPropertyDeclaration(changes, declSourceFile, parentDeclaration, token.text, typeNode, makeStatic); + } + } + }; + for (var _i = 0, infos_1 = infos; _i < infos_1.length; _i++) { + var info = infos_1[_i]; + _loop_20(info); + } + }); + })); + }, + }); + function getAllSupers(decl, checker) { + var res = []; + while (decl) { + var superElement = ts.getClassExtendsHeritageElement(decl); + var superSymbol = superElement && checker.getSymbolAtLocation(superElement.expression); + var superDecl = superSymbol && ts.find(superSymbol.declarations, ts.isClassLike); + if (superDecl) { + res.push(superDecl); + } + decl = superDecl; + } + return res; + } + var InfoKind; + (function (InfoKind) { + InfoKind[InfoKind["Enum"] = 0] = "Enum"; + InfoKind[InfoKind["ClassOrInterface"] = 1] = "ClassOrInterface"; + })(InfoKind || (InfoKind = {})); + function getInfo(tokenSourceFile, tokenPos, checker) { + // The identifier of the missing property. eg: + // this.missing = 1; + // ^^^^^^^ + var token = ts.getTokenAtPosition(tokenSourceFile, tokenPos); + if (!ts.isIdentifier(token)) { + return undefined; + } + var parent = token.parent; + if (!ts.isPropertyAccessExpression(parent)) + return undefined; + var leftExpressionType = ts.skipConstraint(checker.getTypeAtLocation(parent.expression)); + var symbol = leftExpressionType.symbol; + if (!symbol || !symbol.declarations) + return undefined; + // Prefer to change the class instead of the interface if they are merged + var classOrInterface = ts.find(symbol.declarations, ts.isClassLike) || ts.find(symbol.declarations, ts.isInterfaceDeclaration); + if (classOrInterface) { + var makeStatic = (leftExpressionType.target || leftExpressionType) !== checker.getDeclaredTypeOfSymbol(symbol); + var declSourceFile = classOrInterface.getSourceFile(); + var inJs = ts.isSourceFileJS(declSourceFile); + var call = ts.tryCast(parent.parent, ts.isCallExpression); + return { kind: 1 /* ClassOrInterface */, token: token, parentDeclaration: classOrInterface, makeStatic: makeStatic, declSourceFile: declSourceFile, inJs: inJs, call: call }; + } + var enumDeclaration = ts.find(symbol.declarations, ts.isEnumDeclaration); + if (enumDeclaration) { + return { kind: 0 /* Enum */, token: token, parentDeclaration: enumDeclaration }; + } + return undefined; + } + function getActionsForAddMissingMemberInJavascriptFile(context, declSourceFile, classDeclaration, tokenName, makeStatic) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMissingMemberInJs(t, declSourceFile, classDeclaration, tokenName, makeStatic); }); + return changes.length === 0 ? undefined + : codefix.createCodeFixAction(fixName, changes, [makeStatic ? ts.Diagnostics.Initialize_static_property_0 : ts.Diagnostics.Initialize_property_0_in_the_constructor, tokenName], fixId, ts.Diagnostics.Add_all_missing_members); + } + function addMissingMemberInJs(changeTracker, declSourceFile, classDeclaration, tokenName, makeStatic) { + if (makeStatic) { + if (classDeclaration.kind === 209 /* ClassExpression */) { + return; + } + var className = classDeclaration.name.getText(); + var staticInitialization = initializePropertyToUndefined(ts.createIdentifier(className), tokenName); + changeTracker.insertNodeAfter(declSourceFile, classDeclaration, staticInitialization); + } + else { + var classConstructor = ts.getFirstConstructorWithBody(classDeclaration); + if (!classConstructor) { + return; + } + var propertyInitialization = initializePropertyToUndefined(ts.createThis(), tokenName); + changeTracker.insertNodeAtConstructorEnd(declSourceFile, classConstructor, propertyInitialization); + } + } + function initializePropertyToUndefined(obj, propertyName) { + return ts.createStatement(ts.createAssignment(ts.createPropertyAccess(obj, propertyName), ts.createIdentifier("undefined"))); + } + function getActionsForAddMissingMemberInTypeScriptFile(context, declSourceFile, classDeclaration, token, makeStatic) { + var typeNode = getTypeNode(context.program.getTypeChecker(), classDeclaration, token); + var addProp = createAddPropertyDeclarationAction(context, declSourceFile, classDeclaration, makeStatic, token.text, typeNode); + return makeStatic ? [addProp] : [addProp, createAddIndexSignatureAction(context, declSourceFile, classDeclaration, token.text, typeNode)]; + } + function getTypeNode(checker, classDeclaration, token) { + var typeNode; + if (token.parent.parent.kind === 204 /* BinaryExpression */) { + var binaryExpression = token.parent.parent; + var otherExpression = token.parent === binaryExpression.left ? binaryExpression.right : binaryExpression.left; + var widenedType = checker.getWidenedType(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(otherExpression))); + typeNode = checker.typeToTypeNode(widenedType, classDeclaration); + } + else { + var contextualType = checker.getContextualType(token.parent); + typeNode = contextualType ? checker.typeToTypeNode(contextualType) : undefined; + } + return typeNode || ts.createKeywordTypeNode(120 /* AnyKeyword */); + } + function createAddPropertyDeclarationAction(context, declSourceFile, classDeclaration, makeStatic, tokenName, typeNode) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addPropertyDeclaration(t, declSourceFile, classDeclaration, tokenName, typeNode, makeStatic); }); + return codefix.createCodeFixAction(fixName, changes, [makeStatic ? ts.Diagnostics.Declare_static_property_0 : ts.Diagnostics.Declare_property_0, tokenName], fixId, ts.Diagnostics.Add_all_missing_members); + } + function addPropertyDeclaration(changeTracker, declSourceFile, classDeclaration, tokenName, typeNode, makeStatic) { + var property = ts.createProperty( + /*decorators*/ undefined, + /*modifiers*/ makeStatic ? [ts.createToken(116 /* StaticKeyword */)] : undefined, tokenName, + /*questionToken*/ undefined, typeNode, + /*initializer*/ undefined); + var lastProp = getNodeToInsertPropertyAfter(classDeclaration); + if (lastProp) { + changeTracker.insertNodeAfter(declSourceFile, lastProp, property); + } + else { + changeTracker.insertNodeAtClassStart(declSourceFile, classDeclaration, property); + } + } + // Gets the last of the first run of PropertyDeclarations, or undefined if the class does not start with a PropertyDeclaration. + function getNodeToInsertPropertyAfter(cls) { + var res; + for (var _i = 0, _a = cls.members; _i < _a.length; _i++) { + var member = _a[_i]; + if (!ts.isPropertyDeclaration(member)) + break; + res = member; + } + return res; + } + function createAddIndexSignatureAction(context, declSourceFile, classDeclaration, tokenName, typeNode) { + // Index signatures cannot have the static modifier. + var stringTypeNode = ts.createKeywordTypeNode(138 /* StringKeyword */); + var indexingParameter = ts.createParameter( + /*decorators*/ undefined, + /*modifiers*/ undefined, + /*dotDotDotToken*/ undefined, "x", + /*questionToken*/ undefined, stringTypeNode, + /*initializer*/ undefined); + var indexSignature = ts.createIndexSignature( + /*decorators*/ undefined, + /*modifiers*/ undefined, [indexingParameter], typeNode); + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.insertNodeAtClassStart(declSourceFile, classDeclaration, indexSignature); }); + // No fixId here because code-fix-all currently only works on adding individual named properties. + return codefix.createCodeFixActionNoFixId(fixName, changes, [ts.Diagnostics.Add_index_signature_for_property_0, tokenName]); + } + function getActionForMethodDeclaration(context, declSourceFile, classDeclaration, token, callExpression, makeStatic, inJs, preferences) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMethodDeclaration(context, t, declSourceFile, classDeclaration, token, callExpression, makeStatic, inJs, preferences); }); + return codefix.createCodeFixAction(fixName, changes, [makeStatic ? ts.Diagnostics.Declare_static_method_0 : ts.Diagnostics.Declare_method_0, token.text], fixId, ts.Diagnostics.Add_all_missing_members); + } + function addMethodDeclaration(context, changeTracker, declSourceFile, typeDecl, token, callExpression, makeStatic, inJs, preferences) { + var methodDeclaration = codefix.createMethodFromCallExpression(context, callExpression, token.text, inJs, makeStatic, preferences, !ts.isInterfaceDeclaration(typeDecl)); + var containingMethodDeclaration = ts.getAncestor(callExpression, 156 /* MethodDeclaration */); + if (containingMethodDeclaration && containingMethodDeclaration.parent === typeDecl) { + changeTracker.insertNodeAfter(declSourceFile, containingMethodDeclaration, methodDeclaration); + } + else { + changeTracker.insertNodeAtClassStart(declSourceFile, typeDecl, methodDeclaration); + } + } + function addEnumMemberDeclaration(changes, checker, token, enumDeclaration) { + /** + * create initializer only literal enum that has string initializer. + * value of initializer is a string literal that equal to name of enum member. + * numeric enum or empty enum will not create initializer. + */ + var hasStringInitializer = ts.some(enumDeclaration.members, function (member) { + var type = checker.getTypeAtLocation(member); + return !!(type && type.flags & 132 /* StringLike */); + }); + var enumMember = ts.createEnumMember(token, hasStringInitializer ? ts.createStringLiteral(token.text) : undefined); + changes.replaceNode(enumDeclaration.getSourceFile(), enumDeclaration, ts.updateEnumDeclaration(enumDeclaration, enumDeclaration.decorators, enumDeclaration.modifiers, enumDeclaration.name, ts.concatenate(enumDeclaration.members, ts.singleElementArray(enumMember)))); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixName = "fixCannotFindModule"; + var fixIdInstallTypesPackage = "installTypesPackage"; + var fixIdGenerateTypes = "generateTypes"; + var errorCodeCannotFindModule = ts.Diagnostics.Cannot_find_module_0.code; + var errorCodes = [ + errorCodeCannotFindModule, + ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type.code, + ]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var host = context.host, sourceFile = context.sourceFile, start = context.span.start; + var packageName = tryGetImportedPackageName(sourceFile, start); + if (packageName === undefined) + return undefined; + var typesPackageName = getTypesPackageNameToInstall(packageName, host, context.errorCode); + return typesPackageName === undefined + ? ts.singleElementArray(tryGetGenerateTypesAction(context, packageName)) + : [codefix.createCodeFixAction(fixName, /*changes*/ [], [ts.Diagnostics.Install_0, typesPackageName], fixIdInstallTypesPackage, ts.Diagnostics.Install_all_missing_types_packages, getInstallCommand(sourceFile.fileName, typesPackageName))]; + }, + fixIds: [fixIdInstallTypesPackage, fixIdGenerateTypes], + getAllCodeActions: function (context) { + var savedTypesDir = null; // tslint:disable-line no-null-keyword + return codefix.codeFixAll(context, errorCodes, function (changes, diag, commands) { + var packageName = tryGetImportedPackageName(diag.file, diag.start); + if (packageName === undefined) + return undefined; + switch (context.fixId) { + case fixIdInstallTypesPackage: { + var pkg = getTypesPackageNameToInstall(packageName, context.host, diag.code); + if (pkg) { + commands.push(getInstallCommand(diag.file.fileName, pkg)); + } + break; + } + case fixIdGenerateTypes: { + var typesDir = savedTypesDir !== null ? savedTypesDir : savedTypesDir = getOrCreateTypesDirectory(changes, context); + var command = typesDir === undefined ? undefined : tryGenerateTypes(typesDir, packageName, context); + if (command) + commands.push(command); + break; + } + default: + ts.Debug.fail("Bad fixId: " + context.fixId); + } + }); + }, + }); + function tryGetGenerateTypesAction(context, packageName) { + var command; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { + var typesDir = getOrCreateTypesDirectory(t, context); + command = typesDir === undefined ? undefined : tryGenerateTypes(typesDir, packageName, context); + }); + return command && codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Generate_types_for_0, packageName], fixIdGenerateTypes, ts.Diagnostics.Generate_types_for_all_packages_without_types, command); + } + function tryGenerateTypes(typesDir, packageName, context) { + var file = context.sourceFile.fileName; + var fileToGenerateTypesFor = ts.tryResolveJSModule(packageName, ts.getDirectoryPath(file), context.host); // TODO: GH#18217 + if (fileToGenerateTypesFor === undefined) + return undefined; + var outputFileName = ts.resolvePath(ts.getDirectoryPath(context.program.getCompilerOptions().configFile.fileName), typesDir, packageName + ".d.ts"); + if (context.host.fileExists(outputFileName)) + return undefined; + return { type: "generate types", file: file, fileToGenerateTypesFor: fileToGenerateTypesFor, outputFileName: outputFileName }; + } + // If no types directory exists yet, adds it to tsconfig.json + function getOrCreateTypesDirectory(changes, context) { + var configFile = context.program.getCompilerOptions().configFile; + if (!configFile) + return undefined; + var tsconfigObjectLiteral = ts.getTsConfigObjectLiteralExpression(configFile); + if (!tsconfigObjectLiteral) + return undefined; + var compilerOptionsProperty = findProperty(tsconfigObjectLiteral, "compilerOptions"); + if (!compilerOptionsProperty) { + var newCompilerOptions = ts.createObjectLiteral([makeDefaultBaseUrl(), makeDefaultPaths()]); + changes.insertNodeAtObjectStart(configFile, tsconfigObjectLiteral, createJsonPropertyAssignment("compilerOptions", newCompilerOptions)); + return defaultTypesDirectoryName; + } + var compilerOptions = compilerOptionsProperty.initializer; + if (!ts.isObjectLiteralExpression(compilerOptions)) + return defaultTypesDirectoryName; + var baseUrl = getOrAddBaseUrl(changes, configFile, compilerOptions); + var typesDirectoryFromPathMapping = getOrAddPathMapping(changes, configFile, compilerOptions); + return ts.combinePaths(baseUrl, typesDirectoryFromPathMapping); + } + var defaultBaseUrl = "."; + function makeDefaultBaseUrl() { + return createJsonPropertyAssignment("baseUrl", ts.createStringLiteral(defaultBaseUrl)); + } + function getOrAddBaseUrl(changes, tsconfig, compilerOptions) { + var baseUrlProp = findProperty(compilerOptions, "baseUrl"); + if (baseUrlProp) { + return ts.isStringLiteral(baseUrlProp.initializer) ? baseUrlProp.initializer.text : defaultBaseUrl; + } + else { + changes.insertNodeAtObjectStart(tsconfig, compilerOptions, makeDefaultBaseUrl()); + return defaultBaseUrl; + } + } + var defaultTypesDirectoryName = "types"; + function makeDefaultPathMapping() { + return createJsonPropertyAssignment("*", ts.createArrayLiteral([ts.createStringLiteral(defaultTypesDirectoryName + "/*")])); + } + function makeDefaultPaths() { + return createJsonPropertyAssignment("paths", ts.createObjectLiteral([makeDefaultPathMapping()])); + } + function getOrAddPathMapping(changes, tsconfig, compilerOptions) { + var paths = findProperty(compilerOptions, "paths"); + if (!paths || !ts.isObjectLiteralExpression(paths.initializer)) { + changes.insertNodeAtObjectStart(tsconfig, compilerOptions, makeDefaultPaths()); + return defaultTypesDirectoryName; + } + // Look for an existing path mapping. Should look like `"*": "foo/*"`. + var existing = ts.firstDefined(paths.initializer.properties, function (prop) { + return ts.isPropertyAssignment(prop) && ts.isStringLiteral(prop.name) && prop.name.text === "*" && ts.isArrayLiteralExpression(prop.initializer) + ? ts.firstDefined(prop.initializer.elements, function (value) { return ts.isStringLiteral(value) ? ts.tryRemoveSuffix(value.text, "/*") : undefined; }) + : undefined; + }); + if (existing) + return existing; + changes.insertNodeAtObjectStart(tsconfig, paths.initializer, makeDefaultPathMapping()); + return defaultTypesDirectoryName; + } + function createJsonPropertyAssignment(name, initializer) { + return ts.createPropertyAssignment(ts.createStringLiteral(name), initializer); + } + function findProperty(obj, name) { + return ts.find(obj.properties, function (p) { return ts.isPropertyAssignment(p) && !!p.name && ts.isStringLiteral(p.name) && p.name.text === name; }); + } + function getInstallCommand(fileName, packageName) { + return { type: "install package", file: fileName, packageName: packageName }; + } + function tryGetImportedPackageName(sourceFile, pos) { + var moduleName = ts.cast(ts.getTokenAtPosition(sourceFile, pos), ts.isStringLiteral).text; + var packageName = ts.parsePackageName(moduleName).packageName; + return ts.isExternalModuleNameRelative(packageName) ? undefined : packageName; + } + function getTypesPackageNameToInstall(packageName, host, diagCode) { + return diagCode === errorCodeCannotFindModule + ? (ts.JsTyping.nodeCoreModules.has(packageName) ? "@types/node" : undefined) + : (host.isKnownTypesPackageName(packageName) ? ts.getTypesPackageName(packageName) : undefined); // TODO: GH#18217 + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var errorCodes = [ + ts.Diagnostics.Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2.code, + ts.Diagnostics.Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1.code, + ]; + var fixId = "fixClassDoesntImplementInheritedAbstractMember"; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var program = context.program, sourceFile = context.sourceFile, span = context.span; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { + return addMissingMembers(getClass(sourceFile, span.start), sourceFile, program.getTypeChecker(), t, context.preferences); + }); + return changes.length === 0 ? undefined : [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Implement_inherited_abstract_class, fixId, ts.Diagnostics.Implement_all_inherited_abstract_classes)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { + var seenClassDeclarations = ts.createMap(); + return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var classDeclaration = getClass(diag.file, diag.start); + if (ts.addToSeen(seenClassDeclarations, ts.getNodeId(classDeclaration))) { + addMissingMembers(classDeclaration, context.sourceFile, context.program.getTypeChecker(), changes, context.preferences); + } + }); + }, + }); + function getClass(sourceFile, pos) { + // Token is the identifier in the case of a class declaration + // or the class keyword token in the case of a class expression. + var token = ts.getTokenAtPosition(sourceFile, pos); + return ts.cast(token.parent, ts.isClassLike); + } + function addMissingMembers(classDeclaration, sourceFile, checker, changeTracker, preferences) { + var extendsNode = ts.getEffectiveBaseTypeNode(classDeclaration); + var instantiatedExtendsType = checker.getTypeAtLocation(extendsNode); + // Note that this is ultimately derived from a map indexed by symbol names, + // so duplicates cannot occur. + var abstractAndNonPrivateExtendsSymbols = checker.getPropertiesOfType(instantiatedExtendsType).filter(symbolPointsToNonPrivateAndAbstractMember); + codefix.createMissingMemberNodes(classDeclaration, abstractAndNonPrivateExtendsSymbols, checker, preferences, function (member) { return changeTracker.insertNodeAtClassStart(sourceFile, classDeclaration, member); }); + } + function symbolPointsToNonPrivateAndAbstractMember(symbol) { + // See `codeFixClassExtendAbstractProtectedProperty.ts` in https://github.com/Microsoft/TypeScript/pull/11547/files + // (now named `codeFixClassExtendAbstractPrivateProperty.ts`) + var flags = ts.getModifierFlags(ts.first(symbol.getDeclarations())); + return !(flags & 8 /* Private */) && !!(flags & 128 /* Abstract */); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "classSuperMustPrecedeThisAccess"; + var errorCodes = [ts.Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var sourceFile = context.sourceFile, span = context.span; + var nodes = getNodes(sourceFile, span.start); + if (!nodes) + return undefined; + var constructor = nodes.constructor, superCall = nodes.superCall; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, constructor, superCall); }); + return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Make_super_call_the_first_statement_in_the_constructor, fixId, ts.Diagnostics.Make_all_super_calls_the_first_statement_in_their_constructor)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { + var sourceFile = context.sourceFile; + var seenClasses = ts.createMap(); // Ensure we only do this once per class. + return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var nodes = getNodes(diag.file, diag.start); + if (!nodes) + return; + var constructor = nodes.constructor, superCall = nodes.superCall; + if (ts.addToSeen(seenClasses, ts.getNodeId(constructor.parent))) { + doChange(changes, sourceFile, constructor, superCall); + } + }); + }, + }); + function doChange(changes, sourceFile, constructor, superCall) { + changes.insertNodeAtConstructorStart(sourceFile, constructor, superCall); + changes.delete(sourceFile, superCall); + } + function getNodes(sourceFile, pos) { + var token = ts.getTokenAtPosition(sourceFile, pos); + if (token.kind !== 100 /* ThisKeyword */) + return undefined; + var constructor = ts.getContainingFunction(token); + var superCall = findSuperCall(constructor.body); + // figure out if the `this` access is actually inside the supercall + // i.e. super(this.a), since in that case we won't suggest a fix + return superCall && !superCall.expression.arguments.some(function (arg) { return ts.isPropertyAccessExpression(arg) && arg.expression === token; }) ? { constructor: constructor, superCall: superCall } : undefined; + } + function findSuperCall(n) { + return ts.isExpressionStatement(n) && ts.isSuperCall(n.expression) + ? n + : ts.isFunctionLike(n) + ? undefined + : ts.forEachChild(n, findSuperCall); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "constructorForDerivedNeedSuperCall"; + var errorCodes = [ts.Diagnostics.Constructors_for_derived_classes_must_contain_a_super_call.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var sourceFile = context.sourceFile, span = context.span; + var ctr = getNode(sourceFile, span.start); + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, ctr); }); + return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Add_missing_super_call, fixId, ts.Diagnostics.Add_all_missing_super_calls)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + return doChange(changes, context.sourceFile, getNode(diag.file, diag.start)); + }); }, + }); + function getNode(sourceFile, pos) { + var token = ts.getTokenAtPosition(sourceFile, pos); + ts.Debug.assert(token.kind === 124 /* ConstructorKeyword */); + return token.parent; + } + function doChange(changes, sourceFile, ctr) { + var superCall = ts.createStatement(ts.createCall(ts.createSuper(), /*typeArguments*/ undefined, /*argumentsArray*/ ts.emptyArray)); + changes.insertNodeAtConstructorStart(sourceFile, ctr, superCall); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "extendsInterfaceBecomesImplements"; + var errorCodes = [ts.Diagnostics.Cannot_extend_an_interface_0_Did_you_mean_implements.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var sourceFile = context.sourceFile; + var nodes = getNodes(sourceFile, context.span.start); + if (!nodes) + return undefined; + var extendsToken = nodes.extendsToken, heritageClauses = nodes.heritageClauses; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChanges(t, sourceFile, extendsToken, heritageClauses); }); + return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Change_extends_to_implements, fixId, ts.Diagnostics.Change_all_extended_interfaces_to_implements)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var nodes = getNodes(diag.file, diag.start); + if (nodes) + doChanges(changes, diag.file, nodes.extendsToken, nodes.heritageClauses); + }); }, + }); + function getNodes(sourceFile, pos) { + var token = ts.getTokenAtPosition(sourceFile, pos); + var heritageClauses = ts.getContainingClass(token).heritageClauses; + var extendsToken = heritageClauses[0].getFirstToken(); + return extendsToken.kind === 86 /* ExtendsKeyword */ ? { extendsToken: extendsToken, heritageClauses: heritageClauses } : undefined; + } + function doChanges(changes, sourceFile, extendsToken, heritageClauses) { + changes.replaceNode(sourceFile, extendsToken, ts.createToken(109 /* ImplementsKeyword */)); + // If there is already an implements clause, replace the implements keyword with a comma. + if (heritageClauses.length === 2 && + heritageClauses[0].token === 86 /* ExtendsKeyword */ && + heritageClauses[1].token === 109 /* ImplementsKeyword */) { + var implementsToken = heritageClauses[1].getFirstToken(); + var implementsFullStart = implementsToken.getFullStart(); + changes.replaceRange(sourceFile, { pos: implementsFullStart, end: implementsFullStart }, ts.createToken(27 /* CommaToken */)); + // Rough heuristic: delete trailing whitespace after keyword so that it's not excessive. + // (Trailing because leading might be indentation, which is more sensitive.) + var text = sourceFile.text; + var end = implementsToken.end; + while (end < text.length && ts.isWhiteSpaceSingleLine(text.charCodeAt(end))) { + end++; + } + changes.deleteRange(sourceFile, { pos: implementsToken.getStart(), end: end }); + } + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "forgottenThisPropertyAccess"; + var didYouMeanStaticMemberCode = ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_static_member_1_0.code; + var errorCodes = [ + ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0.code, + didYouMeanStaticMemberCode, + ]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var sourceFile = context.sourceFile; + var info = getInfo(sourceFile, context.span.start, context.errorCode); + if (!info) { + return undefined; + } + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, info); }); + return [codefix.createCodeFixAction(fixId, changes, [ts.Diagnostics.Add_0_to_unresolved_variable, info.className || "this"], fixId, ts.Diagnostics.Add_qualifier_to_all_unresolved_variables_matching_a_member_name)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var info = getInfo(diag.file, diag.start, diag.code); + if (info) + doChange(changes, context.sourceFile, info); + }); }, + }); + function getInfo(sourceFile, pos, diagCode) { + var node = ts.getTokenAtPosition(sourceFile, pos); + if (!ts.isIdentifier(node)) + return undefined; + return { node: node, className: diagCode === didYouMeanStaticMemberCode ? ts.getContainingClass(node).name.text : undefined }; + } + function doChange(changes, sourceFile, _a) { + var node = _a.node, className = _a.className; + // TODO (https://github.com/Microsoft/TypeScript/issues/21246): use shared helper + ts.suppressLeadingAndTrailingTrivia(node); + changes.replaceNode(sourceFile, node, ts.createPropertyAccess(className ? ts.createIdentifier(className) : ts.createThis(), node)); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixName = "unusedIdentifier"; + var fixIdPrefix = "unusedIdentifier_prefix"; + var fixIdDelete = "unusedIdentifier_delete"; + var fixIdInfer = "unusedIdentifier_infer"; + var errorCodes = [ + ts.Diagnostics._0_is_declared_but_its_value_is_never_read.code, + ts.Diagnostics._0_is_declared_but_never_used.code, + ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read.code, + ts.Diagnostics.All_imports_in_import_declaration_are_unused.code, + ts.Diagnostics.All_destructured_elements_are_unused.code, + ts.Diagnostics.All_variables_are_unused.code, + ts.Diagnostics.All_type_parameters_are_unused.code, + ]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var errorCode = context.errorCode, sourceFile = context.sourceFile, program = context.program; + var checker = program.getTypeChecker(); + var sourceFiles = program.getSourceFiles(); + var token = ts.getTokenAtPosition(sourceFile, context.span.start); + if (ts.isJSDocTemplateTag(token)) { + return [createDeleteFix(ts.textChanges.ChangeTracker.with(context, function (t) { return t.delete(sourceFile, token); }), ts.Diagnostics.Remove_template_tag)]; + } + if (token.kind === 28 /* LessThanToken */) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return deleteTypeParameters(t, sourceFile, token); }); + return [createDeleteFix(changes, ts.Diagnostics.Remove_type_parameters)]; + } + var importDecl = tryGetFullImport(token); + if (importDecl) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.delete(sourceFile, importDecl); }); + return [createDeleteFix(changes, [ts.Diagnostics.Remove_import_from_0, ts.showModuleSpecifier(importDecl)])]; + } + var delDestructure = ts.textChanges.ChangeTracker.with(context, function (t) { + return tryDeleteFullDestructure(token, t, sourceFile, checker, sourceFiles, /*isFixAll*/ false); + }); + if (delDestructure.length) { + return [createDeleteFix(delDestructure, ts.Diagnostics.Remove_destructuring)]; + } + var delVar = ts.textChanges.ChangeTracker.with(context, function (t) { return tryDeleteFullVariableStatement(sourceFile, token, t); }); + if (delVar.length) { + return [createDeleteFix(delVar, ts.Diagnostics.Remove_variable_statement)]; + } + var result = []; + if (token.kind === 127 /* InferKeyword */) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return changeInferToUnknown(t, sourceFile, token); }); + var name = ts.cast(token.parent, ts.isInferTypeNode).typeParameter.name.text; + result.push(codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Replace_infer_0_with_unknown, name], fixIdInfer, ts.Diagnostics.Replace_all_unused_infer_with_unknown)); + } + else { + var deletion = ts.textChanges.ChangeTracker.with(context, function (t) { + return tryDeleteDeclaration(sourceFile, token, t, checker, sourceFiles, /*isFixAll*/ false); + }); + if (deletion.length) { + var name = ts.isComputedPropertyName(token.parent) ? token.parent : token; + result.push(createDeleteFix(deletion, [ts.Diagnostics.Remove_declaration_for_Colon_0, name.getText(sourceFile)])); + } + } + var prefix = ts.textChanges.ChangeTracker.with(context, function (t) { return tryPrefixDeclaration(t, errorCode, sourceFile, token); }); + if (prefix.length) { + result.push(codefix.createCodeFixAction(fixName, prefix, [ts.Diagnostics.Prefix_0_with_an_underscore, token.getText(sourceFile)], fixIdPrefix, ts.Diagnostics.Prefix_all_unused_declarations_with_where_possible)); + } + return result; + }, + fixIds: [fixIdPrefix, fixIdDelete, fixIdInfer], + getAllCodeActions: function (context) { + var sourceFile = context.sourceFile, program = context.program; + var checker = program.getTypeChecker(); + var sourceFiles = program.getSourceFiles(); + return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var token = ts.getTokenAtPosition(sourceFile, diag.start); + switch (context.fixId) { + case fixIdPrefix: + tryPrefixDeclaration(changes, diag.code, sourceFile, token); + break; + case fixIdDelete: { + if (token.kind === 127 /* InferKeyword */) + break; // Can't delete + var importDecl = tryGetFullImport(token); + if (importDecl) { + changes.delete(sourceFile, importDecl); + } + else if (ts.isJSDocTemplateTag(token)) { + changes.delete(sourceFile, token); + } + else if (token.kind === 28 /* LessThanToken */) { + deleteTypeParameters(changes, sourceFile, token); + } + else if (!tryDeleteFullDestructure(token, changes, sourceFile, checker, sourceFiles, /*isFixAll*/ true) && + !tryDeleteFullVariableStatement(sourceFile, token, changes)) { + tryDeleteDeclaration(sourceFile, token, changes, checker, sourceFiles, /*isFixAll*/ true); + } + break; + } + case fixIdInfer: + if (token.kind === 127 /* InferKeyword */) { + changeInferToUnknown(changes, sourceFile, token); + } + break; + default: + ts.Debug.fail(JSON.stringify(context.fixId)); + } + }); + }, + }); + function changeInferToUnknown(changes, sourceFile, token) { + changes.replaceNode(sourceFile, token.parent, ts.createKeywordTypeNode(143 /* UnknownKeyword */)); + } + function createDeleteFix(changes, diag) { + return codefix.createCodeFixAction(fixName, changes, diag, fixIdDelete, ts.Diagnostics.Delete_all_unused_declarations); + } + function deleteTypeParameters(changes, sourceFile, token) { + changes.delete(sourceFile, ts.Debug.assertDefined(ts.cast(token.parent, ts.isDeclarationWithTypeParameterChildren).typeParameters)); + } + // Sometimes the diagnostic span is an entire ImportDeclaration, so we should remove the whole thing. + function tryGetFullImport(token) { + return token.kind === 92 /* ImportKeyword */ ? ts.tryCast(token.parent, ts.isImportDeclaration) : undefined; + } + function tryDeleteFullDestructure(token, changes, sourceFile, checker, sourceFiles, isFixAll) { + if (token.kind !== 18 /* OpenBraceToken */ || !ts.isObjectBindingPattern(token.parent)) + return false; + var decl = token.parent.parent; + if (decl.kind === 151 /* Parameter */) { + tryDeleteParameter(changes, sourceFile, decl, checker, sourceFiles, isFixAll); + } + else { + changes.delete(sourceFile, decl); + } + return true; + } + function tryDeleteFullVariableStatement(sourceFile, token, changes) { + var declarationList = ts.tryCast(token.parent, ts.isVariableDeclarationList); + if (declarationList && declarationList.getChildren(sourceFile)[0] === token) { + changes.delete(sourceFile, declarationList.parent.kind === 219 /* VariableStatement */ ? declarationList.parent : declarationList); + return true; + } + return false; + } + function tryPrefixDeclaration(changes, errorCode, sourceFile, token) { + // Don't offer to prefix a property. + if (errorCode === ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read.code) + return; + if (token.kind === 127 /* InferKeyword */) { + token = ts.cast(token.parent, ts.isInferTypeNode).typeParameter.name; + } + if (ts.isIdentifier(token) && canPrefix(token)) { + changes.replaceNode(sourceFile, token, ts.createIdentifier("_" + token.text)); + } + } + function canPrefix(token) { + switch (token.parent.kind) { + case 151 /* Parameter */: + case 150 /* TypeParameter */: + return true; + case 237 /* VariableDeclaration */: { + var varDecl = token.parent; + switch (varDecl.parent.parent.kind) { + case 227 /* ForOfStatement */: + case 226 /* ForInStatement */: + return true; + } + } + } + return false; + } + function tryDeleteDeclaration(sourceFile, token, changes, checker, sourceFiles, isFixAll) { + tryDeleteDeclarationWorker(token, changes, sourceFile, checker, sourceFiles, isFixAll); + if (ts.isIdentifier(token)) + deleteAssignments(changes, sourceFile, token, checker); + } + function deleteAssignments(changes, sourceFile, token, checker) { + ts.FindAllReferences.Core.eachSymbolReferenceInFile(token, checker, sourceFile, function (ref) { + if (ts.isPropertyAccessExpression(ref.parent) && ref.parent.name === ref) + ref = ref.parent; + if (ts.isBinaryExpression(ref.parent) && ts.isExpressionStatement(ref.parent.parent) && ref.parent.left === ref) { + changes.delete(sourceFile, ref.parent.parent); + } + }); + } + function tryDeleteDeclarationWorker(token, changes, sourceFile, checker, sourceFiles, isFixAll) { + var parent = token.parent; + if (ts.isParameter(parent)) { + tryDeleteParameter(changes, sourceFile, parent, checker, sourceFiles, isFixAll); + } + else { + changes.delete(sourceFile, ts.isImportClause(parent) ? token : ts.isComputedPropertyName(parent) ? parent.parent : parent); + } + } + function tryDeleteParameter(changes, sourceFile, p, checker, sourceFiles, isFixAll) { + if (mayDeleteParameter(p, checker, isFixAll)) { + if (p.modifiers && p.modifiers.length > 0 + && (!ts.isIdentifier(p.name) || ts.FindAllReferences.Core.isSymbolReferencedInFile(p.name, checker, sourceFile))) { + p.modifiers.forEach(function (modifier) { + changes.deleteModifier(sourceFile, modifier); + }); + } + else { + changes.delete(sourceFile, p); + deleteUnusedArguments(changes, sourceFile, p, sourceFiles, checker); + } + } + } + function mayDeleteParameter(p, checker, isFixAll) { + var parent = p.parent; + switch (parent.kind) { + case 156 /* MethodDeclaration */: + // Don't remove a parameter if this overrides something. + var symbol = checker.getSymbolAtLocation(parent.name); + if (ts.isMemberSymbolInBaseType(symbol, checker)) + return false; + // falls through + case 157 /* Constructor */: + case 239 /* FunctionDeclaration */: + return true; + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: { + // Can't remove a non-last parameter in a callback. Can remove a parameter in code-fix-all if future parameters are also unused. + var parameters = parent.parameters; + var index = parameters.indexOf(p); + ts.Debug.assert(index !== -1); + return isFixAll + ? parameters.slice(index + 1).every(function (p) { return p.name.kind === 72 /* Identifier */ && !p.symbol.isReferenced; }) + : index === parameters.length - 1; + } + case 159 /* SetAccessor */: + // Setter must have a parameter + return false; + default: + return ts.Debug.failBadSyntaxKind(parent); + } + } + function deleteUnusedArguments(changes, sourceFile, deletedParameter, sourceFiles, checker) { + ts.FindAllReferences.Core.eachSignatureCall(deletedParameter.parent, sourceFiles, checker, function (call) { + var index = deletedParameter.parent.parameters.indexOf(deletedParameter); + if (call.arguments.length > index) { // Just in case the call didn't provide enough arguments. + changes.delete(sourceFile, call.arguments[index]); + } + }); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "fixUnreachableCode"; + var errorCodes = [ts.Diagnostics.Unreachable_code_detected.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, context.sourceFile, context.span.start, context.span.length); }); + return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Remove_unreachable_code, fixId, ts.Diagnostics.Remove_all_unreachable_code)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { return doChange(changes, diag.file, diag.start, diag.length); }); }, + }); + function doChange(changes, sourceFile, start, length) { + var token = ts.getTokenAtPosition(sourceFile, start); + var statement = ts.findAncestor(token, ts.isStatement); + ts.Debug.assert(statement.getStart(sourceFile) === token.getStart(sourceFile)); + var container = (ts.isBlock(statement.parent) ? statement.parent : statement).parent; + if (!ts.isBlock(statement.parent) || statement === ts.first(statement.parent.statements)) { + switch (container.kind) { + case 222 /* IfStatement */: + if (container.elseStatement) { + if (ts.isBlock(statement.parent)) { + break; + } + else { + changes.replaceNode(sourceFile, statement, ts.createBlock(ts.emptyArray)); + } + return; + } + // falls through + case 224 /* WhileStatement */: + case 225 /* ForStatement */: + changes.delete(sourceFile, container); + return; + } + } + if (ts.isBlock(statement.parent)) { + var end_2 = start + length; + var lastStatement = ts.Debug.assertDefined(lastWhere(ts.sliceAfter(statement.parent.statements, statement), function (s) { return s.pos < end_2; })); + changes.deleteNodeRange(sourceFile, statement, lastStatement); + } + else { + changes.delete(sourceFile, statement); + } + } + function lastWhere(a, pred) { + var last; + for (var _i = 0, a_1 = a; _i < a_1.length; _i++) { + var value = a_1[_i]; + if (!pred(value)) + break; + last = value; + } + return last; + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "fixUnusedLabel"; + var errorCodes = [ts.Diagnostics.Unused_label.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, context.sourceFile, context.span.start); }); + return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Remove_unused_label, fixId, ts.Diagnostics.Remove_all_unused_labels)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { return doChange(changes, diag.file, diag.start); }); }, + }); + function doChange(changes, sourceFile, start) { + var token = ts.getTokenAtPosition(sourceFile, start); + var labeledStatement = ts.cast(token.parent, ts.isLabeledStatement); + var pos = token.getStart(sourceFile); + var statementPos = labeledStatement.statement.getStart(sourceFile); + // If label is on a separate line, just delete the rest of that line, but not the indentation of the labeled statement. + var end = ts.positionsAreOnSameLine(pos, statementPos, sourceFile) ? statementPos + : ts.skipTrivia(sourceFile.text, ts.findChildOfKind(labeledStatement, 57 /* ColonToken */, sourceFile).end, /*stopAfterLineBreak*/ true); + changes.deleteRange(sourceFile, { pos: pos, end: end }); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixIdPlain = "fixJSDocTypes_plain"; + var fixIdNullable = "fixJSDocTypes_nullable"; + var errorCodes = [ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var sourceFile = context.sourceFile; + var checker = context.program.getTypeChecker(); + var info = getInfo(sourceFile, context.span.start, checker); + if (!info) + return undefined; + var typeNode = info.typeNode, type = info.type; + var original = typeNode.getText(sourceFile); + var actions = [fix(type, fixIdPlain, ts.Diagnostics.Change_all_jsdoc_style_types_to_TypeScript)]; + if (typeNode.kind === 286 /* JSDocNullableType */) { + // for nullable types, suggest the flow-compatible `T | null | undefined` + // in addition to the jsdoc/closure-compatible `T | null` + actions.push(fix(checker.getNullableType(type, 32768 /* Undefined */), fixIdNullable, ts.Diagnostics.Change_all_jsdoc_style_types_to_TypeScript_and_add_undefined_to_nullable_types)); + } + return actions; + function fix(type, fixId, fixAllDescription) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, typeNode, type, checker); }); + return codefix.createCodeFixAction("jdocTypes", changes, [ts.Diagnostics.Change_0_to_1, original, checker.typeToString(type)], fixId, fixAllDescription); + } + }, + fixIds: [fixIdPlain, fixIdNullable], + getAllCodeActions: function (context) { + var fixId = context.fixId, program = context.program, sourceFile = context.sourceFile; + var checker = program.getTypeChecker(); + return codefix.codeFixAll(context, errorCodes, function (changes, err) { + var info = getInfo(err.file, err.start, checker); + if (!info) + return; + var typeNode = info.typeNode, type = info.type; + var fixedType = typeNode.kind === 286 /* JSDocNullableType */ && fixId === fixIdNullable ? checker.getNullableType(type, 32768 /* Undefined */) : type; + doChange(changes, sourceFile, typeNode, fixedType, checker); + }); + } + }); + function doChange(changes, sourceFile, oldTypeNode, newType, checker) { + changes.replaceNode(sourceFile, oldTypeNode, checker.typeToTypeNode(newType, /*enclosingDeclaration*/ oldTypeNode)); // TODO: GH#18217 + } + function getInfo(sourceFile, pos, checker) { + var decl = ts.findAncestor(ts.getTokenAtPosition(sourceFile, pos), isTypeContainer); + var typeNode = decl && decl.type; + return typeNode && { typeNode: typeNode, type: checker.getTypeFromTypeNode(typeNode) }; + } + function isTypeContainer(node) { + // NOTE: Some locations are not handled yet: + // MappedTypeNode.typeParameters and SignatureDeclaration.typeParameters, as well as CallExpression.typeArguments + switch (node.kind) { + case 212 /* AsExpression */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 239 /* FunctionDeclaration */: + case 158 /* GetAccessor */: + case 162 /* IndexSignature */: + case 181 /* MappedType */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 151 /* Parameter */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 159 /* SetAccessor */: + case 242 /* TypeAliasDeclaration */: + case 194 /* TypeAssertionExpression */: + case 237 /* VariableDeclaration */: + return true; + default: + return false; + } + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "fixAwaitInSyncFunction"; + var errorCodes = [ + ts.Diagnostics.await_expression_is_only_allowed_within_an_async_function.code, + ts.Diagnostics.A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator.code, + ]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var sourceFile = context.sourceFile, span = context.span; + var nodes = getNodes(sourceFile, span.start); + if (!nodes) + return undefined; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, nodes); }); + return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Add_async_modifier_to_containing_function, fixId, ts.Diagnostics.Add_all_missing_async_modifiers)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var nodes = getNodes(diag.file, diag.start); + if (!nodes) + return; + doChange(changes, context.sourceFile, nodes); + }); }, + }); + function getReturnType(expr) { + if (expr.type) { + return expr.type; + } + if (ts.isVariableDeclaration(expr.parent) && + expr.parent.type && + ts.isFunctionTypeNode(expr.parent.type)) { + return expr.parent.type.type; + } + } + function getNodes(sourceFile, start) { + var token = ts.getTokenAtPosition(sourceFile, start); + var containingFunction = ts.getContainingFunction(token); + if (!containingFunction) { + return; + } + var insertBefore; + switch (containingFunction.kind) { + case 156 /* MethodDeclaration */: + insertBefore = containingFunction.name; + break; + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + insertBefore = ts.findChildOfKind(containingFunction, 90 /* FunctionKeyword */, sourceFile); + break; + case 197 /* ArrowFunction */: + insertBefore = ts.findChildOfKind(containingFunction, 20 /* OpenParenToken */, sourceFile) || ts.first(containingFunction.parameters); + break; + default: + return; + } + return insertBefore && { + insertBefore: insertBefore, + returnType: getReturnType(containingFunction) + }; + } + function doChange(changes, sourceFile, _a) { + var insertBefore = _a.insertBefore, returnType = _a.returnType; + if (returnType) { + var entityName = ts.getEntityNameFromTypeNode(returnType); + if (!entityName || entityName.kind !== 72 /* Identifier */ || entityName.text !== "Promise") { + changes.replaceNode(sourceFile, returnType, ts.createTypeReferenceNode("Promise", ts.createNodeArray([returnType]))); + } + } + changes.insertModifierBefore(sourceFile, 121 /* AsyncKeyword */, insertBefore); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixName = "disableJsDiagnostics"; + var fixId = "disableJsDiagnostics"; + var errorCodes = ts.mapDefined(Object.keys(ts.Diagnostics), function (key) { + var diag = ts.Diagnostics[key]; + return diag.category === ts.DiagnosticCategory.Error ? diag.code : undefined; + }); + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var sourceFile = context.sourceFile, program = context.program, span = context.span, host = context.host, formatContext = context.formatContext; + if (!ts.isInJSFile(sourceFile) || !ts.isCheckJsEnabledForFile(sourceFile, program.getCompilerOptions())) { + return undefined; + } + var fixes = [ + // fixId unnecessary because adding `// @ts-nocheck` even once will ignore every error in the file. + codefix.createCodeFixActionNoFixId(fixName, [codefix.createFileTextChanges(sourceFile.fileName, [ + ts.createTextChange(sourceFile.checkJsDirective + ? ts.createTextSpanFromBounds(sourceFile.checkJsDirective.pos, sourceFile.checkJsDirective.end) + : ts.createTextSpan(0, 0), "// @ts-nocheck" + ts.getNewLineOrDefaultFromHost(host, formatContext.options)), + ])], ts.Diagnostics.Disable_checking_for_this_file), + ]; + if (ts.textChanges.isValidLocationToAddComment(sourceFile, span.start)) { + fixes.unshift(codefix.createCodeFixAction(fixName, ts.textChanges.ChangeTracker.with(context, function (t) { return makeChange(t, sourceFile, span.start); }), ts.Diagnostics.Ignore_this_error_message, fixId, ts.Diagnostics.Add_ts_ignore_to_all_error_messages)); + } + return fixes; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { + var seenLines = ts.createMap(); + return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + if (ts.textChanges.isValidLocationToAddComment(diag.file, diag.start)) { + makeChange(changes, diag.file, diag.start, seenLines); + } + }); + }, + }); + function makeChange(changes, sourceFile, position, seenLines) { + var lineNumber = ts.getLineAndCharacterOfPosition(sourceFile, position).line; + // Only need to add `// @ts-ignore` for a line once. + if (!seenLines || ts.addToSeen(seenLines, lineNumber)) { + changes.insertCommentBeforeLine(sourceFile, lineNumber, position, " @ts-ignore"); + } + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + /** + * Finds members of the resolved type that are missing in the class pointed to by class decl + * and generates source code for the missing members. + * @param possiblyMissingSymbols The collection of symbols to filter and then get insertions for. + * @returns Empty string iff there are no member insertions. + */ + function createMissingMemberNodes(classDeclaration, possiblyMissingSymbols, checker, preferences, out) { + var classMembers = classDeclaration.symbol.members; + for (var _i = 0, possiblyMissingSymbols_1 = possiblyMissingSymbols; _i < possiblyMissingSymbols_1.length; _i++) { + var symbol = possiblyMissingSymbols_1[_i]; + if (!classMembers.has(symbol.escapedName)) { + addNewNodeForMemberSymbol(symbol, classDeclaration, checker, preferences, out); + } + } + } + codefix.createMissingMemberNodes = createMissingMemberNodes; + /** + * @returns Empty string iff there we can't figure out a representation for `symbol` in `enclosingDeclaration`. + */ + function addNewNodeForMemberSymbol(symbol, enclosingDeclaration, checker, preferences, out) { + var declarations = symbol.getDeclarations(); + if (!(declarations && declarations.length)) { + return undefined; + } + var declaration = declarations[0]; + var name = ts.getSynthesizedDeepClone(ts.getNameOfDeclaration(declaration), /*includeTrivia*/ false); + var visibilityModifier = createVisibilityModifier(ts.getModifierFlags(declaration)); + var modifiers = visibilityModifier ? ts.createNodeArray([visibilityModifier]) : undefined; + var type = checker.getWidenedType(checker.getTypeOfSymbolAtLocation(symbol, enclosingDeclaration)); + var optional = !!(symbol.flags & 16777216 /* Optional */); + switch (declaration.kind) { + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 153 /* PropertySignature */: + case 154 /* PropertyDeclaration */: + var typeNode = checker.typeToTypeNode(type, enclosingDeclaration); + out(ts.createProperty( + /*decorators*/ undefined, modifiers, name, optional ? ts.createToken(56 /* QuestionToken */) : undefined, typeNode, + /*initializer*/ undefined)); + break; + case 155 /* MethodSignature */: + case 156 /* MethodDeclaration */: + // The signature for the implementation appears as an entry in `signatures` iff + // there is only one signature. + // If there are overloads and an implementation signature, it appears as an + // extra declaration that isn't a signature for `type`. + // If there is more than one overload but no implementation signature + // (eg: an abstract method or interface declaration), there is a 1-1 + // correspondence of declarations and signatures. + var signatures = checker.getSignaturesOfType(type, 0 /* Call */); + if (!ts.some(signatures)) { + break; + } + if (declarations.length === 1) { + ts.Debug.assert(signatures.length === 1); + var signature = signatures[0]; + outputMethod(signature, modifiers, name, createStubbedMethodBody(preferences)); + break; + } + for (var _i = 0, signatures_7 = signatures; _i < signatures_7.length; _i++) { + var signature = signatures_7[_i]; + // Need to ensure nodes are fresh each time so they can have different positions. + outputMethod(signature, ts.getSynthesizedDeepClones(modifiers, /*includeTrivia*/ false), ts.getSynthesizedDeepClone(name, /*includeTrivia*/ false)); + } + if (declarations.length > signatures.length) { + var signature = checker.getSignatureFromDeclaration(declarations[declarations.length - 1]); + outputMethod(signature, modifiers, name, createStubbedMethodBody(preferences)); + } + else { + ts.Debug.assert(declarations.length === signatures.length); + out(createMethodImplementingSignatures(signatures, name, optional, modifiers, preferences)); + } + break; + } + function outputMethod(signature, modifiers, name, body) { + var method = signatureToMethodDeclaration(checker, signature, enclosingDeclaration, modifiers, name, optional, body); + if (method) + out(method); + } + } + function signatureToMethodDeclaration(checker, signature, enclosingDeclaration, modifiers, name, optional, body) { + var signatureDeclaration = checker.signatureToSignatureDeclaration(signature, 156 /* MethodDeclaration */, enclosingDeclaration, 256 /* SuppressAnyReturnType */); + if (!signatureDeclaration) { + return undefined; + } + signatureDeclaration.decorators = undefined; + signatureDeclaration.modifiers = modifiers; + signatureDeclaration.name = name; + signatureDeclaration.questionToken = optional ? ts.createToken(56 /* QuestionToken */) : undefined; + signatureDeclaration.body = body; + return signatureDeclaration; + } + function createMethodFromCallExpression(context, call, methodName, inJs, makeStatic, preferences, body) { + var typeArguments = call.typeArguments, args = call.arguments, parent = call.parent; + var checker = context.program.getTypeChecker(); + var types = ts.map(args, function (arg) { + // Widen the type so we don't emit nonsense annotations like "function fn(x: 3) {" + return checker.typeToTypeNode(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(arg))); + }); + var names = ts.map(args, function (arg) { + return ts.isIdentifier(arg) ? arg.text : + ts.isPropertyAccessExpression(arg) ? arg.name.text : undefined; + }); + var contextualType = checker.getContextualType(call); + var returnType = inJs ? undefined : contextualType && checker.typeToTypeNode(contextualType, call) || ts.createKeywordTypeNode(120 /* AnyKeyword */); + return ts.createMethod( + /*decorators*/ undefined, + /*modifiers*/ makeStatic ? [ts.createToken(116 /* StaticKeyword */)] : undefined, + /*asteriskToken*/ ts.isYieldExpression(parent) ? ts.createToken(40 /* AsteriskToken */) : undefined, methodName, + /*questionToken*/ undefined, + /*typeParameters*/ inJs ? undefined : ts.map(typeArguments, function (_, i) { + return ts.createTypeParameterDeclaration(84 /* T */ + typeArguments.length - 1 <= 90 /* Z */ ? String.fromCharCode(84 /* T */ + i) : "T" + i); + }), + /*parameters*/ createDummyParameters(args.length, names, types, /*minArgumentCount*/ undefined, inJs), + /*type*/ returnType, body ? createStubbedMethodBody(preferences) : undefined); + } + codefix.createMethodFromCallExpression = createMethodFromCallExpression; + function createDummyParameters(argCount, names, types, minArgumentCount, inJs) { + var parameters = []; + for (var i = 0; i < argCount; i++) { + var newParameter = ts.createParameter( + /*decorators*/ undefined, + /*modifiers*/ undefined, + /*dotDotDotToken*/ undefined, + /*name*/ names && names[i] || "arg" + i, + /*questionToken*/ minArgumentCount !== undefined && i >= minArgumentCount ? ts.createToken(56 /* QuestionToken */) : undefined, + /*type*/ inJs ? undefined : types && types[i] || ts.createKeywordTypeNode(120 /* AnyKeyword */), + /*initializer*/ undefined); + parameters.push(newParameter); + } + return parameters; + } + function createMethodImplementingSignatures(signatures, name, optional, modifiers, preferences) { + /** This is *a* signature with the maximal number of arguments, + * such that if there is a "maximal" signature without rest arguments, + * this is one of them. + */ + var maxArgsSignature = signatures[0]; + var minArgumentCount = signatures[0].minArgumentCount; + var someSigHasRestParameter = false; + for (var _i = 0, signatures_8 = signatures; _i < signatures_8.length; _i++) { + var sig = signatures_8[_i]; + minArgumentCount = Math.min(sig.minArgumentCount, minArgumentCount); + if (sig.hasRestParameter) { + someSigHasRestParameter = true; + } + if (sig.parameters.length >= maxArgsSignature.parameters.length && (!sig.hasRestParameter || maxArgsSignature.hasRestParameter)) { + maxArgsSignature = sig; + } + } + var maxNonRestArgs = maxArgsSignature.parameters.length - (maxArgsSignature.hasRestParameter ? 1 : 0); + var maxArgsParameterSymbolNames = maxArgsSignature.parameters.map(function (symbol) { return symbol.name; }); + var parameters = createDummyParameters(maxNonRestArgs, maxArgsParameterSymbolNames, /* types */ undefined, minArgumentCount, /*inJs*/ false); + if (someSigHasRestParameter) { + var anyArrayType = ts.createArrayTypeNode(ts.createKeywordTypeNode(120 /* AnyKeyword */)); + var restParameter = ts.createParameter( + /*decorators*/ undefined, + /*modifiers*/ undefined, ts.createToken(25 /* DotDotDotToken */), maxArgsParameterSymbolNames[maxNonRestArgs] || "rest", + /*questionToken*/ maxNonRestArgs >= minArgumentCount ? ts.createToken(56 /* QuestionToken */) : undefined, anyArrayType, + /*initializer*/ undefined); + parameters.push(restParameter); + } + return createStubbedMethod(modifiers, name, optional, + /*typeParameters*/ undefined, parameters, + /*returnType*/ undefined, preferences); + } + function createStubbedMethod(modifiers, name, optional, typeParameters, parameters, returnType, preferences) { + return ts.createMethod( + /*decorators*/ undefined, modifiers, + /*asteriskToken*/ undefined, name, optional ? ts.createToken(56 /* QuestionToken */) : undefined, typeParameters, parameters, returnType, createStubbedMethodBody(preferences)); + } + function createStubbedMethodBody(preferences) { + return ts.createBlock([ts.createThrow(ts.createNew(ts.createIdentifier("Error"), + /*typeArguments*/ undefined, [ts.createLiteral("Method not implemented.", /*isSingleQuote*/ preferences.quotePreference === "single")]))], + /*multiline*/ true); + } + function createVisibilityModifier(flags) { + if (flags & 4 /* Public */) { + return ts.createToken(115 /* PublicKeyword */); + } + else if (flags & 16 /* Protected */) { + return ts.createToken(114 /* ProtectedKeyword */); + } + return undefined; + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixName = "invalidImportSyntax"; + function getCodeFixesForImportDeclaration(context, node) { + var sourceFile = ts.getSourceFileOfNode(node); + var namespace = ts.getNamespaceDeclarationNode(node); + var opts = context.program.getCompilerOptions(); + var variations = []; + // import Bluebird from "bluebird"; + variations.push(createAction(context, sourceFile, node, ts.makeImport(namespace.name, /*namedImports*/ undefined, node.moduleSpecifier, ts.getQuotePreference(sourceFile, context.preferences)))); + if (ts.getEmitModuleKind(opts) === ts.ModuleKind.CommonJS) { + // import Bluebird = require("bluebird"); + variations.push(createAction(context, sourceFile, node, ts.createImportEqualsDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, namespace.name, ts.createExternalModuleReference(node.moduleSpecifier)))); + } + return variations; + } + function createAction(context, sourceFile, node, replacement) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.replaceNode(sourceFile, node, replacement); }); + return codefix.createCodeFixActionNoFixId(fixName, changes, [ts.Diagnostics.Replace_import_with_0, changes[0].textChanges[0].newText]); + } + codefix.registerCodeFix({ + errorCodes: [ + ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures.code, + ts.Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature.code, + ], + getCodeActions: getActionsForUsageOfInvalidImport + }); + function getActionsForUsageOfInvalidImport(context) { + var sourceFile = context.sourceFile; + var targetKind = ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures.code === context.errorCode ? 191 /* CallExpression */ : 192 /* NewExpression */; + var node = ts.findAncestor(ts.getTokenAtPosition(sourceFile, context.span.start), function (a) { return a.kind === targetKind && a.getStart() === context.span.start && a.getEnd() === (context.span.start + context.span.length); }); + if (!node) { + return []; + } + var expr = node.expression; + return getImportCodeFixesForExpression(context, expr); + } + codefix.registerCodeFix({ + errorCodes: [ + // The following error codes cover pretty much all assignability errors that could involve an expression + ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1.code, + ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1.code, + ts.Diagnostics.Type_0_is_not_assignable_to_type_1.code, + ts.Diagnostics.Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated.code, + ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1.code, + ts.Diagnostics.Property_0_of_type_1_is_not_assignable_to_string_index_type_2.code, + ts.Diagnostics.Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2.code, + ts.Diagnostics.Numeric_index_type_0_is_not_assignable_to_string_index_type_1.code, + ts.Diagnostics.Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2.code, + ts.Diagnostics.Property_0_in_type_1_is_not_assignable_to_type_2.code, + ts.Diagnostics.Property_0_of_JSX_spread_attribute_is_not_assignable_to_target_property.code, + ts.Diagnostics.The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1.code, + ], + getCodeActions: getActionsForInvalidImportLocation + }); + function getActionsForInvalidImportLocation(context) { + var sourceFile = context.sourceFile; + var node = ts.findAncestor(ts.getTokenAtPosition(sourceFile, context.span.start), function (a) { return a.getStart() === context.span.start && a.getEnd() === (context.span.start + context.span.length); }); + if (!node) { + return []; + } + return getImportCodeFixesForExpression(context, node); + } + function getImportCodeFixesForExpression(context, expr) { + var type = context.program.getTypeChecker().getTypeAtLocation(expr); + if (!(type.symbol && type.symbol.originatingImport)) { + return []; + } + var fixes = []; + var relatedImport = type.symbol.originatingImport; // TODO: GH#18217 + if (!ts.isImportCall(relatedImport)) { + ts.addRange(fixes, getCodeFixesForImportDeclaration(context, relatedImport)); + } + if (ts.isExpression(expr) && !(ts.isNamedDeclaration(expr.parent) && expr.parent.name === expr)) { + var sourceFile_3 = context.sourceFile; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.replaceNode(sourceFile_3, expr, ts.createPropertyAccess(expr, "default"), {}); }); + fixes.push(codefix.createCodeFixActionNoFixId(fixName, changes, ts.Diagnostics.Use_synthetic_default_member)); + } + return fixes; + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixName = "strictClassInitialization"; + var fixIdAddDefiniteAssignmentAssertions = "addMissingPropertyDefiniteAssignmentAssertions"; + var fixIdAddUndefinedType = "addMissingPropertyUndefinedType"; + var fixIdAddInitializer = "addMissingPropertyInitializer"; + var errorCodes = [ts.Diagnostics.Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var propertyDeclaration = getPropertyDeclaration(context.sourceFile, context.span.start); + if (!propertyDeclaration) + return; + var result = [ + getActionForAddMissingUndefinedType(context, propertyDeclaration), + getActionForAddMissingDefiniteAssignmentAssertion(context, propertyDeclaration) + ]; + ts.append(result, getActionForAddMissingInitializer(context, propertyDeclaration)); + return result; + }, + fixIds: [fixIdAddDefiniteAssignmentAssertions, fixIdAddUndefinedType, fixIdAddInitializer], + getAllCodeActions: function (context) { + return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var propertyDeclaration = getPropertyDeclaration(diag.file, diag.start); + if (!propertyDeclaration) + return; + switch (context.fixId) { + case fixIdAddDefiniteAssignmentAssertions: + addDefiniteAssignmentAssertion(changes, diag.file, propertyDeclaration); + break; + case fixIdAddUndefinedType: + addUndefinedType(changes, diag.file, propertyDeclaration); + break; + case fixIdAddInitializer: + var checker = context.program.getTypeChecker(); + var initializer = getInitializer(checker, propertyDeclaration); + if (!initializer) + return; + addInitializer(changes, diag.file, propertyDeclaration, initializer); + break; + default: + ts.Debug.fail(JSON.stringify(context.fixId)); + } + }); + }, + }); + function getPropertyDeclaration(sourceFile, pos) { + var token = ts.getTokenAtPosition(sourceFile, pos); + return ts.isIdentifier(token) ? ts.cast(token.parent, ts.isPropertyDeclaration) : undefined; + } + function getActionForAddMissingDefiniteAssignmentAssertion(context, propertyDeclaration) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addDefiniteAssignmentAssertion(t, context.sourceFile, propertyDeclaration); }); + return codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Add_definite_assignment_assertion_to_property_0, propertyDeclaration.getText()], fixIdAddDefiniteAssignmentAssertions, ts.Diagnostics.Add_definite_assignment_assertions_to_all_uninitialized_properties); + } + function addDefiniteAssignmentAssertion(changeTracker, propertyDeclarationSourceFile, propertyDeclaration) { + var property = ts.updateProperty(propertyDeclaration, propertyDeclaration.decorators, propertyDeclaration.modifiers, propertyDeclaration.name, ts.createToken(52 /* ExclamationToken */), propertyDeclaration.type, propertyDeclaration.initializer); + changeTracker.replaceNode(propertyDeclarationSourceFile, propertyDeclaration, property); + } + function getActionForAddMissingUndefinedType(context, propertyDeclaration) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addUndefinedType(t, context.sourceFile, propertyDeclaration); }); + return codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Add_undefined_type_to_property_0, propertyDeclaration.name.getText()], fixIdAddUndefinedType, ts.Diagnostics.Add_undefined_type_to_all_uninitialized_properties); + } + function addUndefinedType(changeTracker, propertyDeclarationSourceFile, propertyDeclaration) { + var undefinedTypeNode = ts.createKeywordTypeNode(141 /* UndefinedKeyword */); + var type = propertyDeclaration.type; // TODO: GH#18217 + var types = ts.isUnionTypeNode(type) ? type.types.concat(undefinedTypeNode) : [type, undefinedTypeNode]; + changeTracker.replaceNode(propertyDeclarationSourceFile, type, ts.createUnionTypeNode(types)); + } + function getActionForAddMissingInitializer(context, propertyDeclaration) { + var checker = context.program.getTypeChecker(); + var initializer = getInitializer(checker, propertyDeclaration); + if (!initializer) + return undefined; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addInitializer(t, context.sourceFile, propertyDeclaration, initializer); }); + return codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Add_initializer_to_property_0, propertyDeclaration.name.getText()], fixIdAddInitializer, ts.Diagnostics.Add_initializers_to_all_uninitialized_properties); + } + function addInitializer(changeTracker, propertyDeclarationSourceFile, propertyDeclaration, initializer) { + var property = ts.updateProperty(propertyDeclaration, propertyDeclaration.decorators, propertyDeclaration.modifiers, propertyDeclaration.name, propertyDeclaration.questionToken, propertyDeclaration.type, initializer); + changeTracker.replaceNode(propertyDeclarationSourceFile, propertyDeclaration, property); + } + function getInitializer(checker, propertyDeclaration) { + return getDefaultValueFromType(checker, checker.getTypeFromTypeNode(propertyDeclaration.type)); // TODO: GH#18217 + } + function getDefaultValueFromType(checker, type) { + if (type.flags & 512 /* BooleanLiteral */) { + return (type === checker.getFalseType() || type === checker.getFalseType(/*fresh*/ true)) ? ts.createFalse() : ts.createTrue(); + } + else if (type.isLiteral()) { + return ts.createLiteral(type.value); + } + else if (type.isUnion()) { + return ts.firstDefined(type.types, function (t) { return getDefaultValueFromType(checker, t); }); + } + else if (type.isClass()) { + var classDeclaration = ts.getClassLikeDeclarationOfSymbol(type.symbol); + if (!classDeclaration || ts.hasModifier(classDeclaration, 128 /* Abstract */)) + return undefined; + var constructorDeclaration = ts.getFirstConstructorWithBody(classDeclaration); + if (constructorDeclaration && constructorDeclaration.parameters.length) + return undefined; + return ts.createNew(ts.createIdentifier(type.symbol.name), /*typeArguments*/ undefined, /*argumentsArray*/ undefined); + } + else if (checker.isArrayLikeType(type)) { + return ts.createArrayLiteral(); + } + return undefined; + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + function generateTypesForModule(name, moduleValue, formatSettings) { + return generateTypesForModuleOrGlobal(name, moduleValue, formatSettings, 0 /* ExportEquals */); + } + ts.generateTypesForModule = generateTypesForModule; + function generateTypesForGlobal(name, globalValue, formatSettings) { + return generateTypesForModuleOrGlobal(name, globalValue, formatSettings, 3 /* Global */); + } + ts.generateTypesForGlobal = generateTypesForGlobal; + function generateTypesForModuleOrGlobal(name, globalValue, formatSettings, outputKind) { + return valueInfoToDeclarationFileText(ts.inspectValue(name, globalValue), formatSettings, outputKind); + } + /* @internal */ + function valueInfoToDeclarationFileText(valueInfo, formatSettings, outputKind) { + if (outputKind === void 0) { outputKind = 0 /* ExportEquals */; } + return ts.textChanges.getNewFileText(toStatements(valueInfo, outputKind), 3 /* TS */, formatSettings.newLineCharacter || "\n", ts.formatting.getFormatContext(formatSettings)); + } + ts.valueInfoToDeclarationFileText = valueInfoToDeclarationFileText; + var OutputKind; + (function (OutputKind) { + OutputKind[OutputKind["ExportEquals"] = 0] = "ExportEquals"; + OutputKind[OutputKind["NamedExport"] = 1] = "NamedExport"; + OutputKind[OutputKind["NamespaceMember"] = 2] = "NamespaceMember"; + OutputKind[OutputKind["Global"] = 3] = "Global"; + })(OutputKind || (OutputKind = {})); + function toNamespaceMemberStatements(info) { + return toStatements(info, 2 /* NamespaceMember */); + } + function toStatements(info, kind) { + var isDefault = info.name === "default" /* Default */; + var name = isDefault ? "_default" : info.name; + if (!isValidIdentifier(name) || isDefault && kind !== 1 /* NamedExport */) + return ts.emptyArray; + var modifiers = isDefault && info.kind === 2 /* FunctionOrClass */ ? [ts.createModifier(85 /* ExportKeyword */), ts.createModifier(80 /* DefaultKeyword */)] + : kind === 3 /* Global */ || kind === 0 /* ExportEquals */ ? [ts.createModifier(125 /* DeclareKeyword */)] + : kind === 1 /* NamedExport */ ? [ts.createModifier(85 /* ExportKeyword */)] + : undefined; + var exportEquals = function () { return kind === 0 /* ExportEquals */ ? [exportEqualsOrDefault(info.name, /*isExportEquals*/ true)] : ts.emptyArray; }; + var exportDefault = function () { return isDefault ? [exportEqualsOrDefault("_default", /*isExportEquals*/ false)] : ts.emptyArray; }; + switch (info.kind) { + case 2 /* FunctionOrClass */: + return exportEquals().concat(functionOrClassToStatements(modifiers, name, info)); + case 3 /* Object */: + var members = info.members, hasNontrivialPrototype = info.hasNontrivialPrototype; + if (!hasNontrivialPrototype) { + if (kind === 0 /* ExportEquals */) { + return ts.flatMap(members, function (v) { return toStatements(v, 1 /* NamedExport */); }); + } + if (members.some(function (m) { return m.kind === 2 /* FunctionOrClass */; })) { + // If some member is a function, use a namespace so it gets a FunctionDeclaration or ClassDeclaration. + return exportDefault().concat([createNamespace(modifiers, name, ts.flatMap(members, toNamespaceMemberStatements))]); + } + } + // falls through + case 0 /* Const */: + case 1 /* Array */: { + var comment = info.kind === 0 /* Const */ ? info.comment : undefined; + var constVar = ts.createVariableStatement(modifiers, ts.createVariableDeclarationList([ts.createVariableDeclaration(name, toType(info))], 2 /* Const */)); + return exportEquals().concat(exportDefault(), [addComment(constVar, comment)]); + } + default: + return ts.Debug.assertNever(info); + } + } + function exportEqualsOrDefault(name, isExportEquals) { + return ts.createExportAssignment(/*decorators*/ undefined, /*modifiers*/ undefined, isExportEquals, ts.createIdentifier(name)); + } + function functionOrClassToStatements(modifiers, name, _a) { + var source = _a.source, prototypeMembers = _a.prototypeMembers, namespaceMembers = _a.namespaceMembers; + var fnAst = parseClassOrFunctionBody(source); + var _b = fnAst === undefined ? { parameters: ts.emptyArray, returnType: anyType() } : getParametersAndReturnType(fnAst), parameters = _b.parameters, returnType = _b.returnType; + var protoOrInstanceMembers = ts.createMap(); + if (typeof fnAst === "object") + getConstructorFunctionInstanceProperties(fnAst, protoOrInstanceMembers); + for (var _i = 0, prototypeMembers_1 = prototypeMembers; _i < prototypeMembers_1.length; _i++) { + var p = prototypeMembers_1[_i]; + // ignore non-functions on the prototype + if (p.kind === 2 /* FunctionOrClass */) { + var m = tryGetMethod(p); + if (m) { + protoOrInstanceMembers.set(p.name, m); + } + } + } + var classStaticMembers = protoOrInstanceMembers.size !== 0 || fnAst === undefined || typeof fnAst !== "number" && fnAst.kind === 157 /* Constructor */ ? [] : undefined; + var namespaceStatements = ts.flatMap(namespaceMembers, function (info) { + if (!isValidIdentifier(info.name)) + return undefined; + if (classStaticMembers) { + switch (info.kind) { + case 3 /* Object */: + if (info.members.some(function (m) { return m.kind === 2 /* FunctionOrClass */; })) { + break; + } + // falls through + case 1 /* Array */: + case 0 /* Const */: + classStaticMembers.push(addComment(ts.createProperty(/*decorators*/ undefined, [ts.createModifier(116 /* StaticKeyword */)], info.name, /*questionOrExclamationToken*/ undefined, toType(info), /*initializer*/ undefined), info.kind === 0 /* Const */ ? info.comment : undefined)); + return undefined; + case 2 /* FunctionOrClass */: + if (!info.namespaceMembers.length) { // Else, can't merge a static method with a namespace. Must make it a function on the namespace. + var sig = tryGetMethod(info, [ts.createModifier(116 /* StaticKeyword */)]); + if (sig) { + classStaticMembers.push(sig); + return undefined; + } + } + break; + default: + ts.Debug.assertNever(info); + } + } + return toStatements(info, 2 /* NamespaceMember */); + }); + var decl = classStaticMembers + ? ts.createClassDeclaration( + /*decorators*/ undefined, modifiers, name, + /*typeParameters*/ undefined, + /*heritageClauses*/ undefined, classStaticMembers.concat((parameters.length ? [ts.createConstructor(/*decorators*/ undefined, /*modifiers*/ undefined, parameters, /*body*/ undefined)] : ts.emptyArray), ts.arrayFrom(protoOrInstanceMembers.values()))) + : ts.createFunctionDeclaration(/*decorators*/ undefined, modifiers, /*asteriskToken*/ undefined, name, /*typeParameters*/ undefined, parameters, returnType, /*body*/ undefined); + return [decl].concat((namespaceStatements.length === 0 ? ts.emptyArray : [createNamespace(modifiers && modifiers.map(function (m) { return ts.getSynthesizedDeepClone(m); }), name, namespaceStatements)])); + } + function tryGetMethod(_a, modifiers) { + var name = _a.name, source = _a.source; + if (!isValidIdentifier(name)) + return undefined; + var fnAst = parseClassOrFunctionBody(source); + if (fnAst === undefined || (typeof fnAst !== "number" && fnAst.kind === 157 /* Constructor */)) + return undefined; + var sig = getParametersAndReturnType(fnAst); + return sig && ts.createMethod( + /*decorators*/ undefined, modifiers, + /*asteriskToken*/ undefined, name, + /*questionToken*/ undefined, + /*typeParameters*/ undefined, sig.parameters, sig.returnType, + /*body*/ undefined); + } + function toType(info) { + switch (info.kind) { + case 0 /* Const */: + return ts.createTypeReferenceNode(info.typeName, /*typeArguments*/ undefined); + case 1 /* Array */: + return ts.createArrayTypeNode(toType(info.inner)); + case 2 /* FunctionOrClass */: + return ts.createTypeReferenceNode("Function", /*typeArguments*/ undefined); // Normally we create a FunctionDeclaration, but this can happen for a function in an array. + case 3 /* Object */: + return ts.createTypeLiteralNode(info.members.map(function (m) { return ts.createPropertySignature(/*modifiers*/ undefined, toPropertyName(m.name), /*questionToken*/ undefined, toType(m), /*initializer*/ undefined); })); + default: + return ts.Debug.assertNever(info); + } + } + function toPropertyName(name) { + return ts.isIdentifierText(name, 6 /* ESNext */) ? ts.createIdentifier(name) : ts.createStringLiteral(name); + } + // Parses assignments to "this.x" in the constructor into class property declarations + function getConstructorFunctionInstanceProperties(fnAst, members) { + forEachOwnNodeOfFunction(fnAst, function (node) { + if (ts.isAssignmentExpression(node, /*excludeCompoundAssignment*/ true) && + ts.isPropertyAccessExpression(node.left) && node.left.expression.kind === 100 /* ThisKeyword */) { + var name_6 = node.left.name.text; + if (!ts.isJsPrivate(name_6)) { + ts.getOrUpdate(members, name_6, function () { return ts.createProperty(/*decorators*/ undefined, /*modifiers*/ undefined, name_6, /*questionOrExclamationToken*/ undefined, anyType(), /*initializer*/ undefined); }); + } + } + }); + } + function getParametersAndReturnType(fnAst) { + if (typeof fnAst === "number") { + return { parameters: ts.fill(fnAst, function (i) { return makeParameter("p" + i, anyType()); }), returnType: anyType() }; + } + var usedArguments = false, hasReturn = false; + forEachOwnNodeOfFunction(fnAst, function (node) { + usedArguments = usedArguments || ts.isIdentifier(node) && node.text === "arguments"; + hasReturn = hasReturn || ts.isReturnStatement(node) && !!node.expression && node.expression.kind !== 200 /* VoidExpression */; + }); + var parameters = fnAst.parameters.map(function (p) { return makeParameter("" + p.name.getText(), inferParameterType(fnAst, p)); }).concat((usedArguments ? [makeRestParameter()] : ts.emptyArray)); + return { parameters: parameters, returnType: hasReturn ? anyType() : ts.createKeywordTypeNode(106 /* VoidKeyword */) }; + } + function makeParameter(name, type) { + return ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, name, /*questionToken*/ undefined, type); + } + function makeRestParameter() { + return ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createToken(25 /* DotDotDotToken */), "args", /*questionToken*/ undefined, ts.createArrayTypeNode(anyType())); + } + /** Returns 'undefined' for class with no declared constructor */ + function parseClassOrFunctionBody(source) { + if (typeof source === "number") + return source; + var classOrFunction = ts.tryCast(parseExpression(source), function (node) { return ts.isFunctionExpression(node) || ts.isArrowFunction(node) || ts.isClassExpression(node); }); + return classOrFunction + ? ts.isClassExpression(classOrFunction) ? ts.find(classOrFunction.members, ts.isConstructorDeclaration) : classOrFunction + // If that didn't parse, it's a method `m() {}`. Parse again inside of an object literal. + : ts.cast(ts.first(ts.cast(parseExpression("{ " + source + " }"), ts.isObjectLiteralExpression).properties), ts.isMethodDeclaration); + } + function parseExpression(expr) { + var text = "const _ = " + expr; + var srcFile = ts.createSourceFile("test.ts", text, 6 /* Latest */, /*setParentNodes*/ true); + return ts.first(ts.cast(ts.first(srcFile.statements), ts.isVariableStatement).declarationList.declarations).initializer; + } + function inferParameterType(_fn, _param) { + // TODO: Inspect function body for clues (see inferFromUsage.ts) + return anyType(); + } + // Descends through all nodes in a function, but not in nested functions. + function forEachOwnNodeOfFunction(fnAst, cb) { + fnAst.body.forEachChild(function recur(node) { + cb(node); + if (!ts.isFunctionLike(node)) + node.forEachChild(recur); + }); + } + function isValidIdentifier(name) { + var keyword = ts.stringToToken(name); + return !(keyword && ts.isNonContextualKeyword(keyword)) && ts.isIdentifierText(name, 6 /* ESNext */); + } + function addComment(node, comment) { + if (comment !== undefined) + ts.addSyntheticLeadingComment(node, 2 /* SingleLineCommentTrivia */, comment); + return node; + } + function anyType() { + return ts.createKeywordTypeNode(120 /* AnyKeyword */); + } + function createNamespace(modifiers, name, statements) { + return ts.createModuleDeclaration(/*decorators*/ undefined, modifiers, ts.createIdentifier(name), ts.createModuleBlock(statements), 16 /* Namespace */); + } +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "requireInTs"; + var errorCodes = [ts.Diagnostics.require_call_may_be_converted_to_an_import.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, context.sourceFile, context.span.start, context.program); }); + return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Convert_require_to_import, fixId, ts.Diagnostics.Convert_all_require_to_import)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { return doChange(changes, diag.file, diag.start, context.program); }); }, + }); + function doChange(changes, sourceFile, pos, program) { + var _a = getInfo(sourceFile, pos), statement = _a.statement, name = _a.name, required = _a.required; + changes.replaceNode(sourceFile, statement, ts.getAllowSyntheticDefaultImports(program.getCompilerOptions()) + ? ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createImportClause(name, /*namedBindings*/ undefined), required) + : ts.createImportEqualsDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, name, ts.createExternalModuleReference(required))); + } + function getInfo(sourceFile, pos) { + var parent = ts.getTokenAtPosition(sourceFile, pos).parent; + if (!ts.isRequireCall(parent, /*checkArgumentIsStringLiteralLike*/ true)) + throw ts.Debug.failBadSyntaxKind(parent); + var decl = ts.cast(parent.parent, ts.isVariableDeclaration); + return { statement: ts.cast(decl.parent.parent, ts.isVariableStatement), name: ts.cast(decl.name, ts.isIdentifier), required: parent.arguments[0] }; + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "useDefaultImport"; + var errorCodes = [ts.Diagnostics.Import_may_be_converted_to_a_default_import.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var sourceFile = context.sourceFile, start = context.span.start; + var info = getInfo(sourceFile, start); + if (!info) + return undefined; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, info, context.preferences); }); + return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Convert_to_default_import, fixId, ts.Diagnostics.Convert_all_to_default_imports)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var info = getInfo(diag.file, diag.start); + if (info) + doChange(changes, diag.file, info, context.preferences); + }); }, + }); + function getInfo(sourceFile, pos) { + var name = ts.getTokenAtPosition(sourceFile, pos); + if (!ts.isIdentifier(name)) + return undefined; // bad input + var parent = name.parent; + if (ts.isImportEqualsDeclaration(parent) && ts.isExternalModuleReference(parent.moduleReference)) { + return { importNode: parent, name: name, moduleSpecifier: parent.moduleReference.expression }; + } + else if (ts.isNamespaceImport(parent)) { + var importNode = parent.parent.parent; + return { importNode: importNode, name: name, moduleSpecifier: importNode.moduleSpecifier }; + } + } + function doChange(changes, sourceFile, info, preferences) { + changes.replaceNode(sourceFile, info.importNode, ts.makeImport(info.name, /*namedImports*/ undefined, info.moduleSpecifier, ts.getQuotePreference(sourceFile, preferences))); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixIdAddMissingTypeof = "fixAddModuleReferTypeMissingTypeof"; + var fixId = fixIdAddMissingTypeof; + var errorCodes = [ts.Diagnostics.Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var sourceFile = context.sourceFile, span = context.span; + var importType = getImportTypeNode(sourceFile, span.start); + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, importType); }); + return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Add_missing_typeof, fixId, ts.Diagnostics.Add_missing_typeof)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + return doChange(changes, context.sourceFile, getImportTypeNode(diag.file, diag.start)); + }); }, + }); + function getImportTypeNode(sourceFile, pos) { + var token = ts.getTokenAtPosition(sourceFile, pos); + ts.Debug.assert(token.kind === 92 /* ImportKeyword */); + ts.Debug.assert(token.parent.kind === 183 /* ImportType */); + return token.parent; + } + function doChange(changes, sourceFile, importType) { + var newTypeNode = ts.updateImportTypeNode(importType, importType.argument, importType.qualifier, importType.typeArguments, /* isTypeOf */ true); + changes.replaceNode(sourceFile, importType, newTypeNode); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixIdAddMissingTypeof = "fixConvertToMappedObjectType"; + var fixId = fixIdAddMissingTypeof; + var errorCodes = [ts.Diagnostics.An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var sourceFile = context.sourceFile, span = context.span; + var info = getInfo(sourceFile, span.start); + if (!info) + return undefined; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, info); }); + var name = ts.idText(info.container.name); + return [codefix.createCodeFixAction(fixId, changes, [ts.Diagnostics.Convert_0_to_mapped_object_type, name], fixId, [ts.Diagnostics.Convert_0_to_mapped_object_type, name])]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var info = getInfo(diag.file, diag.start); + if (info) + doChange(changes, diag.file, info); + }); } + }); + function getInfo(sourceFile, pos) { + var token = ts.getTokenAtPosition(sourceFile, pos); + var indexSignature = ts.cast(token.parent.parent, ts.isIndexSignatureDeclaration); + if (ts.isClassDeclaration(indexSignature.parent)) + return undefined; + var container = ts.isInterfaceDeclaration(indexSignature.parent) ? indexSignature.parent : ts.cast(indexSignature.parent.parent, ts.isTypeAliasDeclaration); + return { indexSignature: indexSignature, container: container }; + } + function createTypeAliasFromInterface(declaration, type) { + return ts.createTypeAliasDeclaration(declaration.decorators, declaration.modifiers, declaration.name, declaration.typeParameters, type); + } + function doChange(changes, sourceFile, _a) { + var indexSignature = _a.indexSignature, container = _a.container; + var members = ts.isInterfaceDeclaration(container) ? container.members : container.type.members; + var otherMembers = members.filter(function (member) { return !ts.isIndexSignatureDeclaration(member); }); + var parameter = ts.first(indexSignature.parameters); + var mappedTypeParameter = ts.createTypeParameterDeclaration(ts.cast(parameter.name, ts.isIdentifier), parameter.type); + var mappedIntersectionType = ts.createMappedTypeNode(ts.hasReadonlyModifier(indexSignature) ? ts.createModifier(133 /* ReadonlyKeyword */) : undefined, mappedTypeParameter, indexSignature.questionToken, indexSignature.type); + var intersectionType = ts.createIntersectionTypeNode(ts.getAllSuperTypeNodes(container).concat([ + mappedIntersectionType + ], (otherMembers.length ? [ts.createTypeLiteralNode(otherMembers)] : ts.emptyArray))); + changes.replaceNode(sourceFile, container, createTypeAliasFromInterface(container, intersectionType)); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var refactor; + (function (refactor) { + var refactorName = "Convert export"; + var actionNameDefaultToNamed = "Convert default export to named export"; + var actionNameNamedToDefault = "Convert named export to default export"; + refactor.registerRefactor(refactorName, { + getAvailableActions: function (context) { + var info = getInfo(context); + if (!info) + return ts.emptyArray; + var description = info.wasDefault ? ts.Diagnostics.Convert_default_export_to_named_export.message : ts.Diagnostics.Convert_named_export_to_default_export.message; + var actionName = info.wasDefault ? actionNameDefaultToNamed : actionNameNamedToDefault; + return [{ name: refactorName, description: description, actions: [{ name: actionName, description: description }] }]; + }, + getEditsForAction: function (context, actionName) { + ts.Debug.assert(actionName === actionNameDefaultToNamed || actionName === actionNameNamedToDefault); + var edits = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(context.file, context.program, ts.Debug.assertDefined(getInfo(context)), t, context.cancellationToken); }); + return { edits: edits, renameFilename: undefined, renameLocation: undefined }; + }, + }); + function getInfo(context) { + var file = context.file; + var span = ts.getRefactorContextSpan(context); + var token = ts.getTokenAtPosition(file, span.start); + var exportNode = ts.getParentNodeInSpan(token, file, span); + if (!exportNode || (!ts.isSourceFile(exportNode.parent) && !(ts.isModuleBlock(exportNode.parent) && ts.isAmbientModule(exportNode.parent.parent)))) { + return undefined; + } + var exportingModuleSymbol = ts.isSourceFile(exportNode.parent) ? exportNode.parent.symbol : exportNode.parent.parent.symbol; + var flags = ts.getModifierFlags(exportNode); + var wasDefault = !!(flags & 512 /* Default */); + // If source file already has a default export, don't offer refactor. + if (!(flags & 1 /* Export */) || !wasDefault && exportingModuleSymbol.exports.has("default" /* Default */)) { + return undefined; + } + switch (exportNode.kind) { + case 239 /* FunctionDeclaration */: + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + case 243 /* EnumDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 244 /* ModuleDeclaration */: { + var node = exportNode; + return node.name && ts.isIdentifier(node.name) ? { exportNode: node, exportName: node.name, wasDefault: wasDefault, exportingModuleSymbol: exportingModuleSymbol } : undefined; + } + case 219 /* VariableStatement */: { + var vs = exportNode; + // Must be `export const x = something;`. + if (!(vs.declarationList.flags & 2 /* Const */) || vs.declarationList.declarations.length !== 1) { + return undefined; + } + var decl = ts.first(vs.declarationList.declarations); + if (!decl.initializer) + return undefined; + ts.Debug.assert(!wasDefault); + return ts.isIdentifier(decl.name) ? { exportNode: vs, exportName: decl.name, wasDefault: wasDefault, exportingModuleSymbol: exportingModuleSymbol } : undefined; + } + default: + return undefined; + } + } + function doChange(exportingSourceFile, program, info, changes, cancellationToken) { + changeExport(exportingSourceFile, info, changes, program.getTypeChecker()); + changeImports(program, info, changes, cancellationToken); + } + function changeExport(exportingSourceFile, _a, changes, checker) { + var wasDefault = _a.wasDefault, exportNode = _a.exportNode, exportName = _a.exportName; + if (wasDefault) { + changes.delete(exportingSourceFile, ts.Debug.assertDefined(ts.findModifier(exportNode, 80 /* DefaultKeyword */))); + } + else { + var exportKeyword = ts.Debug.assertDefined(ts.findModifier(exportNode, 85 /* ExportKeyword */)); + switch (exportNode.kind) { + case 239 /* FunctionDeclaration */: + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + changes.insertNodeAfter(exportingSourceFile, exportKeyword, ts.createToken(80 /* DefaultKeyword */)); + break; + case 219 /* VariableStatement */: + // If 'x' isn't used in this file, `export const x = 0;` --> `export default 0;` + if (!ts.FindAllReferences.Core.isSymbolReferencedInFile(exportName, checker, exportingSourceFile)) { + // We checked in `getInfo` that an initializer exists. + changes.replaceNode(exportingSourceFile, exportNode, ts.createExportDefault(ts.Debug.assertDefined(ts.first(exportNode.declarationList.declarations).initializer))); + break; + } + // falls through + case 243 /* EnumDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 244 /* ModuleDeclaration */: + // `export type T = number;` -> `type T = number; export default T;` + changes.deleteModifier(exportingSourceFile, exportKeyword); + changes.insertNodeAfter(exportingSourceFile, exportNode, ts.createExportDefault(ts.createIdentifier(exportName.text))); + break; + default: + ts.Debug.assertNever(exportNode); + } + } + } + function changeImports(program, _a, changes, cancellationToken) { + var wasDefault = _a.wasDefault, exportName = _a.exportName, exportingModuleSymbol = _a.exportingModuleSymbol; + var checker = program.getTypeChecker(); + var exportSymbol = ts.Debug.assertDefined(checker.getSymbolAtLocation(exportName)); + ts.FindAllReferences.Core.eachExportReference(program.getSourceFiles(), checker, cancellationToken, exportSymbol, exportingModuleSymbol, exportName.text, wasDefault, function (ref) { + var importingSourceFile = ref.getSourceFile(); + if (wasDefault) { + changeDefaultToNamedImport(importingSourceFile, ref, changes, exportName.text); + } + else { + changeNamedToDefaultImport(importingSourceFile, ref, changes); + } + }); + } + function changeDefaultToNamedImport(importingSourceFile, ref, changes, exportName) { + var parent = ref.parent; + switch (parent.kind) { + case 189 /* PropertyAccessExpression */: + // `a.default` --> `a.foo` + changes.replaceNode(importingSourceFile, ref, ts.createIdentifier(exportName)); + break; + case 253 /* ImportSpecifier */: + case 257 /* ExportSpecifier */: { + var spec = parent; + // `default as foo` --> `foo`, `default as bar` --> `foo as bar` + changes.replaceNode(importingSourceFile, spec, makeImportSpecifier(exportName, spec.name.text)); + break; + } + case 250 /* ImportClause */: { + var clause = parent; + ts.Debug.assert(clause.name === ref); + var spec = makeImportSpecifier(exportName, ref.text); + var namedBindings = clause.namedBindings; + if (!namedBindings) { + // `import foo from "./a";` --> `import { foo } from "./a";` + changes.replaceNode(importingSourceFile, ref, ts.createNamedImports([spec])); + } + else if (namedBindings.kind === 251 /* NamespaceImport */) { + // `import foo, * as a from "./a";` --> `import * as a from ".a/"; import { foo } from "./a";` + changes.deleteRange(importingSourceFile, { pos: ref.getStart(importingSourceFile), end: namedBindings.getStart(importingSourceFile) }); + var quotePreference = ts.isStringLiteral(clause.parent.moduleSpecifier) ? ts.quotePreferenceFromString(clause.parent.moduleSpecifier, importingSourceFile) : 1 /* Double */; + var newImport = ts.makeImport(/*default*/ undefined, [makeImportSpecifier(exportName, ref.text)], clause.parent.moduleSpecifier, quotePreference); + changes.insertNodeAfter(importingSourceFile, clause.parent, newImport); + } + else { + // `import foo, { bar } from "./a"` --> `import { bar, foo } from "./a";` + changes.delete(importingSourceFile, ref); + changes.insertNodeAtEndOfList(importingSourceFile, namedBindings.elements, spec); + } + break; + } + default: + ts.Debug.failBadSyntaxKind(parent); + } + } + function changeNamedToDefaultImport(importingSourceFile, ref, changes) { + var parent = ref.parent; + switch (parent.kind) { + case 189 /* PropertyAccessExpression */: + // `a.foo` --> `a.default` + changes.replaceNode(importingSourceFile, ref, ts.createIdentifier("default")); + break; + case 253 /* ImportSpecifier */: { + // `import { foo } from "./a";` --> `import foo from "./a";` + // `import { foo as bar } from "./a";` --> `import bar from "./a";` + var defaultImport = ts.createIdentifier(parent.name.text); + if (parent.parent.elements.length === 1) { + changes.replaceNode(importingSourceFile, parent.parent, defaultImport); + } + else { + changes.delete(importingSourceFile, parent); + changes.insertNodeBefore(importingSourceFile, parent.parent, defaultImport); + } + break; + } + case 257 /* ExportSpecifier */: { + // `export { foo } from "./a";` --> `export { default as foo } from "./a";` + // `export { foo as bar } from "./a";` --> `export { default as bar } from "./a";` + // `export { foo as default } from "./a";` --> `export { default } from "./a";` + // (Because `export foo from "./a";` isn't valid syntax.) + changes.replaceNode(importingSourceFile, parent, makeExportSpecifier("default", parent.name.text)); + break; + } + default: + ts.Debug.assertNever(parent); + } + } + function makeImportSpecifier(propertyName, name) { + return ts.createImportSpecifier(propertyName === name ? undefined : ts.createIdentifier(propertyName), ts.createIdentifier(name)); + } + function makeExportSpecifier(propertyName, name) { + return ts.createExportSpecifier(propertyName === name ? undefined : ts.createIdentifier(propertyName), ts.createIdentifier(name)); + } + })(refactor = ts.refactor || (ts.refactor = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var refactor; + (function (refactor) { + var refactorName = "Convert import"; + var actionNameNamespaceToNamed = "Convert namespace import to named imports"; + var actionNameNamedToNamespace = "Convert named imports to namespace import"; + refactor.registerRefactor(refactorName, { + getAvailableActions: function (context) { + var i = getImportToConvert(context); + if (!i) + return ts.emptyArray; + var description = i.kind === 251 /* NamespaceImport */ ? ts.Diagnostics.Convert_namespace_import_to_named_imports.message : ts.Diagnostics.Convert_named_imports_to_namespace_import.message; + var actionName = i.kind === 251 /* NamespaceImport */ ? actionNameNamespaceToNamed : actionNameNamedToNamespace; + return [{ name: refactorName, description: description, actions: [{ name: actionName, description: description }] }]; + }, + getEditsForAction: function (context, actionName) { + ts.Debug.assert(actionName === actionNameNamespaceToNamed || actionName === actionNameNamedToNamespace); + var edits = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(context.file, context.program, t, ts.Debug.assertDefined(getImportToConvert(context))); }); + return { edits: edits, renameFilename: undefined, renameLocation: undefined }; + } + }); + // Can convert imports of the form `import * as m from "m";` or `import d, { x, y } from "m";`. + function getImportToConvert(context) { + var file = context.file; + var span = ts.getRefactorContextSpan(context); + var token = ts.getTokenAtPosition(file, span.start); + var importDecl = ts.getParentNodeInSpan(token, file, span); + if (!importDecl || !ts.isImportDeclaration(importDecl)) + return undefined; + var importClause = importDecl.importClause; + return importClause && importClause.namedBindings; + } + function doChange(sourceFile, program, changes, toConvert) { + var checker = program.getTypeChecker(); + if (toConvert.kind === 251 /* NamespaceImport */) { + doChangeNamespaceToNamed(sourceFile, checker, changes, toConvert, ts.getAllowSyntheticDefaultImports(program.getCompilerOptions())); + } + else { + doChangeNamedToNamespace(sourceFile, checker, changes, toConvert); + } + } + function doChangeNamespaceToNamed(sourceFile, checker, changes, toConvert, allowSyntheticDefaultImports) { + var usedAsNamespaceOrDefault = false; + var nodesToReplace = []; + var conflictingNames = ts.createMap(); + ts.FindAllReferences.Core.eachSymbolReferenceInFile(toConvert.name, checker, sourceFile, function (id) { + if (!ts.isPropertyAccessExpression(id.parent)) { + usedAsNamespaceOrDefault = true; + } + else { + var parent = ts.cast(id.parent, ts.isPropertyAccessExpression); + var exportName = parent.name.text; + if (checker.resolveName(exportName, id, 67108863 /* All */, /*excludeGlobals*/ true)) { + conflictingNames.set(exportName, true); + } + ts.Debug.assert(parent.expression === id); + nodesToReplace.push(parent); + } + }); + // We may need to change `mod.x` to `_x` to avoid a name conflict. + var exportNameToImportName = ts.createMap(); + for (var _i = 0, nodesToReplace_1 = nodesToReplace; _i < nodesToReplace_1.length; _i++) { + var propertyAccess = nodesToReplace_1[_i]; + var exportName = propertyAccess.name.text; + var importName = exportNameToImportName.get(exportName); + if (importName === undefined) { + exportNameToImportName.set(exportName, importName = conflictingNames.has(exportName) ? ts.getUniqueName(exportName, sourceFile) : exportName); + } + changes.replaceNode(sourceFile, propertyAccess, ts.createIdentifier(importName)); + } + var importSpecifiers = []; + exportNameToImportName.forEach(function (name, propertyName) { + importSpecifiers.push(ts.createImportSpecifier(name === propertyName ? undefined : ts.createIdentifier(propertyName), ts.createIdentifier(name))); + }); + var importDecl = toConvert.parent.parent; + if (usedAsNamespaceOrDefault && !allowSyntheticDefaultImports) { + // Need to leave the namespace import alone + changes.insertNodeAfter(sourceFile, importDecl, updateImport(importDecl, /*defaultImportName*/ undefined, importSpecifiers)); + } + else { + changes.replaceNode(sourceFile, importDecl, updateImport(importDecl, usedAsNamespaceOrDefault ? ts.createIdentifier(toConvert.name.text) : undefined, importSpecifiers)); + } + } + function doChangeNamedToNamespace(sourceFile, checker, changes, toConvert) { + var importDecl = toConvert.parent.parent; + var moduleSpecifier = importDecl.moduleSpecifier; + var preferredName = moduleSpecifier && ts.isStringLiteral(moduleSpecifier) ? ts.codefix.moduleSpecifierToValidIdentifier(moduleSpecifier.text, 6 /* ESNext */) : "module"; + var namespaceNameConflicts = toConvert.elements.some(function (element) { + return ts.FindAllReferences.Core.eachSymbolReferenceInFile(element.name, checker, sourceFile, function (id) { + return !!checker.resolveName(preferredName, id, 67108863 /* All */, /*excludeGlobals*/ true); + }) || false; + }); + var namespaceImportName = namespaceNameConflicts ? ts.getUniqueName(preferredName, sourceFile) : preferredName; + var neededNamedImports = []; + var _loop_21 = function (element) { + var propertyName = (element.propertyName || element.name).text; + ts.FindAllReferences.Core.eachSymbolReferenceInFile(element.name, checker, sourceFile, function (id) { + var access = ts.createPropertyAccess(ts.createIdentifier(namespaceImportName), propertyName); + if (ts.isShorthandPropertyAssignment(id.parent)) { + changes.replaceNode(sourceFile, id.parent, ts.createPropertyAssignment(id.text, access)); + } + else if (ts.isExportSpecifier(id.parent) && !id.parent.propertyName) { + if (!neededNamedImports.some(function (n) { return n.name === element.name; })) { + neededNamedImports.push(ts.createImportSpecifier(element.propertyName && ts.createIdentifier(element.propertyName.text), ts.createIdentifier(element.name.text))); + } + } + else { + changes.replaceNode(sourceFile, id, access); + } + }); + }; + for (var _i = 0, _a = toConvert.elements; _i < _a.length; _i++) { + var element = _a[_i]; + _loop_21(element); + } + changes.replaceNode(sourceFile, toConvert, ts.createNamespaceImport(ts.createIdentifier(namespaceImportName))); + if (neededNamedImports.length) { + changes.insertNodeAfter(sourceFile, toConvert.parent.parent, updateImport(importDecl, /*defaultImportName*/ undefined, neededNamedImports)); + } + } + function updateImport(old, defaultImportName, elements) { + return ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createImportClause(defaultImportName, elements && elements.length ? ts.createNamedImports(elements) : undefined), old.moduleSpecifier); + } + })(refactor = ts.refactor || (ts.refactor = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var refactor; + (function (refactor) { + var extractSymbol; + (function (extractSymbol) { + var refactorName = "Extract Symbol"; + refactor.registerRefactor(refactorName, { getAvailableActions: getAvailableActions, getEditsForAction: getEditsForAction }); + /** + * Compute the associated code actions + * Exported for tests. + */ + function getAvailableActions(context) { + var rangeToExtract = getRangeToExtract(context.file, ts.getRefactorContextSpan(context)); + var targetRange = rangeToExtract.targetRange; + if (targetRange === undefined) { + return ts.emptyArray; + } + var extractions = getPossibleExtractions(targetRange, context); + if (extractions === undefined) { + // No extractions possible + return ts.emptyArray; + } + var functionActions = []; + var usedFunctionNames = ts.createMap(); + var constantActions = []; + var usedConstantNames = ts.createMap(); + var i = 0; + for (var _i = 0, extractions_1 = extractions; _i < extractions_1.length; _i++) { + var _a = extractions_1[_i], functionExtraction = _a.functionExtraction, constantExtraction = _a.constantExtraction; + // Skip these since we don't have a way to report errors yet + if (functionExtraction.errors.length === 0) { + // Don't issue refactorings with duplicated names. + // Scopes come back in "innermost first" order, so extractions will + // preferentially go into nearer scopes + var description = functionExtraction.description; + if (!usedFunctionNames.has(description)) { + usedFunctionNames.set(description, true); + functionActions.push({ + description: description, + name: "function_scope_" + i + }); + } + } + // Skip these since we don't have a way to report errors yet + if (constantExtraction.errors.length === 0) { + // Don't issue refactorings with duplicated names. + // Scopes come back in "innermost first" order, so extractions will + // preferentially go into nearer scopes + var description = constantExtraction.description; + if (!usedConstantNames.has(description)) { + usedConstantNames.set(description, true); + constantActions.push({ + description: description, + name: "constant_scope_" + i + }); + } + } + // *do* increment i anyway because we'll look for the i-th scope + // later when actually doing the refactoring if the user requests it + i++; + } + var infos = []; + if (functionActions.length) { + infos.push({ + name: refactorName, + description: ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_function), + actions: functionActions + }); + } + if (constantActions.length) { + infos.push({ + name: refactorName, + description: ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_constant), + actions: constantActions + }); + } + return infos.length ? infos : ts.emptyArray; + } + extractSymbol.getAvailableActions = getAvailableActions; + /* Exported for tests */ + function getEditsForAction(context, actionName) { + var rangeToExtract = getRangeToExtract(context.file, ts.getRefactorContextSpan(context)); + var targetRange = rangeToExtract.targetRange; // TODO:GH#18217 + var parsedFunctionIndexMatch = /^function_scope_(\d+)$/.exec(actionName); + if (parsedFunctionIndexMatch) { + var index = +parsedFunctionIndexMatch[1]; + ts.Debug.assert(isFinite(index), "Expected to parse a finite number from the function scope index"); + return getFunctionExtractionAtIndex(targetRange, context, index); + } + var parsedConstantIndexMatch = /^constant_scope_(\d+)$/.exec(actionName); + if (parsedConstantIndexMatch) { + var index = +parsedConstantIndexMatch[1]; + ts.Debug.assert(isFinite(index), "Expected to parse a finite number from the constant scope index"); + return getConstantExtractionAtIndex(targetRange, context, index); + } + ts.Debug.fail("Unrecognized action name"); + } + extractSymbol.getEditsForAction = getEditsForAction; + // Move these into diagnostic messages if they become user-facing + var Messages; + (function (Messages) { + function createMessage(message) { + return { message: message, code: 0, category: ts.DiagnosticCategory.Message, key: message }; + } + Messages.cannotExtractRange = createMessage("Cannot extract range."); + Messages.cannotExtractImport = createMessage("Cannot extract import statement."); + Messages.cannotExtractSuper = createMessage("Cannot extract super call."); + Messages.cannotExtractEmpty = createMessage("Cannot extract empty range."); + Messages.expressionExpected = createMessage("expression expected."); + Messages.uselessConstantType = createMessage("No reason to extract constant of type."); + Messages.statementOrExpressionExpected = createMessage("Statement or expression expected."); + Messages.cannotExtractRangeContainingConditionalBreakOrContinueStatements = createMessage("Cannot extract range containing conditional break or continue statements."); + Messages.cannotExtractRangeContainingConditionalReturnStatement = createMessage("Cannot extract range containing conditional return statement."); + Messages.cannotExtractRangeContainingLabeledBreakOrContinueStatementWithTargetOutsideOfTheRange = createMessage("Cannot extract range containing labeled break or continue with target outside of the range."); + Messages.cannotExtractRangeThatContainsWritesToReferencesLocatedOutsideOfTheTargetRangeInGenerators = createMessage("Cannot extract range containing writes to references located outside of the target range in generators."); + Messages.typeWillNotBeVisibleInTheNewScope = createMessage("Type will not visible in the new scope."); + Messages.functionWillNotBeVisibleInTheNewScope = createMessage("Function will not visible in the new scope."); + Messages.cannotExtractIdentifier = createMessage("Select more than a single identifier."); + Messages.cannotExtractExportedEntity = createMessage("Cannot extract exported declaration"); + Messages.cannotWriteInExpression = createMessage("Cannot write back side-effects when extracting an expression"); + Messages.cannotExtractReadonlyPropertyInitializerOutsideConstructor = createMessage("Cannot move initialization of read-only class property outside of the constructor"); + Messages.cannotExtractAmbientBlock = createMessage("Cannot extract code from ambient contexts"); + Messages.cannotAccessVariablesFromNestedScopes = createMessage("Cannot access variables from nested scopes"); + Messages.cannotExtractToOtherFunctionLike = createMessage("Cannot extract method to a function-like scope that is not a function"); + Messages.cannotExtractToJSClass = createMessage("Cannot extract constant to a class scope in JS"); + Messages.cannotExtractToExpressionArrowFunction = createMessage("Cannot extract constant to an arrow function without a block"); + })(Messages = extractSymbol.Messages || (extractSymbol.Messages = {})); + var RangeFacts; + (function (RangeFacts) { + RangeFacts[RangeFacts["None"] = 0] = "None"; + RangeFacts[RangeFacts["HasReturn"] = 1] = "HasReturn"; + RangeFacts[RangeFacts["IsGenerator"] = 2] = "IsGenerator"; + RangeFacts[RangeFacts["IsAsyncFunction"] = 4] = "IsAsyncFunction"; + RangeFacts[RangeFacts["UsesThis"] = 8] = "UsesThis"; + /** + * The range is in a function which needs the 'static' modifier in a class + */ + RangeFacts[RangeFacts["InStaticRegion"] = 16] = "InStaticRegion"; + })(RangeFacts || (RangeFacts = {})); + /** + * getRangeToExtract takes a span inside a text file and returns either an expression or an array + * of statements representing the minimum set of nodes needed to extract the entire span. This + * process may fail, in which case a set of errors is returned instead (these are currently + * not shown to the user, but can be used by us diagnostically) + */ + // exported only for tests + function getRangeToExtract(sourceFile, span) { + var length = span.length; + if (length === 0) { + return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractEmpty)] }; + } + // Walk up starting from the the start position until we find a non-SourceFile node that subsumes the selected span. + // This may fail (e.g. you select two statements in the root of a source file) + var start = ts.getParentNodeInSpan(ts.getTokenAtPosition(sourceFile, span.start), sourceFile, span); + // Do the same for the ending position + var end = ts.getParentNodeInSpan(ts.findTokenOnLeftOfPosition(sourceFile, ts.textSpanEnd(span)), sourceFile, span); + var declarations = []; + // We'll modify these flags as we walk the tree to collect data + // about what things need to be done as part of the extraction. + var rangeFacts = RangeFacts.None; + if (!start || !end) { + // cannot find either start or end node + return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractRange)] }; + } + if (start.parent !== end.parent) { + // start and end nodes belong to different subtrees + return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractRange)] }; + } + if (start !== end) { + // start and end should be statements and parent should be either block or a source file + if (!isBlockLike(start.parent)) { + return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractRange)] }; + } + var statements = []; + var start2 = start; // TODO: GH#18217 Need to alias `start` to get this to compile. See https://github.com/Microsoft/TypeScript/issues/19955#issuecomment-344118248 + for (var _i = 0, _a = start2.parent.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + if (statement === start || statements.length) { + var errors_1 = checkNode(statement); + if (errors_1) { + return { errors: errors_1 }; + } + statements.push(statement); + } + if (statement === end) { + break; + } + } + if (!statements.length) { + // https://github.com/Microsoft/TypeScript/issues/20559 + // Ranges like [|case 1: break;|] will fail to populate `statements` because + // they will never find `start` in `start.parent.statements`. + // Consider: We could support ranges like [|case 1:|] by refining them to just + // the expression. + return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractRange)] }; + } + return { targetRange: { range: statements, facts: rangeFacts, declarations: declarations } }; + } + if (ts.isReturnStatement(start) && !start.expression) { + // Makes no sense to extract an expression-less return statement. + return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractRange)] }; + } + // We have a single node (start) + var node = refineNode(start); + var errors = checkRootNode(node) || checkNode(node); + if (errors) { + return { errors: errors }; + } + return { targetRange: { range: getStatementOrExpressionRange(node), facts: rangeFacts, declarations: declarations } }; // TODO: GH#18217 + /** + * Attempt to refine the extraction node (generally, by shrinking it) to produce better results. + * @param node The unrefined extraction node. + */ + function refineNode(node) { + if (ts.isReturnStatement(node)) { + if (node.expression) { + return node.expression; + } + } + else if (ts.isVariableStatement(node)) { + var numInitializers = 0; + var lastInitializer = void 0; + for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (declaration.initializer) { + numInitializers++; + lastInitializer = declaration.initializer; + } + } + if (numInitializers === 1) { + return lastInitializer; + } + // No special handling if there are multiple initializers. + } + else if (ts.isVariableDeclaration(node)) { + if (node.initializer) { + return node.initializer; + } + } + return node; + } + function checkRootNode(node) { + if (ts.isIdentifier(ts.isExpressionStatement(node) ? node.expression : node)) { + return [ts.createDiagnosticForNode(node, Messages.cannotExtractIdentifier)]; + } + return undefined; + } + function checkForStaticContext(nodeToCheck, containingClass) { + var current = nodeToCheck; + while (current !== containingClass) { + if (current.kind === 154 /* PropertyDeclaration */) { + if (ts.hasModifier(current, 32 /* Static */)) { + rangeFacts |= RangeFacts.InStaticRegion; + } + break; + } + else if (current.kind === 151 /* Parameter */) { + var ctorOrMethod = ts.getContainingFunction(current); + if (ctorOrMethod.kind === 157 /* Constructor */) { + rangeFacts |= RangeFacts.InStaticRegion; + } + break; + } + else if (current.kind === 156 /* MethodDeclaration */) { + if (ts.hasModifier(current, 32 /* Static */)) { + rangeFacts |= RangeFacts.InStaticRegion; + } + } + current = current.parent; + } + } + // Verifies whether we can actually extract this node or not. + function checkNode(nodeToCheck) { + var PermittedJumps; + (function (PermittedJumps) { + PermittedJumps[PermittedJumps["None"] = 0] = "None"; + PermittedJumps[PermittedJumps["Break"] = 1] = "Break"; + PermittedJumps[PermittedJumps["Continue"] = 2] = "Continue"; + PermittedJumps[PermittedJumps["Return"] = 4] = "Return"; + })(PermittedJumps || (PermittedJumps = {})); + // We believe it's true because the node is from the (unmodified) tree. + ts.Debug.assert(nodeToCheck.pos <= nodeToCheck.end, "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809"); + // For understanding how skipTrivia functioned: + ts.Debug.assert(!ts.positionIsSynthesized(nodeToCheck.pos), "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809"); + if (!ts.isStatement(nodeToCheck) && !(ts.isExpressionNode(nodeToCheck) && isExtractableExpression(nodeToCheck))) { + return [ts.createDiagnosticForNode(nodeToCheck, Messages.statementOrExpressionExpected)]; + } + if (nodeToCheck.flags & 4194304 /* Ambient */) { + return [ts.createDiagnosticForNode(nodeToCheck, Messages.cannotExtractAmbientBlock)]; + } + // If we're in a class, see whether we're in a static region (static property initializer, static method, class constructor parameter default) + var containingClass = ts.getContainingClass(nodeToCheck); + if (containingClass) { + checkForStaticContext(nodeToCheck, containingClass); + } + var errors; + var permittedJumps = 4 /* Return */; + var seenLabels; + visit(nodeToCheck); + return errors; + function visit(node) { + if (errors) { + // already found an error - can stop now + return true; + } + if (ts.isDeclaration(node)) { + var declaringNode = (node.kind === 237 /* VariableDeclaration */) ? node.parent.parent : node; + if (ts.hasModifier(declaringNode, 1 /* Export */)) { + // TODO: GH#18217 Silly to use `errors ||` since it's definitely not defined (see top of `visit`) + // Also, if we're only pushing one error, just use `let error: Diagnostic | undefined`! + // Also TODO: GH#19956 + (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractExportedEntity)); + return true; + } + declarations.push(node.symbol); + } + // Some things can't be extracted in certain situations + switch (node.kind) { + case 249 /* ImportDeclaration */: + (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractImport)); + return true; + case 98 /* SuperKeyword */: + // For a super *constructor call*, we have to be extracting the entire class, + // but a super *method call* simply implies a 'this' reference + if (node.parent.kind === 191 /* CallExpression */) { + // Super constructor call + var containingClass_1 = ts.getContainingClass(node); // TODO:GH#18217 + if (containingClass_1.pos < span.start || containingClass_1.end >= (span.start + span.length)) { + (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractSuper)); + return true; + } + } + else { + rangeFacts |= RangeFacts.UsesThis; + } + break; + } + if (ts.isFunctionLikeDeclaration(node) || ts.isClassLike(node)) { + switch (node.kind) { + case 239 /* FunctionDeclaration */: + case 240 /* ClassDeclaration */: + if (ts.isSourceFile(node.parent) && node.parent.externalModuleIndicator === undefined) { + // You cannot extract global declarations + (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.functionWillNotBeVisibleInTheNewScope)); + } + break; + } + // do not dive into functions or classes + return false; + } + var savedPermittedJumps = permittedJumps; + switch (node.kind) { + case 222 /* IfStatement */: + permittedJumps = 0 /* None */; + break; + case 235 /* TryStatement */: + // forbid all jumps inside try blocks + permittedJumps = 0 /* None */; + break; + case 218 /* Block */: + if (node.parent && node.parent.kind === 235 /* TryStatement */ && node.parent.finallyBlock === node) { + // allow unconditional returns from finally blocks + permittedJumps = 4 /* Return */; + } + break; + case 271 /* CaseClause */: + // allow unlabeled break inside case clauses + permittedJumps |= 1 /* Break */; + break; + default: + if (ts.isIterationStatement(node, /*lookInLabeledStatements*/ false)) { + // allow unlabeled break/continue inside loops + permittedJumps |= 1 /* Break */ | 2 /* Continue */; + } + break; + } + switch (node.kind) { + case 178 /* ThisType */: + case 100 /* ThisKeyword */: + rangeFacts |= RangeFacts.UsesThis; + break; + case 233 /* LabeledStatement */: + { + var label = node.label; + (seenLabels || (seenLabels = [])).push(label.escapedText); + ts.forEachChild(node, visit); + seenLabels.pop(); + break; + } + case 229 /* BreakStatement */: + case 228 /* ContinueStatement */: + { + var label = node.label; + if (label) { + if (!ts.contains(seenLabels, label.escapedText)) { + // attempts to jump to label that is not in range to be extracted + (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractRangeContainingLabeledBreakOrContinueStatementWithTargetOutsideOfTheRange)); + } + } + else { + if (!(permittedJumps & (node.kind === 229 /* BreakStatement */ ? 1 /* Break */ : 2 /* Continue */))) { + // attempt to break or continue in a forbidden context + (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractRangeContainingConditionalBreakOrContinueStatements)); + } + } + break; + } + case 201 /* AwaitExpression */: + rangeFacts |= RangeFacts.IsAsyncFunction; + break; + case 207 /* YieldExpression */: + rangeFacts |= RangeFacts.IsGenerator; + break; + case 230 /* ReturnStatement */: + if (permittedJumps & 4 /* Return */) { + rangeFacts |= RangeFacts.HasReturn; + } + else { + (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractRangeContainingConditionalReturnStatement)); + } + break; + default: + ts.forEachChild(node, visit); + break; + } + permittedJumps = savedPermittedJumps; + } + } + } + extractSymbol.getRangeToExtract = getRangeToExtract; + function getStatementOrExpressionRange(node) { + if (ts.isStatement(node)) { + return [node]; + } + else if (ts.isExpressionNode(node)) { + // If our selection is the expression in an ExpressionStatement, expand + // the selection to include the enclosing Statement (this stops us + // from trying to care about the return value of the extracted function + // and eliminates double semicolon insertion in certain scenarios) + return ts.isExpressionStatement(node.parent) ? [node.parent] : node; + } + return undefined; + } + function isScope(node) { + return ts.isFunctionLikeDeclaration(node) || ts.isSourceFile(node) || ts.isModuleBlock(node) || ts.isClassLike(node); + } + /** + * Computes possible places we could extract the function into. For example, + * you may be able to extract into a class method *or* local closure *or* namespace function, + * depending on what's in the extracted body. + */ + function collectEnclosingScopes(range) { + var current = isReadonlyArray(range.range) ? ts.first(range.range) : range.range; + if (range.facts & RangeFacts.UsesThis) { + // if range uses this as keyword or as type inside the class then it can only be extracted to a method of the containing class + var containingClass = ts.getContainingClass(current); + if (containingClass) { + var containingFunction = ts.findAncestor(current, ts.isFunctionLikeDeclaration); + return containingFunction + ? [containingFunction, containingClass] + : [containingClass]; + } + } + var scopes = []; + while (true) { + current = current.parent; + // A function parameter's initializer is actually in the outer scope, not the function declaration + if (current.kind === 151 /* Parameter */) { + // Skip all the way to the outer scope of the function that declared this parameter + current = ts.findAncestor(current, function (parent) { return ts.isFunctionLikeDeclaration(parent); }).parent; + } + // We want to find the nearest parent where we can place an "equivalent" sibling to the node we're extracting out of. + // Walk up to the closest parent of a place where we can logically put a sibling: + // * Function declaration + // * Class declaration or expression + // * Module/namespace or source file + if (isScope(current)) { + scopes.push(current); + if (current.kind === 279 /* SourceFile */) { + return scopes; + } + } + } + } + function getFunctionExtractionAtIndex(targetRange, context, requestedChangesIndex) { + var _a = getPossibleExtractionsWorker(targetRange, context), scopes = _a.scopes, _b = _a.readsAndWrites, target = _b.target, usagesPerScope = _b.usagesPerScope, functionErrorsPerScope = _b.functionErrorsPerScope, exposedVariableDeclarations = _b.exposedVariableDeclarations; + ts.Debug.assert(!functionErrorsPerScope[requestedChangesIndex].length, "The extraction went missing? How?"); + context.cancellationToken.throwIfCancellationRequested(); // TODO: GH#18217 + return extractFunctionInScope(target, scopes[requestedChangesIndex], usagesPerScope[requestedChangesIndex], exposedVariableDeclarations, targetRange, context); + } + function getConstantExtractionAtIndex(targetRange, context, requestedChangesIndex) { + var _a = getPossibleExtractionsWorker(targetRange, context), scopes = _a.scopes, _b = _a.readsAndWrites, target = _b.target, usagesPerScope = _b.usagesPerScope, constantErrorsPerScope = _b.constantErrorsPerScope, exposedVariableDeclarations = _b.exposedVariableDeclarations; + ts.Debug.assert(!constantErrorsPerScope[requestedChangesIndex].length, "The extraction went missing? How?"); + ts.Debug.assert(exposedVariableDeclarations.length === 0, "Extract constant accepted a range containing a variable declaration?"); + context.cancellationToken.throwIfCancellationRequested(); + var expression = ts.isExpression(target) + ? target + : target.statements[0].expression; + return extractConstantInScope(expression, scopes[requestedChangesIndex], usagesPerScope[requestedChangesIndex], targetRange.facts, context); + } + /** + * Given a piece of text to extract ('targetRange'), computes a list of possible extractions. + * Each returned ExtractResultForScope corresponds to a possible target scope and is either a set of changes + * or an error explaining why we can't extract into that scope. + */ + function getPossibleExtractions(targetRange, context) { + var _a = getPossibleExtractionsWorker(targetRange, context), scopes = _a.scopes, _b = _a.readsAndWrites, functionErrorsPerScope = _b.functionErrorsPerScope, constantErrorsPerScope = _b.constantErrorsPerScope; + // Need the inner type annotation to avoid https://github.com/Microsoft/TypeScript/issues/7547 + var extractions = scopes.map(function (scope, i) { + var functionDescriptionPart = getDescriptionForFunctionInScope(scope); + var constantDescriptionPart = getDescriptionForConstantInScope(scope); + var scopeDescription = ts.isFunctionLikeDeclaration(scope) + ? getDescriptionForFunctionLikeDeclaration(scope) + : ts.isClassLike(scope) + ? getDescriptionForClassLikeDeclaration(scope) + : getDescriptionForModuleLikeDeclaration(scope); + var functionDescription; + var constantDescription; + if (scopeDescription === 1 /* Global */) { + functionDescription = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_to_0_in_1_scope), [functionDescriptionPart, "global"]); + constantDescription = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_to_0_in_1_scope), [constantDescriptionPart, "global"]); + } + else if (scopeDescription === 0 /* Module */) { + functionDescription = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_to_0_in_1_scope), [functionDescriptionPart, "module"]); + constantDescription = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_to_0_in_1_scope), [constantDescriptionPart, "module"]); + } + else { + functionDescription = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_to_0_in_1), [functionDescriptionPart, scopeDescription]); + constantDescription = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_to_0_in_1), [constantDescriptionPart, scopeDescription]); + } + // Customize the phrasing for the innermost scope to increase clarity. + if (i === 0 && !ts.isClassLike(scope)) { + constantDescription = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_to_0_in_enclosing_scope), [constantDescriptionPart]); + } + return { + functionExtraction: { + description: functionDescription, + errors: functionErrorsPerScope[i], + }, + constantExtraction: { + description: constantDescription, + errors: constantErrorsPerScope[i], + }, + }; + }); + return extractions; + } + function getPossibleExtractionsWorker(targetRange, context) { + var sourceFile = context.file; + var scopes = collectEnclosingScopes(targetRange); + var enclosingTextRange = getEnclosingTextRange(targetRange, sourceFile); + var readsAndWrites = collectReadsAndWrites(targetRange, scopes, enclosingTextRange, sourceFile, context.program.getTypeChecker(), context.cancellationToken); + return { scopes: scopes, readsAndWrites: readsAndWrites }; + } + function getDescriptionForFunctionInScope(scope) { + return ts.isFunctionLikeDeclaration(scope) + ? "inner function" + : ts.isClassLike(scope) + ? "method" + : "function"; + } + function getDescriptionForConstantInScope(scope) { + return ts.isClassLike(scope) + ? "readonly field" + : "constant"; + } + function getDescriptionForFunctionLikeDeclaration(scope) { + switch (scope.kind) { + case 157 /* Constructor */: + return "constructor"; + case 196 /* FunctionExpression */: + case 239 /* FunctionDeclaration */: + return scope.name + ? "function '" + scope.name.text + "'" + : "anonymous function"; + case 197 /* ArrowFunction */: + return "arrow function"; + case 156 /* MethodDeclaration */: + return "method '" + scope.name.getText() + "'"; + case 158 /* GetAccessor */: + return "'get " + scope.name.getText() + "'"; + case 159 /* SetAccessor */: + return "'set " + scope.name.getText() + "'"; + default: + throw ts.Debug.assertNever(scope); + } + } + function getDescriptionForClassLikeDeclaration(scope) { + return scope.kind === 240 /* ClassDeclaration */ + ? scope.name ? "class '" + scope.name.text + "'" : "anonymous class declaration" + : scope.name ? "class expression '" + scope.name.text + "'" : "anonymous class expression"; + } + function getDescriptionForModuleLikeDeclaration(scope) { + return scope.kind === 245 /* ModuleBlock */ + ? "namespace '" + scope.parent.name.getText() + "'" + : scope.externalModuleIndicator ? 0 /* Module */ : 1 /* Global */; + } + var SpecialScope; + (function (SpecialScope) { + SpecialScope[SpecialScope["Module"] = 0] = "Module"; + SpecialScope[SpecialScope["Global"] = 1] = "Global"; + })(SpecialScope || (SpecialScope = {})); + /** + * Result of 'extractRange' operation for a specific scope. + * Stores either a list of changes that should be applied to extract a range or a list of errors + */ + function extractFunctionInScope(node, scope, _a, exposedVariableDeclarations, range, context) { + var usagesInScope = _a.usages, typeParameterUsages = _a.typeParameterUsages, substitutions = _a.substitutions; + var checker = context.program.getTypeChecker(); + // Make a unique name for the extracted function + var file = scope.getSourceFile(); + var functionNameText = ts.getUniqueName(ts.isClassLike(scope) ? "newMethod" : "newFunction", file); + var isJS = ts.isInJSFile(scope); + var functionName = ts.createIdentifier(functionNameText); + var returnType; + var parameters = []; + var callArguments = []; + var writes; + usagesInScope.forEach(function (usage, name) { + var typeNode; + if (!isJS) { + var type = checker.getTypeOfSymbolAtLocation(usage.symbol, usage.node); + // Widen the type so we don't emit nonsense annotations like "function fn(x: 3) {" + type = checker.getBaseTypeOfLiteralType(type); + typeNode = checker.typeToTypeNode(type, scope, 1 /* NoTruncation */); + } + var paramDecl = ts.createParameter( + /*decorators*/ undefined, + /*modifiers*/ undefined, + /*dotDotDotToken*/ undefined, + /*name*/ name, + /*questionToken*/ undefined, typeNode); + parameters.push(paramDecl); + if (usage.usage === 2 /* Write */) { + (writes || (writes = [])).push(usage); + } + callArguments.push(ts.createIdentifier(name)); + }); + var typeParametersAndDeclarations = ts.arrayFrom(typeParameterUsages.values()).map(function (type) { return ({ type: type, declaration: getFirstDeclaration(type) }); }); + var sortedTypeParametersAndDeclarations = typeParametersAndDeclarations.sort(compareTypesByDeclarationOrder); + var typeParameters = sortedTypeParametersAndDeclarations.length === 0 + ? undefined + : sortedTypeParametersAndDeclarations.map(function (t) { return t.declaration; }); + // Strictly speaking, we should check whether each name actually binds to the appropriate type + // parameter. In cases of shadowing, they may not. + var callTypeArguments = typeParameters !== undefined + ? typeParameters.map(function (decl) { return ts.createTypeReferenceNode(decl.name, /*typeArguments*/ undefined); }) + : undefined; + // Provide explicit return types for contextually-typed functions + // to avoid problems when there are literal types present + if (ts.isExpression(node) && !isJS) { + var contextualType = checker.getContextualType(node); + returnType = checker.typeToTypeNode(contextualType, scope, 1 /* NoTruncation */); // TODO: GH#18217 + } + var _b = transformFunctionBody(node, exposedVariableDeclarations, writes, substitutions, !!(range.facts & RangeFacts.HasReturn)), body = _b.body, returnValueProperty = _b.returnValueProperty; + ts.suppressLeadingAndTrailingTrivia(body); + var newFunction; + if (ts.isClassLike(scope)) { + // always create private method in TypeScript files + var modifiers = isJS ? [] : [ts.createToken(113 /* PrivateKeyword */)]; + if (range.facts & RangeFacts.InStaticRegion) { + modifiers.push(ts.createToken(116 /* StaticKeyword */)); + } + if (range.facts & RangeFacts.IsAsyncFunction) { + modifiers.push(ts.createToken(121 /* AsyncKeyword */)); + } + newFunction = ts.createMethod( + /*decorators*/ undefined, modifiers.length ? modifiers : undefined, range.facts & RangeFacts.IsGenerator ? ts.createToken(40 /* AsteriskToken */) : undefined, functionName, + /*questionToken*/ undefined, typeParameters, parameters, returnType, body); + } + else { + newFunction = ts.createFunctionDeclaration( + /*decorators*/ undefined, range.facts & RangeFacts.IsAsyncFunction ? [ts.createToken(121 /* AsyncKeyword */)] : undefined, range.facts & RangeFacts.IsGenerator ? ts.createToken(40 /* AsteriskToken */) : undefined, functionName, typeParameters, parameters, returnType, body); + } + var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); + var minInsertionPos = (isReadonlyArray(range.range) ? ts.last(range.range) : range.range).end; + var nodeToInsertBefore = getNodeToInsertFunctionBefore(minInsertionPos, scope); + if (nodeToInsertBefore) { + changeTracker.insertNodeBefore(context.file, nodeToInsertBefore, newFunction, /*blankLineBetween*/ true); + } + else { + changeTracker.insertNodeAtEndOfScope(context.file, scope, newFunction); + } + var newNodes = []; + // replace range with function call + var called = getCalledExpression(scope, range, functionNameText); + var call = ts.createCall(called, callTypeArguments, // Note that no attempt is made to take advantage of type argument inference + callArguments); + if (range.facts & RangeFacts.IsGenerator) { + call = ts.createYield(ts.createToken(40 /* AsteriskToken */), call); + } + if (range.facts & RangeFacts.IsAsyncFunction) { + call = ts.createAwait(call); + } + if (exposedVariableDeclarations.length && !writes) { + // No need to mix declarations and writes. + // How could any variables be exposed if there's a return statement? + ts.Debug.assert(!returnValueProperty); + ts.Debug.assert(!(range.facts & RangeFacts.HasReturn)); + if (exposedVariableDeclarations.length === 1) { + // Declaring exactly one variable: let x = newFunction(); + var variableDeclaration = exposedVariableDeclarations[0]; + newNodes.push(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(ts.getSynthesizedDeepClone(variableDeclaration.name), /*type*/ ts.getSynthesizedDeepClone(variableDeclaration.type), /*initializer*/ call)], // TODO (acasey): test binding patterns + variableDeclaration.parent.flags))); + } + else { + // Declaring multiple variables / return properties: + // let {x, y} = newFunction(); + var bindingElements = []; + var typeElements = []; + var commonNodeFlags = exposedVariableDeclarations[0].parent.flags; + var sawExplicitType = false; + for (var _i = 0, exposedVariableDeclarations_1 = exposedVariableDeclarations; _i < exposedVariableDeclarations_1.length; _i++) { + var variableDeclaration = exposedVariableDeclarations_1[_i]; + bindingElements.push(ts.createBindingElement( + /*dotDotDotToken*/ undefined, + /*propertyName*/ undefined, + /*name*/ ts.getSynthesizedDeepClone(variableDeclaration.name))); + // Being returned through an object literal will have widened the type. + var variableType = checker.typeToTypeNode(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(variableDeclaration)), scope, 1 /* NoTruncation */); + typeElements.push(ts.createPropertySignature( + /*modifiers*/ undefined, + /*name*/ variableDeclaration.symbol.name, + /*questionToken*/ undefined, + /*type*/ variableType, + /*initializer*/ undefined)); + sawExplicitType = sawExplicitType || variableDeclaration.type !== undefined; + commonNodeFlags = commonNodeFlags & variableDeclaration.parent.flags; + } + var typeLiteral = sawExplicitType ? ts.createTypeLiteralNode(typeElements) : undefined; + if (typeLiteral) { + ts.setEmitFlags(typeLiteral, 1 /* SingleLine */); + } + newNodes.push(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(ts.createObjectBindingPattern(bindingElements), + /*type*/ typeLiteral, + /*initializer*/ call)], commonNodeFlags))); + } + } + else if (exposedVariableDeclarations.length || writes) { + if (exposedVariableDeclarations.length) { + // CONSIDER: we're going to create one statement per variable, but we could actually preserve their original grouping. + for (var _c = 0, exposedVariableDeclarations_2 = exposedVariableDeclarations; _c < exposedVariableDeclarations_2.length; _c++) { + var variableDeclaration = exposedVariableDeclarations_2[_c]; + var flags = variableDeclaration.parent.flags; + if (flags & 2 /* Const */) { + flags = (flags & ~2 /* Const */) | 1 /* Let */; + } + newNodes.push(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(variableDeclaration.symbol.name, getTypeDeepCloneUnionUndefined(variableDeclaration.type))], flags))); + } + } + if (returnValueProperty) { + // has both writes and return, need to create variable declaration to hold return value; + newNodes.push(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(returnValueProperty, getTypeDeepCloneUnionUndefined(returnType))], 1 /* Let */))); + } + var assignments = getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes); + if (returnValueProperty) { + assignments.unshift(ts.createShorthandPropertyAssignment(returnValueProperty)); + } + // propagate writes back + if (assignments.length === 1) { + // We would only have introduced a return value property if there had been + // other assignments to make. + ts.Debug.assert(!returnValueProperty); + newNodes.push(ts.createStatement(ts.createAssignment(assignments[0].name, call))); + if (range.facts & RangeFacts.HasReturn) { + newNodes.push(ts.createReturn()); + } + } + else { + // emit e.g. + // { a, b, __return } = newFunction(a, b); + // return __return; + newNodes.push(ts.createStatement(ts.createAssignment(ts.createObjectLiteral(assignments), call))); + if (returnValueProperty) { + newNodes.push(ts.createReturn(ts.createIdentifier(returnValueProperty))); + } + } + } + else { + if (range.facts & RangeFacts.HasReturn) { + newNodes.push(ts.createReturn(call)); + } + else if (isReadonlyArray(range.range)) { + newNodes.push(ts.createStatement(call)); + } + else { + newNodes.push(call); + } + } + if (isReadonlyArray(range.range)) { + changeTracker.replaceNodeRangeWithNodes(context.file, ts.first(range.range), ts.last(range.range), newNodes); + } + else { + changeTracker.replaceNodeWithNodes(context.file, range.range, newNodes); + } + var edits = changeTracker.getChanges(); + var renameRange = isReadonlyArray(range.range) ? ts.first(range.range) : range.range; + var renameFilename = renameRange.getSourceFile().fileName; + var renameLocation = ts.getRenameLocation(edits, renameFilename, functionNameText, /*isDeclaredBeforeUse*/ false); + return { renameFilename: renameFilename, renameLocation: renameLocation, edits: edits }; + function getTypeDeepCloneUnionUndefined(typeNode) { + if (typeNode === undefined) { + return undefined; + } + var clone = ts.getSynthesizedDeepClone(typeNode); + var withoutParens = clone; + while (ts.isParenthesizedTypeNode(withoutParens)) { + withoutParens = withoutParens.type; + } + return ts.isUnionTypeNode(withoutParens) && ts.find(withoutParens.types, function (t) { return t.kind === 141 /* UndefinedKeyword */; }) + ? clone + : ts.createUnionTypeNode([clone, ts.createKeywordTypeNode(141 /* UndefinedKeyword */)]); + } + } + /** + * Result of 'extractRange' operation for a specific scope. + * Stores either a list of changes that should be applied to extract a range or a list of errors + */ + function extractConstantInScope(node, scope, _a, rangeFacts, context) { + var substitutions = _a.substitutions; + var checker = context.program.getTypeChecker(); + // Make a unique name for the extracted variable + var file = scope.getSourceFile(); + var localNameText = ts.getUniqueName(ts.isClassLike(scope) ? "newProperty" : "newLocal", file); + var isJS = ts.isInJSFile(scope); + var variableType = isJS || !checker.isContextSensitive(node) + ? undefined + : checker.typeToTypeNode(checker.getContextualType(node), scope, 1 /* NoTruncation */); // TODO: GH#18217 + var initializer = transformConstantInitializer(node, substitutions); + ts.suppressLeadingAndTrailingTrivia(initializer); + var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); + if (ts.isClassLike(scope)) { + ts.Debug.assert(!isJS); // See CannotExtractToJSClass + var modifiers = []; + modifiers.push(ts.createToken(113 /* PrivateKeyword */)); + if (rangeFacts & RangeFacts.InStaticRegion) { + modifiers.push(ts.createToken(116 /* StaticKeyword */)); + } + modifiers.push(ts.createToken(133 /* ReadonlyKeyword */)); + var newVariable = ts.createProperty( + /*decorators*/ undefined, modifiers, localNameText, + /*questionToken*/ undefined, variableType, initializer); + var localReference = ts.createPropertyAccess(rangeFacts & RangeFacts.InStaticRegion + ? ts.createIdentifier(scope.name.getText()) // TODO: GH#18217 + : ts.createThis(), ts.createIdentifier(localNameText)); + // Declare + var maxInsertionPos = node.pos; + var nodeToInsertBefore = getNodeToInsertPropertyBefore(maxInsertionPos, scope); + changeTracker.insertNodeBefore(context.file, nodeToInsertBefore, newVariable, /*blankLineBetween*/ true); + // Consume + changeTracker.replaceNode(context.file, node, localReference); + } + else { + var newVariableDeclaration = ts.createVariableDeclaration(localNameText, variableType, initializer); + // If the node is part of an initializer in a list of variable declarations, insert a new + // variable declaration into the list (in case it depends on earlier ones). + // CONSIDER: If the declaration list isn't const, we might want to split it into multiple + // lists so that the newly extracted one can be const. + var oldVariableDeclaration = getContainingVariableDeclarationIfInList(node, scope); + if (oldVariableDeclaration) { + // Declare + // CONSIDER: could detect that each is on a separate line (See `extractConstant_VariableList_MultipleLines` in `extractConstants.ts`) + changeTracker.insertNodeBefore(context.file, oldVariableDeclaration, newVariableDeclaration); + // Consume + var localReference = ts.createIdentifier(localNameText); + changeTracker.replaceNode(context.file, node, localReference); + } + else if (node.parent.kind === 221 /* ExpressionStatement */ && scope === ts.findAncestor(node, isScope)) { + // If the parent is an expression statement and the target scope is the immediately enclosing one, + // replace the statement with the declaration. + var newVariableStatement = ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([newVariableDeclaration], 2 /* Const */)); + changeTracker.replaceNode(context.file, node.parent, newVariableStatement); + } + else { + var newVariableStatement = ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([newVariableDeclaration], 2 /* Const */)); + // Declare + var nodeToInsertBefore = getNodeToInsertConstantBefore(node, scope); + if (nodeToInsertBefore.pos === 0) { + changeTracker.insertNodeAtTopOfFile(context.file, newVariableStatement, /*blankLineBetween*/ false); + } + else { + changeTracker.insertNodeBefore(context.file, nodeToInsertBefore, newVariableStatement, /*blankLineBetween*/ false); + } + // Consume + if (node.parent.kind === 221 /* ExpressionStatement */) { + // If the parent is an expression statement, delete it. + changeTracker.delete(context.file, node.parent); + } + else { + var localReference = ts.createIdentifier(localNameText); + changeTracker.replaceNode(context.file, node, localReference); + } + } + } + var edits = changeTracker.getChanges(); + var renameFilename = node.getSourceFile().fileName; + var renameLocation = ts.getRenameLocation(edits, renameFilename, localNameText, /*isDeclaredBeforeUse*/ true); + return { renameFilename: renameFilename, renameLocation: renameLocation, edits: edits }; + } + function getContainingVariableDeclarationIfInList(node, scope) { + var prevNode; + while (node !== undefined && node !== scope) { + if (ts.isVariableDeclaration(node) && + node.initializer === prevNode && + ts.isVariableDeclarationList(node.parent) && + node.parent.declarations.length > 1) { + return node; + } + prevNode = node; + node = node.parent; + } + } + function getFirstDeclaration(type) { + var firstDeclaration; + var symbol = type.symbol; + if (symbol && symbol.declarations) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (firstDeclaration === undefined || declaration.pos < firstDeclaration.pos) { + firstDeclaration = declaration; + } + } + } + return firstDeclaration; + } + function compareTypesByDeclarationOrder(_a, _b) { + var type1 = _a.type, declaration1 = _a.declaration; + var type2 = _b.type, declaration2 = _b.declaration; + return ts.compareProperties(declaration1, declaration2, "pos", ts.compareValues) + || ts.compareStringsCaseSensitive(type1.symbol ? type1.symbol.getName() : "", type2.symbol ? type2.symbol.getName() : "") + || ts.compareValues(type1.id, type2.id); + } + function getCalledExpression(scope, range, functionNameText) { + var functionReference = ts.createIdentifier(functionNameText); + if (ts.isClassLike(scope)) { + var lhs = range.facts & RangeFacts.InStaticRegion ? ts.createIdentifier(scope.name.text) : ts.createThis(); // TODO: GH#18217 + return ts.createPropertyAccess(lhs, functionReference); + } + else { + return functionReference; + } + } + function transformFunctionBody(body, exposedVariableDeclarations, writes, substitutions, hasReturn) { + var hasWritesOrVariableDeclarations = writes !== undefined || exposedVariableDeclarations.length > 0; + if (ts.isBlock(body) && !hasWritesOrVariableDeclarations && substitutions.size === 0) { + // already block, no declarations or writes to propagate back, no substitutions - can use node as is + return { body: ts.createBlock(body.statements, /*multLine*/ true), returnValueProperty: undefined }; + } + var returnValueProperty; + var ignoreReturns = false; + var statements = ts.createNodeArray(ts.isBlock(body) ? body.statements.slice(0) : [ts.isStatement(body) ? body : ts.createReturn(body)]); + // rewrite body if either there are writes that should be propagated back via return statements or there are substitutions + if (hasWritesOrVariableDeclarations || substitutions.size) { + var rewrittenStatements = ts.visitNodes(statements, visitor).slice(); + if (hasWritesOrVariableDeclarations && !hasReturn && ts.isStatement(body)) { + // add return at the end to propagate writes back in case if control flow falls out of the function body + // it is ok to know that range has at least one return since it we only allow unconditional returns + var assignments = getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes); + if (assignments.length === 1) { + rewrittenStatements.push(ts.createReturn(assignments[0].name)); + } + else { + rewrittenStatements.push(ts.createReturn(ts.createObjectLiteral(assignments))); + } + } + return { body: ts.createBlock(rewrittenStatements, /*multiLine*/ true), returnValueProperty: returnValueProperty }; + } + else { + return { body: ts.createBlock(statements, /*multiLine*/ true), returnValueProperty: undefined }; + } + function visitor(node) { + if (!ignoreReturns && node.kind === 230 /* ReturnStatement */ && hasWritesOrVariableDeclarations) { + var assignments = getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes); + if (node.expression) { + if (!returnValueProperty) { + returnValueProperty = "__return"; + } + assignments.unshift(ts.createPropertyAssignment(returnValueProperty, ts.visitNode(node.expression, visitor))); + } + if (assignments.length === 1) { + return ts.createReturn(assignments[0].name); + } + else { + return ts.createReturn(ts.createObjectLiteral(assignments)); + } + } + else { + var oldIgnoreReturns = ignoreReturns; + ignoreReturns = ignoreReturns || ts.isFunctionLikeDeclaration(node) || ts.isClassLike(node); + var substitution = substitutions.get(ts.getNodeId(node).toString()); + var result = substitution ? ts.getSynthesizedDeepClone(substitution) : ts.visitEachChild(node, visitor, ts.nullTransformationContext); + ignoreReturns = oldIgnoreReturns; + return result; + } + } + } + function transformConstantInitializer(initializer, substitutions) { + return substitutions.size + ? visitor(initializer) + : initializer; + function visitor(node) { + var substitution = substitutions.get(ts.getNodeId(node).toString()); + return substitution ? ts.getSynthesizedDeepClone(substitution) : ts.visitEachChild(node, visitor, ts.nullTransformationContext); + } + } + function getStatementsOrClassElements(scope) { + if (ts.isFunctionLikeDeclaration(scope)) { + var body = scope.body; // TODO: GH#18217 + if (ts.isBlock(body)) { + return body.statements; + } + } + else if (ts.isModuleBlock(scope) || ts.isSourceFile(scope)) { + return scope.statements; + } + else if (ts.isClassLike(scope)) { + return scope.members; + } + else { + ts.assertType(scope); + } + return ts.emptyArray; + } + /** + * If `scope` contains a function after `minPos`, then return the first such function. + * Otherwise, return `undefined`. + */ + function getNodeToInsertFunctionBefore(minPos, scope) { + return ts.find(getStatementsOrClassElements(scope), function (child) { + return child.pos >= minPos && ts.isFunctionLikeDeclaration(child) && !ts.isConstructorDeclaration(child); + }); + } + function getNodeToInsertPropertyBefore(maxPos, scope) { + var members = scope.members; + ts.Debug.assert(members.length > 0); // There must be at least one child, since we extracted from one. + var prevMember; + var allProperties = true; + for (var _i = 0, members_7 = members; _i < members_7.length; _i++) { + var member = members_7[_i]; + if (member.pos > maxPos) { + return prevMember || members[0]; + } + if (allProperties && !ts.isPropertyDeclaration(member)) { + // If it is non-vacuously true that all preceding members are properties, + // insert before the current member (i.e. at the end of the list of properties). + if (prevMember !== undefined) { + return member; + } + allProperties = false; + } + prevMember = member; + } + if (prevMember === undefined) + return ts.Debug.fail(); // If the loop didn't return, then it did set prevMember. + return prevMember; + } + function getNodeToInsertConstantBefore(node, scope) { + ts.Debug.assert(!ts.isClassLike(scope)); + var prevScope; + for (var curr = node; curr !== scope; curr = curr.parent) { + if (isScope(curr)) { + prevScope = curr; + } + } + for (var curr = (prevScope || node).parent;; curr = curr.parent) { + if (isBlockLike(curr)) { + var prevStatement = void 0; + for (var _i = 0, _a = curr.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + if (statement.pos > node.pos) { + break; + } + prevStatement = statement; + } + if (!prevStatement && ts.isCaseClause(curr)) { + // We must have been in the expression of the case clause. + ts.Debug.assert(ts.isSwitchStatement(curr.parent.parent)); + return curr.parent.parent; + } + // There must be at least one statement since we started in one. + return ts.Debug.assertDefined(prevStatement); + } + ts.Debug.assert(curr !== scope, "Didn't encounter a block-like before encountering scope"); + } + } + function getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes) { + var variableAssignments = ts.map(exposedVariableDeclarations, function (v) { return ts.createShorthandPropertyAssignment(v.symbol.name); }); + var writeAssignments = ts.map(writes, function (w) { return ts.createShorthandPropertyAssignment(w.symbol.name); }); + // TODO: GH#18217 `variableAssignments` not possibly undefined! + return variableAssignments === undefined + ? writeAssignments + : writeAssignments === undefined + ? variableAssignments + : variableAssignments.concat(writeAssignments); + } + function isReadonlyArray(v) { + return ts.isArray(v); + } + /** + * Produces a range that spans the entirety of nodes, given a selection + * that might start/end in the middle of nodes. + * + * For example, when the user makes a selection like this + * v---v + * var someThing = foo + bar; + * this returns ^-------^ + */ + function getEnclosingTextRange(targetRange, sourceFile) { + return isReadonlyArray(targetRange.range) + ? { pos: ts.first(targetRange.range).getStart(sourceFile), end: ts.last(targetRange.range).getEnd() } + : targetRange.range; + } + var Usage; + (function (Usage) { + // value should be passed to extracted method + Usage[Usage["Read"] = 1] = "Read"; + // value should be passed to extracted method and propagated back + Usage[Usage["Write"] = 2] = "Write"; + })(Usage || (Usage = {})); + function collectReadsAndWrites(targetRange, scopes, enclosingTextRange, sourceFile, checker, cancellationToken) { + var allTypeParameterUsages = ts.createMap(); // Key is type ID + var usagesPerScope = []; + var substitutionsPerScope = []; + var functionErrorsPerScope = []; + var constantErrorsPerScope = []; + var visibleDeclarationsInExtractedRange = []; + var exposedVariableSymbolSet = ts.createMap(); // Key is symbol ID + var exposedVariableDeclarations = []; + var firstExposedNonVariableDeclaration; + var expression = !isReadonlyArray(targetRange.range) + ? targetRange.range + : targetRange.range.length === 1 && ts.isExpressionStatement(targetRange.range[0]) + ? targetRange.range[0].expression + : undefined; + var expressionDiagnostic; + if (expression === undefined) { + var statements = targetRange.range; + var start = ts.first(statements).getStart(); + var end = ts.last(statements).end; + expressionDiagnostic = ts.createFileDiagnostic(sourceFile, start, end - start, Messages.expressionExpected); + } + else if (checker.getTypeAtLocation(expression).flags & (16384 /* Void */ | 131072 /* Never */)) { + expressionDiagnostic = ts.createDiagnosticForNode(expression, Messages.uselessConstantType); + } + // initialize results + for (var _i = 0, scopes_1 = scopes; _i < scopes_1.length; _i++) { + var scope = scopes_1[_i]; + usagesPerScope.push({ usages: ts.createMap(), typeParameterUsages: ts.createMap(), substitutions: ts.createMap() }); + substitutionsPerScope.push(ts.createMap()); + functionErrorsPerScope.push(ts.isFunctionLikeDeclaration(scope) && scope.kind !== 239 /* FunctionDeclaration */ + ? [ts.createDiagnosticForNode(scope, Messages.cannotExtractToOtherFunctionLike)] + : []); + var constantErrors = []; + if (expressionDiagnostic) { + constantErrors.push(expressionDiagnostic); + } + if (ts.isClassLike(scope) && ts.isInJSFile(scope)) { + constantErrors.push(ts.createDiagnosticForNode(scope, Messages.cannotExtractToJSClass)); + } + if (ts.isArrowFunction(scope) && !ts.isBlock(scope.body)) { + // TODO (https://github.com/Microsoft/TypeScript/issues/18924): allow this + constantErrors.push(ts.createDiagnosticForNode(scope, Messages.cannotExtractToExpressionArrowFunction)); + } + constantErrorsPerScope.push(constantErrors); + } + var seenUsages = ts.createMap(); + var target = isReadonlyArray(targetRange.range) ? ts.createBlock(targetRange.range) : targetRange.range; + var unmodifiedNode = isReadonlyArray(targetRange.range) ? ts.first(targetRange.range) : targetRange.range; + var inGenericContext = isInGenericContext(unmodifiedNode); + collectUsages(target); + // Unfortunately, this code takes advantage of the knowledge that the generated method + // will use the contextual type of an expression as the return type of the extracted + // method (and will therefore "use" all the types involved). + if (inGenericContext && !isReadonlyArray(targetRange.range)) { + var contextualType = checker.getContextualType(targetRange.range); // TODO: GH#18217 + recordTypeParameterUsages(contextualType); + } + if (allTypeParameterUsages.size > 0) { + var seenTypeParameterUsages = ts.createMap(); // Key is type ID + var i_1 = 0; + for (var curr = unmodifiedNode; curr !== undefined && i_1 < scopes.length; curr = curr.parent) { + if (curr === scopes[i_1]) { + // Copy current contents of seenTypeParameterUsages into scope. + seenTypeParameterUsages.forEach(function (typeParameter, id) { + usagesPerScope[i_1].typeParameterUsages.set(id, typeParameter); + }); + i_1++; + } + // Note that we add the current node's type parameters *after* updating the corresponding scope. + if (ts.isDeclarationWithTypeParameters(curr)) { + for (var _a = 0, _b = ts.getEffectiveTypeParameterDeclarations(curr); _a < _b.length; _a++) { + var typeParameterDecl = _b[_a]; + var typeParameter = checker.getTypeAtLocation(typeParameterDecl); + if (allTypeParameterUsages.has(typeParameter.id.toString())) { + seenTypeParameterUsages.set(typeParameter.id.toString(), typeParameter); + } + } + } + } + // If we didn't get through all the scopes, then there were some that weren't in our + // parent chain (impossible at time of writing). A conservative solution would be to + // copy allTypeParameterUsages into all remaining scopes. + ts.Debug.assert(i_1 === scopes.length); + } + // If there are any declarations in the extracted block that are used in the same enclosing + // lexical scope, we can't move the extraction "up" as those declarations will become unreachable + if (visibleDeclarationsInExtractedRange.length) { + var containingLexicalScopeOfExtraction = ts.isBlockScope(scopes[0], scopes[0].parent) + ? scopes[0] + : ts.getEnclosingBlockScopeContainer(scopes[0]); + ts.forEachChild(containingLexicalScopeOfExtraction, checkForUsedDeclarations); + } + var _loop_22 = function (i) { + var scopeUsages = usagesPerScope[i]; + // Special case: in the innermost scope, all usages are available. + // (The computed value reflects the value at the top-level of the scope, but the + // local will actually be declared at the same level as the extracted expression). + if (i > 0 && (scopeUsages.usages.size > 0 || scopeUsages.typeParameterUsages.size > 0)) { + var errorNode = isReadonlyArray(targetRange.range) ? targetRange.range[0] : targetRange.range; + constantErrorsPerScope[i].push(ts.createDiagnosticForNode(errorNode, Messages.cannotAccessVariablesFromNestedScopes)); + } + var hasWrite = false; + var readonlyClassPropertyWrite; + usagesPerScope[i].usages.forEach(function (value) { + if (value.usage === 2 /* Write */) { + hasWrite = true; + if (value.symbol.flags & 106500 /* ClassMember */ && + value.symbol.valueDeclaration && + ts.hasModifier(value.symbol.valueDeclaration, 64 /* Readonly */)) { + readonlyClassPropertyWrite = value.symbol.valueDeclaration; + } + } + }); + // If an expression was extracted, then there shouldn't have been any variable declarations. + ts.Debug.assert(isReadonlyArray(targetRange.range) || exposedVariableDeclarations.length === 0); + if (hasWrite && !isReadonlyArray(targetRange.range)) { + var diag = ts.createDiagnosticForNode(targetRange.range, Messages.cannotWriteInExpression); + functionErrorsPerScope[i].push(diag); + constantErrorsPerScope[i].push(diag); + } + else if (readonlyClassPropertyWrite && i > 0) { + var diag = ts.createDiagnosticForNode(readonlyClassPropertyWrite, Messages.cannotExtractReadonlyPropertyInitializerOutsideConstructor); + functionErrorsPerScope[i].push(diag); + constantErrorsPerScope[i].push(diag); + } + else if (firstExposedNonVariableDeclaration) { + var diag = ts.createDiagnosticForNode(firstExposedNonVariableDeclaration, Messages.cannotExtractExportedEntity); + functionErrorsPerScope[i].push(diag); + constantErrorsPerScope[i].push(diag); + } + }; + for (var i = 0; i < scopes.length; i++) { + _loop_22(i); + } + return { target: target, usagesPerScope: usagesPerScope, functionErrorsPerScope: functionErrorsPerScope, constantErrorsPerScope: constantErrorsPerScope, exposedVariableDeclarations: exposedVariableDeclarations }; + function isInGenericContext(node) { + return !!ts.findAncestor(node, function (n) { return ts.isDeclarationWithTypeParameters(n) && ts.getEffectiveTypeParameterDeclarations(n).length !== 0; }); + } + function recordTypeParameterUsages(type) { + // PERF: This is potentially very expensive. `type` could be a library type with + // a lot of properties, each of which the walker will visit. Unfortunately, the + // solution isn't as trivial as filtering to user types because of (e.g.) Array. + var symbolWalker = checker.getSymbolWalker(function () { return (cancellationToken.throwIfCancellationRequested(), true); }); + var visitedTypes = symbolWalker.walkType(type).visitedTypes; + for (var _i = 0, visitedTypes_1 = visitedTypes; _i < visitedTypes_1.length; _i++) { + var visitedType = visitedTypes_1[_i]; + if (visitedType.isTypeParameter()) { + allTypeParameterUsages.set(visitedType.id.toString(), visitedType); + } + } + } + function collectUsages(node, valueUsage) { + if (valueUsage === void 0) { valueUsage = 1 /* Read */; } + if (inGenericContext) { + var type = checker.getTypeAtLocation(node); + recordTypeParameterUsages(type); + } + if (ts.isDeclaration(node) && node.symbol) { + visibleDeclarationsInExtractedRange.push(node); + } + if (ts.isAssignmentExpression(node)) { + // use 'write' as default usage for values + collectUsages(node.left, 2 /* Write */); + collectUsages(node.right); + } + else if (ts.isUnaryExpressionWithWrite(node)) { + collectUsages(node.operand, 2 /* Write */); + } + else if (ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node)) { + // use 'write' as default usage for values + ts.forEachChild(node, collectUsages); + } + else if (ts.isIdentifier(node)) { + if (!node.parent) { + return; + } + if (ts.isQualifiedName(node.parent) && node !== node.parent.left) { + return; + } + if (ts.isPropertyAccessExpression(node.parent) && node !== node.parent.expression) { + return; + } + recordUsage(node, valueUsage, /*isTypeNode*/ ts.isPartOfTypeNode(node)); + } + else { + ts.forEachChild(node, collectUsages); + } + } + function recordUsage(n, usage, isTypeNode) { + var symbolId = recordUsagebySymbol(n, usage, isTypeNode); + if (symbolId) { + for (var i = 0; i < scopes.length; i++) { + // push substitution from map to map to simplify rewriting + var substitution = substitutionsPerScope[i].get(symbolId); + if (substitution) { + usagesPerScope[i].substitutions.set(ts.getNodeId(n).toString(), substitution); + } + } + } + } + function recordUsagebySymbol(identifier, usage, isTypeName) { + var symbol = getSymbolReferencedByIdentifier(identifier); + if (!symbol) { + // cannot find symbol - do nothing + return undefined; + } + var symbolId = ts.getSymbolId(symbol).toString(); + var lastUsage = seenUsages.get(symbolId); + // there are two kinds of value usages + // - reads - if range contains a read from the value located outside of the range then value should be passed as a parameter + // - writes - if range contains a write to a value located outside the range the value should be passed as a parameter and + // returned as a return value + // 'write' case is a superset of 'read' so if we already have processed 'write' of some symbol there is not need to handle 'read' + // since all information is already recorded + if (lastUsage && lastUsage >= usage) { + return symbolId; + } + seenUsages.set(symbolId, usage); + if (lastUsage) { + // if we get here this means that we are trying to handle 'write' and 'read' was already processed + // walk scopes and update existing records. + for (var _i = 0, usagesPerScope_1 = usagesPerScope; _i < usagesPerScope_1.length; _i++) { + var perScope = usagesPerScope_1[_i]; + var prevEntry = perScope.usages.get(identifier.text); + if (prevEntry) { + perScope.usages.set(identifier.text, { usage: usage, symbol: symbol, node: identifier }); + } + } + return symbolId; + } + // find first declaration in this file + var decls = symbol.getDeclarations(); + var declInFile = decls && ts.find(decls, function (d) { return d.getSourceFile() === sourceFile; }); + if (!declInFile) { + return undefined; + } + if (ts.rangeContainsStartEnd(enclosingTextRange, declInFile.getStart(), declInFile.end)) { + // declaration is located in range to be extracted - do nothing + return undefined; + } + if (targetRange.facts & RangeFacts.IsGenerator && usage === 2 /* Write */) { + // this is write to a reference located outside of the target scope and range is extracted into generator + // currently this is unsupported scenario + var diag = ts.createDiagnosticForNode(identifier, Messages.cannotExtractRangeThatContainsWritesToReferencesLocatedOutsideOfTheTargetRangeInGenerators); + for (var _a = 0, functionErrorsPerScope_1 = functionErrorsPerScope; _a < functionErrorsPerScope_1.length; _a++) { + var errors = functionErrorsPerScope_1[_a]; + errors.push(diag); + } + for (var _b = 0, constantErrorsPerScope_1 = constantErrorsPerScope; _b < constantErrorsPerScope_1.length; _b++) { + var errors = constantErrorsPerScope_1[_b]; + errors.push(diag); + } + } + for (var i = 0; i < scopes.length; i++) { + var scope = scopes[i]; + var resolvedSymbol = checker.resolveName(symbol.name, scope, symbol.flags, /*excludeGlobals*/ false); + if (resolvedSymbol === symbol) { + continue; + } + if (!substitutionsPerScope[i].has(symbolId)) { + var substitution = tryReplaceWithQualifiedNameOrPropertyAccess(symbol.exportSymbol || symbol, scope, isTypeName); + if (substitution) { + substitutionsPerScope[i].set(symbolId, substitution); + } + else if (isTypeName) { + // If the symbol is a type parameter that won't be in scope, we'll pass it as a type argument + // so there's no problem. + if (!(symbol.flags & 262144 /* TypeParameter */)) { + var diag = ts.createDiagnosticForNode(identifier, Messages.typeWillNotBeVisibleInTheNewScope); + functionErrorsPerScope[i].push(diag); + constantErrorsPerScope[i].push(diag); + } + } + else { + usagesPerScope[i].usages.set(identifier.text, { usage: usage, symbol: symbol, node: identifier }); + } + } + } + return symbolId; + } + function checkForUsedDeclarations(node) { + // If this node is entirely within the original extraction range, we don't need to do anything. + if (node === targetRange.range || (isReadonlyArray(targetRange.range) && targetRange.range.indexOf(node) >= 0)) { + return; + } + // Otherwise check and recurse. + var sym = ts.isIdentifier(node) + ? getSymbolReferencedByIdentifier(node) + : checker.getSymbolAtLocation(node); + if (sym) { + var decl = ts.find(visibleDeclarationsInExtractedRange, function (d) { return d.symbol === sym; }); + if (decl) { + if (ts.isVariableDeclaration(decl)) { + var idString = decl.symbol.id.toString(); + if (!exposedVariableSymbolSet.has(idString)) { + exposedVariableDeclarations.push(decl); + exposedVariableSymbolSet.set(idString, true); + } + } + else { + // CONSIDER: this includes binding elements, which we could + // expose in the same way as variables. + firstExposedNonVariableDeclaration = firstExposedNonVariableDeclaration || decl; + } + } + } + ts.forEachChild(node, checkForUsedDeclarations); + } + /** + * Return the symbol referenced by an identifier (even if it declares a different symbol). + */ + function getSymbolReferencedByIdentifier(identifier) { + // If the identifier is both a property name and its value, we're only interested in its value + // (since the name is a declaration and will be included in the extracted range). + return identifier.parent && ts.isShorthandPropertyAssignment(identifier.parent) && identifier.parent.name === identifier + ? checker.getShorthandAssignmentValueSymbol(identifier.parent) + : checker.getSymbolAtLocation(identifier); + } + function tryReplaceWithQualifiedNameOrPropertyAccess(symbol, scopeDecl, isTypeNode) { + if (!symbol) { + return undefined; + } + var decls = symbol.getDeclarations(); + if (decls && decls.some(function (d) { return d.parent === scopeDecl; })) { + return ts.createIdentifier(symbol.name); + } + var prefix = tryReplaceWithQualifiedNameOrPropertyAccess(symbol.parent, scopeDecl, isTypeNode); + if (prefix === undefined) { + return undefined; + } + return isTypeNode + ? ts.createQualifiedName(prefix, ts.createIdentifier(symbol.name)) + : ts.createPropertyAccess(prefix, symbol.name); + } + } + /** + * Computes whether or not a node represents an expression in a position where it could + * be extracted. + * The isExpression() in utilities.ts returns some false positives we need to handle, + * such as `import x from 'y'` -- the 'y' is a StringLiteral but is *not* an expression + * in the sense of something that you could extract on + */ + function isExtractableExpression(node) { + var parent = node.parent; + switch (parent.kind) { + case 278 /* EnumMember */: + return false; + } + switch (node.kind) { + case 10 /* StringLiteral */: + return parent.kind !== 249 /* ImportDeclaration */ && + parent.kind !== 253 /* ImportSpecifier */; + case 208 /* SpreadElement */: + case 184 /* ObjectBindingPattern */: + case 186 /* BindingElement */: + return false; + case 72 /* Identifier */: + return parent.kind !== 186 /* BindingElement */ && + parent.kind !== 253 /* ImportSpecifier */ && + parent.kind !== 257 /* ExportSpecifier */; + } + return true; + } + function isBlockLike(node) { + switch (node.kind) { + case 218 /* Block */: + case 279 /* SourceFile */: + case 245 /* ModuleBlock */: + case 271 /* CaseClause */: + return true; + default: + return false; + } + } + })(extractSymbol = refactor.extractSymbol || (refactor.extractSymbol = {})); + })(refactor = ts.refactor || (ts.refactor = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var refactor; + (function (refactor) { + var generateGetAccessorAndSetAccessor; + (function (generateGetAccessorAndSetAccessor) { + var actionName = "Generate 'get' and 'set' accessors"; + var actionDescription = ts.Diagnostics.Generate_get_and_set_accessors.message; + refactor.registerRefactor(actionName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions }); + function getAvailableActions(context) { + if (!getConvertibleFieldAtPosition(context)) + return ts.emptyArray; + return [{ + name: actionName, + description: actionDescription, + actions: [ + { + name: actionName, + description: actionDescription + } + ] + }]; + } + function getEditsForAction(context, _actionName) { + var file = context.file; + var fieldInfo = getConvertibleFieldAtPosition(context); + if (!fieldInfo) + return undefined; + var isJS = ts.isSourceFileJS(file); + var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); + var isStatic = fieldInfo.isStatic, isReadonly = fieldInfo.isReadonly, fieldName = fieldInfo.fieldName, accessorName = fieldInfo.accessorName, originalName = fieldInfo.originalName, type = fieldInfo.type, container = fieldInfo.container, declaration = fieldInfo.declaration, renameAccessor = fieldInfo.renameAccessor; + ts.suppressLeadingAndTrailingTrivia(fieldName); + ts.suppressLeadingAndTrailingTrivia(declaration); + ts.suppressLeadingAndTrailingTrivia(container); + var isInClassLike = ts.isClassLike(container); + // avoid Readonly modifier because it will convert to get accessor + var modifierFlags = ts.getModifierFlags(declaration) & ~64 /* Readonly */; + var accessorModifiers = isInClassLike + ? !modifierFlags || modifierFlags & 8 /* Private */ + ? getModifiers(isJS, isStatic, 115 /* PublicKeyword */) + : ts.createNodeArray(ts.createModifiersFromModifierFlags(modifierFlags)) + : undefined; + var fieldModifiers = isInClassLike ? getModifiers(isJS, isStatic, 113 /* PrivateKeyword */) : undefined; + updateFieldDeclaration(changeTracker, file, declaration, fieldName, fieldModifiers); + var getAccessor = generateGetAccessor(fieldName, accessorName, type, accessorModifiers, isStatic, container); + ts.suppressLeadingAndTrailingTrivia(getAccessor); + insertAccessor(changeTracker, file, getAccessor, declaration, container); + if (isReadonly) { + // readonly modifier only existed in classLikeDeclaration + var constructor = ts.getFirstConstructorWithBody(container); + if (constructor) { + updateReadonlyPropertyInitializerStatementConstructor(changeTracker, file, constructor, fieldName.text, originalName); + } + } + else { + var setAccessor = generateSetAccessor(fieldName, accessorName, type, accessorModifiers, isStatic, container); + ts.suppressLeadingAndTrailingTrivia(setAccessor); + insertAccessor(changeTracker, file, setAccessor, declaration, container); + } + var edits = changeTracker.getChanges(); + var renameFilename = file.fileName; + var nameNeedRename = renameAccessor ? accessorName : fieldName; + var renameLocationOffset = ts.isIdentifier(nameNeedRename) ? 0 : -1; + var renameLocation = renameLocationOffset + ts.getRenameLocation(edits, renameFilename, nameNeedRename.text, /*preferLastLocation*/ ts.isParameter(declaration)); + return { renameFilename: renameFilename, renameLocation: renameLocation, edits: edits }; + } + function isConvertibleName(name) { + return ts.isIdentifier(name) || ts.isStringLiteral(name); + } + function isAcceptedDeclaration(node) { + return ts.isParameterPropertyDeclaration(node) || ts.isPropertyDeclaration(node) || ts.isPropertyAssignment(node); + } + function createPropertyName(name, originalName) { + return ts.isIdentifier(originalName) ? ts.createIdentifier(name) : ts.createLiteral(name); + } + function createAccessorAccessExpression(fieldName, isStatic, container) { + var leftHead = isStatic ? container.name : ts.createThis(); // TODO: GH#18217 + return ts.isIdentifier(fieldName) ? ts.createPropertyAccess(leftHead, fieldName) : ts.createElementAccess(leftHead, ts.createLiteral(fieldName)); + } + function getModifiers(isJS, isStatic, accessModifier) { + var modifiers = ts.append(!isJS ? [ts.createToken(accessModifier)] : undefined, isStatic ? ts.createToken(116 /* StaticKeyword */) : undefined); + return modifiers && ts.createNodeArray(modifiers); + } + function startsWithUnderscore(name) { + return name.charCodeAt(0) === 95 /* _ */; + } + function getConvertibleFieldAtPosition(context) { + var file = context.file, startPosition = context.startPosition, endPosition = context.endPosition; + var node = ts.getTokenAtPosition(file, startPosition); + var declaration = ts.findAncestor(node.parent, isAcceptedDeclaration); + // make sure declaration have AccessibilityModifier or Static Modifier or Readonly Modifier + var meaning = 28 /* AccessibilityModifier */ | 32 /* Static */ | 64 /* Readonly */; + if (!declaration || !ts.nodeOverlapsWithStartEnd(declaration.name, file, startPosition, endPosition) // TODO: GH#18217 + || !isConvertibleName(declaration.name) || (ts.getModifierFlags(declaration) | meaning) !== meaning) + return undefined; + var name = declaration.name.text; + var startWithUnderscore = startsWithUnderscore(name); + var fieldName = createPropertyName(startWithUnderscore ? name : ts.getUniqueName("_" + name, file), declaration.name); + var accessorName = createPropertyName(startWithUnderscore ? ts.getUniqueName(name.substring(1), file) : name, declaration.name); + return { + isStatic: ts.hasStaticModifier(declaration), + isReadonly: ts.hasReadonlyModifier(declaration), + type: ts.getTypeAnnotationNode(declaration), + container: declaration.kind === 151 /* Parameter */ ? declaration.parent.parent : declaration.parent, + originalName: declaration.name.text, + declaration: declaration, + fieldName: fieldName, + accessorName: accessorName, + renameAccessor: startWithUnderscore + }; + } + function generateGetAccessor(fieldName, accessorName, type, modifiers, isStatic, container) { + return ts.createGetAccessor( + /*decorators*/ undefined, modifiers, accessorName, + /*parameters*/ undefined, // TODO: GH#18217 + type, ts.createBlock([ + ts.createReturn(createAccessorAccessExpression(fieldName, isStatic, container)) + ], /*multiLine*/ true)); + } + function generateSetAccessor(fieldName, accessorName, type, modifiers, isStatic, container) { + return ts.createSetAccessor( + /*decorators*/ undefined, modifiers, accessorName, [ts.createParameter( + /*decorators*/ undefined, + /*modifiers*/ undefined, + /*dotDotDotToken*/ undefined, ts.createIdentifier("value"), + /*questionToken*/ undefined, type)], ts.createBlock([ + ts.createStatement(ts.createAssignment(createAccessorAccessExpression(fieldName, isStatic, container), ts.createIdentifier("value"))) + ], /*multiLine*/ true)); + } + function updatePropertyDeclaration(changeTracker, file, declaration, fieldName, modifiers) { + var property = ts.updateProperty(declaration, declaration.decorators, modifiers, fieldName, declaration.questionToken || declaration.exclamationToken, declaration.type, declaration.initializer); + changeTracker.replaceNode(file, declaration, property); + } + function updatePropertyAssignmentDeclaration(changeTracker, file, declaration, fieldName) { + var assignment = ts.updatePropertyAssignment(declaration, fieldName, declaration.initializer); + changeTracker.replacePropertyAssignment(file, declaration, assignment); + } + function updateFieldDeclaration(changeTracker, file, declaration, fieldName, modifiers) { + if (ts.isPropertyDeclaration(declaration)) { + updatePropertyDeclaration(changeTracker, file, declaration, fieldName, modifiers); + } + else if (ts.isPropertyAssignment(declaration)) { + updatePropertyAssignmentDeclaration(changeTracker, file, declaration, fieldName); + } + else { + changeTracker.replaceNode(file, declaration, ts.updateParameter(declaration, declaration.decorators, modifiers, declaration.dotDotDotToken, ts.cast(fieldName, ts.isIdentifier), declaration.questionToken, declaration.type, declaration.initializer)); + } + } + function insertAccessor(changeTracker, file, accessor, declaration, container) { + ts.isParameterPropertyDeclaration(declaration) + ? changeTracker.insertNodeAtClassStart(file, container, accessor) + : ts.isPropertyAssignment(declaration) + ? changeTracker.insertNodeAfterComma(file, declaration, accessor) + : changeTracker.insertNodeAfter(file, declaration, accessor); + } + function updateReadonlyPropertyInitializerStatementConstructor(changeTracker, file, constructor, fieldName, originalName) { + if (!constructor.body) + return; + constructor.body.forEachChild(function recur(node) { + if (ts.isElementAccessExpression(node) && + node.expression.kind === 100 /* ThisKeyword */ && + ts.isStringLiteral(node.argumentExpression) && + node.argumentExpression.text === originalName && + ts.isWriteAccess(node)) { + changeTracker.replaceNode(file, node.argumentExpression, ts.createStringLiteral(fieldName)); + } + if (ts.isPropertyAccessExpression(node) && node.expression.kind === 100 /* ThisKeyword */ && node.name.text === originalName && ts.isWriteAccess(node)) { + changeTracker.replaceNode(file, node.name, ts.createIdentifier(fieldName)); + } + if (!ts.isFunctionLike(node) && !ts.isClassLike(node)) { + node.forEachChild(recur); + } + }); + } + })(generateGetAccessorAndSetAccessor = refactor.generateGetAccessorAndSetAccessor || (refactor.generateGetAccessorAndSetAccessor = {})); + })(refactor = ts.refactor || (ts.refactor = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var refactor; + (function (refactor) { + var refactorName = "Move to a new file"; + refactor.registerRefactor(refactorName, { + getAvailableActions: function (context) { + if (!context.preferences.allowTextChangesInNewFiles || getStatementsToMove(context) === undefined) + return ts.emptyArray; + var description = ts.getLocaleSpecificMessage(ts.Diagnostics.Move_to_a_new_file); + return [{ name: refactorName, description: description, actions: [{ name: refactorName, description: description }] }]; + }, + getEditsForAction: function (context, actionName) { + ts.Debug.assert(actionName === refactorName); + var statements = ts.Debug.assertDefined(getStatementsToMove(context)); + var edits = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(context.file, context.program, statements, t, context.host, context.preferences); }); + return { edits: edits, renameFilename: undefined, renameLocation: undefined }; + } + }); + function getRangeToMove(context) { + var file = context.file; + var range = ts.createTextRangeFromSpan(ts.getRefactorContextSpan(context)); + var statements = file.statements; + var startNodeIndex = ts.findIndex(statements, function (s) { return s.end > range.pos; }); + if (startNodeIndex === -1) + return undefined; + var startStatement = statements[startNodeIndex]; + if (ts.isNamedDeclaration(startStatement) && startStatement.name && ts.rangeContainsRange(startStatement.name, range)) { + return { toMove: [statements[startNodeIndex]], afterLast: statements[startNodeIndex + 1] }; + } + // Can't only partially include the start node or be partially into the next node + if (range.pos > startStatement.getStart(file)) + return undefined; + var afterEndNodeIndex = ts.findIndex(statements, function (s) { return s.end > range.end; }, startNodeIndex); + // Can't be partially into the next node + if (afterEndNodeIndex !== -1 && (afterEndNodeIndex === 0 || statements[afterEndNodeIndex].getStart(file) < range.end)) + return undefined; + return { + toMove: statements.slice(startNodeIndex, afterEndNodeIndex === -1 ? statements.length : afterEndNodeIndex), + afterLast: afterEndNodeIndex === -1 ? undefined : statements[afterEndNodeIndex], + }; + } + function doChange(oldFile, program, toMove, changes, host, preferences) { + var checker = program.getTypeChecker(); + var usage = getUsageInfo(oldFile, toMove.all, checker); + var currentDirectory = ts.getDirectoryPath(oldFile.fileName); + var extension = ts.extensionFromPath(oldFile.fileName); + var newModuleName = makeUniqueModuleName(getNewModuleName(usage.movedSymbols), extension, currentDirectory, host); + var newFileNameWithExtension = newModuleName + extension; + // If previous file was global, this is easy. + changes.createNewFile(oldFile, ts.combinePaths(currentDirectory, newFileNameWithExtension), getNewStatementsAndRemoveFromOldFile(oldFile, usage, changes, toMove, program, newModuleName, preferences)); + addNewFileToTsconfig(program, changes, oldFile.fileName, newFileNameWithExtension, ts.hostGetCanonicalFileName(host)); + } + // Filters imports out of the range of statements to move. Imports will be copied to the new file anyway, and may still be needed in the old file. + function getStatementsToMove(context) { + var rangeToMove = getRangeToMove(context); + if (rangeToMove === undefined) + return undefined; + var all = []; + var ranges = []; + var toMove = rangeToMove.toMove, afterLast = rangeToMove.afterLast; + ts.getRangesWhere(toMove, function (s) { return !isPureImport(s); }, function (start, afterEndIndex) { + for (var i = start; i < afterEndIndex; i++) + all.push(toMove[i]); + ranges.push({ first: toMove[start], afterLast: afterLast }); + }); + return all.length === 0 ? undefined : { all: all, ranges: ranges }; + } + function isPureImport(node) { + switch (node.kind) { + case 249 /* ImportDeclaration */: + return true; + case 248 /* ImportEqualsDeclaration */: + return !ts.hasModifier(node, 1 /* Export */); + case 219 /* VariableStatement */: + return node.declarationList.declarations.every(function (d) { return !!d.initializer && ts.isRequireCall(d.initializer, /*checkArgumentIsStringLiteralLike*/ true); }); + default: + return false; + } + } + function addNewFileToTsconfig(program, changes, oldFileName, newFileNameWithExtension, getCanonicalFileName) { + var cfg = program.getCompilerOptions().configFile; + if (!cfg) + return; + var newFileAbsolutePath = ts.normalizePath(ts.combinePaths(oldFileName, "..", newFileNameWithExtension)); + var newFilePath = ts.getRelativePathFromFile(cfg.fileName, newFileAbsolutePath, getCanonicalFileName); + var cfgObject = cfg.statements[0] && ts.tryCast(cfg.statements[0].expression, ts.isObjectLiteralExpression); + var filesProp = cfgObject && ts.find(cfgObject.properties, function (prop) { + return ts.isPropertyAssignment(prop) && ts.isStringLiteral(prop.name) && prop.name.text === "files"; + }); + if (filesProp && ts.isArrayLiteralExpression(filesProp.initializer)) { + changes.insertNodeInListAfter(cfg, ts.last(filesProp.initializer.elements), ts.createLiteral(newFilePath), filesProp.initializer.elements); + } + } + function getNewStatementsAndRemoveFromOldFile(oldFile, usage, changes, toMove, program, newModuleName, preferences) { + var checker = program.getTypeChecker(); + if (!oldFile.externalModuleIndicator && !oldFile.commonJsModuleIndicator) { + deleteMovedStatements(oldFile, toMove.ranges, changes); + return toMove.all; + } + var useEs6ModuleSyntax = !!oldFile.externalModuleIndicator; + var quotePreference = ts.getQuotePreference(oldFile, preferences); + var importsFromNewFile = createOldFileImportsFromNewFile(usage.oldFileImportsFromNewFile, newModuleName, useEs6ModuleSyntax, quotePreference); + if (importsFromNewFile) { + ts.insertImport(changes, oldFile, importsFromNewFile); + } + deleteUnusedOldImports(oldFile, toMove.all, changes, usage.unusedImportsFromOldFile, checker); + deleteMovedStatements(oldFile, toMove.ranges, changes); + updateImportsInOtherFiles(changes, program, oldFile, usage.movedSymbols, newModuleName); + return getNewFileImportsAndAddExportInOldFile(oldFile, usage.oldImportsNeededByNewFile, usage.newFileImportsFromOldFile, changes, checker, useEs6ModuleSyntax, quotePreference).concat(addExports(oldFile, toMove.all, usage.oldFileImportsFromNewFile, useEs6ModuleSyntax)); + } + function deleteMovedStatements(sourceFile, moved, changes) { + for (var _i = 0, moved_1 = moved; _i < moved_1.length; _i++) { + var _a = moved_1[_i], first_1 = _a.first, afterLast = _a.afterLast; + changes.deleteNodeRangeExcludingEnd(sourceFile, first_1, afterLast); + } + } + function deleteUnusedOldImports(oldFile, toMove, changes, toDelete, checker) { + for (var _i = 0, _a = oldFile.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + if (ts.contains(toMove, statement)) + continue; + forEachImportInStatement(statement, function (i) { return deleteUnusedImports(oldFile, i, changes, function (name) { return toDelete.has(checker.getSymbolAtLocation(name)); }); }); + } + } + function updateImportsInOtherFiles(changes, program, oldFile, movedSymbols, newModuleName) { + var checker = program.getTypeChecker(); + var _loop_23 = function (sourceFile) { + if (sourceFile === oldFile) + return "continue"; + var _loop_24 = function (statement) { + forEachImportInStatement(statement, function (importNode) { + if (checker.getSymbolAtLocation(moduleSpecifierFromImport(importNode)) !== oldFile.symbol) + return; + var shouldMove = function (name) { + var symbol = ts.isBindingElement(name.parent) + ? ts.getPropertySymbolFromBindingElement(checker, name.parent) + : ts.skipAlias(checker.getSymbolAtLocation(name), checker); // TODO: GH#18217 + return !!symbol && movedSymbols.has(symbol); + }; + deleteUnusedImports(sourceFile, importNode, changes, shouldMove); // These will be changed to imports from the new file + var newModuleSpecifier = ts.combinePaths(ts.getDirectoryPath(moduleSpecifierFromImport(importNode).text), newModuleName); + var newImportDeclaration = filterImport(importNode, ts.createLiteral(newModuleSpecifier), shouldMove); + if (newImportDeclaration) + changes.insertNodeAfter(sourceFile, statement, newImportDeclaration); + var ns = getNamespaceLikeImport(importNode); + if (ns) + updateNamespaceLikeImport(changes, sourceFile, checker, movedSymbols, newModuleName, newModuleSpecifier, ns, importNode); + }); + }; + for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + _loop_24(statement); + } + }; + for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { + var sourceFile = _a[_i]; + _loop_23(sourceFile); + } + } + function getNamespaceLikeImport(node) { + switch (node.kind) { + case 249 /* ImportDeclaration */: + return node.importClause && node.importClause.namedBindings && node.importClause.namedBindings.kind === 251 /* NamespaceImport */ ? + node.importClause.namedBindings.name : undefined; + case 248 /* ImportEqualsDeclaration */: + return node.name; + case 237 /* VariableDeclaration */: + return ts.tryCast(node.name, ts.isIdentifier); + default: + return ts.Debug.assertNever(node); + } + } + function updateNamespaceLikeImport(changes, sourceFile, checker, movedSymbols, newModuleName, newModuleSpecifier, oldImportId, oldImportNode) { + var preferredNewNamespaceName = ts.codefix.moduleSpecifierToValidIdentifier(newModuleName, 6 /* ESNext */); + var needUniqueName = false; + var toChange = []; + ts.FindAllReferences.Core.eachSymbolReferenceInFile(oldImportId, checker, sourceFile, function (ref) { + if (!ts.isPropertyAccessExpression(ref.parent)) + return; + needUniqueName = needUniqueName || !!checker.resolveName(preferredNewNamespaceName, ref, 67108863 /* All */, /*excludeGlobals*/ true); + if (movedSymbols.has(checker.getSymbolAtLocation(ref.parent.name))) { + toChange.push(ref); + } + }); + if (toChange.length) { + var newNamespaceName = needUniqueName ? ts.getUniqueName(preferredNewNamespaceName, sourceFile) : preferredNewNamespaceName; + for (var _i = 0, toChange_1 = toChange; _i < toChange_1.length; _i++) { + var ref = toChange_1[_i]; + changes.replaceNode(sourceFile, ref, ts.createIdentifier(newNamespaceName)); + } + changes.insertNodeAfter(sourceFile, oldImportNode, updateNamespaceLikeImportNode(oldImportNode, newModuleName, newModuleSpecifier)); + } + } + function updateNamespaceLikeImportNode(node, newNamespaceName, newModuleSpecifier) { + var newNamespaceId = ts.createIdentifier(newNamespaceName); + var newModuleString = ts.createLiteral(newModuleSpecifier); + switch (node.kind) { + case 249 /* ImportDeclaration */: + return ts.createImportDeclaration( + /*decorators*/ undefined, /*modifiers*/ undefined, ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(newNamespaceId)), newModuleString); + case 248 /* ImportEqualsDeclaration */: + return ts.createImportEqualsDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, newNamespaceId, ts.createExternalModuleReference(newModuleString)); + case 237 /* VariableDeclaration */: + return ts.createVariableDeclaration(newNamespaceId, /*type*/ undefined, createRequireCall(newModuleString)); + default: + return ts.Debug.assertNever(node); + } + } + function moduleSpecifierFromImport(i) { + return (i.kind === 249 /* ImportDeclaration */ ? i.moduleSpecifier + : i.kind === 248 /* ImportEqualsDeclaration */ ? i.moduleReference.expression + : i.initializer.arguments[0]); + } + function forEachImportInStatement(statement, cb) { + if (ts.isImportDeclaration(statement)) { + if (ts.isStringLiteral(statement.moduleSpecifier)) + cb(statement); + } + else if (ts.isImportEqualsDeclaration(statement)) { + if (ts.isExternalModuleReference(statement.moduleReference) && ts.isStringLiteralLike(statement.moduleReference.expression)) { + cb(statement); + } + } + else if (ts.isVariableStatement(statement)) { + for (var _i = 0, _a = statement.declarationList.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + if (decl.initializer && ts.isRequireCall(decl.initializer, /*checkArgumentIsStringLiteralLike*/ true)) { + cb(decl); + } + } + } + } + function createOldFileImportsFromNewFile(newFileNeedExport, newFileNameWithExtension, useEs6Imports, quotePreference) { + var defaultImport; + var imports = []; + newFileNeedExport.forEach(function (symbol) { + if (symbol.escapedName === "default" /* Default */) { + defaultImport = ts.createIdentifier(ts.symbolNameNoDefault(symbol)); // TODO: GH#18217 + } + else { + imports.push(symbol.name); + } + }); + return makeImportOrRequire(defaultImport, imports, newFileNameWithExtension, useEs6Imports, quotePreference); + } + function makeImportOrRequire(defaultImport, imports, path, useEs6Imports, quotePreference) { + path = ts.ensurePathIsNonModuleName(path); + if (useEs6Imports) { + var specifiers = imports.map(function (i) { return ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(i)); }); + return ts.makeImportIfNecessary(defaultImport, specifiers, path, quotePreference); + } + else { + ts.Debug.assert(!defaultImport); // If there's a default export, it should have been an es6 module. + var bindingElements = imports.map(function (i) { return ts.createBindingElement(/*dotDotDotToken*/ undefined, /*propertyName*/ undefined, i); }); + return bindingElements.length + ? makeVariableStatement(ts.createObjectBindingPattern(bindingElements), /*type*/ undefined, createRequireCall(ts.createLiteral(path))) + : undefined; + } + } + function makeVariableStatement(name, type, initializer, flags) { + if (flags === void 0) { flags = 2 /* Const */; } + return ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(name, type, initializer)], flags)); + } + function createRequireCall(moduleSpecifier) { + return ts.createCall(ts.createIdentifier("require"), /*typeArguments*/ undefined, [moduleSpecifier]); + } + function addExports(sourceFile, toMove, needExport, useEs6Exports) { + return ts.flatMap(toMove, function (statement) { + if (isTopLevelDeclarationStatement(statement) && + !isExported(sourceFile, statement, useEs6Exports) && + forEachTopLevelDeclaration(statement, function (d) { return needExport.has(ts.Debug.assertDefined(d.symbol)); })) { + var exports_2 = addExport(statement, useEs6Exports); + if (exports_2) + return exports_2; + } + return statement; + }); + } + function deleteUnusedImports(sourceFile, importDecl, changes, isUnused) { + switch (importDecl.kind) { + case 249 /* ImportDeclaration */: + deleteUnusedImportsInDeclaration(sourceFile, importDecl, changes, isUnused); + break; + case 248 /* ImportEqualsDeclaration */: + if (isUnused(importDecl.name)) { + changes.delete(sourceFile, importDecl); + } + break; + case 237 /* VariableDeclaration */: + deleteUnusedImportsInVariableDeclaration(sourceFile, importDecl, changes, isUnused); + break; + default: + ts.Debug.assertNever(importDecl); + } + } + function deleteUnusedImportsInDeclaration(sourceFile, importDecl, changes, isUnused) { + if (!importDecl.importClause) + return; + var _a = importDecl.importClause, name = _a.name, namedBindings = _a.namedBindings; + var defaultUnused = !name || isUnused(name); + var namedBindingsUnused = !namedBindings || + (namedBindings.kind === 251 /* NamespaceImport */ ? isUnused(namedBindings.name) : namedBindings.elements.length !== 0 && namedBindings.elements.every(function (e) { return isUnused(e.name); })); + if (defaultUnused && namedBindingsUnused) { + changes.delete(sourceFile, importDecl); + } + else { + if (name && defaultUnused) { + changes.delete(sourceFile, name); + } + if (namedBindings) { + if (namedBindingsUnused) { + changes.delete(sourceFile, namedBindings); + } + else if (namedBindings.kind === 252 /* NamedImports */) { + for (var _i = 0, _b = namedBindings.elements; _i < _b.length; _i++) { + var element = _b[_i]; + if (isUnused(element.name)) + changes.delete(sourceFile, element); + } + } + } + } + } + function deleteUnusedImportsInVariableDeclaration(sourceFile, varDecl, changes, isUnused) { + var name = varDecl.name; + switch (name.kind) { + case 72 /* Identifier */: + if (isUnused(name)) { + changes.delete(sourceFile, name); + } + break; + case 185 /* ArrayBindingPattern */: + break; + case 184 /* ObjectBindingPattern */: + if (name.elements.every(function (e) { return ts.isIdentifier(e.name) && isUnused(e.name); })) { + changes.delete(sourceFile, ts.isVariableDeclarationList(varDecl.parent) && varDecl.parent.declarations.length === 1 ? varDecl.parent.parent : varDecl); + } + else { + for (var _i = 0, _a = name.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (ts.isIdentifier(element.name) && isUnused(element.name)) { + changes.delete(sourceFile, element.name); + } + } + } + break; + } + } + function getNewFileImportsAndAddExportInOldFile(oldFile, importsToCopy, newFileImportsFromOldFile, changes, checker, useEs6ModuleSyntax, quotePreference) { + var copiedOldImports = []; + for (var _i = 0, _a = oldFile.statements; _i < _a.length; _i++) { + var oldStatement = _a[_i]; + forEachImportInStatement(oldStatement, function (i) { + ts.append(copiedOldImports, filterImport(i, moduleSpecifierFromImport(i), function (name) { return importsToCopy.has(checker.getSymbolAtLocation(name)); })); + }); + } + // Also, import things used from the old file, and insert 'export' modifiers as necessary in the old file. + var oldFileDefault; + var oldFileNamedImports = []; + var markSeenTop = ts.nodeSeenTracker(); // Needed because multiple declarations may appear in `const x = 0, y = 1;`. + newFileImportsFromOldFile.forEach(function (symbol) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + if (!isTopLevelDeclaration(decl)) + continue; + var name = nameOfTopLevelDeclaration(decl); + if (!name) + continue; + var top = getTopLevelDeclarationStatement(decl); + if (markSeenTop(top)) { + addExportToChanges(oldFile, top, changes, useEs6ModuleSyntax); + } + if (ts.hasModifier(decl, 512 /* Default */)) { + oldFileDefault = name; + } + else { + oldFileNamedImports.push(name.text); + } + } + }); + ts.append(copiedOldImports, makeImportOrRequire(oldFileDefault, oldFileNamedImports, ts.removeFileExtension(ts.getBaseFileName(oldFile.fileName)), useEs6ModuleSyntax, quotePreference)); + return copiedOldImports; + } + function makeUniqueModuleName(moduleName, extension, inDirectory, host) { + var newModuleName = moduleName; + for (var i = 1;; i++) { + var name = ts.combinePaths(inDirectory, newModuleName + extension); + if (!host.fileExists(name)) + return newModuleName; // TODO: GH#18217 + newModuleName = moduleName + "." + i; + } + } + function getNewModuleName(movedSymbols) { + return movedSymbols.forEachEntry(ts.symbolNameNoDefault) || "newFile"; + } + function getUsageInfo(oldFile, toMove, checker) { + var movedSymbols = new SymbolSet(); + var oldImportsNeededByNewFile = new SymbolSet(); + var newFileImportsFromOldFile = new SymbolSet(); + for (var _i = 0, toMove_1 = toMove; _i < toMove_1.length; _i++) { + var statement = toMove_1[_i]; + forEachTopLevelDeclaration(statement, function (decl) { + movedSymbols.add(ts.Debug.assertDefined(ts.isExpressionStatement(decl) ? checker.getSymbolAtLocation(decl.expression.left) : decl.symbol)); + }); + } + for (var _a = 0, toMove_2 = toMove; _a < toMove_2.length; _a++) { + var statement = toMove_2[_a]; + forEachReference(statement, checker, function (symbol) { + if (!symbol.declarations) + return; + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + if (isInImport(decl)) { + oldImportsNeededByNewFile.add(symbol); + } + else if (isTopLevelDeclaration(decl) && sourceFileOfTopLevelDeclaration(decl) === oldFile && !movedSymbols.has(symbol)) { + newFileImportsFromOldFile.add(symbol); + } + } + }); + } + var unusedImportsFromOldFile = oldImportsNeededByNewFile.clone(); + var oldFileImportsFromNewFile = new SymbolSet(); + for (var _b = 0, _c = oldFile.statements; _b < _c.length; _b++) { + var statement = _c[_b]; + if (ts.contains(toMove, statement)) + continue; + forEachReference(statement, checker, function (symbol) { + if (movedSymbols.has(symbol)) + oldFileImportsFromNewFile.add(symbol); + unusedImportsFromOldFile.delete(symbol); + }); + } + return { movedSymbols: movedSymbols, newFileImportsFromOldFile: newFileImportsFromOldFile, oldFileImportsFromNewFile: oldFileImportsFromNewFile, oldImportsNeededByNewFile: oldImportsNeededByNewFile, unusedImportsFromOldFile: unusedImportsFromOldFile }; + } + // Below should all be utilities + function isInImport(decl) { + switch (decl.kind) { + case 248 /* ImportEqualsDeclaration */: + case 253 /* ImportSpecifier */: + case 250 /* ImportClause */: + return true; + case 237 /* VariableDeclaration */: + return isVariableDeclarationInImport(decl); + case 186 /* BindingElement */: + return ts.isVariableDeclaration(decl.parent.parent) && isVariableDeclarationInImport(decl.parent.parent); + default: + return false; + } + } + function isVariableDeclarationInImport(decl) { + return ts.isSourceFile(decl.parent.parent.parent) && + decl.initializer && ts.isRequireCall(decl.initializer, /*checkArgumentIsStringLiteralLike*/ true); + } + function filterImport(i, moduleSpecifier, keep) { + switch (i.kind) { + case 249 /* ImportDeclaration */: { + var clause = i.importClause; + if (!clause) + return undefined; + var defaultImport = clause.name && keep(clause.name) ? clause.name : undefined; + var namedBindings = clause.namedBindings && filterNamedBindings(clause.namedBindings, keep); + return defaultImport || namedBindings + ? ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createImportClause(defaultImport, namedBindings), moduleSpecifier) + : undefined; + } + case 248 /* ImportEqualsDeclaration */: + return keep(i.name) ? i : undefined; + case 237 /* VariableDeclaration */: { + var name = filterBindingName(i.name, keep); + return name ? makeVariableStatement(name, i.type, createRequireCall(moduleSpecifier), i.parent.flags) : undefined; + } + default: + return ts.Debug.assertNever(i); + } + } + function filterNamedBindings(namedBindings, keep) { + if (namedBindings.kind === 251 /* NamespaceImport */) { + return keep(namedBindings.name) ? namedBindings : undefined; + } + else { + var newElements = namedBindings.elements.filter(function (e) { return keep(e.name); }); + return newElements.length ? ts.createNamedImports(newElements) : undefined; + } + } + function filterBindingName(name, keep) { + switch (name.kind) { + case 72 /* Identifier */: + return keep(name) ? name : undefined; + case 185 /* ArrayBindingPattern */: + return name; + case 184 /* ObjectBindingPattern */: { + // We can't handle nested destructurings or property names well here, so just copy them all. + var newElements = name.elements.filter(function (prop) { return prop.propertyName || !ts.isIdentifier(prop.name) || keep(prop.name); }); + return newElements.length ? ts.createObjectBindingPattern(newElements) : undefined; + } + } + } + function forEachReference(node, checker, onReference) { + node.forEachChild(function cb(node) { + if (ts.isIdentifier(node) && !ts.isDeclarationName(node)) { + var sym = checker.getSymbolAtLocation(node); + if (sym) + onReference(sym); + } + else { + node.forEachChild(cb); + } + }); + } + var SymbolSet = /** @class */ (function () { + function SymbolSet() { + this.map = ts.createMap(); + } + SymbolSet.prototype.add = function (symbol) { + this.map.set(String(ts.getSymbolId(symbol)), symbol); + }; + SymbolSet.prototype.has = function (symbol) { + return this.map.has(String(ts.getSymbolId(symbol))); + }; + SymbolSet.prototype.delete = function (symbol) { + this.map.delete(String(ts.getSymbolId(symbol))); + }; + SymbolSet.prototype.forEach = function (cb) { + this.map.forEach(cb); + }; + SymbolSet.prototype.forEachEntry = function (cb) { + return ts.forEachEntry(this.map, cb); + }; + SymbolSet.prototype.clone = function () { + var clone = new SymbolSet(); + ts.copyEntries(this.map, clone.map); + return clone; + }; + return SymbolSet; + }()); + function isTopLevelDeclaration(node) { + return isNonVariableTopLevelDeclaration(node) && ts.isSourceFile(node.parent) || ts.isVariableDeclaration(node) && ts.isSourceFile(node.parent.parent.parent); + } + function sourceFileOfTopLevelDeclaration(node) { + return ts.isVariableDeclaration(node) ? node.parent.parent.parent : node.parent; + } + function isTopLevelDeclarationStatement(node) { + ts.Debug.assert(ts.isSourceFile(node.parent)); + return isNonVariableTopLevelDeclaration(node) || ts.isVariableStatement(node); + } + function isNonVariableTopLevelDeclaration(node) { + switch (node.kind) { + case 239 /* FunctionDeclaration */: + case 240 /* ClassDeclaration */: + case 244 /* ModuleDeclaration */: + case 243 /* EnumDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 241 /* InterfaceDeclaration */: + case 248 /* ImportEqualsDeclaration */: + return true; + default: + return false; + } + } + function forEachTopLevelDeclaration(statement, cb) { + switch (statement.kind) { + case 239 /* FunctionDeclaration */: + case 240 /* ClassDeclaration */: + case 244 /* ModuleDeclaration */: + case 243 /* EnumDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 241 /* InterfaceDeclaration */: + case 248 /* ImportEqualsDeclaration */: + return cb(statement); + case 219 /* VariableStatement */: + return ts.firstDefined(statement.declarationList.declarations, function (decl) { return forEachTopLevelDeclarationInBindingName(decl.name, cb); }); + case 221 /* ExpressionStatement */: { + var expression = statement.expression; + return ts.isBinaryExpression(expression) && ts.getAssignmentDeclarationKind(expression) === 1 /* ExportsProperty */ + ? cb(statement) + : undefined; + } + } + } + function forEachTopLevelDeclarationInBindingName(name, cb) { + switch (name.kind) { + case 72 /* Identifier */: + return cb(ts.cast(name.parent, function (x) { return ts.isVariableDeclaration(x) || ts.isBindingElement(x); })); + case 185 /* ArrayBindingPattern */: + case 184 /* ObjectBindingPattern */: + return ts.firstDefined(name.elements, function (em) { return ts.isOmittedExpression(em) ? undefined : forEachTopLevelDeclarationInBindingName(em.name, cb); }); + default: + return ts.Debug.assertNever(name); + } + } + function nameOfTopLevelDeclaration(d) { + return ts.isExpressionStatement(d) ? d.expression.left.name : ts.tryCast(d.name, ts.isIdentifier); + } + function getTopLevelDeclarationStatement(d) { + switch (d.kind) { + case 237 /* VariableDeclaration */: + return d.parent.parent; + case 186 /* BindingElement */: + return getTopLevelDeclarationStatement(ts.cast(d.parent.parent, function (p) { return ts.isVariableDeclaration(p) || ts.isBindingElement(p); })); + default: + return d; + } + } + function addExportToChanges(sourceFile, decl, changes, useEs6Exports) { + if (isExported(sourceFile, decl, useEs6Exports)) + return; + if (useEs6Exports) { + if (!ts.isExpressionStatement(decl)) + changes.insertExportModifier(sourceFile, decl); + } + else { + var names = getNamesToExportInCommonJS(decl); + if (names.length !== 0) + changes.insertNodesAfter(sourceFile, decl, names.map(createExportAssignment)); + } + } + function isExported(sourceFile, decl, useEs6Exports) { + if (useEs6Exports) { + return !ts.isExpressionStatement(decl) && ts.hasModifier(decl, 1 /* Export */); + } + else { + return getNamesToExportInCommonJS(decl).some(function (name) { return sourceFile.symbol.exports.has(ts.escapeLeadingUnderscores(name)); }); + } + } + function addExport(decl, useEs6Exports) { + return useEs6Exports ? [addEs6Export(decl)] : addCommonjsExport(decl); + } + function addEs6Export(d) { + var modifiers = ts.concatenate([ts.createModifier(85 /* ExportKeyword */)], d.modifiers); + switch (d.kind) { + case 239 /* FunctionDeclaration */: + return ts.updateFunctionDeclaration(d, d.decorators, modifiers, d.asteriskToken, d.name, d.typeParameters, d.parameters, d.type, d.body); + case 240 /* ClassDeclaration */: + return ts.updateClassDeclaration(d, d.decorators, modifiers, d.name, d.typeParameters, d.heritageClauses, d.members); + case 219 /* VariableStatement */: + return ts.updateVariableStatement(d, modifiers, d.declarationList); + case 244 /* ModuleDeclaration */: + return ts.updateModuleDeclaration(d, d.decorators, modifiers, d.name, d.body); + case 243 /* EnumDeclaration */: + return ts.updateEnumDeclaration(d, d.decorators, modifiers, d.name, d.members); + case 242 /* TypeAliasDeclaration */: + return ts.updateTypeAliasDeclaration(d, d.decorators, modifiers, d.name, d.typeParameters, d.type); + case 241 /* InterfaceDeclaration */: + return ts.updateInterfaceDeclaration(d, d.decorators, modifiers, d.name, d.typeParameters, d.heritageClauses, d.members); + case 248 /* ImportEqualsDeclaration */: + return ts.updateImportEqualsDeclaration(d, d.decorators, modifiers, d.name, d.moduleReference); + case 221 /* ExpressionStatement */: + return ts.Debug.fail(); // Shouldn't try to add 'export' keyword to `exports.x = ...` + default: + return ts.Debug.assertNever(d); + } + } + function addCommonjsExport(decl) { + return [decl].concat(getNamesToExportInCommonJS(decl).map(createExportAssignment)); + } + function getNamesToExportInCommonJS(decl) { + switch (decl.kind) { + case 239 /* FunctionDeclaration */: + case 240 /* ClassDeclaration */: + return [decl.name.text]; // TODO: GH#18217 + case 219 /* VariableStatement */: + return ts.mapDefined(decl.declarationList.declarations, function (d) { return ts.isIdentifier(d.name) ? d.name.text : undefined; }); + case 244 /* ModuleDeclaration */: + case 243 /* EnumDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 241 /* InterfaceDeclaration */: + case 248 /* ImportEqualsDeclaration */: + return ts.emptyArray; + case 221 /* ExpressionStatement */: + return ts.Debug.fail(); // Shouldn't try to add 'export' keyword to `exports.x = ...` + default: + return ts.Debug.assertNever(decl); + } + } + /** Creates `exports.x = x;` */ + function createExportAssignment(name) { + return ts.createExpressionStatement(ts.createBinary(ts.createPropertyAccess(ts.createIdentifier("exports"), ts.createIdentifier(name)), 59 /* EqualsToken */, ts.createIdentifier(name))); + } + })(refactor = ts.refactor || (ts.refactor = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var refactor; + (function (refactor) { + var addOrRemoveBracesToArrowFunction; + (function (addOrRemoveBracesToArrowFunction) { + var refactorName = "Add or remove braces in an arrow function"; + var refactorDescription = ts.Diagnostics.Add_or_remove_braces_in_an_arrow_function.message; + var addBracesActionName = "Add braces to arrow function"; + var removeBracesActionName = "Remove braces from arrow function"; + var addBracesActionDescription = ts.Diagnostics.Add_braces_to_arrow_function.message; + var removeBracesActionDescription = ts.Diagnostics.Remove_braces_from_arrow_function.message; + refactor.registerRefactor(refactorName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions }); + function getAvailableActions(context) { + var file = context.file, startPosition = context.startPosition; + var info = getConvertibleArrowFunctionAtPosition(file, startPosition); + if (!info) + return ts.emptyArray; + return [{ + name: refactorName, + description: refactorDescription, + actions: [ + info.addBraces ? + { + name: addBracesActionName, + description: addBracesActionDescription + } : { + name: removeBracesActionName, + description: removeBracesActionDescription + } + ] + }]; + } + function getEditsForAction(context, actionName) { + var file = context.file, startPosition = context.startPosition; + var info = getConvertibleArrowFunctionAtPosition(file, startPosition); + if (!info) + return undefined; + var expression = info.expression, returnStatement = info.returnStatement, func = info.func; + var body; + if (actionName === addBracesActionName) { + var returnStatement_1 = ts.createReturn(expression); + body = ts.createBlock([returnStatement_1], /* multiLine */ true); + ts.suppressLeadingAndTrailingTrivia(body); + ts.copyComments(expression, returnStatement_1, file, 3 /* MultiLineCommentTrivia */, /* hasTrailingNewLine */ true); + } + else if (actionName === removeBracesActionName && returnStatement) { + var actualExpression = expression || ts.createVoidZero(); + body = needsParentheses(actualExpression) ? ts.createParen(actualExpression) : actualExpression; + ts.suppressLeadingAndTrailingTrivia(body); + ts.copyComments(returnStatement, body, file, 3 /* MultiLineCommentTrivia */, /* hasTrailingNewLine */ false); + } + else { + ts.Debug.fail("invalid action"); + } + var edits = ts.textChanges.ChangeTracker.with(context, function (t) { return t.replaceNode(file, func.body, body); }); + return { renameFilename: undefined, renameLocation: undefined, edits: edits }; + } + function needsParentheses(expression) { + return ts.isBinaryExpression(expression) && expression.operatorToken.kind === 27 /* CommaToken */ || ts.isObjectLiteralExpression(expression); + } + function getConvertibleArrowFunctionAtPosition(file, startPosition) { + var node = ts.getTokenAtPosition(file, startPosition); + var func = ts.getContainingFunction(node); + if (!func || !ts.isArrowFunction(func) || (!ts.rangeContainsRange(func, node) || ts.rangeContainsRange(func.body, node))) + return undefined; + if (ts.isExpression(func.body)) { + return { + func: func, + addBraces: true, + expression: func.body + }; + } + else if (func.body.statements.length === 1) { + var firstStatement = ts.first(func.body.statements); + if (ts.isReturnStatement(firstStatement)) { + return { + func: func, + addBraces: false, + expression: firstStatement.expression, + returnStatement: firstStatement + }; + } + } + return undefined; + } + })(addOrRemoveBracesToArrowFunction = refactor.addOrRemoveBracesToArrowFunction || (refactor.addOrRemoveBracesToArrowFunction = {})); + })(refactor = ts.refactor || (ts.refactor = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + /** The version of the language service API */ + ts.servicesVersion = "0.8"; + function createNode(kind, pos, end, parent) { + var node = ts.isNodeKind(kind) ? new NodeObject(kind, pos, end) : + kind === 72 /* Identifier */ ? new IdentifierObject(72 /* Identifier */, pos, end) : + new TokenObject(kind, pos, end); + node.parent = parent; + node.flags = parent.flags & 12679168 /* ContextFlags */; + return node; + } + var NodeObject = /** @class */ (function () { + function NodeObject(kind, pos, end) { + this.pos = pos; + this.end = end; + this.flags = 0 /* None */; + this.transformFlags = undefined; // TODO: GH#18217 + this.parent = undefined; + this.kind = kind; + } + NodeObject.prototype.assertHasRealPosition = function (message) { + // tslint:disable-next-line:debug-assert + ts.Debug.assert(!ts.positionIsSynthesized(this.pos) && !ts.positionIsSynthesized(this.end), message || "Node must have a real position for this operation"); + }; + NodeObject.prototype.getSourceFile = function () { + return ts.getSourceFileOfNode(this); + }; + NodeObject.prototype.getStart = function (sourceFile, includeJsDocComment) { + this.assertHasRealPosition(); + return ts.getTokenPosOfNode(this, sourceFile, includeJsDocComment); + }; + NodeObject.prototype.getFullStart = function () { + this.assertHasRealPosition(); + return this.pos; + }; + NodeObject.prototype.getEnd = function () { + this.assertHasRealPosition(); + return this.end; + }; + NodeObject.prototype.getWidth = function (sourceFile) { + this.assertHasRealPosition(); + return this.getEnd() - this.getStart(sourceFile); + }; + NodeObject.prototype.getFullWidth = function () { + this.assertHasRealPosition(); + return this.end - this.pos; + }; + NodeObject.prototype.getLeadingTriviaWidth = function (sourceFile) { + this.assertHasRealPosition(); + return this.getStart(sourceFile) - this.pos; + }; + NodeObject.prototype.getFullText = function (sourceFile) { + this.assertHasRealPosition(); + return (sourceFile || this.getSourceFile()).text.substring(this.pos, this.end); + }; + NodeObject.prototype.getText = function (sourceFile) { + this.assertHasRealPosition(); + if (!sourceFile) { + sourceFile = this.getSourceFile(); + } + return sourceFile.text.substring(this.getStart(sourceFile), this.getEnd()); + }; + NodeObject.prototype.getChildCount = function (sourceFile) { + return this.getChildren(sourceFile).length; + }; + NodeObject.prototype.getChildAt = function (index, sourceFile) { + return this.getChildren(sourceFile)[index]; + }; + NodeObject.prototype.getChildren = function (sourceFile) { + this.assertHasRealPosition("Node without a real position cannot be scanned and thus has no token nodes - use forEachChild and collect the result if that's fine"); + return this._children || (this._children = createChildren(this, sourceFile)); + }; + NodeObject.prototype.getFirstToken = function (sourceFile) { + this.assertHasRealPosition(); + var children = this.getChildren(sourceFile); + if (!children.length) { + return undefined; + } + var child = ts.find(children, function (kid) { return kid.kind < 283 /* FirstJSDocNode */ || kid.kind > 305 /* LastJSDocNode */; }); + return child.kind < 148 /* FirstNode */ ? + child : + child.getFirstToken(sourceFile); + }; + NodeObject.prototype.getLastToken = function (sourceFile) { + this.assertHasRealPosition(); + var children = this.getChildren(sourceFile); + var child = ts.lastOrUndefined(children); + if (!child) { + return undefined; + } + return child.kind < 148 /* FirstNode */ ? child : child.getLastToken(sourceFile); + }; + NodeObject.prototype.forEachChild = function (cbNode, cbNodeArray) { + return ts.forEachChild(this, cbNode, cbNodeArray); + }; + return NodeObject; + }()); + function createChildren(node, sourceFile) { + if (!ts.isNodeKind(node.kind)) { + return ts.emptyArray; + } + var children = []; + if (ts.isJSDocCommentContainingNode(node)) { + /** Don't add trivia for "tokens" since this is in a comment. */ + node.forEachChild(function (child) { children.push(child); }); + return children; + } + ts.scanner.setText((sourceFile || node.getSourceFile()).text); + var pos = node.pos; + var processNode = function (child) { + addSyntheticNodes(children, pos, child.pos, node); + children.push(child); + pos = child.end; + }; + var processNodes = function (nodes) { + addSyntheticNodes(children, pos, nodes.pos, node); + children.push(createSyntaxList(nodes, node)); + pos = nodes.end; + }; + // jsDocComments need to be the first children + ts.forEach(node.jsDoc, processNode); + // For syntactic classifications, all trivia are classified together, including jsdoc comments. + // For that to work, the jsdoc comments should still be the leading trivia of the first child. + // Restoring the scanner position ensures that. + pos = node.pos; + node.forEachChild(processNode, processNodes); + addSyntheticNodes(children, pos, node.end, node); + ts.scanner.setText(undefined); + return children; + } + function addSyntheticNodes(nodes, pos, end, parent) { + ts.scanner.setTextPos(pos); + while (pos < end) { + var token = ts.scanner.scan(); + var textPos = ts.scanner.getTextPos(); + if (textPos <= end) { + if (token === 72 /* Identifier */) { + ts.Debug.fail("Did not expect " + ts.Debug.showSyntaxKind(parent) + " to have an Identifier in its trivia"); + } + nodes.push(createNode(token, pos, textPos, parent)); + } + pos = textPos; + if (token === 1 /* EndOfFileToken */) { + break; + } + } + } + function createSyntaxList(nodes, parent) { + var list = createNode(306 /* SyntaxList */, nodes.pos, nodes.end, parent); + list._children = []; + var pos = nodes.pos; + for (var _i = 0, nodes_7 = nodes; _i < nodes_7.length; _i++) { + var node = nodes_7[_i]; + addSyntheticNodes(list._children, pos, node.pos, parent); + list._children.push(node); + pos = node.end; + } + addSyntheticNodes(list._children, pos, nodes.end, parent); + return list; + } + var TokenOrIdentifierObject = /** @class */ (function () { + function TokenOrIdentifierObject(pos, end) { + // Set properties in same order as NodeObject + this.pos = pos; + this.end = end; + this.flags = 0 /* None */; + this.parent = undefined; + } + TokenOrIdentifierObject.prototype.getSourceFile = function () { + return ts.getSourceFileOfNode(this); + }; + TokenOrIdentifierObject.prototype.getStart = function (sourceFile, includeJsDocComment) { + return ts.getTokenPosOfNode(this, sourceFile, includeJsDocComment); + }; + TokenOrIdentifierObject.prototype.getFullStart = function () { + return this.pos; + }; + TokenOrIdentifierObject.prototype.getEnd = function () { + return this.end; + }; + TokenOrIdentifierObject.prototype.getWidth = function (sourceFile) { + return this.getEnd() - this.getStart(sourceFile); + }; + TokenOrIdentifierObject.prototype.getFullWidth = function () { + return this.end - this.pos; + }; + TokenOrIdentifierObject.prototype.getLeadingTriviaWidth = function (sourceFile) { + return this.getStart(sourceFile) - this.pos; + }; + TokenOrIdentifierObject.prototype.getFullText = function (sourceFile) { + return (sourceFile || this.getSourceFile()).text.substring(this.pos, this.end); + }; + TokenOrIdentifierObject.prototype.getText = function (sourceFile) { + if (!sourceFile) { + sourceFile = this.getSourceFile(); + } + return sourceFile.text.substring(this.getStart(sourceFile), this.getEnd()); + }; + TokenOrIdentifierObject.prototype.getChildCount = function () { + return 0; + }; + TokenOrIdentifierObject.prototype.getChildAt = function () { + return undefined; // TODO: GH#18217 + }; + TokenOrIdentifierObject.prototype.getChildren = function () { + return this.kind === 1 /* EndOfFileToken */ ? this.jsDoc || ts.emptyArray : ts.emptyArray; + }; + TokenOrIdentifierObject.prototype.getFirstToken = function () { + return undefined; + }; + TokenOrIdentifierObject.prototype.getLastToken = function () { + return undefined; + }; + TokenOrIdentifierObject.prototype.forEachChild = function () { + return undefined; + }; + return TokenOrIdentifierObject; + }()); + var SymbolObject = /** @class */ (function () { + function SymbolObject(flags, name) { + this.flags = flags; + this.escapedName = name; + } + SymbolObject.prototype.getFlags = function () { + return this.flags; + }; + Object.defineProperty(SymbolObject.prototype, "name", { + get: function () { + return ts.symbolName(this); + }, + enumerable: true, + configurable: true + }); + SymbolObject.prototype.getEscapedName = function () { + return this.escapedName; + }; + SymbolObject.prototype.getName = function () { + return this.name; + }; + SymbolObject.prototype.getDeclarations = function () { + return this.declarations; + }; + SymbolObject.prototype.getDocumentationComment = function (checker) { + if (!this.documentationComment) { + this.documentationComment = ts.emptyArray; // Set temporarily to avoid an infinite loop finding inherited docs + this.documentationComment = getDocumentationComment(this.declarations, checker); + } + return this.documentationComment; + }; + SymbolObject.prototype.getJsDocTags = function () { + if (this.tags === undefined) { + this.tags = ts.JsDoc.getJsDocTagsFromDeclarations(this.declarations); + } + return this.tags; + }; + return SymbolObject; + }()); + var TokenObject = /** @class */ (function (_super) { + __extends(TokenObject, _super); + function TokenObject(kind, pos, end) { + var _this = _super.call(this, pos, end) || this; + _this.kind = kind; + return _this; + } + return TokenObject; + }(TokenOrIdentifierObject)); + var IdentifierObject = /** @class */ (function (_super) { + __extends(IdentifierObject, _super); + function IdentifierObject(_kind, pos, end) { + return _super.call(this, pos, end) || this; + } + Object.defineProperty(IdentifierObject.prototype, "text", { + get: function () { + return ts.idText(this); + }, + enumerable: true, + configurable: true + }); + return IdentifierObject; + }(TokenOrIdentifierObject)); + IdentifierObject.prototype.kind = 72 /* Identifier */; + var TypeObject = /** @class */ (function () { + function TypeObject(checker, flags) { + this.checker = checker; + this.flags = flags; + } + TypeObject.prototype.getFlags = function () { + return this.flags; + }; + TypeObject.prototype.getSymbol = function () { + return this.symbol; + }; + TypeObject.prototype.getProperties = function () { + return this.checker.getPropertiesOfType(this); + }; + TypeObject.prototype.getProperty = function (propertyName) { + return this.checker.getPropertyOfType(this, propertyName); + }; + TypeObject.prototype.getApparentProperties = function () { + return this.checker.getAugmentedPropertiesOfType(this); + }; + TypeObject.prototype.getCallSignatures = function () { + return this.checker.getSignaturesOfType(this, 0 /* Call */); + }; + TypeObject.prototype.getConstructSignatures = function () { + return this.checker.getSignaturesOfType(this, 1 /* Construct */); + }; + TypeObject.prototype.getStringIndexType = function () { + return this.checker.getIndexTypeOfType(this, 0 /* String */); + }; + TypeObject.prototype.getNumberIndexType = function () { + return this.checker.getIndexTypeOfType(this, 1 /* Number */); + }; + TypeObject.prototype.getBaseTypes = function () { + return this.isClassOrInterface() ? this.checker.getBaseTypes(this) : undefined; + }; + TypeObject.prototype.getNonNullableType = function () { + return this.checker.getNonNullableType(this); + }; + TypeObject.prototype.getConstraint = function () { + return this.checker.getBaseConstraintOfType(this); + }; + TypeObject.prototype.getDefault = function () { + return this.checker.getDefaultFromTypeParameter(this); + }; + TypeObject.prototype.isUnion = function () { + return !!(this.flags & 1048576 /* Union */); + }; + TypeObject.prototype.isIntersection = function () { + return !!(this.flags & 2097152 /* Intersection */); + }; + TypeObject.prototype.isUnionOrIntersection = function () { + return !!(this.flags & 3145728 /* UnionOrIntersection */); + }; + TypeObject.prototype.isLiteral = function () { + return !!(this.flags & 384 /* StringOrNumberLiteral */); + }; + TypeObject.prototype.isStringLiteral = function () { + return !!(this.flags & 128 /* StringLiteral */); + }; + TypeObject.prototype.isNumberLiteral = function () { + return !!(this.flags & 256 /* NumberLiteral */); + }; + TypeObject.prototype.isTypeParameter = function () { + return !!(this.flags & 262144 /* TypeParameter */); + }; + TypeObject.prototype.isClassOrInterface = function () { + return !!(ts.getObjectFlags(this) & 3 /* ClassOrInterface */); + }; + TypeObject.prototype.isClass = function () { + return !!(ts.getObjectFlags(this) & 1 /* Class */); + }; + return TypeObject; + }()); + var SignatureObject = /** @class */ (function () { + function SignatureObject(checker) { + this.checker = checker; + } + SignatureObject.prototype.getDeclaration = function () { + return this.declaration; + }; + SignatureObject.prototype.getTypeParameters = function () { + return this.typeParameters; + }; + SignatureObject.prototype.getParameters = function () { + return this.parameters; + }; + SignatureObject.prototype.getReturnType = function () { + return this.checker.getReturnTypeOfSignature(this); + }; + SignatureObject.prototype.getDocumentationComment = function () { + return this.documentationComment || (this.documentationComment = getDocumentationComment(ts.singleElementArray(this.declaration), this.checker)); + }; + SignatureObject.prototype.getJsDocTags = function () { + if (this.jsDocTags === undefined) { + this.jsDocTags = this.declaration ? ts.JsDoc.getJsDocTagsFromDeclarations([this.declaration]) : []; + } + return this.jsDocTags; + }; + return SignatureObject; + }()); + /** + * Returns whether or not the given node has a JSDoc "inheritDoc" tag on it. + * @param node the Node in question. + * @returns `true` if `node` has a JSDoc "inheritDoc" tag on it, otherwise `false`. + */ + function hasJSDocInheritDocTag(node) { + return ts.getJSDocTags(node).some(function (tag) { return tag.tagName.text === "inheritDoc"; }); + } + function getDocumentationComment(declarations, checker) { + if (!declarations) + return ts.emptyArray; + var doc = ts.JsDoc.getJsDocCommentsFromDeclarations(declarations); + if (doc.length === 0 || declarations.some(hasJSDocInheritDocTag)) { + for (var _i = 0, declarations_14 = declarations; _i < declarations_14.length; _i++) { + var declaration = declarations_14[_i]; + var inheritedDocs = findInheritedJSDocComments(declaration, declaration.symbol.name, checker); // TODO: GH#18217 + // TODO: GH#16312 Return a ReadonlyArray, avoid copying inheritedDocs + if (inheritedDocs) + doc = doc.length === 0 ? inheritedDocs.slice() : inheritedDocs.concat(ts.lineBreakPart(), doc); + } + } + return doc; + } + /** + * Attempts to find JSDoc comments for possibly-inherited properties. Checks superclasses then traverses + * implemented interfaces until a symbol is found with the same name and with documentation. + * @param declaration The possibly-inherited declaration to find comments for. + * @param propertyName The name of the possibly-inherited property. + * @param typeChecker A TypeChecker, used to find inherited properties. + * @returns A filled array of documentation comments if any were found, otherwise an empty array. + */ + function findInheritedJSDocComments(declaration, propertyName, typeChecker) { + return ts.firstDefined(declaration.parent ? ts.getAllSuperTypeNodes(declaration.parent) : ts.emptyArray, function (superTypeNode) { + var superType = typeChecker.getTypeAtLocation(superTypeNode); + var baseProperty = superType && typeChecker.getPropertyOfType(superType, propertyName); + var inheritedDocs = baseProperty && baseProperty.getDocumentationComment(typeChecker); + return inheritedDocs && inheritedDocs.length ? inheritedDocs : undefined; + }); + } + var SourceFileObject = /** @class */ (function (_super) { + __extends(SourceFileObject, _super); + function SourceFileObject(kind, pos, end) { + return _super.call(this, kind, pos, end) || this; + } + SourceFileObject.prototype.update = function (newText, textChangeRange) { + return ts.updateSourceFile(this, newText, textChangeRange); + }; + SourceFileObject.prototype.getLineAndCharacterOfPosition = function (position) { + return ts.getLineAndCharacterOfPosition(this, position); + }; + SourceFileObject.prototype.getLineStarts = function () { + return ts.getLineStarts(this); + }; + SourceFileObject.prototype.getPositionOfLineAndCharacter = function (line, character) { + return ts.getPositionOfLineAndCharacter(this, line, character); + }; + SourceFileObject.prototype.getLineEndOfPosition = function (pos) { + var line = this.getLineAndCharacterOfPosition(pos).line; + var lineStarts = this.getLineStarts(); + var lastCharPos; + if (line + 1 >= lineStarts.length) { + lastCharPos = this.getEnd(); + } + if (!lastCharPos) { + lastCharPos = lineStarts[line + 1] - 1; + } + var fullText = this.getFullText(); + // if the new line is "\r\n", we should return the last non-new-line-character position + return fullText[lastCharPos] === "\n" && fullText[lastCharPos - 1] === "\r" ? lastCharPos - 1 : lastCharPos; + }; + SourceFileObject.prototype.getNamedDeclarations = function () { + if (!this.namedDeclarations) { + this.namedDeclarations = this.computeNamedDeclarations(); + } + return this.namedDeclarations; + }; + SourceFileObject.prototype.computeNamedDeclarations = function () { + var result = ts.createMultiMap(); + this.forEachChild(visit); + return result; + function addDeclaration(declaration) { + var name = getDeclarationName(declaration); + if (name) { + result.add(name, declaration); + } + } + function getDeclarations(name) { + var declarations = result.get(name); + if (!declarations) { + result.set(name, declarations = []); + } + return declarations; + } + function getDeclarationName(declaration) { + var name = ts.getNonAssignedNameOfDeclaration(declaration); + return name && (ts.isComputedPropertyName(name) && ts.isPropertyAccessExpression(name.expression) ? name.expression.name.text + : ts.isPropertyName(name) ? ts.getNameFromPropertyName(name) : undefined); + } + function visit(node) { + switch (node.kind) { + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + var functionDeclaration = node; + var declarationName = getDeclarationName(functionDeclaration); + if (declarationName) { + var declarations = getDeclarations(declarationName); + var lastDeclaration = ts.lastOrUndefined(declarations); + // Check whether this declaration belongs to an "overload group". + if (lastDeclaration && functionDeclaration.parent === lastDeclaration.parent && functionDeclaration.symbol === lastDeclaration.symbol) { + // Overwrite the last declaration if it was an overload + // and this one is an implementation. + if (functionDeclaration.body && !lastDeclaration.body) { + declarations[declarations.length - 1] = functionDeclaration; + } + } + else { + declarations.push(functionDeclaration); + } + } + ts.forEachChild(node, visit); + break; + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 241 /* InterfaceDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 243 /* EnumDeclaration */: + case 244 /* ModuleDeclaration */: + case 248 /* ImportEqualsDeclaration */: + case 257 /* ExportSpecifier */: + case 253 /* ImportSpecifier */: + case 250 /* ImportClause */: + case 251 /* NamespaceImport */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 168 /* TypeLiteral */: + addDeclaration(node); + ts.forEachChild(node, visit); + break; + case 151 /* Parameter */: + // Only consider parameter properties + if (!ts.hasModifier(node, 92 /* ParameterPropertyModifier */)) { + break; + } + // falls through + case 237 /* VariableDeclaration */: + case 186 /* BindingElement */: { + var decl = node; + if (ts.isBindingPattern(decl.name)) { + ts.forEachChild(decl.name, visit); + break; + } + if (decl.initializer) { + visit(decl.initializer); + } + } + // falls through + case 278 /* EnumMember */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + addDeclaration(node); + break; + case 255 /* ExportDeclaration */: + // Handle named exports case e.g.: + // export {a, b as B} from "mod"; + if (node.exportClause) { + ts.forEach(node.exportClause.elements, visit); + } + break; + case 249 /* ImportDeclaration */: + var importClause = node.importClause; + if (importClause) { + // Handle default import case e.g.: + // import d from "mod"; + if (importClause.name) { + addDeclaration(importClause.name); + } + // Handle named bindings in imports e.g.: + // import * as NS from "mod"; + // import {a, b as B} from "mod"; + if (importClause.namedBindings) { + if (importClause.namedBindings.kind === 251 /* NamespaceImport */) { + addDeclaration(importClause.namedBindings); + } + else { + ts.forEach(importClause.namedBindings.elements, visit); + } + } + } + break; + case 204 /* BinaryExpression */: + if (ts.getAssignmentDeclarationKind(node) !== 0 /* None */) { + addDeclaration(node); + } + // falls through + default: + ts.forEachChild(node, visit); + } + } + }; + return SourceFileObject; + }(NodeObject)); + var SourceMapSourceObject = /** @class */ (function () { + function SourceMapSourceObject(fileName, text, skipTrivia) { + this.fileName = fileName; + this.text = text; + this.skipTrivia = skipTrivia; + } + SourceMapSourceObject.prototype.getLineAndCharacterOfPosition = function (pos) { + return ts.getLineAndCharacterOfPosition(this, pos); + }; + return SourceMapSourceObject; + }()); + function getServicesObjectAllocator() { + return { + getNodeConstructor: function () { return NodeObject; }, + getTokenConstructor: function () { return TokenObject; }, + getIdentifierConstructor: function () { return IdentifierObject; }, + getSourceFileConstructor: function () { return SourceFileObject; }, + getSymbolConstructor: function () { return SymbolObject; }, + getTypeConstructor: function () { return TypeObject; }, + getSignatureConstructor: function () { return SignatureObject; }, + getSourceMapSourceConstructor: function () { return SourceMapSourceObject; }, + }; + } + function toEditorSettings(optionsAsMap) { + var allPropertiesAreCamelCased = true; + for (var key in optionsAsMap) { + if (ts.hasProperty(optionsAsMap, key) && !isCamelCase(key)) { + allPropertiesAreCamelCased = false; + break; + } + } + if (allPropertiesAreCamelCased) { + return optionsAsMap; + } + var settings = {}; + for (var key in optionsAsMap) { + if (ts.hasProperty(optionsAsMap, key)) { + var newKey = isCamelCase(key) ? key : key.charAt(0).toLowerCase() + key.substr(1); + settings[newKey] = optionsAsMap[key]; + } + } + return settings; + } + ts.toEditorSettings = toEditorSettings; + function isCamelCase(s) { + return !s.length || s.charAt(0) === s.charAt(0).toLowerCase(); + } + function displayPartsToString(displayParts) { + if (displayParts) { + return ts.map(displayParts, function (displayPart) { return displayPart.text; }).join(""); + } + return ""; + } + ts.displayPartsToString = displayPartsToString; + function getDefaultCompilerOptions() { + // Always default to "ScriptTarget.ES5" for the language service + return { + target: 1 /* ES5 */, + jsx: 1 /* Preserve */ + }; + } + ts.getDefaultCompilerOptions = getDefaultCompilerOptions; + function getSupportedCodeFixes() { + return ts.codefix.getSupportedErrorCodes(); + } + ts.getSupportedCodeFixes = getSupportedCodeFixes; + // Cache host information about script Should be refreshed + // at each language service public entry point, since we don't know when + // the set of scripts handled by the host changes. + var HostCache = /** @class */ (function () { + function HostCache(host, getCanonicalFileName) { + this.host = host; + // script id => script index + this.currentDirectory = host.getCurrentDirectory(); + this.fileNameToEntry = ts.createMap(); + // Initialize the list with the root file names + var rootFileNames = host.getScriptFileNames(); + for (var _i = 0, rootFileNames_1 = rootFileNames; _i < rootFileNames_1.length; _i++) { + var fileName = rootFileNames_1[_i]; + this.createEntry(fileName, ts.toPath(fileName, this.currentDirectory, getCanonicalFileName)); + } + // store the compilation settings + this._compilationSettings = host.getCompilationSettings() || getDefaultCompilerOptions(); + } + HostCache.prototype.compilationSettings = function () { + return this._compilationSettings; + }; + HostCache.prototype.getProjectReferences = function () { + return this.host.getProjectReferences && this.host.getProjectReferences(); + }; + HostCache.prototype.createEntry = function (fileName, path) { + var entry; + var scriptSnapshot = this.host.getScriptSnapshot(fileName); + if (scriptSnapshot) { + entry = { + hostFileName: fileName, + version: this.host.getScriptVersion(fileName), + scriptSnapshot: scriptSnapshot, + scriptKind: ts.getScriptKind(fileName, this.host) + }; + } + else { + entry = fileName; + } + this.fileNameToEntry.set(path, entry); + return entry; + }; + HostCache.prototype.getEntryByPath = function (path) { + return this.fileNameToEntry.get(path); + }; + HostCache.prototype.getHostFileInformation = function (path) { + var entry = this.fileNameToEntry.get(path); + return !ts.isString(entry) ? entry : undefined; + }; + HostCache.prototype.getOrCreateEntryByPath = function (fileName, path) { + var info = this.getEntryByPath(path) || this.createEntry(fileName, path); + return ts.isString(info) ? undefined : info; // TODO: GH#18217 + }; + HostCache.prototype.getRootFileNames = function () { + var names = []; + this.fileNameToEntry.forEach(function (entry) { + if (ts.isString(entry)) { + names.push(entry); + } + else { + if (entry.scriptKind !== 6 /* JSON */) { + names.push(entry.hostFileName); + } + } + }); + return names; + }; + HostCache.prototype.getVersion = function (path) { + var file = this.getHostFileInformation(path); + return (file && file.version); // TODO: GH#18217 + }; + HostCache.prototype.getScriptSnapshot = function (path) { + var file = this.getHostFileInformation(path); + return (file && file.scriptSnapshot); // TODO: GH#18217 + }; + return HostCache; + }()); + var SyntaxTreeCache = /** @class */ (function () { + function SyntaxTreeCache(host) { + this.host = host; + } + SyntaxTreeCache.prototype.getCurrentSourceFile = function (fileName) { + var scriptSnapshot = this.host.getScriptSnapshot(fileName); + if (!scriptSnapshot) { + // The host does not know about this file. + throw new Error("Could not find file: '" + fileName + "'."); + } + var scriptKind = ts.getScriptKind(fileName, this.host); + var version = this.host.getScriptVersion(fileName); + var sourceFile; + if (this.currentFileName !== fileName) { + // This is a new file, just parse it + sourceFile = createLanguageServiceSourceFile(fileName, scriptSnapshot, 6 /* Latest */, version, /*setNodeParents*/ true, scriptKind); + } + else if (this.currentFileVersion !== version) { + // This is the same file, just a newer version. Incrementally parse the file. + var editRange = scriptSnapshot.getChangeRange(this.currentFileScriptSnapshot); + sourceFile = updateLanguageServiceSourceFile(this.currentSourceFile, scriptSnapshot, version, editRange); + } + if (sourceFile) { + // All done, ensure state is up to date + this.currentFileVersion = version; + this.currentFileName = fileName; + this.currentFileScriptSnapshot = scriptSnapshot; + this.currentSourceFile = sourceFile; + } + return this.currentSourceFile; + }; + return SyntaxTreeCache; + }()); + function setSourceFileFields(sourceFile, scriptSnapshot, version) { + sourceFile.version = version; + sourceFile.scriptSnapshot = scriptSnapshot; + } + function createLanguageServiceSourceFile(fileName, scriptSnapshot, scriptTarget, version, setNodeParents, scriptKind) { + var sourceFile = ts.createSourceFile(fileName, ts.getSnapshotText(scriptSnapshot), scriptTarget, setNodeParents, scriptKind); + setSourceFileFields(sourceFile, scriptSnapshot, version); + return sourceFile; + } + ts.createLanguageServiceSourceFile = createLanguageServiceSourceFile; + ts.disableIncrementalParsing = false; + function updateLanguageServiceSourceFile(sourceFile, scriptSnapshot, version, textChangeRange, aggressiveChecks) { + // If we were given a text change range, and our version or open-ness changed, then + // incrementally parse this file. + if (textChangeRange) { + if (version !== sourceFile.version) { + // Once incremental parsing is ready, then just call into this function. + if (!ts.disableIncrementalParsing) { + var newText = void 0; + // grab the fragment from the beginning of the original text to the beginning of the span + var prefix = textChangeRange.span.start !== 0 + ? sourceFile.text.substr(0, textChangeRange.span.start) + : ""; + // grab the fragment from the end of the span till the end of the original text + var suffix = ts.textSpanEnd(textChangeRange.span) !== sourceFile.text.length + ? sourceFile.text.substr(ts.textSpanEnd(textChangeRange.span)) + : ""; + if (textChangeRange.newLength === 0) { + // edit was a deletion - just combine prefix and suffix + newText = prefix && suffix ? prefix + suffix : prefix || suffix; + } + else { + // it was actual edit, fetch the fragment of new text that correspond to new span + var changedText = scriptSnapshot.getText(textChangeRange.span.start, textChangeRange.span.start + textChangeRange.newLength); + // combine prefix, changed text and suffix + newText = prefix && suffix + ? prefix + changedText + suffix + : prefix + ? (prefix + changedText) + : (changedText + suffix); + } + var newSourceFile = ts.updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks); + setSourceFileFields(newSourceFile, scriptSnapshot, version); + // after incremental parsing nameTable might not be up-to-date + // drop it so it can be lazily recreated later + newSourceFile.nameTable = undefined; + // dispose all resources held by old script snapshot + if (sourceFile !== newSourceFile && sourceFile.scriptSnapshot) { + if (sourceFile.scriptSnapshot.dispose) { + sourceFile.scriptSnapshot.dispose(); + } + sourceFile.scriptSnapshot = undefined; + } + return newSourceFile; + } + } + } + // Otherwise, just create a new source file. + return createLanguageServiceSourceFile(sourceFile.fileName, scriptSnapshot, sourceFile.languageVersion, version, /*setNodeParents*/ true, sourceFile.scriptKind); + } + ts.updateLanguageServiceSourceFile = updateLanguageServiceSourceFile; + var CancellationTokenObject = /** @class */ (function () { + function CancellationTokenObject(cancellationToken) { + this.cancellationToken = cancellationToken; + } + CancellationTokenObject.prototype.isCancellationRequested = function () { + return !!this.cancellationToken && this.cancellationToken.isCancellationRequested(); + }; + CancellationTokenObject.prototype.throwIfCancellationRequested = function () { + if (this.isCancellationRequested()) { + throw new ts.OperationCanceledException(); + } + }; + return CancellationTokenObject; + }()); + /* @internal */ + /** A cancellation that throttles calls to the host */ + var ThrottledCancellationToken = /** @class */ (function () { + function ThrottledCancellationToken(hostCancellationToken, throttleWaitMilliseconds) { + if (throttleWaitMilliseconds === void 0) { throttleWaitMilliseconds = 20; } + this.hostCancellationToken = hostCancellationToken; + this.throttleWaitMilliseconds = throttleWaitMilliseconds; + // Store when we last tried to cancel. Checking cancellation can be expensive (as we have + // to marshall over to the host layer). So we only bother actually checking once enough + // time has passed. + this.lastCancellationCheckTime = 0; + } + ThrottledCancellationToken.prototype.isCancellationRequested = function () { + var time = ts.timestamp(); + var duration = Math.abs(time - this.lastCancellationCheckTime); + if (duration >= this.throttleWaitMilliseconds) { + // Check no more than once every throttle wait milliseconds + this.lastCancellationCheckTime = time; + return this.hostCancellationToken.isCancellationRequested(); + } + return false; + }; + ThrottledCancellationToken.prototype.throwIfCancellationRequested = function () { + if (this.isCancellationRequested()) { + throw new ts.OperationCanceledException(); + } + }; + return ThrottledCancellationToken; + }()); + ts.ThrottledCancellationToken = ThrottledCancellationToken; + function createLanguageService(host, documentRegistry, syntaxOnly) { + if (documentRegistry === void 0) { documentRegistry = ts.createDocumentRegistry(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames(), host.getCurrentDirectory()); } + if (syntaxOnly === void 0) { syntaxOnly = false; } + var _a; + var syntaxTreeCache = new SyntaxTreeCache(host); + var program; + var lastProjectVersion; + var lastTypesRootVersion = 0; + var cancellationToken = new CancellationTokenObject(host.getCancellationToken && host.getCancellationToken()); + var currentDirectory = host.getCurrentDirectory(); + // Check if the localized messages json is set, otherwise query the host for it + if (!ts.localizedDiagnosticMessages && host.getLocalizedDiagnosticMessages) { + ts.localizedDiagnosticMessages = host.getLocalizedDiagnosticMessages(); + } + function log(message) { + if (host.log) { + host.log(message); + } + } + var useCaseSensitiveFileNames = ts.hostUsesCaseSensitiveFileNames(host); + var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); + var sourceMapper = ts.getSourceMapper(useCaseSensitiveFileNames, currentDirectory, log, host, function () { return program; }); + function getValidSourceFile(fileName) { + var sourceFile = program.getSourceFile(fileName); + if (!sourceFile) { + throw new Error("Could not find file: '" + fileName + "'."); + } + return sourceFile; + } + function synchronizeHostData() { + ts.Debug.assert(!syntaxOnly); + // perform fast check if host supports it + if (host.getProjectVersion) { + var hostProjectVersion = host.getProjectVersion(); + if (hostProjectVersion) { + if (lastProjectVersion === hostProjectVersion && !host.hasChangedAutomaticTypeDirectiveNames) { + return; + } + lastProjectVersion = hostProjectVersion; + } + } + var typeRootsVersion = host.getTypeRootsVersion ? host.getTypeRootsVersion() : 0; + if (lastTypesRootVersion !== typeRootsVersion) { + log("TypeRoots version has changed; provide new program"); + program = undefined; // TODO: GH#18217 + lastTypesRootVersion = typeRootsVersion; + } + // Get a fresh cache of the host information + var hostCache = new HostCache(host, getCanonicalFileName); + var rootFileNames = hostCache.getRootFileNames(); + var hasInvalidatedResolution = host.hasInvalidatedResolution || ts.returnFalse; + var projectReferences = hostCache.getProjectReferences(); + // If the program is already up-to-date, we can reuse it + if (ts.isProgramUptoDate(program, rootFileNames, hostCache.compilationSettings(), function (path) { return hostCache.getVersion(path); }, fileExists, hasInvalidatedResolution, !!host.hasChangedAutomaticTypeDirectiveNames, projectReferences)) { + return; + } + // IMPORTANT - It is critical from this moment onward that we do not check + // cancellation tokens. We are about to mutate source files from a previous program + // instance. If we cancel midway through, we may end up in an inconsistent state where + // the program points to old source files that have been invalidated because of + // incremental parsing. + var newSettings = hostCache.compilationSettings(); + // Now create a new compiler + var compilerHost = { + getSourceFile: getOrCreateSourceFile, + getSourceFileByPath: getOrCreateSourceFileByPath, + getCancellationToken: function () { return cancellationToken; }, + getCanonicalFileName: getCanonicalFileName, + useCaseSensitiveFileNames: function () { return useCaseSensitiveFileNames; }, + getNewLine: function () { return ts.getNewLineCharacter(newSettings, function () { return ts.getNewLineOrDefaultFromHost(host); }); }, + getDefaultLibFileName: function (options) { return host.getDefaultLibFileName(options); }, + writeFile: ts.noop, + getCurrentDirectory: function () { return currentDirectory; }, + fileExists: fileExists, + readFile: function (fileName) { + // stub missing host functionality + var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); + var entry = hostCache && hostCache.getEntryByPath(path); + if (entry) { + return ts.isString(entry) ? undefined : ts.getSnapshotText(entry.scriptSnapshot); + } + return host.readFile && host.readFile(fileName); + }, + realpath: host.realpath && (function (path) { return host.realpath(path); }), + directoryExists: function (directoryName) { + return ts.directoryProbablyExists(directoryName, host); + }, + getDirectories: function (path) { + return host.getDirectories ? host.getDirectories(path) : []; + }, + readDirectory: function (path, extensions, exclude, include, depth) { + ts.Debug.assertDefined(host.readDirectory, "'LanguageServiceHost.readDirectory' must be implemented to correctly process 'projectReferences'"); + return host.readDirectory(path, extensions, exclude, include, depth); + }, + onReleaseOldSourceFile: onReleaseOldSourceFile, + hasInvalidatedResolution: hasInvalidatedResolution, + hasChangedAutomaticTypeDirectiveNames: host.hasChangedAutomaticTypeDirectiveNames + }; + if (host.trace) { + compilerHost.trace = function (message) { return host.trace(message); }; + } + if (host.resolveModuleNames) { + compilerHost.resolveModuleNames = function (moduleNames, containingFile, reusedNames, redirectedReference) { return host.resolveModuleNames(moduleNames, containingFile, reusedNames, redirectedReference); }; + } + if (host.resolveTypeReferenceDirectives) { + compilerHost.resolveTypeReferenceDirectives = function (typeReferenceDirectiveNames, containingFile, redirectedReference) { + return host.resolveTypeReferenceDirectives(typeReferenceDirectiveNames, containingFile, redirectedReference); + }; + } + var documentRegistryBucketKey = documentRegistry.getKeyForCompilationSettings(newSettings); + var options = { + rootNames: rootFileNames, + options: newSettings, + host: compilerHost, + oldProgram: program, + projectReferences: projectReferences + }; + program = ts.createProgram(options); + // hostCache is captured in the closure for 'getOrCreateSourceFile' but it should not be used past this point. + // It needs to be cleared to allow all collected snapshots to be released + hostCache = undefined; + // We reset this cache on structure invalidation so we don't hold on to outdated files for long; however we can't use the `compilerHost` above, + // Because it only functions until `hostCache` is cleared, while we'll potentially need the functionality to lazily read sourcemap files during + // the course of whatever called `synchronizeHostData` + sourceMapper.clearCache(); + // Make sure all the nodes in the program are both bound, and have their parent + // pointers set property. + program.getTypeChecker(); + return; + function fileExists(fileName) { + var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); + var entry = hostCache && hostCache.getEntryByPath(path); + return entry ? + !ts.isString(entry) : + (!!host.fileExists && host.fileExists(fileName)); + } + // Release any files we have acquired in the old program but are + // not part of the new program. + function onReleaseOldSourceFile(oldSourceFile, oldOptions) { + var oldSettingsKey = documentRegistry.getKeyForCompilationSettings(oldOptions); + documentRegistry.releaseDocumentWithKey(oldSourceFile.resolvedPath, oldSettingsKey); + } + function getOrCreateSourceFile(fileName, languageVersion, onError, shouldCreateNewSourceFile) { + return getOrCreateSourceFileByPath(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), languageVersion, onError, shouldCreateNewSourceFile); + } + function getOrCreateSourceFileByPath(fileName, path, _languageVersion, _onError, shouldCreateNewSourceFile) { + ts.Debug.assert(hostCache !== undefined, "getOrCreateSourceFileByPath called after typical CompilerHost lifetime, check the callstack something with a reference to an old host."); + // The program is asking for this file, check first if the host can locate it. + // If the host can not locate the file, then it does not exist. return undefined + // to the program to allow reporting of errors for missing files. + var hostFileInformation = hostCache && hostCache.getOrCreateEntryByPath(fileName, path); + if (!hostFileInformation) { + return undefined; + } + // Check if the language version has changed since we last created a program; if they are the same, + // it is safe to reuse the sourceFiles; if not, then the shape of the AST can change, and the oldSourceFile + // can not be reused. we have to dump all syntax trees and create new ones. + if (!shouldCreateNewSourceFile) { + // Check if the old program had this file already + var oldSourceFile = program && program.getSourceFileByPath(path); + if (oldSourceFile) { + // We already had a source file for this file name. Go to the registry to + // ensure that we get the right up to date version of it. We need this to + // address the following race-condition. Specifically, say we have the following: + // + // LS1 + // \ + // DocumentRegistry + // / + // LS2 + // + // Each LS has a reference to file 'foo.ts' at version 1. LS2 then updates + // it's version of 'foo.ts' to version 2. This will cause LS2 and the + // DocumentRegistry to have version 2 of the document. HOwever, LS1 will + // have version 1. And *importantly* this source file will be *corrupt*. + // The act of creating version 2 of the file irrevocably damages the version + // 1 file. + // + // So, later when we call into LS1, we need to make sure that it doesn't use + // it's source file any more, and instead defers to DocumentRegistry to get + // either version 1, version 2 (or some other version) depending on what the + // host says should be used. + // We do not support the scenario where a host can modify a registered + // file's script kind, i.e. in one project some file is treated as ".ts" + // and in another as ".js" + ts.Debug.assertEqual(hostFileInformation.scriptKind, oldSourceFile.scriptKind, "Registered script kind should match new script kind.", path); + return documentRegistry.updateDocumentWithKey(fileName, path, newSettings, documentRegistryBucketKey, hostFileInformation.scriptSnapshot, hostFileInformation.version, hostFileInformation.scriptKind); + } + // We didn't already have the file. Fall through and acquire it from the registry. + } + // Could not find this file in the old program, create a new SourceFile for it. + return documentRegistry.acquireDocumentWithKey(fileName, path, newSettings, documentRegistryBucketKey, hostFileInformation.scriptSnapshot, hostFileInformation.version, hostFileInformation.scriptKind); + } + } + // TODO: GH#18217 frequently asserted as defined + function getProgram() { + if (syntaxOnly) { + ts.Debug.assert(program === undefined); + return undefined; + } + synchronizeHostData(); + return program; + } + function cleanupSemanticCache() { + program = undefined; // TODO: GH#18217 + } + function dispose() { + if (program) { + ts.forEach(program.getSourceFiles(), function (f) { + return documentRegistry.releaseDocument(f.fileName, program.getCompilerOptions()); + }); + program = undefined; // TODO: GH#18217 + } + host = undefined; + } + /// Diagnostics + function getSyntacticDiagnostics(fileName) { + synchronizeHostData(); + return program.getSyntacticDiagnostics(getValidSourceFile(fileName), cancellationToken).slice(); + } + /** + * getSemanticDiagnostics return array of Diagnostics. If '-d' is not enabled, only report semantic errors + * If '-d' enabled, report both semantic and emitter errors + */ + function getSemanticDiagnostics(fileName) { + synchronizeHostData(); + var targetSourceFile = getValidSourceFile(fileName); + // Only perform the action per file regardless of '-out' flag as LanguageServiceHost is expected to call this function per file. + // Therefore only get diagnostics for given file. + var semanticDiagnostics = program.getSemanticDiagnostics(targetSourceFile, cancellationToken); + if (!ts.getEmitDeclarations(program.getCompilerOptions())) { + return semanticDiagnostics.slice(); + } + // If '-d' is enabled, check for emitter error. One example of emitter error is export class implements non-export interface + var declarationDiagnostics = program.getDeclarationDiagnostics(targetSourceFile, cancellationToken); + return semanticDiagnostics.concat(declarationDiagnostics); + } + function getSuggestionDiagnostics(fileName) { + synchronizeHostData(); + return ts.computeSuggestionDiagnostics(getValidSourceFile(fileName), program, cancellationToken); + } + function getCompilerOptionsDiagnostics() { + synchronizeHostData(); + return program.getOptionsDiagnostics(cancellationToken).concat(program.getGlobalDiagnostics(cancellationToken)); + } + function getCompletionsAtPosition(fileName, position, options) { + if (options === void 0) { options = ts.emptyOptions; } + // Convert from deprecated options names to new names + var fullPreferences = __assign({}, ts.identity(options), { includeCompletionsForModuleExports: options.includeCompletionsForModuleExports || options.includeExternalModuleExports, includeCompletionsWithInsertText: options.includeCompletionsWithInsertText || options.includeInsertTextCompletions }); + synchronizeHostData(); + return ts.Completions.getCompletionsAtPosition(host, program, log, getValidSourceFile(fileName), position, fullPreferences, options.triggerCharacter); + } + function getCompletionEntryDetails(fileName, position, name, formattingOptions, source, preferences) { + if (preferences === void 0) { preferences = ts.emptyOptions; } + synchronizeHostData(); + return ts.Completions.getCompletionEntryDetails(program, log, getValidSourceFile(fileName), position, { name: name, source: source }, host, (formattingOptions && ts.formatting.getFormatContext(formattingOptions)), // TODO: GH#18217 + preferences, cancellationToken); + } + function getCompletionEntrySymbol(fileName, position, name, source) { + synchronizeHostData(); + return ts.Completions.getCompletionEntrySymbol(program, log, getValidSourceFile(fileName), position, { name: name, source: source }); + } + function getQuickInfoAtPosition(fileName, position) { + synchronizeHostData(); + var sourceFile = getValidSourceFile(fileName); + var node = ts.getTouchingPropertyName(sourceFile, position); + if (node === sourceFile) { + // Avoid giving quickInfo for the sourceFile as a whole. + return undefined; + } + var typeChecker = program.getTypeChecker(); + var symbol = getSymbolAtLocationForQuickInfo(node, typeChecker); + if (!symbol || typeChecker.isUnknownSymbol(symbol)) { + var type_7 = shouldGetType(sourceFile, node, position) ? typeChecker.getTypeAtLocation(node) : undefined; + return type_7 && { + kind: "" /* unknown */, + kindModifiers: "" /* none */, + textSpan: ts.createTextSpanFromNode(node, sourceFile), + displayParts: typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { return ts.typeToDisplayParts(typeChecker, type_7, ts.getContainerNode(node)); }), + documentation: type_7.symbol ? type_7.symbol.getDocumentationComment(typeChecker) : undefined, + tags: type_7.symbol ? type_7.symbol.getJsDocTags() : undefined + }; + } + var _a = typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { + return ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, ts.getContainerNode(node), node); + }), symbolKind = _a.symbolKind, displayParts = _a.displayParts, documentation = _a.documentation, tags = _a.tags; + return { + kind: symbolKind, + kindModifiers: ts.SymbolDisplay.getSymbolModifiers(symbol), + textSpan: ts.createTextSpanFromNode(node, sourceFile), + displayParts: displayParts, + documentation: documentation, + tags: tags, + }; + } + function shouldGetType(sourceFile, node, position) { + switch (node.kind) { + case 72 /* Identifier */: + return !ts.isLabelName(node) && !ts.isTagName(node); + case 189 /* PropertyAccessExpression */: + case 148 /* QualifiedName */: + // Don't return quickInfo if inside the comment in `a/**/.b` + return !ts.isInComment(sourceFile, position); + case 100 /* ThisKeyword */: + case 178 /* ThisType */: + case 98 /* SuperKeyword */: + return true; + default: + return false; + } + } + /// Goto definition + function getDefinitionAtPosition(fileName, position) { + synchronizeHostData(); + return ts.GoToDefinition.getDefinitionAtPosition(program, getValidSourceFile(fileName), position); + } + function getDefinitionAndBoundSpan(fileName, position) { + synchronizeHostData(); + return ts.GoToDefinition.getDefinitionAndBoundSpan(program, getValidSourceFile(fileName), position); + } + function getTypeDefinitionAtPosition(fileName, position) { + synchronizeHostData(); + return ts.GoToDefinition.getTypeDefinitionAtPosition(program.getTypeChecker(), getValidSourceFile(fileName), position); + } + /// Goto implementation + function getImplementationAtPosition(fileName, position) { + synchronizeHostData(); + return ts.FindAllReferences.getImplementationsAtPosition(program, cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position); + } + /// References and Occurrences + function getOccurrencesAtPosition(fileName, position) { + return ts.flatMap(getDocumentHighlights(fileName, position, [fileName]), function (entry) { return entry.highlightSpans.map(function (highlightSpan) { return ({ + fileName: entry.fileName, + textSpan: highlightSpan.textSpan, + isWriteAccess: highlightSpan.kind === "writtenReference" /* writtenReference */, + isDefinition: false, + isInString: highlightSpan.isInString, + }); }); }); + } + function getDocumentHighlights(fileName, position, filesToSearch) { + var normalizedFileName = ts.normalizePath(fileName); + ts.Debug.assert(filesToSearch.some(function (f) { return ts.normalizePath(f) === normalizedFileName; })); + synchronizeHostData(); + var sourceFilesToSearch = filesToSearch.map(getValidSourceFile); + var sourceFile = getValidSourceFile(fileName); + return ts.DocumentHighlights.getDocumentHighlights(program, cancellationToken, sourceFile, position, sourceFilesToSearch); + } + function findRenameLocations(fileName, position, findInStrings, findInComments) { + synchronizeHostData(); + var sourceFile = getValidSourceFile(fileName); + var node = ts.getTouchingPropertyName(sourceFile, position); + if (ts.isIdentifier(node) && (ts.isJsxOpeningElement(node.parent) || ts.isJsxClosingElement(node.parent)) && ts.isIntrinsicJsxName(node.escapedText)) { + var _a = node.parent.parent, openingElement = _a.openingElement, closingElement = _a.closingElement; + return [openingElement, closingElement].map(function (node) { + return ({ fileName: sourceFile.fileName, textSpan: ts.createTextSpanFromNode(node.tagName, sourceFile) }); + }); + } + else { + return getReferencesWorker(node, position, { findInStrings: findInStrings, findInComments: findInComments, isForRename: true }, ts.FindAllReferences.toRenameLocation); + } + } + function getReferencesAtPosition(fileName, position) { + synchronizeHostData(); + return getReferencesWorker(ts.getTouchingPropertyName(getValidSourceFile(fileName), position), position, {}, ts.FindAllReferences.toReferenceEntry); + } + function getReferencesWorker(node, position, options, cb) { + synchronizeHostData(); + // Exclude default library when renaming as commonly user don't want to change that file. + var sourceFiles = options && options.isForRename + ? program.getSourceFiles().filter(function (sourceFile) { return !program.isSourceFileDefaultLibrary(sourceFile); }) + : program.getSourceFiles(); + return ts.FindAllReferences.findReferenceOrRenameEntries(program, cancellationToken, sourceFiles, node, position, options, cb); + } + function findReferences(fileName, position) { + synchronizeHostData(); + return ts.FindAllReferences.findReferencedSymbols(program, cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position); + } + function getNavigateToItems(searchValue, maxResultCount, fileName, excludeDtsFiles) { + if (excludeDtsFiles === void 0) { excludeDtsFiles = false; } + synchronizeHostData(); + var sourceFiles = fileName ? [getValidSourceFile(fileName)] : program.getSourceFiles(); + return ts.NavigateTo.getNavigateToItems(sourceFiles, program.getTypeChecker(), cancellationToken, searchValue, maxResultCount, excludeDtsFiles); + } + function getEmitOutput(fileName, emitOnlyDtsFiles) { + if (emitOnlyDtsFiles === void 0) { emitOnlyDtsFiles = false; } + synchronizeHostData(); + var sourceFile = getValidSourceFile(fileName); + var customTransformers = host.getCustomTransformers && host.getCustomTransformers(); + return ts.getFileEmitOutput(program, sourceFile, emitOnlyDtsFiles, cancellationToken, customTransformers); + } + // Signature help + /** + * This is a semantic operation. + */ + function getSignatureHelpItems(fileName, position, _a) { + var triggerReason = (_a === void 0 ? ts.emptyOptions : _a).triggerReason; + synchronizeHostData(); + var sourceFile = getValidSourceFile(fileName); + return ts.SignatureHelp.getSignatureHelpItems(program, sourceFile, position, triggerReason, cancellationToken); + } + /// Syntactic features + function getNonBoundSourceFile(fileName) { + return syntaxTreeCache.getCurrentSourceFile(fileName); + } + function getNameOrDottedNameSpan(fileName, startPos, _endPos) { + var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); + // Get node at the location + var node = ts.getTouchingPropertyName(sourceFile, startPos); + if (node === sourceFile) { + return undefined; + } + switch (node.kind) { + case 189 /* PropertyAccessExpression */: + case 148 /* QualifiedName */: + case 10 /* StringLiteral */: + case 87 /* FalseKeyword */: + case 102 /* TrueKeyword */: + case 96 /* NullKeyword */: + case 98 /* SuperKeyword */: + case 100 /* ThisKeyword */: + case 178 /* ThisType */: + case 72 /* Identifier */: + break; + // Cant create the text span + default: + return undefined; + } + var nodeForStartPos = node; + while (true) { + if (ts.isRightSideOfPropertyAccess(nodeForStartPos) || ts.isRightSideOfQualifiedName(nodeForStartPos)) { + // If on the span is in right side of the the property or qualified name, return the span from the qualified name pos to end of this node + nodeForStartPos = nodeForStartPos.parent; + } + else if (ts.isNameOfModuleDeclaration(nodeForStartPos)) { + // If this is name of a module declarations, check if this is right side of dotted module name + // If parent of the module declaration which is parent of this node is module declaration and its body is the module declaration that this node is name of + // Then this name is name from dotted module + if (nodeForStartPos.parent.parent.kind === 244 /* ModuleDeclaration */ && + nodeForStartPos.parent.parent.body === nodeForStartPos.parent) { + // Use parent module declarations name for start pos + nodeForStartPos = nodeForStartPos.parent.parent.name; + } + else { + // We have to use this name for start pos + break; + } + } + else { + // Is not a member expression so we have found the node for start pos + break; + } + } + return ts.createTextSpanFromBounds(nodeForStartPos.getStart(), node.getEnd()); + } + function getBreakpointStatementAtPosition(fileName, position) { + // doesn't use compiler - no need to synchronize with host + var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); + return ts.BreakpointResolver.spanInSourceFileAtLocation(sourceFile, position); + } + function getNavigationBarItems(fileName) { + return ts.NavigationBar.getNavigationBarItems(syntaxTreeCache.getCurrentSourceFile(fileName), cancellationToken); + } + function getNavigationTree(fileName) { + return ts.NavigationBar.getNavigationTree(syntaxTreeCache.getCurrentSourceFile(fileName), cancellationToken); + } + function isTsOrTsxFile(fileName) { + var kind = ts.getScriptKind(fileName, host); + return kind === 3 /* TS */ || kind === 4 /* TSX */; + } + function getSemanticClassifications(fileName, span) { + if (!isTsOrTsxFile(fileName)) { + // do not run semantic classification on non-ts-or-tsx files + return []; + } + synchronizeHostData(); + return ts.getSemanticClassifications(program.getTypeChecker(), cancellationToken, getValidSourceFile(fileName), program.getClassifiableNames(), span); + } + function getEncodedSemanticClassifications(fileName, span) { + if (!isTsOrTsxFile(fileName)) { + // do not run semantic classification on non-ts-or-tsx files + return { spans: [], endOfLineState: 0 /* None */ }; + } + synchronizeHostData(); + return ts.getEncodedSemanticClassifications(program.getTypeChecker(), cancellationToken, getValidSourceFile(fileName), program.getClassifiableNames(), span); + } + function getSyntacticClassifications(fileName, span) { + // doesn't use compiler - no need to synchronize with host + return ts.getSyntacticClassifications(cancellationToken, syntaxTreeCache.getCurrentSourceFile(fileName), span); + } + function getEncodedSyntacticClassifications(fileName, span) { + // doesn't use compiler - no need to synchronize with host + return ts.getEncodedSyntacticClassifications(cancellationToken, syntaxTreeCache.getCurrentSourceFile(fileName), span); + } + function getOutliningSpans(fileName) { + // doesn't use compiler - no need to synchronize with host + var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); + return ts.OutliningElementsCollector.collectElements(sourceFile, cancellationToken); + } + var braceMatching = ts.createMapFromTemplate((_a = {}, + _a[18 /* OpenBraceToken */] = 19 /* CloseBraceToken */, + _a[20 /* OpenParenToken */] = 21 /* CloseParenToken */, + _a[22 /* OpenBracketToken */] = 23 /* CloseBracketToken */, + _a[30 /* GreaterThanToken */] = 28 /* LessThanToken */, + _a)); + braceMatching.forEach(function (value, key) { return braceMatching.set(value.toString(), Number(key)); }); + function getBraceMatchingAtPosition(fileName, position) { + var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); + var token = ts.getTouchingToken(sourceFile, position); + var matchKind = token.getStart(sourceFile) === position ? braceMatching.get(token.kind.toString()) : undefined; + var match = matchKind && ts.findChildOfKind(token.parent, matchKind, sourceFile); + // We want to order the braces when we return the result. + return match ? [ts.createTextSpanFromNode(token, sourceFile), ts.createTextSpanFromNode(match, sourceFile)].sort(function (a, b) { return a.start - b.start; }) : ts.emptyArray; + } + function getIndentationAtPosition(fileName, position, editorOptions) { + var start = ts.timestamp(); + var settings = toEditorSettings(editorOptions); + var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); + log("getIndentationAtPosition: getCurrentSourceFile: " + (ts.timestamp() - start)); + start = ts.timestamp(); + var result = ts.formatting.SmartIndenter.getIndentation(position, sourceFile, settings); + log("getIndentationAtPosition: computeIndentation : " + (ts.timestamp() - start)); + return result; + } + function getFormattingEditsForRange(fileName, start, end, options) { + var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); + return ts.formatting.formatSelection(start, end, sourceFile, ts.formatting.getFormatContext(toEditorSettings(options))); + } + function getFormattingEditsForDocument(fileName, options) { + return ts.formatting.formatDocument(syntaxTreeCache.getCurrentSourceFile(fileName), ts.formatting.getFormatContext(toEditorSettings(options))); + } + function getFormattingEditsAfterKeystroke(fileName, position, key, options) { + var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); + var formatContext = ts.formatting.getFormatContext(toEditorSettings(options)); + if (!ts.isInComment(sourceFile, position)) { + switch (key) { + case "{": + return ts.formatting.formatOnOpeningCurly(position, sourceFile, formatContext); + case "}": + return ts.formatting.formatOnClosingCurly(position, sourceFile, formatContext); + case ";": + return ts.formatting.formatOnSemicolon(position, sourceFile, formatContext); + case "\n": + return ts.formatting.formatOnEnter(position, sourceFile, formatContext); + } + } + return []; + } + function getCodeFixesAtPosition(fileName, start, end, errorCodes, formatOptions, preferences) { + if (preferences === void 0) { preferences = ts.emptyOptions; } + synchronizeHostData(); + var sourceFile = getValidSourceFile(fileName); + var span = ts.createTextSpanFromBounds(start, end); + var formatContext = ts.formatting.getFormatContext(formatOptions); + return ts.flatMap(ts.deduplicate(errorCodes, ts.equateValues, ts.compareValues), function (errorCode) { + cancellationToken.throwIfCancellationRequested(); + return ts.codefix.getFixes({ errorCode: errorCode, sourceFile: sourceFile, span: span, program: program, host: host, cancellationToken: cancellationToken, formatContext: formatContext, preferences: preferences }); + }); + } + function getCombinedCodeFix(scope, fixId, formatOptions, preferences) { + if (preferences === void 0) { preferences = ts.emptyOptions; } + synchronizeHostData(); + ts.Debug.assert(scope.type === "file"); + var sourceFile = getValidSourceFile(scope.fileName); + var formatContext = ts.formatting.getFormatContext(formatOptions); + return ts.codefix.getAllFixes({ fixId: fixId, sourceFile: sourceFile, program: program, host: host, cancellationToken: cancellationToken, formatContext: formatContext, preferences: preferences }); + } + function organizeImports(scope, formatOptions, preferences) { + if (preferences === void 0) { preferences = ts.emptyOptions; } + synchronizeHostData(); + ts.Debug.assert(scope.type === "file"); + var sourceFile = getValidSourceFile(scope.fileName); + var formatContext = ts.formatting.getFormatContext(formatOptions); + return ts.OrganizeImports.organizeImports(sourceFile, formatContext, host, program, preferences); + } + function getEditsForFileRename(oldFilePath, newFilePath, formatOptions, preferences) { + if (preferences === void 0) { preferences = ts.emptyOptions; } + return ts.getEditsForFileRename(getProgram(), oldFilePath, newFilePath, host, ts.formatting.getFormatContext(formatOptions), preferences, sourceMapper); + } + function applyCodeActionCommand(fileName, actionOrFormatSettingsOrUndefined) { + var action = typeof fileName === "string" ? actionOrFormatSettingsOrUndefined : fileName; + var formatSettings = typeof fileName !== "string" ? actionOrFormatSettingsOrUndefined : undefined; + return ts.isArray(action) ? Promise.all(action.map(function (a) { return applySingleCodeActionCommand(a, formatSettings); })) : applySingleCodeActionCommand(action, formatSettings); + } + function applySingleCodeActionCommand(action, formatSettings) { + var getPath = function (path) { return ts.toPath(path, currentDirectory, getCanonicalFileName); }; + switch (action.type) { + case "install package": + return host.installPackage + ? host.installPackage({ fileName: getPath(action.file), packageName: action.packageName }) + : Promise.reject("Host does not implement `installPackage`"); + case "generate types": { + var fileToGenerateTypesFor = action.fileToGenerateTypesFor, outputFileName_1 = action.outputFileName; + if (!host.inspectValue) + return Promise.reject("Host does not implement `installPackage`"); + var valueInfoPromise = host.inspectValue({ fileNameToRequire: fileToGenerateTypesFor }); + return valueInfoPromise.then(function (valueInfo) { + var fullOut = getPath(outputFileName_1); + host.writeFile(fullOut, ts.valueInfoToDeclarationFileText(valueInfo, formatSettings || ts.testFormatSettings)); // TODO: GH#18217 + return { successMessage: "Wrote types to '" + fullOut + "'" }; + }); + } + default: + return ts.Debug.assertNever(action); + } + } + function getDocCommentTemplateAtPosition(fileName, position) { + return ts.JsDoc.getDocCommentTemplateAtPosition(ts.getNewLineOrDefaultFromHost(host), syntaxTreeCache.getCurrentSourceFile(fileName), position); + } + function isValidBraceCompletionAtPosition(fileName, position, openingBrace) { + // '<' is currently not supported, figuring out if we're in a Generic Type vs. a comparison is too + // expensive to do during typing scenarios + // i.e. whether we're dealing with: + // var x = new foo<| ( with class foo{} ) + // or + // var y = 3 <| + if (openingBrace === 60 /* lessThan */) { + return false; + } + var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); + // Check if in a context where we don't want to perform any insertion + if (ts.isInString(sourceFile, position)) { + return false; + } + if (ts.isInsideJsxElementOrAttribute(sourceFile, position)) { + return openingBrace === 123 /* openBrace */; + } + if (ts.isInTemplateString(sourceFile, position)) { + return false; + } + switch (openingBrace) { + case 39 /* singleQuote */: + case 34 /* doubleQuote */: + case 96 /* backtick */: + return !ts.isInComment(sourceFile, position); + } + return true; + } + function getJsxClosingTagAtPosition(fileName, position) { + var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); + var token = ts.findPrecedingToken(position, sourceFile); + if (!token) + return undefined; + var element = token.kind === 30 /* GreaterThanToken */ && ts.isJsxOpeningElement(token.parent) ? token.parent.parent + : ts.isJsxText(token) ? token.parent : undefined; + if (element && isUnclosedTag(element)) { + return { newText: "" }; + } + } + function isUnclosedTag(_a) { + var openingElement = _a.openingElement, closingElement = _a.closingElement, parent = _a.parent; + return !ts.tagNamesAreEquivalent(openingElement.tagName, closingElement.tagName) || + ts.isJsxElement(parent) && ts.tagNamesAreEquivalent(openingElement.tagName, parent.openingElement.tagName) && isUnclosedTag(parent); + } + function getSpanOfEnclosingComment(fileName, position, onlyMultiLine) { + var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); + var range = ts.formatting.getRangeOfEnclosingComment(sourceFile, position); + return range && (!onlyMultiLine || range.kind === 3 /* MultiLineCommentTrivia */) ? ts.createTextSpanFromRange(range) : undefined; + } + function getTodoComments(fileName, descriptors) { + // Note: while getting todo comments seems like a syntactic operation, we actually + // treat it as a semantic operation here. This is because we expect our host to call + // this on every single file. If we treat this syntactically, then that will cause + // us to populate and throw away the tree in our syntax tree cache for each file. By + // treating this as a semantic operation, we can access any tree without throwing + // anything away. + synchronizeHostData(); + var sourceFile = getValidSourceFile(fileName); + cancellationToken.throwIfCancellationRequested(); + var fileContents = sourceFile.text; + var result = []; + // Exclude node_modules files as we don't want to show the todos of external libraries. + if (descriptors.length > 0 && !isNodeModulesFile(sourceFile.fileName)) { + var regExp = getTodoCommentsRegExp(); + var matchArray = void 0; + while (matchArray = regExp.exec(fileContents)) { + cancellationToken.throwIfCancellationRequested(); + // If we got a match, here is what the match array will look like. Say the source text is: + // + // " // hack 1" + // + // The result array with the regexp: will be: + // + // ["// hack 1", "// ", "hack 1", undefined, "hack"] + // + // Here are the relevant capture groups: + // 0) The full match for the entire regexp. + // 1) The preamble to the message portion. + // 2) The message portion. + // 3...N) The descriptor that was matched - by index. 'undefined' for each + // descriptor that didn't match. an actual value if it did match. + // + // i.e. 'undefined' in position 3 above means TODO(jason) didn't match. + // "hack" in position 4 means HACK did match. + var firstDescriptorCaptureIndex = 3; + ts.Debug.assert(matchArray.length === descriptors.length + firstDescriptorCaptureIndex); + var preamble = matchArray[1]; + var matchPosition = matchArray.index + preamble.length; + // OK, we have found a match in the file. This is only an acceptable match if + // it is contained within a comment. + if (!ts.isInComment(sourceFile, matchPosition)) { + continue; + } + var descriptor = void 0; + for (var i = 0; i < descriptors.length; i++) { + if (matchArray[i + firstDescriptorCaptureIndex]) { + descriptor = descriptors[i]; + } + } + if (descriptor === undefined) + return ts.Debug.fail(); + // We don't want to match something like 'TODOBY', so we make sure a non + // letter/digit follows the match. + if (isLetterOrDigit(fileContents.charCodeAt(matchPosition + descriptor.text.length))) { + continue; + } + var message = matchArray[2]; + result.push({ descriptor: descriptor, message: message, position: matchPosition }); + } + } + return result; + function escapeRegExp(str) { + return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"); + } + function getTodoCommentsRegExp() { + // NOTE: `?:` means 'non-capture group'. It allows us to have groups without having to + // filter them out later in the final result array. + // TODO comments can appear in one of the following forms: + // + // 1) // TODO or /////////// TODO + // + // 2) /* TODO or /********** TODO + // + // 3) /* + // * TODO + // */ + // + // The following three regexps are used to match the start of the text up to the TODO + // comment portion. + var singleLineCommentStart = /(?:\/\/+\s*)/.source; + var multiLineCommentStart = /(?:\/\*+\s*)/.source; + var anyNumberOfSpacesAndAsterisksAtStartOfLine = /(?:^(?:\s|\*)*)/.source; + // Match any of the above three TODO comment start regexps. + // Note that the outermost group *is* a capture group. We want to capture the preamble + // so that we can determine the starting position of the TODO comment match. + var preamble = "(" + anyNumberOfSpacesAndAsterisksAtStartOfLine + "|" + singleLineCommentStart + "|" + multiLineCommentStart + ")"; + // Takes the descriptors and forms a regexp that matches them as if they were literals. + // For example, if the descriptors are "TODO(jason)" and "HACK", then this will be: + // + // (?:(TODO\(jason\))|(HACK)) + // + // Note that the outermost group is *not* a capture group, but the innermost groups + // *are* capture groups. By capturing the inner literals we can determine after + // matching which descriptor we are dealing with. + var literals = "(?:" + ts.map(descriptors, function (d) { return "(" + escapeRegExp(d.text) + ")"; }).join("|") + ")"; + // After matching a descriptor literal, the following regexp matches the rest of the + // text up to the end of the line (or */). + var endOfLineOrEndOfComment = /(?:$|\*\/)/.source; + var messageRemainder = /(?:.*?)/.source; + // This is the portion of the match we'll return as part of the TODO comment result. We + // match the literal portion up to the end of the line or end of comment. + var messagePortion = "(" + literals + messageRemainder + ")"; + var regExpString = preamble + messagePortion + endOfLineOrEndOfComment; + // The final regexp will look like this: + // /((?:\/\/+\s*)|(?:\/\*+\s*)|(?:^(?:\s|\*)*))((?:(TODO\(jason\))|(HACK))(?:.*?))(?:$|\*\/)/gim + // The flags of the regexp are important here. + // 'g' is so that we are doing a global search and can find matches several times + // in the input. + // + // 'i' is for case insensitivity (We do this to match C# TODO comment code). + // + // 'm' is so we can find matches in a multi-line input. + return new RegExp(regExpString, "gim"); + } + function isLetterOrDigit(char) { + return (char >= 97 /* a */ && char <= 122 /* z */) || + (char >= 65 /* A */ && char <= 90 /* Z */) || + (char >= 48 /* _0 */ && char <= 57 /* _9 */); + } + function isNodeModulesFile(path) { + return ts.stringContains(path, "/node_modules/"); + } + } + function getRenameInfo(fileName, position) { + synchronizeHostData(); + return ts.Rename.getRenameInfo(program, getValidSourceFile(fileName), position); + } + function getRefactorContext(file, positionOrRange, preferences, formatOptions) { + var _a = typeof positionOrRange === "number" ? [positionOrRange, undefined] : [positionOrRange.pos, positionOrRange.end], startPosition = _a[0], endPosition = _a[1]; + return { + file: file, + startPosition: startPosition, + endPosition: endPosition, + program: getProgram(), + host: host, + formatContext: ts.formatting.getFormatContext(formatOptions), + cancellationToken: cancellationToken, + preferences: preferences, + }; + } + function getApplicableRefactors(fileName, positionOrRange, preferences) { + if (preferences === void 0) { preferences = ts.emptyOptions; } + synchronizeHostData(); + var file = getValidSourceFile(fileName); + return ts.refactor.getApplicableRefactors(getRefactorContext(file, positionOrRange, preferences)); + } + function getEditsForRefactor(fileName, formatOptions, positionOrRange, refactorName, actionName, preferences) { + if (preferences === void 0) { preferences = ts.emptyOptions; } + synchronizeHostData(); + var file = getValidSourceFile(fileName); + return ts.refactor.getEditsForRefactor(getRefactorContext(file, positionOrRange, preferences, formatOptions), refactorName, actionName); + } + return { + dispose: dispose, + cleanupSemanticCache: cleanupSemanticCache, + getSyntacticDiagnostics: getSyntacticDiagnostics, + getSemanticDiagnostics: getSemanticDiagnostics, + getSuggestionDiagnostics: getSuggestionDiagnostics, + getCompilerOptionsDiagnostics: getCompilerOptionsDiagnostics, + getSyntacticClassifications: getSyntacticClassifications, + getSemanticClassifications: getSemanticClassifications, + getEncodedSyntacticClassifications: getEncodedSyntacticClassifications, + getEncodedSemanticClassifications: getEncodedSemanticClassifications, + getCompletionsAtPosition: getCompletionsAtPosition, + getCompletionEntryDetails: getCompletionEntryDetails, + getCompletionEntrySymbol: getCompletionEntrySymbol, + getSignatureHelpItems: getSignatureHelpItems, + getQuickInfoAtPosition: getQuickInfoAtPosition, + getDefinitionAtPosition: getDefinitionAtPosition, + getDefinitionAndBoundSpan: getDefinitionAndBoundSpan, + getImplementationAtPosition: getImplementationAtPosition, + getTypeDefinitionAtPosition: getTypeDefinitionAtPosition, + getReferencesAtPosition: getReferencesAtPosition, + findReferences: findReferences, + getOccurrencesAtPosition: getOccurrencesAtPosition, + getDocumentHighlights: getDocumentHighlights, + getNameOrDottedNameSpan: getNameOrDottedNameSpan, + getBreakpointStatementAtPosition: getBreakpointStatementAtPosition, + getNavigateToItems: getNavigateToItems, + getRenameInfo: getRenameInfo, + findRenameLocations: findRenameLocations, + getNavigationBarItems: getNavigationBarItems, + getNavigationTree: getNavigationTree, + getOutliningSpans: getOutliningSpans, + getTodoComments: getTodoComments, + getBraceMatchingAtPosition: getBraceMatchingAtPosition, + getIndentationAtPosition: getIndentationAtPosition, + getFormattingEditsForRange: getFormattingEditsForRange, + getFormattingEditsForDocument: getFormattingEditsForDocument, + getFormattingEditsAfterKeystroke: getFormattingEditsAfterKeystroke, + getDocCommentTemplateAtPosition: getDocCommentTemplateAtPosition, + isValidBraceCompletionAtPosition: isValidBraceCompletionAtPosition, + getJsxClosingTagAtPosition: getJsxClosingTagAtPosition, + getSpanOfEnclosingComment: getSpanOfEnclosingComment, + getCodeFixesAtPosition: getCodeFixesAtPosition, + getCombinedCodeFix: getCombinedCodeFix, + applyCodeActionCommand: applyCodeActionCommand, + organizeImports: organizeImports, + getEditsForFileRename: getEditsForFileRename, + getEmitOutput: getEmitOutput, + getNonBoundSourceFile: getNonBoundSourceFile, + getProgram: getProgram, + getApplicableRefactors: getApplicableRefactors, + getEditsForRefactor: getEditsForRefactor, + toLineColumnOffset: sourceMapper.toLineColumnOffset, + getSourceMapper: function () { return sourceMapper; }, + }; + } + ts.createLanguageService = createLanguageService; + /* @internal */ + /** Names in the name table are escaped, so an identifier `__foo` will have a name table entry `___foo`. */ + function getNameTable(sourceFile) { + if (!sourceFile.nameTable) { + initializeNameTable(sourceFile); + } + return sourceFile.nameTable; // TODO: GH#18217 + } + ts.getNameTable = getNameTable; + function initializeNameTable(sourceFile) { + var nameTable = sourceFile.nameTable = ts.createUnderscoreEscapedMap(); + sourceFile.forEachChild(function walk(node) { + if (ts.isIdentifier(node) && !ts.isTagName(node) && node.escapedText || ts.isStringOrNumericLiteralLike(node) && literalIsName(node)) { + var text = ts.getEscapedTextOfIdentifierOrLiteral(node); + nameTable.set(text, nameTable.get(text) === undefined ? node.pos : -1); + } + ts.forEachChild(node, walk); + if (ts.hasJSDocNodes(node)) { + for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { + var jsDoc = _a[_i]; + ts.forEachChild(jsDoc, walk); + } + } + }); + } + /** + * We want to store any numbers/strings if they were a name that could be + * related to a declaration. So, if we have 'import x = require("something")' + * then we want 'something' to be in the name table. Similarly, if we have + * "a['propname']" then we want to store "propname" in the name table. + */ + function literalIsName(node) { + return ts.isDeclarationName(node) || + node.parent.kind === 259 /* ExternalModuleReference */ || + isArgumentOfElementAccessExpression(node) || + ts.isLiteralComputedPropertyDeclarationName(node); + } + /** + * Returns the containing object literal property declaration given a possible name node, e.g. "a" in x = { "a": 1 } + */ + /* @internal */ + function getContainingObjectLiteralElement(node) { + var element = getContainingObjectLiteralElementWorker(node); + return element && (ts.isObjectLiteralExpression(element.parent) || ts.isJsxAttributes(element.parent)) ? element : undefined; + } + ts.getContainingObjectLiteralElement = getContainingObjectLiteralElement; + function getContainingObjectLiteralElementWorker(node) { + switch (node.kind) { + case 10 /* StringLiteral */: + case 8 /* NumericLiteral */: + if (node.parent.kind === 149 /* ComputedPropertyName */) { + return ts.isObjectLiteralElement(node.parent.parent) ? node.parent.parent : undefined; + } + // falls through + case 72 /* Identifier */: + return ts.isObjectLiteralElement(node.parent) && + (node.parent.parent.kind === 188 /* ObjectLiteralExpression */ || node.parent.parent.kind === 268 /* JsxAttributes */) && + node.parent.name === node ? node.parent : undefined; + } + return undefined; + } + function getSymbolAtLocationForQuickInfo(node, checker) { + var object = getContainingObjectLiteralElement(node); + if (object) { + var contextualType = checker.getContextualType(object.parent); + var properties = contextualType && getPropertySymbolsFromContextualType(object, checker, contextualType, /*unionSymbolOk*/ false); + if (properties && properties.length === 1) { + return ts.first(properties); + } + } + return checker.getSymbolAtLocation(node); + } + /** Gets all symbols for one property. Does not get symbols for every property. */ + /* @internal */ + function getPropertySymbolsFromContextualType(node, checker, contextualType, unionSymbolOk) { + var name = ts.getNameFromPropertyName(node.name); + if (!name) + return ts.emptyArray; + if (!contextualType.isUnion()) { + var symbol = contextualType.getProperty(name); + return symbol ? [symbol] : ts.emptyArray; + } + var discriminatedPropertySymbols = ts.mapDefined(contextualType.types, function (t) { return ts.isObjectLiteralExpression(node.parent) && checker.isTypeInvalidDueToUnionDiscriminant(t, node.parent) ? undefined : t.getProperty(name); }); + if (unionSymbolOk && (discriminatedPropertySymbols.length === 0 || discriminatedPropertySymbols.length === contextualType.types.length)) { + var symbol = contextualType.getProperty(name); + if (symbol) + return [symbol]; + } + if (discriminatedPropertySymbols.length === 0) { + // Bad discriminant -- do again without discriminating + return ts.mapDefined(contextualType.types, function (t) { return t.getProperty(name); }); + } + return discriminatedPropertySymbols; + } + ts.getPropertySymbolsFromContextualType = getPropertySymbolsFromContextualType; + function isArgumentOfElementAccessExpression(node) { + return node && + node.parent && + node.parent.kind === 190 /* ElementAccessExpression */ && + node.parent.argumentExpression === node; + } + /** + * Get the path of the default library files (lib.d.ts) as distributed with the typescript + * node package. + * The functionality is not supported if the ts module is consumed outside of a node module. + */ + function getDefaultLibFilePath(options) { + // Check __dirname is defined and that we are on a node.js system. + if (typeof __dirname !== "undefined") { + return __dirname + ts.directorySeparator + ts.getDefaultLibFileName(options); + } + throw new Error("getDefaultLibFilePath is only supported when consumed as a node module. "); + } + ts.getDefaultLibFilePath = getDefaultLibFilePath; + ts.objectAllocator = getServicesObjectAllocator(); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var BreakpointResolver; + (function (BreakpointResolver) { + /** + * Get the breakpoint span in given sourceFile + */ + function spanInSourceFileAtLocation(sourceFile, position) { + // Cannot set breakpoint in dts file + if (sourceFile.isDeclarationFile) { + return undefined; + } + var tokenAtLocation = ts.getTokenAtPosition(sourceFile, position); + var lineOfPosition = sourceFile.getLineAndCharacterOfPosition(position).line; + if (sourceFile.getLineAndCharacterOfPosition(tokenAtLocation.getStart(sourceFile)).line > lineOfPosition) { + // Get previous token if the token is returned starts on new line + // eg: let x =10; |--- cursor is here + // let y = 10; + // token at position will return let keyword on second line as the token but we would like to use + // token on same line if trailing trivia (comments or white spaces on same line) part of the last token on that line + var preceding = ts.findPrecedingToken(tokenAtLocation.pos, sourceFile); + // It's a blank line + if (!preceding || sourceFile.getLineAndCharacterOfPosition(preceding.getEnd()).line !== lineOfPosition) { + return undefined; + } + tokenAtLocation = preceding; + } + // Cannot set breakpoint in ambient declarations + if (tokenAtLocation.flags & 4194304 /* Ambient */) { + return undefined; + } + // Get the span in the node based on its syntax + return spanInNode(tokenAtLocation); + function textSpan(startNode, endNode) { + var start = startNode.decorators ? + ts.skipTrivia(sourceFile.text, startNode.decorators.end) : + startNode.getStart(sourceFile); + return ts.createTextSpanFromBounds(start, (endNode || startNode).getEnd()); + } + function textSpanEndingAtNextToken(startNode, previousTokenToFindNextEndToken) { + return textSpan(startNode, ts.findNextToken(previousTokenToFindNextEndToken, previousTokenToFindNextEndToken.parent, sourceFile)); + } + function spanInNodeIfStartsOnSameLine(node, otherwiseOnNode) { + if (node && lineOfPosition === sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile)).line) { + return spanInNode(node); + } + return spanInNode(otherwiseOnNode); + } + function spanInNodeArray(nodeArray) { + return ts.createTextSpanFromBounds(ts.skipTrivia(sourceFile.text, nodeArray.pos), nodeArray.end); + } + function spanInPreviousNode(node) { + return spanInNode(ts.findPrecedingToken(node.pos, sourceFile)); + } + function spanInNextNode(node) { + return spanInNode(ts.findNextToken(node, node.parent, sourceFile)); + } + function spanInNode(node) { + if (node) { + var parent = node.parent; + switch (node.kind) { + case 219 /* VariableStatement */: + // Span on first variable declaration + return spanInVariableDeclaration(node.declarationList.declarations[0]); + case 237 /* VariableDeclaration */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + return spanInVariableDeclaration(node); + case 151 /* Parameter */: + return spanInParameterDeclaration(node); + case 239 /* FunctionDeclaration */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 157 /* Constructor */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + return spanInFunctionDeclaration(node); + case 218 /* Block */: + if (ts.isFunctionBlock(node)) { + return spanInFunctionBlock(node); + } + // falls through + case 245 /* ModuleBlock */: + return spanInBlock(node); + case 274 /* CatchClause */: + return spanInBlock(node.block); + case 221 /* ExpressionStatement */: + // span on the expression + return textSpan(node.expression); + case 230 /* ReturnStatement */: + // span on return keyword and expression if present + return textSpan(node.getChildAt(0), node.expression); + case 224 /* WhileStatement */: + // Span on while(...) + return textSpanEndingAtNextToken(node, node.expression); + case 223 /* DoStatement */: + // span in statement of the do statement + return spanInNode(node.statement); + case 236 /* DebuggerStatement */: + // span on debugger keyword + return textSpan(node.getChildAt(0)); + case 222 /* IfStatement */: + // set on if(..) span + return textSpanEndingAtNextToken(node, node.expression); + case 233 /* LabeledStatement */: + // span in statement + return spanInNode(node.statement); + case 229 /* BreakStatement */: + case 228 /* ContinueStatement */: + // On break or continue keyword and label if present + return textSpan(node.getChildAt(0), node.label); + case 225 /* ForStatement */: + return spanInForStatement(node); + case 226 /* ForInStatement */: + // span of for (a in ...) + return textSpanEndingAtNextToken(node, node.expression); + case 227 /* ForOfStatement */: + // span in initializer + return spanInInitializerOfForLike(node); + case 232 /* SwitchStatement */: + // span on switch(...) + return textSpanEndingAtNextToken(node, node.expression); + case 271 /* CaseClause */: + case 272 /* DefaultClause */: + // span in first statement of the clause + return spanInNode(node.statements[0]); + case 235 /* TryStatement */: + // span in try block + return spanInBlock(node.tryBlock); + case 234 /* ThrowStatement */: + // span in throw ... + return textSpan(node, node.expression); + case 254 /* ExportAssignment */: + // span on export = id + return textSpan(node, node.expression); + case 248 /* ImportEqualsDeclaration */: + // import statement without including semicolon + return textSpan(node, node.moduleReference); + case 249 /* ImportDeclaration */: + // import statement without including semicolon + return textSpan(node, node.moduleSpecifier); + case 255 /* ExportDeclaration */: + // import statement without including semicolon + return textSpan(node, node.moduleSpecifier); + case 244 /* ModuleDeclaration */: + // span on complete module if it is instantiated + if (ts.getModuleInstanceState(node) !== 1 /* Instantiated */) { + return undefined; + } + // falls through + case 240 /* ClassDeclaration */: + case 243 /* EnumDeclaration */: + case 278 /* EnumMember */: + case 186 /* BindingElement */: + // span on complete node + return textSpan(node); + case 231 /* WithStatement */: + // span in statement + return spanInNode(node.statement); + case 152 /* Decorator */: + return spanInNodeArray(parent.decorators); + case 184 /* ObjectBindingPattern */: + case 185 /* ArrayBindingPattern */: + return spanInBindingPattern(node); + // No breakpoint in interface, type alias + case 241 /* InterfaceDeclaration */: + case 242 /* TypeAliasDeclaration */: + return undefined; + // Tokens: + case 26 /* SemicolonToken */: + case 1 /* EndOfFileToken */: + return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(node.pos, sourceFile)); + case 27 /* CommaToken */: + return spanInPreviousNode(node); + case 18 /* OpenBraceToken */: + return spanInOpenBraceToken(node); + case 19 /* CloseBraceToken */: + return spanInCloseBraceToken(node); + case 23 /* CloseBracketToken */: + return spanInCloseBracketToken(node); + case 20 /* OpenParenToken */: + return spanInOpenParenToken(node); + case 21 /* CloseParenToken */: + return spanInCloseParenToken(node); + case 57 /* ColonToken */: + return spanInColonToken(node); + case 30 /* GreaterThanToken */: + case 28 /* LessThanToken */: + return spanInGreaterThanOrLessThanToken(node); + // Keywords: + case 107 /* WhileKeyword */: + return spanInWhileKeyword(node); + case 83 /* ElseKeyword */: + case 75 /* CatchKeyword */: + case 88 /* FinallyKeyword */: + return spanInNextNode(node); + case 147 /* OfKeyword */: + return spanInOfKeyword(node); + default: + // Destructuring pattern in destructuring assignment + // [a, b, c] of + // [a, b, c] = expression + if (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node)) { + return spanInArrayLiteralOrObjectLiteralDestructuringPattern(node); + } + // Set breakpoint on identifier element of destructuring pattern + // `a` or `...c` or `d: x` from + // `[a, b, ...c]` or `{ a, b }` or `{ d: x }` from destructuring pattern + if ((node.kind === 72 /* Identifier */ || + node.kind === 208 /* SpreadElement */ || + node.kind === 275 /* PropertyAssignment */ || + node.kind === 276 /* ShorthandPropertyAssignment */) && + ts.isArrayLiteralOrObjectLiteralDestructuringPattern(parent)) { + return textSpan(node); + } + if (node.kind === 204 /* BinaryExpression */) { + var _a = node, left = _a.left, operatorToken = _a.operatorToken; + // Set breakpoint in destructuring pattern if its destructuring assignment + // [a, b, c] or {a, b, c} of + // [a, b, c] = expression or + // {a, b, c} = expression + if (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(left)) { + return spanInArrayLiteralOrObjectLiteralDestructuringPattern(left); + } + if (operatorToken.kind === 59 /* EqualsToken */ && ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent)) { + // Set breakpoint on assignment expression element of destructuring pattern + // a = expression of + // [a = expression, b, c] = someExpression or + // { a = expression, b, c } = someExpression + return textSpan(node); + } + if (operatorToken.kind === 27 /* CommaToken */) { + return spanInNode(left); + } + } + if (ts.isExpressionNode(node)) { + switch (parent.kind) { + case 223 /* DoStatement */: + // Set span as if on while keyword + return spanInPreviousNode(node); + case 152 /* Decorator */: + // Set breakpoint on the decorator emit + return spanInNode(node.parent); + case 225 /* ForStatement */: + case 227 /* ForOfStatement */: + return textSpan(node); + case 204 /* BinaryExpression */: + if (node.parent.operatorToken.kind === 27 /* CommaToken */) { + // If this is a comma expression, the breakpoint is possible in this expression + return textSpan(node); + } + break; + case 197 /* ArrowFunction */: + if (node.parent.body === node) { + // If this is body of arrow function, it is allowed to have the breakpoint + return textSpan(node); + } + break; + } + } + switch (node.parent.kind) { + case 275 /* PropertyAssignment */: + // If this is name of property assignment, set breakpoint in the initializer + if (node.parent.name === node && + !ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent.parent)) { + return spanInNode(node.parent.initializer); + } + break; + case 194 /* TypeAssertionExpression */: + // Breakpoint in type assertion goes to its operand + if (node.parent.type === node) { + return spanInNextNode(node.parent.type); + } + break; + case 237 /* VariableDeclaration */: + case 151 /* Parameter */: { + // initializer of variable/parameter declaration go to previous node + var _b = node.parent, initializer = _b.initializer, type = _b.type; + if (initializer === node || type === node || ts.isAssignmentOperator(node.kind)) { + return spanInPreviousNode(node); + } + break; + } + case 204 /* BinaryExpression */: { + var left = node.parent.left; + if (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(left) && node !== left) { + // If initializer of destructuring assignment move to previous token + return spanInPreviousNode(node); + } + break; + } + default: + // return type of function go to previous token + if (ts.isFunctionLike(node.parent) && node.parent.type === node) { + return spanInPreviousNode(node); + } + } + // Default go to parent to set the breakpoint + return spanInNode(node.parent); + } + } + function textSpanFromVariableDeclaration(variableDeclaration) { + if (ts.isVariableDeclarationList(variableDeclaration.parent) && variableDeclaration.parent.declarations[0] === variableDeclaration) { + // First declaration - include let keyword + return textSpan(ts.findPrecedingToken(variableDeclaration.pos, sourceFile, variableDeclaration.parent), variableDeclaration); + } + else { + // Span only on this declaration + return textSpan(variableDeclaration); + } + } + function spanInVariableDeclaration(variableDeclaration) { + // If declaration of for in statement, just set the span in parent + if (variableDeclaration.parent.parent.kind === 226 /* ForInStatement */) { + return spanInNode(variableDeclaration.parent.parent); + } + var parent = variableDeclaration.parent; + // If this is a destructuring pattern, set breakpoint in binding pattern + if (ts.isBindingPattern(variableDeclaration.name)) { + return spanInBindingPattern(variableDeclaration.name); + } + // Breakpoint is possible in variableDeclaration only if there is initialization + // or its declaration from 'for of' + if (variableDeclaration.initializer || + ts.hasModifier(variableDeclaration, 1 /* Export */) || + parent.parent.kind === 227 /* ForOfStatement */) { + return textSpanFromVariableDeclaration(variableDeclaration); + } + if (ts.isVariableDeclarationList(variableDeclaration.parent) && + variableDeclaration.parent.declarations[0] !== variableDeclaration) { + // If we cannot set breakpoint on this declaration, set it on previous one + // Because the variable declaration may be binding pattern and + // we would like to set breakpoint in last binding element if that's the case, + // use preceding token instead + return spanInNode(ts.findPrecedingToken(variableDeclaration.pos, sourceFile, variableDeclaration.parent)); + } + } + function canHaveSpanInParameterDeclaration(parameter) { + // Breakpoint is possible on parameter only if it has initializer, is a rest parameter, or has public or private modifier + return !!parameter.initializer || parameter.dotDotDotToken !== undefined || + ts.hasModifier(parameter, 4 /* Public */ | 8 /* Private */); + } + function spanInParameterDeclaration(parameter) { + if (ts.isBindingPattern(parameter.name)) { + // Set breakpoint in binding pattern + return spanInBindingPattern(parameter.name); + } + else if (canHaveSpanInParameterDeclaration(parameter)) { + return textSpan(parameter); + } + else { + var functionDeclaration = parameter.parent; + var indexOfParameter = functionDeclaration.parameters.indexOf(parameter); + ts.Debug.assert(indexOfParameter !== -1); + if (indexOfParameter !== 0) { + // Not a first parameter, go to previous parameter + return spanInParameterDeclaration(functionDeclaration.parameters[indexOfParameter - 1]); + } + else { + // Set breakpoint in the function declaration body + return spanInNode(functionDeclaration.body); + } + } + } + function canFunctionHaveSpanInWholeDeclaration(functionDeclaration) { + return ts.hasModifier(functionDeclaration, 1 /* Export */) || + (functionDeclaration.parent.kind === 240 /* ClassDeclaration */ && functionDeclaration.kind !== 157 /* Constructor */); + } + function spanInFunctionDeclaration(functionDeclaration) { + // No breakpoints in the function signature + if (!functionDeclaration.body) { + return undefined; + } + if (canFunctionHaveSpanInWholeDeclaration(functionDeclaration)) { + // Set the span on whole function declaration + return textSpan(functionDeclaration); + } + // Set span in function body + return spanInNode(functionDeclaration.body); + } + function spanInFunctionBlock(block) { + var nodeForSpanInBlock = block.statements.length ? block.statements[0] : block.getLastToken(); + if (canFunctionHaveSpanInWholeDeclaration(block.parent)) { + return spanInNodeIfStartsOnSameLine(block.parent, nodeForSpanInBlock); + } + return spanInNode(nodeForSpanInBlock); + } + function spanInBlock(block) { + switch (block.parent.kind) { + case 244 /* ModuleDeclaration */: + if (ts.getModuleInstanceState(block.parent) !== 1 /* Instantiated */) { + return undefined; + } + // falls through + // Set on parent if on same line otherwise on first statement + case 224 /* WhileStatement */: + case 222 /* IfStatement */: + case 226 /* ForInStatement */: + return spanInNodeIfStartsOnSameLine(block.parent, block.statements[0]); + // Set span on previous token if it starts on same line otherwise on the first statement of the block + case 225 /* ForStatement */: + case 227 /* ForOfStatement */: + return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(block.pos, sourceFile, block.parent), block.statements[0]); + } + // Default action is to set on first statement + return spanInNode(block.statements[0]); + } + function spanInInitializerOfForLike(forLikeStatement) { + if (forLikeStatement.initializer.kind === 238 /* VariableDeclarationList */) { + // Declaration list - set breakpoint in first declaration + var variableDeclarationList = forLikeStatement.initializer; + if (variableDeclarationList.declarations.length > 0) { + return spanInNode(variableDeclarationList.declarations[0]); + } + } + else { + // Expression - set breakpoint in it + return spanInNode(forLikeStatement.initializer); + } + } + function spanInForStatement(forStatement) { + if (forStatement.initializer) { + return spanInInitializerOfForLike(forStatement); + } + if (forStatement.condition) { + return textSpan(forStatement.condition); + } + if (forStatement.incrementor) { + return textSpan(forStatement.incrementor); + } + } + function spanInBindingPattern(bindingPattern) { + // Set breakpoint in first binding element + var firstBindingElement = ts.forEach(bindingPattern.elements, function (element) { return element.kind !== 210 /* OmittedExpression */ ? element : undefined; }); + if (firstBindingElement) { + return spanInNode(firstBindingElement); + } + // Empty binding pattern of binding element, set breakpoint on binding element + if (bindingPattern.parent.kind === 186 /* BindingElement */) { + return textSpan(bindingPattern.parent); + } + // Variable declaration is used as the span + return textSpanFromVariableDeclaration(bindingPattern.parent); + } + function spanInArrayLiteralOrObjectLiteralDestructuringPattern(node) { + ts.Debug.assert(node.kind !== 185 /* ArrayBindingPattern */ && node.kind !== 184 /* ObjectBindingPattern */); + var elements = node.kind === 187 /* ArrayLiteralExpression */ ? node.elements : node.properties; + var firstBindingElement = ts.forEach(elements, function (element) { return element.kind !== 210 /* OmittedExpression */ ? element : undefined; }); + if (firstBindingElement) { + return spanInNode(firstBindingElement); + } + // Could be ArrayLiteral from destructuring assignment or + // just nested element in another destructuring assignment + // set breakpoint on assignment when parent is destructuring assignment + // Otherwise set breakpoint for this element + return textSpan(node.parent.kind === 204 /* BinaryExpression */ ? node.parent : node); + } + // Tokens: + function spanInOpenBraceToken(node) { + switch (node.parent.kind) { + case 243 /* EnumDeclaration */: + var enumDeclaration = node.parent; + return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(node.pos, sourceFile, node.parent), enumDeclaration.members.length ? enumDeclaration.members[0] : enumDeclaration.getLastToken(sourceFile)); + case 240 /* ClassDeclaration */: + var classDeclaration = node.parent; + return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(node.pos, sourceFile, node.parent), classDeclaration.members.length ? classDeclaration.members[0] : classDeclaration.getLastToken(sourceFile)); + case 246 /* CaseBlock */: + return spanInNodeIfStartsOnSameLine(node.parent.parent, node.parent.clauses[0]); + } + // Default to parent node + return spanInNode(node.parent); + } + function spanInCloseBraceToken(node) { + switch (node.parent.kind) { + case 245 /* ModuleBlock */: + // If this is not an instantiated module block, no bp span + if (ts.getModuleInstanceState(node.parent.parent) !== 1 /* Instantiated */) { + return undefined; + } + // falls through + case 243 /* EnumDeclaration */: + case 240 /* ClassDeclaration */: + // Span on close brace token + return textSpan(node); + case 218 /* Block */: + if (ts.isFunctionBlock(node.parent)) { + // Span on close brace token + return textSpan(node); + } + // falls through + case 274 /* CatchClause */: + return spanInNode(ts.lastOrUndefined(node.parent.statements)); + case 246 /* CaseBlock */: + // breakpoint in last statement of the last clause + var caseBlock = node.parent; + var lastClause = ts.lastOrUndefined(caseBlock.clauses); + if (lastClause) { + return spanInNode(ts.lastOrUndefined(lastClause.statements)); + } + return undefined; + case 184 /* ObjectBindingPattern */: + // Breakpoint in last binding element or binding pattern if it contains no elements + var bindingPattern = node.parent; + return spanInNode(ts.lastOrUndefined(bindingPattern.elements) || bindingPattern); + // Default to parent node + default: + if (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent)) { + // Breakpoint in last binding element or binding pattern if it contains no elements + var objectLiteral = node.parent; + return textSpan(ts.lastOrUndefined(objectLiteral.properties) || objectLiteral); + } + return spanInNode(node.parent); + } + } + function spanInCloseBracketToken(node) { + switch (node.parent.kind) { + case 185 /* ArrayBindingPattern */: + // Breakpoint in last binding element or binding pattern if it contains no elements + var bindingPattern = node.parent; + return textSpan(ts.lastOrUndefined(bindingPattern.elements) || bindingPattern); + default: + if (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent)) { + // Breakpoint in last binding element or binding pattern if it contains no elements + var arrayLiteral = node.parent; + return textSpan(ts.lastOrUndefined(arrayLiteral.elements) || arrayLiteral); + } + // Default to parent node + return spanInNode(node.parent); + } + } + function spanInOpenParenToken(node) { + if (node.parent.kind === 223 /* DoStatement */ || // Go to while keyword and do action instead + node.parent.kind === 191 /* CallExpression */ || + node.parent.kind === 192 /* NewExpression */) { + return spanInPreviousNode(node); + } + if (node.parent.kind === 195 /* ParenthesizedExpression */) { + return spanInNextNode(node); + } + // Default to parent node + return spanInNode(node.parent); + } + function spanInCloseParenToken(node) { + // Is this close paren token of parameter list, set span in previous token + switch (node.parent.kind) { + case 196 /* FunctionExpression */: + case 239 /* FunctionDeclaration */: + case 197 /* ArrowFunction */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 157 /* Constructor */: + case 224 /* WhileStatement */: + case 223 /* DoStatement */: + case 225 /* ForStatement */: + case 227 /* ForOfStatement */: + case 191 /* CallExpression */: + case 192 /* NewExpression */: + case 195 /* ParenthesizedExpression */: + return spanInPreviousNode(node); + // Default to parent node + default: + return spanInNode(node.parent); + } + } + function spanInColonToken(node) { + // Is this : specifying return annotation of the function declaration + if (ts.isFunctionLike(node.parent) || + node.parent.kind === 275 /* PropertyAssignment */ || + node.parent.kind === 151 /* Parameter */) { + return spanInPreviousNode(node); + } + return spanInNode(node.parent); + } + function spanInGreaterThanOrLessThanToken(node) { + if (node.parent.kind === 194 /* TypeAssertionExpression */) { + return spanInNextNode(node); + } + return spanInNode(node.parent); + } + function spanInWhileKeyword(node) { + if (node.parent.kind === 223 /* DoStatement */) { + // Set span on while expression + return textSpanEndingAtNextToken(node, node.parent.expression); + } + // Default to parent node + return spanInNode(node.parent); + } + function spanInOfKeyword(node) { + if (node.parent.kind === 227 /* ForOfStatement */) { + // Set using next token + return spanInNextNode(node); + } + // Default to parent node + return spanInNode(node.parent); + } + } + } + BreakpointResolver.spanInSourceFileAtLocation = spanInSourceFileAtLocation; + })(BreakpointResolver = ts.BreakpointResolver || (ts.BreakpointResolver = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + /** + * Transform one or more nodes using the supplied transformers. + * @param source A single `Node` or an array of `Node` objects. + * @param transformers An array of `TransformerFactory` callbacks used to process the transformation. + * @param compilerOptions Optional compiler options. + */ + function transform(source, transformers, compilerOptions) { + var diagnostics = []; + compilerOptions = ts.fixupCompilerOptions(compilerOptions, diagnostics); // TODO: GH#18217 + var nodes = ts.isArray(source) ? source : [source]; + var result = ts.transformNodes(/*resolver*/ undefined, /*emitHost*/ undefined, compilerOptions, nodes, transformers, /*allowDtsFiles*/ true); + result.diagnostics = ts.concatenate(result.diagnostics, diagnostics); + return result; + } + ts.transform = transform; +})(ts || (ts = {})); +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +/* @internal */ +var debugObjectHost = (function () { return this; })(); +// We need to use 'null' to interface with the managed side. +/* tslint:disable:no-null-keyword */ +/* tslint:disable:no-in-operator */ +/* @internal */ +var ts; +(function (ts) { + function logInternalError(logger, err) { + if (logger) { + logger.log("*INTERNAL ERROR* - Exception in typescript services: " + err.message); + } + } + var ScriptSnapshotShimAdapter = /** @class */ (function () { + function ScriptSnapshotShimAdapter(scriptSnapshotShim) { + this.scriptSnapshotShim = scriptSnapshotShim; + } + ScriptSnapshotShimAdapter.prototype.getText = function (start, end) { + return this.scriptSnapshotShim.getText(start, end); + }; + ScriptSnapshotShimAdapter.prototype.getLength = function () { + return this.scriptSnapshotShim.getLength(); + }; + ScriptSnapshotShimAdapter.prototype.getChangeRange = function (oldSnapshot) { + var oldSnapshotShim = oldSnapshot; + var encoded = this.scriptSnapshotShim.getChangeRange(oldSnapshotShim.scriptSnapshotShim); + if (encoded === null) { + return null; // TODO: GH#18217 + } + var decoded = JSON.parse(encoded); // TODO: GH#18217 + return ts.createTextChangeRange(ts.createTextSpan(decoded.span.start, decoded.span.length), decoded.newLength); + }; + ScriptSnapshotShimAdapter.prototype.dispose = function () { + // if scriptSnapshotShim is a COM object then property check becomes method call with no arguments + // 'in' does not have this effect + if ("dispose" in this.scriptSnapshotShim) { + this.scriptSnapshotShim.dispose(); // TODO: GH#18217 Can we just use `if (this.scriptSnapshotShim.dispose)`? + } + }; + return ScriptSnapshotShimAdapter; + }()); + var LanguageServiceShimHostAdapter = /** @class */ (function () { + function LanguageServiceShimHostAdapter(shimHost) { + var _this = this; + this.shimHost = shimHost; + this.loggingEnabled = false; + this.tracingEnabled = false; + // if shimHost is a COM object then property check will become method call with no arguments. + // 'in' does not have this effect. + if ("getModuleResolutionsForFile" in this.shimHost) { + this.resolveModuleNames = function (moduleNames, containingFile) { + var resolutionsInFile = JSON.parse(_this.shimHost.getModuleResolutionsForFile(containingFile)); // TODO: GH#18217 + return ts.map(moduleNames, function (name) { + var result = ts.getProperty(resolutionsInFile, name); + return result ? { resolvedFileName: result, extension: ts.extensionFromPath(result), isExternalLibraryImport: false } : undefined; + }); + }; + } + if ("directoryExists" in this.shimHost) { + this.directoryExists = function (directoryName) { return _this.shimHost.directoryExists(directoryName); }; + } + if ("getTypeReferenceDirectiveResolutionsForFile" in this.shimHost) { + this.resolveTypeReferenceDirectives = function (typeDirectiveNames, containingFile) { + var typeDirectivesForFile = JSON.parse(_this.shimHost.getTypeReferenceDirectiveResolutionsForFile(containingFile)); // TODO: GH#18217 + return ts.map(typeDirectiveNames, function (name) { return ts.getProperty(typeDirectivesForFile, name); }); + }; + } + } + LanguageServiceShimHostAdapter.prototype.log = function (s) { + if (this.loggingEnabled) { + this.shimHost.log(s); + } + }; + LanguageServiceShimHostAdapter.prototype.trace = function (s) { + if (this.tracingEnabled) { + this.shimHost.trace(s); + } + }; + LanguageServiceShimHostAdapter.prototype.error = function (s) { + this.shimHost.error(s); + }; + LanguageServiceShimHostAdapter.prototype.getProjectVersion = function () { + if (!this.shimHost.getProjectVersion) { + // shimmed host does not support getProjectVersion + return undefined; // TODO: GH#18217 + } + return this.shimHost.getProjectVersion(); + }; + LanguageServiceShimHostAdapter.prototype.getTypeRootsVersion = function () { + if (!this.shimHost.getTypeRootsVersion) { + return 0; + } + return this.shimHost.getTypeRootsVersion(); + }; + LanguageServiceShimHostAdapter.prototype.useCaseSensitiveFileNames = function () { + return this.shimHost.useCaseSensitiveFileNames ? this.shimHost.useCaseSensitiveFileNames() : false; + }; + LanguageServiceShimHostAdapter.prototype.getCompilationSettings = function () { + var settingsJson = this.shimHost.getCompilationSettings(); + if (settingsJson === null || settingsJson === "") { + throw Error("LanguageServiceShimHostAdapter.getCompilationSettings: empty compilationSettings"); + } + var compilerOptions = JSON.parse(settingsJson); + // permit language service to handle all files (filtering should be performed on the host side) + compilerOptions.allowNonTsExtensions = true; + return compilerOptions; + }; + LanguageServiceShimHostAdapter.prototype.getScriptFileNames = function () { + var encoded = this.shimHost.getScriptFileNames(); + return JSON.parse(encoded); + }; + LanguageServiceShimHostAdapter.prototype.getScriptSnapshot = function (fileName) { + var scriptSnapshot = this.shimHost.getScriptSnapshot(fileName); + return scriptSnapshot && new ScriptSnapshotShimAdapter(scriptSnapshot); + }; + LanguageServiceShimHostAdapter.prototype.getScriptKind = function (fileName) { + if ("getScriptKind" in this.shimHost) { + return this.shimHost.getScriptKind(fileName); // TODO: GH#18217 + } + else { + return 0 /* Unknown */; + } + }; + LanguageServiceShimHostAdapter.prototype.getScriptVersion = function (fileName) { + return this.shimHost.getScriptVersion(fileName); + }; + LanguageServiceShimHostAdapter.prototype.getLocalizedDiagnosticMessages = function () { + var diagnosticMessagesJson = this.shimHost.getLocalizedDiagnosticMessages(); + if (diagnosticMessagesJson === null || diagnosticMessagesJson === "") { + return null; + } + try { + return JSON.parse(diagnosticMessagesJson); + } + catch (e) { + this.log(e.description || "diagnosticMessages.generated.json has invalid JSON format"); + return null; + } + }; + LanguageServiceShimHostAdapter.prototype.getCancellationToken = function () { + var hostCancellationToken = this.shimHost.getCancellationToken(); + return new ts.ThrottledCancellationToken(hostCancellationToken); + }; + LanguageServiceShimHostAdapter.prototype.getCurrentDirectory = function () { + return this.shimHost.getCurrentDirectory(); + }; + LanguageServiceShimHostAdapter.prototype.getDirectories = function (path) { + return JSON.parse(this.shimHost.getDirectories(path)); + }; + LanguageServiceShimHostAdapter.prototype.getDefaultLibFileName = function (options) { + return this.shimHost.getDefaultLibFileName(JSON.stringify(options)); + }; + LanguageServiceShimHostAdapter.prototype.readDirectory = function (path, extensions, exclude, include, depth) { + var pattern = ts.getFileMatcherPatterns(path, exclude, include, this.shimHost.useCaseSensitiveFileNames(), this.shimHost.getCurrentDirectory()); // TODO: GH#18217 + return JSON.parse(this.shimHost.readDirectory(path, JSON.stringify(extensions), JSON.stringify(pattern.basePaths), pattern.excludePattern, pattern.includeFilePattern, pattern.includeDirectoryPattern, depth)); + }; + LanguageServiceShimHostAdapter.prototype.readFile = function (path, encoding) { + return this.shimHost.readFile(path, encoding); + }; + LanguageServiceShimHostAdapter.prototype.fileExists = function (path) { + return this.shimHost.fileExists(path); + }; + return LanguageServiceShimHostAdapter; + }()); + ts.LanguageServiceShimHostAdapter = LanguageServiceShimHostAdapter; + var CoreServicesShimHostAdapter = /** @class */ (function () { + function CoreServicesShimHostAdapter(shimHost) { + var _this = this; + this.shimHost = shimHost; + this.useCaseSensitiveFileNames = this.shimHost.useCaseSensitiveFileNames ? this.shimHost.useCaseSensitiveFileNames() : false; + if ("directoryExists" in this.shimHost) { + this.directoryExists = function (directoryName) { return _this.shimHost.directoryExists(directoryName); }; + } + else { + this.directoryExists = undefined; // TODO: GH#18217 + } + if ("realpath" in this.shimHost) { + this.realpath = function (path) { return _this.shimHost.realpath(path); }; // TODO: GH#18217 + } + else { + this.realpath = undefined; // TODO: GH#18217 + } + } + CoreServicesShimHostAdapter.prototype.readDirectory = function (rootDir, extensions, exclude, include, depth) { + var pattern = ts.getFileMatcherPatterns(rootDir, exclude, include, this.shimHost.useCaseSensitiveFileNames(), this.shimHost.getCurrentDirectory()); // TODO: GH#18217 + return JSON.parse(this.shimHost.readDirectory(rootDir, JSON.stringify(extensions), JSON.stringify(pattern.basePaths), pattern.excludePattern, pattern.includeFilePattern, pattern.includeDirectoryPattern, depth)); + }; + CoreServicesShimHostAdapter.prototype.fileExists = function (fileName) { + return this.shimHost.fileExists(fileName); + }; + CoreServicesShimHostAdapter.prototype.readFile = function (fileName) { + return this.shimHost.readFile(fileName); + }; + CoreServicesShimHostAdapter.prototype.getDirectories = function (path) { + return JSON.parse(this.shimHost.getDirectories(path)); + }; + return CoreServicesShimHostAdapter; + }()); + ts.CoreServicesShimHostAdapter = CoreServicesShimHostAdapter; + function simpleForwardCall(logger, actionDescription, action, logPerformance) { + var start; + if (logPerformance) { + logger.log(actionDescription); + start = ts.timestamp(); + } + var result = action(); + if (logPerformance) { + var end = ts.timestamp(); + logger.log(actionDescription + " completed in " + (end - start) + " msec"); + if (ts.isString(result)) { + var str = result; + if (str.length > 128) { + str = str.substring(0, 128) + "..."; + } + logger.log(" result.length=" + str.length + ", result='" + JSON.stringify(str) + "'"); + } + } + return result; + } + function forwardJSONCall(logger, actionDescription, action, logPerformance) { + return forwardCall(logger, actionDescription, /*returnJson*/ true, action, logPerformance); + } + function forwardCall(logger, actionDescription, returnJson, action, logPerformance) { + try { + var result = simpleForwardCall(logger, actionDescription, action, logPerformance); + return returnJson ? JSON.stringify({ result: result }) : result; + } + catch (err) { + if (err instanceof ts.OperationCanceledException) { + return JSON.stringify({ canceled: true }); + } + logInternalError(logger, err); + err.description = actionDescription; + return JSON.stringify({ error: err }); + } + } + var ShimBase = /** @class */ (function () { + function ShimBase(factory) { + this.factory = factory; + factory.registerShim(this); + } + ShimBase.prototype.dispose = function (_dummy) { + this.factory.unregisterShim(this); + }; + return ShimBase; + }()); + function realizeDiagnostics(diagnostics, newLine) { + return diagnostics.map(function (d) { return realizeDiagnostic(d, newLine); }); + } + ts.realizeDiagnostics = realizeDiagnostics; + function realizeDiagnostic(diagnostic, newLine) { + return { + message: ts.flattenDiagnosticMessageText(diagnostic.messageText, newLine), + start: diagnostic.start, + length: diagnostic.length, + category: ts.diagnosticCategoryName(diagnostic), + code: diagnostic.code, + reportsUnnecessary: diagnostic.reportsUnnecessary, + }; + } + var LanguageServiceShimObject = /** @class */ (function (_super) { + __extends(LanguageServiceShimObject, _super); + function LanguageServiceShimObject(factory, host, languageService) { + var _this = _super.call(this, factory) || this; + _this.host = host; + _this.languageService = languageService; + _this.logPerformance = false; + _this.logger = _this.host; + return _this; + } + LanguageServiceShimObject.prototype.forwardJSONCall = function (actionDescription, action) { + return forwardJSONCall(this.logger, actionDescription, action, this.logPerformance); + }; + /// DISPOSE + /** + * Ensure (almost) deterministic release of internal Javascript resources when + * some external native objects holds onto us (e.g. Com/Interop). + */ + LanguageServiceShimObject.prototype.dispose = function (dummy) { + this.logger.log("dispose()"); + this.languageService.dispose(); + this.languageService = null; + // force a GC + if (debugObjectHost && debugObjectHost.CollectGarbage) { + debugObjectHost.CollectGarbage(); + this.logger.log("CollectGarbage()"); + } + this.logger = null; + _super.prototype.dispose.call(this, dummy); + }; + /// REFRESH + /** + * Update the list of scripts known to the compiler + */ + LanguageServiceShimObject.prototype.refresh = function (throwOnError) { + this.forwardJSONCall("refresh(" + throwOnError + ")", function () { return null; }); + }; + LanguageServiceShimObject.prototype.cleanupSemanticCache = function () { + var _this = this; + this.forwardJSONCall("cleanupSemanticCache()", function () { + _this.languageService.cleanupSemanticCache(); + return null; + }); + }; + LanguageServiceShimObject.prototype.realizeDiagnostics = function (diagnostics) { + var newLine = ts.getNewLineOrDefaultFromHost(this.host); + return realizeDiagnostics(diagnostics, newLine); + }; + LanguageServiceShimObject.prototype.getSyntacticClassifications = function (fileName, start, length) { + var _this = this; + return this.forwardJSONCall("getSyntacticClassifications('" + fileName + "', " + start + ", " + length + ")", function () { return _this.languageService.getSyntacticClassifications(fileName, ts.createTextSpan(start, length)); }); + }; + LanguageServiceShimObject.prototype.getSemanticClassifications = function (fileName, start, length) { + var _this = this; + return this.forwardJSONCall("getSemanticClassifications('" + fileName + "', " + start + ", " + length + ")", function () { return _this.languageService.getSemanticClassifications(fileName, ts.createTextSpan(start, length)); }); + }; + LanguageServiceShimObject.prototype.getEncodedSyntacticClassifications = function (fileName, start, length) { + var _this = this; + return this.forwardJSONCall("getEncodedSyntacticClassifications('" + fileName + "', " + start + ", " + length + ")", + // directly serialize the spans out to a string. This is much faster to decode + // on the managed side versus a full JSON array. + function () { return convertClassifications(_this.languageService.getEncodedSyntacticClassifications(fileName, ts.createTextSpan(start, length))); }); + }; + LanguageServiceShimObject.prototype.getEncodedSemanticClassifications = function (fileName, start, length) { + var _this = this; + return this.forwardJSONCall("getEncodedSemanticClassifications('" + fileName + "', " + start + ", " + length + ")", + // directly serialize the spans out to a string. This is much faster to decode + // on the managed side versus a full JSON array. + function () { return convertClassifications(_this.languageService.getEncodedSemanticClassifications(fileName, ts.createTextSpan(start, length))); }); + }; + LanguageServiceShimObject.prototype.getSyntacticDiagnostics = function (fileName) { + var _this = this; + return this.forwardJSONCall("getSyntacticDiagnostics('" + fileName + "')", function () { + var diagnostics = _this.languageService.getSyntacticDiagnostics(fileName); + return _this.realizeDiagnostics(diagnostics); + }); + }; + LanguageServiceShimObject.prototype.getSemanticDiagnostics = function (fileName) { + var _this = this; + return this.forwardJSONCall("getSemanticDiagnostics('" + fileName + "')", function () { + var diagnostics = _this.languageService.getSemanticDiagnostics(fileName); + return _this.realizeDiagnostics(diagnostics); + }); + }; + LanguageServiceShimObject.prototype.getSuggestionDiagnostics = function (fileName) { + var _this = this; + return this.forwardJSONCall("getSuggestionDiagnostics('" + fileName + "')", function () { return _this.realizeDiagnostics(_this.languageService.getSuggestionDiagnostics(fileName)); }); + }; + LanguageServiceShimObject.prototype.getCompilerOptionsDiagnostics = function () { + var _this = this; + return this.forwardJSONCall("getCompilerOptionsDiagnostics()", function () { + var diagnostics = _this.languageService.getCompilerOptionsDiagnostics(); + return _this.realizeDiagnostics(diagnostics); + }); + }; + /// QUICKINFO + /** + * Computes a string representation of the type at the requested position + * in the active file. + */ + LanguageServiceShimObject.prototype.getQuickInfoAtPosition = function (fileName, position) { + var _this = this; + return this.forwardJSONCall("getQuickInfoAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getQuickInfoAtPosition(fileName, position); }); + }; + /// NAMEORDOTTEDNAMESPAN + /** + * Computes span information of the name or dotted name at the requested position + * in the active file. + */ + LanguageServiceShimObject.prototype.getNameOrDottedNameSpan = function (fileName, startPos, endPos) { + var _this = this; + return this.forwardJSONCall("getNameOrDottedNameSpan('" + fileName + "', " + startPos + ", " + endPos + ")", function () { return _this.languageService.getNameOrDottedNameSpan(fileName, startPos, endPos); }); + }; + /** + * STATEMENTSPAN + * Computes span information of statement at the requested position in the active file. + */ + LanguageServiceShimObject.prototype.getBreakpointStatementAtPosition = function (fileName, position) { + var _this = this; + return this.forwardJSONCall("getBreakpointStatementAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getBreakpointStatementAtPosition(fileName, position); }); + }; + /// SIGNATUREHELP + LanguageServiceShimObject.prototype.getSignatureHelpItems = function (fileName, position, options) { + var _this = this; + return this.forwardJSONCall("getSignatureHelpItems('" + fileName + "', " + position + ")", function () { return _this.languageService.getSignatureHelpItems(fileName, position, options); }); + }; + /// GOTO DEFINITION + /** + * Computes the definition location and file for the symbol + * at the requested position. + */ + LanguageServiceShimObject.prototype.getDefinitionAtPosition = function (fileName, position) { + var _this = this; + return this.forwardJSONCall("getDefinitionAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getDefinitionAtPosition(fileName, position); }); + }; + /** + * Computes the definition location and file for the symbol + * at the requested position. + */ + LanguageServiceShimObject.prototype.getDefinitionAndBoundSpan = function (fileName, position) { + var _this = this; + return this.forwardJSONCall("getDefinitionAndBoundSpan('" + fileName + "', " + position + ")", function () { return _this.languageService.getDefinitionAndBoundSpan(fileName, position); }); + }; + /// GOTO Type + /** + * Computes the definition location of the type of the symbol + * at the requested position. + */ + LanguageServiceShimObject.prototype.getTypeDefinitionAtPosition = function (fileName, position) { + var _this = this; + return this.forwardJSONCall("getTypeDefinitionAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getTypeDefinitionAtPosition(fileName, position); }); + }; + /// GOTO Implementation + /** + * Computes the implementation location of the symbol + * at the requested position. + */ + LanguageServiceShimObject.prototype.getImplementationAtPosition = function (fileName, position) { + var _this = this; + return this.forwardJSONCall("getImplementationAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getImplementationAtPosition(fileName, position); }); + }; + LanguageServiceShimObject.prototype.getRenameInfo = function (fileName, position) { + var _this = this; + return this.forwardJSONCall("getRenameInfo('" + fileName + "', " + position + ")", function () { return _this.languageService.getRenameInfo(fileName, position); }); + }; + LanguageServiceShimObject.prototype.findRenameLocations = function (fileName, position, findInStrings, findInComments) { + var _this = this; + return this.forwardJSONCall("findRenameLocations('" + fileName + "', " + position + ", " + findInStrings + ", " + findInComments + ")", function () { return _this.languageService.findRenameLocations(fileName, position, findInStrings, findInComments); }); + }; + /// GET BRACE MATCHING + LanguageServiceShimObject.prototype.getBraceMatchingAtPosition = function (fileName, position) { + var _this = this; + return this.forwardJSONCall("getBraceMatchingAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getBraceMatchingAtPosition(fileName, position); }); + }; + LanguageServiceShimObject.prototype.isValidBraceCompletionAtPosition = function (fileName, position, openingBrace) { + var _this = this; + return this.forwardJSONCall("isValidBraceCompletionAtPosition('" + fileName + "', " + position + ", " + openingBrace + ")", function () { return _this.languageService.isValidBraceCompletionAtPosition(fileName, position, openingBrace); }); + }; + LanguageServiceShimObject.prototype.getSpanOfEnclosingComment = function (fileName, position, onlyMultiLine) { + var _this = this; + return this.forwardJSONCall("getSpanOfEnclosingComment('" + fileName + "', " + position + ")", function () { return _this.languageService.getSpanOfEnclosingComment(fileName, position, onlyMultiLine); }); + }; + /// GET SMART INDENT + LanguageServiceShimObject.prototype.getIndentationAtPosition = function (fileName, position, options /*Services.EditorOptions*/) { + var _this = this; + return this.forwardJSONCall("getIndentationAtPosition('" + fileName + "', " + position + ")", function () { + var localOptions = JSON.parse(options); + return _this.languageService.getIndentationAtPosition(fileName, position, localOptions); + }); + }; + /// GET REFERENCES + LanguageServiceShimObject.prototype.getReferencesAtPosition = function (fileName, position) { + var _this = this; + return this.forwardJSONCall("getReferencesAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getReferencesAtPosition(fileName, position); }); + }; + LanguageServiceShimObject.prototype.findReferences = function (fileName, position) { + var _this = this; + return this.forwardJSONCall("findReferences('" + fileName + "', " + position + ")", function () { return _this.languageService.findReferences(fileName, position); }); + }; + LanguageServiceShimObject.prototype.getOccurrencesAtPosition = function (fileName, position) { + var _this = this; + return this.forwardJSONCall("getOccurrencesAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getOccurrencesAtPosition(fileName, position); }); + }; + LanguageServiceShimObject.prototype.getDocumentHighlights = function (fileName, position, filesToSearch) { + var _this = this; + return this.forwardJSONCall("getDocumentHighlights('" + fileName + "', " + position + ")", function () { + var results = _this.languageService.getDocumentHighlights(fileName, position, JSON.parse(filesToSearch)); + // workaround for VS document highlighting issue - keep only items from the initial file + var normalizedName = ts.normalizeSlashes(fileName).toLowerCase(); + return ts.filter(results, function (r) { return ts.normalizeSlashes(r.fileName).toLowerCase() === normalizedName; }); + }); + }; + /// COMPLETION LISTS + /** + * Get a string based representation of the completions + * to provide at the given source position and providing a member completion + * list if requested. + */ + LanguageServiceShimObject.prototype.getCompletionsAtPosition = function (fileName, position, preferences) { + var _this = this; + return this.forwardJSONCall("getCompletionsAtPosition('" + fileName + "', " + position + ", " + preferences + ")", function () { return _this.languageService.getCompletionsAtPosition(fileName, position, preferences); }); + }; + /** Get a string based representation of a completion list entry details */ + LanguageServiceShimObject.prototype.getCompletionEntryDetails = function (fileName, position, entryName, formatOptions, source, preferences) { + var _this = this; + return this.forwardJSONCall("getCompletionEntryDetails('" + fileName + "', " + position + ", '" + entryName + "')", function () { + var localOptions = formatOptions === undefined ? undefined : JSON.parse(formatOptions); + return _this.languageService.getCompletionEntryDetails(fileName, position, entryName, localOptions, source, preferences); + }); + }; + LanguageServiceShimObject.prototype.getFormattingEditsForRange = function (fileName, start, end, options /*Services.FormatCodeOptions*/) { + var _this = this; + return this.forwardJSONCall("getFormattingEditsForRange('" + fileName + "', " + start + ", " + end + ")", function () { + var localOptions = JSON.parse(options); + return _this.languageService.getFormattingEditsForRange(fileName, start, end, localOptions); + }); + }; + LanguageServiceShimObject.prototype.getFormattingEditsForDocument = function (fileName, options /*Services.FormatCodeOptions*/) { + var _this = this; + return this.forwardJSONCall("getFormattingEditsForDocument('" + fileName + "')", function () { + var localOptions = JSON.parse(options); + return _this.languageService.getFormattingEditsForDocument(fileName, localOptions); + }); + }; + LanguageServiceShimObject.prototype.getFormattingEditsAfterKeystroke = function (fileName, position, key, options /*Services.FormatCodeOptions*/) { + var _this = this; + return this.forwardJSONCall("getFormattingEditsAfterKeystroke('" + fileName + "', " + position + ", '" + key + "')", function () { + var localOptions = JSON.parse(options); + return _this.languageService.getFormattingEditsAfterKeystroke(fileName, position, key, localOptions); + }); + }; + LanguageServiceShimObject.prototype.getDocCommentTemplateAtPosition = function (fileName, position) { + var _this = this; + return this.forwardJSONCall("getDocCommentTemplateAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getDocCommentTemplateAtPosition(fileName, position); }); + }; + /// NAVIGATE TO + /** Return a list of symbols that are interesting to navigate to */ + LanguageServiceShimObject.prototype.getNavigateToItems = function (searchValue, maxResultCount, fileName) { + var _this = this; + return this.forwardJSONCall("getNavigateToItems('" + searchValue + "', " + maxResultCount + ", " + fileName + ")", function () { return _this.languageService.getNavigateToItems(searchValue, maxResultCount, fileName); }); + }; + LanguageServiceShimObject.prototype.getNavigationBarItems = function (fileName) { + var _this = this; + return this.forwardJSONCall("getNavigationBarItems('" + fileName + "')", function () { return _this.languageService.getNavigationBarItems(fileName); }); + }; + LanguageServiceShimObject.prototype.getNavigationTree = function (fileName) { + var _this = this; + return this.forwardJSONCall("getNavigationTree('" + fileName + "')", function () { return _this.languageService.getNavigationTree(fileName); }); + }; + LanguageServiceShimObject.prototype.getOutliningSpans = function (fileName) { + var _this = this; + return this.forwardJSONCall("getOutliningSpans('" + fileName + "')", function () { return _this.languageService.getOutliningSpans(fileName); }); + }; + LanguageServiceShimObject.prototype.getTodoComments = function (fileName, descriptors) { + var _this = this; + return this.forwardJSONCall("getTodoComments('" + fileName + "')", function () { return _this.languageService.getTodoComments(fileName, JSON.parse(descriptors)); }); + }; + /// Emit + LanguageServiceShimObject.prototype.getEmitOutput = function (fileName) { + var _this = this; + return this.forwardJSONCall("getEmitOutput('" + fileName + "')", function () { return _this.languageService.getEmitOutput(fileName); }); + }; + LanguageServiceShimObject.prototype.getEmitOutputObject = function (fileName) { + var _this = this; + return forwardCall(this.logger, "getEmitOutput('" + fileName + "')", + /*returnJson*/ false, function () { return _this.languageService.getEmitOutput(fileName); }, this.logPerformance); + }; + return LanguageServiceShimObject; + }(ShimBase)); + function convertClassifications(classifications) { + return { spans: classifications.spans.join(","), endOfLineState: classifications.endOfLineState }; + } + var ClassifierShimObject = /** @class */ (function (_super) { + __extends(ClassifierShimObject, _super); + function ClassifierShimObject(factory, logger) { + var _this = _super.call(this, factory) || this; + _this.logger = logger; + _this.logPerformance = false; + _this.classifier = ts.createClassifier(); + return _this; + } + ClassifierShimObject.prototype.getEncodedLexicalClassifications = function (text, lexState, syntacticClassifierAbsent) { + var _this = this; + if (syntacticClassifierAbsent === void 0) { syntacticClassifierAbsent = false; } + return forwardJSONCall(this.logger, "getEncodedLexicalClassifications", function () { return convertClassifications(_this.classifier.getEncodedLexicalClassifications(text, lexState, syntacticClassifierAbsent)); }, this.logPerformance); + }; + /// COLORIZATION + ClassifierShimObject.prototype.getClassificationsForLine = function (text, lexState, classifyKeywordsInGenerics) { + if (classifyKeywordsInGenerics === void 0) { classifyKeywordsInGenerics = false; } + var classification = this.classifier.getClassificationsForLine(text, lexState, classifyKeywordsInGenerics); + var result = ""; + for (var _i = 0, _a = classification.entries; _i < _a.length; _i++) { + var item = _a[_i]; + result += item.length + "\n"; + result += item.classification + "\n"; + } + result += classification.finalLexState; + return result; + }; + return ClassifierShimObject; + }(ShimBase)); + var CoreServicesShimObject = /** @class */ (function (_super) { + __extends(CoreServicesShimObject, _super); + function CoreServicesShimObject(factory, logger, host) { + var _this = _super.call(this, factory) || this; + _this.logger = logger; + _this.host = host; + _this.logPerformance = false; + return _this; + } + CoreServicesShimObject.prototype.forwardJSONCall = function (actionDescription, action) { + return forwardJSONCall(this.logger, actionDescription, action, this.logPerformance); + }; + CoreServicesShimObject.prototype.resolveModuleName = function (fileName, moduleName, compilerOptionsJson) { + var _this = this; + return this.forwardJSONCall("resolveModuleName('" + fileName + "')", function () { + var compilerOptions = JSON.parse(compilerOptionsJson); + var result = ts.resolveModuleName(moduleName, ts.normalizeSlashes(fileName), compilerOptions, _this.host); + var resolvedFileName = result.resolvedModule ? result.resolvedModule.resolvedFileName : undefined; + if (result.resolvedModule && result.resolvedModule.extension !== ".ts" /* Ts */ && result.resolvedModule.extension !== ".tsx" /* Tsx */ && result.resolvedModule.extension !== ".d.ts" /* Dts */) { + resolvedFileName = undefined; + } + return { + resolvedFileName: resolvedFileName, + failedLookupLocations: result.failedLookupLocations + }; + }); + }; + CoreServicesShimObject.prototype.resolveTypeReferenceDirective = function (fileName, typeReferenceDirective, compilerOptionsJson) { + var _this = this; + return this.forwardJSONCall("resolveTypeReferenceDirective(" + fileName + ")", function () { + var compilerOptions = JSON.parse(compilerOptionsJson); + var result = ts.resolveTypeReferenceDirective(typeReferenceDirective, ts.normalizeSlashes(fileName), compilerOptions, _this.host); + return { + resolvedFileName: result.resolvedTypeReferenceDirective ? result.resolvedTypeReferenceDirective.resolvedFileName : undefined, + primary: result.resolvedTypeReferenceDirective ? result.resolvedTypeReferenceDirective.primary : true, + failedLookupLocations: result.failedLookupLocations + }; + }); + }; + CoreServicesShimObject.prototype.getPreProcessedFileInfo = function (fileName, sourceTextSnapshot) { + var _this = this; + return this.forwardJSONCall("getPreProcessedFileInfo('" + fileName + "')", function () { + // for now treat files as JavaScript + var result = ts.preProcessFile(ts.getSnapshotText(sourceTextSnapshot), /* readImportFiles */ true, /* detectJavaScriptImports */ true); + return { + referencedFiles: _this.convertFileReferences(result.referencedFiles), + importedFiles: _this.convertFileReferences(result.importedFiles), + ambientExternalModules: result.ambientExternalModules, + isLibFile: result.isLibFile, + typeReferenceDirectives: _this.convertFileReferences(result.typeReferenceDirectives), + libReferenceDirectives: _this.convertFileReferences(result.libReferenceDirectives) + }; + }); + }; + CoreServicesShimObject.prototype.getAutomaticTypeDirectiveNames = function (compilerOptionsJson) { + var _this = this; + return this.forwardJSONCall("getAutomaticTypeDirectiveNames('" + compilerOptionsJson + "')", function () { + var compilerOptions = JSON.parse(compilerOptionsJson); + return ts.getAutomaticTypeDirectiveNames(compilerOptions, _this.host); + }); + }; + CoreServicesShimObject.prototype.convertFileReferences = function (refs) { + if (!refs) { + return undefined; + } + var result = []; + for (var _i = 0, refs_1 = refs; _i < refs_1.length; _i++) { + var ref = refs_1[_i]; + result.push({ + path: ts.normalizeSlashes(ref.fileName), + position: ref.pos, + length: ref.end - ref.pos + }); + } + return result; + }; + CoreServicesShimObject.prototype.getTSConfigFileInfo = function (fileName, sourceTextSnapshot) { + var _this = this; + return this.forwardJSONCall("getTSConfigFileInfo('" + fileName + "')", function () { + var result = ts.parseJsonText(fileName, ts.getSnapshotText(sourceTextSnapshot)); + var normalizedFileName = ts.normalizeSlashes(fileName); + var configFile = ts.parseJsonSourceFileConfigFileContent(result, _this.host, ts.getDirectoryPath(normalizedFileName), /*existingOptions*/ {}, normalizedFileName); + return { + options: configFile.options, + typeAcquisition: configFile.typeAcquisition, + files: configFile.fileNames, + raw: configFile.raw, + errors: realizeDiagnostics(result.parseDiagnostics.concat(configFile.errors), "\r\n") + }; + }); + }; + CoreServicesShimObject.prototype.getDefaultCompilationSettings = function () { + return this.forwardJSONCall("getDefaultCompilationSettings()", function () { return ts.getDefaultCompilerOptions(); }); + }; + CoreServicesShimObject.prototype.discoverTypings = function (discoverTypingsJson) { + var _this = this; + var getCanonicalFileName = ts.createGetCanonicalFileName(/*useCaseSensitivefileNames:*/ false); + return this.forwardJSONCall("discoverTypings()", function () { + var info = JSON.parse(discoverTypingsJson); + if (_this.safeList === undefined) { + _this.safeList = ts.JsTyping.loadSafeList(_this.host, ts.toPath(info.safeListPath, info.safeListPath, getCanonicalFileName)); + } + return ts.JsTyping.discoverTypings(_this.host, function (msg) { return _this.logger.log(msg); }, info.fileNames, ts.toPath(info.projectRootPath, info.projectRootPath, getCanonicalFileName), _this.safeList, info.packageNameToTypingLocation, info.typeAcquisition, info.unresolvedImports, info.typesRegistry); + }); + }; + return CoreServicesShimObject; + }(ShimBase)); + var TypeScriptServicesFactory = /** @class */ (function () { + function TypeScriptServicesFactory() { + this._shims = []; + } + /* + * Returns script API version. + */ + TypeScriptServicesFactory.prototype.getServicesVersion = function () { + return ts.servicesVersion; + }; + TypeScriptServicesFactory.prototype.createLanguageServiceShim = function (host) { + try { + if (this.documentRegistry === undefined) { + this.documentRegistry = ts.createDocumentRegistry(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames(), host.getCurrentDirectory()); + } + var hostAdapter = new LanguageServiceShimHostAdapter(host); + var languageService = ts.createLanguageService(hostAdapter, this.documentRegistry, /*syntaxOnly*/ false); + return new LanguageServiceShimObject(this, host, languageService); + } + catch (err) { + logInternalError(host, err); + throw err; + } + }; + TypeScriptServicesFactory.prototype.createClassifierShim = function (logger) { + try { + return new ClassifierShimObject(this, logger); + } + catch (err) { + logInternalError(logger, err); + throw err; + } + }; + TypeScriptServicesFactory.prototype.createCoreServicesShim = function (host) { + try { + var adapter = new CoreServicesShimHostAdapter(host); + return new CoreServicesShimObject(this, host, adapter); + } + catch (err) { + logInternalError(host, err); + throw err; + } + }; + TypeScriptServicesFactory.prototype.close = function () { + // Forget all the registered shims + ts.clear(this._shims); + this.documentRegistry = undefined; + }; + TypeScriptServicesFactory.prototype.registerShim = function (shim) { + this._shims.push(shim); + }; + TypeScriptServicesFactory.prototype.unregisterShim = function (shim) { + for (var i = 0; i < this._shims.length; i++) { + if (this._shims[i] === shim) { + delete this._shims[i]; + return; + } + } + throw new Error("Invalid operation"); + }; + return TypeScriptServicesFactory; + }()); + ts.TypeScriptServicesFactory = TypeScriptServicesFactory; + if (typeof module !== "undefined" && module.exports) { + module.exports = ts; + } +})(ts || (ts = {})); +/* tslint:enable:no-in-operator */ +/* tslint:enable:no-null */ +/// TODO: this is used by VS, clean this up on both sides of the interface +/* @internal */ +var TypeScript; +(function (TypeScript) { + var Services; + (function (Services) { + Services.TypeScriptServicesFactory = ts.TypeScriptServicesFactory; + })(Services = TypeScript.Services || (TypeScript.Services = {})); +})(TypeScript || (TypeScript = {})); +// 'toolsVersion' gets consumed by the managed side, so it's not unused. +// TODO: it should be moved into a namespace though. +/* @internal */ +var toolsVersion = ts.versionMajorMinor; +//# sourceMappingURL=typescriptServices.out.js.map \ No newline at end of file diff --git a/node_modules/typescript/lib/typescriptServices.d.ts b/node_modules/typescript/lib/typescriptServices.d.ts new file mode 100644 index 0000000..4c854ca --- /dev/null +++ b/node_modules/typescript/lib/typescriptServices.d.ts @@ -0,0 +1,5565 @@ +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + +declare namespace ts { + const versionMajorMinor = "3.2"; + /** The version of the TypeScript compiler release */ + const version: string; +} +declare namespace ts { + /** + * Type of objects whose values are all of the same type. + * The `in` and `for-in` operators can *not* be safely used, + * since `Object.prototype` may be modified by outside code. + */ + interface MapLike { + [index: string]: T; + } + interface SortedReadonlyArray extends ReadonlyArray { + " __sortedArrayBrand": any; + } + interface SortedArray extends Array { + " __sortedArrayBrand": any; + } + /** ES6 Map interface, only read methods included. */ + interface ReadonlyMap { + get(key: string): T | undefined; + has(key: string): boolean; + forEach(action: (value: T, key: string) => void): void; + readonly size: number; + keys(): Iterator; + values(): Iterator; + entries(): Iterator<[string, T]>; + } + /** ES6 Map interface. */ + interface Map extends ReadonlyMap { + set(key: string, value: T): this; + delete(key: string): boolean; + clear(): void; + } + /** ES6 Iterator type. */ + interface Iterator { + next(): { + value: T; + done: false; + } | { + value: never; + done: true; + }; + } + /** Array that is only intended to be pushed to, never read. */ + interface Push { + push(...values: T[]): void; + } +} +declare namespace ts { + type Path = string & { + __pathBrand: any; + }; + interface TextRange { + pos: number; + end: number; + } + type JsDocSyntaxKind = SyntaxKind.EndOfFileToken | SyntaxKind.WhitespaceTrivia | SyntaxKind.AtToken | SyntaxKind.NewLineTrivia | SyntaxKind.AsteriskToken | SyntaxKind.OpenBraceToken | SyntaxKind.CloseBraceToken | SyntaxKind.LessThanToken | SyntaxKind.OpenBracketToken | SyntaxKind.CloseBracketToken | SyntaxKind.EqualsToken | SyntaxKind.CommaToken | SyntaxKind.DotToken | SyntaxKind.Identifier | SyntaxKind.NoSubstitutionTemplateLiteral | SyntaxKind.Unknown | KeywordSyntaxKind; + type KeywordSyntaxKind = SyntaxKind.AbstractKeyword | SyntaxKind.AnyKeyword | SyntaxKind.AsKeyword | SyntaxKind.BigIntKeyword | SyntaxKind.BooleanKeyword | SyntaxKind.BreakKeyword | SyntaxKind.CaseKeyword | SyntaxKind.CatchKeyword | SyntaxKind.ClassKeyword | SyntaxKind.ContinueKeyword | SyntaxKind.ConstKeyword | SyntaxKind.ConstructorKeyword | SyntaxKind.DebuggerKeyword | SyntaxKind.DeclareKeyword | SyntaxKind.DefaultKeyword | SyntaxKind.DeleteKeyword | SyntaxKind.DoKeyword | SyntaxKind.ElseKeyword | SyntaxKind.EnumKeyword | SyntaxKind.ExportKeyword | SyntaxKind.ExtendsKeyword | SyntaxKind.FalseKeyword | SyntaxKind.FinallyKeyword | SyntaxKind.ForKeyword | SyntaxKind.FromKeyword | SyntaxKind.FunctionKeyword | SyntaxKind.GetKeyword | SyntaxKind.IfKeyword | SyntaxKind.ImplementsKeyword | SyntaxKind.ImportKeyword | SyntaxKind.InKeyword | SyntaxKind.InferKeyword | SyntaxKind.InstanceOfKeyword | SyntaxKind.InterfaceKeyword | SyntaxKind.IsKeyword | SyntaxKind.KeyOfKeyword | SyntaxKind.LetKeyword | SyntaxKind.ModuleKeyword | SyntaxKind.NamespaceKeyword | SyntaxKind.NeverKeyword | SyntaxKind.NewKeyword | SyntaxKind.NullKeyword | SyntaxKind.NumberKeyword | SyntaxKind.ObjectKeyword | SyntaxKind.PackageKeyword | SyntaxKind.PrivateKeyword | SyntaxKind.ProtectedKeyword | SyntaxKind.PublicKeyword | SyntaxKind.ReadonlyKeyword | SyntaxKind.RequireKeyword | SyntaxKind.GlobalKeyword | SyntaxKind.ReturnKeyword | SyntaxKind.SetKeyword | SyntaxKind.StaticKeyword | SyntaxKind.StringKeyword | SyntaxKind.SuperKeyword | SyntaxKind.SwitchKeyword | SyntaxKind.SymbolKeyword | SyntaxKind.ThisKeyword | SyntaxKind.ThrowKeyword | SyntaxKind.TrueKeyword | SyntaxKind.TryKeyword | SyntaxKind.TypeKeyword | SyntaxKind.TypeOfKeyword | SyntaxKind.UndefinedKeyword | SyntaxKind.UniqueKeyword | SyntaxKind.UnknownKeyword | SyntaxKind.VarKeyword | SyntaxKind.VoidKeyword | SyntaxKind.WhileKeyword | SyntaxKind.WithKeyword | SyntaxKind.YieldKeyword | SyntaxKind.AsyncKeyword | SyntaxKind.AwaitKeyword | SyntaxKind.OfKeyword; + type JsxTokenSyntaxKind = SyntaxKind.LessThanSlashToken | SyntaxKind.EndOfFileToken | SyntaxKind.ConflictMarkerTrivia | SyntaxKind.JsxText | SyntaxKind.JsxTextAllWhiteSpaces | SyntaxKind.OpenBraceToken | SyntaxKind.LessThanToken; + enum SyntaxKind { + Unknown = 0, + EndOfFileToken = 1, + SingleLineCommentTrivia = 2, + MultiLineCommentTrivia = 3, + NewLineTrivia = 4, + WhitespaceTrivia = 5, + ShebangTrivia = 6, + ConflictMarkerTrivia = 7, + NumericLiteral = 8, + BigIntLiteral = 9, + StringLiteral = 10, + JsxText = 11, + JsxTextAllWhiteSpaces = 12, + RegularExpressionLiteral = 13, + NoSubstitutionTemplateLiteral = 14, + TemplateHead = 15, + TemplateMiddle = 16, + TemplateTail = 17, + OpenBraceToken = 18, + CloseBraceToken = 19, + OpenParenToken = 20, + CloseParenToken = 21, + OpenBracketToken = 22, + CloseBracketToken = 23, + DotToken = 24, + DotDotDotToken = 25, + SemicolonToken = 26, + CommaToken = 27, + LessThanToken = 28, + LessThanSlashToken = 29, + GreaterThanToken = 30, + LessThanEqualsToken = 31, + GreaterThanEqualsToken = 32, + EqualsEqualsToken = 33, + ExclamationEqualsToken = 34, + EqualsEqualsEqualsToken = 35, + ExclamationEqualsEqualsToken = 36, + EqualsGreaterThanToken = 37, + PlusToken = 38, + MinusToken = 39, + AsteriskToken = 40, + AsteriskAsteriskToken = 41, + SlashToken = 42, + PercentToken = 43, + PlusPlusToken = 44, + MinusMinusToken = 45, + LessThanLessThanToken = 46, + GreaterThanGreaterThanToken = 47, + GreaterThanGreaterThanGreaterThanToken = 48, + AmpersandToken = 49, + BarToken = 50, + CaretToken = 51, + ExclamationToken = 52, + TildeToken = 53, + AmpersandAmpersandToken = 54, + BarBarToken = 55, + QuestionToken = 56, + ColonToken = 57, + AtToken = 58, + EqualsToken = 59, + PlusEqualsToken = 60, + MinusEqualsToken = 61, + AsteriskEqualsToken = 62, + AsteriskAsteriskEqualsToken = 63, + SlashEqualsToken = 64, + PercentEqualsToken = 65, + LessThanLessThanEqualsToken = 66, + GreaterThanGreaterThanEqualsToken = 67, + GreaterThanGreaterThanGreaterThanEqualsToken = 68, + AmpersandEqualsToken = 69, + BarEqualsToken = 70, + CaretEqualsToken = 71, + Identifier = 72, + BreakKeyword = 73, + CaseKeyword = 74, + CatchKeyword = 75, + ClassKeyword = 76, + ConstKeyword = 77, + ContinueKeyword = 78, + DebuggerKeyword = 79, + DefaultKeyword = 80, + DeleteKeyword = 81, + DoKeyword = 82, + ElseKeyword = 83, + EnumKeyword = 84, + ExportKeyword = 85, + ExtendsKeyword = 86, + FalseKeyword = 87, + FinallyKeyword = 88, + ForKeyword = 89, + FunctionKeyword = 90, + IfKeyword = 91, + ImportKeyword = 92, + InKeyword = 93, + InstanceOfKeyword = 94, + NewKeyword = 95, + NullKeyword = 96, + ReturnKeyword = 97, + SuperKeyword = 98, + SwitchKeyword = 99, + ThisKeyword = 100, + ThrowKeyword = 101, + TrueKeyword = 102, + TryKeyword = 103, + TypeOfKeyword = 104, + VarKeyword = 105, + VoidKeyword = 106, + WhileKeyword = 107, + WithKeyword = 108, + ImplementsKeyword = 109, + InterfaceKeyword = 110, + LetKeyword = 111, + PackageKeyword = 112, + PrivateKeyword = 113, + ProtectedKeyword = 114, + PublicKeyword = 115, + StaticKeyword = 116, + YieldKeyword = 117, + AbstractKeyword = 118, + AsKeyword = 119, + AnyKeyword = 120, + AsyncKeyword = 121, + AwaitKeyword = 122, + BooleanKeyword = 123, + ConstructorKeyword = 124, + DeclareKeyword = 125, + GetKeyword = 126, + InferKeyword = 127, + IsKeyword = 128, + KeyOfKeyword = 129, + ModuleKeyword = 130, + NamespaceKeyword = 131, + NeverKeyword = 132, + ReadonlyKeyword = 133, + RequireKeyword = 134, + NumberKeyword = 135, + ObjectKeyword = 136, + SetKeyword = 137, + StringKeyword = 138, + SymbolKeyword = 139, + TypeKeyword = 140, + UndefinedKeyword = 141, + UniqueKeyword = 142, + UnknownKeyword = 143, + FromKeyword = 144, + GlobalKeyword = 145, + BigIntKeyword = 146, + OfKeyword = 147, + QualifiedName = 148, + ComputedPropertyName = 149, + TypeParameter = 150, + Parameter = 151, + Decorator = 152, + PropertySignature = 153, + PropertyDeclaration = 154, + MethodSignature = 155, + MethodDeclaration = 156, + Constructor = 157, + GetAccessor = 158, + SetAccessor = 159, + CallSignature = 160, + ConstructSignature = 161, + IndexSignature = 162, + TypePredicate = 163, + TypeReference = 164, + FunctionType = 165, + ConstructorType = 166, + TypeQuery = 167, + TypeLiteral = 168, + ArrayType = 169, + TupleType = 170, + OptionalType = 171, + RestType = 172, + UnionType = 173, + IntersectionType = 174, + ConditionalType = 175, + InferType = 176, + ParenthesizedType = 177, + ThisType = 178, + TypeOperator = 179, + IndexedAccessType = 180, + MappedType = 181, + LiteralType = 182, + ImportType = 183, + ObjectBindingPattern = 184, + ArrayBindingPattern = 185, + BindingElement = 186, + ArrayLiteralExpression = 187, + ObjectLiteralExpression = 188, + PropertyAccessExpression = 189, + ElementAccessExpression = 190, + CallExpression = 191, + NewExpression = 192, + TaggedTemplateExpression = 193, + TypeAssertionExpression = 194, + ParenthesizedExpression = 195, + FunctionExpression = 196, + ArrowFunction = 197, + DeleteExpression = 198, + TypeOfExpression = 199, + VoidExpression = 200, + AwaitExpression = 201, + PrefixUnaryExpression = 202, + PostfixUnaryExpression = 203, + BinaryExpression = 204, + ConditionalExpression = 205, + TemplateExpression = 206, + YieldExpression = 207, + SpreadElement = 208, + ClassExpression = 209, + OmittedExpression = 210, + ExpressionWithTypeArguments = 211, + AsExpression = 212, + NonNullExpression = 213, + MetaProperty = 214, + SyntheticExpression = 215, + TemplateSpan = 216, + SemicolonClassElement = 217, + Block = 218, + VariableStatement = 219, + EmptyStatement = 220, + ExpressionStatement = 221, + IfStatement = 222, + DoStatement = 223, + WhileStatement = 224, + ForStatement = 225, + ForInStatement = 226, + ForOfStatement = 227, + ContinueStatement = 228, + BreakStatement = 229, + ReturnStatement = 230, + WithStatement = 231, + SwitchStatement = 232, + LabeledStatement = 233, + ThrowStatement = 234, + TryStatement = 235, + DebuggerStatement = 236, + VariableDeclaration = 237, + VariableDeclarationList = 238, + FunctionDeclaration = 239, + ClassDeclaration = 240, + InterfaceDeclaration = 241, + TypeAliasDeclaration = 242, + EnumDeclaration = 243, + ModuleDeclaration = 244, + ModuleBlock = 245, + CaseBlock = 246, + NamespaceExportDeclaration = 247, + ImportEqualsDeclaration = 248, + ImportDeclaration = 249, + ImportClause = 250, + NamespaceImport = 251, + NamedImports = 252, + ImportSpecifier = 253, + ExportAssignment = 254, + ExportDeclaration = 255, + NamedExports = 256, + ExportSpecifier = 257, + MissingDeclaration = 258, + ExternalModuleReference = 259, + JsxElement = 260, + JsxSelfClosingElement = 261, + JsxOpeningElement = 262, + JsxClosingElement = 263, + JsxFragment = 264, + JsxOpeningFragment = 265, + JsxClosingFragment = 266, + JsxAttribute = 267, + JsxAttributes = 268, + JsxSpreadAttribute = 269, + JsxExpression = 270, + CaseClause = 271, + DefaultClause = 272, + HeritageClause = 273, + CatchClause = 274, + PropertyAssignment = 275, + ShorthandPropertyAssignment = 276, + SpreadAssignment = 277, + EnumMember = 278, + SourceFile = 279, + Bundle = 280, + UnparsedSource = 281, + InputFiles = 282, + JSDocTypeExpression = 283, + JSDocAllType = 284, + JSDocUnknownType = 285, + JSDocNullableType = 286, + JSDocNonNullableType = 287, + JSDocOptionalType = 288, + JSDocFunctionType = 289, + JSDocVariadicType = 290, + JSDocComment = 291, + JSDocTypeLiteral = 292, + JSDocSignature = 293, + JSDocTag = 294, + JSDocAugmentsTag = 295, + JSDocClassTag = 296, + JSDocCallbackTag = 297, + JSDocEnumTag = 298, + JSDocParameterTag = 299, + JSDocReturnTag = 300, + JSDocThisTag = 301, + JSDocTypeTag = 302, + JSDocTemplateTag = 303, + JSDocTypedefTag = 304, + JSDocPropertyTag = 305, + SyntaxList = 306, + NotEmittedStatement = 307, + PartiallyEmittedExpression = 308, + CommaListExpression = 309, + MergeDeclarationMarker = 310, + EndOfDeclarationMarker = 311, + Count = 312, + FirstAssignment = 59, + LastAssignment = 71, + FirstCompoundAssignment = 60, + LastCompoundAssignment = 71, + FirstReservedWord = 73, + LastReservedWord = 108, + FirstKeyword = 73, + LastKeyword = 147, + FirstFutureReservedWord = 109, + LastFutureReservedWord = 117, + FirstTypeNode = 163, + LastTypeNode = 183, + FirstPunctuation = 18, + LastPunctuation = 71, + FirstToken = 0, + LastToken = 147, + FirstTriviaToken = 2, + LastTriviaToken = 7, + FirstLiteralToken = 8, + LastLiteralToken = 14, + FirstTemplateToken = 14, + LastTemplateToken = 17, + FirstBinaryOperator = 28, + LastBinaryOperator = 71, + FirstNode = 148, + FirstJSDocNode = 283, + LastJSDocNode = 305, + FirstJSDocTagNode = 294, + LastJSDocTagNode = 305 + } + enum NodeFlags { + None = 0, + Let = 1, + Const = 2, + NestedNamespace = 4, + Synthesized = 8, + Namespace = 16, + ExportContext = 32, + ContainsThis = 64, + HasImplicitReturn = 128, + HasExplicitReturn = 256, + GlobalAugmentation = 512, + HasAsyncFunctions = 1024, + DisallowInContext = 2048, + YieldContext = 4096, + DecoratorContext = 8192, + AwaitContext = 16384, + ThisNodeHasError = 32768, + JavaScriptFile = 65536, + ThisNodeOrAnySubNodesHasError = 131072, + HasAggregatedChildData = 262144, + JSDoc = 2097152, + JsonFile = 16777216, + BlockScoped = 3, + ReachabilityCheckFlags = 384, + ReachabilityAndEmitFlags = 1408, + ContextFlags = 12679168, + TypeExcludesFlags = 20480 + } + enum ModifierFlags { + None = 0, + Export = 1, + Ambient = 2, + Public = 4, + Private = 8, + Protected = 16, + Static = 32, + Readonly = 64, + Abstract = 128, + Async = 256, + Default = 512, + Const = 2048, + HasComputedFlags = 536870912, + AccessibilityModifier = 28, + ParameterPropertyModifier = 92, + NonPublicAccessibilityModifier = 24, + TypeScriptModifier = 2270, + ExportDefault = 513, + All = 3071 + } + enum JsxFlags { + None = 0, + /** An element from a named property of the JSX.IntrinsicElements interface */ + IntrinsicNamedElement = 1, + /** An element inferred from the string index signature of the JSX.IntrinsicElements interface */ + IntrinsicIndexedElement = 2, + IntrinsicElement = 3 + } + interface Node extends TextRange { + kind: SyntaxKind; + flags: NodeFlags; + decorators?: NodeArray; + modifiers?: ModifiersArray; + parent: Node; + } + interface JSDocContainer { + } + type HasJSDoc = ParameterDeclaration | CallSignatureDeclaration | ConstructSignatureDeclaration | MethodSignature | PropertySignature | ArrowFunction | ParenthesizedExpression | SpreadAssignment | ShorthandPropertyAssignment | PropertyAssignment | FunctionExpression | LabeledStatement | ExpressionStatement | VariableStatement | FunctionDeclaration | ConstructorDeclaration | MethodDeclaration | PropertyDeclaration | AccessorDeclaration | ClassLikeDeclaration | InterfaceDeclaration | TypeAliasDeclaration | EnumMember | EnumDeclaration | ModuleDeclaration | ImportEqualsDeclaration | IndexSignatureDeclaration | FunctionTypeNode | ConstructorTypeNode | JSDocFunctionType | ExportDeclaration | EndOfFileToken; + type HasType = SignatureDeclaration | VariableDeclaration | ParameterDeclaration | PropertySignature | PropertyDeclaration | TypePredicateNode | ParenthesizedTypeNode | TypeOperatorNode | MappedTypeNode | AssertionExpression | TypeAliasDeclaration | JSDocTypeExpression | JSDocNonNullableType | JSDocNullableType | JSDocOptionalType | JSDocVariadicType; + type HasInitializer = HasExpressionInitializer | ForStatement | ForInStatement | ForOfStatement | JsxAttribute; + type HasExpressionInitializer = VariableDeclaration | ParameterDeclaration | BindingElement | PropertySignature | PropertyDeclaration | PropertyAssignment | EnumMember; + interface NodeArray extends ReadonlyArray, TextRange { + hasTrailingComma?: boolean; + } + interface Token extends Node { + kind: TKind; + } + type DotDotDotToken = Token; + type QuestionToken = Token; + type ExclamationToken = Token; + type ColonToken = Token; + type EqualsToken = Token; + type AsteriskToken = Token; + type EqualsGreaterThanToken = Token; + type EndOfFileToken = Token & JSDocContainer; + type ReadonlyToken = Token; + type AwaitKeywordToken = Token; + type PlusToken = Token; + type MinusToken = Token; + type Modifier = Token | Token | Token | Token | Token | Token | Token | Token | Token | Token | Token; + type ModifiersArray = NodeArray; + interface Identifier extends PrimaryExpression, Declaration { + kind: SyntaxKind.Identifier; + /** + * Prefer to use `id.unescapedText`. (Note: This is available only in services, not internally to the TypeScript compiler.) + * Text of identifier, but if the identifier begins with two underscores, this will begin with three. + */ + escapedText: __String; + originalKeywordKind?: SyntaxKind; + isInJSDocNamespace?: boolean; + } + interface TransientIdentifier extends Identifier { + resolvedSymbol: Symbol; + } + interface QualifiedName extends Node { + kind: SyntaxKind.QualifiedName; + left: EntityName; + right: Identifier; + } + type EntityName = Identifier | QualifiedName; + type PropertyName = Identifier | StringLiteral | NumericLiteral | ComputedPropertyName; + type DeclarationName = Identifier | StringLiteralLike | NumericLiteral | ComputedPropertyName | BindingPattern; + interface Declaration extends Node { + _declarationBrand: any; + } + interface NamedDeclaration extends Declaration { + name?: DeclarationName; + } + interface DeclarationStatement extends NamedDeclaration, Statement { + name?: Identifier | StringLiteral | NumericLiteral; + } + interface ComputedPropertyName extends Node { + parent: Declaration; + kind: SyntaxKind.ComputedPropertyName; + expression: Expression; + } + interface Decorator extends Node { + kind: SyntaxKind.Decorator; + parent: NamedDeclaration; + expression: LeftHandSideExpression; + } + interface TypeParameterDeclaration extends NamedDeclaration { + kind: SyntaxKind.TypeParameter; + parent: DeclarationWithTypeParameterChildren | InferTypeNode; + name: Identifier; + /** Note: Consider calling `getEffectiveConstraintOfTypeParameter` */ + constraint?: TypeNode; + default?: TypeNode; + expression?: Expression; + } + interface SignatureDeclarationBase extends NamedDeclaration, JSDocContainer { + kind: SignatureDeclaration["kind"]; + name?: PropertyName; + typeParameters?: NodeArray; + parameters: NodeArray; + type?: TypeNode; + } + type SignatureDeclaration = CallSignatureDeclaration | ConstructSignatureDeclaration | MethodSignature | IndexSignatureDeclaration | FunctionTypeNode | ConstructorTypeNode | JSDocFunctionType | FunctionDeclaration | MethodDeclaration | ConstructorDeclaration | AccessorDeclaration | FunctionExpression | ArrowFunction; + interface CallSignatureDeclaration extends SignatureDeclarationBase, TypeElement { + kind: SyntaxKind.CallSignature; + } + interface ConstructSignatureDeclaration extends SignatureDeclarationBase, TypeElement { + kind: SyntaxKind.ConstructSignature; + } + type BindingName = Identifier | BindingPattern; + interface VariableDeclaration extends NamedDeclaration { + kind: SyntaxKind.VariableDeclaration; + parent: VariableDeclarationList | CatchClause; + name: BindingName; + exclamationToken?: ExclamationToken; + type?: TypeNode; + initializer?: Expression; + } + interface VariableDeclarationList extends Node { + kind: SyntaxKind.VariableDeclarationList; + parent: VariableStatement | ForStatement | ForOfStatement | ForInStatement; + declarations: NodeArray; + } + interface ParameterDeclaration extends NamedDeclaration, JSDocContainer { + kind: SyntaxKind.Parameter; + parent: SignatureDeclaration; + dotDotDotToken?: DotDotDotToken; + name: BindingName; + questionToken?: QuestionToken; + type?: TypeNode; + initializer?: Expression; + } + interface BindingElement extends NamedDeclaration { + kind: SyntaxKind.BindingElement; + parent: BindingPattern; + propertyName?: PropertyName; + dotDotDotToken?: DotDotDotToken; + name: BindingName; + initializer?: Expression; + } + interface PropertySignature extends TypeElement, JSDocContainer { + kind: SyntaxKind.PropertySignature; + name: PropertyName; + questionToken?: QuestionToken; + type?: TypeNode; + initializer?: Expression; + } + interface PropertyDeclaration extends ClassElement, JSDocContainer { + kind: SyntaxKind.PropertyDeclaration; + parent: ClassLikeDeclaration; + name: PropertyName; + questionToken?: QuestionToken; + exclamationToken?: ExclamationToken; + type?: TypeNode; + initializer?: Expression; + } + interface ObjectLiteralElement extends NamedDeclaration { + _objectLiteralBrandBrand: any; + name?: PropertyName; + } + /** Unlike ObjectLiteralElement, excludes JSXAttribute and JSXSpreadAttribute. */ + type ObjectLiteralElementLike = PropertyAssignment | ShorthandPropertyAssignment | SpreadAssignment | MethodDeclaration | AccessorDeclaration; + interface PropertyAssignment extends ObjectLiteralElement, JSDocContainer { + parent: ObjectLiteralExpression; + kind: SyntaxKind.PropertyAssignment; + name: PropertyName; + questionToken?: QuestionToken; + initializer: Expression; + } + interface ShorthandPropertyAssignment extends ObjectLiteralElement, JSDocContainer { + parent: ObjectLiteralExpression; + kind: SyntaxKind.ShorthandPropertyAssignment; + name: Identifier; + questionToken?: QuestionToken; + exclamationToken?: ExclamationToken; + equalsToken?: Token; + objectAssignmentInitializer?: Expression; + } + interface SpreadAssignment extends ObjectLiteralElement, JSDocContainer { + parent: ObjectLiteralExpression; + kind: SyntaxKind.SpreadAssignment; + expression: Expression; + } + type VariableLikeDeclaration = VariableDeclaration | ParameterDeclaration | BindingElement | PropertyDeclaration | PropertyAssignment | PropertySignature | JsxAttribute | ShorthandPropertyAssignment | EnumMember | JSDocPropertyTag | JSDocParameterTag; + interface PropertyLikeDeclaration extends NamedDeclaration { + name: PropertyName; + } + interface ObjectBindingPattern extends Node { + kind: SyntaxKind.ObjectBindingPattern; + parent: VariableDeclaration | ParameterDeclaration | BindingElement; + elements: NodeArray; + } + interface ArrayBindingPattern extends Node { + kind: SyntaxKind.ArrayBindingPattern; + parent: VariableDeclaration | ParameterDeclaration | BindingElement; + elements: NodeArray; + } + type BindingPattern = ObjectBindingPattern | ArrayBindingPattern; + type ArrayBindingElement = BindingElement | OmittedExpression; + /** + * Several node kinds share function-like features such as a signature, + * a name, and a body. These nodes should extend FunctionLikeDeclarationBase. + * Examples: + * - FunctionDeclaration + * - MethodDeclaration + * - AccessorDeclaration + */ + interface FunctionLikeDeclarationBase extends SignatureDeclarationBase { + _functionLikeDeclarationBrand: any; + asteriskToken?: AsteriskToken; + questionToken?: QuestionToken; + exclamationToken?: ExclamationToken; + body?: Block | Expression; + } + type FunctionLikeDeclaration = FunctionDeclaration | MethodDeclaration | GetAccessorDeclaration | SetAccessorDeclaration | ConstructorDeclaration | FunctionExpression | ArrowFunction; + /** @deprecated Use SignatureDeclaration */ + type FunctionLike = SignatureDeclaration; + interface FunctionDeclaration extends FunctionLikeDeclarationBase, DeclarationStatement { + kind: SyntaxKind.FunctionDeclaration; + name?: Identifier; + body?: FunctionBody; + } + interface MethodSignature extends SignatureDeclarationBase, TypeElement { + kind: SyntaxKind.MethodSignature; + parent: ObjectTypeDeclaration; + name: PropertyName; + } + interface MethodDeclaration extends FunctionLikeDeclarationBase, ClassElement, ObjectLiteralElement, JSDocContainer { + kind: SyntaxKind.MethodDeclaration; + parent: ClassLikeDeclaration | ObjectLiteralExpression; + name: PropertyName; + body?: FunctionBody; + } + interface ConstructorDeclaration extends FunctionLikeDeclarationBase, ClassElement, JSDocContainer { + kind: SyntaxKind.Constructor; + parent: ClassLikeDeclaration; + body?: FunctionBody; + } + /** For when we encounter a semicolon in a class declaration. ES6 allows these as class elements. */ + interface SemicolonClassElement extends ClassElement { + kind: SyntaxKind.SemicolonClassElement; + parent: ClassLikeDeclaration; + } + interface GetAccessorDeclaration extends FunctionLikeDeclarationBase, ClassElement, ObjectLiteralElement, JSDocContainer { + kind: SyntaxKind.GetAccessor; + parent: ClassLikeDeclaration | ObjectLiteralExpression; + name: PropertyName; + body?: FunctionBody; + } + interface SetAccessorDeclaration extends FunctionLikeDeclarationBase, ClassElement, ObjectLiteralElement, JSDocContainer { + kind: SyntaxKind.SetAccessor; + parent: ClassLikeDeclaration | ObjectLiteralExpression; + name: PropertyName; + body?: FunctionBody; + } + type AccessorDeclaration = GetAccessorDeclaration | SetAccessorDeclaration; + interface IndexSignatureDeclaration extends SignatureDeclarationBase, ClassElement, TypeElement { + kind: SyntaxKind.IndexSignature; + parent: ObjectTypeDeclaration; + } + interface TypeNode extends Node { + _typeNodeBrand: any; + } + interface KeywordTypeNode extends TypeNode { + kind: SyntaxKind.AnyKeyword | SyntaxKind.UnknownKeyword | SyntaxKind.NumberKeyword | SyntaxKind.BigIntKeyword | SyntaxKind.ObjectKeyword | SyntaxKind.BooleanKeyword | SyntaxKind.StringKeyword | SyntaxKind.SymbolKeyword | SyntaxKind.ThisKeyword | SyntaxKind.VoidKeyword | SyntaxKind.UndefinedKeyword | SyntaxKind.NullKeyword | SyntaxKind.NeverKeyword; + } + interface ImportTypeNode extends NodeWithTypeArguments { + kind: SyntaxKind.ImportType; + isTypeOf?: boolean; + argument: TypeNode; + qualifier?: EntityName; + } + interface ThisTypeNode extends TypeNode { + kind: SyntaxKind.ThisType; + } + type FunctionOrConstructorTypeNode = FunctionTypeNode | ConstructorTypeNode; + interface FunctionOrConstructorTypeNodeBase extends TypeNode, SignatureDeclarationBase { + kind: SyntaxKind.FunctionType | SyntaxKind.ConstructorType; + type: TypeNode; + } + interface FunctionTypeNode extends FunctionOrConstructorTypeNodeBase { + kind: SyntaxKind.FunctionType; + } + interface ConstructorTypeNode extends FunctionOrConstructorTypeNodeBase { + kind: SyntaxKind.ConstructorType; + } + interface NodeWithTypeArguments extends TypeNode { + typeArguments?: NodeArray; + } + type TypeReferenceType = TypeReferenceNode | ExpressionWithTypeArguments; + interface TypeReferenceNode extends NodeWithTypeArguments { + kind: SyntaxKind.TypeReference; + typeName: EntityName; + } + interface TypePredicateNode extends TypeNode { + kind: SyntaxKind.TypePredicate; + parent: SignatureDeclaration | JSDocTypeExpression; + parameterName: Identifier | ThisTypeNode; + type: TypeNode; + } + interface TypeQueryNode extends TypeNode { + kind: SyntaxKind.TypeQuery; + exprName: EntityName; + } + interface TypeLiteralNode extends TypeNode, Declaration { + kind: SyntaxKind.TypeLiteral; + members: NodeArray; + } + interface ArrayTypeNode extends TypeNode { + kind: SyntaxKind.ArrayType; + elementType: TypeNode; + } + interface TupleTypeNode extends TypeNode { + kind: SyntaxKind.TupleType; + elementTypes: NodeArray; + } + interface OptionalTypeNode extends TypeNode { + kind: SyntaxKind.OptionalType; + type: TypeNode; + } + interface RestTypeNode extends TypeNode { + kind: SyntaxKind.RestType; + type: TypeNode; + } + type UnionOrIntersectionTypeNode = UnionTypeNode | IntersectionTypeNode; + interface UnionTypeNode extends TypeNode { + kind: SyntaxKind.UnionType; + types: NodeArray; + } + interface IntersectionTypeNode extends TypeNode { + kind: SyntaxKind.IntersectionType; + types: NodeArray; + } + interface ConditionalTypeNode extends TypeNode { + kind: SyntaxKind.ConditionalType; + checkType: TypeNode; + extendsType: TypeNode; + trueType: TypeNode; + falseType: TypeNode; + } + interface InferTypeNode extends TypeNode { + kind: SyntaxKind.InferType; + typeParameter: TypeParameterDeclaration; + } + interface ParenthesizedTypeNode extends TypeNode { + kind: SyntaxKind.ParenthesizedType; + type: TypeNode; + } + interface TypeOperatorNode extends TypeNode { + kind: SyntaxKind.TypeOperator; + operator: SyntaxKind.KeyOfKeyword | SyntaxKind.UniqueKeyword; + type: TypeNode; + } + interface IndexedAccessTypeNode extends TypeNode { + kind: SyntaxKind.IndexedAccessType; + objectType: TypeNode; + indexType: TypeNode; + } + interface MappedTypeNode extends TypeNode, Declaration { + kind: SyntaxKind.MappedType; + readonlyToken?: ReadonlyToken | PlusToken | MinusToken; + typeParameter: TypeParameterDeclaration; + questionToken?: QuestionToken | PlusToken | MinusToken; + type?: TypeNode; + } + interface LiteralTypeNode extends TypeNode { + kind: SyntaxKind.LiteralType; + literal: BooleanLiteral | LiteralExpression | PrefixUnaryExpression; + } + interface StringLiteral extends LiteralExpression { + kind: SyntaxKind.StringLiteral; + } + type StringLiteralLike = StringLiteral | NoSubstitutionTemplateLiteral; + interface Expression extends Node { + _expressionBrand: any; + } + interface OmittedExpression extends Expression { + kind: SyntaxKind.OmittedExpression; + } + interface PartiallyEmittedExpression extends LeftHandSideExpression { + kind: SyntaxKind.PartiallyEmittedExpression; + expression: Expression; + } + interface UnaryExpression extends Expression { + _unaryExpressionBrand: any; + } + /** Deprecated, please use UpdateExpression */ + type IncrementExpression = UpdateExpression; + interface UpdateExpression extends UnaryExpression { + _updateExpressionBrand: any; + } + type PrefixUnaryOperator = SyntaxKind.PlusPlusToken | SyntaxKind.MinusMinusToken | SyntaxKind.PlusToken | SyntaxKind.MinusToken | SyntaxKind.TildeToken | SyntaxKind.ExclamationToken; + interface PrefixUnaryExpression extends UpdateExpression { + kind: SyntaxKind.PrefixUnaryExpression; + operator: PrefixUnaryOperator; + operand: UnaryExpression; + } + type PostfixUnaryOperator = SyntaxKind.PlusPlusToken | SyntaxKind.MinusMinusToken; + interface PostfixUnaryExpression extends UpdateExpression { + kind: SyntaxKind.PostfixUnaryExpression; + operand: LeftHandSideExpression; + operator: PostfixUnaryOperator; + } + interface LeftHandSideExpression extends UpdateExpression { + _leftHandSideExpressionBrand: any; + } + interface MemberExpression extends LeftHandSideExpression { + _memberExpressionBrand: any; + } + interface PrimaryExpression extends MemberExpression { + _primaryExpressionBrand: any; + } + interface NullLiteral extends PrimaryExpression, TypeNode { + kind: SyntaxKind.NullKeyword; + } + interface BooleanLiteral extends PrimaryExpression, TypeNode { + kind: SyntaxKind.TrueKeyword | SyntaxKind.FalseKeyword; + } + interface ThisExpression extends PrimaryExpression, KeywordTypeNode { + kind: SyntaxKind.ThisKeyword; + } + interface SuperExpression extends PrimaryExpression { + kind: SyntaxKind.SuperKeyword; + } + interface ImportExpression extends PrimaryExpression { + kind: SyntaxKind.ImportKeyword; + } + interface DeleteExpression extends UnaryExpression { + kind: SyntaxKind.DeleteExpression; + expression: UnaryExpression; + } + interface TypeOfExpression extends UnaryExpression { + kind: SyntaxKind.TypeOfExpression; + expression: UnaryExpression; + } + interface VoidExpression extends UnaryExpression { + kind: SyntaxKind.VoidExpression; + expression: UnaryExpression; + } + interface AwaitExpression extends UnaryExpression { + kind: SyntaxKind.AwaitExpression; + expression: UnaryExpression; + } + interface YieldExpression extends Expression { + kind: SyntaxKind.YieldExpression; + asteriskToken?: AsteriskToken; + expression?: Expression; + } + interface SyntheticExpression extends Expression { + kind: SyntaxKind.SyntheticExpression; + isSpread: boolean; + type: Type; + } + type ExponentiationOperator = SyntaxKind.AsteriskAsteriskToken; + type MultiplicativeOperator = SyntaxKind.AsteriskToken | SyntaxKind.SlashToken | SyntaxKind.PercentToken; + type MultiplicativeOperatorOrHigher = ExponentiationOperator | MultiplicativeOperator; + type AdditiveOperator = SyntaxKind.PlusToken | SyntaxKind.MinusToken; + type AdditiveOperatorOrHigher = MultiplicativeOperatorOrHigher | AdditiveOperator; + type ShiftOperator = SyntaxKind.LessThanLessThanToken | SyntaxKind.GreaterThanGreaterThanToken | SyntaxKind.GreaterThanGreaterThanGreaterThanToken; + type ShiftOperatorOrHigher = AdditiveOperatorOrHigher | ShiftOperator; + type RelationalOperator = SyntaxKind.LessThanToken | SyntaxKind.LessThanEqualsToken | SyntaxKind.GreaterThanToken | SyntaxKind.GreaterThanEqualsToken | SyntaxKind.InstanceOfKeyword | SyntaxKind.InKeyword; + type RelationalOperatorOrHigher = ShiftOperatorOrHigher | RelationalOperator; + type EqualityOperator = SyntaxKind.EqualsEqualsToken | SyntaxKind.EqualsEqualsEqualsToken | SyntaxKind.ExclamationEqualsEqualsToken | SyntaxKind.ExclamationEqualsToken; + type EqualityOperatorOrHigher = RelationalOperatorOrHigher | EqualityOperator; + type BitwiseOperator = SyntaxKind.AmpersandToken | SyntaxKind.BarToken | SyntaxKind.CaretToken; + type BitwiseOperatorOrHigher = EqualityOperatorOrHigher | BitwiseOperator; + type LogicalOperator = SyntaxKind.AmpersandAmpersandToken | SyntaxKind.BarBarToken; + type LogicalOperatorOrHigher = BitwiseOperatorOrHigher | LogicalOperator; + type CompoundAssignmentOperator = SyntaxKind.PlusEqualsToken | SyntaxKind.MinusEqualsToken | SyntaxKind.AsteriskAsteriskEqualsToken | SyntaxKind.AsteriskEqualsToken | SyntaxKind.SlashEqualsToken | SyntaxKind.PercentEqualsToken | SyntaxKind.AmpersandEqualsToken | SyntaxKind.BarEqualsToken | SyntaxKind.CaretEqualsToken | SyntaxKind.LessThanLessThanEqualsToken | SyntaxKind.GreaterThanGreaterThanGreaterThanEqualsToken | SyntaxKind.GreaterThanGreaterThanEqualsToken; + type AssignmentOperator = SyntaxKind.EqualsToken | CompoundAssignmentOperator; + type AssignmentOperatorOrHigher = LogicalOperatorOrHigher | AssignmentOperator; + type BinaryOperator = AssignmentOperatorOrHigher | SyntaxKind.CommaToken; + type BinaryOperatorToken = Token; + interface BinaryExpression extends Expression, Declaration { + kind: SyntaxKind.BinaryExpression; + left: Expression; + operatorToken: BinaryOperatorToken; + right: Expression; + } + type AssignmentOperatorToken = Token; + interface AssignmentExpression extends BinaryExpression { + left: LeftHandSideExpression; + operatorToken: TOperator; + } + interface ObjectDestructuringAssignment extends AssignmentExpression { + left: ObjectLiteralExpression; + } + interface ArrayDestructuringAssignment extends AssignmentExpression { + left: ArrayLiteralExpression; + } + type DestructuringAssignment = ObjectDestructuringAssignment | ArrayDestructuringAssignment; + type BindingOrAssignmentElement = VariableDeclaration | ParameterDeclaration | BindingElement | PropertyAssignment | ShorthandPropertyAssignment | SpreadAssignment | OmittedExpression | SpreadElement | ArrayLiteralExpression | ObjectLiteralExpression | AssignmentExpression | Identifier | PropertyAccessExpression | ElementAccessExpression; + type BindingOrAssignmentElementRestIndicator = DotDotDotToken | SpreadElement | SpreadAssignment; + type BindingOrAssignmentElementTarget = BindingOrAssignmentPattern | Identifier | PropertyAccessExpression | ElementAccessExpression | OmittedExpression; + type ObjectBindingOrAssignmentPattern = ObjectBindingPattern | ObjectLiteralExpression; + type ArrayBindingOrAssignmentPattern = ArrayBindingPattern | ArrayLiteralExpression; + type AssignmentPattern = ObjectLiteralExpression | ArrayLiteralExpression; + type BindingOrAssignmentPattern = ObjectBindingOrAssignmentPattern | ArrayBindingOrAssignmentPattern; + interface ConditionalExpression extends Expression { + kind: SyntaxKind.ConditionalExpression; + condition: Expression; + questionToken: QuestionToken; + whenTrue: Expression; + colonToken: ColonToken; + whenFalse: Expression; + } + type FunctionBody = Block; + type ConciseBody = FunctionBody | Expression; + interface FunctionExpression extends PrimaryExpression, FunctionLikeDeclarationBase, JSDocContainer { + kind: SyntaxKind.FunctionExpression; + name?: Identifier; + body: FunctionBody; + } + interface ArrowFunction extends Expression, FunctionLikeDeclarationBase, JSDocContainer { + kind: SyntaxKind.ArrowFunction; + equalsGreaterThanToken: EqualsGreaterThanToken; + body: ConciseBody; + name: never; + } + interface LiteralLikeNode extends Node { + text: string; + isUnterminated?: boolean; + hasExtendedUnicodeEscape?: boolean; + } + interface LiteralExpression extends LiteralLikeNode, PrimaryExpression { + _literalExpressionBrand: any; + } + interface RegularExpressionLiteral extends LiteralExpression { + kind: SyntaxKind.RegularExpressionLiteral; + } + interface NoSubstitutionTemplateLiteral extends LiteralExpression { + kind: SyntaxKind.NoSubstitutionTemplateLiteral; + } + interface NumericLiteral extends LiteralExpression { + kind: SyntaxKind.NumericLiteral; + } + interface BigIntLiteral extends LiteralExpression { + kind: SyntaxKind.BigIntLiteral; + } + interface TemplateHead extends LiteralLikeNode { + kind: SyntaxKind.TemplateHead; + parent: TemplateExpression; + } + interface TemplateMiddle extends LiteralLikeNode { + kind: SyntaxKind.TemplateMiddle; + parent: TemplateSpan; + } + interface TemplateTail extends LiteralLikeNode { + kind: SyntaxKind.TemplateTail; + parent: TemplateSpan; + } + type TemplateLiteral = TemplateExpression | NoSubstitutionTemplateLiteral; + interface TemplateExpression extends PrimaryExpression { + kind: SyntaxKind.TemplateExpression; + head: TemplateHead; + templateSpans: NodeArray; + } + interface TemplateSpan extends Node { + kind: SyntaxKind.TemplateSpan; + parent: TemplateExpression; + expression: Expression; + literal: TemplateMiddle | TemplateTail; + } + interface ParenthesizedExpression extends PrimaryExpression, JSDocContainer { + kind: SyntaxKind.ParenthesizedExpression; + expression: Expression; + } + interface ArrayLiteralExpression extends PrimaryExpression { + kind: SyntaxKind.ArrayLiteralExpression; + elements: NodeArray; + } + interface SpreadElement extends Expression { + kind: SyntaxKind.SpreadElement; + parent: ArrayLiteralExpression | CallExpression | NewExpression; + expression: Expression; + } + /** + * This interface is a base interface for ObjectLiteralExpression and JSXAttributes to extend from. JSXAttributes is similar to + * ObjectLiteralExpression in that it contains array of properties; however, JSXAttributes' properties can only be + * JSXAttribute or JSXSpreadAttribute. ObjectLiteralExpression, on the other hand, can only have properties of type + * ObjectLiteralElement (e.g. PropertyAssignment, ShorthandPropertyAssignment etc.) + */ + interface ObjectLiteralExpressionBase extends PrimaryExpression, Declaration { + properties: NodeArray; + } + interface ObjectLiteralExpression extends ObjectLiteralExpressionBase { + kind: SyntaxKind.ObjectLiteralExpression; + } + type EntityNameExpression = Identifier | PropertyAccessEntityNameExpression; + type EntityNameOrEntityNameExpression = EntityName | EntityNameExpression; + interface PropertyAccessExpression extends MemberExpression, NamedDeclaration { + kind: SyntaxKind.PropertyAccessExpression; + expression: LeftHandSideExpression; + name: Identifier; + } + interface SuperPropertyAccessExpression extends PropertyAccessExpression { + expression: SuperExpression; + } + /** Brand for a PropertyAccessExpression which, like a QualifiedName, consists of a sequence of identifiers separated by dots. */ + interface PropertyAccessEntityNameExpression extends PropertyAccessExpression { + _propertyAccessExpressionLikeQualifiedNameBrand?: any; + expression: EntityNameExpression; + } + interface ElementAccessExpression extends MemberExpression { + kind: SyntaxKind.ElementAccessExpression; + expression: LeftHandSideExpression; + argumentExpression: Expression; + } + interface SuperElementAccessExpression extends ElementAccessExpression { + expression: SuperExpression; + } + type SuperProperty = SuperPropertyAccessExpression | SuperElementAccessExpression; + interface CallExpression extends LeftHandSideExpression, Declaration { + kind: SyntaxKind.CallExpression; + expression: LeftHandSideExpression; + typeArguments?: NodeArray; + arguments: NodeArray; + } + interface SuperCall extends CallExpression { + expression: SuperExpression; + } + interface ImportCall extends CallExpression { + expression: ImportExpression; + } + interface ExpressionWithTypeArguments extends NodeWithTypeArguments { + kind: SyntaxKind.ExpressionWithTypeArguments; + parent: HeritageClause | JSDocAugmentsTag; + expression: LeftHandSideExpression; + } + interface NewExpression extends PrimaryExpression, Declaration { + kind: SyntaxKind.NewExpression; + expression: LeftHandSideExpression; + typeArguments?: NodeArray; + arguments?: NodeArray; + } + interface TaggedTemplateExpression extends MemberExpression { + kind: SyntaxKind.TaggedTemplateExpression; + tag: LeftHandSideExpression; + typeArguments?: NodeArray; + template: TemplateLiteral; + } + type CallLikeExpression = CallExpression | NewExpression | TaggedTemplateExpression | Decorator | JsxOpeningLikeElement; + interface AsExpression extends Expression { + kind: SyntaxKind.AsExpression; + expression: Expression; + type: TypeNode; + } + interface TypeAssertion extends UnaryExpression { + kind: SyntaxKind.TypeAssertionExpression; + type: TypeNode; + expression: UnaryExpression; + } + type AssertionExpression = TypeAssertion | AsExpression; + interface NonNullExpression extends LeftHandSideExpression { + kind: SyntaxKind.NonNullExpression; + expression: Expression; + } + interface MetaProperty extends PrimaryExpression { + kind: SyntaxKind.MetaProperty; + keywordToken: SyntaxKind.NewKeyword | SyntaxKind.ImportKeyword; + name: Identifier; + } + interface JsxElement extends PrimaryExpression { + kind: SyntaxKind.JsxElement; + openingElement: JsxOpeningElement; + children: NodeArray; + closingElement: JsxClosingElement; + } + type JsxOpeningLikeElement = JsxSelfClosingElement | JsxOpeningElement; + type JsxAttributeLike = JsxAttribute | JsxSpreadAttribute; + type JsxTagNameExpression = Identifier | ThisExpression | JsxTagNamePropertyAccess; + interface JsxTagNamePropertyAccess extends PropertyAccessExpression { + expression: JsxTagNameExpression; + } + interface JsxAttributes extends ObjectLiteralExpressionBase { + parent: JsxOpeningLikeElement; + } + interface JsxOpeningElement extends Expression { + kind: SyntaxKind.JsxOpeningElement; + parent: JsxElement; + tagName: JsxTagNameExpression; + typeArguments?: NodeArray; + attributes: JsxAttributes; + } + interface JsxSelfClosingElement extends PrimaryExpression { + kind: SyntaxKind.JsxSelfClosingElement; + tagName: JsxTagNameExpression; + typeArguments?: NodeArray; + attributes: JsxAttributes; + } + interface JsxFragment extends PrimaryExpression { + kind: SyntaxKind.JsxFragment; + openingFragment: JsxOpeningFragment; + children: NodeArray; + closingFragment: JsxClosingFragment; + } + interface JsxOpeningFragment extends Expression { + kind: SyntaxKind.JsxOpeningFragment; + parent: JsxFragment; + } + interface JsxClosingFragment extends Expression { + kind: SyntaxKind.JsxClosingFragment; + parent: JsxFragment; + } + interface JsxAttribute extends ObjectLiteralElement { + kind: SyntaxKind.JsxAttribute; + parent: JsxAttributes; + name: Identifier; + initializer?: StringLiteral | JsxExpression; + } + interface JsxSpreadAttribute extends ObjectLiteralElement { + kind: SyntaxKind.JsxSpreadAttribute; + parent: JsxAttributes; + expression: Expression; + } + interface JsxClosingElement extends Node { + kind: SyntaxKind.JsxClosingElement; + parent: JsxElement; + tagName: JsxTagNameExpression; + } + interface JsxExpression extends Expression { + kind: SyntaxKind.JsxExpression; + parent: JsxElement | JsxAttributeLike; + dotDotDotToken?: Token; + expression?: Expression; + } + interface JsxText extends Node { + kind: SyntaxKind.JsxText; + containsOnlyWhiteSpaces: boolean; + parent: JsxElement; + } + type JsxChild = JsxText | JsxExpression | JsxElement | JsxSelfClosingElement | JsxFragment; + interface Statement extends Node { + _statementBrand: any; + } + interface NotEmittedStatement extends Statement { + kind: SyntaxKind.NotEmittedStatement; + } + /** + * A list of comma-separated expressions. This node is only created by transformations. + */ + interface CommaListExpression extends Expression { + kind: SyntaxKind.CommaListExpression; + elements: NodeArray; + } + interface EmptyStatement extends Statement { + kind: SyntaxKind.EmptyStatement; + } + interface DebuggerStatement extends Statement { + kind: SyntaxKind.DebuggerStatement; + } + interface MissingDeclaration extends DeclarationStatement { + kind: SyntaxKind.MissingDeclaration; + name?: Identifier; + } + type BlockLike = SourceFile | Block | ModuleBlock | CaseOrDefaultClause; + interface Block extends Statement { + kind: SyntaxKind.Block; + statements: NodeArray; + } + interface VariableStatement extends Statement, JSDocContainer { + kind: SyntaxKind.VariableStatement; + declarationList: VariableDeclarationList; + } + interface ExpressionStatement extends Statement, JSDocContainer { + kind: SyntaxKind.ExpressionStatement; + expression: Expression; + } + interface IfStatement extends Statement { + kind: SyntaxKind.IfStatement; + expression: Expression; + thenStatement: Statement; + elseStatement?: Statement; + } + interface IterationStatement extends Statement { + statement: Statement; + } + interface DoStatement extends IterationStatement { + kind: SyntaxKind.DoStatement; + expression: Expression; + } + interface WhileStatement extends IterationStatement { + kind: SyntaxKind.WhileStatement; + expression: Expression; + } + type ForInitializer = VariableDeclarationList | Expression; + interface ForStatement extends IterationStatement { + kind: SyntaxKind.ForStatement; + initializer?: ForInitializer; + condition?: Expression; + incrementor?: Expression; + } + type ForInOrOfStatement = ForInStatement | ForOfStatement; + interface ForInStatement extends IterationStatement { + kind: SyntaxKind.ForInStatement; + initializer: ForInitializer; + expression: Expression; + } + interface ForOfStatement extends IterationStatement { + kind: SyntaxKind.ForOfStatement; + awaitModifier?: AwaitKeywordToken; + initializer: ForInitializer; + expression: Expression; + } + interface BreakStatement extends Statement { + kind: SyntaxKind.BreakStatement; + label?: Identifier; + } + interface ContinueStatement extends Statement { + kind: SyntaxKind.ContinueStatement; + label?: Identifier; + } + type BreakOrContinueStatement = BreakStatement | ContinueStatement; + interface ReturnStatement extends Statement { + kind: SyntaxKind.ReturnStatement; + expression?: Expression; + } + interface WithStatement extends Statement { + kind: SyntaxKind.WithStatement; + expression: Expression; + statement: Statement; + } + interface SwitchStatement extends Statement { + kind: SyntaxKind.SwitchStatement; + expression: Expression; + caseBlock: CaseBlock; + possiblyExhaustive?: boolean; + } + interface CaseBlock extends Node { + kind: SyntaxKind.CaseBlock; + parent: SwitchStatement; + clauses: NodeArray; + } + interface CaseClause extends Node { + kind: SyntaxKind.CaseClause; + parent: CaseBlock; + expression: Expression; + statements: NodeArray; + } + interface DefaultClause extends Node { + kind: SyntaxKind.DefaultClause; + parent: CaseBlock; + statements: NodeArray; + } + type CaseOrDefaultClause = CaseClause | DefaultClause; + interface LabeledStatement extends Statement, JSDocContainer { + kind: SyntaxKind.LabeledStatement; + label: Identifier; + statement: Statement; + } + interface ThrowStatement extends Statement { + kind: SyntaxKind.ThrowStatement; + expression?: Expression; + } + interface TryStatement extends Statement { + kind: SyntaxKind.TryStatement; + tryBlock: Block; + catchClause?: CatchClause; + finallyBlock?: Block; + } + interface CatchClause extends Node { + kind: SyntaxKind.CatchClause; + parent: TryStatement; + variableDeclaration?: VariableDeclaration; + block: Block; + } + type ObjectTypeDeclaration = ClassLikeDeclaration | InterfaceDeclaration | TypeLiteralNode; + type DeclarationWithTypeParameters = DeclarationWithTypeParameterChildren | JSDocTypedefTag | JSDocCallbackTag | JSDocSignature; + type DeclarationWithTypeParameterChildren = SignatureDeclaration | ClassLikeDeclaration | InterfaceDeclaration | TypeAliasDeclaration | JSDocTemplateTag; + interface ClassLikeDeclarationBase extends NamedDeclaration, JSDocContainer { + kind: SyntaxKind.ClassDeclaration | SyntaxKind.ClassExpression; + name?: Identifier; + typeParameters?: NodeArray; + heritageClauses?: NodeArray; + members: NodeArray; + } + interface ClassDeclaration extends ClassLikeDeclarationBase, DeclarationStatement { + kind: SyntaxKind.ClassDeclaration; + /** May be undefined in `export default class { ... }`. */ + name?: Identifier; + } + interface ClassExpression extends ClassLikeDeclarationBase, PrimaryExpression { + kind: SyntaxKind.ClassExpression; + } + type ClassLikeDeclaration = ClassDeclaration | ClassExpression; + interface ClassElement extends NamedDeclaration { + _classElementBrand: any; + name?: PropertyName; + } + interface TypeElement extends NamedDeclaration { + _typeElementBrand: any; + name?: PropertyName; + questionToken?: QuestionToken; + } + interface InterfaceDeclaration extends DeclarationStatement, JSDocContainer { + kind: SyntaxKind.InterfaceDeclaration; + name: Identifier; + typeParameters?: NodeArray; + heritageClauses?: NodeArray; + members: NodeArray; + } + interface HeritageClause extends Node { + kind: SyntaxKind.HeritageClause; + parent: InterfaceDeclaration | ClassLikeDeclaration; + token: SyntaxKind.ExtendsKeyword | SyntaxKind.ImplementsKeyword; + types: NodeArray; + } + interface TypeAliasDeclaration extends DeclarationStatement, JSDocContainer { + kind: SyntaxKind.TypeAliasDeclaration; + name: Identifier; + typeParameters?: NodeArray; + type: TypeNode; + } + interface EnumMember extends NamedDeclaration, JSDocContainer { + kind: SyntaxKind.EnumMember; + parent: EnumDeclaration; + name: PropertyName; + initializer?: Expression; + } + interface EnumDeclaration extends DeclarationStatement, JSDocContainer { + kind: SyntaxKind.EnumDeclaration; + name: Identifier; + members: NodeArray; + } + type ModuleName = Identifier | StringLiteral; + type ModuleBody = NamespaceBody | JSDocNamespaceBody; + interface ModuleDeclaration extends DeclarationStatement, JSDocContainer { + kind: SyntaxKind.ModuleDeclaration; + parent: ModuleBody | SourceFile; + name: ModuleName; + body?: ModuleBody | JSDocNamespaceDeclaration; + } + type NamespaceBody = ModuleBlock | NamespaceDeclaration; + interface NamespaceDeclaration extends ModuleDeclaration { + name: Identifier; + body: NamespaceBody; + } + type JSDocNamespaceBody = Identifier | JSDocNamespaceDeclaration; + interface JSDocNamespaceDeclaration extends ModuleDeclaration { + name: Identifier; + body?: JSDocNamespaceBody; + } + interface ModuleBlock extends Node, Statement { + kind: SyntaxKind.ModuleBlock; + parent: ModuleDeclaration; + statements: NodeArray; + } + type ModuleReference = EntityName | ExternalModuleReference; + /** + * One of: + * - import x = require("mod"); + * - import x = M.x; + */ + interface ImportEqualsDeclaration extends DeclarationStatement, JSDocContainer { + kind: SyntaxKind.ImportEqualsDeclaration; + parent: SourceFile | ModuleBlock; + name: Identifier; + moduleReference: ModuleReference; + } + interface ExternalModuleReference extends Node { + kind: SyntaxKind.ExternalModuleReference; + parent: ImportEqualsDeclaration; + expression: Expression; + } + interface ImportDeclaration extends Statement { + kind: SyntaxKind.ImportDeclaration; + parent: SourceFile | ModuleBlock; + importClause?: ImportClause; + /** If this is not a StringLiteral it will be a grammar error. */ + moduleSpecifier: Expression; + } + type NamedImportBindings = NamespaceImport | NamedImports; + interface ImportClause extends NamedDeclaration { + kind: SyntaxKind.ImportClause; + parent: ImportDeclaration; + name?: Identifier; + namedBindings?: NamedImportBindings; + } + interface NamespaceImport extends NamedDeclaration { + kind: SyntaxKind.NamespaceImport; + parent: ImportClause; + name: Identifier; + } + interface NamespaceExportDeclaration extends DeclarationStatement { + kind: SyntaxKind.NamespaceExportDeclaration; + name: Identifier; + } + interface ExportDeclaration extends DeclarationStatement, JSDocContainer { + kind: SyntaxKind.ExportDeclaration; + parent: SourceFile | ModuleBlock; + /** Will not be assigned in the case of `export * from "foo";` */ + exportClause?: NamedExports; + /** If this is not a StringLiteral it will be a grammar error. */ + moduleSpecifier?: Expression; + } + interface NamedImports extends Node { + kind: SyntaxKind.NamedImports; + parent: ImportClause; + elements: NodeArray; + } + interface NamedExports extends Node { + kind: SyntaxKind.NamedExports; + parent: ExportDeclaration; + elements: NodeArray; + } + type NamedImportsOrExports = NamedImports | NamedExports; + interface ImportSpecifier extends NamedDeclaration { + kind: SyntaxKind.ImportSpecifier; + parent: NamedImports; + propertyName?: Identifier; + name: Identifier; + } + interface ExportSpecifier extends NamedDeclaration { + kind: SyntaxKind.ExportSpecifier; + parent: NamedExports; + propertyName?: Identifier; + name: Identifier; + } + type ImportOrExportSpecifier = ImportSpecifier | ExportSpecifier; + /** + * This is either an `export =` or an `export default` declaration. + * Unless `isExportEquals` is set, this node was parsed as an `export default`. + */ + interface ExportAssignment extends DeclarationStatement { + kind: SyntaxKind.ExportAssignment; + parent: SourceFile; + isExportEquals?: boolean; + expression: Expression; + } + interface FileReference extends TextRange { + fileName: string; + } + interface CheckJsDirective extends TextRange { + enabled: boolean; + } + type CommentKind = SyntaxKind.SingleLineCommentTrivia | SyntaxKind.MultiLineCommentTrivia; + interface CommentRange extends TextRange { + hasTrailingNewLine?: boolean; + kind: CommentKind; + } + interface SynthesizedComment extends CommentRange { + text: string; + pos: -1; + end: -1; + } + interface JSDocTypeExpression extends TypeNode { + kind: SyntaxKind.JSDocTypeExpression; + type: TypeNode; + } + interface JSDocType extends TypeNode { + _jsDocTypeBrand: any; + } + interface JSDocAllType extends JSDocType { + kind: SyntaxKind.JSDocAllType; + } + interface JSDocUnknownType extends JSDocType { + kind: SyntaxKind.JSDocUnknownType; + } + interface JSDocNonNullableType extends JSDocType { + kind: SyntaxKind.JSDocNonNullableType; + type: TypeNode; + } + interface JSDocNullableType extends JSDocType { + kind: SyntaxKind.JSDocNullableType; + type: TypeNode; + } + interface JSDocOptionalType extends JSDocType { + kind: SyntaxKind.JSDocOptionalType; + type: TypeNode; + } + interface JSDocFunctionType extends JSDocType, SignatureDeclarationBase { + kind: SyntaxKind.JSDocFunctionType; + } + interface JSDocVariadicType extends JSDocType { + kind: SyntaxKind.JSDocVariadicType; + type: TypeNode; + } + type JSDocTypeReferencingNode = JSDocVariadicType | JSDocOptionalType | JSDocNullableType | JSDocNonNullableType; + interface JSDoc extends Node { + kind: SyntaxKind.JSDocComment; + parent: HasJSDoc; + tags?: NodeArray; + comment?: string; + } + interface JSDocTag extends Node { + parent: JSDoc | JSDocTypeLiteral; + tagName: Identifier; + comment?: string; + } + interface JSDocUnknownTag extends JSDocTag { + kind: SyntaxKind.JSDocTag; + } + /** + * Note that `@extends` is a synonym of `@augments`. + * Both tags are represented by this interface. + */ + interface JSDocAugmentsTag extends JSDocTag { + kind: SyntaxKind.JSDocAugmentsTag; + class: ExpressionWithTypeArguments & { + expression: Identifier | PropertyAccessEntityNameExpression; + }; + } + interface JSDocClassTag extends JSDocTag { + kind: SyntaxKind.JSDocClassTag; + } + interface JSDocEnumTag extends JSDocTag { + kind: SyntaxKind.JSDocEnumTag; + typeExpression?: JSDocTypeExpression; + } + interface JSDocThisTag extends JSDocTag { + kind: SyntaxKind.JSDocThisTag; + typeExpression?: JSDocTypeExpression; + } + interface JSDocTemplateTag extends JSDocTag { + kind: SyntaxKind.JSDocTemplateTag; + constraint: JSDocTypeExpression | undefined; + typeParameters: NodeArray; + } + interface JSDocReturnTag extends JSDocTag { + kind: SyntaxKind.JSDocReturnTag; + typeExpression?: JSDocTypeExpression; + } + interface JSDocTypeTag extends JSDocTag { + kind: SyntaxKind.JSDocTypeTag; + typeExpression?: JSDocTypeExpression; + } + interface JSDocTypedefTag extends JSDocTag, NamedDeclaration { + parent: JSDoc; + kind: SyntaxKind.JSDocTypedefTag; + fullName?: JSDocNamespaceDeclaration | Identifier; + name?: Identifier; + typeExpression?: JSDocTypeExpression | JSDocTypeLiteral; + } + interface JSDocCallbackTag extends JSDocTag, NamedDeclaration { + parent: JSDoc; + kind: SyntaxKind.JSDocCallbackTag; + fullName?: JSDocNamespaceDeclaration | Identifier; + name?: Identifier; + typeExpression: JSDocSignature; + } + interface JSDocSignature extends JSDocType, Declaration { + kind: SyntaxKind.JSDocSignature; + typeParameters?: ReadonlyArray; + parameters: ReadonlyArray; + type: JSDocReturnTag | undefined; + } + interface JSDocPropertyLikeTag extends JSDocTag, Declaration { + parent: JSDoc; + name: EntityName; + typeExpression?: JSDocTypeExpression; + /** Whether the property name came before the type -- non-standard for JSDoc, but Typescript-like */ + isNameFirst: boolean; + isBracketed: boolean; + } + interface JSDocPropertyTag extends JSDocPropertyLikeTag { + kind: SyntaxKind.JSDocPropertyTag; + } + interface JSDocParameterTag extends JSDocPropertyLikeTag { + kind: SyntaxKind.JSDocParameterTag; + } + interface JSDocTypeLiteral extends JSDocType { + kind: SyntaxKind.JSDocTypeLiteral; + jsDocPropertyTags?: ReadonlyArray; + /** If true, then this type literal represents an *array* of its type. */ + isArrayType?: boolean; + } + enum FlowFlags { + Unreachable = 1, + Start = 2, + BranchLabel = 4, + LoopLabel = 8, + Assignment = 16, + TrueCondition = 32, + FalseCondition = 64, + SwitchClause = 128, + ArrayMutation = 256, + Referenced = 512, + Shared = 1024, + PreFinally = 2048, + AfterFinally = 4096, + Label = 12, + Condition = 96 + } + interface FlowLock { + locked?: boolean; + } + interface AfterFinallyFlow extends FlowNodeBase, FlowLock { + antecedent: FlowNode; + } + interface PreFinallyFlow extends FlowNodeBase { + antecedent: FlowNode; + lock: FlowLock; + } + type FlowNode = AfterFinallyFlow | PreFinallyFlow | FlowStart | FlowLabel | FlowAssignment | FlowCondition | FlowSwitchClause | FlowArrayMutation; + interface FlowNodeBase { + flags: FlowFlags; + id?: number; + } + interface FlowStart extends FlowNodeBase { + container?: FunctionExpression | ArrowFunction | MethodDeclaration; + } + interface FlowLabel extends FlowNodeBase { + antecedents: FlowNode[] | undefined; + } + interface FlowAssignment extends FlowNodeBase { + node: Expression | VariableDeclaration | BindingElement; + antecedent: FlowNode; + } + interface FlowCondition extends FlowNodeBase { + expression: Expression; + antecedent: FlowNode; + } + interface FlowSwitchClause extends FlowNodeBase { + switchStatement: SwitchStatement; + clauseStart: number; + clauseEnd: number; + antecedent: FlowNode; + } + interface FlowArrayMutation extends FlowNodeBase { + node: CallExpression | BinaryExpression; + antecedent: FlowNode; + } + type FlowType = Type | IncompleteType; + interface IncompleteType { + flags: TypeFlags; + type: Type; + } + interface AmdDependency { + path: string; + name?: string; + } + interface SourceFile extends Declaration { + kind: SyntaxKind.SourceFile; + statements: NodeArray; + endOfFileToken: Token; + fileName: string; + text: string; + amdDependencies: ReadonlyArray; + moduleName?: string; + referencedFiles: ReadonlyArray; + typeReferenceDirectives: ReadonlyArray; + libReferenceDirectives: ReadonlyArray; + languageVariant: LanguageVariant; + isDeclarationFile: boolean; + /** + * lib.d.ts should have a reference comment like + * + * /// + * + * If any other file has this comment, it signals not to include lib.d.ts + * because this containing file is intended to act as a default library. + */ + hasNoDefaultLib: boolean; + languageVersion: ScriptTarget; + } + interface Bundle extends Node { + kind: SyntaxKind.Bundle; + prepends: ReadonlyArray; + sourceFiles: ReadonlyArray; + } + interface InputFiles extends Node { + kind: SyntaxKind.InputFiles; + javascriptText: string; + javascriptMapPath?: string; + javascriptMapText?: string; + declarationText: string; + declarationMapPath?: string; + declarationMapText?: string; + } + interface UnparsedSource extends Node { + kind: SyntaxKind.UnparsedSource; + text: string; + sourceMapPath?: string; + sourceMapText?: string; + } + interface JsonSourceFile extends SourceFile { + statements: NodeArray; + } + interface TsConfigSourceFile extends JsonSourceFile { + extendedSourceFiles?: string[]; + } + interface JsonMinusNumericLiteral extends PrefixUnaryExpression { + kind: SyntaxKind.PrefixUnaryExpression; + operator: SyntaxKind.MinusToken; + operand: NumericLiteral; + } + interface JsonObjectExpressionStatement extends ExpressionStatement { + expression: ObjectLiteralExpression | ArrayLiteralExpression | JsonMinusNumericLiteral | NumericLiteral | StringLiteral | BooleanLiteral | NullLiteral; + } + interface ScriptReferenceHost { + getCompilerOptions(): CompilerOptions; + getSourceFile(fileName: string): SourceFile | undefined; + getSourceFileByPath(path: Path): SourceFile | undefined; + getCurrentDirectory(): string; + } + interface ParseConfigHost { + useCaseSensitiveFileNames: boolean; + readDirectory(rootDir: string, extensions: ReadonlyArray, excludes: ReadonlyArray | undefined, includes: ReadonlyArray, depth?: number): ReadonlyArray; + /** + * Gets a value indicating whether the specified path exists and is a file. + * @param path The path to test. + */ + fileExists(path: string): boolean; + readFile(path: string): string | undefined; + trace?(s: string): void; + } + /** + * Branded string for keeping track of when we've turned an ambiguous path + * specified like "./blah" to an absolute path to an actual + * tsconfig file, e.g. "/root/blah/tsconfig.json" + */ + type ResolvedConfigFileName = string & { + _isResolvedConfigFileName: never; + }; + type WriteFileCallback = (fileName: string, data: string, writeByteOrderMark: boolean, onError: ((message: string) => void) | undefined, sourceFiles?: ReadonlyArray) => void; + class OperationCanceledException { + } + interface CancellationToken { + isCancellationRequested(): boolean; + /** @throws OperationCanceledException if isCancellationRequested is true */ + throwIfCancellationRequested(): void; + } + interface Program extends ScriptReferenceHost { + /** + * Get a list of root file names that were passed to a 'createProgram' + */ + getRootFileNames(): ReadonlyArray; + /** + * Get a list of files in the program + */ + getSourceFiles(): ReadonlyArray; + /** + * Emits the JavaScript and declaration files. If targetSourceFile is not specified, then + * the JavaScript and declaration files will be produced for all the files in this program. + * If targetSourceFile is specified, then only the JavaScript and declaration for that + * specific file will be generated. + * + * If writeFile is not specified then the writeFile callback from the compiler host will be + * used for writing the JavaScript and declaration files. Otherwise, the writeFile parameter + * will be invoked when writing the JavaScript and declaration files. + */ + emit(targetSourceFile?: SourceFile, writeFile?: WriteFileCallback, cancellationToken?: CancellationToken, emitOnlyDtsFiles?: boolean, customTransformers?: CustomTransformers): EmitResult; + getOptionsDiagnostics(cancellationToken?: CancellationToken): ReadonlyArray; + getGlobalDiagnostics(cancellationToken?: CancellationToken): ReadonlyArray; + getSyntacticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray; + /** The first time this is called, it will return global diagnostics (no location). */ + getSemanticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray; + getDeclarationDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray; + getConfigFileParsingDiagnostics(): ReadonlyArray; + /** + * Gets a type checker that can be used to semantically analyze source files in the program. + */ + getTypeChecker(): TypeChecker; + isSourceFileFromExternalLibrary(file: SourceFile): boolean; + isSourceFileDefaultLibrary(file: SourceFile): boolean; + getProjectReferences(): ReadonlyArray | undefined; + getResolvedProjectReferences(): ReadonlyArray | undefined; + } + interface ResolvedProjectReference { + commandLine: ParsedCommandLine; + sourceFile: SourceFile; + references?: ReadonlyArray; + } + interface CustomTransformers { + /** Custom transformers to evaluate before built-in .js transformations. */ + before?: TransformerFactory[]; + /** Custom transformers to evaluate after built-in .js transformations. */ + after?: TransformerFactory[]; + /** Custom transformers to evaluate after built-in .d.ts transformations. */ + afterDeclarations?: TransformerFactory[]; + } + interface SourceMapSpan { + /** Line number in the .js file. */ + emittedLine: number; + /** Column number in the .js file. */ + emittedColumn: number; + /** Line number in the .ts file. */ + sourceLine: number; + /** Column number in the .ts file. */ + sourceColumn: number; + /** Optional name (index into names array) associated with this span. */ + nameIndex?: number; + /** .ts file (index into sources array) associated with this span */ + sourceIndex: number; + } + /** Return code used by getEmitOutput function to indicate status of the function */ + enum ExitStatus { + Success = 0, + DiagnosticsPresent_OutputsSkipped = 1, + DiagnosticsPresent_OutputsGenerated = 2 + } + interface EmitResult { + emitSkipped: boolean; + /** Contains declaration emit diagnostics */ + diagnostics: ReadonlyArray; + emittedFiles?: string[]; + } + interface TypeChecker { + getTypeOfSymbolAtLocation(symbol: Symbol, node: Node): Type; + getDeclaredTypeOfSymbol(symbol: Symbol): Type; + getPropertiesOfType(type: Type): Symbol[]; + getPropertyOfType(type: Type, propertyName: string): Symbol | undefined; + getIndexInfoOfType(type: Type, kind: IndexKind): IndexInfo | undefined; + getSignaturesOfType(type: Type, kind: SignatureKind): ReadonlyArray; + getIndexTypeOfType(type: Type, kind: IndexKind): Type | undefined; + getBaseTypes(type: InterfaceType): BaseType[]; + getBaseTypeOfLiteralType(type: Type): Type; + getWidenedType(type: Type): Type; + getReturnTypeOfSignature(signature: Signature): Type; + getNullableType(type: Type, flags: TypeFlags): Type; + getNonNullableType(type: Type): Type; + /** Note that the resulting nodes cannot be checked. */ + typeToTypeNode(type: Type, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): TypeNode | undefined; + /** Note that the resulting nodes cannot be checked. */ + signatureToSignatureDeclaration(signature: Signature, kind: SyntaxKind, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): (SignatureDeclaration & { + typeArguments?: NodeArray; + }) | undefined; + /** Note that the resulting nodes cannot be checked. */ + indexInfoToIndexSignatureDeclaration(indexInfo: IndexInfo, kind: IndexKind, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): IndexSignatureDeclaration | undefined; + /** Note that the resulting nodes cannot be checked. */ + symbolToEntityName(symbol: Symbol, meaning: SymbolFlags, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): EntityName | undefined; + /** Note that the resulting nodes cannot be checked. */ + symbolToExpression(symbol: Symbol, meaning: SymbolFlags, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): Expression | undefined; + /** Note that the resulting nodes cannot be checked. */ + symbolToTypeParameterDeclarations(symbol: Symbol, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): NodeArray | undefined; + /** Note that the resulting nodes cannot be checked. */ + symbolToParameterDeclaration(symbol: Symbol, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): ParameterDeclaration | undefined; + /** Note that the resulting nodes cannot be checked. */ + typeParameterToDeclaration(parameter: TypeParameter, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): TypeParameterDeclaration | undefined; + getSymbolsInScope(location: Node, meaning: SymbolFlags): Symbol[]; + getSymbolAtLocation(node: Node): Symbol | undefined; + getSymbolsOfParameterPropertyDeclaration(parameter: ParameterDeclaration, parameterName: string): Symbol[]; + /** + * The function returns the value (local variable) symbol of an identifier in the short-hand property assignment. + * This is necessary as an identifier in short-hand property assignment can contains two meaning: property name and property value. + */ + getShorthandAssignmentValueSymbol(location: Node): Symbol | undefined; + getExportSpecifierLocalTargetSymbol(location: ExportSpecifier): Symbol | undefined; + /** + * If a symbol is a local symbol with an associated exported symbol, returns the exported symbol. + * Otherwise returns its input. + * For example, at `export type T = number;`: + * - `getSymbolAtLocation` at the location `T` will return the exported symbol for `T`. + * - But the result of `getSymbolsInScope` will contain the *local* symbol for `T`, not the exported symbol. + * - Calling `getExportSymbolOfSymbol` on that local symbol will return the exported symbol. + */ + getExportSymbolOfSymbol(symbol: Symbol): Symbol; + getPropertySymbolOfDestructuringAssignment(location: Identifier): Symbol | undefined; + getTypeAtLocation(node: Node): Type; + getTypeFromTypeNode(node: TypeNode): Type; + signatureToString(signature: Signature, enclosingDeclaration?: Node, flags?: TypeFormatFlags, kind?: SignatureKind): string; + typeToString(type: Type, enclosingDeclaration?: Node, flags?: TypeFormatFlags): string; + symbolToString(symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags, flags?: SymbolFormatFlags): string; + typePredicateToString(predicate: TypePredicate, enclosingDeclaration?: Node, flags?: TypeFormatFlags): string; + getFullyQualifiedName(symbol: Symbol): string; + getAugmentedPropertiesOfType(type: Type): Symbol[]; + getRootSymbols(symbol: Symbol): ReadonlyArray; + getContextualType(node: Expression): Type | undefined; + /** + * returns unknownSignature in the case of an error. + * returns undefined if the node is not valid. + * @param argumentCount Apparent number of arguments, passed in case of a possibly incomplete call. This should come from an ArgumentListInfo. See `signatureHelp.ts`. + */ + getResolvedSignature(node: CallLikeExpression, candidatesOutArray?: Signature[], argumentCount?: number): Signature | undefined; + getSignatureFromDeclaration(declaration: SignatureDeclaration): Signature | undefined; + isImplementationOfOverload(node: SignatureDeclaration): boolean | undefined; + isUndefinedSymbol(symbol: Symbol): boolean; + isArgumentsSymbol(symbol: Symbol): boolean; + isUnknownSymbol(symbol: Symbol): boolean; + getConstantValue(node: EnumMember | PropertyAccessExpression | ElementAccessExpression): string | number | undefined; + isValidPropertyAccess(node: PropertyAccessExpression | QualifiedName | ImportTypeNode, propertyName: string): boolean; + /** Follow all aliases to get the original symbol. */ + getAliasedSymbol(symbol: Symbol): Symbol; + getExportsOfModule(moduleSymbol: Symbol): Symbol[]; + getJsxIntrinsicTagNamesAt(location: Node): Symbol[]; + isOptionalParameter(node: ParameterDeclaration): boolean; + getAmbientModules(): Symbol[]; + tryGetMemberInModuleExports(memberName: string, moduleSymbol: Symbol): Symbol | undefined; + getApparentType(type: Type): Type; + getBaseConstraintOfType(type: Type): Type | undefined; + getDefaultFromTypeParameter(type: Type): Type | undefined; + /** + * Depending on the operation performed, it may be appropriate to throw away the checker + * if the cancellation token is triggered. Typically, if it is used for error checking + * and the operation is cancelled, then it should be discarded, otherwise it is safe to keep. + */ + runWithCancellationToken(token: CancellationToken, cb: (checker: TypeChecker) => T): T; + } + enum NodeBuilderFlags { + None = 0, + NoTruncation = 1, + WriteArrayAsGenericType = 2, + GenerateNamesForShadowedTypeParams = 4, + UseStructuralFallback = 8, + ForbidIndexedAccessSymbolReferences = 16, + WriteTypeArgumentsOfSignature = 32, + UseFullyQualifiedType = 64, + UseOnlyExternalAliasing = 128, + SuppressAnyReturnType = 256, + WriteTypeParametersInQualifiedName = 512, + MultilineObjectLiterals = 1024, + WriteClassExpressionAsTypeLiteral = 2048, + UseTypeOfFunction = 4096, + OmitParameterModifiers = 8192, + UseAliasDefinedOutsideCurrentScope = 16384, + AllowThisInObjectLiteral = 32768, + AllowQualifedNameInPlaceOfIdentifier = 65536, + AllowAnonymousIdentifier = 131072, + AllowEmptyUnionOrIntersection = 262144, + AllowEmptyTuple = 524288, + AllowUniqueESSymbolType = 1048576, + AllowEmptyIndexInfoType = 2097152, + AllowNodeModulesRelativePaths = 67108864, + IgnoreErrors = 70221824, + InObjectTypeLiteral = 4194304, + InTypeAlias = 8388608, + InInitialEntityName = 16777216, + InReverseMappedType = 33554432 + } + enum TypeFormatFlags { + None = 0, + NoTruncation = 1, + WriteArrayAsGenericType = 2, + UseStructuralFallback = 8, + WriteTypeArgumentsOfSignature = 32, + UseFullyQualifiedType = 64, + SuppressAnyReturnType = 256, + MultilineObjectLiterals = 1024, + WriteClassExpressionAsTypeLiteral = 2048, + UseTypeOfFunction = 4096, + OmitParameterModifiers = 8192, + UseAliasDefinedOutsideCurrentScope = 16384, + AllowUniqueESSymbolType = 1048576, + AddUndefined = 131072, + WriteArrowStyleSignature = 262144, + InArrayType = 524288, + InElementType = 2097152, + InFirstTypeArgument = 4194304, + InTypeAlias = 8388608, + /** @deprecated */ WriteOwnNameForAnyLike = 0, + NodeBuilderFlagsMask = 9469291 + } + enum SymbolFormatFlags { + None = 0, + WriteTypeParametersOrArguments = 1, + UseOnlyExternalAliasing = 2, + AllowAnyNodeKind = 4, + UseAliasDefinedOutsideCurrentScope = 8 + } + enum TypePredicateKind { + This = 0, + Identifier = 1 + } + interface TypePredicateBase { + kind: TypePredicateKind; + type: Type; + } + interface ThisTypePredicate extends TypePredicateBase { + kind: TypePredicateKind.This; + } + interface IdentifierTypePredicate extends TypePredicateBase { + kind: TypePredicateKind.Identifier; + parameterName: string; + parameterIndex: number; + } + type TypePredicate = IdentifierTypePredicate | ThisTypePredicate; + enum SymbolFlags { + None = 0, + FunctionScopedVariable = 1, + BlockScopedVariable = 2, + Property = 4, + EnumMember = 8, + Function = 16, + Class = 32, + Interface = 64, + ConstEnum = 128, + RegularEnum = 256, + ValueModule = 512, + NamespaceModule = 1024, + TypeLiteral = 2048, + ObjectLiteral = 4096, + Method = 8192, + Constructor = 16384, + GetAccessor = 32768, + SetAccessor = 65536, + Signature = 131072, + TypeParameter = 262144, + TypeAlias = 524288, + ExportValue = 1048576, + Alias = 2097152, + Prototype = 4194304, + ExportStar = 8388608, + Optional = 16777216, + Transient = 33554432, + Assignment = 67108864, + ModuleExports = 134217728, + Enum = 384, + Variable = 3, + Value = 67220415, + Type = 67897832, + Namespace = 1920, + Module = 1536, + Accessor = 98304, + FunctionScopedVariableExcludes = 67220414, + BlockScopedVariableExcludes = 67220415, + ParameterExcludes = 67220415, + PropertyExcludes = 0, + EnumMemberExcludes = 68008959, + FunctionExcludes = 67219887, + ClassExcludes = 68008383, + InterfaceExcludes = 67897736, + RegularEnumExcludes = 68008191, + ConstEnumExcludes = 68008831, + ValueModuleExcludes = 110735, + NamespaceModuleExcludes = 0, + MethodExcludes = 67212223, + GetAccessorExcludes = 67154879, + SetAccessorExcludes = 67187647, + TypeParameterExcludes = 67635688, + TypeAliasExcludes = 67897832, + AliasExcludes = 2097152, + ModuleMember = 2623475, + ExportHasLocal = 944, + BlockScoped = 418, + PropertyOrAccessor = 98308, + ClassMember = 106500 + } + interface Symbol { + flags: SymbolFlags; + escapedName: __String; + declarations: Declaration[]; + valueDeclaration: Declaration; + members?: SymbolTable; + exports?: SymbolTable; + globalExports?: SymbolTable; + } + enum InternalSymbolName { + Call = "__call", + Constructor = "__constructor", + New = "__new", + Index = "__index", + ExportStar = "__export", + Global = "__global", + Missing = "__missing", + Type = "__type", + Object = "__object", + JSXAttributes = "__jsxAttributes", + Class = "__class", + Function = "__function", + Computed = "__computed", + Resolving = "__resolving__", + ExportEquals = "export=", + Default = "default", + This = "this" + } + /** + * This represents a string whose leading underscore have been escaped by adding extra leading underscores. + * The shape of this brand is rather unique compared to others we've used. + * Instead of just an intersection of a string and an object, it is that union-ed + * with an intersection of void and an object. This makes it wholly incompatible + * with a normal string (which is good, it cannot be misused on assignment or on usage), + * while still being comparable with a normal string via === (also good) and castable from a string. + */ + type __String = (string & { + __escapedIdentifier: void; + }) | (void & { + __escapedIdentifier: void; + }) | InternalSymbolName; + /** ReadonlyMap where keys are `__String`s. */ + interface ReadonlyUnderscoreEscapedMap { + get(key: __String): T | undefined; + has(key: __String): boolean; + forEach(action: (value: T, key: __String) => void): void; + readonly size: number; + keys(): Iterator<__String>; + values(): Iterator; + entries(): Iterator<[__String, T]>; + } + /** Map where keys are `__String`s. */ + interface UnderscoreEscapedMap extends ReadonlyUnderscoreEscapedMap { + set(key: __String, value: T): this; + delete(key: __String): boolean; + clear(): void; + } + /** SymbolTable based on ES6 Map interface. */ + type SymbolTable = UnderscoreEscapedMap; + enum TypeFlags { + Any = 1, + Unknown = 2, + String = 4, + Number = 8, + Boolean = 16, + Enum = 32, + BigInt = 64, + StringLiteral = 128, + NumberLiteral = 256, + BooleanLiteral = 512, + EnumLiteral = 1024, + BigIntLiteral = 2048, + ESSymbol = 4096, + UniqueESSymbol = 8192, + Void = 16384, + Undefined = 32768, + Null = 65536, + Never = 131072, + TypeParameter = 262144, + Object = 524288, + Union = 1048576, + Intersection = 2097152, + Index = 4194304, + IndexedAccess = 8388608, + Conditional = 16777216, + Substitution = 33554432, + NonPrimitive = 67108864, + Literal = 2944, + Unit = 109440, + StringOrNumberLiteral = 384, + PossiblyFalsy = 117724, + StringLike = 132, + NumberLike = 296, + BigIntLike = 2112, + BooleanLike = 528, + EnumLike = 1056, + ESSymbolLike = 12288, + VoidLike = 49152, + UnionOrIntersection = 3145728, + StructuredType = 3670016, + TypeVariable = 8650752, + InstantiableNonPrimitive = 58982400, + InstantiablePrimitive = 4194304, + Instantiable = 63176704, + StructuredOrInstantiable = 66846720, + Narrowable = 133970943, + NotUnionOrUnit = 67637251 + } + type DestructuringPattern = BindingPattern | ObjectLiteralExpression | ArrayLiteralExpression; + interface Type { + flags: TypeFlags; + symbol: Symbol; + pattern?: DestructuringPattern; + aliasSymbol?: Symbol; + aliasTypeArguments?: ReadonlyArray; + } + interface LiteralType extends Type { + value: string | number | PseudoBigInt; + freshType: LiteralType; + regularType: LiteralType; + } + interface UniqueESSymbolType extends Type { + symbol: Symbol; + } + interface StringLiteralType extends LiteralType { + value: string; + } + interface NumberLiteralType extends LiteralType { + value: number; + } + interface BigIntLiteralType extends LiteralType { + value: PseudoBigInt; + } + interface EnumType extends Type { + } + enum ObjectFlags { + Class = 1, + Interface = 2, + Reference = 4, + Tuple = 8, + Anonymous = 16, + Mapped = 32, + Instantiated = 64, + ObjectLiteral = 128, + EvolvingArray = 256, + ObjectLiteralPatternWithComputedProperties = 512, + ContainsSpread = 1024, + ReverseMapped = 2048, + JsxAttributes = 4096, + MarkerType = 8192, + JSLiteral = 16384, + FreshLiteral = 32768, + ClassOrInterface = 3 + } + interface ObjectType extends Type { + objectFlags: ObjectFlags; + } + /** Class and interface types (ObjectFlags.Class and ObjectFlags.Interface). */ + interface InterfaceType extends ObjectType { + typeParameters: TypeParameter[] | undefined; + outerTypeParameters: TypeParameter[] | undefined; + localTypeParameters: TypeParameter[] | undefined; + thisType: TypeParameter | undefined; + } + type BaseType = ObjectType | IntersectionType; + interface InterfaceTypeWithDeclaredMembers extends InterfaceType { + declaredProperties: Symbol[]; + declaredCallSignatures: Signature[]; + declaredConstructSignatures: Signature[]; + declaredStringIndexInfo?: IndexInfo; + declaredNumberIndexInfo?: IndexInfo; + } + /** + * Type references (ObjectFlags.Reference). When a class or interface has type parameters or + * a "this" type, references to the class or interface are made using type references. The + * typeArguments property specifies the types to substitute for the type parameters of the + * class or interface and optionally includes an extra element that specifies the type to + * substitute for "this" in the resulting instantiation. When no extra argument is present, + * the type reference itself is substituted for "this". The typeArguments property is undefined + * if the class or interface has no type parameters and the reference isn't specifying an + * explicit "this" argument. + */ + interface TypeReference extends ObjectType { + target: GenericType; + typeArguments?: ReadonlyArray; + } + interface GenericType extends InterfaceType, TypeReference { + } + interface TupleType extends GenericType { + minLength: number; + hasRestElement: boolean; + associatedNames?: __String[]; + } + interface TupleTypeReference extends TypeReference { + target: TupleType; + } + interface UnionOrIntersectionType extends Type { + types: Type[]; + } + interface UnionType extends UnionOrIntersectionType { + } + interface IntersectionType extends UnionOrIntersectionType { + } + type StructuredType = ObjectType | UnionType | IntersectionType; + interface EvolvingArrayType extends ObjectType { + elementType: Type; + finalArrayType?: Type; + } + interface InstantiableType extends Type { + } + interface TypeParameter extends InstantiableType { + } + interface IndexedAccessType extends InstantiableType { + objectType: Type; + indexType: Type; + constraint?: Type; + simplified?: Type; + } + type TypeVariable = TypeParameter | IndexedAccessType; + interface IndexType extends InstantiableType { + type: InstantiableType | UnionOrIntersectionType; + } + interface ConditionalRoot { + node: ConditionalTypeNode; + checkType: Type; + extendsType: Type; + trueType: Type; + falseType: Type; + isDistributive: boolean; + inferTypeParameters?: TypeParameter[]; + outerTypeParameters?: TypeParameter[]; + instantiations?: Map; + aliasSymbol?: Symbol; + aliasTypeArguments?: Type[]; + } + interface ConditionalType extends InstantiableType { + root: ConditionalRoot; + checkType: Type; + extendsType: Type; + resolvedTrueType?: Type; + resolvedFalseType?: Type; + } + interface SubstitutionType extends InstantiableType { + typeVariable: TypeVariable; + substitute: Type; + } + enum SignatureKind { + Call = 0, + Construct = 1 + } + interface Signature { + declaration?: SignatureDeclaration | JSDocSignature; + typeParameters?: ReadonlyArray; + parameters: ReadonlyArray; + } + enum IndexKind { + String = 0, + Number = 1 + } + interface IndexInfo { + type: Type; + isReadonly: boolean; + declaration?: IndexSignatureDeclaration; + } + enum InferencePriority { + NakedTypeVariable = 1, + HomomorphicMappedType = 2, + MappedTypeConstraint = 4, + ReturnType = 8, + LiteralKeyof = 16, + NoConstraints = 32, + AlwaysStrict = 64, + PriorityImpliesCombination = 28 + } + /** @deprecated Use FileExtensionInfo instead. */ + type JsFileExtensionInfo = FileExtensionInfo; + interface FileExtensionInfo { + extension: string; + isMixedContent: boolean; + scriptKind?: ScriptKind; + } + interface DiagnosticMessage { + key: string; + category: DiagnosticCategory; + code: number; + message: string; + reportsUnnecessary?: {}; + } + /** + * A linked list of formatted diagnostic messages to be used as part of a multiline message. + * It is built from the bottom up, leaving the head to be the "main" diagnostic. + * While it seems that DiagnosticMessageChain is structurally similar to DiagnosticMessage, + * the difference is that messages are all preformatted in DMC. + */ + interface DiagnosticMessageChain { + messageText: string; + category: DiagnosticCategory; + code: number; + next?: DiagnosticMessageChain; + } + interface Diagnostic extends DiagnosticRelatedInformation { + /** May store more in future. For now, this will simply be `true` to indicate when a diagnostic is an unused-identifier diagnostic. */ + reportsUnnecessary?: {}; + source?: string; + relatedInformation?: DiagnosticRelatedInformation[]; + } + interface DiagnosticRelatedInformation { + category: DiagnosticCategory; + code: number; + file: SourceFile | undefined; + start: number | undefined; + length: number | undefined; + messageText: string | DiagnosticMessageChain; + } + interface DiagnosticWithLocation extends Diagnostic { + file: SourceFile; + start: number; + length: number; + } + enum DiagnosticCategory { + Warning = 0, + Error = 1, + Suggestion = 2, + Message = 3 + } + enum ModuleResolutionKind { + Classic = 1, + NodeJs = 2 + } + interface PluginImport { + name: string; + } + interface ProjectReference { + /** A normalized path on disk */ + path: string; + /** The path as the user originally wrote it */ + originalPath?: string; + /** True if the output of this reference should be prepended to the output of this project. Only valid for --outFile compilations */ + prepend?: boolean; + /** True if it is intended that this reference form a circularity */ + circular?: boolean; + } + type CompilerOptionsValue = string | number | boolean | (string | number)[] | string[] | MapLike | PluginImport[] | ProjectReference[] | null | undefined; + interface CompilerOptions { + allowJs?: boolean; + allowSyntheticDefaultImports?: boolean; + allowUnreachableCode?: boolean; + allowUnusedLabels?: boolean; + alwaysStrict?: boolean; + baseUrl?: string; + charset?: string; + checkJs?: boolean; + declaration?: boolean; + declarationMap?: boolean; + emitDeclarationOnly?: boolean; + declarationDir?: string; + disableSizeLimit?: boolean; + downlevelIteration?: boolean; + emitBOM?: boolean; + emitDecoratorMetadata?: boolean; + experimentalDecorators?: boolean; + forceConsistentCasingInFileNames?: boolean; + importHelpers?: boolean; + inlineSourceMap?: boolean; + inlineSources?: boolean; + isolatedModules?: boolean; + jsx?: JsxEmit; + keyofStringsOnly?: boolean; + lib?: string[]; + locale?: string; + mapRoot?: string; + maxNodeModuleJsDepth?: number; + module?: ModuleKind; + moduleResolution?: ModuleResolutionKind; + newLine?: NewLineKind; + noEmit?: boolean; + noEmitHelpers?: boolean; + noEmitOnError?: boolean; + noErrorTruncation?: boolean; + noFallthroughCasesInSwitch?: boolean; + noImplicitAny?: boolean; + noImplicitReturns?: boolean; + noImplicitThis?: boolean; + noStrictGenericChecks?: boolean; + noUnusedLocals?: boolean; + noUnusedParameters?: boolean; + noImplicitUseStrict?: boolean; + noLib?: boolean; + noResolve?: boolean; + out?: string; + outDir?: string; + outFile?: string; + paths?: MapLike; + preserveConstEnums?: boolean; + preserveSymlinks?: boolean; + project?: string; + reactNamespace?: string; + jsxFactory?: string; + composite?: boolean; + removeComments?: boolean; + rootDir?: string; + rootDirs?: string[]; + skipLibCheck?: boolean; + skipDefaultLibCheck?: boolean; + sourceMap?: boolean; + sourceRoot?: string; + strict?: boolean; + strictFunctionTypes?: boolean; + strictBindCallApply?: boolean; + strictNullChecks?: boolean; + strictPropertyInitialization?: boolean; + stripInternal?: boolean; + suppressExcessPropertyErrors?: boolean; + suppressImplicitAnyIndexErrors?: boolean; + target?: ScriptTarget; + traceResolution?: boolean; + resolveJsonModule?: boolean; + types?: string[]; + /** Paths used to compute primary types search locations */ + typeRoots?: string[]; + esModuleInterop?: boolean; + [option: string]: CompilerOptionsValue | TsConfigSourceFile | undefined; + } + interface TypeAcquisition { + enableAutoDiscovery?: boolean; + enable?: boolean; + include?: string[]; + exclude?: string[]; + [option: string]: string[] | boolean | undefined; + } + enum ModuleKind { + None = 0, + CommonJS = 1, + AMD = 2, + UMD = 3, + System = 4, + ES2015 = 5, + ESNext = 6 + } + enum JsxEmit { + None = 0, + Preserve = 1, + React = 2, + ReactNative = 3 + } + enum NewLineKind { + CarriageReturnLineFeed = 0, + LineFeed = 1 + } + interface LineAndCharacter { + /** 0-based. */ + line: number; + character: number; + } + enum ScriptKind { + Unknown = 0, + JS = 1, + JSX = 2, + TS = 3, + TSX = 4, + External = 5, + JSON = 6, + /** + * Used on extensions that doesn't define the ScriptKind but the content defines it. + * Deferred extensions are going to be included in all project contexts. + */ + Deferred = 7 + } + enum ScriptTarget { + ES3 = 0, + ES5 = 1, + ES2015 = 2, + ES2016 = 3, + ES2017 = 4, + ES2018 = 5, + ESNext = 6, + JSON = 100, + Latest = 6 + } + enum LanguageVariant { + Standard = 0, + JSX = 1 + } + /** Either a parsed command line or a parsed tsconfig.json */ + interface ParsedCommandLine { + options: CompilerOptions; + typeAcquisition?: TypeAcquisition; + fileNames: string[]; + projectReferences?: ReadonlyArray; + raw?: any; + errors: Diagnostic[]; + wildcardDirectories?: MapLike; + compileOnSave?: boolean; + } + enum WatchDirectoryFlags { + None = 0, + Recursive = 1 + } + interface ExpandResult { + fileNames: string[]; + wildcardDirectories: MapLike; + } + interface CreateProgramOptions { + rootNames: ReadonlyArray; + options: CompilerOptions; + projectReferences?: ReadonlyArray; + host?: CompilerHost; + oldProgram?: Program; + configFileParsingDiagnostics?: ReadonlyArray; + } + interface ModuleResolutionHost { + fileExists(fileName: string): boolean; + readFile(fileName: string): string | undefined; + trace?(s: string): void; + directoryExists?(directoryName: string): boolean; + /** + * Resolve a symbolic link. + * @see https://nodejs.org/api/fs.html#fs_fs_realpathsync_path_options + */ + realpath?(path: string): string; + getCurrentDirectory?(): string; + getDirectories?(path: string): string[]; + } + /** + * Represents the result of module resolution. + * Module resolution will pick up tsx/jsx/js files even if '--jsx' and '--allowJs' are turned off. + * The Program will then filter results based on these flags. + * + * Prefer to return a `ResolvedModuleFull` so that the file type does not have to be inferred. + */ + interface ResolvedModule { + /** Path of the file the module was resolved to. */ + resolvedFileName: string; + /** True if `resolvedFileName` comes from `node_modules`. */ + isExternalLibraryImport?: boolean; + } + /** + * ResolvedModule with an explicitly provided `extension` property. + * Prefer this over `ResolvedModule`. + * If changing this, remember to change `moduleResolutionIsEqualTo`. + */ + interface ResolvedModuleFull extends ResolvedModule { + /** + * Extension of resolvedFileName. This must match what's at the end of resolvedFileName. + * This is optional for backwards-compatibility, but will be added if not provided. + */ + extension: Extension; + packageId?: PackageId; + } + /** + * Unique identifier with a package name and version. + * If changing this, remember to change `packageIdIsEqual`. + */ + interface PackageId { + /** + * Name of the package. + * Should not include `@types`. + * If accessing a non-index file, this should include its name e.g. "foo/bar". + */ + name: string; + /** + * Name of a submodule within this package. + * May be "". + */ + subModuleName: string; + /** Version of the package, e.g. "1.2.3" */ + version: string; + } + enum Extension { + Ts = ".ts", + Tsx = ".tsx", + Dts = ".d.ts", + Js = ".js", + Jsx = ".jsx", + Json = ".json" + } + interface ResolvedModuleWithFailedLookupLocations { + readonly resolvedModule: ResolvedModuleFull | undefined; + } + interface ResolvedTypeReferenceDirective { + primary: boolean; + resolvedFileName: string | undefined; + packageId?: PackageId; + /** True if `resolvedFileName` comes from `node_modules`. */ + isExternalLibraryImport?: boolean; + } + interface ResolvedTypeReferenceDirectiveWithFailedLookupLocations { + readonly resolvedTypeReferenceDirective: ResolvedTypeReferenceDirective | undefined; + readonly failedLookupLocations: ReadonlyArray; + } + interface CompilerHost extends ModuleResolutionHost { + getSourceFile(fileName: string, languageVersion: ScriptTarget, onError?: (message: string) => void, shouldCreateNewSourceFile?: boolean): SourceFile | undefined; + getSourceFileByPath?(fileName: string, path: Path, languageVersion: ScriptTarget, onError?: (message: string) => void, shouldCreateNewSourceFile?: boolean): SourceFile | undefined; + getCancellationToken?(): CancellationToken; + getDefaultLibFileName(options: CompilerOptions): string; + getDefaultLibLocation?(): string; + writeFile: WriteFileCallback; + getCurrentDirectory(): string; + getDirectories(path: string): string[]; + getCanonicalFileName(fileName: string): string; + useCaseSensitiveFileNames(): boolean; + getNewLine(): string; + readDirectory?(rootDir: string, extensions: ReadonlyArray, excludes: ReadonlyArray | undefined, includes: ReadonlyArray, depth?: number): string[]; + resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[], redirectedReference?: ResolvedProjectReference): (ResolvedModule | undefined)[]; + /** + * This method is a companion for 'resolveModuleNames' and is used to resolve 'types' references to actual type declaration files + */ + resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string, redirectedReference?: ResolvedProjectReference): (ResolvedTypeReferenceDirective | undefined)[]; + getEnvironmentVariable?(name: string): string | undefined; + createHash?(data: string): string; + } + interface SourceMapRange extends TextRange { + source?: SourceMapSource; + } + interface SourceMapSource { + fileName: string; + text: string; + skipTrivia?: (pos: number) => number; + } + enum EmitFlags { + None = 0, + SingleLine = 1, + AdviseOnEmitNode = 2, + NoSubstitution = 4, + CapturesThis = 8, + NoLeadingSourceMap = 16, + NoTrailingSourceMap = 32, + NoSourceMap = 48, + NoNestedSourceMaps = 64, + NoTokenLeadingSourceMaps = 128, + NoTokenTrailingSourceMaps = 256, + NoTokenSourceMaps = 384, + NoLeadingComments = 512, + NoTrailingComments = 1024, + NoComments = 1536, + NoNestedComments = 2048, + HelperName = 4096, + ExportName = 8192, + LocalName = 16384, + InternalName = 32768, + Indented = 65536, + NoIndentation = 131072, + AsyncFunctionBody = 262144, + ReuseTempVariableScope = 524288, + CustomPrologue = 1048576, + NoHoisting = 2097152, + HasEndOfDeclarationMarker = 4194304, + Iterator = 8388608, + NoAsciiEscaping = 16777216 + } + interface EmitHelper { + readonly name: string; + readonly scoped: boolean; + readonly text: string | ((node: EmitHelperUniqueNameCallback) => string); + readonly priority?: number; + } + type EmitHelperUniqueNameCallback = (name: string) => string; + enum EmitHint { + SourceFile = 0, + Expression = 1, + IdentifierName = 2, + MappedTypeParameter = 3, + Unspecified = 4, + EmbeddedStatement = 5 + } + interface TransformationContext { + /** Gets the compiler options supplied to the transformer. */ + getCompilerOptions(): CompilerOptions; + /** Starts a new lexical environment. */ + startLexicalEnvironment(): void; + /** Suspends the current lexical environment, usually after visiting a parameter list. */ + suspendLexicalEnvironment(): void; + /** Resumes a suspended lexical environment, usually before visiting a function body. */ + resumeLexicalEnvironment(): void; + /** Ends a lexical environment, returning any declarations. */ + endLexicalEnvironment(): Statement[] | undefined; + /** Hoists a function declaration to the containing scope. */ + hoistFunctionDeclaration(node: FunctionDeclaration): void; + /** Hoists a variable declaration to the containing scope. */ + hoistVariableDeclaration(node: Identifier): void; + /** Records a request for a non-scoped emit helper in the current context. */ + requestEmitHelper(helper: EmitHelper): void; + /** Gets and resets the requested non-scoped emit helpers. */ + readEmitHelpers(): EmitHelper[] | undefined; + /** Enables expression substitutions in the pretty printer for the provided SyntaxKind. */ + enableSubstitution(kind: SyntaxKind): void; + /** Determines whether expression substitutions are enabled for the provided node. */ + isSubstitutionEnabled(node: Node): boolean; + /** + * Hook used by transformers to substitute expressions just before they + * are emitted by the pretty printer. + * + * NOTE: Transformation hooks should only be modified during `Transformer` initialization, + * before returning the `NodeTransformer` callback. + */ + onSubstituteNode: (hint: EmitHint, node: Node) => Node; + /** + * Enables before/after emit notifications in the pretty printer for the provided + * SyntaxKind. + */ + enableEmitNotification(kind: SyntaxKind): void; + /** + * Determines whether before/after emit notifications should be raised in the pretty + * printer when it emits a node. + */ + isEmitNotificationEnabled(node: Node): boolean; + /** + * Hook used to allow transformers to capture state before or after + * the printer emits a node. + * + * NOTE: Transformation hooks should only be modified during `Transformer` initialization, + * before returning the `NodeTransformer` callback. + */ + onEmitNode: (hint: EmitHint, node: Node, emitCallback: (hint: EmitHint, node: Node) => void) => void; + } + interface TransformationResult { + /** Gets the transformed source files. */ + transformed: T[]; + /** Gets diagnostics for the transformation. */ + diagnostics?: DiagnosticWithLocation[]; + /** + * Gets a substitute for a node, if one is available; otherwise, returns the original node. + * + * @param hint A hint as to the intended usage of the node. + * @param node The node to substitute. + */ + substituteNode(hint: EmitHint, node: Node): Node; + /** + * Emits a node with possible notification. + * + * @param hint A hint as to the intended usage of the node. + * @param node The node to emit. + * @param emitCallback A callback used to emit the node. + */ + emitNodeWithNotification(hint: EmitHint, node: Node, emitCallback: (hint: EmitHint, node: Node) => void): void; + /** + * Clean up EmitNode entries on any parse-tree nodes. + */ + dispose(): void; + } + /** + * A function that is used to initialize and return a `Transformer` callback, which in turn + * will be used to transform one or more nodes. + */ + type TransformerFactory = (context: TransformationContext) => Transformer; + /** + * A function that transforms a node. + */ + type Transformer = (node: T) => T; + /** + * A function that accepts and possibly transforms a node. + */ + type Visitor = (node: Node) => VisitResult; + type VisitResult = T | T[] | undefined; + interface Printer { + /** + * Print a node and its subtree as-is, without any emit transformations. + * @param hint A value indicating the purpose of a node. This is primarily used to + * distinguish between an `Identifier` used in an expression position, versus an + * `Identifier` used as an `IdentifierName` as part of a declaration. For most nodes you + * should just pass `Unspecified`. + * @param node The node to print. The node and its subtree are printed as-is, without any + * emit transformations. + * @param sourceFile A source file that provides context for the node. The source text of + * the file is used to emit the original source content for literals and identifiers, while + * the identifiers of the source file are used when generating unique names to avoid + * collisions. + */ + printNode(hint: EmitHint, node: Node, sourceFile: SourceFile): string; + /** + * Prints a list of nodes using the given format flags + */ + printList(format: ListFormat, list: NodeArray, sourceFile: SourceFile): string; + /** + * Prints a source file as-is, without any emit transformations. + */ + printFile(sourceFile: SourceFile): string; + /** + * Prints a bundle of source files as-is, without any emit transformations. + */ + printBundle(bundle: Bundle): string; + } + interface PrintHandlers { + /** + * A hook used by the Printer when generating unique names to avoid collisions with + * globally defined names that exist outside of the current source file. + */ + hasGlobalName?(name: string): boolean; + /** + * A hook used by the Printer to provide notifications prior to emitting a node. A + * compatible implementation **must** invoke `emitCallback` with the provided `hint` and + * `node` values. + * @param hint A hint indicating the intended purpose of the node. + * @param node The node to emit. + * @param emitCallback A callback that, when invoked, will emit the node. + * @example + * ```ts + * var printer = createPrinter(printerOptions, { + * onEmitNode(hint, node, emitCallback) { + * // set up or track state prior to emitting the node... + * emitCallback(hint, node); + * // restore state after emitting the node... + * } + * }); + * ``` + */ + onEmitNode?(hint: EmitHint, node: Node | undefined, emitCallback: (hint: EmitHint, node: Node | undefined) => void): void; + /** + * A hook used by the Printer to perform just-in-time substitution of a node. This is + * primarily used by node transformations that need to substitute one node for another, + * such as replacing `myExportedVar` with `exports.myExportedVar`. + * @param hint A hint indicating the intended purpose of the node. + * @param node The node to emit. + * @example + * ```ts + * var printer = createPrinter(printerOptions, { + * substituteNode(hint, node) { + * // perform substitution if necessary... + * return node; + * } + * }); + * ``` + */ + substituteNode?(hint: EmitHint, node: Node): Node; + } + interface PrinterOptions { + removeComments?: boolean; + newLine?: NewLineKind; + omitTrailingSemicolon?: boolean; + noEmitHelpers?: boolean; + } + interface GetEffectiveTypeRootsHost { + directoryExists?(directoryName: string): boolean; + getCurrentDirectory?(): string; + } + interface TextSpan { + start: number; + length: number; + } + interface TextChangeRange { + span: TextSpan; + newLength: number; + } + interface SyntaxList extends Node { + _children: Node[]; + } + enum ListFormat { + None = 0, + SingleLine = 0, + MultiLine = 1, + PreserveLines = 2, + LinesMask = 3, + NotDelimited = 0, + BarDelimited = 4, + AmpersandDelimited = 8, + CommaDelimited = 16, + AsteriskDelimited = 32, + DelimitersMask = 60, + AllowTrailingComma = 64, + Indented = 128, + SpaceBetweenBraces = 256, + SpaceBetweenSiblings = 512, + Braces = 1024, + Parenthesis = 2048, + AngleBrackets = 4096, + SquareBrackets = 8192, + BracketsMask = 15360, + OptionalIfUndefined = 16384, + OptionalIfEmpty = 32768, + Optional = 49152, + PreferNewLine = 65536, + NoTrailingNewLine = 131072, + NoInterveningComments = 262144, + NoSpaceIfEmpty = 524288, + SingleElement = 1048576, + Modifiers = 262656, + HeritageClauses = 512, + SingleLineTypeLiteralMembers = 768, + MultiLineTypeLiteralMembers = 32897, + TupleTypeElements = 528, + UnionTypeConstituents = 516, + IntersectionTypeConstituents = 520, + ObjectBindingPatternElements = 525136, + ArrayBindingPatternElements = 524880, + ObjectLiteralExpressionProperties = 526226, + ArrayLiteralExpressionElements = 8914, + CommaListElements = 528, + CallExpressionArguments = 2576, + NewExpressionArguments = 18960, + TemplateExpressionSpans = 262144, + SingleLineBlockStatements = 768, + MultiLineBlockStatements = 129, + VariableDeclarationList = 528, + SingleLineFunctionBodyStatements = 768, + MultiLineFunctionBodyStatements = 1, + ClassHeritageClauses = 0, + ClassMembers = 129, + InterfaceMembers = 129, + EnumMembers = 145, + CaseBlockClauses = 129, + NamedImportsOrExportsElements = 525136, + JsxElementOrFragmentChildren = 262144, + JsxElementAttributes = 262656, + CaseOrDefaultClauseStatements = 163969, + HeritageClauseTypes = 528, + SourceFileStatements = 131073, + Decorators = 49153, + TypeArguments = 53776, + TypeParameters = 53776, + Parameters = 2576, + IndexSignatureParameters = 8848, + JSDocComment = 33 + } + interface UserPreferences { + readonly disableSuggestions?: boolean; + readonly quotePreference?: "double" | "single"; + readonly includeCompletionsForModuleExports?: boolean; + readonly includeCompletionsWithInsertText?: boolean; + readonly importModuleSpecifierPreference?: "relative" | "non-relative"; + /** Determines whether we import `foo/index.ts` as "foo", "foo/index", or "foo/index.js" */ + readonly importModuleSpecifierEnding?: "minimal" | "index" | "js"; + readonly allowTextChangesInNewFiles?: boolean; + } + /** Represents a bigint literal value without requiring bigint support */ + interface PseudoBigInt { + negative: boolean; + base10Value: string; + } +} +declare function setTimeout(handler: (...args: any[]) => void, timeout: number): any; +declare function clearTimeout(handle: any): void; +declare namespace ts { + enum FileWatcherEventKind { + Created = 0, + Changed = 1, + Deleted = 2 + } + type FileWatcherCallback = (fileName: string, eventKind: FileWatcherEventKind) => void; + type DirectoryWatcherCallback = (fileName: string) => void; + interface System { + args: string[]; + newLine: string; + useCaseSensitiveFileNames: boolean; + write(s: string): void; + writeOutputIsTTY?(): boolean; + readFile(path: string, encoding?: string): string | undefined; + getFileSize?(path: string): number; + writeFile(path: string, data: string, writeByteOrderMark?: boolean): void; + /** + * @pollingInterval - this parameter is used in polling-based watchers and ignored in watchers that + * use native OS file watching + */ + watchFile?(path: string, callback: FileWatcherCallback, pollingInterval?: number): FileWatcher; + watchDirectory?(path: string, callback: DirectoryWatcherCallback, recursive?: boolean): FileWatcher; + resolvePath(path: string): string; + fileExists(path: string): boolean; + directoryExists(path: string): boolean; + createDirectory(path: string): void; + getExecutingFilePath(): string; + getCurrentDirectory(): string; + getDirectories(path: string): string[]; + readDirectory(path: string, extensions?: ReadonlyArray, exclude?: ReadonlyArray, include?: ReadonlyArray, depth?: number): string[]; + getModifiedTime?(path: string): Date | undefined; + setModifiedTime?(path: string, time: Date): void; + deleteFile?(path: string): void; + /** + * A good implementation is node.js' `crypto.createHash`. (https://nodejs.org/api/crypto.html#crypto_crypto_createhash_algorithm) + */ + createHash?(data: string): string; + /** This must be cryptographically secure. Only implement this method using `crypto.createHash("sha256")`. */ + createSHA256Hash?(data: string): string; + getMemoryUsage?(): number; + exit(exitCode?: number): void; + realpath?(path: string): string; + setTimeout?(callback: (...args: any[]) => void, ms: number, ...args: any[]): any; + clearTimeout?(timeoutId: any): void; + clearScreen?(): void; + base64decode?(input: string): string; + base64encode?(input: string): string; + } + interface FileWatcher { + close(): void; + } + function getNodeMajorVersion(): number | undefined; + let sys: System; +} +declare namespace ts { + type ErrorCallback = (message: DiagnosticMessage, length: number) => void; + interface Scanner { + getStartPos(): number; + getToken(): SyntaxKind; + getTextPos(): number; + getTokenPos(): number; + getTokenText(): string; + getTokenValue(): string; + hasExtendedUnicodeEscape(): boolean; + hasPrecedingLineBreak(): boolean; + isIdentifier(): boolean; + isReservedWord(): boolean; + isUnterminated(): boolean; + reScanGreaterToken(): SyntaxKind; + reScanSlashToken(): SyntaxKind; + reScanTemplateToken(): SyntaxKind; + scanJsxIdentifier(): SyntaxKind; + scanJsxAttributeValue(): SyntaxKind; + reScanJsxToken(): JsxTokenSyntaxKind; + scanJsxToken(): JsxTokenSyntaxKind; + scanJSDocToken(): JsDocSyntaxKind; + scan(): SyntaxKind; + getText(): string; + setText(text: string | undefined, start?: number, length?: number): void; + setOnError(onError: ErrorCallback | undefined): void; + setScriptTarget(scriptTarget: ScriptTarget): void; + setLanguageVariant(variant: LanguageVariant): void; + setTextPos(textPos: number): void; + lookAhead(callback: () => T): T; + scanRange(start: number, length: number, callback: () => T): T; + tryScan(callback: () => T): T; + } + function tokenToString(t: SyntaxKind): string | undefined; + function getPositionOfLineAndCharacter(sourceFile: SourceFileLike, line: number, character: number): number; + function getLineAndCharacterOfPosition(sourceFile: SourceFileLike, position: number): LineAndCharacter; + function isWhiteSpaceLike(ch: number): boolean; + /** Does not include line breaks. For that, see isWhiteSpaceLike. */ + function isWhiteSpaceSingleLine(ch: number): boolean; + function isLineBreak(ch: number): boolean; + function couldStartTrivia(text: string, pos: number): boolean; + function forEachLeadingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean) => U): U | undefined; + function forEachLeadingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T) => U, state: T): U | undefined; + function forEachTrailingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean) => U): U | undefined; + function forEachTrailingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T) => U, state: T): U | undefined; + function reduceEachLeadingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T, memo: U) => U, state: T, initial: U): U | undefined; + function reduceEachTrailingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T, memo: U) => U, state: T, initial: U): U | undefined; + function getLeadingCommentRanges(text: string, pos: number): CommentRange[] | undefined; + function getTrailingCommentRanges(text: string, pos: number): CommentRange[] | undefined; + /** Optionally, get the shebang */ + function getShebang(text: string): string | undefined; + function isIdentifierStart(ch: number, languageVersion: ScriptTarget | undefined): boolean; + function isIdentifierPart(ch: number, languageVersion: ScriptTarget | undefined): boolean; + function createScanner(languageVersion: ScriptTarget, skipTrivia: boolean, languageVariant?: LanguageVariant, textInitial?: string, onError?: ErrorCallback, start?: number, length?: number): Scanner; +} +declare namespace ts { + function isExternalModuleNameRelative(moduleName: string): boolean; + function sortAndDeduplicateDiagnostics(diagnostics: ReadonlyArray): SortedReadonlyArray; +} +declare namespace ts { + function getDefaultLibFileName(options: CompilerOptions): string; + function textSpanEnd(span: TextSpan): number; + function textSpanIsEmpty(span: TextSpan): boolean; + function textSpanContainsPosition(span: TextSpan, position: number): boolean; + function textSpanContainsTextSpan(span: TextSpan, other: TextSpan): boolean; + function textSpanOverlapsWith(span: TextSpan, other: TextSpan): boolean; + function textSpanOverlap(span1: TextSpan, span2: TextSpan): TextSpan | undefined; + function textSpanIntersectsWithTextSpan(span: TextSpan, other: TextSpan): boolean; + function textSpanIntersectsWith(span: TextSpan, start: number, length: number): boolean; + function decodedTextSpanIntersectsWith(start1: number, length1: number, start2: number, length2: number): boolean; + function textSpanIntersectsWithPosition(span: TextSpan, position: number): boolean; + function textSpanIntersection(span1: TextSpan, span2: TextSpan): TextSpan | undefined; + function createTextSpan(start: number, length: number): TextSpan; + function createTextSpanFromBounds(start: number, end: number): TextSpan; + function textChangeRangeNewSpan(range: TextChangeRange): TextSpan; + function textChangeRangeIsUnchanged(range: TextChangeRange): boolean; + function createTextChangeRange(span: TextSpan, newLength: number): TextChangeRange; + let unchangedTextChangeRange: TextChangeRange; + /** + * Called to merge all the changes that occurred across several versions of a script snapshot + * into a single change. i.e. if a user keeps making successive edits to a script we will + * have a text change from V1 to V2, V2 to V3, ..., Vn. + * + * This function will then merge those changes into a single change range valid between V1 and + * Vn. + */ + function collapseTextChangeRangesAcrossMultipleVersions(changes: ReadonlyArray): TextChangeRange; + function getTypeParameterOwner(d: Declaration): Declaration | undefined; + type ParameterPropertyDeclaration = ParameterDeclaration & { + parent: ConstructorDeclaration; + name: Identifier; + }; + function isParameterPropertyDeclaration(node: Node): node is ParameterPropertyDeclaration; + function isEmptyBindingPattern(node: BindingName): node is BindingPattern; + function isEmptyBindingElement(node: BindingElement): boolean; + function walkUpBindingElementsAndPatterns(binding: BindingElement): VariableDeclaration | ParameterDeclaration; + function getCombinedModifierFlags(node: Declaration): ModifierFlags; + function getCombinedNodeFlags(node: Node): NodeFlags; + /** + * Checks to see if the locale is in the appropriate format, + * and if it is, attempts to set the appropriate language. + */ + function validateLocaleAndSetLanguage(locale: string, sys: { + getExecutingFilePath(): string; + resolvePath(path: string): string; + fileExists(fileName: string): boolean; + readFile(fileName: string): string | undefined; + }, errors?: Push): void; + function getOriginalNode(node: Node): Node; + function getOriginalNode(node: Node, nodeTest: (node: Node) => node is T): T; + function getOriginalNode(node: Node | undefined): Node | undefined; + function getOriginalNode(node: Node | undefined, nodeTest: (node: Node | undefined) => node is T): T | undefined; + /** + * Gets a value indicating whether a node originated in the parse tree. + * + * @param node The node to test. + */ + function isParseTreeNode(node: Node): boolean; + /** + * Gets the original parse tree node for a node. + * + * @param node The original node. + * @returns The original parse tree node if found; otherwise, undefined. + */ + function getParseTreeNode(node: Node): Node; + /** + * Gets the original parse tree node for a node. + * + * @param node The original node. + * @param nodeTest A callback used to ensure the correct type of parse tree node is returned. + * @returns The original parse tree node if found; otherwise, undefined. + */ + function getParseTreeNode(node: Node | undefined, nodeTest?: (node: Node) => node is T): T | undefined; + /** Add an extra underscore to identifiers that start with two underscores to avoid issues with magic names like '__proto__' */ + function escapeLeadingUnderscores(identifier: string): __String; + /** + * Remove extra underscore from escaped identifier text content. + * + * @param identifier The escaped identifier text. + * @returns The unescaped identifier text. + */ + function unescapeLeadingUnderscores(identifier: __String): string; + function idText(identifier: Identifier): string; + function symbolName(symbol: Symbol): string; + function getNameOfJSDocTypedef(declaration: JSDocTypedefTag): Identifier | undefined; + function getNameOfDeclaration(declaration: Declaration | Expression): DeclarationName | undefined; + /** + * Gets the JSDoc parameter tags for the node if present. + * + * @remarks Returns any JSDoc param tag whose name matches the provided + * parameter, whether a param tag on a containing function + * expression, or a param tag on a variable declaration whose + * initializer is the containing function. The tags closest to the + * node are returned first, so in the previous example, the param + * tag on the containing function expression would be first. + * + * For binding patterns, parameter tags are matched by position. + */ + function getJSDocParameterTags(param: ParameterDeclaration): ReadonlyArray; + /** + * Gets the JSDoc type parameter tags for the node if present. + * + * @remarks Returns any JSDoc template tag whose names match the provided + * parameter, whether a template tag on a containing function + * expression, or a template tag on a variable declaration whose + * initializer is the containing function. The tags closest to the + * node are returned first, so in the previous example, the template + * tag on the containing function expression would be first. + */ + function getJSDocTypeParameterTags(param: TypeParameterDeclaration): ReadonlyArray; + /** + * Return true if the node has JSDoc parameter tags. + * + * @remarks Includes parameter tags that are not directly on the node, + * for example on a variable declaration whose initializer is a function expression. + */ + function hasJSDocParameterTags(node: FunctionLikeDeclaration | SignatureDeclaration): boolean; + /** Gets the JSDoc augments tag for the node if present */ + function getJSDocAugmentsTag(node: Node): JSDocAugmentsTag | undefined; + /** Gets the JSDoc class tag for the node if present */ + function getJSDocClassTag(node: Node): JSDocClassTag | undefined; + /** Gets the JSDoc enum tag for the node if present */ + function getJSDocEnumTag(node: Node): JSDocEnumTag | undefined; + /** Gets the JSDoc this tag for the node if present */ + function getJSDocThisTag(node: Node): JSDocThisTag | undefined; + /** Gets the JSDoc return tag for the node if present */ + function getJSDocReturnTag(node: Node): JSDocReturnTag | undefined; + /** Gets the JSDoc template tag for the node if present */ + function getJSDocTemplateTag(node: Node): JSDocTemplateTag | undefined; + /** Gets the JSDoc type tag for the node if present and valid */ + function getJSDocTypeTag(node: Node): JSDocTypeTag | undefined; + /** + * Gets the type node for the node if provided via JSDoc. + * + * @remarks The search includes any JSDoc param tag that relates + * to the provided parameter, for example a type tag on the + * parameter itself, or a param tag on a containing function + * expression, or a param tag on a variable declaration whose + * initializer is the containing function. The tags closest to the + * node are examined first, so in the previous example, the type + * tag directly on the node would be returned. + */ + function getJSDocType(node: Node): TypeNode | undefined; + /** + * Gets the return type node for the node if provided via JSDoc return tag or type tag. + * + * @remarks `getJSDocReturnTag` just gets the whole JSDoc tag. This function + * gets the type from inside the braces, after the fat arrow, etc. + */ + function getJSDocReturnType(node: Node): TypeNode | undefined; + /** Get all JSDoc tags related to a node, including those on parent nodes. */ + function getJSDocTags(node: Node): ReadonlyArray; + /** Gets all JSDoc tags of a specified kind, or undefined if not present. */ + function getAllJSDocTagsOfKind(node: Node, kind: SyntaxKind): ReadonlyArray; + /** + * Gets the effective type parameters. If the node was parsed in a + * JavaScript file, gets the type parameters from the `@template` tag from JSDoc. + */ + function getEffectiveTypeParameterDeclarations(node: DeclarationWithTypeParameters): ReadonlyArray; + function getEffectiveConstraintOfTypeParameter(node: TypeParameterDeclaration): TypeNode | undefined; +} +declare namespace ts { + function isNumericLiteral(node: Node): node is NumericLiteral; + function isBigIntLiteral(node: Node): node is BigIntLiteral; + function isStringLiteral(node: Node): node is StringLiteral; + function isJsxText(node: Node): node is JsxText; + function isRegularExpressionLiteral(node: Node): node is RegularExpressionLiteral; + function isNoSubstitutionTemplateLiteral(node: Node): node is NoSubstitutionTemplateLiteral; + function isTemplateHead(node: Node): node is TemplateHead; + function isTemplateMiddle(node: Node): node is TemplateMiddle; + function isTemplateTail(node: Node): node is TemplateTail; + function isIdentifier(node: Node): node is Identifier; + function isQualifiedName(node: Node): node is QualifiedName; + function isComputedPropertyName(node: Node): node is ComputedPropertyName; + function isTypeParameterDeclaration(node: Node): node is TypeParameterDeclaration; + function isParameter(node: Node): node is ParameterDeclaration; + function isDecorator(node: Node): node is Decorator; + function isPropertySignature(node: Node): node is PropertySignature; + function isPropertyDeclaration(node: Node): node is PropertyDeclaration; + function isMethodSignature(node: Node): node is MethodSignature; + function isMethodDeclaration(node: Node): node is MethodDeclaration; + function isConstructorDeclaration(node: Node): node is ConstructorDeclaration; + function isGetAccessorDeclaration(node: Node): node is GetAccessorDeclaration; + function isSetAccessorDeclaration(node: Node): node is SetAccessorDeclaration; + function isCallSignatureDeclaration(node: Node): node is CallSignatureDeclaration; + function isConstructSignatureDeclaration(node: Node): node is ConstructSignatureDeclaration; + function isIndexSignatureDeclaration(node: Node): node is IndexSignatureDeclaration; + function isTypePredicateNode(node: Node): node is TypePredicateNode; + function isTypeReferenceNode(node: Node): node is TypeReferenceNode; + function isFunctionTypeNode(node: Node): node is FunctionTypeNode; + function isConstructorTypeNode(node: Node): node is ConstructorTypeNode; + function isTypeQueryNode(node: Node): node is TypeQueryNode; + function isTypeLiteralNode(node: Node): node is TypeLiteralNode; + function isArrayTypeNode(node: Node): node is ArrayTypeNode; + function isTupleTypeNode(node: Node): node is TupleTypeNode; + function isUnionTypeNode(node: Node): node is UnionTypeNode; + function isIntersectionTypeNode(node: Node): node is IntersectionTypeNode; + function isConditionalTypeNode(node: Node): node is ConditionalTypeNode; + function isInferTypeNode(node: Node): node is InferTypeNode; + function isParenthesizedTypeNode(node: Node): node is ParenthesizedTypeNode; + function isThisTypeNode(node: Node): node is ThisTypeNode; + function isTypeOperatorNode(node: Node): node is TypeOperatorNode; + function isIndexedAccessTypeNode(node: Node): node is IndexedAccessTypeNode; + function isMappedTypeNode(node: Node): node is MappedTypeNode; + function isLiteralTypeNode(node: Node): node is LiteralTypeNode; + function isImportTypeNode(node: Node): node is ImportTypeNode; + function isObjectBindingPattern(node: Node): node is ObjectBindingPattern; + function isArrayBindingPattern(node: Node): node is ArrayBindingPattern; + function isBindingElement(node: Node): node is BindingElement; + function isArrayLiteralExpression(node: Node): node is ArrayLiteralExpression; + function isObjectLiteralExpression(node: Node): node is ObjectLiteralExpression; + function isPropertyAccessExpression(node: Node): node is PropertyAccessExpression; + function isElementAccessExpression(node: Node): node is ElementAccessExpression; + function isCallExpression(node: Node): node is CallExpression; + function isNewExpression(node: Node): node is NewExpression; + function isTaggedTemplateExpression(node: Node): node is TaggedTemplateExpression; + function isTypeAssertion(node: Node): node is TypeAssertion; + function isParenthesizedExpression(node: Node): node is ParenthesizedExpression; + function skipPartiallyEmittedExpressions(node: Expression): Expression; + function skipPartiallyEmittedExpressions(node: Node): Node; + function isFunctionExpression(node: Node): node is FunctionExpression; + function isArrowFunction(node: Node): node is ArrowFunction; + function isDeleteExpression(node: Node): node is DeleteExpression; + function isTypeOfExpression(node: Node): node is TypeOfExpression; + function isVoidExpression(node: Node): node is VoidExpression; + function isAwaitExpression(node: Node): node is AwaitExpression; + function isPrefixUnaryExpression(node: Node): node is PrefixUnaryExpression; + function isPostfixUnaryExpression(node: Node): node is PostfixUnaryExpression; + function isBinaryExpression(node: Node): node is BinaryExpression; + function isConditionalExpression(node: Node): node is ConditionalExpression; + function isTemplateExpression(node: Node): node is TemplateExpression; + function isYieldExpression(node: Node): node is YieldExpression; + function isSpreadElement(node: Node): node is SpreadElement; + function isClassExpression(node: Node): node is ClassExpression; + function isOmittedExpression(node: Node): node is OmittedExpression; + function isExpressionWithTypeArguments(node: Node): node is ExpressionWithTypeArguments; + function isAsExpression(node: Node): node is AsExpression; + function isNonNullExpression(node: Node): node is NonNullExpression; + function isMetaProperty(node: Node): node is MetaProperty; + function isTemplateSpan(node: Node): node is TemplateSpan; + function isSemicolonClassElement(node: Node): node is SemicolonClassElement; + function isBlock(node: Node): node is Block; + function isVariableStatement(node: Node): node is VariableStatement; + function isEmptyStatement(node: Node): node is EmptyStatement; + function isExpressionStatement(node: Node): node is ExpressionStatement; + function isIfStatement(node: Node): node is IfStatement; + function isDoStatement(node: Node): node is DoStatement; + function isWhileStatement(node: Node): node is WhileStatement; + function isForStatement(node: Node): node is ForStatement; + function isForInStatement(node: Node): node is ForInStatement; + function isForOfStatement(node: Node): node is ForOfStatement; + function isContinueStatement(node: Node): node is ContinueStatement; + function isBreakStatement(node: Node): node is BreakStatement; + function isBreakOrContinueStatement(node: Node): node is BreakOrContinueStatement; + function isReturnStatement(node: Node): node is ReturnStatement; + function isWithStatement(node: Node): node is WithStatement; + function isSwitchStatement(node: Node): node is SwitchStatement; + function isLabeledStatement(node: Node): node is LabeledStatement; + function isThrowStatement(node: Node): node is ThrowStatement; + function isTryStatement(node: Node): node is TryStatement; + function isDebuggerStatement(node: Node): node is DebuggerStatement; + function isVariableDeclaration(node: Node): node is VariableDeclaration; + function isVariableDeclarationList(node: Node): node is VariableDeclarationList; + function isFunctionDeclaration(node: Node): node is FunctionDeclaration; + function isClassDeclaration(node: Node): node is ClassDeclaration; + function isInterfaceDeclaration(node: Node): node is InterfaceDeclaration; + function isTypeAliasDeclaration(node: Node): node is TypeAliasDeclaration; + function isEnumDeclaration(node: Node): node is EnumDeclaration; + function isModuleDeclaration(node: Node): node is ModuleDeclaration; + function isModuleBlock(node: Node): node is ModuleBlock; + function isCaseBlock(node: Node): node is CaseBlock; + function isNamespaceExportDeclaration(node: Node): node is NamespaceExportDeclaration; + function isImportEqualsDeclaration(node: Node): node is ImportEqualsDeclaration; + function isImportDeclaration(node: Node): node is ImportDeclaration; + function isImportClause(node: Node): node is ImportClause; + function isNamespaceImport(node: Node): node is NamespaceImport; + function isNamedImports(node: Node): node is NamedImports; + function isImportSpecifier(node: Node): node is ImportSpecifier; + function isExportAssignment(node: Node): node is ExportAssignment; + function isExportDeclaration(node: Node): node is ExportDeclaration; + function isNamedExports(node: Node): node is NamedExports; + function isExportSpecifier(node: Node): node is ExportSpecifier; + function isMissingDeclaration(node: Node): node is MissingDeclaration; + function isExternalModuleReference(node: Node): node is ExternalModuleReference; + function isJsxElement(node: Node): node is JsxElement; + function isJsxSelfClosingElement(node: Node): node is JsxSelfClosingElement; + function isJsxOpeningElement(node: Node): node is JsxOpeningElement; + function isJsxClosingElement(node: Node): node is JsxClosingElement; + function isJsxFragment(node: Node): node is JsxFragment; + function isJsxOpeningFragment(node: Node): node is JsxOpeningFragment; + function isJsxClosingFragment(node: Node): node is JsxClosingFragment; + function isJsxAttribute(node: Node): node is JsxAttribute; + function isJsxAttributes(node: Node): node is JsxAttributes; + function isJsxSpreadAttribute(node: Node): node is JsxSpreadAttribute; + function isJsxExpression(node: Node): node is JsxExpression; + function isCaseClause(node: Node): node is CaseClause; + function isDefaultClause(node: Node): node is DefaultClause; + function isHeritageClause(node: Node): node is HeritageClause; + function isCatchClause(node: Node): node is CatchClause; + function isPropertyAssignment(node: Node): node is PropertyAssignment; + function isShorthandPropertyAssignment(node: Node): node is ShorthandPropertyAssignment; + function isSpreadAssignment(node: Node): node is SpreadAssignment; + function isEnumMember(node: Node): node is EnumMember; + function isSourceFile(node: Node): node is SourceFile; + function isBundle(node: Node): node is Bundle; + function isUnparsedSource(node: Node): node is UnparsedSource; + function isJSDocTypeExpression(node: Node): node is JSDocTypeExpression; + function isJSDocAllType(node: JSDocAllType): node is JSDocAllType; + function isJSDocUnknownType(node: Node): node is JSDocUnknownType; + function isJSDocNullableType(node: Node): node is JSDocNullableType; + function isJSDocNonNullableType(node: Node): node is JSDocNonNullableType; + function isJSDocOptionalType(node: Node): node is JSDocOptionalType; + function isJSDocFunctionType(node: Node): node is JSDocFunctionType; + function isJSDocVariadicType(node: Node): node is JSDocVariadicType; + function isJSDoc(node: Node): node is JSDoc; + function isJSDocAugmentsTag(node: Node): node is JSDocAugmentsTag; + function isJSDocClassTag(node: Node): node is JSDocClassTag; + function isJSDocEnumTag(node: Node): node is JSDocEnumTag; + function isJSDocThisTag(node: Node): node is JSDocThisTag; + function isJSDocParameterTag(node: Node): node is JSDocParameterTag; + function isJSDocReturnTag(node: Node): node is JSDocReturnTag; + function isJSDocTypeTag(node: Node): node is JSDocTypeTag; + function isJSDocTemplateTag(node: Node): node is JSDocTemplateTag; + function isJSDocTypedefTag(node: Node): node is JSDocTypedefTag; + function isJSDocPropertyTag(node: Node): node is JSDocPropertyTag; + function isJSDocPropertyLikeTag(node: Node): node is JSDocPropertyLikeTag; + function isJSDocTypeLiteral(node: Node): node is JSDocTypeLiteral; + function isJSDocCallbackTag(node: Node): node is JSDocCallbackTag; + function isJSDocSignature(node: Node): node is JSDocSignature; +} +declare namespace ts { + /** + * True if node is of some token syntax kind. + * For example, this is true for an IfKeyword but not for an IfStatement. + * Literals are considered tokens, except TemplateLiteral, but does include TemplateHead/Middle/Tail. + */ + function isToken(n: Node): boolean; + function isLiteralExpression(node: Node): node is LiteralExpression; + type TemplateLiteralToken = NoSubstitutionTemplateLiteral | TemplateHead | TemplateMiddle | TemplateTail; + function isTemplateLiteralToken(node: Node): node is TemplateLiteralToken; + function isTemplateMiddleOrTemplateTail(node: Node): node is TemplateMiddle | TemplateTail; + function isImportOrExportSpecifier(node: Node): node is ImportSpecifier | ExportSpecifier; + function isStringTextContainingNode(node: Node): node is StringLiteral | TemplateLiteralToken; + function isModifier(node: Node): node is Modifier; + function isEntityName(node: Node): node is EntityName; + function isPropertyName(node: Node): node is PropertyName; + function isBindingName(node: Node): node is BindingName; + function isFunctionLike(node: Node): node is SignatureDeclaration; + function isClassElement(node: Node): node is ClassElement; + function isClassLike(node: Node): node is ClassLikeDeclaration; + function isAccessor(node: Node): node is AccessorDeclaration; + function isTypeElement(node: Node): node is TypeElement; + function isClassOrTypeElement(node: Node): node is ClassElement | TypeElement; + function isObjectLiteralElementLike(node: Node): node is ObjectLiteralElementLike; + /** + * Node test that determines whether a node is a valid type node. + * This differs from the `isPartOfTypeNode` function which determines whether a node is *part* + * of a TypeNode. + */ + function isTypeNode(node: Node): node is TypeNode; + function isFunctionOrConstructorTypeNode(node: Node): node is FunctionTypeNode | ConstructorTypeNode; + function isPropertyAccessOrQualifiedName(node: Node): node is PropertyAccessExpression | QualifiedName; + function isCallLikeExpression(node: Node): node is CallLikeExpression; + function isCallOrNewExpression(node: Node): node is CallExpression | NewExpression; + function isTemplateLiteral(node: Node): node is TemplateLiteral; + function isAssertionExpression(node: Node): node is AssertionExpression; + function isIterationStatement(node: Node, lookInLabeledStatements: false): node is IterationStatement; + function isIterationStatement(node: Node, lookInLabeledStatements: boolean): node is IterationStatement | LabeledStatement; + function isJsxOpeningLikeElement(node: Node): node is JsxOpeningLikeElement; + function isCaseOrDefaultClause(node: Node): node is CaseOrDefaultClause; + /** True if node is of a kind that may contain comment text. */ + function isJSDocCommentContainingNode(node: Node): boolean; + function isSetAccessor(node: Node): node is SetAccessorDeclaration; + function isGetAccessor(node: Node): node is GetAccessorDeclaration; + function isObjectLiteralElement(node: Node): node is ObjectLiteralElement; + function isStringLiteralLike(node: Node): node is StringLiteralLike; +} +declare namespace ts { + function createNode(kind: SyntaxKind, pos?: number, end?: number): Node; + /** + * Invokes a callback for each child of the given node. The 'cbNode' callback is invoked for all child nodes + * stored in properties. If a 'cbNodes' callback is specified, it is invoked for embedded arrays; otherwise, + * embedded arrays are flattened and the 'cbNode' callback is invoked for each element. If a callback returns + * a truthy value, iteration stops and that value is returned. Otherwise, undefined is returned. + * + * @param node a given node to visit its children + * @param cbNode a callback to be invoked for all child nodes + * @param cbNodes a callback to be invoked for embedded array + * + * @remarks `forEachChild` must visit the children of a node in the order + * that they appear in the source code. The language service depends on this property to locate nodes by position. + */ + function forEachChild(node: Node, cbNode: (node: Node) => T | undefined, cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined; + function createSourceFile(fileName: string, sourceText: string, languageVersion: ScriptTarget, setParentNodes?: boolean, scriptKind?: ScriptKind): SourceFile; + function parseIsolatedEntityName(text: string, languageVersion: ScriptTarget): EntityName | undefined; + /** + * Parse json text into SyntaxTree and return node and parse errors if any + * @param fileName + * @param sourceText + */ + function parseJsonText(fileName: string, sourceText: string): JsonSourceFile; + function isExternalModule(file: SourceFile): boolean; + function updateSourceFile(sourceFile: SourceFile, newText: string, textChangeRange: TextChangeRange, aggressiveChecks?: boolean): SourceFile; +} +declare namespace ts { + function parseCommandLine(commandLine: ReadonlyArray, readFile?: (path: string) => string | undefined): ParsedCommandLine; + type DiagnosticReporter = (diagnostic: Diagnostic) => void; + /** + * Reports config file diagnostics + */ + interface ConfigFileDiagnosticsReporter { + /** + * Reports unrecoverable error when parsing config file + */ + onUnRecoverableConfigFileDiagnostic: DiagnosticReporter; + } + /** + * Interface extending ParseConfigHost to support ParseConfigFile that reads config file and reports errors + */ + interface ParseConfigFileHost extends ParseConfigHost, ConfigFileDiagnosticsReporter { + getCurrentDirectory(): string; + } + /** + * Reads the config file, reports errors if any and exits if the config file cannot be found + */ + function getParsedCommandLineOfConfigFile(configFileName: string, optionsToExtend: CompilerOptions, host: ParseConfigFileHost): ParsedCommandLine | undefined; + /** + * Read tsconfig.json file + * @param fileName The path to the config file + */ + function readConfigFile(fileName: string, readFile: (path: string) => string | undefined): { + config?: any; + error?: Diagnostic; + }; + /** + * Parse the text of the tsconfig.json file + * @param fileName The path to the config file + * @param jsonText The text of the config file + */ + function parseConfigFileTextToJson(fileName: string, jsonText: string): { + config?: any; + error?: Diagnostic; + }; + /** + * Read tsconfig.json file + * @param fileName The path to the config file + */ + function readJsonConfigFile(fileName: string, readFile: (path: string) => string | undefined): TsConfigSourceFile; + /** + * Convert the json syntax tree into the json value + */ + function convertToObject(sourceFile: JsonSourceFile, errors: Push): any; + /** + * Parse the contents of a config file (tsconfig.json). + * @param json The contents of the config file to parse + * @param host Instance of ParseConfigHost used to enumerate files in folder. + * @param basePath A root directory to resolve relative path entries in the config + * file to. e.g. outDir + */ + function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[], extraFileExtensions?: ReadonlyArray): ParsedCommandLine; + /** + * Parse the contents of a config file (tsconfig.json). + * @param jsonNode The contents of the config file to parse + * @param host Instance of ParseConfigHost used to enumerate files in folder. + * @param basePath A root directory to resolve relative path entries in the config + * file to. e.g. outDir + */ + function parseJsonSourceFileConfigFileContent(sourceFile: TsConfigSourceFile, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[], extraFileExtensions?: ReadonlyArray): ParsedCommandLine; + function convertCompilerOptionsFromJson(jsonOptions: any, basePath: string, configFileName?: string): { + options: CompilerOptions; + errors: Diagnostic[]; + }; + function convertTypeAcquisitionFromJson(jsonOptions: any, basePath: string, configFileName?: string): { + options: TypeAcquisition; + errors: Diagnostic[]; + }; +} +declare namespace ts { + function getEffectiveTypeRoots(options: CompilerOptions, host: GetEffectiveTypeRootsHost): string[] | undefined; + /** + * @param {string | undefined} containingFile - file that contains type reference directive, can be undefined if containing file is unknown. + * This is possible in case if resolution is performed for directives specified via 'types' parameter. In this case initial path for secondary lookups + * is assumed to be the same as root directory of the project. + */ + function resolveTypeReferenceDirective(typeReferenceDirectiveName: string, containingFile: string | undefined, options: CompilerOptions, host: ModuleResolutionHost, redirectedReference?: ResolvedProjectReference): ResolvedTypeReferenceDirectiveWithFailedLookupLocations; + /** + * Given a set of options, returns the set of type directive names + * that should be included for this program automatically. + * This list could either come from the config file, + * or from enumerating the types root + initial secondary types lookup location. + * More type directives might appear in the program later as a result of loading actual source files; + * this list is only the set of defaults that are implicitly included. + */ + function getAutomaticTypeDirectiveNames(options: CompilerOptions, host: ModuleResolutionHost): string[]; + /** + * Cached module resolutions per containing directory. + * This assumes that any module id will have the same resolution for sibling files located in the same folder. + */ + interface ModuleResolutionCache extends NonRelativeModuleNameResolutionCache { + getOrCreateCacheForDirectory(directoryName: string, redirectedReference?: ResolvedProjectReference): Map; + } + /** + * Stored map from non-relative module name to a table: directory -> result of module lookup in this directory + * We support only non-relative module names because resolution of relative module names is usually more deterministic and thus less expensive. + */ + interface NonRelativeModuleNameResolutionCache { + getOrCreateCacheForModuleName(nonRelativeModuleName: string, redirectedReference?: ResolvedProjectReference): PerModuleNameCache; + } + interface PerModuleNameCache { + get(directory: string): ResolvedModuleWithFailedLookupLocations | undefined; + set(directory: string, result: ResolvedModuleWithFailedLookupLocations): void; + } + function createModuleResolutionCache(currentDirectory: string, getCanonicalFileName: (s: string) => string): ModuleResolutionCache; + function resolveModuleNameFromCache(moduleName: string, containingFile: string, cache: ModuleResolutionCache): ResolvedModuleWithFailedLookupLocations | undefined; + function resolveModuleName(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: ModuleResolutionCache, redirectedReference?: ResolvedProjectReference): ResolvedModuleWithFailedLookupLocations; + function nodeModuleNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: ModuleResolutionCache, redirectedReference?: ResolvedProjectReference): ResolvedModuleWithFailedLookupLocations; + function classicNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: NonRelativeModuleNameResolutionCache, redirectedReference?: ResolvedProjectReference): ResolvedModuleWithFailedLookupLocations; +} +declare namespace ts { + function createNodeArray(elements?: ReadonlyArray, hasTrailingComma?: boolean): NodeArray; + /** If a node is passed, creates a string literal whose source text is read from a source node during emit. */ + function createLiteral(value: string | StringLiteral | NoSubstitutionTemplateLiteral | NumericLiteral | Identifier): StringLiteral; + function createLiteral(value: number | PseudoBigInt): NumericLiteral; + function createLiteral(value: boolean): BooleanLiteral; + function createLiteral(value: string | number | PseudoBigInt | boolean): PrimaryExpression; + function createNumericLiteral(value: string): NumericLiteral; + function createBigIntLiteral(value: string): BigIntLiteral; + function createStringLiteral(text: string): StringLiteral; + function createRegularExpressionLiteral(text: string): RegularExpressionLiteral; + function createIdentifier(text: string): Identifier; + function updateIdentifier(node: Identifier): Identifier; + /** Create a unique temporary variable. */ + function createTempVariable(recordTempVariable: ((node: Identifier) => void) | undefined): Identifier; + /** Create a unique temporary variable for use in a loop. */ + function createLoopVariable(): Identifier; + /** Create a unique name based on the supplied text. */ + function createUniqueName(text: string): Identifier; + /** Create a unique name based on the supplied text. */ + function createOptimisticUniqueName(text: string): Identifier; + /** Create a unique name based on the supplied text. This does not consider names injected by the transformer. */ + function createFileLevelUniqueName(text: string): Identifier; + /** Create a unique name generated for a node. */ + function getGeneratedNameForNode(node: Node | undefined): Identifier; + function createToken(token: TKind): Token; + function createSuper(): SuperExpression; + function createThis(): ThisExpression & Token; + function createNull(): NullLiteral & Token; + function createTrue(): BooleanLiteral & Token; + function createFalse(): BooleanLiteral & Token; + function createModifier(kind: T): Token; + function createModifiersFromModifierFlags(flags: ModifierFlags): Modifier[]; + function createQualifiedName(left: EntityName, right: string | Identifier): QualifiedName; + function updateQualifiedName(node: QualifiedName, left: EntityName, right: Identifier): QualifiedName; + function createComputedPropertyName(expression: Expression): ComputedPropertyName; + function updateComputedPropertyName(node: ComputedPropertyName, expression: Expression): ComputedPropertyName; + function createTypeParameterDeclaration(name: string | Identifier, constraint?: TypeNode, defaultType?: TypeNode): TypeParameterDeclaration; + function updateTypeParameterDeclaration(node: TypeParameterDeclaration, name: Identifier, constraint: TypeNode | undefined, defaultType: TypeNode | undefined): TypeParameterDeclaration; + function createParameter(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, dotDotDotToken: DotDotDotToken | undefined, name: string | BindingName, questionToken?: QuestionToken, type?: TypeNode, initializer?: Expression): ParameterDeclaration; + function updateParameter(node: ParameterDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, dotDotDotToken: DotDotDotToken | undefined, name: string | BindingName, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): ParameterDeclaration; + function createDecorator(expression: Expression): Decorator; + function updateDecorator(node: Decorator, expression: Expression): Decorator; + function createPropertySignature(modifiers: ReadonlyArray | undefined, name: PropertyName | string, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): PropertySignature; + function updatePropertySignature(node: PropertySignature, modifiers: ReadonlyArray | undefined, name: PropertyName, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): PropertySignature; + function createProperty(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: string | PropertyName, questionOrExclamationToken: QuestionToken | ExclamationToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): PropertyDeclaration; + function updateProperty(node: PropertyDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: string | PropertyName, questionOrExclamationToken: QuestionToken | ExclamationToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): PropertyDeclaration; + function createMethodSignature(typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined): MethodSignature; + function updateMethodSignature(node: MethodSignature, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined, name: PropertyName, questionToken: QuestionToken | undefined): MethodSignature; + function createMethod(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, asteriskToken: AsteriskToken | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined, typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode | undefined, body: Block | undefined): MethodDeclaration; + function updateMethod(node: MethodDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, asteriskToken: AsteriskToken | undefined, name: PropertyName, questionToken: QuestionToken | undefined, typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode | undefined, body: Block | undefined): MethodDeclaration; + function createConstructor(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, parameters: ReadonlyArray, body: Block | undefined): ConstructorDeclaration; + function updateConstructor(node: ConstructorDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, parameters: ReadonlyArray, body: Block | undefined): ConstructorDeclaration; + function createGetAccessor(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: string | PropertyName, parameters: ReadonlyArray, type: TypeNode | undefined, body: Block | undefined): GetAccessorDeclaration; + function updateGetAccessor(node: GetAccessorDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: PropertyName, parameters: ReadonlyArray, type: TypeNode | undefined, body: Block | undefined): GetAccessorDeclaration; + function createSetAccessor(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: string | PropertyName, parameters: ReadonlyArray, body: Block | undefined): SetAccessorDeclaration; + function updateSetAccessor(node: SetAccessorDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: PropertyName, parameters: ReadonlyArray, body: Block | undefined): SetAccessorDeclaration; + function createCallSignature(typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode | undefined): CallSignatureDeclaration; + function updateCallSignature(node: CallSignatureDeclaration, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined): CallSignatureDeclaration; + function createConstructSignature(typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode | undefined): ConstructSignatureDeclaration; + function updateConstructSignature(node: ConstructSignatureDeclaration, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined): ConstructSignatureDeclaration; + function createIndexSignature(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode): IndexSignatureDeclaration; + function updateIndexSignature(node: IndexSignatureDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode): IndexSignatureDeclaration; + function createKeywordTypeNode(kind: KeywordTypeNode["kind"]): KeywordTypeNode; + function createTypePredicateNode(parameterName: Identifier | ThisTypeNode | string, type: TypeNode): TypePredicateNode; + function updateTypePredicateNode(node: TypePredicateNode, parameterName: Identifier | ThisTypeNode, type: TypeNode): TypePredicateNode; + function createTypeReferenceNode(typeName: string | EntityName, typeArguments: ReadonlyArray | undefined): TypeReferenceNode; + function updateTypeReferenceNode(node: TypeReferenceNode, typeName: EntityName, typeArguments: NodeArray | undefined): TypeReferenceNode; + function createFunctionTypeNode(typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode | undefined): FunctionTypeNode; + function updateFunctionTypeNode(node: FunctionTypeNode, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined): FunctionTypeNode; + function createConstructorTypeNode(typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode | undefined): ConstructorTypeNode; + function updateConstructorTypeNode(node: ConstructorTypeNode, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined): ConstructorTypeNode; + function createTypeQueryNode(exprName: EntityName): TypeQueryNode; + function updateTypeQueryNode(node: TypeQueryNode, exprName: EntityName): TypeQueryNode; + function createTypeLiteralNode(members: ReadonlyArray | undefined): TypeLiteralNode; + function updateTypeLiteralNode(node: TypeLiteralNode, members: NodeArray): TypeLiteralNode; + function createArrayTypeNode(elementType: TypeNode): ArrayTypeNode; + function updateArrayTypeNode(node: ArrayTypeNode, elementType: TypeNode): ArrayTypeNode; + function createTupleTypeNode(elementTypes: ReadonlyArray): TupleTypeNode; + function updateTupleTypeNode(node: TupleTypeNode, elementTypes: ReadonlyArray): TupleTypeNode; + function createOptionalTypeNode(type: TypeNode): OptionalTypeNode; + function updateOptionalTypeNode(node: OptionalTypeNode, type: TypeNode): OptionalTypeNode; + function createRestTypeNode(type: TypeNode): RestTypeNode; + function updateRestTypeNode(node: RestTypeNode, type: TypeNode): RestTypeNode; + function createUnionTypeNode(types: ReadonlyArray): UnionTypeNode; + function updateUnionTypeNode(node: UnionTypeNode, types: NodeArray): UnionTypeNode; + function createIntersectionTypeNode(types: ReadonlyArray): IntersectionTypeNode; + function updateIntersectionTypeNode(node: IntersectionTypeNode, types: NodeArray): IntersectionTypeNode; + function createUnionOrIntersectionTypeNode(kind: SyntaxKind.UnionType | SyntaxKind.IntersectionType, types: ReadonlyArray): UnionOrIntersectionTypeNode; + function createConditionalTypeNode(checkType: TypeNode, extendsType: TypeNode, trueType: TypeNode, falseType: TypeNode): ConditionalTypeNode; + function updateConditionalTypeNode(node: ConditionalTypeNode, checkType: TypeNode, extendsType: TypeNode, trueType: TypeNode, falseType: TypeNode): ConditionalTypeNode; + function createInferTypeNode(typeParameter: TypeParameterDeclaration): InferTypeNode; + function updateInferTypeNode(node: InferTypeNode, typeParameter: TypeParameterDeclaration): InferTypeNode; + function createImportTypeNode(argument: TypeNode, qualifier?: EntityName, typeArguments?: ReadonlyArray, isTypeOf?: boolean): ImportTypeNode; + function updateImportTypeNode(node: ImportTypeNode, argument: TypeNode, qualifier?: EntityName, typeArguments?: ReadonlyArray, isTypeOf?: boolean): ImportTypeNode; + function createParenthesizedType(type: TypeNode): ParenthesizedTypeNode; + function updateParenthesizedType(node: ParenthesizedTypeNode, type: TypeNode): ParenthesizedTypeNode; + function createThisTypeNode(): ThisTypeNode; + function createTypeOperatorNode(type: TypeNode): TypeOperatorNode; + function createTypeOperatorNode(operator: SyntaxKind.KeyOfKeyword | SyntaxKind.UniqueKeyword, type: TypeNode): TypeOperatorNode; + function updateTypeOperatorNode(node: TypeOperatorNode, type: TypeNode): TypeOperatorNode; + function createIndexedAccessTypeNode(objectType: TypeNode, indexType: TypeNode): IndexedAccessTypeNode; + function updateIndexedAccessTypeNode(node: IndexedAccessTypeNode, objectType: TypeNode, indexType: TypeNode): IndexedAccessTypeNode; + function createMappedTypeNode(readonlyToken: ReadonlyToken | PlusToken | MinusToken | undefined, typeParameter: TypeParameterDeclaration, questionToken: QuestionToken | PlusToken | MinusToken | undefined, type: TypeNode | undefined): MappedTypeNode; + function updateMappedTypeNode(node: MappedTypeNode, readonlyToken: ReadonlyToken | PlusToken | MinusToken | undefined, typeParameter: TypeParameterDeclaration, questionToken: QuestionToken | PlusToken | MinusToken | undefined, type: TypeNode | undefined): MappedTypeNode; + function createLiteralTypeNode(literal: LiteralTypeNode["literal"]): LiteralTypeNode; + function updateLiteralTypeNode(node: LiteralTypeNode, literal: LiteralTypeNode["literal"]): LiteralTypeNode; + function createObjectBindingPattern(elements: ReadonlyArray): ObjectBindingPattern; + function updateObjectBindingPattern(node: ObjectBindingPattern, elements: ReadonlyArray): ObjectBindingPattern; + function createArrayBindingPattern(elements: ReadonlyArray): ArrayBindingPattern; + function updateArrayBindingPattern(node: ArrayBindingPattern, elements: ReadonlyArray): ArrayBindingPattern; + function createBindingElement(dotDotDotToken: DotDotDotToken | undefined, propertyName: string | PropertyName | undefined, name: string | BindingName, initializer?: Expression): BindingElement; + function updateBindingElement(node: BindingElement, dotDotDotToken: DotDotDotToken | undefined, propertyName: PropertyName | undefined, name: BindingName, initializer: Expression | undefined): BindingElement; + function createArrayLiteral(elements?: ReadonlyArray, multiLine?: boolean): ArrayLiteralExpression; + function updateArrayLiteral(node: ArrayLiteralExpression, elements: ReadonlyArray): ArrayLiteralExpression; + function createObjectLiteral(properties?: ReadonlyArray, multiLine?: boolean): ObjectLiteralExpression; + function updateObjectLiteral(node: ObjectLiteralExpression, properties: ReadonlyArray): ObjectLiteralExpression; + function createPropertyAccess(expression: Expression, name: string | Identifier | undefined): PropertyAccessExpression; + function updatePropertyAccess(node: PropertyAccessExpression, expression: Expression, name: Identifier): PropertyAccessExpression; + function createElementAccess(expression: Expression, index: number | Expression): ElementAccessExpression; + function updateElementAccess(node: ElementAccessExpression, expression: Expression, argumentExpression: Expression): ElementAccessExpression; + function createCall(expression: Expression, typeArguments: ReadonlyArray | undefined, argumentsArray: ReadonlyArray | undefined): CallExpression; + function updateCall(node: CallExpression, expression: Expression, typeArguments: ReadonlyArray | undefined, argumentsArray: ReadonlyArray): CallExpression; + function createNew(expression: Expression, typeArguments: ReadonlyArray | undefined, argumentsArray: ReadonlyArray | undefined): NewExpression; + function updateNew(node: NewExpression, expression: Expression, typeArguments: ReadonlyArray | undefined, argumentsArray: ReadonlyArray | undefined): NewExpression; + /** @deprecated */ function createTaggedTemplate(tag: Expression, template: TemplateLiteral): TaggedTemplateExpression; + function createTaggedTemplate(tag: Expression, typeArguments: ReadonlyArray | undefined, template: TemplateLiteral): TaggedTemplateExpression; + /** @deprecated */ function updateTaggedTemplate(node: TaggedTemplateExpression, tag: Expression, template: TemplateLiteral): TaggedTemplateExpression; + function updateTaggedTemplate(node: TaggedTemplateExpression, tag: Expression, typeArguments: ReadonlyArray | undefined, template: TemplateLiteral): TaggedTemplateExpression; + function createTypeAssertion(type: TypeNode, expression: Expression): TypeAssertion; + function updateTypeAssertion(node: TypeAssertion, type: TypeNode, expression: Expression): TypeAssertion; + function createParen(expression: Expression): ParenthesizedExpression; + function updateParen(node: ParenthesizedExpression, expression: Expression): ParenthesizedExpression; + function createFunctionExpression(modifiers: ReadonlyArray | undefined, asteriskToken: AsteriskToken | undefined, name: string | Identifier | undefined, typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray | undefined, type: TypeNode | undefined, body: Block): FunctionExpression; + function updateFunctionExpression(node: FunctionExpression, modifiers: ReadonlyArray | undefined, asteriskToken: AsteriskToken | undefined, name: Identifier | undefined, typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode | undefined, body: Block): FunctionExpression; + function createArrowFunction(modifiers: ReadonlyArray | undefined, typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode | undefined, equalsGreaterThanToken: EqualsGreaterThanToken | undefined, body: ConciseBody): ArrowFunction; + function updateArrowFunction(node: ArrowFunction, modifiers: ReadonlyArray | undefined, typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode | undefined, equalsGreaterThanToken: Token, body: ConciseBody): ArrowFunction; + function createDelete(expression: Expression): DeleteExpression; + function updateDelete(node: DeleteExpression, expression: Expression): DeleteExpression; + function createTypeOf(expression: Expression): TypeOfExpression; + function updateTypeOf(node: TypeOfExpression, expression: Expression): TypeOfExpression; + function createVoid(expression: Expression): VoidExpression; + function updateVoid(node: VoidExpression, expression: Expression): VoidExpression; + function createAwait(expression: Expression): AwaitExpression; + function updateAwait(node: AwaitExpression, expression: Expression): AwaitExpression; + function createPrefix(operator: PrefixUnaryOperator, operand: Expression): PrefixUnaryExpression; + function updatePrefix(node: PrefixUnaryExpression, operand: Expression): PrefixUnaryExpression; + function createPostfix(operand: Expression, operator: PostfixUnaryOperator): PostfixUnaryExpression; + function updatePostfix(node: PostfixUnaryExpression, operand: Expression): PostfixUnaryExpression; + function createBinary(left: Expression, operator: BinaryOperator | BinaryOperatorToken, right: Expression): BinaryExpression; + function updateBinary(node: BinaryExpression, left: Expression, right: Expression, operator?: BinaryOperator | BinaryOperatorToken): BinaryExpression; + /** @deprecated */ function createConditional(condition: Expression, whenTrue: Expression, whenFalse: Expression): ConditionalExpression; + function createConditional(condition: Expression, questionToken: QuestionToken, whenTrue: Expression, colonToken: ColonToken, whenFalse: Expression): ConditionalExpression; + function updateConditional(node: ConditionalExpression, condition: Expression, questionToken: Token, whenTrue: Expression, colonToken: Token, whenFalse: Expression): ConditionalExpression; + function createTemplateExpression(head: TemplateHead, templateSpans: ReadonlyArray): TemplateExpression; + function updateTemplateExpression(node: TemplateExpression, head: TemplateHead, templateSpans: ReadonlyArray): TemplateExpression; + function createTemplateHead(text: string): TemplateHead; + function createTemplateMiddle(text: string): TemplateMiddle; + function createTemplateTail(text: string): TemplateTail; + function createNoSubstitutionTemplateLiteral(text: string): NoSubstitutionTemplateLiteral; + function createYield(expression?: Expression): YieldExpression; + function createYield(asteriskToken: AsteriskToken | undefined, expression: Expression): YieldExpression; + function updateYield(node: YieldExpression, asteriskToken: AsteriskToken | undefined, expression: Expression): YieldExpression; + function createSpread(expression: Expression): SpreadElement; + function updateSpread(node: SpreadElement, expression: Expression): SpreadElement; + function createClassExpression(modifiers: ReadonlyArray | undefined, name: string | Identifier | undefined, typeParameters: ReadonlyArray | undefined, heritageClauses: ReadonlyArray | undefined, members: ReadonlyArray): ClassExpression; + function updateClassExpression(node: ClassExpression, modifiers: ReadonlyArray | undefined, name: Identifier | undefined, typeParameters: ReadonlyArray | undefined, heritageClauses: ReadonlyArray | undefined, members: ReadonlyArray): ClassExpression; + function createOmittedExpression(): OmittedExpression; + function createExpressionWithTypeArguments(typeArguments: ReadonlyArray | undefined, expression: Expression): ExpressionWithTypeArguments; + function updateExpressionWithTypeArguments(node: ExpressionWithTypeArguments, typeArguments: ReadonlyArray | undefined, expression: Expression): ExpressionWithTypeArguments; + function createAsExpression(expression: Expression, type: TypeNode): AsExpression; + function updateAsExpression(node: AsExpression, expression: Expression, type: TypeNode): AsExpression; + function createNonNullExpression(expression: Expression): NonNullExpression; + function updateNonNullExpression(node: NonNullExpression, expression: Expression): NonNullExpression; + function createMetaProperty(keywordToken: MetaProperty["keywordToken"], name: Identifier): MetaProperty; + function updateMetaProperty(node: MetaProperty, name: Identifier): MetaProperty; + function createTemplateSpan(expression: Expression, literal: TemplateMiddle | TemplateTail): TemplateSpan; + function updateTemplateSpan(node: TemplateSpan, expression: Expression, literal: TemplateMiddle | TemplateTail): TemplateSpan; + function createSemicolonClassElement(): SemicolonClassElement; + function createBlock(statements: ReadonlyArray, multiLine?: boolean): Block; + function updateBlock(node: Block, statements: ReadonlyArray): Block; + function createVariableStatement(modifiers: ReadonlyArray | undefined, declarationList: VariableDeclarationList | ReadonlyArray): VariableStatement; + function updateVariableStatement(node: VariableStatement, modifiers: ReadonlyArray | undefined, declarationList: VariableDeclarationList): VariableStatement; + function createEmptyStatement(): EmptyStatement; + function createExpressionStatement(expression: Expression): ExpressionStatement; + function updateExpressionStatement(node: ExpressionStatement, expression: Expression): ExpressionStatement; + /** @deprecated Use `createExpressionStatement` instead. */ + const createStatement: typeof createExpressionStatement; + /** @deprecated Use `updateExpressionStatement` instead. */ + const updateStatement: typeof updateExpressionStatement; + function createIf(expression: Expression, thenStatement: Statement, elseStatement?: Statement): IfStatement; + function updateIf(node: IfStatement, expression: Expression, thenStatement: Statement, elseStatement: Statement | undefined): IfStatement; + function createDo(statement: Statement, expression: Expression): DoStatement; + function updateDo(node: DoStatement, statement: Statement, expression: Expression): DoStatement; + function createWhile(expression: Expression, statement: Statement): WhileStatement; + function updateWhile(node: WhileStatement, expression: Expression, statement: Statement): WhileStatement; + function createFor(initializer: ForInitializer | undefined, condition: Expression | undefined, incrementor: Expression | undefined, statement: Statement): ForStatement; + function updateFor(node: ForStatement, initializer: ForInitializer | undefined, condition: Expression | undefined, incrementor: Expression | undefined, statement: Statement): ForStatement; + function createForIn(initializer: ForInitializer, expression: Expression, statement: Statement): ForInStatement; + function updateForIn(node: ForInStatement, initializer: ForInitializer, expression: Expression, statement: Statement): ForInStatement; + function createForOf(awaitModifier: AwaitKeywordToken | undefined, initializer: ForInitializer, expression: Expression, statement: Statement): ForOfStatement; + function updateForOf(node: ForOfStatement, awaitModifier: AwaitKeywordToken | undefined, initializer: ForInitializer, expression: Expression, statement: Statement): ForOfStatement; + function createContinue(label?: string | Identifier): ContinueStatement; + function updateContinue(node: ContinueStatement, label: Identifier | undefined): ContinueStatement; + function createBreak(label?: string | Identifier): BreakStatement; + function updateBreak(node: BreakStatement, label: Identifier | undefined): BreakStatement; + function createReturn(expression?: Expression): ReturnStatement; + function updateReturn(node: ReturnStatement, expression: Expression | undefined): ReturnStatement; + function createWith(expression: Expression, statement: Statement): WithStatement; + function updateWith(node: WithStatement, expression: Expression, statement: Statement): WithStatement; + function createSwitch(expression: Expression, caseBlock: CaseBlock): SwitchStatement; + function updateSwitch(node: SwitchStatement, expression: Expression, caseBlock: CaseBlock): SwitchStatement; + function createLabel(label: string | Identifier, statement: Statement): LabeledStatement; + function updateLabel(node: LabeledStatement, label: Identifier, statement: Statement): LabeledStatement; + function createThrow(expression: Expression): ThrowStatement; + function updateThrow(node: ThrowStatement, expression: Expression): ThrowStatement; + function createTry(tryBlock: Block, catchClause: CatchClause | undefined, finallyBlock: Block | undefined): TryStatement; + function updateTry(node: TryStatement, tryBlock: Block, catchClause: CatchClause | undefined, finallyBlock: Block | undefined): TryStatement; + function createDebuggerStatement(): DebuggerStatement; + function createVariableDeclaration(name: string | BindingName, type?: TypeNode, initializer?: Expression): VariableDeclaration; + function updateVariableDeclaration(node: VariableDeclaration, name: BindingName, type: TypeNode | undefined, initializer: Expression | undefined): VariableDeclaration; + function createVariableDeclarationList(declarations: ReadonlyArray, flags?: NodeFlags): VariableDeclarationList; + function updateVariableDeclarationList(node: VariableDeclarationList, declarations: ReadonlyArray): VariableDeclarationList; + function createFunctionDeclaration(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, asteriskToken: AsteriskToken | undefined, name: string | Identifier | undefined, typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode | undefined, body: Block | undefined): FunctionDeclaration; + function updateFunctionDeclaration(node: FunctionDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, asteriskToken: AsteriskToken | undefined, name: Identifier | undefined, typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode | undefined, body: Block | undefined): FunctionDeclaration; + function createClassDeclaration(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: string | Identifier | undefined, typeParameters: ReadonlyArray | undefined, heritageClauses: ReadonlyArray | undefined, members: ReadonlyArray): ClassDeclaration; + function updateClassDeclaration(node: ClassDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: Identifier | undefined, typeParameters: ReadonlyArray | undefined, heritageClauses: ReadonlyArray | undefined, members: ReadonlyArray): ClassDeclaration; + function createInterfaceDeclaration(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: string | Identifier, typeParameters: ReadonlyArray | undefined, heritageClauses: ReadonlyArray | undefined, members: ReadonlyArray): InterfaceDeclaration; + function updateInterfaceDeclaration(node: InterfaceDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: Identifier, typeParameters: ReadonlyArray | undefined, heritageClauses: ReadonlyArray | undefined, members: ReadonlyArray): InterfaceDeclaration; + function createTypeAliasDeclaration(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: string | Identifier, typeParameters: ReadonlyArray | undefined, type: TypeNode): TypeAliasDeclaration; + function updateTypeAliasDeclaration(node: TypeAliasDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: Identifier, typeParameters: ReadonlyArray | undefined, type: TypeNode): TypeAliasDeclaration; + function createEnumDeclaration(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: string | Identifier, members: ReadonlyArray): EnumDeclaration; + function updateEnumDeclaration(node: EnumDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: Identifier, members: ReadonlyArray): EnumDeclaration; + function createModuleDeclaration(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: ModuleName, body: ModuleBody | undefined, flags?: NodeFlags): ModuleDeclaration; + function updateModuleDeclaration(node: ModuleDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: ModuleName, body: ModuleBody | undefined): ModuleDeclaration; + function createModuleBlock(statements: ReadonlyArray): ModuleBlock; + function updateModuleBlock(node: ModuleBlock, statements: ReadonlyArray): ModuleBlock; + function createCaseBlock(clauses: ReadonlyArray): CaseBlock; + function updateCaseBlock(node: CaseBlock, clauses: ReadonlyArray): CaseBlock; + function createNamespaceExportDeclaration(name: string | Identifier): NamespaceExportDeclaration; + function updateNamespaceExportDeclaration(node: NamespaceExportDeclaration, name: Identifier): NamespaceExportDeclaration; + function createImportEqualsDeclaration(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: string | Identifier, moduleReference: ModuleReference): ImportEqualsDeclaration; + function updateImportEqualsDeclaration(node: ImportEqualsDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: Identifier, moduleReference: ModuleReference): ImportEqualsDeclaration; + function createImportDeclaration(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, importClause: ImportClause | undefined, moduleSpecifier: Expression): ImportDeclaration; + function updateImportDeclaration(node: ImportDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, importClause: ImportClause | undefined, moduleSpecifier: Expression): ImportDeclaration; + function createImportClause(name: Identifier | undefined, namedBindings: NamedImportBindings | undefined): ImportClause; + function updateImportClause(node: ImportClause, name: Identifier | undefined, namedBindings: NamedImportBindings | undefined): ImportClause; + function createNamespaceImport(name: Identifier): NamespaceImport; + function updateNamespaceImport(node: NamespaceImport, name: Identifier): NamespaceImport; + function createNamedImports(elements: ReadonlyArray): NamedImports; + function updateNamedImports(node: NamedImports, elements: ReadonlyArray): NamedImports; + function createImportSpecifier(propertyName: Identifier | undefined, name: Identifier): ImportSpecifier; + function updateImportSpecifier(node: ImportSpecifier, propertyName: Identifier | undefined, name: Identifier): ImportSpecifier; + function createExportAssignment(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, isExportEquals: boolean | undefined, expression: Expression): ExportAssignment; + function updateExportAssignment(node: ExportAssignment, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, expression: Expression): ExportAssignment; + function createExportDeclaration(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, exportClause: NamedExports | undefined, moduleSpecifier?: Expression): ExportDeclaration; + function updateExportDeclaration(node: ExportDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, exportClause: NamedExports | undefined, moduleSpecifier: Expression | undefined): ExportDeclaration; + function createNamedExports(elements: ReadonlyArray): NamedExports; + function updateNamedExports(node: NamedExports, elements: ReadonlyArray): NamedExports; + function createExportSpecifier(propertyName: string | Identifier | undefined, name: string | Identifier): ExportSpecifier; + function updateExportSpecifier(node: ExportSpecifier, propertyName: Identifier | undefined, name: Identifier): ExportSpecifier; + function createExternalModuleReference(expression: Expression): ExternalModuleReference; + function updateExternalModuleReference(node: ExternalModuleReference, expression: Expression): ExternalModuleReference; + function createJsxElement(openingElement: JsxOpeningElement, children: ReadonlyArray, closingElement: JsxClosingElement): JsxElement; + function updateJsxElement(node: JsxElement, openingElement: JsxOpeningElement, children: ReadonlyArray, closingElement: JsxClosingElement): JsxElement; + function createJsxSelfClosingElement(tagName: JsxTagNameExpression, typeArguments: ReadonlyArray | undefined, attributes: JsxAttributes): JsxSelfClosingElement; + function updateJsxSelfClosingElement(node: JsxSelfClosingElement, tagName: JsxTagNameExpression, typeArguments: ReadonlyArray | undefined, attributes: JsxAttributes): JsxSelfClosingElement; + function createJsxOpeningElement(tagName: JsxTagNameExpression, typeArguments: ReadonlyArray | undefined, attributes: JsxAttributes): JsxOpeningElement; + function updateJsxOpeningElement(node: JsxOpeningElement, tagName: JsxTagNameExpression, typeArguments: ReadonlyArray | undefined, attributes: JsxAttributes): JsxOpeningElement; + function createJsxClosingElement(tagName: JsxTagNameExpression): JsxClosingElement; + function updateJsxClosingElement(node: JsxClosingElement, tagName: JsxTagNameExpression): JsxClosingElement; + function createJsxFragment(openingFragment: JsxOpeningFragment, children: ReadonlyArray, closingFragment: JsxClosingFragment): JsxFragment; + function updateJsxFragment(node: JsxFragment, openingFragment: JsxOpeningFragment, children: ReadonlyArray, closingFragment: JsxClosingFragment): JsxFragment; + function createJsxAttribute(name: Identifier, initializer: StringLiteral | JsxExpression): JsxAttribute; + function updateJsxAttribute(node: JsxAttribute, name: Identifier, initializer: StringLiteral | JsxExpression): JsxAttribute; + function createJsxAttributes(properties: ReadonlyArray): JsxAttributes; + function updateJsxAttributes(node: JsxAttributes, properties: ReadonlyArray): JsxAttributes; + function createJsxSpreadAttribute(expression: Expression): JsxSpreadAttribute; + function updateJsxSpreadAttribute(node: JsxSpreadAttribute, expression: Expression): JsxSpreadAttribute; + function createJsxExpression(dotDotDotToken: DotDotDotToken | undefined, expression: Expression | undefined): JsxExpression; + function updateJsxExpression(node: JsxExpression, expression: Expression | undefined): JsxExpression; + function createCaseClause(expression: Expression, statements: ReadonlyArray): CaseClause; + function updateCaseClause(node: CaseClause, expression: Expression, statements: ReadonlyArray): CaseClause; + function createDefaultClause(statements: ReadonlyArray): DefaultClause; + function updateDefaultClause(node: DefaultClause, statements: ReadonlyArray): DefaultClause; + function createHeritageClause(token: HeritageClause["token"], types: ReadonlyArray): HeritageClause; + function updateHeritageClause(node: HeritageClause, types: ReadonlyArray): HeritageClause; + function createCatchClause(variableDeclaration: string | VariableDeclaration | undefined, block: Block): CatchClause; + function updateCatchClause(node: CatchClause, variableDeclaration: VariableDeclaration | undefined, block: Block): CatchClause; + function createPropertyAssignment(name: string | PropertyName, initializer: Expression): PropertyAssignment; + function updatePropertyAssignment(node: PropertyAssignment, name: PropertyName, initializer: Expression): PropertyAssignment; + function createShorthandPropertyAssignment(name: string | Identifier, objectAssignmentInitializer?: Expression): ShorthandPropertyAssignment; + function updateShorthandPropertyAssignment(node: ShorthandPropertyAssignment, name: Identifier, objectAssignmentInitializer: Expression | undefined): ShorthandPropertyAssignment; + function createSpreadAssignment(expression: Expression): SpreadAssignment; + function updateSpreadAssignment(node: SpreadAssignment, expression: Expression): SpreadAssignment; + function createEnumMember(name: string | PropertyName, initializer?: Expression): EnumMember; + function updateEnumMember(node: EnumMember, name: PropertyName, initializer: Expression | undefined): EnumMember; + function updateSourceFileNode(node: SourceFile, statements: ReadonlyArray, isDeclarationFile?: boolean, referencedFiles?: SourceFile["referencedFiles"], typeReferences?: SourceFile["typeReferenceDirectives"], hasNoDefaultLib?: boolean, libReferences?: SourceFile["libReferenceDirectives"]): SourceFile; + /** + * Creates a shallow, memberwise clone of a node for mutation. + */ + function getMutableClone(node: T): T; + /** + * Creates a synthetic statement to act as a placeholder for a not-emitted statement in + * order to preserve comments. + * + * @param original The original statement. + */ + function createNotEmittedStatement(original: Node): NotEmittedStatement; + /** + * Creates a synthetic expression to act as a placeholder for a not-emitted expression in + * order to preserve comments or sourcemap positions. + * + * @param expression The inner expression to emit. + * @param original The original outer expression. + * @param location The location for the expression. Defaults to the positions from "original" if provided. + */ + function createPartiallyEmittedExpression(expression: Expression, original?: Node): PartiallyEmittedExpression; + function updatePartiallyEmittedExpression(node: PartiallyEmittedExpression, expression: Expression): PartiallyEmittedExpression; + function createCommaList(elements: ReadonlyArray): CommaListExpression; + function updateCommaList(node: CommaListExpression, elements: ReadonlyArray): CommaListExpression; + function createBundle(sourceFiles: ReadonlyArray, prepends?: ReadonlyArray): Bundle; + function createUnparsedSourceFile(text: string): UnparsedSource; + function createUnparsedSourceFile(text: string, mapPath: string | undefined, map: string | undefined): UnparsedSource; + function createInputFiles(javascript: string, declaration: string): InputFiles; + function createInputFiles(javascript: string, declaration: string, javascriptMapPath: string | undefined, javascriptMapText: string | undefined, declarationMapPath: string | undefined, declarationMapText: string | undefined): InputFiles; + function updateBundle(node: Bundle, sourceFiles: ReadonlyArray, prepends?: ReadonlyArray): Bundle; + function createImmediatelyInvokedFunctionExpression(statements: ReadonlyArray): CallExpression; + function createImmediatelyInvokedFunctionExpression(statements: ReadonlyArray, param: ParameterDeclaration, paramValue: Expression): CallExpression; + function createImmediatelyInvokedArrowFunction(statements: ReadonlyArray): CallExpression; + function createImmediatelyInvokedArrowFunction(statements: ReadonlyArray, param: ParameterDeclaration, paramValue: Expression): CallExpression; + function createComma(left: Expression, right: Expression): Expression; + function createLessThan(left: Expression, right: Expression): Expression; + function createAssignment(left: ObjectLiteralExpression | ArrayLiteralExpression, right: Expression): DestructuringAssignment; + function createAssignment(left: Expression, right: Expression): BinaryExpression; + function createStrictEquality(left: Expression, right: Expression): BinaryExpression; + function createStrictInequality(left: Expression, right: Expression): BinaryExpression; + function createAdd(left: Expression, right: Expression): BinaryExpression; + function createSubtract(left: Expression, right: Expression): BinaryExpression; + function createPostfixIncrement(operand: Expression): PostfixUnaryExpression; + function createLogicalAnd(left: Expression, right: Expression): BinaryExpression; + function createLogicalOr(left: Expression, right: Expression): BinaryExpression; + function createLogicalNot(operand: Expression): PrefixUnaryExpression; + function createVoidZero(): VoidExpression; + function createExportDefault(expression: Expression): ExportAssignment; + function createExternalModuleExport(exportName: Identifier): ExportDeclaration; + /** + * Clears any EmitNode entries from parse-tree nodes. + * @param sourceFile A source file. + */ + function disposeEmitNodes(sourceFile: SourceFile): void; + function setTextRange(range: T, location: TextRange | undefined): T; + /** + * Sets flags that control emit behavior of a node. + */ + function setEmitFlags(node: T, emitFlags: EmitFlags): T; + /** + * Gets a custom text range to use when emitting source maps. + */ + function getSourceMapRange(node: Node): SourceMapRange; + /** + * Sets a custom text range to use when emitting source maps. + */ + function setSourceMapRange(node: T, range: SourceMapRange | undefined): T; + /** + * Create an external source map source file reference + */ + function createSourceMapSource(fileName: string, text: string, skipTrivia?: (pos: number) => number): SourceMapSource; + /** + * Gets the TextRange to use for source maps for a token of a node. + */ + function getTokenSourceMapRange(node: Node, token: SyntaxKind): SourceMapRange | undefined; + /** + * Sets the TextRange to use for source maps for a token of a node. + */ + function setTokenSourceMapRange(node: T, token: SyntaxKind, range: SourceMapRange | undefined): T; + /** + * Gets a custom text range to use when emitting comments. + */ + function getCommentRange(node: Node): TextRange; + /** + * Sets a custom text range to use when emitting comments. + */ + function setCommentRange(node: T, range: TextRange): T; + function getSyntheticLeadingComments(node: Node): SynthesizedComment[] | undefined; + function setSyntheticLeadingComments(node: T, comments: SynthesizedComment[] | undefined): T; + function addSyntheticLeadingComment(node: T, kind: SyntaxKind.SingleLineCommentTrivia | SyntaxKind.MultiLineCommentTrivia, text: string, hasTrailingNewLine?: boolean): T; + function getSyntheticTrailingComments(node: Node): SynthesizedComment[] | undefined; + function setSyntheticTrailingComments(node: T, comments: SynthesizedComment[] | undefined): T; + function addSyntheticTrailingComment(node: T, kind: SyntaxKind.SingleLineCommentTrivia | SyntaxKind.MultiLineCommentTrivia, text: string, hasTrailingNewLine?: boolean): T; + function moveSyntheticComments(node: T, original: Node): T; + /** + * Gets the constant value to emit for an expression. + */ + function getConstantValue(node: PropertyAccessExpression | ElementAccessExpression): string | number | undefined; + /** + * Sets the constant value to emit for an expression. + */ + function setConstantValue(node: PropertyAccessExpression | ElementAccessExpression, value: string | number): PropertyAccessExpression | ElementAccessExpression; + /** + * Adds an EmitHelper to a node. + */ + function addEmitHelper(node: T, helper: EmitHelper): T; + /** + * Add EmitHelpers to a node. + */ + function addEmitHelpers(node: T, helpers: EmitHelper[] | undefined): T; + /** + * Removes an EmitHelper from a node. + */ + function removeEmitHelper(node: Node, helper: EmitHelper): boolean; + /** + * Gets the EmitHelpers of a node. + */ + function getEmitHelpers(node: Node): EmitHelper[] | undefined; + /** + * Moves matching emit helpers from a source node to a target node. + */ + function moveEmitHelpers(source: Node, target: Node, predicate: (helper: EmitHelper) => boolean): void; + function setOriginalNode(node: T, original: Node | undefined): T; +} +declare namespace ts { + /** + * Visits a Node using the supplied visitor, possibly returning a new Node in its place. + * + * @param node The Node to visit. + * @param visitor The callback used to visit the Node. + * @param test A callback to execute to verify the Node is valid. + * @param lift An optional callback to execute to lift a NodeArray into a valid Node. + */ + function visitNode(node: T | undefined, visitor: Visitor | undefined, test?: (node: Node) => boolean, lift?: (node: NodeArray) => T): T; + /** + * Visits a Node using the supplied visitor, possibly returning a new Node in its place. + * + * @param node The Node to visit. + * @param visitor The callback used to visit the Node. + * @param test A callback to execute to verify the Node is valid. + * @param lift An optional callback to execute to lift a NodeArray into a valid Node. + */ + function visitNode(node: T | undefined, visitor: Visitor | undefined, test?: (node: Node) => boolean, lift?: (node: NodeArray) => T): T | undefined; + /** + * Visits a NodeArray using the supplied visitor, possibly returning a new NodeArray in its place. + * + * @param nodes The NodeArray to visit. + * @param visitor The callback used to visit a Node. + * @param test A node test to execute for each node. + * @param start An optional value indicating the starting offset at which to start visiting. + * @param count An optional value indicating the maximum number of nodes to visit. + */ + function visitNodes(nodes: NodeArray | undefined, visitor: Visitor, test?: (node: Node) => boolean, start?: number, count?: number): NodeArray; + /** + * Visits a NodeArray using the supplied visitor, possibly returning a new NodeArray in its place. + * + * @param nodes The NodeArray to visit. + * @param visitor The callback used to visit a Node. + * @param test A node test to execute for each node. + * @param start An optional value indicating the starting offset at which to start visiting. + * @param count An optional value indicating the maximum number of nodes to visit. + */ + function visitNodes(nodes: NodeArray | undefined, visitor: Visitor, test?: (node: Node) => boolean, start?: number, count?: number): NodeArray | undefined; + /** + * Starts a new lexical environment and visits a statement list, ending the lexical environment + * and merging hoisted declarations upon completion. + */ + function visitLexicalEnvironment(statements: NodeArray, visitor: Visitor, context: TransformationContext, start?: number, ensureUseStrict?: boolean): NodeArray; + /** + * Starts a new lexical environment and visits a parameter list, suspending the lexical + * environment upon completion. + */ + function visitParameterList(nodes: NodeArray | undefined, visitor: Visitor, context: TransformationContext, nodesVisitor?: typeof visitNodes): NodeArray; + /** + * Resumes a suspended lexical environment and visits a function body, ending the lexical + * environment and merging hoisted declarations upon completion. + */ + function visitFunctionBody(node: FunctionBody, visitor: Visitor, context: TransformationContext): FunctionBody; + /** + * Resumes a suspended lexical environment and visits a function body, ending the lexical + * environment and merging hoisted declarations upon completion. + */ + function visitFunctionBody(node: FunctionBody | undefined, visitor: Visitor, context: TransformationContext): FunctionBody | undefined; + /** + * Resumes a suspended lexical environment and visits a concise body, ending the lexical + * environment and merging hoisted declarations upon completion. + */ + function visitFunctionBody(node: ConciseBody, visitor: Visitor, context: TransformationContext): ConciseBody; + /** + * Visits each child of a Node using the supplied visitor, possibly returning a new Node of the same kind in its place. + * + * @param node The Node whose children will be visited. + * @param visitor The callback used to visit each child. + * @param context A lexical environment context for the visitor. + */ + function visitEachChild(node: T, visitor: Visitor, context: TransformationContext): T; + /** + * Visits each child of a Node using the supplied visitor, possibly returning a new Node of the same kind in its place. + * + * @param node The Node whose children will be visited. + * @param visitor The callback used to visit each child. + * @param context A lexical environment context for the visitor. + */ + function visitEachChild(node: T | undefined, visitor: Visitor, context: TransformationContext, nodesVisitor?: typeof visitNodes, tokenVisitor?: Visitor): T | undefined; +} +declare namespace ts { + function createPrinter(printerOptions?: PrinterOptions, handlers?: PrintHandlers): Printer; +} +declare namespace ts { + function findConfigFile(searchPath: string, fileExists: (fileName: string) => boolean, configName?: string): string | undefined; + function resolveTripleslashReference(moduleName: string, containingFile: string): string; + function createCompilerHost(options: CompilerOptions, setParentNodes?: boolean): CompilerHost; + function getPreEmitDiagnostics(program: Program, sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray; + interface FormatDiagnosticsHost { + getCurrentDirectory(): string; + getCanonicalFileName(fileName: string): string; + getNewLine(): string; + } + function formatDiagnostics(diagnostics: ReadonlyArray, host: FormatDiagnosticsHost): string; + function formatDiagnostic(diagnostic: Diagnostic, host: FormatDiagnosticsHost): string; + function formatDiagnosticsWithColorAndContext(diagnostics: ReadonlyArray, host: FormatDiagnosticsHost): string; + function flattenDiagnosticMessageText(messageText: string | DiagnosticMessageChain | undefined, newLine: string): string; + function getConfigFileParsingDiagnostics(configFileParseResult: ParsedCommandLine): ReadonlyArray; + /** + * Create a new 'Program' instance. A Program is an immutable collection of 'SourceFile's and a 'CompilerOptions' + * that represent a compilation unit. + * + * Creating a program proceeds from a set of root files, expanding the set of inputs by following imports and + * triple-slash-reference-path directives transitively. '@types' and triple-slash-reference-types are also pulled in. + * + * @param createProgramOptions - The options for creating a program. + * @returns A 'Program' object. + */ + function createProgram(createProgramOptions: CreateProgramOptions): Program; + /** + * Create a new 'Program' instance. A Program is an immutable collection of 'SourceFile's and a 'CompilerOptions' + * that represent a compilation unit. + * + * Creating a program proceeds from a set of root files, expanding the set of inputs by following imports and + * triple-slash-reference-path directives transitively. '@types' and triple-slash-reference-types are also pulled in. + * + * @param rootNames - A set of root files. + * @param options - The compiler options which should be used. + * @param host - The host interacts with the underlying file system. + * @param oldProgram - Reuses an old program structure. + * @param configFileParsingDiagnostics - error during config file parsing + * @returns A 'Program' object. + */ + function createProgram(rootNames: ReadonlyArray, options: CompilerOptions, host?: CompilerHost, oldProgram?: Program, configFileParsingDiagnostics?: ReadonlyArray): Program; + /** @deprecated */ interface ResolveProjectReferencePathHost { + fileExists(fileName: string): boolean; + } + /** + * Returns the target config filename of a project reference. + * Note: The file might not exist. + */ + function resolveProjectReferencePath(ref: ProjectReference): ResolvedConfigFileName; + /** @deprecated */ function resolveProjectReferencePath(host: ResolveProjectReferencePathHost, ref: ProjectReference): ResolvedConfigFileName; +} +declare namespace ts { + interface EmitOutput { + outputFiles: OutputFile[]; + emitSkipped: boolean; + } + interface OutputFile { + name: string; + writeByteOrderMark: boolean; + text: string; + } +} +declare namespace ts { + type AffectedFileResult = { + result: T; + affected: SourceFile | Program; + } | undefined; + interface BuilderProgramHost { + /** + * return true if file names are treated with case sensitivity + */ + useCaseSensitiveFileNames(): boolean; + /** + * If provided this would be used this hash instead of actual file shape text for detecting changes + */ + createHash?: (data: string) => string; + /** + * When emit or emitNextAffectedFile are called without writeFile, + * this callback if present would be used to write files + */ + writeFile?: WriteFileCallback; + } + /** + * Builder to manage the program state changes + */ + interface BuilderProgram { + /** + * Returns current program + */ + getProgram(): Program; + /** + * Get compiler options of the program + */ + getCompilerOptions(): CompilerOptions; + /** + * Get the source file in the program with file name + */ + getSourceFile(fileName: string): SourceFile | undefined; + /** + * Get a list of files in the program + */ + getSourceFiles(): ReadonlyArray; + /** + * Get the diagnostics for compiler options + */ + getOptionsDiagnostics(cancellationToken?: CancellationToken): ReadonlyArray; + /** + * Get the diagnostics that dont belong to any file + */ + getGlobalDiagnostics(cancellationToken?: CancellationToken): ReadonlyArray; + /** + * Get the diagnostics from config file parsing + */ + getConfigFileParsingDiagnostics(): ReadonlyArray; + /** + * Get the syntax diagnostics, for all source files if source file is not supplied + */ + getSyntacticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray; + /** + * Get all the dependencies of the file + */ + getAllDependencies(sourceFile: SourceFile): ReadonlyArray; + /** + * Gets the semantic diagnostics from the program corresponding to this state of file (if provided) or whole program + * The semantic diagnostics are cached and managed here + * Note that it is assumed that when asked about semantic diagnostics through this API, + * the file has been taken out of affected files so it is safe to use cache or get from program and cache the diagnostics + * In case of SemanticDiagnosticsBuilderProgram if the source file is not provided, + * it will iterate through all the affected files, to ensure that cache stays valid and yet provide a way to get all semantic diagnostics + */ + getSemanticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray; + /** + * Emits the JavaScript and declaration files. + * When targetSource file is specified, emits the files corresponding to that source file, + * otherwise for the whole program. + * In case of EmitAndSemanticDiagnosticsBuilderProgram, when targetSourceFile is specified, + * it is assumed that that file is handled from affected file list. If targetSourceFile is not specified, + * it will only emit all the affected files instead of whole program + * + * The first of writeFile if provided, writeFile of BuilderProgramHost if provided, writeFile of compiler host + * in that order would be used to write the files + */ + emit(targetSourceFile?: SourceFile, writeFile?: WriteFileCallback, cancellationToken?: CancellationToken, emitOnlyDtsFiles?: boolean, customTransformers?: CustomTransformers): EmitResult; + /** + * Get the current directory of the program + */ + getCurrentDirectory(): string; + } + /** + * The builder that caches the semantic diagnostics for the program and handles the changed files and affected files + */ + interface SemanticDiagnosticsBuilderProgram extends BuilderProgram { + /** + * Gets the semantic diagnostics from the program for the next affected file and caches it + * Returns undefined if the iteration is complete + */ + getSemanticDiagnosticsOfNextAffectedFile(cancellationToken?: CancellationToken, ignoreSourceFile?: (sourceFile: SourceFile) => boolean): AffectedFileResult>; + } + /** + * The builder that can handle the changes in program and iterate through changed file to emit the files + * The semantic diagnostics are cached per file and managed by clearing for the changed/affected files + */ + interface EmitAndSemanticDiagnosticsBuilderProgram extends BuilderProgram { + /** + * Emits the next affected file's emit result (EmitResult and sourceFiles emitted) or returns undefined if iteration is complete + * The first of writeFile if provided, writeFile of BuilderProgramHost if provided, writeFile of compiler host + * in that order would be used to write the files + */ + emitNextAffectedFile(writeFile?: WriteFileCallback, cancellationToken?: CancellationToken, emitOnlyDtsFiles?: boolean, customTransformers?: CustomTransformers): AffectedFileResult; + } + /** + * Create the builder to manage semantic diagnostics and cache them + */ + function createSemanticDiagnosticsBuilderProgram(newProgram: Program, host: BuilderProgramHost, oldProgram?: SemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): SemanticDiagnosticsBuilderProgram; + function createSemanticDiagnosticsBuilderProgram(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: SemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray, projectReferences?: ReadonlyArray): SemanticDiagnosticsBuilderProgram; + /** + * Create the builder that can handle the changes in program and iterate through changed files + * to emit the those files and manage semantic diagnostics cache as well + */ + function createEmitAndSemanticDiagnosticsBuilderProgram(newProgram: Program, host: BuilderProgramHost, oldProgram?: EmitAndSemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): EmitAndSemanticDiagnosticsBuilderProgram; + function createEmitAndSemanticDiagnosticsBuilderProgram(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: EmitAndSemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray, projectReferences?: ReadonlyArray): EmitAndSemanticDiagnosticsBuilderProgram; + /** + * Creates a builder thats just abstraction over program and can be used with watch + */ + function createAbstractBuilder(newProgram: Program, host: BuilderProgramHost, oldProgram?: BuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): BuilderProgram; + function createAbstractBuilder(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: BuilderProgram, configFileParsingDiagnostics?: ReadonlyArray, projectReferences?: ReadonlyArray): BuilderProgram; +} +declare namespace ts { + type WatchStatusReporter = (diagnostic: Diagnostic, newLine: string, options: CompilerOptions) => void; + /** Create the program with rootNames and options, if they are undefined, oldProgram and new configFile diagnostics create new program */ + type CreateProgram = (rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: T, configFileParsingDiagnostics?: ReadonlyArray, projectReferences?: ReadonlyArray | undefined) => T; + /** Host that has watch functionality used in --watch mode */ + interface WatchHost { + /** If provided, called with Diagnostic message that informs about change in watch status */ + onWatchStatusChange?(diagnostic: Diagnostic, newLine: string, options: CompilerOptions): void; + /** Used to watch changes in source files, missing files needed to update the program or config file */ + watchFile(path: string, callback: FileWatcherCallback, pollingInterval?: number): FileWatcher; + /** Used to watch resolved module's failed lookup locations, config file specs, type roots where auto type reference directives are added */ + watchDirectory(path: string, callback: DirectoryWatcherCallback, recursive?: boolean): FileWatcher; + /** If provided, will be used to set delayed compilation, so that multiple changes in short span are compiled together */ + setTimeout?(callback: (...args: any[]) => void, ms: number, ...args: any[]): any; + /** If provided, will be used to reset existing delayed compilation */ + clearTimeout?(timeoutId: any): void; + } + interface WatchCompilerHost extends WatchHost { + /** + * Used to create the program when need for program creation or recreation detected + */ + createProgram: CreateProgram; + /** If provided, callback to invoke after every new program creation */ + afterProgramCreate?(program: T): void; + useCaseSensitiveFileNames(): boolean; + getNewLine(): string; + getCurrentDirectory(): string; + getDefaultLibFileName(options: CompilerOptions): string; + getDefaultLibLocation?(): string; + createHash?(data: string): string; + /** + * Use to check file presence for source files and + * if resolveModuleNames is not provided (complier is in charge of module resolution) then module files as well + */ + fileExists(path: string): boolean; + /** + * Use to read file text for source files and + * if resolveModuleNames is not provided (complier is in charge of module resolution) then module files as well + */ + readFile(path: string, encoding?: string): string | undefined; + /** If provided, used for module resolution as well as to handle directory structure */ + directoryExists?(path: string): boolean; + /** If provided, used in resolutions as well as handling directory structure */ + getDirectories?(path: string): string[]; + /** If provided, used to cache and handle directory structure modifications */ + readDirectory?(path: string, extensions?: ReadonlyArray, exclude?: ReadonlyArray, include?: ReadonlyArray, depth?: number): string[]; + /** Symbol links resolution */ + realpath?(path: string): string; + /** If provided would be used to write log about compilation */ + trace?(s: string): void; + /** If provided is used to get the environment variable */ + getEnvironmentVariable?(name: string): string | undefined; + /** If provided, used to resolve the module names, otherwise typescript's default module resolution */ + resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[], redirectedReference?: ResolvedProjectReference): (ResolvedModule | undefined)[]; + /** If provided, used to resolve type reference directives, otherwise typescript's default resolution */ + resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string, redirectedReference?: ResolvedProjectReference): (ResolvedTypeReferenceDirective | undefined)[]; + } + /** + * Host to create watch with root files and options + */ + interface WatchCompilerHostOfFilesAndCompilerOptions extends WatchCompilerHost { + /** root files to use to generate program */ + rootFiles: string[]; + /** Compiler options */ + options: CompilerOptions; + /** Project References */ + projectReferences?: ReadonlyArray; + } + /** + * Host to create watch with config file + */ + interface WatchCompilerHostOfConfigFile extends WatchCompilerHost, ConfigFileDiagnosticsReporter { + /** Name of the config file to compile */ + configFileName: string; + /** Options to extend */ + optionsToExtend?: CompilerOptions; + /** + * Used to generate source file names from the config file and its include, exclude, files rules + * and also to cache the directory stucture + */ + readDirectory(path: string, extensions?: ReadonlyArray, exclude?: ReadonlyArray, include?: ReadonlyArray, depth?: number): string[]; + } + interface Watch { + /** Synchronize with host and get updated program */ + getProgram(): T; + } + /** + * Creates the watch what generates program using the config file + */ + interface WatchOfConfigFile extends Watch { + } + /** + * Creates the watch that generates program using the root files and compiler options + */ + interface WatchOfFilesAndCompilerOptions extends Watch { + /** Updates the root files in the program, only if this is not config file compilation */ + updateRootFileNames(fileNames: string[]): void; + } + /** + * Create the watch compiler host for either configFile or fileNames and its options + */ + function createWatchCompilerHost(configFileName: string, optionsToExtend: CompilerOptions | undefined, system: System, createProgram?: CreateProgram, reportDiagnostic?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter): WatchCompilerHostOfConfigFile; + function createWatchCompilerHost(rootFiles: string[], options: CompilerOptions, system: System, createProgram?: CreateProgram, reportDiagnostic?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter, projectReferences?: ReadonlyArray): WatchCompilerHostOfFilesAndCompilerOptions; + /** + * Creates the watch from the host for root files and compiler options + */ + function createWatchProgram(host: WatchCompilerHostOfFilesAndCompilerOptions): WatchOfFilesAndCompilerOptions; + /** + * Creates the watch from the host for config file + */ + function createWatchProgram(host: WatchCompilerHostOfConfigFile): WatchOfConfigFile; +} +declare namespace ts.server { + type ActionSet = "action::set"; + type ActionInvalidate = "action::invalidate"; + type ActionPackageInstalled = "action::packageInstalled"; + type ActionValueInspected = "action::valueInspected"; + type EventTypesRegistry = "event::typesRegistry"; + type EventBeginInstallTypes = "event::beginInstallTypes"; + type EventEndInstallTypes = "event::endInstallTypes"; + type EventInitializationFailed = "event::initializationFailed"; + interface TypingInstallerResponse { + readonly kind: ActionSet | ActionInvalidate | EventTypesRegistry | ActionPackageInstalled | ActionValueInspected | EventBeginInstallTypes | EventEndInstallTypes | EventInitializationFailed; + } + interface TypingInstallerRequestWithProjectName { + readonly projectName: string; + } + interface DiscoverTypings extends TypingInstallerRequestWithProjectName { + readonly fileNames: string[]; + readonly projectRootPath: Path; + readonly compilerOptions: CompilerOptions; + readonly typeAcquisition: TypeAcquisition; + readonly unresolvedImports: SortedReadonlyArray; + readonly cachePath?: string; + readonly kind: "discover"; + } + interface CloseProject extends TypingInstallerRequestWithProjectName { + readonly kind: "closeProject"; + } + interface TypesRegistryRequest { + readonly kind: "typesRegistry"; + } + interface InstallPackageRequest extends TypingInstallerRequestWithProjectName { + readonly kind: "installPackage"; + readonly fileName: Path; + readonly packageName: string; + readonly projectRootPath: Path; + } + interface PackageInstalledResponse extends ProjectResponse { + readonly kind: ActionPackageInstalled; + readonly success: boolean; + readonly message: string; + } + interface InitializationFailedResponse extends TypingInstallerResponse { + readonly kind: EventInitializationFailed; + readonly message: string; + } + interface ProjectResponse extends TypingInstallerResponse { + readonly projectName: string; + } + interface InvalidateCachedTypings extends ProjectResponse { + readonly kind: ActionInvalidate; + } + interface InstallTypes extends ProjectResponse { + readonly kind: EventBeginInstallTypes | EventEndInstallTypes; + readonly eventId: number; + readonly typingsInstallerVersion: string; + readonly packagesToInstall: ReadonlyArray; + } + interface BeginInstallTypes extends InstallTypes { + readonly kind: EventBeginInstallTypes; + } + interface EndInstallTypes extends InstallTypes { + readonly kind: EventEndInstallTypes; + readonly installSuccess: boolean; + } + interface SetTypings extends ProjectResponse { + readonly typeAcquisition: TypeAcquisition; + readonly compilerOptions: CompilerOptions; + readonly typings: string[]; + readonly unresolvedImports: SortedReadonlyArray; + readonly kind: ActionSet; + } +} +declare namespace ts { + interface Node { + getSourceFile(): SourceFile; + getChildCount(sourceFile?: SourceFile): number; + getChildAt(index: number, sourceFile?: SourceFile): Node; + getChildren(sourceFile?: SourceFile): Node[]; + getStart(sourceFile?: SourceFile, includeJsDocComment?: boolean): number; + getFullStart(): number; + getEnd(): number; + getWidth(sourceFile?: SourceFileLike): number; + getFullWidth(): number; + getLeadingTriviaWidth(sourceFile?: SourceFile): number; + getFullText(sourceFile?: SourceFile): string; + getText(sourceFile?: SourceFile): string; + getFirstToken(sourceFile?: SourceFile): Node | undefined; + getLastToken(sourceFile?: SourceFile): Node | undefined; + forEachChild(cbNode: (node: Node) => T | undefined, cbNodeArray?: (nodes: NodeArray) => T | undefined): T | undefined; + } + interface Identifier { + readonly text: string; + } + interface Symbol { + readonly name: string; + getFlags(): SymbolFlags; + getEscapedName(): __String; + getName(): string; + getDeclarations(): Declaration[] | undefined; + getDocumentationComment(typeChecker: TypeChecker | undefined): SymbolDisplayPart[]; + getJsDocTags(): JSDocTagInfo[]; + } + interface Type { + getFlags(): TypeFlags; + getSymbol(): Symbol | undefined; + getProperties(): Symbol[]; + getProperty(propertyName: string): Symbol | undefined; + getApparentProperties(): Symbol[]; + getCallSignatures(): ReadonlyArray; + getConstructSignatures(): ReadonlyArray; + getStringIndexType(): Type | undefined; + getNumberIndexType(): Type | undefined; + getBaseTypes(): BaseType[] | undefined; + getNonNullableType(): Type; + getConstraint(): Type | undefined; + getDefault(): Type | undefined; + isUnion(): this is UnionType; + isIntersection(): this is IntersectionType; + isUnionOrIntersection(): this is UnionOrIntersectionType; + isLiteral(): this is LiteralType; + isStringLiteral(): this is StringLiteralType; + isNumberLiteral(): this is NumberLiteralType; + isTypeParameter(): this is TypeParameter; + isClassOrInterface(): this is InterfaceType; + isClass(): this is InterfaceType; + } + interface Signature { + getDeclaration(): SignatureDeclaration; + getTypeParameters(): TypeParameter[] | undefined; + getParameters(): Symbol[]; + getReturnType(): Type; + getDocumentationComment(typeChecker: TypeChecker | undefined): SymbolDisplayPart[]; + getJsDocTags(): JSDocTagInfo[]; + } + interface SourceFile { + getLineAndCharacterOfPosition(pos: number): LineAndCharacter; + getLineEndOfPosition(pos: number): number; + getLineStarts(): ReadonlyArray; + getPositionOfLineAndCharacter(line: number, character: number): number; + update(newText: string, textChangeRange: TextChangeRange): SourceFile; + } + interface SourceFileLike { + getLineAndCharacterOfPosition(pos: number): LineAndCharacter; + } + interface SourceMapSource { + getLineAndCharacterOfPosition(pos: number): LineAndCharacter; + } + /** + * Represents an immutable snapshot of a script at a specified time.Once acquired, the + * snapshot is observably immutable. i.e. the same calls with the same parameters will return + * the same values. + */ + interface IScriptSnapshot { + /** Gets a portion of the script snapshot specified by [start, end). */ + getText(start: number, end: number): string; + /** Gets the length of this script snapshot. */ + getLength(): number; + /** + * Gets the TextChangeRange that describe how the text changed between this text and + * an older version. This information is used by the incremental parser to determine + * what sections of the script need to be re-parsed. 'undefined' can be returned if the + * change range cannot be determined. However, in that case, incremental parsing will + * not happen and the entire document will be re - parsed. + */ + getChangeRange(oldSnapshot: IScriptSnapshot): TextChangeRange | undefined; + /** Releases all resources held by this script snapshot */ + dispose?(): void; + } + namespace ScriptSnapshot { + function fromString(text: string): IScriptSnapshot; + } + interface PreProcessedFileInfo { + referencedFiles: FileReference[]; + typeReferenceDirectives: FileReference[]; + libReferenceDirectives: FileReference[]; + importedFiles: FileReference[]; + ambientExternalModules?: string[]; + isLibFile: boolean; + } + interface HostCancellationToken { + isCancellationRequested(): boolean; + } + interface InstallPackageOptions { + fileName: Path; + packageName: string; + } + interface LanguageServiceHost extends GetEffectiveTypeRootsHost { + getCompilationSettings(): CompilerOptions; + getNewLine?(): string; + getProjectVersion?(): string; + getScriptFileNames(): string[]; + getScriptKind?(fileName: string): ScriptKind; + getScriptVersion(fileName: string): string; + getScriptSnapshot(fileName: string): IScriptSnapshot | undefined; + getProjectReferences?(): ReadonlyArray | undefined; + getLocalizedDiagnosticMessages?(): any; + getCancellationToken?(): HostCancellationToken; + getCurrentDirectory(): string; + getDefaultLibFileName(options: CompilerOptions): string; + log?(s: string): void; + trace?(s: string): void; + error?(s: string): void; + useCaseSensitiveFileNames?(): boolean; + readDirectory?(path: string, extensions?: ReadonlyArray, exclude?: ReadonlyArray, include?: ReadonlyArray, depth?: number): string[]; + readFile?(path: string, encoding?: string): string | undefined; + realpath?(path: string): string; + fileExists?(path: string): boolean; + getTypeRootsVersion?(): number; + resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[], redirectedReference?: ResolvedProjectReference): (ResolvedModule | undefined)[]; + getResolvedModuleWithFailedLookupLocationsFromCache?(modulename: string, containingFile: string): ResolvedModuleWithFailedLookupLocations | undefined; + resolveTypeReferenceDirectives?(typeDirectiveNames: string[], containingFile: string, redirectedReference?: ResolvedProjectReference): (ResolvedTypeReferenceDirective | undefined)[]; + getDirectories?(directoryName: string): string[]; + /** + * Gets a set of custom transformers to use during emit. + */ + getCustomTransformers?(): CustomTransformers | undefined; + isKnownTypesPackageName?(name: string): boolean; + installPackage?(options: InstallPackageOptions): Promise; + writeFile?(fileName: string, content: string): void; + } + type WithMetadata = T & { + metadata?: unknown; + }; + interface LanguageService { + cleanupSemanticCache(): void; + getSyntacticDiagnostics(fileName: string): DiagnosticWithLocation[]; + /** The first time this is called, it will return global diagnostics (no location). */ + getSemanticDiagnostics(fileName: string): Diagnostic[]; + getSuggestionDiagnostics(fileName: string): DiagnosticWithLocation[]; + getCompilerOptionsDiagnostics(): Diagnostic[]; + /** + * @deprecated Use getEncodedSyntacticClassifications instead. + */ + getSyntacticClassifications(fileName: string, span: TextSpan): ClassifiedSpan[]; + /** + * @deprecated Use getEncodedSemanticClassifications instead. + */ + getSemanticClassifications(fileName: string, span: TextSpan): ClassifiedSpan[]; + getEncodedSyntacticClassifications(fileName: string, span: TextSpan): Classifications; + getEncodedSemanticClassifications(fileName: string, span: TextSpan): Classifications; + getCompletionsAtPosition(fileName: string, position: number, options: GetCompletionsAtPositionOptions | undefined): WithMetadata | undefined; + getCompletionEntryDetails(fileName: string, position: number, name: string, formatOptions: FormatCodeOptions | FormatCodeSettings | undefined, source: string | undefined, preferences: UserPreferences | undefined): CompletionEntryDetails | undefined; + getCompletionEntrySymbol(fileName: string, position: number, name: string, source: string | undefined): Symbol | undefined; + getQuickInfoAtPosition(fileName: string, position: number): QuickInfo | undefined; + getNameOrDottedNameSpan(fileName: string, startPos: number, endPos: number): TextSpan | undefined; + getBreakpointStatementAtPosition(fileName: string, position: number): TextSpan | undefined; + getSignatureHelpItems(fileName: string, position: number, options: SignatureHelpItemsOptions | undefined): SignatureHelpItems | undefined; + getRenameInfo(fileName: string, position: number): RenameInfo; + findRenameLocations(fileName: string, position: number, findInStrings: boolean, findInComments: boolean): ReadonlyArray | undefined; + getDefinitionAtPosition(fileName: string, position: number): ReadonlyArray | undefined; + getDefinitionAndBoundSpan(fileName: string, position: number): DefinitionInfoAndBoundSpan | undefined; + getTypeDefinitionAtPosition(fileName: string, position: number): ReadonlyArray | undefined; + getImplementationAtPosition(fileName: string, position: number): ReadonlyArray | undefined; + getReferencesAtPosition(fileName: string, position: number): ReferenceEntry[] | undefined; + findReferences(fileName: string, position: number): ReferencedSymbol[] | undefined; + getDocumentHighlights(fileName: string, position: number, filesToSearch: string[]): DocumentHighlights[] | undefined; + /** @deprecated */ + getOccurrencesAtPosition(fileName: string, position: number): ReadonlyArray | undefined; + getNavigateToItems(searchValue: string, maxResultCount?: number, fileName?: string, excludeDtsFiles?: boolean): NavigateToItem[]; + getNavigationBarItems(fileName: string): NavigationBarItem[]; + getNavigationTree(fileName: string): NavigationTree; + getOutliningSpans(fileName: string): OutliningSpan[]; + getTodoComments(fileName: string, descriptors: TodoCommentDescriptor[]): TodoComment[]; + getBraceMatchingAtPosition(fileName: string, position: number): TextSpan[]; + getIndentationAtPosition(fileName: string, position: number, options: EditorOptions | EditorSettings): number; + getFormattingEditsForRange(fileName: string, start: number, end: number, options: FormatCodeOptions | FormatCodeSettings): TextChange[]; + getFormattingEditsForDocument(fileName: string, options: FormatCodeOptions | FormatCodeSettings): TextChange[]; + getFormattingEditsAfterKeystroke(fileName: string, position: number, key: string, options: FormatCodeOptions | FormatCodeSettings): TextChange[]; + getDocCommentTemplateAtPosition(fileName: string, position: number): TextInsertion | undefined; + isValidBraceCompletionAtPosition(fileName: string, position: number, openingBrace: number): boolean; + /** + * This will return a defined result if the position is after the `>` of the opening tag, or somewhere in the text, of a JSXElement with no closing tag. + * Editors should call this after `>` is typed. + */ + getJsxClosingTagAtPosition(fileName: string, position: number): JsxClosingTagInfo | undefined; + getSpanOfEnclosingComment(fileName: string, position: number, onlyMultiLine: boolean): TextSpan | undefined; + toLineColumnOffset?(fileName: string, position: number): LineAndCharacter; + getCodeFixesAtPosition(fileName: string, start: number, end: number, errorCodes: ReadonlyArray, formatOptions: FormatCodeSettings, preferences: UserPreferences): ReadonlyArray; + getCombinedCodeFix(scope: CombinedCodeFixScope, fixId: {}, formatOptions: FormatCodeSettings, preferences: UserPreferences): CombinedCodeActions; + applyCodeActionCommand(action: CodeActionCommand, formatSettings?: FormatCodeSettings): Promise; + applyCodeActionCommand(action: CodeActionCommand[], formatSettings?: FormatCodeSettings): Promise; + applyCodeActionCommand(action: CodeActionCommand | CodeActionCommand[], formatSettings?: FormatCodeSettings): Promise; + /** @deprecated `fileName` will be ignored */ + applyCodeActionCommand(fileName: string, action: CodeActionCommand): Promise; + /** @deprecated `fileName` will be ignored */ + applyCodeActionCommand(fileName: string, action: CodeActionCommand[]): Promise; + /** @deprecated `fileName` will be ignored */ + applyCodeActionCommand(fileName: string, action: CodeActionCommand | CodeActionCommand[]): Promise; + getApplicableRefactors(fileName: string, positionOrRange: number | TextRange, preferences: UserPreferences | undefined): ApplicableRefactorInfo[]; + getEditsForRefactor(fileName: string, formatOptions: FormatCodeSettings, positionOrRange: number | TextRange, refactorName: string, actionName: string, preferences: UserPreferences | undefined): RefactorEditInfo | undefined; + organizeImports(scope: OrganizeImportsScope, formatOptions: FormatCodeSettings, preferences: UserPreferences | undefined): ReadonlyArray; + getEditsForFileRename(oldFilePath: string, newFilePath: string, formatOptions: FormatCodeSettings, preferences: UserPreferences | undefined): ReadonlyArray; + getEmitOutput(fileName: string, emitOnlyDtsFiles?: boolean): EmitOutput; + getProgram(): Program | undefined; + dispose(): void; + } + interface JsxClosingTagInfo { + readonly newText: string; + } + interface CombinedCodeFixScope { + type: "file"; + fileName: string; + } + type OrganizeImportsScope = CombinedCodeFixScope; + type CompletionsTriggerCharacter = "." | '"' | "'" | "`" | "/" | "@" | "<"; + interface GetCompletionsAtPositionOptions extends UserPreferences { + /** + * If the editor is asking for completions because a certain character was typed + * (as opposed to when the user explicitly requested them) this should be set. + */ + triggerCharacter?: CompletionsTriggerCharacter; + /** @deprecated Use includeCompletionsForModuleExports */ + includeExternalModuleExports?: boolean; + /** @deprecated Use includeCompletionsWithInsertText */ + includeInsertTextCompletions?: boolean; + } + type SignatureHelpTriggerCharacter = "," | "(" | "<"; + type SignatureHelpRetriggerCharacter = SignatureHelpTriggerCharacter | ")"; + interface SignatureHelpItemsOptions { + triggerReason?: SignatureHelpTriggerReason; + } + type SignatureHelpTriggerReason = SignatureHelpInvokedReason | SignatureHelpCharacterTypedReason | SignatureHelpRetriggeredReason; + /** + * Signals that the user manually requested signature help. + * The language service will unconditionally attempt to provide a result. + */ + interface SignatureHelpInvokedReason { + kind: "invoked"; + triggerCharacter?: undefined; + } + /** + * Signals that the signature help request came from a user typing a character. + * Depending on the character and the syntactic context, the request may or may not be served a result. + */ + interface SignatureHelpCharacterTypedReason { + kind: "characterTyped"; + /** + * Character that was responsible for triggering signature help. + */ + triggerCharacter: SignatureHelpTriggerCharacter; + } + /** + * Signals that this signature help request came from typing a character or moving the cursor. + * This should only occur if a signature help session was already active and the editor needs to see if it should adjust. + * The language service will unconditionally attempt to provide a result. + * `triggerCharacter` can be `undefined` for a retrigger caused by a cursor move. + */ + interface SignatureHelpRetriggeredReason { + kind: "retrigger"; + /** + * Character that was responsible for triggering signature help. + */ + triggerCharacter?: SignatureHelpRetriggerCharacter; + } + interface ApplyCodeActionCommandResult { + successMessage: string; + } + interface Classifications { + spans: number[]; + endOfLineState: EndOfLineState; + } + interface ClassifiedSpan { + textSpan: TextSpan; + classificationType: ClassificationTypeNames; + } + /** + * Navigation bar interface designed for visual studio's dual-column layout. + * This does not form a proper tree. + * The navbar is returned as a list of top-level items, each of which has a list of child items. + * Child items always have an empty array for their `childItems`. + */ + interface NavigationBarItem { + text: string; + kind: ScriptElementKind; + kindModifiers: string; + spans: TextSpan[]; + childItems: NavigationBarItem[]; + indent: number; + bolded: boolean; + grayed: boolean; + } + /** + * Node in a tree of nested declarations in a file. + * The top node is always a script or module node. + */ + interface NavigationTree { + /** Name of the declaration, or a short description, e.g. "". */ + text: string; + kind: ScriptElementKind; + /** ScriptElementKindModifier separated by commas, e.g. "public,abstract" */ + kindModifiers: string; + /** + * Spans of the nodes that generated this declaration. + * There will be more than one if this is the result of merging. + */ + spans: TextSpan[]; + nameSpan: TextSpan | undefined; + /** Present if non-empty */ + childItems?: NavigationTree[]; + } + interface TodoCommentDescriptor { + text: string; + priority: number; + } + interface TodoComment { + descriptor: TodoCommentDescriptor; + message: string; + position: number; + } + interface TextChange { + span: TextSpan; + newText: string; + } + interface FileTextChanges { + fileName: string; + textChanges: TextChange[]; + isNewFile?: boolean; + } + interface CodeAction { + /** Description of the code action to display in the UI of the editor */ + description: string; + /** Text changes to apply to each file as part of the code action */ + changes: FileTextChanges[]; + /** + * If the user accepts the code fix, the editor should send the action back in a `applyAction` request. + * This allows the language service to have side effects (e.g. installing dependencies) upon a code fix. + */ + commands?: CodeActionCommand[]; + } + interface CodeFixAction extends CodeAction { + /** Short name to identify the fix, for use by telemetry. */ + fixName: string; + /** + * If present, one may call 'getCombinedCodeFix' with this fixId. + * This may be omitted to indicate that the code fix can't be applied in a group. + */ + fixId?: {}; + fixAllDescription?: string; + } + interface CombinedCodeActions { + changes: ReadonlyArray; + commands?: ReadonlyArray; + } + type CodeActionCommand = InstallPackageAction | GenerateTypesAction; + interface InstallPackageAction { + } + interface GenerateTypesAction extends GenerateTypesOptions { + } + interface GenerateTypesOptions { + readonly file: string; + readonly fileToGenerateTypesFor: string; + readonly outputFileName: string; + } + /** + * A set of one or more available refactoring actions, grouped under a parent refactoring. + */ + interface ApplicableRefactorInfo { + /** + * The programmatic name of the refactoring + */ + name: string; + /** + * A description of this refactoring category to show to the user. + * If the refactoring gets inlined (see below), this text will not be visible. + */ + description: string; + /** + * Inlineable refactorings can have their actions hoisted out to the top level + * of a context menu. Non-inlineanable refactorings should always be shown inside + * their parent grouping. + * + * If not specified, this value is assumed to be 'true' + */ + inlineable?: boolean; + actions: RefactorActionInfo[]; + } + /** + * Represents a single refactoring action - for example, the "Extract Method..." refactor might + * offer several actions, each corresponding to a surround class or closure to extract into. + */ + interface RefactorActionInfo { + /** + * The programmatic name of the refactoring action + */ + name: string; + /** + * A description of this refactoring action to show to the user. + * If the parent refactoring is inlined away, this will be the only text shown, + * so this description should make sense by itself if the parent is inlineable=true + */ + description: string; + } + /** + * A set of edits to make in response to a refactor action, plus an optional + * location where renaming should be invoked from + */ + interface RefactorEditInfo { + edits: FileTextChanges[]; + renameFilename?: string; + renameLocation?: number; + commands?: CodeActionCommand[]; + } + interface TextInsertion { + newText: string; + /** The position in newText the caret should point to after the insertion. */ + caretOffset: number; + } + interface DocumentSpan { + textSpan: TextSpan; + fileName: string; + /** + * If the span represents a location that was remapped (e.g. via a .d.ts.map file), + * then the original filename and span will be specified here + */ + originalTextSpan?: TextSpan; + originalFileName?: string; + } + interface RenameLocation extends DocumentSpan { + readonly prefixText?: string; + readonly suffixText?: string; + } + interface ReferenceEntry extends DocumentSpan { + isWriteAccess: boolean; + isDefinition: boolean; + isInString?: true; + } + interface ImplementationLocation extends DocumentSpan { + kind: ScriptElementKind; + displayParts: SymbolDisplayPart[]; + } + interface DocumentHighlights { + fileName: string; + highlightSpans: HighlightSpan[]; + } + enum HighlightSpanKind { + none = "none", + definition = "definition", + reference = "reference", + writtenReference = "writtenReference" + } + interface HighlightSpan { + fileName?: string; + isInString?: true; + textSpan: TextSpan; + kind: HighlightSpanKind; + } + interface NavigateToItem { + name: string; + kind: ScriptElementKind; + kindModifiers: string; + matchKind: "exact" | "prefix" | "substring" | "camelCase"; + isCaseSensitive: boolean; + fileName: string; + textSpan: TextSpan; + containerName: string; + containerKind: ScriptElementKind; + } + enum IndentStyle { + None = 0, + Block = 1, + Smart = 2 + } + interface EditorOptions { + BaseIndentSize?: number; + IndentSize: number; + TabSize: number; + NewLineCharacter: string; + ConvertTabsToSpaces: boolean; + IndentStyle: IndentStyle; + } + interface EditorSettings { + baseIndentSize?: number; + indentSize?: number; + tabSize?: number; + newLineCharacter?: string; + convertTabsToSpaces?: boolean; + indentStyle?: IndentStyle; + } + interface FormatCodeOptions extends EditorOptions { + InsertSpaceAfterCommaDelimiter: boolean; + InsertSpaceAfterSemicolonInForStatements: boolean; + InsertSpaceBeforeAndAfterBinaryOperators: boolean; + InsertSpaceAfterConstructor?: boolean; + InsertSpaceAfterKeywordsInControlFlowStatements: boolean; + InsertSpaceAfterFunctionKeywordForAnonymousFunctions: boolean; + InsertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: boolean; + InsertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: boolean; + InsertSpaceAfterOpeningAndBeforeClosingNonemptyBraces?: boolean; + InsertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: boolean; + InsertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces?: boolean; + InsertSpaceAfterTypeAssertion?: boolean; + InsertSpaceBeforeFunctionParenthesis?: boolean; + PlaceOpenBraceOnNewLineForFunctions: boolean; + PlaceOpenBraceOnNewLineForControlBlocks: boolean; + insertSpaceBeforeTypeAnnotation?: boolean; + } + interface FormatCodeSettings extends EditorSettings { + readonly insertSpaceAfterCommaDelimiter?: boolean; + readonly insertSpaceAfterSemicolonInForStatements?: boolean; + readonly insertSpaceBeforeAndAfterBinaryOperators?: boolean; + readonly insertSpaceAfterConstructor?: boolean; + readonly insertSpaceAfterKeywordsInControlFlowStatements?: boolean; + readonly insertSpaceAfterFunctionKeywordForAnonymousFunctions?: boolean; + readonly insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis?: boolean; + readonly insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets?: boolean; + readonly insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces?: boolean; + readonly insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces?: boolean; + readonly insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces?: boolean; + readonly insertSpaceAfterTypeAssertion?: boolean; + readonly insertSpaceBeforeFunctionParenthesis?: boolean; + readonly placeOpenBraceOnNewLineForFunctions?: boolean; + readonly placeOpenBraceOnNewLineForControlBlocks?: boolean; + readonly insertSpaceBeforeTypeAnnotation?: boolean; + readonly indentMultiLineObjectLiteralBeginningOnBlankLine?: boolean; + } + function getDefaultFormatCodeSettings(newLineCharacter?: string): FormatCodeSettings; + interface DefinitionInfo extends DocumentSpan { + kind: ScriptElementKind; + name: string; + containerKind: ScriptElementKind; + containerName: string; + } + interface DefinitionInfoAndBoundSpan { + definitions?: ReadonlyArray; + textSpan: TextSpan; + } + interface ReferencedSymbolDefinitionInfo extends DefinitionInfo { + displayParts: SymbolDisplayPart[]; + } + interface ReferencedSymbol { + definition: ReferencedSymbolDefinitionInfo; + references: ReferenceEntry[]; + } + enum SymbolDisplayPartKind { + aliasName = 0, + className = 1, + enumName = 2, + fieldName = 3, + interfaceName = 4, + keyword = 5, + lineBreak = 6, + numericLiteral = 7, + stringLiteral = 8, + localName = 9, + methodName = 10, + moduleName = 11, + operator = 12, + parameterName = 13, + propertyName = 14, + punctuation = 15, + space = 16, + text = 17, + typeParameterName = 18, + enumMemberName = 19, + functionName = 20, + regularExpressionLiteral = 21 + } + interface SymbolDisplayPart { + text: string; + kind: string; + } + interface JSDocTagInfo { + name: string; + text?: string; + } + interface QuickInfo { + kind: ScriptElementKind; + kindModifiers: string; + textSpan: TextSpan; + displayParts?: SymbolDisplayPart[]; + documentation?: SymbolDisplayPart[]; + tags?: JSDocTagInfo[]; + } + type RenameInfo = RenameInfoSuccess | RenameInfoFailure; + interface RenameInfoSuccess { + canRename: true; + /** + * File or directory to rename. + * If set, `getEditsForFileRename` should be called instead of `findRenameLocations`. + */ + fileToRename?: string; + displayName: string; + fullDisplayName: string; + kind: ScriptElementKind; + kindModifiers: string; + triggerSpan: TextSpan; + } + interface RenameInfoFailure { + canRename: false; + localizedErrorMessage: string; + } + interface SignatureHelpParameter { + name: string; + documentation: SymbolDisplayPart[]; + displayParts: SymbolDisplayPart[]; + isOptional: boolean; + } + /** + * Represents a single signature to show in signature help. + * The id is used for subsequent calls into the language service to ask questions about the + * signature help item in the context of any documents that have been updated. i.e. after + * an edit has happened, while signature help is still active, the host can ask important + * questions like 'what parameter is the user currently contained within?'. + */ + interface SignatureHelpItem { + isVariadic: boolean; + prefixDisplayParts: SymbolDisplayPart[]; + suffixDisplayParts: SymbolDisplayPart[]; + separatorDisplayParts: SymbolDisplayPart[]; + parameters: SignatureHelpParameter[]; + documentation: SymbolDisplayPart[]; + tags: JSDocTagInfo[]; + } + /** + * Represents a set of signature help items, and the preferred item that should be selected. + */ + interface SignatureHelpItems { + items: SignatureHelpItem[]; + applicableSpan: TextSpan; + selectedItemIndex: number; + argumentIndex: number; + argumentCount: number; + } + interface CompletionInfo { + /** Not true for all glboal completions. This will be true if the enclosing scope matches a few syntax kinds. See `isSnippetScope`. */ + isGlobalCompletion: boolean; + isMemberCompletion: boolean; + /** + * true when the current location also allows for a new identifier + */ + isNewIdentifierLocation: boolean; + entries: CompletionEntry[]; + } + interface CompletionEntry { + name: string; + kind: ScriptElementKind; + kindModifiers?: string; + sortText: string; + insertText?: string; + /** + * An optional span that indicates the text to be replaced by this completion item. + * If present, this span should be used instead of the default one. + * It will be set if the required span differs from the one generated by the default replacement behavior. + */ + replacementSpan?: TextSpan; + hasAction?: true; + source?: string; + isRecommended?: true; + } + interface CompletionEntryDetails { + name: string; + kind: ScriptElementKind; + kindModifiers: string; + displayParts: SymbolDisplayPart[]; + documentation?: SymbolDisplayPart[]; + tags?: JSDocTagInfo[]; + codeActions?: CodeAction[]; + source?: SymbolDisplayPart[]; + } + interface OutliningSpan { + /** The span of the document to actually collapse. */ + textSpan: TextSpan; + /** The span of the document to display when the user hovers over the collapsed span. */ + hintSpan: TextSpan; + /** The text to display in the editor for the collapsed region. */ + bannerText: string; + /** + * Whether or not this region should be automatically collapsed when + * the 'Collapse to Definitions' command is invoked. + */ + autoCollapse: boolean; + /** + * Classification of the contents of the span + */ + kind: OutliningSpanKind; + } + enum OutliningSpanKind { + /** Single or multi-line comments */ + Comment = "comment", + /** Sections marked by '// #region' and '// #endregion' comments */ + Region = "region", + /** Declarations and expressions */ + Code = "code", + /** Contiguous blocks of import declarations */ + Imports = "imports" + } + enum OutputFileType { + JavaScript = 0, + SourceMap = 1, + Declaration = 2 + } + enum EndOfLineState { + None = 0, + InMultiLineCommentTrivia = 1, + InSingleQuoteStringLiteral = 2, + InDoubleQuoteStringLiteral = 3, + InTemplateHeadOrNoSubstitutionTemplate = 4, + InTemplateMiddleOrTail = 5, + InTemplateSubstitutionPosition = 6 + } + enum TokenClass { + Punctuation = 0, + Keyword = 1, + Operator = 2, + Comment = 3, + Whitespace = 4, + Identifier = 5, + NumberLiteral = 6, + BigIntLiteral = 7, + StringLiteral = 8, + RegExpLiteral = 9 + } + interface ClassificationResult { + finalLexState: EndOfLineState; + entries: ClassificationInfo[]; + } + interface ClassificationInfo { + length: number; + classification: TokenClass; + } + interface Classifier { + /** + * Gives lexical classifications of tokens on a line without any syntactic context. + * For instance, a token consisting of the text 'string' can be either an identifier + * named 'string' or the keyword 'string', however, because this classifier is not aware, + * it relies on certain heuristics to give acceptable results. For classifications where + * speed trumps accuracy, this function is preferable; however, for true accuracy, the + * syntactic classifier is ideal. In fact, in certain editing scenarios, combining the + * lexical, syntactic, and semantic classifiers may issue the best user experience. + * + * @param text The text of a line to classify. + * @param lexState The state of the lexical classifier at the end of the previous line. + * @param syntacticClassifierAbsent Whether the client is *not* using a syntactic classifier. + * If there is no syntactic classifier (syntacticClassifierAbsent=true), + * certain heuristics may be used in its place; however, if there is a + * syntactic classifier (syntacticClassifierAbsent=false), certain + * classifications which may be incorrectly categorized will be given + * back as Identifiers in order to allow the syntactic classifier to + * subsume the classification. + * @deprecated Use getLexicalClassifications instead. + */ + getClassificationsForLine(text: string, lexState: EndOfLineState, syntacticClassifierAbsent: boolean): ClassificationResult; + getEncodedLexicalClassifications(text: string, endOfLineState: EndOfLineState, syntacticClassifierAbsent: boolean): Classifications; + } + enum ScriptElementKind { + unknown = "", + warning = "warning", + /** predefined type (void) or keyword (class) */ + keyword = "keyword", + /** top level script node */ + scriptElement = "script", + /** module foo {} */ + moduleElement = "module", + /** class X {} */ + classElement = "class", + /** var x = class X {} */ + localClassElement = "local class", + /** interface Y {} */ + interfaceElement = "interface", + /** type T = ... */ + typeElement = "type", + /** enum E */ + enumElement = "enum", + enumMemberElement = "enum member", + /** + * Inside module and script only + * const v = .. + */ + variableElement = "var", + /** Inside function */ + localVariableElement = "local var", + /** + * Inside module and script only + * function f() { } + */ + functionElement = "function", + /** Inside function */ + localFunctionElement = "local function", + /** class X { [public|private]* foo() {} } */ + memberFunctionElement = "method", + /** class X { [public|private]* [get|set] foo:number; } */ + memberGetAccessorElement = "getter", + memberSetAccessorElement = "setter", + /** + * class X { [public|private]* foo:number; } + * interface Y { foo:number; } + */ + memberVariableElement = "property", + /** class X { constructor() { } } */ + constructorImplementationElement = "constructor", + /** interface Y { ():number; } */ + callSignatureElement = "call", + /** interface Y { []:number; } */ + indexSignatureElement = "index", + /** interface Y { new():Y; } */ + constructSignatureElement = "construct", + /** function foo(*Y*: string) */ + parameterElement = "parameter", + typeParameterElement = "type parameter", + primitiveType = "primitive type", + label = "label", + alias = "alias", + constElement = "const", + letElement = "let", + directory = "directory", + externalModuleName = "external module name", + /** + * + */ + jsxAttribute = "JSX attribute", + /** String literal */ + string = "string" + } + enum ScriptElementKindModifier { + none = "", + publicMemberModifier = "public", + privateMemberModifier = "private", + protectedMemberModifier = "protected", + exportedModifier = "export", + ambientModifier = "declare", + staticModifier = "static", + abstractModifier = "abstract", + optionalModifier = "optional", + dtsModifier = ".d.ts", + tsModifier = ".ts", + tsxModifier = ".tsx", + jsModifier = ".js", + jsxModifier = ".jsx", + jsonModifier = ".json" + } + enum ClassificationTypeNames { + comment = "comment", + identifier = "identifier", + keyword = "keyword", + numericLiteral = "number", + bigintLiteral = "bigint", + operator = "operator", + stringLiteral = "string", + whiteSpace = "whitespace", + text = "text", + punctuation = "punctuation", + className = "class name", + enumName = "enum name", + interfaceName = "interface name", + moduleName = "module name", + typeParameterName = "type parameter name", + typeAliasName = "type alias name", + parameterName = "parameter name", + docCommentTagName = "doc comment tag name", + jsxOpenTagName = "jsx open tag name", + jsxCloseTagName = "jsx close tag name", + jsxSelfClosingTagName = "jsx self closing tag name", + jsxAttribute = "jsx attribute", + jsxText = "jsx text", + jsxAttributeStringLiteralValue = "jsx attribute string literal value" + } + enum ClassificationType { + comment = 1, + identifier = 2, + keyword = 3, + numericLiteral = 4, + operator = 5, + stringLiteral = 6, + regularExpressionLiteral = 7, + whiteSpace = 8, + text = 9, + punctuation = 10, + className = 11, + enumName = 12, + interfaceName = 13, + moduleName = 14, + typeParameterName = 15, + typeAliasName = 16, + parameterName = 17, + docCommentTagName = 18, + jsxOpenTagName = 19, + jsxCloseTagName = 20, + jsxSelfClosingTagName = 21, + jsxAttribute = 22, + jsxText = 23, + jsxAttributeStringLiteralValue = 24, + bigintLiteral = 25 + } +} +declare namespace ts { + function createClassifier(): Classifier; +} +declare namespace ts { + /** + * The document registry represents a store of SourceFile objects that can be shared between + * multiple LanguageService instances. A LanguageService instance holds on the SourceFile (AST) + * of files in the context. + * SourceFile objects account for most of the memory usage by the language service. Sharing + * the same DocumentRegistry instance between different instances of LanguageService allow + * for more efficient memory utilization since all projects will share at least the library + * file (lib.d.ts). + * + * A more advanced use of the document registry is to serialize sourceFile objects to disk + * and re-hydrate them when needed. + * + * To create a default DocumentRegistry, use createDocumentRegistry to create one, and pass it + * to all subsequent createLanguageService calls. + */ + interface DocumentRegistry { + /** + * Request a stored SourceFile with a given fileName and compilationSettings. + * The first call to acquire will call createLanguageServiceSourceFile to generate + * the SourceFile if was not found in the registry. + * + * @param fileName The name of the file requested + * @param compilationSettings Some compilation settings like target affects the + * shape of a the resulting SourceFile. This allows the DocumentRegistry to store + * multiple copies of the same file for different compilation settings. + * @param scriptSnapshot Text of the file. Only used if the file was not found + * in the registry and a new one was created. + * @param version Current version of the file. Only used if the file was not found + * in the registry and a new one was created. + */ + acquireDocument(fileName: string, compilationSettings: CompilerOptions, scriptSnapshot: IScriptSnapshot, version: string, scriptKind?: ScriptKind): SourceFile; + acquireDocumentWithKey(fileName: string, path: Path, compilationSettings: CompilerOptions, key: DocumentRegistryBucketKey, scriptSnapshot: IScriptSnapshot, version: string, scriptKind?: ScriptKind): SourceFile; + /** + * Request an updated version of an already existing SourceFile with a given fileName + * and compilationSettings. The update will in-turn call updateLanguageServiceSourceFile + * to get an updated SourceFile. + * + * @param fileName The name of the file requested + * @param compilationSettings Some compilation settings like target affects the + * shape of a the resulting SourceFile. This allows the DocumentRegistry to store + * multiple copies of the same file for different compilation settings. + * @param scriptSnapshot Text of the file. + * @param version Current version of the file. + */ + updateDocument(fileName: string, compilationSettings: CompilerOptions, scriptSnapshot: IScriptSnapshot, version: string, scriptKind?: ScriptKind): SourceFile; + updateDocumentWithKey(fileName: string, path: Path, compilationSettings: CompilerOptions, key: DocumentRegistryBucketKey, scriptSnapshot: IScriptSnapshot, version: string, scriptKind?: ScriptKind): SourceFile; + getKeyForCompilationSettings(settings: CompilerOptions): DocumentRegistryBucketKey; + /** + * Informs the DocumentRegistry that a file is not needed any longer. + * + * Note: It is not allowed to call release on a SourceFile that was not acquired from + * this registry originally. + * + * @param fileName The name of the file to be released + * @param compilationSettings The compilation settings used to acquire the file + */ + releaseDocument(fileName: string, compilationSettings: CompilerOptions): void; + releaseDocumentWithKey(path: Path, key: DocumentRegistryBucketKey): void; + reportStats(): string; + } + type DocumentRegistryBucketKey = string & { + __bucketKey: any; + }; + function createDocumentRegistry(useCaseSensitiveFileNames?: boolean, currentDirectory?: string): DocumentRegistry; +} +declare namespace ts { + function preProcessFile(sourceText: string, readImportFiles?: boolean, detectJavaScriptImports?: boolean): PreProcessedFileInfo; +} +declare namespace ts { + interface TranspileOptions { + compilerOptions?: CompilerOptions; + fileName?: string; + reportDiagnostics?: boolean; + moduleName?: string; + renamedDependencies?: MapLike; + transformers?: CustomTransformers; + } + interface TranspileOutput { + outputText: string; + diagnostics?: Diagnostic[]; + sourceMapText?: string; + } + function transpileModule(input: string, transpileOptions: TranspileOptions): TranspileOutput; + function transpile(input: string, compilerOptions?: CompilerOptions, fileName?: string, diagnostics?: Diagnostic[], moduleName?: string): string; +} +declare namespace ts { + function generateTypesForModule(name: string, moduleValue: unknown, formatSettings: FormatCodeSettings): string; + function generateTypesForGlobal(name: string, globalValue: unknown, formatSettings: FormatCodeSettings): string; +} +declare namespace ts { + /** The version of the language service API */ + const servicesVersion = "0.8"; + function toEditorSettings(options: EditorOptions | EditorSettings): EditorSettings; + function displayPartsToString(displayParts: SymbolDisplayPart[] | undefined): string; + function getDefaultCompilerOptions(): CompilerOptions; + function getSupportedCodeFixes(): string[]; + function createLanguageServiceSourceFile(fileName: string, scriptSnapshot: IScriptSnapshot, scriptTarget: ScriptTarget, version: string, setNodeParents: boolean, scriptKind?: ScriptKind): SourceFile; + let disableIncrementalParsing: boolean; + function updateLanguageServiceSourceFile(sourceFile: SourceFile, scriptSnapshot: IScriptSnapshot, version: string, textChangeRange: TextChangeRange | undefined, aggressiveChecks?: boolean): SourceFile; + function createLanguageService(host: LanguageServiceHost, documentRegistry?: DocumentRegistry, syntaxOnly?: boolean): LanguageService; + /** + * Get the path of the default library files (lib.d.ts) as distributed with the typescript + * node package. + * The functionality is not supported if the ts module is consumed outside of a node module. + */ + function getDefaultLibFilePath(options: CompilerOptions): string; +} +declare namespace ts { + /** + * Transform one or more nodes using the supplied transformers. + * @param source A single `Node` or an array of `Node` objects. + * @param transformers An array of `TransformerFactory` callbacks used to process the transformation. + * @param compilerOptions Optional compiler options. + */ + function transform(source: T | T[], transformers: TransformerFactory[], compilerOptions?: CompilerOptions): TransformationResult; +} diff --git a/node_modules/typescript/lib/typescriptServices.js b/node_modules/typescript/lib/typescriptServices.js new file mode 100644 index 0000000..2a87d69 --- /dev/null +++ b/node_modules/typescript/lib/typescriptServices.js @@ -0,0 +1,119806 @@ +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + +"use strict"; +var __assign = (this && this.__assign) || function () { + __assign = Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; + }; + return __assign.apply(this, arguments); +}; +var __generator = (this && this.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } +}; +var __makeTemplateObject = (this && this.__makeTemplateObject) || function (cooked, raw) { + if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } + return cooked; +}; +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +var ts; +(function (ts) { + // WARNING: The script `configureNightly.ts` uses a regexp to parse out these values. + // If changing the text in this section, be sure to test `configureNightly` too. + ts.versionMajorMinor = "3.2"; + /** The version of the TypeScript compiler release */ + ts.version = ts.versionMajorMinor + ".2"; +})(ts || (ts = {})); +(function (ts) { + /* @internal */ + var Comparison; + (function (Comparison) { + Comparison[Comparison["LessThan"] = -1] = "LessThan"; + Comparison[Comparison["EqualTo"] = 0] = "EqualTo"; + Comparison[Comparison["GreaterThan"] = 1] = "GreaterThan"; + })(Comparison = ts.Comparison || (ts.Comparison = {})); +})(ts || (ts = {})); +/* @internal */ +(function (ts) { + ts.emptyArray = []; + /** Create a MapLike with good performance. */ + function createDictionaryObject() { + var map = Object.create(/*prototype*/ null); // tslint:disable-line:no-null-keyword + // Using 'delete' on an object causes V8 to put the object in dictionary mode. + // This disables creation of hidden classes, which are expensive when an object is + // constantly changing shape. + map.__ = undefined; + delete map.__; + return map; + } + /** Create a new map. If a template object is provided, the map will copy entries from it. */ + function createMap() { + return new ts.MapCtr(); + } + ts.createMap = createMap; + function createMapFromEntries(entries) { + var map = createMap(); + for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) { + var _a = entries_1[_i], key = _a[0], value = _a[1]; + map.set(key, value); + } + return map; + } + ts.createMapFromEntries = createMapFromEntries; + function createMapFromTemplate(template) { + var map = new ts.MapCtr(); + // Copies keys/values from template. Note that for..in will not throw if + // template is undefined, and instead will just exit the loop. + for (var key in template) { + if (hasOwnProperty.call(template, key)) { + map.set(key, template[key]); + } + } + return map; + } + ts.createMapFromTemplate = createMapFromTemplate; + // Internet Explorer's Map doesn't support iteration, so don't use it. + // tslint:disable-next-line no-in-operator variable-name + ts.MapCtr = typeof Map !== "undefined" && "entries" in Map.prototype ? Map : shimMap(); + // Keep the class inside a function so it doesn't get compiled if it's not used. + function shimMap() { + var MapIterator = /** @class */ (function () { + function MapIterator(data, selector) { + this.index = 0; + this.data = data; + this.selector = selector; + this.keys = Object.keys(data); + } + MapIterator.prototype.next = function () { + var index = this.index; + if (index < this.keys.length) { + this.index++; + return { value: this.selector(this.data, this.keys[index]), done: false }; + } + return { value: undefined, done: true }; + }; + return MapIterator; + }()); + return /** @class */ (function () { + function class_1() { + this.data = createDictionaryObject(); + this.size = 0; + } + class_1.prototype.get = function (key) { + return this.data[key]; + }; + class_1.prototype.set = function (key, value) { + if (!this.has(key)) { + this.size++; + } + this.data[key] = value; + return this; + }; + class_1.prototype.has = function (key) { + // tslint:disable-next-line:no-in-operator + return key in this.data; + }; + class_1.prototype.delete = function (key) { + if (this.has(key)) { + this.size--; + delete this.data[key]; + return true; + } + return false; + }; + class_1.prototype.clear = function () { + this.data = createDictionaryObject(); + this.size = 0; + }; + class_1.prototype.keys = function () { + return new MapIterator(this.data, function (_data, key) { return key; }); + }; + class_1.prototype.values = function () { + return new MapIterator(this.data, function (data, key) { return data[key]; }); + }; + class_1.prototype.entries = function () { + return new MapIterator(this.data, function (data, key) { return [key, data[key]]; }); + }; + class_1.prototype.forEach = function (action) { + for (var key in this.data) { + action(this.data[key], key); + } + }; + return class_1; + }()); + } + function length(array) { + return array ? array.length : 0; + } + ts.length = length; + /** + * Iterates through 'array' by index and performs the callback on each element of array until the callback + * returns a truthy value, then returns that value. + * If no such value is found, the callback is applied to each element of array and undefined is returned. + */ + function forEach(array, callback) { + if (array) { + for (var i = 0; i < array.length; i++) { + var result = callback(array[i], i); + if (result) { + return result; + } + } + } + return undefined; + } + ts.forEach = forEach; + /** Like `forEach`, but suitable for use with numbers and strings (which may be falsy). */ + function firstDefined(array, callback) { + if (array === undefined) { + return undefined; + } + for (var i = 0; i < array.length; i++) { + var result = callback(array[i], i); + if (result !== undefined) { + return result; + } + } + return undefined; + } + ts.firstDefined = firstDefined; + function firstDefinedIterator(iter, callback) { + while (true) { + var _a = iter.next(), value = _a.value, done = _a.done; + if (done) { + return undefined; + } + var result = callback(value); + if (result !== undefined) { + return result; + } + } + } + ts.firstDefinedIterator = firstDefinedIterator; + function zipWith(arrayA, arrayB, callback) { + var result = []; + Debug.assertEqual(arrayA.length, arrayB.length); + for (var i = 0; i < arrayA.length; i++) { + result.push(callback(arrayA[i], arrayB[i], i)); + } + return result; + } + ts.zipWith = zipWith; + function zipToIterator(arrayA, arrayB) { + Debug.assertEqual(arrayA.length, arrayB.length); + var i = 0; + return { + next: function () { + if (i === arrayA.length) { + return { value: undefined, done: true }; + } + i++; + return { value: [arrayA[i - 1], arrayB[i - 1]], done: false }; + } + }; + } + ts.zipToIterator = zipToIterator; + function zipToMap(keys, values) { + Debug.assert(keys.length === values.length); + var map = createMap(); + for (var i = 0; i < keys.length; ++i) { + map.set(keys[i], values[i]); + } + return map; + } + ts.zipToMap = zipToMap; + /** + * Iterates through `array` by index and performs the callback on each element of array until the callback + * returns a falsey value, then returns false. + * If no such value is found, the callback is applied to each element of array and `true` is returned. + */ + function every(array, callback) { + if (array) { + for (var i = 0; i < array.length; i++) { + if (!callback(array[i], i)) { + return false; + } + } + } + return true; + } + ts.every = every; + function find(array, predicate) { + for (var i = 0; i < array.length; i++) { + var value = array[i]; + if (predicate(value, i)) { + return value; + } + } + return undefined; + } + ts.find = find; + function findLast(array, predicate) { + for (var i = array.length - 1; i >= 0; i--) { + var value = array[i]; + if (predicate(value, i)) { + return value; + } + } + return undefined; + } + ts.findLast = findLast; + /** Works like Array.prototype.findIndex, returning `-1` if no element satisfying the predicate is found. */ + function findIndex(array, predicate, startIndex) { + for (var i = startIndex || 0; i < array.length; i++) { + if (predicate(array[i], i)) { + return i; + } + } + return -1; + } + ts.findIndex = findIndex; + function findLastIndex(array, predicate, startIndex) { + for (var i = startIndex === undefined ? array.length - 1 : startIndex; i >= 0; i--) { + if (predicate(array[i], i)) { + return i; + } + } + return -1; + } + ts.findLastIndex = findLastIndex; + /** + * Returns the first truthy result of `callback`, or else fails. + * This is like `forEach`, but never returns undefined. + */ + function findMap(array, callback) { + for (var i = 0; i < array.length; i++) { + var result = callback(array[i], i); + if (result) { + return result; + } + } + return Debug.fail(); + } + ts.findMap = findMap; + function contains(array, value, equalityComparer) { + if (equalityComparer === void 0) { equalityComparer = equateValues; } + if (array) { + for (var _i = 0, array_1 = array; _i < array_1.length; _i++) { + var v = array_1[_i]; + if (equalityComparer(v, value)) { + return true; + } + } + } + return false; + } + ts.contains = contains; + function arraysEqual(a, b, equalityComparer) { + if (equalityComparer === void 0) { equalityComparer = equateValues; } + return a.length === b.length && a.every(function (x, i) { return equalityComparer(x, b[i]); }); + } + ts.arraysEqual = arraysEqual; + function indexOfAnyCharCode(text, charCodes, start) { + for (var i = start || 0; i < text.length; i++) { + if (contains(charCodes, text.charCodeAt(i))) { + return i; + } + } + return -1; + } + ts.indexOfAnyCharCode = indexOfAnyCharCode; + function countWhere(array, predicate) { + var count = 0; + if (array) { + for (var i = 0; i < array.length; i++) { + var v = array[i]; + if (predicate(v, i)) { + count++; + } + } + } + return count; + } + ts.countWhere = countWhere; + function filter(array, f) { + if (array) { + var len = array.length; + var i = 0; + while (i < len && f(array[i])) + i++; + if (i < len) { + var result = array.slice(0, i); + i++; + while (i < len) { + var item = array[i]; + if (f(item)) { + result.push(item); + } + i++; + } + return result; + } + } + return array; + } + ts.filter = filter; + function filterMutate(array, f) { + var outIndex = 0; + for (var i = 0; i < array.length; i++) { + if (f(array[i], i, array)) { + array[outIndex] = array[i]; + outIndex++; + } + } + array.length = outIndex; + } + ts.filterMutate = filterMutate; + function clear(array) { + array.length = 0; + } + ts.clear = clear; + function map(array, f) { + var result; + if (array) { + result = []; + for (var i = 0; i < array.length; i++) { + result.push(f(array[i], i)); + } + } + return result; + } + ts.map = map; + function mapIterator(iter, mapFn) { + return { + next: function () { + var iterRes = iter.next(); + return iterRes.done ? iterRes : { value: mapFn(iterRes.value), done: false }; + } + }; + } + ts.mapIterator = mapIterator; + function sameMap(array, f) { + if (array) { + for (var i = 0; i < array.length; i++) { + var item = array[i]; + var mapped = f(item, i); + if (item !== mapped) { + var result = array.slice(0, i); + result.push(mapped); + for (i++; i < array.length; i++) { + result.push(f(array[i], i)); + } + return result; + } + } + } + return array; + } + ts.sameMap = sameMap; + function flatten(array) { + var result; + if (array) { + result = []; + for (var _i = 0, array_2 = array; _i < array_2.length; _i++) { + var v = array_2[_i]; + if (v) { + if (isArray(v)) { + addRange(result, v); + } + else { + result.push(v); + } + } + } + } + return result; + } + ts.flatten = flatten; + /** + * Maps an array. If the mapped value is an array, it is spread into the result. + * + * @param array The array to map. + * @param mapfn The callback used to map the result into one or more values. + */ + function flatMap(array, mapfn) { + var result; + if (array) { + for (var i = 0; i < array.length; i++) { + var v = mapfn(array[i], i); + if (v) { + if (isArray(v)) { + result = addRange(result, v); + } + else { + result = append(result, v); + } + } + } + } + return result || ts.emptyArray; + } + ts.flatMap = flatMap; + function flatMapToMutable(array, mapfn) { + var result = []; + if (array) { + for (var i = 0; i < array.length; i++) { + var v = mapfn(array[i], i); + if (v) { + if (isArray(v)) { + addRange(result, v); + } + else { + result.push(v); + } + } + } + } + return result; + } + ts.flatMapToMutable = flatMapToMutable; + function flatMapIterator(iter, mapfn) { + var first = iter.next(); + if (first.done) { + return ts.emptyIterator; + } + var currentIter = getIterator(first.value); + return { + next: function () { + while (true) { + var currentRes = currentIter.next(); + if (!currentRes.done) { + return currentRes; + } + var iterRes = iter.next(); + if (iterRes.done) { + return iterRes; + } + currentIter = getIterator(iterRes.value); + } + }, + }; + function getIterator(x) { + var res = mapfn(x); + return res === undefined ? ts.emptyIterator : isArray(res) ? arrayIterator(res) : res; + } + } + ts.flatMapIterator = flatMapIterator; + function sameFlatMap(array, mapfn) { + var result; + if (array) { + for (var i = 0; i < array.length; i++) { + var item = array[i]; + var mapped = mapfn(item, i); + if (result || item !== mapped || isArray(mapped)) { + if (!result) { + result = array.slice(0, i); + } + if (isArray(mapped)) { + addRange(result, mapped); + } + else { + result.push(mapped); + } + } + } + } + return result || array; + } + ts.sameFlatMap = sameFlatMap; + function mapAllOrFail(array, mapFn) { + var result = []; + for (var i = 0; i < array.length; i++) { + var mapped = mapFn(array[i], i); + if (mapped === undefined) { + return undefined; + } + result.push(mapped); + } + return result; + } + ts.mapAllOrFail = mapAllOrFail; + function mapDefined(array, mapFn) { + var result = []; + if (array) { + for (var i = 0; i < array.length; i++) { + var mapped = mapFn(array[i], i); + if (mapped !== undefined) { + result.push(mapped); + } + } + } + return result; + } + ts.mapDefined = mapDefined; + function mapDefinedIterator(iter, mapFn) { + return { + next: function () { + while (true) { + var res = iter.next(); + if (res.done) { + return res; + } + var value = mapFn(res.value); + if (value !== undefined) { + return { value: value, done: false }; + } + } + } + }; + } + ts.mapDefinedIterator = mapDefinedIterator; + ts.emptyIterator = { next: function () { return ({ value: undefined, done: true }); } }; + function singleIterator(value) { + var done = false; + return { + next: function () { + var wasDone = done; + done = true; + return wasDone ? { value: undefined, done: true } : { value: value, done: false }; + } + }; + } + ts.singleIterator = singleIterator; + function spanMap(array, keyfn, mapfn) { + var result; + if (array) { + result = []; + var len = array.length; + var previousKey = void 0; + var key = void 0; + var start = 0; + var pos = 0; + while (start < len) { + while (pos < len) { + var value = array[pos]; + key = keyfn(value, pos); + if (pos === 0) { + previousKey = key; + } + else if (key !== previousKey) { + break; + } + pos++; + } + if (start < pos) { + var v = mapfn(array.slice(start, pos), previousKey, start, pos); + if (v) { + result.push(v); + } + start = pos; + } + previousKey = key; + pos++; + } + } + return result; + } + ts.spanMap = spanMap; + function mapEntries(map, f) { + if (!map) { + return undefined; + } + var result = createMap(); + map.forEach(function (value, key) { + var _a = f(key, value), newKey = _a[0], newValue = _a[1]; + result.set(newKey, newValue); + }); + return result; + } + ts.mapEntries = mapEntries; + function some(array, predicate) { + if (array) { + if (predicate) { + for (var _i = 0, array_3 = array; _i < array_3.length; _i++) { + var v = array_3[_i]; + if (predicate(v)) { + return true; + } + } + } + else { + return array.length > 0; + } + } + return false; + } + ts.some = some; + /** Calls the callback with (start, afterEnd) index pairs for each range where 'pred' is true. */ + function getRangesWhere(arr, pred, cb) { + var start; + for (var i = 0; i < arr.length; i++) { + if (pred(arr[i])) { + start = start === undefined ? i : start; + } + else { + if (start !== undefined) { + cb(start, i); + start = undefined; + } + } + } + if (start !== undefined) + cb(start, arr.length); + } + ts.getRangesWhere = getRangesWhere; + function concatenate(array1, array2) { + if (!some(array2)) + return array1; + if (!some(array1)) + return array2; + return array1.concat(array2); + } + ts.concatenate = concatenate; + function deduplicateRelational(array, equalityComparer, comparer) { + // Perform a stable sort of the array. This ensures the first entry in a list of + // duplicates remains the first entry in the result. + var indices = array.map(function (_, i) { return i; }); + stableSortIndices(array, indices, comparer); + var last = array[indices[0]]; + var deduplicated = [indices[0]]; + for (var i = 1; i < indices.length; i++) { + var index = indices[i]; + var item = array[index]; + if (!equalityComparer(last, item)) { + deduplicated.push(index); + last = item; + } + } + // restore original order + deduplicated.sort(); + return deduplicated.map(function (i) { return array[i]; }); + } + function deduplicateEquality(array, equalityComparer) { + var result = []; + for (var _i = 0, array_4 = array; _i < array_4.length; _i++) { + var item = array_4[_i]; + pushIfUnique(result, item, equalityComparer); + } + return result; + } + /** + * Deduplicates an unsorted array. + * @param equalityComparer An optional `EqualityComparer` used to determine if two values are duplicates. + * @param comparer An optional `Comparer` used to sort entries before comparison, though the + * result will remain in the original order in `array`. + */ + function deduplicate(array, equalityComparer, comparer) { + return array.length === 0 ? [] : + array.length === 1 ? array.slice() : + comparer ? deduplicateRelational(array, equalityComparer, comparer) : + deduplicateEquality(array, equalityComparer); + } + ts.deduplicate = deduplicate; + /** + * Deduplicates an array that has already been sorted. + */ + function deduplicateSorted(array, comparer) { + if (array.length === 0) + return ts.emptyArray; + var last = array[0]; + var deduplicated = [last]; + for (var i = 1; i < array.length; i++) { + var next = array[i]; + switch (comparer(next, last)) { + // equality comparison + case true: + // relational comparison + case 0 /* EqualTo */: + continue; + case -1 /* LessThan */: + // If `array` is sorted, `next` should **never** be less than `last`. + return Debug.fail("Array is unsorted."); + } + deduplicated.push(last = next); + } + return deduplicated; + } + function insertSorted(array, insert, compare) { + if (array.length === 0) { + array.push(insert); + return; + } + var insertIndex = binarySearch(array, insert, identity, compare); + if (insertIndex < 0) { + array.splice(~insertIndex, 0, insert); + } + } + ts.insertSorted = insertSorted; + function sortAndDeduplicate(array, comparer, equalityComparer) { + return deduplicateSorted(sort(array, comparer), equalityComparer || comparer || compareStringsCaseSensitive); + } + ts.sortAndDeduplicate = sortAndDeduplicate; + function arrayIsEqualTo(array1, array2, equalityComparer) { + if (equalityComparer === void 0) { equalityComparer = equateValues; } + if (!array1 || !array2) { + return array1 === array2; + } + if (array1.length !== array2.length) { + return false; + } + for (var i = 0; i < array1.length; i++) { + if (!equalityComparer(array1[i], array2[i], i)) { + return false; + } + } + return true; + } + ts.arrayIsEqualTo = arrayIsEqualTo; + function compact(array) { + var result; + if (array) { + for (var i = 0; i < array.length; i++) { + var v = array[i]; + if (result || !v) { + if (!result) { + result = array.slice(0, i); + } + if (v) { + result.push(v); + } + } + } + } + return result || array; + } + ts.compact = compact; + /** + * Gets the relative complement of `arrayA` with respect to `arrayB`, returning the elements that + * are not present in `arrayA` but are present in `arrayB`. Assumes both arrays are sorted + * based on the provided comparer. + */ + function relativeComplement(arrayA, arrayB, comparer) { + if (!arrayB || !arrayA || arrayB.length === 0 || arrayA.length === 0) + return arrayB; + var result = []; + loopB: for (var offsetA = 0, offsetB = 0; offsetB < arrayB.length; offsetB++) { + if (offsetB > 0) { + // Ensure `arrayB` is properly sorted. + Debug.assertGreaterThanOrEqual(comparer(arrayB[offsetB], arrayB[offsetB - 1]), 0 /* EqualTo */); + } + loopA: for (var startA = offsetA; offsetA < arrayA.length; offsetA++) { + if (offsetA > startA) { + // Ensure `arrayA` is properly sorted. We only need to perform this check if + // `offsetA` has changed since we entered the loop. + Debug.assertGreaterThanOrEqual(comparer(arrayA[offsetA], arrayA[offsetA - 1]), 0 /* EqualTo */); + } + switch (comparer(arrayB[offsetB], arrayA[offsetA])) { + case -1 /* LessThan */: + // If B is less than A, B does not exist in arrayA. Add B to the result and + // move to the next element in arrayB without changing the current position + // in arrayA. + result.push(arrayB[offsetB]); + continue loopB; + case 0 /* EqualTo */: + // If B is equal to A, B exists in arrayA. Move to the next element in + // arrayB without adding B to the result or changing the current position + // in arrayA. + continue loopB; + case 1 /* GreaterThan */: + // If B is greater than A, we need to keep looking for B in arrayA. Move to + // the next element in arrayA and recheck. + continue loopA; + } + } + } + return result; + } + ts.relativeComplement = relativeComplement; + function sum(array, prop) { + var result = 0; + for (var _i = 0, array_5 = array; _i < array_5.length; _i++) { + var v = array_5[_i]; + result += v[prop]; + } + return result; + } + ts.sum = sum; + function append(to, value) { + if (value === undefined) + return to; + if (to === undefined) + return [value]; + to.push(value); + return to; + } + ts.append = append; + /** + * Gets the actual offset into an array for a relative offset. Negative offsets indicate a + * position offset from the end of the array. + */ + function toOffset(array, offset) { + return offset < 0 ? array.length + offset : offset; + } + function addRange(to, from, start, end) { + if (from === undefined || from.length === 0) + return to; + if (to === undefined) + return from.slice(start, end); + start = start === undefined ? 0 : toOffset(from, start); + end = end === undefined ? from.length : toOffset(from, end); + for (var i = start; i < end && i < from.length; i++) { + if (from[i] !== undefined) { + to.push(from[i]); + } + } + return to; + } + ts.addRange = addRange; + /** + * @return Whether the value was added. + */ + function pushIfUnique(array, toAdd, equalityComparer) { + if (contains(array, toAdd, equalityComparer)) { + return false; + } + else { + array.push(toAdd); + return true; + } + } + ts.pushIfUnique = pushIfUnique; + /** + * Unlike `pushIfUnique`, this can take `undefined` as an input, and returns a new array. + */ + function appendIfUnique(array, toAdd, equalityComparer) { + if (array) { + pushIfUnique(array, toAdd, equalityComparer); + return array; + } + else { + return [toAdd]; + } + } + ts.appendIfUnique = appendIfUnique; + function stableSortIndices(array, indices, comparer) { + // sort indices by value then position + indices.sort(function (x, y) { return comparer(array[x], array[y]) || compareValues(x, y); }); + } + /** + * Returns a new sorted array. + */ + function sort(array, comparer) { + return (array.length === 0 ? array : array.slice().sort(comparer)); + } + ts.sort = sort; + function arrayIterator(array) { + var i = 0; + return { next: function () { + if (i === array.length) { + return { value: undefined, done: true }; + } + else { + i++; + return { value: array[i - 1], done: false }; + } + } }; + } + ts.arrayIterator = arrayIterator; + /** + * Stable sort of an array. Elements equal to each other maintain their relative position in the array. + */ + function stableSort(array, comparer) { + var indices = array.map(function (_, i) { return i; }); + stableSortIndices(array, indices, comparer); + return indices.map(function (i) { return array[i]; }); + } + ts.stableSort = stableSort; + function rangeEquals(array1, array2, pos, end) { + while (pos < end) { + if (array1[pos] !== array2[pos]) { + return false; + } + pos++; + } + return true; + } + ts.rangeEquals = rangeEquals; + /** + * Returns the element at a specific offset in an array if non-empty, `undefined` otherwise. + * A negative offset indicates the element should be retrieved from the end of the array. + */ + function elementAt(array, offset) { + if (array) { + offset = toOffset(array, offset); + if (offset < array.length) { + return array[offset]; + } + } + return undefined; + } + ts.elementAt = elementAt; + /** + * Returns the first element of an array if non-empty, `undefined` otherwise. + */ + function firstOrUndefined(array) { + return array.length === 0 ? undefined : array[0]; + } + ts.firstOrUndefined = firstOrUndefined; + function first(array) { + Debug.assert(array.length !== 0); + return array[0]; + } + ts.first = first; + /** + * Returns the last element of an array if non-empty, `undefined` otherwise. + */ + function lastOrUndefined(array) { + return array.length === 0 ? undefined : array[array.length - 1]; + } + ts.lastOrUndefined = lastOrUndefined; + function last(array) { + Debug.assert(array.length !== 0); + return array[array.length - 1]; + } + ts.last = last; + /** + * Returns the only element of an array if it contains only one element, `undefined` otherwise. + */ + function singleOrUndefined(array) { + return array && array.length === 1 + ? array[0] + : undefined; + } + ts.singleOrUndefined = singleOrUndefined; + function singleOrMany(array) { + return array && array.length === 1 + ? array[0] + : array; + } + ts.singleOrMany = singleOrMany; + function replaceElement(array, index, value) { + var result = array.slice(0); + result[index] = value; + return result; + } + ts.replaceElement = replaceElement; + /** + * Performs a binary search, finding the index at which `value` occurs in `array`. + * If no such index is found, returns the 2's-complement of first index at which + * `array[index]` exceeds `value`. + * @param array A sorted array whose first element must be no larger than number + * @param value The value to be searched for in the array. + * @param keySelector A callback used to select the search key from `value` and each element of + * `array`. + * @param keyComparer A callback used to compare two keys in a sorted array. + * @param offset An offset into `array` at which to start the search. + */ + function binarySearch(array, value, keySelector, keyComparer, offset) { + return binarySearchKey(array, keySelector(value), keySelector, keyComparer, offset); + } + ts.binarySearch = binarySearch; + /** + * Performs a binary search, finding the index at which an object with `key` occurs in `array`. + * If no such index is found, returns the 2's-complement of first index at which + * `array[index]` exceeds `key`. + * @param array A sorted array whose first element must be no larger than number + * @param key The key to be searched for in the array. + * @param keySelector A callback used to select the search key from each element of `array`. + * @param keyComparer A callback used to compare two keys in a sorted array. + * @param offset An offset into `array` at which to start the search. + */ + function binarySearchKey(array, key, keySelector, keyComparer, offset) { + if (!some(array)) { + return -1; + } + var low = offset || 0; + var high = array.length - 1; + while (low <= high) { + var middle = low + ((high - low) >> 1); + var midKey = keySelector(array[middle]); + switch (keyComparer(midKey, key)) { + case -1 /* LessThan */: + low = middle + 1; + break; + case 0 /* EqualTo */: + return middle; + case 1 /* GreaterThan */: + high = middle - 1; + break; + } + } + return ~low; + } + ts.binarySearchKey = binarySearchKey; + function reduceLeft(array, f, initial, start, count) { + if (array && array.length > 0) { + var size = array.length; + if (size > 0) { + var pos = start === undefined || start < 0 ? 0 : start; + var end = count === undefined || pos + count > size - 1 ? size - 1 : pos + count; + var result = void 0; + if (arguments.length <= 2) { + result = array[pos]; + pos++; + } + else { + result = initial; + } + while (pos <= end) { + result = f(result, array[pos], pos); + pos++; + } + return result; + } + } + return initial; + } + ts.reduceLeft = reduceLeft; + var hasOwnProperty = Object.prototype.hasOwnProperty; + /** + * Indicates whether a map-like contains an own property with the specified key. + * + * @param map A map-like. + * @param key A property key. + */ + function hasProperty(map, key) { + return hasOwnProperty.call(map, key); + } + ts.hasProperty = hasProperty; + /** + * Gets the value of an owned property in a map-like. + * + * @param map A map-like. + * @param key A property key. + */ + function getProperty(map, key) { + return hasOwnProperty.call(map, key) ? map[key] : undefined; + } + ts.getProperty = getProperty; + /** + * Gets the owned, enumerable property keys of a map-like. + */ + function getOwnKeys(map) { + var keys = []; + for (var key in map) { + if (hasOwnProperty.call(map, key)) { + keys.push(key); + } + } + return keys; + } + ts.getOwnKeys = getOwnKeys; + function getOwnValues(sparseArray) { + var values = []; + for (var key in sparseArray) { + if (hasOwnProperty.call(sparseArray, key)) { + values.push(sparseArray[key]); + } + } + return values; + } + ts.getOwnValues = getOwnValues; + function arrayFrom(iterator, map) { + var _a; + var result = []; + for (var _b = iterator.next(), value = _b.value, done = _b.done; !done; _a = iterator.next(), value = _a.value, done = _a.done, _a) { + result.push(map ? map(value) : value); + } + return result; + } + ts.arrayFrom = arrayFrom; + function assign(t) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + for (var _a = 0, args_1 = args; _a < args_1.length; _a++) { + var arg = args_1[_a]; + for (var p in arg) { + if (hasProperty(arg, p)) { + t[p] = arg[p]; // TODO: GH#23368 + } + } + } + return t; + } + ts.assign = assign; + /** + * Performs a shallow equality comparison of the contents of two map-likes. + * + * @param left A map-like whose properties should be compared. + * @param right A map-like whose properties should be compared. + */ + function equalOwnProperties(left, right, equalityComparer) { + if (equalityComparer === void 0) { equalityComparer = equateValues; } + if (left === right) + return true; + if (!left || !right) + return false; + for (var key in left) { + if (hasOwnProperty.call(left, key)) { + if (!hasOwnProperty.call(right, key)) + return false; + if (!equalityComparer(left[key], right[key])) + return false; + } + } + for (var key in right) { + if (hasOwnProperty.call(right, key)) { + if (!hasOwnProperty.call(left, key)) + return false; + } + } + return true; + } + ts.equalOwnProperties = equalOwnProperties; + function arrayToMap(array, makeKey, makeValue) { + if (makeValue === void 0) { makeValue = identity; } + var result = createMap(); + for (var _i = 0, array_6 = array; _i < array_6.length; _i++) { + var value = array_6[_i]; + var key = makeKey(value); + if (key !== undefined) + result.set(key, makeValue(value)); + } + return result; + } + ts.arrayToMap = arrayToMap; + function arrayToNumericMap(array, makeKey, makeValue) { + if (makeValue === void 0) { makeValue = identity; } + var result = []; + for (var _i = 0, array_7 = array; _i < array_7.length; _i++) { + var value = array_7[_i]; + result[makeKey(value)] = makeValue(value); + } + return result; + } + ts.arrayToNumericMap = arrayToNumericMap; + function arrayToMultiMap(values, makeKey, makeValue) { + if (makeValue === void 0) { makeValue = identity; } + var result = createMultiMap(); + for (var _i = 0, values_1 = values; _i < values_1.length; _i++) { + var value = values_1[_i]; + result.add(makeKey(value), makeValue(value)); + } + return result; + } + ts.arrayToMultiMap = arrayToMultiMap; + function group(values, getGroupId) { + return arrayFrom(arrayToMultiMap(values, getGroupId).values()); + } + ts.group = group; + function clone(object) { + var result = {}; + for (var id in object) { + if (hasOwnProperty.call(object, id)) { + result[id] = object[id]; + } + } + return result; + } + ts.clone = clone; + function extend(first, second) { + var result = {}; + for (var id in second) { + if (hasOwnProperty.call(second, id)) { + result[id] = second[id]; + } + } + for (var id in first) { + if (hasOwnProperty.call(first, id)) { + result[id] = first[id]; + } + } + return result; + } + ts.extend = extend; + function createMultiMap() { + var map = createMap(); + map.add = multiMapAdd; + map.remove = multiMapRemove; + return map; + } + ts.createMultiMap = createMultiMap; + function multiMapAdd(key, value) { + var values = this.get(key); + if (values) { + values.push(value); + } + else { + this.set(key, values = [value]); + } + return values; + } + function multiMapRemove(key, value) { + var values = this.get(key); + if (values) { + unorderedRemoveItem(values, value); + if (!values.length) { + this.delete(key); + } + } + } + /** + * Tests whether a value is an array. + */ + function isArray(value) { + return Array.isArray ? Array.isArray(value) : value instanceof Array; + } + ts.isArray = isArray; + function toArray(value) { + return isArray(value) ? value : [value]; + } + ts.toArray = toArray; + /** + * Tests whether a value is string + */ + function isString(text) { + return typeof text === "string"; + } + ts.isString = isString; + function isNumber(x) { + return typeof x === "number"; + } + ts.isNumber = isNumber; + function tryCast(value, test) { + return value !== undefined && test(value) ? value : undefined; + } + ts.tryCast = tryCast; + function cast(value, test) { + if (value !== undefined && test(value)) + return value; + return Debug.fail("Invalid cast. The supplied value " + value + " did not pass the test '" + Debug.getFunctionName(test) + "'."); + } + ts.cast = cast; + /** Does nothing. */ + function noop(_) { } // tslint:disable-line no-empty + ts.noop = noop; + /** Do nothing and return false */ + function returnFalse() { return false; } + ts.returnFalse = returnFalse; + /** Do nothing and return true */ + function returnTrue() { return true; } + ts.returnTrue = returnTrue; + /** Returns its argument. */ + function identity(x) { return x; } + ts.identity = identity; + /** Returns lower case string */ + function toLowerCase(x) { return x.toLowerCase(); } + ts.toLowerCase = toLowerCase; + /** Throws an error because a function is not implemented. */ + function notImplemented() { + throw new Error("Not implemented"); + } + ts.notImplemented = notImplemented; + function memoize(callback) { + var value; + return function () { + if (callback) { + value = callback(); + callback = undefined; + } + return value; + }; + } + ts.memoize = memoize; + function chain(a, b, c, d, e) { + if (e) { + var args_2 = []; + for (var i = 0; i < arguments.length; i++) { + args_2[i] = arguments[i]; + } + return function (t) { return compose.apply(void 0, map(args_2, function (f) { return f(t); })); }; + } + else if (d) { + return function (t) { return compose(a(t), b(t), c(t), d(t)); }; + } + else if (c) { + return function (t) { return compose(a(t), b(t), c(t)); }; + } + else if (b) { + return function (t) { return compose(a(t), b(t)); }; + } + else if (a) { + return function (t) { return compose(a(t)); }; + } + else { + return function (_) { return function (u) { return u; }; }; + } + } + ts.chain = chain; + function compose(a, b, c, d, e) { + if (e) { + var args_3 = []; + for (var i = 0; i < arguments.length; i++) { + args_3[i] = arguments[i]; + } + return function (t) { return reduceLeft(args_3, function (u, f) { return f(u); }, t); }; + } + else if (d) { + return function (t) { return d(c(b(a(t)))); }; + } + else if (c) { + return function (t) { return c(b(a(t))); }; + } + else if (b) { + return function (t) { return b(a(t)); }; + } + else if (a) { + return function (t) { return a(t); }; + } + else { + return function (t) { return t; }; + } + } + ts.compose = compose; + var AssertionLevel; + (function (AssertionLevel) { + AssertionLevel[AssertionLevel["None"] = 0] = "None"; + AssertionLevel[AssertionLevel["Normal"] = 1] = "Normal"; + AssertionLevel[AssertionLevel["Aggressive"] = 2] = "Aggressive"; + AssertionLevel[AssertionLevel["VeryAggressive"] = 3] = "VeryAggressive"; + })(AssertionLevel = ts.AssertionLevel || (ts.AssertionLevel = {})); + var Debug; + (function (Debug) { + Debug.currentAssertionLevel = 0 /* None */; + Debug.isDebugging = false; + function shouldAssert(level) { + return Debug.currentAssertionLevel >= level; + } + Debug.shouldAssert = shouldAssert; + function assert(expression, message, verboseDebugInfo, stackCrawlMark) { + if (!expression) { + if (verboseDebugInfo) { + message += "\r\nVerbose Debug Information: " + (typeof verboseDebugInfo === "string" ? verboseDebugInfo : verboseDebugInfo()); + } + fail(message ? "False expression: " + message : "False expression.", stackCrawlMark || assert); + } + } + Debug.assert = assert; + function assertEqual(a, b, msg, msg2) { + if (a !== b) { + var message = msg ? msg2 ? msg + " " + msg2 : msg : ""; + fail("Expected " + a + " === " + b + ". " + message); + } + } + Debug.assertEqual = assertEqual; + function assertLessThan(a, b, msg) { + if (a >= b) { + fail("Expected " + a + " < " + b + ". " + (msg || "")); + } + } + Debug.assertLessThan = assertLessThan; + function assertLessThanOrEqual(a, b) { + if (a > b) { + fail("Expected " + a + " <= " + b); + } + } + Debug.assertLessThanOrEqual = assertLessThanOrEqual; + function assertGreaterThanOrEqual(a, b) { + if (a < b) { + fail("Expected " + a + " >= " + b); + } + } + Debug.assertGreaterThanOrEqual = assertGreaterThanOrEqual; + function fail(message, stackCrawlMark) { + debugger; + var e = new Error(message ? "Debug Failure. " + message : "Debug Failure."); + if (Error.captureStackTrace) { + Error.captureStackTrace(e, stackCrawlMark || fail); + } + throw e; + } + Debug.fail = fail; + function assertDefined(value, message) { + if (value === undefined || value === null) + return fail(message); + return value; + } + Debug.assertDefined = assertDefined; + function assertEachDefined(value, message) { + for (var _i = 0, value_1 = value; _i < value_1.length; _i++) { + var v = value_1[_i]; + assertDefined(v, message); + } + return value; + } + Debug.assertEachDefined = assertEachDefined; + function assertNever(member, message, stackCrawlMark) { + if (message === void 0) { message = "Illegal value:"; } + var detail = "kind" in member && "pos" in member ? "SyntaxKind: " + Debug.showSyntaxKind(member) : JSON.stringify(member); + return fail(message + " " + detail, stackCrawlMark || assertNever); + } + Debug.assertNever = assertNever; + function getFunctionName(func) { + if (typeof func !== "function") { + return ""; + } + else if (func.hasOwnProperty("name")) { + return func.name; + } + else { + var text = Function.prototype.toString.call(func); + var match = /^function\s+([\w\$]+)\s*\(/.exec(text); + return match ? match[1] : ""; + } + } + Debug.getFunctionName = getFunctionName; + })(Debug = ts.Debug || (ts.Debug = {})); + function equateValues(a, b) { + return a === b; + } + ts.equateValues = equateValues; + /** + * Compare the equality of two strings using a case-sensitive ordinal comparison. + * + * Case-sensitive comparisons compare both strings one code-point at a time using the integer + * value of each code-point after applying `toUpperCase` to each string. We always map both + * strings to their upper-case form as some unicode characters do not properly round-trip to + * lowercase (such as `ẞ` (German sharp capital s)). + */ + function equateStringsCaseInsensitive(a, b) { + return a === b + || a !== undefined + && b !== undefined + && a.toUpperCase() === b.toUpperCase(); + } + ts.equateStringsCaseInsensitive = equateStringsCaseInsensitive; + /** + * Compare the equality of two strings using a case-sensitive ordinal comparison. + * + * Case-sensitive comparisons compare both strings one code-point at a time using the + * integer value of each code-point. + */ + function equateStringsCaseSensitive(a, b) { + return equateValues(a, b); + } + ts.equateStringsCaseSensitive = equateStringsCaseSensitive; + function compareComparableValues(a, b) { + return a === b ? 0 /* EqualTo */ : + a === undefined ? -1 /* LessThan */ : + b === undefined ? 1 /* GreaterThan */ : + a < b ? -1 /* LessThan */ : + 1 /* GreaterThan */; + } + /** + * Compare two numeric values for their order relative to each other. + * To compare strings, use any of the `compareStrings` functions. + */ + function compareValues(a, b) { + return compareComparableValues(a, b); + } + ts.compareValues = compareValues; + function min(a, b, compare) { + return compare(a, b) === -1 /* LessThan */ ? a : b; + } + ts.min = min; + /** + * Compare two strings using a case-insensitive ordinal comparison. + * + * Ordinal comparisons are based on the difference between the unicode code points of both + * strings. Characters with multiple unicode representations are considered unequal. Ordinal + * comparisons provide predictable ordering, but place "a" after "B". + * + * Case-insensitive comparisons compare both strings one code-point at a time using the integer + * value of each code-point after applying `toUpperCase` to each string. We always map both + * strings to their upper-case form as some unicode characters do not properly round-trip to + * lowercase (such as `ẞ` (German sharp capital s)). + */ + function compareStringsCaseInsensitive(a, b) { + if (a === b) + return 0 /* EqualTo */; + if (a === undefined) + return -1 /* LessThan */; + if (b === undefined) + return 1 /* GreaterThan */; + a = a.toUpperCase(); + b = b.toUpperCase(); + return a < b ? -1 /* LessThan */ : a > b ? 1 /* GreaterThan */ : 0 /* EqualTo */; + } + ts.compareStringsCaseInsensitive = compareStringsCaseInsensitive; + /** + * Compare two strings using a case-sensitive ordinal comparison. + * + * Ordinal comparisons are based on the difference between the unicode code points of both + * strings. Characters with multiple unicode representations are considered unequal. Ordinal + * comparisons provide predictable ordering, but place "a" after "B". + * + * Case-sensitive comparisons compare both strings one code-point at a time using the integer + * value of each code-point. + */ + function compareStringsCaseSensitive(a, b) { + return compareComparableValues(a, b); + } + ts.compareStringsCaseSensitive = compareStringsCaseSensitive; + function getStringComparer(ignoreCase) { + return ignoreCase ? compareStringsCaseInsensitive : compareStringsCaseSensitive; + } + ts.getStringComparer = getStringComparer; + /** + * Creates a string comparer for use with string collation in the UI. + */ + var createUIStringComparer = (function () { + var defaultComparer; + var enUSComparer; + var stringComparerFactory = getStringComparerFactory(); + return createStringComparer; + function compareWithCallback(a, b, comparer) { + if (a === b) + return 0 /* EqualTo */; + if (a === undefined) + return -1 /* LessThan */; + if (b === undefined) + return 1 /* GreaterThan */; + var value = comparer(a, b); + return value < 0 ? -1 /* LessThan */ : value > 0 ? 1 /* GreaterThan */ : 0 /* EqualTo */; + } + function createIntlCollatorStringComparer(locale) { + // Intl.Collator.prototype.compare is bound to the collator. See NOTE in + // http://www.ecma-international.org/ecma-402/2.0/#sec-Intl.Collator.prototype.compare + var comparer = new Intl.Collator(locale, { usage: "sort", sensitivity: "variant" }).compare; + return function (a, b) { return compareWithCallback(a, b, comparer); }; + } + function createLocaleCompareStringComparer(locale) { + // if the locale is not the default locale (`undefined`), use the fallback comparer. + if (locale !== undefined) + return createFallbackStringComparer(); + return function (a, b) { return compareWithCallback(a, b, compareStrings); }; + function compareStrings(a, b) { + return a.localeCompare(b); + } + } + function createFallbackStringComparer() { + // An ordinal comparison puts "A" after "b", but for the UI we want "A" before "b". + // We first sort case insensitively. So "Aaa" will come before "baa". + // Then we sort case sensitively, so "aaa" will come before "Aaa". + // + // For case insensitive comparisons we always map both strings to their + // upper-case form as some unicode characters do not properly round-trip to + // lowercase (such as `ẞ` (German sharp capital s)). + return function (a, b) { return compareWithCallback(a, b, compareDictionaryOrder); }; + function compareDictionaryOrder(a, b) { + return compareStrings(a.toUpperCase(), b.toUpperCase()) || compareStrings(a, b); + } + function compareStrings(a, b) { + return a < b ? -1 /* LessThan */ : a > b ? 1 /* GreaterThan */ : 0 /* EqualTo */; + } + } + function getStringComparerFactory() { + // If the host supports Intl, we use it for comparisons using the default locale. + if (typeof Intl === "object" && typeof Intl.Collator === "function") { + return createIntlCollatorStringComparer; + } + // If the host does not support Intl, we fall back to localeCompare. + // localeCompare in Node v0.10 is just an ordinal comparison, so don't use it. + if (typeof String.prototype.localeCompare === "function" && + typeof String.prototype.toLocaleUpperCase === "function" && + "a".localeCompare("B") < 0) { + return createLocaleCompareStringComparer; + } + // Otherwise, fall back to ordinal comparison: + return createFallbackStringComparer; + } + function createStringComparer(locale) { + // Hold onto common string comparers. This avoids constantly reallocating comparers during + // tests. + if (locale === undefined) { + return defaultComparer || (defaultComparer = stringComparerFactory(locale)); + } + else if (locale === "en-US") { + return enUSComparer || (enUSComparer = stringComparerFactory(locale)); + } + else { + return stringComparerFactory(locale); + } + } + })(); + var uiComparerCaseSensitive; + var uiLocale; + function getUILocale() { + return uiLocale; + } + ts.getUILocale = getUILocale; + function setUILocale(value) { + if (uiLocale !== value) { + uiLocale = value; + uiComparerCaseSensitive = undefined; + } + } + ts.setUILocale = setUILocale; + /** + * Compare two strings in a using the case-sensitive sort behavior of the UI locale. + * + * Ordering is not predictable between different host locales, but is best for displaying + * ordered data for UI presentation. Characters with multiple unicode representations may + * be considered equal. + * + * Case-sensitive comparisons compare strings that differ in base characters, or + * accents/diacritic marks, or case as unequal. + */ + function compareStringsCaseSensitiveUI(a, b) { + var comparer = uiComparerCaseSensitive || (uiComparerCaseSensitive = createUIStringComparer(uiLocale)); + return comparer(a, b); + } + ts.compareStringsCaseSensitiveUI = compareStringsCaseSensitiveUI; + function compareProperties(a, b, key, comparer) { + return a === b ? 0 /* EqualTo */ : + a === undefined ? -1 /* LessThan */ : + b === undefined ? 1 /* GreaterThan */ : + comparer(a[key], b[key]); + } + ts.compareProperties = compareProperties; + /** True is greater than false. */ + function compareBooleans(a, b) { + return compareValues(a ? 1 : 0, b ? 1 : 0); + } + ts.compareBooleans = compareBooleans; + /** + * Given a name and a list of names that are *not* equal to the name, return a spelling suggestion if there is one that is close enough. + * Names less than length 3 only check for case-insensitive equality, not Levenshtein distance. + * + * If there is a candidate that's the same except for case, return that. + * If there is a candidate that's within one edit of the name, return that. + * Otherwise, return the candidate with the smallest Levenshtein distance, + * except for candidates: + * * With no name + * * Whose length differs from the target name by more than 0.34 of the length of the name. + * * Whose levenshtein distance is more than 0.4 of the length of the name + * (0.4 allows 1 substitution/transposition for every 5 characters, + * and 1 insertion/deletion at 3 characters) + */ + function getSpellingSuggestion(name, candidates, getName) { + var maximumLengthDifference = Math.min(2, Math.floor(name.length * 0.34)); + var bestDistance = Math.floor(name.length * 0.4) + 1; // If the best result isn't better than this, don't bother. + var bestCandidate; + var justCheckExactMatches = false; + var nameLowerCase = name.toLowerCase(); + for (var _i = 0, candidates_1 = candidates; _i < candidates_1.length; _i++) { + var candidate = candidates_1[_i]; + var candidateName = getName(candidate); + if (candidateName !== undefined && Math.abs(candidateName.length - nameLowerCase.length) <= maximumLengthDifference) { + var candidateNameLowerCase = candidateName.toLowerCase(); + if (candidateNameLowerCase === nameLowerCase) { + if (candidateName === name) { + continue; + } + return candidate; + } + if (justCheckExactMatches) { + continue; + } + if (candidateName.length < 3) { + // Don't bother, user would have noticed a 2-character name having an extra character + continue; + } + // Only care about a result better than the best so far. + var distance = levenshteinWithMax(nameLowerCase, candidateNameLowerCase, bestDistance - 1); + if (distance === undefined) { + continue; + } + if (distance < 3) { + justCheckExactMatches = true; + bestCandidate = candidate; + } + else { + Debug.assert(distance < bestDistance); // Else `levenshteinWithMax` should return undefined + bestDistance = distance; + bestCandidate = candidate; + } + } + } + return bestCandidate; + } + ts.getSpellingSuggestion = getSpellingSuggestion; + function levenshteinWithMax(s1, s2, max) { + var previous = new Array(s2.length + 1); + var current = new Array(s2.length + 1); + /** Represents any value > max. We don't care about the particular value. */ + var big = max + 1; + for (var i = 0; i <= s2.length; i++) { + previous[i] = i; + } + for (var i = 1; i <= s1.length; i++) { + var c1 = s1.charCodeAt(i - 1); + var minJ = i > max ? i - max : 1; + var maxJ = s2.length > max + i ? max + i : s2.length; + current[0] = i; + /** Smallest value of the matrix in the ith column. */ + var colMin = i; + for (var j = 1; j < minJ; j++) { + current[j] = big; + } + for (var j = minJ; j <= maxJ; j++) { + var dist = c1 === s2.charCodeAt(j - 1) + ? previous[j - 1] + : Math.min(/*delete*/ previous[j] + 1, /*insert*/ current[j - 1] + 1, /*substitute*/ previous[j - 1] + 2); + current[j] = dist; + colMin = Math.min(colMin, dist); + } + for (var j = maxJ + 1; j <= s2.length; j++) { + current[j] = big; + } + if (colMin > max) { + // Give up -- everything in this column is > max and it can't get better in future columns. + return undefined; + } + var temp = previous; + previous = current; + current = temp; + } + var res = previous[s2.length]; + return res > max ? undefined : res; + } + function endsWith(str, suffix) { + var expectedPos = str.length - suffix.length; + return expectedPos >= 0 && str.indexOf(suffix, expectedPos) === expectedPos; + } + ts.endsWith = endsWith; + function removeSuffix(str, suffix) { + return endsWith(str, suffix) ? str.slice(0, str.length - suffix.length) : str; + } + ts.removeSuffix = removeSuffix; + function tryRemoveSuffix(str, suffix) { + return endsWith(str, suffix) ? str.slice(0, str.length - suffix.length) : undefined; + } + ts.tryRemoveSuffix = tryRemoveSuffix; + function stringContains(str, substring) { + return str.indexOf(substring) !== -1; + } + ts.stringContains = stringContains; + function fileExtensionIs(path, extension) { + return path.length > extension.length && endsWith(path, extension); + } + ts.fileExtensionIs = fileExtensionIs; + function fileExtensionIsOneOf(path, extensions) { + for (var _i = 0, extensions_1 = extensions; _i < extensions_1.length; _i++) { + var extension = extensions_1[_i]; + if (fileExtensionIs(path, extension)) { + return true; + } + } + return false; + } + ts.fileExtensionIsOneOf = fileExtensionIsOneOf; + /** + * Takes a string like "jquery-min.4.2.3" and returns "jquery" + */ + function removeMinAndVersionNumbers(fileName) { + // Match a "." or "-" followed by a version number or 'min' at the end of the name + var trailingMinOrVersion = /[.-]((min)|(\d+(\.\d+)*))$/; + // The "min" or version may both be present, in either order, so try applying the above twice. + return fileName.replace(trailingMinOrVersion, "").replace(trailingMinOrVersion, ""); + } + ts.removeMinAndVersionNumbers = removeMinAndVersionNumbers; + /** Remove an item from an array, moving everything to its right one space left. */ + function orderedRemoveItem(array, item) { + for (var i = 0; i < array.length; i++) { + if (array[i] === item) { + orderedRemoveItemAt(array, i); + return true; + } + } + return false; + } + ts.orderedRemoveItem = orderedRemoveItem; + /** Remove an item by index from an array, moving everything to its right one space left. */ + function orderedRemoveItemAt(array, index) { + // This seems to be faster than either `array.splice(i, 1)` or `array.copyWithin(i, i+ 1)`. + for (var i = index; i < array.length - 1; i++) { + array[i] = array[i + 1]; + } + array.pop(); + } + ts.orderedRemoveItemAt = orderedRemoveItemAt; + function unorderedRemoveItemAt(array, index) { + // Fill in the "hole" left at `index`. + array[index] = array[array.length - 1]; + array.pop(); + } + ts.unorderedRemoveItemAt = unorderedRemoveItemAt; + /** Remove the *first* occurrence of `item` from the array. */ + function unorderedRemoveItem(array, item) { + return unorderedRemoveFirstItemWhere(array, function (element) { return element === item; }); + } + ts.unorderedRemoveItem = unorderedRemoveItem; + /** Remove the *first* element satisfying `predicate`. */ + function unorderedRemoveFirstItemWhere(array, predicate) { + for (var i = 0; i < array.length; i++) { + if (predicate(array[i])) { + unorderedRemoveItemAt(array, i); + return true; + } + } + return false; + } + function createGetCanonicalFileName(useCaseSensitiveFileNames) { + return useCaseSensitiveFileNames ? identity : toLowerCase; + } + ts.createGetCanonicalFileName = createGetCanonicalFileName; + function patternText(_a) { + var prefix = _a.prefix, suffix = _a.suffix; + return prefix + "*" + suffix; + } + ts.patternText = patternText; + /** + * Given that candidate matches pattern, returns the text matching the '*'. + * E.g.: matchedText(tryParsePattern("foo*baz"), "foobarbaz") === "bar" + */ + function matchedText(pattern, candidate) { + Debug.assert(isPatternMatch(pattern, candidate)); + return candidate.substring(pattern.prefix.length, candidate.length - pattern.suffix.length); + } + ts.matchedText = matchedText; + /** Return the object corresponding to the best pattern to match `candidate`. */ + function findBestPatternMatch(values, getPattern, candidate) { + var matchedValue; + // use length of prefix as betterness criteria + var longestMatchPrefixLength = -1; + for (var _i = 0, values_2 = values; _i < values_2.length; _i++) { + var v = values_2[_i]; + var pattern = getPattern(v); + if (isPatternMatch(pattern, candidate) && pattern.prefix.length > longestMatchPrefixLength) { + longestMatchPrefixLength = pattern.prefix.length; + matchedValue = v; + } + } + return matchedValue; + } + ts.findBestPatternMatch = findBestPatternMatch; + function startsWith(str, prefix) { + return str.lastIndexOf(prefix, 0) === 0; + } + ts.startsWith = startsWith; + function removePrefix(str, prefix) { + return startsWith(str, prefix) ? str.substr(prefix.length) : str; + } + ts.removePrefix = removePrefix; + function tryRemovePrefix(str, prefix, getCanonicalFileName) { + if (getCanonicalFileName === void 0) { getCanonicalFileName = identity; } + return startsWith(getCanonicalFileName(str), getCanonicalFileName(prefix)) ? str.substring(prefix.length) : undefined; + } + ts.tryRemovePrefix = tryRemovePrefix; + function isPatternMatch(_a, candidate) { + var prefix = _a.prefix, suffix = _a.suffix; + return candidate.length >= prefix.length + suffix.length && + startsWith(candidate, prefix) && + endsWith(candidate, suffix); + } + function and(f, g) { + return function (arg) { return f(arg) && g(arg); }; + } + ts.and = and; + function or(f, g) { + return function (arg) { return f(arg) || g(arg); }; + } + ts.or = or; + function assertType(_) { } // tslint:disable-line no-empty + ts.assertType = assertType; + function singleElementArray(t) { + return t === undefined ? undefined : [t]; + } + ts.singleElementArray = singleElementArray; + function enumerateInsertsAndDeletes(newItems, oldItems, comparer, inserted, deleted, unchanged) { + unchanged = unchanged || noop; + var newIndex = 0; + var oldIndex = 0; + var newLen = newItems.length; + var oldLen = oldItems.length; + while (newIndex < newLen && oldIndex < oldLen) { + var newItem = newItems[newIndex]; + var oldItem = oldItems[oldIndex]; + var compareResult = comparer(newItem, oldItem); + if (compareResult === -1 /* LessThan */) { + inserted(newItem); + newIndex++; + } + else if (compareResult === 1 /* GreaterThan */) { + deleted(oldItem); + oldIndex++; + } + else { + unchanged(oldItem, newItem); + newIndex++; + oldIndex++; + } + } + while (newIndex < newLen) { + inserted(newItems[newIndex++]); + } + while (oldIndex < oldLen) { + deleted(oldItems[oldIndex++]); + } + } + ts.enumerateInsertsAndDeletes = enumerateInsertsAndDeletes; + function fill(length, cb) { + return new Array(length).fill(0).map(function (_, i) { return cb(i); }); + } + ts.fill = fill; +})(ts || (ts = {})); +/*@internal*/ +var ts; +(function (ts) { + /** Gets a timestamp with (at least) ms resolution */ + ts.timestamp = typeof performance !== "undefined" && performance.now ? function () { return performance.now(); } : Date.now ? Date.now : function () { return +(new Date()); }; +})(ts || (ts = {})); +/*@internal*/ +/** Performance measurements for the compiler. */ +(function (ts) { + var performance; + (function (performance) { + // NOTE: cannot use ts.noop as core.ts loads after this + var profilerEvent = typeof onProfilerEvent === "function" && onProfilerEvent.profiler === true ? onProfilerEvent : function () { }; + var enabled = false; + var profilerStart = 0; + var counts; + var marks; + var measures; + function createTimerIf(condition, measureName, startMarkName, endMarkName) { + return condition ? createTimer(measureName, startMarkName, endMarkName) : performance.nullTimer; + } + performance.createTimerIf = createTimerIf; + function createTimer(measureName, startMarkName, endMarkName) { + var enterCount = 0; + return { + enter: enter, + exit: exit + }; + function enter() { + if (++enterCount === 1) { + mark(startMarkName); + } + } + function exit() { + if (--enterCount === 0) { + mark(endMarkName); + measure(measureName, startMarkName, endMarkName); + } + else if (enterCount < 0) { + ts.Debug.fail("enter/exit count does not match."); + } + } + } + performance.createTimer = createTimer; + performance.nullTimer = { enter: ts.noop, exit: ts.noop }; + /** + * Marks a performance event. + * + * @param markName The name of the mark. + */ + function mark(markName) { + if (enabled) { + marks.set(markName, ts.timestamp()); + counts.set(markName, (counts.get(markName) || 0) + 1); + profilerEvent(markName); + } + } + performance.mark = mark; + /** + * Adds a performance measurement with the specified name. + * + * @param measureName The name of the performance measurement. + * @param startMarkName The name of the starting mark. If not supplied, the point at which the + * profiler was enabled is used. + * @param endMarkName The name of the ending mark. If not supplied, the current timestamp is + * used. + */ + function measure(measureName, startMarkName, endMarkName) { + if (enabled) { + var end = endMarkName && marks.get(endMarkName) || ts.timestamp(); + var start = startMarkName && marks.get(startMarkName) || profilerStart; + measures.set(measureName, (measures.get(measureName) || 0) + (end - start)); + } + } + performance.measure = measure; + /** + * Gets the number of times a marker was encountered. + * + * @param markName The name of the mark. + */ + function getCount(markName) { + return counts && counts.get(markName) || 0; + } + performance.getCount = getCount; + /** + * Gets the total duration of all measurements with the supplied name. + * + * @param measureName The name of the measure whose durations should be accumulated. + */ + function getDuration(measureName) { + return measures && measures.get(measureName) || 0; + } + performance.getDuration = getDuration; + /** + * Iterate over each measure, performing some action + * + * @param cb The action to perform for each measure + */ + function forEachMeasure(cb) { + measures.forEach(function (measure, key) { + cb(key, measure); + }); + } + performance.forEachMeasure = forEachMeasure; + /** Enables (and resets) performance measurements for the compiler. */ + function enable() { + counts = ts.createMap(); + marks = ts.createMap(); + measures = ts.createMap(); + enabled = true; + profilerStart = ts.timestamp(); + } + performance.enable = enable; + /** Disables performance measurements for the compiler. */ + function disable() { + enabled = false; + } + performance.disable = disable; + })(performance = ts.performance || (ts.performance = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + // https://semver.org/#spec-item-2 + // > A normal version number MUST take the form X.Y.Z where X, Y, and Z are non-negative + // > integers, and MUST NOT contain leading zeroes. X is the major version, Y is the minor + // > version, and Z is the patch version. Each element MUST increase numerically. + // + // NOTE: We differ here in that we allow X and X.Y, with missing parts having the default + // value of `0`. + var versionRegExp = /^(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\-([a-z0-9-.]+))?(?:\+([a-z0-9-.]+))?)?)?$/i; + // https://semver.org/#spec-item-9 + // > A pre-release version MAY be denoted by appending a hyphen and a series of dot separated + // > identifiers immediately following the patch version. Identifiers MUST comprise only ASCII + // > alphanumerics and hyphen [0-9A-Za-z-]. Identifiers MUST NOT be empty. Numeric identifiers + // > MUST NOT include leading zeroes. + var prereleaseRegExp = /^(?:0|[1-9]\d*|[a-z-][a-z0-9-]*)(?:\.(?:0|[1-9]\d*|[a-z-][a-z0-9-]*))*$/i; + // https://semver.org/#spec-item-10 + // > Build metadata MAY be denoted by appending a plus sign and a series of dot separated + // > identifiers immediately following the patch or pre-release version. Identifiers MUST + // > comprise only ASCII alphanumerics and hyphen [0-9A-Za-z-]. Identifiers MUST NOT be empty. + var buildRegExp = /^[a-z0-9-]+(?:\.[a-z0-9-]+)*$/i; + // https://semver.org/#spec-item-9 + // > Numeric identifiers MUST NOT include leading zeroes. + var numericIdentifierRegExp = /^(0|[1-9]\d*)$/; + /** + * Describes a precise semantic version number, https://semver.org + */ + var Version = /** @class */ (function () { + function Version(major, minor, patch, prerelease, build) { + if (minor === void 0) { minor = 0; } + if (patch === void 0) { patch = 0; } + if (prerelease === void 0) { prerelease = ""; } + if (build === void 0) { build = ""; } + if (typeof major === "string") { + var result = ts.Debug.assertDefined(tryParseComponents(major), "Invalid version"); + (major = result.major, minor = result.minor, patch = result.patch, prerelease = result.prerelease, build = result.build); + } + ts.Debug.assert(major >= 0, "Invalid argument: major"); + ts.Debug.assert(minor >= 0, "Invalid argument: minor"); + ts.Debug.assert(patch >= 0, "Invalid argument: patch"); + ts.Debug.assert(!prerelease || prereleaseRegExp.test(prerelease), "Invalid argument: prerelease"); + ts.Debug.assert(!build || buildRegExp.test(build), "Invalid argument: build"); + this.major = major; + this.minor = minor; + this.patch = patch; + this.prerelease = prerelease ? prerelease.split(".") : ts.emptyArray; + this.build = build ? build.split(".") : ts.emptyArray; + } + Version.tryParse = function (text) { + var result = tryParseComponents(text); + if (!result) + return undefined; + var major = result.major, minor = result.minor, patch = result.patch, prerelease = result.prerelease, build = result.build; + return new Version(major, minor, patch, prerelease, build); + }; + Version.prototype.compareTo = function (other) { + // https://semver.org/#spec-item-11 + // > Precedence is determined by the first difference when comparing each of these + // > identifiers from left to right as follows: Major, minor, and patch versions are + // > always compared numerically. + // + // https://semver.org/#spec-item-11 + // > Precedence for two pre-release versions with the same major, minor, and patch version + // > MUST be determined by comparing each dot separated identifier from left to right until + // > a difference is found [...] + // + // https://semver.org/#spec-item-11 + // > Build metadata does not figure into precedence + if (this === other) + return 0 /* EqualTo */; + if (other === undefined) + return 1 /* GreaterThan */; + return ts.compareValues(this.major, other.major) + || ts.compareValues(this.minor, other.minor) + || ts.compareValues(this.patch, other.patch) + || comparePrerelaseIdentifiers(this.prerelease, other.prerelease); + }; + Version.prototype.increment = function (field) { + switch (field) { + case "major": return new Version(this.major + 1, 0, 0); + case "minor": return new Version(this.major, this.minor + 1, 0); + case "patch": return new Version(this.major, this.minor, this.patch + 1); + default: return ts.Debug.assertNever(field); + } + }; + Version.prototype.toString = function () { + var result = this.major + "." + this.minor + "." + this.patch; + if (ts.some(this.prerelease)) + result += "-" + this.prerelease.join("."); + if (ts.some(this.build)) + result += "+" + this.build.join("."); + return result; + }; + Version.zero = new Version(0, 0, 0); + return Version; + }()); + ts.Version = Version; + function tryParseComponents(text) { + var match = versionRegExp.exec(text); + if (!match) + return undefined; + var major = match[1], _a = match[2], minor = _a === void 0 ? "0" : _a, _b = match[3], patch = _b === void 0 ? "0" : _b, _c = match[4], prerelease = _c === void 0 ? "" : _c, _d = match[5], build = _d === void 0 ? "" : _d; + if (prerelease && !prereleaseRegExp.test(prerelease)) + return undefined; + if (build && !buildRegExp.test(build)) + return undefined; + return { + major: parseInt(major, 10), + minor: parseInt(minor, 10), + patch: parseInt(patch, 10), + prerelease: prerelease, + build: build + }; + } + function comparePrerelaseIdentifiers(left, right) { + // https://semver.org/#spec-item-11 + // > When major, minor, and patch are equal, a pre-release version has lower precedence + // > than a normal version. + if (left === right) + return 0 /* EqualTo */; + if (left.length === 0) + return right.length === 0 ? 0 /* EqualTo */ : 1 /* GreaterThan */; + if (right.length === 0) + return -1 /* LessThan */; + // https://semver.org/#spec-item-11 + // > Precedence for two pre-release versions with the same major, minor, and patch version + // > MUST be determined by comparing each dot separated identifier from left to right until + // > a difference is found [...] + var length = Math.min(left.length, right.length); + for (var i = 0; i < length; i++) { + var leftIdentifier = left[i]; + var rightIdentifier = right[i]; + if (leftIdentifier === rightIdentifier) + continue; + var leftIsNumeric = numericIdentifierRegExp.test(leftIdentifier); + var rightIsNumeric = numericIdentifierRegExp.test(rightIdentifier); + if (leftIsNumeric || rightIsNumeric) { + // https://semver.org/#spec-item-11 + // > Numeric identifiers always have lower precedence than non-numeric identifiers. + if (leftIsNumeric !== rightIsNumeric) + return leftIsNumeric ? -1 /* LessThan */ : 1 /* GreaterThan */; + // https://semver.org/#spec-item-11 + // > identifiers consisting of only digits are compared numerically + var result = ts.compareValues(+leftIdentifier, +rightIdentifier); + if (result) + return result; + } + else { + // https://semver.org/#spec-item-11 + // > identifiers with letters or hyphens are compared lexically in ASCII sort order. + var result = ts.compareStringsCaseSensitive(leftIdentifier, rightIdentifier); + if (result) + return result; + } + } + // https://semver.org/#spec-item-11 + // > A larger set of pre-release fields has a higher precedence than a smaller set, if all + // > of the preceding identifiers are equal. + return ts.compareValues(left.length, right.length); + } + /** + * Describes a semantic version range, per https://github.com/npm/node-semver#ranges + */ + var VersionRange = /** @class */ (function () { + function VersionRange(spec) { + this._alternatives = spec ? ts.Debug.assertDefined(parseRange(spec), "Invalid range spec.") : ts.emptyArray; + } + VersionRange.tryParse = function (text) { + var sets = parseRange(text); + if (sets) { + var range = new VersionRange(""); + range._alternatives = sets; + return range; + } + return undefined; + }; + VersionRange.prototype.test = function (version) { + if (typeof version === "string") + version = new Version(version); + return testDisjunction(version, this._alternatives); + }; + VersionRange.prototype.toString = function () { + return formatDisjunction(this._alternatives); + }; + return VersionRange; + }()); + ts.VersionRange = VersionRange; + // https://github.com/npm/node-semver#range-grammar + // + // range-set ::= range ( logical-or range ) * + // range ::= hyphen | simple ( ' ' simple ) * | '' + // logical-or ::= ( ' ' ) * '||' ( ' ' ) * + var logicalOrRegExp = /\s*\|\|\s*/g; + var whitespaceRegExp = /\s+/g; + // https://github.com/npm/node-semver#range-grammar + // + // partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )? + // xr ::= 'x' | 'X' | '*' | nr + // nr ::= '0' | ['1'-'9'] ( ['0'-'9'] ) * + // qualifier ::= ( '-' pre )? ( '+' build )? + // pre ::= parts + // build ::= parts + // parts ::= part ( '.' part ) * + // part ::= nr | [-0-9A-Za-z]+ + var partialRegExp = /^([xX*0]|[1-9]\d*)(?:\.([xX*0]|[1-9]\d*)(?:\.([xX*0]|[1-9]\d*)(?:-([a-z0-9-.]+))?(?:\+([a-z0-9-.]+))?)?)?$/i; + // https://github.com/npm/node-semver#range-grammar + // + // hyphen ::= partial ' - ' partial + var hyphenRegExp = /^\s*([a-z0-9-+.*]+)\s+-\s+([a-z0-9-+.*]+)\s*$/i; + // https://github.com/npm/node-semver#range-grammar + // + // simple ::= primitive | partial | tilde | caret + // primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial + // tilde ::= '~' partial + // caret ::= '^' partial + var rangeRegExp = /^\s*(~|\^|<|<=|>|>=|=)?\s*([a-z0-9-+.*]+)$/i; + function parseRange(text) { + var alternatives = []; + for (var _i = 0, _a = text.trim().split(logicalOrRegExp); _i < _a.length; _i++) { + var range = _a[_i]; + if (!range) + continue; + var comparators = []; + var match = hyphenRegExp.exec(range); + if (match) { + if (!parseHyphen(match[1], match[2], comparators)) + return undefined; + } + else { + for (var _b = 0, _c = range.split(whitespaceRegExp); _b < _c.length; _b++) { + var simple = _c[_b]; + var match_1 = rangeRegExp.exec(simple); + if (!match_1 || !parseComparator(match_1[1], match_1[2], comparators)) + return undefined; + } + } + alternatives.push(comparators); + } + return alternatives; + } + function parsePartial(text) { + var match = partialRegExp.exec(text); + if (!match) + return undefined; + var major = match[1], _a = match[2], minor = _a === void 0 ? "*" : _a, _b = match[3], patch = _b === void 0 ? "*" : _b, prerelease = match[4], build = match[5]; + var version = new Version(isWildcard(major) ? 0 : parseInt(major, 10), isWildcard(major) || isWildcard(minor) ? 0 : parseInt(minor, 10), isWildcard(major) || isWildcard(minor) || isWildcard(patch) ? 0 : parseInt(patch, 10), prerelease, build); + return { version: version, major: major, minor: minor, patch: patch }; + } + function parseHyphen(left, right, comparators) { + var leftResult = parsePartial(left); + if (!leftResult) + return false; + var rightResult = parsePartial(right); + if (!rightResult) + return false; + if (!isWildcard(leftResult.major)) { + comparators.push(createComparator(">=", leftResult.version)); + } + if (!isWildcard(rightResult.major)) { + comparators.push(isWildcard(rightResult.minor) ? createComparator("<", rightResult.version.increment("major")) : + isWildcard(rightResult.patch) ? createComparator("<", rightResult.version.increment("minor")) : + createComparator("<=", rightResult.version)); + } + return true; + } + function parseComparator(operator, text, comparators) { + var result = parsePartial(text); + if (!result) + return false; + var version = result.version, major = result.major, minor = result.minor, patch = result.patch; + if (!isWildcard(major)) { + switch (operator) { + case "~": + comparators.push(createComparator(">=", version)); + comparators.push(createComparator("<", version.increment(isWildcard(minor) ? "major" : + "minor"))); + break; + case "^": + comparators.push(createComparator(">=", version)); + comparators.push(createComparator("<", version.increment(version.major > 0 || isWildcard(minor) ? "major" : + version.minor > 0 || isWildcard(patch) ? "minor" : + "patch"))); + break; + case "<": + case ">=": + comparators.push(createComparator(operator, version)); + break; + case "<=": + case ">": + comparators.push(isWildcard(minor) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("major")) : + isWildcard(patch) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("minor")) : + createComparator(operator, version)); + break; + case "=": + case undefined: + if (isWildcard(minor) || isWildcard(patch)) { + comparators.push(createComparator(">=", version)); + comparators.push(createComparator("<", version.increment(isWildcard(minor) ? "major" : "minor"))); + } + else { + comparators.push(createComparator("=", version)); + } + break; + default: + // unrecognized + return false; + } + } + else if (operator === "<" || operator === ">") { + comparators.push(createComparator("<", Version.zero)); + } + return true; + } + function isWildcard(part) { + return part === "*" || part === "x" || part === "X"; + } + function createComparator(operator, operand) { + return { operator: operator, operand: operand }; + } + function testDisjunction(version, alternatives) { + // an empty disjunction is treated as "*" (all versions) + if (alternatives.length === 0) + return true; + for (var _i = 0, alternatives_1 = alternatives; _i < alternatives_1.length; _i++) { + var alternative = alternatives_1[_i]; + if (testAlternative(version, alternative)) + return true; + } + return false; + } + function testAlternative(version, comparators) { + for (var _i = 0, comparators_1 = comparators; _i < comparators_1.length; _i++) { + var comparator = comparators_1[_i]; + if (!testComparator(version, comparator.operator, comparator.operand)) + return false; + } + return true; + } + function testComparator(version, operator, operand) { + var cmp = version.compareTo(operand); + switch (operator) { + case "<": return cmp < 0; + case "<=": return cmp <= 0; + case ">": return cmp > 0; + case ">=": return cmp >= 0; + case "=": return cmp === 0; + default: return ts.Debug.assertNever(operator); + } + } + function formatDisjunction(alternatives) { + return ts.map(alternatives, formatAlternative).join(" || ") || "*"; + } + function formatAlternative(comparators) { + return ts.map(comparators, formatComparator).join(" "); + } + function formatComparator(comparator) { + return "" + comparator.operator + comparator.operand; + } +})(ts || (ts = {})); +var ts; +(function (ts) { + // token > SyntaxKind.Identifier => token is a keyword + // Also, If you add a new SyntaxKind be sure to keep the `Markers` section at the bottom in sync + var SyntaxKind; + (function (SyntaxKind) { + SyntaxKind[SyntaxKind["Unknown"] = 0] = "Unknown"; + SyntaxKind[SyntaxKind["EndOfFileToken"] = 1] = "EndOfFileToken"; + SyntaxKind[SyntaxKind["SingleLineCommentTrivia"] = 2] = "SingleLineCommentTrivia"; + SyntaxKind[SyntaxKind["MultiLineCommentTrivia"] = 3] = "MultiLineCommentTrivia"; + SyntaxKind[SyntaxKind["NewLineTrivia"] = 4] = "NewLineTrivia"; + SyntaxKind[SyntaxKind["WhitespaceTrivia"] = 5] = "WhitespaceTrivia"; + // We detect and preserve #! on the first line + SyntaxKind[SyntaxKind["ShebangTrivia"] = 6] = "ShebangTrivia"; + // We detect and provide better error recovery when we encounter a git merge marker. This + // allows us to edit files with git-conflict markers in them in a much more pleasant manner. + SyntaxKind[SyntaxKind["ConflictMarkerTrivia"] = 7] = "ConflictMarkerTrivia"; + // Literals + SyntaxKind[SyntaxKind["NumericLiteral"] = 8] = "NumericLiteral"; + SyntaxKind[SyntaxKind["BigIntLiteral"] = 9] = "BigIntLiteral"; + SyntaxKind[SyntaxKind["StringLiteral"] = 10] = "StringLiteral"; + SyntaxKind[SyntaxKind["JsxText"] = 11] = "JsxText"; + SyntaxKind[SyntaxKind["JsxTextAllWhiteSpaces"] = 12] = "JsxTextAllWhiteSpaces"; + SyntaxKind[SyntaxKind["RegularExpressionLiteral"] = 13] = "RegularExpressionLiteral"; + SyntaxKind[SyntaxKind["NoSubstitutionTemplateLiteral"] = 14] = "NoSubstitutionTemplateLiteral"; + // Pseudo-literals + SyntaxKind[SyntaxKind["TemplateHead"] = 15] = "TemplateHead"; + SyntaxKind[SyntaxKind["TemplateMiddle"] = 16] = "TemplateMiddle"; + SyntaxKind[SyntaxKind["TemplateTail"] = 17] = "TemplateTail"; + // Punctuation + SyntaxKind[SyntaxKind["OpenBraceToken"] = 18] = "OpenBraceToken"; + SyntaxKind[SyntaxKind["CloseBraceToken"] = 19] = "CloseBraceToken"; + SyntaxKind[SyntaxKind["OpenParenToken"] = 20] = "OpenParenToken"; + SyntaxKind[SyntaxKind["CloseParenToken"] = 21] = "CloseParenToken"; + SyntaxKind[SyntaxKind["OpenBracketToken"] = 22] = "OpenBracketToken"; + SyntaxKind[SyntaxKind["CloseBracketToken"] = 23] = "CloseBracketToken"; + SyntaxKind[SyntaxKind["DotToken"] = 24] = "DotToken"; + SyntaxKind[SyntaxKind["DotDotDotToken"] = 25] = "DotDotDotToken"; + SyntaxKind[SyntaxKind["SemicolonToken"] = 26] = "SemicolonToken"; + SyntaxKind[SyntaxKind["CommaToken"] = 27] = "CommaToken"; + SyntaxKind[SyntaxKind["LessThanToken"] = 28] = "LessThanToken"; + SyntaxKind[SyntaxKind["LessThanSlashToken"] = 29] = "LessThanSlashToken"; + SyntaxKind[SyntaxKind["GreaterThanToken"] = 30] = "GreaterThanToken"; + SyntaxKind[SyntaxKind["LessThanEqualsToken"] = 31] = "LessThanEqualsToken"; + SyntaxKind[SyntaxKind["GreaterThanEqualsToken"] = 32] = "GreaterThanEqualsToken"; + SyntaxKind[SyntaxKind["EqualsEqualsToken"] = 33] = "EqualsEqualsToken"; + SyntaxKind[SyntaxKind["ExclamationEqualsToken"] = 34] = "ExclamationEqualsToken"; + SyntaxKind[SyntaxKind["EqualsEqualsEqualsToken"] = 35] = "EqualsEqualsEqualsToken"; + SyntaxKind[SyntaxKind["ExclamationEqualsEqualsToken"] = 36] = "ExclamationEqualsEqualsToken"; + SyntaxKind[SyntaxKind["EqualsGreaterThanToken"] = 37] = "EqualsGreaterThanToken"; + SyntaxKind[SyntaxKind["PlusToken"] = 38] = "PlusToken"; + SyntaxKind[SyntaxKind["MinusToken"] = 39] = "MinusToken"; + SyntaxKind[SyntaxKind["AsteriskToken"] = 40] = "AsteriskToken"; + SyntaxKind[SyntaxKind["AsteriskAsteriskToken"] = 41] = "AsteriskAsteriskToken"; + SyntaxKind[SyntaxKind["SlashToken"] = 42] = "SlashToken"; + SyntaxKind[SyntaxKind["PercentToken"] = 43] = "PercentToken"; + SyntaxKind[SyntaxKind["PlusPlusToken"] = 44] = "PlusPlusToken"; + SyntaxKind[SyntaxKind["MinusMinusToken"] = 45] = "MinusMinusToken"; + SyntaxKind[SyntaxKind["LessThanLessThanToken"] = 46] = "LessThanLessThanToken"; + SyntaxKind[SyntaxKind["GreaterThanGreaterThanToken"] = 47] = "GreaterThanGreaterThanToken"; + SyntaxKind[SyntaxKind["GreaterThanGreaterThanGreaterThanToken"] = 48] = "GreaterThanGreaterThanGreaterThanToken"; + SyntaxKind[SyntaxKind["AmpersandToken"] = 49] = "AmpersandToken"; + SyntaxKind[SyntaxKind["BarToken"] = 50] = "BarToken"; + SyntaxKind[SyntaxKind["CaretToken"] = 51] = "CaretToken"; + SyntaxKind[SyntaxKind["ExclamationToken"] = 52] = "ExclamationToken"; + SyntaxKind[SyntaxKind["TildeToken"] = 53] = "TildeToken"; + SyntaxKind[SyntaxKind["AmpersandAmpersandToken"] = 54] = "AmpersandAmpersandToken"; + SyntaxKind[SyntaxKind["BarBarToken"] = 55] = "BarBarToken"; + SyntaxKind[SyntaxKind["QuestionToken"] = 56] = "QuestionToken"; + SyntaxKind[SyntaxKind["ColonToken"] = 57] = "ColonToken"; + SyntaxKind[SyntaxKind["AtToken"] = 58] = "AtToken"; + // Assignments + SyntaxKind[SyntaxKind["EqualsToken"] = 59] = "EqualsToken"; + SyntaxKind[SyntaxKind["PlusEqualsToken"] = 60] = "PlusEqualsToken"; + SyntaxKind[SyntaxKind["MinusEqualsToken"] = 61] = "MinusEqualsToken"; + SyntaxKind[SyntaxKind["AsteriskEqualsToken"] = 62] = "AsteriskEqualsToken"; + SyntaxKind[SyntaxKind["AsteriskAsteriskEqualsToken"] = 63] = "AsteriskAsteriskEqualsToken"; + SyntaxKind[SyntaxKind["SlashEqualsToken"] = 64] = "SlashEqualsToken"; + SyntaxKind[SyntaxKind["PercentEqualsToken"] = 65] = "PercentEqualsToken"; + SyntaxKind[SyntaxKind["LessThanLessThanEqualsToken"] = 66] = "LessThanLessThanEqualsToken"; + SyntaxKind[SyntaxKind["GreaterThanGreaterThanEqualsToken"] = 67] = "GreaterThanGreaterThanEqualsToken"; + SyntaxKind[SyntaxKind["GreaterThanGreaterThanGreaterThanEqualsToken"] = 68] = "GreaterThanGreaterThanGreaterThanEqualsToken"; + SyntaxKind[SyntaxKind["AmpersandEqualsToken"] = 69] = "AmpersandEqualsToken"; + SyntaxKind[SyntaxKind["BarEqualsToken"] = 70] = "BarEqualsToken"; + SyntaxKind[SyntaxKind["CaretEqualsToken"] = 71] = "CaretEqualsToken"; + // Identifiers + SyntaxKind[SyntaxKind["Identifier"] = 72] = "Identifier"; + // Reserved words + SyntaxKind[SyntaxKind["BreakKeyword"] = 73] = "BreakKeyword"; + SyntaxKind[SyntaxKind["CaseKeyword"] = 74] = "CaseKeyword"; + SyntaxKind[SyntaxKind["CatchKeyword"] = 75] = "CatchKeyword"; + SyntaxKind[SyntaxKind["ClassKeyword"] = 76] = "ClassKeyword"; + SyntaxKind[SyntaxKind["ConstKeyword"] = 77] = "ConstKeyword"; + SyntaxKind[SyntaxKind["ContinueKeyword"] = 78] = "ContinueKeyword"; + SyntaxKind[SyntaxKind["DebuggerKeyword"] = 79] = "DebuggerKeyword"; + SyntaxKind[SyntaxKind["DefaultKeyword"] = 80] = "DefaultKeyword"; + SyntaxKind[SyntaxKind["DeleteKeyword"] = 81] = "DeleteKeyword"; + SyntaxKind[SyntaxKind["DoKeyword"] = 82] = "DoKeyword"; + SyntaxKind[SyntaxKind["ElseKeyword"] = 83] = "ElseKeyword"; + SyntaxKind[SyntaxKind["EnumKeyword"] = 84] = "EnumKeyword"; + SyntaxKind[SyntaxKind["ExportKeyword"] = 85] = "ExportKeyword"; + SyntaxKind[SyntaxKind["ExtendsKeyword"] = 86] = "ExtendsKeyword"; + SyntaxKind[SyntaxKind["FalseKeyword"] = 87] = "FalseKeyword"; + SyntaxKind[SyntaxKind["FinallyKeyword"] = 88] = "FinallyKeyword"; + SyntaxKind[SyntaxKind["ForKeyword"] = 89] = "ForKeyword"; + SyntaxKind[SyntaxKind["FunctionKeyword"] = 90] = "FunctionKeyword"; + SyntaxKind[SyntaxKind["IfKeyword"] = 91] = "IfKeyword"; + SyntaxKind[SyntaxKind["ImportKeyword"] = 92] = "ImportKeyword"; + SyntaxKind[SyntaxKind["InKeyword"] = 93] = "InKeyword"; + SyntaxKind[SyntaxKind["InstanceOfKeyword"] = 94] = "InstanceOfKeyword"; + SyntaxKind[SyntaxKind["NewKeyword"] = 95] = "NewKeyword"; + SyntaxKind[SyntaxKind["NullKeyword"] = 96] = "NullKeyword"; + SyntaxKind[SyntaxKind["ReturnKeyword"] = 97] = "ReturnKeyword"; + SyntaxKind[SyntaxKind["SuperKeyword"] = 98] = "SuperKeyword"; + SyntaxKind[SyntaxKind["SwitchKeyword"] = 99] = "SwitchKeyword"; + SyntaxKind[SyntaxKind["ThisKeyword"] = 100] = "ThisKeyword"; + SyntaxKind[SyntaxKind["ThrowKeyword"] = 101] = "ThrowKeyword"; + SyntaxKind[SyntaxKind["TrueKeyword"] = 102] = "TrueKeyword"; + SyntaxKind[SyntaxKind["TryKeyword"] = 103] = "TryKeyword"; + SyntaxKind[SyntaxKind["TypeOfKeyword"] = 104] = "TypeOfKeyword"; + SyntaxKind[SyntaxKind["VarKeyword"] = 105] = "VarKeyword"; + SyntaxKind[SyntaxKind["VoidKeyword"] = 106] = "VoidKeyword"; + SyntaxKind[SyntaxKind["WhileKeyword"] = 107] = "WhileKeyword"; + SyntaxKind[SyntaxKind["WithKeyword"] = 108] = "WithKeyword"; + // Strict mode reserved words + SyntaxKind[SyntaxKind["ImplementsKeyword"] = 109] = "ImplementsKeyword"; + SyntaxKind[SyntaxKind["InterfaceKeyword"] = 110] = "InterfaceKeyword"; + SyntaxKind[SyntaxKind["LetKeyword"] = 111] = "LetKeyword"; + SyntaxKind[SyntaxKind["PackageKeyword"] = 112] = "PackageKeyword"; + SyntaxKind[SyntaxKind["PrivateKeyword"] = 113] = "PrivateKeyword"; + SyntaxKind[SyntaxKind["ProtectedKeyword"] = 114] = "ProtectedKeyword"; + SyntaxKind[SyntaxKind["PublicKeyword"] = 115] = "PublicKeyword"; + SyntaxKind[SyntaxKind["StaticKeyword"] = 116] = "StaticKeyword"; + SyntaxKind[SyntaxKind["YieldKeyword"] = 117] = "YieldKeyword"; + // Contextual keywords + SyntaxKind[SyntaxKind["AbstractKeyword"] = 118] = "AbstractKeyword"; + SyntaxKind[SyntaxKind["AsKeyword"] = 119] = "AsKeyword"; + SyntaxKind[SyntaxKind["AnyKeyword"] = 120] = "AnyKeyword"; + SyntaxKind[SyntaxKind["AsyncKeyword"] = 121] = "AsyncKeyword"; + SyntaxKind[SyntaxKind["AwaitKeyword"] = 122] = "AwaitKeyword"; + SyntaxKind[SyntaxKind["BooleanKeyword"] = 123] = "BooleanKeyword"; + SyntaxKind[SyntaxKind["ConstructorKeyword"] = 124] = "ConstructorKeyword"; + SyntaxKind[SyntaxKind["DeclareKeyword"] = 125] = "DeclareKeyword"; + SyntaxKind[SyntaxKind["GetKeyword"] = 126] = "GetKeyword"; + SyntaxKind[SyntaxKind["InferKeyword"] = 127] = "InferKeyword"; + SyntaxKind[SyntaxKind["IsKeyword"] = 128] = "IsKeyword"; + SyntaxKind[SyntaxKind["KeyOfKeyword"] = 129] = "KeyOfKeyword"; + SyntaxKind[SyntaxKind["ModuleKeyword"] = 130] = "ModuleKeyword"; + SyntaxKind[SyntaxKind["NamespaceKeyword"] = 131] = "NamespaceKeyword"; + SyntaxKind[SyntaxKind["NeverKeyword"] = 132] = "NeverKeyword"; + SyntaxKind[SyntaxKind["ReadonlyKeyword"] = 133] = "ReadonlyKeyword"; + SyntaxKind[SyntaxKind["RequireKeyword"] = 134] = "RequireKeyword"; + SyntaxKind[SyntaxKind["NumberKeyword"] = 135] = "NumberKeyword"; + SyntaxKind[SyntaxKind["ObjectKeyword"] = 136] = "ObjectKeyword"; + SyntaxKind[SyntaxKind["SetKeyword"] = 137] = "SetKeyword"; + SyntaxKind[SyntaxKind["StringKeyword"] = 138] = "StringKeyword"; + SyntaxKind[SyntaxKind["SymbolKeyword"] = 139] = "SymbolKeyword"; + SyntaxKind[SyntaxKind["TypeKeyword"] = 140] = "TypeKeyword"; + SyntaxKind[SyntaxKind["UndefinedKeyword"] = 141] = "UndefinedKeyword"; + SyntaxKind[SyntaxKind["UniqueKeyword"] = 142] = "UniqueKeyword"; + SyntaxKind[SyntaxKind["UnknownKeyword"] = 143] = "UnknownKeyword"; + SyntaxKind[SyntaxKind["FromKeyword"] = 144] = "FromKeyword"; + SyntaxKind[SyntaxKind["GlobalKeyword"] = 145] = "GlobalKeyword"; + SyntaxKind[SyntaxKind["BigIntKeyword"] = 146] = "BigIntKeyword"; + SyntaxKind[SyntaxKind["OfKeyword"] = 147] = "OfKeyword"; + // Parse tree nodes + // Names + SyntaxKind[SyntaxKind["QualifiedName"] = 148] = "QualifiedName"; + SyntaxKind[SyntaxKind["ComputedPropertyName"] = 149] = "ComputedPropertyName"; + // Signature elements + SyntaxKind[SyntaxKind["TypeParameter"] = 150] = "TypeParameter"; + SyntaxKind[SyntaxKind["Parameter"] = 151] = "Parameter"; + SyntaxKind[SyntaxKind["Decorator"] = 152] = "Decorator"; + // TypeMember + SyntaxKind[SyntaxKind["PropertySignature"] = 153] = "PropertySignature"; + SyntaxKind[SyntaxKind["PropertyDeclaration"] = 154] = "PropertyDeclaration"; + SyntaxKind[SyntaxKind["MethodSignature"] = 155] = "MethodSignature"; + SyntaxKind[SyntaxKind["MethodDeclaration"] = 156] = "MethodDeclaration"; + SyntaxKind[SyntaxKind["Constructor"] = 157] = "Constructor"; + SyntaxKind[SyntaxKind["GetAccessor"] = 158] = "GetAccessor"; + SyntaxKind[SyntaxKind["SetAccessor"] = 159] = "SetAccessor"; + SyntaxKind[SyntaxKind["CallSignature"] = 160] = "CallSignature"; + SyntaxKind[SyntaxKind["ConstructSignature"] = 161] = "ConstructSignature"; + SyntaxKind[SyntaxKind["IndexSignature"] = 162] = "IndexSignature"; + // Type + SyntaxKind[SyntaxKind["TypePredicate"] = 163] = "TypePredicate"; + SyntaxKind[SyntaxKind["TypeReference"] = 164] = "TypeReference"; + SyntaxKind[SyntaxKind["FunctionType"] = 165] = "FunctionType"; + SyntaxKind[SyntaxKind["ConstructorType"] = 166] = "ConstructorType"; + SyntaxKind[SyntaxKind["TypeQuery"] = 167] = "TypeQuery"; + SyntaxKind[SyntaxKind["TypeLiteral"] = 168] = "TypeLiteral"; + SyntaxKind[SyntaxKind["ArrayType"] = 169] = "ArrayType"; + SyntaxKind[SyntaxKind["TupleType"] = 170] = "TupleType"; + SyntaxKind[SyntaxKind["OptionalType"] = 171] = "OptionalType"; + SyntaxKind[SyntaxKind["RestType"] = 172] = "RestType"; + SyntaxKind[SyntaxKind["UnionType"] = 173] = "UnionType"; + SyntaxKind[SyntaxKind["IntersectionType"] = 174] = "IntersectionType"; + SyntaxKind[SyntaxKind["ConditionalType"] = 175] = "ConditionalType"; + SyntaxKind[SyntaxKind["InferType"] = 176] = "InferType"; + SyntaxKind[SyntaxKind["ParenthesizedType"] = 177] = "ParenthesizedType"; + SyntaxKind[SyntaxKind["ThisType"] = 178] = "ThisType"; + SyntaxKind[SyntaxKind["TypeOperator"] = 179] = "TypeOperator"; + SyntaxKind[SyntaxKind["IndexedAccessType"] = 180] = "IndexedAccessType"; + SyntaxKind[SyntaxKind["MappedType"] = 181] = "MappedType"; + SyntaxKind[SyntaxKind["LiteralType"] = 182] = "LiteralType"; + SyntaxKind[SyntaxKind["ImportType"] = 183] = "ImportType"; + // Binding patterns + SyntaxKind[SyntaxKind["ObjectBindingPattern"] = 184] = "ObjectBindingPattern"; + SyntaxKind[SyntaxKind["ArrayBindingPattern"] = 185] = "ArrayBindingPattern"; + SyntaxKind[SyntaxKind["BindingElement"] = 186] = "BindingElement"; + // Expression + SyntaxKind[SyntaxKind["ArrayLiteralExpression"] = 187] = "ArrayLiteralExpression"; + SyntaxKind[SyntaxKind["ObjectLiteralExpression"] = 188] = "ObjectLiteralExpression"; + SyntaxKind[SyntaxKind["PropertyAccessExpression"] = 189] = "PropertyAccessExpression"; + SyntaxKind[SyntaxKind["ElementAccessExpression"] = 190] = "ElementAccessExpression"; + SyntaxKind[SyntaxKind["CallExpression"] = 191] = "CallExpression"; + SyntaxKind[SyntaxKind["NewExpression"] = 192] = "NewExpression"; + SyntaxKind[SyntaxKind["TaggedTemplateExpression"] = 193] = "TaggedTemplateExpression"; + SyntaxKind[SyntaxKind["TypeAssertionExpression"] = 194] = "TypeAssertionExpression"; + SyntaxKind[SyntaxKind["ParenthesizedExpression"] = 195] = "ParenthesizedExpression"; + SyntaxKind[SyntaxKind["FunctionExpression"] = 196] = "FunctionExpression"; + SyntaxKind[SyntaxKind["ArrowFunction"] = 197] = "ArrowFunction"; + SyntaxKind[SyntaxKind["DeleteExpression"] = 198] = "DeleteExpression"; + SyntaxKind[SyntaxKind["TypeOfExpression"] = 199] = "TypeOfExpression"; + SyntaxKind[SyntaxKind["VoidExpression"] = 200] = "VoidExpression"; + SyntaxKind[SyntaxKind["AwaitExpression"] = 201] = "AwaitExpression"; + SyntaxKind[SyntaxKind["PrefixUnaryExpression"] = 202] = "PrefixUnaryExpression"; + SyntaxKind[SyntaxKind["PostfixUnaryExpression"] = 203] = "PostfixUnaryExpression"; + SyntaxKind[SyntaxKind["BinaryExpression"] = 204] = "BinaryExpression"; + SyntaxKind[SyntaxKind["ConditionalExpression"] = 205] = "ConditionalExpression"; + SyntaxKind[SyntaxKind["TemplateExpression"] = 206] = "TemplateExpression"; + SyntaxKind[SyntaxKind["YieldExpression"] = 207] = "YieldExpression"; + SyntaxKind[SyntaxKind["SpreadElement"] = 208] = "SpreadElement"; + SyntaxKind[SyntaxKind["ClassExpression"] = 209] = "ClassExpression"; + SyntaxKind[SyntaxKind["OmittedExpression"] = 210] = "OmittedExpression"; + SyntaxKind[SyntaxKind["ExpressionWithTypeArguments"] = 211] = "ExpressionWithTypeArguments"; + SyntaxKind[SyntaxKind["AsExpression"] = 212] = "AsExpression"; + SyntaxKind[SyntaxKind["NonNullExpression"] = 213] = "NonNullExpression"; + SyntaxKind[SyntaxKind["MetaProperty"] = 214] = "MetaProperty"; + SyntaxKind[SyntaxKind["SyntheticExpression"] = 215] = "SyntheticExpression"; + // Misc + SyntaxKind[SyntaxKind["TemplateSpan"] = 216] = "TemplateSpan"; + SyntaxKind[SyntaxKind["SemicolonClassElement"] = 217] = "SemicolonClassElement"; + // Element + SyntaxKind[SyntaxKind["Block"] = 218] = "Block"; + SyntaxKind[SyntaxKind["VariableStatement"] = 219] = "VariableStatement"; + SyntaxKind[SyntaxKind["EmptyStatement"] = 220] = "EmptyStatement"; + SyntaxKind[SyntaxKind["ExpressionStatement"] = 221] = "ExpressionStatement"; + SyntaxKind[SyntaxKind["IfStatement"] = 222] = "IfStatement"; + SyntaxKind[SyntaxKind["DoStatement"] = 223] = "DoStatement"; + SyntaxKind[SyntaxKind["WhileStatement"] = 224] = "WhileStatement"; + SyntaxKind[SyntaxKind["ForStatement"] = 225] = "ForStatement"; + SyntaxKind[SyntaxKind["ForInStatement"] = 226] = "ForInStatement"; + SyntaxKind[SyntaxKind["ForOfStatement"] = 227] = "ForOfStatement"; + SyntaxKind[SyntaxKind["ContinueStatement"] = 228] = "ContinueStatement"; + SyntaxKind[SyntaxKind["BreakStatement"] = 229] = "BreakStatement"; + SyntaxKind[SyntaxKind["ReturnStatement"] = 230] = "ReturnStatement"; + SyntaxKind[SyntaxKind["WithStatement"] = 231] = "WithStatement"; + SyntaxKind[SyntaxKind["SwitchStatement"] = 232] = "SwitchStatement"; + SyntaxKind[SyntaxKind["LabeledStatement"] = 233] = "LabeledStatement"; + SyntaxKind[SyntaxKind["ThrowStatement"] = 234] = "ThrowStatement"; + SyntaxKind[SyntaxKind["TryStatement"] = 235] = "TryStatement"; + SyntaxKind[SyntaxKind["DebuggerStatement"] = 236] = "DebuggerStatement"; + SyntaxKind[SyntaxKind["VariableDeclaration"] = 237] = "VariableDeclaration"; + SyntaxKind[SyntaxKind["VariableDeclarationList"] = 238] = "VariableDeclarationList"; + SyntaxKind[SyntaxKind["FunctionDeclaration"] = 239] = "FunctionDeclaration"; + SyntaxKind[SyntaxKind["ClassDeclaration"] = 240] = "ClassDeclaration"; + SyntaxKind[SyntaxKind["InterfaceDeclaration"] = 241] = "InterfaceDeclaration"; + SyntaxKind[SyntaxKind["TypeAliasDeclaration"] = 242] = "TypeAliasDeclaration"; + SyntaxKind[SyntaxKind["EnumDeclaration"] = 243] = "EnumDeclaration"; + SyntaxKind[SyntaxKind["ModuleDeclaration"] = 244] = "ModuleDeclaration"; + SyntaxKind[SyntaxKind["ModuleBlock"] = 245] = "ModuleBlock"; + SyntaxKind[SyntaxKind["CaseBlock"] = 246] = "CaseBlock"; + SyntaxKind[SyntaxKind["NamespaceExportDeclaration"] = 247] = "NamespaceExportDeclaration"; + SyntaxKind[SyntaxKind["ImportEqualsDeclaration"] = 248] = "ImportEqualsDeclaration"; + SyntaxKind[SyntaxKind["ImportDeclaration"] = 249] = "ImportDeclaration"; + SyntaxKind[SyntaxKind["ImportClause"] = 250] = "ImportClause"; + SyntaxKind[SyntaxKind["NamespaceImport"] = 251] = "NamespaceImport"; + SyntaxKind[SyntaxKind["NamedImports"] = 252] = "NamedImports"; + SyntaxKind[SyntaxKind["ImportSpecifier"] = 253] = "ImportSpecifier"; + SyntaxKind[SyntaxKind["ExportAssignment"] = 254] = "ExportAssignment"; + SyntaxKind[SyntaxKind["ExportDeclaration"] = 255] = "ExportDeclaration"; + SyntaxKind[SyntaxKind["NamedExports"] = 256] = "NamedExports"; + SyntaxKind[SyntaxKind["ExportSpecifier"] = 257] = "ExportSpecifier"; + SyntaxKind[SyntaxKind["MissingDeclaration"] = 258] = "MissingDeclaration"; + // Module references + SyntaxKind[SyntaxKind["ExternalModuleReference"] = 259] = "ExternalModuleReference"; + // JSX + SyntaxKind[SyntaxKind["JsxElement"] = 260] = "JsxElement"; + SyntaxKind[SyntaxKind["JsxSelfClosingElement"] = 261] = "JsxSelfClosingElement"; + SyntaxKind[SyntaxKind["JsxOpeningElement"] = 262] = "JsxOpeningElement"; + SyntaxKind[SyntaxKind["JsxClosingElement"] = 263] = "JsxClosingElement"; + SyntaxKind[SyntaxKind["JsxFragment"] = 264] = "JsxFragment"; + SyntaxKind[SyntaxKind["JsxOpeningFragment"] = 265] = "JsxOpeningFragment"; + SyntaxKind[SyntaxKind["JsxClosingFragment"] = 266] = "JsxClosingFragment"; + SyntaxKind[SyntaxKind["JsxAttribute"] = 267] = "JsxAttribute"; + SyntaxKind[SyntaxKind["JsxAttributes"] = 268] = "JsxAttributes"; + SyntaxKind[SyntaxKind["JsxSpreadAttribute"] = 269] = "JsxSpreadAttribute"; + SyntaxKind[SyntaxKind["JsxExpression"] = 270] = "JsxExpression"; + // Clauses + SyntaxKind[SyntaxKind["CaseClause"] = 271] = "CaseClause"; + SyntaxKind[SyntaxKind["DefaultClause"] = 272] = "DefaultClause"; + SyntaxKind[SyntaxKind["HeritageClause"] = 273] = "HeritageClause"; + SyntaxKind[SyntaxKind["CatchClause"] = 274] = "CatchClause"; + // Property assignments + SyntaxKind[SyntaxKind["PropertyAssignment"] = 275] = "PropertyAssignment"; + SyntaxKind[SyntaxKind["ShorthandPropertyAssignment"] = 276] = "ShorthandPropertyAssignment"; + SyntaxKind[SyntaxKind["SpreadAssignment"] = 277] = "SpreadAssignment"; + // Enum + SyntaxKind[SyntaxKind["EnumMember"] = 278] = "EnumMember"; + // Top-level nodes + SyntaxKind[SyntaxKind["SourceFile"] = 279] = "SourceFile"; + SyntaxKind[SyntaxKind["Bundle"] = 280] = "Bundle"; + SyntaxKind[SyntaxKind["UnparsedSource"] = 281] = "UnparsedSource"; + SyntaxKind[SyntaxKind["InputFiles"] = 282] = "InputFiles"; + // JSDoc nodes + SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 283] = "JSDocTypeExpression"; + // The * type + SyntaxKind[SyntaxKind["JSDocAllType"] = 284] = "JSDocAllType"; + // The ? type + SyntaxKind[SyntaxKind["JSDocUnknownType"] = 285] = "JSDocUnknownType"; + SyntaxKind[SyntaxKind["JSDocNullableType"] = 286] = "JSDocNullableType"; + SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 287] = "JSDocNonNullableType"; + SyntaxKind[SyntaxKind["JSDocOptionalType"] = 288] = "JSDocOptionalType"; + SyntaxKind[SyntaxKind["JSDocFunctionType"] = 289] = "JSDocFunctionType"; + SyntaxKind[SyntaxKind["JSDocVariadicType"] = 290] = "JSDocVariadicType"; + SyntaxKind[SyntaxKind["JSDocComment"] = 291] = "JSDocComment"; + SyntaxKind[SyntaxKind["JSDocTypeLiteral"] = 292] = "JSDocTypeLiteral"; + SyntaxKind[SyntaxKind["JSDocSignature"] = 293] = "JSDocSignature"; + SyntaxKind[SyntaxKind["JSDocTag"] = 294] = "JSDocTag"; + SyntaxKind[SyntaxKind["JSDocAugmentsTag"] = 295] = "JSDocAugmentsTag"; + SyntaxKind[SyntaxKind["JSDocClassTag"] = 296] = "JSDocClassTag"; + SyntaxKind[SyntaxKind["JSDocCallbackTag"] = 297] = "JSDocCallbackTag"; + SyntaxKind[SyntaxKind["JSDocEnumTag"] = 298] = "JSDocEnumTag"; + SyntaxKind[SyntaxKind["JSDocParameterTag"] = 299] = "JSDocParameterTag"; + SyntaxKind[SyntaxKind["JSDocReturnTag"] = 300] = "JSDocReturnTag"; + SyntaxKind[SyntaxKind["JSDocThisTag"] = 301] = "JSDocThisTag"; + SyntaxKind[SyntaxKind["JSDocTypeTag"] = 302] = "JSDocTypeTag"; + SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 303] = "JSDocTemplateTag"; + SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 304] = "JSDocTypedefTag"; + SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 305] = "JSDocPropertyTag"; + // Synthesized list + SyntaxKind[SyntaxKind["SyntaxList"] = 306] = "SyntaxList"; + // Transformation nodes + SyntaxKind[SyntaxKind["NotEmittedStatement"] = 307] = "NotEmittedStatement"; + SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 308] = "PartiallyEmittedExpression"; + SyntaxKind[SyntaxKind["CommaListExpression"] = 309] = "CommaListExpression"; + SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 310] = "MergeDeclarationMarker"; + SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 311] = "EndOfDeclarationMarker"; + // Enum value count + SyntaxKind[SyntaxKind["Count"] = 312] = "Count"; + // Markers + SyntaxKind[SyntaxKind["FirstAssignment"] = 59] = "FirstAssignment"; + SyntaxKind[SyntaxKind["LastAssignment"] = 71] = "LastAssignment"; + SyntaxKind[SyntaxKind["FirstCompoundAssignment"] = 60] = "FirstCompoundAssignment"; + SyntaxKind[SyntaxKind["LastCompoundAssignment"] = 71] = "LastCompoundAssignment"; + SyntaxKind[SyntaxKind["FirstReservedWord"] = 73] = "FirstReservedWord"; + SyntaxKind[SyntaxKind["LastReservedWord"] = 108] = "LastReservedWord"; + SyntaxKind[SyntaxKind["FirstKeyword"] = 73] = "FirstKeyword"; + SyntaxKind[SyntaxKind["LastKeyword"] = 147] = "LastKeyword"; + SyntaxKind[SyntaxKind["FirstFutureReservedWord"] = 109] = "FirstFutureReservedWord"; + SyntaxKind[SyntaxKind["LastFutureReservedWord"] = 117] = "LastFutureReservedWord"; + SyntaxKind[SyntaxKind["FirstTypeNode"] = 163] = "FirstTypeNode"; + SyntaxKind[SyntaxKind["LastTypeNode"] = 183] = "LastTypeNode"; + SyntaxKind[SyntaxKind["FirstPunctuation"] = 18] = "FirstPunctuation"; + SyntaxKind[SyntaxKind["LastPunctuation"] = 71] = "LastPunctuation"; + SyntaxKind[SyntaxKind["FirstToken"] = 0] = "FirstToken"; + SyntaxKind[SyntaxKind["LastToken"] = 147] = "LastToken"; + SyntaxKind[SyntaxKind["FirstTriviaToken"] = 2] = "FirstTriviaToken"; + SyntaxKind[SyntaxKind["LastTriviaToken"] = 7] = "LastTriviaToken"; + SyntaxKind[SyntaxKind["FirstLiteralToken"] = 8] = "FirstLiteralToken"; + SyntaxKind[SyntaxKind["LastLiteralToken"] = 14] = "LastLiteralToken"; + SyntaxKind[SyntaxKind["FirstTemplateToken"] = 14] = "FirstTemplateToken"; + SyntaxKind[SyntaxKind["LastTemplateToken"] = 17] = "LastTemplateToken"; + SyntaxKind[SyntaxKind["FirstBinaryOperator"] = 28] = "FirstBinaryOperator"; + SyntaxKind[SyntaxKind["LastBinaryOperator"] = 71] = "LastBinaryOperator"; + SyntaxKind[SyntaxKind["FirstNode"] = 148] = "FirstNode"; + SyntaxKind[SyntaxKind["FirstJSDocNode"] = 283] = "FirstJSDocNode"; + SyntaxKind[SyntaxKind["LastJSDocNode"] = 305] = "LastJSDocNode"; + SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 294] = "FirstJSDocTagNode"; + SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 305] = "LastJSDocTagNode"; + /* @internal */ SyntaxKind[SyntaxKind["FirstContextualKeyword"] = 118] = "FirstContextualKeyword"; + /* @internal */ SyntaxKind[SyntaxKind["LastContextualKeyword"] = 147] = "LastContextualKeyword"; + })(SyntaxKind = ts.SyntaxKind || (ts.SyntaxKind = {})); + var NodeFlags; + (function (NodeFlags) { + NodeFlags[NodeFlags["None"] = 0] = "None"; + NodeFlags[NodeFlags["Let"] = 1] = "Let"; + NodeFlags[NodeFlags["Const"] = 2] = "Const"; + NodeFlags[NodeFlags["NestedNamespace"] = 4] = "NestedNamespace"; + NodeFlags[NodeFlags["Synthesized"] = 8] = "Synthesized"; + NodeFlags[NodeFlags["Namespace"] = 16] = "Namespace"; + NodeFlags[NodeFlags["ExportContext"] = 32] = "ExportContext"; + NodeFlags[NodeFlags["ContainsThis"] = 64] = "ContainsThis"; + NodeFlags[NodeFlags["HasImplicitReturn"] = 128] = "HasImplicitReturn"; + NodeFlags[NodeFlags["HasExplicitReturn"] = 256] = "HasExplicitReturn"; + NodeFlags[NodeFlags["GlobalAugmentation"] = 512] = "GlobalAugmentation"; + NodeFlags[NodeFlags["HasAsyncFunctions"] = 1024] = "HasAsyncFunctions"; + NodeFlags[NodeFlags["DisallowInContext"] = 2048] = "DisallowInContext"; + NodeFlags[NodeFlags["YieldContext"] = 4096] = "YieldContext"; + NodeFlags[NodeFlags["DecoratorContext"] = 8192] = "DecoratorContext"; + NodeFlags[NodeFlags["AwaitContext"] = 16384] = "AwaitContext"; + NodeFlags[NodeFlags["ThisNodeHasError"] = 32768] = "ThisNodeHasError"; + NodeFlags[NodeFlags["JavaScriptFile"] = 65536] = "JavaScriptFile"; + NodeFlags[NodeFlags["ThisNodeOrAnySubNodesHasError"] = 131072] = "ThisNodeOrAnySubNodesHasError"; + NodeFlags[NodeFlags["HasAggregatedChildData"] = 262144] = "HasAggregatedChildData"; + // These flags will be set when the parser encounters a dynamic import expression or 'import.meta' to avoid + // walking the tree if the flags are not set. However, these flags are just a approximation + // (hence why it's named "PossiblyContainsDynamicImport") because once set, the flags never get cleared. + // During editing, if a dynamic import is removed, incremental parsing will *NOT* clear this flag. + // This means that the tree will always be traversed during module resolution, or when looking for external module indicators. + // However, the removal operation should not occur often and in the case of the + // removal, it is likely that users will add the import anyway. + // The advantage of this approach is its simplicity. For the case of batch compilation, + // we guarantee that users won't have to pay the price of walking the tree if a dynamic import isn't used. + /* @internal */ NodeFlags[NodeFlags["PossiblyContainsDynamicImport"] = 524288] = "PossiblyContainsDynamicImport"; + /* @internal */ NodeFlags[NodeFlags["PossiblyContainsImportMeta"] = 1048576] = "PossiblyContainsImportMeta"; + NodeFlags[NodeFlags["JSDoc"] = 2097152] = "JSDoc"; + /* @internal */ NodeFlags[NodeFlags["Ambient"] = 4194304] = "Ambient"; + /* @internal */ NodeFlags[NodeFlags["InWithStatement"] = 8388608] = "InWithStatement"; + NodeFlags[NodeFlags["JsonFile"] = 16777216] = "JsonFile"; + NodeFlags[NodeFlags["BlockScoped"] = 3] = "BlockScoped"; + NodeFlags[NodeFlags["ReachabilityCheckFlags"] = 384] = "ReachabilityCheckFlags"; + NodeFlags[NodeFlags["ReachabilityAndEmitFlags"] = 1408] = "ReachabilityAndEmitFlags"; + // Parsing context flags + NodeFlags[NodeFlags["ContextFlags"] = 12679168] = "ContextFlags"; + // Exclude these flags when parsing a Type + NodeFlags[NodeFlags["TypeExcludesFlags"] = 20480] = "TypeExcludesFlags"; + // Represents all flags that are potentially set once and + // never cleared on SourceFiles which get re-used in between incremental parses. + // See the comment above on `PossiblyContainsDynamicImport` and `PossiblyContainsImportMeta`. + /* @internal */ NodeFlags[NodeFlags["PermanentlySetIncrementalFlags"] = 1572864] = "PermanentlySetIncrementalFlags"; + })(NodeFlags = ts.NodeFlags || (ts.NodeFlags = {})); + var ModifierFlags; + (function (ModifierFlags) { + ModifierFlags[ModifierFlags["None"] = 0] = "None"; + ModifierFlags[ModifierFlags["Export"] = 1] = "Export"; + ModifierFlags[ModifierFlags["Ambient"] = 2] = "Ambient"; + ModifierFlags[ModifierFlags["Public"] = 4] = "Public"; + ModifierFlags[ModifierFlags["Private"] = 8] = "Private"; + ModifierFlags[ModifierFlags["Protected"] = 16] = "Protected"; + ModifierFlags[ModifierFlags["Static"] = 32] = "Static"; + ModifierFlags[ModifierFlags["Readonly"] = 64] = "Readonly"; + ModifierFlags[ModifierFlags["Abstract"] = 128] = "Abstract"; + ModifierFlags[ModifierFlags["Async"] = 256] = "Async"; + ModifierFlags[ModifierFlags["Default"] = 512] = "Default"; + ModifierFlags[ModifierFlags["Const"] = 2048] = "Const"; + ModifierFlags[ModifierFlags["HasComputedFlags"] = 536870912] = "HasComputedFlags"; + ModifierFlags[ModifierFlags["AccessibilityModifier"] = 28] = "AccessibilityModifier"; + // Accessibility modifiers and 'readonly' can be attached to a parameter in a constructor to make it a property. + ModifierFlags[ModifierFlags["ParameterPropertyModifier"] = 92] = "ParameterPropertyModifier"; + ModifierFlags[ModifierFlags["NonPublicAccessibilityModifier"] = 24] = "NonPublicAccessibilityModifier"; + ModifierFlags[ModifierFlags["TypeScriptModifier"] = 2270] = "TypeScriptModifier"; + ModifierFlags[ModifierFlags["ExportDefault"] = 513] = "ExportDefault"; + ModifierFlags[ModifierFlags["All"] = 3071] = "All"; + })(ModifierFlags = ts.ModifierFlags || (ts.ModifierFlags = {})); + var JsxFlags; + (function (JsxFlags) { + JsxFlags[JsxFlags["None"] = 0] = "None"; + /** An element from a named property of the JSX.IntrinsicElements interface */ + JsxFlags[JsxFlags["IntrinsicNamedElement"] = 1] = "IntrinsicNamedElement"; + /** An element inferred from the string index signature of the JSX.IntrinsicElements interface */ + JsxFlags[JsxFlags["IntrinsicIndexedElement"] = 2] = "IntrinsicIndexedElement"; + JsxFlags[JsxFlags["IntrinsicElement"] = 3] = "IntrinsicElement"; + })(JsxFlags = ts.JsxFlags || (ts.JsxFlags = {})); + /* @internal */ + var RelationComparisonResult; + (function (RelationComparisonResult) { + RelationComparisonResult[RelationComparisonResult["Succeeded"] = 1] = "Succeeded"; + RelationComparisonResult[RelationComparisonResult["Failed"] = 2] = "Failed"; + RelationComparisonResult[RelationComparisonResult["FailedAndReported"] = 3] = "FailedAndReported"; + })(RelationComparisonResult = ts.RelationComparisonResult || (ts.RelationComparisonResult = {})); + /*@internal*/ + var GeneratedIdentifierFlags; + (function (GeneratedIdentifierFlags) { + // Kinds + GeneratedIdentifierFlags[GeneratedIdentifierFlags["None"] = 0] = "None"; + GeneratedIdentifierFlags[GeneratedIdentifierFlags["Auto"] = 1] = "Auto"; + GeneratedIdentifierFlags[GeneratedIdentifierFlags["Loop"] = 2] = "Loop"; + GeneratedIdentifierFlags[GeneratedIdentifierFlags["Unique"] = 3] = "Unique"; + GeneratedIdentifierFlags[GeneratedIdentifierFlags["Node"] = 4] = "Node"; + GeneratedIdentifierFlags[GeneratedIdentifierFlags["KindMask"] = 7] = "KindMask"; + // Flags + GeneratedIdentifierFlags[GeneratedIdentifierFlags["ReservedInNestedScopes"] = 8] = "ReservedInNestedScopes"; + GeneratedIdentifierFlags[GeneratedIdentifierFlags["Optimistic"] = 16] = "Optimistic"; + GeneratedIdentifierFlags[GeneratedIdentifierFlags["FileLevel"] = 32] = "FileLevel"; + })(GeneratedIdentifierFlags = ts.GeneratedIdentifierFlags || (ts.GeneratedIdentifierFlags = {})); + /* @internal */ + var TokenFlags; + (function (TokenFlags) { + TokenFlags[TokenFlags["None"] = 0] = "None"; + TokenFlags[TokenFlags["PrecedingLineBreak"] = 1] = "PrecedingLineBreak"; + TokenFlags[TokenFlags["PrecedingJSDocComment"] = 2] = "PrecedingJSDocComment"; + TokenFlags[TokenFlags["Unterminated"] = 4] = "Unterminated"; + TokenFlags[TokenFlags["ExtendedUnicodeEscape"] = 8] = "ExtendedUnicodeEscape"; + TokenFlags[TokenFlags["Scientific"] = 16] = "Scientific"; + TokenFlags[TokenFlags["Octal"] = 32] = "Octal"; + TokenFlags[TokenFlags["HexSpecifier"] = 64] = "HexSpecifier"; + TokenFlags[TokenFlags["BinarySpecifier"] = 128] = "BinarySpecifier"; + TokenFlags[TokenFlags["OctalSpecifier"] = 256] = "OctalSpecifier"; + TokenFlags[TokenFlags["ContainsSeparator"] = 512] = "ContainsSeparator"; + TokenFlags[TokenFlags["BinaryOrOctalSpecifier"] = 384] = "BinaryOrOctalSpecifier"; + TokenFlags[TokenFlags["NumericLiteralFlags"] = 1008] = "NumericLiteralFlags"; + })(TokenFlags = ts.TokenFlags || (ts.TokenFlags = {})); + var FlowFlags; + (function (FlowFlags) { + FlowFlags[FlowFlags["Unreachable"] = 1] = "Unreachable"; + FlowFlags[FlowFlags["Start"] = 2] = "Start"; + FlowFlags[FlowFlags["BranchLabel"] = 4] = "BranchLabel"; + FlowFlags[FlowFlags["LoopLabel"] = 8] = "LoopLabel"; + FlowFlags[FlowFlags["Assignment"] = 16] = "Assignment"; + FlowFlags[FlowFlags["TrueCondition"] = 32] = "TrueCondition"; + FlowFlags[FlowFlags["FalseCondition"] = 64] = "FalseCondition"; + FlowFlags[FlowFlags["SwitchClause"] = 128] = "SwitchClause"; + FlowFlags[FlowFlags["ArrayMutation"] = 256] = "ArrayMutation"; + FlowFlags[FlowFlags["Referenced"] = 512] = "Referenced"; + FlowFlags[FlowFlags["Shared"] = 1024] = "Shared"; + FlowFlags[FlowFlags["PreFinally"] = 2048] = "PreFinally"; + FlowFlags[FlowFlags["AfterFinally"] = 4096] = "AfterFinally"; + FlowFlags[FlowFlags["Label"] = 12] = "Label"; + FlowFlags[FlowFlags["Condition"] = 96] = "Condition"; + })(FlowFlags = ts.FlowFlags || (ts.FlowFlags = {})); + var OperationCanceledException = /** @class */ (function () { + function OperationCanceledException() { + } + return OperationCanceledException; + }()); + ts.OperationCanceledException = OperationCanceledException; + /* @internal */ + var StructureIsReused; + (function (StructureIsReused) { + StructureIsReused[StructureIsReused["Not"] = 0] = "Not"; + StructureIsReused[StructureIsReused["SafeModules"] = 1] = "SafeModules"; + StructureIsReused[StructureIsReused["Completely"] = 2] = "Completely"; + })(StructureIsReused = ts.StructureIsReused || (ts.StructureIsReused = {})); + /** Return code used by getEmitOutput function to indicate status of the function */ + var ExitStatus; + (function (ExitStatus) { + // Compiler ran successfully. Either this was a simple do-nothing compilation (for example, + // when -version or -help was provided, or this was a normal compilation, no diagnostics + // were produced, and all outputs were generated successfully. + ExitStatus[ExitStatus["Success"] = 0] = "Success"; + // Diagnostics were produced and because of them no code was generated. + ExitStatus[ExitStatus["DiagnosticsPresent_OutputsSkipped"] = 1] = "DiagnosticsPresent_OutputsSkipped"; + // Diagnostics were produced and outputs were generated in spite of them. + ExitStatus[ExitStatus["DiagnosticsPresent_OutputsGenerated"] = 2] = "DiagnosticsPresent_OutputsGenerated"; + })(ExitStatus = ts.ExitStatus || (ts.ExitStatus = {})); + /* @internal */ + var UnionReduction; + (function (UnionReduction) { + UnionReduction[UnionReduction["None"] = 0] = "None"; + UnionReduction[UnionReduction["Literal"] = 1] = "Literal"; + UnionReduction[UnionReduction["Subtype"] = 2] = "Subtype"; + })(UnionReduction = ts.UnionReduction || (ts.UnionReduction = {})); + // NOTE: If modifying this enum, must modify `TypeFormatFlags` too! + var NodeBuilderFlags; + (function (NodeBuilderFlags) { + NodeBuilderFlags[NodeBuilderFlags["None"] = 0] = "None"; + // Options + NodeBuilderFlags[NodeBuilderFlags["NoTruncation"] = 1] = "NoTruncation"; + NodeBuilderFlags[NodeBuilderFlags["WriteArrayAsGenericType"] = 2] = "WriteArrayAsGenericType"; + NodeBuilderFlags[NodeBuilderFlags["GenerateNamesForShadowedTypeParams"] = 4] = "GenerateNamesForShadowedTypeParams"; + NodeBuilderFlags[NodeBuilderFlags["UseStructuralFallback"] = 8] = "UseStructuralFallback"; + NodeBuilderFlags[NodeBuilderFlags["ForbidIndexedAccessSymbolReferences"] = 16] = "ForbidIndexedAccessSymbolReferences"; + NodeBuilderFlags[NodeBuilderFlags["WriteTypeArgumentsOfSignature"] = 32] = "WriteTypeArgumentsOfSignature"; + NodeBuilderFlags[NodeBuilderFlags["UseFullyQualifiedType"] = 64] = "UseFullyQualifiedType"; + NodeBuilderFlags[NodeBuilderFlags["UseOnlyExternalAliasing"] = 128] = "UseOnlyExternalAliasing"; + NodeBuilderFlags[NodeBuilderFlags["SuppressAnyReturnType"] = 256] = "SuppressAnyReturnType"; + NodeBuilderFlags[NodeBuilderFlags["WriteTypeParametersInQualifiedName"] = 512] = "WriteTypeParametersInQualifiedName"; + NodeBuilderFlags[NodeBuilderFlags["MultilineObjectLiterals"] = 1024] = "MultilineObjectLiterals"; + NodeBuilderFlags[NodeBuilderFlags["WriteClassExpressionAsTypeLiteral"] = 2048] = "WriteClassExpressionAsTypeLiteral"; + NodeBuilderFlags[NodeBuilderFlags["UseTypeOfFunction"] = 4096] = "UseTypeOfFunction"; + NodeBuilderFlags[NodeBuilderFlags["OmitParameterModifiers"] = 8192] = "OmitParameterModifiers"; + NodeBuilderFlags[NodeBuilderFlags["UseAliasDefinedOutsideCurrentScope"] = 16384] = "UseAliasDefinedOutsideCurrentScope"; + // Error handling + NodeBuilderFlags[NodeBuilderFlags["AllowThisInObjectLiteral"] = 32768] = "AllowThisInObjectLiteral"; + NodeBuilderFlags[NodeBuilderFlags["AllowQualifedNameInPlaceOfIdentifier"] = 65536] = "AllowQualifedNameInPlaceOfIdentifier"; + NodeBuilderFlags[NodeBuilderFlags["AllowAnonymousIdentifier"] = 131072] = "AllowAnonymousIdentifier"; + NodeBuilderFlags[NodeBuilderFlags["AllowEmptyUnionOrIntersection"] = 262144] = "AllowEmptyUnionOrIntersection"; + NodeBuilderFlags[NodeBuilderFlags["AllowEmptyTuple"] = 524288] = "AllowEmptyTuple"; + NodeBuilderFlags[NodeBuilderFlags["AllowUniqueESSymbolType"] = 1048576] = "AllowUniqueESSymbolType"; + NodeBuilderFlags[NodeBuilderFlags["AllowEmptyIndexInfoType"] = 2097152] = "AllowEmptyIndexInfoType"; + // Errors (cont.) + NodeBuilderFlags[NodeBuilderFlags["AllowNodeModulesRelativePaths"] = 67108864] = "AllowNodeModulesRelativePaths"; + /* @internal */ NodeBuilderFlags[NodeBuilderFlags["DoNotIncludeSymbolChain"] = 134217728] = "DoNotIncludeSymbolChain"; + NodeBuilderFlags[NodeBuilderFlags["IgnoreErrors"] = 70221824] = "IgnoreErrors"; + // State + NodeBuilderFlags[NodeBuilderFlags["InObjectTypeLiteral"] = 4194304] = "InObjectTypeLiteral"; + NodeBuilderFlags[NodeBuilderFlags["InTypeAlias"] = 8388608] = "InTypeAlias"; + NodeBuilderFlags[NodeBuilderFlags["InInitialEntityName"] = 16777216] = "InInitialEntityName"; + NodeBuilderFlags[NodeBuilderFlags["InReverseMappedType"] = 33554432] = "InReverseMappedType"; + })(NodeBuilderFlags = ts.NodeBuilderFlags || (ts.NodeBuilderFlags = {})); + // Ensure the shared flags between this and `NodeBuilderFlags` stay in alignment + var TypeFormatFlags; + (function (TypeFormatFlags) { + TypeFormatFlags[TypeFormatFlags["None"] = 0] = "None"; + TypeFormatFlags[TypeFormatFlags["NoTruncation"] = 1] = "NoTruncation"; + TypeFormatFlags[TypeFormatFlags["WriteArrayAsGenericType"] = 2] = "WriteArrayAsGenericType"; + // hole because there's a hole in node builder flags + TypeFormatFlags[TypeFormatFlags["UseStructuralFallback"] = 8] = "UseStructuralFallback"; + // hole because there's a hole in node builder flags + TypeFormatFlags[TypeFormatFlags["WriteTypeArgumentsOfSignature"] = 32] = "WriteTypeArgumentsOfSignature"; + TypeFormatFlags[TypeFormatFlags["UseFullyQualifiedType"] = 64] = "UseFullyQualifiedType"; + // hole because `UseOnlyExternalAliasing` is here in node builder flags, but functions which take old flags use `SymbolFormatFlags` instead + TypeFormatFlags[TypeFormatFlags["SuppressAnyReturnType"] = 256] = "SuppressAnyReturnType"; + // hole because `WriteTypeParametersInQualifiedName` is here in node builder flags, but functions which take old flags use `SymbolFormatFlags` for this instead + TypeFormatFlags[TypeFormatFlags["MultilineObjectLiterals"] = 1024] = "MultilineObjectLiterals"; + TypeFormatFlags[TypeFormatFlags["WriteClassExpressionAsTypeLiteral"] = 2048] = "WriteClassExpressionAsTypeLiteral"; + TypeFormatFlags[TypeFormatFlags["UseTypeOfFunction"] = 4096] = "UseTypeOfFunction"; + TypeFormatFlags[TypeFormatFlags["OmitParameterModifiers"] = 8192] = "OmitParameterModifiers"; + TypeFormatFlags[TypeFormatFlags["UseAliasDefinedOutsideCurrentScope"] = 16384] = "UseAliasDefinedOutsideCurrentScope"; + // even though `T` can't be accessed in the current scope. + // Error Handling + TypeFormatFlags[TypeFormatFlags["AllowUniqueESSymbolType"] = 1048576] = "AllowUniqueESSymbolType"; + // TypeFormatFlags exclusive + TypeFormatFlags[TypeFormatFlags["AddUndefined"] = 131072] = "AddUndefined"; + TypeFormatFlags[TypeFormatFlags["WriteArrowStyleSignature"] = 262144] = "WriteArrowStyleSignature"; + // State + TypeFormatFlags[TypeFormatFlags["InArrayType"] = 524288] = "InArrayType"; + TypeFormatFlags[TypeFormatFlags["InElementType"] = 2097152] = "InElementType"; + TypeFormatFlags[TypeFormatFlags["InFirstTypeArgument"] = 4194304] = "InFirstTypeArgument"; + TypeFormatFlags[TypeFormatFlags["InTypeAlias"] = 8388608] = "InTypeAlias"; + /** @deprecated */ TypeFormatFlags[TypeFormatFlags["WriteOwnNameForAnyLike"] = 0] = "WriteOwnNameForAnyLike"; + TypeFormatFlags[TypeFormatFlags["NodeBuilderFlagsMask"] = 9469291] = "NodeBuilderFlagsMask"; + })(TypeFormatFlags = ts.TypeFormatFlags || (ts.TypeFormatFlags = {})); + var SymbolFormatFlags; + (function (SymbolFormatFlags) { + SymbolFormatFlags[SymbolFormatFlags["None"] = 0] = "None"; + // Write symbols's type argument if it is instantiated symbol + // eg. class C { p: T } <-- Show p as C.p here + // var a: C; + // var p = a.p; <--- Here p is property of C so show it as C.p instead of just C.p + SymbolFormatFlags[SymbolFormatFlags["WriteTypeParametersOrArguments"] = 1] = "WriteTypeParametersOrArguments"; + // Use only external alias information to get the symbol name in the given context + // eg. module m { export class c { } } import x = m.c; + // When this flag is specified m.c will be used to refer to the class instead of alias symbol x + SymbolFormatFlags[SymbolFormatFlags["UseOnlyExternalAliasing"] = 2] = "UseOnlyExternalAliasing"; + // Build symbol name using any nodes needed, instead of just components of an entity name + SymbolFormatFlags[SymbolFormatFlags["AllowAnyNodeKind"] = 4] = "AllowAnyNodeKind"; + // Prefer aliases which are not directly visible + SymbolFormatFlags[SymbolFormatFlags["UseAliasDefinedOutsideCurrentScope"] = 8] = "UseAliasDefinedOutsideCurrentScope"; + // Skip building an accessible symbol chain + /* @internal */ SymbolFormatFlags[SymbolFormatFlags["DoNotIncludeSymbolChain"] = 16] = "DoNotIncludeSymbolChain"; + })(SymbolFormatFlags = ts.SymbolFormatFlags || (ts.SymbolFormatFlags = {})); + /* @internal */ + var SymbolAccessibility; + (function (SymbolAccessibility) { + SymbolAccessibility[SymbolAccessibility["Accessible"] = 0] = "Accessible"; + SymbolAccessibility[SymbolAccessibility["NotAccessible"] = 1] = "NotAccessible"; + SymbolAccessibility[SymbolAccessibility["CannotBeNamed"] = 2] = "CannotBeNamed"; + })(SymbolAccessibility = ts.SymbolAccessibility || (ts.SymbolAccessibility = {})); + /* @internal */ + var SyntheticSymbolKind; + (function (SyntheticSymbolKind) { + SyntheticSymbolKind[SyntheticSymbolKind["UnionOrIntersection"] = 0] = "UnionOrIntersection"; + SyntheticSymbolKind[SyntheticSymbolKind["Spread"] = 1] = "Spread"; + })(SyntheticSymbolKind = ts.SyntheticSymbolKind || (ts.SyntheticSymbolKind = {})); + var TypePredicateKind; + (function (TypePredicateKind) { + TypePredicateKind[TypePredicateKind["This"] = 0] = "This"; + TypePredicateKind[TypePredicateKind["Identifier"] = 1] = "Identifier"; + })(TypePredicateKind = ts.TypePredicateKind || (ts.TypePredicateKind = {})); + /** Indicates how to serialize the name for a TypeReferenceNode when emitting decorator metadata */ + /* @internal */ + var TypeReferenceSerializationKind; + (function (TypeReferenceSerializationKind) { + TypeReferenceSerializationKind[TypeReferenceSerializationKind["Unknown"] = 0] = "Unknown"; + // should be emitted using a safe fallback. + TypeReferenceSerializationKind[TypeReferenceSerializationKind["TypeWithConstructSignatureAndValue"] = 1] = "TypeWithConstructSignatureAndValue"; + // function that can be reached at runtime (e.g. a `class` + // declaration or a `var` declaration for the static side + // of a type, such as the global `Promise` type in lib.d.ts). + TypeReferenceSerializationKind[TypeReferenceSerializationKind["VoidNullableOrNeverType"] = 2] = "VoidNullableOrNeverType"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["NumberLikeType"] = 3] = "NumberLikeType"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["BigIntLikeType"] = 4] = "BigIntLikeType"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["StringLikeType"] = 5] = "StringLikeType"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["BooleanType"] = 6] = "BooleanType"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["ArrayLikeType"] = 7] = "ArrayLikeType"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["ESSymbolType"] = 8] = "ESSymbolType"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["Promise"] = 9] = "Promise"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["TypeWithCallSignature"] = 10] = "TypeWithCallSignature"; + // with call signatures. + TypeReferenceSerializationKind[TypeReferenceSerializationKind["ObjectType"] = 11] = "ObjectType"; + })(TypeReferenceSerializationKind = ts.TypeReferenceSerializationKind || (ts.TypeReferenceSerializationKind = {})); + var SymbolFlags; + (function (SymbolFlags) { + SymbolFlags[SymbolFlags["None"] = 0] = "None"; + SymbolFlags[SymbolFlags["FunctionScopedVariable"] = 1] = "FunctionScopedVariable"; + SymbolFlags[SymbolFlags["BlockScopedVariable"] = 2] = "BlockScopedVariable"; + SymbolFlags[SymbolFlags["Property"] = 4] = "Property"; + SymbolFlags[SymbolFlags["EnumMember"] = 8] = "EnumMember"; + SymbolFlags[SymbolFlags["Function"] = 16] = "Function"; + SymbolFlags[SymbolFlags["Class"] = 32] = "Class"; + SymbolFlags[SymbolFlags["Interface"] = 64] = "Interface"; + SymbolFlags[SymbolFlags["ConstEnum"] = 128] = "ConstEnum"; + SymbolFlags[SymbolFlags["RegularEnum"] = 256] = "RegularEnum"; + SymbolFlags[SymbolFlags["ValueModule"] = 512] = "ValueModule"; + SymbolFlags[SymbolFlags["NamespaceModule"] = 1024] = "NamespaceModule"; + SymbolFlags[SymbolFlags["TypeLiteral"] = 2048] = "TypeLiteral"; + SymbolFlags[SymbolFlags["ObjectLiteral"] = 4096] = "ObjectLiteral"; + SymbolFlags[SymbolFlags["Method"] = 8192] = "Method"; + SymbolFlags[SymbolFlags["Constructor"] = 16384] = "Constructor"; + SymbolFlags[SymbolFlags["GetAccessor"] = 32768] = "GetAccessor"; + SymbolFlags[SymbolFlags["SetAccessor"] = 65536] = "SetAccessor"; + SymbolFlags[SymbolFlags["Signature"] = 131072] = "Signature"; + SymbolFlags[SymbolFlags["TypeParameter"] = 262144] = "TypeParameter"; + SymbolFlags[SymbolFlags["TypeAlias"] = 524288] = "TypeAlias"; + SymbolFlags[SymbolFlags["ExportValue"] = 1048576] = "ExportValue"; + SymbolFlags[SymbolFlags["Alias"] = 2097152] = "Alias"; + SymbolFlags[SymbolFlags["Prototype"] = 4194304] = "Prototype"; + SymbolFlags[SymbolFlags["ExportStar"] = 8388608] = "ExportStar"; + SymbolFlags[SymbolFlags["Optional"] = 16777216] = "Optional"; + SymbolFlags[SymbolFlags["Transient"] = 33554432] = "Transient"; + SymbolFlags[SymbolFlags["Assignment"] = 67108864] = "Assignment"; + SymbolFlags[SymbolFlags["ModuleExports"] = 134217728] = "ModuleExports"; + /* @internal */ + SymbolFlags[SymbolFlags["All"] = 67108863] = "All"; + SymbolFlags[SymbolFlags["Enum"] = 384] = "Enum"; + SymbolFlags[SymbolFlags["Variable"] = 3] = "Variable"; + SymbolFlags[SymbolFlags["Value"] = 67220415] = "Value"; + SymbolFlags[SymbolFlags["Type"] = 67897832] = "Type"; + SymbolFlags[SymbolFlags["Namespace"] = 1920] = "Namespace"; + SymbolFlags[SymbolFlags["Module"] = 1536] = "Module"; + SymbolFlags[SymbolFlags["Accessor"] = 98304] = "Accessor"; + // Variables can be redeclared, but can not redeclare a block-scoped declaration with the + // same name, or any other value that is not a variable, e.g. ValueModule or Class + SymbolFlags[SymbolFlags["FunctionScopedVariableExcludes"] = 67220414] = "FunctionScopedVariableExcludes"; + // Block-scoped declarations are not allowed to be re-declared + // they can not merge with anything in the value space + SymbolFlags[SymbolFlags["BlockScopedVariableExcludes"] = 67220415] = "BlockScopedVariableExcludes"; + SymbolFlags[SymbolFlags["ParameterExcludes"] = 67220415] = "ParameterExcludes"; + SymbolFlags[SymbolFlags["PropertyExcludes"] = 0] = "PropertyExcludes"; + SymbolFlags[SymbolFlags["EnumMemberExcludes"] = 68008959] = "EnumMemberExcludes"; + SymbolFlags[SymbolFlags["FunctionExcludes"] = 67219887] = "FunctionExcludes"; + SymbolFlags[SymbolFlags["ClassExcludes"] = 68008383] = "ClassExcludes"; + SymbolFlags[SymbolFlags["InterfaceExcludes"] = 67897736] = "InterfaceExcludes"; + SymbolFlags[SymbolFlags["RegularEnumExcludes"] = 68008191] = "RegularEnumExcludes"; + SymbolFlags[SymbolFlags["ConstEnumExcludes"] = 68008831] = "ConstEnumExcludes"; + SymbolFlags[SymbolFlags["ValueModuleExcludes"] = 110735] = "ValueModuleExcludes"; + SymbolFlags[SymbolFlags["NamespaceModuleExcludes"] = 0] = "NamespaceModuleExcludes"; + SymbolFlags[SymbolFlags["MethodExcludes"] = 67212223] = "MethodExcludes"; + SymbolFlags[SymbolFlags["GetAccessorExcludes"] = 67154879] = "GetAccessorExcludes"; + SymbolFlags[SymbolFlags["SetAccessorExcludes"] = 67187647] = "SetAccessorExcludes"; + SymbolFlags[SymbolFlags["TypeParameterExcludes"] = 67635688] = "TypeParameterExcludes"; + SymbolFlags[SymbolFlags["TypeAliasExcludes"] = 67897832] = "TypeAliasExcludes"; + SymbolFlags[SymbolFlags["AliasExcludes"] = 2097152] = "AliasExcludes"; + SymbolFlags[SymbolFlags["ModuleMember"] = 2623475] = "ModuleMember"; + SymbolFlags[SymbolFlags["ExportHasLocal"] = 944] = "ExportHasLocal"; + SymbolFlags[SymbolFlags["BlockScoped"] = 418] = "BlockScoped"; + SymbolFlags[SymbolFlags["PropertyOrAccessor"] = 98308] = "PropertyOrAccessor"; + SymbolFlags[SymbolFlags["ClassMember"] = 106500] = "ClassMember"; + /* @internal */ + // The set of things we consider semantically classifiable. Used to speed up the LS during + // classification. + SymbolFlags[SymbolFlags["Classifiable"] = 2885600] = "Classifiable"; + /* @internal */ + SymbolFlags[SymbolFlags["LateBindingContainer"] = 6240] = "LateBindingContainer"; + })(SymbolFlags = ts.SymbolFlags || (ts.SymbolFlags = {})); + /* @internal */ + var EnumKind; + (function (EnumKind) { + EnumKind[EnumKind["Numeric"] = 0] = "Numeric"; + EnumKind[EnumKind["Literal"] = 1] = "Literal"; // Literal enum (each member has a TypeFlags.EnumLiteral type) + })(EnumKind = ts.EnumKind || (ts.EnumKind = {})); + /* @internal */ + var CheckFlags; + (function (CheckFlags) { + CheckFlags[CheckFlags["Instantiated"] = 1] = "Instantiated"; + CheckFlags[CheckFlags["SyntheticProperty"] = 2] = "SyntheticProperty"; + CheckFlags[CheckFlags["SyntheticMethod"] = 4] = "SyntheticMethod"; + CheckFlags[CheckFlags["Readonly"] = 8] = "Readonly"; + CheckFlags[CheckFlags["Partial"] = 16] = "Partial"; + CheckFlags[CheckFlags["HasNonUniformType"] = 32] = "HasNonUniformType"; + CheckFlags[CheckFlags["ContainsPublic"] = 64] = "ContainsPublic"; + CheckFlags[CheckFlags["ContainsProtected"] = 128] = "ContainsProtected"; + CheckFlags[CheckFlags["ContainsPrivate"] = 256] = "ContainsPrivate"; + CheckFlags[CheckFlags["ContainsStatic"] = 512] = "ContainsStatic"; + CheckFlags[CheckFlags["Late"] = 1024] = "Late"; + CheckFlags[CheckFlags["ReverseMapped"] = 2048] = "ReverseMapped"; + CheckFlags[CheckFlags["OptionalParameter"] = 4096] = "OptionalParameter"; + CheckFlags[CheckFlags["RestParameter"] = 8192] = "RestParameter"; + CheckFlags[CheckFlags["Synthetic"] = 6] = "Synthetic"; + })(CheckFlags = ts.CheckFlags || (ts.CheckFlags = {})); + var InternalSymbolName; + (function (InternalSymbolName) { + InternalSymbolName["Call"] = "__call"; + InternalSymbolName["Constructor"] = "__constructor"; + InternalSymbolName["New"] = "__new"; + InternalSymbolName["Index"] = "__index"; + InternalSymbolName["ExportStar"] = "__export"; + InternalSymbolName["Global"] = "__global"; + InternalSymbolName["Missing"] = "__missing"; + InternalSymbolName["Type"] = "__type"; + InternalSymbolName["Object"] = "__object"; + InternalSymbolName["JSXAttributes"] = "__jsxAttributes"; + InternalSymbolName["Class"] = "__class"; + InternalSymbolName["Function"] = "__function"; + InternalSymbolName["Computed"] = "__computed"; + InternalSymbolName["Resolving"] = "__resolving__"; + InternalSymbolName["ExportEquals"] = "export="; + InternalSymbolName["Default"] = "default"; + InternalSymbolName["This"] = "this"; + })(InternalSymbolName = ts.InternalSymbolName || (ts.InternalSymbolName = {})); + /* @internal */ + var NodeCheckFlags; + (function (NodeCheckFlags) { + NodeCheckFlags[NodeCheckFlags["TypeChecked"] = 1] = "TypeChecked"; + NodeCheckFlags[NodeCheckFlags["LexicalThis"] = 2] = "LexicalThis"; + NodeCheckFlags[NodeCheckFlags["CaptureThis"] = 4] = "CaptureThis"; + NodeCheckFlags[NodeCheckFlags["CaptureNewTarget"] = 8] = "CaptureNewTarget"; + NodeCheckFlags[NodeCheckFlags["SuperInstance"] = 256] = "SuperInstance"; + NodeCheckFlags[NodeCheckFlags["SuperStatic"] = 512] = "SuperStatic"; + NodeCheckFlags[NodeCheckFlags["ContextChecked"] = 1024] = "ContextChecked"; + NodeCheckFlags[NodeCheckFlags["AsyncMethodWithSuper"] = 2048] = "AsyncMethodWithSuper"; + NodeCheckFlags[NodeCheckFlags["AsyncMethodWithSuperBinding"] = 4096] = "AsyncMethodWithSuperBinding"; + NodeCheckFlags[NodeCheckFlags["CaptureArguments"] = 8192] = "CaptureArguments"; + NodeCheckFlags[NodeCheckFlags["EnumValuesComputed"] = 16384] = "EnumValuesComputed"; + NodeCheckFlags[NodeCheckFlags["LexicalModuleMergesWithClass"] = 32768] = "LexicalModuleMergesWithClass"; + NodeCheckFlags[NodeCheckFlags["LoopWithCapturedBlockScopedBinding"] = 65536] = "LoopWithCapturedBlockScopedBinding"; + NodeCheckFlags[NodeCheckFlags["ContainsCapturedBlockScopeBinding"] = 131072] = "ContainsCapturedBlockScopeBinding"; + NodeCheckFlags[NodeCheckFlags["CapturedBlockScopedBinding"] = 262144] = "CapturedBlockScopedBinding"; + NodeCheckFlags[NodeCheckFlags["BlockScopedBindingInLoop"] = 524288] = "BlockScopedBindingInLoop"; + NodeCheckFlags[NodeCheckFlags["ClassWithBodyScopedClassBinding"] = 1048576] = "ClassWithBodyScopedClassBinding"; + NodeCheckFlags[NodeCheckFlags["BodyScopedClassBinding"] = 2097152] = "BodyScopedClassBinding"; + NodeCheckFlags[NodeCheckFlags["NeedsLoopOutParameter"] = 4194304] = "NeedsLoopOutParameter"; + NodeCheckFlags[NodeCheckFlags["AssignmentsMarked"] = 8388608] = "AssignmentsMarked"; + NodeCheckFlags[NodeCheckFlags["ClassWithConstructorReference"] = 16777216] = "ClassWithConstructorReference"; + NodeCheckFlags[NodeCheckFlags["ConstructorReferenceInClass"] = 33554432] = "ConstructorReferenceInClass"; + })(NodeCheckFlags = ts.NodeCheckFlags || (ts.NodeCheckFlags = {})); + var TypeFlags; + (function (TypeFlags) { + TypeFlags[TypeFlags["Any"] = 1] = "Any"; + TypeFlags[TypeFlags["Unknown"] = 2] = "Unknown"; + TypeFlags[TypeFlags["String"] = 4] = "String"; + TypeFlags[TypeFlags["Number"] = 8] = "Number"; + TypeFlags[TypeFlags["Boolean"] = 16] = "Boolean"; + TypeFlags[TypeFlags["Enum"] = 32] = "Enum"; + TypeFlags[TypeFlags["BigInt"] = 64] = "BigInt"; + TypeFlags[TypeFlags["StringLiteral"] = 128] = "StringLiteral"; + TypeFlags[TypeFlags["NumberLiteral"] = 256] = "NumberLiteral"; + TypeFlags[TypeFlags["BooleanLiteral"] = 512] = "BooleanLiteral"; + TypeFlags[TypeFlags["EnumLiteral"] = 1024] = "EnumLiteral"; + TypeFlags[TypeFlags["BigIntLiteral"] = 2048] = "BigIntLiteral"; + TypeFlags[TypeFlags["ESSymbol"] = 4096] = "ESSymbol"; + TypeFlags[TypeFlags["UniqueESSymbol"] = 8192] = "UniqueESSymbol"; + TypeFlags[TypeFlags["Void"] = 16384] = "Void"; + TypeFlags[TypeFlags["Undefined"] = 32768] = "Undefined"; + TypeFlags[TypeFlags["Null"] = 65536] = "Null"; + TypeFlags[TypeFlags["Never"] = 131072] = "Never"; + TypeFlags[TypeFlags["TypeParameter"] = 262144] = "TypeParameter"; + TypeFlags[TypeFlags["Object"] = 524288] = "Object"; + TypeFlags[TypeFlags["Union"] = 1048576] = "Union"; + TypeFlags[TypeFlags["Intersection"] = 2097152] = "Intersection"; + TypeFlags[TypeFlags["Index"] = 4194304] = "Index"; + TypeFlags[TypeFlags["IndexedAccess"] = 8388608] = "IndexedAccess"; + TypeFlags[TypeFlags["Conditional"] = 16777216] = "Conditional"; + TypeFlags[TypeFlags["Substitution"] = 33554432] = "Substitution"; + TypeFlags[TypeFlags["NonPrimitive"] = 67108864] = "NonPrimitive"; + /* @internal */ + TypeFlags[TypeFlags["ContainsWideningType"] = 134217728] = "ContainsWideningType"; + /* @internal */ + TypeFlags[TypeFlags["ContainsObjectLiteral"] = 268435456] = "ContainsObjectLiteral"; + /* @internal */ + TypeFlags[TypeFlags["ContainsAnyFunctionType"] = 536870912] = "ContainsAnyFunctionType"; + /* @internal */ + TypeFlags[TypeFlags["AnyOrUnknown"] = 3] = "AnyOrUnknown"; + /* @internal */ + TypeFlags[TypeFlags["Nullable"] = 98304] = "Nullable"; + TypeFlags[TypeFlags["Literal"] = 2944] = "Literal"; + TypeFlags[TypeFlags["Unit"] = 109440] = "Unit"; + TypeFlags[TypeFlags["StringOrNumberLiteral"] = 384] = "StringOrNumberLiteral"; + /* @internal */ + TypeFlags[TypeFlags["StringOrNumberLiteralOrUnique"] = 8576] = "StringOrNumberLiteralOrUnique"; + /* @internal */ + TypeFlags[TypeFlags["DefinitelyFalsy"] = 117632] = "DefinitelyFalsy"; + TypeFlags[TypeFlags["PossiblyFalsy"] = 117724] = "PossiblyFalsy"; + /* @internal */ + TypeFlags[TypeFlags["Intrinsic"] = 67359327] = "Intrinsic"; + /* @internal */ + TypeFlags[TypeFlags["Primitive"] = 131068] = "Primitive"; + TypeFlags[TypeFlags["StringLike"] = 132] = "StringLike"; + TypeFlags[TypeFlags["NumberLike"] = 296] = "NumberLike"; + TypeFlags[TypeFlags["BigIntLike"] = 2112] = "BigIntLike"; + TypeFlags[TypeFlags["BooleanLike"] = 528] = "BooleanLike"; + TypeFlags[TypeFlags["EnumLike"] = 1056] = "EnumLike"; + TypeFlags[TypeFlags["ESSymbolLike"] = 12288] = "ESSymbolLike"; + TypeFlags[TypeFlags["VoidLike"] = 49152] = "VoidLike"; + /* @internal */ + TypeFlags[TypeFlags["DisjointDomains"] = 67238908] = "DisjointDomains"; + TypeFlags[TypeFlags["UnionOrIntersection"] = 3145728] = "UnionOrIntersection"; + TypeFlags[TypeFlags["StructuredType"] = 3670016] = "StructuredType"; + TypeFlags[TypeFlags["TypeVariable"] = 8650752] = "TypeVariable"; + TypeFlags[TypeFlags["InstantiableNonPrimitive"] = 58982400] = "InstantiableNonPrimitive"; + TypeFlags[TypeFlags["InstantiablePrimitive"] = 4194304] = "InstantiablePrimitive"; + TypeFlags[TypeFlags["Instantiable"] = 63176704] = "Instantiable"; + TypeFlags[TypeFlags["StructuredOrInstantiable"] = 66846720] = "StructuredOrInstantiable"; + // 'Narrowable' types are types where narrowing actually narrows. + // This *should* be every type other than null, undefined, void, and never + TypeFlags[TypeFlags["Narrowable"] = 133970943] = "Narrowable"; + TypeFlags[TypeFlags["NotUnionOrUnit"] = 67637251] = "NotUnionOrUnit"; + /* @internal */ + TypeFlags[TypeFlags["NotPrimitiveUnion"] = 66994211] = "NotPrimitiveUnion"; + /* @internal */ + TypeFlags[TypeFlags["RequiresWidening"] = 402653184] = "RequiresWidening"; + /* @internal */ + TypeFlags[TypeFlags["PropagatingFlags"] = 939524096] = "PropagatingFlags"; + // The following flags are used for different purposes during union and intersection type construction + /* @internal */ + TypeFlags[TypeFlags["NonWideningType"] = 134217728] = "NonWideningType"; + /* @internal */ + TypeFlags[TypeFlags["Wildcard"] = 268435456] = "Wildcard"; + /* @internal */ + TypeFlags[TypeFlags["EmptyObject"] = 536870912] = "EmptyObject"; + /* @internal */ + TypeFlags[TypeFlags["ConstructionFlags"] = 939524096] = "ConstructionFlags"; + // The following flag is used for different purposes by maybeTypeOfKind + /* @internal */ + TypeFlags[TypeFlags["GenericMappedType"] = 134217728] = "GenericMappedType"; + })(TypeFlags = ts.TypeFlags || (ts.TypeFlags = {})); + var ObjectFlags; + (function (ObjectFlags) { + ObjectFlags[ObjectFlags["Class"] = 1] = "Class"; + ObjectFlags[ObjectFlags["Interface"] = 2] = "Interface"; + ObjectFlags[ObjectFlags["Reference"] = 4] = "Reference"; + ObjectFlags[ObjectFlags["Tuple"] = 8] = "Tuple"; + ObjectFlags[ObjectFlags["Anonymous"] = 16] = "Anonymous"; + ObjectFlags[ObjectFlags["Mapped"] = 32] = "Mapped"; + ObjectFlags[ObjectFlags["Instantiated"] = 64] = "Instantiated"; + ObjectFlags[ObjectFlags["ObjectLiteral"] = 128] = "ObjectLiteral"; + ObjectFlags[ObjectFlags["EvolvingArray"] = 256] = "EvolvingArray"; + ObjectFlags[ObjectFlags["ObjectLiteralPatternWithComputedProperties"] = 512] = "ObjectLiteralPatternWithComputedProperties"; + ObjectFlags[ObjectFlags["ContainsSpread"] = 1024] = "ContainsSpread"; + ObjectFlags[ObjectFlags["ReverseMapped"] = 2048] = "ReverseMapped"; + ObjectFlags[ObjectFlags["JsxAttributes"] = 4096] = "JsxAttributes"; + ObjectFlags[ObjectFlags["MarkerType"] = 8192] = "MarkerType"; + ObjectFlags[ObjectFlags["JSLiteral"] = 16384] = "JSLiteral"; + ObjectFlags[ObjectFlags["FreshLiteral"] = 32768] = "FreshLiteral"; + ObjectFlags[ObjectFlags["ClassOrInterface"] = 3] = "ClassOrInterface"; + })(ObjectFlags = ts.ObjectFlags || (ts.ObjectFlags = {})); + /* @internal */ + var Variance; + (function (Variance) { + Variance[Variance["Invariant"] = 0] = "Invariant"; + Variance[Variance["Covariant"] = 1] = "Covariant"; + Variance[Variance["Contravariant"] = 2] = "Contravariant"; + Variance[Variance["Bivariant"] = 3] = "Bivariant"; + Variance[Variance["Independent"] = 4] = "Independent"; + })(Variance = ts.Variance || (ts.Variance = {})); + /* @internal */ + var JsxReferenceKind; + (function (JsxReferenceKind) { + JsxReferenceKind[JsxReferenceKind["Component"] = 0] = "Component"; + JsxReferenceKind[JsxReferenceKind["Function"] = 1] = "Function"; + JsxReferenceKind[JsxReferenceKind["Mixed"] = 2] = "Mixed"; + })(JsxReferenceKind = ts.JsxReferenceKind || (ts.JsxReferenceKind = {})); + var SignatureKind; + (function (SignatureKind) { + SignatureKind[SignatureKind["Call"] = 0] = "Call"; + SignatureKind[SignatureKind["Construct"] = 1] = "Construct"; + })(SignatureKind = ts.SignatureKind || (ts.SignatureKind = {})); + var IndexKind; + (function (IndexKind) { + IndexKind[IndexKind["String"] = 0] = "String"; + IndexKind[IndexKind["Number"] = 1] = "Number"; + })(IndexKind = ts.IndexKind || (ts.IndexKind = {})); + var InferencePriority; + (function (InferencePriority) { + InferencePriority[InferencePriority["NakedTypeVariable"] = 1] = "NakedTypeVariable"; + InferencePriority[InferencePriority["HomomorphicMappedType"] = 2] = "HomomorphicMappedType"; + InferencePriority[InferencePriority["MappedTypeConstraint"] = 4] = "MappedTypeConstraint"; + InferencePriority[InferencePriority["ReturnType"] = 8] = "ReturnType"; + InferencePriority[InferencePriority["LiteralKeyof"] = 16] = "LiteralKeyof"; + InferencePriority[InferencePriority["NoConstraints"] = 32] = "NoConstraints"; + InferencePriority[InferencePriority["AlwaysStrict"] = 64] = "AlwaysStrict"; + InferencePriority[InferencePriority["PriorityImpliesCombination"] = 28] = "PriorityImpliesCombination"; + })(InferencePriority = ts.InferencePriority || (ts.InferencePriority = {})); + /* @internal */ + var InferenceFlags; + (function (InferenceFlags) { + InferenceFlags[InferenceFlags["None"] = 0] = "None"; + InferenceFlags[InferenceFlags["NoDefault"] = 1] = "NoDefault"; + InferenceFlags[InferenceFlags["AnyDefault"] = 2] = "AnyDefault"; + })(InferenceFlags = ts.InferenceFlags || (ts.InferenceFlags = {})); + /** + * Ternary values are defined such that + * x & y is False if either x or y is False. + * x & y is Maybe if either x or y is Maybe, but neither x or y is False. + * x & y is True if both x and y are True. + * x | y is False if both x and y are False. + * x | y is Maybe if either x or y is Maybe, but neither x or y is True. + * x | y is True if either x or y is True. + */ + /* @internal */ + var Ternary; + (function (Ternary) { + Ternary[Ternary["False"] = 0] = "False"; + Ternary[Ternary["Maybe"] = 1] = "Maybe"; + Ternary[Ternary["True"] = -1] = "True"; + })(Ternary = ts.Ternary || (ts.Ternary = {})); + /* @internal */ + var AssignmentDeclarationKind; + (function (AssignmentDeclarationKind) { + AssignmentDeclarationKind[AssignmentDeclarationKind["None"] = 0] = "None"; + /// exports.name = expr + AssignmentDeclarationKind[AssignmentDeclarationKind["ExportsProperty"] = 1] = "ExportsProperty"; + /// module.exports = expr + AssignmentDeclarationKind[AssignmentDeclarationKind["ModuleExports"] = 2] = "ModuleExports"; + /// className.prototype.name = expr + AssignmentDeclarationKind[AssignmentDeclarationKind["PrototypeProperty"] = 3] = "PrototypeProperty"; + /// this.name = expr + AssignmentDeclarationKind[AssignmentDeclarationKind["ThisProperty"] = 4] = "ThisProperty"; + // F.name = expr + AssignmentDeclarationKind[AssignmentDeclarationKind["Property"] = 5] = "Property"; + // F.prototype = { ... } + AssignmentDeclarationKind[AssignmentDeclarationKind["Prototype"] = 6] = "Prototype"; + // Object.defineProperty(x, 'name', { value: any, writable?: boolean (false by default) }); + // Object.defineProperty(x, 'name', { get: Function, set: Function }); + // Object.defineProperty(x, 'name', { get: Function }); + // Object.defineProperty(x, 'name', { set: Function }); + AssignmentDeclarationKind[AssignmentDeclarationKind["ObjectDefinePropertyValue"] = 7] = "ObjectDefinePropertyValue"; + // Object.defineProperty(exports || module.exports, 'name', ...); + AssignmentDeclarationKind[AssignmentDeclarationKind["ObjectDefinePropertyExports"] = 8] = "ObjectDefinePropertyExports"; + // Object.defineProperty(Foo.prototype, 'name', ...); + AssignmentDeclarationKind[AssignmentDeclarationKind["ObjectDefinePrototypeProperty"] = 9] = "ObjectDefinePrototypeProperty"; + })(AssignmentDeclarationKind = ts.AssignmentDeclarationKind || (ts.AssignmentDeclarationKind = {})); + var DiagnosticCategory; + (function (DiagnosticCategory) { + DiagnosticCategory[DiagnosticCategory["Warning"] = 0] = "Warning"; + DiagnosticCategory[DiagnosticCategory["Error"] = 1] = "Error"; + DiagnosticCategory[DiagnosticCategory["Suggestion"] = 2] = "Suggestion"; + DiagnosticCategory[DiagnosticCategory["Message"] = 3] = "Message"; + })(DiagnosticCategory = ts.DiagnosticCategory || (ts.DiagnosticCategory = {})); + /* @internal */ + function diagnosticCategoryName(d, lowerCase) { + if (lowerCase === void 0) { lowerCase = true; } + var name = DiagnosticCategory[d.category]; + return lowerCase ? name.toLowerCase() : name; + } + ts.diagnosticCategoryName = diagnosticCategoryName; + var ModuleResolutionKind; + (function (ModuleResolutionKind) { + ModuleResolutionKind[ModuleResolutionKind["Classic"] = 1] = "Classic"; + ModuleResolutionKind[ModuleResolutionKind["NodeJs"] = 2] = "NodeJs"; + })(ModuleResolutionKind = ts.ModuleResolutionKind || (ts.ModuleResolutionKind = {})); + var ModuleKind; + (function (ModuleKind) { + ModuleKind[ModuleKind["None"] = 0] = "None"; + ModuleKind[ModuleKind["CommonJS"] = 1] = "CommonJS"; + ModuleKind[ModuleKind["AMD"] = 2] = "AMD"; + ModuleKind[ModuleKind["UMD"] = 3] = "UMD"; + ModuleKind[ModuleKind["System"] = 4] = "System"; + ModuleKind[ModuleKind["ES2015"] = 5] = "ES2015"; + ModuleKind[ModuleKind["ESNext"] = 6] = "ESNext"; + })(ModuleKind = ts.ModuleKind || (ts.ModuleKind = {})); + var JsxEmit; + (function (JsxEmit) { + JsxEmit[JsxEmit["None"] = 0] = "None"; + JsxEmit[JsxEmit["Preserve"] = 1] = "Preserve"; + JsxEmit[JsxEmit["React"] = 2] = "React"; + JsxEmit[JsxEmit["ReactNative"] = 3] = "ReactNative"; + })(JsxEmit = ts.JsxEmit || (ts.JsxEmit = {})); + var NewLineKind; + (function (NewLineKind) { + NewLineKind[NewLineKind["CarriageReturnLineFeed"] = 0] = "CarriageReturnLineFeed"; + NewLineKind[NewLineKind["LineFeed"] = 1] = "LineFeed"; + })(NewLineKind = ts.NewLineKind || (ts.NewLineKind = {})); + var ScriptKind; + (function (ScriptKind) { + ScriptKind[ScriptKind["Unknown"] = 0] = "Unknown"; + ScriptKind[ScriptKind["JS"] = 1] = "JS"; + ScriptKind[ScriptKind["JSX"] = 2] = "JSX"; + ScriptKind[ScriptKind["TS"] = 3] = "TS"; + ScriptKind[ScriptKind["TSX"] = 4] = "TSX"; + ScriptKind[ScriptKind["External"] = 5] = "External"; + ScriptKind[ScriptKind["JSON"] = 6] = "JSON"; + /** + * Used on extensions that doesn't define the ScriptKind but the content defines it. + * Deferred extensions are going to be included in all project contexts. + */ + ScriptKind[ScriptKind["Deferred"] = 7] = "Deferred"; + })(ScriptKind = ts.ScriptKind || (ts.ScriptKind = {})); + var ScriptTarget; + (function (ScriptTarget) { + ScriptTarget[ScriptTarget["ES3"] = 0] = "ES3"; + ScriptTarget[ScriptTarget["ES5"] = 1] = "ES5"; + ScriptTarget[ScriptTarget["ES2015"] = 2] = "ES2015"; + ScriptTarget[ScriptTarget["ES2016"] = 3] = "ES2016"; + ScriptTarget[ScriptTarget["ES2017"] = 4] = "ES2017"; + ScriptTarget[ScriptTarget["ES2018"] = 5] = "ES2018"; + ScriptTarget[ScriptTarget["ESNext"] = 6] = "ESNext"; + ScriptTarget[ScriptTarget["JSON"] = 100] = "JSON"; + ScriptTarget[ScriptTarget["Latest"] = 6] = "Latest"; + })(ScriptTarget = ts.ScriptTarget || (ts.ScriptTarget = {})); + var LanguageVariant; + (function (LanguageVariant) { + LanguageVariant[LanguageVariant["Standard"] = 0] = "Standard"; + LanguageVariant[LanguageVariant["JSX"] = 1] = "JSX"; + })(LanguageVariant = ts.LanguageVariant || (ts.LanguageVariant = {})); + var WatchDirectoryFlags; + (function (WatchDirectoryFlags) { + WatchDirectoryFlags[WatchDirectoryFlags["None"] = 0] = "None"; + WatchDirectoryFlags[WatchDirectoryFlags["Recursive"] = 1] = "Recursive"; + })(WatchDirectoryFlags = ts.WatchDirectoryFlags || (ts.WatchDirectoryFlags = {})); + /* @internal */ + var CharacterCodes; + (function (CharacterCodes) { + CharacterCodes[CharacterCodes["nullCharacter"] = 0] = "nullCharacter"; + CharacterCodes[CharacterCodes["maxAsciiCharacter"] = 127] = "maxAsciiCharacter"; + CharacterCodes[CharacterCodes["lineFeed"] = 10] = "lineFeed"; + CharacterCodes[CharacterCodes["carriageReturn"] = 13] = "carriageReturn"; + CharacterCodes[CharacterCodes["lineSeparator"] = 8232] = "lineSeparator"; + CharacterCodes[CharacterCodes["paragraphSeparator"] = 8233] = "paragraphSeparator"; + CharacterCodes[CharacterCodes["nextLine"] = 133] = "nextLine"; + // Unicode 3.0 space characters + CharacterCodes[CharacterCodes["space"] = 32] = "space"; + CharacterCodes[CharacterCodes["nonBreakingSpace"] = 160] = "nonBreakingSpace"; + CharacterCodes[CharacterCodes["enQuad"] = 8192] = "enQuad"; + CharacterCodes[CharacterCodes["emQuad"] = 8193] = "emQuad"; + CharacterCodes[CharacterCodes["enSpace"] = 8194] = "enSpace"; + CharacterCodes[CharacterCodes["emSpace"] = 8195] = "emSpace"; + CharacterCodes[CharacterCodes["threePerEmSpace"] = 8196] = "threePerEmSpace"; + CharacterCodes[CharacterCodes["fourPerEmSpace"] = 8197] = "fourPerEmSpace"; + CharacterCodes[CharacterCodes["sixPerEmSpace"] = 8198] = "sixPerEmSpace"; + CharacterCodes[CharacterCodes["figureSpace"] = 8199] = "figureSpace"; + CharacterCodes[CharacterCodes["punctuationSpace"] = 8200] = "punctuationSpace"; + CharacterCodes[CharacterCodes["thinSpace"] = 8201] = "thinSpace"; + CharacterCodes[CharacterCodes["hairSpace"] = 8202] = "hairSpace"; + CharacterCodes[CharacterCodes["zeroWidthSpace"] = 8203] = "zeroWidthSpace"; + CharacterCodes[CharacterCodes["narrowNoBreakSpace"] = 8239] = "narrowNoBreakSpace"; + CharacterCodes[CharacterCodes["ideographicSpace"] = 12288] = "ideographicSpace"; + CharacterCodes[CharacterCodes["mathematicalSpace"] = 8287] = "mathematicalSpace"; + CharacterCodes[CharacterCodes["ogham"] = 5760] = "ogham"; + CharacterCodes[CharacterCodes["_"] = 95] = "_"; + CharacterCodes[CharacterCodes["$"] = 36] = "$"; + CharacterCodes[CharacterCodes["_0"] = 48] = "_0"; + CharacterCodes[CharacterCodes["_1"] = 49] = "_1"; + CharacterCodes[CharacterCodes["_2"] = 50] = "_2"; + CharacterCodes[CharacterCodes["_3"] = 51] = "_3"; + CharacterCodes[CharacterCodes["_4"] = 52] = "_4"; + CharacterCodes[CharacterCodes["_5"] = 53] = "_5"; + CharacterCodes[CharacterCodes["_6"] = 54] = "_6"; + CharacterCodes[CharacterCodes["_7"] = 55] = "_7"; + CharacterCodes[CharacterCodes["_8"] = 56] = "_8"; + CharacterCodes[CharacterCodes["_9"] = 57] = "_9"; + CharacterCodes[CharacterCodes["a"] = 97] = "a"; + CharacterCodes[CharacterCodes["b"] = 98] = "b"; + CharacterCodes[CharacterCodes["c"] = 99] = "c"; + CharacterCodes[CharacterCodes["d"] = 100] = "d"; + CharacterCodes[CharacterCodes["e"] = 101] = "e"; + CharacterCodes[CharacterCodes["f"] = 102] = "f"; + CharacterCodes[CharacterCodes["g"] = 103] = "g"; + CharacterCodes[CharacterCodes["h"] = 104] = "h"; + CharacterCodes[CharacterCodes["i"] = 105] = "i"; + CharacterCodes[CharacterCodes["j"] = 106] = "j"; + CharacterCodes[CharacterCodes["k"] = 107] = "k"; + CharacterCodes[CharacterCodes["l"] = 108] = "l"; + CharacterCodes[CharacterCodes["m"] = 109] = "m"; + CharacterCodes[CharacterCodes["n"] = 110] = "n"; + CharacterCodes[CharacterCodes["o"] = 111] = "o"; + CharacterCodes[CharacterCodes["p"] = 112] = "p"; + CharacterCodes[CharacterCodes["q"] = 113] = "q"; + CharacterCodes[CharacterCodes["r"] = 114] = "r"; + CharacterCodes[CharacterCodes["s"] = 115] = "s"; + CharacterCodes[CharacterCodes["t"] = 116] = "t"; + CharacterCodes[CharacterCodes["u"] = 117] = "u"; + CharacterCodes[CharacterCodes["v"] = 118] = "v"; + CharacterCodes[CharacterCodes["w"] = 119] = "w"; + CharacterCodes[CharacterCodes["x"] = 120] = "x"; + CharacterCodes[CharacterCodes["y"] = 121] = "y"; + CharacterCodes[CharacterCodes["z"] = 122] = "z"; + CharacterCodes[CharacterCodes["A"] = 65] = "A"; + CharacterCodes[CharacterCodes["B"] = 66] = "B"; + CharacterCodes[CharacterCodes["C"] = 67] = "C"; + CharacterCodes[CharacterCodes["D"] = 68] = "D"; + CharacterCodes[CharacterCodes["E"] = 69] = "E"; + CharacterCodes[CharacterCodes["F"] = 70] = "F"; + CharacterCodes[CharacterCodes["G"] = 71] = "G"; + CharacterCodes[CharacterCodes["H"] = 72] = "H"; + CharacterCodes[CharacterCodes["I"] = 73] = "I"; + CharacterCodes[CharacterCodes["J"] = 74] = "J"; + CharacterCodes[CharacterCodes["K"] = 75] = "K"; + CharacterCodes[CharacterCodes["L"] = 76] = "L"; + CharacterCodes[CharacterCodes["M"] = 77] = "M"; + CharacterCodes[CharacterCodes["N"] = 78] = "N"; + CharacterCodes[CharacterCodes["O"] = 79] = "O"; + CharacterCodes[CharacterCodes["P"] = 80] = "P"; + CharacterCodes[CharacterCodes["Q"] = 81] = "Q"; + CharacterCodes[CharacterCodes["R"] = 82] = "R"; + CharacterCodes[CharacterCodes["S"] = 83] = "S"; + CharacterCodes[CharacterCodes["T"] = 84] = "T"; + CharacterCodes[CharacterCodes["U"] = 85] = "U"; + CharacterCodes[CharacterCodes["V"] = 86] = "V"; + CharacterCodes[CharacterCodes["W"] = 87] = "W"; + CharacterCodes[CharacterCodes["X"] = 88] = "X"; + CharacterCodes[CharacterCodes["Y"] = 89] = "Y"; + CharacterCodes[CharacterCodes["Z"] = 90] = "Z"; + CharacterCodes[CharacterCodes["ampersand"] = 38] = "ampersand"; + CharacterCodes[CharacterCodes["asterisk"] = 42] = "asterisk"; + CharacterCodes[CharacterCodes["at"] = 64] = "at"; + CharacterCodes[CharacterCodes["backslash"] = 92] = "backslash"; + CharacterCodes[CharacterCodes["backtick"] = 96] = "backtick"; + CharacterCodes[CharacterCodes["bar"] = 124] = "bar"; + CharacterCodes[CharacterCodes["caret"] = 94] = "caret"; + CharacterCodes[CharacterCodes["closeBrace"] = 125] = "closeBrace"; + CharacterCodes[CharacterCodes["closeBracket"] = 93] = "closeBracket"; + CharacterCodes[CharacterCodes["closeParen"] = 41] = "closeParen"; + CharacterCodes[CharacterCodes["colon"] = 58] = "colon"; + CharacterCodes[CharacterCodes["comma"] = 44] = "comma"; + CharacterCodes[CharacterCodes["dot"] = 46] = "dot"; + CharacterCodes[CharacterCodes["doubleQuote"] = 34] = "doubleQuote"; + CharacterCodes[CharacterCodes["equals"] = 61] = "equals"; + CharacterCodes[CharacterCodes["exclamation"] = 33] = "exclamation"; + CharacterCodes[CharacterCodes["greaterThan"] = 62] = "greaterThan"; + CharacterCodes[CharacterCodes["hash"] = 35] = "hash"; + CharacterCodes[CharacterCodes["lessThan"] = 60] = "lessThan"; + CharacterCodes[CharacterCodes["minus"] = 45] = "minus"; + CharacterCodes[CharacterCodes["openBrace"] = 123] = "openBrace"; + CharacterCodes[CharacterCodes["openBracket"] = 91] = "openBracket"; + CharacterCodes[CharacterCodes["openParen"] = 40] = "openParen"; + CharacterCodes[CharacterCodes["percent"] = 37] = "percent"; + CharacterCodes[CharacterCodes["plus"] = 43] = "plus"; + CharacterCodes[CharacterCodes["question"] = 63] = "question"; + CharacterCodes[CharacterCodes["semicolon"] = 59] = "semicolon"; + CharacterCodes[CharacterCodes["singleQuote"] = 39] = "singleQuote"; + CharacterCodes[CharacterCodes["slash"] = 47] = "slash"; + CharacterCodes[CharacterCodes["tilde"] = 126] = "tilde"; + CharacterCodes[CharacterCodes["backspace"] = 8] = "backspace"; + CharacterCodes[CharacterCodes["formFeed"] = 12] = "formFeed"; + CharacterCodes[CharacterCodes["byteOrderMark"] = 65279] = "byteOrderMark"; + CharacterCodes[CharacterCodes["tab"] = 9] = "tab"; + CharacterCodes[CharacterCodes["verticalTab"] = 11] = "verticalTab"; + })(CharacterCodes = ts.CharacterCodes || (ts.CharacterCodes = {})); + var Extension; + (function (Extension) { + Extension["Ts"] = ".ts"; + Extension["Tsx"] = ".tsx"; + Extension["Dts"] = ".d.ts"; + Extension["Js"] = ".js"; + Extension["Jsx"] = ".jsx"; + Extension["Json"] = ".json"; + })(Extension = ts.Extension || (ts.Extension = {})); + /* @internal */ + var TransformFlags; + (function (TransformFlags) { + TransformFlags[TransformFlags["None"] = 0] = "None"; + // Facts + // - Flags used to indicate that a node or subtree contains syntax that requires transformation. + TransformFlags[TransformFlags["TypeScript"] = 1] = "TypeScript"; + TransformFlags[TransformFlags["ContainsTypeScript"] = 2] = "ContainsTypeScript"; + TransformFlags[TransformFlags["ContainsJsx"] = 4] = "ContainsJsx"; + TransformFlags[TransformFlags["ContainsESNext"] = 8] = "ContainsESNext"; + TransformFlags[TransformFlags["ContainsES2017"] = 16] = "ContainsES2017"; + TransformFlags[TransformFlags["ContainsES2016"] = 32] = "ContainsES2016"; + TransformFlags[TransformFlags["ES2015"] = 64] = "ES2015"; + TransformFlags[TransformFlags["ContainsES2015"] = 128] = "ContainsES2015"; + TransformFlags[TransformFlags["Generator"] = 256] = "Generator"; + TransformFlags[TransformFlags["ContainsGenerator"] = 512] = "ContainsGenerator"; + TransformFlags[TransformFlags["DestructuringAssignment"] = 1024] = "DestructuringAssignment"; + TransformFlags[TransformFlags["ContainsDestructuringAssignment"] = 2048] = "ContainsDestructuringAssignment"; + // Markers + // - Flags used to indicate that a subtree contains a specific transformation. + TransformFlags[TransformFlags["ContainsTypeScriptClassSyntax"] = 4096] = "ContainsTypeScriptClassSyntax"; + TransformFlags[TransformFlags["ContainsLexicalThis"] = 8192] = "ContainsLexicalThis"; + TransformFlags[TransformFlags["ContainsCapturedLexicalThis"] = 16384] = "ContainsCapturedLexicalThis"; + TransformFlags[TransformFlags["ContainsLexicalThisInComputedPropertyName"] = 32768] = "ContainsLexicalThisInComputedPropertyName"; + TransformFlags[TransformFlags["ContainsDefaultValueAssignments"] = 65536] = "ContainsDefaultValueAssignments"; + TransformFlags[TransformFlags["ContainsRestOrSpread"] = 131072] = "ContainsRestOrSpread"; + TransformFlags[TransformFlags["ContainsObjectRestOrSpread"] = 262144] = "ContainsObjectRestOrSpread"; + TransformFlags[TransformFlags["ContainsComputedPropertyName"] = 524288] = "ContainsComputedPropertyName"; + TransformFlags[TransformFlags["ContainsBlockScopedBinding"] = 1048576] = "ContainsBlockScopedBinding"; + TransformFlags[TransformFlags["ContainsBindingPattern"] = 2097152] = "ContainsBindingPattern"; + TransformFlags[TransformFlags["ContainsYield"] = 4194304] = "ContainsYield"; + TransformFlags[TransformFlags["ContainsHoistedDeclarationOrCompletion"] = 8388608] = "ContainsHoistedDeclarationOrCompletion"; + TransformFlags[TransformFlags["ContainsDynamicImport"] = 16777216] = "ContainsDynamicImport"; + TransformFlags[TransformFlags["Super"] = 33554432] = "Super"; + TransformFlags[TransformFlags["ContainsSuper"] = 67108864] = "ContainsSuper"; + // Please leave this as 1 << 29. + // It is the maximum bit we can set before we outgrow the size of a v8 small integer (SMI) on an x86 system. + // It is a good reminder of how much room we have left + TransformFlags[TransformFlags["HasComputedFlags"] = 536870912] = "HasComputedFlags"; + // Assertions + // - Bitmasks that are used to assert facts about the syntax of a node and its subtree. + TransformFlags[TransformFlags["AssertTypeScript"] = 3] = "AssertTypeScript"; + TransformFlags[TransformFlags["AssertJsx"] = 4] = "AssertJsx"; + TransformFlags[TransformFlags["AssertESNext"] = 8] = "AssertESNext"; + TransformFlags[TransformFlags["AssertES2017"] = 16] = "AssertES2017"; + TransformFlags[TransformFlags["AssertES2016"] = 32] = "AssertES2016"; + TransformFlags[TransformFlags["AssertES2015"] = 192] = "AssertES2015"; + TransformFlags[TransformFlags["AssertGenerator"] = 768] = "AssertGenerator"; + TransformFlags[TransformFlags["AssertDestructuringAssignment"] = 3072] = "AssertDestructuringAssignment"; + // Scope Exclusions + // - Bitmasks that exclude flags from propagating out of a specific context + // into the subtree flags of their container. + TransformFlags[TransformFlags["OuterExpressionExcludes"] = 536872257] = "OuterExpressionExcludes"; + TransformFlags[TransformFlags["PropertyAccessExcludes"] = 570426689] = "PropertyAccessExcludes"; + TransformFlags[TransformFlags["NodeExcludes"] = 637535553] = "NodeExcludes"; + TransformFlags[TransformFlags["ArrowFunctionExcludes"] = 653604161] = "ArrowFunctionExcludes"; + TransformFlags[TransformFlags["FunctionExcludes"] = 653620545] = "FunctionExcludes"; + TransformFlags[TransformFlags["ConstructorExcludes"] = 653616449] = "ConstructorExcludes"; + TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = 653616449] = "MethodOrAccessorExcludes"; + TransformFlags[TransformFlags["ClassExcludes"] = 638121281] = "ClassExcludes"; + TransformFlags[TransformFlags["ModuleExcludes"] = 647001409] = "ModuleExcludes"; + TransformFlags[TransformFlags["TypeExcludes"] = -3] = "TypeExcludes"; + TransformFlags[TransformFlags["ObjectLiteralExcludes"] = 638358849] = "ObjectLiteralExcludes"; + TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = 637666625] = "ArrayLiteralOrCallOrNewExcludes"; + TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = 639894849] = "VariableDeclarationListExcludes"; + TransformFlags[TransformFlags["ParameterExcludes"] = 637535553] = "ParameterExcludes"; + TransformFlags[TransformFlags["CatchClauseExcludes"] = 637797697] = "CatchClauseExcludes"; + TransformFlags[TransformFlags["BindingPatternExcludes"] = 637666625] = "BindingPatternExcludes"; + // Masks + // - Additional bitmasks + TransformFlags[TransformFlags["ES2015FunctionSyntaxMask"] = 81920] = "ES2015FunctionSyntaxMask"; + })(TransformFlags = ts.TransformFlags || (ts.TransformFlags = {})); + var EmitFlags; + (function (EmitFlags) { + EmitFlags[EmitFlags["None"] = 0] = "None"; + EmitFlags[EmitFlags["SingleLine"] = 1] = "SingleLine"; + EmitFlags[EmitFlags["AdviseOnEmitNode"] = 2] = "AdviseOnEmitNode"; + EmitFlags[EmitFlags["NoSubstitution"] = 4] = "NoSubstitution"; + EmitFlags[EmitFlags["CapturesThis"] = 8] = "CapturesThis"; + EmitFlags[EmitFlags["NoLeadingSourceMap"] = 16] = "NoLeadingSourceMap"; + EmitFlags[EmitFlags["NoTrailingSourceMap"] = 32] = "NoTrailingSourceMap"; + EmitFlags[EmitFlags["NoSourceMap"] = 48] = "NoSourceMap"; + EmitFlags[EmitFlags["NoNestedSourceMaps"] = 64] = "NoNestedSourceMaps"; + EmitFlags[EmitFlags["NoTokenLeadingSourceMaps"] = 128] = "NoTokenLeadingSourceMaps"; + EmitFlags[EmitFlags["NoTokenTrailingSourceMaps"] = 256] = "NoTokenTrailingSourceMaps"; + EmitFlags[EmitFlags["NoTokenSourceMaps"] = 384] = "NoTokenSourceMaps"; + EmitFlags[EmitFlags["NoLeadingComments"] = 512] = "NoLeadingComments"; + EmitFlags[EmitFlags["NoTrailingComments"] = 1024] = "NoTrailingComments"; + EmitFlags[EmitFlags["NoComments"] = 1536] = "NoComments"; + EmitFlags[EmitFlags["NoNestedComments"] = 2048] = "NoNestedComments"; + EmitFlags[EmitFlags["HelperName"] = 4096] = "HelperName"; + EmitFlags[EmitFlags["ExportName"] = 8192] = "ExportName"; + EmitFlags[EmitFlags["LocalName"] = 16384] = "LocalName"; + EmitFlags[EmitFlags["InternalName"] = 32768] = "InternalName"; + EmitFlags[EmitFlags["Indented"] = 65536] = "Indented"; + EmitFlags[EmitFlags["NoIndentation"] = 131072] = "NoIndentation"; + EmitFlags[EmitFlags["AsyncFunctionBody"] = 262144] = "AsyncFunctionBody"; + EmitFlags[EmitFlags["ReuseTempVariableScope"] = 524288] = "ReuseTempVariableScope"; + EmitFlags[EmitFlags["CustomPrologue"] = 1048576] = "CustomPrologue"; + EmitFlags[EmitFlags["NoHoisting"] = 2097152] = "NoHoisting"; + EmitFlags[EmitFlags["HasEndOfDeclarationMarker"] = 4194304] = "HasEndOfDeclarationMarker"; + EmitFlags[EmitFlags["Iterator"] = 8388608] = "Iterator"; + EmitFlags[EmitFlags["NoAsciiEscaping"] = 16777216] = "NoAsciiEscaping"; + /*@internal*/ EmitFlags[EmitFlags["TypeScriptClassWrapper"] = 33554432] = "TypeScriptClassWrapper"; + /*@internal*/ EmitFlags[EmitFlags["NeverApplyImportHelper"] = 67108864] = "NeverApplyImportHelper"; + })(EmitFlags = ts.EmitFlags || (ts.EmitFlags = {})); + /** + * Used by the checker, this enum keeps track of external emit helpers that should be type + * checked. + */ + /* @internal */ + var ExternalEmitHelpers; + (function (ExternalEmitHelpers) { + ExternalEmitHelpers[ExternalEmitHelpers["Extends"] = 1] = "Extends"; + ExternalEmitHelpers[ExternalEmitHelpers["Assign"] = 2] = "Assign"; + ExternalEmitHelpers[ExternalEmitHelpers["Rest"] = 4] = "Rest"; + ExternalEmitHelpers[ExternalEmitHelpers["Decorate"] = 8] = "Decorate"; + ExternalEmitHelpers[ExternalEmitHelpers["Metadata"] = 16] = "Metadata"; + ExternalEmitHelpers[ExternalEmitHelpers["Param"] = 32] = "Param"; + ExternalEmitHelpers[ExternalEmitHelpers["Awaiter"] = 64] = "Awaiter"; + ExternalEmitHelpers[ExternalEmitHelpers["Generator"] = 128] = "Generator"; + ExternalEmitHelpers[ExternalEmitHelpers["Values"] = 256] = "Values"; + ExternalEmitHelpers[ExternalEmitHelpers["Read"] = 512] = "Read"; + ExternalEmitHelpers[ExternalEmitHelpers["Spread"] = 1024] = "Spread"; + ExternalEmitHelpers[ExternalEmitHelpers["Await"] = 2048] = "Await"; + ExternalEmitHelpers[ExternalEmitHelpers["AsyncGenerator"] = 4096] = "AsyncGenerator"; + ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegator"] = 8192] = "AsyncDelegator"; + ExternalEmitHelpers[ExternalEmitHelpers["AsyncValues"] = 16384] = "AsyncValues"; + ExternalEmitHelpers[ExternalEmitHelpers["ExportStar"] = 32768] = "ExportStar"; + ExternalEmitHelpers[ExternalEmitHelpers["MakeTemplateObject"] = 65536] = "MakeTemplateObject"; + ExternalEmitHelpers[ExternalEmitHelpers["FirstEmitHelper"] = 1] = "FirstEmitHelper"; + ExternalEmitHelpers[ExternalEmitHelpers["LastEmitHelper"] = 65536] = "LastEmitHelper"; + // Helpers included by ES2015 for..of + ExternalEmitHelpers[ExternalEmitHelpers["ForOfIncludes"] = 256] = "ForOfIncludes"; + // Helpers included by ES2017 for..await..of + ExternalEmitHelpers[ExternalEmitHelpers["ForAwaitOfIncludes"] = 16384] = "ForAwaitOfIncludes"; + // Helpers included by ES2017 async generators + ExternalEmitHelpers[ExternalEmitHelpers["AsyncGeneratorIncludes"] = 6144] = "AsyncGeneratorIncludes"; + // Helpers included by yield* in ES2017 async generators + ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegatorIncludes"] = 26624] = "AsyncDelegatorIncludes"; + // Helpers included by ES2015 spread + ExternalEmitHelpers[ExternalEmitHelpers["SpreadIncludes"] = 1536] = "SpreadIncludes"; + })(ExternalEmitHelpers = ts.ExternalEmitHelpers || (ts.ExternalEmitHelpers = {})); + var EmitHint; + (function (EmitHint) { + EmitHint[EmitHint["SourceFile"] = 0] = "SourceFile"; + EmitHint[EmitHint["Expression"] = 1] = "Expression"; + EmitHint[EmitHint["IdentifierName"] = 2] = "IdentifierName"; + EmitHint[EmitHint["MappedTypeParameter"] = 3] = "MappedTypeParameter"; + EmitHint[EmitHint["Unspecified"] = 4] = "Unspecified"; + EmitHint[EmitHint["EmbeddedStatement"] = 5] = "EmbeddedStatement"; + })(EmitHint = ts.EmitHint || (ts.EmitHint = {})); + var ListFormat; + (function (ListFormat) { + ListFormat[ListFormat["None"] = 0] = "None"; + // Line separators + ListFormat[ListFormat["SingleLine"] = 0] = "SingleLine"; + ListFormat[ListFormat["MultiLine"] = 1] = "MultiLine"; + ListFormat[ListFormat["PreserveLines"] = 2] = "PreserveLines"; + ListFormat[ListFormat["LinesMask"] = 3] = "LinesMask"; + // Delimiters + ListFormat[ListFormat["NotDelimited"] = 0] = "NotDelimited"; + ListFormat[ListFormat["BarDelimited"] = 4] = "BarDelimited"; + ListFormat[ListFormat["AmpersandDelimited"] = 8] = "AmpersandDelimited"; + ListFormat[ListFormat["CommaDelimited"] = 16] = "CommaDelimited"; + ListFormat[ListFormat["AsteriskDelimited"] = 32] = "AsteriskDelimited"; + ListFormat[ListFormat["DelimitersMask"] = 60] = "DelimitersMask"; + ListFormat[ListFormat["AllowTrailingComma"] = 64] = "AllowTrailingComma"; + // Whitespace + ListFormat[ListFormat["Indented"] = 128] = "Indented"; + ListFormat[ListFormat["SpaceBetweenBraces"] = 256] = "SpaceBetweenBraces"; + ListFormat[ListFormat["SpaceBetweenSiblings"] = 512] = "SpaceBetweenSiblings"; + // Brackets/Braces + ListFormat[ListFormat["Braces"] = 1024] = "Braces"; + ListFormat[ListFormat["Parenthesis"] = 2048] = "Parenthesis"; + ListFormat[ListFormat["AngleBrackets"] = 4096] = "AngleBrackets"; + ListFormat[ListFormat["SquareBrackets"] = 8192] = "SquareBrackets"; + ListFormat[ListFormat["BracketsMask"] = 15360] = "BracketsMask"; + ListFormat[ListFormat["OptionalIfUndefined"] = 16384] = "OptionalIfUndefined"; + ListFormat[ListFormat["OptionalIfEmpty"] = 32768] = "OptionalIfEmpty"; + ListFormat[ListFormat["Optional"] = 49152] = "Optional"; + // Other + ListFormat[ListFormat["PreferNewLine"] = 65536] = "PreferNewLine"; + ListFormat[ListFormat["NoTrailingNewLine"] = 131072] = "NoTrailingNewLine"; + ListFormat[ListFormat["NoInterveningComments"] = 262144] = "NoInterveningComments"; + ListFormat[ListFormat["NoSpaceIfEmpty"] = 524288] = "NoSpaceIfEmpty"; + ListFormat[ListFormat["SingleElement"] = 1048576] = "SingleElement"; + // Precomputed Formats + ListFormat[ListFormat["Modifiers"] = 262656] = "Modifiers"; + ListFormat[ListFormat["HeritageClauses"] = 512] = "HeritageClauses"; + ListFormat[ListFormat["SingleLineTypeLiteralMembers"] = 768] = "SingleLineTypeLiteralMembers"; + ListFormat[ListFormat["MultiLineTypeLiteralMembers"] = 32897] = "MultiLineTypeLiteralMembers"; + ListFormat[ListFormat["TupleTypeElements"] = 528] = "TupleTypeElements"; + ListFormat[ListFormat["UnionTypeConstituents"] = 516] = "UnionTypeConstituents"; + ListFormat[ListFormat["IntersectionTypeConstituents"] = 520] = "IntersectionTypeConstituents"; + ListFormat[ListFormat["ObjectBindingPatternElements"] = 525136] = "ObjectBindingPatternElements"; + ListFormat[ListFormat["ArrayBindingPatternElements"] = 524880] = "ArrayBindingPatternElements"; + ListFormat[ListFormat["ObjectLiteralExpressionProperties"] = 526226] = "ObjectLiteralExpressionProperties"; + ListFormat[ListFormat["ArrayLiteralExpressionElements"] = 8914] = "ArrayLiteralExpressionElements"; + ListFormat[ListFormat["CommaListElements"] = 528] = "CommaListElements"; + ListFormat[ListFormat["CallExpressionArguments"] = 2576] = "CallExpressionArguments"; + ListFormat[ListFormat["NewExpressionArguments"] = 18960] = "NewExpressionArguments"; + ListFormat[ListFormat["TemplateExpressionSpans"] = 262144] = "TemplateExpressionSpans"; + ListFormat[ListFormat["SingleLineBlockStatements"] = 768] = "SingleLineBlockStatements"; + ListFormat[ListFormat["MultiLineBlockStatements"] = 129] = "MultiLineBlockStatements"; + ListFormat[ListFormat["VariableDeclarationList"] = 528] = "VariableDeclarationList"; + ListFormat[ListFormat["SingleLineFunctionBodyStatements"] = 768] = "SingleLineFunctionBodyStatements"; + ListFormat[ListFormat["MultiLineFunctionBodyStatements"] = 1] = "MultiLineFunctionBodyStatements"; + ListFormat[ListFormat["ClassHeritageClauses"] = 0] = "ClassHeritageClauses"; + ListFormat[ListFormat["ClassMembers"] = 129] = "ClassMembers"; + ListFormat[ListFormat["InterfaceMembers"] = 129] = "InterfaceMembers"; + ListFormat[ListFormat["EnumMembers"] = 145] = "EnumMembers"; + ListFormat[ListFormat["CaseBlockClauses"] = 129] = "CaseBlockClauses"; + ListFormat[ListFormat["NamedImportsOrExportsElements"] = 525136] = "NamedImportsOrExportsElements"; + ListFormat[ListFormat["JsxElementOrFragmentChildren"] = 262144] = "JsxElementOrFragmentChildren"; + ListFormat[ListFormat["JsxElementAttributes"] = 262656] = "JsxElementAttributes"; + ListFormat[ListFormat["CaseOrDefaultClauseStatements"] = 163969] = "CaseOrDefaultClauseStatements"; + ListFormat[ListFormat["HeritageClauseTypes"] = 528] = "HeritageClauseTypes"; + ListFormat[ListFormat["SourceFileStatements"] = 131073] = "SourceFileStatements"; + ListFormat[ListFormat["Decorators"] = 49153] = "Decorators"; + ListFormat[ListFormat["TypeArguments"] = 53776] = "TypeArguments"; + ListFormat[ListFormat["TypeParameters"] = 53776] = "TypeParameters"; + ListFormat[ListFormat["Parameters"] = 2576] = "Parameters"; + ListFormat[ListFormat["IndexSignatureParameters"] = 8848] = "IndexSignatureParameters"; + ListFormat[ListFormat["JSDocComment"] = 33] = "JSDocComment"; + })(ListFormat = ts.ListFormat || (ts.ListFormat = {})); + /* @internal */ + var PragmaKindFlags; + (function (PragmaKindFlags) { + PragmaKindFlags[PragmaKindFlags["None"] = 0] = "None"; + /** + * Triple slash comment of the form + * /// + */ + PragmaKindFlags[PragmaKindFlags["TripleSlashXML"] = 1] = "TripleSlashXML"; + /** + * Single line comment of the form + * // @pragma-name argval1 argval2 + * or + * /// @pragma-name argval1 argval2 + */ + PragmaKindFlags[PragmaKindFlags["SingleLine"] = 2] = "SingleLine"; + /** + * Multiline non-jsdoc pragma of the form + * /* @pragma-name argval1 argval2 * / + */ + PragmaKindFlags[PragmaKindFlags["MultiLine"] = 4] = "MultiLine"; + PragmaKindFlags[PragmaKindFlags["All"] = 7] = "All"; + PragmaKindFlags[PragmaKindFlags["Default"] = 7] = "Default"; + })(PragmaKindFlags = ts.PragmaKindFlags || (ts.PragmaKindFlags = {})); + /** + * This function only exists to cause exact types to be inferred for all the literals within `commentPragmas` + */ + /* @internal */ + function _contextuallyTypePragmas(args) { + return args; + } + // While not strictly a type, this is here because `PragmaMap` needs to be here to be used with `SourceFile`, and we don't + // fancy effectively defining it twice, once in value-space and once in type-space + /* @internal */ + ts.commentPragmas = _contextuallyTypePragmas({ + "reference": { + args: [ + { name: "types", optional: true, captureSpan: true }, + { name: "lib", optional: true, captureSpan: true }, + { name: "path", optional: true, captureSpan: true }, + { name: "no-default-lib", optional: true } + ], + kind: 1 /* TripleSlashXML */ + }, + "amd-dependency": { + args: [{ name: "path" }, { name: "name", optional: true }], + kind: 1 /* TripleSlashXML */ + }, + "amd-module": { + args: [{ name: "name" }], + kind: 1 /* TripleSlashXML */ + }, + "ts-check": { + kind: 2 /* SingleLine */ + }, + "ts-nocheck": { + kind: 2 /* SingleLine */ + }, + "jsx": { + args: [{ name: "factory" }], + kind: 4 /* MultiLine */ + }, + }); +})(ts || (ts = {})); +var ts; +(function (ts) { + /** + * Set a high stack trace limit to provide more information in case of an error. + * Called for command-line and server use cases. + * Not called if TypeScript is used as a library. + */ + /* @internal */ + function setStackTraceLimit() { + if (Error.stackTraceLimit < 100) { // Also tests that we won't set the property if it doesn't exist. + Error.stackTraceLimit = 100; + } + } + ts.setStackTraceLimit = setStackTraceLimit; + var FileWatcherEventKind; + (function (FileWatcherEventKind) { + FileWatcherEventKind[FileWatcherEventKind["Created"] = 0] = "Created"; + FileWatcherEventKind[FileWatcherEventKind["Changed"] = 1] = "Changed"; + FileWatcherEventKind[FileWatcherEventKind["Deleted"] = 2] = "Deleted"; + })(FileWatcherEventKind = ts.FileWatcherEventKind || (ts.FileWatcherEventKind = {})); + /* @internal */ + var PollingInterval; + (function (PollingInterval) { + PollingInterval[PollingInterval["High"] = 2000] = "High"; + PollingInterval[PollingInterval["Medium"] = 500] = "Medium"; + PollingInterval[PollingInterval["Low"] = 250] = "Low"; + })(PollingInterval = ts.PollingInterval || (ts.PollingInterval = {})); + /* @internal */ + ts.missingFileModifiedTime = new Date(0); // Any subsequent modification will occur after this time + function createPollingIntervalBasedLevels(levels) { + var _a; + return _a = {}, + _a[PollingInterval.Low] = levels.Low, + _a[PollingInterval.Medium] = levels.Medium, + _a[PollingInterval.High] = levels.High, + _a; + } + var defaultChunkLevels = { Low: 32, Medium: 64, High: 256 }; + var pollingChunkSize = createPollingIntervalBasedLevels(defaultChunkLevels); + /* @internal */ + ts.unchangedPollThresholds = createPollingIntervalBasedLevels(defaultChunkLevels); + /* @internal */ + function setCustomPollingValues(system) { + if (!system.getEnvironmentVariable) { + return; + } + var pollingIntervalChanged = setCustomLevels("TSC_WATCH_POLLINGINTERVAL", PollingInterval); + pollingChunkSize = getCustomPollingBasedLevels("TSC_WATCH_POLLINGCHUNKSIZE", defaultChunkLevels) || pollingChunkSize; + ts.unchangedPollThresholds = getCustomPollingBasedLevels("TSC_WATCH_UNCHANGEDPOLLTHRESHOLDS", defaultChunkLevels) || ts.unchangedPollThresholds; + function getLevel(envVar, level) { + return system.getEnvironmentVariable(envVar + "_" + level.toUpperCase()); + } + function getCustomLevels(baseVariable) { + var customLevels; + setCustomLevel("Low"); + setCustomLevel("Medium"); + setCustomLevel("High"); + return customLevels; + function setCustomLevel(level) { + var customLevel = getLevel(baseVariable, level); + if (customLevel) { + (customLevels || (customLevels = {}))[level] = Number(customLevel); + } + } + } + function setCustomLevels(baseVariable, levels) { + var customLevels = getCustomLevels(baseVariable); + if (customLevels) { + setLevel("Low"); + setLevel("Medium"); + setLevel("High"); + return true; + } + return false; + function setLevel(level) { + levels[level] = customLevels[level] || levels[level]; + } + } + function getCustomPollingBasedLevels(baseVariable, defaultLevels) { + var customLevels = getCustomLevels(baseVariable); + return (pollingIntervalChanged || customLevels) && + createPollingIntervalBasedLevels(customLevels ? __assign({}, defaultLevels, customLevels) : defaultLevels); + } + } + ts.setCustomPollingValues = setCustomPollingValues; + /* @internal */ + function createDynamicPriorityPollingWatchFile(host) { + var watchedFiles = []; + var changedFilesInLastPoll = []; + var lowPollingIntervalQueue = createPollingIntervalQueue(PollingInterval.Low); + var mediumPollingIntervalQueue = createPollingIntervalQueue(PollingInterval.Medium); + var highPollingIntervalQueue = createPollingIntervalQueue(PollingInterval.High); + return watchFile; + function watchFile(fileName, callback, defaultPollingInterval) { + var file = { + fileName: fileName, + callback: callback, + unchangedPolls: 0, + mtime: getModifiedTime(fileName) + }; + watchedFiles.push(file); + addToPollingIntervalQueue(file, defaultPollingInterval); + return { + close: function () { + file.isClosed = true; + // Remove from watchedFiles + ts.unorderedRemoveItem(watchedFiles, file); + // Do not update polling interval queue since that will happen as part of polling + } + }; + } + function createPollingIntervalQueue(pollingInterval) { + var queue = []; + queue.pollingInterval = pollingInterval; + queue.pollIndex = 0; + queue.pollScheduled = false; + return queue; + } + function pollPollingIntervalQueue(queue) { + queue.pollIndex = pollQueue(queue, queue.pollingInterval, queue.pollIndex, pollingChunkSize[queue.pollingInterval]); + // Set the next polling index and timeout + if (queue.length) { + scheduleNextPoll(queue.pollingInterval); + } + else { + ts.Debug.assert(queue.pollIndex === 0); + queue.pollScheduled = false; + } + } + function pollLowPollingIntervalQueue(queue) { + // Always poll complete list of changedFilesInLastPoll + pollQueue(changedFilesInLastPoll, PollingInterval.Low, /*pollIndex*/ 0, changedFilesInLastPoll.length); + // Finally do the actual polling of the queue + pollPollingIntervalQueue(queue); + // Schedule poll if there are files in changedFilesInLastPoll but no files in the actual queue + // as pollPollingIntervalQueue wont schedule for next poll + if (!queue.pollScheduled && changedFilesInLastPoll.length) { + scheduleNextPoll(PollingInterval.Low); + } + } + function pollQueue(queue, pollingInterval, pollIndex, chunkSize) { + // Max visit would be all elements of the queue + var needsVisit = queue.length; + var definedValueCopyToIndex = pollIndex; + for (var polled = 0; polled < chunkSize && needsVisit > 0; nextPollIndex(), needsVisit--) { + var watchedFile = queue[pollIndex]; + if (!watchedFile) { + continue; + } + else if (watchedFile.isClosed) { + queue[pollIndex] = undefined; + continue; + } + polled++; + var fileChanged = onWatchedFileStat(watchedFile, getModifiedTime(watchedFile.fileName)); + if (watchedFile.isClosed) { + // Closed watcher as part of callback + queue[pollIndex] = undefined; + } + else if (fileChanged) { + watchedFile.unchangedPolls = 0; + // Changed files go to changedFilesInLastPoll queue + if (queue !== changedFilesInLastPoll) { + queue[pollIndex] = undefined; + addChangedFileToLowPollingIntervalQueue(watchedFile); + } + } + else if (watchedFile.unchangedPolls !== ts.unchangedPollThresholds[pollingInterval]) { + watchedFile.unchangedPolls++; + } + else if (queue === changedFilesInLastPoll) { + // Restart unchangedPollCount for unchanged file and move to low polling interval queue + watchedFile.unchangedPolls = 1; + queue[pollIndex] = undefined; + addToPollingIntervalQueue(watchedFile, PollingInterval.Low); + } + else if (pollingInterval !== PollingInterval.High) { + watchedFile.unchangedPolls++; + queue[pollIndex] = undefined; + addToPollingIntervalQueue(watchedFile, pollingInterval === PollingInterval.Low ? PollingInterval.Medium : PollingInterval.High); + } + if (queue[pollIndex]) { + // Copy this file to the non hole location + if (definedValueCopyToIndex < pollIndex) { + queue[definedValueCopyToIndex] = watchedFile; + queue[pollIndex] = undefined; + } + definedValueCopyToIndex++; + } + } + // Return next poll index + return pollIndex; + function nextPollIndex() { + pollIndex++; + if (pollIndex === queue.length) { + if (definedValueCopyToIndex < pollIndex) { + // There are holes from nextDefinedValueIndex to end of queue, change queue size + queue.length = definedValueCopyToIndex; + } + pollIndex = 0; + definedValueCopyToIndex = 0; + } + } + } + function pollingIntervalQueue(pollingInterval) { + switch (pollingInterval) { + case PollingInterval.Low: + return lowPollingIntervalQueue; + case PollingInterval.Medium: + return mediumPollingIntervalQueue; + case PollingInterval.High: + return highPollingIntervalQueue; + } + } + function addToPollingIntervalQueue(file, pollingInterval) { + pollingIntervalQueue(pollingInterval).push(file); + scheduleNextPollIfNotAlreadyScheduled(pollingInterval); + } + function addChangedFileToLowPollingIntervalQueue(file) { + changedFilesInLastPoll.push(file); + scheduleNextPollIfNotAlreadyScheduled(PollingInterval.Low); + } + function scheduleNextPollIfNotAlreadyScheduled(pollingInterval) { + if (!pollingIntervalQueue(pollingInterval).pollScheduled) { + scheduleNextPoll(pollingInterval); + } + } + function scheduleNextPoll(pollingInterval) { + pollingIntervalQueue(pollingInterval).pollScheduled = host.setTimeout(pollingInterval === PollingInterval.Low ? pollLowPollingIntervalQueue : pollPollingIntervalQueue, pollingInterval, pollingIntervalQueue(pollingInterval)); + } + function getModifiedTime(fileName) { + return host.getModifiedTime(fileName) || ts.missingFileModifiedTime; + } + } + ts.createDynamicPriorityPollingWatchFile = createDynamicPriorityPollingWatchFile; + /** + * Returns true if file status changed + */ + /*@internal*/ + function onWatchedFileStat(watchedFile, modifiedTime) { + var oldTime = watchedFile.mtime.getTime(); + var newTime = modifiedTime.getTime(); + if (oldTime !== newTime) { + watchedFile.mtime = modifiedTime; + watchedFile.callback(watchedFile.fileName, getFileWatcherEventKind(oldTime, newTime)); + return true; + } + return false; + } + ts.onWatchedFileStat = onWatchedFileStat; + /*@internal*/ + function getFileWatcherEventKind(oldTime, newTime) { + return oldTime === 0 + ? FileWatcherEventKind.Created + : newTime === 0 + ? FileWatcherEventKind.Deleted + : FileWatcherEventKind.Changed; + } + ts.getFileWatcherEventKind = getFileWatcherEventKind; + /** + * Watch the directory recursively using host provided method to watch child directories + * that means if this is recursive watcher, watch the children directories as well + * (eg on OS that dont support recursive watch using fs.watch use fs.watchFile) + */ + /*@internal*/ + function createRecursiveDirectoryWatcher(host) { + var cache = ts.createMap(); + var callbackCache = ts.createMultiMap(); + var filePathComparer = ts.getStringComparer(!host.useCaseSensitiveFileNames); + var toCanonicalFilePath = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); + return createDirectoryWatcher; + /** + * Create the directory watcher for the dirPath. + */ + function createDirectoryWatcher(dirName, callback) { + var dirPath = toCanonicalFilePath(dirName); + var directoryWatcher = cache.get(dirPath); + if (directoryWatcher) { + directoryWatcher.refCount++; + } + else { + directoryWatcher = { + watcher: host.watchDirectory(dirName, function (fileName) { + // Call the actual callback + callbackCache.forEach(function (callbacks, rootDirName) { + if (rootDirName === dirPath || (ts.startsWith(dirPath, rootDirName) && dirPath[rootDirName.length] === ts.directorySeparator)) { + callbacks.forEach(function (callback) { return callback(fileName); }); + } + }); + // Iterate through existing children and update the watches if needed + updateChildWatches(dirName, dirPath); + }), + refCount: 1, + childWatches: ts.emptyArray + }; + cache.set(dirPath, directoryWatcher); + updateChildWatches(dirName, dirPath); + } + if (callback) { + callbackCache.add(dirPath, callback); + } + return { + dirName: dirName, + close: function () { + var directoryWatcher = ts.Debug.assertDefined(cache.get(dirPath)); + if (callback) + callbackCache.remove(dirPath, callback); + directoryWatcher.refCount--; + if (directoryWatcher.refCount) + return; + cache.delete(dirPath); + ts.closeFileWatcherOf(directoryWatcher); + directoryWatcher.childWatches.forEach(ts.closeFileWatcher); + } + }; + } + function updateChildWatches(dirName, dirPath) { + // Iterate through existing children and update the watches if needed + var parentWatcher = cache.get(dirPath); + if (parentWatcher) { + parentWatcher.childWatches = watchChildDirectories(dirName, parentWatcher.childWatches); + } + } + /** + * Watch the directories in the parentDir + */ + function watchChildDirectories(parentDir, existingChildWatches) { + var newChildWatches; + ts.enumerateInsertsAndDeletes(host.directoryExists(parentDir) ? ts.mapDefined(host.getAccessibleSortedChildDirectories(parentDir), function (child) { + var childFullName = ts.getNormalizedAbsolutePath(child, parentDir); + // Filter our the symbolic link directories since those arent included in recursive watch + // which is same behaviour when recursive: true is passed to fs.watch + return filePathComparer(childFullName, ts.normalizePath(host.realpath(childFullName))) === 0 /* EqualTo */ ? childFullName : undefined; + }) : ts.emptyArray, existingChildWatches, function (child, childWatcher) { return filePathComparer(child, childWatcher.dirName); }, createAndAddChildDirectoryWatcher, ts.closeFileWatcher, addChildDirectoryWatcher); + return newChildWatches || ts.emptyArray; + /** + * Create new childDirectoryWatcher and add it to the new ChildDirectoryWatcher list + */ + function createAndAddChildDirectoryWatcher(childName) { + var result = createDirectoryWatcher(childName); + addChildDirectoryWatcher(result); + } + /** + * Add child directory watcher to the new ChildDirectoryWatcher list + */ + function addChildDirectoryWatcher(childWatcher) { + (newChildWatches || (newChildWatches = [])).push(childWatcher); + } + } + } + ts.createRecursiveDirectoryWatcher = createRecursiveDirectoryWatcher; + function getNodeMajorVersion() { + if (typeof process === "undefined") { + return undefined; + } + var version = process.version; + if (!version) { + return undefined; + } + var dot = version.indexOf("."); + if (dot === -1) { + return undefined; + } + return parseInt(version.substring(1, dot)); + } + ts.getNodeMajorVersion = getNodeMajorVersion; + // TODO: GH#18217 this is used as if it's certainly defined in many places. + ts.sys = (function () { + // NodeJS detects "\uFEFF" at the start of the string and *replaces* it with the actual + // byte order mark from the specified encoding. Using any other byte order mark does + // not actually work. + var byteOrderMarkIndicator = "\uFEFF"; + function getNodeSystem() { + var _fs = require("fs"); + var _path = require("path"); + var _os = require("os"); + // crypto can be absent on reduced node installations + var _crypto; + try { + _crypto = require("crypto"); + } + catch (_a) { + _crypto = undefined; + } + var Buffer = require("buffer").Buffer; + var nodeVersion = getNodeMajorVersion(); + var isNode4OrLater = nodeVersion >= 4; + var platform = _os.platform(); + var useCaseSensitiveFileNames = isFileSystemCaseSensitive(); + var FileSystemEntryKind; + (function (FileSystemEntryKind) { + FileSystemEntryKind[FileSystemEntryKind["File"] = 0] = "File"; + FileSystemEntryKind[FileSystemEntryKind["Directory"] = 1] = "Directory"; + })(FileSystemEntryKind || (FileSystemEntryKind = {})); + var useNonPollingWatchers = process.env.TSC_NONPOLLING_WATCHER; + var tscWatchFile = process.env.TSC_WATCHFILE; + var tscWatchDirectory = process.env.TSC_WATCHDIRECTORY; + var dynamicPollingWatchFile; + var nodeSystem = { + args: process.argv.slice(2), + newLine: _os.EOL, + useCaseSensitiveFileNames: useCaseSensitiveFileNames, + write: function (s) { + process.stdout.write(s); + }, + writeOutputIsTTY: function () { + return process.stdout.isTTY; + }, + readFile: readFile, + writeFile: writeFile, + watchFile: getWatchFile(), + watchDirectory: getWatchDirectory(), + resolvePath: function (path) { return _path.resolve(path); }, + fileExists: fileExists, + directoryExists: directoryExists, + createDirectory: function (directoryName) { + if (!nodeSystem.directoryExists(directoryName)) { + _fs.mkdirSync(directoryName); + } + }, + getExecutingFilePath: function () { + return __filename; + }, + getCurrentDirectory: function () { + return process.cwd(); + }, + getDirectories: getDirectories, + getEnvironmentVariable: function (name) { + return process.env[name] || ""; + }, + readDirectory: readDirectory, + getModifiedTime: getModifiedTime, + setModifiedTime: setModifiedTime, + deleteFile: deleteFile, + createHash: _crypto ? createMD5HashUsingNativeCrypto : generateDjb2Hash, + createSHA256Hash: _crypto ? createSHA256Hash : undefined, + getMemoryUsage: function () { + if (global.gc) { + global.gc(); + } + return process.memoryUsage().heapUsed; + }, + getFileSize: function (path) { + try { + var stat = _fs.statSync(path); + if (stat.isFile()) { + return stat.size; + } + } + catch ( /*ignore*/_a) { /*ignore*/ } + return 0; + }, + exit: function (exitCode) { + process.exit(exitCode); + }, + realpath: realpath, + debugMode: ts.some(process.execArgv, function (arg) { return /^--(inspect|debug)(-brk)?(=\d+)?$/i.test(arg); }), + tryEnableSourceMapsForHost: function () { + try { + require("source-map-support").install(); + } + catch (_a) { + // Could not enable source maps. + } + }, + setTimeout: setTimeout, + clearTimeout: clearTimeout, + clearScreen: function () { + process.stdout.write("\x1Bc"); + }, + setBlocking: function () { + if (process.stdout && process.stdout._handle && process.stdout._handle.setBlocking) { + process.stdout._handle.setBlocking(true); + } + }, + bufferFrom: bufferFrom, + base64decode: function (input) { return bufferFrom(input, "base64").toString("utf8"); }, + base64encode: function (input) { return bufferFrom(input).toString("base64"); }, + }; + return nodeSystem; + function bufferFrom(input, encoding) { + // See https://github.com/Microsoft/TypeScript/issues/25652 + return Buffer.from && Buffer.from !== Int8Array.from + ? Buffer.from(input, encoding) + : new Buffer(input, encoding); + } + function isFileSystemCaseSensitive() { + // win32\win64 are case insensitive platforms + if (platform === "win32" || platform === "win64") { + return false; + } + // If this file exists under a different case, we must be case-insensitve. + return !fileExists(swapCase(__filename)); + } + /** Convert all lowercase chars to uppercase, and vice-versa */ + function swapCase(s) { + return s.replace(/\w/g, function (ch) { + var up = ch.toUpperCase(); + return ch === up ? ch.toLowerCase() : up; + }); + } + function getWatchFile() { + switch (tscWatchFile) { + case "PriorityPollingInterval": + // Use polling interval based on priority when create watch using host.watchFile + return fsWatchFile; + case "DynamicPriorityPolling": + // Use polling interval but change the interval depending on file changes and their default polling interval + return createDynamicPriorityPollingWatchFile({ getModifiedTime: getModifiedTime, setTimeout: setTimeout }); + case "UseFsEvents": + // Use notifications from FS to watch with falling back to fs.watchFile + return watchFileUsingFsWatch; + case "UseFsEventsWithFallbackDynamicPolling": + // Use notifications from FS to watch with falling back to dynamic watch file + dynamicPollingWatchFile = createDynamicPriorityPollingWatchFile({ getModifiedTime: getModifiedTime, setTimeout: setTimeout }); + return createWatchFileUsingDynamicWatchFile(dynamicPollingWatchFile); + case "UseFsEventsOnParentDirectory": + // Use notifications from FS to watch with falling back to fs.watchFile + return createNonPollingWatchFile(); + } + return useNonPollingWatchers ? + createNonPollingWatchFile() : + // Default to do not use polling interval as it is before this experiment branch + function (fileName, callback) { return fsWatchFile(fileName, callback); }; + } + function getWatchDirectory() { + // Node 4.0 `fs.watch` function supports the "recursive" option on both OSX and Windows + // (ref: https://github.com/nodejs/node/pull/2649 and https://github.com/Microsoft/TypeScript/issues/4643) + var fsSupportsRecursive = isNode4OrLater && (process.platform === "win32" || process.platform === "darwin"); + if (fsSupportsRecursive) { + return watchDirectoryUsingFsWatch; + } + var watchDirectory = tscWatchDirectory === "RecursiveDirectoryUsingFsWatchFile" ? + createWatchDirectoryUsing(fsWatchFile) : + tscWatchDirectory === "RecursiveDirectoryUsingDynamicPriorityPolling" ? + createWatchDirectoryUsing(dynamicPollingWatchFile || createDynamicPriorityPollingWatchFile({ getModifiedTime: getModifiedTime, setTimeout: setTimeout })) : + watchDirectoryUsingFsWatch; + var watchDirectoryRecursively = createRecursiveDirectoryWatcher({ + useCaseSensitiveFileNames: useCaseSensitiveFileNames, + directoryExists: directoryExists, + getAccessibleSortedChildDirectories: function (path) { return getAccessibleFileSystemEntries(path).directories; }, + watchDirectory: watchDirectory, + realpath: realpath + }); + return function (directoryName, callback, recursive) { + if (recursive) { + return watchDirectoryRecursively(directoryName, callback); + } + return watchDirectory(directoryName, callback); + }; + } + function createNonPollingWatchFile() { + // One file can have multiple watchers + var fileWatcherCallbacks = ts.createMultiMap(); + var dirWatchers = ts.createMap(); + var toCanonicalName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); + return nonPollingWatchFile; + function nonPollingWatchFile(fileName, callback) { + var filePath = toCanonicalName(fileName); + fileWatcherCallbacks.add(filePath, callback); + var dirPath = ts.getDirectoryPath(filePath) || "."; + var watcher = dirWatchers.get(dirPath) || createDirectoryWatcher(ts.getDirectoryPath(fileName) || ".", dirPath); + watcher.referenceCount++; + return { + close: function () { + if (watcher.referenceCount === 1) { + watcher.close(); + dirWatchers.delete(dirPath); + } + else { + watcher.referenceCount--; + } + fileWatcherCallbacks.remove(filePath, callback); + } + }; + } + function createDirectoryWatcher(dirName, dirPath) { + var watcher = fsWatchDirectory(dirName, function (_eventName, relativeFileName) { + // When files are deleted from disk, the triggered "rename" event would have a relativefileName of "undefined" + if (!ts.isString(relativeFileName)) { + return; + } + var fileName = ts.getNormalizedAbsolutePath(relativeFileName, dirName); + // Some applications save a working file via rename operations + var callbacks = fileName && fileWatcherCallbacks.get(toCanonicalName(fileName)); + if (callbacks) { + for (var _i = 0, callbacks_1 = callbacks; _i < callbacks_1.length; _i++) { + var fileCallback = callbacks_1[_i]; + fileCallback(fileName, FileWatcherEventKind.Changed); + } + } + }); + watcher.referenceCount = 0; + dirWatchers.set(dirPath, watcher); + return watcher; + } + } + function fsWatchFile(fileName, callback, pollingInterval) { + _fs.watchFile(fileName, { persistent: true, interval: pollingInterval || 250 }, fileChanged); + var eventKind; + return { + close: function () { return _fs.unwatchFile(fileName, fileChanged); } + }; + function fileChanged(curr, prev) { + // previous event kind check is to ensure we recongnize the file as previously also missing when it is restored or renamed twice (that is it disappears and reappears) + // In such case, prevTime returned is same as prev time of event when file was deleted as per node documentation + var isPreviouslyDeleted = +prev.mtime === 0 || eventKind === FileWatcherEventKind.Deleted; + if (+curr.mtime === 0) { + if (isPreviouslyDeleted) { + // Already deleted file, no need to callback again + return; + } + eventKind = FileWatcherEventKind.Deleted; + } + else if (isPreviouslyDeleted) { + eventKind = FileWatcherEventKind.Created; + } + // If there is no change in modified time, ignore the event + else if (+curr.mtime === +prev.mtime) { + return; + } + else { + // File changed + eventKind = FileWatcherEventKind.Changed; + } + callback(fileName, eventKind); + } + } + function createFileWatcherCallback(callback) { + return function (_fileName, eventKind) { return callback(eventKind === FileWatcherEventKind.Changed ? "change" : "rename", ""); }; + } + function createFsWatchCallbackForFileWatcherCallback(fileName, callback) { + return function (eventName) { + if (eventName === "rename") { + callback(fileName, fileExists(fileName) ? FileWatcherEventKind.Created : FileWatcherEventKind.Deleted); + } + else { + // Change + callback(fileName, FileWatcherEventKind.Changed); + } + }; + } + function createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback) { + return function (eventName, relativeFileName) { + // In watchDirectory we only care about adding and removing files (when event name is + // "rename"); changes made within files are handled by corresponding fileWatchers (when + // event name is "change") + if (eventName === "rename") { + // When deleting a file, the passed baseFileName is null + callback(!relativeFileName ? directoryName : ts.normalizePath(ts.combinePaths(directoryName, relativeFileName))); + } + }; + } + function fsWatch(fileOrDirectory, entryKind, callback, recursive, fallbackPollingWatchFile, pollingInterval) { + var options; + /** Watcher for the file system entry depending on whether it is missing or present */ + var watcher = !fileSystemEntryExists(fileOrDirectory, entryKind) ? + watchMissingFileSystemEntry() : + watchPresentFileSystemEntry(); + return { + close: function () { + // Close the watcher (either existing file system entry watcher or missing file system entry watcher) + watcher.close(); + watcher = undefined; + } + }; + /** + * Invoke the callback with rename and update the watcher if not closed + * @param createWatcher + */ + function invokeCallbackAndUpdateWatcher(createWatcher) { + // Call the callback for current directory + callback("rename", ""); + // If watcher is not closed, update it + if (watcher) { + watcher.close(); + watcher = createWatcher(); + } + } + /** + * Watch the file or directory that is currently present + * and when the watched file or directory is deleted, switch to missing file system entry watcher + */ + function watchPresentFileSystemEntry() { + // Node 4.0 `fs.watch` function supports the "recursive" option on both OSX and Windows + // (ref: https://github.com/nodejs/node/pull/2649 and https://github.com/Microsoft/TypeScript/issues/4643) + if (options === undefined) { + if (isNode4OrLater && (process.platform === "win32" || process.platform === "darwin")) { + options = { persistent: true, recursive: !!recursive }; + } + else { + options = { persistent: true }; + } + } + try { + var presentWatcher = _fs.watch(fileOrDirectory, options, callback); + // Watch the missing file or directory or error + presentWatcher.on("error", function () { return invokeCallbackAndUpdateWatcher(watchMissingFileSystemEntry); }); + return presentWatcher; + } + catch (e) { + // Catch the exception and use polling instead + // Eg. on linux the number of watches are limited and one could easily exhaust watches and the exception ENOSPC is thrown when creating watcher at that point + // so instead of throwing error, use fs.watchFile + return watchPresentFileSystemEntryWithFsWatchFile(); + } + } + /** + * Watch the file or directory using fs.watchFile since fs.watch threw exception + * Eg. on linux the number of watches are limited and one could easily exhaust watches and the exception ENOSPC is thrown when creating watcher at that point + */ + function watchPresentFileSystemEntryWithFsWatchFile() { + return fallbackPollingWatchFile(fileOrDirectory, createFileWatcherCallback(callback), pollingInterval); + } + /** + * Watch the file or directory that is missing + * and switch to existing file or directory when the missing filesystem entry is created + */ + function watchMissingFileSystemEntry() { + return fallbackPollingWatchFile(fileOrDirectory, function (_fileName, eventKind) { + if (eventKind === FileWatcherEventKind.Created && fileSystemEntryExists(fileOrDirectory, entryKind)) { + // Call the callback for current file or directory + // For now it could be callback for the inner directory creation, + // but just return current directory, better than current no-op + invokeCallbackAndUpdateWatcher(watchPresentFileSystemEntry); + } + }, pollingInterval); + } + } + function watchFileUsingFsWatch(fileName, callback, pollingInterval) { + return fsWatch(fileName, 0 /* File */, createFsWatchCallbackForFileWatcherCallback(fileName, callback), /*recursive*/ false, fsWatchFile, pollingInterval); + } + function createWatchFileUsingDynamicWatchFile(watchFile) { + return function (fileName, callback, pollingInterval) { return fsWatch(fileName, 0 /* File */, createFsWatchCallbackForFileWatcherCallback(fileName, callback), /*recursive*/ false, watchFile, pollingInterval); }; + } + function fsWatchDirectory(directoryName, callback, recursive) { + return fsWatch(directoryName, 1 /* Directory */, callback, !!recursive, fsWatchFile); + } + function watchDirectoryUsingFsWatch(directoryName, callback, recursive) { + return fsWatchDirectory(directoryName, createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback), recursive); + } + function createWatchDirectoryUsing(fsWatchFile) { + return function (directoryName, callback) { return fsWatchFile(directoryName, function () { return callback(directoryName); }, PollingInterval.Medium); }; + } + function readFile(fileName, _encoding) { + if (!fileExists(fileName)) { + return undefined; + } + var buffer = _fs.readFileSync(fileName); + var len = buffer.length; + if (len >= 2 && buffer[0] === 0xFE && buffer[1] === 0xFF) { + // Big endian UTF-16 byte order mark detected. Since big endian is not supported by node.js, + // flip all byte pairs and treat as little endian. + len &= ~1; // Round down to a multiple of 2 + for (var i = 0; i < len; i += 2) { + var temp = buffer[i]; + buffer[i] = buffer[i + 1]; + buffer[i + 1] = temp; + } + return buffer.toString("utf16le", 2); + } + if (len >= 2 && buffer[0] === 0xFF && buffer[1] === 0xFE) { + // Little endian UTF-16 byte order mark detected + return buffer.toString("utf16le", 2); + } + if (len >= 3 && buffer[0] === 0xEF && buffer[1] === 0xBB && buffer[2] === 0xBF) { + // UTF-8 byte order mark detected + return buffer.toString("utf8", 3); + } + // Default is UTF-8 with no byte order mark + return buffer.toString("utf8"); + } + function writeFile(fileName, data, writeByteOrderMark) { + // If a BOM is required, emit one + if (writeByteOrderMark) { + data = byteOrderMarkIndicator + data; + } + var fd; + try { + fd = _fs.openSync(fileName, "w"); + _fs.writeSync(fd, data, /*position*/ undefined, "utf8"); + } + finally { + if (fd !== undefined) { + _fs.closeSync(fd); + } + } + } + function getAccessibleFileSystemEntries(path) { + try { + var entries = _fs.readdirSync(path || ".").sort(); + var files = []; + var directories = []; + for (var _i = 0, entries_2 = entries; _i < entries_2.length; _i++) { + var entry = entries_2[_i]; + // This is necessary because on some file system node fails to exclude + // "." and "..". See https://github.com/nodejs/node/issues/4002 + if (entry === "." || entry === "..") { + continue; + } + var name = ts.combinePaths(path, entry); + var stat = void 0; + try { + stat = _fs.statSync(name); + } + catch (e) { + continue; + } + if (stat.isFile()) { + files.push(entry); + } + else if (stat.isDirectory()) { + directories.push(entry); + } + } + return { files: files, directories: directories }; + } + catch (e) { + return ts.emptyFileSystemEntries; + } + } + function readDirectory(path, extensions, excludes, includes, depth) { + return ts.matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, process.cwd(), depth, getAccessibleFileSystemEntries); + } + function fileSystemEntryExists(path, entryKind) { + try { + var stat = _fs.statSync(path); + switch (entryKind) { + case 0 /* File */: return stat.isFile(); + case 1 /* Directory */: return stat.isDirectory(); + default: return false; + } + } + catch (e) { + return false; + } + } + function fileExists(path) { + return fileSystemEntryExists(path, 0 /* File */); + } + function directoryExists(path) { + return fileSystemEntryExists(path, 1 /* Directory */); + } + function getDirectories(path) { + return ts.filter(_fs.readdirSync(path), function (dir) { return fileSystemEntryExists(ts.combinePaths(path, dir), 1 /* Directory */); }); + } + function realpath(path) { + try { + return _fs.realpathSync(path); + } + catch (_a) { + return path; + } + } + function getModifiedTime(path) { + try { + return _fs.statSync(path).mtime; + } + catch (e) { + return undefined; + } + } + function setModifiedTime(path, time) { + try { + _fs.utimesSync(path, time, time); + } + catch (e) { + return; + } + } + function deleteFile(path) { + try { + return _fs.unlinkSync(path); + } + catch (e) { + return; + } + } + /** + * djb2 hashing algorithm + * http://www.cse.yorku.ca/~oz/hash.html + */ + function generateDjb2Hash(data) { + var chars = data.split("").map(function (str) { return str.charCodeAt(0); }); + return "" + chars.reduce(function (prev, curr) { return ((prev << 5) + prev) + curr; }, 5381); + } + function createMD5HashUsingNativeCrypto(data) { + var hash = _crypto.createHash("md5"); + hash.update(data); + return hash.digest("hex"); + } + function createSHA256Hash(data) { + var hash = _crypto.createHash("sha256"); + hash.update(data); + return hash.digest("hex"); + } + } + function getChakraSystem() { + var realpath = ChakraHost.realpath && (function (path) { return ChakraHost.realpath(path); }); + return { + newLine: ChakraHost.newLine || "\r\n", + args: ChakraHost.args, + useCaseSensitiveFileNames: !!ChakraHost.useCaseSensitiveFileNames, + write: ChakraHost.echo, + readFile: function (path, _encoding) { + // encoding is automatically handled by the implementation in ChakraHost + return ChakraHost.readFile(path); + }, + writeFile: function (path, data, writeByteOrderMark) { + // If a BOM is required, emit one + if (writeByteOrderMark) { + data = byteOrderMarkIndicator + data; + } + ChakraHost.writeFile(path, data); + }, + resolvePath: ChakraHost.resolvePath, + fileExists: ChakraHost.fileExists, + deleteFile: ChakraHost.deleteFile, + getModifiedTime: ChakraHost.getModifiedTime, + setModifiedTime: ChakraHost.setModifiedTime, + directoryExists: ChakraHost.directoryExists, + createDirectory: ChakraHost.createDirectory, + getExecutingFilePath: function () { return ChakraHost.executingFile; }, + getCurrentDirectory: function () { return ChakraHost.currentDirectory; }, + getDirectories: ChakraHost.getDirectories, + getEnvironmentVariable: ChakraHost.getEnvironmentVariable || (function () { return ""; }), + readDirectory: function (path, extensions, excludes, includes, _depth) { + var pattern = ts.getFileMatcherPatterns(path, excludes, includes, !!ChakraHost.useCaseSensitiveFileNames, ChakraHost.currentDirectory); + return ChakraHost.readDirectory(path, extensions, pattern.basePaths, pattern.excludePattern, pattern.includeFilePattern, pattern.includeDirectoryPattern); + }, + exit: ChakraHost.quit, + realpath: realpath + }; + } + function recursiveCreateDirectory(directoryPath, sys) { + var basePath = ts.getDirectoryPath(directoryPath); + var shouldCreateParent = basePath !== "" && directoryPath !== basePath && !sys.directoryExists(basePath); + if (shouldCreateParent) { + recursiveCreateDirectory(basePath, sys); + } + if (shouldCreateParent || !sys.directoryExists(directoryPath)) { + sys.createDirectory(directoryPath); + } + } + var sys; + if (typeof ChakraHost !== "undefined") { + sys = getChakraSystem(); + } + else if (typeof process !== "undefined" && process.nextTick && !process.browser && typeof require !== "undefined") { + // process and process.nextTick checks if current environment is node-like + // process.browser check excludes webpack and browserify + sys = getNodeSystem(); + } + if (sys) { + // patch writefile to create folder before writing the file + var originalWriteFile_1 = sys.writeFile; + sys.writeFile = function (path, data, writeBom) { + var directoryPath = ts.getDirectoryPath(ts.normalizeSlashes(path)); + if (directoryPath && !sys.directoryExists(directoryPath)) { + recursiveCreateDirectory(directoryPath, sys); + } + originalWriteFile_1.call(sys, path, data, writeBom); + }; + } + return sys; + })(); + if (ts.sys && ts.sys.getEnvironmentVariable) { + setCustomPollingValues(ts.sys); + ts.Debug.currentAssertionLevel = /^development$/i.test(ts.sys.getEnvironmentVariable("NODE_ENV")) + ? 1 /* Normal */ + : 0 /* None */; + } + if (ts.sys && ts.sys.debugMode) { + ts.Debug.isDebugging = true; + } +})(ts || (ts = {})); +// +// generated from './diagnosticInformationMap.generated.ts' by 'src/compiler' +/* @internal */ +var ts; +(function (ts) { + function diag(code, category, key, message, reportsUnnecessary) { + return { code: code, category: category, key: key, message: message, reportsUnnecessary: reportsUnnecessary }; + } + // tslint:disable-next-line variable-name + ts.Diagnostics = { + Unterminated_string_literal: diag(1002, ts.DiagnosticCategory.Error, "Unterminated_string_literal_1002", "Unterminated string literal."), + Identifier_expected: diag(1003, ts.DiagnosticCategory.Error, "Identifier_expected_1003", "Identifier expected."), + _0_expected: diag(1005, ts.DiagnosticCategory.Error, "_0_expected_1005", "'{0}' expected."), + A_file_cannot_have_a_reference_to_itself: diag(1006, ts.DiagnosticCategory.Error, "A_file_cannot_have_a_reference_to_itself_1006", "A file cannot have a reference to itself."), + Trailing_comma_not_allowed: diag(1009, ts.DiagnosticCategory.Error, "Trailing_comma_not_allowed_1009", "Trailing comma not allowed."), + Asterisk_Slash_expected: diag(1010, ts.DiagnosticCategory.Error, "Asterisk_Slash_expected_1010", "'*/' expected."), + An_element_access_expression_should_take_an_argument: diag(1011, ts.DiagnosticCategory.Error, "An_element_access_expression_should_take_an_argument_1011", "An element access expression should take an argument."), + Unexpected_token: diag(1012, ts.DiagnosticCategory.Error, "Unexpected_token_1012", "Unexpected token."), + A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma: diag(1013, ts.DiagnosticCategory.Error, "A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma_1013", "A rest parameter or binding pattern may not have a trailing comma."), + A_rest_parameter_must_be_last_in_a_parameter_list: diag(1014, ts.DiagnosticCategory.Error, "A_rest_parameter_must_be_last_in_a_parameter_list_1014", "A rest parameter must be last in a parameter list."), + Parameter_cannot_have_question_mark_and_initializer: diag(1015, ts.DiagnosticCategory.Error, "Parameter_cannot_have_question_mark_and_initializer_1015", "Parameter cannot have question mark and initializer."), + A_required_parameter_cannot_follow_an_optional_parameter: diag(1016, ts.DiagnosticCategory.Error, "A_required_parameter_cannot_follow_an_optional_parameter_1016", "A required parameter cannot follow an optional parameter."), + An_index_signature_cannot_have_a_rest_parameter: diag(1017, ts.DiagnosticCategory.Error, "An_index_signature_cannot_have_a_rest_parameter_1017", "An index signature cannot have a rest parameter."), + An_index_signature_parameter_cannot_have_an_accessibility_modifier: diag(1018, ts.DiagnosticCategory.Error, "An_index_signature_parameter_cannot_have_an_accessibility_modifier_1018", "An index signature parameter cannot have an accessibility modifier."), + An_index_signature_parameter_cannot_have_a_question_mark: diag(1019, ts.DiagnosticCategory.Error, "An_index_signature_parameter_cannot_have_a_question_mark_1019", "An index signature parameter cannot have a question mark."), + An_index_signature_parameter_cannot_have_an_initializer: diag(1020, ts.DiagnosticCategory.Error, "An_index_signature_parameter_cannot_have_an_initializer_1020", "An index signature parameter cannot have an initializer."), + An_index_signature_must_have_a_type_annotation: diag(1021, ts.DiagnosticCategory.Error, "An_index_signature_must_have_a_type_annotation_1021", "An index signature must have a type annotation."), + An_index_signature_parameter_must_have_a_type_annotation: diag(1022, ts.DiagnosticCategory.Error, "An_index_signature_parameter_must_have_a_type_annotation_1022", "An index signature parameter must have a type annotation."), + An_index_signature_parameter_type_must_be_string_or_number: diag(1023, ts.DiagnosticCategory.Error, "An_index_signature_parameter_type_must_be_string_or_number_1023", "An index signature parameter type must be 'string' or 'number'."), + readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature: diag(1024, ts.DiagnosticCategory.Error, "readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024", "'readonly' modifier can only appear on a property declaration or index signature."), + Accessibility_modifier_already_seen: diag(1028, ts.DiagnosticCategory.Error, "Accessibility_modifier_already_seen_1028", "Accessibility modifier already seen."), + _0_modifier_must_precede_1_modifier: diag(1029, ts.DiagnosticCategory.Error, "_0_modifier_must_precede_1_modifier_1029", "'{0}' modifier must precede '{1}' modifier."), + _0_modifier_already_seen: diag(1030, ts.DiagnosticCategory.Error, "_0_modifier_already_seen_1030", "'{0}' modifier already seen."), + _0_modifier_cannot_appear_on_a_class_element: diag(1031, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_a_class_element_1031", "'{0}' modifier cannot appear on a class element."), + super_must_be_followed_by_an_argument_list_or_member_access: diag(1034, ts.DiagnosticCategory.Error, "super_must_be_followed_by_an_argument_list_or_member_access_1034", "'super' must be followed by an argument list or member access."), + Only_ambient_modules_can_use_quoted_names: diag(1035, ts.DiagnosticCategory.Error, "Only_ambient_modules_can_use_quoted_names_1035", "Only ambient modules can use quoted names."), + Statements_are_not_allowed_in_ambient_contexts: diag(1036, ts.DiagnosticCategory.Error, "Statements_are_not_allowed_in_ambient_contexts_1036", "Statements are not allowed in ambient contexts."), + A_declare_modifier_cannot_be_used_in_an_already_ambient_context: diag(1038, ts.DiagnosticCategory.Error, "A_declare_modifier_cannot_be_used_in_an_already_ambient_context_1038", "A 'declare' modifier cannot be used in an already ambient context."), + Initializers_are_not_allowed_in_ambient_contexts: diag(1039, ts.DiagnosticCategory.Error, "Initializers_are_not_allowed_in_ambient_contexts_1039", "Initializers are not allowed in ambient contexts."), + _0_modifier_cannot_be_used_in_an_ambient_context: diag(1040, ts.DiagnosticCategory.Error, "_0_modifier_cannot_be_used_in_an_ambient_context_1040", "'{0}' modifier cannot be used in an ambient context."), + _0_modifier_cannot_be_used_with_a_class_declaration: diag(1041, ts.DiagnosticCategory.Error, "_0_modifier_cannot_be_used_with_a_class_declaration_1041", "'{0}' modifier cannot be used with a class declaration."), + _0_modifier_cannot_be_used_here: diag(1042, ts.DiagnosticCategory.Error, "_0_modifier_cannot_be_used_here_1042", "'{0}' modifier cannot be used here."), + _0_modifier_cannot_appear_on_a_data_property: diag(1043, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_a_data_property_1043", "'{0}' modifier cannot appear on a data property."), + _0_modifier_cannot_appear_on_a_module_or_namespace_element: diag(1044, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_a_module_or_namespace_element_1044", "'{0}' modifier cannot appear on a module or namespace element."), + A_0_modifier_cannot_be_used_with_an_interface_declaration: diag(1045, ts.DiagnosticCategory.Error, "A_0_modifier_cannot_be_used_with_an_interface_declaration_1045", "A '{0}' modifier cannot be used with an interface declaration."), + A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file: diag(1046, ts.DiagnosticCategory.Error, "A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file_1046", "A 'declare' modifier is required for a top level declaration in a .d.ts file."), + A_rest_parameter_cannot_be_optional: diag(1047, ts.DiagnosticCategory.Error, "A_rest_parameter_cannot_be_optional_1047", "A rest parameter cannot be optional."), + A_rest_parameter_cannot_have_an_initializer: diag(1048, ts.DiagnosticCategory.Error, "A_rest_parameter_cannot_have_an_initializer_1048", "A rest parameter cannot have an initializer."), + A_set_accessor_must_have_exactly_one_parameter: diag(1049, ts.DiagnosticCategory.Error, "A_set_accessor_must_have_exactly_one_parameter_1049", "A 'set' accessor must have exactly one parameter."), + A_set_accessor_cannot_have_an_optional_parameter: diag(1051, ts.DiagnosticCategory.Error, "A_set_accessor_cannot_have_an_optional_parameter_1051", "A 'set' accessor cannot have an optional parameter."), + A_set_accessor_parameter_cannot_have_an_initializer: diag(1052, ts.DiagnosticCategory.Error, "A_set_accessor_parameter_cannot_have_an_initializer_1052", "A 'set' accessor parameter cannot have an initializer."), + A_set_accessor_cannot_have_rest_parameter: diag(1053, ts.DiagnosticCategory.Error, "A_set_accessor_cannot_have_rest_parameter_1053", "A 'set' accessor cannot have rest parameter."), + A_get_accessor_cannot_have_parameters: diag(1054, ts.DiagnosticCategory.Error, "A_get_accessor_cannot_have_parameters_1054", "A 'get' accessor cannot have parameters."), + Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value: diag(1055, ts.DiagnosticCategory.Error, "Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Prom_1055", "Type '{0}' is not a valid async function return type in ES5/ES3 because it does not refer to a Promise-compatible constructor value."), + Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher: diag(1056, ts.DiagnosticCategory.Error, "Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher_1056", "Accessors are only available when targeting ECMAScript 5 and higher."), + An_async_function_or_method_must_have_a_valid_awaitable_return_type: diag(1057, ts.DiagnosticCategory.Error, "An_async_function_or_method_must_have_a_valid_awaitable_return_type_1057", "An async function or method must have a valid awaitable return type."), + The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1058, ts.DiagnosticCategory.Error, "The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_t_1058", "The return type of an async function must either be a valid promise or must not contain a callable 'then' member."), + A_promise_must_have_a_then_method: diag(1059, ts.DiagnosticCategory.Error, "A_promise_must_have_a_then_method_1059", "A promise must have a 'then' method."), + The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback: diag(1060, ts.DiagnosticCategory.Error, "The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback_1060", "The first parameter of the 'then' method of a promise must be a callback."), + Enum_member_must_have_initializer: diag(1061, ts.DiagnosticCategory.Error, "Enum_member_must_have_initializer_1061", "Enum member must have initializer."), + Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method: diag(1062, ts.DiagnosticCategory.Error, "Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method_1062", "Type is referenced directly or indirectly in the fulfillment callback of its own 'then' method."), + An_export_assignment_cannot_be_used_in_a_namespace: diag(1063, ts.DiagnosticCategory.Error, "An_export_assignment_cannot_be_used_in_a_namespace_1063", "An export assignment cannot be used in a namespace."), + The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type: diag(1064, ts.DiagnosticCategory.Error, "The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_1064", "The return type of an async function or method must be the global Promise type."), + In_ambient_enum_declarations_member_initializer_must_be_constant_expression: diag(1066, ts.DiagnosticCategory.Error, "In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066", "In ambient enum declarations member initializer must be constant expression."), + Unexpected_token_A_constructor_method_accessor_or_property_was_expected: diag(1068, ts.DiagnosticCategory.Error, "Unexpected_token_A_constructor_method_accessor_or_property_was_expected_1068", "Unexpected token. A constructor, method, accessor, or property was expected."), + Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces: diag(1069, ts.DiagnosticCategory.Error, "Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces_1069", "Unexpected token. A type parameter name was expected without curly braces."), + _0_modifier_cannot_appear_on_a_type_member: diag(1070, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_a_type_member_1070", "'{0}' modifier cannot appear on a type member."), + _0_modifier_cannot_appear_on_an_index_signature: diag(1071, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_an_index_signature_1071", "'{0}' modifier cannot appear on an index signature."), + A_0_modifier_cannot_be_used_with_an_import_declaration: diag(1079, ts.DiagnosticCategory.Error, "A_0_modifier_cannot_be_used_with_an_import_declaration_1079", "A '{0}' modifier cannot be used with an import declaration."), + Invalid_reference_directive_syntax: diag(1084, ts.DiagnosticCategory.Error, "Invalid_reference_directive_syntax_1084", "Invalid 'reference' directive syntax."), + Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0: diag(1085, ts.DiagnosticCategory.Error, "Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0_1085", "Octal literals are not available when targeting ECMAScript 5 and higher. Use the syntax '{0}'."), + An_accessor_cannot_be_declared_in_an_ambient_context: diag(1086, ts.DiagnosticCategory.Error, "An_accessor_cannot_be_declared_in_an_ambient_context_1086", "An accessor cannot be declared in an ambient context."), + _0_modifier_cannot_appear_on_a_constructor_declaration: diag(1089, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_a_constructor_declaration_1089", "'{0}' modifier cannot appear on a constructor declaration."), + _0_modifier_cannot_appear_on_a_parameter: diag(1090, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_a_parameter_1090", "'{0}' modifier cannot appear on a parameter."), + Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement: diag(1091, ts.DiagnosticCategory.Error, "Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement_1091", "Only a single variable declaration is allowed in a 'for...in' statement."), + Type_parameters_cannot_appear_on_a_constructor_declaration: diag(1092, ts.DiagnosticCategory.Error, "Type_parameters_cannot_appear_on_a_constructor_declaration_1092", "Type parameters cannot appear on a constructor declaration."), + Type_annotation_cannot_appear_on_a_constructor_declaration: diag(1093, ts.DiagnosticCategory.Error, "Type_annotation_cannot_appear_on_a_constructor_declaration_1093", "Type annotation cannot appear on a constructor declaration."), + An_accessor_cannot_have_type_parameters: diag(1094, ts.DiagnosticCategory.Error, "An_accessor_cannot_have_type_parameters_1094", "An accessor cannot have type parameters."), + A_set_accessor_cannot_have_a_return_type_annotation: diag(1095, ts.DiagnosticCategory.Error, "A_set_accessor_cannot_have_a_return_type_annotation_1095", "A 'set' accessor cannot have a return type annotation."), + An_index_signature_must_have_exactly_one_parameter: diag(1096, ts.DiagnosticCategory.Error, "An_index_signature_must_have_exactly_one_parameter_1096", "An index signature must have exactly one parameter."), + _0_list_cannot_be_empty: diag(1097, ts.DiagnosticCategory.Error, "_0_list_cannot_be_empty_1097", "'{0}' list cannot be empty."), + Type_parameter_list_cannot_be_empty: diag(1098, ts.DiagnosticCategory.Error, "Type_parameter_list_cannot_be_empty_1098", "Type parameter list cannot be empty."), + Type_argument_list_cannot_be_empty: diag(1099, ts.DiagnosticCategory.Error, "Type_argument_list_cannot_be_empty_1099", "Type argument list cannot be empty."), + Invalid_use_of_0_in_strict_mode: diag(1100, ts.DiagnosticCategory.Error, "Invalid_use_of_0_in_strict_mode_1100", "Invalid use of '{0}' in strict mode."), + with_statements_are_not_allowed_in_strict_mode: diag(1101, ts.DiagnosticCategory.Error, "with_statements_are_not_allowed_in_strict_mode_1101", "'with' statements are not allowed in strict mode."), + delete_cannot_be_called_on_an_identifier_in_strict_mode: diag(1102, ts.DiagnosticCategory.Error, "delete_cannot_be_called_on_an_identifier_in_strict_mode_1102", "'delete' cannot be called on an identifier in strict mode."), + A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator: diag(1103, ts.DiagnosticCategory.Error, "A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator_1103", "A 'for-await-of' statement is only allowed within an async function or async generator."), + A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement: diag(1104, ts.DiagnosticCategory.Error, "A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement_1104", "A 'continue' statement can only be used within an enclosing iteration statement."), + A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement: diag(1105, ts.DiagnosticCategory.Error, "A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement_1105", "A 'break' statement can only be used within an enclosing iteration or switch statement."), + Jump_target_cannot_cross_function_boundary: diag(1107, ts.DiagnosticCategory.Error, "Jump_target_cannot_cross_function_boundary_1107", "Jump target cannot cross function boundary."), + A_return_statement_can_only_be_used_within_a_function_body: diag(1108, ts.DiagnosticCategory.Error, "A_return_statement_can_only_be_used_within_a_function_body_1108", "A 'return' statement can only be used within a function body."), + Expression_expected: diag(1109, ts.DiagnosticCategory.Error, "Expression_expected_1109", "Expression expected."), + Type_expected: diag(1110, ts.DiagnosticCategory.Error, "Type_expected_1110", "Type expected."), + A_default_clause_cannot_appear_more_than_once_in_a_switch_statement: diag(1113, ts.DiagnosticCategory.Error, "A_default_clause_cannot_appear_more_than_once_in_a_switch_statement_1113", "A 'default' clause cannot appear more than once in a 'switch' statement."), + Duplicate_label_0: diag(1114, ts.DiagnosticCategory.Error, "Duplicate_label_0_1114", "Duplicate label '{0}'."), + A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement: diag(1115, ts.DiagnosticCategory.Error, "A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement_1115", "A 'continue' statement can only jump to a label of an enclosing iteration statement."), + A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement: diag(1116, ts.DiagnosticCategory.Error, "A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement_1116", "A 'break' statement can only jump to a label of an enclosing statement."), + An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode: diag(1117, ts.DiagnosticCategory.Error, "An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode_1117", "An object literal cannot have multiple properties with the same name in strict mode."), + An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name: diag(1118, ts.DiagnosticCategory.Error, "An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name_1118", "An object literal cannot have multiple get/set accessors with the same name."), + An_object_literal_cannot_have_property_and_accessor_with_the_same_name: diag(1119, ts.DiagnosticCategory.Error, "An_object_literal_cannot_have_property_and_accessor_with_the_same_name_1119", "An object literal cannot have property and accessor with the same name."), + An_export_assignment_cannot_have_modifiers: diag(1120, ts.DiagnosticCategory.Error, "An_export_assignment_cannot_have_modifiers_1120", "An export assignment cannot have modifiers."), + Octal_literals_are_not_allowed_in_strict_mode: diag(1121, ts.DiagnosticCategory.Error, "Octal_literals_are_not_allowed_in_strict_mode_1121", "Octal literals are not allowed in strict mode."), + Variable_declaration_list_cannot_be_empty: diag(1123, ts.DiagnosticCategory.Error, "Variable_declaration_list_cannot_be_empty_1123", "Variable declaration list cannot be empty."), + Digit_expected: diag(1124, ts.DiagnosticCategory.Error, "Digit_expected_1124", "Digit expected."), + Hexadecimal_digit_expected: diag(1125, ts.DiagnosticCategory.Error, "Hexadecimal_digit_expected_1125", "Hexadecimal digit expected."), + Unexpected_end_of_text: diag(1126, ts.DiagnosticCategory.Error, "Unexpected_end_of_text_1126", "Unexpected end of text."), + Invalid_character: diag(1127, ts.DiagnosticCategory.Error, "Invalid_character_1127", "Invalid character."), + Declaration_or_statement_expected: diag(1128, ts.DiagnosticCategory.Error, "Declaration_or_statement_expected_1128", "Declaration or statement expected."), + Statement_expected: diag(1129, ts.DiagnosticCategory.Error, "Statement_expected_1129", "Statement expected."), + case_or_default_expected: diag(1130, ts.DiagnosticCategory.Error, "case_or_default_expected_1130", "'case' or 'default' expected."), + Property_or_signature_expected: diag(1131, ts.DiagnosticCategory.Error, "Property_or_signature_expected_1131", "Property or signature expected."), + Enum_member_expected: diag(1132, ts.DiagnosticCategory.Error, "Enum_member_expected_1132", "Enum member expected."), + Variable_declaration_expected: diag(1134, ts.DiagnosticCategory.Error, "Variable_declaration_expected_1134", "Variable declaration expected."), + Argument_expression_expected: diag(1135, ts.DiagnosticCategory.Error, "Argument_expression_expected_1135", "Argument expression expected."), + Property_assignment_expected: diag(1136, ts.DiagnosticCategory.Error, "Property_assignment_expected_1136", "Property assignment expected."), + Expression_or_comma_expected: diag(1137, ts.DiagnosticCategory.Error, "Expression_or_comma_expected_1137", "Expression or comma expected."), + Parameter_declaration_expected: diag(1138, ts.DiagnosticCategory.Error, "Parameter_declaration_expected_1138", "Parameter declaration expected."), + Type_parameter_declaration_expected: diag(1139, ts.DiagnosticCategory.Error, "Type_parameter_declaration_expected_1139", "Type parameter declaration expected."), + Type_argument_expected: diag(1140, ts.DiagnosticCategory.Error, "Type_argument_expected_1140", "Type argument expected."), + String_literal_expected: diag(1141, ts.DiagnosticCategory.Error, "String_literal_expected_1141", "String literal expected."), + Line_break_not_permitted_here: diag(1142, ts.DiagnosticCategory.Error, "Line_break_not_permitted_here_1142", "Line break not permitted here."), + or_expected: diag(1144, ts.DiagnosticCategory.Error, "or_expected_1144", "'{' or ';' expected."), + Declaration_expected: diag(1146, ts.DiagnosticCategory.Error, "Declaration_expected_1146", "Declaration expected."), + Import_declarations_in_a_namespace_cannot_reference_a_module: diag(1147, ts.DiagnosticCategory.Error, "Import_declarations_in_a_namespace_cannot_reference_a_module_1147", "Import declarations in a namespace cannot reference a module."), + Cannot_use_imports_exports_or_module_augmentations_when_module_is_none: diag(1148, ts.DiagnosticCategory.Error, "Cannot_use_imports_exports_or_module_augmentations_when_module_is_none_1148", "Cannot use imports, exports, or module augmentations when '--module' is 'none'."), + File_name_0_differs_from_already_included_file_name_1_only_in_casing: diag(1149, ts.DiagnosticCategory.Error, "File_name_0_differs_from_already_included_file_name_1_only_in_casing_1149", "File name '{0}' differs from already included file name '{1}' only in casing."), + new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead: diag(1150, ts.DiagnosticCategory.Error, "new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead_1150", "'new T[]' cannot be used to create an array. Use 'new Array()' instead."), + const_declarations_must_be_initialized: diag(1155, ts.DiagnosticCategory.Error, "const_declarations_must_be_initialized_1155", "'const' declarations must be initialized."), + const_declarations_can_only_be_declared_inside_a_block: diag(1156, ts.DiagnosticCategory.Error, "const_declarations_can_only_be_declared_inside_a_block_1156", "'const' declarations can only be declared inside a block."), + let_declarations_can_only_be_declared_inside_a_block: diag(1157, ts.DiagnosticCategory.Error, "let_declarations_can_only_be_declared_inside_a_block_1157", "'let' declarations can only be declared inside a block."), + Unterminated_template_literal: diag(1160, ts.DiagnosticCategory.Error, "Unterminated_template_literal_1160", "Unterminated template literal."), + Unterminated_regular_expression_literal: diag(1161, ts.DiagnosticCategory.Error, "Unterminated_regular_expression_literal_1161", "Unterminated regular expression literal."), + An_object_member_cannot_be_declared_optional: diag(1162, ts.DiagnosticCategory.Error, "An_object_member_cannot_be_declared_optional_1162", "An object member cannot be declared optional."), + A_yield_expression_is_only_allowed_in_a_generator_body: diag(1163, ts.DiagnosticCategory.Error, "A_yield_expression_is_only_allowed_in_a_generator_body_1163", "A 'yield' expression is only allowed in a generator body."), + Computed_property_names_are_not_allowed_in_enums: diag(1164, ts.DiagnosticCategory.Error, "Computed_property_names_are_not_allowed_in_enums_1164", "Computed property names are not allowed in enums."), + A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: diag(1165, ts.DiagnosticCategory.Error, "A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_t_1165", "A computed property name in an ambient context must refer to an expression whose type is a literal type or a 'unique symbol' type."), + A_computed_property_name_in_a_class_property_declaration_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: diag(1166, ts.DiagnosticCategory.Error, "A_computed_property_name_in_a_class_property_declaration_must_refer_to_an_expression_whose_type_is_a_1166", "A computed property name in a class property declaration must refer to an expression whose type is a literal type or a 'unique symbol' type."), + A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: diag(1168, ts.DiagnosticCategory.Error, "A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_ty_1168", "A computed property name in a method overload must refer to an expression whose type is a literal type or a 'unique symbol' type."), + A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: diag(1169, ts.DiagnosticCategory.Error, "A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_1169", "A computed property name in an interface must refer to an expression whose type is a literal type or a 'unique symbol' type."), + A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: diag(1170, ts.DiagnosticCategory.Error, "A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type__1170", "A computed property name in a type literal must refer to an expression whose type is a literal type or a 'unique symbol' type."), + A_comma_expression_is_not_allowed_in_a_computed_property_name: diag(1171, ts.DiagnosticCategory.Error, "A_comma_expression_is_not_allowed_in_a_computed_property_name_1171", "A comma expression is not allowed in a computed property name."), + extends_clause_already_seen: diag(1172, ts.DiagnosticCategory.Error, "extends_clause_already_seen_1172", "'extends' clause already seen."), + extends_clause_must_precede_implements_clause: diag(1173, ts.DiagnosticCategory.Error, "extends_clause_must_precede_implements_clause_1173", "'extends' clause must precede 'implements' clause."), + Classes_can_only_extend_a_single_class: diag(1174, ts.DiagnosticCategory.Error, "Classes_can_only_extend_a_single_class_1174", "Classes can only extend a single class."), + implements_clause_already_seen: diag(1175, ts.DiagnosticCategory.Error, "implements_clause_already_seen_1175", "'implements' clause already seen."), + Interface_declaration_cannot_have_implements_clause: diag(1176, ts.DiagnosticCategory.Error, "Interface_declaration_cannot_have_implements_clause_1176", "Interface declaration cannot have 'implements' clause."), + Binary_digit_expected: diag(1177, ts.DiagnosticCategory.Error, "Binary_digit_expected_1177", "Binary digit expected."), + Octal_digit_expected: diag(1178, ts.DiagnosticCategory.Error, "Octal_digit_expected_1178", "Octal digit expected."), + Unexpected_token_expected: diag(1179, ts.DiagnosticCategory.Error, "Unexpected_token_expected_1179", "Unexpected token. '{' expected."), + Property_destructuring_pattern_expected: diag(1180, ts.DiagnosticCategory.Error, "Property_destructuring_pattern_expected_1180", "Property destructuring pattern expected."), + Array_element_destructuring_pattern_expected: diag(1181, ts.DiagnosticCategory.Error, "Array_element_destructuring_pattern_expected_1181", "Array element destructuring pattern expected."), + A_destructuring_declaration_must_have_an_initializer: diag(1182, ts.DiagnosticCategory.Error, "A_destructuring_declaration_must_have_an_initializer_1182", "A destructuring declaration must have an initializer."), + An_implementation_cannot_be_declared_in_ambient_contexts: diag(1183, ts.DiagnosticCategory.Error, "An_implementation_cannot_be_declared_in_ambient_contexts_1183", "An implementation cannot be declared in ambient contexts."), + Modifiers_cannot_appear_here: diag(1184, ts.DiagnosticCategory.Error, "Modifiers_cannot_appear_here_1184", "Modifiers cannot appear here."), + Merge_conflict_marker_encountered: diag(1185, ts.DiagnosticCategory.Error, "Merge_conflict_marker_encountered_1185", "Merge conflict marker encountered."), + A_rest_element_cannot_have_an_initializer: diag(1186, ts.DiagnosticCategory.Error, "A_rest_element_cannot_have_an_initializer_1186", "A rest element cannot have an initializer."), + A_parameter_property_may_not_be_declared_using_a_binding_pattern: diag(1187, ts.DiagnosticCategory.Error, "A_parameter_property_may_not_be_declared_using_a_binding_pattern_1187", "A parameter property may not be declared using a binding pattern."), + Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement: diag(1188, ts.DiagnosticCategory.Error, "Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement_1188", "Only a single variable declaration is allowed in a 'for...of' statement."), + The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer: diag(1189, ts.DiagnosticCategory.Error, "The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer_1189", "The variable declaration of a 'for...in' statement cannot have an initializer."), + The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer: diag(1190, ts.DiagnosticCategory.Error, "The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer_1190", "The variable declaration of a 'for...of' statement cannot have an initializer."), + An_import_declaration_cannot_have_modifiers: diag(1191, ts.DiagnosticCategory.Error, "An_import_declaration_cannot_have_modifiers_1191", "An import declaration cannot have modifiers."), + Module_0_has_no_default_export: diag(1192, ts.DiagnosticCategory.Error, "Module_0_has_no_default_export_1192", "Module '{0}' has no default export."), + An_export_declaration_cannot_have_modifiers: diag(1193, ts.DiagnosticCategory.Error, "An_export_declaration_cannot_have_modifiers_1193", "An export declaration cannot have modifiers."), + Export_declarations_are_not_permitted_in_a_namespace: diag(1194, ts.DiagnosticCategory.Error, "Export_declarations_are_not_permitted_in_a_namespace_1194", "Export declarations are not permitted in a namespace."), + Catch_clause_variable_cannot_have_a_type_annotation: diag(1196, ts.DiagnosticCategory.Error, "Catch_clause_variable_cannot_have_a_type_annotation_1196", "Catch clause variable cannot have a type annotation."), + Catch_clause_variable_cannot_have_an_initializer: diag(1197, ts.DiagnosticCategory.Error, "Catch_clause_variable_cannot_have_an_initializer_1197", "Catch clause variable cannot have an initializer."), + An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive: diag(1198, ts.DiagnosticCategory.Error, "An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive_1198", "An extended Unicode escape value must be between 0x0 and 0x10FFFF inclusive."), + Unterminated_Unicode_escape_sequence: diag(1199, ts.DiagnosticCategory.Error, "Unterminated_Unicode_escape_sequence_1199", "Unterminated Unicode escape sequence."), + Line_terminator_not_permitted_before_arrow: diag(1200, ts.DiagnosticCategory.Error, "Line_terminator_not_permitted_before_arrow_1200", "Line terminator not permitted before arrow."), + Import_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_import_Asterisk_as_ns_from_mod_import_a_from_mod_import_d_from_mod_or_another_module_format_instead: diag(1202, ts.DiagnosticCategory.Error, "Import_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_import_Asterisk_as_1202", "Import assignment cannot be used when targeting ECMAScript modules. Consider using 'import * as ns from \"mod\"', 'import {a} from \"mod\"', 'import d from \"mod\"', or another module format instead."), + Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or_another_module_format_instead: diag(1203, ts.DiagnosticCategory.Error, "Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or__1203", "Export assignment cannot be used when targeting ECMAScript modules. Consider using 'export default' or another module format instead."), + Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided: diag(1205, ts.DiagnosticCategory.Error, "Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205", "Cannot re-export a type when the '--isolatedModules' flag is provided."), + Decorators_are_not_valid_here: diag(1206, ts.DiagnosticCategory.Error, "Decorators_are_not_valid_here_1206", "Decorators are not valid here."), + Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name: diag(1207, ts.DiagnosticCategory.Error, "Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name_1207", "Decorators cannot be applied to multiple get/set accessors of the same name."), + Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided: diag(1208, ts.DiagnosticCategory.Error, "Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided_1208", "Cannot compile namespaces when the '--isolatedModules' flag is provided."), + Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided: diag(1209, ts.DiagnosticCategory.Error, "Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided_1209", "Ambient const enums are not allowed when the '--isolatedModules' flag is provided."), + Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode: diag(1210, ts.DiagnosticCategory.Error, "Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode_1210", "Invalid use of '{0}'. Class definitions are automatically in strict mode."), + A_class_declaration_without_the_default_modifier_must_have_a_name: diag(1211, ts.DiagnosticCategory.Error, "A_class_declaration_without_the_default_modifier_must_have_a_name_1211", "A class declaration without the 'default' modifier must have a name."), + Identifier_expected_0_is_a_reserved_word_in_strict_mode: diag(1212, ts.DiagnosticCategory.Error, "Identifier_expected_0_is_a_reserved_word_in_strict_mode_1212", "Identifier expected. '{0}' is a reserved word in strict mode."), + Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode: diag(1213, ts.DiagnosticCategory.Error, "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_stric_1213", "Identifier expected. '{0}' is a reserved word in strict mode. Class definitions are automatically in strict mode."), + Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode: diag(1214, ts.DiagnosticCategory.Error, "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode_1214", "Identifier expected. '{0}' is a reserved word in strict mode. Modules are automatically in strict mode."), + Invalid_use_of_0_Modules_are_automatically_in_strict_mode: diag(1215, ts.DiagnosticCategory.Error, "Invalid_use_of_0_Modules_are_automatically_in_strict_mode_1215", "Invalid use of '{0}'. Modules are automatically in strict mode."), + Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules: diag(1216, ts.DiagnosticCategory.Error, "Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules_1216", "Identifier expected. '__esModule' is reserved as an exported marker when transforming ECMAScript modules."), + Export_assignment_is_not_supported_when_module_flag_is_system: diag(1218, ts.DiagnosticCategory.Error, "Export_assignment_is_not_supported_when_module_flag_is_system_1218", "Export assignment is not supported when '--module' flag is 'system'."), + Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_to_remove_this_warning: diag(1219, ts.DiagnosticCategory.Error, "Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_t_1219", "Experimental support for decorators is a feature that is subject to change in a future release. Set the 'experimentalDecorators' option to remove this warning."), + Generators_are_only_available_when_targeting_ECMAScript_2015_or_higher: diag(1220, ts.DiagnosticCategory.Error, "Generators_are_only_available_when_targeting_ECMAScript_2015_or_higher_1220", "Generators are only available when targeting ECMAScript 2015 or higher."), + Generators_are_not_allowed_in_an_ambient_context: diag(1221, ts.DiagnosticCategory.Error, "Generators_are_not_allowed_in_an_ambient_context_1221", "Generators are not allowed in an ambient context."), + An_overload_signature_cannot_be_declared_as_a_generator: diag(1222, ts.DiagnosticCategory.Error, "An_overload_signature_cannot_be_declared_as_a_generator_1222", "An overload signature cannot be declared as a generator."), + _0_tag_already_specified: diag(1223, ts.DiagnosticCategory.Error, "_0_tag_already_specified_1223", "'{0}' tag already specified."), + Signature_0_must_be_a_type_predicate: diag(1224, ts.DiagnosticCategory.Error, "Signature_0_must_be_a_type_predicate_1224", "Signature '{0}' must be a type predicate."), + Cannot_find_parameter_0: diag(1225, ts.DiagnosticCategory.Error, "Cannot_find_parameter_0_1225", "Cannot find parameter '{0}'."), + Type_predicate_0_is_not_assignable_to_1: diag(1226, ts.DiagnosticCategory.Error, "Type_predicate_0_is_not_assignable_to_1_1226", "Type predicate '{0}' is not assignable to '{1}'."), + Parameter_0_is_not_in_the_same_position_as_parameter_1: diag(1227, ts.DiagnosticCategory.Error, "Parameter_0_is_not_in_the_same_position_as_parameter_1_1227", "Parameter '{0}' is not in the same position as parameter '{1}'."), + A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods: diag(1228, ts.DiagnosticCategory.Error, "A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods_1228", "A type predicate is only allowed in return type position for functions and methods."), + A_type_predicate_cannot_reference_a_rest_parameter: diag(1229, ts.DiagnosticCategory.Error, "A_type_predicate_cannot_reference_a_rest_parameter_1229", "A type predicate cannot reference a rest parameter."), + A_type_predicate_cannot_reference_element_0_in_a_binding_pattern: diag(1230, ts.DiagnosticCategory.Error, "A_type_predicate_cannot_reference_element_0_in_a_binding_pattern_1230", "A type predicate cannot reference element '{0}' in a binding pattern."), + An_export_assignment_can_only_be_used_in_a_module: diag(1231, ts.DiagnosticCategory.Error, "An_export_assignment_can_only_be_used_in_a_module_1231", "An export assignment can only be used in a module."), + An_import_declaration_can_only_be_used_in_a_namespace_or_module: diag(1232, ts.DiagnosticCategory.Error, "An_import_declaration_can_only_be_used_in_a_namespace_or_module_1232", "An import declaration can only be used in a namespace or module."), + An_export_declaration_can_only_be_used_in_a_module: diag(1233, ts.DiagnosticCategory.Error, "An_export_declaration_can_only_be_used_in_a_module_1233", "An export declaration can only be used in a module."), + An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file: diag(1234, ts.DiagnosticCategory.Error, "An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file_1234", "An ambient module declaration is only allowed at the top level in a file."), + A_namespace_declaration_is_only_allowed_in_a_namespace_or_module: diag(1235, ts.DiagnosticCategory.Error, "A_namespace_declaration_is_only_allowed_in_a_namespace_or_module_1235", "A namespace declaration is only allowed in a namespace or module."), + The_return_type_of_a_property_decorator_function_must_be_either_void_or_any: diag(1236, ts.DiagnosticCategory.Error, "The_return_type_of_a_property_decorator_function_must_be_either_void_or_any_1236", "The return type of a property decorator function must be either 'void' or 'any'."), + The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any: diag(1237, ts.DiagnosticCategory.Error, "The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any_1237", "The return type of a parameter decorator function must be either 'void' or 'any'."), + Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression: diag(1238, ts.DiagnosticCategory.Error, "Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression_1238", "Unable to resolve signature of class decorator when called as an expression."), + Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression: diag(1239, ts.DiagnosticCategory.Error, "Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression_1239", "Unable to resolve signature of parameter decorator when called as an expression."), + Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression: diag(1240, ts.DiagnosticCategory.Error, "Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression_1240", "Unable to resolve signature of property decorator when called as an expression."), + Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression: diag(1241, ts.DiagnosticCategory.Error, "Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression_1241", "Unable to resolve signature of method decorator when called as an expression."), + abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration: diag(1242, ts.DiagnosticCategory.Error, "abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration_1242", "'abstract' modifier can only appear on a class, method, or property declaration."), + _0_modifier_cannot_be_used_with_1_modifier: diag(1243, ts.DiagnosticCategory.Error, "_0_modifier_cannot_be_used_with_1_modifier_1243", "'{0}' modifier cannot be used with '{1}' modifier."), + Abstract_methods_can_only_appear_within_an_abstract_class: diag(1244, ts.DiagnosticCategory.Error, "Abstract_methods_can_only_appear_within_an_abstract_class_1244", "Abstract methods can only appear within an abstract class."), + Method_0_cannot_have_an_implementation_because_it_is_marked_abstract: diag(1245, ts.DiagnosticCategory.Error, "Method_0_cannot_have_an_implementation_because_it_is_marked_abstract_1245", "Method '{0}' cannot have an implementation because it is marked abstract."), + An_interface_property_cannot_have_an_initializer: diag(1246, ts.DiagnosticCategory.Error, "An_interface_property_cannot_have_an_initializer_1246", "An interface property cannot have an initializer."), + A_type_literal_property_cannot_have_an_initializer: diag(1247, ts.DiagnosticCategory.Error, "A_type_literal_property_cannot_have_an_initializer_1247", "A type literal property cannot have an initializer."), + A_class_member_cannot_have_the_0_keyword: diag(1248, ts.DiagnosticCategory.Error, "A_class_member_cannot_have_the_0_keyword_1248", "A class member cannot have the '{0}' keyword."), + A_decorator_can_only_decorate_a_method_implementation_not_an_overload: diag(1249, ts.DiagnosticCategory.Error, "A_decorator_can_only_decorate_a_method_implementation_not_an_overload_1249", "A decorator can only decorate a method implementation, not an overload."), + Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5: diag(1250, ts.DiagnosticCategory.Error, "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_1250", "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'."), + Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_definitions_are_automatically_in_strict_mode: diag(1251, ts.DiagnosticCategory.Error, "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_d_1251", "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Class definitions are automatically in strict mode."), + Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_are_automatically_in_strict_mode: diag(1252, ts.DiagnosticCategory.Error, "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_1252", "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Modules are automatically in strict mode."), + _0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag: diag(1253, ts.DiagnosticCategory.Error, "_0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag_1253", "'{0}' tag cannot be used independently as a top level JSDoc tag."), + A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_reference: diag(1254, ts.DiagnosticCategory.Error, "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_refere_1254", "A 'const' initializer in an ambient context must be a string or numeric literal or literal enum reference."), + A_definite_assignment_assertion_is_not_permitted_in_this_context: diag(1255, ts.DiagnosticCategory.Error, "A_definite_assignment_assertion_is_not_permitted_in_this_context_1255", "A definite assignment assertion '!' is not permitted in this context."), + A_rest_element_must_be_last_in_a_tuple_type: diag(1256, ts.DiagnosticCategory.Error, "A_rest_element_must_be_last_in_a_tuple_type_1256", "A rest element must be last in a tuple type."), + A_required_element_cannot_follow_an_optional_element: diag(1257, ts.DiagnosticCategory.Error, "A_required_element_cannot_follow_an_optional_element_1257", "A required element cannot follow an optional element."), + with_statements_are_not_allowed_in_an_async_function_block: diag(1300, ts.DiagnosticCategory.Error, "with_statements_are_not_allowed_in_an_async_function_block_1300", "'with' statements are not allowed in an async function block."), + await_expression_is_only_allowed_within_an_async_function: diag(1308, ts.DiagnosticCategory.Error, "await_expression_is_only_allowed_within_an_async_function_1308", "'await' expression is only allowed within an async function."), + can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment: diag(1312, ts.DiagnosticCategory.Error, "can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment_1312", "'=' can only be used in an object literal property inside a destructuring assignment."), + The_body_of_an_if_statement_cannot_be_the_empty_statement: diag(1313, ts.DiagnosticCategory.Error, "The_body_of_an_if_statement_cannot_be_the_empty_statement_1313", "The body of an 'if' statement cannot be the empty statement."), + Global_module_exports_may_only_appear_in_module_files: diag(1314, ts.DiagnosticCategory.Error, "Global_module_exports_may_only_appear_in_module_files_1314", "Global module exports may only appear in module files."), + Global_module_exports_may_only_appear_in_declaration_files: diag(1315, ts.DiagnosticCategory.Error, "Global_module_exports_may_only_appear_in_declaration_files_1315", "Global module exports may only appear in declaration files."), + Global_module_exports_may_only_appear_at_top_level: diag(1316, ts.DiagnosticCategory.Error, "Global_module_exports_may_only_appear_at_top_level_1316", "Global module exports may only appear at top level."), + A_parameter_property_cannot_be_declared_using_a_rest_parameter: diag(1317, ts.DiagnosticCategory.Error, "A_parameter_property_cannot_be_declared_using_a_rest_parameter_1317", "A parameter property cannot be declared using a rest parameter."), + An_abstract_accessor_cannot_have_an_implementation: diag(1318, ts.DiagnosticCategory.Error, "An_abstract_accessor_cannot_have_an_implementation_1318", "An abstract accessor cannot have an implementation."), + A_default_export_can_only_be_used_in_an_ECMAScript_style_module: diag(1319, ts.DiagnosticCategory.Error, "A_default_export_can_only_be_used_in_an_ECMAScript_style_module_1319", "A default export can only be used in an ECMAScript-style module."), + Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1320, ts.DiagnosticCategory.Error, "Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member_1320", "Type of 'await' operand must either be a valid promise or must not contain a callable 'then' member."), + Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1321, ts.DiagnosticCategory.Error, "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321", "Type of 'yield' operand in an async generator must either be a valid promise or must not contain a callable 'then' member."), + Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1322, ts.DiagnosticCategory.Error, "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322", "Type of iterated elements of a 'yield*' operand must either be a valid promise or must not contain a callable 'then' member."), + Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext: diag(1323, ts.DiagnosticCategory.Error, "Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext_1323", "Dynamic import is only supported when '--module' flag is 'commonjs' or 'esNext'."), + Dynamic_import_must_have_one_specifier_as_an_argument: diag(1324, ts.DiagnosticCategory.Error, "Dynamic_import_must_have_one_specifier_as_an_argument_1324", "Dynamic import must have one specifier as an argument."), + Specifier_of_dynamic_import_cannot_be_spread_element: diag(1325, ts.DiagnosticCategory.Error, "Specifier_of_dynamic_import_cannot_be_spread_element_1325", "Specifier of dynamic import cannot be spread element."), + Dynamic_import_cannot_have_type_arguments: diag(1326, ts.DiagnosticCategory.Error, "Dynamic_import_cannot_have_type_arguments_1326", "Dynamic import cannot have type arguments"), + String_literal_with_double_quotes_expected: diag(1327, ts.DiagnosticCategory.Error, "String_literal_with_double_quotes_expected_1327", "String literal with double quotes expected."), + Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_literal: diag(1328, ts.DiagnosticCategory.Error, "Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_li_1328", "Property value can only be string literal, numeric literal, 'true', 'false', 'null', object literal or array literal."), + _0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write_0: diag(1329, ts.DiagnosticCategory.Error, "_0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write__1329", "'{0}' accepts too few arguments to be used as a decorator here. Did you mean to call it first and write '@{0}()'?"), + A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly: diag(1330, ts.DiagnosticCategory.Error, "A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly_1330", "A property of an interface or type literal whose type is a 'unique symbol' type must be 'readonly'."), + A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly: diag(1331, ts.DiagnosticCategory.Error, "A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly_1331", "A property of a class whose type is a 'unique symbol' type must be both 'static' and 'readonly'."), + A_variable_whose_type_is_a_unique_symbol_type_must_be_const: diag(1332, ts.DiagnosticCategory.Error, "A_variable_whose_type_is_a_unique_symbol_type_must_be_const_1332", "A variable whose type is a 'unique symbol' type must be 'const'."), + unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name: diag(1333, ts.DiagnosticCategory.Error, "unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name_1333", "'unique symbol' types may not be used on a variable declaration with a binding name."), + unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement: diag(1334, ts.DiagnosticCategory.Error, "unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement_1334", "'unique symbol' types are only allowed on variables in a variable statement."), + unique_symbol_types_are_not_allowed_here: diag(1335, ts.DiagnosticCategory.Error, "unique_symbol_types_are_not_allowed_here_1335", "'unique symbol' types are not allowed here."), + An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead: diag(1336, ts.DiagnosticCategory.Error, "An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead_1336", "An index signature parameter type cannot be a type alias. Consider writing '[{0}: {1}]: {2}' instead."), + An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead: diag(1337, ts.DiagnosticCategory.Error, "An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead_1337", "An index signature parameter type cannot be a union type. Consider using a mapped object type instead."), + infer_declarations_are_only_permitted_in_the_extends_clause_of_a_conditional_type: diag(1338, ts.DiagnosticCategory.Error, "infer_declarations_are_only_permitted_in_the_extends_clause_of_a_conditional_type_1338", "'infer' declarations are only permitted in the 'extends' clause of a conditional type."), + Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here: diag(1339, ts.DiagnosticCategory.Error, "Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here_1339", "Module '{0}' does not refer to a value, but is used as a value here."), + Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0: diag(1340, ts.DiagnosticCategory.Error, "Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0_1340", "Module '{0}' does not refer to a type, but is used as a type here. Did you mean 'typeof import('{0}')'?"), + Type_arguments_cannot_be_used_here: diag(1342, ts.DiagnosticCategory.Error, "Type_arguments_cannot_be_used_here_1342", "Type arguments cannot be used here."), + The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_options: diag(1343, ts.DiagnosticCategory.Error, "The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_option_1343", "The 'import.meta' meta-property is only allowed using 'ESNext' for the 'target' and 'module' compiler options."), + A_label_is_not_allowed_here: diag(1344, ts.DiagnosticCategory.Error, "A_label_is_not_allowed_here_1344", "'A label is not allowed here."), + An_expression_of_type_void_cannot_be_tested_for_truthiness: diag(1345, ts.DiagnosticCategory.Error, "An_expression_of_type_void_cannot_be_tested_for_truthiness_1345", "An expression of type 'void' cannot be tested for truthiness"), + This_parameter_is_not_allowed_with_use_strict_directive: diag(1346, ts.DiagnosticCategory.Error, "This_parameter_is_not_allowed_with_use_strict_directive_1346", "This parameter is not allowed with 'use strict' directive."), + use_strict_directive_cannot_be_used_with_non_simple_parameter_list: diag(1347, ts.DiagnosticCategory.Error, "use_strict_directive_cannot_be_used_with_non_simple_parameter_list_1347", "'use strict' directive cannot be used with non-simple parameter list."), + Non_simple_parameter_declared_here: diag(1348, ts.DiagnosticCategory.Error, "Non_simple_parameter_declared_here_1348", "Non-simple parameter declared here."), + use_strict_directive_used_here: diag(1349, ts.DiagnosticCategory.Error, "use_strict_directive_used_here_1349", "'use strict' directive used here."), + Print_the_final_configuration_instead_of_building: diag(1350, ts.DiagnosticCategory.Message, "Print_the_final_configuration_instead_of_building_1350", "Print the final configuration instead of building."), + Duplicate_identifier_0: diag(2300, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_2300", "Duplicate identifier '{0}'."), + Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: diag(2301, ts.DiagnosticCategory.Error, "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301", "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor."), + Static_members_cannot_reference_class_type_parameters: diag(2302, ts.DiagnosticCategory.Error, "Static_members_cannot_reference_class_type_parameters_2302", "Static members cannot reference class type parameters."), + Circular_definition_of_import_alias_0: diag(2303, ts.DiagnosticCategory.Error, "Circular_definition_of_import_alias_0_2303", "Circular definition of import alias '{0}'."), + Cannot_find_name_0: diag(2304, ts.DiagnosticCategory.Error, "Cannot_find_name_0_2304", "Cannot find name '{0}'."), + Module_0_has_no_exported_member_1: diag(2305, ts.DiagnosticCategory.Error, "Module_0_has_no_exported_member_1_2305", "Module '{0}' has no exported member '{1}'."), + File_0_is_not_a_module: diag(2306, ts.DiagnosticCategory.Error, "File_0_is_not_a_module_2306", "File '{0}' is not a module."), + Cannot_find_module_0: diag(2307, ts.DiagnosticCategory.Error, "Cannot_find_module_0_2307", "Cannot find module '{0}'."), + Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambiguity: diag(2308, ts.DiagnosticCategory.Error, "Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambig_2308", "Module {0} has already exported a member named '{1}'. Consider explicitly re-exporting to resolve the ambiguity."), + An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements: diag(2309, ts.DiagnosticCategory.Error, "An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements_2309", "An export assignment cannot be used in a module with other exported elements."), + Type_0_recursively_references_itself_as_a_base_type: diag(2310, ts.DiagnosticCategory.Error, "Type_0_recursively_references_itself_as_a_base_type_2310", "Type '{0}' recursively references itself as a base type."), + A_class_may_only_extend_another_class: diag(2311, ts.DiagnosticCategory.Error, "A_class_may_only_extend_another_class_2311", "A class may only extend another class."), + An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_members: diag(2312, ts.DiagnosticCategory.Error, "An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_me_2312", "An interface can only extend an object type or intersection of object types with statically known members."), + Type_parameter_0_has_a_circular_constraint: diag(2313, ts.DiagnosticCategory.Error, "Type_parameter_0_has_a_circular_constraint_2313", "Type parameter '{0}' has a circular constraint."), + Generic_type_0_requires_1_type_argument_s: diag(2314, ts.DiagnosticCategory.Error, "Generic_type_0_requires_1_type_argument_s_2314", "Generic type '{0}' requires {1} type argument(s)."), + Type_0_is_not_generic: diag(2315, ts.DiagnosticCategory.Error, "Type_0_is_not_generic_2315", "Type '{0}' is not generic."), + Global_type_0_must_be_a_class_or_interface_type: diag(2316, ts.DiagnosticCategory.Error, "Global_type_0_must_be_a_class_or_interface_type_2316", "Global type '{0}' must be a class or interface type."), + Global_type_0_must_have_1_type_parameter_s: diag(2317, ts.DiagnosticCategory.Error, "Global_type_0_must_have_1_type_parameter_s_2317", "Global type '{0}' must have {1} type parameter(s)."), + Cannot_find_global_type_0: diag(2318, ts.DiagnosticCategory.Error, "Cannot_find_global_type_0_2318", "Cannot find global type '{0}'."), + Named_property_0_of_types_1_and_2_are_not_identical: diag(2319, ts.DiagnosticCategory.Error, "Named_property_0_of_types_1_and_2_are_not_identical_2319", "Named property '{0}' of types '{1}' and '{2}' are not identical."), + Interface_0_cannot_simultaneously_extend_types_1_and_2: diag(2320, ts.DiagnosticCategory.Error, "Interface_0_cannot_simultaneously_extend_types_1_and_2_2320", "Interface '{0}' cannot simultaneously extend types '{1}' and '{2}'."), + Excessive_stack_depth_comparing_types_0_and_1: diag(2321, ts.DiagnosticCategory.Error, "Excessive_stack_depth_comparing_types_0_and_1_2321", "Excessive stack depth comparing types '{0}' and '{1}'."), + Type_0_is_not_assignable_to_type_1: diag(2322, ts.DiagnosticCategory.Error, "Type_0_is_not_assignable_to_type_1_2322", "Type '{0}' is not assignable to type '{1}'."), + Cannot_redeclare_exported_variable_0: diag(2323, ts.DiagnosticCategory.Error, "Cannot_redeclare_exported_variable_0_2323", "Cannot redeclare exported variable '{0}'."), + Property_0_is_missing_in_type_1: diag(2324, ts.DiagnosticCategory.Error, "Property_0_is_missing_in_type_1_2324", "Property '{0}' is missing in type '{1}'."), + Property_0_is_private_in_type_1_but_not_in_type_2: diag(2325, ts.DiagnosticCategory.Error, "Property_0_is_private_in_type_1_but_not_in_type_2_2325", "Property '{0}' is private in type '{1}' but not in type '{2}'."), + Types_of_property_0_are_incompatible: diag(2326, ts.DiagnosticCategory.Error, "Types_of_property_0_are_incompatible_2326", "Types of property '{0}' are incompatible."), + Property_0_is_optional_in_type_1_but_required_in_type_2: diag(2327, ts.DiagnosticCategory.Error, "Property_0_is_optional_in_type_1_but_required_in_type_2_2327", "Property '{0}' is optional in type '{1}' but required in type '{2}'."), + Types_of_parameters_0_and_1_are_incompatible: diag(2328, ts.DiagnosticCategory.Error, "Types_of_parameters_0_and_1_are_incompatible_2328", "Types of parameters '{0}' and '{1}' are incompatible."), + Index_signature_is_missing_in_type_0: diag(2329, ts.DiagnosticCategory.Error, "Index_signature_is_missing_in_type_0_2329", "Index signature is missing in type '{0}'."), + Index_signatures_are_incompatible: diag(2330, ts.DiagnosticCategory.Error, "Index_signatures_are_incompatible_2330", "Index signatures are incompatible."), + this_cannot_be_referenced_in_a_module_or_namespace_body: diag(2331, ts.DiagnosticCategory.Error, "this_cannot_be_referenced_in_a_module_or_namespace_body_2331", "'this' cannot be referenced in a module or namespace body."), + this_cannot_be_referenced_in_current_location: diag(2332, ts.DiagnosticCategory.Error, "this_cannot_be_referenced_in_current_location_2332", "'this' cannot be referenced in current location."), + this_cannot_be_referenced_in_constructor_arguments: diag(2333, ts.DiagnosticCategory.Error, "this_cannot_be_referenced_in_constructor_arguments_2333", "'this' cannot be referenced in constructor arguments."), + this_cannot_be_referenced_in_a_static_property_initializer: diag(2334, ts.DiagnosticCategory.Error, "this_cannot_be_referenced_in_a_static_property_initializer_2334", "'this' cannot be referenced in a static property initializer."), + super_can_only_be_referenced_in_a_derived_class: diag(2335, ts.DiagnosticCategory.Error, "super_can_only_be_referenced_in_a_derived_class_2335", "'super' can only be referenced in a derived class."), + super_cannot_be_referenced_in_constructor_arguments: diag(2336, ts.DiagnosticCategory.Error, "super_cannot_be_referenced_in_constructor_arguments_2336", "'super' cannot be referenced in constructor arguments."), + Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors: diag(2337, ts.DiagnosticCategory.Error, "Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors_2337", "Super calls are not permitted outside constructors or in nested functions inside constructors."), + super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_derived_class: diag(2338, ts.DiagnosticCategory.Error, "super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_der_2338", "'super' property access is permitted only in a constructor, member function, or member accessor of a derived class."), + Property_0_does_not_exist_on_type_1: diag(2339, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_2339", "Property '{0}' does not exist on type '{1}'."), + Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword: diag(2340, ts.DiagnosticCategory.Error, "Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword_2340", "Only public and protected methods of the base class are accessible via the 'super' keyword."), + Property_0_is_private_and_only_accessible_within_class_1: diag(2341, ts.DiagnosticCategory.Error, "Property_0_is_private_and_only_accessible_within_class_1_2341", "Property '{0}' is private and only accessible within class '{1}'."), + An_index_expression_argument_must_be_of_type_string_number_symbol_or_any: diag(2342, ts.DiagnosticCategory.Error, "An_index_expression_argument_must_be_of_type_string_number_symbol_or_any_2342", "An index expression argument must be of type 'string', 'number', 'symbol', or 'any'."), + This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1: diag(2343, ts.DiagnosticCategory.Error, "This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1_2343", "This syntax requires an imported helper named '{1}', but module '{0}' has no exported member '{1}'."), + Type_0_does_not_satisfy_the_constraint_1: diag(2344, ts.DiagnosticCategory.Error, "Type_0_does_not_satisfy_the_constraint_1_2344", "Type '{0}' does not satisfy the constraint '{1}'."), + Argument_of_type_0_is_not_assignable_to_parameter_of_type_1: diag(2345, ts.DiagnosticCategory.Error, "Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_2345", "Argument of type '{0}' is not assignable to parameter of type '{1}'."), + Call_target_does_not_contain_any_signatures: diag(2346, ts.DiagnosticCategory.Error, "Call_target_does_not_contain_any_signatures_2346", "Call target does not contain any signatures."), + Untyped_function_calls_may_not_accept_type_arguments: diag(2347, ts.DiagnosticCategory.Error, "Untyped_function_calls_may_not_accept_type_arguments_2347", "Untyped function calls may not accept type arguments."), + Value_of_type_0_is_not_callable_Did_you_mean_to_include_new: diag(2348, ts.DiagnosticCategory.Error, "Value_of_type_0_is_not_callable_Did_you_mean_to_include_new_2348", "Value of type '{0}' is not callable. Did you mean to include 'new'?"), + Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures: diag(2349, ts.DiagnosticCategory.Error, "Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatur_2349", "Cannot invoke an expression whose type lacks a call signature. Type '{0}' has no compatible call signatures."), + Only_a_void_function_can_be_called_with_the_new_keyword: diag(2350, ts.DiagnosticCategory.Error, "Only_a_void_function_can_be_called_with_the_new_keyword_2350", "Only a void function can be called with the 'new' keyword."), + Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature: diag(2351, ts.DiagnosticCategory.Error, "Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature_2351", "Cannot use 'new' with an expression whose type lacks a call or construct signature."), + Conversion_of_type_0_to_type_1_may_be_a_mistake_because_neither_type_sufficiently_overlaps_with_the_other_If_this_was_intentional_convert_the_expression_to_unknown_first: diag(2352, ts.DiagnosticCategory.Error, "Conversion_of_type_0_to_type_1_may_be_a_mistake_because_neither_type_sufficiently_overlaps_with_the__2352", "Conversion of type '{0}' to type '{1}' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first."), + Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1: diag(2353, ts.DiagnosticCategory.Error, "Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1_2353", "Object literal may only specify known properties, and '{0}' does not exist in type '{1}'."), + This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found: diag(2354, ts.DiagnosticCategory.Error, "This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found_2354", "This syntax requires an imported helper but module '{0}' cannot be found."), + A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value: diag(2355, ts.DiagnosticCategory.Error, "A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value_2355", "A function whose declared type is neither 'void' nor 'any' must return a value."), + An_arithmetic_operand_must_be_of_type_any_number_bigint_or_an_enum_type: diag(2356, ts.DiagnosticCategory.Error, "An_arithmetic_operand_must_be_of_type_any_number_bigint_or_an_enum_type_2356", "An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type."), + The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access: diag(2357, ts.DiagnosticCategory.Error, "The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access_2357", "The operand of an increment or decrement operator must be a variable or a property access."), + The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter: diag(2358, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_paramete_2358", "The left-hand side of an 'instanceof' expression must be of type 'any', an object type or a type parameter."), + The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_Function_interface_type: diag(2359, ts.DiagnosticCategory.Error, "The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_F_2359", "The right-hand side of an 'instanceof' expression must be of type 'any' or of a type assignable to the 'Function' interface type."), + The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol: diag(2360, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol_2360", "The left-hand side of an 'in' expression must be of type 'any', 'string', 'number', or 'symbol'."), + The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter: diag(2361, ts.DiagnosticCategory.Error, "The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter_2361", "The right-hand side of an 'in' expression must be of type 'any', an object type or a type parameter."), + The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type: diag(2362, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type_2362", "The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type."), + The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type: diag(2363, ts.DiagnosticCategory.Error, "The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type_2363", "The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type."), + The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access: diag(2364, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access_2364", "The left-hand side of an assignment expression must be a variable or a property access."), + Operator_0_cannot_be_applied_to_types_1_and_2: diag(2365, ts.DiagnosticCategory.Error, "Operator_0_cannot_be_applied_to_types_1_and_2_2365", "Operator '{0}' cannot be applied to types '{1}' and '{2}'."), + Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined: diag(2366, ts.DiagnosticCategory.Error, "Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined_2366", "Function lacks ending return statement and return type does not include 'undefined'."), + This_condition_will_always_return_0_since_the_types_1_and_2_have_no_overlap: diag(2367, ts.DiagnosticCategory.Error, "This_condition_will_always_return_0_since_the_types_1_and_2_have_no_overlap_2367", "This condition will always return '{0}' since the types '{1}' and '{2}' have no overlap."), + Type_parameter_name_cannot_be_0: diag(2368, ts.DiagnosticCategory.Error, "Type_parameter_name_cannot_be_0_2368", "Type parameter name cannot be '{0}'."), + A_parameter_property_is_only_allowed_in_a_constructor_implementation: diag(2369, ts.DiagnosticCategory.Error, "A_parameter_property_is_only_allowed_in_a_constructor_implementation_2369", "A parameter property is only allowed in a constructor implementation."), + A_rest_parameter_must_be_of_an_array_type: diag(2370, ts.DiagnosticCategory.Error, "A_rest_parameter_must_be_of_an_array_type_2370", "A rest parameter must be of an array type."), + A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation: diag(2371, ts.DiagnosticCategory.Error, "A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation_2371", "A parameter initializer is only allowed in a function or constructor implementation."), + Parameter_0_cannot_be_referenced_in_its_initializer: diag(2372, ts.DiagnosticCategory.Error, "Parameter_0_cannot_be_referenced_in_its_initializer_2372", "Parameter '{0}' cannot be referenced in its initializer."), + Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it: diag(2373, ts.DiagnosticCategory.Error, "Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it_2373", "Initializer of parameter '{0}' cannot reference identifier '{1}' declared after it."), + Duplicate_string_index_signature: diag(2374, ts.DiagnosticCategory.Error, "Duplicate_string_index_signature_2374", "Duplicate string index signature."), + Duplicate_number_index_signature: diag(2375, ts.DiagnosticCategory.Error, "Duplicate_number_index_signature_2375", "Duplicate number index signature."), + A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_properties_or_has_parameter_properties: diag(2376, ts.DiagnosticCategory.Error, "A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_proper_2376", "A 'super' call must be the first statement in the constructor when a class contains initialized properties or has parameter properties."), + Constructors_for_derived_classes_must_contain_a_super_call: diag(2377, ts.DiagnosticCategory.Error, "Constructors_for_derived_classes_must_contain_a_super_call_2377", "Constructors for derived classes must contain a 'super' call."), + A_get_accessor_must_return_a_value: diag(2378, ts.DiagnosticCategory.Error, "A_get_accessor_must_return_a_value_2378", "A 'get' accessor must return a value."), + Getter_and_setter_accessors_do_not_agree_in_visibility: diag(2379, ts.DiagnosticCategory.Error, "Getter_and_setter_accessors_do_not_agree_in_visibility_2379", "Getter and setter accessors do not agree in visibility."), + get_and_set_accessor_must_have_the_same_type: diag(2380, ts.DiagnosticCategory.Error, "get_and_set_accessor_must_have_the_same_type_2380", "'get' and 'set' accessor must have the same type."), + A_signature_with_an_implementation_cannot_use_a_string_literal_type: diag(2381, ts.DiagnosticCategory.Error, "A_signature_with_an_implementation_cannot_use_a_string_literal_type_2381", "A signature with an implementation cannot use a string literal type."), + Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature: diag(2382, ts.DiagnosticCategory.Error, "Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature_2382", "Specialized overload signature is not assignable to any non-specialized signature."), + Overload_signatures_must_all_be_exported_or_non_exported: diag(2383, ts.DiagnosticCategory.Error, "Overload_signatures_must_all_be_exported_or_non_exported_2383", "Overload signatures must all be exported or non-exported."), + Overload_signatures_must_all_be_ambient_or_non_ambient: diag(2384, ts.DiagnosticCategory.Error, "Overload_signatures_must_all_be_ambient_or_non_ambient_2384", "Overload signatures must all be ambient or non-ambient."), + Overload_signatures_must_all_be_public_private_or_protected: diag(2385, ts.DiagnosticCategory.Error, "Overload_signatures_must_all_be_public_private_or_protected_2385", "Overload signatures must all be public, private or protected."), + Overload_signatures_must_all_be_optional_or_required: diag(2386, ts.DiagnosticCategory.Error, "Overload_signatures_must_all_be_optional_or_required_2386", "Overload signatures must all be optional or required."), + Function_overload_must_be_static: diag(2387, ts.DiagnosticCategory.Error, "Function_overload_must_be_static_2387", "Function overload must be static."), + Function_overload_must_not_be_static: diag(2388, ts.DiagnosticCategory.Error, "Function_overload_must_not_be_static_2388", "Function overload must not be static."), + Function_implementation_name_must_be_0: diag(2389, ts.DiagnosticCategory.Error, "Function_implementation_name_must_be_0_2389", "Function implementation name must be '{0}'."), + Constructor_implementation_is_missing: diag(2390, ts.DiagnosticCategory.Error, "Constructor_implementation_is_missing_2390", "Constructor implementation is missing."), + Function_implementation_is_missing_or_not_immediately_following_the_declaration: diag(2391, ts.DiagnosticCategory.Error, "Function_implementation_is_missing_or_not_immediately_following_the_declaration_2391", "Function implementation is missing or not immediately following the declaration."), + Multiple_constructor_implementations_are_not_allowed: diag(2392, ts.DiagnosticCategory.Error, "Multiple_constructor_implementations_are_not_allowed_2392", "Multiple constructor implementations are not allowed."), + Duplicate_function_implementation: diag(2393, ts.DiagnosticCategory.Error, "Duplicate_function_implementation_2393", "Duplicate function implementation."), + Overload_signature_is_not_compatible_with_function_implementation: diag(2394, ts.DiagnosticCategory.Error, "Overload_signature_is_not_compatible_with_function_implementation_2394", "Overload signature is not compatible with function implementation."), + Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local: diag(2395, ts.DiagnosticCategory.Error, "Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local_2395", "Individual declarations in merged declaration '{0}' must be all exported or all local."), + Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters: diag(2396, ts.DiagnosticCategory.Error, "Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters_2396", "Duplicate identifier 'arguments'. Compiler uses 'arguments' to initialize rest parameters."), + Declaration_name_conflicts_with_built_in_global_identifier_0: diag(2397, ts.DiagnosticCategory.Error, "Declaration_name_conflicts_with_built_in_global_identifier_0_2397", "Declaration name conflicts with built-in global identifier '{0}'."), + Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference: diag(2399, ts.DiagnosticCategory.Error, "Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference_2399", "Duplicate identifier '_this'. Compiler uses variable declaration '_this' to capture 'this' reference."), + Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference: diag(2400, ts.DiagnosticCategory.Error, "Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference_2400", "Expression resolves to variable declaration '_this' that compiler uses to capture 'this' reference."), + Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference: diag(2401, ts.DiagnosticCategory.Error, "Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference_2401", "Duplicate identifier '_super'. Compiler uses '_super' to capture base class reference."), + Expression_resolves_to_super_that_compiler_uses_to_capture_base_class_reference: diag(2402, ts.DiagnosticCategory.Error, "Expression_resolves_to_super_that_compiler_uses_to_capture_base_class_reference_2402", "Expression resolves to '_super' that compiler uses to capture base class reference."), + Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2: diag(2403, ts.DiagnosticCategory.Error, "Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_t_2403", "Subsequent variable declarations must have the same type. Variable '{0}' must be of type '{1}', but here has type '{2}'."), + The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation: diag(2404, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation_2404", "The left-hand side of a 'for...in' statement cannot use a type annotation."), + The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any: diag(2405, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any_2405", "The left-hand side of a 'for...in' statement must be of type 'string' or 'any'."), + The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access: diag(2406, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access_2406", "The left-hand side of a 'for...in' statement must be a variable or a property access."), + The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_but_here_has_type_0: diag(2407, ts.DiagnosticCategory.Error, "The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_but_2407", "The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter, but here has type '{0}'."), + Setters_cannot_return_a_value: diag(2408, ts.DiagnosticCategory.Error, "Setters_cannot_return_a_value_2408", "Setters cannot return a value."), + Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class: diag(2409, ts.DiagnosticCategory.Error, "Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class_2409", "Return type of constructor signature must be assignable to the instance type of the class."), + The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any: diag(2410, ts.DiagnosticCategory.Error, "The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any_2410", "The 'with' statement is not supported. All symbols in a 'with' block will have type 'any'."), + Property_0_of_type_1_is_not_assignable_to_string_index_type_2: diag(2411, ts.DiagnosticCategory.Error, "Property_0_of_type_1_is_not_assignable_to_string_index_type_2_2411", "Property '{0}' of type '{1}' is not assignable to string index type '{2}'."), + Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2: diag(2412, ts.DiagnosticCategory.Error, "Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2_2412", "Property '{0}' of type '{1}' is not assignable to numeric index type '{2}'."), + Numeric_index_type_0_is_not_assignable_to_string_index_type_1: diag(2413, ts.DiagnosticCategory.Error, "Numeric_index_type_0_is_not_assignable_to_string_index_type_1_2413", "Numeric index type '{0}' is not assignable to string index type '{1}'."), + Class_name_cannot_be_0: diag(2414, ts.DiagnosticCategory.Error, "Class_name_cannot_be_0_2414", "Class name cannot be '{0}'."), + Class_0_incorrectly_extends_base_class_1: diag(2415, ts.DiagnosticCategory.Error, "Class_0_incorrectly_extends_base_class_1_2415", "Class '{0}' incorrectly extends base class '{1}'."), + Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2: diag(2416, ts.DiagnosticCategory.Error, "Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2_2416", "Property '{0}' in type '{1}' is not assignable to the same property in base type '{2}'."), + Class_static_side_0_incorrectly_extends_base_class_static_side_1: diag(2417, ts.DiagnosticCategory.Error, "Class_static_side_0_incorrectly_extends_base_class_static_side_1_2417", "Class static side '{0}' incorrectly extends base class static side '{1}'."), + Type_of_computed_property_s_value_is_0_which_is_not_assignable_to_type_1: diag(2418, ts.DiagnosticCategory.Error, "Type_of_computed_property_s_value_is_0_which_is_not_assignable_to_type_1_2418", "Type of computed property's value is '{0}', which is not assignable to type '{1}'."), + Class_0_incorrectly_implements_interface_1: diag(2420, ts.DiagnosticCategory.Error, "Class_0_incorrectly_implements_interface_1_2420", "Class '{0}' incorrectly implements interface '{1}'."), + A_class_can_only_implement_an_object_type_or_intersection_of_object_types_with_statically_known_members: diag(2422, ts.DiagnosticCategory.Error, "A_class_can_only_implement_an_object_type_or_intersection_of_object_types_with_statically_known_memb_2422", "A class can only implement an object type or intersection of object types with statically known members."), + Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor: diag(2423, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_access_2423", "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member accessor."), + Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_property: diag(2424, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_proper_2424", "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member property."), + Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_function: diag(2425, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_functi_2425", "Class '{0}' defines instance member property '{1}', but extended class '{2}' defines it as instance member function."), + Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function: diag(2426, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_functi_2426", "Class '{0}' defines instance member accessor '{1}', but extended class '{2}' defines it as instance member function."), + Interface_name_cannot_be_0: diag(2427, ts.DiagnosticCategory.Error, "Interface_name_cannot_be_0_2427", "Interface name cannot be '{0}'."), + All_declarations_of_0_must_have_identical_type_parameters: diag(2428, ts.DiagnosticCategory.Error, "All_declarations_of_0_must_have_identical_type_parameters_2428", "All declarations of '{0}' must have identical type parameters."), + Interface_0_incorrectly_extends_interface_1: diag(2430, ts.DiagnosticCategory.Error, "Interface_0_incorrectly_extends_interface_1_2430", "Interface '{0}' incorrectly extends interface '{1}'."), + Enum_name_cannot_be_0: diag(2431, ts.DiagnosticCategory.Error, "Enum_name_cannot_be_0_2431", "Enum name cannot be '{0}'."), + In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enum_element: diag(2432, ts.DiagnosticCategory.Error, "In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enu_2432", "In an enum with multiple declarations, only one declaration can omit an initializer for its first enum element."), + A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merged: diag(2433, ts.DiagnosticCategory.Error, "A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merg_2433", "A namespace declaration cannot be in a different file from a class or function with which it is merged."), + A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged: diag(2434, ts.DiagnosticCategory.Error, "A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged_2434", "A namespace declaration cannot be located prior to a class or function with which it is merged."), + Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces: diag(2435, ts.DiagnosticCategory.Error, "Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces_2435", "Ambient modules cannot be nested in other modules or namespaces."), + Ambient_module_declaration_cannot_specify_relative_module_name: diag(2436, ts.DiagnosticCategory.Error, "Ambient_module_declaration_cannot_specify_relative_module_name_2436", "Ambient module declaration cannot specify relative module name."), + Module_0_is_hidden_by_a_local_declaration_with_the_same_name: diag(2437, ts.DiagnosticCategory.Error, "Module_0_is_hidden_by_a_local_declaration_with_the_same_name_2437", "Module '{0}' is hidden by a local declaration with the same name."), + Import_name_cannot_be_0: diag(2438, ts.DiagnosticCategory.Error, "Import_name_cannot_be_0_2438", "Import name cannot be '{0}'."), + Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relative_module_name: diag(2439, ts.DiagnosticCategory.Error, "Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relati_2439", "Import or export declaration in an ambient module declaration cannot reference module through relative module name."), + Import_declaration_conflicts_with_local_declaration_of_0: diag(2440, ts.DiagnosticCategory.Error, "Import_declaration_conflicts_with_local_declaration_of_0_2440", "Import declaration conflicts with local declaration of '{0}'."), + Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module: diag(2441, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_2441", "Duplicate identifier '{0}'. Compiler reserves name '{1}' in top level scope of a module."), + Types_have_separate_declarations_of_a_private_property_0: diag(2442, ts.DiagnosticCategory.Error, "Types_have_separate_declarations_of_a_private_property_0_2442", "Types have separate declarations of a private property '{0}'."), + Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2: diag(2443, ts.DiagnosticCategory.Error, "Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2_2443", "Property '{0}' is protected but type '{1}' is not a class derived from '{2}'."), + Property_0_is_protected_in_type_1_but_public_in_type_2: diag(2444, ts.DiagnosticCategory.Error, "Property_0_is_protected_in_type_1_but_public_in_type_2_2444", "Property '{0}' is protected in type '{1}' but public in type '{2}'."), + Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses: diag(2445, ts.DiagnosticCategory.Error, "Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses_2445", "Property '{0}' is protected and only accessible within class '{1}' and its subclasses."), + Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1: diag(2446, ts.DiagnosticCategory.Error, "Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1_2446", "Property '{0}' is protected and only accessible through an instance of class '{1}'."), + The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead: diag(2447, ts.DiagnosticCategory.Error, "The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead_2447", "The '{0}' operator is not allowed for boolean types. Consider using '{1}' instead."), + Block_scoped_variable_0_used_before_its_declaration: diag(2448, ts.DiagnosticCategory.Error, "Block_scoped_variable_0_used_before_its_declaration_2448", "Block-scoped variable '{0}' used before its declaration."), + Class_0_used_before_its_declaration: diag(2449, ts.DiagnosticCategory.Error, "Class_0_used_before_its_declaration_2449", "Class '{0}' used before its declaration."), + Enum_0_used_before_its_declaration: diag(2450, ts.DiagnosticCategory.Error, "Enum_0_used_before_its_declaration_2450", "Enum '{0}' used before its declaration."), + Cannot_redeclare_block_scoped_variable_0: diag(2451, ts.DiagnosticCategory.Error, "Cannot_redeclare_block_scoped_variable_0_2451", "Cannot redeclare block-scoped variable '{0}'."), + An_enum_member_cannot_have_a_numeric_name: diag(2452, ts.DiagnosticCategory.Error, "An_enum_member_cannot_have_a_numeric_name_2452", "An enum member cannot have a numeric name."), + The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_type_arguments_explicitly: diag(2453, ts.DiagnosticCategory.Error, "The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_typ_2453", "The type argument for type parameter '{0}' cannot be inferred from the usage. Consider specifying the type arguments explicitly."), + Variable_0_is_used_before_being_assigned: diag(2454, ts.DiagnosticCategory.Error, "Variable_0_is_used_before_being_assigned_2454", "Variable '{0}' is used before being assigned."), + Type_argument_candidate_1_is_not_a_valid_type_argument_because_it_is_not_a_supertype_of_candidate_0: diag(2455, ts.DiagnosticCategory.Error, "Type_argument_candidate_1_is_not_a_valid_type_argument_because_it_is_not_a_supertype_of_candidate_0_2455", "Type argument candidate '{1}' is not a valid type argument because it is not a supertype of candidate '{0}'."), + Type_alias_0_circularly_references_itself: diag(2456, ts.DiagnosticCategory.Error, "Type_alias_0_circularly_references_itself_2456", "Type alias '{0}' circularly references itself."), + Type_alias_name_cannot_be_0: diag(2457, ts.DiagnosticCategory.Error, "Type_alias_name_cannot_be_0_2457", "Type alias name cannot be '{0}'."), + An_AMD_module_cannot_have_multiple_name_assignments: diag(2458, ts.DiagnosticCategory.Error, "An_AMD_module_cannot_have_multiple_name_assignments_2458", "An AMD module cannot have multiple name assignments."), + Type_0_has_no_property_1_and_no_string_index_signature: diag(2459, ts.DiagnosticCategory.Error, "Type_0_has_no_property_1_and_no_string_index_signature_2459", "Type '{0}' has no property '{1}' and no string index signature."), + Type_0_has_no_property_1: diag(2460, ts.DiagnosticCategory.Error, "Type_0_has_no_property_1_2460", "Type '{0}' has no property '{1}'."), + Type_0_is_not_an_array_type: diag(2461, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_2461", "Type '{0}' is not an array type."), + A_rest_element_must_be_last_in_a_destructuring_pattern: diag(2462, ts.DiagnosticCategory.Error, "A_rest_element_must_be_last_in_a_destructuring_pattern_2462", "A rest element must be last in a destructuring pattern."), + A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature: diag(2463, ts.DiagnosticCategory.Error, "A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature_2463", "A binding pattern parameter cannot be optional in an implementation signature."), + A_computed_property_name_must_be_of_type_string_number_symbol_or_any: diag(2464, ts.DiagnosticCategory.Error, "A_computed_property_name_must_be_of_type_string_number_symbol_or_any_2464", "A computed property name must be of type 'string', 'number', 'symbol', or 'any'."), + this_cannot_be_referenced_in_a_computed_property_name: diag(2465, ts.DiagnosticCategory.Error, "this_cannot_be_referenced_in_a_computed_property_name_2465", "'this' cannot be referenced in a computed property name."), + super_cannot_be_referenced_in_a_computed_property_name: diag(2466, ts.DiagnosticCategory.Error, "super_cannot_be_referenced_in_a_computed_property_name_2466", "'super' cannot be referenced in a computed property name."), + A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type: diag(2467, ts.DiagnosticCategory.Error, "A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type_2467", "A computed property name cannot reference a type parameter from its containing type."), + Cannot_find_global_value_0: diag(2468, ts.DiagnosticCategory.Error, "Cannot_find_global_value_0_2468", "Cannot find global value '{0}'."), + The_0_operator_cannot_be_applied_to_type_symbol: diag(2469, ts.DiagnosticCategory.Error, "The_0_operator_cannot_be_applied_to_type_symbol_2469", "The '{0}' operator cannot be applied to type 'symbol'."), + Symbol_reference_does_not_refer_to_the_global_Symbol_constructor_object: diag(2470, ts.DiagnosticCategory.Error, "Symbol_reference_does_not_refer_to_the_global_Symbol_constructor_object_2470", "'Symbol' reference does not refer to the global Symbol constructor object."), + A_computed_property_name_of_the_form_0_must_be_of_type_symbol: diag(2471, ts.DiagnosticCategory.Error, "A_computed_property_name_of_the_form_0_must_be_of_type_symbol_2471", "A computed property name of the form '{0}' must be of type 'symbol'."), + Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher: diag(2472, ts.DiagnosticCategory.Error, "Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher_2472", "Spread operator in 'new' expressions is only available when targeting ECMAScript 5 and higher."), + Enum_declarations_must_all_be_const_or_non_const: diag(2473, ts.DiagnosticCategory.Error, "Enum_declarations_must_all_be_const_or_non_const_2473", "Enum declarations must all be const or non-const."), + In_const_enum_declarations_member_initializer_must_be_constant_expression: diag(2474, ts.DiagnosticCategory.Error, "In_const_enum_declarations_member_initializer_must_be_constant_expression_2474", "In 'const' enum declarations member initializer must be constant expression."), + const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment_or_type_query: diag(2475, ts.DiagnosticCategory.Error, "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475", "'const' enums can only be used in property or index access expressions or the right hand side of an import declaration or export assignment or type query."), + A_const_enum_member_can_only_be_accessed_using_a_string_literal: diag(2476, ts.DiagnosticCategory.Error, "A_const_enum_member_can_only_be_accessed_using_a_string_literal_2476", "A const enum member can only be accessed using a string literal."), + const_enum_member_initializer_was_evaluated_to_a_non_finite_value: diag(2477, ts.DiagnosticCategory.Error, "const_enum_member_initializer_was_evaluated_to_a_non_finite_value_2477", "'const' enum member initializer was evaluated to a non-finite value."), + const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN: diag(2478, ts.DiagnosticCategory.Error, "const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN_2478", "'const' enum member initializer was evaluated to disallowed value 'NaN'."), + Property_0_does_not_exist_on_const_enum_1: diag(2479, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_const_enum_1_2479", "Property '{0}' does not exist on 'const' enum '{1}'."), + let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations: diag(2480, ts.DiagnosticCategory.Error, "let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations_2480", "'let' is not allowed to be used as a name in 'let' or 'const' declarations."), + Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1: diag(2481, ts.DiagnosticCategory.Error, "Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1_2481", "Cannot initialize outer scoped variable '{0}' in the same scope as block scoped declaration '{1}'."), + The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation: diag(2483, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation_2483", "The left-hand side of a 'for...of' statement cannot use a type annotation."), + Export_declaration_conflicts_with_exported_declaration_of_0: diag(2484, ts.DiagnosticCategory.Error, "Export_declaration_conflicts_with_exported_declaration_of_0_2484", "Export declaration conflicts with exported declaration of '{0}'."), + The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access: diag(2487, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access_2487", "The left-hand side of a 'for...of' statement must be a variable or a property access."), + Type_0_must_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2488, ts.DiagnosticCategory.Error, "Type_0_must_have_a_Symbol_iterator_method_that_returns_an_iterator_2488", "Type '{0}' must have a '[Symbol.iterator]()' method that returns an iterator."), + An_iterator_must_have_a_next_method: diag(2489, ts.DiagnosticCategory.Error, "An_iterator_must_have_a_next_method_2489", "An iterator must have a 'next()' method."), + The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property: diag(2490, ts.DiagnosticCategory.Error, "The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property_2490", "The type returned by the 'next()' method of an iterator must have a 'value' property."), + The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern: diag(2491, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern_2491", "The left-hand side of a 'for...in' statement cannot be a destructuring pattern."), + Cannot_redeclare_identifier_0_in_catch_clause: diag(2492, ts.DiagnosticCategory.Error, "Cannot_redeclare_identifier_0_in_catch_clause_2492", "Cannot redeclare identifier '{0}' in catch clause."), + Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2: diag(2493, ts.DiagnosticCategory.Error, "Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2_2493", "Tuple type '{0}' with length '{1}' cannot be assigned to tuple with length '{2}'."), + Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher: diag(2494, ts.DiagnosticCategory.Error, "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494", "Using a string in a 'for...of' statement is only supported in ECMAScript 5 and higher."), + Type_0_is_not_an_array_type_or_a_string_type: diag(2495, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_a_string_type_2495", "Type '{0}' is not an array type or a string type."), + The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_standard_function_expression: diag(2496, ts.DiagnosticCategory.Error, "The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_stand_2496", "The 'arguments' object cannot be referenced in an arrow function in ES3 and ES5. Consider using a standard function expression."), + Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct: diag(2497, ts.DiagnosticCategory.Error, "Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct_2497", "Module '{0}' resolves to a non-module entity and cannot be imported using this construct."), + Module_0_uses_export_and_cannot_be_used_with_export_Asterisk: diag(2498, ts.DiagnosticCategory.Error, "Module_0_uses_export_and_cannot_be_used_with_export_Asterisk_2498", "Module '{0}' uses 'export =' and cannot be used with 'export *'."), + An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments: diag(2499, ts.DiagnosticCategory.Error, "An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments_2499", "An interface can only extend an identifier/qualified-name with optional type arguments."), + A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments: diag(2500, ts.DiagnosticCategory.Error, "A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments_2500", "A class can only implement an identifier/qualified-name with optional type arguments."), + A_rest_element_cannot_contain_a_binding_pattern: diag(2501, ts.DiagnosticCategory.Error, "A_rest_element_cannot_contain_a_binding_pattern_2501", "A rest element cannot contain a binding pattern."), + _0_is_referenced_directly_or_indirectly_in_its_own_type_annotation: diag(2502, ts.DiagnosticCategory.Error, "_0_is_referenced_directly_or_indirectly_in_its_own_type_annotation_2502", "'{0}' is referenced directly or indirectly in its own type annotation."), + Cannot_find_namespace_0: diag(2503, ts.DiagnosticCategory.Error, "Cannot_find_namespace_0_2503", "Cannot find namespace '{0}'."), + Type_0_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator: diag(2504, ts.DiagnosticCategory.Error, "Type_0_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator_2504", "Type '{0}' must have a '[Symbol.asyncIterator]()' method that returns an async iterator."), + A_generator_cannot_have_a_void_type_annotation: diag(2505, ts.DiagnosticCategory.Error, "A_generator_cannot_have_a_void_type_annotation_2505", "A generator cannot have a 'void' type annotation."), + _0_is_referenced_directly_or_indirectly_in_its_own_base_expression: diag(2506, ts.DiagnosticCategory.Error, "_0_is_referenced_directly_or_indirectly_in_its_own_base_expression_2506", "'{0}' is referenced directly or indirectly in its own base expression."), + Type_0_is_not_a_constructor_function_type: diag(2507, ts.DiagnosticCategory.Error, "Type_0_is_not_a_constructor_function_type_2507", "Type '{0}' is not a constructor function type."), + No_base_constructor_has_the_specified_number_of_type_arguments: diag(2508, ts.DiagnosticCategory.Error, "No_base_constructor_has_the_specified_number_of_type_arguments_2508", "No base constructor has the specified number of type arguments."), + Base_constructor_return_type_0_is_not_an_object_type_or_intersection_of_object_types_with_statically_known_members: diag(2509, ts.DiagnosticCategory.Error, "Base_constructor_return_type_0_is_not_an_object_type_or_intersection_of_object_types_with_statically_2509", "Base constructor return type '{0}' is not an object type or intersection of object types with statically known members."), + Base_constructors_must_all_have_the_same_return_type: diag(2510, ts.DiagnosticCategory.Error, "Base_constructors_must_all_have_the_same_return_type_2510", "Base constructors must all have the same return type."), + Cannot_create_an_instance_of_an_abstract_class: diag(2511, ts.DiagnosticCategory.Error, "Cannot_create_an_instance_of_an_abstract_class_2511", "Cannot create an instance of an abstract class."), + Overload_signatures_must_all_be_abstract_or_non_abstract: diag(2512, ts.DiagnosticCategory.Error, "Overload_signatures_must_all_be_abstract_or_non_abstract_2512", "Overload signatures must all be abstract or non-abstract."), + Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression: diag(2513, ts.DiagnosticCategory.Error, "Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression_2513", "Abstract method '{0}' in class '{1}' cannot be accessed via super expression."), + Classes_containing_abstract_methods_must_be_marked_abstract: diag(2514, ts.DiagnosticCategory.Error, "Classes_containing_abstract_methods_must_be_marked_abstract_2514", "Classes containing abstract methods must be marked abstract."), + Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2: diag(2515, ts.DiagnosticCategory.Error, "Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2_2515", "Non-abstract class '{0}' does not implement inherited abstract member '{1}' from class '{2}'."), + All_declarations_of_an_abstract_method_must_be_consecutive: diag(2516, ts.DiagnosticCategory.Error, "All_declarations_of_an_abstract_method_must_be_consecutive_2516", "All declarations of an abstract method must be consecutive."), + Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type: diag(2517, ts.DiagnosticCategory.Error, "Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type_2517", "Cannot assign an abstract constructor type to a non-abstract constructor type."), + A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard: diag(2518, ts.DiagnosticCategory.Error, "A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard_2518", "A 'this'-based type guard is not compatible with a parameter-based type guard."), + An_async_iterator_must_have_a_next_method: diag(2519, ts.DiagnosticCategory.Error, "An_async_iterator_must_have_a_next_method_2519", "An async iterator must have a 'next()' method."), + Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions: diag(2520, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions_2520", "Duplicate identifier '{0}'. Compiler uses declaration '{1}' to support async functions."), + Expression_resolves_to_variable_declaration_0_that_compiler_uses_to_support_async_functions: diag(2521, ts.DiagnosticCategory.Error, "Expression_resolves_to_variable_declaration_0_that_compiler_uses_to_support_async_functions_2521", "Expression resolves to variable declaration '{0}' that compiler uses to support async functions."), + The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_using_a_standard_function_or_method: diag(2522, ts.DiagnosticCategory.Error, "The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_usi_2522", "The 'arguments' object cannot be referenced in an async function or method in ES3 and ES5. Consider using a standard function or method."), + yield_expressions_cannot_be_used_in_a_parameter_initializer: diag(2523, ts.DiagnosticCategory.Error, "yield_expressions_cannot_be_used_in_a_parameter_initializer_2523", "'yield' expressions cannot be used in a parameter initializer."), + await_expressions_cannot_be_used_in_a_parameter_initializer: diag(2524, ts.DiagnosticCategory.Error, "await_expressions_cannot_be_used_in_a_parameter_initializer_2524", "'await' expressions cannot be used in a parameter initializer."), + Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value: diag(2525, ts.DiagnosticCategory.Error, "Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value_2525", "Initializer provides no value for this binding element and the binding element has no default value."), + A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface: diag(2526, ts.DiagnosticCategory.Error, "A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface_2526", "A 'this' type is available only in a non-static member of a class or interface."), + The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary: diag(2527, ts.DiagnosticCategory.Error, "The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary_2527", "The inferred type of '{0}' references an inaccessible '{1}' type. A type annotation is necessary."), + A_module_cannot_have_multiple_default_exports: diag(2528, ts.DiagnosticCategory.Error, "A_module_cannot_have_multiple_default_exports_2528", "A module cannot have multiple default exports."), + Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_functions: diag(2529, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_func_2529", "Duplicate identifier '{0}'. Compiler reserves name '{1}' in top level scope of a module containing async functions."), + Property_0_is_incompatible_with_index_signature: diag(2530, ts.DiagnosticCategory.Error, "Property_0_is_incompatible_with_index_signature_2530", "Property '{0}' is incompatible with index signature."), + Object_is_possibly_null: diag(2531, ts.DiagnosticCategory.Error, "Object_is_possibly_null_2531", "Object is possibly 'null'."), + Object_is_possibly_undefined: diag(2532, ts.DiagnosticCategory.Error, "Object_is_possibly_undefined_2532", "Object is possibly 'undefined'."), + Object_is_possibly_null_or_undefined: diag(2533, ts.DiagnosticCategory.Error, "Object_is_possibly_null_or_undefined_2533", "Object is possibly 'null' or 'undefined'."), + A_function_returning_never_cannot_have_a_reachable_end_point: diag(2534, ts.DiagnosticCategory.Error, "A_function_returning_never_cannot_have_a_reachable_end_point_2534", "A function returning 'never' cannot have a reachable end point."), + Enum_type_0_has_members_with_initializers_that_are_not_literals: diag(2535, ts.DiagnosticCategory.Error, "Enum_type_0_has_members_with_initializers_that_are_not_literals_2535", "Enum type '{0}' has members with initializers that are not literals."), + Type_0_cannot_be_used_to_index_type_1: diag(2536, ts.DiagnosticCategory.Error, "Type_0_cannot_be_used_to_index_type_1_2536", "Type '{0}' cannot be used to index type '{1}'."), + Type_0_has_no_matching_index_signature_for_type_1: diag(2537, ts.DiagnosticCategory.Error, "Type_0_has_no_matching_index_signature_for_type_1_2537", "Type '{0}' has no matching index signature for type '{1}'."), + Type_0_cannot_be_used_as_an_index_type: diag(2538, ts.DiagnosticCategory.Error, "Type_0_cannot_be_used_as_an_index_type_2538", "Type '{0}' cannot be used as an index type."), + Cannot_assign_to_0_because_it_is_not_a_variable: diag(2539, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_not_a_variable_2539", "Cannot assign to '{0}' because it is not a variable."), + Cannot_assign_to_0_because_it_is_a_read_only_property: diag(2540, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_a_read_only_property_2540", "Cannot assign to '{0}' because it is a read-only property."), + The_target_of_an_assignment_must_be_a_variable_or_a_property_access: diag(2541, ts.DiagnosticCategory.Error, "The_target_of_an_assignment_must_be_a_variable_or_a_property_access_2541", "The target of an assignment must be a variable or a property access."), + Index_signature_in_type_0_only_permits_reading: diag(2542, ts.DiagnosticCategory.Error, "Index_signature_in_type_0_only_permits_reading_2542", "Index signature in type '{0}' only permits reading."), + Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference: diag(2543, ts.DiagnosticCategory.Error, "Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_me_2543", "Duplicate identifier '_newTarget'. Compiler uses variable declaration '_newTarget' to capture 'new.target' meta-property reference."), + Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta_property_reference: diag(2544, ts.DiagnosticCategory.Error, "Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta__2544", "Expression resolves to variable declaration '_newTarget' that compiler uses to capture 'new.target' meta-property reference."), + A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any: diag(2545, ts.DiagnosticCategory.Error, "A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any_2545", "A mixin class must have a constructor with a single rest parameter of type 'any[]'."), + Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1: diag(2546, ts.DiagnosticCategory.Error, "Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1_2546", "Property '{0}' has conflicting declarations and is inaccessible in type '{1}'."), + The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property: diag(2547, ts.DiagnosticCategory.Error, "The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value__2547", "The type returned by the 'next()' method of an async iterator must be a promise for a type with a 'value' property."), + Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2548, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548", "Type '{0}' is not an array type or does not have a '[Symbol.iterator]()' method that returns an iterator."), + Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2549, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549", "Type '{0}' is not an array type or a string type or does not have a '[Symbol.iterator]()' method that returns an iterator."), + Property_0_does_not_exist_on_type_1_Did_you_mean_2: diag(2551, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551", "Property '{0}' does not exist on type '{1}'. Did you mean '{2}'?"), + Cannot_find_name_0_Did_you_mean_1: diag(2552, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Did_you_mean_1_2552", "Cannot find name '{0}'. Did you mean '{1}'?"), + Computed_values_are_not_permitted_in_an_enum_with_string_valued_members: diag(2553, ts.DiagnosticCategory.Error, "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553", "Computed values are not permitted in an enum with string valued members."), + Expected_0_arguments_but_got_1: diag(2554, ts.DiagnosticCategory.Error, "Expected_0_arguments_but_got_1_2554", "Expected {0} arguments, but got {1}."), + Expected_at_least_0_arguments_but_got_1: diag(2555, ts.DiagnosticCategory.Error, "Expected_at_least_0_arguments_but_got_1_2555", "Expected at least {0} arguments, but got {1}."), + Expected_0_arguments_but_got_1_or_more: diag(2556, ts.DiagnosticCategory.Error, "Expected_0_arguments_but_got_1_or_more_2556", "Expected {0} arguments, but got {1} or more."), + Expected_at_least_0_arguments_but_got_1_or_more: diag(2557, ts.DiagnosticCategory.Error, "Expected_at_least_0_arguments_but_got_1_or_more_2557", "Expected at least {0} arguments, but got {1} or more."), + Expected_0_type_arguments_but_got_1: diag(2558, ts.DiagnosticCategory.Error, "Expected_0_type_arguments_but_got_1_2558", "Expected {0} type arguments, but got {1}."), + Type_0_has_no_properties_in_common_with_type_1: diag(2559, ts.DiagnosticCategory.Error, "Type_0_has_no_properties_in_common_with_type_1_2559", "Type '{0}' has no properties in common with type '{1}'."), + Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it: diag(2560, ts.DiagnosticCategory.Error, "Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it_2560", "Value of type '{0}' has no properties in common with type '{1}'. Did you mean to call it?"), + Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_write_2: diag(2561, ts.DiagnosticCategory.Error, "Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_writ_2561", "Object literal may only specify known properties, but '{0}' does not exist in type '{1}'. Did you mean to write '{2}'?"), + Base_class_expressions_cannot_reference_class_type_parameters: diag(2562, ts.DiagnosticCategory.Error, "Base_class_expressions_cannot_reference_class_type_parameters_2562", "Base class expressions cannot reference class type parameters."), + The_containing_function_or_module_body_is_too_large_for_control_flow_analysis: diag(2563, ts.DiagnosticCategory.Error, "The_containing_function_or_module_body_is_too_large_for_control_flow_analysis_2563", "The containing function or module body is too large for control flow analysis."), + Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor: diag(2564, ts.DiagnosticCategory.Error, "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor_2564", "Property '{0}' has no initializer and is not definitely assigned in the constructor."), + Property_0_is_used_before_being_assigned: diag(2565, ts.DiagnosticCategory.Error, "Property_0_is_used_before_being_assigned_2565", "Property '{0}' is used before being assigned."), + A_rest_element_cannot_have_a_property_name: diag(2566, ts.DiagnosticCategory.Error, "A_rest_element_cannot_have_a_property_name_2566", "A rest element cannot have a property name."), + Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations: diag(2567, ts.DiagnosticCategory.Error, "Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations_2567", "Enum declarations can only merge with namespace or other enum declarations."), + Type_0_is_not_an_array_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators: diag(2568, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators_2568", "Type '{0}' is not an array type. Use compiler option '--downlevelIteration' to allow iterating of iterators."), + Type_0_is_not_an_array_type_or_a_string_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators: diag(2569, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_a_string_type_Use_compiler_option_downlevelIteration_to_allow_iterati_2569", "Type '{0}' is not an array type or a string type. Use compiler option '--downlevelIteration' to allow iterating of iterators."), + Property_0_does_not_exist_on_type_1_Did_you_forget_to_use_await: diag(2570, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_Did_you_forget_to_use_await_2570", "Property '{0}' does not exist on type '{1}'. Did you forget to use 'await'?"), + Object_is_of_type_unknown: diag(2571, ts.DiagnosticCategory.Error, "Object_is_of_type_unknown_2571", "Object is of type 'unknown'."), + Rest_signatures_are_incompatible: diag(2572, ts.DiagnosticCategory.Error, "Rest_signatures_are_incompatible_2572", "Rest signatures are incompatible."), + Property_0_is_incompatible_with_rest_element_type: diag(2573, ts.DiagnosticCategory.Error, "Property_0_is_incompatible_with_rest_element_type_2573", "Property '{0}' is incompatible with rest element type."), + A_rest_element_type_must_be_an_array_type: diag(2574, ts.DiagnosticCategory.Error, "A_rest_element_type_must_be_an_array_type_2574", "A rest element type must be an array type."), + No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments: diag(2575, ts.DiagnosticCategory.Error, "No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments_2575", "No overload expects {0} arguments, but overloads do exist that expect either {1} or {2} arguments."), + Property_0_is_a_static_member_of_type_1: diag(2576, ts.DiagnosticCategory.Error, "Property_0_is_a_static_member_of_type_1_2576", "Property '{0}' is a static member of type '{1}'"), + Return_type_annotation_circularly_references_itself: diag(2577, ts.DiagnosticCategory.Error, "Return_type_annotation_circularly_references_itself_2577", "Return type annotation circularly references itself."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_and_then_add_node_to_the_types_field_in_your_tsconfig: diag(2580, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_and_th_2580", "Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i @types/node` and then add `node` to the types field in your tsconfig."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_and_then_add_jquery_to_the_types_field_in_your_tsconfig: diag(2581, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_an_2581", "Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i @types/jquery` and then add `jquery` to the types field in your tsconfig."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha_and_then_add_jest_or_mocha_to_the_types_field_in_your_tsconfig: diag(2582, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashje_2582", "Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha` and then add `jest` or `mocha` to the types field in your tsconfig."), + Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later: diag(2583, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2583", "Cannot find name '{0}'. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later."), + Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom: diag(2584, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2584", "Cannot find name '{0}'. Do you need to change your target library? Try changing the `lib` compiler option to include 'dom'."), + _0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later: diag(2585, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_2585", "'{0}' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later."), + Enum_type_0_circularly_references_itself: diag(2586, ts.DiagnosticCategory.Error, "Enum_type_0_circularly_references_itself_2586", "Enum type '{0}' circularly references itself."), + JSDoc_type_0_circularly_references_itself: diag(2587, ts.DiagnosticCategory.Error, "JSDoc_type_0_circularly_references_itself_2587", "JSDoc type '{0}' circularly references itself."), + Cannot_assign_to_0_because_it_is_a_constant: diag(2588, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_a_constant_2588", "Cannot assign to '{0}' because it is a constant."), + JSX_element_attributes_type_0_may_not_be_a_union_type: diag(2600, ts.DiagnosticCategory.Error, "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", "JSX element attributes type '{0}' may not be a union type."), + The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: diag(2601, ts.DiagnosticCategory.Error, "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", "The return type of a JSX element constructor must return an object type."), + JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: diag(2602, ts.DiagnosticCategory.Error, "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist."), + Property_0_in_type_1_is_not_assignable_to_type_2: diag(2603, ts.DiagnosticCategory.Error, "Property_0_in_type_1_is_not_assignable_to_type_2_2603", "Property '{0}' in type '{1}' is not assignable to type '{2}'."), + JSX_element_type_0_does_not_have_any_construct_or_call_signatures: diag(2604, ts.DiagnosticCategory.Error, "JSX_element_type_0_does_not_have_any_construct_or_call_signatures_2604", "JSX element type '{0}' does not have any construct or call signatures."), + JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements: diag(2605, ts.DiagnosticCategory.Error, "JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements_2605", "JSX element type '{0}' is not a constructor function for JSX elements."), + Property_0_of_JSX_spread_attribute_is_not_assignable_to_target_property: diag(2606, ts.DiagnosticCategory.Error, "Property_0_of_JSX_spread_attribute_is_not_assignable_to_target_property_2606", "Property '{0}' of JSX spread attribute is not assignable to target property."), + JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property: diag(2607, ts.DiagnosticCategory.Error, "JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property_2607", "JSX element class does not support attributes because it does not have a '{0}' property."), + The_global_type_JSX_0_may_not_have_more_than_one_property: diag(2608, ts.DiagnosticCategory.Error, "The_global_type_JSX_0_may_not_have_more_than_one_property_2608", "The global type 'JSX.{0}' may not have more than one property."), + JSX_spread_child_must_be_an_array_type: diag(2609, ts.DiagnosticCategory.Error, "JSX_spread_child_must_be_an_array_type_2609", "JSX spread child must be an array type."), + Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity: diag(2649, ts.DiagnosticCategory.Error, "Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity_2649", "Cannot augment module '{0}' with value exports because it resolves to a non-module entity."), + A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums: diag(2651, ts.DiagnosticCategory.Error, "A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_memb_2651", "A member initializer in a enum declaration cannot reference members declared after it, including members defined in other enums."), + Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead: diag(2652, ts.DiagnosticCategory.Error, "Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_d_2652", "Merged declaration '{0}' cannot include a default export declaration. Consider adding a separate 'export default {0}' declaration instead."), + Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1: diag(2653, ts.DiagnosticCategory.Error, "Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1_2653", "Non-abstract class expression does not implement inherited abstract member '{0}' from class '{1}'."), + Exported_external_package_typings_file_cannot_contain_tripleslash_references_Please_contact_the_package_author_to_update_the_package_definition: diag(2654, ts.DiagnosticCategory.Error, "Exported_external_package_typings_file_cannot_contain_tripleslash_references_Please_contact_the_pack_2654", "Exported external package typings file cannot contain tripleslash references. Please contact the package author to update the package definition."), + Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_the_package_definition: diag(2656, ts.DiagnosticCategory.Error, "Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_2656", "Exported external package typings file '{0}' is not a module. Please contact the package author to update the package definition."), + JSX_expressions_must_have_one_parent_element: diag(2657, ts.DiagnosticCategory.Error, "JSX_expressions_must_have_one_parent_element_2657", "JSX expressions must have one parent element."), + Type_0_provides_no_match_for_the_signature_1: diag(2658, ts.DiagnosticCategory.Error, "Type_0_provides_no_match_for_the_signature_1_2658", "Type '{0}' provides no match for the signature '{1}'."), + super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_higher: diag(2659, ts.DiagnosticCategory.Error, "super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_highe_2659", "'super' is only allowed in members of object literal expressions when option 'target' is 'ES2015' or higher."), + super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions: diag(2660, ts.DiagnosticCategory.Error, "super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions_2660", "'super' can only be referenced in members of derived classes or object literal expressions."), + Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module: diag(2661, ts.DiagnosticCategory.Error, "Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module_2661", "Cannot export '{0}'. Only local declarations can be exported from a module."), + Cannot_find_name_0_Did_you_mean_the_static_member_1_0: diag(2662, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Did_you_mean_the_static_member_1_0_2662", "Cannot find name '{0}'. Did you mean the static member '{1}.{0}'?"), + Cannot_find_name_0_Did_you_mean_the_instance_member_this_0: diag(2663, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Did_you_mean_the_instance_member_this_0_2663", "Cannot find name '{0}'. Did you mean the instance member 'this.{0}'?"), + Invalid_module_name_in_augmentation_module_0_cannot_be_found: diag(2664, ts.DiagnosticCategory.Error, "Invalid_module_name_in_augmentation_module_0_cannot_be_found_2664", "Invalid module name in augmentation, module '{0}' cannot be found."), + Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented: diag(2665, ts.DiagnosticCategory.Error, "Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augm_2665", "Invalid module name in augmentation. Module '{0}' resolves to an untyped module at '{1}', which cannot be augmented."), + Exports_and_export_assignments_are_not_permitted_in_module_augmentations: diag(2666, ts.DiagnosticCategory.Error, "Exports_and_export_assignments_are_not_permitted_in_module_augmentations_2666", "Exports and export assignments are not permitted in module augmentations."), + Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_module: diag(2667, ts.DiagnosticCategory.Error, "Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_mod_2667", "Imports are not permitted in module augmentations. Consider moving them to the enclosing external module."), + export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always_visible: diag(2668, ts.DiagnosticCategory.Error, "export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always__2668", "'export' modifier cannot be applied to ambient modules and module augmentations since they are always visible."), + Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_declarations: diag(2669, ts.DiagnosticCategory.Error, "Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_2669", "Augmentations for the global scope can only be directly nested in external modules or ambient module declarations."), + Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambient_context: diag(2670, ts.DiagnosticCategory.Error, "Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambien_2670", "Augmentations for the global scope should have 'declare' modifier unless they appear in already ambient context."), + Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity: diag(2671, ts.DiagnosticCategory.Error, "Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity_2671", "Cannot augment module '{0}' because it resolves to a non-module entity."), + Cannot_assign_a_0_constructor_type_to_a_1_constructor_type: diag(2672, ts.DiagnosticCategory.Error, "Cannot_assign_a_0_constructor_type_to_a_1_constructor_type_2672", "Cannot assign a '{0}' constructor type to a '{1}' constructor type."), + Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration: diag(2673, ts.DiagnosticCategory.Error, "Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration_2673", "Constructor of class '{0}' is private and only accessible within the class declaration."), + Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration: diag(2674, ts.DiagnosticCategory.Error, "Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration_2674", "Constructor of class '{0}' is protected and only accessible within the class declaration."), + Cannot_extend_a_class_0_Class_constructor_is_marked_as_private: diag(2675, ts.DiagnosticCategory.Error, "Cannot_extend_a_class_0_Class_constructor_is_marked_as_private_2675", "Cannot extend a class '{0}'. Class constructor is marked as private."), + Accessors_must_both_be_abstract_or_non_abstract: diag(2676, ts.DiagnosticCategory.Error, "Accessors_must_both_be_abstract_or_non_abstract_2676", "Accessors must both be abstract or non-abstract."), + A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type: diag(2677, ts.DiagnosticCategory.Error, "A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type_2677", "A type predicate's type must be assignable to its parameter's type."), + Type_0_is_not_comparable_to_type_1: diag(2678, ts.DiagnosticCategory.Error, "Type_0_is_not_comparable_to_type_1_2678", "Type '{0}' is not comparable to type '{1}'."), + A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void: diag(2679, ts.DiagnosticCategory.Error, "A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void_2679", "A function that is called with the 'new' keyword cannot have a 'this' type that is 'void'."), + A_0_parameter_must_be_the_first_parameter: diag(2680, ts.DiagnosticCategory.Error, "A_0_parameter_must_be_the_first_parameter_2680", "A '{0}' parameter must be the first parameter."), + A_constructor_cannot_have_a_this_parameter: diag(2681, ts.DiagnosticCategory.Error, "A_constructor_cannot_have_a_this_parameter_2681", "A constructor cannot have a 'this' parameter."), + get_and_set_accessor_must_have_the_same_this_type: diag(2682, ts.DiagnosticCategory.Error, "get_and_set_accessor_must_have_the_same_this_type_2682", "'get' and 'set' accessor must have the same 'this' type."), + this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation: diag(2683, ts.DiagnosticCategory.Error, "this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_2683", "'this' implicitly has type 'any' because it does not have a type annotation."), + The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1: diag(2684, ts.DiagnosticCategory.Error, "The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1_2684", "The 'this' context of type '{0}' is not assignable to method's 'this' of type '{1}'."), + The_this_types_of_each_signature_are_incompatible: diag(2685, ts.DiagnosticCategory.Error, "The_this_types_of_each_signature_are_incompatible_2685", "The 'this' types of each signature are incompatible."), + _0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead: diag(2686, ts.DiagnosticCategory.Error, "_0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead_2686", "'{0}' refers to a UMD global, but the current file is a module. Consider adding an import instead."), + All_declarations_of_0_must_have_identical_modifiers: diag(2687, ts.DiagnosticCategory.Error, "All_declarations_of_0_must_have_identical_modifiers_2687", "All declarations of '{0}' must have identical modifiers."), + Cannot_find_type_definition_file_for_0: diag(2688, ts.DiagnosticCategory.Error, "Cannot_find_type_definition_file_for_0_2688", "Cannot find type definition file for '{0}'."), + Cannot_extend_an_interface_0_Did_you_mean_implements: diag(2689, ts.DiagnosticCategory.Error, "Cannot_extend_an_interface_0_Did_you_mean_implements_2689", "Cannot extend an interface '{0}'. Did you mean 'implements'?"), + An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead: diag(2691, ts.DiagnosticCategory.Error, "An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead_2691", "An import path cannot end with a '{0}' extension. Consider importing '{1}' instead."), + _0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible: diag(2692, ts.DiagnosticCategory.Error, "_0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible_2692", "'{0}' is a primitive, but '{1}' is a wrapper object. Prefer using '{0}' when possible."), + _0_only_refers_to_a_type_but_is_being_used_as_a_value_here: diag(2693, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_2693", "'{0}' only refers to a type, but is being used as a value here."), + Namespace_0_has_no_exported_member_1: diag(2694, ts.DiagnosticCategory.Error, "Namespace_0_has_no_exported_member_1_2694", "Namespace '{0}' has no exported member '{1}'."), + Left_side_of_comma_operator_is_unused_and_has_no_side_effects: diag(2695, ts.DiagnosticCategory.Error, "Left_side_of_comma_operator_is_unused_and_has_no_side_effects_2695", "Left side of comma operator is unused and has no side effects.", /*reportsUnnecessary*/ true), + The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead: diag(2696, ts.DiagnosticCategory.Error, "The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead_2696", "The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead?"), + An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option: diag(2697, ts.DiagnosticCategory.Error, "An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_in_2697", "An async function or method must return a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your `--lib` option."), + Spread_types_may_only_be_created_from_object_types: diag(2698, ts.DiagnosticCategory.Error, "Spread_types_may_only_be_created_from_object_types_2698", "Spread types may only be created from object types."), + Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1: diag(2699, ts.DiagnosticCategory.Error, "Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1_2699", "Static property '{0}' conflicts with built-in property 'Function.{0}' of constructor function '{1}'."), + Rest_types_may_only_be_created_from_object_types: diag(2700, ts.DiagnosticCategory.Error, "Rest_types_may_only_be_created_from_object_types_2700", "Rest types may only be created from object types."), + The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access: diag(2701, ts.DiagnosticCategory.Error, "The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access_2701", "The target of an object rest assignment must be a variable or a property access."), + _0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here: diag(2702, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here_2702", "'{0}' only refers to a type, but is being used as a namespace here."), + The_operand_of_a_delete_operator_must_be_a_property_reference: diag(2703, ts.DiagnosticCategory.Error, "The_operand_of_a_delete_operator_must_be_a_property_reference_2703", "The operand of a delete operator must be a property reference."), + The_operand_of_a_delete_operator_cannot_be_a_read_only_property: diag(2704, ts.DiagnosticCategory.Error, "The_operand_of_a_delete_operator_cannot_be_a_read_only_property_2704", "The operand of a delete operator cannot be a read-only property."), + An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option: diag(2705, ts.DiagnosticCategory.Error, "An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_de_2705", "An async function or method in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your `--lib` option."), + Required_type_parameters_may_not_follow_optional_type_parameters: diag(2706, ts.DiagnosticCategory.Error, "Required_type_parameters_may_not_follow_optional_type_parameters_2706", "Required type parameters may not follow optional type parameters."), + Generic_type_0_requires_between_1_and_2_type_arguments: diag(2707, ts.DiagnosticCategory.Error, "Generic_type_0_requires_between_1_and_2_type_arguments_2707", "Generic type '{0}' requires between {1} and {2} type arguments."), + Cannot_use_namespace_0_as_a_value: diag(2708, ts.DiagnosticCategory.Error, "Cannot_use_namespace_0_as_a_value_2708", "Cannot use namespace '{0}' as a value."), + Cannot_use_namespace_0_as_a_type: diag(2709, ts.DiagnosticCategory.Error, "Cannot_use_namespace_0_as_a_type_2709", "Cannot use namespace '{0}' as a type."), + _0_are_specified_twice_The_attribute_named_0_will_be_overwritten: diag(2710, ts.DiagnosticCategory.Error, "_0_are_specified_twice_The_attribute_named_0_will_be_overwritten_2710", "'{0}' are specified twice. The attribute named '{0}' will be overwritten."), + A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option: diag(2711, ts.DiagnosticCategory.Error, "A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES20_2711", "A dynamic import call returns a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your `--lib` option."), + A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option: diag(2712, ts.DiagnosticCategory.Error, "A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declarat_2712", "A dynamic import call in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your `--lib` option."), + Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_property_1_in_0_with_0_1: diag(2713, ts.DiagnosticCategory.Error, "Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_p_2713", "Cannot access '{0}.{1}' because '{0}' is a type, but not a namespace. Did you mean to retrieve the type of the property '{1}' in '{0}' with '{0}[\"{1}\"]'?"), + The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context: diag(2714, ts.DiagnosticCategory.Error, "The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context_2714", "The expression of an export assignment must be an identifier or qualified name in an ambient context."), + Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor: diag(2715, ts.DiagnosticCategory.Error, "Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor_2715", "Abstract property '{0}' in class '{1}' cannot be accessed in the constructor."), + Type_parameter_0_has_a_circular_default: diag(2716, ts.DiagnosticCategory.Error, "Type_parameter_0_has_a_circular_default_2716", "Type parameter '{0}' has a circular default."), + Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_type_2: diag(2717, ts.DiagnosticCategory.Error, "Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_t_2717", "Subsequent property declarations must have the same type. Property '{0}' must be of type '{1}', but here has type '{2}'."), + Duplicate_declaration_0: diag(2718, ts.DiagnosticCategory.Error, "Duplicate_declaration_0_2718", "Duplicate declaration '{0}'."), + Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated: diag(2719, ts.DiagnosticCategory.Error, "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_2719", "Type '{0}' is not assignable to type '{1}'. Two different types with this name exist, but they are unrelated."), + Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass: diag(2720, ts.DiagnosticCategory.Error, "Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclas_2720", "Class '{0}' incorrectly implements class '{1}'. Did you mean to extend '{1}' and inherit its members as a subclass?"), + Cannot_invoke_an_object_which_is_possibly_null: diag(2721, ts.DiagnosticCategory.Error, "Cannot_invoke_an_object_which_is_possibly_null_2721", "Cannot invoke an object which is possibly 'null'."), + Cannot_invoke_an_object_which_is_possibly_undefined: diag(2722, ts.DiagnosticCategory.Error, "Cannot_invoke_an_object_which_is_possibly_undefined_2722", "Cannot invoke an object which is possibly 'undefined'."), + Cannot_invoke_an_object_which_is_possibly_null_or_undefined: diag(2723, ts.DiagnosticCategory.Error, "Cannot_invoke_an_object_which_is_possibly_null_or_undefined_2723", "Cannot invoke an object which is possibly 'null' or 'undefined'."), + Module_0_has_no_exported_member_1_Did_you_mean_2: diag(2724, ts.DiagnosticCategory.Error, "Module_0_has_no_exported_member_1_Did_you_mean_2_2724", "Module '{0}' has no exported member '{1}'. Did you mean '{2}'?"), + Class_name_cannot_be_Object_when_targeting_ES5_with_module_0: diag(2725, ts.DiagnosticCategory.Error, "Class_name_cannot_be_Object_when_targeting_ES5_with_module_0_2725", "Class name cannot be 'Object' when targeting ES5 with module {0}."), + Cannot_find_lib_definition_for_0: diag(2726, ts.DiagnosticCategory.Error, "Cannot_find_lib_definition_for_0_2726", "Cannot find lib definition for '{0}'."), + Cannot_find_lib_definition_for_0_Did_you_mean_1: diag(2727, ts.DiagnosticCategory.Error, "Cannot_find_lib_definition_for_0_Did_you_mean_1_2727", "Cannot find lib definition for '{0}'. Did you mean '{1}'?"), + _0_is_declared_here: diag(2728, ts.DiagnosticCategory.Message, "_0_is_declared_here_2728", "'{0}' is declared here."), + Property_0_is_used_before_its_initialization: diag(2729, ts.DiagnosticCategory.Error, "Property_0_is_used_before_its_initialization_2729", "Property '{0}' is used before its initialization."), + An_arrow_function_cannot_have_a_this_parameter: diag(2730, ts.DiagnosticCategory.Error, "An_arrow_function_cannot_have_a_this_parameter_2730", "An arrow function cannot have a 'this' parameter."), + Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_in_String: diag(2731, ts.DiagnosticCategory.Error, "Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_i_2731", "Implicit conversion of a 'symbol' to a 'string' will fail at runtime. Consider wrapping this expression in 'String(...)'."), + Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension: diag(2732, ts.DiagnosticCategory.Error, "Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension_2732", "Cannot find module '{0}'. Consider using '--resolveJsonModule' to import module with '.json' extension"), + It_is_highly_likely_that_you_are_missing_a_semicolon: diag(2734, ts.DiagnosticCategory.Error, "It_is_highly_likely_that_you_are_missing_a_semicolon_2734", "It is highly likely that you are missing a semicolon."), + Did_you_mean_for_0_to_be_constrained_to_type_new_args_Colon_any_1: diag(2735, ts.DiagnosticCategory.Error, "Did_you_mean_for_0_to_be_constrained_to_type_new_args_Colon_any_1_2735", "Did you mean for '{0}' to be constrained to type 'new (...args: any[]) => {1}'?"), + Operator_0_cannot_be_applied_to_type_1: diag(2736, ts.DiagnosticCategory.Error, "Operator_0_cannot_be_applied_to_type_1_2736", "Operator '{0}' cannot be applied to type '{1}'."), + BigInt_literals_are_not_available_when_targeting_lower_than_ESNext: diag(2737, ts.DiagnosticCategory.Error, "BigInt_literals_are_not_available_when_targeting_lower_than_ESNext_2737", "BigInt literals are not available when targeting lower than ESNext."), + An_outer_value_of_this_is_shadowed_by_this_container: diag(2738, ts.DiagnosticCategory.Message, "An_outer_value_of_this_is_shadowed_by_this_container_2738", "An outer value of 'this' is shadowed by this container."), + Type_0_is_missing_the_following_properties_from_type_1_Colon_2: diag(2739, ts.DiagnosticCategory.Error, "Type_0_is_missing_the_following_properties_from_type_1_Colon_2_2739", "Type '{0}' is missing the following properties from type '{1}': {2}"), + Type_0_is_missing_the_following_properties_from_type_1_Colon_2_and_3_more: diag(2740, ts.DiagnosticCategory.Error, "Type_0_is_missing_the_following_properties_from_type_1_Colon_2_and_3_more_2740", "Type '{0}' is missing the following properties from type '{1}': {2}, and {3} more."), + Property_0_is_missing_in_type_1_but_required_in_type_2: diag(2741, ts.DiagnosticCategory.Error, "Property_0_is_missing_in_type_1_but_required_in_type_2_2741", "Property '{0}' is missing in type '{1}' but required in type '{2}'."), + The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_annotation_is_necessary: diag(2742, ts.DiagnosticCategory.Error, "The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_a_2742", "The inferred type of '{0}' cannot be named without a reference to '{1}'. This is likely not portable. A type annotation is necessary."), + Import_declaration_0_is_using_private_name_1: diag(4000, ts.DiagnosticCategory.Error, "Import_declaration_0_is_using_private_name_1_4000", "Import declaration '{0}' is using private name '{1}'."), + Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: diag(4002, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", "Type parameter '{0}' of exported class has or is using private name '{1}'."), + Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: diag(4004, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", "Type parameter '{0}' of exported interface has or is using private name '{1}'."), + Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1: diag(4006, ts.DiagnosticCategory.Error, "Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4006", "Type parameter '{0}' of constructor signature from exported interface has or is using private name '{1}'."), + Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1: diag(4008, ts.DiagnosticCategory.Error, "Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4008", "Type parameter '{0}' of call signature from exported interface has or is using private name '{1}'."), + Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1: diag(4010, ts.DiagnosticCategory.Error, "Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4010", "Type parameter '{0}' of public static method from exported class has or is using private name '{1}'."), + Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1: diag(4012, ts.DiagnosticCategory.Error, "Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4012", "Type parameter '{0}' of public method from exported class has or is using private name '{1}'."), + Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1: diag(4014, ts.DiagnosticCategory.Error, "Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4014", "Type parameter '{0}' of method from exported interface has or is using private name '{1}'."), + Type_parameter_0_of_exported_function_has_or_is_using_private_name_1: diag(4016, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_function_has_or_is_using_private_name_1_4016", "Type parameter '{0}' of exported function has or is using private name '{1}'."), + Implements_clause_of_exported_class_0_has_or_is_using_private_name_1: diag(4019, ts.DiagnosticCategory.Error, "Implements_clause_of_exported_class_0_has_or_is_using_private_name_1_4019", "Implements clause of exported class '{0}' has or is using private name '{1}'."), + extends_clause_of_exported_class_0_has_or_is_using_private_name_1: diag(4020, ts.DiagnosticCategory.Error, "extends_clause_of_exported_class_0_has_or_is_using_private_name_1_4020", "'extends' clause of exported class '{0}' has or is using private name '{1}'."), + extends_clause_of_exported_interface_0_has_or_is_using_private_name_1: diag(4022, ts.DiagnosticCategory.Error, "extends_clause_of_exported_interface_0_has_or_is_using_private_name_1_4022", "'extends' clause of exported interface '{0}' has or is using private name '{1}'."), + Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4023, ts.DiagnosticCategory.Error, "Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4023", "Exported variable '{0}' has or is using name '{1}' from external module {2} but cannot be named."), + Exported_variable_0_has_or_is_using_name_1_from_private_module_2: diag(4024, ts.DiagnosticCategory.Error, "Exported_variable_0_has_or_is_using_name_1_from_private_module_2_4024", "Exported variable '{0}' has or is using name '{1}' from private module '{2}'."), + Exported_variable_0_has_or_is_using_private_name_1: diag(4025, ts.DiagnosticCategory.Error, "Exported_variable_0_has_or_is_using_private_name_1_4025", "Exported variable '{0}' has or is using private name '{1}'."), + Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4026, ts.DiagnosticCategory.Error, "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot__4026", "Public static property '{0}' of exported class has or is using name '{1}' from external module {2} but cannot be named."), + Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4027, ts.DiagnosticCategory.Error, "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4027", "Public static property '{0}' of exported class has or is using name '{1}' from private module '{2}'."), + Public_static_property_0_of_exported_class_has_or_is_using_private_name_1: diag(4028, ts.DiagnosticCategory.Error, "Public_static_property_0_of_exported_class_has_or_is_using_private_name_1_4028", "Public static property '{0}' of exported class has or is using private name '{1}'."), + Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4029, ts.DiagnosticCategory.Error, "Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_name_4029", "Public property '{0}' of exported class has or is using name '{1}' from external module {2} but cannot be named."), + Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4030, ts.DiagnosticCategory.Error, "Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4030", "Public property '{0}' of exported class has or is using name '{1}' from private module '{2}'."), + Public_property_0_of_exported_class_has_or_is_using_private_name_1: diag(4031, ts.DiagnosticCategory.Error, "Public_property_0_of_exported_class_has_or_is_using_private_name_1_4031", "Public property '{0}' of exported class has or is using private name '{1}'."), + Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4032, ts.DiagnosticCategory.Error, "Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4032", "Property '{0}' of exported interface has or is using name '{1}' from private module '{2}'."), + Property_0_of_exported_interface_has_or_is_using_private_name_1: diag(4033, ts.DiagnosticCategory.Error, "Property_0_of_exported_interface_has_or_is_using_private_name_1_4033", "Property '{0}' of exported interface has or is using private name '{1}'."), + Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4034, ts.DiagnosticCategory.Error, "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_name_1_from_private_mod_4034", "Parameter type of public static setter '{0}' from exported class has or is using name '{1}' from private module '{2}'."), + Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1: diag(4035, ts.DiagnosticCategory.Error, "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1_4035", "Parameter type of public static setter '{0}' from exported class has or is using private name '{1}'."), + Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4036, ts.DiagnosticCategory.Error, "Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2_4036", "Parameter type of public setter '{0}' from exported class has or is using name '{1}' from private module '{2}'."), + Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_private_name_1: diag(4037, ts.DiagnosticCategory.Error, "Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_private_name_1_4037", "Parameter type of public setter '{0}' from exported class has or is using private name '{1}'."), + Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4038, ts.DiagnosticCategory.Error, "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_external_modul_4038", "Return type of public static getter '{0}' from exported class has or is using name '{1}' from external module {2} but cannot be named."), + Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4039, ts.DiagnosticCategory.Error, "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_4039", "Return type of public static getter '{0}' from exported class has or is using name '{1}' from private module '{2}'."), + Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_private_name_1: diag(4040, ts.DiagnosticCategory.Error, "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_private_name_1_4040", "Return type of public static getter '{0}' from exported class has or is using private name '{1}'."), + Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4041, ts.DiagnosticCategory.Error, "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_4041", "Return type of public getter '{0}' from exported class has or is using name '{1}' from external module {2} but cannot be named."), + Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4042, ts.DiagnosticCategory.Error, "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2_4042", "Return type of public getter '{0}' from exported class has or is using name '{1}' from private module '{2}'."), + Return_type_of_public_getter_0_from_exported_class_has_or_is_using_private_name_1: diag(4043, ts.DiagnosticCategory.Error, "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_private_name_1_4043", "Return type of public getter '{0}' from exported class has or is using private name '{1}'."), + Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1: diag(4044, ts.DiagnosticCategory.Error, "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_mod_4044", "Return type of constructor signature from exported interface has or is using name '{0}' from private module '{1}'."), + Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0: diag(4045, ts.DiagnosticCategory.Error, "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0_4045", "Return type of constructor signature from exported interface has or is using private name '{0}'."), + Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1: diag(4046, ts.DiagnosticCategory.Error, "Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4046", "Return type of call signature from exported interface has or is using name '{0}' from private module '{1}'."), + Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0: diag(4047, ts.DiagnosticCategory.Error, "Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0_4047", "Return type of call signature from exported interface has or is using private name '{0}'."), + Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1: diag(4048, ts.DiagnosticCategory.Error, "Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4048", "Return type of index signature from exported interface has or is using name '{0}' from private module '{1}'."), + Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0: diag(4049, ts.DiagnosticCategory.Error, "Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0_4049", "Return type of index signature from exported interface has or is using private name '{0}'."), + Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: diag(4050, ts.DiagnosticCategory.Error, "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module__4050", "Return type of public static method from exported class has or is using name '{0}' from external module {1} but cannot be named."), + Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1: diag(4051, ts.DiagnosticCategory.Error, "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4051", "Return type of public static method from exported class has or is using name '{0}' from private module '{1}'."), + Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0: diag(4052, ts.DiagnosticCategory.Error, "Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0_4052", "Return type of public static method from exported class has or is using private name '{0}'."), + Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: diag(4053, ts.DiagnosticCategory.Error, "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_c_4053", "Return type of public method from exported class has or is using name '{0}' from external module {1} but cannot be named."), + Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1: diag(4054, ts.DiagnosticCategory.Error, "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4054", "Return type of public method from exported class has or is using name '{0}' from private module '{1}'."), + Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0: diag(4055, ts.DiagnosticCategory.Error, "Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0_4055", "Return type of public method from exported class has or is using private name '{0}'."), + Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1: diag(4056, ts.DiagnosticCategory.Error, "Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4056", "Return type of method from exported interface has or is using name '{0}' from private module '{1}'."), + Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0: diag(4057, ts.DiagnosticCategory.Error, "Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0_4057", "Return type of method from exported interface has or is using private name '{0}'."), + Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: diag(4058, ts.DiagnosticCategory.Error, "Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named_4058", "Return type of exported function has or is using name '{0}' from external module {1} but cannot be named."), + Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1: diag(4059, ts.DiagnosticCategory.Error, "Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1_4059", "Return type of exported function has or is using name '{0}' from private module '{1}'."), + Return_type_of_exported_function_has_or_is_using_private_name_0: diag(4060, ts.DiagnosticCategory.Error, "Return_type_of_exported_function_has_or_is_using_private_name_0_4060", "Return type of exported function has or is using private name '{0}'."), + Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4061, ts.DiagnosticCategory.Error, "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_can_4061", "Parameter '{0}' of constructor from exported class has or is using name '{1}' from external module {2} but cannot be named."), + Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4062, ts.DiagnosticCategory.Error, "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2_4062", "Parameter '{0}' of constructor from exported class has or is using name '{1}' from private module '{2}'."), + Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1: diag(4063, ts.DiagnosticCategory.Error, "Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1_4063", "Parameter '{0}' of constructor from exported class has or is using private name '{1}'."), + Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4064, ts.DiagnosticCategory.Error, "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_mod_4064", "Parameter '{0}' of constructor signature from exported interface has or is using name '{1}' from private module '{2}'."), + Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1: diag(4065, ts.DiagnosticCategory.Error, "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4065", "Parameter '{0}' of constructor signature from exported interface has or is using private name '{1}'."), + Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4066, ts.DiagnosticCategory.Error, "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4066", "Parameter '{0}' of call signature from exported interface has or is using name '{1}' from private module '{2}'."), + Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1: diag(4067, ts.DiagnosticCategory.Error, "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4067", "Parameter '{0}' of call signature from exported interface has or is using private name '{1}'."), + Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4068, ts.DiagnosticCategory.Error, "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module__4068", "Parameter '{0}' of public static method from exported class has or is using name '{1}' from external module {2} but cannot be named."), + Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4069, ts.DiagnosticCategory.Error, "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4069", "Parameter '{0}' of public static method from exported class has or is using name '{1}' from private module '{2}'."), + Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1: diag(4070, ts.DiagnosticCategory.Error, "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4070", "Parameter '{0}' of public static method from exported class has or is using private name '{1}'."), + Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4071, ts.DiagnosticCategory.Error, "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_c_4071", "Parameter '{0}' of public method from exported class has or is using name '{1}' from external module {2} but cannot be named."), + Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4072, ts.DiagnosticCategory.Error, "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4072", "Parameter '{0}' of public method from exported class has or is using name '{1}' from private module '{2}'."), + Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1: diag(4073, ts.DiagnosticCategory.Error, "Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4073", "Parameter '{0}' of public method from exported class has or is using private name '{1}'."), + Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4074, ts.DiagnosticCategory.Error, "Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4074", "Parameter '{0}' of method from exported interface has or is using name '{1}' from private module '{2}'."), + Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1: diag(4075, ts.DiagnosticCategory.Error, "Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4075", "Parameter '{0}' of method from exported interface has or is using private name '{1}'."), + Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4076, ts.DiagnosticCategory.Error, "Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4076", "Parameter '{0}' of exported function has or is using name '{1}' from external module {2} but cannot be named."), + Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2: diag(4077, ts.DiagnosticCategory.Error, "Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2_4077", "Parameter '{0}' of exported function has or is using name '{1}' from private module '{2}'."), + Parameter_0_of_exported_function_has_or_is_using_private_name_1: diag(4078, ts.DiagnosticCategory.Error, "Parameter_0_of_exported_function_has_or_is_using_private_name_1_4078", "Parameter '{0}' of exported function has or is using private name '{1}'."), + Exported_type_alias_0_has_or_is_using_private_name_1: diag(4081, ts.DiagnosticCategory.Error, "Exported_type_alias_0_has_or_is_using_private_name_1_4081", "Exported type alias '{0}' has or is using private name '{1}'."), + Default_export_of_the_module_has_or_is_using_private_name_0: diag(4082, ts.DiagnosticCategory.Error, "Default_export_of_the_module_has_or_is_using_private_name_0_4082", "Default export of the module has or is using private name '{0}'."), + Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1: diag(4083, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1_4083", "Type parameter '{0}' of exported type alias has or is using private name '{1}'."), + Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict: diag(4090, ts.DiagnosticCategory.Error, "Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_librar_4090", "Conflicting definitions for '{0}' found at '{1}' and '{2}'. Consider installing a specific version of this library to resolve the conflict."), + Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4091, ts.DiagnosticCategory.Error, "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4091", "Parameter '{0}' of index signature from exported interface has or is using name '{1}' from private module '{2}'."), + Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1: diag(4092, ts.DiagnosticCategory.Error, "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1_4092", "Parameter '{0}' of index signature from exported interface has or is using private name '{1}'."), + Property_0_of_exported_class_expression_may_not_be_private_or_protected: diag(4094, ts.DiagnosticCategory.Error, "Property_0_of_exported_class_expression_may_not_be_private_or_protected_4094", "Property '{0}' of exported class expression may not be private or protected."), + Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4095, ts.DiagnosticCategory.Error, "Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_4095", "Public static method '{0}' of exported class has or is using name '{1}' from external module {2} but cannot be named."), + Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4096, ts.DiagnosticCategory.Error, "Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4096", "Public static method '{0}' of exported class has or is using name '{1}' from private module '{2}'."), + Public_static_method_0_of_exported_class_has_or_is_using_private_name_1: diag(4097, ts.DiagnosticCategory.Error, "Public_static_method_0_of_exported_class_has_or_is_using_private_name_1_4097", "Public static method '{0}' of exported class has or is using private name '{1}'."), + Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4098, ts.DiagnosticCategory.Error, "Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4098", "Public method '{0}' of exported class has or is using name '{1}' from external module {2} but cannot be named."), + Public_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4099, ts.DiagnosticCategory.Error, "Public_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4099", "Public method '{0}' of exported class has or is using name '{1}' from private module '{2}'."), + Public_method_0_of_exported_class_has_or_is_using_private_name_1: diag(4100, ts.DiagnosticCategory.Error, "Public_method_0_of_exported_class_has_or_is_using_private_name_1_4100", "Public method '{0}' of exported class has or is using private name '{1}'."), + Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4101, ts.DiagnosticCategory.Error, "Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4101", "Method '{0}' of exported interface has or is using name '{1}' from private module '{2}'."), + Method_0_of_exported_interface_has_or_is_using_private_name_1: diag(4102, ts.DiagnosticCategory.Error, "Method_0_of_exported_interface_has_or_is_using_private_name_1_4102", "Method '{0}' of exported interface has or is using private name '{1}'."), + The_current_host_does_not_support_the_0_option: diag(5001, ts.DiagnosticCategory.Error, "The_current_host_does_not_support_the_0_option_5001", "The current host does not support the '{0}' option."), + Cannot_find_the_common_subdirectory_path_for_the_input_files: diag(5009, ts.DiagnosticCategory.Error, "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009", "Cannot find the common subdirectory path for the input files."), + File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: diag(5010, ts.DiagnosticCategory.Error, "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010", "File specification cannot end in a recursive directory wildcard ('**'): '{0}'."), + Cannot_read_file_0_Colon_1: diag(5012, ts.DiagnosticCategory.Error, "Cannot_read_file_0_Colon_1_5012", "Cannot read file '{0}': {1}."), + Failed_to_parse_file_0_Colon_1: diag(5014, ts.DiagnosticCategory.Error, "Failed_to_parse_file_0_Colon_1_5014", "Failed to parse file '{0}': {1}."), + Unknown_compiler_option_0: diag(5023, ts.DiagnosticCategory.Error, "Unknown_compiler_option_0_5023", "Unknown compiler option '{0}'."), + Compiler_option_0_requires_a_value_of_type_1: diag(5024, ts.DiagnosticCategory.Error, "Compiler_option_0_requires_a_value_of_type_1_5024", "Compiler option '{0}' requires a value of type {1}."), + Could_not_write_file_0_Colon_1: diag(5033, ts.DiagnosticCategory.Error, "Could_not_write_file_0_Colon_1_5033", "Could not write file '{0}': {1}."), + Option_project_cannot_be_mixed_with_source_files_on_a_command_line: diag(5042, ts.DiagnosticCategory.Error, "Option_project_cannot_be_mixed_with_source_files_on_a_command_line_5042", "Option 'project' cannot be mixed with source files on a command line."), + Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher: diag(5047, ts.DiagnosticCategory.Error, "Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES_5047", "Option 'isolatedModules' can only be used when either option '--module' is provided or option 'target' is 'ES2015' or higher."), + Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided: diag(5051, ts.DiagnosticCategory.Error, "Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided_5051", "Option '{0} can only be used when either option '--inlineSourceMap' or option '--sourceMap' is provided."), + Option_0_cannot_be_specified_without_specifying_option_1: diag(5052, ts.DiagnosticCategory.Error, "Option_0_cannot_be_specified_without_specifying_option_1_5052", "Option '{0}' cannot be specified without specifying option '{1}'."), + Option_0_cannot_be_specified_with_option_1: diag(5053, ts.DiagnosticCategory.Error, "Option_0_cannot_be_specified_with_option_1_5053", "Option '{0}' cannot be specified with option '{1}'."), + A_tsconfig_json_file_is_already_defined_at_Colon_0: diag(5054, ts.DiagnosticCategory.Error, "A_tsconfig_json_file_is_already_defined_at_Colon_0_5054", "A 'tsconfig.json' file is already defined at: '{0}'."), + Cannot_write_file_0_because_it_would_overwrite_input_file: diag(5055, ts.DiagnosticCategory.Error, "Cannot_write_file_0_because_it_would_overwrite_input_file_5055", "Cannot write file '{0}' because it would overwrite input file."), + Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files: diag(5056, ts.DiagnosticCategory.Error, "Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files_5056", "Cannot write file '{0}' because it would be overwritten by multiple input files."), + Cannot_find_a_tsconfig_json_file_at_the_specified_directory_Colon_0: diag(5057, ts.DiagnosticCategory.Error, "Cannot_find_a_tsconfig_json_file_at_the_specified_directory_Colon_0_5057", "Cannot find a tsconfig.json file at the specified directory: '{0}'."), + The_specified_path_does_not_exist_Colon_0: diag(5058, ts.DiagnosticCategory.Error, "The_specified_path_does_not_exist_Colon_0_5058", "The specified path does not exist: '{0}'."), + Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier: diag(5059, ts.DiagnosticCategory.Error, "Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier_5059", "Invalid value for '--reactNamespace'. '{0}' is not a valid identifier."), + Option_paths_cannot_be_used_without_specifying_baseUrl_option: diag(5060, ts.DiagnosticCategory.Error, "Option_paths_cannot_be_used_without_specifying_baseUrl_option_5060", "Option 'paths' cannot be used without specifying '--baseUrl' option."), + Pattern_0_can_have_at_most_one_Asterisk_character: diag(5061, ts.DiagnosticCategory.Error, "Pattern_0_can_have_at_most_one_Asterisk_character_5061", "Pattern '{0}' can have at most one '*' character."), + Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character: diag(5062, ts.DiagnosticCategory.Error, "Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character_5062", "Substitution '{0}' in pattern '{1}' in can have at most one '*' character."), + Substitutions_for_pattern_0_should_be_an_array: diag(5063, ts.DiagnosticCategory.Error, "Substitutions_for_pattern_0_should_be_an_array_5063", "Substitutions for pattern '{0}' should be an array."), + Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2: diag(5064, ts.DiagnosticCategory.Error, "Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2_5064", "Substitution '{0}' for pattern '{1}' has incorrect type, expected 'string', got '{2}'."), + File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: diag(5065, ts.DiagnosticCategory.Error, "File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildca_5065", "File specification cannot contain a parent directory ('..') that appears after a recursive directory wildcard ('**'): '{0}'."), + Substitutions_for_pattern_0_shouldn_t_be_an_empty_array: diag(5066, ts.DiagnosticCategory.Error, "Substitutions_for_pattern_0_shouldn_t_be_an_empty_array_5066", "Substitutions for pattern '{0}' shouldn't be an empty array."), + Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name: diag(5067, ts.DiagnosticCategory.Error, "Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name_5067", "Invalid value for 'jsxFactory'. '{0}' is not a valid identifier or qualified-name."), + Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig: diag(5068, ts.DiagnosticCategory.Error, "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068", "Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig."), + Option_0_cannot_be_specified_without_specifying_option_1_or_option_2: diag(5069, ts.DiagnosticCategory.Error, "Option_0_cannot_be_specified_without_specifying_option_1_or_option_2_5069", "Option '{0}' cannot be specified without specifying option '{1}' or option '{2}'."), + Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy: diag(5070, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070", "Option '--resolveJsonModule' cannot be specified without 'node' module resolution strategy."), + Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_esNext: diag(5071, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_5071", "Option '--resolveJsonModule' can only be specified when module code generation is 'commonjs', 'amd', 'es2015' or 'esNext'."), + Unknown_build_option_0: diag(5072, ts.DiagnosticCategory.Error, "Unknown_build_option_0_5072", "Unknown build option '{0}'."), + Build_option_0_requires_a_value_of_type_1: diag(5073, ts.DiagnosticCategory.Error, "Build_option_0_requires_a_value_of_type_1_5073", "Build option '{0}' requires a value of type {1}."), + Generates_a_sourcemap_for_each_corresponding_d_ts_file: diag(6000, ts.DiagnosticCategory.Message, "Generates_a_sourcemap_for_each_corresponding_d_ts_file_6000", "Generates a sourcemap for each corresponding '.d.ts' file."), + Concatenate_and_emit_output_to_single_file: diag(6001, ts.DiagnosticCategory.Message, "Concatenate_and_emit_output_to_single_file_6001", "Concatenate and emit output to single file."), + Generates_corresponding_d_ts_file: diag(6002, ts.DiagnosticCategory.Message, "Generates_corresponding_d_ts_file_6002", "Generates corresponding '.d.ts' file."), + Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations: diag(6003, ts.DiagnosticCategory.Message, "Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations_6003", "Specify the location where debugger should locate map files instead of generated locations."), + Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations: diag(6004, ts.DiagnosticCategory.Message, "Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations_6004", "Specify the location where debugger should locate TypeScript files instead of source locations."), + Watch_input_files: diag(6005, ts.DiagnosticCategory.Message, "Watch_input_files_6005", "Watch input files."), + Redirect_output_structure_to_the_directory: diag(6006, ts.DiagnosticCategory.Message, "Redirect_output_structure_to_the_directory_6006", "Redirect output structure to the directory."), + Do_not_erase_const_enum_declarations_in_generated_code: diag(6007, ts.DiagnosticCategory.Message, "Do_not_erase_const_enum_declarations_in_generated_code_6007", "Do not erase const enum declarations in generated code."), + Do_not_emit_outputs_if_any_errors_were_reported: diag(6008, ts.DiagnosticCategory.Message, "Do_not_emit_outputs_if_any_errors_were_reported_6008", "Do not emit outputs if any errors were reported."), + Do_not_emit_comments_to_output: diag(6009, ts.DiagnosticCategory.Message, "Do_not_emit_comments_to_output_6009", "Do not emit comments to output."), + Do_not_emit_outputs: diag(6010, ts.DiagnosticCategory.Message, "Do_not_emit_outputs_6010", "Do not emit outputs."), + Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking: diag(6011, ts.DiagnosticCategory.Message, "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011", "Allow default imports from modules with no default export. This does not affect code emit, just typechecking."), + Skip_type_checking_of_declaration_files: diag(6012, ts.DiagnosticCategory.Message, "Skip_type_checking_of_declaration_files_6012", "Skip type checking of declaration files."), + Do_not_resolve_the_real_path_of_symlinks: diag(6013, ts.DiagnosticCategory.Message, "Do_not_resolve_the_real_path_of_symlinks_6013", "Do not resolve the real path of symlinks."), + Only_emit_d_ts_declaration_files: diag(6014, ts.DiagnosticCategory.Message, "Only_emit_d_ts_declaration_files_6014", "Only emit '.d.ts' declaration files."), + Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_or_ESNEXT: diag(6015, ts.DiagnosticCategory.Message, "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_or_ESNEXT_6015", "Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'."), + Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext: diag(6016, ts.DiagnosticCategory.Message, "Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext_6016", "Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'."), + Print_this_message: diag(6017, ts.DiagnosticCategory.Message, "Print_this_message_6017", "Print this message."), + Print_the_compiler_s_version: diag(6019, ts.DiagnosticCategory.Message, "Print_the_compiler_s_version_6019", "Print the compiler's version."), + Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json: diag(6020, ts.DiagnosticCategory.Message, "Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json_6020", "Compile the project given the path to its configuration file, or to a folder with a 'tsconfig.json'."), + Syntax_Colon_0: diag(6023, ts.DiagnosticCategory.Message, "Syntax_Colon_0_6023", "Syntax: {0}"), + options: diag(6024, ts.DiagnosticCategory.Message, "options_6024", "options"), + file: diag(6025, ts.DiagnosticCategory.Message, "file_6025", "file"), + Examples_Colon_0: diag(6026, ts.DiagnosticCategory.Message, "Examples_Colon_0_6026", "Examples: {0}"), + Options_Colon: diag(6027, ts.DiagnosticCategory.Message, "Options_Colon_6027", "Options:"), + Version_0: diag(6029, ts.DiagnosticCategory.Message, "Version_0_6029", "Version {0}"), + Insert_command_line_options_and_files_from_a_file: diag(6030, ts.DiagnosticCategory.Message, "Insert_command_line_options_and_files_from_a_file_6030", "Insert command line options and files from a file."), + Starting_compilation_in_watch_mode: diag(6031, ts.DiagnosticCategory.Message, "Starting_compilation_in_watch_mode_6031", "Starting compilation in watch mode..."), + File_change_detected_Starting_incremental_compilation: diag(6032, ts.DiagnosticCategory.Message, "File_change_detected_Starting_incremental_compilation_6032", "File change detected. Starting incremental compilation..."), + KIND: diag(6034, ts.DiagnosticCategory.Message, "KIND_6034", "KIND"), + FILE: diag(6035, ts.DiagnosticCategory.Message, "FILE_6035", "FILE"), + VERSION: diag(6036, ts.DiagnosticCategory.Message, "VERSION_6036", "VERSION"), + LOCATION: diag(6037, ts.DiagnosticCategory.Message, "LOCATION_6037", "LOCATION"), + DIRECTORY: diag(6038, ts.DiagnosticCategory.Message, "DIRECTORY_6038", "DIRECTORY"), + STRATEGY: diag(6039, ts.DiagnosticCategory.Message, "STRATEGY_6039", "STRATEGY"), + FILE_OR_DIRECTORY: diag(6040, ts.DiagnosticCategory.Message, "FILE_OR_DIRECTORY_6040", "FILE OR DIRECTORY"), + Generates_corresponding_map_file: diag(6043, ts.DiagnosticCategory.Message, "Generates_corresponding_map_file_6043", "Generates corresponding '.map' file."), + Compiler_option_0_expects_an_argument: diag(6044, ts.DiagnosticCategory.Error, "Compiler_option_0_expects_an_argument_6044", "Compiler option '{0}' expects an argument."), + Unterminated_quoted_string_in_response_file_0: diag(6045, ts.DiagnosticCategory.Error, "Unterminated_quoted_string_in_response_file_0_6045", "Unterminated quoted string in response file '{0}'."), + Argument_for_0_option_must_be_Colon_1: diag(6046, ts.DiagnosticCategory.Error, "Argument_for_0_option_must_be_Colon_1_6046", "Argument for '{0}' option must be: {1}."), + Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1: diag(6048, ts.DiagnosticCategory.Error, "Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1_6048", "Locale must be of the form or -. For example '{0}' or '{1}'."), + Unsupported_locale_0: diag(6049, ts.DiagnosticCategory.Error, "Unsupported_locale_0_6049", "Unsupported locale '{0}'."), + Unable_to_open_file_0: diag(6050, ts.DiagnosticCategory.Error, "Unable_to_open_file_0_6050", "Unable to open file '{0}'."), + Corrupted_locale_file_0: diag(6051, ts.DiagnosticCategory.Error, "Corrupted_locale_file_0_6051", "Corrupted locale file {0}."), + Raise_error_on_expressions_and_declarations_with_an_implied_any_type: diag(6052, ts.DiagnosticCategory.Message, "Raise_error_on_expressions_and_declarations_with_an_implied_any_type_6052", "Raise error on expressions and declarations with an implied 'any' type."), + File_0_not_found: diag(6053, ts.DiagnosticCategory.Error, "File_0_not_found_6053", "File '{0}' not found."), + File_0_has_unsupported_extension_The_only_supported_extensions_are_1: diag(6054, ts.DiagnosticCategory.Error, "File_0_has_unsupported_extension_The_only_supported_extensions_are_1_6054", "File '{0}' has unsupported extension. The only supported extensions are {1}."), + Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures: diag(6055, ts.DiagnosticCategory.Message, "Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures_6055", "Suppress noImplicitAny errors for indexing objects lacking index signatures."), + Do_not_emit_declarations_for_code_that_has_an_internal_annotation: diag(6056, ts.DiagnosticCategory.Message, "Do_not_emit_declarations_for_code_that_has_an_internal_annotation_6056", "Do not emit declarations for code that has an '@internal' annotation."), + Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir: diag(6058, ts.DiagnosticCategory.Message, "Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir_6058", "Specify the root directory of input files. Use to control the output directory structure with --outDir."), + File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files: diag(6059, ts.DiagnosticCategory.Error, "File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files_6059", "File '{0}' is not under 'rootDir' '{1}'. 'rootDir' is expected to contain all source files."), + Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix: diag(6060, ts.DiagnosticCategory.Message, "Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix_6060", "Specify the end of line sequence to be used when emitting files: 'CRLF' (dos) or 'LF' (unix)."), + NEWLINE: diag(6061, ts.DiagnosticCategory.Message, "NEWLINE_6061", "NEWLINE"), + Option_0_can_only_be_specified_in_tsconfig_json_file: diag(6064, ts.DiagnosticCategory.Error, "Option_0_can_only_be_specified_in_tsconfig_json_file_6064", "Option '{0}' can only be specified in 'tsconfig.json' file."), + Enables_experimental_support_for_ES7_decorators: diag(6065, ts.DiagnosticCategory.Message, "Enables_experimental_support_for_ES7_decorators_6065", "Enables experimental support for ES7 decorators."), + Enables_experimental_support_for_emitting_type_metadata_for_decorators: diag(6066, ts.DiagnosticCategory.Message, "Enables_experimental_support_for_emitting_type_metadata_for_decorators_6066", "Enables experimental support for emitting type metadata for decorators."), + Enables_experimental_support_for_ES7_async_functions: diag(6068, ts.DiagnosticCategory.Message, "Enables_experimental_support_for_ES7_async_functions_6068", "Enables experimental support for ES7 async functions."), + Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6: diag(6069, ts.DiagnosticCategory.Message, "Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6_6069", "Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6)."), + Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file: diag(6070, ts.DiagnosticCategory.Message, "Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file_6070", "Initializes a TypeScript project and creates a tsconfig.json file."), + Successfully_created_a_tsconfig_json_file: diag(6071, ts.DiagnosticCategory.Message, "Successfully_created_a_tsconfig_json_file_6071", "Successfully created a tsconfig.json file."), + Suppress_excess_property_checks_for_object_literals: diag(6072, ts.DiagnosticCategory.Message, "Suppress_excess_property_checks_for_object_literals_6072", "Suppress excess property checks for object literals."), + Stylize_errors_and_messages_using_color_and_context_experimental: diag(6073, ts.DiagnosticCategory.Message, "Stylize_errors_and_messages_using_color_and_context_experimental_6073", "Stylize errors and messages using color and context (experimental)."), + Do_not_report_errors_on_unused_labels: diag(6074, ts.DiagnosticCategory.Message, "Do_not_report_errors_on_unused_labels_6074", "Do not report errors on unused labels."), + Report_error_when_not_all_code_paths_in_function_return_a_value: diag(6075, ts.DiagnosticCategory.Message, "Report_error_when_not_all_code_paths_in_function_return_a_value_6075", "Report error when not all code paths in function return a value."), + Report_errors_for_fallthrough_cases_in_switch_statement: diag(6076, ts.DiagnosticCategory.Message, "Report_errors_for_fallthrough_cases_in_switch_statement_6076", "Report errors for fallthrough cases in switch statement."), + Do_not_report_errors_on_unreachable_code: diag(6077, ts.DiagnosticCategory.Message, "Do_not_report_errors_on_unreachable_code_6077", "Do not report errors on unreachable code."), + Disallow_inconsistently_cased_references_to_the_same_file: diag(6078, ts.DiagnosticCategory.Message, "Disallow_inconsistently_cased_references_to_the_same_file_6078", "Disallow inconsistently-cased references to the same file."), + Specify_library_files_to_be_included_in_the_compilation: diag(6079, ts.DiagnosticCategory.Message, "Specify_library_files_to_be_included_in_the_compilation_6079", "Specify library files to be included in the compilation."), + Specify_JSX_code_generation_Colon_preserve_react_native_or_react: diag(6080, ts.DiagnosticCategory.Message, "Specify_JSX_code_generation_Colon_preserve_react_native_or_react_6080", "Specify JSX code generation: 'preserve', 'react-native', or 'react'."), + File_0_has_an_unsupported_extension_so_skipping_it: diag(6081, ts.DiagnosticCategory.Message, "File_0_has_an_unsupported_extension_so_skipping_it_6081", "File '{0}' has an unsupported extension, so skipping it."), + Only_amd_and_system_modules_are_supported_alongside_0: diag(6082, ts.DiagnosticCategory.Error, "Only_amd_and_system_modules_are_supported_alongside_0_6082", "Only 'amd' and 'system' modules are supported alongside --{0}."), + Base_directory_to_resolve_non_absolute_module_names: diag(6083, ts.DiagnosticCategory.Message, "Base_directory_to_resolve_non_absolute_module_names_6083", "Base directory to resolve non-absolute module names."), + Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react_JSX_emit: diag(6084, ts.DiagnosticCategory.Message, "Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react__6084", "[Deprecated] Use '--jsxFactory' instead. Specify the object invoked for createElement when targeting 'react' JSX emit"), + Enable_tracing_of_the_name_resolution_process: diag(6085, ts.DiagnosticCategory.Message, "Enable_tracing_of_the_name_resolution_process_6085", "Enable tracing of the name resolution process."), + Resolving_module_0_from_1: diag(6086, ts.DiagnosticCategory.Message, "Resolving_module_0_from_1_6086", "======== Resolving module '{0}' from '{1}'. ========"), + Explicitly_specified_module_resolution_kind_Colon_0: diag(6087, ts.DiagnosticCategory.Message, "Explicitly_specified_module_resolution_kind_Colon_0_6087", "Explicitly specified module resolution kind: '{0}'."), + Module_resolution_kind_is_not_specified_using_0: diag(6088, ts.DiagnosticCategory.Message, "Module_resolution_kind_is_not_specified_using_0_6088", "Module resolution kind is not specified, using '{0}'."), + Module_name_0_was_successfully_resolved_to_1: diag(6089, ts.DiagnosticCategory.Message, "Module_name_0_was_successfully_resolved_to_1_6089", "======== Module name '{0}' was successfully resolved to '{1}'. ========"), + Module_name_0_was_not_resolved: diag(6090, ts.DiagnosticCategory.Message, "Module_name_0_was_not_resolved_6090", "======== Module name '{0}' was not resolved. ========"), + paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0: diag(6091, ts.DiagnosticCategory.Message, "paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0_6091", "'paths' option is specified, looking for a pattern to match module name '{0}'."), + Module_name_0_matched_pattern_1: diag(6092, ts.DiagnosticCategory.Message, "Module_name_0_matched_pattern_1_6092", "Module name '{0}', matched pattern '{1}'."), + Trying_substitution_0_candidate_module_location_Colon_1: diag(6093, ts.DiagnosticCategory.Message, "Trying_substitution_0_candidate_module_location_Colon_1_6093", "Trying substitution '{0}', candidate module location: '{1}'."), + Resolving_module_name_0_relative_to_base_url_1_2: diag(6094, ts.DiagnosticCategory.Message, "Resolving_module_name_0_relative_to_base_url_1_2_6094", "Resolving module name '{0}' relative to base url '{1}' - '{2}'."), + Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1: diag(6095, ts.DiagnosticCategory.Message, "Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1_6095", "Loading module as file / folder, candidate module location '{0}', target file type '{1}'."), + File_0_does_not_exist: diag(6096, ts.DiagnosticCategory.Message, "File_0_does_not_exist_6096", "File '{0}' does not exist."), + File_0_exist_use_it_as_a_name_resolution_result: diag(6097, ts.DiagnosticCategory.Message, "File_0_exist_use_it_as_a_name_resolution_result_6097", "File '{0}' exist - use it as a name resolution result."), + Loading_module_0_from_node_modules_folder_target_file_type_1: diag(6098, ts.DiagnosticCategory.Message, "Loading_module_0_from_node_modules_folder_target_file_type_1_6098", "Loading module '{0}' from 'node_modules' folder, target file type '{1}'."), + Found_package_json_at_0: diag(6099, ts.DiagnosticCategory.Message, "Found_package_json_at_0_6099", "Found 'package.json' at '{0}'."), + package_json_does_not_have_a_0_field: diag(6100, ts.DiagnosticCategory.Message, "package_json_does_not_have_a_0_field_6100", "'package.json' does not have a '{0}' field."), + package_json_has_0_field_1_that_references_2: diag(6101, ts.DiagnosticCategory.Message, "package_json_has_0_field_1_that_references_2_6101", "'package.json' has '{0}' field '{1}' that references '{2}'."), + Allow_javascript_files_to_be_compiled: diag(6102, ts.DiagnosticCategory.Message, "Allow_javascript_files_to_be_compiled_6102", "Allow javascript files to be compiled."), + Option_0_should_have_array_of_strings_as_a_value: diag(6103, ts.DiagnosticCategory.Error, "Option_0_should_have_array_of_strings_as_a_value_6103", "Option '{0}' should have array of strings as a value."), + Checking_if_0_is_the_longest_matching_prefix_for_1_2: diag(6104, ts.DiagnosticCategory.Message, "Checking_if_0_is_the_longest_matching_prefix_for_1_2_6104", "Checking if '{0}' is the longest matching prefix for '{1}' - '{2}'."), + Expected_type_of_0_field_in_package_json_to_be_1_got_2: diag(6105, ts.DiagnosticCategory.Message, "Expected_type_of_0_field_in_package_json_to_be_1_got_2_6105", "Expected type of '{0}' field in 'package.json' to be '{1}', got '{2}'."), + baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1: diag(6106, ts.DiagnosticCategory.Message, "baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1_6106", "'baseUrl' option is set to '{0}', using this value to resolve non-relative module name '{1}'."), + rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0: diag(6107, ts.DiagnosticCategory.Message, "rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107", "'rootDirs' option is set, using it to resolve relative module name '{0}'."), + Longest_matching_prefix_for_0_is_1: diag(6108, ts.DiagnosticCategory.Message, "Longest_matching_prefix_for_0_is_1_6108", "Longest matching prefix for '{0}' is '{1}'."), + Loading_0_from_the_root_dir_1_candidate_location_2: diag(6109, ts.DiagnosticCategory.Message, "Loading_0_from_the_root_dir_1_candidate_location_2_6109", "Loading '{0}' from the root dir '{1}', candidate location '{2}'."), + Trying_other_entries_in_rootDirs: diag(6110, ts.DiagnosticCategory.Message, "Trying_other_entries_in_rootDirs_6110", "Trying other entries in 'rootDirs'."), + Module_resolution_using_rootDirs_has_failed: diag(6111, ts.DiagnosticCategory.Message, "Module_resolution_using_rootDirs_has_failed_6111", "Module resolution using 'rootDirs' has failed."), + Do_not_emit_use_strict_directives_in_module_output: diag(6112, ts.DiagnosticCategory.Message, "Do_not_emit_use_strict_directives_in_module_output_6112", "Do not emit 'use strict' directives in module output."), + Enable_strict_null_checks: diag(6113, ts.DiagnosticCategory.Message, "Enable_strict_null_checks_6113", "Enable strict null checks."), + Unknown_option_excludes_Did_you_mean_exclude: diag(6114, ts.DiagnosticCategory.Error, "Unknown_option_excludes_Did_you_mean_exclude_6114", "Unknown option 'excludes'. Did you mean 'exclude'?"), + Raise_error_on_this_expressions_with_an_implied_any_type: diag(6115, ts.DiagnosticCategory.Message, "Raise_error_on_this_expressions_with_an_implied_any_type_6115", "Raise error on 'this' expressions with an implied 'any' type."), + Resolving_type_reference_directive_0_containing_file_1_root_directory_2: diag(6116, ts.DiagnosticCategory.Message, "Resolving_type_reference_directive_0_containing_file_1_root_directory_2_6116", "======== Resolving type reference directive '{0}', containing file '{1}', root directory '{2}'. ========"), + Resolving_using_primary_search_paths: diag(6117, ts.DiagnosticCategory.Message, "Resolving_using_primary_search_paths_6117", "Resolving using primary search paths..."), + Resolving_from_node_modules_folder: diag(6118, ts.DiagnosticCategory.Message, "Resolving_from_node_modules_folder_6118", "Resolving from node_modules folder..."), + Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2: diag(6119, ts.DiagnosticCategory.Message, "Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2_6119", "======== Type reference directive '{0}' was successfully resolved to '{1}', primary: {2}. ========"), + Type_reference_directive_0_was_not_resolved: diag(6120, ts.DiagnosticCategory.Message, "Type_reference_directive_0_was_not_resolved_6120", "======== Type reference directive '{0}' was not resolved. ========"), + Resolving_with_primary_search_path_0: diag(6121, ts.DiagnosticCategory.Message, "Resolving_with_primary_search_path_0_6121", "Resolving with primary search path '{0}'."), + Root_directory_cannot_be_determined_skipping_primary_search_paths: diag(6122, ts.DiagnosticCategory.Message, "Root_directory_cannot_be_determined_skipping_primary_search_paths_6122", "Root directory cannot be determined, skipping primary search paths."), + Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set: diag(6123, ts.DiagnosticCategory.Message, "Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set_6123", "======== Resolving type reference directive '{0}', containing file '{1}', root directory not set. ========"), + Type_declaration_files_to_be_included_in_compilation: diag(6124, ts.DiagnosticCategory.Message, "Type_declaration_files_to_be_included_in_compilation_6124", "Type declaration files to be included in compilation."), + Looking_up_in_node_modules_folder_initial_location_0: diag(6125, ts.DiagnosticCategory.Message, "Looking_up_in_node_modules_folder_initial_location_0_6125", "Looking up in 'node_modules' folder, initial location '{0}'."), + Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder: diag(6126, ts.DiagnosticCategory.Message, "Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126", "Containing file is not specified and root directory cannot be determined, skipping lookup in 'node_modules' folder."), + Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1: diag(6127, ts.DiagnosticCategory.Message, "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1_6127", "======== Resolving type reference directive '{0}', containing file not set, root directory '{1}'. ========"), + Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set: diag(6128, ts.DiagnosticCategory.Message, "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set_6128", "======== Resolving type reference directive '{0}', containing file not set, root directory not set. ========"), + Resolving_real_path_for_0_result_1: diag(6130, ts.DiagnosticCategory.Message, "Resolving_real_path_for_0_result_1_6130", "Resolving real path for '{0}', result '{1}'."), + Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system: diag(6131, ts.DiagnosticCategory.Error, "Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system_6131", "Cannot compile modules using option '{0}' unless the '--module' flag is 'amd' or 'system'."), + File_name_0_has_a_1_extension_stripping_it: diag(6132, ts.DiagnosticCategory.Message, "File_name_0_has_a_1_extension_stripping_it_6132", "File name '{0}' has a '{1}' extension - stripping it."), + _0_is_declared_but_its_value_is_never_read: diag(6133, ts.DiagnosticCategory.Error, "_0_is_declared_but_its_value_is_never_read_6133", "'{0}' is declared but its value is never read.", /*reportsUnnecessary*/ true), + Report_errors_on_unused_locals: diag(6134, ts.DiagnosticCategory.Message, "Report_errors_on_unused_locals_6134", "Report errors on unused locals."), + Report_errors_on_unused_parameters: diag(6135, ts.DiagnosticCategory.Message, "Report_errors_on_unused_parameters_6135", "Report errors on unused parameters."), + The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files: diag(6136, ts.DiagnosticCategory.Message, "The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files_6136", "The maximum dependency depth to search under node_modules and load JavaScript files."), + Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1: diag(6137, ts.DiagnosticCategory.Error, "Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1_6137", "Cannot import type declaration files. Consider importing '{0}' instead of '{1}'."), + Property_0_is_declared_but_its_value_is_never_read: diag(6138, ts.DiagnosticCategory.Error, "Property_0_is_declared_but_its_value_is_never_read_6138", "Property '{0}' is declared but its value is never read.", /*reportsUnnecessary*/ true), + Import_emit_helpers_from_tslib: diag(6139, ts.DiagnosticCategory.Message, "Import_emit_helpers_from_tslib_6139", "Import emit helpers from 'tslib'."), + Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2: diag(6140, ts.DiagnosticCategory.Error, "Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using__6140", "Auto discovery for typings is enabled in project '{0}'. Running extra resolution pass for module '{1}' using cache location '{2}'."), + Parse_in_strict_mode_and_emit_use_strict_for_each_source_file: diag(6141, ts.DiagnosticCategory.Message, "Parse_in_strict_mode_and_emit_use_strict_for_each_source_file_6141", "Parse in strict mode and emit \"use strict\" for each source file."), + Module_0_was_resolved_to_1_but_jsx_is_not_set: diag(6142, ts.DiagnosticCategory.Error, "Module_0_was_resolved_to_1_but_jsx_is_not_set_6142", "Module '{0}' was resolved to '{1}', but '--jsx' is not set."), + Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1: diag(6144, ts.DiagnosticCategory.Message, "Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1_6144", "Module '{0}' was resolved as locally declared ambient module in file '{1}'."), + Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified: diag(6145, ts.DiagnosticCategory.Message, "Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified_6145", "Module '{0}' was resolved as ambient module declared in '{1}' since this file was not modified."), + Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h: diag(6146, ts.DiagnosticCategory.Message, "Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h_6146", "Specify the JSX factory function to use when targeting 'react' JSX emit, e.g. 'React.createElement' or 'h'."), + Resolution_for_module_0_was_found_in_cache_from_location_1: diag(6147, ts.DiagnosticCategory.Message, "Resolution_for_module_0_was_found_in_cache_from_location_1_6147", "Resolution for module '{0}' was found in cache from location '{1}'."), + Directory_0_does_not_exist_skipping_all_lookups_in_it: diag(6148, ts.DiagnosticCategory.Message, "Directory_0_does_not_exist_skipping_all_lookups_in_it_6148", "Directory '{0}' does not exist, skipping all lookups in it."), + Show_diagnostic_information: diag(6149, ts.DiagnosticCategory.Message, "Show_diagnostic_information_6149", "Show diagnostic information."), + Show_verbose_diagnostic_information: diag(6150, ts.DiagnosticCategory.Message, "Show_verbose_diagnostic_information_6150", "Show verbose diagnostic information."), + Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file: diag(6151, ts.DiagnosticCategory.Message, "Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file_6151", "Emit a single file with source maps instead of having a separate file."), + Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap_to_be_set: diag(6152, ts.DiagnosticCategory.Message, "Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap__6152", "Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set."), + Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule: diag(6153, ts.DiagnosticCategory.Message, "Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule_6153", "Transpile each file as a separate module (similar to 'ts.transpileModule')."), + Print_names_of_generated_files_part_of_the_compilation: diag(6154, ts.DiagnosticCategory.Message, "Print_names_of_generated_files_part_of_the_compilation_6154", "Print names of generated files part of the compilation."), + Print_names_of_files_part_of_the_compilation: diag(6155, ts.DiagnosticCategory.Message, "Print_names_of_files_part_of_the_compilation_6155", "Print names of files part of the compilation."), + The_locale_used_when_displaying_messages_to_the_user_e_g_en_us: diag(6156, ts.DiagnosticCategory.Message, "The_locale_used_when_displaying_messages_to_the_user_e_g_en_us_6156", "The locale used when displaying messages to the user (e.g. 'en-us')"), + Do_not_generate_custom_helper_functions_like_extends_in_compiled_output: diag(6157, ts.DiagnosticCategory.Message, "Do_not_generate_custom_helper_functions_like_extends_in_compiled_output_6157", "Do not generate custom helper functions like '__extends' in compiled output."), + Do_not_include_the_default_library_file_lib_d_ts: diag(6158, ts.DiagnosticCategory.Message, "Do_not_include_the_default_library_file_lib_d_ts_6158", "Do not include the default library file (lib.d.ts)."), + Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files: diag(6159, ts.DiagnosticCategory.Message, "Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files_6159", "Do not add triple-slash references or imported modules to the list of compiled files."), + Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files: diag(6160, ts.DiagnosticCategory.Message, "Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files_6160", "[Deprecated] Use '--skipLibCheck' instead. Skip type checking of default library declaration files."), + List_of_folders_to_include_type_definitions_from: diag(6161, ts.DiagnosticCategory.Message, "List_of_folders_to_include_type_definitions_from_6161", "List of folders to include type definitions from."), + Disable_size_limitations_on_JavaScript_projects: diag(6162, ts.DiagnosticCategory.Message, "Disable_size_limitations_on_JavaScript_projects_6162", "Disable size limitations on JavaScript projects."), + The_character_set_of_the_input_files: diag(6163, ts.DiagnosticCategory.Message, "The_character_set_of_the_input_files_6163", "The character set of the input files."), + Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files: diag(6164, ts.DiagnosticCategory.Message, "Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files_6164", "Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files."), + Do_not_truncate_error_messages: diag(6165, ts.DiagnosticCategory.Message, "Do_not_truncate_error_messages_6165", "Do not truncate error messages."), + Output_directory_for_generated_declaration_files: diag(6166, ts.DiagnosticCategory.Message, "Output_directory_for_generated_declaration_files_6166", "Output directory for generated declaration files."), + A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl: diag(6167, ts.DiagnosticCategory.Message, "A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl_6167", "A series of entries which re-map imports to lookup locations relative to the 'baseUrl'."), + List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime: diag(6168, ts.DiagnosticCategory.Message, "List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime_6168", "List of root folders whose combined content represents the structure of the project at runtime."), + Show_all_compiler_options: diag(6169, ts.DiagnosticCategory.Message, "Show_all_compiler_options_6169", "Show all compiler options."), + Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file: diag(6170, ts.DiagnosticCategory.Message, "Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file_6170", "[Deprecated] Use '--outFile' instead. Concatenate and emit output to single file"), + Command_line_Options: diag(6171, ts.DiagnosticCategory.Message, "Command_line_Options_6171", "Command-line Options"), + Basic_Options: diag(6172, ts.DiagnosticCategory.Message, "Basic_Options_6172", "Basic Options"), + Strict_Type_Checking_Options: diag(6173, ts.DiagnosticCategory.Message, "Strict_Type_Checking_Options_6173", "Strict Type-Checking Options"), + Module_Resolution_Options: diag(6174, ts.DiagnosticCategory.Message, "Module_Resolution_Options_6174", "Module Resolution Options"), + Source_Map_Options: diag(6175, ts.DiagnosticCategory.Message, "Source_Map_Options_6175", "Source Map Options"), + Additional_Checks: diag(6176, ts.DiagnosticCategory.Message, "Additional_Checks_6176", "Additional Checks"), + Experimental_Options: diag(6177, ts.DiagnosticCategory.Message, "Experimental_Options_6177", "Experimental Options"), + Advanced_Options: diag(6178, ts.DiagnosticCategory.Message, "Advanced_Options_6178", "Advanced Options"), + Provide_full_support_for_iterables_in_for_of_spread_and_destructuring_when_targeting_ES5_or_ES3: diag(6179, ts.DiagnosticCategory.Message, "Provide_full_support_for_iterables_in_for_of_spread_and_destructuring_when_targeting_ES5_or_ES3_6179", "Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'."), + Enable_all_strict_type_checking_options: diag(6180, ts.DiagnosticCategory.Message, "Enable_all_strict_type_checking_options_6180", "Enable all strict type-checking options."), + List_of_language_service_plugins: diag(6181, ts.DiagnosticCategory.Message, "List_of_language_service_plugins_6181", "List of language service plugins."), + Scoped_package_detected_looking_in_0: diag(6182, ts.DiagnosticCategory.Message, "Scoped_package_detected_looking_in_0_6182", "Scoped package detected, looking in '{0}'"), + Reusing_resolution_of_module_0_to_file_1_from_old_program: diag(6183, ts.DiagnosticCategory.Message, "Reusing_resolution_of_module_0_to_file_1_from_old_program_6183", "Reusing resolution of module '{0}' to file '{1}' from old program."), + Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program: diag(6184, ts.DiagnosticCategory.Message, "Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program_6184", "Reusing module resolutions originating in '{0}' since resolutions are unchanged from old program."), + Disable_strict_checking_of_generic_signatures_in_function_types: diag(6185, ts.DiagnosticCategory.Message, "Disable_strict_checking_of_generic_signatures_in_function_types_6185", "Disable strict checking of generic signatures in function types."), + Enable_strict_checking_of_function_types: diag(6186, ts.DiagnosticCategory.Message, "Enable_strict_checking_of_function_types_6186", "Enable strict checking of function types."), + Enable_strict_checking_of_property_initialization_in_classes: diag(6187, ts.DiagnosticCategory.Message, "Enable_strict_checking_of_property_initialization_in_classes_6187", "Enable strict checking of property initialization in classes."), + Numeric_separators_are_not_allowed_here: diag(6188, ts.DiagnosticCategory.Error, "Numeric_separators_are_not_allowed_here_6188", "Numeric separators are not allowed here."), + Multiple_consecutive_numeric_separators_are_not_permitted: diag(6189, ts.DiagnosticCategory.Error, "Multiple_consecutive_numeric_separators_are_not_permitted_6189", "Multiple consecutive numeric separators are not permitted."), + Found_package_json_at_0_Package_ID_is_1: diag(6190, ts.DiagnosticCategory.Message, "Found_package_json_at_0_Package_ID_is_1_6190", "Found 'package.json' at '{0}'. Package ID is '{1}'."), + Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen: diag(6191, ts.DiagnosticCategory.Message, "Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen_6191", "Whether to keep outdated console output in watch mode instead of clearing the screen."), + All_imports_in_import_declaration_are_unused: diag(6192, ts.DiagnosticCategory.Error, "All_imports_in_import_declaration_are_unused_6192", "All imports in import declaration are unused.", /*reportsUnnecessary*/ true), + Found_1_error_Watching_for_file_changes: diag(6193, ts.DiagnosticCategory.Message, "Found_1_error_Watching_for_file_changes_6193", "Found 1 error. Watching for file changes."), + Found_0_errors_Watching_for_file_changes: diag(6194, ts.DiagnosticCategory.Message, "Found_0_errors_Watching_for_file_changes_6194", "Found {0} errors. Watching for file changes."), + Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols: diag(6195, ts.DiagnosticCategory.Message, "Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols_6195", "Resolve 'keyof' to string valued property names only (no numbers or symbols)."), + _0_is_declared_but_never_used: diag(6196, ts.DiagnosticCategory.Error, "_0_is_declared_but_never_used_6196", "'{0}' is declared but never used.", /*reportsUnnecessary*/ true), + Include_modules_imported_with_json_extension: diag(6197, ts.DiagnosticCategory.Message, "Include_modules_imported_with_json_extension_6197", "Include modules imported with '.json' extension"), + All_destructured_elements_are_unused: diag(6198, ts.DiagnosticCategory.Error, "All_destructured_elements_are_unused_6198", "All destructured elements are unused.", /*reportsUnnecessary*/ true), + All_variables_are_unused: diag(6199, ts.DiagnosticCategory.Error, "All_variables_are_unused_6199", "All variables are unused.", /*reportsUnnecessary*/ true), + Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0: diag(6200, ts.DiagnosticCategory.Error, "Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0_6200", "Definitions of the following identifiers conflict with those in another file: {0}"), + Conflicts_are_in_this_file: diag(6201, ts.DiagnosticCategory.Message, "Conflicts_are_in_this_file_6201", "Conflicts are in this file."), + _0_was_also_declared_here: diag(6203, ts.DiagnosticCategory.Message, "_0_was_also_declared_here_6203", "'{0}' was also declared here."), + and_here: diag(6204, ts.DiagnosticCategory.Message, "and_here_6204", "and here."), + All_type_parameters_are_unused: diag(6205, ts.DiagnosticCategory.Error, "All_type_parameters_are_unused_6205", "All type parameters are unused"), + package_json_has_a_typesVersions_field_with_version_specific_path_mappings: diag(6206, ts.DiagnosticCategory.Message, "package_json_has_a_typesVersions_field_with_version_specific_path_mappings_6206", "'package.json' has a 'typesVersions' field with version-specific path mappings."), + package_json_does_not_have_a_typesVersions_entry_that_matches_version_0: diag(6207, ts.DiagnosticCategory.Message, "package_json_does_not_have_a_typesVersions_entry_that_matches_version_0_6207", "'package.json' does not have a 'typesVersions' entry that matches version '{0}'."), + package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2: diag(6208, ts.DiagnosticCategory.Message, "package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_ma_6208", "'package.json' has a 'typesVersions' entry '{0}' that matches compiler version '{1}', looking for a pattern to match module name '{2}'."), + package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range: diag(6209, ts.DiagnosticCategory.Message, "package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range_6209", "'package.json' has a 'typesVersions' entry '{0}' that is not a valid semver range."), + An_argument_for_0_was_not_provided: diag(6210, ts.DiagnosticCategory.Message, "An_argument_for_0_was_not_provided_6210", "An argument for '{0}' was not provided."), + An_argument_matching_this_binding_pattern_was_not_provided: diag(6211, ts.DiagnosticCategory.Message, "An_argument_matching_this_binding_pattern_was_not_provided_6211", "An argument matching this binding pattern was not provided."), + Did_you_mean_to_call_this_expression: diag(6212, ts.DiagnosticCategory.Message, "Did_you_mean_to_call_this_expression_6212", "Did you mean to call this expression?"), + Did_you_mean_to_use_new_with_this_expression: diag(6213, ts.DiagnosticCategory.Message, "Did_you_mean_to_use_new_with_this_expression_6213", "Did you mean to use 'new' with this expression?"), + Enable_strict_bind_call_and_apply_methods_on_functions: diag(6214, ts.DiagnosticCategory.Message, "Enable_strict_bind_call_and_apply_methods_on_functions_6214", "Enable strict 'bind', 'call', and 'apply' methods on functions."), + Using_compiler_options_of_project_reference_redirect_0: diag(6215, ts.DiagnosticCategory.Message, "Using_compiler_options_of_project_reference_redirect_0_6215", "Using compiler options of project reference redirect '{0}'."), + Found_1_error: diag(6216, ts.DiagnosticCategory.Message, "Found_1_error_6216", "Found 1 error."), + Found_0_errors: diag(6217, ts.DiagnosticCategory.Message, "Found_0_errors_6217", "Found {0} errors."), + Projects_to_reference: diag(6300, ts.DiagnosticCategory.Message, "Projects_to_reference_6300", "Projects to reference"), + Enable_project_compilation: diag(6302, ts.DiagnosticCategory.Message, "Enable_project_compilation_6302", "Enable project compilation"), + Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0: diag(6202, ts.DiagnosticCategory.Error, "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202", "Project references may not form a circular graph. Cycle detected: {0}"), + Composite_projects_may_not_disable_declaration_emit: diag(6304, ts.DiagnosticCategory.Error, "Composite_projects_may_not_disable_declaration_emit_6304", "Composite projects may not disable declaration emit."), + Output_file_0_has_not_been_built_from_source_file_1: diag(6305, ts.DiagnosticCategory.Error, "Output_file_0_has_not_been_built_from_source_file_1_6305", "Output file '{0}' has not been built from source file '{1}'."), + Referenced_project_0_must_have_setting_composite_Colon_true: diag(6306, ts.DiagnosticCategory.Error, "Referenced_project_0_must_have_setting_composite_Colon_true_6306", "Referenced project '{0}' must have setting \"composite\": true."), + File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern: diag(6307, ts.DiagnosticCategory.Error, "File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern_6307", "File '{0}' is not in project file list. Projects must list all files or use an 'include' pattern."), + Cannot_prepend_project_0_because_it_does_not_have_outFile_set: diag(6308, ts.DiagnosticCategory.Error, "Cannot_prepend_project_0_because_it_does_not_have_outFile_set_6308", "Cannot prepend project '{0}' because it does not have 'outFile' set"), + Output_file_0_from_project_1_does_not_exist: diag(6309, ts.DiagnosticCategory.Error, "Output_file_0_from_project_1_does_not_exist_6309", "Output file '{0}' from project '{1}' does not exist"), + Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2: diag(6350, ts.DiagnosticCategory.Message, "Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2_6350", "Project '{0}' is out of date because oldest output '{1}' is older than newest input '{2}'"), + Project_0_is_up_to_date_because_newest_input_1_is_older_than_oldest_output_2: diag(6351, ts.DiagnosticCategory.Message, "Project_0_is_up_to_date_because_newest_input_1_is_older_than_oldest_output_2_6351", "Project '{0}' is up to date because newest input '{1}' is older than oldest output '{2}'"), + Project_0_is_out_of_date_because_output_file_1_does_not_exist: diag(6352, ts.DiagnosticCategory.Message, "Project_0_is_out_of_date_because_output_file_1_does_not_exist_6352", "Project '{0}' is out of date because output file '{1}' does not exist"), + Project_0_is_out_of_date_because_its_dependency_1_is_out_of_date: diag(6353, ts.DiagnosticCategory.Message, "Project_0_is_out_of_date_because_its_dependency_1_is_out_of_date_6353", "Project '{0}' is out of date because its dependency '{1}' is out of date"), + Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies: diag(6354, ts.DiagnosticCategory.Message, "Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies_6354", "Project '{0}' is up to date with .d.ts files from its dependencies"), + Projects_in_this_build_Colon_0: diag(6355, ts.DiagnosticCategory.Message, "Projects_in_this_build_Colon_0_6355", "Projects in this build: {0}"), + A_non_dry_build_would_delete_the_following_files_Colon_0: diag(6356, ts.DiagnosticCategory.Message, "A_non_dry_build_would_delete_the_following_files_Colon_0_6356", "A non-dry build would delete the following files: {0}"), + A_non_dry_build_would_build_project_0: diag(6357, ts.DiagnosticCategory.Message, "A_non_dry_build_would_build_project_0_6357", "A non-dry build would build project '{0}'"), + Building_project_0: diag(6358, ts.DiagnosticCategory.Message, "Building_project_0_6358", "Building project '{0}'..."), + Updating_output_timestamps_of_project_0: diag(6359, ts.DiagnosticCategory.Message, "Updating_output_timestamps_of_project_0_6359", "Updating output timestamps of project '{0}'..."), + delete_this_Project_0_is_up_to_date_because_it_was_previously_built: diag(6360, ts.DiagnosticCategory.Message, "delete_this_Project_0_is_up_to_date_because_it_was_previously_built_6360", "delete this - Project '{0}' is up to date because it was previously built"), + Project_0_is_up_to_date: diag(6361, ts.DiagnosticCategory.Message, "Project_0_is_up_to_date_6361", "Project '{0}' is up to date"), + Skipping_build_of_project_0_because_its_dependency_1_has_errors: diag(6362, ts.DiagnosticCategory.Message, "Skipping_build_of_project_0_because_its_dependency_1_has_errors_6362", "Skipping build of project '{0}' because its dependency '{1}' has errors"), + Project_0_can_t_be_built_because_its_dependency_1_has_errors: diag(6363, ts.DiagnosticCategory.Message, "Project_0_can_t_be_built_because_its_dependency_1_has_errors_6363", "Project '{0}' can't be built because its dependency '{1}' has errors"), + Build_one_or_more_projects_and_their_dependencies_if_out_of_date: diag(6364, ts.DiagnosticCategory.Message, "Build_one_or_more_projects_and_their_dependencies_if_out_of_date_6364", "Build one or more projects and their dependencies, if out of date"), + Delete_the_outputs_of_all_projects: diag(6365, ts.DiagnosticCategory.Message, "Delete_the_outputs_of_all_projects_6365", "Delete the outputs of all projects"), + Enable_verbose_logging: diag(6366, ts.DiagnosticCategory.Message, "Enable_verbose_logging_6366", "Enable verbose logging"), + Show_what_would_be_built_or_deleted_if_specified_with_clean: diag(6367, ts.DiagnosticCategory.Message, "Show_what_would_be_built_or_deleted_if_specified_with_clean_6367", "Show what would be built (or deleted, if specified with '--clean')"), + Build_all_projects_including_those_that_appear_to_be_up_to_date: diag(6368, ts.DiagnosticCategory.Message, "Build_all_projects_including_those_that_appear_to_be_up_to_date_6368", "Build all projects, including those that appear to be up to date"), + Option_build_must_be_the_first_command_line_argument: diag(6369, ts.DiagnosticCategory.Error, "Option_build_must_be_the_first_command_line_argument_6369", "Option '--build' must be the first command line argument."), + Options_0_and_1_cannot_be_combined: diag(6370, ts.DiagnosticCategory.Error, "Options_0_and_1_cannot_be_combined_6370", "Options '{0}' and '{1}' cannot be combined."), + The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1: diag(6500, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1_6500", "The expected type comes from property '{0}' which is declared here on type '{1}'"), + The_expected_type_comes_from_this_index_signature: diag(6501, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_this_index_signature_6501", "The expected type comes from this index signature."), + The_expected_type_comes_from_the_return_type_of_this_signature: diag(6502, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_the_return_type_of_this_signature_6502", "The expected type comes from the return type of this signature."), + Variable_0_implicitly_has_an_1_type: diag(7005, ts.DiagnosticCategory.Error, "Variable_0_implicitly_has_an_1_type_7005", "Variable '{0}' implicitly has an '{1}' type."), + Parameter_0_implicitly_has_an_1_type: diag(7006, ts.DiagnosticCategory.Error, "Parameter_0_implicitly_has_an_1_type_7006", "Parameter '{0}' implicitly has an '{1}' type."), + Member_0_implicitly_has_an_1_type: diag(7008, ts.DiagnosticCategory.Error, "Member_0_implicitly_has_an_1_type_7008", "Member '{0}' implicitly has an '{1}' type."), + new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type: diag(7009, ts.DiagnosticCategory.Error, "new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type_7009", "'new' expression, whose target lacks a construct signature, implicitly has an 'any' type."), + _0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type: diag(7010, ts.DiagnosticCategory.Error, "_0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type_7010", "'{0}', which lacks return-type annotation, implicitly has an '{1}' return type."), + Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type: diag(7011, ts.DiagnosticCategory.Error, "Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type_7011", "Function expression, which lacks return-type annotation, implicitly has an '{0}' return type."), + Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: diag(7013, ts.DiagnosticCategory.Error, "Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7013", "Construct signature, which lacks return-type annotation, implicitly has an 'any' return type."), + Function_type_which_lacks_return_type_annotation_implicitly_has_an_0_return_type: diag(7014, ts.DiagnosticCategory.Error, "Function_type_which_lacks_return_type_annotation_implicitly_has_an_0_return_type_7014", "Function type, which lacks return-type annotation, implicitly has an '{0}' return type."), + Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number: diag(7015, ts.DiagnosticCategory.Error, "Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015", "Element implicitly has an 'any' type because index expression is not of type 'number'."), + Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type: diag(7016, ts.DiagnosticCategory.Error, "Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type_7016", "Could not find a declaration file for module '{0}'. '{1}' implicitly has an 'any' type."), + Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature: diag(7017, ts.DiagnosticCategory.Error, "Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature_7017", "Element implicitly has an 'any' type because type '{0}' has no index signature."), + Object_literal_s_property_0_implicitly_has_an_1_type: diag(7018, ts.DiagnosticCategory.Error, "Object_literal_s_property_0_implicitly_has_an_1_type_7018", "Object literal's property '{0}' implicitly has an '{1}' type."), + Rest_parameter_0_implicitly_has_an_any_type: diag(7019, ts.DiagnosticCategory.Error, "Rest_parameter_0_implicitly_has_an_any_type_7019", "Rest parameter '{0}' implicitly has an 'any[]' type."), + Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: diag(7020, ts.DiagnosticCategory.Error, "Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7020", "Call signature, which lacks return-type annotation, implicitly has an 'any' return type."), + _0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer: diag(7022, ts.DiagnosticCategory.Error, "_0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or__7022", "'{0}' implicitly has type 'any' because it does not have a type annotation and is referenced directly or indirectly in its own initializer."), + _0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions: diag(7023, ts.DiagnosticCategory.Error, "_0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_reference_7023", "'{0}' implicitly has return type 'any' because it does not have a return type annotation and is referenced directly or indirectly in one of its return expressions."), + Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions: diag(7024, ts.DiagnosticCategory.Error, "Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_ref_7024", "Function implicitly has return type 'any' because it does not have a return type annotation and is referenced directly or indirectly in one of its return expressions."), + Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_type: diag(7025, ts.DiagnosticCategory.Error, "Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_typ_7025", "Generator implicitly has type '{0}' because it does not yield any values. Consider supplying a return type."), + JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists: diag(7026, ts.DiagnosticCategory.Error, "JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists_7026", "JSX element implicitly has type 'any' because no interface 'JSX.{0}' exists."), + Unreachable_code_detected: diag(7027, ts.DiagnosticCategory.Error, "Unreachable_code_detected_7027", "Unreachable code detected.", /*reportsUnnecessary*/ true), + Unused_label: diag(7028, ts.DiagnosticCategory.Error, "Unused_label_7028", "Unused label.", /*reportsUnnecessary*/ true), + Fallthrough_case_in_switch: diag(7029, ts.DiagnosticCategory.Error, "Fallthrough_case_in_switch_7029", "Fallthrough case in switch."), + Not_all_code_paths_return_a_value: diag(7030, ts.DiagnosticCategory.Error, "Not_all_code_paths_return_a_value_7030", "Not all code paths return a value."), + Binding_element_0_implicitly_has_an_1_type: diag(7031, ts.DiagnosticCategory.Error, "Binding_element_0_implicitly_has_an_1_type_7031", "Binding element '{0}' implicitly has an '{1}' type."), + Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation: diag(7032, ts.DiagnosticCategory.Error, "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032", "Property '{0}' implicitly has type 'any', because its set accessor lacks a parameter type annotation."), + Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation: diag(7033, ts.DiagnosticCategory.Error, "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033", "Property '{0}' implicitly has type 'any', because its get accessor lacks a return type annotation."), + Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined: diag(7034, ts.DiagnosticCategory.Error, "Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined_7034", "Variable '{0}' implicitly has type '{1}' in some locations where its type cannot be determined."), + Try_npm_install_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0: diag(7035, ts.DiagnosticCategory.Error, "Try_npm_install_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_mod_7035", "Try `npm install @types/{1}` if it exists or add a new declaration (.d.ts) file containing `declare module '{0}';`"), + Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0: diag(7036, ts.DiagnosticCategory.Error, "Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036", "Dynamic import's specifier must be of type 'string', but here has type '{0}'."), + Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for_all_imports_Implies_allowSyntheticDefaultImports: diag(7037, ts.DiagnosticCategory.Message, "Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for__7037", "Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'."), + Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_Consider_using_a_default_import_or_import_require_here_instead: diag(7038, ts.DiagnosticCategory.Message, "Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cau_7038", "Type originates at this import. A namespace-style import cannot be called or constructed, and will cause a failure at runtime. Consider using a default import or import require here instead."), + Mapped_object_type_implicitly_has_an_any_template_type: diag(7039, ts.DiagnosticCategory.Error, "Mapped_object_type_implicitly_has_an_any_template_type_7039", "Mapped object type implicitly has an 'any' template type."), + If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1: diag(7040, ts.DiagnosticCategory.Error, "If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_S_7040", "If the '{0}' package actually exposes this module, consider sending a pull request to amend 'https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/{1}`"), + The_containing_arrow_function_captures_the_global_value_of_this_which_implicitly_has_type_any: diag(7041, ts.DiagnosticCategory.Error, "The_containing_arrow_function_captures_the_global_value_of_this_which_implicitly_has_type_any_7041", "The containing arrow function captures the global value of 'this' which implicitly has type 'any'."), + Module_0_was_resolved_to_1_but_resolveJsonModule_is_not_used: diag(7042, ts.DiagnosticCategory.Error, "Module_0_was_resolved_to_1_but_resolveJsonModule_is_not_used_7042", "Module '{0}' was resolved to '{1}', but '--resolveJsonModule' is not used."), + Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage: diag(7043, ts.DiagnosticCategory.Suggestion, "Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7043", "Variable '{0}' implicitly has an '{1}' type, but a better type may be inferred from usage."), + Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage: diag(7044, ts.DiagnosticCategory.Suggestion, "Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7044", "Parameter '{0}' implicitly has an '{1}' type, but a better type may be inferred from usage."), + Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage: diag(7045, ts.DiagnosticCategory.Suggestion, "Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7045", "Member '{0}' implicitly has an '{1}' type, but a better type may be inferred from usage."), + Variable_0_implicitly_has_type_1_in_some_locations_but_a_better_type_may_be_inferred_from_usage: diag(7046, ts.DiagnosticCategory.Suggestion, "Variable_0_implicitly_has_type_1_in_some_locations_but_a_better_type_may_be_inferred_from_usage_7046", "Variable '{0}' implicitly has type '{1}' in some locations, but a better type may be inferred from usage."), + Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage: diag(7047, ts.DiagnosticCategory.Suggestion, "Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage_7047", "Rest parameter '{0}' implicitly has an 'any[]' type, but a better type may be inferred from usage."), + Property_0_implicitly_has_type_any_but_a_better_type_for_its_get_accessor_may_be_inferred_from_usage: diag(7048, ts.DiagnosticCategory.Suggestion, "Property_0_implicitly_has_type_any_but_a_better_type_for_its_get_accessor_may_be_inferred_from_usage_7048", "Property '{0}' implicitly has type 'any', but a better type for its get accessor may be inferred from usage."), + Property_0_implicitly_has_type_any_but_a_better_type_for_its_set_accessor_may_be_inferred_from_usage: diag(7049, ts.DiagnosticCategory.Suggestion, "Property_0_implicitly_has_type_any_but_a_better_type_for_its_set_accessor_may_be_inferred_from_usage_7049", "Property '{0}' implicitly has type 'any', but a better type for its set accessor may be inferred from usage."), + _0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage: diag(7050, ts.DiagnosticCategory.Suggestion, "_0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage_7050", "'{0}' implicitly has an '{1}' return type, but a better type may be inferred from usage."), + Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1: diag(7051, ts.DiagnosticCategory.Error, "Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1_7051", "Parameter has a name but no type. Did you mean '{0}: {1}'?"), + You_cannot_rename_this_element: diag(8000, ts.DiagnosticCategory.Error, "You_cannot_rename_this_element_8000", "You cannot rename this element."), + You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library: diag(8001, ts.DiagnosticCategory.Error, "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001", "You cannot rename elements that are defined in the standard TypeScript library."), + import_can_only_be_used_in_a_ts_file: diag(8002, ts.DiagnosticCategory.Error, "import_can_only_be_used_in_a_ts_file_8002", "'import ... =' can only be used in a .ts file."), + export_can_only_be_used_in_a_ts_file: diag(8003, ts.DiagnosticCategory.Error, "export_can_only_be_used_in_a_ts_file_8003", "'export=' can only be used in a .ts file."), + type_parameter_declarations_can_only_be_used_in_a_ts_file: diag(8004, ts.DiagnosticCategory.Error, "type_parameter_declarations_can_only_be_used_in_a_ts_file_8004", "'type parameter declarations' can only be used in a .ts file."), + implements_clauses_can_only_be_used_in_a_ts_file: diag(8005, ts.DiagnosticCategory.Error, "implements_clauses_can_only_be_used_in_a_ts_file_8005", "'implements clauses' can only be used in a .ts file."), + interface_declarations_can_only_be_used_in_a_ts_file: diag(8006, ts.DiagnosticCategory.Error, "interface_declarations_can_only_be_used_in_a_ts_file_8006", "'interface declarations' can only be used in a .ts file."), + module_declarations_can_only_be_used_in_a_ts_file: diag(8007, ts.DiagnosticCategory.Error, "module_declarations_can_only_be_used_in_a_ts_file_8007", "'module declarations' can only be used in a .ts file."), + type_aliases_can_only_be_used_in_a_ts_file: diag(8008, ts.DiagnosticCategory.Error, "type_aliases_can_only_be_used_in_a_ts_file_8008", "'type aliases' can only be used in a .ts file."), + _0_can_only_be_used_in_a_ts_file: diag(8009, ts.DiagnosticCategory.Error, "_0_can_only_be_used_in_a_ts_file_8009", "'{0}' can only be used in a .ts file."), + types_can_only_be_used_in_a_ts_file: diag(8010, ts.DiagnosticCategory.Error, "types_can_only_be_used_in_a_ts_file_8010", "'types' can only be used in a .ts file."), + type_arguments_can_only_be_used_in_a_ts_file: diag(8011, ts.DiagnosticCategory.Error, "type_arguments_can_only_be_used_in_a_ts_file_8011", "'type arguments' can only be used in a .ts file."), + parameter_modifiers_can_only_be_used_in_a_ts_file: diag(8012, ts.DiagnosticCategory.Error, "parameter_modifiers_can_only_be_used_in_a_ts_file_8012", "'parameter modifiers' can only be used in a .ts file."), + non_null_assertions_can_only_be_used_in_a_ts_file: diag(8013, ts.DiagnosticCategory.Error, "non_null_assertions_can_only_be_used_in_a_ts_file_8013", "'non-null assertions' can only be used in a .ts file."), + enum_declarations_can_only_be_used_in_a_ts_file: diag(8015, ts.DiagnosticCategory.Error, "enum_declarations_can_only_be_used_in_a_ts_file_8015", "'enum declarations' can only be used in a .ts file."), + type_assertion_expressions_can_only_be_used_in_a_ts_file: diag(8016, ts.DiagnosticCategory.Error, "type_assertion_expressions_can_only_be_used_in_a_ts_file_8016", "'type assertion expressions' can only be used in a .ts file."), + Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0: diag(8017, ts.DiagnosticCategory.Error, "Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0_8017", "Octal literal types must use ES2015 syntax. Use the syntax '{0}'."), + Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0: diag(8018, ts.DiagnosticCategory.Error, "Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0_8018", "Octal literals are not allowed in enums members initializer. Use the syntax '{0}'."), + Report_errors_in_js_files: diag(8019, ts.DiagnosticCategory.Message, "Report_errors_in_js_files_8019", "Report errors in .js files."), + JSDoc_types_can_only_be_used_inside_documentation_comments: diag(8020, ts.DiagnosticCategory.Error, "JSDoc_types_can_only_be_used_inside_documentation_comments_8020", "JSDoc types can only be used inside documentation comments."), + JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags: diag(8021, ts.DiagnosticCategory.Error, "JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags_8021", "JSDoc '@typedef' tag should either have a type annotation or be followed by '@property' or '@member' tags."), + JSDoc_0_is_not_attached_to_a_class: diag(8022, ts.DiagnosticCategory.Error, "JSDoc_0_is_not_attached_to_a_class_8022", "JSDoc '@{0}' is not attached to a class."), + JSDoc_0_1_does_not_match_the_extends_2_clause: diag(8023, ts.DiagnosticCategory.Error, "JSDoc_0_1_does_not_match_the_extends_2_clause_8023", "JSDoc '@{0} {1}' does not match the 'extends {2}' clause."), + JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name: diag(8024, ts.DiagnosticCategory.Error, "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_8024", "JSDoc '@param' tag has name '{0}', but there is no parameter with that name."), + Class_declarations_cannot_have_more_than_one_augments_or_extends_tag: diag(8025, ts.DiagnosticCategory.Error, "Class_declarations_cannot_have_more_than_one_augments_or_extends_tag_8025", "Class declarations cannot have more than one `@augments` or `@extends` tag."), + Expected_0_type_arguments_provide_these_with_an_extends_tag: diag(8026, ts.DiagnosticCategory.Error, "Expected_0_type_arguments_provide_these_with_an_extends_tag_8026", "Expected {0} type arguments; provide these with an '@extends' tag."), + Expected_0_1_type_arguments_provide_these_with_an_extends_tag: diag(8027, ts.DiagnosticCategory.Error, "Expected_0_1_type_arguments_provide_these_with_an_extends_tag_8027", "Expected {0}-{1} type arguments; provide these with an '@extends' tag."), + JSDoc_may_only_appear_in_the_last_parameter_of_a_signature: diag(8028, ts.DiagnosticCategory.Error, "JSDoc_may_only_appear_in_the_last_parameter_of_a_signature_8028", "JSDoc '...' may only appear in the last parameter of a signature."), + JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_had_an_array_type: diag(8029, ts.DiagnosticCategory.Error, "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_h_8029", "JSDoc '@param' tag has name '{0}', but there is no parameter with that name. It would match 'arguments' if it had an array type."), + The_type_of_a_function_declaration_must_match_the_function_s_signature: diag(8030, ts.DiagnosticCategory.Error, "The_type_of_a_function_declaration_must_match_the_function_s_signature_8030", "The type of a function declaration must match the function's signature."), + You_cannot_rename_a_module_via_a_global_import: diag(8031, ts.DiagnosticCategory.Error, "You_cannot_rename_a_module_via_a_global_import_8031", "You cannot rename a module via a global import."), + Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_class_extends_clause: diag(9002, ts.DiagnosticCategory.Error, "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002", "Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clause."), + class_expressions_are_not_currently_supported: diag(9003, ts.DiagnosticCategory.Error, "class_expressions_are_not_currently_supported_9003", "'class' expressions are not currently supported."), + Language_service_is_disabled: diag(9004, ts.DiagnosticCategory.Error, "Language_service_is_disabled_9004", "Language service is disabled."), + JSX_attributes_must_only_be_assigned_a_non_empty_expression: diag(17000, ts.DiagnosticCategory.Error, "JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000", "JSX attributes must only be assigned a non-empty 'expression'."), + JSX_elements_cannot_have_multiple_attributes_with_the_same_name: diag(17001, ts.DiagnosticCategory.Error, "JSX_elements_cannot_have_multiple_attributes_with_the_same_name_17001", "JSX elements cannot have multiple attributes with the same name."), + Expected_corresponding_JSX_closing_tag_for_0: diag(17002, ts.DiagnosticCategory.Error, "Expected_corresponding_JSX_closing_tag_for_0_17002", "Expected corresponding JSX closing tag for '{0}'."), + JSX_attribute_expected: diag(17003, ts.DiagnosticCategory.Error, "JSX_attribute_expected_17003", "JSX attribute expected."), + Cannot_use_JSX_unless_the_jsx_flag_is_provided: diag(17004, ts.DiagnosticCategory.Error, "Cannot_use_JSX_unless_the_jsx_flag_is_provided_17004", "Cannot use JSX unless the '--jsx' flag is provided."), + A_constructor_cannot_contain_a_super_call_when_its_class_extends_null: diag(17005, ts.DiagnosticCategory.Error, "A_constructor_cannot_contain_a_super_call_when_its_class_extends_null_17005", "A constructor cannot contain a 'super' call when its class extends 'null'."), + An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses: diag(17006, ts.DiagnosticCategory.Error, "An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_ex_17006", "An unary expression with the '{0}' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses."), + A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses: diag(17007, ts.DiagnosticCategory.Error, "A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Con_17007", "A type assertion expression is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses."), + JSX_element_0_has_no_corresponding_closing_tag: diag(17008, ts.DiagnosticCategory.Error, "JSX_element_0_has_no_corresponding_closing_tag_17008", "JSX element '{0}' has no corresponding closing tag."), + super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class: diag(17009, ts.DiagnosticCategory.Error, "super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class_17009", "'super' must be called before accessing 'this' in the constructor of a derived class."), + Unknown_type_acquisition_option_0: diag(17010, ts.DiagnosticCategory.Error, "Unknown_type_acquisition_option_0_17010", "Unknown type acquisition option '{0}'."), + super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class: diag(17011, ts.DiagnosticCategory.Error, "super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class_17011", "'super' must be called before accessing a property of 'super' in the constructor of a derived class."), + _0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2: diag(17012, ts.DiagnosticCategory.Error, "_0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2_17012", "'{0}' is not a valid meta-property for keyword '{1}'. Did you mean '{2}'?"), + Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constructor: diag(17013, ts.DiagnosticCategory.Error, "Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constru_17013", "Meta-property '{0}' is only allowed in the body of a function declaration, function expression, or constructor."), + JSX_fragment_has_no_corresponding_closing_tag: diag(17014, ts.DiagnosticCategory.Error, "JSX_fragment_has_no_corresponding_closing_tag_17014", "JSX fragment has no corresponding closing tag."), + Expected_corresponding_closing_tag_for_JSX_fragment: diag(17015, ts.DiagnosticCategory.Error, "Expected_corresponding_closing_tag_for_JSX_fragment_17015", "Expected corresponding closing tag for JSX fragment."), + JSX_fragment_is_not_supported_when_using_jsxFactory: diag(17016, ts.DiagnosticCategory.Error, "JSX_fragment_is_not_supported_when_using_jsxFactory_17016", "JSX fragment is not supported when using --jsxFactory"), + JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma: diag(17017, ts.DiagnosticCategory.Error, "JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma_17017", "JSX fragment is not supported when using an inline JSX factory pragma"), + Circularity_detected_while_resolving_configuration_Colon_0: diag(18000, ts.DiagnosticCategory.Error, "Circularity_detected_while_resolving_configuration_Colon_0_18000", "Circularity detected while resolving configuration: {0}"), + A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not: diag(18001, ts.DiagnosticCategory.Error, "A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not_18001", "A path in an 'extends' option must be relative or rooted, but '{0}' is not."), + The_files_list_in_config_file_0_is_empty: diag(18002, ts.DiagnosticCategory.Error, "The_files_list_in_config_file_0_is_empty_18002", "The 'files' list in config file '{0}' is empty."), + No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2: diag(18003, ts.DiagnosticCategory.Error, "No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2_18003", "No inputs were found in config file '{0}'. Specified 'include' paths were '{1}' and 'exclude' paths were '{2}'."), + File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module: diag(80001, ts.DiagnosticCategory.Suggestion, "File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module_80001", "File is a CommonJS module; it may be converted to an ES6 module."), + This_constructor_function_may_be_converted_to_a_class_declaration: diag(80002, ts.DiagnosticCategory.Suggestion, "This_constructor_function_may_be_converted_to_a_class_declaration_80002", "This constructor function may be converted to a class declaration."), + Import_may_be_converted_to_a_default_import: diag(80003, ts.DiagnosticCategory.Suggestion, "Import_may_be_converted_to_a_default_import_80003", "Import may be converted to a default import."), + JSDoc_types_may_be_moved_to_TypeScript_types: diag(80004, ts.DiagnosticCategory.Suggestion, "JSDoc_types_may_be_moved_to_TypeScript_types_80004", "JSDoc types may be moved to TypeScript types."), + require_call_may_be_converted_to_an_import: diag(80005, ts.DiagnosticCategory.Suggestion, "require_call_may_be_converted_to_an_import_80005", "'require' call may be converted to an import."), + This_may_be_converted_to_an_async_function: diag(80006, ts.DiagnosticCategory.Suggestion, "This_may_be_converted_to_an_async_function_80006", "This may be converted to an async function."), + Add_missing_super_call: diag(90001, ts.DiagnosticCategory.Message, "Add_missing_super_call_90001", "Add missing 'super()' call"), + Make_super_call_the_first_statement_in_the_constructor: diag(90002, ts.DiagnosticCategory.Message, "Make_super_call_the_first_statement_in_the_constructor_90002", "Make 'super()' call the first statement in the constructor"), + Change_extends_to_implements: diag(90003, ts.DiagnosticCategory.Message, "Change_extends_to_implements_90003", "Change 'extends' to 'implements'"), + Remove_declaration_for_Colon_0: diag(90004, ts.DiagnosticCategory.Message, "Remove_declaration_for_Colon_0_90004", "Remove declaration for: '{0}'"), + Remove_import_from_0: diag(90005, ts.DiagnosticCategory.Message, "Remove_import_from_0_90005", "Remove import from '{0}'"), + Implement_interface_0: diag(90006, ts.DiagnosticCategory.Message, "Implement_interface_0_90006", "Implement interface '{0}'"), + Implement_inherited_abstract_class: diag(90007, ts.DiagnosticCategory.Message, "Implement_inherited_abstract_class_90007", "Implement inherited abstract class"), + Add_0_to_unresolved_variable: diag(90008, ts.DiagnosticCategory.Message, "Add_0_to_unresolved_variable_90008", "Add '{0}.' to unresolved variable"), + Remove_destructuring: diag(90009, ts.DiagnosticCategory.Message, "Remove_destructuring_90009", "Remove destructuring"), + Remove_variable_statement: diag(90010, ts.DiagnosticCategory.Message, "Remove_variable_statement_90010", "Remove variable statement"), + Remove_template_tag: diag(90011, ts.DiagnosticCategory.Message, "Remove_template_tag_90011", "Remove template tag"), + Remove_type_parameters: diag(90012, ts.DiagnosticCategory.Message, "Remove_type_parameters_90012", "Remove type parameters"), + Import_0_from_module_1: diag(90013, ts.DiagnosticCategory.Message, "Import_0_from_module_1_90013", "Import '{0}' from module \"{1}\""), + Change_0_to_1: diag(90014, ts.DiagnosticCategory.Message, "Change_0_to_1_90014", "Change '{0}' to '{1}'"), + Add_0_to_existing_import_declaration_from_1: diag(90015, ts.DiagnosticCategory.Message, "Add_0_to_existing_import_declaration_from_1_90015", "Add '{0}' to existing import declaration from \"{1}\""), + Declare_property_0: diag(90016, ts.DiagnosticCategory.Message, "Declare_property_0_90016", "Declare property '{0}'"), + Add_index_signature_for_property_0: diag(90017, ts.DiagnosticCategory.Message, "Add_index_signature_for_property_0_90017", "Add index signature for property '{0}'"), + Disable_checking_for_this_file: diag(90018, ts.DiagnosticCategory.Message, "Disable_checking_for_this_file_90018", "Disable checking for this file"), + Ignore_this_error_message: diag(90019, ts.DiagnosticCategory.Message, "Ignore_this_error_message_90019", "Ignore this error message"), + Initialize_property_0_in_the_constructor: diag(90020, ts.DiagnosticCategory.Message, "Initialize_property_0_in_the_constructor_90020", "Initialize property '{0}' in the constructor"), + Initialize_static_property_0: diag(90021, ts.DiagnosticCategory.Message, "Initialize_static_property_0_90021", "Initialize static property '{0}'"), + Change_spelling_to_0: diag(90022, ts.DiagnosticCategory.Message, "Change_spelling_to_0_90022", "Change spelling to '{0}'"), + Declare_method_0: diag(90023, ts.DiagnosticCategory.Message, "Declare_method_0_90023", "Declare method '{0}'"), + Declare_static_method_0: diag(90024, ts.DiagnosticCategory.Message, "Declare_static_method_0_90024", "Declare static method '{0}'"), + Prefix_0_with_an_underscore: diag(90025, ts.DiagnosticCategory.Message, "Prefix_0_with_an_underscore_90025", "Prefix '{0}' with an underscore"), + Rewrite_as_the_indexed_access_type_0: diag(90026, ts.DiagnosticCategory.Message, "Rewrite_as_the_indexed_access_type_0_90026", "Rewrite as the indexed access type '{0}'"), + Declare_static_property_0: diag(90027, ts.DiagnosticCategory.Message, "Declare_static_property_0_90027", "Declare static property '{0}'"), + Call_decorator_expression: diag(90028, ts.DiagnosticCategory.Message, "Call_decorator_expression_90028", "Call decorator expression"), + Add_async_modifier_to_containing_function: diag(90029, ts.DiagnosticCategory.Message, "Add_async_modifier_to_containing_function_90029", "Add async modifier to containing function"), + Replace_infer_0_with_unknown: diag(90030, ts.DiagnosticCategory.Message, "Replace_infer_0_with_unknown_90030", "Replace 'infer {0}' with 'unknown'"), + Replace_all_unused_infer_with_unknown: diag(90031, ts.DiagnosticCategory.Message, "Replace_all_unused_infer_with_unknown_90031", "Replace all unused 'infer' with 'unknown'"), + Import_default_0_from_module_1: diag(90032, ts.DiagnosticCategory.Message, "Import_default_0_from_module_1_90032", "Import default '{0}' from module \"{1}\""), + Add_default_import_0_to_existing_import_declaration_from_1: diag(90033, ts.DiagnosticCategory.Message, "Add_default_import_0_to_existing_import_declaration_from_1_90033", "Add default import '{0}' to existing import declaration from \"{1}\""), + Add_parameter_name: diag(90034, ts.DiagnosticCategory.Message, "Add_parameter_name_90034", "Add parameter name"), + Convert_function_to_an_ES2015_class: diag(95001, ts.DiagnosticCategory.Message, "Convert_function_to_an_ES2015_class_95001", "Convert function to an ES2015 class"), + Convert_function_0_to_class: diag(95002, ts.DiagnosticCategory.Message, "Convert_function_0_to_class_95002", "Convert function '{0}' to class"), + Extract_to_0_in_1: diag(95004, ts.DiagnosticCategory.Message, "Extract_to_0_in_1_95004", "Extract to {0} in {1}"), + Extract_function: diag(95005, ts.DiagnosticCategory.Message, "Extract_function_95005", "Extract function"), + Extract_constant: diag(95006, ts.DiagnosticCategory.Message, "Extract_constant_95006", "Extract constant"), + Extract_to_0_in_enclosing_scope: diag(95007, ts.DiagnosticCategory.Message, "Extract_to_0_in_enclosing_scope_95007", "Extract to {0} in enclosing scope"), + Extract_to_0_in_1_scope: diag(95008, ts.DiagnosticCategory.Message, "Extract_to_0_in_1_scope_95008", "Extract to {0} in {1} scope"), + Annotate_with_type_from_JSDoc: diag(95009, ts.DiagnosticCategory.Message, "Annotate_with_type_from_JSDoc_95009", "Annotate with type from JSDoc"), + Annotate_with_types_from_JSDoc: diag(95010, ts.DiagnosticCategory.Message, "Annotate_with_types_from_JSDoc_95010", "Annotate with types from JSDoc"), + Infer_type_of_0_from_usage: diag(95011, ts.DiagnosticCategory.Message, "Infer_type_of_0_from_usage_95011", "Infer type of '{0}' from usage"), + Infer_parameter_types_from_usage: diag(95012, ts.DiagnosticCategory.Message, "Infer_parameter_types_from_usage_95012", "Infer parameter types from usage"), + Convert_to_default_import: diag(95013, ts.DiagnosticCategory.Message, "Convert_to_default_import_95013", "Convert to default import"), + Install_0: diag(95014, ts.DiagnosticCategory.Message, "Install_0_95014", "Install '{0}'"), + Replace_import_with_0: diag(95015, ts.DiagnosticCategory.Message, "Replace_import_with_0_95015", "Replace import with '{0}'."), + Use_synthetic_default_member: diag(95016, ts.DiagnosticCategory.Message, "Use_synthetic_default_member_95016", "Use synthetic 'default' member."), + Convert_to_ES6_module: diag(95017, ts.DiagnosticCategory.Message, "Convert_to_ES6_module_95017", "Convert to ES6 module"), + Add_undefined_type_to_property_0: diag(95018, ts.DiagnosticCategory.Message, "Add_undefined_type_to_property_0_95018", "Add 'undefined' type to property '{0}'"), + Add_initializer_to_property_0: diag(95019, ts.DiagnosticCategory.Message, "Add_initializer_to_property_0_95019", "Add initializer to property '{0}'"), + Add_definite_assignment_assertion_to_property_0: diag(95020, ts.DiagnosticCategory.Message, "Add_definite_assignment_assertion_to_property_0_95020", "Add definite assignment assertion to property '{0}'"), + Add_all_missing_members: diag(95022, ts.DiagnosticCategory.Message, "Add_all_missing_members_95022", "Add all missing members"), + Infer_all_types_from_usage: diag(95023, ts.DiagnosticCategory.Message, "Infer_all_types_from_usage_95023", "Infer all types from usage"), + Delete_all_unused_declarations: diag(95024, ts.DiagnosticCategory.Message, "Delete_all_unused_declarations_95024", "Delete all unused declarations"), + Prefix_all_unused_declarations_with_where_possible: diag(95025, ts.DiagnosticCategory.Message, "Prefix_all_unused_declarations_with_where_possible_95025", "Prefix all unused declarations with '_' where possible"), + Fix_all_detected_spelling_errors: diag(95026, ts.DiagnosticCategory.Message, "Fix_all_detected_spelling_errors_95026", "Fix all detected spelling errors"), + Add_initializers_to_all_uninitialized_properties: diag(95027, ts.DiagnosticCategory.Message, "Add_initializers_to_all_uninitialized_properties_95027", "Add initializers to all uninitialized properties"), + Add_definite_assignment_assertions_to_all_uninitialized_properties: diag(95028, ts.DiagnosticCategory.Message, "Add_definite_assignment_assertions_to_all_uninitialized_properties_95028", "Add definite assignment assertions to all uninitialized properties"), + Add_undefined_type_to_all_uninitialized_properties: diag(95029, ts.DiagnosticCategory.Message, "Add_undefined_type_to_all_uninitialized_properties_95029", "Add undefined type to all uninitialized properties"), + Change_all_jsdoc_style_types_to_TypeScript: diag(95030, ts.DiagnosticCategory.Message, "Change_all_jsdoc_style_types_to_TypeScript_95030", "Change all jsdoc-style types to TypeScript"), + Change_all_jsdoc_style_types_to_TypeScript_and_add_undefined_to_nullable_types: diag(95031, ts.DiagnosticCategory.Message, "Change_all_jsdoc_style_types_to_TypeScript_and_add_undefined_to_nullable_types_95031", "Change all jsdoc-style types to TypeScript (and add '| undefined' to nullable types)"), + Implement_all_unimplemented_interfaces: diag(95032, ts.DiagnosticCategory.Message, "Implement_all_unimplemented_interfaces_95032", "Implement all unimplemented interfaces"), + Install_all_missing_types_packages: diag(95033, ts.DiagnosticCategory.Message, "Install_all_missing_types_packages_95033", "Install all missing types packages"), + Rewrite_all_as_indexed_access_types: diag(95034, ts.DiagnosticCategory.Message, "Rewrite_all_as_indexed_access_types_95034", "Rewrite all as indexed access types"), + Convert_all_to_default_imports: diag(95035, ts.DiagnosticCategory.Message, "Convert_all_to_default_imports_95035", "Convert all to default imports"), + Make_all_super_calls_the_first_statement_in_their_constructor: diag(95036, ts.DiagnosticCategory.Message, "Make_all_super_calls_the_first_statement_in_their_constructor_95036", "Make all 'super()' calls the first statement in their constructor"), + Add_qualifier_to_all_unresolved_variables_matching_a_member_name: diag(95037, ts.DiagnosticCategory.Message, "Add_qualifier_to_all_unresolved_variables_matching_a_member_name_95037", "Add qualifier to all unresolved variables matching a member name"), + Change_all_extended_interfaces_to_implements: diag(95038, ts.DiagnosticCategory.Message, "Change_all_extended_interfaces_to_implements_95038", "Change all extended interfaces to 'implements'"), + Add_all_missing_super_calls: diag(95039, ts.DiagnosticCategory.Message, "Add_all_missing_super_calls_95039", "Add all missing super calls"), + Implement_all_inherited_abstract_classes: diag(95040, ts.DiagnosticCategory.Message, "Implement_all_inherited_abstract_classes_95040", "Implement all inherited abstract classes"), + Add_all_missing_async_modifiers: diag(95041, ts.DiagnosticCategory.Message, "Add_all_missing_async_modifiers_95041", "Add all missing 'async' modifiers"), + Add_ts_ignore_to_all_error_messages: diag(95042, ts.DiagnosticCategory.Message, "Add_ts_ignore_to_all_error_messages_95042", "Add '@ts-ignore' to all error messages"), + Annotate_everything_with_types_from_JSDoc: diag(95043, ts.DiagnosticCategory.Message, "Annotate_everything_with_types_from_JSDoc_95043", "Annotate everything with types from JSDoc"), + Add_to_all_uncalled_decorators: diag(95044, ts.DiagnosticCategory.Message, "Add_to_all_uncalled_decorators_95044", "Add '()' to all uncalled decorators"), + Convert_all_constructor_functions_to_classes: diag(95045, ts.DiagnosticCategory.Message, "Convert_all_constructor_functions_to_classes_95045", "Convert all constructor functions to classes"), + Generate_get_and_set_accessors: diag(95046, ts.DiagnosticCategory.Message, "Generate_get_and_set_accessors_95046", "Generate 'get' and 'set' accessors"), + Convert_require_to_import: diag(95047, ts.DiagnosticCategory.Message, "Convert_require_to_import_95047", "Convert 'require' to 'import'"), + Convert_all_require_to_import: diag(95048, ts.DiagnosticCategory.Message, "Convert_all_require_to_import_95048", "Convert all 'require' to 'import'"), + Move_to_a_new_file: diag(95049, ts.DiagnosticCategory.Message, "Move_to_a_new_file_95049", "Move to a new file"), + Remove_unreachable_code: diag(95050, ts.DiagnosticCategory.Message, "Remove_unreachable_code_95050", "Remove unreachable code"), + Remove_all_unreachable_code: diag(95051, ts.DiagnosticCategory.Message, "Remove_all_unreachable_code_95051", "Remove all unreachable code"), + Add_missing_typeof: diag(95052, ts.DiagnosticCategory.Message, "Add_missing_typeof_95052", "Add missing 'typeof'"), + Remove_unused_label: diag(95053, ts.DiagnosticCategory.Message, "Remove_unused_label_95053", "Remove unused label"), + Remove_all_unused_labels: diag(95054, ts.DiagnosticCategory.Message, "Remove_all_unused_labels_95054", "Remove all unused labels"), + Convert_0_to_mapped_object_type: diag(95055, ts.DiagnosticCategory.Message, "Convert_0_to_mapped_object_type_95055", "Convert '{0}' to mapped object type"), + Convert_namespace_import_to_named_imports: diag(95056, ts.DiagnosticCategory.Message, "Convert_namespace_import_to_named_imports_95056", "Convert namespace import to named imports"), + Convert_named_imports_to_namespace_import: diag(95057, ts.DiagnosticCategory.Message, "Convert_named_imports_to_namespace_import_95057", "Convert named imports to namespace import"), + Add_or_remove_braces_in_an_arrow_function: diag(95058, ts.DiagnosticCategory.Message, "Add_or_remove_braces_in_an_arrow_function_95058", "Add or remove braces in an arrow function"), + Add_braces_to_arrow_function: diag(95059, ts.DiagnosticCategory.Message, "Add_braces_to_arrow_function_95059", "Add braces to arrow function"), + Remove_braces_from_arrow_function: diag(95060, ts.DiagnosticCategory.Message, "Remove_braces_from_arrow_function_95060", "Remove braces from arrow function"), + Convert_default_export_to_named_export: diag(95061, ts.DiagnosticCategory.Message, "Convert_default_export_to_named_export_95061", "Convert default export to named export"), + Convert_named_export_to_default_export: diag(95062, ts.DiagnosticCategory.Message, "Convert_named_export_to_default_export_95062", "Convert named export to default export"), + Add_missing_enum_member_0: diag(95063, ts.DiagnosticCategory.Message, "Add_missing_enum_member_0_95063", "Add missing enum member '{0}'"), + Add_all_missing_imports: diag(95064, ts.DiagnosticCategory.Message, "Add_all_missing_imports_95064", "Add all missing imports"), + Convert_to_async_function: diag(95065, ts.DiagnosticCategory.Message, "Convert_to_async_function_95065", "Convert to async function"), + Convert_all_to_async_functions: diag(95066, ts.DiagnosticCategory.Message, "Convert_all_to_async_functions_95066", "Convert all to async functions"), + Generate_types_for_0: diag(95067, ts.DiagnosticCategory.Message, "Generate_types_for_0_95067", "Generate types for '{0}'"), + Generate_types_for_all_packages_without_types: diag(95068, ts.DiagnosticCategory.Message, "Generate_types_for_all_packages_without_types_95068", "Generate types for all packages without types"), + Add_unknown_conversion_for_non_overlapping_types: diag(95069, ts.DiagnosticCategory.Message, "Add_unknown_conversion_for_non_overlapping_types_95069", "Add 'unknown' conversion for non-overlapping types"), + Add_unknown_to_all_conversions_of_non_overlapping_types: diag(95070, ts.DiagnosticCategory.Message, "Add_unknown_to_all_conversions_of_non_overlapping_types_95070", "Add 'unknown' to all conversions of non-overlapping types"), + Add_missing_new_operator_to_call: diag(95071, ts.DiagnosticCategory.Message, "Add_missing_new_operator_to_call_95071", "Add missing 'new' operator to call"), + Add_missing_new_operator_to_all_calls: diag(95072, ts.DiagnosticCategory.Message, "Add_missing_new_operator_to_all_calls_95072", "Add missing 'new' operator to all calls"), + Add_names_to_all_parameters_without_names: diag(95073, ts.DiagnosticCategory.Message, "Add_names_to_all_parameters_without_names_95073", "Add names to all parameters without names"), + }; +})(ts || (ts = {})); +var ts; +(function (ts) { + var _a; + /* @internal */ + function tokenIsIdentifierOrKeyword(token) { + return token >= 72 /* Identifier */; + } + ts.tokenIsIdentifierOrKeyword = tokenIsIdentifierOrKeyword; + /* @internal */ + function tokenIsIdentifierOrKeywordOrGreaterThan(token) { + return token === 30 /* GreaterThanToken */ || tokenIsIdentifierOrKeyword(token); + } + ts.tokenIsIdentifierOrKeywordOrGreaterThan = tokenIsIdentifierOrKeywordOrGreaterThan; + var textToKeywordObj = (_a = { + abstract: 118 /* AbstractKeyword */, + any: 120 /* AnyKeyword */, + as: 119 /* AsKeyword */, + bigint: 146 /* BigIntKeyword */, + boolean: 123 /* BooleanKeyword */, + break: 73 /* BreakKeyword */, + case: 74 /* CaseKeyword */, + catch: 75 /* CatchKeyword */, + class: 76 /* ClassKeyword */, + continue: 78 /* ContinueKeyword */, + const: 77 /* ConstKeyword */ + }, + _a["" + "constructor"] = 124 /* ConstructorKeyword */, + _a.debugger = 79 /* DebuggerKeyword */, + _a.declare = 125 /* DeclareKeyword */, + _a.default = 80 /* DefaultKeyword */, + _a.delete = 81 /* DeleteKeyword */, + _a.do = 82 /* DoKeyword */, + _a.else = 83 /* ElseKeyword */, + _a.enum = 84 /* EnumKeyword */, + _a.export = 85 /* ExportKeyword */, + _a.extends = 86 /* ExtendsKeyword */, + _a.false = 87 /* FalseKeyword */, + _a.finally = 88 /* FinallyKeyword */, + _a.for = 89 /* ForKeyword */, + _a.from = 144 /* FromKeyword */, + _a.function = 90 /* FunctionKeyword */, + _a.get = 126 /* GetKeyword */, + _a.if = 91 /* IfKeyword */, + _a.implements = 109 /* ImplementsKeyword */, + _a.import = 92 /* ImportKeyword */, + _a.in = 93 /* InKeyword */, + _a.infer = 127 /* InferKeyword */, + _a.instanceof = 94 /* InstanceOfKeyword */, + _a.interface = 110 /* InterfaceKeyword */, + _a.is = 128 /* IsKeyword */, + _a.keyof = 129 /* KeyOfKeyword */, + _a.let = 111 /* LetKeyword */, + _a.module = 130 /* ModuleKeyword */, + _a.namespace = 131 /* NamespaceKeyword */, + _a.never = 132 /* NeverKeyword */, + _a.new = 95 /* NewKeyword */, + _a.null = 96 /* NullKeyword */, + _a.number = 135 /* NumberKeyword */, + _a.object = 136 /* ObjectKeyword */, + _a.package = 112 /* PackageKeyword */, + _a.private = 113 /* PrivateKeyword */, + _a.protected = 114 /* ProtectedKeyword */, + _a.public = 115 /* PublicKeyword */, + _a.readonly = 133 /* ReadonlyKeyword */, + _a.require = 134 /* RequireKeyword */, + _a.global = 145 /* GlobalKeyword */, + _a.return = 97 /* ReturnKeyword */, + _a.set = 137 /* SetKeyword */, + _a.static = 116 /* StaticKeyword */, + _a.string = 138 /* StringKeyword */, + _a.super = 98 /* SuperKeyword */, + _a.switch = 99 /* SwitchKeyword */, + _a.symbol = 139 /* SymbolKeyword */, + _a.this = 100 /* ThisKeyword */, + _a.throw = 101 /* ThrowKeyword */, + _a.true = 102 /* TrueKeyword */, + _a.try = 103 /* TryKeyword */, + _a.type = 140 /* TypeKeyword */, + _a.typeof = 104 /* TypeOfKeyword */, + _a.undefined = 141 /* UndefinedKeyword */, + _a.unique = 142 /* UniqueKeyword */, + _a.unknown = 143 /* UnknownKeyword */, + _a.var = 105 /* VarKeyword */, + _a.void = 106 /* VoidKeyword */, + _a.while = 107 /* WhileKeyword */, + _a.with = 108 /* WithKeyword */, + _a.yield = 117 /* YieldKeyword */, + _a.async = 121 /* AsyncKeyword */, + _a.await = 122 /* AwaitKeyword */, + _a.of = 147 /* OfKeyword */, + _a); + var textToKeyword = ts.createMapFromTemplate(textToKeywordObj); + var textToToken = ts.createMapFromTemplate(__assign({}, textToKeywordObj, { "{": 18 /* OpenBraceToken */, "}": 19 /* CloseBraceToken */, "(": 20 /* OpenParenToken */, ")": 21 /* CloseParenToken */, "[": 22 /* OpenBracketToken */, "]": 23 /* CloseBracketToken */, ".": 24 /* DotToken */, "...": 25 /* DotDotDotToken */, ";": 26 /* SemicolonToken */, ",": 27 /* CommaToken */, "<": 28 /* LessThanToken */, ">": 30 /* GreaterThanToken */, "<=": 31 /* LessThanEqualsToken */, ">=": 32 /* GreaterThanEqualsToken */, "==": 33 /* EqualsEqualsToken */, "!=": 34 /* ExclamationEqualsToken */, "===": 35 /* EqualsEqualsEqualsToken */, "!==": 36 /* ExclamationEqualsEqualsToken */, "=>": 37 /* EqualsGreaterThanToken */, "+": 38 /* PlusToken */, "-": 39 /* MinusToken */, "**": 41 /* AsteriskAsteriskToken */, "*": 40 /* AsteriskToken */, "/": 42 /* SlashToken */, "%": 43 /* PercentToken */, "++": 44 /* PlusPlusToken */, "--": 45 /* MinusMinusToken */, "<<": 46 /* LessThanLessThanToken */, ">": 47 /* GreaterThanGreaterThanToken */, ">>>": 48 /* GreaterThanGreaterThanGreaterThanToken */, "&": 49 /* AmpersandToken */, "|": 50 /* BarToken */, "^": 51 /* CaretToken */, "!": 52 /* ExclamationToken */, "~": 53 /* TildeToken */, "&&": 54 /* AmpersandAmpersandToken */, "||": 55 /* BarBarToken */, "?": 56 /* QuestionToken */, ":": 57 /* ColonToken */, "=": 59 /* EqualsToken */, "+=": 60 /* PlusEqualsToken */, "-=": 61 /* MinusEqualsToken */, "*=": 62 /* AsteriskEqualsToken */, "**=": 63 /* AsteriskAsteriskEqualsToken */, "/=": 64 /* SlashEqualsToken */, "%=": 65 /* PercentEqualsToken */, "<<=": 66 /* LessThanLessThanEqualsToken */, ">>=": 67 /* GreaterThanGreaterThanEqualsToken */, ">>>=": 68 /* GreaterThanGreaterThanGreaterThanEqualsToken */, "&=": 69 /* AmpersandEqualsToken */, "|=": 70 /* BarEqualsToken */, "^=": 71 /* CaretEqualsToken */, "@": 58 /* AtToken */ })); + /* + As per ECMAScript Language Specification 3th Edition, Section 7.6: Identifiers + IdentifierStart :: + Can contain Unicode 3.0.0 categories: + Uppercase letter (Lu), + Lowercase letter (Ll), + Titlecase letter (Lt), + Modifier letter (Lm), + Other letter (Lo), or + Letter number (Nl). + IdentifierPart :: = + Can contain IdentifierStart + Unicode 3.0.0 categories: + Non-spacing mark (Mn), + Combining spacing mark (Mc), + Decimal number (Nd), or + Connector punctuation (Pc). + + Codepoint ranges for ES3 Identifiers are extracted from the Unicode 3.0.0 specification at: + http://www.unicode.org/Public/3.0-Update/UnicodeData-3.0.0.txt + */ + var unicodeES3IdentifierStart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 543, 546, 563, 592, 685, 688, 696, 699, 705, 720, 721, 736, 740, 750, 750, 890, 890, 902, 902, 904, 906, 908, 908, 910, 929, 931, 974, 976, 983, 986, 1011, 1024, 1153, 1164, 1220, 1223, 1224, 1227, 1228, 1232, 1269, 1272, 1273, 1329, 1366, 1369, 1369, 1377, 1415, 1488, 1514, 1520, 1522, 1569, 1594, 1600, 1610, 1649, 1747, 1749, 1749, 1765, 1766, 1786, 1788, 1808, 1808, 1810, 1836, 1920, 1957, 2309, 2361, 2365, 2365, 2384, 2384, 2392, 2401, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2524, 2525, 2527, 2529, 2544, 2545, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2649, 2652, 2654, 2654, 2674, 2676, 2693, 2699, 2701, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2749, 2749, 2768, 2768, 2784, 2784, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2870, 2873, 2877, 2877, 2908, 2909, 2911, 2913, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 2997, 2999, 3001, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3168, 3169, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3294, 3294, 3296, 3297, 3333, 3340, 3342, 3344, 3346, 3368, 3370, 3385, 3424, 3425, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3585, 3632, 3634, 3635, 3648, 3654, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3760, 3762, 3763, 3773, 3773, 3776, 3780, 3782, 3782, 3804, 3805, 3840, 3840, 3904, 3911, 3913, 3946, 3976, 3979, 4096, 4129, 4131, 4135, 4137, 4138, 4176, 4181, 4256, 4293, 4304, 4342, 4352, 4441, 4447, 4514, 4520, 4601, 4608, 4614, 4616, 4678, 4680, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4742, 4744, 4744, 4746, 4749, 4752, 4782, 4784, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4814, 4816, 4822, 4824, 4846, 4848, 4878, 4880, 4880, 4882, 4885, 4888, 4894, 4896, 4934, 4936, 4954, 5024, 5108, 5121, 5740, 5743, 5750, 5761, 5786, 5792, 5866, 6016, 6067, 6176, 6263, 6272, 6312, 7680, 7835, 7840, 7929, 7936, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8319, 8319, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8497, 8499, 8505, 8544, 8579, 12293, 12295, 12321, 12329, 12337, 12341, 12344, 12346, 12353, 12436, 12445, 12446, 12449, 12538, 12540, 12542, 12549, 12588, 12593, 12686, 12704, 12727, 13312, 19893, 19968, 40869, 40960, 42124, 44032, 55203, 63744, 64045, 64256, 64262, 64275, 64279, 64285, 64285, 64287, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65136, 65138, 65140, 65140, 65142, 65276, 65313, 65338, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500,]; + var unicodeES3IdentifierPart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 543, 546, 563, 592, 685, 688, 696, 699, 705, 720, 721, 736, 740, 750, 750, 768, 846, 864, 866, 890, 890, 902, 902, 904, 906, 908, 908, 910, 929, 931, 974, 976, 983, 986, 1011, 1024, 1153, 1155, 1158, 1164, 1220, 1223, 1224, 1227, 1228, 1232, 1269, 1272, 1273, 1329, 1366, 1369, 1369, 1377, 1415, 1425, 1441, 1443, 1465, 1467, 1469, 1471, 1471, 1473, 1474, 1476, 1476, 1488, 1514, 1520, 1522, 1569, 1594, 1600, 1621, 1632, 1641, 1648, 1747, 1749, 1756, 1759, 1768, 1770, 1773, 1776, 1788, 1808, 1836, 1840, 1866, 1920, 1968, 2305, 2307, 2309, 2361, 2364, 2381, 2384, 2388, 2392, 2403, 2406, 2415, 2433, 2435, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2492, 2492, 2494, 2500, 2503, 2504, 2507, 2509, 2519, 2519, 2524, 2525, 2527, 2531, 2534, 2545, 2562, 2562, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2620, 2620, 2622, 2626, 2631, 2632, 2635, 2637, 2649, 2652, 2654, 2654, 2662, 2676, 2689, 2691, 2693, 2699, 2701, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2748, 2757, 2759, 2761, 2763, 2765, 2768, 2768, 2784, 2784, 2790, 2799, 2817, 2819, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2870, 2873, 2876, 2883, 2887, 2888, 2891, 2893, 2902, 2903, 2908, 2909, 2911, 2913, 2918, 2927, 2946, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 2997, 2999, 3001, 3006, 3010, 3014, 3016, 3018, 3021, 3031, 3031, 3047, 3055, 3073, 3075, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3134, 3140, 3142, 3144, 3146, 3149, 3157, 3158, 3168, 3169, 3174, 3183, 3202, 3203, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3262, 3268, 3270, 3272, 3274, 3277, 3285, 3286, 3294, 3294, 3296, 3297, 3302, 3311, 3330, 3331, 3333, 3340, 3342, 3344, 3346, 3368, 3370, 3385, 3390, 3395, 3398, 3400, 3402, 3405, 3415, 3415, 3424, 3425, 3430, 3439, 3458, 3459, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3530, 3530, 3535, 3540, 3542, 3542, 3544, 3551, 3570, 3571, 3585, 3642, 3648, 3662, 3664, 3673, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3769, 3771, 3773, 3776, 3780, 3782, 3782, 3784, 3789, 3792, 3801, 3804, 3805, 3840, 3840, 3864, 3865, 3872, 3881, 3893, 3893, 3895, 3895, 3897, 3897, 3902, 3911, 3913, 3946, 3953, 3972, 3974, 3979, 3984, 3991, 3993, 4028, 4038, 4038, 4096, 4129, 4131, 4135, 4137, 4138, 4140, 4146, 4150, 4153, 4160, 4169, 4176, 4185, 4256, 4293, 4304, 4342, 4352, 4441, 4447, 4514, 4520, 4601, 4608, 4614, 4616, 4678, 4680, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4742, 4744, 4744, 4746, 4749, 4752, 4782, 4784, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4814, 4816, 4822, 4824, 4846, 4848, 4878, 4880, 4880, 4882, 4885, 4888, 4894, 4896, 4934, 4936, 4954, 4969, 4977, 5024, 5108, 5121, 5740, 5743, 5750, 5761, 5786, 5792, 5866, 6016, 6099, 6112, 6121, 6160, 6169, 6176, 6263, 6272, 6313, 7680, 7835, 7840, 7929, 7936, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8255, 8256, 8319, 8319, 8400, 8412, 8417, 8417, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8497, 8499, 8505, 8544, 8579, 12293, 12295, 12321, 12335, 12337, 12341, 12344, 12346, 12353, 12436, 12441, 12442, 12445, 12446, 12449, 12542, 12549, 12588, 12593, 12686, 12704, 12727, 13312, 19893, 19968, 40869, 40960, 42124, 44032, 55203, 63744, 64045, 64256, 64262, 64275, 64279, 64285, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65056, 65059, 65075, 65076, 65101, 65103, 65136, 65138, 65140, 65140, 65142, 65276, 65296, 65305, 65313, 65338, 65343, 65343, 65345, 65370, 65381, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500,]; + /* + As per ECMAScript Language Specification 5th Edition, Section 7.6: ISyntaxToken Names and Identifiers + IdentifierStart :: + Can contain Unicode 6.2 categories: + Uppercase letter (Lu), + Lowercase letter (Ll), + Titlecase letter (Lt), + Modifier letter (Lm), + Other letter (Lo), or + Letter number (Nl). + IdentifierPart :: + Can contain IdentifierStart + Unicode 6.2 categories: + Non-spacing mark (Mn), + Combining spacing mark (Mc), + Decimal number (Nd), + Connector punctuation (Pc), + , or + . + + Codepoint ranges for ES5 Identifiers are extracted from the Unicode 6.2 specification at: + http://www.unicode.org/Public/6.2.0/ucd/UnicodeData.txt + */ + var unicodeES5IdentifierStart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 705, 710, 721, 736, 740, 748, 748, 750, 750, 880, 884, 886, 887, 890, 893, 902, 902, 904, 906, 908, 908, 910, 929, 931, 1013, 1015, 1153, 1162, 1319, 1329, 1366, 1369, 1369, 1377, 1415, 1488, 1514, 1520, 1522, 1568, 1610, 1646, 1647, 1649, 1747, 1749, 1749, 1765, 1766, 1774, 1775, 1786, 1788, 1791, 1791, 1808, 1808, 1810, 1839, 1869, 1957, 1969, 1969, 1994, 2026, 2036, 2037, 2042, 2042, 2048, 2069, 2074, 2074, 2084, 2084, 2088, 2088, 2112, 2136, 2208, 2208, 2210, 2220, 2308, 2361, 2365, 2365, 2384, 2384, 2392, 2401, 2417, 2423, 2425, 2431, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2493, 2493, 2510, 2510, 2524, 2525, 2527, 2529, 2544, 2545, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2649, 2652, 2654, 2654, 2674, 2676, 2693, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2749, 2749, 2768, 2768, 2784, 2785, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2869, 2873, 2877, 2877, 2908, 2909, 2911, 2913, 2929, 2929, 2947, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 3001, 3024, 3024, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3133, 3133, 3160, 3161, 3168, 3169, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3261, 3261, 3294, 3294, 3296, 3297, 3313, 3314, 3333, 3340, 3342, 3344, 3346, 3386, 3389, 3389, 3406, 3406, 3424, 3425, 3450, 3455, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3585, 3632, 3634, 3635, 3648, 3654, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3760, 3762, 3763, 3773, 3773, 3776, 3780, 3782, 3782, 3804, 3807, 3840, 3840, 3904, 3911, 3913, 3948, 3976, 3980, 4096, 4138, 4159, 4159, 4176, 4181, 4186, 4189, 4193, 4193, 4197, 4198, 4206, 4208, 4213, 4225, 4238, 4238, 4256, 4293, 4295, 4295, 4301, 4301, 4304, 4346, 4348, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4744, 4746, 4749, 4752, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4822, 4824, 4880, 4882, 4885, 4888, 4954, 4992, 5007, 5024, 5108, 5121, 5740, 5743, 5759, 5761, 5786, 5792, 5866, 5870, 5872, 5888, 5900, 5902, 5905, 5920, 5937, 5952, 5969, 5984, 5996, 5998, 6000, 6016, 6067, 6103, 6103, 6108, 6108, 6176, 6263, 6272, 6312, 6314, 6314, 6320, 6389, 6400, 6428, 6480, 6509, 6512, 6516, 6528, 6571, 6593, 6599, 6656, 6678, 6688, 6740, 6823, 6823, 6917, 6963, 6981, 6987, 7043, 7072, 7086, 7087, 7098, 7141, 7168, 7203, 7245, 7247, 7258, 7293, 7401, 7404, 7406, 7409, 7413, 7414, 7424, 7615, 7680, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8305, 8305, 8319, 8319, 8336, 8348, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8505, 8508, 8511, 8517, 8521, 8526, 8526, 8544, 8584, 11264, 11310, 11312, 11358, 11360, 11492, 11499, 11502, 11506, 11507, 11520, 11557, 11559, 11559, 11565, 11565, 11568, 11623, 11631, 11631, 11648, 11670, 11680, 11686, 11688, 11694, 11696, 11702, 11704, 11710, 11712, 11718, 11720, 11726, 11728, 11734, 11736, 11742, 11823, 11823, 12293, 12295, 12321, 12329, 12337, 12341, 12344, 12348, 12353, 12438, 12445, 12447, 12449, 12538, 12540, 12543, 12549, 12589, 12593, 12686, 12704, 12730, 12784, 12799, 13312, 19893, 19968, 40908, 40960, 42124, 42192, 42237, 42240, 42508, 42512, 42527, 42538, 42539, 42560, 42606, 42623, 42647, 42656, 42735, 42775, 42783, 42786, 42888, 42891, 42894, 42896, 42899, 42912, 42922, 43000, 43009, 43011, 43013, 43015, 43018, 43020, 43042, 43072, 43123, 43138, 43187, 43250, 43255, 43259, 43259, 43274, 43301, 43312, 43334, 43360, 43388, 43396, 43442, 43471, 43471, 43520, 43560, 43584, 43586, 43588, 43595, 43616, 43638, 43642, 43642, 43648, 43695, 43697, 43697, 43701, 43702, 43705, 43709, 43712, 43712, 43714, 43714, 43739, 43741, 43744, 43754, 43762, 43764, 43777, 43782, 43785, 43790, 43793, 43798, 43808, 43814, 43816, 43822, 43968, 44002, 44032, 55203, 55216, 55238, 55243, 55291, 63744, 64109, 64112, 64217, 64256, 64262, 64275, 64279, 64285, 64285, 64287, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65136, 65140, 65142, 65276, 65313, 65338, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500,]; + var unicodeES5IdentifierPart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 705, 710, 721, 736, 740, 748, 748, 750, 750, 768, 884, 886, 887, 890, 893, 902, 902, 904, 906, 908, 908, 910, 929, 931, 1013, 1015, 1153, 1155, 1159, 1162, 1319, 1329, 1366, 1369, 1369, 1377, 1415, 1425, 1469, 1471, 1471, 1473, 1474, 1476, 1477, 1479, 1479, 1488, 1514, 1520, 1522, 1552, 1562, 1568, 1641, 1646, 1747, 1749, 1756, 1759, 1768, 1770, 1788, 1791, 1791, 1808, 1866, 1869, 1969, 1984, 2037, 2042, 2042, 2048, 2093, 2112, 2139, 2208, 2208, 2210, 2220, 2276, 2302, 2304, 2403, 2406, 2415, 2417, 2423, 2425, 2431, 2433, 2435, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2492, 2500, 2503, 2504, 2507, 2510, 2519, 2519, 2524, 2525, 2527, 2531, 2534, 2545, 2561, 2563, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2620, 2620, 2622, 2626, 2631, 2632, 2635, 2637, 2641, 2641, 2649, 2652, 2654, 2654, 2662, 2677, 2689, 2691, 2693, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2748, 2757, 2759, 2761, 2763, 2765, 2768, 2768, 2784, 2787, 2790, 2799, 2817, 2819, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2869, 2873, 2876, 2884, 2887, 2888, 2891, 2893, 2902, 2903, 2908, 2909, 2911, 2915, 2918, 2927, 2929, 2929, 2946, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 3001, 3006, 3010, 3014, 3016, 3018, 3021, 3024, 3024, 3031, 3031, 3046, 3055, 3073, 3075, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3133, 3140, 3142, 3144, 3146, 3149, 3157, 3158, 3160, 3161, 3168, 3171, 3174, 3183, 3202, 3203, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3260, 3268, 3270, 3272, 3274, 3277, 3285, 3286, 3294, 3294, 3296, 3299, 3302, 3311, 3313, 3314, 3330, 3331, 3333, 3340, 3342, 3344, 3346, 3386, 3389, 3396, 3398, 3400, 3402, 3406, 3415, 3415, 3424, 3427, 3430, 3439, 3450, 3455, 3458, 3459, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3530, 3530, 3535, 3540, 3542, 3542, 3544, 3551, 3570, 3571, 3585, 3642, 3648, 3662, 3664, 3673, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3769, 3771, 3773, 3776, 3780, 3782, 3782, 3784, 3789, 3792, 3801, 3804, 3807, 3840, 3840, 3864, 3865, 3872, 3881, 3893, 3893, 3895, 3895, 3897, 3897, 3902, 3911, 3913, 3948, 3953, 3972, 3974, 3991, 3993, 4028, 4038, 4038, 4096, 4169, 4176, 4253, 4256, 4293, 4295, 4295, 4301, 4301, 4304, 4346, 4348, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4744, 4746, 4749, 4752, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4822, 4824, 4880, 4882, 4885, 4888, 4954, 4957, 4959, 4992, 5007, 5024, 5108, 5121, 5740, 5743, 5759, 5761, 5786, 5792, 5866, 5870, 5872, 5888, 5900, 5902, 5908, 5920, 5940, 5952, 5971, 5984, 5996, 5998, 6000, 6002, 6003, 6016, 6099, 6103, 6103, 6108, 6109, 6112, 6121, 6155, 6157, 6160, 6169, 6176, 6263, 6272, 6314, 6320, 6389, 6400, 6428, 6432, 6443, 6448, 6459, 6470, 6509, 6512, 6516, 6528, 6571, 6576, 6601, 6608, 6617, 6656, 6683, 6688, 6750, 6752, 6780, 6783, 6793, 6800, 6809, 6823, 6823, 6912, 6987, 6992, 7001, 7019, 7027, 7040, 7155, 7168, 7223, 7232, 7241, 7245, 7293, 7376, 7378, 7380, 7414, 7424, 7654, 7676, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8204, 8205, 8255, 8256, 8276, 8276, 8305, 8305, 8319, 8319, 8336, 8348, 8400, 8412, 8417, 8417, 8421, 8432, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8505, 8508, 8511, 8517, 8521, 8526, 8526, 8544, 8584, 11264, 11310, 11312, 11358, 11360, 11492, 11499, 11507, 11520, 11557, 11559, 11559, 11565, 11565, 11568, 11623, 11631, 11631, 11647, 11670, 11680, 11686, 11688, 11694, 11696, 11702, 11704, 11710, 11712, 11718, 11720, 11726, 11728, 11734, 11736, 11742, 11744, 11775, 11823, 11823, 12293, 12295, 12321, 12335, 12337, 12341, 12344, 12348, 12353, 12438, 12441, 12442, 12445, 12447, 12449, 12538, 12540, 12543, 12549, 12589, 12593, 12686, 12704, 12730, 12784, 12799, 13312, 19893, 19968, 40908, 40960, 42124, 42192, 42237, 42240, 42508, 42512, 42539, 42560, 42607, 42612, 42621, 42623, 42647, 42655, 42737, 42775, 42783, 42786, 42888, 42891, 42894, 42896, 42899, 42912, 42922, 43000, 43047, 43072, 43123, 43136, 43204, 43216, 43225, 43232, 43255, 43259, 43259, 43264, 43309, 43312, 43347, 43360, 43388, 43392, 43456, 43471, 43481, 43520, 43574, 43584, 43597, 43600, 43609, 43616, 43638, 43642, 43643, 43648, 43714, 43739, 43741, 43744, 43759, 43762, 43766, 43777, 43782, 43785, 43790, 43793, 43798, 43808, 43814, 43816, 43822, 43968, 44010, 44012, 44013, 44016, 44025, 44032, 55203, 55216, 55238, 55243, 55291, 63744, 64109, 64112, 64217, 64256, 64262, 64275, 64279, 64285, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65024, 65039, 65056, 65062, 65075, 65076, 65101, 65103, 65136, 65140, 65142, 65276, 65296, 65305, 65313, 65338, 65343, 65343, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500,]; + function lookupInUnicodeMap(code, map) { + // Bail out quickly if it couldn't possibly be in the map. + if (code < map[0]) { + return false; + } + // Perform binary search in one of the Unicode range maps + var lo = 0; + var hi = map.length; + var mid; + while (lo + 1 < hi) { + mid = lo + (hi - lo) / 2; + // mid has to be even to catch a range's beginning + mid -= mid % 2; + if (map[mid] <= code && code <= map[mid + 1]) { + return true; + } + if (code < map[mid]) { + hi = mid; + } + else { + lo = mid + 2; + } + } + return false; + } + /* @internal */ function isUnicodeIdentifierStart(code, languageVersion) { + return languageVersion >= 1 /* ES5 */ ? + lookupInUnicodeMap(code, unicodeES5IdentifierStart) : + lookupInUnicodeMap(code, unicodeES3IdentifierStart); + } + ts.isUnicodeIdentifierStart = isUnicodeIdentifierStart; + function isUnicodeIdentifierPart(code, languageVersion) { + return languageVersion >= 1 /* ES5 */ ? + lookupInUnicodeMap(code, unicodeES5IdentifierPart) : + lookupInUnicodeMap(code, unicodeES3IdentifierPart); + } + function makeReverseMap(source) { + var result = []; + source.forEach(function (value, name) { + result[value] = name; + }); + return result; + } + var tokenStrings = makeReverseMap(textToToken); + function tokenToString(t) { + return tokenStrings[t]; + } + ts.tokenToString = tokenToString; + /* @internal */ + function stringToToken(s) { + return textToToken.get(s); + } + ts.stringToToken = stringToToken; + /* @internal */ + function computeLineStarts(text) { + var result = new Array(); + var pos = 0; + var lineStart = 0; + while (pos < text.length) { + var ch = text.charCodeAt(pos); + pos++; + switch (ch) { + case 13 /* carriageReturn */: + if (text.charCodeAt(pos) === 10 /* lineFeed */) { + pos++; + } + // falls through + case 10 /* lineFeed */: + result.push(lineStart); + lineStart = pos; + break; + default: + if (ch > 127 /* maxAsciiCharacter */ && isLineBreak(ch)) { + result.push(lineStart); + lineStart = pos; + } + break; + } + } + result.push(lineStart); + return result; + } + ts.computeLineStarts = computeLineStarts; + function getPositionOfLineAndCharacter(sourceFile, line, character) { + return computePositionOfLineAndCharacter(getLineStarts(sourceFile), line, character, sourceFile.text); + } + ts.getPositionOfLineAndCharacter = getPositionOfLineAndCharacter; + /* @internal */ + function getPositionOfLineAndCharacterWithEdits(sourceFile, line, character) { + return computePositionOfLineAndCharacter(getLineStarts(sourceFile), line, character, sourceFile.text, /*allowEdits*/ true); + } + ts.getPositionOfLineAndCharacterWithEdits = getPositionOfLineAndCharacterWithEdits; + /* @internal */ + function computePositionOfLineAndCharacter(lineStarts, line, character, debugText, allowEdits) { + if (line < 0 || line >= lineStarts.length) { + if (allowEdits) { + // Clamp line to nearest allowable value + line = line < 0 ? 0 : line >= lineStarts.length ? lineStarts.length - 1 : line; + } + else { + ts.Debug.fail("Bad line number. Line: " + line + ", lineStarts.length: " + lineStarts.length + " , line map is correct? " + (debugText !== undefined ? ts.arraysEqual(lineStarts, computeLineStarts(debugText)) : "unknown")); + } + } + var res = lineStarts[line] + character; + if (allowEdits) { + // Clamp to nearest allowable values to allow the underlying to be edited without crashing (accuracy is lost, instead) + // TODO: Somehow track edits between file as it was during the creation of sourcemap we have and the current file and + // apply them to the computed position to improve accuracy + return res > lineStarts[line + 1] ? lineStarts[line + 1] : typeof debugText === "string" && res > debugText.length ? debugText.length : res; + } + if (line < lineStarts.length - 1) { + ts.Debug.assert(res < lineStarts[line + 1]); + } + else if (debugText !== undefined) { + ts.Debug.assert(res <= debugText.length); // Allow single character overflow for trailing newline + } + return res; + } + ts.computePositionOfLineAndCharacter = computePositionOfLineAndCharacter; + /* @internal */ + function getLineStarts(sourceFile) { + return sourceFile.lineMap || (sourceFile.lineMap = computeLineStarts(sourceFile.text)); + } + ts.getLineStarts = getLineStarts; + /* @internal */ + /** + * We assume the first line starts at position 0 and 'position' is non-negative. + */ + function computeLineAndCharacterOfPosition(lineStarts, position) { + var lineNumber = ts.binarySearch(lineStarts, position, ts.identity, ts.compareValues); + if (lineNumber < 0) { + // If the actual position was not found, + // the binary search returns the 2's-complement of the next line start + // e.g. if the line starts at [5, 10, 23, 80] and the position requested was 20 + // then the search will return -2. + // + // We want the index of the previous line start, so we subtract 1. + // Review 2's-complement if this is confusing. + lineNumber = ~lineNumber - 1; + ts.Debug.assert(lineNumber !== -1, "position cannot precede the beginning of the file"); + } + return { + line: lineNumber, + character: position - lineStarts[lineNumber] + }; + } + ts.computeLineAndCharacterOfPosition = computeLineAndCharacterOfPosition; + function getLineAndCharacterOfPosition(sourceFile, position) { + return computeLineAndCharacterOfPosition(getLineStarts(sourceFile), position); + } + ts.getLineAndCharacterOfPosition = getLineAndCharacterOfPosition; + function isWhiteSpaceLike(ch) { + return isWhiteSpaceSingleLine(ch) || isLineBreak(ch); + } + ts.isWhiteSpaceLike = isWhiteSpaceLike; + /** Does not include line breaks. For that, see isWhiteSpaceLike. */ + function isWhiteSpaceSingleLine(ch) { + // Note: nextLine is in the Zs space, and should be considered to be a whitespace. + // It is explicitly not a line-break as it isn't in the exact set specified by EcmaScript. + return ch === 32 /* space */ || + ch === 9 /* tab */ || + ch === 11 /* verticalTab */ || + ch === 12 /* formFeed */ || + ch === 160 /* nonBreakingSpace */ || + ch === 133 /* nextLine */ || + ch === 5760 /* ogham */ || + ch >= 8192 /* enQuad */ && ch <= 8203 /* zeroWidthSpace */ || + ch === 8239 /* narrowNoBreakSpace */ || + ch === 8287 /* mathematicalSpace */ || + ch === 12288 /* ideographicSpace */ || + ch === 65279 /* byteOrderMark */; + } + ts.isWhiteSpaceSingleLine = isWhiteSpaceSingleLine; + function isLineBreak(ch) { + // ES5 7.3: + // The ECMAScript line terminator characters are listed in Table 3. + // Table 3: Line Terminator Characters + // Code Unit Value Name Formal Name + // \u000A Line Feed + // \u000D Carriage Return + // \u2028 Line separator + // \u2029 Paragraph separator + // Only the characters in Table 3 are treated as line terminators. Other new line or line + // breaking characters are treated as white space but not as line terminators. + return ch === 10 /* lineFeed */ || + ch === 13 /* carriageReturn */ || + ch === 8232 /* lineSeparator */ || + ch === 8233 /* paragraphSeparator */; + } + ts.isLineBreak = isLineBreak; + function isDigit(ch) { + return ch >= 48 /* _0 */ && ch <= 57 /* _9 */; + } + /* @internal */ + function isOctalDigit(ch) { + return ch >= 48 /* _0 */ && ch <= 55 /* _7 */; + } + ts.isOctalDigit = isOctalDigit; + function couldStartTrivia(text, pos) { + // Keep in sync with skipTrivia + var ch = text.charCodeAt(pos); + switch (ch) { + case 13 /* carriageReturn */: + case 10 /* lineFeed */: + case 9 /* tab */: + case 11 /* verticalTab */: + case 12 /* formFeed */: + case 32 /* space */: + case 47 /* slash */: + // starts of normal trivia + case 60 /* lessThan */: + case 124 /* bar */: + case 61 /* equals */: + case 62 /* greaterThan */: + // Starts of conflict marker trivia + return true; + case 35 /* hash */: + // Only if its the beginning can we have #! trivia + return pos === 0; + default: + return ch > 127 /* maxAsciiCharacter */; + } + } + ts.couldStartTrivia = couldStartTrivia; + /* @internal */ + function skipTrivia(text, pos, stopAfterLineBreak, stopAtComments) { + if (stopAtComments === void 0) { stopAtComments = false; } + if (ts.positionIsSynthesized(pos)) { + return pos; + } + // Keep in sync with couldStartTrivia + while (true) { + var ch = text.charCodeAt(pos); + switch (ch) { + case 13 /* carriageReturn */: + if (text.charCodeAt(pos + 1) === 10 /* lineFeed */) { + pos++; + } + // falls through + case 10 /* lineFeed */: + pos++; + if (stopAfterLineBreak) { + return pos; + } + continue; + case 9 /* tab */: + case 11 /* verticalTab */: + case 12 /* formFeed */: + case 32 /* space */: + pos++; + continue; + case 47 /* slash */: + if (stopAtComments) { + break; + } + if (text.charCodeAt(pos + 1) === 47 /* slash */) { + pos += 2; + while (pos < text.length) { + if (isLineBreak(text.charCodeAt(pos))) { + break; + } + pos++; + } + continue; + } + if (text.charCodeAt(pos + 1) === 42 /* asterisk */) { + pos += 2; + while (pos < text.length) { + if (text.charCodeAt(pos) === 42 /* asterisk */ && text.charCodeAt(pos + 1) === 47 /* slash */) { + pos += 2; + break; + } + pos++; + } + continue; + } + break; + case 60 /* lessThan */: + case 124 /* bar */: + case 61 /* equals */: + case 62 /* greaterThan */: + if (isConflictMarkerTrivia(text, pos)) { + pos = scanConflictMarkerTrivia(text, pos); + continue; + } + break; + case 35 /* hash */: + if (pos === 0 && isShebangTrivia(text, pos)) { + pos = scanShebangTrivia(text, pos); + continue; + } + break; + default: + if (ch > 127 /* maxAsciiCharacter */ && (isWhiteSpaceLike(ch))) { + pos++; + continue; + } + break; + } + return pos; + } + } + ts.skipTrivia = skipTrivia; + // All conflict markers consist of the same character repeated seven times. If it is + // a <<<<<<< or >>>>>>> marker then it is also followed by a space. + var mergeConflictMarkerLength = "<<<<<<<".length; + function isConflictMarkerTrivia(text, pos) { + ts.Debug.assert(pos >= 0); + // Conflict markers must be at the start of a line. + if (pos === 0 || isLineBreak(text.charCodeAt(pos - 1))) { + var ch = text.charCodeAt(pos); + if ((pos + mergeConflictMarkerLength) < text.length) { + for (var i = 0; i < mergeConflictMarkerLength; i++) { + if (text.charCodeAt(pos + i) !== ch) { + return false; + } + } + return ch === 61 /* equals */ || + text.charCodeAt(pos + mergeConflictMarkerLength) === 32 /* space */; + } + } + return false; + } + function scanConflictMarkerTrivia(text, pos, error) { + if (error) { + error(ts.Diagnostics.Merge_conflict_marker_encountered, pos, mergeConflictMarkerLength); + } + var ch = text.charCodeAt(pos); + var len = text.length; + if (ch === 60 /* lessThan */ || ch === 62 /* greaterThan */) { + while (pos < len && !isLineBreak(text.charCodeAt(pos))) { + pos++; + } + } + else { + ts.Debug.assert(ch === 124 /* bar */ || ch === 61 /* equals */); + // Consume everything from the start of a ||||||| or ======= marker to the start + // of the next ======= or >>>>>>> marker. + while (pos < len) { + var currentChar = text.charCodeAt(pos); + if ((currentChar === 61 /* equals */ || currentChar === 62 /* greaterThan */) && currentChar !== ch && isConflictMarkerTrivia(text, pos)) { + break; + } + pos++; + } + } + return pos; + } + var shebangTriviaRegex = /^#!.*/; + function isShebangTrivia(text, pos) { + // Shebangs check must only be done at the start of the file + ts.Debug.assert(pos === 0); + return shebangTriviaRegex.test(text); + } + function scanShebangTrivia(text, pos) { + var shebang = shebangTriviaRegex.exec(text)[0]; + pos = pos + shebang.length; + return pos; + } + /** + * Invokes a callback for each comment range following the provided position. + * + * Single-line comment ranges include the leading double-slash characters but not the ending + * line break. Multi-line comment ranges include the leading slash-asterisk and trailing + * asterisk-slash characters. + * + * @param reduce If true, accumulates the result of calling the callback in a fashion similar + * to reduceLeft. If false, iteration stops when the callback returns a truthy value. + * @param text The source text to scan. + * @param pos The position at which to start scanning. + * @param trailing If false, whitespace is skipped until the first line break and comments + * between that location and the next token are returned. If true, comments occurring + * between the given position and the next line break are returned. + * @param cb The callback to execute as each comment range is encountered. + * @param state A state value to pass to each iteration of the callback. + * @param initial An initial value to pass when accumulating results (when "reduce" is true). + * @returns If "reduce" is true, the accumulated value. If "reduce" is false, the first truthy + * return value of the callback. + */ + function iterateCommentRanges(reduce, text, pos, trailing, cb, state, initial) { + var pendingPos; + var pendingEnd; + var pendingKind; + var pendingHasTrailingNewLine; + var hasPendingCommentRange = false; + var collecting = trailing || pos === 0; + var accumulator = initial; + scan: while (pos >= 0 && pos < text.length) { + var ch = text.charCodeAt(pos); + switch (ch) { + case 13 /* carriageReturn */: + if (text.charCodeAt(pos + 1) === 10 /* lineFeed */) { + pos++; + } + // falls through + case 10 /* lineFeed */: + pos++; + if (trailing) { + break scan; + } + collecting = true; + if (hasPendingCommentRange) { + pendingHasTrailingNewLine = true; + } + continue; + case 9 /* tab */: + case 11 /* verticalTab */: + case 12 /* formFeed */: + case 32 /* space */: + pos++; + continue; + case 47 /* slash */: + var nextChar = text.charCodeAt(pos + 1); + var hasTrailingNewLine = false; + if (nextChar === 47 /* slash */ || nextChar === 42 /* asterisk */) { + var kind = nextChar === 47 /* slash */ ? 2 /* SingleLineCommentTrivia */ : 3 /* MultiLineCommentTrivia */; + var startPos = pos; + pos += 2; + if (nextChar === 47 /* slash */) { + while (pos < text.length) { + if (isLineBreak(text.charCodeAt(pos))) { + hasTrailingNewLine = true; + break; + } + pos++; + } + } + else { + while (pos < text.length) { + if (text.charCodeAt(pos) === 42 /* asterisk */ && text.charCodeAt(pos + 1) === 47 /* slash */) { + pos += 2; + break; + } + pos++; + } + } + if (collecting) { + if (hasPendingCommentRange) { + accumulator = cb(pendingPos, pendingEnd, pendingKind, pendingHasTrailingNewLine, state, accumulator); + if (!reduce && accumulator) { + // If we are not reducing and we have a truthy result, return it. + return accumulator; + } + } + pendingPos = startPos; + pendingEnd = pos; + pendingKind = kind; + pendingHasTrailingNewLine = hasTrailingNewLine; + hasPendingCommentRange = true; + } + continue; + } + break scan; + default: + if (ch > 127 /* maxAsciiCharacter */ && (isWhiteSpaceLike(ch))) { + if (hasPendingCommentRange && isLineBreak(ch)) { + pendingHasTrailingNewLine = true; + } + pos++; + continue; + } + break scan; + } + } + if (hasPendingCommentRange) { + accumulator = cb(pendingPos, pendingEnd, pendingKind, pendingHasTrailingNewLine, state, accumulator); + } + return accumulator; + } + function forEachLeadingCommentRange(text, pos, cb, state) { + return iterateCommentRanges(/*reduce*/ false, text, pos, /*trailing*/ false, cb, state); + } + ts.forEachLeadingCommentRange = forEachLeadingCommentRange; + function forEachTrailingCommentRange(text, pos, cb, state) { + return iterateCommentRanges(/*reduce*/ false, text, pos, /*trailing*/ true, cb, state); + } + ts.forEachTrailingCommentRange = forEachTrailingCommentRange; + function reduceEachLeadingCommentRange(text, pos, cb, state, initial) { + return iterateCommentRanges(/*reduce*/ true, text, pos, /*trailing*/ false, cb, state, initial); + } + ts.reduceEachLeadingCommentRange = reduceEachLeadingCommentRange; + function reduceEachTrailingCommentRange(text, pos, cb, state, initial) { + return iterateCommentRanges(/*reduce*/ true, text, pos, /*trailing*/ true, cb, state, initial); + } + ts.reduceEachTrailingCommentRange = reduceEachTrailingCommentRange; + function appendCommentRange(pos, end, kind, hasTrailingNewLine, _state, comments) { + if (!comments) { + comments = []; + } + comments.push({ kind: kind, pos: pos, end: end, hasTrailingNewLine: hasTrailingNewLine }); + return comments; + } + function getLeadingCommentRanges(text, pos) { + return reduceEachLeadingCommentRange(text, pos, appendCommentRange, /*state*/ undefined, /*initial*/ undefined); + } + ts.getLeadingCommentRanges = getLeadingCommentRanges; + function getTrailingCommentRanges(text, pos) { + return reduceEachTrailingCommentRange(text, pos, appendCommentRange, /*state*/ undefined, /*initial*/ undefined); + } + ts.getTrailingCommentRanges = getTrailingCommentRanges; + /** Optionally, get the shebang */ + function getShebang(text) { + var match = shebangTriviaRegex.exec(text); + if (match) { + return match[0]; + } + } + ts.getShebang = getShebang; + function isIdentifierStart(ch, languageVersion) { + return ch >= 65 /* A */ && ch <= 90 /* Z */ || ch >= 97 /* a */ && ch <= 122 /* z */ || + ch === 36 /* $ */ || ch === 95 /* _ */ || + ch > 127 /* maxAsciiCharacter */ && isUnicodeIdentifierStart(ch, languageVersion); + } + ts.isIdentifierStart = isIdentifierStart; + function isIdentifierPart(ch, languageVersion) { + return ch >= 65 /* A */ && ch <= 90 /* Z */ || ch >= 97 /* a */ && ch <= 122 /* z */ || + ch >= 48 /* _0 */ && ch <= 57 /* _9 */ || ch === 36 /* $ */ || ch === 95 /* _ */ || + ch > 127 /* maxAsciiCharacter */ && isUnicodeIdentifierPart(ch, languageVersion); + } + ts.isIdentifierPart = isIdentifierPart; + /* @internal */ + function isIdentifierText(name, languageVersion) { + if (!isIdentifierStart(name.charCodeAt(0), languageVersion)) { + return false; + } + for (var i = 1; i < name.length; i++) { + if (!isIdentifierPart(name.charCodeAt(i), languageVersion)) { + return false; + } + } + return true; + } + ts.isIdentifierText = isIdentifierText; + // Creates a scanner over a (possibly unspecified) range of a piece of text. + function createScanner(languageVersion, skipTrivia, languageVariant, textInitial, onError, start, length) { + if (languageVariant === void 0) { languageVariant = 0 /* Standard */; } + var text = textInitial; + // Current position (end position of text of current token) + var pos; + // end of text + var end; + // Start position of whitespace before current token + var startPos; + // Start position of text of current token + var tokenPos; + var token; + var tokenValue; + var tokenFlags; + var inJSDocType = 0; + setText(text, start, length); + return { + getStartPos: function () { return startPos; }, + getTextPos: function () { return pos; }, + getToken: function () { return token; }, + getTokenPos: function () { return tokenPos; }, + getTokenText: function () { return text.substring(tokenPos, pos); }, + getTokenValue: function () { return tokenValue; }, + hasExtendedUnicodeEscape: function () { return (tokenFlags & 8 /* ExtendedUnicodeEscape */) !== 0; }, + hasPrecedingLineBreak: function () { return (tokenFlags & 1 /* PrecedingLineBreak */) !== 0; }, + isIdentifier: function () { return token === 72 /* Identifier */ || token > 108 /* LastReservedWord */; }, + isReservedWord: function () { return token >= 73 /* FirstReservedWord */ && token <= 108 /* LastReservedWord */; }, + isUnterminated: function () { return (tokenFlags & 4 /* Unterminated */) !== 0; }, + getTokenFlags: function () { return tokenFlags; }, + reScanGreaterToken: reScanGreaterToken, + reScanSlashToken: reScanSlashToken, + reScanTemplateToken: reScanTemplateToken, + scanJsxIdentifier: scanJsxIdentifier, + scanJsxAttributeValue: scanJsxAttributeValue, + reScanJsxToken: reScanJsxToken, + scanJsxToken: scanJsxToken, + scanJSDocToken: scanJSDocToken, + scan: scan, + getText: getText, + setText: setText, + setScriptTarget: setScriptTarget, + setLanguageVariant: setLanguageVariant, + setOnError: setOnError, + setTextPos: setTextPos, + setInJSDocType: setInJSDocType, + tryScan: tryScan, + lookAhead: lookAhead, + scanRange: scanRange, + }; + function error(message, errPos, length) { + if (errPos === void 0) { errPos = pos; } + if (onError) { + var oldPos = pos; + pos = errPos; + onError(message, length || 0); + pos = oldPos; + } + } + function scanNumberFragment() { + var start = pos; + var allowSeparator = false; + var isPreviousTokenSeparator = false; + var result = ""; + while (true) { + var ch = text.charCodeAt(pos); + if (ch === 95 /* _ */) { + tokenFlags |= 512 /* ContainsSeparator */; + if (allowSeparator) { + allowSeparator = false; + isPreviousTokenSeparator = true; + result += text.substring(start, pos); + } + else if (isPreviousTokenSeparator) { + error(ts.Diagnostics.Multiple_consecutive_numeric_separators_are_not_permitted, pos, 1); + } + else { + error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos, 1); + } + pos++; + start = pos; + continue; + } + if (isDigit(ch)) { + allowSeparator = true; + isPreviousTokenSeparator = false; + pos++; + continue; + } + break; + } + if (text.charCodeAt(pos - 1) === 95 /* _ */) { + error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos - 1, 1); + } + return result + text.substring(start, pos); + } + function scanNumber() { + var start = pos; + var mainFragment = scanNumberFragment(); + var decimalFragment; + var scientificFragment; + if (text.charCodeAt(pos) === 46 /* dot */) { + pos++; + decimalFragment = scanNumberFragment(); + } + var end = pos; + if (text.charCodeAt(pos) === 69 /* E */ || text.charCodeAt(pos) === 101 /* e */) { + pos++; + tokenFlags |= 16 /* Scientific */; + if (text.charCodeAt(pos) === 43 /* plus */ || text.charCodeAt(pos) === 45 /* minus */) + pos++; + var preNumericPart = pos; + var finalFragment = scanNumberFragment(); + if (!finalFragment) { + error(ts.Diagnostics.Digit_expected); + } + else { + scientificFragment = text.substring(end, preNumericPart) + finalFragment; + end = pos; + } + } + var result; + if (tokenFlags & 512 /* ContainsSeparator */) { + result = mainFragment; + if (decimalFragment) { + result += "." + decimalFragment; + } + if (scientificFragment) { + result += scientificFragment; + } + } + else { + result = text.substring(start, end); // No need to use all the fragments; no _ removal needed + } + if (decimalFragment !== undefined || tokenFlags & 16 /* Scientific */) { + return { + type: 8 /* NumericLiteral */, + value: "" + +result // if value is not an integer, it can be safely coerced to a number + }; + } + else { + tokenValue = result; + var type = checkBigIntSuffix(); // if value is an integer, check whether it is a bigint + return { type: type, value: tokenValue }; + } + } + function scanOctalDigits() { + var start = pos; + while (isOctalDigit(text.charCodeAt(pos))) { + pos++; + } + return +(text.substring(start, pos)); + } + /** + * Scans the given number of hexadecimal digits in the text, + * returning -1 if the given number is unavailable. + */ + function scanExactNumberOfHexDigits(count, canHaveSeparators) { + var valueString = scanHexDigits(/*minCount*/ count, /*scanAsManyAsPossible*/ false, canHaveSeparators); + return valueString ? parseInt(valueString, 16) : -1; + } + /** + * Scans as many hexadecimal digits as are available in the text, + * returning "" if the given number of digits was unavailable. + */ + function scanMinimumNumberOfHexDigits(count, canHaveSeparators) { + return scanHexDigits(/*minCount*/ count, /*scanAsManyAsPossible*/ true, canHaveSeparators); + } + function scanHexDigits(minCount, scanAsManyAsPossible, canHaveSeparators) { + var valueChars = []; + var allowSeparator = false; + var isPreviousTokenSeparator = false; + while (valueChars.length < minCount || scanAsManyAsPossible) { + var ch = text.charCodeAt(pos); + if (canHaveSeparators && ch === 95 /* _ */) { + tokenFlags |= 512 /* ContainsSeparator */; + if (allowSeparator) { + allowSeparator = false; + isPreviousTokenSeparator = true; + } + else if (isPreviousTokenSeparator) { + error(ts.Diagnostics.Multiple_consecutive_numeric_separators_are_not_permitted, pos, 1); + } + else { + error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos, 1); + } + pos++; + continue; + } + allowSeparator = canHaveSeparators; + if (ch >= 65 /* A */ && ch <= 70 /* F */) { + ch += 97 /* a */ - 65 /* A */; // standardize hex literals to lowercase + } + else if (!((ch >= 48 /* _0 */ && ch <= 57 /* _9 */) || + (ch >= 97 /* a */ && ch <= 102 /* f */))) { + break; + } + valueChars.push(ch); + pos++; + isPreviousTokenSeparator = false; + } + if (valueChars.length < minCount) { + valueChars = []; + } + if (text.charCodeAt(pos - 1) === 95 /* _ */) { + error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos - 1, 1); + } + return String.fromCharCode.apply(String, valueChars); + } + function scanString(jsxAttributeString) { + if (jsxAttributeString === void 0) { jsxAttributeString = false; } + var quote = text.charCodeAt(pos); + pos++; + var result = ""; + var start = pos; + while (true) { + if (pos >= end) { + result += text.substring(start, pos); + tokenFlags |= 4 /* Unterminated */; + error(ts.Diagnostics.Unterminated_string_literal); + break; + } + var ch = text.charCodeAt(pos); + if (ch === quote) { + result += text.substring(start, pos); + pos++; + break; + } + if (ch === 92 /* backslash */ && !jsxAttributeString) { + result += text.substring(start, pos); + result += scanEscapeSequence(); + start = pos; + continue; + } + if (isLineBreak(ch) && !jsxAttributeString) { + result += text.substring(start, pos); + tokenFlags |= 4 /* Unterminated */; + error(ts.Diagnostics.Unterminated_string_literal); + break; + } + pos++; + } + return result; + } + /** + * Sets the current 'tokenValue' and returns a NoSubstitutionTemplateLiteral or + * a literal component of a TemplateExpression. + */ + function scanTemplateAndSetTokenValue() { + var startedWithBacktick = text.charCodeAt(pos) === 96 /* backtick */; + pos++; + var start = pos; + var contents = ""; + var resultingToken; + while (true) { + if (pos >= end) { + contents += text.substring(start, pos); + tokenFlags |= 4 /* Unterminated */; + error(ts.Diagnostics.Unterminated_template_literal); + resultingToken = startedWithBacktick ? 14 /* NoSubstitutionTemplateLiteral */ : 17 /* TemplateTail */; + break; + } + var currChar = text.charCodeAt(pos); + // '`' + if (currChar === 96 /* backtick */) { + contents += text.substring(start, pos); + pos++; + resultingToken = startedWithBacktick ? 14 /* NoSubstitutionTemplateLiteral */ : 17 /* TemplateTail */; + break; + } + // '${' + if (currChar === 36 /* $ */ && pos + 1 < end && text.charCodeAt(pos + 1) === 123 /* openBrace */) { + contents += text.substring(start, pos); + pos += 2; + resultingToken = startedWithBacktick ? 15 /* TemplateHead */ : 16 /* TemplateMiddle */; + break; + } + // Escape character + if (currChar === 92 /* backslash */) { + contents += text.substring(start, pos); + contents += scanEscapeSequence(); + start = pos; + continue; + } + // Speculated ECMAScript 6 Spec 11.8.6.1: + // and LineTerminatorSequences are normalized to for Template Values + if (currChar === 13 /* carriageReturn */) { + contents += text.substring(start, pos); + pos++; + if (pos < end && text.charCodeAt(pos) === 10 /* lineFeed */) { + pos++; + } + contents += "\n"; + start = pos; + continue; + } + pos++; + } + ts.Debug.assert(resultingToken !== undefined); + tokenValue = contents; + return resultingToken; + } + function scanEscapeSequence() { + pos++; + if (pos >= end) { + error(ts.Diagnostics.Unexpected_end_of_text); + return ""; + } + var ch = text.charCodeAt(pos); + pos++; + switch (ch) { + case 48 /* _0 */: + return "\0"; + case 98 /* b */: + return "\b"; + case 116 /* t */: + return "\t"; + case 110 /* n */: + return "\n"; + case 118 /* v */: + return "\v"; + case 102 /* f */: + return "\f"; + case 114 /* r */: + return "\r"; + case 39 /* singleQuote */: + return "\'"; + case 34 /* doubleQuote */: + return "\""; + case 117 /* u */: + // '\u{DDDDDDDD}' + if (pos < end && text.charCodeAt(pos) === 123 /* openBrace */) { + tokenFlags |= 8 /* ExtendedUnicodeEscape */; + pos++; + return scanExtendedUnicodeEscape(); + } + // '\uDDDD' + return scanHexadecimalEscape(/*numDigits*/ 4); + case 120 /* x */: + // '\xDD' + return scanHexadecimalEscape(/*numDigits*/ 2); + // when encountering a LineContinuation (i.e. a backslash and a line terminator sequence), + // the line terminator is interpreted to be "the empty code unit sequence". + case 13 /* carriageReturn */: + if (pos < end && text.charCodeAt(pos) === 10 /* lineFeed */) { + pos++; + } + // falls through + case 10 /* lineFeed */: + case 8232 /* lineSeparator */: + case 8233 /* paragraphSeparator */: + return ""; + default: + return String.fromCharCode(ch); + } + } + function scanHexadecimalEscape(numDigits) { + var escapedValue = scanExactNumberOfHexDigits(numDigits, /*canHaveSeparators*/ false); + if (escapedValue >= 0) { + return String.fromCharCode(escapedValue); + } + else { + error(ts.Diagnostics.Hexadecimal_digit_expected); + return ""; + } + } + function scanExtendedUnicodeEscape() { + var escapedValueString = scanMinimumNumberOfHexDigits(1, /*canHaveSeparators*/ false); + var escapedValue = escapedValueString ? parseInt(escapedValueString, 16) : -1; + var isInvalidExtendedEscape = false; + // Validate the value of the digit + if (escapedValue < 0) { + error(ts.Diagnostics.Hexadecimal_digit_expected); + isInvalidExtendedEscape = true; + } + else if (escapedValue > 0x10FFFF) { + error(ts.Diagnostics.An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive); + isInvalidExtendedEscape = true; + } + if (pos >= end) { + error(ts.Diagnostics.Unexpected_end_of_text); + isInvalidExtendedEscape = true; + } + else if (text.charCodeAt(pos) === 125 /* closeBrace */) { + // Only swallow the following character up if it's a '}'. + pos++; + } + else { + error(ts.Diagnostics.Unterminated_Unicode_escape_sequence); + isInvalidExtendedEscape = true; + } + if (isInvalidExtendedEscape) { + return ""; + } + return utf16EncodeAsString(escapedValue); + } + // Derived from the 10.1.1 UTF16Encoding of the ES6 Spec. + function utf16EncodeAsString(codePoint) { + ts.Debug.assert(0x0 <= codePoint && codePoint <= 0x10FFFF); + if (codePoint <= 65535) { + return String.fromCharCode(codePoint); + } + var codeUnit1 = Math.floor((codePoint - 65536) / 1024) + 0xD800; + var codeUnit2 = ((codePoint - 65536) % 1024) + 0xDC00; + return String.fromCharCode(codeUnit1, codeUnit2); + } + // Current character is known to be a backslash. Check for Unicode escape of the form '\uXXXX' + // and return code point value if valid Unicode escape is found. Otherwise return -1. + function peekUnicodeEscape() { + if (pos + 5 < end && text.charCodeAt(pos + 1) === 117 /* u */) { + var start_1 = pos; + pos += 2; + var value = scanExactNumberOfHexDigits(4, /*canHaveSeparators*/ false); + pos = start_1; + return value; + } + return -1; + } + function scanIdentifierParts() { + var result = ""; + var start = pos; + while (pos < end) { + var ch = text.charCodeAt(pos); + if (isIdentifierPart(ch, languageVersion)) { + pos++; + } + else if (ch === 92 /* backslash */) { + ch = peekUnicodeEscape(); + if (!(ch >= 0 && isIdentifierPart(ch, languageVersion))) { + break; + } + result += text.substring(start, pos); + result += String.fromCharCode(ch); + // Valid Unicode escape is always six characters + pos += 6; + start = pos; + } + else { + break; + } + } + result += text.substring(start, pos); + return result; + } + function getIdentifierToken() { + // Reserved words are between 2 and 11 characters long and start with a lowercase letter + var len = tokenValue.length; + if (len >= 2 && len <= 11) { + var ch = tokenValue.charCodeAt(0); + if (ch >= 97 /* a */ && ch <= 122 /* z */) { + var keyword = textToKeyword.get(tokenValue); + if (keyword !== undefined) { + return token = keyword; + } + } + } + return token = 72 /* Identifier */; + } + function scanBinaryOrOctalDigits(base) { + var value = ""; + // For counting number of digits; Valid binaryIntegerLiteral must have at least one binary digit following B or b. + // Similarly valid octalIntegerLiteral must have at least one octal digit following o or O. + var separatorAllowed = false; + var isPreviousTokenSeparator = false; + while (true) { + var ch = text.charCodeAt(pos); + // Numeric separators are allowed anywhere within a numeric literal, except not at the beginning, or following another separator + if (ch === 95 /* _ */) { + tokenFlags |= 512 /* ContainsSeparator */; + if (separatorAllowed) { + separatorAllowed = false; + isPreviousTokenSeparator = true; + } + else if (isPreviousTokenSeparator) { + error(ts.Diagnostics.Multiple_consecutive_numeric_separators_are_not_permitted, pos, 1); + } + else { + error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos, 1); + } + pos++; + continue; + } + separatorAllowed = true; + if (!isDigit(ch) || ch - 48 /* _0 */ >= base) { + break; + } + value += text[pos]; + pos++; + isPreviousTokenSeparator = false; + } + if (text.charCodeAt(pos - 1) === 95 /* _ */) { + // Literal ends with underscore - not allowed + error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos - 1, 1); + } + return value; + } + function checkBigIntSuffix() { + if (text.charCodeAt(pos) === 110 /* n */) { + tokenValue += "n"; + // Use base 10 instead of base 2 or base 8 for shorter literals + if (tokenFlags & 384 /* BinaryOrOctalSpecifier */) { + tokenValue = ts.parsePseudoBigInt(tokenValue) + "n"; + } + pos++; + return 9 /* BigIntLiteral */; + } + else { // not a bigint, so can convert to number in simplified form + // Number() may not support 0b or 0o, so use parseInt() instead + var numericValue = tokenFlags & 128 /* BinarySpecifier */ + ? parseInt(tokenValue.slice(2), 2) // skip "0b" + : tokenFlags & 256 /* OctalSpecifier */ + ? parseInt(tokenValue.slice(2), 8) // skip "0o" + : +tokenValue; + tokenValue = "" + numericValue; + return 8 /* NumericLiteral */; + } + } + function scan() { + var _a; + startPos = pos; + tokenFlags = 0; + var asteriskSeen = false; + while (true) { + tokenPos = pos; + if (pos >= end) { + return token = 1 /* EndOfFileToken */; + } + var ch = text.charCodeAt(pos); + // Special handling for shebang + if (ch === 35 /* hash */ && pos === 0 && isShebangTrivia(text, pos)) { + pos = scanShebangTrivia(text, pos); + if (skipTrivia) { + continue; + } + else { + return token = 6 /* ShebangTrivia */; + } + } + switch (ch) { + case 10 /* lineFeed */: + case 13 /* carriageReturn */: + tokenFlags |= 1 /* PrecedingLineBreak */; + if (skipTrivia) { + pos++; + continue; + } + else { + if (ch === 13 /* carriageReturn */ && pos + 1 < end && text.charCodeAt(pos + 1) === 10 /* lineFeed */) { + // consume both CR and LF + pos += 2; + } + else { + pos++; + } + return token = 4 /* NewLineTrivia */; + } + case 9 /* tab */: + case 11 /* verticalTab */: + case 12 /* formFeed */: + case 32 /* space */: + case 160 /* nonBreakingSpace */: + case 5760 /* ogham */: + case 8192 /* enQuad */: + case 8193 /* emQuad */: + case 8194 /* enSpace */: + case 8195 /* emSpace */: + case 8196 /* threePerEmSpace */: + case 8197 /* fourPerEmSpace */: + case 8198 /* sixPerEmSpace */: + case 8199 /* figureSpace */: + case 8200 /* punctuationSpace */: + case 8201 /* thinSpace */: + case 8202 /* hairSpace */: + case 8203 /* zeroWidthSpace */: + case 8239 /* narrowNoBreakSpace */: + case 8287 /* mathematicalSpace */: + case 12288 /* ideographicSpace */: + case 65279 /* byteOrderMark */: + if (skipTrivia) { + pos++; + continue; + } + else { + while (pos < end && isWhiteSpaceSingleLine(text.charCodeAt(pos))) { + pos++; + } + return token = 5 /* WhitespaceTrivia */; + } + case 33 /* exclamation */: + if (text.charCodeAt(pos + 1) === 61 /* equals */) { + if (text.charCodeAt(pos + 2) === 61 /* equals */) { + return pos += 3, token = 36 /* ExclamationEqualsEqualsToken */; + } + return pos += 2, token = 34 /* ExclamationEqualsToken */; + } + pos++; + return token = 52 /* ExclamationToken */; + case 34 /* doubleQuote */: + case 39 /* singleQuote */: + tokenValue = scanString(); + return token = 10 /* StringLiteral */; + case 96 /* backtick */: + return token = scanTemplateAndSetTokenValue(); + case 37 /* percent */: + if (text.charCodeAt(pos + 1) === 61 /* equals */) { + return pos += 2, token = 65 /* PercentEqualsToken */; + } + pos++; + return token = 43 /* PercentToken */; + case 38 /* ampersand */: + if (text.charCodeAt(pos + 1) === 38 /* ampersand */) { + return pos += 2, token = 54 /* AmpersandAmpersandToken */; + } + if (text.charCodeAt(pos + 1) === 61 /* equals */) { + return pos += 2, token = 69 /* AmpersandEqualsToken */; + } + pos++; + return token = 49 /* AmpersandToken */; + case 40 /* openParen */: + pos++; + return token = 20 /* OpenParenToken */; + case 41 /* closeParen */: + pos++; + return token = 21 /* CloseParenToken */; + case 42 /* asterisk */: + if (text.charCodeAt(pos + 1) === 61 /* equals */) { + return pos += 2, token = 62 /* AsteriskEqualsToken */; + } + if (text.charCodeAt(pos + 1) === 42 /* asterisk */) { + if (text.charCodeAt(pos + 2) === 61 /* equals */) { + return pos += 3, token = 63 /* AsteriskAsteriskEqualsToken */; + } + return pos += 2, token = 41 /* AsteriskAsteriskToken */; + } + pos++; + if (inJSDocType && !asteriskSeen && (tokenFlags & 1 /* PrecedingLineBreak */)) { + // decoration at the start of a JSDoc comment line + asteriskSeen = true; + continue; + } + return token = 40 /* AsteriskToken */; + case 43 /* plus */: + if (text.charCodeAt(pos + 1) === 43 /* plus */) { + return pos += 2, token = 44 /* PlusPlusToken */; + } + if (text.charCodeAt(pos + 1) === 61 /* equals */) { + return pos += 2, token = 60 /* PlusEqualsToken */; + } + pos++; + return token = 38 /* PlusToken */; + case 44 /* comma */: + pos++; + return token = 27 /* CommaToken */; + case 45 /* minus */: + if (text.charCodeAt(pos + 1) === 45 /* minus */) { + return pos += 2, token = 45 /* MinusMinusToken */; + } + if (text.charCodeAt(pos + 1) === 61 /* equals */) { + return pos += 2, token = 61 /* MinusEqualsToken */; + } + pos++; + return token = 39 /* MinusToken */; + case 46 /* dot */: + if (isDigit(text.charCodeAt(pos + 1))) { + tokenValue = scanNumber().value; + return token = 8 /* NumericLiteral */; + } + if (text.charCodeAt(pos + 1) === 46 /* dot */ && text.charCodeAt(pos + 2) === 46 /* dot */) { + return pos += 3, token = 25 /* DotDotDotToken */; + } + pos++; + return token = 24 /* DotToken */; + case 47 /* slash */: + // Single-line comment + if (text.charCodeAt(pos + 1) === 47 /* slash */) { + pos += 2; + while (pos < end) { + if (isLineBreak(text.charCodeAt(pos))) { + break; + } + pos++; + } + if (skipTrivia) { + continue; + } + else { + return token = 2 /* SingleLineCommentTrivia */; + } + } + // Multi-line comment + if (text.charCodeAt(pos + 1) === 42 /* asterisk */) { + pos += 2; + if (text.charCodeAt(pos) === 42 /* asterisk */ && text.charCodeAt(pos + 1) !== 47 /* slash */) { + tokenFlags |= 2 /* PrecedingJSDocComment */; + } + var commentClosed = false; + while (pos < end) { + var ch_1 = text.charCodeAt(pos); + if (ch_1 === 42 /* asterisk */ && text.charCodeAt(pos + 1) === 47 /* slash */) { + pos += 2; + commentClosed = true; + break; + } + if (isLineBreak(ch_1)) { + tokenFlags |= 1 /* PrecedingLineBreak */; + } + pos++; + } + if (!commentClosed) { + error(ts.Diagnostics.Asterisk_Slash_expected); + } + if (skipTrivia) { + continue; + } + else { + if (!commentClosed) { + tokenFlags |= 4 /* Unterminated */; + } + return token = 3 /* MultiLineCommentTrivia */; + } + } + if (text.charCodeAt(pos + 1) === 61 /* equals */) { + return pos += 2, token = 64 /* SlashEqualsToken */; + } + pos++; + return token = 42 /* SlashToken */; + case 48 /* _0 */: + if (pos + 2 < end && (text.charCodeAt(pos + 1) === 88 /* X */ || text.charCodeAt(pos + 1) === 120 /* x */)) { + pos += 2; + tokenValue = scanMinimumNumberOfHexDigits(1, /*canHaveSeparators*/ true); + if (!tokenValue) { + error(ts.Diagnostics.Hexadecimal_digit_expected); + tokenValue = "0"; + } + tokenValue = "0x" + tokenValue; + tokenFlags |= 64 /* HexSpecifier */; + return token = checkBigIntSuffix(); + } + else if (pos + 2 < end && (text.charCodeAt(pos + 1) === 66 /* B */ || text.charCodeAt(pos + 1) === 98 /* b */)) { + pos += 2; + tokenValue = scanBinaryOrOctalDigits(/* base */ 2); + if (!tokenValue) { + error(ts.Diagnostics.Binary_digit_expected); + tokenValue = "0"; + } + tokenValue = "0b" + tokenValue; + tokenFlags |= 128 /* BinarySpecifier */; + return token = checkBigIntSuffix(); + } + else if (pos + 2 < end && (text.charCodeAt(pos + 1) === 79 /* O */ || text.charCodeAt(pos + 1) === 111 /* o */)) { + pos += 2; + tokenValue = scanBinaryOrOctalDigits(/* base */ 8); + if (!tokenValue) { + error(ts.Diagnostics.Octal_digit_expected); + tokenValue = "0"; + } + tokenValue = "0o" + tokenValue; + tokenFlags |= 256 /* OctalSpecifier */; + return token = checkBigIntSuffix(); + } + // Try to parse as an octal + if (pos + 1 < end && isOctalDigit(text.charCodeAt(pos + 1))) { + tokenValue = "" + scanOctalDigits(); + tokenFlags |= 32 /* Octal */; + return token = 8 /* NumericLiteral */; + } + // This fall-through is a deviation from the EcmaScript grammar. The grammar says that a leading zero + // can only be followed by an octal digit, a dot, or the end of the number literal. However, we are being + // permissive and allowing decimal digits of the form 08* and 09* (which many browsers also do). + // falls through + case 49 /* _1 */: + case 50 /* _2 */: + case 51 /* _3 */: + case 52 /* _4 */: + case 53 /* _5 */: + case 54 /* _6 */: + case 55 /* _7 */: + case 56 /* _8 */: + case 57 /* _9 */: + (_a = scanNumber(), token = _a.type, tokenValue = _a.value); + return token; + case 58 /* colon */: + pos++; + return token = 57 /* ColonToken */; + case 59 /* semicolon */: + pos++; + return token = 26 /* SemicolonToken */; + case 60 /* lessThan */: + if (isConflictMarkerTrivia(text, pos)) { + pos = scanConflictMarkerTrivia(text, pos, error); + if (skipTrivia) { + continue; + } + else { + return token = 7 /* ConflictMarkerTrivia */; + } + } + if (text.charCodeAt(pos + 1) === 60 /* lessThan */) { + if (text.charCodeAt(pos + 2) === 61 /* equals */) { + return pos += 3, token = 66 /* LessThanLessThanEqualsToken */; + } + return pos += 2, token = 46 /* LessThanLessThanToken */; + } + if (text.charCodeAt(pos + 1) === 61 /* equals */) { + return pos += 2, token = 31 /* LessThanEqualsToken */; + } + if (languageVariant === 1 /* JSX */ && + text.charCodeAt(pos + 1) === 47 /* slash */ && + text.charCodeAt(pos + 2) !== 42 /* asterisk */) { + return pos += 2, token = 29 /* LessThanSlashToken */; + } + pos++; + return token = 28 /* LessThanToken */; + case 61 /* equals */: + if (isConflictMarkerTrivia(text, pos)) { + pos = scanConflictMarkerTrivia(text, pos, error); + if (skipTrivia) { + continue; + } + else { + return token = 7 /* ConflictMarkerTrivia */; + } + } + if (text.charCodeAt(pos + 1) === 61 /* equals */) { + if (text.charCodeAt(pos + 2) === 61 /* equals */) { + return pos += 3, token = 35 /* EqualsEqualsEqualsToken */; + } + return pos += 2, token = 33 /* EqualsEqualsToken */; + } + if (text.charCodeAt(pos + 1) === 62 /* greaterThan */) { + return pos += 2, token = 37 /* EqualsGreaterThanToken */; + } + pos++; + return token = 59 /* EqualsToken */; + case 62 /* greaterThan */: + if (isConflictMarkerTrivia(text, pos)) { + pos = scanConflictMarkerTrivia(text, pos, error); + if (skipTrivia) { + continue; + } + else { + return token = 7 /* ConflictMarkerTrivia */; + } + } + pos++; + return token = 30 /* GreaterThanToken */; + case 63 /* question */: + pos++; + return token = 56 /* QuestionToken */; + case 91 /* openBracket */: + pos++; + return token = 22 /* OpenBracketToken */; + case 93 /* closeBracket */: + pos++; + return token = 23 /* CloseBracketToken */; + case 94 /* caret */: + if (text.charCodeAt(pos + 1) === 61 /* equals */) { + return pos += 2, token = 71 /* CaretEqualsToken */; + } + pos++; + return token = 51 /* CaretToken */; + case 123 /* openBrace */: + pos++; + return token = 18 /* OpenBraceToken */; + case 124 /* bar */: + if (isConflictMarkerTrivia(text, pos)) { + pos = scanConflictMarkerTrivia(text, pos, error); + if (skipTrivia) { + continue; + } + else { + return token = 7 /* ConflictMarkerTrivia */; + } + } + if (text.charCodeAt(pos + 1) === 124 /* bar */) { + return pos += 2, token = 55 /* BarBarToken */; + } + if (text.charCodeAt(pos + 1) === 61 /* equals */) { + return pos += 2, token = 70 /* BarEqualsToken */; + } + pos++; + return token = 50 /* BarToken */; + case 125 /* closeBrace */: + pos++; + return token = 19 /* CloseBraceToken */; + case 126 /* tilde */: + pos++; + return token = 53 /* TildeToken */; + case 64 /* at */: + pos++; + return token = 58 /* AtToken */; + case 92 /* backslash */: + var cookedChar = peekUnicodeEscape(); + if (cookedChar >= 0 && isIdentifierStart(cookedChar, languageVersion)) { + pos += 6; + tokenValue = String.fromCharCode(cookedChar) + scanIdentifierParts(); + return token = getIdentifierToken(); + } + error(ts.Diagnostics.Invalid_character); + pos++; + return token = 0 /* Unknown */; + default: + if (isIdentifierStart(ch, languageVersion)) { + pos++; + while (pos < end && isIdentifierPart(ch = text.charCodeAt(pos), languageVersion)) + pos++; + tokenValue = text.substring(tokenPos, pos); + if (ch === 92 /* backslash */) { + tokenValue += scanIdentifierParts(); + } + return token = getIdentifierToken(); + } + else if (isWhiteSpaceSingleLine(ch)) { + pos++; + continue; + } + else if (isLineBreak(ch)) { + tokenFlags |= 1 /* PrecedingLineBreak */; + pos++; + continue; + } + error(ts.Diagnostics.Invalid_character); + pos++; + return token = 0 /* Unknown */; + } + } + } + function reScanGreaterToken() { + if (token === 30 /* GreaterThanToken */) { + if (text.charCodeAt(pos) === 62 /* greaterThan */) { + if (text.charCodeAt(pos + 1) === 62 /* greaterThan */) { + if (text.charCodeAt(pos + 2) === 61 /* equals */) { + return pos += 3, token = 68 /* GreaterThanGreaterThanGreaterThanEqualsToken */; + } + return pos += 2, token = 48 /* GreaterThanGreaterThanGreaterThanToken */; + } + if (text.charCodeAt(pos + 1) === 61 /* equals */) { + return pos += 2, token = 67 /* GreaterThanGreaterThanEqualsToken */; + } + pos++; + return token = 47 /* GreaterThanGreaterThanToken */; + } + if (text.charCodeAt(pos) === 61 /* equals */) { + pos++; + return token = 32 /* GreaterThanEqualsToken */; + } + } + return token; + } + function reScanSlashToken() { + if (token === 42 /* SlashToken */ || token === 64 /* SlashEqualsToken */) { + var p = tokenPos + 1; + var inEscape = false; + var inCharacterClass = false; + while (true) { + // If we reach the end of a file, or hit a newline, then this is an unterminated + // regex. Report error and return what we have so far. + if (p >= end) { + tokenFlags |= 4 /* Unterminated */; + error(ts.Diagnostics.Unterminated_regular_expression_literal); + break; + } + var ch = text.charCodeAt(p); + if (isLineBreak(ch)) { + tokenFlags |= 4 /* Unterminated */; + error(ts.Diagnostics.Unterminated_regular_expression_literal); + break; + } + if (inEscape) { + // Parsing an escape character; + // reset the flag and just advance to the next char. + inEscape = false; + } + else if (ch === 47 /* slash */ && !inCharacterClass) { + // A slash within a character class is permissible, + // but in general it signals the end of the regexp literal. + p++; + break; + } + else if (ch === 91 /* openBracket */) { + inCharacterClass = true; + } + else if (ch === 92 /* backslash */) { + inEscape = true; + } + else if (ch === 93 /* closeBracket */) { + inCharacterClass = false; + } + p++; + } + while (p < end && isIdentifierPart(text.charCodeAt(p), languageVersion)) { + p++; + } + pos = p; + tokenValue = text.substring(tokenPos, pos); + token = 13 /* RegularExpressionLiteral */; + } + return token; + } + /** + * Unconditionally back up and scan a template expression portion. + */ + function reScanTemplateToken() { + ts.Debug.assert(token === 19 /* CloseBraceToken */, "'reScanTemplateToken' should only be called on a '}'"); + pos = tokenPos; + return token = scanTemplateAndSetTokenValue(); + } + function reScanJsxToken() { + pos = tokenPos = startPos; + return token = scanJsxToken(); + } + function scanJsxToken() { + startPos = tokenPos = pos; + if (pos >= end) { + return token = 1 /* EndOfFileToken */; + } + var char = text.charCodeAt(pos); + if (char === 60 /* lessThan */) { + if (text.charCodeAt(pos + 1) === 47 /* slash */) { + pos += 2; + return token = 29 /* LessThanSlashToken */; + } + pos++; + return token = 28 /* LessThanToken */; + } + if (char === 123 /* openBrace */) { + pos++; + return token = 18 /* OpenBraceToken */; + } + // First non-whitespace character on this line. + var firstNonWhitespace = 0; + // These initial values are special because the first line is: + // firstNonWhitespace = 0 to indicate that we want leading whitspace, + while (pos < end) { + char = text.charCodeAt(pos); + if (char === 123 /* openBrace */) { + break; + } + if (char === 60 /* lessThan */) { + if (isConflictMarkerTrivia(text, pos)) { + pos = scanConflictMarkerTrivia(text, pos, error); + return token = 7 /* ConflictMarkerTrivia */; + } + break; + } + // FirstNonWhitespace is 0, then we only see whitespaces so far. If we see a linebreak, we want to ignore that whitespaces. + // i.e (- : whitespace) + //
      ---- + //
      becomes
      + // + //
      ----
      becomes
      ----
      + if (isLineBreak(char) && firstNonWhitespace === 0) { + firstNonWhitespace = -1; + } + else if (!isWhiteSpaceLike(char)) { + firstNonWhitespace = pos; + } + pos++; + } + return firstNonWhitespace === -1 ? 12 /* JsxTextAllWhiteSpaces */ : 11 /* JsxText */; + } + // Scans a JSX identifier; these differ from normal identifiers in that + // they allow dashes + function scanJsxIdentifier() { + if (tokenIsIdentifierOrKeyword(token)) { + var firstCharPosition = pos; + while (pos < end) { + var ch = text.charCodeAt(pos); + if (ch === 45 /* minus */ || ((firstCharPosition === pos) ? isIdentifierStart(ch, languageVersion) : isIdentifierPart(ch, languageVersion))) { + pos++; + } + else { + break; + } + } + tokenValue += text.substring(firstCharPosition, pos); + } + return token; + } + function scanJsxAttributeValue() { + startPos = pos; + switch (text.charCodeAt(pos)) { + case 34 /* doubleQuote */: + case 39 /* singleQuote */: + tokenValue = scanString(/*jsxAttributeString*/ true); + return token = 10 /* StringLiteral */; + default: + // If this scans anything other than `{`, it's a parse error. + return scan(); + } + } + function scanJSDocToken() { + startPos = tokenPos = pos; + tokenFlags = 0; + if (pos >= end) { + return token = 1 /* EndOfFileToken */; + } + var ch = text.charCodeAt(pos); + pos++; + switch (ch) { + case 9 /* tab */: + case 11 /* verticalTab */: + case 12 /* formFeed */: + case 32 /* space */: + while (pos < end && isWhiteSpaceSingleLine(text.charCodeAt(pos))) { + pos++; + } + return token = 5 /* WhitespaceTrivia */; + case 64 /* at */: + return token = 58 /* AtToken */; + case 10 /* lineFeed */: + case 13 /* carriageReturn */: + tokenFlags |= 1 /* PrecedingLineBreak */; + return token = 4 /* NewLineTrivia */; + case 42 /* asterisk */: + return token = 40 /* AsteriskToken */; + case 123 /* openBrace */: + return token = 18 /* OpenBraceToken */; + case 125 /* closeBrace */: + return token = 19 /* CloseBraceToken */; + case 91 /* openBracket */: + return token = 22 /* OpenBracketToken */; + case 93 /* closeBracket */: + return token = 23 /* CloseBracketToken */; + case 60 /* lessThan */: + return token = 28 /* LessThanToken */; + case 61 /* equals */: + return token = 59 /* EqualsToken */; + case 44 /* comma */: + return token = 27 /* CommaToken */; + case 46 /* dot */: + return token = 24 /* DotToken */; + case 96 /* backtick */: + while (pos < end && text.charCodeAt(pos) !== 96 /* backtick */) { + pos++; + } + tokenValue = text.substring(tokenPos + 1, pos); + pos++; + return token = 14 /* NoSubstitutionTemplateLiteral */; + } + if (isIdentifierStart(ch, 6 /* Latest */)) { + while (isIdentifierPart(text.charCodeAt(pos), 6 /* Latest */) && pos < end) { + pos++; + } + tokenValue = text.substring(tokenPos, pos); + return token = getIdentifierToken(); + } + else { + return token = 0 /* Unknown */; + } + } + function speculationHelper(callback, isLookahead) { + var savePos = pos; + var saveStartPos = startPos; + var saveTokenPos = tokenPos; + var saveToken = token; + var saveTokenValue = tokenValue; + var saveTokenFlags = tokenFlags; + var result = callback(); + // If our callback returned something 'falsy' or we're just looking ahead, + // then unconditionally restore us to where we were. + if (!result || isLookahead) { + pos = savePos; + startPos = saveStartPos; + tokenPos = saveTokenPos; + token = saveToken; + tokenValue = saveTokenValue; + tokenFlags = saveTokenFlags; + } + return result; + } + function scanRange(start, length, callback) { + var saveEnd = end; + var savePos = pos; + var saveStartPos = startPos; + var saveTokenPos = tokenPos; + var saveToken = token; + var saveTokenValue = tokenValue; + var saveTokenFlags = tokenFlags; + setText(text, start, length); + var result = callback(); + end = saveEnd; + pos = savePos; + startPos = saveStartPos; + tokenPos = saveTokenPos; + token = saveToken; + tokenValue = saveTokenValue; + tokenFlags = saveTokenFlags; + return result; + } + function lookAhead(callback) { + return speculationHelper(callback, /*isLookahead*/ true); + } + function tryScan(callback) { + return speculationHelper(callback, /*isLookahead*/ false); + } + function getText() { + return text; + } + function setText(newText, start, length) { + text = newText || ""; + end = length === undefined ? text.length : start + length; + setTextPos(start || 0); + } + function setOnError(errorCallback) { + onError = errorCallback; + } + function setScriptTarget(scriptTarget) { + languageVersion = scriptTarget; + } + function setLanguageVariant(variant) { + languageVariant = variant; + } + function setTextPos(textPos) { + ts.Debug.assert(textPos >= 0); + pos = textPos; + startPos = textPos; + tokenPos = textPos; + token = 0 /* Unknown */; + tokenValue = undefined; + tokenFlags = 0; + } + function setInJSDocType(inType) { + inJSDocType += inType ? 1 : -1; + } + } + ts.createScanner = createScanner; +})(ts || (ts = {})); +var ts; +(function (ts) { + function isExternalModuleNameRelative(moduleName) { + // TypeScript 1.0 spec (April 2014): 11.2.1 + // An external module name is "relative" if the first term is "." or "..". + // Update: We also consider a path like `C:\foo.ts` "relative" because we do not search for it in `node_modules` or treat it as an ambient module. + return ts.pathIsRelative(moduleName) || ts.isRootedDiskPath(moduleName); + } + ts.isExternalModuleNameRelative = isExternalModuleNameRelative; + function sortAndDeduplicateDiagnostics(diagnostics) { + return ts.sortAndDeduplicate(diagnostics, ts.compareDiagnostics); + } + ts.sortAndDeduplicateDiagnostics = sortAndDeduplicateDiagnostics; +})(ts || (ts = {})); +/* @internal */ +(function (ts) { + ts.resolvingEmptyArray = []; + ts.emptyMap = ts.createMap(); + ts.emptyUnderscoreEscapedMap = ts.emptyMap; + ts.externalHelpersModuleNameText = "tslib"; + ts.defaultMaximumTruncationLength = 160; + function getDeclarationOfKind(symbol, kind) { + var declarations = symbol.declarations; + if (declarations) { + for (var _i = 0, declarations_1 = declarations; _i < declarations_1.length; _i++) { + var declaration = declarations_1[_i]; + if (declaration.kind === kind) { + return declaration; + } + } + } + return undefined; + } + ts.getDeclarationOfKind = getDeclarationOfKind; + /** Create a new escaped identifier map. */ + function createUnderscoreEscapedMap() { + return new ts.MapCtr(); + } + ts.createUnderscoreEscapedMap = createUnderscoreEscapedMap; + function hasEntries(map) { + return !!map && !!map.size; + } + ts.hasEntries = hasEntries; + function createSymbolTable(symbols) { + var result = ts.createMap(); + if (symbols) { + for (var _i = 0, symbols_1 = symbols; _i < symbols_1.length; _i++) { + var symbol = symbols_1[_i]; + result.set(symbol.escapedName, symbol); + } + } + return result; + } + ts.createSymbolTable = createSymbolTable; + var stringWriter = createSingleLineStringWriter(); + function createSingleLineStringWriter() { + var str = ""; + var writeText = function (text) { return str += text; }; + return { + getText: function () { return str; }, + write: writeText, + rawWrite: writeText, + writeKeyword: writeText, + writeOperator: writeText, + writePunctuation: writeText, + writeSpace: writeText, + writeStringLiteral: writeText, + writeLiteral: writeText, + writeParameter: writeText, + writeProperty: writeText, + writeSymbol: function (s, _) { return writeText(s); }, + writeTrailingSemicolon: writeText, + writeComment: writeText, + getTextPos: function () { return str.length; }, + getLine: function () { return 0; }, + getColumn: function () { return 0; }, + getIndent: function () { return 0; }, + isAtStartOfLine: function () { return false; }, + // Completely ignore indentation for string writers. And map newlines to + // a single space. + writeLine: function () { return str += " "; }, + increaseIndent: ts.noop, + decreaseIndent: ts.noop, + clear: function () { return str = ""; }, + trackSymbol: ts.noop, + reportInaccessibleThisError: ts.noop, + reportInaccessibleUniqueSymbolError: ts.noop, + reportPrivateInBaseOfClassExpression: ts.noop, + }; + } + function toPath(fileName, basePath, getCanonicalFileName) { + var nonCanonicalizedPath = ts.isRootedDiskPath(fileName) + ? ts.normalizePath(fileName) + : ts.getNormalizedAbsolutePath(fileName, basePath); + return getCanonicalFileName(nonCanonicalizedPath); + } + ts.toPath = toPath; + function changesAffectModuleResolution(oldOptions, newOptions) { + return oldOptions.configFilePath !== newOptions.configFilePath || ts.moduleResolutionOptionDeclarations.some(function (o) { + return !ts.isJsonEqual(ts.getCompilerOptionValue(oldOptions, o), ts.getCompilerOptionValue(newOptions, o)); + }); + } + ts.changesAffectModuleResolution = changesAffectModuleResolution; + function findAncestor(node, callback) { + while (node) { + var result = callback(node); + if (result === "quit") { + return undefined; + } + else if (result) { + return node; + } + node = node.parent; + } + return undefined; + } + ts.findAncestor = findAncestor; + function forEachAncestor(node, callback) { + while (true) { + var res = callback(node); + if (res === "quit") + return undefined; + if (res !== undefined) + return res; + if (ts.isSourceFile(node)) + return undefined; + node = node.parent; + } + } + ts.forEachAncestor = forEachAncestor; + function forEachEntry(map, callback) { + var _a; + var iterator = map.entries(); + for (var _b = iterator.next(), pair = _b.value, done = _b.done; !done; _a = iterator.next(), pair = _a.value, done = _a.done, _a) { + var key = pair[0], value = pair[1]; + var result = callback(value, key); + if (result) { + return result; + } + } + return undefined; + } + ts.forEachEntry = forEachEntry; + function forEachKey(map, callback) { + var _a; + var iterator = map.keys(); + for (var _b = iterator.next(), key = _b.value, done = _b.done; !done; _a = iterator.next(), key = _a.value, done = _a.done, _a) { + var result = callback(key); + if (result) { + return result; + } + } + return undefined; + } + ts.forEachKey = forEachKey; + function copyEntries(source, target) { + source.forEach(function (value, key) { + target.set(key, value); + }); + } + ts.copyEntries = copyEntries; + function arrayToSet(array, makeKey) { + return ts.arrayToMap(array, makeKey || (function (s) { return s; }), function () { return true; }); + } + ts.arrayToSet = arrayToSet; + function cloneMap(map) { + var clone = ts.createMap(); + copyEntries(map, clone); + return clone; + } + ts.cloneMap = cloneMap; + function usingSingleLineStringWriter(action) { + var oldString = stringWriter.getText(); + try { + action(stringWriter); + return stringWriter.getText(); + } + finally { + stringWriter.clear(); + stringWriter.writeKeyword(oldString); + } + } + ts.usingSingleLineStringWriter = usingSingleLineStringWriter; + function getFullWidth(node) { + return node.end - node.pos; + } + ts.getFullWidth = getFullWidth; + function getResolvedModule(sourceFile, moduleNameText) { + return sourceFile && sourceFile.resolvedModules && sourceFile.resolvedModules.get(moduleNameText); + } + ts.getResolvedModule = getResolvedModule; + function setResolvedModule(sourceFile, moduleNameText, resolvedModule) { + if (!sourceFile.resolvedModules) { + sourceFile.resolvedModules = ts.createMap(); + } + sourceFile.resolvedModules.set(moduleNameText, resolvedModule); + } + ts.setResolvedModule = setResolvedModule; + function setResolvedTypeReferenceDirective(sourceFile, typeReferenceDirectiveName, resolvedTypeReferenceDirective) { + if (!sourceFile.resolvedTypeReferenceDirectiveNames) { + sourceFile.resolvedTypeReferenceDirectiveNames = ts.createMap(); + } + sourceFile.resolvedTypeReferenceDirectiveNames.set(typeReferenceDirectiveName, resolvedTypeReferenceDirective); + } + ts.setResolvedTypeReferenceDirective = setResolvedTypeReferenceDirective; + function projectReferenceIsEqualTo(oldRef, newRef) { + return oldRef.path === newRef.path && + !oldRef.prepend === !newRef.prepend && + !oldRef.circular === !newRef.circular; + } + ts.projectReferenceIsEqualTo = projectReferenceIsEqualTo; + function moduleResolutionIsEqualTo(oldResolution, newResolution) { + return oldResolution.isExternalLibraryImport === newResolution.isExternalLibraryImport && + oldResolution.extension === newResolution.extension && + oldResolution.resolvedFileName === newResolution.resolvedFileName && + oldResolution.originalPath === newResolution.originalPath && + packageIdIsEqual(oldResolution.packageId, newResolution.packageId); + } + ts.moduleResolutionIsEqualTo = moduleResolutionIsEqualTo; + function packageIdIsEqual(a, b) { + return a === b || !!a && !!b && a.name === b.name && a.subModuleName === b.subModuleName && a.version === b.version; + } + function packageIdToString(_a) { + var name = _a.name, subModuleName = _a.subModuleName, version = _a.version; + var fullName = subModuleName ? name + "/" + subModuleName : name; + return fullName + "@" + version; + } + ts.packageIdToString = packageIdToString; + function typeDirectiveIsEqualTo(oldResolution, newResolution) { + return oldResolution.resolvedFileName === newResolution.resolvedFileName && oldResolution.primary === newResolution.primary; + } + ts.typeDirectiveIsEqualTo = typeDirectiveIsEqualTo; + function hasChangesInResolutions(names, newResolutions, oldResolutions, comparer) { + ts.Debug.assert(names.length === newResolutions.length); + for (var i = 0; i < names.length; i++) { + var newResolution = newResolutions[i]; + var oldResolution = oldResolutions && oldResolutions.get(names[i]); + var changed = oldResolution + ? !newResolution || !comparer(oldResolution, newResolution) + : newResolution; + if (changed) { + return true; + } + } + return false; + } + ts.hasChangesInResolutions = hasChangesInResolutions; + // Returns true if this node contains a parse error anywhere underneath it. + function containsParseError(node) { + aggregateChildData(node); + return (node.flags & 131072 /* ThisNodeOrAnySubNodesHasError */) !== 0; + } + ts.containsParseError = containsParseError; + function aggregateChildData(node) { + if (!(node.flags & 262144 /* HasAggregatedChildData */)) { + // A node is considered to contain a parse error if: + // a) the parser explicitly marked that it had an error + // b) any of it's children reported that it had an error. + var thisNodeOrAnySubNodesHasError = ((node.flags & 32768 /* ThisNodeHasError */) !== 0) || + ts.forEachChild(node, containsParseError); + // If so, mark ourselves accordingly. + if (thisNodeOrAnySubNodesHasError) { + node.flags |= 131072 /* ThisNodeOrAnySubNodesHasError */; + } + // Also mark that we've propagated the child information to this node. This way we can + // always consult the bit directly on this node without needing to check its children + // again. + node.flags |= 262144 /* HasAggregatedChildData */; + } + } + function getSourceFileOfNode(node) { + while (node && node.kind !== 279 /* SourceFile */) { + node = node.parent; + } + return node; + } + ts.getSourceFileOfNode = getSourceFileOfNode; + function isStatementWithLocals(node) { + switch (node.kind) { + case 218 /* Block */: + case 246 /* CaseBlock */: + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + return true; + } + return false; + } + ts.isStatementWithLocals = isStatementWithLocals; + function getStartPositionOfLine(line, sourceFile) { + ts.Debug.assert(line >= 0); + return ts.getLineStarts(sourceFile)[line]; + } + ts.getStartPositionOfLine = getStartPositionOfLine; + // This is a useful function for debugging purposes. + function nodePosToString(node) { + var file = getSourceFileOfNode(node); + var loc = ts.getLineAndCharacterOfPosition(file, node.pos); + return file.fileName + "(" + (loc.line + 1) + "," + (loc.character + 1) + ")"; + } + ts.nodePosToString = nodePosToString; + function getEndLinePosition(line, sourceFile) { + ts.Debug.assert(line >= 0); + var lineStarts = ts.getLineStarts(sourceFile); + var lineIndex = line; + var sourceText = sourceFile.text; + if (lineIndex + 1 === lineStarts.length) { + // last line - return EOF + return sourceText.length - 1; + } + else { + // current line start + var start = lineStarts[lineIndex]; + // take the start position of the next line - 1 = it should be some line break + var pos = lineStarts[lineIndex + 1] - 1; + ts.Debug.assert(ts.isLineBreak(sourceText.charCodeAt(pos))); + // walk backwards skipping line breaks, stop the the beginning of current line. + // i.e: + // + // $ <- end of line for this position should match the start position + while (start <= pos && ts.isLineBreak(sourceText.charCodeAt(pos))) { + pos--; + } + return pos; + } + } + ts.getEndLinePosition = getEndLinePosition; + /** + * Returns a value indicating whether a name is unique globally or within the current file. + * Note: This does not consider whether a name appears as a free identifier or not, so at the expression `x.y` this includes both `x` and `y`. + */ + function isFileLevelUniqueName(sourceFile, name, hasGlobalName) { + return !(hasGlobalName && hasGlobalName(name)) && !sourceFile.identifiers.has(name); + } + ts.isFileLevelUniqueName = isFileLevelUniqueName; + // Returns true if this node is missing from the actual source code. A 'missing' node is different + // from 'undefined/defined'. When a node is undefined (which can happen for optional nodes + // in the tree), it is definitely missing. However, a node may be defined, but still be + // missing. This happens whenever the parser knows it needs to parse something, but can't + // get anything in the source code that it expects at that location. For example: + // + // let a: ; + // + // Here, the Type in the Type-Annotation is not-optional (as there is a colon in the source + // code). So the parser will attempt to parse out a type, and will create an actual node. + // However, this node will be 'missing' in the sense that no actual source-code/tokens are + // contained within it. + function nodeIsMissing(node) { + if (node === undefined) { + return true; + } + return node.pos === node.end && node.pos >= 0 && node.kind !== 1 /* EndOfFileToken */; + } + ts.nodeIsMissing = nodeIsMissing; + function nodeIsPresent(node) { + return !nodeIsMissing(node); + } + ts.nodeIsPresent = nodeIsPresent; + /** + * Prepends statements to an array while taking care of prologue directives. + */ + function addStatementsAfterPrologue(to, from) { + if (from === undefined || from.length === 0) + return to; + var statementIndex = 0; + // skip all prologue directives to insert at the correct position + for (; statementIndex < to.length; ++statementIndex) { + if (!isPrologueDirective(to[statementIndex])) { + break; + } + } + to.splice.apply(to, [statementIndex, 0].concat(from)); + return to; + } + ts.addStatementsAfterPrologue = addStatementsAfterPrologue; + /** + * Determine if the given comment is a triple-slash + * + * @return true if the comment is a triple-slash comment else false + */ + function isRecognizedTripleSlashComment(text, commentPos, commentEnd) { + // Verify this is /// comment, but do the regexp match only when we first can find /// in the comment text + // so that we don't end up computing comment string and doing match for all // comments + if (text.charCodeAt(commentPos + 1) === 47 /* slash */ && + commentPos + 2 < commentEnd && + text.charCodeAt(commentPos + 2) === 47 /* slash */) { + var textSubStr = text.substring(commentPos, commentEnd); + return textSubStr.match(ts.fullTripleSlashReferencePathRegEx) || + textSubStr.match(ts.fullTripleSlashAMDReferencePathRegEx) || + textSubStr.match(fullTripleSlashReferenceTypeReferenceDirectiveRegEx) || + textSubStr.match(defaultLibReferenceRegEx) ? + true : false; + } + return false; + } + ts.isRecognizedTripleSlashComment = isRecognizedTripleSlashComment; + function isPinnedComment(text, start) { + return text.charCodeAt(start + 1) === 42 /* asterisk */ && + text.charCodeAt(start + 2) === 33 /* exclamation */; + } + ts.isPinnedComment = isPinnedComment; + function getTokenPosOfNode(node, sourceFile, includeJsDoc) { + // With nodes that have no width (i.e. 'Missing' nodes), we actually *don't* + // want to skip trivia because this will launch us forward to the next token. + if (nodeIsMissing(node)) { + return node.pos; + } + if (ts.isJSDocNode(node)) { + return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos, /*stopAfterLineBreak*/ false, /*stopAtComments*/ true); + } + if (includeJsDoc && ts.hasJSDocNodes(node)) { + return getTokenPosOfNode(node.jsDoc[0]); + } + // For a syntax list, it is possible that one of its children has JSDocComment nodes, while + // the syntax list itself considers them as normal trivia. Therefore if we simply skip + // trivia for the list, we may have skipped the JSDocComment as well. So we should process its + // first child to determine the actual position of its first token. + if (node.kind === 306 /* SyntaxList */ && node._children.length > 0) { + return getTokenPosOfNode(node._children[0], sourceFile, includeJsDoc); + } + return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos); + } + ts.getTokenPosOfNode = getTokenPosOfNode; + function getNonDecoratorTokenPosOfNode(node, sourceFile) { + if (nodeIsMissing(node) || !node.decorators) { + return getTokenPosOfNode(node, sourceFile); + } + return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.decorators.end); + } + ts.getNonDecoratorTokenPosOfNode = getNonDecoratorTokenPosOfNode; + function getSourceTextOfNodeFromSourceFile(sourceFile, node, includeTrivia) { + if (includeTrivia === void 0) { includeTrivia = false; } + return getTextOfNodeFromSourceText(sourceFile.text, node, includeTrivia); + } + ts.getSourceTextOfNodeFromSourceFile = getSourceTextOfNodeFromSourceFile; + function isJSDocTypeExpressionOrChild(node) { + return node.kind === 283 /* JSDocTypeExpression */ || (node.parent && isJSDocTypeExpressionOrChild(node.parent)); + } + function getTextOfNodeFromSourceText(sourceText, node, includeTrivia) { + if (includeTrivia === void 0) { includeTrivia = false; } + if (nodeIsMissing(node)) { + return ""; + } + var text = sourceText.substring(includeTrivia ? node.pos : ts.skipTrivia(sourceText, node.pos), node.end); + if (isJSDocTypeExpressionOrChild(node)) { + // strip space + asterisk at line start + text = text.replace(/(^|\r?\n|\r)\s*\*\s*/g, "$1"); + } + return text; + } + ts.getTextOfNodeFromSourceText = getTextOfNodeFromSourceText; + function getTextOfNode(node, includeTrivia) { + if (includeTrivia === void 0) { includeTrivia = false; } + return getSourceTextOfNodeFromSourceFile(getSourceFileOfNode(node), node, includeTrivia); + } + ts.getTextOfNode = getTextOfNode; + function getPos(range) { + return range.pos; + } + /** + * Note: it is expected that the `nodeArray` and the `node` are within the same file. + * For example, searching for a `SourceFile` in a `SourceFile[]` wouldn't work. + */ + function indexOfNode(nodeArray, node) { + return ts.binarySearch(nodeArray, node, getPos, ts.compareValues); + } + ts.indexOfNode = indexOfNode; + /** + * Gets flags that control emit behavior of a node. + */ + function getEmitFlags(node) { + var emitNode = node.emitNode; + return emitNode && emitNode.flags || 0; + } + ts.getEmitFlags = getEmitFlags; + function getLiteralText(node, sourceFile, neverAsciiEscape) { + // If we don't need to downlevel and we can reach the original source text using + // the node's parent reference, then simply get the text as it was originally written. + if (!nodeIsSynthesized(node) && node.parent && !((ts.isNumericLiteral(node) && node.numericLiteralFlags & 512 /* ContainsSeparator */) || + ts.isBigIntLiteral(node))) { + return getSourceTextOfNodeFromSourceFile(sourceFile, node); + } + var escapeText = neverAsciiEscape || (getEmitFlags(node) & 16777216 /* NoAsciiEscaping */) ? escapeString : escapeNonAsciiString; + // If we can't reach the original source text, use the canonical form if it's a number, + // or a (possibly escaped) quoted form of the original text if it's string-like. + switch (node.kind) { + case 10 /* StringLiteral */: + if (node.singleQuote) { + return "'" + escapeText(node.text, 39 /* singleQuote */) + "'"; + } + else { + return '"' + escapeText(node.text, 34 /* doubleQuote */) + '"'; + } + case 14 /* NoSubstitutionTemplateLiteral */: + return "`" + escapeText(node.text, 96 /* backtick */) + "`"; + case 15 /* TemplateHead */: + // tslint:disable-next-line no-invalid-template-strings + return "`" + escapeText(node.text, 96 /* backtick */) + "${"; + case 16 /* TemplateMiddle */: + // tslint:disable-next-line no-invalid-template-strings + return "}" + escapeText(node.text, 96 /* backtick */) + "${"; + case 17 /* TemplateTail */: + return "}" + escapeText(node.text, 96 /* backtick */) + "`"; + case 8 /* NumericLiteral */: + case 9 /* BigIntLiteral */: + case 13 /* RegularExpressionLiteral */: + return node.text; + } + return ts.Debug.fail("Literal kind '" + node.kind + "' not accounted for."); + } + ts.getLiteralText = getLiteralText; + function getTextOfConstantValue(value) { + return ts.isString(value) ? '"' + escapeNonAsciiString(value) + '"' : "" + value; + } + ts.getTextOfConstantValue = getTextOfConstantValue; + // Make an identifier from an external module name by extracting the string after the last "/" and replacing + // all non-alphanumeric characters with underscores + function makeIdentifierFromModuleName(moduleName) { + return ts.getBaseFileName(moduleName).replace(/^(\d)/, "_$1").replace(/\W/g, "_"); + } + ts.makeIdentifierFromModuleName = makeIdentifierFromModuleName; + function isBlockOrCatchScoped(declaration) { + return (ts.getCombinedNodeFlags(declaration) & 3 /* BlockScoped */) !== 0 || + isCatchClauseVariableDeclarationOrBindingElement(declaration); + } + ts.isBlockOrCatchScoped = isBlockOrCatchScoped; + function isCatchClauseVariableDeclarationOrBindingElement(declaration) { + var node = getRootDeclaration(declaration); + return node.kind === 237 /* VariableDeclaration */ && node.parent.kind === 274 /* CatchClause */; + } + ts.isCatchClauseVariableDeclarationOrBindingElement = isCatchClauseVariableDeclarationOrBindingElement; + function isAmbientModule(node) { + return ts.isModuleDeclaration(node) && (node.name.kind === 10 /* StringLiteral */ || isGlobalScopeAugmentation(node)); + } + ts.isAmbientModule = isAmbientModule; + function isModuleWithStringLiteralName(node) { + return ts.isModuleDeclaration(node) && node.name.kind === 10 /* StringLiteral */; + } + ts.isModuleWithStringLiteralName = isModuleWithStringLiteralName; + function isNonGlobalAmbientModule(node) { + return ts.isModuleDeclaration(node) && ts.isStringLiteral(node.name); + } + ts.isNonGlobalAmbientModule = isNonGlobalAmbientModule; + /** + * An effective module (namespace) declaration is either + * 1. An actual declaration: namespace X { ... } + * 2. A Javascript declaration, which is: + * An identifier in a nested property access expression: Y in `X.Y.Z = { ... }` + */ + function isEffectiveModuleDeclaration(node) { + return ts.isModuleDeclaration(node) || ts.isIdentifier(node); + } + ts.isEffectiveModuleDeclaration = isEffectiveModuleDeclaration; + /** Given a symbol for a module, checks that it is a shorthand ambient module. */ + function isShorthandAmbientModuleSymbol(moduleSymbol) { + return isShorthandAmbientModule(moduleSymbol.valueDeclaration); + } + ts.isShorthandAmbientModuleSymbol = isShorthandAmbientModuleSymbol; + function isShorthandAmbientModule(node) { + // The only kind of module that can be missing a body is a shorthand ambient module. + return node && node.kind === 244 /* ModuleDeclaration */ && (!node.body); + } + function isBlockScopedContainerTopLevel(node) { + return node.kind === 279 /* SourceFile */ || + node.kind === 244 /* ModuleDeclaration */ || + ts.isFunctionLike(node); + } + ts.isBlockScopedContainerTopLevel = isBlockScopedContainerTopLevel; + function isGlobalScopeAugmentation(module) { + return !!(module.flags & 512 /* GlobalAugmentation */); + } + ts.isGlobalScopeAugmentation = isGlobalScopeAugmentation; + function isExternalModuleAugmentation(node) { + return isAmbientModule(node) && isModuleAugmentationExternal(node); + } + ts.isExternalModuleAugmentation = isExternalModuleAugmentation; + function isModuleAugmentationExternal(node) { + // external module augmentation is a ambient module declaration that is either: + // - defined in the top level scope and source file is an external module + // - defined inside ambient module declaration located in the top level scope and source file not an external module + switch (node.parent.kind) { + case 279 /* SourceFile */: + return ts.isExternalModule(node.parent); + case 245 /* ModuleBlock */: + return isAmbientModule(node.parent.parent) && ts.isSourceFile(node.parent.parent.parent) && !ts.isExternalModule(node.parent.parent.parent); + } + return false; + } + ts.isModuleAugmentationExternal = isModuleAugmentationExternal; + function getNonAugmentationDeclaration(symbol) { + return ts.find(symbol.declarations, function (d) { return !isExternalModuleAugmentation(d) && !(ts.isModuleDeclaration(d) && isGlobalScopeAugmentation(d)); }); + } + ts.getNonAugmentationDeclaration = getNonAugmentationDeclaration; + function isEffectiveExternalModule(node, compilerOptions) { + return ts.isExternalModule(node) || compilerOptions.isolatedModules || ((ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS) && !!node.commonJsModuleIndicator); + } + ts.isEffectiveExternalModule = isEffectiveExternalModule; + function isBlockScope(node, parentNode) { + switch (node.kind) { + case 279 /* SourceFile */: + case 246 /* CaseBlock */: + case 274 /* CatchClause */: + case 244 /* ModuleDeclaration */: + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + case 157 /* Constructor */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + return true; + case 218 /* Block */: + // function block is not considered block-scope container + // see comment in binder.ts: bind(...), case for SyntaxKind.Block + return !ts.isFunctionLike(parentNode); + } + return false; + } + ts.isBlockScope = isBlockScope; + function isDeclarationWithTypeParameters(node) { + switch (node.kind) { + case 297 /* JSDocCallbackTag */: + case 304 /* JSDocTypedefTag */: + case 293 /* JSDocSignature */: + return true; + default: + ts.assertType(node); + return isDeclarationWithTypeParameterChildren(node); + } + } + ts.isDeclarationWithTypeParameters = isDeclarationWithTypeParameters; + function isDeclarationWithTypeParameterChildren(node) { + switch (node.kind) { + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 155 /* MethodSignature */: + case 162 /* IndexSignature */: + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + case 289 /* JSDocFunctionType */: + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 241 /* InterfaceDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 303 /* JSDocTemplateTag */: + case 239 /* FunctionDeclaration */: + case 156 /* MethodDeclaration */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + return true; + default: + ts.assertType(node); + return false; + } + } + ts.isDeclarationWithTypeParameterChildren = isDeclarationWithTypeParameterChildren; + function isAnyImportSyntax(node) { + switch (node.kind) { + case 249 /* ImportDeclaration */: + case 248 /* ImportEqualsDeclaration */: + return true; + default: + return false; + } + } + ts.isAnyImportSyntax = isAnyImportSyntax; + function isLateVisibilityPaintedStatement(node) { + switch (node.kind) { + case 249 /* ImportDeclaration */: + case 248 /* ImportEqualsDeclaration */: + case 219 /* VariableStatement */: + case 240 /* ClassDeclaration */: + case 239 /* FunctionDeclaration */: + case 244 /* ModuleDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 241 /* InterfaceDeclaration */: + case 243 /* EnumDeclaration */: + return true; + default: + return false; + } + } + ts.isLateVisibilityPaintedStatement = isLateVisibilityPaintedStatement; + function isAnyImportOrReExport(node) { + return isAnyImportSyntax(node) || ts.isExportDeclaration(node); + } + ts.isAnyImportOrReExport = isAnyImportOrReExport; + // Gets the nearest enclosing block scope container that has the provided node + // as a descendant, that is not the provided node. + function getEnclosingBlockScopeContainer(node) { + return findAncestor(node.parent, function (current) { return isBlockScope(current, current.parent); }); + } + ts.getEnclosingBlockScopeContainer = getEnclosingBlockScopeContainer; + // Return display name of an identifier + // Computed property names will just be emitted as "[]", where is the source + // text of the expression in the computed property. + function declarationNameToString(name) { + return !name || getFullWidth(name) === 0 ? "(Missing)" : getTextOfNode(name); + } + ts.declarationNameToString = declarationNameToString; + function getNameFromIndexInfo(info) { + return info.declaration ? declarationNameToString(info.declaration.parameters[0].name) : undefined; + } + ts.getNameFromIndexInfo = getNameFromIndexInfo; + function getTextOfPropertyName(name) { + switch (name.kind) { + case 72 /* Identifier */: + return name.escapedText; + case 10 /* StringLiteral */: + case 8 /* NumericLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: + return ts.escapeLeadingUnderscores(name.text); + case 149 /* ComputedPropertyName */: + return isStringOrNumericLiteralLike(name.expression) ? ts.escapeLeadingUnderscores(name.expression.text) : undefined; // TODO: GH#18217 Almost all uses of this assume the result to be defined! + default: + return ts.Debug.assertNever(name); + } + } + ts.getTextOfPropertyName = getTextOfPropertyName; + function entityNameToString(name) { + switch (name.kind) { + case 72 /* Identifier */: + return getFullWidth(name) === 0 ? ts.idText(name) : getTextOfNode(name); + case 148 /* QualifiedName */: + return entityNameToString(name.left) + "." + entityNameToString(name.right); + case 189 /* PropertyAccessExpression */: + return entityNameToString(name.expression) + "." + entityNameToString(name.name); + default: + throw ts.Debug.assertNever(name); + } + } + ts.entityNameToString = entityNameToString; + function createDiagnosticForNode(node, message, arg0, arg1, arg2, arg3) { + var sourceFile = getSourceFileOfNode(node); + return createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2, arg3); + } + ts.createDiagnosticForNode = createDiagnosticForNode; + function createDiagnosticForNodeArray(sourceFile, nodes, message, arg0, arg1, arg2, arg3) { + var start = ts.skipTrivia(sourceFile.text, nodes.pos); + return ts.createFileDiagnostic(sourceFile, start, nodes.end - start, message, arg0, arg1, arg2, arg3); + } + ts.createDiagnosticForNodeArray = createDiagnosticForNodeArray; + function createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2, arg3) { + var span = getErrorSpanForNode(sourceFile, node); + return ts.createFileDiagnostic(sourceFile, span.start, span.length, message, arg0, arg1, arg2, arg3); + } + ts.createDiagnosticForNodeInSourceFile = createDiagnosticForNodeInSourceFile; + function createDiagnosticForNodeFromMessageChain(node, messageChain, relatedInformation) { + var sourceFile = getSourceFileOfNode(node); + var span = getErrorSpanForNode(sourceFile, node); + return { + file: sourceFile, + start: span.start, + length: span.length, + code: messageChain.code, + category: messageChain.category, + messageText: messageChain.next ? messageChain : messageChain.messageText, + relatedInformation: relatedInformation + }; + } + ts.createDiagnosticForNodeFromMessageChain = createDiagnosticForNodeFromMessageChain; + function getSpanOfTokenAtPosition(sourceFile, pos) { + var scanner = ts.createScanner(sourceFile.languageVersion, /*skipTrivia*/ true, sourceFile.languageVariant, sourceFile.text, /*onError:*/ undefined, pos); + scanner.scan(); + var start = scanner.getTokenPos(); + return ts.createTextSpanFromBounds(start, scanner.getTextPos()); + } + ts.getSpanOfTokenAtPosition = getSpanOfTokenAtPosition; + function getErrorSpanForArrowFunction(sourceFile, node) { + var pos = ts.skipTrivia(sourceFile.text, node.pos); + if (node.body && node.body.kind === 218 /* Block */) { + var startLine = ts.getLineAndCharacterOfPosition(sourceFile, node.body.pos).line; + var endLine = ts.getLineAndCharacterOfPosition(sourceFile, node.body.end).line; + if (startLine < endLine) { + // The arrow function spans multiple lines, + // make the error span be the first line, inclusive. + return ts.createTextSpan(pos, getEndLinePosition(startLine, sourceFile) - pos + 1); + } + } + return ts.createTextSpanFromBounds(pos, node.end); + } + function getErrorSpanForNode(sourceFile, node) { + var errorNode = node; + switch (node.kind) { + case 279 /* SourceFile */: + var pos_1 = ts.skipTrivia(sourceFile.text, 0, /*stopAfterLineBreak*/ false); + if (pos_1 === sourceFile.text.length) { + // file is empty - return span for the beginning of the file + return ts.createTextSpan(0, 0); + } + return getSpanOfTokenAtPosition(sourceFile, pos_1); + // This list is a work in progress. Add missing node kinds to improve their error + // spans. + case 237 /* VariableDeclaration */: + case 186 /* BindingElement */: + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 241 /* InterfaceDeclaration */: + case 244 /* ModuleDeclaration */: + case 243 /* EnumDeclaration */: + case 278 /* EnumMember */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 242 /* TypeAliasDeclaration */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + errorNode = node.name; + break; + case 197 /* ArrowFunction */: + return getErrorSpanForArrowFunction(sourceFile, node); + } + if (errorNode === undefined) { + // If we don't have a better node, then just set the error on the first token of + // construct. + return getSpanOfTokenAtPosition(sourceFile, node.pos); + } + var isMissing = nodeIsMissing(errorNode); + var pos = isMissing + ? errorNode.pos + : ts.skipTrivia(sourceFile.text, errorNode.pos); + // These asserts should all be satisfied for a properly constructed `errorNode`. + if (isMissing) { + ts.Debug.assert(pos === errorNode.pos, "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809"); + ts.Debug.assert(pos === errorNode.end, "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809"); + } + else { + ts.Debug.assert(pos >= errorNode.pos, "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809"); + ts.Debug.assert(pos <= errorNode.end, "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809"); + } + return ts.createTextSpanFromBounds(pos, errorNode.end); + } + ts.getErrorSpanForNode = getErrorSpanForNode; + function isExternalOrCommonJsModule(file) { + return (file.externalModuleIndicator || file.commonJsModuleIndicator) !== undefined; + } + ts.isExternalOrCommonJsModule = isExternalOrCommonJsModule; + function isJsonSourceFile(file) { + return file.scriptKind === 6 /* JSON */; + } + ts.isJsonSourceFile = isJsonSourceFile; + function isEnumConst(node) { + return !!(ts.getCombinedModifierFlags(node) & 2048 /* Const */); + } + ts.isEnumConst = isEnumConst; + function isDeclarationReadonly(declaration) { + return !!(ts.getCombinedModifierFlags(declaration) & 64 /* Readonly */ && !ts.isParameterPropertyDeclaration(declaration)); + } + ts.isDeclarationReadonly = isDeclarationReadonly; + function isVarConst(node) { + return !!(ts.getCombinedNodeFlags(node) & 2 /* Const */); + } + ts.isVarConst = isVarConst; + function isLet(node) { + return !!(ts.getCombinedNodeFlags(node) & 1 /* Let */); + } + ts.isLet = isLet; + function isSuperCall(n) { + return n.kind === 191 /* CallExpression */ && n.expression.kind === 98 /* SuperKeyword */; + } + ts.isSuperCall = isSuperCall; + function isImportCall(n) { + return n.kind === 191 /* CallExpression */ && n.expression.kind === 92 /* ImportKeyword */; + } + ts.isImportCall = isImportCall; + function isLiteralImportTypeNode(n) { + return ts.isImportTypeNode(n) && ts.isLiteralTypeNode(n.argument) && ts.isStringLiteral(n.argument.literal); + } + ts.isLiteralImportTypeNode = isLiteralImportTypeNode; + function isPrologueDirective(node) { + return node.kind === 221 /* ExpressionStatement */ + && node.expression.kind === 10 /* StringLiteral */; + } + ts.isPrologueDirective = isPrologueDirective; + function getLeadingCommentRangesOfNode(node, sourceFileOfNode) { + return node.kind !== 11 /* JsxText */ ? ts.getLeadingCommentRanges(sourceFileOfNode.text, node.pos) : undefined; + } + ts.getLeadingCommentRangesOfNode = getLeadingCommentRangesOfNode; + function getJSDocCommentRanges(node, text) { + var commentRanges = (node.kind === 151 /* Parameter */ || + node.kind === 150 /* TypeParameter */ || + node.kind === 196 /* FunctionExpression */ || + node.kind === 197 /* ArrowFunction */ || + node.kind === 195 /* ParenthesizedExpression */) ? + ts.concatenate(ts.getTrailingCommentRanges(text, node.pos), ts.getLeadingCommentRanges(text, node.pos)) : + ts.getLeadingCommentRanges(text, node.pos); + // True if the comment starts with '/**' but not if it is '/**/' + return ts.filter(commentRanges, function (comment) { + return text.charCodeAt(comment.pos + 1) === 42 /* asterisk */ && + text.charCodeAt(comment.pos + 2) === 42 /* asterisk */ && + text.charCodeAt(comment.pos + 3) !== 47 /* slash */; + }); + } + ts.getJSDocCommentRanges = getJSDocCommentRanges; + ts.fullTripleSlashReferencePathRegEx = /^(\/\/\/\s*/; + var fullTripleSlashReferenceTypeReferenceDirectiveRegEx = /^(\/\/\/\s*/; + ts.fullTripleSlashAMDReferencePathRegEx = /^(\/\/\/\s*/; + var defaultLibReferenceRegEx = /^(\/\/\/\s*/; + function isPartOfTypeNode(node) { + if (163 /* FirstTypeNode */ <= node.kind && node.kind <= 183 /* LastTypeNode */) { + return true; + } + switch (node.kind) { + case 120 /* AnyKeyword */: + case 143 /* UnknownKeyword */: + case 135 /* NumberKeyword */: + case 146 /* BigIntKeyword */: + case 138 /* StringKeyword */: + case 123 /* BooleanKeyword */: + case 139 /* SymbolKeyword */: + case 136 /* ObjectKeyword */: + case 141 /* UndefinedKeyword */: + case 132 /* NeverKeyword */: + return true; + case 106 /* VoidKeyword */: + return node.parent.kind !== 200 /* VoidExpression */; + case 211 /* ExpressionWithTypeArguments */: + return !isExpressionWithTypeArgumentsInClassExtendsClause(node); + case 150 /* TypeParameter */: + return node.parent.kind === 181 /* MappedType */ || node.parent.kind === 176 /* InferType */; + // Identifiers and qualified names may be type nodes, depending on their context. Climb + // above them to find the lowest container + case 72 /* Identifier */: + // If the identifier is the RHS of a qualified name, then it's a type iff its parent is. + if (node.parent.kind === 148 /* QualifiedName */ && node.parent.right === node) { + node = node.parent; + } + else if (node.parent.kind === 189 /* PropertyAccessExpression */ && node.parent.name === node) { + node = node.parent; + } + // At this point, node is either a qualified name or an identifier + ts.Debug.assert(node.kind === 72 /* Identifier */ || node.kind === 148 /* QualifiedName */ || node.kind === 189 /* PropertyAccessExpression */, "'node' was expected to be a qualified name, identifier or property access in 'isPartOfTypeNode'."); + // falls through + case 148 /* QualifiedName */: + case 189 /* PropertyAccessExpression */: + case 100 /* ThisKeyword */: { + var parent = node.parent; + if (parent.kind === 167 /* TypeQuery */) { + return false; + } + if (parent.kind === 183 /* ImportType */) { + return !parent.isTypeOf; + } + // Do not recursively call isPartOfTypeNode on the parent. In the example: + // + // let a: A.B.C; + // + // Calling isPartOfTypeNode would consider the qualified name A.B a type node. + // Only C and A.B.C are type nodes. + if (163 /* FirstTypeNode */ <= parent.kind && parent.kind <= 183 /* LastTypeNode */) { + return true; + } + switch (parent.kind) { + case 211 /* ExpressionWithTypeArguments */: + return !isExpressionWithTypeArgumentsInClassExtendsClause(parent); + case 150 /* TypeParameter */: + return node === parent.constraint; + case 303 /* JSDocTemplateTag */: + return node === parent.constraint; + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 151 /* Parameter */: + case 237 /* VariableDeclaration */: + return node === parent.type; + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 157 /* Constructor */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + return node === parent.type; + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 162 /* IndexSignature */: + return node === parent.type; + case 194 /* TypeAssertionExpression */: + return node === parent.type; + case 191 /* CallExpression */: + case 192 /* NewExpression */: + return ts.contains(parent.typeArguments, node); + case 193 /* TaggedTemplateExpression */: + // TODO (drosen): TaggedTemplateExpressions may eventually support type arguments. + return false; + } + } + } + return false; + } + ts.isPartOfTypeNode = isPartOfTypeNode; + function isChildOfNodeWithKind(node, kind) { + while (node) { + if (node.kind === kind) { + return true; + } + node = node.parent; + } + return false; + } + ts.isChildOfNodeWithKind = isChildOfNodeWithKind; + // Warning: This has the same semantics as the forEach family of functions, + // in that traversal terminates in the event that 'visitor' supplies a truthy value. + function forEachReturnStatement(body, visitor) { + return traverse(body); + function traverse(node) { + switch (node.kind) { + case 230 /* ReturnStatement */: + return visitor(node); + case 246 /* CaseBlock */: + case 218 /* Block */: + case 222 /* IfStatement */: + case 223 /* DoStatement */: + case 224 /* WhileStatement */: + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + case 231 /* WithStatement */: + case 232 /* SwitchStatement */: + case 271 /* CaseClause */: + case 272 /* DefaultClause */: + case 233 /* LabeledStatement */: + case 235 /* TryStatement */: + case 274 /* CatchClause */: + return ts.forEachChild(node, traverse); + } + } + } + ts.forEachReturnStatement = forEachReturnStatement; + function forEachYieldExpression(body, visitor) { + return traverse(body); + function traverse(node) { + switch (node.kind) { + case 207 /* YieldExpression */: + visitor(node); + var operand = node.expression; + if (operand) { + traverse(operand); + } + return; + case 243 /* EnumDeclaration */: + case 241 /* InterfaceDeclaration */: + case 244 /* ModuleDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + // These are not allowed inside a generator now, but eventually they may be allowed + // as local types. Regardless, any yield statements contained within them should be + // skipped in this traversal. + return; + default: + if (ts.isFunctionLike(node)) { + if (node.name && node.name.kind === 149 /* ComputedPropertyName */) { + // Note that we will not include methods/accessors of a class because they would require + // first descending into the class. This is by design. + traverse(node.name.expression); + return; + } + } + else if (!isPartOfTypeNode(node)) { + // This is the general case, which should include mostly expressions and statements. + // Also includes NodeArrays. + ts.forEachChild(node, traverse); + } + } + } + } + ts.forEachYieldExpression = forEachYieldExpression; + /** + * Gets the most likely element type for a TypeNode. This is not an exhaustive test + * as it assumes a rest argument can only be an array type (either T[], or Array). + * + * @param node The type node. + */ + function getRestParameterElementType(node) { + if (node && node.kind === 169 /* ArrayType */) { + return node.elementType; + } + else if (node && node.kind === 164 /* TypeReference */) { + return ts.singleOrUndefined(node.typeArguments); + } + else { + return undefined; + } + } + ts.getRestParameterElementType = getRestParameterElementType; + function getMembersOfDeclaration(node) { + switch (node.kind) { + case 241 /* InterfaceDeclaration */: + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 168 /* TypeLiteral */: + return node.members; + case 188 /* ObjectLiteralExpression */: + return node.properties; + } + } + ts.getMembersOfDeclaration = getMembersOfDeclaration; + function isVariableLike(node) { + if (node) { + switch (node.kind) { + case 186 /* BindingElement */: + case 278 /* EnumMember */: + case 151 /* Parameter */: + case 275 /* PropertyAssignment */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 276 /* ShorthandPropertyAssignment */: + case 237 /* VariableDeclaration */: + return true; + } + } + return false; + } + ts.isVariableLike = isVariableLike; + function isVariableLikeOrAccessor(node) { + return isVariableLike(node) || ts.isAccessor(node); + } + ts.isVariableLikeOrAccessor = isVariableLikeOrAccessor; + function isVariableDeclarationInVariableStatement(node) { + return node.parent.kind === 238 /* VariableDeclarationList */ + && node.parent.parent.kind === 219 /* VariableStatement */; + } + ts.isVariableDeclarationInVariableStatement = isVariableDeclarationInVariableStatement; + function isValidESSymbolDeclaration(node) { + return ts.isVariableDeclaration(node) ? isVarConst(node) && ts.isIdentifier(node.name) && isVariableDeclarationInVariableStatement(node) : + ts.isPropertyDeclaration(node) ? hasReadonlyModifier(node) && hasStaticModifier(node) : + ts.isPropertySignature(node) && hasReadonlyModifier(node); + } + ts.isValidESSymbolDeclaration = isValidESSymbolDeclaration; + function introducesArgumentsExoticObject(node) { + switch (node.kind) { + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + return true; + } + return false; + } + ts.introducesArgumentsExoticObject = introducesArgumentsExoticObject; + function unwrapInnermostStatementOfLabel(node, beforeUnwrapLabelCallback) { + while (true) { + if (beforeUnwrapLabelCallback) { + beforeUnwrapLabelCallback(node); + } + if (node.statement.kind !== 233 /* LabeledStatement */) { + return node.statement; + } + node = node.statement; + } + } + ts.unwrapInnermostStatementOfLabel = unwrapInnermostStatementOfLabel; + function isFunctionBlock(node) { + return node && node.kind === 218 /* Block */ && ts.isFunctionLike(node.parent); + } + ts.isFunctionBlock = isFunctionBlock; + function isObjectLiteralMethod(node) { + return node && node.kind === 156 /* MethodDeclaration */ && node.parent.kind === 188 /* ObjectLiteralExpression */; + } + ts.isObjectLiteralMethod = isObjectLiteralMethod; + function isObjectLiteralOrClassExpressionMethod(node) { + return node.kind === 156 /* MethodDeclaration */ && + (node.parent.kind === 188 /* ObjectLiteralExpression */ || + node.parent.kind === 209 /* ClassExpression */); + } + ts.isObjectLiteralOrClassExpressionMethod = isObjectLiteralOrClassExpressionMethod; + function isIdentifierTypePredicate(predicate) { + return predicate && predicate.kind === 1 /* Identifier */; + } + ts.isIdentifierTypePredicate = isIdentifierTypePredicate; + function isThisTypePredicate(predicate) { + return predicate && predicate.kind === 0 /* This */; + } + ts.isThisTypePredicate = isThisTypePredicate; + function getPropertyAssignment(objectLiteral, key, key2) { + return objectLiteral.properties.filter(function (property) { + if (property.kind === 275 /* PropertyAssignment */) { + var propName = getTextOfPropertyName(property.name); + return key === propName || (!!key2 && key2 === propName); + } + return false; + }); + } + ts.getPropertyAssignment = getPropertyAssignment; + function getTsConfigObjectLiteralExpression(tsConfigSourceFile) { + if (tsConfigSourceFile && tsConfigSourceFile.statements.length) { + var expression = tsConfigSourceFile.statements[0].expression; + return ts.tryCast(expression, ts.isObjectLiteralExpression); + } + } + ts.getTsConfigObjectLiteralExpression = getTsConfigObjectLiteralExpression; + function getTsConfigPropArrayElementValue(tsConfigSourceFile, propKey, elementValue) { + return ts.firstDefined(getTsConfigPropArray(tsConfigSourceFile, propKey), function (property) { + return ts.isArrayLiteralExpression(property.initializer) ? + ts.find(property.initializer.elements, function (element) { return ts.isStringLiteral(element) && element.text === elementValue; }) : + undefined; + }); + } + ts.getTsConfigPropArrayElementValue = getTsConfigPropArrayElementValue; + function getTsConfigPropArray(tsConfigSourceFile, propKey) { + var jsonObjectLiteral = getTsConfigObjectLiteralExpression(tsConfigSourceFile); + return jsonObjectLiteral ? getPropertyAssignment(jsonObjectLiteral, propKey) : ts.emptyArray; + } + ts.getTsConfigPropArray = getTsConfigPropArray; + function getContainingFunction(node) { + return findAncestor(node.parent, ts.isFunctionLike); + } + ts.getContainingFunction = getContainingFunction; + function getContainingClass(node) { + return findAncestor(node.parent, ts.isClassLike); + } + ts.getContainingClass = getContainingClass; + function getThisContainer(node, includeArrowFunctions) { + ts.Debug.assert(node.kind !== 279 /* SourceFile */); + while (true) { + node = node.parent; + if (!node) { + return ts.Debug.fail(); // If we never pass in a SourceFile, this should be unreachable, since we'll stop when we reach that. + } + switch (node.kind) { + case 149 /* ComputedPropertyName */: + // If the grandparent node is an object literal (as opposed to a class), + // then the computed property is not a 'this' container. + // A computed property name in a class needs to be a this container + // so that we can error on it. + if (ts.isClassLike(node.parent.parent)) { + return node; + } + // If this is a computed property, then the parent should not + // make it a this container. The parent might be a property + // in an object literal, like a method or accessor. But in order for + // such a parent to be a this container, the reference must be in + // the *body* of the container. + node = node.parent; + break; + case 152 /* Decorator */: + // Decorators are always applied outside of the body of a class or method. + if (node.parent.kind === 151 /* Parameter */ && ts.isClassElement(node.parent.parent)) { + // If the decorator's parent is a Parameter, we resolve the this container from + // the grandparent class declaration. + node = node.parent.parent; + } + else if (ts.isClassElement(node.parent)) { + // If the decorator's parent is a class element, we resolve the 'this' container + // from the parent class declaration. + node = node.parent; + } + break; + case 197 /* ArrowFunction */: + if (!includeArrowFunctions) { + continue; + } + // falls through + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 244 /* ModuleDeclaration */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 162 /* IndexSignature */: + case 243 /* EnumDeclaration */: + case 279 /* SourceFile */: + return node; + } + } + } + ts.getThisContainer = getThisContainer; + function getNewTargetContainer(node) { + var container = getThisContainer(node, /*includeArrowFunctions*/ false); + if (container) { + switch (container.kind) { + case 157 /* Constructor */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + return container; + } + } + return undefined; + } + ts.getNewTargetContainer = getNewTargetContainer; + /** + * Given an super call/property node, returns the closest node where + * - a super call/property access is legal in the node and not legal in the parent node the node. + * i.e. super call is legal in constructor but not legal in the class body. + * - the container is an arrow function (so caller might need to call getSuperContainer again in case it needs to climb higher) + * - a super call/property is definitely illegal in the container (but might be legal in some subnode) + * i.e. super property access is illegal in function declaration but can be legal in the statement list + */ + function getSuperContainer(node, stopOnFunctions) { + while (true) { + node = node.parent; + if (!node) { + return node; + } + switch (node.kind) { + case 149 /* ComputedPropertyName */: + node = node.parent; + break; + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + if (!stopOnFunctions) { + continue; + } + // falls through + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + return node; + case 152 /* Decorator */: + // Decorators are always applied outside of the body of a class or method. + if (node.parent.kind === 151 /* Parameter */ && ts.isClassElement(node.parent.parent)) { + // If the decorator's parent is a Parameter, we resolve the this container from + // the grandparent class declaration. + node = node.parent.parent; + } + else if (ts.isClassElement(node.parent)) { + // If the decorator's parent is a class element, we resolve the 'this' container + // from the parent class declaration. + node = node.parent; + } + break; + } + } + } + ts.getSuperContainer = getSuperContainer; + function getImmediatelyInvokedFunctionExpression(func) { + if (func.kind === 196 /* FunctionExpression */ || func.kind === 197 /* ArrowFunction */) { + var prev = func; + var parent = func.parent; + while (parent.kind === 195 /* ParenthesizedExpression */) { + prev = parent; + parent = parent.parent; + } + if (parent.kind === 191 /* CallExpression */ && parent.expression === prev) { + return parent; + } + } + } + ts.getImmediatelyInvokedFunctionExpression = getImmediatelyInvokedFunctionExpression; + /** + * Determines whether a node is a property or element access expression for `super`. + */ + function isSuperProperty(node) { + var kind = node.kind; + return (kind === 189 /* PropertyAccessExpression */ || kind === 190 /* ElementAccessExpression */) + && node.expression.kind === 98 /* SuperKeyword */; + } + ts.isSuperProperty = isSuperProperty; + /** + * Determines whether a node is a property or element access expression for `this`. + */ + function isThisProperty(node) { + var kind = node.kind; + return (kind === 189 /* PropertyAccessExpression */ || kind === 190 /* ElementAccessExpression */) + && node.expression.kind === 100 /* ThisKeyword */; + } + ts.isThisProperty = isThisProperty; + function getEntityNameFromTypeNode(node) { + switch (node.kind) { + case 164 /* TypeReference */: + return node.typeName; + case 211 /* ExpressionWithTypeArguments */: + return isEntityNameExpression(node.expression) + ? node.expression + : undefined; + case 72 /* Identifier */: + case 148 /* QualifiedName */: + return node; + } + return undefined; + } + ts.getEntityNameFromTypeNode = getEntityNameFromTypeNode; + function getInvokedExpression(node) { + switch (node.kind) { + case 193 /* TaggedTemplateExpression */: + return node.tag; + case 262 /* JsxOpeningElement */: + case 261 /* JsxSelfClosingElement */: + return node.tagName; + default: + return node.expression; + } + } + ts.getInvokedExpression = getInvokedExpression; + function nodeCanBeDecorated(node, parent, grandparent) { + switch (node.kind) { + case 240 /* ClassDeclaration */: + // classes are valid targets + return true; + case 154 /* PropertyDeclaration */: + // property declarations are valid if their parent is a class declaration. + return parent.kind === 240 /* ClassDeclaration */; + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 156 /* MethodDeclaration */: + // if this method has a body and its parent is a class declaration, this is a valid target. + return node.body !== undefined + && parent.kind === 240 /* ClassDeclaration */; + case 151 /* Parameter */: + // if the parameter's parent has a body and its grandparent is a class declaration, this is a valid target; + return parent.body !== undefined + && (parent.kind === 157 /* Constructor */ + || parent.kind === 156 /* MethodDeclaration */ + || parent.kind === 159 /* SetAccessor */) + && grandparent.kind === 240 /* ClassDeclaration */; + } + return false; + } + ts.nodeCanBeDecorated = nodeCanBeDecorated; + function nodeIsDecorated(node, parent, grandparent) { + return node.decorators !== undefined + && nodeCanBeDecorated(node, parent, grandparent); // TODO: GH#18217 + } + ts.nodeIsDecorated = nodeIsDecorated; + function nodeOrChildIsDecorated(node, parent, grandparent) { + return nodeIsDecorated(node, parent, grandparent) || childIsDecorated(node, parent); // TODO: GH#18217 + } + ts.nodeOrChildIsDecorated = nodeOrChildIsDecorated; + function childIsDecorated(node, parent) { + switch (node.kind) { + case 240 /* ClassDeclaration */: + return ts.some(node.members, function (m) { return nodeOrChildIsDecorated(m, node, parent); }); // TODO: GH#18217 + case 156 /* MethodDeclaration */: + case 159 /* SetAccessor */: + return ts.some(node.parameters, function (p) { return nodeIsDecorated(p, node, parent); }); // TODO: GH#18217 + default: + return false; + } + } + ts.childIsDecorated = childIsDecorated; + function isJSXTagName(node) { + var parent = node.parent; + if (parent.kind === 262 /* JsxOpeningElement */ || + parent.kind === 261 /* JsxSelfClosingElement */ || + parent.kind === 263 /* JsxClosingElement */) { + return parent.tagName === node; + } + return false; + } + ts.isJSXTagName = isJSXTagName; + function isExpressionNode(node) { + switch (node.kind) { + case 98 /* SuperKeyword */: + case 96 /* NullKeyword */: + case 102 /* TrueKeyword */: + case 87 /* FalseKeyword */: + case 13 /* RegularExpressionLiteral */: + case 187 /* ArrayLiteralExpression */: + case 188 /* ObjectLiteralExpression */: + case 189 /* PropertyAccessExpression */: + case 190 /* ElementAccessExpression */: + case 191 /* CallExpression */: + case 192 /* NewExpression */: + case 193 /* TaggedTemplateExpression */: + case 212 /* AsExpression */: + case 194 /* TypeAssertionExpression */: + case 213 /* NonNullExpression */: + case 195 /* ParenthesizedExpression */: + case 196 /* FunctionExpression */: + case 209 /* ClassExpression */: + case 197 /* ArrowFunction */: + case 200 /* VoidExpression */: + case 198 /* DeleteExpression */: + case 199 /* TypeOfExpression */: + case 202 /* PrefixUnaryExpression */: + case 203 /* PostfixUnaryExpression */: + case 204 /* BinaryExpression */: + case 205 /* ConditionalExpression */: + case 208 /* SpreadElement */: + case 206 /* TemplateExpression */: + case 14 /* NoSubstitutionTemplateLiteral */: + case 210 /* OmittedExpression */: + case 260 /* JsxElement */: + case 261 /* JsxSelfClosingElement */: + case 264 /* JsxFragment */: + case 207 /* YieldExpression */: + case 201 /* AwaitExpression */: + case 214 /* MetaProperty */: + return true; + case 148 /* QualifiedName */: + while (node.parent.kind === 148 /* QualifiedName */) { + node = node.parent; + } + return node.parent.kind === 167 /* TypeQuery */ || isJSXTagName(node); + case 72 /* Identifier */: + if (node.parent.kind === 167 /* TypeQuery */ || isJSXTagName(node)) { + return true; + } + // falls through + case 8 /* NumericLiteral */: + case 9 /* BigIntLiteral */: + case 10 /* StringLiteral */: + case 100 /* ThisKeyword */: + return isInExpressionContext(node); + default: + return false; + } + } + ts.isExpressionNode = isExpressionNode; + function isInExpressionContext(node) { + var parent = node.parent; + switch (parent.kind) { + case 237 /* VariableDeclaration */: + case 151 /* Parameter */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 278 /* EnumMember */: + case 275 /* PropertyAssignment */: + case 186 /* BindingElement */: + return parent.initializer === node; + case 221 /* ExpressionStatement */: + case 222 /* IfStatement */: + case 223 /* DoStatement */: + case 224 /* WhileStatement */: + case 230 /* ReturnStatement */: + case 231 /* WithStatement */: + case 232 /* SwitchStatement */: + case 271 /* CaseClause */: + case 234 /* ThrowStatement */: + return parent.expression === node; + case 225 /* ForStatement */: + var forStatement = parent; + return (forStatement.initializer === node && forStatement.initializer.kind !== 238 /* VariableDeclarationList */) || + forStatement.condition === node || + forStatement.incrementor === node; + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + var forInStatement = parent; + return (forInStatement.initializer === node && forInStatement.initializer.kind !== 238 /* VariableDeclarationList */) || + forInStatement.expression === node; + case 194 /* TypeAssertionExpression */: + case 212 /* AsExpression */: + return node === parent.expression; + case 216 /* TemplateSpan */: + return node === parent.expression; + case 149 /* ComputedPropertyName */: + return node === parent.expression; + case 152 /* Decorator */: + case 270 /* JsxExpression */: + case 269 /* JsxSpreadAttribute */: + case 277 /* SpreadAssignment */: + return true; + case 211 /* ExpressionWithTypeArguments */: + return parent.expression === node && isExpressionWithTypeArgumentsInClassExtendsClause(parent); + case 276 /* ShorthandPropertyAssignment */: + return parent.objectAssignmentInitializer === node; + default: + return isExpressionNode(parent); + } + } + ts.isInExpressionContext = isInExpressionContext; + function isExternalModuleImportEqualsDeclaration(node) { + return node.kind === 248 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 259 /* ExternalModuleReference */; + } + ts.isExternalModuleImportEqualsDeclaration = isExternalModuleImportEqualsDeclaration; + function getExternalModuleImportEqualsDeclarationExpression(node) { + ts.Debug.assert(isExternalModuleImportEqualsDeclaration(node)); + return node.moduleReference.expression; + } + ts.getExternalModuleImportEqualsDeclarationExpression = getExternalModuleImportEqualsDeclarationExpression; + function isInternalModuleImportEqualsDeclaration(node) { + return node.kind === 248 /* ImportEqualsDeclaration */ && node.moduleReference.kind !== 259 /* ExternalModuleReference */; + } + ts.isInternalModuleImportEqualsDeclaration = isInternalModuleImportEqualsDeclaration; + function isSourceFileJS(file) { + return isInJSFile(file); + } + ts.isSourceFileJS = isSourceFileJS; + function isSourceFileNotJS(file) { + return !isInJSFile(file); + } + ts.isSourceFileNotJS = isSourceFileNotJS; + function isInJSFile(node) { + return !!node && !!(node.flags & 65536 /* JavaScriptFile */); + } + ts.isInJSFile = isInJSFile; + function isInJsonFile(node) { + return !!node && !!(node.flags & 16777216 /* JsonFile */); + } + ts.isInJsonFile = isInJsonFile; + function isInJSDoc(node) { + return !!node && !!(node.flags & 2097152 /* JSDoc */); + } + ts.isInJSDoc = isInJSDoc; + function isJSDocIndexSignature(node) { + return ts.isTypeReferenceNode(node) && + ts.isIdentifier(node.typeName) && + node.typeName.escapedText === "Object" && + node.typeArguments && node.typeArguments.length === 2 && + (node.typeArguments[0].kind === 138 /* StringKeyword */ || node.typeArguments[0].kind === 135 /* NumberKeyword */); + } + ts.isJSDocIndexSignature = isJSDocIndexSignature; + function isRequireCall(callExpression, checkArgumentIsStringLiteralLike) { + if (callExpression.kind !== 191 /* CallExpression */) { + return false; + } + var _a = callExpression, expression = _a.expression, args = _a.arguments; + if (expression.kind !== 72 /* Identifier */ || expression.escapedText !== "require") { + return false; + } + if (args.length !== 1) { + return false; + } + var arg = args[0]; + return !checkArgumentIsStringLiteralLike || ts.isStringLiteralLike(arg); + } + ts.isRequireCall = isRequireCall; + function isSingleOrDoubleQuote(charCode) { + return charCode === 39 /* singleQuote */ || charCode === 34 /* doubleQuote */; + } + ts.isSingleOrDoubleQuote = isSingleOrDoubleQuote; + function isStringDoubleQuoted(str, sourceFile) { + return getSourceTextOfNodeFromSourceFile(sourceFile, str).charCodeAt(0) === 34 /* doubleQuote */; + } + ts.isStringDoubleQuoted = isStringDoubleQuoted; + function getDeclarationOfExpando(node) { + if (!node.parent) { + return undefined; + } + var name; + var decl; + if (ts.isVariableDeclaration(node.parent) && node.parent.initializer === node) { + if (!isInJSFile(node) && !isVarConst(node.parent)) { + return undefined; + } + name = node.parent.name; + decl = node.parent; + } + else if (ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 59 /* EqualsToken */ && node.parent.right === node) { + name = node.parent.left; + decl = name; + } + else if (ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 55 /* BarBarToken */) { + if (ts.isVariableDeclaration(node.parent.parent) && node.parent.parent.initializer === node.parent) { + name = node.parent.parent.name; + decl = node.parent.parent; + } + else if (ts.isBinaryExpression(node.parent.parent) && node.parent.parent.operatorToken.kind === 59 /* EqualsToken */ && node.parent.parent.right === node.parent) { + name = node.parent.parent.left; + decl = name; + } + if (!name || !isEntityNameExpression(name) || !isSameEntityName(name, node.parent.left)) { + return undefined; + } + } + if (!name || !getExpandoInitializer(node, isPrototypeAccess(name))) { + return undefined; + } + return decl; + } + ts.getDeclarationOfExpando = getDeclarationOfExpando; + function isAssignmentDeclaration(decl) { + return ts.isBinaryExpression(decl) || ts.isPropertyAccessExpression(decl) || ts.isIdentifier(decl) || ts.isCallExpression(decl); + } + ts.isAssignmentDeclaration = isAssignmentDeclaration; + /** Get the initializer, taking into account defaulted Javascript initializers */ + function getEffectiveInitializer(node) { + if (isInJSFile(node) && node.initializer && + ts.isBinaryExpression(node.initializer) && node.initializer.operatorToken.kind === 55 /* BarBarToken */ && + node.name && isEntityNameExpression(node.name) && isSameEntityName(node.name, node.initializer.left)) { + return node.initializer.right; + } + return node.initializer; + } + ts.getEffectiveInitializer = getEffectiveInitializer; + /** Get the declaration initializer when it is container-like (See getExpandoInitializer). */ + function getDeclaredExpandoInitializer(node) { + var init = getEffectiveInitializer(node); + return init && getExpandoInitializer(init, isPrototypeAccess(node.name)); + } + ts.getDeclaredExpandoInitializer = getDeclaredExpandoInitializer; + function hasExpandoValueProperty(node, isPrototypeAssignment) { + return ts.forEach(node.properties, function (p) { return ts.isPropertyAssignment(p) && ts.isIdentifier(p.name) && p.name.escapedText === "value" && p.initializer && getExpandoInitializer(p.initializer, isPrototypeAssignment); }); + } + /** + * Get the assignment 'initializer' -- the righthand side-- when the initializer is container-like (See getExpandoInitializer). + * We treat the right hand side of assignments with container-like initalizers as declarations. + */ + function getAssignedExpandoInitializer(node) { + if (node && node.parent && ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 59 /* EqualsToken */) { + var isPrototypeAssignment = isPrototypeAccess(node.parent.left); + return getExpandoInitializer(node.parent.right, isPrototypeAssignment) || + getDefaultedExpandoInitializer(node.parent.left, node.parent.right, isPrototypeAssignment); + } + if (node && ts.isCallExpression(node) && isBindableObjectDefinePropertyCall(node)) { + var result = hasExpandoValueProperty(node.arguments[2], node.arguments[1].text === "prototype"); + if (result) { + return result; + } + } + } + ts.getAssignedExpandoInitializer = getAssignedExpandoInitializer; + /** + * Recognized expando initializers are: + * 1. (function() {})() -- IIFEs + * 2. function() { } -- Function expressions + * 3. class { } -- Class expressions + * 4. {} -- Empty object literals + * 5. { ... } -- Non-empty object literals, when used to initialize a prototype, like `C.prototype = { m() { } }` + * + * This function returns the provided initializer, or undefined if it is not valid. + */ + function getExpandoInitializer(initializer, isPrototypeAssignment) { + if (ts.isCallExpression(initializer)) { + var e = skipParentheses(initializer.expression); + return e.kind === 196 /* FunctionExpression */ || e.kind === 197 /* ArrowFunction */ ? initializer : undefined; + } + if (initializer.kind === 196 /* FunctionExpression */ || + initializer.kind === 209 /* ClassExpression */ || + initializer.kind === 197 /* ArrowFunction */) { + return initializer; + } + if (ts.isObjectLiteralExpression(initializer) && (initializer.properties.length === 0 || isPrototypeAssignment)) { + return initializer; + } + } + ts.getExpandoInitializer = getExpandoInitializer; + /** + * A defaulted expando initializer matches the pattern + * `Lhs = Lhs || ExpandoInitializer` + * or `var Lhs = Lhs || ExpandoInitializer` + * + * The second Lhs is required to be the same as the first except that it may be prefixed with + * 'window.', 'global.' or 'self.' The second Lhs is otherwise ignored by the binder and checker. + */ + function getDefaultedExpandoInitializer(name, initializer, isPrototypeAssignment) { + var e = ts.isBinaryExpression(initializer) && initializer.operatorToken.kind === 55 /* BarBarToken */ && getExpandoInitializer(initializer.right, isPrototypeAssignment); + if (e && isSameEntityName(name, initializer.left)) { + return e; + } + } + function isDefaultedExpandoInitializer(node) { + var name = ts.isVariableDeclaration(node.parent) ? node.parent.name : + ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 59 /* EqualsToken */ ? node.parent.left : + undefined; + return name && getExpandoInitializer(node.right, isPrototypeAccess(name)) && isEntityNameExpression(name) && isSameEntityName(name, node.left); + } + ts.isDefaultedExpandoInitializer = isDefaultedExpandoInitializer; + /** Given an expando initializer, return its declaration name, or the left-hand side of the assignment if it's part of an assignment declaration. */ + function getNameOfExpando(node) { + if (ts.isBinaryExpression(node.parent)) { + var parent = (node.parent.operatorToken.kind === 55 /* BarBarToken */ && ts.isBinaryExpression(node.parent.parent)) ? node.parent.parent : node.parent; + if (parent.operatorToken.kind === 59 /* EqualsToken */ && ts.isIdentifier(parent.left)) { + return parent.left; + } + } + else if (ts.isVariableDeclaration(node.parent)) { + return node.parent.name; + } + } + ts.getNameOfExpando = getNameOfExpando; + /** + * Is the 'declared' name the same as the one in the initializer? + * @return true for identical entity names, as well as ones where the initializer is prefixed with + * 'window', 'self' or 'global'. For example: + * + * var my = my || {} + * var min = window.min || {} + * my.app = self.my.app || class { } + */ + function isSameEntityName(name, initializer) { + if (ts.isIdentifier(name) && ts.isIdentifier(initializer)) { + return name.escapedText === initializer.escapedText; + } + if (ts.isIdentifier(name) && ts.isPropertyAccessExpression(initializer)) { + return (initializer.expression.kind === 100 /* ThisKeyword */ || + ts.isIdentifier(initializer.expression) && + (initializer.expression.escapedText === "window" || + initializer.expression.escapedText === "self" || + initializer.expression.escapedText === "global")) && + isSameEntityName(name, initializer.name); + } + if (ts.isPropertyAccessExpression(name) && ts.isPropertyAccessExpression(initializer)) { + return name.name.escapedText === initializer.name.escapedText && isSameEntityName(name.expression, initializer.expression); + } + return false; + } + function getRightMostAssignedExpression(node) { + while (isAssignmentExpression(node, /*excludeCompoundAssignments*/ true)) { + node = node.right; + } + return node; + } + ts.getRightMostAssignedExpression = getRightMostAssignedExpression; + function isExportsIdentifier(node) { + return ts.isIdentifier(node) && node.escapedText === "exports"; + } + ts.isExportsIdentifier = isExportsIdentifier; + function isModuleExportsPropertyAccessExpression(node) { + return ts.isPropertyAccessExpression(node) && ts.isIdentifier(node.expression) && node.expression.escapedText === "module" && node.name.escapedText === "exports"; + } + ts.isModuleExportsPropertyAccessExpression = isModuleExportsPropertyAccessExpression; + /// Given a BinaryExpression, returns SpecialPropertyAssignmentKind for the various kinds of property + /// assignments we treat as special in the binder + function getAssignmentDeclarationKind(expr) { + var special = getAssignmentDeclarationKindWorker(expr); + return special === 5 /* Property */ || isInJSFile(expr) ? special : 0 /* None */; + } + ts.getAssignmentDeclarationKind = getAssignmentDeclarationKind; + function isBindableObjectDefinePropertyCall(expr) { + return ts.length(expr.arguments) === 3 && + ts.isPropertyAccessExpression(expr.expression) && + ts.isIdentifier(expr.expression.expression) && + ts.idText(expr.expression.expression) === "Object" && + ts.idText(expr.expression.name) === "defineProperty" && + isStringOrNumericLiteralLike(expr.arguments[1]) && + isEntityNameExpression(expr.arguments[0]); + } + ts.isBindableObjectDefinePropertyCall = isBindableObjectDefinePropertyCall; + function getAssignmentDeclarationKindWorker(expr) { + if (ts.isCallExpression(expr)) { + if (!isBindableObjectDefinePropertyCall(expr)) { + return 0 /* None */; + } + var entityName = expr.arguments[0]; + if (isExportsIdentifier(entityName) || isModuleExportsPropertyAccessExpression(entityName)) { + return 8 /* ObjectDefinePropertyExports */; + } + if (ts.isPropertyAccessExpression(entityName) && entityName.name.escapedText === "prototype" && isEntityNameExpression(entityName.expression)) { + return 9 /* ObjectDefinePrototypeProperty */; + } + return 7 /* ObjectDefinePropertyValue */; + } + if (expr.operatorToken.kind !== 59 /* EqualsToken */ || + !ts.isPropertyAccessExpression(expr.left)) { + return 0 /* None */; + } + var lhs = expr.left; + if (isEntityNameExpression(lhs.expression) && lhs.name.escapedText === "prototype" && ts.isObjectLiteralExpression(getInitializerOfBinaryExpression(expr))) { + // F.prototype = { ... } + return 6 /* Prototype */; + } + return getAssignmentDeclarationPropertyAccessKind(lhs); + } + function getAssignmentDeclarationPropertyAccessKind(lhs) { + if (lhs.expression.kind === 100 /* ThisKeyword */) { + return 4 /* ThisProperty */; + } + else if (isModuleExportsPropertyAccessExpression(lhs)) { + // module.exports = expr + return 2 /* ModuleExports */; + } + else if (isEntityNameExpression(lhs.expression)) { + if (isPrototypeAccess(lhs.expression)) { + // F.G....prototype.x = expr + return 3 /* PrototypeProperty */; + } + var nextToLast = lhs; + while (ts.isPropertyAccessExpression(nextToLast.expression)) { + nextToLast = nextToLast.expression; + } + ts.Debug.assert(ts.isIdentifier(nextToLast.expression)); + var id = nextToLast.expression; + if (id.escapedText === "exports" || + id.escapedText === "module" && nextToLast.name.escapedText === "exports") { + // exports.name = expr OR module.exports.name = expr + return 1 /* ExportsProperty */; + } + // F.G...x = expr + return 5 /* Property */; + } + return 0 /* None */; + } + ts.getAssignmentDeclarationPropertyAccessKind = getAssignmentDeclarationPropertyAccessKind; + function getInitializerOfBinaryExpression(expr) { + while (ts.isBinaryExpression(expr.right)) { + expr = expr.right; + } + return expr.right; + } + ts.getInitializerOfBinaryExpression = getInitializerOfBinaryExpression; + function isPrototypePropertyAssignment(node) { + return ts.isBinaryExpression(node) && getAssignmentDeclarationKind(node) === 3 /* PrototypeProperty */; + } + ts.isPrototypePropertyAssignment = isPrototypePropertyAssignment; + function isSpecialPropertyDeclaration(expr) { + return isInJSFile(expr) && + expr.parent && expr.parent.kind === 221 /* ExpressionStatement */ && + !!ts.getJSDocTypeTag(expr.parent); + } + ts.isSpecialPropertyDeclaration = isSpecialPropertyDeclaration; + function isFunctionSymbol(symbol) { + if (!symbol || !symbol.valueDeclaration) { + return false; + } + var decl = symbol.valueDeclaration; + return decl.kind === 239 /* FunctionDeclaration */ || ts.isVariableDeclaration(decl) && decl.initializer && ts.isFunctionLike(decl.initializer); + } + ts.isFunctionSymbol = isFunctionSymbol; + function importFromModuleSpecifier(node) { + return tryGetImportFromModuleSpecifier(node) || ts.Debug.fail(ts.Debug.showSyntaxKind(node.parent)); + } + ts.importFromModuleSpecifier = importFromModuleSpecifier; + function tryGetImportFromModuleSpecifier(node) { + switch (node.parent.kind) { + case 249 /* ImportDeclaration */: + case 255 /* ExportDeclaration */: + return node.parent; + case 259 /* ExternalModuleReference */: + return node.parent.parent; + case 191 /* CallExpression */: + return isImportCall(node.parent) || isRequireCall(node.parent, /*checkArg*/ false) ? node.parent : undefined; + case 182 /* LiteralType */: + ts.Debug.assert(ts.isStringLiteral(node)); + return ts.tryCast(node.parent.parent, ts.isImportTypeNode); + default: + return undefined; + } + } + ts.tryGetImportFromModuleSpecifier = tryGetImportFromModuleSpecifier; + function getExternalModuleName(node) { + switch (node.kind) { + case 249 /* ImportDeclaration */: + case 255 /* ExportDeclaration */: + return node.moduleSpecifier; + case 248 /* ImportEqualsDeclaration */: + return node.moduleReference.kind === 259 /* ExternalModuleReference */ ? node.moduleReference.expression : undefined; + case 183 /* ImportType */: + return isLiteralImportTypeNode(node) ? node.argument.literal : undefined; + default: + return ts.Debug.assertNever(node); + } + } + ts.getExternalModuleName = getExternalModuleName; + function getNamespaceDeclarationNode(node) { + switch (node.kind) { + case 249 /* ImportDeclaration */: + return node.importClause && ts.tryCast(node.importClause.namedBindings, ts.isNamespaceImport); + case 248 /* ImportEqualsDeclaration */: + return node; + case 255 /* ExportDeclaration */: + return undefined; + default: + return ts.Debug.assertNever(node); + } + } + ts.getNamespaceDeclarationNode = getNamespaceDeclarationNode; + function isDefaultImport(node) { + return node.kind === 249 /* ImportDeclaration */ && !!node.importClause && !!node.importClause.name; + } + ts.isDefaultImport = isDefaultImport; + function hasQuestionToken(node) { + if (node) { + switch (node.kind) { + case 151 /* Parameter */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 276 /* ShorthandPropertyAssignment */: + case 275 /* PropertyAssignment */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + return node.questionToken !== undefined; + } + } + return false; + } + ts.hasQuestionToken = hasQuestionToken; + function isJSDocConstructSignature(node) { + var param = ts.isJSDocFunctionType(node) ? ts.firstOrUndefined(node.parameters) : undefined; + var name = ts.tryCast(param && param.name, ts.isIdentifier); + return !!name && name.escapedText === "new"; + } + ts.isJSDocConstructSignature = isJSDocConstructSignature; + function isJSDocTypeAlias(node) { + return node.kind === 304 /* JSDocTypedefTag */ || node.kind === 297 /* JSDocCallbackTag */; + } + ts.isJSDocTypeAlias = isJSDocTypeAlias; + function isTypeAlias(node) { + return isJSDocTypeAlias(node) || ts.isTypeAliasDeclaration(node); + } + ts.isTypeAlias = isTypeAlias; + function getSourceOfAssignment(node) { + return ts.isExpressionStatement(node) && + node.expression && ts.isBinaryExpression(node.expression) && + node.expression.operatorToken.kind === 59 /* EqualsToken */ + ? node.expression.right + : undefined; + } + function getSourceOfDefaultedAssignment(node) { + return ts.isExpressionStatement(node) && + ts.isBinaryExpression(node.expression) && + getAssignmentDeclarationKind(node.expression) !== 0 /* None */ && + ts.isBinaryExpression(node.expression.right) && + node.expression.right.operatorToken.kind === 55 /* BarBarToken */ + ? node.expression.right.right + : undefined; + } + function getSingleInitializerOfVariableStatementOrPropertyDeclaration(node) { + switch (node.kind) { + case 219 /* VariableStatement */: + var v = getSingleVariableOfVariableStatement(node); + return v && v.initializer; + case 154 /* PropertyDeclaration */: + return node.initializer; + case 275 /* PropertyAssignment */: + return node.initializer; + } + } + function getSingleVariableOfVariableStatement(node) { + return ts.isVariableStatement(node) ? ts.firstOrUndefined(node.declarationList.declarations) : undefined; + } + function getNestedModuleDeclaration(node) { + return ts.isModuleDeclaration(node) && + node.body && + node.body.kind === 244 /* ModuleDeclaration */ + ? node.body + : undefined; + } + function getJSDocCommentsAndTags(hostNode) { + var result; + // Pull parameter comments from declaring function as well + if (isVariableLike(hostNode) && ts.hasInitializer(hostNode) && ts.hasJSDocNodes(hostNode.initializer)) { + result = ts.addRange(result, hostNode.initializer.jsDoc); + } + var node = hostNode; + while (node && node.parent) { + if (ts.hasJSDocNodes(node)) { + result = ts.addRange(result, node.jsDoc); + } + if (node.kind === 151 /* Parameter */) { + result = ts.addRange(result, ts.getJSDocParameterTags(node)); + break; + } + if (node.kind === 150 /* TypeParameter */) { + result = ts.addRange(result, ts.getJSDocTypeParameterTags(node)); + break; + } + node = getNextJSDocCommentLocation(node); + } + return result || ts.emptyArray; + } + ts.getJSDocCommentsAndTags = getJSDocCommentsAndTags; + function getNextJSDocCommentLocation(node) { + var parent = node.parent; + if (parent.kind === 275 /* PropertyAssignment */ || + parent.kind === 154 /* PropertyDeclaration */ || + parent.kind === 221 /* ExpressionStatement */ && node.kind === 189 /* PropertyAccessExpression */ || + getNestedModuleDeclaration(parent) || + ts.isBinaryExpression(node) && node.operatorToken.kind === 59 /* EqualsToken */) { + return parent; + } + // Try to recognize this pattern when node is initializer of variable declaration and JSDoc comments are on containing variable statement. + // /** + // * @param {number} name + // * @returns {number} + // */ + // var x = function(name) { return name.length; } + else if (parent.parent && + (getSingleVariableOfVariableStatement(parent.parent) === node || + ts.isBinaryExpression(parent) && parent.operatorToken.kind === 59 /* EqualsToken */)) { + return parent.parent; + } + else if (parent.parent && parent.parent.parent && + (getSingleVariableOfVariableStatement(parent.parent.parent) || + getSingleInitializerOfVariableStatementOrPropertyDeclaration(parent.parent.parent) === node || + getSourceOfDefaultedAssignment(parent.parent.parent))) { + return parent.parent.parent; + } + } + /** Does the opposite of `getJSDocParameterTags`: given a JSDoc parameter, finds the parameter corresponding to it. */ + function getParameterSymbolFromJSDoc(node) { + if (node.symbol) { + return node.symbol; + } + if (!ts.isIdentifier(node.name)) { + return undefined; + } + var name = node.name.escapedText; + var decl = getHostSignatureFromJSDoc(node); + if (!decl) { + return undefined; + } + var parameter = ts.find(decl.parameters, function (p) { return p.name.kind === 72 /* Identifier */ && p.name.escapedText === name; }); + return parameter && parameter.symbol; + } + ts.getParameterSymbolFromJSDoc = getParameterSymbolFromJSDoc; + function getHostSignatureFromJSDoc(node) { + return getHostSignatureFromJSDocHost(getJSDocHost(node)); + } + ts.getHostSignatureFromJSDoc = getHostSignatureFromJSDoc; + function getHostSignatureFromJSDocHost(host) { + var decl = getSourceOfDefaultedAssignment(host) || + getSourceOfAssignment(host) || + getSingleInitializerOfVariableStatementOrPropertyDeclaration(host) || + getSingleVariableOfVariableStatement(host) || + getNestedModuleDeclaration(host) || + host; + return decl && ts.isFunctionLike(decl) ? decl : undefined; + } + ts.getHostSignatureFromJSDocHost = getHostSignatureFromJSDocHost; + function getJSDocHost(node) { + return ts.Debug.assertDefined(findAncestor(node.parent, ts.isJSDoc)).parent; + } + ts.getJSDocHost = getJSDocHost; + function getTypeParameterFromJsDoc(node) { + var name = node.name.escapedText; + var typeParameters = node.parent.parent.parent.typeParameters; + return ts.find(typeParameters, function (p) { return p.name.escapedText === name; }); + } + ts.getTypeParameterFromJsDoc = getTypeParameterFromJsDoc; + function hasRestParameter(s) { + var last = ts.lastOrUndefined(s.parameters); + return !!last && isRestParameter(last); + } + ts.hasRestParameter = hasRestParameter; + function isRestParameter(node) { + var type = ts.isJSDocParameterTag(node) ? (node.typeExpression && node.typeExpression.type) : node.type; + return node.dotDotDotToken !== undefined || !!type && type.kind === 290 /* JSDocVariadicType */; + } + ts.isRestParameter = isRestParameter; + var AssignmentKind; + (function (AssignmentKind) { + AssignmentKind[AssignmentKind["None"] = 0] = "None"; + AssignmentKind[AssignmentKind["Definite"] = 1] = "Definite"; + AssignmentKind[AssignmentKind["Compound"] = 2] = "Compound"; + })(AssignmentKind = ts.AssignmentKind || (ts.AssignmentKind = {})); + function getAssignmentTargetKind(node) { + var parent = node.parent; + while (true) { + switch (parent.kind) { + case 204 /* BinaryExpression */: + var binaryOperator = parent.operatorToken.kind; + return isAssignmentOperator(binaryOperator) && parent.left === node ? + binaryOperator === 59 /* EqualsToken */ ? 1 /* Definite */ : 2 /* Compound */ : + 0 /* None */; + case 202 /* PrefixUnaryExpression */: + case 203 /* PostfixUnaryExpression */: + var unaryOperator = parent.operator; + return unaryOperator === 44 /* PlusPlusToken */ || unaryOperator === 45 /* MinusMinusToken */ ? 2 /* Compound */ : 0 /* None */; + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + return parent.initializer === node ? 1 /* Definite */ : 0 /* None */; + case 195 /* ParenthesizedExpression */: + case 187 /* ArrayLiteralExpression */: + case 208 /* SpreadElement */: + case 213 /* NonNullExpression */: + node = parent; + break; + case 276 /* ShorthandPropertyAssignment */: + if (parent.name !== node) { + return 0 /* None */; + } + node = parent.parent; + break; + case 275 /* PropertyAssignment */: + if (parent.name === node) { + return 0 /* None */; + } + node = parent.parent; + break; + default: + return 0 /* None */; + } + parent = node.parent; + } + } + ts.getAssignmentTargetKind = getAssignmentTargetKind; + // A node is an assignment target if it is on the left hand side of an '=' token, if it is parented by a property + // assignment in an object literal that is an assignment target, or if it is parented by an array literal that is + // an assignment target. Examples include 'a = xxx', '{ p: a } = xxx', '[{ a }] = xxx'. + // (Note that `p` is not a target in the above examples, only `a`.) + function isAssignmentTarget(node) { + return getAssignmentTargetKind(node) !== 0 /* None */; + } + ts.isAssignmentTarget = isAssignmentTarget; + /** + * Indicates whether a node could contain a `var` VariableDeclarationList that contributes to + * the same `var` declaration scope as the node's parent. + */ + function isNodeWithPossibleHoistedDeclaration(node) { + switch (node.kind) { + case 218 /* Block */: + case 219 /* VariableStatement */: + case 231 /* WithStatement */: + case 222 /* IfStatement */: + case 232 /* SwitchStatement */: + case 246 /* CaseBlock */: + case 271 /* CaseClause */: + case 272 /* DefaultClause */: + case 233 /* LabeledStatement */: + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + case 223 /* DoStatement */: + case 224 /* WhileStatement */: + case 235 /* TryStatement */: + case 274 /* CatchClause */: + return true; + } + return false; + } + ts.isNodeWithPossibleHoistedDeclaration = isNodeWithPossibleHoistedDeclaration; + function isValueSignatureDeclaration(node) { + return ts.isFunctionExpression(node) || ts.isArrowFunction(node) || ts.isMethodOrAccessor(node) || ts.isFunctionDeclaration(node) || ts.isConstructorDeclaration(node); + } + ts.isValueSignatureDeclaration = isValueSignatureDeclaration; + function walkUp(node, kind) { + while (node && node.kind === kind) { + node = node.parent; + } + return node; + } + function walkUpParenthesizedTypes(node) { + return walkUp(node, 177 /* ParenthesizedType */); + } + ts.walkUpParenthesizedTypes = walkUpParenthesizedTypes; + function walkUpParenthesizedExpressions(node) { + return walkUp(node, 195 /* ParenthesizedExpression */); + } + ts.walkUpParenthesizedExpressions = walkUpParenthesizedExpressions; + function skipParentheses(node) { + while (node.kind === 195 /* ParenthesizedExpression */) { + node = node.expression; + } + return node; + } + ts.skipParentheses = skipParentheses; + function skipParenthesesUp(node) { + while (node.kind === 195 /* ParenthesizedExpression */) { + node = node.parent; + } + return node; + } + // a node is delete target iff. it is PropertyAccessExpression/ElementAccessExpression with parentheses skipped + function isDeleteTarget(node) { + if (node.kind !== 189 /* PropertyAccessExpression */ && node.kind !== 190 /* ElementAccessExpression */) { + return false; + } + node = walkUpParenthesizedExpressions(node.parent); + return node && node.kind === 198 /* DeleteExpression */; + } + ts.isDeleteTarget = isDeleteTarget; + function isNodeDescendantOf(node, ancestor) { + while (node) { + if (node === ancestor) + return true; + node = node.parent; + } + return false; + } + ts.isNodeDescendantOf = isNodeDescendantOf; + // True if `name` is the name of a declaration node + function isDeclarationName(name) { + return !ts.isSourceFile(name) && !ts.isBindingPattern(name) && ts.isDeclaration(name.parent) && name.parent.name === name; + } + ts.isDeclarationName = isDeclarationName; + // See GH#16030 + function getDeclarationFromName(name) { + var parent = name.parent; + switch (name.kind) { + case 10 /* StringLiteral */: + case 8 /* NumericLiteral */: + if (ts.isComputedPropertyName(parent)) + return parent.parent; + // falls through + case 72 /* Identifier */: + if (ts.isDeclaration(parent)) { + return parent.name === name ? parent : undefined; + } + else if (ts.isQualifiedName(parent)) { + var tag = parent.parent; + return ts.isJSDocParameterTag(tag) && tag.name === parent ? tag : undefined; + } + else { + var binExp = parent.parent; + return ts.isBinaryExpression(binExp) && + getAssignmentDeclarationKind(binExp) !== 0 /* None */ && + (binExp.left.symbol || binExp.symbol) && + ts.getNameOfDeclaration(binExp) === name + ? binExp + : undefined; + } + default: + return undefined; + } + } + ts.getDeclarationFromName = getDeclarationFromName; + function isLiteralComputedPropertyDeclarationName(node) { + return (node.kind === 10 /* StringLiteral */ || node.kind === 8 /* NumericLiteral */) && + node.parent.kind === 149 /* ComputedPropertyName */ && + ts.isDeclaration(node.parent.parent); + } + ts.isLiteralComputedPropertyDeclarationName = isLiteralComputedPropertyDeclarationName; + // Return true if the given identifier is classified as an IdentifierName + function isIdentifierName(node) { + var parent = node.parent; + switch (parent.kind) { + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 278 /* EnumMember */: + case 275 /* PropertyAssignment */: + case 189 /* PropertyAccessExpression */: + // Name in member declaration or property name in property access + return parent.name === node; + case 148 /* QualifiedName */: + // Name on right hand side of dot in a type query or type reference + if (parent.right === node) { + while (parent.kind === 148 /* QualifiedName */) { + parent = parent.parent; + } + return parent.kind === 167 /* TypeQuery */ || parent.kind === 164 /* TypeReference */; + } + return false; + case 186 /* BindingElement */: + case 253 /* ImportSpecifier */: + // Property name in binding element or import specifier + return parent.propertyName === node; + case 257 /* ExportSpecifier */: + case 267 /* JsxAttribute */: + // Any name in an export specifier or JSX Attribute + return true; + } + return false; + } + ts.isIdentifierName = isIdentifierName; + // An alias symbol is created by one of the following declarations: + // import = ... + // import from ... + // import * as from ... + // import { x as } from ... + // export { x as } from ... + // export = + // export default + // module.exports = + function isAliasSymbolDeclaration(node) { + return node.kind === 248 /* ImportEqualsDeclaration */ || + node.kind === 247 /* NamespaceExportDeclaration */ || + node.kind === 250 /* ImportClause */ && !!node.name || + node.kind === 251 /* NamespaceImport */ || + node.kind === 253 /* ImportSpecifier */ || + node.kind === 257 /* ExportSpecifier */ || + node.kind === 254 /* ExportAssignment */ && exportAssignmentIsAlias(node) || + ts.isBinaryExpression(node) && getAssignmentDeclarationKind(node) === 2 /* ModuleExports */ && exportAssignmentIsAlias(node); + } + ts.isAliasSymbolDeclaration = isAliasSymbolDeclaration; + function exportAssignmentIsAlias(node) { + var e = ts.isExportAssignment(node) ? node.expression : node.right; + return isEntityNameExpression(e) || ts.isClassExpression(e); + } + ts.exportAssignmentIsAlias = exportAssignmentIsAlias; + function getEffectiveBaseTypeNode(node) { + if (isInJSFile(node)) { + // Prefer an @augments tag because it may have type parameters. + var tag = ts.getJSDocAugmentsTag(node); + if (tag) { + return tag.class; + } + } + return getClassExtendsHeritageElement(node); + } + ts.getEffectiveBaseTypeNode = getEffectiveBaseTypeNode; + function getClassExtendsHeritageElement(node) { + var heritageClause = getHeritageClause(node.heritageClauses, 86 /* ExtendsKeyword */); + return heritageClause && heritageClause.types.length > 0 ? heritageClause.types[0] : undefined; + } + ts.getClassExtendsHeritageElement = getClassExtendsHeritageElement; + function getClassImplementsHeritageClauseElements(node) { + var heritageClause = getHeritageClause(node.heritageClauses, 109 /* ImplementsKeyword */); + return heritageClause ? heritageClause.types : undefined; + } + ts.getClassImplementsHeritageClauseElements = getClassImplementsHeritageClauseElements; + /** Returns the node in an `extends` or `implements` clause of a class or interface. */ + function getAllSuperTypeNodes(node) { + return ts.isInterfaceDeclaration(node) ? getInterfaceBaseTypeNodes(node) || ts.emptyArray + : ts.isClassLike(node) ? ts.concatenate(ts.singleElementArray(getEffectiveBaseTypeNode(node)), getClassImplementsHeritageClauseElements(node)) || ts.emptyArray + : ts.emptyArray; + } + ts.getAllSuperTypeNodes = getAllSuperTypeNodes; + function getInterfaceBaseTypeNodes(node) { + var heritageClause = getHeritageClause(node.heritageClauses, 86 /* ExtendsKeyword */); + return heritageClause ? heritageClause.types : undefined; + } + ts.getInterfaceBaseTypeNodes = getInterfaceBaseTypeNodes; + function getHeritageClause(clauses, kind) { + if (clauses) { + for (var _i = 0, clauses_1 = clauses; _i < clauses_1.length; _i++) { + var clause = clauses_1[_i]; + if (clause.token === kind) { + return clause; + } + } + } + return undefined; + } + ts.getHeritageClause = getHeritageClause; + function tryResolveScriptReference(host, sourceFile, reference) { + if (!host.getCompilerOptions().noResolve) { + var referenceFileName = ts.isRootedDiskPath(reference.fileName) ? reference.fileName : ts.combinePaths(ts.getDirectoryPath(sourceFile.fileName), reference.fileName); + return host.getSourceFile(referenceFileName); + } + } + ts.tryResolveScriptReference = tryResolveScriptReference; + function getAncestor(node, kind) { + while (node) { + if (node.kind === kind) { + return node; + } + node = node.parent; + } + return undefined; + } + ts.getAncestor = getAncestor; + function isKeyword(token) { + return 73 /* FirstKeyword */ <= token && token <= 147 /* LastKeyword */; + } + ts.isKeyword = isKeyword; + function isContextualKeyword(token) { + return 118 /* FirstContextualKeyword */ <= token && token <= 147 /* LastContextualKeyword */; + } + ts.isContextualKeyword = isContextualKeyword; + function isNonContextualKeyword(token) { + return isKeyword(token) && !isContextualKeyword(token); + } + ts.isNonContextualKeyword = isNonContextualKeyword; + function isStringANonContextualKeyword(name) { + var token = ts.stringToToken(name); + return token !== undefined && isNonContextualKeyword(token); + } + ts.isStringANonContextualKeyword = isStringANonContextualKeyword; + function isIdentifierANonContextualKeyword(_a) { + var originalKeywordKind = _a.originalKeywordKind; + return !!originalKeywordKind && !isContextualKeyword(originalKeywordKind); + } + ts.isIdentifierANonContextualKeyword = isIdentifierANonContextualKeyword; + function isTrivia(token) { + return 2 /* FirstTriviaToken */ <= token && token <= 7 /* LastTriviaToken */; + } + ts.isTrivia = isTrivia; + var FunctionFlags; + (function (FunctionFlags) { + FunctionFlags[FunctionFlags["Normal"] = 0] = "Normal"; + FunctionFlags[FunctionFlags["Generator"] = 1] = "Generator"; + FunctionFlags[FunctionFlags["Async"] = 2] = "Async"; + FunctionFlags[FunctionFlags["Invalid"] = 4] = "Invalid"; + FunctionFlags[FunctionFlags["AsyncGenerator"] = 3] = "AsyncGenerator"; + })(FunctionFlags = ts.FunctionFlags || (ts.FunctionFlags = {})); + function getFunctionFlags(node) { + if (!node) { + return 4 /* Invalid */; + } + var flags = 0 /* Normal */; + switch (node.kind) { + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 156 /* MethodDeclaration */: + if (node.asteriskToken) { + flags |= 1 /* Generator */; + } + // falls through + case 197 /* ArrowFunction */: + if (hasModifier(node, 256 /* Async */)) { + flags |= 2 /* Async */; + } + break; + } + if (!node.body) { + flags |= 4 /* Invalid */; + } + return flags; + } + ts.getFunctionFlags = getFunctionFlags; + function isAsyncFunction(node) { + switch (node.kind) { + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 156 /* MethodDeclaration */: + return node.body !== undefined + && node.asteriskToken === undefined + && hasModifier(node, 256 /* Async */); + } + return false; + } + ts.isAsyncFunction = isAsyncFunction; + function isStringOrNumericLiteralLike(node) { + return ts.isStringLiteralLike(node) || ts.isNumericLiteral(node); + } + ts.isStringOrNumericLiteralLike = isStringOrNumericLiteralLike; + /** + * A declaration has a dynamic name if both of the following are true: + * 1. The declaration has a computed property name + * 2. The computed name is *not* expressed as Symbol., where name + * is a property of the Symbol constructor that denotes a built in + * Symbol. + */ + function hasDynamicName(declaration) { + var name = ts.getNameOfDeclaration(declaration); + return !!name && isDynamicName(name); + } + ts.hasDynamicName = hasDynamicName; + function isDynamicName(name) { + return name.kind === 149 /* ComputedPropertyName */ && + !isStringOrNumericLiteralLike(name.expression) && + !isWellKnownSymbolSyntactically(name.expression); + } + ts.isDynamicName = isDynamicName; + /** + * Checks if the expression is of the form: + * Symbol.name + * where Symbol is literally the word "Symbol", and name is any identifierName + */ + function isWellKnownSymbolSyntactically(node) { + return ts.isPropertyAccessExpression(node) && isESSymbolIdentifier(node.expression); + } + ts.isWellKnownSymbolSyntactically = isWellKnownSymbolSyntactically; + function getPropertyNameForPropertyNameNode(name) { + switch (name.kind) { + case 72 /* Identifier */: + return name.escapedText; + case 10 /* StringLiteral */: + case 8 /* NumericLiteral */: + return ts.escapeLeadingUnderscores(name.text); + case 149 /* ComputedPropertyName */: + var nameExpression = name.expression; + if (isWellKnownSymbolSyntactically(nameExpression)) { + return getPropertyNameForKnownSymbolName(ts.idText(nameExpression.name)); + } + else if (isStringOrNumericLiteralLike(nameExpression)) { + return ts.escapeLeadingUnderscores(nameExpression.text); + } + return undefined; + default: + return ts.Debug.assertNever(name); + } + } + ts.getPropertyNameForPropertyNameNode = getPropertyNameForPropertyNameNode; + function isPropertyNameLiteral(node) { + switch (node.kind) { + case 72 /* Identifier */: + case 10 /* StringLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: + case 8 /* NumericLiteral */: + return true; + default: + return false; + } + } + ts.isPropertyNameLiteral = isPropertyNameLiteral; + function getTextOfIdentifierOrLiteral(node) { + return node.kind === 72 /* Identifier */ ? ts.idText(node) : node.text; + } + ts.getTextOfIdentifierOrLiteral = getTextOfIdentifierOrLiteral; + function getEscapedTextOfIdentifierOrLiteral(node) { + return node.kind === 72 /* Identifier */ ? node.escapedText : ts.escapeLeadingUnderscores(node.text); + } + ts.getEscapedTextOfIdentifierOrLiteral = getEscapedTextOfIdentifierOrLiteral; + function getPropertyNameForKnownSymbolName(symbolName) { + return "__@" + symbolName; + } + ts.getPropertyNameForKnownSymbolName = getPropertyNameForKnownSymbolName; + function isKnownSymbol(symbol) { + return ts.startsWith(symbol.escapedName, "__@"); + } + ts.isKnownSymbol = isKnownSymbol; + /** + * Includes the word "Symbol" with unicode escapes + */ + function isESSymbolIdentifier(node) { + return node.kind === 72 /* Identifier */ && node.escapedText === "Symbol"; + } + ts.isESSymbolIdentifier = isESSymbolIdentifier; + function isPushOrUnshiftIdentifier(node) { + return node.escapedText === "push" || node.escapedText === "unshift"; + } + ts.isPushOrUnshiftIdentifier = isPushOrUnshiftIdentifier; + function isParameterDeclaration(node) { + var root = getRootDeclaration(node); + return root.kind === 151 /* Parameter */; + } + ts.isParameterDeclaration = isParameterDeclaration; + function getRootDeclaration(node) { + while (node.kind === 186 /* BindingElement */) { + node = node.parent.parent; + } + return node; + } + ts.getRootDeclaration = getRootDeclaration; + function nodeStartsNewLexicalEnvironment(node) { + var kind = node.kind; + return kind === 157 /* Constructor */ + || kind === 196 /* FunctionExpression */ + || kind === 239 /* FunctionDeclaration */ + || kind === 197 /* ArrowFunction */ + || kind === 156 /* MethodDeclaration */ + || kind === 158 /* GetAccessor */ + || kind === 159 /* SetAccessor */ + || kind === 244 /* ModuleDeclaration */ + || kind === 279 /* SourceFile */; + } + ts.nodeStartsNewLexicalEnvironment = nodeStartsNewLexicalEnvironment; + function nodeIsSynthesized(range) { + return ts.positionIsSynthesized(range.pos) + || ts.positionIsSynthesized(range.end); + } + ts.nodeIsSynthesized = nodeIsSynthesized; + function getOriginalSourceFile(sourceFile) { + return ts.getParseTreeNode(sourceFile, ts.isSourceFile) || sourceFile; + } + ts.getOriginalSourceFile = getOriginalSourceFile; + var Associativity; + (function (Associativity) { + Associativity[Associativity["Left"] = 0] = "Left"; + Associativity[Associativity["Right"] = 1] = "Right"; + })(Associativity = ts.Associativity || (ts.Associativity = {})); + function getExpressionAssociativity(expression) { + var operator = getOperator(expression); + var hasArguments = expression.kind === 192 /* NewExpression */ && expression.arguments !== undefined; + return getOperatorAssociativity(expression.kind, operator, hasArguments); + } + ts.getExpressionAssociativity = getExpressionAssociativity; + function getOperatorAssociativity(kind, operator, hasArguments) { + switch (kind) { + case 192 /* NewExpression */: + return hasArguments ? 0 /* Left */ : 1 /* Right */; + case 202 /* PrefixUnaryExpression */: + case 199 /* TypeOfExpression */: + case 200 /* VoidExpression */: + case 198 /* DeleteExpression */: + case 201 /* AwaitExpression */: + case 205 /* ConditionalExpression */: + case 207 /* YieldExpression */: + return 1 /* Right */; + case 204 /* BinaryExpression */: + switch (operator) { + case 41 /* AsteriskAsteriskToken */: + case 59 /* EqualsToken */: + case 60 /* PlusEqualsToken */: + case 61 /* MinusEqualsToken */: + case 63 /* AsteriskAsteriskEqualsToken */: + case 62 /* AsteriskEqualsToken */: + case 64 /* SlashEqualsToken */: + case 65 /* PercentEqualsToken */: + case 66 /* LessThanLessThanEqualsToken */: + case 67 /* GreaterThanGreaterThanEqualsToken */: + case 68 /* GreaterThanGreaterThanGreaterThanEqualsToken */: + case 69 /* AmpersandEqualsToken */: + case 71 /* CaretEqualsToken */: + case 70 /* BarEqualsToken */: + return 1 /* Right */; + } + } + return 0 /* Left */; + } + ts.getOperatorAssociativity = getOperatorAssociativity; + function getExpressionPrecedence(expression) { + var operator = getOperator(expression); + var hasArguments = expression.kind === 192 /* NewExpression */ && expression.arguments !== undefined; + return getOperatorPrecedence(expression.kind, operator, hasArguments); + } + ts.getExpressionPrecedence = getExpressionPrecedence; + function getOperator(expression) { + if (expression.kind === 204 /* BinaryExpression */) { + return expression.operatorToken.kind; + } + else if (expression.kind === 202 /* PrefixUnaryExpression */ || expression.kind === 203 /* PostfixUnaryExpression */) { + return expression.operator; + } + else { + return expression.kind; + } + } + ts.getOperator = getOperator; + function getOperatorPrecedence(nodeKind, operatorKind, hasArguments) { + switch (nodeKind) { + case 309 /* CommaListExpression */: + return 0; + case 208 /* SpreadElement */: + return 1; + case 207 /* YieldExpression */: + return 2; + case 205 /* ConditionalExpression */: + return 4; + case 204 /* BinaryExpression */: + switch (operatorKind) { + case 27 /* CommaToken */: + return 0; + case 59 /* EqualsToken */: + case 60 /* PlusEqualsToken */: + case 61 /* MinusEqualsToken */: + case 63 /* AsteriskAsteriskEqualsToken */: + case 62 /* AsteriskEqualsToken */: + case 64 /* SlashEqualsToken */: + case 65 /* PercentEqualsToken */: + case 66 /* LessThanLessThanEqualsToken */: + case 67 /* GreaterThanGreaterThanEqualsToken */: + case 68 /* GreaterThanGreaterThanGreaterThanEqualsToken */: + case 69 /* AmpersandEqualsToken */: + case 71 /* CaretEqualsToken */: + case 70 /* BarEqualsToken */: + return 3; + default: + return getBinaryOperatorPrecedence(operatorKind); + } + case 202 /* PrefixUnaryExpression */: + case 199 /* TypeOfExpression */: + case 200 /* VoidExpression */: + case 198 /* DeleteExpression */: + case 201 /* AwaitExpression */: + return 16; + case 203 /* PostfixUnaryExpression */: + return 17; + case 191 /* CallExpression */: + return 18; + case 192 /* NewExpression */: + return hasArguments ? 19 : 18; + case 193 /* TaggedTemplateExpression */: + case 189 /* PropertyAccessExpression */: + case 190 /* ElementAccessExpression */: + return 19; + case 100 /* ThisKeyword */: + case 98 /* SuperKeyword */: + case 72 /* Identifier */: + case 96 /* NullKeyword */: + case 102 /* TrueKeyword */: + case 87 /* FalseKeyword */: + case 8 /* NumericLiteral */: + case 9 /* BigIntLiteral */: + case 10 /* StringLiteral */: + case 187 /* ArrayLiteralExpression */: + case 188 /* ObjectLiteralExpression */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 209 /* ClassExpression */: + case 260 /* JsxElement */: + case 261 /* JsxSelfClosingElement */: + case 264 /* JsxFragment */: + case 13 /* RegularExpressionLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: + case 206 /* TemplateExpression */: + case 195 /* ParenthesizedExpression */: + case 210 /* OmittedExpression */: + return 20; + default: + return -1; + } + } + ts.getOperatorPrecedence = getOperatorPrecedence; + function getBinaryOperatorPrecedence(kind) { + switch (kind) { + case 55 /* BarBarToken */: + return 5; + case 54 /* AmpersandAmpersandToken */: + return 6; + case 50 /* BarToken */: + return 7; + case 51 /* CaretToken */: + return 8; + case 49 /* AmpersandToken */: + return 9; + case 33 /* EqualsEqualsToken */: + case 34 /* ExclamationEqualsToken */: + case 35 /* EqualsEqualsEqualsToken */: + case 36 /* ExclamationEqualsEqualsToken */: + return 10; + case 28 /* LessThanToken */: + case 30 /* GreaterThanToken */: + case 31 /* LessThanEqualsToken */: + case 32 /* GreaterThanEqualsToken */: + case 94 /* InstanceOfKeyword */: + case 93 /* InKeyword */: + case 119 /* AsKeyword */: + return 11; + case 46 /* LessThanLessThanToken */: + case 47 /* GreaterThanGreaterThanToken */: + case 48 /* GreaterThanGreaterThanGreaterThanToken */: + return 12; + case 38 /* PlusToken */: + case 39 /* MinusToken */: + return 13; + case 40 /* AsteriskToken */: + case 42 /* SlashToken */: + case 43 /* PercentToken */: + return 14; + case 41 /* AsteriskAsteriskToken */: + return 15; + } + // -1 is lower than all other precedences. Returning it will cause binary expression + // parsing to stop. + return -1; + } + ts.getBinaryOperatorPrecedence = getBinaryOperatorPrecedence; + function createDiagnosticCollection() { + var nonFileDiagnostics = []; // See GH#19873 + var filesWithDiagnostics = []; + var fileDiagnostics = ts.createMap(); + var hasReadNonFileDiagnostics = false; + return { + add: add, + lookup: lookup, + getGlobalDiagnostics: getGlobalDiagnostics, + getDiagnostics: getDiagnostics, + reattachFileDiagnostics: reattachFileDiagnostics + }; + function reattachFileDiagnostics(newFile) { + ts.forEach(fileDiagnostics.get(newFile.fileName), function (diagnostic) { return diagnostic.file = newFile; }); + } + function lookup(diagnostic) { + var diagnostics; + if (diagnostic.file) { + diagnostics = fileDiagnostics.get(diagnostic.file.fileName); + } + else { + diagnostics = nonFileDiagnostics; + } + if (!diagnostics) { + return undefined; + } + var result = ts.binarySearch(diagnostics, diagnostic, ts.identity, ts.compareDiagnosticsSkipRelatedInformation); + if (result >= 0) { + return diagnostics[result]; + } + return undefined; + } + function add(diagnostic) { + var diagnostics; + if (diagnostic.file) { + diagnostics = fileDiagnostics.get(diagnostic.file.fileName); + if (!diagnostics) { + diagnostics = []; // See GH#19873 + fileDiagnostics.set(diagnostic.file.fileName, diagnostics); + ts.insertSorted(filesWithDiagnostics, diagnostic.file.fileName, ts.compareStringsCaseSensitive); + } + } + else { + // If we've already read the non-file diagnostics, do not modify the existing array. + if (hasReadNonFileDiagnostics) { + hasReadNonFileDiagnostics = false; + nonFileDiagnostics = nonFileDiagnostics.slice(); + } + diagnostics = nonFileDiagnostics; + } + ts.insertSorted(diagnostics, diagnostic, ts.compareDiagnostics); + } + function getGlobalDiagnostics() { + hasReadNonFileDiagnostics = true; + return nonFileDiagnostics; + } + function getDiagnostics(fileName) { + if (fileName) { + return fileDiagnostics.get(fileName) || []; + } + var fileDiags = ts.flatMapToMutable(filesWithDiagnostics, function (f) { return fileDiagnostics.get(f); }); + if (!nonFileDiagnostics.length) { + return fileDiags; + } + fileDiags.unshift.apply(fileDiags, nonFileDiagnostics); + return fileDiags; + } + } + ts.createDiagnosticCollection = createDiagnosticCollection; + // This consists of the first 19 unprintable ASCII characters, canonical escapes, lineSeparator, + // paragraphSeparator, and nextLine. The latter three are just desirable to suppress new lines in + // the language service. These characters should be escaped when printing, and if any characters are added, + // the map below must be updated. Note that this regexp *does not* include the 'delete' character. + // There is no reason for this other than that JSON.stringify does not handle it either. + var doubleQuoteEscapedCharsRegExp = /[\\\"\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g; + var singleQuoteEscapedCharsRegExp = /[\\\'\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g; + var backtickQuoteEscapedCharsRegExp = /[\\\`\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g; + var escapedCharsMap = ts.createMapFromTemplate({ + "\t": "\\t", + "\v": "\\v", + "\f": "\\f", + "\b": "\\b", + "\r": "\\r", + "\n": "\\n", + "\\": "\\\\", + "\"": "\\\"", + "\'": "\\\'", + "\`": "\\\`", + "\u2028": "\\u2028", + "\u2029": "\\u2029", + "\u0085": "\\u0085" // nextLine + }); + /** + * Based heavily on the abstract 'Quote'/'QuoteJSONString' operation from ECMA-262 (24.3.2.2), + * but augmented for a few select characters (e.g. lineSeparator, paragraphSeparator, nextLine) + * Note that this doesn't actually wrap the input in double quotes. + */ + function escapeString(s, quoteChar) { + var escapedCharsRegExp = quoteChar === 96 /* backtick */ ? backtickQuoteEscapedCharsRegExp : + quoteChar === 39 /* singleQuote */ ? singleQuoteEscapedCharsRegExp : + doubleQuoteEscapedCharsRegExp; + return s.replace(escapedCharsRegExp, getReplacement); + } + ts.escapeString = escapeString; + function getReplacement(c, offset, input) { + if (c.charCodeAt(0) === 0 /* nullCharacter */) { + var lookAhead = input.charCodeAt(offset + c.length); + if (lookAhead >= 48 /* _0 */ && lookAhead <= 57 /* _9 */) { + // If the null character is followed by digits, print as a hex escape to prevent the result from parsing as an octal (which is forbidden in strict mode) + return "\\x00"; + } + // Otherwise, keep printing a literal \0 for the null character + return "\\0"; + } + return escapedCharsMap.get(c) || get16BitUnicodeEscapeSequence(c.charCodeAt(0)); + } + function isIntrinsicJsxName(name) { + var ch = name.charCodeAt(0); + return (ch >= 97 /* a */ && ch <= 122 /* z */) || ts.stringContains(name, "-"); + } + ts.isIntrinsicJsxName = isIntrinsicJsxName; + function get16BitUnicodeEscapeSequence(charCode) { + var hexCharCode = charCode.toString(16).toUpperCase(); + var paddedHexCode = ("0000" + hexCharCode).slice(-4); + return "\\u" + paddedHexCode; + } + var nonAsciiCharacters = /[^\u0000-\u007F]/g; + function escapeNonAsciiString(s, quoteChar) { + s = escapeString(s, quoteChar); + // Replace non-ASCII characters with '\uNNNN' escapes if any exist. + // Otherwise just return the original string. + return nonAsciiCharacters.test(s) ? + s.replace(nonAsciiCharacters, function (c) { return get16BitUnicodeEscapeSequence(c.charCodeAt(0)); }) : + s; + } + ts.escapeNonAsciiString = escapeNonAsciiString; + var indentStrings = ["", " "]; + function getIndentString(level) { + if (indentStrings[level] === undefined) { + indentStrings[level] = getIndentString(level - 1) + indentStrings[1]; + } + return indentStrings[level]; + } + ts.getIndentString = getIndentString; + function getIndentSize() { + return indentStrings[1].length; + } + ts.getIndentSize = getIndentSize; + function createTextWriter(newLine) { + var output; + var indent; + var lineStart; + var lineCount; + var linePos; + function updateLineCountAndPosFor(s) { + var lineStartsOfS = ts.computeLineStarts(s); + if (lineStartsOfS.length > 1) { + lineCount = lineCount + lineStartsOfS.length - 1; + linePos = output.length - s.length + ts.last(lineStartsOfS); + lineStart = (linePos - output.length) === 0; + } + else { + lineStart = false; + } + } + function write(s) { + if (s && s.length) { + if (lineStart) { + s = getIndentString(indent) + s; + lineStart = false; + } + output += s; + updateLineCountAndPosFor(s); + } + } + function reset() { + output = ""; + indent = 0; + lineStart = true; + lineCount = 0; + linePos = 0; + } + function rawWrite(s) { + if (s !== undefined) { + output += s; + updateLineCountAndPosFor(s); + } + } + function writeLiteral(s) { + if (s && s.length) { + write(s); + } + } + function writeLine() { + if (!lineStart) { + output += newLine; + lineCount++; + linePos = output.length; + lineStart = true; + } + } + reset(); + return { + write: write, + rawWrite: rawWrite, + writeLiteral: writeLiteral, + writeLine: writeLine, + increaseIndent: function () { indent++; }, + decreaseIndent: function () { indent--; }, + getIndent: function () { return indent; }, + getTextPos: function () { return output.length; }, + getLine: function () { return lineCount; }, + getColumn: function () { return lineStart ? indent * getIndentSize() : output.length - linePos; }, + getText: function () { return output; }, + isAtStartOfLine: function () { return lineStart; }, + clear: reset, + reportInaccessibleThisError: ts.noop, + reportPrivateInBaseOfClassExpression: ts.noop, + reportInaccessibleUniqueSymbolError: ts.noop, + trackSymbol: ts.noop, + writeKeyword: write, + writeOperator: write, + writeParameter: write, + writeProperty: write, + writePunctuation: write, + writeSpace: write, + writeStringLiteral: write, + writeSymbol: function (s, _) { return write(s); }, + writeTrailingSemicolon: write, + writeComment: write + }; + } + ts.createTextWriter = createTextWriter; + function getTrailingSemicolonOmittingWriter(writer) { + var pendingTrailingSemicolon = false; + function commitPendingTrailingSemicolon() { + if (pendingTrailingSemicolon) { + writer.writeTrailingSemicolon(";"); + pendingTrailingSemicolon = false; + } + } + return __assign({}, writer, { writeTrailingSemicolon: function () { + pendingTrailingSemicolon = true; + }, + writeLiteral: function (s) { + commitPendingTrailingSemicolon(); + writer.writeLiteral(s); + }, + writeStringLiteral: function (s) { + commitPendingTrailingSemicolon(); + writer.writeStringLiteral(s); + }, + writeSymbol: function (s, sym) { + commitPendingTrailingSemicolon(); + writer.writeSymbol(s, sym); + }, + writePunctuation: function (s) { + commitPendingTrailingSemicolon(); + writer.writePunctuation(s); + }, + writeKeyword: function (s) { + commitPendingTrailingSemicolon(); + writer.writeKeyword(s); + }, + writeOperator: function (s) { + commitPendingTrailingSemicolon(); + writer.writeOperator(s); + }, + writeParameter: function (s) { + commitPendingTrailingSemicolon(); + writer.writeParameter(s); + }, + writeSpace: function (s) { + commitPendingTrailingSemicolon(); + writer.writeSpace(s); + }, + writeProperty: function (s) { + commitPendingTrailingSemicolon(); + writer.writeProperty(s); + }, + writeComment: function (s) { + commitPendingTrailingSemicolon(); + writer.writeComment(s); + }, + writeLine: function () { + commitPendingTrailingSemicolon(); + writer.writeLine(); + }, + increaseIndent: function () { + commitPendingTrailingSemicolon(); + writer.increaseIndent(); + }, + decreaseIndent: function () { + commitPendingTrailingSemicolon(); + writer.decreaseIndent(); + } }); + } + ts.getTrailingSemicolonOmittingWriter = getTrailingSemicolonOmittingWriter; + function getResolvedExternalModuleName(host, file, referenceFile) { + return file.moduleName || getExternalModuleNameFromPath(host, file.fileName, referenceFile && referenceFile.fileName); + } + ts.getResolvedExternalModuleName = getResolvedExternalModuleName; + function getExternalModuleNameFromDeclaration(host, resolver, declaration) { + var file = resolver.getExternalModuleFileFromDeclaration(declaration); + if (!file || file.isDeclarationFile) { + return undefined; + } + return getResolvedExternalModuleName(host, file); + } + ts.getExternalModuleNameFromDeclaration = getExternalModuleNameFromDeclaration; + /** + * Resolves a local path to a path which is absolute to the base of the emit + */ + function getExternalModuleNameFromPath(host, fileName, referencePath) { + var getCanonicalFileName = function (f) { return host.getCanonicalFileName(f); }; + var dir = toPath(referencePath ? ts.getDirectoryPath(referencePath) : host.getCommonSourceDirectory(), host.getCurrentDirectory(), getCanonicalFileName); + var filePath = ts.getNormalizedAbsolutePath(fileName, host.getCurrentDirectory()); + var relativePath = ts.getRelativePathToDirectoryOrUrl(dir, filePath, dir, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); + var extensionless = ts.removeFileExtension(relativePath); + return referencePath ? ts.ensurePathIsNonModuleName(extensionless) : extensionless; + } + ts.getExternalModuleNameFromPath = getExternalModuleNameFromPath; + function getOwnEmitOutputFilePath(fileName, host, extension) { + var compilerOptions = host.getCompilerOptions(); + var emitOutputFilePathWithoutExtension; + if (compilerOptions.outDir) { + emitOutputFilePathWithoutExtension = ts.removeFileExtension(getSourceFilePathInNewDir(fileName, host, compilerOptions.outDir)); + } + else { + emitOutputFilePathWithoutExtension = ts.removeFileExtension(fileName); + } + return emitOutputFilePathWithoutExtension + extension; + } + ts.getOwnEmitOutputFilePath = getOwnEmitOutputFilePath; + function getDeclarationEmitOutputFilePath(fileName, host) { + return getDeclarationEmitOutputFilePathWorker(fileName, host.getCompilerOptions(), host.getCurrentDirectory(), host.getCommonSourceDirectory(), function (f) { return host.getCanonicalFileName(f); }); + } + ts.getDeclarationEmitOutputFilePath = getDeclarationEmitOutputFilePath; + function getDeclarationEmitOutputFilePathWorker(fileName, options, currentDirectory, commonSourceDirectory, getCanonicalFileName) { + var outputDir = options.declarationDir || options.outDir; // Prefer declaration folder if specified + var path = outputDir + ? getSourceFilePathInNewDirWorker(fileName, outputDir, currentDirectory, commonSourceDirectory, getCanonicalFileName) + : fileName; + return ts.removeFileExtension(path) + ".d.ts" /* Dts */; + } + ts.getDeclarationEmitOutputFilePathWorker = getDeclarationEmitOutputFilePathWorker; + /** + * Gets the source files that are expected to have an emit output. + * + * Originally part of `forEachExpectedEmitFile`, this functionality was extracted to support + * transformations. + * + * @param host An EmitHost. + * @param targetSourceFile An optional target source file to emit. + */ + function getSourceFilesToEmit(host, targetSourceFile) { + var options = host.getCompilerOptions(); + var isSourceFileFromExternalLibrary = function (file) { return host.isSourceFileFromExternalLibrary(file); }; + if (options.outFile || options.out) { + var moduleKind = ts.getEmitModuleKind(options); + var moduleEmitEnabled_1 = options.emitDeclarationOnly || moduleKind === ts.ModuleKind.AMD || moduleKind === ts.ModuleKind.System; + // Can emit only sources that are not declaration file and are either non module code or module with --module or --target es6 specified + return ts.filter(host.getSourceFiles(), function (sourceFile) { + return (moduleEmitEnabled_1 || !ts.isExternalModule(sourceFile)) && sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary); + }); + } + else { + var sourceFiles = targetSourceFile === undefined ? host.getSourceFiles() : [targetSourceFile]; + return ts.filter(sourceFiles, function (sourceFile) { return sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary); }); + } + } + ts.getSourceFilesToEmit = getSourceFilesToEmit; + /** Don't call this for `--outFile`, just for `--outDir` or plain emit. `--outFile` needs additional checks. */ + function sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary) { + return !(options.noEmitForJsFiles && isSourceFileJS(sourceFile)) && !sourceFile.isDeclarationFile && !isSourceFileFromExternalLibrary(sourceFile); + } + ts.sourceFileMayBeEmitted = sourceFileMayBeEmitted; + function getSourceFilePathInNewDir(fileName, host, newDirPath) { + return getSourceFilePathInNewDirWorker(fileName, newDirPath, host.getCurrentDirectory(), host.getCommonSourceDirectory(), function (f) { return host.getCanonicalFileName(f); }); + } + ts.getSourceFilePathInNewDir = getSourceFilePathInNewDir; + function getSourceFilePathInNewDirWorker(fileName, newDirPath, currentDirectory, commonSourceDirectory, getCanonicalFileName) { + var sourceFilePath = ts.getNormalizedAbsolutePath(fileName, currentDirectory); + var isSourceFileInCommonSourceDirectory = getCanonicalFileName(sourceFilePath).indexOf(getCanonicalFileName(commonSourceDirectory)) === 0; + sourceFilePath = isSourceFileInCommonSourceDirectory ? sourceFilePath.substring(commonSourceDirectory.length) : sourceFilePath; + return ts.combinePaths(newDirPath, sourceFilePath); + } + ts.getSourceFilePathInNewDirWorker = getSourceFilePathInNewDirWorker; + function writeFile(host, diagnostics, fileName, data, writeByteOrderMark, sourceFiles) { + host.writeFile(fileName, data, writeByteOrderMark, function (hostErrorMessage) { + diagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Could_not_write_file_0_Colon_1, fileName, hostErrorMessage)); + }, sourceFiles); + } + ts.writeFile = writeFile; + function getLineOfLocalPosition(currentSourceFile, pos) { + return ts.getLineAndCharacterOfPosition(currentSourceFile, pos).line; + } + ts.getLineOfLocalPosition = getLineOfLocalPosition; + function getLineOfLocalPositionFromLineMap(lineMap, pos) { + return ts.computeLineAndCharacterOfPosition(lineMap, pos).line; + } + ts.getLineOfLocalPositionFromLineMap = getLineOfLocalPositionFromLineMap; + function getFirstConstructorWithBody(node) { + return ts.find(node.members, function (member) { return ts.isConstructorDeclaration(member) && nodeIsPresent(member.body); }); + } + ts.getFirstConstructorWithBody = getFirstConstructorWithBody; + function getSetAccessorValueParameter(accessor) { + if (accessor && accessor.parameters.length > 0) { + var hasThis = accessor.parameters.length === 2 && parameterIsThisKeyword(accessor.parameters[0]); + return accessor.parameters[hasThis ? 1 : 0]; + } + } + /** Get the type annotation for the value parameter. */ + function getSetAccessorTypeAnnotationNode(accessor) { + var parameter = getSetAccessorValueParameter(accessor); + return parameter && parameter.type; + } + ts.getSetAccessorTypeAnnotationNode = getSetAccessorTypeAnnotationNode; + function getThisParameter(signature) { + // callback tags do not currently support this parameters + if (signature.parameters.length && !ts.isJSDocSignature(signature)) { + var thisParameter = signature.parameters[0]; + if (parameterIsThisKeyword(thisParameter)) { + return thisParameter; + } + } + } + ts.getThisParameter = getThisParameter; + function parameterIsThisKeyword(parameter) { + return isThisIdentifier(parameter.name); + } + ts.parameterIsThisKeyword = parameterIsThisKeyword; + function isThisIdentifier(node) { + return !!node && node.kind === 72 /* Identifier */ && identifierIsThisKeyword(node); + } + ts.isThisIdentifier = isThisIdentifier; + function identifierIsThisKeyword(id) { + return id.originalKeywordKind === 100 /* ThisKeyword */; + } + ts.identifierIsThisKeyword = identifierIsThisKeyword; + function getAllAccessorDeclarations(declarations, accessor) { + // TODO: GH#18217 + var firstAccessor; + var secondAccessor; + var getAccessor; + var setAccessor; + if (hasDynamicName(accessor)) { + firstAccessor = accessor; + if (accessor.kind === 158 /* GetAccessor */) { + getAccessor = accessor; + } + else if (accessor.kind === 159 /* SetAccessor */) { + setAccessor = accessor; + } + else { + ts.Debug.fail("Accessor has wrong kind"); + } + } + else { + ts.forEach(declarations, function (member) { + if (ts.isAccessor(member) + && hasModifier(member, 32 /* Static */) === hasModifier(accessor, 32 /* Static */)) { + var memberName = getPropertyNameForPropertyNameNode(member.name); + var accessorName = getPropertyNameForPropertyNameNode(accessor.name); + if (memberName === accessorName) { + if (!firstAccessor) { + firstAccessor = member; + } + else if (!secondAccessor) { + secondAccessor = member; + } + if (member.kind === 158 /* GetAccessor */ && !getAccessor) { + getAccessor = member; + } + if (member.kind === 159 /* SetAccessor */ && !setAccessor) { + setAccessor = member; + } + } + } + }); + } + return { + firstAccessor: firstAccessor, + secondAccessor: secondAccessor, + getAccessor: getAccessor, + setAccessor: setAccessor + }; + } + ts.getAllAccessorDeclarations = getAllAccessorDeclarations; + /** + * Gets the effective type annotation of a variable, parameter, or property. If the node was + * parsed in a JavaScript file, gets the type annotation from JSDoc. + */ + function getEffectiveTypeAnnotationNode(node) { + var type = node.type; + if (type || !isInJSFile(node)) + return type; + return ts.isJSDocPropertyLikeTag(node) ? node.typeExpression && node.typeExpression.type : ts.getJSDocType(node); + } + ts.getEffectiveTypeAnnotationNode = getEffectiveTypeAnnotationNode; + function getTypeAnnotationNode(node) { + return node.type; + } + ts.getTypeAnnotationNode = getTypeAnnotationNode; + /** + * Gets the effective return type annotation of a signature. If the node was parsed in a + * JavaScript file, gets the return type annotation from JSDoc. + */ + function getEffectiveReturnTypeNode(node) { + return ts.isJSDocSignature(node) ? + node.type && node.type.typeExpression && node.type.typeExpression.type : + node.type || (isInJSFile(node) ? ts.getJSDocReturnType(node) : undefined); + } + ts.getEffectiveReturnTypeNode = getEffectiveReturnTypeNode; + function getJSDocTypeParameterDeclarations(node) { + return ts.flatMap(ts.getJSDocTags(node), function (tag) { return isNonTypeAliasTemplate(tag) ? tag.typeParameters : undefined; }); + } + ts.getJSDocTypeParameterDeclarations = getJSDocTypeParameterDeclarations; + /** template tags are only available when a typedef isn't already using them */ + function isNonTypeAliasTemplate(tag) { + return ts.isJSDocTemplateTag(tag) && !(tag.parent.kind === 291 /* JSDocComment */ && tag.parent.tags.some(isJSDocTypeAlias)); + } + /** + * Gets the effective type annotation of the value parameter of a set accessor. If the node + * was parsed in a JavaScript file, gets the type annotation from JSDoc. + */ + function getEffectiveSetAccessorTypeAnnotationNode(node) { + var parameter = getSetAccessorValueParameter(node); + return parameter && getEffectiveTypeAnnotationNode(parameter); + } + ts.getEffectiveSetAccessorTypeAnnotationNode = getEffectiveSetAccessorTypeAnnotationNode; + function emitNewLineBeforeLeadingComments(lineMap, writer, node, leadingComments) { + emitNewLineBeforeLeadingCommentsOfPosition(lineMap, writer, node.pos, leadingComments); + } + ts.emitNewLineBeforeLeadingComments = emitNewLineBeforeLeadingComments; + function emitNewLineBeforeLeadingCommentsOfPosition(lineMap, writer, pos, leadingComments) { + // If the leading comments start on different line than the start of node, write new line + if (leadingComments && leadingComments.length && pos !== leadingComments[0].pos && + getLineOfLocalPositionFromLineMap(lineMap, pos) !== getLineOfLocalPositionFromLineMap(lineMap, leadingComments[0].pos)) { + writer.writeLine(); + } + } + ts.emitNewLineBeforeLeadingCommentsOfPosition = emitNewLineBeforeLeadingCommentsOfPosition; + function emitNewLineBeforeLeadingCommentOfPosition(lineMap, writer, pos, commentPos) { + // If the leading comments start on different line than the start of node, write new line + if (pos !== commentPos && + getLineOfLocalPositionFromLineMap(lineMap, pos) !== getLineOfLocalPositionFromLineMap(lineMap, commentPos)) { + writer.writeLine(); + } + } + ts.emitNewLineBeforeLeadingCommentOfPosition = emitNewLineBeforeLeadingCommentOfPosition; + function emitComments(text, lineMap, writer, comments, leadingSeparator, trailingSeparator, newLine, writeComment) { + if (comments && comments.length > 0) { + if (leadingSeparator) { + writer.writeSpace(" "); + } + var emitInterveningSeparator = false; + for (var _i = 0, comments_1 = comments; _i < comments_1.length; _i++) { + var comment = comments_1[_i]; + if (emitInterveningSeparator) { + writer.writeSpace(" "); + emitInterveningSeparator = false; + } + writeComment(text, lineMap, writer, comment.pos, comment.end, newLine); + if (comment.hasTrailingNewLine) { + writer.writeLine(); + } + else { + emitInterveningSeparator = true; + } + } + if (emitInterveningSeparator && trailingSeparator) { + writer.writeSpace(" "); + } + } + } + ts.emitComments = emitComments; + /** + * Detached comment is a comment at the top of file or function body that is separated from + * the next statement by space. + */ + function emitDetachedComments(text, lineMap, writer, writeComment, node, newLine, removeComments) { + var leadingComments; + var currentDetachedCommentInfo; + if (removeComments) { + // removeComments is true, only reserve pinned comment at the top of file + // For example: + // /*! Pinned Comment */ + // + // var x = 10; + if (node.pos === 0) { + leadingComments = ts.filter(ts.getLeadingCommentRanges(text, node.pos), isPinnedCommentLocal); + } + } + else { + // removeComments is false, just get detached as normal and bypass the process to filter comment + leadingComments = ts.getLeadingCommentRanges(text, node.pos); + } + if (leadingComments) { + var detachedComments = []; + var lastComment = void 0; + for (var _i = 0, leadingComments_1 = leadingComments; _i < leadingComments_1.length; _i++) { + var comment = leadingComments_1[_i]; + if (lastComment) { + var lastCommentLine = getLineOfLocalPositionFromLineMap(lineMap, lastComment.end); + var commentLine = getLineOfLocalPositionFromLineMap(lineMap, comment.pos); + if (commentLine >= lastCommentLine + 2) { + // There was a blank line between the last comment and this comment. This + // comment is not part of the copyright comments. Return what we have so + // far. + break; + } + } + detachedComments.push(comment); + lastComment = comment; + } + if (detachedComments.length) { + // All comments look like they could have been part of the copyright header. Make + // sure there is at least one blank line between it and the node. If not, it's not + // a copyright header. + var lastCommentLine = getLineOfLocalPositionFromLineMap(lineMap, ts.last(detachedComments).end); + var nodeLine = getLineOfLocalPositionFromLineMap(lineMap, ts.skipTrivia(text, node.pos)); + if (nodeLine >= lastCommentLine + 2) { + // Valid detachedComments + emitNewLineBeforeLeadingComments(lineMap, writer, node, leadingComments); + emitComments(text, lineMap, writer, detachedComments, /*leadingSeparator*/ false, /*trailingSeparator*/ true, newLine, writeComment); + currentDetachedCommentInfo = { nodePos: node.pos, detachedCommentEndPos: ts.last(detachedComments).end }; + } + } + } + return currentDetachedCommentInfo; + function isPinnedCommentLocal(comment) { + return isPinnedComment(text, comment.pos); + } + } + ts.emitDetachedComments = emitDetachedComments; + function writeCommentRange(text, lineMap, writer, commentPos, commentEnd, newLine) { + if (text.charCodeAt(commentPos + 1) === 42 /* asterisk */) { + var firstCommentLineAndCharacter = ts.computeLineAndCharacterOfPosition(lineMap, commentPos); + var lineCount = lineMap.length; + var firstCommentLineIndent = void 0; + for (var pos = commentPos, currentLine = firstCommentLineAndCharacter.line; pos < commentEnd; currentLine++) { + var nextLineStart = (currentLine + 1) === lineCount + ? text.length + 1 + : lineMap[currentLine + 1]; + if (pos !== commentPos) { + // If we are not emitting first line, we need to write the spaces to adjust the alignment + if (firstCommentLineIndent === undefined) { + firstCommentLineIndent = calculateIndent(text, lineMap[firstCommentLineAndCharacter.line], commentPos); + } + // These are number of spaces writer is going to write at current indent + var currentWriterIndentSpacing = writer.getIndent() * getIndentSize(); + // Number of spaces we want to be writing + // eg: Assume writer indent + // module m { + // /* starts at character 9 this is line 1 + // * starts at character pos 4 line --1 = 8 - 8 + 3 + // More left indented comment */ --2 = 8 - 8 + 2 + // class c { } + // } + // module m { + // /* this is line 1 -- Assume current writer indent 8 + // * line --3 = 8 - 4 + 5 + // More right indented comment */ --4 = 8 - 4 + 11 + // class c { } + // } + var spacesToEmit = currentWriterIndentSpacing - firstCommentLineIndent + calculateIndent(text, pos, nextLineStart); + if (spacesToEmit > 0) { + var numberOfSingleSpacesToEmit = spacesToEmit % getIndentSize(); + var indentSizeSpaceString = getIndentString((spacesToEmit - numberOfSingleSpacesToEmit) / getIndentSize()); + // Write indent size string ( in eg 1: = "", 2: "" , 3: string with 8 spaces 4: string with 12 spaces + writer.rawWrite(indentSizeSpaceString); + // Emit the single spaces (in eg: 1: 3 spaces, 2: 2 spaces, 3: 1 space, 4: 3 spaces) + while (numberOfSingleSpacesToEmit) { + writer.rawWrite(" "); + numberOfSingleSpacesToEmit--; + } + } + else { + // No spaces to emit write empty string + writer.rawWrite(""); + } + } + // Write the comment line text + writeTrimmedCurrentLine(text, commentEnd, writer, newLine, pos, nextLineStart); + pos = nextLineStart; + } + } + else { + // Single line comment of style //.... + writer.writeComment(text.substring(commentPos, commentEnd)); + } + } + ts.writeCommentRange = writeCommentRange; + function writeTrimmedCurrentLine(text, commentEnd, writer, newLine, pos, nextLineStart) { + var end = Math.min(commentEnd, nextLineStart - 1); + var currentLineText = text.substring(pos, end).replace(/^\s+|\s+$/g, ""); + if (currentLineText) { + // trimmed forward and ending spaces text + writer.writeComment(currentLineText); + if (end !== commentEnd) { + writer.writeLine(); + } + } + else { + // Empty string - make sure we write empty line + writer.rawWrite(newLine); + } + } + function calculateIndent(text, pos, end) { + var currentLineIndent = 0; + for (; pos < end && ts.isWhiteSpaceSingleLine(text.charCodeAt(pos)); pos++) { + if (text.charCodeAt(pos) === 9 /* tab */) { + // Tabs = TabSize = indent size and go to next tabStop + currentLineIndent += getIndentSize() - (currentLineIndent % getIndentSize()); + } + else { + // Single space + currentLineIndent++; + } + } + return currentLineIndent; + } + function hasModifiers(node) { + return getModifierFlags(node) !== 0 /* None */; + } + ts.hasModifiers = hasModifiers; + function hasModifier(node, flags) { + return !!getSelectedModifierFlags(node, flags); + } + ts.hasModifier = hasModifier; + function hasStaticModifier(node) { + return hasModifier(node, 32 /* Static */); + } + ts.hasStaticModifier = hasStaticModifier; + function hasReadonlyModifier(node) { + return hasModifier(node, 64 /* Readonly */); + } + ts.hasReadonlyModifier = hasReadonlyModifier; + function getSelectedModifierFlags(node, flags) { + return getModifierFlags(node) & flags; + } + ts.getSelectedModifierFlags = getSelectedModifierFlags; + function getModifierFlags(node) { + if (node.modifierFlagsCache & 536870912 /* HasComputedFlags */) { + return node.modifierFlagsCache & ~536870912 /* HasComputedFlags */; + } + var flags = getModifierFlagsNoCache(node); + node.modifierFlagsCache = flags | 536870912 /* HasComputedFlags */; + return flags; + } + ts.getModifierFlags = getModifierFlags; + function getModifierFlagsNoCache(node) { + var flags = 0 /* None */; + if (node.modifiers) { + for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) { + var modifier = _a[_i]; + flags |= modifierToFlag(modifier.kind); + } + } + if (node.flags & 4 /* NestedNamespace */ || (node.kind === 72 /* Identifier */ && node.isInJSDocNamespace)) { + flags |= 1 /* Export */; + } + return flags; + } + ts.getModifierFlagsNoCache = getModifierFlagsNoCache; + function modifierToFlag(token) { + switch (token) { + case 116 /* StaticKeyword */: return 32 /* Static */; + case 115 /* PublicKeyword */: return 4 /* Public */; + case 114 /* ProtectedKeyword */: return 16 /* Protected */; + case 113 /* PrivateKeyword */: return 8 /* Private */; + case 118 /* AbstractKeyword */: return 128 /* Abstract */; + case 85 /* ExportKeyword */: return 1 /* Export */; + case 125 /* DeclareKeyword */: return 2 /* Ambient */; + case 77 /* ConstKeyword */: return 2048 /* Const */; + case 80 /* DefaultKeyword */: return 512 /* Default */; + case 121 /* AsyncKeyword */: return 256 /* Async */; + case 133 /* ReadonlyKeyword */: return 64 /* Readonly */; + } + return 0 /* None */; + } + ts.modifierToFlag = modifierToFlag; + function isLogicalOperator(token) { + return token === 55 /* BarBarToken */ + || token === 54 /* AmpersandAmpersandToken */ + || token === 52 /* ExclamationToken */; + } + ts.isLogicalOperator = isLogicalOperator; + function isAssignmentOperator(token) { + return token >= 59 /* FirstAssignment */ && token <= 71 /* LastAssignment */; + } + ts.isAssignmentOperator = isAssignmentOperator; + /** Get `C` given `N` if `N` is in the position `class C extends N` where `N` is an ExpressionWithTypeArguments. */ + function tryGetClassExtendingExpressionWithTypeArguments(node) { + var cls = tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node); + return cls && !cls.isImplements ? cls.class : undefined; + } + ts.tryGetClassExtendingExpressionWithTypeArguments = tryGetClassExtendingExpressionWithTypeArguments; + function tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node) { + return ts.isExpressionWithTypeArguments(node) + && ts.isHeritageClause(node.parent) + && ts.isClassLike(node.parent.parent) + ? { class: node.parent.parent, isImplements: node.parent.token === 109 /* ImplementsKeyword */ } + : undefined; + } + ts.tryGetClassImplementingOrExtendingExpressionWithTypeArguments = tryGetClassImplementingOrExtendingExpressionWithTypeArguments; + function isAssignmentExpression(node, excludeCompoundAssignment) { + return ts.isBinaryExpression(node) + && (excludeCompoundAssignment + ? node.operatorToken.kind === 59 /* EqualsToken */ + : isAssignmentOperator(node.operatorToken.kind)) + && ts.isLeftHandSideExpression(node.left); + } + ts.isAssignmentExpression = isAssignmentExpression; + function isDestructuringAssignment(node) { + if (isAssignmentExpression(node, /*excludeCompoundAssignment*/ true)) { + var kind = node.left.kind; + return kind === 188 /* ObjectLiteralExpression */ + || kind === 187 /* ArrayLiteralExpression */; + } + return false; + } + ts.isDestructuringAssignment = isDestructuringAssignment; + function isExpressionWithTypeArgumentsInClassExtendsClause(node) { + return tryGetClassExtendingExpressionWithTypeArguments(node) !== undefined; + } + ts.isExpressionWithTypeArgumentsInClassExtendsClause = isExpressionWithTypeArgumentsInClassExtendsClause; + function isEntityNameExpression(node) { + return node.kind === 72 /* Identifier */ || isPropertyAccessEntityNameExpression(node); + } + ts.isEntityNameExpression = isEntityNameExpression; + function isPropertyAccessEntityNameExpression(node) { + return ts.isPropertyAccessExpression(node) && isEntityNameExpression(node.expression); + } + ts.isPropertyAccessEntityNameExpression = isPropertyAccessEntityNameExpression; + function isPrototypeAccess(node) { + return ts.isPropertyAccessExpression(node) && node.name.escapedText === "prototype"; + } + ts.isPrototypeAccess = isPrototypeAccess; + function isRightSideOfQualifiedNameOrPropertyAccess(node) { + return (node.parent.kind === 148 /* QualifiedName */ && node.parent.right === node) || + (node.parent.kind === 189 /* PropertyAccessExpression */ && node.parent.name === node); + } + ts.isRightSideOfQualifiedNameOrPropertyAccess = isRightSideOfQualifiedNameOrPropertyAccess; + function isEmptyObjectLiteral(expression) { + return expression.kind === 188 /* ObjectLiteralExpression */ && + expression.properties.length === 0; + } + ts.isEmptyObjectLiteral = isEmptyObjectLiteral; + function isEmptyArrayLiteral(expression) { + return expression.kind === 187 /* ArrayLiteralExpression */ && + expression.elements.length === 0; + } + ts.isEmptyArrayLiteral = isEmptyArrayLiteral; + function getLocalSymbolForExportDefault(symbol) { + return isExportDefaultSymbol(symbol) ? symbol.declarations[0].localSymbol : undefined; + } + ts.getLocalSymbolForExportDefault = getLocalSymbolForExportDefault; + function isExportDefaultSymbol(symbol) { + return symbol && ts.length(symbol.declarations) > 0 && hasModifier(symbol.declarations[0], 512 /* Default */); + } + /** Return ".ts", ".d.ts", or ".tsx", if that is the extension. */ + function tryExtractTSExtension(fileName) { + return ts.find(ts.supportedTSExtensionsForExtractExtension, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + } + ts.tryExtractTSExtension = tryExtractTSExtension; + /** + * Replace each instance of non-ascii characters by one, two, three, or four escape sequences + * representing the UTF-8 encoding of the character, and return the expanded char code list. + */ + function getExpandedCharCodes(input) { + var output = []; + var length = input.length; + for (var i = 0; i < length; i++) { + var charCode = input.charCodeAt(i); + // handle utf8 + if (charCode < 0x80) { + output.push(charCode); + } + else if (charCode < 0x800) { + output.push((charCode >> 6) | 192); + output.push((charCode & 63) | 128); + } + else if (charCode < 0x10000) { + output.push((charCode >> 12) | 224); + output.push(((charCode >> 6) & 63) | 128); + output.push((charCode & 63) | 128); + } + else if (charCode < 0x20000) { + output.push((charCode >> 18) | 240); + output.push(((charCode >> 12) & 63) | 128); + output.push(((charCode >> 6) & 63) | 128); + output.push((charCode & 63) | 128); + } + else { + ts.Debug.assert(false, "Unexpected code point"); + } + } + return output; + } + var base64Digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; + /** + * Converts a string to a base-64 encoded ASCII string. + */ + function convertToBase64(input) { + var result = ""; + var charCodes = getExpandedCharCodes(input); + var i = 0; + var length = charCodes.length; + var byte1, byte2, byte3, byte4; + while (i < length) { + // Convert every 6-bits in the input 3 character points + // into a base64 digit + byte1 = charCodes[i] >> 2; + byte2 = (charCodes[i] & 3) << 4 | charCodes[i + 1] >> 4; + byte3 = (charCodes[i + 1] & 15) << 2 | charCodes[i + 2] >> 6; + byte4 = charCodes[i + 2] & 63; + // We are out of characters in the input, set the extra + // digits to 64 (padding character). + if (i + 1 >= length) { + byte3 = byte4 = 64; + } + else if (i + 2 >= length) { + byte4 = 64; + } + // Write to the output + result += base64Digits.charAt(byte1) + base64Digits.charAt(byte2) + base64Digits.charAt(byte3) + base64Digits.charAt(byte4); + i += 3; + } + return result; + } + ts.convertToBase64 = convertToBase64; + function getStringFromExpandedCharCodes(codes) { + var output = ""; + var i = 0; + var length = codes.length; + while (i < length) { + var charCode = codes[i]; + if (charCode < 0x80) { + output += String.fromCharCode(charCode); + i++; + } + else if ((charCode & 192) === 192) { + var value = charCode & 63; + i++; + var nextCode = codes[i]; + while ((nextCode & 192) === 128) { + value = (value << 6) | (nextCode & 63); + i++; + nextCode = codes[i]; + } + // `value` may be greater than 10FFFF (the maximum unicode codepoint) - JS will just make this into an invalid character for us + output += String.fromCharCode(value); + } + else { + // We don't want to kill the process when decoding fails (due to a following char byte not + // following a leading char), so we just print the (bad) value + output += String.fromCharCode(charCode); + i++; + } + } + return output; + } + function base64encode(host, input) { + if (host && host.base64encode) { + return host.base64encode(input); + } + return convertToBase64(input); + } + ts.base64encode = base64encode; + function base64decode(host, input) { + if (host && host.base64decode) { + return host.base64decode(input); + } + var length = input.length; + var expandedCharCodes = []; + var i = 0; + while (i < length) { + // Stop decoding once padding characters are present + if (input.charCodeAt(i) === base64Digits.charCodeAt(64)) { + break; + } + // convert 4 input digits into three characters, ignoring padding characters at the end + var ch1 = base64Digits.indexOf(input[i]); + var ch2 = base64Digits.indexOf(input[i + 1]); + var ch3 = base64Digits.indexOf(input[i + 2]); + var ch4 = base64Digits.indexOf(input[i + 3]); + var code1 = ((ch1 & 63) << 2) | ((ch2 >> 4) & 3); + var code2 = ((ch2 & 15) << 4) | ((ch3 >> 2) & 15); + var code3 = ((ch3 & 3) << 6) | (ch4 & 63); + if (code2 === 0 && ch3 !== 0) { // code2 decoded to zero, but ch3 was padding - elide code2 and code3 + expandedCharCodes.push(code1); + } + else if (code3 === 0 && ch4 !== 0) { // code3 decoded to zero, but ch4 was padding, elide code3 + expandedCharCodes.push(code1, code2); + } + else { + expandedCharCodes.push(code1, code2, code3); + } + i += 4; + } + return getStringFromExpandedCharCodes(expandedCharCodes); + } + ts.base64decode = base64decode; + function readJson(path, host) { + try { + var jsonText = host.readFile(path); + if (!jsonText) + return {}; + var result = ts.parseConfigFileTextToJson(path, jsonText); + if (result.error) { + return {}; + } + return result.config; + } + catch (e) { + // gracefully handle if readFile fails or returns not JSON + return {}; + } + } + ts.readJson = readJson; + function directoryProbablyExists(directoryName, host) { + // if host does not support 'directoryExists' assume that directory will exist + return !host.directoryExists || host.directoryExists(directoryName); + } + ts.directoryProbablyExists = directoryProbablyExists; + var carriageReturnLineFeed = "\r\n"; + var lineFeed = "\n"; + function getNewLineCharacter(options, getNewLine) { + switch (options.newLine) { + case 0 /* CarriageReturnLineFeed */: + return carriageReturnLineFeed; + case 1 /* LineFeed */: + return lineFeed; + } + return getNewLine ? getNewLine() : ts.sys ? ts.sys.newLine : carriageReturnLineFeed; + } + ts.getNewLineCharacter = getNewLineCharacter; + /** + * Formats an enum value as a string for debugging and debug assertions. + */ + function formatEnum(value, enumObject, isFlags) { + if (value === void 0) { value = 0; } + var members = getEnumMembers(enumObject); + if (value === 0) { + return members.length > 0 && members[0][0] === 0 ? members[0][1] : "0"; + } + if (isFlags) { + var result = ""; + var remainingFlags = value; + for (var i = members.length - 1; i >= 0 && remainingFlags !== 0; i--) { + var _a = members[i], enumValue = _a[0], enumName = _a[1]; + if (enumValue !== 0 && (remainingFlags & enumValue) === enumValue) { + remainingFlags &= ~enumValue; + result = "" + enumName + (result ? ", " : "") + result; + } + } + if (remainingFlags === 0) { + return result; + } + } + else { + for (var _i = 0, members_1 = members; _i < members_1.length; _i++) { + var _b = members_1[_i], enumValue = _b[0], enumName = _b[1]; + if (enumValue === value) { + return enumName; + } + } + } + return value.toString(); + } + function getEnumMembers(enumObject) { + var result = []; + for (var name in enumObject) { + var value = enumObject[name]; + if (typeof value === "number") { + result.push([value, name]); + } + } + return ts.stableSort(result, function (x, y) { return ts.compareValues(x[0], y[0]); }); + } + function formatSyntaxKind(kind) { + return formatEnum(kind, ts.SyntaxKind, /*isFlags*/ false); + } + ts.formatSyntaxKind = formatSyntaxKind; + function formatModifierFlags(flags) { + return formatEnum(flags, ts.ModifierFlags, /*isFlags*/ true); + } + ts.formatModifierFlags = formatModifierFlags; + function formatTransformFlags(flags) { + return formatEnum(flags, ts.TransformFlags, /*isFlags*/ true); + } + ts.formatTransformFlags = formatTransformFlags; + function formatEmitFlags(flags) { + return formatEnum(flags, ts.EmitFlags, /*isFlags*/ true); + } + ts.formatEmitFlags = formatEmitFlags; + function formatSymbolFlags(flags) { + return formatEnum(flags, ts.SymbolFlags, /*isFlags*/ true); + } + ts.formatSymbolFlags = formatSymbolFlags; + function formatTypeFlags(flags) { + return formatEnum(flags, ts.TypeFlags, /*isFlags*/ true); + } + ts.formatTypeFlags = formatTypeFlags; + function formatObjectFlags(flags) { + return formatEnum(flags, ts.ObjectFlags, /*isFlags*/ true); + } + ts.formatObjectFlags = formatObjectFlags; + /** + * Creates a new TextRange from the provided pos and end. + * + * @param pos The start position. + * @param end The end position. + */ + function createRange(pos, end) { + if (end === void 0) { end = pos; } + ts.Debug.assert(end >= pos || end === -1); + return { pos: pos, end: end }; + } + ts.createRange = createRange; + /** + * Creates a new TextRange from a provided range with a new end position. + * + * @param range A TextRange. + * @param end The new end position. + */ + function moveRangeEnd(range, end) { + return createRange(range.pos, end); + } + ts.moveRangeEnd = moveRangeEnd; + /** + * Creates a new TextRange from a provided range with a new start position. + * + * @param range A TextRange. + * @param pos The new Start position. + */ + function moveRangePos(range, pos) { + return createRange(pos, range.end); + } + ts.moveRangePos = moveRangePos; + /** + * Moves the start position of a range past any decorators. + */ + function moveRangePastDecorators(node) { + return node.decorators && node.decorators.length > 0 + ? moveRangePos(node, node.decorators.end) + : node; + } + ts.moveRangePastDecorators = moveRangePastDecorators; + /** + * Moves the start position of a range past any decorators or modifiers. + */ + function moveRangePastModifiers(node) { + return node.modifiers && node.modifiers.length > 0 + ? moveRangePos(node, node.modifiers.end) + : moveRangePastDecorators(node); + } + ts.moveRangePastModifiers = moveRangePastModifiers; + /** + * Determines whether a TextRange has the same start and end positions. + * + * @param range A TextRange. + */ + function isCollapsedRange(range) { + return range.pos === range.end; + } + ts.isCollapsedRange = isCollapsedRange; + /** + * Creates a new TextRange for a token at the provides start position. + * + * @param pos The start position. + * @param token The token. + */ + function createTokenRange(pos, token) { + return createRange(pos, pos + ts.tokenToString(token).length); + } + ts.createTokenRange = createTokenRange; + function rangeIsOnSingleLine(range, sourceFile) { + return rangeStartIsOnSameLineAsRangeEnd(range, range, sourceFile); + } + ts.rangeIsOnSingleLine = rangeIsOnSingleLine; + function rangeStartPositionsAreOnSameLine(range1, range2, sourceFile) { + return positionsAreOnSameLine(getStartPositionOfRange(range1, sourceFile), getStartPositionOfRange(range2, sourceFile), sourceFile); + } + ts.rangeStartPositionsAreOnSameLine = rangeStartPositionsAreOnSameLine; + function rangeEndPositionsAreOnSameLine(range1, range2, sourceFile) { + return positionsAreOnSameLine(range1.end, range2.end, sourceFile); + } + ts.rangeEndPositionsAreOnSameLine = rangeEndPositionsAreOnSameLine; + function rangeStartIsOnSameLineAsRangeEnd(range1, range2, sourceFile) { + return positionsAreOnSameLine(getStartPositionOfRange(range1, sourceFile), range2.end, sourceFile); + } + ts.rangeStartIsOnSameLineAsRangeEnd = rangeStartIsOnSameLineAsRangeEnd; + function rangeEndIsOnSameLineAsRangeStart(range1, range2, sourceFile) { + return positionsAreOnSameLine(range1.end, getStartPositionOfRange(range2, sourceFile), sourceFile); + } + ts.rangeEndIsOnSameLineAsRangeStart = rangeEndIsOnSameLineAsRangeStart; + function positionsAreOnSameLine(pos1, pos2, sourceFile) { + return pos1 === pos2 || + getLineOfLocalPosition(sourceFile, pos1) === getLineOfLocalPosition(sourceFile, pos2); + } + ts.positionsAreOnSameLine = positionsAreOnSameLine; + function getStartPositionOfRange(range, sourceFile) { + return ts.positionIsSynthesized(range.pos) ? -1 : ts.skipTrivia(sourceFile.text, range.pos); + } + ts.getStartPositionOfRange = getStartPositionOfRange; + /** + * Determines whether a name was originally the declaration name of an enum or namespace + * declaration. + */ + function isDeclarationNameOfEnumOrNamespace(node) { + var parseNode = ts.getParseTreeNode(node); + if (parseNode) { + switch (parseNode.parent.kind) { + case 243 /* EnumDeclaration */: + case 244 /* ModuleDeclaration */: + return parseNode === parseNode.parent.name; + } + } + return false; + } + ts.isDeclarationNameOfEnumOrNamespace = isDeclarationNameOfEnumOrNamespace; + function getInitializedVariables(node) { + return ts.filter(node.declarations, isInitializedVariable); + } + ts.getInitializedVariables = getInitializedVariables; + function isInitializedVariable(node) { + return node.initializer !== undefined; + } + function isWatchSet(options) { + // Firefox has Object.prototype.watch + return options.watch && options.hasOwnProperty("watch"); + } + ts.isWatchSet = isWatchSet; + function closeFileWatcher(watcher) { + watcher.close(); + } + ts.closeFileWatcher = closeFileWatcher; + function getCheckFlags(symbol) { + return symbol.flags & 33554432 /* Transient */ ? symbol.checkFlags : 0; + } + ts.getCheckFlags = getCheckFlags; + function getDeclarationModifierFlagsFromSymbol(s) { + if (s.valueDeclaration) { + var flags = ts.getCombinedModifierFlags(s.valueDeclaration); + return s.parent && s.parent.flags & 32 /* Class */ ? flags : flags & ~28 /* AccessibilityModifier */; + } + if (getCheckFlags(s) & 6 /* Synthetic */) { + var checkFlags = s.checkFlags; + var accessModifier = checkFlags & 256 /* ContainsPrivate */ ? 8 /* Private */ : + checkFlags & 64 /* ContainsPublic */ ? 4 /* Public */ : + 16 /* Protected */; + var staticModifier = checkFlags & 512 /* ContainsStatic */ ? 32 /* Static */ : 0; + return accessModifier | staticModifier; + } + if (s.flags & 4194304 /* Prototype */) { + return 4 /* Public */ | 32 /* Static */; + } + return 0; + } + ts.getDeclarationModifierFlagsFromSymbol = getDeclarationModifierFlagsFromSymbol; + function skipAlias(symbol, checker) { + return symbol.flags & 2097152 /* Alias */ ? checker.getAliasedSymbol(symbol) : symbol; + } + ts.skipAlias = skipAlias; + /** See comment on `declareModuleMember` in `binder.ts`. */ + function getCombinedLocalAndExportSymbolFlags(symbol) { + return symbol.exportSymbol ? symbol.exportSymbol.flags | symbol.flags : symbol.flags; + } + ts.getCombinedLocalAndExportSymbolFlags = getCombinedLocalAndExportSymbolFlags; + function isWriteOnlyAccess(node) { + return accessKind(node) === 1 /* Write */; + } + ts.isWriteOnlyAccess = isWriteOnlyAccess; + function isWriteAccess(node) { + return accessKind(node) !== 0 /* Read */; + } + ts.isWriteAccess = isWriteAccess; + var AccessKind; + (function (AccessKind) { + /** Only reads from a variable. */ + AccessKind[AccessKind["Read"] = 0] = "Read"; + /** Only writes to a variable without using the result. E.g.: `x++;`. */ + AccessKind[AccessKind["Write"] = 1] = "Write"; + /** Writes to a variable and uses the result as an expression. E.g.: `f(x++);`. */ + AccessKind[AccessKind["ReadWrite"] = 2] = "ReadWrite"; + })(AccessKind || (AccessKind = {})); + function accessKind(node) { + var parent = node.parent; + if (!parent) + return 0 /* Read */; + switch (parent.kind) { + case 195 /* ParenthesizedExpression */: + return accessKind(parent); + case 203 /* PostfixUnaryExpression */: + case 202 /* PrefixUnaryExpression */: + var operator = parent.operator; + return operator === 44 /* PlusPlusToken */ || operator === 45 /* MinusMinusToken */ ? writeOrReadWrite() : 0 /* Read */; + case 204 /* BinaryExpression */: + var _a = parent, left = _a.left, operatorToken = _a.operatorToken; + return left === node && isAssignmentOperator(operatorToken.kind) ? + operatorToken.kind === 59 /* EqualsToken */ ? 1 /* Write */ : writeOrReadWrite() + : 0 /* Read */; + case 189 /* PropertyAccessExpression */: + return parent.name !== node ? 0 /* Read */ : accessKind(parent); + case 275 /* PropertyAssignment */: { + var parentAccess = accessKind(parent.parent); + // In `({ x: varname }) = { x: 1 }`, the left `x` is a read, the right `x` is a write. + return node === parent.name ? reverseAccessKind(parentAccess) : parentAccess; + } + case 276 /* ShorthandPropertyAssignment */: + // Assume it's the local variable being accessed, since we don't check public properties for --noUnusedLocals. + return node === parent.objectAssignmentInitializer ? 0 /* Read */ : accessKind(parent.parent); + case 187 /* ArrayLiteralExpression */: + return accessKind(parent); + default: + return 0 /* Read */; + } + function writeOrReadWrite() { + // If grandparent is not an ExpressionStatement, this is used as an expression in addition to having a side effect. + return parent.parent && skipParenthesesUp(parent.parent).kind === 221 /* ExpressionStatement */ ? 1 /* Write */ : 2 /* ReadWrite */; + } + } + function reverseAccessKind(a) { + switch (a) { + case 0 /* Read */: + return 1 /* Write */; + case 1 /* Write */: + return 0 /* Read */; + case 2 /* ReadWrite */: + return 2 /* ReadWrite */; + default: + return ts.Debug.assertNever(a); + } + } + function compareDataObjects(dst, src) { + if (!dst || !src || Object.keys(dst).length !== Object.keys(src).length) { + return false; + } + for (var e in dst) { + if (typeof dst[e] === "object") { + if (!compareDataObjects(dst[e], src[e])) { + return false; + } + } + else if (typeof dst[e] !== "function") { + if (dst[e] !== src[e]) { + return false; + } + } + } + return true; + } + ts.compareDataObjects = compareDataObjects; + /** + * clears already present map by calling onDeleteExistingValue callback before deleting that key/value + */ + function clearMap(map, onDeleteValue) { + // Remove all + map.forEach(onDeleteValue); + map.clear(); + } + ts.clearMap = clearMap; + /** + * Mutates the map with newMap such that keys in map will be same as newMap. + */ + function mutateMap(map, newMap, options) { + var createNewValue = options.createNewValue, onDeleteValue = options.onDeleteValue, onExistingValue = options.onExistingValue; + // Needs update + map.forEach(function (existingValue, key) { + var valueInNewMap = newMap.get(key); + // Not present any more in new map, remove it + if (valueInNewMap === undefined) { + map.delete(key); + onDeleteValue(existingValue, key); + } + // If present notify about existing values + else if (onExistingValue) { + onExistingValue(existingValue, valueInNewMap, key); + } + }); + // Add new values that are not already present + newMap.forEach(function (valueInNewMap, key) { + if (!map.has(key)) { + // New values + map.set(key, createNewValue(key, valueInNewMap)); + } + }); + } + ts.mutateMap = mutateMap; + /** Calls `callback` on `directory` and every ancestor directory it has, returning the first defined result. */ + function forEachAncestorDirectory(directory, callback) { + while (true) { + var result = callback(directory); + if (result !== undefined) { + return result; + } + var parentPath = ts.getDirectoryPath(directory); + if (parentPath === directory) { + return undefined; + } + directory = parentPath; + } + } + ts.forEachAncestorDirectory = forEachAncestorDirectory; + // Return true if the given type is the constructor type for an abstract class + function isAbstractConstructorType(type) { + return !!(getObjectFlags(type) & 16 /* Anonymous */) && !!type.symbol && isAbstractConstructorSymbol(type.symbol); + } + ts.isAbstractConstructorType = isAbstractConstructorType; + function isAbstractConstructorSymbol(symbol) { + if (symbol.flags & 32 /* Class */) { + var declaration = getClassLikeDeclarationOfSymbol(symbol); + return !!declaration && hasModifier(declaration, 128 /* Abstract */); + } + return false; + } + ts.isAbstractConstructorSymbol = isAbstractConstructorSymbol; + function getClassLikeDeclarationOfSymbol(symbol) { + return ts.find(symbol.declarations, ts.isClassLike); + } + ts.getClassLikeDeclarationOfSymbol = getClassLikeDeclarationOfSymbol; + function getObjectFlags(type) { + return type.flags & 524288 /* Object */ ? type.objectFlags : 0; + } + ts.getObjectFlags = getObjectFlags; + function typeHasCallOrConstructSignatures(type, checker) { + return checker.getSignaturesOfType(type, 0 /* Call */).length !== 0 || checker.getSignaturesOfType(type, 1 /* Construct */).length !== 0; + } + ts.typeHasCallOrConstructSignatures = typeHasCallOrConstructSignatures; + function forSomeAncestorDirectory(directory, callback) { + return !!forEachAncestorDirectory(directory, function (d) { return callback(d) ? true : undefined; }); + } + ts.forSomeAncestorDirectory = forSomeAncestorDirectory; + function isUMDExportSymbol(symbol) { + return !!symbol && !!symbol.declarations && !!symbol.declarations[0] && ts.isNamespaceExportDeclaration(symbol.declarations[0]); + } + ts.isUMDExportSymbol = isUMDExportSymbol; + function showModuleSpecifier(_a) { + var moduleSpecifier = _a.moduleSpecifier; + return ts.isStringLiteral(moduleSpecifier) ? moduleSpecifier.text : getTextOfNode(moduleSpecifier); + } + ts.showModuleSpecifier = showModuleSpecifier; + function getLastChild(node) { + var lastChild; + ts.forEachChild(node, function (child) { + if (nodeIsPresent(child)) + lastChild = child; + }, function (children) { + // As an optimization, jump straight to the end of the list. + for (var i = children.length - 1; i >= 0; i--) { + if (nodeIsPresent(children[i])) { + lastChild = children[i]; + break; + } + } + }); + return lastChild; + } + ts.getLastChild = getLastChild; + function addToSeen(seen, key, value) { + if (value === void 0) { value = true; } + key = String(key); + if (seen.has(key)) { + return false; + } + seen.set(key, value); + return true; + } + ts.addToSeen = addToSeen; + function isObjectTypeDeclaration(node) { + return ts.isClassLike(node) || ts.isInterfaceDeclaration(node) || ts.isTypeLiteralNode(node); + } + ts.isObjectTypeDeclaration = isObjectTypeDeclaration; + function isTypeNodeKind(kind) { + return (kind >= 163 /* FirstTypeNode */ && kind <= 183 /* LastTypeNode */) + || kind === 120 /* AnyKeyword */ + || kind === 143 /* UnknownKeyword */ + || kind === 135 /* NumberKeyword */ + || kind === 146 /* BigIntKeyword */ + || kind === 136 /* ObjectKeyword */ + || kind === 123 /* BooleanKeyword */ + || kind === 138 /* StringKeyword */ + || kind === 139 /* SymbolKeyword */ + || kind === 100 /* ThisKeyword */ + || kind === 106 /* VoidKeyword */ + || kind === 141 /* UndefinedKeyword */ + || kind === 96 /* NullKeyword */ + || kind === 132 /* NeverKeyword */ + || kind === 211 /* ExpressionWithTypeArguments */ + || kind === 284 /* JSDocAllType */ + || kind === 285 /* JSDocUnknownType */ + || kind === 286 /* JSDocNullableType */ + || kind === 287 /* JSDocNonNullableType */ + || kind === 288 /* JSDocOptionalType */ + || kind === 289 /* JSDocFunctionType */ + || kind === 290 /* JSDocVariadicType */; + } + ts.isTypeNodeKind = isTypeNodeKind; +})(ts || (ts = {})); +(function (ts) { + function getDefaultLibFileName(options) { + switch (options.target) { + case 6 /* ESNext */: + return "lib.esnext.full.d.ts"; + case 5 /* ES2018 */: + return "lib.es2018.full.d.ts"; + case 4 /* ES2017 */: + return "lib.es2017.full.d.ts"; + case 3 /* ES2016 */: + return "lib.es2016.full.d.ts"; + case 2 /* ES2015 */: + return "lib.es6.d.ts"; // We don't use lib.es2015.full.d.ts due to breaking change. + default: + return "lib.d.ts"; + } + } + ts.getDefaultLibFileName = getDefaultLibFileName; + function textSpanEnd(span) { + return span.start + span.length; + } + ts.textSpanEnd = textSpanEnd; + function textSpanIsEmpty(span) { + return span.length === 0; + } + ts.textSpanIsEmpty = textSpanIsEmpty; + function textSpanContainsPosition(span, position) { + return position >= span.start && position < textSpanEnd(span); + } + ts.textSpanContainsPosition = textSpanContainsPosition; + /* @internal */ + function textRangeContainsPositionInclusive(span, position) { + return position >= span.pos && position <= span.end; + } + ts.textRangeContainsPositionInclusive = textRangeContainsPositionInclusive; + // Returns true if 'span' contains 'other'. + function textSpanContainsTextSpan(span, other) { + return other.start >= span.start && textSpanEnd(other) <= textSpanEnd(span); + } + ts.textSpanContainsTextSpan = textSpanContainsTextSpan; + function textSpanOverlapsWith(span, other) { + return textSpanOverlap(span, other) !== undefined; + } + ts.textSpanOverlapsWith = textSpanOverlapsWith; + function textSpanOverlap(span1, span2) { + var overlap = textSpanIntersection(span1, span2); + return overlap && overlap.length === 0 ? undefined : overlap; + } + ts.textSpanOverlap = textSpanOverlap; + function textSpanIntersectsWithTextSpan(span, other) { + return decodedTextSpanIntersectsWith(span.start, span.length, other.start, other.length); + } + ts.textSpanIntersectsWithTextSpan = textSpanIntersectsWithTextSpan; + function textSpanIntersectsWith(span, start, length) { + return decodedTextSpanIntersectsWith(span.start, span.length, start, length); + } + ts.textSpanIntersectsWith = textSpanIntersectsWith; + function decodedTextSpanIntersectsWith(start1, length1, start2, length2) { + var end1 = start1 + length1; + var end2 = start2 + length2; + return start2 <= end1 && end2 >= start1; + } + ts.decodedTextSpanIntersectsWith = decodedTextSpanIntersectsWith; + function textSpanIntersectsWithPosition(span, position) { + return position <= textSpanEnd(span) && position >= span.start; + } + ts.textSpanIntersectsWithPosition = textSpanIntersectsWithPosition; + function textSpanIntersection(span1, span2) { + var start = Math.max(span1.start, span2.start); + var end = Math.min(textSpanEnd(span1), textSpanEnd(span2)); + return start <= end ? createTextSpanFromBounds(start, end) : undefined; + } + ts.textSpanIntersection = textSpanIntersection; + function createTextSpan(start, length) { + if (start < 0) { + throw new Error("start < 0"); + } + if (length < 0) { + throw new Error("length < 0"); + } + return { start: start, length: length }; + } + ts.createTextSpan = createTextSpan; + function createTextSpanFromBounds(start, end) { + return createTextSpan(start, end - start); + } + ts.createTextSpanFromBounds = createTextSpanFromBounds; + function textChangeRangeNewSpan(range) { + return createTextSpan(range.span.start, range.newLength); + } + ts.textChangeRangeNewSpan = textChangeRangeNewSpan; + function textChangeRangeIsUnchanged(range) { + return textSpanIsEmpty(range.span) && range.newLength === 0; + } + ts.textChangeRangeIsUnchanged = textChangeRangeIsUnchanged; + function createTextChangeRange(span, newLength) { + if (newLength < 0) { + throw new Error("newLength < 0"); + } + return { span: span, newLength: newLength }; + } + ts.createTextChangeRange = createTextChangeRange; + ts.unchangedTextChangeRange = createTextChangeRange(createTextSpan(0, 0), 0); + /** + * Called to merge all the changes that occurred across several versions of a script snapshot + * into a single change. i.e. if a user keeps making successive edits to a script we will + * have a text change from V1 to V2, V2 to V3, ..., Vn. + * + * This function will then merge those changes into a single change range valid between V1 and + * Vn. + */ + function collapseTextChangeRangesAcrossMultipleVersions(changes) { + if (changes.length === 0) { + return ts.unchangedTextChangeRange; + } + if (changes.length === 1) { + return changes[0]; + } + // We change from talking about { { oldStart, oldLength }, newLength } to { oldStart, oldEnd, newEnd } + // as it makes things much easier to reason about. + var change0 = changes[0]; + var oldStartN = change0.span.start; + var oldEndN = textSpanEnd(change0.span); + var newEndN = oldStartN + change0.newLength; + for (var i = 1; i < changes.length; i++) { + var nextChange = changes[i]; + // Consider the following case: + // i.e. two edits. The first represents the text change range { { 10, 50 }, 30 }. i.e. The span starting + // at 10, with length 50 is reduced to length 30. The second represents the text change range { { 30, 30 }, 40 }. + // i.e. the span starting at 30 with length 30 is increased to length 40. + // + // 0 10 20 30 40 50 60 70 80 90 100 + // ------------------------------------------------------------------------------------------------------- + // | / + // | /---- + // T1 | /---- + // | /---- + // | /---- + // ------------------------------------------------------------------------------------------------------- + // | \ + // | \ + // T2 | \ + // | \ + // | \ + // ------------------------------------------------------------------------------------------------------- + // + // Merging these turns out to not be too difficult. First, determining the new start of the change is trivial + // it's just the min of the old and new starts. i.e.: + // + // 0 10 20 30 40 50 60 70 80 90 100 + // ------------------------------------------------------------*------------------------------------------ + // | / + // | /---- + // T1 | /---- + // | /---- + // | /---- + // ----------------------------------------$-------------------$------------------------------------------ + // . | \ + // . | \ + // T2 . | \ + // . | \ + // . | \ + // ----------------------------------------------------------------------*-------------------------------- + // + // (Note the dots represent the newly inferred start. + // Determining the new and old end is also pretty simple. Basically it boils down to paying attention to the + // absolute positions at the asterisks, and the relative change between the dollar signs. Basically, we see + // which if the two $'s precedes the other, and we move that one forward until they line up. in this case that + // means: + // + // 0 10 20 30 40 50 60 70 80 90 100 + // --------------------------------------------------------------------------------*---------------------- + // | / + // | /---- + // T1 | /---- + // | /---- + // | /---- + // ------------------------------------------------------------$------------------------------------------ + // . | \ + // . | \ + // T2 . | \ + // . | \ + // . | \ + // ----------------------------------------------------------------------*-------------------------------- + // + // In other words (in this case), we're recognizing that the second edit happened after where the first edit + // ended with a delta of 20 characters (60 - 40). Thus, if we go back in time to where the first edit started + // that's the same as if we started at char 80 instead of 60. + // + // As it so happens, the same logic applies if the second edit precedes the first edit. In that case rather + // than pushing the first edit forward to match the second, we'll push the second edit forward to match the + // first. + // + // In this case that means we have { oldStart: 10, oldEnd: 80, newEnd: 70 } or, in TextChangeRange + // semantics: { { start: 10, length: 70 }, newLength: 60 } + // + // The math then works out as follows. + // If we have { oldStart1, oldEnd1, newEnd1 } and { oldStart2, oldEnd2, newEnd2 } then we can compute the + // final result like so: + // + // { + // oldStart3: Min(oldStart1, oldStart2), + // oldEnd3: Max(oldEnd1, oldEnd1 + (oldEnd2 - newEnd1)), + // newEnd3: Max(newEnd2, newEnd2 + (newEnd1 - oldEnd2)) + // } + var oldStart1 = oldStartN; + var oldEnd1 = oldEndN; + var newEnd1 = newEndN; + var oldStart2 = nextChange.span.start; + var oldEnd2 = textSpanEnd(nextChange.span); + var newEnd2 = oldStart2 + nextChange.newLength; + oldStartN = Math.min(oldStart1, oldStart2); + oldEndN = Math.max(oldEnd1, oldEnd1 + (oldEnd2 - newEnd1)); + newEndN = Math.max(newEnd2, newEnd2 + (newEnd1 - oldEnd2)); + } + return createTextChangeRange(createTextSpanFromBounds(oldStartN, oldEndN), /*newLength*/ newEndN - oldStartN); + } + ts.collapseTextChangeRangesAcrossMultipleVersions = collapseTextChangeRangesAcrossMultipleVersions; + function getTypeParameterOwner(d) { + if (d && d.kind === 150 /* TypeParameter */) { + for (var current = d; current; current = current.parent) { + if (ts.isFunctionLike(current) || ts.isClassLike(current) || current.kind === 241 /* InterfaceDeclaration */) { + return current; + } + } + } + } + ts.getTypeParameterOwner = getTypeParameterOwner; + function isParameterPropertyDeclaration(node) { + return ts.hasModifier(node, 92 /* ParameterPropertyModifier */) && node.parent.kind === 157 /* Constructor */; + } + ts.isParameterPropertyDeclaration = isParameterPropertyDeclaration; + function isEmptyBindingPattern(node) { + if (ts.isBindingPattern(node)) { + return ts.every(node.elements, isEmptyBindingElement); + } + return false; + } + ts.isEmptyBindingPattern = isEmptyBindingPattern; + function isEmptyBindingElement(node) { + if (ts.isOmittedExpression(node)) { + return true; + } + return isEmptyBindingPattern(node.name); + } + ts.isEmptyBindingElement = isEmptyBindingElement; + function walkUpBindingElementsAndPatterns(binding) { + var node = binding.parent; + while (ts.isBindingElement(node.parent)) { + node = node.parent.parent; + } + return node.parent; + } + ts.walkUpBindingElementsAndPatterns = walkUpBindingElementsAndPatterns; + function getCombinedFlags(node, getFlags) { + if (ts.isBindingElement(node)) { + node = walkUpBindingElementsAndPatterns(node); + } + var flags = getFlags(node); + if (node.kind === 237 /* VariableDeclaration */) { + node = node.parent; + } + if (node && node.kind === 238 /* VariableDeclarationList */) { + flags |= getFlags(node); + node = node.parent; + } + if (node && node.kind === 219 /* VariableStatement */) { + flags |= getFlags(node); + } + return flags; + } + function getCombinedModifierFlags(node) { + return getCombinedFlags(node, ts.getModifierFlags); + } + ts.getCombinedModifierFlags = getCombinedModifierFlags; + // Returns the node flags for this node and all relevant parent nodes. This is done so that + // nodes like variable declarations and binding elements can returned a view of their flags + // that includes the modifiers from their container. i.e. flags like export/declare aren't + // stored on the variable declaration directly, but on the containing variable statement + // (if it has one). Similarly, flags for let/const are store on the variable declaration + // list. By calling this function, all those flags are combined so that the client can treat + // the node as if it actually had those flags. + function getCombinedNodeFlags(node) { + return getCombinedFlags(node, function (n) { return n.flags; }); + } + ts.getCombinedNodeFlags = getCombinedNodeFlags; + /** + * Checks to see if the locale is in the appropriate format, + * and if it is, attempts to set the appropriate language. + */ + function validateLocaleAndSetLanguage(locale, sys, errors) { + var matchResult = /^([a-z]+)([_\-]([a-z]+))?$/.exec(locale.toLowerCase()); + if (!matchResult) { + if (errors) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1, "en", "ja-jp")); + } + return; + } + var language = matchResult[1]; + var territory = matchResult[3]; + // First try the entire locale, then fall back to just language if that's all we have. + // Either ways do not fail, and fallback to the English diagnostic strings. + if (!trySetLanguageAndTerritory(language, territory, errors)) { + trySetLanguageAndTerritory(language, /*territory*/ undefined, errors); + } + // Set the UI locale for string collation + ts.setUILocale(locale); + function trySetLanguageAndTerritory(language, territory, errors) { + var compilerFilePath = ts.normalizePath(sys.getExecutingFilePath()); + var containingDirectoryPath = ts.getDirectoryPath(compilerFilePath); + var filePath = ts.combinePaths(containingDirectoryPath, language); + if (territory) { + filePath = filePath + "-" + territory; + } + filePath = sys.resolvePath(ts.combinePaths(filePath, "diagnosticMessages.generated.json")); + if (!sys.fileExists(filePath)) { + return false; + } + // TODO: Add codePage support for readFile? + var fileContents = ""; + try { + fileContents = sys.readFile(filePath); + } + catch (e) { + if (errors) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unable_to_open_file_0, filePath)); + } + return false; + } + try { + // tslint:disable-next-line no-unnecessary-qualifier (making clear this is a global mutation!) + ts.localizedDiagnosticMessages = JSON.parse(fileContents); + } + catch (_a) { + if (errors) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Corrupted_locale_file_0, filePath)); + } + return false; + } + return true; + } + } + ts.validateLocaleAndSetLanguage = validateLocaleAndSetLanguage; + function getOriginalNode(node, nodeTest) { + if (node) { + while (node.original !== undefined) { + node = node.original; + } + } + return !nodeTest || nodeTest(node) ? node : undefined; + } + ts.getOriginalNode = getOriginalNode; + /** + * Gets a value indicating whether a node originated in the parse tree. + * + * @param node The node to test. + */ + function isParseTreeNode(node) { + return (node.flags & 8 /* Synthesized */) === 0; + } + ts.isParseTreeNode = isParseTreeNode; + function getParseTreeNode(node, nodeTest) { + if (node === undefined || isParseTreeNode(node)) { + return node; + } + node = getOriginalNode(node); + if (isParseTreeNode(node) && (!nodeTest || nodeTest(node))) { + return node; + } + return undefined; + } + ts.getParseTreeNode = getParseTreeNode; + /** Add an extra underscore to identifiers that start with two underscores to avoid issues with magic names like '__proto__' */ + function escapeLeadingUnderscores(identifier) { + return (identifier.length >= 2 && identifier.charCodeAt(0) === 95 /* _ */ && identifier.charCodeAt(1) === 95 /* _ */ ? "_" + identifier : identifier); + } + ts.escapeLeadingUnderscores = escapeLeadingUnderscores; + /** + * Remove extra underscore from escaped identifier text content. + * + * @param identifier The escaped identifier text. + * @returns The unescaped identifier text. + */ + function unescapeLeadingUnderscores(identifier) { + var id = identifier; + return id.length >= 3 && id.charCodeAt(0) === 95 /* _ */ && id.charCodeAt(1) === 95 /* _ */ && id.charCodeAt(2) === 95 /* _ */ ? id.substr(1) : id; + } + ts.unescapeLeadingUnderscores = unescapeLeadingUnderscores; + function idText(identifier) { + return unescapeLeadingUnderscores(identifier.escapedText); + } + ts.idText = idText; + function symbolName(symbol) { + return unescapeLeadingUnderscores(symbol.escapedName); + } + ts.symbolName = symbolName; + /** + * A JSDocTypedef tag has an _optional_ name field - if a name is not directly present, we should + * attempt to draw the name from the node the declaration is on (as that declaration is what its' symbol + * will be merged with) + */ + function nameForNamelessJSDocTypedef(declaration) { + var hostNode = declaration.parent.parent; + if (!hostNode) { + return undefined; + } + // Covers classes, functions - any named declaration host node + if (ts.isDeclaration(hostNode)) { + return getDeclarationIdentifier(hostNode); + } + // Covers remaining cases (returning undefined if none match). + switch (hostNode.kind) { + case 219 /* VariableStatement */: + if (hostNode.declarationList && hostNode.declarationList.declarations[0]) { + return getDeclarationIdentifier(hostNode.declarationList.declarations[0]); + } + break; + case 221 /* ExpressionStatement */: + var expr = hostNode.expression; + switch (expr.kind) { + case 189 /* PropertyAccessExpression */: + return expr.name; + case 190 /* ElementAccessExpression */: + var arg = expr.argumentExpression; + if (ts.isIdentifier(arg)) { + return arg; + } + } + break; + case 195 /* ParenthesizedExpression */: { + return getDeclarationIdentifier(hostNode.expression); + } + case 233 /* LabeledStatement */: { + if (ts.isDeclaration(hostNode.statement) || ts.isExpression(hostNode.statement)) { + return getDeclarationIdentifier(hostNode.statement); + } + break; + } + } + } + function getDeclarationIdentifier(node) { + var name = getNameOfDeclaration(node); + return name && ts.isIdentifier(name) ? name : undefined; + } + function getNameOfJSDocTypedef(declaration) { + return declaration.name || nameForNamelessJSDocTypedef(declaration); + } + ts.getNameOfJSDocTypedef = getNameOfJSDocTypedef; + /** @internal */ + function isNamedDeclaration(node) { + return !!node.name; // A 'name' property should always be a DeclarationName. + } + ts.isNamedDeclaration = isNamedDeclaration; + /** @internal */ + function getNonAssignedNameOfDeclaration(declaration) { + switch (declaration.kind) { + case 72 /* Identifier */: + return declaration; + case 305 /* JSDocPropertyTag */: + case 299 /* JSDocParameterTag */: { + var name = declaration.name; + if (name.kind === 148 /* QualifiedName */) { + return name.right; + } + break; + } + case 191 /* CallExpression */: + case 204 /* BinaryExpression */: { + var expr = declaration; + switch (ts.getAssignmentDeclarationKind(expr)) { + case 1 /* ExportsProperty */: + case 4 /* ThisProperty */: + case 5 /* Property */: + case 3 /* PrototypeProperty */: + return expr.left.name; + case 7 /* ObjectDefinePropertyValue */: + case 8 /* ObjectDefinePropertyExports */: + case 9 /* ObjectDefinePrototypeProperty */: + return expr.arguments[1]; + default: + return undefined; + } + } + case 304 /* JSDocTypedefTag */: + return getNameOfJSDocTypedef(declaration); + case 254 /* ExportAssignment */: { + var expression = declaration.expression; + return ts.isIdentifier(expression) ? expression : undefined; + } + } + return declaration.name; + } + ts.getNonAssignedNameOfDeclaration = getNonAssignedNameOfDeclaration; + function getNameOfDeclaration(declaration) { + if (declaration === undefined) + return undefined; + return getNonAssignedNameOfDeclaration(declaration) || + (ts.isFunctionExpression(declaration) || ts.isClassExpression(declaration) ? getAssignedName(declaration) : undefined); + } + ts.getNameOfDeclaration = getNameOfDeclaration; + function getAssignedName(node) { + if (!node.parent) { + return undefined; + } + else if (ts.isPropertyAssignment(node.parent) || ts.isBindingElement(node.parent)) { + return node.parent.name; + } + else if (ts.isBinaryExpression(node.parent) && node === node.parent.right) { + if (ts.isIdentifier(node.parent.left)) { + return node.parent.left; + } + else if (ts.isPropertyAccessExpression(node.parent.left)) { + return node.parent.left.name; + } + } + } + /** + * Gets the JSDoc parameter tags for the node if present. + * + * @remarks Returns any JSDoc param tag whose name matches the provided + * parameter, whether a param tag on a containing function + * expression, or a param tag on a variable declaration whose + * initializer is the containing function. The tags closest to the + * node are returned first, so in the previous example, the param + * tag on the containing function expression would be first. + * + * For binding patterns, parameter tags are matched by position. + */ + function getJSDocParameterTags(param) { + if (param.name) { + if (ts.isIdentifier(param.name)) { + var name_1 = param.name.escapedText; + return getJSDocTags(param.parent).filter(function (tag) { return ts.isJSDocParameterTag(tag) && ts.isIdentifier(tag.name) && tag.name.escapedText === name_1; }); + } + else { + var i = param.parent.parameters.indexOf(param); + ts.Debug.assert(i > -1, "Parameters should always be in their parents' parameter list"); + var paramTags = getJSDocTags(param.parent).filter(ts.isJSDocParameterTag); + if (i < paramTags.length) { + return [paramTags[i]]; + } + } + } + // return empty array for: out-of-order binding patterns and JSDoc function syntax, which has un-named parameters + return ts.emptyArray; + } + ts.getJSDocParameterTags = getJSDocParameterTags; + /** + * Gets the JSDoc type parameter tags for the node if present. + * + * @remarks Returns any JSDoc template tag whose names match the provided + * parameter, whether a template tag on a containing function + * expression, or a template tag on a variable declaration whose + * initializer is the containing function. The tags closest to the + * node are returned first, so in the previous example, the template + * tag on the containing function expression would be first. + */ + function getJSDocTypeParameterTags(param) { + var name = param.name.escapedText; + return getJSDocTags(param.parent).filter(function (tag) { + return ts.isJSDocTemplateTag(tag) && tag.typeParameters.some(function (tp) { return tp.name.escapedText === name; }); + }); + } + ts.getJSDocTypeParameterTags = getJSDocTypeParameterTags; + /** + * Return true if the node has JSDoc parameter tags. + * + * @remarks Includes parameter tags that are not directly on the node, + * for example on a variable declaration whose initializer is a function expression. + */ + function hasJSDocParameterTags(node) { + return !!getFirstJSDocTag(node, ts.isJSDocParameterTag); + } + ts.hasJSDocParameterTags = hasJSDocParameterTags; + /** Gets the JSDoc augments tag for the node if present */ + function getJSDocAugmentsTag(node) { + return getFirstJSDocTag(node, ts.isJSDocAugmentsTag); + } + ts.getJSDocAugmentsTag = getJSDocAugmentsTag; + /** Gets the JSDoc class tag for the node if present */ + function getJSDocClassTag(node) { + return getFirstJSDocTag(node, ts.isJSDocClassTag); + } + ts.getJSDocClassTag = getJSDocClassTag; + /** Gets the JSDoc enum tag for the node if present */ + function getJSDocEnumTag(node) { + return getFirstJSDocTag(node, ts.isJSDocEnumTag); + } + ts.getJSDocEnumTag = getJSDocEnumTag; + /** Gets the JSDoc this tag for the node if present */ + function getJSDocThisTag(node) { + return getFirstJSDocTag(node, ts.isJSDocThisTag); + } + ts.getJSDocThisTag = getJSDocThisTag; + /** Gets the JSDoc return tag for the node if present */ + function getJSDocReturnTag(node) { + return getFirstJSDocTag(node, ts.isJSDocReturnTag); + } + ts.getJSDocReturnTag = getJSDocReturnTag; + /** Gets the JSDoc template tag for the node if present */ + function getJSDocTemplateTag(node) { + return getFirstJSDocTag(node, ts.isJSDocTemplateTag); + } + ts.getJSDocTemplateTag = getJSDocTemplateTag; + /** Gets the JSDoc type tag for the node if present and valid */ + function getJSDocTypeTag(node) { + // We should have already issued an error if there were multiple type jsdocs, so just use the first one. + var tag = getFirstJSDocTag(node, ts.isJSDocTypeTag); + if (tag && tag.typeExpression && tag.typeExpression.type) { + return tag; + } + return undefined; + } + ts.getJSDocTypeTag = getJSDocTypeTag; + /** + * Gets the type node for the node if provided via JSDoc. + * + * @remarks The search includes any JSDoc param tag that relates + * to the provided parameter, for example a type tag on the + * parameter itself, or a param tag on a containing function + * expression, or a param tag on a variable declaration whose + * initializer is the containing function. The tags closest to the + * node are examined first, so in the previous example, the type + * tag directly on the node would be returned. + */ + function getJSDocType(node) { + var tag = getFirstJSDocTag(node, ts.isJSDocTypeTag); + if (!tag && ts.isParameter(node)) { + tag = ts.find(getJSDocParameterTags(node), function (tag) { return !!tag.typeExpression; }); + } + return tag && tag.typeExpression && tag.typeExpression.type; + } + ts.getJSDocType = getJSDocType; + /** + * Gets the return type node for the node if provided via JSDoc return tag or type tag. + * + * @remarks `getJSDocReturnTag` just gets the whole JSDoc tag. This function + * gets the type from inside the braces, after the fat arrow, etc. + */ + function getJSDocReturnType(node) { + var returnTag = getJSDocReturnTag(node); + if (returnTag && returnTag.typeExpression) { + return returnTag.typeExpression.type; + } + var typeTag = getJSDocTypeTag(node); + if (typeTag && typeTag.typeExpression) { + var type = typeTag.typeExpression.type; + if (ts.isTypeLiteralNode(type)) { + var sig = ts.find(type.members, ts.isCallSignatureDeclaration); + return sig && sig.type; + } + if (ts.isFunctionTypeNode(type)) { + return type.type; + } + } + } + ts.getJSDocReturnType = getJSDocReturnType; + /** Get all JSDoc tags related to a node, including those on parent nodes. */ + function getJSDocTags(node) { + var tags = node.jsDocCache; + // If cache is 'null', that means we did the work of searching for JSDoc tags and came up with nothing. + if (tags === undefined) { + var comments = ts.getJSDocCommentsAndTags(node); + ts.Debug.assert(comments.length < 2 || comments[0] !== comments[1]); + node.jsDocCache = tags = ts.flatMap(comments, function (j) { return ts.isJSDoc(j) ? j.tags : j; }); + } + return tags; + } + ts.getJSDocTags = getJSDocTags; + /** Get the first JSDoc tag of a specified kind, or undefined if not present. */ + function getFirstJSDocTag(node, predicate) { + return ts.find(getJSDocTags(node), predicate); + } + /** Gets all JSDoc tags of a specified kind, or undefined if not present. */ + function getAllJSDocTagsOfKind(node, kind) { + return getJSDocTags(node).filter(function (doc) { return doc.kind === kind; }); + } + ts.getAllJSDocTagsOfKind = getAllJSDocTagsOfKind; + /** + * Gets the effective type parameters. If the node was parsed in a + * JavaScript file, gets the type parameters from the `@template` tag from JSDoc. + */ + function getEffectiveTypeParameterDeclarations(node) { + if (ts.isJSDocSignature(node)) { + return ts.emptyArray; + } + if (ts.isJSDocTypeAlias(node)) { + ts.Debug.assert(node.parent.kind === 291 /* JSDocComment */); + return ts.flatMap(node.parent.tags, function (tag) { return ts.isJSDocTemplateTag(tag) ? tag.typeParameters : undefined; }); + } + if (node.typeParameters) { + return node.typeParameters; + } + if (ts.isInJSFile(node)) { + var decls = ts.getJSDocTypeParameterDeclarations(node); + if (decls.length) { + return decls; + } + var typeTag = getJSDocType(node); + if (typeTag && ts.isFunctionTypeNode(typeTag) && typeTag.typeParameters) { + return typeTag.typeParameters; + } + } + return ts.emptyArray; + } + ts.getEffectiveTypeParameterDeclarations = getEffectiveTypeParameterDeclarations; + function getEffectiveConstraintOfTypeParameter(node) { + return node.constraint ? node.constraint + : ts.isJSDocTemplateTag(node.parent) && node === node.parent.typeParameters[0] + ? node.parent.constraint + : undefined; + } + ts.getEffectiveConstraintOfTypeParameter = getEffectiveConstraintOfTypeParameter; +})(ts || (ts = {})); +// Simple node tests of the form `node.kind === SyntaxKind.Foo`. +(function (ts) { + // Literals + function isNumericLiteral(node) { + return node.kind === 8 /* NumericLiteral */; + } + ts.isNumericLiteral = isNumericLiteral; + function isBigIntLiteral(node) { + return node.kind === 9 /* BigIntLiteral */; + } + ts.isBigIntLiteral = isBigIntLiteral; + function isStringLiteral(node) { + return node.kind === 10 /* StringLiteral */; + } + ts.isStringLiteral = isStringLiteral; + function isJsxText(node) { + return node.kind === 11 /* JsxText */; + } + ts.isJsxText = isJsxText; + function isRegularExpressionLiteral(node) { + return node.kind === 13 /* RegularExpressionLiteral */; + } + ts.isRegularExpressionLiteral = isRegularExpressionLiteral; + function isNoSubstitutionTemplateLiteral(node) { + return node.kind === 14 /* NoSubstitutionTemplateLiteral */; + } + ts.isNoSubstitutionTemplateLiteral = isNoSubstitutionTemplateLiteral; + // Pseudo-literals + function isTemplateHead(node) { + return node.kind === 15 /* TemplateHead */; + } + ts.isTemplateHead = isTemplateHead; + function isTemplateMiddle(node) { + return node.kind === 16 /* TemplateMiddle */; + } + ts.isTemplateMiddle = isTemplateMiddle; + function isTemplateTail(node) { + return node.kind === 17 /* TemplateTail */; + } + ts.isTemplateTail = isTemplateTail; + function isIdentifier(node) { + return node.kind === 72 /* Identifier */; + } + ts.isIdentifier = isIdentifier; + // Names + function isQualifiedName(node) { + return node.kind === 148 /* QualifiedName */; + } + ts.isQualifiedName = isQualifiedName; + function isComputedPropertyName(node) { + return node.kind === 149 /* ComputedPropertyName */; + } + ts.isComputedPropertyName = isComputedPropertyName; + // Signature elements + function isTypeParameterDeclaration(node) { + return node.kind === 150 /* TypeParameter */; + } + ts.isTypeParameterDeclaration = isTypeParameterDeclaration; + function isParameter(node) { + return node.kind === 151 /* Parameter */; + } + ts.isParameter = isParameter; + function isDecorator(node) { + return node.kind === 152 /* Decorator */; + } + ts.isDecorator = isDecorator; + // TypeMember + function isPropertySignature(node) { + return node.kind === 153 /* PropertySignature */; + } + ts.isPropertySignature = isPropertySignature; + function isPropertyDeclaration(node) { + return node.kind === 154 /* PropertyDeclaration */; + } + ts.isPropertyDeclaration = isPropertyDeclaration; + function isMethodSignature(node) { + return node.kind === 155 /* MethodSignature */; + } + ts.isMethodSignature = isMethodSignature; + function isMethodDeclaration(node) { + return node.kind === 156 /* MethodDeclaration */; + } + ts.isMethodDeclaration = isMethodDeclaration; + function isConstructorDeclaration(node) { + return node.kind === 157 /* Constructor */; + } + ts.isConstructorDeclaration = isConstructorDeclaration; + function isGetAccessorDeclaration(node) { + return node.kind === 158 /* GetAccessor */; + } + ts.isGetAccessorDeclaration = isGetAccessorDeclaration; + function isSetAccessorDeclaration(node) { + return node.kind === 159 /* SetAccessor */; + } + ts.isSetAccessorDeclaration = isSetAccessorDeclaration; + function isCallSignatureDeclaration(node) { + return node.kind === 160 /* CallSignature */; + } + ts.isCallSignatureDeclaration = isCallSignatureDeclaration; + function isConstructSignatureDeclaration(node) { + return node.kind === 161 /* ConstructSignature */; + } + ts.isConstructSignatureDeclaration = isConstructSignatureDeclaration; + function isIndexSignatureDeclaration(node) { + return node.kind === 162 /* IndexSignature */; + } + ts.isIndexSignatureDeclaration = isIndexSignatureDeclaration; + /* @internal */ + function isGetOrSetAccessorDeclaration(node) { + return node.kind === 159 /* SetAccessor */ || node.kind === 158 /* GetAccessor */; + } + ts.isGetOrSetAccessorDeclaration = isGetOrSetAccessorDeclaration; + // Type + function isTypePredicateNode(node) { + return node.kind === 163 /* TypePredicate */; + } + ts.isTypePredicateNode = isTypePredicateNode; + function isTypeReferenceNode(node) { + return node.kind === 164 /* TypeReference */; + } + ts.isTypeReferenceNode = isTypeReferenceNode; + function isFunctionTypeNode(node) { + return node.kind === 165 /* FunctionType */; + } + ts.isFunctionTypeNode = isFunctionTypeNode; + function isConstructorTypeNode(node) { + return node.kind === 166 /* ConstructorType */; + } + ts.isConstructorTypeNode = isConstructorTypeNode; + function isTypeQueryNode(node) { + return node.kind === 167 /* TypeQuery */; + } + ts.isTypeQueryNode = isTypeQueryNode; + function isTypeLiteralNode(node) { + return node.kind === 168 /* TypeLiteral */; + } + ts.isTypeLiteralNode = isTypeLiteralNode; + function isArrayTypeNode(node) { + return node.kind === 169 /* ArrayType */; + } + ts.isArrayTypeNode = isArrayTypeNode; + function isTupleTypeNode(node) { + return node.kind === 170 /* TupleType */; + } + ts.isTupleTypeNode = isTupleTypeNode; + function isUnionTypeNode(node) { + return node.kind === 173 /* UnionType */; + } + ts.isUnionTypeNode = isUnionTypeNode; + function isIntersectionTypeNode(node) { + return node.kind === 174 /* IntersectionType */; + } + ts.isIntersectionTypeNode = isIntersectionTypeNode; + function isConditionalTypeNode(node) { + return node.kind === 175 /* ConditionalType */; + } + ts.isConditionalTypeNode = isConditionalTypeNode; + function isInferTypeNode(node) { + return node.kind === 176 /* InferType */; + } + ts.isInferTypeNode = isInferTypeNode; + function isParenthesizedTypeNode(node) { + return node.kind === 177 /* ParenthesizedType */; + } + ts.isParenthesizedTypeNode = isParenthesizedTypeNode; + function isThisTypeNode(node) { + return node.kind === 178 /* ThisType */; + } + ts.isThisTypeNode = isThisTypeNode; + function isTypeOperatorNode(node) { + return node.kind === 179 /* TypeOperator */; + } + ts.isTypeOperatorNode = isTypeOperatorNode; + function isIndexedAccessTypeNode(node) { + return node.kind === 180 /* IndexedAccessType */; + } + ts.isIndexedAccessTypeNode = isIndexedAccessTypeNode; + function isMappedTypeNode(node) { + return node.kind === 181 /* MappedType */; + } + ts.isMappedTypeNode = isMappedTypeNode; + function isLiteralTypeNode(node) { + return node.kind === 182 /* LiteralType */; + } + ts.isLiteralTypeNode = isLiteralTypeNode; + function isImportTypeNode(node) { + return node.kind === 183 /* ImportType */; + } + ts.isImportTypeNode = isImportTypeNode; + // Binding patterns + function isObjectBindingPattern(node) { + return node.kind === 184 /* ObjectBindingPattern */; + } + ts.isObjectBindingPattern = isObjectBindingPattern; + function isArrayBindingPattern(node) { + return node.kind === 185 /* ArrayBindingPattern */; + } + ts.isArrayBindingPattern = isArrayBindingPattern; + function isBindingElement(node) { + return node.kind === 186 /* BindingElement */; + } + ts.isBindingElement = isBindingElement; + // Expression + function isArrayLiteralExpression(node) { + return node.kind === 187 /* ArrayLiteralExpression */; + } + ts.isArrayLiteralExpression = isArrayLiteralExpression; + function isObjectLiteralExpression(node) { + return node.kind === 188 /* ObjectLiteralExpression */; + } + ts.isObjectLiteralExpression = isObjectLiteralExpression; + function isPropertyAccessExpression(node) { + return node.kind === 189 /* PropertyAccessExpression */; + } + ts.isPropertyAccessExpression = isPropertyAccessExpression; + function isElementAccessExpression(node) { + return node.kind === 190 /* ElementAccessExpression */; + } + ts.isElementAccessExpression = isElementAccessExpression; + function isCallExpression(node) { + return node.kind === 191 /* CallExpression */; + } + ts.isCallExpression = isCallExpression; + function isNewExpression(node) { + return node.kind === 192 /* NewExpression */; + } + ts.isNewExpression = isNewExpression; + function isTaggedTemplateExpression(node) { + return node.kind === 193 /* TaggedTemplateExpression */; + } + ts.isTaggedTemplateExpression = isTaggedTemplateExpression; + function isTypeAssertion(node) { + return node.kind === 194 /* TypeAssertionExpression */; + } + ts.isTypeAssertion = isTypeAssertion; + function isParenthesizedExpression(node) { + return node.kind === 195 /* ParenthesizedExpression */; + } + ts.isParenthesizedExpression = isParenthesizedExpression; + function skipPartiallyEmittedExpressions(node) { + while (node.kind === 308 /* PartiallyEmittedExpression */) { + node = node.expression; + } + return node; + } + ts.skipPartiallyEmittedExpressions = skipPartiallyEmittedExpressions; + function isFunctionExpression(node) { + return node.kind === 196 /* FunctionExpression */; + } + ts.isFunctionExpression = isFunctionExpression; + function isArrowFunction(node) { + return node.kind === 197 /* ArrowFunction */; + } + ts.isArrowFunction = isArrowFunction; + function isDeleteExpression(node) { + return node.kind === 198 /* DeleteExpression */; + } + ts.isDeleteExpression = isDeleteExpression; + function isTypeOfExpression(node) { + return node.kind === 199 /* TypeOfExpression */; + } + ts.isTypeOfExpression = isTypeOfExpression; + function isVoidExpression(node) { + return node.kind === 200 /* VoidExpression */; + } + ts.isVoidExpression = isVoidExpression; + function isAwaitExpression(node) { + return node.kind === 201 /* AwaitExpression */; + } + ts.isAwaitExpression = isAwaitExpression; + function isPrefixUnaryExpression(node) { + return node.kind === 202 /* PrefixUnaryExpression */; + } + ts.isPrefixUnaryExpression = isPrefixUnaryExpression; + function isPostfixUnaryExpression(node) { + return node.kind === 203 /* PostfixUnaryExpression */; + } + ts.isPostfixUnaryExpression = isPostfixUnaryExpression; + function isBinaryExpression(node) { + return node.kind === 204 /* BinaryExpression */; + } + ts.isBinaryExpression = isBinaryExpression; + function isConditionalExpression(node) { + return node.kind === 205 /* ConditionalExpression */; + } + ts.isConditionalExpression = isConditionalExpression; + function isTemplateExpression(node) { + return node.kind === 206 /* TemplateExpression */; + } + ts.isTemplateExpression = isTemplateExpression; + function isYieldExpression(node) { + return node.kind === 207 /* YieldExpression */; + } + ts.isYieldExpression = isYieldExpression; + function isSpreadElement(node) { + return node.kind === 208 /* SpreadElement */; + } + ts.isSpreadElement = isSpreadElement; + function isClassExpression(node) { + return node.kind === 209 /* ClassExpression */; + } + ts.isClassExpression = isClassExpression; + function isOmittedExpression(node) { + return node.kind === 210 /* OmittedExpression */; + } + ts.isOmittedExpression = isOmittedExpression; + function isExpressionWithTypeArguments(node) { + return node.kind === 211 /* ExpressionWithTypeArguments */; + } + ts.isExpressionWithTypeArguments = isExpressionWithTypeArguments; + function isAsExpression(node) { + return node.kind === 212 /* AsExpression */; + } + ts.isAsExpression = isAsExpression; + function isNonNullExpression(node) { + return node.kind === 213 /* NonNullExpression */; + } + ts.isNonNullExpression = isNonNullExpression; + function isMetaProperty(node) { + return node.kind === 214 /* MetaProperty */; + } + ts.isMetaProperty = isMetaProperty; + // Misc + function isTemplateSpan(node) { + return node.kind === 216 /* TemplateSpan */; + } + ts.isTemplateSpan = isTemplateSpan; + function isSemicolonClassElement(node) { + return node.kind === 217 /* SemicolonClassElement */; + } + ts.isSemicolonClassElement = isSemicolonClassElement; + // Block + function isBlock(node) { + return node.kind === 218 /* Block */; + } + ts.isBlock = isBlock; + function isVariableStatement(node) { + return node.kind === 219 /* VariableStatement */; + } + ts.isVariableStatement = isVariableStatement; + function isEmptyStatement(node) { + return node.kind === 220 /* EmptyStatement */; + } + ts.isEmptyStatement = isEmptyStatement; + function isExpressionStatement(node) { + return node.kind === 221 /* ExpressionStatement */; + } + ts.isExpressionStatement = isExpressionStatement; + function isIfStatement(node) { + return node.kind === 222 /* IfStatement */; + } + ts.isIfStatement = isIfStatement; + function isDoStatement(node) { + return node.kind === 223 /* DoStatement */; + } + ts.isDoStatement = isDoStatement; + function isWhileStatement(node) { + return node.kind === 224 /* WhileStatement */; + } + ts.isWhileStatement = isWhileStatement; + function isForStatement(node) { + return node.kind === 225 /* ForStatement */; + } + ts.isForStatement = isForStatement; + function isForInStatement(node) { + return node.kind === 226 /* ForInStatement */; + } + ts.isForInStatement = isForInStatement; + function isForOfStatement(node) { + return node.kind === 227 /* ForOfStatement */; + } + ts.isForOfStatement = isForOfStatement; + function isContinueStatement(node) { + return node.kind === 228 /* ContinueStatement */; + } + ts.isContinueStatement = isContinueStatement; + function isBreakStatement(node) { + return node.kind === 229 /* BreakStatement */; + } + ts.isBreakStatement = isBreakStatement; + function isBreakOrContinueStatement(node) { + return node.kind === 229 /* BreakStatement */ || node.kind === 228 /* ContinueStatement */; + } + ts.isBreakOrContinueStatement = isBreakOrContinueStatement; + function isReturnStatement(node) { + return node.kind === 230 /* ReturnStatement */; + } + ts.isReturnStatement = isReturnStatement; + function isWithStatement(node) { + return node.kind === 231 /* WithStatement */; + } + ts.isWithStatement = isWithStatement; + function isSwitchStatement(node) { + return node.kind === 232 /* SwitchStatement */; + } + ts.isSwitchStatement = isSwitchStatement; + function isLabeledStatement(node) { + return node.kind === 233 /* LabeledStatement */; + } + ts.isLabeledStatement = isLabeledStatement; + function isThrowStatement(node) { + return node.kind === 234 /* ThrowStatement */; + } + ts.isThrowStatement = isThrowStatement; + function isTryStatement(node) { + return node.kind === 235 /* TryStatement */; + } + ts.isTryStatement = isTryStatement; + function isDebuggerStatement(node) { + return node.kind === 236 /* DebuggerStatement */; + } + ts.isDebuggerStatement = isDebuggerStatement; + function isVariableDeclaration(node) { + return node.kind === 237 /* VariableDeclaration */; + } + ts.isVariableDeclaration = isVariableDeclaration; + function isVariableDeclarationList(node) { + return node.kind === 238 /* VariableDeclarationList */; + } + ts.isVariableDeclarationList = isVariableDeclarationList; + function isFunctionDeclaration(node) { + return node.kind === 239 /* FunctionDeclaration */; + } + ts.isFunctionDeclaration = isFunctionDeclaration; + function isClassDeclaration(node) { + return node.kind === 240 /* ClassDeclaration */; + } + ts.isClassDeclaration = isClassDeclaration; + function isInterfaceDeclaration(node) { + return node.kind === 241 /* InterfaceDeclaration */; + } + ts.isInterfaceDeclaration = isInterfaceDeclaration; + function isTypeAliasDeclaration(node) { + return node.kind === 242 /* TypeAliasDeclaration */; + } + ts.isTypeAliasDeclaration = isTypeAliasDeclaration; + function isEnumDeclaration(node) { + return node.kind === 243 /* EnumDeclaration */; + } + ts.isEnumDeclaration = isEnumDeclaration; + function isModuleDeclaration(node) { + return node.kind === 244 /* ModuleDeclaration */; + } + ts.isModuleDeclaration = isModuleDeclaration; + function isModuleBlock(node) { + return node.kind === 245 /* ModuleBlock */; + } + ts.isModuleBlock = isModuleBlock; + function isCaseBlock(node) { + return node.kind === 246 /* CaseBlock */; + } + ts.isCaseBlock = isCaseBlock; + function isNamespaceExportDeclaration(node) { + return node.kind === 247 /* NamespaceExportDeclaration */; + } + ts.isNamespaceExportDeclaration = isNamespaceExportDeclaration; + function isImportEqualsDeclaration(node) { + return node.kind === 248 /* ImportEqualsDeclaration */; + } + ts.isImportEqualsDeclaration = isImportEqualsDeclaration; + function isImportDeclaration(node) { + return node.kind === 249 /* ImportDeclaration */; + } + ts.isImportDeclaration = isImportDeclaration; + function isImportClause(node) { + return node.kind === 250 /* ImportClause */; + } + ts.isImportClause = isImportClause; + function isNamespaceImport(node) { + return node.kind === 251 /* NamespaceImport */; + } + ts.isNamespaceImport = isNamespaceImport; + function isNamedImports(node) { + return node.kind === 252 /* NamedImports */; + } + ts.isNamedImports = isNamedImports; + function isImportSpecifier(node) { + return node.kind === 253 /* ImportSpecifier */; + } + ts.isImportSpecifier = isImportSpecifier; + function isExportAssignment(node) { + return node.kind === 254 /* ExportAssignment */; + } + ts.isExportAssignment = isExportAssignment; + function isExportDeclaration(node) { + return node.kind === 255 /* ExportDeclaration */; + } + ts.isExportDeclaration = isExportDeclaration; + function isNamedExports(node) { + return node.kind === 256 /* NamedExports */; + } + ts.isNamedExports = isNamedExports; + function isExportSpecifier(node) { + return node.kind === 257 /* ExportSpecifier */; + } + ts.isExportSpecifier = isExportSpecifier; + function isMissingDeclaration(node) { + return node.kind === 258 /* MissingDeclaration */; + } + ts.isMissingDeclaration = isMissingDeclaration; + // Module References + function isExternalModuleReference(node) { + return node.kind === 259 /* ExternalModuleReference */; + } + ts.isExternalModuleReference = isExternalModuleReference; + // JSX + function isJsxElement(node) { + return node.kind === 260 /* JsxElement */; + } + ts.isJsxElement = isJsxElement; + function isJsxSelfClosingElement(node) { + return node.kind === 261 /* JsxSelfClosingElement */; + } + ts.isJsxSelfClosingElement = isJsxSelfClosingElement; + function isJsxOpeningElement(node) { + return node.kind === 262 /* JsxOpeningElement */; + } + ts.isJsxOpeningElement = isJsxOpeningElement; + function isJsxClosingElement(node) { + return node.kind === 263 /* JsxClosingElement */; + } + ts.isJsxClosingElement = isJsxClosingElement; + function isJsxFragment(node) { + return node.kind === 264 /* JsxFragment */; + } + ts.isJsxFragment = isJsxFragment; + function isJsxOpeningFragment(node) { + return node.kind === 265 /* JsxOpeningFragment */; + } + ts.isJsxOpeningFragment = isJsxOpeningFragment; + function isJsxClosingFragment(node) { + return node.kind === 266 /* JsxClosingFragment */; + } + ts.isJsxClosingFragment = isJsxClosingFragment; + function isJsxAttribute(node) { + return node.kind === 267 /* JsxAttribute */; + } + ts.isJsxAttribute = isJsxAttribute; + function isJsxAttributes(node) { + return node.kind === 268 /* JsxAttributes */; + } + ts.isJsxAttributes = isJsxAttributes; + function isJsxSpreadAttribute(node) { + return node.kind === 269 /* JsxSpreadAttribute */; + } + ts.isJsxSpreadAttribute = isJsxSpreadAttribute; + function isJsxExpression(node) { + return node.kind === 270 /* JsxExpression */; + } + ts.isJsxExpression = isJsxExpression; + // Clauses + function isCaseClause(node) { + return node.kind === 271 /* CaseClause */; + } + ts.isCaseClause = isCaseClause; + function isDefaultClause(node) { + return node.kind === 272 /* DefaultClause */; + } + ts.isDefaultClause = isDefaultClause; + function isHeritageClause(node) { + return node.kind === 273 /* HeritageClause */; + } + ts.isHeritageClause = isHeritageClause; + function isCatchClause(node) { + return node.kind === 274 /* CatchClause */; + } + ts.isCatchClause = isCatchClause; + // Property assignments + function isPropertyAssignment(node) { + return node.kind === 275 /* PropertyAssignment */; + } + ts.isPropertyAssignment = isPropertyAssignment; + function isShorthandPropertyAssignment(node) { + return node.kind === 276 /* ShorthandPropertyAssignment */; + } + ts.isShorthandPropertyAssignment = isShorthandPropertyAssignment; + function isSpreadAssignment(node) { + return node.kind === 277 /* SpreadAssignment */; + } + ts.isSpreadAssignment = isSpreadAssignment; + // Enum + function isEnumMember(node) { + return node.kind === 278 /* EnumMember */; + } + ts.isEnumMember = isEnumMember; + // Top-level nodes + function isSourceFile(node) { + return node.kind === 279 /* SourceFile */; + } + ts.isSourceFile = isSourceFile; + function isBundle(node) { + return node.kind === 280 /* Bundle */; + } + ts.isBundle = isBundle; + function isUnparsedSource(node) { + return node.kind === 281 /* UnparsedSource */; + } + ts.isUnparsedSource = isUnparsedSource; + // JSDoc + function isJSDocTypeExpression(node) { + return node.kind === 283 /* JSDocTypeExpression */; + } + ts.isJSDocTypeExpression = isJSDocTypeExpression; + function isJSDocAllType(node) { + return node.kind === 284 /* JSDocAllType */; + } + ts.isJSDocAllType = isJSDocAllType; + function isJSDocUnknownType(node) { + return node.kind === 285 /* JSDocUnknownType */; + } + ts.isJSDocUnknownType = isJSDocUnknownType; + function isJSDocNullableType(node) { + return node.kind === 286 /* JSDocNullableType */; + } + ts.isJSDocNullableType = isJSDocNullableType; + function isJSDocNonNullableType(node) { + return node.kind === 287 /* JSDocNonNullableType */; + } + ts.isJSDocNonNullableType = isJSDocNonNullableType; + function isJSDocOptionalType(node) { + return node.kind === 288 /* JSDocOptionalType */; + } + ts.isJSDocOptionalType = isJSDocOptionalType; + function isJSDocFunctionType(node) { + return node.kind === 289 /* JSDocFunctionType */; + } + ts.isJSDocFunctionType = isJSDocFunctionType; + function isJSDocVariadicType(node) { + return node.kind === 290 /* JSDocVariadicType */; + } + ts.isJSDocVariadicType = isJSDocVariadicType; + function isJSDoc(node) { + return node.kind === 291 /* JSDocComment */; + } + ts.isJSDoc = isJSDoc; + function isJSDocAugmentsTag(node) { + return node.kind === 295 /* JSDocAugmentsTag */; + } + ts.isJSDocAugmentsTag = isJSDocAugmentsTag; + function isJSDocClassTag(node) { + return node.kind === 296 /* JSDocClassTag */; + } + ts.isJSDocClassTag = isJSDocClassTag; + function isJSDocEnumTag(node) { + return node.kind === 298 /* JSDocEnumTag */; + } + ts.isJSDocEnumTag = isJSDocEnumTag; + function isJSDocThisTag(node) { + return node.kind === 301 /* JSDocThisTag */; + } + ts.isJSDocThisTag = isJSDocThisTag; + function isJSDocParameterTag(node) { + return node.kind === 299 /* JSDocParameterTag */; + } + ts.isJSDocParameterTag = isJSDocParameterTag; + function isJSDocReturnTag(node) { + return node.kind === 300 /* JSDocReturnTag */; + } + ts.isJSDocReturnTag = isJSDocReturnTag; + function isJSDocTypeTag(node) { + return node.kind === 302 /* JSDocTypeTag */; + } + ts.isJSDocTypeTag = isJSDocTypeTag; + function isJSDocTemplateTag(node) { + return node.kind === 303 /* JSDocTemplateTag */; + } + ts.isJSDocTemplateTag = isJSDocTemplateTag; + function isJSDocTypedefTag(node) { + return node.kind === 304 /* JSDocTypedefTag */; + } + ts.isJSDocTypedefTag = isJSDocTypedefTag; + function isJSDocPropertyTag(node) { + return node.kind === 305 /* JSDocPropertyTag */; + } + ts.isJSDocPropertyTag = isJSDocPropertyTag; + function isJSDocPropertyLikeTag(node) { + return node.kind === 305 /* JSDocPropertyTag */ || node.kind === 299 /* JSDocParameterTag */; + } + ts.isJSDocPropertyLikeTag = isJSDocPropertyLikeTag; + function isJSDocTypeLiteral(node) { + return node.kind === 292 /* JSDocTypeLiteral */; + } + ts.isJSDocTypeLiteral = isJSDocTypeLiteral; + function isJSDocCallbackTag(node) { + return node.kind === 297 /* JSDocCallbackTag */; + } + ts.isJSDocCallbackTag = isJSDocCallbackTag; + function isJSDocSignature(node) { + return node.kind === 293 /* JSDocSignature */; + } + ts.isJSDocSignature = isJSDocSignature; +})(ts || (ts = {})); +// Node tests +// +// All node tests in the following list should *not* reference parent pointers so that +// they may be used with transformations. +(function (ts) { + /* @internal */ + function isSyntaxList(n) { + return n.kind === 306 /* SyntaxList */; + } + ts.isSyntaxList = isSyntaxList; + /* @internal */ + function isNode(node) { + return isNodeKind(node.kind); + } + ts.isNode = isNode; + /* @internal */ + function isNodeKind(kind) { + return kind >= 148 /* FirstNode */; + } + ts.isNodeKind = isNodeKind; + /** + * True if node is of some token syntax kind. + * For example, this is true for an IfKeyword but not for an IfStatement. + * Literals are considered tokens, except TemplateLiteral, but does include TemplateHead/Middle/Tail. + */ + function isToken(n) { + return n.kind >= 0 /* FirstToken */ && n.kind <= 147 /* LastToken */; + } + ts.isToken = isToken; + // Node Arrays + /* @internal */ + function isNodeArray(array) { + return array.hasOwnProperty("pos") && array.hasOwnProperty("end"); + } + ts.isNodeArray = isNodeArray; + // Literals + /* @internal */ + function isLiteralKind(kind) { + return 8 /* FirstLiteralToken */ <= kind && kind <= 14 /* LastLiteralToken */; + } + ts.isLiteralKind = isLiteralKind; + function isLiteralExpression(node) { + return isLiteralKind(node.kind); + } + ts.isLiteralExpression = isLiteralExpression; + // Pseudo-literals + /* @internal */ + function isTemplateLiteralKind(kind) { + return 14 /* FirstTemplateToken */ <= kind && kind <= 17 /* LastTemplateToken */; + } + ts.isTemplateLiteralKind = isTemplateLiteralKind; + function isTemplateLiteralToken(node) { + return isTemplateLiteralKind(node.kind); + } + ts.isTemplateLiteralToken = isTemplateLiteralToken; + function isTemplateMiddleOrTemplateTail(node) { + var kind = node.kind; + return kind === 16 /* TemplateMiddle */ + || kind === 17 /* TemplateTail */; + } + ts.isTemplateMiddleOrTemplateTail = isTemplateMiddleOrTemplateTail; + function isImportOrExportSpecifier(node) { + return ts.isImportSpecifier(node) || ts.isExportSpecifier(node); + } + ts.isImportOrExportSpecifier = isImportOrExportSpecifier; + function isStringTextContainingNode(node) { + return node.kind === 10 /* StringLiteral */ || isTemplateLiteralKind(node.kind); + } + ts.isStringTextContainingNode = isStringTextContainingNode; + // Identifiers + /* @internal */ + function isGeneratedIdentifier(node) { + return ts.isIdentifier(node) && (node.autoGenerateFlags & 7 /* KindMask */) > 0 /* None */; + } + ts.isGeneratedIdentifier = isGeneratedIdentifier; + // Keywords + /* @internal */ + function isModifierKind(token) { + switch (token) { + case 118 /* AbstractKeyword */: + case 121 /* AsyncKeyword */: + case 77 /* ConstKeyword */: + case 125 /* DeclareKeyword */: + case 80 /* DefaultKeyword */: + case 85 /* ExportKeyword */: + case 115 /* PublicKeyword */: + case 113 /* PrivateKeyword */: + case 114 /* ProtectedKeyword */: + case 133 /* ReadonlyKeyword */: + case 116 /* StaticKeyword */: + return true; + } + return false; + } + ts.isModifierKind = isModifierKind; + /* @internal */ + function isParameterPropertyModifier(kind) { + return !!(ts.modifierToFlag(kind) & 92 /* ParameterPropertyModifier */); + } + ts.isParameterPropertyModifier = isParameterPropertyModifier; + /* @internal */ + function isClassMemberModifier(idToken) { + return isParameterPropertyModifier(idToken) || idToken === 116 /* StaticKeyword */; + } + ts.isClassMemberModifier = isClassMemberModifier; + function isModifier(node) { + return isModifierKind(node.kind); + } + ts.isModifier = isModifier; + function isEntityName(node) { + var kind = node.kind; + return kind === 148 /* QualifiedName */ + || kind === 72 /* Identifier */; + } + ts.isEntityName = isEntityName; + function isPropertyName(node) { + var kind = node.kind; + return kind === 72 /* Identifier */ + || kind === 10 /* StringLiteral */ + || kind === 8 /* NumericLiteral */ + || kind === 149 /* ComputedPropertyName */; + } + ts.isPropertyName = isPropertyName; + function isBindingName(node) { + var kind = node.kind; + return kind === 72 /* Identifier */ + || kind === 184 /* ObjectBindingPattern */ + || kind === 185 /* ArrayBindingPattern */; + } + ts.isBindingName = isBindingName; + // Functions + function isFunctionLike(node) { + return node && isFunctionLikeKind(node.kind); + } + ts.isFunctionLike = isFunctionLike; + /* @internal */ + function isFunctionLikeDeclaration(node) { + return node && isFunctionLikeDeclarationKind(node.kind); + } + ts.isFunctionLikeDeclaration = isFunctionLikeDeclaration; + function isFunctionLikeDeclarationKind(kind) { + switch (kind) { + case 239 /* FunctionDeclaration */: + case 156 /* MethodDeclaration */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + return true; + default: + return false; + } + } + /* @internal */ + function isFunctionLikeKind(kind) { + switch (kind) { + case 155 /* MethodSignature */: + case 160 /* CallSignature */: + case 293 /* JSDocSignature */: + case 161 /* ConstructSignature */: + case 162 /* IndexSignature */: + case 165 /* FunctionType */: + case 289 /* JSDocFunctionType */: + case 166 /* ConstructorType */: + return true; + default: + return isFunctionLikeDeclarationKind(kind); + } + } + ts.isFunctionLikeKind = isFunctionLikeKind; + /* @internal */ + function isFunctionOrModuleBlock(node) { + return ts.isSourceFile(node) || ts.isModuleBlock(node) || ts.isBlock(node) && isFunctionLike(node.parent); + } + ts.isFunctionOrModuleBlock = isFunctionOrModuleBlock; + // Classes + function isClassElement(node) { + var kind = node.kind; + return kind === 157 /* Constructor */ + || kind === 154 /* PropertyDeclaration */ + || kind === 156 /* MethodDeclaration */ + || kind === 158 /* GetAccessor */ + || kind === 159 /* SetAccessor */ + || kind === 162 /* IndexSignature */ + || kind === 217 /* SemicolonClassElement */; + } + ts.isClassElement = isClassElement; + function isClassLike(node) { + return node && (node.kind === 240 /* ClassDeclaration */ || node.kind === 209 /* ClassExpression */); + } + ts.isClassLike = isClassLike; + function isAccessor(node) { + return node && (node.kind === 158 /* GetAccessor */ || node.kind === 159 /* SetAccessor */); + } + ts.isAccessor = isAccessor; + /* @internal */ + function isMethodOrAccessor(node) { + switch (node.kind) { + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + return true; + default: + return false; + } + } + ts.isMethodOrAccessor = isMethodOrAccessor; + // Type members + function isTypeElement(node) { + var kind = node.kind; + return kind === 161 /* ConstructSignature */ + || kind === 160 /* CallSignature */ + || kind === 153 /* PropertySignature */ + || kind === 155 /* MethodSignature */ + || kind === 162 /* IndexSignature */; + } + ts.isTypeElement = isTypeElement; + function isClassOrTypeElement(node) { + return isTypeElement(node) || isClassElement(node); + } + ts.isClassOrTypeElement = isClassOrTypeElement; + function isObjectLiteralElementLike(node) { + var kind = node.kind; + return kind === 275 /* PropertyAssignment */ + || kind === 276 /* ShorthandPropertyAssignment */ + || kind === 277 /* SpreadAssignment */ + || kind === 156 /* MethodDeclaration */ + || kind === 158 /* GetAccessor */ + || kind === 159 /* SetAccessor */; + } + ts.isObjectLiteralElementLike = isObjectLiteralElementLike; + // Type + /** + * Node test that determines whether a node is a valid type node. + * This differs from the `isPartOfTypeNode` function which determines whether a node is *part* + * of a TypeNode. + */ + function isTypeNode(node) { + return ts.isTypeNodeKind(node.kind); + } + ts.isTypeNode = isTypeNode; + function isFunctionOrConstructorTypeNode(node) { + switch (node.kind) { + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + return true; + } + return false; + } + ts.isFunctionOrConstructorTypeNode = isFunctionOrConstructorTypeNode; + // Binding patterns + /* @internal */ + function isBindingPattern(node) { + if (node) { + var kind = node.kind; + return kind === 185 /* ArrayBindingPattern */ + || kind === 184 /* ObjectBindingPattern */; + } + return false; + } + ts.isBindingPattern = isBindingPattern; + /* @internal */ + function isAssignmentPattern(node) { + var kind = node.kind; + return kind === 187 /* ArrayLiteralExpression */ + || kind === 188 /* ObjectLiteralExpression */; + } + ts.isAssignmentPattern = isAssignmentPattern; + /* @internal */ + function isArrayBindingElement(node) { + var kind = node.kind; + return kind === 186 /* BindingElement */ + || kind === 210 /* OmittedExpression */; + } + ts.isArrayBindingElement = isArrayBindingElement; + /** + * Determines whether the BindingOrAssignmentElement is a BindingElement-like declaration + */ + /* @internal */ + function isDeclarationBindingElement(bindingElement) { + switch (bindingElement.kind) { + case 237 /* VariableDeclaration */: + case 151 /* Parameter */: + case 186 /* BindingElement */: + return true; + } + return false; + } + ts.isDeclarationBindingElement = isDeclarationBindingElement; + /** + * Determines whether a node is a BindingOrAssignmentPattern + */ + /* @internal */ + function isBindingOrAssignmentPattern(node) { + return isObjectBindingOrAssignmentPattern(node) + || isArrayBindingOrAssignmentPattern(node); + } + ts.isBindingOrAssignmentPattern = isBindingOrAssignmentPattern; + /** + * Determines whether a node is an ObjectBindingOrAssignmentPattern + */ + /* @internal */ + function isObjectBindingOrAssignmentPattern(node) { + switch (node.kind) { + case 184 /* ObjectBindingPattern */: + case 188 /* ObjectLiteralExpression */: + return true; + } + return false; + } + ts.isObjectBindingOrAssignmentPattern = isObjectBindingOrAssignmentPattern; + /** + * Determines whether a node is an ArrayBindingOrAssignmentPattern + */ + /* @internal */ + function isArrayBindingOrAssignmentPattern(node) { + switch (node.kind) { + case 185 /* ArrayBindingPattern */: + case 187 /* ArrayLiteralExpression */: + return true; + } + return false; + } + ts.isArrayBindingOrAssignmentPattern = isArrayBindingOrAssignmentPattern; + /* @internal */ + function isPropertyAccessOrQualifiedNameOrImportTypeNode(node) { + var kind = node.kind; + return kind === 189 /* PropertyAccessExpression */ + || kind === 148 /* QualifiedName */ + || kind === 183 /* ImportType */; + } + ts.isPropertyAccessOrQualifiedNameOrImportTypeNode = isPropertyAccessOrQualifiedNameOrImportTypeNode; + // Expression + function isPropertyAccessOrQualifiedName(node) { + var kind = node.kind; + return kind === 189 /* PropertyAccessExpression */ + || kind === 148 /* QualifiedName */; + } + ts.isPropertyAccessOrQualifiedName = isPropertyAccessOrQualifiedName; + function isCallLikeExpression(node) { + switch (node.kind) { + case 262 /* JsxOpeningElement */: + case 261 /* JsxSelfClosingElement */: + case 191 /* CallExpression */: + case 192 /* NewExpression */: + case 193 /* TaggedTemplateExpression */: + case 152 /* Decorator */: + return true; + default: + return false; + } + } + ts.isCallLikeExpression = isCallLikeExpression; + function isCallOrNewExpression(node) { + return node.kind === 191 /* CallExpression */ || node.kind === 192 /* NewExpression */; + } + ts.isCallOrNewExpression = isCallOrNewExpression; + function isTemplateLiteral(node) { + var kind = node.kind; + return kind === 206 /* TemplateExpression */ + || kind === 14 /* NoSubstitutionTemplateLiteral */; + } + ts.isTemplateLiteral = isTemplateLiteral; + /* @internal */ + function isLeftHandSideExpression(node) { + return isLeftHandSideExpressionKind(ts.skipPartiallyEmittedExpressions(node).kind); + } + ts.isLeftHandSideExpression = isLeftHandSideExpression; + function isLeftHandSideExpressionKind(kind) { + switch (kind) { + case 189 /* PropertyAccessExpression */: + case 190 /* ElementAccessExpression */: + case 192 /* NewExpression */: + case 191 /* CallExpression */: + case 260 /* JsxElement */: + case 261 /* JsxSelfClosingElement */: + case 264 /* JsxFragment */: + case 193 /* TaggedTemplateExpression */: + case 187 /* ArrayLiteralExpression */: + case 195 /* ParenthesizedExpression */: + case 188 /* ObjectLiteralExpression */: + case 209 /* ClassExpression */: + case 196 /* FunctionExpression */: + case 72 /* Identifier */: + case 13 /* RegularExpressionLiteral */: + case 8 /* NumericLiteral */: + case 9 /* BigIntLiteral */: + case 10 /* StringLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: + case 206 /* TemplateExpression */: + case 87 /* FalseKeyword */: + case 96 /* NullKeyword */: + case 100 /* ThisKeyword */: + case 102 /* TrueKeyword */: + case 98 /* SuperKeyword */: + case 213 /* NonNullExpression */: + case 214 /* MetaProperty */: + case 92 /* ImportKeyword */: // technically this is only an Expression if it's in a CallExpression + return true; + default: + return false; + } + } + /* @internal */ + function isUnaryExpression(node) { + return isUnaryExpressionKind(ts.skipPartiallyEmittedExpressions(node).kind); + } + ts.isUnaryExpression = isUnaryExpression; + function isUnaryExpressionKind(kind) { + switch (kind) { + case 202 /* PrefixUnaryExpression */: + case 203 /* PostfixUnaryExpression */: + case 198 /* DeleteExpression */: + case 199 /* TypeOfExpression */: + case 200 /* VoidExpression */: + case 201 /* AwaitExpression */: + case 194 /* TypeAssertionExpression */: + return true; + default: + return isLeftHandSideExpressionKind(kind); + } + } + /* @internal */ + function isUnaryExpressionWithWrite(expr) { + switch (expr.kind) { + case 203 /* PostfixUnaryExpression */: + return true; + case 202 /* PrefixUnaryExpression */: + return expr.operator === 44 /* PlusPlusToken */ || + expr.operator === 45 /* MinusMinusToken */; + default: + return false; + } + } + ts.isUnaryExpressionWithWrite = isUnaryExpressionWithWrite; + /* @internal */ + /** + * Determines whether a node is an expression based only on its kind. + * Use `isExpressionNode` if not in transforms. + */ + function isExpression(node) { + return isExpressionKind(ts.skipPartiallyEmittedExpressions(node).kind); + } + ts.isExpression = isExpression; + function isExpressionKind(kind) { + switch (kind) { + case 205 /* ConditionalExpression */: + case 207 /* YieldExpression */: + case 197 /* ArrowFunction */: + case 204 /* BinaryExpression */: + case 208 /* SpreadElement */: + case 212 /* AsExpression */: + case 210 /* OmittedExpression */: + case 309 /* CommaListExpression */: + case 308 /* PartiallyEmittedExpression */: + return true; + default: + return isUnaryExpressionKind(kind); + } + } + function isAssertionExpression(node) { + var kind = node.kind; + return kind === 194 /* TypeAssertionExpression */ + || kind === 212 /* AsExpression */; + } + ts.isAssertionExpression = isAssertionExpression; + /* @internal */ + function isPartiallyEmittedExpression(node) { + return node.kind === 308 /* PartiallyEmittedExpression */; + } + ts.isPartiallyEmittedExpression = isPartiallyEmittedExpression; + /* @internal */ + function isNotEmittedStatement(node) { + return node.kind === 307 /* NotEmittedStatement */; + } + ts.isNotEmittedStatement = isNotEmittedStatement; + /* @internal */ + function isNotEmittedOrPartiallyEmittedNode(node) { + return isNotEmittedStatement(node) + || isPartiallyEmittedExpression(node); + } + ts.isNotEmittedOrPartiallyEmittedNode = isNotEmittedOrPartiallyEmittedNode; + function isIterationStatement(node, lookInLabeledStatements) { + switch (node.kind) { + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + case 223 /* DoStatement */: + case 224 /* WhileStatement */: + return true; + case 233 /* LabeledStatement */: + return lookInLabeledStatements && isIterationStatement(node.statement, lookInLabeledStatements); + } + return false; + } + ts.isIterationStatement = isIterationStatement; + /* @internal */ + function isForInOrOfStatement(node) { + return node.kind === 226 /* ForInStatement */ || node.kind === 227 /* ForOfStatement */; + } + ts.isForInOrOfStatement = isForInOrOfStatement; + // Element + /* @internal */ + function isConciseBody(node) { + return ts.isBlock(node) + || isExpression(node); + } + ts.isConciseBody = isConciseBody; + /* @internal */ + function isFunctionBody(node) { + return ts.isBlock(node); + } + ts.isFunctionBody = isFunctionBody; + /* @internal */ + function isForInitializer(node) { + return ts.isVariableDeclarationList(node) + || isExpression(node); + } + ts.isForInitializer = isForInitializer; + /* @internal */ + function isModuleBody(node) { + var kind = node.kind; + return kind === 245 /* ModuleBlock */ + || kind === 244 /* ModuleDeclaration */ + || kind === 72 /* Identifier */; + } + ts.isModuleBody = isModuleBody; + /* @internal */ + function isNamespaceBody(node) { + var kind = node.kind; + return kind === 245 /* ModuleBlock */ + || kind === 244 /* ModuleDeclaration */; + } + ts.isNamespaceBody = isNamespaceBody; + /* @internal */ + function isJSDocNamespaceBody(node) { + var kind = node.kind; + return kind === 72 /* Identifier */ + || kind === 244 /* ModuleDeclaration */; + } + ts.isJSDocNamespaceBody = isJSDocNamespaceBody; + /* @internal */ + function isNamedImportBindings(node) { + var kind = node.kind; + return kind === 252 /* NamedImports */ + || kind === 251 /* NamespaceImport */; + } + ts.isNamedImportBindings = isNamedImportBindings; + /* @internal */ + function isModuleOrEnumDeclaration(node) { + return node.kind === 244 /* ModuleDeclaration */ || node.kind === 243 /* EnumDeclaration */; + } + ts.isModuleOrEnumDeclaration = isModuleOrEnumDeclaration; + function isDeclarationKind(kind) { + return kind === 197 /* ArrowFunction */ + || kind === 186 /* BindingElement */ + || kind === 240 /* ClassDeclaration */ + || kind === 209 /* ClassExpression */ + || kind === 157 /* Constructor */ + || kind === 243 /* EnumDeclaration */ + || kind === 278 /* EnumMember */ + || kind === 257 /* ExportSpecifier */ + || kind === 239 /* FunctionDeclaration */ + || kind === 196 /* FunctionExpression */ + || kind === 158 /* GetAccessor */ + || kind === 250 /* ImportClause */ + || kind === 248 /* ImportEqualsDeclaration */ + || kind === 253 /* ImportSpecifier */ + || kind === 241 /* InterfaceDeclaration */ + || kind === 267 /* JsxAttribute */ + || kind === 156 /* MethodDeclaration */ + || kind === 155 /* MethodSignature */ + || kind === 244 /* ModuleDeclaration */ + || kind === 247 /* NamespaceExportDeclaration */ + || kind === 251 /* NamespaceImport */ + || kind === 151 /* Parameter */ + || kind === 275 /* PropertyAssignment */ + || kind === 154 /* PropertyDeclaration */ + || kind === 153 /* PropertySignature */ + || kind === 159 /* SetAccessor */ + || kind === 276 /* ShorthandPropertyAssignment */ + || kind === 242 /* TypeAliasDeclaration */ + || kind === 150 /* TypeParameter */ + || kind === 237 /* VariableDeclaration */ + || kind === 304 /* JSDocTypedefTag */ + || kind === 297 /* JSDocCallbackTag */ + || kind === 305 /* JSDocPropertyTag */; + } + function isDeclarationStatementKind(kind) { + return kind === 239 /* FunctionDeclaration */ + || kind === 258 /* MissingDeclaration */ + || kind === 240 /* ClassDeclaration */ + || kind === 241 /* InterfaceDeclaration */ + || kind === 242 /* TypeAliasDeclaration */ + || kind === 243 /* EnumDeclaration */ + || kind === 244 /* ModuleDeclaration */ + || kind === 249 /* ImportDeclaration */ + || kind === 248 /* ImportEqualsDeclaration */ + || kind === 255 /* ExportDeclaration */ + || kind === 254 /* ExportAssignment */ + || kind === 247 /* NamespaceExportDeclaration */; + } + function isStatementKindButNotDeclarationKind(kind) { + return kind === 229 /* BreakStatement */ + || kind === 228 /* ContinueStatement */ + || kind === 236 /* DebuggerStatement */ + || kind === 223 /* DoStatement */ + || kind === 221 /* ExpressionStatement */ + || kind === 220 /* EmptyStatement */ + || kind === 226 /* ForInStatement */ + || kind === 227 /* ForOfStatement */ + || kind === 225 /* ForStatement */ + || kind === 222 /* IfStatement */ + || kind === 233 /* LabeledStatement */ + || kind === 230 /* ReturnStatement */ + || kind === 232 /* SwitchStatement */ + || kind === 234 /* ThrowStatement */ + || kind === 235 /* TryStatement */ + || kind === 219 /* VariableStatement */ + || kind === 224 /* WhileStatement */ + || kind === 231 /* WithStatement */ + || kind === 307 /* NotEmittedStatement */ + || kind === 311 /* EndOfDeclarationMarker */ + || kind === 310 /* MergeDeclarationMarker */; + } + /* @internal */ + function isDeclaration(node) { + if (node.kind === 150 /* TypeParameter */) { + return node.parent.kind !== 303 /* JSDocTemplateTag */ || ts.isInJSFile(node); + } + return isDeclarationKind(node.kind); + } + ts.isDeclaration = isDeclaration; + /* @internal */ + function isDeclarationStatement(node) { + return isDeclarationStatementKind(node.kind); + } + ts.isDeclarationStatement = isDeclarationStatement; + /** + * Determines whether the node is a statement that is not also a declaration + */ + /* @internal */ + function isStatementButNotDeclaration(node) { + return isStatementKindButNotDeclarationKind(node.kind); + } + ts.isStatementButNotDeclaration = isStatementButNotDeclaration; + /* @internal */ + function isStatement(node) { + var kind = node.kind; + return isStatementKindButNotDeclarationKind(kind) + || isDeclarationStatementKind(kind) + || isBlockStatement(node); + } + ts.isStatement = isStatement; + function isBlockStatement(node) { + if (node.kind !== 218 /* Block */) + return false; + if (node.parent !== undefined) { + if (node.parent.kind === 235 /* TryStatement */ || node.parent.kind === 274 /* CatchClause */) { + return false; + } + } + return !ts.isFunctionBlock(node); + } + // Module references + /* @internal */ + function isModuleReference(node) { + var kind = node.kind; + return kind === 259 /* ExternalModuleReference */ + || kind === 148 /* QualifiedName */ + || kind === 72 /* Identifier */; + } + ts.isModuleReference = isModuleReference; + // JSX + /* @internal */ + function isJsxTagNameExpression(node) { + var kind = node.kind; + return kind === 100 /* ThisKeyword */ + || kind === 72 /* Identifier */ + || kind === 189 /* PropertyAccessExpression */; + } + ts.isJsxTagNameExpression = isJsxTagNameExpression; + /* @internal */ + function isJsxChild(node) { + var kind = node.kind; + return kind === 260 /* JsxElement */ + || kind === 270 /* JsxExpression */ + || kind === 261 /* JsxSelfClosingElement */ + || kind === 11 /* JsxText */ + || kind === 264 /* JsxFragment */; + } + ts.isJsxChild = isJsxChild; + /* @internal */ + function isJsxAttributeLike(node) { + var kind = node.kind; + return kind === 267 /* JsxAttribute */ + || kind === 269 /* JsxSpreadAttribute */; + } + ts.isJsxAttributeLike = isJsxAttributeLike; + /* @internal */ + function isStringLiteralOrJsxExpression(node) { + var kind = node.kind; + return kind === 10 /* StringLiteral */ + || kind === 270 /* JsxExpression */; + } + ts.isStringLiteralOrJsxExpression = isStringLiteralOrJsxExpression; + function isJsxOpeningLikeElement(node) { + var kind = node.kind; + return kind === 262 /* JsxOpeningElement */ + || kind === 261 /* JsxSelfClosingElement */; + } + ts.isJsxOpeningLikeElement = isJsxOpeningLikeElement; + // Clauses + function isCaseOrDefaultClause(node) { + var kind = node.kind; + return kind === 271 /* CaseClause */ + || kind === 272 /* DefaultClause */; + } + ts.isCaseOrDefaultClause = isCaseOrDefaultClause; + // JSDoc + /** True if node is of some JSDoc syntax kind. */ + /* @internal */ + function isJSDocNode(node) { + return node.kind >= 283 /* FirstJSDocNode */ && node.kind <= 305 /* LastJSDocNode */; + } + ts.isJSDocNode = isJSDocNode; + /** True if node is of a kind that may contain comment text. */ + function isJSDocCommentContainingNode(node) { + return node.kind === 291 /* JSDocComment */ || isJSDocTag(node) || ts.isJSDocTypeLiteral(node) || ts.isJSDocSignature(node); + } + ts.isJSDocCommentContainingNode = isJSDocCommentContainingNode; + // TODO: determine what this does before making it public. + /* @internal */ + function isJSDocTag(node) { + return node.kind >= 294 /* FirstJSDocTagNode */ && node.kind <= 305 /* LastJSDocTagNode */; + } + ts.isJSDocTag = isJSDocTag; + function isSetAccessor(node) { + return node.kind === 159 /* SetAccessor */; + } + ts.isSetAccessor = isSetAccessor; + function isGetAccessor(node) { + return node.kind === 158 /* GetAccessor */; + } + ts.isGetAccessor = isGetAccessor; + /** True if has jsdoc nodes attached to it. */ + /* @internal */ + // TODO: GH#19856 Would like to return `node is Node & { jsDoc: JSDoc[] }` but it causes long compile times + function hasJSDocNodes(node) { + var jsDoc = node.jsDoc; + return !!jsDoc && jsDoc.length > 0; + } + ts.hasJSDocNodes = hasJSDocNodes; + /** True if has type node attached to it. */ + /* @internal */ + function hasType(node) { + return !!node.type; + } + ts.hasType = hasType; + /** True if has initializer node attached to it. */ + /* @internal */ + function hasInitializer(node) { + return !!node.initializer; + } + ts.hasInitializer = hasInitializer; + /** True if has initializer node attached to it. */ + /* @internal */ + function hasOnlyExpressionInitializer(node) { + return hasInitializer(node) && !ts.isForStatement(node) && !ts.isForInStatement(node) && !ts.isForOfStatement(node) && !ts.isJsxAttribute(node); + } + ts.hasOnlyExpressionInitializer = hasOnlyExpressionInitializer; + function isObjectLiteralElement(node) { + return node.kind === 267 /* JsxAttribute */ || node.kind === 269 /* JsxSpreadAttribute */ || isObjectLiteralElementLike(node); + } + ts.isObjectLiteralElement = isObjectLiteralElement; + /* @internal */ + function isTypeReferenceType(node) { + return node.kind === 164 /* TypeReference */ || node.kind === 211 /* ExpressionWithTypeArguments */; + } + ts.isTypeReferenceType = isTypeReferenceType; + var MAX_SMI_X86 = 1073741823; + /* @internal */ + function guessIndentation(lines) { + var indentation = MAX_SMI_X86; + for (var _i = 0, lines_1 = lines; _i < lines_1.length; _i++) { + var line = lines_1[_i]; + if (!line.length) { + continue; + } + var i = 0; + for (; i < line.length && i < indentation; i++) { + if (!ts.isWhiteSpaceLike(line.charCodeAt(i))) { + break; + } + } + if (i < indentation) { + indentation = i; + } + if (indentation === 0) { + return 0; + } + } + return indentation === MAX_SMI_X86 ? undefined : indentation; + } + ts.guessIndentation = guessIndentation; + function isStringLiteralLike(node) { + return node.kind === 10 /* StringLiteral */ || node.kind === 14 /* NoSubstitutionTemplateLiteral */; + } + ts.isStringLiteralLike = isStringLiteralLike; +})(ts || (ts = {})); +/* @internal */ +(function (ts) { + function isNamedImportsOrExports(node) { + return node.kind === 252 /* NamedImports */ || node.kind === 256 /* NamedExports */; + } + ts.isNamedImportsOrExports = isNamedImportsOrExports; + function Symbol(flags, name) { + this.flags = flags; + this.escapedName = name; + this.declarations = undefined; + this.valueDeclaration = undefined; + this.id = undefined; + this.mergeId = undefined; + this.parent = undefined; + } + function Type(checker, flags) { + this.flags = flags; + if (ts.Debug.isDebugging) { + this.checker = checker; + } + } + function Signature() { } // tslint:disable-line no-empty + function Node(kind, pos, end) { + this.pos = pos; + this.end = end; + this.kind = kind; + this.id = 0; + this.flags = 0 /* None */; + this.modifierFlagsCache = 0 /* None */; + this.transformFlags = 0 /* None */; + this.parent = undefined; + this.original = undefined; + } + function SourceMapSource(fileName, text, skipTrivia) { + this.fileName = fileName; + this.text = text; + this.skipTrivia = skipTrivia || (function (pos) { return pos; }); + } + ts.objectAllocator = { + getNodeConstructor: function () { return Node; }, + getTokenConstructor: function () { return Node; }, + getIdentifierConstructor: function () { return Node; }, + getSourceFileConstructor: function () { return Node; }, + getSymbolConstructor: function () { return Symbol; }, + getTypeConstructor: function () { return Type; }, + getSignatureConstructor: function () { return Signature; }, + getSourceMapSourceConstructor: function () { return SourceMapSource; }, + }; + function formatStringFromArgs(text, args, baseIndex) { + if (baseIndex === void 0) { baseIndex = 0; } + return text.replace(/{(\d+)}/g, function (_match, index) { return "" + ts.Debug.assertDefined(args[+index + baseIndex]); }); + } + ts.formatStringFromArgs = formatStringFromArgs; + function getLocaleSpecificMessage(message) { + return ts.localizedDiagnosticMessages && ts.localizedDiagnosticMessages[message.key] || message.message; + } + ts.getLocaleSpecificMessage = getLocaleSpecificMessage; + function createFileDiagnostic(file, start, length, message) { + ts.Debug.assertGreaterThanOrEqual(start, 0); + ts.Debug.assertGreaterThanOrEqual(length, 0); + if (file) { + ts.Debug.assertLessThanOrEqual(start, file.text.length); + ts.Debug.assertLessThanOrEqual(start + length, file.text.length); + } + var text = getLocaleSpecificMessage(message); + if (arguments.length > 4) { + text = formatStringFromArgs(text, arguments, 4); + } + return { + file: file, + start: start, + length: length, + messageText: text, + category: message.category, + code: message.code, + reportsUnnecessary: message.reportsUnnecessary, + }; + } + ts.createFileDiagnostic = createFileDiagnostic; + function formatMessage(_dummy, message) { + var text = getLocaleSpecificMessage(message); + if (arguments.length > 2) { + text = formatStringFromArgs(text, arguments, 2); + } + return text; + } + ts.formatMessage = formatMessage; + function createCompilerDiagnostic(message) { + var text = getLocaleSpecificMessage(message); + if (arguments.length > 1) { + text = formatStringFromArgs(text, arguments, 1); + } + return { + file: undefined, + start: undefined, + length: undefined, + messageText: text, + category: message.category, + code: message.code, + reportsUnnecessary: message.reportsUnnecessary, + }; + } + ts.createCompilerDiagnostic = createCompilerDiagnostic; + function createCompilerDiagnosticFromMessageChain(chain) { + return { + file: undefined, + start: undefined, + length: undefined, + code: chain.code, + category: chain.category, + messageText: chain.next ? chain : chain.messageText, + }; + } + ts.createCompilerDiagnosticFromMessageChain = createCompilerDiagnosticFromMessageChain; + function chainDiagnosticMessages(details, message) { + var text = getLocaleSpecificMessage(message); + if (arguments.length > 2) { + text = formatStringFromArgs(text, arguments, 2); + } + return { + messageText: text, + category: message.category, + code: message.code, + next: details + }; + } + ts.chainDiagnosticMessages = chainDiagnosticMessages; + function concatenateDiagnosticMessageChains(headChain, tailChain) { + var lastChain = headChain; + while (lastChain.next) { + lastChain = lastChain.next; + } + lastChain.next = tailChain; + return headChain; + } + ts.concatenateDiagnosticMessageChains = concatenateDiagnosticMessageChains; + function getDiagnosticFilePath(diagnostic) { + return diagnostic.file ? diagnostic.file.path : undefined; + } + function compareDiagnostics(d1, d2) { + return compareDiagnosticsSkipRelatedInformation(d1, d2) || + compareRelatedInformation(d1, d2) || + 0 /* EqualTo */; + } + ts.compareDiagnostics = compareDiagnostics; + function compareDiagnosticsSkipRelatedInformation(d1, d2) { + return ts.compareStringsCaseSensitive(getDiagnosticFilePath(d1), getDiagnosticFilePath(d2)) || + ts.compareValues(d1.start, d2.start) || + ts.compareValues(d1.length, d2.length) || + ts.compareValues(d1.code, d2.code) || + compareMessageText(d1.messageText, d2.messageText) || + 0 /* EqualTo */; + } + ts.compareDiagnosticsSkipRelatedInformation = compareDiagnosticsSkipRelatedInformation; + function compareRelatedInformation(d1, d2) { + if (!d1.relatedInformation && !d2.relatedInformation) { + return 0 /* EqualTo */; + } + if (d1.relatedInformation && d2.relatedInformation) { + return ts.compareValues(d1.relatedInformation.length, d2.relatedInformation.length) || ts.forEach(d1.relatedInformation, function (d1i, index) { + var d2i = d2.relatedInformation[index]; + return compareDiagnostics(d1i, d2i); // EqualTo is 0, so falsy, and will cause the next item to be compared + }) || 0 /* EqualTo */; + } + return d1.relatedInformation ? -1 /* LessThan */ : 1 /* GreaterThan */; + } + function compareMessageText(t1, t2) { + var text1 = t1; + var text2 = t2; + while (text1 && text2) { + // We still have both chains. + var string1 = ts.isString(text1) ? text1 : text1.messageText; + var string2 = ts.isString(text2) ? text2 : text2.messageText; + var res = ts.compareStringsCaseSensitive(string1, string2); + if (res) { + return res; + } + text1 = ts.isString(text1) ? undefined : text1.next; + text2 = ts.isString(text2) ? undefined : text2.next; + } + if (!text1 && !text2) { + // if the chains are done, then these messages are the same. + return 0 /* EqualTo */; + } + // We still have one chain remaining. The shorter chain should come first. + return text1 ? 1 /* GreaterThan */ : -1 /* LessThan */; + } + function getEmitScriptTarget(compilerOptions) { + return compilerOptions.target || 0 /* ES3 */; + } + ts.getEmitScriptTarget = getEmitScriptTarget; + function getEmitModuleKind(compilerOptions) { + return typeof compilerOptions.module === "number" ? + compilerOptions.module : + getEmitScriptTarget(compilerOptions) >= 2 /* ES2015 */ ? ts.ModuleKind.ES2015 : ts.ModuleKind.CommonJS; + } + ts.getEmitModuleKind = getEmitModuleKind; + function getEmitModuleResolutionKind(compilerOptions) { + var moduleResolution = compilerOptions.moduleResolution; + if (moduleResolution === undefined) { + moduleResolution = getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS ? ts.ModuleResolutionKind.NodeJs : ts.ModuleResolutionKind.Classic; + } + return moduleResolution; + } + ts.getEmitModuleResolutionKind = getEmitModuleResolutionKind; + function hasJsonModuleEmitEnabled(options) { + switch (getEmitModuleKind(options)) { + case ts.ModuleKind.CommonJS: + case ts.ModuleKind.AMD: + case ts.ModuleKind.ES2015: + case ts.ModuleKind.ESNext: + return true; + default: + return false; + } + } + ts.hasJsonModuleEmitEnabled = hasJsonModuleEmitEnabled; + function unreachableCodeIsError(options) { + return options.allowUnreachableCode === false; + } + ts.unreachableCodeIsError = unreachableCodeIsError; + function unusedLabelIsError(options) { + return options.allowUnusedLabels === false; + } + ts.unusedLabelIsError = unusedLabelIsError; + function getAreDeclarationMapsEnabled(options) { + return !!(getEmitDeclarations(options) && options.declarationMap); + } + ts.getAreDeclarationMapsEnabled = getAreDeclarationMapsEnabled; + function getAllowSyntheticDefaultImports(compilerOptions) { + var moduleKind = getEmitModuleKind(compilerOptions); + return compilerOptions.allowSyntheticDefaultImports !== undefined + ? compilerOptions.allowSyntheticDefaultImports + : compilerOptions.esModuleInterop || + moduleKind === ts.ModuleKind.System; + } + ts.getAllowSyntheticDefaultImports = getAllowSyntheticDefaultImports; + function getEmitDeclarations(compilerOptions) { + return !!(compilerOptions.declaration || compilerOptions.composite); + } + ts.getEmitDeclarations = getEmitDeclarations; + function getStrictOptionValue(compilerOptions, flag) { + return compilerOptions[flag] === undefined ? !!compilerOptions.strict : !!compilerOptions[flag]; + } + ts.getStrictOptionValue = getStrictOptionValue; + function compilerOptionsAffectSemanticDiagnostics(newOptions, oldOptions) { + return oldOptions !== newOptions && + ts.semanticDiagnosticsOptionDeclarations.some(function (option) { return !ts.isJsonEqual(getCompilerOptionValue(oldOptions, option), getCompilerOptionValue(newOptions, option)); }); + } + ts.compilerOptionsAffectSemanticDiagnostics = compilerOptionsAffectSemanticDiagnostics; + function getCompilerOptionValue(options, option) { + return option.strictFlag ? getStrictOptionValue(options, option.name) : options[option.name]; + } + ts.getCompilerOptionValue = getCompilerOptionValue; + function hasZeroOrOneAsteriskCharacter(str) { + var seenAsterisk = false; + for (var i = 0; i < str.length; i++) { + if (str.charCodeAt(i) === 42 /* asterisk */) { + if (!seenAsterisk) { + seenAsterisk = true; + } + else { + // have already seen asterisk + return false; + } + } + } + return true; + } + ts.hasZeroOrOneAsteriskCharacter = hasZeroOrOneAsteriskCharacter; + /** + * Internally, we represent paths as strings with '/' as the directory separator. + * When we make system calls (eg: LanguageServiceHost.getDirectory()), + * we expect the host to correctly handle paths in our specified format. + */ + ts.directorySeparator = "/"; + var altDirectorySeparator = "\\"; + var urlSchemeSeparator = "://"; + var backslashRegExp = /\\/g; + /** + * Normalize path separators. + */ + function normalizeSlashes(path) { + return path.replace(backslashRegExp, ts.directorySeparator); + } + ts.normalizeSlashes = normalizeSlashes; + function isVolumeCharacter(charCode) { + return (charCode >= 97 /* a */ && charCode <= 122 /* z */) || + (charCode >= 65 /* A */ && charCode <= 90 /* Z */); + } + function getFileUrlVolumeSeparatorEnd(url, start) { + var ch0 = url.charCodeAt(start); + if (ch0 === 58 /* colon */) + return start + 1; + if (ch0 === 37 /* percent */ && url.charCodeAt(start + 1) === 51 /* _3 */) { + var ch2 = url.charCodeAt(start + 2); + if (ch2 === 97 /* a */ || ch2 === 65 /* A */) + return start + 3; + } + return -1; + } + /** + * Returns length of the root part of a path or URL (i.e. length of "/", "x:/", "//server/share/, file:///user/files"). + * If the root is part of a URL, the twos-complement of the root length is returned. + */ + function getEncodedRootLength(path) { + if (!path) + return 0; + var ch0 = path.charCodeAt(0); + // POSIX or UNC + if (ch0 === 47 /* slash */ || ch0 === 92 /* backslash */) { + if (path.charCodeAt(1) !== ch0) + return 1; // POSIX: "/" (or non-normalized "\") + var p1 = path.indexOf(ch0 === 47 /* slash */ ? ts.directorySeparator : altDirectorySeparator, 2); + if (p1 < 0) + return path.length; // UNC: "//server" or "\\server" + return p1 + 1; // UNC: "//server/" or "\\server\" + } + // DOS + if (isVolumeCharacter(ch0) && path.charCodeAt(1) === 58 /* colon */) { + var ch2 = path.charCodeAt(2); + if (ch2 === 47 /* slash */ || ch2 === 92 /* backslash */) + return 3; // DOS: "c:/" or "c:\" + if (path.length === 2) + return 2; // DOS: "c:" (but not "c:d") + } + // URL + var schemeEnd = path.indexOf(urlSchemeSeparator); + if (schemeEnd !== -1) { + var authorityStart = schemeEnd + urlSchemeSeparator.length; + var authorityEnd = path.indexOf(ts.directorySeparator, authorityStart); + if (authorityEnd !== -1) { // URL: "file:///", "file://server/", "file://server/path" + // For local "file" URLs, include the leading DOS volume (if present). + // Per https://www.ietf.org/rfc/rfc1738.txt, a host of "" or "localhost" is a + // special case interpreted as "the machine from which the URL is being interpreted". + var scheme = path.slice(0, schemeEnd); + var authority = path.slice(authorityStart, authorityEnd); + if (scheme === "file" && (authority === "" || authority === "localhost") && + isVolumeCharacter(path.charCodeAt(authorityEnd + 1))) { + var volumeSeparatorEnd = getFileUrlVolumeSeparatorEnd(path, authorityEnd + 2); + if (volumeSeparatorEnd !== -1) { + if (path.charCodeAt(volumeSeparatorEnd) === 47 /* slash */) { + // URL: "file:///c:/", "file://localhost/c:/", "file:///c%3a/", "file://localhost/c%3a/" + return ~(volumeSeparatorEnd + 1); + } + if (volumeSeparatorEnd === path.length) { + // URL: "file:///c:", "file://localhost/c:", "file:///c$3a", "file://localhost/c%3a" + // but not "file:///c:d" or "file:///c%3ad" + return ~volumeSeparatorEnd; + } + } + } + return ~(authorityEnd + 1); // URL: "file://server/", "http://server/" + } + return ~path.length; // URL: "file://server", "http://server" + } + // relative + return 0; + } + /** + * Returns length of the root part of a path or URL (i.e. length of "/", "x:/", "//server/share/, file:///user/files"). + * + * For example: + * ```ts + * getRootLength("a") === 0 // "" + * getRootLength("/") === 1 // "/" + * getRootLength("c:") === 2 // "c:" + * getRootLength("c:d") === 0 // "" + * getRootLength("c:/") === 3 // "c:/" + * getRootLength("c:\\") === 3 // "c:\\" + * getRootLength("//server") === 7 // "//server" + * getRootLength("//server/share") === 8 // "//server/" + * getRootLength("\\\\server") === 7 // "\\\\server" + * getRootLength("\\\\server\\share") === 8 // "\\\\server\\" + * getRootLength("file:///path") === 8 // "file:///" + * getRootLength("file:///c:") === 10 // "file:///c:" + * getRootLength("file:///c:d") === 8 // "file:///" + * getRootLength("file:///c:/path") === 11 // "file:///c:/" + * getRootLength("file://server") === 13 // "file://server" + * getRootLength("file://server/path") === 14 // "file://server/" + * getRootLength("http://server") === 13 // "http://server" + * getRootLength("http://server/path") === 14 // "http://server/" + * ``` + */ + function getRootLength(path) { + var rootLength = getEncodedRootLength(path); + return rootLength < 0 ? ~rootLength : rootLength; + } + ts.getRootLength = getRootLength; + // TODO(rbuckton): replace references with `resolvePath` + function normalizePath(path) { + return ts.resolvePath(path); + } + ts.normalizePath = normalizePath; + function normalizePathAndParts(path) { + path = normalizeSlashes(path); + var _a = reducePathComponents(getPathComponents(path)), root = _a[0], parts = _a.slice(1); + if (parts.length) { + var joinedParts = root + parts.join(ts.directorySeparator); + return { path: ts.hasTrailingDirectorySeparator(path) ? ts.ensureTrailingDirectorySeparator(joinedParts) : joinedParts, parts: parts }; + } + else { + return { path: root, parts: parts }; + } + } + ts.normalizePathAndParts = normalizePathAndParts; + function getDirectoryPath(path) { + path = normalizeSlashes(path); + // If the path provided is itself the root, then return it. + var rootLength = getRootLength(path); + if (rootLength === path.length) + return path; + // return the leading portion of the path up to the last (non-terminal) directory separator + // but not including any trailing directory separator. + path = ts.removeTrailingDirectorySeparator(path); + return path.slice(0, Math.max(rootLength, path.lastIndexOf(ts.directorySeparator))); + } + ts.getDirectoryPath = getDirectoryPath; + function startsWithDirectory(fileName, directoryName, getCanonicalFileName) { + var canonicalFileName = getCanonicalFileName(fileName); + var canonicalDirectoryName = getCanonicalFileName(directoryName); + return ts.startsWith(canonicalFileName, canonicalDirectoryName + "/") || ts.startsWith(canonicalFileName, canonicalDirectoryName + "\\"); + } + ts.startsWithDirectory = startsWithDirectory; + function isUrl(path) { + return getEncodedRootLength(path) < 0; + } + ts.isUrl = isUrl; + function pathIsRelative(path) { + return /^\.\.?($|[\\/])/.test(path); + } + ts.pathIsRelative = pathIsRelative; + /** + * Determines whether a path is an absolute path (e.g. starts with `/`, or a dos path + * like `c:`, `c:\` or `c:/`). + */ + function isRootedDiskPath(path) { + return getEncodedRootLength(path) > 0; + } + ts.isRootedDiskPath = isRootedDiskPath; + /** + * Determines whether a path consists only of a path root. + */ + function isDiskPathRoot(path) { + var rootLength = getEncodedRootLength(path); + return rootLength > 0 && rootLength === path.length; + } + ts.isDiskPathRoot = isDiskPathRoot; + function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) { + return !isRootedDiskPath(absoluteOrRelativePath) + ? absoluteOrRelativePath + : ts.getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); + } + ts.convertToRelativePath = convertToRelativePath; + function pathComponents(path, rootLength) { + var root = path.substring(0, rootLength); + var rest = path.substring(rootLength).split(ts.directorySeparator); + if (rest.length && !ts.lastOrUndefined(rest)) + rest.pop(); + return [root].concat(rest); + } + /** + * Parse a path into an array containing a root component (at index 0) and zero or more path + * components (at indices > 0). The result is not normalized. + * If the path is relative, the root component is `""`. + * If the path is absolute, the root component includes the first path separator (`/`). + */ + function getPathComponents(path, currentDirectory) { + if (currentDirectory === void 0) { currentDirectory = ""; } + path = ts.combinePaths(currentDirectory, path); + var rootLength = getRootLength(path); + return pathComponents(path, rootLength); + } + ts.getPathComponents = getPathComponents; + /** + * Reduce an array of path components to a more simplified path by navigating any + * `"."` or `".."` entries in the path. + */ + function reducePathComponents(components) { + if (!ts.some(components)) + return []; + var reduced = [components[0]]; + for (var i = 1; i < components.length; i++) { + var component = components[i]; + if (!component) + continue; + if (component === ".") + continue; + if (component === "..") { + if (reduced.length > 1) { + if (reduced[reduced.length - 1] !== "..") { + reduced.pop(); + continue; + } + } + else if (reduced[0]) + continue; + } + reduced.push(component); + } + return reduced; + } + ts.reducePathComponents = reducePathComponents; + /** + * Parse a path into an array containing a root component (at index 0) and zero or more path + * components (at indices > 0). The result is normalized. + * If the path is relative, the root component is `""`. + * If the path is absolute, the root component includes the first path separator (`/`). + */ + function getNormalizedPathComponents(path, currentDirectory) { + return reducePathComponents(getPathComponents(path, currentDirectory)); + } + ts.getNormalizedPathComponents = getNormalizedPathComponents; + function getNormalizedAbsolutePath(fileName, currentDirectory) { + return getPathFromPathComponents(getNormalizedPathComponents(fileName, currentDirectory)); + } + ts.getNormalizedAbsolutePath = getNormalizedAbsolutePath; + /** + * Formats a parsed path consisting of a root component (at index 0) and zero or more path + * segments (at indices > 0). + */ + function getPathFromPathComponents(pathComponents) { + if (pathComponents.length === 0) + return ""; + var root = pathComponents[0] && ts.ensureTrailingDirectorySeparator(pathComponents[0]); + return root + pathComponents.slice(1).join(ts.directorySeparator); + } + ts.getPathFromPathComponents = getPathFromPathComponents; +})(ts || (ts = {})); +/* @internal */ +(function (ts) { + function getPathComponentsRelativeTo(from, to, stringEqualityComparer, getCanonicalFileName) { + var fromComponents = ts.reducePathComponents(ts.getPathComponents(from)); + var toComponents = ts.reducePathComponents(ts.getPathComponents(to)); + var start; + for (start = 0; start < fromComponents.length && start < toComponents.length; start++) { + var fromComponent = getCanonicalFileName(fromComponents[start]); + var toComponent = getCanonicalFileName(toComponents[start]); + var comparer = start === 0 ? ts.equateStringsCaseInsensitive : stringEqualityComparer; + if (!comparer(fromComponent, toComponent)) + break; + } + if (start === 0) { + return toComponents; + } + var components = toComponents.slice(start); + var relative = []; + for (; start < fromComponents.length; start++) { + relative.push(".."); + } + return [""].concat(relative, components); + } + ts.getPathComponentsRelativeTo = getPathComponentsRelativeTo; + function getRelativePathFromFile(from, to, getCanonicalFileName) { + return ensurePathIsNonModuleName(getRelativePathFromDirectory(ts.getDirectoryPath(from), to, getCanonicalFileName)); + } + ts.getRelativePathFromFile = getRelativePathFromFile; + function getRelativePathFromDirectory(fromDirectory, to, getCanonicalFileNameOrIgnoreCase) { + Debug.assert((ts.getRootLength(fromDirectory) > 0) === (ts.getRootLength(to) > 0), "Paths must either both be absolute or both be relative"); + var getCanonicalFileName = typeof getCanonicalFileNameOrIgnoreCase === "function" ? getCanonicalFileNameOrIgnoreCase : ts.identity; + var ignoreCase = typeof getCanonicalFileNameOrIgnoreCase === "boolean" ? getCanonicalFileNameOrIgnoreCase : false; + var pathComponents = getPathComponentsRelativeTo(fromDirectory, to, ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive, getCanonicalFileName); + return ts.getPathFromPathComponents(pathComponents); + } + ts.getRelativePathFromDirectory = getRelativePathFromDirectory; + function getRelativePathToDirectoryOrUrl(directoryPathOrUrl, relativeOrAbsolutePath, currentDirectory, getCanonicalFileName, isAbsolutePathAnUrl) { + var pathComponents = getPathComponentsRelativeTo(resolvePath(currentDirectory, directoryPathOrUrl), resolvePath(currentDirectory, relativeOrAbsolutePath), ts.equateStringsCaseSensitive, getCanonicalFileName); + var firstComponent = pathComponents[0]; + if (isAbsolutePathAnUrl && ts.isRootedDiskPath(firstComponent)) { + var prefix = firstComponent.charAt(0) === ts.directorySeparator ? "file://" : "file:///"; + pathComponents[0] = prefix + firstComponent; + } + return ts.getPathFromPathComponents(pathComponents); + } + ts.getRelativePathToDirectoryOrUrl = getRelativePathToDirectoryOrUrl; + /** + * Ensures a path is either absolute (prefixed with `/` or `c:`) or dot-relative (prefixed + * with `./` or `../`) so as not to be confused with an unprefixed module name. + */ + function ensurePathIsNonModuleName(path) { + return ts.getRootLength(path) === 0 && !ts.pathIsRelative(path) ? "./" + path : path; + } + ts.ensurePathIsNonModuleName = ensurePathIsNonModuleName; + function getBaseFileName(path, extensions, ignoreCase) { + path = ts.normalizeSlashes(path); + // if the path provided is itself the root, then it has not file name. + var rootLength = ts.getRootLength(path); + if (rootLength === path.length) + return ""; + // return the trailing portion of the path starting after the last (non-terminal) directory + // separator but not including any trailing directory separator. + path = removeTrailingDirectorySeparator(path); + var name = path.slice(Math.max(ts.getRootLength(path), path.lastIndexOf(ts.directorySeparator) + 1)); + var extension = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(name, extensions, ignoreCase) : undefined; + return extension ? name.slice(0, name.length - extension.length) : name; + } + ts.getBaseFileName = getBaseFileName; + /** + * Combines paths. If a path is absolute, it replaces any previous path. + */ + function combinePaths(path) { + var paths = []; + for (var _i = 1; _i < arguments.length; _i++) { + paths[_i - 1] = arguments[_i]; + } + if (path) + path = ts.normalizeSlashes(path); + for (var _a = 0, paths_1 = paths; _a < paths_1.length; _a++) { + var relativePath = paths_1[_a]; + if (!relativePath) + continue; + relativePath = ts.normalizeSlashes(relativePath); + if (!path || ts.getRootLength(relativePath) !== 0) { + path = relativePath; + } + else { + path = ensureTrailingDirectorySeparator(path) + relativePath; + } + } + return path; + } + ts.combinePaths = combinePaths; + /** + * Combines and resolves paths. If a path is absolute, it replaces any previous path. Any + * `.` and `..` path components are resolved. + */ + function resolvePath(path) { + var paths = []; + for (var _i = 1; _i < arguments.length; _i++) { + paths[_i - 1] = arguments[_i]; + } + var combined = ts.some(paths) ? combinePaths.apply(void 0, [path].concat(paths)) : ts.normalizeSlashes(path); + var normalized = ts.getPathFromPathComponents(ts.reducePathComponents(ts.getPathComponents(combined))); + return normalized && hasTrailingDirectorySeparator(combined) ? ensureTrailingDirectorySeparator(normalized) : normalized; + } + ts.resolvePath = resolvePath; + /** + * Determines whether a path has a trailing separator (`/` or `\\`). + */ + function hasTrailingDirectorySeparator(path) { + if (path.length === 0) + return false; + var ch = path.charCodeAt(path.length - 1); + return ch === 47 /* slash */ || ch === 92 /* backslash */; + } + ts.hasTrailingDirectorySeparator = hasTrailingDirectorySeparator; + function removeTrailingDirectorySeparator(path) { + if (hasTrailingDirectorySeparator(path)) { + return path.substr(0, path.length - 1); + } + return path; + } + ts.removeTrailingDirectorySeparator = removeTrailingDirectorySeparator; + function ensureTrailingDirectorySeparator(path) { + if (!hasTrailingDirectorySeparator(path)) { + return path + ts.directorySeparator; + } + return path; + } + ts.ensureTrailingDirectorySeparator = ensureTrailingDirectorySeparator; + function comparePathsWorker(a, b, componentComparer) { + if (a === b) + return 0 /* EqualTo */; + if (a === undefined) + return -1 /* LessThan */; + if (b === undefined) + return 1 /* GreaterThan */; + var aComponents = ts.reducePathComponents(ts.getPathComponents(a)); + var bComponents = ts.reducePathComponents(ts.getPathComponents(b)); + var sharedLength = Math.min(aComponents.length, bComponents.length); + for (var i = 0; i < sharedLength; i++) { + var stringComparer = i === 0 ? ts.compareStringsCaseInsensitive : componentComparer; + var result = stringComparer(aComponents[i], bComponents[i]); + if (result !== 0 /* EqualTo */) { + return result; + } + } + return ts.compareValues(aComponents.length, bComponents.length); + } + /** + * Performs a case-sensitive comparison of two paths. + */ + function comparePathsCaseSensitive(a, b) { + return comparePathsWorker(a, b, ts.compareStringsCaseSensitive); + } + ts.comparePathsCaseSensitive = comparePathsCaseSensitive; + /** + * Performs a case-insensitive comparison of two paths. + */ + function comparePathsCaseInsensitive(a, b) { + return comparePathsWorker(a, b, ts.compareStringsCaseInsensitive); + } + ts.comparePathsCaseInsensitive = comparePathsCaseInsensitive; + function comparePaths(a, b, currentDirectory, ignoreCase) { + if (typeof currentDirectory === "string") { + a = combinePaths(currentDirectory, a); + b = combinePaths(currentDirectory, b); + } + else if (typeof currentDirectory === "boolean") { + ignoreCase = currentDirectory; + } + return comparePathsWorker(a, b, ts.getStringComparer(ignoreCase)); + } + ts.comparePaths = comparePaths; + function containsPath(parent, child, currentDirectory, ignoreCase) { + if (typeof currentDirectory === "string") { + parent = combinePaths(currentDirectory, parent); + child = combinePaths(currentDirectory, child); + } + else if (typeof currentDirectory === "boolean") { + ignoreCase = currentDirectory; + } + if (parent === undefined || child === undefined) + return false; + if (parent === child) + return true; + var parentComponents = ts.reducePathComponents(ts.getPathComponents(parent)); + var childComponents = ts.reducePathComponents(ts.getPathComponents(child)); + if (childComponents.length < parentComponents.length) { + return false; + } + var componentEqualityComparer = ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive; + for (var i = 0; i < parentComponents.length; i++) { + var equalityComparer = i === 0 ? ts.equateStringsCaseInsensitive : componentEqualityComparer; + if (!equalityComparer(parentComponents[i], childComponents[i])) { + return false; + } + } + return true; + } + ts.containsPath = containsPath; + function isDirectorySeparator(charCode) { + return charCode === 47 /* slash */ || charCode === 92 /* backslash */; + } + function stripLeadingDirectorySeparator(s) { + return isDirectorySeparator(s.charCodeAt(0)) ? s.slice(1) : undefined; + } + function tryRemoveDirectoryPrefix(path, dirPath, getCanonicalFileName) { + var withoutPrefix = ts.tryRemovePrefix(path, dirPath, getCanonicalFileName); + return withoutPrefix === undefined ? undefined : stripLeadingDirectorySeparator(withoutPrefix); + } + ts.tryRemoveDirectoryPrefix = tryRemoveDirectoryPrefix; + // Reserved characters, forces escaping of any non-word (or digit), non-whitespace character. + // It may be inefficient (we could just match (/[-[\]{}()*+?.,\\^$|#\s]/g), but this is future + // proof. + var reservedCharacterPattern = /[^\w\s\/]/g; + function regExpEscape(text) { + return text.replace(reservedCharacterPattern, escapeRegExpCharacter); + } + ts.regExpEscape = regExpEscape; + function escapeRegExpCharacter(match) { + return "\\" + match; + } + var wildcardCharCodes = [42 /* asterisk */, 63 /* question */]; + function hasExtension(fileName) { + return ts.stringContains(getBaseFileName(fileName), "."); + } + ts.hasExtension = hasExtension; + ts.commonPackageFolders = ["node_modules", "bower_components", "jspm_packages"]; + var implicitExcludePathRegexPattern = "(?!(" + ts.commonPackageFolders.join("|") + ")(/|$))"; + var filesMatcher = { + /** + * Matches any single directory segment unless it is the last segment and a .min.js file + * Breakdown: + * [^./] # matches everything up to the first . character (excluding directory separators) + * (\\.(?!min\\.js$))? # matches . characters but not if they are part of the .min.js file extension + */ + singleAsteriskRegexFragment: "([^./]|(\\.(?!min\\.js$))?)*", + /** + * Regex for the ** wildcard. Matches any number of subdirectories. When used for including + * files or directories, does not match subdirectories that start with a . character + */ + doubleAsteriskRegexFragment: "(/" + implicitExcludePathRegexPattern + "[^/.][^/]*)*?", + replaceWildcardCharacter: function (match) { return replaceWildcardCharacter(match, filesMatcher.singleAsteriskRegexFragment); } + }; + var directoriesMatcher = { + singleAsteriskRegexFragment: "[^/]*", + /** + * Regex for the ** wildcard. Matches any number of subdirectories. When used for including + * files or directories, does not match subdirectories that start with a . character + */ + doubleAsteriskRegexFragment: "(/" + implicitExcludePathRegexPattern + "[^/.][^/]*)*?", + replaceWildcardCharacter: function (match) { return replaceWildcardCharacter(match, directoriesMatcher.singleAsteriskRegexFragment); } + }; + var excludeMatcher = { + singleAsteriskRegexFragment: "[^/]*", + doubleAsteriskRegexFragment: "(/.+?)?", + replaceWildcardCharacter: function (match) { return replaceWildcardCharacter(match, excludeMatcher.singleAsteriskRegexFragment); } + }; + var wildcardMatchers = { + files: filesMatcher, + directories: directoriesMatcher, + exclude: excludeMatcher + }; + function getRegularExpressionForWildcard(specs, basePath, usage) { + var patterns = getRegularExpressionsForWildcards(specs, basePath, usage); + if (!patterns || !patterns.length) { + return undefined; + } + var pattern = patterns.map(function (pattern) { return "(" + pattern + ")"; }).join("|"); + // If excluding, match "foo/bar/baz...", but if including, only allow "foo". + var terminator = usage === "exclude" ? "($|/)" : "$"; + return "^(" + pattern + ")" + terminator; + } + ts.getRegularExpressionForWildcard = getRegularExpressionForWildcard; + function getRegularExpressionsForWildcards(specs, basePath, usage) { + if (specs === undefined || specs.length === 0) { + return undefined; + } + return ts.flatMap(specs, function (spec) { + return spec && getSubPatternFromSpec(spec, basePath, usage, wildcardMatchers[usage]); + }); + } + ts.getRegularExpressionsForWildcards = getRegularExpressionsForWildcards; + /** + * An "includes" path "foo" is implicitly a glob "foo/** /*" (without the space) if its last component has no extension, + * and does not contain any glob characters itself. + */ + function isImplicitGlob(lastPathComponent) { + return !/[.*?]/.test(lastPathComponent); + } + ts.isImplicitGlob = isImplicitGlob; + function getSubPatternFromSpec(spec, basePath, usage, _a) { + var singleAsteriskRegexFragment = _a.singleAsteriskRegexFragment, doubleAsteriskRegexFragment = _a.doubleAsteriskRegexFragment, replaceWildcardCharacter = _a.replaceWildcardCharacter; + var subpattern = ""; + var hasWrittenComponent = false; + var components = ts.getNormalizedPathComponents(spec, basePath); + var lastComponent = ts.last(components); + if (usage !== "exclude" && lastComponent === "**") { + return undefined; + } + // getNormalizedPathComponents includes the separator for the root component. + // We need to remove to create our regex correctly. + components[0] = removeTrailingDirectorySeparator(components[0]); + if (isImplicitGlob(lastComponent)) { + components.push("**", "*"); + } + var optionalCount = 0; + for (var _i = 0, components_1 = components; _i < components_1.length; _i++) { + var component = components_1[_i]; + if (component === "**") { + subpattern += doubleAsteriskRegexFragment; + } + else { + if (usage === "directories") { + subpattern += "("; + optionalCount++; + } + if (hasWrittenComponent) { + subpattern += ts.directorySeparator; + } + if (usage !== "exclude") { + var componentPattern = ""; + // The * and ? wildcards should not match directories or files that start with . if they + // appear first in a component. Dotted directories and files can be included explicitly + // like so: **/.*/.* + if (component.charCodeAt(0) === 42 /* asterisk */) { + componentPattern += "([^./]" + singleAsteriskRegexFragment + ")?"; + component = component.substr(1); + } + else if (component.charCodeAt(0) === 63 /* question */) { + componentPattern += "[^./]"; + component = component.substr(1); + } + componentPattern += component.replace(reservedCharacterPattern, replaceWildcardCharacter); + // Patterns should not include subfolders like node_modules unless they are + // explicitly included as part of the path. + // + // As an optimization, if the component pattern is the same as the component, + // then there definitely were no wildcard characters and we do not need to + // add the exclusion pattern. + if (componentPattern !== component) { + subpattern += implicitExcludePathRegexPattern; + } + subpattern += componentPattern; + } + else { + subpattern += component.replace(reservedCharacterPattern, replaceWildcardCharacter); + } + } + hasWrittenComponent = true; + } + while (optionalCount > 0) { + subpattern += ")?"; + optionalCount--; + } + return subpattern; + } + function replaceWildcardCharacter(match, singleAsteriskRegexFragment) { + return match === "*" ? singleAsteriskRegexFragment : match === "?" ? "[^/]" : "\\" + match; + } + /** @param path directory of the tsconfig.json */ + function getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory) { + path = ts.normalizePath(path); + currentDirectory = ts.normalizePath(currentDirectory); + var absolutePath = combinePaths(currentDirectory, path); + return { + includeFilePatterns: ts.map(getRegularExpressionsForWildcards(includes, absolutePath, "files"), function (pattern) { return "^" + pattern + "$"; }), + includeFilePattern: getRegularExpressionForWildcard(includes, absolutePath, "files"), + includeDirectoryPattern: getRegularExpressionForWildcard(includes, absolutePath, "directories"), + excludePattern: getRegularExpressionForWildcard(excludes, absolutePath, "exclude"), + basePaths: getBasePaths(path, includes, useCaseSensitiveFileNames) + }; + } + ts.getFileMatcherPatterns = getFileMatcherPatterns; + function getRegexFromPattern(pattern, useCaseSensitiveFileNames) { + return new RegExp(pattern, useCaseSensitiveFileNames ? "" : "i"); + } + ts.getRegexFromPattern = getRegexFromPattern; + /** @param path directory of the tsconfig.json */ + function matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries) { + path = ts.normalizePath(path); + currentDirectory = ts.normalizePath(currentDirectory); + var patterns = getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory); + var includeFileRegexes = patterns.includeFilePatterns && patterns.includeFilePatterns.map(function (pattern) { return getRegexFromPattern(pattern, useCaseSensitiveFileNames); }); + var includeDirectoryRegex = patterns.includeDirectoryPattern && getRegexFromPattern(patterns.includeDirectoryPattern, useCaseSensitiveFileNames); + var excludeRegex = patterns.excludePattern && getRegexFromPattern(patterns.excludePattern, useCaseSensitiveFileNames); + // Associate an array of results with each include regex. This keeps results in order of the "include" order. + // If there are no "includes", then just put everything in results[0]. + var results = includeFileRegexes ? includeFileRegexes.map(function () { return []; }) : [[]]; + for (var _i = 0, _a = patterns.basePaths; _i < _a.length; _i++) { + var basePath = _a[_i]; + visitDirectory(basePath, combinePaths(currentDirectory, basePath), depth); + } + return ts.flatten(results); + function visitDirectory(path, absolutePath, depth) { + var _a = getFileSystemEntries(path), files = _a.files, directories = _a.directories; + var _loop_1 = function (current) { + var name = combinePaths(path, current); + var absoluteName = combinePaths(absolutePath, current); + if (extensions && !ts.fileExtensionIsOneOf(name, extensions)) + return "continue"; + if (excludeRegex && excludeRegex.test(absoluteName)) + return "continue"; + if (!includeFileRegexes) { + results[0].push(name); + } + else { + var includeIndex = ts.findIndex(includeFileRegexes, function (re) { return re.test(absoluteName); }); + if (includeIndex !== -1) { + results[includeIndex].push(name); + } + } + }; + for (var _i = 0, _b = ts.sort(files, ts.compareStringsCaseSensitive); _i < _b.length; _i++) { + var current = _b[_i]; + _loop_1(current); + } + if (depth !== undefined) { + depth--; + if (depth === 0) { + return; + } + } + for (var _c = 0, _d = ts.sort(directories, ts.compareStringsCaseSensitive); _c < _d.length; _c++) { + var current = _d[_c]; + var name = combinePaths(path, current); + var absoluteName = combinePaths(absolutePath, current); + if ((!includeDirectoryRegex || includeDirectoryRegex.test(absoluteName)) && + (!excludeRegex || !excludeRegex.test(absoluteName))) { + visitDirectory(name, absoluteName, depth); + } + } + } + } + ts.matchFiles = matchFiles; + /** + * Computes the unique non-wildcard base paths amongst the provided include patterns. + */ + function getBasePaths(path, includes, useCaseSensitiveFileNames) { + // Storage for our results in the form of literal paths (e.g. the paths as written by the user). + var basePaths = [path]; + if (includes) { + // Storage for literal base paths amongst the include patterns. + var includeBasePaths = []; + for (var _i = 0, includes_1 = includes; _i < includes_1.length; _i++) { + var include = includes_1[_i]; + // We also need to check the relative paths by converting them to absolute and normalizing + // in case they escape the base path (e.g "..\somedirectory") + var absolute = ts.isRootedDiskPath(include) ? include : ts.normalizePath(combinePaths(path, include)); + // Append the literal and canonical candidate base paths. + includeBasePaths.push(getIncludeBasePath(absolute)); + } + // Sort the offsets array using either the literal or canonical path representations. + includeBasePaths.sort(ts.getStringComparer(!useCaseSensitiveFileNames)); + var _loop_2 = function (includeBasePath) { + if (ts.every(basePaths, function (basePath) { return !containsPath(basePath, includeBasePath, path, !useCaseSensitiveFileNames); })) { + basePaths.push(includeBasePath); + } + }; + // Iterate over each include base path and include unique base paths that are not a + // subpath of an existing base path + for (var _a = 0, includeBasePaths_1 = includeBasePaths; _a < includeBasePaths_1.length; _a++) { + var includeBasePath = includeBasePaths_1[_a]; + _loop_2(includeBasePath); + } + } + return basePaths; + } + function getIncludeBasePath(absolute) { + var wildcardOffset = ts.indexOfAnyCharCode(absolute, wildcardCharCodes); + if (wildcardOffset < 0) { + // No "*" or "?" in the path + return !hasExtension(absolute) + ? absolute + : removeTrailingDirectorySeparator(ts.getDirectoryPath(absolute)); + } + return absolute.substring(0, absolute.lastIndexOf(ts.directorySeparator, wildcardOffset)); + } + function ensureScriptKind(fileName, scriptKind) { + // Using scriptKind as a condition handles both: + // - 'scriptKind' is unspecified and thus it is `undefined` + // - 'scriptKind' is set and it is `Unknown` (0) + // If the 'scriptKind' is 'undefined' or 'Unknown' then we attempt + // to get the ScriptKind from the file name. If it cannot be resolved + // from the file name then the default 'TS' script kind is returned. + return scriptKind || getScriptKindFromFileName(fileName) || 3 /* TS */; + } + ts.ensureScriptKind = ensureScriptKind; + function getScriptKindFromFileName(fileName) { + var ext = fileName.substr(fileName.lastIndexOf(".")); + switch (ext.toLowerCase()) { + case ".js" /* Js */: + return 1 /* JS */; + case ".jsx" /* Jsx */: + return 2 /* JSX */; + case ".ts" /* Ts */: + return 3 /* TS */; + case ".tsx" /* Tsx */: + return 4 /* TSX */; + case ".json" /* Json */: + return 6 /* JSON */; + default: + return 0 /* Unknown */; + } + } + ts.getScriptKindFromFileName = getScriptKindFromFileName; + /** + * List of supported extensions in order of file resolution precedence. + */ + ts.supportedTSExtensions = [".ts" /* Ts */, ".tsx" /* Tsx */, ".d.ts" /* Dts */]; + ts.supportedTSExtensionsWithJson = [".ts" /* Ts */, ".tsx" /* Tsx */, ".d.ts" /* Dts */, ".json" /* Json */]; + /** Must have ".d.ts" first because if ".ts" goes first, that will be detected as the extension instead of ".d.ts". */ + ts.supportedTSExtensionsForExtractExtension = [".d.ts" /* Dts */, ".ts" /* Ts */, ".tsx" /* Tsx */]; + ts.supportedJSExtensions = [".js" /* Js */, ".jsx" /* Jsx */]; + ts.supportedJSAndJsonExtensions = [".js" /* Js */, ".jsx" /* Jsx */, ".json" /* Json */]; + var allSupportedExtensions = ts.supportedTSExtensions.concat(ts.supportedJSExtensions); + var allSupportedExtensionsWithJson = ts.supportedTSExtensions.concat(ts.supportedJSExtensions, [".json" /* Json */]); + function getSupportedExtensions(options, extraFileExtensions) { + var needJsExtensions = options && options.allowJs; + if (!extraFileExtensions || extraFileExtensions.length === 0) { + return needJsExtensions ? allSupportedExtensions : ts.supportedTSExtensions; + } + var extensions = (needJsExtensions ? allSupportedExtensions : ts.supportedTSExtensions).concat(ts.mapDefined(extraFileExtensions, function (x) { return x.scriptKind === 7 /* Deferred */ || needJsExtensions && isJSLike(x.scriptKind) ? x.extension : undefined; })); + return ts.deduplicate(extensions, ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive); + } + ts.getSupportedExtensions = getSupportedExtensions; + function getSuppoertedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions) { + if (!options || !options.resolveJsonModule) { + return supportedExtensions; + } + if (supportedExtensions === allSupportedExtensions) { + return allSupportedExtensionsWithJson; + } + if (supportedExtensions === ts.supportedTSExtensions) { + return ts.supportedTSExtensionsWithJson; + } + return supportedExtensions.concat([".json" /* Json */]); + } + ts.getSuppoertedExtensionsWithJsonIfResolveJsonModule = getSuppoertedExtensionsWithJsonIfResolveJsonModule; + function isJSLike(scriptKind) { + return scriptKind === 1 /* JS */ || scriptKind === 2 /* JSX */; + } + function hasJSFileExtension(fileName) { + return ts.some(ts.supportedJSExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + } + ts.hasJSFileExtension = hasJSFileExtension; + function hasJSOrJsonFileExtension(fileName) { + return ts.supportedJSAndJsonExtensions.some(function (ext) { return ts.fileExtensionIs(fileName, ext); }); + } + ts.hasJSOrJsonFileExtension = hasJSOrJsonFileExtension; + function hasTSFileExtension(fileName) { + return ts.some(ts.supportedTSExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + } + ts.hasTSFileExtension = hasTSFileExtension; + function isSupportedSourceFileName(fileName, compilerOptions, extraFileExtensions) { + if (!fileName) { + return false; + } + var supportedExtensions = getSupportedExtensions(compilerOptions, extraFileExtensions); + for (var _i = 0, _a = getSuppoertedExtensionsWithJsonIfResolveJsonModule(compilerOptions, supportedExtensions); _i < _a.length; _i++) { + var extension = _a[_i]; + if (ts.fileExtensionIs(fileName, extension)) { + return true; + } + } + return false; + } + ts.isSupportedSourceFileName = isSupportedSourceFileName; + /** + * Extension boundaries by priority. Lower numbers indicate higher priorities, and are + * aligned to the offset of the highest priority extension in the + * allSupportedExtensions array. + */ + var ExtensionPriority; + (function (ExtensionPriority) { + ExtensionPriority[ExtensionPriority["TypeScriptFiles"] = 0] = "TypeScriptFiles"; + ExtensionPriority[ExtensionPriority["DeclarationAndJavaScriptFiles"] = 2] = "DeclarationAndJavaScriptFiles"; + ExtensionPriority[ExtensionPriority["Highest"] = 0] = "Highest"; + ExtensionPriority[ExtensionPriority["Lowest"] = 2] = "Lowest"; + })(ExtensionPriority = ts.ExtensionPriority || (ts.ExtensionPriority = {})); + function getExtensionPriority(path, supportedExtensions) { + for (var i = supportedExtensions.length - 1; i >= 0; i--) { + if (ts.fileExtensionIs(path, supportedExtensions[i])) { + return adjustExtensionPriority(i, supportedExtensions); + } + } + // If its not in the list of supported extensions, this is likely a + // TypeScript file with a non-ts extension + return 0 /* Highest */; + } + ts.getExtensionPriority = getExtensionPriority; + /** + * Adjusts an extension priority to be the highest priority within the same range. + */ + function adjustExtensionPriority(extensionPriority, supportedExtensions) { + if (extensionPriority < 2 /* DeclarationAndJavaScriptFiles */) { + return 0 /* TypeScriptFiles */; + } + else if (extensionPriority < supportedExtensions.length) { + return 2 /* DeclarationAndJavaScriptFiles */; + } + else { + return supportedExtensions.length; + } + } + ts.adjustExtensionPriority = adjustExtensionPriority; + /** + * Gets the next lowest extension priority for a given priority. + */ + function getNextLowestExtensionPriority(extensionPriority, supportedExtensions) { + if (extensionPriority < 2 /* DeclarationAndJavaScriptFiles */) { + return 2 /* DeclarationAndJavaScriptFiles */; + } + else { + return supportedExtensions.length; + } + } + ts.getNextLowestExtensionPriority = getNextLowestExtensionPriority; + var extensionsToRemove = [".d.ts" /* Dts */, ".ts" /* Ts */, ".js" /* Js */, ".tsx" /* Tsx */, ".jsx" /* Jsx */, ".json" /* Json */]; + function removeFileExtension(path) { + for (var _i = 0, extensionsToRemove_1 = extensionsToRemove; _i < extensionsToRemove_1.length; _i++) { + var ext = extensionsToRemove_1[_i]; + var extensionless = tryRemoveExtension(path, ext); + if (extensionless !== undefined) { + return extensionless; + } + } + return path; + } + ts.removeFileExtension = removeFileExtension; + function tryRemoveExtension(path, extension) { + return ts.fileExtensionIs(path, extension) ? removeExtension(path, extension) : undefined; + } + ts.tryRemoveExtension = tryRemoveExtension; + function removeExtension(path, extension) { + return path.substring(0, path.length - extension.length); + } + ts.removeExtension = removeExtension; + function changeExtension(path, newExtension) { + return changeAnyExtension(path, newExtension, extensionsToRemove, /*ignoreCase*/ false); + } + ts.changeExtension = changeExtension; + function changeAnyExtension(path, ext, extensions, ignoreCase) { + var pathext = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(path, extensions, ignoreCase) : getAnyExtensionFromPath(path); + return pathext ? path.slice(0, path.length - pathext.length) + (ts.startsWith(ext, ".") ? ext : "." + ext) : path; + } + ts.changeAnyExtension = changeAnyExtension; + var Debug; + (function (Debug) { + function showSymbol(symbol) { + var symbolFlags = ts.SymbolFlags; + return "{ flags: " + (symbolFlags ? showFlags(symbol.flags, symbolFlags) : symbol.flags) + "; declarations: " + ts.map(symbol.declarations, showSyntaxKind) + " }"; + } + Debug.showSymbol = showSymbol; + function showFlags(flags, flagsEnum) { + var out = []; + for (var pow = 0; pow <= 30; pow++) { + var n = 1 << pow; + if (flags & n) { + out.push(flagsEnum[n]); + } + } + return out.join("|"); + } + function showSyntaxKind(node) { + var syntaxKind = ts.SyntaxKind; + return syntaxKind ? syntaxKind[node.kind] : node.kind.toString(); + } + Debug.showSyntaxKind = showSyntaxKind; + })(Debug = ts.Debug || (ts.Debug = {})); + function tryParsePattern(pattern) { + // This should be verified outside of here and a proper error thrown. + Debug.assert(ts.hasZeroOrOneAsteriskCharacter(pattern)); + var indexOfStar = pattern.indexOf("*"); + return indexOfStar === -1 ? undefined : { + prefix: pattern.substr(0, indexOfStar), + suffix: pattern.substr(indexOfStar + 1) + }; + } + ts.tryParsePattern = tryParsePattern; + function positionIsSynthesized(pos) { + // This is a fast way of testing the following conditions: + // pos === undefined || pos === null || isNaN(pos) || pos < 0; + return !(pos >= 0); + } + ts.positionIsSynthesized = positionIsSynthesized; + /** True if an extension is one of the supported TypeScript extensions. */ + function extensionIsTS(ext) { + return ext === ".ts" /* Ts */ || ext === ".tsx" /* Tsx */ || ext === ".d.ts" /* Dts */; + } + ts.extensionIsTS = extensionIsTS; + function resolutionExtensionIsTSOrJson(ext) { + return extensionIsTS(ext) || ext === ".json" /* Json */; + } + ts.resolutionExtensionIsTSOrJson = resolutionExtensionIsTSOrJson; + /** + * Gets the extension from a path. + * Path must have a valid extension. + */ + function extensionFromPath(path) { + var ext = tryGetExtensionFromPath(path); + return ext !== undefined ? ext : Debug.fail("File " + path + " has unknown extension."); + } + ts.extensionFromPath = extensionFromPath; + function isAnySupportedFileExtension(path) { + return tryGetExtensionFromPath(path) !== undefined; + } + ts.isAnySupportedFileExtension = isAnySupportedFileExtension; + function tryGetExtensionFromPath(path) { + return ts.find(extensionsToRemove, function (e) { return ts.fileExtensionIs(path, e); }); + } + ts.tryGetExtensionFromPath = tryGetExtensionFromPath; + function getAnyExtensionFromPathWorker(path, extensions, stringEqualityComparer) { + if (typeof extensions === "string") + extensions = [extensions]; + for (var _i = 0, extensions_2 = extensions; _i < extensions_2.length; _i++) { + var extension = extensions_2[_i]; + if (!ts.startsWith(extension, ".")) + extension = "." + extension; + if (path.length >= extension.length && path.charAt(path.length - extension.length) === ".") { + var pathExtension = path.slice(path.length - extension.length); + if (stringEqualityComparer(pathExtension, extension)) { + return pathExtension; + } + } + } + return ""; + } + function getAnyExtensionFromPath(path, extensions, ignoreCase) { + // Retrieves any string from the final "." onwards from a base file name. + // Unlike extensionFromPath, which throws an exception on unrecognized extensions. + if (extensions) { + return getAnyExtensionFromPathWorker(path, extensions, ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive); + } + var baseFileName = getBaseFileName(path); + var extensionIndex = baseFileName.lastIndexOf("."); + if (extensionIndex >= 0) { + return baseFileName.substring(extensionIndex); + } + return ""; + } + ts.getAnyExtensionFromPath = getAnyExtensionFromPath; + function isCheckJsEnabledForFile(sourceFile, compilerOptions) { + return sourceFile.checkJsDirective ? sourceFile.checkJsDirective.enabled : compilerOptions.checkJs; + } + ts.isCheckJsEnabledForFile = isCheckJsEnabledForFile; + ts.emptyFileSystemEntries = { + files: ts.emptyArray, + directories: ts.emptyArray + }; + /** + * patternStrings contains both pattern strings (containing "*") and regular strings. + * Return an exact match if possible, or a pattern match, or undefined. + * (These are verified by verifyCompilerOptions to have 0 or 1 "*" characters.) + */ + function matchPatternOrExact(patternStrings, candidate) { + var patterns = []; + for (var _i = 0, patternStrings_1 = patternStrings; _i < patternStrings_1.length; _i++) { + var patternString = patternStrings_1[_i]; + var pattern = tryParsePattern(patternString); + if (pattern) { + patterns.push(pattern); + } + else if (patternString === candidate) { + // pattern was matched as is - no need to search further + return patternString; + } + } + return ts.findBestPatternMatch(patterns, function (_) { return _; }, candidate); + } + ts.matchPatternOrExact = matchPatternOrExact; + function sliceAfter(arr, value) { + var index = arr.indexOf(value); + Debug.assert(index !== -1); + return arr.slice(index); + } + ts.sliceAfter = sliceAfter; + function minAndMax(arr, getValue) { + Debug.assert(arr.length !== 0); + var min = getValue(arr[0]); + var max = min; + for (var i = 1; i < arr.length; i++) { + var value = getValue(arr[i]); + if (value < min) { + min = value; + } + else if (value > max) { + max = value; + } + } + return { min: min, max: max }; + } + ts.minAndMax = minAndMax; + var NodeSet = /** @class */ (function () { + function NodeSet() { + this.map = ts.createMap(); + } + NodeSet.prototype.add = function (node) { + this.map.set(String(ts.getNodeId(node)), node); + }; + NodeSet.prototype.tryAdd = function (node) { + if (this.has(node)) + return false; + this.add(node); + return true; + }; + NodeSet.prototype.has = function (node) { + return this.map.has(String(ts.getNodeId(node))); + }; + NodeSet.prototype.forEach = function (cb) { + this.map.forEach(cb); + }; + NodeSet.prototype.some = function (pred) { + return ts.forEachEntry(this.map, pred) || false; + }; + return NodeSet; + }()); + ts.NodeSet = NodeSet; + var NodeMap = /** @class */ (function () { + function NodeMap() { + this.map = ts.createMap(); + } + NodeMap.prototype.get = function (node) { + var res = this.map.get(String(ts.getNodeId(node))); + return res && res.value; + }; + NodeMap.prototype.getOrUpdate = function (node, setValue) { + var res = this.get(node); + if (res) + return res; + var value = setValue(); + this.set(node, value); + return value; + }; + NodeMap.prototype.set = function (node, value) { + this.map.set(String(ts.getNodeId(node)), { node: node, value: value }); + }; + NodeMap.prototype.has = function (node) { + return this.map.has(String(ts.getNodeId(node))); + }; + NodeMap.prototype.forEach = function (cb) { + this.map.forEach(function (_a) { + var node = _a.node, value = _a.value; + return cb(value, node); + }); + }; + return NodeMap; + }()); + ts.NodeMap = NodeMap; + function rangeOfNode(node) { + return { pos: ts.getTokenPosOfNode(node), end: node.end }; + } + ts.rangeOfNode = rangeOfNode; + function rangeOfTypeParameters(typeParameters) { + // Include the `<>` + return { pos: typeParameters.pos - 1, end: typeParameters.end + 1 }; + } + ts.rangeOfTypeParameters = rangeOfTypeParameters; + function skipTypeChecking(sourceFile, options) { + // If skipLibCheck is enabled, skip reporting errors if file is a declaration file. + // If skipDefaultLibCheck is enabled, skip reporting errors if file contains a + // '/// ' directive. + return options.skipLibCheck && sourceFile.isDeclarationFile || options.skipDefaultLibCheck && sourceFile.hasNoDefaultLib; + } + ts.skipTypeChecking = skipTypeChecking; + function isJsonEqual(a, b) { + return a === b || typeof a === "object" && a !== null && typeof b === "object" && b !== null && ts.equalOwnProperties(a, b, isJsonEqual); + } + ts.isJsonEqual = isJsonEqual; + function getOrUpdate(map, key, getDefault) { + var got = map.get(key); + if (got === undefined) { + var value = getDefault(); + map.set(key, value); + return value; + } + else { + return got; + } + } + ts.getOrUpdate = getOrUpdate; + /** + * Converts a bigint literal string, e.g. `0x1234n`, + * to its decimal string representation, e.g. `4660`. + */ + function parsePseudoBigInt(stringValue) { + var log2Base; + switch (stringValue.charCodeAt(1)) { // "x" in "0x123" + case 98 /* b */: + case 66 /* B */: // 0b or 0B + log2Base = 1; + break; + case 111 /* o */: + case 79 /* O */: // 0o or 0O + log2Base = 3; + break; + case 120 /* x */: + case 88 /* X */: // 0x or 0X + log2Base = 4; + break; + default: // already in decimal; omit trailing "n" + var nIndex = stringValue.length - 1; + // Skip leading 0s + var nonZeroStart = 0; + while (stringValue.charCodeAt(nonZeroStart) === 48 /* _0 */) { + nonZeroStart++; + } + return stringValue.slice(nonZeroStart, nIndex) || "0"; + } + // Omit leading "0b", "0o", or "0x", and trailing "n" + var startIndex = 2, endIndex = stringValue.length - 1; + var bitsNeeded = (endIndex - startIndex) * log2Base; + // Stores the value specified by the string as a LE array of 16-bit integers + // using Uint16 instead of Uint32 so combining steps can use bitwise operators + var segments = new Uint16Array((bitsNeeded >>> 4) + (bitsNeeded & 15 ? 1 : 0)); + // Add the digits, one at a time + for (var i = endIndex - 1, bitOffset = 0; i >= startIndex; i--, bitOffset += log2Base) { + var segment = bitOffset >>> 4; + var digitChar = stringValue.charCodeAt(i); + // Find character range: 0-9 < A-F < a-f + var digit = digitChar <= 57 /* _9 */ + ? digitChar - 48 /* _0 */ + : 10 + digitChar - + (digitChar <= 70 /* F */ ? 65 /* A */ : 97 /* a */); + var shiftedDigit = digit << (bitOffset & 15); + segments[segment] |= shiftedDigit; + var residual = shiftedDigit >>> 16; + if (residual) + segments[segment + 1] |= residual; // overflows segment + } + // Repeatedly divide segments by 10 and add remainder to base10Value + var base10Value = ""; + var firstNonzeroSegment = segments.length - 1; + var segmentsRemaining = true; + while (segmentsRemaining) { + var mod10 = 0; + segmentsRemaining = false; + for (var segment = firstNonzeroSegment; segment >= 0; segment--) { + var newSegment = mod10 << 16 | segments[segment]; + var segmentValue = (newSegment / 10) | 0; + segments[segment] = segmentValue; + mod10 = newSegment - segmentValue * 10; + if (segmentValue && !segmentsRemaining) { + firstNonzeroSegment = segment; + segmentsRemaining = true; + } + } + base10Value = mod10 + base10Value; + } + return base10Value; + } + ts.parsePseudoBigInt = parsePseudoBigInt; + function pseudoBigIntToString(_a) { + var negative = _a.negative, base10Value = _a.base10Value; + return (negative && base10Value !== "0" ? "-" : "") + base10Value; + } + ts.pseudoBigIntToString = pseudoBigIntToString; +})(ts || (ts = {})); +var ts; +(function (ts) { + var SignatureFlags; + (function (SignatureFlags) { + SignatureFlags[SignatureFlags["None"] = 0] = "None"; + SignatureFlags[SignatureFlags["Yield"] = 1] = "Yield"; + SignatureFlags[SignatureFlags["Await"] = 2] = "Await"; + SignatureFlags[SignatureFlags["Type"] = 4] = "Type"; + SignatureFlags[SignatureFlags["IgnoreMissingOpenBrace"] = 16] = "IgnoreMissingOpenBrace"; + SignatureFlags[SignatureFlags["JSDoc"] = 32] = "JSDoc"; + })(SignatureFlags || (SignatureFlags = {})); + // tslint:disable variable-name + var NodeConstructor; + var TokenConstructor; + var IdentifierConstructor; + var SourceFileConstructor; + // tslint:enable variable-name + function createNode(kind, pos, end) { + if (kind === 279 /* SourceFile */) { + return new (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor()))(kind, pos, end); + } + else if (kind === 72 /* Identifier */) { + return new (IdentifierConstructor || (IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor()))(kind, pos, end); + } + else if (!ts.isNodeKind(kind)) { + return new (TokenConstructor || (TokenConstructor = ts.objectAllocator.getTokenConstructor()))(kind, pos, end); + } + else { + return new (NodeConstructor || (NodeConstructor = ts.objectAllocator.getNodeConstructor()))(kind, pos, end); + } + } + ts.createNode = createNode; + function visitNode(cbNode, node) { + return node && cbNode(node); + } + function visitNodes(cbNode, cbNodes, nodes) { + if (nodes) { + if (cbNodes) { + return cbNodes(nodes); + } + for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) { + var node = nodes_1[_i]; + var result = cbNode(node); + if (result) { + return result; + } + } + } + } + /*@internal*/ + function isJSDocLikeText(text, start) { + return text.charCodeAt(start + 1) === 42 /* asterisk */ && + text.charCodeAt(start + 2) === 42 /* asterisk */ && + text.charCodeAt(start + 3) !== 47 /* slash */; + } + ts.isJSDocLikeText = isJSDocLikeText; + /** + * Invokes a callback for each child of the given node. The 'cbNode' callback is invoked for all child nodes + * stored in properties. If a 'cbNodes' callback is specified, it is invoked for embedded arrays; otherwise, + * embedded arrays are flattened and the 'cbNode' callback is invoked for each element. If a callback returns + * a truthy value, iteration stops and that value is returned. Otherwise, undefined is returned. + * + * @param node a given node to visit its children + * @param cbNode a callback to be invoked for all child nodes + * @param cbNodes a callback to be invoked for embedded array + * + * @remarks `forEachChild` must visit the children of a node in the order + * that they appear in the source code. The language service depends on this property to locate nodes by position. + */ + function forEachChild(node, cbNode, cbNodes) { + if (!node || node.kind <= 147 /* LastToken */) { + return; + } + switch (node.kind) { + case 148 /* QualifiedName */: + return visitNode(cbNode, node.left) || + visitNode(cbNode, node.right); + case 150 /* TypeParameter */: + return visitNode(cbNode, node.name) || + visitNode(cbNode, node.constraint) || + visitNode(cbNode, node.default) || + visitNode(cbNode, node.expression); + case 276 /* ShorthandPropertyAssignment */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.exclamationToken) || + visitNode(cbNode, node.equalsToken) || + visitNode(cbNode, node.objectAssignmentInitializer); + case 277 /* SpreadAssignment */: + return visitNode(cbNode, node.expression); + case 151 /* Parameter */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.dotDotDotToken) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.type) || + visitNode(cbNode, node.initializer); + case 154 /* PropertyDeclaration */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.exclamationToken) || + visitNode(cbNode, node.type) || + visitNode(cbNode, node.initializer); + case 153 /* PropertySignature */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.type) || + visitNode(cbNode, node.initializer); + case 275 /* PropertyAssignment */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.initializer); + case 237 /* VariableDeclaration */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.exclamationToken) || + visitNode(cbNode, node.type) || + visitNode(cbNode, node.initializer); + case 186 /* BindingElement */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.dotDotDotToken) || + visitNode(cbNode, node.propertyName) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.initializer); + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 162 /* IndexSignature */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type); + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 196 /* FunctionExpression */: + case 239 /* FunctionDeclaration */: + case 197 /* ArrowFunction */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.asteriskToken) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.exclamationToken) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type) || + visitNode(cbNode, node.equalsGreaterThanToken) || + visitNode(cbNode, node.body); + case 164 /* TypeReference */: + return visitNode(cbNode, node.typeName) || + visitNodes(cbNode, cbNodes, node.typeArguments); + case 163 /* TypePredicate */: + return visitNode(cbNode, node.parameterName) || + visitNode(cbNode, node.type); + case 167 /* TypeQuery */: + return visitNode(cbNode, node.exprName); + case 168 /* TypeLiteral */: + return visitNodes(cbNode, cbNodes, node.members); + case 169 /* ArrayType */: + return visitNode(cbNode, node.elementType); + case 170 /* TupleType */: + return visitNodes(cbNode, cbNodes, node.elementTypes); + case 173 /* UnionType */: + case 174 /* IntersectionType */: + return visitNodes(cbNode, cbNodes, node.types); + case 175 /* ConditionalType */: + return visitNode(cbNode, node.checkType) || + visitNode(cbNode, node.extendsType) || + visitNode(cbNode, node.trueType) || + visitNode(cbNode, node.falseType); + case 176 /* InferType */: + return visitNode(cbNode, node.typeParameter); + case 183 /* ImportType */: + return visitNode(cbNode, node.argument) || + visitNode(cbNode, node.qualifier) || + visitNodes(cbNode, cbNodes, node.typeArguments); + case 177 /* ParenthesizedType */: + case 179 /* TypeOperator */: + return visitNode(cbNode, node.type); + case 180 /* IndexedAccessType */: + return visitNode(cbNode, node.objectType) || + visitNode(cbNode, node.indexType); + case 181 /* MappedType */: + return visitNode(cbNode, node.readonlyToken) || + visitNode(cbNode, node.typeParameter) || + visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.type); + case 182 /* LiteralType */: + return visitNode(cbNode, node.literal); + case 184 /* ObjectBindingPattern */: + case 185 /* ArrayBindingPattern */: + return visitNodes(cbNode, cbNodes, node.elements); + case 187 /* ArrayLiteralExpression */: + return visitNodes(cbNode, cbNodes, node.elements); + case 188 /* ObjectLiteralExpression */: + return visitNodes(cbNode, cbNodes, node.properties); + case 189 /* PropertyAccessExpression */: + return visitNode(cbNode, node.expression) || + visitNode(cbNode, node.name); + case 190 /* ElementAccessExpression */: + return visitNode(cbNode, node.expression) || + visitNode(cbNode, node.argumentExpression); + case 191 /* CallExpression */: + case 192 /* NewExpression */: + return visitNode(cbNode, node.expression) || + visitNodes(cbNode, cbNodes, node.typeArguments) || + visitNodes(cbNode, cbNodes, node.arguments); + case 193 /* TaggedTemplateExpression */: + return visitNode(cbNode, node.tag) || + visitNodes(cbNode, cbNodes, node.typeArguments) || + visitNode(cbNode, node.template); + case 194 /* TypeAssertionExpression */: + return visitNode(cbNode, node.type) || + visitNode(cbNode, node.expression); + case 195 /* ParenthesizedExpression */: + return visitNode(cbNode, node.expression); + case 198 /* DeleteExpression */: + return visitNode(cbNode, node.expression); + case 199 /* TypeOfExpression */: + return visitNode(cbNode, node.expression); + case 200 /* VoidExpression */: + return visitNode(cbNode, node.expression); + case 202 /* PrefixUnaryExpression */: + return visitNode(cbNode, node.operand); + case 207 /* YieldExpression */: + return visitNode(cbNode, node.asteriskToken) || + visitNode(cbNode, node.expression); + case 201 /* AwaitExpression */: + return visitNode(cbNode, node.expression); + case 203 /* PostfixUnaryExpression */: + return visitNode(cbNode, node.operand); + case 204 /* BinaryExpression */: + return visitNode(cbNode, node.left) || + visitNode(cbNode, node.operatorToken) || + visitNode(cbNode, node.right); + case 212 /* AsExpression */: + return visitNode(cbNode, node.expression) || + visitNode(cbNode, node.type); + case 213 /* NonNullExpression */: + return visitNode(cbNode, node.expression); + case 214 /* MetaProperty */: + return visitNode(cbNode, node.name); + case 205 /* ConditionalExpression */: + return visitNode(cbNode, node.condition) || + visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.whenTrue) || + visitNode(cbNode, node.colonToken) || + visitNode(cbNode, node.whenFalse); + case 208 /* SpreadElement */: + return visitNode(cbNode, node.expression); + case 218 /* Block */: + case 245 /* ModuleBlock */: + return visitNodes(cbNode, cbNodes, node.statements); + case 279 /* SourceFile */: + return visitNodes(cbNode, cbNodes, node.statements) || + visitNode(cbNode, node.endOfFileToken); + case 219 /* VariableStatement */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.declarationList); + case 238 /* VariableDeclarationList */: + return visitNodes(cbNode, cbNodes, node.declarations); + case 221 /* ExpressionStatement */: + return visitNode(cbNode, node.expression); + case 222 /* IfStatement */: + return visitNode(cbNode, node.expression) || + visitNode(cbNode, node.thenStatement) || + visitNode(cbNode, node.elseStatement); + case 223 /* DoStatement */: + return visitNode(cbNode, node.statement) || + visitNode(cbNode, node.expression); + case 224 /* WhileStatement */: + return visitNode(cbNode, node.expression) || + visitNode(cbNode, node.statement); + case 225 /* ForStatement */: + return visitNode(cbNode, node.initializer) || + visitNode(cbNode, node.condition) || + visitNode(cbNode, node.incrementor) || + visitNode(cbNode, node.statement); + case 226 /* ForInStatement */: + return visitNode(cbNode, node.initializer) || + visitNode(cbNode, node.expression) || + visitNode(cbNode, node.statement); + case 227 /* ForOfStatement */: + return visitNode(cbNode, node.awaitModifier) || + visitNode(cbNode, node.initializer) || + visitNode(cbNode, node.expression) || + visitNode(cbNode, node.statement); + case 228 /* ContinueStatement */: + case 229 /* BreakStatement */: + return visitNode(cbNode, node.label); + case 230 /* ReturnStatement */: + return visitNode(cbNode, node.expression); + case 231 /* WithStatement */: + return visitNode(cbNode, node.expression) || + visitNode(cbNode, node.statement); + case 232 /* SwitchStatement */: + return visitNode(cbNode, node.expression) || + visitNode(cbNode, node.caseBlock); + case 246 /* CaseBlock */: + return visitNodes(cbNode, cbNodes, node.clauses); + case 271 /* CaseClause */: + return visitNode(cbNode, node.expression) || + visitNodes(cbNode, cbNodes, node.statements); + case 272 /* DefaultClause */: + return visitNodes(cbNode, cbNodes, node.statements); + case 233 /* LabeledStatement */: + return visitNode(cbNode, node.label) || + visitNode(cbNode, node.statement); + case 234 /* ThrowStatement */: + return visitNode(cbNode, node.expression); + case 235 /* TryStatement */: + return visitNode(cbNode, node.tryBlock) || + visitNode(cbNode, node.catchClause) || + visitNode(cbNode, node.finallyBlock); + case 274 /* CatchClause */: + return visitNode(cbNode, node.variableDeclaration) || + visitNode(cbNode, node.block); + case 152 /* Decorator */: + return visitNode(cbNode, node.expression); + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.heritageClauses) || + visitNodes(cbNode, cbNodes, node.members); + case 241 /* InterfaceDeclaration */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.heritageClauses) || + visitNodes(cbNode, cbNodes, node.members); + case 242 /* TypeAliasDeclaration */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNode(cbNode, node.type); + case 243 /* EnumDeclaration */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNodes(cbNode, cbNodes, node.members); + case 278 /* EnumMember */: + return visitNode(cbNode, node.name) || + visitNode(cbNode, node.initializer); + case 244 /* ModuleDeclaration */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.body); + case 248 /* ImportEqualsDeclaration */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.moduleReference); + case 249 /* ImportDeclaration */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.importClause) || + visitNode(cbNode, node.moduleSpecifier); + case 250 /* ImportClause */: + return visitNode(cbNode, node.name) || + visitNode(cbNode, node.namedBindings); + case 247 /* NamespaceExportDeclaration */: + return visitNode(cbNode, node.name); + case 251 /* NamespaceImport */: + return visitNode(cbNode, node.name); + case 252 /* NamedImports */: + case 256 /* NamedExports */: + return visitNodes(cbNode, cbNodes, node.elements); + case 255 /* ExportDeclaration */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.exportClause) || + visitNode(cbNode, node.moduleSpecifier); + case 253 /* ImportSpecifier */: + case 257 /* ExportSpecifier */: + return visitNode(cbNode, node.propertyName) || + visitNode(cbNode, node.name); + case 254 /* ExportAssignment */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.expression); + case 206 /* TemplateExpression */: + return visitNode(cbNode, node.head) || visitNodes(cbNode, cbNodes, node.templateSpans); + case 216 /* TemplateSpan */: + return visitNode(cbNode, node.expression) || visitNode(cbNode, node.literal); + case 149 /* ComputedPropertyName */: + return visitNode(cbNode, node.expression); + case 273 /* HeritageClause */: + return visitNodes(cbNode, cbNodes, node.types); + case 211 /* ExpressionWithTypeArguments */: + return visitNode(cbNode, node.expression) || + visitNodes(cbNode, cbNodes, node.typeArguments); + case 259 /* ExternalModuleReference */: + return visitNode(cbNode, node.expression); + case 258 /* MissingDeclaration */: + return visitNodes(cbNode, cbNodes, node.decorators); + case 309 /* CommaListExpression */: + return visitNodes(cbNode, cbNodes, node.elements); + case 260 /* JsxElement */: + return visitNode(cbNode, node.openingElement) || + visitNodes(cbNode, cbNodes, node.children) || + visitNode(cbNode, node.closingElement); + case 264 /* JsxFragment */: + return visitNode(cbNode, node.openingFragment) || + visitNodes(cbNode, cbNodes, node.children) || + visitNode(cbNode, node.closingFragment); + case 261 /* JsxSelfClosingElement */: + case 262 /* JsxOpeningElement */: + return visitNode(cbNode, node.tagName) || + visitNodes(cbNode, cbNodes, node.typeArguments) || + visitNode(cbNode, node.attributes); + case 268 /* JsxAttributes */: + return visitNodes(cbNode, cbNodes, node.properties); + case 267 /* JsxAttribute */: + return visitNode(cbNode, node.name) || + visitNode(cbNode, node.initializer); + case 269 /* JsxSpreadAttribute */: + return visitNode(cbNode, node.expression); + case 270 /* JsxExpression */: + return visitNode(cbNode, node.dotDotDotToken) || + visitNode(cbNode, node.expression); + case 263 /* JsxClosingElement */: + return visitNode(cbNode, node.tagName); + case 171 /* OptionalType */: + case 172 /* RestType */: + case 283 /* JSDocTypeExpression */: + case 287 /* JSDocNonNullableType */: + case 286 /* JSDocNullableType */: + case 288 /* JSDocOptionalType */: + case 290 /* JSDocVariadicType */: + return visitNode(cbNode, node.type); + case 289 /* JSDocFunctionType */: + return visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type); + case 291 /* JSDocComment */: + return visitNodes(cbNode, cbNodes, node.tags); + case 299 /* JSDocParameterTag */: + case 305 /* JSDocPropertyTag */: + return visitNode(cbNode, node.tagName) || + (node.isNameFirst + ? visitNode(cbNode, node.name) || + visitNode(cbNode, node.typeExpression) + : visitNode(cbNode, node.typeExpression) || + visitNode(cbNode, node.name)); + case 295 /* JSDocAugmentsTag */: + return visitNode(cbNode, node.tagName) || + visitNode(cbNode, node.class); + case 303 /* JSDocTemplateTag */: + return visitNode(cbNode, node.tagName) || + visitNode(cbNode, node.constraint) || + visitNodes(cbNode, cbNodes, node.typeParameters); + case 304 /* JSDocTypedefTag */: + return visitNode(cbNode, node.tagName) || + (node.typeExpression && + node.typeExpression.kind === 283 /* JSDocTypeExpression */ + ? visitNode(cbNode, node.typeExpression) || + visitNode(cbNode, node.fullName) + : visitNode(cbNode, node.fullName) || + visitNode(cbNode, node.typeExpression)); + case 297 /* JSDocCallbackTag */: + return visitNode(cbNode, node.tagName) || + visitNode(cbNode, node.fullName) || + visitNode(cbNode, node.typeExpression); + case 300 /* JSDocReturnTag */: + case 302 /* JSDocTypeTag */: + case 301 /* JSDocThisTag */: + case 298 /* JSDocEnumTag */: + return visitNode(cbNode, node.tagName) || + visitNode(cbNode, node.typeExpression); + case 293 /* JSDocSignature */: + return ts.forEach(node.typeParameters, cbNode) || + ts.forEach(node.parameters, cbNode) || + visitNode(cbNode, node.type); + case 292 /* JSDocTypeLiteral */: + return ts.forEach(node.jsDocPropertyTags, cbNode); + case 294 /* JSDocTag */: + case 296 /* JSDocClassTag */: + return visitNode(cbNode, node.tagName); + case 308 /* PartiallyEmittedExpression */: + return visitNode(cbNode, node.expression); + } + } + ts.forEachChild = forEachChild; + function createSourceFile(fileName, sourceText, languageVersion, setParentNodes, scriptKind) { + if (setParentNodes === void 0) { setParentNodes = false; } + ts.performance.mark("beforeParse"); + var result; + if (languageVersion === 100 /* JSON */) { + result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes, 6 /* JSON */); + } + else { + result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes, scriptKind); + } + ts.performance.mark("afterParse"); + ts.performance.measure("Parse", "beforeParse", "afterParse"); + return result; + } + ts.createSourceFile = createSourceFile; + function parseIsolatedEntityName(text, languageVersion) { + return Parser.parseIsolatedEntityName(text, languageVersion); + } + ts.parseIsolatedEntityName = parseIsolatedEntityName; + /** + * Parse json text into SyntaxTree and return node and parse errors if any + * @param fileName + * @param sourceText + */ + function parseJsonText(fileName, sourceText) { + return Parser.parseJsonText(fileName, sourceText); + } + ts.parseJsonText = parseJsonText; + // See also `isExternalOrCommonJsModule` in utilities.ts + function isExternalModule(file) { + return file.externalModuleIndicator !== undefined; + } + ts.isExternalModule = isExternalModule; + // Produces a new SourceFile for the 'newText' provided. The 'textChangeRange' parameter + // indicates what changed between the 'text' that this SourceFile has and the 'newText'. + // The SourceFile will be created with the compiler attempting to reuse as many nodes from + // this file as possible. + // + // Note: this function mutates nodes from this SourceFile. That means any existing nodes + // from this SourceFile that are being held onto may change as a result (including + // becoming detached from any SourceFile). It is recommended that this SourceFile not + // be used once 'update' is called on it. + function updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks) { + if (aggressiveChecks === void 0) { aggressiveChecks = false; } + var newSourceFile = IncrementalParser.updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks); + // Because new source file node is created, it may not have the flag PossiblyContainDynamicImport. This is the case if there is no new edit to add dynamic import. + // We will manually port the flag to the new source file. + newSourceFile.flags |= (sourceFile.flags & 1572864 /* PermanentlySetIncrementalFlags */); + return newSourceFile; + } + ts.updateSourceFile = updateSourceFile; + /* @internal */ + function parseIsolatedJSDocComment(content, start, length) { + var result = Parser.JSDocParser.parseIsolatedJSDocComment(content, start, length); + if (result && result.jsDoc) { + // because the jsDocComment was parsed out of the source file, it might + // not be covered by the fixupParentReferences. + Parser.fixupParentReferences(result.jsDoc); + } + return result; + } + ts.parseIsolatedJSDocComment = parseIsolatedJSDocComment; + /* @internal */ + // Exposed only for testing. + function parseJSDocTypeExpressionForTests(content, start, length) { + return Parser.JSDocParser.parseJSDocTypeExpressionForTests(content, start, length); + } + ts.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests; + // Implement the parser as a singleton module. We do this for perf reasons because creating + // parser instances can actually be expensive enough to impact us on projects with many source + // files. + var Parser; + (function (Parser) { + // Share a single scanner across all calls to parse a source file. This helps speed things + // up by avoiding the cost of creating/compiling scanners over and over again. + var scanner = ts.createScanner(6 /* Latest */, /*skipTrivia*/ true); + var disallowInAndDecoratorContext = 2048 /* DisallowInContext */ | 8192 /* DecoratorContext */; + // capture constructors in 'initializeState' to avoid null checks + // tslint:disable variable-name + var NodeConstructor; + var TokenConstructor; + var IdentifierConstructor; + var SourceFileConstructor; + // tslint:enable variable-name + var sourceFile; + var parseDiagnostics; + var syntaxCursor; + var currentToken; + var sourceText; + var nodeCount; + var identifiers; + var identifierCount; + var parsingContext; + // Flags that dictate what parsing context we're in. For example: + // Whether or not we are in strict parsing mode. All that changes in strict parsing mode is + // that some tokens that would be considered identifiers may be considered keywords. + // + // When adding more parser context flags, consider which is the more common case that the + // flag will be in. This should be the 'false' state for that flag. The reason for this is + // that we don't store data in our nodes unless the value is in the *non-default* state. So, + // for example, more often than code 'allows-in' (or doesn't 'disallow-in'). We opt for + // 'disallow-in' set to 'false'. Otherwise, if we had 'allowsIn' set to 'true', then almost + // all nodes would need extra state on them to store this info. + // + // Note: 'allowIn' and 'allowYield' track 1:1 with the [in] and [yield] concepts in the ES6 + // grammar specification. + // + // An important thing about these context concepts. By default they are effectively inherited + // while parsing through every grammar production. i.e. if you don't change them, then when + // you parse a sub-production, it will have the same context values as the parent production. + // This is great most of the time. After all, consider all the 'expression' grammar productions + // and how nearly all of them pass along the 'in' and 'yield' context values: + // + // EqualityExpression[In, Yield] : + // RelationalExpression[?In, ?Yield] + // EqualityExpression[?In, ?Yield] == RelationalExpression[?In, ?Yield] + // EqualityExpression[?In, ?Yield] != RelationalExpression[?In, ?Yield] + // EqualityExpression[?In, ?Yield] === RelationalExpression[?In, ?Yield] + // EqualityExpression[?In, ?Yield] !== RelationalExpression[?In, ?Yield] + // + // Where you have to be careful is then understanding what the points are in the grammar + // where the values are *not* passed along. For example: + // + // SingleNameBinding[Yield,GeneratorParameter] + // [+GeneratorParameter]BindingIdentifier[Yield] Initializer[In]opt + // [~GeneratorParameter]BindingIdentifier[?Yield]Initializer[In, ?Yield]opt + // + // Here this is saying that if the GeneratorParameter context flag is set, that we should + // explicitly set the 'yield' context flag to false before calling into the BindingIdentifier + // and we should explicitly unset the 'yield' context flag before calling into the Initializer. + // production. Conversely, if the GeneratorParameter context flag is not set, then we + // should leave the 'yield' context flag alone. + // + // Getting this all correct is tricky and requires careful reading of the grammar to + // understand when these values should be changed versus when they should be inherited. + // + // Note: it should not be necessary to save/restore these flags during speculative/lookahead + // parsing. These context flags are naturally stored and restored through normal recursive + // descent parsing and unwinding. + var contextFlags; + // Whether or not we've had a parse error since creating the last AST node. If we have + // encountered an error, it will be stored on the next AST node we create. Parse errors + // can be broken down into three categories: + // + // 1) An error that occurred during scanning. For example, an unterminated literal, or a + // character that was completely not understood. + // + // 2) A token was expected, but was not present. This type of error is commonly produced + // by the 'parseExpected' function. + // + // 3) A token was present that no parsing function was able to consume. This type of error + // only occurs in the 'abortParsingListOrMoveToNextToken' function when the parser + // decides to skip the token. + // + // In all of these cases, we want to mark the next node as having had an error before it. + // With this mark, we can know in incremental settings if this node can be reused, or if + // we have to reparse it. If we don't keep this information around, we may just reuse the + // node. in that event we would then not produce the same errors as we did before, causing + // significant confusion problems. + // + // Note: it is necessary that this value be saved/restored during speculative/lookahead + // parsing. During lookahead parsing, we will often create a node. That node will have + // this value attached, and then this value will be set back to 'false'. If we decide to + // rewind, we must get back to the same value we had prior to the lookahead. + // + // Note: any errors at the end of the file that do not precede a regular node, should get + // attached to the EOF token. + var parseErrorBeforeNextFinishedNode = false; + function parseSourceFile(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes, scriptKind) { + if (setParentNodes === void 0) { setParentNodes = false; } + scriptKind = ts.ensureScriptKind(fileName, scriptKind); + if (scriptKind === 6 /* JSON */) { + var result_1 = parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes); + ts.convertToObjectWorker(result_1, result_1.parseDiagnostics, /*returnValue*/ false, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined); + result_1.referencedFiles = ts.emptyArray; + result_1.typeReferenceDirectives = ts.emptyArray; + result_1.libReferenceDirectives = ts.emptyArray; + result_1.amdDependencies = ts.emptyArray; + result_1.hasNoDefaultLib = false; + result_1.pragmas = ts.emptyMap; + return result_1; + } + initializeState(sourceText, languageVersion, syntaxCursor, scriptKind); + var result = parseSourceFileWorker(fileName, languageVersion, setParentNodes, scriptKind); + clearState(); + return result; + } + Parser.parseSourceFile = parseSourceFile; + function parseIsolatedEntityName(content, languageVersion) { + // Choice of `isDeclarationFile` should be arbitrary + initializeState(content, languageVersion, /*syntaxCursor*/ undefined, 1 /* JS */); + // Prime the scanner. + nextToken(); + var entityName = parseEntityName(/*allowReservedWords*/ true); + var isInvalid = token() === 1 /* EndOfFileToken */ && !parseDiagnostics.length; + clearState(); + return isInvalid ? entityName : undefined; + } + Parser.parseIsolatedEntityName = parseIsolatedEntityName; + function parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes) { + if (languageVersion === void 0) { languageVersion = 2 /* ES2015 */; } + initializeState(sourceText, languageVersion, syntaxCursor, 6 /* JSON */); + // Set source file so that errors will be reported with this file name + sourceFile = createSourceFile(fileName, 2 /* ES2015 */, 6 /* JSON */, /*isDeclaration*/ false); + sourceFile.flags = contextFlags; + // Prime the scanner. + nextToken(); + var pos = getNodePos(); + if (token() === 1 /* EndOfFileToken */) { + sourceFile.statements = createNodeArray([], pos, pos); + sourceFile.endOfFileToken = parseTokenNode(); + } + else { + var statement = createNode(221 /* ExpressionStatement */); + switch (token()) { + case 22 /* OpenBracketToken */: + statement.expression = parseArrayLiteralExpression(); + break; + case 102 /* TrueKeyword */: + case 87 /* FalseKeyword */: + case 96 /* NullKeyword */: + statement.expression = parseTokenNode(); + break; + case 39 /* MinusToken */: + if (lookAhead(function () { return nextToken() === 8 /* NumericLiteral */ && nextToken() !== 57 /* ColonToken */; })) { + statement.expression = parsePrefixUnaryExpression(); + } + else { + statement.expression = parseObjectLiteralExpression(); + } + break; + case 8 /* NumericLiteral */: + case 10 /* StringLiteral */: + if (lookAhead(function () { return nextToken() !== 57 /* ColonToken */; })) { + statement.expression = parseLiteralNode(); + break; + } + // falls through + default: + statement.expression = parseObjectLiteralExpression(); + break; + } + finishNode(statement); + sourceFile.statements = createNodeArray([statement], pos); + sourceFile.endOfFileToken = parseExpectedToken(1 /* EndOfFileToken */, ts.Diagnostics.Unexpected_token); + } + if (setParentNodes) { + fixupParentReferences(sourceFile); + } + sourceFile.parseDiagnostics = parseDiagnostics; + var result = sourceFile; + clearState(); + return result; + } + Parser.parseJsonText = parseJsonText; + function getLanguageVariant(scriptKind) { + // .tsx and .jsx files are treated as jsx language variant. + return scriptKind === 4 /* TSX */ || scriptKind === 2 /* JSX */ || scriptKind === 1 /* JS */ || scriptKind === 6 /* JSON */ ? 1 /* JSX */ : 0 /* Standard */; + } + function initializeState(_sourceText, languageVersion, _syntaxCursor, scriptKind) { + NodeConstructor = ts.objectAllocator.getNodeConstructor(); + TokenConstructor = ts.objectAllocator.getTokenConstructor(); + IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor(); + SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor(); + sourceText = _sourceText; + syntaxCursor = _syntaxCursor; + parseDiagnostics = []; + parsingContext = 0; + identifiers = ts.createMap(); + identifierCount = 0; + nodeCount = 0; + switch (scriptKind) { + case 1 /* JS */: + case 2 /* JSX */: + contextFlags = 65536 /* JavaScriptFile */; + break; + case 6 /* JSON */: + contextFlags = 65536 /* JavaScriptFile */ | 16777216 /* JsonFile */; + break; + default: + contextFlags = 0 /* None */; + break; + } + parseErrorBeforeNextFinishedNode = false; + // Initialize and prime the scanner before parsing the source elements. + scanner.setText(sourceText); + scanner.setOnError(scanError); + scanner.setScriptTarget(languageVersion); + scanner.setLanguageVariant(getLanguageVariant(scriptKind)); + } + function clearState() { + // Clear out the text the scanner is pointing at, so it doesn't keep anything alive unnecessarily. + scanner.setText(""); + scanner.setOnError(undefined); + // Clear any data. We don't want to accidentally hold onto it for too long. + parseDiagnostics = undefined; + sourceFile = undefined; + identifiers = undefined; + syntaxCursor = undefined; + sourceText = undefined; + } + function parseSourceFileWorker(fileName, languageVersion, setParentNodes, scriptKind) { + var isDeclarationFile = isDeclarationFileName(fileName); + if (isDeclarationFile) { + contextFlags |= 4194304 /* Ambient */; + } + sourceFile = createSourceFile(fileName, languageVersion, scriptKind, isDeclarationFile); + sourceFile.flags = contextFlags; + // Prime the scanner. + nextToken(); + // A member of ReadonlyArray isn't assignable to a member of T[] (and prevents a direct cast) - but this is where we set up those members so they can be readonly in the future + processCommentPragmas(sourceFile, sourceText); + processPragmasIntoFields(sourceFile, reportPragmaDiagnostic); + sourceFile.statements = parseList(0 /* SourceElements */, parseStatement); + ts.Debug.assert(token() === 1 /* EndOfFileToken */); + sourceFile.endOfFileToken = addJSDocComment(parseTokenNode()); + setExternalModuleIndicator(sourceFile); + sourceFile.nodeCount = nodeCount; + sourceFile.identifierCount = identifierCount; + sourceFile.identifiers = identifiers; + sourceFile.parseDiagnostics = parseDiagnostics; + if (setParentNodes) { + fixupParentReferences(sourceFile); + } + return sourceFile; + function reportPragmaDiagnostic(pos, end, diagnostic) { + parseDiagnostics.push(ts.createFileDiagnostic(sourceFile, pos, end, diagnostic)); + } + } + function addJSDocComment(node) { + ts.Debug.assert(!node.jsDoc); // Should only be called once per node + var jsDoc = ts.mapDefined(ts.getJSDocCommentRanges(node, sourceFile.text), function (comment) { return JSDocParser.parseJSDocComment(node, comment.pos, comment.end - comment.pos); }); + if (jsDoc.length) + node.jsDoc = jsDoc; + return node; + } + function fixupParentReferences(rootNode) { + // normally parent references are set during binding. However, for clients that only need + // a syntax tree, and no semantic features, then the binding process is an unnecessary + // overhead. This functions allows us to set all the parents, without all the expense of + // binding. + var parent = rootNode; + forEachChild(rootNode, visitNode); + return; + function visitNode(n) { + // walk down setting parents that differ from the parent we think it should be. This + // allows us to quickly bail out of setting parents for subtrees during incremental + // parsing + if (n.parent !== parent) { + n.parent = parent; + var saveParent = parent; + parent = n; + forEachChild(n, visitNode); + if (ts.hasJSDocNodes(n)) { + for (var _i = 0, _a = n.jsDoc; _i < _a.length; _i++) { + var jsDoc = _a[_i]; + jsDoc.parent = n; + parent = jsDoc; + forEachChild(jsDoc, visitNode); + } + } + parent = saveParent; + } + } + } + Parser.fixupParentReferences = fixupParentReferences; + function createSourceFile(fileName, languageVersion, scriptKind, isDeclarationFile) { + // code from createNode is inlined here so createNode won't have to deal with special case of creating source files + // this is quite rare comparing to other nodes and createNode should be as fast as possible + var sourceFile = new SourceFileConstructor(279 /* SourceFile */, /*pos*/ 0, /* end */ sourceText.length); + nodeCount++; + sourceFile.text = sourceText; + sourceFile.bindDiagnostics = []; + sourceFile.bindSuggestionDiagnostics = undefined; + sourceFile.languageVersion = languageVersion; + sourceFile.fileName = ts.normalizePath(fileName); + sourceFile.languageVariant = getLanguageVariant(scriptKind); + sourceFile.isDeclarationFile = isDeclarationFile; + sourceFile.scriptKind = scriptKind; + return sourceFile; + } + function setContextFlag(val, flag) { + if (val) { + contextFlags |= flag; + } + else { + contextFlags &= ~flag; + } + } + function setDisallowInContext(val) { + setContextFlag(val, 2048 /* DisallowInContext */); + } + function setYieldContext(val) { + setContextFlag(val, 4096 /* YieldContext */); + } + function setDecoratorContext(val) { + setContextFlag(val, 8192 /* DecoratorContext */); + } + function setAwaitContext(val) { + setContextFlag(val, 16384 /* AwaitContext */); + } + function doOutsideOfContext(context, func) { + // contextFlagsToClear will contain only the context flags that are + // currently set that we need to temporarily clear + // We don't just blindly reset to the previous flags to ensure + // that we do not mutate cached flags for the incremental + // parser (ThisNodeHasError, ThisNodeOrAnySubNodesHasError, and + // HasAggregatedChildData). + var contextFlagsToClear = context & contextFlags; + if (contextFlagsToClear) { + // clear the requested context flags + setContextFlag(/*val*/ false, contextFlagsToClear); + var result = func(); + // restore the context flags we just cleared + setContextFlag(/*val*/ true, contextFlagsToClear); + return result; + } + // no need to do anything special as we are not in any of the requested contexts + return func(); + } + function doInsideOfContext(context, func) { + // contextFlagsToSet will contain only the context flags that + // are not currently set that we need to temporarily enable. + // We don't just blindly reset to the previous flags to ensure + // that we do not mutate cached flags for the incremental + // parser (ThisNodeHasError, ThisNodeOrAnySubNodesHasError, and + // HasAggregatedChildData). + var contextFlagsToSet = context & ~contextFlags; + if (contextFlagsToSet) { + // set the requested context flags + setContextFlag(/*val*/ true, contextFlagsToSet); + var result = func(); + // reset the context flags we just set + setContextFlag(/*val*/ false, contextFlagsToSet); + return result; + } + // no need to do anything special as we are already in all of the requested contexts + return func(); + } + function allowInAnd(func) { + return doOutsideOfContext(2048 /* DisallowInContext */, func); + } + function disallowInAnd(func) { + return doInsideOfContext(2048 /* DisallowInContext */, func); + } + function doInYieldContext(func) { + return doInsideOfContext(4096 /* YieldContext */, func); + } + function doInDecoratorContext(func) { + return doInsideOfContext(8192 /* DecoratorContext */, func); + } + function doInAwaitContext(func) { + return doInsideOfContext(16384 /* AwaitContext */, func); + } + function doOutsideOfAwaitContext(func) { + return doOutsideOfContext(16384 /* AwaitContext */, func); + } + function doInYieldAndAwaitContext(func) { + return doInsideOfContext(4096 /* YieldContext */ | 16384 /* AwaitContext */, func); + } + function inContext(flags) { + return (contextFlags & flags) !== 0; + } + function inYieldContext() { + return inContext(4096 /* YieldContext */); + } + function inDisallowInContext() { + return inContext(2048 /* DisallowInContext */); + } + function inDecoratorContext() { + return inContext(8192 /* DecoratorContext */); + } + function inAwaitContext() { + return inContext(16384 /* AwaitContext */); + } + function parseErrorAtCurrentToken(message, arg0) { + parseErrorAt(scanner.getTokenPos(), scanner.getTextPos(), message, arg0); + } + function parseErrorAtPosition(start, length, message, arg0) { + // Don't report another error if it would just be at the same position as the last error. + var lastError = ts.lastOrUndefined(parseDiagnostics); + if (!lastError || start !== lastError.start) { + parseDiagnostics.push(ts.createFileDiagnostic(sourceFile, start, length, message, arg0)); + } + // Mark that we've encountered an error. We'll set an appropriate bit on the next + // node we finish so that it can't be reused incrementally. + parseErrorBeforeNextFinishedNode = true; + } + function parseErrorAt(start, end, message, arg0) { + parseErrorAtPosition(start, end - start, message, arg0); + } + function parseErrorAtRange(range, message, arg0) { + parseErrorAt(range.pos, range.end, message, arg0); + } + function scanError(message, length) { + parseErrorAtPosition(scanner.getTextPos(), length, message); + } + function getNodePos() { + return scanner.getStartPos(); + } + // Use this function to access the current token instead of reading the currentToken + // variable. Since function results aren't narrowed in control flow analysis, this ensures + // that the type checker doesn't make wrong assumptions about the type of the current + // token (e.g. a call to nextToken() changes the current token but the checker doesn't + // reason about this side effect). Mainstream VMs inline simple functions like this, so + // there is no performance penalty. + function token() { + return currentToken; + } + function nextToken() { + return currentToken = scanner.scan(); + } + function reScanGreaterToken() { + return currentToken = scanner.reScanGreaterToken(); + } + function reScanSlashToken() { + return currentToken = scanner.reScanSlashToken(); + } + function reScanTemplateToken() { + return currentToken = scanner.reScanTemplateToken(); + } + function scanJsxIdentifier() { + return currentToken = scanner.scanJsxIdentifier(); + } + function scanJsxText() { + return currentToken = scanner.scanJsxToken(); + } + function scanJsxAttributeValue() { + return currentToken = scanner.scanJsxAttributeValue(); + } + function speculationHelper(callback, isLookAhead) { + // Keep track of the state we'll need to rollback to if lookahead fails (or if the + // caller asked us to always reset our state). + var saveToken = currentToken; + var saveParseDiagnosticsLength = parseDiagnostics.length; + var saveParseErrorBeforeNextFinishedNode = parseErrorBeforeNextFinishedNode; + // Note: it is not actually necessary to save/restore the context flags here. That's + // because the saving/restoring of these flags happens naturally through the recursive + // descent nature of our parser. However, we still store this here just so we can + // assert that invariant holds. + var saveContextFlags = contextFlags; + // If we're only looking ahead, then tell the scanner to only lookahead as well. + // Otherwise, if we're actually speculatively parsing, then tell the scanner to do the + // same. + var result = isLookAhead + ? scanner.lookAhead(callback) + : scanner.tryScan(callback); + ts.Debug.assert(saveContextFlags === contextFlags); + // If our callback returned something 'falsy' or we're just looking ahead, + // then unconditionally restore us to where we were. + if (!result || isLookAhead) { + currentToken = saveToken; + parseDiagnostics.length = saveParseDiagnosticsLength; + parseErrorBeforeNextFinishedNode = saveParseErrorBeforeNextFinishedNode; + } + return result; + } + /** Invokes the provided callback then unconditionally restores the parser to the state it + * was in immediately prior to invoking the callback. The result of invoking the callback + * is returned from this function. + */ + function lookAhead(callback) { + return speculationHelper(callback, /*isLookAhead*/ true); + } + /** Invokes the provided callback. If the callback returns something falsy, then it restores + * the parser to the state it was in immediately prior to invoking the callback. If the + * callback returns something truthy, then the parser state is not rolled back. The result + * of invoking the callback is returned from this function. + */ + function tryParse(callback) { + return speculationHelper(callback, /*isLookAhead*/ false); + } + // Ignore strict mode flag because we will report an error in type checker instead. + function isIdentifier() { + if (token() === 72 /* Identifier */) { + return true; + } + // If we have a 'yield' keyword, and we're in the [yield] context, then 'yield' is + // considered a keyword and is not an identifier. + if (token() === 117 /* YieldKeyword */ && inYieldContext()) { + return false; + } + // If we have a 'await' keyword, and we're in the [Await] context, then 'await' is + // considered a keyword and is not an identifier. + if (token() === 122 /* AwaitKeyword */ && inAwaitContext()) { + return false; + } + return token() > 108 /* LastReservedWord */; + } + function parseExpected(kind, diagnosticMessage, shouldAdvance) { + if (shouldAdvance === void 0) { shouldAdvance = true; } + if (token() === kind) { + if (shouldAdvance) { + nextToken(); + } + return true; + } + // Report specific message if provided with one. Otherwise, report generic fallback message. + if (diagnosticMessage) { + parseErrorAtCurrentToken(diagnosticMessage); + } + else { + parseErrorAtCurrentToken(ts.Diagnostics._0_expected, ts.tokenToString(kind)); + } + return false; + } + function parseOptional(t) { + if (token() === t) { + nextToken(); + return true; + } + return false; + } + function parseOptionalToken(t) { + if (token() === t) { + return parseTokenNode(); + } + return undefined; + } + function parseExpectedToken(t, diagnosticMessage, arg0) { + return parseOptionalToken(t) || + createMissingNode(t, /*reportAtCurrentPosition*/ false, diagnosticMessage || ts.Diagnostics._0_expected, arg0 || ts.tokenToString(t)); + } + function parseTokenNode() { + var node = createNode(token()); + nextToken(); + return finishNode(node); + } + function canParseSemicolon() { + // If there's a real semicolon, then we can always parse it out. + if (token() === 26 /* SemicolonToken */) { + return true; + } + // We can parse out an optional semicolon in ASI cases in the following cases. + return token() === 19 /* CloseBraceToken */ || token() === 1 /* EndOfFileToken */ || scanner.hasPrecedingLineBreak(); + } + function parseSemicolon() { + if (canParseSemicolon()) { + if (token() === 26 /* SemicolonToken */) { + // consume the semicolon if it was explicitly provided. + nextToken(); + } + return true; + } + else { + return parseExpected(26 /* SemicolonToken */); + } + } + function createNode(kind, pos) { + nodeCount++; + var p = pos >= 0 ? pos : scanner.getStartPos(); + return ts.isNodeKind(kind) || kind === 0 /* Unknown */ ? new NodeConstructor(kind, p, p) : + kind === 72 /* Identifier */ ? new IdentifierConstructor(kind, p, p) : + new TokenConstructor(kind, p, p); + } + function createNodeWithJSDoc(kind, pos) { + var node = createNode(kind, pos); + if (scanner.getTokenFlags() & 2 /* PrecedingJSDocComment */) { + addJSDocComment(node); + } + return node; + } + function createNodeArray(elements, pos, end) { + // Since the element list of a node array is typically created by starting with an empty array and + // repeatedly calling push(), the list may not have the optimal memory layout. We invoke slice() for + // small arrays (1 to 4 elements) to give the VM a chance to allocate an optimal representation. + var length = elements.length; + var array = (length >= 1 && length <= 4 ? elements.slice() : elements); + array.pos = pos; + array.end = end === undefined ? scanner.getStartPos() : end; + return array; + } + function finishNode(node, end) { + node.end = end === undefined ? scanner.getStartPos() : end; + if (contextFlags) { + node.flags |= contextFlags; + } + // Keep track on the node if we encountered an error while parsing it. If we did, then + // we cannot reuse the node incrementally. Once we've marked this node, clear out the + // flag so that we don't mark any subsequent nodes. + if (parseErrorBeforeNextFinishedNode) { + parseErrorBeforeNextFinishedNode = false; + node.flags |= 32768 /* ThisNodeHasError */; + } + return node; + } + function createMissingNode(kind, reportAtCurrentPosition, diagnosticMessage, arg0) { + if (reportAtCurrentPosition) { + parseErrorAtPosition(scanner.getStartPos(), 0, diagnosticMessage, arg0); + } + else if (diagnosticMessage) { + parseErrorAtCurrentToken(diagnosticMessage, arg0); + } + var result = createNode(kind); + if (kind === 72 /* Identifier */) { + result.escapedText = ""; + } + else if (ts.isLiteralKind(kind) || ts.isTemplateLiteralKind(kind)) { + result.text = ""; + } + return finishNode(result); + } + function internIdentifier(text) { + var identifier = identifiers.get(text); + if (identifier === undefined) { + identifiers.set(text, identifier = text); + } + return identifier; + } + // An identifier that starts with two underscores has an extra underscore character prepended to it to avoid issues + // with magic property names like '__proto__'. The 'identifiers' object is used to share a single string instance for + // each identifier in order to reduce memory consumption. + function createIdentifier(isIdentifier, diagnosticMessage) { + identifierCount++; + if (isIdentifier) { + var node = createNode(72 /* Identifier */); + // Store original token kind if it is not just an Identifier so we can report appropriate error later in type checker + if (token() !== 72 /* Identifier */) { + node.originalKeywordKind = token(); + } + node.escapedText = ts.escapeLeadingUnderscores(internIdentifier(scanner.getTokenValue())); + nextToken(); + return finishNode(node); + } + // Only for end of file because the error gets reported incorrectly on embedded script tags. + var reportAtCurrentPosition = token() === 1 /* EndOfFileToken */; + return createMissingNode(72 /* Identifier */, reportAtCurrentPosition, diagnosticMessage || ts.Diagnostics.Identifier_expected); + } + function parseIdentifier(diagnosticMessage) { + return createIdentifier(isIdentifier(), diagnosticMessage); + } + function parseIdentifierName(diagnosticMessage) { + return createIdentifier(ts.tokenIsIdentifierOrKeyword(token()), diagnosticMessage); + } + function isLiteralPropertyName() { + return ts.tokenIsIdentifierOrKeyword(token()) || + token() === 10 /* StringLiteral */ || + token() === 8 /* NumericLiteral */; + } + function parsePropertyNameWorker(allowComputedPropertyNames) { + if (token() === 10 /* StringLiteral */ || token() === 8 /* NumericLiteral */) { + var node = parseLiteralNode(); + node.text = internIdentifier(node.text); + return node; + } + if (allowComputedPropertyNames && token() === 22 /* OpenBracketToken */) { + return parseComputedPropertyName(); + } + return parseIdentifierName(); + } + function parsePropertyName() { + return parsePropertyNameWorker(/*allowComputedPropertyNames*/ true); + } + function parseComputedPropertyName() { + // PropertyName [Yield]: + // LiteralPropertyName + // ComputedPropertyName[?Yield] + var node = createNode(149 /* ComputedPropertyName */); + parseExpected(22 /* OpenBracketToken */); + // We parse any expression (including a comma expression). But the grammar + // says that only an assignment expression is allowed, so the grammar checker + // will error if it sees a comma expression. + node.expression = allowInAnd(parseExpression); + parseExpected(23 /* CloseBracketToken */); + return finishNode(node); + } + function parseContextualModifier(t) { + return token() === t && tryParse(nextTokenCanFollowModifier); + } + function nextTokenIsOnSameLineAndCanFollowModifier() { + nextToken(); + if (scanner.hasPrecedingLineBreak()) { + return false; + } + return canFollowModifier(); + } + function nextTokenCanFollowModifier() { + switch (token()) { + case 77 /* ConstKeyword */: + // 'const' is only a modifier if followed by 'enum'. + return nextToken() === 84 /* EnumKeyword */; + case 85 /* ExportKeyword */: + nextToken(); + if (token() === 80 /* DefaultKeyword */) { + return lookAhead(nextTokenCanFollowDefaultKeyword); + } + return token() !== 40 /* AsteriskToken */ && token() !== 119 /* AsKeyword */ && token() !== 18 /* OpenBraceToken */ && canFollowModifier(); + case 80 /* DefaultKeyword */: + return nextTokenCanFollowDefaultKeyword(); + case 116 /* StaticKeyword */: + case 126 /* GetKeyword */: + case 137 /* SetKeyword */: + nextToken(); + return canFollowModifier(); + default: + return nextTokenIsOnSameLineAndCanFollowModifier(); + } + } + function parseAnyContextualModifier() { + return ts.isModifierKind(token()) && tryParse(nextTokenCanFollowModifier); + } + function canFollowModifier() { + return token() === 22 /* OpenBracketToken */ + || token() === 18 /* OpenBraceToken */ + || token() === 40 /* AsteriskToken */ + || token() === 25 /* DotDotDotToken */ + || isLiteralPropertyName(); + } + function nextTokenCanFollowDefaultKeyword() { + nextToken(); + return token() === 76 /* ClassKeyword */ || token() === 90 /* FunctionKeyword */ || + token() === 110 /* InterfaceKeyword */ || + (token() === 118 /* AbstractKeyword */ && lookAhead(nextTokenIsClassKeywordOnSameLine)) || + (token() === 121 /* AsyncKeyword */ && lookAhead(nextTokenIsFunctionKeywordOnSameLine)); + } + // True if positioned at the start of a list element + function isListElement(parsingContext, inErrorRecovery) { + var node = currentNode(parsingContext); + if (node) { + return true; + } + switch (parsingContext) { + case 0 /* SourceElements */: + case 1 /* BlockStatements */: + case 3 /* SwitchClauseStatements */: + // If we're in error recovery, then we don't want to treat ';' as an empty statement. + // The problem is that ';' can show up in far too many contexts, and if we see one + // and assume it's a statement, then we may bail out inappropriately from whatever + // we're parsing. For example, if we have a semicolon in the middle of a class, then + // we really don't want to assume the class is over and we're on a statement in the + // outer module. We just want to consume and move on. + return !(token() === 26 /* SemicolonToken */ && inErrorRecovery) && isStartOfStatement(); + case 2 /* SwitchClauses */: + return token() === 74 /* CaseKeyword */ || token() === 80 /* DefaultKeyword */; + case 4 /* TypeMembers */: + return lookAhead(isTypeMemberStart); + case 5 /* ClassMembers */: + // We allow semicolons as class elements (as specified by ES6) as long as we're + // not in error recovery. If we're in error recovery, we don't want an errant + // semicolon to be treated as a class member (since they're almost always used + // for statements. + return lookAhead(isClassMemberStart) || (token() === 26 /* SemicolonToken */ && !inErrorRecovery); + case 6 /* EnumMembers */: + // Include open bracket computed properties. This technically also lets in indexers, + // which would be a candidate for improved error reporting. + return token() === 22 /* OpenBracketToken */ || isLiteralPropertyName(); + case 12 /* ObjectLiteralMembers */: + switch (token()) { + case 22 /* OpenBracketToken */: + case 40 /* AsteriskToken */: + case 25 /* DotDotDotToken */: + case 24 /* DotToken */: // Not an object literal member, but don't want to close the object (see `tests/cases/fourslash/completionsDotInObjectLiteral.ts`) + return true; + default: + return isLiteralPropertyName(); + } + case 18 /* RestProperties */: + return isLiteralPropertyName(); + case 9 /* ObjectBindingElements */: + return token() === 22 /* OpenBracketToken */ || token() === 25 /* DotDotDotToken */ || isLiteralPropertyName(); + case 7 /* HeritageClauseElement */: + // If we see `{ ... }` then only consume it as an expression if it is followed by `,` or `{` + // That way we won't consume the body of a class in its heritage clause. + if (token() === 18 /* OpenBraceToken */) { + return lookAhead(isValidHeritageClauseObjectLiteral); + } + if (!inErrorRecovery) { + return isStartOfLeftHandSideExpression() && !isHeritageClauseExtendsOrImplementsKeyword(); + } + else { + // If we're in error recovery we tighten up what we're willing to match. + // That way we don't treat something like "this" as a valid heritage clause + // element during recovery. + return isIdentifier() && !isHeritageClauseExtendsOrImplementsKeyword(); + } + case 8 /* VariableDeclarations */: + return isIdentifierOrPattern(); + case 10 /* ArrayBindingElements */: + return token() === 27 /* CommaToken */ || token() === 25 /* DotDotDotToken */ || isIdentifierOrPattern(); + case 19 /* TypeParameters */: + return isIdentifier(); + case 15 /* ArrayLiteralMembers */: + switch (token()) { + case 27 /* CommaToken */: + case 24 /* DotToken */: // Not an array literal member, but don't want to close the array (see `tests/cases/fourslash/completionsDotInArrayLiteralInObjectLiteral.ts`) + return true; + } + // falls through + case 11 /* ArgumentExpressions */: + return token() === 25 /* DotDotDotToken */ || isStartOfExpression(); + case 16 /* Parameters */: + return isStartOfParameter(/*isJSDocParameter*/ false); + case 17 /* JSDocParameters */: + return isStartOfParameter(/*isJSDocParameter*/ true); + case 20 /* TypeArguments */: + case 21 /* TupleElementTypes */: + return token() === 27 /* CommaToken */ || isStartOfType(); + case 22 /* HeritageClauses */: + return isHeritageClause(); + case 23 /* ImportOrExportSpecifiers */: + return ts.tokenIsIdentifierOrKeyword(token()); + case 13 /* JsxAttributes */: + return ts.tokenIsIdentifierOrKeyword(token()) || token() === 18 /* OpenBraceToken */; + case 14 /* JsxChildren */: + return true; + } + return ts.Debug.fail("Non-exhaustive case in 'isListElement'."); + } + function isValidHeritageClauseObjectLiteral() { + ts.Debug.assert(token() === 18 /* OpenBraceToken */); + if (nextToken() === 19 /* CloseBraceToken */) { + // if we see "extends {}" then only treat the {} as what we're extending (and not + // the class body) if we have: + // + // extends {} { + // extends {}, + // extends {} extends + // extends {} implements + var next = nextToken(); + return next === 27 /* CommaToken */ || next === 18 /* OpenBraceToken */ || next === 86 /* ExtendsKeyword */ || next === 109 /* ImplementsKeyword */; + } + return true; + } + function nextTokenIsIdentifier() { + nextToken(); + return isIdentifier(); + } + function nextTokenIsIdentifierOrKeyword() { + nextToken(); + return ts.tokenIsIdentifierOrKeyword(token()); + } + function nextTokenIsIdentifierOrKeywordOrGreaterThan() { + nextToken(); + return ts.tokenIsIdentifierOrKeywordOrGreaterThan(token()); + } + function isHeritageClauseExtendsOrImplementsKeyword() { + if (token() === 109 /* ImplementsKeyword */ || + token() === 86 /* ExtendsKeyword */) { + return lookAhead(nextTokenIsStartOfExpression); + } + return false; + } + function nextTokenIsStartOfExpression() { + nextToken(); + return isStartOfExpression(); + } + function nextTokenIsStartOfType() { + nextToken(); + return isStartOfType(); + } + // True if positioned at a list terminator + function isListTerminator(kind) { + if (token() === 1 /* EndOfFileToken */) { + // Being at the end of the file ends all lists. + return true; + } + switch (kind) { + case 1 /* BlockStatements */: + case 2 /* SwitchClauses */: + case 4 /* TypeMembers */: + case 5 /* ClassMembers */: + case 6 /* EnumMembers */: + case 12 /* ObjectLiteralMembers */: + case 9 /* ObjectBindingElements */: + case 23 /* ImportOrExportSpecifiers */: + return token() === 19 /* CloseBraceToken */; + case 3 /* SwitchClauseStatements */: + return token() === 19 /* CloseBraceToken */ || token() === 74 /* CaseKeyword */ || token() === 80 /* DefaultKeyword */; + case 7 /* HeritageClauseElement */: + return token() === 18 /* OpenBraceToken */ || token() === 86 /* ExtendsKeyword */ || token() === 109 /* ImplementsKeyword */; + case 8 /* VariableDeclarations */: + return isVariableDeclaratorListTerminator(); + case 19 /* TypeParameters */: + // Tokens other than '>' are here for better error recovery + return token() === 30 /* GreaterThanToken */ || token() === 20 /* OpenParenToken */ || token() === 18 /* OpenBraceToken */ || token() === 86 /* ExtendsKeyword */ || token() === 109 /* ImplementsKeyword */; + case 11 /* ArgumentExpressions */: + // Tokens other than ')' are here for better error recovery + return token() === 21 /* CloseParenToken */ || token() === 26 /* SemicolonToken */; + case 15 /* ArrayLiteralMembers */: + case 21 /* TupleElementTypes */: + case 10 /* ArrayBindingElements */: + return token() === 23 /* CloseBracketToken */; + case 17 /* JSDocParameters */: + case 16 /* Parameters */: + case 18 /* RestProperties */: + // Tokens other than ')' and ']' (the latter for index signatures) are here for better error recovery + return token() === 21 /* CloseParenToken */ || token() === 23 /* CloseBracketToken */ /*|| token === SyntaxKind.OpenBraceToken*/; + case 20 /* TypeArguments */: + // All other tokens should cause the type-argument to terminate except comma token + return token() !== 27 /* CommaToken */; + case 22 /* HeritageClauses */: + return token() === 18 /* OpenBraceToken */ || token() === 19 /* CloseBraceToken */; + case 13 /* JsxAttributes */: + return token() === 30 /* GreaterThanToken */ || token() === 42 /* SlashToken */; + case 14 /* JsxChildren */: + return token() === 28 /* LessThanToken */ && lookAhead(nextTokenIsSlash); + default: + return false; + } + } + function isVariableDeclaratorListTerminator() { + // If we can consume a semicolon (either explicitly, or with ASI), then consider us done + // with parsing the list of variable declarators. + if (canParseSemicolon()) { + return true; + } + // in the case where we're parsing the variable declarator of a 'for-in' statement, we + // are done if we see an 'in' keyword in front of us. Same with for-of + if (isInOrOfKeyword(token())) { + return true; + } + // ERROR RECOVERY TWEAK: + // For better error recovery, if we see an '=>' then we just stop immediately. We've got an + // arrow function here and it's going to be very unlikely that we'll resynchronize and get + // another variable declaration. + if (token() === 37 /* EqualsGreaterThanToken */) { + return true; + } + // Keep trying to parse out variable declarators. + return false; + } + // True if positioned at element or terminator of the current list or any enclosing list + function isInSomeParsingContext() { + for (var kind = 0; kind < 24 /* Count */; kind++) { + if (parsingContext & (1 << kind)) { + if (isListElement(kind, /*inErrorRecovery*/ true) || isListTerminator(kind)) { + return true; + } + } + } + return false; + } + // Parses a list of elements + function parseList(kind, parseElement) { + var saveParsingContext = parsingContext; + parsingContext |= 1 << kind; + var list = []; + var listPos = getNodePos(); + while (!isListTerminator(kind)) { + if (isListElement(kind, /*inErrorRecovery*/ false)) { + var element = parseListElement(kind, parseElement); + list.push(element); + continue; + } + if (abortParsingListOrMoveToNextToken(kind)) { + break; + } + } + parsingContext = saveParsingContext; + return createNodeArray(list, listPos); + } + function parseListElement(parsingContext, parseElement) { + var node = currentNode(parsingContext); + if (node) { + return consumeNode(node); + } + return parseElement(); + } + function currentNode(parsingContext) { + // If there is an outstanding parse error that we've encountered, but not attached to + // some node, then we cannot get a node from the old source tree. This is because we + // want to mark the next node we encounter as being unusable. + // + // Note: This may be too conservative. Perhaps we could reuse the node and set the bit + // on it (or its leftmost child) as having the error. For now though, being conservative + // is nice and likely won't ever affect perf. + if (parseErrorBeforeNextFinishedNode) { + return undefined; + } + if (!syntaxCursor) { + // if we don't have a cursor, we could never return a node from the old tree. + return undefined; + } + var node = syntaxCursor.currentNode(scanner.getStartPos()); + // Can't reuse a missing node. + if (ts.nodeIsMissing(node)) { + return undefined; + } + // Can't reuse a node that intersected the change range. + if (node.intersectsChange) { + return undefined; + } + // Can't reuse a node that contains a parse error. This is necessary so that we + // produce the same set of errors again. + if (ts.containsParseError(node)) { + return undefined; + } + // We can only reuse a node if it was parsed under the same strict mode that we're + // currently in. i.e. if we originally parsed a node in non-strict mode, but then + // the user added 'using strict' at the top of the file, then we can't use that node + // again as the presence of strict mode may cause us to parse the tokens in the file + // differently. + // + // Note: we *can* reuse tokens when the strict mode changes. That's because tokens + // are unaffected by strict mode. It's just the parser will decide what to do with it + // differently depending on what mode it is in. + // + // This also applies to all our other context flags as well. + var nodeContextFlags = node.flags & 12679168 /* ContextFlags */; + if (nodeContextFlags !== contextFlags) { + return undefined; + } + // Ok, we have a node that looks like it could be reused. Now verify that it is valid + // in the current list parsing context that we're currently at. + if (!canReuseNode(node, parsingContext)) { + return undefined; + } + if (node.jsDocCache) { + // jsDocCache may include tags from parent nodes, which might have been modified. + node.jsDocCache = undefined; + } + return node; + } + function consumeNode(node) { + // Move the scanner so it is after the node we just consumed. + scanner.setTextPos(node.end); + nextToken(); + return node; + } + function canReuseNode(node, parsingContext) { + switch (parsingContext) { + case 5 /* ClassMembers */: + return isReusableClassMember(node); + case 2 /* SwitchClauses */: + return isReusableSwitchClause(node); + case 0 /* SourceElements */: + case 1 /* BlockStatements */: + case 3 /* SwitchClauseStatements */: + return isReusableStatement(node); + case 6 /* EnumMembers */: + return isReusableEnumMember(node); + case 4 /* TypeMembers */: + return isReusableTypeMember(node); + case 8 /* VariableDeclarations */: + return isReusableVariableDeclaration(node); + case 17 /* JSDocParameters */: + case 16 /* Parameters */: + return isReusableParameter(node); + case 18 /* RestProperties */: + return false; + // Any other lists we do not care about reusing nodes in. But feel free to add if + // you can do so safely. Danger areas involve nodes that may involve speculative + // parsing. If speculative parsing is involved with the node, then the range the + // parser reached while looking ahead might be in the edited range (see the example + // in canReuseVariableDeclaratorNode for a good case of this). + case 22 /* HeritageClauses */: + // This would probably be safe to reuse. There is no speculative parsing with + // heritage clauses. + case 19 /* TypeParameters */: + // This would probably be safe to reuse. There is no speculative parsing with + // type parameters. Note that that's because type *parameters* only occur in + // unambiguous *type* contexts. While type *arguments* occur in very ambiguous + // *expression* contexts. + case 21 /* TupleElementTypes */: + // This would probably be safe to reuse. There is no speculative parsing with + // tuple types. + // Technically, type argument list types are probably safe to reuse. While + // speculative parsing is involved with them (since type argument lists are only + // produced from speculative parsing a < as a type argument list), we only have + // the types because speculative parsing succeeded. Thus, the lookahead never + // went past the end of the list and rewound. + case 20 /* TypeArguments */: + // Note: these are almost certainly not safe to ever reuse. Expressions commonly + // need a large amount of lookahead, and we should not reuse them as they may + // have actually intersected the edit. + case 11 /* ArgumentExpressions */: + // This is not safe to reuse for the same reason as the 'AssignmentExpression' + // cases. i.e. a property assignment may end with an expression, and thus might + // have lookahead far beyond it's old node. + case 12 /* ObjectLiteralMembers */: + // This is probably not safe to reuse. There can be speculative parsing with + // type names in a heritage clause. There can be generic names in the type + // name list, and there can be left hand side expressions (which can have type + // arguments.) + case 7 /* HeritageClauseElement */: + // Perhaps safe to reuse, but it's unlikely we'd see more than a dozen attributes + // on any given element. Same for children. + case 13 /* JsxAttributes */: + case 14 /* JsxChildren */: + } + return false; + } + function isReusableClassMember(node) { + if (node) { + switch (node.kind) { + case 157 /* Constructor */: + case 162 /* IndexSignature */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 154 /* PropertyDeclaration */: + case 217 /* SemicolonClassElement */: + return true; + case 156 /* MethodDeclaration */: + // Method declarations are not necessarily reusable. An object-literal + // may have a method calls "constructor(...)" and we must reparse that + // into an actual .ConstructorDeclaration. + var methodDeclaration = node; + var nameIsConstructor = methodDeclaration.name.kind === 72 /* Identifier */ && + methodDeclaration.name.originalKeywordKind === 124 /* ConstructorKeyword */; + return !nameIsConstructor; + } + } + return false; + } + function isReusableSwitchClause(node) { + if (node) { + switch (node.kind) { + case 271 /* CaseClause */: + case 272 /* DefaultClause */: + return true; + } + } + return false; + } + function isReusableStatement(node) { + if (node) { + switch (node.kind) { + case 239 /* FunctionDeclaration */: + case 219 /* VariableStatement */: + case 218 /* Block */: + case 222 /* IfStatement */: + case 221 /* ExpressionStatement */: + case 234 /* ThrowStatement */: + case 230 /* ReturnStatement */: + case 232 /* SwitchStatement */: + case 229 /* BreakStatement */: + case 228 /* ContinueStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + case 225 /* ForStatement */: + case 224 /* WhileStatement */: + case 231 /* WithStatement */: + case 220 /* EmptyStatement */: + case 235 /* TryStatement */: + case 233 /* LabeledStatement */: + case 223 /* DoStatement */: + case 236 /* DebuggerStatement */: + case 249 /* ImportDeclaration */: + case 248 /* ImportEqualsDeclaration */: + case 255 /* ExportDeclaration */: + case 254 /* ExportAssignment */: + case 244 /* ModuleDeclaration */: + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + case 243 /* EnumDeclaration */: + case 242 /* TypeAliasDeclaration */: + return true; + } + } + return false; + } + function isReusableEnumMember(node) { + return node.kind === 278 /* EnumMember */; + } + function isReusableTypeMember(node) { + if (node) { + switch (node.kind) { + case 161 /* ConstructSignature */: + case 155 /* MethodSignature */: + case 162 /* IndexSignature */: + case 153 /* PropertySignature */: + case 160 /* CallSignature */: + return true; + } + } + return false; + } + function isReusableVariableDeclaration(node) { + if (node.kind !== 237 /* VariableDeclaration */) { + return false; + } + // Very subtle incremental parsing bug. Consider the following code: + // + // let v = new List < A, B + // + // This is actually legal code. It's a list of variable declarators "v = new List() + // + // then we have a problem. "v = new List= 0) { + // Always preserve a trailing comma by marking it on the NodeArray + result.hasTrailingComma = true; + } + return result; + } + function createMissingList() { + var list = createNodeArray([], getNodePos()); + list.isMissingList = true; + return list; + } + function isMissingList(arr) { + return !!arr.isMissingList; + } + function parseBracketedList(kind, parseElement, open, close) { + if (parseExpected(open)) { + var result = parseDelimitedList(kind, parseElement); + parseExpected(close); + return result; + } + return createMissingList(); + } + function parseEntityName(allowReservedWords, diagnosticMessage) { + var entity = allowReservedWords ? parseIdentifierName(diagnosticMessage) : parseIdentifier(diagnosticMessage); + var dotPos = scanner.getStartPos(); + while (parseOptional(24 /* DotToken */)) { + if (token() === 28 /* LessThanToken */) { + // the entity is part of a JSDoc-style generic, so record the trailing dot for later error reporting + entity.jsdocDotPos = dotPos; + break; + } + dotPos = scanner.getStartPos(); + entity = createQualifiedName(entity, parseRightSideOfDot(allowReservedWords)); + } + return entity; + } + function createQualifiedName(entity, name) { + var node = createNode(148 /* QualifiedName */, entity.pos); + node.left = entity; + node.right = name; + return finishNode(node); + } + function parseRightSideOfDot(allowIdentifierNames) { + // Technically a keyword is valid here as all identifiers and keywords are identifier names. + // However, often we'll encounter this in error situations when the identifier or keyword + // is actually starting another valid construct. + // + // So, we check for the following specific case: + // + // name. + // identifierOrKeyword identifierNameOrKeyword + // + // Note: the newlines are important here. For example, if that above code + // were rewritten into: + // + // name.identifierOrKeyword + // identifierNameOrKeyword + // + // Then we would consider it valid. That's because ASI would take effect and + // the code would be implicitly: "name.identifierOrKeyword; identifierNameOrKeyword". + // In the first case though, ASI will not take effect because there is not a + // line terminator after the identifier or keyword. + if (scanner.hasPrecedingLineBreak() && ts.tokenIsIdentifierOrKeyword(token())) { + var matchesPattern = lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine); + if (matchesPattern) { + // Report that we need an identifier. However, report it right after the dot, + // and not on the next token. This is because the next token might actually + // be an identifier and the error would be quite confusing. + return createMissingNode(72 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Identifier_expected); + } + } + return allowIdentifierNames ? parseIdentifierName() : parseIdentifier(); + } + function parseTemplateExpression() { + var template = createNode(206 /* TemplateExpression */); + template.head = parseTemplateHead(); + ts.Debug.assert(template.head.kind === 15 /* TemplateHead */, "Template head has wrong token kind"); + var list = []; + var listPos = getNodePos(); + do { + list.push(parseTemplateSpan()); + } while (ts.last(list).literal.kind === 16 /* TemplateMiddle */); + template.templateSpans = createNodeArray(list, listPos); + return finishNode(template); + } + function parseTemplateSpan() { + var span = createNode(216 /* TemplateSpan */); + span.expression = allowInAnd(parseExpression); + var literal; + if (token() === 19 /* CloseBraceToken */) { + reScanTemplateToken(); + literal = parseTemplateMiddleOrTemplateTail(); + } + else { + literal = parseExpectedToken(17 /* TemplateTail */, ts.Diagnostics._0_expected, ts.tokenToString(19 /* CloseBraceToken */)); + } + span.literal = literal; + return finishNode(span); + } + function parseLiteralNode() { + return parseLiteralLikeNode(token()); + } + function parseTemplateHead() { + var fragment = parseLiteralLikeNode(token()); + ts.Debug.assert(fragment.kind === 15 /* TemplateHead */, "Template head has wrong token kind"); + return fragment; + } + function parseTemplateMiddleOrTemplateTail() { + var fragment = parseLiteralLikeNode(token()); + ts.Debug.assert(fragment.kind === 16 /* TemplateMiddle */ || fragment.kind === 17 /* TemplateTail */, "Template fragment has wrong token kind"); + return fragment; + } + function parseLiteralLikeNode(kind) { + var node = createNode(kind); + node.text = scanner.getTokenValue(); + if (scanner.hasExtendedUnicodeEscape()) { + node.hasExtendedUnicodeEscape = true; + } + if (scanner.isUnterminated()) { + node.isUnterminated = true; + } + // Octal literals are not allowed in strict mode or ES5 + // Note that theoretically the following condition would hold true literals like 009, + // which is not octal.But because of how the scanner separates the tokens, we would + // never get a token like this. Instead, we would get 00 and 9 as two separate tokens. + // We also do not need to check for negatives because any prefix operator would be part of a + // parent unary expression. + if (node.kind === 8 /* NumericLiteral */) { + node.numericLiteralFlags = scanner.getTokenFlags() & 1008 /* NumericLiteralFlags */; + } + nextToken(); + finishNode(node); + return node; + } + // TYPES + function parseTypeReference() { + var node = createNode(164 /* TypeReference */); + node.typeName = parseEntityName(/*allowReservedWords*/ true, ts.Diagnostics.Type_expected); + if (!scanner.hasPrecedingLineBreak() && token() === 28 /* LessThanToken */) { + node.typeArguments = parseBracketedList(20 /* TypeArguments */, parseType, 28 /* LessThanToken */, 30 /* GreaterThanToken */); + } + return finishNode(node); + } + // If true, we should abort parsing an error function. + function typeHasArrowFunctionBlockingParseError(node) { + switch (node.kind) { + case 164 /* TypeReference */: + return ts.nodeIsMissing(node.typeName); + case 165 /* FunctionType */: + case 166 /* ConstructorType */: { + var _a = node, parameters = _a.parameters, type = _a.type; + return isMissingList(parameters) || typeHasArrowFunctionBlockingParseError(type); + } + case 177 /* ParenthesizedType */: + return typeHasArrowFunctionBlockingParseError(node.type); + default: + return false; + } + } + function parseThisTypePredicate(lhs) { + nextToken(); + var node = createNode(163 /* TypePredicate */, lhs.pos); + node.parameterName = lhs; + node.type = parseType(); + return finishNode(node); + } + function parseThisTypeNode() { + var node = createNode(178 /* ThisType */); + nextToken(); + return finishNode(node); + } + function parseJSDocAllType(postFixEquals) { + var result = createNode(284 /* JSDocAllType */); + if (postFixEquals) { + return createPostfixType(288 /* JSDocOptionalType */, result); + } + else { + nextToken(); + } + return finishNode(result); + } + function parseJSDocNonNullableType() { + var result = createNode(287 /* JSDocNonNullableType */); + nextToken(); + result.type = parseNonArrayType(); + return finishNode(result); + } + function parseJSDocUnknownOrNullableType() { + var pos = scanner.getStartPos(); + // skip the ? + nextToken(); + // Need to lookahead to decide if this is a nullable or unknown type. + // Here are cases where we'll pick the unknown type: + // + // Foo(?, + // { a: ? } + // Foo(?) + // Foo + // Foo(?= + // (?| + if (token() === 27 /* CommaToken */ || + token() === 19 /* CloseBraceToken */ || + token() === 21 /* CloseParenToken */ || + token() === 30 /* GreaterThanToken */ || + token() === 59 /* EqualsToken */ || + token() === 50 /* BarToken */) { + var result = createNode(285 /* JSDocUnknownType */, pos); + return finishNode(result); + } + else { + var result = createNode(286 /* JSDocNullableType */, pos); + result.type = parseType(); + return finishNode(result); + } + } + function parseJSDocFunctionType() { + if (lookAhead(nextTokenIsOpenParen)) { + var result = createNodeWithJSDoc(289 /* JSDocFunctionType */); + nextToken(); + fillSignature(57 /* ColonToken */, 4 /* Type */ | 32 /* JSDoc */, result); + return finishNode(result); + } + var node = createNode(164 /* TypeReference */); + node.typeName = parseIdentifierName(); + return finishNode(node); + } + function parseJSDocParameter() { + var parameter = createNode(151 /* Parameter */); + if (token() === 100 /* ThisKeyword */ || token() === 95 /* NewKeyword */) { + parameter.name = parseIdentifierName(); + parseExpected(57 /* ColonToken */); + } + parameter.type = parseJSDocType(); + return finishNode(parameter); + } + function parseJSDocType() { + scanner.setInJSDocType(true); + var dotdotdot = parseOptionalToken(25 /* DotDotDotToken */); + var type = parseTypeOrTypePredicate(); + scanner.setInJSDocType(false); + if (dotdotdot) { + var variadic = createNode(290 /* JSDocVariadicType */, dotdotdot.pos); + variadic.type = type; + type = finishNode(variadic); + } + if (token() === 59 /* EqualsToken */) { + return createPostfixType(288 /* JSDocOptionalType */, type); + } + return type; + } + function parseTypeQuery() { + var node = createNode(167 /* TypeQuery */); + parseExpected(104 /* TypeOfKeyword */); + node.exprName = parseEntityName(/*allowReservedWords*/ true); + return finishNode(node); + } + function parseTypeParameter() { + var node = createNode(150 /* TypeParameter */); + node.name = parseIdentifier(); + if (parseOptional(86 /* ExtendsKeyword */)) { + // It's not uncommon for people to write improper constraints to a generic. If the + // user writes a constraint that is an expression and not an actual type, then parse + // it out as an expression (so we can recover well), but report that a type is needed + // instead. + if (isStartOfType() || !isStartOfExpression()) { + node.constraint = parseType(); + } + else { + // It was not a type, and it looked like an expression. Parse out an expression + // here so we recover well. Note: it is important that we call parseUnaryExpression + // and not parseExpression here. If the user has: + // + // + // + // We do *not* want to consume the `>` as we're consuming the expression for "". + node.expression = parseUnaryExpressionOrHigher(); + } + } + if (parseOptional(59 /* EqualsToken */)) { + node.default = parseType(); + } + return finishNode(node); + } + function parseTypeParameters() { + if (token() === 28 /* LessThanToken */) { + return parseBracketedList(19 /* TypeParameters */, parseTypeParameter, 28 /* LessThanToken */, 30 /* GreaterThanToken */); + } + } + function parseParameterType() { + if (parseOptional(57 /* ColonToken */)) { + return parseType(); + } + return undefined; + } + function isStartOfParameter(isJSDocParameter) { + return token() === 25 /* DotDotDotToken */ || + isIdentifierOrPattern() || + ts.isModifierKind(token()) || + token() === 58 /* AtToken */ || + isStartOfType(/*inStartOfParameter*/ !isJSDocParameter); + } + function parseParameter() { + var node = createNodeWithJSDoc(151 /* Parameter */); + if (token() === 100 /* ThisKeyword */) { + node.name = createIdentifier(/*isIdentifier*/ true); + node.type = parseParameterType(); + return finishNode(node); + } + node.decorators = parseDecorators(); + node.modifiers = parseModifiers(); + node.dotDotDotToken = parseOptionalToken(25 /* DotDotDotToken */); + // FormalParameter [Yield,Await]: + // BindingElement[?Yield,?Await] + node.name = parseIdentifierOrPattern(); + if (ts.getFullWidth(node.name) === 0 && !ts.hasModifiers(node) && ts.isModifierKind(token())) { + // in cases like + // 'use strict' + // function foo(static) + // isParameter('static') === true, because of isModifier('static') + // however 'static' is not a legal identifier in a strict mode. + // so result of this function will be ParameterDeclaration (flags = 0, name = missing, type = undefined, initializer = undefined) + // and current token will not change => parsing of the enclosing parameter list will last till the end of time (or OOM) + // to avoid this we'll advance cursor to the next token. + nextToken(); + } + node.questionToken = parseOptionalToken(56 /* QuestionToken */); + node.type = parseParameterType(); + node.initializer = parseInitializer(); + return finishNode(node); + } + /** + * Note: If returnToken is EqualsGreaterThanToken, `signature.type` will always be defined. + * @returns If return type parsing succeeds + */ + function fillSignature(returnToken, flags, signature) { + if (!(flags & 32 /* JSDoc */)) { + signature.typeParameters = parseTypeParameters(); + } + var parametersParsedSuccessfully = parseParameterList(signature, flags); + if (shouldParseReturnType(returnToken, !!(flags & 4 /* Type */))) { + signature.type = parseTypeOrTypePredicate(); + if (typeHasArrowFunctionBlockingParseError(signature.type)) + return false; + } + return parametersParsedSuccessfully; + } + function shouldParseReturnType(returnToken, isType) { + if (returnToken === 37 /* EqualsGreaterThanToken */) { + parseExpected(returnToken); + return true; + } + else if (parseOptional(57 /* ColonToken */)) { + return true; + } + else if (isType && token() === 37 /* EqualsGreaterThanToken */) { + // This is easy to get backward, especially in type contexts, so parse the type anyway + parseErrorAtCurrentToken(ts.Diagnostics._0_expected, ts.tokenToString(57 /* ColonToken */)); + nextToken(); + return true; + } + return false; + } + // Returns true on success. + function parseParameterList(signature, flags) { + // FormalParameters [Yield,Await]: (modified) + // [empty] + // FormalParameterList[?Yield,Await] + // + // FormalParameter[Yield,Await]: (modified) + // BindingElement[?Yield,Await] + // + // BindingElement [Yield,Await]: (modified) + // SingleNameBinding[?Yield,?Await] + // BindingPattern[?Yield,?Await]Initializer [In, ?Yield,?Await] opt + // + // SingleNameBinding [Yield,Await]: + // BindingIdentifier[?Yield,?Await]Initializer [In, ?Yield,?Await] opt + if (!parseExpected(20 /* OpenParenToken */)) { + signature.parameters = createMissingList(); + return false; + } + var savedYieldContext = inYieldContext(); + var savedAwaitContext = inAwaitContext(); + setYieldContext(!!(flags & 1 /* Yield */)); + setAwaitContext(!!(flags & 2 /* Await */)); + signature.parameters = flags & 32 /* JSDoc */ ? + parseDelimitedList(17 /* JSDocParameters */, parseJSDocParameter) : + parseDelimitedList(16 /* Parameters */, parseParameter); + setYieldContext(savedYieldContext); + setAwaitContext(savedAwaitContext); + return parseExpected(21 /* CloseParenToken */); + } + function parseTypeMemberSemicolon() { + // We allow type members to be separated by commas or (possibly ASI) semicolons. + // First check if it was a comma. If so, we're done with the member. + if (parseOptional(27 /* CommaToken */)) { + return; + } + // Didn't have a comma. We must have a (possible ASI) semicolon. + parseSemicolon(); + } + function parseSignatureMember(kind) { + var node = createNodeWithJSDoc(kind); + if (kind === 161 /* ConstructSignature */) { + parseExpected(95 /* NewKeyword */); + } + fillSignature(57 /* ColonToken */, 4 /* Type */, node); + parseTypeMemberSemicolon(); + return finishNode(node); + } + function isIndexSignature() { + return token() === 22 /* OpenBracketToken */ && lookAhead(isUnambiguouslyIndexSignature); + } + function isUnambiguouslyIndexSignature() { + // The only allowed sequence is: + // + // [id: + // + // However, for error recovery, we also check the following cases: + // + // [... + // [id, + // [id?, + // [id?: + // [id?] + // [public id + // [private id + // [protected id + // [] + // + nextToken(); + if (token() === 25 /* DotDotDotToken */ || token() === 23 /* CloseBracketToken */) { + return true; + } + if (ts.isModifierKind(token())) { + nextToken(); + if (isIdentifier()) { + return true; + } + } + else if (!isIdentifier()) { + return false; + } + else { + // Skip the identifier + nextToken(); + } + // A colon signifies a well formed indexer + // A comma should be a badly formed indexer because comma expressions are not allowed + // in computed properties. + if (token() === 57 /* ColonToken */ || token() === 27 /* CommaToken */) { + return true; + } + // Question mark could be an indexer with an optional property, + // or it could be a conditional expression in a computed property. + if (token() !== 56 /* QuestionToken */) { + return false; + } + // If any of the following tokens are after the question mark, it cannot + // be a conditional expression, so treat it as an indexer. + nextToken(); + return token() === 57 /* ColonToken */ || token() === 27 /* CommaToken */ || token() === 23 /* CloseBracketToken */; + } + function parseIndexSignatureDeclaration(node) { + node.kind = 162 /* IndexSignature */; + node.parameters = parseBracketedList(16 /* Parameters */, parseParameter, 22 /* OpenBracketToken */, 23 /* CloseBracketToken */); + node.type = parseTypeAnnotation(); + parseTypeMemberSemicolon(); + return finishNode(node); + } + function parsePropertyOrMethodSignature(node) { + node.name = parsePropertyName(); + node.questionToken = parseOptionalToken(56 /* QuestionToken */); + if (token() === 20 /* OpenParenToken */ || token() === 28 /* LessThanToken */) { + node.kind = 155 /* MethodSignature */; + // Method signatures don't exist in expression contexts. So they have neither + // [Yield] nor [Await] + fillSignature(57 /* ColonToken */, 4 /* Type */, node); + } + else { + node.kind = 153 /* PropertySignature */; + node.type = parseTypeAnnotation(); + if (token() === 59 /* EqualsToken */) { + // Although type literal properties cannot not have initializers, we attempt + // to parse an initializer so we can report in the checker that an interface + // property or type literal property cannot have an initializer. + node.initializer = parseInitializer(); + } + } + parseTypeMemberSemicolon(); + return finishNode(node); + } + function isTypeMemberStart() { + // Return true if we have the start of a signature member + if (token() === 20 /* OpenParenToken */ || token() === 28 /* LessThanToken */) { + return true; + } + var idToken = false; + // Eat up all modifiers, but hold on to the last one in case it is actually an identifier + while (ts.isModifierKind(token())) { + idToken = true; + nextToken(); + } + // Index signatures and computed property names are type members + if (token() === 22 /* OpenBracketToken */) { + return true; + } + // Try to get the first property-like token following all modifiers + if (isLiteralPropertyName()) { + idToken = true; + nextToken(); + } + // If we were able to get any potential identifier, check that it is + // the start of a member declaration + if (idToken) { + return token() === 20 /* OpenParenToken */ || + token() === 28 /* LessThanToken */ || + token() === 56 /* QuestionToken */ || + token() === 57 /* ColonToken */ || + token() === 27 /* CommaToken */ || + canParseSemicolon(); + } + return false; + } + function parseTypeMember() { + if (token() === 20 /* OpenParenToken */ || token() === 28 /* LessThanToken */) { + return parseSignatureMember(160 /* CallSignature */); + } + if (token() === 95 /* NewKeyword */ && lookAhead(nextTokenIsOpenParenOrLessThan)) { + return parseSignatureMember(161 /* ConstructSignature */); + } + var node = createNodeWithJSDoc(0 /* Unknown */); + node.modifiers = parseModifiers(); + if (isIndexSignature()) { + return parseIndexSignatureDeclaration(node); + } + return parsePropertyOrMethodSignature(node); + } + function nextTokenIsOpenParenOrLessThan() { + nextToken(); + return token() === 20 /* OpenParenToken */ || token() === 28 /* LessThanToken */; + } + function nextTokenIsDot() { + return nextToken() === 24 /* DotToken */; + } + function nextTokenIsOpenParenOrLessThanOrDot() { + switch (nextToken()) { + case 20 /* OpenParenToken */: + case 28 /* LessThanToken */: + case 24 /* DotToken */: + return true; + } + return false; + } + function parseTypeLiteral() { + var node = createNode(168 /* TypeLiteral */); + node.members = parseObjectTypeMembers(); + return finishNode(node); + } + function parseObjectTypeMembers() { + var members; + if (parseExpected(18 /* OpenBraceToken */)) { + members = parseList(4 /* TypeMembers */, parseTypeMember); + parseExpected(19 /* CloseBraceToken */); + } + else { + members = createMissingList(); + } + return members; + } + function isStartOfMappedType() { + nextToken(); + if (token() === 38 /* PlusToken */ || token() === 39 /* MinusToken */) { + return nextToken() === 133 /* ReadonlyKeyword */; + } + if (token() === 133 /* ReadonlyKeyword */) { + nextToken(); + } + return token() === 22 /* OpenBracketToken */ && nextTokenIsIdentifier() && nextToken() === 93 /* InKeyword */; + } + function parseMappedTypeParameter() { + var node = createNode(150 /* TypeParameter */); + node.name = parseIdentifier(); + parseExpected(93 /* InKeyword */); + node.constraint = parseType(); + return finishNode(node); + } + function parseMappedType() { + var node = createNode(181 /* MappedType */); + parseExpected(18 /* OpenBraceToken */); + if (token() === 133 /* ReadonlyKeyword */ || token() === 38 /* PlusToken */ || token() === 39 /* MinusToken */) { + node.readonlyToken = parseTokenNode(); + if (node.readonlyToken.kind !== 133 /* ReadonlyKeyword */) { + parseExpectedToken(133 /* ReadonlyKeyword */); + } + } + parseExpected(22 /* OpenBracketToken */); + node.typeParameter = parseMappedTypeParameter(); + parseExpected(23 /* CloseBracketToken */); + if (token() === 56 /* QuestionToken */ || token() === 38 /* PlusToken */ || token() === 39 /* MinusToken */) { + node.questionToken = parseTokenNode(); + if (node.questionToken.kind !== 56 /* QuestionToken */) { + parseExpectedToken(56 /* QuestionToken */); + } + } + node.type = parseTypeAnnotation(); + parseSemicolon(); + parseExpected(19 /* CloseBraceToken */); + return finishNode(node); + } + function parseTupleElementType() { + var pos = getNodePos(); + if (parseOptional(25 /* DotDotDotToken */)) { + var node = createNode(172 /* RestType */, pos); + node.type = parseType(); + return finishNode(node); + } + var type = parseType(); + if (!(contextFlags & 2097152 /* JSDoc */) && type.kind === 286 /* JSDocNullableType */ && type.pos === type.type.pos) { + type.kind = 171 /* OptionalType */; + } + return type; + } + function parseTupleType() { + var node = createNode(170 /* TupleType */); + node.elementTypes = parseBracketedList(21 /* TupleElementTypes */, parseTupleElementType, 22 /* OpenBracketToken */, 23 /* CloseBracketToken */); + return finishNode(node); + } + function parseParenthesizedType() { + var node = createNode(177 /* ParenthesizedType */); + parseExpected(20 /* OpenParenToken */); + node.type = parseType(); + parseExpected(21 /* CloseParenToken */); + return finishNode(node); + } + function parseFunctionOrConstructorType() { + var pos = getNodePos(); + var kind = parseOptional(95 /* NewKeyword */) ? 166 /* ConstructorType */ : 165 /* FunctionType */; + var node = createNodeWithJSDoc(kind, pos); + fillSignature(37 /* EqualsGreaterThanToken */, 4 /* Type */, node); + return finishNode(node); + } + function parseKeywordAndNoDot() { + var node = parseTokenNode(); + return token() === 24 /* DotToken */ ? undefined : node; + } + function parseLiteralTypeNode(negative) { + var node = createNode(182 /* LiteralType */); + var unaryMinusExpression; + if (negative) { + unaryMinusExpression = createNode(202 /* PrefixUnaryExpression */); + unaryMinusExpression.operator = 39 /* MinusToken */; + nextToken(); + } + var expression = token() === 102 /* TrueKeyword */ || token() === 87 /* FalseKeyword */ + ? parseTokenNode() + : parseLiteralLikeNode(token()); + if (negative) { + unaryMinusExpression.operand = expression; + finishNode(unaryMinusExpression); + expression = unaryMinusExpression; + } + node.literal = expression; + return finishNode(node); + } + function isStartOfTypeOfImportType() { + nextToken(); + return token() === 92 /* ImportKeyword */; + } + function parseImportType() { + sourceFile.flags |= 524288 /* PossiblyContainsDynamicImport */; + var node = createNode(183 /* ImportType */); + if (parseOptional(104 /* TypeOfKeyword */)) { + node.isTypeOf = true; + } + parseExpected(92 /* ImportKeyword */); + parseExpected(20 /* OpenParenToken */); + node.argument = parseType(); + parseExpected(21 /* CloseParenToken */); + if (parseOptional(24 /* DotToken */)) { + node.qualifier = parseEntityName(/*allowReservedWords*/ true, ts.Diagnostics.Type_expected); + } + node.typeArguments = tryParseTypeArguments(); + return finishNode(node); + } + function nextTokenIsNumericOrBigIntLiteral() { + nextToken(); + return token() === 8 /* NumericLiteral */ || token() === 9 /* BigIntLiteral */; + } + function parseNonArrayType() { + switch (token()) { + case 120 /* AnyKeyword */: + case 143 /* UnknownKeyword */: + case 138 /* StringKeyword */: + case 135 /* NumberKeyword */: + case 146 /* BigIntKeyword */: + case 139 /* SymbolKeyword */: + case 123 /* BooleanKeyword */: + case 141 /* UndefinedKeyword */: + case 132 /* NeverKeyword */: + case 136 /* ObjectKeyword */: + // If these are followed by a dot, then parse these out as a dotted type reference instead. + return tryParse(parseKeywordAndNoDot) || parseTypeReference(); + case 40 /* AsteriskToken */: + return parseJSDocAllType(/*postfixEquals*/ false); + case 62 /* AsteriskEqualsToken */: + return parseJSDocAllType(/*postfixEquals*/ true); + case 56 /* QuestionToken */: + return parseJSDocUnknownOrNullableType(); + case 90 /* FunctionKeyword */: + return parseJSDocFunctionType(); + case 52 /* ExclamationToken */: + return parseJSDocNonNullableType(); + case 14 /* NoSubstitutionTemplateLiteral */: + case 10 /* StringLiteral */: + case 8 /* NumericLiteral */: + case 9 /* BigIntLiteral */: + case 102 /* TrueKeyword */: + case 87 /* FalseKeyword */: + return parseLiteralTypeNode(); + case 39 /* MinusToken */: + return lookAhead(nextTokenIsNumericOrBigIntLiteral) ? parseLiteralTypeNode(/*negative*/ true) : parseTypeReference(); + case 106 /* VoidKeyword */: + case 96 /* NullKeyword */: + return parseTokenNode(); + case 100 /* ThisKeyword */: { + var thisKeyword = parseThisTypeNode(); + if (token() === 128 /* IsKeyword */ && !scanner.hasPrecedingLineBreak()) { + return parseThisTypePredicate(thisKeyword); + } + else { + return thisKeyword; + } + } + case 104 /* TypeOfKeyword */: + return lookAhead(isStartOfTypeOfImportType) ? parseImportType() : parseTypeQuery(); + case 18 /* OpenBraceToken */: + return lookAhead(isStartOfMappedType) ? parseMappedType() : parseTypeLiteral(); + case 22 /* OpenBracketToken */: + return parseTupleType(); + case 20 /* OpenParenToken */: + return parseParenthesizedType(); + case 92 /* ImportKeyword */: + return parseImportType(); + default: + return parseTypeReference(); + } + } + function isStartOfType(inStartOfParameter) { + switch (token()) { + case 120 /* AnyKeyword */: + case 143 /* UnknownKeyword */: + case 138 /* StringKeyword */: + case 135 /* NumberKeyword */: + case 146 /* BigIntKeyword */: + case 123 /* BooleanKeyword */: + case 139 /* SymbolKeyword */: + case 142 /* UniqueKeyword */: + case 106 /* VoidKeyword */: + case 141 /* UndefinedKeyword */: + case 96 /* NullKeyword */: + case 100 /* ThisKeyword */: + case 104 /* TypeOfKeyword */: + case 132 /* NeverKeyword */: + case 18 /* OpenBraceToken */: + case 22 /* OpenBracketToken */: + case 28 /* LessThanToken */: + case 50 /* BarToken */: + case 49 /* AmpersandToken */: + case 95 /* NewKeyword */: + case 10 /* StringLiteral */: + case 8 /* NumericLiteral */: + case 9 /* BigIntLiteral */: + case 102 /* TrueKeyword */: + case 87 /* FalseKeyword */: + case 136 /* ObjectKeyword */: + case 40 /* AsteriskToken */: + case 56 /* QuestionToken */: + case 52 /* ExclamationToken */: + case 25 /* DotDotDotToken */: + case 127 /* InferKeyword */: + case 92 /* ImportKeyword */: + return true; + case 90 /* FunctionKeyword */: + return !inStartOfParameter; + case 39 /* MinusToken */: + return !inStartOfParameter && lookAhead(nextTokenIsNumericOrBigIntLiteral); + case 20 /* OpenParenToken */: + // Only consider '(' the start of a type if followed by ')', '...', an identifier, a modifier, + // or something that starts a type. We don't want to consider things like '(1)' a type. + return !inStartOfParameter && lookAhead(isStartOfParenthesizedOrFunctionType); + default: + return isIdentifier(); + } + } + function isStartOfParenthesizedOrFunctionType() { + nextToken(); + return token() === 21 /* CloseParenToken */ || isStartOfParameter(/*isJSDocParameter*/ false) || isStartOfType(); + } + function parsePostfixTypeOrHigher() { + var type = parseNonArrayType(); + while (!scanner.hasPrecedingLineBreak()) { + switch (token()) { + case 52 /* ExclamationToken */: + type = createPostfixType(287 /* JSDocNonNullableType */, type); + break; + case 56 /* QuestionToken */: + // If not in JSDoc and next token is start of a type we have a conditional type + if (!(contextFlags & 2097152 /* JSDoc */) && lookAhead(nextTokenIsStartOfType)) { + return type; + } + type = createPostfixType(286 /* JSDocNullableType */, type); + break; + case 22 /* OpenBracketToken */: + parseExpected(22 /* OpenBracketToken */); + if (isStartOfType()) { + var node = createNode(180 /* IndexedAccessType */, type.pos); + node.objectType = type; + node.indexType = parseType(); + parseExpected(23 /* CloseBracketToken */); + type = finishNode(node); + } + else { + var node = createNode(169 /* ArrayType */, type.pos); + node.elementType = type; + parseExpected(23 /* CloseBracketToken */); + type = finishNode(node); + } + break; + default: + return type; + } + } + return type; + } + function createPostfixType(kind, type) { + nextToken(); + var postfix = createNode(kind, type.pos); + postfix.type = type; + return finishNode(postfix); + } + function parseTypeOperator(operator) { + var node = createNode(179 /* TypeOperator */); + parseExpected(operator); + node.operator = operator; + node.type = parseTypeOperatorOrHigher(); + return finishNode(node); + } + function parseInferType() { + var node = createNode(176 /* InferType */); + parseExpected(127 /* InferKeyword */); + var typeParameter = createNode(150 /* TypeParameter */); + typeParameter.name = parseIdentifier(); + node.typeParameter = finishNode(typeParameter); + return finishNode(node); + } + function parseTypeOperatorOrHigher() { + var operator = token(); + switch (operator) { + case 129 /* KeyOfKeyword */: + case 142 /* UniqueKeyword */: + return parseTypeOperator(operator); + case 127 /* InferKeyword */: + return parseInferType(); + } + return parsePostfixTypeOrHigher(); + } + function parseUnionOrIntersectionType(kind, parseConstituentType, operator) { + parseOptional(operator); + var type = parseConstituentType(); + if (token() === operator) { + var types = [type]; + while (parseOptional(operator)) { + types.push(parseConstituentType()); + } + var node = createNode(kind, type.pos); + node.types = createNodeArray(types, type.pos); + type = finishNode(node); + } + return type; + } + function parseIntersectionTypeOrHigher() { + return parseUnionOrIntersectionType(174 /* IntersectionType */, parseTypeOperatorOrHigher, 49 /* AmpersandToken */); + } + function parseUnionTypeOrHigher() { + return parseUnionOrIntersectionType(173 /* UnionType */, parseIntersectionTypeOrHigher, 50 /* BarToken */); + } + function isStartOfFunctionType() { + if (token() === 28 /* LessThanToken */) { + return true; + } + return token() === 20 /* OpenParenToken */ && lookAhead(isUnambiguouslyStartOfFunctionType); + } + function skipParameterStart() { + if (ts.isModifierKind(token())) { + // Skip modifiers + parseModifiers(); + } + if (isIdentifier() || token() === 100 /* ThisKeyword */) { + nextToken(); + return true; + } + if (token() === 22 /* OpenBracketToken */ || token() === 18 /* OpenBraceToken */) { + // Return true if we can parse an array or object binding pattern with no errors + var previousErrorCount = parseDiagnostics.length; + parseIdentifierOrPattern(); + return previousErrorCount === parseDiagnostics.length; + } + return false; + } + function isUnambiguouslyStartOfFunctionType() { + nextToken(); + if (token() === 21 /* CloseParenToken */ || token() === 25 /* DotDotDotToken */) { + // ( ) + // ( ... + return true; + } + if (skipParameterStart()) { + // We successfully skipped modifiers (if any) and an identifier or binding pattern, + // now see if we have something that indicates a parameter declaration + if (token() === 57 /* ColonToken */ || token() === 27 /* CommaToken */ || + token() === 56 /* QuestionToken */ || token() === 59 /* EqualsToken */) { + // ( xxx : + // ( xxx , + // ( xxx ? + // ( xxx = + return true; + } + if (token() === 21 /* CloseParenToken */) { + nextToken(); + if (token() === 37 /* EqualsGreaterThanToken */) { + // ( xxx ) => + return true; + } + } + } + return false; + } + function parseTypeOrTypePredicate() { + var typePredicateVariable = isIdentifier() && tryParse(parseTypePredicatePrefix); + var type = parseType(); + if (typePredicateVariable) { + var node = createNode(163 /* TypePredicate */, typePredicateVariable.pos); + node.parameterName = typePredicateVariable; + node.type = type; + return finishNode(node); + } + else { + return type; + } + } + function parseTypePredicatePrefix() { + var id = parseIdentifier(); + if (token() === 128 /* IsKeyword */ && !scanner.hasPrecedingLineBreak()) { + nextToken(); + return id; + } + } + function parseType() { + // The rules about 'yield' only apply to actual code/expression contexts. They don't + // apply to 'type' contexts. So we disable these parameters here before moving on. + return doOutsideOfContext(20480 /* TypeExcludesFlags */, parseTypeWorker); + } + function parseTypeWorker(noConditionalTypes) { + if (isStartOfFunctionType() || token() === 95 /* NewKeyword */) { + return parseFunctionOrConstructorType(); + } + var type = parseUnionTypeOrHigher(); + if (!noConditionalTypes && !scanner.hasPrecedingLineBreak() && parseOptional(86 /* ExtendsKeyword */)) { + var node = createNode(175 /* ConditionalType */, type.pos); + node.checkType = type; + // The type following 'extends' is not permitted to be another conditional type + node.extendsType = parseTypeWorker(/*noConditionalTypes*/ true); + parseExpected(56 /* QuestionToken */); + node.trueType = parseTypeWorker(); + parseExpected(57 /* ColonToken */); + node.falseType = parseTypeWorker(); + return finishNode(node); + } + return type; + } + function parseTypeAnnotation() { + return parseOptional(57 /* ColonToken */) ? parseType() : undefined; + } + // EXPRESSIONS + function isStartOfLeftHandSideExpression() { + switch (token()) { + case 100 /* ThisKeyword */: + case 98 /* SuperKeyword */: + case 96 /* NullKeyword */: + case 102 /* TrueKeyword */: + case 87 /* FalseKeyword */: + case 8 /* NumericLiteral */: + case 9 /* BigIntLiteral */: + case 10 /* StringLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: + case 15 /* TemplateHead */: + case 20 /* OpenParenToken */: + case 22 /* OpenBracketToken */: + case 18 /* OpenBraceToken */: + case 90 /* FunctionKeyword */: + case 76 /* ClassKeyword */: + case 95 /* NewKeyword */: + case 42 /* SlashToken */: + case 64 /* SlashEqualsToken */: + case 72 /* Identifier */: + return true; + case 92 /* ImportKeyword */: + return lookAhead(nextTokenIsOpenParenOrLessThanOrDot); + default: + return isIdentifier(); + } + } + function isStartOfExpression() { + if (isStartOfLeftHandSideExpression()) { + return true; + } + switch (token()) { + case 38 /* PlusToken */: + case 39 /* MinusToken */: + case 53 /* TildeToken */: + case 52 /* ExclamationToken */: + case 81 /* DeleteKeyword */: + case 104 /* TypeOfKeyword */: + case 106 /* VoidKeyword */: + case 44 /* PlusPlusToken */: + case 45 /* MinusMinusToken */: + case 28 /* LessThanToken */: + case 122 /* AwaitKeyword */: + case 117 /* YieldKeyword */: + // Yield/await always starts an expression. Either it is an identifier (in which case + // it is definitely an expression). Or it's a keyword (either because we're in + // a generator or async function, or in strict mode (or both)) and it started a yield or await expression. + return true; + default: + // Error tolerance. If we see the start of some binary operator, we consider + // that the start of an expression. That way we'll parse out a missing identifier, + // give a good message about an identifier being missing, and then consume the + // rest of the binary expression. + if (isBinaryOperator()) { + return true; + } + return isIdentifier(); + } + } + function isStartOfExpressionStatement() { + // As per the grammar, none of '{' or 'function' or 'class' can start an expression statement. + return token() !== 18 /* OpenBraceToken */ && + token() !== 90 /* FunctionKeyword */ && + token() !== 76 /* ClassKeyword */ && + token() !== 58 /* AtToken */ && + isStartOfExpression(); + } + function parseExpression() { + // Expression[in]: + // AssignmentExpression[in] + // Expression[in] , AssignmentExpression[in] + // clear the decorator context when parsing Expression, as it should be unambiguous when parsing a decorator + var saveDecoratorContext = inDecoratorContext(); + if (saveDecoratorContext) { + setDecoratorContext(/*val*/ false); + } + var expr = parseAssignmentExpressionOrHigher(); + var operatorToken; + while ((operatorToken = parseOptionalToken(27 /* CommaToken */))) { + expr = makeBinaryExpression(expr, operatorToken, parseAssignmentExpressionOrHigher()); + } + if (saveDecoratorContext) { + setDecoratorContext(/*val*/ true); + } + return expr; + } + function parseInitializer() { + return parseOptional(59 /* EqualsToken */) ? parseAssignmentExpressionOrHigher() : undefined; + } + function parseAssignmentExpressionOrHigher() { + // AssignmentExpression[in,yield]: + // 1) ConditionalExpression[?in,?yield] + // 2) LeftHandSideExpression = AssignmentExpression[?in,?yield] + // 3) LeftHandSideExpression AssignmentOperator AssignmentExpression[?in,?yield] + // 4) ArrowFunctionExpression[?in,?yield] + // 5) AsyncArrowFunctionExpression[in,yield,await] + // 6) [+Yield] YieldExpression[?In] + // + // Note: for ease of implementation we treat productions '2' and '3' as the same thing. + // (i.e. they're both BinaryExpressions with an assignment operator in it). + // First, do the simple check if we have a YieldExpression (production '6'). + if (isYieldExpression()) { + return parseYieldExpression(); + } + // Then, check if we have an arrow function (production '4' and '5') that starts with a parenthesized + // parameter list or is an async arrow function. + // AsyncArrowFunctionExpression: + // 1) async[no LineTerminator here]AsyncArrowBindingIdentifier[?Yield][no LineTerminator here]=>AsyncConciseBody[?In] + // 2) CoverCallExpressionAndAsyncArrowHead[?Yield, ?Await][no LineTerminator here]=>AsyncConciseBody[?In] + // Production (1) of AsyncArrowFunctionExpression is parsed in "tryParseAsyncSimpleArrowFunctionExpression". + // And production (2) is parsed in "tryParseParenthesizedArrowFunctionExpression". + // + // If we do successfully parse arrow-function, we must *not* recurse for productions 1, 2 or 3. An ArrowFunction is + // not a LeftHandSideExpression, nor does it start a ConditionalExpression. So we are done + // with AssignmentExpression if we see one. + var arrowExpression = tryParseParenthesizedArrowFunctionExpression() || tryParseAsyncSimpleArrowFunctionExpression(); + if (arrowExpression) { + return arrowExpression; + } + // Now try to see if we're in production '1', '2' or '3'. A conditional expression can + // start with a LogicalOrExpression, while the assignment productions can only start with + // LeftHandSideExpressions. + // + // So, first, we try to just parse out a BinaryExpression. If we get something that is a + // LeftHandSide or higher, then we can try to parse out the assignment expression part. + // Otherwise, we try to parse out the conditional expression bit. We want to allow any + // binary expression here, so we pass in the 'lowest' precedence here so that it matches + // and consumes anything. + var expr = parseBinaryExpressionOrHigher(/*precedence*/ 0); + // To avoid a look-ahead, we did not handle the case of an arrow function with a single un-parenthesized + // parameter ('x => ...') above. We handle it here by checking if the parsed expression was a single + // identifier and the current token is an arrow. + if (expr.kind === 72 /* Identifier */ && token() === 37 /* EqualsGreaterThanToken */) { + return parseSimpleArrowFunctionExpression(expr); + } + // Now see if we might be in cases '2' or '3'. + // If the expression was a LHS expression, and we have an assignment operator, then + // we're in '2' or '3'. Consume the assignment and return. + // + // Note: we call reScanGreaterToken so that we get an appropriately merged token + // for cases like `> > =` becoming `>>=` + if (ts.isLeftHandSideExpression(expr) && ts.isAssignmentOperator(reScanGreaterToken())) { + return makeBinaryExpression(expr, parseTokenNode(), parseAssignmentExpressionOrHigher()); + } + // It wasn't an assignment or a lambda. This is a conditional expression: + return parseConditionalExpressionRest(expr); + } + function isYieldExpression() { + if (token() === 117 /* YieldKeyword */) { + // If we have a 'yield' keyword, and this is a context where yield expressions are + // allowed, then definitely parse out a yield expression. + if (inYieldContext()) { + return true; + } + // We're in a context where 'yield expr' is not allowed. However, if we can + // definitely tell that the user was trying to parse a 'yield expr' and not + // just a normal expr that start with a 'yield' identifier, then parse out + // a 'yield expr'. We can then report an error later that they are only + // allowed in generator expressions. + // + // for example, if we see 'yield(foo)', then we'll have to treat that as an + // invocation expression of something called 'yield'. However, if we have + // 'yield foo' then that is not legal as a normal expression, so we can + // definitely recognize this as a yield expression. + // + // for now we just check if the next token is an identifier. More heuristics + // can be added here later as necessary. We just need to make sure that we + // don't accidentally consume something legal. + return lookAhead(nextTokenIsIdentifierOrKeywordOrLiteralOnSameLine); + } + return false; + } + function nextTokenIsIdentifierOnSameLine() { + nextToken(); + return !scanner.hasPrecedingLineBreak() && isIdentifier(); + } + function parseYieldExpression() { + var node = createNode(207 /* YieldExpression */); + // YieldExpression[In] : + // yield + // yield [no LineTerminator here] [Lexical goal InputElementRegExp]AssignmentExpression[?In, Yield] + // yield [no LineTerminator here] * [Lexical goal InputElementRegExp]AssignmentExpression[?In, Yield] + nextToken(); + if (!scanner.hasPrecedingLineBreak() && + (token() === 40 /* AsteriskToken */ || isStartOfExpression())) { + node.asteriskToken = parseOptionalToken(40 /* AsteriskToken */); + node.expression = parseAssignmentExpressionOrHigher(); + return finishNode(node); + } + else { + // if the next token is not on the same line as yield. or we don't have an '*' or + // the start of an expression, then this is just a simple "yield" expression. + return finishNode(node); + } + } + function parseSimpleArrowFunctionExpression(identifier, asyncModifier) { + ts.Debug.assert(token() === 37 /* EqualsGreaterThanToken */, "parseSimpleArrowFunctionExpression should only have been called if we had a =>"); + var node; + if (asyncModifier) { + node = createNode(197 /* ArrowFunction */, asyncModifier.pos); + node.modifiers = asyncModifier; + } + else { + node = createNode(197 /* ArrowFunction */, identifier.pos); + } + var parameter = createNode(151 /* Parameter */, identifier.pos); + parameter.name = identifier; + finishNode(parameter); + node.parameters = createNodeArray([parameter], parameter.pos, parameter.end); + node.equalsGreaterThanToken = parseExpectedToken(37 /* EqualsGreaterThanToken */); + node.body = parseArrowFunctionExpressionBody(/*isAsync*/ !!asyncModifier); + return addJSDocComment(finishNode(node)); + } + function tryParseParenthesizedArrowFunctionExpression() { + var triState = isParenthesizedArrowFunctionExpression(); + if (triState === 0 /* False */) { + // It's definitely not a parenthesized arrow function expression. + return undefined; + } + // If we definitely have an arrow function, then we can just parse one, not requiring a + // following => or { token. Otherwise, we *might* have an arrow function. Try to parse + // it out, but don't allow any ambiguity, and return 'undefined' if this could be an + // expression instead. + var arrowFunction = triState === 1 /* True */ + ? parseParenthesizedArrowFunctionExpressionHead(/*allowAmbiguity*/ true) + : tryParse(parsePossibleParenthesizedArrowFunctionExpressionHead); + if (!arrowFunction) { + // Didn't appear to actually be a parenthesized arrow function. Just bail out. + return undefined; + } + var isAsync = ts.hasModifier(arrowFunction, 256 /* Async */); + // If we have an arrow, then try to parse the body. Even if not, try to parse if we + // have an opening brace, just in case we're in an error state. + var lastToken = token(); + arrowFunction.equalsGreaterThanToken = parseExpectedToken(37 /* EqualsGreaterThanToken */); + arrowFunction.body = (lastToken === 37 /* EqualsGreaterThanToken */ || lastToken === 18 /* OpenBraceToken */) + ? parseArrowFunctionExpressionBody(isAsync) + : parseIdentifier(); + return finishNode(arrowFunction); + } + // True -> We definitely expect a parenthesized arrow function here. + // False -> There *cannot* be a parenthesized arrow function here. + // Unknown -> There *might* be a parenthesized arrow function here. + // Speculatively look ahead to be sure, and rollback if not. + function isParenthesizedArrowFunctionExpression() { + if (token() === 20 /* OpenParenToken */ || token() === 28 /* LessThanToken */ || token() === 121 /* AsyncKeyword */) { + return lookAhead(isParenthesizedArrowFunctionExpressionWorker); + } + if (token() === 37 /* EqualsGreaterThanToken */) { + // ERROR RECOVERY TWEAK: + // If we see a standalone => try to parse it as an arrow function expression as that's + // likely what the user intended to write. + return 1 /* True */; + } + // Definitely not a parenthesized arrow function. + return 0 /* False */; + } + function isParenthesizedArrowFunctionExpressionWorker() { + if (token() === 121 /* AsyncKeyword */) { + nextToken(); + if (scanner.hasPrecedingLineBreak()) { + return 0 /* False */; + } + if (token() !== 20 /* OpenParenToken */ && token() !== 28 /* LessThanToken */) { + return 0 /* False */; + } + } + var first = token(); + var second = nextToken(); + if (first === 20 /* OpenParenToken */) { + if (second === 21 /* CloseParenToken */) { + // Simple cases: "() =>", "(): ", and "() {". + // This is an arrow function with no parameters. + // The last one is not actually an arrow function, + // but this is probably what the user intended. + var third = nextToken(); + switch (third) { + case 37 /* EqualsGreaterThanToken */: + case 57 /* ColonToken */: + case 18 /* OpenBraceToken */: + return 1 /* True */; + default: + return 0 /* False */; + } + } + // If encounter "([" or "({", this could be the start of a binding pattern. + // Examples: + // ([ x ]) => { } + // ({ x }) => { } + // ([ x ]) + // ({ x }) + if (second === 22 /* OpenBracketToken */ || second === 18 /* OpenBraceToken */) { + return 2 /* Unknown */; + } + // Simple case: "(..." + // This is an arrow function with a rest parameter. + if (second === 25 /* DotDotDotToken */) { + return 1 /* True */; + } + // Check for "(xxx yyy", where xxx is a modifier and yyy is an identifier. This + // isn't actually allowed, but we want to treat it as a lambda so we can provide + // a good error message. + if (ts.isModifierKind(second) && second !== 121 /* AsyncKeyword */ && lookAhead(nextTokenIsIdentifier)) { + return 1 /* True */; + } + // If we had "(" followed by something that's not an identifier, + // then this definitely doesn't look like a lambda. "this" is not + // valid, but we want to parse it and then give a semantic error. + if (!isIdentifier() && second !== 100 /* ThisKeyword */) { + return 0 /* False */; + } + switch (nextToken()) { + case 57 /* ColonToken */: + // If we have something like "(a:", then we must have a + // type-annotated parameter in an arrow function expression. + return 1 /* True */; + case 56 /* QuestionToken */: + nextToken(); + // If we have "(a?:" or "(a?," or "(a?=" or "(a?)" then it is definitely a lambda. + if (token() === 57 /* ColonToken */ || token() === 27 /* CommaToken */ || token() === 59 /* EqualsToken */ || token() === 21 /* CloseParenToken */) { + return 1 /* True */; + } + // Otherwise it is definitely not a lambda. + return 0 /* False */; + case 27 /* CommaToken */: + case 59 /* EqualsToken */: + case 21 /* CloseParenToken */: + // If we have "(a," or "(a=" or "(a)" this *could* be an arrow function + return 2 /* Unknown */; + } + // It is definitely not an arrow function + return 0 /* False */; + } + else { + ts.Debug.assert(first === 28 /* LessThanToken */); + // If we have "<" not followed by an identifier, + // then this definitely is not an arrow function. + if (!isIdentifier()) { + return 0 /* False */; + } + // JSX overrides + if (sourceFile.languageVariant === 1 /* JSX */) { + var isArrowFunctionInJsx = lookAhead(function () { + var third = nextToken(); + if (third === 86 /* ExtendsKeyword */) { + var fourth = nextToken(); + switch (fourth) { + case 59 /* EqualsToken */: + case 30 /* GreaterThanToken */: + return false; + default: + return true; + } + } + else if (third === 27 /* CommaToken */) { + return true; + } + return false; + }); + if (isArrowFunctionInJsx) { + return 1 /* True */; + } + return 0 /* False */; + } + // This *could* be a parenthesized arrow function. + return 2 /* Unknown */; + } + } + function parsePossibleParenthesizedArrowFunctionExpressionHead() { + return parseParenthesizedArrowFunctionExpressionHead(/*allowAmbiguity*/ false); + } + function tryParseAsyncSimpleArrowFunctionExpression() { + // We do a check here so that we won't be doing unnecessarily call to "lookAhead" + if (token() === 121 /* AsyncKeyword */) { + if (lookAhead(isUnParenthesizedAsyncArrowFunctionWorker) === 1 /* True */) { + var asyncModifier = parseModifiersForArrowFunction(); + var expr = parseBinaryExpressionOrHigher(/*precedence*/ 0); + return parseSimpleArrowFunctionExpression(expr, asyncModifier); + } + } + return undefined; + } + function isUnParenthesizedAsyncArrowFunctionWorker() { + // AsyncArrowFunctionExpression: + // 1) async[no LineTerminator here]AsyncArrowBindingIdentifier[?Yield][no LineTerminator here]=>AsyncConciseBody[?In] + // 2) CoverCallExpressionAndAsyncArrowHead[?Yield, ?Await][no LineTerminator here]=>AsyncConciseBody[?In] + if (token() === 121 /* AsyncKeyword */) { + nextToken(); + // If the "async" is followed by "=>" token then it is not a beginning of an async arrow-function + // but instead a simple arrow-function which will be parsed inside "parseAssignmentExpressionOrHigher" + if (scanner.hasPrecedingLineBreak() || token() === 37 /* EqualsGreaterThanToken */) { + return 0 /* False */; + } + // Check for un-parenthesized AsyncArrowFunction + var expr = parseBinaryExpressionOrHigher(/*precedence*/ 0); + if (!scanner.hasPrecedingLineBreak() && expr.kind === 72 /* Identifier */ && token() === 37 /* EqualsGreaterThanToken */) { + return 1 /* True */; + } + } + return 0 /* False */; + } + function parseParenthesizedArrowFunctionExpressionHead(allowAmbiguity) { + var node = createNodeWithJSDoc(197 /* ArrowFunction */); + node.modifiers = parseModifiersForArrowFunction(); + var isAsync = ts.hasModifier(node, 256 /* Async */) ? 2 /* Await */ : 0 /* None */; + // Arrow functions are never generators. + // + // If we're speculatively parsing a signature for a parenthesized arrow function, then + // we have to have a complete parameter list. Otherwise we might see something like + // a => (b => c) + // And think that "(b =>" was actually a parenthesized arrow function with a missing + // close paren. + if (!fillSignature(57 /* ColonToken */, isAsync, node) && !allowAmbiguity) { + return undefined; + } + // Parsing a signature isn't enough. + // Parenthesized arrow signatures often look like other valid expressions. + // For instance: + // - "(x = 10)" is an assignment expression parsed as a signature with a default parameter value. + // - "(x,y)" is a comma expression parsed as a signature with two parameters. + // - "a ? (b): c" will have "(b):" parsed as a signature with a return type annotation. + // + // So we need just a bit of lookahead to ensure that it can only be a signature. + if (!allowAmbiguity && token() !== 37 /* EqualsGreaterThanToken */ && token() !== 18 /* OpenBraceToken */) { + // Returning undefined here will cause our caller to rewind to where we started from. + return undefined; + } + return node; + } + function parseArrowFunctionExpressionBody(isAsync) { + if (token() === 18 /* OpenBraceToken */) { + return parseFunctionBlock(isAsync ? 2 /* Await */ : 0 /* None */); + } + if (token() !== 26 /* SemicolonToken */ && + token() !== 90 /* FunctionKeyword */ && + token() !== 76 /* ClassKeyword */ && + isStartOfStatement() && + !isStartOfExpressionStatement()) { + // Check if we got a plain statement (i.e. no expression-statements, no function/class expressions/declarations) + // + // Here we try to recover from a potential error situation in the case where the + // user meant to supply a block. For example, if the user wrote: + // + // a => + // let v = 0; + // } + // + // they may be missing an open brace. Check to see if that's the case so we can + // try to recover better. If we don't do this, then the next close curly we see may end + // up preemptively closing the containing construct. + // + // Note: even when 'IgnoreMissingOpenBrace' is passed, parseBody will still error. + return parseFunctionBlock(16 /* IgnoreMissingOpenBrace */ | (isAsync ? 2 /* Await */ : 0 /* None */)); + } + return isAsync + ? doInAwaitContext(parseAssignmentExpressionOrHigher) + : doOutsideOfAwaitContext(parseAssignmentExpressionOrHigher); + } + function parseConditionalExpressionRest(leftOperand) { + // Note: we are passed in an expression which was produced from parseBinaryExpressionOrHigher. + var questionToken = parseOptionalToken(56 /* QuestionToken */); + if (!questionToken) { + return leftOperand; + } + // Note: we explicitly 'allowIn' in the whenTrue part of the condition expression, and + // we do not that for the 'whenFalse' part. + var node = createNode(205 /* ConditionalExpression */, leftOperand.pos); + node.condition = leftOperand; + node.questionToken = questionToken; + node.whenTrue = doOutsideOfContext(disallowInAndDecoratorContext, parseAssignmentExpressionOrHigher); + node.colonToken = parseExpectedToken(57 /* ColonToken */); + node.whenFalse = ts.nodeIsPresent(node.colonToken) + ? parseAssignmentExpressionOrHigher() + : createMissingNode(72 /* Identifier */, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, ts.tokenToString(57 /* ColonToken */)); + return finishNode(node); + } + function parseBinaryExpressionOrHigher(precedence) { + var leftOperand = parseUnaryExpressionOrHigher(); + return parseBinaryExpressionRest(precedence, leftOperand); + } + function isInOrOfKeyword(t) { + return t === 93 /* InKeyword */ || t === 147 /* OfKeyword */; + } + function parseBinaryExpressionRest(precedence, leftOperand) { + while (true) { + // We either have a binary operator here, or we're finished. We call + // reScanGreaterToken so that we merge token sequences like > and = into >= + reScanGreaterToken(); + var newPrecedence = ts.getBinaryOperatorPrecedence(token()); + // Check the precedence to see if we should "take" this operator + // - For left associative operator (all operator but **), consume the operator, + // recursively call the function below, and parse binaryExpression as a rightOperand + // of the caller if the new precedence of the operator is greater then or equal to the current precedence. + // For example: + // a - b - c; + // ^token; leftOperand = b. Return b to the caller as a rightOperand + // a * b - c + // ^token; leftOperand = b. Return b to the caller as a rightOperand + // a - b * c; + // ^token; leftOperand = b. Return b * c to the caller as a rightOperand + // - For right associative operator (**), consume the operator, recursively call the function + // and parse binaryExpression as a rightOperand of the caller if the new precedence of + // the operator is strictly grater than the current precedence + // For example: + // a ** b ** c; + // ^^token; leftOperand = b. Return b ** c to the caller as a rightOperand + // a - b ** c; + // ^^token; leftOperand = b. Return b ** c to the caller as a rightOperand + // a ** b - c + // ^token; leftOperand = b. Return b to the caller as a rightOperand + var consumeCurrentOperator = token() === 41 /* AsteriskAsteriskToken */ ? + newPrecedence >= precedence : + newPrecedence > precedence; + if (!consumeCurrentOperator) { + break; + } + if (token() === 93 /* InKeyword */ && inDisallowInContext()) { + break; + } + if (token() === 119 /* AsKeyword */) { + // Make sure we *do* perform ASI for constructs like this: + // var x = foo + // as (Bar) + // This should be parsed as an initialized variable, followed + // by a function call to 'as' with the argument 'Bar' + if (scanner.hasPrecedingLineBreak()) { + break; + } + else { + nextToken(); + leftOperand = makeAsExpression(leftOperand, parseType()); + } + } + else { + leftOperand = makeBinaryExpression(leftOperand, parseTokenNode(), parseBinaryExpressionOrHigher(newPrecedence)); + } + } + return leftOperand; + } + function isBinaryOperator() { + if (inDisallowInContext() && token() === 93 /* InKeyword */) { + return false; + } + return ts.getBinaryOperatorPrecedence(token()) > 0; + } + function makeBinaryExpression(left, operatorToken, right) { + var node = createNode(204 /* BinaryExpression */, left.pos); + node.left = left; + node.operatorToken = operatorToken; + node.right = right; + return finishNode(node); + } + function makeAsExpression(left, right) { + var node = createNode(212 /* AsExpression */, left.pos); + node.expression = left; + node.type = right; + return finishNode(node); + } + function parsePrefixUnaryExpression() { + var node = createNode(202 /* PrefixUnaryExpression */); + node.operator = token(); + nextToken(); + node.operand = parseSimpleUnaryExpression(); + return finishNode(node); + } + function parseDeleteExpression() { + var node = createNode(198 /* DeleteExpression */); + nextToken(); + node.expression = parseSimpleUnaryExpression(); + return finishNode(node); + } + function parseTypeOfExpression() { + var node = createNode(199 /* TypeOfExpression */); + nextToken(); + node.expression = parseSimpleUnaryExpression(); + return finishNode(node); + } + function parseVoidExpression() { + var node = createNode(200 /* VoidExpression */); + nextToken(); + node.expression = parseSimpleUnaryExpression(); + return finishNode(node); + } + function isAwaitExpression() { + if (token() === 122 /* AwaitKeyword */) { + if (inAwaitContext()) { + return true; + } + // here we are using similar heuristics as 'isYieldExpression' + return lookAhead(nextTokenIsIdentifierOrKeywordOrLiteralOnSameLine); + } + return false; + } + function parseAwaitExpression() { + var node = createNode(201 /* AwaitExpression */); + nextToken(); + node.expression = parseSimpleUnaryExpression(); + return finishNode(node); + } + /** + * Parse ES7 exponential expression and await expression + * + * ES7 ExponentiationExpression: + * 1) UnaryExpression[?Yield] + * 2) UpdateExpression[?Yield] ** ExponentiationExpression[?Yield] + * + */ + function parseUnaryExpressionOrHigher() { + /** + * ES7 UpdateExpression: + * 1) LeftHandSideExpression[?Yield] + * 2) LeftHandSideExpression[?Yield][no LineTerminator here]++ + * 3) LeftHandSideExpression[?Yield][no LineTerminator here]-- + * 4) ++UnaryExpression[?Yield] + * 5) --UnaryExpression[?Yield] + */ + if (isUpdateExpression()) { + var updateExpression = parseUpdateExpression(); + return token() === 41 /* AsteriskAsteriskToken */ ? + parseBinaryExpressionRest(ts.getBinaryOperatorPrecedence(token()), updateExpression) : + updateExpression; + } + /** + * ES7 UnaryExpression: + * 1) UpdateExpression[?yield] + * 2) delete UpdateExpression[?yield] + * 3) void UpdateExpression[?yield] + * 4) typeof UpdateExpression[?yield] + * 5) + UpdateExpression[?yield] + * 6) - UpdateExpression[?yield] + * 7) ~ UpdateExpression[?yield] + * 8) ! UpdateExpression[?yield] + */ + var unaryOperator = token(); + var simpleUnaryExpression = parseSimpleUnaryExpression(); + if (token() === 41 /* AsteriskAsteriskToken */) { + var pos = ts.skipTrivia(sourceText, simpleUnaryExpression.pos); + var end = simpleUnaryExpression.end; + if (simpleUnaryExpression.kind === 194 /* TypeAssertionExpression */) { + parseErrorAt(pos, end, ts.Diagnostics.A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses); + } + else { + parseErrorAt(pos, end, ts.Diagnostics.An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses, ts.tokenToString(unaryOperator)); + } + } + return simpleUnaryExpression; + } + /** + * Parse ES7 simple-unary expression or higher: + * + * ES7 UnaryExpression: + * 1) UpdateExpression[?yield] + * 2) delete UnaryExpression[?yield] + * 3) void UnaryExpression[?yield] + * 4) typeof UnaryExpression[?yield] + * 5) + UnaryExpression[?yield] + * 6) - UnaryExpression[?yield] + * 7) ~ UnaryExpression[?yield] + * 8) ! UnaryExpression[?yield] + * 9) [+Await] await UnaryExpression[?yield] + */ + function parseSimpleUnaryExpression() { + switch (token()) { + case 38 /* PlusToken */: + case 39 /* MinusToken */: + case 53 /* TildeToken */: + case 52 /* ExclamationToken */: + return parsePrefixUnaryExpression(); + case 81 /* DeleteKeyword */: + return parseDeleteExpression(); + case 104 /* TypeOfKeyword */: + return parseTypeOfExpression(); + case 106 /* VoidKeyword */: + return parseVoidExpression(); + case 28 /* LessThanToken */: + // This is modified UnaryExpression grammar in TypeScript + // UnaryExpression (modified): + // < type > UnaryExpression + return parseTypeAssertion(); + case 122 /* AwaitKeyword */: + if (isAwaitExpression()) { + return parseAwaitExpression(); + } + // falls through + default: + return parseUpdateExpression(); + } + } + /** + * Check if the current token can possibly be an ES7 increment expression. + * + * ES7 UpdateExpression: + * LeftHandSideExpression[?Yield] + * LeftHandSideExpression[?Yield][no LineTerminator here]++ + * LeftHandSideExpression[?Yield][no LineTerminator here]-- + * ++LeftHandSideExpression[?Yield] + * --LeftHandSideExpression[?Yield] + */ + function isUpdateExpression() { + // This function is called inside parseUnaryExpression to decide + // whether to call parseSimpleUnaryExpression or call parseUpdateExpression directly + switch (token()) { + case 38 /* PlusToken */: + case 39 /* MinusToken */: + case 53 /* TildeToken */: + case 52 /* ExclamationToken */: + case 81 /* DeleteKeyword */: + case 104 /* TypeOfKeyword */: + case 106 /* VoidKeyword */: + case 122 /* AwaitKeyword */: + return false; + case 28 /* LessThanToken */: + // If we are not in JSX context, we are parsing TypeAssertion which is an UnaryExpression + if (sourceFile.languageVariant !== 1 /* JSX */) { + return false; + } + // We are in JSX context and the token is part of JSXElement. + // falls through + default: + return true; + } + } + /** + * Parse ES7 UpdateExpression. UpdateExpression is used instead of ES6's PostFixExpression. + * + * ES7 UpdateExpression[yield]: + * 1) LeftHandSideExpression[?yield] + * 2) LeftHandSideExpression[?yield] [[no LineTerminator here]]++ + * 3) LeftHandSideExpression[?yield] [[no LineTerminator here]]-- + * 4) ++LeftHandSideExpression[?yield] + * 5) --LeftHandSideExpression[?yield] + * In TypeScript (2), (3) are parsed as PostfixUnaryExpression. (4), (5) are parsed as PrefixUnaryExpression + */ + function parseUpdateExpression() { + if (token() === 44 /* PlusPlusToken */ || token() === 45 /* MinusMinusToken */) { + var node = createNode(202 /* PrefixUnaryExpression */); + node.operator = token(); + nextToken(); + node.operand = parseLeftHandSideExpressionOrHigher(); + return finishNode(node); + } + else if (sourceFile.languageVariant === 1 /* JSX */ && token() === 28 /* LessThanToken */ && lookAhead(nextTokenIsIdentifierOrKeywordOrGreaterThan)) { + // JSXElement is part of primaryExpression + return parseJsxElementOrSelfClosingElementOrFragment(/*inExpressionContext*/ true); + } + var expression = parseLeftHandSideExpressionOrHigher(); + ts.Debug.assert(ts.isLeftHandSideExpression(expression)); + if ((token() === 44 /* PlusPlusToken */ || token() === 45 /* MinusMinusToken */) && !scanner.hasPrecedingLineBreak()) { + var node = createNode(203 /* PostfixUnaryExpression */, expression.pos); + node.operand = expression; + node.operator = token(); + nextToken(); + return finishNode(node); + } + return expression; + } + function parseLeftHandSideExpressionOrHigher() { + // Original Ecma: + // LeftHandSideExpression: See 11.2 + // NewExpression + // CallExpression + // + // Our simplification: + // + // LeftHandSideExpression: See 11.2 + // MemberExpression + // CallExpression + // + // See comment in parseMemberExpressionOrHigher on how we replaced NewExpression with + // MemberExpression to make our lives easier. + // + // to best understand the below code, it's important to see how CallExpression expands + // out into its own productions: + // + // CallExpression: + // MemberExpression Arguments + // CallExpression Arguments + // CallExpression[Expression] + // CallExpression.IdentifierName + // import (AssignmentExpression) + // super Arguments + // super.IdentifierName + // + // Because of the recursion in these calls, we need to bottom out first. There are three + // bottom out states we can run into: 1) We see 'super' which must start either of + // the last two CallExpression productions. 2) We see 'import' which must start import call. + // 3)we have a MemberExpression which either completes the LeftHandSideExpression, + // or starts the beginning of the first four CallExpression productions. + var expression; + if (token() === 92 /* ImportKeyword */) { + if (lookAhead(nextTokenIsOpenParenOrLessThan)) { + // We don't want to eagerly consume all import keyword as import call expression so we look ahead to find "(" + // For example: + // var foo3 = require("subfolder + // import * as foo1 from "module-from-node + // We want this import to be a statement rather than import call expression + sourceFile.flags |= 524288 /* PossiblyContainsDynamicImport */; + expression = parseTokenNode(); + } + else if (lookAhead(nextTokenIsDot)) { + // This is an 'import.*' metaproperty (i.e. 'import.meta') + var fullStart = scanner.getStartPos(); + nextToken(); // advance past the 'import' + nextToken(); // advance past the dot + var node = createNode(214 /* MetaProperty */, fullStart); + node.keywordToken = 92 /* ImportKeyword */; + node.name = parseIdentifierName(); + expression = finishNode(node); + sourceFile.flags |= 1048576 /* PossiblyContainsImportMeta */; + } + else { + expression = parseMemberExpressionOrHigher(); + } + } + else { + expression = token() === 98 /* SuperKeyword */ ? parseSuperExpression() : parseMemberExpressionOrHigher(); + } + // Now, we *may* be complete. However, we might have consumed the start of a + // CallExpression. As such, we need to consume the rest of it here to be complete. + return parseCallExpressionRest(expression); + } + function parseMemberExpressionOrHigher() { + // Note: to make our lives simpler, we decompose the NewExpression productions and + // place ObjectCreationExpression and FunctionExpression into PrimaryExpression. + // like so: + // + // PrimaryExpression : See 11.1 + // this + // Identifier + // Literal + // ArrayLiteral + // ObjectLiteral + // (Expression) + // FunctionExpression + // new MemberExpression Arguments? + // + // MemberExpression : See 11.2 + // PrimaryExpression + // MemberExpression[Expression] + // MemberExpression.IdentifierName + // + // CallExpression : See 11.2 + // MemberExpression + // CallExpression Arguments + // CallExpression[Expression] + // CallExpression.IdentifierName + // + // Technically this is ambiguous. i.e. CallExpression defines: + // + // CallExpression: + // CallExpression Arguments + // + // If you see: "new Foo()" + // + // Then that could be treated as a single ObjectCreationExpression, or it could be + // treated as the invocation of "new Foo". We disambiguate that in code (to match + // the original grammar) by making sure that if we see an ObjectCreationExpression + // we always consume arguments if they are there. So we treat "new Foo()" as an + // object creation only, and not at all as an invocation. Another way to think + // about this is that for every "new" that we see, we will consume an argument list if + // it is there as part of the *associated* object creation node. Any additional + // argument lists we see, will become invocation expressions. + // + // Because there are no other places in the grammar now that refer to FunctionExpression + // or ObjectCreationExpression, it is safe to push down into the PrimaryExpression + // production. + // + // Because CallExpression and MemberExpression are left recursive, we need to bottom out + // of the recursion immediately. So we parse out a primary expression to start with. + var expression = parsePrimaryExpression(); + return parseMemberExpressionRest(expression); + } + function parseSuperExpression() { + var expression = parseTokenNode(); + if (token() === 20 /* OpenParenToken */ || token() === 24 /* DotToken */ || token() === 22 /* OpenBracketToken */) { + return expression; + } + // If we have seen "super" it must be followed by '(' or '.'. + // If it wasn't then just try to parse out a '.' and report an error. + var node = createNode(189 /* PropertyAccessExpression */, expression.pos); + node.expression = expression; + parseExpectedToken(24 /* DotToken */, ts.Diagnostics.super_must_be_followed_by_an_argument_list_or_member_access); + node.name = parseRightSideOfDot(/*allowIdentifierNames*/ true); + return finishNode(node); + } + function parseJsxElementOrSelfClosingElementOrFragment(inExpressionContext) { + var opening = parseJsxOpeningOrSelfClosingElementOrOpeningFragment(inExpressionContext); + var result; + if (opening.kind === 262 /* JsxOpeningElement */) { + var node = createNode(260 /* JsxElement */, opening.pos); + node.openingElement = opening; + node.children = parseJsxChildren(node.openingElement); + node.closingElement = parseJsxClosingElement(inExpressionContext); + if (!tagNamesAreEquivalent(node.openingElement.tagName, node.closingElement.tagName)) { + parseErrorAtRange(node.closingElement, ts.Diagnostics.Expected_corresponding_JSX_closing_tag_for_0, ts.getTextOfNodeFromSourceText(sourceText, node.openingElement.tagName)); + } + result = finishNode(node); + } + else if (opening.kind === 265 /* JsxOpeningFragment */) { + var node = createNode(264 /* JsxFragment */, opening.pos); + node.openingFragment = opening; + node.children = parseJsxChildren(node.openingFragment); + node.closingFragment = parseJsxClosingFragment(inExpressionContext); + result = finishNode(node); + } + else { + ts.Debug.assert(opening.kind === 261 /* JsxSelfClosingElement */); + // Nothing else to do for self-closing elements + result = opening; + } + // If the user writes the invalid code '
      ' in an expression context (i.e. not wrapped in + // an enclosing tag), we'll naively try to parse ^ this as a 'less than' operator and the remainder of the tag + // as garbage, which will cause the formatter to badly mangle the JSX. Perform a speculative parse of a JSX + // element if we see a < token so that we can wrap it in a synthetic binary expression so the formatter + // does less damage and we can report a better error. + // Since JSX elements are invalid < operands anyway, this lookahead parse will only occur in error scenarios + // of one sort or another. + if (inExpressionContext && token() === 28 /* LessThanToken */) { + var invalidElement = tryParse(function () { return parseJsxElementOrSelfClosingElementOrFragment(/*inExpressionContext*/ true); }); + if (invalidElement) { + parseErrorAtCurrentToken(ts.Diagnostics.JSX_expressions_must_have_one_parent_element); + var badNode = createNode(204 /* BinaryExpression */, result.pos); + badNode.end = invalidElement.end; + badNode.left = result; + badNode.right = invalidElement; + badNode.operatorToken = createMissingNode(27 /* CommaToken */, /*reportAtCurrentPosition*/ false, /*diagnosticMessage*/ undefined); // TODO: GH#18217 + badNode.operatorToken.pos = badNode.operatorToken.end = badNode.right.pos; + return badNode; + } + } + return result; + } + function parseJsxText() { + var node = createNode(11 /* JsxText */); + node.containsOnlyWhiteSpaces = currentToken === 12 /* JsxTextAllWhiteSpaces */; + currentToken = scanner.scanJsxToken(); + return finishNode(node); + } + function parseJsxChild(openingTag, token) { + switch (token) { + case 1 /* EndOfFileToken */: + // If we hit EOF, issue the error at the tag that lacks the closing element + // rather than at the end of the file (which is useless) + if (ts.isJsxOpeningFragment(openingTag)) { + parseErrorAtRange(openingTag, ts.Diagnostics.JSX_fragment_has_no_corresponding_closing_tag); + } + else { + parseErrorAtRange(openingTag.tagName, ts.Diagnostics.JSX_element_0_has_no_corresponding_closing_tag, ts.getTextOfNodeFromSourceText(sourceText, openingTag.tagName)); + } + return undefined; + case 29 /* LessThanSlashToken */: + case 7 /* ConflictMarkerTrivia */: + return undefined; + case 11 /* JsxText */: + case 12 /* JsxTextAllWhiteSpaces */: + return parseJsxText(); + case 18 /* OpenBraceToken */: + return parseJsxExpression(/*inExpressionContext*/ false); + case 28 /* LessThanToken */: + return parseJsxElementOrSelfClosingElementOrFragment(/*inExpressionContext*/ false); + default: + return ts.Debug.assertNever(token); + } + } + function parseJsxChildren(openingTag) { + var list = []; + var listPos = getNodePos(); + var saveParsingContext = parsingContext; + parsingContext |= 1 << 14 /* JsxChildren */; + while (true) { + var child = parseJsxChild(openingTag, currentToken = scanner.reScanJsxToken()); + if (!child) + break; + list.push(child); + } + parsingContext = saveParsingContext; + return createNodeArray(list, listPos); + } + function parseJsxAttributes() { + var jsxAttributes = createNode(268 /* JsxAttributes */); + jsxAttributes.properties = parseList(13 /* JsxAttributes */, parseJsxAttribute); + return finishNode(jsxAttributes); + } + function parseJsxOpeningOrSelfClosingElementOrOpeningFragment(inExpressionContext) { + var fullStart = scanner.getStartPos(); + parseExpected(28 /* LessThanToken */); + if (token() === 30 /* GreaterThanToken */) { + // See below for explanation of scanJsxText + var node_1 = createNode(265 /* JsxOpeningFragment */, fullStart); + scanJsxText(); + return finishNode(node_1); + } + var tagName = parseJsxElementName(); + var typeArguments = tryParseTypeArguments(); + var attributes = parseJsxAttributes(); + var node; + if (token() === 30 /* GreaterThanToken */) { + // Closing tag, so scan the immediately-following text with the JSX scanning instead + // of regular scanning to avoid treating illegal characters (e.g. '#') as immediate + // scanning errors + node = createNode(262 /* JsxOpeningElement */, fullStart); + scanJsxText(); + } + else { + parseExpected(42 /* SlashToken */); + if (inExpressionContext) { + parseExpected(30 /* GreaterThanToken */); + } + else { + parseExpected(30 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false); + scanJsxText(); + } + node = createNode(261 /* JsxSelfClosingElement */, fullStart); + } + node.tagName = tagName; + node.typeArguments = typeArguments; + node.attributes = attributes; + return finishNode(node); + } + function parseJsxElementName() { + scanJsxIdentifier(); + // JsxElement can have name in the form of + // propertyAccessExpression + // primaryExpression in the form of an identifier and "this" keyword + // We can't just simply use parseLeftHandSideExpressionOrHigher because then we will start consider class,function etc as a keyword + // We only want to consider "this" as a primaryExpression + var expression = token() === 100 /* ThisKeyword */ ? + parseTokenNode() : parseIdentifierName(); + while (parseOptional(24 /* DotToken */)) { + var propertyAccess = createNode(189 /* PropertyAccessExpression */, expression.pos); + propertyAccess.expression = expression; + propertyAccess.name = parseRightSideOfDot(/*allowIdentifierNames*/ true); + expression = finishNode(propertyAccess); + } + return expression; + } + function parseJsxExpression(inExpressionContext) { + var node = createNode(270 /* JsxExpression */); + if (!parseExpected(18 /* OpenBraceToken */)) { + return undefined; + } + if (token() !== 19 /* CloseBraceToken */) { + node.dotDotDotToken = parseOptionalToken(25 /* DotDotDotToken */); + node.expression = parseAssignmentExpressionOrHigher(); + } + if (inExpressionContext) { + parseExpected(19 /* CloseBraceToken */); + } + else { + parseExpected(19 /* CloseBraceToken */, /*message*/ undefined, /*shouldAdvance*/ false); + scanJsxText(); + } + return finishNode(node); + } + function parseJsxAttribute() { + if (token() === 18 /* OpenBraceToken */) { + return parseJsxSpreadAttribute(); + } + scanJsxIdentifier(); + var node = createNode(267 /* JsxAttribute */); + node.name = parseIdentifierName(); + if (token() === 59 /* EqualsToken */) { + switch (scanJsxAttributeValue()) { + case 10 /* StringLiteral */: + node.initializer = parseLiteralNode(); + break; + default: + node.initializer = parseJsxExpression(/*inExpressionContext*/ true); + break; + } + } + return finishNode(node); + } + function parseJsxSpreadAttribute() { + var node = createNode(269 /* JsxSpreadAttribute */); + parseExpected(18 /* OpenBraceToken */); + parseExpected(25 /* DotDotDotToken */); + node.expression = parseExpression(); + parseExpected(19 /* CloseBraceToken */); + return finishNode(node); + } + function parseJsxClosingElement(inExpressionContext) { + var node = createNode(263 /* JsxClosingElement */); + parseExpected(29 /* LessThanSlashToken */); + node.tagName = parseJsxElementName(); + if (inExpressionContext) { + parseExpected(30 /* GreaterThanToken */); + } + else { + parseExpected(30 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false); + scanJsxText(); + } + return finishNode(node); + } + function parseJsxClosingFragment(inExpressionContext) { + var node = createNode(266 /* JsxClosingFragment */); + parseExpected(29 /* LessThanSlashToken */); + if (ts.tokenIsIdentifierOrKeyword(token())) { + parseErrorAtRange(parseJsxElementName(), ts.Diagnostics.Expected_corresponding_closing_tag_for_JSX_fragment); + } + if (inExpressionContext) { + parseExpected(30 /* GreaterThanToken */); + } + else { + parseExpected(30 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false); + scanJsxText(); + } + return finishNode(node); + } + function parseTypeAssertion() { + var node = createNode(194 /* TypeAssertionExpression */); + parseExpected(28 /* LessThanToken */); + node.type = parseType(); + parseExpected(30 /* GreaterThanToken */); + node.expression = parseSimpleUnaryExpression(); + return finishNode(node); + } + function parseMemberExpressionRest(expression) { + while (true) { + var dotToken = parseOptionalToken(24 /* DotToken */); + if (dotToken) { + var propertyAccess = createNode(189 /* PropertyAccessExpression */, expression.pos); + propertyAccess.expression = expression; + propertyAccess.name = parseRightSideOfDot(/*allowIdentifierNames*/ true); + expression = finishNode(propertyAccess); + continue; + } + if (token() === 52 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) { + nextToken(); + var nonNullExpression = createNode(213 /* NonNullExpression */, expression.pos); + nonNullExpression.expression = expression; + expression = finishNode(nonNullExpression); + continue; + } + // when in the [Decorator] context, we do not parse ElementAccess as it could be part of a ComputedPropertyName + if (!inDecoratorContext() && parseOptional(22 /* OpenBracketToken */)) { + var indexedAccess = createNode(190 /* ElementAccessExpression */, expression.pos); + indexedAccess.expression = expression; + if (token() === 23 /* CloseBracketToken */) { + indexedAccess.argumentExpression = createMissingNode(72 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.An_element_access_expression_should_take_an_argument); + } + else { + var argument = allowInAnd(parseExpression); + if (ts.isStringOrNumericLiteralLike(argument)) { + argument.text = internIdentifier(argument.text); + } + indexedAccess.argumentExpression = argument; + } + parseExpected(23 /* CloseBracketToken */); + expression = finishNode(indexedAccess); + continue; + } + if (isTemplateStartOfTaggedTemplate()) { + expression = parseTaggedTemplateRest(expression, /*typeArguments*/ undefined); + continue; + } + return expression; + } + } + function isTemplateStartOfTaggedTemplate() { + return token() === 14 /* NoSubstitutionTemplateLiteral */ || token() === 15 /* TemplateHead */; + } + function parseTaggedTemplateRest(tag, typeArguments) { + var tagExpression = createNode(193 /* TaggedTemplateExpression */, tag.pos); + tagExpression.tag = tag; + tagExpression.typeArguments = typeArguments; + tagExpression.template = token() === 14 /* NoSubstitutionTemplateLiteral */ + ? parseLiteralNode() + : parseTemplateExpression(); + return finishNode(tagExpression); + } + function parseCallExpressionRest(expression) { + while (true) { + expression = parseMemberExpressionRest(expression); + if (token() === 28 /* LessThanToken */) { + // See if this is the start of a generic invocation. If so, consume it and + // keep checking for postfix expressions. Otherwise, it's just a '<' that's + // part of an arithmetic expression. Break out so we consume it higher in the + // stack. + var typeArguments = tryParse(parseTypeArgumentsInExpression); + if (!typeArguments) { + return expression; + } + if (isTemplateStartOfTaggedTemplate()) { + expression = parseTaggedTemplateRest(expression, typeArguments); + continue; + } + var callExpr = createNode(191 /* CallExpression */, expression.pos); + callExpr.expression = expression; + callExpr.typeArguments = typeArguments; + callExpr.arguments = parseArgumentList(); + expression = finishNode(callExpr); + continue; + } + else if (token() === 20 /* OpenParenToken */) { + var callExpr = createNode(191 /* CallExpression */, expression.pos); + callExpr.expression = expression; + callExpr.arguments = parseArgumentList(); + expression = finishNode(callExpr); + continue; + } + return expression; + } + } + function parseArgumentList() { + parseExpected(20 /* OpenParenToken */); + var result = parseDelimitedList(11 /* ArgumentExpressions */, parseArgumentExpression); + parseExpected(21 /* CloseParenToken */); + return result; + } + function parseTypeArgumentsInExpression() { + if (!parseOptional(28 /* LessThanToken */)) { + return undefined; + } + var typeArguments = parseDelimitedList(20 /* TypeArguments */, parseType); + if (!parseExpected(30 /* GreaterThanToken */)) { + // If it doesn't have the closing `>` then it's definitely not an type argument list. + return undefined; + } + // If we have a '<', then only parse this as a argument list if the type arguments + // are complete and we have an open paren. if we don't, rewind and return nothing. + return typeArguments && canFollowTypeArgumentsInExpression() + ? typeArguments + : undefined; + } + function canFollowTypeArgumentsInExpression() { + switch (token()) { + case 20 /* OpenParenToken */: // foo( + case 14 /* NoSubstitutionTemplateLiteral */: // foo `...` + case 15 /* TemplateHead */: // foo `...${100}...` + // these are the only tokens can legally follow a type argument + // list. So we definitely want to treat them as type arg lists. + case 24 /* DotToken */: // foo. + case 21 /* CloseParenToken */: // foo) + case 23 /* CloseBracketToken */: // foo] + case 57 /* ColonToken */: // foo: + case 26 /* SemicolonToken */: // foo; + case 56 /* QuestionToken */: // foo? + case 33 /* EqualsEqualsToken */: // foo == + case 35 /* EqualsEqualsEqualsToken */: // foo === + case 34 /* ExclamationEqualsToken */: // foo != + case 36 /* ExclamationEqualsEqualsToken */: // foo !== + case 54 /* AmpersandAmpersandToken */: // foo && + case 55 /* BarBarToken */: // foo || + case 51 /* CaretToken */: // foo ^ + case 49 /* AmpersandToken */: // foo & + case 50 /* BarToken */: // foo | + case 19 /* CloseBraceToken */: // foo } + case 1 /* EndOfFileToken */: // foo + // these cases can't legally follow a type arg list. However, they're not legal + // expressions either. The user is probably in the middle of a generic type. So + // treat it as such. + return true; + case 27 /* CommaToken */: // foo, + case 18 /* OpenBraceToken */: // foo { + // We don't want to treat these as type arguments. Otherwise we'll parse this + // as an invocation expression. Instead, we want to parse out the expression + // in isolation from the type arguments. + default: + // Anything else treat as an expression. + return false; + } + } + function parsePrimaryExpression() { + switch (token()) { + case 8 /* NumericLiteral */: + case 9 /* BigIntLiteral */: + case 10 /* StringLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: + return parseLiteralNode(); + case 100 /* ThisKeyword */: + case 98 /* SuperKeyword */: + case 96 /* NullKeyword */: + case 102 /* TrueKeyword */: + case 87 /* FalseKeyword */: + return parseTokenNode(); + case 20 /* OpenParenToken */: + return parseParenthesizedExpression(); + case 22 /* OpenBracketToken */: + return parseArrayLiteralExpression(); + case 18 /* OpenBraceToken */: + return parseObjectLiteralExpression(); + case 121 /* AsyncKeyword */: + // Async arrow functions are parsed earlier in parseAssignmentExpressionOrHigher. + // If we encounter `async [no LineTerminator here] function` then this is an async + // function; otherwise, its an identifier. + if (!lookAhead(nextTokenIsFunctionKeywordOnSameLine)) { + break; + } + return parseFunctionExpression(); + case 76 /* ClassKeyword */: + return parseClassExpression(); + case 90 /* FunctionKeyword */: + return parseFunctionExpression(); + case 95 /* NewKeyword */: + return parseNewExpressionOrNewDotTarget(); + case 42 /* SlashToken */: + case 64 /* SlashEqualsToken */: + if (reScanSlashToken() === 13 /* RegularExpressionLiteral */) { + return parseLiteralNode(); + } + break; + case 15 /* TemplateHead */: + return parseTemplateExpression(); + } + return parseIdentifier(ts.Diagnostics.Expression_expected); + } + function parseParenthesizedExpression() { + var node = createNodeWithJSDoc(195 /* ParenthesizedExpression */); + parseExpected(20 /* OpenParenToken */); + node.expression = allowInAnd(parseExpression); + parseExpected(21 /* CloseParenToken */); + return finishNode(node); + } + function parseSpreadElement() { + var node = createNode(208 /* SpreadElement */); + parseExpected(25 /* DotDotDotToken */); + node.expression = parseAssignmentExpressionOrHigher(); + return finishNode(node); + } + function parseArgumentOrArrayLiteralElement() { + return token() === 25 /* DotDotDotToken */ ? parseSpreadElement() : + token() === 27 /* CommaToken */ ? createNode(210 /* OmittedExpression */) : + parseAssignmentExpressionOrHigher(); + } + function parseArgumentExpression() { + return doOutsideOfContext(disallowInAndDecoratorContext, parseArgumentOrArrayLiteralElement); + } + function parseArrayLiteralExpression() { + var node = createNode(187 /* ArrayLiteralExpression */); + parseExpected(22 /* OpenBracketToken */); + if (scanner.hasPrecedingLineBreak()) { + node.multiLine = true; + } + node.elements = parseDelimitedList(15 /* ArrayLiteralMembers */, parseArgumentOrArrayLiteralElement); + parseExpected(23 /* CloseBracketToken */); + return finishNode(node); + } + function parseObjectLiteralElement() { + var node = createNodeWithJSDoc(0 /* Unknown */); + if (parseOptionalToken(25 /* DotDotDotToken */)) { + node.kind = 277 /* SpreadAssignment */; + node.expression = parseAssignmentExpressionOrHigher(); + return finishNode(node); + } + node.decorators = parseDecorators(); + node.modifiers = parseModifiers(); + if (parseContextualModifier(126 /* GetKeyword */)) { + return parseAccessorDeclaration(node, 158 /* GetAccessor */); + } + if (parseContextualModifier(137 /* SetKeyword */)) { + return parseAccessorDeclaration(node, 159 /* SetAccessor */); + } + var asteriskToken = parseOptionalToken(40 /* AsteriskToken */); + var tokenIsIdentifier = isIdentifier(); + node.name = parsePropertyName(); + // Disallowing of optional property assignments and definite assignment assertion happens in the grammar checker. + node.questionToken = parseOptionalToken(56 /* QuestionToken */); + node.exclamationToken = parseOptionalToken(52 /* ExclamationToken */); + if (asteriskToken || token() === 20 /* OpenParenToken */ || token() === 28 /* LessThanToken */) { + return parseMethodDeclaration(node, asteriskToken); + } + // check if it is short-hand property assignment or normal property assignment + // NOTE: if token is EqualsToken it is interpreted as CoverInitializedName production + // CoverInitializedName[Yield] : + // IdentifierReference[?Yield] Initializer[In, ?Yield] + // this is necessary because ObjectLiteral productions are also used to cover grammar for ObjectAssignmentPattern + var isShorthandPropertyAssignment = tokenIsIdentifier && (token() !== 57 /* ColonToken */); + if (isShorthandPropertyAssignment) { + node.kind = 276 /* ShorthandPropertyAssignment */; + var equalsToken = parseOptionalToken(59 /* EqualsToken */); + if (equalsToken) { + node.equalsToken = equalsToken; + node.objectAssignmentInitializer = allowInAnd(parseAssignmentExpressionOrHigher); + } + } + else { + node.kind = 275 /* PropertyAssignment */; + parseExpected(57 /* ColonToken */); + node.initializer = allowInAnd(parseAssignmentExpressionOrHigher); + } + return finishNode(node); + } + function parseObjectLiteralExpression() { + var node = createNode(188 /* ObjectLiteralExpression */); + parseExpected(18 /* OpenBraceToken */); + if (scanner.hasPrecedingLineBreak()) { + node.multiLine = true; + } + node.properties = parseDelimitedList(12 /* ObjectLiteralMembers */, parseObjectLiteralElement, /*considerSemicolonAsDelimiter*/ true); + parseExpected(19 /* CloseBraceToken */); + return finishNode(node); + } + function parseFunctionExpression() { + // GeneratorExpression: + // function* BindingIdentifier [Yield][opt](FormalParameters[Yield]){ GeneratorBody } + // + // FunctionExpression: + // function BindingIdentifier[opt](FormalParameters){ FunctionBody } + var saveDecoratorContext = inDecoratorContext(); + if (saveDecoratorContext) { + setDecoratorContext(/*val*/ false); + } + var node = createNodeWithJSDoc(196 /* FunctionExpression */); + node.modifiers = parseModifiers(); + parseExpected(90 /* FunctionKeyword */); + node.asteriskToken = parseOptionalToken(40 /* AsteriskToken */); + var isGenerator = node.asteriskToken ? 1 /* Yield */ : 0 /* None */; + var isAsync = ts.hasModifier(node, 256 /* Async */) ? 2 /* Await */ : 0 /* None */; + node.name = + isGenerator && isAsync ? doInYieldAndAwaitContext(parseOptionalIdentifier) : + isGenerator ? doInYieldContext(parseOptionalIdentifier) : + isAsync ? doInAwaitContext(parseOptionalIdentifier) : + parseOptionalIdentifier(); + fillSignature(57 /* ColonToken */, isGenerator | isAsync, node); + node.body = parseFunctionBlock(isGenerator | isAsync); + if (saveDecoratorContext) { + setDecoratorContext(/*val*/ true); + } + return finishNode(node); + } + function parseOptionalIdentifier() { + return isIdentifier() ? parseIdentifier() : undefined; + } + function parseNewExpressionOrNewDotTarget() { + var fullStart = scanner.getStartPos(); + parseExpected(95 /* NewKeyword */); + if (parseOptional(24 /* DotToken */)) { + var node_2 = createNode(214 /* MetaProperty */, fullStart); + node_2.keywordToken = 95 /* NewKeyword */; + node_2.name = parseIdentifierName(); + return finishNode(node_2); + } + var expression = parsePrimaryExpression(); + var typeArguments; + while (true) { + expression = parseMemberExpressionRest(expression); + typeArguments = tryParse(parseTypeArgumentsInExpression); + if (isTemplateStartOfTaggedTemplate()) { + ts.Debug.assert(!!typeArguments, "Expected a type argument list; all plain tagged template starts should be consumed in 'parseMemberExpressionRest'"); + expression = parseTaggedTemplateRest(expression, typeArguments); + typeArguments = undefined; + } + break; + } + var node = createNode(192 /* NewExpression */, fullStart); + node.expression = expression; + node.typeArguments = typeArguments; + if (node.typeArguments || token() === 20 /* OpenParenToken */) { + node.arguments = parseArgumentList(); + } + return finishNode(node); + } + // STATEMENTS + function parseBlock(ignoreMissingOpenBrace, diagnosticMessage) { + var node = createNode(218 /* Block */); + if (parseExpected(18 /* OpenBraceToken */, diagnosticMessage) || ignoreMissingOpenBrace) { + if (scanner.hasPrecedingLineBreak()) { + node.multiLine = true; + } + node.statements = parseList(1 /* BlockStatements */, parseStatement); + parseExpected(19 /* CloseBraceToken */); + } + else { + node.statements = createMissingList(); + } + return finishNode(node); + } + function parseFunctionBlock(flags, diagnosticMessage) { + var savedYieldContext = inYieldContext(); + setYieldContext(!!(flags & 1 /* Yield */)); + var savedAwaitContext = inAwaitContext(); + setAwaitContext(!!(flags & 2 /* Await */)); + // We may be in a [Decorator] context when parsing a function expression or + // arrow function. The body of the function is not in [Decorator] context. + var saveDecoratorContext = inDecoratorContext(); + if (saveDecoratorContext) { + setDecoratorContext(/*val*/ false); + } + var block = parseBlock(!!(flags & 16 /* IgnoreMissingOpenBrace */), diagnosticMessage); + if (saveDecoratorContext) { + setDecoratorContext(/*val*/ true); + } + setYieldContext(savedYieldContext); + setAwaitContext(savedAwaitContext); + return block; + } + function parseEmptyStatement() { + var node = createNode(220 /* EmptyStatement */); + parseExpected(26 /* SemicolonToken */); + return finishNode(node); + } + function parseIfStatement() { + var node = createNode(222 /* IfStatement */); + parseExpected(91 /* IfKeyword */); + parseExpected(20 /* OpenParenToken */); + node.expression = allowInAnd(parseExpression); + parseExpected(21 /* CloseParenToken */); + node.thenStatement = parseStatement(); + node.elseStatement = parseOptional(83 /* ElseKeyword */) ? parseStatement() : undefined; + return finishNode(node); + } + function parseDoStatement() { + var node = createNode(223 /* DoStatement */); + parseExpected(82 /* DoKeyword */); + node.statement = parseStatement(); + parseExpected(107 /* WhileKeyword */); + parseExpected(20 /* OpenParenToken */); + node.expression = allowInAnd(parseExpression); + parseExpected(21 /* CloseParenToken */); + // From: https://mail.mozilla.org/pipermail/es-discuss/2011-August/016188.html + // 157 min --- All allen at wirfs-brock.com CONF --- "do{;}while(false)false" prohibited in + // spec but allowed in consensus reality. Approved -- this is the de-facto standard whereby + // do;while(0)x will have a semicolon inserted before x. + parseOptional(26 /* SemicolonToken */); + return finishNode(node); + } + function parseWhileStatement() { + var node = createNode(224 /* WhileStatement */); + parseExpected(107 /* WhileKeyword */); + parseExpected(20 /* OpenParenToken */); + node.expression = allowInAnd(parseExpression); + parseExpected(21 /* CloseParenToken */); + node.statement = parseStatement(); + return finishNode(node); + } + function parseForOrForInOrForOfStatement() { + var pos = getNodePos(); + parseExpected(89 /* ForKeyword */); + var awaitToken = parseOptionalToken(122 /* AwaitKeyword */); + parseExpected(20 /* OpenParenToken */); + var initializer; + if (token() !== 26 /* SemicolonToken */) { + if (token() === 105 /* VarKeyword */ || token() === 111 /* LetKeyword */ || token() === 77 /* ConstKeyword */) { + initializer = parseVariableDeclarationList(/*inForStatementInitializer*/ true); + } + else { + initializer = disallowInAnd(parseExpression); + } + } + var forOrForInOrForOfStatement; + if (awaitToken ? parseExpected(147 /* OfKeyword */) : parseOptional(147 /* OfKeyword */)) { + var forOfStatement = createNode(227 /* ForOfStatement */, pos); + forOfStatement.awaitModifier = awaitToken; + forOfStatement.initializer = initializer; + forOfStatement.expression = allowInAnd(parseAssignmentExpressionOrHigher); + parseExpected(21 /* CloseParenToken */); + forOrForInOrForOfStatement = forOfStatement; + } + else if (parseOptional(93 /* InKeyword */)) { + var forInStatement = createNode(226 /* ForInStatement */, pos); + forInStatement.initializer = initializer; + forInStatement.expression = allowInAnd(parseExpression); + parseExpected(21 /* CloseParenToken */); + forOrForInOrForOfStatement = forInStatement; + } + else { + var forStatement = createNode(225 /* ForStatement */, pos); + forStatement.initializer = initializer; + parseExpected(26 /* SemicolonToken */); + if (token() !== 26 /* SemicolonToken */ && token() !== 21 /* CloseParenToken */) { + forStatement.condition = allowInAnd(parseExpression); + } + parseExpected(26 /* SemicolonToken */); + if (token() !== 21 /* CloseParenToken */) { + forStatement.incrementor = allowInAnd(parseExpression); + } + parseExpected(21 /* CloseParenToken */); + forOrForInOrForOfStatement = forStatement; + } + forOrForInOrForOfStatement.statement = parseStatement(); + return finishNode(forOrForInOrForOfStatement); + } + function parseBreakOrContinueStatement(kind) { + var node = createNode(kind); + parseExpected(kind === 229 /* BreakStatement */ ? 73 /* BreakKeyword */ : 78 /* ContinueKeyword */); + if (!canParseSemicolon()) { + node.label = parseIdentifier(); + } + parseSemicolon(); + return finishNode(node); + } + function parseReturnStatement() { + var node = createNode(230 /* ReturnStatement */); + parseExpected(97 /* ReturnKeyword */); + if (!canParseSemicolon()) { + node.expression = allowInAnd(parseExpression); + } + parseSemicolon(); + return finishNode(node); + } + function parseWithStatement() { + var node = createNode(231 /* WithStatement */); + parseExpected(108 /* WithKeyword */); + parseExpected(20 /* OpenParenToken */); + node.expression = allowInAnd(parseExpression); + parseExpected(21 /* CloseParenToken */); + node.statement = doInsideOfContext(8388608 /* InWithStatement */, parseStatement); + return finishNode(node); + } + function parseCaseClause() { + var node = createNode(271 /* CaseClause */); + parseExpected(74 /* CaseKeyword */); + node.expression = allowInAnd(parseExpression); + parseExpected(57 /* ColonToken */); + node.statements = parseList(3 /* SwitchClauseStatements */, parseStatement); + return finishNode(node); + } + function parseDefaultClause() { + var node = createNode(272 /* DefaultClause */); + parseExpected(80 /* DefaultKeyword */); + parseExpected(57 /* ColonToken */); + node.statements = parseList(3 /* SwitchClauseStatements */, parseStatement); + return finishNode(node); + } + function parseCaseOrDefaultClause() { + return token() === 74 /* CaseKeyword */ ? parseCaseClause() : parseDefaultClause(); + } + function parseSwitchStatement() { + var node = createNode(232 /* SwitchStatement */); + parseExpected(99 /* SwitchKeyword */); + parseExpected(20 /* OpenParenToken */); + node.expression = allowInAnd(parseExpression); + parseExpected(21 /* CloseParenToken */); + var caseBlock = createNode(246 /* CaseBlock */); + parseExpected(18 /* OpenBraceToken */); + caseBlock.clauses = parseList(2 /* SwitchClauses */, parseCaseOrDefaultClause); + parseExpected(19 /* CloseBraceToken */); + node.caseBlock = finishNode(caseBlock); + return finishNode(node); + } + function parseThrowStatement() { + // ThrowStatement[Yield] : + // throw [no LineTerminator here]Expression[In, ?Yield]; + // Because of automatic semicolon insertion, we need to report error if this + // throw could be terminated with a semicolon. Note: we can't call 'parseExpression' + // directly as that might consume an expression on the following line. + // We just return 'undefined' in that case. The actual error will be reported in the + // grammar walker. + var node = createNode(234 /* ThrowStatement */); + parseExpected(101 /* ThrowKeyword */); + node.expression = scanner.hasPrecedingLineBreak() ? undefined : allowInAnd(parseExpression); + parseSemicolon(); + return finishNode(node); + } + // TODO: Review for error recovery + function parseTryStatement() { + var node = createNode(235 /* TryStatement */); + parseExpected(103 /* TryKeyword */); + node.tryBlock = parseBlock(/*ignoreMissingOpenBrace*/ false); + node.catchClause = token() === 75 /* CatchKeyword */ ? parseCatchClause() : undefined; + // If we don't have a catch clause, then we must have a finally clause. Try to parse + // one out no matter what. + if (!node.catchClause || token() === 88 /* FinallyKeyword */) { + parseExpected(88 /* FinallyKeyword */); + node.finallyBlock = parseBlock(/*ignoreMissingOpenBrace*/ false); + } + return finishNode(node); + } + function parseCatchClause() { + var result = createNode(274 /* CatchClause */); + parseExpected(75 /* CatchKeyword */); + if (parseOptional(20 /* OpenParenToken */)) { + result.variableDeclaration = parseVariableDeclaration(); + parseExpected(21 /* CloseParenToken */); + } + else { + // Keep shape of node to avoid degrading performance. + result.variableDeclaration = undefined; + } + result.block = parseBlock(/*ignoreMissingOpenBrace*/ false); + return finishNode(result); + } + function parseDebuggerStatement() { + var node = createNode(236 /* DebuggerStatement */); + parseExpected(79 /* DebuggerKeyword */); + parseSemicolon(); + return finishNode(node); + } + function parseExpressionOrLabeledStatement() { + // Avoiding having to do the lookahead for a labeled statement by just trying to parse + // out an expression, seeing if it is identifier and then seeing if it is followed by + // a colon. + var node = createNodeWithJSDoc(0 /* Unknown */); + var expression = allowInAnd(parseExpression); + if (expression.kind === 72 /* Identifier */ && parseOptional(57 /* ColonToken */)) { + node.kind = 233 /* LabeledStatement */; + node.label = expression; + node.statement = parseStatement(); + } + else { + node.kind = 221 /* ExpressionStatement */; + node.expression = expression; + parseSemicolon(); + } + return finishNode(node); + } + function nextTokenIsIdentifierOrKeywordOnSameLine() { + nextToken(); + return ts.tokenIsIdentifierOrKeyword(token()) && !scanner.hasPrecedingLineBreak(); + } + function nextTokenIsClassKeywordOnSameLine() { + nextToken(); + return token() === 76 /* ClassKeyword */ && !scanner.hasPrecedingLineBreak(); + } + function nextTokenIsFunctionKeywordOnSameLine() { + nextToken(); + return token() === 90 /* FunctionKeyword */ && !scanner.hasPrecedingLineBreak(); + } + function nextTokenIsIdentifierOrKeywordOrLiteralOnSameLine() { + nextToken(); + return (ts.tokenIsIdentifierOrKeyword(token()) || token() === 8 /* NumericLiteral */ || token() === 9 /* BigIntLiteral */ || token() === 10 /* StringLiteral */) && !scanner.hasPrecedingLineBreak(); + } + function isDeclaration() { + while (true) { + switch (token()) { + case 105 /* VarKeyword */: + case 111 /* LetKeyword */: + case 77 /* ConstKeyword */: + case 90 /* FunctionKeyword */: + case 76 /* ClassKeyword */: + case 84 /* EnumKeyword */: + return true; + // 'declare', 'module', 'namespace', 'interface'* and 'type' are all legal JavaScript identifiers; + // however, an identifier cannot be followed by another identifier on the same line. This is what we + // count on to parse out the respective declarations. For instance, we exploit this to say that + // + // namespace n + // + // can be none other than the beginning of a namespace declaration, but need to respect that JavaScript sees + // + // namespace + // n + // + // as the identifier 'namespace' on one line followed by the identifier 'n' on another. + // We need to look one token ahead to see if it permissible to try parsing a declaration. + // + // *Note*: 'interface' is actually a strict mode reserved word. So while + // + // "use strict" + // interface + // I {} + // + // could be legal, it would add complexity for very little gain. + case 110 /* InterfaceKeyword */: + case 140 /* TypeKeyword */: + return nextTokenIsIdentifierOnSameLine(); + case 130 /* ModuleKeyword */: + case 131 /* NamespaceKeyword */: + return nextTokenIsIdentifierOrStringLiteralOnSameLine(); + case 118 /* AbstractKeyword */: + case 121 /* AsyncKeyword */: + case 125 /* DeclareKeyword */: + case 113 /* PrivateKeyword */: + case 114 /* ProtectedKeyword */: + case 115 /* PublicKeyword */: + case 133 /* ReadonlyKeyword */: + nextToken(); + // ASI takes effect for this modifier. + if (scanner.hasPrecedingLineBreak()) { + return false; + } + continue; + case 145 /* GlobalKeyword */: + nextToken(); + return token() === 18 /* OpenBraceToken */ || token() === 72 /* Identifier */ || token() === 85 /* ExportKeyword */; + case 92 /* ImportKeyword */: + nextToken(); + return token() === 10 /* StringLiteral */ || token() === 40 /* AsteriskToken */ || + token() === 18 /* OpenBraceToken */ || ts.tokenIsIdentifierOrKeyword(token()); + case 85 /* ExportKeyword */: + nextToken(); + if (token() === 59 /* EqualsToken */ || token() === 40 /* AsteriskToken */ || + token() === 18 /* OpenBraceToken */ || token() === 80 /* DefaultKeyword */ || + token() === 119 /* AsKeyword */) { + return true; + } + continue; + case 116 /* StaticKeyword */: + nextToken(); + continue; + default: + return false; + } + } + } + function isStartOfDeclaration() { + return lookAhead(isDeclaration); + } + function isStartOfStatement() { + switch (token()) { + case 58 /* AtToken */: + case 26 /* SemicolonToken */: + case 18 /* OpenBraceToken */: + case 105 /* VarKeyword */: + case 111 /* LetKeyword */: + case 90 /* FunctionKeyword */: + case 76 /* ClassKeyword */: + case 84 /* EnumKeyword */: + case 91 /* IfKeyword */: + case 82 /* DoKeyword */: + case 107 /* WhileKeyword */: + case 89 /* ForKeyword */: + case 78 /* ContinueKeyword */: + case 73 /* BreakKeyword */: + case 97 /* ReturnKeyword */: + case 108 /* WithKeyword */: + case 99 /* SwitchKeyword */: + case 101 /* ThrowKeyword */: + case 103 /* TryKeyword */: + case 79 /* DebuggerKeyword */: + // 'catch' and 'finally' do not actually indicate that the code is part of a statement, + // however, we say they are here so that we may gracefully parse them and error later. + case 75 /* CatchKeyword */: + case 88 /* FinallyKeyword */: + return true; + case 92 /* ImportKeyword */: + return isStartOfDeclaration() || lookAhead(nextTokenIsOpenParenOrLessThanOrDot); + case 77 /* ConstKeyword */: + case 85 /* ExportKeyword */: + return isStartOfDeclaration(); + case 121 /* AsyncKeyword */: + case 125 /* DeclareKeyword */: + case 110 /* InterfaceKeyword */: + case 130 /* ModuleKeyword */: + case 131 /* NamespaceKeyword */: + case 140 /* TypeKeyword */: + case 145 /* GlobalKeyword */: + // When these don't start a declaration, they're an identifier in an expression statement + return true; + case 115 /* PublicKeyword */: + case 113 /* PrivateKeyword */: + case 114 /* ProtectedKeyword */: + case 116 /* StaticKeyword */: + case 133 /* ReadonlyKeyword */: + // When these don't start a declaration, they may be the start of a class member if an identifier + // immediately follows. Otherwise they're an identifier in an expression statement. + return isStartOfDeclaration() || !lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine); + default: + return isStartOfExpression(); + } + } + function nextTokenIsIdentifierOrStartOfDestructuring() { + nextToken(); + return isIdentifier() || token() === 18 /* OpenBraceToken */ || token() === 22 /* OpenBracketToken */; + } + function isLetDeclaration() { + // In ES6 'let' always starts a lexical declaration if followed by an identifier or { + // or [. + return lookAhead(nextTokenIsIdentifierOrStartOfDestructuring); + } + function parseStatement() { + switch (token()) { + case 26 /* SemicolonToken */: + return parseEmptyStatement(); + case 18 /* OpenBraceToken */: + return parseBlock(/*ignoreMissingOpenBrace*/ false); + case 105 /* VarKeyword */: + return parseVariableStatement(createNodeWithJSDoc(237 /* VariableDeclaration */)); + case 111 /* LetKeyword */: + if (isLetDeclaration()) { + return parseVariableStatement(createNodeWithJSDoc(237 /* VariableDeclaration */)); + } + break; + case 90 /* FunctionKeyword */: + return parseFunctionDeclaration(createNodeWithJSDoc(239 /* FunctionDeclaration */)); + case 76 /* ClassKeyword */: + return parseClassDeclaration(createNodeWithJSDoc(240 /* ClassDeclaration */)); + case 91 /* IfKeyword */: + return parseIfStatement(); + case 82 /* DoKeyword */: + return parseDoStatement(); + case 107 /* WhileKeyword */: + return parseWhileStatement(); + case 89 /* ForKeyword */: + return parseForOrForInOrForOfStatement(); + case 78 /* ContinueKeyword */: + return parseBreakOrContinueStatement(228 /* ContinueStatement */); + case 73 /* BreakKeyword */: + return parseBreakOrContinueStatement(229 /* BreakStatement */); + case 97 /* ReturnKeyword */: + return parseReturnStatement(); + case 108 /* WithKeyword */: + return parseWithStatement(); + case 99 /* SwitchKeyword */: + return parseSwitchStatement(); + case 101 /* ThrowKeyword */: + return parseThrowStatement(); + case 103 /* TryKeyword */: + // Include 'catch' and 'finally' for error recovery. + case 75 /* CatchKeyword */: + case 88 /* FinallyKeyword */: + return parseTryStatement(); + case 79 /* DebuggerKeyword */: + return parseDebuggerStatement(); + case 58 /* AtToken */: + return parseDeclaration(); + case 121 /* AsyncKeyword */: + case 110 /* InterfaceKeyword */: + case 140 /* TypeKeyword */: + case 130 /* ModuleKeyword */: + case 131 /* NamespaceKeyword */: + case 125 /* DeclareKeyword */: + case 77 /* ConstKeyword */: + case 84 /* EnumKeyword */: + case 85 /* ExportKeyword */: + case 92 /* ImportKeyword */: + case 113 /* PrivateKeyword */: + case 114 /* ProtectedKeyword */: + case 115 /* PublicKeyword */: + case 118 /* AbstractKeyword */: + case 116 /* StaticKeyword */: + case 133 /* ReadonlyKeyword */: + case 145 /* GlobalKeyword */: + if (isStartOfDeclaration()) { + return parseDeclaration(); + } + break; + } + return parseExpressionOrLabeledStatement(); + } + function isDeclareModifier(modifier) { + return modifier.kind === 125 /* DeclareKeyword */; + } + function parseDeclaration() { + var node = createNodeWithJSDoc(0 /* Unknown */); + node.decorators = parseDecorators(); + node.modifiers = parseModifiers(); + if (ts.some(node.modifiers, isDeclareModifier)) { + for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) { + var m = _a[_i]; + m.flags |= 4194304 /* Ambient */; + } + return doInsideOfContext(4194304 /* Ambient */, function () { return parseDeclarationWorker(node); }); + } + else { + return parseDeclarationWorker(node); + } + } + function parseDeclarationWorker(node) { + switch (token()) { + case 105 /* VarKeyword */: + case 111 /* LetKeyword */: + case 77 /* ConstKeyword */: + return parseVariableStatement(node); + case 90 /* FunctionKeyword */: + return parseFunctionDeclaration(node); + case 76 /* ClassKeyword */: + return parseClassDeclaration(node); + case 110 /* InterfaceKeyword */: + return parseInterfaceDeclaration(node); + case 140 /* TypeKeyword */: + return parseTypeAliasDeclaration(node); + case 84 /* EnumKeyword */: + return parseEnumDeclaration(node); + case 145 /* GlobalKeyword */: + case 130 /* ModuleKeyword */: + case 131 /* NamespaceKeyword */: + return parseModuleDeclaration(node); + case 92 /* ImportKeyword */: + return parseImportDeclarationOrImportEqualsDeclaration(node); + case 85 /* ExportKeyword */: + nextToken(); + switch (token()) { + case 80 /* DefaultKeyword */: + case 59 /* EqualsToken */: + return parseExportAssignment(node); + case 119 /* AsKeyword */: + return parseNamespaceExportDeclaration(node); + default: + return parseExportDeclaration(node); + } + default: + if (node.decorators || node.modifiers) { + // We reached this point because we encountered decorators and/or modifiers and assumed a declaration + // would follow. For recovery and error reporting purposes, return an incomplete declaration. + var missing = createMissingNode(258 /* MissingDeclaration */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected); + missing.pos = node.pos; + missing.decorators = node.decorators; + missing.modifiers = node.modifiers; + return finishNode(missing); + } + return undefined; // TODO: GH#18217 + } + } + function nextTokenIsIdentifierOrStringLiteralOnSameLine() { + nextToken(); + return !scanner.hasPrecedingLineBreak() && (isIdentifier() || token() === 10 /* StringLiteral */); + } + function parseFunctionBlockOrSemicolon(flags, diagnosticMessage) { + if (token() !== 18 /* OpenBraceToken */ && canParseSemicolon()) { + parseSemicolon(); + return; + } + return parseFunctionBlock(flags, diagnosticMessage); + } + // DECLARATIONS + function parseArrayBindingElement() { + if (token() === 27 /* CommaToken */) { + return createNode(210 /* OmittedExpression */); + } + var node = createNode(186 /* BindingElement */); + node.dotDotDotToken = parseOptionalToken(25 /* DotDotDotToken */); + node.name = parseIdentifierOrPattern(); + node.initializer = parseInitializer(); + return finishNode(node); + } + function parseObjectBindingElement() { + var node = createNode(186 /* BindingElement */); + node.dotDotDotToken = parseOptionalToken(25 /* DotDotDotToken */); + var tokenIsIdentifier = isIdentifier(); + var propertyName = parsePropertyName(); + if (tokenIsIdentifier && token() !== 57 /* ColonToken */) { + node.name = propertyName; + } + else { + parseExpected(57 /* ColonToken */); + node.propertyName = propertyName; + node.name = parseIdentifierOrPattern(); + } + node.initializer = parseInitializer(); + return finishNode(node); + } + function parseObjectBindingPattern() { + var node = createNode(184 /* ObjectBindingPattern */); + parseExpected(18 /* OpenBraceToken */); + node.elements = parseDelimitedList(9 /* ObjectBindingElements */, parseObjectBindingElement); + parseExpected(19 /* CloseBraceToken */); + return finishNode(node); + } + function parseArrayBindingPattern() { + var node = createNode(185 /* ArrayBindingPattern */); + parseExpected(22 /* OpenBracketToken */); + node.elements = parseDelimitedList(10 /* ArrayBindingElements */, parseArrayBindingElement); + parseExpected(23 /* CloseBracketToken */); + return finishNode(node); + } + function isIdentifierOrPattern() { + return token() === 18 /* OpenBraceToken */ || token() === 22 /* OpenBracketToken */ || isIdentifier(); + } + function parseIdentifierOrPattern() { + if (token() === 22 /* OpenBracketToken */) { + return parseArrayBindingPattern(); + } + if (token() === 18 /* OpenBraceToken */) { + return parseObjectBindingPattern(); + } + return parseIdentifier(); + } + function parseVariableDeclarationAllowExclamation() { + return parseVariableDeclaration(/*allowExclamation*/ true); + } + function parseVariableDeclaration(allowExclamation) { + var node = createNode(237 /* VariableDeclaration */); + node.name = parseIdentifierOrPattern(); + if (allowExclamation && node.name.kind === 72 /* Identifier */ && + token() === 52 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) { + node.exclamationToken = parseTokenNode(); + } + node.type = parseTypeAnnotation(); + if (!isInOrOfKeyword(token())) { + node.initializer = parseInitializer(); + } + return finishNode(node); + } + function parseVariableDeclarationList(inForStatementInitializer) { + var node = createNode(238 /* VariableDeclarationList */); + switch (token()) { + case 105 /* VarKeyword */: + break; + case 111 /* LetKeyword */: + node.flags |= 1 /* Let */; + break; + case 77 /* ConstKeyword */: + node.flags |= 2 /* Const */; + break; + default: + ts.Debug.fail(); + } + nextToken(); + // The user may have written the following: + // + // for (let of X) { } + // + // In this case, we want to parse an empty declaration list, and then parse 'of' + // as a keyword. The reason this is not automatic is that 'of' is a valid identifier. + // So we need to look ahead to determine if 'of' should be treated as a keyword in + // this context. + // The checker will then give an error that there is an empty declaration list. + if (token() === 147 /* OfKeyword */ && lookAhead(canFollowContextualOfKeyword)) { + node.declarations = createMissingList(); + } + else { + var savedDisallowIn = inDisallowInContext(); + setDisallowInContext(inForStatementInitializer); + node.declarations = parseDelimitedList(8 /* VariableDeclarations */, inForStatementInitializer ? parseVariableDeclaration : parseVariableDeclarationAllowExclamation); + setDisallowInContext(savedDisallowIn); + } + return finishNode(node); + } + function canFollowContextualOfKeyword() { + return nextTokenIsIdentifier() && nextToken() === 21 /* CloseParenToken */; + } + function parseVariableStatement(node) { + node.kind = 219 /* VariableStatement */; + node.declarationList = parseVariableDeclarationList(/*inForStatementInitializer*/ false); + parseSemicolon(); + return finishNode(node); + } + function parseFunctionDeclaration(node) { + node.kind = 239 /* FunctionDeclaration */; + parseExpected(90 /* FunctionKeyword */); + node.asteriskToken = parseOptionalToken(40 /* AsteriskToken */); + node.name = ts.hasModifier(node, 512 /* Default */) ? parseOptionalIdentifier() : parseIdentifier(); + var isGenerator = node.asteriskToken ? 1 /* Yield */ : 0 /* None */; + var isAsync = ts.hasModifier(node, 256 /* Async */) ? 2 /* Await */ : 0 /* None */; + fillSignature(57 /* ColonToken */, isGenerator | isAsync, node); + node.body = parseFunctionBlockOrSemicolon(isGenerator | isAsync, ts.Diagnostics.or_expected); + return finishNode(node); + } + function parseConstructorDeclaration(node) { + node.kind = 157 /* Constructor */; + parseExpected(124 /* ConstructorKeyword */); + fillSignature(57 /* ColonToken */, 0 /* None */, node); + node.body = parseFunctionBlockOrSemicolon(0 /* None */, ts.Diagnostics.or_expected); + return finishNode(node); + } + function parseMethodDeclaration(node, asteriskToken, diagnosticMessage) { + node.kind = 156 /* MethodDeclaration */; + node.asteriskToken = asteriskToken; + var isGenerator = asteriskToken ? 1 /* Yield */ : 0 /* None */; + var isAsync = ts.hasModifier(node, 256 /* Async */) ? 2 /* Await */ : 0 /* None */; + fillSignature(57 /* ColonToken */, isGenerator | isAsync, node); + node.body = parseFunctionBlockOrSemicolon(isGenerator | isAsync, diagnosticMessage); + return finishNode(node); + } + function parsePropertyDeclaration(node) { + node.kind = 154 /* PropertyDeclaration */; + if (!node.questionToken && token() === 52 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) { + node.exclamationToken = parseTokenNode(); + } + node.type = parseTypeAnnotation(); + // For instance properties specifically, since they are evaluated inside the constructor, + // we do *not * want to parse yield expressions, so we specifically turn the yield context + // off. The grammar would look something like this: + // + // MemberVariableDeclaration[Yield]: + // AccessibilityModifier_opt PropertyName TypeAnnotation_opt Initializer_opt[In]; + // AccessibilityModifier_opt static_opt PropertyName TypeAnnotation_opt Initializer_opt[In, ?Yield]; + // + // The checker may still error in the static case to explicitly disallow the yield expression. + node.initializer = ts.hasModifier(node, 32 /* Static */) + ? allowInAnd(parseInitializer) + : doOutsideOfContext(4096 /* YieldContext */ | 2048 /* DisallowInContext */, parseInitializer); + parseSemicolon(); + return finishNode(node); + } + function parsePropertyOrMethodDeclaration(node) { + var asteriskToken = parseOptionalToken(40 /* AsteriskToken */); + node.name = parsePropertyName(); + // Note: this is not legal as per the grammar. But we allow it in the parser and + // report an error in the grammar checker. + node.questionToken = parseOptionalToken(56 /* QuestionToken */); + if (asteriskToken || token() === 20 /* OpenParenToken */ || token() === 28 /* LessThanToken */) { + return parseMethodDeclaration(node, asteriskToken, ts.Diagnostics.or_expected); + } + return parsePropertyDeclaration(node); + } + function parseAccessorDeclaration(node, kind) { + node.kind = kind; + node.name = parsePropertyName(); + fillSignature(57 /* ColonToken */, 0 /* None */, node); + node.body = parseFunctionBlockOrSemicolon(0 /* None */); + return finishNode(node); + } + function isClassMemberStart() { + var idToken; + if (token() === 58 /* AtToken */) { + return true; + } + // Eat up all modifiers, but hold on to the last one in case it is actually an identifier. + while (ts.isModifierKind(token())) { + idToken = token(); + // If the idToken is a class modifier (protected, private, public, and static), it is + // certain that we are starting to parse class member. This allows better error recovery + // Example: + // public foo() ... // true + // public @dec blah ... // true; we will then report an error later + // export public ... // true; we will then report an error later + if (ts.isClassMemberModifier(idToken)) { + return true; + } + nextToken(); + } + if (token() === 40 /* AsteriskToken */) { + return true; + } + // Try to get the first property-like token following all modifiers. + // This can either be an identifier or the 'get' or 'set' keywords. + if (isLiteralPropertyName()) { + idToken = token(); + nextToken(); + } + // Index signatures and computed properties are class members; we can parse. + if (token() === 22 /* OpenBracketToken */) { + return true; + } + // If we were able to get any potential identifier... + if (idToken !== undefined) { + // If we have a non-keyword identifier, or if we have an accessor, then it's safe to parse. + if (!ts.isKeyword(idToken) || idToken === 137 /* SetKeyword */ || idToken === 126 /* GetKeyword */) { + return true; + } + // If it *is* a keyword, but not an accessor, check a little farther along + // to see if it should actually be parsed as a class member. + switch (token()) { + case 20 /* OpenParenToken */: // Method declaration + case 28 /* LessThanToken */: // Generic Method declaration + case 52 /* ExclamationToken */: // Non-null assertion on property name + case 57 /* ColonToken */: // Type Annotation for declaration + case 59 /* EqualsToken */: // Initializer for declaration + case 56 /* QuestionToken */: // Not valid, but permitted so that it gets caught later on. + return true; + default: + // Covers + // - Semicolons (declaration termination) + // - Closing braces (end-of-class, must be declaration) + // - End-of-files (not valid, but permitted so that it gets caught later on) + // - Line-breaks (enabling *automatic semicolon insertion*) + return canParseSemicolon(); + } + } + return false; + } + function parseDecorators() { + var list; + var listPos = getNodePos(); + while (true) { + var decoratorStart = getNodePos(); + if (!parseOptional(58 /* AtToken */)) { + break; + } + var decorator = createNode(152 /* Decorator */, decoratorStart); + decorator.expression = doInDecoratorContext(parseLeftHandSideExpressionOrHigher); + finishNode(decorator); + (list || (list = [])).push(decorator); + } + return list && createNodeArray(list, listPos); + } + /* + * There are situations in which a modifier like 'const' will appear unexpectedly, such as on a class member. + * In those situations, if we are entirely sure that 'const' is not valid on its own (such as when ASI takes effect + * and turns it into a standalone declaration), then it is better to parse it and report an error later. + * + * In such situations, 'permitInvalidConstAsModifier' should be set to true. + */ + function parseModifiers(permitInvalidConstAsModifier) { + var list; + var listPos = getNodePos(); + while (true) { + var modifierStart = scanner.getStartPos(); + var modifierKind = token(); + if (token() === 77 /* ConstKeyword */ && permitInvalidConstAsModifier) { + // We need to ensure that any subsequent modifiers appear on the same line + // so that when 'const' is a standalone declaration, we don't issue an error. + if (!tryParse(nextTokenIsOnSameLineAndCanFollowModifier)) { + break; + } + } + else { + if (!parseAnyContextualModifier()) { + break; + } + } + var modifier = finishNode(createNode(modifierKind, modifierStart)); + (list || (list = [])).push(modifier); + } + return list && createNodeArray(list, listPos); + } + function parseModifiersForArrowFunction() { + var modifiers; + if (token() === 121 /* AsyncKeyword */) { + var modifierStart = scanner.getStartPos(); + var modifierKind = token(); + nextToken(); + var modifier = finishNode(createNode(modifierKind, modifierStart)); + modifiers = createNodeArray([modifier], modifierStart); + } + return modifiers; + } + function parseClassElement() { + if (token() === 26 /* SemicolonToken */) { + var result = createNode(217 /* SemicolonClassElement */); + nextToken(); + return finishNode(result); + } + var node = createNodeWithJSDoc(0 /* Unknown */); + node.decorators = parseDecorators(); + node.modifiers = parseModifiers(/*permitInvalidConstAsModifier*/ true); + if (parseContextualModifier(126 /* GetKeyword */)) { + return parseAccessorDeclaration(node, 158 /* GetAccessor */); + } + if (parseContextualModifier(137 /* SetKeyword */)) { + return parseAccessorDeclaration(node, 159 /* SetAccessor */); + } + if (token() === 124 /* ConstructorKeyword */) { + return parseConstructorDeclaration(node); + } + if (isIndexSignature()) { + return parseIndexSignatureDeclaration(node); + } + // It is very important that we check this *after* checking indexers because + // the [ token can start an index signature or a computed property name + if (ts.tokenIsIdentifierOrKeyword(token()) || + token() === 10 /* StringLiteral */ || + token() === 8 /* NumericLiteral */ || + token() === 40 /* AsteriskToken */ || + token() === 22 /* OpenBracketToken */) { + return parsePropertyOrMethodDeclaration(node); + } + if (node.decorators || node.modifiers) { + // treat this as a property declaration with a missing name. + node.name = createMissingNode(72 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected); + return parsePropertyDeclaration(node); + } + // 'isClassMemberStart' should have hinted not to attempt parsing. + return ts.Debug.fail("Should not have attempted to parse class member declaration."); + } + function parseClassExpression() { + return parseClassDeclarationOrExpression(createNodeWithJSDoc(0 /* Unknown */), 209 /* ClassExpression */); + } + function parseClassDeclaration(node) { + return parseClassDeclarationOrExpression(node, 240 /* ClassDeclaration */); + } + function parseClassDeclarationOrExpression(node, kind) { + node.kind = kind; + parseExpected(76 /* ClassKeyword */); + node.name = parseNameOfClassDeclarationOrExpression(); + node.typeParameters = parseTypeParameters(); + node.heritageClauses = parseHeritageClauses(); + if (parseExpected(18 /* OpenBraceToken */)) { + // ClassTail[Yield,Await] : (Modified) See 14.5 + // ClassHeritage[?Yield,?Await]opt { ClassBody[?Yield,?Await]opt } + node.members = parseClassMembers(); + parseExpected(19 /* CloseBraceToken */); + } + else { + node.members = createMissingList(); + } + return finishNode(node); + } + function parseNameOfClassDeclarationOrExpression() { + // implements is a future reserved word so + // 'class implements' might mean either + // - class expression with omitted name, 'implements' starts heritage clause + // - class with name 'implements' + // 'isImplementsClause' helps to disambiguate between these two cases + return isIdentifier() && !isImplementsClause() + ? parseIdentifier() + : undefined; + } + function isImplementsClause() { + return token() === 109 /* ImplementsKeyword */ && lookAhead(nextTokenIsIdentifierOrKeyword); + } + function parseHeritageClauses() { + // ClassTail[Yield,Await] : (Modified) See 14.5 + // ClassHeritage[?Yield,?Await]opt { ClassBody[?Yield,?Await]opt } + if (isHeritageClause()) { + return parseList(22 /* HeritageClauses */, parseHeritageClause); + } + return undefined; + } + function parseHeritageClause() { + var tok = token(); + ts.Debug.assert(tok === 86 /* ExtendsKeyword */ || tok === 109 /* ImplementsKeyword */); // isListElement() should ensure this. + var node = createNode(273 /* HeritageClause */); + node.token = tok; + nextToken(); + node.types = parseDelimitedList(7 /* HeritageClauseElement */, parseExpressionWithTypeArguments); + return finishNode(node); + } + function parseExpressionWithTypeArguments() { + var node = createNode(211 /* ExpressionWithTypeArguments */); + node.expression = parseLeftHandSideExpressionOrHigher(); + node.typeArguments = tryParseTypeArguments(); + return finishNode(node); + } + function tryParseTypeArguments() { + return token() === 28 /* LessThanToken */ + ? parseBracketedList(20 /* TypeArguments */, parseType, 28 /* LessThanToken */, 30 /* GreaterThanToken */) + : undefined; + } + function isHeritageClause() { + return token() === 86 /* ExtendsKeyword */ || token() === 109 /* ImplementsKeyword */; + } + function parseClassMembers() { + return parseList(5 /* ClassMembers */, parseClassElement); + } + function parseInterfaceDeclaration(node) { + node.kind = 241 /* InterfaceDeclaration */; + parseExpected(110 /* InterfaceKeyword */); + node.name = parseIdentifier(); + node.typeParameters = parseTypeParameters(); + node.heritageClauses = parseHeritageClauses(); + node.members = parseObjectTypeMembers(); + return finishNode(node); + } + function parseTypeAliasDeclaration(node) { + node.kind = 242 /* TypeAliasDeclaration */; + parseExpected(140 /* TypeKeyword */); + node.name = parseIdentifier(); + node.typeParameters = parseTypeParameters(); + parseExpected(59 /* EqualsToken */); + node.type = parseType(); + parseSemicolon(); + return finishNode(node); + } + // In an ambient declaration, the grammar only allows integer literals as initializers. + // In a non-ambient declaration, the grammar allows uninitialized members only in a + // ConstantEnumMemberSection, which starts at the beginning of an enum declaration + // or any time an integer literal initializer is encountered. + function parseEnumMember() { + var node = createNodeWithJSDoc(278 /* EnumMember */); + node.name = parsePropertyName(); + node.initializer = allowInAnd(parseInitializer); + return finishNode(node); + } + function parseEnumDeclaration(node) { + node.kind = 243 /* EnumDeclaration */; + parseExpected(84 /* EnumKeyword */); + node.name = parseIdentifier(); + if (parseExpected(18 /* OpenBraceToken */)) { + node.members = parseDelimitedList(6 /* EnumMembers */, parseEnumMember); + parseExpected(19 /* CloseBraceToken */); + } + else { + node.members = createMissingList(); + } + return finishNode(node); + } + function parseModuleBlock() { + var node = createNode(245 /* ModuleBlock */); + if (parseExpected(18 /* OpenBraceToken */)) { + node.statements = parseList(1 /* BlockStatements */, parseStatement); + parseExpected(19 /* CloseBraceToken */); + } + else { + node.statements = createMissingList(); + } + return finishNode(node); + } + function parseModuleOrNamespaceDeclaration(node, flags) { + node.kind = 244 /* ModuleDeclaration */; + // If we are parsing a dotted namespace name, we want to + // propagate the 'Namespace' flag across the names if set. + var namespaceFlag = flags & 16 /* Namespace */; + node.flags |= flags; + node.name = parseIdentifier(); + node.body = parseOptional(24 /* DotToken */) + ? parseModuleOrNamespaceDeclaration(createNode(0 /* Unknown */), 4 /* NestedNamespace */ | namespaceFlag) + : parseModuleBlock(); + return finishNode(node); + } + function parseAmbientExternalModuleDeclaration(node) { + node.kind = 244 /* ModuleDeclaration */; + if (token() === 145 /* GlobalKeyword */) { + // parse 'global' as name of global scope augmentation + node.name = parseIdentifier(); + node.flags |= 512 /* GlobalAugmentation */; + } + else { + node.name = parseLiteralNode(); + node.name.text = internIdentifier(node.name.text); + } + if (token() === 18 /* OpenBraceToken */) { + node.body = parseModuleBlock(); + } + else { + parseSemicolon(); + } + return finishNode(node); + } + function parseModuleDeclaration(node) { + var flags = 0; + if (token() === 145 /* GlobalKeyword */) { + // global augmentation + return parseAmbientExternalModuleDeclaration(node); + } + else if (parseOptional(131 /* NamespaceKeyword */)) { + flags |= 16 /* Namespace */; + } + else { + parseExpected(130 /* ModuleKeyword */); + if (token() === 10 /* StringLiteral */) { + return parseAmbientExternalModuleDeclaration(node); + } + } + return parseModuleOrNamespaceDeclaration(node, flags); + } + function isExternalModuleReference() { + return token() === 134 /* RequireKeyword */ && + lookAhead(nextTokenIsOpenParen); + } + function nextTokenIsOpenParen() { + return nextToken() === 20 /* OpenParenToken */; + } + function nextTokenIsSlash() { + return nextToken() === 42 /* SlashToken */; + } + function parseNamespaceExportDeclaration(node) { + node.kind = 247 /* NamespaceExportDeclaration */; + parseExpected(119 /* AsKeyword */); + parseExpected(131 /* NamespaceKeyword */); + node.name = parseIdentifier(); + parseSemicolon(); + return finishNode(node); + } + function parseImportDeclarationOrImportEqualsDeclaration(node) { + parseExpected(92 /* ImportKeyword */); + var afterImportPos = scanner.getStartPos(); + var identifier; + if (isIdentifier()) { + identifier = parseIdentifier(); + if (token() !== 27 /* CommaToken */ && token() !== 144 /* FromKeyword */) { + return parseImportEqualsDeclaration(node, identifier); + } + } + // Import statement + node.kind = 249 /* ImportDeclaration */; + // ImportDeclaration: + // import ImportClause from ModuleSpecifier ; + // import ModuleSpecifier; + if (identifier || // import id + token() === 40 /* AsteriskToken */ || // import * + token() === 18 /* OpenBraceToken */) { // import { + node.importClause = parseImportClause(identifier, afterImportPos); + parseExpected(144 /* FromKeyword */); + } + node.moduleSpecifier = parseModuleSpecifier(); + parseSemicolon(); + return finishNode(node); + } + function parseImportEqualsDeclaration(node, identifier) { + node.kind = 248 /* ImportEqualsDeclaration */; + node.name = identifier; + parseExpected(59 /* EqualsToken */); + node.moduleReference = parseModuleReference(); + parseSemicolon(); + return finishNode(node); + } + function parseImportClause(identifier, fullStart) { + // ImportClause: + // ImportedDefaultBinding + // NameSpaceImport + // NamedImports + // ImportedDefaultBinding, NameSpaceImport + // ImportedDefaultBinding, NamedImports + var importClause = createNode(250 /* ImportClause */, fullStart); + if (identifier) { + // ImportedDefaultBinding: + // ImportedBinding + importClause.name = identifier; + } + // If there was no default import or if there is comma token after default import + // parse namespace or named imports + if (!importClause.name || + parseOptional(27 /* CommaToken */)) { + importClause.namedBindings = token() === 40 /* AsteriskToken */ ? parseNamespaceImport() : parseNamedImportsOrExports(252 /* NamedImports */); + } + return finishNode(importClause); + } + function parseModuleReference() { + return isExternalModuleReference() + ? parseExternalModuleReference() + : parseEntityName(/*allowReservedWords*/ false); + } + function parseExternalModuleReference() { + var node = createNode(259 /* ExternalModuleReference */); + parseExpected(134 /* RequireKeyword */); + parseExpected(20 /* OpenParenToken */); + node.expression = parseModuleSpecifier(); + parseExpected(21 /* CloseParenToken */); + return finishNode(node); + } + function parseModuleSpecifier() { + if (token() === 10 /* StringLiteral */) { + var result = parseLiteralNode(); + result.text = internIdentifier(result.text); + return result; + } + else { + // We allow arbitrary expressions here, even though the grammar only allows string + // literals. We check to ensure that it is only a string literal later in the grammar + // check pass. + return parseExpression(); + } + } + function parseNamespaceImport() { + // NameSpaceImport: + // * as ImportedBinding + var namespaceImport = createNode(251 /* NamespaceImport */); + parseExpected(40 /* AsteriskToken */); + parseExpected(119 /* AsKeyword */); + namespaceImport.name = parseIdentifier(); + return finishNode(namespaceImport); + } + function parseNamedImportsOrExports(kind) { + var node = createNode(kind); + // NamedImports: + // { } + // { ImportsList } + // { ImportsList, } + // ImportsList: + // ImportSpecifier + // ImportsList, ImportSpecifier + node.elements = parseBracketedList(23 /* ImportOrExportSpecifiers */, kind === 252 /* NamedImports */ ? parseImportSpecifier : parseExportSpecifier, 18 /* OpenBraceToken */, 19 /* CloseBraceToken */); + return finishNode(node); + } + function parseExportSpecifier() { + return parseImportOrExportSpecifier(257 /* ExportSpecifier */); + } + function parseImportSpecifier() { + return parseImportOrExportSpecifier(253 /* ImportSpecifier */); + } + function parseImportOrExportSpecifier(kind) { + var node = createNode(kind); + // ImportSpecifier: + // BindingIdentifier + // IdentifierName as BindingIdentifier + // ExportSpecifier: + // IdentifierName + // IdentifierName as IdentifierName + var checkIdentifierIsKeyword = ts.isKeyword(token()) && !isIdentifier(); + var checkIdentifierStart = scanner.getTokenPos(); + var checkIdentifierEnd = scanner.getTextPos(); + var identifierName = parseIdentifierName(); + if (token() === 119 /* AsKeyword */) { + node.propertyName = identifierName; + parseExpected(119 /* AsKeyword */); + checkIdentifierIsKeyword = ts.isKeyword(token()) && !isIdentifier(); + checkIdentifierStart = scanner.getTokenPos(); + checkIdentifierEnd = scanner.getTextPos(); + node.name = parseIdentifierName(); + } + else { + node.name = identifierName; + } + if (kind === 253 /* ImportSpecifier */ && checkIdentifierIsKeyword) { + parseErrorAt(checkIdentifierStart, checkIdentifierEnd, ts.Diagnostics.Identifier_expected); + } + return finishNode(node); + } + function parseExportDeclaration(node) { + node.kind = 255 /* ExportDeclaration */; + if (parseOptional(40 /* AsteriskToken */)) { + parseExpected(144 /* FromKeyword */); + node.moduleSpecifier = parseModuleSpecifier(); + } + else { + node.exportClause = parseNamedImportsOrExports(256 /* NamedExports */); + // It is not uncommon to accidentally omit the 'from' keyword. Additionally, in editing scenarios, + // the 'from' keyword can be parsed as a named export when the export clause is unterminated (i.e. `export { from "moduleName";`) + // If we don't have a 'from' keyword, see if we have a string literal such that ASI won't take effect. + if (token() === 144 /* FromKeyword */ || (token() === 10 /* StringLiteral */ && !scanner.hasPrecedingLineBreak())) { + parseExpected(144 /* FromKeyword */); + node.moduleSpecifier = parseModuleSpecifier(); + } + } + parseSemicolon(); + return finishNode(node); + } + function parseExportAssignment(node) { + node.kind = 254 /* ExportAssignment */; + if (parseOptional(59 /* EqualsToken */)) { + node.isExportEquals = true; + } + else { + parseExpected(80 /* DefaultKeyword */); + } + node.expression = parseAssignmentExpressionOrHigher(); + parseSemicolon(); + return finishNode(node); + } + function setExternalModuleIndicator(sourceFile) { + // Try to use the first top-level import/export when available, then + // fall back to looking for an 'import.meta' somewhere in the tree if necessary. + sourceFile.externalModuleIndicator = + ts.forEach(sourceFile.statements, isAnExternalModuleIndicatorNode) || + getImportMetaIfNecessary(sourceFile); + } + function isAnExternalModuleIndicatorNode(node) { + return ts.hasModifier(node, 1 /* Export */) + || node.kind === 248 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 259 /* ExternalModuleReference */ + || node.kind === 249 /* ImportDeclaration */ + || node.kind === 254 /* ExportAssignment */ + || node.kind === 255 /* ExportDeclaration */ + ? node + : undefined; + } + function getImportMetaIfNecessary(sourceFile) { + return sourceFile.flags & 1048576 /* PossiblyContainsImportMeta */ ? + walkTreeForExternalModuleIndicators(sourceFile) : + undefined; + } + function walkTreeForExternalModuleIndicators(node) { + return isImportMeta(node) ? node : forEachChild(node, walkTreeForExternalModuleIndicators); + } + function isImportMeta(node) { + return ts.isMetaProperty(node) && node.keywordToken === 92 /* ImportKeyword */ && node.name.escapedText === "meta"; + } + var ParsingContext; + (function (ParsingContext) { + ParsingContext[ParsingContext["SourceElements"] = 0] = "SourceElements"; + ParsingContext[ParsingContext["BlockStatements"] = 1] = "BlockStatements"; + ParsingContext[ParsingContext["SwitchClauses"] = 2] = "SwitchClauses"; + ParsingContext[ParsingContext["SwitchClauseStatements"] = 3] = "SwitchClauseStatements"; + ParsingContext[ParsingContext["TypeMembers"] = 4] = "TypeMembers"; + ParsingContext[ParsingContext["ClassMembers"] = 5] = "ClassMembers"; + ParsingContext[ParsingContext["EnumMembers"] = 6] = "EnumMembers"; + ParsingContext[ParsingContext["HeritageClauseElement"] = 7] = "HeritageClauseElement"; + ParsingContext[ParsingContext["VariableDeclarations"] = 8] = "VariableDeclarations"; + ParsingContext[ParsingContext["ObjectBindingElements"] = 9] = "ObjectBindingElements"; + ParsingContext[ParsingContext["ArrayBindingElements"] = 10] = "ArrayBindingElements"; + ParsingContext[ParsingContext["ArgumentExpressions"] = 11] = "ArgumentExpressions"; + ParsingContext[ParsingContext["ObjectLiteralMembers"] = 12] = "ObjectLiteralMembers"; + ParsingContext[ParsingContext["JsxAttributes"] = 13] = "JsxAttributes"; + ParsingContext[ParsingContext["JsxChildren"] = 14] = "JsxChildren"; + ParsingContext[ParsingContext["ArrayLiteralMembers"] = 15] = "ArrayLiteralMembers"; + ParsingContext[ParsingContext["Parameters"] = 16] = "Parameters"; + ParsingContext[ParsingContext["JSDocParameters"] = 17] = "JSDocParameters"; + ParsingContext[ParsingContext["RestProperties"] = 18] = "RestProperties"; + ParsingContext[ParsingContext["TypeParameters"] = 19] = "TypeParameters"; + ParsingContext[ParsingContext["TypeArguments"] = 20] = "TypeArguments"; + ParsingContext[ParsingContext["TupleElementTypes"] = 21] = "TupleElementTypes"; + ParsingContext[ParsingContext["HeritageClauses"] = 22] = "HeritageClauses"; + ParsingContext[ParsingContext["ImportOrExportSpecifiers"] = 23] = "ImportOrExportSpecifiers"; + ParsingContext[ParsingContext["Count"] = 24] = "Count"; // Number of parsing contexts + })(ParsingContext || (ParsingContext = {})); + var Tristate; + (function (Tristate) { + Tristate[Tristate["False"] = 0] = "False"; + Tristate[Tristate["True"] = 1] = "True"; + Tristate[Tristate["Unknown"] = 2] = "Unknown"; + })(Tristate || (Tristate = {})); + var JSDocParser; + (function (JSDocParser) { + function parseJSDocTypeExpressionForTests(content, start, length) { + initializeState(content, 6 /* Latest */, /*_syntaxCursor:*/ undefined, 1 /* JS */); + sourceFile = createSourceFile("file.js", 6 /* Latest */, 1 /* JS */, /*isDeclarationFile*/ false); + scanner.setText(content, start, length); + currentToken = scanner.scan(); + var jsDocTypeExpression = parseJSDocTypeExpression(); + var diagnostics = parseDiagnostics; + clearState(); + return jsDocTypeExpression ? { jsDocTypeExpression: jsDocTypeExpression, diagnostics: diagnostics } : undefined; + } + JSDocParser.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests; + // Parses out a JSDoc type expression. + function parseJSDocTypeExpression(mayOmitBraces) { + var result = createNode(283 /* JSDocTypeExpression */); + var hasBrace = (mayOmitBraces ? parseOptional : parseExpected)(18 /* OpenBraceToken */); + result.type = doInsideOfContext(2097152 /* JSDoc */, parseJSDocType); + if (!mayOmitBraces || hasBrace) { + parseExpected(19 /* CloseBraceToken */); + } + fixupParentReferences(result); + return finishNode(result); + } + JSDocParser.parseJSDocTypeExpression = parseJSDocTypeExpression; + function parseIsolatedJSDocComment(content, start, length) { + initializeState(content, 6 /* Latest */, /*_syntaxCursor:*/ undefined, 1 /* JS */); + sourceFile = { languageVariant: 0 /* Standard */, text: content }; // tslint:disable-line no-object-literal-type-assertion + var jsDoc = parseJSDocCommentWorker(start, length); + var diagnostics = parseDiagnostics; + clearState(); + return jsDoc ? { jsDoc: jsDoc, diagnostics: diagnostics } : undefined; + } + JSDocParser.parseIsolatedJSDocComment = parseIsolatedJSDocComment; + function parseJSDocComment(parent, start, length) { + var _a; + var saveToken = currentToken; + var saveParseDiagnosticsLength = parseDiagnostics.length; + var saveParseErrorBeforeNextFinishedNode = parseErrorBeforeNextFinishedNode; + var comment = parseJSDocCommentWorker(start, length); + if (comment) { + comment.parent = parent; + } + if (contextFlags & 65536 /* JavaScriptFile */) { + if (!sourceFile.jsDocDiagnostics) { + sourceFile.jsDocDiagnostics = []; + } + (_a = sourceFile.jsDocDiagnostics).push.apply(_a, parseDiagnostics); + } + currentToken = saveToken; + parseDiagnostics.length = saveParseDiagnosticsLength; + parseErrorBeforeNextFinishedNode = saveParseErrorBeforeNextFinishedNode; + return comment; + } + JSDocParser.parseJSDocComment = parseJSDocComment; + var JSDocState; + (function (JSDocState) { + JSDocState[JSDocState["BeginningOfLine"] = 0] = "BeginningOfLine"; + JSDocState[JSDocState["SawAsterisk"] = 1] = "SawAsterisk"; + JSDocState[JSDocState["SavingComments"] = 2] = "SavingComments"; + })(JSDocState || (JSDocState = {})); + var PropertyLikeParse; + (function (PropertyLikeParse) { + PropertyLikeParse[PropertyLikeParse["Property"] = 1] = "Property"; + PropertyLikeParse[PropertyLikeParse["Parameter"] = 2] = "Parameter"; + PropertyLikeParse[PropertyLikeParse["CallbackParameter"] = 4] = "CallbackParameter"; + })(PropertyLikeParse || (PropertyLikeParse = {})); + function parseJSDocCommentWorker(start, length) { + if (start === void 0) { start = 0; } + var content = sourceText; + var end = length === undefined ? content.length : start + length; + length = end - start; + ts.Debug.assert(start >= 0); + ts.Debug.assert(start <= end); + ts.Debug.assert(end <= content.length); + // Check for /** (JSDoc opening part) + if (!isJSDocLikeText(content, start)) { + return undefined; + } + var tags; + var tagsPos; + var tagsEnd; + var comments = []; + // + 3 for leading /**, - 5 in total for /** */ + return scanner.scanRange(start + 3, length - 5, function () { + // Initially we can parse out a tag. We also have seen a starting asterisk. + // This is so that /** * @type */ doesn't parse. + var state = 1 /* SawAsterisk */; + var margin; + // + 4 for leading '/** ' + var indent = start - Math.max(content.lastIndexOf("\n", start), 0) + 4; + function pushComment(text) { + if (!margin) { + margin = indent; + } + comments.push(text); + indent += text.length; + } + nextJSDocToken(); + while (parseOptionalJsdoc(5 /* WhitespaceTrivia */)) + ; + if (parseOptionalJsdoc(4 /* NewLineTrivia */)) { + state = 0 /* BeginningOfLine */; + indent = 0; + } + loop: while (true) { + switch (token()) { + case 58 /* AtToken */: + if (state === 0 /* BeginningOfLine */ || state === 1 /* SawAsterisk */) { + removeTrailingWhitespace(comments); + addTag(parseTag(indent)); + // NOTE: According to usejsdoc.org, a tag goes to end of line, except the last tag. + // Real-world comments may break this rule, so "BeginningOfLine" will not be a real line beginning + // for malformed examples like `/** @param {string} x @returns {number} the length */` + state = 0 /* BeginningOfLine */; + margin = undefined; + indent++; + } + else { + pushComment(scanner.getTokenText()); + } + break; + case 4 /* NewLineTrivia */: + comments.push(scanner.getTokenText()); + state = 0 /* BeginningOfLine */; + indent = 0; + break; + case 40 /* AsteriskToken */: + var asterisk = scanner.getTokenText(); + if (state === 1 /* SawAsterisk */ || state === 2 /* SavingComments */) { + // If we've already seen an asterisk, then we can no longer parse a tag on this line + state = 2 /* SavingComments */; + pushComment(asterisk); + } + else { + // Ignore the first asterisk on a line + state = 1 /* SawAsterisk */; + indent += asterisk.length; + } + break; + case 5 /* WhitespaceTrivia */: + // only collect whitespace if we're already saving comments or have just crossed the comment indent margin + var whitespace = scanner.getTokenText(); + if (state === 2 /* SavingComments */) { + comments.push(whitespace); + } + else if (margin !== undefined && indent + whitespace.length > margin) { + comments.push(whitespace.slice(margin - indent - 1)); + } + indent += whitespace.length; + break; + case 1 /* EndOfFileToken */: + break loop; + default: + // Anything else is doc comment text. We just save it. Because it + // wasn't a tag, we can no longer parse a tag on this line until we hit the next + // line break. + state = 2 /* SavingComments */; + pushComment(scanner.getTokenText()); + break; + } + nextJSDocToken(); + } + removeLeadingNewlines(comments); + removeTrailingWhitespace(comments); + return createJSDocComment(); + }); + function removeLeadingNewlines(comments) { + while (comments.length && (comments[0] === "\n" || comments[0] === "\r")) { + comments.shift(); + } + } + function removeTrailingWhitespace(comments) { + while (comments.length && comments[comments.length - 1].trim() === "") { + comments.pop(); + } + } + function createJSDocComment() { + var result = createNode(291 /* JSDocComment */, start); + result.tags = tags && createNodeArray(tags, tagsPos, tagsEnd); + result.comment = comments.length ? comments.join("") : undefined; + return finishNode(result, end); + } + function isNextNonwhitespaceTokenEndOfFile() { + // We must use infinite lookahead, as there could be any number of newlines :( + while (true) { + nextJSDocToken(); + if (token() === 1 /* EndOfFileToken */) { + return true; + } + if (!(token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */)) { + return false; + } + } + } + function skipWhitespace() { + if (token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) { + if (lookAhead(isNextNonwhitespaceTokenEndOfFile)) { + return; // Don't skip whitespace prior to EoF (or end of comment) - that shouldn't be included in any node's range + } + } + while (token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) { + nextJSDocToken(); + } + } + function skipWhitespaceOrAsterisk() { + if (token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) { + if (lookAhead(isNextNonwhitespaceTokenEndOfFile)) { + return; // Don't skip whitespace prior to EoF (or end of comment) - that shouldn't be included in any node's range + } + } + var precedingLineBreak = scanner.hasPrecedingLineBreak(); + while ((precedingLineBreak && token() === 40 /* AsteriskToken */) || token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) { + if (token() === 4 /* NewLineTrivia */) { + precedingLineBreak = true; + } + else if (token() === 40 /* AsteriskToken */) { + precedingLineBreak = false; + } + nextJSDocToken(); + } + } + function parseTag(indent) { + ts.Debug.assert(token() === 58 /* AtToken */); + var start = scanner.getTokenPos(); + nextJSDocToken(); + var tagName = parseJSDocIdentifierName(/*message*/ undefined); + skipWhitespaceOrAsterisk(); + var tag; + switch (tagName.escapedText) { + case "augments": + case "extends": + tag = parseAugmentsTag(start, tagName); + break; + case "class": + case "constructor": + tag = parseClassTag(start, tagName); + break; + case "this": + tag = parseThisTag(start, tagName); + break; + case "enum": + tag = parseEnumTag(start, tagName); + break; + case "arg": + case "argument": + case "param": + return parseParameterOrPropertyTag(start, tagName, 2 /* Parameter */, indent); + case "return": + case "returns": + tag = parseReturnTag(start, tagName); + break; + case "template": + tag = parseTemplateTag(start, tagName); + break; + case "type": + tag = parseTypeTag(start, tagName); + break; + case "typedef": + tag = parseTypedefTag(start, tagName, indent); + break; + case "callback": + tag = parseCallbackTag(start, tagName, indent); + break; + default: + tag = parseUnknownTag(start, tagName); + break; + } + if (!tag.comment) { + // some tags, like typedef and callback, have already parsed their comments earlier + tag.comment = parseTagComments(indent + tag.end - tag.pos); + } + return tag; + } + function parseTagComments(indent) { + var comments = []; + var state = 0 /* BeginningOfLine */; + var margin; + function pushComment(text) { + if (!margin) { + margin = indent; + } + comments.push(text); + indent += text.length; + } + var tok = token(); + loop: while (true) { + switch (tok) { + case 4 /* NewLineTrivia */: + if (state >= 1 /* SawAsterisk */) { + state = 0 /* BeginningOfLine */; + comments.push(scanner.getTokenText()); + } + indent = 0; + break; + case 58 /* AtToken */: + scanner.setTextPos(scanner.getTextPos() - 1); + // falls through + case 1 /* EndOfFileToken */: + // Done + break loop; + case 5 /* WhitespaceTrivia */: + if (state === 2 /* SavingComments */) { + pushComment(scanner.getTokenText()); + } + else { + var whitespace = scanner.getTokenText(); + // if the whitespace crosses the margin, take only the whitespace that passes the margin + if (margin !== undefined && indent + whitespace.length > margin) { + comments.push(whitespace.slice(margin - indent - 1)); + } + indent += whitespace.length; + } + break; + case 18 /* OpenBraceToken */: + state = 2 /* SavingComments */; + if (lookAhead(function () { return nextJSDocToken() === 58 /* AtToken */ && ts.tokenIsIdentifierOrKeyword(nextJSDocToken()) && scanner.getTokenText() === "link"; })) { + pushComment(scanner.getTokenText()); + nextJSDocToken(); + pushComment(scanner.getTokenText()); + nextJSDocToken(); + } + pushComment(scanner.getTokenText()); + break; + case 40 /* AsteriskToken */: + if (state === 0 /* BeginningOfLine */) { + // leading asterisks start recording on the *next* (non-whitespace) token + state = 1 /* SawAsterisk */; + indent += 1; + break; + } + // record the * as a comment + // falls through + default: + state = 2 /* SavingComments */; // leading identifiers start recording as well + pushComment(scanner.getTokenText()); + break; + } + tok = nextJSDocToken(); + } + removeLeadingNewlines(comments); + removeTrailingWhitespace(comments); + return comments.length === 0 ? undefined : comments.join(""); + } + function parseUnknownTag(start, tagName) { + var result = createNode(294 /* JSDocTag */, start); + result.tagName = tagName; + return finishNode(result); + } + function addTag(tag) { + if (!tag) { + return; + } + if (!tags) { + tags = [tag]; + tagsPos = tag.pos; + } + else { + tags.push(tag); + } + tagsEnd = tag.end; + } + function tryParseTypeExpression() { + skipWhitespaceOrAsterisk(); + return token() === 18 /* OpenBraceToken */ ? parseJSDocTypeExpression() : undefined; + } + function parseBracketNameInPropertyAndParamTag() { + if (token() === 14 /* NoSubstitutionTemplateLiteral */) { + // a markdown-quoted name: `arg` is not legal jsdoc, but occurs in the wild + return { name: createIdentifier(/*isIdentifier*/ true), isBracketed: false }; + } + // Looking for something like '[foo]', 'foo', '[foo.bar]' or 'foo.bar' + var isBracketed = parseOptional(22 /* OpenBracketToken */); + var name = parseJSDocEntityName(); + if (isBracketed) { + skipWhitespace(); + // May have an optional default, e.g. '[foo = 42]' + if (parseOptionalToken(59 /* EqualsToken */)) { + parseExpression(); + } + parseExpected(23 /* CloseBracketToken */); + } + return { name: name, isBracketed: isBracketed }; + } + function isObjectOrObjectArrayTypeReference(node) { + switch (node.kind) { + case 136 /* ObjectKeyword */: + return true; + case 169 /* ArrayType */: + return isObjectOrObjectArrayTypeReference(node.elementType); + default: + return ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) && node.typeName.escapedText === "Object"; + } + } + function parseParameterOrPropertyTag(start, tagName, target, indent) { + var typeExpression = tryParseTypeExpression(); + var isNameFirst = !typeExpression; + skipWhitespaceOrAsterisk(); + var _a = parseBracketNameInPropertyAndParamTag(), name = _a.name, isBracketed = _a.isBracketed; + skipWhitespace(); + if (isNameFirst) { + typeExpression = tryParseTypeExpression(); + } + var result = target === 1 /* Property */ ? + createNode(305 /* JSDocPropertyTag */, start) : + createNode(299 /* JSDocParameterTag */, start); + var comment = parseTagComments(indent + scanner.getStartPos() - start); + var nestedTypeLiteral = target !== 4 /* CallbackParameter */ && parseNestedTypeLiteral(typeExpression, name, target, indent); + if (nestedTypeLiteral) { + typeExpression = nestedTypeLiteral; + isNameFirst = true; + } + result.tagName = tagName; + result.typeExpression = typeExpression; + result.name = name; + result.isNameFirst = isNameFirst; + result.isBracketed = isBracketed; + result.comment = comment; + return finishNode(result); + } + function parseNestedTypeLiteral(typeExpression, name, target, indent) { + if (typeExpression && isObjectOrObjectArrayTypeReference(typeExpression.type)) { + var typeLiteralExpression = createNode(283 /* JSDocTypeExpression */, scanner.getTokenPos()); + var child = void 0; + var jsdocTypeLiteral = void 0; + var start_2 = scanner.getStartPos(); + var children = void 0; + while (child = tryParse(function () { return parseChildParameterOrPropertyTag(target, indent, name); })) { + if (child.kind === 299 /* JSDocParameterTag */ || child.kind === 305 /* JSDocPropertyTag */) { + children = ts.append(children, child); + } + } + if (children) { + jsdocTypeLiteral = createNode(292 /* JSDocTypeLiteral */, start_2); + jsdocTypeLiteral.jsDocPropertyTags = children; + if (typeExpression.type.kind === 169 /* ArrayType */) { + jsdocTypeLiteral.isArrayType = true; + } + typeLiteralExpression.type = finishNode(jsdocTypeLiteral); + return finishNode(typeLiteralExpression); + } + } + } + function parseReturnTag(start, tagName) { + if (ts.forEach(tags, function (t) { return t.kind === 300 /* JSDocReturnTag */; })) { + parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText); + } + var result = createNode(300 /* JSDocReturnTag */, start); + result.tagName = tagName; + result.typeExpression = tryParseTypeExpression(); + return finishNode(result); + } + function parseTypeTag(start, tagName) { + if (ts.forEach(tags, function (t) { return t.kind === 302 /* JSDocTypeTag */; })) { + parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText); + } + var result = createNode(302 /* JSDocTypeTag */, start); + result.tagName = tagName; + result.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true); + return finishNode(result); + } + function parseAugmentsTag(start, tagName) { + var result = createNode(295 /* JSDocAugmentsTag */, start); + result.tagName = tagName; + result.class = parseExpressionWithTypeArgumentsForAugments(); + return finishNode(result); + } + function parseExpressionWithTypeArgumentsForAugments() { + var usedBrace = parseOptional(18 /* OpenBraceToken */); + var node = createNode(211 /* ExpressionWithTypeArguments */); + node.expression = parsePropertyAccessEntityNameExpression(); + node.typeArguments = tryParseTypeArguments(); + var res = finishNode(node); + if (usedBrace) { + parseExpected(19 /* CloseBraceToken */); + } + return res; + } + function parsePropertyAccessEntityNameExpression() { + var node = parseJSDocIdentifierName(); + while (parseOptional(24 /* DotToken */)) { + var prop = createNode(189 /* PropertyAccessExpression */, node.pos); + prop.expression = node; + prop.name = parseJSDocIdentifierName(); + node = finishNode(prop); + } + return node; + } + function parseClassTag(start, tagName) { + var tag = createNode(296 /* JSDocClassTag */, start); + tag.tagName = tagName; + return finishNode(tag); + } + function parseThisTag(start, tagName) { + var tag = createNode(301 /* JSDocThisTag */, start); + tag.tagName = tagName; + tag.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true); + skipWhitespace(); + return finishNode(tag); + } + function parseEnumTag(start, tagName) { + var tag = createNode(298 /* JSDocEnumTag */, start); + tag.tagName = tagName; + tag.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true); + skipWhitespace(); + return finishNode(tag); + } + function parseTypedefTag(start, tagName, indent) { + var typeExpression = tryParseTypeExpression(); + skipWhitespaceOrAsterisk(); + var typedefTag = createNode(304 /* JSDocTypedefTag */, start); + typedefTag.tagName = tagName; + typedefTag.fullName = parseJSDocTypeNameWithNamespace(); + typedefTag.name = getJSDocTypeAliasName(typedefTag.fullName); + skipWhitespace(); + typedefTag.comment = parseTagComments(indent); + typedefTag.typeExpression = typeExpression; + var end; + if (!typeExpression || isObjectOrObjectArrayTypeReference(typeExpression.type)) { + var child = void 0; + var jsdocTypeLiteral = void 0; + var childTypeTag = void 0; + while (child = tryParse(function () { return parseChildPropertyTag(indent); })) { + if (!jsdocTypeLiteral) { + jsdocTypeLiteral = createNode(292 /* JSDocTypeLiteral */, start); + } + if (child.kind === 302 /* JSDocTypeTag */) { + if (childTypeTag) { + break; + } + else { + childTypeTag = child; + } + } + else { + jsdocTypeLiteral.jsDocPropertyTags = ts.append(jsdocTypeLiteral.jsDocPropertyTags, child); + } + } + if (jsdocTypeLiteral) { + if (typeExpression && typeExpression.type.kind === 169 /* ArrayType */) { + jsdocTypeLiteral.isArrayType = true; + } + typedefTag.typeExpression = childTypeTag && childTypeTag.typeExpression && !isObjectOrObjectArrayTypeReference(childTypeTag.typeExpression.type) ? + childTypeTag.typeExpression : + finishNode(jsdocTypeLiteral); + end = typedefTag.typeExpression.end; + } + } + // Only include the characters between the name end and the next token if a comment was actually parsed out - otherwise it's just whitespace + return finishNode(typedefTag, end || typedefTag.comment !== undefined ? scanner.getStartPos() : (typedefTag.fullName || typedefTag.typeExpression || typedefTag.tagName).end); + } + function parseJSDocTypeNameWithNamespace(nested) { + var pos = scanner.getTokenPos(); + if (!ts.tokenIsIdentifierOrKeyword(token())) { + return undefined; + } + var typeNameOrNamespaceName = parseJSDocIdentifierName(); + if (parseOptional(24 /* DotToken */)) { + var jsDocNamespaceNode = createNode(244 /* ModuleDeclaration */, pos); + if (nested) { + jsDocNamespaceNode.flags |= 4 /* NestedNamespace */; + } + jsDocNamespaceNode.name = typeNameOrNamespaceName; + jsDocNamespaceNode.body = parseJSDocTypeNameWithNamespace(/*nested*/ true); + return finishNode(jsDocNamespaceNode); + } + if (nested) { + typeNameOrNamespaceName.isInJSDocNamespace = true; + } + return typeNameOrNamespaceName; + } + function parseCallbackTag(start, tagName, indent) { + var callbackTag = createNode(297 /* JSDocCallbackTag */, start); + callbackTag.tagName = tagName; + callbackTag.fullName = parseJSDocTypeNameWithNamespace(); + callbackTag.name = getJSDocTypeAliasName(callbackTag.fullName); + skipWhitespace(); + callbackTag.comment = parseTagComments(indent); + var child; + var jsdocSignature = createNode(293 /* JSDocSignature */, start); + jsdocSignature.parameters = []; + while (child = tryParse(function () { return parseChildParameterOrPropertyTag(4 /* CallbackParameter */, indent); })) { + jsdocSignature.parameters = ts.append(jsdocSignature.parameters, child); + } + var returnTag = tryParse(function () { + if (parseOptionalJsdoc(58 /* AtToken */)) { + var tag = parseTag(indent); + if (tag && tag.kind === 300 /* JSDocReturnTag */) { + return tag; + } + } + }); + if (returnTag) { + jsdocSignature.type = returnTag; + } + callbackTag.typeExpression = finishNode(jsdocSignature); + return finishNode(callbackTag); + } + function getJSDocTypeAliasName(fullName) { + if (fullName) { + var rightNode = fullName; + while (true) { + if (ts.isIdentifier(rightNode) || !rightNode.body) { + return ts.isIdentifier(rightNode) ? rightNode : rightNode.name; + } + rightNode = rightNode.body; + } + } + } + function escapedTextsEqual(a, b) { + while (!ts.isIdentifier(a) || !ts.isIdentifier(b)) { + if (!ts.isIdentifier(a) && !ts.isIdentifier(b) && a.right.escapedText === b.right.escapedText) { + a = a.left; + b = b.left; + } + else { + return false; + } + } + return a.escapedText === b.escapedText; + } + function parseChildPropertyTag(indent) { + return parseChildParameterOrPropertyTag(1 /* Property */, indent); + } + function parseChildParameterOrPropertyTag(target, indent, name) { + var canParseTag = true; + var seenAsterisk = false; + while (true) { + switch (nextJSDocToken()) { + case 58 /* AtToken */: + if (canParseTag) { + var child = tryParseChildTag(target, indent); + if (child && (child.kind === 299 /* JSDocParameterTag */ || child.kind === 305 /* JSDocPropertyTag */) && + target !== 4 /* CallbackParameter */ && + name && (ts.isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) { + return false; + } + return child; + } + seenAsterisk = false; + break; + case 4 /* NewLineTrivia */: + canParseTag = true; + seenAsterisk = false; + break; + case 40 /* AsteriskToken */: + if (seenAsterisk) { + canParseTag = false; + } + seenAsterisk = true; + break; + case 72 /* Identifier */: + canParseTag = false; + break; + case 1 /* EndOfFileToken */: + return false; + } + } + } + function tryParseChildTag(target, indent) { + ts.Debug.assert(token() === 58 /* AtToken */); + var start = scanner.getStartPos(); + nextJSDocToken(); + var tagName = parseJSDocIdentifierName(); + skipWhitespace(); + var t; + switch (tagName.escapedText) { + case "type": + return target === 1 /* Property */ && parseTypeTag(start, tagName); + case "prop": + case "property": + t = 1 /* Property */; + break; + case "arg": + case "argument": + case "param": + t = 2 /* Parameter */ | 4 /* CallbackParameter */; + break; + default: + return false; + } + if (!(target & t)) { + return false; + } + return parseParameterOrPropertyTag(start, tagName, target, indent); + } + function parseTemplateTag(start, tagName) { + // the template tag looks like '@template {Constraint} T,U,V' + var constraint; + if (token() === 18 /* OpenBraceToken */) { + constraint = parseJSDocTypeExpression(); + } + var typeParameters = []; + var typeParametersPos = getNodePos(); + do { + skipWhitespace(); + var typeParameter = createNode(150 /* TypeParameter */); + typeParameter.name = parseJSDocIdentifierName(ts.Diagnostics.Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces); + finishNode(typeParameter); + skipWhitespace(); + typeParameters.push(typeParameter); + } while (parseOptionalJsdoc(27 /* CommaToken */)); + var result = createNode(303 /* JSDocTemplateTag */, start); + result.tagName = tagName; + result.constraint = constraint; + result.typeParameters = createNodeArray(typeParameters, typeParametersPos); + finishNode(result); + return result; + } + function nextJSDocToken() { + return currentToken = scanner.scanJSDocToken(); + } + function parseOptionalJsdoc(t) { + if (token() === t) { + nextJSDocToken(); + return true; + } + return false; + } + function parseJSDocEntityName() { + var entity = parseJSDocIdentifierName(); + if (parseOptional(22 /* OpenBracketToken */)) { + parseExpected(23 /* CloseBracketToken */); + // Note that y[] is accepted as an entity name, but the postfix brackets are not saved for checking. + // Technically usejsdoc.org requires them for specifying a property of a type equivalent to Array<{ x: ...}> + // but it's not worth it to enforce that restriction. + } + while (parseOptional(24 /* DotToken */)) { + var name = parseJSDocIdentifierName(); + if (parseOptional(22 /* OpenBracketToken */)) { + parseExpected(23 /* CloseBracketToken */); + } + entity = createQualifiedName(entity, name); + } + return entity; + } + function parseJSDocIdentifierName(message) { + if (!ts.tokenIsIdentifierOrKeyword(token())) { + return createMissingNode(72 /* Identifier */, /*reportAtCurrentPosition*/ !message, message || ts.Diagnostics.Identifier_expected); + } + var pos = scanner.getTokenPos(); + var end = scanner.getTextPos(); + var result = createNode(72 /* Identifier */, pos); + result.escapedText = ts.escapeLeadingUnderscores(scanner.getTokenText()); + finishNode(result, end); + nextJSDocToken(); + return result; + } + } + JSDocParser.parseJSDocCommentWorker = parseJSDocCommentWorker; + })(JSDocParser = Parser.JSDocParser || (Parser.JSDocParser = {})); + })(Parser || (Parser = {})); + var IncrementalParser; + (function (IncrementalParser) { + function updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks) { + aggressiveChecks = aggressiveChecks || ts.Debug.shouldAssert(2 /* Aggressive */); + checkChangeRange(sourceFile, newText, textChangeRange, aggressiveChecks); + if (ts.textChangeRangeIsUnchanged(textChangeRange)) { + // if the text didn't change, then we can just return our current source file as-is. + return sourceFile; + } + if (sourceFile.statements.length === 0) { + // If we don't have any statements in the current source file, then there's no real + // way to incrementally parse. So just do a full parse instead. + return Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, /*syntaxCursor*/ undefined, /*setParentNodes*/ true, sourceFile.scriptKind); + } + // Make sure we're not trying to incrementally update a source file more than once. Once + // we do an update the original source file is considered unusable from that point onwards. + // + // This is because we do incremental parsing in-place. i.e. we take nodes from the old + // tree and give them new positions and parents. From that point on, trusting the old + // tree at all is not possible as far too much of it may violate invariants. + var incrementalSourceFile = sourceFile; + ts.Debug.assert(!incrementalSourceFile.hasBeenIncrementallyParsed); + incrementalSourceFile.hasBeenIncrementallyParsed = true; + var oldText = sourceFile.text; + var syntaxCursor = createSyntaxCursor(sourceFile); + // Make the actual change larger so that we know to reparse anything whose lookahead + // might have intersected the change. + var changeRange = extendToAffectedRange(sourceFile, textChangeRange); + checkChangeRange(sourceFile, newText, changeRange, aggressiveChecks); + // Ensure that extending the affected range only moved the start of the change range + // earlier in the file. + ts.Debug.assert(changeRange.span.start <= textChangeRange.span.start); + ts.Debug.assert(ts.textSpanEnd(changeRange.span) === ts.textSpanEnd(textChangeRange.span)); + ts.Debug.assert(ts.textSpanEnd(ts.textChangeRangeNewSpan(changeRange)) === ts.textSpanEnd(ts.textChangeRangeNewSpan(textChangeRange))); + // The is the amount the nodes after the edit range need to be adjusted. It can be + // positive (if the edit added characters), negative (if the edit deleted characters) + // or zero (if this was a pure overwrite with nothing added/removed). + var delta = ts.textChangeRangeNewSpan(changeRange).length - changeRange.span.length; + // If we added or removed characters during the edit, then we need to go and adjust all + // the nodes after the edit. Those nodes may move forward (if we inserted chars) or they + // may move backward (if we deleted chars). + // + // Doing this helps us out in two ways. First, it means that any nodes/tokens we want + // to reuse are already at the appropriate position in the new text. That way when we + // reuse them, we don't have to figure out if they need to be adjusted. Second, it makes + // it very easy to determine if we can reuse a node. If the node's position is at where + // we are in the text, then we can reuse it. Otherwise we can't. If the node's position + // is ahead of us, then we'll need to rescan tokens. If the node's position is behind + // us, then we'll need to skip it or crumble it as appropriate + // + // We will also adjust the positions of nodes that intersect the change range as well. + // By doing this, we ensure that all the positions in the old tree are consistent, not + // just the positions of nodes entirely before/after the change range. By being + // consistent, we can then easily map from positions to nodes in the old tree easily. + // + // Also, mark any syntax elements that intersect the changed span. We know, up front, + // that we cannot reuse these elements. + updateTokenPositionsAndMarkElements(incrementalSourceFile, changeRange.span.start, ts.textSpanEnd(changeRange.span), ts.textSpanEnd(ts.textChangeRangeNewSpan(changeRange)), delta, oldText, newText, aggressiveChecks); + // Now that we've set up our internal incremental state just proceed and parse the + // source file in the normal fashion. When possible the parser will retrieve and + // reuse nodes from the old tree. + // + // Note: passing in 'true' for setNodeParents is very important. When incrementally + // parsing, we will be reusing nodes from the old tree, and placing it into new + // parents. If we don't set the parents now, we'll end up with an observably + // inconsistent tree. Setting the parents on the new tree should be very fast. We + // will immediately bail out of walking any subtrees when we can see that their parents + // are already correct. + var result = Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, syntaxCursor, /*setParentNodes*/ true, sourceFile.scriptKind); + return result; + } + IncrementalParser.updateSourceFile = updateSourceFile; + function moveElementEntirelyPastChangeRange(element, isArray, delta, oldText, newText, aggressiveChecks) { + if (isArray) { + visitArray(element); + } + else { + visitNode(element); + } + return; + function visitNode(node) { + var text = ""; + if (aggressiveChecks && shouldCheckNode(node)) { + text = oldText.substring(node.pos, node.end); + } + // Ditch any existing LS children we may have created. This way we can avoid + // moving them forward. + if (node._children) { + node._children = undefined; + } + node.pos += delta; + node.end += delta; + if (aggressiveChecks && shouldCheckNode(node)) { + ts.Debug.assert(text === newText.substring(node.pos, node.end)); + } + forEachChild(node, visitNode, visitArray); + if (ts.hasJSDocNodes(node)) { + for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { + var jsDocComment = _a[_i]; + visitNode(jsDocComment); + } + } + checkNodePositions(node, aggressiveChecks); + } + function visitArray(array) { + array._children = undefined; + array.pos += delta; + array.end += delta; + for (var _i = 0, array_8 = array; _i < array_8.length; _i++) { + var node = array_8[_i]; + visitNode(node); + } + } + } + function shouldCheckNode(node) { + switch (node.kind) { + case 10 /* StringLiteral */: + case 8 /* NumericLiteral */: + case 72 /* Identifier */: + return true; + } + return false; + } + function adjustIntersectingElement(element, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta) { + ts.Debug.assert(element.end >= changeStart, "Adjusting an element that was entirely before the change range"); + ts.Debug.assert(element.pos <= changeRangeOldEnd, "Adjusting an element that was entirely after the change range"); + ts.Debug.assert(element.pos <= element.end); + // We have an element that intersects the change range in some way. It may have its + // start, or its end (or both) in the changed range. We want to adjust any part + // that intersects such that the final tree is in a consistent state. i.e. all + // children have spans within the span of their parent, and all siblings are ordered + // properly. + // We may need to update both the 'pos' and the 'end' of the element. + // If the 'pos' is before the start of the change, then we don't need to touch it. + // If it isn't, then the 'pos' must be inside the change. How we update it will + // depend if delta is positive or negative. If delta is positive then we have + // something like: + // + // -------------------AAA----------------- + // -------------------BBBCCCCCCC----------------- + // + // In this case, we consider any node that started in the change range to still be + // starting at the same position. + // + // however, if the delta is negative, then we instead have something like this: + // + // -------------------XXXYYYYYYY----------------- + // -------------------ZZZ----------------- + // + // In this case, any element that started in the 'X' range will keep its position. + // However any element that started after that will have their pos adjusted to be + // at the end of the new range. i.e. any node that started in the 'Y' range will + // be adjusted to have their start at the end of the 'Z' range. + // + // The element will keep its position if possible. Or Move backward to the new-end + // if it's in the 'Y' range. + element.pos = Math.min(element.pos, changeRangeNewEnd); + // If the 'end' is after the change range, then we always adjust it by the delta + // amount. However, if the end is in the change range, then how we adjust it + // will depend on if delta is positive or negative. If delta is positive then we + // have something like: + // + // -------------------AAA----------------- + // -------------------BBBCCCCCCC----------------- + // + // In this case, we consider any node that ended inside the change range to keep its + // end position. + // + // however, if the delta is negative, then we instead have something like this: + // + // -------------------XXXYYYYYYY----------------- + // -------------------ZZZ----------------- + // + // In this case, any element that ended in the 'X' range will keep its position. + // However any element that ended after that will have their pos adjusted to be + // at the end of the new range. i.e. any node that ended in the 'Y' range will + // be adjusted to have their end at the end of the 'Z' range. + if (element.end >= changeRangeOldEnd) { + // Element ends after the change range. Always adjust the end pos. + element.end += delta; + } + else { + // Element ends in the change range. The element will keep its position if + // possible. Or Move backward to the new-end if it's in the 'Y' range. + element.end = Math.min(element.end, changeRangeNewEnd); + } + ts.Debug.assert(element.pos <= element.end); + if (element.parent) { + ts.Debug.assert(element.pos >= element.parent.pos); + ts.Debug.assert(element.end <= element.parent.end); + } + } + function checkNodePositions(node, aggressiveChecks) { + if (aggressiveChecks) { + var pos_2 = node.pos; + var visitNode_1 = function (child) { + ts.Debug.assert(child.pos >= pos_2); + pos_2 = child.end; + }; + if (ts.hasJSDocNodes(node)) { + for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { + var jsDocComment = _a[_i]; + visitNode_1(jsDocComment); + } + } + forEachChild(node, visitNode_1); + ts.Debug.assert(pos_2 <= node.end); + } + } + function updateTokenPositionsAndMarkElements(sourceFile, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta, oldText, newText, aggressiveChecks) { + visitNode(sourceFile); + return; + function visitNode(child) { + ts.Debug.assert(child.pos <= child.end); + if (child.pos > changeRangeOldEnd) { + // Node is entirely past the change range. We need to move both its pos and + // end, forward or backward appropriately. + moveElementEntirelyPastChangeRange(child, /*isArray*/ false, delta, oldText, newText, aggressiveChecks); + return; + } + // Check if the element intersects the change range. If it does, then it is not + // reusable. Also, we'll need to recurse to see what constituent portions we may + // be able to use. + var fullEnd = child.end; + if (fullEnd >= changeStart) { + child.intersectsChange = true; + child._children = undefined; + // Adjust the pos or end (or both) of the intersecting element accordingly. + adjustIntersectingElement(child, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta); + forEachChild(child, visitNode, visitArray); + if (ts.hasJSDocNodes(child)) { + for (var _i = 0, _a = child.jsDoc; _i < _a.length; _i++) { + var jsDocComment = _a[_i]; + visitNode(jsDocComment); + } + } + checkNodePositions(child, aggressiveChecks); + return; + } + // Otherwise, the node is entirely before the change range. No need to do anything with it. + ts.Debug.assert(fullEnd < changeStart); + } + function visitArray(array) { + ts.Debug.assert(array.pos <= array.end); + if (array.pos > changeRangeOldEnd) { + // Array is entirely after the change range. We need to move it, and move any of + // its children. + moveElementEntirelyPastChangeRange(array, /*isArray*/ true, delta, oldText, newText, aggressiveChecks); + return; + } + // Check if the element intersects the change range. If it does, then it is not + // reusable. Also, we'll need to recurse to see what constituent portions we may + // be able to use. + var fullEnd = array.end; + if (fullEnd >= changeStart) { + array.intersectsChange = true; + array._children = undefined; + // Adjust the pos or end (or both) of the intersecting array accordingly. + adjustIntersectingElement(array, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta); + for (var _i = 0, array_9 = array; _i < array_9.length; _i++) { + var node = array_9[_i]; + visitNode(node); + } + return; + } + // Otherwise, the array is entirely before the change range. No need to do anything with it. + ts.Debug.assert(fullEnd < changeStart); + } + } + function extendToAffectedRange(sourceFile, changeRange) { + // Consider the following code: + // void foo() { /; } + // + // If the text changes with an insertion of / just before the semicolon then we end up with: + // void foo() { //; } + // + // If we were to just use the changeRange a is, then we would not rescan the { token + // (as it does not intersect the actual original change range). Because an edit may + // change the token touching it, we actually need to look back *at least* one token so + // that the prior token sees that change. + var maxLookahead = 1; + var start = changeRange.span.start; + // the first iteration aligns us with the change start. subsequent iteration move us to + // the left by maxLookahead tokens. We only need to do this as long as we're not at the + // start of the tree. + for (var i = 0; start > 0 && i <= maxLookahead; i++) { + var nearestNode = findNearestNodeStartingBeforeOrAtPosition(sourceFile, start); + ts.Debug.assert(nearestNode.pos <= start); + var position = nearestNode.pos; + start = Math.max(0, position - 1); + } + var finalSpan = ts.createTextSpanFromBounds(start, ts.textSpanEnd(changeRange.span)); + var finalLength = changeRange.newLength + (changeRange.span.start - start); + return ts.createTextChangeRange(finalSpan, finalLength); + } + function findNearestNodeStartingBeforeOrAtPosition(sourceFile, position) { + var bestResult = sourceFile; + var lastNodeEntirelyBeforePosition; + forEachChild(sourceFile, visit); + if (lastNodeEntirelyBeforePosition) { + var lastChildOfLastEntireNodeBeforePosition = getLastDescendant(lastNodeEntirelyBeforePosition); + if (lastChildOfLastEntireNodeBeforePosition.pos > bestResult.pos) { + bestResult = lastChildOfLastEntireNodeBeforePosition; + } + } + return bestResult; + function getLastDescendant(node) { + while (true) { + var lastChild = ts.getLastChild(node); + if (lastChild) { + node = lastChild; + } + else { + return node; + } + } + } + function visit(child) { + if (ts.nodeIsMissing(child)) { + // Missing nodes are effectively invisible to us. We never even consider them + // When trying to find the nearest node before us. + return; + } + // If the child intersects this position, then this node is currently the nearest + // node that starts before the position. + if (child.pos <= position) { + if (child.pos >= bestResult.pos) { + // This node starts before the position, and is closer to the position than + // the previous best node we found. It is now the new best node. + bestResult = child; + } + // Now, the node may overlap the position, or it may end entirely before the + // position. If it overlaps with the position, then either it, or one of its + // children must be the nearest node before the position. So we can just + // recurse into this child to see if we can find something better. + if (position < child.end) { + // The nearest node is either this child, or one of the children inside + // of it. We've already marked this child as the best so far. Recurse + // in case one of the children is better. + forEachChild(child, visit); + // Once we look at the children of this node, then there's no need to + // continue any further. + return true; + } + else { + ts.Debug.assert(child.end <= position); + // The child ends entirely before this position. Say you have the following + // (where $ is the position) + // + // ? $ : <...> <...> + // + // We would want to find the nearest preceding node in "complex expr 2". + // To support that, we keep track of this node, and once we're done searching + // for a best node, we recurse down this node to see if we can find a good + // result in it. + // + // This approach allows us to quickly skip over nodes that are entirely + // before the position, while still allowing us to find any nodes in the + // last one that might be what we want. + lastNodeEntirelyBeforePosition = child; + } + } + else { + ts.Debug.assert(child.pos > position); + // We're now at a node that is entirely past the position we're searching for. + // This node (and all following nodes) could never contribute to the result, + // so just skip them by returning 'true' here. + return true; + } + } + } + function checkChangeRange(sourceFile, newText, textChangeRange, aggressiveChecks) { + var oldText = sourceFile.text; + if (textChangeRange) { + ts.Debug.assert((oldText.length - textChangeRange.span.length + textChangeRange.newLength) === newText.length); + if (aggressiveChecks || ts.Debug.shouldAssert(3 /* VeryAggressive */)) { + var oldTextPrefix = oldText.substr(0, textChangeRange.span.start); + var newTextPrefix = newText.substr(0, textChangeRange.span.start); + ts.Debug.assert(oldTextPrefix === newTextPrefix); + var oldTextSuffix = oldText.substring(ts.textSpanEnd(textChangeRange.span), oldText.length); + var newTextSuffix = newText.substring(ts.textSpanEnd(ts.textChangeRangeNewSpan(textChangeRange)), newText.length); + ts.Debug.assert(oldTextSuffix === newTextSuffix); + } + } + } + function createSyntaxCursor(sourceFile) { + var currentArray = sourceFile.statements; + var currentArrayIndex = 0; + ts.Debug.assert(currentArrayIndex < currentArray.length); + var current = currentArray[currentArrayIndex]; + var lastQueriedPosition = -1 /* Value */; + return { + currentNode: function (position) { + // Only compute the current node if the position is different than the last time + // we were asked. The parser commonly asks for the node at the same position + // twice. Once to know if can read an appropriate list element at a certain point, + // and then to actually read and consume the node. + if (position !== lastQueriedPosition) { + // Much of the time the parser will need the very next node in the array that + // we just returned a node from.So just simply check for that case and move + // forward in the array instead of searching for the node again. + if (current && current.end === position && currentArrayIndex < (currentArray.length - 1)) { + currentArrayIndex++; + current = currentArray[currentArrayIndex]; + } + // If we don't have a node, or the node we have isn't in the right position, + // then try to find a viable node at the position requested. + if (!current || current.pos !== position) { + findHighestListElementThatStartsAtPosition(position); + } + } + // Cache this query so that we don't do any extra work if the parser calls back + // into us. Note: this is very common as the parser will make pairs of calls like + // 'isListElement -> parseListElement'. If we were unable to find a node when + // called with 'isListElement', we don't want to redo the work when parseListElement + // is called immediately after. + lastQueriedPosition = position; + // Either we don'd have a node, or we have a node at the position being asked for. + ts.Debug.assert(!current || current.pos === position); + return current; + } + }; + // Finds the highest element in the tree we can find that starts at the provided position. + // The element must be a direct child of some node list in the tree. This way after we + // return it, we can easily return its next sibling in the list. + function findHighestListElementThatStartsAtPosition(position) { + // Clear out any cached state about the last node we found. + currentArray = undefined; + currentArrayIndex = -1 /* Value */; + current = undefined; + // Recurse into the source file to find the highest node at this position. + forEachChild(sourceFile, visitNode, visitArray); + return; + function visitNode(node) { + if (position >= node.pos && position < node.end) { + // Position was within this node. Keep searching deeper to find the node. + forEachChild(node, visitNode, visitArray); + // don't proceed any further in the search. + return true; + } + // position wasn't in this node, have to keep searching. + return false; + } + function visitArray(array) { + if (position >= array.pos && position < array.end) { + // position was in this array. Search through this array to see if we find a + // viable element. + for (var i = 0; i < array.length; i++) { + var child = array[i]; + if (child) { + if (child.pos === position) { + // Found the right node. We're done. + currentArray = array; + currentArrayIndex = i; + current = child; + return true; + } + else { + if (child.pos < position && position < child.end) { + // Position in somewhere within this child. Search in it and + // stop searching in this array. + forEachChild(child, visitNode, visitArray); + return true; + } + } + } + } + } + // position wasn't in this array, have to keep searching. + return false; + } + } + } + var InvalidPosition; + (function (InvalidPosition) { + InvalidPosition[InvalidPosition["Value"] = -1] = "Value"; + })(InvalidPosition || (InvalidPosition = {})); + })(IncrementalParser || (IncrementalParser = {})); + /** @internal */ + function isDeclarationFileName(fileName) { + return ts.fileExtensionIs(fileName, ".d.ts" /* Dts */); + } + ts.isDeclarationFileName = isDeclarationFileName; + /*@internal*/ + function processCommentPragmas(context, sourceText) { + var triviaScanner = ts.createScanner(context.languageVersion, /*skipTrivia*/ false, 0 /* Standard */, sourceText); + var pragmas = []; + // Keep scanning all the leading trivia in the file until we get to something that + // isn't trivia. Any single line comment will be analyzed to see if it is a + // reference comment. + while (true) { + var kind = triviaScanner.scan(); + if (!ts.isTrivia(kind)) { + break; + } + var range = { + kind: triviaScanner.getToken(), + pos: triviaScanner.getTokenPos(), + end: triviaScanner.getTextPos(), + }; + var comment = sourceText.substring(range.pos, range.end); + extractPragmas(pragmas, range, comment); + } + context.pragmas = ts.createMap(); + for (var _i = 0, pragmas_1 = pragmas; _i < pragmas_1.length; _i++) { + var pragma = pragmas_1[_i]; + if (context.pragmas.has(pragma.name)) { // TODO: GH#18217 + var currentValue = context.pragmas.get(pragma.name); + if (currentValue instanceof Array) { + currentValue.push(pragma.args); + } + else { + context.pragmas.set(pragma.name, [currentValue, pragma.args]); + } + continue; + } + context.pragmas.set(pragma.name, pragma.args); + } + } + ts.processCommentPragmas = processCommentPragmas; + /*@internal*/ + function processPragmasIntoFields(context, reportDiagnostic) { + context.checkJsDirective = undefined; + context.referencedFiles = []; + context.typeReferenceDirectives = []; + context.libReferenceDirectives = []; + context.amdDependencies = []; + context.hasNoDefaultLib = false; + context.pragmas.forEach(function (entryOrList, key) { + // TODO: The below should be strongly type-guarded and not need casts/explicit annotations, since entryOrList is related to + // key and key is constrained to a union; but it's not (see GH#21483 for at least partial fix) :( + switch (key) { + case "reference": { + var referencedFiles_1 = context.referencedFiles; + var typeReferenceDirectives_1 = context.typeReferenceDirectives; + var libReferenceDirectives_1 = context.libReferenceDirectives; + ts.forEach(ts.toArray(entryOrList), function (arg) { + // TODO: GH#18217 + if (arg.arguments["no-default-lib"]) { + context.hasNoDefaultLib = true; + } + else if (arg.arguments.types) { + typeReferenceDirectives_1.push({ pos: arg.arguments.types.pos, end: arg.arguments.types.end, fileName: arg.arguments.types.value }); + } + else if (arg.arguments.lib) { + libReferenceDirectives_1.push({ pos: arg.arguments.lib.pos, end: arg.arguments.lib.end, fileName: arg.arguments.lib.value }); + } + else if (arg.arguments.path) { + referencedFiles_1.push({ pos: arg.arguments.path.pos, end: arg.arguments.path.end, fileName: arg.arguments.path.value }); + } + else { + reportDiagnostic(arg.range.pos, arg.range.end - arg.range.pos, ts.Diagnostics.Invalid_reference_directive_syntax); + } + }); + break; + } + case "amd-dependency": { + context.amdDependencies = ts.map(ts.toArray(entryOrList), function (x) { return ({ name: x.arguments.name, path: x.arguments.path }); }); // TODO: GH#18217 + break; + } + case "amd-module": { + if (entryOrList instanceof Array) { + for (var _i = 0, entryOrList_1 = entryOrList; _i < entryOrList_1.length; _i++) { + var entry = entryOrList_1[_i]; + if (context.moduleName) { + // TODO: It's probably fine to issue this diagnostic on all instances of the pragma + reportDiagnostic(entry.range.pos, entry.range.end - entry.range.pos, ts.Diagnostics.An_AMD_module_cannot_have_multiple_name_assignments); + } + context.moduleName = entry.arguments.name; + } + } + else { + context.moduleName = entryOrList.arguments.name; + } + break; + } + case "ts-nocheck": + case "ts-check": { + // _last_ of either nocheck or check in a file is the "winner" + ts.forEach(ts.toArray(entryOrList), function (entry) { + if (!context.checkJsDirective || entry.range.pos > context.checkJsDirective.pos) { // TODO: GH#18217 + context.checkJsDirective = { + enabled: key === "ts-check", + end: entry.range.end, + pos: entry.range.pos + }; + } + }); + break; + } + case "jsx": return; // Accessed directly + default: ts.Debug.fail("Unhandled pragma kind"); // Can this be made into an assertNever in the future? + } + }); + } + ts.processPragmasIntoFields = processPragmasIntoFields; + var namedArgRegExCache = ts.createMap(); + function getNamedArgRegEx(name) { + if (namedArgRegExCache.has(name)) { + return namedArgRegExCache.get(name); + } + var result = new RegExp("(\\s" + name + "\\s*=\\s*)('|\")(.+?)\\2", "im"); + namedArgRegExCache.set(name, result); + return result; + } + var tripleSlashXMLCommentStartRegEx = /^\/\/\/\s*<(\S+)\s.*?\/>/im; + var singleLinePragmaRegEx = /^\/\/\/?\s*@(\S+)\s*(.*)\s*$/im; + function extractPragmas(pragmas, range, text) { + var tripleSlash = range.kind === 2 /* SingleLineCommentTrivia */ && tripleSlashXMLCommentStartRegEx.exec(text); + if (tripleSlash) { + var name = tripleSlash[1].toLowerCase(); // Technically unsafe cast, but we do it so the below check to make it safe typechecks + var pragma = ts.commentPragmas[name]; + if (!pragma || !(pragma.kind & 1 /* TripleSlashXML */)) { + return; + } + if (pragma.args) { + var argument = {}; + for (var _i = 0, _a = pragma.args; _i < _a.length; _i++) { + var arg = _a[_i]; + var matcher = getNamedArgRegEx(arg.name); + var matchResult = matcher.exec(text); + if (!matchResult && !arg.optional) { + return; // Missing required argument, don't parse + } + else if (matchResult) { + if (arg.captureSpan) { + var startPos = range.pos + matchResult.index + matchResult[1].length + matchResult[2].length; + argument[arg.name] = { + value: matchResult[3], + pos: startPos, + end: startPos + matchResult[3].length + }; + } + else { + argument[arg.name] = matchResult[3]; + } + } + } + pragmas.push({ name: name, args: { arguments: argument, range: range } }); + } + else { + pragmas.push({ name: name, args: { arguments: {}, range: range } }); + } + return; + } + var singleLine = range.kind === 2 /* SingleLineCommentTrivia */ && singleLinePragmaRegEx.exec(text); + if (singleLine) { + return addPragmaForMatch(pragmas, range, 2 /* SingleLine */, singleLine); + } + if (range.kind === 3 /* MultiLineCommentTrivia */) { + var multiLinePragmaRegEx = /\s*@(\S+)\s*(.*)\s*$/gim; // Defined inline since it uses the "g" flag, which keeps a persistent index (for iterating) + var multiLineMatch = void 0; + while (multiLineMatch = multiLinePragmaRegEx.exec(text)) { + addPragmaForMatch(pragmas, range, 4 /* MultiLine */, multiLineMatch); + } + } + } + function addPragmaForMatch(pragmas, range, kind, match) { + if (!match) + return; + var name = match[1].toLowerCase(); // Technically unsafe cast, but we do it so they below check to make it safe typechecks + var pragma = ts.commentPragmas[name]; + if (!pragma || !(pragma.kind & kind)) { + return; + } + var args = match[2]; // Split on spaces and match up positionally with definition + var argument = getNamedPragmaArguments(pragma, args); + if (argument === "fail") + return; // Missing required argument, fail to parse it + pragmas.push({ name: name, args: { arguments: argument, range: range } }); + return; + } + function getNamedPragmaArguments(pragma, text) { + if (!text) + return {}; + if (!pragma.args) + return {}; + var args = text.split(/\s+/); + var argMap = {}; + for (var i = 0; i < pragma.args.length; i++) { + var argument = pragma.args[i]; + if (!args[i] && !argument.optional) { + return "fail"; + } + if (argument.captureSpan) { + return ts.Debug.fail("Capture spans not yet implemented for non-xml pragmas"); + } + argMap[argument.name] = args[i]; + } + return argMap; + } + /** @internal */ + function tagNamesAreEquivalent(lhs, rhs) { + if (lhs.kind !== rhs.kind) { + return false; + } + if (lhs.kind === 72 /* Identifier */) { + return lhs.escapedText === rhs.escapedText; + } + if (lhs.kind === 100 /* ThisKeyword */) { + return true; + } + // If we are at this statement then we must have PropertyAccessExpression and because tag name in Jsx element can only + // take forms of JsxTagNameExpression which includes an identifier, "this" expression, or another propertyAccessExpression + // it is safe to case the expression property as such. See parseJsxElementName for how we parse tag name in Jsx element + return lhs.name.escapedText === rhs.name.escapedText && + tagNamesAreEquivalent(lhs.expression, rhs.expression); + } + ts.tagNamesAreEquivalent = tagNamesAreEquivalent; +})(ts || (ts = {})); +var ts; +(function (ts) { + /* @internal */ + ts.compileOnSaveCommandLineOption = { name: "compileOnSave", type: "boolean" }; + // NOTE: The order here is important to default lib ordering as entries will have the same + // order in the generated program (see `getDefaultLibPriority` in program.ts). This + // order also affects overload resolution when a type declared in one lib is + // augmented in another lib. + var libEntries = [ + // JavaScript only + ["es5", "lib.es5.d.ts"], + ["es6", "lib.es2015.d.ts"], + ["es2015", "lib.es2015.d.ts"], + ["es7", "lib.es2016.d.ts"], + ["es2016", "lib.es2016.d.ts"], + ["es2017", "lib.es2017.d.ts"], + ["es2018", "lib.es2018.d.ts"], + ["esnext", "lib.esnext.d.ts"], + // Host only + ["dom", "lib.dom.d.ts"], + ["dom.iterable", "lib.dom.iterable.d.ts"], + ["webworker", "lib.webworker.d.ts"], + ["webworker.importscripts", "lib.webworker.importscripts.d.ts"], + ["scripthost", "lib.scripthost.d.ts"], + // ES2015 Or ESNext By-feature options + ["es2015.core", "lib.es2015.core.d.ts"], + ["es2015.collection", "lib.es2015.collection.d.ts"], + ["es2015.generator", "lib.es2015.generator.d.ts"], + ["es2015.iterable", "lib.es2015.iterable.d.ts"], + ["es2015.promise", "lib.es2015.promise.d.ts"], + ["es2015.proxy", "lib.es2015.proxy.d.ts"], + ["es2015.reflect", "lib.es2015.reflect.d.ts"], + ["es2015.symbol", "lib.es2015.symbol.d.ts"], + ["es2015.symbol.wellknown", "lib.es2015.symbol.wellknown.d.ts"], + ["es2016.array.include", "lib.es2016.array.include.d.ts"], + ["es2017.object", "lib.es2017.object.d.ts"], + ["es2017.sharedmemory", "lib.es2017.sharedmemory.d.ts"], + ["es2017.string", "lib.es2017.string.d.ts"], + ["es2017.intl", "lib.es2017.intl.d.ts"], + ["es2017.typedarrays", "lib.es2017.typedarrays.d.ts"], + ["es2018.intl", "lib.es2018.intl.d.ts"], + ["es2018.promise", "lib.es2018.promise.d.ts"], + ["es2018.regexp", "lib.es2018.regexp.d.ts"], + ["esnext.array", "lib.esnext.array.d.ts"], + ["esnext.symbol", "lib.esnext.symbol.d.ts"], + ["esnext.asynciterable", "lib.esnext.asynciterable.d.ts"], + ["esnext.intl", "lib.esnext.intl.d.ts"], + ["esnext.bigint", "lib.esnext.bigint.d.ts"] + ]; + /** + * An array of supported "lib" reference file names used to determine the order for inclusion + * when referenced, as well as for spelling suggestions. This ensures the correct ordering for + * overload resolution when a type declared in one lib is extended by another. + */ + /* @internal */ + ts.libs = libEntries.map(function (entry) { return entry[0]; }); + /** + * A map of lib names to lib files. This map is used both for parsing the "lib" command line + * option as well as for resolving lib reference directives. + */ + /* @internal */ + ts.libMap = ts.createMapFromEntries(libEntries); + /* @internal */ + ts.commonOptionsWithBuild = [ + { + name: "help", + shortName: "h", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Print_this_message, + }, + { + name: "help", + shortName: "?", + type: "boolean" + }, + { + name: "watch", + shortName: "w", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Watch_input_files, + }, + { + name: "preserveWatchOutput", + type: "boolean", + showInSimplifiedHelpView: false, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen, + }, + { + name: "listFiles", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Print_names_of_files_part_of_the_compilation + }, + { + name: "listEmittedFiles", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Print_names_of_generated_files_part_of_the_compilation + }, + { + name: "pretty", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Stylize_errors_and_messages_using_color_and_context_experimental + }, + { + name: "traceResolution", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Enable_tracing_of_the_name_resolution_process + }, + { + name: "diagnostics", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Show_diagnostic_information + }, + { + name: "extendedDiagnostics", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Show_verbose_diagnostic_information + }, + ]; + /* @internal */ + ts.optionDeclarations = ts.commonOptionsWithBuild.concat([ + { + name: "all", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Show_all_compiler_options, + }, + { + name: "version", + shortName: "v", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Print_the_compiler_s_version, + }, + { + name: "init", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file, + }, + { + name: "project", + shortName: "p", + type: "string", + isFilePath: true, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Command_line_Options, + paramType: ts.Diagnostics.FILE_OR_DIRECTORY, + description: ts.Diagnostics.Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json, + }, + { + name: "build", + type: "boolean", + shortName: "b", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Build_one_or_more_projects_and_their_dependencies_if_out_of_date + }, + { + name: "showConfig", + type: "boolean", + category: ts.Diagnostics.Command_line_Options, + isCommandLineOnly: true, + description: ts.Diagnostics.Print_the_final_configuration_instead_of_building + }, + // Basic + { + name: "target", + shortName: "t", + type: ts.createMapFromTemplate({ + es3: 0 /* ES3 */, + es5: 1 /* ES5 */, + es6: 2 /* ES2015 */, + es2015: 2 /* ES2015 */, + es2016: 3 /* ES2016 */, + es2017: 4 /* ES2017 */, + es2018: 5 /* ES2018 */, + esnext: 6 /* ESNext */, + }), + affectsSourceFile: true, + affectsModuleResolution: true, + paramType: ts.Diagnostics.VERSION, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_or_ESNEXT, + }, + { + name: "module", + shortName: "m", + type: ts.createMapFromTemplate({ + none: ts.ModuleKind.None, + commonjs: ts.ModuleKind.CommonJS, + amd: ts.ModuleKind.AMD, + system: ts.ModuleKind.System, + umd: ts.ModuleKind.UMD, + es6: ts.ModuleKind.ES2015, + es2015: ts.ModuleKind.ES2015, + esnext: ts.ModuleKind.ESNext + }), + affectsModuleResolution: true, + paramType: ts.Diagnostics.KIND, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext, + }, + { + name: "lib", + type: "list", + element: { + name: "lib", + type: ts.libMap + }, + affectsModuleResolution: true, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Specify_library_files_to_be_included_in_the_compilation + }, + { + name: "allowJs", + type: "boolean", + affectsModuleResolution: true, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Allow_javascript_files_to_be_compiled + }, + { + name: "checkJs", + type: "boolean", + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Report_errors_in_js_files + }, + { + name: "jsx", + type: ts.createMapFromTemplate({ + "preserve": 1 /* Preserve */, + "react-native": 3 /* ReactNative */, + "react": 2 /* React */ + }), + affectsSourceFile: true, + paramType: ts.Diagnostics.KIND, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Specify_JSX_code_generation_Colon_preserve_react_native_or_react, + }, + { + name: "declaration", + shortName: "d", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Generates_corresponding_d_ts_file, + }, + { + name: "declarationMap", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Generates_a_sourcemap_for_each_corresponding_d_ts_file, + }, + { + name: "emitDeclarationOnly", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Only_emit_d_ts_declaration_files, + }, + { + name: "sourceMap", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Generates_corresponding_map_file, + }, + { + name: "outFile", + type: "string", + isFilePath: true, + paramType: ts.Diagnostics.FILE, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Concatenate_and_emit_output_to_single_file, + }, + { + name: "outDir", + type: "string", + isFilePath: true, + paramType: ts.Diagnostics.DIRECTORY, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Redirect_output_structure_to_the_directory, + }, + { + name: "rootDir", + type: "string", + isFilePath: true, + paramType: ts.Diagnostics.LOCATION, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir, + }, + { + name: "composite", + type: "boolean", + isTSConfigOnly: true, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Enable_project_compilation, + }, + { + name: "removeComments", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Do_not_emit_comments_to_output, + }, + { + name: "noEmit", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Do_not_emit_outputs, + }, + { + name: "importHelpers", + type: "boolean", + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Import_emit_helpers_from_tslib + }, + { + name: "downlevelIteration", + type: "boolean", + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Provide_full_support_for_iterables_in_for_of_spread_and_destructuring_when_targeting_ES5_or_ES3 + }, + { + name: "isolatedModules", + type: "boolean", + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule + }, + // Strict Type Checks + { + name: "strict", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Strict_Type_Checking_Options, + description: ts.Diagnostics.Enable_all_strict_type_checking_options + }, + { + name: "noImplicitAny", + type: "boolean", + affectsSemanticDiagnostics: true, + strictFlag: true, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Strict_Type_Checking_Options, + description: ts.Diagnostics.Raise_error_on_expressions_and_declarations_with_an_implied_any_type + }, + { + name: "strictNullChecks", + type: "boolean", + affectsSemanticDiagnostics: true, + strictFlag: true, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Strict_Type_Checking_Options, + description: ts.Diagnostics.Enable_strict_null_checks + }, + { + name: "strictFunctionTypes", + type: "boolean", + affectsSemanticDiagnostics: true, + strictFlag: true, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Strict_Type_Checking_Options, + description: ts.Diagnostics.Enable_strict_checking_of_function_types + }, + { + name: "strictBindCallApply", + type: "boolean", + strictFlag: true, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Strict_Type_Checking_Options, + description: ts.Diagnostics.Enable_strict_bind_call_and_apply_methods_on_functions + }, + { + name: "strictPropertyInitialization", + type: "boolean", + affectsSemanticDiagnostics: true, + strictFlag: true, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Strict_Type_Checking_Options, + description: ts.Diagnostics.Enable_strict_checking_of_property_initialization_in_classes + }, + { + name: "noImplicitThis", + type: "boolean", + affectsSemanticDiagnostics: true, + strictFlag: true, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Strict_Type_Checking_Options, + description: ts.Diagnostics.Raise_error_on_this_expressions_with_an_implied_any_type, + }, + { + name: "alwaysStrict", + type: "boolean", + affectsSourceFile: true, + strictFlag: true, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Strict_Type_Checking_Options, + description: ts.Diagnostics.Parse_in_strict_mode_and_emit_use_strict_for_each_source_file + }, + // Additional Checks + { + name: "noUnusedLocals", + type: "boolean", + affectsSemanticDiagnostics: true, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Additional_Checks, + description: ts.Diagnostics.Report_errors_on_unused_locals, + }, + { + name: "noUnusedParameters", + type: "boolean", + affectsSemanticDiagnostics: true, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Additional_Checks, + description: ts.Diagnostics.Report_errors_on_unused_parameters, + }, + { + name: "noImplicitReturns", + type: "boolean", + affectsSemanticDiagnostics: true, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Additional_Checks, + description: ts.Diagnostics.Report_error_when_not_all_code_paths_in_function_return_a_value + }, + { + name: "noFallthroughCasesInSwitch", + type: "boolean", + affectsBindDiagnostics: true, + affectsSemanticDiagnostics: true, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Additional_Checks, + description: ts.Diagnostics.Report_errors_for_fallthrough_cases_in_switch_statement + }, + // Module Resolution + { + name: "moduleResolution", + type: ts.createMapFromTemplate({ + node: ts.ModuleResolutionKind.NodeJs, + classic: ts.ModuleResolutionKind.Classic, + }), + affectsModuleResolution: true, + paramType: ts.Diagnostics.STRATEGY, + category: ts.Diagnostics.Module_Resolution_Options, + description: ts.Diagnostics.Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6, + }, + { + name: "baseUrl", + type: "string", + affectsModuleResolution: true, + isFilePath: true, + category: ts.Diagnostics.Module_Resolution_Options, + description: ts.Diagnostics.Base_directory_to_resolve_non_absolute_module_names + }, + { + // this option can only be specified in tsconfig.json + // use type = object to copy the value as-is + name: "paths", + type: "object", + affectsModuleResolution: true, + isTSConfigOnly: true, + category: ts.Diagnostics.Module_Resolution_Options, + description: ts.Diagnostics.A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl + }, + { + // this option can only be specified in tsconfig.json + // use type = object to copy the value as-is + name: "rootDirs", + type: "list", + isTSConfigOnly: true, + element: { + name: "rootDirs", + type: "string", + isFilePath: true + }, + affectsModuleResolution: true, + category: ts.Diagnostics.Module_Resolution_Options, + description: ts.Diagnostics.List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime + }, + { + name: "typeRoots", + type: "list", + element: { + name: "typeRoots", + type: "string", + isFilePath: true + }, + affectsModuleResolution: true, + category: ts.Diagnostics.Module_Resolution_Options, + description: ts.Diagnostics.List_of_folders_to_include_type_definitions_from + }, + { + name: "types", + type: "list", + element: { + name: "types", + type: "string" + }, + affectsModuleResolution: true, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Module_Resolution_Options, + description: ts.Diagnostics.Type_declaration_files_to_be_included_in_compilation + }, + { + name: "allowSyntheticDefaultImports", + type: "boolean", + affectsSemanticDiagnostics: true, + category: ts.Diagnostics.Module_Resolution_Options, + description: ts.Diagnostics.Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking + }, + { + name: "esModuleInterop", + type: "boolean", + affectsSemanticDiagnostics: true, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Module_Resolution_Options, + description: ts.Diagnostics.Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for_all_imports_Implies_allowSyntheticDefaultImports + }, + { + name: "preserveSymlinks", + type: "boolean", + category: ts.Diagnostics.Module_Resolution_Options, + description: ts.Diagnostics.Do_not_resolve_the_real_path_of_symlinks, + }, + // Source Maps + { + name: "sourceRoot", + type: "string", + paramType: ts.Diagnostics.LOCATION, + category: ts.Diagnostics.Source_Map_Options, + description: ts.Diagnostics.Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations, + }, + { + name: "mapRoot", + type: "string", + paramType: ts.Diagnostics.LOCATION, + category: ts.Diagnostics.Source_Map_Options, + description: ts.Diagnostics.Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations, + }, + { + name: "inlineSourceMap", + type: "boolean", + category: ts.Diagnostics.Source_Map_Options, + description: ts.Diagnostics.Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file + }, + { + name: "inlineSources", + type: "boolean", + category: ts.Diagnostics.Source_Map_Options, + description: ts.Diagnostics.Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap_to_be_set + }, + // Experimental + { + name: "experimentalDecorators", + type: "boolean", + category: ts.Diagnostics.Experimental_Options, + description: ts.Diagnostics.Enables_experimental_support_for_ES7_decorators + }, + { + name: "emitDecoratorMetadata", + type: "boolean", + category: ts.Diagnostics.Experimental_Options, + description: ts.Diagnostics.Enables_experimental_support_for_emitting_type_metadata_for_decorators + }, + // Advanced + { + name: "jsxFactory", + type: "string", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h + }, + { + name: "resolveJsonModule", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Include_modules_imported_with_json_extension + }, + { + name: "out", + type: "string", + isFilePath: false, + // for correct behaviour, please use outFile + category: ts.Diagnostics.Advanced_Options, + paramType: ts.Diagnostics.FILE, + description: ts.Diagnostics.Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file, + }, + { + name: "reactNamespace", + type: "string", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react_JSX_emit + }, + { + name: "skipDefaultLibCheck", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files + }, + { + name: "charset", + type: "string", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.The_character_set_of_the_input_files + }, + { + name: "emitBOM", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files + }, + { + name: "locale", + type: "string", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.The_locale_used_when_displaying_messages_to_the_user_e_g_en_us + }, + { + name: "newLine", + type: ts.createMapFromTemplate({ + crlf: 0 /* CarriageReturnLineFeed */, + lf: 1 /* LineFeed */ + }), + paramType: ts.Diagnostics.NEWLINE, + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix, + }, + { + name: "noErrorTruncation", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Do_not_truncate_error_messages + }, + { + name: "noLib", + type: "boolean", + affectsModuleResolution: true, + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Do_not_include_the_default_library_file_lib_d_ts + }, + { + name: "noResolve", + type: "boolean", + affectsModuleResolution: true, + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files + }, + { + name: "stripInternal", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Do_not_emit_declarations_for_code_that_has_an_internal_annotation, + }, + { + name: "disableSizeLimit", + type: "boolean", + affectsSourceFile: true, + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Disable_size_limitations_on_JavaScript_projects + }, + { + name: "noImplicitUseStrict", + type: "boolean", + affectsSemanticDiagnostics: true, + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Do_not_emit_use_strict_directives_in_module_output + }, + { + name: "noEmitHelpers", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Do_not_generate_custom_helper_functions_like_extends_in_compiled_output + }, + { + name: "noEmitOnError", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Do_not_emit_outputs_if_any_errors_were_reported, + }, + { + name: "preserveConstEnums", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Do_not_erase_const_enum_declarations_in_generated_code + }, + { + name: "declarationDir", + type: "string", + isFilePath: true, + paramType: ts.Diagnostics.DIRECTORY, + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Output_directory_for_generated_declaration_files + }, + { + name: "skipLibCheck", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Skip_type_checking_of_declaration_files, + }, + { + name: "allowUnusedLabels", + type: "boolean", + affectsBindDiagnostics: true, + affectsSemanticDiagnostics: true, + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Do_not_report_errors_on_unused_labels + }, + { + name: "allowUnreachableCode", + type: "boolean", + affectsBindDiagnostics: true, + affectsSemanticDiagnostics: true, + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Do_not_report_errors_on_unreachable_code + }, + { + name: "suppressExcessPropertyErrors", + type: "boolean", + affectsSemanticDiagnostics: true, + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Suppress_excess_property_checks_for_object_literals, + }, + { + name: "suppressImplicitAnyIndexErrors", + type: "boolean", + affectsSemanticDiagnostics: true, + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures, + }, + { + name: "forceConsistentCasingInFileNames", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Disallow_inconsistently_cased_references_to_the_same_file + }, + { + name: "maxNodeModuleJsDepth", + type: "number", + affectsModuleResolution: true, + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files + }, + { + name: "noStrictGenericChecks", + type: "boolean", + affectsSemanticDiagnostics: true, + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Disable_strict_checking_of_generic_signatures_in_function_types, + }, + { + name: "keyofStringsOnly", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols, + }, + { + // A list of plugins to load in the language service + name: "plugins", + type: "list", + isTSConfigOnly: true, + element: { + name: "plugin", + type: "object" + }, + description: ts.Diagnostics.List_of_language_service_plugins + } + ]); + /* @internal */ + ts.semanticDiagnosticsOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsSemanticDiagnostics; }); + /* @internal */ + ts.moduleResolutionOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsModuleResolution; }); + /* @internal */ + ts.sourceFileAffectingCompilerOptions = ts.optionDeclarations.filter(function (option) { + return !!option.affectsSourceFile || !!option.affectsModuleResolution || !!option.affectsBindDiagnostics; + }); + /* @internal */ + ts.buildOpts = ts.commonOptionsWithBuild.concat([ + { + name: "verbose", + shortName: "v", + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Enable_verbose_logging, + type: "boolean" + }, + { + name: "dry", + shortName: "d", + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Show_what_would_be_built_or_deleted_if_specified_with_clean, + type: "boolean" + }, + { + name: "force", + shortName: "f", + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Build_all_projects_including_those_that_appear_to_be_up_to_date, + type: "boolean" + }, + { + name: "clean", + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Delete_the_outputs_of_all_projects, + type: "boolean" + } + ]); + /* @internal */ + ts.typeAcquisitionDeclarations = [ + { + /* @deprecated typingOptions.enableAutoDiscovery + * Use typeAcquisition.enable instead. + */ + name: "enableAutoDiscovery", + type: "boolean", + }, + { + name: "enable", + type: "boolean", + }, + { + name: "include", + type: "list", + element: { + name: "include", + type: "string" + } + }, + { + name: "exclude", + type: "list", + element: { + name: "exclude", + type: "string" + } + } + ]; + /* @internal */ + ts.defaultInitCompilerOptions = { + module: ts.ModuleKind.CommonJS, + target: 1 /* ES5 */, + strict: true, + esModuleInterop: true + }; + var optionNameMapCache; + /* @internal */ + function convertEnableAutoDiscoveryToEnable(typeAcquisition) { + // Convert deprecated typingOptions.enableAutoDiscovery to typeAcquisition.enable + if (typeAcquisition && typeAcquisition.enableAutoDiscovery !== undefined && typeAcquisition.enable === undefined) { + return { + enable: typeAcquisition.enableAutoDiscovery, + include: typeAcquisition.include || [], + exclude: typeAcquisition.exclude || [] + }; + } + return typeAcquisition; + } + ts.convertEnableAutoDiscoveryToEnable = convertEnableAutoDiscoveryToEnable; + function getOptionNameMap() { + return optionNameMapCache || (optionNameMapCache = createOptionNameMap(ts.optionDeclarations)); + } + /*@internal*/ + function createOptionNameMap(optionDeclarations) { + var optionNameMap = ts.createMap(); + var shortOptionNames = ts.createMap(); + ts.forEach(optionDeclarations, function (option) { + optionNameMap.set(option.name.toLowerCase(), option); + if (option.shortName) { + shortOptionNames.set(option.shortName, option.name); + } + }); + return { optionNameMap: optionNameMap, shortOptionNames: shortOptionNames }; + } + ts.createOptionNameMap = createOptionNameMap; + /* @internal */ + function createCompilerDiagnosticForInvalidCustomType(opt) { + return createDiagnosticForInvalidCustomType(opt, ts.createCompilerDiagnostic); + } + ts.createCompilerDiagnosticForInvalidCustomType = createCompilerDiagnosticForInvalidCustomType; + function createDiagnosticForInvalidCustomType(opt, createDiagnostic) { + var namesOfType = ts.arrayFrom(opt.type.keys()).map(function (key) { return "'" + key + "'"; }).join(", "); + return createDiagnostic(ts.Diagnostics.Argument_for_0_option_must_be_Colon_1, "--" + opt.name, namesOfType); + } + /* @internal */ + function parseCustomTypeOption(opt, value, errors) { + return convertJsonOptionOfCustomType(opt, trimString(value || ""), errors); + } + ts.parseCustomTypeOption = parseCustomTypeOption; + /* @internal */ + function parseListTypeOption(opt, value, errors) { + if (value === void 0) { value = ""; } + value = trimString(value); + if (ts.startsWith(value, "-")) { + return undefined; + } + if (value === "") { + return []; + } + var values = value.split(","); + switch (opt.element.type) { + case "number": + return ts.map(values, parseInt); + case "string": + return ts.map(values, function (v) { return v || ""; }); + default: + return ts.mapDefined(values, function (v) { return parseCustomTypeOption(opt.element, v, errors); }); + } + } + ts.parseListTypeOption = parseListTypeOption; + function parseCommandLineWorker(getOptionNameMap, _a, commandLine, readFile) { + var unknownOptionDiagnostic = _a[0], optionTypeMismatchDiagnostic = _a[1]; + var options = {}; + var fileNames = []; + var errors = []; + parseStrings(commandLine); + return { + options: options, + fileNames: fileNames, + errors: errors + }; + function parseStrings(args) { + var i = 0; + while (i < args.length) { + var s = args[i]; + i++; + if (s.charCodeAt(0) === 64 /* at */) { + parseResponseFile(s.slice(1)); + } + else if (s.charCodeAt(0) === 45 /* minus */) { + var opt = getOptionDeclarationFromName(getOptionNameMap, s.slice(s.charCodeAt(1) === 45 /* minus */ ? 2 : 1), /*allowShort*/ true); + if (opt) { + if (opt.isTSConfigOnly) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_can_only_be_specified_in_tsconfig_json_file, opt.name)); + } + else { + // Check to see if no argument was provided (e.g. "--locale" is the last command-line argument). + if (!args[i] && opt.type !== "boolean") { + errors.push(ts.createCompilerDiagnostic(optionTypeMismatchDiagnostic, opt.name)); + } + switch (opt.type) { + case "number": + options[opt.name] = parseInt(args[i]); + i++; + break; + case "boolean": + // boolean flag has optional value true, false, others + var optValue = args[i]; + options[opt.name] = optValue !== "false"; + // consume next argument as boolean flag value + if (optValue === "false" || optValue === "true") { + i++; + } + break; + case "string": + options[opt.name] = args[i] || ""; + i++; + break; + case "list": + var result = parseListTypeOption(opt, args[i], errors); + options[opt.name] = result || []; + if (result) { + i++; + } + break; + // If not a primitive, the possible types are specified in what is effectively a map of options. + default: + options[opt.name] = parseCustomTypeOption(opt, args[i], errors); + i++; + break; + } + } + } + else { + errors.push(ts.createCompilerDiagnostic(unknownOptionDiagnostic, s)); + } + } + else { + fileNames.push(s); + } + } + } + function parseResponseFile(fileName) { + var text = readFile ? readFile(fileName) : ts.sys.readFile(fileName); + if (!text) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_not_found, fileName)); + return; + } + var args = []; + var pos = 0; + while (true) { + while (pos < text.length && text.charCodeAt(pos) <= 32 /* space */) + pos++; + if (pos >= text.length) + break; + var start = pos; + if (text.charCodeAt(start) === 34 /* doubleQuote */) { + pos++; + while (pos < text.length && text.charCodeAt(pos) !== 34 /* doubleQuote */) + pos++; + if (pos < text.length) { + args.push(text.substring(start + 1, pos)); + pos++; + } + else { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unterminated_quoted_string_in_response_file_0, fileName)); + } + } + else { + while (text.charCodeAt(pos) > 32 /* space */) + pos++; + args.push(text.substring(start, pos)); + } + } + parseStrings(args); + } + } + function parseCommandLine(commandLine, readFile) { + return parseCommandLineWorker(getOptionNameMap, [ + ts.Diagnostics.Unknown_compiler_option_0, + ts.Diagnostics.Compiler_option_0_expects_an_argument + ], commandLine, readFile); + } + ts.parseCommandLine = parseCommandLine; + /** @internal */ + function getOptionFromName(optionName, allowShort) { + return getOptionDeclarationFromName(getOptionNameMap, optionName, allowShort); + } + ts.getOptionFromName = getOptionFromName; + function getOptionDeclarationFromName(getOptionNameMap, optionName, allowShort) { + if (allowShort === void 0) { allowShort = false; } + optionName = optionName.toLowerCase(); + var _a = getOptionNameMap(), optionNameMap = _a.optionNameMap, shortOptionNames = _a.shortOptionNames; + // Try to translate short option names to their full equivalents. + if (allowShort) { + var short = shortOptionNames.get(optionName); + if (short !== undefined) { + optionName = short; + } + } + return optionNameMap.get(optionName); + } + /*@internal*/ + function parseBuildCommand(args) { + var buildOptionNameMap; + var returnBuildOptionNameMap = function () { return (buildOptionNameMap || (buildOptionNameMap = createOptionNameMap(ts.buildOpts))); }; + var _a = parseCommandLineWorker(returnBuildOptionNameMap, [ + ts.Diagnostics.Unknown_build_option_0, + ts.Diagnostics.Build_option_0_requires_a_value_of_type_1 + ], args), options = _a.options, projects = _a.fileNames, errors = _a.errors; + var buildOptions = options; + if (projects.length === 0) { + // tsc -b invoked with no extra arguments; act as if invoked with "tsc -b ." + projects.push("."); + } + // Nonsensical combinations + if (buildOptions.clean && buildOptions.force) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "force")); + } + if (buildOptions.clean && buildOptions.verbose) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "verbose")); + } + if (buildOptions.clean && buildOptions.watch) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "watch")); + } + if (buildOptions.watch && buildOptions.dry) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "watch", "dry")); + } + return { buildOptions: buildOptions, projects: projects, errors: errors }; + } + ts.parseBuildCommand = parseBuildCommand; + function getDiagnosticText(_message) { + var _args = []; + for (var _i = 1; _i < arguments.length; _i++) { + _args[_i - 1] = arguments[_i]; + } + var diagnostic = ts.createCompilerDiagnostic.apply(undefined, arguments); + return diagnostic.messageText; + } + /* @internal */ + function printVersion() { + ts.sys.write(getDiagnosticText(ts.Diagnostics.Version_0, ts.version) + ts.sys.newLine); + } + ts.printVersion = printVersion; + /* @internal */ + function printHelp(optionsList, syntaxPrefix) { + if (syntaxPrefix === void 0) { syntaxPrefix = ""; } + var output = []; + // We want to align our "syntax" and "examples" commands to a certain margin. + var syntaxLength = getDiagnosticText(ts.Diagnostics.Syntax_Colon_0, "").length; + var examplesLength = getDiagnosticText(ts.Diagnostics.Examples_Colon_0, "").length; + var marginLength = Math.max(syntaxLength, examplesLength); + // Build up the syntactic skeleton. + var syntax = makePadding(marginLength - syntaxLength); + syntax += "tsc " + syntaxPrefix + "[" + getDiagnosticText(ts.Diagnostics.options) + "] [" + getDiagnosticText(ts.Diagnostics.file) + "...]"; + output.push(getDiagnosticText(ts.Diagnostics.Syntax_Colon_0, syntax)); + output.push(ts.sys.newLine + ts.sys.newLine); + // Build up the list of examples. + var padding = makePadding(marginLength); + output.push(getDiagnosticText(ts.Diagnostics.Examples_Colon_0, makePadding(marginLength - examplesLength) + "tsc hello.ts") + ts.sys.newLine); + output.push(padding + "tsc --outFile file.js file.ts" + ts.sys.newLine); + output.push(padding + "tsc @args.txt" + ts.sys.newLine); + output.push(padding + "tsc --build tsconfig.json" + ts.sys.newLine); + output.push(ts.sys.newLine); + output.push(getDiagnosticText(ts.Diagnostics.Options_Colon) + ts.sys.newLine); + // We want our descriptions to align at the same column in our output, + // so we keep track of the longest option usage string. + marginLength = 0; + var usageColumn = []; // Things like "-d, --declaration" go in here. + var descriptionColumn = []; + var optionsDescriptionMap = ts.createMap(); // Map between option.description and list of option.type if it is a kind + for (var _i = 0, optionsList_1 = optionsList; _i < optionsList_1.length; _i++) { + var option = optionsList_1[_i]; + // If an option lacks a description, + // it is not officially supported. + if (!option.description) { + continue; + } + var usageText_1 = " "; + if (option.shortName) { + usageText_1 += "-" + option.shortName; + usageText_1 += getParamType(option); + usageText_1 += ", "; + } + usageText_1 += "--" + option.name; + usageText_1 += getParamType(option); + usageColumn.push(usageText_1); + var description = void 0; + if (option.name === "lib") { + description = getDiagnosticText(option.description); + var element = option.element; + var typeMap = element.type; + optionsDescriptionMap.set(description, ts.arrayFrom(typeMap.keys()).map(function (key) { return "'" + key + "'"; })); + } + else { + description = getDiagnosticText(option.description); + } + descriptionColumn.push(description); + // Set the new margin for the description column if necessary. + marginLength = Math.max(usageText_1.length, marginLength); + } + // Special case that can't fit in the loop. + var usageText = " @<" + getDiagnosticText(ts.Diagnostics.file) + ">"; + usageColumn.push(usageText); + descriptionColumn.push(getDiagnosticText(ts.Diagnostics.Insert_command_line_options_and_files_from_a_file)); + marginLength = Math.max(usageText.length, marginLength); + // Print out each row, aligning all the descriptions on the same column. + for (var i = 0; i < usageColumn.length; i++) { + var usage = usageColumn[i]; + var description = descriptionColumn[i]; + var kindsList = optionsDescriptionMap.get(description); + output.push(usage + makePadding(marginLength - usage.length + 2) + description + ts.sys.newLine); + if (kindsList) { + output.push(makePadding(marginLength + 4)); + for (var _a = 0, kindsList_1 = kindsList; _a < kindsList_1.length; _a++) { + var kind = kindsList_1[_a]; + output.push(kind + " "); + } + output.push(ts.sys.newLine); + } + } + for (var _b = 0, output_1 = output; _b < output_1.length; _b++) { + var line = output_1[_b]; + ts.sys.write(line); + } + return; + function getParamType(option) { + if (option.paramType !== undefined) { + return " " + getDiagnosticText(option.paramType); + } + return ""; + } + function makePadding(paddingLength) { + return Array(paddingLength + 1).join(" "); + } + } + ts.printHelp = printHelp; + /** + * Reads the config file, reports errors if any and exits if the config file cannot be found + */ + function getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host) { + var configFileText; + try { + configFileText = host.readFile(configFileName); + } + catch (e) { + var error = ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, configFileName, e.message); + host.onUnRecoverableConfigFileDiagnostic(error); + return undefined; + } + if (!configFileText) { + var error = ts.createCompilerDiagnostic(ts.Diagnostics.File_0_not_found, configFileName); + host.onUnRecoverableConfigFileDiagnostic(error); + return undefined; + } + var result = ts.parseJsonText(configFileName, configFileText); + var cwd = host.getCurrentDirectory(); + result.path = ts.toPath(configFileName, cwd, ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames)); + result.resolvedPath = result.path; + result.originalFileName = result.fileName; + return parseJsonSourceFileConfigFileContent(result, host, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), cwd), optionsToExtend, ts.getNormalizedAbsolutePath(configFileName, cwd)); + } + ts.getParsedCommandLineOfConfigFile = getParsedCommandLineOfConfigFile; + /** + * Read tsconfig.json file + * @param fileName The path to the config file + */ + function readConfigFile(fileName, readFile) { + var textOrDiagnostic = tryReadFile(fileName, readFile); + return ts.isString(textOrDiagnostic) ? parseConfigFileTextToJson(fileName, textOrDiagnostic) : { config: {}, error: textOrDiagnostic }; + } + ts.readConfigFile = readConfigFile; + /** + * Parse the text of the tsconfig.json file + * @param fileName The path to the config file + * @param jsonText The text of the config file + */ + function parseConfigFileTextToJson(fileName, jsonText) { + var jsonSourceFile = ts.parseJsonText(fileName, jsonText); + return { + config: convertToObject(jsonSourceFile, jsonSourceFile.parseDiagnostics), + error: jsonSourceFile.parseDiagnostics.length ? jsonSourceFile.parseDiagnostics[0] : undefined + }; + } + ts.parseConfigFileTextToJson = parseConfigFileTextToJson; + /** + * Read tsconfig.json file + * @param fileName The path to the config file + */ + function readJsonConfigFile(fileName, readFile) { + var textOrDiagnostic = tryReadFile(fileName, readFile); + return ts.isString(textOrDiagnostic) ? ts.parseJsonText(fileName, textOrDiagnostic) : { parseDiagnostics: [textOrDiagnostic] }; + } + ts.readJsonConfigFile = readJsonConfigFile; + function tryReadFile(fileName, readFile) { + var text; + try { + text = readFile(fileName); + } + catch (e) { + return ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, e.message); + } + return text === undefined ? ts.createCompilerDiagnostic(ts.Diagnostics.The_specified_path_does_not_exist_Colon_0, fileName) : text; + } + function commandLineOptionsToMap(options) { + return ts.arrayToMap(options, function (option) { return option.name; }); + } + var _tsconfigRootOptions; + function getTsconfigRootOptionsMap() { + if (_tsconfigRootOptions === undefined) { + _tsconfigRootOptions = { + name: undefined, + type: "object", + elementOptions: commandLineOptionsToMap([ + { + name: "compilerOptions", + type: "object", + elementOptions: commandLineOptionsToMap(ts.optionDeclarations), + extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_compiler_option_0 + }, + { + name: "typingOptions", + type: "object", + elementOptions: commandLineOptionsToMap(ts.typeAcquisitionDeclarations), + extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_type_acquisition_option_0 + }, + { + name: "typeAcquisition", + type: "object", + elementOptions: commandLineOptionsToMap(ts.typeAcquisitionDeclarations), + extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_type_acquisition_option_0 + }, + { + name: "extends", + type: "string" + }, + { + name: "references", + type: "list", + element: { + name: "references", + type: "object" + } + }, + { + name: "files", + type: "list", + element: { + name: "files", + type: "string" + } + }, + { + name: "include", + type: "list", + element: { + name: "include", + type: "string" + } + }, + { + name: "exclude", + type: "list", + element: { + name: "exclude", + type: "string" + } + }, + ts.compileOnSaveCommandLineOption + ]) + }; + } + return _tsconfigRootOptions; + } + /** + * Convert the json syntax tree into the json value + */ + function convertToObject(sourceFile, errors) { + return convertToObjectWorker(sourceFile, errors, /*returnValue*/ true, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined); + } + ts.convertToObject = convertToObject; + /** + * Convert the json syntax tree into the json value and report errors + * This returns the json value (apart from checking errors) only if returnValue provided is true. + * Otherwise it just checks the errors and returns undefined + */ + /*@internal*/ + function convertToObjectWorker(sourceFile, errors, returnValue, knownRootOptions, jsonConversionNotifier) { + if (!sourceFile.statements.length) { + return returnValue ? {} : undefined; + } + return convertPropertyValueToJson(sourceFile.statements[0].expression, knownRootOptions); + function isRootOptionMap(knownOptions) { + return knownRootOptions && knownRootOptions.elementOptions === knownOptions; + } + function convertObjectLiteralExpressionToJson(node, knownOptions, extraKeyDiagnosticMessage, parentOption) { + var result = returnValue ? {} : undefined; + for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { + var element = _a[_i]; + if (element.kind !== 275 /* PropertyAssignment */) { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element, ts.Diagnostics.Property_assignment_expected)); + continue; + } + if (element.questionToken) { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.questionToken, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, "?")); + } + if (!isDoubleQuotedString(element.name)) { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, ts.Diagnostics.String_literal_with_double_quotes_expected)); + } + var textOfKey = ts.getTextOfPropertyName(element.name); + var keyText = textOfKey && ts.unescapeLeadingUnderscores(textOfKey); + var option = keyText && knownOptions ? knownOptions.get(keyText) : undefined; + if (keyText && extraKeyDiagnosticMessage && !option) { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, extraKeyDiagnosticMessage, keyText)); + } + var value = convertPropertyValueToJson(element.initializer, option); + if (typeof keyText !== "undefined") { + if (returnValue) { + result[keyText] = value; + } + // Notify key value set, if user asked for it + if (jsonConversionNotifier && + // Current callbacks are only on known parent option or if we are setting values in the root + (parentOption || isRootOptionMap(knownOptions))) { + var isValidOptionValue = isCompilerOptionsValue(option, value); + if (parentOption) { + if (isValidOptionValue) { + // Notify option set in the parent if its a valid option value + jsonConversionNotifier.onSetValidOptionKeyValueInParent(parentOption, option, value); + } + } + else if (isRootOptionMap(knownOptions)) { + if (isValidOptionValue) { + // Notify about the valid root key value being set + jsonConversionNotifier.onSetValidOptionKeyValueInRoot(keyText, element.name, value, element.initializer); + } + else if (!option) { + // Notify about the unknown root key value being set + jsonConversionNotifier.onSetUnknownOptionKeyValueInRoot(keyText, element.name, value, element.initializer); + } + } + } + } + } + return result; + } + function convertArrayLiteralExpressionToJson(elements, elementOption) { + if (!returnValue) { + return elements.forEach(function (element) { return convertPropertyValueToJson(element, elementOption); }); + } + // Filter out invalid values + return ts.filter(elements.map(function (element) { return convertPropertyValueToJson(element, elementOption); }), function (v) { return v !== undefined; }); + } + function convertPropertyValueToJson(valueExpression, option) { + switch (valueExpression.kind) { + case 102 /* TrueKeyword */: + reportInvalidOptionValue(option && option.type !== "boolean"); + return true; + case 87 /* FalseKeyword */: + reportInvalidOptionValue(option && option.type !== "boolean"); + return false; + case 96 /* NullKeyword */: + reportInvalidOptionValue(option && option.name === "extends"); // "extends" is the only option we don't allow null/undefined for + return null; // tslint:disable-line:no-null-keyword + case 10 /* StringLiteral */: + if (!isDoubleQuotedString(valueExpression)) { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, ts.Diagnostics.String_literal_with_double_quotes_expected)); + } + reportInvalidOptionValue(option && (ts.isString(option.type) && option.type !== "string")); + var text = valueExpression.text; + if (option && !ts.isString(option.type)) { + var customOption = option; + // Validate custom option type + if (!customOption.type.has(text.toLowerCase())) { + errors.push(createDiagnosticForInvalidCustomType(customOption, function (message, arg0, arg1) { return ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, message, arg0, arg1); })); + } + } + return text; + case 8 /* NumericLiteral */: + reportInvalidOptionValue(option && option.type !== "number"); + return Number(valueExpression.text); + case 202 /* PrefixUnaryExpression */: + if (valueExpression.operator !== 39 /* MinusToken */ || valueExpression.operand.kind !== 8 /* NumericLiteral */) { + break; // not valid JSON syntax + } + reportInvalidOptionValue(option && option.type !== "number"); + return -Number(valueExpression.operand.text); + case 188 /* ObjectLiteralExpression */: + reportInvalidOptionValue(option && option.type !== "object"); + var objectLiteralExpression = valueExpression; + // Currently having element option declaration in the tsconfig with type "object" + // determines if it needs onSetValidOptionKeyValueInParent callback or not + // At moment there are only "compilerOptions", "typeAcquisition" and "typingOptions" + // that satifies it and need it to modify options set in them (for normalizing file paths) + // vs what we set in the json + // If need arises, we can modify this interface and callbacks as needed + if (option) { + var _a = option, elementOptions = _a.elementOptions, extraKeyDiagnosticMessage = _a.extraKeyDiagnosticMessage, optionName = _a.name; + return convertObjectLiteralExpressionToJson(objectLiteralExpression, elementOptions, extraKeyDiagnosticMessage, optionName); + } + else { + return convertObjectLiteralExpressionToJson(objectLiteralExpression, /* knownOptions*/ undefined, + /*extraKeyDiagnosticMessage */ undefined, /*parentOption*/ undefined); + } + case 187 /* ArrayLiteralExpression */: + reportInvalidOptionValue(option && option.type !== "list"); + return convertArrayLiteralExpressionToJson(valueExpression.elements, option && option.element); + } + // Not in expected format + if (option) { + reportInvalidOptionValue(/*isError*/ true); + } + else { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, ts.Diagnostics.Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_literal)); + } + return undefined; + function reportInvalidOptionValue(isError) { + if (isError) { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, option.name, getCompilerOptionValueTypeString(option))); + } + } + } + function isDoubleQuotedString(node) { + return ts.isStringLiteral(node) && ts.isStringDoubleQuoted(node, sourceFile); + } + } + ts.convertToObjectWorker = convertToObjectWorker; + function getCompilerOptionValueTypeString(option) { + return option.type === "list" ? + "Array" : + ts.isString(option.type) ? option.type : "string"; + } + function isCompilerOptionsValue(option, value) { + if (option) { + if (isNullOrUndefined(value)) + return true; // All options are undefinable/nullable + if (option.type === "list") { + return ts.isArray(value); + } + var expectedType = ts.isString(option.type) ? option.type : "string"; + return typeof value === expectedType; + } + return false; + } + /** + * Generate an uncommented, complete tsconfig for use with "--showConfig" + * @param configParseResult options to be generated into tsconfig.json + * @param configFileName name of the parsed config file - output paths will be generated relative to this + * @param host provides current directory and case sensitivity services + */ + /** @internal */ + function convertToTSConfig(configParseResult, configFileName, host) { + var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); + var files = ts.map(ts.filter(configParseResult.fileNames, (!configParseResult.configFileSpecs || !configParseResult.configFileSpecs.validatedIncludeSpecs) ? function (_) { return true; } : matchesSpecs(configFileName, configParseResult.configFileSpecs.validatedIncludeSpecs, configParseResult.configFileSpecs.validatedExcludeSpecs)), function (f) { return ts.getRelativePathFromFile(ts.getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), ts.getNormalizedAbsolutePath(f, host.getCurrentDirectory()), getCanonicalFileName); }); + var optionMap = serializeCompilerOptions(configParseResult.options, { configFilePath: ts.getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), useCaseSensitiveFileNames: host.useCaseSensitiveFileNames }); + var config = __assign({ compilerOptions: __assign({}, ts.arrayFrom(optionMap.entries()).reduce(function (prev, cur) { + var _a; + return (__assign({}, prev, (_a = {}, _a[cur[0]] = cur[1], _a))); + }, {}), { showConfig: undefined, configFile: undefined, configFilePath: undefined, help: undefined, init: undefined, listFiles: undefined, listEmittedFiles: undefined, project: undefined }), references: ts.map(configParseResult.projectReferences, function (r) { return (__assign({}, r, { path: r.originalPath, originalPath: undefined })); }), files: ts.length(files) ? files : undefined }, (configParseResult.configFileSpecs ? { + include: filterSameAsDefaultInclude(configParseResult.configFileSpecs.validatedIncludeSpecs), + exclude: configParseResult.configFileSpecs.validatedExcludeSpecs + } : {}), { compilerOnSave: !!configParseResult.compileOnSave ? true : undefined }); + return config; + } + ts.convertToTSConfig = convertToTSConfig; + function filterSameAsDefaultInclude(specs) { + if (!ts.length(specs)) + return undefined; + if (ts.length(specs) !== 1) + return specs; + if (specs[0] === "**/*") + return undefined; + return specs; + } + function matchesSpecs(path, includeSpecs, excludeSpecs) { + if (!includeSpecs) + return function (_) { return true; }; + var patterns = ts.getFileMatcherPatterns(path, excludeSpecs, includeSpecs, ts.sys.useCaseSensitiveFileNames, ts.sys.getCurrentDirectory()); + var excludeRe = patterns.excludePattern && ts.getRegexFromPattern(patterns.excludePattern, ts.sys.useCaseSensitiveFileNames); + var includeRe = patterns.includeFilePattern && ts.getRegexFromPattern(patterns.includeFilePattern, ts.sys.useCaseSensitiveFileNames); + if (includeRe) { + if (excludeRe) { + return function (path) { return !(includeRe.test(path) && !excludeRe.test(path)); }; + } + return function (path) { return !includeRe.test(path); }; + } + if (excludeRe) { + return function (path) { return excludeRe.test(path); }; + } + return function (_) { return true; }; + } + function getCustomTypeMapOfCommandLineOption(optionDefinition) { + if (optionDefinition.type === "string" || optionDefinition.type === "number" || optionDefinition.type === "boolean") { + // this is of a type CommandLineOptionOfPrimitiveType + return undefined; + } + else if (optionDefinition.type === "list") { + return getCustomTypeMapOfCommandLineOption(optionDefinition.element); + } + else { + return optionDefinition.type; + } + } + function getNameOfCompilerOptionValue(value, customTypeMap) { + // There is a typeMap associated with this command-line option so use it to map value back to its name + return ts.forEachEntry(customTypeMap, function (mapValue, key) { + if (mapValue === value) { + return key; + } + }); + } + function serializeCompilerOptions(options, pathOptions) { + var result = ts.createMap(); + var optionsNameMap = getOptionNameMap().optionNameMap; + var getCanonicalFileName = pathOptions && ts.createGetCanonicalFileName(pathOptions.useCaseSensitiveFileNames); + var _loop_3 = function (name) { + if (ts.hasProperty(options, name)) { + // tsconfig only options cannot be specified via command line, + // so we can assume that only types that can appear here string | number | boolean + if (optionsNameMap.has(name) && optionsNameMap.get(name).category === ts.Diagnostics.Command_line_Options) { + return "continue"; + } + var value = options[name]; + var optionDefinition = optionsNameMap.get(name.toLowerCase()); + if (optionDefinition) { + var customTypeMap_1 = getCustomTypeMapOfCommandLineOption(optionDefinition); + if (!customTypeMap_1) { + // There is no map associated with this compiler option then use the value as-is + // This is the case if the value is expect to be string, number, boolean or list of string + if (pathOptions && optionDefinition.isFilePath) { + result.set(name, ts.getRelativePathFromFile(pathOptions.configFilePath, ts.getNormalizedAbsolutePath(value, ts.getDirectoryPath(pathOptions.configFilePath)), getCanonicalFileName)); + } + else { + result.set(name, value); + } + } + else { + if (optionDefinition.type === "list") { + result.set(name, value.map(function (element) { return getNameOfCompilerOptionValue(element, customTypeMap_1); })); // TODO: GH#18217 + } + else { + // There is a typeMap associated with this command-line option so use it to map value back to its name + result.set(name, getNameOfCompilerOptionValue(value, customTypeMap_1)); + } + } + } + } + }; + for (var name in options) { + _loop_3(name); + } + return result; + } + /** + * Generate tsconfig configuration when running command line "--init" + * @param options commandlineOptions to be generated into tsconfig.json + * @param fileNames array of filenames to be generated into tsconfig.json + */ + /* @internal */ + function generateTSConfig(options, fileNames, newLine) { + var compilerOptions = ts.extend(options, ts.defaultInitCompilerOptions); + var compilerOptionsMap = serializeCompilerOptions(compilerOptions); + return writeConfigurations(); + function getDefaultValueForOption(option) { + switch (option.type) { + case "number": + return 1; + case "boolean": + return true; + case "string": + return option.isFilePath ? "./" : ""; + case "list": + return []; + case "object": + return {}; + default: + return option.type.keys().next().value; + } + } + function makePadding(paddingLength) { + return Array(paddingLength + 1).join(" "); + } + function isAllowedOption(_a) { + var category = _a.category, name = _a.name; + // Skip options which do not have a category or have category `Command_line_Options` + // Exclude all possible `Advanced_Options` in tsconfig.json which were NOT defined in command line + return category !== undefined + && category !== ts.Diagnostics.Command_line_Options + && (category !== ts.Diagnostics.Advanced_Options || compilerOptionsMap.has(name)); + } + function writeConfigurations() { + // Filter applicable options to place in the file + var categorizedOptions = ts.createMultiMap(); + for (var _i = 0, optionDeclarations_1 = ts.optionDeclarations; _i < optionDeclarations_1.length; _i++) { + var option = optionDeclarations_1[_i]; + var category = option.category; + if (isAllowedOption(option)) { + categorizedOptions.add(ts.getLocaleSpecificMessage(category), option); + } + } + // Serialize all options and their descriptions + var marginLength = 0; + var seenKnownKeys = 0; + var nameColumn = []; + var descriptionColumn = []; + categorizedOptions.forEach(function (options, category) { + if (nameColumn.length !== 0) { + nameColumn.push(""); + descriptionColumn.push(""); + } + nameColumn.push("/* " + category + " */"); + descriptionColumn.push(""); + for (var _i = 0, options_1 = options; _i < options_1.length; _i++) { + var option = options_1[_i]; + var optionName = void 0; + if (compilerOptionsMap.has(option.name)) { + optionName = "\"" + option.name + "\": " + JSON.stringify(compilerOptionsMap.get(option.name)) + ((seenKnownKeys += 1) === compilerOptionsMap.size ? "" : ","); + } + else { + optionName = "// \"" + option.name + "\": " + JSON.stringify(getDefaultValueForOption(option)) + ","; + } + nameColumn.push(optionName); + descriptionColumn.push("/* " + (option.description && ts.getLocaleSpecificMessage(option.description) || option.name) + " */"); + marginLength = Math.max(optionName.length, marginLength); + } + }); + // Write the output + var tab = makePadding(2); + var result = []; + result.push("{"); + result.push(tab + "\"compilerOptions\": {"); + // Print out each row, aligning all the descriptions on the same column. + for (var i = 0; i < nameColumn.length; i++) { + var optionName = nameColumn[i]; + var description = descriptionColumn[i]; + result.push(optionName && "" + tab + tab + optionName + (description && (makePadding(marginLength - optionName.length + 2) + description))); + } + if (fileNames.length) { + result.push(tab + "},"); + result.push(tab + "\"files\": ["); + for (var i = 0; i < fileNames.length; i++) { + result.push("" + tab + tab + JSON.stringify(fileNames[i]) + (i === fileNames.length - 1 ? "" : ",")); + } + result.push(tab + "]"); + } + else { + result.push(tab + "}"); + } + result.push("}"); + return result.join(newLine); + } + } + ts.generateTSConfig = generateTSConfig; + /** + * Parse the contents of a config file (tsconfig.json). + * @param json The contents of the config file to parse + * @param host Instance of ParseConfigHost used to enumerate files in folder. + * @param basePath A root directory to resolve relative path entries in the config + * file to. e.g. outDir + */ + function parseJsonConfigFileContent(json, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions) { + return parseJsonConfigFileContentWorker(json, /*sourceFile*/ undefined, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions); + } + ts.parseJsonConfigFileContent = parseJsonConfigFileContent; + /** + * Parse the contents of a config file (tsconfig.json). + * @param jsonNode The contents of the config file to parse + * @param host Instance of ParseConfigHost used to enumerate files in folder. + * @param basePath A root directory to resolve relative path entries in the config + * file to. e.g. outDir + */ + function parseJsonSourceFileConfigFileContent(sourceFile, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions) { + return parseJsonConfigFileContentWorker(/*json*/ undefined, sourceFile, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions); + } + ts.parseJsonSourceFileConfigFileContent = parseJsonSourceFileConfigFileContent; + /*@internal*/ + function setConfigFileInOptions(options, configFile) { + if (configFile) { + Object.defineProperty(options, "configFile", { enumerable: false, writable: false, value: configFile }); + } + } + ts.setConfigFileInOptions = setConfigFileInOptions; + function isNullOrUndefined(x) { + // tslint:disable-next-line:no-null-keyword + return x === undefined || x === null; + } + function directoryOfCombinedPath(fileName, basePath) { + // Use the `getNormalizedAbsolutePath` function to avoid canonicalizing the path, as it must remain noncanonical + // until consistient casing errors are reported + return ts.getDirectoryPath(ts.getNormalizedAbsolutePath(fileName, basePath)); + } + /** + * Parse the contents of a config file from json or json source file (tsconfig.json). + * @param json The contents of the config file to parse + * @param sourceFile sourceFile corresponding to the Json + * @param host Instance of ParseConfigHost used to enumerate files in folder. + * @param basePath A root directory to resolve relative path entries in the config + * file to. e.g. outDir + * @param resolutionStack Only present for backwards-compatibility. Should be empty. + */ + function parseJsonConfigFileContentWorker(json, sourceFile, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions) { + if (existingOptions === void 0) { existingOptions = {}; } + if (resolutionStack === void 0) { resolutionStack = []; } + if (extraFileExtensions === void 0) { extraFileExtensions = []; } + ts.Debug.assert((json === undefined && sourceFile !== undefined) || (json !== undefined && sourceFile === undefined)); + var errors = []; + var parsedConfig = parseConfig(json, sourceFile, host, basePath, configFileName, resolutionStack, errors); + var raw = parsedConfig.raw; + var options = ts.extend(existingOptions, parsedConfig.options || {}); + options.configFilePath = configFileName && ts.normalizeSlashes(configFileName); + setConfigFileInOptions(options, sourceFile); + var projectReferences; + var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories, spec = _a.spec; + return { + options: options, + fileNames: fileNames, + projectReferences: projectReferences, + typeAcquisition: parsedConfig.typeAcquisition || getDefaultTypeAcquisition(), + raw: raw, + errors: errors, + wildcardDirectories: wildcardDirectories, + compileOnSave: !!raw.compileOnSave, + configFileSpecs: spec + }; + function getFileNames() { + var filesSpecs; + if (ts.hasProperty(raw, "files") && !isNullOrUndefined(raw.files)) { + if (ts.isArray(raw.files)) { + filesSpecs = raw.files; + var hasReferences = ts.hasProperty(raw, "references") && !isNullOrUndefined(raw.references); + var hasZeroOrNoReferences = !hasReferences || raw.references.length === 0; + var hasExtends = ts.hasProperty(raw, "extends"); + if (filesSpecs.length === 0 && hasZeroOrNoReferences && !hasExtends) { + if (sourceFile) { + var fileName = configFileName || "tsconfig.json"; + var diagnosticMessage = ts.Diagnostics.The_files_list_in_config_file_0_is_empty; + var nodeValue = ts.firstDefined(ts.getTsConfigPropArray(sourceFile, "files"), function (property) { return property.initializer; }); + var error = nodeValue + ? ts.createDiagnosticForNodeInSourceFile(sourceFile, nodeValue, diagnosticMessage, fileName) + : ts.createCompilerDiagnostic(diagnosticMessage, fileName); + errors.push(error); + } + else { + createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json"); + } + } + } + else { + createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "files", "Array"); + } + } + var includeSpecs; + if (ts.hasProperty(raw, "include") && !isNullOrUndefined(raw.include)) { + if (ts.isArray(raw.include)) { + includeSpecs = raw.include; + } + else { + createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "include", "Array"); + } + } + var excludeSpecs; + if (ts.hasProperty(raw, "exclude") && !isNullOrUndefined(raw.exclude)) { + if (ts.isArray(raw.exclude)) { + excludeSpecs = raw.exclude; + } + else { + createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "exclude", "Array"); + } + } + else if (raw.compilerOptions) { + var outDir = raw.compilerOptions.outDir; + var declarationDir = raw.compilerOptions.declarationDir; + if (outDir || declarationDir) { + excludeSpecs = [outDir, declarationDir].filter(function (d) { return !!d; }); + } + } + if (filesSpecs === undefined && includeSpecs === undefined) { + includeSpecs = ["**/*"]; + } + var result = matchFileNames(filesSpecs, includeSpecs, excludeSpecs, configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath, options, host, errors, extraFileExtensions, sourceFile); + if (shouldReportNoInputFiles(result, canJsonReportNoInutFiles(raw), resolutionStack)) { + errors.push(getErrorForNoInputFiles(result.spec, configFileName)); + } + if (ts.hasProperty(raw, "references") && !isNullOrUndefined(raw.references)) { + if (ts.isArray(raw.references)) { + for (var _i = 0, _a = raw.references; _i < _a.length; _i++) { + var ref = _a[_i]; + if (typeof ref.path !== "string") { + createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "reference.path", "string"); + } + else { + (projectReferences || (projectReferences = [])).push({ + path: ts.getNormalizedAbsolutePath(ref.path, basePath), + originalPath: ref.path, + prepend: ref.prepend, + circular: ref.circular + }); + } + } + } + else { + createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "references", "Array"); + } + } + return result; + } + function createCompilerDiagnosticOnlyIfJson(message, arg0, arg1) { + if (!sourceFile) { + errors.push(ts.createCompilerDiagnostic(message, arg0, arg1)); + } + } + } + function isErrorNoInputFiles(error) { + return error.code === ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2.code; + } + function getErrorForNoInputFiles(_a, configFileName) { + var includeSpecs = _a.includeSpecs, excludeSpecs = _a.excludeSpecs; + return ts.createCompilerDiagnostic(ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2, configFileName || "tsconfig.json", JSON.stringify(includeSpecs || []), JSON.stringify(excludeSpecs || [])); + } + function shouldReportNoInputFiles(result, canJsonReportNoInutFiles, resolutionStack) { + return result.fileNames.length === 0 && canJsonReportNoInutFiles && (!resolutionStack || resolutionStack.length === 0); + } + /*@internal*/ + function canJsonReportNoInutFiles(raw) { + return !ts.hasProperty(raw, "files") && !ts.hasProperty(raw, "references"); + } + ts.canJsonReportNoInutFiles = canJsonReportNoInutFiles; + /*@internal*/ + function updateErrorForNoInputFiles(result, configFileName, configFileSpecs, configParseDiagnostics, canJsonReportNoInutFiles) { + var existingErrors = configParseDiagnostics.length; + if (shouldReportNoInputFiles(result, canJsonReportNoInutFiles)) { + configParseDiagnostics.push(getErrorForNoInputFiles(configFileSpecs, configFileName)); + } + else { + ts.filterMutate(configParseDiagnostics, function (error) { return !isErrorNoInputFiles(error); }); + } + return existingErrors !== configParseDiagnostics.length; + } + ts.updateErrorForNoInputFiles = updateErrorForNoInputFiles; + function isSuccessfulParsedTsconfig(value) { + return !!value.options; + } + /** + * This *just* extracts options/include/exclude/files out of a config file. + * It does *not* resolve the included files. + */ + function parseConfig(json, sourceFile, host, basePath, configFileName, resolutionStack, errors) { + basePath = ts.normalizeSlashes(basePath); + var resolvedPath = ts.getNormalizedAbsolutePath(configFileName || "", basePath); + if (resolutionStack.indexOf(resolvedPath) >= 0) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Circularity_detected_while_resolving_configuration_Colon_0, resolutionStack.concat([resolvedPath]).join(" -> "))); + return { raw: json || convertToObject(sourceFile, errors) }; + } + var ownConfig = json ? + parseOwnConfigOfJson(json, host, basePath, configFileName, errors) : + parseOwnConfigOfJsonSourceFile(sourceFile, host, basePath, configFileName, errors); + if (ownConfig.extendedConfigPath) { + // copy the resolution stack so it is never reused between branches in potential diamond-problem scenarios. + resolutionStack = resolutionStack.concat([resolvedPath]); + var extendedConfig = getExtendedConfig(sourceFile, ownConfig.extendedConfigPath, host, basePath, resolutionStack, errors); + if (extendedConfig && isSuccessfulParsedTsconfig(extendedConfig)) { + var baseRaw_1 = extendedConfig.raw; + var raw_1 = ownConfig.raw; + var setPropertyInRawIfNotUndefined = function (propertyName) { + var value = raw_1[propertyName] || baseRaw_1[propertyName]; + if (value) { + raw_1[propertyName] = value; + } + }; + setPropertyInRawIfNotUndefined("include"); + setPropertyInRawIfNotUndefined("exclude"); + setPropertyInRawIfNotUndefined("files"); + if (raw_1.compileOnSave === undefined) { + raw_1.compileOnSave = baseRaw_1.compileOnSave; + } + ownConfig.options = ts.assign({}, extendedConfig.options, ownConfig.options); + // TODO extend type typeAcquisition + } + } + return ownConfig; + } + function parseOwnConfigOfJson(json, host, basePath, configFileName, errors) { + if (ts.hasProperty(json, "excludes")) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude)); + } + var options = convertCompilerOptionsFromJsonWorker(json.compilerOptions, basePath, errors, configFileName); + // typingOptions has been deprecated and is only supported for backward compatibility purposes. + // It should be removed in future releases - use typeAcquisition instead. + var typeAcquisition = convertTypeAcquisitionFromJsonWorker(json.typeAcquisition || json.typingOptions, basePath, errors, configFileName); + json.compileOnSave = convertCompileOnSaveOptionFromJson(json, basePath, errors); + var extendedConfigPath; + if (json.extends) { + if (!ts.isString(json.extends)) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "extends", "string")); + } + else { + var newBase = configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath; + extendedConfigPath = getExtendsConfigPath(json.extends, host, newBase, errors, ts.createCompilerDiagnostic); + } + } + return { raw: json, options: options, typeAcquisition: typeAcquisition, extendedConfigPath: extendedConfigPath }; + } + function parseOwnConfigOfJsonSourceFile(sourceFile, host, basePath, configFileName, errors) { + var options = getDefaultCompilerOptions(configFileName); + var typeAcquisition, typingOptionstypeAcquisition; + var extendedConfigPath; + var optionsIterator = { + onSetValidOptionKeyValueInParent: function (parentOption, option, value) { + ts.Debug.assert(parentOption === "compilerOptions" || parentOption === "typeAcquisition" || parentOption === "typingOptions"); + var currentOption = parentOption === "compilerOptions" ? + options : + parentOption === "typeAcquisition" ? + (typeAcquisition || (typeAcquisition = getDefaultTypeAcquisition(configFileName))) : + (typingOptionstypeAcquisition || (typingOptionstypeAcquisition = getDefaultTypeAcquisition(configFileName))); + currentOption[option.name] = normalizeOptionValue(option, basePath, value); + }, + onSetValidOptionKeyValueInRoot: function (key, _keyNode, value, valueNode) { + switch (key) { + case "extends": + var newBase = configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath; + extendedConfigPath = getExtendsConfigPath(value, host, newBase, errors, function (message, arg0) { + return ts.createDiagnosticForNodeInSourceFile(sourceFile, valueNode, message, arg0); + }); + return; + } + }, + onSetUnknownOptionKeyValueInRoot: function (key, keyNode, _value, _valueNode) { + if (key === "excludes") { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, keyNode, ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude)); + } + } + }; + var json = convertToObjectWorker(sourceFile, errors, /*returnValue*/ true, getTsconfigRootOptionsMap(), optionsIterator); + if (!typeAcquisition) { + if (typingOptionstypeAcquisition) { + typeAcquisition = (typingOptionstypeAcquisition.enableAutoDiscovery !== undefined) ? + { + enable: typingOptionstypeAcquisition.enableAutoDiscovery, + include: typingOptionstypeAcquisition.include, + exclude: typingOptionstypeAcquisition.exclude + } : + typingOptionstypeAcquisition; + } + else { + typeAcquisition = getDefaultTypeAcquisition(configFileName); + } + } + return { raw: json, options: options, typeAcquisition: typeAcquisition, extendedConfigPath: extendedConfigPath }; + } + function getExtendsConfigPath(extendedConfig, host, basePath, errors, createDiagnostic) { + extendedConfig = ts.normalizeSlashes(extendedConfig); + if (ts.isRootedDiskPath(extendedConfig) || ts.startsWith(extendedConfig, "./") || ts.startsWith(extendedConfig, "../")) { + var extendedConfigPath = ts.getNormalizedAbsolutePath(extendedConfig, basePath); + if (!host.fileExists(extendedConfigPath) && !ts.endsWith(extendedConfigPath, ".json" /* Json */)) { + extendedConfigPath = extendedConfigPath + ".json"; + if (!host.fileExists(extendedConfigPath)) { + errors.push(createDiagnostic(ts.Diagnostics.File_0_does_not_exist, extendedConfig)); + return undefined; + } + } + return extendedConfigPath; + } + // If the path isn't a rooted or relative path, resolve like a module + var resolved = ts.nodeModuleNameResolver(extendedConfig, ts.combinePaths(basePath, "tsconfig.json"), { moduleResolution: ts.ModuleResolutionKind.NodeJs }, host, /*cache*/ undefined, /*projectRefs*/ undefined, /*lookupConfig*/ true); + if (resolved.resolvedModule) { + return resolved.resolvedModule.resolvedFileName; + } + errors.push(createDiagnostic(ts.Diagnostics.File_0_does_not_exist, extendedConfig)); + return undefined; + } + function getExtendedConfig(sourceFile, extendedConfigPath, host, basePath, resolutionStack, errors) { + var _a; + var extendedResult = readJsonConfigFile(extendedConfigPath, function (path) { return host.readFile(path); }); + if (sourceFile) { + sourceFile.extendedSourceFiles = [extendedResult.fileName]; + } + if (extendedResult.parseDiagnostics.length) { + errors.push.apply(errors, extendedResult.parseDiagnostics); + return undefined; + } + var extendedDirname = ts.getDirectoryPath(extendedConfigPath); + var extendedConfig = parseConfig(/*json*/ undefined, extendedResult, host, extendedDirname, ts.getBaseFileName(extendedConfigPath), resolutionStack, errors); + if (sourceFile && extendedResult.extendedSourceFiles) { + (_a = sourceFile.extendedSourceFiles).push.apply(_a, extendedResult.extendedSourceFiles); + } + if (isSuccessfulParsedTsconfig(extendedConfig)) { + // Update the paths to reflect base path + var relativeDifference_1 = ts.convertToRelativePath(extendedDirname, basePath, ts.identity); + var updatePath_1 = function (path) { return ts.isRootedDiskPath(path) ? path : ts.combinePaths(relativeDifference_1, path); }; + var mapPropertiesInRawIfNotUndefined = function (propertyName) { + if (raw_2[propertyName]) { + raw_2[propertyName] = ts.map(raw_2[propertyName], updatePath_1); + } + }; + var raw_2 = extendedConfig.raw; + mapPropertiesInRawIfNotUndefined("include"); + mapPropertiesInRawIfNotUndefined("exclude"); + mapPropertiesInRawIfNotUndefined("files"); + } + return extendedConfig; + } + function convertCompileOnSaveOptionFromJson(jsonOption, basePath, errors) { + if (!ts.hasProperty(jsonOption, ts.compileOnSaveCommandLineOption.name)) { + return false; + } + var result = convertJsonOption(ts.compileOnSaveCommandLineOption, jsonOption.compileOnSave, basePath, errors); + return typeof result === "boolean" && result; + } + function convertCompilerOptionsFromJson(jsonOptions, basePath, configFileName) { + var errors = []; + var options = convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName); + return { options: options, errors: errors }; + } + ts.convertCompilerOptionsFromJson = convertCompilerOptionsFromJson; + function convertTypeAcquisitionFromJson(jsonOptions, basePath, configFileName) { + var errors = []; + var options = convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName); + return { options: options, errors: errors }; + } + ts.convertTypeAcquisitionFromJson = convertTypeAcquisitionFromJson; + function getDefaultCompilerOptions(configFileName) { + var options = configFileName && ts.getBaseFileName(configFileName) === "jsconfig.json" + ? { allowJs: true, maxNodeModuleJsDepth: 2, allowSyntheticDefaultImports: true, skipLibCheck: true, noEmit: true } + : {}; + return options; + } + function convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName) { + var options = getDefaultCompilerOptions(configFileName); + convertOptionsFromJson(ts.optionDeclarations, jsonOptions, basePath, options, ts.Diagnostics.Unknown_compiler_option_0, errors); + if (configFileName) { + options.configFilePath = ts.normalizeSlashes(configFileName); + } + return options; + } + function getDefaultTypeAcquisition(configFileName) { + return { enable: !!configFileName && ts.getBaseFileName(configFileName) === "jsconfig.json", include: [], exclude: [] }; + } + function convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName) { + var options = getDefaultTypeAcquisition(configFileName); + var typeAcquisition = convertEnableAutoDiscoveryToEnable(jsonOptions); + convertOptionsFromJson(ts.typeAcquisitionDeclarations, typeAcquisition, basePath, options, ts.Diagnostics.Unknown_type_acquisition_option_0, errors); + return options; + } + function convertOptionsFromJson(optionDeclarations, jsonOptions, basePath, defaultOptions, diagnosticMessage, errors) { + if (!jsonOptions) { + return; + } + var optionNameMap = commandLineOptionsToMap(optionDeclarations); + for (var id in jsonOptions) { + var opt = optionNameMap.get(id); + if (opt) { + defaultOptions[opt.name] = convertJsonOption(opt, jsonOptions[id], basePath, errors); + } + else { + errors.push(ts.createCompilerDiagnostic(diagnosticMessage, id)); + } + } + } + function convertJsonOption(opt, value, basePath, errors) { + if (isCompilerOptionsValue(opt, value)) { + var optType = opt.type; + if (optType === "list" && ts.isArray(value)) { + return convertJsonOptionOfListType(opt, value, basePath, errors); + } + else if (!ts.isString(optType)) { + return convertJsonOptionOfCustomType(opt, value, errors); + } + return normalizeNonListOptionValue(opt, basePath, value); + } + else { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, opt.name, getCompilerOptionValueTypeString(opt))); + } + } + function normalizeOptionValue(option, basePath, value) { + if (isNullOrUndefined(value)) + return undefined; + if (option.type === "list") { + var listOption_1 = option; + if (listOption_1.element.isFilePath || !ts.isString(listOption_1.element.type)) { + return ts.filter(ts.map(value, function (v) { return normalizeOptionValue(listOption_1.element, basePath, v); }), function (v) { return !!v; }); + } + return value; + } + else if (!ts.isString(option.type)) { + return option.type.get(ts.isString(value) ? value.toLowerCase() : value); + } + return normalizeNonListOptionValue(option, basePath, value); + } + function normalizeNonListOptionValue(option, basePath, value) { + if (option.isFilePath) { + value = ts.normalizePath(ts.combinePaths(basePath, value)); + if (value === "") { + value = "."; + } + } + return value; + } + function convertJsonOptionOfCustomType(opt, value, errors) { + if (isNullOrUndefined(value)) + return undefined; + var key = value.toLowerCase(); + var val = opt.type.get(key); + if (val !== undefined) { + return val; + } + else { + errors.push(createCompilerDiagnosticForInvalidCustomType(opt)); + } + } + function convertJsonOptionOfListType(option, values, basePath, errors) { + return ts.filter(ts.map(values, function (v) { return convertJsonOption(option.element, v, basePath, errors); }), function (v) { return !!v; }); + } + function trimString(s) { + return typeof s.trim === "function" ? s.trim() : s.replace(/^[\s]+|[\s]+$/g, ""); + } + /** + * Tests for a path that ends in a recursive directory wildcard. + * Matches **, \**, **\, and \**\, but not a**b. + * + * NOTE: used \ in place of / above to avoid issues with multiline comments. + * + * Breakdown: + * (^|\/) # matches either the beginning of the string or a directory separator. + * \*\* # matches the recursive directory wildcard "**". + * \/?$ # matches an optional trailing directory separator at the end of the string. + */ + var invalidTrailingRecursionPattern = /(^|\/)\*\*\/?$/; + /** + * Tests for a path where .. appears after a recursive directory wildcard. + * Matches **\..\*, **\a\..\*, and **\.., but not ..\**\* + * + * NOTE: used \ in place of / above to avoid issues with multiline comments. + * + * Breakdown: + * (^|\/) # matches either the beginning of the string or a directory separator. + * \*\*\/ # matches a recursive directory wildcard "**" followed by a directory separator. + * (.*\/)? # optionally matches any number of characters followed by a directory separator. + * \.\. # matches a parent directory path component ".." + * ($|\/) # matches either the end of the string or a directory separator. + */ + var invalidDotDotAfterRecursiveWildcardPattern = /(^|\/)\*\*\/(.*\/)?\.\.($|\/)/; + /** + * Tests for a path containing a wildcard character in a directory component of the path. + * Matches \*\, \?\, and \a*b\, but not \a\ or \a\*. + * + * NOTE: used \ in place of / above to avoid issues with multiline comments. + * + * Breakdown: + * \/ # matches a directory separator. + * [^/]*? # matches any number of characters excluding directory separators (non-greedy). + * [*?] # matches either a wildcard character (* or ?) + * [^/]* # matches any number of characters excluding directory separators (greedy). + * \/ # matches a directory separator. + */ + var watchRecursivePattern = /\/[^/]*?[*?][^/]*\//; + /** + * Matches the portion of a wildcard path that does not contain wildcards. + * Matches \a of \a\*, or \a\b\c of \a\b\c\?\d. + * + * NOTE: used \ in place of / above to avoid issues with multiline comments. + * + * Breakdown: + * ^ # matches the beginning of the string + * [^*?]* # matches any number of non-wildcard characters + * (?=\/[^/]*[*?]) # lookahead that matches a directory separator followed by + * # a path component that contains at least one wildcard character (* or ?). + */ + var wildcardDirectoryPattern = /^[^*?]*(?=\/[^/]*[*?])/; + /** + * Expands an array of file specifications. + * + * @param filesSpecs The literal file names to include. + * @param includeSpecs The wildcard file specifications to include. + * @param excludeSpecs The wildcard file specifications to exclude. + * @param basePath The base path for any relative file specifications. + * @param options Compiler options. + * @param host The host used to resolve files and directories. + * @param errors An array for diagnostic reporting. + */ + function matchFileNames(filesSpecs, includeSpecs, excludeSpecs, basePath, options, host, errors, extraFileExtensions, jsonSourceFile) { + basePath = ts.normalizePath(basePath); + var validatedIncludeSpecs, validatedExcludeSpecs; + // The exclude spec list is converted into a regular expression, which allows us to quickly + // test whether a file or directory should be excluded before recursively traversing the + // file system. + if (includeSpecs) { + validatedIncludeSpecs = validateSpecs(includeSpecs, errors, /*allowTrailingRecursion*/ false, jsonSourceFile, "include"); + } + if (excludeSpecs) { + validatedExcludeSpecs = validateSpecs(excludeSpecs, errors, /*allowTrailingRecursion*/ true, jsonSourceFile, "exclude"); + } + // Wildcard directories (provided as part of a wildcard path) are stored in a + // file map that marks whether it was a regular wildcard match (with a `*` or `?` token), + // or a recursive directory. This information is used by filesystem watchers to monitor for + // new entries in these paths. + var wildcardDirectories = getWildcardDirectories(validatedIncludeSpecs, validatedExcludeSpecs, basePath, host.useCaseSensitiveFileNames); + var spec = { filesSpecs: filesSpecs, includeSpecs: includeSpecs, excludeSpecs: excludeSpecs, validatedIncludeSpecs: validatedIncludeSpecs, validatedExcludeSpecs: validatedExcludeSpecs, wildcardDirectories: wildcardDirectories }; + return getFileNamesFromConfigSpecs(spec, basePath, options, host, extraFileExtensions); + } + /** + * Gets the file names from the provided config file specs that contain, files, include, exclude and + * other properties needed to resolve the file names + * @param spec The config file specs extracted with file names to include, wildcards to include/exclude and other details + * @param basePath The base path for any relative file specifications. + * @param options Compiler options. + * @param host The host used to resolve files and directories. + * @param extraFileExtensions optionaly file extra file extension information from host + */ + /* @internal */ + function getFileNamesFromConfigSpecs(spec, basePath, options, host, extraFileExtensions) { + if (extraFileExtensions === void 0) { extraFileExtensions = []; } + basePath = ts.normalizePath(basePath); + var keyMapper = host.useCaseSensitiveFileNames ? ts.identity : ts.toLowerCase; + // Literal file names (provided via the "files" array in tsconfig.json) are stored in a + // file map with a possibly case insensitive key. We use this map later when when including + // wildcard paths. + var literalFileMap = ts.createMap(); + // Wildcard paths (provided via the "includes" array in tsconfig.json) are stored in a + // file map with a possibly case insensitive key. We use this map to store paths matched + // via wildcard, and to handle extension priority. + var wildcardFileMap = ts.createMap(); + // Wildcard paths of json files (provided via the "includes" array in tsconfig.json) are stored in a + // file map with a possibly case insensitive key. We use this map to store paths matched + // via wildcard of *.json kind + var wildCardJsonFileMap = ts.createMap(); + var filesSpecs = spec.filesSpecs, validatedIncludeSpecs = spec.validatedIncludeSpecs, validatedExcludeSpecs = spec.validatedExcludeSpecs, wildcardDirectories = spec.wildcardDirectories; + // Rather than requery this for each file and filespec, we query the supported extensions + // once and store it on the expansion context. + var supportedExtensions = ts.getSupportedExtensions(options, extraFileExtensions); + var supportedExtensionsWithJsonIfResolveJsonModule = ts.getSuppoertedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions); + // Literal files are always included verbatim. An "include" or "exclude" specification cannot + // remove a literal file. + if (filesSpecs) { + for (var _i = 0, filesSpecs_1 = filesSpecs; _i < filesSpecs_1.length; _i++) { + var fileName = filesSpecs_1[_i]; + var file = ts.getNormalizedAbsolutePath(fileName, basePath); + literalFileMap.set(keyMapper(file), file); + } + } + var jsonOnlyIncludeRegexes; + if (validatedIncludeSpecs && validatedIncludeSpecs.length > 0) { + var _loop_4 = function (file) { + if (ts.fileExtensionIs(file, ".json" /* Json */)) { + // Valid only if *.json specified + if (!jsonOnlyIncludeRegexes) { + var includes = validatedIncludeSpecs.filter(function (s) { return ts.endsWith(s, ".json" /* Json */); }); + var includeFilePatterns = ts.map(ts.getRegularExpressionsForWildcards(includes, basePath, "files"), function (pattern) { return "^" + pattern + "$"; }); + jsonOnlyIncludeRegexes = includeFilePatterns ? includeFilePatterns.map(function (pattern) { return ts.getRegexFromPattern(pattern, host.useCaseSensitiveFileNames); }) : ts.emptyArray; + } + var includeIndex = ts.findIndex(jsonOnlyIncludeRegexes, function (re) { return re.test(file); }); + if (includeIndex !== -1) { + var key_1 = keyMapper(file); + if (!literalFileMap.has(key_1) && !wildCardJsonFileMap.has(key_1)) { + wildCardJsonFileMap.set(key_1, file); + } + } + return "continue"; + } + // If we have already included a literal or wildcard path with a + // higher priority extension, we should skip this file. + // + // This handles cases where we may encounter both .ts and + // .d.ts (or .js if "allowJs" is enabled) in the same + // directory when they are compilation outputs. + if (hasFileWithHigherPriorityExtension(file, literalFileMap, wildcardFileMap, supportedExtensions, keyMapper)) { + return "continue"; + } + // We may have included a wildcard path with a lower priority + // extension due to the user-defined order of entries in the + // "include" array. If there is a lower priority extension in the + // same directory, we should remove it. + removeWildcardFilesWithLowerPriorityExtension(file, wildcardFileMap, supportedExtensions, keyMapper); + var key = keyMapper(file); + if (!literalFileMap.has(key) && !wildcardFileMap.has(key)) { + wildcardFileMap.set(key, file); + } + }; + for (var _a = 0, _b = host.readDirectory(basePath, supportedExtensionsWithJsonIfResolveJsonModule, validatedExcludeSpecs, validatedIncludeSpecs, /*depth*/ undefined); _a < _b.length; _a++) { + var file = _b[_a]; + _loop_4(file); + } + } + var literalFiles = ts.arrayFrom(literalFileMap.values()); + var wildcardFiles = ts.arrayFrom(wildcardFileMap.values()); + return { + fileNames: literalFiles.concat(wildcardFiles, ts.arrayFrom(wildCardJsonFileMap.values())), + wildcardDirectories: wildcardDirectories, + spec: spec + }; + } + ts.getFileNamesFromConfigSpecs = getFileNamesFromConfigSpecs; + function validateSpecs(specs, errors, allowTrailingRecursion, jsonSourceFile, specKey) { + return specs.filter(function (spec) { + var diag = specToDiagnostic(spec, allowTrailingRecursion); + if (diag !== undefined) { + errors.push(createDiagnostic(diag, spec)); + } + return diag === undefined; + }); + function createDiagnostic(message, spec) { + var element = ts.getTsConfigPropArrayElementValue(jsonSourceFile, specKey, spec); + return element ? + ts.createDiagnosticForNodeInSourceFile(jsonSourceFile, element, message, spec) : + ts.createCompilerDiagnostic(message, spec); + } + } + function specToDiagnostic(spec, allowTrailingRecursion) { + if (!allowTrailingRecursion && invalidTrailingRecursionPattern.test(spec)) { + return ts.Diagnostics.File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0; + } + else if (invalidDotDotAfterRecursiveWildcardPattern.test(spec)) { + return ts.Diagnostics.File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0; + } + } + /** + * Gets directories in a set of include patterns that should be watched for changes. + */ + function getWildcardDirectories(include, exclude, path, useCaseSensitiveFileNames) { + // We watch a directory recursively if it contains a wildcard anywhere in a directory segment + // of the pattern: + // + // /a/b/**/d - Watch /a/b recursively to catch changes to any d in any subfolder recursively + // /a/b/*/d - Watch /a/b recursively to catch any d in any immediate subfolder, even if a new subfolder is added + // /a/b - Watch /a/b recursively to catch changes to anything in any recursive subfoler + // + // We watch a directory without recursion if it contains a wildcard in the file segment of + // the pattern: + // + // /a/b/* - Watch /a/b directly to catch any new file + // /a/b/a?z - Watch /a/b directly to catch any new file matching a?z + var rawExcludeRegex = ts.getRegularExpressionForWildcard(exclude, path, "exclude"); + var excludeRegex = rawExcludeRegex && new RegExp(rawExcludeRegex, useCaseSensitiveFileNames ? "" : "i"); + var wildcardDirectories = {}; + if (include !== undefined) { + var recursiveKeys = []; + for (var _i = 0, include_1 = include; _i < include_1.length; _i++) { + var file = include_1[_i]; + var spec = ts.normalizePath(ts.combinePaths(path, file)); + if (excludeRegex && excludeRegex.test(spec)) { + continue; + } + var match = getWildcardDirectoryFromSpec(spec, useCaseSensitiveFileNames); + if (match) { + var key = match.key, flags = match.flags; + var existingFlags = wildcardDirectories[key]; + if (existingFlags === undefined || existingFlags < flags) { + wildcardDirectories[key] = flags; + if (flags === 1 /* Recursive */) { + recursiveKeys.push(key); + } + } + } + } + // Remove any subpaths under an existing recursively watched directory. + for (var key in wildcardDirectories) { + if (ts.hasProperty(wildcardDirectories, key)) { + for (var _a = 0, recursiveKeys_1 = recursiveKeys; _a < recursiveKeys_1.length; _a++) { + var recursiveKey = recursiveKeys_1[_a]; + if (key !== recursiveKey && ts.containsPath(recursiveKey, key, path, !useCaseSensitiveFileNames)) { + delete wildcardDirectories[key]; + } + } + } + } + } + return wildcardDirectories; + } + function getWildcardDirectoryFromSpec(spec, useCaseSensitiveFileNames) { + var match = wildcardDirectoryPattern.exec(spec); + if (match) { + return { + key: useCaseSensitiveFileNames ? match[0] : match[0].toLowerCase(), + flags: watchRecursivePattern.test(spec) ? 1 /* Recursive */ : 0 /* None */ + }; + } + if (ts.isImplicitGlob(spec)) { + return { key: spec, flags: 1 /* Recursive */ }; + } + return undefined; + } + /** + * Determines whether a literal or wildcard file has already been included that has a higher + * extension priority. + * + * @param file The path to the file. + * @param extensionPriority The priority of the extension. + * @param context The expansion context. + */ + function hasFileWithHigherPriorityExtension(file, literalFiles, wildcardFiles, extensions, keyMapper) { + var extensionPriority = ts.getExtensionPriority(file, extensions); + var adjustedExtensionPriority = ts.adjustExtensionPriority(extensionPriority, extensions); + for (var i = 0 /* Highest */; i < adjustedExtensionPriority; i++) { + var higherPriorityExtension = extensions[i]; + var higherPriorityPath = keyMapper(ts.changeExtension(file, higherPriorityExtension)); + if (literalFiles.has(higherPriorityPath) || wildcardFiles.has(higherPriorityPath)) { + return true; + } + } + return false; + } + /** + * Removes files included via wildcard expansion with a lower extension priority that have + * already been included. + * + * @param file The path to the file. + * @param extensionPriority The priority of the extension. + * @param context The expansion context. + */ + function removeWildcardFilesWithLowerPriorityExtension(file, wildcardFiles, extensions, keyMapper) { + var extensionPriority = ts.getExtensionPriority(file, extensions); + var nextExtensionPriority = ts.getNextLowestExtensionPriority(extensionPriority, extensions); + for (var i = nextExtensionPriority; i < extensions.length; i++) { + var lowerPriorityExtension = extensions[i]; + var lowerPriorityPath = keyMapper(ts.changeExtension(file, lowerPriorityExtension)); + wildcardFiles.delete(lowerPriorityPath); + } + } + /** + * Produces a cleaned version of compiler options with personally identifying info (aka, paths) removed. + * Also converts enum values back to strings. + */ + /* @internal */ + function convertCompilerOptionsForTelemetry(opts) { + var out = {}; + for (var key in opts) { + if (opts.hasOwnProperty(key)) { + var type = getOptionFromName(key); + if (type !== undefined) { // Ignore unknown options + out[key] = getOptionValueWithEmptyStrings(opts[key], type); + } + } + } + return out; + } + ts.convertCompilerOptionsForTelemetry = convertCompilerOptionsForTelemetry; + function getOptionValueWithEmptyStrings(value, option) { + switch (option.type) { + case "object": // "paths". Can't get any useful information from the value since we blank out strings, so just return "". + return ""; + case "string": // Could be any arbitrary string -- use empty string instead. + return ""; + case "number": // Allow numbers, but be sure to check it's actually a number. + return typeof value === "number" ? value : ""; + case "boolean": + return typeof value === "boolean" ? value : ""; + case "list": + var elementType_1 = option.element; + return ts.isArray(value) ? value.map(function (v) { return getOptionValueWithEmptyStrings(v, elementType_1); }) : ""; + default: + return ts.forEachEntry(option.type, function (optionEnumValue, optionStringValue) { + if (optionEnumValue === value) { + return optionStringValue; + } + }); // TODO: GH#18217 + } + } +})(ts || (ts = {})); +var ts; +(function (ts) { + function trace(host) { + host.trace(ts.formatMessage.apply(undefined, arguments)); + } + ts.trace = trace; + /* @internal */ + function isTraceEnabled(compilerOptions, host) { + return !!compilerOptions.traceResolution && host.trace !== undefined; + } + ts.isTraceEnabled = isTraceEnabled; + function withPackageId(packageId, r) { + return r && { path: r.path, extension: r.ext, packageId: packageId }; + } + function noPackageId(r) { + return withPackageId(/*packageId*/ undefined, r); + } + function removeIgnoredPackageId(r) { + if (r) { + ts.Debug.assert(r.packageId === undefined); + return { path: r.path, ext: r.extension }; + } + } + /** + * Kinds of file that we are currently looking for. + * Typically there is one pass with Extensions.TypeScript, then a second pass with Extensions.JavaScript. + */ + var Extensions; + (function (Extensions) { + Extensions[Extensions["TypeScript"] = 0] = "TypeScript"; + Extensions[Extensions["JavaScript"] = 1] = "JavaScript"; + Extensions[Extensions["Json"] = 2] = "Json"; + Extensions[Extensions["TSConfig"] = 3] = "TSConfig"; + Extensions[Extensions["DtsOnly"] = 4] = "DtsOnly"; /** Only '.d.ts' */ + })(Extensions || (Extensions = {})); + /** Used with `Extensions.DtsOnly` to extract the path from TypeScript results. */ + function resolvedTypeScriptOnly(resolved) { + if (!resolved) { + return undefined; + } + ts.Debug.assert(ts.extensionIsTS(resolved.extension)); + return { fileName: resolved.path, packageId: resolved.packageId }; + } + function createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations) { + return { + resolvedModule: resolved && { resolvedFileName: resolved.path, originalPath: resolved.originalPath === true ? undefined : resolved.originalPath, extension: resolved.extension, isExternalLibraryImport: isExternalLibraryImport, packageId: resolved.packageId }, + failedLookupLocations: failedLookupLocations + }; + } + function readPackageJsonField(jsonContent, fieldName, typeOfTag, state) { + if (!ts.hasProperty(jsonContent, fieldName)) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_does_not_have_a_0_field, fieldName); + } + return; + } + var value = jsonContent[fieldName]; + if (typeof value !== typeOfTag || value === null) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_1_got_2, fieldName, typeOfTag, value === null ? "null" : typeof value); + } + return; + } + return value; + } + function readPackageJsonPathField(jsonContent, fieldName, baseDirectory, state) { + var fileName = readPackageJsonField(jsonContent, fieldName, "string", state); + if (fileName === undefined) + return; + var path = ts.normalizePath(ts.combinePaths(baseDirectory, fileName)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, fileName, path); + } + return path; + } + function readPackageJsonTypesFields(jsonContent, baseDirectory, state) { + return readPackageJsonPathField(jsonContent, "typings", baseDirectory, state) + || readPackageJsonPathField(jsonContent, "types", baseDirectory, state); + } + function readPackageJsonTSConfigField(jsonContent, baseDirectory, state) { + return readPackageJsonPathField(jsonContent, "tsconfig", baseDirectory, state); + } + function readPackageJsonMainField(jsonContent, baseDirectory, state) { + return readPackageJsonPathField(jsonContent, "main", baseDirectory, state); + } + function readPackageJsonTypesVersionsField(jsonContent, state) { + var typesVersions = readPackageJsonField(jsonContent, "typesVersions", "object", state); + if (typesVersions === undefined) + return; + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_field_with_version_specific_path_mappings); + } + return typesVersions; + } + function readPackageJsonTypesVersionPaths(jsonContent, state) { + var typesVersions = readPackageJsonTypesVersionsField(jsonContent, state); + if (typesVersions === undefined) + return; + if (state.traceEnabled) { + for (var key in typesVersions) { + if (ts.hasProperty(typesVersions, key) && !ts.VersionRange.tryParse(key)) { + trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range, key); + } + } + } + var result = getPackageJsonTypesVersionsPaths(typesVersions); + if (!result) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_does_not_have_a_typesVersions_entry_that_matches_version_0, ts.versionMajorMinor); + } + return; + } + var bestVersionKey = result.version, bestVersionPaths = result.paths; + if (typeof bestVersionPaths !== "object") { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_1_got_2, "typesVersions['" + bestVersionKey + "']", "object", typeof bestVersionPaths); + } + return; + } + return result; + } + var typeScriptVersion; + /* @internal */ + function getPackageJsonTypesVersionsPaths(typesVersions) { + if (!typeScriptVersion) + typeScriptVersion = new ts.Version(ts.version); + for (var key in typesVersions) { + if (!ts.hasProperty(typesVersions, key)) + continue; + var keyRange = ts.VersionRange.tryParse(key); + if (keyRange === undefined) { + continue; + } + // return the first entry whose range matches the current compiler version. + if (keyRange.test(typeScriptVersion)) { + return { version: key, paths: typesVersions[key] }; + } + } + } + ts.getPackageJsonTypesVersionsPaths = getPackageJsonTypesVersionsPaths; + function getEffectiveTypeRoots(options, host) { + if (options.typeRoots) { + return options.typeRoots; + } + var currentDirectory; + if (options.configFilePath) { + currentDirectory = ts.getDirectoryPath(options.configFilePath); + } + else if (host.getCurrentDirectory) { + currentDirectory = host.getCurrentDirectory(); + } + if (currentDirectory !== undefined) { + return getDefaultTypeRoots(currentDirectory, host); + } + } + ts.getEffectiveTypeRoots = getEffectiveTypeRoots; + /** + * Returns the path to every node_modules/@types directory from some ancestor directory. + * Returns undefined if there are none. + */ + function getDefaultTypeRoots(currentDirectory, host) { + if (!host.directoryExists) { + return [ts.combinePaths(currentDirectory, nodeModulesAtTypes)]; + // And if it doesn't exist, tough. + } + var typeRoots; + ts.forEachAncestorDirectory(ts.normalizePath(currentDirectory), function (directory) { + var atTypes = ts.combinePaths(directory, nodeModulesAtTypes); + if (host.directoryExists(atTypes)) { + (typeRoots || (typeRoots = [])).push(atTypes); + } + return undefined; + }); + return typeRoots; + } + var nodeModulesAtTypes = ts.combinePaths("node_modules", "@types"); + /** + * @param {string | undefined} containingFile - file that contains type reference directive, can be undefined if containing file is unknown. + * This is possible in case if resolution is performed for directives specified via 'types' parameter. In this case initial path for secondary lookups + * is assumed to be the same as root directory of the project. + */ + function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host, redirectedReference) { + var traceEnabled = isTraceEnabled(options, host); + if (redirectedReference) { + options = redirectedReference.commandLine.options; + } + var failedLookupLocations = []; + var moduleResolutionState = { compilerOptions: options, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; + var typeRoots = getEffectiveTypeRoots(options, host); + if (traceEnabled) { + if (containingFile === undefined) { + if (typeRoots === undefined) { + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set, typeReferenceDirectiveName); + } + else { + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1, typeReferenceDirectiveName, typeRoots); + } + } + else { + if (typeRoots === undefined) { + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set, typeReferenceDirectiveName, containingFile); + } + else { + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_2, typeReferenceDirectiveName, containingFile, typeRoots); + } + } + if (redirectedReference) { + trace(host, ts.Diagnostics.Using_compiler_options_of_project_reference_redirect_0, redirectedReference.sourceFile.fileName); + } + } + var resolved = primaryLookup(); + var primary = true; + if (!resolved) { + resolved = secondaryLookup(); + primary = false; + } + var resolvedTypeReferenceDirective; + if (resolved) { + var fileName = resolved.fileName, packageId = resolved.packageId; + var resolvedFileName = options.preserveSymlinks ? fileName : realPath(fileName, host, traceEnabled); + if (traceEnabled) { + trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFileName, primary); + } + resolvedTypeReferenceDirective = { primary: primary, resolvedFileName: resolvedFileName, packageId: packageId, isExternalLibraryImport: pathContainsNodeModules(fileName) }; + } + return { resolvedTypeReferenceDirective: resolvedTypeReferenceDirective, failedLookupLocations: failedLookupLocations }; + function primaryLookup() { + // Check primary library paths + if (typeRoots && typeRoots.length) { + if (traceEnabled) { + trace(host, ts.Diagnostics.Resolving_with_primary_search_path_0, typeRoots.join(", ")); + } + return ts.firstDefined(typeRoots, function (typeRoot) { + var candidate = ts.combinePaths(typeRoot, typeReferenceDirectiveName); + var candidateDirectory = ts.getDirectoryPath(candidate); + var directoryExists = ts.directoryProbablyExists(candidateDirectory, host); + if (!directoryExists && traceEnabled) { + trace(host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, candidateDirectory); + } + return resolvedTypeScriptOnly(loadNodeModuleFromDirectory(Extensions.DtsOnly, candidate, !directoryExists, moduleResolutionState)); + }); + } + else { + if (traceEnabled) { + trace(host, ts.Diagnostics.Root_directory_cannot_be_determined_skipping_primary_search_paths); + } + } + } + function secondaryLookup() { + var initialLocationForSecondaryLookup = containingFile && ts.getDirectoryPath(containingFile); + if (initialLocationForSecondaryLookup !== undefined) { + // check secondary locations + if (traceEnabled) { + trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup); + } + var result = void 0; + if (!ts.isExternalModuleNameRelative(typeReferenceDirectiveName)) { + var searchResult = loadModuleFromNearestNodeModulesDirectory(Extensions.DtsOnly, typeReferenceDirectiveName, initialLocationForSecondaryLookup, moduleResolutionState, /*cache*/ undefined, /*redirectedReference*/ undefined); + result = searchResult && searchResult.value; + } + else { + var candidate = ts.normalizePathAndParts(ts.combinePaths(initialLocationForSecondaryLookup, typeReferenceDirectiveName)).path; + result = nodeLoadModuleByRelativeName(Extensions.DtsOnly, candidate, /*onlyRecordFailures*/ false, moduleResolutionState, /*considerPackageJson*/ true); + } + var resolvedFile = resolvedTypeScriptOnly(result); + if (!resolvedFile && traceEnabled) { + trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName); + } + return resolvedFile; + } + else { + if (traceEnabled) { + trace(host, ts.Diagnostics.Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder); + } + } + } + } + ts.resolveTypeReferenceDirective = resolveTypeReferenceDirective; + /** + * Given a set of options, returns the set of type directive names + * that should be included for this program automatically. + * This list could either come from the config file, + * or from enumerating the types root + initial secondary types lookup location. + * More type directives might appear in the program later as a result of loading actual source files; + * this list is only the set of defaults that are implicitly included. + */ + function getAutomaticTypeDirectiveNames(options, host) { + // Use explicit type list from tsconfig.json + if (options.types) { + return options.types; + } + // Walk the primary type lookup locations + var result = []; + if (host.directoryExists && host.getDirectories) { + var typeRoots = getEffectiveTypeRoots(options, host); + if (typeRoots) { + for (var _i = 0, typeRoots_1 = typeRoots; _i < typeRoots_1.length; _i++) { + var root = typeRoots_1[_i]; + if (host.directoryExists(root)) { + for (var _a = 0, _b = host.getDirectories(root); _a < _b.length; _a++) { + var typeDirectivePath = _b[_a]; + var normalized = ts.normalizePath(typeDirectivePath); + var packageJsonPath = ts.combinePaths(root, normalized, "package.json"); + // `types-publisher` sometimes creates packages with `"typings": null` for packages that don't provide their own types. + // See `createNotNeededPackageJSON` in the types-publisher` repo. + // tslint:disable-next-line:no-null-keyword + var isNotNeededPackage = host.fileExists(packageJsonPath) && ts.readJson(packageJsonPath, host).typings === null; + if (!isNotNeededPackage) { + var baseFileName = ts.getBaseFileName(normalized); + // At this stage, skip results with leading dot. + if (baseFileName.charCodeAt(0) !== 46 /* dot */) { + // Return just the type directive names + result.push(baseFileName); + } + } + } + } + } + } + } + return result; + } + ts.getAutomaticTypeDirectiveNames = getAutomaticTypeDirectiveNames; + function createModuleResolutionCache(currentDirectory, getCanonicalFileName) { + return createModuleResolutionCacheWithMaps(createCacheWithRedirects(), createCacheWithRedirects(), currentDirectory, getCanonicalFileName); + } + ts.createModuleResolutionCache = createModuleResolutionCache; + /*@internal*/ + function createCacheWithRedirects() { + var ownMap = ts.createMap(); + var redirectsMap = ts.createMap(); + return { + ownMap: ownMap, + redirectsMap: redirectsMap, + getOrCreateMapOfCacheRedirects: getOrCreateMapOfCacheRedirects, + clear: clear + }; + function getOrCreateMapOfCacheRedirects(redirectedReference) { + if (!redirectedReference) { + return ownMap; + } + var path = redirectedReference.sourceFile.path; + var redirects = redirectsMap.get(path); + if (!redirects) { + redirects = ts.createMap(); + redirectsMap.set(path, redirects); + } + return redirects; + } + function clear() { + ownMap.clear(); + redirectsMap.clear(); + } + } + ts.createCacheWithRedirects = createCacheWithRedirects; + /*@internal*/ + function createModuleResolutionCacheWithMaps(directoryToModuleNameMap, moduleNameToDirectoryMap, currentDirectory, getCanonicalFileName) { + return { getOrCreateCacheForDirectory: getOrCreateCacheForDirectory, getOrCreateCacheForModuleName: getOrCreateCacheForModuleName }; + function getOrCreateCacheForDirectory(directoryName, redirectedReference) { + var path = ts.toPath(directoryName, currentDirectory, getCanonicalFileName); + return getOrCreateCache(directoryToModuleNameMap, redirectedReference, path, ts.createMap); + } + function getOrCreateCacheForModuleName(nonRelativeModuleName, redirectedReference) { + ts.Debug.assert(!ts.isExternalModuleNameRelative(nonRelativeModuleName)); + return getOrCreateCache(moduleNameToDirectoryMap, redirectedReference, nonRelativeModuleName, createPerModuleNameCache); + } + function getOrCreateCache(cacheWithRedirects, redirectedReference, key, create) { + var cache = cacheWithRedirects.getOrCreateMapOfCacheRedirects(redirectedReference); + var result = cache.get(key); + if (!result) { + result = create(); + cache.set(key, result); + } + return result; + } + function createPerModuleNameCache() { + var directoryPathMap = ts.createMap(); + return { get: get, set: set }; + function get(directory) { + return directoryPathMap.get(ts.toPath(directory, currentDirectory, getCanonicalFileName)); + } + /** + * At first this function add entry directory -> module resolution result to the table. + * Then it computes the set of parent folders for 'directory' that should have the same module resolution result + * and for every parent folder in set it adds entry: parent -> module resolution. . + * Lets say we first directory name: /a/b/c/d/e and resolution result is: /a/b/bar.ts. + * Set of parent folders that should have the same result will be: + * [ + * /a/b/c/d, /a/b/c, /a/b + * ] + * this means that request for module resolution from file in any of these folder will be immediately found in cache. + */ + function set(directory, result) { + var path = ts.toPath(directory, currentDirectory, getCanonicalFileName); + // if entry is already in cache do nothing + if (directoryPathMap.has(path)) { + return; + } + directoryPathMap.set(path, result); + var resolvedFileName = result.resolvedModule && + (result.resolvedModule.originalPath || result.resolvedModule.resolvedFileName); + // find common prefix between directory and resolved file name + // this common prefix should be the shortest path that has the same resolution + // directory: /a/b/c/d/e + // resolvedFileName: /a/b/foo.d.ts + // commonPrefix: /a/b + // for failed lookups cache the result for every directory up to root + var commonPrefix = resolvedFileName && getCommonPrefix(path, resolvedFileName); + var current = path; + while (current !== commonPrefix) { + var parent = ts.getDirectoryPath(current); + if (parent === current || directoryPathMap.has(parent)) { + break; + } + directoryPathMap.set(parent, result); + current = parent; + } + } + function getCommonPrefix(directory, resolution) { + var resolutionDirectory = ts.toPath(ts.getDirectoryPath(resolution), currentDirectory, getCanonicalFileName); + // find first position where directory and resolution differs + var i = 0; + var limit = Math.min(directory.length, resolutionDirectory.length); + while (i < limit && directory.charCodeAt(i) === resolutionDirectory.charCodeAt(i)) { + i++; + } + if (i === directory.length && (resolutionDirectory.length === i || resolutionDirectory[i] === ts.directorySeparator)) { + return directory; + } + var rootLength = ts.getRootLength(directory); + if (i < rootLength) { + return undefined; + } + var sep = directory.lastIndexOf(ts.directorySeparator, i - 1); + if (sep === -1) { + return undefined; + } + return directory.substr(0, Math.max(sep, rootLength)); + } + } + } + ts.createModuleResolutionCacheWithMaps = createModuleResolutionCacheWithMaps; + function resolveModuleNameFromCache(moduleName, containingFile, cache) { + var containingDirectory = ts.getDirectoryPath(containingFile); + var perFolderCache = cache && cache.getOrCreateCacheForDirectory(containingDirectory); + return perFolderCache && perFolderCache.get(moduleName); + } + ts.resolveModuleNameFromCache = resolveModuleNameFromCache; + function resolveModuleName(moduleName, containingFile, compilerOptions, host, cache, redirectedReference) { + var traceEnabled = isTraceEnabled(compilerOptions, host); + if (redirectedReference) { + compilerOptions = redirectedReference.commandLine.options; + } + if (traceEnabled) { + trace(host, ts.Diagnostics.Resolving_module_0_from_1, moduleName, containingFile); + if (redirectedReference) { + trace(host, ts.Diagnostics.Using_compiler_options_of_project_reference_redirect_0, redirectedReference.sourceFile.fileName); + } + } + var containingDirectory = ts.getDirectoryPath(containingFile); + var perFolderCache = cache && cache.getOrCreateCacheForDirectory(containingDirectory, redirectedReference); + var result = perFolderCache && perFolderCache.get(moduleName); + if (result) { + if (traceEnabled) { + trace(host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory); + } + } + else { + var moduleResolution = compilerOptions.moduleResolution; + if (moduleResolution === undefined) { + moduleResolution = ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS ? ts.ModuleResolutionKind.NodeJs : ts.ModuleResolutionKind.Classic; + if (traceEnabled) { + trace(host, ts.Diagnostics.Module_resolution_kind_is_not_specified_using_0, ts.ModuleResolutionKind[moduleResolution]); + } + } + else { + if (traceEnabled) { + trace(host, ts.Diagnostics.Explicitly_specified_module_resolution_kind_Colon_0, ts.ModuleResolutionKind[moduleResolution]); + } + } + switch (moduleResolution) { + case ts.ModuleResolutionKind.NodeJs: + result = nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference); + break; + case ts.ModuleResolutionKind.Classic: + result = classicNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference); + break; + default: + return ts.Debug.fail("Unexpected moduleResolution: " + moduleResolution); + } + if (perFolderCache) { + perFolderCache.set(moduleName, result); + if (!ts.isExternalModuleNameRelative(moduleName)) { + // put result in per-module name cache + cache.getOrCreateCacheForModuleName(moduleName, redirectedReference).set(containingDirectory, result); + } + } + } + if (traceEnabled) { + if (result.resolvedModule) { + trace(host, ts.Diagnostics.Module_name_0_was_successfully_resolved_to_1, moduleName, result.resolvedModule.resolvedFileName); + } + else { + trace(host, ts.Diagnostics.Module_name_0_was_not_resolved, moduleName); + } + } + return result; + } + ts.resolveModuleName = resolveModuleName; + /** + * Any module resolution kind can be augmented with optional settings: 'baseUrl', 'paths' and 'rootDirs' - they are used to + * mitigate differences between design time structure of the project and its runtime counterpart so the same import name + * can be resolved successfully by TypeScript compiler and runtime module loader. + * If these settings are set then loading procedure will try to use them to resolve module name and it can of failure it will + * fallback to standard resolution routine. + * + * - baseUrl - this setting controls how non-relative module names are resolved. If this setting is specified then non-relative + * names will be resolved relative to baseUrl: i.e. if baseUrl is '/a/b' then candidate location to resolve module name 'c/d' will + * be '/a/b/c/d' + * - paths - this setting can only be used when baseUrl is specified. allows to tune how non-relative module names + * will be resolved based on the content of the module name. + * Structure of 'paths' compiler options + * 'paths': { + * pattern-1: [...substitutions], + * pattern-2: [...substitutions], + * ... + * pattern-n: [...substitutions] + * } + * Pattern here is a string that can contain zero or one '*' character. During module resolution module name will be matched against + * all patterns in the list. Matching for patterns that don't contain '*' means that module name must be equal to pattern respecting the case. + * If pattern contains '*' then to match pattern "*" module name must start with the and end with . + * denotes part of the module name between and . + * If module name can be matches with multiple patterns then pattern with the longest prefix will be picked. + * After selecting pattern we'll use list of substitutions to get candidate locations of the module and the try to load module + * from the candidate location. + * Substitution is a string that can contain zero or one '*'. To get candidate location from substitution we'll pick every + * substitution in the list and replace '*' with string. If candidate location is not rooted it + * will be converted to absolute using baseUrl. + * For example: + * baseUrl: /a/b/c + * "paths": { + * // match all module names + * "*": [ + * "*", // use matched name as is, + * // will be looked as /a/b/c/ + * + * "folder1/*" // substitution will convert matched name to 'folder1/', + * // since it is not rooted then final candidate location will be /a/b/c/folder1/ + * ], + * // match module names that start with 'components/' + * "components/*": [ "/root/components/*" ] // substitution will convert /components/folder1/ to '/root/components/folder1/', + * // it is rooted so it will be final candidate location + * } + * + * 'rootDirs' allows the project to be spreaded across multiple locations and resolve modules with relative names as if + * they were in the same location. For example lets say there are two files + * '/local/src/content/file1.ts' + * '/shared/components/contracts/src/content/protocols/file2.ts' + * After bundling content of '/shared/components/contracts/src' will be merged with '/local/src' so + * if file1 has the following import 'import {x} from "./protocols/file2"' it will be resolved successfully in runtime. + * 'rootDirs' provides the way to tell compiler that in order to get the whole project it should behave as if content of all + * root dirs were merged together. + * I.e. for the example above 'rootDirs' will have two entries: [ '/local/src', '/shared/components/contracts/src' ]. + * Compiler will first convert './protocols/file2' into absolute path relative to the location of containing file: + * '/local/src/content/protocols/file2' and try to load it - failure. + * Then it will search 'rootDirs' looking for a longest matching prefix of this absolute path and if such prefix is found - absolute path will + * be converted to a path relative to found rootDir entry './content/protocols/file2' (*). As a last step compiler will check all remaining + * entries in 'rootDirs', use them to build absolute path out of (*) and try to resolve module from this location. + */ + function tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, state) { + var resolved = tryLoadModuleUsingPathsIfEligible(extensions, moduleName, loader, state); + if (resolved) + return resolved.value; + if (!ts.isExternalModuleNameRelative(moduleName)) { + return tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, state); + } + else { + return tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, state); + } + } + function tryLoadModuleUsingPathsIfEligible(extensions, moduleName, loader, state) { + var _a = state.compilerOptions, baseUrl = _a.baseUrl, paths = _a.paths; + if (baseUrl && paths && !ts.pathIsRelative(moduleName)) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, baseUrl, moduleName); + trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName); + } + return tryLoadModuleUsingPaths(extensions, moduleName, baseUrl, paths, loader, /*onlyRecordFailures*/ false, state); + } + } + function tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, state) { + if (!state.compilerOptions.rootDirs) { + return undefined; + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0, moduleName); + } + var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); + var matchedRootDir; + var matchedNormalizedPrefix; + for (var _i = 0, _a = state.compilerOptions.rootDirs; _i < _a.length; _i++) { + var rootDir = _a[_i]; + // rootDirs are expected to be absolute + // in case of tsconfig.json this will happen automatically - compiler will expand relative names + // using location of tsconfig.json as base location + var normalizedRoot = ts.normalizePath(rootDir); + if (!ts.endsWith(normalizedRoot, ts.directorySeparator)) { + normalizedRoot += ts.directorySeparator; + } + var isLongestMatchingPrefix = ts.startsWith(candidate, normalizedRoot) && + (matchedNormalizedPrefix === undefined || matchedNormalizedPrefix.length < normalizedRoot.length); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Checking_if_0_is_the_longest_matching_prefix_for_1_2, normalizedRoot, candidate, isLongestMatchingPrefix); + } + if (isLongestMatchingPrefix) { + matchedNormalizedPrefix = normalizedRoot; + matchedRootDir = rootDir; + } + } + if (matchedNormalizedPrefix) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Longest_matching_prefix_for_0_is_1, candidate, matchedNormalizedPrefix); + } + var suffix = candidate.substr(matchedNormalizedPrefix.length); + // first - try to load from a initial location + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, matchedNormalizedPrefix, candidate); + } + var resolvedFileName = loader(extensions, candidate, !ts.directoryProbablyExists(containingDirectory, state.host), state); + if (resolvedFileName) { + return resolvedFileName; + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Trying_other_entries_in_rootDirs); + } + // then try to resolve using remaining entries in rootDirs + for (var _b = 0, _c = state.compilerOptions.rootDirs; _b < _c.length; _b++) { + var rootDir = _c[_b]; + if (rootDir === matchedRootDir) { + // skip the initially matched entry + continue; + } + var candidate_1 = ts.combinePaths(ts.normalizePath(rootDir), suffix); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, rootDir, candidate_1); + } + var baseDirectory = ts.getDirectoryPath(candidate_1); + var resolvedFileName_1 = loader(extensions, candidate_1, !ts.directoryProbablyExists(baseDirectory, state.host), state); + if (resolvedFileName_1) { + return resolvedFileName_1; + } + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Module_resolution_using_rootDirs_has_failed); + } + } + return undefined; + } + function tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, state) { + var baseUrl = state.compilerOptions.baseUrl; + if (!baseUrl) { + return undefined; + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, baseUrl, moduleName); + } + var candidate = ts.normalizePath(ts.combinePaths(baseUrl, moduleName)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, baseUrl, candidate); + } + return loader(extensions, candidate, !ts.directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); + } + /** + * Expose resolution logic to allow us to use Node module resolution logic from arbitrary locations. + * No way to do this with `require()`: https://github.com/nodejs/node/issues/5963 + * Throws an error if the module can't be resolved. + */ + /* @internal */ + function resolveJSModule(moduleName, initialDir, host) { + var _a = tryResolveJSModuleWorker(moduleName, initialDir, host), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; + if (!resolvedModule) { + throw new Error("Could not resolve JS module '" + moduleName + "' starting at '" + initialDir + "'. Looked in: " + failedLookupLocations.join(", ")); + } + return resolvedModule.resolvedFileName; + } + ts.resolveJSModule = resolveJSModule; + /* @internal */ + function tryResolveJSModule(moduleName, initialDir, host) { + var resolvedModule = tryResolveJSModuleWorker(moduleName, initialDir, host).resolvedModule; + return resolvedModule && resolvedModule.resolvedFileName; + } + ts.tryResolveJSModule = tryResolveJSModule; + var jsOnlyExtensions = [Extensions.JavaScript]; + var tsExtensions = [Extensions.TypeScript, Extensions.JavaScript]; + var tsPlusJsonExtensions = tsExtensions.concat([Extensions.Json]); + var tsconfigExtensions = [Extensions.TSConfig]; + function tryResolveJSModuleWorker(moduleName, initialDir, host) { + return nodeModuleNameResolverWorker(moduleName, initialDir, { moduleResolution: ts.ModuleResolutionKind.NodeJs, allowJs: true }, host, /*cache*/ undefined, jsOnlyExtensions, /*redirectedReferences*/ undefined); + } + function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference, lookupConfig) { + return nodeModuleNameResolverWorker(moduleName, ts.getDirectoryPath(containingFile), compilerOptions, host, cache, lookupConfig ? tsconfigExtensions : (compilerOptions.resolveJsonModule ? tsPlusJsonExtensions : tsExtensions), redirectedReference); + } + ts.nodeModuleNameResolver = nodeModuleNameResolver; + function nodeModuleNameResolverWorker(moduleName, containingDirectory, compilerOptions, host, cache, extensions, redirectedReference) { + var traceEnabled = isTraceEnabled(compilerOptions, host); + var failedLookupLocations = []; + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; + var result = ts.forEach(extensions, function (ext) { return tryResolve(ext); }); + if (result && result.value) { + var _a = result.value, resolved = _a.resolved, isExternalLibraryImport = _a.isExternalLibraryImport; + return createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations); + } + return { resolvedModule: undefined, failedLookupLocations: failedLookupLocations }; + function tryResolve(extensions) { + var loader = function (extensions, candidate, onlyRecordFailures, state) { return nodeLoadModuleByRelativeName(extensions, candidate, onlyRecordFailures, state, /*considerPackageJson*/ true); }; + var resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, state); + if (resolved) { + return toSearchResult({ resolved: resolved, isExternalLibraryImport: pathContainsNodeModules(resolved.path) }); + } + if (!ts.isExternalModuleNameRelative(moduleName)) { + if (traceEnabled) { + trace(host, ts.Diagnostics.Loading_module_0_from_node_modules_folder_target_file_type_1, moduleName, Extensions[extensions]); + } + var resolved_1 = loadModuleFromNearestNodeModulesDirectory(extensions, moduleName, containingDirectory, state, cache, redirectedReference); + if (!resolved_1) + return undefined; + var resolvedValue = resolved_1.value; + if (!compilerOptions.preserveSymlinks && resolvedValue && !resolvedValue.originalPath) { + var path = realPath(resolvedValue.path, host, traceEnabled); + var originalPath = path === resolvedValue.path ? undefined : resolvedValue.path; + resolvedValue = __assign({}, resolvedValue, { path: path, originalPath: originalPath }); + } + // For node_modules lookups, get the real path so that multiple accesses to an `npm link`-ed module do not create duplicate files. + return { value: resolvedValue && { resolved: resolvedValue, isExternalLibraryImport: true } }; + } + else { + var _a = ts.normalizePathAndParts(ts.combinePaths(containingDirectory, moduleName)), candidate = _a.path, parts = _a.parts; + var resolved_2 = nodeLoadModuleByRelativeName(extensions, candidate, /*onlyRecordFailures*/ false, state, /*considerPackageJson*/ true); + // Treat explicit "node_modules" import as an external library import. + return resolved_2 && toSearchResult({ resolved: resolved_2, isExternalLibraryImport: ts.contains(parts, "node_modules") }); + } + } + } + function realPath(path, host, traceEnabled) { + if (!host.realpath) { + return path; + } + var real = ts.normalizePath(host.realpath(path)); + if (traceEnabled) { + trace(host, ts.Diagnostics.Resolving_real_path_for_0_result_1, path, real); + } + ts.Debug.assert(host.fileExists(real), path + " linked to nonexistent file " + real); // tslint:disable-line + return real; + } + function nodeLoadModuleByRelativeName(extensions, candidate, onlyRecordFailures, state, considerPackageJson) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1, candidate, Extensions[extensions]); + } + if (!ts.hasTrailingDirectorySeparator(candidate)) { + if (!onlyRecordFailures) { + var parentOfCandidate = ts.getDirectoryPath(candidate); + if (!ts.directoryProbablyExists(parentOfCandidate, state.host)) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, parentOfCandidate); + } + onlyRecordFailures = true; + } + } + var resolvedFromFile = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state); + if (resolvedFromFile) { + var nm = considerPackageJson ? parseNodeModuleFromPath(resolvedFromFile) : undefined; + var packageInfo = nm && getPackageJsonInfo(nm.packageDirectory, nm.subModuleName, /*onlyRecordFailures*/ false, state); + var packageId = packageInfo && packageInfo.packageId; + return withPackageId(packageId, resolvedFromFile); + } + } + if (!onlyRecordFailures) { + var candidateExists = ts.directoryProbablyExists(candidate, state.host); + if (!candidateExists) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, candidate); + } + onlyRecordFailures = true; + } + } + return loadNodeModuleFromDirectory(extensions, candidate, onlyRecordFailures, state, considerPackageJson); + } + /*@internal*/ + ts.nodeModulesPathPart = "/node_modules/"; + /*@internal*/ + function pathContainsNodeModules(path) { + return ts.stringContains(path, ts.nodeModulesPathPart); + } + ts.pathContainsNodeModules = pathContainsNodeModules; + /** + * This will be called on the successfully resolved path from `loadModuleFromFile`. + * (Not neeeded for `loadModuleFromNodeModules` as that looks up the `package.json` as part of resolution.) + * + * packageDirectory is the directory of the package itself. + * subModuleName is the path within the package. + * For `blah/node_modules/foo/index.d.ts` this is { packageDirectory: "foo", subModuleName: "index.d.ts" }. (Part before "/node_modules/" is ignored.) + * For `/node_modules/foo/bar.d.ts` this is { packageDirectory: "foo", subModuleName": "bar/index.d.ts" }. + * For `/node_modules/@types/foo/bar/index.d.ts` this is { packageDirectory: "@types/foo", subModuleName: "bar/index.d.ts" }. + * For `/node_modules/foo/bar/index.d.ts` this is { packageDirectory: "foo", subModuleName": "bar/index.d.ts" }. + */ + function parseNodeModuleFromPath(resolved) { + var path = ts.normalizePath(resolved.path); + var idx = path.lastIndexOf(ts.nodeModulesPathPart); + if (idx === -1) { + return undefined; + } + var indexAfterNodeModules = idx + ts.nodeModulesPathPart.length; + var indexAfterPackageName = moveToNextDirectorySeparatorIfAvailable(path, indexAfterNodeModules); + if (path.charCodeAt(indexAfterNodeModules) === 64 /* at */) { + indexAfterPackageName = moveToNextDirectorySeparatorIfAvailable(path, indexAfterPackageName); + } + var packageDirectory = path.slice(0, indexAfterPackageName); + var subModuleName = ts.removeExtension(path.slice(indexAfterPackageName + 1), resolved.ext) + ".d.ts" /* Dts */; + return { packageDirectory: packageDirectory, subModuleName: subModuleName }; + } + function moveToNextDirectorySeparatorIfAvailable(path, prevSeparatorIndex) { + var nextSeparatorIndex = path.indexOf(ts.directorySeparator, prevSeparatorIndex + 1); + return nextSeparatorIndex === -1 ? prevSeparatorIndex : nextSeparatorIndex; + } + function addExtensionAndIndex(path) { + if (path === "") { + return "index.d.ts"; + } + if (ts.endsWith(path, ".d.ts")) { + return path; + } + if (path === "index" || ts.endsWith(path, "/index")) { + return path + ".d.ts"; + } + return path + "/index.d.ts"; + } + function loadModuleFromFileNoPackageId(extensions, candidate, onlyRecordFailures, state) { + return noPackageId(loadModuleFromFile(extensions, candidate, onlyRecordFailures, state)); + } + /** + * @param {boolean} onlyRecordFailures - if true then function won't try to actually load files but instead record all attempts as failures. This flag is necessary + * in cases when we know upfront that all load attempts will fail (because containing folder does not exists) however we still need to record all failed lookup locations. + */ + function loadModuleFromFile(extensions, candidate, onlyRecordFailures, state) { + if (extensions === Extensions.Json || extensions === Extensions.TSConfig) { + var extensionLess = ts.tryRemoveExtension(candidate, ".json" /* Json */); + return (extensionLess === undefined && extensions === Extensions.Json) ? undefined : tryAddingExtensions(extensionLess || candidate, extensions, onlyRecordFailures, state); + } + // First, try adding an extension. An import of "foo" could be matched by a file "foo.ts", or "foo.js" by "foo.js.ts" + var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, onlyRecordFailures, state); + if (resolvedByAddingExtension) { + return resolvedByAddingExtension; + } + // If that didn't work, try stripping a ".js" or ".jsx" extension and replacing it with a TypeScript one; + // e.g. "./foo.js" can be matched by "./foo.ts" or "./foo.d.ts" + if (ts.hasJSFileExtension(candidate)) { + var extensionless = ts.removeFileExtension(candidate); + if (state.traceEnabled) { + var extension = candidate.substring(extensionless.length); + trace(state.host, ts.Diagnostics.File_name_0_has_a_1_extension_stripping_it, candidate, extension); + } + return tryAddingExtensions(extensionless, extensions, onlyRecordFailures, state); + } + } + /** Try to return an existing file that adds one of the `extensions` to `candidate`. */ + function tryAddingExtensions(candidate, extensions, onlyRecordFailures, state) { + if (!onlyRecordFailures) { + // check if containing folder exists - if it doesn't then just record failures for all supported extensions without disk probing + var directory = ts.getDirectoryPath(candidate); + if (directory) { + onlyRecordFailures = !ts.directoryProbablyExists(directory, state.host); + } + } + switch (extensions) { + case Extensions.DtsOnly: + return tryExtension(".d.ts" /* Dts */); + case Extensions.TypeScript: + return tryExtension(".ts" /* Ts */) || tryExtension(".tsx" /* Tsx */) || tryExtension(".d.ts" /* Dts */); + case Extensions.JavaScript: + return tryExtension(".js" /* Js */) || tryExtension(".jsx" /* Jsx */); + case Extensions.TSConfig: + case Extensions.Json: + return tryExtension(".json" /* Json */); + } + function tryExtension(ext) { + var path = tryFile(candidate + ext, onlyRecordFailures, state); + return path === undefined ? undefined : { path: path, ext: ext }; + } + } + /** Return the file if it exists. */ + function tryFile(fileName, onlyRecordFailures, state) { + if (!onlyRecordFailures) { + if (state.host.fileExists(fileName)) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_exist_use_it_as_a_name_resolution_result, fileName); + } + return fileName; + } + else { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_does_not_exist, fileName); + } + } + } + state.failedLookupLocations.push(fileName); + return undefined; + } + function loadNodeModuleFromDirectory(extensions, candidate, onlyRecordFailures, state, considerPackageJson) { + if (considerPackageJson === void 0) { considerPackageJson = true; } + var packageInfo = considerPackageJson ? getPackageJsonInfo(candidate, "", onlyRecordFailures, state) : undefined; + var packageId = packageInfo && packageInfo.packageId; + var packageJsonContent = packageInfo && packageInfo.packageJsonContent; + var versionPaths = packageJsonContent && readPackageJsonTypesVersionPaths(packageJsonContent, state); + return withPackageId(packageId, loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths)); + } + function getPackageJsonInfo(packageDirectory, subModuleName, onlyRecordFailures, state) { + var host = state.host, traceEnabled = state.traceEnabled; + var directoryExists = !onlyRecordFailures && ts.directoryProbablyExists(packageDirectory, host); + var packageJsonPath = ts.combinePaths(packageDirectory, "package.json"); + if (directoryExists && host.fileExists(packageJsonPath)) { + var packageJsonContent = ts.readJson(packageJsonPath, host); + if (subModuleName === "") { // looking up the root - need to handle types/typings/main redirects for subModuleName + var path = readPackageJsonTypesFields(packageJsonContent, packageDirectory, state); + if (typeof path === "string") { + subModuleName = addExtensionAndIndex(path.substring(packageDirectory.length + 1)); + } + else { + var jsPath = readPackageJsonMainField(packageJsonContent, packageDirectory, state); + if (typeof jsPath === "string" && jsPath.length > packageDirectory.length) { + var potentialSubModule_1 = jsPath.substring(packageDirectory.length + 1); + subModuleName = (ts.forEach(ts.supportedJSExtensions, function (extension) { + return ts.tryRemoveExtension(potentialSubModule_1, extension); + }) || potentialSubModule_1) + ".d.ts" /* Dts */; + } + else { + subModuleName = "index.d.ts"; + } + } + } + if (!ts.endsWith(subModuleName, ".d.ts" /* Dts */)) { + subModuleName = addExtensionAndIndex(subModuleName); + } + var versionPaths = readPackageJsonTypesVersionPaths(packageJsonContent, state); + var packageId = typeof packageJsonContent.name === "string" && typeof packageJsonContent.version === "string" + ? { name: packageJsonContent.name, subModuleName: subModuleName, version: packageJsonContent.version } + : undefined; + if (traceEnabled) { + if (packageId) { + trace(host, ts.Diagnostics.Found_package_json_at_0_Package_ID_is_1, packageJsonPath, ts.packageIdToString(packageId)); + } + else { + trace(host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); + } + } + return { packageJsonContent: packageJsonContent, packageId: packageId, versionPaths: versionPaths }; + } + else { + if (directoryExists && traceEnabled) { + trace(host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath); + } + // record package json as one of failed lookup locations - in the future if this file will appear it will invalidate resolution results + state.failedLookupLocations.push(packageJsonPath); + } + } + function loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, jsonContent, versionPaths) { + var packageFile; + if (jsonContent) { + switch (extensions) { + case Extensions.JavaScript: + case Extensions.Json: + packageFile = readPackageJsonMainField(jsonContent, candidate, state); + break; + case Extensions.TypeScript: + // When resolving typescript modules, try resolving using main field as well + packageFile = readPackageJsonTypesFields(jsonContent, candidate, state) || readPackageJsonMainField(jsonContent, candidate, state); + break; + case Extensions.DtsOnly: + packageFile = readPackageJsonTypesFields(jsonContent, candidate, state); + break; + case Extensions.TSConfig: + packageFile = readPackageJsonTSConfigField(jsonContent, candidate, state); + break; + default: + return ts.Debug.assertNever(extensions); + } + } + var loader = function (extensions, candidate, onlyRecordFailures, state) { + var fromFile = tryFile(candidate, onlyRecordFailures, state); + if (fromFile) { + var resolved = resolvedIfExtensionMatches(extensions, fromFile); + if (resolved) { + return noPackageId(resolved); + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_has_an_unsupported_extension_so_skipping_it, fromFile); + } + } + // Even if extensions is DtsOnly, we can still look up a .ts file as a result of package.json "types" + var nextExtensions = extensions === Extensions.DtsOnly ? Extensions.TypeScript : extensions; + // Don't do package.json lookup recursively, because Node.js' package lookup doesn't. + return nodeLoadModuleByRelativeName(nextExtensions, candidate, onlyRecordFailures, state, /*considerPackageJson*/ false); + }; + var onlyRecordFailuresForPackageFile = packageFile ? !ts.directoryProbablyExists(ts.getDirectoryPath(packageFile), state.host) : undefined; + var onlyRecordFailuresForIndex = onlyRecordFailures || !ts.directoryProbablyExists(candidate, state.host); + var indexPath = ts.combinePaths(candidate, extensions === Extensions.TSConfig ? "tsconfig" : "index"); + if (versionPaths && (!packageFile || ts.containsPath(candidate, packageFile))) { + var moduleName = ts.getRelativePathFromDirectory(candidate, packageFile || indexPath, /*ignoreCase*/ false); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2, versionPaths.version, ts.version, moduleName); + } + var result = tryLoadModuleUsingPaths(extensions, moduleName, candidate, versionPaths.paths, loader, onlyRecordFailuresForPackageFile || onlyRecordFailuresForIndex, state); + if (result) { + return removeIgnoredPackageId(result.value); + } + } + // It won't have a `packageId` set, because we disabled `considerPackageJson`. + var packageFileResult = packageFile && removeIgnoredPackageId(loader(extensions, packageFile, onlyRecordFailuresForPackageFile, state)); + if (packageFileResult) + return packageFileResult; + return loadModuleFromFile(extensions, indexPath, onlyRecordFailuresForIndex, state); + } + /** Resolve from an arbitrarily specified file. Return `undefined` if it has an unsupported extension. */ + function resolvedIfExtensionMatches(extensions, path) { + var ext = ts.tryGetExtensionFromPath(path); + return ext !== undefined && extensionIsOk(extensions, ext) ? { path: path, ext: ext } : undefined; + } + /** True if `extension` is one of the supported `extensions`. */ + function extensionIsOk(extensions, extension) { + switch (extensions) { + case Extensions.JavaScript: + return extension === ".js" /* Js */ || extension === ".jsx" /* Jsx */; + case Extensions.TSConfig: + case Extensions.Json: + return extension === ".json" /* Json */; + case Extensions.TypeScript: + return extension === ".ts" /* Ts */ || extension === ".tsx" /* Tsx */ || extension === ".d.ts" /* Dts */; + case Extensions.DtsOnly: + return extension === ".d.ts" /* Dts */; + } + } + /* @internal */ + function parsePackageName(moduleName) { + var idx = moduleName.indexOf(ts.directorySeparator); + if (moduleName[0] === "@") { + idx = moduleName.indexOf(ts.directorySeparator, idx + 1); + } + return idx === -1 ? { packageName: moduleName, rest: "" } : { packageName: moduleName.slice(0, idx), rest: moduleName.slice(idx + 1) }; + } + ts.parsePackageName = parsePackageName; + function loadModuleFromNearestNodeModulesDirectory(extensions, moduleName, directory, state, cache, redirectedReference) { + return loadModuleFromNearestNodeModulesDirectoryWorker(extensions, moduleName, directory, state, /*typesScopeOnly*/ false, cache, redirectedReference); + } + function loadModuleFromNearestNodeModulesDirectoryTypesScope(moduleName, directory, state) { + // Extensions parameter here doesn't actually matter, because typesOnly ensures we're just doing @types lookup, which is always DtsOnly. + return loadModuleFromNearestNodeModulesDirectoryWorker(Extensions.DtsOnly, moduleName, directory, state, /*typesScopeOnly*/ true, /*cache*/ undefined, /*redirectedReference*/ undefined); + } + function loadModuleFromNearestNodeModulesDirectoryWorker(extensions, moduleName, directory, state, typesScopeOnly, cache, redirectedReference) { + var perModuleNameCache = cache && cache.getOrCreateCacheForModuleName(moduleName, redirectedReference); + return ts.forEachAncestorDirectory(ts.normalizeSlashes(directory), function (ancestorDirectory) { + if (ts.getBaseFileName(ancestorDirectory) !== "node_modules") { + var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, ancestorDirectory, state); + if (resolutionFromCache) { + return resolutionFromCache; + } + return toSearchResult(loadModuleFromImmediateNodeModulesDirectory(extensions, moduleName, ancestorDirectory, state, typesScopeOnly)); + } + }); + } + function loadModuleFromImmediateNodeModulesDirectory(extensions, moduleName, directory, state, typesScopeOnly) { + var nodeModulesFolder = ts.combinePaths(directory, "node_modules"); + var nodeModulesFolderExists = ts.directoryProbablyExists(nodeModulesFolder, state.host); + if (!nodeModulesFolderExists && state.traceEnabled) { + trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, nodeModulesFolder); + } + var packageResult = typesScopeOnly ? undefined : loadModuleFromSpecificNodeModulesDirectory(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, state); + if (packageResult) { + return packageResult; + } + if (extensions === Extensions.TypeScript || extensions === Extensions.DtsOnly) { + var nodeModulesAtTypes_1 = ts.combinePaths(nodeModulesFolder, "@types"); + var nodeModulesAtTypesExists = nodeModulesFolderExists; + if (nodeModulesFolderExists && !ts.directoryProbablyExists(nodeModulesAtTypes_1, state.host)) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, nodeModulesAtTypes_1); + } + nodeModulesAtTypesExists = false; + } + return loadModuleFromSpecificNodeModulesDirectory(Extensions.DtsOnly, mangleScopedPackageNameWithTrace(moduleName, state), nodeModulesAtTypes_1, nodeModulesAtTypesExists, state); + } + } + function loadModuleFromSpecificNodeModulesDirectory(extensions, moduleName, nodeModulesDirectory, nodeModulesDirectoryExists, state) { + var candidate = ts.normalizePath(ts.combinePaths(nodeModulesDirectory, moduleName)); + // First look for a nested package.json, as in `node_modules/foo/bar/package.json`. + var packageJsonContent; + var packageId; + var versionPaths; + var packageInfo = getPackageJsonInfo(candidate, "", !nodeModulesDirectoryExists, state); + if (packageInfo) { + (packageJsonContent = packageInfo.packageJsonContent, packageId = packageInfo.packageId, versionPaths = packageInfo.versionPaths); + var fromFile = loadModuleFromFile(extensions, candidate, !nodeModulesDirectoryExists, state); + if (fromFile) { + return noPackageId(fromFile); + } + var fromDirectory = loadNodeModuleFromDirectoryWorker(extensions, candidate, !nodeModulesDirectoryExists, state, packageJsonContent, versionPaths); + return withPackageId(packageId, fromDirectory); + } + var loader = function (extensions, candidate, onlyRecordFailures, state) { + var pathAndExtension = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state) || + loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths); + return withPackageId(packageId, pathAndExtension); + }; + var _a = parsePackageName(moduleName), packageName = _a.packageName, rest = _a.rest; + if (rest !== "") { // If "rest" is empty, we just did this search above. + var packageDirectory = ts.combinePaths(nodeModulesDirectory, packageName); + // Don't use a "types" or "main" from here because we're not loading the root, but a subdirectory -- just here for the packageId and path mappings. + var packageInfo_1 = getPackageJsonInfo(packageDirectory, rest, !nodeModulesDirectoryExists, state); + if (packageInfo_1) + (packageId = packageInfo_1.packageId, versionPaths = packageInfo_1.versionPaths); + if (versionPaths) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2, versionPaths.version, ts.version, rest); + } + var packageDirectoryExists = nodeModulesDirectoryExists && ts.directoryProbablyExists(packageDirectory, state.host); + var fromPaths = tryLoadModuleUsingPaths(extensions, rest, packageDirectory, versionPaths.paths, loader, !packageDirectoryExists, state); + if (fromPaths) { + return fromPaths.value; + } + } + } + return loader(extensions, candidate, !nodeModulesDirectoryExists, state); + } + function tryLoadModuleUsingPaths(extensions, moduleName, baseDirectory, paths, loader, onlyRecordFailures, state) { + var matchedPattern = ts.matchPatternOrExact(ts.getOwnKeys(paths), moduleName); + if (matchedPattern) { + var matchedStar_1 = ts.isString(matchedPattern) ? undefined : ts.matchedText(matchedPattern, moduleName); + var matchedPatternText = ts.isString(matchedPattern) ? matchedPattern : ts.patternText(matchedPattern); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText); + } + var resolved = ts.forEach(paths[matchedPatternText], function (subst) { + var path = matchedStar_1 ? subst.replace("*", matchedStar_1) : subst; + var candidate = ts.normalizePath(ts.combinePaths(baseDirectory, path)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path); + } + // A path mapping may have an extension, in contrast to an import, which should omit it. + var extension = ts.tryGetExtensionFromPath(candidate); + if (extension !== undefined) { + var path_1 = tryFile(candidate, onlyRecordFailures, state); + if (path_1 !== undefined) { + return noPackageId({ path: path_1, ext: extension }); + } + } + return loader(extensions, candidate, onlyRecordFailures || !ts.directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); + }); + return { value: resolved }; + } + } + /** Double underscores are used in DefinitelyTyped to delimit scoped packages. */ + var mangledScopedPackageSeparator = "__"; + /** For a scoped package, we must look in `@types/foo__bar` instead of `@types/@foo/bar`. */ + function mangleScopedPackageNameWithTrace(packageName, state) { + var mangled = mangleScopedPackageName(packageName); + if (state.traceEnabled && mangled !== packageName) { + trace(state.host, ts.Diagnostics.Scoped_package_detected_looking_in_0, mangled); + } + return mangled; + } + /* @internal */ + function getTypesPackageName(packageName) { + return "@types/" + mangleScopedPackageName(packageName); + } + ts.getTypesPackageName = getTypesPackageName; + /* @internal */ + function mangleScopedPackageName(packageName) { + if (ts.startsWith(packageName, "@")) { + var replaceSlash = packageName.replace(ts.directorySeparator, mangledScopedPackageSeparator); + if (replaceSlash !== packageName) { + return replaceSlash.slice(1); // Take off the "@" + } + } + return packageName; + } + ts.mangleScopedPackageName = mangleScopedPackageName; + /* @internal */ + function getPackageNameFromTypesPackageName(mangledName) { + var withoutAtTypePrefix = ts.removePrefix(mangledName, "@types/"); + if (withoutAtTypePrefix !== mangledName) { + return unmangleScopedPackageName(withoutAtTypePrefix); + } + return mangledName; + } + ts.getPackageNameFromTypesPackageName = getPackageNameFromTypesPackageName; + /* @internal */ + function unmangleScopedPackageName(typesPackageName) { + return ts.stringContains(typesPackageName, mangledScopedPackageSeparator) ? + "@" + typesPackageName.replace(mangledScopedPackageSeparator, ts.directorySeparator) : + typesPackageName; + } + ts.unmangleScopedPackageName = unmangleScopedPackageName; + function tryFindNonRelativeModuleNameInCache(cache, moduleName, containingDirectory, state) { + var _a; + var result = cache && cache.get(containingDirectory); + if (result) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory); + } + (_a = state.failedLookupLocations).push.apply(_a, result.failedLookupLocations); + return { value: result.resolvedModule && { path: result.resolvedModule.resolvedFileName, originalPath: result.resolvedModule.originalPath || true, extension: result.resolvedModule.extension, packageId: result.resolvedModule.packageId } }; + } + } + function classicNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference) { + var traceEnabled = isTraceEnabled(compilerOptions, host); + var failedLookupLocations = []; + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; + var containingDirectory = ts.getDirectoryPath(containingFile); + var resolved = tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript); + // No originalPath because classic resolution doesn't resolve realPath + return createResolvedModuleWithFailedLookupLocations(resolved && resolved.value, /*isExternalLibraryImport*/ false, failedLookupLocations); + function tryResolve(extensions) { + var resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFileNoPackageId, state); + if (resolvedUsingSettings) { + return { value: resolvedUsingSettings }; + } + if (!ts.isExternalModuleNameRelative(moduleName)) { + var perModuleNameCache_1 = cache && cache.getOrCreateCacheForModuleName(moduleName, redirectedReference); + // Climb up parent directories looking for a module. + var resolved_3 = ts.forEachAncestorDirectory(containingDirectory, function (directory) { + var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache_1, moduleName, directory, state); + if (resolutionFromCache) { + return resolutionFromCache; + } + var searchName = ts.normalizePath(ts.combinePaths(directory, moduleName)); + return toSearchResult(loadModuleFromFileNoPackageId(extensions, searchName, /*onlyRecordFailures*/ false, state)); + }); + if (resolved_3) { + return resolved_3; + } + if (extensions === Extensions.TypeScript) { + // If we didn't find the file normally, look it up in @types. + return loadModuleFromNearestNodeModulesDirectoryTypesScope(moduleName, containingDirectory, state); + } + } + else { + var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); + return toSearchResult(loadModuleFromFileNoPackageId(extensions, candidate, /*onlyRecordFailures*/ false, state)); + } + } + } + ts.classicNameResolver = classicNameResolver; + /** + * LSHost may load a module from a global cache of typings. + * This is the minumum code needed to expose that functionality; the rest is in LSHost. + */ + /* @internal */ + function loadModuleFromGlobalCache(moduleName, projectName, compilerOptions, host, globalCache) { + var traceEnabled = isTraceEnabled(compilerOptions, host); + if (traceEnabled) { + trace(host, ts.Diagnostics.Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2, projectName, moduleName, globalCache); + } + var failedLookupLocations = []; + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; + var resolved = loadModuleFromImmediateNodeModulesDirectory(Extensions.DtsOnly, moduleName, globalCache, state, /*typesScopeOnly*/ false); + return createResolvedModuleWithFailedLookupLocations(resolved, /*isExternalLibraryImport*/ true, failedLookupLocations); + } + ts.loadModuleFromGlobalCache = loadModuleFromGlobalCache; + /** + * Wraps value to SearchResult. + * @returns undefined if value is undefined or { value } otherwise + */ + function toSearchResult(value) { + return value !== undefined ? { value: value } : undefined; + } +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var ModuleInstanceState; + (function (ModuleInstanceState) { + ModuleInstanceState[ModuleInstanceState["NonInstantiated"] = 0] = "NonInstantiated"; + ModuleInstanceState[ModuleInstanceState["Instantiated"] = 1] = "Instantiated"; + ModuleInstanceState[ModuleInstanceState["ConstEnumOnly"] = 2] = "ConstEnumOnly"; + })(ModuleInstanceState = ts.ModuleInstanceState || (ts.ModuleInstanceState = {})); + function getModuleInstanceState(node) { + return node.body ? getModuleInstanceStateWorker(node.body) : 1 /* Instantiated */; + } + ts.getModuleInstanceState = getModuleInstanceState; + function getModuleInstanceStateWorker(node) { + // A module is uninstantiated if it contains only + switch (node.kind) { + // 1. interface declarations, type alias declarations + case 241 /* InterfaceDeclaration */: + case 242 /* TypeAliasDeclaration */: + return 0 /* NonInstantiated */; + // 2. const enum declarations + case 243 /* EnumDeclaration */: + if (ts.isEnumConst(node)) { + return 2 /* ConstEnumOnly */; + } + break; + // 3. non-exported import declarations + case 249 /* ImportDeclaration */: + case 248 /* ImportEqualsDeclaration */: + if (!(ts.hasModifier(node, 1 /* Export */))) { + return 0 /* NonInstantiated */; + } + break; + // 4. other uninstantiated module declarations. + case 245 /* ModuleBlock */: { + var state_1 = 0 /* NonInstantiated */; + ts.forEachChild(node, function (n) { + var childState = getModuleInstanceStateWorker(n); + switch (childState) { + case 0 /* NonInstantiated */: + // child is non-instantiated - continue searching + return; + case 2 /* ConstEnumOnly */: + // child is const enum only - record state and continue searching + state_1 = 2 /* ConstEnumOnly */; + return; + case 1 /* Instantiated */: + // child is instantiated - record state and stop + state_1 = 1 /* Instantiated */; + return true; + default: + ts.Debug.assertNever(childState); + } + }); + return state_1; + } + case 244 /* ModuleDeclaration */: + return getModuleInstanceState(node); + case 72 /* Identifier */: + // Only jsdoc typedef definition can exist in jsdoc namespace, and it should + // be considered the same as type alias + if (node.isInJSDocNamespace) { + return 0 /* NonInstantiated */; + } + } + return 1 /* Instantiated */; + } + var ContainerFlags; + (function (ContainerFlags) { + // The current node is not a container, and no container manipulation should happen before + // recursing into it. + ContainerFlags[ContainerFlags["None"] = 0] = "None"; + // The current node is a container. It should be set as the current container (and block- + // container) before recursing into it. The current node does not have locals. Examples: + // + // Classes, ObjectLiterals, TypeLiterals, Interfaces... + ContainerFlags[ContainerFlags["IsContainer"] = 1] = "IsContainer"; + // The current node is a block-scoped-container. It should be set as the current block- + // container before recursing into it. Examples: + // + // Blocks (when not parented by functions), Catch clauses, For/For-in/For-of statements... + ContainerFlags[ContainerFlags["IsBlockScopedContainer"] = 2] = "IsBlockScopedContainer"; + // The current node is the container of a control flow path. The current control flow should + // be saved and restored, and a new control flow initialized within the container. + ContainerFlags[ContainerFlags["IsControlFlowContainer"] = 4] = "IsControlFlowContainer"; + ContainerFlags[ContainerFlags["IsFunctionLike"] = 8] = "IsFunctionLike"; + ContainerFlags[ContainerFlags["IsFunctionExpression"] = 16] = "IsFunctionExpression"; + ContainerFlags[ContainerFlags["HasLocals"] = 32] = "HasLocals"; + ContainerFlags[ContainerFlags["IsInterface"] = 64] = "IsInterface"; + ContainerFlags[ContainerFlags["IsObjectLiteralOrClassExpressionMethod"] = 128] = "IsObjectLiteralOrClassExpressionMethod"; + })(ContainerFlags || (ContainerFlags = {})); + var binder = createBinder(); + function bindSourceFile(file, options) { + ts.performance.mark("beforeBind"); + binder(file, options); + ts.performance.mark("afterBind"); + ts.performance.measure("Bind", "beforeBind", "afterBind"); + } + ts.bindSourceFile = bindSourceFile; + function createBinder() { + var file; + var options; + var languageVersion; + var parent; + var container; + var thisParentContainer; // Container one level up + var blockScopeContainer; + var lastContainer; + var delayedTypeAliases; + var seenThisKeyword; + // state used by control flow analysis + var currentFlow; + var currentBreakTarget; + var currentContinueTarget; + var currentReturnTarget; + var currentTrueTarget; + var currentFalseTarget; + var preSwitchCaseFlow; + var activeLabels; + var hasExplicitReturn; + // state used for emit helpers + var emitFlags; + // If this file is an external module, then it is automatically in strict-mode according to + // ES6. If it is not an external module, then we'll determine if it is in strict mode or + // not depending on if we see "use strict" in certain places or if we hit a class/namespace + // or if compiler options contain alwaysStrict. + var inStrictMode; + var symbolCount = 0; + var Symbol; // tslint:disable-line variable-name + var classifiableNames; + var unreachableFlow = { flags: 1 /* Unreachable */ }; + var reportedUnreachableFlow = { flags: 1 /* Unreachable */ }; + // state used to aggregate transform flags during bind. + var subtreeTransformFlags = 0 /* None */; + var skipTransformFlagAggregation; + /** + * Inside the binder, we may create a diagnostic for an as-yet unbound node (with potentially no parent pointers, implying no accessible source file) + * If so, the node _must_ be in the current file (as that's the only way anything could have traversed to it to yield it as the error node) + * This version of `createDiagnosticForNode` uses the binder's context to account for this, and always yields correct diagnostics even in these situations. + */ + function createDiagnosticForNode(node, message, arg0, arg1, arg2) { + return ts.createDiagnosticForNodeInSourceFile(ts.getSourceFileOfNode(node) || file, node, message, arg0, arg1, arg2); + } + function bindSourceFile(f, opts) { + file = f; + options = opts; + languageVersion = ts.getEmitScriptTarget(options); + inStrictMode = bindInStrictMode(file, opts); + classifiableNames = ts.createUnderscoreEscapedMap(); + symbolCount = 0; + skipTransformFlagAggregation = file.isDeclarationFile; + Symbol = ts.objectAllocator.getSymbolConstructor(); + if (!file.locals) { + bind(file); + file.symbolCount = symbolCount; + file.classifiableNames = classifiableNames; + delayedBindJSDocTypedefTag(); + } + file = undefined; + options = undefined; + languageVersion = undefined; + parent = undefined; + container = undefined; + thisParentContainer = undefined; + blockScopeContainer = undefined; + lastContainer = undefined; + delayedTypeAliases = undefined; + seenThisKeyword = false; + currentFlow = undefined; + currentBreakTarget = undefined; + currentContinueTarget = undefined; + currentReturnTarget = undefined; + currentTrueTarget = undefined; + currentFalseTarget = undefined; + activeLabels = undefined; + hasExplicitReturn = false; + emitFlags = 0 /* None */; + subtreeTransformFlags = 0 /* None */; + } + return bindSourceFile; + function bindInStrictMode(file, opts) { + if (ts.getStrictOptionValue(opts, "alwaysStrict") && !file.isDeclarationFile) { + // bind in strict mode source files with alwaysStrict option + return true; + } + else { + return !!file.externalModuleIndicator; + } + } + function createSymbol(flags, name) { + symbolCount++; + return new Symbol(flags, name); + } + function addDeclarationToSymbol(symbol, node, symbolFlags) { + symbol.flags |= symbolFlags; + node.symbol = symbol; + symbol.declarations = ts.append(symbol.declarations, node); + if (symbolFlags & (32 /* Class */ | 384 /* Enum */ | 1536 /* Module */ | 3 /* Variable */) && !symbol.exports) { + symbol.exports = ts.createSymbolTable(); + } + if (symbolFlags & (32 /* Class */ | 64 /* Interface */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && !symbol.members) { + symbol.members = ts.createSymbolTable(); + } + if (symbolFlags & 67220415 /* Value */) { + setValueDeclaration(symbol, node); + } + } + function setValueDeclaration(symbol, node) { + var valueDeclaration = symbol.valueDeclaration; + if (!valueDeclaration || + (ts.isAssignmentDeclaration(valueDeclaration) && !ts.isAssignmentDeclaration(node)) || + (valueDeclaration.kind !== node.kind && ts.isEffectiveModuleDeclaration(valueDeclaration))) { + // other kinds of value declarations take precedence over modules and assignment declarations + symbol.valueDeclaration = node; + } + } + // Should not be called on a declaration with a computed property name, + // unless it is a well known Symbol. + function getDeclarationName(node) { + if (node.kind === 254 /* ExportAssignment */) { + return node.isExportEquals ? "export=" /* ExportEquals */ : "default" /* Default */; + } + var name = ts.getNameOfDeclaration(node); + if (name) { + if (ts.isAmbientModule(node)) { + var moduleName = ts.getTextOfIdentifierOrLiteral(name); + return (ts.isGlobalScopeAugmentation(node) ? "__global" : "\"" + moduleName + "\""); + } + if (name.kind === 149 /* ComputedPropertyName */) { + var nameExpression = name.expression; + // treat computed property names where expression is string/numeric literal as just string/numeric literal + if (ts.isStringOrNumericLiteralLike(nameExpression)) { + return ts.escapeLeadingUnderscores(nameExpression.text); + } + ts.Debug.assert(ts.isWellKnownSymbolSyntactically(nameExpression)); + return ts.getPropertyNameForKnownSymbolName(ts.idText(nameExpression.name)); + } + return ts.isPropertyNameLiteral(name) ? ts.getEscapedTextOfIdentifierOrLiteral(name) : undefined; + } + switch (node.kind) { + case 157 /* Constructor */: + return "__constructor" /* Constructor */; + case 165 /* FunctionType */: + case 160 /* CallSignature */: + case 293 /* JSDocSignature */: + return "__call" /* Call */; + case 166 /* ConstructorType */: + case 161 /* ConstructSignature */: + return "__new" /* New */; + case 162 /* IndexSignature */: + return "__index" /* Index */; + case 255 /* ExportDeclaration */: + return "__export" /* ExportStar */; + case 279 /* SourceFile */: + // json file should behave as + // module.exports = ... + return "export=" /* ExportEquals */; + case 204 /* BinaryExpression */: + if (ts.getAssignmentDeclarationKind(node) === 2 /* ModuleExports */) { + // module.exports = ... + return "export=" /* ExportEquals */; + } + ts.Debug.fail("Unknown binary declaration kind"); + break; + case 289 /* JSDocFunctionType */: + return (ts.isJSDocConstructSignature(node) ? "__new" /* New */ : "__call" /* Call */); + case 151 /* Parameter */: + // Parameters with names are handled at the top of this function. Parameters + // without names can only come from JSDocFunctionTypes. + ts.Debug.assert(node.parent.kind === 289 /* JSDocFunctionType */, "Impossible parameter parent kind", function () { return "parent is: " + (ts.SyntaxKind ? ts.SyntaxKind[node.parent.kind] : node.parent.kind) + ", expected JSDocFunctionType"; }); + var functionType = node.parent; + var index = functionType.parameters.indexOf(node); + return "arg" + index; + } + } + function getDisplayName(node) { + return ts.isNamedDeclaration(node) ? ts.declarationNameToString(node.name) : ts.unescapeLeadingUnderscores(ts.Debug.assertDefined(getDeclarationName(node))); + } + /** + * Declares a Symbol for the node and adds it to symbols. Reports errors for conflicting identifier names. + * @param symbolTable - The symbol table which node will be added to. + * @param parent - node's parent declaration. + * @param node - The declaration to be added to the symbol table + * @param includes - The SymbolFlags that node has in addition to its declaration type (eg: export, ambient, etc.) + * @param excludes - The flags which node cannot be declared alongside in a symbol table. Used to report forbidden declarations. + */ + function declareSymbol(symbolTable, parent, node, includes, excludes, isReplaceableByMethod) { + ts.Debug.assert(!ts.hasDynamicName(node)); + var isDefaultExport = ts.hasModifier(node, 512 /* Default */); + // The exported symbol for an export default function/class node is always named "default" + var name = isDefaultExport && parent ? "default" /* Default */ : getDeclarationName(node); + var symbol; + if (name === undefined) { + symbol = createSymbol(0 /* None */, "__missing" /* Missing */); + } + else { + // Check and see if the symbol table already has a symbol with this name. If not, + // create a new symbol with this name and add it to the table. Note that we don't + // give the new symbol any flags *yet*. This ensures that it will not conflict + // with the 'excludes' flags we pass in. + // + // If we do get an existing symbol, see if it conflicts with the new symbol we're + // creating. For example, a 'var' symbol and a 'class' symbol will conflict within + // the same symbol table. If we have a conflict, report the issue on each + // declaration we have for this symbol, and then create a new symbol for this + // declaration. + // + // Note that when properties declared in Javascript constructors + // (marked by isReplaceableByMethod) conflict with another symbol, the property loses. + // Always. This allows the common Javascript pattern of overwriting a prototype method + // with an bound instance method of the same type: `this.method = this.method.bind(this)` + // + // If we created a new symbol, either because we didn't have a symbol with this name + // in the symbol table, or we conflicted with an existing symbol, then just add this + // node as the sole declaration of the new symbol. + // + // Otherwise, we'll be merging into a compatible existing symbol (for example when + // you have multiple 'vars' with the same name in the same container). In this case + // just add this node into the declarations list of the symbol. + symbol = symbolTable.get(name); + if (includes & 2885600 /* Classifiable */) { + classifiableNames.set(name, true); + } + if (!symbol) { + symbolTable.set(name, symbol = createSymbol(0 /* None */, name)); + if (isReplaceableByMethod) + symbol.isReplaceableByMethod = true; + } + else if (isReplaceableByMethod && !symbol.isReplaceableByMethod) { + // A symbol already exists, so don't add this as a declaration. + return symbol; + } + else if (symbol.flags & excludes) { + if (symbol.isReplaceableByMethod) { + // Javascript constructor-declared symbols can be discarded in favor of + // prototype symbols like methods. + symbolTable.set(name, symbol = createSymbol(0 /* None */, name)); + } + else if (!(includes & 3 /* Variable */ && symbol.flags & 67108864 /* Assignment */)) { + // Assignment declarations are allowed to merge with variables, no matter what other flags they have. + if (ts.isNamedDeclaration(node)) { + node.name.parent = node; + } + // Report errors every position with duplicate declaration + // Report errors on previous encountered declarations + var message_1 = symbol.flags & 2 /* BlockScopedVariable */ + ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 + : ts.Diagnostics.Duplicate_identifier_0; + var messageNeedsName_1 = true; + if (symbol.flags & 384 /* Enum */ || includes & 384 /* Enum */) { + message_1 = ts.Diagnostics.Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations; + messageNeedsName_1 = false; + } + if (symbol.declarations && symbol.declarations.length) { + // If the current node is a default export of some sort, then check if + // there are any other default exports that we need to error on. + // We'll know whether we have other default exports depending on if `symbol` already has a declaration list set. + if (isDefaultExport) { + message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; + messageNeedsName_1 = false; + } + else { + // This is to properly report an error in the case "export default { }" is after export default of class declaration or function declaration. + // Error on multiple export default in the following case: + // 1. multiple export default of class declaration or function declaration by checking NodeFlags.Default + // 2. multiple export default of export assignment. This one doesn't have NodeFlags.Default on (as export default doesn't considered as modifiers) + if (symbol.declarations && symbol.declarations.length && + (node.kind === 254 /* ExportAssignment */ && !node.isExportEquals)) { + message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; + messageNeedsName_1 = false; + } + } + } + var addError = function (decl) { + file.bindDiagnostics.push(createDiagnosticForNode(ts.getNameOfDeclaration(decl) || decl, message_1, messageNeedsName_1 ? getDisplayName(decl) : undefined)); + }; + ts.forEach(symbol.declarations, addError); + addError(node); + symbol = createSymbol(0 /* None */, name); + } + } + } + addDeclarationToSymbol(symbol, node, includes); + if (symbol.parent) { + ts.Debug.assert(symbol.parent === parent, "Existing symbol parent should match new one"); + } + else { + symbol.parent = parent; + } + return symbol; + } + function declareModuleMember(node, symbolFlags, symbolExcludes) { + var hasExportModifier = ts.getCombinedModifierFlags(node) & 1 /* Export */; + if (symbolFlags & 2097152 /* Alias */) { + if (node.kind === 257 /* ExportSpecifier */ || (node.kind === 248 /* ImportEqualsDeclaration */ && hasExportModifier)) { + return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); + } + else { + return declareSymbol(container.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes); + } + } + else { + // Exported module members are given 2 symbols: A local symbol that is classified with an ExportValue flag, + // and an associated export symbol with all the correct flags set on it. There are 2 main reasons: + // + // 1. We treat locals and exports of the same name as mutually exclusive within a container. + // That means the binder will issue a Duplicate Identifier error if you mix locals and exports + // with the same name in the same container. + // TODO: Make this a more specific error and decouple it from the exclusion logic. + // 2. When we checkIdentifier in the checker, we set its resolved symbol to the local symbol, + // but return the export symbol (by calling getExportSymbolOfValueSymbolIfExported). That way + // when the emitter comes back to it, it knows not to qualify the name if it was found in a containing scope. + // NOTE: Nested ambient modules always should go to to 'locals' table to prevent their automatic merge + // during global merging in the checker. Why? The only case when ambient module is permitted inside another module is module augmentation + // and this case is specially handled. Module augmentations should only be merged with original module definition + // and should never be merged directly with other augmentation, and the latter case would be possible if automatic merge is allowed. + if (ts.isJSDocTypeAlias(node)) + ts.Debug.assert(ts.isInJSFile(node)); // We shouldn't add symbols for JSDoc nodes if not in a JS file. + if ((!ts.isAmbientModule(node) && (hasExportModifier || container.flags & 32 /* ExportContext */)) || ts.isJSDocTypeAlias(node)) { + if (ts.hasModifier(node, 512 /* Default */) && !getDeclarationName(node)) { + return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); // No local symbol for an unnamed default! + } + var exportKind = symbolFlags & 67220415 /* Value */ ? 1048576 /* ExportValue */ : 0; + var local = declareSymbol(container.locals, /*parent*/ undefined, node, exportKind, symbolExcludes); + local.exportSymbol = declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); + node.localSymbol = local; + return local; + } + else { + return declareSymbol(container.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes); + } + } + } + // All container nodes are kept on a linked list in declaration order. This list is used by + // the getLocalNameOfContainer function in the type checker to validate that the local name + // used for a container is unique. + function bindContainer(node, containerFlags) { + // Before we recurse into a node's children, we first save the existing parent, container + // and block-container. Then after we pop out of processing the children, we restore + // these saved values. + var saveContainer = container; + var saveThisParentContainer = thisParentContainer; + var savedBlockScopeContainer = blockScopeContainer; + // Depending on what kind of node this is, we may have to adjust the current container + // and block-container. If the current node is a container, then it is automatically + // considered the current block-container as well. Also, for containers that we know + // may contain locals, we eagerly initialize the .locals field. We do this because + // it's highly likely that the .locals will be needed to place some child in (for example, + // a parameter, or variable declaration). + // + // However, we do not proactively create the .locals for block-containers because it's + // totally normal and common for block-containers to never actually have a block-scoped + // variable in them. We don't want to end up allocating an object for every 'block' we + // run into when most of them won't be necessary. + // + // Finally, if this is a block-container, then we clear out any existing .locals object + // it may contain within it. This happens in incremental scenarios. Because we can be + // reusing a node from a previous compilation, that node may have had 'locals' created + // for it. We must clear this so we don't accidentally move any stale data forward from + // a previous compilation. + if (containerFlags & 1 /* IsContainer */) { + if (node.kind !== 197 /* ArrowFunction */) { + thisParentContainer = container; + } + container = blockScopeContainer = node; + if (containerFlags & 32 /* HasLocals */) { + container.locals = ts.createSymbolTable(); + } + addToContainerChain(container); + } + else if (containerFlags & 2 /* IsBlockScopedContainer */) { + blockScopeContainer = node; + blockScopeContainer.locals = undefined; + } + if (containerFlags & 4 /* IsControlFlowContainer */) { + var saveCurrentFlow = currentFlow; + var saveBreakTarget = currentBreakTarget; + var saveContinueTarget = currentContinueTarget; + var saveReturnTarget = currentReturnTarget; + var saveActiveLabels = activeLabels; + var saveHasExplicitReturn = hasExplicitReturn; + var isIIFE = containerFlags & 16 /* IsFunctionExpression */ && !ts.hasModifier(node, 256 /* Async */) && + !node.asteriskToken && !!ts.getImmediatelyInvokedFunctionExpression(node); + // A non-async, non-generator IIFE is considered part of the containing control flow. Return statements behave + // similarly to break statements that exit to a label just past the statement body. + if (!isIIFE) { + currentFlow = { flags: 2 /* Start */ }; + if (containerFlags & (16 /* IsFunctionExpression */ | 128 /* IsObjectLiteralOrClassExpressionMethod */)) { + currentFlow.container = node; + } + } + // We create a return control flow graph for IIFEs and constructors. For constructors + // we use the return control flow graph in strict property intialization checks. + currentReturnTarget = isIIFE || node.kind === 157 /* Constructor */ ? createBranchLabel() : undefined; + currentBreakTarget = undefined; + currentContinueTarget = undefined; + activeLabels = undefined; + hasExplicitReturn = false; + bindChildren(node); + // Reset all reachability check related flags on node (for incremental scenarios) + node.flags &= ~1408 /* ReachabilityAndEmitFlags */; + if (!(currentFlow.flags & 1 /* Unreachable */) && containerFlags & 8 /* IsFunctionLike */ && ts.nodeIsPresent(node.body)) { + node.flags |= 128 /* HasImplicitReturn */; + if (hasExplicitReturn) + node.flags |= 256 /* HasExplicitReturn */; + } + if (node.kind === 279 /* SourceFile */) { + node.flags |= emitFlags; + } + if (currentReturnTarget) { + addAntecedent(currentReturnTarget, currentFlow); + currentFlow = finishFlowLabel(currentReturnTarget); + if (node.kind === 157 /* Constructor */) { + node.returnFlowNode = currentFlow; + } + } + if (!isIIFE) { + currentFlow = saveCurrentFlow; + } + currentBreakTarget = saveBreakTarget; + currentContinueTarget = saveContinueTarget; + currentReturnTarget = saveReturnTarget; + activeLabels = saveActiveLabels; + hasExplicitReturn = saveHasExplicitReturn; + } + else if (containerFlags & 64 /* IsInterface */) { + seenThisKeyword = false; + bindChildren(node); + node.flags = seenThisKeyword ? node.flags | 64 /* ContainsThis */ : node.flags & ~64 /* ContainsThis */; + } + else { + bindChildren(node); + } + container = saveContainer; + thisParentContainer = saveThisParentContainer; + blockScopeContainer = savedBlockScopeContainer; + } + function bindChildren(node) { + if (skipTransformFlagAggregation) { + bindChildrenWorker(node); + } + else if (node.transformFlags & 536870912 /* HasComputedFlags */) { + skipTransformFlagAggregation = true; + bindChildrenWorker(node); + skipTransformFlagAggregation = false; + subtreeTransformFlags |= node.transformFlags & ~getTransformFlagsSubtreeExclusions(node.kind); + } + else { + var savedSubtreeTransformFlags = subtreeTransformFlags; + subtreeTransformFlags = 0; + bindChildrenWorker(node); + subtreeTransformFlags = savedSubtreeTransformFlags | computeTransformFlagsForNode(node, subtreeTransformFlags); + } + } + function bindEachFunctionsFirst(nodes) { + bindEach(nodes, function (n) { return n.kind === 239 /* FunctionDeclaration */ ? bind(n) : undefined; }); + bindEach(nodes, function (n) { return n.kind !== 239 /* FunctionDeclaration */ ? bind(n) : undefined; }); + } + function bindEach(nodes, bindFunction) { + if (bindFunction === void 0) { bindFunction = bind; } + if (nodes === undefined) { + return; + } + if (skipTransformFlagAggregation) { + ts.forEach(nodes, bindFunction); + } + else { + var savedSubtreeTransformFlags = subtreeTransformFlags; + subtreeTransformFlags = 0 /* None */; + var nodeArrayFlags = 0 /* None */; + for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) { + var node = nodes_2[_i]; + bindFunction(node); + nodeArrayFlags |= node.transformFlags & ~536870912 /* HasComputedFlags */; + } + nodes.transformFlags = nodeArrayFlags | 536870912 /* HasComputedFlags */; + subtreeTransformFlags |= savedSubtreeTransformFlags; + } + } + function bindEachChild(node) { + ts.forEachChild(node, bind, bindEach); + } + function bindChildrenWorker(node) { + if (checkUnreachable(node)) { + bindEachChild(node); + bindJSDoc(node); + return; + } + switch (node.kind) { + case 224 /* WhileStatement */: + bindWhileStatement(node); + break; + case 223 /* DoStatement */: + bindDoStatement(node); + break; + case 225 /* ForStatement */: + bindForStatement(node); + break; + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + bindForInOrForOfStatement(node); + break; + case 222 /* IfStatement */: + bindIfStatement(node); + break; + case 230 /* ReturnStatement */: + case 234 /* ThrowStatement */: + bindReturnOrThrow(node); + break; + case 229 /* BreakStatement */: + case 228 /* ContinueStatement */: + bindBreakOrContinueStatement(node); + break; + case 235 /* TryStatement */: + bindTryStatement(node); + break; + case 232 /* SwitchStatement */: + bindSwitchStatement(node); + break; + case 246 /* CaseBlock */: + bindCaseBlock(node); + break; + case 271 /* CaseClause */: + bindCaseClause(node); + break; + case 233 /* LabeledStatement */: + bindLabeledStatement(node); + break; + case 202 /* PrefixUnaryExpression */: + bindPrefixUnaryExpressionFlow(node); + break; + case 203 /* PostfixUnaryExpression */: + bindPostfixUnaryExpressionFlow(node); + break; + case 204 /* BinaryExpression */: + bindBinaryExpressionFlow(node); + break; + case 198 /* DeleteExpression */: + bindDeleteExpressionFlow(node); + break; + case 205 /* ConditionalExpression */: + bindConditionalExpressionFlow(node); + break; + case 237 /* VariableDeclaration */: + bindVariableDeclarationFlow(node); + break; + case 191 /* CallExpression */: + bindCallExpressionFlow(node); + break; + case 304 /* JSDocTypedefTag */: + case 297 /* JSDocCallbackTag */: + bindJSDocTypeAlias(node); + break; + // In source files and blocks, bind functions first to match hoisting that occurs at runtime + case 279 /* SourceFile */: { + bindEachFunctionsFirst(node.statements); + bind(node.endOfFileToken); + break; + } + case 218 /* Block */: + case 245 /* ModuleBlock */: + bindEachFunctionsFirst(node.statements); + break; + default: + bindEachChild(node); + break; + } + bindJSDoc(node); + } + function isNarrowingExpression(expr) { + switch (expr.kind) { + case 72 /* Identifier */: + case 100 /* ThisKeyword */: + case 189 /* PropertyAccessExpression */: + case 190 /* ElementAccessExpression */: + return isNarrowableReference(expr); + case 191 /* CallExpression */: + return hasNarrowableArgument(expr); + case 195 /* ParenthesizedExpression */: + return isNarrowingExpression(expr.expression); + case 204 /* BinaryExpression */: + return isNarrowingBinaryExpression(expr); + case 202 /* PrefixUnaryExpression */: + return expr.operator === 52 /* ExclamationToken */ && isNarrowingExpression(expr.operand); + case 199 /* TypeOfExpression */: + return isNarrowingExpression(expr.expression); + } + return false; + } + function isNarrowableReference(expr) { + return expr.kind === 72 /* Identifier */ || expr.kind === 100 /* ThisKeyword */ || expr.kind === 98 /* SuperKeyword */ || + ts.isPropertyAccessExpression(expr) && isNarrowableReference(expr.expression) || + ts.isElementAccessExpression(expr) && expr.argumentExpression && + (ts.isStringLiteral(expr.argumentExpression) || ts.isNumericLiteral(expr.argumentExpression)) && + isNarrowableReference(expr.expression); + } + function hasNarrowableArgument(expr) { + if (expr.arguments) { + for (var _i = 0, _a = expr.arguments; _i < _a.length; _i++) { + var argument = _a[_i]; + if (isNarrowableReference(argument)) { + return true; + } + } + } + if (expr.expression.kind === 189 /* PropertyAccessExpression */ && + isNarrowableReference(expr.expression.expression)) { + return true; + } + return false; + } + function isNarrowingTypeofOperands(expr1, expr2) { + return ts.isTypeOfExpression(expr1) && isNarrowableOperand(expr1.expression) && ts.isStringLiteralLike(expr2); + } + function isNarrowableInOperands(left, right) { + return ts.isStringLiteralLike(left) && isNarrowingExpression(right); + } + function isNarrowingBinaryExpression(expr) { + switch (expr.operatorToken.kind) { + case 59 /* EqualsToken */: + return isNarrowableReference(expr.left); + case 33 /* EqualsEqualsToken */: + case 34 /* ExclamationEqualsToken */: + case 35 /* EqualsEqualsEqualsToken */: + case 36 /* ExclamationEqualsEqualsToken */: + return isNarrowableOperand(expr.left) || isNarrowableOperand(expr.right) || + isNarrowingTypeofOperands(expr.right, expr.left) || isNarrowingTypeofOperands(expr.left, expr.right); + case 94 /* InstanceOfKeyword */: + return isNarrowableOperand(expr.left); + case 93 /* InKeyword */: + return isNarrowableInOperands(expr.left, expr.right); + case 27 /* CommaToken */: + return isNarrowingExpression(expr.right); + } + return false; + } + function isNarrowableOperand(expr) { + switch (expr.kind) { + case 195 /* ParenthesizedExpression */: + return isNarrowableOperand(expr.expression); + case 204 /* BinaryExpression */: + switch (expr.operatorToken.kind) { + case 59 /* EqualsToken */: + return isNarrowableOperand(expr.left); + case 27 /* CommaToken */: + return isNarrowableOperand(expr.right); + } + } + return isNarrowableReference(expr); + } + function createBranchLabel() { + return { + flags: 4 /* BranchLabel */, + antecedents: undefined + }; + } + function createLoopLabel() { + return { + flags: 8 /* LoopLabel */, + antecedents: undefined + }; + } + function setFlowNodeReferenced(flow) { + // On first reference we set the Referenced flag, thereafter we set the Shared flag + flow.flags |= flow.flags & 512 /* Referenced */ ? 1024 /* Shared */ : 512 /* Referenced */; + } + function addAntecedent(label, antecedent) { + if (!(antecedent.flags & 1 /* Unreachable */) && !ts.contains(label.antecedents, antecedent)) { + (label.antecedents || (label.antecedents = [])).push(antecedent); + setFlowNodeReferenced(antecedent); + } + } + function createFlowCondition(flags, antecedent, expression) { + if (antecedent.flags & 1 /* Unreachable */) { + return antecedent; + } + if (!expression) { + return flags & 32 /* TrueCondition */ ? antecedent : unreachableFlow; + } + if (expression.kind === 102 /* TrueKeyword */ && flags & 64 /* FalseCondition */ || + expression.kind === 87 /* FalseKeyword */ && flags & 32 /* TrueCondition */) { + return unreachableFlow; + } + if (!isNarrowingExpression(expression)) { + return antecedent; + } + setFlowNodeReferenced(antecedent); + return { flags: flags, expression: expression, antecedent: antecedent }; + } + function createFlowSwitchClause(antecedent, switchStatement, clauseStart, clauseEnd) { + if (!isNarrowingExpression(switchStatement.expression)) { + return antecedent; + } + setFlowNodeReferenced(antecedent); + return { flags: 128 /* SwitchClause */, switchStatement: switchStatement, clauseStart: clauseStart, clauseEnd: clauseEnd, antecedent: antecedent }; + } + function createFlowAssignment(antecedent, node) { + setFlowNodeReferenced(antecedent); + return { flags: 16 /* Assignment */, antecedent: antecedent, node: node }; + } + function createFlowArrayMutation(antecedent, node) { + setFlowNodeReferenced(antecedent); + var res = { flags: 256 /* ArrayMutation */, antecedent: antecedent, node: node }; + return res; + } + function finishFlowLabel(flow) { + var antecedents = flow.antecedents; + if (!antecedents) { + return unreachableFlow; + } + if (antecedents.length === 1) { + return antecedents[0]; + } + return flow; + } + function isStatementCondition(node) { + var parent = node.parent; + switch (parent.kind) { + case 222 /* IfStatement */: + case 224 /* WhileStatement */: + case 223 /* DoStatement */: + return parent.expression === node; + case 225 /* ForStatement */: + case 205 /* ConditionalExpression */: + return parent.condition === node; + } + return false; + } + function isLogicalExpression(node) { + while (true) { + if (node.kind === 195 /* ParenthesizedExpression */) { + node = node.expression; + } + else if (node.kind === 202 /* PrefixUnaryExpression */ && node.operator === 52 /* ExclamationToken */) { + node = node.operand; + } + else { + return node.kind === 204 /* BinaryExpression */ && (node.operatorToken.kind === 54 /* AmpersandAmpersandToken */ || + node.operatorToken.kind === 55 /* BarBarToken */); + } + } + } + function isTopLevelLogicalExpression(node) { + while (node.parent.kind === 195 /* ParenthesizedExpression */ || + node.parent.kind === 202 /* PrefixUnaryExpression */ && + node.parent.operator === 52 /* ExclamationToken */) { + node = node.parent; + } + return !isStatementCondition(node) && !isLogicalExpression(node.parent); + } + function bindCondition(node, trueTarget, falseTarget) { + var saveTrueTarget = currentTrueTarget; + var saveFalseTarget = currentFalseTarget; + currentTrueTarget = trueTarget; + currentFalseTarget = falseTarget; + bind(node); + currentTrueTarget = saveTrueTarget; + currentFalseTarget = saveFalseTarget; + if (!node || !isLogicalExpression(node)) { + addAntecedent(trueTarget, createFlowCondition(32 /* TrueCondition */, currentFlow, node)); + addAntecedent(falseTarget, createFlowCondition(64 /* FalseCondition */, currentFlow, node)); + } + } + function bindIterativeStatement(node, breakTarget, continueTarget) { + var saveBreakTarget = currentBreakTarget; + var saveContinueTarget = currentContinueTarget; + currentBreakTarget = breakTarget; + currentContinueTarget = continueTarget; + bind(node); + currentBreakTarget = saveBreakTarget; + currentContinueTarget = saveContinueTarget; + } + function bindWhileStatement(node) { + var preWhileLabel = createLoopLabel(); + var preBodyLabel = createBranchLabel(); + var postWhileLabel = createBranchLabel(); + addAntecedent(preWhileLabel, currentFlow); + currentFlow = preWhileLabel; + bindCondition(node.expression, preBodyLabel, postWhileLabel); + currentFlow = finishFlowLabel(preBodyLabel); + bindIterativeStatement(node.statement, postWhileLabel, preWhileLabel); + addAntecedent(preWhileLabel, currentFlow); + currentFlow = finishFlowLabel(postWhileLabel); + } + function bindDoStatement(node) { + var preDoLabel = createLoopLabel(); + var enclosingLabeledStatement = node.parent.kind === 233 /* LabeledStatement */ + ? ts.lastOrUndefined(activeLabels) + : undefined; + // if do statement is wrapped in labeled statement then target labels for break/continue with or without + // label should be the same + var preConditionLabel = enclosingLabeledStatement ? enclosingLabeledStatement.continueTarget : createBranchLabel(); + var postDoLabel = enclosingLabeledStatement ? enclosingLabeledStatement.breakTarget : createBranchLabel(); + addAntecedent(preDoLabel, currentFlow); + currentFlow = preDoLabel; + bindIterativeStatement(node.statement, postDoLabel, preConditionLabel); + addAntecedent(preConditionLabel, currentFlow); + currentFlow = finishFlowLabel(preConditionLabel); + bindCondition(node.expression, preDoLabel, postDoLabel); + currentFlow = finishFlowLabel(postDoLabel); + } + function bindForStatement(node) { + var preLoopLabel = createLoopLabel(); + var preBodyLabel = createBranchLabel(); + var postLoopLabel = createBranchLabel(); + bind(node.initializer); + addAntecedent(preLoopLabel, currentFlow); + currentFlow = preLoopLabel; + bindCondition(node.condition, preBodyLabel, postLoopLabel); + currentFlow = finishFlowLabel(preBodyLabel); + bindIterativeStatement(node.statement, postLoopLabel, preLoopLabel); + bind(node.incrementor); + addAntecedent(preLoopLabel, currentFlow); + currentFlow = finishFlowLabel(postLoopLabel); + } + function bindForInOrForOfStatement(node) { + var preLoopLabel = createLoopLabel(); + var postLoopLabel = createBranchLabel(); + addAntecedent(preLoopLabel, currentFlow); + currentFlow = preLoopLabel; + if (node.kind === 227 /* ForOfStatement */) { + bind(node.awaitModifier); + } + bind(node.expression); + addAntecedent(postLoopLabel, currentFlow); + bind(node.initializer); + if (node.initializer.kind !== 238 /* VariableDeclarationList */) { + bindAssignmentTargetFlow(node.initializer); + } + bindIterativeStatement(node.statement, postLoopLabel, preLoopLabel); + addAntecedent(preLoopLabel, currentFlow); + currentFlow = finishFlowLabel(postLoopLabel); + } + function bindIfStatement(node) { + var thenLabel = createBranchLabel(); + var elseLabel = createBranchLabel(); + var postIfLabel = createBranchLabel(); + bindCondition(node.expression, thenLabel, elseLabel); + currentFlow = finishFlowLabel(thenLabel); + bind(node.thenStatement); + addAntecedent(postIfLabel, currentFlow); + currentFlow = finishFlowLabel(elseLabel); + bind(node.elseStatement); + addAntecedent(postIfLabel, currentFlow); + currentFlow = finishFlowLabel(postIfLabel); + } + function bindReturnOrThrow(node) { + bind(node.expression); + if (node.kind === 230 /* ReturnStatement */) { + hasExplicitReturn = true; + if (currentReturnTarget) { + addAntecedent(currentReturnTarget, currentFlow); + } + } + currentFlow = unreachableFlow; + } + function findActiveLabel(name) { + if (activeLabels) { + for (var _i = 0, activeLabels_1 = activeLabels; _i < activeLabels_1.length; _i++) { + var label = activeLabels_1[_i]; + if (label.name === name) { + return label; + } + } + } + return undefined; + } + function bindBreakOrContinueFlow(node, breakTarget, continueTarget) { + var flowLabel = node.kind === 229 /* BreakStatement */ ? breakTarget : continueTarget; + if (flowLabel) { + addAntecedent(flowLabel, currentFlow); + currentFlow = unreachableFlow; + } + } + function bindBreakOrContinueStatement(node) { + bind(node.label); + if (node.label) { + var activeLabel = findActiveLabel(node.label.escapedText); + if (activeLabel) { + activeLabel.referenced = true; + bindBreakOrContinueFlow(node, activeLabel.breakTarget, activeLabel.continueTarget); + } + } + else { + bindBreakOrContinueFlow(node, currentBreakTarget, currentContinueTarget); + } + } + function bindTryStatement(node) { + var preFinallyLabel = createBranchLabel(); + var preTryFlow = currentFlow; + // TODO: Every statement in try block is potentially an exit point! + bind(node.tryBlock); + addAntecedent(preFinallyLabel, currentFlow); + var flowAfterTry = currentFlow; + var flowAfterCatch = unreachableFlow; + if (node.catchClause) { + currentFlow = preTryFlow; + bind(node.catchClause); + addAntecedent(preFinallyLabel, currentFlow); + flowAfterCatch = currentFlow; + } + if (node.finallyBlock) { + // in finally flow is combined from pre-try/flow from try/flow from catch + // pre-flow is necessary to make sure that finally is reachable even if finally flows in both try and finally blocks are unreachable + // also for finally blocks we inject two extra edges into the flow graph. + // first -> edge that connects pre-try flow with the label at the beginning of the finally block, it has lock associated with it + // second -> edge that represents post-finally flow. + // these edges are used in following scenario: + // let a; (1) + // try { a = someOperation(); (2)} + // finally { (3) console.log(a) } (4) + // (5) a + // flow graph for this case looks roughly like this (arrows show ): + // (1-pre-try-flow) <--.. <-- (2-post-try-flow) + // ^ ^ + // |*****(3-pre-finally-label) -----| + // ^ + // |-- ... <-- (4-post-finally-label) <--- (5) + // In case when we walk the flow starting from inside the finally block we want to take edge '*****' into account + // since it ensures that finally is always reachable. However when we start outside the finally block and go through label (5) + // then edge '*****' should be discarded because label 4 is only reachable if post-finally label-4 is reachable + // Simply speaking code inside finally block is treated as reachable as pre-try-flow + // since we conservatively assume that any line in try block can throw or return in which case we'll enter finally. + // However code after finally is reachable only if control flow was not abrupted in try/catch or finally blocks - it should be composed from + // final flows of these blocks without taking pre-try flow into account. + // + // extra edges that we inject allows to control this behavior + // if when walking the flow we step on post-finally edge - we can mark matching pre-finally edge as locked so it will be skipped. + var preFinallyFlow = { flags: 2048 /* PreFinally */, antecedent: preTryFlow, lock: {} }; + addAntecedent(preFinallyLabel, preFinallyFlow); + currentFlow = finishFlowLabel(preFinallyLabel); + bind(node.finallyBlock); + // if flow after finally is unreachable - keep it + // otherwise check if flows after try and after catch are unreachable + // if yes - convert current flow to unreachable + // i.e. + // try { return "1" } finally { console.log(1); } + // console.log(2); // this line should be unreachable even if flow falls out of finally block + if (!(currentFlow.flags & 1 /* Unreachable */)) { + if ((flowAfterTry.flags & 1 /* Unreachable */) && (flowAfterCatch.flags & 1 /* Unreachable */)) { + currentFlow = flowAfterTry === reportedUnreachableFlow || flowAfterCatch === reportedUnreachableFlow + ? reportedUnreachableFlow + : unreachableFlow; + } + } + if (!(currentFlow.flags & 1 /* Unreachable */)) { + var afterFinallyFlow = { flags: 4096 /* AfterFinally */, antecedent: currentFlow }; + preFinallyFlow.lock = afterFinallyFlow; + currentFlow = afterFinallyFlow; + } + } + else { + currentFlow = finishFlowLabel(preFinallyLabel); + } + } + function bindSwitchStatement(node) { + var postSwitchLabel = createBranchLabel(); + bind(node.expression); + var saveBreakTarget = currentBreakTarget; + var savePreSwitchCaseFlow = preSwitchCaseFlow; + currentBreakTarget = postSwitchLabel; + preSwitchCaseFlow = currentFlow; + bind(node.caseBlock); + addAntecedent(postSwitchLabel, currentFlow); + var hasDefault = ts.forEach(node.caseBlock.clauses, function (c) { return c.kind === 272 /* DefaultClause */; }); + // We mark a switch statement as possibly exhaustive if it has no default clause and if all + // case clauses have unreachable end points (e.g. they all return). + node.possiblyExhaustive = !hasDefault && !postSwitchLabel.antecedents; + if (!hasDefault) { + addAntecedent(postSwitchLabel, createFlowSwitchClause(preSwitchCaseFlow, node, 0, 0)); + } + currentBreakTarget = saveBreakTarget; + preSwitchCaseFlow = savePreSwitchCaseFlow; + currentFlow = finishFlowLabel(postSwitchLabel); + } + function bindCaseBlock(node) { + var savedSubtreeTransformFlags = subtreeTransformFlags; + subtreeTransformFlags = 0; + var clauses = node.clauses; + var fallthroughFlow = unreachableFlow; + for (var i = 0; i < clauses.length; i++) { + var clauseStart = i; + while (!clauses[i].statements.length && i + 1 < clauses.length) { + bind(clauses[i]); + i++; + } + var preCaseLabel = createBranchLabel(); + addAntecedent(preCaseLabel, createFlowSwitchClause(preSwitchCaseFlow, node.parent, clauseStart, i + 1)); + addAntecedent(preCaseLabel, fallthroughFlow); + currentFlow = finishFlowLabel(preCaseLabel); + var clause = clauses[i]; + bind(clause); + fallthroughFlow = currentFlow; + if (!(currentFlow.flags & 1 /* Unreachable */) && i !== clauses.length - 1 && options.noFallthroughCasesInSwitch) { + errorOnFirstToken(clause, ts.Diagnostics.Fallthrough_case_in_switch); + } + } + clauses.transformFlags = subtreeTransformFlags | 536870912 /* HasComputedFlags */; + subtreeTransformFlags |= savedSubtreeTransformFlags; + } + function bindCaseClause(node) { + var saveCurrentFlow = currentFlow; + currentFlow = preSwitchCaseFlow; + bind(node.expression); + currentFlow = saveCurrentFlow; + bindEach(node.statements); + } + function pushActiveLabel(name, breakTarget, continueTarget) { + var activeLabel = { + name: name, + breakTarget: breakTarget, + continueTarget: continueTarget, + referenced: false + }; + (activeLabels || (activeLabels = [])).push(activeLabel); + return activeLabel; + } + function popActiveLabel() { + activeLabels.pop(); + } + function bindLabeledStatement(node) { + var preStatementLabel = createLoopLabel(); + var postStatementLabel = createBranchLabel(); + bind(node.label); + addAntecedent(preStatementLabel, currentFlow); + var activeLabel = pushActiveLabel(node.label.escapedText, postStatementLabel, preStatementLabel); + bind(node.statement); + popActiveLabel(); + if (!activeLabel.referenced && !options.allowUnusedLabels) { + errorOrSuggestionOnNode(ts.unusedLabelIsError(options), node.label, ts.Diagnostics.Unused_label); + } + if (!node.statement || node.statement.kind !== 223 /* DoStatement */) { + // do statement sets current flow inside bindDoStatement + addAntecedent(postStatementLabel, currentFlow); + currentFlow = finishFlowLabel(postStatementLabel); + } + } + function bindDestructuringTargetFlow(node) { + if (node.kind === 204 /* BinaryExpression */ && node.operatorToken.kind === 59 /* EqualsToken */) { + bindAssignmentTargetFlow(node.left); + } + else { + bindAssignmentTargetFlow(node); + } + } + function bindAssignmentTargetFlow(node) { + if (isNarrowableReference(node)) { + currentFlow = createFlowAssignment(currentFlow, node); + } + else if (node.kind === 187 /* ArrayLiteralExpression */) { + for (var _i = 0, _a = node.elements; _i < _a.length; _i++) { + var e = _a[_i]; + if (e.kind === 208 /* SpreadElement */) { + bindAssignmentTargetFlow(e.expression); + } + else { + bindDestructuringTargetFlow(e); + } + } + } + else if (node.kind === 188 /* ObjectLiteralExpression */) { + for (var _b = 0, _c = node.properties; _b < _c.length; _b++) { + var p = _c[_b]; + if (p.kind === 275 /* PropertyAssignment */) { + bindDestructuringTargetFlow(p.initializer); + } + else if (p.kind === 276 /* ShorthandPropertyAssignment */) { + bindAssignmentTargetFlow(p.name); + } + else if (p.kind === 277 /* SpreadAssignment */) { + bindAssignmentTargetFlow(p.expression); + } + } + } + } + function bindLogicalExpression(node, trueTarget, falseTarget) { + var preRightLabel = createBranchLabel(); + if (node.operatorToken.kind === 54 /* AmpersandAmpersandToken */) { + bindCondition(node.left, preRightLabel, falseTarget); + } + else { + bindCondition(node.left, trueTarget, preRightLabel); + } + currentFlow = finishFlowLabel(preRightLabel); + bind(node.operatorToken); + bindCondition(node.right, trueTarget, falseTarget); + } + function bindPrefixUnaryExpressionFlow(node) { + if (node.operator === 52 /* ExclamationToken */) { + var saveTrueTarget = currentTrueTarget; + currentTrueTarget = currentFalseTarget; + currentFalseTarget = saveTrueTarget; + bindEachChild(node); + currentFalseTarget = currentTrueTarget; + currentTrueTarget = saveTrueTarget; + } + else { + bindEachChild(node); + if (node.operator === 44 /* PlusPlusToken */ || node.operator === 45 /* MinusMinusToken */) { + bindAssignmentTargetFlow(node.operand); + } + } + } + function bindPostfixUnaryExpressionFlow(node) { + bindEachChild(node); + if (node.operator === 44 /* PlusPlusToken */ || node.operator === 45 /* MinusMinusToken */) { + bindAssignmentTargetFlow(node.operand); + } + } + function bindBinaryExpressionFlow(node) { + var operator = node.operatorToken.kind; + if (operator === 54 /* AmpersandAmpersandToken */ || operator === 55 /* BarBarToken */) { + if (isTopLevelLogicalExpression(node)) { + var postExpressionLabel = createBranchLabel(); + bindLogicalExpression(node, postExpressionLabel, postExpressionLabel); + currentFlow = finishFlowLabel(postExpressionLabel); + } + else { + bindLogicalExpression(node, currentTrueTarget, currentFalseTarget); + } + } + else { + bindEachChild(node); + if (ts.isAssignmentOperator(operator) && !ts.isAssignmentTarget(node)) { + bindAssignmentTargetFlow(node.left); + if (operator === 59 /* EqualsToken */ && node.left.kind === 190 /* ElementAccessExpression */) { + var elementAccess = node.left; + if (isNarrowableOperand(elementAccess.expression)) { + currentFlow = createFlowArrayMutation(currentFlow, node); + } + } + } + } + } + function bindDeleteExpressionFlow(node) { + bindEachChild(node); + if (node.expression.kind === 189 /* PropertyAccessExpression */) { + bindAssignmentTargetFlow(node.expression); + } + } + function bindConditionalExpressionFlow(node) { + var trueLabel = createBranchLabel(); + var falseLabel = createBranchLabel(); + var postExpressionLabel = createBranchLabel(); + bindCondition(node.condition, trueLabel, falseLabel); + currentFlow = finishFlowLabel(trueLabel); + bind(node.questionToken); + bind(node.whenTrue); + addAntecedent(postExpressionLabel, currentFlow); + currentFlow = finishFlowLabel(falseLabel); + bind(node.colonToken); + bind(node.whenFalse); + addAntecedent(postExpressionLabel, currentFlow); + currentFlow = finishFlowLabel(postExpressionLabel); + } + function bindInitializedVariableFlow(node) { + var name = !ts.isOmittedExpression(node) ? node.name : undefined; + if (ts.isBindingPattern(name)) { + for (var _i = 0, _a = name.elements; _i < _a.length; _i++) { + var child = _a[_i]; + bindInitializedVariableFlow(child); + } + } + else { + currentFlow = createFlowAssignment(currentFlow, node); + } + } + function bindVariableDeclarationFlow(node) { + bindEachChild(node); + if (node.initializer || ts.isForInOrOfStatement(node.parent.parent)) { + bindInitializedVariableFlow(node); + } + } + function bindJSDocTypeAlias(node) { + node.tagName.parent = node; + if (node.fullName) { + setParentPointers(node, node.fullName); + } + } + function bindCallExpressionFlow(node) { + // If the target of the call expression is a function expression or arrow function we have + // an immediately invoked function expression (IIFE). Initialize the flowNode property to + // the current control flow (which includes evaluation of the IIFE arguments). + var expr = node.expression; + while (expr.kind === 195 /* ParenthesizedExpression */) { + expr = expr.expression; + } + if (expr.kind === 196 /* FunctionExpression */ || expr.kind === 197 /* ArrowFunction */) { + bindEach(node.typeArguments); + bindEach(node.arguments); + bind(node.expression); + } + else { + bindEachChild(node); + } + if (node.expression.kind === 189 /* PropertyAccessExpression */) { + var propertyAccess = node.expression; + if (isNarrowableOperand(propertyAccess.expression) && ts.isPushOrUnshiftIdentifier(propertyAccess.name)) { + currentFlow = createFlowArrayMutation(currentFlow, node); + } + } + } + function getContainerFlags(node) { + switch (node.kind) { + case 209 /* ClassExpression */: + case 240 /* ClassDeclaration */: + case 243 /* EnumDeclaration */: + case 188 /* ObjectLiteralExpression */: + case 168 /* TypeLiteral */: + case 292 /* JSDocTypeLiteral */: + case 268 /* JsxAttributes */: + return 1 /* IsContainer */; + case 241 /* InterfaceDeclaration */: + return 1 /* IsContainer */ | 64 /* IsInterface */; + case 244 /* ModuleDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 181 /* MappedType */: + return 1 /* IsContainer */ | 32 /* HasLocals */; + case 279 /* SourceFile */: + return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */; + case 156 /* MethodDeclaration */: + if (ts.isObjectLiteralOrClassExpressionMethod(node)) { + return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */ | 128 /* IsObjectLiteralOrClassExpressionMethod */; + } + // falls through + case 157 /* Constructor */: + case 239 /* FunctionDeclaration */: + case 155 /* MethodSignature */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 160 /* CallSignature */: + case 293 /* JSDocSignature */: + case 289 /* JSDocFunctionType */: + case 165 /* FunctionType */: + case 161 /* ConstructSignature */: + case 162 /* IndexSignature */: + case 166 /* ConstructorType */: + return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */; + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */ | 16 /* IsFunctionExpression */; + case 245 /* ModuleBlock */: + return 4 /* IsControlFlowContainer */; + case 154 /* PropertyDeclaration */: + return node.initializer ? 4 /* IsControlFlowContainer */ : 0; + case 274 /* CatchClause */: + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + case 246 /* CaseBlock */: + return 2 /* IsBlockScopedContainer */; + case 218 /* Block */: + // do not treat blocks directly inside a function as a block-scoped-container. + // Locals that reside in this block should go to the function locals. Otherwise 'x' + // would not appear to be a redeclaration of a block scoped local in the following + // example: + // + // function foo() { + // var x; + // let x; + // } + // + // If we placed 'var x' into the function locals and 'let x' into the locals of + // the block, then there would be no collision. + // + // By not creating a new block-scoped-container here, we ensure that both 'var x' + // and 'let x' go into the Function-container's locals, and we do get a collision + // conflict. + return ts.isFunctionLike(node.parent) ? 0 /* None */ : 2 /* IsBlockScopedContainer */; + } + return 0 /* None */; + } + function addToContainerChain(next) { + if (lastContainer) { + lastContainer.nextContainer = next; + } + lastContainer = next; + } + function declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes) { + switch (container.kind) { + // Modules, source files, and classes need specialized handling for how their + // members are declared (for example, a member of a class will go into a specific + // symbol table depending on if it is static or not). We defer to specialized + // handlers to take care of declaring these child members. + case 244 /* ModuleDeclaration */: + return declareModuleMember(node, symbolFlags, symbolExcludes); + case 279 /* SourceFile */: + return declareSourceFileMember(node, symbolFlags, symbolExcludes); + case 209 /* ClassExpression */: + case 240 /* ClassDeclaration */: + return declareClassMember(node, symbolFlags, symbolExcludes); + case 243 /* EnumDeclaration */: + return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); + case 168 /* TypeLiteral */: + case 292 /* JSDocTypeLiteral */: + case 188 /* ObjectLiteralExpression */: + case 241 /* InterfaceDeclaration */: + case 268 /* JsxAttributes */: + // Interface/Object-types always have their children added to the 'members' of + // their container. They are only accessible through an instance of their + // container, and are never in scope otherwise (even inside the body of the + // object / type / interface declaring them). An exception is type parameters, + // which are in scope without qualification (similar to 'locals'). + return declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes); + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 293 /* JSDocSignature */: + case 162 /* IndexSignature */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 289 /* JSDocFunctionType */: + case 304 /* JSDocTypedefTag */: + case 297 /* JSDocCallbackTag */: + case 242 /* TypeAliasDeclaration */: + case 181 /* MappedType */: + // All the children of these container types are never visible through another + // symbol (i.e. through another symbol's 'exports' or 'members'). Instead, + // they're only accessed 'lexically' (i.e. from code that exists underneath + // their container in the tree). To accomplish this, we simply add their declared + // symbol to the 'locals' of the container. These symbols can then be found as + // the type checker walks up the containers, checking them for matching names. + return declareSymbol(container.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes); + } + } + function declareClassMember(node, symbolFlags, symbolExcludes) { + return ts.hasModifier(node, 32 /* Static */) + ? declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes) + : declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes); + } + function declareSourceFileMember(node, symbolFlags, symbolExcludes) { + return ts.isExternalModule(file) + ? declareModuleMember(node, symbolFlags, symbolExcludes) + : declareSymbol(file.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes); + } + function hasExportDeclarations(node) { + var body = node.kind === 279 /* SourceFile */ ? node : node.body; + if (body && (body.kind === 279 /* SourceFile */ || body.kind === 245 /* ModuleBlock */)) { + for (var _i = 0, _a = body.statements; _i < _a.length; _i++) { + var stat = _a[_i]; + if (stat.kind === 255 /* ExportDeclaration */ || stat.kind === 254 /* ExportAssignment */) { + return true; + } + } + } + return false; + } + function setExportContextFlag(node) { + // A declaration source file or ambient module declaration that contains no export declarations (but possibly regular + // declarations with export modifiers) is an export context in which declarations are implicitly exported. + if (node.flags & 4194304 /* Ambient */ && !hasExportDeclarations(node)) { + node.flags |= 32 /* ExportContext */; + } + else { + node.flags &= ~32 /* ExportContext */; + } + } + function bindModuleDeclaration(node) { + setExportContextFlag(node); + if (ts.isAmbientModule(node)) { + if (ts.hasModifier(node, 1 /* Export */)) { + errorOnFirstToken(node, ts.Diagnostics.export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always_visible); + } + if (ts.isModuleAugmentationExternal(node)) { + declareModuleSymbol(node); + } + else { + var pattern = void 0; + if (node.name.kind === 10 /* StringLiteral */) { + var text = node.name.text; + if (ts.hasZeroOrOneAsteriskCharacter(text)) { + pattern = ts.tryParsePattern(text); + } + else { + errorOnFirstToken(node.name, ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, text); + } + } + var symbol = declareSymbolAndAddToSymbolTable(node, 512 /* ValueModule */, 110735 /* ValueModuleExcludes */); + file.patternAmbientModules = ts.append(file.patternAmbientModules, pattern && { pattern: pattern, symbol: symbol }); + } + } + else { + var state = declareModuleSymbol(node); + if (state !== 0 /* NonInstantiated */) { + var symbol = node.symbol; + // if module was already merged with some function, class or non-const enum, treat it as non-const-enum-only + symbol.constEnumOnlyModule = (!(symbol.flags & (16 /* Function */ | 32 /* Class */ | 256 /* RegularEnum */))) + // Current must be `const enum` only + && state === 2 /* ConstEnumOnly */ + // Can't have been set to 'false' in a previous merged symbol. ('undefined' OK) + && symbol.constEnumOnlyModule !== false; + } + } + } + function declareModuleSymbol(node) { + var state = getModuleInstanceState(node); + var instantiated = state !== 0 /* NonInstantiated */; + declareSymbolAndAddToSymbolTable(node, instantiated ? 512 /* ValueModule */ : 1024 /* NamespaceModule */, instantiated ? 110735 /* ValueModuleExcludes */ : 0 /* NamespaceModuleExcludes */); + return state; + } + function bindFunctionOrConstructorType(node) { + // For a given function symbol "<...>(...) => T" we want to generate a symbol identical + // to the one we would get for: { <...>(...): T } + // + // We do that by making an anonymous type literal symbol, and then setting the function + // symbol as its sole member. To the rest of the system, this symbol will be indistinguishable + // from an actual type literal symbol you would have gotten had you used the long form. + var symbol = createSymbol(131072 /* Signature */, getDeclarationName(node)); // TODO: GH#18217 + addDeclarationToSymbol(symbol, node, 131072 /* Signature */); + var typeLiteralSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */); + addDeclarationToSymbol(typeLiteralSymbol, node, 2048 /* TypeLiteral */); + typeLiteralSymbol.members = ts.createSymbolTable(); + typeLiteralSymbol.members.set(symbol.escapedName, symbol); + } + function bindObjectLiteralExpression(node) { + var ElementKind; + (function (ElementKind) { + ElementKind[ElementKind["Property"] = 1] = "Property"; + ElementKind[ElementKind["Accessor"] = 2] = "Accessor"; + })(ElementKind || (ElementKind = {})); + if (inStrictMode) { + var seen = ts.createUnderscoreEscapedMap(); + for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { + var prop = _a[_i]; + if (prop.kind === 277 /* SpreadAssignment */ || prop.name.kind !== 72 /* Identifier */) { + continue; + } + var identifier = prop.name; + // ECMA-262 11.1.5 Object Initializer + // If previous is not undefined then throw a SyntaxError exception if any of the following conditions are true + // a.This production is contained in strict code and IsDataDescriptor(previous) is true and + // IsDataDescriptor(propId.descriptor) is true. + // b.IsDataDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true. + // c.IsAccessorDescriptor(previous) is true and IsDataDescriptor(propId.descriptor) is true. + // d.IsAccessorDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true + // and either both previous and propId.descriptor have[[Get]] fields or both previous and propId.descriptor have[[Set]] fields + var currentKind = prop.kind === 275 /* PropertyAssignment */ || prop.kind === 276 /* ShorthandPropertyAssignment */ || prop.kind === 156 /* MethodDeclaration */ + ? 1 /* Property */ + : 2 /* Accessor */; + var existingKind = seen.get(identifier.escapedText); + if (!existingKind) { + seen.set(identifier.escapedText, currentKind); + continue; + } + if (currentKind === 1 /* Property */ && existingKind === 1 /* Property */) { + var span = ts.getErrorSpanForNode(file, identifier); + file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, ts.Diagnostics.An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode)); + } + } + } + return bindAnonymousDeclaration(node, 4096 /* ObjectLiteral */, "__object" /* Object */); + } + function bindJsxAttributes(node) { + return bindAnonymousDeclaration(node, 4096 /* ObjectLiteral */, "__jsxAttributes" /* JSXAttributes */); + } + function bindJsxAttribute(node, symbolFlags, symbolExcludes) { + return declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes); + } + function bindAnonymousDeclaration(node, symbolFlags, name) { + var symbol = createSymbol(symbolFlags, name); + if (symbolFlags & (8 /* EnumMember */ | 106500 /* ClassMember */)) { + symbol.parent = container.symbol; + } + addDeclarationToSymbol(symbol, node, symbolFlags); + return symbol; + } + function bindBlockScopedDeclaration(node, symbolFlags, symbolExcludes) { + switch (blockScopeContainer.kind) { + case 244 /* ModuleDeclaration */: + declareModuleMember(node, symbolFlags, symbolExcludes); + break; + case 279 /* SourceFile */: + if (ts.isExternalOrCommonJsModule(container)) { + declareModuleMember(node, symbolFlags, symbolExcludes); + break; + } + // falls through + default: + if (!blockScopeContainer.locals) { + blockScopeContainer.locals = ts.createSymbolTable(); + addToContainerChain(blockScopeContainer); + } + declareSymbol(blockScopeContainer.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes); + } + } + function delayedBindJSDocTypedefTag() { + if (!delayedTypeAliases) { + return; + } + var saveContainer = container; + var saveLastContainer = lastContainer; + var saveBlockScopeContainer = blockScopeContainer; + var saveParent = parent; + var saveCurrentFlow = currentFlow; + for (var _i = 0, delayedTypeAliases_1 = delayedTypeAliases; _i < delayedTypeAliases_1.length; _i++) { + var typeAlias = delayedTypeAliases_1[_i]; + var host = ts.getJSDocHost(typeAlias); + container = ts.findAncestor(host.parent, function (n) { return !!(getContainerFlags(n) & 1 /* IsContainer */); }) || file; + blockScopeContainer = ts.getEnclosingBlockScopeContainer(host) || file; + currentFlow = { flags: 2 /* Start */ }; + parent = typeAlias; + bind(typeAlias.typeExpression); + if (!typeAlias.fullName || typeAlias.fullName.kind === 72 /* Identifier */) { + parent = typeAlias.parent; + bindBlockScopedDeclaration(typeAlias, 524288 /* TypeAlias */, 67897832 /* TypeAliasExcludes */); + } + else { + bind(typeAlias.fullName); + } + } + container = saveContainer; + lastContainer = saveLastContainer; + blockScopeContainer = saveBlockScopeContainer; + parent = saveParent; + currentFlow = saveCurrentFlow; + } + // The binder visits every node in the syntax tree so it is a convenient place to perform a single localized + // check for reserved words used as identifiers in strict mode code. + function checkStrictModeIdentifier(node) { + if (inStrictMode && + node.originalKeywordKind >= 109 /* FirstFutureReservedWord */ && + node.originalKeywordKind <= 117 /* LastFutureReservedWord */ && + !ts.isIdentifierName(node) && + !(node.flags & 4194304 /* Ambient */)) { + // Report error only if there are no parse errors in file + if (!file.parseDiagnostics.length) { + file.bindDiagnostics.push(createDiagnosticForNode(node, getStrictModeIdentifierMessage(node), ts.declarationNameToString(node))); + } + } + } + function getStrictModeIdentifierMessage(node) { + // Provide specialized messages to help the user understand why we think they're in + // strict mode. + if (ts.getContainingClass(node)) { + return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode; + } + if (file.externalModuleIndicator) { + return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode; + } + return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode; + } + function checkStrictModeBinaryExpression(node) { + if (inStrictMode && ts.isLeftHandSideExpression(node.left) && ts.isAssignmentOperator(node.operatorToken.kind)) { + // ECMA 262 (Annex C) The identifier eval or arguments may not appear as the LeftHandSideExpression of an + // Assignment operator(11.13) or of a PostfixExpression(11.3) + checkStrictModeEvalOrArguments(node, node.left); + } + } + function checkStrictModeCatchClause(node) { + // It is a SyntaxError if a TryStatement with a Catch occurs within strict code and the Identifier of the + // Catch production is eval or arguments + if (inStrictMode && node.variableDeclaration) { + checkStrictModeEvalOrArguments(node, node.variableDeclaration.name); + } + } + function checkStrictModeDeleteExpression(node) { + // Grammar checking + if (inStrictMode && node.expression.kind === 72 /* Identifier */) { + // When a delete operator occurs within strict mode code, a SyntaxError is thrown if its + // UnaryExpression is a direct reference to a variable, function argument, or function name + var span = ts.getErrorSpanForNode(file, node.expression); + file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, ts.Diagnostics.delete_cannot_be_called_on_an_identifier_in_strict_mode)); + } + } + function isEvalOrArgumentsIdentifier(node) { + return ts.isIdentifier(node) && (node.escapedText === "eval" || node.escapedText === "arguments"); + } + function checkStrictModeEvalOrArguments(contextNode, name) { + if (name && name.kind === 72 /* Identifier */) { + var identifier = name; + if (isEvalOrArgumentsIdentifier(identifier)) { + // We check first if the name is inside class declaration or class expression; if so give explicit message + // otherwise report generic error message. + var span = ts.getErrorSpanForNode(file, name); + file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, getStrictModeEvalOrArgumentsMessage(contextNode), ts.idText(identifier))); + } + } + } + function getStrictModeEvalOrArgumentsMessage(node) { + // Provide specialized messages to help the user understand why we think they're in + // strict mode. + if (ts.getContainingClass(node)) { + return ts.Diagnostics.Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode; + } + if (file.externalModuleIndicator) { + return ts.Diagnostics.Invalid_use_of_0_Modules_are_automatically_in_strict_mode; + } + return ts.Diagnostics.Invalid_use_of_0_in_strict_mode; + } + function checkStrictModeFunctionName(node) { + if (inStrictMode) { + // It is a SyntaxError if the identifier eval or arguments appears within a FormalParameterList of a strict mode FunctionDeclaration or FunctionExpression (13.1)) + checkStrictModeEvalOrArguments(node, node.name); + } + } + function getStrictModeBlockScopeFunctionDeclarationMessage(node) { + // Provide specialized messages to help the user understand why we think they're in + // strict mode. + if (ts.getContainingClass(node)) { + return ts.Diagnostics.Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_definitions_are_automatically_in_strict_mode; + } + if (file.externalModuleIndicator) { + return ts.Diagnostics.Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_are_automatically_in_strict_mode; + } + return ts.Diagnostics.Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5; + } + function checkStrictModeFunctionDeclaration(node) { + if (languageVersion < 2 /* ES2015 */) { + // Report error if function is not top level function declaration + if (blockScopeContainer.kind !== 279 /* SourceFile */ && + blockScopeContainer.kind !== 244 /* ModuleDeclaration */ && + !ts.isFunctionLike(blockScopeContainer)) { + // We check first if the name is inside class declaration or class expression; if so give explicit message + // otherwise report generic error message. + var errorSpan = ts.getErrorSpanForNode(file, node); + file.bindDiagnostics.push(ts.createFileDiagnostic(file, errorSpan.start, errorSpan.length, getStrictModeBlockScopeFunctionDeclarationMessage(node))); + } + } + } + function checkStrictModeNumericLiteral(node) { + if (inStrictMode && node.numericLiteralFlags & 32 /* Octal */) { + file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Octal_literals_are_not_allowed_in_strict_mode)); + } + } + function checkStrictModePostfixUnaryExpression(node) { + // Grammar checking + // The identifier eval or arguments may not appear as the LeftHandSideExpression of an + // Assignment operator(11.13) or of a PostfixExpression(11.3) or as the UnaryExpression + // operated upon by a Prefix Increment(11.4.4) or a Prefix Decrement(11.4.5) operator. + if (inStrictMode) { + checkStrictModeEvalOrArguments(node, node.operand); + } + } + function checkStrictModePrefixUnaryExpression(node) { + // Grammar checking + if (inStrictMode) { + if (node.operator === 44 /* PlusPlusToken */ || node.operator === 45 /* MinusMinusToken */) { + checkStrictModeEvalOrArguments(node, node.operand); + } + } + } + function checkStrictModeWithStatement(node) { + // Grammar checking for withStatement + if (inStrictMode) { + errorOnFirstToken(node, ts.Diagnostics.with_statements_are_not_allowed_in_strict_mode); + } + } + function checkStrictModeLabeledStatement(node) { + // Grammar checking for labeledStatement + if (inStrictMode && options.target >= 2 /* ES2015 */) { + if (ts.isDeclarationStatement(node.statement) || ts.isVariableStatement(node.statement)) { + errorOnFirstToken(node.label, ts.Diagnostics.A_label_is_not_allowed_here); + } + } + } + function errorOnFirstToken(node, message, arg0, arg1, arg2) { + var span = ts.getSpanOfTokenAtPosition(file, node.pos); + file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, message, arg0, arg1, arg2)); + } + function errorOrSuggestionOnNode(isError, node, message) { + errorOrSuggestionOnRange(isError, node, node, message); + } + function errorOrSuggestionOnRange(isError, startNode, endNode, message) { + addErrorOrSuggestionDiagnostic(isError, { pos: ts.getTokenPosOfNode(startNode, file), end: endNode.end }, message); + } + function addErrorOrSuggestionDiagnostic(isError, range, message) { + var diag = ts.createFileDiagnostic(file, range.pos, range.end - range.pos, message); + if (isError) { + file.bindDiagnostics.push(diag); + } + else { + file.bindSuggestionDiagnostics = ts.append(file.bindSuggestionDiagnostics, __assign({}, diag, { category: ts.DiagnosticCategory.Suggestion })); + } + } + function bind(node) { + if (!node) { + return; + } + node.parent = parent; + var saveInStrictMode = inStrictMode; + // Even though in the AST the jsdoc @typedef node belongs to the current node, + // its symbol might be in the same scope with the current node's symbol. Consider: + // + // /** @typedef {string | number} MyType */ + // function foo(); + // + // Here the current node is "foo", which is a container, but the scope of "MyType" should + // not be inside "foo". Therefore we always bind @typedef before bind the parent node, + // and skip binding this tag later when binding all the other jsdoc tags. + // First we bind declaration nodes to a symbol if possible. We'll both create a symbol + // and then potentially add the symbol to an appropriate symbol table. Possible + // destination symbol tables are: + // + // 1) The 'exports' table of the current container's symbol. + // 2) The 'members' table of the current container's symbol. + // 3) The 'locals' table of the current container. + // + // However, not all symbols will end up in any of these tables. 'Anonymous' symbols + // (like TypeLiterals for example) will not be put in any table. + bindWorker(node); + // Then we recurse into the children of the node to bind them as well. For certain + // symbols we do specialized work when we recurse. For example, we'll keep track of + // the current 'container' node when it changes. This helps us know which symbol table + // a local should go into for example. Since terminal nodes are known not to have + // children, as an optimization we don't process those. + if (node.kind > 147 /* LastToken */) { + var saveParent = parent; + parent = node; + var containerFlags = getContainerFlags(node); + if (containerFlags === 0 /* None */) { + bindChildren(node); + } + else { + bindContainer(node, containerFlags); + } + parent = saveParent; + } + else if (!skipTransformFlagAggregation && (node.transformFlags & 536870912 /* HasComputedFlags */) === 0) { + subtreeTransformFlags |= computeTransformFlagsForNode(node, 0); + var saveParent = parent; + if (node.kind === 1 /* EndOfFileToken */) + parent = node; + bindJSDoc(node); + parent = saveParent; + } + inStrictMode = saveInStrictMode; + } + function bindJSDoc(node) { + if (ts.hasJSDocNodes(node)) { + if (ts.isInJSFile(node)) { + for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { + var j = _a[_i]; + bind(j); + } + } + else { + for (var _b = 0, _c = node.jsDoc; _b < _c.length; _b++) { + var j = _c[_b]; + setParentPointers(node, j); + } + } + } + } + function updateStrictModeStatementList(statements) { + if (!inStrictMode) { + for (var _i = 0, statements_1 = statements; _i < statements_1.length; _i++) { + var statement = statements_1[_i]; + if (!ts.isPrologueDirective(statement)) { + return; + } + if (isUseStrictPrologueDirective(statement)) { + inStrictMode = true; + return; + } + } + } + } + /// Should be called only on prologue directives (isPrologueDirective(node) should be true) + function isUseStrictPrologueDirective(node) { + var nodeText = ts.getSourceTextOfNodeFromSourceFile(file, node.expression); + // Note: the node text must be exactly "use strict" or 'use strict'. It is not ok for the + // string to contain unicode escapes (as per ES5). + return nodeText === '"use strict"' || nodeText === "'use strict'"; + } + function bindWorker(node) { + switch (node.kind) { + /* Strict mode checks */ + case 72 /* Identifier */: + // for typedef type names with namespaces, bind the new jsdoc type symbol here + // because it requires all containing namespaces to be in effect, namely the + // current "blockScopeContainer" needs to be set to its immediate namespace parent. + if (node.isInJSDocNamespace) { + var parentNode = node.parent; + while (parentNode && !ts.isJSDocTypeAlias(parentNode)) { + parentNode = parentNode.parent; + } + bindBlockScopedDeclaration(parentNode, 524288 /* TypeAlias */, 67897832 /* TypeAliasExcludes */); + break; + } + // falls through + case 100 /* ThisKeyword */: + if (currentFlow && (ts.isExpression(node) || parent.kind === 276 /* ShorthandPropertyAssignment */)) { + node.flowNode = currentFlow; + } + return checkStrictModeIdentifier(node); + case 189 /* PropertyAccessExpression */: + case 190 /* ElementAccessExpression */: + if (currentFlow && isNarrowableReference(node)) { + node.flowNode = currentFlow; + } + if (ts.isSpecialPropertyDeclaration(node)) { + bindSpecialPropertyDeclaration(node); + } + if (ts.isInJSFile(node) && + file.commonJsModuleIndicator && + ts.isModuleExportsPropertyAccessExpression(node) && + !lookupSymbolForNameWorker(blockScopeContainer, "module")) { + declareSymbol(file.locals, /*parent*/ undefined, node.expression, 1 /* FunctionScopedVariable */ | 134217728 /* ModuleExports */, 67220414 /* FunctionScopedVariableExcludes */); + } + break; + case 204 /* BinaryExpression */: + var specialKind = ts.getAssignmentDeclarationKind(node); + switch (specialKind) { + case 1 /* ExportsProperty */: + bindExportsPropertyAssignment(node); + break; + case 2 /* ModuleExports */: + bindModuleExportsAssignment(node); + break; + case 3 /* PrototypeProperty */: + bindPrototypePropertyAssignment(node.left, node); + break; + case 6 /* Prototype */: + bindPrototypeAssignment(node); + break; + case 4 /* ThisProperty */: + bindThisPropertyAssignment(node); + break; + case 5 /* Property */: + bindSpecialPropertyAssignment(node); + break; + case 0 /* None */: + // Nothing to do + break; + default: + ts.Debug.fail("Unknown binary expression special property assignment kind"); + } + return checkStrictModeBinaryExpression(node); + case 274 /* CatchClause */: + return checkStrictModeCatchClause(node); + case 198 /* DeleteExpression */: + return checkStrictModeDeleteExpression(node); + case 8 /* NumericLiteral */: + return checkStrictModeNumericLiteral(node); + case 203 /* PostfixUnaryExpression */: + return checkStrictModePostfixUnaryExpression(node); + case 202 /* PrefixUnaryExpression */: + return checkStrictModePrefixUnaryExpression(node); + case 231 /* WithStatement */: + return checkStrictModeWithStatement(node); + case 233 /* LabeledStatement */: + return checkStrictModeLabeledStatement(node); + case 178 /* ThisType */: + seenThisKeyword = true; + return; + case 163 /* TypePredicate */: + break; // Binding the children will handle everything + case 150 /* TypeParameter */: + return bindTypeParameter(node); + case 151 /* Parameter */: + return bindParameter(node); + case 237 /* VariableDeclaration */: + return bindVariableDeclarationOrBindingElement(node); + case 186 /* BindingElement */: + node.flowNode = currentFlow; + return bindVariableDeclarationOrBindingElement(node); + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + return bindPropertyWorker(node); + case 275 /* PropertyAssignment */: + case 276 /* ShorthandPropertyAssignment */: + return bindPropertyOrMethodOrAccessor(node, 4 /* Property */, 0 /* PropertyExcludes */); + case 278 /* EnumMember */: + return bindPropertyOrMethodOrAccessor(node, 8 /* EnumMember */, 68008959 /* EnumMemberExcludes */); + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 162 /* IndexSignature */: + return declareSymbolAndAddToSymbolTable(node, 131072 /* Signature */, 0 /* None */); + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + // If this is an ObjectLiteralExpression method, then it sits in the same space + // as other properties in the object literal. So we use SymbolFlags.PropertyExcludes + // so that it will conflict with any other object literal members with the same + // name. + return bindPropertyOrMethodOrAccessor(node, 8192 /* Method */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), ts.isObjectLiteralMethod(node) ? 0 /* PropertyExcludes */ : 67212223 /* MethodExcludes */); + case 239 /* FunctionDeclaration */: + return bindFunctionDeclaration(node); + case 157 /* Constructor */: + return declareSymbolAndAddToSymbolTable(node, 16384 /* Constructor */, /*symbolExcludes:*/ 0 /* None */); + case 158 /* GetAccessor */: + return bindPropertyOrMethodOrAccessor(node, 32768 /* GetAccessor */, 67154879 /* GetAccessorExcludes */); + case 159 /* SetAccessor */: + return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 67187647 /* SetAccessorExcludes */); + case 165 /* FunctionType */: + case 289 /* JSDocFunctionType */: + case 293 /* JSDocSignature */: + case 166 /* ConstructorType */: + return bindFunctionOrConstructorType(node); + case 168 /* TypeLiteral */: + case 292 /* JSDocTypeLiteral */: + case 181 /* MappedType */: + return bindAnonymousTypeWorker(node); + case 188 /* ObjectLiteralExpression */: + return bindObjectLiteralExpression(node); + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + return bindFunctionExpression(node); + case 191 /* CallExpression */: + var assignmentKind = ts.getAssignmentDeclarationKind(node); + switch (assignmentKind) { + case 7 /* ObjectDefinePropertyValue */: + return bindObjectDefinePropertyAssignment(node); + case 8 /* ObjectDefinePropertyExports */: + return bindObjectDefinePropertyExport(node); + case 9 /* ObjectDefinePrototypeProperty */: + return bindObjectDefinePrototypeProperty(node); + case 0 /* None */: + break; // Nothing to do + default: + return ts.Debug.fail("Unknown call expression assignment declaration kind"); + } + if (ts.isInJSFile(node)) { + bindCallExpression(node); + } + break; + // Members of classes, interfaces, and modules + case 209 /* ClassExpression */: + case 240 /* ClassDeclaration */: + // All classes are automatically in strict mode in ES6. + inStrictMode = true; + return bindClassLikeDeclaration(node); + case 241 /* InterfaceDeclaration */: + return bindBlockScopedDeclaration(node, 64 /* Interface */, 67897736 /* InterfaceExcludes */); + case 242 /* TypeAliasDeclaration */: + return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 67897832 /* TypeAliasExcludes */); + case 243 /* EnumDeclaration */: + return bindEnumDeclaration(node); + case 244 /* ModuleDeclaration */: + return bindModuleDeclaration(node); + // Jsx-attributes + case 268 /* JsxAttributes */: + return bindJsxAttributes(node); + case 267 /* JsxAttribute */: + return bindJsxAttribute(node, 4 /* Property */, 0 /* PropertyExcludes */); + // Imports and exports + case 248 /* ImportEqualsDeclaration */: + case 251 /* NamespaceImport */: + case 253 /* ImportSpecifier */: + case 257 /* ExportSpecifier */: + return declareSymbolAndAddToSymbolTable(node, 2097152 /* Alias */, 2097152 /* AliasExcludes */); + case 247 /* NamespaceExportDeclaration */: + return bindNamespaceExportDeclaration(node); + case 250 /* ImportClause */: + return bindImportClause(node); + case 255 /* ExportDeclaration */: + return bindExportDeclaration(node); + case 254 /* ExportAssignment */: + return bindExportAssignment(node); + case 279 /* SourceFile */: + updateStrictModeStatementList(node.statements); + return bindSourceFileIfExternalModule(); + case 218 /* Block */: + if (!ts.isFunctionLike(node.parent)) { + return; + } + // falls through + case 245 /* ModuleBlock */: + return updateStrictModeStatementList(node.statements); + case 299 /* JSDocParameterTag */: + if (node.parent.kind === 293 /* JSDocSignature */) { + return bindParameter(node); + } + if (node.parent.kind !== 292 /* JSDocTypeLiteral */) { + break; + } + // falls through + case 305 /* JSDocPropertyTag */: + var propTag = node; + var flags = propTag.isBracketed || propTag.typeExpression && propTag.typeExpression.type.kind === 288 /* JSDocOptionalType */ ? + 4 /* Property */ | 16777216 /* Optional */ : + 4 /* Property */; + return declareSymbolAndAddToSymbolTable(propTag, flags, 0 /* PropertyExcludes */); + case 304 /* JSDocTypedefTag */: + case 297 /* JSDocCallbackTag */: + return (delayedTypeAliases || (delayedTypeAliases = [])).push(node); + } + } + function bindPropertyWorker(node) { + return bindPropertyOrMethodOrAccessor(node, 4 /* Property */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), 0 /* PropertyExcludes */); + } + function bindAnonymousTypeWorker(node) { + return bindAnonymousDeclaration(node, 2048 /* TypeLiteral */, "__type" /* Type */); + } + function bindSourceFileIfExternalModule() { + setExportContextFlag(file); + if (ts.isExternalModule(file)) { + bindSourceFileAsExternalModule(); + } + else if (ts.isJsonSourceFile(file)) { + bindSourceFileAsExternalModule(); + // Create symbol equivalent for the module.exports = {} + var originalSymbol = file.symbol; + declareSymbol(file.symbol.exports, file.symbol, file, 4 /* Property */, 67108863 /* All */); + file.symbol = originalSymbol; + } + } + function bindSourceFileAsExternalModule() { + bindAnonymousDeclaration(file, 512 /* ValueModule */, "\"" + ts.removeFileExtension(file.fileName) + "\""); + } + function bindExportAssignment(node) { + if (!container.symbol || !container.symbol.exports) { + // Export assignment in some sort of block construct + bindAnonymousDeclaration(node, 2097152 /* Alias */, getDeclarationName(node)); + } + else { + var flags = ts.exportAssignmentIsAlias(node) + // An export default clause with an EntityNameExpression or a class expression exports all meanings of that identifier or expression; + ? 2097152 /* Alias */ + // An export default clause with any other expression exports a value + : 4 /* Property */; + // If there is an `export default x;` alias declaration, can't `export default` anything else. + // (In contrast, you can still have `export default function f() {}` and `export default interface I {}`.) + var symbol = declareSymbol(container.symbol.exports, container.symbol, node, flags, 67108863 /* All */); + if (node.isExportEquals) { + // Will be an error later, since the module already has other exports. Just make sure this has a valueDeclaration set. + setValueDeclaration(symbol, node); + } + } + } + function bindNamespaceExportDeclaration(node) { + if (node.modifiers && node.modifiers.length) { + file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Modifiers_cannot_appear_here)); + } + var diag = !ts.isSourceFile(node.parent) ? ts.Diagnostics.Global_module_exports_may_only_appear_at_top_level + : !ts.isExternalModule(node.parent) ? ts.Diagnostics.Global_module_exports_may_only_appear_in_module_files + : !node.parent.isDeclarationFile ? ts.Diagnostics.Global_module_exports_may_only_appear_in_declaration_files + : undefined; + if (diag) { + file.bindDiagnostics.push(createDiagnosticForNode(node, diag)); + } + else { + file.symbol.globalExports = file.symbol.globalExports || ts.createSymbolTable(); + declareSymbol(file.symbol.globalExports, file.symbol, node, 2097152 /* Alias */, 2097152 /* AliasExcludes */); + } + } + function bindExportDeclaration(node) { + if (!container.symbol || !container.symbol.exports) { + // Export * in some sort of block construct + bindAnonymousDeclaration(node, 8388608 /* ExportStar */, getDeclarationName(node)); + } + else if (!node.exportClause) { + // All export * declarations are collected in an __export symbol + declareSymbol(container.symbol.exports, container.symbol, node, 8388608 /* ExportStar */, 0 /* None */); + } + } + function bindImportClause(node) { + if (node.name) { + declareSymbolAndAddToSymbolTable(node, 2097152 /* Alias */, 2097152 /* AliasExcludes */); + } + } + function setCommonJsModuleIndicator(node) { + if (file.externalModuleIndicator) { + return false; + } + if (!file.commonJsModuleIndicator) { + file.commonJsModuleIndicator = node; + bindSourceFileAsExternalModule(); + } + return true; + } + function bindObjectDefinePropertyExport(node) { + if (!setCommonJsModuleIndicator(node)) { + return; + } + var symbol = forEachIdentifierInEntityName(node.arguments[0], /*parent*/ undefined, function (id, symbol) { + if (symbol) { + addDeclarationToSymbol(symbol, id, 1536 /* Module */ | 67108864 /* Assignment */); + } + return symbol; + }); + if (symbol) { + var flags = 4 /* Property */ | 1048576 /* ExportValue */; + declareSymbol(symbol.exports, symbol, node, flags, 0 /* None */); + } + } + function bindExportsPropertyAssignment(node) { + // When we create a property via 'exports.foo = bar', the 'exports.foo' property access + // expression is the declaration + if (!setCommonJsModuleIndicator(node)) { + return; + } + var lhs = node.left; + var symbol = forEachIdentifierInEntityName(lhs.expression, /*parent*/ undefined, function (id, symbol) { + if (symbol) { + addDeclarationToSymbol(symbol, id, 1536 /* Module */ | 67108864 /* Assignment */); + } + return symbol; + }); + if (symbol) { + var flags = ts.isClassExpression(node.right) ? + 4 /* Property */ | 1048576 /* ExportValue */ | 32 /* Class */ : + 4 /* Property */ | 1048576 /* ExportValue */; + declareSymbol(symbol.exports, symbol, lhs, flags, 0 /* None */); + } + } + function bindModuleExportsAssignment(node) { + // A common practice in node modules is to set 'export = module.exports = {}', this ensures that 'exports' + // is still pointing to 'module.exports'. + // We do not want to consider this as 'export=' since a module can have only one of these. + // Similarly we do not want to treat 'module.exports = exports' as an 'export='. + if (!setCommonJsModuleIndicator(node)) { + return; + } + var assignedExpression = ts.getRightMostAssignedExpression(node.right); + if (ts.isEmptyObjectLiteral(assignedExpression) || container === file && isExportsOrModuleExportsOrAlias(file, assignedExpression)) { + return; + } + // 'module.exports = expr' assignment + var flags = ts.exportAssignmentIsAlias(node) + ? 2097152 /* Alias */ + : 4 /* Property */ | 1048576 /* ExportValue */ | 512 /* ValueModule */; + declareSymbol(file.symbol.exports, file.symbol, node, flags | 67108864 /* Assignment */, 0 /* None */); + } + function bindThisPropertyAssignment(node) { + ts.Debug.assert(ts.isInJSFile(node)); + var thisContainer = ts.getThisContainer(node, /*includeArrowFunctions*/ false); + switch (thisContainer.kind) { + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + var constructorSymbol = thisContainer.symbol; + // For `f.prototype.m = function() { this.x = 0; }`, `this.x = 0` should modify `f`'s members, not the function expression. + if (ts.isBinaryExpression(thisContainer.parent) && thisContainer.parent.operatorToken.kind === 59 /* EqualsToken */) { + var l = thisContainer.parent.left; + if (ts.isPropertyAccessEntityNameExpression(l) && ts.isPrototypeAccess(l.expression)) { + constructorSymbol = lookupSymbolForPropertyAccess(l.expression.expression, thisParentContainer); + } + } + if (constructorSymbol) { + // Declare a 'member' if the container is an ES5 class or ES6 constructor + constructorSymbol.members = constructorSymbol.members || ts.createSymbolTable(); + // It's acceptable for multiple 'this' assignments of the same identifier to occur + declareSymbol(constructorSymbol.members, constructorSymbol, node, 4 /* Property */, 0 /* PropertyExcludes */ & ~4 /* Property */); + } + break; + case 157 /* Constructor */: + case 154 /* PropertyDeclaration */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + // this.foo assignment in a JavaScript class + // Bind this property to the containing class + var containingClass = thisContainer.parent; + var symbolTable = ts.hasModifier(thisContainer, 32 /* Static */) ? containingClass.symbol.exports : containingClass.symbol.members; + declareSymbol(symbolTable, containingClass.symbol, node, 4 /* Property */, 0 /* None */, /*isReplaceableByMethod*/ true); + break; + case 279 /* SourceFile */: + // this.foo assignment in a source file + // Do not bind. It would be nice to support this someday though. + break; + default: + ts.Debug.fail(ts.Debug.showSyntaxKind(thisContainer)); + } + } + function bindSpecialPropertyDeclaration(node) { + if (node.expression.kind === 100 /* ThisKeyword */) { + bindThisPropertyAssignment(node); + } + else if (ts.isPropertyAccessEntityNameExpression(node) && node.parent.parent.kind === 279 /* SourceFile */) { + if (ts.isPrototypeAccess(node.expression)) { + bindPrototypePropertyAssignment(node, node.parent); + } + else { + bindStaticPropertyAssignment(node); + } + } + } + /** For `x.prototype = { p, ... }`, declare members p,... if `x` is function/class/{}, or not declared. */ + function bindPrototypeAssignment(node) { + node.left.parent = node; + node.right.parent = node; + var lhs = node.left; + bindPropertyAssignment(lhs.expression, lhs, /*isPrototypeProperty*/ false); + } + function bindObjectDefinePrototypeProperty(node) { + var namespaceSymbol = lookupSymbolForPropertyAccess(node.arguments[0].expression); + bindPotentiallyNewExpandoMemberToNamespace(node, namespaceSymbol, /*isPrototypeProperty*/ true); + } + /** + * For `x.prototype.y = z`, declare a member `y` on `x` if `x` is a function or class, or not declared. + * Note that jsdoc preceding an ExpressionStatement like `x.prototype.y;` is also treated as a declaration. + */ + function bindPrototypePropertyAssignment(lhs, parent) { + // Look up the function in the local scope, since prototype assignments should + // follow the function declaration + var classPrototype = lhs.expression; + var constructorFunction = classPrototype.expression; + // Fix up parent pointers since we're going to use these nodes before we bind into them + lhs.parent = parent; + constructorFunction.parent = classPrototype; + classPrototype.parent = lhs; + bindPropertyAssignment(constructorFunction, lhs, /*isPrototypeProperty*/ true); + } + function bindObjectDefinePropertyAssignment(node) { + var namespaceSymbol = lookupSymbolForPropertyAccess(node.arguments[0]); + var isToplevel = node.parent.parent.kind === 279 /* SourceFile */; + namespaceSymbol = bindPotentiallyMissingNamespaces(namespaceSymbol, node.arguments[0], isToplevel, /*isPrototypeProperty*/ false); + bindPotentiallyNewExpandoMemberToNamespace(node, namespaceSymbol, /*isPrototypeProperty*/ false); + } + function bindSpecialPropertyAssignment(node) { + var lhs = node.left; + // Class declarations in Typescript do not allow property declarations + var parentSymbol = lookupSymbolForPropertyAccess(lhs.expression); + if (!ts.isInJSFile(node) && !ts.isFunctionSymbol(parentSymbol)) { + return; + } + // Fix up parent pointers since we're going to use these nodes before we bind into them + node.left.parent = node; + node.right.parent = node; + if (ts.isIdentifier(lhs.expression) && container === file && isNameOfExportsOrModuleExportsAliasDeclaration(file, lhs.expression)) { + // This can be an alias for the 'exports' or 'module.exports' names, e.g. + // var util = module.exports; + // util.property = function ... + bindExportsPropertyAssignment(node); + } + else { + bindStaticPropertyAssignment(lhs); + } + } + /** + * For nodes like `x.y = z`, declare a member 'y' on 'x' if x is a function (or IIFE) or class or {}, or not declared. + * Also works for expression statements preceded by JSDoc, like / ** @type number * / x.y; + */ + function bindStaticPropertyAssignment(node) { + node.expression.parent = node; + bindPropertyAssignment(node.expression, node, /*isPrototypeProperty*/ false); + } + function bindPotentiallyMissingNamespaces(namespaceSymbol, entityName, isToplevel, isPrototypeProperty) { + if (isToplevel && !isPrototypeProperty && (!namespaceSymbol || !(namespaceSymbol.flags & 1920 /* Namespace */))) { + // make symbols or add declarations for intermediate containers + var flags_1 = 1536 /* Module */ | 67108864 /* Assignment */; + var excludeFlags_1 = 110735 /* ValueModuleExcludes */ & ~67108864 /* Assignment */; + namespaceSymbol = forEachIdentifierInEntityName(entityName, namespaceSymbol, function (id, symbol, parent) { + if (symbol) { + addDeclarationToSymbol(symbol, id, flags_1); + return symbol; + } + else { + var table = parent ? parent.exports : + file.jsGlobalAugmentations || (file.jsGlobalAugmentations = ts.createSymbolTable()); + return declareSymbol(table, parent, id, flags_1, excludeFlags_1); + } + }); + } + return namespaceSymbol; + } + function bindPotentiallyNewExpandoMemberToNamespace(declaration, namespaceSymbol, isPrototypeProperty) { + if (!namespaceSymbol || !isExpandoSymbol(namespaceSymbol)) { + return; + } + // Set up the members collection if it doesn't exist already + var symbolTable = isPrototypeProperty ? + (namespaceSymbol.members || (namespaceSymbol.members = ts.createSymbolTable())) : + (namespaceSymbol.exports || (namespaceSymbol.exports = ts.createSymbolTable())); + var isMethod = ts.isFunctionLikeDeclaration(ts.getAssignedExpandoInitializer(declaration)); + var includes = isMethod ? 8192 /* Method */ : 4 /* Property */; + var excludes = isMethod ? 67212223 /* MethodExcludes */ : 0 /* PropertyExcludes */; + declareSymbol(symbolTable, namespaceSymbol, declaration, includes | 67108864 /* Assignment */, excludes & ~67108864 /* Assignment */); + } + function bindPropertyAssignment(name, propertyAccess, isPrototypeProperty) { + var namespaceSymbol = lookupSymbolForPropertyAccess(name); + var isToplevel = ts.isBinaryExpression(propertyAccess.parent) + ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 279 /* SourceFile */ + : propertyAccess.parent.parent.kind === 279 /* SourceFile */; + namespaceSymbol = bindPotentiallyMissingNamespaces(namespaceSymbol, propertyAccess.expression, isToplevel, isPrototypeProperty); + bindPotentiallyNewExpandoMemberToNamespace(propertyAccess, namespaceSymbol, isPrototypeProperty); + } + /** + * Javascript expando values are: + * - Functions + * - classes + * - namespaces + * - variables initialized with function expressions + * - with class expressions + * - with empty object literals + * - with non-empty object literals if assigned to the prototype property + */ + function isExpandoSymbol(symbol) { + if (symbol.flags & (16 /* Function */ | 32 /* Class */ | 1024 /* NamespaceModule */)) { + return true; + } + var node = symbol.valueDeclaration; + if (node && ts.isCallExpression(node)) { + return !!ts.getAssignedExpandoInitializer(node); + } + var init = !node ? undefined : + ts.isVariableDeclaration(node) ? node.initializer : + ts.isBinaryExpression(node) ? node.right : + ts.isPropertyAccessExpression(node) && ts.isBinaryExpression(node.parent) ? node.parent.right : + undefined; + init = init && ts.getRightMostAssignedExpression(init); + if (init) { + var isPrototypeAssignment = ts.isPrototypeAccess(ts.isVariableDeclaration(node) ? node.name : ts.isBinaryExpression(node) ? node.left : node); + return !!ts.getExpandoInitializer(ts.isBinaryExpression(init) && init.operatorToken.kind === 55 /* BarBarToken */ ? init.right : init, isPrototypeAssignment); + } + return false; + } + function getParentOfBinaryExpression(expr) { + while (ts.isBinaryExpression(expr.parent)) { + expr = expr.parent; + } + return expr.parent; + } + function lookupSymbolForPropertyAccess(node, lookupContainer) { + if (lookupContainer === void 0) { lookupContainer = container; } + if (ts.isIdentifier(node)) { + return lookupSymbolForNameWorker(lookupContainer, node.escapedText); + } + else { + var symbol = lookupSymbolForPropertyAccess(node.expression); + return symbol && symbol.exports && symbol.exports.get(node.name.escapedText); + } + } + function forEachIdentifierInEntityName(e, parent, action) { + if (isExportsOrModuleExportsOrAlias(file, e)) { + return file.symbol; + } + else if (ts.isIdentifier(e)) { + return action(e, lookupSymbolForPropertyAccess(e), parent); + } + else { + var s = forEachIdentifierInEntityName(e.expression, parent, action); + if (!s || !s.exports) + return ts.Debug.fail(); + return action(e.name, s.exports.get(e.name.escapedText), s); + } + } + function bindCallExpression(node) { + // We're only inspecting call expressions to detect CommonJS modules, so we can skip + // this check if we've already seen the module indicator + if (!file.commonJsModuleIndicator && ts.isRequireCall(node, /*checkArgumentIsStringLiteralLike*/ false)) { + setCommonJsModuleIndicator(node); + } + } + function bindClassLikeDeclaration(node) { + if (node.kind === 240 /* ClassDeclaration */) { + bindBlockScopedDeclaration(node, 32 /* Class */, 68008383 /* ClassExcludes */); + } + else { + var bindingName = node.name ? node.name.escapedText : "__class" /* Class */; + bindAnonymousDeclaration(node, 32 /* Class */, bindingName); + // Add name of class expression into the map for semantic classifier + if (node.name) { + classifiableNames.set(node.name.escapedText, true); + } + } + var symbol = node.symbol; + // TypeScript 1.0 spec (April 2014): 8.4 + // Every class automatically contains a static property member named 'prototype', the + // type of which is an instantiation of the class type with type Any supplied as a type + // argument for each type parameter. It is an error to explicitly declare a static + // property member with the name 'prototype'. + // + // Note: we check for this here because this class may be merging into a module. The + // module might have an exported variable called 'prototype'. We can't allow that as + // that would clash with the built-in 'prototype' for the class. + var prototypeSymbol = createSymbol(4 /* Property */ | 4194304 /* Prototype */, "prototype"); + var symbolExport = symbol.exports.get(prototypeSymbol.escapedName); + if (symbolExport) { + if (node.name) { + node.name.parent = node; + } + file.bindDiagnostics.push(createDiagnosticForNode(symbolExport.declarations[0], ts.Diagnostics.Duplicate_identifier_0, ts.symbolName(prototypeSymbol))); + } + symbol.exports.set(prototypeSymbol.escapedName, prototypeSymbol); + prototypeSymbol.parent = symbol; + } + function bindEnumDeclaration(node) { + return ts.isEnumConst(node) + ? bindBlockScopedDeclaration(node, 128 /* ConstEnum */, 68008831 /* ConstEnumExcludes */) + : bindBlockScopedDeclaration(node, 256 /* RegularEnum */, 68008191 /* RegularEnumExcludes */); + } + function bindVariableDeclarationOrBindingElement(node) { + if (inStrictMode) { + checkStrictModeEvalOrArguments(node, node.name); + } + if (!ts.isBindingPattern(node.name)) { + var isEnum = ts.isInJSFile(node) && !!ts.getJSDocEnumTag(node); + var enumFlags = (isEnum ? 256 /* RegularEnum */ : 0 /* None */); + var enumExcludes = (isEnum ? 68008191 /* RegularEnumExcludes */ : 0 /* None */); + if (ts.isBlockOrCatchScoped(node)) { + bindBlockScopedDeclaration(node, 2 /* BlockScopedVariable */ | enumFlags, 67220415 /* BlockScopedVariableExcludes */ | enumExcludes); + } + else if (ts.isParameterDeclaration(node)) { + // It is safe to walk up parent chain to find whether the node is a destructuring parameter declaration + // because its parent chain has already been set up, since parents are set before descending into children. + // + // If node is a binding element in parameter declaration, we need to use ParameterExcludes. + // Using ParameterExcludes flag allows the compiler to report an error on duplicate identifiers in Parameter Declaration + // For example: + // function foo([a,a]) {} // Duplicate Identifier error + // function bar(a,a) {} // Duplicate Identifier error, parameter declaration in this case is handled in bindParameter + // // which correctly set excluded symbols + declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67220415 /* ParameterExcludes */); + } + else { + declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */ | enumFlags, 67220414 /* FunctionScopedVariableExcludes */ | enumExcludes); + } + } + } + function bindParameter(node) { + if (node.kind === 299 /* JSDocParameterTag */ && container.kind !== 293 /* JSDocSignature */) { + return; + } + if (inStrictMode && !(node.flags & 4194304 /* Ambient */)) { + // It is a SyntaxError if the identifier eval or arguments appears within a FormalParameterList of a + // strict mode FunctionLikeDeclaration or FunctionExpression(13.1) + checkStrictModeEvalOrArguments(node, node.name); + } + if (ts.isBindingPattern(node.name)) { + bindAnonymousDeclaration(node, 1 /* FunctionScopedVariable */, "__" + node.parent.parameters.indexOf(node)); + } + else { + declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67220415 /* ParameterExcludes */); + } + // If this is a property-parameter, then also declare the property symbol into the + // containing class. + if (ts.isParameterPropertyDeclaration(node)) { + var classDeclaration = node.parent.parent; + declareSymbol(classDeclaration.symbol.members, classDeclaration.symbol, node, 4 /* Property */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), 0 /* PropertyExcludes */); + } + } + function bindFunctionDeclaration(node) { + if (!file.isDeclarationFile && !(node.flags & 4194304 /* Ambient */)) { + if (ts.isAsyncFunction(node)) { + emitFlags |= 1024 /* HasAsyncFunctions */; + } + } + checkStrictModeFunctionName(node); + if (inStrictMode) { + checkStrictModeFunctionDeclaration(node); + bindBlockScopedDeclaration(node, 16 /* Function */, 67219887 /* FunctionExcludes */); + } + else { + declareSymbolAndAddToSymbolTable(node, 16 /* Function */, 67219887 /* FunctionExcludes */); + } + } + function bindFunctionExpression(node) { + if (!file.isDeclarationFile && !(node.flags & 4194304 /* Ambient */)) { + if (ts.isAsyncFunction(node)) { + emitFlags |= 1024 /* HasAsyncFunctions */; + } + } + if (currentFlow) { + node.flowNode = currentFlow; + } + checkStrictModeFunctionName(node); + var bindingName = node.name ? node.name.escapedText : "__function" /* Function */; + return bindAnonymousDeclaration(node, 16 /* Function */, bindingName); + } + function bindPropertyOrMethodOrAccessor(node, symbolFlags, symbolExcludes) { + if (!file.isDeclarationFile && !(node.flags & 4194304 /* Ambient */) && ts.isAsyncFunction(node)) { + emitFlags |= 1024 /* HasAsyncFunctions */; + } + if (currentFlow && ts.isObjectLiteralOrClassExpressionMethod(node)) { + node.flowNode = currentFlow; + } + return ts.hasDynamicName(node) + ? bindAnonymousDeclaration(node, symbolFlags, "__computed" /* Computed */) + : declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes); + } + function getInferTypeContainer(node) { + var extendsType = ts.findAncestor(node, function (n) { return n.parent && ts.isConditionalTypeNode(n.parent) && n.parent.extendsType === n; }); + return extendsType && extendsType.parent; + } + function bindTypeParameter(node) { + if (ts.isJSDocTemplateTag(node.parent)) { + var container_1 = ts.find(node.parent.parent.tags, ts.isJSDocTypeAlias) || ts.getHostSignatureFromJSDoc(node.parent); // TODO: GH#18217 + if (container_1) { + if (!container_1.locals) { + container_1.locals = ts.createSymbolTable(); + } + declareSymbol(container_1.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 67635688 /* TypeParameterExcludes */); + } + else { + declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 67635688 /* TypeParameterExcludes */); + } + } + else if (node.parent.kind === 176 /* InferType */) { + var container_2 = getInferTypeContainer(node.parent); + if (container_2) { + if (!container_2.locals) { + container_2.locals = ts.createSymbolTable(); + } + declareSymbol(container_2.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 67635688 /* TypeParameterExcludes */); + } + else { + bindAnonymousDeclaration(node, 262144 /* TypeParameter */, getDeclarationName(node)); // TODO: GH#18217 + } + } + else { + declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 67635688 /* TypeParameterExcludes */); + } + } + // reachability checks + function shouldReportErrorOnModuleDeclaration(node) { + var instanceState = getModuleInstanceState(node); + return instanceState === 1 /* Instantiated */ || (instanceState === 2 /* ConstEnumOnly */ && !!options.preserveConstEnums); + } + function checkUnreachable(node) { + if (!(currentFlow.flags & 1 /* Unreachable */)) { + return false; + } + if (currentFlow === unreachableFlow) { + var reportError = + // report error on all statements except empty ones + (ts.isStatementButNotDeclaration(node) && node.kind !== 220 /* EmptyStatement */) || + // report error on class declarations + node.kind === 240 /* ClassDeclaration */ || + // report error on instantiated modules or const-enums only modules if preserveConstEnums is set + (node.kind === 244 /* ModuleDeclaration */ && shouldReportErrorOnModuleDeclaration(node)); + if (reportError) { + currentFlow = reportedUnreachableFlow; + if (!options.allowUnreachableCode) { + // unreachable code is reported if + // - user has explicitly asked about it AND + // - statement is in not ambient context (statements in ambient context is already an error + // so we should not report extras) AND + // - node is not variable statement OR + // - node is block scoped variable statement OR + // - node is not block scoped variable statement and at least one variable declaration has initializer + // Rationale: we don't want to report errors on non-initialized var's since they are hoisted + // On the other side we do want to report errors on non-initialized 'lets' because of TDZ + var isError_1 = ts.unreachableCodeIsError(options) && + !(node.flags & 4194304 /* Ambient */) && + (!ts.isVariableStatement(node) || + !!(ts.getCombinedNodeFlags(node.declarationList) & 3 /* BlockScoped */) || + node.declarationList.declarations.some(function (d) { return !!d.initializer; })); + eachUnreachableRange(node, function (start, end) { return errorOrSuggestionOnRange(isError_1, start, end, ts.Diagnostics.Unreachable_code_detected); }); + } + } + } + return true; + } + } + function eachUnreachableRange(node, cb) { + if (ts.isStatement(node) && isExecutableStatement(node) && ts.isBlock(node.parent)) { + var statements = node.parent.statements; + var slice_1 = ts.sliceAfter(statements, node); + ts.getRangesWhere(slice_1, isExecutableStatement, function (start, afterEnd) { return cb(slice_1[start], slice_1[afterEnd - 1]); }); + } + else { + cb(node, node); + } + } + // As opposed to a pure declaration like an `interface` + function isExecutableStatement(s) { + // Don't remove statements that can validly be used before they appear. + return !ts.isFunctionDeclaration(s) && !isPurelyTypeDeclaration(s) && !ts.isEnumDeclaration(s) && + // `var x;` may declare a variable used above + !(ts.isVariableStatement(s) && !(ts.getCombinedNodeFlags(s) & (1 /* Let */ | 2 /* Const */)) && s.declarationList.declarations.some(function (d) { return !d.initializer; })); + } + function isPurelyTypeDeclaration(s) { + switch (s.kind) { + case 241 /* InterfaceDeclaration */: + case 242 /* TypeAliasDeclaration */: + return true; + case 244 /* ModuleDeclaration */: + return getModuleInstanceState(s) !== 1 /* Instantiated */; + case 243 /* EnumDeclaration */: + return ts.hasModifier(s, 2048 /* Const */); + default: + return false; + } + } + function isExportsOrModuleExportsOrAlias(sourceFile, node) { + return ts.isExportsIdentifier(node) || + ts.isModuleExportsPropertyAccessExpression(node) || + ts.isIdentifier(node) && isNameOfExportsOrModuleExportsAliasDeclaration(sourceFile, node); + } + ts.isExportsOrModuleExportsOrAlias = isExportsOrModuleExportsOrAlias; + function isNameOfExportsOrModuleExportsAliasDeclaration(sourceFile, node) { + var symbol = lookupSymbolForNameWorker(sourceFile, node.escapedText); + return !!symbol && !!symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && + !!symbol.valueDeclaration.initializer && isExportsOrModuleExportsOrAliasOrAssignment(sourceFile, symbol.valueDeclaration.initializer); + } + function isExportsOrModuleExportsOrAliasOrAssignment(sourceFile, node) { + return isExportsOrModuleExportsOrAlias(sourceFile, node) || + (ts.isAssignmentExpression(node, /*excludeCompoundAssignment*/ true) && (isExportsOrModuleExportsOrAliasOrAssignment(sourceFile, node.left) || isExportsOrModuleExportsOrAliasOrAssignment(sourceFile, node.right))); + } + function lookupSymbolForNameWorker(container, name) { + var local = container.locals && container.locals.get(name); + if (local) { + return local.exportSymbol || local; + } + if (ts.isSourceFile(container) && container.jsGlobalAugmentations && container.jsGlobalAugmentations.has(name)) { + return container.jsGlobalAugmentations.get(name); + } + return container.symbol && container.symbol.exports && container.symbol.exports.get(name); + } + /** + * Computes the transform flags for a node, given the transform flags of its subtree + * + * @param node The node to analyze + * @param subtreeFlags Transform flags computed for this node's subtree + */ + function computeTransformFlagsForNode(node, subtreeFlags) { + var kind = node.kind; + switch (kind) { + case 191 /* CallExpression */: + return computeCallExpression(node, subtreeFlags); + case 192 /* NewExpression */: + return computeNewExpression(node, subtreeFlags); + case 244 /* ModuleDeclaration */: + return computeModuleDeclaration(node, subtreeFlags); + case 195 /* ParenthesizedExpression */: + return computeParenthesizedExpression(node, subtreeFlags); + case 204 /* BinaryExpression */: + return computeBinaryExpression(node, subtreeFlags); + case 221 /* ExpressionStatement */: + return computeExpressionStatement(node, subtreeFlags); + case 151 /* Parameter */: + return computeParameter(node, subtreeFlags); + case 197 /* ArrowFunction */: + return computeArrowFunction(node, subtreeFlags); + case 196 /* FunctionExpression */: + return computeFunctionExpression(node, subtreeFlags); + case 239 /* FunctionDeclaration */: + return computeFunctionDeclaration(node, subtreeFlags); + case 237 /* VariableDeclaration */: + return computeVariableDeclaration(node, subtreeFlags); + case 238 /* VariableDeclarationList */: + return computeVariableDeclarationList(node, subtreeFlags); + case 219 /* VariableStatement */: + return computeVariableStatement(node, subtreeFlags); + case 233 /* LabeledStatement */: + return computeLabeledStatement(node, subtreeFlags); + case 240 /* ClassDeclaration */: + return computeClassDeclaration(node, subtreeFlags); + case 209 /* ClassExpression */: + return computeClassExpression(node, subtreeFlags); + case 273 /* HeritageClause */: + return computeHeritageClause(node, subtreeFlags); + case 274 /* CatchClause */: + return computeCatchClause(node, subtreeFlags); + case 211 /* ExpressionWithTypeArguments */: + return computeExpressionWithTypeArguments(node, subtreeFlags); + case 157 /* Constructor */: + return computeConstructor(node, subtreeFlags); + case 154 /* PropertyDeclaration */: + return computePropertyDeclaration(node, subtreeFlags); + case 156 /* MethodDeclaration */: + return computeMethod(node, subtreeFlags); + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + return computeAccessor(node, subtreeFlags); + case 248 /* ImportEqualsDeclaration */: + return computeImportEquals(node, subtreeFlags); + case 189 /* PropertyAccessExpression */: + return computePropertyAccess(node, subtreeFlags); + case 190 /* ElementAccessExpression */: + return computeElementAccess(node, subtreeFlags); + default: + return computeOther(node, kind, subtreeFlags); + } + } + ts.computeTransformFlagsForNode = computeTransformFlagsForNode; + function computeCallExpression(node, subtreeFlags) { + var transformFlags = subtreeFlags; + var expression = node.expression; + if (node.typeArguments) { + transformFlags |= 3 /* AssertTypeScript */; + } + if (subtreeFlags & 131072 /* ContainsRestOrSpread */ + || (expression.transformFlags & (33554432 /* Super */ | 67108864 /* ContainsSuper */))) { + // If the this node contains a SpreadExpression, or is a super call, then it is an ES6 + // node. + transformFlags |= 192 /* AssertES2015 */; + // super property or element accesses could be inside lambdas, etc, and need a captured `this`, + // while super keyword for super calls (indicated by TransformFlags.Super) does not (since it can only be top-level in a constructor) + if (expression.transformFlags & 67108864 /* ContainsSuper */) { + transformFlags |= 8192 /* ContainsLexicalThis */; + } + } + if (expression.kind === 92 /* ImportKeyword */) { + transformFlags |= 16777216 /* ContainsDynamicImport */; + // A dynamic 'import()' call that contains a lexical 'this' will + // require a captured 'this' when emitting down-level. + if (subtreeFlags & 8192 /* ContainsLexicalThis */) { + transformFlags |= 16384 /* ContainsCapturedLexicalThis */; + } + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~637666625 /* ArrayLiteralOrCallOrNewExcludes */; + } + function computeNewExpression(node, subtreeFlags) { + var transformFlags = subtreeFlags; + if (node.typeArguments) { + transformFlags |= 3 /* AssertTypeScript */; + } + if (subtreeFlags & 131072 /* ContainsRestOrSpread */) { + // If the this node contains a SpreadElementExpression then it is an ES6 + // node. + transformFlags |= 192 /* AssertES2015 */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~637666625 /* ArrayLiteralOrCallOrNewExcludes */; + } + function computeBinaryExpression(node, subtreeFlags) { + var transformFlags = subtreeFlags; + var operatorTokenKind = node.operatorToken.kind; + var leftKind = node.left.kind; + if (operatorTokenKind === 59 /* EqualsToken */ && leftKind === 188 /* ObjectLiteralExpression */) { + // Destructuring object assignments with are ES2015 syntax + // and possibly ESNext if they contain rest + transformFlags |= 8 /* AssertESNext */ | 192 /* AssertES2015 */ | 3072 /* AssertDestructuringAssignment */; + } + else if (operatorTokenKind === 59 /* EqualsToken */ && leftKind === 187 /* ArrayLiteralExpression */) { + // Destructuring assignments are ES2015 syntax. + transformFlags |= 192 /* AssertES2015 */ | 3072 /* AssertDestructuringAssignment */; + } + else if (operatorTokenKind === 41 /* AsteriskAsteriskToken */ + || operatorTokenKind === 63 /* AsteriskAsteriskEqualsToken */) { + // Exponentiation is ES2016 syntax. + transformFlags |= 32 /* AssertES2016 */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~637535553 /* NodeExcludes */; + } + function computeParameter(node, subtreeFlags) { + var transformFlags = subtreeFlags; + var name = node.name; + var initializer = node.initializer; + var dotDotDotToken = node.dotDotDotToken; + // The '?' token, type annotations, decorators, and 'this' parameters are TypeSCript + // syntax. + if (node.questionToken + || node.type + || (subtreeFlags & 4096 /* ContainsTypeScriptClassSyntax */ && ts.some(node.decorators)) + || ts.isThisIdentifier(name)) { + transformFlags |= 3 /* AssertTypeScript */; + } + // If a parameter has an accessibility modifier, then it is TypeScript syntax. + if (ts.hasModifier(node, 92 /* ParameterPropertyModifier */)) { + transformFlags |= 3 /* AssertTypeScript */ | 4096 /* ContainsTypeScriptClassSyntax */; + } + // parameters with object rest destructuring are ES Next syntax + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { + transformFlags |= 8 /* AssertESNext */; + } + // If a parameter has an initializer, a binding pattern or a dotDotDot token, then + // it is ES6 syntax and its container must emit default value assignments or parameter destructuring downlevel. + if (subtreeFlags & 2097152 /* ContainsBindingPattern */ || initializer || dotDotDotToken) { + transformFlags |= 192 /* AssertES2015 */ | 65536 /* ContainsDefaultValueAssignments */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~637535553 /* ParameterExcludes */; + } + function computeParenthesizedExpression(node, subtreeFlags) { + var transformFlags = subtreeFlags; + var expression = node.expression; + var expressionKind = expression.kind; + var expressionTransformFlags = expression.transformFlags; + // If the node is synthesized, it means the emitter put the parentheses there, + // not the user. If we didn't want them, the emitter would not have put them + // there. + if (expressionKind === 212 /* AsExpression */ + || expressionKind === 194 /* TypeAssertionExpression */) { + transformFlags |= 3 /* AssertTypeScript */; + } + // If the expression of a ParenthesizedExpression is a destructuring assignment, + // then the ParenthesizedExpression is a destructuring assignment. + if (expressionTransformFlags & 1024 /* DestructuringAssignment */) { + transformFlags |= 1024 /* DestructuringAssignment */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~536872257 /* OuterExpressionExcludes */; + } + function computeClassDeclaration(node, subtreeFlags) { + var transformFlags; + if (ts.hasModifier(node, 2 /* Ambient */)) { + // An ambient declaration is TypeScript syntax. + transformFlags = 3 /* AssertTypeScript */; + } + else { + // A ClassDeclaration is ES6 syntax. + transformFlags = subtreeFlags | 192 /* AssertES2015 */; + // A class with a parameter property assignment, property initializer, computed property name, or decorator is + // TypeScript syntax. + // An exported declaration may be TypeScript syntax, but is handled by the visitor + // for a namespace declaration. + if ((subtreeFlags & 4096 /* ContainsTypeScriptClassSyntax */) + || node.typeParameters) { + transformFlags |= 3 /* AssertTypeScript */; + } + if (subtreeFlags & 32768 /* ContainsLexicalThisInComputedPropertyName */) { + // A computed property name containing `this` might need to be rewritten, + // so propagate the ContainsLexicalThis flag upward. + transformFlags |= 8192 /* ContainsLexicalThis */; + } + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~638121281 /* ClassExcludes */; + } + function computeClassExpression(node, subtreeFlags) { + // A ClassExpression is ES6 syntax. + var transformFlags = subtreeFlags | 192 /* AssertES2015 */; + // A class with a parameter property assignment, property initializer, or decorator is + // TypeScript syntax. + if (subtreeFlags & 4096 /* ContainsTypeScriptClassSyntax */ + || node.typeParameters) { + transformFlags |= 3 /* AssertTypeScript */; + } + if (subtreeFlags & 32768 /* ContainsLexicalThisInComputedPropertyName */) { + // A computed property name containing `this` might need to be rewritten, + // so propagate the ContainsLexicalThis flag upward. + transformFlags |= 8192 /* ContainsLexicalThis */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~638121281 /* ClassExcludes */; + } + function computeHeritageClause(node, subtreeFlags) { + var transformFlags = subtreeFlags; + switch (node.token) { + case 86 /* ExtendsKeyword */: + // An `extends` HeritageClause is ES6 syntax. + transformFlags |= 192 /* AssertES2015 */; + break; + case 109 /* ImplementsKeyword */: + // An `implements` HeritageClause is TypeScript syntax. + transformFlags |= 3 /* AssertTypeScript */; + break; + default: + ts.Debug.fail("Unexpected token for heritage clause"); + break; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~637535553 /* NodeExcludes */; + } + function computeCatchClause(node, subtreeFlags) { + var transformFlags = subtreeFlags; + if (!node.variableDeclaration) { + transformFlags |= 8 /* AssertESNext */; + } + else if (ts.isBindingPattern(node.variableDeclaration.name)) { + transformFlags |= 192 /* AssertES2015 */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~637797697 /* CatchClauseExcludes */; + } + function computeExpressionWithTypeArguments(node, subtreeFlags) { + // An ExpressionWithTypeArguments is ES6 syntax, as it is used in the + // extends clause of a class. + var transformFlags = subtreeFlags | 192 /* AssertES2015 */; + // If an ExpressionWithTypeArguments contains type arguments, then it + // is TypeScript syntax. + if (node.typeArguments) { + transformFlags |= 3 /* AssertTypeScript */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~637535553 /* NodeExcludes */; + } + function computeConstructor(node, subtreeFlags) { + var transformFlags = subtreeFlags; + // TypeScript-specific modifiers and overloads are TypeScript syntax + if (ts.hasModifier(node, 2270 /* TypeScriptModifier */) + || !node.body) { + transformFlags |= 3 /* AssertTypeScript */; + } + // function declarations with object rest destructuring are ES Next syntax + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { + transformFlags |= 8 /* AssertESNext */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~653616449 /* ConstructorExcludes */; + } + function computeMethod(node, subtreeFlags) { + // A MethodDeclaration is ES6 syntax. + var transformFlags = subtreeFlags | 192 /* AssertES2015 */; + // Decorators, TypeScript-specific modifiers, type parameters, type annotations, and + // overloads are TypeScript syntax. + if (node.decorators + || ts.hasModifier(node, 2270 /* TypeScriptModifier */) + || node.typeParameters + || node.type + || (node.name && ts.isComputedPropertyName(node.name)) // While computed method names aren't typescript, the TS transform must visit them to emit property declarations correctly + || !node.body) { + transformFlags |= 3 /* AssertTypeScript */; + } + // function declarations with object rest destructuring are ES Next syntax + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { + transformFlags |= 8 /* AssertESNext */; + } + // An async method declaration is ES2017 syntax. + if (ts.hasModifier(node, 256 /* Async */)) { + transformFlags |= node.asteriskToken ? 8 /* AssertESNext */ : 16 /* AssertES2017 */; + } + if (node.asteriskToken) { + transformFlags |= 768 /* AssertGenerator */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~653616449 /* MethodOrAccessorExcludes */; + } + function computeAccessor(node, subtreeFlags) { + var transformFlags = subtreeFlags; + // Decorators, TypeScript-specific modifiers, type annotations, and overloads are + // TypeScript syntax. + if (node.decorators + || ts.hasModifier(node, 2270 /* TypeScriptModifier */) + || node.type + || (node.name && ts.isComputedPropertyName(node.name)) // While computed accessor names aren't typescript, the TS transform must visit them to emit property declarations correctly + || !node.body) { + transformFlags |= 3 /* AssertTypeScript */; + } + // function declarations with object rest destructuring are ES Next syntax + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { + transformFlags |= 8 /* AssertESNext */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~653616449 /* MethodOrAccessorExcludes */; + } + function computePropertyDeclaration(node, subtreeFlags) { + // A PropertyDeclaration is TypeScript syntax. + var transformFlags = subtreeFlags | 3 /* AssertTypeScript */; + // If the PropertyDeclaration has an initializer or a computed name, we need to inform its ancestor + // so that it handle the transformation. + if (node.initializer || ts.isComputedPropertyName(node.name)) { + transformFlags |= 4096 /* ContainsTypeScriptClassSyntax */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~637535553 /* NodeExcludes */; + } + function computeFunctionDeclaration(node, subtreeFlags) { + var transformFlags; + var modifierFlags = ts.getModifierFlags(node); + var body = node.body; + if (!body || (modifierFlags & 2 /* Ambient */)) { + // An ambient declaration is TypeScript syntax. + // A FunctionDeclaration without a body is an overload and is TypeScript syntax. + transformFlags = 3 /* AssertTypeScript */; + } + else { + transformFlags = subtreeFlags | 8388608 /* ContainsHoistedDeclarationOrCompletion */; + // TypeScript-specific modifiers, type parameters, and type annotations are TypeScript + // syntax. + if (modifierFlags & 2270 /* TypeScriptModifier */ + || node.typeParameters + || node.type) { + transformFlags |= 3 /* AssertTypeScript */; + } + // An async function declaration is ES2017 syntax. + if (modifierFlags & 256 /* Async */) { + transformFlags |= node.asteriskToken ? 8 /* AssertESNext */ : 16 /* AssertES2017 */; + } + // function declarations with object rest destructuring are ES Next syntax + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { + transformFlags |= 8 /* AssertESNext */; + } + // If a FunctionDeclaration's subtree has marked the container as needing to capture the + // lexical this, or the function contains parameters with initializers, then this node is + // ES6 syntax. + if (subtreeFlags & 81920 /* ES2015FunctionSyntaxMask */) { + transformFlags |= 192 /* AssertES2015 */; + } + // If a FunctionDeclaration is generator function and is the body of a + // transformed async function, then this node can be transformed to a + // down-level generator. + // Currently we do not support transforming any other generator fucntions + // down level. + if (node.asteriskToken) { + transformFlags |= 768 /* AssertGenerator */; + } + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~653620545 /* FunctionExcludes */; + } + function computeFunctionExpression(node, subtreeFlags) { + var transformFlags = subtreeFlags; + // TypeScript-specific modifiers, type parameters, and type annotations are TypeScript + // syntax. + if (ts.hasModifier(node, 2270 /* TypeScriptModifier */) + || node.typeParameters + || node.type) { + transformFlags |= 3 /* AssertTypeScript */; + } + // An async function expression is ES2017 syntax. + if (ts.hasModifier(node, 256 /* Async */)) { + transformFlags |= node.asteriskToken ? 8 /* AssertESNext */ : 16 /* AssertES2017 */; + } + // function expressions with object rest destructuring are ES Next syntax + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { + transformFlags |= 8 /* AssertESNext */; + } + // If a FunctionExpression's subtree has marked the container as needing to capture the + // lexical this, or the function contains parameters with initializers, then this node is + // ES6 syntax. + if (subtreeFlags & 81920 /* ES2015FunctionSyntaxMask */) { + transformFlags |= 192 /* AssertES2015 */; + } + // If a FunctionExpression is generator function and is the body of a + // transformed async function, then this node can be transformed to a + // down-level generator. + if (node.asteriskToken) { + transformFlags |= 768 /* AssertGenerator */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~653620545 /* FunctionExcludes */; + } + function computeArrowFunction(node, subtreeFlags) { + // An ArrowFunction is ES6 syntax, and excludes markers that should not escape the scope of an ArrowFunction. + var transformFlags = subtreeFlags | 192 /* AssertES2015 */; + // TypeScript-specific modifiers, type parameters, and type annotations are TypeScript + // syntax. + if (ts.hasModifier(node, 2270 /* TypeScriptModifier */) + || node.typeParameters + || node.type) { + transformFlags |= 3 /* AssertTypeScript */; + } + // An async arrow function is ES2017 syntax. + if (ts.hasModifier(node, 256 /* Async */)) { + transformFlags |= 16 /* AssertES2017 */; + } + // arrow functions with object rest destructuring are ES Next syntax + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { + transformFlags |= 8 /* AssertESNext */; + } + // If an ArrowFunction contains a lexical this, its container must capture the lexical this. + if (subtreeFlags & 8192 /* ContainsLexicalThis */) { + transformFlags |= 16384 /* ContainsCapturedLexicalThis */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~653604161 /* ArrowFunctionExcludes */; + } + function computePropertyAccess(node, subtreeFlags) { + var transformFlags = subtreeFlags; + // If a PropertyAccessExpression starts with a super keyword, then it is + // ES6 syntax, and requires a lexical `this` binding. + if (transformFlags & 33554432 /* Super */) { + transformFlags ^= 33554432 /* Super */; + // super inside of an async function requires hoisting the super access (ES2017). + // same for super inside of an async generator, which is ESNext. + transformFlags |= 67108864 /* ContainsSuper */ | 16 /* ContainsES2017 */ | 8 /* ContainsESNext */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~570426689 /* PropertyAccessExcludes */; + } + function computeElementAccess(node, subtreeFlags) { + var transformFlags = subtreeFlags; + var expression = node.expression; + var expressionFlags = expression.transformFlags; // We do not want to aggregate flags from the argument expression for super/this capturing + // If an ElementAccessExpression starts with a super keyword, then it is + // ES6 syntax, and requires a lexical `this` binding. + if (expressionFlags & 33554432 /* Super */) { + transformFlags &= ~33554432 /* Super */; + // super inside of an async function requires hoisting the super access (ES2017). + // same for super inside of an async generator, which is ESNext. + transformFlags |= 67108864 /* ContainsSuper */ | 16 /* ContainsES2017 */ | 8 /* ContainsESNext */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~570426689 /* PropertyAccessExcludes */; + } + function computeVariableDeclaration(node, subtreeFlags) { + var transformFlags = subtreeFlags; + transformFlags |= 192 /* AssertES2015 */ | 2097152 /* ContainsBindingPattern */; + // A VariableDeclaration containing ObjectRest is ESNext syntax + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { + transformFlags |= 8 /* AssertESNext */; + } + // Type annotations are TypeScript syntax. + if (node.type) { + transformFlags |= 3 /* AssertTypeScript */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~637535553 /* NodeExcludes */; + } + function computeVariableStatement(node, subtreeFlags) { + var transformFlags; + var declarationListTransformFlags = node.declarationList.transformFlags; + // An ambient declaration is TypeScript syntax. + if (ts.hasModifier(node, 2 /* Ambient */)) { + transformFlags = 3 /* AssertTypeScript */; + } + else { + transformFlags = subtreeFlags; + if (declarationListTransformFlags & 2097152 /* ContainsBindingPattern */) { + transformFlags |= 192 /* AssertES2015 */; + } + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~637535553 /* NodeExcludes */; + } + function computeLabeledStatement(node, subtreeFlags) { + var transformFlags = subtreeFlags; + // A labeled statement containing a block scoped binding *may* need to be transformed from ES6. + if (subtreeFlags & 1048576 /* ContainsBlockScopedBinding */ + && ts.isIterationStatement(node, /*lookInLabeledStatements*/ true)) { + transformFlags |= 192 /* AssertES2015 */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~637535553 /* NodeExcludes */; + } + function computeImportEquals(node, subtreeFlags) { + var transformFlags = subtreeFlags; + // An ImportEqualsDeclaration with a namespace reference is TypeScript. + if (!ts.isExternalModuleImportEqualsDeclaration(node)) { + transformFlags |= 3 /* AssertTypeScript */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~637535553 /* NodeExcludes */; + } + function computeExpressionStatement(node, subtreeFlags) { + var transformFlags = subtreeFlags; + // If the expression of an expression statement is a destructuring assignment, + // then we treat the statement as ES6 so that we can indicate that we do not + // need to hold on to the right-hand side. + if (node.expression.transformFlags & 1024 /* DestructuringAssignment */) { + transformFlags |= 192 /* AssertES2015 */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~637535553 /* NodeExcludes */; + } + function computeModuleDeclaration(node, subtreeFlags) { + var transformFlags = 3 /* AssertTypeScript */; + var modifierFlags = ts.getModifierFlags(node); + if ((modifierFlags & 2 /* Ambient */) === 0) { + transformFlags |= subtreeFlags; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~647001409 /* ModuleExcludes */; + } + function computeVariableDeclarationList(node, subtreeFlags) { + var transformFlags = subtreeFlags | 8388608 /* ContainsHoistedDeclarationOrCompletion */; + if (subtreeFlags & 2097152 /* ContainsBindingPattern */) { + transformFlags |= 192 /* AssertES2015 */; + } + // If a VariableDeclarationList is `let` or `const`, then it is ES6 syntax. + if (node.flags & 3 /* BlockScoped */) { + transformFlags |= 192 /* AssertES2015 */ | 1048576 /* ContainsBlockScopedBinding */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~639894849 /* VariableDeclarationListExcludes */; + } + function computeOther(node, kind, subtreeFlags) { + // Mark transformations needed for each node + var transformFlags = subtreeFlags; + var excludeFlags = 637535553 /* NodeExcludes */; + switch (kind) { + case 121 /* AsyncKeyword */: + case 201 /* AwaitExpression */: + // async/await is ES2017 syntax, but may be ESNext syntax (for async generators) + transformFlags |= 8 /* AssertESNext */ | 16 /* AssertES2017 */; + break; + case 194 /* TypeAssertionExpression */: + case 212 /* AsExpression */: + case 308 /* PartiallyEmittedExpression */: + // These nodes are TypeScript syntax. + transformFlags |= 3 /* AssertTypeScript */; + excludeFlags = 536872257 /* OuterExpressionExcludes */; + break; + case 115 /* PublicKeyword */: + case 113 /* PrivateKeyword */: + case 114 /* ProtectedKeyword */: + case 118 /* AbstractKeyword */: + case 125 /* DeclareKeyword */: + case 77 /* ConstKeyword */: + case 243 /* EnumDeclaration */: + case 278 /* EnumMember */: + case 213 /* NonNullExpression */: + case 133 /* ReadonlyKeyword */: + // These nodes are TypeScript syntax. + transformFlags |= 3 /* AssertTypeScript */; + break; + case 260 /* JsxElement */: + case 261 /* JsxSelfClosingElement */: + case 262 /* JsxOpeningElement */: + case 11 /* JsxText */: + case 263 /* JsxClosingElement */: + case 264 /* JsxFragment */: + case 265 /* JsxOpeningFragment */: + case 266 /* JsxClosingFragment */: + case 267 /* JsxAttribute */: + case 268 /* JsxAttributes */: + case 269 /* JsxSpreadAttribute */: + case 270 /* JsxExpression */: + // These nodes are Jsx syntax. + transformFlags |= 4 /* AssertJsx */; + break; + case 14 /* NoSubstitutionTemplateLiteral */: + case 15 /* TemplateHead */: + case 16 /* TemplateMiddle */: + case 17 /* TemplateTail */: + case 206 /* TemplateExpression */: + case 193 /* TaggedTemplateExpression */: + case 276 /* ShorthandPropertyAssignment */: + case 116 /* StaticKeyword */: + case 214 /* MetaProperty */: + // These nodes are ES6 syntax. + transformFlags |= 192 /* AssertES2015 */; + break; + case 10 /* StringLiteral */: + if (node.hasExtendedUnicodeEscape) { + transformFlags |= 192 /* AssertES2015 */; + } + break; + case 8 /* NumericLiteral */: + if (node.numericLiteralFlags & 384 /* BinaryOrOctalSpecifier */) { + transformFlags |= 192 /* AssertES2015 */; + } + break; + case 9 /* BigIntLiteral */: + transformFlags |= 8 /* AssertESNext */; + break; + case 227 /* ForOfStatement */: + // This node is either ES2015 syntax or ES2017 syntax (if it is a for-await-of). + if (node.awaitModifier) { + transformFlags |= 8 /* AssertESNext */; + } + transformFlags |= 192 /* AssertES2015 */; + break; + case 207 /* YieldExpression */: + // This node is either ES2015 syntax (in a generator) or ES2017 syntax (in an async + // generator). + transformFlags |= 8 /* AssertESNext */ | 192 /* AssertES2015 */ | 4194304 /* ContainsYield */; + break; + case 120 /* AnyKeyword */: + case 135 /* NumberKeyword */: + case 146 /* BigIntKeyword */: + case 132 /* NeverKeyword */: + case 136 /* ObjectKeyword */: + case 138 /* StringKeyword */: + case 123 /* BooleanKeyword */: + case 139 /* SymbolKeyword */: + case 106 /* VoidKeyword */: + case 150 /* TypeParameter */: + case 153 /* PropertySignature */: + case 155 /* MethodSignature */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 162 /* IndexSignature */: + case 163 /* TypePredicate */: + case 164 /* TypeReference */: + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + case 167 /* TypeQuery */: + case 168 /* TypeLiteral */: + case 169 /* ArrayType */: + case 170 /* TupleType */: + case 171 /* OptionalType */: + case 172 /* RestType */: + case 173 /* UnionType */: + case 174 /* IntersectionType */: + case 175 /* ConditionalType */: + case 176 /* InferType */: + case 177 /* ParenthesizedType */: + case 241 /* InterfaceDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 178 /* ThisType */: + case 179 /* TypeOperator */: + case 180 /* IndexedAccessType */: + case 181 /* MappedType */: + case 182 /* LiteralType */: + case 247 /* NamespaceExportDeclaration */: + // Types and signatures are TypeScript syntax, and exclude all other facts. + transformFlags = 3 /* AssertTypeScript */; + excludeFlags = -3 /* TypeExcludes */; + break; + case 149 /* ComputedPropertyName */: + // Even though computed property names are ES6, we don't treat them as such. + // This is so that they can flow through PropertyName transforms unaffected. + // Instead, we mark the container as ES6, so that it can properly handle the transform. + transformFlags |= 524288 /* ContainsComputedPropertyName */; + if (subtreeFlags & 8192 /* ContainsLexicalThis */) { + // A computed method name like `[this.getName()](x: string) { ... }` needs to + // distinguish itself from the normal case of a method body containing `this`: + // `this` inside a method doesn't need to be rewritten (the method provides `this`), + // whereas `this` inside a computed name *might* need to be rewritten if the class/object + // is inside an arrow function: + // `_this = this; () => class K { [_this.getName()]() { ... } }` + // To make this distinction, use ContainsLexicalThisInComputedPropertyName + // instead of ContainsLexicalThis for computed property names + transformFlags |= 32768 /* ContainsLexicalThisInComputedPropertyName */; + } + break; + case 208 /* SpreadElement */: + transformFlags |= 192 /* AssertES2015 */ | 131072 /* ContainsRestOrSpread */; + break; + case 277 /* SpreadAssignment */: + transformFlags |= 8 /* AssertESNext */ | 262144 /* ContainsObjectRestOrSpread */; + break; + case 98 /* SuperKeyword */: + // This node is ES6 syntax. + transformFlags |= 192 /* AssertES2015 */ | 33554432 /* Super */; + excludeFlags = 536872257 /* OuterExpressionExcludes */; // must be set to persist `Super` + break; + case 100 /* ThisKeyword */: + // Mark this node and its ancestors as containing a lexical `this` keyword. + transformFlags |= 8192 /* ContainsLexicalThis */; + break; + case 184 /* ObjectBindingPattern */: + transformFlags |= 192 /* AssertES2015 */ | 2097152 /* ContainsBindingPattern */; + if (subtreeFlags & 131072 /* ContainsRestOrSpread */) { + transformFlags |= 8 /* AssertESNext */ | 262144 /* ContainsObjectRestOrSpread */; + } + excludeFlags = 637666625 /* BindingPatternExcludes */; + break; + case 185 /* ArrayBindingPattern */: + transformFlags |= 192 /* AssertES2015 */ | 2097152 /* ContainsBindingPattern */; + excludeFlags = 637666625 /* BindingPatternExcludes */; + break; + case 186 /* BindingElement */: + transformFlags |= 192 /* AssertES2015 */; + if (node.dotDotDotToken) { + transformFlags |= 131072 /* ContainsRestOrSpread */; + } + break; + case 152 /* Decorator */: + // This node is TypeScript syntax, and marks its container as also being TypeScript syntax. + transformFlags |= 3 /* AssertTypeScript */ | 4096 /* ContainsTypeScriptClassSyntax */; + break; + case 188 /* ObjectLiteralExpression */: + excludeFlags = 638358849 /* ObjectLiteralExcludes */; + if (subtreeFlags & 524288 /* ContainsComputedPropertyName */) { + // If an ObjectLiteralExpression contains a ComputedPropertyName, then it + // is an ES6 node. + transformFlags |= 192 /* AssertES2015 */; + } + if (subtreeFlags & 32768 /* ContainsLexicalThisInComputedPropertyName */) { + // A computed property name containing `this` might need to be rewritten, + // so propagate the ContainsLexicalThis flag upward. + transformFlags |= 8192 /* ContainsLexicalThis */; + } + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { + // If an ObjectLiteralExpression contains a spread element, then it + // is an ES next node. + transformFlags |= 8 /* AssertESNext */; + } + break; + case 187 /* ArrayLiteralExpression */: + case 192 /* NewExpression */: + excludeFlags = 637666625 /* ArrayLiteralOrCallOrNewExcludes */; + if (subtreeFlags & 131072 /* ContainsRestOrSpread */) { + // If the this node contains a SpreadExpression, then it is an ES6 + // node. + transformFlags |= 192 /* AssertES2015 */; + } + break; + case 223 /* DoStatement */: + case 224 /* WhileStatement */: + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + // A loop containing a block scoped binding *may* need to be transformed from ES6. + if (subtreeFlags & 1048576 /* ContainsBlockScopedBinding */) { + transformFlags |= 192 /* AssertES2015 */; + } + break; + case 279 /* SourceFile */: + if (subtreeFlags & 16384 /* ContainsCapturedLexicalThis */) { + transformFlags |= 192 /* AssertES2015 */; + } + break; + case 230 /* ReturnStatement */: + // Return statements may require an `await` in ESNext. + transformFlags |= 8388608 /* ContainsHoistedDeclarationOrCompletion */ | 8 /* AssertESNext */; + break; + case 228 /* ContinueStatement */: + case 229 /* BreakStatement */: + transformFlags |= 8388608 /* ContainsHoistedDeclarationOrCompletion */; + break; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~excludeFlags; + } + /** + * Gets the transform flags to exclude when unioning the transform flags of a subtree. + * + * NOTE: This needs to be kept up-to-date with the exclusions used in `computeTransformFlagsForNode`. + * For performance reasons, `computeTransformFlagsForNode` uses local constant values rather + * than calling this function. + */ + function getTransformFlagsSubtreeExclusions(kind) { + if (kind >= 163 /* FirstTypeNode */ && kind <= 183 /* LastTypeNode */) { + return -3 /* TypeExcludes */; + } + switch (kind) { + case 191 /* CallExpression */: + case 192 /* NewExpression */: + case 187 /* ArrayLiteralExpression */: + return 637666625 /* ArrayLiteralOrCallOrNewExcludes */; + case 244 /* ModuleDeclaration */: + return 647001409 /* ModuleExcludes */; + case 151 /* Parameter */: + return 637535553 /* ParameterExcludes */; + case 197 /* ArrowFunction */: + return 653604161 /* ArrowFunctionExcludes */; + case 196 /* FunctionExpression */: + case 239 /* FunctionDeclaration */: + return 653620545 /* FunctionExcludes */; + case 238 /* VariableDeclarationList */: + return 639894849 /* VariableDeclarationListExcludes */; + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + return 638121281 /* ClassExcludes */; + case 157 /* Constructor */: + return 653616449 /* ConstructorExcludes */; + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + return 653616449 /* MethodOrAccessorExcludes */; + case 120 /* AnyKeyword */: + case 135 /* NumberKeyword */: + case 146 /* BigIntKeyword */: + case 132 /* NeverKeyword */: + case 138 /* StringKeyword */: + case 136 /* ObjectKeyword */: + case 123 /* BooleanKeyword */: + case 139 /* SymbolKeyword */: + case 106 /* VoidKeyword */: + case 150 /* TypeParameter */: + case 153 /* PropertySignature */: + case 155 /* MethodSignature */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 162 /* IndexSignature */: + case 241 /* InterfaceDeclaration */: + case 242 /* TypeAliasDeclaration */: + return -3 /* TypeExcludes */; + case 188 /* ObjectLiteralExpression */: + return 638358849 /* ObjectLiteralExcludes */; + case 274 /* CatchClause */: + return 637797697 /* CatchClauseExcludes */; + case 184 /* ObjectBindingPattern */: + case 185 /* ArrayBindingPattern */: + return 637666625 /* BindingPatternExcludes */; + case 194 /* TypeAssertionExpression */: + case 212 /* AsExpression */: + case 308 /* PartiallyEmittedExpression */: + case 195 /* ParenthesizedExpression */: + case 98 /* SuperKeyword */: + return 536872257 /* OuterExpressionExcludes */; + case 189 /* PropertyAccessExpression */: + case 190 /* ElementAccessExpression */: + return 570426689 /* PropertyAccessExcludes */; + default: + return 637535553 /* NodeExcludes */; + } + } + ts.getTransformFlagsSubtreeExclusions = getTransformFlagsSubtreeExclusions; + /** + * "Binds" JSDoc nodes in TypeScript code. + * Since we will never create symbols for JSDoc, we just set parent pointers instead. + */ + function setParentPointers(parent, child) { + child.parent = parent; + ts.forEachChild(child, function (grandchild) { return setParentPointers(child, grandchild); }); + } +})(ts || (ts = {})); +/** @internal */ +var ts; +(function (ts) { + function createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintOfTypeParameter, getFirstIdentifier) { + return getSymbolWalker; + function getSymbolWalker(accept) { + if (accept === void 0) { accept = function () { return true; }; } + var visitedTypes = []; // Sparse array from id to type + var visitedSymbols = []; // Sparse array from id to symbol + return { + walkType: function (type) { + try { + visitType(type); + return { visitedTypes: ts.getOwnValues(visitedTypes), visitedSymbols: ts.getOwnValues(visitedSymbols) }; + } + finally { + ts.clear(visitedTypes); + ts.clear(visitedSymbols); + } + }, + walkSymbol: function (symbol) { + try { + visitSymbol(symbol); + return { visitedTypes: ts.getOwnValues(visitedTypes), visitedSymbols: ts.getOwnValues(visitedSymbols) }; + } + finally { + ts.clear(visitedTypes); + ts.clear(visitedSymbols); + } + }, + }; + function visitType(type) { + if (!type) { + return; + } + if (visitedTypes[type.id]) { + return; + } + visitedTypes[type.id] = type; + // Reuse visitSymbol to visit the type's symbol, + // but be sure to bail on recuring into the type if accept declines the symbol. + var shouldBail = visitSymbol(type.symbol); + if (shouldBail) + return; + // Visit the type's related types, if any + if (type.flags & 524288 /* Object */) { + var objectType = type; + var objectFlags = objectType.objectFlags; + if (objectFlags & 4 /* Reference */) { + visitTypeReference(type); + } + if (objectFlags & 32 /* Mapped */) { + visitMappedType(type); + } + if (objectFlags & (1 /* Class */ | 2 /* Interface */)) { + visitInterfaceType(type); + } + if (objectFlags & (8 /* Tuple */ | 16 /* Anonymous */)) { + visitObjectType(objectType); + } + } + if (type.flags & 262144 /* TypeParameter */) { + visitTypeParameter(type); + } + if (type.flags & 3145728 /* UnionOrIntersection */) { + visitUnionOrIntersectionType(type); + } + if (type.flags & 4194304 /* Index */) { + visitIndexType(type); + } + if (type.flags & 8388608 /* IndexedAccess */) { + visitIndexedAccessType(type); + } + } + function visitTypeReference(type) { + visitType(type.target); + ts.forEach(type.typeArguments, visitType); + } + function visitTypeParameter(type) { + visitType(getConstraintOfTypeParameter(type)); + } + function visitUnionOrIntersectionType(type) { + ts.forEach(type.types, visitType); + } + function visitIndexType(type) { + visitType(type.type); + } + function visitIndexedAccessType(type) { + visitType(type.objectType); + visitType(type.indexType); + visitType(type.constraint); + } + function visitMappedType(type) { + visitType(type.typeParameter); + visitType(type.constraintType); + visitType(type.templateType); + visitType(type.modifiersType); + } + function visitSignature(signature) { + var typePredicate = getTypePredicateOfSignature(signature); + if (typePredicate) { + visitType(typePredicate.type); + } + ts.forEach(signature.typeParameters, visitType); + for (var _i = 0, _a = signature.parameters; _i < _a.length; _i++) { + var parameter = _a[_i]; + visitSymbol(parameter); + } + visitType(getRestTypeOfSignature(signature)); + visitType(getReturnTypeOfSignature(signature)); + } + function visitInterfaceType(interfaceT) { + visitObjectType(interfaceT); + ts.forEach(interfaceT.typeParameters, visitType); + ts.forEach(getBaseTypes(interfaceT), visitType); + visitType(interfaceT.thisType); + } + function visitObjectType(type) { + var stringIndexType = getIndexTypeOfStructuredType(type, 0 /* String */); + visitType(stringIndexType); + var numberIndexType = getIndexTypeOfStructuredType(type, 1 /* Number */); + visitType(numberIndexType); + // The two checks above *should* have already resolved the type (if needed), so this should be cached + var resolved = resolveStructuredTypeMembers(type); + for (var _i = 0, _a = resolved.callSignatures; _i < _a.length; _i++) { + var signature = _a[_i]; + visitSignature(signature); + } + for (var _b = 0, _c = resolved.constructSignatures; _b < _c.length; _b++) { + var signature = _c[_b]; + visitSignature(signature); + } + for (var _d = 0, _e = resolved.properties; _d < _e.length; _d++) { + var p = _e[_d]; + visitSymbol(p); + } + } + function visitSymbol(symbol) { + if (!symbol) { + return false; + } + var symbolId = ts.getSymbolId(symbol); + if (visitedSymbols[symbolId]) { + return false; + } + visitedSymbols[symbolId] = symbol; + if (!accept(symbol)) { + return true; + } + var t = getTypeOfSymbol(symbol); + visitType(t); // Should handle members on classes and such + if (symbol.exports) { + symbol.exports.forEach(visitSymbol); + } + ts.forEach(symbol.declarations, function (d) { + // Type queries are too far resolved when we just visit the symbol's type + // (their type resolved directly to the member deeply referenced) + // So to get the intervening symbols, we need to check if there's a type + // query node on any of the symbol's declarations and get symbols there + if (d.type && d.type.kind === 167 /* TypeQuery */) { + var query = d.type; + var entity = getResolvedSymbol(getFirstIdentifier(query.exprName)); + visitSymbol(entity); + } + }); + return false; + } + } + } + ts.createGetSymbolWalker = createGetSymbolWalker; +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var ambientModuleSymbolRegex = /^".+"$/; + var nextSymbolId = 1; + var nextNodeId = 1; + var nextMergeId = 1; + var nextFlowId = 1; + function getNodeId(node) { + if (!node.id) { + node.id = nextNodeId; + nextNodeId++; + } + return node.id; + } + ts.getNodeId = getNodeId; + function getSymbolId(symbol) { + if (!symbol.id) { + symbol.id = nextSymbolId; + nextSymbolId++; + } + return symbol.id; + } + ts.getSymbolId = getSymbolId; + function isInstantiatedModule(node, preserveConstEnums) { + var moduleState = ts.getModuleInstanceState(node); + return moduleState === 1 /* Instantiated */ || + (preserveConstEnums && moduleState === 2 /* ConstEnumOnly */); + } + ts.isInstantiatedModule = isInstantiatedModule; + function createTypeChecker(host, produceDiagnostics) { + var getPackagesSet = ts.memoize(function () { + var set = ts.createMap(); + host.getSourceFiles().forEach(function (sf) { + if (!sf.resolvedModules) + return; + ts.forEachEntry(sf.resolvedModules, function (r) { + if (r && r.packageId) + set.set(r.packageId.name, true); + }); + }); + return set; + }); + // Cancellation that controls whether or not we can cancel in the middle of type checking. + // In general cancelling is *not* safe for the type checker. We might be in the middle of + // computing something, and we will leave our internals in an inconsistent state. Callers + // who set the cancellation token should catch if a cancellation exception occurs, and + // should throw away and create a new TypeChecker. + // + // Currently we only support setting the cancellation token when getting diagnostics. This + // is because diagnostics can be quite expensive, and we want to allow hosts to bail out if + // they no longer need the information (for example, if the user started editing again). + var cancellationToken; + var requestedExternalEmitHelpers; + var externalHelpersModule; + // tslint:disable variable-name + var Symbol = ts.objectAllocator.getSymbolConstructor(); + var Type = ts.objectAllocator.getTypeConstructor(); + var Signature = ts.objectAllocator.getSignatureConstructor(); + // tslint:enable variable-name + var typeCount = 0; + var symbolCount = 0; + var enumCount = 0; + var instantiationDepth = 0; + var constraintDepth = 0; + var emptySymbols = ts.createSymbolTable(); + var identityMapper = ts.identity; + var compilerOptions = host.getCompilerOptions(); + var languageVersion = ts.getEmitScriptTarget(compilerOptions); + var moduleKind = ts.getEmitModuleKind(compilerOptions); + var allowSyntheticDefaultImports = ts.getAllowSyntheticDefaultImports(compilerOptions); + var strictNullChecks = ts.getStrictOptionValue(compilerOptions, "strictNullChecks"); + var strictFunctionTypes = ts.getStrictOptionValue(compilerOptions, "strictFunctionTypes"); + var strictBindCallApply = ts.getStrictOptionValue(compilerOptions, "strictBindCallApply"); + var strictPropertyInitialization = ts.getStrictOptionValue(compilerOptions, "strictPropertyInitialization"); + var noImplicitAny = ts.getStrictOptionValue(compilerOptions, "noImplicitAny"); + var noImplicitThis = ts.getStrictOptionValue(compilerOptions, "noImplicitThis"); + var keyofStringsOnly = !!compilerOptions.keyofStringsOnly; + var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 32768 /* FreshLiteral */; + var emitResolver = createResolver(); + var nodeBuilder = createNodeBuilder(); + var undefinedSymbol = createSymbol(4 /* Property */, "undefined"); + undefinedSymbol.declarations = []; + var argumentsSymbol = createSymbol(4 /* Property */, "arguments"); + var requireSymbol = createSymbol(4 /* Property */, "require"); + /** This will be set during calls to `getResolvedSignature` where services determines an apparent number of arguments greater than what is actually provided. */ + var apparentArgumentCount; + // for public members that accept a Node or one of its subtypes, we must guard against + // synthetic nodes created during transformations by calling `getParseTreeNode`. + // for most of these, we perform the guard only on `checker` to avoid any possible + // extra cost of calling `getParseTreeNode` when calling these functions from inside the + // checker. + var checker = { + getNodeCount: function () { return ts.sum(host.getSourceFiles(), "nodeCount"); }, + getIdentifierCount: function () { return ts.sum(host.getSourceFiles(), "identifierCount"); }, + getSymbolCount: function () { return ts.sum(host.getSourceFiles(), "symbolCount") + symbolCount; }, + getTypeCount: function () { return typeCount; }, + isUndefinedSymbol: function (symbol) { return symbol === undefinedSymbol; }, + isArgumentsSymbol: function (symbol) { return symbol === argumentsSymbol; }, + isUnknownSymbol: function (symbol) { return symbol === unknownSymbol; }, + getMergedSymbol: getMergedSymbol, + getDiagnostics: getDiagnostics, + getGlobalDiagnostics: getGlobalDiagnostics, + getTypeOfSymbolAtLocation: function (symbol, location) { + location = ts.getParseTreeNode(location); + return location ? getTypeOfSymbolAtLocation(symbol, location) : errorType; + }, + getSymbolsOfParameterPropertyDeclaration: function (parameterIn, parameterName) { + var parameter = ts.getParseTreeNode(parameterIn, ts.isParameter); + if (parameter === undefined) + return ts.Debug.fail("Cannot get symbols of a synthetic parameter that cannot be resolved to a parse-tree node."); + return getSymbolsOfParameterPropertyDeclaration(parameter, ts.escapeLeadingUnderscores(parameterName)); + }, + getDeclaredTypeOfSymbol: getDeclaredTypeOfSymbol, + getPropertiesOfType: getPropertiesOfType, + getPropertyOfType: function (type, name) { return getPropertyOfType(type, ts.escapeLeadingUnderscores(name)); }, + getTypeOfPropertyOfType: function (type, name) { return getTypeOfPropertyOfType(type, ts.escapeLeadingUnderscores(name)); }, + getIndexInfoOfType: getIndexInfoOfType, + getSignaturesOfType: getSignaturesOfType, + getIndexTypeOfType: getIndexTypeOfType, + getBaseTypes: getBaseTypes, + getBaseTypeOfLiteralType: getBaseTypeOfLiteralType, + getWidenedType: getWidenedType, + getTypeFromTypeNode: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isTypeNode); + return node ? getTypeFromTypeNode(node) : errorType; + }, + getParameterType: getTypeAtPosition, + getPromisedTypeOfPromise: getPromisedTypeOfPromise, + getReturnTypeOfSignature: getReturnTypeOfSignature, + getNullableType: getNullableType, + getNonNullableType: getNonNullableType, + typeToTypeNode: nodeBuilder.typeToTypeNode, + indexInfoToIndexSignatureDeclaration: nodeBuilder.indexInfoToIndexSignatureDeclaration, + signatureToSignatureDeclaration: nodeBuilder.signatureToSignatureDeclaration, + symbolToEntityName: nodeBuilder.symbolToEntityName, + symbolToExpression: nodeBuilder.symbolToExpression, + symbolToTypeParameterDeclarations: nodeBuilder.symbolToTypeParameterDeclarations, + symbolToParameterDeclaration: nodeBuilder.symbolToParameterDeclaration, + typeParameterToDeclaration: nodeBuilder.typeParameterToDeclaration, + getSymbolsInScope: function (location, meaning) { + location = ts.getParseTreeNode(location); + return location ? getSymbolsInScope(location, meaning) : []; + }, + getSymbolAtLocation: function (node) { + node = ts.getParseTreeNode(node); + return node ? getSymbolAtLocation(node) : undefined; + }, + getShorthandAssignmentValueSymbol: function (node) { + node = ts.getParseTreeNode(node); + return node ? getShorthandAssignmentValueSymbol(node) : undefined; + }, + getExportSpecifierLocalTargetSymbol: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isExportSpecifier); + return node ? getExportSpecifierLocalTargetSymbol(node) : undefined; + }, + getExportSymbolOfSymbol: function (symbol) { + return getMergedSymbol(symbol.exportSymbol || symbol); + }, + getTypeAtLocation: function (node) { + node = ts.getParseTreeNode(node); + return node ? getTypeOfNode(node) : errorType; + }, + getPropertySymbolOfDestructuringAssignment: function (locationIn) { + var location = ts.getParseTreeNode(locationIn, ts.isIdentifier); + return location ? getPropertySymbolOfDestructuringAssignment(location) : undefined; + }, + signatureToString: function (signature, enclosingDeclaration, flags, kind) { + return signatureToString(signature, ts.getParseTreeNode(enclosingDeclaration), flags, kind); + }, + typeToString: function (type, enclosingDeclaration, flags) { + return typeToString(type, ts.getParseTreeNode(enclosingDeclaration), flags); + }, + symbolToString: function (symbol, enclosingDeclaration, meaning, flags) { + return symbolToString(symbol, ts.getParseTreeNode(enclosingDeclaration), meaning, flags); + }, + typePredicateToString: function (predicate, enclosingDeclaration, flags) { + return typePredicateToString(predicate, ts.getParseTreeNode(enclosingDeclaration), flags); + }, + writeSignature: function (signature, enclosingDeclaration, flags, kind, writer) { + return signatureToString(signature, ts.getParseTreeNode(enclosingDeclaration), flags, kind, writer); + }, + writeType: function (type, enclosingDeclaration, flags, writer) { + return typeToString(type, ts.getParseTreeNode(enclosingDeclaration), flags, writer); + }, + writeSymbol: function (symbol, enclosingDeclaration, meaning, flags, writer) { + return symbolToString(symbol, ts.getParseTreeNode(enclosingDeclaration), meaning, flags, writer); + }, + writeTypePredicate: function (predicate, enclosingDeclaration, flags, writer) { + return typePredicateToString(predicate, ts.getParseTreeNode(enclosingDeclaration), flags, writer); + }, + getAugmentedPropertiesOfType: getAugmentedPropertiesOfType, + getRootSymbols: getRootSymbols, + getContextualType: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isExpression); + return node ? getContextualType(node) : undefined; + }, + getContextualTypeForObjectLiteralElement: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isObjectLiteralElementLike); + return node ? getContextualTypeForObjectLiteralElement(node) : undefined; + }, + getContextualTypeForArgumentAtIndex: function (nodeIn, argIndex) { + var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression); + return node && getContextualTypeForArgumentAtIndex(node, argIndex); + }, + getContextualTypeForJsxAttribute: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isJsxAttributeLike); + return node && getContextualTypeForJsxAttribute(node); + }, + isContextSensitive: isContextSensitive, + getFullyQualifiedName: getFullyQualifiedName, + getResolvedSignature: function (node, candidatesOutArray, agumentCount) { + return getResolvedSignatureWorker(node, candidatesOutArray, agumentCount, /*isForSignatureHelp*/ false); + }, + getResolvedSignatureForSignatureHelp: function (node, candidatesOutArray, agumentCount) { + return getResolvedSignatureWorker(node, candidatesOutArray, agumentCount, /*isForSignatureHelp*/ true); + }, + getConstantValue: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, canHaveConstantValue); + return node ? getConstantValue(node) : undefined; + }, + isValidPropertyAccess: function (nodeIn, propertyName) { + var node = ts.getParseTreeNode(nodeIn, ts.isPropertyAccessOrQualifiedNameOrImportTypeNode); + return !!node && isValidPropertyAccess(node, ts.escapeLeadingUnderscores(propertyName)); + }, + isValidPropertyAccessForCompletions: function (nodeIn, type, property) { + var node = ts.getParseTreeNode(nodeIn, ts.isPropertyAccessExpression); + return !!node && isValidPropertyAccessForCompletions(node, type, property); + }, + getSignatureFromDeclaration: function (declarationIn) { + var declaration = ts.getParseTreeNode(declarationIn, ts.isFunctionLike); + return declaration ? getSignatureFromDeclaration(declaration) : undefined; + }, + isImplementationOfOverload: function (node) { + var parsed = ts.getParseTreeNode(node, ts.isFunctionLike); + return parsed ? isImplementationOfOverload(parsed) : undefined; + }, + getImmediateAliasedSymbol: getImmediateAliasedSymbol, + getAliasedSymbol: resolveAlias, + getEmitResolver: getEmitResolver, + getExportsOfModule: getExportsOfModuleAsArray, + getExportsAndPropertiesOfModule: getExportsAndPropertiesOfModule, + getSymbolWalker: ts.createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintOfTypeParameter, getFirstIdentifier), + getAmbientModules: getAmbientModules, + getJsxIntrinsicTagNamesAt: getJsxIntrinsicTagNamesAt, + isOptionalParameter: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isParameter); + return node ? isOptionalParameter(node) : false; + }, + tryGetMemberInModuleExports: function (name, symbol) { return tryGetMemberInModuleExports(ts.escapeLeadingUnderscores(name), symbol); }, + tryGetMemberInModuleExportsAndProperties: function (name, symbol) { return tryGetMemberInModuleExportsAndProperties(ts.escapeLeadingUnderscores(name), symbol); }, + tryFindAmbientModuleWithoutAugmentations: function (moduleName) { + // we deliberately exclude augmentations + // since we are only interested in declarations of the module itself + return tryFindAmbientModule(moduleName, /*withAugmentations*/ false); + }, + getApparentType: getApparentType, + getUnionType: getUnionType, + createAnonymousType: createAnonymousType, + createSignature: createSignature, + createSymbol: createSymbol, + createIndexInfo: createIndexInfo, + getAnyType: function () { return anyType; }, + getStringType: function () { return stringType; }, + getNumberType: function () { return numberType; }, + createPromiseType: createPromiseType, + createArrayType: createArrayType, + getElementTypeOfArrayType: getElementTypeOfArrayType, + getBooleanType: function () { return booleanType; }, + getFalseType: function (fresh) { return fresh ? falseType : regularFalseType; }, + getTrueType: function (fresh) { return fresh ? trueType : regularTrueType; }, + getVoidType: function () { return voidType; }, + getUndefinedType: function () { return undefinedType; }, + getNullType: function () { return nullType; }, + getESSymbolType: function () { return esSymbolType; }, + getNeverType: function () { return neverType; }, + isSymbolAccessible: isSymbolAccessible, + getObjectFlags: ts.getObjectFlags, + isArrayLikeType: isArrayLikeType, + isTypeInvalidDueToUnionDiscriminant: isTypeInvalidDueToUnionDiscriminant, + getAllPossiblePropertiesOfTypes: getAllPossiblePropertiesOfTypes, + getSuggestionForNonexistentProperty: function (node, type) { return getSuggestionForNonexistentProperty(node, type); }, + getSuggestionForNonexistentSymbol: function (location, name, meaning) { return getSuggestionForNonexistentSymbol(location, ts.escapeLeadingUnderscores(name), meaning); }, + getSuggestionForNonexistentExport: function (node, target) { return getSuggestionForNonexistentExport(node, target); }, + getBaseConstraintOfType: getBaseConstraintOfType, + getDefaultFromTypeParameter: function (type) { return type && type.flags & 262144 /* TypeParameter */ ? getDefaultFromTypeParameter(type) : undefined; }, + resolveName: function (name, location, meaning, excludeGlobals) { + return resolveName(location, ts.escapeLeadingUnderscores(name), meaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false, excludeGlobals); + }, + getJsxNamespace: function (n) { return ts.unescapeLeadingUnderscores(getJsxNamespace(n)); }, + getAccessibleSymbolChain: getAccessibleSymbolChain, + getTypePredicateOfSignature: getTypePredicateOfSignature, + resolveExternalModuleSymbol: resolveExternalModuleSymbol, + tryGetThisTypeAt: function (node) { + node = ts.getParseTreeNode(node); + return node && tryGetThisTypeAt(node); + }, + getTypeArgumentConstraint: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isTypeNode); + return node && getTypeArgumentConstraint(node); + }, + getSuggestionDiagnostics: function (file, ct) { + if (ts.skipTypeChecking(file, compilerOptions)) { + return ts.emptyArray; + } + var diagnostics; + try { + // Record the cancellation token so it can be checked later on during checkSourceElement. + // Do this in a finally block so we can ensure that it gets reset back to nothing after + // this call is done. + cancellationToken = ct; + // Ensure file is type checked + checkSourceFile(file); + ts.Debug.assert(!!(getNodeLinks(file).flags & 1 /* TypeChecked */)); + diagnostics = ts.addRange(diagnostics, suggestionDiagnostics.get(file.fileName)); + if (!file.isDeclarationFile && (!unusedIsError(0 /* Local */) || !unusedIsError(1 /* Parameter */))) { + addUnusedDiagnostics(); + } + return diagnostics || ts.emptyArray; + } + finally { + cancellationToken = undefined; + } + function addUnusedDiagnostics() { + checkUnusedIdentifiers(getPotentiallyUnusedIdentifiers(file), function (containingNode, kind, diag) { + if (!ts.containsParseError(containingNode) && !unusedIsError(kind)) { + (diagnostics || (diagnostics = [])).push(__assign({}, diag, { category: ts.DiagnosticCategory.Suggestion })); + } + }); + } + }, + runWithCancellationToken: function (token, callback) { + try { + cancellationToken = token; + return callback(checker); + } + finally { + cancellationToken = undefined; + } + }, + getLocalTypeParametersOfClassOrInterfaceOrTypeAlias: getLocalTypeParametersOfClassOrInterfaceOrTypeAlias, + }; + function getResolvedSignatureWorker(nodeIn, candidatesOutArray, argumentCount, isForSignatureHelp) { + var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression); + apparentArgumentCount = argumentCount; + var res = node ? getResolvedSignature(node, candidatesOutArray, isForSignatureHelp) : undefined; + apparentArgumentCount = undefined; + return res; + } + var tupleTypes = ts.createMap(); + var unionTypes = ts.createMap(); + var intersectionTypes = ts.createMap(); + var literalTypes = ts.createMap(); + var indexedAccessTypes = ts.createMap(); + var evolvingArrayTypes = []; + var undefinedProperties = ts.createMap(); + var unknownSymbol = createSymbol(4 /* Property */, "unknown"); + var resolvingSymbol = createSymbol(0, "__resolving__" /* Resolving */); + var anyType = createIntrinsicType(1 /* Any */, "any"); + var autoType = createIntrinsicType(1 /* Any */, "any"); + var wildcardType = createIntrinsicType(1 /* Any */, "any"); + var errorType = createIntrinsicType(1 /* Any */, "error"); + var unknownType = createIntrinsicType(2 /* Unknown */, "unknown"); + var undefinedType = createIntrinsicType(32768 /* Undefined */, "undefined"); + var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(32768 /* Undefined */ | 134217728 /* ContainsWideningType */, "undefined"); + var nullType = createIntrinsicType(65536 /* Null */, "null"); + var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(65536 /* Null */ | 134217728 /* ContainsWideningType */, "null"); + var stringType = createIntrinsicType(4 /* String */, "string"); + var numberType = createIntrinsicType(8 /* Number */, "number"); + var bigintType = createIntrinsicType(64 /* BigInt */, "bigint"); + var falseType = createIntrinsicType(512 /* BooleanLiteral */, "false"); + var regularFalseType = createIntrinsicType(512 /* BooleanLiteral */, "false"); + var trueType = createIntrinsicType(512 /* BooleanLiteral */, "true"); + var regularTrueType = createIntrinsicType(512 /* BooleanLiteral */, "true"); + trueType.regularType = regularTrueType; + trueType.freshType = trueType; + regularTrueType.regularType = regularTrueType; + regularTrueType.freshType = trueType; + falseType.regularType = regularFalseType; + falseType.freshType = falseType; + regularFalseType.regularType = regularFalseType; + regularFalseType.freshType = falseType; + var booleanType = createBooleanType([regularFalseType, regularTrueType]); + // Also mark all combinations of fresh/regular booleans as "Boolean" so they print as `boolean` instead of `true | false` + // (The union is cached, so simply doing the marking here is sufficient) + createBooleanType([regularFalseType, trueType]); + createBooleanType([falseType, regularTrueType]); + createBooleanType([falseType, trueType]); + var esSymbolType = createIntrinsicType(4096 /* ESSymbol */, "symbol"); + var voidType = createIntrinsicType(16384 /* Void */, "void"); + var neverType = createIntrinsicType(131072 /* Never */, "never"); + var silentNeverType = createIntrinsicType(131072 /* Never */, "never"); + var implicitNeverType = createIntrinsicType(131072 /* Never */, "never"); + var nonPrimitiveType = createIntrinsicType(67108864 /* NonPrimitive */, "object"); + var stringNumberSymbolType = getUnionType([stringType, numberType, esSymbolType]); + var keyofConstraintType = keyofStringsOnly ? stringType : stringNumberSymbolType; + var numberOrBigIntType = getUnionType([numberType, bigintType]); + var emptyObjectType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + var emptyJsxObjectType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + emptyJsxObjectType.objectFlags |= 4096 /* JsxAttributes */; + var emptyTypeLiteralSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */); + emptyTypeLiteralSymbol.members = ts.createSymbolTable(); + var emptyTypeLiteralType = createAnonymousType(emptyTypeLiteralSymbol, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + var emptyGenericType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + emptyGenericType.instantiations = ts.createMap(); + var anyFunctionType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + // The anyFunctionType contains the anyFunctionType by definition. The flag is further propagated + // in getPropagatingFlagsOfTypes, and it is checked in inferFromTypes. + anyFunctionType.flags |= 536870912 /* ContainsAnyFunctionType */; + var noConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + var circularConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + var resolvingDefaultType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + var markerSuperType = createType(262144 /* TypeParameter */); + var markerSubType = createType(262144 /* TypeParameter */); + markerSubType.constraint = markerSuperType; + var markerOtherType = createType(262144 /* TypeParameter */); + var noTypePredicate = createIdentifierTypePredicate("<>", 0, anyType); + var anySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + var unknownSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, errorType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + var resolvingSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + var silentNeverSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, silentNeverType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + var enumNumberIndexInfo = createIndexInfo(stringType, /*isReadonly*/ true); + var globals = ts.createSymbolTable(); + /** Key is "/path/to/a.ts|/path/to/b.ts". */ + var amalgamatedDuplicates; + var reverseMappedCache = ts.createMap(); + var ambientModulesCache; + /** + * List of every ambient module with a "*" wildcard. + * Unlike other ambient modules, these can't be stored in `globals` because symbol tables only deal with exact matches. + * This is only used if there is no exact match. + */ + var patternAmbientModules; + var globalObjectType; + var globalFunctionType; + var globalCallableFunctionType; + var globalNewableFunctionType; + var globalArrayType; + var globalReadonlyArrayType; + var globalStringType; + var globalNumberType; + var globalBooleanType; + var globalRegExpType; + var globalThisType; + var anyArrayType; + var autoArrayType; + var anyReadonlyArrayType; + var deferredGlobalNonNullableTypeAlias; + // The library files are only loaded when the feature is used. + // This allows users to just specify library files they want to used through --lib + // and they will not get an error from not having unrelated library files + var deferredGlobalESSymbolConstructorSymbol; + var deferredGlobalESSymbolType; + var deferredGlobalTypedPropertyDescriptorType; + var deferredGlobalPromiseType; + var deferredGlobalPromiseLikeType; + var deferredGlobalPromiseConstructorSymbol; + var deferredGlobalPromiseConstructorLikeType; + var deferredGlobalIterableType; + var deferredGlobalIteratorType; + var deferredGlobalIterableIteratorType; + var deferredGlobalAsyncIterableType; + var deferredGlobalAsyncIteratorType; + var deferredGlobalAsyncIterableIteratorType; + var deferredGlobalTemplateStringsArrayType; + var deferredGlobalImportMetaType; + var deferredGlobalExtractSymbol; + var deferredGlobalExcludeSymbol; + var deferredGlobalPickSymbol; + var deferredGlobalBigIntType; + var allPotentiallyUnusedIdentifiers = ts.createMap(); // key is file name + var flowLoopStart = 0; + var flowLoopCount = 0; + var sharedFlowCount = 0; + var flowAnalysisDisabled = false; + var emptyStringType = getLiteralType(""); + var zeroType = getLiteralType(0); + var zeroBigIntType = getLiteralType({ negative: false, base10Value: "0" }); + var resolutionTargets = []; + var resolutionResults = []; + var resolutionPropertyNames = []; + var suggestionCount = 0; + var maximumSuggestionCount = 10; + var mergedSymbols = []; + var symbolLinks = []; + var nodeLinks = []; + var flowLoopCaches = []; + var flowLoopNodes = []; + var flowLoopKeys = []; + var flowLoopTypes = []; + var sharedFlowNodes = []; + var sharedFlowTypes = []; + var potentialThisCollisions = []; + var potentialNewTargetCollisions = []; + var awaitedTypeStack = []; + var diagnostics = ts.createDiagnosticCollection(); + // Suggestion diagnostics must have a file. Keyed by source file name. + var suggestionDiagnostics = ts.createMultiMap(); + var TypeFacts; + (function (TypeFacts) { + TypeFacts[TypeFacts["None"] = 0] = "None"; + TypeFacts[TypeFacts["TypeofEQString"] = 1] = "TypeofEQString"; + TypeFacts[TypeFacts["TypeofEQNumber"] = 2] = "TypeofEQNumber"; + TypeFacts[TypeFacts["TypeofEQBigInt"] = 4] = "TypeofEQBigInt"; + TypeFacts[TypeFacts["TypeofEQBoolean"] = 8] = "TypeofEQBoolean"; + TypeFacts[TypeFacts["TypeofEQSymbol"] = 16] = "TypeofEQSymbol"; + TypeFacts[TypeFacts["TypeofEQObject"] = 32] = "TypeofEQObject"; + TypeFacts[TypeFacts["TypeofEQFunction"] = 64] = "TypeofEQFunction"; + TypeFacts[TypeFacts["TypeofEQHostObject"] = 128] = "TypeofEQHostObject"; + TypeFacts[TypeFacts["TypeofNEString"] = 256] = "TypeofNEString"; + TypeFacts[TypeFacts["TypeofNENumber"] = 512] = "TypeofNENumber"; + TypeFacts[TypeFacts["TypeofNEBigInt"] = 1024] = "TypeofNEBigInt"; + TypeFacts[TypeFacts["TypeofNEBoolean"] = 2048] = "TypeofNEBoolean"; + TypeFacts[TypeFacts["TypeofNESymbol"] = 4096] = "TypeofNESymbol"; + TypeFacts[TypeFacts["TypeofNEObject"] = 8192] = "TypeofNEObject"; + TypeFacts[TypeFacts["TypeofNEFunction"] = 16384] = "TypeofNEFunction"; + TypeFacts[TypeFacts["TypeofNEHostObject"] = 32768] = "TypeofNEHostObject"; + TypeFacts[TypeFacts["EQUndefined"] = 65536] = "EQUndefined"; + TypeFacts[TypeFacts["EQNull"] = 131072] = "EQNull"; + TypeFacts[TypeFacts["EQUndefinedOrNull"] = 262144] = "EQUndefinedOrNull"; + TypeFacts[TypeFacts["NEUndefined"] = 524288] = "NEUndefined"; + TypeFacts[TypeFacts["NENull"] = 1048576] = "NENull"; + TypeFacts[TypeFacts["NEUndefinedOrNull"] = 2097152] = "NEUndefinedOrNull"; + TypeFacts[TypeFacts["Truthy"] = 4194304] = "Truthy"; + TypeFacts[TypeFacts["Falsy"] = 8388608] = "Falsy"; + TypeFacts[TypeFacts["All"] = 16777215] = "All"; + // The following members encode facts about particular kinds of types for use in the getTypeFacts function. + // The presence of a particular fact means that the given test is true for some (and possibly all) values + // of that kind of type. + TypeFacts[TypeFacts["BaseStringStrictFacts"] = 3735041] = "BaseStringStrictFacts"; + TypeFacts[TypeFacts["BaseStringFacts"] = 12582401] = "BaseStringFacts"; + TypeFacts[TypeFacts["StringStrictFacts"] = 16317953] = "StringStrictFacts"; + TypeFacts[TypeFacts["StringFacts"] = 16776705] = "StringFacts"; + TypeFacts[TypeFacts["EmptyStringStrictFacts"] = 12123649] = "EmptyStringStrictFacts"; + TypeFacts[TypeFacts["EmptyStringFacts"] = 12582401] = "EmptyStringFacts"; + TypeFacts[TypeFacts["NonEmptyStringStrictFacts"] = 7929345] = "NonEmptyStringStrictFacts"; + TypeFacts[TypeFacts["NonEmptyStringFacts"] = 16776705] = "NonEmptyStringFacts"; + TypeFacts[TypeFacts["BaseNumberStrictFacts"] = 3734786] = "BaseNumberStrictFacts"; + TypeFacts[TypeFacts["BaseNumberFacts"] = 12582146] = "BaseNumberFacts"; + TypeFacts[TypeFacts["NumberStrictFacts"] = 16317698] = "NumberStrictFacts"; + TypeFacts[TypeFacts["NumberFacts"] = 16776450] = "NumberFacts"; + TypeFacts[TypeFacts["ZeroNumberStrictFacts"] = 12123394] = "ZeroNumberStrictFacts"; + TypeFacts[TypeFacts["ZeroNumberFacts"] = 12582146] = "ZeroNumberFacts"; + TypeFacts[TypeFacts["NonZeroNumberStrictFacts"] = 7929090] = "NonZeroNumberStrictFacts"; + TypeFacts[TypeFacts["NonZeroNumberFacts"] = 16776450] = "NonZeroNumberFacts"; + TypeFacts[TypeFacts["BaseBigIntStrictFacts"] = 3734276] = "BaseBigIntStrictFacts"; + TypeFacts[TypeFacts["BaseBigIntFacts"] = 12581636] = "BaseBigIntFacts"; + TypeFacts[TypeFacts["BigIntStrictFacts"] = 16317188] = "BigIntStrictFacts"; + TypeFacts[TypeFacts["BigIntFacts"] = 16775940] = "BigIntFacts"; + TypeFacts[TypeFacts["ZeroBigIntStrictFacts"] = 12122884] = "ZeroBigIntStrictFacts"; + TypeFacts[TypeFacts["ZeroBigIntFacts"] = 12581636] = "ZeroBigIntFacts"; + TypeFacts[TypeFacts["NonZeroBigIntStrictFacts"] = 7928580] = "NonZeroBigIntStrictFacts"; + TypeFacts[TypeFacts["NonZeroBigIntFacts"] = 16775940] = "NonZeroBigIntFacts"; + TypeFacts[TypeFacts["BaseBooleanStrictFacts"] = 3733256] = "BaseBooleanStrictFacts"; + TypeFacts[TypeFacts["BaseBooleanFacts"] = 12580616] = "BaseBooleanFacts"; + TypeFacts[TypeFacts["BooleanStrictFacts"] = 16316168] = "BooleanStrictFacts"; + TypeFacts[TypeFacts["BooleanFacts"] = 16774920] = "BooleanFacts"; + TypeFacts[TypeFacts["FalseStrictFacts"] = 12121864] = "FalseStrictFacts"; + TypeFacts[TypeFacts["FalseFacts"] = 12580616] = "FalseFacts"; + TypeFacts[TypeFacts["TrueStrictFacts"] = 7927560] = "TrueStrictFacts"; + TypeFacts[TypeFacts["TrueFacts"] = 16774920] = "TrueFacts"; + TypeFacts[TypeFacts["SymbolStrictFacts"] = 7925520] = "SymbolStrictFacts"; + TypeFacts[TypeFacts["SymbolFacts"] = 16772880] = "SymbolFacts"; + TypeFacts[TypeFacts["ObjectStrictFacts"] = 7888800] = "ObjectStrictFacts"; + TypeFacts[TypeFacts["ObjectFacts"] = 16736160] = "ObjectFacts"; + TypeFacts[TypeFacts["FunctionStrictFacts"] = 7880640] = "FunctionStrictFacts"; + TypeFacts[TypeFacts["FunctionFacts"] = 16728000] = "FunctionFacts"; + TypeFacts[TypeFacts["UndefinedFacts"] = 9830144] = "UndefinedFacts"; + TypeFacts[TypeFacts["NullFacts"] = 9363232] = "NullFacts"; + TypeFacts[TypeFacts["EmptyObjectStrictFacts"] = 16318463] = "EmptyObjectStrictFacts"; + TypeFacts[TypeFacts["EmptyObjectFacts"] = 16777215] = "EmptyObjectFacts"; + })(TypeFacts || (TypeFacts = {})); + var typeofEQFacts = ts.createMapFromTemplate({ + string: 1 /* TypeofEQString */, + number: 2 /* TypeofEQNumber */, + bigint: 4 /* TypeofEQBigInt */, + boolean: 8 /* TypeofEQBoolean */, + symbol: 16 /* TypeofEQSymbol */, + undefined: 65536 /* EQUndefined */, + object: 32 /* TypeofEQObject */, + function: 64 /* TypeofEQFunction */ + }); + var typeofNEFacts = ts.createMapFromTemplate({ + string: 256 /* TypeofNEString */, + number: 512 /* TypeofNENumber */, + bigint: 1024 /* TypeofNEBigInt */, + boolean: 2048 /* TypeofNEBoolean */, + symbol: 4096 /* TypeofNESymbol */, + undefined: 524288 /* NEUndefined */, + object: 8192 /* TypeofNEObject */, + function: 16384 /* TypeofNEFunction */ + }); + var typeofTypesByName = ts.createMapFromTemplate({ + string: stringType, + number: numberType, + bigint: bigintType, + boolean: booleanType, + symbol: esSymbolType, + undefined: undefinedType + }); + var typeofType = createTypeofType(); + var _jsxNamespace; + var _jsxFactoryEntity; + var subtypeRelation = ts.createMap(); + var assignableRelation = ts.createMap(); + var definitelyAssignableRelation = ts.createMap(); + var comparableRelation = ts.createMap(); + var identityRelation = ts.createMap(); + var enumRelation = ts.createMap(); + var TypeSystemPropertyName; + (function (TypeSystemPropertyName) { + TypeSystemPropertyName[TypeSystemPropertyName["Type"] = 0] = "Type"; + TypeSystemPropertyName[TypeSystemPropertyName["ResolvedBaseConstructorType"] = 1] = "ResolvedBaseConstructorType"; + TypeSystemPropertyName[TypeSystemPropertyName["DeclaredType"] = 2] = "DeclaredType"; + TypeSystemPropertyName[TypeSystemPropertyName["ResolvedReturnType"] = 3] = "ResolvedReturnType"; + TypeSystemPropertyName[TypeSystemPropertyName["ImmediateBaseConstraint"] = 4] = "ImmediateBaseConstraint"; + TypeSystemPropertyName[TypeSystemPropertyName["EnumTagType"] = 5] = "EnumTagType"; + TypeSystemPropertyName[TypeSystemPropertyName["JSDocTypeReference"] = 6] = "JSDocTypeReference"; + })(TypeSystemPropertyName || (TypeSystemPropertyName = {})); + var CheckMode; + (function (CheckMode) { + CheckMode[CheckMode["Normal"] = 0] = "Normal"; + CheckMode[CheckMode["SkipContextSensitive"] = 1] = "SkipContextSensitive"; + CheckMode[CheckMode["Inferential"] = 2] = "Inferential"; + CheckMode[CheckMode["Contextual"] = 3] = "Contextual"; + })(CheckMode || (CheckMode = {})); + var CallbackCheck; + (function (CallbackCheck) { + CallbackCheck[CallbackCheck["None"] = 0] = "None"; + CallbackCheck[CallbackCheck["Bivariant"] = 1] = "Bivariant"; + CallbackCheck[CallbackCheck["Strict"] = 2] = "Strict"; + })(CallbackCheck || (CallbackCheck = {})); + var MappedTypeModifiers; + (function (MappedTypeModifiers) { + MappedTypeModifiers[MappedTypeModifiers["IncludeReadonly"] = 1] = "IncludeReadonly"; + MappedTypeModifiers[MappedTypeModifiers["ExcludeReadonly"] = 2] = "ExcludeReadonly"; + MappedTypeModifiers[MappedTypeModifiers["IncludeOptional"] = 4] = "IncludeOptional"; + MappedTypeModifiers[MappedTypeModifiers["ExcludeOptional"] = 8] = "ExcludeOptional"; + })(MappedTypeModifiers || (MappedTypeModifiers = {})); + var ExpandingFlags; + (function (ExpandingFlags) { + ExpandingFlags[ExpandingFlags["None"] = 0] = "None"; + ExpandingFlags[ExpandingFlags["Source"] = 1] = "Source"; + ExpandingFlags[ExpandingFlags["Target"] = 2] = "Target"; + ExpandingFlags[ExpandingFlags["Both"] = 3] = "Both"; + })(ExpandingFlags || (ExpandingFlags = {})); + var MembersOrExportsResolutionKind; + (function (MembersOrExportsResolutionKind) { + MembersOrExportsResolutionKind["resolvedExports"] = "resolvedExports"; + MembersOrExportsResolutionKind["resolvedMembers"] = "resolvedMembers"; + })(MembersOrExportsResolutionKind || (MembersOrExportsResolutionKind = {})); + var UnusedKind; + (function (UnusedKind) { + UnusedKind[UnusedKind["Local"] = 0] = "Local"; + UnusedKind[UnusedKind["Parameter"] = 1] = "Parameter"; + })(UnusedKind || (UnusedKind = {})); + var builtinGlobals = ts.createSymbolTable(); + builtinGlobals.set(undefinedSymbol.escapedName, undefinedSymbol); + var isNotOverloadAndNotAccessor = ts.and(isNotOverload, isNotAccessor); + initializeTypeChecker(); + return checker; + function getJsxNamespace(location) { + if (location) { + var file = ts.getSourceFileOfNode(location); + if (file) { + if (file.localJsxNamespace) { + return file.localJsxNamespace; + } + var jsxPragma = file.pragmas.get("jsx"); + if (jsxPragma) { + var chosenpragma = ts.isArray(jsxPragma) ? jsxPragma[0] : jsxPragma; // TODO: GH#18217 + file.localJsxFactory = ts.parseIsolatedEntityName(chosenpragma.arguments.factory, languageVersion); + if (file.localJsxFactory) { + return file.localJsxNamespace = getFirstIdentifier(file.localJsxFactory).escapedText; + } + } + } + } + if (!_jsxNamespace) { + _jsxNamespace = "React"; + if (compilerOptions.jsxFactory) { + _jsxFactoryEntity = ts.parseIsolatedEntityName(compilerOptions.jsxFactory, languageVersion); + if (_jsxFactoryEntity) { + _jsxNamespace = getFirstIdentifier(_jsxFactoryEntity).escapedText; + } + } + else if (compilerOptions.reactNamespace) { + _jsxNamespace = ts.escapeLeadingUnderscores(compilerOptions.reactNamespace); + } + } + return _jsxNamespace; + } + function getEmitResolver(sourceFile, cancellationToken) { + // Ensure we have all the type information in place for this file so that all the + // emitter questions of this resolver will return the right information. + getDiagnostics(sourceFile, cancellationToken); + return emitResolver; + } + function lookupOrIssueError(location, message, arg0, arg1, arg2, arg3) { + var diagnostic = location + ? ts.createDiagnosticForNode(location, message, arg0, arg1, arg2, arg3) + : ts.createCompilerDiagnostic(message, arg0, arg1, arg2, arg3); + var existing = diagnostics.lookup(diagnostic); + if (existing) { + return existing; + } + else { + diagnostics.add(diagnostic); + return diagnostic; + } + } + function addRelatedInfo(diagnostic) { + var relatedInformation = []; + for (var _i = 1; _i < arguments.length; _i++) { + relatedInformation[_i - 1] = arguments[_i]; + } + var _a; + if (!diagnostic.relatedInformation) { + diagnostic.relatedInformation = []; + } + (_a = diagnostic.relatedInformation).push.apply(_a, relatedInformation); + return diagnostic; + } + function error(location, message, arg0, arg1, arg2, arg3) { + var diagnostic = location + ? ts.createDiagnosticForNode(location, message, arg0, arg1, arg2, arg3) + : ts.createCompilerDiagnostic(message, arg0, arg1, arg2, arg3); + diagnostics.add(diagnostic); + return diagnostic; + } + function addErrorOrSuggestion(isError, diagnostic) { + if (isError) { + diagnostics.add(diagnostic); + } + else { + suggestionDiagnostics.add(diagnostic.file.fileName, __assign({}, diagnostic, { category: ts.DiagnosticCategory.Suggestion })); + } + } + function errorOrSuggestion(isError, location, message, arg0, arg1, arg2, arg3) { + addErrorOrSuggestion(isError, "message" in message ? ts.createDiagnosticForNode(location, message, arg0, arg1, arg2, arg3) : ts.createDiagnosticForNodeFromMessageChain(location, message)); + } + function createSymbol(flags, name, checkFlags) { + symbolCount++; + var symbol = (new Symbol(flags | 33554432 /* Transient */, name)); + symbol.checkFlags = checkFlags || 0; + return symbol; + } + function isTransientSymbol(symbol) { + return (symbol.flags & 33554432 /* Transient */) !== 0; + } + function getExcludedSymbolFlags(flags) { + var result = 0; + if (flags & 2 /* BlockScopedVariable */) + result |= 67220415 /* BlockScopedVariableExcludes */; + if (flags & 1 /* FunctionScopedVariable */) + result |= 67220414 /* FunctionScopedVariableExcludes */; + if (flags & 4 /* Property */) + result |= 0 /* PropertyExcludes */; + if (flags & 8 /* EnumMember */) + result |= 68008959 /* EnumMemberExcludes */; + if (flags & 16 /* Function */) + result |= 67219887 /* FunctionExcludes */; + if (flags & 32 /* Class */) + result |= 68008383 /* ClassExcludes */; + if (flags & 64 /* Interface */) + result |= 67897736 /* InterfaceExcludes */; + if (flags & 256 /* RegularEnum */) + result |= 68008191 /* RegularEnumExcludes */; + if (flags & 128 /* ConstEnum */) + result |= 68008831 /* ConstEnumExcludes */; + if (flags & 512 /* ValueModule */) + result |= 110735 /* ValueModuleExcludes */; + if (flags & 8192 /* Method */) + result |= 67212223 /* MethodExcludes */; + if (flags & 32768 /* GetAccessor */) + result |= 67154879 /* GetAccessorExcludes */; + if (flags & 65536 /* SetAccessor */) + result |= 67187647 /* SetAccessorExcludes */; + if (flags & 262144 /* TypeParameter */) + result |= 67635688 /* TypeParameterExcludes */; + if (flags & 524288 /* TypeAlias */) + result |= 67897832 /* TypeAliasExcludes */; + if (flags & 2097152 /* Alias */) + result |= 2097152 /* AliasExcludes */; + return result; + } + function recordMergedSymbol(target, source) { + if (!source.mergeId) { + source.mergeId = nextMergeId; + nextMergeId++; + } + mergedSymbols[source.mergeId] = target; + } + function cloneSymbol(symbol) { + var result = createSymbol(symbol.flags, symbol.escapedName); + result.declarations = symbol.declarations ? symbol.declarations.slice() : []; + result.parent = symbol.parent; + if (symbol.valueDeclaration) + result.valueDeclaration = symbol.valueDeclaration; + if (symbol.constEnumOnlyModule) + result.constEnumOnlyModule = true; + if (symbol.members) + result.members = ts.cloneMap(symbol.members); + if (symbol.exports) + result.exports = ts.cloneMap(symbol.exports); + recordMergedSymbol(result, symbol); + return result; + } + /** + * Note: if target is transient, then it is mutable, and mergeSymbol with both mutate and return it. + * If target is not transient, mergeSymbol will produce a transient clone, mutate that and return it. + */ + function mergeSymbol(target, source) { + if (!(target.flags & getExcludedSymbolFlags(source.flags)) || + (source.flags | target.flags) & 67108864 /* Assignment */) { + ts.Debug.assert(source !== target); + if (!(target.flags & 33554432 /* Transient */)) { + var resolvedTarget = resolveSymbol(target); + if (resolvedTarget === unknownSymbol) { + return source; + } + target = cloneSymbol(resolvedTarget); + } + // Javascript static-property-assignment declarations always merge, even though they are also values + if (source.flags & 512 /* ValueModule */ && target.flags & 512 /* ValueModule */ && target.constEnumOnlyModule && !source.constEnumOnlyModule) { + // reset flag when merging instantiated module into value module that has only const enums + target.constEnumOnlyModule = false; + } + target.flags |= source.flags; + if (source.valueDeclaration && + (!target.valueDeclaration || + ts.isAssignmentDeclaration(target.valueDeclaration) && !ts.isAssignmentDeclaration(source.valueDeclaration) || + ts.isEffectiveModuleDeclaration(target.valueDeclaration) && !ts.isEffectiveModuleDeclaration(source.valueDeclaration))) { + // other kinds of value declarations take precedence over modules and assignment declarations + target.valueDeclaration = source.valueDeclaration; + } + ts.addRange(target.declarations, source.declarations); + if (source.members) { + if (!target.members) + target.members = ts.createSymbolTable(); + mergeSymbolTable(target.members, source.members); + } + if (source.exports) { + if (!target.exports) + target.exports = ts.createSymbolTable(); + mergeSymbolTable(target.exports, source.exports); + } + recordMergedSymbol(target, source); + } + else if (target.flags & 1024 /* NamespaceModule */) { + error(ts.getNameOfDeclaration(source.declarations[0]), ts.Diagnostics.Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity, symbolToString(target)); + } + else { // error + var isEitherEnum = !!(target.flags & 384 /* Enum */ || source.flags & 384 /* Enum */); + var isEitherBlockScoped_1 = !!(target.flags & 2 /* BlockScopedVariable */ || source.flags & 2 /* BlockScopedVariable */); + var message = isEitherEnum + ? ts.Diagnostics.Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations + : isEitherBlockScoped_1 + ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 + : ts.Diagnostics.Duplicate_identifier_0; + var sourceSymbolFile = source.declarations && ts.getSourceFileOfNode(source.declarations[0]); + var targetSymbolFile = target.declarations && ts.getSourceFileOfNode(target.declarations[0]); + var symbolName_1 = symbolToString(source); + // Collect top-level duplicate identifier errors into one mapping, so we can then merge their diagnostics if there are a bunch + if (sourceSymbolFile && targetSymbolFile && amalgamatedDuplicates && !isEitherEnum && sourceSymbolFile !== targetSymbolFile) { + var firstFile_1 = ts.comparePaths(sourceSymbolFile.path, targetSymbolFile.path) === -1 /* LessThan */ ? sourceSymbolFile : targetSymbolFile; + var secondFile_1 = firstFile_1 === sourceSymbolFile ? targetSymbolFile : sourceSymbolFile; + var filesDuplicates = ts.getOrUpdate(amalgamatedDuplicates, firstFile_1.path + "|" + secondFile_1.path, function () { + return ({ firstFile: firstFile_1, secondFile: secondFile_1, conflictingSymbols: ts.createMap() }); + }); + var conflictingSymbolInfo = ts.getOrUpdate(filesDuplicates.conflictingSymbols, symbolName_1, function () { + return ({ isBlockScoped: isEitherBlockScoped_1, firstFileLocations: [], secondFileLocations: [] }); + }); + addDuplicateLocations(conflictingSymbolInfo.firstFileLocations, source); + addDuplicateLocations(conflictingSymbolInfo.secondFileLocations, target); + } + else { + addDuplicateDeclarationErrorsForSymbols(source, message, symbolName_1, target); + addDuplicateDeclarationErrorsForSymbols(target, message, symbolName_1, source); + } + } + return target; + function addDuplicateLocations(locs, symbol) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + ts.pushIfUnique(locs, (ts.getExpandoInitializer(decl, /*isPrototypeAssignment*/ false) ? ts.getNameOfExpando(decl) : ts.getNameOfDeclaration(decl)) || decl); + } + } + } + function addDuplicateDeclarationErrorsForSymbols(target, message, symbolName, source) { + ts.forEach(target.declarations, function (node) { + var errorNode = (ts.getExpandoInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getNameOfExpando(node) : ts.getNameOfDeclaration(node)) || node; + addDuplicateDeclarationError(errorNode, message, symbolName, source.declarations); + }); + } + function addDuplicateDeclarationError(errorNode, message, symbolName, relatedNodes) { + var err = lookupOrIssueError(errorNode, message, symbolName); + for (var _i = 0, _a = relatedNodes || ts.emptyArray; _i < _a.length; _i++) { + var relatedNode = _a[_i]; + err.relatedInformation = err.relatedInformation || []; + if (ts.length(err.relatedInformation) >= 5) + continue; + addRelatedInfo(err, !ts.length(err.relatedInformation) ? ts.createDiagnosticForNode(relatedNode, ts.Diagnostics._0_was_also_declared_here, symbolName) : ts.createDiagnosticForNode(relatedNode, ts.Diagnostics.and_here)); + } + } + function combineSymbolTables(first, second) { + if (!ts.hasEntries(first)) + return second; + if (!ts.hasEntries(second)) + return first; + var combined = ts.createSymbolTable(); + mergeSymbolTable(combined, first); + mergeSymbolTable(combined, second); + return combined; + } + function mergeSymbolTable(target, source) { + source.forEach(function (sourceSymbol, id) { + var targetSymbol = target.get(id); + target.set(id, targetSymbol ? mergeSymbol(targetSymbol, sourceSymbol) : sourceSymbol); + }); + } + function mergeModuleAugmentation(moduleName) { + var moduleAugmentation = moduleName.parent; + if (moduleAugmentation.symbol.declarations[0] !== moduleAugmentation) { + // this is a combined symbol for multiple augmentations within the same file. + // its symbol already has accumulated information for all declarations + // so we need to add it just once - do the work only for first declaration + ts.Debug.assert(moduleAugmentation.symbol.declarations.length > 1); + return; + } + if (ts.isGlobalScopeAugmentation(moduleAugmentation)) { + mergeSymbolTable(globals, moduleAugmentation.symbol.exports); + } + else { + // find a module that about to be augmented + // do not validate names of augmentations that are defined in ambient context + var moduleNotFoundError = !(moduleName.parent.parent.flags & 4194304 /* Ambient */) + ? ts.Diagnostics.Invalid_module_name_in_augmentation_module_0_cannot_be_found + : undefined; + var mainModule = resolveExternalModuleNameWorker(moduleName, moduleName, moduleNotFoundError, /*isForAugmentation*/ true); + if (!mainModule) { + return; + } + // obtain item referenced by 'export=' + mainModule = resolveExternalModuleSymbol(mainModule); + if (mainModule.flags & 1920 /* Namespace */) { + mainModule = mergeSymbol(mainModule, moduleAugmentation.symbol); + } + else { + // moduleName will be a StringLiteral since this is not `declare global`. + error(moduleName, ts.Diagnostics.Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity, moduleName.text); + } + } + } + function addToSymbolTable(target, source, message) { + source.forEach(function (sourceSymbol, id) { + var targetSymbol = target.get(id); + if (targetSymbol) { + // Error on redeclarations + ts.forEach(targetSymbol.declarations, addDeclarationDiagnostic(ts.unescapeLeadingUnderscores(id), message)); + } + else { + target.set(id, sourceSymbol); + } + }); + function addDeclarationDiagnostic(id, message) { + return function (declaration) { return diagnostics.add(ts.createDiagnosticForNode(declaration, message, id)); }; + } + } + function getSymbolLinks(symbol) { + if (symbol.flags & 33554432 /* Transient */) + return symbol; + var id = getSymbolId(symbol); + return symbolLinks[id] || (symbolLinks[id] = {}); + } + function getNodeLinks(node) { + var nodeId = getNodeId(node); + return nodeLinks[nodeId] || (nodeLinks[nodeId] = { flags: 0 }); + } + function isGlobalSourceFile(node) { + return node.kind === 279 /* SourceFile */ && !ts.isExternalOrCommonJsModule(node); + } + function getSymbol(symbols, name, meaning) { + if (meaning) { + var symbol = symbols.get(name); + if (symbol) { + ts.Debug.assert((ts.getCheckFlags(symbol) & 1 /* Instantiated */) === 0, "Should never get an instantiated symbol here."); + if (symbol.flags & meaning) { + return symbol; + } + if (symbol.flags & 2097152 /* Alias */) { + var target = resolveAlias(symbol); + // Unknown symbol means an error occurred in alias resolution, treat it as positive answer to avoid cascading errors + if (target === unknownSymbol || target.flags & meaning) { + return symbol; + } + } + } + } + // return undefined if we can't find a symbol. + } + /** + * Get symbols that represent parameter-property-declaration as parameter and as property declaration + * @param parameter a parameterDeclaration node + * @param parameterName a name of the parameter to get the symbols for. + * @return a tuple of two symbols + */ + function getSymbolsOfParameterPropertyDeclaration(parameter, parameterName) { + var constructorDeclaration = parameter.parent; + var classDeclaration = parameter.parent.parent; + var parameterSymbol = getSymbol(constructorDeclaration.locals, parameterName, 67220415 /* Value */); + var propertySymbol = getSymbol(getMembersOfSymbol(classDeclaration.symbol), parameterName, 67220415 /* Value */); + if (parameterSymbol && propertySymbol) { + return [parameterSymbol, propertySymbol]; + } + return ts.Debug.fail("There should exist two symbols, one as property declaration and one as parameter declaration"); + } + function isBlockScopedNameDeclaredBeforeUse(declaration, usage) { + var declarationFile = ts.getSourceFileOfNode(declaration); + var useFile = ts.getSourceFileOfNode(usage); + if (declarationFile !== useFile) { + if ((moduleKind && (declarationFile.externalModuleIndicator || useFile.externalModuleIndicator)) || + (!compilerOptions.outFile && !compilerOptions.out) || + isInTypeQuery(usage) || + declaration.flags & 4194304 /* Ambient */) { + // nodes are in different files and order cannot be determined + return true; + } + // declaration is after usage + // can be legal if usage is deferred (i.e. inside function or in initializer of instance property) + if (isUsedInFunctionOrInstanceProperty(usage, declaration)) { + return true; + } + var sourceFiles = host.getSourceFiles(); + return sourceFiles.indexOf(declarationFile) <= sourceFiles.indexOf(useFile); + } + if (declaration.pos <= usage.pos) { + // declaration is before usage + if (declaration.kind === 186 /* BindingElement */) { + // still might be illegal if declaration and usage are both binding elements (eg var [a = b, b = b] = [1, 2]) + var errorBindingElement = ts.getAncestor(usage, 186 /* BindingElement */); + if (errorBindingElement) { + return ts.findAncestor(errorBindingElement, ts.isBindingElement) !== ts.findAncestor(declaration, ts.isBindingElement) || + declaration.pos < errorBindingElement.pos; + } + // or it might be illegal if usage happens before parent variable is declared (eg var [a] = a) + return isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 237 /* VariableDeclaration */), usage); + } + else if (declaration.kind === 237 /* VariableDeclaration */) { + // still might be illegal if usage is in the initializer of the variable declaration (eg var a = a) + return !isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage); + } + else if (ts.isClassDeclaration(declaration)) { + // still might be illegal if the usage is within a computed property name in the class (eg class A { static p = "a"; [A.p]() {} }) + return !ts.findAncestor(usage, function (n) { return ts.isComputedPropertyName(n) && n.parent.parent === declaration; }); + } + return true; + } + // declaration is after usage, but it can still be legal if usage is deferred: + // 1. inside an export specifier + // 2. inside a function + // 3. inside an instance property initializer, a reference to a non-instance property + // 4. inside a static property initializer, a reference to a static method in the same class + // 5. inside a TS export= declaration (since we will move the export statement during emit to avoid TDZ) + // or if usage is in a type context: + // 1. inside a type query (typeof in type position) + // 2. inside a jsdoc comment + if (usage.parent.kind === 257 /* ExportSpecifier */ || (usage.parent.kind === 254 /* ExportAssignment */ && usage.parent.isExportEquals)) { + // export specifiers do not use the variable, they only make it available for use + return true; + } + // When resolving symbols for exports, the `usage` location passed in can be the export site directly + if (usage.kind === 254 /* ExportAssignment */ && usage.isExportEquals) { + return true; + } + var container = ts.getEnclosingBlockScopeContainer(declaration); + return !!(usage.flags & 2097152 /* JSDoc */) || isInTypeQuery(usage) || isUsedInFunctionOrInstanceProperty(usage, declaration, container); + function isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage) { + var container = ts.getEnclosingBlockScopeContainer(declaration); + switch (declaration.parent.parent.kind) { + case 219 /* VariableStatement */: + case 225 /* ForStatement */: + case 227 /* ForOfStatement */: + // variable statement/for/for-of statement case, + // use site should not be inside variable declaration (initializer of declaration or binding element) + if (isSameScopeDescendentOf(usage, declaration, container)) { + return true; + } + break; + } + // ForIn/ForOf case - use site should not be used in expression part + var grandparent = declaration.parent.parent; + return ts.isForInOrOfStatement(grandparent) && isSameScopeDescendentOf(usage, grandparent.expression, container); + } + function isUsedInFunctionOrInstanceProperty(usage, declaration, container) { + return !!ts.findAncestor(usage, function (current) { + if (current === container) { + return "quit"; + } + if (ts.isFunctionLike(current)) { + return true; + } + var initializerOfProperty = current.parent && + current.parent.kind === 154 /* PropertyDeclaration */ && + current.parent.initializer === current; + if (initializerOfProperty) { + if (ts.hasModifier(current.parent, 32 /* Static */)) { + if (declaration.kind === 156 /* MethodDeclaration */) { + return true; + } + } + else { + var isDeclarationInstanceProperty = declaration.kind === 154 /* PropertyDeclaration */ && !ts.hasModifier(declaration, 32 /* Static */); + if (!isDeclarationInstanceProperty || ts.getContainingClass(usage) !== ts.getContainingClass(declaration)) { + return true; + } + } + } + return false; + }); + } + } + /** + * Resolve a given name for a given meaning at a given location. An error is reported if the name was not found and + * the nameNotFoundMessage argument is not undefined. Returns the resolved symbol, or undefined if no symbol with + * the given name can be found. + * + * @param isUse If true, this will count towards --noUnusedLocals / --noUnusedParameters. + */ + function resolveName(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, suggestedNameNotFoundMessage) { + if (excludeGlobals === void 0) { excludeGlobals = false; } + return resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, getSymbol, suggestedNameNotFoundMessage); + } + function resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, lookup, suggestedNameNotFoundMessage) { + var originalLocation = location; // needed for did-you-mean error reporting, which gathers candidates starting from the original location + var result; + var lastLocation; + var lastSelfReferenceLocation; + var propertyWithInvalidInitializer; + var errorLocation = location; + var grandparent; + var isInExternalModule = false; + loop: while (location) { + // Locals of a source file are not in scope (because they get merged into the global symbol table) + if (location.locals && !isGlobalSourceFile(location)) { + if (result = lookup(location.locals, name, meaning)) { + var useResult = true; + if (ts.isFunctionLike(location) && lastLocation && lastLocation !== location.body) { + // symbol lookup restrictions for function-like declarations + // - Type parameters of a function are in scope in the entire function declaration, including the parameter + // list and return type. However, local types are only in scope in the function body. + // - parameters are only in the scope of function body + // This restriction does not apply to JSDoc comment types because they are parented + // at a higher level than type parameters would normally be + if (meaning & result.flags & 67897832 /* Type */ && lastLocation.kind !== 291 /* JSDocComment */) { + useResult = result.flags & 262144 /* TypeParameter */ + // type parameters are visible in parameter list, return type and type parameter list + ? lastLocation === location.type || + lastLocation.kind === 151 /* Parameter */ || + lastLocation.kind === 150 /* TypeParameter */ + // local types not visible outside the function body + : false; + } + if (meaning & result.flags & 3 /* Variable */) { + // expression inside parameter will lookup as normal variable scope when targeting es2015+ + var functionLocation = location; + if (compilerOptions.target && compilerOptions.target >= 2 /* ES2015 */ && ts.isParameter(lastLocation) && + functionLocation.body && result.valueDeclaration.pos >= functionLocation.body.pos && result.valueDeclaration.end <= functionLocation.body.end) { + useResult = false; + } + else if (result.flags & 1 /* FunctionScopedVariable */) { + // parameters are visible only inside function body, parameter list and return type + // technically for parameter list case here we might mix parameters and variables declared in function, + // however it is detected separately when checking initializers of parameters + // to make sure that they reference no variables declared after them. + useResult = + lastLocation.kind === 151 /* Parameter */ || + (lastLocation === location.type && + !!ts.findAncestor(result.valueDeclaration, ts.isParameter)); + } + } + } + else if (location.kind === 175 /* ConditionalType */) { + // A type parameter declared using 'infer T' in a conditional type is visible only in + // the true branch of the conditional type. + useResult = lastLocation === location.trueType; + } + if (useResult) { + break loop; + } + else { + result = undefined; + } + } + } + switch (location.kind) { + case 279 /* SourceFile */: + if (!ts.isExternalOrCommonJsModule(location)) + break; + isInExternalModule = true; + // falls through + case 244 /* ModuleDeclaration */: + var moduleExports = getSymbolOfNode(location).exports; + if (location.kind === 279 /* SourceFile */ || ts.isAmbientModule(location)) { + // It's an external module. First see if the module has an export default and if the local + // name of that export default matches. + if (result = moduleExports.get("default" /* Default */)) { + var localSymbol = ts.getLocalSymbolForExportDefault(result); + if (localSymbol && (result.flags & meaning) && localSymbol.escapedName === name) { + break loop; + } + result = undefined; + } + // Because of module/namespace merging, a module's exports are in scope, + // yet we never want to treat an export specifier as putting a member in scope. + // Therefore, if the name we find is purely an export specifier, it is not actually considered in scope. + // Two things to note about this: + // 1. We have to check this without calling getSymbol. The problem with calling getSymbol + // on an export specifier is that it might find the export specifier itself, and try to + // resolve it as an alias. This will cause the checker to consider the export specifier + // a circular alias reference when it might not be. + // 2. We check === SymbolFlags.Alias in order to check that the symbol is *purely* + // an alias. If we used &, we'd be throwing out symbols that have non alias aspects, + // which is not the desired behavior. + var moduleExport = moduleExports.get(name); + if (moduleExport && + moduleExport.flags === 2097152 /* Alias */ && + ts.getDeclarationOfKind(moduleExport, 257 /* ExportSpecifier */)) { + break; + } + } + // ES6 exports are also visible locally (except for 'default'), but commonjs exports are not (except typedefs) + if (name !== "default" /* Default */ && (result = lookup(moduleExports, name, meaning & 2623475 /* ModuleMember */))) { + if (ts.isSourceFile(location) && location.commonJsModuleIndicator && !result.declarations.some(ts.isJSDocTypeAlias)) { + result = undefined; + } + else { + break loop; + } + } + break; + case 243 /* EnumDeclaration */: + if (result = lookup(getSymbolOfNode(location).exports, name, meaning & 8 /* EnumMember */)) { + break loop; + } + break; + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + // TypeScript 1.0 spec (April 2014): 8.4.1 + // Initializer expressions for instance member variables are evaluated in the scope + // of the class constructor body but are not permitted to reference parameters or + // local variables of the constructor. This effectively means that entities from outer scopes + // by the same name as a constructor parameter or local variable are inaccessible + // in initializer expressions for instance member variables. + if (ts.isClassLike(location.parent) && !ts.hasModifier(location, 32 /* Static */)) { + var ctor = findConstructorDeclaration(location.parent); + if (ctor && ctor.locals) { + if (lookup(ctor.locals, name, meaning & 67220415 /* Value */)) { + // Remember the property node, it will be used later to report appropriate error + propertyWithInvalidInitializer = location; + } + } + } + break; + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 241 /* InterfaceDeclaration */: + // The below is used to lookup type parameters within a class or interface, as they are added to the class/interface locals + // These can never be latebound, so the symbol's raw members are sufficient. `getMembersOfNode` cannot be used, as it would + // trigger resolving late-bound names, which we may already be in the process of doing while we're here! + if (result = lookup(getSymbolOfNode(location).members || emptySymbols, name, meaning & 67897832 /* Type */)) { + if (!isTypeParameterSymbolDeclaredInContainer(result, location)) { + // ignore type parameters not declared in this container + result = undefined; + break; + } + if (lastLocation && ts.hasModifier(lastLocation, 32 /* Static */)) { + // TypeScript 1.0 spec (April 2014): 3.4.1 + // The scope of a type parameter extends over the entire declaration with which the type + // parameter list is associated, with the exception of static member declarations in classes. + error(errorLocation, ts.Diagnostics.Static_members_cannot_reference_class_type_parameters); + return undefined; + } + break loop; + } + if (location.kind === 209 /* ClassExpression */ && meaning & 32 /* Class */) { + var className = location.name; + if (className && name === className.escapedText) { + result = location.symbol; + break loop; + } + } + break; + case 211 /* ExpressionWithTypeArguments */: + // The type parameters of a class are not in scope in the base class expression. + if (lastLocation === location.expression && location.parent.token === 86 /* ExtendsKeyword */) { + var container = location.parent.parent; + if (ts.isClassLike(container) && (result = lookup(getSymbolOfNode(container).members, name, meaning & 67897832 /* Type */))) { + if (nameNotFoundMessage) { + error(errorLocation, ts.Diagnostics.Base_class_expressions_cannot_reference_class_type_parameters); + } + return undefined; + } + } + break; + // It is not legal to reference a class's own type parameters from a computed property name that + // belongs to the class. For example: + // + // function foo() { return '' } + // class C { // <-- Class's own type parameter T + // [foo()]() { } // <-- Reference to T from class's own computed property + // } + // + case 149 /* ComputedPropertyName */: + grandparent = location.parent.parent; + if (ts.isClassLike(grandparent) || grandparent.kind === 241 /* InterfaceDeclaration */) { + // A reference to this grandparent's type parameters would be an error + if (result = lookup(getSymbolOfNode(grandparent).members, name, meaning & 67897832 /* Type */)) { + error(errorLocation, ts.Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type); + return undefined; + } + } + break; + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 239 /* FunctionDeclaration */: + case 197 /* ArrowFunction */: + if (meaning & 3 /* Variable */ && name === "arguments") { + result = argumentsSymbol; + break loop; + } + break; + case 196 /* FunctionExpression */: + if (meaning & 3 /* Variable */ && name === "arguments") { + result = argumentsSymbol; + break loop; + } + if (meaning & 16 /* Function */) { + var functionName = location.name; + if (functionName && name === functionName.escapedText) { + result = location.symbol; + break loop; + } + } + break; + case 152 /* Decorator */: + // Decorators are resolved at the class declaration. Resolving at the parameter + // or member would result in looking up locals in the method. + // + // function y() {} + // class C { + // method(@y x, y) {} // <-- decorator y should be resolved at the class declaration, not the parameter. + // } + // + if (location.parent && location.parent.kind === 151 /* Parameter */) { + location = location.parent; + } + // + // function y() {} + // class C { + // @y method(x, y) {} // <-- decorator y should be resolved at the class declaration, not the method. + // } + // + if (location.parent && ts.isClassElement(location.parent)) { + location = location.parent; + } + break; + case 304 /* JSDocTypedefTag */: + case 297 /* JSDocCallbackTag */: + // js type aliases do not resolve names from their host, so skip past it + location = ts.getJSDocHost(location); + break; + } + if (isSelfReferenceLocation(location)) { + lastSelfReferenceLocation = location; + } + lastLocation = location; + location = location.parent; + } + // We just climbed up parents looking for the name, meaning that we started in a descendant node of `lastLocation`. + // If `result === lastSelfReferenceLocation.symbol`, that means that we are somewhere inside `lastSelfReferenceLocation` looking up a name, and resolving to `lastLocation` itself. + // That means that this is a self-reference of `lastLocation`, and shouldn't count this when considering whether `lastLocation` is used. + if (isUse && result && (!lastSelfReferenceLocation || result !== lastSelfReferenceLocation.symbol)) { + result.isReferenced |= meaning; + } + if (!result) { + if (lastLocation) { + ts.Debug.assert(lastLocation.kind === 279 /* SourceFile */); + if (lastLocation.commonJsModuleIndicator && name === "exports" && meaning & lastLocation.symbol.flags) { + return lastLocation.symbol; + } + } + if (!excludeGlobals) { + result = lookup(globals, name, meaning); + } + } + if (!result) { + if (originalLocation && ts.isInJSFile(originalLocation) && originalLocation.parent) { + if (ts.isRequireCall(originalLocation.parent, /*checkArgumentIsStringLiteralLike*/ false)) { + return requireSymbol; + } + } + } + if (!result) { + if (nameNotFoundMessage) { + if (!errorLocation || + !checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) && // TODO: GH#18217 + !checkAndReportErrorForExtendingInterface(errorLocation) && + !checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) && + !checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) && + !checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning)) { + var suggestion = void 0; + if (suggestedNameNotFoundMessage && suggestionCount < maximumSuggestionCount) { + suggestion = getSuggestedSymbolForNonexistentSymbol(originalLocation, name, meaning); + if (suggestion) { + var suggestionName = symbolToString(suggestion); + var diagnostic = error(errorLocation, suggestedNameNotFoundMessage, diagnosticName(nameArg), suggestionName); + if (suggestion.valueDeclaration) { + addRelatedInfo(diagnostic, ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestionName)); + } + } + } + if (!suggestion) { + error(errorLocation, nameNotFoundMessage, diagnosticName(nameArg)); + } + suggestionCount++; + } + } + return undefined; + } + // Perform extra checks only if error reporting was requested + if (nameNotFoundMessage) { + if (propertyWithInvalidInitializer) { + // We have a match, but the reference occurred within a property initializer and the identifier also binds + // to a local variable in the constructor where the code will be emitted. + var propertyName = propertyWithInvalidInitializer.name; + error(errorLocation, ts.Diagnostics.Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor, ts.declarationNameToString(propertyName), diagnosticName(nameArg)); + return undefined; + } + // Only check for block-scoped variable if we have an error location and are looking for the + // name with variable meaning + // For example, + // declare module foo { + // interface bar {} + // } + // const foo/*1*/: foo/*2*/.bar; + // The foo at /*1*/ and /*2*/ will share same symbol with two meanings: + // block-scoped variable and namespace module. However, only when we + // try to resolve name in /*1*/ which is used in variable position, + // we want to check for block-scoped + if (errorLocation && + (meaning & 2 /* BlockScopedVariable */ || + ((meaning & 32 /* Class */ || meaning & 384 /* Enum */) && (meaning & 67220415 /* Value */) === 67220415 /* Value */))) { + var exportOrLocalSymbol = getExportSymbolOfValueSymbolIfExported(result); + if (exportOrLocalSymbol.flags & 2 /* BlockScopedVariable */ || exportOrLocalSymbol.flags & 32 /* Class */ || exportOrLocalSymbol.flags & 384 /* Enum */) { + checkResolvedBlockScopedVariable(exportOrLocalSymbol, errorLocation); + } + } + // If we're in an external module, we can't reference value symbols created from UMD export declarations + if (result && isInExternalModule && (meaning & 67220415 /* Value */) === 67220415 /* Value */ && !(originalLocation.flags & 2097152 /* JSDoc */)) { + if (ts.some(result.declarations, function (d) { return ts.isNamespaceExportDeclaration(d) || ts.isSourceFile(d) && !!d.symbol.globalExports; })) { + error(errorLocation, ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead, ts.unescapeLeadingUnderscores(name)); // TODO: GH#18217 + } + } + } + return result; + } + function isSelfReferenceLocation(node) { + switch (node.kind) { + case 239 /* FunctionDeclaration */: + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + case 243 /* EnumDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 244 /* ModuleDeclaration */: // For `namespace N { N; }` + return true; + default: + return false; + } + } + function diagnosticName(nameArg) { + return ts.isString(nameArg) ? ts.unescapeLeadingUnderscores(nameArg) : ts.declarationNameToString(nameArg); + } + function isTypeParameterSymbolDeclaredInContainer(symbol, container) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + if (decl.kind === 150 /* TypeParameter */) { + var parent = ts.isJSDocTemplateTag(decl.parent) ? ts.getJSDocHost(decl.parent) : decl.parent; + if (parent === container) { + return !(ts.isJSDocTemplateTag(decl.parent) && ts.find(decl.parent.parent.tags, ts.isJSDocTypeAlias)); // TODO: GH#18217 + } + } + } + return false; + } + function checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) { + if (!ts.isIdentifier(errorLocation) || errorLocation.escapedText !== name || isTypeReferenceIdentifier(errorLocation) || isInTypeQuery(errorLocation)) { + return false; + } + var container = ts.getThisContainer(errorLocation, /*includeArrowFunctions*/ false); + var location = container; + while (location) { + if (ts.isClassLike(location.parent)) { + var classSymbol = getSymbolOfNode(location.parent); + if (!classSymbol) { + break; + } + // Check to see if a static member exists. + var constructorType = getTypeOfSymbol(classSymbol); + if (getPropertyOfType(constructorType, name)) { + error(errorLocation, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_static_member_1_0, diagnosticName(nameArg), symbolToString(classSymbol)); + return true; + } + // No static member is present. + // Check if we're in an instance method and look for a relevant instance member. + if (location === container && !ts.hasModifier(location, 32 /* Static */)) { + var instanceType = getDeclaredTypeOfSymbol(classSymbol).thisType; // TODO: GH#18217 + if (getPropertyOfType(instanceType, name)) { + error(errorLocation, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0, diagnosticName(nameArg)); + return true; + } + } + } + location = location.parent; + } + return false; + } + function checkAndReportErrorForExtendingInterface(errorLocation) { + var expression = getEntityNameForExtendingInterface(errorLocation); + if (expression && resolveEntityName(expression, 64 /* Interface */, /*ignoreErrors*/ true)) { + error(errorLocation, ts.Diagnostics.Cannot_extend_an_interface_0_Did_you_mean_implements, ts.getTextOfNode(expression)); + return true; + } + return false; + } + /** + * Climbs up parents to an ExpressionWithTypeArguments, and returns its expression, + * but returns undefined if that expression is not an EntityNameExpression. + */ + function getEntityNameForExtendingInterface(node) { + switch (node.kind) { + case 72 /* Identifier */: + case 189 /* PropertyAccessExpression */: + return node.parent ? getEntityNameForExtendingInterface(node.parent) : undefined; + case 211 /* ExpressionWithTypeArguments */: + if (ts.isEntityNameExpression(node.expression)) { + return node.expression; + } + // falls through + default: + return undefined; + } + } + function checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) { + var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJSFile(errorLocation) ? 67220415 /* Value */ : 0); + if (meaning === namespaceMeaning) { + var symbol = resolveSymbol(resolveName(errorLocation, name, 67897832 /* Type */ & ~namespaceMeaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + var parent = errorLocation.parent; + if (symbol) { + if (ts.isQualifiedName(parent)) { + ts.Debug.assert(parent.left === errorLocation, "Should only be resolving left side of qualified name as a namespace"); + var propName = parent.right.escapedText; + var propType = getPropertyOfType(getDeclaredTypeOfSymbol(symbol), propName); + if (propType) { + error(parent, ts.Diagnostics.Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_property_1_in_0_with_0_1, ts.unescapeLeadingUnderscores(name), ts.unescapeLeadingUnderscores(propName)); + return true; + } + } + error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here, ts.unescapeLeadingUnderscores(name)); + return true; + } + } + return false; + } + function checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) { + if (meaning & (67220415 /* Value */ & ~1024 /* NamespaceModule */)) { + if (name === "any" || name === "string" || name === "number" || name === "boolean" || name === "never") { + error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, ts.unescapeLeadingUnderscores(name)); + return true; + } + var symbol = resolveSymbol(resolveName(errorLocation, name, 67897832 /* Type */ & ~67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + if (symbol && !(symbol.flags & 1024 /* NamespaceModule */)) { + var message = (name === "Promise" || name === "Symbol") + ? ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later + : ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here; + error(errorLocation, message, ts.unescapeLeadingUnderscores(name)); + return true; + } + } + return false; + } + function checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) { + if (meaning & (67220415 /* Value */ & ~1024 /* NamespaceModule */ & ~67897832 /* Type */)) { + var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 /* NamespaceModule */ & ~67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + if (symbol) { + error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_value, ts.unescapeLeadingUnderscores(name)); + return true; + } + } + else if (meaning & (67897832 /* Type */ & ~1024 /* NamespaceModule */ & ~67220415 /* Value */)) { + var symbol = resolveSymbol(resolveName(errorLocation, name, (512 /* ValueModule */ | 1024 /* NamespaceModule */) & ~67897832 /* Type */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + if (symbol) { + error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_type, ts.unescapeLeadingUnderscores(name)); + return true; + } + } + return false; + } + function checkResolvedBlockScopedVariable(result, errorLocation) { + ts.Debug.assert(!!(result.flags & 2 /* BlockScopedVariable */ || result.flags & 32 /* Class */ || result.flags & 384 /* Enum */)); + // Block-scoped variables cannot be used before their definition + var declaration = ts.find(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) || ts.isClassLike(d) || (d.kind === 243 /* EnumDeclaration */) || ts.isInJSFile(d) && !!ts.getJSDocEnumTag(d); }); + if (declaration === undefined) + return ts.Debug.fail("Declaration to checkResolvedBlockScopedVariable is undefined"); + if (!(declaration.flags & 4194304 /* Ambient */) && !isBlockScopedNameDeclaredBeforeUse(declaration, errorLocation)) { + var diagnosticMessage = void 0; + var declarationName = ts.declarationNameToString(ts.getNameOfDeclaration(declaration)); + if (result.flags & 2 /* BlockScopedVariable */) { + diagnosticMessage = error(errorLocation, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, declarationName); + } + else if (result.flags & 32 /* Class */) { + diagnosticMessage = error(errorLocation, ts.Diagnostics.Class_0_used_before_its_declaration, declarationName); + } + else if (result.flags & 256 /* RegularEnum */) { + diagnosticMessage = error(errorLocation, ts.Diagnostics.Enum_0_used_before_its_declaration, declarationName); + } + else { + ts.Debug.assert(!!(result.flags & 128 /* ConstEnum */)); + if (compilerOptions.preserveConstEnums) { + diagnosticMessage = error(errorLocation, ts.Diagnostics.Class_0_used_before_its_declaration, declarationName); + } + } + if (diagnosticMessage) { + addRelatedInfo(diagnosticMessage, ts.createDiagnosticForNode(declaration, ts.Diagnostics._0_is_declared_here, declarationName)); + } + } + } + /* Starting from 'initial' node walk up the parent chain until 'stopAt' node is reached. + * If at any point current node is equal to 'parent' node - return true. + * Return false if 'stopAt' node is reached or isFunctionLike(current) === true. + */ + function isSameScopeDescendentOf(initial, parent, stopAt) { + return !!parent && !!ts.findAncestor(initial, function (n) { return n === stopAt || ts.isFunctionLike(n) ? "quit" : n === parent; }); + } + function getAnyImportSyntax(node) { + switch (node.kind) { + case 248 /* ImportEqualsDeclaration */: + return node; + case 250 /* ImportClause */: + return node.parent; + case 251 /* NamespaceImport */: + return node.parent.parent; + case 253 /* ImportSpecifier */: + return node.parent.parent.parent; + default: + return undefined; + } + } + function getDeclarationOfAliasSymbol(symbol) { + return ts.find(symbol.declarations, ts.isAliasSymbolDeclaration); + } + function getTargetOfImportEqualsDeclaration(node, dontResolveAlias) { + if (node.moduleReference.kind === 259 /* ExternalModuleReference */) { + return resolveExternalModuleSymbol(resolveExternalModuleName(node, ts.getExternalModuleImportEqualsDeclarationExpression(node))); + } + return getSymbolOfPartOfRightHandSideOfImportEquals(node.moduleReference, dontResolveAlias); + } + function resolveExportByName(moduleSymbol, name, dontResolveAlias) { + var exportValue = moduleSymbol.exports.get("export=" /* ExportEquals */); + return exportValue + ? getPropertyOfType(getTypeOfSymbol(exportValue), name) + : resolveSymbol(moduleSymbol.exports.get(name), dontResolveAlias); + } + function isSyntacticDefault(node) { + return ((ts.isExportAssignment(node) && !node.isExportEquals) || ts.hasModifier(node, 512 /* Default */) || ts.isExportSpecifier(node)); + } + function canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias) { + if (!allowSyntheticDefaultImports) { + return false; + } + // Declaration files (and ambient modules) + if (!file || file.isDeclarationFile) { + // Definitely cannot have a synthetic default if they have a syntactic default member specified + var defaultExportSymbol = resolveExportByName(moduleSymbol, "default" /* Default */, /*dontResolveAlias*/ true); // Dont resolve alias because we want the immediately exported symbol's declaration + if (defaultExportSymbol && ts.some(defaultExportSymbol.declarations, isSyntacticDefault)) { + return false; + } + // It _might_ still be incorrect to assume there is no __esModule marker on the import at runtime, even if there is no `default` member + // So we check a bit more, + if (resolveExportByName(moduleSymbol, ts.escapeLeadingUnderscores("__esModule"), dontResolveAlias)) { + // If there is an `__esModule` specified in the declaration (meaning someone explicitly added it or wrote it in their code), + // it definitely is a module and does not have a synthetic default + return false; + } + // There are _many_ declaration files not written with esmodules in mind that still get compiled into a format with __esModule set + // Meaning there may be no default at runtime - however to be on the permissive side, we allow access to a synthetic default member + // as there is no marker to indicate if the accompanying JS has `__esModule` or not, or is even native esm + return true; + } + // TypeScript files never have a synthetic default (as they are always emitted with an __esModule marker) _unless_ they contain an export= statement + if (!ts.isSourceFileJS(file)) { + return hasExportAssignmentSymbol(moduleSymbol); + } + // JS files have a synthetic default if they do not contain ES2015+ module syntax (export = is not valid in js) _and_ do not have an __esModule marker + return !file.externalModuleIndicator && !resolveExportByName(moduleSymbol, ts.escapeLeadingUnderscores("__esModule"), dontResolveAlias); + } + function getTargetOfImportClause(node, dontResolveAlias) { + var moduleSymbol = resolveExternalModuleName(node, node.parent.moduleSpecifier); + if (moduleSymbol) { + var exportDefaultSymbol = void 0; + if (ts.isShorthandAmbientModuleSymbol(moduleSymbol)) { + exportDefaultSymbol = moduleSymbol; + } + else { + exportDefaultSymbol = resolveExportByName(moduleSymbol, "default" /* Default */, dontResolveAlias); + } + var file = ts.find(moduleSymbol.declarations, ts.isSourceFile); + var hasSyntheticDefault = canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias); + if (!exportDefaultSymbol && !hasSyntheticDefault) { + error(node.name, ts.Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol)); + } + else if (hasSyntheticDefault) { + // per emit behavior, a synthetic default overrides a "real" .default member if `__esModule` is not present + return resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias); + } + return exportDefaultSymbol; + } + } + function getTargetOfNamespaceImport(node, dontResolveAlias) { + var moduleSpecifier = node.parent.parent.moduleSpecifier; + return resolveESModuleSymbol(resolveExternalModuleName(node, moduleSpecifier), moduleSpecifier, dontResolveAlias); + } + // This function creates a synthetic symbol that combines the value side of one symbol with the + // type/namespace side of another symbol. Consider this example: + // + // declare module graphics { + // interface Point { + // x: number; + // y: number; + // } + // } + // declare var graphics: { + // Point: new (x: number, y: number) => graphics.Point; + // } + // declare module "graphics" { + // export = graphics; + // } + // + // An 'import { Point } from "graphics"' needs to create a symbol that combines the value side 'Point' + // property with the type/namespace side interface 'Point'. + function combineValueAndTypeSymbols(valueSymbol, typeSymbol) { + if (valueSymbol === unknownSymbol && typeSymbol === unknownSymbol) { + return unknownSymbol; + } + if (valueSymbol.flags & (67897832 /* Type */ | 1920 /* Namespace */)) { + return valueSymbol; + } + var result = createSymbol(valueSymbol.flags | typeSymbol.flags, valueSymbol.escapedName); + result.declarations = ts.deduplicate(ts.concatenate(valueSymbol.declarations, typeSymbol.declarations), ts.equateValues); + result.parent = valueSymbol.parent || typeSymbol.parent; + if (valueSymbol.valueDeclaration) + result.valueDeclaration = valueSymbol.valueDeclaration; + if (typeSymbol.members) + result.members = typeSymbol.members; + if (valueSymbol.exports) + result.exports = valueSymbol.exports; + return result; + } + function getExportOfModule(symbol, name, dontResolveAlias) { + if (symbol.flags & 1536 /* Module */) { + return resolveSymbol(getExportsOfSymbol(symbol).get(name), dontResolveAlias); + } + } + function getPropertyOfVariable(symbol, name) { + if (symbol.flags & 3 /* Variable */) { + var typeAnnotation = symbol.valueDeclaration.type; + if (typeAnnotation) { + return resolveSymbol(getPropertyOfType(getTypeFromTypeNode(typeAnnotation), name)); + } + } + } + function getExternalModuleMember(node, specifier, dontResolveAlias) { + if (dontResolveAlias === void 0) { dontResolveAlias = false; } + var moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier); // TODO: GH#18217 + var targetSymbol = resolveESModuleSymbol(moduleSymbol, node.moduleSpecifier, dontResolveAlias); + if (targetSymbol) { + var name = specifier.propertyName || specifier.name; + if (name.escapedText) { + if (ts.isShorthandAmbientModuleSymbol(moduleSymbol)) { + return moduleSymbol; + } + var symbolFromVariable = void 0; + // First check if module was specified with "export=". If so, get the member from the resolved type + if (moduleSymbol && moduleSymbol.exports && moduleSymbol.exports.get("export=" /* ExportEquals */)) { + symbolFromVariable = getPropertyOfType(getTypeOfSymbol(targetSymbol), name.escapedText); + } + else { + symbolFromVariable = getPropertyOfVariable(targetSymbol, name.escapedText); + } + // if symbolFromVariable is export - get its final target + symbolFromVariable = resolveSymbol(symbolFromVariable, dontResolveAlias); + var symbolFromModule = getExportOfModule(targetSymbol, name.escapedText, dontResolveAlias); + // If the export member we're looking for is default, and there is no real default but allowSyntheticDefaultImports is on, return the entire module as the default + if (!symbolFromModule && allowSyntheticDefaultImports && name.escapedText === "default" /* Default */) { + symbolFromModule = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias); + } + var symbol = symbolFromModule && symbolFromVariable && symbolFromModule !== symbolFromVariable ? + combineValueAndTypeSymbols(symbolFromVariable, symbolFromModule) : + symbolFromModule || symbolFromVariable; + if (!symbol) { + var moduleName = getFullyQualifiedName(moduleSymbol, node); + var declarationName = ts.declarationNameToString(name); + var suggestion = getSuggestedSymbolForNonexistentModule(name, targetSymbol); + if (suggestion !== undefined) { + var suggestionName = symbolToString(suggestion); + var diagnostic = error(name, ts.Diagnostics.Module_0_has_no_exported_member_1_Did_you_mean_2, moduleName, declarationName, suggestionName); + if (suggestion.valueDeclaration) { + addRelatedInfo(diagnostic, ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestionName)); + } + } + else { + error(name, ts.Diagnostics.Module_0_has_no_exported_member_1, moduleName, declarationName); + } + } + return symbol; + } + } + } + function getTargetOfImportSpecifier(node, dontResolveAlias) { + return getExternalModuleMember(node.parent.parent.parent, node, dontResolveAlias); + } + function getTargetOfNamespaceExportDeclaration(node, dontResolveAlias) { + return resolveExternalModuleSymbol(node.parent.symbol, dontResolveAlias); + } + function getTargetOfExportSpecifier(node, meaning, dontResolveAlias) { + return node.parent.parent.moduleSpecifier ? + getExternalModuleMember(node.parent.parent, node, dontResolveAlias) : + resolveEntityName(node.propertyName || node.name, meaning, /*ignoreErrors*/ false, dontResolveAlias); + } + function getTargetOfExportAssignment(node, dontResolveAlias) { + var expression = (ts.isExportAssignment(node) ? node.expression : node.right); + if (ts.isClassExpression(expression)) { + return checkExpression(expression).symbol; + } + var aliasLike = resolveEntityName(expression, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ true, dontResolveAlias); + if (aliasLike) { + return aliasLike; + } + checkExpression(expression); + return getNodeLinks(expression).resolvedSymbol; + } + function getTargetOfAliasDeclaration(node, dontRecursivelyResolve) { + if (dontRecursivelyResolve === void 0) { dontRecursivelyResolve = false; } + switch (node.kind) { + case 248 /* ImportEqualsDeclaration */: + return getTargetOfImportEqualsDeclaration(node, dontRecursivelyResolve); + case 250 /* ImportClause */: + return getTargetOfImportClause(node, dontRecursivelyResolve); + case 251 /* NamespaceImport */: + return getTargetOfNamespaceImport(node, dontRecursivelyResolve); + case 253 /* ImportSpecifier */: + return getTargetOfImportSpecifier(node, dontRecursivelyResolve); + case 257 /* ExportSpecifier */: + return getTargetOfExportSpecifier(node, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */, dontRecursivelyResolve); + case 254 /* ExportAssignment */: + case 204 /* BinaryExpression */: + return getTargetOfExportAssignment(node, dontRecursivelyResolve); + case 247 /* NamespaceExportDeclaration */: + return getTargetOfNamespaceExportDeclaration(node, dontRecursivelyResolve); + default: + return ts.Debug.fail(); + } + } + /** + * Indicates that a symbol is an alias that does not merge with a local declaration. + * OR Is a JSContainer which may merge an alias with a local declaration + */ + function isNonLocalAlias(symbol, excludes) { + if (excludes === void 0) { excludes = 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */; } + if (!symbol) + return false; + return (symbol.flags & (2097152 /* Alias */ | excludes)) === 2097152 /* Alias */ || !!(symbol.flags & 2097152 /* Alias */ && symbol.flags & 67108864 /* Assignment */); + } + function resolveSymbol(symbol, dontResolveAlias) { + return !dontResolveAlias && isNonLocalAlias(symbol) ? resolveAlias(symbol) : symbol; + } + function resolveAlias(symbol) { + ts.Debug.assert((symbol.flags & 2097152 /* Alias */) !== 0, "Should only get Alias here."); + var links = getSymbolLinks(symbol); + if (!links.target) { + links.target = resolvingSymbol; + var node = getDeclarationOfAliasSymbol(symbol); + if (!node) + return ts.Debug.fail(); + var target = getTargetOfAliasDeclaration(node); + if (links.target === resolvingSymbol) { + links.target = target || unknownSymbol; + } + else { + error(node, ts.Diagnostics.Circular_definition_of_import_alias_0, symbolToString(symbol)); + } + } + else if (links.target === resolvingSymbol) { + links.target = unknownSymbol; + } + return links.target; + } + function markExportAsReferenced(node) { + var symbol = getSymbolOfNode(node); + var target = resolveAlias(symbol); + if (target) { + var markAlias = target === unknownSymbol || + ((target.flags & 67220415 /* Value */) && !isConstEnumOrConstEnumOnlyModule(target)); + if (markAlias) { + markAliasSymbolAsReferenced(symbol); + } + } + } + // When an alias symbol is referenced, we need to mark the entity it references as referenced and in turn repeat that until + // we reach a non-alias or an exported entity (which is always considered referenced). We do this by checking the target of + // the alias as an expression (which recursively takes us back here if the target references another alias). + function markAliasSymbolAsReferenced(symbol) { + var links = getSymbolLinks(symbol); + if (!links.referenced) { + links.referenced = true; + var node = getDeclarationOfAliasSymbol(symbol); + if (!node) + return ts.Debug.fail(); + if (node.kind === 254 /* ExportAssignment */) { + // export default + checkExpressionCached(node.expression); + } + else if (node.kind === 257 /* ExportSpecifier */) { + // export { } or export { as foo } + checkExpressionCached(node.propertyName || node.name); + } + else if (ts.isInternalModuleImportEqualsDeclaration(node)) { + // import foo = + checkExpressionCached(node.moduleReference); + } + } + } + // This function is only for imports with entity names + function getSymbolOfPartOfRightHandSideOfImportEquals(entityName, dontResolveAlias) { + // There are three things we might try to look for. In the following examples, + // the search term is enclosed in |...|: + // + // import a = |b|; // Namespace + // import a = |b.c|; // Value, type, namespace + // import a = |b.c|.d; // Namespace + if (entityName.kind === 72 /* Identifier */ && ts.isRightSideOfQualifiedNameOrPropertyAccess(entityName)) { + entityName = entityName.parent; + } + // Check for case 1 and 3 in the above example + if (entityName.kind === 72 /* Identifier */ || entityName.parent.kind === 148 /* QualifiedName */) { + return resolveEntityName(entityName, 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); + } + else { + // Case 2 in above example + // entityName.kind could be a QualifiedName or a Missing identifier + ts.Debug.assert(entityName.parent.kind === 248 /* ImportEqualsDeclaration */); + return resolveEntityName(entityName, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); + } + } + function getFullyQualifiedName(symbol, containingLocation) { + return symbol.parent ? getFullyQualifiedName(symbol.parent, containingLocation) + "." + symbolToString(symbol) : symbolToString(symbol, containingLocation, /*meaning*/ undefined, 16 /* DoNotIncludeSymbolChain */ | 4 /* AllowAnyNodeKind */); + } + /** + * Resolves a qualified name and any involved aliases. + */ + function resolveEntityName(name, meaning, ignoreErrors, dontResolveAlias, location) { + if (ts.nodeIsMissing(name)) { + return undefined; + } + var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJSFile(name) ? meaning & 67220415 /* Value */ : 0); + var symbol; + if (name.kind === 72 /* Identifier */) { + var message = meaning === namespaceMeaning ? ts.Diagnostics.Cannot_find_namespace_0 : getCannotFindNameDiagnosticForName(getFirstIdentifier(name).escapedText); + var symbolFromJSPrototype = ts.isInJSFile(name) ? resolveEntityNameFromAssignmentDeclaration(name, meaning) : undefined; + symbol = resolveName(location || name, name.escapedText, meaning, ignoreErrors || symbolFromJSPrototype ? undefined : message, name, /*isUse*/ true); + if (!symbol) { + return symbolFromJSPrototype; + } + } + else if (name.kind === 148 /* QualifiedName */ || name.kind === 189 /* PropertyAccessExpression */) { + var left = name.kind === 148 /* QualifiedName */ ? name.left : name.expression; + var right = name.kind === 148 /* QualifiedName */ ? name.right : name.name; + var namespace = resolveEntityName(left, namespaceMeaning, ignoreErrors, /*dontResolveAlias*/ false, location); + if (!namespace || ts.nodeIsMissing(right)) { + return undefined; + } + else if (namespace === unknownSymbol) { + return namespace; + } + if (ts.isInJSFile(name)) { + if (namespace.valueDeclaration && + ts.isVariableDeclaration(namespace.valueDeclaration) && + namespace.valueDeclaration.initializer && + isCommonJsRequire(namespace.valueDeclaration.initializer)) { + var moduleName = namespace.valueDeclaration.initializer.arguments[0]; + var moduleSym = resolveExternalModuleName(moduleName, moduleName); + if (moduleSym) { + var resolvedModuleSymbol = resolveExternalModuleSymbol(moduleSym); + if (resolvedModuleSymbol) { + namespace = resolvedModuleSymbol; + } + } + } + } + symbol = getSymbol(getExportsOfSymbol(namespace), right.escapedText, meaning); + if (!symbol) { + if (!ignoreErrors) { + error(right, ts.Diagnostics.Namespace_0_has_no_exported_member_1, getFullyQualifiedName(namespace), ts.declarationNameToString(right)); + } + return undefined; + } + } + else { + throw ts.Debug.assertNever(name, "Unknown entity name kind."); + } + ts.Debug.assert((ts.getCheckFlags(symbol) & 1 /* Instantiated */) === 0, "Should never get an instantiated symbol here."); + return (symbol.flags & meaning) || dontResolveAlias ? symbol : resolveAlias(symbol); + } + /** + * 1. For prototype-property methods like `A.prototype.m = function () ...`, try to resolve names in the scope of `A` too. + * Note that prototype-property assignment to locations outside the current file (eg globals) doesn't work, so + * name resolution won't work either. + * 2. For property assignments like `{ x: function f () { } }`, try to resolve names in the scope of `f` too. + */ + function resolveEntityNameFromAssignmentDeclaration(name, meaning) { + if (isJSDocTypeReference(name.parent)) { + var secondaryLocation = getAssignmentDeclarationLocation(name.parent); + if (secondaryLocation) { + return resolveName(secondaryLocation, name.escapedText, meaning, /*nameNotFoundMessage*/ undefined, name, /*isUse*/ true); + } + } + } + function getAssignmentDeclarationLocation(node) { + var typeAlias = ts.findAncestor(node, function (node) { return !(ts.isJSDocNode(node) || node.flags & 2097152 /* JSDoc */) ? "quit" : ts.isJSDocTypeAlias(node); }); + if (typeAlias) { + return; + } + var host = ts.getJSDocHost(node); + if (ts.isExpressionStatement(host) && + ts.isBinaryExpression(host.expression) && + ts.getAssignmentDeclarationKind(host.expression) === 3 /* PrototypeProperty */) { + // X.prototype.m = /** @param {K} p */ function () { } <-- look for K on X's declaration + var symbol = getSymbolOfNode(host.expression.left); + if (symbol) { + return getDeclarationOfJSPrototypeContainer(symbol); + } + } + if ((ts.isObjectLiteralMethod(host) || ts.isPropertyAssignment(host)) && + ts.isBinaryExpression(host.parent.parent) && + ts.getAssignmentDeclarationKind(host.parent.parent) === 6 /* Prototype */) { + // X.prototype = { /** @param {K} p */m() { } } <-- look for K on X's declaration + var symbol = getSymbolOfNode(host.parent.parent.left); + if (symbol) { + return getDeclarationOfJSPrototypeContainer(symbol); + } + } + var sig = ts.getHostSignatureFromJSDocHost(host); + if (sig) { + var symbol = getSymbolOfNode(sig); + return symbol && symbol.valueDeclaration; + } + } + function getDeclarationOfJSPrototypeContainer(symbol) { + var decl = symbol.parent.valueDeclaration; + if (!decl) { + return undefined; + } + var initializer = ts.isAssignmentDeclaration(decl) ? ts.getAssignedExpandoInitializer(decl) : + ts.hasOnlyExpressionInitializer(decl) ? ts.getDeclaredExpandoInitializer(decl) : + undefined; + return initializer || decl; + } + function resolveExternalModuleName(location, moduleReferenceExpression, ignoreErrors) { + return resolveExternalModuleNameWorker(location, moduleReferenceExpression, ignoreErrors ? undefined : ts.Diagnostics.Cannot_find_module_0); + } + function resolveExternalModuleNameWorker(location, moduleReferenceExpression, moduleNotFoundError, isForAugmentation) { + if (isForAugmentation === void 0) { isForAugmentation = false; } + return ts.isStringLiteralLike(moduleReferenceExpression) + ? resolveExternalModule(location, moduleReferenceExpression.text, moduleNotFoundError, moduleReferenceExpression, isForAugmentation) + : undefined; + } + function resolveExternalModule(location, moduleReference, moduleNotFoundError, errorNode, isForAugmentation) { + if (isForAugmentation === void 0) { isForAugmentation = false; } + if (moduleReference === undefined) { + return; + } + if (ts.startsWith(moduleReference, "@types/")) { + var diag = ts.Diagnostics.Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1; + var withoutAtTypePrefix = ts.removePrefix(moduleReference, "@types/"); + error(errorNode, diag, withoutAtTypePrefix, moduleReference); + } + var ambientModule = tryFindAmbientModule(moduleReference, /*withAugmentations*/ true); + if (ambientModule) { + return ambientModule; + } + var currentSourceFile = ts.getSourceFileOfNode(location); + var resolvedModule = ts.getResolvedModule(currentSourceFile, moduleReference); // TODO: GH#18217 + var resolutionDiagnostic = resolvedModule && ts.getResolutionDiagnostic(compilerOptions, resolvedModule); + var sourceFile = resolvedModule && !resolutionDiagnostic && host.getSourceFile(resolvedModule.resolvedFileName); + if (sourceFile) { + if (sourceFile.symbol) { + if (resolvedModule.isExternalLibraryImport && !ts.resolutionExtensionIsTSOrJson(resolvedModule.extension)) { + errorOnImplicitAnyModule(/*isError*/ false, errorNode, resolvedModule, moduleReference); + } + // merged symbol is module declaration symbol combined with all augmentations + return getMergedSymbol(sourceFile.symbol); + } + if (moduleNotFoundError) { + // report errors only if it was requested + error(errorNode, ts.Diagnostics.File_0_is_not_a_module, sourceFile.fileName); + } + return undefined; + } + if (patternAmbientModules) { + var pattern = ts.findBestPatternMatch(patternAmbientModules, function (_) { return _.pattern; }, moduleReference); + if (pattern) { + return getMergedSymbol(pattern.symbol); + } + } + // May be an untyped module. If so, ignore resolutionDiagnostic. + if (resolvedModule && !ts.resolutionExtensionIsTSOrJson(resolvedModule.extension) && resolutionDiagnostic === undefined || resolutionDiagnostic === ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type) { + if (isForAugmentation) { + var diag = ts.Diagnostics.Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented; + error(errorNode, diag, moduleReference, resolvedModule.resolvedFileName); + } + else { + errorOnImplicitAnyModule(/*isError*/ noImplicitAny && !!moduleNotFoundError, errorNode, resolvedModule, moduleReference); + } + // Failed imports and untyped modules are both treated in an untyped manner; only difference is whether we give a diagnostic first. + return undefined; + } + if (moduleNotFoundError) { + // For relative paths, see if this was possibly a projectReference redirect + if (ts.pathIsRelative(moduleReference)) { + var sourceFile_1 = ts.getSourceFileOfNode(location); + var redirects = sourceFile_1.redirectedReferences; + if (redirects) { + var normalizedTargetPath = ts.getNormalizedAbsolutePath(moduleReference, ts.getDirectoryPath(sourceFile_1.fileName)); + for (var _i = 0, _a = [".ts" /* Ts */, ".tsx" /* Tsx */]; _i < _a.length; _i++) { + var ext = _a[_i]; + var probePath = normalizedTargetPath + ext; + if (redirects.indexOf(probePath) >= 0) { + error(errorNode, ts.Diagnostics.Output_file_0_has_not_been_built_from_source_file_1, moduleReference, probePath); + return undefined; + } + } + } + } + if (resolutionDiagnostic) { + error(errorNode, resolutionDiagnostic, moduleReference, resolvedModule.resolvedFileName); + } + else { + var tsExtension = ts.tryExtractTSExtension(moduleReference); + if (tsExtension) { + var diag = ts.Diagnostics.An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead; + error(errorNode, diag, tsExtension, ts.removeExtension(moduleReference, tsExtension)); + } + else if (!compilerOptions.resolveJsonModule && + ts.fileExtensionIs(moduleReference, ".json" /* Json */) && + ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs && + ts.hasJsonModuleEmitEnabled(compilerOptions)) { + error(errorNode, ts.Diagnostics.Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension, moduleReference); + } + else { + error(errorNode, moduleNotFoundError, moduleReference); + } + } + } + return undefined; + } + function errorOnImplicitAnyModule(isError, errorNode, _a, moduleReference) { + var packageId = _a.packageId, resolvedFileName = _a.resolvedFileName; + var errorInfo = !ts.isExternalModuleNameRelative(moduleReference) && packageId + ? typesPackageExists(packageId.name) + ? ts.chainDiagnosticMessages( + /*details*/ undefined, ts.Diagnostics.If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1, packageId.name, ts.mangleScopedPackageName(packageId.name)) + : ts.chainDiagnosticMessages( + /*details*/ undefined, ts.Diagnostics.Try_npm_install_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, moduleReference, ts.mangleScopedPackageName(packageId.name)) + : undefined; + errorOrSuggestion(isError, errorNode, ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type, moduleReference, resolvedFileName)); + } + function typesPackageExists(packageName) { + return getPackagesSet().has(ts.getTypesPackageName(packageName)); + } + function resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) { + if (moduleSymbol) { + var exportEquals = resolveSymbol(moduleSymbol.exports.get("export=" /* ExportEquals */), dontResolveAlias); + var exported = getCommonJsExportEquals(exportEquals, moduleSymbol); + return getMergedSymbol(exported) || moduleSymbol; + } + return undefined; + } + function getCommonJsExportEquals(exported, moduleSymbol) { + if (!exported || exported === unknownSymbol || exported === moduleSymbol || moduleSymbol.exports.size === 1 || exported.flags & 2097152 /* Alias */) { + return exported; + } + var merged = cloneSymbol(exported); + if (merged.exports === undefined) { + merged.flags = merged.flags | 512 /* ValueModule */; + merged.exports = ts.createSymbolTable(); + } + moduleSymbol.exports.forEach(function (s, name) { + if (name === "export=" /* ExportEquals */) + return; + merged.exports.set(name, merged.exports.has(name) ? mergeSymbol(merged.exports.get(name), s) : s); + }); + return merged; + } + // An external module with an 'export =' declaration may be referenced as an ES6 module provided the 'export =' + // references a symbol that is at least declared as a module or a variable. The target of the 'export =' may + // combine other declarations with the module or variable (e.g. a class/module, function/module, interface/variable). + function resolveESModuleSymbol(moduleSymbol, referencingLocation, dontResolveAlias) { + var symbol = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias); + if (!dontResolveAlias && symbol) { + if (!(symbol.flags & (1536 /* Module */ | 3 /* Variable */)) && !ts.getDeclarationOfKind(symbol, 279 /* SourceFile */)) { + error(referencingLocation, ts.Diagnostics.Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct, symbolToString(moduleSymbol)); + return symbol; + } + if (compilerOptions.esModuleInterop) { + var referenceParent = referencingLocation.parent; + if ((ts.isImportDeclaration(referenceParent) && ts.getNamespaceDeclarationNode(referenceParent)) || + ts.isImportCall(referenceParent)) { + var type = getTypeOfSymbol(symbol); + var sigs = getSignaturesOfStructuredType(type, 0 /* Call */); + if (!sigs || !sigs.length) { + sigs = getSignaturesOfStructuredType(type, 1 /* Construct */); + } + if (sigs && sigs.length) { + var moduleType = getTypeWithSyntheticDefaultImportType(type, symbol, moduleSymbol); + // Create a new symbol which has the module's type less the call and construct signatures + var result = createSymbol(symbol.flags, symbol.escapedName); + result.declarations = symbol.declarations ? symbol.declarations.slice() : []; + result.parent = symbol.parent; + result.target = symbol; + result.originatingImport = referenceParent; + if (symbol.valueDeclaration) + result.valueDeclaration = symbol.valueDeclaration; + if (symbol.constEnumOnlyModule) + result.constEnumOnlyModule = true; + if (symbol.members) + result.members = ts.cloneMap(symbol.members); + if (symbol.exports) + result.exports = ts.cloneMap(symbol.exports); + var resolvedModuleType = resolveStructuredTypeMembers(moduleType); // Should already be resolved from the signature checks above + result.type = createAnonymousType(result, resolvedModuleType.members, ts.emptyArray, ts.emptyArray, resolvedModuleType.stringIndexInfo, resolvedModuleType.numberIndexInfo); + return result; + } + } + } + } + return symbol; + } + function hasExportAssignmentSymbol(moduleSymbol) { + return moduleSymbol.exports.get("export=" /* ExportEquals */) !== undefined; + } + function getExportsOfModuleAsArray(moduleSymbol) { + return symbolsToArray(getExportsOfModule(moduleSymbol)); + } + function getExportsAndPropertiesOfModule(moduleSymbol) { + var exports = getExportsOfModuleAsArray(moduleSymbol); + var exportEquals = resolveExternalModuleSymbol(moduleSymbol); + if (exportEquals !== moduleSymbol) { + ts.addRange(exports, getPropertiesOfType(getTypeOfSymbol(exportEquals))); + } + return exports; + } + function tryGetMemberInModuleExports(memberName, moduleSymbol) { + var symbolTable = getExportsOfModule(moduleSymbol); + if (symbolTable) { + return symbolTable.get(memberName); + } + } + function tryGetMemberInModuleExportsAndProperties(memberName, moduleSymbol) { + var symbol = tryGetMemberInModuleExports(memberName, moduleSymbol); + if (symbol) { + return symbol; + } + var exportEquals = resolveExternalModuleSymbol(moduleSymbol); + if (exportEquals === moduleSymbol) { + return undefined; + } + var type = getTypeOfSymbol(exportEquals); + return type.flags & 131068 /* Primitive */ ? undefined : getPropertyOfType(type, memberName); + } + function getExportsOfSymbol(symbol) { + return symbol.flags & 32 /* Class */ ? getResolvedMembersOrExportsOfSymbol(symbol, "resolvedExports" /* resolvedExports */) : + symbol.flags & 1536 /* Module */ ? getExportsOfModule(symbol) : + symbol.exports || emptySymbols; + } + function getExportsOfModule(moduleSymbol) { + var links = getSymbolLinks(moduleSymbol); + return links.resolvedExports || (links.resolvedExports = getExportsOfModuleWorker(moduleSymbol)); + } + /** + * Extends one symbol table with another while collecting information on name collisions for error message generation into the `lookupTable` argument + * Not passing `lookupTable` and `exportNode` disables this collection, and just extends the tables + */ + function extendExportSymbols(target, source, lookupTable, exportNode) { + if (!source) + return; + source.forEach(function (sourceSymbol, id) { + if (id === "default" /* Default */) + return; + var targetSymbol = target.get(id); + if (!targetSymbol) { + target.set(id, sourceSymbol); + if (lookupTable && exportNode) { + lookupTable.set(id, { + specifierText: ts.getTextOfNode(exportNode.moduleSpecifier) + }); + } + } + else if (lookupTable && exportNode && targetSymbol && resolveSymbol(targetSymbol) !== resolveSymbol(sourceSymbol)) { + var collisionTracker = lookupTable.get(id); + if (!collisionTracker.exportsWithDuplicate) { + collisionTracker.exportsWithDuplicate = [exportNode]; + } + else { + collisionTracker.exportsWithDuplicate.push(exportNode); + } + } + }); + } + function getExportsOfModuleWorker(moduleSymbol) { + var visitedSymbols = []; + // A module defined by an 'export=' consists of one export that needs to be resolved + moduleSymbol = resolveExternalModuleSymbol(moduleSymbol); + return visit(moduleSymbol) || emptySymbols; + // The ES6 spec permits export * declarations in a module to circularly reference the module itself. For example, + // module 'a' can 'export * from "b"' and 'b' can 'export * from "a"' without error. + function visit(symbol) { + if (!(symbol && symbol.exports && ts.pushIfUnique(visitedSymbols, symbol))) { + return; + } + var symbols = ts.cloneMap(symbol.exports); + // All export * declarations are collected in an __export symbol by the binder + var exportStars = symbol.exports.get("__export" /* ExportStar */); + if (exportStars) { + var nestedSymbols = ts.createSymbolTable(); + var lookupTable_1 = ts.createMap(); + for (var _i = 0, _a = exportStars.declarations; _i < _a.length; _i++) { + var node = _a[_i]; + var resolvedModule = resolveExternalModuleName(node, node.moduleSpecifier); + var exportedSymbols = visit(resolvedModule); + extendExportSymbols(nestedSymbols, exportedSymbols, lookupTable_1, node); + } + lookupTable_1.forEach(function (_a, id) { + var exportsWithDuplicate = _a.exportsWithDuplicate; + // It's not an error if the file with multiple `export *`s with duplicate names exports a member with that name itself + if (id === "export=" || !(exportsWithDuplicate && exportsWithDuplicate.length) || symbols.has(id)) { + return; + } + for (var _i = 0, exportsWithDuplicate_1 = exportsWithDuplicate; _i < exportsWithDuplicate_1.length; _i++) { + var node = exportsWithDuplicate_1[_i]; + diagnostics.add(ts.createDiagnosticForNode(node, ts.Diagnostics.Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambiguity, lookupTable_1.get(id).specifierText, ts.unescapeLeadingUnderscores(id))); + } + }); + extendExportSymbols(symbols, nestedSymbols); + } + return symbols; + } + } + function getMergedSymbol(symbol) { + var merged; + return symbol && symbol.mergeId && (merged = mergedSymbols[symbol.mergeId]) ? merged : symbol; + } + function getSymbolOfNode(node) { + return getMergedSymbol(node.symbol && getLateBoundSymbol(node.symbol)); + } + function getParentOfSymbol(symbol) { + return getMergedSymbol(symbol.parent && getLateBoundSymbol(symbol.parent)); + } + function getAlternativeContainingModules(symbol, enclosingDeclaration) { + var containingFile = ts.getSourceFileOfNode(enclosingDeclaration); + var id = "" + getNodeId(containingFile); + var links = getSymbolLinks(symbol); + var results; + if (links.extendedContainersByFile && (results = links.extendedContainersByFile.get(id))) { + return results; + } + if (containingFile && containingFile.imports) { + // Try to make an import using an import already in the enclosing file, if possible + for (var _i = 0, _a = containingFile.imports; _i < _a.length; _i++) { + var importRef = _a[_i]; + if (ts.nodeIsSynthesized(importRef)) + continue; // Synthetic names can't be resolved by `resolveExternalModuleName` - they'll cause a debug assert if they error + var resolvedModule = resolveExternalModuleName(enclosingDeclaration, importRef, /*ignoreErrors*/ true); + if (!resolvedModule) + continue; + var ref = getAliasForSymbolInContainer(resolvedModule, symbol); + if (!ref) + continue; + results = ts.append(results, resolvedModule); + } + if (ts.length(results)) { + (links.extendedContainersByFile || (links.extendedContainersByFile = ts.createMap())).set(id, results); + return results; + } + } + if (links.extendedContainers) { + return links.extendedContainers; + } + // No results from files already being imported by this file - expand search (expensive, but not location-specific, so cached) + var otherFiles = host.getSourceFiles(); + for (var _b = 0, otherFiles_1 = otherFiles; _b < otherFiles_1.length; _b++) { + var file = otherFiles_1[_b]; + if (!ts.isExternalModule(file)) + continue; + var sym = getSymbolOfNode(file); + var ref = getAliasForSymbolInContainer(sym, symbol); + if (!ref) + continue; + results = ts.append(results, sym); + } + return links.extendedContainers = results || ts.emptyArray; + } + /** + * Attempts to find the symbol corresponding to the container a symbol is in - usually this + * is just its' `.parent`, but for locals, this value is `undefined` + */ + function getContainersOfSymbol(symbol, enclosingDeclaration) { + var container = getParentOfSymbol(symbol); + if (container) { + var additionalContainers = ts.mapDefined(container.declarations, fileSymbolIfFileSymbolExportEqualsContainer); + var reexportContainers = enclosingDeclaration && getAlternativeContainingModules(symbol, enclosingDeclaration); + if (enclosingDeclaration && getAccessibleSymbolChain(container, enclosingDeclaration, 1920 /* Namespace */, /*externalOnly*/ false)) { + return ts.concatenate(ts.concatenate([container], additionalContainers), reexportContainers); // This order expresses a preference for the real container if it is in scope + } + var res = ts.append(additionalContainers, container); + return ts.concatenate(res, reexportContainers); + } + var candidates = ts.mapDefined(symbol.declarations, function (d) { return !ts.isAmbientModule(d) && d.parent && hasNonGlobalAugmentationExternalModuleSymbol(d.parent) ? getSymbolOfNode(d.parent) : undefined; }); + if (!ts.length(candidates)) { + return undefined; + } + return ts.mapDefined(candidates, function (candidate) { return getAliasForSymbolInContainer(candidate, symbol) ? candidate : undefined; }); + function fileSymbolIfFileSymbolExportEqualsContainer(d) { + var fileSymbol = getExternalModuleContainer(d); + var exported = fileSymbol && fileSymbol.exports && fileSymbol.exports.get("export=" /* ExportEquals */); + return resolveSymbol(exported) === resolveSymbol(container) ? fileSymbol : undefined; + } + } + function getAliasForSymbolInContainer(container, symbol) { + if (container === getParentOfSymbol(symbol)) { + // fast path, `symbol` is either already the alias or isn't aliased + return symbol; + } + var exports = getExportsOfSymbol(container); + var quick = exports.get(symbol.escapedName); + if (quick && symbolRefersToTarget(quick)) { + return quick; + } + return ts.forEachEntry(exports, function (exported) { + if (symbolRefersToTarget(exported)) { + return exported; + } + }); + function symbolRefersToTarget(s) { + if (s === symbol || resolveSymbol(s) === symbol || resolveSymbol(s) === resolveSymbol(symbol)) { + return s; + } + } + } + function getExportSymbolOfValueSymbolIfExported(symbol) { + return getMergedSymbol(symbol && (symbol.flags & 1048576 /* ExportValue */) !== 0 ? symbol.exportSymbol : symbol); + } + function symbolIsValue(symbol) { + return !!(symbol.flags & 67220415 /* Value */ || symbol.flags & 2097152 /* Alias */ && resolveAlias(symbol).flags & 67220415 /* Value */); + } + function findConstructorDeclaration(node) { + var members = node.members; + for (var _i = 0, members_2 = members; _i < members_2.length; _i++) { + var member = members_2[_i]; + if (member.kind === 157 /* Constructor */ && ts.nodeIsPresent(member.body)) { + return member; + } + } + } + function createType(flags) { + var result = new Type(checker, flags); + typeCount++; + result.id = typeCount; + return result; + } + function createIntrinsicType(kind, intrinsicName) { + var type = createType(kind); + type.intrinsicName = intrinsicName; + return type; + } + function createBooleanType(trueFalseTypes) { + var type = getUnionType(trueFalseTypes); + type.flags |= 16 /* Boolean */; + type.intrinsicName = "boolean"; + return type; + } + function createObjectType(objectFlags, symbol) { + var type = createType(524288 /* Object */); + type.objectFlags = objectFlags; + type.symbol = symbol; + type.members = undefined; + type.properties = undefined; + type.callSignatures = undefined; + type.constructSignatures = undefined; + type.stringIndexInfo = undefined; + type.numberIndexInfo = undefined; + return type; + } + function createTypeofType() { + return getUnionType(ts.arrayFrom(typeofEQFacts.keys(), getLiteralType)); + } + // A reserved member name starts with two underscores, but the third character cannot be an underscore + // or the @ symbol. A third underscore indicates an escaped form of an identifer that started + // with at least two underscores. The @ character indicates that the name is denoted by a well known ES + // Symbol instance. + function isReservedMemberName(name) { + return name.charCodeAt(0) === 95 /* _ */ && + name.charCodeAt(1) === 95 /* _ */ && + name.charCodeAt(2) !== 95 /* _ */ && + name.charCodeAt(2) !== 64 /* at */; + } + function getNamedMembers(members) { + var result; + members.forEach(function (symbol, id) { + if (!isReservedMemberName(id) && symbolIsValue(symbol)) { + (result || (result = [])).push(symbol); + } + }); + return result || ts.emptyArray; + } + function setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo) { + type.members = members; + type.properties = members === emptySymbols ? ts.emptyArray : getNamedMembers(members); + type.callSignatures = callSignatures; + type.constructSignatures = constructSignatures; + type.stringIndexInfo = stringIndexInfo; + type.numberIndexInfo = numberIndexInfo; + return type; + } + function createAnonymousType(symbol, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo) { + return setStructuredTypeMembers(createObjectType(16 /* Anonymous */, symbol), members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + } + function forEachSymbolTableInScope(enclosingDeclaration, callback) { + var result; + for (var location = enclosingDeclaration; location; location = location.parent) { + // Locals of a source file are not in scope (because they get merged into the global symbol table) + if (location.locals && !isGlobalSourceFile(location)) { + if (result = callback(location.locals)) { + return result; + } + } + switch (location.kind) { + case 279 /* SourceFile */: + if (!ts.isExternalOrCommonJsModule(location)) { + break; + } + // falls through + case 244 /* ModuleDeclaration */: + if (result = callback(getSymbolOfNode(location).exports)) { + return result; + } + break; + } + } + return callback(globals); + } + function getQualifiedLeftMeaning(rightMeaning) { + // If we are looking in value space, the parent meaning is value, other wise it is namespace + return rightMeaning === 67220415 /* Value */ ? 67220415 /* Value */ : 1920 /* Namespace */; + } + function getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, useOnlyExternalAliasing, visitedSymbolTablesMap) { + if (visitedSymbolTablesMap === void 0) { visitedSymbolTablesMap = ts.createMap(); } + if (!(symbol && !isPropertyOrMethodDeclarationSymbol(symbol))) { + return undefined; + } + var id = "" + getSymbolId(symbol); + var visitedSymbolTables = visitedSymbolTablesMap.get(id); + if (!visitedSymbolTables) { + visitedSymbolTablesMap.set(id, visitedSymbolTables = []); + } + return forEachSymbolTableInScope(enclosingDeclaration, getAccessibleSymbolChainFromSymbolTable); + /** + * @param {ignoreQualification} boolean Set when a symbol is being looked for through the exports of another symbol (meaning we have a route to qualify it already) + */ + function getAccessibleSymbolChainFromSymbolTable(symbols, ignoreQualification) { + if (!ts.pushIfUnique(visitedSymbolTables, symbols)) { + return undefined; + } + var result = trySymbolTable(symbols, ignoreQualification); + visitedSymbolTables.pop(); + return result; + } + function canQualifySymbol(symbolFromSymbolTable, meaning) { + // If the symbol is equivalent and doesn't need further qualification, this symbol is accessible + return !needsQualification(symbolFromSymbolTable, enclosingDeclaration, meaning) || + // If symbol needs qualification, make sure that parent is accessible, if it is then this symbol is accessible too + !!getAccessibleSymbolChain(symbolFromSymbolTable.parent, enclosingDeclaration, getQualifiedLeftMeaning(meaning), useOnlyExternalAliasing, visitedSymbolTablesMap); + } + function isAccessible(symbolFromSymbolTable, resolvedAliasSymbol, ignoreQualification) { + return symbol === (resolvedAliasSymbol || symbolFromSymbolTable) && + // if the symbolFromSymbolTable is not external module (it could be if it was determined as ambient external module and would be in globals table) + // and if symbolFromSymbolTable or alias resolution matches the symbol, + // check the symbol can be qualified, it is only then this symbol is accessible + !ts.some(symbolFromSymbolTable.declarations, hasNonGlobalAugmentationExternalModuleSymbol) && + (ignoreQualification || canQualifySymbol(symbolFromSymbolTable, meaning)); + } + function trySymbolTable(symbols, ignoreQualification) { + // If symbol is directly available by its name in the symbol table + if (isAccessible(symbols.get(symbol.escapedName), /*resolvedAliasSymbol*/ undefined, ignoreQualification)) { + return [symbol]; + } + // Check if symbol is any of the alias + return ts.forEachEntry(symbols, function (symbolFromSymbolTable) { + if (symbolFromSymbolTable.flags & 2097152 /* Alias */ + && symbolFromSymbolTable.escapedName !== "export=" /* ExportEquals */ + && symbolFromSymbolTable.escapedName !== "default" /* Default */ + && !(ts.isUMDExportSymbol(symbolFromSymbolTable) && enclosingDeclaration && ts.isExternalModule(ts.getSourceFileOfNode(enclosingDeclaration))) + // If `!useOnlyExternalAliasing`, we can use any type of alias to get the name + && (!useOnlyExternalAliasing || ts.some(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration)) + // While exports are generally considered to be in scope, export-specifier declared symbols are _not_ + // See similar comment in `resolveName` for details + && (ignoreQualification || !ts.getDeclarationOfKind(symbolFromSymbolTable, 257 /* ExportSpecifier */))) { + var resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable); + if (isAccessible(symbolFromSymbolTable, resolvedImportedSymbol, ignoreQualification)) { + return [symbolFromSymbolTable]; + } + // Look in the exported members, if we can find accessibleSymbolChain, symbol is accessible using this chain + // but only if the symbolFromSymbolTable can be qualified + var candidateTable = getExportsOfSymbol(resolvedImportedSymbol); + var accessibleSymbolsFromExports = candidateTable && getAccessibleSymbolChainFromSymbolTable(candidateTable, /*ignoreQualification*/ true); + if (accessibleSymbolsFromExports && canQualifySymbol(symbolFromSymbolTable, getQualifiedLeftMeaning(meaning))) { + return [symbolFromSymbolTable].concat(accessibleSymbolsFromExports); + } + } + if (symbolFromSymbolTable.escapedName === symbol.escapedName && symbolFromSymbolTable.exportSymbol) { + if (isAccessible(getMergedSymbol(symbolFromSymbolTable.exportSymbol), /*aliasSymbol*/ undefined, ignoreQualification)) { + return [symbol]; + } + } + }); + } + } + function needsQualification(symbol, enclosingDeclaration, meaning) { + var qualify = false; + forEachSymbolTableInScope(enclosingDeclaration, function (symbolTable) { + // If symbol of this name is not available in the symbol table we are ok + var symbolFromSymbolTable = getMergedSymbol(symbolTable.get(symbol.escapedName)); + if (!symbolFromSymbolTable) { + // Continue to the next symbol table + return false; + } + // If the symbol with this name is present it should refer to the symbol + if (symbolFromSymbolTable === symbol) { + // No need to qualify + return true; + } + // Qualify if the symbol from symbol table has same meaning as expected + symbolFromSymbolTable = (symbolFromSymbolTable.flags & 2097152 /* Alias */ && !ts.getDeclarationOfKind(symbolFromSymbolTable, 257 /* ExportSpecifier */)) ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable; + if (symbolFromSymbolTable.flags & meaning) { + qualify = true; + return true; + } + // Continue to the next symbol table + return false; + }); + return qualify; + } + function isPropertyOrMethodDeclarationSymbol(symbol) { + if (symbol.declarations && symbol.declarations.length) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + switch (declaration.kind) { + case 154 /* PropertyDeclaration */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + continue; + default: + return false; + } + } + return true; + } + return false; + } + function isTypeSymbolAccessible(typeSymbol, enclosingDeclaration) { + var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67897832 /* Type */, /*shouldComputeAliasesToMakeVisible*/ false); + return access.accessibility === 0 /* Accessible */; + } + function isValueSymbolAccessible(typeSymbol, enclosingDeclaration) { + var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67220415 /* Value */, /*shouldComputeAliasesToMakeVisible*/ false); + return access.accessibility === 0 /* Accessible */; + } + function isAnySymbolAccessible(symbols, enclosingDeclaration, initialSymbol, meaning, shouldComputeAliasesToMakeVisible) { + if (!ts.length(symbols)) + return; + var hadAccessibleChain; + for (var _i = 0, _a = symbols; _i < _a.length; _i++) { + var symbol = _a[_i]; + // Symbol is accessible if it by itself is accessible + var accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, /*useOnlyExternalAliasing*/ false); + if (accessibleSymbolChain) { + hadAccessibleChain = symbol; + var hasAccessibleDeclarations = hasVisibleDeclarations(accessibleSymbolChain[0], shouldComputeAliasesToMakeVisible); + if (hasAccessibleDeclarations) { + return hasAccessibleDeclarations; + } + } + else { + if (ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { + // Any meaning of a module symbol is always accessible via an `import` type + return { + accessibility: 0 /* Accessible */ + }; + } + } + // If we haven't got the accessible symbol, it doesn't mean the symbol is actually inaccessible. + // It could be a qualified symbol and hence verify the path + // e.g.: + // module m { + // export class c { + // } + // } + // const x: typeof m.c + // In the above example when we start with checking if typeof m.c symbol is accessible, + // we are going to see if c can be accessed in scope directly. + // But it can't, hence the accessible is going to be undefined, but that doesn't mean m.c is inaccessible + // It is accessible if the parent m is accessible because then m.c can be accessed through qualification + var containers = getContainersOfSymbol(symbol, enclosingDeclaration); + // If we're trying to reference some object literal in, eg `var a = { x: 1 }`, the symbol for the literal, `__object`, is distinct + // from the symbol of the declaration it is being assigned to. Since we can use the declaration to refer to the literal, however, + // we'd like to make that connection here - potentially causing us to paint the declararation's visibiility, and therefore the literal. + var firstDecl = ts.first(symbol.declarations); + if (!ts.length(containers) && meaning & 67220415 /* Value */ && firstDecl && ts.isObjectLiteralExpression(firstDecl)) { + if (firstDecl.parent && ts.isVariableDeclaration(firstDecl.parent) && firstDecl === firstDecl.parent.initializer) { + containers = [getSymbolOfNode(firstDecl.parent)]; + } + } + var parentResult = isAnySymbolAccessible(containers, enclosingDeclaration, initialSymbol, initialSymbol === symbol ? getQualifiedLeftMeaning(meaning) : meaning, shouldComputeAliasesToMakeVisible); + if (parentResult) { + return parentResult; + } + } + if (hadAccessibleChain) { + return { + accessibility: 1 /* NotAccessible */, + errorSymbolName: symbolToString(initialSymbol, enclosingDeclaration, meaning), + errorModuleName: hadAccessibleChain !== initialSymbol ? symbolToString(hadAccessibleChain, enclosingDeclaration, 1920 /* Namespace */) : undefined, + }; + } + } + /** + * Check if the given symbol in given enclosing declaration is accessible and mark all associated alias to be visible if requested + * + * @param symbol a Symbol to check if accessible + * @param enclosingDeclaration a Node containing reference to the symbol + * @param meaning a SymbolFlags to check if such meaning of the symbol is accessible + * @param shouldComputeAliasToMakeVisible a boolean value to indicate whether to return aliases to be mark visible in case the symbol is accessible + */ + function isSymbolAccessible(symbol, enclosingDeclaration, meaning, shouldComputeAliasesToMakeVisible) { + if (symbol && enclosingDeclaration) { + var result = isAnySymbolAccessible([symbol], enclosingDeclaration, symbol, meaning, shouldComputeAliasesToMakeVisible); + if (result) { + return result; + } + // This could be a symbol that is not exported in the external module + // or it could be a symbol from different external module that is not aliased and hence cannot be named + var symbolExternalModule = ts.forEach(symbol.declarations, getExternalModuleContainer); + if (symbolExternalModule) { + var enclosingExternalModule = getExternalModuleContainer(enclosingDeclaration); + if (symbolExternalModule !== enclosingExternalModule) { + // name from different external module that is not visible + return { + accessibility: 2 /* CannotBeNamed */, + errorSymbolName: symbolToString(symbol, enclosingDeclaration, meaning), + errorModuleName: symbolToString(symbolExternalModule) + }; + } + } + // Just a local name that is not accessible + return { + accessibility: 1 /* NotAccessible */, + errorSymbolName: symbolToString(symbol, enclosingDeclaration, meaning), + }; + } + return { accessibility: 0 /* Accessible */ }; + } + function getExternalModuleContainer(declaration) { + var node = ts.findAncestor(declaration, hasExternalModuleSymbol); + return node && getSymbolOfNode(node); + } + function hasExternalModuleSymbol(declaration) { + return ts.isAmbientModule(declaration) || (declaration.kind === 279 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration)); + } + function hasNonGlobalAugmentationExternalModuleSymbol(declaration) { + return ts.isModuleWithStringLiteralName(declaration) || (declaration.kind === 279 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration)); + } + function hasVisibleDeclarations(symbol, shouldComputeAliasToMakeVisible) { + var aliasesToMakeVisible; + if (!ts.every(symbol.declarations, getIsDeclarationVisible)) { + return undefined; + } + return { accessibility: 0 /* Accessible */, aliasesToMakeVisible: aliasesToMakeVisible }; + function getIsDeclarationVisible(declaration) { + if (!isDeclarationVisible(declaration)) { + // Mark the unexported alias as visible if its parent is visible + // because these kind of aliases can be used to name types in declaration file + var anyImportSyntax = getAnyImportSyntax(declaration); + if (anyImportSyntax && + !ts.hasModifier(anyImportSyntax, 1 /* Export */) && // import clause without export + isDeclarationVisible(anyImportSyntax.parent)) { + return addVisibleAlias(declaration, anyImportSyntax); + } + else if (ts.isVariableDeclaration(declaration) && ts.isVariableStatement(declaration.parent.parent) && + !ts.hasModifier(declaration.parent.parent, 1 /* Export */) && // unexported variable statement + isDeclarationVisible(declaration.parent.parent.parent)) { + return addVisibleAlias(declaration, declaration.parent.parent); + } + else if (ts.isLateVisibilityPaintedStatement(declaration) // unexported top-level statement + && !ts.hasModifier(declaration, 1 /* Export */) + && isDeclarationVisible(declaration.parent)) { + return addVisibleAlias(declaration, declaration); + } + // Declaration is not visible + return false; + } + return true; + } + function addVisibleAlias(declaration, aliasingStatement) { + // In function "buildTypeDisplay" where we decide whether to write type-alias or serialize types, + // we want to just check if type- alias is accessible or not but we don't care about emitting those alias at that time + // since we will do the emitting later in trackSymbol. + if (shouldComputeAliasToMakeVisible) { + getNodeLinks(declaration).isVisible = true; + aliasesToMakeVisible = ts.appendIfUnique(aliasesToMakeVisible, aliasingStatement); + } + return true; + } + } + function isEntityNameVisible(entityName, enclosingDeclaration) { + // get symbol of the first identifier of the entityName + var meaning; + if (entityName.parent.kind === 167 /* TypeQuery */ || + ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent) || + entityName.parent.kind === 149 /* ComputedPropertyName */) { + // Typeof value + meaning = 67220415 /* Value */ | 1048576 /* ExportValue */; + } + else if (entityName.kind === 148 /* QualifiedName */ || entityName.kind === 189 /* PropertyAccessExpression */ || + entityName.parent.kind === 248 /* ImportEqualsDeclaration */) { + // Left identifier from type reference or TypeAlias + // Entity name of the import declaration + meaning = 1920 /* Namespace */; + } + else { + // Type Reference or TypeAlias entity = Identifier + meaning = 67897832 /* Type */; + } + var firstIdentifier = getFirstIdentifier(entityName); + var symbol = resolveName(enclosingDeclaration, firstIdentifier.escapedText, meaning, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); + // Verify if the symbol is accessible + return (symbol && hasVisibleDeclarations(symbol, /*shouldComputeAliasToMakeVisible*/ true)) || { + accessibility: 1 /* NotAccessible */, + errorSymbolName: ts.getTextOfNode(firstIdentifier), + errorNode: firstIdentifier + }; + } + function symbolToString(symbol, enclosingDeclaration, meaning, flags, writer) { + if (flags === void 0) { flags = 4 /* AllowAnyNodeKind */; } + var nodeFlags = 70221824 /* IgnoreErrors */; + if (flags & 2 /* UseOnlyExternalAliasing */) { + nodeFlags |= 128 /* UseOnlyExternalAliasing */; + } + if (flags & 1 /* WriteTypeParametersOrArguments */) { + nodeFlags |= 512 /* WriteTypeParametersInQualifiedName */; + } + if (flags & 8 /* UseAliasDefinedOutsideCurrentScope */) { + nodeFlags |= 16384 /* UseAliasDefinedOutsideCurrentScope */; + } + if (flags & 16 /* DoNotIncludeSymbolChain */) { + nodeFlags |= 134217728 /* DoNotIncludeSymbolChain */; + } + var builder = flags & 4 /* AllowAnyNodeKind */ ? nodeBuilder.symbolToExpression : nodeBuilder.symbolToEntityName; + return writer ? symbolToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(symbolToStringWorker); + function symbolToStringWorker(writer) { + var entity = builder(symbol, meaning, enclosingDeclaration, nodeFlags); // TODO: GH#18217 + var printer = ts.createPrinter({ removeComments: true }); + var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); + printer.writeNode(4 /* Unspecified */, entity, /*sourceFile*/ sourceFile, writer); + return writer; + } + } + function signatureToString(signature, enclosingDeclaration, flags, kind, writer) { + if (flags === void 0) { flags = 0 /* None */; } + return writer ? signatureToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(signatureToStringWorker); + function signatureToStringWorker(writer) { + var sigOutput; + if (flags & 262144 /* WriteArrowStyleSignature */) { + sigOutput = kind === 1 /* Construct */ ? 166 /* ConstructorType */ : 165 /* FunctionType */; + } + else { + sigOutput = kind === 1 /* Construct */ ? 161 /* ConstructSignature */ : 160 /* CallSignature */; + } + var sig = nodeBuilder.signatureToSignatureDeclaration(signature, sigOutput, enclosingDeclaration, toNodeBuilderFlags(flags) | 70221824 /* IgnoreErrors */ | 512 /* WriteTypeParametersInQualifiedName */); + var printer = ts.createPrinter({ removeComments: true, omitTrailingSemicolon: true }); + var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); + printer.writeNode(4 /* Unspecified */, sig, /*sourceFile*/ sourceFile, ts.getTrailingSemicolonOmittingWriter(writer)); // TODO: GH#18217 + return writer; + } + } + function typeToString(type, enclosingDeclaration, flags, writer) { + if (flags === void 0) { flags = 1048576 /* AllowUniqueESSymbolType */ | 16384 /* UseAliasDefinedOutsideCurrentScope */; } + if (writer === void 0) { writer = ts.createTextWriter(""); } + var noTruncation = compilerOptions.noErrorTruncation || flags & 1 /* NoTruncation */; + var typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, toNodeBuilderFlags(flags) | 70221824 /* IgnoreErrors */ | (noTruncation ? 1 /* NoTruncation */ : 0), writer); + if (typeNode === undefined) + return ts.Debug.fail("should always get typenode"); + var options = { removeComments: true }; + var printer = ts.createPrinter(options); + var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); + printer.writeNode(4 /* Unspecified */, typeNode, /*sourceFile*/ sourceFile, writer); + var result = writer.getText(); + var maxLength = noTruncation ? undefined : ts.defaultMaximumTruncationLength * 2; + if (maxLength && result && result.length >= maxLength) { + return result.substr(0, maxLength - "...".length) + "..."; + } + return result; + } + function toNodeBuilderFlags(flags) { + if (flags === void 0) { flags = 0 /* None */; } + return flags & 9469291 /* NodeBuilderFlagsMask */; + } + function createNodeBuilder() { + return { + typeToTypeNode: function (type, enclosingDeclaration, flags, tracker) { + return withContext(enclosingDeclaration, flags, tracker, function (context) { return typeToTypeNodeHelper(type, context); }); + }, + indexInfoToIndexSignatureDeclaration: function (indexInfo, kind, enclosingDeclaration, flags, tracker) { + return withContext(enclosingDeclaration, flags, tracker, function (context) { return indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind, context); }); + }, + signatureToSignatureDeclaration: function (signature, kind, enclosingDeclaration, flags, tracker) { + return withContext(enclosingDeclaration, flags, tracker, function (context) { return signatureToSignatureDeclarationHelper(signature, kind, context); }); + }, + symbolToEntityName: function (symbol, meaning, enclosingDeclaration, flags, tracker) { + return withContext(enclosingDeclaration, flags, tracker, function (context) { return symbolToName(symbol, context, meaning, /*expectsIdentifier*/ false); }); + }, + symbolToExpression: function (symbol, meaning, enclosingDeclaration, flags, tracker) { + return withContext(enclosingDeclaration, flags, tracker, function (context) { return symbolToExpression(symbol, context, meaning); }); + }, + symbolToTypeParameterDeclarations: function (symbol, enclosingDeclaration, flags, tracker) { + return withContext(enclosingDeclaration, flags, tracker, function (context) { return typeParametersToTypeParameterDeclarations(symbol, context); }); + }, + symbolToParameterDeclaration: function (symbol, enclosingDeclaration, flags, tracker) { + return withContext(enclosingDeclaration, flags, tracker, function (context) { return symbolToParameterDeclaration(symbol, context); }); + }, + typeParameterToDeclaration: function (parameter, enclosingDeclaration, flags, tracker) { + return withContext(enclosingDeclaration, flags, tracker, function (context) { return typeParameterToDeclaration(parameter, context); }); + }, + }; + function withContext(enclosingDeclaration, flags, tracker, cb) { + ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8 /* Synthesized */) === 0); + var context = { + enclosingDeclaration: enclosingDeclaration, + flags: flags || 0 /* None */, + // If no full tracker is provided, fake up a dummy one with a basic limited-functionality moduleResolverHost + tracker: tracker && tracker.trackSymbol ? tracker : { trackSymbol: ts.noop, moduleResolverHost: flags & 134217728 /* DoNotIncludeSymbolChain */ ? { + getCommonSourceDirectory: host.getCommonSourceDirectory ? function () { return host.getCommonSourceDirectory(); } : function () { return ""; }, + getSourceFiles: function () { return host.getSourceFiles(); }, + getCurrentDirectory: host.getCurrentDirectory && (function () { return host.getCurrentDirectory(); }) + } : undefined }, + encounteredError: false, + visitedTypes: undefined, + symbolDepth: undefined, + inferTypeParameters: undefined, + approximateLength: 0 + }; + var resultingNode = cb(context); + return context.encounteredError ? undefined : resultingNode; + } + function checkTruncationLength(context) { + if (context.truncating) + return context.truncating; + return context.truncating = !(context.flags & 1 /* NoTruncation */) && context.approximateLength > ts.defaultMaximumTruncationLength; + } + function typeToTypeNodeHelper(type, context) { + if (cancellationToken && cancellationToken.throwIfCancellationRequested) { + cancellationToken.throwIfCancellationRequested(); + } + var inTypeAlias = context.flags & 8388608 /* InTypeAlias */; + context.flags &= ~8388608 /* InTypeAlias */; + if (!type) { + context.encounteredError = true; + return undefined; // TODO: GH#18217 + } + if (type.flags & 1 /* Any */) { + context.approximateLength += 3; + return ts.createKeywordTypeNode(120 /* AnyKeyword */); + } + if (type.flags & 2 /* Unknown */) { + return ts.createKeywordTypeNode(143 /* UnknownKeyword */); + } + if (type.flags & 4 /* String */) { + context.approximateLength += 6; + return ts.createKeywordTypeNode(138 /* StringKeyword */); + } + if (type.flags & 8 /* Number */) { + context.approximateLength += 6; + return ts.createKeywordTypeNode(135 /* NumberKeyword */); + } + if (type.flags & 64 /* BigInt */) { + context.approximateLength += 6; + return ts.createKeywordTypeNode(146 /* BigIntKeyword */); + } + if (type.flags & 16 /* Boolean */) { + context.approximateLength += 7; + return ts.createKeywordTypeNode(123 /* BooleanKeyword */); + } + if (type.flags & 1024 /* EnumLiteral */ && !(type.flags & 1048576 /* Union */)) { + var parentSymbol = getParentOfSymbol(type.symbol); + var parentName = symbolToTypeNode(parentSymbol, context, 67897832 /* Type */); + var enumLiteralName = getDeclaredTypeOfSymbol(parentSymbol) === type + ? parentName + : appendReferenceToType(parentName, ts.createTypeReferenceNode(ts.symbolName(type.symbol), /*typeArguments*/ undefined)); + return enumLiteralName; + } + if (type.flags & 1056 /* EnumLike */) { + return symbolToTypeNode(type.symbol, context, 67897832 /* Type */); + } + if (type.flags & 128 /* StringLiteral */) { + context.approximateLength += (type.value.length + 2); + return ts.createLiteralTypeNode(ts.setEmitFlags(ts.createLiteral(type.value), 16777216 /* NoAsciiEscaping */)); + } + if (type.flags & 256 /* NumberLiteral */) { + context.approximateLength += (("" + type.value).length); + return ts.createLiteralTypeNode((ts.createLiteral(type.value))); + } + if (type.flags & 2048 /* BigIntLiteral */) { + context.approximateLength += (ts.pseudoBigIntToString(type.value).length) + 1; + return ts.createLiteralTypeNode((ts.createLiteral(type.value))); + } + if (type.flags & 512 /* BooleanLiteral */) { + context.approximateLength += type.intrinsicName.length; + return type.intrinsicName === "true" ? ts.createTrue() : ts.createFalse(); + } + if (type.flags & 8192 /* UniqueESSymbol */) { + if (!(context.flags & 1048576 /* AllowUniqueESSymbolType */)) { + if (isValueSymbolAccessible(type.symbol, context.enclosingDeclaration)) { + context.approximateLength += 6; + return symbolToTypeNode(type.symbol, context, 67220415 /* Value */); + } + if (context.tracker.reportInaccessibleUniqueSymbolError) { + context.tracker.reportInaccessibleUniqueSymbolError(); + } + } + context.approximateLength += 13; + return ts.createTypeOperatorNode(142 /* UniqueKeyword */, ts.createKeywordTypeNode(139 /* SymbolKeyword */)); + } + if (type.flags & 16384 /* Void */) { + context.approximateLength += 4; + return ts.createKeywordTypeNode(106 /* VoidKeyword */); + } + if (type.flags & 32768 /* Undefined */) { + context.approximateLength += 9; + return ts.createKeywordTypeNode(141 /* UndefinedKeyword */); + } + if (type.flags & 65536 /* Null */) { + context.approximateLength += 4; + return ts.createKeywordTypeNode(96 /* NullKeyword */); + } + if (type.flags & 131072 /* Never */) { + context.approximateLength += 5; + return ts.createKeywordTypeNode(132 /* NeverKeyword */); + } + if (type.flags & 4096 /* ESSymbol */) { + context.approximateLength += 6; + return ts.createKeywordTypeNode(139 /* SymbolKeyword */); + } + if (type.flags & 67108864 /* NonPrimitive */) { + context.approximateLength += 6; + return ts.createKeywordTypeNode(136 /* ObjectKeyword */); + } + if (type.flags & 262144 /* TypeParameter */ && type.isThisType) { + if (context.flags & 4194304 /* InObjectTypeLiteral */) { + if (!context.encounteredError && !(context.flags & 32768 /* AllowThisInObjectLiteral */)) { + context.encounteredError = true; + } + if (context.tracker.reportInaccessibleThisError) { + context.tracker.reportInaccessibleThisError(); + } + } + context.approximateLength += 4; + return ts.createThis(); + } + var objectFlags = ts.getObjectFlags(type); + if (objectFlags & 4 /* Reference */) { + ts.Debug.assert(!!(type.flags & 524288 /* Object */)); + return typeReferenceToTypeNode(type); + } + if (type.flags & 262144 /* TypeParameter */ || objectFlags & 3 /* ClassOrInterface */) { + if (type.flags & 262144 /* TypeParameter */ && ts.contains(context.inferTypeParameters, type)) { + context.approximateLength += (ts.symbolName(type.symbol).length + 6); + return ts.createInferTypeNode(typeParameterToDeclarationWithConstraint(type, context, /*constraintNode*/ undefined)); + } + if (context.flags & 4 /* GenerateNamesForShadowedTypeParams */ && + type.flags & 262144 /* TypeParameter */ && + ts.length(type.symbol.declarations) && + ts.isTypeParameterDeclaration(type.symbol.declarations[0]) && + typeParameterShadowsNameInScope(type, context) && + !isTypeSymbolAccessible(type.symbol, context.enclosingDeclaration)) { + var name = type.symbol.declarations[0].name; + context.approximateLength += ts.idText(name).length; + return ts.createTypeReferenceNode(ts.getGeneratedNameForNode(name, 16 /* Optimistic */ | 8 /* ReservedInNestedScopes */), /*typeArguments*/ undefined); + } + // Ignore constraint/default when creating a usage (as opposed to declaration) of a type parameter. + return type.symbol + ? symbolToTypeNode(type.symbol, context, 67897832 /* Type */) + : ts.createTypeReferenceNode(ts.createIdentifier("?"), /*typeArguments*/ undefined); + } + if (!inTypeAlias && type.aliasSymbol && (context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */ || isTypeSymbolAccessible(type.aliasSymbol, context.enclosingDeclaration))) { + var typeArgumentNodes = mapToTypeNodes(type.aliasTypeArguments, context); + if (isReservedMemberName(type.aliasSymbol.escapedName) && !(type.aliasSymbol.flags & 32 /* Class */)) + return ts.createTypeReferenceNode(ts.createIdentifier(""), typeArgumentNodes); + return symbolToTypeNode(type.aliasSymbol, context, 67897832 /* Type */, typeArgumentNodes); + } + if (type.flags & (1048576 /* Union */ | 2097152 /* Intersection */)) { + var types = type.flags & 1048576 /* Union */ ? formatUnionTypes(type.types) : type.types; + if (ts.length(types) === 1) { + return typeToTypeNodeHelper(types[0], context); + } + var typeNodes = mapToTypeNodes(types, context, /*isBareList*/ true); + if (typeNodes && typeNodes.length > 0) { + var unionOrIntersectionTypeNode = ts.createUnionOrIntersectionTypeNode(type.flags & 1048576 /* Union */ ? 173 /* UnionType */ : 174 /* IntersectionType */, typeNodes); + return unionOrIntersectionTypeNode; + } + else { + if (!context.encounteredError && !(context.flags & 262144 /* AllowEmptyUnionOrIntersection */)) { + context.encounteredError = true; + } + return undefined; // TODO: GH#18217 + } + } + if (objectFlags & (16 /* Anonymous */ | 32 /* Mapped */)) { + ts.Debug.assert(!!(type.flags & 524288 /* Object */)); + // The type is an object literal type. + return createAnonymousTypeNode(type); + } + if (type.flags & 4194304 /* Index */) { + var indexedType = type.type; + context.approximateLength += 6; + var indexTypeNode = typeToTypeNodeHelper(indexedType, context); + return ts.createTypeOperatorNode(indexTypeNode); + } + if (type.flags & 8388608 /* IndexedAccess */) { + var objectTypeNode = typeToTypeNodeHelper(type.objectType, context); + var indexTypeNode = typeToTypeNodeHelper(type.indexType, context); + context.approximateLength += 2; + return ts.createIndexedAccessTypeNode(objectTypeNode, indexTypeNode); + } + if (type.flags & 16777216 /* Conditional */) { + var checkTypeNode = typeToTypeNodeHelper(type.checkType, context); + var saveInferTypeParameters = context.inferTypeParameters; + context.inferTypeParameters = type.root.inferTypeParameters; + var extendsTypeNode = typeToTypeNodeHelper(type.extendsType, context); + context.inferTypeParameters = saveInferTypeParameters; + var trueTypeNode = typeToTypeNodeHelper(getTrueTypeFromConditionalType(type), context); + var falseTypeNode = typeToTypeNodeHelper(getFalseTypeFromConditionalType(type), context); + context.approximateLength += 15; + return ts.createConditionalTypeNode(checkTypeNode, extendsTypeNode, trueTypeNode, falseTypeNode); + } + if (type.flags & 33554432 /* Substitution */) { + return typeToTypeNodeHelper(type.typeVariable, context); + } + return ts.Debug.fail("Should be unreachable."); + function createMappedTypeNodeFromType(type) { + ts.Debug.assert(!!(type.flags & 524288 /* Object */)); + var readonlyToken = type.declaration.readonlyToken ? ts.createToken(type.declaration.readonlyToken.kind) : undefined; + var questionToken = type.declaration.questionToken ? ts.createToken(type.declaration.questionToken.kind) : undefined; + var appropriateConstraintTypeNode; + if (isMappedTypeWithKeyofConstraintDeclaration(type)) { + // We have a { [P in keyof T]: X } + // We do this to ensure we retain the toplevel keyof-ness of the type which may be lost due to keyof distribution during `getConstraintTypeFromMappedType` + appropriateConstraintTypeNode = ts.createTypeOperatorNode(typeToTypeNodeHelper(getModifiersTypeFromMappedType(type), context)); + } + else { + appropriateConstraintTypeNode = typeToTypeNodeHelper(getConstraintTypeFromMappedType(type), context); + } + var typeParameterNode = typeParameterToDeclarationWithConstraint(getTypeParameterFromMappedType(type), context, appropriateConstraintTypeNode); + var templateTypeNode = typeToTypeNodeHelper(getTemplateTypeFromMappedType(type), context); + var mappedTypeNode = ts.createMappedTypeNode(readonlyToken, typeParameterNode, questionToken, templateTypeNode); + context.approximateLength += 10; + return ts.setEmitFlags(mappedTypeNode, 1 /* SingleLine */); + } + function createAnonymousTypeNode(type) { + var typeId = "" + type.id; + var symbol = type.symbol; + var id; + if (symbol) { + var isConstructorObject = ts.getObjectFlags(type) & 16 /* Anonymous */ && type.symbol && type.symbol.flags & 32 /* Class */; + id = (isConstructorObject ? "+" : "") + getSymbolId(symbol); + if (isJSConstructor(symbol.valueDeclaration)) { + // Instance and static types share the same symbol; only add 'typeof' for the static side. + var isInstanceType = type === getInferredClassType(symbol) ? 67897832 /* Type */ : 67220415 /* Value */; + return symbolToTypeNode(symbol, context, isInstanceType); + } + // Always use 'typeof T' for type of class, enum, and module objects + else if (symbol.flags & 32 /* Class */ && !getBaseTypeVariableOfClass(symbol) && !(symbol.valueDeclaration.kind === 209 /* ClassExpression */ && context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */) || + symbol.flags & (384 /* Enum */ | 512 /* ValueModule */) || + shouldWriteTypeOfFunctionSymbol()) { + return symbolToTypeNode(symbol, context, 67220415 /* Value */); + } + else if (context.visitedTypes && context.visitedTypes.has(typeId)) { + // If type is an anonymous type literal in a type alias declaration, use type alias name + var typeAlias = getTypeAliasForTypeLiteral(type); + if (typeAlias) { + // The specified symbol flags need to be reinterpreted as type flags + return symbolToTypeNode(typeAlias, context, 67897832 /* Type */); + } + else { + return createElidedInformationPlaceholder(context); + } + } + else { + // Since instantiations of the same anonymous type have the same symbol, tracking symbols instead + // of types allows us to catch circular references to instantiations of the same anonymous type + if (!context.visitedTypes) { + context.visitedTypes = ts.createMap(); + } + if (!context.symbolDepth) { + context.symbolDepth = ts.createMap(); + } + var depth = context.symbolDepth.get(id) || 0; + if (depth > 10) { + return createElidedInformationPlaceholder(context); + } + context.symbolDepth.set(id, depth + 1); + context.visitedTypes.set(typeId, true); + var result = createTypeNodeFromObjectType(type); + context.visitedTypes.delete(typeId); + context.symbolDepth.set(id, depth); + return result; + } + } + else { + // Anonymous types without a symbol are never circular. + return createTypeNodeFromObjectType(type); + } + function shouldWriteTypeOfFunctionSymbol() { + var isStaticMethodSymbol = !!(symbol.flags & 8192 /* Method */) && // typeof static method + ts.some(symbol.declarations, function (declaration) { return ts.hasModifier(declaration, 32 /* Static */); }); + var isNonLocalFunctionSymbol = !!(symbol.flags & 16 /* Function */) && + (symbol.parent || // is exported function symbol + ts.forEach(symbol.declarations, function (declaration) { + return declaration.parent.kind === 279 /* SourceFile */ || declaration.parent.kind === 245 /* ModuleBlock */; + })); + if (isStaticMethodSymbol || isNonLocalFunctionSymbol) { + // typeof is allowed only for static/non local functions + return (!!(context.flags & 4096 /* UseTypeOfFunction */) || (context.visitedTypes && context.visitedTypes.has(typeId))) && // it is type of the symbol uses itself recursively + (!(context.flags & 8 /* UseStructuralFallback */) || isValueSymbolAccessible(symbol, context.enclosingDeclaration)); // TODO: GH#18217 // And the build is going to succeed without visibility error or there is no structural fallback allowed + } + } + } + function createTypeNodeFromObjectType(type) { + if (isGenericMappedType(type)) { + return createMappedTypeNodeFromType(type); + } + var resolved = resolveStructuredTypeMembers(type); + if (!resolved.properties.length && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { + if (!resolved.callSignatures.length && !resolved.constructSignatures.length) { + context.approximateLength += 2; + return ts.setEmitFlags(ts.createTypeLiteralNode(/*members*/ undefined), 1 /* SingleLine */); + } + if (resolved.callSignatures.length === 1 && !resolved.constructSignatures.length) { + var signature = resolved.callSignatures[0]; + var signatureNode = signatureToSignatureDeclarationHelper(signature, 165 /* FunctionType */, context); + return signatureNode; + } + if (resolved.constructSignatures.length === 1 && !resolved.callSignatures.length) { + var signature = resolved.constructSignatures[0]; + var signatureNode = signatureToSignatureDeclarationHelper(signature, 166 /* ConstructorType */, context); + return signatureNode; + } + } + var savedFlags = context.flags; + context.flags |= 4194304 /* InObjectTypeLiteral */; + var members = createTypeNodesFromResolvedType(resolved); + context.flags = savedFlags; + var typeLiteralNode = ts.createTypeLiteralNode(members); + context.approximateLength += 2; + return ts.setEmitFlags(typeLiteralNode, (context.flags & 1024 /* MultilineObjectLiterals */) ? 0 : 1 /* SingleLine */); + } + function typeReferenceToTypeNode(type) { + var typeArguments = type.typeArguments || ts.emptyArray; + if (type.target === globalArrayType) { + if (context.flags & 2 /* WriteArrayAsGenericType */) { + var typeArgumentNode = typeToTypeNodeHelper(typeArguments[0], context); + return ts.createTypeReferenceNode("Array", [typeArgumentNode]); + } + var elementType = typeToTypeNodeHelper(typeArguments[0], context); + return ts.createArrayTypeNode(elementType); + } + else if (type.target.objectFlags & 8 /* Tuple */) { + if (typeArguments.length > 0) { + var arity = getTypeReferenceArity(type); + var tupleConstituentNodes = mapToTypeNodes(typeArguments.slice(0, arity), context); + var hasRestElement = type.target.hasRestElement; + if (tupleConstituentNodes) { + for (var i = type.target.minLength; i < Math.min(arity, tupleConstituentNodes.length); i++) { + tupleConstituentNodes[i] = hasRestElement && i === arity - 1 ? + ts.createRestTypeNode(ts.createArrayTypeNode(tupleConstituentNodes[i])) : + ts.createOptionalTypeNode(tupleConstituentNodes[i]); + } + return ts.createTupleTypeNode(tupleConstituentNodes); + } + } + if (context.encounteredError || (context.flags & 524288 /* AllowEmptyTuple */)) { + return ts.createTupleTypeNode([]); + } + context.encounteredError = true; + return undefined; // TODO: GH#18217 + } + else if (context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */ && + type.symbol.valueDeclaration && + ts.isClassLike(type.symbol.valueDeclaration) && + !isValueSymbolAccessible(type.symbol, context.enclosingDeclaration)) { + return createAnonymousTypeNode(type); + } + else { + var outerTypeParameters = type.target.outerTypeParameters; + var i = 0; + var resultType = void 0; + if (outerTypeParameters) { + var length_1 = outerTypeParameters.length; + while (i < length_1) { + // Find group of type arguments for type parameters with the same declaring container. + var start = i; + var parent = getParentSymbolOfTypeParameter(outerTypeParameters[i]); + do { + i++; + } while (i < length_1 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent); + // When type parameters are their own type arguments for the whole group (i.e. we have + // the default outer type arguments), we don't show the group. + if (!ts.rangeEquals(outerTypeParameters, typeArguments, start, i)) { + var typeArgumentSlice = mapToTypeNodes(typeArguments.slice(start, i), context); + var flags_2 = context.flags; + context.flags |= 16 /* ForbidIndexedAccessSymbolReferences */; + var ref = symbolToTypeNode(parent, context, 67897832 /* Type */, typeArgumentSlice); + context.flags = flags_2; + resultType = !resultType ? ref : appendReferenceToType(resultType, ref); + } + } + } + var typeArgumentNodes = void 0; + if (typeArguments.length > 0) { + var typeParameterCount = (type.target.typeParameters || ts.emptyArray).length; + typeArgumentNodes = mapToTypeNodes(typeArguments.slice(i, typeParameterCount), context); + } + var flags = context.flags; + context.flags |= 16 /* ForbidIndexedAccessSymbolReferences */; + var finalRef = symbolToTypeNode(type.symbol, context, 67897832 /* Type */, typeArgumentNodes); + context.flags = flags; + return !resultType ? finalRef : appendReferenceToType(resultType, finalRef); + } + } + function appendReferenceToType(root, ref) { + if (ts.isImportTypeNode(root)) { + // first shift type arguments + var innerParams = root.typeArguments; + if (root.qualifier) { + (ts.isIdentifier(root.qualifier) ? root.qualifier : root.qualifier.right).typeArguments = innerParams; + } + root.typeArguments = ref.typeArguments; + // then move qualifiers + var ids = getAccessStack(ref); + for (var _i = 0, ids_1 = ids; _i < ids_1.length; _i++) { + var id = ids_1[_i]; + root.qualifier = root.qualifier ? ts.createQualifiedName(root.qualifier, id) : id; + } + return root; + } + else { + // first shift type arguments + var innerParams = root.typeArguments; + (ts.isIdentifier(root.typeName) ? root.typeName : root.typeName.right).typeArguments = innerParams; + root.typeArguments = ref.typeArguments; + // then move qualifiers + var ids = getAccessStack(ref); + for (var _a = 0, ids_2 = ids; _a < ids_2.length; _a++) { + var id = ids_2[_a]; + root.typeName = ts.createQualifiedName(root.typeName, id); + } + return root; + } + } + function getAccessStack(ref) { + var state = ref.typeName; + var ids = []; + while (!ts.isIdentifier(state)) { + ids.unshift(state.right); + state = state.left; + } + ids.unshift(state); + return ids; + } + function createTypeNodesFromResolvedType(resolvedType) { + if (checkTruncationLength(context)) { + return [ts.createPropertySignature(/*modifiers*/ undefined, "...", /*questionToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined)]; + } + var typeElements = []; + for (var _i = 0, _a = resolvedType.callSignatures; _i < _a.length; _i++) { + var signature = _a[_i]; + typeElements.push(signatureToSignatureDeclarationHelper(signature, 160 /* CallSignature */, context)); + } + for (var _b = 0, _c = resolvedType.constructSignatures; _b < _c.length; _b++) { + var signature = _c[_b]; + typeElements.push(signatureToSignatureDeclarationHelper(signature, 161 /* ConstructSignature */, context)); + } + if (resolvedType.stringIndexInfo) { + var indexSignature = void 0; + if (resolvedType.objectFlags & 2048 /* ReverseMapped */) { + indexSignature = indexInfoToIndexSignatureDeclarationHelper(createIndexInfo(anyType, resolvedType.stringIndexInfo.isReadonly, resolvedType.stringIndexInfo.declaration), 0 /* String */, context); + indexSignature.type = createElidedInformationPlaceholder(context); + } + else { + indexSignature = indexInfoToIndexSignatureDeclarationHelper(resolvedType.stringIndexInfo, 0 /* String */, context); + } + typeElements.push(indexSignature); + } + if (resolvedType.numberIndexInfo) { + typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.numberIndexInfo, 1 /* Number */, context)); + } + var properties = resolvedType.properties; + if (!properties) { + return typeElements; + } + var i = 0; + for (var _d = 0, properties_1 = properties; _d < properties_1.length; _d++) { + var propertySymbol = properties_1[_d]; + i++; + if (context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */) { + if (propertySymbol.flags & 4194304 /* Prototype */) { + continue; + } + if (ts.getDeclarationModifierFlagsFromSymbol(propertySymbol) & (8 /* Private */ | 16 /* Protected */) && context.tracker.reportPrivateInBaseOfClassExpression) { + context.tracker.reportPrivateInBaseOfClassExpression(ts.unescapeLeadingUnderscores(propertySymbol.escapedName)); + } + } + if (checkTruncationLength(context) && (i + 2 < properties.length - 1)) { + typeElements.push(ts.createPropertySignature(/*modifiers*/ undefined, "... " + (properties.length - i) + " more ...", /*questionToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined)); + addPropertyToElementList(properties[properties.length - 1], context, typeElements); + break; + } + addPropertyToElementList(propertySymbol, context, typeElements); + } + return typeElements.length ? typeElements : undefined; + } + } + function createElidedInformationPlaceholder(context) { + context.approximateLength += 3; + if (!(context.flags & 1 /* NoTruncation */)) { + return ts.createTypeReferenceNode(ts.createIdentifier("..."), /*typeArguments*/ undefined); + } + return ts.createKeywordTypeNode(120 /* AnyKeyword */); + } + function addPropertyToElementList(propertySymbol, context, typeElements) { + var propertyIsReverseMapped = !!(ts.getCheckFlags(propertySymbol) & 2048 /* ReverseMapped */); + var propertyType = propertyIsReverseMapped && context.flags & 33554432 /* InReverseMappedType */ ? + anyType : getTypeOfSymbol(propertySymbol); + var saveEnclosingDeclaration = context.enclosingDeclaration; + context.enclosingDeclaration = undefined; + if (context.tracker.trackSymbol && ts.getCheckFlags(propertySymbol) & 1024 /* Late */) { + var decl = ts.first(propertySymbol.declarations); + if (hasLateBindableName(decl)) { + trackComputedName(decl.name, saveEnclosingDeclaration, context); + } + } + var propertyName = symbolToName(propertySymbol, context, 67220415 /* Value */, /*expectsIdentifier*/ true); + context.approximateLength += (ts.symbolName(propertySymbol).length + 1); + context.enclosingDeclaration = saveEnclosingDeclaration; + var optionalToken = propertySymbol.flags & 16777216 /* Optional */ ? ts.createToken(56 /* QuestionToken */) : undefined; + if (propertySymbol.flags & (16 /* Function */ | 8192 /* Method */) && !getPropertiesOfObjectType(propertyType).length) { + var signatures = getSignaturesOfType(propertyType, 0 /* Call */); + for (var _i = 0, signatures_1 = signatures; _i < signatures_1.length; _i++) { + var signature = signatures_1[_i]; + var methodDeclaration = signatureToSignatureDeclarationHelper(signature, 155 /* MethodSignature */, context); + methodDeclaration.name = propertyName; + methodDeclaration.questionToken = optionalToken; + if (propertySymbol.valueDeclaration) { + // Copy comments to node for declaration emit + ts.setCommentRange(methodDeclaration, propertySymbol.valueDeclaration); + } + typeElements.push(methodDeclaration); + } + } + else { + var savedFlags = context.flags; + context.flags |= propertyIsReverseMapped ? 33554432 /* InReverseMappedType */ : 0; + var propertyTypeNode = void 0; + if (propertyIsReverseMapped && !!(savedFlags & 33554432 /* InReverseMappedType */)) { + propertyTypeNode = createElidedInformationPlaceholder(context); + } + else { + propertyTypeNode = propertyType ? typeToTypeNodeHelper(propertyType, context) : ts.createKeywordTypeNode(120 /* AnyKeyword */); + } + context.flags = savedFlags; + var modifiers = isReadonlySymbol(propertySymbol) ? [ts.createToken(133 /* ReadonlyKeyword */)] : undefined; + if (modifiers) { + context.approximateLength += 9; + } + var propertySignature = ts.createPropertySignature(modifiers, propertyName, optionalToken, propertyTypeNode, + /*initializer*/ undefined); + if (propertySymbol.valueDeclaration) { + // Copy comments to node for declaration emit + ts.setCommentRange(propertySignature, propertySymbol.valueDeclaration); + } + typeElements.push(propertySignature); + } + } + function mapToTypeNodes(types, context, isBareList) { + if (ts.some(types)) { + if (checkTruncationLength(context)) { + if (!isBareList) { + return [ts.createTypeReferenceNode("...", /*typeArguments*/ undefined)]; + } + else if (types.length > 2) { + return [ + typeToTypeNodeHelper(types[0], context), + ts.createTypeReferenceNode("... " + (types.length - 2) + " more ...", /*typeArguments*/ undefined), + typeToTypeNodeHelper(types[types.length - 1], context) + ]; + } + } + var result = []; + var i = 0; + for (var _i = 0, types_1 = types; _i < types_1.length; _i++) { + var type = types_1[_i]; + i++; + if (checkTruncationLength(context) && (i + 2 < types.length - 1)) { + result.push(ts.createTypeReferenceNode("... " + (types.length - i) + " more ...", /*typeArguments*/ undefined)); + var typeNode_1 = typeToTypeNodeHelper(types[types.length - 1], context); + if (typeNode_1) { + result.push(typeNode_1); + } + break; + } + context.approximateLength += 2; // Account for whitespace + separator + var typeNode = typeToTypeNodeHelper(type, context); + if (typeNode) { + result.push(typeNode); + } + } + return result; + } + } + function indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind, context) { + var name = ts.getNameFromIndexInfo(indexInfo) || "x"; + var indexerTypeNode = ts.createKeywordTypeNode(kind === 0 /* String */ ? 138 /* StringKeyword */ : 135 /* NumberKeyword */); + var indexingParameter = ts.createParameter( + /*decorators*/ undefined, + /*modifiers*/ undefined, + /*dotDotDotToken*/ undefined, name, + /*questionToken*/ undefined, indexerTypeNode, + /*initializer*/ undefined); + var typeNode = typeToTypeNodeHelper(indexInfo.type || anyType, context); + if (!indexInfo.type && !(context.flags & 2097152 /* AllowEmptyIndexInfoType */)) { + context.encounteredError = true; + } + context.approximateLength += (name.length + 4); + return ts.createIndexSignature( + /*decorators*/ undefined, indexInfo.isReadonly ? [ts.createToken(133 /* ReadonlyKeyword */)] : undefined, [indexingParameter], typeNode); + } + function signatureToSignatureDeclarationHelper(signature, kind, context) { + var typeParameters; + var typeArguments; + if (context.flags & 32 /* WriteTypeArgumentsOfSignature */ && signature.target && signature.mapper && signature.target.typeParameters) { + typeArguments = signature.target.typeParameters.map(function (parameter) { return typeToTypeNodeHelper(instantiateType(parameter, signature.mapper), context); }); + } + else { + typeParameters = signature.typeParameters && signature.typeParameters.map(function (parameter) { return typeParameterToDeclaration(parameter, context); }); + } + var parameters = getExpandedParameters(signature).map(function (parameter) { return symbolToParameterDeclaration(parameter, context, kind === 157 /* Constructor */); }); + if (signature.thisParameter) { + var thisParameter = symbolToParameterDeclaration(signature.thisParameter, context); + parameters.unshift(thisParameter); + } + var returnTypeNode; + var typePredicate = getTypePredicateOfSignature(signature); + if (typePredicate) { + var parameterName = typePredicate.kind === 1 /* Identifier */ ? + ts.setEmitFlags(ts.createIdentifier(typePredicate.parameterName), 16777216 /* NoAsciiEscaping */) : + ts.createThisTypeNode(); + var typeNode = typeToTypeNodeHelper(typePredicate.type, context); + returnTypeNode = ts.createTypePredicateNode(parameterName, typeNode); + } + else { + var returnType = getReturnTypeOfSignature(signature); + returnTypeNode = returnType && typeToTypeNodeHelper(returnType, context); + } + if (context.flags & 256 /* SuppressAnyReturnType */) { + if (returnTypeNode && returnTypeNode.kind === 120 /* AnyKeyword */) { + returnTypeNode = undefined; + } + } + else if (!returnTypeNode) { + returnTypeNode = ts.createKeywordTypeNode(120 /* AnyKeyword */); + } + context.approximateLength += 3; // Usually a signature contributes a few more characters than this, but 3 is the minimum + return ts.createSignatureDeclaration(kind, typeParameters, parameters, returnTypeNode, typeArguments); + } + function typeParameterShadowsNameInScope(type, context) { + return !!resolveName(context.enclosingDeclaration, type.symbol.escapedName, 67897832 /* Type */, /*nameNotFoundArg*/ undefined, type.symbol.escapedName, /*isUse*/ false); + } + function typeParameterToDeclarationWithConstraint(type, context, constraintNode) { + var savedContextFlags = context.flags; + context.flags &= ~512 /* WriteTypeParametersInQualifiedName */; // Avoids potential infinite loop when building for a claimspace with a generic + var shouldUseGeneratedName = context.flags & 4 /* GenerateNamesForShadowedTypeParams */ && + type.symbol.declarations[0] && + ts.isTypeParameterDeclaration(type.symbol.declarations[0]) && + typeParameterShadowsNameInScope(type, context); + var name = shouldUseGeneratedName + ? ts.getGeneratedNameForNode(type.symbol.declarations[0].name, 16 /* Optimistic */ | 8 /* ReservedInNestedScopes */) + : symbolToName(type.symbol, context, 67897832 /* Type */, /*expectsIdentifier*/ true); + var defaultParameter = getDefaultFromTypeParameter(type); + var defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter, context); + context.flags = savedContextFlags; + return ts.createTypeParameterDeclaration(name, constraintNode, defaultParameterNode); + } + function typeParameterToDeclaration(type, context, constraint) { + if (constraint === void 0) { constraint = getConstraintOfTypeParameter(type); } + var constraintNode = constraint && typeToTypeNodeHelper(constraint, context); + return typeParameterToDeclarationWithConstraint(type, context, constraintNode); + } + function symbolToParameterDeclaration(parameterSymbol, context, preserveModifierFlags) { + var parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 151 /* Parameter */); + if (!parameterDeclaration && !isTransientSymbol(parameterSymbol)) { + parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 299 /* JSDocParameterTag */); + } + var parameterType = getTypeOfSymbol(parameterSymbol); + if (parameterDeclaration && isRequiredInitializedParameter(parameterDeclaration)) { + parameterType = getOptionalType(parameterType); + } + var parameterTypeNode = typeToTypeNodeHelper(parameterType, context); + var modifiers = !(context.flags & 8192 /* OmitParameterModifiers */) && preserveModifierFlags && parameterDeclaration && parameterDeclaration.modifiers ? parameterDeclaration.modifiers.map(ts.getSynthesizedClone) : undefined; + var isRest = parameterDeclaration && ts.isRestParameter(parameterDeclaration) || ts.getCheckFlags(parameterSymbol) & 8192 /* RestParameter */; + var dotDotDotToken = isRest ? ts.createToken(25 /* DotDotDotToken */) : undefined; + var name = parameterDeclaration + ? parameterDeclaration.name ? + parameterDeclaration.name.kind === 72 /* Identifier */ ? ts.setEmitFlags(ts.getSynthesizedClone(parameterDeclaration.name), 16777216 /* NoAsciiEscaping */) : + parameterDeclaration.name.kind === 148 /* QualifiedName */ ? ts.setEmitFlags(ts.getSynthesizedClone(parameterDeclaration.name.right), 16777216 /* NoAsciiEscaping */) : + cloneBindingName(parameterDeclaration.name) : + ts.symbolName(parameterSymbol) + : ts.symbolName(parameterSymbol); + var isOptional = parameterDeclaration && isOptionalParameter(parameterDeclaration) || ts.getCheckFlags(parameterSymbol) & 4096 /* OptionalParameter */; + var questionToken = isOptional ? ts.createToken(56 /* QuestionToken */) : undefined; + var parameterNode = ts.createParameter( + /*decorators*/ undefined, modifiers, dotDotDotToken, name, questionToken, parameterTypeNode, + /*initializer*/ undefined); + context.approximateLength += ts.symbolName(parameterSymbol).length + 3; + return parameterNode; + function cloneBindingName(node) { + return elideInitializerAndSetEmitFlags(node); + function elideInitializerAndSetEmitFlags(node) { + if (context.tracker.trackSymbol && ts.isComputedPropertyName(node) && isLateBindableName(node)) { + trackComputedName(node, context.enclosingDeclaration, context); + } + var visited = ts.visitEachChild(node, elideInitializerAndSetEmitFlags, ts.nullTransformationContext, /*nodesVisitor*/ undefined, elideInitializerAndSetEmitFlags); + var clone = ts.nodeIsSynthesized(visited) ? visited : ts.getSynthesizedClone(visited); + if (clone.kind === 186 /* BindingElement */) { + clone.initializer = undefined; + } + return ts.setEmitFlags(clone, 1 /* SingleLine */ | 16777216 /* NoAsciiEscaping */); + } + } + } + function trackComputedName(node, enclosingDeclaration, context) { + if (!context.tracker.trackSymbol) + return; + // get symbol of the first identifier of the entityName + var firstIdentifier = getFirstIdentifier(node.expression); + var name = resolveName(firstIdentifier, firstIdentifier.escapedText, 67220415 /* Value */ | 1048576 /* ExportValue */, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); + if (name) { + context.tracker.trackSymbol(name, enclosingDeclaration, 67220415 /* Value */); + } + } + function lookupSymbolChain(symbol, context, meaning, yieldModuleSymbol) { + context.tracker.trackSymbol(symbol, context.enclosingDeclaration, meaning); // TODO: GH#18217 + // Try to get qualified name if the symbol is not a type parameter and there is an enclosing declaration. + var chain; + var isTypeParameter = symbol.flags & 262144 /* TypeParameter */; + if (!isTypeParameter && (context.enclosingDeclaration || context.flags & 64 /* UseFullyQualifiedType */) && !(context.flags & 134217728 /* DoNotIncludeSymbolChain */)) { + chain = ts.Debug.assertDefined(getSymbolChain(symbol, meaning, /*endOfChain*/ true)); + ts.Debug.assert(chain && chain.length > 0); + } + else { + chain = [symbol]; + } + return chain; + /** @param endOfChain Set to false for recursive calls; non-recursive calls should always output something. */ + function getSymbolChain(symbol, meaning, endOfChain) { + var accessibleSymbolChain = getAccessibleSymbolChain(symbol, context.enclosingDeclaration, meaning, !!(context.flags & 128 /* UseOnlyExternalAliasing */)); + var parentSpecifiers; + if (!accessibleSymbolChain || + needsQualification(accessibleSymbolChain[0], context.enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) { + // Go up and add our parent. + var parents_1 = getContainersOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol, context.enclosingDeclaration); + if (ts.length(parents_1)) { + parentSpecifiers = parents_1.map(function (symbol) { + return ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol) + ? getSpecifierForModuleSymbol(symbol, context) + : undefined; + }); + var indices = parents_1.map(function (_, i) { return i; }); + indices.sort(sortByBestName); + var sortedParents = indices.map(function (i) { return parents_1[i]; }); + for (var _i = 0, sortedParents_1 = sortedParents; _i < sortedParents_1.length; _i++) { + var parent = sortedParents_1[_i]; + var parentChain = getSymbolChain(parent, getQualifiedLeftMeaning(meaning), /*endOfChain*/ false); + if (parentChain) { + accessibleSymbolChain = parentChain.concat(accessibleSymbolChain || [getAliasForSymbolInContainer(parent, symbol) || symbol]); + break; + } + } + } + } + if (accessibleSymbolChain) { + return accessibleSymbolChain; + } + if ( + // If this is the last part of outputting the symbol, always output. The cases apply only to parent symbols. + endOfChain || + // If a parent symbol is an anonymous type, don't write it. + !(symbol.flags & (2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */))) { + // If a parent symbol is an external module, don't write it. (We prefer just `x` vs `"foo/bar".x`.) + if (!endOfChain && !yieldModuleSymbol && !!ts.forEach(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { + return; + } + return [symbol]; + } + function sortByBestName(a, b) { + var specifierA = parentSpecifiers[a]; + var specifierB = parentSpecifiers[b]; + if (specifierA && specifierB) { + var isBRelative = ts.pathIsRelative(specifierB); + if (ts.pathIsRelative(specifierA) === isBRelative) { + // Both relative or both non-relative, sort by number of parts + return ts.moduleSpecifiers.countPathComponents(specifierA) - ts.moduleSpecifiers.countPathComponents(specifierB); + } + if (isBRelative) { + // A is non-relative, B is relative: prefer A + return -1; + } + // A is relative, B is non-relative: prefer B + return 1; + } + return 0; + } + } + } + function typeParametersToTypeParameterDeclarations(symbol, context) { + var typeParameterNodes; + var targetSymbol = getTargetSymbol(symbol); + if (targetSymbol.flags & (32 /* Class */ | 64 /* Interface */ | 524288 /* TypeAlias */)) { + typeParameterNodes = ts.createNodeArray(ts.map(getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol), function (tp) { return typeParameterToDeclaration(tp, context); })); + } + return typeParameterNodes; + } + function lookupTypeParameterNodes(chain, index, context) { + ts.Debug.assert(chain && 0 <= index && index < chain.length); + var symbol = chain[index]; + var typeParameterNodes; + if (context.flags & 512 /* WriteTypeParametersInQualifiedName */ && index < (chain.length - 1)) { + var parentSymbol = symbol; + var nextSymbol = chain[index + 1]; + if (ts.getCheckFlags(nextSymbol) & 1 /* Instantiated */) { + var params = getTypeParametersOfClassOrInterface(parentSymbol.flags & 2097152 /* Alias */ ? resolveAlias(parentSymbol) : parentSymbol); + typeParameterNodes = mapToTypeNodes(ts.map(params, nextSymbol.mapper), context); + } + else { + typeParameterNodes = typeParametersToTypeParameterDeclarations(symbol, context); + } + } + return typeParameterNodes; + } + /** + * Given A[B][C][D], finds A[B] + */ + function getTopmostIndexedAccessType(top) { + if (ts.isIndexedAccessTypeNode(top.objectType)) { + return getTopmostIndexedAccessType(top.objectType); + } + return top; + } + function getSpecifierForModuleSymbol(symbol, context) { + var file = ts.getDeclarationOfKind(symbol, 279 /* SourceFile */); + if (file && file.moduleName !== undefined) { + // Use the amd name if it is available + return file.moduleName; + } + if (!file) { + if (context.tracker.trackReferencedAmbientModule) { + var ambientDecls = ts.filter(symbol.declarations, ts.isAmbientModule); + if (ts.length(ambientDecls)) { + for (var _i = 0, ambientDecls_1 = ambientDecls; _i < ambientDecls_1.length; _i++) { + var decl = ambientDecls_1[_i]; + context.tracker.trackReferencedAmbientModule(decl, symbol); + } + } + } + if (ambientModuleSymbolRegex.test(symbol.escapedName)) { + return symbol.escapedName.substring(1, symbol.escapedName.length - 1); + } + } + if (!context.enclosingDeclaration || !context.tracker.moduleResolverHost) { + // If there's no context declaration, we can't lookup a non-ambient specifier, so we just use the symbol name + if (ambientModuleSymbolRegex.test(symbol.escapedName)) { + return symbol.escapedName.substring(1, symbol.escapedName.length - 1); + } + return ts.getSourceFileOfNode(ts.getNonAugmentationDeclaration(symbol)).fileName; // A resolver may not be provided for baselines and errors - in those cases we use the fileName in full + } + var contextFile = ts.getSourceFileOfNode(ts.getOriginalNode(context.enclosingDeclaration)); + var links = getSymbolLinks(symbol); + var specifier = links.specifierCache && links.specifierCache.get(contextFile.path); + if (!specifier) { + var isBundle_1 = (compilerOptions.out || compilerOptions.outFile); + // For declaration bundles, we need to generate absolute paths relative to the common source dir for imports, + // just like how the declaration emitter does for the ambient module declarations - we can easily accomplish this + // using the `baseUrl` compiler option (which we would otherwise never use in declaration emit) and a non-relative + // specifier preference + var moduleResolverHost = context.tracker.moduleResolverHost; + var specifierCompilerOptions = isBundle_1 ? __assign({}, compilerOptions, { baseUrl: moduleResolverHost.getCommonSourceDirectory() }) : compilerOptions; + specifier = ts.first(ts.moduleSpecifiers.getModuleSpecifiers(symbol, specifierCompilerOptions, contextFile, moduleResolverHost, host.getSourceFiles(), { importModuleSpecifierPreference: isBundle_1 ? "non-relative" : "relative" }, host.redirectTargetsMap)); + links.specifierCache = links.specifierCache || ts.createMap(); + links.specifierCache.set(contextFile.path, specifier); + } + return specifier; + } + function symbolToTypeNode(symbol, context, meaning, overrideTypeArguments) { + var chain = lookupSymbolChain(symbol, context, meaning, !(context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */)); // If we're using aliases outside the current scope, dont bother with the module + var isTypeOf = meaning === 67220415 /* Value */; + if (ts.some(chain[0].declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { + // module is root, must use `ImportTypeNode` + var nonRootParts = chain.length > 1 ? createAccessFromSymbolChain(chain, chain.length - 1, 1) : undefined; + var typeParameterNodes = overrideTypeArguments || lookupTypeParameterNodes(chain, 0, context); + var specifier = getSpecifierForModuleSymbol(chain[0], context); + if (!(context.flags & 67108864 /* AllowNodeModulesRelativePaths */) && ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs && specifier.indexOf("/node_modules/") >= 0) { + // If ultimately we can only name the symbol with a reference that dives into a `node_modules` folder, we should error + // since declaration files with these kinds of references are liable to fail when published :( + context.encounteredError = true; + if (context.tracker.reportLikelyUnsafeImportRequiredError) { + context.tracker.reportLikelyUnsafeImportRequiredError(specifier); + } + } + var lit = ts.createLiteralTypeNode(ts.createLiteral(specifier)); + if (context.tracker.trackExternalModuleSymbolOfImportTypeNode) + context.tracker.trackExternalModuleSymbolOfImportTypeNode(chain[0]); + context.approximateLength += specifier.length + 10; // specifier + import("") + if (!nonRootParts || ts.isEntityName(nonRootParts)) { + if (nonRootParts) { + var lastId = ts.isIdentifier(nonRootParts) ? nonRootParts : nonRootParts.right; + lastId.typeArguments = undefined; + } + return ts.createImportTypeNode(lit, nonRootParts, typeParameterNodes, isTypeOf); + } + else { + var splitNode = getTopmostIndexedAccessType(nonRootParts); + var qualifier = splitNode.objectType.typeName; + return ts.createIndexedAccessTypeNode(ts.createImportTypeNode(lit, qualifier, typeParameterNodes, isTypeOf), splitNode.indexType); + } + } + var entityName = createAccessFromSymbolChain(chain, chain.length - 1, 0); + if (ts.isIndexedAccessTypeNode(entityName)) { + return entityName; // Indexed accesses can never be `typeof` + } + if (isTypeOf) { + return ts.createTypeQueryNode(entityName); + } + else { + var lastId = ts.isIdentifier(entityName) ? entityName : entityName.right; + var lastTypeArgs = lastId.typeArguments; + lastId.typeArguments = undefined; + return ts.createTypeReferenceNode(entityName, lastTypeArgs); + } + function createAccessFromSymbolChain(chain, index, stopper) { + var typeParameterNodes = index === (chain.length - 1) ? overrideTypeArguments : lookupTypeParameterNodes(chain, index, context); + var symbol = chain[index]; + if (index === 0) { + context.flags |= 16777216 /* InInitialEntityName */; + } + var symbolName = getNameOfSymbolAsWritten(symbol, context); + context.approximateLength += symbolName.length + 1; + if (index === 0) { + context.flags ^= 16777216 /* InInitialEntityName */; + } + var parent = chain[index - 1]; + if (!(context.flags & 16 /* ForbidIndexedAccessSymbolReferences */) && parent && getMembersOfSymbol(parent) && getMembersOfSymbol(parent).get(symbol.escapedName) === symbol) { + // Should use an indexed access + var LHS = createAccessFromSymbolChain(chain, index - 1, stopper); + if (ts.isIndexedAccessTypeNode(LHS)) { + return ts.createIndexedAccessTypeNode(LHS, ts.createLiteralTypeNode(ts.createLiteral(symbolName))); + } + else { + return ts.createIndexedAccessTypeNode(ts.createTypeReferenceNode(LHS, typeParameterNodes), ts.createLiteralTypeNode(ts.createLiteral(symbolName))); + } + } + var identifier = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216 /* NoAsciiEscaping */); + identifier.symbol = symbol; + if (index > stopper) { + var LHS = createAccessFromSymbolChain(chain, index - 1, stopper); + if (!ts.isEntityName(LHS)) { + return ts.Debug.fail("Impossible construct - an export of an indexed access cannot be reachable"); + } + return ts.createQualifiedName(LHS, identifier); + } + return identifier; + } + } + function symbolToName(symbol, context, meaning, expectsIdentifier) { + var chain = lookupSymbolChain(symbol, context, meaning); + if (expectsIdentifier && chain.length !== 1 + && !context.encounteredError + && !(context.flags & 65536 /* AllowQualifedNameInPlaceOfIdentifier */)) { + context.encounteredError = true; + } + return createEntityNameFromSymbolChain(chain, chain.length - 1); + function createEntityNameFromSymbolChain(chain, index) { + var typeParameterNodes = lookupTypeParameterNodes(chain, index, context); + var symbol = chain[index]; + if (index === 0) { + context.flags |= 16777216 /* InInitialEntityName */; + } + var symbolName = getNameOfSymbolAsWritten(symbol, context); + if (index === 0) { + context.flags ^= 16777216 /* InInitialEntityName */; + } + var identifier = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216 /* NoAsciiEscaping */); + identifier.symbol = symbol; + return index > 0 ? ts.createQualifiedName(createEntityNameFromSymbolChain(chain, index - 1), identifier) : identifier; + } + } + function symbolToExpression(symbol, context, meaning) { + var chain = lookupSymbolChain(symbol, context, meaning); + return createExpressionFromSymbolChain(chain, chain.length - 1); + function createExpressionFromSymbolChain(chain, index) { + var typeParameterNodes = lookupTypeParameterNodes(chain, index, context); + var symbol = chain[index]; + if (ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { + return ts.createLiteral(getSpecifierForModuleSymbol(symbol, context)); + } + if (index === 0) { + context.flags |= 16777216 /* InInitialEntityName */; + } + var symbolName = getNameOfSymbolAsWritten(symbol, context); + if (index === 0) { + context.flags ^= 16777216 /* InInitialEntityName */; + } + var firstChar = symbolName.charCodeAt(0); + var canUsePropertyAccess = ts.isIdentifierStart(firstChar, languageVersion); + if (index === 0 || canUsePropertyAccess) { + var identifier = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216 /* NoAsciiEscaping */); + identifier.symbol = symbol; + return index > 0 ? ts.createPropertyAccess(createExpressionFromSymbolChain(chain, index - 1), identifier) : identifier; + } + else { + if (firstChar === 91 /* openBracket */) { + symbolName = symbolName.substring(1, symbolName.length - 1); + firstChar = symbolName.charCodeAt(0); + } + var expression = void 0; + if (ts.isSingleOrDoubleQuote(firstChar)) { + expression = ts.createLiteral(symbolName.substring(1, symbolName.length - 1).replace(/\\./g, function (s) { return s.substring(1); })); + expression.singleQuote = firstChar === 39 /* singleQuote */; + } + else if (("" + +symbolName) === symbolName) { + expression = ts.createLiteral(+symbolName); + } + if (!expression) { + expression = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216 /* NoAsciiEscaping */); + expression.symbol = symbol; + } + return ts.createElementAccess(createExpressionFromSymbolChain(chain, index - 1), expression); + } + } + } + } + function typePredicateToString(typePredicate, enclosingDeclaration, flags, writer) { + if (flags === void 0) { flags = 16384 /* UseAliasDefinedOutsideCurrentScope */; } + return writer ? typePredicateToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(typePredicateToStringWorker); + function typePredicateToStringWorker(writer) { + var predicate = ts.createTypePredicateNode(typePredicate.kind === 1 /* Identifier */ ? ts.createIdentifier(typePredicate.parameterName) : ts.createThisTypeNode(), nodeBuilder.typeToTypeNode(typePredicate.type, enclosingDeclaration, toNodeBuilderFlags(flags) | 70221824 /* IgnoreErrors */ | 512 /* WriteTypeParametersInQualifiedName */)); + var printer = ts.createPrinter({ removeComments: true }); + var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); + printer.writeNode(4 /* Unspecified */, predicate, /*sourceFile*/ sourceFile, writer); + return writer; + } + } + function formatUnionTypes(types) { + var result = []; + var flags = 0; + for (var i = 0; i < types.length; i++) { + var t = types[i]; + flags |= t.flags; + if (!(t.flags & 98304 /* Nullable */)) { + if (t.flags & (512 /* BooleanLiteral */ | 1024 /* EnumLiteral */)) { + var baseType = t.flags & 512 /* BooleanLiteral */ ? booleanType : getBaseTypeOfEnumLiteralType(t); + if (baseType.flags & 1048576 /* Union */) { + var count = baseType.types.length; + if (i + count <= types.length && getRegularTypeOfLiteralType(types[i + count - 1]) === getRegularTypeOfLiteralType(baseType.types[count - 1])) { + result.push(baseType); + i += count - 1; + continue; + } + } + } + result.push(t); + } + } + if (flags & 65536 /* Null */) + result.push(nullType); + if (flags & 32768 /* Undefined */) + result.push(undefinedType); + return result || types; + } + function visibilityToString(flags) { + if (flags === 8 /* Private */) { + return "private"; + } + if (flags === 16 /* Protected */) { + return "protected"; + } + return "public"; + } + function getTypeAliasForTypeLiteral(type) { + if (type.symbol && type.symbol.flags & 2048 /* TypeLiteral */) { + var node = ts.findAncestor(type.symbol.declarations[0].parent, function (n) { return n.kind !== 177 /* ParenthesizedType */; }); + if (node.kind === 242 /* TypeAliasDeclaration */) { + return getSymbolOfNode(node); + } + } + return undefined; + } + function isTopLevelInExternalModuleAugmentation(node) { + return node && node.parent && + node.parent.kind === 245 /* ModuleBlock */ && + ts.isExternalModuleAugmentation(node.parent.parent); + } + function isDefaultBindingContext(location) { + return location.kind === 279 /* SourceFile */ || ts.isAmbientModule(location); + } + /** + * Gets a human-readable name for a symbol. + * Should *not* be used for the right-hand side of a `.` -- use `symbolName(symbol)` for that instead. + * + * Unlike `symbolName(symbol)`, this will include quotes if the name is from a string literal. + * It will also use a representation of a number as written instead of a decimal form, e.g. `0o11` instead of `9`. + */ + function getNameOfSymbolAsWritten(symbol, context) { + if (context && symbol.escapedName === "default" /* Default */ && !(context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */) && + // If it's not the first part of an entity name, it must print as `default` + (!(context.flags & 16777216 /* InInitialEntityName */) || + // if the symbol is synthesized, it will only be referenced externally it must print as `default` + !symbol.declarations || + // if not in the same binding context (source file, module declaration), it must print as `default` + (context.enclosingDeclaration && ts.findAncestor(symbol.declarations[0], isDefaultBindingContext) !== ts.findAncestor(context.enclosingDeclaration, isDefaultBindingContext)))) { + return "default"; + } + if (symbol.declarations && symbol.declarations.length) { + var declaration = symbol.declarations[0]; + var name = ts.getNameOfDeclaration(declaration); + if (name) { + if (ts.isCallExpression(declaration) && ts.isBindableObjectDefinePropertyCall(declaration)) { + return ts.symbolName(symbol); + } + return ts.declarationNameToString(name); + } + if (declaration.parent && declaration.parent.kind === 237 /* VariableDeclaration */) { + return ts.declarationNameToString(declaration.parent.name); + } + switch (declaration.kind) { + case 209 /* ClassExpression */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + if (context && !context.encounteredError && !(context.flags & 131072 /* AllowAnonymousIdentifier */)) { + context.encounteredError = true; + } + return declaration.kind === 209 /* ClassExpression */ ? "(Anonymous class)" : "(Anonymous function)"; + } + } + var nameType = symbol.nameType; + if (nameType) { + if (nameType.flags & 128 /* StringLiteral */ && !ts.isIdentifierText(nameType.value, compilerOptions.target)) { + return "\"" + ts.escapeString(nameType.value, 34 /* doubleQuote */) + "\""; + } + if (nameType && nameType.flags & 8192 /* UniqueESSymbol */) { + return "[" + getNameOfSymbolAsWritten(nameType.symbol, context) + "]"; + } + } + return ts.symbolName(symbol); + } + function isDeclarationVisible(node) { + if (node) { + var links = getNodeLinks(node); + if (links.isVisible === undefined) { + links.isVisible = !!determineIfDeclarationIsVisible(); + } + return links.isVisible; + } + return false; + function determineIfDeclarationIsVisible() { + switch (node.kind) { + case 297 /* JSDocCallbackTag */: + case 304 /* JSDocTypedefTag */: + // Top-level jsdoc type aliases are considered exported + // First parent is comment node, second is hosting declaration or token; we only care about those tokens or declarations whose parent is a source file + return !!(node.parent && node.parent.parent && node.parent.parent.parent && ts.isSourceFile(node.parent.parent.parent)); + case 186 /* BindingElement */: + return isDeclarationVisible(node.parent.parent); + case 237 /* VariableDeclaration */: + if (ts.isBindingPattern(node.name) && + !node.name.elements.length) { + // If the binding pattern is empty, this variable declaration is not visible + return false; + } + // falls through + case 244 /* ModuleDeclaration */: + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 239 /* FunctionDeclaration */: + case 243 /* EnumDeclaration */: + case 248 /* ImportEqualsDeclaration */: + // external module augmentation is always visible + if (ts.isExternalModuleAugmentation(node)) { + return true; + } + var parent = getDeclarationContainer(node); + // If the node is not exported or it is not ambient module element (except import declaration) + if (!(ts.getCombinedModifierFlags(node) & 1 /* Export */) && + !(node.kind !== 248 /* ImportEqualsDeclaration */ && parent.kind !== 279 /* SourceFile */ && parent.flags & 4194304 /* Ambient */)) { + return isGlobalSourceFile(parent); + } + // Exported members/ambient module elements (exception import declaration) are visible if parent is visible + return isDeclarationVisible(parent); + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + if (ts.hasModifier(node, 8 /* Private */ | 16 /* Protected */)) { + // Private/protected properties/methods are not visible + return false; + } + // Public properties/methods are visible if its parents are visible, so: + // falls through + case 157 /* Constructor */: + case 161 /* ConstructSignature */: + case 160 /* CallSignature */: + case 162 /* IndexSignature */: + case 151 /* Parameter */: + case 245 /* ModuleBlock */: + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + case 168 /* TypeLiteral */: + case 164 /* TypeReference */: + case 169 /* ArrayType */: + case 170 /* TupleType */: + case 173 /* UnionType */: + case 174 /* IntersectionType */: + case 177 /* ParenthesizedType */: + return isDeclarationVisible(node.parent); + // Default binding, import specifier and namespace import is visible + // only on demand so by default it is not visible + case 250 /* ImportClause */: + case 251 /* NamespaceImport */: + case 253 /* ImportSpecifier */: + return false; + // Type parameters are always visible + case 150 /* TypeParameter */: + // Source file and namespace export are always visible + case 279 /* SourceFile */: + case 247 /* NamespaceExportDeclaration */: + return true; + // Export assignments do not create name bindings outside the module + case 254 /* ExportAssignment */: + return false; + default: + return false; + } + } + } + function collectLinkedAliases(node, setVisibility) { + var exportSymbol; + if (node.parent && node.parent.kind === 254 /* ExportAssignment */) { + exportSymbol = resolveName(node, node.escapedText, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, node, /*isUse*/ false); + } + else if (node.parent.kind === 257 /* ExportSpecifier */) { + exportSymbol = getTargetOfExportSpecifier(node.parent, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); + } + var result; + if (exportSymbol) { + buildVisibleNodeList(exportSymbol.declarations); + } + return result; + function buildVisibleNodeList(declarations) { + ts.forEach(declarations, function (declaration) { + var resultNode = getAnyImportSyntax(declaration) || declaration; + if (setVisibility) { + getNodeLinks(declaration).isVisible = true; + } + else { + result = result || []; + ts.pushIfUnique(result, resultNode); + } + if (ts.isInternalModuleImportEqualsDeclaration(declaration)) { + // Add the referenced top container visible + var internalModuleReference = declaration.moduleReference; + var firstIdentifier = getFirstIdentifier(internalModuleReference); + var importSymbol = resolveName(declaration, firstIdentifier.escapedText, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */, undefined, undefined, /*isUse*/ false); + if (importSymbol) { + buildVisibleNodeList(importSymbol.declarations); + } + } + }); + } + } + /** + * Push an entry on the type resolution stack. If an entry with the given target and the given property name + * is already on the stack, and no entries in between already have a type, then a circularity has occurred. + * In this case, the result values of the existing entry and all entries pushed after it are changed to false, + * and the value false is returned. Otherwise, the new entry is just pushed onto the stack, and true is returned. + * In order to see if the same query has already been done before, the target object and the propertyName both + * must match the one passed in. + * + * @param target The symbol, type, or signature whose type is being queried + * @param propertyName The property name that should be used to query the target for its type + */ + function pushTypeResolution(target, propertyName) { + var resolutionCycleStartIndex = findResolutionCycleStartIndex(target, propertyName); + if (resolutionCycleStartIndex >= 0) { + // A cycle was found + var length_2 = resolutionTargets.length; + for (var i = resolutionCycleStartIndex; i < length_2; i++) { + resolutionResults[i] = false; + } + return false; + } + resolutionTargets.push(target); + resolutionResults.push(/*items*/ true); + resolutionPropertyNames.push(propertyName); + return true; + } + function findResolutionCycleStartIndex(target, propertyName) { + for (var i = resolutionTargets.length - 1; i >= 0; i--) { + if (hasType(resolutionTargets[i], resolutionPropertyNames[i])) { + return -1; + } + if (resolutionTargets[i] === target && resolutionPropertyNames[i] === propertyName) { + return i; + } + } + return -1; + } + function hasType(target, propertyName) { + switch (propertyName) { + case 0 /* Type */: + return !!getSymbolLinks(target).type; + case 5 /* EnumTagType */: + return !!(getNodeLinks(target).resolvedEnumType); + case 2 /* DeclaredType */: + return !!getSymbolLinks(target).declaredType; + case 1 /* ResolvedBaseConstructorType */: + return !!target.resolvedBaseConstructorType; + case 3 /* ResolvedReturnType */: + return !!target.resolvedReturnType; + case 4 /* ImmediateBaseConstraint */: + return !!target.immediateBaseConstraint; + case 6 /* JSDocTypeReference */: + return !!getSymbolLinks(target).resolvedJSDocType; + } + return ts.Debug.assertNever(propertyName); + } + // Pop an entry from the type resolution stack and return its associated result value. The result value will + // be true if no circularities were detected, or false if a circularity was found. + function popTypeResolution() { + resolutionTargets.pop(); + resolutionPropertyNames.pop(); + return resolutionResults.pop(); + } + function getDeclarationContainer(node) { + return ts.findAncestor(ts.getRootDeclaration(node), function (node) { + switch (node.kind) { + case 237 /* VariableDeclaration */: + case 238 /* VariableDeclarationList */: + case 253 /* ImportSpecifier */: + case 252 /* NamedImports */: + case 251 /* NamespaceImport */: + case 250 /* ImportClause */: + return false; + default: + return true; + } + }).parent; + } + function getTypeOfPrototypeProperty(prototype) { + // TypeScript 1.0 spec (April 2014): 8.4 + // Every class automatically contains a static property member named 'prototype', + // the type of which is an instantiation of the class type with type Any supplied as a type argument for each type parameter. + // It is an error to explicitly declare a static property member with the name 'prototype'. + var classType = getDeclaredTypeOfSymbol(getParentOfSymbol(prototype)); + return classType.typeParameters ? createTypeReference(classType, ts.map(classType.typeParameters, function (_) { return anyType; })) : classType; + } + // Return the type of the given property in the given type, or undefined if no such property exists + function getTypeOfPropertyOfType(type, name) { + var prop = getPropertyOfType(type, name); + return prop ? getTypeOfSymbol(prop) : undefined; + } + function isTypeAny(type) { + return type && (type.flags & 1 /* Any */) !== 0; + } + // Return the type of a binding element parent. We check SymbolLinks first to see if a type has been + // assigned by contextual typing. + function getTypeForBindingElementParent(node) { + var symbol = getSymbolOfNode(node); + return symbol && getSymbolLinks(symbol).type || getTypeForVariableLikeDeclaration(node, /*includeOptionality*/ false); + } + function isComputedNonLiteralName(name) { + return name.kind === 149 /* ComputedPropertyName */ && !ts.isStringOrNumericLiteralLike(name.expression); + } + function getRestType(source, properties, symbol) { + source = filterType(source, function (t) { return !(t.flags & 98304 /* Nullable */); }); + if (source.flags & 131072 /* Never */) { + return emptyObjectType; + } + if (source.flags & 1048576 /* Union */) { + return mapType(source, function (t) { return getRestType(t, properties, symbol); }); + } + var omitKeyType = getUnionType(ts.map(properties, getLiteralTypeFromPropertyName)); + if (isGenericObjectType(source) || isGenericIndexType(omitKeyType)) { + if (omitKeyType.flags & 131072 /* Never */) { + return source; + } + var pickTypeAlias = getGlobalPickSymbol(); + var excludeTypeAlias = getGlobalExcludeSymbol(); + if (!pickTypeAlias || !excludeTypeAlias) { + return errorType; + } + var pickKeys = getTypeAliasInstantiation(excludeTypeAlias, [getIndexType(source), omitKeyType]); + return getTypeAliasInstantiation(pickTypeAlias, [source, pickKeys]); + } + var members = ts.createSymbolTable(); + for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) { + var prop = _a[_i]; + if (!isTypeAssignableTo(getLiteralTypeFromProperty(prop, 8576 /* StringOrNumberLiteralOrUnique */), omitKeyType) + && !(ts.getDeclarationModifierFlagsFromSymbol(prop) & (8 /* Private */ | 16 /* Protected */)) + && isSpreadableProperty(prop)) { + members.set(prop.escapedName, getSpreadSymbol(prop)); + } + } + var stringIndexInfo = getIndexInfoOfType(source, 0 /* String */); + var numberIndexInfo = getIndexInfoOfType(source, 1 /* Number */); + return createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); + } + /** Return the inferred type for a binding element */ + function getTypeForBindingElement(declaration) { + var pattern = declaration.parent; + var parentType = getTypeForBindingElementParent(pattern.parent); + // If parent has the unknown (error) type, then so does this binding element + if (parentType === errorType) { + return errorType; + } + // If no type was specified or inferred for parent, + // infer from the initializer of the binding element if one is present. + // Otherwise, go with the undefined type of the parent. + if (!parentType) { + return declaration.initializer ? checkDeclarationInitializer(declaration) : parentType; + } + if (isTypeAny(parentType)) { + return parentType; + } + // Relax null check on ambient destructuring parameters, since the parameters have no implementation and are just documentation + if (strictNullChecks && declaration.flags & 4194304 /* Ambient */ && ts.isParameterDeclaration(declaration)) { + parentType = getNonNullableType(parentType); + } + var type; + if (pattern.kind === 184 /* ObjectBindingPattern */) { + if (declaration.dotDotDotToken) { + if (parentType.flags & 2 /* Unknown */ || !isValidSpreadType(parentType)) { + error(declaration, ts.Diagnostics.Rest_types_may_only_be_created_from_object_types); + return errorType; + } + var literalMembers = []; + for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (!element.dotDotDotToken) { + literalMembers.push(element.propertyName || element.name); + } + } + type = getRestType(parentType, literalMembers, declaration.symbol); + } + else { + // Use explicitly specified property name ({ p: xxx } form), or otherwise the implied name ({ p } form) + var name = declaration.propertyName || declaration.name; + var exprType = getLiteralTypeFromPropertyName(name); + var declaredType = checkIndexedAccessIndexType(getIndexedAccessType(parentType, exprType, name), name); + type = getFlowTypeOfReference(declaration, getConstraintForLocation(declaredType, declaration.name)); + } + } + else { + // This elementType will be used if the specific property corresponding to this index is not + // present (aka the tuple element property). This call also checks that the parentType is in + // fact an iterable or array (depending on target language). + var elementType = checkIteratedTypeOrElementType(parentType, pattern, /*allowStringInput*/ false, /*allowAsyncIterables*/ false); + var index_1 = pattern.elements.indexOf(declaration); + if (declaration.dotDotDotToken) { + // If the parent is a tuple type, the rest element has a tuple type of the + // remaining tuple element types. Otherwise, the rest element has an array type with same + // element type as the parent type. + type = everyType(parentType, isTupleType) ? + mapType(parentType, function (t) { return sliceTupleType(t, index_1); }) : + createArrayType(elementType); + } + else { + // Use specific property type when parent is a tuple or numeric index type when parent is an array + var index_2 = pattern.elements.indexOf(declaration); + type = everyType(parentType, isTupleLikeType) ? + getTupleElementType(parentType, index_2) || declaration.initializer && checkDeclarationInitializer(declaration) : + elementType; + if (!type) { + if (isTupleType(parentType)) { + error(declaration, ts.Diagnostics.Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2, typeToString(parentType), getTypeReferenceArity(parentType), pattern.elements.length); + } + else { + error(declaration, ts.Diagnostics.Type_0_has_no_property_1, typeToString(parentType), "" + index_2); + } + return errorType; + } + } + } + // In strict null checking mode, if a default value of a non-undefined type is specified, remove + // undefined from the final type. + if (strictNullChecks && declaration.initializer && !(getFalsyFlags(checkDeclarationInitializer(declaration)) & 32768 /* Undefined */)) { + type = getTypeWithFacts(type, 524288 /* NEUndefined */); + } + return declaration.initializer && !ts.getEffectiveTypeAnnotationNode(ts.walkUpBindingElementsAndPatterns(declaration)) ? + getUnionType([type, checkDeclarationInitializer(declaration)], 2 /* Subtype */) : + type; + } + function getTypeForDeclarationFromJSDocComment(declaration) { + var jsdocType = ts.getJSDocType(declaration); + if (jsdocType) { + return getTypeFromTypeNode(jsdocType); + } + return undefined; + } + function isNullOrUndefined(node) { + var expr = ts.skipParentheses(node); + return expr.kind === 96 /* NullKeyword */ || expr.kind === 72 /* Identifier */ && getResolvedSymbol(expr) === undefinedSymbol; + } + function isEmptyArrayLiteral(node) { + var expr = ts.skipParentheses(node); + return expr.kind === 187 /* ArrayLiteralExpression */ && expr.elements.length === 0; + } + function addOptionality(type, optional) { + if (optional === void 0) { optional = true; } + return strictNullChecks && optional ? getOptionalType(type) : type; + } + // Return the inferred type for a variable, parameter, or property declaration + function getTypeForVariableLikeDeclaration(declaration, includeOptionality) { + // A variable declared in a for..in statement is of type string, or of type keyof T when the + // right hand expression is of a type parameter type. + if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 226 /* ForInStatement */) { + var indexType = getIndexType(getNonNullableTypeIfNeeded(checkExpression(declaration.parent.parent.expression))); + return indexType.flags & (262144 /* TypeParameter */ | 4194304 /* Index */) ? getExtractStringType(indexType) : stringType; + } + if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 227 /* ForOfStatement */) { + // checkRightHandSideOfForOf will return undefined if the for-of expression type was + // missing properties/signatures required to get its iteratedType (like + // [Symbol.iterator] or next). This may be because we accessed properties from anyType, + // or it may have led to an error inside getElementTypeOfIterable. + var forOfStatement = declaration.parent.parent; + return checkRightHandSideOfForOf(forOfStatement.expression, forOfStatement.awaitModifier) || anyType; + } + if (ts.isBindingPattern(declaration.parent)) { + return getTypeForBindingElement(declaration); + } + var isOptional = includeOptionality && (ts.isParameter(declaration) && isJSDocOptionalParameter(declaration) + || !ts.isBindingElement(declaration) && !ts.isVariableDeclaration(declaration) && !!declaration.questionToken); + // Use type from type annotation if one is present + var declaredType = tryGetTypeFromEffectiveTypeNode(declaration); + if (declaredType) { + return addOptionality(declaredType, isOptional); + } + if ((noImplicitAny || ts.isInJSFile(declaration)) && + declaration.kind === 237 /* VariableDeclaration */ && !ts.isBindingPattern(declaration.name) && + !(ts.getCombinedModifierFlags(declaration) & 1 /* Export */) && !(declaration.flags & 4194304 /* Ambient */)) { + // If --noImplicitAny is on or the declaration is in a Javascript file, + // use control flow tracked 'any' type for non-ambient, non-exported var or let variables with no + // initializer or a 'null' or 'undefined' initializer. + if (!(ts.getCombinedNodeFlags(declaration) & 2 /* Const */) && (!declaration.initializer || isNullOrUndefined(declaration.initializer))) { + return autoType; + } + // Use control flow tracked 'any[]' type for non-ambient, non-exported variables with an empty array + // literal initializer. + if (declaration.initializer && isEmptyArrayLiteral(declaration.initializer)) { + return autoArrayType; + } + } + if (declaration.kind === 151 /* Parameter */) { + var func = declaration.parent; + // For a parameter of a set accessor, use the type of the get accessor if one is present + if (func.kind === 159 /* SetAccessor */ && !hasNonBindableDynamicName(func)) { + var getter = ts.getDeclarationOfKind(getSymbolOfNode(declaration.parent), 158 /* GetAccessor */); + if (getter) { + var getterSignature = getSignatureFromDeclaration(getter); + var thisParameter = getAccessorThisParameter(func); + if (thisParameter && declaration === thisParameter) { + // Use the type from the *getter* + ts.Debug.assert(!thisParameter.type); + return getTypeOfSymbol(getterSignature.thisParameter); + } + return getReturnTypeOfSignature(getterSignature); + } + } + if (ts.isInJSFile(declaration)) { + var typeTag = ts.getJSDocType(func); + if (typeTag && ts.isFunctionTypeNode(typeTag)) { + return getTypeAtPosition(getSignatureFromDeclaration(typeTag), func.parameters.indexOf(declaration)); + } + } + // Use contextual parameter type if one is available + var type = declaration.symbol.escapedName === "this" /* This */ ? getContextualThisParameterType(func) : getContextuallyTypedParameterType(declaration); + if (type) { + return addOptionality(type, isOptional); + } + } + else if (ts.isInJSFile(declaration)) { + var containerObjectType = getJSContainerObjectType(declaration, getSymbolOfNode(declaration), ts.getDeclaredExpandoInitializer(declaration)); + if (containerObjectType) { + return containerObjectType; + } + } + // Use the type of the initializer expression if one is present + if (declaration.initializer) { + var type = checkDeclarationInitializer(declaration); + return addOptionality(type, isOptional); + } + if (ts.isJsxAttribute(declaration)) { + // if JSX attribute doesn't have initializer, by default the attribute will have boolean value of true. + // I.e is sugar for + return trueType; + } + // If the declaration specifies a binding pattern, use the type implied by the binding pattern + if (ts.isBindingPattern(declaration.name)) { + return getTypeFromBindingPattern(declaration.name, /*includePatternInType*/ false, /*reportErrors*/ true); + } + // No type specified and nothing can be inferred + return undefined; + } + function getWidenedTypeFromAssignmentDeclaration(symbol, resolvedSymbol) { + // function/class/{} initializers are themselves containers, so they won't merge in the same way as other initializers + var container = ts.getAssignedExpandoInitializer(symbol.valueDeclaration); + if (container) { + var tag = ts.getJSDocTypeTag(container); + if (tag && tag.typeExpression) { + return getTypeFromTypeNode(tag.typeExpression); + } + var containerObjectType = getJSContainerObjectType(symbol.valueDeclaration, symbol, container); + return containerObjectType || getWidenedLiteralType(checkExpressionCached(container)); + } + var definedInConstructor = false; + var definedInMethod = false; + var jsdocType; + var types; + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + var expression = (ts.isBinaryExpression(declaration) || ts.isCallExpression(declaration)) ? declaration : + ts.isPropertyAccessExpression(declaration) ? ts.isBinaryExpression(declaration.parent) ? declaration.parent : declaration : + undefined; + if (!expression) { + return errorType; + } + var kind = ts.isPropertyAccessExpression(expression) ? ts.getAssignmentDeclarationPropertyAccessKind(expression) : ts.getAssignmentDeclarationKind(expression); + if (kind === 4 /* ThisProperty */) { + if (isDeclarationInConstructor(expression)) { + definedInConstructor = true; + } + else { + definedInMethod = true; + } + } + if (!ts.isCallExpression(expression)) { + jsdocType = getJSDocTypeFromAssignmentDeclaration(jsdocType, expression, symbol, declaration); + } + if (!jsdocType) { + (types || (types = [])).push((ts.isBinaryExpression(expression) || ts.isCallExpression(expression)) ? getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) : neverType); + } + } + var type = jsdocType; + if (!type) { + var constructorTypes = definedInConstructor ? getConstructorDefinedThisAssignmentTypes(types, symbol.declarations) : undefined; + // use only the constructor types unless they were only assigned null | undefined (including widening variants) + if (definedInMethod) { + var propType = getTypeOfAssignmentDeclarationPropertyOfBaseType(symbol); + if (propType) { + (constructorTypes || (constructorTypes = [])).push(propType); + definedInConstructor = true; + } + } + var sourceTypes = ts.some(constructorTypes, function (t) { return !!(t.flags & ~(98304 /* Nullable */ | 134217728 /* ContainsWideningType */)); }) ? constructorTypes : types; // TODO: GH#18217 + type = getUnionType(sourceTypes, 2 /* Subtype */); + } + var widened = getWidenedType(addOptionality(type, definedInMethod && !definedInConstructor)); + if (filterType(widened, function (t) { return !!(t.flags & ~98304 /* Nullable */); }) === neverType) { + reportImplicitAny(symbol.valueDeclaration, anyType); + return anyType; + } + return widened; + } + function getJSContainerObjectType(decl, symbol, init) { + if (!ts.isInJSFile(decl) || !init || !ts.isObjectLiteralExpression(init) || init.properties.length) { + return undefined; + } + var exports = ts.createSymbolTable(); + while (ts.isBinaryExpression(decl) || ts.isPropertyAccessExpression(decl)) { + var s_1 = getSymbolOfNode(decl); + if (s_1 && ts.hasEntries(s_1.exports)) { + mergeSymbolTable(exports, s_1.exports); + } + decl = ts.isBinaryExpression(decl) ? decl.parent : decl.parent.parent; + } + var s = getSymbolOfNode(decl); + if (s && ts.hasEntries(s.exports)) { + mergeSymbolTable(exports, s.exports); + } + var type = createAnonymousType(symbol, exports, ts.emptyArray, ts.emptyArray, undefined, undefined); + type.objectFlags |= 16384 /* JSLiteral */; + return type; + } + function getJSDocTypeFromAssignmentDeclaration(declaredType, expression, _symbol, declaration) { + var typeNode = ts.getJSDocType(expression.parent); + if (typeNode) { + var type = getWidenedType(getTypeFromTypeNode(typeNode)); + if (!declaredType) { + return type; + } + else if (declaredType !== errorType && type !== errorType && !isTypeIdenticalTo(declaredType, type)) { + errorNextVariableOrPropertyDeclarationMustHaveSameType(declaredType, declaration, type); + } + } + return declaredType; + } + /** If we don't have an explicit JSDoc type, get the type from the initializer. */ + function getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) { + if (ts.isCallExpression(expression)) { + if (resolvedSymbol) { + return getTypeOfSymbol(resolvedSymbol); // This shouldn't happen except under some hopefully forbidden merges of export assignments and object define assignments + } + var objectLitType = checkExpressionCached(expression.arguments[2]); + var valueType = getTypeOfPropertyOfType(objectLitType, "value"); + if (valueType) { + return valueType; + } + var getFunc = getTypeOfPropertyOfType(objectLitType, "get"); + if (getFunc) { + var getSig = getSingleCallSignature(getFunc); + if (getSig) { + return getReturnTypeOfSignature(getSig); + } + } + var setFunc = getTypeOfPropertyOfType(objectLitType, "set"); + if (setFunc) { + var setSig = getSingleCallSignature(setFunc); + if (setSig) { + return getTypeOfFirstParameterOfSignature(setSig); + } + } + return anyType; + } + var type = resolvedSymbol ? getTypeOfSymbol(resolvedSymbol) : getWidenedLiteralType(checkExpressionCached(expression.right)); + if (type.flags & 524288 /* Object */ && + kind === 2 /* ModuleExports */ && + symbol.escapedName === "export=" /* ExportEquals */) { + var exportedType_1 = resolveStructuredTypeMembers(type); + var members_3 = ts.createSymbolTable(); + ts.copyEntries(exportedType_1.members, members_3); + if (resolvedSymbol && !resolvedSymbol.exports) { + resolvedSymbol.exports = ts.createSymbolTable(); + } + (resolvedSymbol || symbol).exports.forEach(function (s, name) { + if (members_3.has(name)) { + var exportedMember = exportedType_1.members.get(name); + var union = createSymbol(s.flags | exportedMember.flags, name); + union.type = getUnionType([getTypeOfSymbol(s), getTypeOfSymbol(exportedMember)]); + members_3.set(name, union); + } + else { + members_3.set(name, s); + } + }); + var result = createAnonymousType(exportedType_1.symbol, members_3, exportedType_1.callSignatures, exportedType_1.constructSignatures, exportedType_1.stringIndexInfo, exportedType_1.numberIndexInfo); + result.objectFlags |= (ts.getObjectFlags(type) & 16384 /* JSLiteral */); // Propagate JSLiteral flag + return result; + } + if (isEmptyArrayLiteralType(type)) { + reportImplicitAny(expression, anyArrayType); + return anyArrayType; + } + return type; + } + function isDeclarationInConstructor(expression) { + var thisContainer = ts.getThisContainer(expression, /*includeArrowFunctions*/ false); + // Properties defined in a constructor (or base constructor, or javascript constructor function) don't get undefined added. + // Function expressions that are assigned to the prototype count as methods. + return thisContainer.kind === 157 /* Constructor */ || + thisContainer.kind === 239 /* FunctionDeclaration */ || + (thisContainer.kind === 196 /* FunctionExpression */ && !ts.isPrototypePropertyAssignment(thisContainer.parent)); + } + function getConstructorDefinedThisAssignmentTypes(types, declarations) { + ts.Debug.assert(types.length === declarations.length); + return types.filter(function (_, i) { + var declaration = declarations[i]; + var expression = ts.isBinaryExpression(declaration) ? declaration : + ts.isBinaryExpression(declaration.parent) ? declaration.parent : undefined; + return expression && isDeclarationInConstructor(expression); + }); + } + /** check for definition in base class if any declaration is in a class */ + function getTypeOfAssignmentDeclarationPropertyOfBaseType(property) { + var parentDeclaration = ts.forEach(property.declarations, function (d) { + var parent = ts.getThisContainer(d, /*includeArrowFunctions*/ false).parent; + return ts.isClassLike(parent) && parent; + }); + if (parentDeclaration) { + var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(parentDeclaration)); + var baseClassType = classType && getBaseTypes(classType)[0]; + if (baseClassType) { + return getTypeOfPropertyOfType(baseClassType, property.escapedName); + } + } + } + // Return the type implied by a binding pattern element. This is the type of the initializer of the element if + // one is present. Otherwise, if the element is itself a binding pattern, it is the type implied by the binding + // pattern. Otherwise, it is the type any. + function getTypeFromBindingElement(element, includePatternInType, reportErrors) { + if (element.initializer) { + return addOptionality(checkDeclarationInitializer(element)); + } + if (ts.isBindingPattern(element.name)) { + return getTypeFromBindingPattern(element.name, includePatternInType, reportErrors); + } + if (reportErrors && !declarationBelongsToPrivateAmbientMember(element)) { + reportImplicitAny(element, anyType); + } + return anyType; + } + // Return the type implied by an object binding pattern + function getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) { + var members = ts.createSymbolTable(); + var stringIndexInfo; + var objectFlags = 128 /* ObjectLiteral */; + ts.forEach(pattern.elements, function (e) { + var name = e.propertyName || e.name; + if (isComputedNonLiteralName(name)) { + // do not include computed properties in the implied type + objectFlags |= 512 /* ObjectLiteralPatternWithComputedProperties */; + return; + } + if (e.dotDotDotToken) { + stringIndexInfo = createIndexInfo(anyType, /*isReadonly*/ false); + return; + } + var text = ts.getTextOfPropertyName(name); + var flags = 4 /* Property */ | (e.initializer ? 16777216 /* Optional */ : 0); + var symbol = createSymbol(flags, text); + symbol.type = getTypeFromBindingElement(e, includePatternInType, reportErrors); + symbol.bindingElement = e; + members.set(symbol.escapedName, symbol); + }); + var result = createAnonymousType(undefined, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, undefined); + result.flags |= 268435456 /* ContainsObjectLiteral */; + result.objectFlags |= objectFlags; + if (includePatternInType) { + result.pattern = pattern; + } + return result; + } + // Return the type implied by an array binding pattern + function getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors) { + var elements = pattern.elements; + var lastElement = ts.lastOrUndefined(elements); + var hasRestElement = !!(lastElement && lastElement.kind === 186 /* BindingElement */ && lastElement.dotDotDotToken); + if (elements.length === 0 || elements.length === 1 && hasRestElement) { + return languageVersion >= 2 /* ES2015 */ ? createIterableType(anyType) : anyArrayType; + } + var elementTypes = ts.map(elements, function (e) { return ts.isOmittedExpression(e) ? anyType : getTypeFromBindingElement(e, includePatternInType, reportErrors); }); + var minLength = ts.findLastIndex(elements, function (e) { return !ts.isOmittedExpression(e) && !hasDefaultValue(e); }, elements.length - (hasRestElement ? 2 : 1)) + 1; + var result = createTupleType(elementTypes, minLength, hasRestElement); + if (includePatternInType) { + result = cloneTypeReference(result); + result.pattern = pattern; + } + return result; + } + // Return the type implied by a binding pattern. This is the type implied purely by the binding pattern itself + // and without regard to its context (i.e. without regard any type annotation or initializer associated with the + // declaration in which the binding pattern is contained). For example, the implied type of [x, y] is [any, any] + // and the implied type of { x, y: z = 1 } is { x: any; y: number; }. The type implied by a binding pattern is + // used as the contextual type of an initializer associated with the binding pattern. Also, for a destructuring + // parameter with no type annotation or initializer, the type implied by the binding pattern becomes the type of + // the parameter. + function getTypeFromBindingPattern(pattern, includePatternInType, reportErrors) { + if (includePatternInType === void 0) { includePatternInType = false; } + if (reportErrors === void 0) { reportErrors = false; } + return pattern.kind === 184 /* ObjectBindingPattern */ + ? getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) + : getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors); + } + // Return the type associated with a variable, parameter, or property declaration. In the simple case this is the type + // specified in a type annotation or inferred from an initializer. However, in the case of a destructuring declaration it + // is a bit more involved. For example: + // + // var [x, s = ""] = [1, "one"]; + // + // Here, the array literal [1, "one"] is contextually typed by the type [any, string], which is the implied type of the + // binding pattern [x, s = ""]. Because the contextual type is a tuple type, the resulting type of [1, "one"] is the + // tuple type [number, string]. Thus, the type inferred for 'x' is number and the type inferred for 's' is string. + function getWidenedTypeForVariableLikeDeclaration(declaration, reportErrors) { + return widenTypeForVariableLikeDeclaration(getTypeForVariableLikeDeclaration(declaration, /*includeOptionality*/ true), declaration, reportErrors); + } + function widenTypeForVariableLikeDeclaration(type, declaration, reportErrors) { + if (type) { + if (reportErrors) { + reportErrorsFromWidening(declaration, type); + } + // always widen a 'unique symbol' type if the type was created for a different declaration. + if (type.flags & 8192 /* UniqueESSymbol */ && (ts.isBindingElement(declaration) || !declaration.type) && type.symbol !== getSymbolOfNode(declaration)) { + type = esSymbolType; + } + return getWidenedType(type); + } + // Rest parameters default to type any[], other parameters default to type any + type = ts.isParameter(declaration) && declaration.dotDotDotToken ? anyArrayType : anyType; + // Report implicit any errors unless this is a private property within an ambient declaration + if (reportErrors) { + if (!declarationBelongsToPrivateAmbientMember(declaration)) { + reportImplicitAny(declaration, type); + } + } + return type; + } + function declarationBelongsToPrivateAmbientMember(declaration) { + var root = ts.getRootDeclaration(declaration); + var memberDeclaration = root.kind === 151 /* Parameter */ ? root.parent : root; + return isPrivateWithinAmbient(memberDeclaration); + } + function tryGetTypeFromEffectiveTypeNode(declaration) { + var typeNode = ts.getEffectiveTypeAnnotationNode(declaration); + if (typeNode) { + return getTypeFromTypeNode(typeNode); + } + } + function getTypeOfVariableOrParameterOrProperty(symbol) { + var links = getSymbolLinks(symbol); + return links.type || (links.type = getTypeOfVariableOrParameterOrPropertyWorker(symbol)); + } + function getTypeOfVariableOrParameterOrPropertyWorker(symbol) { + // Handle prototype property + if (symbol.flags & 4194304 /* Prototype */) { + return getTypeOfPrototypeProperty(symbol); + } + // CommonsJS require and module both have type any. + if (symbol === requireSymbol) { + return anyType; + } + if (symbol.flags & 134217728 /* ModuleExports */) { + var fileSymbol = getSymbolOfNode(ts.getSourceFileOfNode(symbol.valueDeclaration)); + var members = ts.createSymbolTable(); + members.set("exports", fileSymbol); + return createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, undefined, undefined); + } + // Handle catch clause variables + var declaration = symbol.valueDeclaration; + if (ts.isCatchClauseVariableDeclarationOrBindingElement(declaration)) { + return anyType; + } + // Handle export default expressions + if (ts.isSourceFile(declaration)) { + var jsonSourceFile = ts.cast(declaration, ts.isJsonSourceFile); + if (!jsonSourceFile.statements.length) { + return emptyObjectType; + } + var type_1 = getWidenedLiteralType(checkExpression(jsonSourceFile.statements[0].expression)); + if (type_1.flags & 524288 /* Object */) { + return getRegularTypeOfObjectLiteral(type_1); + } + return type_1; + } + if (declaration.kind === 254 /* ExportAssignment */) { + return widenTypeForVariableLikeDeclaration(checkExpressionCached(declaration.expression), declaration); + } + // Handle variable, parameter or property + if (!pushTypeResolution(symbol, 0 /* Type */)) { + return errorType; + } + var type; + if (ts.isInJSFile(declaration) && + (ts.isCallExpression(declaration) || ts.isBinaryExpression(declaration) || ts.isPropertyAccessExpression(declaration) && ts.isBinaryExpression(declaration.parent))) { + type = getWidenedTypeFromAssignmentDeclaration(symbol); + } + else if (ts.isJSDocPropertyLikeTag(declaration) + || ts.isPropertyAccessExpression(declaration) + || ts.isIdentifier(declaration) + || ts.isClassDeclaration(declaration) + || ts.isFunctionDeclaration(declaration) + || (ts.isMethodDeclaration(declaration) && !ts.isObjectLiteralMethod(declaration)) + || ts.isMethodSignature(declaration)) { + // Symbol is property of some kind that is merged with something - should use `getTypeOfFuncClassEnumModule` and not `getTypeOfVariableOrParameterOrProperty` + if (symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 384 /* Enum */ | 512 /* ValueModule */)) { + return getTypeOfFuncClassEnumModule(symbol); + } + type = ts.isBinaryExpression(declaration.parent) ? + getWidenedTypeFromAssignmentDeclaration(symbol) : + tryGetTypeFromEffectiveTypeNode(declaration) || anyType; + } + else if (ts.isPropertyAssignment(declaration)) { + type = tryGetTypeFromEffectiveTypeNode(declaration) || checkPropertyAssignment(declaration); + } + else if (ts.isJsxAttribute(declaration)) { + type = tryGetTypeFromEffectiveTypeNode(declaration) || checkJsxAttribute(declaration); + } + else if (ts.isShorthandPropertyAssignment(declaration)) { + type = tryGetTypeFromEffectiveTypeNode(declaration) || checkExpressionForMutableLocation(declaration.name, 0 /* Normal */); + } + else if (ts.isObjectLiteralMethod(declaration)) { + type = tryGetTypeFromEffectiveTypeNode(declaration) || checkObjectLiteralMethod(declaration, 0 /* Normal */); + } + else if (ts.isParameter(declaration) + || ts.isPropertyDeclaration(declaration) + || ts.isPropertySignature(declaration) + || ts.isVariableDeclaration(declaration) + || ts.isBindingElement(declaration)) { + type = getWidenedTypeForVariableLikeDeclaration(declaration, /*includeOptionality*/ true); + } + // getTypeOfSymbol dispatches some JS merges incorrectly because their symbol flags are not mutually exclusive. + // Re-dispatch based on valueDeclaration.kind instead. + else if (ts.isEnumDeclaration(declaration)) { + type = getTypeOfFuncClassEnumModule(symbol); + } + else if (ts.isEnumMember(declaration)) { + type = getTypeOfEnumMember(symbol); + } + else { + return ts.Debug.fail("Unhandled declaration kind! " + ts.Debug.showSyntaxKind(declaration) + " for " + ts.Debug.showSymbol(symbol)); + } + if (!popTypeResolution()) { + type = reportCircularityError(symbol); + } + return type; + } + function getAnnotatedAccessorTypeNode(accessor) { + if (accessor) { + if (accessor.kind === 158 /* GetAccessor */) { + var getterTypeAnnotation = ts.getEffectiveReturnTypeNode(accessor); + return getterTypeAnnotation; + } + else { + var setterTypeAnnotation = ts.getEffectiveSetAccessorTypeAnnotationNode(accessor); + return setterTypeAnnotation; + } + } + return undefined; + } + function getAnnotatedAccessorType(accessor) { + var node = getAnnotatedAccessorTypeNode(accessor); + return node && getTypeFromTypeNode(node); + } + function getAnnotatedAccessorThisParameter(accessor) { + var parameter = getAccessorThisParameter(accessor); + return parameter && parameter.symbol; + } + function getThisTypeOfDeclaration(declaration) { + return getThisTypeOfSignature(getSignatureFromDeclaration(declaration)); + } + function getTypeOfAccessors(symbol) { + var links = getSymbolLinks(symbol); + return links.type || (links.type = getTypeOfAccessorsWorker(symbol)); + } + function getTypeOfAccessorsWorker(symbol) { + var getter = ts.getDeclarationOfKind(symbol, 158 /* GetAccessor */); + var setter = ts.getDeclarationOfKind(symbol, 159 /* SetAccessor */); + if (getter && ts.isInJSFile(getter)) { + var jsDocType = getTypeForDeclarationFromJSDocComment(getter); + if (jsDocType) { + return jsDocType; + } + } + if (!pushTypeResolution(symbol, 0 /* Type */)) { + return errorType; + } + var type; + // First try to see if the user specified a return type on the get-accessor. + var getterReturnType = getAnnotatedAccessorType(getter); + if (getterReturnType) { + type = getterReturnType; + } + else { + // If the user didn't specify a return type, try to use the set-accessor's parameter type. + var setterParameterType = getAnnotatedAccessorType(setter); + if (setterParameterType) { + type = setterParameterType; + } + else { + // If there are no specified types, try to infer it from the body of the get accessor if it exists. + if (getter && getter.body) { + type = getReturnTypeFromBody(getter); + } + // Otherwise, fall back to 'any'. + else { + if (setter) { + errorOrSuggestion(noImplicitAny, setter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation, symbolToString(symbol)); + } + else { + ts.Debug.assert(!!getter, "there must existed getter as we are current checking either setter or getter in this function"); + errorOrSuggestion(noImplicitAny, getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); + } + type = anyType; + } + } + } + if (!popTypeResolution()) { + type = anyType; + if (noImplicitAny) { + var getter_1 = ts.getDeclarationOfKind(symbol, 158 /* GetAccessor */); + error(getter_1, ts.Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, symbolToString(symbol)); + } + } + return type; + } + function getBaseTypeVariableOfClass(symbol) { + var baseConstructorType = getBaseConstructorTypeOfClass(getDeclaredTypeOfClassOrInterface(symbol)); + return baseConstructorType.flags & 8650752 /* TypeVariable */ ? baseConstructorType : undefined; + } + function getTypeOfFuncClassEnumModule(symbol) { + var links = getSymbolLinks(symbol); + var originalLinks = links; + if (!links.type) { + var jsDeclaration = ts.getDeclarationOfExpando(symbol.valueDeclaration); + if (jsDeclaration) { + var jsSymbol = getSymbolOfNode(jsDeclaration); + if (jsSymbol && (ts.hasEntries(jsSymbol.exports) || ts.hasEntries(jsSymbol.members))) { + symbol = cloneSymbol(symbol); + // note:we overwrite links because we just cloned the symbol + links = symbol; + if (ts.hasEntries(jsSymbol.exports)) { + symbol.exports = symbol.exports || ts.createSymbolTable(); + mergeSymbolTable(symbol.exports, jsSymbol.exports); + } + if (ts.hasEntries(jsSymbol.members)) { + symbol.members = symbol.members || ts.createSymbolTable(); + mergeSymbolTable(symbol.members, jsSymbol.members); + } + } + } + originalLinks.type = links.type = getTypeOfFuncClassEnumModuleWorker(symbol); + } + return links.type; + } + function getTypeOfFuncClassEnumModuleWorker(symbol) { + var declaration = symbol.valueDeclaration; + if (symbol.flags & 1536 /* Module */ && ts.isShorthandAmbientModuleSymbol(symbol)) { + return anyType; + } + else if (declaration.kind === 204 /* BinaryExpression */ || + declaration.kind === 189 /* PropertyAccessExpression */ && declaration.parent.kind === 204 /* BinaryExpression */) { + return getWidenedTypeFromAssignmentDeclaration(symbol); + } + else if (symbol.flags & 512 /* ValueModule */ && declaration && ts.isSourceFile(declaration) && declaration.commonJsModuleIndicator) { + var resolvedModule = resolveExternalModuleSymbol(symbol); + if (resolvedModule !== symbol) { + if (!pushTypeResolution(symbol, 0 /* Type */)) { + return errorType; + } + var exportEquals = getMergedSymbol(symbol.exports.get("export=" /* ExportEquals */)); + var type_2 = getWidenedTypeFromAssignmentDeclaration(exportEquals, exportEquals === resolvedModule ? undefined : resolvedModule); + if (!popTypeResolution()) { + return reportCircularityError(symbol); + } + return type_2; + } + } + var type = createObjectType(16 /* Anonymous */, symbol); + if (symbol.flags & 32 /* Class */) { + var baseTypeVariable = getBaseTypeVariableOfClass(symbol); + return baseTypeVariable ? getIntersectionType([type, baseTypeVariable]) : type; + } + else { + return strictNullChecks && symbol.flags & 16777216 /* Optional */ ? getOptionalType(type) : type; + } + } + function getTypeOfEnumMember(symbol) { + var links = getSymbolLinks(symbol); + return links.type || (links.type = getDeclaredTypeOfEnumMember(symbol)); + } + function getTypeOfAlias(symbol) { + var links = getSymbolLinks(symbol); + if (!links.type) { + var targetSymbol = resolveAlias(symbol); + // It only makes sense to get the type of a value symbol. If the result of resolving + // the alias is not a value, then it has no type. To get the type associated with a + // type symbol, call getDeclaredTypeOfSymbol. + // This check is important because without it, a call to getTypeOfSymbol could end + // up recursively calling getTypeOfAlias, causing a stack overflow. + links.type = targetSymbol.flags & 67220415 /* Value */ + ? getTypeOfSymbol(targetSymbol) + : errorType; + } + return links.type; + } + function getTypeOfInstantiatedSymbol(symbol) { + var links = getSymbolLinks(symbol); + if (!links.type) { + if (!pushTypeResolution(symbol, 0 /* Type */)) { + return links.type = errorType; + } + var type = instantiateType(getTypeOfSymbol(links.target), links.mapper); + if (!popTypeResolution()) { + type = reportCircularityError(symbol); + } + links.type = type; + } + return links.type; + } + function reportCircularityError(symbol) { + // Check if variable has type annotation that circularly references the variable itself + if (ts.getEffectiveTypeAnnotationNode(symbol.valueDeclaration)) { + error(symbol.valueDeclaration, ts.Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_type_annotation, symbolToString(symbol)); + return errorType; + } + // Otherwise variable has initializer that circularly references the variable itself + if (noImplicitAny) { + error(symbol.valueDeclaration, ts.Diagnostics._0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer, symbolToString(symbol)); + } + return anyType; + } + function getTypeOfSymbol(symbol) { + if (ts.getCheckFlags(symbol) & 1 /* Instantiated */) { + return getTypeOfInstantiatedSymbol(symbol); + } + if (ts.getCheckFlags(symbol) & 2048 /* ReverseMapped */) { + return getTypeOfReverseMappedSymbol(symbol); + } + if (symbol.flags & (3 /* Variable */ | 4 /* Property */)) { + return getTypeOfVariableOrParameterOrProperty(symbol); + } + if (symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 384 /* Enum */ | 512 /* ValueModule */)) { + return getTypeOfFuncClassEnumModule(symbol); + } + if (symbol.flags & 8 /* EnumMember */) { + return getTypeOfEnumMember(symbol); + } + if (symbol.flags & 98304 /* Accessor */) { + return getTypeOfAccessors(symbol); + } + if (symbol.flags & 2097152 /* Alias */) { + return getTypeOfAlias(symbol); + } + return errorType; + } + function isReferenceToType(type, target) { + return type !== undefined + && target !== undefined + && (ts.getObjectFlags(type) & 4 /* Reference */) !== 0 + && type.target === target; + } + function getTargetType(type) { + return ts.getObjectFlags(type) & 4 /* Reference */ ? type.target : type; + } + // TODO: GH#18217 If `checkBase` is undefined, we should not call this because this will always return false. + function hasBaseType(type, checkBase) { + return check(type); + function check(type) { + if (ts.getObjectFlags(type) & (3 /* ClassOrInterface */ | 4 /* Reference */)) { + var target = getTargetType(type); + return target === checkBase || ts.some(getBaseTypes(target), check); + } + else if (type.flags & 2097152 /* Intersection */) { + return ts.some(type.types, check); + } + return false; + } + } + // Appends the type parameters given by a list of declarations to a set of type parameters and returns the resulting set. + // The function allocates a new array if the input type parameter set is undefined, but otherwise it modifies the set + // in-place and returns the same array. + function appendTypeParameters(typeParameters, declarations) { + for (var _i = 0, declarations_2 = declarations; _i < declarations_2.length; _i++) { + var declaration = declarations_2[_i]; + typeParameters = ts.appendIfUnique(typeParameters, getDeclaredTypeOfTypeParameter(getSymbolOfNode(declaration))); + } + return typeParameters; + } + // Return the outer type parameters of a node or undefined if the node has no outer type parameters. + function getOuterTypeParameters(node, includeThisTypes) { + while (true) { + node = node.parent; // TODO: GH#18217 Use SourceFile kind check instead + if (!node) { + return undefined; + } + switch (node.kind) { + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 241 /* InterfaceDeclaration */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 155 /* MethodSignature */: + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + case 289 /* JSDocFunctionType */: + case 239 /* FunctionDeclaration */: + case 156 /* MethodDeclaration */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 242 /* TypeAliasDeclaration */: + case 303 /* JSDocTemplateTag */: + case 304 /* JSDocTypedefTag */: + case 297 /* JSDocCallbackTag */: + case 181 /* MappedType */: + case 175 /* ConditionalType */: + var outerTypeParameters = getOuterTypeParameters(node, includeThisTypes); + if (node.kind === 181 /* MappedType */) { + return ts.append(outerTypeParameters, getDeclaredTypeOfTypeParameter(getSymbolOfNode(node.typeParameter))); + } + else if (node.kind === 175 /* ConditionalType */) { + return ts.concatenate(outerTypeParameters, getInferTypeParameters(node)); + } + var outerAndOwnTypeParameters = appendTypeParameters(outerTypeParameters, ts.getEffectiveTypeParameterDeclarations(node)); + var thisType = includeThisTypes && + (node.kind === 240 /* ClassDeclaration */ || node.kind === 209 /* ClassExpression */ || node.kind === 241 /* InterfaceDeclaration */) && + getDeclaredTypeOfClassOrInterface(getSymbolOfNode(node)).thisType; + return thisType ? ts.append(outerAndOwnTypeParameters, thisType) : outerAndOwnTypeParameters; + } + } + } + // The outer type parameters are those defined by enclosing generic classes, methods, or functions. + function getOuterTypeParametersOfClassOrInterface(symbol) { + var declaration = symbol.flags & 32 /* Class */ ? symbol.valueDeclaration : ts.getDeclarationOfKind(symbol, 241 /* InterfaceDeclaration */); + return getOuterTypeParameters(declaration); + } + // The local type parameters are the combined set of type parameters from all declarations of the class, + // interface, or type alias. + function getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) { + var result; + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var node = _a[_i]; + if (node.kind === 241 /* InterfaceDeclaration */ || + node.kind === 240 /* ClassDeclaration */ || + node.kind === 209 /* ClassExpression */ || + ts.isTypeAlias(node)) { + var declaration = node; + result = appendTypeParameters(result, ts.getEffectiveTypeParameterDeclarations(declaration)); + } + } + return result; + } + // The full set of type parameters for a generic class or interface type consists of its outer type parameters plus + // its locally declared type parameters. + function getTypeParametersOfClassOrInterface(symbol) { + return ts.concatenate(getOuterTypeParametersOfClassOrInterface(symbol), getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol)); + } + // A type is a mixin constructor if it has a single construct signature taking no type parameters and a single + // rest parameter of type any[]. + function isMixinConstructorType(type) { + var signatures = getSignaturesOfType(type, 1 /* Construct */); + if (signatures.length === 1) { + var s = signatures[0]; + return !s.typeParameters && s.parameters.length === 1 && s.hasRestParameter && getTypeOfParameter(s.parameters[0]) === anyArrayType; + } + return false; + } + function isConstructorType(type) { + if (isValidBaseType(type) && getSignaturesOfType(type, 1 /* Construct */).length > 0) { + return true; + } + if (type.flags & 8650752 /* TypeVariable */) { + var constraint = getBaseConstraintOfType(type); + return !!constraint && isValidBaseType(constraint) && isMixinConstructorType(constraint); + } + return isJSConstructorType(type); + } + function getBaseTypeNodeOfClass(type) { + return ts.getEffectiveBaseTypeNode(type.symbol.valueDeclaration); + } + function getConstructorsForTypeArguments(type, typeArgumentNodes, location) { + var typeArgCount = ts.length(typeArgumentNodes); + var isJavascript = ts.isInJSFile(location); + return ts.filter(getSignaturesOfType(type, 1 /* Construct */), function (sig) { return (isJavascript || typeArgCount >= getMinTypeArgumentCount(sig.typeParameters)) && typeArgCount <= ts.length(sig.typeParameters); }); + } + function getInstantiatedConstructorsForTypeArguments(type, typeArgumentNodes, location) { + var signatures = getConstructorsForTypeArguments(type, typeArgumentNodes, location); + var typeArguments = ts.map(typeArgumentNodes, getTypeFromTypeNode); + return ts.sameMap(signatures, function (sig) { return ts.some(sig.typeParameters) ? getSignatureInstantiation(sig, typeArguments, ts.isInJSFile(location)) : sig; }); + } + /** + * The base constructor of a class can resolve to + * * undefinedType if the class has no extends clause, + * * unknownType if an error occurred during resolution of the extends expression, + * * nullType if the extends expression is the null value, + * * anyType if the extends expression has type any, or + * * an object type with at least one construct signature. + */ + function getBaseConstructorTypeOfClass(type) { + if (!type.resolvedBaseConstructorType) { + var decl = type.symbol.valueDeclaration; + var extended = ts.getEffectiveBaseTypeNode(decl); + var baseTypeNode = getBaseTypeNodeOfClass(type); + if (!baseTypeNode) { + return type.resolvedBaseConstructorType = undefinedType; + } + if (!pushTypeResolution(type, 1 /* ResolvedBaseConstructorType */)) { + return errorType; + } + var baseConstructorType = checkExpression(baseTypeNode.expression); + if (extended && baseTypeNode !== extended) { + ts.Debug.assert(!extended.typeArguments); // Because this is in a JS file, and baseTypeNode is in an @extends tag + checkExpression(extended.expression); + } + if (baseConstructorType.flags & (524288 /* Object */ | 2097152 /* Intersection */)) { + // Resolving the members of a class requires us to resolve the base class of that class. + // We force resolution here such that we catch circularities now. + resolveStructuredTypeMembers(baseConstructorType); + } + if (!popTypeResolution()) { + error(type.symbol.valueDeclaration, ts.Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_base_expression, symbolToString(type.symbol)); + return type.resolvedBaseConstructorType = errorType; + } + if (!(baseConstructorType.flags & 1 /* Any */) && baseConstructorType !== nullWideningType && !isConstructorType(baseConstructorType)) { + var err = error(baseTypeNode.expression, ts.Diagnostics.Type_0_is_not_a_constructor_function_type, typeToString(baseConstructorType)); + if (baseConstructorType.flags & 262144 /* TypeParameter */) { + var constraint = getConstraintFromTypeParameter(baseConstructorType); + var ctorReturn = unknownType; + if (constraint) { + var ctorSig = getSignaturesOfType(constraint, 1 /* Construct */); + if (ctorSig[0]) { + ctorReturn = getReturnTypeOfSignature(ctorSig[0]); + } + } + addRelatedInfo(err, ts.createDiagnosticForNode(baseConstructorType.symbol.declarations[0], ts.Diagnostics.Did_you_mean_for_0_to_be_constrained_to_type_new_args_Colon_any_1, symbolToString(baseConstructorType.symbol), typeToString(ctorReturn))); + } + return type.resolvedBaseConstructorType = errorType; + } + type.resolvedBaseConstructorType = baseConstructorType; + } + return type.resolvedBaseConstructorType; + } + function getBaseTypes(type) { + if (!type.resolvedBaseTypes) { + if (type.objectFlags & 8 /* Tuple */) { + type.resolvedBaseTypes = [createArrayType(getUnionType(type.typeParameters || ts.emptyArray))]; + } + else if (type.symbol.flags & (32 /* Class */ | 64 /* Interface */)) { + if (type.symbol.flags & 32 /* Class */) { + resolveBaseTypesOfClass(type); + } + if (type.symbol.flags & 64 /* Interface */) { + resolveBaseTypesOfInterface(type); + } + } + else { + ts.Debug.fail("type must be class or interface"); + } + } + return type.resolvedBaseTypes; + } + function resolveBaseTypesOfClass(type) { + type.resolvedBaseTypes = ts.resolvingEmptyArray; + var baseConstructorType = getApparentType(getBaseConstructorTypeOfClass(type)); + if (!(baseConstructorType.flags & (524288 /* Object */ | 2097152 /* Intersection */ | 1 /* Any */))) { + return type.resolvedBaseTypes = ts.emptyArray; + } + var baseTypeNode = getBaseTypeNodeOfClass(type); + var typeArgs = typeArgumentsFromTypeReferenceNode(baseTypeNode); + var baseType; + var originalBaseType = isJSConstructorType(baseConstructorType) ? baseConstructorType : + baseConstructorType.symbol ? getDeclaredTypeOfSymbol(baseConstructorType.symbol) : + undefined; + if (baseConstructorType.symbol && baseConstructorType.symbol.flags & 32 /* Class */ && + areAllOuterTypeParametersApplied(originalBaseType)) { + // When base constructor type is a class with no captured type arguments we know that the constructors all have the same type parameters as the + // class and all return the instance type of the class. There is no need for further checks and we can apply the + // type arguments in the same manner as a type reference to get the same error reporting experience. + baseType = getTypeFromClassOrInterfaceReference(baseTypeNode, baseConstructorType.symbol, typeArgs); + } + else if (baseConstructorType.flags & 1 /* Any */) { + baseType = baseConstructorType; + } + else if (isJSConstructorType(baseConstructorType)) { + baseType = !baseTypeNode.typeArguments && getJSClassType(baseConstructorType.symbol) || anyType; + } + else { + // The class derives from a "class-like" constructor function, check that we have at least one construct signature + // with a matching number of type parameters and use the return type of the first instantiated signature. Elsewhere + // we check that all instantiated signatures return the same type. + var constructors = getInstantiatedConstructorsForTypeArguments(baseConstructorType, baseTypeNode.typeArguments, baseTypeNode); + if (!constructors.length) { + error(baseTypeNode.expression, ts.Diagnostics.No_base_constructor_has_the_specified_number_of_type_arguments); + return type.resolvedBaseTypes = ts.emptyArray; + } + baseType = getReturnTypeOfSignature(constructors[0]); + } + if (baseType === errorType) { + return type.resolvedBaseTypes = ts.emptyArray; + } + if (!isValidBaseType(baseType)) { + error(baseTypeNode.expression, ts.Diagnostics.Base_constructor_return_type_0_is_not_an_object_type_or_intersection_of_object_types_with_statically_known_members, typeToString(baseType)); + return type.resolvedBaseTypes = ts.emptyArray; + } + if (type === baseType || hasBaseType(baseType, type)) { + error(type.symbol.valueDeclaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, /*enclosingDeclaration*/ undefined, 2 /* WriteArrayAsGenericType */)); + return type.resolvedBaseTypes = ts.emptyArray; + } + if (type.resolvedBaseTypes === ts.resolvingEmptyArray) { + // Circular reference, likely through instantiation of default parameters + // (otherwise there'd be an error from hasBaseType) - this is fine, but `.members` should be reset + // as `getIndexedAccessType` via `instantiateType` via `getTypeFromClassOrInterfaceReference` forces a + // partial instantiation of the members without the base types fully resolved + type.members = undefined; + } + return type.resolvedBaseTypes = [baseType]; + } + function areAllOuterTypeParametersApplied(type) { + // An unapplied type parameter has its symbol still the same as the matching argument symbol. + // Since parameters are applied outer-to-inner, only the last outer parameter needs to be checked. + var outerTypeParameters = type.outerTypeParameters; + if (outerTypeParameters) { + var last_1 = outerTypeParameters.length - 1; + var typeArguments = type.typeArguments; + return outerTypeParameters[last_1].symbol !== typeArguments[last_1].symbol; + } + return true; + } + // A valid base type is `any`, any non-generic object type or intersection of non-generic + // object types. + function isValidBaseType(type) { + return !!(type.flags & (524288 /* Object */ | 67108864 /* NonPrimitive */ | 1 /* Any */)) && !isGenericMappedType(type) || + !!(type.flags & 2097152 /* Intersection */) && ts.every(type.types, isValidBaseType); + } + function resolveBaseTypesOfInterface(type) { + type.resolvedBaseTypes = type.resolvedBaseTypes || ts.emptyArray; + for (var _i = 0, _a = type.symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (declaration.kind === 241 /* InterfaceDeclaration */ && ts.getInterfaceBaseTypeNodes(declaration)) { + for (var _b = 0, _c = ts.getInterfaceBaseTypeNodes(declaration); _b < _c.length; _b++) { + var node = _c[_b]; + var baseType = getTypeFromTypeNode(node); + if (baseType !== errorType) { + if (isValidBaseType(baseType)) { + if (type !== baseType && !hasBaseType(baseType, type)) { + if (type.resolvedBaseTypes === ts.emptyArray) { + type.resolvedBaseTypes = [baseType]; + } + else { + type.resolvedBaseTypes.push(baseType); + } + } + else { + error(declaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, /*enclosingDeclaration*/ undefined, 2 /* WriteArrayAsGenericType */)); + } + } + else { + error(node, ts.Diagnostics.An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_members); + } + } + } + } + } + } + /** + * Returns true if the interface given by the symbol is free of "this" references. + * + * Specifically, the result is true if the interface itself contains no references + * to "this" in its body, if all base types are interfaces, + * and if none of the base interfaces have a "this" type. + */ + function isThislessInterface(symbol) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (declaration.kind === 241 /* InterfaceDeclaration */) { + if (declaration.flags & 64 /* ContainsThis */) { + return false; + } + var baseTypeNodes = ts.getInterfaceBaseTypeNodes(declaration); + if (baseTypeNodes) { + for (var _b = 0, baseTypeNodes_1 = baseTypeNodes; _b < baseTypeNodes_1.length; _b++) { + var node = baseTypeNodes_1[_b]; + if (ts.isEntityNameExpression(node.expression)) { + var baseSymbol = resolveEntityName(node.expression, 67897832 /* Type */, /*ignoreErrors*/ true); + if (!baseSymbol || !(baseSymbol.flags & 64 /* Interface */) || getDeclaredTypeOfClassOrInterface(baseSymbol).thisType) { + return false; + } + } + } + } + } + } + return true; + } + function getDeclaredTypeOfClassOrInterface(symbol) { + var links = getSymbolLinks(symbol); + if (!links.declaredType) { + var kind = symbol.flags & 32 /* Class */ ? 1 /* Class */ : 2 /* Interface */; + var type = links.declaredType = createObjectType(kind, symbol); + var outerTypeParameters = getOuterTypeParametersOfClassOrInterface(symbol); + var localTypeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); + // A class or interface is generic if it has type parameters or a "this" type. We always give classes a "this" type + // because it is not feasible to analyze all members to determine if the "this" type escapes the class (in particular, + // property types inferred from initializers and method return types inferred from return statements are very hard + // to exhaustively analyze). We give interfaces a "this" type if we can't definitely determine that they are free of + // "this" references. + if (outerTypeParameters || localTypeParameters || kind === 1 /* Class */ || !isThislessInterface(symbol)) { + type.objectFlags |= 4 /* Reference */; + type.typeParameters = ts.concatenate(outerTypeParameters, localTypeParameters); + type.outerTypeParameters = outerTypeParameters; + type.localTypeParameters = localTypeParameters; + type.instantiations = ts.createMap(); + type.instantiations.set(getTypeListId(type.typeParameters), type); + type.target = type; + type.typeArguments = type.typeParameters; + type.thisType = createType(262144 /* TypeParameter */); + type.thisType.isThisType = true; + type.thisType.symbol = symbol; + type.thisType.constraint = type; + } + } + return links.declaredType; + } + function getDeclaredTypeOfTypeAlias(symbol) { + var links = getSymbolLinks(symbol); + if (!links.declaredType) { + // Note that we use the links object as the target here because the symbol object is used as the unique + // identity for resolution of the 'type' property in SymbolLinks. + if (!pushTypeResolution(symbol, 2 /* DeclaredType */)) { + return errorType; + } + var declaration = ts.find(symbol.declarations, function (d) { + return ts.isJSDocTypeAlias(d) || d.kind === 242 /* TypeAliasDeclaration */; + }); + var typeNode = ts.isJSDocTypeAlias(declaration) ? declaration.typeExpression : declaration.type; + // If typeNode is missing, we will error in checkJSDocTypedefTag. + var type = typeNode ? getTypeFromTypeNode(typeNode) : errorType; + if (popTypeResolution()) { + var typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); + if (typeParameters) { + // Initialize the instantiation cache for generic type aliases. The declared type corresponds to + // an instantiation of the type alias with the type parameters supplied as type arguments. + links.typeParameters = typeParameters; + links.instantiations = ts.createMap(); + links.instantiations.set(getTypeListId(typeParameters), type); + } + } + else { + type = errorType; + error(declaration.name, ts.Diagnostics.Type_alias_0_circularly_references_itself, symbolToString(symbol)); + } + links.declaredType = type; + } + return links.declaredType; + } + function isStringConcatExpression(expr) { + if (expr.kind === 10 /* StringLiteral */) { + return true; + } + else if (expr.kind === 204 /* BinaryExpression */) { + return isStringConcatExpression(expr.left) && isStringConcatExpression(expr.right); + } + return false; + } + function isLiteralEnumMember(member) { + var expr = member.initializer; + if (!expr) { + return !(member.flags & 4194304 /* Ambient */); + } + switch (expr.kind) { + case 10 /* StringLiteral */: + case 8 /* NumericLiteral */: + return true; + case 202 /* PrefixUnaryExpression */: + return expr.operator === 39 /* MinusToken */ && + expr.operand.kind === 8 /* NumericLiteral */; + case 72 /* Identifier */: + return ts.nodeIsMissing(expr) || !!getSymbolOfNode(member.parent).exports.get(expr.escapedText); + case 204 /* BinaryExpression */: + return isStringConcatExpression(expr); + default: + return false; + } + } + function getEnumKind(symbol) { + var links = getSymbolLinks(symbol); + if (links.enumKind !== undefined) { + return links.enumKind; + } + var hasNonLiteralMember = false; + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (declaration.kind === 243 /* EnumDeclaration */) { + for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { + var member = _c[_b]; + if (member.initializer && member.initializer.kind === 10 /* StringLiteral */) { + return links.enumKind = 1 /* Literal */; + } + if (!isLiteralEnumMember(member)) { + hasNonLiteralMember = true; + } + } + } + } + return links.enumKind = hasNonLiteralMember ? 0 /* Numeric */ : 1 /* Literal */; + } + function getBaseTypeOfEnumLiteralType(type) { + return type.flags & 1024 /* EnumLiteral */ && !(type.flags & 1048576 /* Union */) ? getDeclaredTypeOfSymbol(getParentOfSymbol(type.symbol)) : type; + } + function getDeclaredTypeOfEnum(symbol) { + var links = getSymbolLinks(symbol); + if (links.declaredType) { + return links.declaredType; + } + if (getEnumKind(symbol) === 1 /* Literal */) { + enumCount++; + var memberTypeList = []; + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (declaration.kind === 243 /* EnumDeclaration */) { + for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { + var member = _c[_b]; + var memberType = getFreshTypeOfLiteralType(getLiteralType(getEnumMemberValue(member), enumCount, getSymbolOfNode(member))); // TODO: GH#18217 + getSymbolLinks(getSymbolOfNode(member)).declaredType = memberType; + memberTypeList.push(getRegularTypeOfLiteralType(memberType)); + } + } + } + if (memberTypeList.length) { + var enumType_1 = getUnionType(memberTypeList, 1 /* Literal */, symbol, /*aliasTypeArguments*/ undefined); + if (enumType_1.flags & 1048576 /* Union */) { + enumType_1.flags |= 1024 /* EnumLiteral */; + enumType_1.symbol = symbol; + } + return links.declaredType = enumType_1; + } + } + var enumType = createType(32 /* Enum */); + enumType.symbol = symbol; + return links.declaredType = enumType; + } + function getDeclaredTypeOfEnumMember(symbol) { + var links = getSymbolLinks(symbol); + if (!links.declaredType) { + var enumType = getDeclaredTypeOfEnum(getParentOfSymbol(symbol)); + if (!links.declaredType) { + links.declaredType = enumType; + } + } + return links.declaredType; + } + function getDeclaredTypeOfTypeParameter(symbol) { + var links = getSymbolLinks(symbol); + if (!links.declaredType) { + var type = createType(262144 /* TypeParameter */); + type.symbol = symbol; + links.declaredType = type; + } + return links.declaredType; + } + function getDeclaredTypeOfAlias(symbol) { + var links = getSymbolLinks(symbol); + if (!links.declaredType) { + links.declaredType = getDeclaredTypeOfSymbol(resolveAlias(symbol)); + } + return links.declaredType; + } + function getDeclaredTypeOfSymbol(symbol) { + return tryGetDeclaredTypeOfSymbol(symbol) || errorType; + } + function tryGetDeclaredTypeOfSymbol(symbol) { + if (symbol.flags & (32 /* Class */ | 64 /* Interface */)) { + return getDeclaredTypeOfClassOrInterface(symbol); + } + if (symbol.flags & 524288 /* TypeAlias */) { + return getDeclaredTypeOfTypeAlias(symbol); + } + if (symbol.flags & 262144 /* TypeParameter */) { + return getDeclaredTypeOfTypeParameter(symbol); + } + if (symbol.flags & 384 /* Enum */) { + return getDeclaredTypeOfEnum(symbol); + } + if (symbol.flags & 8 /* EnumMember */) { + return getDeclaredTypeOfEnumMember(symbol); + } + if (symbol.flags & 2097152 /* Alias */) { + return getDeclaredTypeOfAlias(symbol); + } + return undefined; + } + /** + * A type is free of this references if it's the any, string, number, boolean, symbol, or void keyword, a string + * literal type, an array with an element type that is free of this references, or a type reference that is + * free of this references. + */ + function isThislessType(node) { + switch (node.kind) { + case 120 /* AnyKeyword */: + case 143 /* UnknownKeyword */: + case 138 /* StringKeyword */: + case 135 /* NumberKeyword */: + case 146 /* BigIntKeyword */: + case 123 /* BooleanKeyword */: + case 139 /* SymbolKeyword */: + case 136 /* ObjectKeyword */: + case 106 /* VoidKeyword */: + case 141 /* UndefinedKeyword */: + case 96 /* NullKeyword */: + case 132 /* NeverKeyword */: + case 182 /* LiteralType */: + return true; + case 169 /* ArrayType */: + return isThislessType(node.elementType); + case 164 /* TypeReference */: + return !node.typeArguments || node.typeArguments.every(isThislessType); + } + return false; + } + /** A type parameter is thisless if its contraint is thisless, or if it has no constraint. */ + function isThislessTypeParameter(node) { + var constraint = ts.getEffectiveConstraintOfTypeParameter(node); + return !constraint || isThislessType(constraint); + } + /** + * A variable-like declaration is free of this references if it has a type annotation + * that is thisless, or if it has no type annotation and no initializer (and is thus of type any). + */ + function isThislessVariableLikeDeclaration(node) { + var typeNode = ts.getEffectiveTypeAnnotationNode(node); + return typeNode ? isThislessType(typeNode) : !ts.hasInitializer(node); + } + /** + * A function-like declaration is considered free of `this` references if it has a return type + * annotation that is free of this references and if each parameter is thisless and if + * each type parameter (if present) is thisless. + */ + function isThislessFunctionLikeDeclaration(node) { + var returnType = ts.getEffectiveReturnTypeNode(node); + var typeParameters = ts.getEffectiveTypeParameterDeclarations(node); + return (node.kind === 157 /* Constructor */ || (!!returnType && isThislessType(returnType))) && + node.parameters.every(isThislessVariableLikeDeclaration) && + typeParameters.every(isThislessTypeParameter); + } + /** + * Returns true if the class or interface member given by the symbol is free of "this" references. The + * function may return false for symbols that are actually free of "this" references because it is not + * feasible to perform a complete analysis in all cases. In particular, property members with types + * inferred from their initializers and function members with inferred return types are conservatively + * assumed not to be free of "this" references. + */ + function isThisless(symbol) { + if (symbol.declarations && symbol.declarations.length === 1) { + var declaration = symbol.declarations[0]; + if (declaration) { + switch (declaration.kind) { + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + return isThislessVariableLikeDeclaration(declaration); + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 157 /* Constructor */: + return isThislessFunctionLikeDeclaration(declaration); + } + } + } + return false; + } + // The mappingThisOnly flag indicates that the only type parameter being mapped is "this". When the flag is true, + // we check symbols to see if we can quickly conclude they are free of "this" references, thus needing no instantiation. + function createInstantiatedSymbolTable(symbols, mapper, mappingThisOnly) { + var result = ts.createSymbolTable(); + for (var _i = 0, symbols_2 = symbols; _i < symbols_2.length; _i++) { + var symbol = symbols_2[_i]; + result.set(symbol.escapedName, mappingThisOnly && isThisless(symbol) ? symbol : instantiateSymbol(symbol, mapper)); + } + return result; + } + function addInheritedMembers(symbols, baseSymbols) { + for (var _i = 0, baseSymbols_1 = baseSymbols; _i < baseSymbols_1.length; _i++) { + var s = baseSymbols_1[_i]; + if (!symbols.has(s.escapedName)) { + symbols.set(s.escapedName, s); + } + } + } + function resolveDeclaredMembers(type) { + if (!type.declaredProperties) { + var symbol = type.symbol; + var members = getMembersOfSymbol(symbol); + type.declaredProperties = getNamedMembers(members); + // Start with signatures at empty array in case of recursive types + type.declaredCallSignatures = ts.emptyArray; + type.declaredConstructSignatures = ts.emptyArray; + type.declaredCallSignatures = getSignaturesOfSymbol(members.get("__call" /* Call */)); + type.declaredConstructSignatures = getSignaturesOfSymbol(members.get("__new" /* New */)); + type.declaredStringIndexInfo = getIndexInfoOfSymbol(symbol, 0 /* String */); + type.declaredNumberIndexInfo = getIndexInfoOfSymbol(symbol, 1 /* Number */); + } + return type; + } + /** + * Indicates whether a type can be used as a late-bound name. + */ + function isTypeUsableAsLateBoundName(type) { + return !!(type.flags & 8576 /* StringOrNumberLiteralOrUnique */); + } + /** + * Indicates whether a declaration name is definitely late-bindable. + * A declaration name is only late-bindable if: + * - It is a `ComputedPropertyName`. + * - Its expression is an `Identifier` or either a `PropertyAccessExpression` an + * `ElementAccessExpression` consisting only of these same three types of nodes. + * - The type of its expression is a string or numeric literal type, or is a `unique symbol` type. + */ + function isLateBindableName(node) { + return ts.isComputedPropertyName(node) + && ts.isEntityNameExpression(node.expression) + && isTypeUsableAsLateBoundName(checkComputedPropertyName(node)); + } + function isLateBoundName(name) { + return name.charCodeAt(0) === 95 /* _ */ && + name.charCodeAt(1) === 95 /* _ */ && + name.charCodeAt(2) === 64 /* at */; + } + /** + * Indicates whether a declaration has a late-bindable dynamic name. + */ + function hasLateBindableName(node) { + var name = ts.getNameOfDeclaration(node); + return !!name && isLateBindableName(name); + } + /** + * Indicates whether a declaration has a dynamic name that cannot be late-bound. + */ + function hasNonBindableDynamicName(node) { + return ts.hasDynamicName(node) && !hasLateBindableName(node); + } + /** + * Indicates whether a declaration name is a dynamic name that cannot be late-bound. + */ + function isNonBindableDynamicName(node) { + return ts.isDynamicName(node) && !isLateBindableName(node); + } + /** + * Gets the symbolic name for a late-bound member from its type. + */ + function getLateBoundNameFromType(type) { + if (type.flags & 8192 /* UniqueESSymbol */) { + return "__@" + type.symbol.escapedName + "@" + getSymbolId(type.symbol); + } + if (type.flags & (128 /* StringLiteral */ | 256 /* NumberLiteral */)) { + return ts.escapeLeadingUnderscores("" + type.value); + } + return ts.Debug.fail(); + } + /** + * Adds a declaration to a late-bound dynamic member. This performs the same function for + * late-bound members that `addDeclarationToSymbol` in binder.ts performs for early-bound + * members. + */ + function addDeclarationToLateBoundSymbol(symbol, member, symbolFlags) { + ts.Debug.assert(!!(ts.getCheckFlags(symbol) & 1024 /* Late */), "Expected a late-bound symbol."); + symbol.flags |= symbolFlags; + getSymbolLinks(member.symbol).lateSymbol = symbol; + if (!symbol.declarations) { + symbol.declarations = [member]; + } + else { + symbol.declarations.push(member); + } + if (symbolFlags & 67220415 /* Value */) { + if (!symbol.valueDeclaration || symbol.valueDeclaration.kind !== member.kind) { + symbol.valueDeclaration = member; + } + } + } + /** + * Performs late-binding of a dynamic member. This performs the same function for + * late-bound members that `declareSymbol` in binder.ts performs for early-bound + * members. + * + * If a symbol is a dynamic name from a computed property, we perform an additional "late" + * binding phase to attempt to resolve the name for the symbol from the type of the computed + * property's expression. If the type of the expression is a string-literal, numeric-literal, + * or unique symbol type, we can use that type as the name of the symbol. + * + * For example, given: + * + * const x = Symbol(); + * + * interface I { + * [x]: number; + * } + * + * The binder gives the property `[x]: number` a special symbol with the name "__computed". + * In the late-binding phase we can type-check the expression `x` and see that it has a + * unique symbol type which we can then use as the name of the member. This allows users + * to define custom symbols that can be used in the members of an object type. + * + * @param parent The containing symbol for the member. + * @param earlySymbols The early-bound symbols of the parent. + * @param lateSymbols The late-bound symbols of the parent. + * @param decl The member to bind. + */ + function lateBindMember(parent, earlySymbols, lateSymbols, decl) { + ts.Debug.assert(!!decl.symbol, "The member is expected to have a symbol."); + var links = getNodeLinks(decl); + if (!links.resolvedSymbol) { + // In the event we attempt to resolve the late-bound name of this member recursively, + // fall back to the early-bound name of this member. + links.resolvedSymbol = decl.symbol; + var type = checkComputedPropertyName(decl.name); + if (isTypeUsableAsLateBoundName(type)) { + var memberName = getLateBoundNameFromType(type); + var symbolFlags = decl.symbol.flags; + // Get or add a late-bound symbol for the member. This allows us to merge late-bound accessor declarations. + var lateSymbol = lateSymbols.get(memberName); + if (!lateSymbol) + lateSymbols.set(memberName, lateSymbol = createSymbol(0 /* None */, memberName, 1024 /* Late */)); + // Report an error if a late-bound member has the same name as an early-bound member, + // or if we have another early-bound symbol declaration with the same name and + // conflicting flags. + var earlySymbol = earlySymbols && earlySymbols.get(memberName); + if (lateSymbol.flags & getExcludedSymbolFlags(symbolFlags) || earlySymbol) { + // If we have an existing early-bound member, combine its declarations so that we can + // report an error at each declaration. + var declarations = earlySymbol ? ts.concatenate(earlySymbol.declarations, lateSymbol.declarations) : lateSymbol.declarations; + var name_2 = ts.declarationNameToString(decl.name); + ts.forEach(declarations, function (declaration) { return error(ts.getNameOfDeclaration(declaration) || declaration, ts.Diagnostics.Duplicate_declaration_0, name_2); }); + error(decl.name || decl, ts.Diagnostics.Duplicate_declaration_0, name_2); + lateSymbol = createSymbol(0 /* None */, memberName, 1024 /* Late */); + } + lateSymbol.nameType = type; + addDeclarationToLateBoundSymbol(lateSymbol, decl, symbolFlags); + if (lateSymbol.parent) { + ts.Debug.assert(lateSymbol.parent === parent, "Existing symbol parent should match new one"); + } + else { + lateSymbol.parent = parent; + } + return links.resolvedSymbol = lateSymbol; + } + } + return links.resolvedSymbol; + } + function getResolvedMembersOrExportsOfSymbol(symbol, resolutionKind) { + var links = getSymbolLinks(symbol); + if (!links[resolutionKind]) { + var isStatic = resolutionKind === "resolvedExports" /* resolvedExports */; + var earlySymbols = !isStatic ? symbol.members : + symbol.flags & 1536 /* Module */ ? getExportsOfModuleWorker(symbol) : + symbol.exports; + // In the event we recursively resolve the members/exports of the symbol, we + // set the initial value of resolvedMembers/resolvedExports to the early-bound + // members/exports of the symbol. + links[resolutionKind] = earlySymbols || emptySymbols; + // fill in any as-yet-unresolved late-bound members. + var lateSymbols = ts.createSymbolTable(); + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + var members = ts.getMembersOfDeclaration(decl); + if (members) { + for (var _b = 0, members_4 = members; _b < members_4.length; _b++) { + var member = members_4[_b]; + if (isStatic === ts.hasStaticModifier(member) && hasLateBindableName(member)) { + lateBindMember(symbol, earlySymbols, lateSymbols, member); + } + } + } + } + links[resolutionKind] = combineSymbolTables(earlySymbols, lateSymbols) || emptySymbols; + } + return links[resolutionKind]; + } + /** + * Gets a SymbolTable containing both the early- and late-bound members of a symbol. + * + * For a description of late-binding, see `lateBindMember`. + */ + function getMembersOfSymbol(symbol) { + return symbol.flags & 6240 /* LateBindingContainer */ + ? getResolvedMembersOrExportsOfSymbol(symbol, "resolvedMembers" /* resolvedMembers */) + : symbol.members || emptySymbols; + } + /** + * If a symbol is the dynamic name of the member of an object type, get the late-bound + * symbol of the member. + * + * For a description of late-binding, see `lateBindMember`. + */ + function getLateBoundSymbol(symbol) { + if (symbol.flags & 106500 /* ClassMember */ && symbol.escapedName === "__computed" /* Computed */) { + var links = getSymbolLinks(symbol); + if (!links.lateSymbol && ts.some(symbol.declarations, hasLateBindableName)) { + // force late binding of members/exports. This will set the late-bound symbol + if (ts.some(symbol.declarations, ts.hasStaticModifier)) { + getExportsOfSymbol(symbol.parent); + } + else { + getMembersOfSymbol(symbol.parent); + } + } + return links.lateSymbol || (links.lateSymbol = symbol); + } + return symbol; + } + function getTypeWithThisArgument(type, thisArgument, needApparentType) { + if (ts.getObjectFlags(type) & 4 /* Reference */) { + var target = type.target; + var typeArguments = type.typeArguments; + if (ts.length(target.typeParameters) === ts.length(typeArguments)) { + var ref = createTypeReference(target, ts.concatenate(typeArguments, [thisArgument || target.thisType])); + return needApparentType ? getApparentType(ref) : ref; + } + } + else if (type.flags & 2097152 /* Intersection */) { + return getIntersectionType(ts.map(type.types, function (t) { return getTypeWithThisArgument(t, thisArgument, needApparentType); })); + } + return needApparentType ? getApparentType(type) : type; + } + function resolveObjectTypeMembers(type, source, typeParameters, typeArguments) { + var mapper; + var members; + var callSignatures; + var constructSignatures; + var stringIndexInfo; + var numberIndexInfo; + if (ts.rangeEquals(typeParameters, typeArguments, 0, typeParameters.length)) { + mapper = identityMapper; + members = source.symbol ? getMembersOfSymbol(source.symbol) : ts.createSymbolTable(source.declaredProperties); + callSignatures = source.declaredCallSignatures; + constructSignatures = source.declaredConstructSignatures; + stringIndexInfo = source.declaredStringIndexInfo; + numberIndexInfo = source.declaredNumberIndexInfo; + } + else { + mapper = createTypeMapper(typeParameters, typeArguments); + members = createInstantiatedSymbolTable(source.declaredProperties, mapper, /*mappingThisOnly*/ typeParameters.length === 1); + callSignatures = instantiateSignatures(source.declaredCallSignatures, mapper); + constructSignatures = instantiateSignatures(source.declaredConstructSignatures, mapper); + stringIndexInfo = instantiateIndexInfo(source.declaredStringIndexInfo, mapper); + numberIndexInfo = instantiateIndexInfo(source.declaredNumberIndexInfo, mapper); + } + var baseTypes = getBaseTypes(source); + if (baseTypes.length) { + if (source.symbol && members === getMembersOfSymbol(source.symbol)) { + members = ts.createSymbolTable(source.declaredProperties); + } + setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + var thisArgument = ts.lastOrUndefined(typeArguments); + for (var _i = 0, baseTypes_1 = baseTypes; _i < baseTypes_1.length; _i++) { + var baseType = baseTypes_1[_i]; + var instantiatedBaseType = thisArgument ? getTypeWithThisArgument(instantiateType(baseType, mapper), thisArgument) : baseType; + addInheritedMembers(members, getPropertiesOfType(instantiatedBaseType)); + callSignatures = ts.concatenate(callSignatures, getSignaturesOfType(instantiatedBaseType, 0 /* Call */)); + constructSignatures = ts.concatenate(constructSignatures, getSignaturesOfType(instantiatedBaseType, 1 /* Construct */)); + if (!stringIndexInfo) { + stringIndexInfo = instantiatedBaseType === anyType ? + createIndexInfo(anyType, /*isReadonly*/ false) : + getIndexInfoOfType(instantiatedBaseType, 0 /* String */); + } + numberIndexInfo = numberIndexInfo || getIndexInfoOfType(instantiatedBaseType, 1 /* Number */); + } + } + setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + } + function resolveClassOrInterfaceMembers(type) { + resolveObjectTypeMembers(type, resolveDeclaredMembers(type), ts.emptyArray, ts.emptyArray); + } + function resolveTypeReferenceMembers(type) { + var source = resolveDeclaredMembers(type.target); + var typeParameters = ts.concatenate(source.typeParameters, [source.thisType]); + var typeArguments = type.typeArguments && type.typeArguments.length === typeParameters.length ? + type.typeArguments : ts.concatenate(type.typeArguments, [type]); + resolveObjectTypeMembers(type, source, typeParameters, typeArguments); + } + function createSignature(declaration, typeParameters, thisParameter, parameters, resolvedReturnType, resolvedTypePredicate, minArgumentCount, hasRestParameter, hasLiteralTypes) { + var sig = new Signature(checker); + sig.declaration = declaration; + sig.typeParameters = typeParameters; + sig.parameters = parameters; + sig.thisParameter = thisParameter; + sig.resolvedReturnType = resolvedReturnType; + sig.resolvedTypePredicate = resolvedTypePredicate; + sig.minArgumentCount = minArgumentCount; + sig.hasRestParameter = hasRestParameter; + sig.hasLiteralTypes = hasLiteralTypes; + sig.target = undefined; + sig.mapper = undefined; + return sig; + } + function cloneSignature(sig) { + return createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, /*resolvedReturnType*/ undefined, + /*resolvedTypePredicate*/ undefined, sig.minArgumentCount, sig.hasRestParameter, sig.hasLiteralTypes); + } + function getExpandedParameters(sig) { + if (sig.hasRestParameter) { + var restIndex_1 = sig.parameters.length - 1; + var restParameter = sig.parameters[restIndex_1]; + var restType = getTypeOfSymbol(restParameter); + if (isTupleType(restType)) { + var elementTypes = restType.typeArguments || ts.emptyArray; + var minLength_1 = restType.target.minLength; + var tupleRestIndex_1 = restType.target.hasRestElement ? elementTypes.length - 1 : -1; + var restParams = ts.map(elementTypes, function (t, i) { + var name = getParameterNameAtPosition(sig, restIndex_1 + i); + var checkFlags = i === tupleRestIndex_1 ? 8192 /* RestParameter */ : + i >= minLength_1 ? 4096 /* OptionalParameter */ : 0; + var symbol = createSymbol(1 /* FunctionScopedVariable */, name, checkFlags); + symbol.type = i === tupleRestIndex_1 ? createArrayType(t) : t; + return symbol; + }); + return ts.concatenate(sig.parameters.slice(0, restIndex_1), restParams); + } + } + return sig.parameters; + } + function getDefaultConstructSignatures(classType) { + var baseConstructorType = getBaseConstructorTypeOfClass(classType); + var baseSignatures = getSignaturesOfType(baseConstructorType, 1 /* Construct */); + if (baseSignatures.length === 0) { + return [createSignature(undefined, classType.localTypeParameters, undefined, ts.emptyArray, classType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false)]; // TODO: GH#18217 + } + var baseTypeNode = getBaseTypeNodeOfClass(classType); + var isJavaScript = ts.isInJSFile(baseTypeNode); + var typeArguments = typeArgumentsFromTypeReferenceNode(baseTypeNode); + var typeArgCount = ts.length(typeArguments); + var result = []; + for (var _i = 0, baseSignatures_1 = baseSignatures; _i < baseSignatures_1.length; _i++) { + var baseSig = baseSignatures_1[_i]; + var minTypeArgumentCount = getMinTypeArgumentCount(baseSig.typeParameters); + var typeParamCount = ts.length(baseSig.typeParameters); + if (isJavaScript || typeArgCount >= minTypeArgumentCount && typeArgCount <= typeParamCount) { + var sig = typeParamCount ? createSignatureInstantiation(baseSig, fillMissingTypeArguments(typeArguments, baseSig.typeParameters, minTypeArgumentCount, isJavaScript)) : cloneSignature(baseSig); + sig.typeParameters = classType.localTypeParameters; + sig.resolvedReturnType = classType; + result.push(sig); + } + } + return result; + } + function findMatchingSignature(signatureList, signature, partialMatch, ignoreThisTypes, ignoreReturnTypes) { + for (var _i = 0, signatureList_1 = signatureList; _i < signatureList_1.length; _i++) { + var s = signatureList_1[_i]; + if (compareSignaturesIdentical(s, signature, partialMatch, ignoreThisTypes, ignoreReturnTypes, partialMatch ? compareTypesSubtypeOf : compareTypesIdentical)) { + return s; + } + } + } + function findMatchingSignatures(signatureLists, signature, listIndex) { + if (signature.typeParameters) { + // We require an exact match for generic signatures, so we only return signatures from the first + // signature list and only if they have exact matches in the other signature lists. + if (listIndex > 0) { + return undefined; + } + for (var i = 1; i < signatureLists.length; i++) { + if (!findMatchingSignature(signatureLists[i], signature, /*partialMatch*/ false, /*ignoreThisTypes*/ false, /*ignoreReturnTypes*/ false)) { + return undefined; + } + } + return [signature]; + } + var result; + for (var i = 0; i < signatureLists.length; i++) { + // Allow matching non-generic signatures to have excess parameters and different return types + var match = i === listIndex ? signature : findMatchingSignature(signatureLists[i], signature, /*partialMatch*/ true, /*ignoreThisTypes*/ true, /*ignoreReturnTypes*/ true); + if (!match) { + return undefined; + } + result = ts.appendIfUnique(result, match); + } + return result; + } + // The signatures of a union type are those signatures that are present in each of the constituent types. + // Generic signatures must match exactly, but non-generic signatures are allowed to have extra optional + // parameters and may differ in return types. When signatures differ in return types, the resulting return + // type is the union of the constituent return types. + function getUnionSignatures(signatureLists) { + var result; + for (var i = 0; i < signatureLists.length; i++) { + for (var _i = 0, _a = signatureLists[i]; _i < _a.length; _i++) { + var signature = _a[_i]; + // Only process signatures with parameter lists that aren't already in the result list + if (!result || !findMatchingSignature(result, signature, /*partialMatch*/ false, /*ignoreThisTypes*/ true, /*ignoreReturnTypes*/ true)) { + var unionSignatures = findMatchingSignatures(signatureLists, signature, i); + if (unionSignatures) { + var s = signature; + // Union the result types when more than one signature matches + if (unionSignatures.length > 1) { + var thisParameter = signature.thisParameter; + if (ts.forEach(unionSignatures, function (sig) { return sig.thisParameter; })) { + // TODO: GH#18217 We tested that *some* has thisParameter and now act as if *all* do + var thisType = getUnionType(ts.map(unionSignatures, function (sig) { return sig.thisParameter ? getTypeOfSymbol(sig.thisParameter) : anyType; }), 2 /* Subtype */); + thisParameter = createSymbolWithType(signature.thisParameter, thisType); + } + s = cloneSignature(signature); + s.thisParameter = thisParameter; + s.unionSignatures = unionSignatures; + } + (result || (result = [])).push(s); + } + } + } + } + return result || ts.emptyArray; + } + function getUnionIndexInfo(types, kind) { + var indexTypes = []; + var isAnyReadonly = false; + for (var _i = 0, types_2 = types; _i < types_2.length; _i++) { + var type = types_2[_i]; + var indexInfo = getIndexInfoOfType(type, kind); + if (!indexInfo) { + return undefined; + } + indexTypes.push(indexInfo.type); + isAnyReadonly = isAnyReadonly || indexInfo.isReadonly; + } + return createIndexInfo(getUnionType(indexTypes, 2 /* Subtype */), isAnyReadonly); + } + function resolveUnionTypeMembers(type) { + // The members and properties collections are empty for union types. To get all properties of a union + // type use getPropertiesOfType (only the language service uses this). + var callSignatures = getUnionSignatures(ts.map(type.types, function (t) { return getSignaturesOfType(t, 0 /* Call */); })); + var constructSignatures = getUnionSignatures(ts.map(type.types, function (t) { return getSignaturesOfType(t, 1 /* Construct */); })); + var stringIndexInfo = getUnionIndexInfo(type.types, 0 /* String */); + var numberIndexInfo = getUnionIndexInfo(type.types, 1 /* Number */); + setStructuredTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + } + function intersectTypes(type1, type2) { + return !type1 ? type2 : !type2 ? type1 : getIntersectionType([type1, type2]); + } + function intersectIndexInfos(info1, info2) { + return !info1 ? info2 : !info2 ? info1 : createIndexInfo(getIntersectionType([info1.type, info2.type]), info1.isReadonly && info2.isReadonly); + } + function unionSpreadIndexInfos(info1, info2) { + return info1 && info2 && createIndexInfo(getUnionType([info1.type, info2.type]), info1.isReadonly || info2.isReadonly); + } + function includeMixinType(type, types, index) { + var mixedTypes = []; + for (var i = 0; i < types.length; i++) { + if (i === index) { + mixedTypes.push(type); + } + else if (isMixinConstructorType(types[i])) { + mixedTypes.push(getReturnTypeOfSignature(getSignaturesOfType(types[i], 1 /* Construct */)[0])); + } + } + return getIntersectionType(mixedTypes); + } + function resolveIntersectionTypeMembers(type) { + // The members and properties collections are empty for intersection types. To get all properties of an + // intersection type use getPropertiesOfType (only the language service uses this). + var callSignatures = ts.emptyArray; + var constructSignatures = ts.emptyArray; + var stringIndexInfo; + var numberIndexInfo; + var types = type.types; + var mixinCount = ts.countWhere(types, isMixinConstructorType); + var _loop_5 = function (i) { + var t = type.types[i]; + // When an intersection type contains mixin constructor types, the construct signatures from + // those types are discarded and their return types are mixed into the return types of all + // other construct signatures in the intersection type. For example, the intersection type + // '{ new(...args: any[]) => A } & { new(s: string) => B }' has a single construct signature + // 'new(s: string) => A & B'. + if (mixinCount === 0 || mixinCount === types.length && i === 0 || !isMixinConstructorType(t)) { + var signatures = getSignaturesOfType(t, 1 /* Construct */); + if (signatures.length && mixinCount > 0) { + signatures = ts.map(signatures, function (s) { + var clone = cloneSignature(s); + clone.resolvedReturnType = includeMixinType(getReturnTypeOfSignature(s), types, i); + return clone; + }); + } + constructSignatures = ts.concatenate(constructSignatures, signatures); + } + callSignatures = ts.concatenate(callSignatures, getSignaturesOfType(t, 0 /* Call */)); + stringIndexInfo = intersectIndexInfos(stringIndexInfo, getIndexInfoOfType(t, 0 /* String */)); + numberIndexInfo = intersectIndexInfos(numberIndexInfo, getIndexInfoOfType(t, 1 /* Number */)); + }; + for (var i = 0; i < types.length; i++) { + _loop_5(i); + } + setStructuredTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + } + /** + * Converts an AnonymousType to a ResolvedType. + */ + function resolveAnonymousTypeMembers(type) { + var symbol = type.symbol; + if (type.target) { + setStructuredTypeMembers(type, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + var members = createInstantiatedSymbolTable(getPropertiesOfObjectType(type.target), type.mapper, /*mappingThisOnly*/ false); + var callSignatures = instantiateSignatures(getSignaturesOfType(type.target, 0 /* Call */), type.mapper); + var constructSignatures = instantiateSignatures(getSignaturesOfType(type.target, 1 /* Construct */), type.mapper); + var stringIndexInfo = instantiateIndexInfo(getIndexInfoOfType(type.target, 0 /* String */), type.mapper); + var numberIndexInfo = instantiateIndexInfo(getIndexInfoOfType(type.target, 1 /* Number */), type.mapper); + setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + } + else if (symbol.flags & 2048 /* TypeLiteral */) { + setStructuredTypeMembers(type, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + var members = getMembersOfSymbol(symbol); + var callSignatures = getSignaturesOfSymbol(members.get("__call" /* Call */)); + var constructSignatures = getSignaturesOfSymbol(members.get("__new" /* New */)); + var stringIndexInfo = getIndexInfoOfSymbol(symbol, 0 /* String */); + var numberIndexInfo = getIndexInfoOfSymbol(symbol, 1 /* Number */); + setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + } + else { + // Combinations of function, class, enum and module + var members = emptySymbols; + var stringIndexInfo = void 0; + if (symbol.exports) { + members = getExportsOfSymbol(symbol); + } + setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, undefined, undefined); + if (symbol.flags & 32 /* Class */) { + var classType = getDeclaredTypeOfClassOrInterface(symbol); + var baseConstructorType = getBaseConstructorTypeOfClass(classType); + if (baseConstructorType.flags & (524288 /* Object */ | 2097152 /* Intersection */ | 8650752 /* TypeVariable */)) { + members = ts.createSymbolTable(getNamedMembers(members)); + addInheritedMembers(members, getPropertiesOfType(baseConstructorType)); + } + else if (baseConstructorType === anyType) { + stringIndexInfo = createIndexInfo(anyType, /*isReadonly*/ false); + } + } + var numberIndexInfo = symbol.flags & 384 /* Enum */ ? enumNumberIndexInfo : undefined; + setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); + // We resolve the members before computing the signatures because a signature may use + // typeof with a qualified name expression that circularly references the type we are + // in the process of resolving (see issue #6072). The temporarily empty signature list + // will never be observed because a qualified name can't reference signatures. + if (symbol.flags & (16 /* Function */ | 8192 /* Method */)) { + type.callSignatures = getSignaturesOfSymbol(symbol); + type.constructSignatures = ts.filter(type.callSignatures, function (sig) { return isJSConstructor(sig.declaration); }); + } + // And likewise for construct signatures for classes + if (symbol.flags & 32 /* Class */) { + var classType = getDeclaredTypeOfClassOrInterface(symbol); + var constructSignatures = getSignaturesOfSymbol(symbol.members.get("__constructor" /* Constructor */)); + if (!constructSignatures.length) { + constructSignatures = getDefaultConstructSignatures(classType); + } + type.constructSignatures = constructSignatures; + } + } + } + function resolveReverseMappedTypeMembers(type) { + var indexInfo = getIndexInfoOfType(type.source, 0 /* String */); + var modifiers = getMappedTypeModifiers(type.mappedType); + var readonlyMask = modifiers & 1 /* IncludeReadonly */ ? false : true; + var optionalMask = modifiers & 4 /* IncludeOptional */ ? 0 : 16777216 /* Optional */; + var stringIndexInfo = indexInfo && createIndexInfo(inferReverseMappedType(indexInfo.type, type.mappedType, type.constraintType), readonlyMask && indexInfo.isReadonly); + var members = ts.createSymbolTable(); + for (var _i = 0, _a = getPropertiesOfType(type.source); _i < _a.length; _i++) { + var prop = _a[_i]; + var checkFlags = 2048 /* ReverseMapped */ | (readonlyMask && isReadonlySymbol(prop) ? 8 /* Readonly */ : 0); + var inferredProp = createSymbol(4 /* Property */ | prop.flags & optionalMask, prop.escapedName, checkFlags); + inferredProp.declarations = prop.declarations; + inferredProp.nameType = prop.nameType; + inferredProp.propertyType = getTypeOfSymbol(prop); + inferredProp.mappedType = type.mappedType; + inferredProp.constraintType = type.constraintType; + members.set(prop.escapedName, inferredProp); + } + setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, undefined); + } + /** Resolve the members of a mapped type { [P in K]: T } */ + function resolveMappedTypeMembers(type) { + var members = ts.createSymbolTable(); + var stringIndexInfo; + var numberIndexInfo; + // Resolve upfront such that recursive references see an empty object type. + setStructuredTypeMembers(type, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + // In { [P in K]: T }, we refer to P as the type parameter type, K as the constraint type, + // and T as the template type. + var typeParameter = getTypeParameterFromMappedType(type); + var constraintType = getConstraintTypeFromMappedType(type); + var templateType = getTemplateTypeFromMappedType(type.target || type); + var modifiersType = getApparentType(getModifiersTypeFromMappedType(type)); // The 'T' in 'keyof T' + var templateModifiers = getMappedTypeModifiers(type); + var include = keyofStringsOnly ? 128 /* StringLiteral */ : 8576 /* StringOrNumberLiteralOrUnique */; + if (isMappedTypeWithKeyofConstraintDeclaration(type)) { + // We have a { [P in keyof T]: X } + for (var _i = 0, _a = getPropertiesOfType(modifiersType); _i < _a.length; _i++) { + var prop = _a[_i]; + addMemberForKeyType(getLiteralTypeFromProperty(prop, include)); + } + if (modifiersType.flags & 1 /* Any */ || getIndexInfoOfType(modifiersType, 0 /* String */)) { + addMemberForKeyType(stringType); + } + if (!keyofStringsOnly && getIndexInfoOfType(modifiersType, 1 /* Number */)) { + addMemberForKeyType(numberType); + } + } + else { + // If the key type is a 'keyof X', obtain 'keyof C' where C is the base constraint of X. + // Then iterate over the constituents of the key type. + var iterationType = constraintType.flags & 4194304 /* Index */ ? getIndexType(getApparentType(constraintType.type)) : constraintType; + forEachType(iterationType, addMemberForKeyType); + } + setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); + function addMemberForKeyType(t) { + // Create a mapper from T to the current iteration type constituent. Then, if the + // mapped type is itself an instantiated type, combine the iteration mapper with the + // instantiation mapper. + var templateMapper = combineTypeMappers(type.mapper, createTypeMapper([typeParameter], [t])); + var propType = instantiateType(templateType, templateMapper); + // If the current iteration type constituent is a string literal type, create a property. + // Otherwise, for type string create a string index signature. + if (t.flags & 8576 /* StringOrNumberLiteralOrUnique */) { + var propName = getLateBoundNameFromType(t); + var modifiersProp = getPropertyOfType(modifiersType, propName); + var isOptional = !!(templateModifiers & 4 /* IncludeOptional */ || + !(templateModifiers & 8 /* ExcludeOptional */) && modifiersProp && modifiersProp.flags & 16777216 /* Optional */); + var isReadonly = !!(templateModifiers & 1 /* IncludeReadonly */ || + !(templateModifiers & 2 /* ExcludeReadonly */) && modifiersProp && isReadonlySymbol(modifiersProp)); + var prop = createSymbol(4 /* Property */ | (isOptional ? 16777216 /* Optional */ : 0), propName, isReadonly ? 8 /* Readonly */ : 0); + // When creating an optional property in strictNullChecks mode, if 'undefined' isn't assignable to the + // type, we include 'undefined' in the type. Similarly, when creating a non-optional property in strictNullChecks + // mode, if the underlying property is optional we remove 'undefined' from the type. + prop.type = strictNullChecks && isOptional && !isTypeAssignableTo(undefinedType, propType) ? getOptionalType(propType) : + strictNullChecks && !isOptional && modifiersProp && modifiersProp.flags & 16777216 /* Optional */ ? getTypeWithFacts(propType, 524288 /* NEUndefined */) : + propType; + if (modifiersProp) { + prop.syntheticOrigin = modifiersProp; + prop.declarations = modifiersProp.declarations; + } + prop.nameType = t; + members.set(propName, prop); + } + else if (t.flags & (1 /* Any */ | 4 /* String */)) { + stringIndexInfo = createIndexInfo(propType, !!(templateModifiers & 1 /* IncludeReadonly */)); + } + else if (t.flags & 8 /* Number */) { + numberIndexInfo = createIndexInfo(propType, !!(templateModifiers & 1 /* IncludeReadonly */)); + } + } + } + function getTypeParameterFromMappedType(type) { + return type.typeParameter || + (type.typeParameter = getDeclaredTypeOfTypeParameter(getSymbolOfNode(type.declaration.typeParameter))); + } + function getConstraintTypeFromMappedType(type) { + return type.constraintType || + (type.constraintType = getConstraintOfTypeParameter(getTypeParameterFromMappedType(type)) || errorType); + } + function getTemplateTypeFromMappedType(type) { + return type.templateType || + (type.templateType = type.declaration.type ? + instantiateType(addOptionality(getTypeFromTypeNode(type.declaration.type), !!(getMappedTypeModifiers(type) & 4 /* IncludeOptional */)), type.mapper || identityMapper) : + errorType); + } + function getConstraintDeclarationForMappedType(type) { + return ts.getEffectiveConstraintOfTypeParameter(type.declaration.typeParameter); + } + function isMappedTypeWithKeyofConstraintDeclaration(type) { + var constraintDeclaration = getConstraintDeclarationForMappedType(type); // TODO: GH#18217 + return constraintDeclaration.kind === 179 /* TypeOperator */ && + constraintDeclaration.operator === 129 /* KeyOfKeyword */; + } + function getModifiersTypeFromMappedType(type) { + if (!type.modifiersType) { + if (isMappedTypeWithKeyofConstraintDeclaration(type)) { + // If the constraint declaration is a 'keyof T' node, the modifiers type is T. We check + // AST nodes here because, when T is a non-generic type, the logic below eagerly resolves + // 'keyof T' to a literal union type and we can't recover T from that type. + type.modifiersType = instantiateType(getTypeFromTypeNode(getConstraintDeclarationForMappedType(type).type), type.mapper || identityMapper); + } + else { + // Otherwise, get the declared constraint type, and if the constraint type is a type parameter, + // get the constraint of that type parameter. If the resulting type is an indexed type 'keyof T', + // the modifiers type is T. Otherwise, the modifiers type is {}. + var declaredType = getTypeFromMappedTypeNode(type.declaration); + var constraint = getConstraintTypeFromMappedType(declaredType); + var extendedConstraint = constraint && constraint.flags & 262144 /* TypeParameter */ ? getConstraintOfTypeParameter(constraint) : constraint; + type.modifiersType = extendedConstraint && extendedConstraint.flags & 4194304 /* Index */ ? instantiateType(extendedConstraint.type, type.mapper || identityMapper) : emptyObjectType; + } + } + return type.modifiersType; + } + function getMappedTypeModifiers(type) { + var declaration = type.declaration; + return (declaration.readonlyToken ? declaration.readonlyToken.kind === 39 /* MinusToken */ ? 2 /* ExcludeReadonly */ : 1 /* IncludeReadonly */ : 0) | + (declaration.questionToken ? declaration.questionToken.kind === 39 /* MinusToken */ ? 8 /* ExcludeOptional */ : 4 /* IncludeOptional */ : 0); + } + function getMappedTypeOptionality(type) { + var modifiers = getMappedTypeModifiers(type); + return modifiers & 8 /* ExcludeOptional */ ? -1 : modifiers & 4 /* IncludeOptional */ ? 1 : 0; + } + function getCombinedMappedTypeOptionality(type) { + var optionality = getMappedTypeOptionality(type); + var modifiersType = getModifiersTypeFromMappedType(type); + return optionality || (isGenericMappedType(modifiersType) ? getMappedTypeOptionality(modifiersType) : 0); + } + function isPartialMappedType(type) { + return !!(ts.getObjectFlags(type) & 32 /* Mapped */ && getMappedTypeModifiers(type) & 4 /* IncludeOptional */); + } + function isGenericMappedType(type) { + return !!(ts.getObjectFlags(type) & 32 /* Mapped */) && isGenericIndexType(getConstraintTypeFromMappedType(type)); + } + function resolveStructuredTypeMembers(type) { + if (!type.members) { + if (type.flags & 524288 /* Object */) { + if (type.objectFlags & 4 /* Reference */) { + resolveTypeReferenceMembers(type); + } + else if (type.objectFlags & 3 /* ClassOrInterface */) { + resolveClassOrInterfaceMembers(type); + } + else if (type.objectFlags & 2048 /* ReverseMapped */) { + resolveReverseMappedTypeMembers(type); + } + else if (type.objectFlags & 16 /* Anonymous */) { + resolveAnonymousTypeMembers(type); + } + else if (type.objectFlags & 32 /* Mapped */) { + resolveMappedTypeMembers(type); + } + } + else if (type.flags & 1048576 /* Union */) { + resolveUnionTypeMembers(type); + } + else if (type.flags & 2097152 /* Intersection */) { + resolveIntersectionTypeMembers(type); + } + } + return type; + } + /** Return properties of an object type or an empty array for other types */ + function getPropertiesOfObjectType(type) { + if (type.flags & 524288 /* Object */) { + return resolveStructuredTypeMembers(type).properties; + } + return ts.emptyArray; + } + /** If the given type is an object type and that type has a property by the given name, + * return the symbol for that property. Otherwise return undefined. + */ + function getPropertyOfObjectType(type, name) { + if (type.flags & 524288 /* Object */) { + var resolved = resolveStructuredTypeMembers(type); + var symbol = resolved.members.get(name); + if (symbol && symbolIsValue(symbol)) { + return symbol; + } + } + } + function getPropertiesOfUnionOrIntersectionType(type) { + if (!type.resolvedProperties) { + var members = ts.createSymbolTable(); + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var current = _a[_i]; + for (var _b = 0, _c = getPropertiesOfType(current); _b < _c.length; _b++) { + var prop = _c[_b]; + if (!members.has(prop.escapedName)) { + var combinedProp = getPropertyOfUnionOrIntersectionType(type, prop.escapedName); + if (combinedProp) { + members.set(prop.escapedName, combinedProp); + } + } + } + // The properties of a union type are those that are present in all constituent types, so + // we only need to check the properties of the first type + if (type.flags & 1048576 /* Union */) { + break; + } + } + type.resolvedProperties = getNamedMembers(members); + } + return type.resolvedProperties; + } + function getPropertiesOfType(type) { + type = getApparentType(type); + return type.flags & 3145728 /* UnionOrIntersection */ ? + getPropertiesOfUnionOrIntersectionType(type) : + getPropertiesOfObjectType(type); + } + function isTypeInvalidDueToUnionDiscriminant(contextualType, obj) { + var list = obj.properties; + return list.some(function (property) { + var name = property.name && ts.getTextOfPropertyName(property.name); + var expected = name === undefined ? undefined : getTypeOfPropertyOfType(contextualType, name); + return !!expected && typeIsLiteralType(expected) && !isTypeIdenticalTo(getTypeOfNode(property), expected); + }); + } + function getAllPossiblePropertiesOfTypes(types) { + var unionType = getUnionType(types); + if (!(unionType.flags & 1048576 /* Union */)) { + return getAugmentedPropertiesOfType(unionType); + } + var props = ts.createSymbolTable(); + for (var _i = 0, types_3 = types; _i < types_3.length; _i++) { + var memberType = types_3[_i]; + for (var _a = 0, _b = getAugmentedPropertiesOfType(memberType); _a < _b.length; _a++) { + var escapedName = _b[_a].escapedName; + if (!props.has(escapedName)) { + var prop = createUnionOrIntersectionProperty(unionType, escapedName); + // May be undefined if the property is private + if (prop) + props.set(escapedName, prop); + } + } + } + return ts.arrayFrom(props.values()); + } + function getConstraintOfType(type) { + return type.flags & 262144 /* TypeParameter */ ? getConstraintOfTypeParameter(type) : + type.flags & 8388608 /* IndexedAccess */ ? getConstraintOfIndexedAccess(type) : + type.flags & 16777216 /* Conditional */ ? getConstraintOfConditionalType(type) : + getBaseConstraintOfType(type); + } + function getConstraintOfTypeParameter(typeParameter) { + return hasNonCircularBaseConstraint(typeParameter) ? getConstraintFromTypeParameter(typeParameter) : undefined; + } + function getConstraintOfIndexedAccess(type) { + var objectType = getConstraintOfType(type.objectType) || type.objectType; + if (objectType !== type.objectType) { + var constraint = getIndexedAccessType(objectType, type.indexType, /*accessNode*/ undefined, errorType); + if (constraint && constraint !== errorType) { + return constraint; + } + } + var baseConstraint = getBaseConstraintOfType(type); + return baseConstraint && baseConstraint !== type ? baseConstraint : undefined; + } + function getDefaultConstraintOfConditionalType(type) { + if (!type.resolvedDefaultConstraint) { + var rootTrueType = type.root.trueType; + var rootTrueConstraint = !(rootTrueType.flags & 33554432 /* Substitution */) + ? rootTrueType + : (rootTrueType.substitute).flags & 3 /* AnyOrUnknown */ + ? rootTrueType.typeVariable + : getIntersectionType([rootTrueType.substitute, rootTrueType.typeVariable]); + type.resolvedDefaultConstraint = getUnionType([instantiateType(rootTrueConstraint, type.combinedMapper || type.mapper), getFalseTypeFromConditionalType(type)]); + } + return type.resolvedDefaultConstraint; + } + function getConstraintOfDistributiveConditionalType(type) { + // Check if we have a conditional type of the form 'T extends U ? X : Y', where T is a constrained + // type parameter. If so, create an instantiation of the conditional type where T is replaced + // with its constraint. We do this because if the constraint is a union type it will be distributed + // over the conditional type and possibly reduced. For example, 'T extends undefined ? never : T' + // removes 'undefined' from T. + if (type.root.isDistributive) { + var simplified = getSimplifiedType(type.checkType); + var constraint = simplified === type.checkType ? getConstraintOfType(simplified) : simplified; + if (constraint) { + var mapper = makeUnaryTypeMapper(type.root.checkType, constraint); + var instantiated = getConditionalTypeInstantiation(type, combineTypeMappers(mapper, type.mapper)); + if (!(instantiated.flags & 131072 /* Never */)) { + return instantiated; + } + } + } + return undefined; + } + function getConstraintOfConditionalType(type) { + return getConstraintOfDistributiveConditionalType(type) || getDefaultConstraintOfConditionalType(type); + } + function getUnionConstraintOfIntersection(type, targetIsUnion) { + var constraints; + var hasDisjointDomainType = false; + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (t.flags & 63176704 /* Instantiable */) { + // We keep following constraints as long as we have an instantiable type that is known + // not to be circular or infinite (hence we stop on index access types). + var constraint = getConstraintOfType(t); + while (constraint && constraint.flags & (262144 /* TypeParameter */ | 4194304 /* Index */ | 16777216 /* Conditional */)) { + constraint = getConstraintOfType(constraint); + } + if (constraint) { + // A constraint that isn't a union type implies that the final type would be a non-union + // type as well. Since non-union constraints are of no interest, we can exit here. + if (!(constraint.flags & 1048576 /* Union */)) { + return undefined; + } + constraints = ts.append(constraints, constraint); + } + } + else if (t.flags & 67238908 /* DisjointDomains */) { + hasDisjointDomainType = true; + } + } + // If the target is a union type or if we are intersecting with types belonging to one of the + // disjoint domans, we may end up producing a constraint that hasn't been examined before. + if (constraints && (targetIsUnion || hasDisjointDomainType)) { + if (hasDisjointDomainType) { + // We add any types belong to one of the disjoint domans because they might cause the final + // intersection operation to reduce the union constraints. + for (var _b = 0, _c = type.types; _b < _c.length; _b++) { + var t = _c[_b]; + if (t.flags & 67238908 /* DisjointDomains */) { + constraints = ts.append(constraints, t); + } + } + } + return getIntersectionType(constraints); + } + return undefined; + } + function getBaseConstraintOfType(type) { + if (type.flags & (58982400 /* InstantiableNonPrimitive */ | 3145728 /* UnionOrIntersection */)) { + var constraint = getResolvedBaseConstraint(type); + return constraint !== noConstraintType && constraint !== circularConstraintType ? constraint : undefined; + } + return type.flags & 4194304 /* Index */ ? keyofConstraintType : undefined; + } + /** + * This is similar to `getBaseConstraintOfType` except it returns the input type if there's no base constraint, instead of `undefined` + * It also doesn't map indexes to `string`, as where this is used this would be unneeded (and likely undesirable) + */ + function getBaseConstraintOrType(type) { + return getBaseConstraintOfType(type) || type; + } + function hasNonCircularBaseConstraint(type) { + return getResolvedBaseConstraint(type) !== circularConstraintType; + } + /** + * Return the resolved base constraint of a type variable. The noConstraintType singleton is returned if the + * type variable has no constraint, and the circularConstraintType singleton is returned if the constraint + * circularly references the type variable. + */ + function getResolvedBaseConstraint(type) { + var nonTerminating = false; + return type.resolvedBaseConstraint || + (type.resolvedBaseConstraint = getTypeWithThisArgument(getImmediateBaseConstraint(type), type)); + function getImmediateBaseConstraint(t) { + if (!t.immediateBaseConstraint) { + if (!pushTypeResolution(t, 4 /* ImmediateBaseConstraint */)) { + return circularConstraintType; + } + if (constraintDepth === 50) { + // We have reached 50 recursive invocations of getImmediateBaseConstraint and there is a + // very high likelyhood we're dealing with an infinite generic type that perpetually generates + // new type identities as we descend into it. We stop the recursion here and mark this type + // and the outer types as having circular constraints. + nonTerminating = true; + return t.immediateBaseConstraint = noConstraintType; + } + constraintDepth++; + var result = computeBaseConstraint(getSimplifiedType(t)); + constraintDepth--; + if (!popTypeResolution() || nonTerminating) { + result = circularConstraintType; + } + t.immediateBaseConstraint = result || noConstraintType; + } + return t.immediateBaseConstraint; + } + function getBaseConstraint(t) { + var c = getImmediateBaseConstraint(t); + return c !== noConstraintType && c !== circularConstraintType ? c : undefined; + } + function computeBaseConstraint(t) { + if (t.flags & 262144 /* TypeParameter */) { + var constraint = getConstraintFromTypeParameter(t); + return t.isThisType || !constraint ? + constraint : + getBaseConstraint(constraint); + } + if (t.flags & 3145728 /* UnionOrIntersection */) { + var types = t.types; + var baseTypes = []; + for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { + var type_3 = types_4[_i]; + var baseType = getBaseConstraint(type_3); + if (baseType) { + baseTypes.push(baseType); + } + } + return t.flags & 1048576 /* Union */ && baseTypes.length === types.length ? getUnionType(baseTypes) : + t.flags & 2097152 /* Intersection */ && baseTypes.length ? getIntersectionType(baseTypes) : + undefined; + } + if (t.flags & 4194304 /* Index */) { + return keyofConstraintType; + } + if (t.flags & 8388608 /* IndexedAccess */) { + var baseObjectType = getBaseConstraint(t.objectType); + var baseIndexType = getBaseConstraint(t.indexType); + var baseIndexedAccess = baseObjectType && baseIndexType ? getIndexedAccessType(baseObjectType, baseIndexType, /*accessNode*/ undefined, errorType) : undefined; + return baseIndexedAccess && baseIndexedAccess !== errorType ? getBaseConstraint(baseIndexedAccess) : undefined; + } + if (t.flags & 16777216 /* Conditional */) { + var constraint = getConstraintOfConditionalType(t); + return constraint && getBaseConstraint(constraint); + } + if (t.flags & 33554432 /* Substitution */) { + return getBaseConstraint(t.substitute); + } + return t; + } + } + function getApparentTypeOfIntersectionType(type) { + return type.resolvedApparentType || (type.resolvedApparentType = getTypeWithThisArgument(type, type, /*apparentType*/ true)); + } + function getResolvedTypeParameterDefault(typeParameter) { + if (!typeParameter.default) { + if (typeParameter.target) { + var targetDefault = getResolvedTypeParameterDefault(typeParameter.target); + typeParameter.default = targetDefault ? instantiateType(targetDefault, typeParameter.mapper) : noConstraintType; + } + else { + // To block recursion, set the initial value to the resolvingDefaultType. + typeParameter.default = resolvingDefaultType; + var defaultDeclaration = typeParameter.symbol && ts.forEach(typeParameter.symbol.declarations, function (decl) { return ts.isTypeParameterDeclaration(decl) && decl.default; }); + var defaultType = defaultDeclaration ? getTypeFromTypeNode(defaultDeclaration) : noConstraintType; + if (typeParameter.default === resolvingDefaultType) { + // If we have not been called recursively, set the correct default type. + typeParameter.default = defaultType; + } + } + } + else if (typeParameter.default === resolvingDefaultType) { + // If we are called recursively for this type parameter, mark the default as circular. + typeParameter.default = circularConstraintType; + } + return typeParameter.default; + } + /** + * Gets the default type for a type parameter. + * + * If the type parameter is the result of an instantiation, this gets the instantiated + * default type of its target. If the type parameter has no default type or the default is + * circular, `undefined` is returned. + */ + function getDefaultFromTypeParameter(typeParameter) { + var defaultType = getResolvedTypeParameterDefault(typeParameter); + return defaultType !== noConstraintType && defaultType !== circularConstraintType ? defaultType : undefined; + } + function hasNonCircularTypeParameterDefault(typeParameter) { + return getResolvedTypeParameterDefault(typeParameter) !== circularConstraintType; + } + /** + * Indicates whether the declaration of a typeParameter has a default type. + */ + function hasTypeParameterDefault(typeParameter) { + return !!(typeParameter.symbol && ts.forEach(typeParameter.symbol.declarations, function (decl) { return ts.isTypeParameterDeclaration(decl) && decl.default; })); + } + function getApparentTypeOfMappedType(type) { + return type.resolvedApparentType || (type.resolvedApparentType = getResolvedApparentTypeOfMappedType(type)); + } + function getResolvedApparentTypeOfMappedType(type) { + var typeVariable = getHomomorphicTypeVariable(type); + if (typeVariable) { + var constraint = getConstraintOfTypeParameter(typeVariable); + if (constraint && (isArrayType(constraint) || isReadonlyArrayType(constraint) || isTupleType(constraint))) { + var mapper = makeUnaryTypeMapper(typeVariable, constraint); + return instantiateType(type, combineTypeMappers(mapper, type.mapper)); + } + } + return type; + } + /** + * For a type parameter, return the base constraint of the type parameter. For the string, number, + * boolean, and symbol primitive types, return the corresponding object types. Otherwise return the + * type itself. Note that the apparent type of a union type is the union type itself. + */ + function getApparentType(type) { + var t = type.flags & 63176704 /* Instantiable */ ? getBaseConstraintOfType(type) || emptyObjectType : type; + return ts.getObjectFlags(t) & 32 /* Mapped */ ? getApparentTypeOfMappedType(t) : + t.flags & 2097152 /* Intersection */ ? getApparentTypeOfIntersectionType(t) : + t.flags & 132 /* StringLike */ ? globalStringType : + t.flags & 296 /* NumberLike */ ? globalNumberType : + t.flags & 2112 /* BigIntLike */ ? getGlobalBigIntType(/*reportErrors*/ languageVersion >= 6 /* ESNext */) : + t.flags & 528 /* BooleanLike */ ? globalBooleanType : + t.flags & 12288 /* ESSymbolLike */ ? getGlobalESSymbolType(/*reportErrors*/ languageVersion >= 2 /* ES2015 */) : + t.flags & 67108864 /* NonPrimitive */ ? emptyObjectType : + t.flags & 4194304 /* Index */ ? keyofConstraintType : + t; + } + function createUnionOrIntersectionProperty(containingType, name) { + var props; + var indexTypes; + var isUnion = containingType.flags & 1048576 /* Union */; + var excludeModifiers = isUnion ? 24 /* NonPublicAccessibilityModifier */ : 0; + // Flags we want to propagate to the result if they exist in all source symbols + var commonFlags = isUnion ? 0 /* None */ : 16777216 /* Optional */; + var syntheticFlag = 4 /* SyntheticMethod */; + var checkFlags = 0; + for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) { + var current = _a[_i]; + var type = getApparentType(current); + if (type !== errorType) { + var prop = getPropertyOfType(type, name); + var modifiers = prop ? ts.getDeclarationModifierFlagsFromSymbol(prop) : 0; + if (prop && !(modifiers & excludeModifiers)) { + commonFlags &= prop.flags; + props = ts.appendIfUnique(props, prop); + checkFlags |= (isReadonlySymbol(prop) ? 8 /* Readonly */ : 0) | + (!(modifiers & 24 /* NonPublicAccessibilityModifier */) ? 64 /* ContainsPublic */ : 0) | + (modifiers & 16 /* Protected */ ? 128 /* ContainsProtected */ : 0) | + (modifiers & 8 /* Private */ ? 256 /* ContainsPrivate */ : 0) | + (modifiers & 32 /* Static */ ? 512 /* ContainsStatic */ : 0); + if (!isPrototypeProperty(prop)) { + syntheticFlag = 2 /* SyntheticProperty */; + } + } + else if (isUnion) { + var indexInfo = !isLateBoundName(name) && (isNumericLiteralName(name) && getIndexInfoOfType(type, 1 /* Number */) || getIndexInfoOfType(type, 0 /* String */)); + if (indexInfo) { + checkFlags |= indexInfo.isReadonly ? 8 /* Readonly */ : 0; + indexTypes = ts.append(indexTypes, isTupleType(type) ? getRestTypeOfTupleType(type) || undefinedType : indexInfo.type); + } + else { + checkFlags |= 16 /* Partial */; + } + } + } + } + if (!props) { + return undefined; + } + if (props.length === 1 && !(checkFlags & 16 /* Partial */) && !indexTypes) { + return props[0]; + } + var declarations; + var commonType; + var nameType; + var propTypes = []; + var first = true; + var commonValueDeclaration; + var hasNonUniformValueDeclaration = false; + for (var _b = 0, props_1 = props; _b < props_1.length; _b++) { + var prop = props_1[_b]; + if (!commonValueDeclaration) { + commonValueDeclaration = prop.valueDeclaration; + } + else if (prop.valueDeclaration !== commonValueDeclaration) { + hasNonUniformValueDeclaration = true; + } + declarations = ts.addRange(declarations, prop.declarations); + var type = getTypeOfSymbol(prop); + if (first) { + commonType = type; + nameType = prop.nameType; + first = false; + } + else { + if (type !== commonType) { + checkFlags |= 32 /* HasNonUniformType */; + } + } + propTypes.push(type); + } + ts.addRange(propTypes, indexTypes); + var result = createSymbol(4 /* Property */ | commonFlags, name, syntheticFlag | checkFlags); + result.containingType = containingType; + if (!hasNonUniformValueDeclaration && commonValueDeclaration) { + result.valueDeclaration = commonValueDeclaration; + } + result.declarations = declarations; + result.nameType = nameType; + result.type = isUnion ? getUnionType(propTypes) : getIntersectionType(propTypes); + return result; + } + // Return the symbol for a given property in a union or intersection type, or undefined if the property + // does not exist in any constituent type. Note that the returned property may only be present in some + // constituents, in which case the isPartial flag is set when the containing type is union type. We need + // these partial properties when identifying discriminant properties, but otherwise they are filtered out + // and do not appear to be present in the union type. + function getUnionOrIntersectionProperty(type, name) { + var properties = type.propertyCache || (type.propertyCache = ts.createSymbolTable()); + var property = properties.get(name); + if (!property) { + property = createUnionOrIntersectionProperty(type, name); + if (property) { + properties.set(name, property); + } + } + return property; + } + function getPropertyOfUnionOrIntersectionType(type, name) { + var property = getUnionOrIntersectionProperty(type, name); + // We need to filter out partial properties in union types + return property && !(ts.getCheckFlags(property) & 16 /* Partial */) ? property : undefined; + } + /** + * Return the symbol for the property with the given name in the given type. Creates synthetic union properties when + * necessary, maps primitive types and type parameters are to their apparent types, and augments with properties from + * Object and Function as appropriate. + * + * @param type a type to look up property from + * @param name a name of property to look up in a given type + */ + function getPropertyOfType(type, name) { + type = getApparentType(type); + if (type.flags & 524288 /* Object */) { + var resolved = resolveStructuredTypeMembers(type); + var symbol = resolved.members.get(name); + if (symbol && symbolIsValue(symbol)) { + return symbol; + } + var functionType = resolved === anyFunctionType ? globalFunctionType : + resolved.callSignatures.length ? globalCallableFunctionType : + resolved.constructSignatures.length ? globalNewableFunctionType : + undefined; + if (functionType) { + var symbol_1 = getPropertyOfObjectType(functionType, name); + if (symbol_1) { + return symbol_1; + } + } + return getPropertyOfObjectType(globalObjectType, name); + } + if (type.flags & 3145728 /* UnionOrIntersection */) { + return getPropertyOfUnionOrIntersectionType(type, name); + } + return undefined; + } + function getSignaturesOfStructuredType(type, kind) { + if (type.flags & 3670016 /* StructuredType */) { + var resolved = resolveStructuredTypeMembers(type); + return kind === 0 /* Call */ ? resolved.callSignatures : resolved.constructSignatures; + } + return ts.emptyArray; + } + /** + * Return the signatures of the given kind in the given type. Creates synthetic union signatures when necessary and + * maps primitive types and type parameters are to their apparent types. + */ + function getSignaturesOfType(type, kind) { + return getSignaturesOfStructuredType(getApparentType(type), kind); + } + function getIndexInfoOfStructuredType(type, kind) { + if (type.flags & 3670016 /* StructuredType */) { + var resolved = resolveStructuredTypeMembers(type); + return kind === 0 /* String */ ? resolved.stringIndexInfo : resolved.numberIndexInfo; + } + } + function getIndexTypeOfStructuredType(type, kind) { + var info = getIndexInfoOfStructuredType(type, kind); + return info && info.type; + } + // Return the indexing info of the given kind in the given type. Creates synthetic union index types when necessary and + // maps primitive types and type parameters are to their apparent types. + function getIndexInfoOfType(type, kind) { + return getIndexInfoOfStructuredType(getApparentType(type), kind); + } + // Return the index type of the given kind in the given type. Creates synthetic union index types when necessary and + // maps primitive types and type parameters are to their apparent types. + function getIndexTypeOfType(type, kind) { + return getIndexTypeOfStructuredType(getApparentType(type), kind); + } + function getImplicitIndexTypeOfType(type, kind) { + if (isObjectTypeWithInferableIndex(type)) { + var propTypes = []; + for (var _i = 0, _a = getPropertiesOfType(type); _i < _a.length; _i++) { + var prop = _a[_i]; + if (kind === 0 /* String */ || isNumericLiteralName(prop.escapedName)) { + propTypes.push(getTypeOfSymbol(prop)); + } + } + if (propTypes.length) { + return getUnionType(propTypes, 2 /* Subtype */); + } + } + return undefined; + } + // Return list of type parameters with duplicates removed (duplicate identifier errors are generated in the actual + // type checking functions). + function getTypeParametersFromDeclaration(declaration) { + var result; + for (var _i = 0, _a = ts.getEffectiveTypeParameterDeclarations(declaration); _i < _a.length; _i++) { + var node = _a[_i]; + result = ts.appendIfUnique(result, getDeclaredTypeOfTypeParameter(node.symbol)); + } + return result; + } + function symbolsToArray(symbols) { + var result = []; + symbols.forEach(function (symbol, id) { + if (!isReservedMemberName(id)) { + result.push(symbol); + } + }); + return result; + } + function isJSDocOptionalParameter(node) { + return ts.isInJSFile(node) && ( + // node.type should only be a JSDocOptionalType when node is a parameter of a JSDocFunctionType + node.type && node.type.kind === 288 /* JSDocOptionalType */ + || ts.getJSDocParameterTags(node).some(function (_a) { + var isBracketed = _a.isBracketed, typeExpression = _a.typeExpression; + return isBracketed || !!typeExpression && typeExpression.type.kind === 288 /* JSDocOptionalType */; + })); + } + function tryFindAmbientModule(moduleName, withAugmentations) { + if (ts.isExternalModuleNameRelative(moduleName)) { + return undefined; + } + var symbol = getSymbol(globals, '"' + moduleName + '"', 512 /* ValueModule */); + // merged symbol is module declaration symbol combined with all augmentations + return symbol && withAugmentations ? getMergedSymbol(symbol) : symbol; + } + function isOptionalParameter(node) { + if (ts.hasQuestionToken(node) || isOptionalJSDocParameterTag(node) || isJSDocOptionalParameter(node)) { + return true; + } + if (node.initializer) { + var signature = getSignatureFromDeclaration(node.parent); + var parameterIndex = node.parent.parameters.indexOf(node); + ts.Debug.assert(parameterIndex >= 0); + return parameterIndex >= getMinArgumentCount(signature); + } + var iife = ts.getImmediatelyInvokedFunctionExpression(node.parent); + if (iife) { + return !node.type && + !node.dotDotDotToken && + node.parent.parameters.indexOf(node) >= iife.arguments.length; + } + return false; + } + function isOptionalJSDocParameterTag(node) { + if (!ts.isJSDocParameterTag(node)) { + return false; + } + var isBracketed = node.isBracketed, typeExpression = node.typeExpression; + return isBracketed || !!typeExpression && typeExpression.type.kind === 288 /* JSDocOptionalType */; + } + function createIdentifierTypePredicate(parameterName, parameterIndex, type) { + return { kind: 1 /* Identifier */, parameterName: parameterName, parameterIndex: parameterIndex, type: type }; + } + function createThisTypePredicate(type) { + return { kind: 0 /* This */, type: type }; + } + /** + * Gets the minimum number of type arguments needed to satisfy all non-optional type + * parameters. + */ + function getMinTypeArgumentCount(typeParameters) { + var minTypeArgumentCount = 0; + if (typeParameters) { + for (var i = 0; i < typeParameters.length; i++) { + if (!hasTypeParameterDefault(typeParameters[i])) { + minTypeArgumentCount = i + 1; + } + } + } + return minTypeArgumentCount; + } + function fillMissingTypeArguments(typeArguments, typeParameters, minTypeArgumentCount, isJavaScriptImplicitAny) { + var numTypeParameters = ts.length(typeParameters); + if (!numTypeParameters) { + return []; + } + var numTypeArguments = ts.length(typeArguments); + if (isJavaScriptImplicitAny || (numTypeArguments >= minTypeArgumentCount && numTypeArguments <= numTypeParameters)) { + var result = typeArguments ? typeArguments.slice() : []; + // Map an unsatisfied type parameter with a default type. + // If a type parameter does not have a default type, or if the default type + // is a forward reference, the empty object type is used. + var baseDefaultType_1 = getDefaultTypeArgumentType(isJavaScriptImplicitAny); + var circularityMapper = createTypeMapper(typeParameters, ts.map(typeParameters, function () { return baseDefaultType_1; })); + for (var i = numTypeArguments; i < numTypeParameters; i++) { + result[i] = instantiateType(getConstraintFromTypeParameter(typeParameters[i]) || baseDefaultType_1, circularityMapper); + } + for (var i = numTypeArguments; i < numTypeParameters; i++) { + var mapper = createTypeMapper(typeParameters, result); + var defaultType = getDefaultFromTypeParameter(typeParameters[i]); + if (isJavaScriptImplicitAny && defaultType && isTypeIdenticalTo(defaultType, emptyObjectType)) { + defaultType = anyType; + } + result[i] = defaultType ? instantiateType(defaultType, mapper) : baseDefaultType_1; + } + result.length = typeParameters.length; + return result; + } + return typeArguments && typeArguments.slice(); + } + function getSignatureFromDeclaration(declaration) { + var links = getNodeLinks(declaration); + if (!links.resolvedSignature) { + var parameters = []; + var hasLiteralTypes = false; + var minArgumentCount = 0; + var thisParameter = void 0; + var hasThisParameter = false; + var iife = ts.getImmediatelyInvokedFunctionExpression(declaration); + var isJSConstructSignature = ts.isJSDocConstructSignature(declaration); + var isUntypedSignatureInJSFile = !iife && + ts.isInJSFile(declaration) && + ts.isValueSignatureDeclaration(declaration) && + !ts.hasJSDocParameterTags(declaration) && + !ts.getJSDocType(declaration); + // If this is a JSDoc construct signature, then skip the first parameter in the + // parameter list. The first parameter represents the return type of the construct + // signature. + for (var i = isJSConstructSignature ? 1 : 0; i < declaration.parameters.length; i++) { + var param = declaration.parameters[i]; + var paramSymbol = param.symbol; + var type = ts.isJSDocParameterTag(param) ? (param.typeExpression && param.typeExpression.type) : param.type; + // Include parameter symbol instead of property symbol in the signature + if (paramSymbol && !!(paramSymbol.flags & 4 /* Property */) && !ts.isBindingPattern(param.name)) { + var resolvedSymbol = resolveName(param, paramSymbol.escapedName, 67220415 /* Value */, undefined, undefined, /*isUse*/ false); + paramSymbol = resolvedSymbol; + } + if (i === 0 && paramSymbol.escapedName === "this" /* This */) { + hasThisParameter = true; + thisParameter = param.symbol; + } + else { + parameters.push(paramSymbol); + } + if (type && type.kind === 182 /* LiteralType */) { + hasLiteralTypes = true; + } + // Record a new minimum argument count if this is not an optional parameter + var isOptionalParameter_1 = isOptionalJSDocParameterTag(param) || + param.initializer || param.questionToken || param.dotDotDotToken || + iife && parameters.length > iife.arguments.length && !type || + isUntypedSignatureInJSFile || + isJSDocOptionalParameter(param); + if (!isOptionalParameter_1) { + minArgumentCount = parameters.length; + } + } + // If only one accessor includes a this-type annotation, the other behaves as if it had the same type annotation + if ((declaration.kind === 158 /* GetAccessor */ || declaration.kind === 159 /* SetAccessor */) && + !hasNonBindableDynamicName(declaration) && + (!hasThisParameter || !thisParameter)) { + var otherKind = declaration.kind === 158 /* GetAccessor */ ? 159 /* SetAccessor */ : 158 /* GetAccessor */; + var other = ts.getDeclarationOfKind(getSymbolOfNode(declaration), otherKind); + if (other) { + thisParameter = getAnnotatedAccessorThisParameter(other); + } + } + var classType = declaration.kind === 157 /* Constructor */ ? + getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)) + : undefined; + var typeParameters = classType ? classType.localTypeParameters : getTypeParametersFromDeclaration(declaration); + var hasRestLikeParameter = ts.hasRestParameter(declaration) || ts.isInJSFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters); + links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, + /*resolvedReturnType*/ undefined, /*resolvedTypePredicate*/ undefined, minArgumentCount, hasRestLikeParameter, hasLiteralTypes); + } + return links.resolvedSignature; + } + /** + * A JS function gets a synthetic rest parameter if it references `arguments` AND: + * 1. It has no parameters but at least one `@param` with a type that starts with `...` + * OR + * 2. It has at least one parameter, and the last parameter has a matching `@param` with a type that starts with `...` + */ + function maybeAddJsSyntheticRestParameter(declaration, parameters) { + if (ts.isJSDocSignature(declaration) || !containsArgumentsReference(declaration)) { + return false; + } + var lastParam = ts.lastOrUndefined(declaration.parameters); + var lastParamTags = lastParam ? ts.getJSDocParameterTags(lastParam) : ts.getJSDocTags(declaration).filter(ts.isJSDocParameterTag); + var lastParamVariadicType = ts.firstDefined(lastParamTags, function (p) { + return p.typeExpression && ts.isJSDocVariadicType(p.typeExpression.type) ? p.typeExpression.type : undefined; + }); + var syntheticArgsSymbol = createSymbol(3 /* Variable */, "args", 8192 /* RestParameter */); + syntheticArgsSymbol.type = lastParamVariadicType ? createArrayType(getTypeFromTypeNode(lastParamVariadicType.type)) : anyArrayType; + if (lastParamVariadicType) { + // Replace the last parameter with a rest parameter. + parameters.pop(); + } + parameters.push(syntheticArgsSymbol); + return true; + } + function getSignatureOfTypeTag(node) { + var typeTag = ts.isInJSFile(node) ? ts.getJSDocTypeTag(node) : undefined; + var signature = typeTag && typeTag.typeExpression && getSingleCallSignature(getTypeFromTypeNode(typeTag.typeExpression)); + return signature && getErasedSignature(signature); + } + function getReturnTypeOfTypeTag(node) { + var signature = getSignatureOfTypeTag(node); + return signature && getReturnTypeOfSignature(signature); + } + function containsArgumentsReference(declaration) { + var links = getNodeLinks(declaration); + if (links.containsArgumentsReference === undefined) { + if (links.flags & 8192 /* CaptureArguments */) { + links.containsArgumentsReference = true; + } + else { + links.containsArgumentsReference = traverse(declaration.body); + } + } + return links.containsArgumentsReference; + function traverse(node) { + if (!node) + return false; + switch (node.kind) { + case 72 /* Identifier */: + return node.escapedText === "arguments" && ts.isExpressionNode(node); + case 154 /* PropertyDeclaration */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + return node.name.kind === 149 /* ComputedPropertyName */ + && traverse(node.name); + default: + return !ts.nodeStartsNewLexicalEnvironment(node) && !ts.isPartOfTypeNode(node) && !!ts.forEachChild(node, traverse); + } + } + } + function getSignaturesOfSymbol(symbol) { + if (!symbol) + return ts.emptyArray; + var result = []; + for (var i = 0; i < symbol.declarations.length; i++) { + var decl = symbol.declarations[i]; + if (!ts.isFunctionLike(decl)) + continue; + // Don't include signature if node is the implementation of an overloaded function. A node is considered + // an implementation node if it has a body and the previous node is of the same kind and immediately + // precedes the implementation node (i.e. has the same parent and ends where the implementation starts). + if (i > 0 && decl.body) { + var previous = symbol.declarations[i - 1]; + if (decl.parent === previous.parent && decl.kind === previous.kind && decl.pos === previous.end) { + continue; + } + } + result.push(getSignatureFromDeclaration(decl)); + } + return result; + } + function resolveExternalModuleTypeByLiteral(name) { + var moduleSym = resolveExternalModuleName(name, name); + if (moduleSym) { + var resolvedModuleSymbol = resolveExternalModuleSymbol(moduleSym); + if (resolvedModuleSymbol) { + return getTypeOfSymbol(resolvedModuleSymbol); + } + } + return anyType; + } + function getThisTypeOfSignature(signature) { + if (signature.thisParameter) { + return getTypeOfSymbol(signature.thisParameter); + } + } + function signatureHasTypePredicate(signature) { + return getTypePredicateOfSignature(signature) !== undefined; + } + function getTypePredicateOfSignature(signature) { + if (!signature.resolvedTypePredicate) { + if (signature.target) { + var targetTypePredicate = getTypePredicateOfSignature(signature.target); + signature.resolvedTypePredicate = targetTypePredicate ? instantiateTypePredicate(targetTypePredicate, signature.mapper) : noTypePredicate; + } + else if (signature.unionSignatures) { + signature.resolvedTypePredicate = getUnionTypePredicate(signature.unionSignatures) || noTypePredicate; + } + else { + var type = signature.declaration && ts.getEffectiveReturnTypeNode(signature.declaration); + var jsdocPredicate = void 0; + if (!type && ts.isInJSFile(signature.declaration)) { + var jsdocSignature = getSignatureOfTypeTag(signature.declaration); + if (jsdocSignature && signature !== jsdocSignature) { + jsdocPredicate = getTypePredicateOfSignature(jsdocSignature); + } + } + signature.resolvedTypePredicate = type && ts.isTypePredicateNode(type) ? + createTypePredicateFromTypePredicateNode(type, signature.declaration) : + jsdocPredicate || noTypePredicate; + } + ts.Debug.assert(!!signature.resolvedTypePredicate); + } + return signature.resolvedTypePredicate === noTypePredicate ? undefined : signature.resolvedTypePredicate; + } + function createTypePredicateFromTypePredicateNode(node, func) { + var parameterName = node.parameterName; + var type = getTypeFromTypeNode(node.type); + if (parameterName.kind === 72 /* Identifier */) { + return createIdentifierTypePredicate(parameterName.escapedText, getTypePredicateParameterIndex(func.parameters, parameterName), type); + } + else { + return createThisTypePredicate(type); + } + } + function getTypePredicateParameterIndex(parameterList, parameter) { + for (var i = 0; i < parameterList.length; i++) { + var param = parameterList[i]; + if (param.name.kind === 72 /* Identifier */ && param.name.escapedText === parameter.escapedText) { + return i; + } + } + return -1; + } + function getReturnTypeOfSignature(signature) { + if (!signature.resolvedReturnType) { + if (!pushTypeResolution(signature, 3 /* ResolvedReturnType */)) { + return errorType; + } + var type = signature.target ? instantiateType(getReturnTypeOfSignature(signature.target), signature.mapper) : + signature.unionSignatures ? getUnionType(ts.map(signature.unionSignatures, getReturnTypeOfSignature), 2 /* Subtype */) : + getReturnTypeFromAnnotation(signature.declaration) || + isJSConstructor(signature.declaration) && getJSClassType(getSymbolOfNode(signature.declaration)) || + (ts.nodeIsMissing(signature.declaration.body) ? anyType : getReturnTypeFromBody(signature.declaration)); + if (!popTypeResolution()) { + if (signature.declaration) { + var typeNode = ts.getEffectiveReturnTypeNode(signature.declaration); + if (typeNode) { + error(typeNode, ts.Diagnostics.Return_type_annotation_circularly_references_itself); + } + else if (noImplicitAny) { + var declaration = signature.declaration; + var name = ts.getNameOfDeclaration(declaration); + if (name) { + error(name, ts.Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, ts.declarationNameToString(name)); + } + else { + error(declaration, ts.Diagnostics.Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions); + } + } + } + type = anyType; + } + signature.resolvedReturnType = type; + } + return signature.resolvedReturnType; + } + function getReturnTypeFromAnnotation(declaration) { + if (declaration.kind === 157 /* Constructor */) { + return getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)); + } + if (ts.isJSDocConstructSignature(declaration)) { + return getTypeFromTypeNode(declaration.parameters[0].type); // TODO: GH#18217 + } + var typeNode = ts.getEffectiveReturnTypeNode(declaration); + if (typeNode) { + return getTypeFromTypeNode(typeNode); + } + if (declaration.kind === 158 /* GetAccessor */ && !hasNonBindableDynamicName(declaration)) { + var jsDocType = ts.isInJSFile(declaration) && getTypeForDeclarationFromJSDocComment(declaration); + if (jsDocType) { + return jsDocType; + } + var setter = ts.getDeclarationOfKind(getSymbolOfNode(declaration), 159 /* SetAccessor */); + var setterType = getAnnotatedAccessorType(setter); + if (setterType) { + return setterType; + } + } + return getReturnTypeOfTypeTag(declaration); + } + function isResolvingReturnTypeOfSignature(signature) { + return !signature.resolvedReturnType && findResolutionCycleStartIndex(signature, 3 /* ResolvedReturnType */) >= 0; + } + function getRestTypeOfSignature(signature) { + return tryGetRestTypeOfSignature(signature) || anyType; + } + function tryGetRestTypeOfSignature(signature) { + if (signature.hasRestParameter) { + var sigRestType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); + var restType = isTupleType(sigRestType) ? getRestTypeOfTupleType(sigRestType) : sigRestType; + return restType && getIndexTypeOfType(restType, 1 /* Number */); + } + return undefined; + } + function getSignatureInstantiation(signature, typeArguments, isJavascript) { + return getSignatureInstantiationWithoutFillingInTypeArguments(signature, fillMissingTypeArguments(typeArguments, signature.typeParameters, getMinTypeArgumentCount(signature.typeParameters), isJavascript)); + } + function getSignatureInstantiationWithoutFillingInTypeArguments(signature, typeArguments) { + var instantiations = signature.instantiations || (signature.instantiations = ts.createMap()); + var id = getTypeListId(typeArguments); + var instantiation = instantiations.get(id); + if (!instantiation) { + instantiations.set(id, instantiation = createSignatureInstantiation(signature, typeArguments)); + } + return instantiation; + } + function createSignatureInstantiation(signature, typeArguments) { + return instantiateSignature(signature, createSignatureTypeMapper(signature, typeArguments), /*eraseTypeParameters*/ true); + } + function createSignatureTypeMapper(signature, typeArguments) { + return createTypeMapper(signature.typeParameters, typeArguments); + } + function getErasedSignature(signature) { + return signature.typeParameters ? + signature.erasedSignatureCache || (signature.erasedSignatureCache = createErasedSignature(signature)) : + signature; + } + function createErasedSignature(signature) { + // Create an instantiation of the signature where all type arguments are the any type. + return instantiateSignature(signature, createTypeEraser(signature.typeParameters), /*eraseTypeParameters*/ true); + } + function getCanonicalSignature(signature) { + return signature.typeParameters ? + signature.canonicalSignatureCache || (signature.canonicalSignatureCache = createCanonicalSignature(signature)) : + signature; + } + function createCanonicalSignature(signature) { + // Create an instantiation of the signature where each unconstrained type parameter is replaced with + // its original. When a generic class or interface is instantiated, each generic method in the class or + // interface is instantiated with a fresh set of cloned type parameters (which we need to handle scenarios + // where different generations of the same type parameter are in scope). This leads to a lot of new type + // identities, and potentially a lot of work comparing those identities, so here we create an instantiation + // that uses the original type identities for all unconstrained type parameters. + return getSignatureInstantiation(signature, ts.map(signature.typeParameters, function (tp) { return tp.target && !getConstraintOfTypeParameter(tp.target) ? tp.target : tp; }), ts.isInJSFile(signature.declaration)); + } + function getBaseSignature(signature) { + var typeParameters = signature.typeParameters; + if (typeParameters) { + var typeEraser_1 = createTypeEraser(typeParameters); + var baseConstraints = ts.map(typeParameters, function (tp) { return instantiateType(getBaseConstraintOfType(tp), typeEraser_1) || emptyObjectType; }); + return instantiateSignature(signature, createTypeMapper(typeParameters, baseConstraints), /*eraseTypeParameters*/ true); + } + return signature; + } + function getOrCreateTypeFromSignature(signature) { + // There are two ways to declare a construct signature, one is by declaring a class constructor + // using the constructor keyword, and the other is declaring a bare construct signature in an + // object type literal or interface (using the new keyword). Each way of declaring a constructor + // will result in a different declaration kind. + if (!signature.isolatedSignatureType) { + var isConstructor = signature.declaration.kind === 157 /* Constructor */ || signature.declaration.kind === 161 /* ConstructSignature */; // TODO: GH#18217 + var type = createObjectType(16 /* Anonymous */); + type.members = emptySymbols; + type.properties = ts.emptyArray; + type.callSignatures = !isConstructor ? [signature] : ts.emptyArray; + type.constructSignatures = isConstructor ? [signature] : ts.emptyArray; + signature.isolatedSignatureType = type; + } + return signature.isolatedSignatureType; + } + function getIndexSymbol(symbol) { + return symbol.members.get("__index" /* Index */); + } + function getIndexDeclarationOfSymbol(symbol, kind) { + var syntaxKind = kind === 1 /* Number */ ? 135 /* NumberKeyword */ : 138 /* StringKeyword */; + var indexSymbol = getIndexSymbol(symbol); + if (indexSymbol) { + for (var _i = 0, _a = indexSymbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + var node = ts.cast(decl, ts.isIndexSignatureDeclaration); + if (node.parameters.length === 1) { + var parameter = node.parameters[0]; + if (parameter.type && parameter.type.kind === syntaxKind) { + return node; + } + } + } + } + return undefined; + } + function createIndexInfo(type, isReadonly, declaration) { + return { type: type, isReadonly: isReadonly, declaration: declaration }; + } + function getIndexInfoOfSymbol(symbol, kind) { + var declaration = getIndexDeclarationOfSymbol(symbol, kind); + if (declaration) { + return createIndexInfo(declaration.type ? getTypeFromTypeNode(declaration.type) : anyType, ts.hasModifier(declaration, 64 /* Readonly */), declaration); + } + return undefined; + } + function getConstraintDeclaration(type) { + var decl = type.symbol && ts.getDeclarationOfKind(type.symbol, 150 /* TypeParameter */); + return decl && ts.getEffectiveConstraintOfTypeParameter(decl); + } + function getInferredTypeParameterConstraint(typeParameter) { + var inferences; + if (typeParameter.symbol) { + for (var _i = 0, _a = typeParameter.symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (declaration.parent.kind === 176 /* InferType */) { + // When an 'infer T' declaration is immediately contained in a type reference node + // (such as 'Foo'), T's constraint is inferred from the constraint of the + // corresponding type parameter in 'Foo'. When multiple 'infer T' declarations are + // present, we form an intersection of the inferred constraint types. + var grandParent = declaration.parent.parent; + if (grandParent.kind === 164 /* TypeReference */) { + var typeReference = grandParent; + var typeParameters = getTypeParametersForTypeReference(typeReference); + if (typeParameters) { + var index = typeReference.typeArguments.indexOf(declaration.parent); + if (index < typeParameters.length) { + var declaredConstraint = getConstraintOfTypeParameter(typeParameters[index]); + if (declaredConstraint) { + // Type parameter constraints can reference other type parameters so + // constraints need to be instantiated. If instantiation produces the + // type parameter itself, we discard that inference. For example, in + // type Foo = [T, U]; + // type Bar = T extends Foo ? Foo : T; + // the instantiated constraint for U is X, so we discard that inference. + var mapper = createTypeMapper(typeParameters, getEffectiveTypeArguments(typeReference, typeParameters)); + var constraint = instantiateType(declaredConstraint, mapper); + if (constraint !== typeParameter) { + inferences = ts.append(inferences, constraint); + } + } + } + } + } + // When an 'infer T' declaration is immediately contained in a rest parameter + // declaration, we infer an 'unknown[]' constraint. + else if (grandParent.kind === 151 /* Parameter */ && grandParent.dotDotDotToken) { + inferences = ts.append(inferences, createArrayType(unknownType)); + } + } + } + } + return inferences && getIntersectionType(inferences); + } + /** This is a worker function. Use getConstraintOfTypeParameter which guards against circular constraints. */ + function getConstraintFromTypeParameter(typeParameter) { + if (!typeParameter.constraint) { + if (typeParameter.target) { + var targetConstraint = getConstraintOfTypeParameter(typeParameter.target); + typeParameter.constraint = targetConstraint ? instantiateType(targetConstraint, typeParameter.mapper) : noConstraintType; + } + else { + var constraintDeclaration = getConstraintDeclaration(typeParameter); + typeParameter.constraint = constraintDeclaration ? getTypeFromTypeNode(constraintDeclaration) : + getInferredTypeParameterConstraint(typeParameter) || noConstraintType; + } + } + return typeParameter.constraint === noConstraintType ? undefined : typeParameter.constraint; + } + function getParentSymbolOfTypeParameter(typeParameter) { + var tp = ts.getDeclarationOfKind(typeParameter.symbol, 150 /* TypeParameter */); + var host = ts.isJSDocTemplateTag(tp.parent) ? ts.getHostSignatureFromJSDoc(tp.parent) : tp.parent; + return host && getSymbolOfNode(host); + } + function getTypeListId(types) { + var result = ""; + if (types) { + var length_3 = types.length; + var i = 0; + while (i < length_3) { + var startId = types[i].id; + var count = 1; + while (i + count < length_3 && types[i + count].id === startId + count) { + count++; + } + if (result.length) { + result += ","; + } + result += startId; + if (count > 1) { + result += ":" + count; + } + i += count; + } + } + return result; + } + // This function is used to propagate certain flags when creating new object type references and union types. + // It is only necessary to do so if a constituent type might be the undefined type, the null type, the type + // of an object literal or the anyFunctionType. This is because there are operations in the type checker + // that care about the presence of such types at arbitrary depth in a containing type. + function getPropagatingFlagsOfTypes(types, excludeKinds) { + var result = 0; + for (var _i = 0, types_5 = types; _i < types_5.length; _i++) { + var type = types_5[_i]; + if (!(type.flags & excludeKinds)) { + result |= type.flags; + } + } + return result & 939524096 /* PropagatingFlags */; + } + function createTypeReference(target, typeArguments) { + var id = getTypeListId(typeArguments); + var type = target.instantiations.get(id); + if (!type) { + type = createObjectType(4 /* Reference */, target.symbol); + target.instantiations.set(id, type); + type.flags |= typeArguments ? getPropagatingFlagsOfTypes(typeArguments, /*excludeKinds*/ 0) : 0; + type.target = target; + type.typeArguments = typeArguments; + } + return type; + } + function cloneTypeReference(source) { + var type = createType(source.flags); + type.symbol = source.symbol; + type.objectFlags = source.objectFlags; + type.target = source.target; + type.typeArguments = source.typeArguments; + return type; + } + function getTypeReferenceArity(type) { + return ts.length(type.target.typeParameters); + } + /** + * Get type from type-reference that reference to class or interface + */ + function getTypeFromClassOrInterfaceReference(node, symbol, typeArgs) { + var type = getDeclaredTypeOfSymbol(getMergedSymbol(symbol)); + var typeParameters = type.localTypeParameters; + if (typeParameters) { + var numTypeArguments = ts.length(node.typeArguments); + var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters); + var isJs = ts.isInJSFile(node); + var isJsImplicitAny = !noImplicitAny && isJs; + if (!isJsImplicitAny && (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length)) { + var missingAugmentsTag = isJs && ts.isExpressionWithTypeArguments(node) && !ts.isJSDocAugmentsTag(node.parent); + var diag = minTypeArgumentCount === typeParameters.length + ? missingAugmentsTag + ? ts.Diagnostics.Expected_0_type_arguments_provide_these_with_an_extends_tag + : ts.Diagnostics.Generic_type_0_requires_1_type_argument_s + : missingAugmentsTag + ? ts.Diagnostics.Expected_0_1_type_arguments_provide_these_with_an_extends_tag + : ts.Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments; + var typeStr = typeToString(type, /*enclosingDeclaration*/ undefined, 2 /* WriteArrayAsGenericType */); + error(node, diag, typeStr, minTypeArgumentCount, typeParameters.length); + if (!isJs) { + // TODO: Adopt same permissive behavior in TS as in JS to reduce follow-on editing experience failures (requires editing fillMissingTypeArguments) + return errorType; + } + } + // In a type reference, the outer type parameters of the referenced class or interface are automatically + // supplied as type arguments and the type reference only specifies arguments for the local type parameters + // of the class or interface. + var typeArguments = ts.concatenate(type.outerTypeParameters, fillMissingTypeArguments(typeArgs, typeParameters, minTypeArgumentCount, isJs)); + return createTypeReference(type, typeArguments); + } + return checkNoTypeArguments(node, symbol) ? type : errorType; + } + function getTypeAliasInstantiation(symbol, typeArguments) { + var type = getDeclaredTypeOfSymbol(symbol); + var links = getSymbolLinks(symbol); + var typeParameters = links.typeParameters; + var id = getTypeListId(typeArguments); + var instantiation = links.instantiations.get(id); + if (!instantiation) { + links.instantiations.set(id, instantiation = instantiateType(type, createTypeMapper(typeParameters, fillMissingTypeArguments(typeArguments, typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJSFile(symbol.valueDeclaration))))); + } + return instantiation; + } + /** + * Get type from reference to type alias. When a type alias is generic, the declared type of the type alias may include + * references to the type parameters of the alias. We replace those with the actual type arguments by instantiating the + * declared type. Instantiations are cached using the type identities of the type arguments as the key. + */ + function getTypeFromTypeAliasReference(node, symbol, typeArguments) { + var type = getDeclaredTypeOfSymbol(symbol); + var typeParameters = getSymbolLinks(symbol).typeParameters; + if (typeParameters) { + var numTypeArguments = ts.length(node.typeArguments); + var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters); + if (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length) { + error(node, minTypeArgumentCount === typeParameters.length + ? ts.Diagnostics.Generic_type_0_requires_1_type_argument_s + : ts.Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments, symbolToString(symbol), minTypeArgumentCount, typeParameters.length); + return errorType; + } + return getTypeAliasInstantiation(symbol, typeArguments); + } + return checkNoTypeArguments(node, symbol) ? type : errorType; + } + function getTypeReferenceName(node) { + switch (node.kind) { + case 164 /* TypeReference */: + return node.typeName; + case 211 /* ExpressionWithTypeArguments */: + // We only support expressions that are simple qualified names. For other + // expressions this produces undefined. + var expr = node.expression; + if (ts.isEntityNameExpression(expr)) { + return expr; + } + // fall through; + } + return undefined; + } + function resolveTypeReferenceName(typeReferenceName, meaning) { + if (!typeReferenceName) { + return unknownSymbol; + } + return resolveEntityName(typeReferenceName, meaning) || unknownSymbol; + } + function getTypeReferenceType(node, symbol) { + var typeArguments = typeArgumentsFromTypeReferenceNode(node); // Do unconditionally so we mark type arguments as referenced. + if (symbol === unknownSymbol) { + return errorType; + } + var type = getTypeReferenceTypeWorker(node, symbol, typeArguments); + if (type) { + return type; + } + // JS enums are 'string' or 'number', not an enum type. + var enumTag = ts.isInJSFile(node) && symbol.valueDeclaration && ts.getJSDocEnumTag(symbol.valueDeclaration); + if (enumTag) { + var links = getNodeLinks(enumTag); + if (!pushTypeResolution(enumTag, 5 /* EnumTagType */)) { + return errorType; + } + var type_4 = enumTag.typeExpression ? getTypeFromTypeNode(enumTag.typeExpression) : errorType; + if (!popTypeResolution()) { + type_4 = errorType; + error(node, ts.Diagnostics.Enum_type_0_circularly_references_itself, symbolToString(symbol)); + } + return (links.resolvedEnumType = type_4); + } + // Get type from reference to named type that cannot be generic (enum or type parameter) + var res = tryGetDeclaredTypeOfSymbol(symbol); + if (res) { + return checkNoTypeArguments(node, symbol) ? + res.flags & 262144 /* TypeParameter */ ? getConstrainedTypeVariable(res, node) : getRegularTypeOfLiteralType(res) : + errorType; + } + if (!(symbol.flags & 67220415 /* Value */ && isJSDocTypeReference(node))) { + return errorType; + } + var jsdocType = getJSDocTypeReference(node, symbol, typeArguments); + if (jsdocType) { + return jsdocType; + } + // Resolve the type reference as a Type for the purpose of reporting errors. + resolveTypeReferenceName(getTypeReferenceName(node), 67897832 /* Type */); + return getTypeOfSymbol(symbol); + } + /** + * A jsdoc TypeReference may have resolved to a value (as opposed to a type). If + * the symbol is a constructor function, return the inferred class type; otherwise, + * the type of this reference is just the type of the value we resolved to. + */ + function getJSDocTypeReference(node, symbol, typeArguments) { + if (!pushTypeResolution(symbol, 6 /* JSDocTypeReference */)) { + return errorType; + } + var assignedType = getAssignedClassType(symbol); + var valueType = getTypeOfSymbol(symbol); + var referenceType = valueType.symbol && valueType.symbol !== symbol && !isInferredClassType(valueType) && getTypeReferenceTypeWorker(node, valueType.symbol, typeArguments); + if (!popTypeResolution()) { + getSymbolLinks(symbol).resolvedJSDocType = errorType; + error(node, ts.Diagnostics.JSDoc_type_0_circularly_references_itself, symbolToString(symbol)); + return errorType; + } + if (referenceType || assignedType) { + // TODO: GH#18217 (should the `|| assignedType` be at a lower precedence?) + var type = (referenceType && assignedType ? getIntersectionType([assignedType, referenceType]) : referenceType || assignedType); + return getSymbolLinks(symbol).resolvedJSDocType = type; + } + } + function getTypeReferenceTypeWorker(node, symbol, typeArguments) { + if (symbol.flags & (32 /* Class */ | 64 /* Interface */)) { + if (symbol.valueDeclaration && ts.isBinaryExpression(symbol.valueDeclaration.parent)) { + var jsdocType = getJSDocTypeReference(node, symbol, typeArguments); + if (jsdocType) { + return jsdocType; + } + } + return getTypeFromClassOrInterfaceReference(node, symbol, typeArguments); + } + if (symbol.flags & 524288 /* TypeAlias */) { + return getTypeFromTypeAliasReference(node, symbol, typeArguments); + } + if (symbol.flags & 16 /* Function */ && + isJSDocTypeReference(node) && + (symbol.members || ts.getJSDocClassTag(symbol.valueDeclaration))) { + return getInferredClassType(symbol); + } + } + function getSubstitutionType(typeVariable, substitute) { + var result = createType(33554432 /* Substitution */); + result.typeVariable = typeVariable; + result.substitute = substitute; + return result; + } + function isUnaryTupleTypeNode(node) { + return node.kind === 170 /* TupleType */ && node.elementTypes.length === 1; + } + function getImpliedConstraint(typeVariable, checkNode, extendsNode) { + return isUnaryTupleTypeNode(checkNode) && isUnaryTupleTypeNode(extendsNode) ? getImpliedConstraint(typeVariable, checkNode.elementTypes[0], extendsNode.elementTypes[0]) : + getActualTypeVariable(getTypeFromTypeNode(checkNode)) === typeVariable ? getTypeFromTypeNode(extendsNode) : + undefined; + } + function getConstrainedTypeVariable(typeVariable, node) { + var constraints; + while (node && !ts.isStatement(node) && node.kind !== 291 /* JSDocComment */) { + var parent = node.parent; + if (parent.kind === 175 /* ConditionalType */ && node === parent.trueType) { + var constraint = getImpliedConstraint(typeVariable, parent.checkType, parent.extendsType); + if (constraint) { + constraints = ts.append(constraints, constraint); + } + } + node = parent; + } + return constraints ? getSubstitutionType(typeVariable, getIntersectionType(ts.append(constraints, typeVariable))) : typeVariable; + } + function isJSDocTypeReference(node) { + return !!(node.flags & 2097152 /* JSDoc */) && (node.kind === 164 /* TypeReference */ || node.kind === 183 /* ImportType */); + } + function checkNoTypeArguments(node, symbol) { + if (node.typeArguments) { + error(node, ts.Diagnostics.Type_0_is_not_generic, symbol ? symbolToString(symbol) : node.typeName ? ts.declarationNameToString(node.typeName) : "(anonymous)"); + return false; + } + return true; + } + function getIntendedTypeFromJSDocTypeReference(node) { + if (ts.isIdentifier(node.typeName)) { + var typeArgs = node.typeArguments; + switch (node.typeName.escapedText) { + case "String": + checkNoTypeArguments(node); + return stringType; + case "Number": + checkNoTypeArguments(node); + return numberType; + case "Boolean": + checkNoTypeArguments(node); + return booleanType; + case "Void": + checkNoTypeArguments(node); + return voidType; + case "Undefined": + checkNoTypeArguments(node); + return undefinedType; + case "Null": + checkNoTypeArguments(node); + return nullType; + case "Function": + case "function": + checkNoTypeArguments(node); + return globalFunctionType; + case "Array": + case "array": + return !typeArgs || !typeArgs.length ? anyArrayType : undefined; + case "Promise": + case "promise": + return !typeArgs || !typeArgs.length ? createPromiseType(anyType) : undefined; + case "Object": + if (typeArgs && typeArgs.length === 2) { + if (ts.isJSDocIndexSignature(node)) { + var indexed = getTypeFromTypeNode(typeArgs[0]); + var target = getTypeFromTypeNode(typeArgs[1]); + var index = createIndexInfo(target, /*isReadonly*/ false); + return createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, indexed === stringType ? index : undefined, indexed === numberType ? index : undefined); + } + return anyType; + } + checkNoTypeArguments(node); + return anyType; + } + } + } + function getTypeFromJSDocNullableTypeNode(node) { + var type = getTypeFromTypeNode(node.type); + return strictNullChecks ? getNullableType(type, 65536 /* Null */) : type; + } + function getTypeFromTypeReference(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + var symbol = void 0; + var type = void 0; + var meaning = 67897832 /* Type */; + if (isJSDocTypeReference(node)) { + type = getIntendedTypeFromJSDocTypeReference(node); + meaning |= 67220415 /* Value */; + } + if (!type) { + symbol = resolveTypeReferenceName(getTypeReferenceName(node), meaning); + type = getTypeReferenceType(node, symbol); + } + // Cache both the resolved symbol and the resolved type. The resolved symbol is needed when we check the + // type reference in checkTypeReferenceNode. + links.resolvedSymbol = symbol; + links.resolvedType = type; + } + return links.resolvedType; + } + function typeArgumentsFromTypeReferenceNode(node) { + return ts.map(node.typeArguments, getTypeFromTypeNode); + } + function getTypeFromTypeQueryNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + // TypeScript 1.0 spec (April 2014): 3.6.3 + // The expression is processed as an identifier expression (section 4.3) + // or property access expression(section 4.10), + // the widened type(section 3.9) of which becomes the result. + links.resolvedType = getRegularTypeOfLiteralType(getWidenedType(checkExpression(node.exprName))); + } + return links.resolvedType; + } + function getTypeOfGlobalSymbol(symbol, arity) { + function getTypeDeclaration(symbol) { + var declarations = symbol.declarations; + for (var _i = 0, declarations_3 = declarations; _i < declarations_3.length; _i++) { + var declaration = declarations_3[_i]; + switch (declaration.kind) { + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + case 243 /* EnumDeclaration */: + return declaration; + } + } + } + if (!symbol) { + return arity ? emptyGenericType : emptyObjectType; + } + var type = getDeclaredTypeOfSymbol(symbol); + if (!(type.flags & 524288 /* Object */)) { + error(getTypeDeclaration(symbol), ts.Diagnostics.Global_type_0_must_be_a_class_or_interface_type, ts.symbolName(symbol)); + return arity ? emptyGenericType : emptyObjectType; + } + if (ts.length(type.typeParameters) !== arity) { + error(getTypeDeclaration(symbol), ts.Diagnostics.Global_type_0_must_have_1_type_parameter_s, ts.symbolName(symbol), arity); + return arity ? emptyGenericType : emptyObjectType; + } + return type; + } + function getGlobalValueSymbol(name, reportErrors) { + return getGlobalSymbol(name, 67220415 /* Value */, reportErrors ? ts.Diagnostics.Cannot_find_global_value_0 : undefined); + } + function getGlobalTypeSymbol(name, reportErrors) { + return getGlobalSymbol(name, 67897832 /* Type */, reportErrors ? ts.Diagnostics.Cannot_find_global_type_0 : undefined); + } + function getGlobalSymbol(name, meaning, diagnostic) { + // Don't track references for global symbols anyway, so value if `isReference` is arbitrary + return resolveName(undefined, name, meaning, diagnostic, name, /*isUse*/ false); + } + function getGlobalType(name, arity, reportErrors) { + var symbol = getGlobalTypeSymbol(name, reportErrors); + return symbol || reportErrors ? getTypeOfGlobalSymbol(symbol, arity) : undefined; + } + function getGlobalTypedPropertyDescriptorType() { + return deferredGlobalTypedPropertyDescriptorType || (deferredGlobalTypedPropertyDescriptorType = getGlobalType("TypedPropertyDescriptor", /*arity*/ 1, /*reportErrors*/ true)) || emptyGenericType; + } + function getGlobalTemplateStringsArrayType() { + return deferredGlobalTemplateStringsArrayType || (deferredGlobalTemplateStringsArrayType = getGlobalType("TemplateStringsArray", /*arity*/ 0, /*reportErrors*/ true)) || emptyObjectType; + } + function getGlobalImportMetaType() { + return deferredGlobalImportMetaType || (deferredGlobalImportMetaType = getGlobalType("ImportMeta", /*arity*/ 0, /*reportErrors*/ true)) || emptyObjectType; + } + function getGlobalESSymbolConstructorSymbol(reportErrors) { + return deferredGlobalESSymbolConstructorSymbol || (deferredGlobalESSymbolConstructorSymbol = getGlobalValueSymbol("Symbol", reportErrors)); + } + function getGlobalESSymbolType(reportErrors) { + return deferredGlobalESSymbolType || (deferredGlobalESSymbolType = getGlobalType("Symbol", /*arity*/ 0, reportErrors)) || emptyObjectType; + } + function getGlobalPromiseType(reportErrors) { + return deferredGlobalPromiseType || (deferredGlobalPromiseType = getGlobalType("Promise", /*arity*/ 1, reportErrors)) || emptyGenericType; + } + function getGlobalPromiseLikeType(reportErrors) { + return deferredGlobalPromiseLikeType || (deferredGlobalPromiseLikeType = getGlobalType("PromiseLike", /*arity*/ 1, reportErrors)) || emptyGenericType; + } + function getGlobalPromiseConstructorSymbol(reportErrors) { + return deferredGlobalPromiseConstructorSymbol || (deferredGlobalPromiseConstructorSymbol = getGlobalValueSymbol("Promise", reportErrors)); + } + function getGlobalPromiseConstructorLikeType(reportErrors) { + return deferredGlobalPromiseConstructorLikeType || (deferredGlobalPromiseConstructorLikeType = getGlobalType("PromiseConstructorLike", /*arity*/ 0, reportErrors)) || emptyObjectType; + } + function getGlobalAsyncIterableType(reportErrors) { + return deferredGlobalAsyncIterableType || (deferredGlobalAsyncIterableType = getGlobalType("AsyncIterable", /*arity*/ 1, reportErrors)) || emptyGenericType; + } + function getGlobalAsyncIteratorType(reportErrors) { + return deferredGlobalAsyncIteratorType || (deferredGlobalAsyncIteratorType = getGlobalType("AsyncIterator", /*arity*/ 1, reportErrors)) || emptyGenericType; + } + function getGlobalAsyncIterableIteratorType(reportErrors) { + return deferredGlobalAsyncIterableIteratorType || (deferredGlobalAsyncIterableIteratorType = getGlobalType("AsyncIterableIterator", /*arity*/ 1, reportErrors)) || emptyGenericType; + } + function getGlobalIterableType(reportErrors) { + return deferredGlobalIterableType || (deferredGlobalIterableType = getGlobalType("Iterable", /*arity*/ 1, reportErrors)) || emptyGenericType; + } + function getGlobalIteratorType(reportErrors) { + return deferredGlobalIteratorType || (deferredGlobalIteratorType = getGlobalType("Iterator", /*arity*/ 1, reportErrors)) || emptyGenericType; + } + function getGlobalIterableIteratorType(reportErrors) { + return deferredGlobalIterableIteratorType || (deferredGlobalIterableIteratorType = getGlobalType("IterableIterator", /*arity*/ 1, reportErrors)) || emptyGenericType; + } + function getGlobalTypeOrUndefined(name, arity) { + if (arity === void 0) { arity = 0; } + var symbol = getGlobalSymbol(name, 67897832 /* Type */, /*diagnostic*/ undefined); + return symbol && getTypeOfGlobalSymbol(symbol, arity); + } + function getGlobalExtractSymbol() { + return deferredGlobalExtractSymbol || (deferredGlobalExtractSymbol = getGlobalSymbol("Extract", 524288 /* TypeAlias */, ts.Diagnostics.Cannot_find_global_type_0)); // TODO: GH#18217 + } + function getGlobalExcludeSymbol() { + return deferredGlobalExcludeSymbol || (deferredGlobalExcludeSymbol = getGlobalSymbol("Exclude", 524288 /* TypeAlias */, ts.Diagnostics.Cannot_find_global_type_0)); // TODO: GH#18217 + } + function getGlobalPickSymbol() { + return deferredGlobalPickSymbol || (deferredGlobalPickSymbol = getGlobalSymbol("Pick", 524288 /* TypeAlias */, ts.Diagnostics.Cannot_find_global_type_0)); // TODO: GH#18217 + } + function getGlobalBigIntType(reportErrors) { + return deferredGlobalBigIntType || (deferredGlobalBigIntType = getGlobalType("BigInt", /*arity*/ 0, reportErrors)) || emptyObjectType; + } + /** + * Instantiates a global type that is generic with some element type, and returns that instantiation. + */ + function createTypeFromGenericGlobalType(genericGlobalType, typeArguments) { + return genericGlobalType !== emptyGenericType ? createTypeReference(genericGlobalType, typeArguments) : emptyObjectType; + } + function createTypedPropertyDescriptorType(propertyType) { + return createTypeFromGenericGlobalType(getGlobalTypedPropertyDescriptorType(), [propertyType]); + } + function createAsyncIterableType(iteratedType) { + return createTypeFromGenericGlobalType(getGlobalAsyncIterableType(/*reportErrors*/ true), [iteratedType]); + } + function createAsyncIterableIteratorType(iteratedType) { + return createTypeFromGenericGlobalType(getGlobalAsyncIterableIteratorType(/*reportErrors*/ true), [iteratedType]); + } + function createIterableType(iteratedType) { + return createTypeFromGenericGlobalType(getGlobalIterableType(/*reportErrors*/ true), [iteratedType]); + } + function createIterableIteratorType(iteratedType) { + return createTypeFromGenericGlobalType(getGlobalIterableIteratorType(/*reportErrors*/ true), [iteratedType]); + } + function createArrayType(elementType) { + return createTypeFromGenericGlobalType(globalArrayType, [elementType]); + } + function createReadonlyArrayType(elementType) { + return createTypeFromGenericGlobalType(globalReadonlyArrayType, [elementType]); + } + function getTypeFromArrayTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + links.resolvedType = createArrayType(getTypeFromTypeNode(node.elementType)); + } + return links.resolvedType; + } + // We represent tuple types as type references to synthesized generic interface types created by + // this function. The types are of the form: + // + // interface Tuple extends Array { 0: T0, 1: T1, 2: T2, ... } + // + // Note that the generic type created by this function has no symbol associated with it. The same + // is true for each of the synthesized type parameters. + function createTupleTypeOfArity(arity, minLength, hasRestElement, associatedNames) { + var typeParameters; + var properties = []; + var maxLength = hasRestElement ? arity - 1 : arity; + if (arity) { + typeParameters = new Array(arity); + for (var i = 0; i < arity; i++) { + var typeParameter = typeParameters[i] = createType(262144 /* TypeParameter */); + if (i < maxLength) { + var property = createSymbol(4 /* Property */ | (i >= minLength ? 16777216 /* Optional */ : 0), "" + i); + property.type = typeParameter; + properties.push(property); + } + } + } + var literalTypes = []; + for (var i = minLength; i <= maxLength; i++) + literalTypes.push(getLiteralType(i)); + var lengthSymbol = createSymbol(4 /* Property */, "length"); + lengthSymbol.type = hasRestElement ? numberType : getUnionType(literalTypes); + properties.push(lengthSymbol); + var type = createObjectType(8 /* Tuple */ | 4 /* Reference */); + type.typeParameters = typeParameters; + type.outerTypeParameters = undefined; + type.localTypeParameters = typeParameters; + type.instantiations = ts.createMap(); + type.instantiations.set(getTypeListId(type.typeParameters), type); + type.target = type; + type.typeArguments = type.typeParameters; + type.thisType = createType(262144 /* TypeParameter */); + type.thisType.isThisType = true; + type.thisType.constraint = type; + type.declaredProperties = properties; + type.declaredCallSignatures = ts.emptyArray; + type.declaredConstructSignatures = ts.emptyArray; + type.declaredStringIndexInfo = undefined; + type.declaredNumberIndexInfo = undefined; + type.minLength = minLength; + type.hasRestElement = hasRestElement; + type.associatedNames = associatedNames; + return type; + } + function getTupleTypeOfArity(arity, minLength, hasRestElement, associatedNames) { + var key = arity + (hasRestElement ? "+" : ",") + minLength + (associatedNames && associatedNames.length ? "," + associatedNames.join(",") : ""); + var type = tupleTypes.get(key); + if (!type) { + tupleTypes.set(key, type = createTupleTypeOfArity(arity, minLength, hasRestElement, associatedNames)); + } + return type; + } + function createTupleType(elementTypes, minLength, hasRestElement, associatedNames) { + if (minLength === void 0) { minLength = elementTypes.length; } + if (hasRestElement === void 0) { hasRestElement = false; } + var arity = elementTypes.length; + if (arity === 1 && hasRestElement) { + return createArrayType(elementTypes[0]); + } + var tupleType = getTupleTypeOfArity(arity, minLength, arity > 0 && hasRestElement, associatedNames); + return elementTypes.length ? createTypeReference(tupleType, elementTypes) : tupleType; + } + function getTypeFromTupleTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + var lastElement = ts.lastOrUndefined(node.elementTypes); + var restElement_1 = lastElement && lastElement.kind === 172 /* RestType */ ? lastElement : undefined; + var minLength = ts.findLastIndex(node.elementTypes, function (n) { return n.kind !== 171 /* OptionalType */ && n !== restElement_1; }) + 1; + var elementTypes = ts.map(node.elementTypes, function (n) { + var type = getTypeFromTypeNode(n); + return n === restElement_1 && getIndexTypeOfType(type, 1 /* Number */) || type; + }); + links.resolvedType = createTupleType(elementTypes, minLength, !!restElement_1); + } + return links.resolvedType; + } + function sliceTupleType(type, index) { + var tuple = type.target; + if (tuple.hasRestElement) { + // don't slice off rest element + index = Math.min(index, getTypeReferenceArity(type) - 1); + } + return createTupleType((type.typeArguments || ts.emptyArray).slice(index), Math.max(0, tuple.minLength - index), tuple.hasRestElement, tuple.associatedNames && tuple.associatedNames.slice(index)); + } + function getTypeFromOptionalTypeNode(node) { + var type = getTypeFromTypeNode(node.type); + return strictNullChecks ? getOptionalType(type) : type; + } + function getTypeId(type) { + return type.id; + } + function containsType(types, type) { + return ts.binarySearch(types, type, getTypeId, ts.compareValues) >= 0; + } + function insertType(types, type) { + var index = ts.binarySearch(types, type, getTypeId, ts.compareValues); + if (index < 0) { + types.splice(~index, 0, type); + return true; + } + return false; + } + // Return true if the given intersection type contains + // more than one unit type or, + // an object type and a nullable type (null or undefined), or + // a string-like type and a type known to be non-string-like, or + // a number-like type and a type known to be non-number-like, or + // a symbol-like type and a type known to be non-symbol-like, or + // a void-like type and a type known to be non-void-like, or + // a non-primitive type and a type known to be primitive. + function isEmptyIntersectionType(type) { + var combined = 0; + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (t.flags & 109440 /* Unit */ && combined & 109440 /* Unit */) { + return true; + } + combined |= t.flags; + if (combined & 98304 /* Nullable */ && combined & (524288 /* Object */ | 67108864 /* NonPrimitive */) || + combined & 67108864 /* NonPrimitive */ && combined & (67238908 /* DisjointDomains */ & ~67108864 /* NonPrimitive */) || + combined & 132 /* StringLike */ && combined & (67238908 /* DisjointDomains */ & ~132 /* StringLike */) || + combined & 296 /* NumberLike */ && combined & (67238908 /* DisjointDomains */ & ~296 /* NumberLike */) || + combined & 2112 /* BigIntLike */ && combined & (67238908 /* DisjointDomains */ & ~2112 /* BigIntLike */) || + combined & 12288 /* ESSymbolLike */ && combined & (67238908 /* DisjointDomains */ & ~12288 /* ESSymbolLike */) || + combined & 49152 /* VoidLike */ && combined & (67238908 /* DisjointDomains */ & ~49152 /* VoidLike */)) { + return true; + } + } + return false; + } + function addTypeToUnion(typeSet, includes, type) { + var flags = type.flags; + if (flags & 1048576 /* Union */) { + return addTypesToUnion(typeSet, includes, type.types); + } + // We ignore 'never' types in unions. Likewise, we ignore intersections of unit types as they are + // another form of 'never' (in that they have an empty value domain). We could in theory turn + // intersections of unit types into 'never' upon construction, but deferring the reduction makes it + // easier to reason about their origin. + if (!(flags & 131072 /* Never */ || flags & 2097152 /* Intersection */ && isEmptyIntersectionType(type))) { + includes |= flags & ~939524096 /* ConstructionFlags */; + if (type === wildcardType) + includes |= 268435456 /* Wildcard */; + if (!strictNullChecks && flags & 98304 /* Nullable */) { + if (!(flags & 134217728 /* ContainsWideningType */)) + includes |= 134217728 /* NonWideningType */; + } + else { + var len = typeSet.length; + var index = len && type.id > typeSet[len - 1].id ? ~len : ts.binarySearch(typeSet, type, getTypeId, ts.compareValues); + if (index < 0) { + typeSet.splice(~index, 0, type); + } + } + } + return includes; + } + // Add the given types to the given type set. Order is preserved, duplicates are removed, + // and nested types of the given kind are flattened into the set. + function addTypesToUnion(typeSet, includes, types) { + for (var _i = 0, types_6 = types; _i < types_6.length; _i++) { + var type = types_6[_i]; + includes = addTypeToUnion(typeSet, includes, type); + } + return includes; + } + function isSubtypeOfAny(source, targets) { + for (var _i = 0, targets_1 = targets; _i < targets_1.length; _i++) { + var target = targets_1[_i]; + if (source !== target && isTypeSubtypeOf(source, target) && (!(ts.getObjectFlags(getTargetType(source)) & 1 /* Class */) || + !(ts.getObjectFlags(getTargetType(target)) & 1 /* Class */) || + isTypeDerivedFrom(source, target))) { + return true; + } + } + return false; + } + function isSetOfLiteralsFromSameEnum(types) { + var first = types[0]; + if (first.flags & 1024 /* EnumLiteral */) { + var firstEnum = getParentOfSymbol(first.symbol); + for (var i = 1; i < types.length; i++) { + var other = types[i]; + if (!(other.flags & 1024 /* EnumLiteral */) || (firstEnum !== getParentOfSymbol(other.symbol))) { + return false; + } + } + return true; + } + return false; + } + function removeSubtypes(types) { + if (types.length === 0 || isSetOfLiteralsFromSameEnum(types)) { + return; + } + var i = types.length; + while (i > 0) { + i--; + if (isSubtypeOfAny(types[i], types)) { + ts.orderedRemoveItemAt(types, i); + } + } + } + function removeRedundantLiteralTypes(types, includes) { + var i = types.length; + while (i > 0) { + i--; + var t = types[i]; + var remove = t.flags & 128 /* StringLiteral */ && includes & 4 /* String */ || + t.flags & 256 /* NumberLiteral */ && includes & 8 /* Number */ || + t.flags & 2048 /* BigIntLiteral */ && includes & 64 /* BigInt */ || + t.flags & 8192 /* UniqueESSymbol */ && includes & 4096 /* ESSymbol */ || + isFreshLiteralType(t) && containsType(types, t.regularType); + if (remove) { + ts.orderedRemoveItemAt(types, i); + } + } + } + // We sort and deduplicate the constituent types based on object identity. If the subtypeReduction + // flag is specified we also reduce the constituent type set to only include types that aren't subtypes + // of other types. Subtype reduction is expensive for large union types and is possible only when union + // types are known not to circularly reference themselves (as is the case with union types created by + // expression constructs such as array literals and the || and ?: operators). Named types can + // circularly reference themselves and therefore cannot be subtype reduced during their declaration. + // For example, "type Item = string | (() => Item" is a named type that circularly references itself. + function getUnionType(types, unionReduction, aliasSymbol, aliasTypeArguments) { + if (unionReduction === void 0) { unionReduction = 1 /* Literal */; } + if (types.length === 0) { + return neverType; + } + if (types.length === 1) { + return types[0]; + } + var typeSet = []; + var includes = addTypesToUnion(typeSet, 0, types); + if (unionReduction !== 0 /* None */) { + if (includes & 3 /* AnyOrUnknown */) { + return includes & 1 /* Any */ ? includes & 268435456 /* Wildcard */ ? wildcardType : anyType : unknownType; + } + switch (unionReduction) { + case 1 /* Literal */: + if (includes & 8576 /* StringOrNumberLiteralOrUnique */ | 512 /* BooleanLiteral */) { + removeRedundantLiteralTypes(typeSet, includes); + } + break; + case 2 /* Subtype */: + removeSubtypes(typeSet); + break; + } + if (typeSet.length === 0) { + return includes & 65536 /* Null */ ? includes & 134217728 /* NonWideningType */ ? nullType : nullWideningType : + includes & 32768 /* Undefined */ ? includes & 134217728 /* NonWideningType */ ? undefinedType : undefinedWideningType : + neverType; + } + } + return getUnionTypeFromSortedList(typeSet, !(includes & 66994211 /* NotPrimitiveUnion */), aliasSymbol, aliasTypeArguments); + } + function getUnionTypePredicate(signatures) { + var first; + var types = []; + for (var _i = 0, signatures_2 = signatures; _i < signatures_2.length; _i++) { + var sig = signatures_2[_i]; + var pred = getTypePredicateOfSignature(sig); + if (!pred) { + continue; + } + if (first) { + if (!typePredicateKindsMatch(first, pred)) { + // No common type predicate. + return undefined; + } + } + else { + first = pred; + } + types.push(pred.type); + } + if (!first) { + // No union signatures had a type predicate. + return undefined; + } + var unionType = getUnionType(types); + return ts.isIdentifierTypePredicate(first) + ? createIdentifierTypePredicate(first.parameterName, first.parameterIndex, unionType) + : createThisTypePredicate(unionType); + } + function typePredicateKindsMatch(a, b) { + return ts.isIdentifierTypePredicate(a) + ? ts.isIdentifierTypePredicate(b) && a.parameterIndex === b.parameterIndex + : !ts.isIdentifierTypePredicate(b); + } + // This function assumes the constituent type list is sorted and deduplicated. + function getUnionTypeFromSortedList(types, primitiveTypesOnly, aliasSymbol, aliasTypeArguments) { + if (types.length === 0) { + return neverType; + } + if (types.length === 1) { + return types[0]; + } + var id = getTypeListId(types); + var type = unionTypes.get(id); + if (!type) { + var propagatedFlags = getPropagatingFlagsOfTypes(types, /*excludeKinds*/ 98304 /* Nullable */); + type = createType(1048576 /* Union */ | propagatedFlags); + unionTypes.set(id, type); + type.types = types; + type.primitiveTypesOnly = primitiveTypesOnly; + /* + Note: This is the alias symbol (or lack thereof) that we see when we first encounter this union type. + For aliases of identical unions, eg `type T = A | B; type U = A | B`, the symbol of the first alias encountered is the aliasSymbol. + (In the language service, the order may depend on the order in which a user takes actions, such as hovering over symbols.) + It's important that we create equivalent union types only once, so that's an unfortunate side effect. + */ + type.aliasSymbol = aliasSymbol; + type.aliasTypeArguments = aliasTypeArguments; + } + return type; + } + function getTypeFromUnionTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + var aliasSymbol = getAliasSymbolForTypeNode(node); + links.resolvedType = getUnionType(ts.map(node.types, getTypeFromTypeNode), 1 /* Literal */, aliasSymbol, getTypeArgumentsForAliasSymbol(aliasSymbol)); + } + return links.resolvedType; + } + function addTypeToIntersection(typeSet, includes, type) { + var flags = type.flags; + if (flags & 2097152 /* Intersection */) { + return addTypesToIntersection(typeSet, includes, type.types); + } + if (isEmptyAnonymousObjectType(type)) { + if (!(includes & 536870912 /* EmptyObject */)) { + includes |= 536870912 /* EmptyObject */; + typeSet.push(type); + } + } + else { + includes |= flags & ~939524096 /* ConstructionFlags */; + if (flags & 3 /* AnyOrUnknown */) { + if (type === wildcardType) + includes |= 268435456 /* Wildcard */; + } + else if ((strictNullChecks || !(flags & 98304 /* Nullable */)) && !ts.contains(typeSet, type)) { + typeSet.push(type); + } + } + return includes; + } + // Add the given types to the given type set. Order is preserved, freshness is removed from literal + // types, duplicates are removed, and nested types of the given kind are flattened into the set. + function addTypesToIntersection(typeSet, includes, types) { + for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { + var type = types_7[_i]; + includes = addTypeToIntersection(typeSet, includes, getRegularTypeOfLiteralType(type)); + } + return includes; + } + function removeRedundantPrimitiveTypes(types, includes) { + var i = types.length; + while (i > 0) { + i--; + var t = types[i]; + var remove = t.flags & 4 /* String */ && includes & 128 /* StringLiteral */ || + t.flags & 8 /* Number */ && includes & 256 /* NumberLiteral */ || + t.flags & 64 /* BigInt */ && includes & 2048 /* BigIntLiteral */ || + t.flags & 4096 /* ESSymbol */ && includes & 8192 /* UniqueESSymbol */; + if (remove) { + ts.orderedRemoveItemAt(types, i); + } + } + } + // Check that the given type has a match in every union. A given type is matched by + // an identical type, and a literal type is additionally matched by its corresponding + // primitive type. + function eachUnionContains(unionTypes, type) { + for (var _i = 0, unionTypes_1 = unionTypes; _i < unionTypes_1.length; _i++) { + var u = unionTypes_1[_i]; + if (!containsType(u.types, type)) { + var primitive = type.flags & 128 /* StringLiteral */ ? stringType : + type.flags & 256 /* NumberLiteral */ ? numberType : + type.flags & 2048 /* BigIntLiteral */ ? bigintType : + type.flags & 8192 /* UniqueESSymbol */ ? esSymbolType : + undefined; + if (!primitive || !containsType(u.types, primitive)) { + return false; + } + } + } + return true; + } + // If the given list of types contains more than one union of primitive types, replace the + // first with a union containing an intersection of those primitive types, then remove the + // other unions and return true. Otherwise, do nothing and return false. + function intersectUnionsOfPrimitiveTypes(types) { + var unionTypes; + var index = ts.findIndex(types, function (t) { return !!(t.flags & 1048576 /* Union */) && t.primitiveTypesOnly; }); + if (index < 0) { + return false; + } + var i = index + 1; + // Remove all but the first union of primitive types and collect them in + // the unionTypes array. + while (i < types.length) { + var t = types[i]; + if (t.flags & 1048576 /* Union */ && t.primitiveTypesOnly) { + (unionTypes || (unionTypes = [types[index]])).push(t); + ts.orderedRemoveItemAt(types, i); + } + else { + i++; + } + } + // Return false if there was only one union of primitive types + if (!unionTypes) { + return false; + } + // We have more than one union of primitive types, now intersect them. For each + // type in each union we check if the type is matched in every union and if so + // we include it in the result. + var checked = []; + var result = []; + for (var _i = 0, unionTypes_2 = unionTypes; _i < unionTypes_2.length; _i++) { + var u = unionTypes_2[_i]; + for (var _a = 0, _b = u.types; _a < _b.length; _a++) { + var t = _b[_a]; + if (insertType(checked, t)) { + if (eachUnionContains(unionTypes, t)) { + insertType(result, t); + } + } + } + } + // Finally replace the first union with the result + types[index] = getUnionTypeFromSortedList(result, /*primitiveTypesOnly*/ true); + return true; + } + // We normalize combinations of intersection and union types based on the distributive property of the '&' + // operator. Specifically, because X & (A | B) is equivalent to X & A | X & B, we can transform intersection + // types with union type constituents into equivalent union types with intersection type constituents and + // effectively ensure that union types are always at the top level in type representations. + // + // We do not perform structural deduplication on intersection types. Intersection types are created only by the & + // type operator and we can't reduce those because we want to support recursive intersection types. For example, + // a type alias of the form "type List = T & { next: List }" cannot be reduced during its declaration. + // Also, unlike union types, the order of the constituent types is preserved in order that overload resolution + // for intersections of types with signatures can be deterministic. + function getIntersectionType(types, aliasSymbol, aliasTypeArguments) { + var typeSet = []; + var includes = addTypesToIntersection(typeSet, 0, types); + if (includes & 131072 /* Never */) { + return neverType; + } + if (includes & 1 /* Any */) { + return includes & 268435456 /* Wildcard */ ? wildcardType : anyType; + } + if (!strictNullChecks && includes & 98304 /* Nullable */) { + return includes & 32768 /* Undefined */ ? undefinedType : nullType; + } + if (includes & 4 /* String */ && includes & 128 /* StringLiteral */ || + includes & 8 /* Number */ && includes & 256 /* NumberLiteral */ || + includes & 64 /* BigInt */ && includes & 2048 /* BigIntLiteral */ || + includes & 4096 /* ESSymbol */ && includes & 8192 /* UniqueESSymbol */) { + removeRedundantPrimitiveTypes(typeSet, includes); + } + if (includes & 536870912 /* EmptyObject */ && includes & 524288 /* Object */) { + ts.orderedRemoveItemAt(typeSet, ts.findIndex(typeSet, isEmptyAnonymousObjectType)); + } + if (typeSet.length === 0) { + return unknownType; + } + if (typeSet.length === 1) { + return typeSet[0]; + } + if (includes & 1048576 /* Union */) { + if (intersectUnionsOfPrimitiveTypes(typeSet)) { + // When the intersection creates a reduced set (which might mean that *all* union types have + // disappeared), we restart the operation to get a new set of combined flags. Once we have + // reduced we'll never reduce again, so this occurs at most once. + return getIntersectionType(typeSet, aliasSymbol, aliasTypeArguments); + } + // We are attempting to construct a type of the form X & (A | B) & Y. Transform this into a type of + // the form X & A & Y | X & B & Y and recursively reduce until no union type constituents remain. + var unionIndex_1 = ts.findIndex(typeSet, function (t) { return (t.flags & 1048576 /* Union */) !== 0; }); + var unionType = typeSet[unionIndex_1]; + return getUnionType(ts.map(unionType.types, function (t) { return getIntersectionType(ts.replaceElement(typeSet, unionIndex_1, t)); }), 1 /* Literal */, aliasSymbol, aliasTypeArguments); + } + var id = getTypeListId(typeSet); + var type = intersectionTypes.get(id); + if (!type) { + var propagatedFlags = getPropagatingFlagsOfTypes(typeSet, /*excludeKinds*/ 98304 /* Nullable */); + type = createType(2097152 /* Intersection */ | propagatedFlags); + intersectionTypes.set(id, type); + type.types = typeSet; + type.aliasSymbol = aliasSymbol; // See comment in `getUnionTypeFromSortedList`. + type.aliasTypeArguments = aliasTypeArguments; + } + return type; + } + function getTypeFromIntersectionTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + var aliasSymbol = getAliasSymbolForTypeNode(node); + links.resolvedType = getIntersectionType(ts.map(node.types, getTypeFromTypeNode), aliasSymbol, getTypeArgumentsForAliasSymbol(aliasSymbol)); + } + return links.resolvedType; + } + function createIndexType(type, stringsOnly) { + var result = createType(4194304 /* Index */); + result.type = type; + result.stringsOnly = stringsOnly; + return result; + } + function getIndexTypeForGenericType(type, stringsOnly) { + return stringsOnly ? + type.resolvedStringIndexType || (type.resolvedStringIndexType = createIndexType(type, /*stringsOnly*/ true)) : + type.resolvedIndexType || (type.resolvedIndexType = createIndexType(type, /*stringsOnly*/ false)); + } + function getLiteralTypeFromPropertyName(name) { + return ts.isIdentifier(name) ? getLiteralType(ts.unescapeLeadingUnderscores(name.escapedText)) : + getRegularTypeOfLiteralType(ts.isComputedPropertyName(name) ? checkComputedPropertyName(name) : checkExpression(name)); + } + function getBigIntLiteralType(node) { + return getLiteralType({ + negative: false, + base10Value: ts.parsePseudoBigInt(node.text) + }); + } + function getLiteralTypeFromProperty(prop, include) { + if (!(ts.getDeclarationModifierFlagsFromSymbol(prop) & 24 /* NonPublicAccessibilityModifier */)) { + var type = getLateBoundSymbol(prop).nameType; + if (!type && !ts.isKnownSymbol(prop)) { + if (prop.escapedName === "default" /* Default */) { + type = getLiteralType("default"); + } + else { + var name = prop.valueDeclaration && ts.getNameOfDeclaration(prop.valueDeclaration); + type = name && getLiteralTypeFromPropertyName(name) || getLiteralType(ts.symbolName(prop)); + } + } + if (type && type.flags & include) { + return type; + } + } + return neverType; + } + function getLiteralTypeFromProperties(type, include) { + return getUnionType(ts.map(getPropertiesOfType(type), function (t) { return getLiteralTypeFromProperty(t, include); })); + } + function getNonEnumNumberIndexInfo(type) { + var numberIndexInfo = getIndexInfoOfType(type, 1 /* Number */); + return numberIndexInfo !== enumNumberIndexInfo ? numberIndexInfo : undefined; + } + function getIndexType(type, stringsOnly) { + if (stringsOnly === void 0) { stringsOnly = keyofStringsOnly; } + return type.flags & 1048576 /* Union */ ? getIntersectionType(ts.map(type.types, function (t) { return getIndexType(t, stringsOnly); })) : + type.flags & 2097152 /* Intersection */ ? getUnionType(ts.map(type.types, function (t) { return getIndexType(t, stringsOnly); })) : + maybeTypeOfKind(type, 58982400 /* InstantiableNonPrimitive */) ? getIndexTypeForGenericType(type, stringsOnly) : + ts.getObjectFlags(type) & 32 /* Mapped */ ? getConstraintTypeFromMappedType(type) : + type === wildcardType ? wildcardType : + type.flags & 1 /* Any */ ? keyofConstraintType : + stringsOnly ? getIndexInfoOfType(type, 0 /* String */) ? stringType : getLiteralTypeFromProperties(type, 128 /* StringLiteral */) : + getIndexInfoOfType(type, 0 /* String */) ? getUnionType([stringType, numberType, getLiteralTypeFromProperties(type, 8192 /* UniqueESSymbol */)]) : + getNonEnumNumberIndexInfo(type) ? getUnionType([numberType, getLiteralTypeFromProperties(type, 128 /* StringLiteral */ | 8192 /* UniqueESSymbol */)]) : + getLiteralTypeFromProperties(type, 8576 /* StringOrNumberLiteralOrUnique */); + } + function getExtractStringType(type) { + if (keyofStringsOnly) { + return type; + } + var extractTypeAlias = getGlobalExtractSymbol(); + return extractTypeAlias ? getTypeAliasInstantiation(extractTypeAlias, [type, stringType]) : stringType; + } + function getIndexTypeOrString(type) { + var indexType = getExtractStringType(getIndexType(type)); + return indexType.flags & 131072 /* Never */ ? stringType : indexType; + } + function getTypeFromTypeOperatorNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + switch (node.operator) { + case 129 /* KeyOfKeyword */: + links.resolvedType = getIndexType(getTypeFromTypeNode(node.type)); + break; + case 142 /* UniqueKeyword */: + links.resolvedType = node.type.kind === 139 /* SymbolKeyword */ + ? getESSymbolLikeTypeForNode(ts.walkUpParenthesizedTypes(node.parent)) + : errorType; + break; + } + } + return links.resolvedType; // TODO: GH#18217 + } + function createIndexedAccessType(objectType, indexType) { + var type = createType(8388608 /* IndexedAccess */); + type.objectType = objectType; + type.indexType = indexType; + return type; + } + /** + * Returns if a type is or consists of a JSLiteral object type + * In addition to objects which are directly literals, + * * unions where every element is a jsliteral + * * intersections where at least one element is a jsliteral + * * and instantiable types constrained to a jsliteral + * Should all count as literals and not print errors on access or assignment of possibly existing properties. + * This mirrors the behavior of the index signature propagation, to which this behaves similarly (but doesn't affect assignability or inference). + */ + function isJSLiteralType(type) { + if (noImplicitAny) { + return false; // Flag is meaningless under `noImplicitAny` mode + } + if (ts.getObjectFlags(type) & 16384 /* JSLiteral */) { + return true; + } + if (type.flags & 1048576 /* Union */) { + return ts.every(type.types, isJSLiteralType); + } + if (type.flags & 2097152 /* Intersection */) { + return ts.some(type.types, isJSLiteralType); + } + if (type.flags & 63176704 /* Instantiable */) { + return isJSLiteralType(getResolvedBaseConstraint(type)); + } + return false; + } + function getPropertyTypeForIndexType(objectType, indexType, accessNode, cacheSymbol, missingType) { + var accessExpression = accessNode && accessNode.kind === 190 /* ElementAccessExpression */ ? accessNode : undefined; + var propName = isTypeUsableAsLateBoundName(indexType) + ? getLateBoundNameFromType(indexType) + : accessExpression && checkThatExpressionIsProperSymbolReference(accessExpression.argumentExpression, indexType, /*reportError*/ false) + ? ts.getPropertyNameForKnownSymbolName(ts.idText(accessExpression.argumentExpression.name)) + : accessNode && ts.isPropertyName(accessNode) + // late bound names are handled in the first branch, so here we only need to handle normal names + ? ts.getPropertyNameForPropertyNameNode(accessNode) + : undefined; + if (propName !== undefined) { + var prop = getPropertyOfType(objectType, propName); + if (prop) { + if (accessExpression) { + markPropertyAsReferenced(prop, accessExpression, /*isThisAccess*/ accessExpression.expression.kind === 100 /* ThisKeyword */); + if (ts.isAssignmentTarget(accessExpression) && (isReferenceToReadonlyEntity(accessExpression, prop) || isReferenceThroughNamespaceImport(accessExpression))) { + error(accessExpression.argumentExpression, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, symbolToString(prop)); + return missingType; + } + if (cacheSymbol) { + getNodeLinks(accessNode).resolvedSymbol = prop; + } + } + var propType = getTypeOfSymbol(prop); + return accessExpression && ts.getAssignmentTargetKind(accessExpression) !== 1 /* Definite */ ? + getFlowTypeOfReference(accessExpression, propType) : + propType; + } + if (everyType(objectType, isTupleType) && isNumericLiteralName(propName) && +propName >= 0) { + if (accessNode && everyType(objectType, function (t) { return !t.target.hasRestElement; })) { + var indexNode = getIndexNodeForAccessExpression(accessNode); + error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(propName), typeToString(objectType)); + } + return mapType(objectType, function (t) { return getRestTypeOfTupleType(t) || undefinedType; }); + } + } + if (!(indexType.flags & 98304 /* Nullable */) && isTypeAssignableToKind(indexType, 132 /* StringLike */ | 296 /* NumberLike */ | 12288 /* ESSymbolLike */)) { + if (objectType.flags & (1 /* Any */ | 131072 /* Never */)) { + return objectType; + } + var indexInfo = isTypeAssignableToKind(indexType, 296 /* NumberLike */) && getIndexInfoOfType(objectType, 1 /* Number */) || + getIndexInfoOfType(objectType, 0 /* String */) || + undefined; + if (indexInfo) { + if (accessNode && !isTypeAssignableToKind(indexType, 4 /* String */ | 8 /* Number */)) { + var indexNode = getIndexNodeForAccessExpression(accessNode); + error(indexNode, ts.Diagnostics.Type_0_cannot_be_used_as_an_index_type, typeToString(indexType)); + } + else if (accessExpression && indexInfo.isReadonly && (ts.isAssignmentTarget(accessExpression) || ts.isDeleteTarget(accessExpression))) { + error(accessExpression, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(objectType)); + } + return indexInfo.type; + } + if (indexType.flags & 131072 /* Never */) { + return neverType; + } + if (isJSLiteralType(objectType)) { + return anyType; + } + if (accessExpression && !isConstEnumObjectType(objectType)) { + if (noImplicitAny && !compilerOptions.suppressImplicitAnyIndexErrors) { + if (propName !== undefined && typeHasStaticProperty(propName, objectType)) { + error(accessExpression, ts.Diagnostics.Property_0_is_a_static_member_of_type_1, propName, typeToString(objectType)); + } + else if (getIndexTypeOfType(objectType, 1 /* Number */)) { + error(accessExpression.argumentExpression, ts.Diagnostics.Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number); + } + else { + var suggestion = void 0; + if (propName !== undefined && (suggestion = getSuggestionForNonexistentProperty(propName, objectType))) { + if (suggestion !== undefined) { + error(accessExpression.argumentExpression, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2, propName, typeToString(objectType), suggestion); + } + } + else { + error(accessExpression, ts.Diagnostics.Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature, typeToString(objectType)); + } + } + } + return missingType; + } + } + if (isJSLiteralType(objectType)) { + return anyType; + } + if (accessNode) { + var indexNode = getIndexNodeForAccessExpression(accessNode); + if (indexType.flags & (128 /* StringLiteral */ | 256 /* NumberLiteral */)) { + error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, "" + indexType.value, typeToString(objectType)); + } + else if (indexType.flags & (4 /* String */ | 8 /* Number */)) { + error(indexNode, ts.Diagnostics.Type_0_has_no_matching_index_signature_for_type_1, typeToString(objectType), typeToString(indexType)); + } + else { + error(indexNode, ts.Diagnostics.Type_0_cannot_be_used_as_an_index_type, typeToString(indexType)); + } + } + if (isTypeAny(indexType)) { + return indexType; + } + return missingType; + } + function getIndexNodeForAccessExpression(accessNode) { + return accessNode.kind === 190 /* ElementAccessExpression */ + ? accessNode.argumentExpression + : accessNode.kind === 180 /* IndexedAccessType */ + ? accessNode.indexType + : accessNode.kind === 149 /* ComputedPropertyName */ + ? accessNode.expression + : accessNode; + } + function isGenericObjectType(type) { + return maybeTypeOfKind(type, 58982400 /* InstantiableNonPrimitive */ | 134217728 /* GenericMappedType */); + } + function isGenericIndexType(type) { + return maybeTypeOfKind(type, 58982400 /* InstantiableNonPrimitive */ | 4194304 /* Index */); + } + function getSimplifiedType(type) { + return type.flags & 8388608 /* IndexedAccess */ ? getSimplifiedIndexedAccessType(type) : type; + } + function distributeIndexOverObjectType(objectType, indexType) { + // (T | U)[K] -> T[K] | U[K] + if (objectType.flags & 1048576 /* Union */) { + return mapType(objectType, function (t) { return getSimplifiedType(getIndexedAccessType(t, indexType)); }); + } + // (T & U)[K] -> T[K] & U[K] + if (objectType.flags & 2097152 /* Intersection */) { + return getIntersectionType(ts.map(objectType.types, function (t) { return getSimplifiedType(getIndexedAccessType(t, indexType)); })); + } + } + // Transform an indexed access to a simpler form, if possible. Return the simpler form, or return + // the type itself if no transformation is possible. + function getSimplifiedIndexedAccessType(type) { + if (type.simplified) { + return type.simplified === circularConstraintType ? type : type.simplified; + } + type.simplified = circularConstraintType; + // We recursively simplify the object type as it may in turn be an indexed access type. For example, with + // '{ [P in T]: { [Q in U]: number } }[T][U]' we want to first simplify the inner indexed access type. + var objectType = getSimplifiedType(type.objectType); + var indexType = getSimplifiedType(type.indexType); + // T[A | B] -> T[A] | T[B] + if (indexType.flags & 1048576 /* Union */) { + return type.simplified = mapType(indexType, function (t) { return getSimplifiedType(getIndexedAccessType(objectType, t)); }); + } + // Only do the inner distributions if the index can no longer be instantiated to cause index distribution again + if (!(indexType.flags & 63176704 /* Instantiable */)) { + var simplified = distributeIndexOverObjectType(objectType, indexType); + if (simplified) { + return type.simplified = simplified; + } + } + // So ultimately: + // ((A & B) | C)[K1 | K2] -> ((A & B) | C)[K1] | ((A & B) | C)[K2] -> (A & B)[K1] | C[K1] | (A & B)[K2] | C[K2] -> (A[K1] & B[K1]) | C[K1] | (A[K2] & B[K2]) | C[K2] + // If the object type is a mapped type { [P in K]: E }, where K is generic, instantiate E using a mapper + // that substitutes the index type for P. For example, for an index access { [P in K]: Box }[X], we + // construct the type Box. We do not further simplify the result because mapped types can be recursive + // and we might never terminate. + if (isGenericMappedType(objectType)) { + return type.simplified = substituteIndexedMappedType(objectType, type); + } + if (objectType.flags & 262144 /* TypeParameter */) { + var constraint = getConstraintOfTypeParameter(objectType); + if (constraint && isGenericMappedType(constraint)) { + return type.simplified = substituteIndexedMappedType(constraint, type); + } + } + return type.simplified = type; + } + function substituteIndexedMappedType(objectType, type) { + var mapper = createTypeMapper([getTypeParameterFromMappedType(objectType)], [type.indexType]); + var templateMapper = combineTypeMappers(objectType.mapper, mapper); + return instantiateType(getTemplateTypeFromMappedType(objectType), templateMapper); + } + function getIndexedAccessType(objectType, indexType, accessNode, missingType) { + if (missingType === void 0) { missingType = accessNode ? errorType : unknownType; } + if (objectType === wildcardType || indexType === wildcardType) { + return wildcardType; + } + // If the index type is generic, or if the object type is generic and doesn't originate in an expression, + // we are performing a higher-order index access where we cannot meaningfully access the properties of the + // object type. Note that for a generic T and a non-generic K, we eagerly resolve T[K] if it originates in + // an expression. This is to preserve backwards compatibility. For example, an element access 'this["foo"]' + // has always been resolved eagerly using the constraint type of 'this' at the given location. + if (isGenericIndexType(indexType) || !(accessNode && accessNode.kind !== 180 /* IndexedAccessType */) && isGenericObjectType(objectType)) { + if (objectType.flags & 3 /* AnyOrUnknown */) { + return objectType; + } + // Defer the operation by creating an indexed access type. + var id = objectType.id + "," + indexType.id; + var type = indexedAccessTypes.get(id); + if (!type) { + indexedAccessTypes.set(id, type = createIndexedAccessType(objectType, indexType)); + } + return type; + } + // In the following we resolve T[K] to the type of the property in T selected by K. + // We treat boolean as different from other unions to improve errors; + // skipping straight to getPropertyTypeForIndexType gives errors with 'boolean' instead of 'true'. + var apparentObjectType = getApparentType(objectType); + if (indexType.flags & 1048576 /* Union */ && !(indexType.flags & 16 /* Boolean */)) { + var propTypes = []; + var wasMissingProp = false; + for (var _i = 0, _a = indexType.types; _i < _a.length; _i++) { + var t = _a[_i]; + var propType = getPropertyTypeForIndexType(apparentObjectType, t, accessNode, /*cacheSymbol*/ false, missingType); + if (propType === missingType) { + if (!accessNode) { + // If there's no error node, we can immeditely stop, since error reporting is off + return missingType; + } + else { + // Otherwise we set a flag and return at the end of the loop so we still mark all errors + wasMissingProp = true; + } + } + propTypes.push(propType); + } + if (wasMissingProp) { + return missingType; + } + return getUnionType(propTypes); + } + return getPropertyTypeForIndexType(apparentObjectType, indexType, accessNode, /*cacheSymbol*/ true, missingType); + } + function getTypeFromIndexedAccessTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + var objectType = getTypeFromTypeNode(node.objectType); + var indexType = getTypeFromTypeNode(node.indexType); + var resolved = getIndexedAccessType(objectType, indexType, node); + links.resolvedType = resolved.flags & 8388608 /* IndexedAccess */ && + resolved.objectType === objectType && + resolved.indexType === indexType ? + getConstrainedTypeVariable(resolved, node) : resolved; + } + return links.resolvedType; + } + function getTypeFromMappedTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + var type = createObjectType(32 /* Mapped */, node.symbol); + type.declaration = node; + type.aliasSymbol = getAliasSymbolForTypeNode(node); + type.aliasTypeArguments = getTypeArgumentsForAliasSymbol(type.aliasSymbol); + links.resolvedType = type; + // Eagerly resolve the constraint type which forces an error if the constraint type circularly + // references itself through one or more type aliases. + getConstraintTypeFromMappedType(type); + } + return links.resolvedType; + } + function getActualTypeVariable(type) { + return type.flags & 33554432 /* Substitution */ ? type.typeVariable : type; + } + function getConditionalType(root, mapper) { + var checkType = instantiateType(root.checkType, mapper); + var extendsType = instantiateType(root.extendsType, mapper); + if (checkType === wildcardType || extendsType === wildcardType) { + return wildcardType; + } + // If this is a distributive conditional type and the check type is generic we need to defer + // resolution of the conditional type such that a later instantiation will properly distribute + // over union types. + var isDeferred = root.isDistributive && maybeTypeOfKind(checkType, 63176704 /* Instantiable */); + var combinedMapper; + if (root.inferTypeParameters) { + var context = createInferenceContext(root.inferTypeParameters, /*signature*/ undefined, 0 /* None */); + if (!isDeferred) { + // We don't want inferences from constraints as they may cause us to eagerly resolve the + // conditional type instead of deferring resolution. Also, we always want strict function + // types rules (i.e. proper contravariance) for inferences. + inferTypes(context.inferences, checkType, extendsType, 32 /* NoConstraints */ | 64 /* AlwaysStrict */); + } + combinedMapper = combineTypeMappers(mapper, context); + } + if (!isDeferred) { + if (extendsType.flags & 3 /* AnyOrUnknown */) { + return instantiateType(root.trueType, mapper); + } + // Return union of trueType and falseType for 'any' since it matches anything + if (checkType.flags & 1 /* Any */) { + return getUnionType([instantiateType(root.trueType, combinedMapper || mapper), instantiateType(root.falseType, mapper)]); + } + // Instantiate the extends type including inferences for 'infer T' type parameters + var inferredExtendsType = combinedMapper ? instantiateType(root.extendsType, combinedMapper) : extendsType; + // Return falseType for a definitely false extends check. We check an instantations of the two + // types with type parameters mapped to the wildcard type, the most permissive instantiations + // possible (the wildcard type is assignable to and from all types). If those are not related, + // then no instatiations will be and we can just return the false branch type. + if (!isTypeAssignableTo(getWildcardInstantiation(checkType), getWildcardInstantiation(inferredExtendsType))) { + return instantiateType(root.falseType, mapper); + } + // Return trueType for a definitely true extends check. The definitely assignable relation excludes + // type variable constraints from consideration. Without the definitely assignable relation, the type + // type Foo = T extends { x: string } ? string : number + // would immediately resolve to 'string' instead of being deferred. + if (checkTypeRelatedTo(checkType, inferredExtendsType, definitelyAssignableRelation, /*errorNode*/ undefined)) { + return instantiateType(root.trueType, combinedMapper || mapper); + } + } + // Return a deferred type for a check that is neither definitely true nor definitely false + var erasedCheckType = getActualTypeVariable(checkType); + var result = createType(16777216 /* Conditional */); + result.root = root; + result.checkType = erasedCheckType; + result.extendsType = extendsType; + result.mapper = mapper; + result.combinedMapper = combinedMapper; + result.aliasSymbol = root.aliasSymbol; + result.aliasTypeArguments = instantiateTypes(root.aliasTypeArguments, mapper); // TODO: GH#18217 + return result; + } + function getTrueTypeFromConditionalType(type) { + return type.resolvedTrueType || (type.resolvedTrueType = instantiateType(type.root.trueType, type.mapper)); + } + function getFalseTypeFromConditionalType(type) { + return type.resolvedFalseType || (type.resolvedFalseType = instantiateType(type.root.falseType, type.mapper)); + } + function getInferTypeParameters(node) { + var result; + if (node.locals) { + node.locals.forEach(function (symbol) { + if (symbol.flags & 262144 /* TypeParameter */) { + result = ts.append(result, getDeclaredTypeOfSymbol(symbol)); + } + }); + } + return result; + } + function isPossiblyReferencedInConditionalType(tp, node) { + if (isTypeParameterPossiblyReferenced(tp, node)) { + return true; + } + while (node) { + if (node.kind === 175 /* ConditionalType */) { + if (isTypeParameterPossiblyReferenced(tp, node.extendsType)) { + return true; + } + } + node = node.parent; + } + return false; + } + function getTypeFromConditionalTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + var checkType = getTypeFromTypeNode(node.checkType); + var aliasSymbol = getAliasSymbolForTypeNode(node); + var aliasTypeArguments = getTypeArgumentsForAliasSymbol(aliasSymbol); + var allOuterTypeParameters = getOuterTypeParameters(node, /*includeThisTypes*/ true); + var outerTypeParameters = aliasTypeArguments ? allOuterTypeParameters : ts.filter(allOuterTypeParameters, function (tp) { return isPossiblyReferencedInConditionalType(tp, node); }); + var root = { + node: node, + checkType: checkType, + extendsType: getTypeFromTypeNode(node.extendsType), + trueType: getTypeFromTypeNode(node.trueType), + falseType: getTypeFromTypeNode(node.falseType), + isDistributive: !!(checkType.flags & 262144 /* TypeParameter */), + inferTypeParameters: getInferTypeParameters(node), + outerTypeParameters: outerTypeParameters, + instantiations: undefined, + aliasSymbol: aliasSymbol, + aliasTypeArguments: aliasTypeArguments + }; + links.resolvedType = getConditionalType(root, /*mapper*/ undefined); + if (outerTypeParameters) { + root.instantiations = ts.createMap(); + root.instantiations.set(getTypeListId(outerTypeParameters), links.resolvedType); + } + } + return links.resolvedType; + } + function getTypeFromInferTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + links.resolvedType = getDeclaredTypeOfTypeParameter(getSymbolOfNode(node.typeParameter)); + } + return links.resolvedType; + } + function getIdentifierChain(node) { + if (ts.isIdentifier(node)) { + return [node]; + } + else { + return ts.append(getIdentifierChain(node.left), node.right); + } + } + function getTypeFromImportTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + if (node.isTypeOf && node.typeArguments) { // Only the non-typeof form can make use of type arguments + error(node, ts.Diagnostics.Type_arguments_cannot_be_used_here); + links.resolvedSymbol = unknownSymbol; + return links.resolvedType = errorType; + } + if (!ts.isLiteralImportTypeNode(node)) { + error(node.argument, ts.Diagnostics.String_literal_expected); + links.resolvedSymbol = unknownSymbol; + return links.resolvedType = errorType; + } + var targetMeaning = node.isTypeOf ? 67220415 /* Value */ : node.flags & 2097152 /* JSDoc */ ? 67220415 /* Value */ | 67897832 /* Type */ : 67897832 /* Type */; + // TODO: Future work: support unions/generics/whatever via a deferred import-type + var innerModuleSymbol = resolveExternalModuleName(node, node.argument.literal); + if (!innerModuleSymbol) { + links.resolvedSymbol = unknownSymbol; + return links.resolvedType = errorType; + } + var moduleSymbol = resolveExternalModuleSymbol(innerModuleSymbol, /*dontResolveAlias*/ false); + if (!ts.nodeIsMissing(node.qualifier)) { + var nameStack = getIdentifierChain(node.qualifier); + var currentNamespace = moduleSymbol; + var current = void 0; + while (current = nameStack.shift()) { + var meaning = nameStack.length ? 1920 /* Namespace */ : targetMeaning; + var next = getSymbol(getExportsOfSymbol(getMergedSymbol(resolveSymbol(currentNamespace))), current.escapedText, meaning); + if (!next) { + error(current, ts.Diagnostics.Namespace_0_has_no_exported_member_1, getFullyQualifiedName(currentNamespace), ts.declarationNameToString(current)); + return links.resolvedType = errorType; + } + getNodeLinks(current).resolvedSymbol = next; + getNodeLinks(current.parent).resolvedSymbol = next; + currentNamespace = next; + } + resolveImportSymbolType(node, links, currentNamespace, targetMeaning); + } + else { + if (moduleSymbol.flags & targetMeaning) { + resolveImportSymbolType(node, links, moduleSymbol, targetMeaning); + } + else { + var errorMessage = targetMeaning === 67220415 /* Value */ + ? ts.Diagnostics.Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here + : ts.Diagnostics.Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0; + error(node, errorMessage, node.argument.literal.text); + links.resolvedSymbol = unknownSymbol; + links.resolvedType = errorType; + } + } + } + return links.resolvedType; // TODO: GH#18217 + } + function resolveImportSymbolType(node, links, symbol, meaning) { + var resolvedSymbol = resolveSymbol(symbol); + links.resolvedSymbol = resolvedSymbol; + if (meaning === 67220415 /* Value */) { + return links.resolvedType = getTypeOfSymbol(symbol); // intentionally doesn't use resolved symbol so type is cached as expected on the alias + } + else { + return links.resolvedType = getTypeReferenceType(node, resolvedSymbol); // getTypeReferenceType doesn't handle aliases - it must get the resolved symbol + } + } + function getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + // Deferred resolution of members is handled by resolveObjectTypeMembers + var aliasSymbol = getAliasSymbolForTypeNode(node); + if (getMembersOfSymbol(node.symbol).size === 0 && !aliasSymbol) { + links.resolvedType = emptyTypeLiteralType; + } + else { + var type = createObjectType(16 /* Anonymous */, node.symbol); + type.aliasSymbol = aliasSymbol; + type.aliasTypeArguments = getTypeArgumentsForAliasSymbol(aliasSymbol); + if (ts.isJSDocTypeLiteral(node) && node.isArrayType) { + type = createArrayType(type); + } + links.resolvedType = type; + } + } + return links.resolvedType; + } + function getAliasSymbolForTypeNode(node) { + return ts.isTypeAlias(node.parent) ? getSymbolOfNode(node.parent) : undefined; + } + function getTypeArgumentsForAliasSymbol(symbol) { + return symbol ? getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) : undefined; + } + function isNonGenericObjectType(type) { + return !!(type.flags & 524288 /* Object */) && !isGenericMappedType(type); + } + /** + * Since the source of spread types are object literals, which are not binary, + * this function should be called in a left folding style, with left = previous result of getSpreadType + * and right = the new element to be spread. + */ + function getSpreadType(left, right, symbol, typeFlags, objectFlags) { + if (left.flags & 1 /* Any */ || right.flags & 1 /* Any */) { + return anyType; + } + if (left.flags & 2 /* Unknown */ || right.flags & 2 /* Unknown */) { + return unknownType; + } + if (left.flags & 131072 /* Never */) { + return right; + } + if (right.flags & 131072 /* Never */) { + return left; + } + if (left.flags & 1048576 /* Union */) { + return mapType(left, function (t) { return getSpreadType(t, right, symbol, typeFlags, objectFlags); }); + } + if (right.flags & 1048576 /* Union */) { + return mapType(right, function (t) { return getSpreadType(left, t, symbol, typeFlags, objectFlags); }); + } + if (right.flags & (528 /* BooleanLike */ | 296 /* NumberLike */ | 2112 /* BigIntLike */ | 132 /* StringLike */ | 1056 /* EnumLike */ | 67108864 /* NonPrimitive */ | 4194304 /* Index */)) { + return left; + } + if (isGenericObjectType(left) || isGenericObjectType(right)) { + if (isEmptyObjectType(left)) { + return right; + } + // When the left type is an intersection, we may need to merge the last constituent of the + // intersection with the right type. For example when the left type is 'T & { a: string }' + // and the right type is '{ b: string }' we produce 'T & { a: string, b: string }'. + if (left.flags & 2097152 /* Intersection */) { + var types = left.types; + var lastLeft = types[types.length - 1]; + if (isNonGenericObjectType(lastLeft) && isNonGenericObjectType(right)) { + return getIntersectionType(ts.concatenate(types.slice(0, types.length - 1), [getSpreadType(lastLeft, right, symbol, typeFlags, objectFlags)])); + } + } + return getIntersectionType([left, right]); + } + var members = ts.createSymbolTable(); + var skippedPrivateMembers = ts.createUnderscoreEscapedMap(); + var stringIndexInfo; + var numberIndexInfo; + if (left === emptyObjectType) { + // for the first spread element, left === emptyObjectType, so take the right's string indexer + stringIndexInfo = getIndexInfoOfType(right, 0 /* String */); + numberIndexInfo = getIndexInfoOfType(right, 1 /* Number */); + } + else { + stringIndexInfo = unionSpreadIndexInfos(getIndexInfoOfType(left, 0 /* String */), getIndexInfoOfType(right, 0 /* String */)); + numberIndexInfo = unionSpreadIndexInfos(getIndexInfoOfType(left, 1 /* Number */), getIndexInfoOfType(right, 1 /* Number */)); + } + for (var _i = 0, _a = getPropertiesOfType(right); _i < _a.length; _i++) { + var rightProp = _a[_i]; + if (ts.getDeclarationModifierFlagsFromSymbol(rightProp) & (8 /* Private */ | 16 /* Protected */)) { + skippedPrivateMembers.set(rightProp.escapedName, true); + } + else if (isSpreadableProperty(rightProp)) { + members.set(rightProp.escapedName, getSpreadSymbol(rightProp)); + } + } + for (var _b = 0, _c = getPropertiesOfType(left); _b < _c.length; _b++) { + var leftProp = _c[_b]; + if (skippedPrivateMembers.has(leftProp.escapedName) || !isSpreadableProperty(leftProp)) { + continue; + } + if (members.has(leftProp.escapedName)) { + var rightProp = members.get(leftProp.escapedName); + var rightType = getTypeOfSymbol(rightProp); + if (rightProp.flags & 16777216 /* Optional */) { + var declarations = ts.concatenate(leftProp.declarations, rightProp.declarations); + var flags = 4 /* Property */ | (leftProp.flags & 16777216 /* Optional */); + var result = createSymbol(flags, leftProp.escapedName); + result.type = getUnionType([getTypeOfSymbol(leftProp), getTypeWithFacts(rightType, 524288 /* NEUndefined */)]); + result.leftSpread = leftProp; + result.rightSpread = rightProp; + result.declarations = declarations; + result.nameType = leftProp.nameType; + members.set(leftProp.escapedName, result); + } + } + else { + members.set(leftProp.escapedName, getSpreadSymbol(leftProp)); + } + } + var spread = createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, getNonReadonlyIndexSignature(stringIndexInfo), getNonReadonlyIndexSignature(numberIndexInfo)); + spread.flags |= 268435456 /* ContainsObjectLiteral */ | typeFlags; + spread.objectFlags |= 128 /* ObjectLiteral */ | 1024 /* ContainsSpread */ | objectFlags; + return spread; + } + /** We approximate own properties as non-methods plus methods that are inside the object literal */ + function isSpreadableProperty(prop) { + return !(prop.flags & (8192 /* Method */ | 32768 /* GetAccessor */ | 65536 /* SetAccessor */)) || + !prop.declarations.some(function (decl) { return ts.isClassLike(decl.parent); }); + } + function getSpreadSymbol(prop) { + var isReadonly = isReadonlySymbol(prop); + var isSetonlyAccessor = prop.flags & 65536 /* SetAccessor */ && !(prop.flags & 32768 /* GetAccessor */); + if (!isReadonly && !isSetonlyAccessor) { + return prop; + } + var flags = 4 /* Property */ | (prop.flags & 16777216 /* Optional */); + var result = createSymbol(flags, prop.escapedName); + result.type = isSetonlyAccessor ? undefinedType : getTypeOfSymbol(prop); + result.declarations = prop.declarations; + result.nameType = prop.nameType; + result.syntheticOrigin = prop; + return result; + } + function getNonReadonlyIndexSignature(index) { + if (index && index.isReadonly) { + return createIndexInfo(index.type, /*isReadonly*/ false, index.declaration); + } + return index; + } + function createLiteralType(flags, value, symbol) { + var type = createType(flags); + type.symbol = symbol; + type.value = value; + return type; + } + function getFreshTypeOfLiteralType(type) { + if (type.flags & 2944 /* Literal */) { + if (!type.freshType) { + var freshType = createLiteralType(type.flags, type.value, type.symbol); + freshType.regularType = type; + freshType.freshType = freshType; + type.freshType = freshType; + } + return type.freshType; + } + return type; + } + function getRegularTypeOfLiteralType(type) { + return type.flags & 2944 /* Literal */ ? type.regularType : + type.flags & 1048576 /* Union */ ? getUnionType(ts.sameMap(type.types, getRegularTypeOfLiteralType)) : + type; + } + function isFreshLiteralType(type) { + return !!(type.flags & 2944 /* Literal */) && type.freshType === type; + } + function getLiteralType(value, enumId, symbol) { + // We store all literal types in a single map with keys of the form '#NNN' and '@SSS', + // where NNN is the text representation of a numeric literal and SSS are the characters + // of a string literal. For literal enum members we use 'EEE#NNN' and 'EEE@SSS', where + // EEE is a unique id for the containing enum type. + var qualifier = typeof value === "number" ? "#" : typeof value === "string" ? "@" : "n"; + var key = (enumId ? enumId : "") + qualifier + (typeof value === "object" ? ts.pseudoBigIntToString(value) : value); + var type = literalTypes.get(key); + if (!type) { + var flags = (typeof value === "number" ? 256 /* NumberLiteral */ : + typeof value === "string" ? 128 /* StringLiteral */ : 2048 /* BigIntLiteral */) | + (enumId ? 1024 /* EnumLiteral */ : 0); + literalTypes.set(key, type = createLiteralType(flags, value, symbol)); + type.regularType = type; + } + return type; + } + function getTypeFromLiteralTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + links.resolvedType = getRegularTypeOfLiteralType(checkExpression(node.literal)); + } + return links.resolvedType; + } + function createUniqueESSymbolType(symbol) { + var type = createType(8192 /* UniqueESSymbol */); + type.symbol = symbol; + return type; + } + function getESSymbolLikeTypeForNode(node) { + if (ts.isValidESSymbolDeclaration(node)) { + var symbol = getSymbolOfNode(node); + var links = getSymbolLinks(symbol); + return links.uniqueESSymbolType || (links.uniqueESSymbolType = createUniqueESSymbolType(symbol)); + } + return esSymbolType; + } + function getThisType(node) { + var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); + var parent = container && container.parent; + if (parent && (ts.isClassLike(parent) || parent.kind === 241 /* InterfaceDeclaration */)) { + if (!ts.hasModifier(container, 32 /* Static */) && + (container.kind !== 157 /* Constructor */ || ts.isNodeDescendantOf(node, container.body))) { + return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(parent)).thisType; + } + } + error(node, ts.Diagnostics.A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface); + return errorType; + } + function getTypeFromThisTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + links.resolvedType = getThisType(node); + } + return links.resolvedType; + } + function getTypeFromTypeNode(node) { + switch (node.kind) { + case 120 /* AnyKeyword */: + case 284 /* JSDocAllType */: + case 285 /* JSDocUnknownType */: + return anyType; + case 143 /* UnknownKeyword */: + return unknownType; + case 138 /* StringKeyword */: + return stringType; + case 135 /* NumberKeyword */: + return numberType; + case 146 /* BigIntKeyword */: + return bigintType; + case 123 /* BooleanKeyword */: + return booleanType; + case 139 /* SymbolKeyword */: + return esSymbolType; + case 106 /* VoidKeyword */: + return voidType; + case 141 /* UndefinedKeyword */: + return undefinedType; + case 96 /* NullKeyword */: + return nullType; + case 132 /* NeverKeyword */: + return neverType; + case 136 /* ObjectKeyword */: + return node.flags & 65536 /* JavaScriptFile */ ? anyType : nonPrimitiveType; + case 178 /* ThisType */: + case 100 /* ThisKeyword */: + return getTypeFromThisTypeNode(node); + case 182 /* LiteralType */: + return getTypeFromLiteralTypeNode(node); + case 164 /* TypeReference */: + return getTypeFromTypeReference(node); + case 163 /* TypePredicate */: + return booleanType; + case 211 /* ExpressionWithTypeArguments */: + return getTypeFromTypeReference(node); + case 167 /* TypeQuery */: + return getTypeFromTypeQueryNode(node); + case 169 /* ArrayType */: + return getTypeFromArrayTypeNode(node); + case 170 /* TupleType */: + return getTypeFromTupleTypeNode(node); + case 171 /* OptionalType */: + return getTypeFromOptionalTypeNode(node); + case 173 /* UnionType */: + return getTypeFromUnionTypeNode(node); + case 174 /* IntersectionType */: + return getTypeFromIntersectionTypeNode(node); + case 286 /* JSDocNullableType */: + return getTypeFromJSDocNullableTypeNode(node); + case 288 /* JSDocOptionalType */: + return addOptionality(getTypeFromTypeNode(node.type)); + case 177 /* ParenthesizedType */: + case 172 /* RestType */: + case 287 /* JSDocNonNullableType */: + case 283 /* JSDocTypeExpression */: + return getTypeFromTypeNode(node.type); + case 290 /* JSDocVariadicType */: + return getTypeFromJSDocVariadicType(node); + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + case 168 /* TypeLiteral */: + case 292 /* JSDocTypeLiteral */: + case 289 /* JSDocFunctionType */: + case 293 /* JSDocSignature */: + return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node); + case 179 /* TypeOperator */: + return getTypeFromTypeOperatorNode(node); + case 180 /* IndexedAccessType */: + return getTypeFromIndexedAccessTypeNode(node); + case 181 /* MappedType */: + return getTypeFromMappedTypeNode(node); + case 175 /* ConditionalType */: + return getTypeFromConditionalTypeNode(node); + case 176 /* InferType */: + return getTypeFromInferTypeNode(node); + case 183 /* ImportType */: + return getTypeFromImportTypeNode(node); + // This function assumes that an identifier or qualified name is a type expression + // Callers should first ensure this by calling isTypeNode + case 72 /* Identifier */: + case 148 /* QualifiedName */: + var symbol = getSymbolAtLocation(node); + return symbol ? getDeclaredTypeOfSymbol(symbol) : errorType; + default: + return errorType; + } + } + function instantiateList(items, mapper, instantiator) { + if (items && items.length) { + for (var i = 0; i < items.length; i++) { + var item = items[i]; + var mapped = instantiator(item, mapper); + if (item !== mapped) { + var result = i === 0 ? [] : items.slice(0, i); + result.push(mapped); + for (i++; i < items.length; i++) { + result.push(instantiator(items[i], mapper)); + } + return result; + } + } + } + return items; + } + function instantiateTypes(types, mapper) { + return instantiateList(types, mapper, instantiateType); + } + function instantiateSignatures(signatures, mapper) { + return instantiateList(signatures, mapper, instantiateSignature); + } + function makeUnaryTypeMapper(source, target) { + return function (t) { return t === source ? target : t; }; + } + function makeBinaryTypeMapper(source1, target1, source2, target2) { + return function (t) { return t === source1 ? target1 : t === source2 ? target2 : t; }; + } + function makeArrayTypeMapper(sources, targets) { + return function (t) { + for (var i = 0; i < sources.length; i++) { + if (t === sources[i]) { + return targets ? targets[i] : anyType; + } + } + return t; + }; + } + function createTypeMapper(sources, targets) { + ts.Debug.assert(targets === undefined || sources.length === targets.length); + return sources.length === 1 ? makeUnaryTypeMapper(sources[0], targets ? targets[0] : anyType) : + sources.length === 2 ? makeBinaryTypeMapper(sources[0], targets ? targets[0] : anyType, sources[1], targets ? targets[1] : anyType) : + makeArrayTypeMapper(sources, targets); + } + function createTypeEraser(sources) { + return createTypeMapper(sources, /*targets*/ undefined); + } + /** + * Maps forward-references to later types parameters to the empty object type. + * This is used during inference when instantiating type parameter defaults. + */ + function createBackreferenceMapper(typeParameters, index) { + return function (t) { return typeParameters.indexOf(t) >= index ? emptyObjectType : t; }; + } + function isInferenceContext(mapper) { + return !!mapper.typeParameters; + } + function cloneTypeMapper(mapper) { + return mapper && isInferenceContext(mapper) ? + createInferenceContext(mapper.typeParameters, mapper.signature, mapper.flags | 1 /* NoDefault */, mapper.compareTypes, mapper.inferences) : + mapper; + } + function combineTypeMappers(mapper1, mapper2) { + if (!mapper1) + return mapper2; + if (!mapper2) + return mapper1; + return function (t) { return instantiateType(mapper1(t), mapper2); }; + } + function createReplacementMapper(source, target, baseMapper) { + return function (t) { return t === source ? target : baseMapper(t); }; + } + function wildcardMapper(type) { + return type.flags & 262144 /* TypeParameter */ ? wildcardType : type; + } + function cloneTypeParameter(typeParameter) { + var result = createType(262144 /* TypeParameter */); + result.symbol = typeParameter.symbol; + result.target = typeParameter; + return result; + } + function instantiateTypePredicate(predicate, mapper) { + if (ts.isIdentifierTypePredicate(predicate)) { + return { + kind: 1 /* Identifier */, + parameterName: predicate.parameterName, + parameterIndex: predicate.parameterIndex, + type: instantiateType(predicate.type, mapper) + }; + } + else { + return { + kind: 0 /* This */, + type: instantiateType(predicate.type, mapper) + }; + } + } + function instantiateSignature(signature, mapper, eraseTypeParameters) { + var freshTypeParameters; + if (signature.typeParameters && !eraseTypeParameters) { + // First create a fresh set of type parameters, then include a mapping from the old to the + // new type parameters in the mapper function. Finally store this mapper in the new type + // parameters such that we can use it when instantiating constraints. + freshTypeParameters = ts.map(signature.typeParameters, cloneTypeParameter); + mapper = combineTypeMappers(createTypeMapper(signature.typeParameters, freshTypeParameters), mapper); + for (var _i = 0, freshTypeParameters_1 = freshTypeParameters; _i < freshTypeParameters_1.length; _i++) { + var tp = freshTypeParameters_1[_i]; + tp.mapper = mapper; + } + } + // Don't compute resolvedReturnType and resolvedTypePredicate now, + // because using `mapper` now could trigger inferences to become fixed. (See `createInferenceContext`.) + // See GH#17600. + var result = createSignature(signature.declaration, freshTypeParameters, signature.thisParameter && instantiateSymbol(signature.thisParameter, mapper), instantiateList(signature.parameters, mapper, instantiateSymbol), + /*resolvedReturnType*/ undefined, + /*resolvedTypePredicate*/ undefined, signature.minArgumentCount, signature.hasRestParameter, signature.hasLiteralTypes); + result.target = signature; + result.mapper = mapper; + return result; + } + function instantiateSymbol(symbol, mapper) { + var links = getSymbolLinks(symbol); + if (links.type && !maybeTypeOfKind(links.type, 524288 /* Object */ | 63176704 /* Instantiable */)) { + // If the type of the symbol is already resolved, and if that type could not possibly + // be affected by instantiation, simply return the symbol itself. + return symbol; + } + if (ts.getCheckFlags(symbol) & 1 /* Instantiated */) { + // If symbol being instantiated is itself a instantiation, fetch the original target and combine the + // type mappers. This ensures that original type identities are properly preserved and that aliases + // always reference a non-aliases. + symbol = links.target; + mapper = combineTypeMappers(links.mapper, mapper); + } + // Keep the flags from the symbol we're instantiating. Mark that is instantiated, and + // also transient so that we can just store data on it directly. + var result = createSymbol(symbol.flags, symbol.escapedName, 1 /* Instantiated */ | ts.getCheckFlags(symbol) & (1024 /* Late */ | 4096 /* OptionalParameter */ | 8192 /* RestParameter */)); + result.declarations = symbol.declarations; + result.parent = symbol.parent; + result.target = symbol; + result.mapper = mapper; + if (symbol.valueDeclaration) { + result.valueDeclaration = symbol.valueDeclaration; + } + if (symbol.nameType) { + result.nameType = symbol.nameType; + } + return result; + } + function getAnonymousTypeInstantiation(type, mapper) { + var target = type.objectFlags & 64 /* Instantiated */ ? type.target : type; + var symbol = target.symbol; + var links = getSymbolLinks(symbol); + var typeParameters = links.outerTypeParameters; + if (!typeParameters) { + // The first time an anonymous type is instantiated we compute and store a list of the type + // parameters that are in scope (and therefore potentially referenced). For type literals that + // aren't the right hand side of a generic type alias declaration we optimize by reducing the + // set of type parameters to those that are possibly referenced in the literal. + var declaration_1 = symbol.declarations[0]; + if (ts.isInJSFile(declaration_1)) { + var paramTag = ts.findAncestor(declaration_1, ts.isJSDocParameterTag); + if (paramTag) { + var paramSymbol = ts.getParameterSymbolFromJSDoc(paramTag); + if (paramSymbol) { + declaration_1 = paramSymbol.valueDeclaration; + } + } + } + var outerTypeParameters = getOuterTypeParameters(declaration_1, /*includeThisTypes*/ true); + if (isJSConstructor(declaration_1)) { + var templateTagParameters = getTypeParametersFromDeclaration(declaration_1); + outerTypeParameters = ts.addRange(outerTypeParameters, templateTagParameters); + } + typeParameters = outerTypeParameters || ts.emptyArray; + typeParameters = symbol.flags & 2048 /* TypeLiteral */ && !target.aliasTypeArguments ? + ts.filter(typeParameters, function (tp) { return isTypeParameterPossiblyReferenced(tp, declaration_1); }) : + typeParameters; + links.outerTypeParameters = typeParameters; + if (typeParameters.length) { + links.instantiations = ts.createMap(); + links.instantiations.set(getTypeListId(typeParameters), target); + } + } + if (typeParameters.length) { + // We are instantiating an anonymous type that has one or more type parameters in scope. Apply the + // mapper to the type parameters to produce the effective list of type arguments, and compute the + // instantiation cache key from the type IDs of the type arguments. + var combinedMapper = type.objectFlags & 64 /* Instantiated */ ? combineTypeMappers(type.mapper, mapper) : mapper; + var typeArguments = ts.map(typeParameters, combinedMapper); + var id = getTypeListId(typeArguments); + var result = links.instantiations.get(id); + if (!result) { + var newMapper = createTypeMapper(typeParameters, typeArguments); + result = target.objectFlags & 32 /* Mapped */ ? instantiateMappedType(target, newMapper) : instantiateAnonymousType(target, newMapper); + links.instantiations.set(id, result); + } + return result; + } + return type; + } + function maybeTypeParameterReference(node) { + return !(node.kind === 148 /* QualifiedName */ || + node.parent.kind === 164 /* TypeReference */ && node.parent.typeArguments && node === node.parent.typeName); + } + function isTypeParameterPossiblyReferenced(tp, node) { + // If the type parameter doesn't have exactly one declaration, if there are invening statement blocks + // between the node and the type parameter declaration, if the node contains actual references to the + // type parameter, or if the node contains type queries, we consider the type parameter possibly referenced. + if (tp.symbol && tp.symbol.declarations && tp.symbol.declarations.length === 1) { + var container_3 = tp.symbol.declarations[0].parent; + if (ts.findAncestor(node, function (n) { return n.kind === 218 /* Block */ ? "quit" : n === container_3; })) { + return !!ts.forEachChild(node, containsReference); + } + } + return true; + function containsReference(node) { + switch (node.kind) { + case 178 /* ThisType */: + return !!tp.isThisType; + case 72 /* Identifier */: + return !tp.isThisType && ts.isPartOfTypeNode(node) && maybeTypeParameterReference(node) && + getTypeFromTypeNode(node) === tp; + case 167 /* TypeQuery */: + return true; + } + return !!ts.forEachChild(node, containsReference); + } + } + function getHomomorphicTypeVariable(type) { + var constraintType = getConstraintTypeFromMappedType(type); + if (constraintType.flags & 4194304 /* Index */) { + var typeVariable = constraintType.type; + if (typeVariable.flags & 262144 /* TypeParameter */) { + return typeVariable; + } + } + return undefined; + } + function instantiateMappedType(type, mapper) { + // For a homomorphic mapped type { [P in keyof T]: X }, where T is some type variable, the mapping + // operation depends on T as follows: + // * If T is a primitive type no mapping is performed and the result is simply T. + // * If T is a union type we distribute the mapped type over the union. + // * If T is an array we map to an array where the element type has been transformed. + // * If T is a tuple we map to a tuple where the element types have been transformed. + // * Otherwise we map to an object type where the type of each property has been transformed. + // For example, when T is instantiated to a union type A | B, we produce { [P in keyof A]: X } | + // { [P in keyof B]: X }, and when when T is instantiated to a union type A | undefined, we produce + // { [P in keyof A]: X } | undefined. + var typeVariable = getHomomorphicTypeVariable(type); + if (typeVariable) { + var mappedTypeVariable = instantiateType(typeVariable, mapper); + if (typeVariable !== mappedTypeVariable) { + // If we are already in the process of creating an instantiation of this mapped type, + // return the error type. This situation only arises if we are instantiating the mapped + // type for an array or tuple type, as we then need to eagerly resolve the (possibly + // circular) element type(s). + if (type.instantiating) { + return errorType; + } + type.instantiating = true; + var result = mapType(mappedTypeVariable, function (t) { + if (t.flags & (3 /* AnyOrUnknown */ | 58982400 /* InstantiableNonPrimitive */ | 524288 /* Object */ | 2097152 /* Intersection */) && t !== wildcardType) { + var replacementMapper = createReplacementMapper(typeVariable, t, mapper); + return isArrayType(t) ? createArrayType(instantiateMappedTypeTemplate(type, numberType, /*isOptional*/ true, replacementMapper)) : + isReadonlyArrayType(t) ? createReadonlyArrayType(instantiateMappedTypeTemplate(type, numberType, /*isOptional*/ true, replacementMapper)) : + isTupleType(t) ? instantiateMappedTupleType(t, type, replacementMapper) : + instantiateAnonymousType(type, replacementMapper); + } + return t; + }); + type.instantiating = false; + return result; + } + } + return instantiateAnonymousType(type, mapper); + } + function instantiateMappedTupleType(tupleType, mappedType, mapper) { + var minLength = tupleType.target.minLength; + var elementTypes = ts.map(tupleType.typeArguments || ts.emptyArray, function (_, i) { + return instantiateMappedTypeTemplate(mappedType, getLiteralType("" + i), i >= minLength, mapper); + }); + var modifiers = getMappedTypeModifiers(mappedType); + var newMinLength = modifiers & 4 /* IncludeOptional */ ? 0 : + modifiers & 8 /* ExcludeOptional */ ? getTypeReferenceArity(tupleType) - (tupleType.target.hasRestElement ? 1 : 0) : + minLength; + return createTupleType(elementTypes, newMinLength, tupleType.target.hasRestElement, tupleType.target.associatedNames); + } + function instantiateMappedTypeTemplate(type, key, isOptional, mapper) { + var templateMapper = combineTypeMappers(mapper, createTypeMapper([getTypeParameterFromMappedType(type)], [key])); + var propType = instantiateType(getTemplateTypeFromMappedType(type.target || type), templateMapper); + var modifiers = getMappedTypeModifiers(type); + return strictNullChecks && modifiers & 4 /* IncludeOptional */ && !isTypeAssignableTo(undefinedType, propType) ? getOptionalType(propType) : + strictNullChecks && modifiers & 8 /* ExcludeOptional */ && isOptional ? getTypeWithFacts(propType, 524288 /* NEUndefined */) : + propType; + } + function instantiateAnonymousType(type, mapper) { + var result = createObjectType(type.objectFlags | 64 /* Instantiated */, type.symbol); + if (type.objectFlags & 32 /* Mapped */) { + result.declaration = type.declaration; + // C.f. instantiateSignature + var origTypeParameter = getTypeParameterFromMappedType(type); + var freshTypeParameter = cloneTypeParameter(origTypeParameter); + result.typeParameter = freshTypeParameter; + mapper = combineTypeMappers(makeUnaryTypeMapper(origTypeParameter, freshTypeParameter), mapper); + freshTypeParameter.mapper = mapper; + } + result.target = type; + result.mapper = mapper; + result.aliasSymbol = type.aliasSymbol; + result.aliasTypeArguments = instantiateTypes(type.aliasTypeArguments, mapper); + return result; + } + function getConditionalTypeInstantiation(type, mapper) { + var root = type.root; + if (root.outerTypeParameters) { + // We are instantiating a conditional type that has one or more type parameters in scope. Apply the + // mapper to the type parameters to produce the effective list of type arguments, and compute the + // instantiation cache key from the type IDs of the type arguments. + var typeArguments = ts.map(root.outerTypeParameters, mapper); + var id = getTypeListId(typeArguments); + var result = root.instantiations.get(id); + if (!result) { + var newMapper = createTypeMapper(root.outerTypeParameters, typeArguments); + result = instantiateConditionalType(root, newMapper); + root.instantiations.set(id, result); + } + return result; + } + return type; + } + function instantiateConditionalType(root, mapper) { + // Check if we have a conditional type where the check type is a naked type parameter. If so, + // the conditional type is distributive over union types and when T is instantiated to a union + // type A | B, we produce (A extends U ? X : Y) | (B extends U ? X : Y). + if (root.isDistributive) { + var checkType_1 = root.checkType; + var instantiatedType = mapper(checkType_1); + if (checkType_1 !== instantiatedType && instantiatedType.flags & (1048576 /* Union */ | 131072 /* Never */)) { + return mapType(instantiatedType, function (t) { return getConditionalType(root, createReplacementMapper(checkType_1, t, mapper)); }); + } + } + return getConditionalType(root, mapper); + } + function instantiateType(type, mapper) { + if (!type || !mapper || mapper === identityMapper) { + return type; + } + if (instantiationDepth === 50) { + // We have reached 50 recursive type instantiations and there is a very high likelyhood we're dealing + // with a combination of infinite generic types that perpetually generate new type identities. We stop + // the recursion here by yielding the error type. + return errorType; + } + instantiationDepth++; + var result = instantiateTypeWorker(type, mapper); + instantiationDepth--; + return result; + } + function instantiateTypeWorker(type, mapper) { + var flags = type.flags; + if (flags & 262144 /* TypeParameter */) { + return mapper(type); + } + if (flags & 524288 /* Object */) { + var objectFlags = type.objectFlags; + if (objectFlags & 16 /* Anonymous */) { + // If the anonymous type originates in a declaration of a function, method, class, or + // interface, in an object type literal, or in an object literal expression, we may need + // to instantiate the type because it might reference a type parameter. + return type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && type.symbol.declarations ? + getAnonymousTypeInstantiation(type, mapper) : type; + } + if (objectFlags & 32 /* Mapped */) { + return getAnonymousTypeInstantiation(type, mapper); + } + if (objectFlags & 4 /* Reference */) { + var typeArguments = type.typeArguments; + var newTypeArguments = instantiateTypes(typeArguments, mapper); + return newTypeArguments !== typeArguments ? createTypeReference(type.target, newTypeArguments) : type; + } + return type; + } + if (flags & 1048576 /* Union */ && !(flags & 131068 /* Primitive */)) { + var types = type.types; + var newTypes = instantiateTypes(types, mapper); + return newTypes !== types ? getUnionType(newTypes, 1 /* Literal */, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type; + } + if (flags & 2097152 /* Intersection */) { + var types = type.types; + var newTypes = instantiateTypes(types, mapper); + return newTypes !== types ? getIntersectionType(newTypes, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type; + } + if (flags & 4194304 /* Index */) { + return getIndexType(instantiateType(type.type, mapper)); + } + if (flags & 8388608 /* IndexedAccess */) { + return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper)); + } + if (flags & 16777216 /* Conditional */) { + return getConditionalTypeInstantiation(type, combineTypeMappers(type.mapper, mapper)); + } + if (flags & 33554432 /* Substitution */) { + return instantiateType(type.typeVariable, mapper); + } + return type; + } + function getWildcardInstantiation(type) { + return type.flags & (131068 /* Primitive */ | 3 /* AnyOrUnknown */ | 131072 /* Never */) ? type : + type.wildcardInstantiation || (type.wildcardInstantiation = instantiateType(type, wildcardMapper)); + } + function instantiateIndexInfo(info, mapper) { + return info && createIndexInfo(instantiateType(info.type, mapper), info.isReadonly, info.declaration); + } + // Returns true if the given expression contains (at any level of nesting) a function or arrow expression + // that is subject to contextual typing. + function isContextSensitive(node) { + ts.Debug.assert(node.kind !== 156 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + switch (node.kind) { + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 156 /* MethodDeclaration */: + return isContextSensitiveFunctionLikeDeclaration(node); + case 188 /* ObjectLiteralExpression */: + return ts.some(node.properties, isContextSensitive); + case 187 /* ArrayLiteralExpression */: + return ts.some(node.elements, isContextSensitive); + case 205 /* ConditionalExpression */: + return isContextSensitive(node.whenTrue) || + isContextSensitive(node.whenFalse); + case 204 /* BinaryExpression */: + return node.operatorToken.kind === 55 /* BarBarToken */ && + (isContextSensitive(node.left) || isContextSensitive(node.right)); + case 275 /* PropertyAssignment */: + return isContextSensitive(node.initializer); + case 195 /* ParenthesizedExpression */: + return isContextSensitive(node.expression); + case 268 /* JsxAttributes */: + return ts.some(node.properties, isContextSensitive) || ts.isJsxOpeningElement(node.parent) && ts.some(node.parent.parent.children, isContextSensitive); + case 267 /* JsxAttribute */: { + // If there is no initializer, JSX attribute has a boolean value of true which is not context sensitive. + var initializer = node.initializer; + return !!initializer && isContextSensitive(initializer); + } + case 270 /* JsxExpression */: { + // It is possible to that node.expression is undefined (e.g
      ) + var expression = node.expression; + return !!expression && isContextSensitive(expression); + } + } + return false; + } + function isContextSensitiveFunctionLikeDeclaration(node) { + // Functions with type parameters are not context sensitive. + if (node.typeParameters) { + return false; + } + // Functions with any parameters that lack type annotations are context sensitive. + if (ts.some(node.parameters, function (p) { return !ts.getEffectiveTypeAnnotationNode(p); })) { + return true; + } + if (node.kind !== 197 /* ArrowFunction */) { + // If the first parameter is not an explicit 'this' parameter, then the function has + // an implicit 'this' parameter which is subject to contextual typing. + var parameter = ts.firstOrUndefined(node.parameters); + if (!(parameter && ts.parameterIsThisKeyword(parameter))) { + return true; + } + } + return hasContextSensitiveReturnExpression(node); + } + function hasContextSensitiveReturnExpression(node) { + // TODO(anhans): A block should be context-sensitive if it has a context-sensitive return value. + var body = node.body; + return body.kind === 218 /* Block */ ? false : isContextSensitive(body); + } + function isContextSensitiveFunctionOrObjectLiteralMethod(func) { + return (ts.isInJSFile(func) && ts.isFunctionDeclaration(func) || isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && + isContextSensitiveFunctionLikeDeclaration(func); + } + function getTypeWithoutSignatures(type) { + if (type.flags & 524288 /* Object */) { + var resolved = resolveStructuredTypeMembers(type); + if (resolved.constructSignatures.length || resolved.callSignatures.length) { + var result = createObjectType(16 /* Anonymous */, type.symbol); + result.members = resolved.members; + result.properties = resolved.properties; + result.callSignatures = ts.emptyArray; + result.constructSignatures = ts.emptyArray; + return result; + } + } + else if (type.flags & 2097152 /* Intersection */) { + return getIntersectionType(ts.map(type.types, getTypeWithoutSignatures)); + } + return type; + } + // TYPE CHECKING + function isTypeIdenticalTo(source, target) { + return isTypeRelatedTo(source, target, identityRelation); + } + function compareTypesIdentical(source, target) { + return isTypeRelatedTo(source, target, identityRelation) ? -1 /* True */ : 0 /* False */; + } + function compareTypesAssignable(source, target) { + return isTypeRelatedTo(source, target, assignableRelation) ? -1 /* True */ : 0 /* False */; + } + function compareTypesSubtypeOf(source, target) { + return isTypeRelatedTo(source, target, subtypeRelation) ? -1 /* True */ : 0 /* False */; + } + function isTypeSubtypeOf(source, target) { + return isTypeRelatedTo(source, target, subtypeRelation); + } + function isTypeAssignableTo(source, target) { + return isTypeRelatedTo(source, target, assignableRelation); + } + // An object type S is considered to be derived from an object type T if + // S is a union type and every constituent of S is derived from T, + // T is a union type and S is derived from at least one constituent of T, or + // S is a type variable with a base constraint that is derived from T, + // T is one of the global types Object and Function and S is a subtype of T, or + // T occurs directly or indirectly in an 'extends' clause of S. + // Note that this check ignores type parameters and only considers the + // inheritance hierarchy. + function isTypeDerivedFrom(source, target) { + return source.flags & 1048576 /* Union */ ? ts.every(source.types, function (t) { return isTypeDerivedFrom(t, target); }) : + target.flags & 1048576 /* Union */ ? ts.some(target.types, function (t) { return isTypeDerivedFrom(source, t); }) : + source.flags & 58982400 /* InstantiableNonPrimitive */ ? isTypeDerivedFrom(getBaseConstraintOfType(source) || emptyObjectType, target) : + target === globalObjectType ? !!(source.flags & (524288 /* Object */ | 67108864 /* NonPrimitive */)) : + target === globalFunctionType ? !!(source.flags & 524288 /* Object */) && isFunctionObjectType(source) : + hasBaseType(source, getTargetType(target)); + } + /** + * This is *not* a bi-directional relationship. + * If one needs to check both directions for comparability, use a second call to this function or 'checkTypeComparableTo'. + * + * A type S is comparable to a type T if some (but not necessarily all) of the possible values of S are also possible values of T. + * It is used to check following cases: + * - the types of the left and right sides of equality/inequality operators (`===`, `!==`, `==`, `!=`). + * - the types of `case` clause expressions and their respective `switch` expressions. + * - the type of an expression in a type assertion with the type being asserted. + */ + function isTypeComparableTo(source, target) { + return isTypeRelatedTo(source, target, comparableRelation); + } + function areTypesComparable(type1, type2) { + return isTypeComparableTo(type1, type2) || isTypeComparableTo(type2, type1); + } + function checkTypeAssignableTo(source, target, errorNode, headMessage, containingMessageChain, errorOutputObject) { + return checkTypeRelatedTo(source, target, assignableRelation, errorNode, headMessage, containingMessageChain, errorOutputObject); + } + /** + * Like `checkTypeAssignableTo`, but if it would issue an error, instead performs structural comparisons of the types using the given expression node to + * attempt to issue more specific errors on, for example, specific object literal properties or tuple members. + */ + function checkTypeAssignableToAndOptionallyElaborate(source, target, errorNode, expr, headMessage, containingMessageChain) { + return checkTypeRelatedToAndOptionallyElaborate(source, target, assignableRelation, errorNode, expr, headMessage, containingMessageChain); + } + function checkTypeRelatedToAndOptionallyElaborate(source, target, relation, errorNode, expr, headMessage, containingMessageChain) { + if (isTypeRelatedTo(source, target, relation)) + return true; + if (!errorNode || !elaborateError(expr, source, target, relation, headMessage)) { + return checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain); + } + return false; + } + function isOrHasGenericConditional(type) { + return !!(type.flags & 16777216 /* Conditional */ || (type.flags & 2097152 /* Intersection */ && ts.some(type.types, isOrHasGenericConditional))); + } + function elaborateError(node, source, target, relation, headMessage) { + if (!node || isOrHasGenericConditional(target)) + return false; + if (!checkTypeRelatedTo(source, target, relation, /*errorNode*/ undefined) && elaborateDidYouMeanToCallOrConstruct(node, source, target, relation, headMessage)) { + return true; + } + switch (node.kind) { + case 270 /* JsxExpression */: + case 195 /* ParenthesizedExpression */: + return elaborateError(node.expression, source, target, relation, headMessage); + case 204 /* BinaryExpression */: + switch (node.operatorToken.kind) { + case 59 /* EqualsToken */: + case 27 /* CommaToken */: + return elaborateError(node.right, source, target, relation, headMessage); + } + break; + case 188 /* ObjectLiteralExpression */: + return elaborateObjectLiteral(node, source, target, relation); + case 187 /* ArrayLiteralExpression */: + return elaborateArrayLiteral(node, source, target, relation); + case 268 /* JsxAttributes */: + return elaborateJsxAttributes(node, source, target, relation); + case 197 /* ArrowFunction */: + return elaborateArrowFunction(node, source, target, relation); + } + return false; + } + function elaborateDidYouMeanToCallOrConstruct(node, source, target, relation, headMessage) { + var callSignatures = getSignaturesOfType(source, 0 /* Call */); + var constructSignatures = getSignaturesOfType(source, 1 /* Construct */); + for (var _i = 0, _a = [constructSignatures, callSignatures]; _i < _a.length; _i++) { + var signatures = _a[_i]; + if (ts.some(signatures, function (s) { + var returnType = getReturnTypeOfSignature(s); + return !(returnType.flags & (1 /* Any */ | 131072 /* Never */)) && checkTypeRelatedTo(returnType, target, relation, /*errorNode*/ undefined); + })) { + var resultObj = {}; + checkTypeAssignableTo(source, target, node, headMessage, /*containingChain*/ undefined, resultObj); + var diagnostic = resultObj.error; + addRelatedInfo(diagnostic, ts.createDiagnosticForNode(node, signatures === constructSignatures ? ts.Diagnostics.Did_you_mean_to_use_new_with_this_expression : ts.Diagnostics.Did_you_mean_to_call_this_expression)); + return true; + } + } + return false; + } + function elaborateArrowFunction(node, source, target, relation) { + // Don't elaborate blocks + if (ts.isBlock(node.body)) { + return false; + } + // Or functions with annotated parameter types + if (ts.some(node.parameters, ts.hasType)) { + return false; + } + var sourceSig = getSingleCallSignature(source); + if (!sourceSig) { + return false; + } + var targetSignatures = getSignaturesOfType(target, 0 /* Call */); + if (!ts.length(targetSignatures)) { + return false; + } + var returnExpression = node.body; + var sourceReturn = getReturnTypeOfSignature(sourceSig); + var targetReturn = getUnionType(ts.map(targetSignatures, getReturnTypeOfSignature)); + if (!checkTypeRelatedTo(sourceReturn, targetReturn, relation, /*errorNode*/ undefined)) { + var elaborated = returnExpression && elaborateError(returnExpression, sourceReturn, targetReturn, relation, /*headMessage*/ undefined); + if (elaborated) { + return elaborated; + } + var resultObj = {}; + checkTypeRelatedTo(sourceReturn, targetReturn, relation, returnExpression, /*message*/ undefined, /*chain*/ undefined, resultObj); + if (resultObj.error) { + if (target.symbol && ts.length(target.symbol.declarations)) { + addRelatedInfo(resultObj.error, ts.createDiagnosticForNode(target.symbol.declarations[0], ts.Diagnostics.The_expected_type_comes_from_the_return_type_of_this_signature)); + } + return true; + } + } + return false; + } + /** + * For every element returned from the iterator, checks that element to issue an error on a property of that element's type + * If that element would issue an error, we first attempt to dive into that element's inner expression and issue a more specific error by recuring into `elaborateError` + * Otherwise, we issue an error on _every_ element which fail the assignability check + */ + function elaborateElementwise(iterator, source, target, relation) { + // Assignability failure - check each prop individually, and if that fails, fall back on the bad error span + var reportedError = false; + for (var status = iterator.next(); !status.done; status = iterator.next()) { + var _a = status.value, prop = _a.errorNode, next = _a.innerExpression, nameType = _a.nameType, errorMessage = _a.errorMessage; + var targetPropType = getIndexedAccessType(target, nameType, /*accessNode*/ undefined, errorType); + if (targetPropType === errorType || targetPropType.flags & 8388608 /* IndexedAccess */) + continue; // Don't elaborate on indexes on generic variables + var sourcePropType = getIndexedAccessType(source, nameType, /*accessNode*/ undefined, errorType); + if (sourcePropType !== errorType && targetPropType !== errorType && !checkTypeRelatedTo(sourcePropType, targetPropType, relation, /*errorNode*/ undefined)) { + var elaborated = next && elaborateError(next, sourcePropType, targetPropType, relation, /*headMessage*/ undefined); + if (elaborated) { + reportedError = true; + } + else { + // Issue error on the prop itself, since the prop couldn't elaborate the error + var resultObj = {}; + // Use the expression type, if available + var specificSource = next ? checkExpressionForMutableLocation(next, 0 /* Normal */, sourcePropType) : sourcePropType; + var result = checkTypeRelatedTo(specificSource, targetPropType, relation, prop, errorMessage, /*containingChain*/ undefined, resultObj); + if (result && specificSource !== sourcePropType) { + // If for whatever reason the expression type doesn't yield an error, make sure we still issue an error on the sourcePropType + checkTypeRelatedTo(sourcePropType, targetPropType, relation, prop, errorMessage, /*containingChain*/ undefined, resultObj); + } + if (resultObj.error) { + var reportedDiag = resultObj.error; + var propertyName = isTypeUsableAsLateBoundName(nameType) ? getLateBoundNameFromType(nameType) : undefined; + var targetProp = propertyName !== undefined ? getPropertyOfType(target, propertyName) : undefined; + var issuedElaboration = false; + if (!targetProp) { + var indexInfo = isTypeAssignableToKind(nameType, 296 /* NumberLike */) && getIndexInfoOfType(target, 1 /* Number */) || + getIndexInfoOfType(target, 0 /* String */) || + undefined; + if (indexInfo && indexInfo.declaration && !ts.getSourceFileOfNode(indexInfo.declaration).hasNoDefaultLib) { + issuedElaboration = true; + addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(indexInfo.declaration, ts.Diagnostics.The_expected_type_comes_from_this_index_signature)); + } + } + if (!issuedElaboration && (targetProp && ts.length(targetProp.declarations) || target.symbol && ts.length(target.symbol.declarations))) { + var targetNode = targetProp && ts.length(targetProp.declarations) ? targetProp.declarations[0] : target.symbol.declarations[0]; + if (!ts.getSourceFileOfNode(targetNode).hasNoDefaultLib) { + addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(targetNode, ts.Diagnostics.The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1, propertyName && !(nameType.flags & 8192 /* UniqueESSymbol */) ? ts.unescapeLeadingUnderscores(propertyName) : typeToString(nameType), typeToString(target))); + } + } + } + reportedError = true; + } + } + } + return reportedError; + } + function generateJsxAttributes(node) { + var _i, _a, prop; + return __generator(this, function (_b) { + switch (_b.label) { + case 0: + if (!ts.length(node.properties)) + return [2 /*return*/]; + _i = 0, _a = node.properties; + _b.label = 1; + case 1: + if (!(_i < _a.length)) return [3 /*break*/, 4]; + prop = _a[_i]; + if (ts.isJsxSpreadAttribute(prop)) + return [3 /*break*/, 3]; + return [4 /*yield*/, { errorNode: prop.name, innerExpression: prop.initializer, nameType: getLiteralType(ts.idText(prop.name)) }]; + case 2: + _b.sent(); + _b.label = 3; + case 3: + _i++; + return [3 /*break*/, 1]; + case 4: return [2 /*return*/]; + } + }); + } + function elaborateJsxAttributes(node, source, target, relation) { + return elaborateElementwise(generateJsxAttributes(node), source, target, relation); + } + function generateLimitedTupleElements(node, target) { + var len, i, elem, nameType; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + len = ts.length(node.elements); + if (!len) + return [2 /*return*/]; + i = 0; + _a.label = 1; + case 1: + if (!(i < len)) return [3 /*break*/, 4]; + // Skip elements which do not exist in the target - a length error on the tuple overall is likely better than an error on a mismatched index signature + if (isTupleLikeType(target) && !getPropertyOfType(target, ("" + i))) + return [3 /*break*/, 3]; + elem = node.elements[i]; + if (ts.isOmittedExpression(elem)) + return [3 /*break*/, 3]; + nameType = getLiteralType(i); + return [4 /*yield*/, { errorNode: elem, innerExpression: elem, nameType: nameType }]; + case 2: + _a.sent(); + _a.label = 3; + case 3: + i++; + return [3 /*break*/, 1]; + case 4: return [2 /*return*/]; + } + }); + } + function elaborateArrayLiteral(node, source, target, relation) { + if (isTupleLikeType(source)) { + return elaborateElementwise(generateLimitedTupleElements(node, target), source, target, relation); + } + // recreate a tuple from the elements, if possible + var tupleizedType = checkArrayLiteral(node, 3 /* Contextual */, /*forceTuple*/ true); + if (isTupleLikeType(tupleizedType)) { + return elaborateElementwise(generateLimitedTupleElements(node, target), tupleizedType, target, relation); + } + return false; + } + function generateObjectLiteralElements(node) { + var _i, _a, prop, type, _b; + return __generator(this, function (_c) { + switch (_c.label) { + case 0: + if (!ts.length(node.properties)) + return [2 /*return*/]; + _i = 0, _a = node.properties; + _c.label = 1; + case 1: + if (!(_i < _a.length)) return [3 /*break*/, 8]; + prop = _a[_i]; + if (ts.isSpreadAssignment(prop)) + return [3 /*break*/, 7]; + type = getLiteralTypeFromProperty(getSymbolOfNode(prop), 8576 /* StringOrNumberLiteralOrUnique */); + if (!type || (type.flags & 131072 /* Never */)) { + return [3 /*break*/, 7]; + } + _b = prop.kind; + switch (_b) { + case 159 /* SetAccessor */: return [3 /*break*/, 2]; + case 158 /* GetAccessor */: return [3 /*break*/, 2]; + case 156 /* MethodDeclaration */: return [3 /*break*/, 2]; + case 276 /* ShorthandPropertyAssignment */: return [3 /*break*/, 2]; + case 275 /* PropertyAssignment */: return [3 /*break*/, 4]; + } + return [3 /*break*/, 6]; + case 2: return [4 /*yield*/, { errorNode: prop.name, innerExpression: undefined, nameType: type }]; + case 3: + _c.sent(); + return [3 /*break*/, 7]; + case 4: return [4 /*yield*/, { errorNode: prop.name, innerExpression: prop.initializer, nameType: type, errorMessage: isComputedNonLiteralName(prop.name) ? ts.Diagnostics.Type_of_computed_property_s_value_is_0_which_is_not_assignable_to_type_1 : undefined }]; + case 5: + _c.sent(); + return [3 /*break*/, 7]; + case 6: + ts.Debug.assertNever(prop); + _c.label = 7; + case 7: + _i++; + return [3 /*break*/, 1]; + case 8: return [2 /*return*/]; + } + }); + } + function elaborateObjectLiteral(node, source, target, relation) { + return elaborateElementwise(generateObjectLiteralElements(node), source, target, relation); + } + /** + * This is *not* a bi-directional relationship. + * If one needs to check both directions for comparability, use a second call to this function or 'isTypeComparableTo'. + */ + function checkTypeComparableTo(source, target, errorNode, headMessage, containingMessageChain) { + return checkTypeRelatedTo(source, target, comparableRelation, errorNode, headMessage, containingMessageChain); + } + function isSignatureAssignableTo(source, target, ignoreReturnTypes) { + return compareSignaturesRelated(source, target, 0 /* None */, ignoreReturnTypes, /*reportErrors*/ false, + /*errorReporter*/ undefined, compareTypesAssignable) !== 0 /* False */; + } + /** + * See signatureRelatedTo, compareSignaturesIdentical + */ + function compareSignaturesRelated(source, target, callbackCheck, ignoreReturnTypes, reportErrors, errorReporter, compareTypes) { + // TODO (drosen): De-duplicate code between related functions. + if (source === target) { + return -1 /* True */; + } + var targetCount = getParameterCount(target); + if (!hasEffectiveRestParameter(target) && getMinArgumentCount(source) > targetCount) { + return 0 /* False */; + } + if (source.typeParameters && source.typeParameters !== target.typeParameters) { + target = getCanonicalSignature(target); + source = instantiateSignatureInContextOf(source, target, /*contextualMapper*/ undefined, compareTypes); + } + var sourceCount = getParameterCount(source); + var sourceRestType = getNonArrayRestType(source); + var targetRestType = getNonArrayRestType(target); + if (sourceRestType && targetRestType && sourceCount !== targetCount) { + // We're not able to relate misaligned complex rest parameters + return 0 /* False */; + } + var kind = target.declaration ? target.declaration.kind : 0 /* Unknown */; + var strictVariance = !callbackCheck && strictFunctionTypes && kind !== 156 /* MethodDeclaration */ && + kind !== 155 /* MethodSignature */ && kind !== 157 /* Constructor */; + var result = -1 /* True */; + var sourceThisType = getThisTypeOfSignature(source); + if (sourceThisType && sourceThisType !== voidType) { + var targetThisType = getThisTypeOfSignature(target); + if (targetThisType) { + // void sources are assignable to anything. + var related = !strictVariance && compareTypes(sourceThisType, targetThisType, /*reportErrors*/ false) + || compareTypes(targetThisType, sourceThisType, reportErrors); + if (!related) { + if (reportErrors) { + errorReporter(ts.Diagnostics.The_this_types_of_each_signature_are_incompatible); + } + return 0 /* False */; + } + result &= related; + } + } + var paramCount = sourceRestType || targetRestType ? Math.min(sourceCount, targetCount) : Math.max(sourceCount, targetCount); + var restIndex = sourceRestType || targetRestType ? paramCount - 1 : -1; + for (var i = 0; i < paramCount; i++) { + var sourceType = i === restIndex ? getRestTypeAtPosition(source, i) : getTypeAtPosition(source, i); + var targetType = i === restIndex ? getRestTypeAtPosition(target, i) : getTypeAtPosition(target, i); + // In order to ensure that any generic type Foo is at least co-variant with respect to T no matter + // how Foo uses T, we need to relate parameters bi-variantly (given that parameters are input positions, + // they naturally relate only contra-variantly). However, if the source and target parameters both have + // function types with a single call signature, we know we are relating two callback parameters. In + // that case it is sufficient to only relate the parameters of the signatures co-variantly because, + // similar to return values, callback parameters are output positions. This means that a Promise, + // where T is used only in callback parameter positions, will be co-variant (as opposed to bi-variant) + // with respect to T. + var sourceSig = callbackCheck ? undefined : getSingleCallSignature(getNonNullableType(sourceType)); + var targetSig = callbackCheck ? undefined : getSingleCallSignature(getNonNullableType(targetType)); + var callbacks = sourceSig && targetSig && !signatureHasTypePredicate(sourceSig) && !signatureHasTypePredicate(targetSig) && + (getFalsyFlags(sourceType) & 98304 /* Nullable */) === (getFalsyFlags(targetType) & 98304 /* Nullable */); + var related = callbacks ? + // TODO: GH#18217 It will work if they're both `undefined`, but not if only one is + compareSignaturesRelated(targetSig, sourceSig, strictVariance ? 2 /* Strict */ : 1 /* Bivariant */, /*ignoreReturnTypes*/ false, reportErrors, errorReporter, compareTypes) : + !callbackCheck && !strictVariance && compareTypes(sourceType, targetType, /*reportErrors*/ false) || compareTypes(targetType, sourceType, reportErrors); + if (!related) { + if (reportErrors) { + errorReporter(ts.Diagnostics.Types_of_parameters_0_and_1_are_incompatible, ts.unescapeLeadingUnderscores(getParameterNameAtPosition(source, i)), ts.unescapeLeadingUnderscores(getParameterNameAtPosition(target, i))); + } + return 0 /* False */; + } + result &= related; + } + if (!ignoreReturnTypes) { + var targetReturnType = (target.declaration && isJSConstructor(target.declaration)) ? + getJSClassType(target.declaration.symbol) : getReturnTypeOfSignature(target); + if (targetReturnType === voidType) { + return result; + } + var sourceReturnType = (source.declaration && isJSConstructor(source.declaration)) ? + getJSClassType(source.declaration.symbol) : getReturnTypeOfSignature(source); + // The following block preserves behavior forbidding boolean returning functions from being assignable to type guard returning functions + var targetTypePredicate = getTypePredicateOfSignature(target); + if (targetTypePredicate) { + var sourceTypePredicate = getTypePredicateOfSignature(source); + if (sourceTypePredicate) { + result &= compareTypePredicateRelatedTo(sourceTypePredicate, targetTypePredicate, source.declaration, target.declaration, reportErrors, errorReporter, compareTypes); // TODO: GH#18217 + } + else if (ts.isIdentifierTypePredicate(targetTypePredicate)) { + if (reportErrors) { + errorReporter(ts.Diagnostics.Signature_0_must_be_a_type_predicate, signatureToString(source)); + } + return 0 /* False */; + } + } + else { + // When relating callback signatures, we still need to relate return types bi-variantly as otherwise + // the containing type wouldn't be co-variant. For example, interface Foo { add(cb: () => T): void } + // wouldn't be co-variant for T without this rule. + result &= callbackCheck === 1 /* Bivariant */ && compareTypes(targetReturnType, sourceReturnType, /*reportErrors*/ false) || + compareTypes(sourceReturnType, targetReturnType, reportErrors); + } + } + return result; + } + function compareTypePredicateRelatedTo(source, target, sourceDeclaration, targetDeclaration, reportErrors, errorReporter, compareTypes) { + if (source.kind !== target.kind) { + if (reportErrors) { + errorReporter(ts.Diagnostics.A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard); + errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target)); + } + return 0 /* False */; + } + if (source.kind === 1 /* Identifier */) { + var targetPredicate = target; + var sourceIndex = source.parameterIndex - (ts.getThisParameter(sourceDeclaration) ? 1 : 0); + var targetIndex = targetPredicate.parameterIndex - (ts.getThisParameter(targetDeclaration) ? 1 : 0); + if (sourceIndex !== targetIndex) { + if (reportErrors) { + errorReporter(ts.Diagnostics.Parameter_0_is_not_in_the_same_position_as_parameter_1, source.parameterName, targetPredicate.parameterName); + errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target)); + } + return 0 /* False */; + } + } + var related = compareTypes(source.type, target.type, reportErrors); + if (related === 0 /* False */ && reportErrors) { + errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target)); + } + return related; + } + function isImplementationCompatibleWithOverload(implementation, overload) { + var erasedSource = getErasedSignature(implementation); + var erasedTarget = getErasedSignature(overload); + // First see if the return types are compatible in either direction. + var sourceReturnType = getReturnTypeOfSignature(erasedSource); + var targetReturnType = getReturnTypeOfSignature(erasedTarget); + if (targetReturnType === voidType + || isTypeRelatedTo(targetReturnType, sourceReturnType, assignableRelation) + || isTypeRelatedTo(sourceReturnType, targetReturnType, assignableRelation)) { + return isSignatureAssignableTo(erasedSource, erasedTarget, /*ignoreReturnTypes*/ true); + } + return false; + } + function isEmptyResolvedType(t) { + return t.properties.length === 0 && + t.callSignatures.length === 0 && + t.constructSignatures.length === 0 && + !t.stringIndexInfo && + !t.numberIndexInfo; + } + function isEmptyObjectType(type) { + return type.flags & 524288 /* Object */ ? isEmptyResolvedType(resolveStructuredTypeMembers(type)) : + type.flags & 67108864 /* NonPrimitive */ ? true : + type.flags & 1048576 /* Union */ ? ts.some(type.types, isEmptyObjectType) : + type.flags & 2097152 /* Intersection */ ? ts.every(type.types, isEmptyObjectType) : + false; + } + function isEmptyAnonymousObjectType(type) { + return !!(ts.getObjectFlags(type) & 16 /* Anonymous */) && isEmptyObjectType(type); + } + function isEnumTypeRelatedTo(sourceSymbol, targetSymbol, errorReporter) { + if (sourceSymbol === targetSymbol) { + return true; + } + var id = getSymbolId(sourceSymbol) + "," + getSymbolId(targetSymbol); + var relation = enumRelation.get(id); + if (relation !== undefined && !(relation === 2 /* Failed */ && errorReporter)) { + return relation === 1 /* Succeeded */; + } + if (sourceSymbol.escapedName !== targetSymbol.escapedName || !(sourceSymbol.flags & 256 /* RegularEnum */) || !(targetSymbol.flags & 256 /* RegularEnum */)) { + enumRelation.set(id, 3 /* FailedAndReported */); + return false; + } + var targetEnumType = getTypeOfSymbol(targetSymbol); + for (var _i = 0, _a = getPropertiesOfType(getTypeOfSymbol(sourceSymbol)); _i < _a.length; _i++) { + var property = _a[_i]; + if (property.flags & 8 /* EnumMember */) { + var targetProperty = getPropertyOfType(targetEnumType, property.escapedName); + if (!targetProperty || !(targetProperty.flags & 8 /* EnumMember */)) { + if (errorReporter) { + errorReporter(ts.Diagnostics.Property_0_is_missing_in_type_1, ts.symbolName(property), typeToString(getDeclaredTypeOfSymbol(targetSymbol), /*enclosingDeclaration*/ undefined, 64 /* UseFullyQualifiedType */)); + enumRelation.set(id, 3 /* FailedAndReported */); + } + else { + enumRelation.set(id, 2 /* Failed */); + } + return false; + } + } + } + enumRelation.set(id, 1 /* Succeeded */); + return true; + } + function isSimpleTypeRelatedTo(source, target, relation, errorReporter) { + var s = source.flags; + var t = target.flags; + if (t & 3 /* AnyOrUnknown */ || s & 131072 /* Never */ || source === wildcardType) + return true; + if (t & 131072 /* Never */) + return false; + if (s & 132 /* StringLike */ && t & 4 /* String */) + return true; + if (s & 128 /* StringLiteral */ && s & 1024 /* EnumLiteral */ && + t & 128 /* StringLiteral */ && !(t & 1024 /* EnumLiteral */) && + source.value === target.value) + return true; + if (s & 296 /* NumberLike */ && t & 8 /* Number */) + return true; + if (s & 256 /* NumberLiteral */ && s & 1024 /* EnumLiteral */ && + t & 256 /* NumberLiteral */ && !(t & 1024 /* EnumLiteral */) && + source.value === target.value) + return true; + if (s & 2112 /* BigIntLike */ && t & 64 /* BigInt */) + return true; + if (s & 528 /* BooleanLike */ && t & 16 /* Boolean */) + return true; + if (s & 12288 /* ESSymbolLike */ && t & 4096 /* ESSymbol */) + return true; + if (s & 32 /* Enum */ && t & 32 /* Enum */ && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) + return true; + if (s & 1024 /* EnumLiteral */ && t & 1024 /* EnumLiteral */) { + if (s & 1048576 /* Union */ && t & 1048576 /* Union */ && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) + return true; + if (s & 2944 /* Literal */ && t & 2944 /* Literal */ && + source.value === target.value && + isEnumTypeRelatedTo(getParentOfSymbol(source.symbol), getParentOfSymbol(target.symbol), errorReporter)) + return true; + } + if (s & 32768 /* Undefined */ && (!strictNullChecks || t & (32768 /* Undefined */ | 16384 /* Void */))) + return true; + if (s & 65536 /* Null */ && (!strictNullChecks || t & 65536 /* Null */)) + return true; + if (s & 524288 /* Object */ && t & 67108864 /* NonPrimitive */) + return true; + if (s & 8192 /* UniqueESSymbol */ || t & 8192 /* UniqueESSymbol */) + return false; + if (relation === assignableRelation || relation === definitelyAssignableRelation || relation === comparableRelation) { + if (s & 1 /* Any */) + return true; + // Type number or any numeric literal type is assignable to any numeric enum type or any + // numeric enum literal type. This rule exists for backwards compatibility reasons because + // bit-flag enum types sometimes look like literal enum types with numeric literal values. + if (s & (8 /* Number */ | 256 /* NumberLiteral */) && !(s & 1024 /* EnumLiteral */) && (t & 32 /* Enum */ || t & 256 /* NumberLiteral */ && t & 1024 /* EnumLiteral */)) + return true; + } + return false; + } + function isTypeRelatedTo(source, target, relation) { + if (isFreshLiteralType(source)) { + source = source.regularType; + } + if (isFreshLiteralType(target)) { + target = target.regularType; + } + if (source === target || + relation === comparableRelation && !(target.flags & 131072 /* Never */) && isSimpleTypeRelatedTo(target, source, relation) || + relation !== identityRelation && isSimpleTypeRelatedTo(source, target, relation)) { + return true; + } + if (source.flags & 524288 /* Object */ && target.flags & 524288 /* Object */) { + var related = relation.get(getRelationKey(source, target, relation)); + if (related !== undefined) { + return related === 1 /* Succeeded */; + } + } + if (source.flags & 66846720 /* StructuredOrInstantiable */ || target.flags & 66846720 /* StructuredOrInstantiable */) { + return checkTypeRelatedTo(source, target, relation, /*errorNode*/ undefined); + } + return false; + } + function isIgnoredJsxProperty(source, sourceProp, targetMemberType) { + return ts.getObjectFlags(source) & 4096 /* JsxAttributes */ && !(isUnhyphenatedJsxName(sourceProp.escapedName) || targetMemberType); + } + /** + * Checks if 'source' is related to 'target' (e.g.: is a assignable to). + * @param source The left-hand-side of the relation. + * @param target The right-hand-side of the relation. + * @param relation The relation considered. One of 'identityRelation', 'subtypeRelation', 'assignableRelation', or 'comparableRelation'. + * Used as both to determine which checks are performed and as a cache of previously computed results. + * @param errorNode The suggested node upon which all errors will be reported, if defined. This may or may not be the actual node used. + * @param headMessage If the error chain should be prepended by a head message, then headMessage will be used. + * @param containingMessageChain A chain of errors to prepend any new errors found. + */ + function checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain, errorOutputContainer) { + var errorInfo; + var relatedInfo; + var maybeKeys; + var sourceStack; + var targetStack; + var maybeCount = 0; + var depth = 0; + var expandingFlags = 0 /* None */; + var overflow = false; + var suppressNextError = false; + ts.Debug.assert(relation !== identityRelation || !errorNode, "no error reporting in identity checking"); + var result = isRelatedTo(source, target, /*reportErrors*/ !!errorNode, headMessage); + if (overflow) { + error(errorNode, ts.Diagnostics.Excessive_stack_depth_comparing_types_0_and_1, typeToString(source), typeToString(target)); + } + else if (errorInfo) { + if (containingMessageChain) { + var chain_1 = containingMessageChain(); + if (chain_1) { + errorInfo = ts.concatenateDiagnosticMessageChains(chain_1, errorInfo); + } + } + var relatedInformation = void 0; + // Check if we should issue an extra diagnostic to produce a quickfix for a slightly incorrect import statement + if (headMessage && errorNode && !result && source.symbol) { + var links = getSymbolLinks(source.symbol); + if (links.originatingImport && !ts.isImportCall(links.originatingImport)) { + var helpfulRetry = checkTypeRelatedTo(getTypeOfSymbol(links.target), target, relation, /*errorNode*/ undefined); + if (helpfulRetry) { + // Likely an incorrect import. Issue a helpful diagnostic to produce a quickfix to change the import + var diag_1 = ts.createDiagnosticForNode(links.originatingImport, ts.Diagnostics.Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_Consider_using_a_default_import_or_import_require_here_instead); + relatedInformation = ts.append(relatedInformation, diag_1); // Cause the error to appear with the error that triggered it + } + } + } + var diag = ts.createDiagnosticForNodeFromMessageChain(errorNode, errorInfo, relatedInformation); + if (relatedInfo) { + addRelatedInfo.apply(void 0, [diag].concat(relatedInfo)); + } + if (errorOutputContainer) { + errorOutputContainer.error = diag; + } + diagnostics.add(diag); // TODO: GH#18217 + } + return result !== 0 /* False */; + function reportError(message, arg0, arg1, arg2, arg3) { + ts.Debug.assert(!!errorNode); + errorInfo = ts.chainDiagnosticMessages(errorInfo, message, arg0, arg1, arg2, arg3); + } + function associateRelatedInfo(info) { + ts.Debug.assert(!!errorInfo); + if (!relatedInfo) { + relatedInfo = [info]; + } + else { + relatedInfo.push(info); + } + } + function reportRelationError(message, source, target) { + var sourceType = typeToString(source); + var targetType = typeToString(target); + if (sourceType === targetType) { + sourceType = typeToString(source, /*enclosingDeclaration*/ undefined, 64 /* UseFullyQualifiedType */); + targetType = typeToString(target, /*enclosingDeclaration*/ undefined, 64 /* UseFullyQualifiedType */); + } + if (!message) { + if (relation === comparableRelation) { + message = ts.Diagnostics.Type_0_is_not_comparable_to_type_1; + } + else if (sourceType === targetType) { + message = ts.Diagnostics.Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated; + } + else { + message = ts.Diagnostics.Type_0_is_not_assignable_to_type_1; + } + } + reportError(message, sourceType, targetType); + } + function tryElaborateErrorsForPrimitivesAndObjects(source, target) { + var sourceType = typeToString(source); + var targetType = typeToString(target); + if ((globalStringType === source && stringType === target) || + (globalNumberType === source && numberType === target) || + (globalBooleanType === source && booleanType === target) || + (getGlobalESSymbolType(/*reportErrors*/ false) === source && esSymbolType === target)) { + reportError(ts.Diagnostics._0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible, targetType, sourceType); + } + } + function isUnionOrIntersectionTypeWithoutNullableConstituents(type) { + if (!(type.flags & 3145728 /* UnionOrIntersection */)) { + return false; + } + // at this point we know that this is union or intersection type possibly with nullable constituents. + // check if we still will have compound type if we ignore nullable components. + var seenNonNullable = false; + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (t.flags & 98304 /* Nullable */) { + continue; + } + if (seenNonNullable) { + return true; + } + seenNonNullable = true; + } + return false; + } + /** + * Compare two types and return + * * Ternary.True if they are related with no assumptions, + * * Ternary.Maybe if they are related with assumptions of other relationships, or + * * Ternary.False if they are not related. + */ + function isRelatedTo(source, target, reportErrors, headMessage, isApparentIntersectionConstituent) { + if (reportErrors === void 0) { reportErrors = false; } + if (isFreshLiteralType(source)) { + source = source.regularType; + } + if (isFreshLiteralType(target)) { + target = target.regularType; + } + if (source.flags & 33554432 /* Substitution */) { + source = relation === definitelyAssignableRelation ? source.typeVariable : source.substitute; + } + if (target.flags & 33554432 /* Substitution */) { + target = target.typeVariable; + } + if (source.flags & 8388608 /* IndexedAccess */) { + source = getSimplifiedType(source); + } + if (target.flags & 8388608 /* IndexedAccess */) { + target = getSimplifiedType(target); + } + // Try to see if we're relating something like `Foo` -> `Bar | null | undefined`. + // If so, reporting the `null` and `undefined` in the type is hardly useful. + // First, see if we're even relating an object type to a union. + // Then see if the target is stripped down to a single non-union type. + // Note + // * We actually want to remove null and undefined naively here (rather than using getNonNullableType), + // since we don't want to end up with a worse error like "`Foo` is not assignable to `NonNullable`" + // when dealing with generics. + // * We also don't deal with primitive source types, since we already halt elaboration below. + if (target.flags & 1048576 /* Union */ && source.flags & 524288 /* Object */ && + target.types.length <= 3 && maybeTypeOfKind(target, 98304 /* Nullable */)) { + var nullStrippedTarget = extractTypesOfKind(target, ~98304 /* Nullable */); + if (!(nullStrippedTarget.flags & (1048576 /* Union */ | 131072 /* Never */))) { + target = nullStrippedTarget; + } + } + // both types are the same - covers 'they are the same primitive type or both are Any' or the same type parameter cases + if (source === target) + return -1 /* True */; + if (relation === identityRelation) { + return isIdenticalTo(source, target); + } + if (relation === comparableRelation && !(target.flags & 131072 /* Never */) && isSimpleTypeRelatedTo(target, source, relation) || + isSimpleTypeRelatedTo(source, target, relation, reportErrors ? reportError : undefined)) + return -1 /* True */; + var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096 /* JsxAttributes */); + if (isObjectLiteralType(source) && ts.getObjectFlags(source) & 32768 /* FreshLiteral */) { + var discriminantType = target.flags & 1048576 /* Union */ ? findMatchingDiscriminantType(source, target) : undefined; + if (hasExcessProperties(source, target, discriminantType, reportErrors)) { + if (reportErrors) { + reportRelationError(headMessage, source, target); + } + return 0 /* False */; + } + // Above we check for excess properties with respect to the entire target type. When union + // and intersection types are further deconstructed on the target side, we don't want to + // make the check again (as it might fail for a partial target type). Therefore we obtain + // the regular source type and proceed with that. + if (isUnionOrIntersectionTypeWithoutNullableConstituents(target) && !discriminantType) { + source = getRegularTypeOfObjectLiteral(source); + } + } + if (relation !== comparableRelation && !isApparentIntersectionConstituent && + source.flags & (131068 /* Primitive */ | 524288 /* Object */ | 2097152 /* Intersection */) && source !== globalObjectType && + target.flags & (524288 /* Object */ | 2097152 /* Intersection */) && isWeakType(target) && + (getPropertiesOfType(source).length > 0 || typeHasCallOrConstructSignatures(source)) && + !hasCommonProperties(source, target, isComparingJsxAttributes)) { + if (reportErrors) { + var calls = getSignaturesOfType(source, 0 /* Call */); + var constructs = getSignaturesOfType(source, 1 /* Construct */); + if (calls.length > 0 && isRelatedTo(getReturnTypeOfSignature(calls[0]), target, /*reportErrors*/ false) || + constructs.length > 0 && isRelatedTo(getReturnTypeOfSignature(constructs[0]), target, /*reportErrors*/ false)) { + reportError(ts.Diagnostics.Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it, typeToString(source), typeToString(target)); + } + else { + reportError(ts.Diagnostics.Type_0_has_no_properties_in_common_with_type_1, typeToString(source), typeToString(target)); + } + } + return 0 /* False */; + } + var result = 0 /* False */; + var saveErrorInfo = errorInfo; + var isIntersectionConstituent = !!isApparentIntersectionConstituent; + // Note that these checks are specifically ordered to produce correct results. In particular, + // we need to deconstruct unions before intersections (because unions are always at the top), + // and we need to handle "each" relations before "some" relations for the same kind of type. + if (source.flags & 1048576 /* Union */) { + result = relation === comparableRelation ? + someTypeRelatedToType(source, target, reportErrors && !(source.flags & 131068 /* Primitive */)) : + eachTypeRelatedToType(source, target, reportErrors && !(source.flags & 131068 /* Primitive */)); + } + else { + if (target.flags & 1048576 /* Union */) { + result = typeRelatedToSomeType(source, target, reportErrors && !(source.flags & 131068 /* Primitive */) && !(target.flags & 131068 /* Primitive */)); + } + else if (target.flags & 2097152 /* Intersection */) { + isIntersectionConstituent = true; // set here to affect the following trio of checks + result = typeRelatedToEachType(source, target, reportErrors); + } + else if (source.flags & 2097152 /* Intersection */) { + // Check to see if any constituents of the intersection are immediately related to the target. + // + // Don't report errors though. Checking whether a constituent is related to the source is not actually + // useful and leads to some confusing error messages. Instead it is better to let the below checks + // take care of this, or to not elaborate at all. For instance, + // + // - For an object type (such as 'C = A & B'), users are usually more interested in structural errors. + // + // - For a union type (such as '(A | B) = (C & D)'), it's better to hold onto the whole intersection + // than to report that 'D' is not assignable to 'A' or 'B'. + // + // - For a primitive type or type parameter (such as 'number = A & B') there is no point in + // breaking the intersection apart. + result = someTypeRelatedToType(source, target, /*reportErrors*/ false); + } + if (!result && (source.flags & 66846720 /* StructuredOrInstantiable */ || target.flags & 66846720 /* StructuredOrInstantiable */)) { + if (result = recursiveTypeRelatedTo(source, target, reportErrors, isIntersectionConstituent)) { + errorInfo = saveErrorInfo; + } + } + } + if (!result && source.flags & 2097152 /* Intersection */) { + // The combined constraint of an intersection type is the intersection of the constraints of + // the constituents. When an intersection type contains instantiable types with union type + // constraints, there are situations where we need to examine the combined constraint. One is + // when the target is a union type. Another is when the intersection contains types belonging + // to one of the disjoint domains. For example, given type variables T and U, each with the + // constraint 'string | number', the combined constraint of 'T & U' is 'string | number' and + // we need to check this constraint against a union on the target side. Also, given a type + // variable V constrained to 'string | number', 'V & number' has a combined constraint of + // 'string & number | number & number' which reduces to just 'number'. + var constraint = getUnionConstraintOfIntersection(source, !!(target.flags & 1048576 /* Union */)); + if (constraint) { + if (result = isRelatedTo(constraint, target, reportErrors, /*headMessage*/ undefined, isIntersectionConstituent)) { + errorInfo = saveErrorInfo; + } + } + } + if (!result && reportErrors) { + var maybeSuppress = suppressNextError; + suppressNextError = false; + if (source.flags & 524288 /* Object */ && target.flags & 131068 /* Primitive */) { + tryElaborateErrorsForPrimitivesAndObjects(source, target); + } + else if (source.symbol && source.flags & 524288 /* Object */ && globalObjectType === source) { + reportError(ts.Diagnostics.The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead); + } + else if (isComparingJsxAttributes && target.flags & 2097152 /* Intersection */) { + var targetTypes = target.types; + var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes, errorNode); + var intrinsicClassAttributes = getJsxType(JsxNames.IntrinsicClassAttributes, errorNode); + if (intrinsicAttributes !== errorType && intrinsicClassAttributes !== errorType && + (ts.contains(targetTypes, intrinsicAttributes) || ts.contains(targetTypes, intrinsicClassAttributes))) { + // do not report top error + return result; + } + } + if (!headMessage && maybeSuppress) { + // Used by, eg, missing property checking to replace the top-level message with a more informative one + return result; + } + reportRelationError(headMessage, source, target); + } + return result; + } + function isIdenticalTo(source, target) { + var result; + var flags = source.flags & target.flags; + if (flags & 524288 /* Object */ || flags & 8388608 /* IndexedAccess */ || flags & 16777216 /* Conditional */ || flags & 4194304 /* Index */ || flags & 33554432 /* Substitution */) { + return recursiveTypeRelatedTo(source, target, /*reportErrors*/ false, /*isIntersectionConstituent*/ false); + } + if (flags & (1048576 /* Union */ | 2097152 /* Intersection */)) { + if (result = eachTypeRelatedToSomeType(source, target)) { + if (result &= eachTypeRelatedToSomeType(target, source)) { + return result; + } + } + } + return 0 /* False */; + } + function hasExcessProperties(source, target, discriminant, reportErrors) { + if (!noImplicitAny && ts.getObjectFlags(target) & 16384 /* JSLiteral */) { + return false; // Disable excess property checks on JS literals to simulate having an implicit "index signature" - but only outside of noImplicitAny + } + if (maybeTypeOfKind(target, 524288 /* Object */) && !(ts.getObjectFlags(target) & 512 /* ObjectLiteralPatternWithComputedProperties */)) { + var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096 /* JsxAttributes */); + if ((relation === assignableRelation || relation === definitelyAssignableRelation || relation === comparableRelation) && + (isTypeSubsetOf(globalObjectType, target) || (!isComparingJsxAttributes && isEmptyObjectType(target)))) { + return false; + } + if (discriminant) { + // check excess properties against discriminant type only, not the entire union + return hasExcessProperties(source, discriminant, /*discriminant*/ undefined, reportErrors); + } + var _loop_6 = function (prop) { + if (shouldCheckAsExcessProperty(prop, source.symbol) && !isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { + if (reportErrors) { + // We know *exactly* where things went wrong when comparing the types. + // Use this property as the error node as this will be more helpful in + // reasoning about what went wrong. + if (!errorNode) + return { value: ts.Debug.fail() }; + if (ts.isJsxAttributes(errorNode) || ts.isJsxOpeningLikeElement(errorNode) || ts.isJsxOpeningLikeElement(errorNode.parent)) { + // JsxAttributes has an object-literal flag and undergo same type-assignablity check as normal object-literal. + // However, using an object-literal error message will be very confusing to the users so we give different a message. + // TODO: Spelling suggestions for excess jsx attributes (needs new diagnostic messages) + reportError(ts.Diagnostics.Property_0_does_not_exist_on_type_1, symbolToString(prop), typeToString(target)); + } + else { + // use the property's value declaration if the property is assigned inside the literal itself + var objectLiteralDeclaration_1 = source.symbol && ts.firstOrUndefined(source.symbol.declarations); + var suggestion = void 0; + if (prop.valueDeclaration && ts.findAncestor(prop.valueDeclaration, function (d) { return d === objectLiteralDeclaration_1; })) { + var propDeclaration = prop.valueDeclaration; + ts.Debug.assertNode(propDeclaration, ts.isObjectLiteralElementLike); + errorNode = propDeclaration; + var name = propDeclaration.name; + if (ts.isIdentifier(name)) { + suggestion = getSuggestionForNonexistentProperty(name, target); + } + } + if (suggestion !== undefined) { + reportError(ts.Diagnostics.Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_write_2, symbolToString(prop), typeToString(target), suggestion); + } + else { + reportError(ts.Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(prop), typeToString(target)); + } + } + } + return { value: true }; + } + }; + for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) { + var prop = _a[_i]; + var state_2 = _loop_6(prop); + if (typeof state_2 === "object") + return state_2.value; + } + } + return false; + } + function shouldCheckAsExcessProperty(prop, container) { + return prop.valueDeclaration && container.valueDeclaration && prop.valueDeclaration.parent === container.valueDeclaration; + } + function eachTypeRelatedToSomeType(source, target) { + var result = -1 /* True */; + var sourceTypes = source.types; + for (var _i = 0, sourceTypes_1 = sourceTypes; _i < sourceTypes_1.length; _i++) { + var sourceType = sourceTypes_1[_i]; + var related = typeRelatedToSomeType(sourceType, target, /*reportErrors*/ false); + if (!related) { + return 0 /* False */; + } + result &= related; + } + return result; + } + function typeRelatedToSomeType(source, target, reportErrors) { + var targetTypes = target.types; + if (target.flags & 1048576 /* Union */ && containsType(targetTypes, source)) { + return -1 /* True */; + } + for (var _i = 0, targetTypes_1 = targetTypes; _i < targetTypes_1.length; _i++) { + var type = targetTypes_1[_i]; + var related = isRelatedTo(source, type, /*reportErrors*/ false); + if (related) { + return related; + } + } + if (reportErrors) { + var bestMatchingType = findMatchingDiscriminantType(source, target) || + findMatchingTypeReferenceOrTypeAliasReference(source, target) || + findBestTypeForObjectLiteral(source, target) || + findBestTypeForInvokable(source, target) || + findMostOverlappyType(source, target); + isRelatedTo(source, bestMatchingType || targetTypes[targetTypes.length - 1], /*reportErrors*/ true); + } + return 0 /* False */; + } + function findMatchingTypeReferenceOrTypeAliasReference(source, unionTarget) { + var sourceObjectFlags = ts.getObjectFlags(source); + if (sourceObjectFlags & (4 /* Reference */ | 16 /* Anonymous */) && unionTarget.flags & 1048576 /* Union */) { + return ts.find(unionTarget.types, function (target) { + if (target.flags & 524288 /* Object */) { + var overlapObjFlags = sourceObjectFlags & ts.getObjectFlags(target); + if (overlapObjFlags & 4 /* Reference */) { + return source.target === target.target; + } + if (overlapObjFlags & 16 /* Anonymous */) { + return !!source.aliasSymbol && source.aliasSymbol === target.aliasSymbol; + } + } + return false; + }); + } + } + function findBestTypeForObjectLiteral(source, unionTarget) { + if (ts.getObjectFlags(source) & 128 /* ObjectLiteral */ && forEachType(unionTarget, isArrayLikeType)) { + return ts.find(unionTarget.types, function (t) { return !isArrayLikeType(t); }); + } + } + function findBestTypeForInvokable(source, unionTarget) { + var signatureKind = 0 /* Call */; + var hasSignatures = getSignaturesOfType(source, signatureKind).length > 0 || + (signatureKind = 1 /* Construct */, getSignaturesOfType(source, signatureKind).length > 0); + if (hasSignatures) { + return ts.find(unionTarget.types, function (t) { return getSignaturesOfType(t, signatureKind).length > 0; }); + } + } + function findMostOverlappyType(source, unionTarget) { + var bestMatch; + var matchingCount = 0; + for (var _i = 0, _a = unionTarget.types; _i < _a.length; _i++) { + var target_1 = _a[_i]; + var overlap = getIntersectionType([getIndexType(source), getIndexType(target_1)]); + if (overlap.flags & 4194304 /* Index */) { + // perfect overlap of keys + bestMatch = target_1; + matchingCount = Infinity; + } + else if (overlap.flags & 1048576 /* Union */) { + // Some subset overlap if we have only string literals. + // If we have a union of index types, it seems likely that we + // needed to elaborate between two generic mapped types anyway. + var len = ts.length(overlap.types); + if (len >= matchingCount) { + bestMatch = target_1; + matchingCount = len; + } + } + else if (!(overlap.flags & 131072 /* Never */) && 1 >= matchingCount) { + bestMatch = target_1; + matchingCount = 1; + } + } + return bestMatch; + } + // Keep this up-to-date with the same logic within `getApparentTypeOfContextualType`, since they should behave similarly + function findMatchingDiscriminantType(source, target) { + if (target.flags & 1048576 /* Union */) { + var sourceProperties = getPropertiesOfObjectType(source); + if (sourceProperties) { + var sourcePropertiesFiltered = findDiscriminantProperties(sourceProperties, target); + if (sourcePropertiesFiltered) { + return discriminateTypeByDiscriminableItems(target, ts.map(sourcePropertiesFiltered, function (p) { return [function () { return getTypeOfSymbol(p); }, p.escapedName]; }), isRelatedTo); + } + } + } + return undefined; + } + function typeRelatedToEachType(source, target, reportErrors) { + var result = -1 /* True */; + var targetTypes = target.types; + for (var _i = 0, targetTypes_2 = targetTypes; _i < targetTypes_2.length; _i++) { + var targetType = targetTypes_2[_i]; + var related = isRelatedTo(source, targetType, reportErrors, /*headMessage*/ undefined, /*isIntersectionConstituent*/ true); + if (!related) { + return 0 /* False */; + } + result &= related; + } + return result; + } + function someTypeRelatedToType(source, target, reportErrors) { + var sourceTypes = source.types; + if (source.flags & 1048576 /* Union */ && containsType(sourceTypes, target)) { + return -1 /* True */; + } + var len = sourceTypes.length; + for (var i = 0; i < len; i++) { + var related = isRelatedTo(sourceTypes[i], target, reportErrors && i === len - 1); + if (related) { + return related; + } + } + return 0 /* False */; + } + function eachTypeRelatedToType(source, target, reportErrors) { + var result = -1 /* True */; + var sourceTypes = source.types; + for (var _i = 0, sourceTypes_2 = sourceTypes; _i < sourceTypes_2.length; _i++) { + var sourceType = sourceTypes_2[_i]; + var related = isRelatedTo(sourceType, target, reportErrors); + if (!related) { + return 0 /* False */; + } + result &= related; + } + return result; + } + function typeArgumentsRelatedTo(sources, targets, variances, reportErrors) { + if (sources === void 0) { sources = ts.emptyArray; } + if (targets === void 0) { targets = ts.emptyArray; } + if (variances === void 0) { variances = ts.emptyArray; } + if (sources.length !== targets.length && relation === identityRelation) { + return 0 /* False */; + } + var length = sources.length <= targets.length ? sources.length : targets.length; + var result = -1 /* True */; + for (var i = 0; i < length; i++) { + // When variance information isn't available we default to covariance. This happens + // in the process of computing variance information for recursive types and when + // comparing 'this' type arguments. + var variance = i < variances.length ? variances[i] : 1 /* Covariant */; + // We ignore arguments for independent type parameters (because they're never witnessed). + if (variance !== 4 /* Independent */) { + var s = sources[i]; + var t = targets[i]; + var related = -1 /* True */; + if (variance === 1 /* Covariant */) { + related = isRelatedTo(s, t, reportErrors); + } + else if (variance === 2 /* Contravariant */) { + related = isRelatedTo(t, s, reportErrors); + } + else if (variance === 3 /* Bivariant */) { + // In the bivariant case we first compare contravariantly without reporting + // errors. Then, if that doesn't succeed, we compare covariantly with error + // reporting. Thus, error elaboration will be based on the the covariant check, + // which is generally easier to reason about. + related = isRelatedTo(t, s, /*reportErrors*/ false); + if (!related) { + related = isRelatedTo(s, t, reportErrors); + } + } + else { + // In the invariant case we first compare covariantly, and only when that + // succeeds do we proceed to compare contravariantly. Thus, error elaboration + // will typically be based on the covariant check. + related = isRelatedTo(s, t, reportErrors); + if (related) { + related &= isRelatedTo(t, s, reportErrors); + } + } + if (!related) { + return 0 /* False */; + } + result &= related; + } + } + return result; + } + // Determine if possibly recursive types are related. First, check if the result is already available in the global cache. + // Second, check if we have already started a comparison of the given two types in which case we assume the result to be true. + // Third, check if both types are part of deeply nested chains of generic type instantiations and if so assume the types are + // equal and infinitely expanding. Fourth, if we have reached a depth of 100 nested comparisons, assume we have runaway recursion + // and issue an error. Otherwise, actually compare the structure of the two types. + function recursiveTypeRelatedTo(source, target, reportErrors, isIntersectionConstituent) { + if (overflow) { + return 0 /* False */; + } + var id = getRelationKey(source, target, relation); + var related = relation.get(id); + if (related !== undefined) { + if (reportErrors && related === 2 /* Failed */) { + // We are elaborating errors and the cached result is an unreported failure. The result will be reported + // as a failure, and should be updated as a reported failure by the bottom of this function. + } + else { + return related === 1 /* Succeeded */ ? -1 /* True */ : 0 /* False */; + } + } + if (!maybeKeys) { + maybeKeys = []; + sourceStack = []; + targetStack = []; + } + else { + for (var i = 0; i < maybeCount; i++) { + // If source and target are already being compared, consider them related with assumptions + if (id === maybeKeys[i]) { + return 1 /* Maybe */; + } + } + if (depth === 100) { + overflow = true; + return 0 /* False */; + } + } + var maybeStart = maybeCount; + maybeKeys[maybeCount] = id; + maybeCount++; + sourceStack[depth] = source; + targetStack[depth] = target; + depth++; + var saveExpandingFlags = expandingFlags; + if (!(expandingFlags & 1 /* Source */) && isDeeplyNestedType(source, sourceStack, depth)) + expandingFlags |= 1 /* Source */; + if (!(expandingFlags & 2 /* Target */) && isDeeplyNestedType(target, targetStack, depth)) + expandingFlags |= 2 /* Target */; + var result = expandingFlags !== 3 /* Both */ ? structuredTypeRelatedTo(source, target, reportErrors, isIntersectionConstituent) : 1 /* Maybe */; + expandingFlags = saveExpandingFlags; + depth--; + if (result) { + if (result === -1 /* True */ || depth === 0) { + // If result is definitely true, record all maybe keys as having succeeded + for (var i = maybeStart; i < maybeCount; i++) { + relation.set(maybeKeys[i], 1 /* Succeeded */); + } + maybeCount = maybeStart; + } + } + else { + // A false result goes straight into global cache (when something is false under + // assumptions it will also be false without assumptions) + relation.set(id, reportErrors ? 3 /* FailedAndReported */ : 2 /* Failed */); + maybeCount = maybeStart; + } + return result; + } + function getConstraintForRelation(type) { + return relation === definitelyAssignableRelation ? undefined : getConstraintOfType(type); + } + function structuredTypeRelatedTo(source, target, reportErrors, isIntersectionConstituent) { + var flags = source.flags & target.flags; + if (relation === identityRelation && !(flags & 524288 /* Object */)) { + if (flags & 4194304 /* Index */) { + return isRelatedTo(source.type, target.type, /*reportErrors*/ false); + } + var result_2 = 0 /* False */; + if (flags & 8388608 /* IndexedAccess */) { + if (result_2 = isRelatedTo(source.objectType, target.objectType, /*reportErrors*/ false)) { + if (result_2 &= isRelatedTo(source.indexType, target.indexType, /*reportErrors*/ false)) { + return result_2; + } + } + } + if (flags & 16777216 /* Conditional */) { + if (source.root.isDistributive === target.root.isDistributive) { + if (result_2 = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) { + if (result_2 &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) { + if (result_2 &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), /*reportErrors*/ false)) { + if (result_2 &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), /*reportErrors*/ false)) { + return result_2; + } + } + } + } + } + } + if (flags & 33554432 /* Substitution */) { + return isRelatedTo(source.substitute, target.substitute, /*reportErrors*/ false); + } + return 0 /* False */; + } + var result; + var originalErrorInfo; + var saveErrorInfo = errorInfo; + // We limit alias variance probing to only object and conditional types since their alias behavior + // is more predictable than other, interned types, which may or may not have an alias depending on + // the order in which things were checked. + if (source.flags & (524288 /* Object */ | 16777216 /* Conditional */) && source.aliasSymbol && + source.aliasTypeArguments && source.aliasSymbol === target.aliasSymbol && + !(source.aliasTypeArgumentsContainsMarker || target.aliasTypeArgumentsContainsMarker)) { + var variances = getAliasVariances(source.aliasSymbol); + if (result = typeArgumentsRelatedTo(source.aliasTypeArguments, target.aliasTypeArguments, variances, reportErrors)) { + return result; + } + originalErrorInfo = errorInfo; + errorInfo = saveErrorInfo; + } + if (target.flags & 262144 /* TypeParameter */) { + // A source type { [P in Q]: X } is related to a target type T if keyof T is related to Q and X is related to T[Q]. + if (ts.getObjectFlags(source) & 32 /* Mapped */ && isRelatedTo(getIndexType(target), getConstraintTypeFromMappedType(source))) { + if (!(getMappedTypeModifiers(source) & 4 /* IncludeOptional */)) { + var templateType = getTemplateTypeFromMappedType(source); + var indexedAccessType = getIndexedAccessType(target, getTypeParameterFromMappedType(source)); + if (result = isRelatedTo(templateType, indexedAccessType, reportErrors)) { + return result; + } + } + } + } + else if (target.flags & 4194304 /* Index */) { + // A keyof S is related to a keyof T if T is related to S. + if (source.flags & 4194304 /* Index */) { + if (result = isRelatedTo(target.type, source.type, /*reportErrors*/ false)) { + return result; + } + } + // A type S is assignable to keyof T if S is assignable to keyof C, where C is the + // simplified form of T or, if T doesn't simplify, the constraint of T. + if (relation !== definitelyAssignableRelation) { + var simplified = getSimplifiedType(target.type); + var constraint = simplified !== target.type ? simplified : getConstraintOfType(target.type); + if (constraint) { + // We require Ternary.True here such that circular constraints don't cause + // false positives. For example, given 'T extends { [K in keyof T]: string }', + // 'keyof T' has itself as its constraint and produces a Ternary.Maybe when + // related to other types. + if (isRelatedTo(source, getIndexType(constraint, target.stringsOnly), reportErrors) === -1 /* True */) { + return -1 /* True */; + } + } + } + } + else if (target.flags & 8388608 /* IndexedAccess */) { + // A type S is related to a type T[K], where T and K aren't both type variables, if S is related to C, + // where C is the base constraint of T[K] + if (relation !== identityRelation && !(isGenericObjectType(target.objectType) && isGenericIndexType(target.indexType))) { + var constraint = getBaseConstraintOfType(target); + if (constraint && constraint !== target) { + if (result = isRelatedTo(source, constraint, reportErrors)) { + return result; + } + } + } + } + else if (isGenericMappedType(target)) { + // A source type T is related to a target type { [P in X]: T[P] } + var template = getTemplateTypeFromMappedType(target); + var modifiers = getMappedTypeModifiers(target); + if (!(modifiers & 8 /* ExcludeOptional */)) { + if (template.flags & 8388608 /* IndexedAccess */ && template.objectType === source && + template.indexType === getTypeParameterFromMappedType(target)) { + return -1 /* True */; + } + // A source type T is related to a target type { [P in Q]: X } if Q is related to keyof T and T[Q] is related to X. + if (!isGenericMappedType(source) && isRelatedTo(getConstraintTypeFromMappedType(target), getIndexType(source))) { + var indexedAccessType = getIndexedAccessType(source, getTypeParameterFromMappedType(target)); + var templateType = getTemplateTypeFromMappedType(target); + if (result = isRelatedTo(indexedAccessType, templateType, reportErrors)) { + return result; + } + } + originalErrorInfo = errorInfo; + errorInfo = saveErrorInfo; + } + } + if (source.flags & 8650752 /* TypeVariable */) { + if (source.flags & 8388608 /* IndexedAccess */ && target.flags & 8388608 /* IndexedAccess */) { + // A type S[K] is related to a type T[J] if S is related to T and K is related to J. + if (result = isRelatedTo(source.objectType, target.objectType, reportErrors)) { + result &= isRelatedTo(source.indexType, target.indexType, reportErrors); + } + if (result) { + errorInfo = saveErrorInfo; + return result; + } + } + var constraint = getConstraintForRelation(source); + if (!constraint || (source.flags & 262144 /* TypeParameter */ && constraint.flags & 3 /* AnyOrUnknown */)) { + // A type variable with no constraint is not related to the non-primitive object type. + if (result = isRelatedTo(emptyObjectType, extractTypesOfKind(target, ~67108864 /* NonPrimitive */))) { + errorInfo = saveErrorInfo; + return result; + } + } + // hi-speed no-this-instantiation check (less accurate, but avoids costly `this`-instantiation when the constraint will suffice), see #28231 for report on why this is needed + else if (result = isRelatedTo(constraint, target, /*reportErrors*/ false, /*headMessage*/ undefined, isIntersectionConstituent)) { + errorInfo = saveErrorInfo; + return result; + } + // slower, fuller, this-instantiated check (necessary when comparing raw `this` types from base classes), see `subclassWithPolymorphicThisIsAssignable.ts` test for example + else if (result = isRelatedTo(getTypeWithThisArgument(constraint, source), target, reportErrors, /*headMessage*/ undefined, isIntersectionConstituent)) { + errorInfo = saveErrorInfo; + return result; + } + } + else if (source.flags & 4194304 /* Index */) { + if (result = isRelatedTo(keyofConstraintType, target, reportErrors)) { + errorInfo = saveErrorInfo; + return result; + } + } + else if (source.flags & 16777216 /* Conditional */) { + if (target.flags & 16777216 /* Conditional */) { + // Two conditional types 'T1 extends U1 ? X1 : Y1' and 'T2 extends U2 ? X2 : Y2' are related if + // one of T1 and T2 is related to the other, U1 and U2 are identical types, X1 is related to X2, + // and Y1 is related to Y2. + if (isTypeIdenticalTo(source.extendsType, target.extendsType) && + (isRelatedTo(source.checkType, target.checkType) || isRelatedTo(target.checkType, source.checkType))) { + if (result = isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), reportErrors)) { + result &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), reportErrors); + } + if (result) { + errorInfo = saveErrorInfo; + return result; + } + } + } + else if (relation !== definitelyAssignableRelation) { + var distributiveConstraint = getConstraintOfDistributiveConditionalType(source); + if (distributiveConstraint) { + if (result = isRelatedTo(distributiveConstraint, target, reportErrors)) { + errorInfo = saveErrorInfo; + return result; + } + } + var defaultConstraint = getDefaultConstraintOfConditionalType(source); + if (defaultConstraint) { + if (result = isRelatedTo(defaultConstraint, target, reportErrors)) { + errorInfo = saveErrorInfo; + return result; + } + } + } + } + else { + // An empty object type is related to any mapped type that includes a '?' modifier. + if (isPartialMappedType(target) && !isGenericMappedType(source) && isEmptyObjectType(source)) { + return -1 /* True */; + } + if (isGenericMappedType(target)) { + if (isGenericMappedType(source)) { + if (result = mappedTypeRelatedTo(source, target, reportErrors)) { + errorInfo = saveErrorInfo; + return result; + } + } + return 0 /* False */; + } + if (relation === definitelyAssignableRelation && isGenericMappedType(source)) { + return 0 /* False */; + } + var sourceIsPrimitive = !!(source.flags & 131068 /* Primitive */); + if (relation !== identityRelation) { + source = getApparentType(source); + } + if (ts.getObjectFlags(source) & 4 /* Reference */ && ts.getObjectFlags(target) & 4 /* Reference */ && source.target === target.target && + !(ts.getObjectFlags(source) & 8192 /* MarkerType */ || ts.getObjectFlags(target) & 8192 /* MarkerType */)) { + // We have type references to the same generic type, and the type references are not marker + // type references (which are intended by be compared structurally). Obtain the variance + // information for the type parameters and relate the type arguments accordingly. + var variances = getVariances(source.target); + if (result = typeArgumentsRelatedTo(source.typeArguments, target.typeArguments, variances, reportErrors)) { + return result; + } + // The type arguments did not relate appropriately, but it may be because we have no variance + // information (in which case typeArgumentsRelatedTo defaulted to covariance for all type + // arguments). It might also be the case that the target type has a 'void' type argument for + // a covariant type parameter that is only used in return positions within the generic type + // (in which case any type argument is permitted on the source side). In those cases we proceed + // with a structural comparison. Otherwise, we know for certain the instantiations aren't + // related and we can return here. + if (variances !== ts.emptyArray && !hasCovariantVoidArgument(target, variances)) { + // In some cases generic types that are covariant in regular type checking mode become + // invariant in --strictFunctionTypes mode because one or more type parameters are used in + // both co- and contravariant positions. In order to make it easier to diagnose *why* such + // types are invariant, if any of the type parameters are invariant we reset the reported + // errors and instead force a structural comparison (which will include elaborations that + // reveal the reason). + if (!(reportErrors && ts.some(variances, function (v) { return v === 0 /* Invariant */; }))) { + return 0 /* False */; + } + // We remember the original error information so we can restore it in case the structural + // comparison unexpectedly succeeds. This can happen when the structural comparison result + // is a Ternary.Maybe for example caused by the recursion depth limiter. + originalErrorInfo = errorInfo; + errorInfo = saveErrorInfo; + } + } + else if (isTupleType(source) && (isArrayType(target) || isReadonlyArrayType(target)) || isArrayType(source) && isReadonlyArrayType(target)) { + return isRelatedTo(getIndexTypeOfType(source, 1 /* Number */) || anyType, getIndexTypeOfType(target, 1 /* Number */) || anyType, reportErrors); + } + // Even if relationship doesn't hold for unions, intersections, or generic type references, + // it may hold in a structural comparison. + // In a check of the form X = A & B, we will have previously checked if A relates to X or B relates + // to X. Failing both of those we want to check if the aggregation of A and B's members structurally + // relates to X. Thus, we include intersection types on the source side here. + if (source.flags & (524288 /* Object */ | 2097152 /* Intersection */) && target.flags & 524288 /* Object */) { + // Report structural errors only if we haven't reported any errors yet + var reportStructuralErrors = reportErrors && errorInfo === saveErrorInfo && !sourceIsPrimitive; + result = propertiesRelatedTo(source, target, reportStructuralErrors); + if (result) { + result &= signaturesRelatedTo(source, target, 0 /* Call */, reportStructuralErrors); + if (result) { + result &= signaturesRelatedTo(source, target, 1 /* Construct */, reportStructuralErrors); + if (result) { + result &= indexTypesRelatedTo(source, target, 0 /* String */, sourceIsPrimitive, reportStructuralErrors); + if (result) { + result &= indexTypesRelatedTo(source, target, 1 /* Number */, sourceIsPrimitive, reportStructuralErrors); + } + } + } + } + if (result) { + if (!originalErrorInfo) { + errorInfo = saveErrorInfo; + return result; + } + errorInfo = originalErrorInfo; + } + } + } + return 0 /* False */; + } + // A type [P in S]: X is related to a type [Q in T]: Y if T is related to S and X' is + // related to Y, where X' is an instantiation of X in which P is replaced with Q. Notice + // that S and T are contra-variant whereas X and Y are co-variant. + function mappedTypeRelatedTo(source, target, reportErrors) { + var modifiersRelated = relation === comparableRelation || (relation === identityRelation ? getMappedTypeModifiers(source) === getMappedTypeModifiers(target) : + getCombinedMappedTypeOptionality(source) <= getCombinedMappedTypeOptionality(target)); + if (modifiersRelated) { + var result_3; + if (result_3 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) { + var mapper = createTypeMapper([getTypeParameterFromMappedType(source)], [getTypeParameterFromMappedType(target)]); + return result_3 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); + } + } + return 0 /* False */; + } + function propertiesRelatedTo(source, target, reportErrors) { + if (relation === identityRelation) { + return propertiesIdenticalTo(source, target); + } + var requireOptionalProperties = relation === subtypeRelation && !isObjectLiteralType(source) && !isEmptyArrayLiteralType(source) && !isTupleType(source); + var unmatchedProperty = getUnmatchedProperty(source, target, requireOptionalProperties); + if (unmatchedProperty) { + if (reportErrors) { + var props = ts.arrayFrom(getUnmatchedProperties(source, target, requireOptionalProperties)); + if (!headMessage || (headMessage.code !== ts.Diagnostics.Class_0_incorrectly_implements_interface_1.code && + headMessage.code !== ts.Diagnostics.Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass.code)) { + suppressNextError = true; // Retain top-level error for interface implementing issues, otherwise omit it + } + if (props.length === 1) { + var propName = symbolToString(unmatchedProperty); + reportError(ts.Diagnostics.Property_0_is_missing_in_type_1_but_required_in_type_2, propName, typeToString(source), typeToString(target)); + if (ts.length(unmatchedProperty.declarations)) { + associateRelatedInfo(ts.createDiagnosticForNode(unmatchedProperty.declarations[0], ts.Diagnostics._0_is_declared_here, propName)); + } + } + else if (props.length > 5) { // arbitrary cutoff for too-long list form + reportError(ts.Diagnostics.Type_0_is_missing_the_following_properties_from_type_1_Colon_2_and_3_more, typeToString(source), typeToString(target), ts.map(props.slice(0, 4), function (p) { return symbolToString(p); }).join(", "), props.length - 4); + } + else { + reportError(ts.Diagnostics.Type_0_is_missing_the_following_properties_from_type_1_Colon_2, typeToString(source), typeToString(target), ts.map(props, function (p) { return symbolToString(p); }).join(", ")); + } + } + return 0 /* False */; + } + if (isObjectLiteralType(target)) { + for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) { + var sourceProp = _a[_i]; + if (!getPropertyOfObjectType(target, sourceProp.escapedName)) { + var sourceType = getTypeOfSymbol(sourceProp); + if (!(sourceType === undefinedType || sourceType === undefinedWideningType)) { + if (reportErrors) { + reportError(ts.Diagnostics.Property_0_does_not_exist_on_type_1, symbolToString(sourceProp), typeToString(target)); + } + return 0 /* False */; + } + } + } + } + var result = -1 /* True */; + if (isTupleType(target)) { + var targetRestType = getRestTypeOfTupleType(target); + if (targetRestType) { + if (!isTupleType(source)) { + return 0 /* False */; + } + var sourceRestType = getRestTypeOfTupleType(source); + if (sourceRestType && !isRelatedTo(sourceRestType, targetRestType, reportErrors)) { + if (reportErrors) { + reportError(ts.Diagnostics.Rest_signatures_are_incompatible); + } + return 0 /* False */; + } + var targetCount = getTypeReferenceArity(target) - 1; + var sourceCount = getTypeReferenceArity(source) - (sourceRestType ? 1 : 0); + for (var i = targetCount; i < sourceCount; i++) { + var related = isRelatedTo(source.typeArguments[i], targetRestType, reportErrors); + if (!related) { + if (reportErrors) { + reportError(ts.Diagnostics.Property_0_is_incompatible_with_rest_element_type, "" + i); + } + return 0 /* False */; + } + result &= related; + } + } + } + var properties = getPropertiesOfObjectType(target); + for (var _b = 0, properties_2 = properties; _b < properties_2.length; _b++) { + var targetProp = properties_2[_b]; + if (!(targetProp.flags & 4194304 /* Prototype */)) { + var sourceProp = getPropertyOfType(source, targetProp.escapedName); + if (sourceProp && sourceProp !== targetProp) { + if (isIgnoredJsxProperty(source, sourceProp, getTypeOfSymbol(targetProp))) { + continue; + } + var sourcePropFlags = ts.getDeclarationModifierFlagsFromSymbol(sourceProp); + var targetPropFlags = ts.getDeclarationModifierFlagsFromSymbol(targetProp); + if (sourcePropFlags & 8 /* Private */ || targetPropFlags & 8 /* Private */) { + var hasDifferingDeclarations = sourceProp.valueDeclaration !== targetProp.valueDeclaration; + if (ts.getCheckFlags(sourceProp) & 256 /* ContainsPrivate */ && hasDifferingDeclarations) { + if (reportErrors) { + reportError(ts.Diagnostics.Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1, symbolToString(sourceProp), typeToString(source)); + } + return 0 /* False */; + } + if (hasDifferingDeclarations) { + if (reportErrors) { + if (sourcePropFlags & 8 /* Private */ && targetPropFlags & 8 /* Private */) { + reportError(ts.Diagnostics.Types_have_separate_declarations_of_a_private_property_0, symbolToString(targetProp)); + } + else { + reportError(ts.Diagnostics.Property_0_is_private_in_type_1_but_not_in_type_2, symbolToString(targetProp), typeToString(sourcePropFlags & 8 /* Private */ ? source : target), typeToString(sourcePropFlags & 8 /* Private */ ? target : source)); + } + } + return 0 /* False */; + } + } + else if (targetPropFlags & 16 /* Protected */) { + if (!isValidOverrideOf(sourceProp, targetProp)) { + if (reportErrors) { + reportError(ts.Diagnostics.Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2, symbolToString(targetProp), typeToString(getDeclaringClass(sourceProp) || source), typeToString(getDeclaringClass(targetProp) || target)); + } + return 0 /* False */; + } + } + else if (sourcePropFlags & 16 /* Protected */) { + if (reportErrors) { + reportError(ts.Diagnostics.Property_0_is_protected_in_type_1_but_public_in_type_2, symbolToString(targetProp), typeToString(source), typeToString(target)); + } + return 0 /* False */; + } + var related = isRelatedTo(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp), reportErrors); + if (!related) { + if (reportErrors) { + reportError(ts.Diagnostics.Types_of_property_0_are_incompatible, symbolToString(targetProp)); + } + return 0 /* False */; + } + result &= related; + // When checking for comparability, be more lenient with optional properties. + if (relation !== comparableRelation && sourceProp.flags & 16777216 /* Optional */ && !(targetProp.flags & 16777216 /* Optional */)) { + // TypeScript 1.0 spec (April 2014): 3.8.3 + // S is a subtype of a type T, and T is a supertype of S if ... + // S' and T are object types and, for each member M in T.. + // M is a property and S' contains a property N where + // if M is a required property, N is also a required property + // (M - property in T) + // (N - property in S) + if (reportErrors) { + reportError(ts.Diagnostics.Property_0_is_optional_in_type_1_but_required_in_type_2, symbolToString(targetProp), typeToString(source), typeToString(target)); + } + return 0 /* False */; + } + } + } + } + return result; + } + function propertiesIdenticalTo(source, target) { + if (!(source.flags & 524288 /* Object */ && target.flags & 524288 /* Object */)) { + return 0 /* False */; + } + var sourceProperties = getPropertiesOfObjectType(source); + var targetProperties = getPropertiesOfObjectType(target); + if (sourceProperties.length !== targetProperties.length) { + return 0 /* False */; + } + var result = -1 /* True */; + for (var _i = 0, sourceProperties_1 = sourceProperties; _i < sourceProperties_1.length; _i++) { + var sourceProp = sourceProperties_1[_i]; + var targetProp = getPropertyOfObjectType(target, sourceProp.escapedName); + if (!targetProp) { + return 0 /* False */; + } + var related = compareProperties(sourceProp, targetProp, isRelatedTo); + if (!related) { + return 0 /* False */; + } + result &= related; + } + return result; + } + function signaturesRelatedTo(source, target, kind, reportErrors) { + if (relation === identityRelation) { + return signaturesIdenticalTo(source, target, kind); + } + if (target === anyFunctionType || source === anyFunctionType) { + return -1 /* True */; + } + var sourceIsJSConstructor = source.symbol && isJSConstructor(source.symbol.valueDeclaration); + var targetIsJSConstructor = target.symbol && isJSConstructor(target.symbol.valueDeclaration); + var sourceSignatures = getSignaturesOfType(source, (sourceIsJSConstructor && kind === 1 /* Construct */) ? + 0 /* Call */ : kind); + var targetSignatures = getSignaturesOfType(target, (targetIsJSConstructor && kind === 1 /* Construct */) ? + 0 /* Call */ : kind); + if (kind === 1 /* Construct */ && sourceSignatures.length && targetSignatures.length) { + if (ts.isAbstractConstructorType(source) && !ts.isAbstractConstructorType(target)) { + // An abstract constructor type is not assignable to a non-abstract constructor type + // as it would otherwise be possible to new an abstract class. Note that the assignability + // check we perform for an extends clause excludes construct signatures from the target, + // so this check never proceeds. + if (reportErrors) { + reportError(ts.Diagnostics.Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type); + } + return 0 /* False */; + } + if (!constructorVisibilitiesAreCompatible(sourceSignatures[0], targetSignatures[0], reportErrors)) { + return 0 /* False */; + } + } + var result = -1 /* True */; + var saveErrorInfo = errorInfo; + if (ts.getObjectFlags(source) & 64 /* Instantiated */ && ts.getObjectFlags(target) & 64 /* Instantiated */ && source.symbol === target.symbol) { + // We have instantiations of the same anonymous type (which typically will be the type of a + // method). Simply do a pairwise comparison of the signatures in the two signature lists instead + // of the much more expensive N * M comparison matrix we explore below. We erase type parameters + // as they are known to always be the same. + for (var i = 0; i < targetSignatures.length; i++) { + var related = signatureRelatedTo(sourceSignatures[i], targetSignatures[i], /*erase*/ true, reportErrors); + if (!related) { + return 0 /* False */; + } + result &= related; + } + } + else if (sourceSignatures.length === 1 && targetSignatures.length === 1) { + // For simple functions (functions with a single signature) we only erase type parameters for + // the comparable relation. Otherwise, if the source signature is generic, we instantiate it + // in the context of the target signature before checking the relationship. Ideally we'd do + // this regardless of the number of signatures, but the potential costs are prohibitive due + // to the quadratic nature of the logic below. + var eraseGenerics = relation === comparableRelation || !!compilerOptions.noStrictGenericChecks; + result = signatureRelatedTo(sourceSignatures[0], targetSignatures[0], eraseGenerics, reportErrors); + } + else { + outer: for (var _i = 0, targetSignatures_1 = targetSignatures; _i < targetSignatures_1.length; _i++) { + var t = targetSignatures_1[_i]; + // Only elaborate errors from the first failure + var shouldElaborateErrors = reportErrors; + for (var _a = 0, sourceSignatures_1 = sourceSignatures; _a < sourceSignatures_1.length; _a++) { + var s = sourceSignatures_1[_a]; + var related = signatureRelatedTo(s, t, /*erase*/ true, shouldElaborateErrors); + if (related) { + result &= related; + errorInfo = saveErrorInfo; + continue outer; + } + shouldElaborateErrors = false; + } + if (shouldElaborateErrors) { + reportError(ts.Diagnostics.Type_0_provides_no_match_for_the_signature_1, typeToString(source), signatureToString(t, /*enclosingDeclaration*/ undefined, /*flags*/ undefined, kind)); + } + return 0 /* False */; + } + } + return result; + } + /** + * See signatureAssignableTo, compareSignaturesIdentical + */ + function signatureRelatedTo(source, target, erase, reportErrors) { + return compareSignaturesRelated(erase ? getErasedSignature(source) : source, erase ? getErasedSignature(target) : target, 0 /* None */, /*ignoreReturnTypes*/ false, reportErrors, reportError, isRelatedTo); + } + function signaturesIdenticalTo(source, target, kind) { + var sourceSignatures = getSignaturesOfType(source, kind); + var targetSignatures = getSignaturesOfType(target, kind); + if (sourceSignatures.length !== targetSignatures.length) { + return 0 /* False */; + } + var result = -1 /* True */; + for (var i = 0; i < sourceSignatures.length; i++) { + var related = compareSignaturesIdentical(sourceSignatures[i], targetSignatures[i], /*partialMatch*/ false, /*ignoreThisTypes*/ false, /*ignoreReturnTypes*/ false, isRelatedTo); + if (!related) { + return 0 /* False */; + } + result &= related; + } + return result; + } + function eachPropertyRelatedTo(source, target, kind, reportErrors) { + var result = -1 /* True */; + for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) { + var prop = _a[_i]; + if (isIgnoredJsxProperty(source, prop, /*targetMemberType*/ undefined)) { + continue; + } + // Skip over symbol-named members + if (prop.nameType && prop.nameType.flags & 8192 /* UniqueESSymbol */) { + continue; + } + if (kind === 0 /* String */ || isNumericLiteralName(prop.escapedName)) { + var related = isRelatedTo(getTypeOfSymbol(prop), target, reportErrors); + if (!related) { + if (reportErrors) { + reportError(ts.Diagnostics.Property_0_is_incompatible_with_index_signature, symbolToString(prop)); + } + return 0 /* False */; + } + result &= related; + } + } + return result; + } + function indexInfoRelatedTo(sourceInfo, targetInfo, reportErrors) { + var related = isRelatedTo(sourceInfo.type, targetInfo.type, reportErrors); + if (!related && reportErrors) { + reportError(ts.Diagnostics.Index_signatures_are_incompatible); + } + return related; + } + function indexTypesRelatedTo(source, target, kind, sourceIsPrimitive, reportErrors) { + if (relation === identityRelation) { + return indexTypesIdenticalTo(source, target, kind); + } + var targetInfo = getIndexInfoOfType(target, kind); + if (!targetInfo || targetInfo.type.flags & 3 /* AnyOrUnknown */ && !sourceIsPrimitive) { + // Index signature of type any permits assignment from everything but primitives + return -1 /* True */; + } + var sourceInfo = getIndexInfoOfType(source, kind) || + kind === 1 /* Number */ && getIndexInfoOfType(source, 0 /* String */); + if (sourceInfo) { + return indexInfoRelatedTo(sourceInfo, targetInfo, reportErrors); + } + if (isGenericMappedType(source)) { + // A generic mapped type { [P in K]: T } is related to an index signature { [x: string]: U } + // if T is related to U. + return (kind === 0 /* String */ && isRelatedTo(getTemplateTypeFromMappedType(source), targetInfo.type, reportErrors)); // TODO: GH#18217 + } + if (isObjectTypeWithInferableIndex(source)) { + var related = -1 /* True */; + if (kind === 0 /* String */) { + var sourceNumberInfo = getIndexInfoOfType(source, 1 /* Number */); + if (sourceNumberInfo) { + related = indexInfoRelatedTo(sourceNumberInfo, targetInfo, reportErrors); + } + } + if (related) { + related &= eachPropertyRelatedTo(source, targetInfo.type, kind, reportErrors); + } + return related; + } + if (reportErrors) { + reportError(ts.Diagnostics.Index_signature_is_missing_in_type_0, typeToString(source)); + } + return 0 /* False */; + } + function indexTypesIdenticalTo(source, target, indexKind) { + var targetInfo = getIndexInfoOfType(target, indexKind); + var sourceInfo = getIndexInfoOfType(source, indexKind); + if (!sourceInfo && !targetInfo) { + return -1 /* True */; + } + if (sourceInfo && targetInfo && sourceInfo.isReadonly === targetInfo.isReadonly) { + return isRelatedTo(sourceInfo.type, targetInfo.type); + } + return 0 /* False */; + } + function constructorVisibilitiesAreCompatible(sourceSignature, targetSignature, reportErrors) { + if (!sourceSignature.declaration || !targetSignature.declaration) { + return true; + } + var sourceAccessibility = ts.getSelectedModifierFlags(sourceSignature.declaration, 24 /* NonPublicAccessibilityModifier */); + var targetAccessibility = ts.getSelectedModifierFlags(targetSignature.declaration, 24 /* NonPublicAccessibilityModifier */); + // A public, protected and private signature is assignable to a private signature. + if (targetAccessibility === 8 /* Private */) { + return true; + } + // A public and protected signature is assignable to a protected signature. + if (targetAccessibility === 16 /* Protected */ && sourceAccessibility !== 8 /* Private */) { + return true; + } + // Only a public signature is assignable to public signature. + if (targetAccessibility !== 16 /* Protected */ && !sourceAccessibility) { + return true; + } + if (reportErrors) { + reportError(ts.Diagnostics.Cannot_assign_a_0_constructor_type_to_a_1_constructor_type, visibilityToString(sourceAccessibility), visibilityToString(targetAccessibility)); + } + return false; + } + } + function discriminateTypeByDiscriminableItems(target, discriminators, related, defaultValue) { + var match; + for (var _i = 0, discriminators_1 = discriminators; _i < discriminators_1.length; _i++) { + var _a = discriminators_1[_i], getDiscriminatingType = _a[0], propertyName = _a[1]; + for (var _b = 0, _c = target.types; _b < _c.length; _b++) { + var type = _c[_b]; + var targetType = getTypeOfPropertyOfType(type, propertyName); + if (targetType && related(getDiscriminatingType(), targetType)) { + if (match) { + if (type === match) + continue; // Finding multiple fields which discriminate to the same type is fine + return defaultValue; + } + match = type; + } + } + } + return match || defaultValue; + } + /** + * A type is 'weak' if it is an object type with at least one optional property + * and no required properties, call/construct signatures or index signatures + */ + function isWeakType(type) { + if (type.flags & 524288 /* Object */) { + var resolved = resolveStructuredTypeMembers(type); + return resolved.callSignatures.length === 0 && resolved.constructSignatures.length === 0 && + !resolved.stringIndexInfo && !resolved.numberIndexInfo && + resolved.properties.length > 0 && + ts.every(resolved.properties, function (p) { return !!(p.flags & 16777216 /* Optional */); }); + } + if (type.flags & 2097152 /* Intersection */) { + return ts.every(type.types, isWeakType); + } + return false; + } + function hasCommonProperties(source, target, isComparingJsxAttributes) { + for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) { + var prop = _a[_i]; + if (isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { + return true; + } + } + return false; + } + // Return a type reference where the source type parameter is replaced with the target marker + // type, and flag the result as a marker type reference. + function getMarkerTypeReference(type, source, target) { + var result = createTypeReference(type, ts.map(type.typeParameters, function (t) { return t === source ? target : t; })); + result.objectFlags |= 8192 /* MarkerType */; + return result; + } + function getAliasVariances(symbol) { + var links = getSymbolLinks(symbol); + return getVariancesWorker(links.typeParameters, links, function (_links, param, marker) { + var type = getTypeAliasInstantiation(symbol, instantiateTypes(links.typeParameters, makeUnaryTypeMapper(param, marker))); + type.aliasTypeArgumentsContainsMarker = true; + return type; + }); + } + // Return an array containing the variance of each type parameter. The variance is effectively + // a digest of the type comparisons that occur for each type argument when instantiations of the + // generic type are structurally compared. We infer the variance information by comparing + // instantiations of the generic type for type arguments with known relations. The function + // returns the emptyArray singleton if we're not in strictFunctionTypes mode or if the function + // has been invoked recursively for the given generic type. + function getVariancesWorker(typeParameters, cache, createMarkerType) { + if (typeParameters === void 0) { typeParameters = ts.emptyArray; } + var variances = cache.variances; + if (!variances) { + // The emptyArray singleton is used to signal a recursive invocation. + cache.variances = ts.emptyArray; + variances = []; + for (var _i = 0, typeParameters_1 = typeParameters; _i < typeParameters_1.length; _i++) { + var tp = typeParameters_1[_i]; + // We first compare instantiations where the type parameter is replaced with + // marker types that have a known subtype relationship. From this we can infer + // invariance, covariance, contravariance or bivariance. + var typeWithSuper = createMarkerType(cache, tp, markerSuperType); + var typeWithSub = createMarkerType(cache, tp, markerSubType); + var variance = (isTypeAssignableTo(typeWithSub, typeWithSuper) ? 1 /* Covariant */ : 0) | + (isTypeAssignableTo(typeWithSuper, typeWithSub) ? 2 /* Contravariant */ : 0); + // If the instantiations appear to be related bivariantly it may be because the + // type parameter is independent (i.e. it isn't witnessed anywhere in the generic + // type). To determine this we compare instantiations where the type parameter is + // replaced with marker types that are known to be unrelated. + if (variance === 3 /* Bivariant */ && isTypeAssignableTo(createMarkerType(cache, tp, markerOtherType), typeWithSuper)) { + variance = 4 /* Independent */; + } + variances.push(variance); + } + cache.variances = variances; + } + return variances; + } + function getVariances(type) { + if (!strictFunctionTypes) { + return ts.emptyArray; + } + if (type === globalArrayType || type === globalReadonlyArrayType) { + // Arrays are known to be covariant, no need to spend time computing this (emptyArray implies covariance for all parameters) + return ts.emptyArray; + } + return getVariancesWorker(type.typeParameters, type, getMarkerTypeReference); + } + // Return true if the given type reference has a 'void' type argument for a covariant type parameter. + // See comment at call in recursiveTypeRelatedTo for when this case matters. + function hasCovariantVoidArgument(type, variances) { + for (var i = 0; i < variances.length; i++) { + if (variances[i] === 1 /* Covariant */ && type.typeArguments[i].flags & 16384 /* Void */) { + return true; + } + } + return false; + } + function isUnconstrainedTypeParameter(type) { + return type.flags & 262144 /* TypeParameter */ && !getConstraintOfTypeParameter(type); + } + function isTypeReferenceWithGenericArguments(type) { + return !!(ts.getObjectFlags(type) & 4 /* Reference */) && ts.some(type.typeArguments, function (t) { return isUnconstrainedTypeParameter(t) || isTypeReferenceWithGenericArguments(t); }); + } + /** + * getTypeReferenceId(A) returns "111=0-12=1" + * where A.id=111 and number.id=12 + */ + function getTypeReferenceId(type, typeParameters, depth) { + if (depth === void 0) { depth = 0; } + var result = "" + type.target.id; + for (var _i = 0, _a = type.typeArguments; _i < _a.length; _i++) { + var t = _a[_i]; + if (isUnconstrainedTypeParameter(t)) { + var index = typeParameters.indexOf(t); + if (index < 0) { + index = typeParameters.length; + typeParameters.push(t); + } + result += "=" + index; + } + else if (depth < 4 && isTypeReferenceWithGenericArguments(t)) { + result += "<" + getTypeReferenceId(t, typeParameters, depth + 1) + ">"; + } + else { + result += "-" + t.id; + } + } + return result; + } + /** + * To improve caching, the relation key for two generic types uses the target's id plus ids of the type parameters. + * For other cases, the types ids are used. + */ + function getRelationKey(source, target, relation) { + if (relation === identityRelation && source.id > target.id) { + var temp = source; + source = target; + target = temp; + } + if (isTypeReferenceWithGenericArguments(source) && isTypeReferenceWithGenericArguments(target)) { + var typeParameters = []; + return getTypeReferenceId(source, typeParameters) + "," + getTypeReferenceId(target, typeParameters); + } + return source.id + "," + target.id; + } + // Invoke the callback for each underlying property symbol of the given symbol and return the first + // value that isn't undefined. + function forEachProperty(prop, callback) { + if (ts.getCheckFlags(prop) & 6 /* Synthetic */) { + for (var _i = 0, _a = prop.containingType.types; _i < _a.length; _i++) { + var t = _a[_i]; + var p = getPropertyOfType(t, prop.escapedName); + var result = p && forEachProperty(p, callback); + if (result) { + return result; + } + } + return undefined; + } + return callback(prop); + } + // Return the declaring class type of a property or undefined if property not declared in class + function getDeclaringClass(prop) { + return prop.parent && prop.parent.flags & 32 /* Class */ ? getDeclaredTypeOfSymbol(getParentOfSymbol(prop)) : undefined; + } + // Return true if some underlying source property is declared in a class that derives + // from the given base class. + function isPropertyInClassDerivedFrom(prop, baseClass) { + return forEachProperty(prop, function (sp) { + var sourceClass = getDeclaringClass(sp); + return sourceClass ? hasBaseType(sourceClass, baseClass) : false; + }); + } + // Return true if source property is a valid override of protected parts of target property. + function isValidOverrideOf(sourceProp, targetProp) { + return !forEachProperty(targetProp, function (tp) { return ts.getDeclarationModifierFlagsFromSymbol(tp) & 16 /* Protected */ ? + !isPropertyInClassDerivedFrom(sourceProp, getDeclaringClass(tp)) : false; }); + } + // Return true if the given class derives from each of the declaring classes of the protected + // constituents of the given property. + function isClassDerivedFromDeclaringClasses(checkClass, prop) { + return forEachProperty(prop, function (p) { return ts.getDeclarationModifierFlagsFromSymbol(p) & 16 /* Protected */ ? + !hasBaseType(checkClass, getDeclaringClass(p)) : false; }) ? undefined : checkClass; + } + // Return true if the given type is deeply nested. We consider this to be the case when structural type comparisons + // for 5 or more occurrences or instantiations of the type have been recorded on the given stack. It is possible, + // though highly unlikely, for this test to be true in a situation where a chain of instantiations is not infinitely + // expanding. Effectively, we will generate a false positive when two types are structurally equal to at least 5 + // levels, but unequal at some level beyond that. + function isDeeplyNestedType(type, stack, depth) { + // We track all object types that have an associated symbol (representing the origin of the type) + if (depth >= 5 && type.flags & 524288 /* Object */) { + var symbol = type.symbol; + if (symbol) { + var count = 0; + for (var i = 0; i < depth; i++) { + var t = stack[i]; + if (t.flags & 524288 /* Object */ && t.symbol === symbol) { + count++; + if (count >= 5) + return true; + } + } + } + } + return false; + } + function isPropertyIdenticalTo(sourceProp, targetProp) { + return compareProperties(sourceProp, targetProp, compareTypesIdentical) !== 0 /* False */; + } + function compareProperties(sourceProp, targetProp, compareTypes) { + // Two members are considered identical when + // - they are public properties with identical names, optionality, and types, + // - they are private or protected properties originating in the same declaration and having identical types + if (sourceProp === targetProp) { + return -1 /* True */; + } + var sourcePropAccessibility = ts.getDeclarationModifierFlagsFromSymbol(sourceProp) & 24 /* NonPublicAccessibilityModifier */; + var targetPropAccessibility = ts.getDeclarationModifierFlagsFromSymbol(targetProp) & 24 /* NonPublicAccessibilityModifier */; + if (sourcePropAccessibility !== targetPropAccessibility) { + return 0 /* False */; + } + if (sourcePropAccessibility) { + if (getTargetSymbol(sourceProp) !== getTargetSymbol(targetProp)) { + return 0 /* False */; + } + } + else { + if ((sourceProp.flags & 16777216 /* Optional */) !== (targetProp.flags & 16777216 /* Optional */)) { + return 0 /* False */; + } + } + if (isReadonlySymbol(sourceProp) !== isReadonlySymbol(targetProp)) { + return 0 /* False */; + } + return compareTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); + } + function isMatchingSignature(source, target, partialMatch) { + var sourceParameterCount = getParameterCount(source); + var targetParameterCount = getParameterCount(target); + var sourceMinArgumentCount = getMinArgumentCount(source); + var targetMinArgumentCount = getMinArgumentCount(target); + var sourceHasRestParameter = hasEffectiveRestParameter(source); + var targetHasRestParameter = hasEffectiveRestParameter(target); + // A source signature matches a target signature if the two signatures have the same number of required, + // optional, and rest parameters. + if (sourceParameterCount === targetParameterCount && + sourceMinArgumentCount === targetMinArgumentCount && + sourceHasRestParameter === targetHasRestParameter) { + return true; + } + // A source signature partially matches a target signature if the target signature has no fewer required + // parameters + if (partialMatch && sourceMinArgumentCount <= targetMinArgumentCount) { + return true; + } + return false; + } + /** + * See signatureRelatedTo, compareSignaturesIdentical + */ + function compareSignaturesIdentical(source, target, partialMatch, ignoreThisTypes, ignoreReturnTypes, compareTypes) { + // TODO (drosen): De-duplicate code between related functions. + if (source === target) { + return -1 /* True */; + } + if (!(isMatchingSignature(source, target, partialMatch))) { + return 0 /* False */; + } + // Check that the two signatures have the same number of type parameters. We might consider + // also checking that any type parameter constraints match, but that would require instantiating + // the constraints with a common set of type arguments to get relatable entities in places where + // type parameters occur in the constraints. The complexity of doing that doesn't seem worthwhile, + // particularly as we're comparing erased versions of the signatures below. + if (ts.length(source.typeParameters) !== ts.length(target.typeParameters)) { + return 0 /* False */; + } + // Spec 1.0 Section 3.8.3 & 3.8.4: + // M and N (the signatures) are instantiated using type Any as the type argument for all type parameters declared by M and N + source = getErasedSignature(source); + target = getErasedSignature(target); + var result = -1 /* True */; + if (!ignoreThisTypes) { + var sourceThisType = getThisTypeOfSignature(source); + if (sourceThisType) { + var targetThisType = getThisTypeOfSignature(target); + if (targetThisType) { + var related = compareTypes(sourceThisType, targetThisType); + if (!related) { + return 0 /* False */; + } + result &= related; + } + } + } + var targetLen = getParameterCount(target); + for (var i = 0; i < targetLen; i++) { + var s = getTypeAtPosition(source, i); + var t = getTypeAtPosition(target, i); + var related = compareTypes(t, s); + if (!related) { + return 0 /* False */; + } + result &= related; + } + if (!ignoreReturnTypes) { + var sourceTypePredicate = getTypePredicateOfSignature(source); + var targetTypePredicate = getTypePredicateOfSignature(target); + result &= sourceTypePredicate !== undefined || targetTypePredicate !== undefined + ? compareTypePredicatesIdentical(sourceTypePredicate, targetTypePredicate, compareTypes) + // If they're both type predicates their return types will both be `boolean`, so no need to compare those. + : compareTypes(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target)); + } + return result; + } + function compareTypePredicatesIdentical(source, target, compareTypes) { + return source === undefined || target === undefined || !typePredicateKindsMatch(source, target) ? 0 /* False */ : compareTypes(source.type, target.type); + } + function literalTypesWithSameBaseType(types) { + var commonBaseType; + for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { + var t = types_8[_i]; + var baseType = getBaseTypeOfLiteralType(t); + if (!commonBaseType) { + commonBaseType = baseType; + } + if (baseType === t || baseType !== commonBaseType) { + return false; + } + } + return true; + } + // When the candidate types are all literal types with the same base type, return a union + // of those literal types. Otherwise, return the leftmost type for which no type to the + // right is a supertype. + function getSupertypeOrUnion(types) { + return literalTypesWithSameBaseType(types) ? + getUnionType(types) : + ts.reduceLeft(types, function (s, t) { return isTypeSubtypeOf(s, t) ? t : s; }); + } + function getCommonSupertype(types) { + if (!strictNullChecks) { + return getSupertypeOrUnion(types); + } + var primaryTypes = ts.filter(types, function (t) { return !(t.flags & 98304 /* Nullable */); }); + return primaryTypes.length ? + getNullableType(getSupertypeOrUnion(primaryTypes), getFalsyFlagsOfTypes(types) & 98304 /* Nullable */) : + getUnionType(types, 2 /* Subtype */); + } + // Return the leftmost type for which no type to the right is a subtype. + function getCommonSubtype(types) { + return ts.reduceLeft(types, function (s, t) { return isTypeSubtypeOf(t, s) ? t : s; }); + } + function isArrayType(type) { + return !!(ts.getObjectFlags(type) & 4 /* Reference */) && type.target === globalArrayType; + } + function isReadonlyArrayType(type) { + return !!(ts.getObjectFlags(type) & 4 /* Reference */) && type.target === globalReadonlyArrayType; + } + function getElementTypeOfArrayType(type) { + return isArrayType(type) && type.typeArguments ? type.typeArguments[0] : undefined; + } + function isArrayLikeType(type) { + // A type is array-like if it is a reference to the global Array or global ReadonlyArray type, + // or if it is not the undefined or null type and if it is assignable to ReadonlyArray + return ts.getObjectFlags(type) & 4 /* Reference */ && (type.target === globalArrayType || type.target === globalReadonlyArrayType) || + !(type.flags & 98304 /* Nullable */) && isTypeAssignableTo(type, anyReadonlyArrayType); + } + function isEmptyArrayLiteralType(type) { + var elementType = isArrayType(type) ? type.typeArguments[0] : undefined; + return elementType === undefinedWideningType || elementType === implicitNeverType; + } + function isTupleLikeType(type) { + return isTupleType(type) || !!getPropertyOfType(type, "0"); + } + function getTupleElementType(type, index) { + var propType = getTypeOfPropertyOfType(type, "" + index); + if (propType) { + return propType; + } + if (everyType(type, isTupleType) && !everyType(type, function (t) { return !t.target.hasRestElement; })) { + return mapType(type, function (t) { return getRestTypeOfTupleType(t) || undefinedType; }); + } + return undefined; + } + function isNeitherUnitTypeNorNever(type) { + return !(type.flags & (109440 /* Unit */ | 131072 /* Never */)); + } + function isUnitType(type) { + return !!(type.flags & 109440 /* Unit */); + } + function isLiteralType(type) { + return type.flags & 16 /* Boolean */ ? true : + type.flags & 1048576 /* Union */ ? type.flags & 1024 /* EnumLiteral */ ? true : ts.every(type.types, isUnitType) : + isUnitType(type); + } + function getBaseTypeOfLiteralType(type) { + return type.flags & 1024 /* EnumLiteral */ ? getBaseTypeOfEnumLiteralType(type) : + type.flags & 128 /* StringLiteral */ ? stringType : + type.flags & 256 /* NumberLiteral */ ? numberType : + type.flags & 2048 /* BigIntLiteral */ ? bigintType : + type.flags & 512 /* BooleanLiteral */ ? booleanType : + type.flags & 1048576 /* Union */ ? getUnionType(ts.sameMap(type.types, getBaseTypeOfLiteralType)) : + type; + } + function getWidenedLiteralType(type) { + return type.flags & 1024 /* EnumLiteral */ && isFreshLiteralType(type) ? getBaseTypeOfEnumLiteralType(type) : + type.flags & 128 /* StringLiteral */ && isFreshLiteralType(type) ? stringType : + type.flags & 256 /* NumberLiteral */ && isFreshLiteralType(type) ? numberType : + type.flags & 2048 /* BigIntLiteral */ && isFreshLiteralType(type) ? bigintType : + type.flags & 512 /* BooleanLiteral */ && isFreshLiteralType(type) ? booleanType : + type.flags & 1048576 /* Union */ ? getUnionType(ts.sameMap(type.types, getWidenedLiteralType)) : + type; + } + function getWidenedUniqueESSymbolType(type) { + return type.flags & 8192 /* UniqueESSymbol */ ? esSymbolType : + type.flags & 1048576 /* Union */ ? getUnionType(ts.sameMap(type.types, getWidenedUniqueESSymbolType)) : + type; + } + function getWidenedLiteralLikeTypeForContextualType(type, contextualType) { + if (!isLiteralOfContextualType(type, contextualType)) { + type = getWidenedUniqueESSymbolType(getWidenedLiteralType(type)); + } + return type; + } + /** + * Check if a Type was written as a tuple type literal. + * Prefer using isTupleLikeType() unless the use of `elementTypes` is required. + */ + function isTupleType(type) { + return !!(ts.getObjectFlags(type) & 4 /* Reference */ && type.target.objectFlags & 8 /* Tuple */); + } + function getRestTypeOfTupleType(type) { + return type.target.hasRestElement ? type.typeArguments[type.target.typeParameters.length - 1] : undefined; + } + function getRestArrayTypeOfTupleType(type) { + var restType = getRestTypeOfTupleType(type); + return restType && createArrayType(restType); + } + function getLengthOfTupleType(type) { + return getTypeReferenceArity(type) - (type.target.hasRestElement ? 1 : 0); + } + function isZeroBigInt(_a) { + var value = _a.value; + return value.base10Value === "0"; + } + function getFalsyFlagsOfTypes(types) { + var result = 0; + for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { + var t = types_9[_i]; + result |= getFalsyFlags(t); + } + return result; + } + // Returns the String, Number, Boolean, StringLiteral, NumberLiteral, BooleanLiteral, Void, Undefined, or Null + // flags for the string, number, boolean, "", 0, false, void, undefined, or null types respectively. Returns + // no flags for all other types (including non-falsy literal types). + function getFalsyFlags(type) { + return type.flags & 1048576 /* Union */ ? getFalsyFlagsOfTypes(type.types) : + type.flags & 128 /* StringLiteral */ ? type.value === "" ? 128 /* StringLiteral */ : 0 : + type.flags & 256 /* NumberLiteral */ ? type.value === 0 ? 256 /* NumberLiteral */ : 0 : + type.flags & 2048 /* BigIntLiteral */ ? isZeroBigInt(type) ? 2048 /* BigIntLiteral */ : 0 : + type.flags & 512 /* BooleanLiteral */ ? (type === falseType || type === regularFalseType) ? 512 /* BooleanLiteral */ : 0 : + type.flags & 117724 /* PossiblyFalsy */; + } + function removeDefinitelyFalsyTypes(type) { + return getFalsyFlags(type) & 117632 /* DefinitelyFalsy */ ? + filterType(type, function (t) { return !(getFalsyFlags(t) & 117632 /* DefinitelyFalsy */); }) : + type; + } + function extractDefinitelyFalsyTypes(type) { + return mapType(type, getDefinitelyFalsyPartOfType); + } + function getDefinitelyFalsyPartOfType(type) { + return type.flags & 4 /* String */ ? emptyStringType : + type.flags & 8 /* Number */ ? zeroType : + type.flags & 64 /* BigInt */ ? zeroBigIntType : + type === regularFalseType || + type === falseType || + type.flags & (16384 /* Void */ | 32768 /* Undefined */ | 65536 /* Null */) || + type.flags & 128 /* StringLiteral */ && type.value === "" || + type.flags & 256 /* NumberLiteral */ && type.value === 0 || + type.flags & 2048 /* BigIntLiteral */ && isZeroBigInt(type) ? type : + neverType; + } + /** + * Add undefined or null or both to a type if they are missing. + * @param type - type to add undefined and/or null to if not present + * @param flags - Either TypeFlags.Undefined or TypeFlags.Null, or both + */ + function getNullableType(type, flags) { + var missing = (flags & ~type.flags) & (32768 /* Undefined */ | 65536 /* Null */); + return missing === 0 ? type : + missing === 32768 /* Undefined */ ? getUnionType([type, undefinedType]) : + missing === 65536 /* Null */ ? getUnionType([type, nullType]) : + getUnionType([type, undefinedType, nullType]); + } + function getOptionalType(type) { + ts.Debug.assert(strictNullChecks); + return type.flags & 32768 /* Undefined */ ? type : getUnionType([type, undefinedType]); + } + function getGlobalNonNullableTypeInstantiation(type) { + if (!deferredGlobalNonNullableTypeAlias) { + deferredGlobalNonNullableTypeAlias = getGlobalSymbol("NonNullable", 524288 /* TypeAlias */, /*diagnostic*/ undefined) || unknownSymbol; + } + // Use NonNullable global type alias if available to improve quick info/declaration emit + if (deferredGlobalNonNullableTypeAlias !== unknownSymbol) { + return getTypeAliasInstantiation(deferredGlobalNonNullableTypeAlias, [type]); + } + return getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */); // Type alias unavailable, fall back to non-higher-order behavior + } + function getNonNullableType(type) { + return strictNullChecks ? getGlobalNonNullableTypeInstantiation(type) : type; + } + /** + * Return true if type was inferred from an object literal, written as an object type literal, or is the shape of a module + * with no call or construct signatures. + */ + function isObjectTypeWithInferableIndex(type) { + return type.symbol && (type.symbol.flags & (4096 /* ObjectLiteral */ | 2048 /* TypeLiteral */ | 512 /* ValueModule */)) !== 0 && + !typeHasCallOrConstructSignatures(type); + } + function createSymbolWithType(source, type) { + var symbol = createSymbol(source.flags, source.escapedName); + symbol.declarations = source.declarations; + symbol.parent = source.parent; + symbol.type = type; + symbol.target = source; + if (source.valueDeclaration) { + symbol.valueDeclaration = source.valueDeclaration; + } + if (source.nameType) { + symbol.nameType = source.nameType; + } + return symbol; + } + function transformTypeOfMembers(type, f) { + var members = ts.createSymbolTable(); + for (var _i = 0, _a = getPropertiesOfObjectType(type); _i < _a.length; _i++) { + var property = _a[_i]; + var original = getTypeOfSymbol(property); + var updated = f(original); + members.set(property.escapedName, updated === original ? property : createSymbolWithType(property, updated)); + } + return members; + } + /** + * If the the provided object literal is subject to the excess properties check, + * create a new that is exempt. Recursively mark object literal members as exempt. + * Leave signatures alone since they are not subject to the check. + */ + function getRegularTypeOfObjectLiteral(type) { + if (!(isObjectLiteralType(type) && ts.getObjectFlags(type) & 32768 /* FreshLiteral */)) { + return type; + } + var regularType = type.regularType; + if (regularType) { + return regularType; + } + var resolved = type; + var members = transformTypeOfMembers(type, getRegularTypeOfObjectLiteral); + var regularNew = createAnonymousType(resolved.symbol, members, resolved.callSignatures, resolved.constructSignatures, resolved.stringIndexInfo, resolved.numberIndexInfo); + regularNew.flags = resolved.flags; + regularNew.objectFlags |= 128 /* ObjectLiteral */ | (ts.getObjectFlags(resolved) & 16384 /* JSLiteral */); + type.regularType = regularNew; + return regularNew; + } + function createWideningContext(parent, propertyName, siblings) { + return { parent: parent, propertyName: propertyName, siblings: siblings, resolvedProperties: undefined }; + } + function getSiblingsOfContext(context) { + if (!context.siblings) { + var siblings_1 = []; + for (var _i = 0, _a = getSiblingsOfContext(context.parent); _i < _a.length; _i++) { + var type = _a[_i]; + if (isObjectLiteralType(type)) { + var prop = getPropertyOfObjectType(type, context.propertyName); + if (prop) { + forEachType(getTypeOfSymbol(prop), function (t) { + siblings_1.push(t); + }); + } + } + } + context.siblings = siblings_1; + } + return context.siblings; + } + function getPropertiesOfContext(context) { + if (!context.resolvedProperties) { + var names = ts.createMap(); + for (var _i = 0, _a = getSiblingsOfContext(context); _i < _a.length; _i++) { + var t = _a[_i]; + if (isObjectLiteralType(t) && !(ts.getObjectFlags(t) & 1024 /* ContainsSpread */)) { + for (var _b = 0, _c = getPropertiesOfType(t); _b < _c.length; _b++) { + var prop = _c[_b]; + names.set(prop.escapedName, prop); + } + } + } + context.resolvedProperties = ts.arrayFrom(names.values()); + } + return context.resolvedProperties; + } + function getWidenedProperty(prop, context) { + if (!(prop.flags & 4 /* Property */)) { + // Since get accessors already widen their return value there is no need to + // widen accessor based properties here. + return prop; + } + var original = getTypeOfSymbol(prop); + var propContext = context && createWideningContext(context, prop.escapedName, /*siblings*/ undefined); + var widened = getWidenedTypeWithContext(original, propContext); + return widened === original ? prop : createSymbolWithType(prop, widened); + } + function getUndefinedProperty(prop) { + var cached = undefinedProperties.get(prop.escapedName); + if (cached) { + return cached; + } + var result = createSymbolWithType(prop, undefinedType); + result.flags |= 16777216 /* Optional */; + undefinedProperties.set(prop.escapedName, result); + return result; + } + function getWidenedTypeOfObjectLiteral(type, context) { + var members = ts.createSymbolTable(); + for (var _i = 0, _a = getPropertiesOfObjectType(type); _i < _a.length; _i++) { + var prop = _a[_i]; + members.set(prop.escapedName, getWidenedProperty(prop, context)); + } + if (context) { + for (var _b = 0, _c = getPropertiesOfContext(context); _b < _c.length; _b++) { + var prop = _c[_b]; + if (!members.has(prop.escapedName)) { + members.set(prop.escapedName, getUndefinedProperty(prop)); + } + } + } + var stringIndexInfo = getIndexInfoOfType(type, 0 /* String */); + var numberIndexInfo = getIndexInfoOfType(type, 1 /* Number */); + var result = createAnonymousType(type.symbol, members, ts.emptyArray, ts.emptyArray, stringIndexInfo && createIndexInfo(getWidenedType(stringIndexInfo.type), stringIndexInfo.isReadonly), numberIndexInfo && createIndexInfo(getWidenedType(numberIndexInfo.type), numberIndexInfo.isReadonly)); + result.objectFlags |= (ts.getObjectFlags(type) & 16384 /* JSLiteral */); // Retain js literal flag through widening + return result; + } + function getWidenedType(type) { + return getWidenedTypeWithContext(type, /*context*/ undefined); + } + function getWidenedTypeWithContext(type, context) { + if (type.flags & 402653184 /* RequiresWidening */) { + if (type.flags & 98304 /* Nullable */) { + return anyType; + } + if (isObjectLiteralType(type)) { + return getWidenedTypeOfObjectLiteral(type, context); + } + if (type.flags & 1048576 /* Union */) { + var unionContext_1 = context || createWideningContext(/*parent*/ undefined, /*propertyName*/ undefined, type.types); + var widenedTypes = ts.sameMap(type.types, function (t) { return t.flags & 98304 /* Nullable */ ? t : getWidenedTypeWithContext(t, unionContext_1); }); + // Widening an empty object literal transitions from a highly restrictive type to + // a highly inclusive one. For that reason we perform subtype reduction here if the + // union includes empty object types (e.g. reducing {} | string to just {}). + return getUnionType(widenedTypes, ts.some(widenedTypes, isEmptyObjectType) ? 2 /* Subtype */ : 1 /* Literal */); + } + if (isArrayType(type) || isTupleType(type)) { + return createTypeReference(type.target, ts.sameMap(type.typeArguments, getWidenedType)); + } + } + return type; + } + /** + * Reports implicit any errors that occur as a result of widening 'null' and 'undefined' + * to 'any'. A call to reportWideningErrorsInType is normally accompanied by a call to + * getWidenedType. But in some cases getWidenedType is called without reporting errors + * (type argument inference is an example). + * + * The return value indicates whether an error was in fact reported. The particular circumstances + * are on a best effort basis. Currently, if the null or undefined that causes widening is inside + * an object literal property (arbitrarily deeply), this function reports an error. If no error is + * reported, reportImplicitAnyError is a suitable fallback to report a general error. + */ + function reportWideningErrorsInType(type) { + var errorReported = false; + if (type.flags & 134217728 /* ContainsWideningType */) { + if (type.flags & 1048576 /* Union */) { + if (ts.some(type.types, isEmptyObjectType)) { + errorReported = true; + } + else { + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (reportWideningErrorsInType(t)) { + errorReported = true; + } + } + } + } + if (isArrayType(type) || isTupleType(type)) { + for (var _b = 0, _c = type.typeArguments; _b < _c.length; _b++) { + var t = _c[_b]; + if (reportWideningErrorsInType(t)) { + errorReported = true; + } + } + } + if (isObjectLiteralType(type)) { + for (var _d = 0, _e = getPropertiesOfObjectType(type); _d < _e.length; _d++) { + var p = _e[_d]; + var t = getTypeOfSymbol(p); + if (t.flags & 134217728 /* ContainsWideningType */) { + if (!reportWideningErrorsInType(t)) { + error(p.valueDeclaration, ts.Diagnostics.Object_literal_s_property_0_implicitly_has_an_1_type, symbolToString(p), typeToString(getWidenedType(t))); + } + errorReported = true; + } + } + } + } + return errorReported; + } + function reportImplicitAny(declaration, type) { + var typeAsString = typeToString(getWidenedType(type)); + if (ts.isInJSFile(declaration) && !ts.isCheckJsEnabledForFile(ts.getSourceFileOfNode(declaration), compilerOptions)) { + // Only report implicit any errors/suggestions in TS and ts-check JS files + return; + } + var diagnostic; + switch (declaration.kind) { + case 204 /* BinaryExpression */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + diagnostic = noImplicitAny ? ts.Diagnostics.Member_0_implicitly_has_an_1_type : ts.Diagnostics.Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage; + break; + case 151 /* Parameter */: + var param = declaration; + if (ts.isIdentifier(param.name) && + (ts.isCallSignatureDeclaration(param.parent) || ts.isMethodSignature(param.parent) || ts.isFunctionTypeNode(param.parent)) && + param.parent.parameters.indexOf(param) > -1 && + (resolveName(param, param.name.escapedText, 67897832 /* Type */, undefined, param.name.escapedText, /*isUse*/ true) || + param.name.originalKeywordKind && ts.isTypeNodeKind(param.name.originalKeywordKind))) { + var newName = "arg" + param.parent.parameters.indexOf(param); + errorOrSuggestion(noImplicitAny, declaration, ts.Diagnostics.Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1, newName, ts.declarationNameToString(param.name)); + return; + } + diagnostic = declaration.dotDotDotToken ? + noImplicitAny ? ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type : ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage : + noImplicitAny ? ts.Diagnostics.Parameter_0_implicitly_has_an_1_type : ts.Diagnostics.Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage; + break; + case 186 /* BindingElement */: + diagnostic = ts.Diagnostics.Binding_element_0_implicitly_has_an_1_type; + break; + case 289 /* JSDocFunctionType */: + error(declaration, ts.Diagnostics.Function_type_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString); + return; + case 239 /* FunctionDeclaration */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + if (noImplicitAny && !declaration.name) { + error(declaration, ts.Diagnostics.Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString); + return; + } + diagnostic = noImplicitAny ? ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type : ts.Diagnostics._0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage; + break; + case 181 /* MappedType */: + if (noImplicitAny) { + error(declaration, ts.Diagnostics.Mapped_object_type_implicitly_has_an_any_template_type); + } + return; + default: + diagnostic = noImplicitAny ? ts.Diagnostics.Variable_0_implicitly_has_an_1_type : ts.Diagnostics.Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage; + } + errorOrSuggestion(noImplicitAny, declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString); + } + function reportErrorsFromWidening(declaration, type) { + if (produceDiagnostics && noImplicitAny && type.flags & 134217728 /* ContainsWideningType */) { + // Report implicit any error within type if possible, otherwise report error on declaration + if (!reportWideningErrorsInType(type)) { + reportImplicitAny(declaration, type); + } + } + } + function forEachMatchingParameterType(source, target, callback) { + var sourceCount = getParameterCount(source); + var targetCount = getParameterCount(target); + var sourceRestType = getEffectiveRestType(source); + var targetRestType = getEffectiveRestType(target); + var targetNonRestCount = targetRestType ? targetCount - 1 : targetCount; + var paramCount = sourceRestType ? targetNonRestCount : Math.min(sourceCount, targetNonRestCount); + var sourceThisType = getThisTypeOfSignature(source); + if (sourceThisType) { + var targetThisType = getThisTypeOfSignature(target); + if (targetThisType) { + callback(sourceThisType, targetThisType); + } + } + for (var i = 0; i < paramCount; i++) { + callback(getTypeAtPosition(source, i), getTypeAtPosition(target, i)); + } + if (targetRestType) { + callback(getRestTypeAtPosition(source, paramCount), targetRestType); + } + } + function createInferenceContext(typeParameters, signature, flags, compareTypes, baseInferences) { + var inferences = baseInferences ? baseInferences.map(cloneInferenceInfo) : typeParameters.map(createInferenceInfo); + var context = mapper; + context.typeParameters = typeParameters; + context.signature = signature; + context.inferences = inferences; + context.flags = flags; + context.compareTypes = compareTypes || compareTypesAssignable; + return context; + function mapper(t) { + for (var i = 0; i < inferences.length; i++) { + if (t === inferences[i].typeParameter) { + inferences[i].isFixed = true; + return getInferredType(context, i); + } + } + return t; + } + } + function createInferenceInfo(typeParameter) { + return { + typeParameter: typeParameter, + candidates: undefined, + contraCandidates: undefined, + inferredType: undefined, + priority: undefined, + topLevel: true, + isFixed: false + }; + } + function cloneInferenceInfo(inference) { + return { + typeParameter: inference.typeParameter, + candidates: inference.candidates && inference.candidates.slice(), + contraCandidates: inference.contraCandidates && inference.contraCandidates.slice(), + inferredType: inference.inferredType, + priority: inference.priority, + topLevel: inference.topLevel, + isFixed: inference.isFixed + }; + } + // Return true if the given type could possibly reference a type parameter for which + // we perform type inference (i.e. a type parameter of a generic function). We cache + // results for union and intersection types for performance reasons. + function couldContainTypeVariables(type) { + var objectFlags = ts.getObjectFlags(type); + return !!(type.flags & 63176704 /* Instantiable */ || + objectFlags & 4 /* Reference */ && ts.forEach(type.typeArguments, couldContainTypeVariables) || + objectFlags & 16 /* Anonymous */ && type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 2048 /* TypeLiteral */ | 32 /* Class */) || + objectFlags & 32 /* Mapped */ || + type.flags & 3145728 /* UnionOrIntersection */ && couldUnionOrIntersectionContainTypeVariables(type)); + } + function couldUnionOrIntersectionContainTypeVariables(type) { + if (type.couldContainTypeVariables === undefined) { + type.couldContainTypeVariables = ts.some(type.types, couldContainTypeVariables); + } + return type.couldContainTypeVariables; + } + function isTypeParameterAtTopLevel(type, typeParameter) { + return type === typeParameter || !!(type.flags & 3145728 /* UnionOrIntersection */) && ts.some(type.types, function (t) { return isTypeParameterAtTopLevel(t, typeParameter); }); + } + /** Create an object with properties named in the string literal type. Every property has type `any` */ + function createEmptyObjectTypeFromStringLiteral(type) { + var members = ts.createSymbolTable(); + forEachType(type, function (t) { + if (!(t.flags & 128 /* StringLiteral */)) { + return; + } + var name = ts.escapeLeadingUnderscores(t.value); + var literalProp = createSymbol(4 /* Property */, name); + literalProp.type = anyType; + if (t.symbol) { + literalProp.declarations = t.symbol.declarations; + literalProp.valueDeclaration = t.symbol.valueDeclaration; + } + members.set(name, literalProp); + }); + var indexInfo = type.flags & 4 /* String */ ? createIndexInfo(emptyObjectType, /*isReadonly*/ false) : undefined; + return createAnonymousType(undefined, members, ts.emptyArray, ts.emptyArray, indexInfo, undefined); + } + /** + * Infer a suitable input type for a homomorphic mapped type { [P in keyof T]: X }. We construct + * an object type with the same set of properties as the source type, where the type of each + * property is computed by inferring from the source property type to X for the type + * variable T[P] (i.e. we treat the type T[P] as the type variable we're inferring for). + */ + function inferTypeForHomomorphicMappedType(source, target, constraint) { + var key = source.id + "," + target.id + "," + constraint.id; + if (reverseMappedCache.has(key)) { + return reverseMappedCache.get(key); + } + reverseMappedCache.set(key, undefined); + var type = createReverseMappedType(source, target, constraint); + reverseMappedCache.set(key, type); + return type; + } + function createReverseMappedType(source, target, constraint) { + var properties = getPropertiesOfType(source); + if (properties.length === 0 && !getIndexInfoOfType(source, 0 /* String */)) { + return undefined; + } + // If any property contains context sensitive functions that have been skipped, the source type + // is incomplete and we can't infer a meaningful input type. + for (var _i = 0, properties_3 = properties; _i < properties_3.length; _i++) { + var prop = properties_3[_i]; + if (getTypeOfSymbol(prop).flags & 536870912 /* ContainsAnyFunctionType */) { + return undefined; + } + } + // For arrays and tuples we infer new arrays and tuples where the reverse mapping has been + // applied to the element type(s). + if (isArrayType(source)) { + return createArrayType(inferReverseMappedType(source.typeArguments[0], target, constraint)); + } + if (isReadonlyArrayType(source)) { + return createReadonlyArrayType(inferReverseMappedType(source.typeArguments[0], target, constraint)); + } + if (isTupleType(source)) { + var elementTypes = ts.map(source.typeArguments || ts.emptyArray, function (t) { return inferReverseMappedType(t, target, constraint); }); + var minLength = getMappedTypeModifiers(target) & 4 /* IncludeOptional */ ? + getTypeReferenceArity(source) - (source.target.hasRestElement ? 1 : 0) : source.target.minLength; + return createTupleType(elementTypes, minLength, source.target.hasRestElement, source.target.associatedNames); + } + // For all other object types we infer a new object type where the reverse mapping has been + // applied to the type of each property. + var reversed = createObjectType(2048 /* ReverseMapped */ | 16 /* Anonymous */, /*symbol*/ undefined); + reversed.source = source; + reversed.mappedType = target; + reversed.constraintType = constraint; + return reversed; + } + function getTypeOfReverseMappedSymbol(symbol) { + return inferReverseMappedType(symbol.propertyType, symbol.mappedType, symbol.constraintType); + } + function inferReverseMappedType(sourceType, target, constraint) { + var typeParameter = getIndexedAccessType(constraint.type, getTypeParameterFromMappedType(target)); + var templateType = getTemplateTypeFromMappedType(target); + var inference = createInferenceInfo(typeParameter); + inferTypes([inference], sourceType, templateType); + return getTypeFromInference(inference); + } + function getUnmatchedProperties(source, target, requireOptionalProperties) { + var properties, _i, properties_4, targetProp, sourceProp; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + properties = target.flags & 2097152 /* Intersection */ ? getPropertiesOfUnionOrIntersectionType(target) : getPropertiesOfObjectType(target); + _i = 0, properties_4 = properties; + _a.label = 1; + case 1: + if (!(_i < properties_4.length)) return [3 /*break*/, 4]; + targetProp = properties_4[_i]; + if (!(requireOptionalProperties || !(targetProp.flags & 16777216 /* Optional */))) return [3 /*break*/, 3]; + sourceProp = getPropertyOfType(source, targetProp.escapedName); + if (!!sourceProp) return [3 /*break*/, 3]; + return [4 /*yield*/, targetProp]; + case 2: + _a.sent(); + _a.label = 3; + case 3: + _i++; + return [3 /*break*/, 1]; + case 4: return [2 /*return*/]; + } + }); + } + function getUnmatchedProperty(source, target, requireOptionalProperties) { + return getUnmatchedProperties(source, target, requireOptionalProperties).next().value; + } + function tupleTypesDefinitelyUnrelated(source, target) { + return target.target.minLength > source.target.minLength || + !getRestTypeOfTupleType(target) && (!!getRestTypeOfTupleType(source) || getLengthOfTupleType(target) < getLengthOfTupleType(source)); + } + function typesDefinitelyUnrelated(source, target) { + // Two tuple types with incompatible arities are definitely unrelated. + // Two object types that each have a property that is unmatched in the other are definitely unrelated. + return isTupleType(source) && isTupleType(target) && tupleTypesDefinitelyUnrelated(source, target) || + !!getUnmatchedProperty(source, target, /*requireOptionalProperties*/ false) && !!getUnmatchedProperty(target, source, /*requireOptionalProperties*/ false); + } + function getTypeFromInference(inference) { + return inference.candidates ? getUnionType(inference.candidates, 2 /* Subtype */) : + inference.contraCandidates ? getIntersectionType(inference.contraCandidates) : + emptyObjectType; + } + function inferTypes(inferences, originalSource, originalTarget, priority) { + if (priority === void 0) { priority = 0; } + var symbolStack; + var visited; + var contravariant = false; + var bivariant = false; + var propagationType; + var allowComplexConstraintInference = true; + inferFromTypes(originalSource, originalTarget); + function inferFromTypes(source, target) { + if (!couldContainTypeVariables(target)) { + return; + } + if (source === wildcardType) { + // We are inferring from an 'any' type. We want to infer this type for every type parameter + // referenced in the target type, so we record it as the propagation type and infer from the + // target to itself. Then, as we find candidates we substitute the propagation type. + var savePropagationType = propagationType; + propagationType = source; + inferFromTypes(target, target); + propagationType = savePropagationType; + return; + } + if (source.aliasSymbol && source.aliasTypeArguments && source.aliasSymbol === target.aliasSymbol) { + // Source and target are types originating in the same generic type alias declaration. + // Simply infer from source type arguments to target type arguments. + var sourceTypes = source.aliasTypeArguments; + var targetTypes = target.aliasTypeArguments; + for (var i = 0; i < sourceTypes.length; i++) { + inferFromTypes(sourceTypes[i], targetTypes[i]); + } + return; + } + if (source.flags & 1048576 /* Union */ && target.flags & 1048576 /* Union */ && !(source.flags & 1024 /* EnumLiteral */ && target.flags & 1024 /* EnumLiteral */) || + source.flags & 2097152 /* Intersection */ && target.flags & 2097152 /* Intersection */) { + // Source and target are both unions or both intersections. If source and target + // are the same type, just relate each constituent type to itself. + if (source === target) { + for (var _i = 0, _a = source.types; _i < _a.length; _i++) { + var t = _a[_i]; + inferFromTypes(t, t); + } + return; + } + // Find each source constituent type that has an identically matching target constituent + // type, and for each such type infer from the type to itself. When inferring from a + // type to itself we effectively find all type parameter occurrences within that type + // and infer themselves as their type arguments. We have special handling for numeric + // and string literals because the number and string types are not represented as unions + // of all their possible values. + var matchingTypes = void 0; + for (var _b = 0, _c = source.types; _b < _c.length; _b++) { + var t = _c[_b]; + if (typeIdenticalToSomeType(t, target.types)) { + (matchingTypes || (matchingTypes = [])).push(t); + inferFromTypes(t, t); + } + else if (t.flags & (256 /* NumberLiteral */ | 128 /* StringLiteral */)) { + var b = getBaseTypeOfLiteralType(t); + if (typeIdenticalToSomeType(b, target.types)) { + (matchingTypes || (matchingTypes = [])).push(t, b); + } + } + } + // Next, to improve the quality of inferences, reduce the source and target types by + // removing the identically matched constituents. For example, when inferring from + // 'string | string[]' to 'string | T' we reduce the types to 'string[]' and 'T'. + if (matchingTypes) { + source = removeTypesFromUnionOrIntersection(source, matchingTypes); + target = removeTypesFromUnionOrIntersection(target, matchingTypes); + } + } + if (target.flags & 8650752 /* TypeVariable */) { + // If target is a type parameter, make an inference, unless the source type contains + // the anyFunctionType (the wildcard type that's used to avoid contextually typing functions). + // Because the anyFunctionType is internal, it should not be exposed to the user by adding + // it as an inference candidate. Hopefully, a better candidate will come along that does + // not contain anyFunctionType when we come back to this argument for its second round + // of inference. Also, we exclude inferences for silentNeverType (which is used as a wildcard + // when constructing types from type parameters that had no inference candidates). + if (source.flags & 536870912 /* ContainsAnyFunctionType */ || source === silentNeverType || (priority & 8 /* ReturnType */ && (source === autoType || source === autoArrayType))) { + return; + } + var inference = getInferenceInfoForType(target); + if (inference) { + if (!inference.isFixed) { + if (inference.priority === undefined || priority < inference.priority) { + inference.candidates = undefined; + inference.contraCandidates = undefined; + inference.priority = priority; + } + if (priority === inference.priority) { + var candidate = propagationType || source; + // We make contravariant inferences only if we are in a pure contravariant position, + // i.e. only if we have not descended into a bivariant position. + if (contravariant && !bivariant) { + inference.contraCandidates = ts.appendIfUnique(inference.contraCandidates, candidate); + } + else { + inference.candidates = ts.appendIfUnique(inference.candidates, candidate); + } + } + if (!(priority & 8 /* ReturnType */) && target.flags & 262144 /* TypeParameter */ && !isTypeParameterAtTopLevel(originalTarget, target)) { + inference.topLevel = false; + } + } + return; + } + else { + // Infer to the simplified version of an indexed access, if possible, to (hopefully) expose more bare type parameters to the inference engine + var simplified = getSimplifiedType(target); + if (simplified !== target) { + inferFromTypesOnce(source, simplified); + } + else if (target.flags & 8388608 /* IndexedAccess */) { + var indexType = getSimplifiedType(target.indexType); + // Generally simplifications of instantiable indexes are avoided to keep relationship checking correct, however if our target is an access, we can consider + // that key of that access to be "instantiated", since we're looking to find the infernce goal in any way we can. + if (indexType.flags & 63176704 /* Instantiable */) { + var simplified_1 = distributeIndexOverObjectType(getSimplifiedType(target.objectType), indexType); + if (simplified_1 && simplified_1 !== target) { + inferFromTypesOnce(source, simplified_1); + } + } + } + } + } + if (ts.getObjectFlags(source) & 4 /* Reference */ && ts.getObjectFlags(target) & 4 /* Reference */ && source.target === target.target) { + // If source and target are references to the same generic type, infer from type arguments + var sourceTypes = source.typeArguments || ts.emptyArray; + var targetTypes = target.typeArguments || ts.emptyArray; + var count = sourceTypes.length < targetTypes.length ? sourceTypes.length : targetTypes.length; + var variances = getVariances(source.target); + for (var i = 0; i < count; i++) { + if (i < variances.length && variances[i] === 2 /* Contravariant */) { + inferFromContravariantTypes(sourceTypes[i], targetTypes[i]); + } + else { + inferFromTypes(sourceTypes[i], targetTypes[i]); + } + } + } + else if (source.flags & 4194304 /* Index */ && target.flags & 4194304 /* Index */) { + contravariant = !contravariant; + inferFromTypes(source.type, target.type); + contravariant = !contravariant; + } + else if ((isLiteralType(source) || source.flags & 4 /* String */) && target.flags & 4194304 /* Index */) { + var empty = createEmptyObjectTypeFromStringLiteral(source); + contravariant = !contravariant; + var savePriority = priority; + priority |= 16 /* LiteralKeyof */; + inferFromTypes(empty, target.type); + priority = savePriority; + contravariant = !contravariant; + } + else if (source.flags & 8388608 /* IndexedAccess */ && target.flags & 8388608 /* IndexedAccess */) { + inferFromTypes(source.objectType, target.objectType); + inferFromTypes(source.indexType, target.indexType); + } + else if (source.flags & 16777216 /* Conditional */ && target.flags & 16777216 /* Conditional */) { + inferFromTypes(source.checkType, target.checkType); + inferFromTypes(source.extendsType, target.extendsType); + inferFromTypes(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target)); + inferFromTypes(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target)); + } + else if (target.flags & 16777216 /* Conditional */) { + inferFromTypes(source, getUnionType([getTrueTypeFromConditionalType(target), getFalseTypeFromConditionalType(target)])); + } + else if (target.flags & 3145728 /* UnionOrIntersection */) { + var targetTypes = target.types; + var typeVariableCount = 0; + var typeVariable = void 0; + // First infer to each type in union or intersection that isn't a type variable + for (var _d = 0, targetTypes_3 = targetTypes; _d < targetTypes_3.length; _d++) { + var t = targetTypes_3[_d]; + if (getInferenceInfoForType(t)) { + typeVariable = t; + typeVariableCount++; + } + else { + inferFromTypes(source, t); + } + } + // Next, if target containings a single naked type variable, make a secondary inference to that type + // variable. This gives meaningful results for union types in co-variant positions and intersection + // types in contra-variant positions (such as callback parameters). + if (typeVariableCount === 1) { + var savePriority = priority; + priority |= 1 /* NakedTypeVariable */; + inferFromTypes(source, typeVariable); + priority = savePriority; + } + } + else if (source.flags & 1048576 /* Union */) { + // Source is a union or intersection type, infer from each constituent type + var sourceTypes = source.types; + for (var _e = 0, sourceTypes_3 = sourceTypes; _e < sourceTypes_3.length; _e++) { + var sourceType = sourceTypes_3[_e]; + inferFromTypes(sourceType, target); + } + } + else { + if (!(priority & 32 /* NoConstraints */ && source.flags & (2097152 /* Intersection */ | 63176704 /* Instantiable */))) { + var apparentSource = getApparentType(source); + // getApparentType can return _any_ type, since an indexed access or conditional may simplify to any other type. + // If that occurs and it doesn't simplify to an object or intersection, we'll need to restart `inferFromTypes` + // with the simplified source. + if (apparentSource !== source && allowComplexConstraintInference && !(apparentSource.flags & (524288 /* Object */ | 2097152 /* Intersection */))) { + // TODO: The `allowComplexConstraintInference` flag is a hack! This forbids inference from complex constraints within constraints! + // This isn't required algorithmically, but rather is used to lower the memory burden caused by performing inference + // that is _too good_ in projects with complicated constraints (eg, fp-ts). In such cases, if we did not limit ourselves + // here, we might produce more valid inferences for types, causing us to do more checks and perform more instantiations + // (in addition to the extra stack depth here) which, in turn, can push the already close process over its limit. + // TL;DR: If we ever become generally more memory efficienct (or our resource budget ever increases), we should just + // remove this `allowComplexConstraintInference` flag. + allowComplexConstraintInference = false; + return inferFromTypes(apparentSource, target); + } + source = apparentSource; + } + if (source.flags & (524288 /* Object */ | 2097152 /* Intersection */)) { + var key = source.id + "," + target.id; + if (visited && visited.get(key)) { + return; + } + (visited || (visited = ts.createMap())).set(key, true); + // If we are already processing another target type with the same associated symbol (such as + // an instantiation of the same generic type), we do not explore this target as it would yield + // no further inferences. We exclude the static side of classes from this check since it shares + // its symbol with the instance side which would lead to false positives. + var isNonConstructorObject = target.flags & 524288 /* Object */ && + !(ts.getObjectFlags(target) & 16 /* Anonymous */ && target.symbol && target.symbol.flags & 32 /* Class */); + var symbol = isNonConstructorObject ? target.symbol : undefined; + if (symbol) { + if (ts.contains(symbolStack, symbol)) { + return; + } + (symbolStack || (symbolStack = [])).push(symbol); + inferFromObjectTypes(source, target); + symbolStack.pop(); + } + else { + inferFromObjectTypes(source, target); + } + } + } + function inferFromTypesOnce(source, target) { + var key = source.id + "," + target.id; + if (!visited || !visited.get(key)) { + (visited || (visited = ts.createMap())).set(key, true); + inferFromTypes(source, target); + } + } + } + function inferFromContravariantTypes(source, target) { + if (strictFunctionTypes || priority & 64 /* AlwaysStrict */) { + contravariant = !contravariant; + inferFromTypes(source, target); + contravariant = !contravariant; + } + else { + inferFromTypes(source, target); + } + } + function getInferenceInfoForType(type) { + if (type.flags & 8650752 /* TypeVariable */) { + for (var _i = 0, inferences_1 = inferences; _i < inferences_1.length; _i++) { + var inference = inferences_1[_i]; + if (type === inference.typeParameter) { + return inference; + } + } + } + return undefined; + } + function inferFromMappedTypeConstraint(source, target, constraintType) { + if (constraintType.flags & 1048576 /* Union */) { + var result = false; + for (var _i = 0, _a = constraintType.types; _i < _a.length; _i++) { + var type = _a[_i]; + result = inferFromMappedTypeConstraint(source, target, type) || result; + } + return result; + } + if (constraintType.flags & 4194304 /* Index */) { + // We're inferring from some source type S to a homomorphic mapped type { [P in keyof T]: X }, + // where T is a type variable. Use inferTypeForHomomorphicMappedType to infer a suitable source + // type and then make a secondary inference from that type to T. We make a secondary inference + // such that direct inferences to T get priority over inferences to Partial, for example. + var inference = getInferenceInfoForType(constraintType.type); + if (inference && !inference.isFixed) { + var inferredType = inferTypeForHomomorphicMappedType(source, target, constraintType); + if (inferredType) { + var savePriority = priority; + priority |= 2 /* HomomorphicMappedType */; + inferFromTypes(inferredType, inference.typeParameter); + priority = savePriority; + } + } + return true; + } + if (constraintType.flags & 262144 /* TypeParameter */) { + // We're inferring from some source type S to a mapped type { [P in T]: X }, where T is a type + // parameter. Infer from 'keyof S' to T and infer from a union of each property type in S to X. + var savePriority = priority; + priority |= 4 /* MappedTypeConstraint */; + inferFromTypes(getIndexType(source), constraintType); + priority = savePriority; + inferFromTypes(getUnionType(ts.map(getPropertiesOfType(source), getTypeOfSymbol)), getTemplateTypeFromMappedType(target)); + return true; + } + return false; + } + function inferFromObjectTypes(source, target) { + if (isGenericMappedType(source) && isGenericMappedType(target)) { + // The source and target types are generic types { [P in S]: X } and { [P in T]: Y }, so we infer + // from S to T and from X to Y. + inferFromTypes(getConstraintTypeFromMappedType(source), getConstraintTypeFromMappedType(target)); + inferFromTypes(getTemplateTypeFromMappedType(source), getTemplateTypeFromMappedType(target)); + } + if (ts.getObjectFlags(target) & 32 /* Mapped */) { + var constraintType = getConstraintTypeFromMappedType(target); + if (inferFromMappedTypeConstraint(source, target, constraintType)) { + return; + } + } + // Infer from the members of source and target only if the two types are possibly related + if (!typesDefinitelyUnrelated(source, target)) { + inferFromProperties(source, target); + inferFromSignatures(source, target, 0 /* Call */); + inferFromSignatures(source, target, 1 /* Construct */); + inferFromIndexTypes(source, target); + } + } + function inferFromProperties(source, target) { + if (isTupleType(source)) { + if (isTupleType(target)) { + var sourceLength = getLengthOfTupleType(source); + var targetLength = getLengthOfTupleType(target); + var sourceRestType = getRestTypeOfTupleType(source); + var targetRestType = getRestTypeOfTupleType(target); + var fixedLength = targetLength < sourceLength || sourceRestType ? targetLength : sourceLength; + for (var i = 0; i < fixedLength; i++) { + inferFromTypes(i < sourceLength ? source.typeArguments[i] : sourceRestType, target.typeArguments[i]); + } + if (targetRestType) { + var types = fixedLength < sourceLength ? source.typeArguments.slice(fixedLength, sourceLength) : []; + if (sourceRestType) { + types.push(sourceRestType); + } + if (types.length) { + inferFromTypes(getUnionType(types), targetRestType); + } + } + return; + } + if (isArrayType(target)) { + inferFromIndexTypes(source, target); + return; + } + } + var properties = getPropertiesOfObjectType(target); + for (var _i = 0, properties_5 = properties; _i < properties_5.length; _i++) { + var targetProp = properties_5[_i]; + var sourceProp = getPropertyOfType(source, targetProp.escapedName); + if (sourceProp) { + inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); + } + } + } + function inferFromSignatures(source, target, kind) { + var sourceSignatures = getSignaturesOfType(source, kind); + var targetSignatures = getSignaturesOfType(target, kind); + var sourceLen = sourceSignatures.length; + var targetLen = targetSignatures.length; + var len = sourceLen < targetLen ? sourceLen : targetLen; + var skipParameters = !!(source.flags & 536870912 /* ContainsAnyFunctionType */); + for (var i = 0; i < len; i++) { + inferFromSignature(getBaseSignature(sourceSignatures[sourceLen - len + i]), getBaseSignature(targetSignatures[targetLen - len + i]), skipParameters); + } + } + function inferFromSignature(source, target, skipParameters) { + if (!skipParameters) { + var saveBivariant = bivariant; + var kind = target.declaration ? target.declaration.kind : 0 /* Unknown */; + // Once we descend into a bivariant signature we remain bivariant for all nested inferences + bivariant = bivariant || kind === 156 /* MethodDeclaration */ || kind === 155 /* MethodSignature */ || kind === 157 /* Constructor */; + forEachMatchingParameterType(source, target, inferFromContravariantTypes); + bivariant = saveBivariant; + } + var sourceTypePredicate = getTypePredicateOfSignature(source); + var targetTypePredicate = getTypePredicateOfSignature(target); + if (sourceTypePredicate && targetTypePredicate && sourceTypePredicate.kind === targetTypePredicate.kind) { + inferFromTypes(sourceTypePredicate.type, targetTypePredicate.type); + } + else { + inferFromTypes(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target)); + } + } + function inferFromIndexTypes(source, target) { + var targetStringIndexType = getIndexTypeOfType(target, 0 /* String */); + if (targetStringIndexType) { + var sourceIndexType = getIndexTypeOfType(source, 0 /* String */) || + getImplicitIndexTypeOfType(source, 0 /* String */); + if (sourceIndexType) { + inferFromTypes(sourceIndexType, targetStringIndexType); + } + } + var targetNumberIndexType = getIndexTypeOfType(target, 1 /* Number */); + if (targetNumberIndexType) { + var sourceIndexType = getIndexTypeOfType(source, 1 /* Number */) || + getIndexTypeOfType(source, 0 /* String */) || + getImplicitIndexTypeOfType(source, 1 /* Number */); + if (sourceIndexType) { + inferFromTypes(sourceIndexType, targetNumberIndexType); + } + } + } + } + function typeIdenticalToSomeType(type, types) { + for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { + var t = types_10[_i]; + if (isTypeIdenticalTo(t, type)) { + return true; + } + } + return false; + } + /** + * Return a new union or intersection type computed by removing a given set of types + * from a given union or intersection type. + */ + function removeTypesFromUnionOrIntersection(type, typesToRemove) { + var reducedTypes = []; + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (!typeIdenticalToSomeType(t, typesToRemove)) { + reducedTypes.push(t); + } + } + return type.flags & 1048576 /* Union */ ? getUnionType(reducedTypes) : getIntersectionType(reducedTypes); + } + function hasPrimitiveConstraint(type) { + var constraint = getConstraintOfTypeParameter(type); + return !!constraint && maybeTypeOfKind(constraint.flags & 16777216 /* Conditional */ ? getDefaultConstraintOfConditionalType(constraint) : constraint, 131068 /* Primitive */ | 4194304 /* Index */); + } + function isObjectLiteralType(type) { + return !!(ts.getObjectFlags(type) & 128 /* ObjectLiteral */); + } + function widenObjectLiteralCandidates(candidates) { + if (candidates.length > 1) { + var objectLiterals = ts.filter(candidates, isObjectLiteralType); + if (objectLiterals.length) { + var objectLiteralsType = getWidenedType(getUnionType(objectLiterals, 2 /* Subtype */)); + return ts.concatenate(ts.filter(candidates, function (t) { return !isObjectLiteralType(t); }), [objectLiteralsType]); + } + } + return candidates; + } + function getContravariantInference(inference) { + return inference.priority & 28 /* PriorityImpliesCombination */ ? getIntersectionType(inference.contraCandidates) : getCommonSubtype(inference.contraCandidates); + } + function getCovariantInference(inference, signature) { + // Extract all object literal types and replace them with a single widened and normalized type. + var candidates = widenObjectLiteralCandidates(inference.candidates); + // We widen inferred literal types if + // all inferences were made to top-level occurrences of the type parameter, and + // the type parameter has no constraint or its constraint includes no primitive or literal types, and + // the type parameter was fixed during inference or does not occur at top-level in the return type. + var primitiveConstraint = hasPrimitiveConstraint(inference.typeParameter); + var widenLiteralTypes = !primitiveConstraint && inference.topLevel && + (inference.isFixed || !isTypeParameterAtTopLevel(getReturnTypeOfSignature(signature), inference.typeParameter)); + var baseCandidates = primitiveConstraint ? ts.sameMap(candidates, getRegularTypeOfLiteralType) : + widenLiteralTypes ? ts.sameMap(candidates, getWidenedLiteralType) : + candidates; + // If all inferences were made from a position that implies a combined result, infer a union type. + // Otherwise, infer a common supertype. + var unwidenedType = inference.priority & 28 /* PriorityImpliesCombination */ ? + getUnionType(baseCandidates, 2 /* Subtype */) : + getCommonSupertype(baseCandidates); + return getWidenedType(unwidenedType); + } + function getInferredType(context, index) { + var inference = context.inferences[index]; + var inferredType = inference.inferredType; + if (!inferredType) { + var signature = context.signature; + if (signature) { + var inferredCovariantType = inference.candidates ? getCovariantInference(inference, signature) : undefined; + if (inference.contraCandidates) { + var inferredContravariantType = getContravariantInference(inference); + // If we have both co- and contra-variant inferences, we prefer the contra-variant inference + // unless the co-variant inference is a subtype and not 'never'. + inferredType = inferredCovariantType && !(inferredCovariantType.flags & 131072 /* Never */) && + isTypeSubtypeOf(inferredCovariantType, inferredContravariantType) ? + inferredCovariantType : inferredContravariantType; + } + else if (inferredCovariantType) { + inferredType = inferredCovariantType; + } + else if (context.flags & 1 /* NoDefault */) { + // We use silentNeverType as the wildcard that signals no inferences. + inferredType = silentNeverType; + } + else { + // Infer either the default or the empty object type when no inferences were + // made. It is important to remember that in this case, inference still + // succeeds, meaning there is no error for not having inference candidates. An + // inference error only occurs when there are *conflicting* candidates, i.e. + // candidates with no common supertype. + var defaultType = getDefaultFromTypeParameter(inference.typeParameter); + if (defaultType) { + // Instantiate the default type. Any forward reference to a type + // parameter should be instantiated to the empty object type. + inferredType = instantiateType(defaultType, combineTypeMappers(createBackreferenceMapper(context.signature.typeParameters, index), context)); + } + else { + inferredType = getDefaultTypeArgumentType(!!(context.flags & 2 /* AnyDefault */)); + } + } + } + else { + inferredType = getTypeFromInference(inference); + } + inference.inferredType = inferredType; + var constraint = getConstraintOfTypeParameter(inference.typeParameter); + if (constraint) { + var instantiatedConstraint = instantiateType(constraint, context); + if (!context.compareTypes(inferredType, getTypeWithThisArgument(instantiatedConstraint, inferredType))) { + inference.inferredType = inferredType = instantiatedConstraint; + } + } + } + return inferredType; + } + function getDefaultTypeArgumentType(isInJavaScriptFile) { + return isInJavaScriptFile ? anyType : emptyObjectType; + } + function getInferredTypes(context) { + var result = []; + for (var i = 0; i < context.inferences.length; i++) { + result.push(getInferredType(context, i)); + } + return result; + } + // EXPRESSION TYPE CHECKING + function getCannotFindNameDiagnosticForName(name) { + switch (name) { + case "document": + case "console": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom; + case "$": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_and_then_add_jquery_to_the_types_field_in_your_tsconfig; + case "describe": + case "suite": + case "it": + case "test": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha_and_then_add_jest_or_mocha_to_the_types_field_in_your_tsconfig; + case "process": + case "require": + case "Buffer": + case "module": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_and_then_add_node_to_the_types_field_in_your_tsconfig; + case "Map": + case "Set": + case "Promise": + case "Symbol": + case "WeakMap": + case "WeakSet": + case "Iterator": + case "AsyncIterator": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later; + default: return ts.Diagnostics.Cannot_find_name_0; + } + } + function getResolvedSymbol(node) { + var links = getNodeLinks(node); + if (!links.resolvedSymbol) { + links.resolvedSymbol = !ts.nodeIsMissing(node) && + resolveName(node, node.escapedText, 67220415 /* Value */ | 1048576 /* ExportValue */, getCannotFindNameDiagnosticForName(node.escapedText), node, !ts.isWriteOnlyAccess(node), + /*excludeGlobals*/ false, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1) || unknownSymbol; + } + return links.resolvedSymbol; + } + function isInTypeQuery(node) { + // TypeScript 1.0 spec (April 2014): 3.6.3 + // A type query consists of the keyword typeof followed by an expression. + // The expression is restricted to a single identifier or a sequence of identifiers separated by periods + return !!ts.findAncestor(node, function (n) { return n.kind === 167 /* TypeQuery */ ? true : n.kind === 72 /* Identifier */ || n.kind === 148 /* QualifiedName */ ? false : "quit"; }); + } + // Return the flow cache key for a "dotted name" (i.e. a sequence of identifiers + // separated by dots). The key consists of the id of the symbol referenced by the + // leftmost identifier followed by zero or more property names separated by dots. + // The result is undefined if the reference isn't a dotted name. We prefix nodes + // occurring in an apparent type position with '@' because the control flow type + // of such nodes may be based on the apparent type instead of the declared type. + function getFlowCacheKey(node) { + if (node.kind === 72 /* Identifier */) { + var symbol = getResolvedSymbol(node); + return symbol !== unknownSymbol ? (isConstraintPosition(node) ? "@" : "") + getSymbolId(symbol) : undefined; + } + if (node.kind === 100 /* ThisKeyword */) { + return "0"; + } + if (node.kind === 189 /* PropertyAccessExpression */) { + var key = getFlowCacheKey(node.expression); + return key && key + "." + ts.idText(node.name); + } + if (node.kind === 186 /* BindingElement */) { + var container = node.parent.parent; + var key = container.kind === 186 /* BindingElement */ ? getFlowCacheKey(container) : (container.initializer && getFlowCacheKey(container.initializer)); + var text = getBindingElementNameText(node); + var result = key && text && (key + "." + text); + return result; + } + return undefined; + } + function getBindingElementNameText(element) { + var parent = element.parent; + if (parent.kind === 184 /* ObjectBindingPattern */) { + var name = element.propertyName || element.name; + switch (name.kind) { + case 72 /* Identifier */: + return ts.idText(name); + case 149 /* ComputedPropertyName */: + return ts.isStringOrNumericLiteralLike(name.expression) ? name.expression.text : undefined; + case 10 /* StringLiteral */: + case 8 /* NumericLiteral */: + return name.text; + default: + // Per types, array and object binding patterns remain, however they should never be present if propertyName is not defined + ts.Debug.fail("Unexpected name kind for binding element name"); + } + } + else { + return "" + parent.elements.indexOf(element); + } + } + function isMatchingReference(source, target) { + switch (source.kind) { + case 72 /* Identifier */: + return target.kind === 72 /* Identifier */ && getResolvedSymbol(source) === getResolvedSymbol(target) || + (target.kind === 237 /* VariableDeclaration */ || target.kind === 186 /* BindingElement */) && + getExportSymbolOfValueSymbolIfExported(getResolvedSymbol(source)) === getSymbolOfNode(target); + case 100 /* ThisKeyword */: + return target.kind === 100 /* ThisKeyword */; + case 98 /* SuperKeyword */: + return target.kind === 98 /* SuperKeyword */; + case 189 /* PropertyAccessExpression */: + case 190 /* ElementAccessExpression */: + return (ts.isPropertyAccessExpression(target) || ts.isElementAccessExpression(target)) && + getAccessedPropertyName(source) === getAccessedPropertyName(target) && + isMatchingReference(source.expression, target.expression); + case 186 /* BindingElement */: + if (target.kind !== 189 /* PropertyAccessExpression */) + return false; + var t = target; + if (t.name.escapedText !== getBindingElementNameText(source)) + return false; + if (source.parent.parent.kind === 186 /* BindingElement */ && isMatchingReference(source.parent.parent, t.expression)) { + return true; + } + if (source.parent.parent.kind === 237 /* VariableDeclaration */) { + var maybeId = source.parent.parent.initializer; + return !!maybeId && isMatchingReference(maybeId, t.expression); + } + } + return false; + } + function getAccessedPropertyName(access) { + return ts.isPropertyAccessExpression(access) ? access.name.escapedText : + ts.isStringLiteral(access.argumentExpression) || ts.isNumericLiteral(access.argumentExpression) ? ts.escapeLeadingUnderscores(access.argumentExpression.text) : + undefined; + } + function containsMatchingReference(source, target) { + while (source.kind === 189 /* PropertyAccessExpression */) { + source = source.expression; + if (isMatchingReference(source, target)) { + return true; + } + } + return false; + } + // Return true if target is a property access xxx.yyy, source is a property access xxx.zzz, the declared + // type of xxx is a union type, and yyy is a property that is possibly a discriminant. We consider a property + // a possible discriminant if its type differs in the constituents of containing union type, and if every + // choice is a unit type or a union of unit types. + function containsMatchingReferenceDiscriminant(source, target) { + return target.kind === 189 /* PropertyAccessExpression */ && + containsMatchingReference(source, target.expression) && + isDiscriminantProperty(getDeclaredTypeOfReference(target.expression), target.name.escapedText); + } + function getDeclaredTypeOfReference(expr) { + if (expr.kind === 72 /* Identifier */) { + return getTypeOfSymbol(getResolvedSymbol(expr)); + } + if (expr.kind === 189 /* PropertyAccessExpression */) { + var type = getDeclaredTypeOfReference(expr.expression); + return type && getTypeOfPropertyOfType(type, expr.name.escapedText); + } + return undefined; + } + function isDiscriminantType(type) { + if (type.flags & 1048576 /* Union */) { + if (type.flags & (16 /* Boolean */ | 1024 /* EnumLiteral */)) { + return true; + } + var combined = 0; + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var t = _a[_i]; + combined |= t.flags; + } + if (combined & 109440 /* Unit */ && !(combined & 63176704 /* Instantiable */)) { + return true; + } + } + return false; + } + function isDiscriminantProperty(type, name) { + if (type && type.flags & 1048576 /* Union */) { + var prop = getUnionOrIntersectionProperty(type, name); + if (prop && ts.getCheckFlags(prop) & 2 /* SyntheticProperty */) { + if (prop.isDiscriminantProperty === undefined) { + prop.isDiscriminantProperty = !!(prop.checkFlags & 32 /* HasNonUniformType */) && isDiscriminantType(getTypeOfSymbol(prop)); + } + return !!prop.isDiscriminantProperty; + } + } + return false; + } + function hasNarrowableDeclaredType(expr) { + var type = getDeclaredTypeOfReference(expr); + return !!(type && type.flags & 1048576 /* Union */); + } + function findDiscriminantProperties(sourceProperties, target) { + var result; + for (var _i = 0, sourceProperties_2 = sourceProperties; _i < sourceProperties_2.length; _i++) { + var sourceProperty = sourceProperties_2[_i]; + if (isDiscriminantProperty(target, sourceProperty.escapedName)) { + if (result) { + result.push(sourceProperty); + continue; + } + result = [sourceProperty]; + } + } + return result; + } + function isOrContainsMatchingReference(source, target) { + return isMatchingReference(source, target) || containsMatchingReference(source, target); + } + function hasMatchingArgument(callExpression, reference) { + if (callExpression.arguments) { + for (var _i = 0, _a = callExpression.arguments; _i < _a.length; _i++) { + var argument = _a[_i]; + if (isOrContainsMatchingReference(reference, argument)) { + return true; + } + } + } + if (callExpression.expression.kind === 189 /* PropertyAccessExpression */ && + isOrContainsMatchingReference(reference, callExpression.expression.expression)) { + return true; + } + return false; + } + function getFlowNodeId(flow) { + if (!flow.id) { + flow.id = nextFlowId; + nextFlowId++; + } + return flow.id; + } + function typeMaybeAssignableTo(source, target) { + if (!(source.flags & 1048576 /* Union */)) { + return isTypeAssignableTo(source, target); + } + for (var _i = 0, _a = source.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (isTypeAssignableTo(t, target)) { + return true; + } + } + return false; + } + // Remove those constituent types of declaredType to which no constituent type of assignedType is assignable. + // For example, when a variable of type number | string | boolean is assigned a value of type number | boolean, + // we remove type string. + function getAssignmentReducedType(declaredType, assignedType) { + if (declaredType !== assignedType) { + if (assignedType.flags & 131072 /* Never */) { + return assignedType; + } + var reducedType = filterType(declaredType, function (t) { return typeMaybeAssignableTo(assignedType, t); }); + if (assignedType.flags & 512 /* BooleanLiteral */ && isFreshLiteralType(assignedType)) { + reducedType = mapType(reducedType, getFreshTypeOfLiteralType); // Ensure that if the assignment is a fresh type, that we narrow to fresh types + } + // Our crude heuristic produces an invalid result in some cases: see GH#26130. + // For now, when that happens, we give up and don't narrow at all. (This also + // means we'll never narrow for erroneous assignments where the assigned type + // is not assignable to the declared type.) + if (isTypeAssignableTo(assignedType, reducedType)) { + return reducedType; + } + } + return declaredType; + } + function getTypeFactsOfTypes(types) { + var result = 0 /* None */; + for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { + var t = types_11[_i]; + result |= getTypeFacts(t); + } + return result; + } + function isFunctionObjectType(type) { + // We do a quick check for a "bind" property before performing the more expensive subtype + // check. This gives us a quicker out in the common case where an object type is not a function. + var resolved = resolveStructuredTypeMembers(type); + return !!(resolved.callSignatures.length || resolved.constructSignatures.length || + resolved.members.get("bind") && isTypeSubtypeOf(type, globalFunctionType)); + } + function getTypeFacts(type) { + var flags = type.flags; + if (flags & 4 /* String */) { + return strictNullChecks ? 16317953 /* StringStrictFacts */ : 16776705 /* StringFacts */; + } + if (flags & 128 /* StringLiteral */) { + var isEmpty = type.value === ""; + return strictNullChecks ? + isEmpty ? 12123649 /* EmptyStringStrictFacts */ : 7929345 /* NonEmptyStringStrictFacts */ : + isEmpty ? 12582401 /* EmptyStringFacts */ : 16776705 /* NonEmptyStringFacts */; + } + if (flags & (8 /* Number */ | 32 /* Enum */)) { + return strictNullChecks ? 16317698 /* NumberStrictFacts */ : 16776450 /* NumberFacts */; + } + if (flags & 256 /* NumberLiteral */) { + var isZero = type.value === 0; + return strictNullChecks ? + isZero ? 12123394 /* ZeroNumberStrictFacts */ : 7929090 /* NonZeroNumberStrictFacts */ : + isZero ? 12582146 /* ZeroNumberFacts */ : 16776450 /* NonZeroNumberFacts */; + } + if (flags & 64 /* BigInt */) { + return strictNullChecks ? 16317188 /* BigIntStrictFacts */ : 16775940 /* BigIntFacts */; + } + if (flags & 2048 /* BigIntLiteral */) { + var isZero = isZeroBigInt(type); + return strictNullChecks ? + isZero ? 12122884 /* ZeroBigIntStrictFacts */ : 7928580 /* NonZeroBigIntStrictFacts */ : + isZero ? 12581636 /* ZeroBigIntFacts */ : 16775940 /* NonZeroBigIntFacts */; + } + if (flags & 16 /* Boolean */) { + return strictNullChecks ? 16316168 /* BooleanStrictFacts */ : 16774920 /* BooleanFacts */; + } + if (flags & 528 /* BooleanLike */) { + return strictNullChecks ? + (type === falseType || type === regularFalseType) ? 12121864 /* FalseStrictFacts */ : 7927560 /* TrueStrictFacts */ : + (type === falseType || type === regularFalseType) ? 12580616 /* FalseFacts */ : 16774920 /* TrueFacts */; + } + if (flags & 524288 /* Object */) { + return ts.getObjectFlags(type) & 16 /* Anonymous */ && isEmptyObjectType(type) ? + strictNullChecks ? 16318463 /* EmptyObjectStrictFacts */ : 16777215 /* EmptyObjectFacts */ : + isFunctionObjectType(type) ? + strictNullChecks ? 7880640 /* FunctionStrictFacts */ : 16728000 /* FunctionFacts */ : + strictNullChecks ? 7888800 /* ObjectStrictFacts */ : 16736160 /* ObjectFacts */; + } + if (flags & (16384 /* Void */ | 32768 /* Undefined */)) { + return 9830144 /* UndefinedFacts */; + } + if (flags & 65536 /* Null */) { + return 9363232 /* NullFacts */; + } + if (flags & 12288 /* ESSymbolLike */) { + return strictNullChecks ? 7925520 /* SymbolStrictFacts */ : 16772880 /* SymbolFacts */; + } + if (flags & 67108864 /* NonPrimitive */) { + return strictNullChecks ? 7888800 /* ObjectStrictFacts */ : 16736160 /* ObjectFacts */; + } + if (flags & 63176704 /* Instantiable */) { + return getTypeFacts(getBaseConstraintOfType(type) || emptyObjectType); + } + if (flags & 3145728 /* UnionOrIntersection */) { + return getTypeFactsOfTypes(type.types); + } + return 16777215 /* All */; + } + function getTypeWithFacts(type, include) { + return filterType(type, function (t) { return (getTypeFacts(t) & include) !== 0; }); + } + function getTypeWithDefault(type, defaultExpression) { + if (defaultExpression) { + var defaultType = getTypeOfExpression(defaultExpression); + return getUnionType([getTypeWithFacts(type, 524288 /* NEUndefined */), defaultType]); + } + return type; + } + function getTypeOfDestructuredProperty(type, name) { + var text = ts.getTextOfPropertyName(name); + return getConstraintForLocation(getTypeOfPropertyOfType(type, text), name) || + isNumericLiteralName(text) && getIndexTypeOfType(type, 1 /* Number */) || + getIndexTypeOfType(type, 0 /* String */) || + errorType; + } + function getTypeOfDestructuredArrayElement(type, index) { + return everyType(type, isTupleLikeType) && getTupleElementType(type, index) || + checkIteratedTypeOrElementType(type, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterables*/ false) || + errorType; + } + function getTypeOfDestructuredSpreadExpression(type) { + return createArrayType(checkIteratedTypeOrElementType(type, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterables*/ false) || errorType); + } + function getAssignedTypeOfBinaryExpression(node) { + var isDestructuringDefaultAssignment = node.parent.kind === 187 /* ArrayLiteralExpression */ && isDestructuringAssignmentTarget(node.parent) || + node.parent.kind === 275 /* PropertyAssignment */ && isDestructuringAssignmentTarget(node.parent.parent); + return isDestructuringDefaultAssignment ? + getTypeWithDefault(getAssignedType(node), node.right) : + getTypeOfExpression(node.right); + } + function isDestructuringAssignmentTarget(parent) { + return parent.parent.kind === 204 /* BinaryExpression */ && parent.parent.left === parent || + parent.parent.kind === 227 /* ForOfStatement */ && parent.parent.initializer === parent; + } + function getAssignedTypeOfArrayLiteralElement(node, element) { + return getTypeOfDestructuredArrayElement(getAssignedType(node), node.elements.indexOf(element)); + } + function getAssignedTypeOfSpreadExpression(node) { + return getTypeOfDestructuredSpreadExpression(getAssignedType(node.parent)); + } + function getAssignedTypeOfPropertyAssignment(node) { + return getTypeOfDestructuredProperty(getAssignedType(node.parent), node.name); + } + function getAssignedTypeOfShorthandPropertyAssignment(node) { + return getTypeWithDefault(getAssignedTypeOfPropertyAssignment(node), node.objectAssignmentInitializer); + } + function getAssignedType(node) { + var parent = node.parent; + switch (parent.kind) { + case 226 /* ForInStatement */: + return stringType; + case 227 /* ForOfStatement */: + return checkRightHandSideOfForOf(parent.expression, parent.awaitModifier) || errorType; + case 204 /* BinaryExpression */: + return getAssignedTypeOfBinaryExpression(parent); + case 198 /* DeleteExpression */: + return undefinedType; + case 187 /* ArrayLiteralExpression */: + return getAssignedTypeOfArrayLiteralElement(parent, node); + case 208 /* SpreadElement */: + return getAssignedTypeOfSpreadExpression(parent); + case 275 /* PropertyAssignment */: + return getAssignedTypeOfPropertyAssignment(parent); + case 276 /* ShorthandPropertyAssignment */: + return getAssignedTypeOfShorthandPropertyAssignment(parent); + } + return errorType; + } + function getInitialTypeOfBindingElement(node) { + var pattern = node.parent; + var parentType = getInitialType(pattern.parent); + var type = pattern.kind === 184 /* ObjectBindingPattern */ ? + getTypeOfDestructuredProperty(parentType, node.propertyName || node.name) : + !node.dotDotDotToken ? + getTypeOfDestructuredArrayElement(parentType, pattern.elements.indexOf(node)) : + getTypeOfDestructuredSpreadExpression(parentType); + return getTypeWithDefault(type, node.initializer); + } + function getTypeOfInitializer(node) { + // Return the cached type if one is available. If the type of the variable was inferred + // from its initializer, we'll already have cached the type. Otherwise we compute it now + // without caching such that transient types are reflected. + var links = getNodeLinks(node); + return links.resolvedType || getTypeOfExpression(node); + } + function getInitialTypeOfVariableDeclaration(node) { + if (node.initializer) { + return getTypeOfInitializer(node.initializer); + } + if (node.parent.parent.kind === 226 /* ForInStatement */) { + return stringType; + } + if (node.parent.parent.kind === 227 /* ForOfStatement */) { + return checkRightHandSideOfForOf(node.parent.parent.expression, node.parent.parent.awaitModifier) || errorType; + } + return errorType; + } + function getInitialType(node) { + return node.kind === 237 /* VariableDeclaration */ ? + getInitialTypeOfVariableDeclaration(node) : + getInitialTypeOfBindingElement(node); + } + function getInitialOrAssignedType(node, reference) { + return getConstraintForLocation(node.kind === 237 /* VariableDeclaration */ || node.kind === 186 /* BindingElement */ ? + getInitialType(node) : + getAssignedType(node), reference); + } + function isEmptyArrayAssignment(node) { + return node.kind === 237 /* VariableDeclaration */ && node.initializer && + isEmptyArrayLiteral(node.initializer) || + node.kind !== 186 /* BindingElement */ && node.parent.kind === 204 /* BinaryExpression */ && + isEmptyArrayLiteral(node.parent.right); + } + function getReferenceCandidate(node) { + switch (node.kind) { + case 195 /* ParenthesizedExpression */: + return getReferenceCandidate(node.expression); + case 204 /* BinaryExpression */: + switch (node.operatorToken.kind) { + case 59 /* EqualsToken */: + return getReferenceCandidate(node.left); + case 27 /* CommaToken */: + return getReferenceCandidate(node.right); + } + } + return node; + } + function getReferenceRoot(node) { + var parent = node.parent; + return parent.kind === 195 /* ParenthesizedExpression */ || + parent.kind === 204 /* BinaryExpression */ && parent.operatorToken.kind === 59 /* EqualsToken */ && parent.left === node || + parent.kind === 204 /* BinaryExpression */ && parent.operatorToken.kind === 27 /* CommaToken */ && parent.right === node ? + getReferenceRoot(parent) : node; + } + function getTypeOfSwitchClause(clause) { + if (clause.kind === 271 /* CaseClause */) { + return getRegularTypeOfLiteralType(getTypeOfExpression(clause.expression)); + } + return neverType; + } + function getSwitchClauseTypes(switchStatement) { + var links = getNodeLinks(switchStatement); + if (!links.switchTypes) { + links.switchTypes = []; + for (var _i = 0, _a = switchStatement.caseBlock.clauses; _i < _a.length; _i++) { + var clause = _a[_i]; + links.switchTypes.push(getTypeOfSwitchClause(clause)); + } + } + return links.switchTypes; + } + // Get the types from all cases in a switch on `typeof`. An + // `undefined` element denotes an explicit `default` clause. + function getSwitchClauseTypeOfWitnesses(switchStatement) { + var witnesses = []; + for (var _i = 0, _a = switchStatement.caseBlock.clauses; _i < _a.length; _i++) { + var clause = _a[_i]; + if (clause.kind === 271 /* CaseClause */) { + if (clause.expression.kind === 10 /* StringLiteral */) { + witnesses.push(clause.expression.text); + continue; + } + return ts.emptyArray; + } + witnesses.push(/*explicitDefaultStatement*/ undefined); + } + return witnesses; + } + function eachTypeContainedIn(source, types) { + return source.flags & 1048576 /* Union */ ? !ts.forEach(source.types, function (t) { return !ts.contains(types, t); }) : ts.contains(types, source); + } + function isTypeSubsetOf(source, target) { + return source === target || target.flags & 1048576 /* Union */ && isTypeSubsetOfUnion(source, target); + } + function isTypeSubsetOfUnion(source, target) { + if (source.flags & 1048576 /* Union */) { + for (var _i = 0, _a = source.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (!containsType(target.types, t)) { + return false; + } + } + return true; + } + if (source.flags & 1024 /* EnumLiteral */ && getBaseTypeOfEnumLiteralType(source) === target) { + return true; + } + return containsType(target.types, source); + } + function forEachType(type, f) { + return type.flags & 1048576 /* Union */ ? ts.forEach(type.types, f) : f(type); + } + function everyType(type, f) { + return type.flags & 1048576 /* Union */ ? ts.every(type.types, f) : f(type); + } + function filterType(type, f) { + if (type.flags & 1048576 /* Union */) { + var types = type.types; + var filtered = ts.filter(types, f); + return filtered === types ? type : getUnionTypeFromSortedList(filtered, type.primitiveTypesOnly); + } + return f(type) ? type : neverType; + } + function mapType(type, mapper, noReductions) { + if (type.flags & 131072 /* Never */) { + return type; + } + if (!(type.flags & 1048576 /* Union */)) { + return mapper(type); + } + var types = type.types; + var mappedType; + var mappedTypes; + for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { + var current = types_12[_i]; + var t = mapper(current); + if (t) { + if (!mappedType) { + mappedType = t; + } + else if (!mappedTypes) { + mappedTypes = [mappedType, t]; + } + else { + mappedTypes.push(t); + } + } + } + return mappedTypes ? getUnionType(mappedTypes, noReductions ? 0 /* None */ : 1 /* Literal */) : mappedType; + } + function extractTypesOfKind(type, kind) { + return filterType(type, function (t) { return (t.flags & kind) !== 0; }); + } + // Return a new type in which occurrences of the string and number primitive types in + // typeWithPrimitives have been replaced with occurrences of string literals and numeric + // literals in typeWithLiterals, respectively. + function replacePrimitivesWithLiterals(typeWithPrimitives, typeWithLiterals) { + if (isTypeSubsetOf(stringType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 128 /* StringLiteral */) || + isTypeSubsetOf(numberType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 256 /* NumberLiteral */) || + isTypeSubsetOf(bigintType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 2048 /* BigIntLiteral */)) { + return mapType(typeWithPrimitives, function (t) { + return t.flags & 4 /* String */ ? extractTypesOfKind(typeWithLiterals, 4 /* String */ | 128 /* StringLiteral */) : + t.flags & 8 /* Number */ ? extractTypesOfKind(typeWithLiterals, 8 /* Number */ | 256 /* NumberLiteral */) : + t.flags & 64 /* BigInt */ ? extractTypesOfKind(typeWithLiterals, 64 /* BigInt */ | 2048 /* BigIntLiteral */) : + t; + }); + } + return typeWithPrimitives; + } + function isIncomplete(flowType) { + return flowType.flags === 0; + } + function getTypeFromFlowType(flowType) { + return flowType.flags === 0 ? flowType.type : flowType; + } + function createFlowType(type, incomplete) { + return incomplete ? { flags: 0, type: type } : type; + } + // An evolving array type tracks the element types that have so far been seen in an + // 'x.push(value)' or 'x[n] = value' operation along the control flow graph. Evolving + // array types are ultimately converted into manifest array types (using getFinalArrayType) + // and never escape the getFlowTypeOfReference function. + function createEvolvingArrayType(elementType) { + var result = createObjectType(256 /* EvolvingArray */); + result.elementType = elementType; + return result; + } + function getEvolvingArrayType(elementType) { + return evolvingArrayTypes[elementType.id] || (evolvingArrayTypes[elementType.id] = createEvolvingArrayType(elementType)); + } + // When adding evolving array element types we do not perform subtype reduction. Instead, + // we defer subtype reduction until the evolving array type is finalized into a manifest + // array type. + function addEvolvingArrayElementType(evolvingArrayType, node) { + var elementType = getBaseTypeOfLiteralType(getContextFreeTypeOfExpression(node)); + return isTypeSubsetOf(elementType, evolvingArrayType.elementType) ? evolvingArrayType : getEvolvingArrayType(getUnionType([evolvingArrayType.elementType, elementType])); + } + function createFinalArrayType(elementType) { + return elementType.flags & 131072 /* Never */ ? + autoArrayType : + createArrayType(elementType.flags & 1048576 /* Union */ ? + getUnionType(elementType.types, 2 /* Subtype */) : + elementType); + } + // We perform subtype reduction upon obtaining the final array type from an evolving array type. + function getFinalArrayType(evolvingArrayType) { + return evolvingArrayType.finalArrayType || (evolvingArrayType.finalArrayType = createFinalArrayType(evolvingArrayType.elementType)); + } + function finalizeEvolvingArrayType(type) { + return ts.getObjectFlags(type) & 256 /* EvolvingArray */ ? getFinalArrayType(type) : type; + } + function getElementTypeOfEvolvingArrayType(type) { + return ts.getObjectFlags(type) & 256 /* EvolvingArray */ ? type.elementType : neverType; + } + function isEvolvingArrayTypeList(types) { + var hasEvolvingArrayType = false; + for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { + var t = types_13[_i]; + if (!(t.flags & 131072 /* Never */)) { + if (!(ts.getObjectFlags(t) & 256 /* EvolvingArray */)) { + return false; + } + hasEvolvingArrayType = true; + } + } + return hasEvolvingArrayType; + } + // At flow control branch or loop junctions, if the type along every antecedent code path + // is an evolving array type, we construct a combined evolving array type. Otherwise we + // finalize all evolving array types. + function getUnionOrEvolvingArrayType(types, subtypeReduction) { + return isEvolvingArrayTypeList(types) ? + getEvolvingArrayType(getUnionType(ts.map(types, getElementTypeOfEvolvingArrayType))) : + getUnionType(ts.sameMap(types, finalizeEvolvingArrayType), subtypeReduction); + } + // Return true if the given node is 'x' in an 'x.length', x.push(value)', 'x.unshift(value)' or + // 'x[n] = value' operation, where 'n' is an expression of type any, undefined, or a number-like type. + function isEvolvingArrayOperationTarget(node) { + var root = getReferenceRoot(node); + var parent = root.parent; + var isLengthPushOrUnshift = parent.kind === 189 /* PropertyAccessExpression */ && (parent.name.escapedText === "length" || + parent.parent.kind === 191 /* CallExpression */ && ts.isPushOrUnshiftIdentifier(parent.name)); + var isElementAssignment = parent.kind === 190 /* ElementAccessExpression */ && + parent.expression === root && + parent.parent.kind === 204 /* BinaryExpression */ && + parent.parent.operatorToken.kind === 59 /* EqualsToken */ && + parent.parent.left === parent && + !ts.isAssignmentTarget(parent.parent) && + isTypeAssignableToKind(getTypeOfExpression(parent.argumentExpression), 296 /* NumberLike */); + return isLengthPushOrUnshift || isElementAssignment; + } + function maybeTypePredicateCall(node) { + var links = getNodeLinks(node); + if (links.maybeTypePredicate === undefined) { + links.maybeTypePredicate = getMaybeTypePredicate(node); + } + return links.maybeTypePredicate; + } + function getMaybeTypePredicate(node) { + if (node.expression.kind !== 98 /* SuperKeyword */) { + var funcType = checkNonNullExpression(node.expression); + if (funcType !== silentNeverType) { + var apparentType = getApparentType(funcType); + return apparentType !== errorType && ts.some(getSignaturesOfType(apparentType, 0 /* Call */), signatureHasTypePredicate); + } + } + return false; + } + function reportFlowControlError(node) { + var block = ts.findAncestor(node, ts.isFunctionOrModuleBlock); + var sourceFile = ts.getSourceFileOfNode(node); + var span = ts.getSpanOfTokenAtPosition(sourceFile, block.statements.pos); + diagnostics.add(ts.createFileDiagnostic(sourceFile, span.start, span.length, ts.Diagnostics.The_containing_function_or_module_body_is_too_large_for_control_flow_analysis)); + } + function getFlowTypeOfReference(reference, declaredType, initialType, flowContainer, couldBeUninitialized) { + if (initialType === void 0) { initialType = declaredType; } + var key; + var flowDepth = 0; + if (flowAnalysisDisabled) { + return errorType; + } + if (!reference.flowNode || !couldBeUninitialized && !(declaredType.flags & 133970943 /* Narrowable */)) { + return declaredType; + } + var sharedFlowStart = sharedFlowCount; + var evolvedType = getTypeFromFlowType(getTypeAtFlowNode(reference.flowNode)); + sharedFlowCount = sharedFlowStart; + // When the reference is 'x' in an 'x.length', 'x.push(value)', 'x.unshift(value)' or x[n] = value' operation, + // we give type 'any[]' to 'x' instead of using the type determined by control flow analysis such that operations + // on empty arrays are possible without implicit any errors and new element types can be inferred without + // type mismatch errors. + var resultType = ts.getObjectFlags(evolvedType) & 256 /* EvolvingArray */ && isEvolvingArrayOperationTarget(reference) ? autoArrayType : finalizeEvolvingArrayType(evolvedType); + if (reference.parent && reference.parent.kind === 213 /* NonNullExpression */ && getTypeWithFacts(resultType, 2097152 /* NEUndefinedOrNull */).flags & 131072 /* Never */) { + return declaredType; + } + return resultType; + function getTypeAtFlowNode(flow) { + if (flowDepth === 2000) { + // We have made 2000 recursive invocations. To avoid overflowing the call stack we report an error + // and disable further control flow analysis in the containing function or module body. + flowAnalysisDisabled = true; + reportFlowControlError(reference); + return errorType; + } + flowDepth++; + while (true) { + var flags = flow.flags; + if (flags & 1024 /* Shared */) { + // We cache results of flow type resolution for shared nodes that were previously visited in + // the same getFlowTypeOfReference invocation. A node is considered shared when it is the + // antecedent of more than one node. + for (var i = sharedFlowStart; i < sharedFlowCount; i++) { + if (sharedFlowNodes[i] === flow) { + flowDepth--; + return sharedFlowTypes[i]; + } + } + } + var type = void 0; + if (flags & 4096 /* AfterFinally */) { + // block flow edge: finally -> pre-try (for larger explanation check comment in binder.ts - bindTryStatement + flow.locked = true; + type = getTypeAtFlowNode(flow.antecedent); + flow.locked = false; + } + else if (flags & 2048 /* PreFinally */) { + // locked pre-finally flows are filtered out in getTypeAtFlowBranchLabel + // so here just redirect to antecedent + flow = flow.antecedent; + continue; + } + else if (flags & 16 /* Assignment */) { + type = getTypeAtFlowAssignment(flow); + if (!type) { + flow = flow.antecedent; + continue; + } + } + else if (flags & 96 /* Condition */) { + type = getTypeAtFlowCondition(flow); + } + else if (flags & 128 /* SwitchClause */) { + type = getTypeAtSwitchClause(flow); + } + else if (flags & 12 /* Label */) { + if (flow.antecedents.length === 1) { + flow = flow.antecedents[0]; + continue; + } + type = flags & 4 /* BranchLabel */ ? + getTypeAtFlowBranchLabel(flow) : + getTypeAtFlowLoopLabel(flow); + } + else if (flags & 256 /* ArrayMutation */) { + type = getTypeAtFlowArrayMutation(flow); + if (!type) { + flow = flow.antecedent; + continue; + } + } + else if (flags & 2 /* Start */) { + // Check if we should continue with the control flow of the containing function. + var container = flow.container; + if (container && container !== flowContainer && + reference.kind !== 189 /* PropertyAccessExpression */ && + reference.kind !== 190 /* ElementAccessExpression */ && + reference.kind !== 100 /* ThisKeyword */) { + flow = container.flowNode; + continue; + } + // At the top of the flow we have the initial type. + type = initialType; + } + else { + // Unreachable code errors are reported in the binding phase. Here we + // simply return the non-auto declared type to reduce follow-on errors. + type = convertAutoToAny(declaredType); + } + if (flags & 1024 /* Shared */) { + // Record visited node and the associated type in the cache. + sharedFlowNodes[sharedFlowCount] = flow; + sharedFlowTypes[sharedFlowCount] = type; + sharedFlowCount++; + } + flowDepth--; + return type; + } + } + function getTypeAtFlowAssignment(flow) { + var node = flow.node; + // Assignments only narrow the computed type if the declared type is a union type. Thus, we + // only need to evaluate the assigned type if the declared type is a union type. + if (isMatchingReference(reference, node)) { + if (ts.getAssignmentTargetKind(node) === 2 /* Compound */) { + var flowType = getTypeAtFlowNode(flow.antecedent); + return createFlowType(getBaseTypeOfLiteralType(getTypeFromFlowType(flowType)), isIncomplete(flowType)); + } + if (declaredType === autoType || declaredType === autoArrayType) { + if (isEmptyArrayAssignment(node)) { + return getEvolvingArrayType(neverType); + } + var assignedType = getBaseTypeOfLiteralType(getInitialOrAssignedType(node, reference)); + return isTypeAssignableTo(assignedType, declaredType) ? assignedType : anyArrayType; + } + if (declaredType.flags & 1048576 /* Union */) { + return getAssignmentReducedType(declaredType, getInitialOrAssignedType(node, reference)); + } + return declaredType; + } + // We didn't have a direct match. However, if the reference is a dotted name, this + // may be an assignment to a left hand part of the reference. For example, for a + // reference 'x.y.z', we may be at an assignment to 'x.y' or 'x'. In that case, + // return the declared type. + if (containsMatchingReference(reference, node)) { + // A matching dotted name might also be an expando property on a function *expression*, + // in which case we continue control flow analysis back to the function's declaration + if (ts.isVariableDeclaration(node) && (ts.isInJSFile(node) || ts.isVarConst(node))) { + var init = ts.getDeclaredExpandoInitializer(node); + if (init && (init.kind === 196 /* FunctionExpression */ || init.kind === 197 /* ArrowFunction */)) { + return getTypeAtFlowNode(flow.antecedent); + } + } + return declaredType; + } + // for (const _ in ref) acts as a nonnull on ref + if (ts.isVariableDeclaration(node) && node.parent.parent.kind === 226 /* ForInStatement */ && isMatchingReference(reference, node.parent.parent.expression)) { + return getNonNullableTypeIfNeeded(getTypeFromFlowType(getTypeAtFlowNode(flow.antecedent))); + } + // Assignment doesn't affect reference + return undefined; + } + function getTypeAtFlowArrayMutation(flow) { + if (declaredType === autoType || declaredType === autoArrayType) { + var node = flow.node; + var expr = node.kind === 191 /* CallExpression */ ? + node.expression.expression : + node.left.expression; + if (isMatchingReference(reference, getReferenceCandidate(expr))) { + var flowType = getTypeAtFlowNode(flow.antecedent); + var type = getTypeFromFlowType(flowType); + if (ts.getObjectFlags(type) & 256 /* EvolvingArray */) { + var evolvedType_1 = type; + if (node.kind === 191 /* CallExpression */) { + for (var _i = 0, _a = node.arguments; _i < _a.length; _i++) { + var arg = _a[_i]; + evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, arg); + } + } + else { + // We must get the context free expression type so as to not recur in an uncached fashion on the LHS (which causes exponential blowup in compile time) + var indexType = getContextFreeTypeOfExpression(node.left.argumentExpression); + if (isTypeAssignableToKind(indexType, 296 /* NumberLike */)) { + evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, node.right); + } + } + return evolvedType_1 === type ? flowType : createFlowType(evolvedType_1, isIncomplete(flowType)); + } + return flowType; + } + } + return undefined; + } + function getTypeAtFlowCondition(flow) { + var flowType = getTypeAtFlowNode(flow.antecedent); + var type = getTypeFromFlowType(flowType); + if (type.flags & 131072 /* Never */) { + return flowType; + } + // If we have an antecedent type (meaning we're reachable in some way), we first + // attempt to narrow the antecedent type. If that produces the never type, and if + // the antecedent type is incomplete (i.e. a transient type in a loop), then we + // take the type guard as an indication that control *could* reach here once we + // have the complete type. We proceed by switching to the silent never type which + // doesn't report errors when operators are applied to it. Note that this is the + // *only* place a silent never type is ever generated. + var assumeTrue = (flow.flags & 32 /* TrueCondition */) !== 0; + var nonEvolvingType = finalizeEvolvingArrayType(type); + var narrowedType = narrowType(nonEvolvingType, flow.expression, assumeTrue); + if (narrowedType === nonEvolvingType) { + return flowType; + } + var incomplete = isIncomplete(flowType); + var resultType = incomplete && narrowedType.flags & 131072 /* Never */ ? silentNeverType : narrowedType; + return createFlowType(resultType, incomplete); + } + function getTypeAtSwitchClause(flow) { + var expr = flow.switchStatement.expression; + if (containsMatchingReferenceDiscriminant(reference, expr)) { + return declaredType; + } + var flowType = getTypeAtFlowNode(flow.antecedent); + var type = getTypeFromFlowType(flowType); + if (isMatchingReference(reference, expr)) { + type = narrowTypeBySwitchOnDiscriminant(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); + } + else if (isMatchingReferenceDiscriminant(expr, type)) { + type = narrowTypeByDiscriminant(type, expr, function (t) { return narrowTypeBySwitchOnDiscriminant(t, flow.switchStatement, flow.clauseStart, flow.clauseEnd); }); + } + else if (expr.kind === 199 /* TypeOfExpression */ && isMatchingReference(reference, expr.expression)) { + type = narrowBySwitchOnTypeOf(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); + } + return createFlowType(type, isIncomplete(flowType)); + } + function getTypeAtFlowBranchLabel(flow) { + var antecedentTypes = []; + var subtypeReduction = false; + var seenIncomplete = false; + for (var _i = 0, _a = flow.antecedents; _i < _a.length; _i++) { + var antecedent = _a[_i]; + if (antecedent.flags & 2048 /* PreFinally */ && antecedent.lock.locked) { + // if flow correspond to branch from pre-try to finally and this branch is locked - this means that + // we initially have started following the flow outside the finally block. + // in this case we should ignore this branch. + continue; + } + var flowType = getTypeAtFlowNode(antecedent); + var type = getTypeFromFlowType(flowType); + // If the type at a particular antecedent path is the declared type and the + // reference is known to always be assigned (i.e. when declared and initial types + // are the same), there is no reason to process more antecedents since the only + // possible outcome is subtypes that will be removed in the final union type anyway. + if (type === declaredType && declaredType === initialType) { + return type; + } + ts.pushIfUnique(antecedentTypes, type); + // If an antecedent type is not a subset of the declared type, we need to perform + // subtype reduction. This happens when a "foreign" type is injected into the control + // flow using the instanceof operator or a user defined type predicate. + if (!isTypeSubsetOf(type, declaredType)) { + subtypeReduction = true; + } + if (isIncomplete(flowType)) { + seenIncomplete = true; + } + } + return createFlowType(getUnionOrEvolvingArrayType(antecedentTypes, subtypeReduction ? 2 /* Subtype */ : 1 /* Literal */), seenIncomplete); + } + function getTypeAtFlowLoopLabel(flow) { + // If we have previously computed the control flow type for the reference at + // this flow loop junction, return the cached type. + var id = getFlowNodeId(flow); + var cache = flowLoopCaches[id] || (flowLoopCaches[id] = ts.createMap()); + if (!key) { + key = getFlowCacheKey(reference); + // No cache key is generated when binding patterns are in unnarrowable situations + if (!key) { + return declaredType; + } + } + var cached = cache.get(key); + if (cached) { + return cached; + } + // If this flow loop junction and reference are already being processed, return + // the union of the types computed for each branch so far, marked as incomplete. + // It is possible to see an empty array in cases where loops are nested and the + // back edge of the outer loop reaches an inner loop that is already being analyzed. + // In such cases we restart the analysis of the inner loop, which will then see + // a non-empty in-process array for the outer loop and eventually terminate because + // the first antecedent of a loop junction is always the non-looping control flow + // path that leads to the top. + for (var i = flowLoopStart; i < flowLoopCount; i++) { + if (flowLoopNodes[i] === flow && flowLoopKeys[i] === key && flowLoopTypes[i].length) { + return createFlowType(getUnionOrEvolvingArrayType(flowLoopTypes[i], 1 /* Literal */), /*incomplete*/ true); + } + } + // Add the flow loop junction and reference to the in-process stack and analyze + // each antecedent code path. + var antecedentTypes = []; + var subtypeReduction = false; + var firstAntecedentType; + flowLoopNodes[flowLoopCount] = flow; + flowLoopKeys[flowLoopCount] = key; + flowLoopTypes[flowLoopCount] = antecedentTypes; + for (var _i = 0, _a = flow.antecedents; _i < _a.length; _i++) { + var antecedent = _a[_i]; + flowLoopCount++; + var flowType = getTypeAtFlowNode(antecedent); + flowLoopCount--; + if (!firstAntecedentType) { + firstAntecedentType = flowType; + } + var type = getTypeFromFlowType(flowType); + // If we see a value appear in the cache it is a sign that control flow analysis + // was restarted and completed by checkExpressionCached. We can simply pick up + // the resulting type and bail out. + var cached_1 = cache.get(key); + if (cached_1) { + return cached_1; + } + ts.pushIfUnique(antecedentTypes, type); + // If an antecedent type is not a subset of the declared type, we need to perform + // subtype reduction. This happens when a "foreign" type is injected into the control + // flow using the instanceof operator or a user defined type predicate. + if (!isTypeSubsetOf(type, declaredType)) { + subtypeReduction = true; + } + // If the type at a particular antecedent path is the declared type there is no + // reason to process more antecedents since the only possible outcome is subtypes + // that will be removed in the final union type anyway. + if (type === declaredType) { + break; + } + } + // The result is incomplete if the first antecedent (the non-looping control flow path) + // is incomplete. + var result = getUnionOrEvolvingArrayType(antecedentTypes, subtypeReduction ? 2 /* Subtype */ : 1 /* Literal */); + if (isIncomplete(firstAntecedentType)) { + return createFlowType(result, /*incomplete*/ true); + } + cache.set(key, result); + return result; + } + function isMatchingReferenceDiscriminant(expr, computedType) { + if (!(computedType.flags & 1048576 /* Union */) || + expr.kind !== 189 /* PropertyAccessExpression */ && expr.kind !== 190 /* ElementAccessExpression */) { + return false; + } + var access = expr; + var name = getAccessedPropertyName(access); + if (!name) { + return false; + } + return isMatchingReference(reference, access.expression) && isDiscriminantProperty(computedType, name); + } + function narrowTypeByDiscriminant(type, access, narrowType) { + var propName = getAccessedPropertyName(access); + if (!propName) { + return type; + } + var propType = getTypeOfPropertyOfType(type, propName); + var narrowedPropType = propType && narrowType(propType); + return propType === narrowedPropType ? type : filterType(type, function (t) { return isTypeComparableTo(getTypeOfPropertyOfType(t, propName), narrowedPropType); }); + } + function narrowTypeByTruthiness(type, expr, assumeTrue) { + if (isMatchingReference(reference, expr)) { + return getTypeWithFacts(type, assumeTrue ? 4194304 /* Truthy */ : 8388608 /* Falsy */); + } + if (isMatchingReferenceDiscriminant(expr, declaredType)) { + return narrowTypeByDiscriminant(type, expr, function (t) { return getTypeWithFacts(t, assumeTrue ? 4194304 /* Truthy */ : 8388608 /* Falsy */); }); + } + if (containsMatchingReferenceDiscriminant(reference, expr)) { + return declaredType; + } + return type; + } + function isTypePresencePossible(type, propName, assumeTrue) { + if (getIndexInfoOfType(type, 0 /* String */)) { + return true; + } + var prop = getPropertyOfType(type, propName); + if (prop) { + return prop.flags & 16777216 /* Optional */ ? true : assumeTrue; + } + return !assumeTrue; + } + function narrowByInKeyword(type, literal, assumeTrue) { + if ((type.flags & (1048576 /* Union */ | 524288 /* Object */)) || (type.flags & 262144 /* TypeParameter */ && type.isThisType)) { + var propName_1 = ts.escapeLeadingUnderscores(literal.text); + return filterType(type, function (t) { return isTypePresencePossible(t, propName_1, assumeTrue); }); + } + return type; + } + function narrowTypeByBinaryExpression(type, expr, assumeTrue) { + switch (expr.operatorToken.kind) { + case 59 /* EqualsToken */: + return narrowTypeByTruthiness(type, expr.left, assumeTrue); + case 33 /* EqualsEqualsToken */: + case 34 /* ExclamationEqualsToken */: + case 35 /* EqualsEqualsEqualsToken */: + case 36 /* ExclamationEqualsEqualsToken */: + var operator_1 = expr.operatorToken.kind; + var left_1 = getReferenceCandidate(expr.left); + var right_1 = getReferenceCandidate(expr.right); + if (left_1.kind === 199 /* TypeOfExpression */ && ts.isStringLiteralLike(right_1)) { + return narrowTypeByTypeof(type, left_1, operator_1, right_1, assumeTrue); + } + if (right_1.kind === 199 /* TypeOfExpression */ && ts.isStringLiteralLike(left_1)) { + return narrowTypeByTypeof(type, right_1, operator_1, left_1, assumeTrue); + } + if (isMatchingReference(reference, left_1)) { + return narrowTypeByEquality(type, operator_1, right_1, assumeTrue); + } + if (isMatchingReference(reference, right_1)) { + return narrowTypeByEquality(type, operator_1, left_1, assumeTrue); + } + if (isMatchingReferenceDiscriminant(left_1, declaredType)) { + return narrowTypeByDiscriminant(type, left_1, function (t) { return narrowTypeByEquality(t, operator_1, right_1, assumeTrue); }); + } + if (isMatchingReferenceDiscriminant(right_1, declaredType)) { + return narrowTypeByDiscriminant(type, right_1, function (t) { return narrowTypeByEquality(t, operator_1, left_1, assumeTrue); }); + } + if (containsMatchingReferenceDiscriminant(reference, left_1) || containsMatchingReferenceDiscriminant(reference, right_1)) { + return declaredType; + } + break; + case 94 /* InstanceOfKeyword */: + return narrowTypeByInstanceof(type, expr, assumeTrue); + case 93 /* InKeyword */: + var target = getReferenceCandidate(expr.right); + if (ts.isStringLiteralLike(expr.left) && isMatchingReference(reference, target)) { + return narrowByInKeyword(type, expr.left, assumeTrue); + } + break; + case 27 /* CommaToken */: + return narrowType(type, expr.right, assumeTrue); + } + return type; + } + function narrowTypeByEquality(type, operator, value, assumeTrue) { + if (type.flags & 1 /* Any */) { + return type; + } + if (operator === 34 /* ExclamationEqualsToken */ || operator === 36 /* ExclamationEqualsEqualsToken */) { + assumeTrue = !assumeTrue; + } + var valueType = getTypeOfExpression(value); + if (valueType.flags & 98304 /* Nullable */) { + if (!strictNullChecks) { + return type; + } + var doubleEquals = operator === 33 /* EqualsEqualsToken */ || operator === 34 /* ExclamationEqualsToken */; + var facts = doubleEquals ? + assumeTrue ? 262144 /* EQUndefinedOrNull */ : 2097152 /* NEUndefinedOrNull */ : + valueType.flags & 65536 /* Null */ ? + assumeTrue ? 131072 /* EQNull */ : 1048576 /* NENull */ : + assumeTrue ? 65536 /* EQUndefined */ : 524288 /* NEUndefined */; + return getTypeWithFacts(type, facts); + } + if (type.flags & 67637251 /* NotUnionOrUnit */) { + return type; + } + if (assumeTrue) { + var narrowedType = filterType(type, function (t) { return areTypesComparable(t, valueType); }); + return narrowedType.flags & 131072 /* Never */ ? type : replacePrimitivesWithLiterals(narrowedType, valueType); + } + if (isUnitType(valueType)) { + var regularType_1 = getRegularTypeOfLiteralType(valueType); + return filterType(type, function (t) { return getRegularTypeOfLiteralType(t) !== regularType_1; }); + } + return type; + } + function narrowTypeByTypeof(type, typeOfExpr, operator, literal, assumeTrue) { + // We have '==', '!=', '====', or !==' operator with 'typeof xxx' and string literal operands + var target = getReferenceCandidate(typeOfExpr.expression); + if (!isMatchingReference(reference, target)) { + // For a reference of the form 'x.y', where 'x' has a narrowable declared type, a + // 'typeof x === ...' type guard resets the narrowed type of 'y' to its declared type. + if (containsMatchingReference(reference, target) && hasNarrowableDeclaredType(target)) { + return declaredType; + } + return type; + } + if (operator === 34 /* ExclamationEqualsToken */ || operator === 36 /* ExclamationEqualsEqualsToken */) { + assumeTrue = !assumeTrue; + } + if (type.flags & 1 /* Any */ && literal.text === "function") { + return type; + } + var facts = assumeTrue ? + typeofEQFacts.get(literal.text) || 128 /* TypeofEQHostObject */ : + typeofNEFacts.get(literal.text) || 32768 /* TypeofNEHostObject */; + return getTypeWithFacts(assumeTrue ? mapType(type, narrowTypeForTypeof) : type, facts); + function narrowTypeForTypeof(type) { + if (type.flags & 2 /* Unknown */ && literal.text === "object") { + return getUnionType([nonPrimitiveType, nullType]); + } + // We narrow a non-union type to an exact primitive type if the non-union type + // is a supertype of that primitive type. For example, type 'any' can be narrowed + // to one of the primitive types. + var targetType = literal.text === "function" ? globalFunctionType : typeofTypesByName.get(literal.text); + if (targetType) { + if (isTypeSubtypeOf(type, targetType)) { + return type; + } + if (isTypeSubtypeOf(targetType, type)) { + return targetType; + } + if (type.flags & 63176704 /* Instantiable */) { + var constraint = getBaseConstraintOfType(type) || anyType; + if (isTypeSubtypeOf(targetType, constraint)) { + return getIntersectionType([type, targetType]); + } + } + } + return type; + } + } + function narrowTypeBySwitchOnDiscriminant(type, switchStatement, clauseStart, clauseEnd) { + // We only narrow if all case expressions specify values with unit types + var switchTypes = getSwitchClauseTypes(switchStatement); + if (!switchTypes.length) { + return type; + } + var clauseTypes = switchTypes.slice(clauseStart, clauseEnd); + var hasDefaultClause = clauseStart === clauseEnd || ts.contains(clauseTypes, neverType); + var discriminantType = getUnionType(clauseTypes); + var caseType = discriminantType.flags & 131072 /* Never */ ? neverType : + replacePrimitivesWithLiterals(filterType(type, function (t) { return areTypesComparable(discriminantType, t); }), discriminantType); + if (!hasDefaultClause) { + return caseType; + } + var defaultType = filterType(type, function (t) { return !(isUnitType(t) && ts.contains(switchTypes, getRegularTypeOfLiteralType(t))); }); + return caseType.flags & 131072 /* Never */ ? defaultType : getUnionType([caseType, defaultType]); + } + function getImpliedTypeFromTypeofCase(type, text) { + switch (text) { + case "function": + return type.flags & 1 /* Any */ ? type : globalFunctionType; + case "object": + return type.flags & 2 /* Unknown */ ? getUnionType([nonPrimitiveType, nullType]) : type; + default: + return typeofTypesByName.get(text) || type; + } + } + function narrowTypeForTypeofSwitch(candidate) { + return function (type) { + if (isTypeSubtypeOf(candidate, type)) { + return candidate; + } + if (type.flags & 63176704 /* Instantiable */) { + var constraint = getBaseConstraintOfType(type) || anyType; + if (isTypeSubtypeOf(candidate, constraint)) { + return getIntersectionType([type, candidate]); + } + } + return type; + }; + } + function narrowBySwitchOnTypeOf(type, switchStatement, clauseStart, clauseEnd) { + var switchWitnesses = getSwitchClauseTypeOfWitnesses(switchStatement); + if (!switchWitnesses.length) { + return type; + } + // Equal start and end denotes implicit fallthrough; undefined marks explicit default clause + var defaultCaseLocation = ts.findIndex(switchWitnesses, function (elem) { return elem === undefined; }); + var hasDefaultClause = clauseStart === clauseEnd || (defaultCaseLocation >= clauseStart && defaultCaseLocation < clauseEnd); + var clauseWitnesses; + var switchFacts; + if (defaultCaseLocation > -1) { + // We no longer need the undefined denoting an + // explicit default case. Remove the undefined and + // fix-up clauseStart and clauseEnd. This means + // that we don't have to worry about undefined + // in the witness array. + var witnesses = switchWitnesses.filter(function (witness) { return witness !== undefined; }); + // The adjusted clause start and end after removing the `default` statement. + var fixedClauseStart = defaultCaseLocation < clauseStart ? clauseStart - 1 : clauseStart; + var fixedClauseEnd = defaultCaseLocation < clauseEnd ? clauseEnd - 1 : clauseEnd; + clauseWitnesses = witnesses.slice(fixedClauseStart, fixedClauseEnd); + switchFacts = getFactsFromTypeofSwitch(fixedClauseStart, fixedClauseEnd, witnesses, hasDefaultClause); + } + else { + clauseWitnesses = switchWitnesses.slice(clauseStart, clauseEnd); + switchFacts = getFactsFromTypeofSwitch(clauseStart, clauseEnd, switchWitnesses, hasDefaultClause); + } + if (hasDefaultClause) { + return filterType(type, function (t) { return (getTypeFacts(t) & switchFacts) === switchFacts; }); + } + /* + The implied type is the raw type suggested by a + value being caught in this clause. + + When the clause contains a default case we ignore + the implied type and try to narrow using any facts + we can learn: see `switchFacts`. + + Example: + switch (typeof x) { + case 'number': + case 'string': break; + default: break; + case 'number': + case 'boolean': break + } + + In the first clause (case `number` and `string`) the + implied type is number | string. + + In the default clause we de not compute an implied type. + + In the third clause (case `number` and `boolean`) + the naive implied type is number | boolean, however + we use the type facts to narrow the implied type to + boolean. We know that number cannot be selected + because it is caught in the first clause. + */ + var impliedType = getTypeWithFacts(getUnionType(clauseWitnesses.map(function (text) { return getImpliedTypeFromTypeofCase(type, text); })), switchFacts); + if (impliedType.flags & 1048576 /* Union */) { + impliedType = getAssignmentReducedType(impliedType, getBaseConstraintOrType(type)); + } + return getTypeWithFacts(mapType(type, narrowTypeForTypeofSwitch(impliedType)), switchFacts); + } + function narrowTypeByInstanceof(type, expr, assumeTrue) { + var left = getReferenceCandidate(expr.left); + if (!isMatchingReference(reference, left)) { + // For a reference of the form 'x.y', where 'x' has a narrowable declared type, an + // 'x instanceof T' type guard resets the narrowed type of 'y' to its declared type. + if (containsMatchingReference(reference, left) && hasNarrowableDeclaredType(left)) { + return declaredType; + } + return type; + } + // Check that right operand is a function type with a prototype property + var rightType = getTypeOfExpression(expr.right); + if (!isTypeDerivedFrom(rightType, globalFunctionType)) { + return type; + } + var targetType; + var prototypeProperty = getPropertyOfType(rightType, "prototype"); + if (prototypeProperty) { + // Target type is type of the prototype property + var prototypePropertyType = getTypeOfSymbol(prototypeProperty); + if (!isTypeAny(prototypePropertyType)) { + targetType = prototypePropertyType; + } + } + // Don't narrow from 'any' if the target type is exactly 'Object' or 'Function' + if (isTypeAny(type) && (targetType === globalObjectType || targetType === globalFunctionType)) { + return type; + } + if (!targetType) { + var constructSignatures = getSignaturesOfType(rightType, 1 /* Construct */); + targetType = constructSignatures.length ? + getUnionType(ts.map(constructSignatures, function (signature) { return getReturnTypeOfSignature(getErasedSignature(signature)); })) : + emptyObjectType; + } + return getNarrowedType(type, targetType, assumeTrue, isTypeDerivedFrom); + } + function getNarrowedType(type, candidate, assumeTrue, isRelated) { + if (!assumeTrue) { + return filterType(type, function (t) { return !isRelated(t, candidate); }); + } + // If the current type is a union type, remove all constituents that couldn't be instances of + // the candidate type. If one or more constituents remain, return a union of those. + if (type.flags & 1048576 /* Union */) { + var assignableType = filterType(type, function (t) { return isRelated(t, candidate); }); + if (!(assignableType.flags & 131072 /* Never */)) { + return assignableType; + } + } + // If the candidate type is a subtype of the target type, narrow to the candidate type. + // Otherwise, if the target type is assignable to the candidate type, keep the target type. + // Otherwise, if the candidate type is assignable to the target type, narrow to the candidate + // type. Otherwise, the types are completely unrelated, so narrow to an intersection of the + // two types. + return isTypeSubtypeOf(candidate, type) ? candidate : + isTypeAssignableTo(type, candidate) ? type : + isTypeAssignableTo(candidate, type) ? candidate : + getIntersectionType([type, candidate]); + } + function narrowTypeByTypePredicate(type, callExpression, assumeTrue) { + if (!hasMatchingArgument(callExpression, reference) || !maybeTypePredicateCall(callExpression)) { + return type; + } + var signature = getResolvedSignature(callExpression); + var predicate = getTypePredicateOfSignature(signature); + if (!predicate) { + return type; + } + // Don't narrow from 'any' if the predicate type is exactly 'Object' or 'Function' + if (isTypeAny(type) && (predicate.type === globalObjectType || predicate.type === globalFunctionType)) { + return type; + } + if (ts.isIdentifierTypePredicate(predicate)) { + var predicateArgument = callExpression.arguments[predicate.parameterIndex - (signature.thisParameter ? 1 : 0)]; + if (predicateArgument) { + if (isMatchingReference(reference, predicateArgument)) { + return getNarrowedType(type, predicate.type, assumeTrue, isTypeSubtypeOf); + } + if (containsMatchingReference(reference, predicateArgument)) { + return declaredType; + } + } + } + else { + var invokedExpression = ts.skipParentheses(callExpression.expression); + if (invokedExpression.kind === 190 /* ElementAccessExpression */ || invokedExpression.kind === 189 /* PropertyAccessExpression */) { + var accessExpression = invokedExpression; + var possibleReference = ts.skipParentheses(accessExpression.expression); + if (isMatchingReference(reference, possibleReference)) { + return getNarrowedType(type, predicate.type, assumeTrue, isTypeSubtypeOf); + } + if (containsMatchingReference(reference, possibleReference)) { + return declaredType; + } + } + } + return type; + } + // Narrow the given type based on the given expression having the assumed boolean value. The returned type + // will be a subtype or the same type as the argument. + function narrowType(type, expr, assumeTrue) { + switch (expr.kind) { + case 72 /* Identifier */: + case 100 /* ThisKeyword */: + case 98 /* SuperKeyword */: + case 189 /* PropertyAccessExpression */: + case 190 /* ElementAccessExpression */: + return narrowTypeByTruthiness(type, expr, assumeTrue); + case 191 /* CallExpression */: + return narrowTypeByTypePredicate(type, expr, assumeTrue); + case 195 /* ParenthesizedExpression */: + return narrowType(type, expr.expression, assumeTrue); + case 204 /* BinaryExpression */: + return narrowTypeByBinaryExpression(type, expr, assumeTrue); + case 202 /* PrefixUnaryExpression */: + if (expr.operator === 52 /* ExclamationToken */) { + return narrowType(type, expr.operand, !assumeTrue); + } + break; + } + return type; + } + } + function getTypeOfSymbolAtLocation(symbol, location) { + symbol = symbol.exportSymbol || symbol; + // If we have an identifier or a property access at the given location, if the location is + // an dotted name expression, and if the location is not an assignment target, obtain the type + // of the expression (which will reflect control flow analysis). If the expression indeed + // resolved to the given symbol, return the narrowed type. + if (location.kind === 72 /* Identifier */) { + if (ts.isRightSideOfQualifiedNameOrPropertyAccess(location)) { + location = location.parent; + } + if (ts.isExpressionNode(location) && !ts.isAssignmentTarget(location)) { + var type = getTypeOfExpression(location); + if (getExportSymbolOfValueSymbolIfExported(getNodeLinks(location).resolvedSymbol) === symbol) { + return type; + } + } + } + // The location isn't a reference to the given symbol, meaning we're being asked + // a hypothetical question of what type the symbol would have if there was a reference + // to it at the given location. Since we have no control flow information for the + // hypothetical reference (control flow information is created and attached by the + // binder), we simply return the declared type of the symbol. + return getTypeOfSymbol(symbol); + } + function getControlFlowContainer(node) { + return ts.findAncestor(node.parent, function (node) { + return ts.isFunctionLike(node) && !ts.getImmediatelyInvokedFunctionExpression(node) || + node.kind === 245 /* ModuleBlock */ || + node.kind === 279 /* SourceFile */ || + node.kind === 154 /* PropertyDeclaration */; + }); + } + // Check if a parameter is assigned anywhere within its declaring function. + function isParameterAssigned(symbol) { + var func = ts.getRootDeclaration(symbol.valueDeclaration).parent; + var links = getNodeLinks(func); + if (!(links.flags & 8388608 /* AssignmentsMarked */)) { + links.flags |= 8388608 /* AssignmentsMarked */; + if (!hasParentWithAssignmentsMarked(func)) { + markParameterAssignments(func); + } + } + return symbol.isAssigned || false; + } + function hasParentWithAssignmentsMarked(node) { + return !!ts.findAncestor(node.parent, function (node) { return ts.isFunctionLike(node) && !!(getNodeLinks(node).flags & 8388608 /* AssignmentsMarked */); }); + } + function markParameterAssignments(node) { + if (node.kind === 72 /* Identifier */) { + if (ts.isAssignmentTarget(node)) { + var symbol = getResolvedSymbol(node); + if (symbol.valueDeclaration && ts.getRootDeclaration(symbol.valueDeclaration).kind === 151 /* Parameter */) { + symbol.isAssigned = true; + } + } + } + else { + ts.forEachChild(node, markParameterAssignments); + } + } + function isConstVariable(symbol) { + return symbol.flags & 3 /* Variable */ && (getDeclarationNodeFlagsFromSymbol(symbol) & 2 /* Const */) !== 0 && getTypeOfSymbol(symbol) !== autoArrayType; + } + /** remove undefined from the annotated type of a parameter when there is an initializer (that doesn't include undefined) */ + function removeOptionalityFromDeclaredType(declaredType, declaration) { + var annotationIncludesUndefined = strictNullChecks && + declaration.kind === 151 /* Parameter */ && + declaration.initializer && + getFalsyFlags(declaredType) & 32768 /* Undefined */ && + !(getFalsyFlags(checkExpression(declaration.initializer)) & 32768 /* Undefined */); + return annotationIncludesUndefined ? getTypeWithFacts(declaredType, 524288 /* NEUndefined */) : declaredType; + } + function isConstraintPosition(node) { + var parent = node.parent; + return parent.kind === 189 /* PropertyAccessExpression */ || + parent.kind === 191 /* CallExpression */ && parent.expression === node || + parent.kind === 190 /* ElementAccessExpression */ && parent.expression === node || + parent.kind === 186 /* BindingElement */ && parent.name === node && !!parent.initializer; + } + function typeHasNullableConstraint(type) { + return type.flags & 58982400 /* InstantiableNonPrimitive */ && maybeTypeOfKind(getBaseConstraintOfType(type) || emptyObjectType, 98304 /* Nullable */); + } + function getConstraintForLocation(type, node) { + // When a node is the left hand expression of a property access, element access, or call expression, + // and the type of the node includes type variables with constraints that are nullable, we fetch the + // apparent type of the node *before* performing control flow analysis such that narrowings apply to + // the constraint type. + if (type && isConstraintPosition(node) && forEachType(type, typeHasNullableConstraint)) { + return mapType(getWidenedType(type), getBaseConstraintOrType); + } + return type; + } + function markAliasReferenced(symbol, location) { + if (isNonLocalAlias(symbol, /*excludes*/ 67220415 /* Value */) && !isInTypeQuery(location) && !isConstEnumOrConstEnumOnlyModule(resolveAlias(symbol))) { + markAliasSymbolAsReferenced(symbol); + } + } + function checkIdentifier(node) { + var symbol = getResolvedSymbol(node); + if (symbol === unknownSymbol) { + return errorType; + } + // As noted in ECMAScript 6 language spec, arrow functions never have an arguments objects. + // Although in down-level emit of arrow function, we emit it using function expression which means that + // arguments objects will be bound to the inner object; emitting arrow function natively in ES6, arguments objects + // will be bound to non-arrow function that contain this arrow function. This results in inconsistent behavior. + // To avoid that we will give an error to users if they use arguments objects in arrow function so that they + // can explicitly bound arguments objects + if (symbol === argumentsSymbol) { + var container = ts.getContainingFunction(node); + if (languageVersion < 2 /* ES2015 */) { + if (container.kind === 197 /* ArrowFunction */) { + error(node, ts.Diagnostics.The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_standard_function_expression); + } + else if (ts.hasModifier(container, 256 /* Async */)) { + error(node, ts.Diagnostics.The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_using_a_standard_function_or_method); + } + } + getNodeLinks(container).flags |= 8192 /* CaptureArguments */; + return getTypeOfSymbol(symbol); + } + // We should only mark aliases as referenced if there isn't a local value declaration + // for the symbol. Also, don't mark any property access expression LHS - checkPropertyAccessExpression will handle that + if (!(node.parent && ts.isPropertyAccessExpression(node.parent) && node.parent.expression === node)) { + markAliasReferenced(symbol, node); + } + var localOrExportSymbol = getExportSymbolOfValueSymbolIfExported(symbol); + var declaration = localOrExportSymbol.valueDeclaration; + if (localOrExportSymbol.flags & 32 /* Class */) { + // Due to the emit for class decorators, any reference to the class from inside of the class body + // must instead be rewritten to point to a temporary variable to avoid issues with the double-bind + // behavior of class names in ES6. + if (declaration.kind === 240 /* ClassDeclaration */ + && ts.nodeIsDecorated(declaration)) { + var container = ts.getContainingClass(node); + while (container !== undefined) { + if (container === declaration && container.name !== node) { + getNodeLinks(declaration).flags |= 16777216 /* ClassWithConstructorReference */; + getNodeLinks(node).flags |= 33554432 /* ConstructorReferenceInClass */; + break; + } + container = ts.getContainingClass(container); + } + } + else if (declaration.kind === 209 /* ClassExpression */) { + // When we emit a class expression with static members that contain a reference + // to the constructor in the initializer, we will need to substitute that + // binding with an alias as the class name is not in scope. + var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); + while (container.kind !== 279 /* SourceFile */) { + if (container.parent === declaration) { + if (container.kind === 154 /* PropertyDeclaration */ && ts.hasModifier(container, 32 /* Static */)) { + getNodeLinks(declaration).flags |= 16777216 /* ClassWithConstructorReference */; + getNodeLinks(node).flags |= 33554432 /* ConstructorReferenceInClass */; + } + break; + } + container = ts.getThisContainer(container, /*includeArrowFunctions*/ false); + } + } + } + checkNestedBlockScopedBinding(node, symbol); + var type = getConstraintForLocation(getTypeOfSymbol(localOrExportSymbol), node); + var assignmentKind = ts.getAssignmentTargetKind(node); + if (assignmentKind) { + if (!(localOrExportSymbol.flags & 3 /* Variable */) && + !(ts.isInJSFile(node) && localOrExportSymbol.flags & 512 /* ValueModule */)) { + error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_not_a_variable, symbolToString(symbol)); + return errorType; + } + if (isReadonlySymbol(localOrExportSymbol)) { + if (localOrExportSymbol.flags & 3 /* Variable */) { + error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant, symbolToString(symbol)); + } + else { + error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, symbolToString(symbol)); + } + return errorType; + } + } + var isAlias = localOrExportSymbol.flags & 2097152 /* Alias */; + // We only narrow variables and parameters occurring in a non-assignment position. For all other + // entities we simply return the declared type. + if (localOrExportSymbol.flags & 3 /* Variable */) { + if (assignmentKind === 1 /* Definite */) { + return type; + } + } + else if (isAlias) { + declaration = ts.find(symbol.declarations, isSomeImportDeclaration); + } + else { + return type; + } + if (!declaration) { + return type; + } + // The declaration container is the innermost function that encloses the declaration of the variable + // or parameter. The flow container is the innermost function starting with which we analyze the control + // flow graph to determine the control flow based type. + var isParameter = ts.getRootDeclaration(declaration).kind === 151 /* Parameter */; + var declarationContainer = getControlFlowContainer(declaration); + var flowContainer = getControlFlowContainer(node); + var isOuterVariable = flowContainer !== declarationContainer; + var isSpreadDestructuringAssignmentTarget = node.parent && node.parent.parent && ts.isSpreadAssignment(node.parent) && isDestructuringAssignmentTarget(node.parent.parent); + var isModuleExports = symbol.flags & 134217728 /* ModuleExports */; + // When the control flow originates in a function expression or arrow function and we are referencing + // a const variable or parameter from an outer function, we extend the origin of the control flow + // analysis to include the immediately enclosing function. + while (flowContainer !== declarationContainer && (flowContainer.kind === 196 /* FunctionExpression */ || + flowContainer.kind === 197 /* ArrowFunction */ || ts.isObjectLiteralOrClassExpressionMethod(flowContainer)) && + (isConstVariable(localOrExportSymbol) || isParameter && !isParameterAssigned(localOrExportSymbol))) { + flowContainer = getControlFlowContainer(flowContainer); + } + // We only look for uninitialized variables in strict null checking mode, and only when we can analyze + // the entire control flow graph from the variable's declaration (i.e. when the flow container and + // declaration container are the same). + var assumeInitialized = isParameter || isAlias || isOuterVariable || isSpreadDestructuringAssignmentTarget || isModuleExports || + type !== autoType && type !== autoArrayType && (!strictNullChecks || (type.flags & 3 /* AnyOrUnknown */) !== 0 || + isInTypeQuery(node) || node.parent.kind === 257 /* ExportSpecifier */) || + node.parent.kind === 213 /* NonNullExpression */ || + declaration.kind === 237 /* VariableDeclaration */ && declaration.exclamationToken || + declaration.flags & 4194304 /* Ambient */; + var initialType = assumeInitialized ? (isParameter ? removeOptionalityFromDeclaredType(type, declaration) : type) : + type === autoType || type === autoArrayType ? undefinedType : + getOptionalType(type); + var flowType = getFlowTypeOfReference(node, type, initialType, flowContainer, !assumeInitialized); + // A variable is considered uninitialized when it is possible to analyze the entire control flow graph + // from declaration to use, and when the variable's declared type doesn't include undefined but the + // control flow based type does include undefined. + if (!isEvolvingArrayOperationTarget(node) && (type === autoType || type === autoArrayType)) { + if (flowType === autoType || flowType === autoArrayType) { + if (noImplicitAny) { + error(ts.getNameOfDeclaration(declaration), ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined, symbolToString(symbol), typeToString(flowType)); + error(node, ts.Diagnostics.Variable_0_implicitly_has_an_1_type, symbolToString(symbol), typeToString(flowType)); + } + return convertAutoToAny(flowType); + } + } + else if (!assumeInitialized && !(getFalsyFlags(type) & 32768 /* Undefined */) && getFalsyFlags(flowType) & 32768 /* Undefined */) { + error(node, ts.Diagnostics.Variable_0_is_used_before_being_assigned, symbolToString(symbol)); + // Return the declared type to reduce follow-on errors + return type; + } + return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType; + } + function isInsideFunction(node, threshold) { + return !!ts.findAncestor(node, function (n) { return n === threshold ? "quit" : ts.isFunctionLike(n); }); + } + function getPartOfForStatementContainingNode(node, container) { + return ts.findAncestor(node, function (n) { return n === container ? "quit" : n === container.initializer || n === container.condition || n === container.incrementor || n === container.statement; }); + } + function checkNestedBlockScopedBinding(node, symbol) { + if (languageVersion >= 2 /* ES2015 */ || + (symbol.flags & (2 /* BlockScopedVariable */ | 32 /* Class */)) === 0 || + symbol.valueDeclaration.parent.kind === 274 /* CatchClause */) { + return; + } + // 1. walk from the use site up to the declaration and check + // if there is anything function like between declaration and use-site (is binding/class is captured in function). + // 2. walk from the declaration up to the boundary of lexical environment and check + // if there is an iteration statement in between declaration and boundary (is binding/class declared inside iteration statement) + var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); + var usedInFunction = isInsideFunction(node.parent, container); + var current = container; + var containedInIterationStatement = false; + while (current && !ts.nodeStartsNewLexicalEnvironment(current)) { + if (ts.isIterationStatement(current, /*lookInLabeledStatements*/ false)) { + containedInIterationStatement = true; + break; + } + current = current.parent; + } + if (containedInIterationStatement) { + if (usedInFunction) { + // mark iteration statement as containing block-scoped binding captured in some function + var capturesBlockScopeBindingInLoopBody = true; + if (ts.isForStatement(container) && + ts.getAncestor(symbol.valueDeclaration, 238 /* VariableDeclarationList */).parent === container) { + var part = getPartOfForStatementContainingNode(node.parent, container); + if (part) { + var links = getNodeLinks(part); + links.flags |= 131072 /* ContainsCapturedBlockScopeBinding */; + var capturedBindings = links.capturedBlockScopeBindings || (links.capturedBlockScopeBindings = []); + ts.pushIfUnique(capturedBindings, symbol); + if (part === container.initializer) { + capturesBlockScopeBindingInLoopBody = false; // Initializer is outside of loop body + } + } + } + if (capturesBlockScopeBindingInLoopBody) { + getNodeLinks(current).flags |= 65536 /* LoopWithCapturedBlockScopedBinding */; + } + } + // mark variables that are declared in loop initializer and reassigned inside the body of ForStatement. + // if body of ForStatement will be converted to function then we'll need a extra machinery to propagate reassigned values back. + if (container.kind === 225 /* ForStatement */ && + ts.getAncestor(symbol.valueDeclaration, 238 /* VariableDeclarationList */).parent === container && + isAssignedInBodyOfForStatement(node, container)) { + getNodeLinks(symbol.valueDeclaration).flags |= 4194304 /* NeedsLoopOutParameter */; + } + // set 'declared inside loop' bit on the block-scoped binding + getNodeLinks(symbol.valueDeclaration).flags |= 524288 /* BlockScopedBindingInLoop */; + } + if (usedInFunction) { + getNodeLinks(symbol.valueDeclaration).flags |= 262144 /* CapturedBlockScopedBinding */; + } + } + function isBindingCapturedByNode(node, decl) { + var links = getNodeLinks(node); + return !!links && ts.contains(links.capturedBlockScopeBindings, getSymbolOfNode(decl)); + } + function isAssignedInBodyOfForStatement(node, container) { + // skip parenthesized nodes + var current = node; + while (current.parent.kind === 195 /* ParenthesizedExpression */) { + current = current.parent; + } + // check if node is used as LHS in some assignment expression + var isAssigned = false; + if (ts.isAssignmentTarget(current)) { + isAssigned = true; + } + else if ((current.parent.kind === 202 /* PrefixUnaryExpression */ || current.parent.kind === 203 /* PostfixUnaryExpression */)) { + var expr = current.parent; + isAssigned = expr.operator === 44 /* PlusPlusToken */ || expr.operator === 45 /* MinusMinusToken */; + } + if (!isAssigned) { + return false; + } + // at this point we know that node is the target of assignment + // now check that modification happens inside the statement part of the ForStatement + return !!ts.findAncestor(current, function (n) { return n === container ? "quit" : n === container.statement; }); + } + function captureLexicalThis(node, container) { + getNodeLinks(node).flags |= 2 /* LexicalThis */; + if (container.kind === 154 /* PropertyDeclaration */ || container.kind === 157 /* Constructor */) { + var classNode = container.parent; + getNodeLinks(classNode).flags |= 4 /* CaptureThis */; + } + else { + getNodeLinks(container).flags |= 4 /* CaptureThis */; + } + } + function findFirstSuperCall(n) { + if (ts.isSuperCall(n)) { + return n; + } + else if (ts.isFunctionLike(n)) { + return undefined; + } + return ts.forEachChild(n, findFirstSuperCall); + } + /** + * Return a cached result if super-statement is already found. + * Otherwise, find a super statement in a given constructor function and cache the result in the node-links of the constructor + * + * @param constructor constructor-function to look for super statement + */ + function getSuperCallInConstructor(constructor) { + var links = getNodeLinks(constructor); + // Only trying to find super-call if we haven't yet tried to find one. Once we try, we will record the result + if (links.hasSuperCall === undefined) { + links.superCall = findFirstSuperCall(constructor.body); + links.hasSuperCall = links.superCall ? true : false; + } + return links.superCall; + } + /** + * Check if the given class-declaration extends null then return true. + * Otherwise, return false + * @param classDecl a class declaration to check if it extends null + */ + function classDeclarationExtendsNull(classDecl) { + var classSymbol = getSymbolOfNode(classDecl); + var classInstanceType = getDeclaredTypeOfSymbol(classSymbol); + var baseConstructorType = getBaseConstructorTypeOfClass(classInstanceType); + return baseConstructorType === nullWideningType; + } + function checkThisBeforeSuper(node, container, diagnosticMessage) { + var containingClassDecl = container.parent; + var baseTypeNode = ts.getEffectiveBaseTypeNode(containingClassDecl); + // If a containing class does not have extends clause or the class extends null + // skip checking whether super statement is called before "this" accessing. + if (baseTypeNode && !classDeclarationExtendsNull(containingClassDecl)) { + var superCall = getSuperCallInConstructor(container); + // We should give an error in the following cases: + // - No super-call + // - "this" is accessing before super-call. + // i.e super(this) + // this.x; super(); + // We want to make sure that super-call is done before accessing "this" so that + // "this" is not accessed as a parameter of the super-call. + if (!superCall || superCall.end > node.pos) { + // In ES6, super inside constructor of class-declaration has to precede "this" accessing + error(node, diagnosticMessage); + } + } + } + function checkThisExpression(node) { + // Stop at the first arrow function so that we can + // tell whether 'this' needs to be captured. + var container = ts.getThisContainer(node, /* includeArrowFunctions */ true); + var capturedByArrowFunction = false; + if (container.kind === 157 /* Constructor */) { + checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class); + } + // Now skip arrow functions to get the "real" owner of 'this'. + if (container.kind === 197 /* ArrowFunction */) { + container = ts.getThisContainer(container, /* includeArrowFunctions */ false); + capturedByArrowFunction = true; + } + switch (container.kind) { + case 244 /* ModuleDeclaration */: + error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_module_or_namespace_body); + // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks + break; + case 243 /* EnumDeclaration */: + error(node, ts.Diagnostics.this_cannot_be_referenced_in_current_location); + // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks + break; + case 157 /* Constructor */: + if (isInConstructorArgumentInitializer(node, container)) { + error(node, ts.Diagnostics.this_cannot_be_referenced_in_constructor_arguments); + // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks + } + break; + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + if (ts.hasModifier(container, 32 /* Static */)) { + error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_static_property_initializer); + // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks + } + break; + case 149 /* ComputedPropertyName */: + error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_computed_property_name); + break; + } + // When targeting es6, mark that we'll need to capture `this` in its lexically bound scope. + if (capturedByArrowFunction && languageVersion < 2 /* ES2015 */) { + captureLexicalThis(node, container); + } + var type = tryGetThisTypeAt(node, container); + if (!type && noImplicitThis) { + // With noImplicitThis, functions may not reference 'this' if it has type 'any' + var diag = error(node, capturedByArrowFunction && container.kind === 279 /* SourceFile */ ? + ts.Diagnostics.The_containing_arrow_function_captures_the_global_value_of_this_which_implicitly_has_type_any : + ts.Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation); + if (!ts.isSourceFile(container)) { + var outsideThis = tryGetThisTypeAt(container); + if (outsideThis) { + addRelatedInfo(diag, ts.createDiagnosticForNode(container, ts.Diagnostics.An_outer_value_of_this_is_shadowed_by_this_container)); + } + } + } + return type || anyType; + } + function tryGetThisTypeAt(node, container) { + if (container === void 0) { container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); } + var isInJS = ts.isInJSFile(node); + if (ts.isFunctionLike(container) && + (!isInParameterInitializerBeforeContainingFunction(node) || ts.getThisParameter(container))) { + // Note: a parameter initializer should refer to class-this unless function-this is explicitly annotated. + // If this is a function in a JS file, it might be a class method. + var className = getClassNameFromPrototypeMethod(container); + if (isInJS && className) { + var classSymbol = checkExpression(className).symbol; + if (classSymbol && classSymbol.members && (classSymbol.flags & 16 /* Function */)) { + var classType = getJSClassType(classSymbol); + if (classType) { + return getFlowTypeOfReference(node, classType); + } + } + } + // Check if it's a constructor definition, can be either a variable decl or function decl + // i.e. + // * /** @constructor */ function [name]() { ... } + // * /** @constructor */ var x = function() { ... } + else if (isInJS && + (container.kind === 196 /* FunctionExpression */ || container.kind === 239 /* FunctionDeclaration */) && + ts.getJSDocClassTag(container)) { + var classType = getJSClassType(container.symbol); + if (classType) { + return getFlowTypeOfReference(node, classType); + } + } + var thisType = getThisTypeOfDeclaration(container) || getContextualThisParameterType(container); + if (thisType) { + return getFlowTypeOfReference(node, thisType); + } + } + if (ts.isClassLike(container.parent)) { + var symbol = getSymbolOfNode(container.parent); + var type = ts.hasModifier(container, 32 /* Static */) ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol).thisType; + return getFlowTypeOfReference(node, type); + } + if (isInJS) { + var type = getTypeForThisExpressionFromJSDoc(container); + if (type && type !== errorType) { + return getFlowTypeOfReference(node, type); + } + } + } + function getClassNameFromPrototypeMethod(container) { + // Check if it's the RHS of a x.prototype.y = function [name]() { .... } + if (container.kind === 196 /* FunctionExpression */ && + ts.isBinaryExpression(container.parent) && + ts.getAssignmentDeclarationKind(container.parent) === 3 /* PrototypeProperty */) { + // Get the 'x' of 'x.prototype.y = container' + return container.parent // x.prototype.y = container + .left // x.prototype.y + .expression // x.prototype + .expression; // x + } + // x.prototype = { method() { } } + else if (container.kind === 156 /* MethodDeclaration */ && + container.parent.kind === 188 /* ObjectLiteralExpression */ && + ts.isBinaryExpression(container.parent.parent) && + ts.getAssignmentDeclarationKind(container.parent.parent) === 6 /* Prototype */) { + return container.parent.parent.left.expression; + } + // x.prototype = { method: function() { } } + else if (container.kind === 196 /* FunctionExpression */ && + container.parent.kind === 275 /* PropertyAssignment */ && + container.parent.parent.kind === 188 /* ObjectLiteralExpression */ && + ts.isBinaryExpression(container.parent.parent.parent) && + ts.getAssignmentDeclarationKind(container.parent.parent.parent) === 6 /* Prototype */) { + return container.parent.parent.parent.left.expression; + } + // Object.defineProperty(x, "method", { value: function() { } }); + // Object.defineProperty(x, "method", { set: (x: () => void) => void }); + // Object.defineProperty(x, "method", { get: () => function() { }) }); + else if (container.kind === 196 /* FunctionExpression */ && + ts.isPropertyAssignment(container.parent) && + ts.isIdentifier(container.parent.name) && + (container.parent.name.escapedText === "value" || container.parent.name.escapedText === "get" || container.parent.name.escapedText === "set") && + ts.isObjectLiteralExpression(container.parent.parent) && + ts.isCallExpression(container.parent.parent.parent) && + container.parent.parent.parent.arguments[2] === container.parent.parent && + ts.getAssignmentDeclarationKind(container.parent.parent.parent) === 9 /* ObjectDefinePrototypeProperty */) { + return container.parent.parent.parent.arguments[0].expression; + } + // Object.defineProperty(x, "method", { value() { } }); + // Object.defineProperty(x, "method", { set(x: () => void) {} }); + // Object.defineProperty(x, "method", { get() { return () => {} } }); + else if (ts.isMethodDeclaration(container) && + ts.isIdentifier(container.name) && + (container.name.escapedText === "value" || container.name.escapedText === "get" || container.name.escapedText === "set") && + ts.isObjectLiteralExpression(container.parent) && + ts.isCallExpression(container.parent.parent) && + container.parent.parent.arguments[2] === container.parent && + ts.getAssignmentDeclarationKind(container.parent.parent) === 9 /* ObjectDefinePrototypeProperty */) { + return container.parent.parent.arguments[0].expression; + } + } + function getTypeForThisExpressionFromJSDoc(node) { + var jsdocType = ts.getJSDocType(node); + if (jsdocType && jsdocType.kind === 289 /* JSDocFunctionType */) { + var jsDocFunctionType = jsdocType; + if (jsDocFunctionType.parameters.length > 0 && + jsDocFunctionType.parameters[0].name && + jsDocFunctionType.parameters[0].name.escapedText === "this" /* This */) { + return getTypeFromTypeNode(jsDocFunctionType.parameters[0].type); + } + } + var thisTag = ts.getJSDocThisTag(node); + if (thisTag && thisTag.typeExpression) { + return getTypeFromTypeNode(thisTag.typeExpression); + } + } + function isInConstructorArgumentInitializer(node, constructorDecl) { + return !!ts.findAncestor(node, function (n) { return n === constructorDecl ? "quit" : n.kind === 151 /* Parameter */; }); + } + function checkSuperExpression(node) { + var isCallExpression = node.parent.kind === 191 /* CallExpression */ && node.parent.expression === node; + var container = ts.getSuperContainer(node, /*stopOnFunctions*/ true); + var needToCaptureLexicalThis = false; + // adjust the container reference in case if super is used inside arrow functions with arbitrarily deep nesting + if (!isCallExpression) { + while (container && container.kind === 197 /* ArrowFunction */) { + container = ts.getSuperContainer(container, /*stopOnFunctions*/ true); + needToCaptureLexicalThis = languageVersion < 2 /* ES2015 */; + } + } + var canUseSuperExpression = isLegalUsageOfSuperExpression(container); + var nodeCheckFlag = 0; + if (!canUseSuperExpression) { + // issue more specific error if super is used in computed property name + // class A { foo() { return "1" }} + // class B { + // [super.foo()]() {} + // } + var current = ts.findAncestor(node, function (n) { return n === container ? "quit" : n.kind === 149 /* ComputedPropertyName */; }); + if (current && current.kind === 149 /* ComputedPropertyName */) { + error(node, ts.Diagnostics.super_cannot_be_referenced_in_a_computed_property_name); + } + else if (isCallExpression) { + error(node, ts.Diagnostics.Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors); + } + else if (!container || !container.parent || !(ts.isClassLike(container.parent) || container.parent.kind === 188 /* ObjectLiteralExpression */)) { + error(node, ts.Diagnostics.super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions); + } + else { + error(node, ts.Diagnostics.super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_derived_class); + } + return errorType; + } + if (!isCallExpression && container.kind === 157 /* Constructor */) { + checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class); + } + if (ts.hasModifier(container, 32 /* Static */) || isCallExpression) { + nodeCheckFlag = 512 /* SuperStatic */; + } + else { + nodeCheckFlag = 256 /* SuperInstance */; + } + getNodeLinks(node).flags |= nodeCheckFlag; + // Due to how we emit async functions, we need to specialize the emit for an async method that contains a `super` reference. + // This is due to the fact that we emit the body of an async function inside of a generator function. As generator + // functions cannot reference `super`, we emit a helper inside of the method body, but outside of the generator. This helper + // uses an arrow function, which is permitted to reference `super`. + // + // There are two primary ways we can access `super` from within an async method. The first is getting the value of a property + // or indexed access on super, either as part of a right-hand-side expression or call expression. The second is when setting the value + // of a property or indexed access, either as part of an assignment expression or destructuring assignment. + // + // The simplest case is reading a value, in which case we will emit something like the following: + // + // // ts + // ... + // async asyncMethod() { + // let x = await super.asyncMethod(); + // return x; + // } + // ... + // + // // js + // ... + // asyncMethod() { + // const _super = Object.create(null, { + // asyncMethod: { get: () => super.asyncMethod }, + // }); + // return __awaiter(this, arguments, Promise, function *() { + // let x = yield _super.asyncMethod.call(this); + // return x; + // }); + // } + // ... + // + // The more complex case is when we wish to assign a value, especially as part of a destructuring assignment. As both cases + // are legal in ES6, but also likely less frequent, we only emit setters if there is an assignment: + // + // // ts + // ... + // async asyncMethod(ar: Promise) { + // [super.a, super.b] = await ar; + // } + // ... + // + // // js + // ... + // asyncMethod(ar) { + // const _super = Object.create(null, { + // a: { get: () => super.a, set: (v) => super.a = v }, + // b: { get: () => super.b, set: (v) => super.b = v } + // }; + // return __awaiter(this, arguments, Promise, function *() { + // [_super.a, _super.b] = yield ar; + // }); + // } + // ... + // + // Creating an object that has getter and setters instead of just an accessor function is required for destructuring assignments + // as a call expression cannot be used as the target of a destructuring assignment while a property access can. + // + // For element access expressions (`super[x]`), we emit a generic helper that forwards the element access in both situations. + if (container.kind === 156 /* MethodDeclaration */ && ts.hasModifier(container, 256 /* Async */)) { + if (ts.isSuperProperty(node.parent) && ts.isAssignmentTarget(node.parent)) { + getNodeLinks(container).flags |= 4096 /* AsyncMethodWithSuperBinding */; + } + else { + getNodeLinks(container).flags |= 2048 /* AsyncMethodWithSuper */; + } + } + if (needToCaptureLexicalThis) { + // call expressions are allowed only in constructors so they should always capture correct 'this' + // super property access expressions can also appear in arrow functions - + // in this case they should also use correct lexical this + captureLexicalThis(node.parent, container); + } + if (container.parent.kind === 188 /* ObjectLiteralExpression */) { + if (languageVersion < 2 /* ES2015 */) { + error(node, ts.Diagnostics.super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_higher); + return errorType; + } + else { + // for object literal assume that type of 'super' is 'any' + return anyType; + } + } + // at this point the only legal case for parent is ClassLikeDeclaration + var classLikeDeclaration = container.parent; + if (!ts.getEffectiveBaseTypeNode(classLikeDeclaration)) { + error(node, ts.Diagnostics.super_can_only_be_referenced_in_a_derived_class); + return errorType; + } + var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(classLikeDeclaration)); + var baseClassType = classType && getBaseTypes(classType)[0]; + if (!baseClassType) { + return errorType; + } + if (container.kind === 157 /* Constructor */ && isInConstructorArgumentInitializer(node, container)) { + // issue custom error message for super property access in constructor arguments (to be aligned with old compiler) + error(node, ts.Diagnostics.super_cannot_be_referenced_in_constructor_arguments); + return errorType; + } + return nodeCheckFlag === 512 /* SuperStatic */ + ? getBaseConstructorTypeOfClass(classType) + : getTypeWithThisArgument(baseClassType, classType.thisType); + function isLegalUsageOfSuperExpression(container) { + if (!container) { + return false; + } + if (isCallExpression) { + // TS 1.0 SPEC (April 2014): 4.8.1 + // Super calls are only permitted in constructors of derived classes + return container.kind === 157 /* Constructor */; + } + else { + // TS 1.0 SPEC (April 2014) + // 'super' property access is allowed + // - In a constructor, instance member function, instance member accessor, or instance member variable initializer where this references a derived class instance + // - In a static member function or static member accessor + // topmost container must be something that is directly nested in the class declaration\object literal expression + if (ts.isClassLike(container.parent) || container.parent.kind === 188 /* ObjectLiteralExpression */) { + if (ts.hasModifier(container, 32 /* Static */)) { + return container.kind === 156 /* MethodDeclaration */ || + container.kind === 155 /* MethodSignature */ || + container.kind === 158 /* GetAccessor */ || + container.kind === 159 /* SetAccessor */; + } + else { + return container.kind === 156 /* MethodDeclaration */ || + container.kind === 155 /* MethodSignature */ || + container.kind === 158 /* GetAccessor */ || + container.kind === 159 /* SetAccessor */ || + container.kind === 154 /* PropertyDeclaration */ || + container.kind === 153 /* PropertySignature */ || + container.kind === 157 /* Constructor */; + } + } + } + return false; + } + } + function getContainingObjectLiteral(func) { + return (func.kind === 156 /* MethodDeclaration */ || + func.kind === 158 /* GetAccessor */ || + func.kind === 159 /* SetAccessor */) && func.parent.kind === 188 /* ObjectLiteralExpression */ ? func.parent : + func.kind === 196 /* FunctionExpression */ && func.parent.kind === 275 /* PropertyAssignment */ ? func.parent.parent : + undefined; + } + function getThisTypeArgument(type) { + return ts.getObjectFlags(type) & 4 /* Reference */ && type.target === globalThisType ? type.typeArguments[0] : undefined; + } + function getThisTypeFromContextualType(type) { + return mapType(type, function (t) { + return t.flags & 2097152 /* Intersection */ ? ts.forEach(t.types, getThisTypeArgument) : getThisTypeArgument(t); + }); + } + function getContextualThisParameterType(func) { + if (func.kind === 197 /* ArrowFunction */) { + return undefined; + } + if (isContextSensitiveFunctionOrObjectLiteralMethod(func)) { + var contextualSignature = getContextualSignature(func); + if (contextualSignature) { + var thisParameter = contextualSignature.thisParameter; + if (thisParameter) { + return getTypeOfSymbol(thisParameter); + } + } + } + var inJs = ts.isInJSFile(func); + if (noImplicitThis || inJs) { + var containingLiteral = getContainingObjectLiteral(func); + if (containingLiteral) { + // We have an object literal method. Check if the containing object literal has a contextual type + // that includes a ThisType. If so, T is the contextual type for 'this'. We continue looking in + // any directly enclosing object literals. + var contextualType = getApparentTypeOfContextualType(containingLiteral); + var literal = containingLiteral; + var type = contextualType; + while (type) { + var thisType = getThisTypeFromContextualType(type); + if (thisType) { + return instantiateType(thisType, getContextualMapper(containingLiteral)); + } + if (literal.parent.kind !== 275 /* PropertyAssignment */) { + break; + } + literal = literal.parent.parent; + type = getApparentTypeOfContextualType(literal); + } + // There was no contextual ThisType for the containing object literal, so the contextual type + // for 'this' is the non-null form of the contextual type for the containing object literal or + // the type of the object literal itself. + return contextualType ? getNonNullableType(contextualType) : checkExpressionCached(containingLiteral); + } + // In an assignment of the form 'obj.xxx = function(...)' or 'obj[xxx] = function(...)', the + // contextual type for 'this' is 'obj'. + var parent = func.parent; + if (parent.kind === 204 /* BinaryExpression */ && parent.operatorToken.kind === 59 /* EqualsToken */) { + var target = parent.left; + if (target.kind === 189 /* PropertyAccessExpression */ || target.kind === 190 /* ElementAccessExpression */) { + var expression = target.expression; + // Don't contextually type `this` as `exports` in `exports.Point = function(x, y) { this.x = x; this.y = y; }` + if (inJs && ts.isIdentifier(expression)) { + var sourceFile = ts.getSourceFileOfNode(parent); + if (sourceFile.commonJsModuleIndicator && getResolvedSymbol(expression) === sourceFile.symbol) { + return undefined; + } + } + return checkExpressionCached(expression); + } + } + } + return undefined; + } + // Return contextual type of parameter or undefined if no contextual type is available + function getContextuallyTypedParameterType(parameter) { + var func = parameter.parent; + if (!isContextSensitiveFunctionOrObjectLiteralMethod(func)) { + return undefined; + } + var iife = ts.getImmediatelyInvokedFunctionExpression(func); + if (iife && iife.arguments) { + var args = getEffectiveCallArguments(iife); + var indexOfParameter = func.parameters.indexOf(parameter); + if (parameter.dotDotDotToken) { + return getSpreadArgumentType(args, indexOfParameter, args.length, anyType, /*context*/ undefined); + } + var links = getNodeLinks(iife); + var cached = links.resolvedSignature; + links.resolvedSignature = anySignature; + var type = indexOfParameter < args.length ? + getWidenedLiteralType(checkExpression(args[indexOfParameter])) : + parameter.initializer ? undefined : undefinedWideningType; + links.resolvedSignature = cached; + return type; + } + var contextualSignature = getContextualSignature(func); + if (contextualSignature) { + var index = func.parameters.indexOf(parameter) - (ts.getThisParameter(func) ? 1 : 0); + return parameter.dotDotDotToken && ts.lastOrUndefined(func.parameters) === parameter ? + getRestTypeAtPosition(contextualSignature, index) : + tryGetTypeAtPosition(contextualSignature, index); + } + } + // In a variable, parameter or property declaration with a type annotation, + // the contextual type of an initializer expression is the type of the variable, parameter or property. + // Otherwise, in a parameter declaration of a contextually typed function expression, + // the contextual type of an initializer expression is the contextual type of the parameter. + // Otherwise, in a variable or parameter declaration with a binding pattern name, + // the contextual type of an initializer expression is the type implied by the binding pattern. + // Otherwise, in a binding pattern inside a variable or parameter declaration, + // the contextual type of an initializer expression is the type annotation of the containing declaration, if present. + function getContextualTypeForInitializerExpression(node) { + var declaration = node.parent; + if (ts.hasInitializer(declaration) && node === declaration.initializer) { + var typeNode = ts.getEffectiveTypeAnnotationNode(declaration); + if (typeNode) { + return getTypeFromTypeNode(typeNode); + } + if (declaration.kind === 151 /* Parameter */) { + var type = getContextuallyTypedParameterType(declaration); + if (type) { + return type; + } + } + if (ts.isBindingPattern(declaration.name)) { + return getTypeFromBindingPattern(declaration.name, /*includePatternInType*/ true, /*reportErrors*/ false); + } + if (ts.isBindingPattern(declaration.parent)) { + var parentDeclaration = declaration.parent.parent; + var name = declaration.propertyName || declaration.name; + if (parentDeclaration.kind !== 186 /* BindingElement */) { + var parentTypeNode = ts.getEffectiveTypeAnnotationNode(parentDeclaration); + if (parentTypeNode && !ts.isBindingPattern(name)) { + var text = ts.getTextOfPropertyName(name); + if (text) { + return getTypeOfPropertyOfType(getTypeFromTypeNode(parentTypeNode), text); + } + } + } + } + } + return undefined; + } + function getContextualTypeForReturnExpression(node) { + var func = ts.getContainingFunction(node); + if (func) { + var functionFlags = ts.getFunctionFlags(func); + if (functionFlags & 1 /* Generator */) { // AsyncGenerator function or Generator function + return undefined; + } + var contextualReturnType = getContextualReturnType(func); + if (contextualReturnType) { + if (functionFlags & 2 /* Async */) { // Async function + var contextualAwaitedType = getAwaitedTypeOfPromise(contextualReturnType); + return contextualAwaitedType && getUnionType([contextualAwaitedType, createPromiseLikeType(contextualAwaitedType)]); + } + return contextualReturnType; // Regular function + } + } + return undefined; + } + function getContextualTypeForAwaitOperand(node) { + var contextualType = getContextualType(node); + if (contextualType) { + var contextualAwaitedType = getAwaitedType(contextualType); + return contextualAwaitedType && getUnionType([contextualAwaitedType, createPromiseLikeType(contextualAwaitedType)]); + } + return undefined; + } + function getContextualTypeForYieldOperand(node) { + var func = ts.getContainingFunction(node); + if (func) { + var functionFlags = ts.getFunctionFlags(func); + var contextualReturnType = getContextualReturnType(func); + if (contextualReturnType) { + return node.asteriskToken + ? contextualReturnType + : getIteratedTypeOfGenerator(contextualReturnType, (functionFlags & 2 /* Async */) !== 0); + } + } + return undefined; + } + function isInParameterInitializerBeforeContainingFunction(node) { + var inBindingInitializer = false; + while (node.parent && !ts.isFunctionLike(node.parent)) { + if (ts.isParameter(node.parent) && (inBindingInitializer || node.parent.initializer === node)) { + return true; + } + if (ts.isBindingElement(node.parent) && node.parent.initializer === node) { + inBindingInitializer = true; + } + node = node.parent; + } + return false; + } + function getContextualReturnType(functionDecl) { + // If the containing function has a return type annotation, is a constructor, or is a get accessor whose + // corresponding set accessor has a type annotation, return statements in the function are contextually typed + var returnType = getReturnTypeFromAnnotation(functionDecl); + if (returnType) { + return returnType; + } + // Otherwise, if the containing function is contextually typed by a function type with exactly one call signature + // and that call signature is non-generic, return statements are contextually typed by the return type of the signature + var signature = getContextualSignatureForFunctionLikeDeclaration(functionDecl); + if (signature && !isResolvingReturnTypeOfSignature(signature)) { + return getReturnTypeOfSignature(signature); + } + return undefined; + } + // In a typed function call, an argument or substitution expression is contextually typed by the type of the corresponding parameter. + function getContextualTypeForArgument(callTarget, arg) { + var args = getEffectiveCallArguments(callTarget); + var argIndex = args.indexOf(arg); // -1 for e.g. the expression of a CallExpression, or the tag of a TaggedTemplateExpression + return argIndex === -1 ? undefined : getContextualTypeForArgumentAtIndex(callTarget, argIndex); + } + function getContextualTypeForArgumentAtIndex(callTarget, argIndex) { + // If we're already in the process of resolving the given signature, don't resolve again as + // that could cause infinite recursion. Instead, return anySignature. + var signature = getNodeLinks(callTarget).resolvedSignature === resolvingSignature ? resolvingSignature : getResolvedSignature(callTarget); + if (ts.isJsxOpeningLikeElement(callTarget) && argIndex === 0) { + return getEffectiveFirstArgumentForJsxSignature(signature, callTarget); + } + return getTypeAtPosition(signature, argIndex); + } + function getContextualTypeForSubstitutionExpression(template, substitutionExpression) { + if (template.parent.kind === 193 /* TaggedTemplateExpression */) { + return getContextualTypeForArgument(template.parent, substitutionExpression); + } + return undefined; + } + function getContextualTypeForBinaryOperand(node) { + var binaryExpression = node.parent; + var left = binaryExpression.left, operatorToken = binaryExpression.operatorToken, right = binaryExpression.right; + switch (operatorToken.kind) { + case 59 /* EqualsToken */: + if (node !== right) { + return undefined; + } + var contextSensitive = getIsContextSensitiveAssignmentOrContextType(binaryExpression); + if (!contextSensitive) { + return undefined; + } + return contextSensitive === true ? getTypeOfExpression(left) : contextSensitive; + case 55 /* BarBarToken */: + // When an || expression has a contextual type, the operands are contextually typed by that type. When an || + // expression has no contextual type, the right operand is contextually typed by the type of the left operand, + // except for the special case of Javascript declarations of the form `namespace.prop = namespace.prop || {}` + var type = getContextualType(binaryExpression); + return !type && node === right && !ts.isDefaultedExpandoInitializer(binaryExpression) ? + getTypeOfExpression(left) : type; + case 54 /* AmpersandAmpersandToken */: + case 27 /* CommaToken */: + return node === right ? getContextualType(binaryExpression) : undefined; + default: + return undefined; + } + } + // In an assignment expression, the right operand is contextually typed by the type of the left operand. + // Don't do this for assignment declarations unless there is a type tag on the assignment, to avoid circularity from checking the right operand. + function getIsContextSensitiveAssignmentOrContextType(binaryExpression) { + var kind = ts.getAssignmentDeclarationKind(binaryExpression); + switch (kind) { + case 0 /* None */: + return true; + case 5 /* Property */: + case 1 /* ExportsProperty */: + case 6 /* Prototype */: + case 3 /* PrototypeProperty */: + // If `binaryExpression.left` was assigned a symbol, then this is a new declaration; otherwise it is an assignment to an existing declaration. + // See `bindStaticPropertyAssignment` in `binder.ts`. + if (!binaryExpression.left.symbol) { + return true; + } + else { + var decl = binaryExpression.left.symbol.valueDeclaration; + if (!decl) { + return false; + } + var lhs = binaryExpression.left; + var overallAnnotation = ts.getEffectiveTypeAnnotationNode(decl); + if (overallAnnotation) { + return getTypeFromTypeNode(overallAnnotation); + } + else if (ts.isIdentifier(lhs.expression)) { + var id = lhs.expression; + var parentSymbol = resolveName(id, id.escapedText, 67220415 /* Value */, undefined, id.escapedText, /*isUse*/ true); + if (parentSymbol) { + var annotated = ts.getEffectiveTypeAnnotationNode(parentSymbol.valueDeclaration); + if (annotated) { + var type = getTypeOfPropertyOfContextualType(getTypeFromTypeNode(annotated), lhs.name.escapedText); + return type || false; + } + return false; + } + } + return !ts.isInJSFile(decl); + } + case 2 /* ModuleExports */: + case 4 /* ThisProperty */: + if (!binaryExpression.symbol) + return true; + if (binaryExpression.symbol.valueDeclaration) { + var annotated = ts.getEffectiveTypeAnnotationNode(binaryExpression.symbol.valueDeclaration); + if (annotated) { + var type = getTypeFromTypeNode(annotated); + if (type) { + return type; + } + } + } + if (kind === 2 /* ModuleExports */) + return false; + var thisAccess = binaryExpression.left; + if (!ts.isObjectLiteralMethod(ts.getThisContainer(thisAccess.expression, /*includeArrowFunctions*/ false))) { + return false; + } + var thisType = checkThisExpression(thisAccess.expression); + return thisType && getTypeOfPropertyOfContextualType(thisType, thisAccess.name.escapedText) || false; + case 7 /* ObjectDefinePropertyValue */: + case 8 /* ObjectDefinePropertyExports */: + case 9 /* ObjectDefinePrototypeProperty */: + return ts.Debug.fail("Does not apply"); + default: + return ts.Debug.assertNever(kind); + } + } + function getTypeOfPropertyOfContextualType(type, name) { + return mapType(type, function (t) { + if (t.flags & 3670016 /* StructuredType */) { + var prop = getPropertyOfType(t, name); + if (prop) { + return getTypeOfSymbol(prop); + } + if (isTupleType(t)) { + var restType = getRestTypeOfTupleType(t); + if (restType && isNumericLiteralName(name) && +name >= 0) { + return restType; + } + } + return isNumericLiteralName(name) && getIndexTypeOfContextualType(t, 1 /* Number */) || + getIndexTypeOfContextualType(t, 0 /* String */); + } + return undefined; + }, /*noReductions*/ true); + } + function getIndexTypeOfContextualType(type, kind) { + return mapType(type, function (t) { return getIndexTypeOfStructuredType(t, kind); }, /*noReductions*/ true); + } + // In an object literal contextually typed by a type T, the contextual type of a property assignment is the type of + // the matching property in T, if one exists. Otherwise, it is the type of the numeric index signature in T, if one + // exists. Otherwise, it is the type of the string index signature in T, if one exists. + function getContextualTypeForObjectLiteralMethod(node) { + ts.Debug.assert(ts.isObjectLiteralMethod(node)); + if (node.flags & 8388608 /* InWithStatement */) { + // We cannot answer semantic questions within a with block, do not proceed any further + return undefined; + } + return getContextualTypeForObjectLiteralElement(node); + } + function getContextualTypeForObjectLiteralElement(element) { + var objectLiteral = element.parent; + var type = getApparentTypeOfContextualType(objectLiteral); + if (type) { + if (!hasNonBindableDynamicName(element)) { + // For a (non-symbol) computed property, there is no reason to look up the name + // in the type. It will just be "__computed", which does not appear in any + // SymbolTable. + var symbolName_2 = getSymbolOfNode(element).escapedName; + var propertyType = getTypeOfPropertyOfContextualType(type, symbolName_2); + if (propertyType) { + return propertyType; + } + } + return isNumericName(element.name) && getIndexTypeOfContextualType(type, 1 /* Number */) || + getIndexTypeOfContextualType(type, 0 /* String */); + } + return undefined; + } + // In an array literal contextually typed by a type T, the contextual type of an element expression at index N is + // the type of the property with the numeric name N in T, if one exists. Otherwise, if T has a numeric index signature, + // it is the type of the numeric index signature in T. Otherwise, in ES6 and higher, the contextual type is the iterated + // type of T. + function getContextualTypeForElementExpression(arrayContextualType, index) { + return arrayContextualType && (getTypeOfPropertyOfContextualType(arrayContextualType, "" + index) + || getIteratedTypeOrElementType(arrayContextualType, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterables*/ false, /*checkAssignability*/ false)); + } + // In a contextually typed conditional expression, the true/false expressions are contextually typed by the same type. + function getContextualTypeForConditionalOperand(node) { + var conditional = node.parent; + return node === conditional.whenTrue || node === conditional.whenFalse ? getContextualType(conditional) : undefined; + } + function getContextualTypeForChildJsxExpression(node) { + var attributesType = getApparentTypeOfContextualType(node.openingElement.tagName); + // JSX expression is in children of JSX Element, we will look for an "children" atttribute (we get the name from JSX.ElementAttributesProperty) + var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(node)); + return attributesType && !isTypeAny(attributesType) && jsxChildrenPropertyName && jsxChildrenPropertyName !== "" ? getTypeOfPropertyOfContextualType(attributesType, jsxChildrenPropertyName) : undefined; + } + function getContextualTypeForJsxExpression(node) { + var exprParent = node.parent; + return ts.isJsxAttributeLike(exprParent) + ? getContextualType(node) + : ts.isJsxElement(exprParent) + ? getContextualTypeForChildJsxExpression(exprParent) + : undefined; + } + function getContextualTypeForJsxAttribute(attribute) { + // When we trying to resolve JsxOpeningLikeElement as a stateless function element, we will already give its attributes a contextual type + // which is a type of the parameter of the signature we are trying out. + // If there is no contextual type (e.g. we are trying to resolve stateful component), get attributes type from resolving element's tagName + if (ts.isJsxAttribute(attribute)) { + var attributesType = getApparentTypeOfContextualType(attribute.parent); + if (!attributesType || isTypeAny(attributesType)) { + return undefined; + } + return getTypeOfPropertyOfContextualType(attributesType, attribute.name.escapedText); + } + else { + return getContextualType(attribute.parent); + } + } + // Return true if the given expression is possibly a discriminant value. We limit the kinds of + // expressions we check to those that don't depend on their contextual type in order not to cause + // recursive (and possibly infinite) invocations of getContextualType. + function isPossiblyDiscriminantValue(node) { + switch (node.kind) { + case 10 /* StringLiteral */: + case 8 /* NumericLiteral */: + case 9 /* BigIntLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: + case 102 /* TrueKeyword */: + case 87 /* FalseKeyword */: + case 96 /* NullKeyword */: + case 72 /* Identifier */: + case 141 /* UndefinedKeyword */: + return true; + case 189 /* PropertyAccessExpression */: + case 195 /* ParenthesizedExpression */: + return isPossiblyDiscriminantValue(node.expression); + case 270 /* JsxExpression */: + return !node.expression || isPossiblyDiscriminantValue(node.expression); + } + return false; + } + function discriminateContextualTypeByObjectMembers(node, contextualType) { + return discriminateTypeByDiscriminableItems(contextualType, ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 275 /* PropertyAssignment */ && isPossiblyDiscriminantValue(p.initializer) && isDiscriminantProperty(contextualType, p.symbol.escapedName); }), function (prop) { return [function () { return checkExpression(prop.initializer); }, prop.symbol.escapedName]; }), isTypeAssignableTo, contextualType); + } + function discriminateContextualTypeByJSXAttributes(node, contextualType) { + return discriminateTypeByDiscriminableItems(contextualType, ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 267 /* JsxAttribute */ && isDiscriminantProperty(contextualType, p.symbol.escapedName) && (!p.initializer || isPossiblyDiscriminantValue(p.initializer)); }), function (prop) { return [!prop.initializer ? (function () { return trueType; }) : (function () { return checkExpression(prop.initializer); }), prop.symbol.escapedName]; }), isTypeAssignableTo, contextualType); + } + // Return the contextual type for a given expression node. During overload resolution, a contextual type may temporarily + // be "pushed" onto a node using the contextualType property. + function getApparentTypeOfContextualType(node) { + var contextualType = getContextualType(node); + contextualType = contextualType && mapType(contextualType, getApparentType); + if (contextualType && contextualType.flags & 1048576 /* Union */) { + if (ts.isObjectLiteralExpression(node)) { + return discriminateContextualTypeByObjectMembers(node, contextualType); + } + else if (ts.isJsxAttributes(node)) { + return discriminateContextualTypeByJSXAttributes(node, contextualType); + } + } + return contextualType; + } + /** + * Woah! Do you really want to use this function? + * + * Unless you're trying to get the *non-apparent* type for a + * value-literal type or you're authoring relevant portions of this algorithm, + * you probably meant to use 'getApparentTypeOfContextualType'. + * Otherwise this may not be very useful. + * + * In cases where you *are* working on this function, you should understand + * when it is appropriate to use 'getContextualType' and 'getApparentTypeOfContextualType'. + * + * - Use 'getContextualType' when you are simply going to propagate the result to the expression. + * - Use 'getApparentTypeOfContextualType' when you're going to need the members of the type. + * + * @param node the expression whose contextual type will be returned. + * @returns the contextual type of an expression. + */ + function getContextualType(node) { + if (node.flags & 8388608 /* InWithStatement */) { + // We cannot answer semantic questions within a with block, do not proceed any further + return undefined; + } + if (node.contextualType) { + return node.contextualType; + } + var parent = node.parent; + switch (parent.kind) { + case 237 /* VariableDeclaration */: + case 151 /* Parameter */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 186 /* BindingElement */: + return getContextualTypeForInitializerExpression(node); + case 197 /* ArrowFunction */: + case 230 /* ReturnStatement */: + return getContextualTypeForReturnExpression(node); + case 207 /* YieldExpression */: + return getContextualTypeForYieldOperand(parent); + case 201 /* AwaitExpression */: + return getContextualTypeForAwaitOperand(parent); + case 191 /* CallExpression */: + case 192 /* NewExpression */: + return getContextualTypeForArgument(parent, node); + case 194 /* TypeAssertionExpression */: + case 212 /* AsExpression */: + return getTypeFromTypeNode(parent.type); + case 204 /* BinaryExpression */: + return getContextualTypeForBinaryOperand(node); + case 275 /* PropertyAssignment */: + case 276 /* ShorthandPropertyAssignment */: + return getContextualTypeForObjectLiteralElement(parent); + case 277 /* SpreadAssignment */: + return getApparentTypeOfContextualType(parent.parent); + case 187 /* ArrayLiteralExpression */: { + var arrayLiteral = parent; + var type = getApparentTypeOfContextualType(arrayLiteral); + return getContextualTypeForElementExpression(type, ts.indexOfNode(arrayLiteral.elements, node)); + } + case 205 /* ConditionalExpression */: + return getContextualTypeForConditionalOperand(node); + case 216 /* TemplateSpan */: + ts.Debug.assert(parent.parent.kind === 206 /* TemplateExpression */); + return getContextualTypeForSubstitutionExpression(parent.parent, node); + case 195 /* ParenthesizedExpression */: { + // Like in `checkParenthesizedExpression`, an `/** @type {xyz} */` comment before a parenthesized expression acts as a type cast. + var tag = ts.isInJSFile(parent) ? ts.getJSDocTypeTag(parent) : undefined; + return tag ? getTypeFromTypeNode(tag.typeExpression.type) : getContextualType(parent); + } + case 270 /* JsxExpression */: + return getContextualTypeForJsxExpression(parent); + case 267 /* JsxAttribute */: + case 269 /* JsxSpreadAttribute */: + return getContextualTypeForJsxAttribute(parent); + case 262 /* JsxOpeningElement */: + case 261 /* JsxSelfClosingElement */: + return getContextualJsxElementAttributesType(parent); + } + return undefined; + } + function getContextualMapper(node) { + var ancestor = ts.findAncestor(node, function (n) { return !!n.contextualMapper; }); + return ancestor ? ancestor.contextualMapper : identityMapper; + } + function getContextualJsxElementAttributesType(node) { + if (ts.isJsxOpeningElement(node) && node.parent.contextualType) { + // Contextually applied type is moved from attributes up to the outer jsx attributes so when walking up from the children they get hit + // _However_ to hit them from the _attributes_ we must look for them here; otherwise we'll used the declared type + // (as below) instead! + return node.parent.contextualType; + } + return getContextualTypeForArgumentAtIndex(node, 0); + } + function getEffectiveFirstArgumentForJsxSignature(signature, node) { + return getJsxReferenceKind(node) !== 0 /* Component */ ? getJsxPropsTypeFromCallSignature(signature, node) : getJsxPropsTypeFromClassType(signature, node); + } + function getJsxPropsTypeFromCallSignature(sig, context) { + var propsType = getTypeOfFirstParameterOfSignatureWithFallback(sig, emptyObjectType); + propsType = getJsxManagedAttributesFromLocatedAttributes(context, getJsxNamespaceAt(context), propsType); + var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes, context); + if (intrinsicAttribs !== errorType) { + propsType = intersectTypes(intrinsicAttribs, propsType); + } + return propsType; + } + function getJsxPropsTypeForSignatureFromMember(sig, forcedLookupLocation) { + var instanceType = getReturnTypeOfSignature(sig); + return isTypeAny(instanceType) ? instanceType : getTypeOfPropertyOfType(instanceType, forcedLookupLocation); + } + function getStaticTypeOfReferencedJsxConstructor(context) { + if (isJsxIntrinsicIdentifier(context.tagName)) { + var result = getIntrinsicAttributesTypeFromJsxOpeningLikeElement(context); + var fakeSignature = createSignatureForJSXIntrinsic(context, result); + return getOrCreateTypeFromSignature(fakeSignature); + } + var tagType = checkExpressionCached(context.tagName); + if (tagType.flags & 128 /* StringLiteral */) { + var result = getIntrinsicAttributesTypeFromStringLiteralType(tagType, context); + if (!result) { + return errorType; + } + var fakeSignature = createSignatureForJSXIntrinsic(context, result); + return getOrCreateTypeFromSignature(fakeSignature); + } + return tagType; + } + function getJsxManagedAttributesFromLocatedAttributes(context, ns, attributesType) { + var managedSym = getJsxLibraryManagedAttributes(ns); + if (managedSym) { + var declaredManagedType = getDeclaredTypeOfSymbol(managedSym); + var ctorType = getStaticTypeOfReferencedJsxConstructor(context); + if (ts.length(declaredManagedType.typeParameters) >= 2) { + var args = fillMissingTypeArguments([ctorType, attributesType], declaredManagedType.typeParameters, 2, ts.isInJSFile(context)); + return createTypeReference(declaredManagedType, args); + } + else if (ts.length(declaredManagedType.aliasTypeArguments) >= 2) { + var args = fillMissingTypeArguments([ctorType, attributesType], declaredManagedType.aliasTypeArguments, 2, ts.isInJSFile(context)); + return getTypeAliasInstantiation(declaredManagedType.aliasSymbol, args); + } + } + return attributesType; + } + function getJsxPropsTypeFromClassType(sig, context) { + var ns = getJsxNamespaceAt(context); + var forcedLookupLocation = getJsxElementPropertiesName(ns); + var attributesType = forcedLookupLocation === undefined + // If there is no type ElementAttributesProperty, return the type of the first parameter of the signature, which should be the props type + ? getTypeOfFirstParameterOfSignatureWithFallback(sig, emptyObjectType) + : forcedLookupLocation === "" + // If there is no e.g. 'props' member in ElementAttributesProperty, use the element class type instead + ? getReturnTypeOfSignature(sig) + // Otherwise get the type of the property on the signature return type + : getJsxPropsTypeForSignatureFromMember(sig, forcedLookupLocation); + if (!attributesType) { + // There is no property named 'props' on this instance type + if (!!forcedLookupLocation && !!ts.length(context.attributes.properties)) { + error(context, ts.Diagnostics.JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property, ts.unescapeLeadingUnderscores(forcedLookupLocation)); + } + return emptyObjectType; + } + attributesType = getJsxManagedAttributesFromLocatedAttributes(context, ns, attributesType); + if (isTypeAny(attributesType)) { + // Props is of type 'any' or unknown + return attributesType; + } + else { + // Normal case -- add in IntrinsicClassElements and IntrinsicElements + var apparentAttributesType = attributesType; + var intrinsicClassAttribs = getJsxType(JsxNames.IntrinsicClassAttributes, context); + if (intrinsicClassAttribs !== errorType) { + var typeParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(intrinsicClassAttribs.symbol); + var hostClassType = getReturnTypeOfSignature(sig); + apparentAttributesType = intersectTypes(typeParams + ? createTypeReference(intrinsicClassAttribs, fillMissingTypeArguments([hostClassType], typeParams, getMinTypeArgumentCount(typeParams), ts.isInJSFile(context))) + : intrinsicClassAttribs, apparentAttributesType); + } + var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes, context); + if (intrinsicAttribs !== errorType) { + apparentAttributesType = intersectTypes(intrinsicAttribs, apparentAttributesType); + } + return apparentAttributesType; + } + } + // If the given type is an object or union type with a single signature, and if that signature has at + // least as many parameters as the given function, return the signature. Otherwise return undefined. + function getContextualCallSignature(type, node) { + var signatures = getSignaturesOfType(type, 0 /* Call */); + if (signatures.length === 1) { + var signature = signatures[0]; + if (!isAritySmaller(signature, node)) { + return signature; + } + } + } + /** If the contextual signature has fewer parameters than the function expression, do not use it */ + function isAritySmaller(signature, target) { + var targetParameterCount = 0; + for (; targetParameterCount < target.parameters.length; targetParameterCount++) { + var param = target.parameters[targetParameterCount]; + if (param.initializer || param.questionToken || param.dotDotDotToken || isJSDocOptionalParameter(param)) { + break; + } + } + if (target.parameters.length && ts.parameterIsThisKeyword(target.parameters[0])) { + targetParameterCount--; + } + return !hasEffectiveRestParameter(signature) && getParameterCount(signature) < targetParameterCount; + } + function isFunctionExpressionOrArrowFunction(node) { + return node.kind === 196 /* FunctionExpression */ || node.kind === 197 /* ArrowFunction */; + } + function getContextualSignatureForFunctionLikeDeclaration(node) { + // Only function expressions, arrow functions, and object literal methods are contextually typed. + return isFunctionExpressionOrArrowFunction(node) || ts.isObjectLiteralMethod(node) + ? getContextualSignature(node) + : undefined; + } + function getContextualTypeForFunctionLikeDeclaration(node) { + return ts.isObjectLiteralMethod(node) ? + getContextualTypeForObjectLiteralMethod(node) : + getApparentTypeOfContextualType(node); + } + // Return the contextual signature for a given expression node. A contextual type provides a + // contextual signature if it has a single call signature and if that call signature is non-generic. + // If the contextual type is a union type, get the signature from each type possible and if they are + // all identical ignoring their return type, the result is same signature but with return type as + // union type of return types from these signatures + function getContextualSignature(node) { + ts.Debug.assert(node.kind !== 156 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + var typeTagSignature = getSignatureOfTypeTag(node); + if (typeTagSignature) { + return typeTagSignature; + } + var type = getContextualTypeForFunctionLikeDeclaration(node); + if (!type) { + return undefined; + } + if (!(type.flags & 1048576 /* Union */)) { + return getContextualCallSignature(type, node); + } + var signatureList; + var types = type.types; + for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { + var current = types_14[_i]; + var signature = getContextualCallSignature(current, node); + if (signature) { + if (!signatureList) { + // This signature will contribute to contextual union signature + signatureList = [signature]; + } + else if (!compareSignaturesIdentical(signatureList[0], signature, /*partialMatch*/ false, /*ignoreThisTypes*/ true, /*ignoreReturnTypes*/ true, compareTypesIdentical)) { + // Signatures aren't identical, do not use + return undefined; + } + else { + // Use this signature for contextual union signature + signatureList.push(signature); + } + } + } + // Result is union of signatures collected (return type is union of return types of this signature set) + var result; + if (signatureList) { + result = cloneSignature(signatureList[0]); + result.unionSignatures = signatureList; + } + return result; + } + function checkSpreadExpression(node, checkMode) { + if (languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) { + checkExternalEmitHelpers(node, 1536 /* SpreadIncludes */); + } + var arrayOrIterableType = checkExpression(node.expression, checkMode); + return checkIteratedTypeOrElementType(arrayOrIterableType, node.expression, /*allowStringInput*/ false, /*allowAsyncIterables*/ false); + } + function hasDefaultValue(node) { + return (node.kind === 186 /* BindingElement */ && !!node.initializer) || + (node.kind === 204 /* BinaryExpression */ && node.operatorToken.kind === 59 /* EqualsToken */); + } + function checkArrayLiteral(node, checkMode, forceTuple) { + var elements = node.elements; + var elementCount = elements.length; + var hasNonEndingSpreadElement = false; + var elementTypes = []; + var inDestructuringPattern = ts.isAssignmentTarget(node); + var contextualType = getApparentTypeOfContextualType(node); + for (var index = 0; index < elementCount; index++) { + var e = elements[index]; + if (inDestructuringPattern && e.kind === 208 /* SpreadElement */) { + // Given the following situation: + // var c: {}; + // [...c] = ["", 0]; + // + // c is represented in the tree as a spread element in an array literal. + // But c really functions as a rest element, and its purpose is to provide + // a contextual type for the right hand side of the assignment. Therefore, + // instead of calling checkExpression on "...c", which will give an error + // if c is not iterable/array-like, we need to act as if we are trying to + // get the contextual element type from it. So we do something similar to + // getContextualTypeForElementExpression, which will crucially not error + // if there is no index type / iterated type. + var restArrayType = checkExpression(e.expression, checkMode, forceTuple); + var restElementType = getIndexTypeOfType(restArrayType, 1 /* Number */) || + getIteratedTypeOrElementType(restArrayType, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterables*/ false, /*checkAssignability*/ false); + if (restElementType) { + elementTypes.push(restElementType); + } + } + else { + var elementContextualType = getContextualTypeForElementExpression(contextualType, index); + var type = checkExpressionForMutableLocation(e, checkMode, elementContextualType, forceTuple); + elementTypes.push(type); + } + if (index < elementCount - 1 && e.kind === 208 /* SpreadElement */) { + hasNonEndingSpreadElement = true; + } + } + if (!hasNonEndingSpreadElement) { + var hasRestElement = elementCount > 0 && elements[elementCount - 1].kind === 208 /* SpreadElement */; + var minLength = elementCount - (hasRestElement ? 1 : 0); + // If array literal is actually a destructuring pattern, mark it as an implied type. We do this such + // that we get the same behavior for "var [x, y] = []" and "[x, y] = []". + var tupleResult = void 0; + if (inDestructuringPattern && minLength > 0) { + var type = cloneTypeReference(createTupleType(elementTypes, minLength, hasRestElement)); + type.pattern = node; + return type; + } + else if (tupleResult = getArrayLiteralTupleTypeIfApplicable(elementTypes, contextualType, hasRestElement, elementCount)) { + return tupleResult; + } + else if (forceTuple) { + return createTupleType(elementTypes, minLength, hasRestElement); + } + } + return getArrayLiteralType(elementTypes, 2 /* Subtype */); + } + function getArrayLiteralTupleTypeIfApplicable(elementTypes, contextualType, hasRestElement, elementCount) { + if (elementCount === void 0) { elementCount = elementTypes.length; } + // Infer a tuple type when the contextual type is or contains a tuple-like type + if (contextualType && forEachType(contextualType, isTupleLikeType)) { + var minLength = elementCount - (hasRestElement ? 1 : 0); + var pattern = contextualType.pattern; + // If array literal is contextually typed by a binding pattern or an assignment pattern, pad the resulting + // tuple type with the corresponding binding or assignment element types to make the lengths equal. + if (!hasRestElement && pattern && (pattern.kind === 185 /* ArrayBindingPattern */ || pattern.kind === 187 /* ArrayLiteralExpression */)) { + var patternElements = pattern.elements; + for (var i = elementCount; i < patternElements.length; i++) { + var e = patternElements[i]; + if (hasDefaultValue(e)) { + elementTypes.push(contextualType.typeArguments[i]); + } + else if (i < patternElements.length - 1 || !(e.kind === 186 /* BindingElement */ && e.dotDotDotToken || e.kind === 208 /* SpreadElement */)) { + if (e.kind !== 210 /* OmittedExpression */) { + error(e, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); + } + elementTypes.push(strictNullChecks ? implicitNeverType : undefinedWideningType); + } + } + } + return createTupleType(elementTypes, minLength, hasRestElement); + } + } + function getArrayLiteralType(elementTypes, unionReduction) { + if (unionReduction === void 0) { unionReduction = 1 /* Literal */; } + return createArrayType(elementTypes.length ? + getUnionType(elementTypes, unionReduction) : + strictNullChecks ? implicitNeverType : undefinedWideningType); + } + function isNumericName(name) { + switch (name.kind) { + case 149 /* ComputedPropertyName */: + return isNumericComputedName(name); + case 72 /* Identifier */: + return isNumericLiteralName(name.escapedText); + case 8 /* NumericLiteral */: + case 10 /* StringLiteral */: + return isNumericLiteralName(name.text); + default: + return false; + } + } + function isNumericComputedName(name) { + // It seems odd to consider an expression of type Any to result in a numeric name, + // but this behavior is consistent with checkIndexedAccess + return isTypeAssignableToKind(checkComputedPropertyName(name), 296 /* NumberLike */); + } + function isInfinityOrNaNString(name) { + return name === "Infinity" || name === "-Infinity" || name === "NaN"; + } + function isNumericLiteralName(name) { + // The intent of numeric names is that + // - they are names with text in a numeric form, and that + // - setting properties/indexing with them is always equivalent to doing so with the numeric literal 'numLit', + // acquired by applying the abstract 'ToNumber' operation on the name's text. + // + // The subtlety is in the latter portion, as we cannot reliably say that anything that looks like a numeric literal is a numeric name. + // In fact, it is the case that the text of the name must be equal to 'ToString(numLit)' for this to hold. + // + // Consider the property name '"0xF00D"'. When one indexes with '0xF00D', they are actually indexing with the value of 'ToString(0xF00D)' + // according to the ECMAScript specification, so it is actually as if the user indexed with the string '"61453"'. + // Thus, the text of all numeric literals equivalent to '61543' such as '0xF00D', '0xf00D', '0170015', etc. are not valid numeric names + // because their 'ToString' representation is not equal to their original text. + // This is motivated by ECMA-262 sections 9.3.1, 9.8.1, 11.1.5, and 11.2.1. + // + // Here, we test whether 'ToString(ToNumber(name))' is exactly equal to 'name'. + // The '+' prefix operator is equivalent here to applying the abstract ToNumber operation. + // Applying the 'toString()' method on a number gives us the abstract ToString operation on a number. + // + // Note that this accepts the values 'Infinity', '-Infinity', and 'NaN', and that this is intentional. + // This is desired behavior, because when indexing with them as numeric entities, you are indexing + // with the strings '"Infinity"', '"-Infinity"', and '"NaN"' respectively. + return (+name).toString() === name; + } + function checkComputedPropertyName(node) { + var links = getNodeLinks(node.expression); + if (!links.resolvedType) { + links.resolvedType = checkExpression(node.expression); + // This will allow types number, string, symbol or any. It will also allow enums, the unknown + // type, and any union of these types (like string | number). + if (links.resolvedType.flags & 98304 /* Nullable */ || + !isTypeAssignableToKind(links.resolvedType, 132 /* StringLike */ | 296 /* NumberLike */ | 12288 /* ESSymbolLike */) && + !isTypeAssignableTo(links.resolvedType, stringNumberSymbolType)) { + error(node, ts.Diagnostics.A_computed_property_name_must_be_of_type_string_number_symbol_or_any); + } + else { + checkThatExpressionIsProperSymbolReference(node.expression, links.resolvedType, /*reportError*/ true); + } + } + return links.resolvedType; + } + function getObjectLiteralIndexInfo(propertyNodes, offset, properties, kind) { + var propTypes = []; + for (var i = 0; i < properties.length; i++) { + if (kind === 0 /* String */ || isNumericName(propertyNodes[i + offset].name)) { + propTypes.push(getTypeOfSymbol(properties[i])); + } + } + var unionType = propTypes.length ? getUnionType(propTypes, 2 /* Subtype */) : undefinedType; + return createIndexInfo(unionType, /*isReadonly*/ false); + } + function getImmediateAliasedSymbol(symbol) { + ts.Debug.assert((symbol.flags & 2097152 /* Alias */) !== 0, "Should only get Alias here."); + var links = getSymbolLinks(symbol); + if (!links.immediateTarget) { + var node = getDeclarationOfAliasSymbol(symbol); + if (!node) + return ts.Debug.fail(); + links.immediateTarget = getTargetOfAliasDeclaration(node, /*dontRecursivelyResolve*/ true); + } + return links.immediateTarget; + } + function checkObjectLiteral(node, checkMode) { + var inDestructuringPattern = ts.isAssignmentTarget(node); + // Grammar checking + checkGrammarObjectLiteralExpression(node, inDestructuringPattern); + var propertiesTable; + var propertiesArray = []; + var spread = emptyObjectType; + var propagatedFlags = 0; + var contextualType = getApparentTypeOfContextualType(node); + var contextualTypeHasPattern = contextualType && contextualType.pattern && + (contextualType.pattern.kind === 184 /* ObjectBindingPattern */ || contextualType.pattern.kind === 188 /* ObjectLiteralExpression */); + var isInJavascript = ts.isInJSFile(node) && !ts.isInJsonFile(node); + var enumTag = ts.getJSDocEnumTag(node); + var isJSObjectLiteral = !contextualType && isInJavascript && !enumTag; + var typeFlags = 0; + var patternWithComputedProperties = false; + var hasComputedStringProperty = false; + var hasComputedNumberProperty = false; + propertiesTable = ts.createSymbolTable(); + var offset = 0; + for (var i = 0; i < node.properties.length; i++) { + var memberDecl = node.properties[i]; + var member = getSymbolOfNode(memberDecl); + var computedNameType = memberDecl.name && memberDecl.name.kind === 149 /* ComputedPropertyName */ && !ts.isWellKnownSymbolSyntactically(memberDecl.name.expression) ? + checkComputedPropertyName(memberDecl.name) : undefined; + if (memberDecl.kind === 275 /* PropertyAssignment */ || + memberDecl.kind === 276 /* ShorthandPropertyAssignment */ || + ts.isObjectLiteralMethod(memberDecl)) { + var type = memberDecl.kind === 275 /* PropertyAssignment */ ? checkPropertyAssignment(memberDecl, checkMode) : + memberDecl.kind === 276 /* ShorthandPropertyAssignment */ ? checkExpressionForMutableLocation(memberDecl.name, checkMode) : + checkObjectLiteralMethod(memberDecl, checkMode); + if (isInJavascript) { + var jsDocType = getTypeForDeclarationFromJSDocComment(memberDecl); + if (jsDocType) { + checkTypeAssignableTo(type, jsDocType, memberDecl); + type = jsDocType; + } + else if (enumTag && enumTag.typeExpression) { + checkTypeAssignableTo(type, getTypeFromTypeNode(enumTag.typeExpression), memberDecl); + } + } + typeFlags |= type.flags; + var nameType = computedNameType && computedNameType.flags & 8576 /* StringOrNumberLiteralOrUnique */ ? + computedNameType : undefined; + var prop = nameType ? + createSymbol(4 /* Property */ | member.flags, getLateBoundNameFromType(nameType), 1024 /* Late */) : + createSymbol(4 /* Property */ | member.flags, member.escapedName); + if (nameType) { + prop.nameType = nameType; + } + if (inDestructuringPattern) { + // If object literal is an assignment pattern and if the assignment pattern specifies a default value + // for the property, make the property optional. + var isOptional = (memberDecl.kind === 275 /* PropertyAssignment */ && hasDefaultValue(memberDecl.initializer)) || + (memberDecl.kind === 276 /* ShorthandPropertyAssignment */ && memberDecl.objectAssignmentInitializer); + if (isOptional) { + prop.flags |= 16777216 /* Optional */; + } + } + else if (contextualTypeHasPattern && !(ts.getObjectFlags(contextualType) & 512 /* ObjectLiteralPatternWithComputedProperties */)) { + // If object literal is contextually typed by the implied type of a binding pattern, and if the + // binding pattern specifies a default value for the property, make the property optional. + var impliedProp = getPropertyOfType(contextualType, member.escapedName); + if (impliedProp) { + prop.flags |= impliedProp.flags & 16777216 /* Optional */; + } + else if (!compilerOptions.suppressExcessPropertyErrors && !getIndexInfoOfType(contextualType, 0 /* String */)) { + error(memberDecl.name, ts.Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(member), typeToString(contextualType)); + } + } + prop.declarations = member.declarations; + prop.parent = member.parent; + if (member.valueDeclaration) { + prop.valueDeclaration = member.valueDeclaration; + } + prop.type = type; + prop.target = member; + member = prop; + } + else if (memberDecl.kind === 277 /* SpreadAssignment */) { + if (languageVersion < 2 /* ES2015 */) { + checkExternalEmitHelpers(memberDecl, 2 /* Assign */); + } + if (propertiesArray.length > 0) { + spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, propagatedFlags, 32768 /* FreshLiteral */); + propertiesArray = []; + propertiesTable = ts.createSymbolTable(); + hasComputedStringProperty = false; + hasComputedNumberProperty = false; + typeFlags = 0; + } + var type = checkExpression(memberDecl.expression); + if (!isValidSpreadType(type)) { + error(memberDecl, ts.Diagnostics.Spread_types_may_only_be_created_from_object_types); + return errorType; + } + spread = getSpreadType(spread, type, node.symbol, propagatedFlags, 32768 /* FreshLiteral */); + offset = i + 1; + continue; + } + else { + // TypeScript 1.0 spec (April 2014) + // A get accessor declaration is processed in the same manner as + // an ordinary function declaration(section 6.1) with no parameters. + // A set accessor declaration is processed in the same manner + // as an ordinary function declaration with a single parameter and a Void return type. + ts.Debug.assert(memberDecl.kind === 158 /* GetAccessor */ || memberDecl.kind === 159 /* SetAccessor */); + checkNodeDeferred(memberDecl); + } + if (computedNameType && !(computedNameType.flags & 8576 /* StringOrNumberLiteralOrUnique */)) { + if (isTypeAssignableTo(computedNameType, stringNumberSymbolType)) { + if (isTypeAssignableTo(computedNameType, numberType)) { + hasComputedNumberProperty = true; + } + else { + hasComputedStringProperty = true; + } + if (inDestructuringPattern) { + patternWithComputedProperties = true; + } + } + } + else { + propertiesTable.set(member.escapedName, member); + } + propertiesArray.push(member); + } + // If object literal is contextually typed by the implied type of a binding pattern, augment the result + // type with those properties for which the binding pattern specifies a default value. + if (contextualTypeHasPattern) { + for (var _i = 0, _a = getPropertiesOfType(contextualType); _i < _a.length; _i++) { + var prop = _a[_i]; + if (!propertiesTable.get(prop.escapedName) && !(spread && getPropertyOfType(spread, prop.escapedName))) { + if (!(prop.flags & 16777216 /* Optional */)) { + error(prop.valueDeclaration || prop.bindingElement, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); + } + propertiesTable.set(prop.escapedName, prop); + propertiesArray.push(prop); + } + } + } + if (spread !== emptyObjectType) { + if (propertiesArray.length > 0) { + spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, propagatedFlags, 32768 /* FreshLiteral */); + } + return spread; + } + return createObjectLiteralType(); + function createObjectLiteralType() { + var stringIndexInfo = hasComputedStringProperty ? getObjectLiteralIndexInfo(node.properties, offset, propertiesArray, 0 /* String */) : undefined; + var numberIndexInfo = hasComputedNumberProperty ? getObjectLiteralIndexInfo(node.properties, offset, propertiesArray, 1 /* Number */) : undefined; + var result = createAnonymousType(node.symbol, propertiesTable, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); + result.flags |= 268435456 /* ContainsObjectLiteral */ | typeFlags & 939524096 /* PropagatingFlags */; + result.objectFlags |= 128 /* ObjectLiteral */ | freshObjectLiteralFlag; + if (isJSObjectLiteral) { + result.objectFlags |= 16384 /* JSLiteral */; + } + if (patternWithComputedProperties) { + result.objectFlags |= 512 /* ObjectLiteralPatternWithComputedProperties */; + } + if (inDestructuringPattern) { + result.pattern = node; + } + propagatedFlags |= result.flags & 939524096 /* PropagatingFlags */; + return result; + } + } + function isValidSpreadType(type) { + return !!(type.flags & (3 /* AnyOrUnknown */ | 67108864 /* NonPrimitive */ | 524288 /* Object */ | 58982400 /* InstantiableNonPrimitive */) || + getFalsyFlags(type) & 117632 /* DefinitelyFalsy */ && isValidSpreadType(removeDefinitelyFalsyTypes(type)) || + type.flags & 3145728 /* UnionOrIntersection */ && ts.every(type.types, isValidSpreadType)); + } + function checkJsxSelfClosingElementDeferred(node) { + checkJsxOpeningLikeElementOrOpeningFragment(node); + } + function checkJsxSelfClosingElement(node, _checkMode) { + checkNodeDeferred(node); + return getJsxElementTypeAt(node) || anyType; + } + function checkJsxElementDeferred(node) { + // Check attributes + checkJsxOpeningLikeElementOrOpeningFragment(node.openingElement); + // Perform resolution on the closing tag so that rename/go to definition/etc work + if (isJsxIntrinsicIdentifier(node.closingElement.tagName)) { + getIntrinsicTagSymbol(node.closingElement); + } + else { + checkExpression(node.closingElement.tagName); + } + checkJsxChildren(node); + } + function checkJsxElement(node, _checkMode) { + checkNodeDeferred(node); + return getJsxElementTypeAt(node) || anyType; + } + function checkJsxFragment(node) { + checkJsxOpeningLikeElementOrOpeningFragment(node.openingFragment); + if (compilerOptions.jsx === 2 /* React */ && (compilerOptions.jsxFactory || ts.getSourceFileOfNode(node).pragmas.has("jsx"))) { + error(node, compilerOptions.jsxFactory + ? ts.Diagnostics.JSX_fragment_is_not_supported_when_using_jsxFactory + : ts.Diagnostics.JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma); + } + checkJsxChildren(node); + return getJsxElementTypeAt(node) || anyType; + } + /** + * Returns true iff the JSX element name would be a valid JS identifier, ignoring restrictions about keywords not being identifiers + */ + function isUnhyphenatedJsxName(name) { + // - is the only character supported in JSX attribute names that isn't valid in JavaScript identifiers + return !ts.stringContains(name, "-"); + } + /** + * Returns true iff React would emit this tag name as a string rather than an identifier or qualified name + */ + function isJsxIntrinsicIdentifier(tagName) { + return tagName.kind === 72 /* Identifier */ && ts.isIntrinsicJsxName(tagName.escapedText); + } + function checkJsxAttribute(node, checkMode) { + return node.initializer + ? checkExpressionForMutableLocation(node.initializer, checkMode) + : trueType; // is sugar for + } + /** + * Get attributes type of the JSX opening-like element. The result is from resolving "attributes" property of the opening-like element. + * + * @param openingLikeElement a JSX opening-like element + * @param filter a function to remove attributes that will not participate in checking whether attributes are assignable + * @return an anonymous type (similar to the one returned by checkObjectLiteral) in which its properties are attributes property. + * @remarks Because this function calls getSpreadType, it needs to use the same checks as checkObjectLiteral, + * which also calls getSpreadType. + */ + function createJsxAttributesTypeFromAttributesProperty(openingLikeElement, checkMode) { + var attributes = openingLikeElement.attributes; + var attributesTable = ts.createSymbolTable(); + var spread = emptyJsxObjectType; + var hasSpreadAnyType = false; + var typeToIntersect; + var explicitlySpecifyChildrenAttribute = false; + var typeFlags = 0; + var objectFlags = 4096 /* JsxAttributes */; + var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(openingLikeElement)); + for (var _i = 0, _a = attributes.properties; _i < _a.length; _i++) { + var attributeDecl = _a[_i]; + var member = attributeDecl.symbol; + if (ts.isJsxAttribute(attributeDecl)) { + var exprType = checkJsxAttribute(attributeDecl, checkMode); + typeFlags |= exprType.flags & 939524096 /* PropagatingFlags */; + var attributeSymbol = createSymbol(4 /* Property */ | 33554432 /* Transient */ | member.flags, member.escapedName); + attributeSymbol.declarations = member.declarations; + attributeSymbol.parent = member.parent; + if (member.valueDeclaration) { + attributeSymbol.valueDeclaration = member.valueDeclaration; + } + attributeSymbol.type = exprType; + attributeSymbol.target = member; + attributesTable.set(attributeSymbol.escapedName, attributeSymbol); + if (attributeDecl.name.escapedText === jsxChildrenPropertyName) { + explicitlySpecifyChildrenAttribute = true; + } + } + else { + ts.Debug.assert(attributeDecl.kind === 269 /* JsxSpreadAttribute */); + if (attributesTable.size > 0) { + spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, typeFlags, objectFlags); + attributesTable = ts.createSymbolTable(); + } + var exprType = checkExpressionCached(attributeDecl.expression, checkMode); + if (isTypeAny(exprType)) { + hasSpreadAnyType = true; + } + if (isValidSpreadType(exprType)) { + spread = getSpreadType(spread, exprType, attributes.symbol, typeFlags, objectFlags); + } + else { + typeToIntersect = typeToIntersect ? getIntersectionType([typeToIntersect, exprType]) : exprType; + } + } + } + if (!hasSpreadAnyType) { + if (attributesTable.size > 0) { + spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, typeFlags, objectFlags); + } + } + // Handle children attribute + var parent = openingLikeElement.parent.kind === 260 /* JsxElement */ ? openingLikeElement.parent : undefined; + // We have to check that openingElement of the parent is the one we are visiting as this may not be true for selfClosingElement + if (parent && parent.openingElement === openingLikeElement && parent.children.length > 0) { + var childrenTypes = checkJsxChildren(parent, checkMode); + if (!hasSpreadAnyType && jsxChildrenPropertyName && jsxChildrenPropertyName !== "") { + // Error if there is a attribute named "children" explicitly specified and children element. + // This is because children element will overwrite the value from attributes. + // Note: we will not warn "children" attribute overwritten if "children" attribute is specified in object spread. + if (explicitlySpecifyChildrenAttribute) { + error(attributes, ts.Diagnostics._0_are_specified_twice_The_attribute_named_0_will_be_overwritten, ts.unescapeLeadingUnderscores(jsxChildrenPropertyName)); + } + var contextualType = getApparentTypeOfContextualType(openingLikeElement.attributes); + var childrenContextualType = contextualType && getTypeOfPropertyOfContextualType(contextualType, jsxChildrenPropertyName); + // If there are children in the body of JSX element, create dummy attribute "children" with the union of children types so that it will pass the attribute checking process + var childrenPropSymbol = createSymbol(4 /* Property */ | 33554432 /* Transient */, jsxChildrenPropertyName); + childrenPropSymbol.type = childrenTypes.length === 1 ? + childrenTypes[0] : + (getArrayLiteralTupleTypeIfApplicable(childrenTypes, childrenContextualType, /*hasRestElement*/ false) || createArrayType(getUnionType(childrenTypes))); + var childPropMap = ts.createSymbolTable(); + childPropMap.set(jsxChildrenPropertyName, childrenPropSymbol); + spread = getSpreadType(spread, createAnonymousType(attributes.symbol, childPropMap, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined), attributes.symbol, typeFlags, objectFlags); + } + } + if (hasSpreadAnyType) { + return anyType; + } + if (typeToIntersect && spread !== emptyJsxObjectType) { + return getIntersectionType([typeToIntersect, spread]); + } + return typeToIntersect || (spread === emptyJsxObjectType ? createJsxAttributesType() : spread); + /** + * Create anonymous type from given attributes symbol table. + * @param symbol a symbol of JsxAttributes containing attributes corresponding to attributesTable + * @param attributesTable a symbol table of attributes property + */ + function createJsxAttributesType() { + objectFlags |= freshObjectLiteralFlag; + var result = createAnonymousType(attributes.symbol, attributesTable, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined); + result.flags |= 268435456 /* ContainsObjectLiteral */ | typeFlags; + result.objectFlags |= 128 /* ObjectLiteral */ | objectFlags; + return result; + } + } + function checkJsxChildren(node, checkMode) { + var childrenTypes = []; + for (var _i = 0, _a = node.children; _i < _a.length; _i++) { + var child = _a[_i]; + // In React, JSX text that contains only whitespaces will be ignored so we don't want to type-check that + // because then type of children property will have constituent of string type. + if (child.kind === 11 /* JsxText */) { + if (!child.containsOnlyWhiteSpaces) { + childrenTypes.push(stringType); + } + } + else { + childrenTypes.push(checkExpressionForMutableLocation(child, checkMode)); + } + } + return childrenTypes; + } + /** + * Check attributes property of opening-like element. This function is called during chooseOverload to get call signature of a JSX opening-like element. + * (See "checkApplicableSignatureForJsxOpeningLikeElement" for how the function is used) + * @param node a JSXAttributes to be resolved of its type + */ + function checkJsxAttributes(node, checkMode) { + return createJsxAttributesTypeFromAttributesProperty(node.parent, checkMode); + } + function getJsxType(name, location) { + var namespace = getJsxNamespaceAt(location); + var exports = namespace && getExportsOfSymbol(namespace); + var typeSymbol = exports && getSymbol(exports, name, 67897832 /* Type */); + return typeSymbol ? getDeclaredTypeOfSymbol(typeSymbol) : errorType; + } + /** + * Looks up an intrinsic tag name and returns a symbol that either points to an intrinsic + * property (in which case nodeLinks.jsxFlags will be IntrinsicNamedElement) or an intrinsic + * string index signature (in which case nodeLinks.jsxFlags will be IntrinsicIndexedElement). + * May also return unknownSymbol if both of these lookups fail. + */ + function getIntrinsicTagSymbol(node) { + var links = getNodeLinks(node); + if (!links.resolvedSymbol) { + var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements, node); + if (intrinsicElementsType !== errorType) { + // Property case + if (!ts.isIdentifier(node.tagName)) + return ts.Debug.fail(); + var intrinsicProp = getPropertyOfType(intrinsicElementsType, node.tagName.escapedText); + if (intrinsicProp) { + links.jsxFlags |= 1 /* IntrinsicNamedElement */; + return links.resolvedSymbol = intrinsicProp; + } + // Intrinsic string indexer case + var indexSignatureType = getIndexTypeOfType(intrinsicElementsType, 0 /* String */); + if (indexSignatureType) { + links.jsxFlags |= 2 /* IntrinsicIndexedElement */; + return links.resolvedSymbol = intrinsicElementsType.symbol; + } + // Wasn't found + error(node, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.idText(node.tagName), "JSX." + JsxNames.IntrinsicElements); + return links.resolvedSymbol = unknownSymbol; + } + else { + if (noImplicitAny) { + error(node, ts.Diagnostics.JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists, ts.unescapeLeadingUnderscores(JsxNames.IntrinsicElements)); + } + return links.resolvedSymbol = unknownSymbol; + } + } + return links.resolvedSymbol; + } + function getJsxNamespaceAt(location) { + var links = location && getNodeLinks(location); + if (links && links.jsxNamespace) { + return links.jsxNamespace; + } + if (!links || links.jsxNamespace !== false) { + var namespaceName = getJsxNamespace(location); + var resolvedNamespace = resolveName(location, namespaceName, 1920 /* Namespace */, /*diagnosticMessage*/ undefined, namespaceName, /*isUse*/ false); + if (resolvedNamespace) { + var candidate = getSymbol(getExportsOfSymbol(resolveSymbol(resolvedNamespace)), JsxNames.JSX, 1920 /* Namespace */); + if (candidate) { + if (links) { + links.jsxNamespace = candidate; + } + return candidate; + } + if (links) { + links.jsxNamespace = false; + } + } + } + // JSX global fallback + return getGlobalSymbol(JsxNames.JSX, 1920 /* Namespace */, /*diagnosticMessage*/ undefined); // TODO: GH#18217 + } + /** + * Look into JSX namespace and then look for container with matching name as nameOfAttribPropContainer. + * Get a single property from that container if existed. Report an error if there are more than one property. + * + * @param nameOfAttribPropContainer a string of value JsxNames.ElementAttributesPropertyNameContainer or JsxNames.ElementChildrenAttributeNameContainer + * if other string is given or the container doesn't exist, return undefined. + */ + function getNameFromJsxElementAttributesContainer(nameOfAttribPropContainer, jsxNamespace) { + // JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute [symbol] + var jsxElementAttribPropInterfaceSym = jsxNamespace && getSymbol(jsxNamespace.exports, nameOfAttribPropContainer, 67897832 /* Type */); + // JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute [type] + var jsxElementAttribPropInterfaceType = jsxElementAttribPropInterfaceSym && getDeclaredTypeOfSymbol(jsxElementAttribPropInterfaceSym); + // The properties of JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute + var propertiesOfJsxElementAttribPropInterface = jsxElementAttribPropInterfaceType && getPropertiesOfType(jsxElementAttribPropInterfaceType); + if (propertiesOfJsxElementAttribPropInterface) { + // Element Attributes has zero properties, so the element attributes type will be the class instance type + if (propertiesOfJsxElementAttribPropInterface.length === 0) { + return ""; + } + // Element Attributes has one property, so the element attributes type will be the type of the corresponding + // property of the class instance type + else if (propertiesOfJsxElementAttribPropInterface.length === 1) { + return propertiesOfJsxElementAttribPropInterface[0].escapedName; + } + else if (propertiesOfJsxElementAttribPropInterface.length > 1) { + // More than one property on ElementAttributesProperty is an error + error(jsxElementAttribPropInterfaceSym.declarations[0], ts.Diagnostics.The_global_type_JSX_0_may_not_have_more_than_one_property, ts.unescapeLeadingUnderscores(nameOfAttribPropContainer)); + } + } + return undefined; + } + function getJsxLibraryManagedAttributes(jsxNamespace) { + // JSX.LibraryManagedAttributes [symbol] + return jsxNamespace && getSymbol(jsxNamespace.exports, JsxNames.LibraryManagedAttributes, 67897832 /* Type */); + } + /// e.g. "props" for React.d.ts, + /// or 'undefined' if ElementAttributesProperty doesn't exist (which means all + /// non-intrinsic elements' attributes type is 'any'), + /// or '' if it has 0 properties (which means every + /// non-intrinsic elements' attributes type is the element instance type) + function getJsxElementPropertiesName(jsxNamespace) { + return getNameFromJsxElementAttributesContainer(JsxNames.ElementAttributesPropertyNameContainer, jsxNamespace); + } + function getJsxElementChildrenPropertyName(jsxNamespace) { + return getNameFromJsxElementAttributesContainer(JsxNames.ElementChildrenAttributeNameContainer, jsxNamespace); + } + function getUninstantiatedJsxSignaturesOfType(elementType, caller) { + if (elementType.flags & 4 /* String */) { + return [anySignature]; + } + else if (elementType.flags & 128 /* StringLiteral */) { + var intrinsicType = getIntrinsicAttributesTypeFromStringLiteralType(elementType, caller); + if (!intrinsicType) { + error(caller, ts.Diagnostics.Property_0_does_not_exist_on_type_1, elementType.value, "JSX." + JsxNames.IntrinsicElements); + return ts.emptyArray; + } + else { + var fakeSignature = createSignatureForJSXIntrinsic(caller, intrinsicType); + return [fakeSignature]; + } + } + var apparentElemType = getApparentType(elementType); + // Resolve the signatures, preferring constructor + var signatures = getSignaturesOfType(apparentElemType, 1 /* Construct */); + if (signatures.length === 0) { + // No construct signatures, try call signatures + signatures = getSignaturesOfType(apparentElemType, 0 /* Call */); + } + if (signatures.length === 0 && apparentElemType.flags & 1048576 /* Union */) { + // If each member has some combination of new/call signatures; make a union signature list for those + signatures = getUnionSignatures(ts.map(apparentElemType.types, function (t) { return getUninstantiatedJsxSignaturesOfType(t, caller); })); + } + return signatures; + } + function getIntrinsicAttributesTypeFromStringLiteralType(type, location) { + // If the elemType is a stringLiteral type, we can then provide a check to make sure that the string literal type is one of the Jsx intrinsic element type + // For example: + // var CustomTag: "h1" = "h1"; + // Hello World + var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements, location); + if (intrinsicElementsType !== errorType) { + var stringLiteralTypeName = type.value; + var intrinsicProp = getPropertyOfType(intrinsicElementsType, ts.escapeLeadingUnderscores(stringLiteralTypeName)); + if (intrinsicProp) { + return getTypeOfSymbol(intrinsicProp); + } + var indexSignatureType = getIndexTypeOfType(intrinsicElementsType, 0 /* String */); + if (indexSignatureType) { + return indexSignatureType; + } + return undefined; + } + // If we need to report an error, we already done so here. So just return any to prevent any more error downstream + return anyType; + } + function checkJsxReturnAssignableToAppropriateBound(refKind, elemInstanceType, openingLikeElement) { + if (refKind === 1 /* Function */) { + var sfcReturnConstraint = getJsxStatelessElementTypeAt(openingLikeElement); + if (sfcReturnConstraint) { + checkTypeRelatedTo(elemInstanceType, sfcReturnConstraint, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); + } + } + else if (refKind === 0 /* Component */) { + var classConstraint = getJsxElementClassTypeAt(openingLikeElement); + if (classConstraint) { + // Issue an error if this return type isn't assignable to JSX.ElementClass or JSX.Element, failing that + checkTypeRelatedTo(elemInstanceType, classConstraint, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); + } + } + else { // Mixed + var sfcReturnConstraint = getJsxStatelessElementTypeAt(openingLikeElement); + var classConstraint = getJsxElementClassTypeAt(openingLikeElement); + if (!sfcReturnConstraint || !classConstraint) { + return; + } + var combined = getUnionType([sfcReturnConstraint, classConstraint]); + checkTypeRelatedTo(elemInstanceType, combined, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); + } + } + /** + * Get attributes type of the given intrinsic opening-like Jsx element by resolving the tag name. + * The function is intended to be called from a function which has checked that the opening element is an intrinsic element. + * @param node an intrinsic JSX opening-like element + */ + function getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node) { + ts.Debug.assert(isJsxIntrinsicIdentifier(node.tagName)); + var links = getNodeLinks(node); + if (!links.resolvedJsxElementAttributesType) { + var symbol = getIntrinsicTagSymbol(node); + if (links.jsxFlags & 1 /* IntrinsicNamedElement */) { + return links.resolvedJsxElementAttributesType = getTypeOfSymbol(symbol); + } + else if (links.jsxFlags & 2 /* IntrinsicIndexedElement */) { + return links.resolvedJsxElementAttributesType = getIndexInfoOfSymbol(symbol, 0 /* String */).type; + } + else { + return links.resolvedJsxElementAttributesType = errorType; + } + } + return links.resolvedJsxElementAttributesType; + } + function getJsxElementClassTypeAt(location) { + var type = getJsxType(JsxNames.ElementClass, location); + if (type === errorType) + return undefined; + return type; + } + function getJsxElementTypeAt(location) { + return getJsxType(JsxNames.Element, location); + } + function getJsxStatelessElementTypeAt(location) { + var jsxElementType = getJsxElementTypeAt(location); + if (jsxElementType) { + return getUnionType([jsxElementType, nullType]); + } + } + /** + * Returns all the properties of the Jsx.IntrinsicElements interface + */ + function getJsxIntrinsicTagNamesAt(location) { + var intrinsics = getJsxType(JsxNames.IntrinsicElements, location); + return intrinsics ? getPropertiesOfType(intrinsics) : ts.emptyArray; + } + function checkJsxPreconditions(errorNode) { + // Preconditions for using JSX + if ((compilerOptions.jsx || 0 /* None */) === 0 /* None */) { + error(errorNode, ts.Diagnostics.Cannot_use_JSX_unless_the_jsx_flag_is_provided); + } + if (getJsxElementTypeAt(errorNode) === undefined) { + if (noImplicitAny) { + error(errorNode, ts.Diagnostics.JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist); + } + } + } + function checkJsxOpeningLikeElementOrOpeningFragment(node) { + var isNodeOpeningLikeElement = ts.isJsxOpeningLikeElement(node); + if (isNodeOpeningLikeElement) { + checkGrammarJsxElement(node); + } + checkJsxPreconditions(node); + // The reactNamespace/jsxFactory's root symbol should be marked as 'used' so we don't incorrectly elide its import. + // And if there is no reactNamespace/jsxFactory's symbol in scope when targeting React emit, we should issue an error. + var reactRefErr = diagnostics && compilerOptions.jsx === 2 /* React */ ? ts.Diagnostics.Cannot_find_name_0 : undefined; + var reactNamespace = getJsxNamespace(node); + var reactLocation = isNodeOpeningLikeElement ? node.tagName : node; + var reactSym = resolveName(reactLocation, reactNamespace, 67220415 /* Value */, reactRefErr, reactNamespace, /*isUse*/ true); + if (reactSym) { + // Mark local symbol as referenced here because it might not have been marked + // if jsx emit was not react as there wont be error being emitted + reactSym.isReferenced = 67108863 /* All */; + // If react symbol is alias, mark it as refereced + if (reactSym.flags & 2097152 /* Alias */ && !isConstEnumOrConstEnumOnlyModule(resolveAlias(reactSym))) { + markAliasSymbolAsReferenced(reactSym); + } + } + if (isNodeOpeningLikeElement) { + var sig = getResolvedSignature(node); + checkJsxReturnAssignableToAppropriateBound(getJsxReferenceKind(node), getReturnTypeOfSignature(sig), node); + } + } + /** + * Check if a property with the given name is known anywhere in the given type. In an object type, a property + * is considered known if + * 1. the object type is empty and the check is for assignability, or + * 2. if the object type has index signatures, or + * 3. if the property is actually declared in the object type + * (this means that 'toString', for example, is not usually a known property). + * 4. In a union or intersection type, + * a property is considered known if it is known in any constituent type. + * @param targetType a type to search a given name in + * @param name a property name to search + * @param isComparingJsxAttributes a boolean flag indicating whether we are searching in JsxAttributesType + */ + function isKnownProperty(targetType, name, isComparingJsxAttributes) { + if (targetType.flags & 524288 /* Object */) { + var resolved = resolveStructuredTypeMembers(targetType); + if (resolved.stringIndexInfo || + resolved.numberIndexInfo && isNumericLiteralName(name) || + getPropertyOfObjectType(targetType, name) || + isComparingJsxAttributes && !isUnhyphenatedJsxName(name)) { + // For JSXAttributes, if the attribute has a hyphenated name, consider that the attribute to be known. + return true; + } + } + else if (targetType.flags & 3145728 /* UnionOrIntersection */) { + for (var _i = 0, _a = targetType.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (isKnownProperty(t, name, isComparingJsxAttributes)) { + return true; + } + } + } + else if (targetType.flags & 16777216 /* Conditional */) { + return isKnownProperty(targetType.root.trueType, name, isComparingJsxAttributes) || + isKnownProperty(targetType.root.falseType, name, isComparingJsxAttributes); + } + return false; + } + function checkJsxExpression(node, checkMode) { + if (node.expression) { + var type = checkExpression(node.expression, checkMode); + if (node.dotDotDotToken && type !== anyType && !isArrayType(type)) { + error(node, ts.Diagnostics.JSX_spread_child_must_be_an_array_type); + } + return type; + } + else { + return errorType; + } + } + function getDeclarationNodeFlagsFromSymbol(s) { + return s.valueDeclaration ? ts.getCombinedNodeFlags(s.valueDeclaration) : 0; + } + /** + * Return whether this symbol is a member of a prototype somewhere + * Note that this is not tracked well within the compiler, so the answer may be incorrect. + */ + function isPrototypeProperty(symbol) { + if (symbol.flags & 8192 /* Method */ || ts.getCheckFlags(symbol) & 4 /* SyntheticMethod */) { + return true; + } + if (ts.isInJSFile(symbol.valueDeclaration)) { + var parent = symbol.valueDeclaration.parent; + return parent && ts.isBinaryExpression(parent) && + ts.getAssignmentDeclarationKind(parent) === 3 /* PrototypeProperty */; + } + } + /** + * Check whether the requested property access is valid. + * Returns true if node is a valid property access, and false otherwise. + * @param node The node to be checked. + * @param isSuper True if the access is from `super.`. + * @param type The type of the object whose property is being accessed. (Not the type of the property.) + * @param prop The symbol for the property being accessed. + */ + function checkPropertyAccessibility(node, isSuper, type, prop) { + var flags = ts.getDeclarationModifierFlagsFromSymbol(prop); + var errorNode = node.kind === 148 /* QualifiedName */ ? node.right : node.kind === 183 /* ImportType */ ? node : node.name; + if (ts.getCheckFlags(prop) & 256 /* ContainsPrivate */) { + // Synthetic property with private constituent property + error(errorNode, ts.Diagnostics.Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1, symbolToString(prop), typeToString(type)); + return false; + } + if (isSuper) { + // TS 1.0 spec (April 2014): 4.8.2 + // - In a constructor, instance member function, instance member accessor, or + // instance member variable initializer where this references a derived class instance, + // a super property access is permitted and must specify a public instance member function of the base class. + // - In a static member function or static member accessor + // where this references the constructor function object of a derived class, + // a super property access is permitted and must specify a public static member function of the base class. + if (languageVersion < 2 /* ES2015 */) { + if (symbolHasNonMethodDeclaration(prop)) { + error(errorNode, ts.Diagnostics.Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword); + return false; + } + } + if (flags & 128 /* Abstract */) { + // A method cannot be accessed in a super property access if the method is abstract. + // This error could mask a private property access error. But, a member + // cannot simultaneously be private and abstract, so this will trigger an + // additional error elsewhere. + error(errorNode, ts.Diagnostics.Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression, symbolToString(prop), typeToString(getDeclaringClass(prop))); + return false; + } + } + // Referencing abstract properties within their own constructors is not allowed + if ((flags & 128 /* Abstract */) && ts.isThisProperty(node) && symbolHasNonMethodDeclaration(prop)) { + var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop)); + if (declaringClassDeclaration && isNodeUsedDuringClassInitialization(node)) { + error(errorNode, ts.Diagnostics.Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor, symbolToString(prop), ts.getTextOfIdentifierOrLiteral(declaringClassDeclaration.name)); // TODO: GH#18217 + return false; + } + } + // Public properties are otherwise accessible. + if (!(flags & 24 /* NonPublicAccessibilityModifier */)) { + return true; + } + // Property is known to be private or protected at this point + // Private property is accessible if the property is within the declaring class + if (flags & 8 /* Private */) { + var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop)); + if (!isNodeWithinClass(node, declaringClassDeclaration)) { + error(errorNode, ts.Diagnostics.Property_0_is_private_and_only_accessible_within_class_1, symbolToString(prop), typeToString(getDeclaringClass(prop))); + return false; + } + return true; + } + // Property is known to be protected at this point + // All protected properties of a supertype are accessible in a super access + if (isSuper) { + return true; + } + // Find the first enclosing class that has the declaring classes of the protected constituents + // of the property as base classes + var enclosingClass = forEachEnclosingClass(node, function (enclosingDeclaration) { + var enclosingClass = getDeclaredTypeOfSymbol(getSymbolOfNode(enclosingDeclaration)); + return isClassDerivedFromDeclaringClasses(enclosingClass, prop) ? enclosingClass : undefined; + }); + // A protected property is accessible if the property is within the declaring class or classes derived from it + if (!enclosingClass) { + // allow PropertyAccessibility if context is in function with this parameter + // static member access is disallow + var thisParameter = void 0; + if (flags & 32 /* Static */ || !(thisParameter = getThisParameterFromNodeContext(node)) || !thisParameter.type) { + error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses, symbolToString(prop), typeToString(getDeclaringClass(prop) || type)); + return false; + } + var thisType = getTypeFromTypeNode(thisParameter.type); + enclosingClass = ((thisType.flags & 262144 /* TypeParameter */) ? getConstraintOfTypeParameter(thisType) : thisType); + } + // No further restrictions for static properties + if (flags & 32 /* Static */) { + return true; + } + if (type.flags & 262144 /* TypeParameter */) { + // get the original type -- represented as the type constraint of the 'this' type + type = type.isThisType ? getConstraintOfTypeParameter(type) : getBaseConstraintOfType(type); // TODO: GH#18217 Use a different variable that's allowed to be undefined + } + if (!type || !hasBaseType(type, enclosingClass)) { + error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1, symbolToString(prop), typeToString(enclosingClass)); + return false; + } + return true; + } + function getThisParameterFromNodeContext(node) { + var thisContainer = ts.getThisContainer(node, /* includeArrowFunctions */ false); + return thisContainer && ts.isFunctionLike(thisContainer) ? ts.getThisParameter(thisContainer) : undefined; + } + function symbolHasNonMethodDeclaration(symbol) { + return !!forEachProperty(symbol, function (prop) { return !(prop.flags & 8192 /* Method */); }); + } + function checkNonNullExpression(node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic) { + return checkNonNullType(checkExpression(node), node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic); + } + function getNonNullableTypeIfNeeded(type) { + var kind = (strictNullChecks ? getFalsyFlags(type) : type.flags) & 98304 /* Nullable */; + if (kind) { + return getNonNullableType(type); + } + return type; + } + function checkNonNullType(type, node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic) { + if (type.flags & 2 /* Unknown */) { + error(node, ts.Diagnostics.Object_is_of_type_unknown); + return errorType; + } + var kind = (strictNullChecks ? getFalsyFlags(type) : type.flags) & 98304 /* Nullable */; + if (kind) { + error(node, kind & 32768 /* Undefined */ ? kind & 65536 /* Null */ ? + (nullOrUndefinedDiagnostic || ts.Diagnostics.Object_is_possibly_null_or_undefined) : + (undefinedDiagnostic || ts.Diagnostics.Object_is_possibly_undefined) : + (nullDiagnostic || ts.Diagnostics.Object_is_possibly_null)); + var t = getNonNullableType(type); + return t.flags & (98304 /* Nullable */ | 131072 /* Never */) ? errorType : t; + } + return type; + } + function checkPropertyAccessExpression(node) { + return checkPropertyAccessExpressionOrQualifiedName(node, node.expression, node.name); + } + function checkQualifiedName(node) { + return checkPropertyAccessExpressionOrQualifiedName(node, node.left, node.right); + } + function checkPropertyAccessExpressionOrQualifiedName(node, left, right) { + var propType; + var leftType = checkNonNullExpression(left); + var parentSymbol = getNodeLinks(left).resolvedSymbol; + var apparentType = getApparentType(getWidenedType(leftType)); + if (isTypeAny(apparentType) || apparentType === silentNeverType) { + if (ts.isIdentifier(left) && parentSymbol) { + markAliasReferenced(parentSymbol, node); + } + return apparentType; + } + var assignmentKind = ts.getAssignmentTargetKind(node); + var prop = getPropertyOfType(apparentType, right.escapedText); + if (ts.isIdentifier(left) && parentSymbol && !(prop && isConstEnumOrConstEnumOnlyModule(prop))) { + markAliasReferenced(parentSymbol, node); + } + if (!prop) { + var indexInfo = getIndexInfoOfType(apparentType, 0 /* String */); + if (!(indexInfo && indexInfo.type)) { + if (isJSLiteralType(leftType)) { + return anyType; + } + if (right.escapedText && !checkAndReportErrorForExtendingInterface(node)) { + reportNonexistentProperty(right, leftType.flags & 262144 /* TypeParameter */ && leftType.isThisType ? apparentType : leftType); + } + return errorType; + } + if (indexInfo.isReadonly && (ts.isAssignmentTarget(node) || ts.isDeleteTarget(node))) { + error(node, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(apparentType)); + } + propType = indexInfo.type; + } + else { + checkPropertyNotUsedBeforeDeclaration(prop, node, right); + markPropertyAsReferenced(prop, node, left.kind === 100 /* ThisKeyword */); + getNodeLinks(node).resolvedSymbol = prop; + checkPropertyAccessibility(node, left.kind === 98 /* SuperKeyword */, apparentType, prop); + if (assignmentKind) { + if (isReferenceToReadonlyEntity(node, prop) || isReferenceThroughNamespaceImport(node)) { + error(right, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, ts.idText(right)); + return errorType; + } + } + propType = getConstraintForLocation(getTypeOfSymbol(prop), node); + } + // Only compute control flow type if this is a property access expression that isn't an + // assignment target, and the referenced property was declared as a variable, property, + // accessor, or optional method. + if (node.kind !== 189 /* PropertyAccessExpression */ || + assignmentKind === 1 /* Definite */ || + prop && !(prop.flags & (3 /* Variable */ | 4 /* Property */ | 98304 /* Accessor */)) && !(prop.flags & 8192 /* Method */ && propType.flags & 1048576 /* Union */)) { + return propType; + } + // If strict null checks and strict property initialization checks are enabled, if we have + // a this.xxx property access, if the property is an instance property without an initializer, + // and if we are in a constructor of the same class as the property declaration, assume that + // the property is uninitialized at the top of the control flow. + var assumeUninitialized = false; + if (strictNullChecks && strictPropertyInitialization && left.kind === 100 /* ThisKeyword */) { + var declaration = prop && prop.valueDeclaration; + if (declaration && isInstancePropertyWithoutInitializer(declaration)) { + var flowContainer = getControlFlowContainer(node); + if (flowContainer.kind === 157 /* Constructor */ && flowContainer.parent === declaration.parent) { + assumeUninitialized = true; + } + } + } + else if (strictNullChecks && prop && prop.valueDeclaration && + ts.isPropertyAccessExpression(prop.valueDeclaration) && + ts.getAssignmentDeclarationPropertyAccessKind(prop.valueDeclaration) && + getControlFlowContainer(node) === getControlFlowContainer(prop.valueDeclaration)) { + assumeUninitialized = true; + } + var flowType = getFlowTypeOfReference(node, propType, assumeUninitialized ? getOptionalType(propType) : propType); + if (assumeUninitialized && !(getFalsyFlags(propType) & 32768 /* Undefined */) && getFalsyFlags(flowType) & 32768 /* Undefined */) { + error(right, ts.Diagnostics.Property_0_is_used_before_being_assigned, symbolToString(prop)); // TODO: GH#18217 + // Return the declared type to reduce follow-on errors + return propType; + } + return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType; + } + function checkPropertyNotUsedBeforeDeclaration(prop, node, right) { + var valueDeclaration = prop.valueDeclaration; + if (!valueDeclaration) { + return; + } + var diagnosticMessage; + var declarationName = ts.idText(right); + if (isInPropertyInitializer(node) && + !isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right) + && !isPropertyDeclaredInAncestorClass(prop)) { + diagnosticMessage = error(right, ts.Diagnostics.Property_0_is_used_before_its_initialization, declarationName); + } + else if (valueDeclaration.kind === 240 /* ClassDeclaration */ && + node.parent.kind !== 164 /* TypeReference */ && + !(valueDeclaration.flags & 4194304 /* Ambient */) && + !isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right)) { + diagnosticMessage = error(right, ts.Diagnostics.Class_0_used_before_its_declaration, declarationName); + } + if (diagnosticMessage) { + addRelatedInfo(diagnosticMessage, ts.createDiagnosticForNode(valueDeclaration, ts.Diagnostics._0_is_declared_here, declarationName)); + } + } + function isInPropertyInitializer(node) { + return !!ts.findAncestor(node, function (node) { + switch (node.kind) { + case 154 /* PropertyDeclaration */: + return true; + case 275 /* PropertyAssignment */: + // We might be in `a = { b: this.b }`, so keep looking. See `tests/cases/compiler/useBeforeDeclaration_propertyAssignment.ts`. + return false; + default: + return ts.isExpressionNode(node) ? false : "quit"; + } + }); + } + /** + * It's possible that "prop.valueDeclaration" is a local declaration, but the property was also declared in a superclass. + * In that case we won't consider it used before its declaration, because it gets its value from the superclass' declaration. + */ + function isPropertyDeclaredInAncestorClass(prop) { + if (!(prop.parent.flags & 32 /* Class */)) { + return false; + } + var classType = getTypeOfSymbol(prop.parent); + while (true) { + classType = classType.symbol && getSuperClass(classType); + if (!classType) { + return false; + } + var superProperty = getPropertyOfType(classType, prop.escapedName); + if (superProperty && superProperty.valueDeclaration) { + return true; + } + } + } + function getSuperClass(classType) { + var x = getBaseTypes(classType); + if (x.length === 0) { + return undefined; + } + return getIntersectionType(x); + } + function reportNonexistentProperty(propNode, containingType) { + var errorInfo; + var relatedInfo; + if (containingType.flags & 1048576 /* Union */ && !(containingType.flags & 131068 /* Primitive */)) { + for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) { + var subtype = _a[_i]; + if (!getPropertyOfType(subtype, propNode.escapedText)) { + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(subtype)); + break; + } + } + } + if (typeHasStaticProperty(propNode.escapedText, containingType)) { + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_is_a_static_member_of_type_1, ts.declarationNameToString(propNode), typeToString(containingType)); + } + else { + var promisedType = getPromisedTypeOfPromise(containingType); + if (promisedType && getPropertyOfType(promisedType, propNode.escapedText)) { + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_forget_to_use_await, ts.declarationNameToString(propNode), typeToString(containingType)); + } + else { + var suggestion = getSuggestedSymbolForNonexistentProperty(propNode, containingType); + if (suggestion !== undefined) { + var suggestedName = ts.symbolName(suggestion); + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2, ts.declarationNameToString(propNode), typeToString(containingType), suggestedName); + relatedInfo = suggestion.valueDeclaration && ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestedName); + } + else { + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(containingType)); + } + } + } + var resultDiagnostic = ts.createDiagnosticForNodeFromMessageChain(propNode, errorInfo); + if (relatedInfo) { + addRelatedInfo(resultDiagnostic, relatedInfo); + } + diagnostics.add(resultDiagnostic); + } + function typeHasStaticProperty(propName, containingType) { + var prop = containingType.symbol && getPropertyOfType(getTypeOfSymbol(containingType.symbol), propName); + return prop !== undefined && prop.valueDeclaration && ts.hasModifier(prop.valueDeclaration, 32 /* Static */); + } + function getSuggestedSymbolForNonexistentProperty(name, containingType) { + return getSpellingSuggestionForName(ts.isString(name) ? name : ts.idText(name), getPropertiesOfType(containingType), 67220415 /* Value */); + } + function getSuggestionForNonexistentProperty(name, containingType) { + var suggestion = getSuggestedSymbolForNonexistentProperty(name, containingType); + return suggestion && ts.symbolName(suggestion); + } + function getSuggestedSymbolForNonexistentSymbol(location, outerName, meaning) { + ts.Debug.assert(outerName !== undefined, "outername should always be defined"); + var result = resolveNameHelper(location, outerName, meaning, /*nameNotFoundMessage*/ undefined, outerName, /*isUse*/ false, /*excludeGlobals*/ false, function (symbols, name, meaning) { + ts.Debug.assertEqual(outerName, name, "name should equal outerName"); + var symbol = getSymbol(symbols, name, meaning); + // Sometimes the symbol is found when location is a return type of a function: `typeof x` and `x` is declared in the body of the function + // So the table *contains* `x` but `x` isn't actually in scope. + // However, resolveNameHelper will continue and call this callback again, so we'll eventually get a correct suggestion. + return symbol || getSpellingSuggestionForName(ts.unescapeLeadingUnderscores(name), ts.arrayFrom(symbols.values()), meaning); + }); + return result; + } + function getSuggestionForNonexistentSymbol(location, outerName, meaning) { + var symbolResult = getSuggestedSymbolForNonexistentSymbol(location, outerName, meaning); + return symbolResult && ts.symbolName(symbolResult); + } + function getSuggestedSymbolForNonexistentModule(name, targetModule) { + return targetModule.exports && getSpellingSuggestionForName(ts.idText(name), getExportsOfModuleAsArray(targetModule), 2623475 /* ModuleMember */); + } + function getSuggestionForNonexistentExport(name, targetModule) { + var suggestion = getSuggestedSymbolForNonexistentModule(name, targetModule); + return suggestion && ts.symbolName(suggestion); + } + /** + * Given a name and a list of symbols whose names are *not* equal to the name, return a spelling suggestion if there is one that is close enough. + * Names less than length 3 only check for case-insensitive equality, not levenshtein distance. + * + * If there is a candidate that's the same except for case, return that. + * If there is a candidate that's within one edit of the name, return that. + * Otherwise, return the candidate with the smallest Levenshtein distance, + * except for candidates: + * * With no name + * * Whose meaning doesn't match the `meaning` parameter. + * * Whose length differs from the target name by more than 0.34 of the length of the name. + * * Whose levenshtein distance is more than 0.4 of the length of the name + * (0.4 allows 1 substitution/transposition for every 5 characters, + * and 1 insertion/deletion at 3 characters) + */ + function getSpellingSuggestionForName(name, symbols, meaning) { + return ts.getSpellingSuggestion(name, symbols, getCandidateName); + function getCandidateName(candidate) { + var candidateName = ts.symbolName(candidate); + return !ts.startsWith(candidateName, "\"") && candidate.flags & meaning ? candidateName : undefined; + } + } + function markPropertyAsReferenced(prop, nodeForCheckWriteOnly, isThisAccess) { + if (!prop || !(prop.flags & 106500 /* ClassMember */) || !prop.valueDeclaration || !ts.hasModifier(prop.valueDeclaration, 8 /* Private */)) { + return; + } + if (nodeForCheckWriteOnly && ts.isWriteOnlyAccess(nodeForCheckWriteOnly) && !(prop.flags & 65536 /* SetAccessor */ && !(prop.flags & 32768 /* GetAccessor */))) { + return; + } + if (isThisAccess) { + // Find any FunctionLikeDeclaration because those create a new 'this' binding. But this should only matter for methods (or getters/setters). + var containingMethod = ts.findAncestor(nodeForCheckWriteOnly, ts.isFunctionLikeDeclaration); + if (containingMethod && containingMethod.symbol === prop) { + return; + } + } + (ts.getCheckFlags(prop) & 1 /* Instantiated */ ? getSymbolLinks(prop).target : prop).isReferenced = 67108863 /* All */; + } + function isValidPropertyAccess(node, propertyName) { + switch (node.kind) { + case 189 /* PropertyAccessExpression */: + return isValidPropertyAccessWithType(node, node.expression.kind === 98 /* SuperKeyword */, propertyName, getWidenedType(checkExpression(node.expression))); + case 148 /* QualifiedName */: + return isValidPropertyAccessWithType(node, /*isSuper*/ false, propertyName, getWidenedType(checkExpression(node.left))); + case 183 /* ImportType */: + return isValidPropertyAccessWithType(node, /*isSuper*/ false, propertyName, getTypeFromTypeNode(node)); + } + } + function isValidPropertyAccessForCompletions(node, type, property) { + return isValidPropertyAccessWithType(node, node.kind !== 183 /* ImportType */ && node.expression.kind === 98 /* SuperKeyword */, property.escapedName, type) + && (!(property.flags & 8192 /* Method */) || isValidMethodAccess(property, type)); + } + function isValidMethodAccess(method, actualThisType) { + var propType = getTypeOfPropertyOfType(actualThisType, method.escapedName); + var signatures = getSignaturesOfType(getNonNullableType(propType), 0 /* Call */); + ts.Debug.assert(signatures.length !== 0); + return signatures.some(function (sig) { + var signatureThisType = getThisTypeOfSignature(sig); + return !signatureThisType || isTypeAssignableTo(actualThisType, getInstantiatedSignatureThisType(sig, signatureThisType, actualThisType)); + }); + } + function getInstantiatedSignatureThisType(sig, signatureThisType, actualThisType) { + if (!sig.typeParameters) { + return signatureThisType; + } + var context = createInferenceContext(sig.typeParameters, sig, 0 /* None */); + inferTypes(context.inferences, actualThisType, signatureThisType); + return instantiateType(signatureThisType, createSignatureTypeMapper(sig, getInferredTypes(context))); + } + function isValidPropertyAccessWithType(node, isSuper, propertyName, type) { + if (type === errorType || isTypeAny(type)) { + return true; + } + var prop = getPropertyOfType(type, propertyName); + return prop ? checkPropertyAccessibility(node, isSuper, type, prop) + // In js files properties of unions are allowed in completion + : ts.isInJSFile(node) && (type.flags & 1048576 /* Union */) !== 0 && type.types.some(function (elementType) { return isValidPropertyAccessWithType(node, isSuper, propertyName, elementType); }); + } + /** + * Return the symbol of the for-in variable declared or referenced by the given for-in statement. + */ + function getForInVariableSymbol(node) { + var initializer = node.initializer; + if (initializer.kind === 238 /* VariableDeclarationList */) { + var variable = initializer.declarations[0]; + if (variable && !ts.isBindingPattern(variable.name)) { + return getSymbolOfNode(variable); + } + } + else if (initializer.kind === 72 /* Identifier */) { + return getResolvedSymbol(initializer); + } + return undefined; + } + /** + * Return true if the given type is considered to have numeric property names. + */ + function hasNumericPropertyNames(type) { + return getIndexTypeOfType(type, 1 /* Number */) && !getIndexTypeOfType(type, 0 /* String */); + } + /** + * Return true if given node is an expression consisting of an identifier (possibly parenthesized) + * that references a for-in variable for an object with numeric property names. + */ + function isForInVariableForNumericPropertyNames(expr) { + var e = ts.skipParentheses(expr); + if (e.kind === 72 /* Identifier */) { + var symbol = getResolvedSymbol(e); + if (symbol.flags & 3 /* Variable */) { + var child = expr; + var node = expr.parent; + while (node) { + if (node.kind === 226 /* ForInStatement */ && + child === node.statement && + getForInVariableSymbol(node) === symbol && + hasNumericPropertyNames(getTypeOfExpression(node.expression))) { + return true; + } + child = node; + node = node.parent; + } + } + } + return false; + } + function checkIndexedAccess(node) { + var objectType = checkNonNullExpression(node.expression); + var indexExpression = node.argumentExpression; + if (!indexExpression) { + var sourceFile = ts.getSourceFileOfNode(node); + if (node.parent.kind === 192 /* NewExpression */ && node.parent.expression === node) { + var start = ts.skipTrivia(sourceFile.text, node.expression.end); + var end = node.end; + grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead); + } + else { + var start = node.end - "]".length; + var end = node.end; + grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.Expression_expected); + } + return errorType; + } + var indexType = checkExpression(indexExpression); + if (objectType === errorType || objectType === silentNeverType) { + return objectType; + } + if (isConstEnumObjectType(objectType) && indexExpression.kind !== 10 /* StringLiteral */) { + error(indexExpression, ts.Diagnostics.A_const_enum_member_can_only_be_accessed_using_a_string_literal); + return errorType; + } + return checkIndexedAccessIndexType(getIndexedAccessType(objectType, isForInVariableForNumericPropertyNames(indexExpression) ? numberType : indexType, node), node); + } + function checkThatExpressionIsProperSymbolReference(expression, expressionType, reportError) { + if (expressionType === errorType) { + // There is already an error, so no need to report one. + return false; + } + if (!ts.isWellKnownSymbolSyntactically(expression)) { + return false; + } + // Make sure the property type is the primitive symbol type + if ((expressionType.flags & 12288 /* ESSymbolLike */) === 0) { + if (reportError) { + error(expression, ts.Diagnostics.A_computed_property_name_of_the_form_0_must_be_of_type_symbol, ts.getTextOfNode(expression)); + } + return false; + } + // The name is Symbol., so make sure Symbol actually resolves to the + // global Symbol object + var leftHandSide = expression.expression; + var leftHandSideSymbol = getResolvedSymbol(leftHandSide); + if (!leftHandSideSymbol) { + return false; + } + var globalESSymbol = getGlobalESSymbolConstructorSymbol(/*reportErrors*/ true); + if (!globalESSymbol) { + // Already errored when we tried to look up the symbol + return false; + } + if (leftHandSideSymbol !== globalESSymbol) { + if (reportError) { + error(leftHandSide, ts.Diagnostics.Symbol_reference_does_not_refer_to_the_global_Symbol_constructor_object); + } + return false; + } + return true; + } + function callLikeExpressionMayHaveTypeArguments(node) { + return ts.isCallOrNewExpression(node) || ts.isTaggedTemplateExpression(node) || ts.isJsxOpeningLikeElement(node); + } + function resolveUntypedCall(node) { + if (callLikeExpressionMayHaveTypeArguments(node)) { + // Check type arguments even though we will give an error that untyped calls may not accept type arguments. + // This gets us diagnostics for the type arguments and marks them as referenced. + ts.forEach(node.typeArguments, checkSourceElement); + } + if (node.kind === 193 /* TaggedTemplateExpression */) { + checkExpression(node.template); + } + else if (ts.isJsxOpeningLikeElement(node)) { + checkExpression(node.attributes); + } + else if (node.kind !== 152 /* Decorator */) { + ts.forEach(node.arguments, function (argument) { + checkExpression(argument); + }); + } + return anySignature; + } + function resolveErrorCall(node) { + resolveUntypedCall(node); + return unknownSignature; + } + // Re-order candidate signatures into the result array. Assumes the result array to be empty. + // The candidate list orders groups in reverse, but within a group signatures are kept in declaration order + // A nit here is that we reorder only signatures that belong to the same symbol, + // so order how inherited signatures are processed is still preserved. + // interface A { (x: string): void } + // interface B extends A { (x: 'foo'): string } + // const b: B; + // b('foo') // <- here overloads should be processed as [(x:'foo'): string, (x: string): void] + function reorderCandidates(signatures, result) { + var lastParent; + var lastSymbol; + var cutoffIndex = 0; + var index; + var specializedIndex = -1; + var spliceIndex; + ts.Debug.assert(!result.length); + for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { + var signature = signatures_3[_i]; + var symbol = signature.declaration && getSymbolOfNode(signature.declaration); + var parent = signature.declaration && signature.declaration.parent; + if (!lastSymbol || symbol === lastSymbol) { + if (lastParent && parent === lastParent) { + index = index + 1; + } + else { + lastParent = parent; + index = cutoffIndex; + } + } + else { + // current declaration belongs to a different symbol + // set cutoffIndex so re-orderings in the future won't change result set from 0 to cutoffIndex + index = cutoffIndex = result.length; + lastParent = parent; + } + lastSymbol = symbol; + // specialized signatures always need to be placed before non-specialized signatures regardless + // of the cutoff position; see GH#1133 + if (signature.hasLiteralTypes) { + specializedIndex++; + spliceIndex = specializedIndex; + // The cutoff index always needs to be greater than or equal to the specialized signature index + // in order to prevent non-specialized signatures from being added before a specialized + // signature. + cutoffIndex++; + } + else { + spliceIndex = index; + } + result.splice(spliceIndex, 0, signature); + } + } + function isSpreadArgument(arg) { + return !!arg && (arg.kind === 208 /* SpreadElement */ || arg.kind === 215 /* SyntheticExpression */ && arg.isSpread); + } + function getSpreadArgumentIndex(args) { + return ts.findIndex(args, isSpreadArgument); + } + function acceptsVoid(t) { + return !!(t.flags & 16384 /* Void */); + } + function hasCorrectArity(node, args, signature, signatureHelpTrailingComma) { + if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; } + var argCount; + var callIsIncomplete = false; // In incomplete call we want to be lenient when we have too few arguments + var effectiveParameterCount = getParameterCount(signature); + var effectiveMinimumArguments = getMinArgumentCount(signature); + if (node.kind === 193 /* TaggedTemplateExpression */) { + argCount = args.length; + if (node.template.kind === 206 /* TemplateExpression */) { + // If a tagged template expression lacks a tail literal, the call is incomplete. + // Specifically, a template only can end in a TemplateTail or a Missing literal. + var lastSpan = ts.last(node.template.templateSpans); // we should always have at least one span. + callIsIncomplete = ts.nodeIsMissing(lastSpan.literal) || !!lastSpan.literal.isUnterminated; + } + else { + // If the template didn't end in a backtick, or its beginning occurred right prior to EOF, + // then this might actually turn out to be a TemplateHead in the future; + // so we consider the call to be incomplete. + var templateLiteral = node.template; + ts.Debug.assert(templateLiteral.kind === 14 /* NoSubstitutionTemplateLiteral */); + callIsIncomplete = !!templateLiteral.isUnterminated; + } + } + else if (node.kind === 152 /* Decorator */) { + argCount = getDecoratorArgumentCount(node, signature); + } + else if (ts.isJsxOpeningLikeElement(node)) { + callIsIncomplete = node.attributes.end === node.end; + if (callIsIncomplete) { + return true; + } + argCount = effectiveMinimumArguments === 0 ? args.length : 1; + effectiveParameterCount = args.length === 0 ? effectiveParameterCount : 1; // class may have argumentless ctor functions - still resolve ctor and compare vs props member type + effectiveMinimumArguments = Math.min(effectiveMinimumArguments, 1); // sfc may specify context argument - handled by framework and not typechecked + } + else { + if (!node.arguments) { + // This only happens when we have something of the form: 'new C' + ts.Debug.assert(node.kind === 192 /* NewExpression */); + return getMinArgumentCount(signature) === 0; + } + argCount = signatureHelpTrailingComma ? args.length + 1 : args.length; + // If we are missing the close parenthesis, the call is incomplete. + callIsIncomplete = node.arguments.end === node.end; + // If a spread argument is present, check that it corresponds to a rest parameter or at least that it's in the valid range. + var spreadArgIndex = getSpreadArgumentIndex(args); + if (spreadArgIndex >= 0) { + return spreadArgIndex >= getMinArgumentCount(signature) && (hasEffectiveRestParameter(signature) || spreadArgIndex < getParameterCount(signature)); + } + } + // Too many arguments implies incorrect arity. + if (!hasEffectiveRestParameter(signature) && argCount > effectiveParameterCount) { + return false; + } + // If the call is incomplete, we should skip the lower bound check. + // JSX signatures can have extra parameters provided by the library which we don't check + if (callIsIncomplete || argCount >= effectiveMinimumArguments) { + return true; + } + for (var i = argCount; i < effectiveMinimumArguments; i++) { + var type = getTypeAtPosition(signature, i); + if (filterType(type, acceptsVoid).flags & 131072 /* Never */) { + return false; + } + } + return true; + } + function hasCorrectTypeArgumentArity(signature, typeArguments) { + // If the user supplied type arguments, but the number of type arguments does not match + // the declared number of type parameters, the call has an incorrect arity. + var numTypeParameters = ts.length(signature.typeParameters); + var minTypeArgumentCount = getMinTypeArgumentCount(signature.typeParameters); + return !typeArguments || + (typeArguments.length >= minTypeArgumentCount && typeArguments.length <= numTypeParameters); + } + // If type has a single call signature and no other members, return that signature. Otherwise, return undefined. + function getSingleCallSignature(type) { + if (type.flags & 524288 /* Object */) { + var resolved = resolveStructuredTypeMembers(type); + if (resolved.callSignatures.length === 1 && resolved.constructSignatures.length === 0 && + resolved.properties.length === 0 && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { + return resolved.callSignatures[0]; + } + } + return undefined; + } + // Instantiate a generic signature in the context of a non-generic signature (section 3.8.5 in TypeScript spec) + function instantiateSignatureInContextOf(signature, contextualSignature, contextualMapper, compareTypes) { + var context = createInferenceContext(signature.typeParameters, signature, 0 /* None */, compareTypes); + var sourceSignature = contextualMapper ? instantiateSignature(contextualSignature, contextualMapper) : contextualSignature; + forEachMatchingParameterType(sourceSignature, signature, function (source, target) { + // Type parameters from outer context referenced by source type are fixed by instantiation of the source type + inferTypes(context.inferences, source, target); + }); + if (!contextualMapper) { + inferTypes(context.inferences, getReturnTypeOfSignature(contextualSignature), getReturnTypeOfSignature(signature), 8 /* ReturnType */); + } + return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJSFile(contextualSignature.declaration)); + } + function inferJsxTypeArguments(node, signature, excludeArgument, context) { + var paramType = getEffectiveFirstArgumentForJsxSignature(signature, node); + var checkAttrType = checkExpressionWithContextualType(node.attributes, paramType, excludeArgument && excludeArgument[0] !== undefined ? identityMapper : context); + inferTypes(context.inferences, checkAttrType, paramType); + return getInferredTypes(context); + } + function inferTypeArguments(node, signature, args, excludeArgument, context) { + // Clear out all the inference results from the last time inferTypeArguments was called on this context + for (var _i = 0, _a = context.inferences; _i < _a.length; _i++) { + var inference = _a[_i]; + // As an optimization, we don't have to clear (and later recompute) inferred types + // for type parameters that have already been fixed on the previous call to inferTypeArguments. + // It would be just as correct to reset all of them. But then we'd be repeating the same work + // for the type parameters that were fixed, namely the work done by getInferredType. + if (!inference.isFixed) { + inference.inferredType = undefined; + } + } + if (ts.isJsxOpeningLikeElement(node)) { + return inferJsxTypeArguments(node, signature, excludeArgument, context); + } + // If a contextual type is available, infer from that type to the return type of the call expression. For + // example, given a 'function wrap(cb: (x: T) => U): (x: T) => U' and a call expression + // 'let f: (x: string) => number = wrap(s => s.length)', we infer from the declared type of 'f' to the + // return type of 'wrap'. + if (node.kind !== 152 /* Decorator */) { + var contextualType = getContextualType(node); + if (contextualType) { + // We clone the contextual mapper to avoid disturbing a resolution in progress for an + // outer call expression. Effectively we just want a snapshot of whatever has been + // inferred for any outer call expression so far. + var instantiatedType = instantiateType(contextualType, cloneTypeMapper(getContextualMapper(node))); + // If the contextual type is a generic function type with a single call signature, we + // instantiate the type with its own type parameters and type arguments. This ensures that + // the type parameters are not erased to type any during type inference such that they can + // be inferred as actual types from the contextual type. For example: + // declare function arrayMap(f: (x: T) => U): (a: T[]) => U[]; + // const boxElements: (a: A[]) => { value: A }[] = arrayMap(value => ({ value })); + // Above, the type of the 'value' parameter is inferred to be 'A'. + var contextualSignature = getSingleCallSignature(instantiatedType); + var inferenceSourceType = contextualSignature && contextualSignature.typeParameters ? + getOrCreateTypeFromSignature(getSignatureInstantiationWithoutFillingInTypeArguments(contextualSignature, contextualSignature.typeParameters)) : + instantiatedType; + var inferenceTargetType = getReturnTypeOfSignature(signature); + // Inferences made from return types have lower priority than all other inferences. + inferTypes(context.inferences, inferenceSourceType, inferenceTargetType, 8 /* ReturnType */); + } + } + var thisType = getThisTypeOfSignature(signature); + if (thisType) { + var thisArgumentNode = getThisArgumentOfCall(node); + var thisArgumentType = thisArgumentNode ? checkExpression(thisArgumentNode) : voidType; + inferTypes(context.inferences, thisArgumentType, thisType); + } + var restType = getNonArrayRestType(signature); + var argCount = restType ? Math.min(getParameterCount(signature) - 1, args.length) : args.length; + for (var i = 0; i < argCount; i++) { + var arg = args[i]; + if (arg.kind !== 210 /* OmittedExpression */) { + var paramType = getTypeAtPosition(signature, i); + // For context sensitive arguments we pass the identityMapper, which is a signal to treat all + // context sensitive function expressions as wildcards + var mapper = excludeArgument && excludeArgument[i] !== undefined ? identityMapper : context; + var argType = checkExpressionWithContextualType(arg, paramType, mapper); + inferTypes(context.inferences, argType, paramType); + } + } + if (restType) { + var spreadType = getSpreadArgumentType(args, argCount, args.length, restType, context); + inferTypes(context.inferences, spreadType, restType); + } + return getInferredTypes(context); + } + function getArrayifiedType(type) { + if (forEachType(type, function (t) { return !(t.flags & (1 /* Any */ | 63176704 /* Instantiable */) || isArrayType(t) || isTupleType(t)); })) { + return createArrayType(getIndexTypeOfType(type, 1 /* Number */) || errorType); + } + return type; + } + function getSpreadArgumentType(args, index, argCount, restType, context) { + if (index >= argCount - 1) { + var arg = args[argCount - 1]; + if (isSpreadArgument(arg)) { + // We are inferring from a spread expression in the last argument position, i.e. both the parameter + // and the argument are ...x forms. + return arg.kind === 215 /* SyntheticExpression */ ? + createArrayType(arg.type) : + getArrayifiedType(checkExpressionWithContextualType(arg.expression, restType, context)); + } + } + var contextualType = getIndexTypeOfType(restType, 1 /* Number */) || anyType; + var hasPrimitiveContextualType = maybeTypeOfKind(contextualType, 131068 /* Primitive */ | 4194304 /* Index */); + var types = []; + var spreadIndex = -1; + for (var i = index; i < argCount; i++) { + var argType = checkExpressionWithContextualType(args[i], contextualType, context); + if (spreadIndex < 0 && isSpreadArgument(args[i])) { + spreadIndex = i - index; + } + types.push(hasPrimitiveContextualType ? getRegularTypeOfLiteralType(argType) : getWidenedLiteralType(argType)); + } + return spreadIndex < 0 ? + createTupleType(types) : + createTupleType(ts.append(types.slice(0, spreadIndex), getUnionType(types.slice(spreadIndex))), spreadIndex, /*hasRestElement*/ true); + } + function checkTypeArguments(signature, typeArgumentNodes, reportErrors, headMessage) { + var isJavascript = ts.isInJSFile(signature.declaration); + var typeParameters = signature.typeParameters; + var typeArgumentTypes = fillMissingTypeArguments(ts.map(typeArgumentNodes, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), isJavascript); + var mapper; + for (var i = 0; i < typeArgumentNodes.length; i++) { + ts.Debug.assert(typeParameters[i] !== undefined, "Should not call checkTypeArguments with too many type arguments"); + var constraint = getConstraintOfTypeParameter(typeParameters[i]); + if (constraint) { + var errorInfo = reportErrors && headMessage ? (function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); }) : undefined; + var typeArgumentHeadMessage = headMessage || ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1; + if (!mapper) { + mapper = createTypeMapper(typeParameters, typeArgumentTypes); + } + var typeArgument = typeArgumentTypes[i]; + if (!checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), reportErrors ? typeArgumentNodes[i] : undefined, typeArgumentHeadMessage, errorInfo)) { + return undefined; + } + } + } + return typeArgumentTypes; + } + function getJsxReferenceKind(node) { + if (isJsxIntrinsicIdentifier(node.tagName)) { + return 2 /* Mixed */; + } + var tagType = getApparentType(checkExpression(node.tagName)); + if (ts.length(getSignaturesOfType(tagType, 1 /* Construct */))) { + return 0 /* Component */; + } + if (ts.length(getSignaturesOfType(tagType, 0 /* Call */))) { + return 1 /* Function */; + } + return 2 /* Mixed */; + } + /** + * Check if the given signature can possibly be a signature called by the JSX opening-like element. + * @param node a JSX opening-like element we are trying to figure its call signature + * @param signature a candidate signature we are trying whether it is a call signature + * @param relation a relationship to check parameter and argument type + * @param excludeArgument + */ + function checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation, excludeArgument, reportErrors) { + // Stateless function components can have maximum of three arguments: "props", "context", and "updater". + // However "context" and "updater" are implicit and can't be specify by users. Only the first parameter, props, + // can be specified by users through attributes property. + var paramType = getEffectiveFirstArgumentForJsxSignature(signature, node); + var attributesType = checkExpressionWithContextualType(node.attributes, paramType, excludeArgument && excludeArgument[0] ? identityMapper : undefined); + return checkTypeRelatedToAndOptionallyElaborate(attributesType, paramType, relation, reportErrors ? node.tagName : undefined, node.attributes); + } + function checkApplicableSignature(node, args, signature, relation, excludeArgument, reportErrors) { + if (ts.isJsxOpeningLikeElement(node)) { + return checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation, excludeArgument, reportErrors); + } + var thisType = getThisTypeOfSignature(signature); + if (thisType && thisType !== voidType && node.kind !== 192 /* NewExpression */) { + // If the called expression is not of the form `x.f` or `x["f"]`, then sourceType = voidType + // If the signature's 'this' type is voidType, then the check is skipped -- anything is compatible. + // If the expression is a new expression, then the check is skipped. + var thisArgumentNode = getThisArgumentOfCall(node); + var thisArgumentType = thisArgumentNode ? checkExpression(thisArgumentNode) : voidType; + var errorNode = reportErrors ? (thisArgumentNode || node) : undefined; + var headMessage_1 = ts.Diagnostics.The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1; + if (!checkTypeRelatedTo(thisArgumentType, thisType, relation, errorNode, headMessage_1)) { + return false; + } + } + var headMessage = ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1; + var restType = getNonArrayRestType(signature); + var argCount = restType ? Math.min(getParameterCount(signature) - 1, args.length) : args.length; + for (var i = 0; i < argCount; i++) { + var arg = args[i]; + if (arg.kind !== 210 /* OmittedExpression */) { + var paramType = getTypeAtPosition(signature, i); + var argType = checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); + // If one or more arguments are still excluded (as indicated by a non-null excludeArgument parameter), + // we obtain the regular type of any object literal arguments because we may not have inferred complete + // parameter types yet and therefore excess property checks may yield false positives (see #17041). + var checkArgType = excludeArgument ? getRegularTypeOfObjectLiteral(argType) : argType; + if (!checkTypeRelatedToAndOptionallyElaborate(checkArgType, paramType, relation, reportErrors ? arg : undefined, arg, headMessage)) { + return false; + } + } + } + if (restType) { + var spreadType = getSpreadArgumentType(args, argCount, args.length, restType, /*context*/ undefined); + var errorNode = reportErrors ? argCount < args.length ? args[argCount] : node : undefined; + return checkTypeRelatedTo(spreadType, restType, relation, errorNode, headMessage); + } + return true; + } + /** + * Returns the this argument in calls like x.f(...) and x[f](...). Undefined otherwise. + */ + function getThisArgumentOfCall(node) { + if (node.kind === 191 /* CallExpression */) { + var callee = ts.skipOuterExpressions(node.expression); + if (callee.kind === 189 /* PropertyAccessExpression */ || callee.kind === 190 /* ElementAccessExpression */) { + return callee.expression; + } + } + } + function createSyntheticExpression(parent, type, isSpread) { + var result = ts.createNode(215 /* SyntheticExpression */, parent.pos, parent.end); + result.parent = parent; + result.type = type; + result.isSpread = isSpread || false; + return result; + } + /** + * Returns the effective arguments for an expression that works like a function invocation. + */ + function getEffectiveCallArguments(node) { + if (node.kind === 193 /* TaggedTemplateExpression */) { + var template = node.template; + var args_4 = [createSyntheticExpression(template, getGlobalTemplateStringsArrayType())]; + if (template.kind === 206 /* TemplateExpression */) { + ts.forEach(template.templateSpans, function (span) { + args_4.push(span.expression); + }); + } + return args_4; + } + if (node.kind === 152 /* Decorator */) { + return getEffectiveDecoratorArguments(node); + } + if (ts.isJsxOpeningLikeElement(node)) { + return node.attributes.properties.length > 0 || (ts.isJsxOpeningElement(node) && node.parent.children.length > 0) ? [node.attributes] : ts.emptyArray; + } + var args = node.arguments || ts.emptyArray; + var length = args.length; + if (length && isSpreadArgument(args[length - 1]) && getSpreadArgumentIndex(args) === length - 1) { + // We have a spread argument in the last position and no other spread arguments. If the type + // of the argument is a tuple type, spread the tuple elements into the argument list. We can + // call checkExpressionCached because spread expressions never have a contextual type. + var spreadArgument_1 = args[length - 1]; + var type = checkExpressionCached(spreadArgument_1.expression); + if (isTupleType(type)) { + var typeArguments = type.typeArguments || ts.emptyArray; + var restIndex_2 = type.target.hasRestElement ? typeArguments.length - 1 : -1; + var syntheticArgs = ts.map(typeArguments, function (t, i) { return createSyntheticExpression(spreadArgument_1, t, /*isSpread*/ i === restIndex_2); }); + return ts.concatenate(args.slice(0, length - 1), syntheticArgs); + } + } + return args; + } + /** + * Returns the synthetic argument list for a decorator invocation. + */ + function getEffectiveDecoratorArguments(node) { + var parent = node.parent; + var expr = node.expression; + switch (parent.kind) { + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + // For a class decorator, the `target` is the type of the class (e.g. the + // "static" or "constructor" side of the class). + return [ + createSyntheticExpression(expr, getTypeOfSymbol(getSymbolOfNode(parent))) + ]; + case 151 /* Parameter */: + // A parameter declaration decorator will have three arguments (see + // `ParameterDecorator` in core.d.ts). + var func = parent.parent; + return [ + createSyntheticExpression(expr, parent.parent.kind === 157 /* Constructor */ ? getTypeOfSymbol(getSymbolOfNode(func)) : errorType), + createSyntheticExpression(expr, anyType), + createSyntheticExpression(expr, numberType) + ]; + case 154 /* PropertyDeclaration */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + // A method or accessor declaration decorator will have two or three arguments (see + // `PropertyDecorator` and `MethodDecorator` in core.d.ts). If we are emitting decorators + // for ES3, we will only pass two arguments. + var hasPropDesc = parent.kind !== 154 /* PropertyDeclaration */ && languageVersion !== 0 /* ES3 */; + return [ + createSyntheticExpression(expr, getParentTypeOfClassElement(parent)), + createSyntheticExpression(expr, getClassElementPropertyKeyType(parent)), + createSyntheticExpression(expr, hasPropDesc ? createTypedPropertyDescriptorType(getTypeOfNode(parent)) : anyType) + ]; + } + return ts.Debug.fail(); + } + /** + * Returns the argument count for a decorator node that works like a function invocation. + */ + function getDecoratorArgumentCount(node, signature) { + switch (node.parent.kind) { + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + return 1; + case 154 /* PropertyDeclaration */: + return 2; + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + // For ES3 or decorators with only two parameters we supply only two arguments + return languageVersion === 0 /* ES3 */ || signature.parameters.length <= 2 ? 2 : 3; + case 151 /* Parameter */: + return 3; + default: + return ts.Debug.fail(); + } + } + function getArgumentArityError(node, signatures, args) { + var min = Number.POSITIVE_INFINITY; + var max = Number.NEGATIVE_INFINITY; + var belowArgCount = Number.NEGATIVE_INFINITY; + var aboveArgCount = Number.POSITIVE_INFINITY; + var argCount = args.length; + var closestSignature; + for (var _i = 0, signatures_4 = signatures; _i < signatures_4.length; _i++) { + var sig = signatures_4[_i]; + var minCount = getMinArgumentCount(sig); + var maxCount = getParameterCount(sig); + if (minCount < argCount && minCount > belowArgCount) + belowArgCount = minCount; + if (argCount < maxCount && maxCount < aboveArgCount) + aboveArgCount = maxCount; + if (minCount < min) { + min = minCount; + closestSignature = sig; + } + max = Math.max(max, maxCount); + } + var hasRestParameter = ts.some(signatures, hasEffectiveRestParameter); + var paramRange = hasRestParameter ? min : + min < max ? min + "-" + max : + min; + var hasSpreadArgument = getSpreadArgumentIndex(args) > -1; + if (argCount <= max && hasSpreadArgument) { + argCount--; + } + var related; + if (closestSignature && getMinArgumentCount(closestSignature) > argCount && closestSignature.declaration) { + var paramDecl = closestSignature.declaration.parameters[closestSignature.thisParameter ? argCount + 1 : argCount]; + if (paramDecl) { + related = ts.createDiagnosticForNode(paramDecl, ts.isBindingPattern(paramDecl.name) ? ts.Diagnostics.An_argument_matching_this_binding_pattern_was_not_provided : ts.Diagnostics.An_argument_for_0_was_not_provided, !paramDecl.name ? argCount : !ts.isBindingPattern(paramDecl.name) ? ts.idText(getFirstIdentifier(paramDecl.name)) : undefined); + } + } + if (hasRestParameter || hasSpreadArgument) { + var error_1 = hasRestParameter && hasSpreadArgument ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1_or_more : + hasRestParameter ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1 : + ts.Diagnostics.Expected_0_arguments_but_got_1_or_more; + var diagnostic_1 = ts.createDiagnosticForNode(node, error_1, paramRange, argCount); + return related ? addRelatedInfo(diagnostic_1, related) : diagnostic_1; + } + if (min < argCount && argCount < max) { + return ts.createDiagnosticForNode(node, ts.Diagnostics.No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments, argCount, belowArgCount, aboveArgCount); + } + var diagnostic = ts.createDiagnosticForNode(node, ts.Diagnostics.Expected_0_arguments_but_got_1, paramRange, argCount); + return related ? addRelatedInfo(diagnostic, related) : diagnostic; + } + function getTypeArgumentArityError(node, signatures, typeArguments) { + var min = Infinity; + var max = -Infinity; + for (var _i = 0, signatures_5 = signatures; _i < signatures_5.length; _i++) { + var sig = signatures_5[_i]; + min = Math.min(min, getMinTypeArgumentCount(sig.typeParameters)); + max = Math.max(max, ts.length(sig.typeParameters)); + } + var paramCount = min === max ? min : min + "-" + max; + return ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), typeArguments, ts.Diagnostics.Expected_0_type_arguments_but_got_1, paramCount, typeArguments.length); + } + function resolveCall(node, signatures, candidatesOutArray, isForSignatureHelp, fallbackError) { + var isTaggedTemplate = node.kind === 193 /* TaggedTemplateExpression */; + var isDecorator = node.kind === 152 /* Decorator */; + var isJsxOpeningOrSelfClosingElement = ts.isJsxOpeningLikeElement(node); + var reportErrors = !candidatesOutArray; + var typeArguments; + if (!isDecorator) { + typeArguments = node.typeArguments; + // We already perform checking on the type arguments on the class declaration itself. + if (isTaggedTemplate || isJsxOpeningOrSelfClosingElement || node.expression.kind !== 98 /* SuperKeyword */) { + ts.forEach(typeArguments, checkSourceElement); + } + } + var candidates = candidatesOutArray || []; + // reorderCandidates fills up the candidates array directly + reorderCandidates(signatures, candidates); + if (!candidates.length) { + if (reportErrors) { + diagnostics.add(ts.createDiagnosticForNode(node, ts.Diagnostics.Call_target_does_not_contain_any_signatures)); + } + return resolveErrorCall(node); + } + var args = getEffectiveCallArguments(node); + // The excludeArgument array contains true for each context sensitive argument (an argument + // is context sensitive it is susceptible to a one-time permanent contextual typing). + // + // The idea is that we will perform type argument inference & assignability checking once + // without using the susceptible parameters that are functions, and once more for those + // parameters, contextually typing each as we go along. + // + // For a tagged template, then the first argument be 'undefined' if necessary because it + // represents a TemplateStringsArray. + // + // For a decorator, no arguments are susceptible to contextual typing due to the fact + // decorators are applied to a declaration by the emitter, and not to an expression. + var isSingleNonGenericCandidate = candidates.length === 1 && !candidates[0].typeParameters; + var excludeArgument = !isDecorator && !isSingleNonGenericCandidate ? getExcludeArgument(args) : undefined; + // The following variables are captured and modified by calls to chooseOverload. + // If overload resolution or type argument inference fails, we want to report the + // best error possible. The best error is one which says that an argument was not + // assignable to a parameter. This implies that everything else about the overload + // was fine. So if there is any overload that is only incorrect because of an + // argument, we will report an error on that one. + // + // function foo(s: string): void; + // function foo(n: number): void; // Report argument error on this overload + // function foo(): void; + // foo(true); + // + // If none of the overloads even made it that far, there are two possibilities. + // There was a problem with type arguments for some overload, in which case + // report an error on that. Or none of the overloads even had correct arity, + // in which case give an arity error. + // + // function foo(x: T): void; // Report type argument error + // function foo(): void; + // foo(0); + // + var candidateForArgumentError; + var candidateForArgumentArityError; + var candidateForTypeArgumentError; + var result; + // If we are in signature help, a trailing comma indicates that we intend to provide another argument, + // so we will only accept overloads with arity at least 1 higher than the current number of provided arguments. + var signatureHelpTrailingComma = isForSignatureHelp && node.kind === 191 /* CallExpression */ && node.arguments.hasTrailingComma; + // Section 4.12.1: + // if the candidate list contains one or more signatures for which the type of each argument + // expression is a subtype of each corresponding parameter type, the return type of the first + // of those signatures becomes the return type of the function call. + // Otherwise, the return type of the first signature in the candidate list becomes the return + // type of the function call. + // + // Whether the call is an error is determined by assignability of the arguments. The subtype pass + // is just important for choosing the best signature. So in the case where there is only one + // signature, the subtype pass is useless. So skipping it is an optimization. + if (candidates.length > 1) { + result = chooseOverload(candidates, subtypeRelation, signatureHelpTrailingComma); + } + if (!result) { + result = chooseOverload(candidates, assignableRelation, signatureHelpTrailingComma); + } + if (result) { + return result; + } + // No signatures were applicable. Now report errors based on the last applicable signature with + // no arguments excluded from assignability checks. + // If candidate is undefined, it means that no candidates had a suitable arity. In that case, + // skip the checkApplicableSignature check. + if (reportErrors) { + if (candidateForArgumentError) { + // excludeArgument is undefined, in this case also equivalent to [undefined, undefined, ...] + // The importance of excludeArgument is to prevent us from typing function expression parameters + // in arguments too early. If possible, we'd like to only type them once we know the correct + // overload. However, this matters for the case where the call is correct. When the call is + // an error, we don't need to exclude any arguments, although it would cause no harm to do so. + checkApplicableSignature(node, args, candidateForArgumentError, assignableRelation, /*excludeArgument*/ undefined, /*reportErrors*/ true); + } + else if (candidateForArgumentArityError) { + diagnostics.add(getArgumentArityError(node, [candidateForArgumentArityError], args)); + } + else if (candidateForTypeArgumentError) { + checkTypeArguments(candidateForTypeArgumentError, node.typeArguments, /*reportErrors*/ true, fallbackError); + } + else { + var signaturesWithCorrectTypeArgumentArity = ts.filter(signatures, function (s) { return hasCorrectTypeArgumentArity(s, typeArguments); }); + if (signaturesWithCorrectTypeArgumentArity.length === 0) { + diagnostics.add(getTypeArgumentArityError(node, signatures, typeArguments)); + } + else if (!isDecorator) { + diagnostics.add(getArgumentArityError(node, signaturesWithCorrectTypeArgumentArity, args)); + } + else if (fallbackError) { + diagnostics.add(ts.createDiagnosticForNode(node, fallbackError)); + } + } + } + return produceDiagnostics || !args ? resolveErrorCall(node) : getCandidateForOverloadFailure(node, candidates, args, !!candidatesOutArray); + function chooseOverload(candidates, relation, signatureHelpTrailingComma) { + if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; } + candidateForArgumentError = undefined; + candidateForArgumentArityError = undefined; + candidateForTypeArgumentError = undefined; + if (isSingleNonGenericCandidate) { + var candidate = candidates[0]; + if (typeArguments || !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) { + return undefined; + } + if (!checkApplicableSignature(node, args, candidate, relation, excludeArgument, /*reportErrors*/ false)) { + candidateForArgumentError = candidate; + return undefined; + } + return candidate; + } + for (var candidateIndex = 0; candidateIndex < candidates.length; candidateIndex++) { + var candidate = candidates[candidateIndex]; + if (!hasCorrectTypeArgumentArity(candidate, typeArguments) || !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) { + continue; + } + var checkCandidate = void 0; + var inferenceContext = void 0; + if (candidate.typeParameters) { + var typeArgumentTypes = void 0; + if (typeArguments) { + typeArgumentTypes = checkTypeArguments(candidate, typeArguments, /*reportErrors*/ false); + if (!typeArgumentTypes) { + candidateForTypeArgumentError = candidate; + continue; + } + } + else { + inferenceContext = createInferenceContext(candidate.typeParameters, candidate, /*flags*/ ts.isInJSFile(node) ? 2 /* AnyDefault */ : 0 /* None */); + typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); + } + checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration)); + // If the original signature has a generic rest type, instantiation may produce a + // signature with different arity and we need to perform another arity check. + if (getNonArrayRestType(candidate) && !hasCorrectArity(node, args, checkCandidate, signatureHelpTrailingComma)) { + candidateForArgumentArityError = checkCandidate; + continue; + } + } + else { + checkCandidate = candidate; + } + if (!checkApplicableSignature(node, args, checkCandidate, relation, excludeArgument, /*reportErrors*/ false)) { + // Give preference to error candidates that have no rest parameters (as they are more specific) + if (!candidateForArgumentError || getEffectiveRestType(candidateForArgumentError) || !getEffectiveRestType(checkCandidate)) { + candidateForArgumentError = checkCandidate; + } + continue; + } + if (excludeArgument) { + // If one or more context sensitive arguments were excluded, we start including + // them now (and keeping do so for any subsequent candidates) and perform a second + // round of type inference and applicability checking for this particular candidate. + excludeArgument = undefined; + if (inferenceContext) { + var typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); + checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration)); + } + if (!checkApplicableSignature(node, args, checkCandidate, relation, excludeArgument, /*reportErrors*/ false)) { + // Give preference to error candidates that have no rest parameters (as they are more specific) + if (!candidateForArgumentError || getEffectiveRestType(candidateForArgumentError) || !getEffectiveRestType(checkCandidate)) { + candidateForArgumentError = checkCandidate; + } + continue; + } + } + candidates[candidateIndex] = checkCandidate; + return checkCandidate; + } + return undefined; + } + } + function getExcludeArgument(args) { + var excludeArgument; + // We do not need to call `getEffectiveArgumentCount` here as it only + // applies when calculating the number of arguments for a decorator. + for (var i = 0; i < args.length; i++) { + if (isContextSensitive(args[i])) { + if (!excludeArgument) { + excludeArgument = new Array(args.length); + } + excludeArgument[i] = true; + } + } + return excludeArgument; + } + // No signature was applicable. We have already reported the errors for the invalid signature. + // If this is a type resolution session, e.g. Language Service, try to get better information than anySignature. + function getCandidateForOverloadFailure(node, candidates, args, hasCandidatesOutArray) { + ts.Debug.assert(candidates.length > 0); // Else should not have called this. + // Normally we will combine overloads. Skip this if they have type parameters since that's hard to combine. + // Don't do this if there is a `candidatesOutArray`, + // because then we want the chosen best candidate to be one of the overloads, not a combination. + return hasCandidatesOutArray || candidates.length === 1 || candidates.some(function (c) { return !!c.typeParameters; }) + ? pickLongestCandidateSignature(node, candidates, args) + : createUnionOfSignaturesForOverloadFailure(candidates); + } + function createUnionOfSignaturesForOverloadFailure(candidates) { + var thisParameters = ts.mapDefined(candidates, function (c) { return c.thisParameter; }); + var thisParameter; + if (thisParameters.length) { + thisParameter = createCombinedSymbolFromTypes(thisParameters, thisParameters.map(getTypeOfParameter)); + } + var _a = ts.minAndMax(candidates, getNumNonRestParameters), minArgumentCount = _a.min, maxNonRestParam = _a.max; + var parameters = []; + var _loop_7 = function (i) { + var symbols = ts.mapDefined(candidates, function (_a) { + var parameters = _a.parameters, hasRestParameter = _a.hasRestParameter; + return hasRestParameter ? + i < parameters.length - 1 ? parameters[i] : ts.last(parameters) : + i < parameters.length ? parameters[i] : undefined; + }); + ts.Debug.assert(symbols.length !== 0); + parameters.push(createCombinedSymbolFromTypes(symbols, ts.mapDefined(candidates, function (candidate) { return tryGetTypeAtPosition(candidate, i); }))); + }; + for (var i = 0; i < maxNonRestParam; i++) { + _loop_7(i); + } + var restParameterSymbols = ts.mapDefined(candidates, function (c) { return c.hasRestParameter ? ts.last(c.parameters) : undefined; }); + var hasRestParameter = restParameterSymbols.length !== 0; + if (hasRestParameter) { + var type = createArrayType(getUnionType(ts.mapDefined(candidates, tryGetRestTypeOfSignature), 2 /* Subtype */)); + parameters.push(createCombinedSymbolForOverloadFailure(restParameterSymbols, type)); + } + return createSignature(candidates[0].declaration, + /*typeParameters*/ undefined, // Before calling this we tested for `!candidates.some(c => !!c.typeParameters)`. + thisParameter, parameters, + /*resolvedReturnType*/ getIntersectionType(candidates.map(getReturnTypeOfSignature)), + /*typePredicate*/ undefined, minArgumentCount, hasRestParameter, + /*hasLiteralTypes*/ candidates.some(function (c) { return c.hasLiteralTypes; })); + } + function getNumNonRestParameters(signature) { + var numParams = signature.parameters.length; + return signature.hasRestParameter ? numParams - 1 : numParams; + } + function createCombinedSymbolFromTypes(sources, types) { + return createCombinedSymbolForOverloadFailure(sources, getUnionType(types, 2 /* Subtype */)); + } + function createCombinedSymbolForOverloadFailure(sources, type) { + // This function is currently only used for erroneous overloads, so it's good enough to just use the first source. + return createSymbolWithType(ts.first(sources), type); + } + function pickLongestCandidateSignature(node, candidates, args) { + // Pick the longest signature. This way we can get a contextual type for cases like: + // declare function f(a: { xa: number; xb: number; }, b: number); + // f({ | + // Also, use explicitly-supplied type arguments if they are provided, so we can get a contextual signature in cases like: + // declare function f(k: keyof T); + // f(" + var bestIndex = getLongestCandidateIndex(candidates, apparentArgumentCount === undefined ? args.length : apparentArgumentCount); + var candidate = candidates[bestIndex]; + var typeParameters = candidate.typeParameters; + if (!typeParameters) { + return candidate; + } + var typeArgumentNodes = callLikeExpressionMayHaveTypeArguments(node) ? node.typeArguments : undefined; + var instantiated = typeArgumentNodes + ? createSignatureInstantiation(candidate, getTypeArgumentsFromNodes(typeArgumentNodes, typeParameters, ts.isInJSFile(node))) + : inferSignatureInstantiationForOverloadFailure(node, typeParameters, candidate, args); + candidates[bestIndex] = instantiated; + return instantiated; + } + function getTypeArgumentsFromNodes(typeArgumentNodes, typeParameters, isJs) { + var typeArguments = typeArgumentNodes.map(getTypeOfNode); + while (typeArguments.length > typeParameters.length) { + typeArguments.pop(); + } + while (typeArguments.length < typeParameters.length) { + typeArguments.push(getConstraintOfTypeParameter(typeParameters[typeArguments.length]) || getDefaultTypeArgumentType(isJs)); + } + return typeArguments; + } + function inferSignatureInstantiationForOverloadFailure(node, typeParameters, candidate, args) { + var inferenceContext = createInferenceContext(typeParameters, candidate, /*flags*/ ts.isInJSFile(node) ? 2 /* AnyDefault */ : 0 /* None */); + var typeArgumentTypes = inferTypeArguments(node, candidate, args, getExcludeArgument(args), inferenceContext); + return createSignatureInstantiation(candidate, typeArgumentTypes); + } + function getLongestCandidateIndex(candidates, argsCount) { + var maxParamsIndex = -1; + var maxParams = -1; + for (var i = 0; i < candidates.length; i++) { + var candidate = candidates[i]; + var paramCount = getParameterCount(candidate); + if (hasEffectiveRestParameter(candidate) || paramCount >= argsCount) { + return i; + } + if (paramCount > maxParams) { + maxParams = paramCount; + maxParamsIndex = i; + } + } + return maxParamsIndex; + } + function resolveCallExpression(node, candidatesOutArray, isForSignatureHelp) { + if (node.expression.kind === 98 /* SuperKeyword */) { + var superType = checkSuperExpression(node.expression); + if (isTypeAny(superType)) { + for (var _i = 0, _a = node.arguments; _i < _a.length; _i++) { + var arg = _a[_i]; + checkExpression(arg); // Still visit arguments so they get marked for visibility, etc + } + return anySignature; + } + if (superType !== errorType) { + // In super call, the candidate signatures are the matching arity signatures of the base constructor function instantiated + // with the type arguments specified in the extends clause. + var baseTypeNode = ts.getEffectiveBaseTypeNode(ts.getContainingClass(node)); + if (baseTypeNode) { + var baseConstructors = getInstantiatedConstructorsForTypeArguments(superType, baseTypeNode.typeArguments, baseTypeNode); + return resolveCall(node, baseConstructors, candidatesOutArray, isForSignatureHelp); + } + } + return resolveUntypedCall(node); + } + var funcType = checkNonNullExpression(node.expression, ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_null, ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_undefined, ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_null_or_undefined); + if (funcType === silentNeverType) { + return silentNeverSignature; + } + var apparentType = getApparentType(funcType); + if (apparentType === errorType) { + // Another error has already been reported + return resolveErrorCall(node); + } + // Technically, this signatures list may be incomplete. We are taking the apparent type, + // but we are not including call signatures that may have been added to the Object or + // Function interface, since they have none by default. This is a bit of a leap of faith + // that the user will not add any. + var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */); + var numConstructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */).length; + // TS 1.0 Spec: 4.12 + // In an untyped function call no TypeArgs are permitted, Args can be any argument list, no contextual + // types are provided for the argument expressions, and the result is always of type Any. + if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, numConstructSignatures)) { + // The unknownType indicates that an error already occurred (and was reported). No + // need to report another error in this case. + if (funcType !== errorType && node.typeArguments) { + error(node, ts.Diagnostics.Untyped_function_calls_may_not_accept_type_arguments); + } + return resolveUntypedCall(node); + } + // If FuncExpr's apparent type(section 3.8.1) is a function type, the call is a typed function call. + // TypeScript employs overload resolution in typed function calls in order to support functions + // with multiple call signatures. + if (!callSignatures.length) { + if (numConstructSignatures) { + error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType)); + } + else { + var relatedInformation = void 0; + if (node.arguments.length === 1) { + var text = ts.getSourceFileOfNode(node).text; + if (ts.isLineBreak(text.charCodeAt(ts.skipTrivia(text, node.expression.end, /* stopAfterLineBreak */ true) - 1))) { + relatedInformation = ts.createDiagnosticForNode(node.expression, ts.Diagnostics.It_is_highly_likely_that_you_are_missing_a_semicolon); + } + } + invocationError(node, apparentType, 0 /* Call */, relatedInformation); + } + return resolveErrorCall(node); + } + // If the function is explicitly marked with `@class`, then it must be constructed. + if (callSignatures.some(function (sig) { return ts.isInJSFile(sig.declaration) && !!ts.getJSDocClassTag(sig.declaration); })) { + error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType)); + return resolveErrorCall(node); + } + return resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp); + } + /** + * TS 1.0 spec: 4.12 + * If FuncExpr is of type Any, or of an object type that has no call or construct signatures + * but is a subtype of the Function interface, the call is an untyped function call. + */ + function isUntypedFunctionCall(funcType, apparentFuncType, numCallSignatures, numConstructSignatures) { + // We exclude union types because we may have a union of function types that happen to have no common signatures. + return isTypeAny(funcType) || isTypeAny(apparentFuncType) && funcType.flags & 262144 /* TypeParameter */ || + !numCallSignatures && !numConstructSignatures && !(apparentFuncType.flags & (1048576 /* Union */ | 131072 /* Never */)) && isTypeAssignableTo(funcType, globalFunctionType); + } + function resolveNewExpression(node, candidatesOutArray, isForSignatureHelp) { + if (node.arguments && languageVersion < 1 /* ES5 */) { + var spreadIndex = getSpreadArgumentIndex(node.arguments); + if (spreadIndex >= 0) { + error(node.arguments[spreadIndex], ts.Diagnostics.Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher); + } + } + var expressionType = checkNonNullExpression(node.expression); + if (expressionType === silentNeverType) { + return silentNeverSignature; + } + // If expressionType's apparent type(section 3.8.1) is an object type with one or + // more construct signatures, the expression is processed in the same manner as a + // function call, but using the construct signatures as the initial set of candidate + // signatures for overload resolution. The result type of the function call becomes + // the result type of the operation. + expressionType = getApparentType(expressionType); + if (expressionType === errorType) { + // Another error has already been reported + return resolveErrorCall(node); + } + // TS 1.0 spec: 4.11 + // If expressionType is of type Any, Args can be any argument + // list and the result of the operation is of type Any. + if (isTypeAny(expressionType)) { + if (node.typeArguments) { + error(node, ts.Diagnostics.Untyped_function_calls_may_not_accept_type_arguments); + } + return resolveUntypedCall(node); + } + // Technically, this signatures list may be incomplete. We are taking the apparent type, + // but we are not including construct signatures that may have been added to the Object or + // Function interface, since they have none by default. This is a bit of a leap of faith + // that the user will not add any. + var constructSignatures = getSignaturesOfType(expressionType, 1 /* Construct */); + if (constructSignatures.length) { + if (!isConstructorAccessible(node, constructSignatures[0])) { + return resolveErrorCall(node); + } + // If the expression is a class of abstract type, then it cannot be instantiated. + // Note, only class declarations can be declared abstract. + // In the case of a merged class-module or class-interface declaration, + // only the class declaration node will have the Abstract flag set. + var valueDecl = expressionType.symbol && ts.getClassLikeDeclarationOfSymbol(expressionType.symbol); + if (valueDecl && ts.hasModifier(valueDecl, 128 /* Abstract */)) { + error(node, ts.Diagnostics.Cannot_create_an_instance_of_an_abstract_class); + return resolveErrorCall(node); + } + return resolveCall(node, constructSignatures, candidatesOutArray, isForSignatureHelp); + } + // If expressionType's apparent type is an object type with no construct signatures but + // one or more call signatures, the expression is processed as a function call. A compile-time + // error occurs if the result of the function call is not Void. The type of the result of the + // operation is Any. It is an error to have a Void this type. + var callSignatures = getSignaturesOfType(expressionType, 0 /* Call */); + if (callSignatures.length) { + var signature = resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp); + if (!noImplicitAny) { + if (signature.declaration && !isJSConstructor(signature.declaration) && getReturnTypeOfSignature(signature) !== voidType) { + error(node, ts.Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword); + } + if (getThisTypeOfSignature(signature) === voidType) { + error(node, ts.Diagnostics.A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void); + } + } + return signature; + } + invocationError(node, expressionType, 1 /* Construct */); + return resolveErrorCall(node); + } + function typeHasProtectedAccessibleBase(target, type) { + var baseTypes = getBaseTypes(type); + if (!ts.length(baseTypes)) { + return false; + } + var firstBase = baseTypes[0]; + if (firstBase.flags & 2097152 /* Intersection */) { + var types = firstBase.types; + var mixinCount = ts.countWhere(types, isMixinConstructorType); + var i = 0; + for (var _i = 0, _a = firstBase.types; _i < _a.length; _i++) { + var intersectionMember = _a[_i]; + i++; + // We want to ignore mixin ctors + if (mixinCount === 0 || mixinCount === types.length && i === 0 || !isMixinConstructorType(intersectionMember)) { + if (ts.getObjectFlags(intersectionMember) & (1 /* Class */ | 2 /* Interface */)) { + if (intersectionMember.symbol === target) { + return true; + } + if (typeHasProtectedAccessibleBase(target, intersectionMember)) { + return true; + } + } + } + } + return false; + } + if (firstBase.symbol === target) { + return true; + } + return typeHasProtectedAccessibleBase(target, firstBase); + } + function isConstructorAccessible(node, signature) { + if (!signature || !signature.declaration) { + return true; + } + var declaration = signature.declaration; + var modifiers = ts.getSelectedModifierFlags(declaration, 24 /* NonPublicAccessibilityModifier */); + // Public constructor is accessible. + if (!modifiers) { + return true; + } + var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(declaration.parent.symbol); + var declaringClass = getDeclaredTypeOfSymbol(declaration.parent.symbol); + // A private or protected constructor can only be instantiated within its own class (or a subclass, for protected) + if (!isNodeWithinClass(node, declaringClassDeclaration)) { + var containingClass = ts.getContainingClass(node); + if (containingClass && modifiers & 16 /* Protected */) { + var containingType = getTypeOfNode(containingClass); + if (typeHasProtectedAccessibleBase(declaration.parent.symbol, containingType)) { + return true; + } + } + if (modifiers & 8 /* Private */) { + error(node, ts.Diagnostics.Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration, typeToString(declaringClass)); + } + if (modifiers & 16 /* Protected */) { + error(node, ts.Diagnostics.Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration, typeToString(declaringClass)); + } + return false; + } + return true; + } + function invocationError(node, apparentType, kind, relatedInformation) { + var diagnostic = error(node, (kind === 0 /* Call */ ? + ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures : + ts.Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature), typeToString(apparentType)); + invocationErrorRecovery(apparentType, kind, relatedInformation ? addRelatedInfo(diagnostic, relatedInformation) : diagnostic); + } + function invocationErrorRecovery(apparentType, kind, diagnostic) { + if (!apparentType.symbol) { + return; + } + var importNode = getSymbolLinks(apparentType.symbol).originatingImport; + // Create a diagnostic on the originating import if possible onto which we can attach a quickfix + // An import call expression cannot be rewritten into another form to correct the error - the only solution is to use `.default` at the use-site + if (importNode && !ts.isImportCall(importNode)) { + var sigs = getSignaturesOfType(getTypeOfSymbol(getSymbolLinks(apparentType.symbol).target), kind); + if (!sigs || !sigs.length) + return; + addRelatedInfo(diagnostic, ts.createDiagnosticForNode(importNode, ts.Diagnostics.Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_Consider_using_a_default_import_or_import_require_here_instead)); + } + } + function resolveTaggedTemplateExpression(node, candidatesOutArray, isForSignatureHelp) { + var tagType = checkExpression(node.tag); + var apparentType = getApparentType(tagType); + if (apparentType === errorType) { + // Another error has already been reported + return resolveErrorCall(node); + } + var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */); + var numConstructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */).length; + if (isUntypedFunctionCall(tagType, apparentType, callSignatures.length, numConstructSignatures)) { + return resolveUntypedCall(node); + } + if (!callSignatures.length) { + invocationError(node, apparentType, 0 /* Call */); + return resolveErrorCall(node); + } + return resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp); + } + /** + * Gets the localized diagnostic head message to use for errors when resolving a decorator as a call expression. + */ + function getDiagnosticHeadMessageForDecoratorResolution(node) { + switch (node.parent.kind) { + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + return ts.Diagnostics.Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression; + case 151 /* Parameter */: + return ts.Diagnostics.Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression; + case 154 /* PropertyDeclaration */: + return ts.Diagnostics.Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression; + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + return ts.Diagnostics.Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression; + default: + return ts.Debug.fail(); + } + } + /** + * Resolves a decorator as if it were a call expression. + */ + function resolveDecorator(node, candidatesOutArray, isForSignatureHelp) { + var funcType = checkExpression(node.expression); + var apparentType = getApparentType(funcType); + if (apparentType === errorType) { + return resolveErrorCall(node); + } + var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */); + var numConstructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */).length; + if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, numConstructSignatures)) { + return resolveUntypedCall(node); + } + if (isPotentiallyUncalledDecorator(node, callSignatures)) { + var nodeStr = ts.getTextOfNode(node.expression, /*includeTrivia*/ false); + error(node, ts.Diagnostics._0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write_0, nodeStr); + return resolveErrorCall(node); + } + var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); + if (!callSignatures.length) { + var errorInfo = ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures, typeToString(apparentType)); + errorInfo = ts.chainDiagnosticMessages(errorInfo, headMessage); + var diag = ts.createDiagnosticForNodeFromMessageChain(node, errorInfo); + diagnostics.add(diag); + invocationErrorRecovery(apparentType, 0 /* Call */, diag); + return resolveErrorCall(node); + } + return resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp, headMessage); + } + function createSignatureForJSXIntrinsic(node, result) { + var namespace = getJsxNamespaceAt(node); + var exports = namespace && getExportsOfSymbol(namespace); + // We fake up a SFC signature for each intrinsic, however a more specific per-element signature drawn from the JSX declaration + // file would probably be preferable. + var typeSymbol = exports && getSymbol(exports, JsxNames.Element, 67897832 /* Type */); + var returnNode = typeSymbol && nodeBuilder.symbolToEntityName(typeSymbol, 67897832 /* Type */, node); + var declaration = ts.createFunctionTypeNode(/*typeParameters*/ undefined, [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotdotdot*/ undefined, "props", /*questionMark*/ undefined, nodeBuilder.typeToTypeNode(result, node))], returnNode ? ts.createTypeReferenceNode(returnNode, /*typeArguments*/ undefined) : ts.createKeywordTypeNode(120 /* AnyKeyword */)); + var parameterSymbol = createSymbol(1 /* FunctionScopedVariable */, "props"); + parameterSymbol.type = result; + return createSignature(declaration, + /*typeParameters*/ undefined, + /*thisParameter*/ undefined, [parameterSymbol], typeSymbol ? getDeclaredTypeOfSymbol(typeSymbol) : errorType, + /*returnTypePredicate*/ undefined, 1, + /*hasRestparameter*/ false, + /*hasLiteralTypes*/ false); + } + function resolveJsxOpeningLikeElement(node, candidatesOutArray, isForSignatureHelp) { + if (isJsxIntrinsicIdentifier(node.tagName)) { + var result = getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node); + var fakeSignature = createSignatureForJSXIntrinsic(node, result); + checkTypeAssignableToAndOptionallyElaborate(checkExpressionWithContextualType(node.attributes, getEffectiveFirstArgumentForJsxSignature(fakeSignature, node), /*mapper*/ undefined), result, node.tagName, node.attributes); + return fakeSignature; + } + var exprTypes = checkExpression(node.tagName); + var apparentType = getApparentType(exprTypes); + if (apparentType === errorType) { + return resolveErrorCall(node); + } + var signatures = getUninstantiatedJsxSignaturesOfType(exprTypes, node); + if (isUntypedFunctionCall(exprTypes, apparentType, signatures.length, /*constructSignatures*/ 0)) { + return resolveUntypedCall(node); + } + if (signatures.length === 0) { + // We found no signatures at all, which is an error + error(node.tagName, ts.Diagnostics.JSX_element_type_0_does_not_have_any_construct_or_call_signatures, ts.getTextOfNode(node.tagName)); + return resolveErrorCall(node); + } + return resolveCall(node, signatures, candidatesOutArray, isForSignatureHelp); + } + /** + * Sometimes, we have a decorator that could accept zero arguments, + * but is receiving too many arguments as part of the decorator invocation. + * In those cases, a user may have meant to *call* the expression before using it as a decorator. + */ + function isPotentiallyUncalledDecorator(decorator, signatures) { + return signatures.length && ts.every(signatures, function (signature) { + return signature.minArgumentCount === 0 && + !signature.hasRestParameter && + signature.parameters.length < getDecoratorArgumentCount(decorator, signature); + }); + } + function resolveSignature(node, candidatesOutArray, isForSignatureHelp) { + switch (node.kind) { + case 191 /* CallExpression */: + return resolveCallExpression(node, candidatesOutArray, isForSignatureHelp); + case 192 /* NewExpression */: + return resolveNewExpression(node, candidatesOutArray, isForSignatureHelp); + case 193 /* TaggedTemplateExpression */: + return resolveTaggedTemplateExpression(node, candidatesOutArray, isForSignatureHelp); + case 152 /* Decorator */: + return resolveDecorator(node, candidatesOutArray, isForSignatureHelp); + case 262 /* JsxOpeningElement */: + case 261 /* JsxSelfClosingElement */: + return resolveJsxOpeningLikeElement(node, candidatesOutArray, isForSignatureHelp); + } + throw ts.Debug.assertNever(node, "Branch in 'resolveSignature' should be unreachable."); + } + /** + * Resolve a signature of a given call-like expression. + * @param node a call-like expression to try resolve a signature for + * @param candidatesOutArray an array of signature to be filled in by the function. It is passed by signature help in the language service; + * the function will fill it up with appropriate candidate signatures + * @return a signature of the call-like expression or undefined if one can't be found + */ + function getResolvedSignature(node, candidatesOutArray, isForSignatureHelp) { + if (isForSignatureHelp === void 0) { isForSignatureHelp = false; } + var links = getNodeLinks(node); + // If getResolvedSignature has already been called, we will have cached the resolvedSignature. + // However, it is possible that either candidatesOutArray was not passed in the first time, + // or that a different candidatesOutArray was passed in. Therefore, we need to redo the work + // to correctly fill the candidatesOutArray. + var cached = links.resolvedSignature; + if (cached && cached !== resolvingSignature && !candidatesOutArray) { + return cached; + } + links.resolvedSignature = resolvingSignature; + var result = resolveSignature(node, candidatesOutArray, isForSignatureHelp); + // If signature resolution originated in control flow type analysis (for example to compute the + // assigned type in a flow assignment) we don't cache the result as it may be based on temporary + // types from the control flow analysis. + links.resolvedSignature = flowLoopStart === flowLoopCount ? result : cached; + return result; + } + /** + * Indicates whether a declaration can be treated as a constructor in a JavaScript + * file. + */ + function isJSConstructor(node) { + if (!node || !ts.isInJSFile(node)) { + return false; + } + var func = ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node) ? node : + ts.isVariableDeclaration(node) && node.initializer && ts.isFunctionExpression(node.initializer) ? node.initializer : + undefined; + if (func) { + // If the node has a @class tag, treat it like a constructor. + if (ts.getJSDocClassTag(node)) + return true; + // If the symbol of the node has members, treat it like a constructor. + var symbol = getSymbolOfNode(func); + return !!symbol && symbol.members !== undefined; + } + return false; + } + function isJSConstructorType(type) { + if (type.flags & 524288 /* Object */) { + var resolved = resolveStructuredTypeMembers(type); + return resolved.callSignatures.length === 1 && isJSConstructor(resolved.callSignatures[0].declaration); + } + return false; + } + function getJSClassType(symbol) { + var inferred; + if (isJSConstructor(symbol.valueDeclaration)) { + inferred = getInferredClassType(symbol); + } + var assigned = getAssignedClassType(symbol); + var valueType = getTypeOfSymbol(symbol); + if (valueType.symbol && !isInferredClassType(valueType) && isJSConstructor(valueType.symbol.valueDeclaration)) { + inferred = getInferredClassType(valueType.symbol); + } + return assigned && inferred ? + getIntersectionType([inferred, assigned]) : + assigned || inferred; + } + function getAssignedClassType(symbol) { + var decl = symbol.valueDeclaration; + var assignmentSymbol = decl && decl.parent && + (ts.isFunctionDeclaration(decl) && getSymbolOfNode(decl) || + ts.isBinaryExpression(decl.parent) && getSymbolOfNode(decl.parent.left) || + ts.isVariableDeclaration(decl.parent) && getSymbolOfNode(decl.parent)); + var prototype = assignmentSymbol && assignmentSymbol.exports && assignmentSymbol.exports.get("prototype"); + var init = prototype && prototype.valueDeclaration && getAssignedJSPrototype(prototype.valueDeclaration); + return init ? checkExpression(init) : undefined; + } + function getAssignedJSPrototype(node) { + if (!node.parent) { + return false; + } + var parent = node.parent; + while (parent && parent.kind === 189 /* PropertyAccessExpression */) { + parent = parent.parent; + } + if (parent && ts.isBinaryExpression(parent) && ts.isPrototypeAccess(parent.left) && parent.operatorToken.kind === 59 /* EqualsToken */) { + var right = ts.getInitializerOfBinaryExpression(parent); + return ts.isObjectLiteralExpression(right) && right; + } + } + function getInferredClassType(symbol) { + var links = getSymbolLinks(symbol); + if (!links.inferredClassType) { + links.inferredClassType = createAnonymousType(symbol, getMembersOfSymbol(symbol) || emptySymbols, ts.emptyArray, ts.emptyArray, /*stringIndexType*/ undefined, /*numberIndexType*/ undefined); + } + return links.inferredClassType; + } + function isInferredClassType(type) { + return type.symbol + && ts.getObjectFlags(type) & 16 /* Anonymous */ + && getSymbolLinks(type.symbol).inferredClassType === type; + } + /** + * Syntactically and semantically checks a call or new expression. + * @param node The call/new expression to be checked. + * @returns On success, the expression's signature's return type. On failure, anyType. + */ + function checkCallExpression(node) { + if (!checkGrammarTypeArguments(node, node.typeArguments)) + checkGrammarArguments(node.arguments); + var signature = getResolvedSignature(node); + if (node.expression.kind === 98 /* SuperKeyword */) { + return voidType; + } + if (node.kind === 192 /* NewExpression */) { + var declaration = signature.declaration; + if (declaration && + declaration.kind !== 157 /* Constructor */ && + declaration.kind !== 161 /* ConstructSignature */ && + declaration.kind !== 166 /* ConstructorType */ && + !ts.isJSDocConstructSignature(declaration)) { + // When resolved signature is a call signature (and not a construct signature) the result type is any, unless + // the declaring function had members created through 'x.prototype.y = expr' or 'this.y = expr' psuedodeclarations + // in a JS file + // Note:JS inferred classes might come from a variable declaration instead of a function declaration. + // In this case, using getResolvedSymbol directly is required to avoid losing the members from the declaration. + var funcSymbol = checkExpression(node.expression).symbol; + if (!funcSymbol && node.expression.kind === 72 /* Identifier */) { + funcSymbol = getResolvedSymbol(node.expression); + } + var type = funcSymbol && getJSClassType(funcSymbol); + if (type) { + return signature.target ? instantiateType(type, signature.mapper) : type; + } + if (noImplicitAny) { + error(node, ts.Diagnostics.new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type); + } + return anyType; + } + } + // In JavaScript files, calls to any identifier 'require' are treated as external module imports + if (ts.isInJSFile(node) && isCommonJsRequire(node)) { + return resolveExternalModuleTypeByLiteral(node.arguments[0]); + } + var returnType = getReturnTypeOfSignature(signature); + // Treat any call to the global 'Symbol' function that is part of a const variable or readonly property + // as a fresh unique symbol literal type. + if (returnType.flags & 12288 /* ESSymbolLike */ && isSymbolOrSymbolForCall(node)) { + return getESSymbolLikeTypeForNode(ts.walkUpParenthesizedExpressions(node.parent)); + } + var jsAssignmentType; + if (ts.isInJSFile(node)) { + var decl = ts.getDeclarationOfExpando(node); + if (decl) { + var jsSymbol = getSymbolOfNode(decl); + if (jsSymbol && ts.hasEntries(jsSymbol.exports)) { + jsAssignmentType = createAnonymousType(jsSymbol, jsSymbol.exports, ts.emptyArray, ts.emptyArray, undefined, undefined); + jsAssignmentType.objectFlags |= 16384 /* JSLiteral */; + } + } + } + return jsAssignmentType ? getIntersectionType([returnType, jsAssignmentType]) : returnType; + } + function isSymbolOrSymbolForCall(node) { + if (!ts.isCallExpression(node)) + return false; + var left = node.expression; + if (ts.isPropertyAccessExpression(left) && left.name.escapedText === "for") { + left = left.expression; + } + if (!ts.isIdentifier(left) || left.escapedText !== "Symbol") { + return false; + } + // make sure `Symbol` is the global symbol + var globalESSymbol = getGlobalESSymbolConstructorSymbol(/*reportErrors*/ false); + if (!globalESSymbol) { + return false; + } + return globalESSymbol === resolveName(left, "Symbol", 67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); + } + function checkImportCallExpression(node) { + // Check grammar of dynamic import + if (!checkGrammarArguments(node.arguments)) + checkGrammarImportCallExpression(node); + if (node.arguments.length === 0) { + return createPromiseReturnType(node, anyType); + } + var specifier = node.arguments[0]; + var specifierType = checkExpressionCached(specifier); + // Even though multiple arguments is grammatically incorrect, type-check extra arguments for completion + for (var i = 1; i < node.arguments.length; ++i) { + checkExpressionCached(node.arguments[i]); + } + if (specifierType.flags & 32768 /* Undefined */ || specifierType.flags & 65536 /* Null */ || !isTypeAssignableTo(specifierType, stringType)) { + error(specifier, ts.Diagnostics.Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0, typeToString(specifierType)); + } + // resolveExternalModuleName will return undefined if the moduleReferenceExpression is not a string literal + var moduleSymbol = resolveExternalModuleName(node, specifier); + if (moduleSymbol) { + var esModuleSymbol = resolveESModuleSymbol(moduleSymbol, specifier, /*dontRecursivelyResolve*/ true); + if (esModuleSymbol) { + return createPromiseReturnType(node, getTypeWithSyntheticDefaultImportType(getTypeOfSymbol(esModuleSymbol), esModuleSymbol, moduleSymbol)); + } + } + return createPromiseReturnType(node, anyType); + } + function getTypeWithSyntheticDefaultImportType(type, symbol, originalSymbol) { + if (allowSyntheticDefaultImports && type && type !== errorType) { + var synthType = type; + if (!synthType.syntheticType) { + var file = ts.find(originalSymbol.declarations, ts.isSourceFile); + var hasSyntheticDefault = canHaveSyntheticDefault(file, originalSymbol, /*dontResolveAlias*/ false); + if (hasSyntheticDefault) { + var memberTable = ts.createSymbolTable(); + var newSymbol = createSymbol(2097152 /* Alias */, "default" /* Default */); + newSymbol.nameType = getLiteralType("default"); + newSymbol.target = resolveSymbol(symbol); + memberTable.set("default" /* Default */, newSymbol); + var anonymousSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */); + var defaultContainingObject = createAnonymousType(anonymousSymbol, memberTable, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined); + anonymousSymbol.type = defaultContainingObject; + synthType.syntheticType = isValidSpreadType(type) ? getSpreadType(type, defaultContainingObject, anonymousSymbol, /*typeFLags*/ 0, /*objectFlags*/ 0) : defaultContainingObject; + } + else { + synthType.syntheticType = type; + } + } + return synthType.syntheticType; + } + return type; + } + function isCommonJsRequire(node) { + if (!ts.isRequireCall(node, /*checkArgumentIsStringLiteralLike*/ true)) { + return false; + } + // Make sure require is not a local function + if (!ts.isIdentifier(node.expression)) + return ts.Debug.fail(); + var resolvedRequire = resolveName(node.expression, node.expression.escapedText, 67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); // TODO: GH#18217 + if (resolvedRequire === requireSymbol) { + return true; + } + // project includes symbol named 'require' - make sure that it is ambient and local non-alias + if (resolvedRequire.flags & 2097152 /* Alias */) { + return false; + } + var targetDeclarationKind = resolvedRequire.flags & 16 /* Function */ + ? 239 /* FunctionDeclaration */ + : resolvedRequire.flags & 3 /* Variable */ + ? 237 /* VariableDeclaration */ + : 0 /* Unknown */; + if (targetDeclarationKind !== 0 /* Unknown */) { + var decl = ts.getDeclarationOfKind(resolvedRequire, targetDeclarationKind); + // function/variable declaration should be ambient + return !!decl && !!(decl.flags & 4194304 /* Ambient */); + } + return false; + } + function checkTaggedTemplateExpression(node) { + checkGrammarTypeArguments(node, node.typeArguments); + if (languageVersion < 2 /* ES2015 */) { + checkExternalEmitHelpers(node, 65536 /* MakeTemplateObject */); + } + return getReturnTypeOfSignature(getResolvedSignature(node)); + } + function checkAssertion(node) { + return checkAssertionWorker(node, node.type, node.expression); + } + function checkAssertionWorker(errNode, type, expression, checkMode) { + var exprType = getRegularTypeOfObjectLiteral(getBaseTypeOfLiteralType(checkExpression(expression, checkMode))); + checkSourceElement(type); + var targetType = getTypeFromTypeNode(type); + if (produceDiagnostics && targetType !== errorType) { + var widenedType = getWidenedType(exprType); + if (!isTypeComparableTo(targetType, widenedType)) { + checkTypeComparableTo(exprType, targetType, errNode, ts.Diagnostics.Conversion_of_type_0_to_type_1_may_be_a_mistake_because_neither_type_sufficiently_overlaps_with_the_other_If_this_was_intentional_convert_the_expression_to_unknown_first); + } + } + return targetType; + } + function checkNonNullAssertion(node) { + return getNonNullableType(checkExpression(node.expression)); + } + function checkMetaProperty(node) { + checkGrammarMetaProperty(node); + if (node.keywordToken === 95 /* NewKeyword */) { + return checkNewTargetMetaProperty(node); + } + if (node.keywordToken === 92 /* ImportKeyword */) { + return checkImportMetaProperty(node); + } + return ts.Debug.assertNever(node.keywordToken); + } + function checkNewTargetMetaProperty(node) { + var container = ts.getNewTargetContainer(node); + if (!container) { + error(node, ts.Diagnostics.Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constructor, "new.target"); + return errorType; + } + else if (container.kind === 157 /* Constructor */) { + var symbol = getSymbolOfNode(container.parent); + return getTypeOfSymbol(symbol); + } + else { + var symbol = getSymbolOfNode(container); + return getTypeOfSymbol(symbol); + } + } + function checkImportMetaProperty(node) { + if (languageVersion < 6 /* ESNext */ || moduleKind < ts.ModuleKind.ESNext) { + error(node, ts.Diagnostics.The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_options); + } + var file = ts.getSourceFileOfNode(node); + ts.Debug.assert(!!(file.flags & 1048576 /* PossiblyContainsImportMeta */), "Containing file is missing import meta node flag."); + ts.Debug.assert(!!file.externalModuleIndicator, "Containing file should be a module."); + return node.name.escapedText === "meta" ? getGlobalImportMetaType() : errorType; + } + function getTypeOfParameter(symbol) { + var type = getTypeOfSymbol(symbol); + if (strictNullChecks) { + var declaration = symbol.valueDeclaration; + if (declaration && ts.hasInitializer(declaration)) { + return getOptionalType(type); + } + } + return type; + } + function getParameterNameAtPosition(signature, pos) { + var paramCount = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); + if (pos < paramCount) { + return signature.parameters[pos].escapedName; + } + var restParameter = signature.parameters[paramCount] || unknownSymbol; + var restType = getTypeOfSymbol(restParameter); + if (isTupleType(restType)) { + var associatedNames = restType.target.associatedNames; + var index = pos - paramCount; + return associatedNames ? associatedNames[index] : restParameter.escapedName + "_" + index; + } + return restParameter.escapedName; + } + function getTypeAtPosition(signature, pos) { + return tryGetTypeAtPosition(signature, pos) || anyType; + } + function tryGetTypeAtPosition(signature, pos) { + var paramCount = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); + if (pos < paramCount) { + return getTypeOfParameter(signature.parameters[pos]); + } + if (signature.hasRestParameter) { + var restType = getTypeOfSymbol(signature.parameters[paramCount]); + if (isTupleType(restType)) { + if (pos - paramCount < getLengthOfTupleType(restType)) { + return restType.typeArguments[pos - paramCount]; + } + return getRestTypeOfTupleType(restType); + } + return getIndexTypeOfType(restType, 1 /* Number */); + } + return undefined; + } + function getRestTypeAtPosition(source, pos) { + var paramCount = getParameterCount(source); + var restType = getEffectiveRestType(source); + if (restType && pos === paramCount - 1) { + return restType; + } + var start = restType ? Math.min(pos, paramCount - 1) : pos; + var types = []; + var names = []; + for (var i = start; i < paramCount; i++) { + types.push(getTypeAtPosition(source, i)); + names.push(getParameterNameAtPosition(source, i)); + } + var minArgumentCount = getMinArgumentCount(source); + var minLength = minArgumentCount < start ? 0 : minArgumentCount - start; + return createTupleType(types, minLength, !!restType, names); + } + function getParameterCount(signature) { + var length = signature.parameters.length; + if (signature.hasRestParameter) { + var restType = getTypeOfSymbol(signature.parameters[length - 1]); + if (isTupleType(restType)) { + return length + (restType.typeArguments || ts.emptyArray).length - 1; + } + } + return length; + } + function getMinArgumentCount(signature) { + if (signature.hasRestParameter) { + var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); + if (isTupleType(restType)) { + var minLength = restType.target.minLength; + if (minLength > 0) { + return signature.parameters.length - 1 + minLength; + } + } + } + return signature.minArgumentCount; + } + function hasEffectiveRestParameter(signature) { + if (signature.hasRestParameter) { + var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); + return !isTupleType(restType) || restType.target.hasRestElement; + } + return false; + } + function getEffectiveRestType(signature) { + if (signature.hasRestParameter) { + var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); + return isTupleType(restType) ? getRestArrayTypeOfTupleType(restType) : restType; + } + return undefined; + } + function getNonArrayRestType(signature) { + var restType = getEffectiveRestType(signature); + return restType && !isArrayType(restType) && !isTypeAny(restType) ? restType : undefined; + } + function getTypeOfFirstParameterOfSignature(signature) { + return getTypeOfFirstParameterOfSignatureWithFallback(signature, neverType); + } + function getTypeOfFirstParameterOfSignatureWithFallback(signature, fallbackType) { + return signature.parameters.length > 0 ? getTypeAtPosition(signature, 0) : fallbackType; + } + function inferFromAnnotatedParameters(signature, context, mapper) { + var len = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); + for (var i = 0; i < len; i++) { + var declaration = signature.parameters[i].valueDeclaration; + if (declaration.type) { + var typeNode = ts.getEffectiveTypeAnnotationNode(declaration); + if (typeNode) { + inferTypes(mapper.inferences, getTypeFromTypeNode(typeNode), getTypeAtPosition(context, i)); + } + } + } + } + function assignContextualParameterTypes(signature, context) { + signature.typeParameters = context.typeParameters; + if (context.thisParameter) { + var parameter = signature.thisParameter; + if (!parameter || parameter.valueDeclaration && !parameter.valueDeclaration.type) { + if (!parameter) { + signature.thisParameter = createSymbolWithType(context.thisParameter, /*type*/ undefined); + } + assignTypeToParameterAndFixTypeParameters(signature.thisParameter, getTypeOfSymbol(context.thisParameter)); + } + } + var len = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); + for (var i = 0; i < len; i++) { + var parameter = signature.parameters[i]; + if (!ts.getEffectiveTypeAnnotationNode(parameter.valueDeclaration)) { + var contextualParameterType = getTypeAtPosition(context, i); + assignTypeToParameterAndFixTypeParameters(parameter, contextualParameterType); + } + } + if (signature.hasRestParameter) { + // parameter might be a transient symbol generated by use of `arguments` in the function body. + var parameter = ts.last(signature.parameters); + if (isTransientSymbol(parameter) || !ts.getEffectiveTypeAnnotationNode(parameter.valueDeclaration)) { + var contextualParameterType = getRestTypeAtPosition(context, len); + assignTypeToParameterAndFixTypeParameters(parameter, contextualParameterType); + } + } + } + // When contextual typing assigns a type to a parameter that contains a binding pattern, we also need to push + // the destructured type into the contained binding elements. + function assignBindingElementTypes(pattern) { + for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (!ts.isOmittedExpression(element)) { + if (element.name.kind === 72 /* Identifier */) { + getSymbolLinks(getSymbolOfNode(element)).type = getTypeForBindingElement(element); + } + else { + assignBindingElementTypes(element.name); + } + } + } + } + function assignTypeToParameterAndFixTypeParameters(parameter, contextualType) { + var links = getSymbolLinks(parameter); + if (!links.type) { + links.type = contextualType; + var decl = parameter.valueDeclaration; + if (decl.name.kind !== 72 /* Identifier */) { + // if inference didn't come up with anything but {}, fall back to the binding pattern if present. + if (links.type === emptyObjectType) { + links.type = getTypeFromBindingPattern(decl.name); + } + assignBindingElementTypes(decl.name); + } + } + } + function createPromiseType(promisedType) { + // creates a `Promise` type where `T` is the promisedType argument + var globalPromiseType = getGlobalPromiseType(/*reportErrors*/ true); + if (globalPromiseType !== emptyGenericType) { + // if the promised type is itself a promise, get the underlying type; otherwise, fallback to the promised type + promisedType = getAwaitedType(promisedType) || emptyObjectType; + return createTypeReference(globalPromiseType, [promisedType]); + } + return emptyObjectType; + } + function createPromiseLikeType(promisedType) { + // creates a `PromiseLike` type where `T` is the promisedType argument + var globalPromiseLikeType = getGlobalPromiseLikeType(/*reportErrors*/ true); + if (globalPromiseLikeType !== emptyGenericType) { + // if the promised type is itself a promise, get the underlying type; otherwise, fallback to the promised type + promisedType = getAwaitedType(promisedType) || emptyObjectType; + return createTypeReference(globalPromiseLikeType, [promisedType]); + } + return emptyObjectType; + } + function createPromiseReturnType(func, promisedType) { + var promiseType = createPromiseType(promisedType); + if (promiseType === emptyObjectType) { + error(func, ts.isImportCall(func) ? + ts.Diagnostics.A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option : + ts.Diagnostics.An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option); + return errorType; + } + else if (!getGlobalPromiseConstructorSymbol(/*reportErrors*/ true)) { + error(func, ts.isImportCall(func) ? + ts.Diagnostics.A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option : + ts.Diagnostics.An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option); + } + return promiseType; + } + function getReturnTypeFromBody(func, checkMode) { + if (!func.body) { + return errorType; + } + var functionFlags = ts.getFunctionFlags(func); + var type; + if (func.body.kind !== 218 /* Block */) { + type = checkExpressionCached(func.body, checkMode); + if (functionFlags & 2 /* Async */) { + // From within an async function you can return either a non-promise value or a promise. Any + // Promise/A+ compatible implementation will always assimilate any foreign promise, so the + // return type of the body should be unwrapped to its awaited type, which we will wrap in + // the native Promise type later in this function. + type = checkAwaitedType(type, /*errorNode*/ func, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); + } + } + else { + var types = checkAndAggregateReturnExpressionTypes(func, checkMode); + if (functionFlags & 1 /* Generator */) { // Generator or AsyncGenerator function + types = ts.concatenate(checkAndAggregateYieldOperandTypes(func, checkMode), types); + if (!types || types.length === 0) { + var iterableIteratorAny = functionFlags & 2 /* Async */ + ? createAsyncIterableIteratorType(anyType) // AsyncGenerator function + : createIterableIteratorType(anyType); // Generator function + if (noImplicitAny) { + error(func.asteriskToken, ts.Diagnostics.Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_type, typeToString(iterableIteratorAny)); + } + return iterableIteratorAny; + } + } + else { + if (!types) { + // For an async function, the return type will not be never, but rather a Promise for never. + return functionFlags & 2 /* Async */ + ? createPromiseReturnType(func, neverType) // Async function + : neverType; // Normal function + } + if (types.length === 0) { + // For an async function, the return type will not be void, but rather a Promise for void. + return functionFlags & 2 /* Async */ + ? createPromiseReturnType(func, voidType) // Async function + : voidType; // Normal function + } + } + // Return a union of the return expression types. + type = getUnionType(types, 2 /* Subtype */); + } + var contextualSignature = getContextualSignatureForFunctionLikeDeclaration(func); + if (!contextualSignature) { + reportErrorsFromWidening(func, type); + } + if (isUnitType(type)) { + var contextualType = !contextualSignature ? undefined : + contextualSignature === getSignatureFromDeclaration(func) ? type : + getReturnTypeOfSignature(contextualSignature); + if (contextualType) { + switch (functionFlags & 3 /* AsyncGenerator */) { + case 3 /* AsyncGenerator */: + contextualType = getIteratedTypeOfGenerator(contextualType, /*isAsyncGenerator*/ true); + break; + case 1 /* Generator */: + contextualType = getIteratedTypeOfGenerator(contextualType, /*isAsyncGenerator*/ false); + break; + case 2 /* Async */: + contextualType = getPromisedTypeOfPromise(contextualType); + break; + } + } + type = getWidenedLiteralLikeTypeForContextualType(type, contextualType); + } + var widenedType = getWidenedType(type); + switch (functionFlags & 3 /* AsyncGenerator */) { + case 3 /* AsyncGenerator */: + return createAsyncIterableIteratorType(widenedType); + case 1 /* Generator */: + return createIterableIteratorType(widenedType); + case 2 /* Async */: + // From within an async function you can return either a non-promise value or a promise. Any + // Promise/A+ compatible implementation will always assimilate any foreign promise, so the + // return type of the body is awaited type of the body, wrapped in a native Promise type. + return createPromiseType(widenedType); + default: + return widenedType; + } + } + function checkAndAggregateYieldOperandTypes(func, checkMode) { + var aggregatedTypes = []; + var isAsync = (ts.getFunctionFlags(func) & 2 /* Async */) !== 0; + ts.forEachYieldExpression(func.body, function (yieldExpression) { + ts.pushIfUnique(aggregatedTypes, getYieldedTypeOfYieldExpression(yieldExpression, isAsync, checkMode)); + }); + return aggregatedTypes; + } + function getYieldedTypeOfYieldExpression(node, isAsync, checkMode) { + var errorNode = node.expression || node; + var expressionType = node.expression ? checkExpression(node.expression, checkMode) : undefinedWideningType; + // A `yield*` expression effectively yields everything that its operand yields + var yieldedType = node.asteriskToken ? checkIteratedTypeOrElementType(expressionType, errorNode, /*allowStringInput*/ false, isAsync) : expressionType; + return !isAsync ? yieldedType : getAwaitedType(yieldedType, errorNode, node.asteriskToken + ? ts.Diagnostics.Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member + : ts.Diagnostics.Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); + } + /** + * Collect the TypeFacts learned from a typeof switch with + * total clauses `witnesses`, and the active clause ranging + * from `start` to `end`. Parameter `hasDefault` denotes + * whether the active clause contains a default clause. + */ + function getFactsFromTypeofSwitch(start, end, witnesses, hasDefault) { + var facts = 0 /* None */; + // When in the default we only collect inequality facts + // because default is 'in theory' a set of infinite + // equalities. + if (hasDefault) { + // Value is not equal to any types after the active clause. + for (var i = end; i < witnesses.length; i++) { + facts |= typeofNEFacts.get(witnesses[i]) || 32768 /* TypeofNEHostObject */; + } + // Remove inequalities for types that appear in the + // active clause because they appear before other + // types collected so far. + for (var i = start; i < end; i++) { + facts &= ~(typeofNEFacts.get(witnesses[i]) || 0); + } + // Add inequalities for types before the active clause unconditionally. + for (var i = 0; i < start; i++) { + facts |= typeofNEFacts.get(witnesses[i]) || 32768 /* TypeofNEHostObject */; + } + } + // When in an active clause without default the set of + // equalities is finite. + else { + // Add equalities for all types in the active clause. + for (var i = start; i < end; i++) { + facts |= typeofEQFacts.get(witnesses[i]) || 128 /* TypeofEQHostObject */; + } + // Remove equalities for types that appear before the + // active clause. + for (var i = 0; i < start; i++) { + facts &= ~(typeofEQFacts.get(witnesses[i]) || 0); + } + } + return facts; + } + function isExhaustiveSwitchStatement(node) { + if (!node.possiblyExhaustive) { + return false; + } + if (node.expression.kind === 199 /* TypeOfExpression */) { + var operandType = getTypeOfExpression(node.expression.expression); + // This cast is safe because the switch is possibly exhaustive and does not contain a default case, so there can be no undefined. + var witnesses = getSwitchClauseTypeOfWitnesses(node); + // notEqualFacts states that the type of the switched value is not equal to every type in the switch. + var notEqualFacts_1 = getFactsFromTypeofSwitch(0, 0, witnesses, /*hasDefault*/ true); + var type_5 = getBaseConstraintOfType(operandType) || operandType; + return !!(filterType(type_5, function (t) { return (getTypeFacts(t) & notEqualFacts_1) === notEqualFacts_1; }).flags & 131072 /* Never */); + } + var type = getTypeOfExpression(node.expression); + if (!isLiteralType(type)) { + return false; + } + var switchTypes = getSwitchClauseTypes(node); + if (!switchTypes.length || ts.some(switchTypes, isNeitherUnitTypeNorNever)) { + return false; + } + return eachTypeContainedIn(mapType(type, getRegularTypeOfLiteralType), switchTypes); + } + function functionHasImplicitReturn(func) { + if (!(func.flags & 128 /* HasImplicitReturn */)) { + return false; + } + if (ts.some(func.body.statements, function (statement) { return statement.kind === 232 /* SwitchStatement */ && isExhaustiveSwitchStatement(statement); })) { + return false; + } + return true; + } + /** NOTE: Return value of `[]` means a different thing than `undefined`. `[]` means func returns `void`, `undefined` means it returns `never`. */ + function checkAndAggregateReturnExpressionTypes(func, checkMode) { + var functionFlags = ts.getFunctionFlags(func); + var aggregatedTypes = []; + var hasReturnWithNoExpression = functionHasImplicitReturn(func); + var hasReturnOfTypeNever = false; + ts.forEachReturnStatement(func.body, function (returnStatement) { + var expr = returnStatement.expression; + if (expr) { + var type = checkExpressionCached(expr, checkMode); + if (functionFlags & 2 /* Async */) { + // From within an async function you can return either a non-promise value or a promise. Any + // Promise/A+ compatible implementation will always assimilate any foreign promise, so the + // return type of the body should be unwrapped to its awaited type, which should be wrapped in + // the native Promise type by the caller. + type = checkAwaitedType(type, func, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); + } + if (type.flags & 131072 /* Never */) { + hasReturnOfTypeNever = true; + } + ts.pushIfUnique(aggregatedTypes, type); + } + else { + hasReturnWithNoExpression = true; + } + }); + if (aggregatedTypes.length === 0 && !hasReturnWithNoExpression && (hasReturnOfTypeNever || mayReturnNever(func))) { + return undefined; + } + if (strictNullChecks && aggregatedTypes.length && hasReturnWithNoExpression && + !(isJSConstructor(func) && aggregatedTypes.some(function (t) { return t.symbol === func.symbol; }))) { + // Javascript "callable constructors", containing eg `if (!(this instanceof A)) return new A()` should not add undefined + ts.pushIfUnique(aggregatedTypes, undefinedType); + } + return aggregatedTypes; + } + function mayReturnNever(func) { + switch (func.kind) { + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + return true; + case 156 /* MethodDeclaration */: + return func.parent.kind === 188 /* ObjectLiteralExpression */; + default: + return false; + } + } + /** + * TypeScript Specification 1.0 (6.3) - July 2014 + * An explicitly typed function whose return type isn't the Void type, + * the Any type, or a union type containing the Void or Any type as a constituent + * must have at least one return statement somewhere in its body. + * An exception to this rule is if the function implementation consists of a single 'throw' statement. + * + * @param returnType - return type of the function, can be undefined if return type is not explicitly specified + */ + function checkAllCodePathsInNonVoidFunctionReturnOrThrow(func, returnType) { + if (!produceDiagnostics) { + return; + } + // Functions with with an explicitly specified 'void' or 'any' return type don't need any return expressions. + if (returnType && maybeTypeOfKind(returnType, 1 /* Any */ | 16384 /* Void */)) { + return; + } + // If all we have is a function signature, or an arrow function with an expression body, then there is nothing to check. + // also if HasImplicitReturn flag is not set this means that all codepaths in function body end with return or throw + if (func.kind === 155 /* MethodSignature */ || ts.nodeIsMissing(func.body) || func.body.kind !== 218 /* Block */ || !functionHasImplicitReturn(func)) { + return; + } + var hasExplicitReturn = func.flags & 256 /* HasExplicitReturn */; + if (returnType && returnType.flags & 131072 /* Never */) { + error(ts.getEffectiveReturnTypeNode(func), ts.Diagnostics.A_function_returning_never_cannot_have_a_reachable_end_point); + } + else if (returnType && !hasExplicitReturn) { + // minimal check: function has syntactic return type annotation and no explicit return statements in the body + // this function does not conform to the specification. + // NOTE: having returnType !== undefined is a precondition for entering this branch so func.type will always be present + error(ts.getEffectiveReturnTypeNode(func), ts.Diagnostics.A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value); + } + else if (returnType && strictNullChecks && !isTypeAssignableTo(undefinedType, returnType)) { + error(ts.getEffectiveReturnTypeNode(func), ts.Diagnostics.Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined); + } + else if (compilerOptions.noImplicitReturns) { + if (!returnType) { + // If return type annotation is omitted check if function has any explicit return statements. + // If it does not have any - its inferred return type is void - don't do any checks. + // Otherwise get inferred return type from function body and report error only if it is not void / anytype + if (!hasExplicitReturn) { + return; + } + var inferredReturnType = getReturnTypeOfSignature(getSignatureFromDeclaration(func)); + if (isUnwrappedReturnTypeVoidOrAny(func, inferredReturnType)) { + return; + } + } + error(ts.getEffectiveReturnTypeNode(func) || func, ts.Diagnostics.Not_all_code_paths_return_a_value); + } + } + function checkFunctionExpressionOrObjectLiteralMethod(node, checkMode) { + ts.Debug.assert(node.kind !== 156 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + checkNodeDeferred(node); + // The identityMapper object is used to indicate that function expressions are wildcards + if (checkMode === 1 /* SkipContextSensitive */ && isContextSensitive(node)) { + // Skip parameters, return signature with return type that retains noncontextual parts so inferences can still be drawn in an early stage + if (!ts.getEffectiveReturnTypeNode(node) && hasContextSensitiveReturnExpression(node)) { + var links_1 = getNodeLinks(node); + if (links_1.contextFreeType) { + return links_1.contextFreeType; + } + var returnType = getReturnTypeFromBody(node, checkMode); + var returnOnlySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, returnType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + var returnOnlyType = createAnonymousType(node.symbol, emptySymbols, [returnOnlySignature], ts.emptyArray, undefined, undefined); + returnOnlyType.flags |= 536870912 /* ContainsAnyFunctionType */; + return links_1.contextFreeType = returnOnlyType; + } + return anyFunctionType; + } + // Grammar checking + var hasGrammarError = checkGrammarFunctionLikeDeclaration(node); + if (!hasGrammarError && node.kind === 196 /* FunctionExpression */) { + checkGrammarForGenerator(node); + } + var links = getNodeLinks(node); + var type = getTypeOfSymbol(getMergedSymbol(node.symbol)); + if (isTypeAny(type)) { + return type; + } + // Check if function expression is contextually typed and assign parameter types if so. + if (!(links.flags & 1024 /* ContextChecked */)) { + var contextualSignature = getContextualSignature(node); + // If a type check is started at a function expression that is an argument of a function call, obtaining the + // contextual type may recursively get back to here during overload resolution of the call. If so, we will have + // already assigned contextual types. + if (!(links.flags & 1024 /* ContextChecked */)) { + links.flags |= 1024 /* ContextChecked */; + if (contextualSignature) { + var signature = getSignaturesOfType(type, 0 /* Call */)[0]; + if (isContextSensitive(node)) { + var contextualMapper = getContextualMapper(node); + if (checkMode === 2 /* Inferential */) { + inferFromAnnotatedParameters(signature, contextualSignature, contextualMapper); + } + var instantiatedContextualSignature = contextualMapper === identityMapper ? + contextualSignature : instantiateSignature(contextualSignature, contextualMapper); + assignContextualParameterTypes(signature, instantiatedContextualSignature); + } + if (!getReturnTypeFromAnnotation(node) && !signature.resolvedReturnType) { + var returnType = getReturnTypeFromBody(node, checkMode); + if (!signature.resolvedReturnType) { + signature.resolvedReturnType = returnType; + } + } + } + checkSignatureDeclaration(node); + } + } + return type; + } + function getReturnOrPromisedType(node, functionFlags) { + var type = getReturnTypeFromAnnotation(node); + return type && ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */) ? + getAwaitedType(type) || errorType : type; + } + function checkFunctionExpressionOrObjectLiteralMethodDeferred(node) { + ts.Debug.assert(node.kind !== 156 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + var functionFlags = ts.getFunctionFlags(node); + var returnOrPromisedType = getReturnOrPromisedType(node, functionFlags); + if ((functionFlags & 1 /* Generator */) === 0) { // Async function or normal function + // return is not necessary in the body of generators + checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnOrPromisedType); + } + if (node.body) { + if (!ts.getEffectiveReturnTypeNode(node)) { + // There are some checks that are only performed in getReturnTypeFromBody, that may produce errors + // we need. An example is the noImplicitAny errors resulting from widening the return expression + // of a function. Because checking of function expression bodies is deferred, there was never an + // appropriate time to do this during the main walk of the file (see the comment at the top of + // checkFunctionExpressionBodies). So it must be done now. + getReturnTypeOfSignature(getSignatureFromDeclaration(node)); + } + if (node.body.kind === 218 /* Block */) { + checkSourceElement(node.body); + } + else { + // From within an async function you can return either a non-promise value or a promise. Any + // Promise/A+ compatible implementation will always assimilate any foreign promise, so we + // should not be checking assignability of a promise to the return type. Instead, we need to + // check assignability of the awaited type of the expression body against the promised type of + // its return type annotation. + var exprType = checkExpression(node.body); + if (returnOrPromisedType) { + if ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */) { // Async function + var awaitedType = checkAwaitedType(exprType, node.body, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); + checkTypeAssignableToAndOptionallyElaborate(awaitedType, returnOrPromisedType, node.body, node.body); + } + else { // Normal function + checkTypeAssignableToAndOptionallyElaborate(exprType, returnOrPromisedType, node.body, node.body); + } + } + } + } + } + function checkArithmeticOperandType(operand, type, diagnostic) { + if (!isTypeAssignableTo(type, numberOrBigIntType)) { + error(operand, diagnostic); + return false; + } + return true; + } + function isReadonlyAssignmentDeclaration(d) { + if (!ts.isCallExpression(d)) { + return false; + } + if (!ts.isBindableObjectDefinePropertyCall(d)) { + return false; + } + var objectLitType = checkExpressionCached(d.arguments[2]); + var valueType = getTypeOfPropertyOfType(objectLitType, "value"); + if (valueType) { + var writableProp = getPropertyOfType(objectLitType, "writable"); + var writableType = writableProp && getTypeOfSymbol(writableProp); + if (!writableType || writableType === falseType || writableType === regularFalseType) { + return true; + } + // We include this definition whereupon we walk back and check the type at the declaration because + // The usual definition of `Object.defineProperty` will _not_ cause literal types to be preserved in the + // argument types, should the type be contextualized by the call itself. + if (writableProp && writableProp.valueDeclaration && ts.isPropertyAssignment(writableProp.valueDeclaration)) { + var initializer = writableProp.valueDeclaration.initializer; + var rawOriginalType = checkExpression(initializer); + if (rawOriginalType === falseType || rawOriginalType === regularFalseType) { + return true; + } + } + return false; + } + var setProp = getPropertyOfType(objectLitType, "set"); + return !setProp; + } + function isReadonlySymbol(symbol) { + // The following symbols are considered read-only: + // Properties with a 'readonly' modifier + // Variables declared with 'const' + // Get accessors without matching set accessors + // Enum members + // Object.defineProperty assignments with writable false or no setter + // Unions and intersections of the above (unions and intersections eagerly set isReadonly on creation) + return !!(ts.getCheckFlags(symbol) & 8 /* Readonly */ || + symbol.flags & 4 /* Property */ && ts.getDeclarationModifierFlagsFromSymbol(symbol) & 64 /* Readonly */ || + symbol.flags & 3 /* Variable */ && getDeclarationNodeFlagsFromSymbol(symbol) & 2 /* Const */ || + symbol.flags & 98304 /* Accessor */ && !(symbol.flags & 65536 /* SetAccessor */) || + symbol.flags & 8 /* EnumMember */ || + ts.some(symbol.declarations, isReadonlyAssignmentDeclaration)); + } + function isReferenceToReadonlyEntity(expr, symbol) { + if (isReadonlySymbol(symbol)) { + // Allow assignments to readonly properties within constructors of the same class declaration. + if (symbol.flags & 4 /* Property */ && + (expr.kind === 189 /* PropertyAccessExpression */ || expr.kind === 190 /* ElementAccessExpression */) && + expr.expression.kind === 100 /* ThisKeyword */) { + // Look for if this is the constructor for the class that `symbol` is a property of. + var func = ts.getContainingFunction(expr); + if (!(func && func.kind === 157 /* Constructor */)) { + return true; + } + // If func.parent is a class and symbol is a (readonly) property of that class, or + // if func is a constructor and symbol is a (readonly) parameter property declared in it, + // then symbol is writeable here. + return !symbol.valueDeclaration || !(func.parent === symbol.valueDeclaration.parent || func === symbol.valueDeclaration.parent); + } + return true; + } + return false; + } + function isReferenceThroughNamespaceImport(expr) { + if (expr.kind === 189 /* PropertyAccessExpression */ || expr.kind === 190 /* ElementAccessExpression */) { + var node = ts.skipParentheses(expr.expression); + if (node.kind === 72 /* Identifier */) { + var symbol = getNodeLinks(node).resolvedSymbol; + if (symbol.flags & 2097152 /* Alias */) { + var declaration = getDeclarationOfAliasSymbol(symbol); + return !!declaration && declaration.kind === 251 /* NamespaceImport */; + } + } + } + return false; + } + function checkReferenceExpression(expr, invalidReferenceMessage) { + // References are combinations of identifiers, parentheses, and property accesses. + var node = ts.skipOuterExpressions(expr, 2 /* Assertions */ | 1 /* Parentheses */); + if (node.kind !== 72 /* Identifier */ && node.kind !== 189 /* PropertyAccessExpression */ && node.kind !== 190 /* ElementAccessExpression */) { + error(expr, invalidReferenceMessage); + return false; + } + return true; + } + function checkDeleteExpression(node) { + checkExpression(node.expression); + var expr = ts.skipParentheses(node.expression); + if (expr.kind !== 189 /* PropertyAccessExpression */ && expr.kind !== 190 /* ElementAccessExpression */) { + error(expr, ts.Diagnostics.The_operand_of_a_delete_operator_must_be_a_property_reference); + return booleanType; + } + var links = getNodeLinks(expr); + var symbol = getExportSymbolOfValueSymbolIfExported(links.resolvedSymbol); + if (symbol && isReadonlySymbol(symbol)) { + error(expr, ts.Diagnostics.The_operand_of_a_delete_operator_cannot_be_a_read_only_property); + } + return booleanType; + } + function checkTypeOfExpression(node) { + checkExpression(node.expression); + return typeofType; + } + function checkVoidExpression(node) { + checkExpression(node.expression); + return undefinedWideningType; + } + function checkAwaitExpression(node) { + // Grammar checking + if (produceDiagnostics) { + if (!(node.flags & 16384 /* AwaitContext */)) { + grammarErrorOnFirstToken(node, ts.Diagnostics.await_expression_is_only_allowed_within_an_async_function); + } + if (isInParameterInitializerBeforeContainingFunction(node)) { + error(node, ts.Diagnostics.await_expressions_cannot_be_used_in_a_parameter_initializer); + } + } + var operandType = checkExpression(node.expression); + return checkAwaitedType(operandType, node, ts.Diagnostics.Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); + } + function checkPrefixUnaryExpression(node) { + var operandType = checkExpression(node.operand); + if (operandType === silentNeverType) { + return silentNeverType; + } + switch (node.operand.kind) { + case 8 /* NumericLiteral */: + switch (node.operator) { + case 39 /* MinusToken */: + return getFreshTypeOfLiteralType(getLiteralType(-node.operand.text)); + case 38 /* PlusToken */: + return getFreshTypeOfLiteralType(getLiteralType(+node.operand.text)); + } + break; + case 9 /* BigIntLiteral */: + if (node.operator === 39 /* MinusToken */) { + return getFreshTypeOfLiteralType(getLiteralType({ + negative: true, + base10Value: ts.parsePseudoBigInt(node.operand.text) + })); + } + } + switch (node.operator) { + case 38 /* PlusToken */: + case 39 /* MinusToken */: + case 53 /* TildeToken */: + checkNonNullType(operandType, node.operand); + if (maybeTypeOfKind(operandType, 12288 /* ESSymbolLike */)) { + error(node.operand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(node.operator)); + } + if (node.operator === 38 /* PlusToken */) { + if (maybeTypeOfKind(operandType, 2112 /* BigIntLike */)) { + error(node.operand, ts.Diagnostics.Operator_0_cannot_be_applied_to_type_1, ts.tokenToString(node.operator), typeToString(operandType)); + } + return numberType; + } + return getUnaryResultType(operandType); + case 52 /* ExclamationToken */: + checkTruthinessExpression(node.operand); + var facts = getTypeFacts(operandType) & (4194304 /* Truthy */ | 8388608 /* Falsy */); + return facts === 4194304 /* Truthy */ ? falseType : + facts === 8388608 /* Falsy */ ? trueType : + booleanType; + case 44 /* PlusPlusToken */: + case 45 /* MinusMinusToken */: + var ok = checkArithmeticOperandType(node.operand, checkNonNullType(operandType, node.operand), ts.Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_bigint_or_an_enum_type); + if (ok) { + // run check only if former checks succeeded to avoid reporting cascading errors + checkReferenceExpression(node.operand, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access); + } + return getUnaryResultType(operandType); + } + return errorType; + } + function checkPostfixUnaryExpression(node) { + var operandType = checkExpression(node.operand); + if (operandType === silentNeverType) { + return silentNeverType; + } + var ok = checkArithmeticOperandType(node.operand, checkNonNullType(operandType, node.operand), ts.Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_bigint_or_an_enum_type); + if (ok) { + // run check only if former checks succeeded to avoid reporting cascading errors + checkReferenceExpression(node.operand, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access); + } + return getUnaryResultType(operandType); + } + function getUnaryResultType(operandType) { + if (maybeTypeOfKind(operandType, 2112 /* BigIntLike */)) { + return isTypeAssignableToKind(operandType, 3 /* AnyOrUnknown */) || maybeTypeOfKind(operandType, 296 /* NumberLike */) + ? numberOrBigIntType + : bigintType; + } + // If it's not a bigint type, implicit coercion will result in a number + return numberType; + } + // Return true if type might be of the given kind. A union or intersection type might be of a given + // kind if at least one constituent type is of the given kind. + function maybeTypeOfKind(type, kind) { + if (type.flags & kind & ~134217728 /* GenericMappedType */ || kind & 134217728 /* GenericMappedType */ && isGenericMappedType(type)) { + return true; + } + if (type.flags & 3145728 /* UnionOrIntersection */) { + var types = type.types; + for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { + var t = types_15[_i]; + if (maybeTypeOfKind(t, kind)) { + return true; + } + } + } + return false; + } + function isTypeAssignableToKind(source, kind, strict) { + if (source.flags & kind) { + return true; + } + if (strict && source.flags & (3 /* AnyOrUnknown */ | 16384 /* Void */ | 32768 /* Undefined */ | 65536 /* Null */)) { + return false; + } + return !!(kind & 296 /* NumberLike */) && isTypeAssignableTo(source, numberType) || + !!(kind & 2112 /* BigIntLike */) && isTypeAssignableTo(source, bigintType) || + !!(kind & 132 /* StringLike */) && isTypeAssignableTo(source, stringType) || + !!(kind & 528 /* BooleanLike */) && isTypeAssignableTo(source, booleanType) || + !!(kind & 16384 /* Void */) && isTypeAssignableTo(source, voidType) || + !!(kind & 131072 /* Never */) && isTypeAssignableTo(source, neverType) || + !!(kind & 65536 /* Null */) && isTypeAssignableTo(source, nullType) || + !!(kind & 32768 /* Undefined */) && isTypeAssignableTo(source, undefinedType) || + !!(kind & 4096 /* ESSymbol */) && isTypeAssignableTo(source, esSymbolType) || + !!(kind & 67108864 /* NonPrimitive */) && isTypeAssignableTo(source, nonPrimitiveType); + } + function allTypesAssignableToKind(source, kind, strict) { + return source.flags & 1048576 /* Union */ ? + ts.every(source.types, function (subType) { return allTypesAssignableToKind(subType, kind, strict); }) : + isTypeAssignableToKind(source, kind, strict); + } + function isConstEnumObjectType(type) { + return !!(ts.getObjectFlags(type) & 16 /* Anonymous */) && !!type.symbol && isConstEnumSymbol(type.symbol); + } + function isConstEnumSymbol(symbol) { + return (symbol.flags & 128 /* ConstEnum */) !== 0; + } + function checkInstanceOfExpression(left, right, leftType, rightType) { + if (leftType === silentNeverType || rightType === silentNeverType) { + return silentNeverType; + } + // TypeScript 1.0 spec (April 2014): 4.15.4 + // The instanceof operator requires the left operand to be of type Any, an object type, or a type parameter type, + // and the right operand to be of type Any, a subtype of the 'Function' interface type, or have a call or construct signature. + // The result is always of the Boolean primitive type. + // NOTE: do not raise error if leftType is unknown as related error was already reported + if (!isTypeAny(leftType) && + allTypesAssignableToKind(leftType, 131068 /* Primitive */)) { + error(left, ts.Diagnostics.The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter); + } + // NOTE: do not raise error if right is unknown as related error was already reported + if (!(isTypeAny(rightType) || typeHasCallOrConstructSignatures(rightType) || isTypeSubtypeOf(rightType, globalFunctionType))) { + error(right, ts.Diagnostics.The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_Function_interface_type); + } + return booleanType; + } + function checkInExpression(left, right, leftType, rightType) { + if (leftType === silentNeverType || rightType === silentNeverType) { + return silentNeverType; + } + leftType = checkNonNullType(leftType, left); + rightType = checkNonNullType(rightType, right); + // TypeScript 1.0 spec (April 2014): 4.15.5 + // The in operator requires the left operand to be of type Any, the String primitive type, or the Number primitive type, + // and the right operand to be of type Any, an object type, or a type parameter type. + // The result is always of the Boolean primitive type. + if (!(isTypeComparableTo(leftType, stringType) || isTypeAssignableToKind(leftType, 296 /* NumberLike */ | 12288 /* ESSymbolLike */))) { + error(left, ts.Diagnostics.The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol); + } + if (!isTypeAssignableToKind(rightType, 67108864 /* NonPrimitive */ | 58982400 /* InstantiableNonPrimitive */)) { + error(right, ts.Diagnostics.The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter); + } + return booleanType; + } + function checkObjectLiteralAssignment(node, sourceType, rightIsThis) { + var properties = node.properties; + if (strictNullChecks && properties.length === 0) { + return checkNonNullType(sourceType, node); + } + for (var _i = 0, properties_6 = properties; _i < properties_6.length; _i++) { + var p = properties_6[_i]; + checkObjectLiteralDestructuringPropertyAssignment(sourceType, p, properties, rightIsThis); + } + return sourceType; + } + /** Note: If property cannot be a SpreadAssignment, then allProperties does not need to be provided */ + function checkObjectLiteralDestructuringPropertyAssignment(objectLiteralType, property, allProperties, rightIsThis) { + if (rightIsThis === void 0) { rightIsThis = false; } + if (property.kind === 275 /* PropertyAssignment */ || property.kind === 276 /* ShorthandPropertyAssignment */) { + var name = property.name; + if (name.kind === 149 /* ComputedPropertyName */) { + checkComputedPropertyName(name); + } + if (isComputedNonLiteralName(name)) { + return undefined; + } + var type = getTypeOfObjectLiteralDestructuringProperty(objectLiteralType, name, property, rightIsThis); + if (type) { + // non-shorthand property assignments should always have initializers + return checkDestructuringAssignment(property.kind === 276 /* ShorthandPropertyAssignment */ ? property : property.initializer, type); + } + else { + error(name, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(objectLiteralType), ts.declarationNameToString(name)); + } + } + else if (property.kind === 277 /* SpreadAssignment */) { + if (languageVersion < 6 /* ESNext */) { + checkExternalEmitHelpers(property, 4 /* Rest */); + } + var nonRestNames = []; + if (allProperties) { + for (var i = 0; i < allProperties.length - 1; i++) { + nonRestNames.push(allProperties[i].name); + } + } + var type = getRestType(objectLiteralType, nonRestNames, objectLiteralType.symbol); + checkGrammarForDisallowedTrailingComma(allProperties, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma); + return checkDestructuringAssignment(property.expression, type); + } + else { + error(property, ts.Diagnostics.Property_assignment_expected); + } + } + function getTypeOfObjectLiteralDestructuringProperty(objectLiteralType, name, property, rightIsThis) { + if (isTypeAny(objectLiteralType)) { + return objectLiteralType; + } + var type; + var text = ts.getTextOfPropertyName(name); + if (text) { // TODO: GH#26379 + var prop = getPropertyOfType(objectLiteralType, text); + if (prop) { + markPropertyAsReferenced(prop, property, rightIsThis); + checkPropertyAccessibility(property, /*isSuper*/ false, objectLiteralType, prop); + type = getTypeOfSymbol(prop); + } + type = type || (isNumericLiteralName(text) ? getIndexTypeOfType(objectLiteralType, 1 /* Number */) : undefined); + } + return type || getIndexTypeOfType(objectLiteralType, 0 /* String */); + } + function checkArrayLiteralAssignment(node, sourceType, checkMode) { + var elements = node.elements; + if (languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) { + checkExternalEmitHelpers(node, 512 /* Read */); + } + // This elementType will be used if the specific property corresponding to this index is not + // present (aka the tuple element property). This call also checks that the parentType is in + // fact an iterable or array (depending on target language). + var elementType = checkIteratedTypeOrElementType(sourceType, node, /*allowStringInput*/ false, /*allowAsyncIterables*/ false) || errorType; + for (var i = 0; i < elements.length; i++) { + checkArrayLiteralDestructuringElementAssignment(node, sourceType, i, elementType, checkMode); + } + return sourceType; + } + function checkArrayLiteralDestructuringElementAssignment(node, sourceType, elementIndex, elementType, checkMode) { + var elements = node.elements; + var element = elements[elementIndex]; + if (element.kind !== 210 /* OmittedExpression */) { + if (element.kind !== 208 /* SpreadElement */) { + var propName = "" + elementIndex; + var type = isTypeAny(sourceType) ? sourceType : + everyType(sourceType, isTupleLikeType) ? getTupleElementType(sourceType, elementIndex) : + elementType; + if (type) { + return checkDestructuringAssignment(element, type, checkMode); + } + // We still need to check element expression here because we may need to set appropriate flag on the expression + // such as NodeCheckFlags.LexicalThis on "this"expression. + checkExpression(element); + if (isTupleType(sourceType)) { + error(element, ts.Diagnostics.Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2, typeToString(sourceType), getTypeReferenceArity(sourceType), elements.length); + } + else { + error(element, ts.Diagnostics.Type_0_has_no_property_1, typeToString(sourceType), propName); + } + } + else { + if (elementIndex < elements.length - 1) { + error(element, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern); + } + else { + var restExpression = element.expression; + if (restExpression.kind === 204 /* BinaryExpression */ && restExpression.operatorToken.kind === 59 /* EqualsToken */) { + error(restExpression.operatorToken, ts.Diagnostics.A_rest_element_cannot_have_an_initializer); + } + else { + checkGrammarForDisallowedTrailingComma(node.elements, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma); + var type = everyType(sourceType, isTupleType) ? + mapType(sourceType, function (t) { return sliceTupleType(t, elementIndex); }) : + createArrayType(elementType); + return checkDestructuringAssignment(restExpression, type, checkMode); + } + } + } + } + return undefined; + } + function checkDestructuringAssignment(exprOrAssignment, sourceType, checkMode, rightIsThis) { + var target; + if (exprOrAssignment.kind === 276 /* ShorthandPropertyAssignment */) { + var prop = exprOrAssignment; + if (prop.objectAssignmentInitializer) { + // In strict null checking mode, if a default value of a non-undefined type is specified, remove + // undefined from the final type. + if (strictNullChecks && + !(getFalsyFlags(checkExpression(prop.objectAssignmentInitializer)) & 32768 /* Undefined */)) { + sourceType = getTypeWithFacts(sourceType, 524288 /* NEUndefined */); + } + checkBinaryLikeExpression(prop.name, prop.equalsToken, prop.objectAssignmentInitializer, checkMode); + } + target = exprOrAssignment.name; + } + else { + target = exprOrAssignment; + } + if (target.kind === 204 /* BinaryExpression */ && target.operatorToken.kind === 59 /* EqualsToken */) { + checkBinaryExpression(target, checkMode); + target = target.left; + } + if (target.kind === 188 /* ObjectLiteralExpression */) { + return checkObjectLiteralAssignment(target, sourceType, rightIsThis); + } + if (target.kind === 187 /* ArrayLiteralExpression */) { + return checkArrayLiteralAssignment(target, sourceType, checkMode); + } + return checkReferenceAssignment(target, sourceType, checkMode); + } + function checkReferenceAssignment(target, sourceType, checkMode) { + var targetType = checkExpression(target, checkMode); + var error = target.parent.kind === 277 /* SpreadAssignment */ ? + ts.Diagnostics.The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access : + ts.Diagnostics.The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access; + if (checkReferenceExpression(target, error)) { + checkTypeAssignableToAndOptionallyElaborate(sourceType, targetType, target, target); + } + return sourceType; + } + /** + * This is a *shallow* check: An expression is side-effect-free if the + * evaluation of the expression *itself* cannot produce side effects. + * For example, x++ / 3 is side-effect free because the / operator + * does not have side effects. + * The intent is to "smell test" an expression for correctness in positions where + * its value is discarded (e.g. the left side of the comma operator). + */ + function isSideEffectFree(node) { + node = ts.skipParentheses(node); + switch (node.kind) { + case 72 /* Identifier */: + case 10 /* StringLiteral */: + case 13 /* RegularExpressionLiteral */: + case 193 /* TaggedTemplateExpression */: + case 206 /* TemplateExpression */: + case 14 /* NoSubstitutionTemplateLiteral */: + case 8 /* NumericLiteral */: + case 9 /* BigIntLiteral */: + case 102 /* TrueKeyword */: + case 87 /* FalseKeyword */: + case 96 /* NullKeyword */: + case 141 /* UndefinedKeyword */: + case 196 /* FunctionExpression */: + case 209 /* ClassExpression */: + case 197 /* ArrowFunction */: + case 187 /* ArrayLiteralExpression */: + case 188 /* ObjectLiteralExpression */: + case 199 /* TypeOfExpression */: + case 213 /* NonNullExpression */: + case 261 /* JsxSelfClosingElement */: + case 260 /* JsxElement */: + return true; + case 205 /* ConditionalExpression */: + return isSideEffectFree(node.whenTrue) && + isSideEffectFree(node.whenFalse); + case 204 /* BinaryExpression */: + if (ts.isAssignmentOperator(node.operatorToken.kind)) { + return false; + } + return isSideEffectFree(node.left) && + isSideEffectFree(node.right); + case 202 /* PrefixUnaryExpression */: + case 203 /* PostfixUnaryExpression */: + // Unary operators ~, !, +, and - have no side effects. + // The rest do. + switch (node.operator) { + case 52 /* ExclamationToken */: + case 38 /* PlusToken */: + case 39 /* MinusToken */: + case 53 /* TildeToken */: + return true; + } + return false; + // Some forms listed here for clarity + case 200 /* VoidExpression */: // Explicit opt-out + case 194 /* TypeAssertionExpression */: // Not SEF, but can produce useful type warnings + case 212 /* AsExpression */: // Not SEF, but can produce useful type warnings + default: + return false; + } + } + function isTypeEqualityComparableTo(source, target) { + return (target.flags & 98304 /* Nullable */) !== 0 || isTypeComparableTo(source, target); + } + function checkBinaryExpression(node, checkMode) { + if (ts.isInJSFile(node) && ts.getAssignedExpandoInitializer(node)) { + return checkExpression(node.right, checkMode); + } + return checkBinaryLikeExpression(node.left, node.operatorToken, node.right, checkMode, node); + } + function checkBinaryLikeExpression(left, operatorToken, right, checkMode, errorNode) { + var operator = operatorToken.kind; + if (operator === 59 /* EqualsToken */ && (left.kind === 188 /* ObjectLiteralExpression */ || left.kind === 187 /* ArrayLiteralExpression */)) { + return checkDestructuringAssignment(left, checkExpression(right, checkMode), checkMode, right.kind === 100 /* ThisKeyword */); + } + var leftType; + if (operator === 54 /* AmpersandAmpersandToken */ || operator === 55 /* BarBarToken */) { + leftType = checkTruthinessExpression(left, checkMode); + } + else { + leftType = checkExpression(left, checkMode); + } + var rightType = checkExpression(right, checkMode); + switch (operator) { + case 40 /* AsteriskToken */: + case 41 /* AsteriskAsteriskToken */: + case 62 /* AsteriskEqualsToken */: + case 63 /* AsteriskAsteriskEqualsToken */: + case 42 /* SlashToken */: + case 64 /* SlashEqualsToken */: + case 43 /* PercentToken */: + case 65 /* PercentEqualsToken */: + case 39 /* MinusToken */: + case 61 /* MinusEqualsToken */: + case 46 /* LessThanLessThanToken */: + case 66 /* LessThanLessThanEqualsToken */: + case 47 /* GreaterThanGreaterThanToken */: + case 67 /* GreaterThanGreaterThanEqualsToken */: + case 48 /* GreaterThanGreaterThanGreaterThanToken */: + case 68 /* GreaterThanGreaterThanGreaterThanEqualsToken */: + case 50 /* BarToken */: + case 70 /* BarEqualsToken */: + case 51 /* CaretToken */: + case 71 /* CaretEqualsToken */: + case 49 /* AmpersandToken */: + case 69 /* AmpersandEqualsToken */: + if (leftType === silentNeverType || rightType === silentNeverType) { + return silentNeverType; + } + leftType = checkNonNullType(leftType, left); + rightType = checkNonNullType(rightType, right); + var suggestedOperator = void 0; + // if a user tries to apply a bitwise operator to 2 boolean operands + // try and return them a helpful suggestion + if ((leftType.flags & 528 /* BooleanLike */) && + (rightType.flags & 528 /* BooleanLike */) && + (suggestedOperator = getSuggestedBooleanOperator(operatorToken.kind)) !== undefined) { + error(errorNode || operatorToken, ts.Diagnostics.The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead, ts.tokenToString(operatorToken.kind), ts.tokenToString(suggestedOperator)); + return numberType; + } + else { + // otherwise just check each operand separately and report errors as normal + var leftOk = checkArithmeticOperandType(left, leftType, ts.Diagnostics.The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type); + var rightOk = checkArithmeticOperandType(right, rightType, ts.Diagnostics.The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type); + var resultType_1; + // If both are any or unknown, allow operation; assume it will resolve to number + if ((isTypeAssignableToKind(leftType, 3 /* AnyOrUnknown */) && isTypeAssignableToKind(rightType, 3 /* AnyOrUnknown */)) || + // Or, if neither could be bigint, implicit coercion results in a number result + !(maybeTypeOfKind(leftType, 2112 /* BigIntLike */) || maybeTypeOfKind(rightType, 2112 /* BigIntLike */))) { + resultType_1 = numberType; + } + // At least one is assignable to bigint, so both should be only assignable to bigint + else if (isTypeAssignableToKind(leftType, 2112 /* BigIntLike */) && isTypeAssignableToKind(rightType, 2112 /* BigIntLike */)) { + switch (operator) { + case 48 /* GreaterThanGreaterThanGreaterThanToken */: + case 68 /* GreaterThanGreaterThanGreaterThanEqualsToken */: + reportOperatorError(); + } + resultType_1 = bigintType; + } + else { + reportOperatorError(); + resultType_1 = errorType; + } + if (leftOk && rightOk) { + checkAssignmentOperator(resultType_1); + } + return resultType_1; + } + case 38 /* PlusToken */: + case 60 /* PlusEqualsToken */: + if (leftType === silentNeverType || rightType === silentNeverType) { + return silentNeverType; + } + if (!isTypeAssignableToKind(leftType, 132 /* StringLike */) && !isTypeAssignableToKind(rightType, 132 /* StringLike */)) { + leftType = checkNonNullType(leftType, left); + rightType = checkNonNullType(rightType, right); + } + var resultType = void 0; + if (isTypeAssignableToKind(leftType, 296 /* NumberLike */, /*strict*/ true) && isTypeAssignableToKind(rightType, 296 /* NumberLike */, /*strict*/ true)) { + // Operands of an enum type are treated as having the primitive type Number. + // If both operands are of the Number primitive type, the result is of the Number primitive type. + resultType = numberType; + } + else if (isTypeAssignableToKind(leftType, 2112 /* BigIntLike */, /*strict*/ true) && isTypeAssignableToKind(rightType, 2112 /* BigIntLike */, /*strict*/ true)) { + // If both operands are of the BigInt primitive type, the result is of the BigInt primitive type. + resultType = bigintType; + } + else if (isTypeAssignableToKind(leftType, 132 /* StringLike */, /*strict*/ true) || isTypeAssignableToKind(rightType, 132 /* StringLike */, /*strict*/ true)) { + // If one or both operands are of the String primitive type, the result is of the String primitive type. + resultType = stringType; + } + else if (isTypeAny(leftType) || isTypeAny(rightType)) { + // Otherwise, the result is of type Any. + // NOTE: unknown type here denotes error type. Old compiler treated this case as any type so do we. + resultType = leftType === errorType || rightType === errorType ? errorType : anyType; + } + // Symbols are not allowed at all in arithmetic expressions + if (resultType && !checkForDisallowedESSymbolOperand(operator)) { + return resultType; + } + if (!resultType) { + reportOperatorError(); + return anyType; + } + if (operator === 60 /* PlusEqualsToken */) { + checkAssignmentOperator(resultType); + } + return resultType; + case 28 /* LessThanToken */: + case 30 /* GreaterThanToken */: + case 31 /* LessThanEqualsToken */: + case 32 /* GreaterThanEqualsToken */: + if (checkForDisallowedESSymbolOperand(operator)) { + leftType = getBaseTypeOfLiteralType(checkNonNullType(leftType, left)); + rightType = getBaseTypeOfLiteralType(checkNonNullType(rightType, right)); + if (!(isTypeComparableTo(leftType, rightType) || isTypeComparableTo(rightType, leftType) || + (isTypeAssignableTo(leftType, numberOrBigIntType) && isTypeAssignableTo(rightType, numberOrBigIntType)))) { + reportOperatorError(); + } + } + return booleanType; + case 33 /* EqualsEqualsToken */: + case 34 /* ExclamationEqualsToken */: + case 35 /* EqualsEqualsEqualsToken */: + case 36 /* ExclamationEqualsEqualsToken */: + var leftIsLiteral = isLiteralType(leftType); + var rightIsLiteral = isLiteralType(rightType); + if (!leftIsLiteral || !rightIsLiteral) { + leftType = leftIsLiteral ? getBaseTypeOfLiteralType(leftType) : leftType; + rightType = rightIsLiteral ? getBaseTypeOfLiteralType(rightType) : rightType; + } + if (!isTypeEqualityComparableTo(leftType, rightType) && !isTypeEqualityComparableTo(rightType, leftType)) { + reportOperatorError(); + } + return booleanType; + case 94 /* InstanceOfKeyword */: + return checkInstanceOfExpression(left, right, leftType, rightType); + case 93 /* InKeyword */: + return checkInExpression(left, right, leftType, rightType); + case 54 /* AmpersandAmpersandToken */: + return getTypeFacts(leftType) & 4194304 /* Truthy */ ? + getUnionType([extractDefinitelyFalsyTypes(strictNullChecks ? leftType : getBaseTypeOfLiteralType(rightType)), rightType]) : + leftType; + case 55 /* BarBarToken */: + return getTypeFacts(leftType) & 8388608 /* Falsy */ ? + getUnionType([removeDefinitelyFalsyTypes(leftType), rightType], 2 /* Subtype */) : + leftType; + case 59 /* EqualsToken */: + var declKind = ts.isBinaryExpression(left.parent) ? ts.getAssignmentDeclarationKind(left.parent) : 0 /* None */; + checkAssignmentDeclaration(declKind, rightType); + if (isAssignmentDeclaration(declKind)) { + if (!(rightType.flags & 524288 /* Object */) || + declKind !== 2 /* ModuleExports */ && + declKind !== 6 /* Prototype */ && + !isEmptyObjectType(rightType) && + !isFunctionObjectType(rightType) && + !(ts.getObjectFlags(rightType) & 1 /* Class */)) { + // don't check assignability of module.exports=, C.prototype=, or expando types because they will necessarily be incomplete + checkAssignmentOperator(rightType); + } + return leftType; + } + else { + checkAssignmentOperator(rightType); + return getRegularTypeOfObjectLiteral(rightType); + } + case 27 /* CommaToken */: + if (!compilerOptions.allowUnreachableCode && isSideEffectFree(left) && !isEvalNode(right)) { + error(left, ts.Diagnostics.Left_side_of_comma_operator_is_unused_and_has_no_side_effects); + } + return rightType; + default: + return ts.Debug.fail(); + } + function checkAssignmentDeclaration(kind, rightType) { + if (kind === 2 /* ModuleExports */) { + for (var _i = 0, _a = getPropertiesOfObjectType(rightType); _i < _a.length; _i++) { + var prop = _a[_i]; + var propType = getTypeOfSymbol(prop); + if (propType.symbol && propType.symbol.flags & 32 /* Class */) { + var name = prop.escapedName; + var symbol = resolveName(prop.valueDeclaration, name, 67897832 /* Type */, undefined, name, /*isUse*/ false); + if (symbol && symbol.declarations.some(ts.isJSDocTypedefTag)) { + grammarErrorOnNode(symbol.declarations[0], ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name)); + return grammarErrorOnNode(prop.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name)); + } + } + } + } + } + function isEvalNode(node) { + return node.kind === 72 /* Identifier */ && node.escapedText === "eval"; + } + // Return true if there was no error, false if there was an error. + function checkForDisallowedESSymbolOperand(operator) { + var offendingSymbolOperand = maybeTypeOfKind(leftType, 12288 /* ESSymbolLike */) ? left : + maybeTypeOfKind(rightType, 12288 /* ESSymbolLike */) ? right : + undefined; + if (offendingSymbolOperand) { + error(offendingSymbolOperand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(operator)); + return false; + } + return true; + } + function getSuggestedBooleanOperator(operator) { + switch (operator) { + case 50 /* BarToken */: + case 70 /* BarEqualsToken */: + return 55 /* BarBarToken */; + case 51 /* CaretToken */: + case 71 /* CaretEqualsToken */: + return 36 /* ExclamationEqualsEqualsToken */; + case 49 /* AmpersandToken */: + case 69 /* AmpersandEqualsToken */: + return 54 /* AmpersandAmpersandToken */; + default: + return undefined; + } + } + function checkAssignmentOperator(valueType) { + if (produceDiagnostics && ts.isAssignmentOperator(operator)) { + // TypeScript 1.0 spec (April 2014): 4.17 + // An assignment of the form + // VarExpr = ValueExpr + // requires VarExpr to be classified as a reference + // A compound assignment furthermore requires VarExpr to be classified as a reference (section 4.1) + // and the type of the non-compound operation to be assignable to the type of VarExpr. + if (checkReferenceExpression(left, ts.Diagnostics.The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access) + && (!ts.isIdentifier(left) || ts.unescapeLeadingUnderscores(left.escapedText) !== "exports")) { + // to avoid cascading errors check assignability only if 'isReference' check succeeded and no errors were reported + checkTypeAssignableToAndOptionallyElaborate(valueType, leftType, left, right); + } + } + } + function isAssignmentDeclaration(kind) { + switch (kind) { + case 2 /* ModuleExports */: + return true; + case 1 /* ExportsProperty */: + case 5 /* Property */: + case 6 /* Prototype */: + case 3 /* PrototypeProperty */: + case 4 /* ThisProperty */: + var symbol = getSymbolOfNode(left); + var init = ts.getAssignedExpandoInitializer(right); + return init && ts.isObjectLiteralExpression(init) && + symbol && ts.hasEntries(symbol.exports); + default: + return false; + } + } + function reportOperatorError() { + var leftStr = typeToString(leftType); + var rightStr = typeToString(rightType); + var errNode = errorNode || operatorToken; + if (!tryGiveBetterPrimaryError(errNode, leftStr, rightStr)) { + error(errNode, ts.Diagnostics.Operator_0_cannot_be_applied_to_types_1_and_2, ts.tokenToString(operatorToken.kind), leftStr, rightStr); + } + } + function tryGiveBetterPrimaryError(errNode, leftStr, rightStr) { + switch (operatorToken.kind) { + case 35 /* EqualsEqualsEqualsToken */: + case 33 /* EqualsEqualsToken */: + return error(errNode, ts.Diagnostics.This_condition_will_always_return_0_since_the_types_1_and_2_have_no_overlap, "false", leftStr, rightStr); + case 36 /* ExclamationEqualsEqualsToken */: + case 34 /* ExclamationEqualsToken */: + return error(errNode, ts.Diagnostics.This_condition_will_always_return_0_since_the_types_1_and_2_have_no_overlap, "true", leftStr, rightStr); + } + return undefined; + } + } + function isYieldExpressionInClass(node) { + var current = node; + var parent = node.parent; + while (parent) { + if (ts.isFunctionLike(parent) && current === parent.body) { + return false; + } + else if (ts.isClassLike(current)) { + return true; + } + current = parent; + parent = parent.parent; + } + return false; + } + function checkYieldExpression(node) { + // Grammar checking + if (produceDiagnostics) { + if (!(node.flags & 4096 /* YieldContext */) || isYieldExpressionInClass(node)) { + grammarErrorOnFirstToken(node, ts.Diagnostics.A_yield_expression_is_only_allowed_in_a_generator_body); + } + if (isInParameterInitializerBeforeContainingFunction(node)) { + error(node, ts.Diagnostics.yield_expressions_cannot_be_used_in_a_parameter_initializer); + } + } + var func = ts.getContainingFunction(node); + if (!func) + return anyType; + var functionFlags = ts.getFunctionFlags(func); + if (!(functionFlags & 1 /* Generator */)) { + // If the user's code is syntactically correct, the func should always have a star. After all, we are in a yield context. + return anyType; + } + if (node.asteriskToken) { + // Async generator functions prior to ESNext require the __await, __asyncDelegator, + // and __asyncValues helpers + if ((functionFlags & 3 /* AsyncGenerator */) === 3 /* AsyncGenerator */ && + languageVersion < 6 /* ESNext */) { + checkExternalEmitHelpers(node, 26624 /* AsyncDelegatorIncludes */); + } + // Generator functions prior to ES2015 require the __values helper + if ((functionFlags & 3 /* AsyncGenerator */) === 1 /* Generator */ && + languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) { + checkExternalEmitHelpers(node, 256 /* Values */); + } + } + var isAsync = (functionFlags & 2 /* Async */) !== 0; + var yieldedType = getYieldedTypeOfYieldExpression(node, isAsync); // TODO: GH#18217 + // There is no point in doing an assignability check if the function + // has no explicit return type because the return type is directly computed + // from the yield expressions. + var returnType = getReturnTypeFromAnnotation(func); + if (returnType) { + var signatureElementType = getIteratedTypeOfGenerator(returnType, isAsync) || anyType; + checkTypeAssignableToAndOptionallyElaborate(yieldedType, signatureElementType, node.expression || node, node.expression); + } + // Both yield and yield* expressions have type 'any' + return anyType; + } + function checkConditionalExpression(node, checkMode) { + checkTruthinessExpression(node.condition); + var type1 = checkExpression(node.whenTrue, checkMode); + var type2 = checkExpression(node.whenFalse, checkMode); + return getUnionType([type1, type2], 2 /* Subtype */); + } + function checkTemplateExpression(node) { + // We just want to check each expressions, but we are unconcerned with + // the type of each expression, as any value may be coerced into a string. + // It is worth asking whether this is what we really want though. + // A place where we actually *are* concerned with the expressions' types are + // in tagged templates. + ts.forEach(node.templateSpans, function (templateSpan) { + if (maybeTypeOfKind(checkExpression(templateSpan.expression), 12288 /* ESSymbolLike */)) { + error(templateSpan.expression, ts.Diagnostics.Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_in_String); + } + }); + return stringType; + } + function getContextNode(node) { + if (node.kind === 268 /* JsxAttributes */ && !ts.isJsxSelfClosingElement(node.parent)) { + return node.parent.parent; // Needs to be the root JsxElement, so it encompasses the attributes _and_ the children (which are essentially part of the attributes) + } + return node; + } + function checkExpressionWithContextualType(node, contextualType, contextualMapper) { + var context = getContextNode(node); + var saveContextualType = context.contextualType; + var saveContextualMapper = context.contextualMapper; + context.contextualType = contextualType; + context.contextualMapper = contextualMapper; + var checkMode = contextualMapper === identityMapper ? 1 /* SkipContextSensitive */ : + contextualMapper ? 2 /* Inferential */ : 3 /* Contextual */; + var result = checkExpression(node, checkMode); + context.contextualType = saveContextualType; + context.contextualMapper = saveContextualMapper; + return result; + } + function checkExpressionCached(node, checkMode) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + if (checkMode) { + return checkExpression(node, checkMode); + } + // When computing a type that we're going to cache, we need to ignore any ongoing control flow + // analysis because variables may have transient types in indeterminable states. Moving flowLoopStart + // to the top of the stack ensures all transient types are computed from a known point. + var saveFlowLoopStart = flowLoopStart; + flowLoopStart = flowLoopCount; + links.resolvedType = checkExpression(node, checkMode); + flowLoopStart = saveFlowLoopStart; + } + return links.resolvedType; + } + function isTypeAssertion(node) { + node = ts.skipParentheses(node); + return node.kind === 194 /* TypeAssertionExpression */ || node.kind === 212 /* AsExpression */; + } + function checkDeclarationInitializer(declaration) { + var initializer = ts.getEffectiveInitializer(declaration); + var type = getTypeOfExpression(initializer, /*cache*/ true); + var widened = ts.getCombinedNodeFlags(declaration) & 2 /* Const */ || + ts.isDeclarationReadonly(declaration) || + isTypeAssertion(initializer) ? type : getWidenedLiteralType(type); + if (ts.isInJSFile(declaration)) { + if (widened.flags & 98304 /* Nullable */) { + reportImplicitAny(declaration, anyType); + return anyType; + } + else if (isEmptyArrayLiteralType(widened)) { + reportImplicitAny(declaration, anyArrayType); + return anyArrayType; + } + } + return widened; + } + function isLiteralOfContextualType(candidateType, contextualType) { + if (contextualType) { + if (contextualType.flags & 3145728 /* UnionOrIntersection */) { + var types = contextualType.types; + return ts.some(types, function (t) { return isLiteralOfContextualType(candidateType, t); }); + } + if (contextualType.flags & 58982400 /* InstantiableNonPrimitive */) { + // If the contextual type is a type variable constrained to a primitive type, consider + // this a literal context for literals of that primitive type. For example, given a + // type parameter 'T extends string', infer string literal types for T. + var constraint = getBaseConstraintOfType(contextualType) || emptyObjectType; + return maybeTypeOfKind(constraint, 4 /* String */) && maybeTypeOfKind(candidateType, 128 /* StringLiteral */) || + maybeTypeOfKind(constraint, 8 /* Number */) && maybeTypeOfKind(candidateType, 256 /* NumberLiteral */) || + maybeTypeOfKind(constraint, 64 /* BigInt */) && maybeTypeOfKind(candidateType, 2048 /* BigIntLiteral */) || + maybeTypeOfKind(constraint, 4096 /* ESSymbol */) && maybeTypeOfKind(candidateType, 8192 /* UniqueESSymbol */) || + isLiteralOfContextualType(candidateType, constraint); + } + // If the contextual type is a literal of a particular primitive type, we consider this a + // literal context for all literals of that primitive type. + return !!(contextualType.flags & (128 /* StringLiteral */ | 4194304 /* Index */) && maybeTypeOfKind(candidateType, 128 /* StringLiteral */) || + contextualType.flags & 256 /* NumberLiteral */ && maybeTypeOfKind(candidateType, 256 /* NumberLiteral */) || + contextualType.flags & 2048 /* BigIntLiteral */ && maybeTypeOfKind(candidateType, 2048 /* BigIntLiteral */) || + contextualType.flags & 512 /* BooleanLiteral */ && maybeTypeOfKind(candidateType, 512 /* BooleanLiteral */) || + contextualType.flags & 8192 /* UniqueESSymbol */ && maybeTypeOfKind(candidateType, 8192 /* UniqueESSymbol */)); + } + return false; + } + function checkExpressionForMutableLocation(node, checkMode, contextualType, forceTuple) { + if (arguments.length === 2) { + contextualType = getContextualType(node); + } + var type = checkExpression(node, checkMode, forceTuple); + return isTypeAssertion(node) ? type : + getWidenedLiteralLikeTypeForContextualType(type, contextualType); + } + function checkPropertyAssignment(node, checkMode) { + // Do not use hasDynamicName here, because that returns false for well known symbols. + // We want to perform checkComputedPropertyName for all computed properties, including + // well known symbols. + if (node.name.kind === 149 /* ComputedPropertyName */) { + checkComputedPropertyName(node.name); + } + return checkExpressionForMutableLocation(node.initializer, checkMode); + } + function checkObjectLiteralMethod(node, checkMode) { + // Grammar checking + checkGrammarMethod(node); + // Do not use hasDynamicName here, because that returns false for well known symbols. + // We want to perform checkComputedPropertyName for all computed properties, including + // well known symbols. + if (node.name.kind === 149 /* ComputedPropertyName */) { + checkComputedPropertyName(node.name); + } + var uninstantiatedType = checkFunctionExpressionOrObjectLiteralMethod(node, checkMode); + return instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode); + } + function instantiateTypeWithSingleGenericCallSignature(node, type, checkMode) { + if (checkMode === 2 /* Inferential */) { + var signature = getSingleCallSignature(type); + if (signature && signature.typeParameters) { + var contextualType = getApparentTypeOfContextualType(node); + if (contextualType) { + var contextualSignature = getSingleCallSignature(getNonNullableType(contextualType)); + if (contextualSignature && !contextualSignature.typeParameters) { + return getOrCreateTypeFromSignature(instantiateSignatureInContextOf(signature, contextualSignature, getContextualMapper(node))); + } + } + } + } + return type; + } + /** + * Returns the type of an expression. Unlike checkExpression, this function is simply concerned + * with computing the type and may not fully check all contained sub-expressions for errors. + * A cache argument of true indicates that if the function performs a full type check, it is ok + * to cache the result. + */ + function getTypeOfExpression(node, cache) { + var expr = ts.skipParentheses(node); + // Optimize for the common case of a call to a function with a single non-generic call + // signature where we can just fetch the return type without checking the arguments. + if (expr.kind === 191 /* CallExpression */ && expr.expression.kind !== 98 /* SuperKeyword */ && !ts.isRequireCall(expr, /*checkArgumentIsStringLiteralLike*/ true) && !isSymbolOrSymbolForCall(expr)) { + var funcType = checkNonNullExpression(expr.expression); + var signature = getSingleCallSignature(funcType); + if (signature && !signature.typeParameters) { + return getReturnTypeOfSignature(signature); + } + } + else if (expr.kind === 194 /* TypeAssertionExpression */ || expr.kind === 212 /* AsExpression */) { + return getTypeFromTypeNode(expr.type); + } + // Otherwise simply call checkExpression. Ideally, the entire family of checkXXX functions + // should have a parameter that indicates whether full error checking is required such that + // we can perform the optimizations locally. + return cache ? checkExpressionCached(node) : checkExpression(node); + } + /** + * Returns the type of an expression. Unlike checkExpression, this function is simply concerned + * with computing the type and may not fully check all contained sub-expressions for errors. + * It is intended for uses where you know there is no contextual type, + * and requesting the contextual type might cause a circularity or other bad behaviour. + * It sets the contextual type of the node to any before calling getTypeOfExpression. + */ + function getContextFreeTypeOfExpression(node) { + var links = getNodeLinks(node); + if (links.contextFreeType) { + return links.contextFreeType; + } + var saveContextualType = node.contextualType; + node.contextualType = anyType; + var type = links.contextFreeType = checkExpression(node, 1 /* SkipContextSensitive */); + node.contextualType = saveContextualType; + return type; + } + // Checks an expression and returns its type. The contextualMapper parameter serves two purposes: When + // contextualMapper is not undefined and not equal to the identityMapper function object it indicates that the + // expression is being inferentially typed (section 4.15.2 in spec) and provides the type mapper to use in + // conjunction with the generic contextual type. When contextualMapper is equal to the identityMapper function + // object, it serves as an indicator that all contained function and arrow expressions should be considered to + // have the wildcard function type; this form of type check is used during overload resolution to exclude + // contextually typed function and arrow expressions in the initial phase. + function checkExpression(node, checkMode, forceTuple) { + var type; + if (node.kind === 148 /* QualifiedName */) { + type = checkQualifiedName(node); + } + else { + var uninstantiatedType = checkExpressionWorker(node, checkMode, forceTuple); + type = instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode); + } + if (isConstEnumObjectType(type)) { + // enum object type for const enums are only permitted in: + // - 'left' in property access + // - 'object' in indexed access + // - target in rhs of import statement + var ok = (node.parent.kind === 189 /* PropertyAccessExpression */ && node.parent.expression === node) || + (node.parent.kind === 190 /* ElementAccessExpression */ && node.parent.expression === node) || + ((node.kind === 72 /* Identifier */ || node.kind === 148 /* QualifiedName */) && isInRightSideOfImportOrExportAssignment(node) || + (node.parent.kind === 167 /* TypeQuery */ && node.parent.exprName === node)); + if (!ok) { + error(node, ts.Diagnostics.const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment_or_type_query); + } + } + return type; + } + function checkParenthesizedExpression(node, checkMode) { + var tag = ts.isInJSFile(node) ? ts.getJSDocTypeTag(node) : undefined; + if (tag) { + return checkAssertionWorker(tag, tag.typeExpression.type, node.expression, checkMode); + } + return checkExpression(node.expression, checkMode); + } + function checkExpressionWorker(node, checkMode, forceTuple) { + switch (node.kind) { + case 72 /* Identifier */: + return checkIdentifier(node); + case 100 /* ThisKeyword */: + return checkThisExpression(node); + case 98 /* SuperKeyword */: + return checkSuperExpression(node); + case 96 /* NullKeyword */: + return nullWideningType; + case 14 /* NoSubstitutionTemplateLiteral */: + case 10 /* StringLiteral */: + return getFreshTypeOfLiteralType(getLiteralType(node.text)); + case 8 /* NumericLiteral */: + checkGrammarNumericLiteral(node); + return getFreshTypeOfLiteralType(getLiteralType(+node.text)); + case 9 /* BigIntLiteral */: + checkGrammarBigIntLiteral(node); + return getFreshTypeOfLiteralType(getBigIntLiteralType(node)); + case 102 /* TrueKeyword */: + return trueType; + case 87 /* FalseKeyword */: + return falseType; + case 206 /* TemplateExpression */: + return checkTemplateExpression(node); + case 13 /* RegularExpressionLiteral */: + return globalRegExpType; + case 187 /* ArrayLiteralExpression */: + return checkArrayLiteral(node, checkMode, forceTuple); + case 188 /* ObjectLiteralExpression */: + return checkObjectLiteral(node, checkMode); + case 189 /* PropertyAccessExpression */: + return checkPropertyAccessExpression(node); + case 190 /* ElementAccessExpression */: + return checkIndexedAccess(node); + case 191 /* CallExpression */: + if (node.expression.kind === 92 /* ImportKeyword */) { + return checkImportCallExpression(node); + } + /* falls through */ + case 192 /* NewExpression */: + return checkCallExpression(node); + case 193 /* TaggedTemplateExpression */: + return checkTaggedTemplateExpression(node); + case 195 /* ParenthesizedExpression */: + return checkParenthesizedExpression(node, checkMode); + case 209 /* ClassExpression */: + return checkClassExpression(node); + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + return checkFunctionExpressionOrObjectLiteralMethod(node, checkMode); + case 199 /* TypeOfExpression */: + return checkTypeOfExpression(node); + case 194 /* TypeAssertionExpression */: + case 212 /* AsExpression */: + return checkAssertion(node); + case 213 /* NonNullExpression */: + return checkNonNullAssertion(node); + case 214 /* MetaProperty */: + return checkMetaProperty(node); + case 198 /* DeleteExpression */: + return checkDeleteExpression(node); + case 200 /* VoidExpression */: + return checkVoidExpression(node); + case 201 /* AwaitExpression */: + return checkAwaitExpression(node); + case 202 /* PrefixUnaryExpression */: + return checkPrefixUnaryExpression(node); + case 203 /* PostfixUnaryExpression */: + return checkPostfixUnaryExpression(node); + case 204 /* BinaryExpression */: + return checkBinaryExpression(node, checkMode); + case 205 /* ConditionalExpression */: + return checkConditionalExpression(node, checkMode); + case 208 /* SpreadElement */: + return checkSpreadExpression(node, checkMode); + case 210 /* OmittedExpression */: + return undefinedWideningType; + case 207 /* YieldExpression */: + return checkYieldExpression(node); + case 215 /* SyntheticExpression */: + return node.type; + case 270 /* JsxExpression */: + return checkJsxExpression(node, checkMode); + case 260 /* JsxElement */: + return checkJsxElement(node, checkMode); + case 261 /* JsxSelfClosingElement */: + return checkJsxSelfClosingElement(node, checkMode); + case 264 /* JsxFragment */: + return checkJsxFragment(node); + case 268 /* JsxAttributes */: + return checkJsxAttributes(node, checkMode); + case 262 /* JsxOpeningElement */: + ts.Debug.fail("Shouldn't ever directly check a JsxOpeningElement"); + } + return errorType; + } + // DECLARATION AND STATEMENT TYPE CHECKING + function checkTypeParameter(node) { + // Grammar Checking + if (node.expression) { + grammarErrorOnFirstToken(node.expression, ts.Diagnostics.Type_expected); + } + checkSourceElement(node.constraint); + checkSourceElement(node.default); + var typeParameter = getDeclaredTypeOfTypeParameter(getSymbolOfNode(node)); + if (!hasNonCircularBaseConstraint(typeParameter)) { + error(ts.getEffectiveConstraintOfTypeParameter(node), ts.Diagnostics.Type_parameter_0_has_a_circular_constraint, typeToString(typeParameter)); + } + if (!hasNonCircularTypeParameterDefault(typeParameter)) { + error(node.default, ts.Diagnostics.Type_parameter_0_has_a_circular_default, typeToString(typeParameter)); + } + var constraintType = getConstraintOfTypeParameter(typeParameter); + var defaultType = getDefaultFromTypeParameter(typeParameter); + if (constraintType && defaultType) { + checkTypeAssignableTo(defaultType, getTypeWithThisArgument(constraintType, defaultType), node.default, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); + } + if (produceDiagnostics) { + checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_parameter_name_cannot_be_0); + } + } + function checkParameter(node) { + // Grammar checking + // It is a SyntaxError if the Identifier "eval" or the Identifier "arguments" occurs as the + // Identifier in a PropertySetParameterList of a PropertyAssignment that is contained in strict code + // or if its FunctionBody is strict code(11.1.5). + checkGrammarDecoratorsAndModifiers(node); + checkVariableLikeDeclaration(node); + var func = ts.getContainingFunction(node); + if (ts.hasModifier(node, 92 /* ParameterPropertyModifier */)) { + if (!(func.kind === 157 /* Constructor */ && ts.nodeIsPresent(func.body))) { + error(node, ts.Diagnostics.A_parameter_property_is_only_allowed_in_a_constructor_implementation); + } + } + if (node.questionToken && ts.isBindingPattern(node.name) && func.body) { + error(node, ts.Diagnostics.A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature); + } + if (node.name && ts.isIdentifier(node.name) && (node.name.escapedText === "this" || node.name.escapedText === "new")) { + if (func.parameters.indexOf(node) !== 0) { + error(node, ts.Diagnostics.A_0_parameter_must_be_the_first_parameter, node.name.escapedText); + } + if (func.kind === 157 /* Constructor */ || func.kind === 161 /* ConstructSignature */ || func.kind === 166 /* ConstructorType */) { + error(node, ts.Diagnostics.A_constructor_cannot_have_a_this_parameter); + } + if (func.kind === 197 /* ArrowFunction */) { + error(node, ts.Diagnostics.An_arrow_function_cannot_have_a_this_parameter); + } + } + // Only check rest parameter type if it's not a binding pattern. Since binding patterns are + // not allowed in a rest parameter, we already have an error from checkGrammarParameterList. + if (node.dotDotDotToken && !ts.isBindingPattern(node.name) && !isTypeAssignableTo(getTypeOfSymbol(node.symbol), anyArrayType)) { + error(node, ts.Diagnostics.A_rest_parameter_must_be_of_an_array_type); + } + } + function checkTypePredicate(node) { + var parent = getTypePredicateParent(node); + if (!parent) { + // The parent must not be valid. + error(node, ts.Diagnostics.A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods); + return; + } + var typePredicate = getTypePredicateOfSignature(getSignatureFromDeclaration(parent)); + if (!typePredicate) { + return; + } + checkSourceElement(node.type); + var parameterName = node.parameterName; + if (ts.isThisTypePredicate(typePredicate)) { + getTypeFromThisTypeNode(parameterName); + } + else { + if (typePredicate.parameterIndex >= 0) { + if (parent.parameters[typePredicate.parameterIndex].dotDotDotToken) { + error(parameterName, ts.Diagnostics.A_type_predicate_cannot_reference_a_rest_parameter); + } + else { + var leadingError = function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type); }; + checkTypeAssignableTo(typePredicate.type, getTypeOfNode(parent.parameters[typePredicate.parameterIndex]), node.type, + /*headMessage*/ undefined, leadingError); + } + } + else if (parameterName) { + var hasReportedError = false; + for (var _i = 0, _a = parent.parameters; _i < _a.length; _i++) { + var name = _a[_i].name; + if (ts.isBindingPattern(name) && + checkIfTypePredicateVariableIsDeclaredInBindingPattern(name, parameterName, typePredicate.parameterName)) { + hasReportedError = true; + break; + } + } + if (!hasReportedError) { + error(node.parameterName, ts.Diagnostics.Cannot_find_parameter_0, typePredicate.parameterName); + } + } + } + } + function getTypePredicateParent(node) { + switch (node.parent.kind) { + case 197 /* ArrowFunction */: + case 160 /* CallSignature */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 165 /* FunctionType */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + var parent = node.parent; + if (node === parent.type) { + return parent; + } + } + } + function checkIfTypePredicateVariableIsDeclaredInBindingPattern(pattern, predicateVariableNode, predicateVariableName) { + for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (ts.isOmittedExpression(element)) { + continue; + } + var name = element.name; + if (name.kind === 72 /* Identifier */ && name.escapedText === predicateVariableName) { + error(predicateVariableNode, ts.Diagnostics.A_type_predicate_cannot_reference_element_0_in_a_binding_pattern, predicateVariableName); + return true; + } + else if (name.kind === 185 /* ArrayBindingPattern */ || name.kind === 184 /* ObjectBindingPattern */) { + if (checkIfTypePredicateVariableIsDeclaredInBindingPattern(name, predicateVariableNode, predicateVariableName)) { + return true; + } + } + } + } + function checkSignatureDeclaration(node) { + // Grammar checking + if (node.kind === 162 /* IndexSignature */) { + checkGrammarIndexSignature(node); + } + // TODO (yuisu): Remove this check in else-if when SyntaxKind.Construct is moved and ambient context is handled + else if (node.kind === 165 /* FunctionType */ || node.kind === 239 /* FunctionDeclaration */ || node.kind === 166 /* ConstructorType */ || + node.kind === 160 /* CallSignature */ || node.kind === 157 /* Constructor */ || + node.kind === 161 /* ConstructSignature */) { + checkGrammarFunctionLikeDeclaration(node); + } + var functionFlags = ts.getFunctionFlags(node); + if (!(functionFlags & 4 /* Invalid */)) { + // Async generators prior to ESNext require the __await and __asyncGenerator helpers + if ((functionFlags & 3 /* AsyncGenerator */) === 3 /* AsyncGenerator */ && languageVersion < 6 /* ESNext */) { + checkExternalEmitHelpers(node, 6144 /* AsyncGeneratorIncludes */); + } + // Async functions prior to ES2017 require the __awaiter helper + if ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */ && languageVersion < 4 /* ES2017 */) { + checkExternalEmitHelpers(node, 64 /* Awaiter */); + } + // Generator functions, Async functions, and Async Generator functions prior to + // ES2015 require the __generator helper + if ((functionFlags & 3 /* AsyncGenerator */) !== 0 /* Normal */ && languageVersion < 2 /* ES2015 */) { + checkExternalEmitHelpers(node, 128 /* Generator */); + } + } + checkTypeParameters(node.typeParameters); + ts.forEach(node.parameters, checkParameter); + // TODO(rbuckton): Should we start checking JSDoc types? + if (node.type) { + checkSourceElement(node.type); + } + if (produceDiagnostics) { + checkCollisionWithArgumentsInGeneratedCode(node); + var returnTypeNode = ts.getEffectiveReturnTypeNode(node); + if (noImplicitAny && !returnTypeNode) { + switch (node.kind) { + case 161 /* ConstructSignature */: + error(node, ts.Diagnostics.Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type); + break; + case 160 /* CallSignature */: + error(node, ts.Diagnostics.Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type); + break; + } + } + if (returnTypeNode) { + var functionFlags_1 = ts.getFunctionFlags(node); + if ((functionFlags_1 & (4 /* Invalid */ | 1 /* Generator */)) === 1 /* Generator */) { + var returnType = getTypeFromTypeNode(returnTypeNode); + if (returnType === voidType) { + error(returnTypeNode, ts.Diagnostics.A_generator_cannot_have_a_void_type_annotation); + } + else { + var generatorElementType = getIteratedTypeOfGenerator(returnType, (functionFlags_1 & 2 /* Async */) !== 0) || anyType; + var iterableIteratorInstantiation = functionFlags_1 & 2 /* Async */ + ? createAsyncIterableIteratorType(generatorElementType) // AsyncGenerator function + : createIterableIteratorType(generatorElementType); // Generator function + // Naively, one could check that IterableIterator is assignable to the return type annotation. + // However, that would not catch the error in the following case. + // + // interface BadGenerator extends Iterable, Iterator { } + // function* g(): BadGenerator { } // Iterable and Iterator have different types! + // + checkTypeAssignableTo(iterableIteratorInstantiation, returnType, returnTypeNode); + } + } + else if ((functionFlags_1 & 3 /* AsyncGenerator */) === 2 /* Async */) { + checkAsyncFunctionReturnType(node, returnTypeNode); + } + } + if (node.kind !== 162 /* IndexSignature */ && node.kind !== 289 /* JSDocFunctionType */) { + registerForUnusedIdentifiersCheck(node); + } + } + } + function checkClassForDuplicateDeclarations(node) { + var Declaration; + (function (Declaration) { + Declaration[Declaration["Getter"] = 1] = "Getter"; + Declaration[Declaration["Setter"] = 2] = "Setter"; + Declaration[Declaration["Method"] = 4] = "Method"; + Declaration[Declaration["Property"] = 3] = "Property"; + })(Declaration || (Declaration = {})); + var instanceNames = ts.createUnderscoreEscapedMap(); + var staticNames = ts.createUnderscoreEscapedMap(); + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + if (member.kind === 157 /* Constructor */) { + for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { + var param = _c[_b]; + if (ts.isParameterPropertyDeclaration(param) && !ts.isBindingPattern(param.name)) { + addName(instanceNames, param.name, param.name.escapedText, 3 /* Property */); + } + } + } + else { + var isStatic = ts.hasModifier(member, 32 /* Static */); + var names = isStatic ? staticNames : instanceNames; + var name = member.name; + var memberName = name && ts.getPropertyNameForPropertyNameNode(name); + if (name && memberName) { + switch (member.kind) { + case 158 /* GetAccessor */: + addName(names, name, memberName, 1 /* Getter */); + break; + case 159 /* SetAccessor */: + addName(names, name, memberName, 2 /* Setter */); + break; + case 154 /* PropertyDeclaration */: + addName(names, name, memberName, 3 /* Property */); + break; + case 156 /* MethodDeclaration */: + addName(names, name, memberName, 4 /* Method */); + break; + } + } + } + } + function addName(names, location, name, meaning) { + var prev = names.get(name); + if (prev) { + if (prev & 4 /* Method */) { + if (meaning !== 4 /* Method */) { + error(location, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(location)); + } + } + else if (prev & meaning) { + error(location, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(location)); + } + else { + names.set(name, prev | meaning); + } + } + else { + names.set(name, meaning); + } + } + } + /** + * Static members being set on a constructor function may conflict with built-in properties + * of Function. Esp. in ECMAScript 5 there are non-configurable and non-writable + * built-in properties. This check issues a transpile error when a class has a static + * member with the same name as a non-writable built-in property. + * + * @see http://www.ecma-international.org/ecma-262/5.1/#sec-15.3.3 + * @see http://www.ecma-international.org/ecma-262/5.1/#sec-15.3.5 + * @see http://www.ecma-international.org/ecma-262/6.0/#sec-properties-of-the-function-constructor + * @see http://www.ecma-international.org/ecma-262/6.0/#sec-function-instances + */ + function checkClassForStaticPropertyNameConflicts(node) { + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + var memberNameNode = member.name; + var isStatic = ts.hasModifier(member, 32 /* Static */); + if (isStatic && memberNameNode) { + var memberName = ts.getPropertyNameForPropertyNameNode(memberNameNode); + switch (memberName) { + case "name": + case "length": + case "caller": + case "arguments": + case "prototype": + var message = ts.Diagnostics.Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1; + var className = getNameOfSymbolAsWritten(getSymbolOfNode(node)); + error(memberNameNode, message, memberName, className); + break; + } + } + } + } + function checkObjectTypeForDuplicateDeclarations(node) { + var names = ts.createMap(); + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + if (member.kind === 153 /* PropertySignature */) { + var memberName = void 0; + var name = member.name; + switch (name.kind) { + case 10 /* StringLiteral */: + case 8 /* NumericLiteral */: + memberName = name.text; + break; + case 72 /* Identifier */: + memberName = ts.idText(name); + break; + default: + continue; + } + if (names.get(memberName)) { + error(ts.getNameOfDeclaration(member.symbol.valueDeclaration), ts.Diagnostics.Duplicate_identifier_0, memberName); + error(member.name, ts.Diagnostics.Duplicate_identifier_0, memberName); + } + else { + names.set(memberName, true); + } + } + } + } + function checkTypeForDuplicateIndexSignatures(node) { + if (node.kind === 241 /* InterfaceDeclaration */) { + var nodeSymbol = getSymbolOfNode(node); + // in case of merging interface declaration it is possible that we'll enter this check procedure several times for every declaration + // to prevent this run check only for the first declaration of a given kind + if (nodeSymbol.declarations.length > 0 && nodeSymbol.declarations[0] !== node) { + return; + } + } + // TypeScript 1.0 spec (April 2014) + // 3.7.4: An object type can contain at most one string index signature and one numeric index signature. + // 8.5: A class declaration can have at most one string index member declaration and one numeric index member declaration + var indexSymbol = getIndexSymbol(getSymbolOfNode(node)); + if (indexSymbol) { + var seenNumericIndexer = false; + var seenStringIndexer = false; + for (var _i = 0, _a = indexSymbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + var declaration = decl; + if (declaration.parameters.length === 1 && declaration.parameters[0].type) { + switch (declaration.parameters[0].type.kind) { + case 138 /* StringKeyword */: + if (!seenStringIndexer) { + seenStringIndexer = true; + } + else { + error(declaration, ts.Diagnostics.Duplicate_string_index_signature); + } + break; + case 135 /* NumberKeyword */: + if (!seenNumericIndexer) { + seenNumericIndexer = true; + } + else { + error(declaration, ts.Diagnostics.Duplicate_number_index_signature); + } + break; + } + } + } + } + } + function checkPropertyDeclaration(node) { + // Grammar checking + if (!checkGrammarDecoratorsAndModifiers(node) && !checkGrammarProperty(node)) + checkGrammarComputedPropertyName(node.name); + checkVariableLikeDeclaration(node); + } + function checkMethodDeclaration(node) { + // Grammar checking + if (!checkGrammarMethod(node)) + checkGrammarComputedPropertyName(node.name); + // Grammar checking for modifiers is done inside the function checkGrammarFunctionLikeDeclaration + checkFunctionOrMethodDeclaration(node); + // Abstract methods cannot have an implementation. + // Extra checks are to avoid reporting multiple errors relating to the "abstractness" of the node. + if (ts.hasModifier(node, 128 /* Abstract */) && node.kind === 156 /* MethodDeclaration */ && node.body) { + error(node, ts.Diagnostics.Method_0_cannot_have_an_implementation_because_it_is_marked_abstract, ts.declarationNameToString(node.name)); + } + } + function checkConstructorDeclaration(node) { + // Grammar check on signature of constructor and modifier of the constructor is done in checkSignatureDeclaration function. + checkSignatureDeclaration(node); + // Grammar check for checking only related to constructorDeclaration + if (!checkGrammarConstructorTypeParameters(node)) + checkGrammarConstructorTypeAnnotation(node); + checkSourceElement(node.body); + var symbol = getSymbolOfNode(node); + var firstDeclaration = ts.getDeclarationOfKind(symbol, node.kind); + // Only type check the symbol once + if (node === firstDeclaration) { + checkFunctionOrConstructorSymbol(symbol); + } + // exit early in the case of signature - super checks are not relevant to them + if (ts.nodeIsMissing(node.body)) { + return; + } + if (!produceDiagnostics) { + return; + } + function isInstancePropertyWithInitializer(n) { + return n.kind === 154 /* PropertyDeclaration */ && + !ts.hasModifier(n, 32 /* Static */) && + !!n.initializer; + } + // TS 1.0 spec (April 2014): 8.3.2 + // Constructors of classes with no extends clause may not contain super calls, whereas + // constructors of derived classes must contain at least one super call somewhere in their function body. + var containingClassDecl = node.parent; + if (ts.getEffectiveBaseTypeNode(containingClassDecl)) { + captureLexicalThis(node.parent, containingClassDecl); + var classExtendsNull = classDeclarationExtendsNull(containingClassDecl); + var superCall = getSuperCallInConstructor(node); + if (superCall) { + if (classExtendsNull) { + error(superCall, ts.Diagnostics.A_constructor_cannot_contain_a_super_call_when_its_class_extends_null); + } + // The first statement in the body of a constructor (excluding prologue directives) must be a super call + // if both of the following are true: + // - The containing class is a derived class. + // - The constructor declares parameter properties + // or the containing class declares instance member variables with initializers. + var superCallShouldBeFirst = ts.some(node.parent.members, isInstancePropertyWithInitializer) || + ts.some(node.parameters, function (p) { return ts.hasModifier(p, 92 /* ParameterPropertyModifier */); }); + // Skip past any prologue directives to find the first statement + // to ensure that it was a super call. + if (superCallShouldBeFirst) { + var statements = node.body.statements; + var superCallStatement = void 0; + for (var _i = 0, statements_2 = statements; _i < statements_2.length; _i++) { + var statement = statements_2[_i]; + if (statement.kind === 221 /* ExpressionStatement */ && ts.isSuperCall(statement.expression)) { + superCallStatement = statement; + break; + } + if (!ts.isPrologueDirective(statement)) { + break; + } + } + if (!superCallStatement) { + error(node, ts.Diagnostics.A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_properties_or_has_parameter_properties); + } + } + } + else if (!classExtendsNull) { + error(node, ts.Diagnostics.Constructors_for_derived_classes_must_contain_a_super_call); + } + } + } + function checkAccessorDeclaration(node) { + if (produceDiagnostics) { + // Grammar checking accessors + if (!checkGrammarFunctionLikeDeclaration(node) && !checkGrammarAccessor(node)) + checkGrammarComputedPropertyName(node.name); + checkDecorators(node); + checkSignatureDeclaration(node); + if (node.kind === 158 /* GetAccessor */) { + if (!(node.flags & 4194304 /* Ambient */) && ts.nodeIsPresent(node.body) && (node.flags & 128 /* HasImplicitReturn */)) { + if (!(node.flags & 256 /* HasExplicitReturn */)) { + error(node.name, ts.Diagnostics.A_get_accessor_must_return_a_value); + } + } + } + // Do not use hasDynamicName here, because that returns false for well known symbols. + // We want to perform checkComputedPropertyName for all computed properties, including + // well known symbols. + if (node.name.kind === 149 /* ComputedPropertyName */) { + checkComputedPropertyName(node.name); + } + if (!hasNonBindableDynamicName(node)) { + // TypeScript 1.0 spec (April 2014): 8.4.3 + // Accessors for the same member name must specify the same accessibility. + var otherKind = node.kind === 158 /* GetAccessor */ ? 159 /* SetAccessor */ : 158 /* GetAccessor */; + var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(node), otherKind); + if (otherAccessor) { + var nodeFlags = ts.getModifierFlags(node); + var otherFlags = ts.getModifierFlags(otherAccessor); + if ((nodeFlags & 28 /* AccessibilityModifier */) !== (otherFlags & 28 /* AccessibilityModifier */)) { + error(node.name, ts.Diagnostics.Getter_and_setter_accessors_do_not_agree_in_visibility); + } + if ((nodeFlags & 128 /* Abstract */) !== (otherFlags & 128 /* Abstract */)) { + error(node.name, ts.Diagnostics.Accessors_must_both_be_abstract_or_non_abstract); + } + // TypeScript 1.0 spec (April 2014): 4.5 + // If both accessors include type annotations, the specified types must be identical. + checkAccessorDeclarationTypesIdentical(node, otherAccessor, getAnnotatedAccessorType, ts.Diagnostics.get_and_set_accessor_must_have_the_same_type); + checkAccessorDeclarationTypesIdentical(node, otherAccessor, getThisTypeOfDeclaration, ts.Diagnostics.get_and_set_accessor_must_have_the_same_this_type); + } + } + var returnType = getTypeOfAccessors(getSymbolOfNode(node)); + if (node.kind === 158 /* GetAccessor */) { + checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnType); + } + } + checkSourceElement(node.body); + } + function checkAccessorDeclarationTypesIdentical(first, second, getAnnotatedType, message) { + var firstType = getAnnotatedType(first); + var secondType = getAnnotatedType(second); + if (firstType && secondType && !isTypeIdenticalTo(firstType, secondType)) { + error(first, message); + } + } + function checkMissingDeclaration(node) { + checkDecorators(node); + } + function getEffectiveTypeArguments(node, typeParameters) { + return fillMissingTypeArguments(ts.map(node.typeArguments, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJSFile(node)); + } + function checkTypeArgumentConstraints(node, typeParameters) { + var typeArguments; + var mapper; + var result = true; + for (var i = 0; i < typeParameters.length; i++) { + var constraint = getConstraintOfTypeParameter(typeParameters[i]); + if (constraint) { + if (!typeArguments) { + typeArguments = getEffectiveTypeArguments(node, typeParameters); + mapper = createTypeMapper(typeParameters, typeArguments); + } + result = result && checkTypeAssignableTo(typeArguments[i], instantiateType(constraint, mapper), node.typeArguments[i], ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); + } + } + return result; + } + function getTypeParametersForTypeReference(node) { + var type = getTypeFromTypeReference(node); + if (type !== errorType) { + var symbol = getNodeLinks(node).resolvedSymbol; + if (symbol) { + return symbol.flags & 524288 /* TypeAlias */ && getSymbolLinks(symbol).typeParameters || + (ts.getObjectFlags(type) & 4 /* Reference */ ? type.target.localTypeParameters : undefined); + } + } + return undefined; + } + function checkTypeReferenceNode(node) { + checkGrammarTypeArguments(node, node.typeArguments); + if (node.kind === 164 /* TypeReference */ && node.typeName.jsdocDotPos !== undefined && !ts.isInJSFile(node) && !ts.isInJSDoc(node)) { + grammarErrorAtPos(node, node.typeName.jsdocDotPos, 1, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments); + } + var type = getTypeFromTypeReference(node); + if (type !== errorType) { + if (node.typeArguments) { + // Do type argument local checks only if referenced type is successfully resolved + ts.forEach(node.typeArguments, checkSourceElement); + if (produceDiagnostics) { + var typeParameters = getTypeParametersForTypeReference(node); + if (typeParameters) { + checkTypeArgumentConstraints(node, typeParameters); + } + } + } + if (type.flags & 32 /* Enum */ && getNodeLinks(node).resolvedSymbol.flags & 8 /* EnumMember */) { + error(node, ts.Diagnostics.Enum_type_0_has_members_with_initializers_that_are_not_literals, typeToString(type)); + } + } + } + function getTypeArgumentConstraint(node) { + var typeReferenceNode = ts.tryCast(node.parent, ts.isTypeReferenceType); + if (!typeReferenceNode) + return undefined; + var typeParameters = getTypeParametersForTypeReference(typeReferenceNode); // TODO: GH#18217 + var constraint = getConstraintOfTypeParameter(typeParameters[typeReferenceNode.typeArguments.indexOf(node)]); + return constraint && instantiateType(constraint, createTypeMapper(typeParameters, getEffectiveTypeArguments(typeReferenceNode, typeParameters))); + } + function checkTypeQuery(node) { + getTypeFromTypeQueryNode(node); + } + function checkTypeLiteral(node) { + ts.forEach(node.members, checkSourceElement); + if (produceDiagnostics) { + var type = getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node); + checkIndexConstraints(type); + checkTypeForDuplicateIndexSignatures(node); + checkObjectTypeForDuplicateDeclarations(node); + } + } + function checkArrayType(node) { + checkSourceElement(node.elementType); + } + function checkTupleType(node) { + var elementTypes = node.elementTypes; + var seenOptionalElement = false; + for (var i = 0; i < elementTypes.length; i++) { + var e = elementTypes[i]; + if (e.kind === 172 /* RestType */) { + if (i !== elementTypes.length - 1) { + grammarErrorOnNode(e, ts.Diagnostics.A_rest_element_must_be_last_in_a_tuple_type); + break; + } + if (!isArrayType(getTypeFromTypeNode(e))) { + error(e, ts.Diagnostics.A_rest_element_type_must_be_an_array_type); + } + } + else if (e.kind === 171 /* OptionalType */) { + seenOptionalElement = true; + } + else if (seenOptionalElement) { + grammarErrorOnNode(e, ts.Diagnostics.A_required_element_cannot_follow_an_optional_element); + break; + } + } + checkGrammarForDisallowedTrailingComma(node.elementTypes); + ts.forEach(node.elementTypes, checkSourceElement); + } + function checkUnionOrIntersectionType(node) { + ts.forEach(node.types, checkSourceElement); + } + function checkIndexedAccessIndexType(type, accessNode) { + if (!(type.flags & 8388608 /* IndexedAccess */)) { + return type; + } + // Check if the index type is assignable to 'keyof T' for the object type. + var objectType = type.objectType; + var indexType = type.indexType; + if (isTypeAssignableTo(indexType, getIndexType(objectType, /*stringsOnly*/ false))) { + if (accessNode.kind === 190 /* ElementAccessExpression */ && ts.isAssignmentTarget(accessNode) && + ts.getObjectFlags(objectType) & 32 /* Mapped */ && getMappedTypeModifiers(objectType) & 1 /* IncludeReadonly */) { + error(accessNode, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(objectType)); + } + return type; + } + // Check if we're indexing with a numeric type and if either object or index types + // is a generic type with a constraint that has a numeric index signature. + if (getIndexInfoOfType(getApparentType(objectType), 1 /* Number */) && isTypeAssignableToKind(indexType, 296 /* NumberLike */)) { + return type; + } + error(accessNode, ts.Diagnostics.Type_0_cannot_be_used_to_index_type_1, typeToString(indexType), typeToString(objectType)); + return type; + } + function checkIndexedAccessType(node) { + checkSourceElement(node.objectType); + checkSourceElement(node.indexType); + checkIndexedAccessIndexType(getTypeFromIndexedAccessTypeNode(node), node); + } + function checkMappedType(node) { + checkSourceElement(node.typeParameter); + checkSourceElement(node.type); + if (!node.type) { + reportImplicitAny(node, anyType); + } + var type = getTypeFromMappedTypeNode(node); + var constraintType = getConstraintTypeFromMappedType(type); + checkTypeAssignableTo(constraintType, keyofConstraintType, ts.getEffectiveConstraintOfTypeParameter(node.typeParameter)); + } + function checkThisType(node) { + getTypeFromThisTypeNode(node); + } + function checkTypeOperator(node) { + checkGrammarTypeOperatorNode(node); + checkSourceElement(node.type); + } + function checkConditionalType(node) { + ts.forEachChild(node, checkSourceElement); + } + function checkInferType(node) { + if (!ts.findAncestor(node, function (n) { return n.parent && n.parent.kind === 175 /* ConditionalType */ && n.parent.extendsType === n; })) { + grammarErrorOnNode(node, ts.Diagnostics.infer_declarations_are_only_permitted_in_the_extends_clause_of_a_conditional_type); + } + checkSourceElement(node.typeParameter); + registerForUnusedIdentifiersCheck(node); + } + function checkImportType(node) { + checkSourceElement(node.argument); + getTypeFromTypeNode(node); + } + function isPrivateWithinAmbient(node) { + return ts.hasModifier(node, 8 /* Private */) && !!(node.flags & 4194304 /* Ambient */); + } + function getEffectiveDeclarationFlags(n, flagsToCheck) { + var flags = ts.getCombinedModifierFlags(n); + // children of classes (even ambient classes) should not be marked as ambient or export + // because those flags have no useful semantics there. + if (n.parent.kind !== 241 /* InterfaceDeclaration */ && + n.parent.kind !== 240 /* ClassDeclaration */ && + n.parent.kind !== 209 /* ClassExpression */ && + n.flags & 4194304 /* Ambient */) { + if (!(flags & 2 /* Ambient */) && !(ts.isModuleBlock(n.parent) && ts.isModuleDeclaration(n.parent.parent) && ts.isGlobalScopeAugmentation(n.parent.parent))) { + // It is nested in an ambient context, which means it is automatically exported + flags |= 1 /* Export */; + } + flags |= 2 /* Ambient */; + } + return flags & flagsToCheck; + } + function checkFunctionOrConstructorSymbol(symbol) { + if (!produceDiagnostics) { + return; + } + function getCanonicalOverload(overloads, implementation) { + // Consider the canonical set of flags to be the flags of the bodyDeclaration or the first declaration + // Error on all deviations from this canonical set of flags + // The caveat is that if some overloads are defined in lib.d.ts, we don't want to + // report the errors on those. To achieve this, we will say that the implementation is + // the canonical signature only if it is in the same container as the first overload + var implementationSharesContainerWithFirstOverload = implementation !== undefined && implementation.parent === overloads[0].parent; + return implementationSharesContainerWithFirstOverload ? implementation : overloads[0]; + } + function checkFlagAgreementBetweenOverloads(overloads, implementation, flagsToCheck, someOverloadFlags, allOverloadFlags) { + // Error if some overloads have a flag that is not shared by all overloads. To find the + // deviations, we XOR someOverloadFlags with allOverloadFlags + var someButNotAllOverloadFlags = someOverloadFlags ^ allOverloadFlags; + if (someButNotAllOverloadFlags !== 0) { + var canonicalFlags_1 = getEffectiveDeclarationFlags(getCanonicalOverload(overloads, implementation), flagsToCheck); + ts.forEach(overloads, function (o) { + var deviation = getEffectiveDeclarationFlags(o, flagsToCheck) ^ canonicalFlags_1; + if (deviation & 1 /* Export */) { + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_exported_or_non_exported); + } + else if (deviation & 2 /* Ambient */) { + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_ambient_or_non_ambient); + } + else if (deviation & (8 /* Private */ | 16 /* Protected */)) { + error(ts.getNameOfDeclaration(o) || o, ts.Diagnostics.Overload_signatures_must_all_be_public_private_or_protected); + } + else if (deviation & 128 /* Abstract */) { + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_abstract_or_non_abstract); + } + }); + } + } + function checkQuestionTokenAgreementBetweenOverloads(overloads, implementation, someHaveQuestionToken, allHaveQuestionToken) { + if (someHaveQuestionToken !== allHaveQuestionToken) { + var canonicalHasQuestionToken_1 = ts.hasQuestionToken(getCanonicalOverload(overloads, implementation)); + ts.forEach(overloads, function (o) { + var deviation = ts.hasQuestionToken(o) !== canonicalHasQuestionToken_1; + if (deviation) { + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_optional_or_required); + } + }); + } + } + var flagsToCheck = 1 /* Export */ | 2 /* Ambient */ | 8 /* Private */ | 16 /* Protected */ | 128 /* Abstract */; + var someNodeFlags = 0 /* None */; + var allNodeFlags = flagsToCheck; + var someHaveQuestionToken = false; + var allHaveQuestionToken = true; + var hasOverloads = false; + var bodyDeclaration; + var lastSeenNonAmbientDeclaration; + var previousDeclaration; + var declarations = symbol.declarations; + var isConstructor = (symbol.flags & 16384 /* Constructor */) !== 0; + function reportImplementationExpectedError(node) { + if (node.name && ts.nodeIsMissing(node.name)) { + return; + } + var seen = false; + var subsequentNode = ts.forEachChild(node.parent, function (c) { + if (seen) { + return c; + } + else { + seen = c === node; + } + }); + // We may be here because of some extra nodes between overloads that could not be parsed into a valid node. + // In this case the subsequent node is not really consecutive (.pos !== node.end), and we must ignore it here. + if (subsequentNode && subsequentNode.pos === node.end) { + if (subsequentNode.kind === node.kind) { + var errorNode_1 = subsequentNode.name || subsequentNode; + // TODO: GH#17345: These are methods, so handle computed name case. (`Always allowing computed property names is *not* the correct behavior!) + var subsequentName = subsequentNode.name; + if (node.name && subsequentName && + (ts.isComputedPropertyName(node.name) && ts.isComputedPropertyName(subsequentName) || + !ts.isComputedPropertyName(node.name) && !ts.isComputedPropertyName(subsequentName) && ts.getEscapedTextOfIdentifierOrLiteral(node.name) === ts.getEscapedTextOfIdentifierOrLiteral(subsequentName))) { + var reportError = (node.kind === 156 /* MethodDeclaration */ || node.kind === 155 /* MethodSignature */) && + ts.hasModifier(node, 32 /* Static */) !== ts.hasModifier(subsequentNode, 32 /* Static */); + // we can get here in two cases + // 1. mixed static and instance class members + // 2. something with the same name was defined before the set of overloads that prevents them from merging + // here we'll report error only for the first case since for second we should already report error in binder + if (reportError) { + var diagnostic = ts.hasModifier(node, 32 /* Static */) ? ts.Diagnostics.Function_overload_must_be_static : ts.Diagnostics.Function_overload_must_not_be_static; + error(errorNode_1, diagnostic); + } + return; + } + else if (ts.nodeIsPresent(subsequentNode.body)) { + error(errorNode_1, ts.Diagnostics.Function_implementation_name_must_be_0, ts.declarationNameToString(node.name)); + return; + } + } + } + var errorNode = node.name || node; + if (isConstructor) { + error(errorNode, ts.Diagnostics.Constructor_implementation_is_missing); + } + else { + // Report different errors regarding non-consecutive blocks of declarations depending on whether + // the node in question is abstract. + if (ts.hasModifier(node, 128 /* Abstract */)) { + error(errorNode, ts.Diagnostics.All_declarations_of_an_abstract_method_must_be_consecutive); + } + else { + error(errorNode, ts.Diagnostics.Function_implementation_is_missing_or_not_immediately_following_the_declaration); + } + } + } + var duplicateFunctionDeclaration = false; + var multipleConstructorImplementation = false; + for (var _i = 0, declarations_4 = declarations; _i < declarations_4.length; _i++) { + var current = declarations_4[_i]; + var node = current; + var inAmbientContext = node.flags & 4194304 /* Ambient */; + var inAmbientContextOrInterface = node.parent.kind === 241 /* InterfaceDeclaration */ || node.parent.kind === 168 /* TypeLiteral */ || inAmbientContext; + if (inAmbientContextOrInterface) { + // check if declarations are consecutive only if they are non-ambient + // 1. ambient declarations can be interleaved + // i.e. this is legal + // declare function foo(); + // declare function bar(); + // declare function foo(); + // 2. mixing ambient and non-ambient declarations is a separate error that will be reported - do not want to report an extra one + previousDeclaration = undefined; + } + if (node.kind === 239 /* FunctionDeclaration */ || node.kind === 156 /* MethodDeclaration */ || node.kind === 155 /* MethodSignature */ || node.kind === 157 /* Constructor */) { + var currentNodeFlags = getEffectiveDeclarationFlags(node, flagsToCheck); + someNodeFlags |= currentNodeFlags; + allNodeFlags &= currentNodeFlags; + someHaveQuestionToken = someHaveQuestionToken || ts.hasQuestionToken(node); + allHaveQuestionToken = allHaveQuestionToken && ts.hasQuestionToken(node); + if (ts.nodeIsPresent(node.body) && bodyDeclaration) { + if (isConstructor) { + multipleConstructorImplementation = true; + } + else { + duplicateFunctionDeclaration = true; + } + } + else if (previousDeclaration && previousDeclaration.parent === node.parent && previousDeclaration.end !== node.pos) { + reportImplementationExpectedError(previousDeclaration); + } + if (ts.nodeIsPresent(node.body)) { + if (!bodyDeclaration) { + bodyDeclaration = node; + } + } + else { + hasOverloads = true; + } + previousDeclaration = node; + if (!inAmbientContextOrInterface) { + lastSeenNonAmbientDeclaration = node; + } + } + } + if (multipleConstructorImplementation) { + ts.forEach(declarations, function (declaration) { + error(declaration, ts.Diagnostics.Multiple_constructor_implementations_are_not_allowed); + }); + } + if (duplicateFunctionDeclaration) { + ts.forEach(declarations, function (declaration) { + error(ts.getNameOfDeclaration(declaration), ts.Diagnostics.Duplicate_function_implementation); + }); + } + // Abstract methods can't have an implementation -- in particular, they don't need one. + if (lastSeenNonAmbientDeclaration && !lastSeenNonAmbientDeclaration.body && + !ts.hasModifier(lastSeenNonAmbientDeclaration, 128 /* Abstract */) && !lastSeenNonAmbientDeclaration.questionToken) { + reportImplementationExpectedError(lastSeenNonAmbientDeclaration); + } + if (hasOverloads) { + checkFlagAgreementBetweenOverloads(declarations, bodyDeclaration, flagsToCheck, someNodeFlags, allNodeFlags); + checkQuestionTokenAgreementBetweenOverloads(declarations, bodyDeclaration, someHaveQuestionToken, allHaveQuestionToken); + if (bodyDeclaration) { + var signatures = getSignaturesOfSymbol(symbol); + var bodySignature = getSignatureFromDeclaration(bodyDeclaration); + for (var _a = 0, signatures_6 = signatures; _a < signatures_6.length; _a++) { + var signature = signatures_6[_a]; + if (!isImplementationCompatibleWithOverload(bodySignature, signature)) { + error(signature.declaration, ts.Diagnostics.Overload_signature_is_not_compatible_with_function_implementation); + break; + } + } + } + } + } + var DeclarationSpaces; + (function (DeclarationSpaces) { + DeclarationSpaces[DeclarationSpaces["None"] = 0] = "None"; + DeclarationSpaces[DeclarationSpaces["ExportValue"] = 1] = "ExportValue"; + DeclarationSpaces[DeclarationSpaces["ExportType"] = 2] = "ExportType"; + DeclarationSpaces[DeclarationSpaces["ExportNamespace"] = 4] = "ExportNamespace"; + })(DeclarationSpaces || (DeclarationSpaces = {})); + function checkExportsOnMergedDeclarations(node) { + if (!produceDiagnostics) { + return; + } + // if localSymbol is defined on node then node itself is exported - check is required + var symbol = node.localSymbol; + if (!symbol) { + // local symbol is undefined => this declaration is non-exported. + // however symbol might contain other declarations that are exported + symbol = getSymbolOfNode(node); + if (!symbol.exportSymbol) { + // this is a pure local symbol (all declarations are non-exported) - no need to check anything + return; + } + } + // run the check only for the first declaration in the list + if (ts.getDeclarationOfKind(symbol, node.kind) !== node) { + return; + } + var exportedDeclarationSpaces = 0 /* None */; + var nonExportedDeclarationSpaces = 0 /* None */; + var defaultExportedDeclarationSpaces = 0 /* None */; + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var d = _a[_i]; + var declarationSpaces = getDeclarationSpaces(d); + var effectiveDeclarationFlags = getEffectiveDeclarationFlags(d, 1 /* Export */ | 512 /* Default */); + if (effectiveDeclarationFlags & 1 /* Export */) { + if (effectiveDeclarationFlags & 512 /* Default */) { + defaultExportedDeclarationSpaces |= declarationSpaces; + } + else { + exportedDeclarationSpaces |= declarationSpaces; + } + } + else { + nonExportedDeclarationSpaces |= declarationSpaces; + } + } + // Spaces for anything not declared a 'default export'. + var nonDefaultExportedDeclarationSpaces = exportedDeclarationSpaces | nonExportedDeclarationSpaces; + var commonDeclarationSpacesForExportsAndLocals = exportedDeclarationSpaces & nonExportedDeclarationSpaces; + var commonDeclarationSpacesForDefaultAndNonDefault = defaultExportedDeclarationSpaces & nonDefaultExportedDeclarationSpaces; + if (commonDeclarationSpacesForExportsAndLocals || commonDeclarationSpacesForDefaultAndNonDefault) { + // declaration spaces for exported and non-exported declarations intersect + for (var _b = 0, _c = symbol.declarations; _b < _c.length; _b++) { + var d = _c[_b]; + var declarationSpaces = getDeclarationSpaces(d); + var name = ts.getNameOfDeclaration(d); + // Only error on the declarations that contributed to the intersecting spaces. + if (declarationSpaces & commonDeclarationSpacesForDefaultAndNonDefault) { + error(name, ts.Diagnostics.Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead, ts.declarationNameToString(name)); + } + else if (declarationSpaces & commonDeclarationSpacesForExportsAndLocals) { + error(name, ts.Diagnostics.Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local, ts.declarationNameToString(name)); + } + } + } + function getDeclarationSpaces(decl) { + var d = decl; + switch (d.kind) { + case 241 /* InterfaceDeclaration */: + case 242 /* TypeAliasDeclaration */: + // A jsdoc typedef and callback are, by definition, type aliases + case 304 /* JSDocTypedefTag */: + case 297 /* JSDocCallbackTag */: + return 2 /* ExportType */; + case 244 /* ModuleDeclaration */: + return ts.isAmbientModule(d) || ts.getModuleInstanceState(d) !== 0 /* NonInstantiated */ + ? 4 /* ExportNamespace */ | 1 /* ExportValue */ + : 4 /* ExportNamespace */; + case 240 /* ClassDeclaration */: + case 243 /* EnumDeclaration */: + return 2 /* ExportType */ | 1 /* ExportValue */; + case 279 /* SourceFile */: + return 2 /* ExportType */ | 1 /* ExportValue */ | 4 /* ExportNamespace */; + case 254 /* ExportAssignment */: + // Export assigned entity name expressions act as aliases and should fall through, otherwise they export values + if (!ts.isEntityNameExpression(d.expression)) { + return 1 /* ExportValue */; + } + d = d.expression; + /* falls through */ + // The below options all declare an Alias, which is allowed to merge with other values within the importing module + case 248 /* ImportEqualsDeclaration */: + case 251 /* NamespaceImport */: + case 250 /* ImportClause */: + var result_4 = 0 /* None */; + var target = resolveAlias(getSymbolOfNode(d)); + ts.forEach(target.declarations, function (d) { result_4 |= getDeclarationSpaces(d); }); + return result_4; + case 237 /* VariableDeclaration */: + case 186 /* BindingElement */: + case 239 /* FunctionDeclaration */: + case 253 /* ImportSpecifier */: // https://github.com/Microsoft/TypeScript/pull/7591 + return 1 /* ExportValue */; + default: + return ts.Debug.fail(ts.Debug.showSyntaxKind(d)); + } + } + } + function getAwaitedTypeOfPromise(type, errorNode, diagnosticMessage) { + var promisedType = getPromisedTypeOfPromise(type, errorNode); + return promisedType && getAwaitedType(promisedType, errorNode, diagnosticMessage); + } + /** + * Gets the "promised type" of a promise. + * @param type The type of the promise. + * @remarks The "promised type" of a type is the type of the "value" parameter of the "onfulfilled" callback. + */ + function getPromisedTypeOfPromise(promise, errorNode) { + // + // { // promise + // then( // thenFunction + // onfulfilled: ( // onfulfilledParameterType + // value: T // valueParameterType + // ) => any + // ): any; + // } + // + if (isTypeAny(promise)) { + return undefined; + } + var typeAsPromise = promise; + if (typeAsPromise.promisedTypeOfPromise) { + return typeAsPromise.promisedTypeOfPromise; + } + if (isReferenceToType(promise, getGlobalPromiseType(/*reportErrors*/ false))) { + return typeAsPromise.promisedTypeOfPromise = promise.typeArguments[0]; + } + var thenFunction = getTypeOfPropertyOfType(promise, "then"); // TODO: GH#18217 + if (isTypeAny(thenFunction)) { + return undefined; + } + var thenSignatures = thenFunction ? getSignaturesOfType(thenFunction, 0 /* Call */) : ts.emptyArray; + if (thenSignatures.length === 0) { + if (errorNode) { + error(errorNode, ts.Diagnostics.A_promise_must_have_a_then_method); + } + return undefined; + } + var onfulfilledParameterType = getTypeWithFacts(getUnionType(ts.map(thenSignatures, getTypeOfFirstParameterOfSignature)), 2097152 /* NEUndefinedOrNull */); + if (isTypeAny(onfulfilledParameterType)) { + return undefined; + } + var onfulfilledParameterSignatures = getSignaturesOfType(onfulfilledParameterType, 0 /* Call */); + if (onfulfilledParameterSignatures.length === 0) { + if (errorNode) { + error(errorNode, ts.Diagnostics.The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback); + } + return undefined; + } + return typeAsPromise.promisedTypeOfPromise = getUnionType(ts.map(onfulfilledParameterSignatures, getTypeOfFirstParameterOfSignature), 2 /* Subtype */); + } + /** + * Gets the "awaited type" of a type. + * @param type The type to await. + * @remarks The "awaited type" of an expression is its "promised type" if the expression is a + * Promise-like type; otherwise, it is the type of the expression. This is used to reflect + * The runtime behavior of the `await` keyword. + */ + function checkAwaitedType(type, errorNode, diagnosticMessage) { + return getAwaitedType(type, errorNode, diagnosticMessage) || errorType; + } + function getAwaitedType(type, errorNode, diagnosticMessage) { + var typeAsAwaitable = type; + if (typeAsAwaitable.awaitedTypeOfType) { + return typeAsAwaitable.awaitedTypeOfType; + } + if (isTypeAny(type)) { + return typeAsAwaitable.awaitedTypeOfType = type; + } + if (type.flags & 1048576 /* Union */) { + var types = void 0; + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var constituentType = _a[_i]; + types = ts.append(types, getAwaitedType(constituentType, errorNode, diagnosticMessage)); + } + if (!types) { + return undefined; + } + return typeAsAwaitable.awaitedTypeOfType = getUnionType(types); + } + var promisedType = getPromisedTypeOfPromise(type); + if (promisedType) { + if (type.id === promisedType.id || awaitedTypeStack.indexOf(promisedType.id) >= 0) { + // Verify that we don't have a bad actor in the form of a promise whose + // promised type is the same as the promise type, or a mutually recursive + // promise. If so, we return undefined as we cannot guess the shape. If this + // were the actual case in the JavaScript, this Promise would never resolve. + // + // An example of a bad actor with a singly-recursive promise type might + // be: + // + // interface BadPromise { + // then( + // onfulfilled: (value: BadPromise) => any, + // onrejected: (error: any) => any): BadPromise; + // } + // The above interface will pass the PromiseLike check, and return a + // promised type of `BadPromise`. Since this is a self reference, we + // don't want to keep recursing ad infinitum. + // + // An example of a bad actor in the form of a mutually-recursive + // promise type might be: + // + // interface BadPromiseA { + // then( + // onfulfilled: (value: BadPromiseB) => any, + // onrejected: (error: any) => any): BadPromiseB; + // } + // + // interface BadPromiseB { + // then( + // onfulfilled: (value: BadPromiseA) => any, + // onrejected: (error: any) => any): BadPromiseA; + // } + // + if (errorNode) { + error(errorNode, ts.Diagnostics.Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method); + } + return undefined; + } + // Keep track of the type we're about to unwrap to avoid bad recursive promise types. + // See the comments above for more information. + awaitedTypeStack.push(type.id); + var awaitedType = getAwaitedType(promisedType, errorNode, diagnosticMessage); + awaitedTypeStack.pop(); + if (!awaitedType) { + return undefined; + } + return typeAsAwaitable.awaitedTypeOfType = awaitedType; + } + // The type was not a promise, so it could not be unwrapped any further. + // As long as the type does not have a callable "then" property, it is + // safe to return the type; otherwise, an error will be reported in + // the call to getNonThenableType and we will return undefined. + // + // An example of a non-promise "thenable" might be: + // + // await { then(): void {} } + // + // The "thenable" does not match the minimal definition for a promise. When + // a Promise/A+-compatible or ES6 promise tries to adopt this value, the promise + // will never settle. We treat this as an error to help flag an early indicator + // of a runtime problem. If the user wants to return this value from an async + // function, they would need to wrap it in some other value. If they want it to + // be treated as a promise, they can cast to . + var thenFunction = getTypeOfPropertyOfType(type, "then"); + if (thenFunction && getSignaturesOfType(thenFunction, 0 /* Call */).length > 0) { + if (errorNode) { + if (!diagnosticMessage) + return ts.Debug.fail(); + error(errorNode, diagnosticMessage); + } + return undefined; + } + return typeAsAwaitable.awaitedTypeOfType = type; + } + /** + * Checks the return type of an async function to ensure it is a compatible + * Promise implementation. + * + * This checks that an async function has a valid Promise-compatible return type. + * An async function has a valid Promise-compatible return type if the resolved value + * of the return type has a construct signature that takes in an `initializer` function + * that in turn supplies a `resolve` function as one of its arguments and results in an + * object with a callable `then` signature. + * + * @param node The signature to check + */ + function checkAsyncFunctionReturnType(node, returnTypeNode) { + // As part of our emit for an async function, we will need to emit the entity name of + // the return type annotation as an expression. To meet the necessary runtime semantics + // for __awaiter, we must also check that the type of the declaration (e.g. the static + // side or "constructor" of the promise type) is compatible `PromiseConstructorLike`. + // + // An example might be (from lib.es6.d.ts): + // + // interface Promise { ... } + // interface PromiseConstructor { + // new (...): Promise; + // } + // declare var Promise: PromiseConstructor; + // + // When an async function declares a return type annotation of `Promise`, we + // need to get the type of the `Promise` variable declaration above, which would + // be `PromiseConstructor`. + // + // The same case applies to a class: + // + // declare class Promise { + // constructor(...); + // then(...): Promise; + // } + // + var returnType = getTypeFromTypeNode(returnTypeNode); + if (languageVersion >= 2 /* ES2015 */) { + if (returnType === errorType) { + return; + } + var globalPromiseType = getGlobalPromiseType(/*reportErrors*/ true); + if (globalPromiseType !== emptyGenericType && !isReferenceToType(returnType, globalPromiseType)) { + // The promise type was not a valid type reference to the global promise type, so we + // report an error and return the unknown type. + error(returnTypeNode, ts.Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type); + return; + } + } + else { + // Always mark the type node as referenced if it points to a value + markTypeNodeAsReferenced(returnTypeNode); + if (returnType === errorType) { + return; + } + var promiseConstructorName = ts.getEntityNameFromTypeNode(returnTypeNode); + if (promiseConstructorName === undefined) { + error(returnTypeNode, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, typeToString(returnType)); + return; + } + var promiseConstructorSymbol = resolveEntityName(promiseConstructorName, 67220415 /* Value */, /*ignoreErrors*/ true); + var promiseConstructorType = promiseConstructorSymbol ? getTypeOfSymbol(promiseConstructorSymbol) : errorType; + if (promiseConstructorType === errorType) { + if (promiseConstructorName.kind === 72 /* Identifier */ && promiseConstructorName.escapedText === "Promise" && getTargetType(returnType) === getGlobalPromiseType(/*reportErrors*/ false)) { + error(returnTypeNode, ts.Diagnostics.An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option); + } + else { + error(returnTypeNode, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, ts.entityNameToString(promiseConstructorName)); + } + return; + } + var globalPromiseConstructorLikeType = getGlobalPromiseConstructorLikeType(/*reportErrors*/ true); + if (globalPromiseConstructorLikeType === emptyObjectType) { + // If we couldn't resolve the global PromiseConstructorLike type we cannot verify + // compatibility with __awaiter. + error(returnTypeNode, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, ts.entityNameToString(promiseConstructorName)); + return; + } + if (!checkTypeAssignableTo(promiseConstructorType, globalPromiseConstructorLikeType, returnTypeNode, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value)) { + return; + } + // Verify there is no local declaration that could collide with the promise constructor. + var rootName = promiseConstructorName && getFirstIdentifier(promiseConstructorName); + var collidingSymbol = getSymbol(node.locals, rootName.escapedText, 67220415 /* Value */); + if (collidingSymbol) { + error(collidingSymbol.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, ts.idText(rootName), ts.entityNameToString(promiseConstructorName)); + return; + } + } + checkAwaitedType(returnType, node, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); + } + /** Check a decorator */ + function checkDecorator(node) { + var signature = getResolvedSignature(node); + var returnType = getReturnTypeOfSignature(signature); + if (returnType.flags & 1 /* Any */) { + return; + } + var expectedReturnType; + var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); + var errorInfo; + switch (node.parent.kind) { + case 240 /* ClassDeclaration */: + var classSymbol = getSymbolOfNode(node.parent); + var classConstructorType = getTypeOfSymbol(classSymbol); + expectedReturnType = getUnionType([classConstructorType, voidType]); + break; + case 151 /* Parameter */: + expectedReturnType = voidType; + errorInfo = ts.chainDiagnosticMessages( + /*details*/ undefined, ts.Diagnostics.The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any); + break; + case 154 /* PropertyDeclaration */: + expectedReturnType = voidType; + errorInfo = ts.chainDiagnosticMessages( + /*details*/ undefined, ts.Diagnostics.The_return_type_of_a_property_decorator_function_must_be_either_void_or_any); + break; + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + var methodType = getTypeOfNode(node.parent); + var descriptorType = createTypedPropertyDescriptorType(methodType); + expectedReturnType = getUnionType([descriptorType, voidType]); + break; + default: + return ts.Debug.fail(); + } + checkTypeAssignableTo(returnType, expectedReturnType, node, headMessage, function () { return errorInfo; }); + } + /** + * If a TypeNode can be resolved to a value symbol imported from an external module, it is + * marked as referenced to prevent import elision. + */ + function markTypeNodeAsReferenced(node) { + markEntityNameOrEntityExpressionAsReference(node && ts.getEntityNameFromTypeNode(node)); + } + function markEntityNameOrEntityExpressionAsReference(typeName) { + if (!typeName) + return; + var rootName = getFirstIdentifier(typeName); + var meaning = (typeName.kind === 72 /* Identifier */ ? 67897832 /* Type */ : 1920 /* Namespace */) | 2097152 /* Alias */; + var rootSymbol = resolveName(rootName, rootName.escapedText, meaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isRefernce*/ true); + if (rootSymbol + && rootSymbol.flags & 2097152 /* Alias */ + && symbolIsValue(rootSymbol) + && !isConstEnumOrConstEnumOnlyModule(resolveAlias(rootSymbol))) { + markAliasSymbolAsReferenced(rootSymbol); + } + } + /** + * This function marks the type used for metadata decorator as referenced if it is import + * from external module. + * This is different from markTypeNodeAsReferenced because it tries to simplify type nodes in + * union and intersection type + * @param node + */ + function markDecoratorMedataDataTypeNodeAsReferenced(node) { + var entityName = getEntityNameForDecoratorMetadata(node); + if (entityName && ts.isEntityName(entityName)) { + markEntityNameOrEntityExpressionAsReference(entityName); + } + } + function getEntityNameForDecoratorMetadata(node) { + if (node) { + switch (node.kind) { + case 174 /* IntersectionType */: + case 173 /* UnionType */: + return getEntityNameForDecoratorMetadataFromTypeList(node.types); + case 175 /* ConditionalType */: + return getEntityNameForDecoratorMetadataFromTypeList([node.trueType, node.falseType]); + case 177 /* ParenthesizedType */: + return getEntityNameForDecoratorMetadata(node.type); + case 164 /* TypeReference */: + return node.typeName; + } + } + } + function getEntityNameForDecoratorMetadataFromTypeList(types) { + var commonEntityName; + for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { + var typeNode = types_16[_i]; + while (typeNode.kind === 177 /* ParenthesizedType */) { + typeNode = typeNode.type; // Skip parens if need be + } + if (typeNode.kind === 132 /* NeverKeyword */) { + continue; // Always elide `never` from the union/intersection if possible + } + if (!strictNullChecks && (typeNode.kind === 96 /* NullKeyword */ || typeNode.kind === 141 /* UndefinedKeyword */)) { + continue; // Elide null and undefined from unions for metadata, just like what we did prior to the implementation of strict null checks + } + var individualEntityName = getEntityNameForDecoratorMetadata(typeNode); + if (!individualEntityName) { + // Individual is something like string number + // So it would be serialized to either that type or object + // Safe to return here + return undefined; + } + if (commonEntityName) { + // Note this is in sync with the transformation that happens for type node. + // Keep this in sync with serializeUnionOrIntersectionType + // Verify if they refer to same entity and is identifier + // return undefined if they dont match because we would emit object + if (!ts.isIdentifier(commonEntityName) || + !ts.isIdentifier(individualEntityName) || + commonEntityName.escapedText !== individualEntityName.escapedText) { + return undefined; + } + } + else { + commonEntityName = individualEntityName; + } + } + return commonEntityName; + } + function getParameterTypeNodeForDecoratorCheck(node) { + var typeNode = ts.getEffectiveTypeAnnotationNode(node); + return ts.isRestParameter(node) ? ts.getRestParameterElementType(typeNode) : typeNode; + } + /** Check the decorators of a node */ + function checkDecorators(node) { + if (!node.decorators) { + return; + } + // skip this check for nodes that cannot have decorators. These should have already had an error reported by + // checkGrammarDecorators. + if (!ts.nodeCanBeDecorated(node, node.parent, node.parent.parent)) { + return; + } + if (!compilerOptions.experimentalDecorators) { + error(node, ts.Diagnostics.Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_to_remove_this_warning); + } + var firstDecorator = node.decorators[0]; + checkExternalEmitHelpers(firstDecorator, 8 /* Decorate */); + if (node.kind === 151 /* Parameter */) { + checkExternalEmitHelpers(firstDecorator, 32 /* Param */); + } + if (compilerOptions.emitDecoratorMetadata) { + checkExternalEmitHelpers(firstDecorator, 16 /* Metadata */); + // we only need to perform these checks if we are emitting serialized type metadata for the target of a decorator. + switch (node.kind) { + case 240 /* ClassDeclaration */: + var constructor = ts.getFirstConstructorWithBody(node); + if (constructor) { + for (var _i = 0, _a = constructor.parameters; _i < _a.length; _i++) { + var parameter = _a[_i]; + markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); + } + } + break; + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + var otherKind = node.kind === 158 /* GetAccessor */ ? 159 /* SetAccessor */ : 158 /* GetAccessor */; + var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(node), otherKind); + markDecoratorMedataDataTypeNodeAsReferenced(getAnnotatedAccessorTypeNode(node) || otherAccessor && getAnnotatedAccessorTypeNode(otherAccessor)); + break; + case 156 /* MethodDeclaration */: + for (var _b = 0, _c = node.parameters; _b < _c.length; _b++) { + var parameter = _c[_b]; + markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); + } + markDecoratorMedataDataTypeNodeAsReferenced(ts.getEffectiveReturnTypeNode(node)); + break; + case 154 /* PropertyDeclaration */: + markDecoratorMedataDataTypeNodeAsReferenced(ts.getEffectiveTypeAnnotationNode(node)); + break; + case 151 /* Parameter */: + markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(node)); + var containingSignature = node.parent; + for (var _d = 0, _e = containingSignature.parameters; _d < _e.length; _d++) { + var parameter = _e[_d]; + markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); + } + break; + } + } + ts.forEach(node.decorators, checkDecorator); + } + function checkFunctionDeclaration(node) { + if (produceDiagnostics) { + checkFunctionOrMethodDeclaration(node); + checkGrammarForGenerator(node); + checkCollisionWithRequireExportsInGeneratedCode(node, node.name); + checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); + } + } + function checkJSDocTypeAliasTag(node) { + if (!node.typeExpression) { + // If the node had `@property` tags, `typeExpression` would have been set to the first property tag. + error(node.name, ts.Diagnostics.JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags); + } + if (node.name) { + checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_alias_name_cannot_be_0); + } + checkSourceElement(node.typeExpression); + } + function checkJSDocTemplateTag(node) { + checkSourceElement(node.constraint); + for (var _i = 0, _a = node.typeParameters; _i < _a.length; _i++) { + var tp = _a[_i]; + checkSourceElement(tp); + } + } + function checkJSDocTypeTag(node) { + checkSourceElement(node.typeExpression); + } + function checkJSDocParameterTag(node) { + checkSourceElement(node.typeExpression); + if (!ts.getParameterSymbolFromJSDoc(node)) { + var decl = ts.getHostSignatureFromJSDoc(node); + // don't issue an error for invalid hosts -- just functions -- + // and give a better error message when the host function mentions `arguments` + // but the tag doesn't have an array type + if (decl) { + var i = ts.getJSDocTags(decl).filter(ts.isJSDocParameterTag).indexOf(node); + if (i > -1 && i < decl.parameters.length && ts.isBindingPattern(decl.parameters[i].name)) { + return; + } + if (!containsArgumentsReference(decl)) { + error(node.name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name, ts.idText(node.name.kind === 148 /* QualifiedName */ ? node.name.right : node.name)); + } + else if (ts.findLast(ts.getJSDocTags(decl), ts.isJSDocParameterTag) === node && + node.typeExpression && node.typeExpression.type && + !isArrayType(getTypeFromTypeNode(node.typeExpression.type))) { + error(node.name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_had_an_array_type, ts.idText(node.name.kind === 148 /* QualifiedName */ ? node.name.right : node.name)); + } + } + } + } + function checkJSDocFunctionType(node) { + if (produceDiagnostics && !node.type && !ts.isJSDocConstructSignature(node)) { + reportImplicitAny(node, anyType); + } + checkSignatureDeclaration(node); + } + function checkJSDocAugmentsTag(node) { + var classLike = ts.getJSDocHost(node); + if (!ts.isClassDeclaration(classLike) && !ts.isClassExpression(classLike)) { + error(classLike, ts.Diagnostics.JSDoc_0_is_not_attached_to_a_class, ts.idText(node.tagName)); + return; + } + var augmentsTags = ts.getJSDocTags(classLike).filter(ts.isJSDocAugmentsTag); + ts.Debug.assert(augmentsTags.length > 0); + if (augmentsTags.length > 1) { + error(augmentsTags[1], ts.Diagnostics.Class_declarations_cannot_have_more_than_one_augments_or_extends_tag); + } + var name = getIdentifierFromEntityNameExpression(node.class.expression); + var extend = ts.getClassExtendsHeritageElement(classLike); + if (extend) { + var className = getIdentifierFromEntityNameExpression(extend.expression); + if (className && name.escapedText !== className.escapedText) { + error(name, ts.Diagnostics.JSDoc_0_1_does_not_match_the_extends_2_clause, ts.idText(node.tagName), ts.idText(name), ts.idText(className)); + } + } + } + function getIdentifierFromEntityNameExpression(node) { + switch (node.kind) { + case 72 /* Identifier */: + return node; + case 189 /* PropertyAccessExpression */: + return node.name; + default: + return undefined; + } + } + function checkFunctionOrMethodDeclaration(node) { + checkDecorators(node); + checkSignatureDeclaration(node); + var functionFlags = ts.getFunctionFlags(node); + // Do not use hasDynamicName here, because that returns false for well known symbols. + // We want to perform checkComputedPropertyName for all computed properties, including + // well known symbols. + if (node.name && node.name.kind === 149 /* ComputedPropertyName */) { + // This check will account for methods in class/interface declarations, + // as well as accessors in classes/object literals + checkComputedPropertyName(node.name); + } + if (!hasNonBindableDynamicName(node)) { + // first we want to check the local symbol that contain this declaration + // - if node.localSymbol !== undefined - this is current declaration is exported and localSymbol points to the local symbol + // - if node.localSymbol === undefined - this node is non-exported so we can just pick the result of getSymbolOfNode + var symbol = getSymbolOfNode(node); + var localSymbol = node.localSymbol || symbol; + // Since the javascript won't do semantic analysis like typescript, + // if the javascript file comes before the typescript file and both contain same name functions, + // checkFunctionOrConstructorSymbol wouldn't be called if we didnt ignore javascript function. + var firstDeclaration = ts.find(localSymbol.declarations, + // Get first non javascript function declaration + function (declaration) { return declaration.kind === node.kind && !(declaration.flags & 65536 /* JavaScriptFile */); }); + // Only type check the symbol once + if (node === firstDeclaration) { + checkFunctionOrConstructorSymbol(localSymbol); + } + if (symbol.parent) { + // run check once for the first declaration + if (ts.getDeclarationOfKind(symbol, node.kind) === node) { + // run check on export symbol to check that modifiers agree across all exported declarations + checkFunctionOrConstructorSymbol(symbol); + } + } + } + var body = node.kind === 155 /* MethodSignature */ ? undefined : node.body; + checkSourceElement(body); + if ((functionFlags & 1 /* Generator */) === 0) { // Async function or normal function + var returnOrPromisedType = getReturnOrPromisedType(node, functionFlags); + checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnOrPromisedType); + } + if (produceDiagnostics && !ts.getEffectiveReturnTypeNode(node)) { + // Report an implicit any error if there is no body, no explicit return type, and node is not a private method + // in an ambient context + if (ts.nodeIsMissing(body) && !isPrivateWithinAmbient(node)) { + reportImplicitAny(node, anyType); + } + if (functionFlags & 1 /* Generator */ && ts.nodeIsPresent(body)) { + // A generator with a body and no type annotation can still cause errors. It can error if the + // yielded values have no common supertype, or it can give an implicit any error if it has no + // yielded values. The only way to trigger these errors is to try checking its return type. + getReturnTypeOfSignature(getSignatureFromDeclaration(node)); + } + } + // A js function declaration can have a @type tag instead of a return type node, but that type must have a call signature + if (ts.isInJSFile(node)) { + var typeTag = ts.getJSDocTypeTag(node); + if (typeTag && typeTag.typeExpression && !getContextualCallSignature(getTypeFromTypeNode(typeTag.typeExpression), node)) { + error(typeTag, ts.Diagnostics.The_type_of_a_function_declaration_must_match_the_function_s_signature); + } + } + } + function registerForUnusedIdentifiersCheck(node) { + // May be in a call such as getTypeOfNode that happened to call this. But potentiallyUnusedIdentifiers is only defined in the scope of `checkSourceFile`. + if (produceDiagnostics && !(node.flags & 4194304 /* Ambient */)) { + var sourceFile = ts.getSourceFileOfNode(node); + var potentiallyUnusedIdentifiers = allPotentiallyUnusedIdentifiers.get(sourceFile.path); + if (!potentiallyUnusedIdentifiers) { + potentiallyUnusedIdentifiers = []; + allPotentiallyUnusedIdentifiers.set(sourceFile.path, potentiallyUnusedIdentifiers); + } + // TODO: GH#22580 + // Debug.assert(addToSeen(seenPotentiallyUnusedIdentifiers, getNodeId(node)), "Adding potentially-unused identifier twice"); + potentiallyUnusedIdentifiers.push(node); + } + } + function checkUnusedIdentifiers(potentiallyUnusedIdentifiers, addDiagnostic) { + for (var _i = 0, potentiallyUnusedIdentifiers_1 = potentiallyUnusedIdentifiers; _i < potentiallyUnusedIdentifiers_1.length; _i++) { + var node = potentiallyUnusedIdentifiers_1[_i]; + switch (node.kind) { + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + checkUnusedClassMembers(node, addDiagnostic); + checkUnusedTypeParameters(node, addDiagnostic); + break; + case 279 /* SourceFile */: + case 244 /* ModuleDeclaration */: + case 218 /* Block */: + case 246 /* CaseBlock */: + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + checkUnusedLocalsAndParameters(node, addDiagnostic); + break; + case 157 /* Constructor */: + case 196 /* FunctionExpression */: + case 239 /* FunctionDeclaration */: + case 197 /* ArrowFunction */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + if (node.body) { // Don't report unused parameters in overloads + checkUnusedLocalsAndParameters(node, addDiagnostic); + } + checkUnusedTypeParameters(node, addDiagnostic); + break; + case 155 /* MethodSignature */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + case 242 /* TypeAliasDeclaration */: + case 241 /* InterfaceDeclaration */: + checkUnusedTypeParameters(node, addDiagnostic); + break; + case 176 /* InferType */: + checkUnusedInferTypeParameter(node, addDiagnostic); + break; + default: + ts.Debug.assertNever(node, "Node should not have been registered for unused identifiers check"); + } + } + } + function errorUnusedLocal(declaration, name, addDiagnostic) { + var node = ts.getNameOfDeclaration(declaration) || declaration; + var message = isTypeDeclaration(declaration) ? ts.Diagnostics._0_is_declared_but_never_used : ts.Diagnostics._0_is_declared_but_its_value_is_never_read; + addDiagnostic(declaration, 0 /* Local */, ts.createDiagnosticForNode(node, message, name)); + } + function isIdentifierThatStartsWithUnderscore(node) { + return ts.isIdentifier(node) && ts.idText(node).charCodeAt(0) === 95 /* _ */; + } + function checkUnusedClassMembers(node, addDiagnostic) { + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + switch (member.kind) { + case 156 /* MethodDeclaration */: + case 154 /* PropertyDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + if (member.kind === 159 /* SetAccessor */ && member.symbol.flags & 32768 /* GetAccessor */) { + // Already would have reported an error on the getter. + break; + } + var symbol = getSymbolOfNode(member); + if (!symbol.isReferenced && ts.hasModifier(member, 8 /* Private */)) { + addDiagnostic(member, 0 /* Local */, ts.createDiagnosticForNode(member.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, symbolToString(symbol))); + } + break; + case 157 /* Constructor */: + for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { + var parameter = _c[_b]; + if (!parameter.symbol.isReferenced && ts.hasModifier(parameter, 8 /* Private */)) { + addDiagnostic(parameter, 0 /* Local */, ts.createDiagnosticForNode(parameter.name, ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read, ts.symbolName(parameter.symbol))); + } + } + break; + case 162 /* IndexSignature */: + case 217 /* SemicolonClassElement */: + // Can't be private + break; + default: + ts.Debug.fail(); + } + } + } + function checkUnusedInferTypeParameter(node, addDiagnostic) { + var typeParameter = node.typeParameter; + if (isTypeParameterUnused(typeParameter)) { + addDiagnostic(node, 1 /* Parameter */, ts.createDiagnosticForNode(node, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(typeParameter.name))); + } + } + function checkUnusedTypeParameters(node, addDiagnostic) { + // Only report errors on the last declaration for the type parameter container; + // this ensures that all uses have been accounted for. + if (ts.last(getSymbolOfNode(node).declarations) !== node) + return; + var typeParameters = ts.getEffectiveTypeParameterDeclarations(node); + var seenParentsWithEveryUnused = new ts.NodeSet(); + for (var _i = 0, typeParameters_2 = typeParameters; _i < typeParameters_2.length; _i++) { + var typeParameter = typeParameters_2[_i]; + if (!isTypeParameterUnused(typeParameter)) + continue; + var name = ts.idText(typeParameter.name); + var parent = typeParameter.parent; + if (parent.kind !== 176 /* InferType */ && parent.typeParameters.every(isTypeParameterUnused)) { + if (seenParentsWithEveryUnused.tryAdd(parent)) { + var range = ts.isJSDocTemplateTag(parent) + // Whole @template tag + ? ts.rangeOfNode(parent) + // Include the `<>` in the error message + : ts.rangeOfTypeParameters(parent.typeParameters); + var only = typeParameters.length === 1; + var message = only ? ts.Diagnostics._0_is_declared_but_its_value_is_never_read : ts.Diagnostics.All_type_parameters_are_unused; + var arg0 = only ? name : undefined; + addDiagnostic(typeParameter, 1 /* Parameter */, ts.createFileDiagnostic(ts.getSourceFileOfNode(parent), range.pos, range.end - range.pos, message, arg0)); + } + } + else { + addDiagnostic(typeParameter, 1 /* Parameter */, ts.createDiagnosticForNode(typeParameter, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, name)); + } + } + } + function isTypeParameterUnused(typeParameter) { + return !(getMergedSymbol(typeParameter.symbol).isReferenced & 262144 /* TypeParameter */) && !isIdentifierThatStartsWithUnderscore(typeParameter.name); + } + function addToGroup(map, key, value, getKey) { + var keyString = String(getKey(key)); + var group = map.get(keyString); + if (group) { + group[1].push(value); + } + else { + map.set(keyString, [key, [value]]); + } + } + function tryGetRootParameterDeclaration(node) { + return ts.tryCast(ts.getRootDeclaration(node), ts.isParameter); + } + function checkUnusedLocalsAndParameters(nodeWithLocals, addDiagnostic) { + if (nodeWithLocals.flags & 4194304 /* Ambient */) + return; + // Ideally we could use the ImportClause directly as a key, but must wait until we have full ES6 maps. So must store key along with value. + var unusedImports = ts.createMap(); + var unusedDestructures = ts.createMap(); + var unusedVariables = ts.createMap(); + nodeWithLocals.locals.forEach(function (local) { + // If it's purely a type parameter, ignore, will be checked in `checkUnusedTypeParameters`. + // If it's a type parameter merged with a parameter, check if the parameter-side is used. + if (local.flags & 262144 /* TypeParameter */ ? !(local.flags & 3 /* Variable */ && !(local.isReferenced & 3 /* Variable */)) : local.isReferenced || local.exportSymbol) { + return; + } + for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (ts.isAmbientModule(declaration) || + (ts.isVariableDeclaration(declaration) && ts.isForInOrOfStatement(declaration.parent.parent) || isImportedDeclaration(declaration)) && isIdentifierThatStartsWithUnderscore(declaration.name)) { + continue; + } + if (isImportedDeclaration(declaration)) { + addToGroup(unusedImports, importClauseFromImported(declaration), declaration, getNodeId); + } + else if (ts.isBindingElement(declaration) && ts.isObjectBindingPattern(declaration.parent)) { + // In `{ a, ...b }, `a` is considered used since it removes a property from `b`. `b` may still be unused though. + var lastElement = ts.last(declaration.parent.elements); + if (declaration === lastElement || !ts.last(declaration.parent.elements).dotDotDotToken) { + addToGroup(unusedDestructures, declaration.parent, declaration, getNodeId); + } + } + else if (ts.isVariableDeclaration(declaration)) { + addToGroup(unusedVariables, declaration.parent, declaration, getNodeId); + } + else { + var parameter = local.valueDeclaration && tryGetRootParameterDeclaration(local.valueDeclaration); + var name = local.valueDeclaration && ts.getNameOfDeclaration(local.valueDeclaration); + if (parameter && name) { + if (!ts.isParameterPropertyDeclaration(parameter) && !ts.parameterIsThisKeyword(parameter) && !isIdentifierThatStartsWithUnderscore(name)) { + addDiagnostic(parameter, 1 /* Parameter */, ts.createDiagnosticForNode(name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.symbolName(local))); + } + } + else { + errorUnusedLocal(declaration, ts.symbolName(local), addDiagnostic); + } + } + } + }); + unusedImports.forEach(function (_a) { + var importClause = _a[0], unuseds = _a[1]; + var importDecl = importClause.parent; + var nDeclarations = (importClause.name ? 1 : 0) + + (importClause.namedBindings ? + (importClause.namedBindings.kind === 251 /* NamespaceImport */ ? 1 : importClause.namedBindings.elements.length) + : 0); + if (nDeclarations === unuseds.length) { + addDiagnostic(importDecl, 0 /* Local */, unuseds.length === 1 + ? ts.createDiagnosticForNode(importDecl, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(ts.first(unuseds).name)) + : ts.createDiagnosticForNode(importDecl, ts.Diagnostics.All_imports_in_import_declaration_are_unused)); + } + else { + for (var _i = 0, unuseds_1 = unuseds; _i < unuseds_1.length; _i++) { + var unused = unuseds_1[_i]; + errorUnusedLocal(unused, ts.idText(unused.name), addDiagnostic); + } + } + }); + unusedDestructures.forEach(function (_a) { + var bindingPattern = _a[0], bindingElements = _a[1]; + var kind = tryGetRootParameterDeclaration(bindingPattern.parent) ? 1 /* Parameter */ : 0 /* Local */; + if (bindingPattern.elements.length === bindingElements.length) { + if (bindingElements.length === 1 && bindingPattern.parent.kind === 237 /* VariableDeclaration */ && bindingPattern.parent.parent.kind === 238 /* VariableDeclarationList */) { + addToGroup(unusedVariables, bindingPattern.parent.parent, bindingPattern.parent, getNodeId); + } + else { + addDiagnostic(bindingPattern, kind, bindingElements.length === 1 + ? ts.createDiagnosticForNode(bindingPattern, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(ts.first(bindingElements).name)) + : ts.createDiagnosticForNode(bindingPattern, ts.Diagnostics.All_destructured_elements_are_unused)); + } + } + else { + for (var _i = 0, bindingElements_1 = bindingElements; _i < bindingElements_1.length; _i++) { + var e = bindingElements_1[_i]; + addDiagnostic(e, kind, ts.createDiagnosticForNode(e, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(e.name))); + } + } + }); + unusedVariables.forEach(function (_a) { + var declarationList = _a[0], declarations = _a[1]; + if (declarationList.declarations.length === declarations.length) { + addDiagnostic(declarationList, 0 /* Local */, declarations.length === 1 + ? ts.createDiagnosticForNode(ts.first(declarations).name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(ts.first(declarations).name)) + : ts.createDiagnosticForNode(declarationList.parent.kind === 219 /* VariableStatement */ ? declarationList.parent : declarationList, ts.Diagnostics.All_variables_are_unused)); + } + else { + for (var _i = 0, declarations_5 = declarations; _i < declarations_5.length; _i++) { + var decl = declarations_5[_i]; + addDiagnostic(decl, 0 /* Local */, ts.createDiagnosticForNode(decl, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(decl.name))); + } + } + }); + } + function bindingNameText(name) { + switch (name.kind) { + case 72 /* Identifier */: + return ts.idText(name); + case 185 /* ArrayBindingPattern */: + case 184 /* ObjectBindingPattern */: + return bindingNameText(ts.cast(ts.first(name.elements), ts.isBindingElement).name); + default: + return ts.Debug.assertNever(name); + } + } + function isImportedDeclaration(node) { + return node.kind === 250 /* ImportClause */ || node.kind === 253 /* ImportSpecifier */ || node.kind === 251 /* NamespaceImport */; + } + function importClauseFromImported(decl) { + return decl.kind === 250 /* ImportClause */ ? decl : decl.kind === 251 /* NamespaceImport */ ? decl.parent : decl.parent.parent; + } + function checkBlock(node) { + // Grammar checking for SyntaxKind.Block + if (node.kind === 218 /* Block */) { + checkGrammarStatementInAmbientContext(node); + } + if (ts.isFunctionOrModuleBlock(node)) { + var saveFlowAnalysisDisabled = flowAnalysisDisabled; + ts.forEach(node.statements, checkSourceElement); + flowAnalysisDisabled = saveFlowAnalysisDisabled; + } + else { + ts.forEach(node.statements, checkSourceElement); + } + if (node.locals) { + registerForUnusedIdentifiersCheck(node); + } + } + function checkCollisionWithArgumentsInGeneratedCode(node) { + // no rest parameters \ declaration context \ overload - no codegen impact + if (languageVersion >= 2 /* ES2015 */ || compilerOptions.noEmit || !ts.hasRestParameter(node) || node.flags & 4194304 /* Ambient */ || ts.nodeIsMissing(node.body)) { + return; + } + ts.forEach(node.parameters, function (p) { + if (p.name && !ts.isBindingPattern(p.name) && p.name.escapedText === argumentsSymbol.escapedName) { + error(p, ts.Diagnostics.Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters); + } + }); + } + function needCollisionCheckForIdentifier(node, identifier, name) { + if (!(identifier && identifier.escapedText === name)) { + return false; + } + if (node.kind === 154 /* PropertyDeclaration */ || + node.kind === 153 /* PropertySignature */ || + node.kind === 156 /* MethodDeclaration */ || + node.kind === 155 /* MethodSignature */ || + node.kind === 158 /* GetAccessor */ || + node.kind === 159 /* SetAccessor */) { + // it is ok to have member named '_super' or '_this' - member access is always qualified + return false; + } + if (node.flags & 4194304 /* Ambient */) { + // ambient context - no codegen impact + return false; + } + var root = ts.getRootDeclaration(node); + if (root.kind === 151 /* Parameter */ && ts.nodeIsMissing(root.parent.body)) { + // just an overload - no codegen impact + return false; + } + return true; + } + // this function will run after checking the source file so 'CaptureThis' is correct for all nodes + function checkIfThisIsCapturedInEnclosingScope(node) { + ts.findAncestor(node, function (current) { + if (getNodeCheckFlags(current) & 4 /* CaptureThis */) { + var isDeclaration_1 = node.kind !== 72 /* Identifier */; + if (isDeclaration_1) { + error(ts.getNameOfDeclaration(node), ts.Diagnostics.Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference); + } + else { + error(node, ts.Diagnostics.Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference); + } + return true; + } + return false; + }); + } + function checkIfNewTargetIsCapturedInEnclosingScope(node) { + ts.findAncestor(node, function (current) { + if (getNodeCheckFlags(current) & 8 /* CaptureNewTarget */) { + var isDeclaration_2 = node.kind !== 72 /* Identifier */; + if (isDeclaration_2) { + error(ts.getNameOfDeclaration(node), ts.Diagnostics.Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference); + } + else { + error(node, ts.Diagnostics.Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta_property_reference); + } + return true; + } + return false; + }); + } + function checkCollisionWithRequireExportsInGeneratedCode(node, name) { + // No need to check for require or exports for ES6 modules and later + if (moduleKind >= ts.ModuleKind.ES2015 || compilerOptions.noEmit) { + return; + } + if (!needCollisionCheckForIdentifier(node, name, "require") && !needCollisionCheckForIdentifier(node, name, "exports")) { + return; + } + // Uninstantiated modules shouldnt do this check + if (ts.isModuleDeclaration(node) && ts.getModuleInstanceState(node) !== 1 /* Instantiated */) { + return; + } + // In case of variable declaration, node.parent is variable statement so look at the variable statement's parent + var parent = getDeclarationContainer(node); + if (parent.kind === 279 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent)) { + // If the declaration happens to be in external module, report error that require and exports are reserved keywords + error(name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module, ts.declarationNameToString(name), ts.declarationNameToString(name)); + } + } + function checkCollisionWithGlobalPromiseInGeneratedCode(node, name) { + if (languageVersion >= 4 /* ES2017 */ || compilerOptions.noEmit || !needCollisionCheckForIdentifier(node, name, "Promise")) { + return; + } + // Uninstantiated modules shouldnt do this check + if (ts.isModuleDeclaration(node) && ts.getModuleInstanceState(node) !== 1 /* Instantiated */) { + return; + } + // In case of variable declaration, node.parent is variable statement so look at the variable statement's parent + var parent = getDeclarationContainer(node); + if (parent.kind === 279 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent) && parent.flags & 1024 /* HasAsyncFunctions */) { + // If the declaration happens to be in external module, report error that Promise is a reserved identifier. + error(name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_functions, ts.declarationNameToString(name), ts.declarationNameToString(name)); + } + } + function checkVarDeclaredNamesNotShadowed(node) { + // - ScriptBody : StatementList + // It is a Syntax Error if any element of the LexicallyDeclaredNames of StatementList + // also occurs in the VarDeclaredNames of StatementList. + // - Block : { StatementList } + // It is a Syntax Error if any element of the LexicallyDeclaredNames of StatementList + // also occurs in the VarDeclaredNames of StatementList. + // Variable declarations are hoisted to the top of their function scope. They can shadow + // block scoped declarations, which bind tighter. this will not be flagged as duplicate definition + // by the binder as the declaration scope is different. + // A non-initialized declaration is a no-op as the block declaration will resolve before the var + // declaration. the problem is if the declaration has an initializer. this will act as a write to the + // block declared value. this is fine for let, but not const. + // Only consider declarations with initializers, uninitialized const declarations will not + // step on a let/const variable. + // Do not consider const and const declarations, as duplicate block-scoped declarations + // are handled by the binder. + // We are only looking for const declarations that step on let\const declarations from a + // different scope. e.g.: + // { + // const x = 0; // localDeclarationSymbol obtained after name resolution will correspond to this declaration + // const x = 0; // symbol for this declaration will be 'symbol' + // } + // skip block-scoped variables and parameters + if ((ts.getCombinedNodeFlags(node) & 3 /* BlockScoped */) !== 0 || ts.isParameterDeclaration(node)) { + return; + } + // skip variable declarations that don't have initializers + // NOTE: in ES6 spec initializer is required in variable declarations where name is binding pattern + // so we'll always treat binding elements as initialized + if (node.kind === 237 /* VariableDeclaration */ && !node.initializer) { + return; + } + var symbol = getSymbolOfNode(node); + if (symbol.flags & 1 /* FunctionScopedVariable */) { + if (!ts.isIdentifier(node.name)) + return ts.Debug.fail(); + var localDeclarationSymbol = resolveName(node, node.name.escapedText, 3 /* Variable */, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); + if (localDeclarationSymbol && + localDeclarationSymbol !== symbol && + localDeclarationSymbol.flags & 2 /* BlockScopedVariable */) { + if (getDeclarationNodeFlagsFromSymbol(localDeclarationSymbol) & 3 /* BlockScoped */) { + var varDeclList = ts.getAncestor(localDeclarationSymbol.valueDeclaration, 238 /* VariableDeclarationList */); + var container = varDeclList.parent.kind === 219 /* VariableStatement */ && varDeclList.parent.parent + ? varDeclList.parent.parent + : undefined; + // names of block-scoped and function scoped variables can collide only + // if block scoped variable is defined in the function\module\source file scope (because of variable hoisting) + var namesShareScope = container && + (container.kind === 218 /* Block */ && ts.isFunctionLike(container.parent) || + container.kind === 245 /* ModuleBlock */ || + container.kind === 244 /* ModuleDeclaration */ || + container.kind === 279 /* SourceFile */); + // here we know that function scoped variable is shadowed by block scoped one + // if they are defined in the same scope - binder has already reported redeclaration error + // otherwise if variable has an initializer - show error that initialization will fail + // since LHS will be block scoped name instead of function scoped + if (!namesShareScope) { + var name = symbolToString(localDeclarationSymbol); + error(node, ts.Diagnostics.Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1, name, name); + } + } + } + } + } + // Check that a parameter initializer contains no references to parameters declared to the right of itself + function checkParameterInitializer(node) { + if (ts.getRootDeclaration(node).kind !== 151 /* Parameter */) { + return; + } + var func = ts.getContainingFunction(node); + visit(node.initializer); + function visit(n) { + if (ts.isTypeNode(n) || ts.isDeclarationName(n)) { + // do not dive in types + // skip declaration names (i.e. in object literal expressions) + return; + } + if (n.kind === 189 /* PropertyAccessExpression */) { + // skip property names in property access expression + return visit(n.expression); + } + else if (n.kind === 72 /* Identifier */) { + // check FunctionLikeDeclaration.locals (stores parameters\function local variable) + // if it contains entry with a specified name + var symbol = resolveName(n, n.escapedText, 67220415 /* Value */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); + if (!symbol || symbol === unknownSymbol || !symbol.valueDeclaration) { + return; + } + if (symbol.valueDeclaration === node) { + error(n, ts.Diagnostics.Parameter_0_cannot_be_referenced_in_its_initializer, ts.declarationNameToString(node.name)); + return; + } + // locals map for function contain both parameters and function locals + // so we need to do a bit of extra work to check if reference is legal + var enclosingContainer = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); + if (enclosingContainer === func) { + if (symbol.valueDeclaration.kind === 151 /* Parameter */ || + symbol.valueDeclaration.kind === 186 /* BindingElement */) { + // it is ok to reference parameter in initializer if either + // - parameter is located strictly on the left of current parameter declaration + if (symbol.valueDeclaration.pos < node.pos) { + return; + } + // - parameter is wrapped in function-like entity + if (ts.findAncestor(n, function (current) { + if (current === node.initializer) { + return "quit"; + } + return ts.isFunctionLike(current.parent) || + // computed property names/initializers in instance property declaration of class like entities + // are executed in constructor and thus deferred + (current.parent.kind === 154 /* PropertyDeclaration */ && + !(ts.hasModifier(current.parent, 32 /* Static */)) && + ts.isClassLike(current.parent.parent)); + })) { + return; + } + // fall through to report error + } + error(n, ts.Diagnostics.Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it, ts.declarationNameToString(node.name), ts.declarationNameToString(n)); + } + } + else { + return ts.forEachChild(n, visit); + } + } + } + function convertAutoToAny(type) { + return type === autoType ? anyType : type === autoArrayType ? anyArrayType : type; + } + // Check variable, parameter, or property declaration + function checkVariableLikeDeclaration(node) { + checkDecorators(node); + if (!ts.isBindingElement(node)) { + checkSourceElement(node.type); + } + // JSDoc `function(string, string): string` syntax results in parameters with no name + if (!node.name) { + return; + } + // For a computed property, just check the initializer and exit + // Do not use hasDynamicName here, because that returns false for well known symbols. + // We want to perform checkComputedPropertyName for all computed properties, including + // well known symbols. + if (node.name.kind === 149 /* ComputedPropertyName */) { + checkComputedPropertyName(node.name); + if (node.initializer) { + checkExpressionCached(node.initializer); + } + } + if (node.kind === 186 /* BindingElement */) { + if (node.parent.kind === 184 /* ObjectBindingPattern */ && languageVersion < 6 /* ESNext */) { + checkExternalEmitHelpers(node, 4 /* Rest */); + } + // check computed properties inside property names of binding elements + if (node.propertyName && node.propertyName.kind === 149 /* ComputedPropertyName */) { + checkComputedPropertyName(node.propertyName); + } + // check private/protected variable access + var parent = node.parent.parent; + var parentType = getTypeForBindingElementParent(parent); + var name = node.propertyName || node.name; + if (!ts.isBindingPattern(name)) { + var nameText = ts.getTextOfPropertyName(name); + if (nameText) { + var property = getPropertyOfType(parentType, nameText); // TODO: GH#18217 + if (property) { + markPropertyAsReferenced(property, /*nodeForCheckWriteOnly*/ undefined, /*isThisAccess*/ false); // A destructuring is never a write-only reference. + checkPropertyAccessibility(parent, !!parent.initializer && parent.initializer.kind === 98 /* SuperKeyword */, parentType, property); + } + } + } + } + // For a binding pattern, check contained binding elements + if (ts.isBindingPattern(node.name)) { + if (node.name.kind === 185 /* ArrayBindingPattern */ && languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) { + checkExternalEmitHelpers(node, 512 /* Read */); + } + ts.forEach(node.name.elements, checkSourceElement); + } + // For a parameter declaration with an initializer, error and exit if the containing function doesn't have a body + if (node.initializer && ts.getRootDeclaration(node).kind === 151 /* Parameter */ && ts.nodeIsMissing(ts.getContainingFunction(node).body)) { + error(node, ts.Diagnostics.A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation); + return; + } + // For a binding pattern, validate the initializer and exit + if (ts.isBindingPattern(node.name)) { + // Don't validate for-in initializer as it is already an error + if (node.initializer && node.parent.parent.kind !== 226 /* ForInStatement */) { + var initializerType = checkExpressionCached(node.initializer); + if (strictNullChecks && node.name.elements.length === 0) { + checkNonNullType(initializerType, node); + } + else { + checkTypeAssignableToAndOptionallyElaborate(initializerType, getWidenedTypeForVariableLikeDeclaration(node), node, node.initializer); + } + checkParameterInitializer(node); + } + return; + } + var symbol = getSymbolOfNode(node); + var type = convertAutoToAny(getTypeOfSymbol(symbol)); + if (node === symbol.valueDeclaration) { + // Node is the primary declaration of the symbol, just validate the initializer + // Don't validate for-in initializer as it is already an error + var initializer = ts.getEffectiveInitializer(node); + if (initializer) { + var isJSObjectLiteralInitializer = ts.isInJSFile(node) && + ts.isObjectLiteralExpression(initializer) && + (initializer.properties.length === 0 || ts.isPrototypeAccess(node.name)) && + ts.hasEntries(symbol.exports); + if (!isJSObjectLiteralInitializer && node.parent.parent.kind !== 226 /* ForInStatement */) { + checkTypeAssignableToAndOptionallyElaborate(checkExpressionCached(initializer), type, node, initializer, /*headMessage*/ undefined); + checkParameterInitializer(node); + } + } + if (symbol.declarations.length > 1) { + if (ts.some(symbol.declarations, function (d) { return d !== node && ts.isVariableLike(d) && !areDeclarationFlagsIdentical(d, node); })) { + error(node.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); + } + } + } + else { + // Node is a secondary declaration, check that type is identical to primary declaration and check that + // initializer is consistent with type associated with the node + var declarationType = convertAutoToAny(getWidenedTypeForVariableLikeDeclaration(node)); + if (type !== errorType && declarationType !== errorType && + !isTypeIdenticalTo(type, declarationType) && + !(symbol.flags & 67108864 /* Assignment */)) { + errorNextVariableOrPropertyDeclarationMustHaveSameType(type, node, declarationType); + } + if (node.initializer) { + checkTypeAssignableToAndOptionallyElaborate(checkExpressionCached(node.initializer), declarationType, node, node.initializer, /*headMessage*/ undefined); + } + if (!areDeclarationFlagsIdentical(node, symbol.valueDeclaration)) { + error(node.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); + } + } + if (node.kind !== 154 /* PropertyDeclaration */ && node.kind !== 153 /* PropertySignature */) { + // We know we don't have a binding pattern or computed name here + checkExportsOnMergedDeclarations(node); + if (node.kind === 237 /* VariableDeclaration */ || node.kind === 186 /* BindingElement */) { + checkVarDeclaredNamesNotShadowed(node); + } + checkCollisionWithRequireExportsInGeneratedCode(node, node.name); + checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); + } + } + function errorNextVariableOrPropertyDeclarationMustHaveSameType(firstType, nextDeclaration, nextType) { + var nextDeclarationName = ts.getNameOfDeclaration(nextDeclaration); + var message = nextDeclaration.kind === 154 /* PropertyDeclaration */ || nextDeclaration.kind === 153 /* PropertySignature */ + ? ts.Diagnostics.Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_type_2 + : ts.Diagnostics.Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2; + error(nextDeclarationName, message, ts.declarationNameToString(nextDeclarationName), typeToString(firstType), typeToString(nextType)); + } + function areDeclarationFlagsIdentical(left, right) { + if ((left.kind === 151 /* Parameter */ && right.kind === 237 /* VariableDeclaration */) || + (left.kind === 237 /* VariableDeclaration */ && right.kind === 151 /* Parameter */)) { + // Differences in optionality between parameters and variables are allowed. + return true; + } + if (ts.hasQuestionToken(left) !== ts.hasQuestionToken(right)) { + return false; + } + var interestingFlags = 8 /* Private */ | + 16 /* Protected */ | + 256 /* Async */ | + 128 /* Abstract */ | + 64 /* Readonly */ | + 32 /* Static */; + return ts.getSelectedModifierFlags(left, interestingFlags) === ts.getSelectedModifierFlags(right, interestingFlags); + } + function checkVariableDeclaration(node) { + checkGrammarVariableDeclaration(node); + return checkVariableLikeDeclaration(node); + } + function checkBindingElement(node) { + checkGrammarBindingElement(node); + return checkVariableLikeDeclaration(node); + } + function checkVariableStatement(node) { + // Grammar checking + if (!checkGrammarDecoratorsAndModifiers(node) && !checkGrammarVariableDeclarationList(node.declarationList)) + checkGrammarForDisallowedLetOrConstStatement(node); + ts.forEach(node.declarationList.declarations, checkSourceElement); + } + function checkExpressionStatement(node) { + // Grammar checking + checkGrammarStatementInAmbientContext(node); + checkExpression(node.expression); + } + function checkIfStatement(node) { + // Grammar checking + checkGrammarStatementInAmbientContext(node); + checkTruthinessExpression(node.expression); + checkSourceElement(node.thenStatement); + if (node.thenStatement.kind === 220 /* EmptyStatement */) { + error(node.thenStatement, ts.Diagnostics.The_body_of_an_if_statement_cannot_be_the_empty_statement); + } + checkSourceElement(node.elseStatement); + } + function checkDoStatement(node) { + // Grammar checking + checkGrammarStatementInAmbientContext(node); + checkSourceElement(node.statement); + checkTruthinessExpression(node.expression); + } + function checkWhileStatement(node) { + // Grammar checking + checkGrammarStatementInAmbientContext(node); + checkTruthinessExpression(node.expression); + checkSourceElement(node.statement); + } + function checkTruthinessExpression(node, checkMode) { + var type = checkExpression(node, checkMode); + if (type.flags & 16384 /* Void */) { + error(node, ts.Diagnostics.An_expression_of_type_void_cannot_be_tested_for_truthiness); + } + return type; + } + function checkForStatement(node) { + // Grammar checking + if (!checkGrammarStatementInAmbientContext(node)) { + if (node.initializer && node.initializer.kind === 238 /* VariableDeclarationList */) { + checkGrammarVariableDeclarationList(node.initializer); + } + } + if (node.initializer) { + if (node.initializer.kind === 238 /* VariableDeclarationList */) { + ts.forEach(node.initializer.declarations, checkVariableDeclaration); + } + else { + checkExpression(node.initializer); + } + } + if (node.condition) + checkTruthinessExpression(node.condition); + if (node.incrementor) + checkExpression(node.incrementor); + checkSourceElement(node.statement); + if (node.locals) { + registerForUnusedIdentifiersCheck(node); + } + } + function checkForOfStatement(node) { + checkGrammarForInOrForOfStatement(node); + if (node.awaitModifier) { + var functionFlags = ts.getFunctionFlags(ts.getContainingFunction(node)); + if ((functionFlags & (4 /* Invalid */ | 2 /* Async */)) === 2 /* Async */ && languageVersion < 6 /* ESNext */) { + // for..await..of in an async function or async generator function prior to ESNext requires the __asyncValues helper + checkExternalEmitHelpers(node, 16384 /* ForAwaitOfIncludes */); + } + } + else if (compilerOptions.downlevelIteration && languageVersion < 2 /* ES2015 */) { + // for..of prior to ES2015 requires the __values helper when downlevelIteration is enabled + checkExternalEmitHelpers(node, 256 /* ForOfIncludes */); + } + // Check the LHS and RHS + // If the LHS is a declaration, just check it as a variable declaration, which will in turn check the RHS + // via checkRightHandSideOfForOf. + // If the LHS is an expression, check the LHS, as a destructuring assignment or as a reference. + // Then check that the RHS is assignable to it. + if (node.initializer.kind === 238 /* VariableDeclarationList */) { + checkForInOrForOfVariableDeclaration(node); + } + else { + var varExpr = node.initializer; + var iteratedType = checkRightHandSideOfForOf(node.expression, node.awaitModifier); + // There may be a destructuring assignment on the left side + if (varExpr.kind === 187 /* ArrayLiteralExpression */ || varExpr.kind === 188 /* ObjectLiteralExpression */) { + // iteratedType may be undefined. In this case, we still want to check the structure of + // varExpr, in particular making sure it's a valid LeftHandSideExpression. But we'd like + // to short circuit the type relation checking as much as possible, so we pass the unknownType. + checkDestructuringAssignment(varExpr, iteratedType || errorType); + } + else { + var leftType = checkExpression(varExpr); + checkReferenceExpression(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access); + // iteratedType will be undefined if the rightType was missing properties/signatures + // required to get its iteratedType (like [Symbol.iterator] or next). This may be + // because we accessed properties from anyType, or it may have led to an error inside + // getElementTypeOfIterable. + if (iteratedType) { + checkTypeAssignableToAndOptionallyElaborate(iteratedType, leftType, varExpr, node.expression); + } + } + } + checkSourceElement(node.statement); + if (node.locals) { + registerForUnusedIdentifiersCheck(node); + } + } + function checkForInStatement(node) { + // Grammar checking + checkGrammarForInOrForOfStatement(node); + var rightType = getNonNullableTypeIfNeeded(checkExpression(node.expression)); + // TypeScript 1.0 spec (April 2014): 5.4 + // In a 'for-in' statement of the form + // for (let VarDecl in Expr) Statement + // VarDecl must be a variable declaration without a type annotation that declares a variable of type Any, + // and Expr must be an expression of type Any, an object type, or a type parameter type. + if (node.initializer.kind === 238 /* VariableDeclarationList */) { + var variable = node.initializer.declarations[0]; + if (variable && ts.isBindingPattern(variable.name)) { + error(variable.name, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern); + } + checkForInOrForOfVariableDeclaration(node); + } + else { + // In a 'for-in' statement of the form + // for (Var in Expr) Statement + // Var must be an expression classified as a reference of type Any or the String primitive type, + // and Expr must be an expression of type Any, an object type, or a type parameter type. + var varExpr = node.initializer; + var leftType = checkExpression(varExpr); + if (varExpr.kind === 187 /* ArrayLiteralExpression */ || varExpr.kind === 188 /* ObjectLiteralExpression */) { + error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern); + } + else if (!isTypeAssignableTo(getIndexTypeOrString(rightType), leftType)) { + error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any); + } + else { + // run check only former check succeeded to avoid cascading errors + checkReferenceExpression(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access); + } + } + // unknownType is returned i.e. if node.expression is identifier whose name cannot be resolved + // in this case error about missing name is already reported - do not report extra one + if (rightType === neverType || !isTypeAssignableToKind(rightType, 67108864 /* NonPrimitive */ | 58982400 /* InstantiableNonPrimitive */)) { + error(node.expression, ts.Diagnostics.The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_but_here_has_type_0, typeToString(rightType)); + } + checkSourceElement(node.statement); + if (node.locals) { + registerForUnusedIdentifiersCheck(node); + } + } + function checkForInOrForOfVariableDeclaration(iterationStatement) { + var variableDeclarationList = iterationStatement.initializer; + // checkGrammarForInOrForOfStatement will check that there is exactly one declaration. + if (variableDeclarationList.declarations.length >= 1) { + var decl = variableDeclarationList.declarations[0]; + checkVariableDeclaration(decl); + } + } + function checkRightHandSideOfForOf(rhsExpression, awaitModifier) { + var expressionType = checkNonNullExpression(rhsExpression); + return checkIteratedTypeOrElementType(expressionType, rhsExpression, /*allowStringInput*/ true, awaitModifier !== undefined); + } + function checkIteratedTypeOrElementType(inputType, errorNode, allowStringInput, allowAsyncIterables) { + if (isTypeAny(inputType)) { + return inputType; + } + return getIteratedTypeOrElementType(inputType, errorNode, allowStringInput, allowAsyncIterables, /*checkAssignability*/ true) || anyType; + } + /** + * When consuming an iterable type in a for..of, spread, or iterator destructuring assignment + * we want to get the iterated type of an iterable for ES2015 or later, or the iterated type + * of a iterable (if defined globally) or element type of an array like for ES2015 or earlier. + */ + function getIteratedTypeOrElementType(inputType, errorNode, allowStringInput, allowAsyncIterables, checkAssignability) { + if (inputType === neverType) { + reportTypeNotIterableError(errorNode, inputType, allowAsyncIterables); // TODO: GH#18217 + return undefined; + } + var uplevelIteration = languageVersion >= 2 /* ES2015 */; + var downlevelIteration = !uplevelIteration && compilerOptions.downlevelIteration; + // Get the iterated type of an `Iterable` or `IterableIterator` only in ES2015 + // or higher, when inside of an async generator or for-await-if, or when + // downlevelIteration is requested. + if (uplevelIteration || downlevelIteration || allowAsyncIterables) { + // We only report errors for an invalid iterable type in ES2015 or higher. + var iteratedType = getIteratedTypeOfIterable(inputType, uplevelIteration ? errorNode : undefined, allowAsyncIterables, /*allowSyncIterables*/ true, checkAssignability); + if (iteratedType || uplevelIteration) { + return iteratedType; + } + } + var arrayType = inputType; + var reportedError = false; + var hasStringConstituent = false; + // If strings are permitted, remove any string-like constituents from the array type. + // This allows us to find other non-string element types from an array unioned with + // a string. + if (allowStringInput) { + if (arrayType.flags & 1048576 /* Union */) { + // After we remove all types that are StringLike, we will know if there was a string constituent + // based on whether the result of filter is a new array. + var arrayTypes = inputType.types; + var filteredTypes = ts.filter(arrayTypes, function (t) { return !(t.flags & 132 /* StringLike */); }); + if (filteredTypes !== arrayTypes) { + arrayType = getUnionType(filteredTypes, 2 /* Subtype */); + } + } + else if (arrayType.flags & 132 /* StringLike */) { + arrayType = neverType; + } + hasStringConstituent = arrayType !== inputType; + if (hasStringConstituent) { + if (languageVersion < 1 /* ES5 */) { + if (errorNode) { + error(errorNode, ts.Diagnostics.Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher); + reportedError = true; + } + } + // Now that we've removed all the StringLike types, if no constituents remain, then the entire + // arrayOrStringType was a string. + if (arrayType.flags & 131072 /* Never */) { + return stringType; + } + } + } + if (!isArrayLikeType(arrayType)) { + if (errorNode && !reportedError) { + // Which error we report depends on whether we allow strings or if there was a + // string constituent. For example, if the input type is number | string, we + // want to say that number is not an array type. But if the input was just + // number and string input is allowed, we want to say that number is not an + // array type or a string type. + var isIterable = !!getIteratedTypeOfIterable(inputType, /* errorNode */ undefined, allowAsyncIterables, /*allowSyncIterables*/ true, checkAssignability); + var diagnostic = !allowStringInput || hasStringConstituent + ? downlevelIteration + ? ts.Diagnostics.Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator + : isIterable + ? ts.Diagnostics.Type_0_is_not_an_array_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators + : ts.Diagnostics.Type_0_is_not_an_array_type + : downlevelIteration + ? ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator + : isIterable + ? ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators + : ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type; + error(errorNode, diagnostic, typeToString(arrayType)); + } + return hasStringConstituent ? stringType : undefined; + } + var arrayElementType = getIndexTypeOfType(arrayType, 1 /* Number */); + if (hasStringConstituent && arrayElementType) { + // This is just an optimization for the case where arrayOrStringType is string | string[] + if (arrayElementType.flags & 132 /* StringLike */) { + return stringType; + } + return getUnionType([arrayElementType, stringType], 2 /* Subtype */); + } + return arrayElementType; + } + /** + * We want to treat type as an iterable, and get the type it is an iterable of. The iterable + * must have the following structure (annotated with the names of the variables below): + * + * { // iterable + * [Symbol.iterator]: { // iteratorMethod + * (): Iterator + * } + * } + * + * For an async iterable, we expect the following structure: + * + * { // iterable + * [Symbol.asyncIterator]: { // iteratorMethod + * (): AsyncIterator + * } + * } + * + * T is the type we are after. At every level that involves analyzing return types + * of signatures, we union the return types of all the signatures. + * + * Another thing to note is that at any step of this process, we could run into a dead end, + * meaning either the property is missing, or we run into the anyType. If either of these things + * happens, we return undefined to signal that we could not find the iterated type. If a property + * is missing, and the previous step did not result in 'any', then we also give an error if the + * caller requested it. Then the caller can decide what to do in the case where there is no iterated + * type. This is different from returning anyType, because that would signify that we have matched the + * whole pattern and that T (above) is 'any'. + * + * For a **for-of** statement, `yield*` (in a normal generator), spread, array + * destructuring, or normal generator we will only ever look for a `[Symbol.iterator]()` + * method. + * + * For an async generator we will only ever look at the `[Symbol.asyncIterator]()` method. + * + * For a **for-await-of** statement or a `yield*` in an async generator we will look for + * the `[Symbol.asyncIterator]()` method first, and then the `[Symbol.iterator]()` method. + */ + function getIteratedTypeOfIterable(type, errorNode, allowAsyncIterables, allowSyncIterables, checkAssignability) { + if (isTypeAny(type)) { + return undefined; + } + return mapType(type, getIteratedType); + function getIteratedType(type) { + var typeAsIterable = type; + if (allowAsyncIterables) { + if (typeAsIterable.iteratedTypeOfAsyncIterable) { + return typeAsIterable.iteratedTypeOfAsyncIterable; + } + // As an optimization, if the type is an instantiation of the global `AsyncIterable` + // or the global `AsyncIterableIterator` then just grab its type argument. + if (isReferenceToType(type, getGlobalAsyncIterableType(/*reportErrors*/ false)) || + isReferenceToType(type, getGlobalAsyncIterableIteratorType(/*reportErrors*/ false))) { + return typeAsIterable.iteratedTypeOfAsyncIterable = type.typeArguments[0]; + } + } + if (allowSyncIterables) { + if (typeAsIterable.iteratedTypeOfIterable) { + return allowAsyncIterables + ? typeAsIterable.iteratedTypeOfAsyncIterable = getAwaitedType(typeAsIterable.iteratedTypeOfIterable) + : typeAsIterable.iteratedTypeOfIterable; + } + // As an optimization, if the type is an instantiation of the global `Iterable` or + // `IterableIterator` then just grab its type argument. + if (isReferenceToType(type, getGlobalIterableType(/*reportErrors*/ false)) || + isReferenceToType(type, getGlobalIterableIteratorType(/*reportErrors*/ false))) { + return allowAsyncIterables + ? typeAsIterable.iteratedTypeOfAsyncIterable = getAwaitedType(type.typeArguments[0]) + : typeAsIterable.iteratedTypeOfIterable = type.typeArguments[0]; + } + } + var asyncMethodType = allowAsyncIterables && getTypeOfPropertyOfType(type, ts.getPropertyNameForKnownSymbolName("asyncIterator")); + var methodType = asyncMethodType || (allowSyncIterables ? getTypeOfPropertyOfType(type, ts.getPropertyNameForKnownSymbolName("iterator")) : undefined); + if (isTypeAny(methodType)) { + return undefined; + } + var signatures = methodType ? getSignaturesOfType(methodType, 0 /* Call */) : undefined; + if (!ts.some(signatures)) { + if (errorNode) { + // only report on the first error + reportTypeNotIterableError(errorNode, type, allowAsyncIterables); + errorNode = undefined; + } + return undefined; + } + var returnType = getUnionType(ts.map(signatures, getReturnTypeOfSignature), 2 /* Subtype */); + var iteratedType = getIteratedTypeOfIterator(returnType, errorNode, /*isAsyncIterator*/ !!asyncMethodType); + if (checkAssignability && errorNode && iteratedType) { + // If `checkAssignability` was specified, we were called from + // `checkIteratedTypeOrElementType`. As such, we need to validate that + // the type passed in is actually an Iterable. + checkTypeAssignableTo(type, asyncMethodType + ? createAsyncIterableType(iteratedType) + : createIterableType(iteratedType), errorNode); + } + if (iteratedType) { + return allowAsyncIterables + ? typeAsIterable.iteratedTypeOfAsyncIterable = asyncMethodType ? iteratedType : getAwaitedType(iteratedType) + : typeAsIterable.iteratedTypeOfIterable = iteratedType; + } + } + } + function reportTypeNotIterableError(errorNode, type, allowAsyncIterables) { + error(errorNode, allowAsyncIterables + ? ts.Diagnostics.Type_0_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator + : ts.Diagnostics.Type_0_must_have_a_Symbol_iterator_method_that_returns_an_iterator, typeToString(type)); + } + /** + * This function has very similar logic as getIteratedTypeOfIterable, except that it operates on + * Iterators instead of Iterables. Here is the structure: + * + * { // iterator + * next: { // nextMethod + * (): { // nextResult + * value: T // nextValue + * } + * } + * } + * + * For an async iterator, we expect the following structure: + * + * { // iterator + * next: { // nextMethod + * (): PromiseLike<{ // nextResult + * value: T // nextValue + * }> + * } + * } + */ + function getIteratedTypeOfIterator(type, errorNode, isAsyncIterator) { + if (isTypeAny(type)) { + return undefined; + } + var typeAsIterator = type; + if (isAsyncIterator ? typeAsIterator.iteratedTypeOfAsyncIterator : typeAsIterator.iteratedTypeOfIterator) { + return isAsyncIterator ? typeAsIterator.iteratedTypeOfAsyncIterator : typeAsIterator.iteratedTypeOfIterator; + } + // As an optimization, if the type is an instantiation of the global `Iterator` (for + // a non-async iterator) or the global `AsyncIterator` (for an async-iterator) then + // just grab its type argument. + var getIteratorType = isAsyncIterator ? getGlobalAsyncIteratorType : getGlobalIteratorType; + if (isReferenceToType(type, getIteratorType(/*reportErrors*/ false))) { + return isAsyncIterator + ? typeAsIterator.iteratedTypeOfAsyncIterator = type.typeArguments[0] + : typeAsIterator.iteratedTypeOfIterator = type.typeArguments[0]; + } + // Both async and non-async iterators must have a `next` method. + var nextMethod = getTypeOfPropertyOfType(type, "next"); + if (isTypeAny(nextMethod)) { + return undefined; + } + var nextMethodSignatures = nextMethod ? getSignaturesOfType(nextMethod, 0 /* Call */) : ts.emptyArray; + if (nextMethodSignatures.length === 0) { + if (errorNode) { + error(errorNode, isAsyncIterator + ? ts.Diagnostics.An_async_iterator_must_have_a_next_method + : ts.Diagnostics.An_iterator_must_have_a_next_method); + } + return undefined; + } + var nextResult = getUnionType(ts.map(nextMethodSignatures, getReturnTypeOfSignature), 2 /* Subtype */); + if (isTypeAny(nextResult)) { + return undefined; + } + // For an async iterator, we must get the awaited type of the return type. + if (isAsyncIterator) { + nextResult = getAwaitedTypeOfPromise(nextResult, errorNode, ts.Diagnostics.The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property); + if (isTypeAny(nextResult)) { + return undefined; + } + } + var nextValue = nextResult && getTypeOfPropertyOfType(nextResult, "value"); + if (!nextValue) { + if (errorNode) { + error(errorNode, isAsyncIterator + ? ts.Diagnostics.The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property + : ts.Diagnostics.The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property); + } + return undefined; + } + return isAsyncIterator + ? typeAsIterator.iteratedTypeOfAsyncIterator = nextValue + : typeAsIterator.iteratedTypeOfIterator = nextValue; + } + /** + * A generator may have a return type of `Iterator`, `Iterable`, or + * `IterableIterator`. An async generator may have a return type of `AsyncIterator`, + * `AsyncIterable`, or `AsyncIterableIterator`. This function can be used to extract + * the iterated type from this return type for contextual typing and verifying signatures. + */ + function getIteratedTypeOfGenerator(returnType, isAsyncGenerator) { + if (isTypeAny(returnType)) { + return undefined; + } + return getIteratedTypeOfIterable(returnType, /*errorNode*/ undefined, /*allowAsyncIterables*/ isAsyncGenerator, /*allowSyncIterables*/ !isAsyncGenerator, /*checkAssignability*/ false) + || getIteratedTypeOfIterator(returnType, /*errorNode*/ undefined, isAsyncGenerator); + } + function checkBreakOrContinueStatement(node) { + // Grammar checking + if (!checkGrammarStatementInAmbientContext(node)) + checkGrammarBreakOrContinueStatement(node); + // TODO: Check that target label is valid + } + function isUnwrappedReturnTypeVoidOrAny(func, returnType) { + var unwrappedReturnType = (ts.getFunctionFlags(func) & 3 /* AsyncGenerator */) === 2 /* Async */ + ? getPromisedTypeOfPromise(returnType) // Async function + : returnType; // AsyncGenerator function, Generator function, or normal function + return !!unwrappedReturnType && maybeTypeOfKind(unwrappedReturnType, 16384 /* Void */ | 3 /* AnyOrUnknown */); + } + function checkReturnStatement(node) { + // Grammar checking + if (checkGrammarStatementInAmbientContext(node)) { + return; + } + var func = ts.getContainingFunction(node); + if (!func) { + grammarErrorOnFirstToken(node, ts.Diagnostics.A_return_statement_can_only_be_used_within_a_function_body); + return; + } + var signature = getSignatureFromDeclaration(func); + var returnType = getReturnTypeOfSignature(signature); + var functionFlags = ts.getFunctionFlags(func); + var isGenerator = functionFlags & 1 /* Generator */; + if (strictNullChecks || node.expression || returnType.flags & 131072 /* Never */) { + var exprType = node.expression ? checkExpressionCached(node.expression) : undefinedType; + if (isGenerator) { // AsyncGenerator function or Generator function + // A generator does not need its return expressions checked against its return type. + // Instead, the yield expressions are checked against the element type. + // TODO: Check return types of generators when return type tracking is added + // for generators. + return; + } + else if (func.kind === 159 /* SetAccessor */) { + if (node.expression) { + error(node, ts.Diagnostics.Setters_cannot_return_a_value); + } + } + else if (func.kind === 157 /* Constructor */) { + if (node.expression && !checkTypeAssignableToAndOptionallyElaborate(exprType, returnType, node, node.expression)) { + error(node, ts.Diagnostics.Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class); + } + } + else if (getReturnTypeFromAnnotation(func)) { + if (functionFlags & 2 /* Async */) { // Async function + var promisedType = getPromisedTypeOfPromise(returnType); + var awaitedType = checkAwaitedType(exprType, node, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); + if (promisedType) { + // If the function has a return type, but promisedType is + // undefined, an error will be reported in checkAsyncFunctionReturnType + // so we don't need to report one here. + checkTypeAssignableTo(awaitedType, promisedType, node); + } + } + else { + checkTypeAssignableToAndOptionallyElaborate(exprType, returnType, node, node.expression); + } + } + } + else if (func.kind !== 157 /* Constructor */ && compilerOptions.noImplicitReturns && !isUnwrappedReturnTypeVoidOrAny(func, returnType) && !isGenerator) { + // The function has a return type, but the return statement doesn't have an expression. + error(node, ts.Diagnostics.Not_all_code_paths_return_a_value); + } + } + function checkWithStatement(node) { + // Grammar checking for withStatement + if (!checkGrammarStatementInAmbientContext(node)) { + if (node.flags & 16384 /* AwaitContext */) { + grammarErrorOnFirstToken(node, ts.Diagnostics.with_statements_are_not_allowed_in_an_async_function_block); + } + } + checkExpression(node.expression); + var sourceFile = ts.getSourceFileOfNode(node); + if (!hasParseDiagnostics(sourceFile)) { + var start = ts.getSpanOfTokenAtPosition(sourceFile, node.pos).start; + var end = node.statement.pos; + grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any); + } + } + function checkSwitchStatement(node) { + // Grammar checking + checkGrammarStatementInAmbientContext(node); + var firstDefaultClause; + var hasDuplicateDefaultClause = false; + var expressionType = checkExpression(node.expression); + var expressionIsLiteral = isLiteralType(expressionType); + ts.forEach(node.caseBlock.clauses, function (clause) { + // Grammar check for duplicate default clauses, skip if we already report duplicate default clause + if (clause.kind === 272 /* DefaultClause */ && !hasDuplicateDefaultClause) { + if (firstDefaultClause === undefined) { + firstDefaultClause = clause; + } + else { + var sourceFile = ts.getSourceFileOfNode(node); + var start = ts.skipTrivia(sourceFile.text, clause.pos); + var end = clause.statements.length > 0 ? clause.statements[0].pos : clause.end; + grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.A_default_clause_cannot_appear_more_than_once_in_a_switch_statement); + hasDuplicateDefaultClause = true; + } + } + if (produceDiagnostics && clause.kind === 271 /* CaseClause */) { + // TypeScript 1.0 spec (April 2014): 5.9 + // In a 'switch' statement, each 'case' expression must be of a type that is comparable + // to or from the type of the 'switch' expression. + var caseType = checkExpression(clause.expression); + var caseIsLiteral = isLiteralType(caseType); + var comparedExpressionType = expressionType; + if (!caseIsLiteral || !expressionIsLiteral) { + caseType = caseIsLiteral ? getBaseTypeOfLiteralType(caseType) : caseType; + comparedExpressionType = getBaseTypeOfLiteralType(expressionType); + } + if (!isTypeEqualityComparableTo(comparedExpressionType, caseType)) { + // expressionType is not comparable to caseType, try the reversed check and report errors if it fails + checkTypeComparableTo(caseType, comparedExpressionType, clause.expression, /*headMessage*/ undefined); + } + } + ts.forEach(clause.statements, checkSourceElement); + }); + if (node.caseBlock.locals) { + registerForUnusedIdentifiersCheck(node.caseBlock); + } + } + function checkLabeledStatement(node) { + // Grammar checking + if (!checkGrammarStatementInAmbientContext(node)) { + ts.findAncestor(node.parent, function (current) { + if (ts.isFunctionLike(current)) { + return "quit"; + } + if (current.kind === 233 /* LabeledStatement */ && current.label.escapedText === node.label.escapedText) { + grammarErrorOnNode(node.label, ts.Diagnostics.Duplicate_label_0, ts.getTextOfNode(node.label)); + return true; + } + return false; + }); + } + // ensure that label is unique + checkSourceElement(node.statement); + } + function checkThrowStatement(node) { + // Grammar checking + if (!checkGrammarStatementInAmbientContext(node)) { + if (node.expression === undefined) { + grammarErrorAfterFirstToken(node, ts.Diagnostics.Line_break_not_permitted_here); + } + } + if (node.expression) { + checkExpression(node.expression); + } + } + function checkTryStatement(node) { + // Grammar checking + checkGrammarStatementInAmbientContext(node); + checkBlock(node.tryBlock); + var catchClause = node.catchClause; + if (catchClause) { + // Grammar checking + if (catchClause.variableDeclaration) { + if (catchClause.variableDeclaration.type) { + grammarErrorOnFirstToken(catchClause.variableDeclaration.type, ts.Diagnostics.Catch_clause_variable_cannot_have_a_type_annotation); + } + else if (catchClause.variableDeclaration.initializer) { + grammarErrorOnFirstToken(catchClause.variableDeclaration.initializer, ts.Diagnostics.Catch_clause_variable_cannot_have_an_initializer); + } + else { + var blockLocals_1 = catchClause.block.locals; + if (blockLocals_1) { + ts.forEachKey(catchClause.locals, function (caughtName) { + var blockLocal = blockLocals_1.get(caughtName); + if (blockLocal && (blockLocal.flags & 2 /* BlockScopedVariable */) !== 0) { + grammarErrorOnNode(blockLocal.valueDeclaration, ts.Diagnostics.Cannot_redeclare_identifier_0_in_catch_clause, caughtName); + } + }); + } + } + } + checkBlock(catchClause.block); + } + if (node.finallyBlock) { + checkBlock(node.finallyBlock); + } + } + function checkIndexConstraints(type) { + var declaredNumberIndexer = getIndexDeclarationOfSymbol(type.symbol, 1 /* Number */); + var declaredStringIndexer = getIndexDeclarationOfSymbol(type.symbol, 0 /* String */); + var stringIndexType = getIndexTypeOfType(type, 0 /* String */); + var numberIndexType = getIndexTypeOfType(type, 1 /* Number */); + if (stringIndexType || numberIndexType) { + ts.forEach(getPropertiesOfObjectType(type), function (prop) { + var propType = getTypeOfSymbol(prop); + checkIndexConstraintForProperty(prop, propType, type, declaredStringIndexer, stringIndexType, 0 /* String */); + checkIndexConstraintForProperty(prop, propType, type, declaredNumberIndexer, numberIndexType, 1 /* Number */); + }); + var classDeclaration = type.symbol.valueDeclaration; + if (ts.getObjectFlags(type) & 1 /* Class */ && ts.isClassLike(classDeclaration)) { + for (var _i = 0, _a = classDeclaration.members; _i < _a.length; _i++) { + var member = _a[_i]; + // Only process instance properties with computed names here. + // Static properties cannot be in conflict with indexers, + // and properties with literal names were already checked. + if (!ts.hasModifier(member, 32 /* Static */) && hasNonBindableDynamicName(member)) { + var symbol = getSymbolOfNode(member); + var propType = getTypeOfSymbol(symbol); + checkIndexConstraintForProperty(symbol, propType, type, declaredStringIndexer, stringIndexType, 0 /* String */); + checkIndexConstraintForProperty(symbol, propType, type, declaredNumberIndexer, numberIndexType, 1 /* Number */); + } + } + } + } + var errorNode; + if (stringIndexType && numberIndexType) { + errorNode = declaredNumberIndexer || declaredStringIndexer; + // condition 'errorNode === undefined' may appear if types does not declare nor string neither number indexer + if (!errorNode && (ts.getObjectFlags(type) & 2 /* Interface */)) { + var someBaseTypeHasBothIndexers = ts.forEach(getBaseTypes(type), function (base) { return getIndexTypeOfType(base, 0 /* String */) && getIndexTypeOfType(base, 1 /* Number */); }); + errorNode = someBaseTypeHasBothIndexers ? undefined : type.symbol.declarations[0]; + } + } + if (errorNode && !isTypeAssignableTo(numberIndexType, stringIndexType)) { // TODO: GH#18217 + error(errorNode, ts.Diagnostics.Numeric_index_type_0_is_not_assignable_to_string_index_type_1, typeToString(numberIndexType), typeToString(stringIndexType)); + } + function checkIndexConstraintForProperty(prop, propertyType, containingType, indexDeclaration, indexType, indexKind) { + // ESSymbol properties apply to neither string nor numeric indexers. + if (!indexType || ts.isKnownSymbol(prop)) { + return; + } + var propDeclaration = prop.valueDeclaration; + var name = propDeclaration && ts.getNameOfDeclaration(propDeclaration); + // index is numeric and property name is not valid numeric literal + if (indexKind === 1 /* Number */ && !(name ? isNumericName(name) : isNumericLiteralName(prop.escapedName))) { + return; + } + // perform property check if property or indexer is declared in 'type' + // this allows us to rule out cases when both property and indexer are inherited from the base class + var errorNode; + if (propDeclaration && name && + (propDeclaration.kind === 204 /* BinaryExpression */ || + name.kind === 149 /* ComputedPropertyName */ || + prop.parent === containingType.symbol)) { + errorNode = propDeclaration; + } + else if (indexDeclaration) { + errorNode = indexDeclaration; + } + else if (ts.getObjectFlags(containingType) & 2 /* Interface */) { + // for interfaces property and indexer might be inherited from different bases + // check if any base class already has both property and indexer. + // check should be performed only if 'type' is the first type that brings property\indexer together + var someBaseClassHasBothPropertyAndIndexer = ts.forEach(getBaseTypes(containingType), function (base) { return getPropertyOfObjectType(base, prop.escapedName) && getIndexTypeOfType(base, indexKind); }); + errorNode = someBaseClassHasBothPropertyAndIndexer ? undefined : containingType.symbol.declarations[0]; + } + if (errorNode && !isTypeAssignableTo(propertyType, indexType)) { + var errorMessage = indexKind === 0 /* String */ + ? ts.Diagnostics.Property_0_of_type_1_is_not_assignable_to_string_index_type_2 + : ts.Diagnostics.Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2; + error(errorNode, errorMessage, symbolToString(prop), typeToString(propertyType), typeToString(indexType)); + } + } + } + function checkTypeNameIsReserved(name, message) { + // TS 1.0 spec (April 2014): 3.6.1 + // The predefined type keywords are reserved and cannot be used as names of user defined types. + switch (name.escapedText) { + case "any": + case "unknown": + case "number": + case "bigint": + case "boolean": + case "string": + case "symbol": + case "void": + case "object": + error(name, message, name.escapedText); + } + } + /** + * The name cannot be used as 'Object' of user defined types with special target. + */ + function checkClassNameCollisionWithObject(name) { + if (languageVersion === 1 /* ES5 */ && name.escapedText === "Object" + && moduleKind !== ts.ModuleKind.ES2015 && moduleKind !== ts.ModuleKind.ESNext) { + error(name, ts.Diagnostics.Class_name_cannot_be_Object_when_targeting_ES5_with_module_0, ts.ModuleKind[moduleKind]); // https://github.com/Microsoft/TypeScript/issues/17494 + } + } + /** + * Check each type parameter and check that type parameters have no duplicate type parameter declarations + */ + function checkTypeParameters(typeParameterDeclarations) { + if (typeParameterDeclarations) { + var seenDefault = false; + for (var i = 0; i < typeParameterDeclarations.length; i++) { + var node = typeParameterDeclarations[i]; + checkTypeParameter(node); + if (produceDiagnostics) { + if (node.default) { + seenDefault = true; + } + else if (seenDefault) { + error(node, ts.Diagnostics.Required_type_parameters_may_not_follow_optional_type_parameters); + } + for (var j = 0; j < i; j++) { + if (typeParameterDeclarations[j].symbol === node.symbol) { + error(node.name, ts.Diagnostics.Duplicate_identifier_0, ts.declarationNameToString(node.name)); + } + } + } + } + } + } + /** Check that type parameter lists are identical across multiple declarations */ + function checkTypeParameterListsIdentical(symbol) { + if (symbol.declarations.length === 1) { + return; + } + var links = getSymbolLinks(symbol); + if (!links.typeParametersChecked) { + links.typeParametersChecked = true; + var declarations = getClassOrInterfaceDeclarationsOfSymbol(symbol); + if (declarations.length <= 1) { + return; + } + var type = getDeclaredTypeOfSymbol(symbol); + if (!areTypeParametersIdentical(declarations, type.localTypeParameters)) { + // Report an error on every conflicting declaration. + var name = symbolToString(symbol); + for (var _i = 0, declarations_6 = declarations; _i < declarations_6.length; _i++) { + var declaration = declarations_6[_i]; + error(declaration.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_type_parameters, name); + } + } + } + } + function areTypeParametersIdentical(declarations, targetParameters) { + var maxTypeArgumentCount = ts.length(targetParameters); + var minTypeArgumentCount = getMinTypeArgumentCount(targetParameters); + for (var _i = 0, declarations_7 = declarations; _i < declarations_7.length; _i++) { + var declaration = declarations_7[_i]; + // If this declaration has too few or too many type parameters, we report an error + var sourceParameters = ts.getEffectiveTypeParameterDeclarations(declaration); + var numTypeParameters = sourceParameters.length; + if (numTypeParameters < minTypeArgumentCount || numTypeParameters > maxTypeArgumentCount) { + return false; + } + for (var i = 0; i < numTypeParameters; i++) { + var source = sourceParameters[i]; + var target = targetParameters[i]; + // If the type parameter node does not have the same as the resolved type + // parameter at this position, we report an error. + if (source.name.escapedText !== target.symbol.escapedName) { + return false; + } + // If the type parameter node does not have an identical constraint as the resolved + // type parameter at this position, we report an error. + var constraint = ts.getEffectiveConstraintOfTypeParameter(source); + var sourceConstraint = constraint && getTypeFromTypeNode(constraint); + var targetConstraint = getConstraintOfTypeParameter(target); + if (sourceConstraint) { + // relax check if later interface augmentation has no constraint + if (!targetConstraint || !isTypeIdenticalTo(sourceConstraint, targetConstraint)) { + return false; + } + } + // If the type parameter node has a default and it is not identical to the default + // for the type parameter at this position, we report an error. + var sourceDefault = source.default && getTypeFromTypeNode(source.default); + var targetDefault = getDefaultFromTypeParameter(target); + if (sourceDefault && targetDefault && !isTypeIdenticalTo(sourceDefault, targetDefault)) { + return false; + } + } + } + return true; + } + function checkClassExpression(node) { + checkClassLikeDeclaration(node); + checkNodeDeferred(node); + return getTypeOfSymbol(getSymbolOfNode(node)); + } + function checkClassExpressionDeferred(node) { + ts.forEach(node.members, checkSourceElement); + registerForUnusedIdentifiersCheck(node); + } + function checkClassDeclaration(node) { + if (!node.name && !ts.hasModifier(node, 512 /* Default */)) { + grammarErrorOnFirstToken(node, ts.Diagnostics.A_class_declaration_without_the_default_modifier_must_have_a_name); + } + checkClassLikeDeclaration(node); + ts.forEach(node.members, checkSourceElement); + registerForUnusedIdentifiersCheck(node); + } + function checkClassLikeDeclaration(node) { + checkGrammarClassLikeDeclaration(node); + checkDecorators(node); + if (node.name) { + checkTypeNameIsReserved(node.name, ts.Diagnostics.Class_name_cannot_be_0); + checkCollisionWithRequireExportsInGeneratedCode(node, node.name); + checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); + if (!(node.flags & 4194304 /* Ambient */)) { + checkClassNameCollisionWithObject(node.name); + } + } + checkTypeParameters(ts.getEffectiveTypeParameterDeclarations(node)); + checkExportsOnMergedDeclarations(node); + var symbol = getSymbolOfNode(node); + var type = getDeclaredTypeOfSymbol(symbol); + var typeWithThis = getTypeWithThisArgument(type); + var staticType = getTypeOfSymbol(symbol); + checkTypeParameterListsIdentical(symbol); + checkClassForDuplicateDeclarations(node); + // Only check for reserved static identifiers on non-ambient context. + if (!(node.flags & 4194304 /* Ambient */)) { + checkClassForStaticPropertyNameConflicts(node); + } + var baseTypeNode = ts.getEffectiveBaseTypeNode(node); + if (baseTypeNode) { + if (languageVersion < 2 /* ES2015 */) { + checkExternalEmitHelpers(baseTypeNode.parent, 1 /* Extends */); + } + var baseTypes = getBaseTypes(type); + if (baseTypes.length && produceDiagnostics) { + var baseType_1 = baseTypes[0]; + var baseConstructorType = getBaseConstructorTypeOfClass(type); + var staticBaseType = getApparentType(baseConstructorType); + checkBaseTypeAccessibility(staticBaseType, baseTypeNode); + checkSourceElement(baseTypeNode.expression); + var extendsNode = ts.getClassExtendsHeritageElement(node); + if (extendsNode && extendsNode !== baseTypeNode) { + checkExpression(extendsNode.expression); + } + if (ts.some(baseTypeNode.typeArguments)) { + ts.forEach(baseTypeNode.typeArguments, checkSourceElement); + for (var _i = 0, _a = getConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments, baseTypeNode); _i < _a.length; _i++) { + var constructor = _a[_i]; + if (!checkTypeArgumentConstraints(baseTypeNode, constructor.typeParameters)) { + break; + } + } + } + var baseWithThis = getTypeWithThisArgument(baseType_1, type.thisType); + if (!checkTypeAssignableTo(typeWithThis, baseWithThis, /*errorNode*/ undefined)) { + issueMemberSpecificError(node, typeWithThis, baseWithThis, ts.Diagnostics.Class_0_incorrectly_extends_base_class_1); + } + else { + // Report static side error only when instance type is assignable + checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, ts.Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1); + } + if (baseConstructorType.flags & 8650752 /* TypeVariable */ && !isMixinConstructorType(staticType)) { + error(node.name || node, ts.Diagnostics.A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any); + } + if (!(staticBaseType.symbol && staticBaseType.symbol.flags & 32 /* Class */) && !(baseConstructorType.flags & 8650752 /* TypeVariable */)) { + // When the static base type is a "class-like" constructor function (but not actually a class), we verify + // that all instantiated base constructor signatures return the same type. We can simply compare the type + // references (as opposed to checking the structure of the types) because elsewhere we have already checked + // that the base type is a class or interface type (and not, for example, an anonymous object type). + // (Javascript constructor functions have this property trivially true since their return type is ignored.) + var constructors = getInstantiatedConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments, baseTypeNode); + if (ts.forEach(constructors, function (sig) { return !isJSConstructor(sig.declaration) && getReturnTypeOfSignature(sig) !== baseType_1; })) { + error(baseTypeNode.expression, ts.Diagnostics.Base_constructors_must_all_have_the_same_return_type); + } + } + checkKindsOfPropertyMemberOverrides(type, baseType_1); + } + } + var implementedTypeNodes = ts.getClassImplementsHeritageClauseElements(node); + if (implementedTypeNodes) { + for (var _b = 0, implementedTypeNodes_1 = implementedTypeNodes; _b < implementedTypeNodes_1.length; _b++) { + var typeRefNode = implementedTypeNodes_1[_b]; + if (!ts.isEntityNameExpression(typeRefNode.expression)) { + error(typeRefNode.expression, ts.Diagnostics.A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments); + } + checkTypeReferenceNode(typeRefNode); + if (produceDiagnostics) { + var t = getTypeFromTypeNode(typeRefNode); + if (t !== errorType) { + if (isValidBaseType(t)) { + var genericDiag = t.symbol && t.symbol.flags & 32 /* Class */ ? + ts.Diagnostics.Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass : + ts.Diagnostics.Class_0_incorrectly_implements_interface_1; + var baseWithThis = getTypeWithThisArgument(t, type.thisType); + if (!checkTypeAssignableTo(typeWithThis, baseWithThis, /*errorNode*/ undefined)) { + issueMemberSpecificError(node, typeWithThis, baseWithThis, genericDiag); + } + } + else { + error(typeRefNode, ts.Diagnostics.A_class_can_only_implement_an_object_type_or_intersection_of_object_types_with_statically_known_members); + } + } + } + } + } + if (produceDiagnostics) { + checkIndexConstraints(type); + checkTypeForDuplicateIndexSignatures(node); + checkPropertyInitialization(node); + } + } + function issueMemberSpecificError(node, typeWithThis, baseWithThis, broadDiag) { + // iterate over all implemented properties and issue errors on each one which isn't compatible, rather than the class as a whole, if possible + var issuedMemberError = false; + var _loop_8 = function (member) { + if (ts.hasStaticModifier(member)) { + return "continue"; + } + var declaredProp = member.name && getSymbolAtLocation(member.name) || getSymbolAtLocation(member); + if (declaredProp) { + var prop = getPropertyOfType(typeWithThis, declaredProp.escapedName); + var baseProp = getPropertyOfType(baseWithThis, declaredProp.escapedName); + if (prop && baseProp) { + var rootChain = function () { return ts.chainDiagnosticMessages( + /*details*/ undefined, ts.Diagnostics.Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2, symbolToString(declaredProp), typeToString(typeWithThis), typeToString(baseWithThis)); }; + if (!checkTypeAssignableTo(getTypeOfSymbol(prop), getTypeOfSymbol(baseProp), member.name || member, /*message*/ undefined, rootChain)) { + issuedMemberError = true; + } + } + } + }; + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + _loop_8(member); + } + if (!issuedMemberError) { + // check again with diagnostics to generate a less-specific error + checkTypeAssignableTo(typeWithThis, baseWithThis, node.name || node, broadDiag); + } + } + function checkBaseTypeAccessibility(type, node) { + var signatures = getSignaturesOfType(type, 1 /* Construct */); + if (signatures.length) { + var declaration = signatures[0].declaration; + if (declaration && ts.hasModifier(declaration, 8 /* Private */)) { + var typeClassDeclaration = ts.getClassLikeDeclarationOfSymbol(type.symbol); + if (!isNodeWithinClass(node, typeClassDeclaration)) { + error(node, ts.Diagnostics.Cannot_extend_a_class_0_Class_constructor_is_marked_as_private, getFullyQualifiedName(type.symbol)); + } + } + } + } + function getTargetSymbol(s) { + // if symbol is instantiated its flags are not copied from the 'target' + // so we'll need to get back original 'target' symbol to work with correct set of flags + return ts.getCheckFlags(s) & 1 /* Instantiated */ ? s.target : s; + } + function getClassOrInterfaceDeclarationsOfSymbol(symbol) { + return ts.filter(symbol.declarations, function (d) { + return d.kind === 240 /* ClassDeclaration */ || d.kind === 241 /* InterfaceDeclaration */; + }); + } + function checkKindsOfPropertyMemberOverrides(type, baseType) { + // TypeScript 1.0 spec (April 2014): 8.2.3 + // A derived class inherits all members from its base class it doesn't override. + // Inheritance means that a derived class implicitly contains all non - overridden members of the base class. + // Both public and private property members are inherited, but only public property members can be overridden. + // A property member in a derived class is said to override a property member in a base class + // when the derived class property member has the same name and kind(instance or static) + // as the base class property member. + // The type of an overriding property member must be assignable(section 3.8.4) + // to the type of the overridden property member, or otherwise a compile - time error occurs. + // Base class instance member functions can be overridden by derived class instance member functions, + // but not by other kinds of members. + // Base class instance member variables and accessors can be overridden by + // derived class instance member variables and accessors, but not by other kinds of members. + // NOTE: assignability is checked in checkClassDeclaration + var baseProperties = getPropertiesOfType(baseType); + for (var _i = 0, baseProperties_1 = baseProperties; _i < baseProperties_1.length; _i++) { + var baseProperty = baseProperties_1[_i]; + var base = getTargetSymbol(baseProperty); + if (base.flags & 4194304 /* Prototype */) { + continue; + } + var derived = getTargetSymbol(getPropertyOfObjectType(type, base.escapedName)); // TODO: GH#18217 + var baseDeclarationFlags = ts.getDeclarationModifierFlagsFromSymbol(base); + ts.Debug.assert(!!derived, "derived should point to something, even if it is the base class' declaration."); + if (derived) { + // In order to resolve whether the inherited method was overridden in the base class or not, + // we compare the Symbols obtained. Since getTargetSymbol returns the symbol on the *uninstantiated* + // type declaration, derived and base resolve to the same symbol even in the case of generic classes. + if (derived === base) { + // derived class inherits base without override/redeclaration + var derivedClassDecl = ts.getClassLikeDeclarationOfSymbol(type.symbol); + // It is an error to inherit an abstract member without implementing it or being declared abstract. + // If there is no declaration for the derived class (as in the case of class expressions), + // then the class cannot be declared abstract. + if (baseDeclarationFlags & 128 /* Abstract */ && (!derivedClassDecl || !ts.hasModifier(derivedClassDecl, 128 /* Abstract */))) { + if (derivedClassDecl.kind === 209 /* ClassExpression */) { + error(derivedClassDecl, ts.Diagnostics.Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1, symbolToString(baseProperty), typeToString(baseType)); + } + else { + error(derivedClassDecl, ts.Diagnostics.Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2, typeToString(type), symbolToString(baseProperty), typeToString(baseType)); + } + } + } + else { + // derived overrides base. + var derivedDeclarationFlags = ts.getDeclarationModifierFlagsFromSymbol(derived); + if (baseDeclarationFlags & 8 /* Private */ || derivedDeclarationFlags & 8 /* Private */) { + // either base or derived property is private - not override, skip it + continue; + } + if (isPrototypeProperty(base) || base.flags & 98308 /* PropertyOrAccessor */ && derived.flags & 98308 /* PropertyOrAccessor */) { + // method is overridden with method or property/accessor is overridden with property/accessor - correct case + continue; + } + var errorMessage = void 0; + if (isPrototypeProperty(base)) { + if (derived.flags & 98304 /* Accessor */) { + errorMessage = ts.Diagnostics.Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor; + } + else { + errorMessage = ts.Diagnostics.Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_property; + } + } + else if (base.flags & 98304 /* Accessor */) { + errorMessage = ts.Diagnostics.Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function; + } + else { + errorMessage = ts.Diagnostics.Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_function; + } + error(ts.getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage, typeToString(baseType), symbolToString(base), typeToString(type)); + } + } + } + } + function checkInheritedPropertiesAreIdentical(type, typeNode) { + var baseTypes = getBaseTypes(type); + if (baseTypes.length < 2) { + return true; + } + var seen = ts.createUnderscoreEscapedMap(); + ts.forEach(resolveDeclaredMembers(type).declaredProperties, function (p) { seen.set(p.escapedName, { prop: p, containingType: type }); }); + var ok = true; + for (var _i = 0, baseTypes_2 = baseTypes; _i < baseTypes_2.length; _i++) { + var base = baseTypes_2[_i]; + var properties = getPropertiesOfType(getTypeWithThisArgument(base, type.thisType)); + for (var _a = 0, properties_7 = properties; _a < properties_7.length; _a++) { + var prop = properties_7[_a]; + var existing = seen.get(prop.escapedName); + if (!existing) { + seen.set(prop.escapedName, { prop: prop, containingType: base }); + } + else { + var isInheritedProperty = existing.containingType !== type; + if (isInheritedProperty && !isPropertyIdenticalTo(existing.prop, prop)) { + ok = false; + var typeName1 = typeToString(existing.containingType); + var typeName2 = typeToString(base); + var errorInfo = ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Named_property_0_of_types_1_and_2_are_not_identical, symbolToString(prop), typeName1, typeName2); + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Interface_0_cannot_simultaneously_extend_types_1_and_2, typeToString(type), typeName1, typeName2); + diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(typeNode, errorInfo)); + } + } + } + } + return ok; + } + function checkPropertyInitialization(node) { + if (!strictNullChecks || !strictPropertyInitialization || node.flags & 4194304 /* Ambient */) { + return; + } + var constructor = findConstructorDeclaration(node); + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + if (isInstancePropertyWithoutInitializer(member)) { + var propName = member.name; + if (ts.isIdentifier(propName)) { + var type = getTypeOfSymbol(getSymbolOfNode(member)); + if (!(type.flags & 3 /* AnyOrUnknown */ || getFalsyFlags(type) & 32768 /* Undefined */)) { + if (!constructor || !isPropertyInitializedInConstructor(propName, type, constructor)) { + error(member.name, ts.Diagnostics.Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor, ts.declarationNameToString(propName)); + } + } + } + } + } + } + function isInstancePropertyWithoutInitializer(node) { + return node.kind === 154 /* PropertyDeclaration */ && + !ts.hasModifier(node, 32 /* Static */ | 128 /* Abstract */) && + !node.exclamationToken && + !node.initializer; + } + function isPropertyInitializedInConstructor(propName, propType, constructor) { + var reference = ts.createPropertyAccess(ts.createThis(), propName); + reference.expression.parent = reference; + reference.parent = constructor; + reference.flowNode = constructor.returnFlowNode; + var flowType = getFlowTypeOfReference(reference, propType, getOptionalType(propType)); + return !(getFalsyFlags(flowType) & 32768 /* Undefined */); + } + function checkInterfaceDeclaration(node) { + // Grammar checking + if (!checkGrammarDecoratorsAndModifiers(node)) + checkGrammarInterfaceDeclaration(node); + checkTypeParameters(node.typeParameters); + if (produceDiagnostics) { + checkTypeNameIsReserved(node.name, ts.Diagnostics.Interface_name_cannot_be_0); + checkExportsOnMergedDeclarations(node); + var symbol = getSymbolOfNode(node); + checkTypeParameterListsIdentical(symbol); + // Only check this symbol once + var firstInterfaceDecl = ts.getDeclarationOfKind(symbol, 241 /* InterfaceDeclaration */); + if (node === firstInterfaceDecl) { + var type = getDeclaredTypeOfSymbol(symbol); + var typeWithThis = getTypeWithThisArgument(type); + // run subsequent checks only if first set succeeded + if (checkInheritedPropertiesAreIdentical(type, node.name)) { + for (var _i = 0, _a = getBaseTypes(type); _i < _a.length; _i++) { + var baseType = _a[_i]; + checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(baseType, type.thisType), node.name, ts.Diagnostics.Interface_0_incorrectly_extends_interface_1); + } + checkIndexConstraints(type); + } + } + checkObjectTypeForDuplicateDeclarations(node); + } + ts.forEach(ts.getInterfaceBaseTypeNodes(node), function (heritageElement) { + if (!ts.isEntityNameExpression(heritageElement.expression)) { + error(heritageElement.expression, ts.Diagnostics.An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments); + } + checkTypeReferenceNode(heritageElement); + }); + ts.forEach(node.members, checkSourceElement); + if (produceDiagnostics) { + checkTypeForDuplicateIndexSignatures(node); + registerForUnusedIdentifiersCheck(node); + } + } + function checkTypeAliasDeclaration(node) { + // Grammar checking + checkGrammarDecoratorsAndModifiers(node); + checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_alias_name_cannot_be_0); + checkTypeParameters(node.typeParameters); + checkSourceElement(node.type); + registerForUnusedIdentifiersCheck(node); + } + function computeEnumMemberValues(node) { + var nodeLinks = getNodeLinks(node); + if (!(nodeLinks.flags & 16384 /* EnumValuesComputed */)) { + nodeLinks.flags |= 16384 /* EnumValuesComputed */; + var autoValue = 0; + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + var value = computeMemberValue(member, autoValue); + getNodeLinks(member).enumMemberValue = value; + autoValue = typeof value === "number" ? value + 1 : undefined; + } + } + } + function computeMemberValue(member, autoValue) { + if (isComputedNonLiteralName(member.name)) { + error(member.name, ts.Diagnostics.Computed_property_names_are_not_allowed_in_enums); + } + else { + var text = ts.getTextOfPropertyName(member.name); + if (isNumericLiteralName(text) && !isInfinityOrNaNString(text)) { + error(member.name, ts.Diagnostics.An_enum_member_cannot_have_a_numeric_name); + } + } + if (member.initializer) { + return computeConstantValue(member); + } + // In ambient enum declarations that specify no const modifier, enum member declarations that omit + // a value are considered computed members (as opposed to having auto-incremented values). + if (member.parent.flags & 4194304 /* Ambient */ && !ts.isEnumConst(member.parent)) { + return undefined; + } + // If the member declaration specifies no value, the member is considered a constant enum member. + // If the member is the first member in the enum declaration, it is assigned the value zero. + // Otherwise, it is assigned the value of the immediately preceding member plus one, and an error + // occurs if the immediately preceding member is not a constant enum member. + if (autoValue !== undefined) { + return autoValue; + } + error(member.name, ts.Diagnostics.Enum_member_must_have_initializer); + return undefined; + } + function computeConstantValue(member) { + var enumKind = getEnumKind(getSymbolOfNode(member.parent)); + var isConstEnum = ts.isEnumConst(member.parent); + var initializer = member.initializer; + var value = enumKind === 1 /* Literal */ && !isLiteralEnumMember(member) ? undefined : evaluate(initializer); + if (value !== undefined) { + if (isConstEnum && typeof value === "number" && !isFinite(value)) { + error(initializer, isNaN(value) ? + ts.Diagnostics.const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN : + ts.Diagnostics.const_enum_member_initializer_was_evaluated_to_a_non_finite_value); + } + } + else if (enumKind === 1 /* Literal */) { + error(initializer, ts.Diagnostics.Computed_values_are_not_permitted_in_an_enum_with_string_valued_members); + return 0; + } + else if (isConstEnum) { + error(initializer, ts.Diagnostics.In_const_enum_declarations_member_initializer_must_be_constant_expression); + } + else if (member.parent.flags & 4194304 /* Ambient */) { + error(initializer, ts.Diagnostics.In_ambient_enum_declarations_member_initializer_must_be_constant_expression); + } + else { + // Only here do we need to check that the initializer is assignable to the enum type. + checkTypeAssignableTo(checkExpression(initializer), getDeclaredTypeOfSymbol(getSymbolOfNode(member.parent)), initializer, /*headMessage*/ undefined); + } + return value; + function evaluate(expr) { + switch (expr.kind) { + case 202 /* PrefixUnaryExpression */: + var value_2 = evaluate(expr.operand); + if (typeof value_2 === "number") { + switch (expr.operator) { + case 38 /* PlusToken */: return value_2; + case 39 /* MinusToken */: return -value_2; + case 53 /* TildeToken */: return ~value_2; + } + } + break; + case 204 /* BinaryExpression */: + var left = evaluate(expr.left); + var right = evaluate(expr.right); + if (typeof left === "number" && typeof right === "number") { + switch (expr.operatorToken.kind) { + case 50 /* BarToken */: return left | right; + case 49 /* AmpersandToken */: return left & right; + case 47 /* GreaterThanGreaterThanToken */: return left >> right; + case 48 /* GreaterThanGreaterThanGreaterThanToken */: return left >>> right; + case 46 /* LessThanLessThanToken */: return left << right; + case 51 /* CaretToken */: return left ^ right; + case 40 /* AsteriskToken */: return left * right; + case 42 /* SlashToken */: return left / right; + case 38 /* PlusToken */: return left + right; + case 39 /* MinusToken */: return left - right; + case 43 /* PercentToken */: return left % right; + case 41 /* AsteriskAsteriskToken */: return Math.pow(left, right); + } + } + else if (typeof left === "string" && typeof right === "string" && expr.operatorToken.kind === 38 /* PlusToken */) { + return left + right; + } + break; + case 10 /* StringLiteral */: + return expr.text; + case 8 /* NumericLiteral */: + checkGrammarNumericLiteral(expr); + return +expr.text; + case 195 /* ParenthesizedExpression */: + return evaluate(expr.expression); + case 72 /* Identifier */: + var identifier = expr; + if (isInfinityOrNaNString(identifier.escapedText)) { + return +(identifier.escapedText); + } + return ts.nodeIsMissing(expr) ? 0 : evaluateEnumMember(expr, getSymbolOfNode(member.parent), identifier.escapedText); + case 190 /* ElementAccessExpression */: + case 189 /* PropertyAccessExpression */: + var ex = expr; + if (isConstantMemberAccess(ex)) { + var type = getTypeOfExpression(ex.expression); + if (type.symbol && type.symbol.flags & 384 /* Enum */) { + var name = void 0; + if (ex.kind === 189 /* PropertyAccessExpression */) { + name = ex.name.escapedText; + } + else { + var argument = ex.argumentExpression; + ts.Debug.assert(ts.isLiteralExpression(argument)); + name = ts.escapeLeadingUnderscores(argument.text); + } + return evaluateEnumMember(expr, type.symbol, name); + } + } + break; + } + return undefined; + } + function evaluateEnumMember(expr, enumSymbol, name) { + var memberSymbol = enumSymbol.exports.get(name); + if (memberSymbol) { + var declaration = memberSymbol.valueDeclaration; + if (declaration !== member) { + if (isBlockScopedNameDeclaredBeforeUse(declaration, member)) { + return getEnumMemberValue(declaration); + } + error(expr, ts.Diagnostics.A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums); + return 0; + } + } + return undefined; + } + } + function isConstantMemberAccess(node) { + return node.kind === 72 /* Identifier */ || + node.kind === 189 /* PropertyAccessExpression */ && isConstantMemberAccess(node.expression) || + node.kind === 190 /* ElementAccessExpression */ && isConstantMemberAccess(node.expression) && + node.argumentExpression.kind === 10 /* StringLiteral */; + } + function checkEnumDeclaration(node) { + if (!produceDiagnostics) { + return; + } + // Grammar checking + checkGrammarDecoratorsAndModifiers(node); + checkTypeNameIsReserved(node.name, ts.Diagnostics.Enum_name_cannot_be_0); + checkCollisionWithRequireExportsInGeneratedCode(node, node.name); + checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); + checkExportsOnMergedDeclarations(node); + computeEnumMemberValues(node); + var enumIsConst = ts.isEnumConst(node); + if (compilerOptions.isolatedModules && enumIsConst && node.flags & 4194304 /* Ambient */) { + error(node.name, ts.Diagnostics.Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided); + } + // Spec 2014 - Section 9.3: + // It isn't possible for one enum declaration to continue the automatic numbering sequence of another, + // and when an enum type has multiple declarations, only one declaration is permitted to omit a value + // for the first member. + // + // Only perform this check once per symbol + var enumSymbol = getSymbolOfNode(node); + var firstDeclaration = ts.getDeclarationOfKind(enumSymbol, node.kind); + if (node === firstDeclaration) { + if (enumSymbol.declarations.length > 1) { + // check that const is placed\omitted on all enum declarations + ts.forEach(enumSymbol.declarations, function (decl) { + if (ts.isEnumDeclaration(decl) && ts.isEnumConst(decl) !== enumIsConst) { + error(ts.getNameOfDeclaration(decl), ts.Diagnostics.Enum_declarations_must_all_be_const_or_non_const); + } + }); + } + var seenEnumMissingInitialInitializer_1 = false; + ts.forEach(enumSymbol.declarations, function (declaration) { + // return true if we hit a violation of the rule, false otherwise + if (declaration.kind !== 243 /* EnumDeclaration */) { + return false; + } + var enumDeclaration = declaration; + if (!enumDeclaration.members.length) { + return false; + } + var firstEnumMember = enumDeclaration.members[0]; + if (!firstEnumMember.initializer) { + if (seenEnumMissingInitialInitializer_1) { + error(firstEnumMember.name, ts.Diagnostics.In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enum_element); + } + else { + seenEnumMissingInitialInitializer_1 = true; + } + } + }); + } + } + function getFirstNonAmbientClassOrFunctionDeclaration(symbol) { + var declarations = symbol.declarations; + for (var _i = 0, declarations_8 = declarations; _i < declarations_8.length; _i++) { + var declaration = declarations_8[_i]; + if ((declaration.kind === 240 /* ClassDeclaration */ || + (declaration.kind === 239 /* FunctionDeclaration */ && ts.nodeIsPresent(declaration.body))) && + !(declaration.flags & 4194304 /* Ambient */)) { + return declaration; + } + } + return undefined; + } + function inSameLexicalScope(node1, node2) { + var container1 = ts.getEnclosingBlockScopeContainer(node1); + var container2 = ts.getEnclosingBlockScopeContainer(node2); + if (isGlobalSourceFile(container1)) { + return isGlobalSourceFile(container2); + } + else if (isGlobalSourceFile(container2)) { + return false; + } + else { + return container1 === container2; + } + } + function checkModuleDeclaration(node) { + if (produceDiagnostics) { + // Grammar checking + var isGlobalAugmentation = ts.isGlobalScopeAugmentation(node); + var inAmbientContext = node.flags & 4194304 /* Ambient */; + if (isGlobalAugmentation && !inAmbientContext) { + error(node.name, ts.Diagnostics.Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambient_context); + } + var isAmbientExternalModule = ts.isAmbientModule(node); + var contextErrorMessage = isAmbientExternalModule + ? ts.Diagnostics.An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file + : ts.Diagnostics.A_namespace_declaration_is_only_allowed_in_a_namespace_or_module; + if (checkGrammarModuleElementContext(node, contextErrorMessage)) { + // If we hit a module declaration in an illegal context, just bail out to avoid cascading errors. + return; + } + if (!checkGrammarDecoratorsAndModifiers(node)) { + if (!inAmbientContext && node.name.kind === 10 /* StringLiteral */) { + grammarErrorOnNode(node.name, ts.Diagnostics.Only_ambient_modules_can_use_quoted_names); + } + } + if (ts.isIdentifier(node.name)) { + checkCollisionWithRequireExportsInGeneratedCode(node, node.name); + checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); + } + checkExportsOnMergedDeclarations(node); + var symbol = getSymbolOfNode(node); + // The following checks only apply on a non-ambient instantiated module declaration. + if (symbol.flags & 512 /* ValueModule */ + && symbol.declarations.length > 1 + && !inAmbientContext + && isInstantiatedModule(node, !!compilerOptions.preserveConstEnums || !!compilerOptions.isolatedModules)) { + var firstNonAmbientClassOrFunc = getFirstNonAmbientClassOrFunctionDeclaration(symbol); + if (firstNonAmbientClassOrFunc) { + if (ts.getSourceFileOfNode(node) !== ts.getSourceFileOfNode(firstNonAmbientClassOrFunc)) { + error(node.name, ts.Diagnostics.A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merged); + } + else if (node.pos < firstNonAmbientClassOrFunc.pos) { + error(node.name, ts.Diagnostics.A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged); + } + } + // if the module merges with a class declaration in the same lexical scope, + // we need to track this to ensure the correct emit. + var mergedClass = ts.getDeclarationOfKind(symbol, 240 /* ClassDeclaration */); + if (mergedClass && + inSameLexicalScope(node, mergedClass)) { + getNodeLinks(node).flags |= 32768 /* LexicalModuleMergesWithClass */; + } + } + if (isAmbientExternalModule) { + if (ts.isExternalModuleAugmentation(node)) { + // body of the augmentation should be checked for consistency only if augmentation was applied to its target (either global scope or module) + // otherwise we'll be swamped in cascading errors. + // We can detect if augmentation was applied using following rules: + // - augmentation for a global scope is always applied + // - augmentation for some external module is applied if symbol for augmentation is merged (it was combined with target module). + var checkBody = isGlobalAugmentation || (getSymbolOfNode(node).flags & 33554432 /* Transient */); + if (checkBody && node.body) { + for (var _i = 0, _a = node.body.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + checkModuleAugmentationElement(statement, isGlobalAugmentation); + } + } + } + else if (isGlobalSourceFile(node.parent)) { + if (isGlobalAugmentation) { + error(node.name, ts.Diagnostics.Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_declarations); + } + else if (ts.isExternalModuleNameRelative(ts.getTextOfIdentifierOrLiteral(node.name))) { + error(node.name, ts.Diagnostics.Ambient_module_declaration_cannot_specify_relative_module_name); + } + } + else { + if (isGlobalAugmentation) { + error(node.name, ts.Diagnostics.Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_declarations); + } + else { + // Node is not an augmentation and is not located on the script level. + // This means that this is declaration of ambient module that is located in other module or namespace which is prohibited. + error(node.name, ts.Diagnostics.Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces); + } + } + } + } + if (node.body) { + checkSourceElement(node.body); + if (!ts.isGlobalScopeAugmentation(node)) { + registerForUnusedIdentifiersCheck(node); + } + } + } + function checkModuleAugmentationElement(node, isGlobalAugmentation) { + switch (node.kind) { + case 219 /* VariableStatement */: + // error each individual name in variable statement instead of marking the entire variable statement + for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + checkModuleAugmentationElement(decl, isGlobalAugmentation); + } + break; + case 254 /* ExportAssignment */: + case 255 /* ExportDeclaration */: + grammarErrorOnFirstToken(node, ts.Diagnostics.Exports_and_export_assignments_are_not_permitted_in_module_augmentations); + break; + case 248 /* ImportEqualsDeclaration */: + case 249 /* ImportDeclaration */: + grammarErrorOnFirstToken(node, ts.Diagnostics.Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_module); + break; + case 186 /* BindingElement */: + case 237 /* VariableDeclaration */: + var name = node.name; + if (ts.isBindingPattern(name)) { + for (var _b = 0, _c = name.elements; _b < _c.length; _b++) { + var el = _c[_b]; + // mark individual names in binding pattern + checkModuleAugmentationElement(el, isGlobalAugmentation); + } + break; + } + // falls through + case 240 /* ClassDeclaration */: + case 243 /* EnumDeclaration */: + case 239 /* FunctionDeclaration */: + case 241 /* InterfaceDeclaration */: + case 244 /* ModuleDeclaration */: + case 242 /* TypeAliasDeclaration */: + if (isGlobalAugmentation) { + return; + } + var symbol = getSymbolOfNode(node); + if (symbol) { + // module augmentations cannot introduce new names on the top level scope of the module + // this is done it two steps + // 1. quick check - if symbol for node is not merged - this is local symbol to this augmentation - report error + // 2. main check - report error if value declaration of the parent symbol is module augmentation) + var reportError = !(symbol.flags & 33554432 /* Transient */); + if (!reportError) { + // symbol should not originate in augmentation + reportError = !!symbol.parent && ts.isExternalModuleAugmentation(symbol.parent.declarations[0]); + } + } + break; + } + } + function getFirstIdentifier(node) { + switch (node.kind) { + case 72 /* Identifier */: + return node; + case 148 /* QualifiedName */: + do { + node = node.left; + } while (node.kind !== 72 /* Identifier */); + return node; + case 189 /* PropertyAccessExpression */: + do { + node = node.expression; + } while (node.kind !== 72 /* Identifier */); + return node; + } + } + function checkExternalImportOrExportDeclaration(node) { + var moduleName = ts.getExternalModuleName(node); + if (!moduleName || ts.nodeIsMissing(moduleName)) { + // Should be a parse error. + return false; + } + if (!ts.isStringLiteral(moduleName)) { + error(moduleName, ts.Diagnostics.String_literal_expected); + return false; + } + var inAmbientExternalModule = node.parent.kind === 245 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent); + if (node.parent.kind !== 279 /* SourceFile */ && !inAmbientExternalModule) { + error(moduleName, node.kind === 255 /* ExportDeclaration */ ? + ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace : + ts.Diagnostics.Import_declarations_in_a_namespace_cannot_reference_a_module); + return false; + } + if (inAmbientExternalModule && ts.isExternalModuleNameRelative(moduleName.text)) { + // we have already reported errors on top level imports\exports in external module augmentations in checkModuleDeclaration + // no need to do this again. + if (!isTopLevelInExternalModuleAugmentation(node)) { + // TypeScript 1.0 spec (April 2013): 12.1.6 + // An ExternalImportDeclaration in an AmbientExternalModuleDeclaration may reference + // other external modules only through top - level external module names. + // Relative external module names are not permitted. + error(node, ts.Diagnostics.Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relative_module_name); + return false; + } + } + return true; + } + function checkAliasSymbol(node) { + var symbol = getSymbolOfNode(node); + var target = resolveAlias(symbol); + if (target !== unknownSymbol) { + // For external modules symbol represent local symbol for an alias. + // This local symbol will merge any other local declarations (excluding other aliases) + // and symbol.flags will contains combined representation for all merged declaration. + // Based on symbol.flags we can compute a set of excluded meanings (meaning that resolved alias should not have, + // otherwise it will conflict with some local declaration). Note that in addition to normal flags we include matching SymbolFlags.Export* + // in order to prevent collisions with declarations that were exported from the current module (they still contribute to local names). + var excludedMeanings = (symbol.flags & (67220415 /* Value */ | 1048576 /* ExportValue */) ? 67220415 /* Value */ : 0) | + (symbol.flags & 67897832 /* Type */ ? 67897832 /* Type */ : 0) | + (symbol.flags & 1920 /* Namespace */ ? 1920 /* Namespace */ : 0); + if (target.flags & excludedMeanings) { + var message = node.kind === 257 /* ExportSpecifier */ ? + ts.Diagnostics.Export_declaration_conflicts_with_exported_declaration_of_0 : + ts.Diagnostics.Import_declaration_conflicts_with_local_declaration_of_0; + error(node, message, symbolToString(symbol)); + } + // Don't allow to re-export something with no value side when `--isolatedModules` is set. + if (compilerOptions.isolatedModules + && node.kind === 257 /* ExportSpecifier */ + && !(target.flags & 67220415 /* Value */) + && !(node.flags & 4194304 /* Ambient */)) { + error(node, ts.Diagnostics.Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided); + } + } + } + function checkImportBinding(node) { + checkCollisionWithRequireExportsInGeneratedCode(node, node.name); + checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); + checkAliasSymbol(node); + } + function checkImportDeclaration(node) { + if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_import_declaration_can_only_be_used_in_a_namespace_or_module)) { + // If we hit an import declaration in an illegal context, just bail out to avoid cascading errors. + return; + } + if (!checkGrammarDecoratorsAndModifiers(node) && ts.hasModifiers(node)) { + grammarErrorOnFirstToken(node, ts.Diagnostics.An_import_declaration_cannot_have_modifiers); + } + if (checkExternalImportOrExportDeclaration(node)) { + var importClause = node.importClause; + if (importClause) { + if (importClause.name) { + checkImportBinding(importClause); + } + if (importClause.namedBindings) { + if (importClause.namedBindings.kind === 251 /* NamespaceImport */) { + checkImportBinding(importClause.namedBindings); + } + else { + var moduleExisted = resolveExternalModuleName(node, node.moduleSpecifier); + if (moduleExisted) { + ts.forEach(importClause.namedBindings.elements, checkImportBinding); + } + } + } + } + } + } + function checkImportEqualsDeclaration(node) { + if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_import_declaration_can_only_be_used_in_a_namespace_or_module)) { + // If we hit an import declaration in an illegal context, just bail out to avoid cascading errors. + return; + } + checkGrammarDecoratorsAndModifiers(node); + if (ts.isInternalModuleImportEqualsDeclaration(node) || checkExternalImportOrExportDeclaration(node)) { + checkImportBinding(node); + if (ts.hasModifier(node, 1 /* Export */)) { + markExportAsReferenced(node); + } + if (node.moduleReference.kind !== 259 /* ExternalModuleReference */) { + var target = resolveAlias(getSymbolOfNode(node)); + if (target !== unknownSymbol) { + if (target.flags & 67220415 /* Value */) { + // Target is a value symbol, check that it is not hidden by a local declaration with the same name + var moduleName = getFirstIdentifier(node.moduleReference); + if (!(resolveEntityName(moduleName, 67220415 /* Value */ | 1920 /* Namespace */).flags & 1920 /* Namespace */)) { + error(moduleName, ts.Diagnostics.Module_0_is_hidden_by_a_local_declaration_with_the_same_name, ts.declarationNameToString(moduleName)); + } + } + if (target.flags & 67897832 /* Type */) { + checkTypeNameIsReserved(node.name, ts.Diagnostics.Import_name_cannot_be_0); + } + } + } + else { + if (moduleKind >= ts.ModuleKind.ES2015 && !(node.flags & 4194304 /* Ambient */)) { + // Import equals declaration is deprecated in es6 or above + grammarErrorOnNode(node, ts.Diagnostics.Import_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_import_Asterisk_as_ns_from_mod_import_a_from_mod_import_d_from_mod_or_another_module_format_instead); + } + } + } + } + function checkExportDeclaration(node) { + if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_export_declaration_can_only_be_used_in_a_module)) { + // If we hit an export in an illegal context, just bail out to avoid cascading errors. + return; + } + if (!checkGrammarDecoratorsAndModifiers(node) && ts.hasModifiers(node)) { + grammarErrorOnFirstToken(node, ts.Diagnostics.An_export_declaration_cannot_have_modifiers); + } + if (!node.moduleSpecifier || checkExternalImportOrExportDeclaration(node)) { + if (node.exportClause) { + // export { x, y } + // export { x, y } from "foo" + ts.forEach(node.exportClause.elements, checkExportSpecifier); + var inAmbientExternalModule = node.parent.kind === 245 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent); + var inAmbientNamespaceDeclaration = !inAmbientExternalModule && node.parent.kind === 245 /* ModuleBlock */ && + !node.moduleSpecifier && node.flags & 4194304 /* Ambient */; + if (node.parent.kind !== 279 /* SourceFile */ && !inAmbientExternalModule && !inAmbientNamespaceDeclaration) { + error(node, ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace); + } + } + else { + // export * from "foo" + var moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier); + if (moduleSymbol && hasExportAssignmentSymbol(moduleSymbol)) { + error(node.moduleSpecifier, ts.Diagnostics.Module_0_uses_export_and_cannot_be_used_with_export_Asterisk, symbolToString(moduleSymbol)); + } + if (moduleKind !== ts.ModuleKind.System && moduleKind !== ts.ModuleKind.ES2015 && moduleKind !== ts.ModuleKind.ESNext) { + checkExternalEmitHelpers(node, 32768 /* ExportStar */); + } + } + } + } + function checkGrammarModuleElementContext(node, errorMessage) { + var isInAppropriateContext = node.parent.kind === 279 /* SourceFile */ || node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 244 /* ModuleDeclaration */; + if (!isInAppropriateContext) { + grammarErrorOnFirstToken(node, errorMessage); + } + return !isInAppropriateContext; + } + function checkExportSpecifier(node) { + checkAliasSymbol(node); + if (ts.getEmitDeclarations(compilerOptions)) { + collectLinkedAliases(node.propertyName || node.name, /*setVisibility*/ true); + } + if (!node.parent.parent.moduleSpecifier) { + var exportedName = node.propertyName || node.name; + // find immediate value referenced by exported name (SymbolFlags.Alias is set so we don't chase down aliases) + var symbol = resolveName(exportedName, exportedName.escapedText, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, + /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); + if (symbol && (symbol === undefinedSymbol || isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { + error(exportedName, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, ts.idText(exportedName)); + } + else { + markExportAsReferenced(node); + } + } + } + function checkExportAssignment(node) { + if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_export_assignment_can_only_be_used_in_a_module)) { + // If we hit an export assignment in an illegal context, just bail out to avoid cascading errors. + return; + } + var container = node.parent.kind === 279 /* SourceFile */ ? node.parent : node.parent.parent; + if (container.kind === 244 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) { + if (node.isExportEquals) { + error(node, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_namespace); + } + else { + error(node, ts.Diagnostics.A_default_export_can_only_be_used_in_an_ECMAScript_style_module); + } + return; + } + // Grammar checking + if (!checkGrammarDecoratorsAndModifiers(node) && ts.hasModifiers(node)) { + grammarErrorOnFirstToken(node, ts.Diagnostics.An_export_assignment_cannot_have_modifiers); + } + if (node.expression.kind === 72 /* Identifier */) { + markExportAsReferenced(node); + if (ts.getEmitDeclarations(compilerOptions)) { + collectLinkedAliases(node.expression, /*setVisibility*/ true); + } + } + else { + checkExpressionCached(node.expression); + } + checkExternalModuleExports(container); + if ((node.flags & 4194304 /* Ambient */) && !ts.isEntityNameExpression(node.expression)) { + grammarErrorOnNode(node.expression, ts.Diagnostics.The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context); + } + if (node.isExportEquals && !(node.flags & 4194304 /* Ambient */)) { + if (moduleKind >= ts.ModuleKind.ES2015) { + // export assignment is not supported in es6 modules + grammarErrorOnNode(node, ts.Diagnostics.Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or_another_module_format_instead); + } + else if (moduleKind === ts.ModuleKind.System) { + // system modules does not support export assignment + grammarErrorOnNode(node, ts.Diagnostics.Export_assignment_is_not_supported_when_module_flag_is_system); + } + } + } + function hasExportedMembers(moduleSymbol) { + return ts.forEachEntry(moduleSymbol.exports, function (_, id) { return id !== "export="; }); + } + function checkExternalModuleExports(node) { + var moduleSymbol = getSymbolOfNode(node); + var links = getSymbolLinks(moduleSymbol); + if (!links.exportsChecked) { + var exportEqualsSymbol = moduleSymbol.exports.get("export="); + if (exportEqualsSymbol && hasExportedMembers(moduleSymbol)) { + var declaration = getDeclarationOfAliasSymbol(exportEqualsSymbol) || exportEqualsSymbol.valueDeclaration; + if (!isTopLevelInExternalModuleAugmentation(declaration) && !ts.isInJSFile(declaration)) { + error(declaration, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements); + } + } + // Checks for export * conflicts + var exports_1 = getExportsOfModule(moduleSymbol); + if (exports_1) { + exports_1.forEach(function (_a, id) { + var declarations = _a.declarations, flags = _a.flags; + if (id === "__export") { + return; + } + // ECMA262: 15.2.1.1 It is a Syntax Error if the ExportedNames of ModuleItemList contains any duplicate entries. + // (TS Exceptions: namespaces, function overloads, enums, and interfaces) + if (flags & (1920 /* Namespace */ | 64 /* Interface */ | 384 /* Enum */)) { + return; + } + var exportedDeclarationsCount = ts.countWhere(declarations, isNotOverloadAndNotAccessor); + if (flags & 524288 /* TypeAlias */ && exportedDeclarationsCount <= 2) { + // it is legal to merge type alias with other values + // so count should be either 1 (just type alias) or 2 (type alias + merged value) + return; + } + if (exportedDeclarationsCount > 1) { + for (var _i = 0, declarations_9 = declarations; _i < declarations_9.length; _i++) { + var declaration = declarations_9[_i]; + if (isNotOverload(declaration)) { + diagnostics.add(ts.createDiagnosticForNode(declaration, ts.Diagnostics.Cannot_redeclare_exported_variable_0, ts.unescapeLeadingUnderscores(id))); + } + } + } + }); + } + links.exportsChecked = true; + } + } + function isNotAccessor(declaration) { + // Accessors check for their own matching duplicates, and in contexts where they are valid, there are already duplicate identifier checks + return !ts.isAccessor(declaration); + } + function isNotOverload(declaration) { + return (declaration.kind !== 239 /* FunctionDeclaration */ && declaration.kind !== 156 /* MethodDeclaration */) || + !!declaration.body; + } + function checkSourceElement(node) { + if (!node) { + return; + } + if (ts.isInJSFile(node)) { + ts.forEach(node.jsDoc, function (_a) { + var tags = _a.tags; + return ts.forEach(tags, checkSourceElement); + }); + } + var kind = node.kind; + if (cancellationToken) { + // Only bother checking on a few construct kinds. We don't want to be excessively + // hitting the cancellation token on every node we check. + switch (kind) { + case 244 /* ModuleDeclaration */: + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + case 239 /* FunctionDeclaration */: + cancellationToken.throwIfCancellationRequested(); + } + } + switch (kind) { + case 150 /* TypeParameter */: + return checkTypeParameter(node); + case 151 /* Parameter */: + return checkParameter(node); + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + return checkPropertyDeclaration(node); + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 162 /* IndexSignature */: + return checkSignatureDeclaration(node); + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + return checkMethodDeclaration(node); + case 157 /* Constructor */: + return checkConstructorDeclaration(node); + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + return checkAccessorDeclaration(node); + case 164 /* TypeReference */: + return checkTypeReferenceNode(node); + case 163 /* TypePredicate */: + return checkTypePredicate(node); + case 167 /* TypeQuery */: + return checkTypeQuery(node); + case 168 /* TypeLiteral */: + return checkTypeLiteral(node); + case 169 /* ArrayType */: + return checkArrayType(node); + case 170 /* TupleType */: + return checkTupleType(node); + case 173 /* UnionType */: + case 174 /* IntersectionType */: + return checkUnionOrIntersectionType(node); + case 177 /* ParenthesizedType */: + case 171 /* OptionalType */: + case 172 /* RestType */: + return checkSourceElement(node.type); + case 178 /* ThisType */: + return checkThisType(node); + case 179 /* TypeOperator */: + return checkTypeOperator(node); + case 175 /* ConditionalType */: + return checkConditionalType(node); + case 176 /* InferType */: + return checkInferType(node); + case 183 /* ImportType */: + return checkImportType(node); + case 295 /* JSDocAugmentsTag */: + return checkJSDocAugmentsTag(node); + case 304 /* JSDocTypedefTag */: + case 297 /* JSDocCallbackTag */: + return checkJSDocTypeAliasTag(node); + case 303 /* JSDocTemplateTag */: + return checkJSDocTemplateTag(node); + case 302 /* JSDocTypeTag */: + return checkJSDocTypeTag(node); + case 299 /* JSDocParameterTag */: + return checkJSDocParameterTag(node); + case 289 /* JSDocFunctionType */: + checkJSDocFunctionType(node); + // falls through + case 287 /* JSDocNonNullableType */: + case 286 /* JSDocNullableType */: + case 284 /* JSDocAllType */: + case 285 /* JSDocUnknownType */: + case 292 /* JSDocTypeLiteral */: + checkJSDocTypeIsInJsFile(node); + ts.forEachChild(node, checkSourceElement); + return; + case 290 /* JSDocVariadicType */: + checkJSDocVariadicType(node); + return; + case 283 /* JSDocTypeExpression */: + return checkSourceElement(node.type); + case 180 /* IndexedAccessType */: + return checkIndexedAccessType(node); + case 181 /* MappedType */: + return checkMappedType(node); + case 239 /* FunctionDeclaration */: + return checkFunctionDeclaration(node); + case 218 /* Block */: + case 245 /* ModuleBlock */: + return checkBlock(node); + case 219 /* VariableStatement */: + return checkVariableStatement(node); + case 221 /* ExpressionStatement */: + return checkExpressionStatement(node); + case 222 /* IfStatement */: + return checkIfStatement(node); + case 223 /* DoStatement */: + return checkDoStatement(node); + case 224 /* WhileStatement */: + return checkWhileStatement(node); + case 225 /* ForStatement */: + return checkForStatement(node); + case 226 /* ForInStatement */: + return checkForInStatement(node); + case 227 /* ForOfStatement */: + return checkForOfStatement(node); + case 228 /* ContinueStatement */: + case 229 /* BreakStatement */: + return checkBreakOrContinueStatement(node); + case 230 /* ReturnStatement */: + return checkReturnStatement(node); + case 231 /* WithStatement */: + return checkWithStatement(node); + case 232 /* SwitchStatement */: + return checkSwitchStatement(node); + case 233 /* LabeledStatement */: + return checkLabeledStatement(node); + case 234 /* ThrowStatement */: + return checkThrowStatement(node); + case 235 /* TryStatement */: + return checkTryStatement(node); + case 237 /* VariableDeclaration */: + return checkVariableDeclaration(node); + case 186 /* BindingElement */: + return checkBindingElement(node); + case 240 /* ClassDeclaration */: + return checkClassDeclaration(node); + case 241 /* InterfaceDeclaration */: + return checkInterfaceDeclaration(node); + case 242 /* TypeAliasDeclaration */: + return checkTypeAliasDeclaration(node); + case 243 /* EnumDeclaration */: + return checkEnumDeclaration(node); + case 244 /* ModuleDeclaration */: + return checkModuleDeclaration(node); + case 249 /* ImportDeclaration */: + return checkImportDeclaration(node); + case 248 /* ImportEqualsDeclaration */: + return checkImportEqualsDeclaration(node); + case 255 /* ExportDeclaration */: + return checkExportDeclaration(node); + case 254 /* ExportAssignment */: + return checkExportAssignment(node); + case 220 /* EmptyStatement */: + case 236 /* DebuggerStatement */: + checkGrammarStatementInAmbientContext(node); + return; + case 258 /* MissingDeclaration */: + return checkMissingDeclaration(node); + } + } + function checkJSDocTypeIsInJsFile(node) { + if (!ts.isInJSFile(node)) { + grammarErrorOnNode(node, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments); + } + } + function checkJSDocVariadicType(node) { + checkJSDocTypeIsInJsFile(node); + checkSourceElement(node.type); + // Only legal location is in the *last* parameter tag or last parameter of a JSDoc function. + var parent = node.parent; + if (ts.isParameter(parent) && ts.isJSDocFunctionType(parent.parent)) { + if (ts.last(parent.parent.parameters) !== parent) { + error(node, ts.Diagnostics.A_rest_parameter_must_be_last_in_a_parameter_list); + } + return; + } + if (!ts.isJSDocTypeExpression(parent)) { + error(node, ts.Diagnostics.JSDoc_may_only_appear_in_the_last_parameter_of_a_signature); + } + var paramTag = node.parent.parent; + if (!ts.isJSDocParameterTag(paramTag)) { + error(node, ts.Diagnostics.JSDoc_may_only_appear_in_the_last_parameter_of_a_signature); + return; + } + var param = ts.getParameterSymbolFromJSDoc(paramTag); + if (!param) { + // We will error in `checkJSDocParameterTag`. + return; + } + var host = ts.getHostSignatureFromJSDoc(paramTag); + if (!host || ts.last(host.parameters).symbol !== param) { + error(node, ts.Diagnostics.A_rest_parameter_must_be_last_in_a_parameter_list); + } + } + function getTypeFromJSDocVariadicType(node) { + var type = getTypeFromTypeNode(node.type); + var parent = node.parent; + var paramTag = node.parent.parent; + if (ts.isJSDocTypeExpression(node.parent) && ts.isJSDocParameterTag(paramTag)) { + // Else we will add a diagnostic, see `checkJSDocVariadicType`. + var host_1 = ts.getHostSignatureFromJSDoc(paramTag); + if (host_1) { + /* + Only return an array type if the corresponding parameter is marked as a rest parameter, or if there are no parameters. + So in the following situation we will not create an array type: + /** @param {...number} a * / + function f(a) {} + Because `a` will just be of type `number | undefined`. A synthetic `...args` will also be added, which *will* get an array type. + */ + var lastParamDeclaration = ts.lastOrUndefined(host_1.parameters); + var symbol = ts.getParameterSymbolFromJSDoc(paramTag); + if (!lastParamDeclaration || + symbol && lastParamDeclaration.symbol === symbol && ts.isRestParameter(lastParamDeclaration)) { + return createArrayType(type); + } + } + } + if (ts.isParameter(parent) && ts.isJSDocFunctionType(parent.parent)) { + return createArrayType(type); + } + return addOptionality(type); + } + // Function and class expression bodies are checked after all statements in the enclosing body. This is + // to ensure constructs like the following are permitted: + // const foo = function () { + // const s = foo(); + // return "hello"; + // } + // Here, performing a full type check of the body of the function expression whilst in the process of + // determining the type of foo would cause foo to be given type any because of the recursive reference. + // Delaying the type check of the body ensures foo has been assigned a type. + function checkNodeDeferred(node) { + var enclosingFile = ts.getSourceFileOfNode(node); + var links = getNodeLinks(enclosingFile); + if (!(links.flags & 1 /* TypeChecked */)) { + links.deferredNodes = links.deferredNodes || ts.createMap(); + var id = "" + getNodeId(node); + links.deferredNodes.set(id, node); + } + } + function checkDeferredNodes(context) { + var links = getNodeLinks(context); + if (!links.deferredNodes) { + return; + } + links.deferredNodes.forEach(function (node) { + switch (node.kind) { + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + checkFunctionExpressionOrObjectLiteralMethodDeferred(node); + break; + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + checkAccessorDeclaration(node); + break; + case 209 /* ClassExpression */: + checkClassExpressionDeferred(node); + break; + case 261 /* JsxSelfClosingElement */: + checkJsxSelfClosingElementDeferred(node); + break; + case 260 /* JsxElement */: + checkJsxElementDeferred(node); + break; + } + }); + } + function checkSourceFile(node) { + ts.performance.mark("beforeCheck"); + checkSourceFileWorker(node); + ts.performance.mark("afterCheck"); + ts.performance.measure("Check", "beforeCheck", "afterCheck"); + } + function unusedIsError(kind) { + switch (kind) { + case 0 /* Local */: + return !!compilerOptions.noUnusedLocals; + case 1 /* Parameter */: + return !!compilerOptions.noUnusedParameters; + default: + return ts.Debug.assertNever(kind); + } + } + function getPotentiallyUnusedIdentifiers(sourceFile) { + return allPotentiallyUnusedIdentifiers.get(sourceFile.path) || ts.emptyArray; + } + // Fully type check a source file and collect the relevant diagnostics. + function checkSourceFileWorker(node) { + var links = getNodeLinks(node); + if (!(links.flags & 1 /* TypeChecked */)) { + if (ts.skipTypeChecking(node, compilerOptions)) { + return; + } + // Grammar checking + checkGrammarSourceFile(node); + ts.clear(potentialThisCollisions); + ts.clear(potentialNewTargetCollisions); + ts.forEach(node.statements, checkSourceElement); + checkSourceElement(node.endOfFileToken); + checkDeferredNodes(node); + if (ts.isExternalOrCommonJsModule(node)) { + registerForUnusedIdentifiersCheck(node); + } + if (!node.isDeclarationFile && (compilerOptions.noUnusedLocals || compilerOptions.noUnusedParameters)) { + checkUnusedIdentifiers(getPotentiallyUnusedIdentifiers(node), function (containingNode, kind, diag) { + if (!ts.containsParseError(containingNode) && unusedIsError(kind)) { + diagnostics.add(diag); + } + }); + } + if (ts.isExternalOrCommonJsModule(node)) { + checkExternalModuleExports(node); + } + if (potentialThisCollisions.length) { + ts.forEach(potentialThisCollisions, checkIfThisIsCapturedInEnclosingScope); + ts.clear(potentialThisCollisions); + } + if (potentialNewTargetCollisions.length) { + ts.forEach(potentialNewTargetCollisions, checkIfNewTargetIsCapturedInEnclosingScope); + ts.clear(potentialNewTargetCollisions); + } + links.flags |= 1 /* TypeChecked */; + } + } + function getDiagnostics(sourceFile, ct) { + try { + // Record the cancellation token so it can be checked later on during checkSourceElement. + // Do this in a finally block so we can ensure that it gets reset back to nothing after + // this call is done. + cancellationToken = ct; + return getDiagnosticsWorker(sourceFile); + } + finally { + cancellationToken = undefined; + } + } + function getDiagnosticsWorker(sourceFile) { + throwIfNonDiagnosticsProducing(); + if (sourceFile) { + // Some global diagnostics are deferred until they are needed and + // may not be reported in the firt call to getGlobalDiagnostics. + // We should catch these changes and report them. + var previousGlobalDiagnostics = diagnostics.getGlobalDiagnostics(); + var previousGlobalDiagnosticsSize = previousGlobalDiagnostics.length; + checkSourceFile(sourceFile); + var semanticDiagnostics = diagnostics.getDiagnostics(sourceFile.fileName); + var currentGlobalDiagnostics = diagnostics.getGlobalDiagnostics(); + if (currentGlobalDiagnostics !== previousGlobalDiagnostics) { + // If the arrays are not the same reference, new diagnostics were added. + var deferredGlobalDiagnostics = ts.relativeComplement(previousGlobalDiagnostics, currentGlobalDiagnostics, ts.compareDiagnostics); + return ts.concatenate(deferredGlobalDiagnostics, semanticDiagnostics); + } + else if (previousGlobalDiagnosticsSize === 0 && currentGlobalDiagnostics.length > 0) { + // If the arrays are the same reference, but the length has changed, a single + // new diagnostic was added as DiagnosticCollection attempts to reuse the + // same array. + return ts.concatenate(currentGlobalDiagnostics, semanticDiagnostics); + } + return semanticDiagnostics; + } + // Global diagnostics are always added when a file is not provided to + // getDiagnostics + ts.forEach(host.getSourceFiles(), checkSourceFile); + return diagnostics.getDiagnostics(); + } + function getGlobalDiagnostics() { + throwIfNonDiagnosticsProducing(); + return diagnostics.getGlobalDiagnostics(); + } + function throwIfNonDiagnosticsProducing() { + if (!produceDiagnostics) { + throw new Error("Trying to get diagnostics from a type checker that does not produce them."); + } + } + // Language service support + function getSymbolsInScope(location, meaning) { + if (location.flags & 8388608 /* InWithStatement */) { + // We cannot answer semantic questions within a with block, do not proceed any further + return []; + } + var symbols = ts.createSymbolTable(); + var isStatic = false; + populateSymbols(); + symbols.delete("this" /* This */); // Not a symbol, a keyword + return symbolsToArray(symbols); + function populateSymbols() { + while (location) { + if (location.locals && !isGlobalSourceFile(location)) { + copySymbols(location.locals, meaning); + } + switch (location.kind) { + case 279 /* SourceFile */: + if (!ts.isExternalOrCommonJsModule(location)) + break; + // falls through + case 244 /* ModuleDeclaration */: + copySymbols(getSymbolOfNode(location).exports, meaning & 2623475 /* ModuleMember */); + break; + case 243 /* EnumDeclaration */: + copySymbols(getSymbolOfNode(location).exports, meaning & 8 /* EnumMember */); + break; + case 209 /* ClassExpression */: + var className = location.name; + if (className) { + copySymbol(location.symbol, meaning); + } + // falls through + // this fall-through is necessary because we would like to handle + // type parameter inside class expression similar to how we handle it in classDeclaration and interface Declaration + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + // If we didn't come from static member of class or interface, + // add the type parameters into the symbol table + // (type parameters of classDeclaration/classExpression and interface are in member property of the symbol. + // Note: that the memberFlags come from previous iteration. + if (!isStatic) { + copySymbols(getMembersOfSymbol(getSymbolOfNode(location)), meaning & 67897832 /* Type */); + } + break; + case 196 /* FunctionExpression */: + var funcName = location.name; + if (funcName) { + copySymbol(location.symbol, meaning); + } + break; + } + if (ts.introducesArgumentsExoticObject(location)) { + copySymbol(argumentsSymbol, meaning); + } + isStatic = ts.hasModifier(location, 32 /* Static */); + location = location.parent; + } + copySymbols(globals, meaning); + } + /** + * Copy the given symbol into symbol tables if the symbol has the given meaning + * and it doesn't already existed in the symbol table + * @param key a key for storing in symbol table; if undefined, use symbol.name + * @param symbol the symbol to be added into symbol table + * @param meaning meaning of symbol to filter by before adding to symbol table + */ + function copySymbol(symbol, meaning) { + if (ts.getCombinedLocalAndExportSymbolFlags(symbol) & meaning) { + var id = symbol.escapedName; + // We will copy all symbol regardless of its reserved name because + // symbolsToArray will check whether the key is a reserved name and + // it will not copy symbol with reserved name to the array + if (!symbols.has(id)) { + symbols.set(id, symbol); + } + } + } + function copySymbols(source, meaning) { + if (meaning) { + source.forEach(function (symbol) { + copySymbol(symbol, meaning); + }); + } + } + } + function isTypeDeclarationName(name) { + return name.kind === 72 /* Identifier */ && + isTypeDeclaration(name.parent) && + name.parent.name === name; + } + function isTypeDeclaration(node) { + switch (node.kind) { + case 150 /* TypeParameter */: + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 243 /* EnumDeclaration */: + return true; + default: + return false; + } + } + // True if the given identifier is part of a type reference + function isTypeReferenceIdentifier(node) { + while (node.parent.kind === 148 /* QualifiedName */) { + node = node.parent; + } + return node.parent.kind === 164 /* TypeReference */; + } + function isHeritageClauseElementIdentifier(node) { + while (node.parent.kind === 189 /* PropertyAccessExpression */) { + node = node.parent; + } + return node.parent.kind === 211 /* ExpressionWithTypeArguments */; + } + function forEachEnclosingClass(node, callback) { + var result; + while (true) { + node = ts.getContainingClass(node); + if (!node) + break; + if (result = callback(node)) + break; + } + return result; + } + function isNodeUsedDuringClassInitialization(node) { + return !!ts.findAncestor(node, function (element) { + if (ts.isConstructorDeclaration(element) && ts.nodeIsPresent(element.body) || ts.isPropertyDeclaration(element)) { + return true; + } + else if (ts.isClassLike(element) || ts.isFunctionLikeDeclaration(element)) { + return "quit"; + } + return false; + }); + } + function isNodeWithinClass(node, classDeclaration) { + return !!forEachEnclosingClass(node, function (n) { return n === classDeclaration; }); + } + function getLeftSideOfImportEqualsOrExportAssignment(nodeOnRightSide) { + while (nodeOnRightSide.parent.kind === 148 /* QualifiedName */) { + nodeOnRightSide = nodeOnRightSide.parent; + } + if (nodeOnRightSide.parent.kind === 248 /* ImportEqualsDeclaration */) { + return nodeOnRightSide.parent.moduleReference === nodeOnRightSide ? nodeOnRightSide.parent : undefined; + } + if (nodeOnRightSide.parent.kind === 254 /* ExportAssignment */) { + return nodeOnRightSide.parent.expression === nodeOnRightSide ? nodeOnRightSide.parent : undefined; + } + return undefined; + } + function isInRightSideOfImportOrExportAssignment(node) { + return getLeftSideOfImportEqualsOrExportAssignment(node) !== undefined; + } + function getSpecialPropertyAssignmentSymbolFromEntityName(entityName) { + var specialPropertyAssignmentKind = ts.getAssignmentDeclarationKind(entityName.parent.parent); + switch (specialPropertyAssignmentKind) { + case 1 /* ExportsProperty */: + case 3 /* PrototypeProperty */: + return getSymbolOfNode(entityName.parent); + case 4 /* ThisProperty */: + case 2 /* ModuleExports */: + case 5 /* Property */: + return getSymbolOfNode(entityName.parent.parent); + } + } + function isImportTypeQualifierPart(node) { + var parent = node.parent; + while (ts.isQualifiedName(parent)) { + node = parent; + parent = parent.parent; + } + if (parent && parent.kind === 183 /* ImportType */ && parent.qualifier === node) { + return parent; + } + return undefined; + } + function getSymbolOfEntityNameOrPropertyAccessExpression(entityName) { + if (ts.isDeclarationName(entityName)) { + return getSymbolOfNode(entityName.parent); + } + if (ts.isInJSFile(entityName) && + entityName.parent.kind === 189 /* PropertyAccessExpression */ && + entityName.parent === entityName.parent.parent.left) { + // Check if this is a special property assignment + var specialPropertyAssignmentSymbol = getSpecialPropertyAssignmentSymbolFromEntityName(entityName); + if (specialPropertyAssignmentSymbol) { + return specialPropertyAssignmentSymbol; + } + } + if (entityName.parent.kind === 254 /* ExportAssignment */ && ts.isEntityNameExpression(entityName)) { + // Even an entity name expression that doesn't resolve as an entityname may still typecheck as a property access expression + var success = resolveEntityName(entityName, + /*all meanings*/ 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*ignoreErrors*/ true); + if (success && success !== unknownSymbol) { + return success; + } + } + else if (!ts.isPropertyAccessExpression(entityName) && isInRightSideOfImportOrExportAssignment(entityName)) { + // Since we already checked for ExportAssignment, this really could only be an Import + var importEqualsDeclaration = ts.getAncestor(entityName, 248 /* ImportEqualsDeclaration */); + ts.Debug.assert(importEqualsDeclaration !== undefined); + return getSymbolOfPartOfRightHandSideOfImportEquals(entityName, /*dontResolveAlias*/ true); + } + if (!ts.isPropertyAccessExpression(entityName)) { + var possibleImportNode = isImportTypeQualifierPart(entityName); + if (possibleImportNode) { + getTypeFromTypeNode(possibleImportNode); + var sym = getNodeLinks(entityName).resolvedSymbol; + return sym === unknownSymbol ? undefined : sym; + } + } + while (ts.isRightSideOfQualifiedNameOrPropertyAccess(entityName)) { + entityName = entityName.parent; + } + if (isHeritageClauseElementIdentifier(entityName)) { + var meaning = 0 /* None */; + // In an interface or class, we're definitely interested in a type. + if (entityName.parent.kind === 211 /* ExpressionWithTypeArguments */) { + meaning = 67897832 /* Type */; + // In a class 'extends' clause we are also looking for a value. + if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent)) { + meaning |= 67220415 /* Value */; + } + } + else { + meaning = 1920 /* Namespace */; + } + meaning |= 2097152 /* Alias */; + var entityNameSymbol = ts.isEntityNameExpression(entityName) ? resolveEntityName(entityName, meaning) : undefined; + if (entityNameSymbol) { + return entityNameSymbol; + } + } + if (entityName.parent.kind === 299 /* JSDocParameterTag */) { + return ts.getParameterSymbolFromJSDoc(entityName.parent); + } + if (entityName.parent.kind === 150 /* TypeParameter */ && entityName.parent.parent.kind === 303 /* JSDocTemplateTag */) { + ts.Debug.assert(!ts.isInJSFile(entityName)); // Otherwise `isDeclarationName` would have been true. + var typeParameter = ts.getTypeParameterFromJsDoc(entityName.parent); + return typeParameter && typeParameter.symbol; + } + if (ts.isExpressionNode(entityName)) { + if (ts.nodeIsMissing(entityName)) { + // Missing entity name. + return undefined; + } + if (entityName.kind === 72 /* Identifier */) { + if (ts.isJSXTagName(entityName) && isJsxIntrinsicIdentifier(entityName)) { + var symbol = getIntrinsicTagSymbol(entityName.parent); + return symbol === unknownSymbol ? undefined : symbol; + } + return resolveEntityName(entityName, 67220415 /* Value */, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); + } + else if (entityName.kind === 189 /* PropertyAccessExpression */ || entityName.kind === 148 /* QualifiedName */) { + var links = getNodeLinks(entityName); + if (links.resolvedSymbol) { + return links.resolvedSymbol; + } + if (entityName.kind === 189 /* PropertyAccessExpression */) { + checkPropertyAccessExpression(entityName); + } + else { + checkQualifiedName(entityName); + } + return links.resolvedSymbol; + } + } + else if (isTypeReferenceIdentifier(entityName)) { + var meaning = entityName.parent.kind === 164 /* TypeReference */ ? 67897832 /* Type */ : 1920 /* Namespace */; + return resolveEntityName(entityName, meaning, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); + } + if (entityName.parent.kind === 163 /* TypePredicate */) { + return resolveEntityName(entityName, /*meaning*/ 1 /* FunctionScopedVariable */); + } + // Do we want to return undefined here? + return undefined; + } + function getSymbolAtLocation(node) { + if (node.kind === 279 /* SourceFile */) { + return ts.isExternalModule(node) ? getMergedSymbol(node.symbol) : undefined; + } + var parent = node.parent; + var grandParent = parent.parent; + if (node.flags & 8388608 /* InWithStatement */) { + // We cannot answer semantic questions within a with block, do not proceed any further + return undefined; + } + if (isDeclarationNameOrImportPropertyName(node)) { + // This is a declaration, call getSymbolOfNode + var parentSymbol = getSymbolOfNode(parent); + return ts.isImportOrExportSpecifier(node.parent) && node.parent.propertyName === node + ? getImmediateAliasedSymbol(parentSymbol) + : parentSymbol; + } + else if (ts.isLiteralComputedPropertyDeclarationName(node)) { + return getSymbolOfNode(parent.parent); + } + if (node.kind === 72 /* Identifier */) { + if (isInRightSideOfImportOrExportAssignment(node)) { + return getSymbolOfEntityNameOrPropertyAccessExpression(node); + } + else if (parent.kind === 186 /* BindingElement */ && + grandParent.kind === 184 /* ObjectBindingPattern */ && + node === parent.propertyName) { + var typeOfPattern = getTypeOfNode(grandParent); + var propertyDeclaration = getPropertyOfType(typeOfPattern, node.escapedText); + if (propertyDeclaration) { + return propertyDeclaration; + } + } + } + switch (node.kind) { + case 72 /* Identifier */: + case 189 /* PropertyAccessExpression */: + case 148 /* QualifiedName */: + return getSymbolOfEntityNameOrPropertyAccessExpression(node); + case 100 /* ThisKeyword */: + var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); + if (ts.isFunctionLike(container)) { + var sig = getSignatureFromDeclaration(container); + if (sig.thisParameter) { + return sig.thisParameter; + } + } + if (ts.isInExpressionContext(node)) { + return checkExpression(node).symbol; + } + // falls through + case 178 /* ThisType */: + return getTypeFromThisTypeNode(node).symbol; + case 98 /* SuperKeyword */: + return checkExpression(node).symbol; + case 124 /* ConstructorKeyword */: + // constructor keyword for an overload, should take us to the definition if it exist + var constructorDeclaration = node.parent; + if (constructorDeclaration && constructorDeclaration.kind === 157 /* Constructor */) { + return constructorDeclaration.parent.symbol; + } + return undefined; + case 10 /* StringLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: + // 1). import x = require("./mo/*gotToDefinitionHere*/d") + // 2). External module name in an import declaration + // 3). Dynamic import call or require in javascript + // 4). type A = import("./f/*gotToDefinitionHere*/oo") + if ((ts.isExternalModuleImportEqualsDeclaration(node.parent.parent) && ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node) || + ((node.parent.kind === 249 /* ImportDeclaration */ || node.parent.kind === 255 /* ExportDeclaration */) && node.parent.moduleSpecifier === node) || + ((ts.isInJSFile(node) && ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteralLike*/ false)) || ts.isImportCall(node.parent)) || + (ts.isLiteralTypeNode(node.parent) && ts.isLiteralImportTypeNode(node.parent.parent) && node.parent.parent.argument === node.parent)) { + return resolveExternalModuleName(node, node); + } + if (ts.isCallExpression(parent) && ts.isBindableObjectDefinePropertyCall(parent) && parent.arguments[1] === node) { + return getSymbolOfNode(parent); + } + // falls through + case 8 /* NumericLiteral */: + // index access + var objectType = ts.isElementAccessExpression(parent) + ? parent.argumentExpression === node ? getTypeOfExpression(parent.expression) : undefined + : ts.isLiteralTypeNode(parent) && ts.isIndexedAccessTypeNode(grandParent) + ? getTypeFromTypeNode(grandParent.objectType) + : undefined; + return objectType && getPropertyOfType(objectType, ts.escapeLeadingUnderscores(node.text)); + case 80 /* DefaultKeyword */: + case 90 /* FunctionKeyword */: + case 37 /* EqualsGreaterThanToken */: + case 76 /* ClassKeyword */: + return getSymbolOfNode(node.parent); + case 183 /* ImportType */: + return ts.isLiteralImportTypeNode(node) ? getSymbolAtLocation(node.argument.literal) : undefined; + case 85 /* ExportKeyword */: + return ts.isExportAssignment(node.parent) ? ts.Debug.assertDefined(node.parent.symbol) : undefined; + default: + return undefined; + } + } + function getShorthandAssignmentValueSymbol(location) { + if (location && location.kind === 276 /* ShorthandPropertyAssignment */) { + return resolveEntityName(location.name, 67220415 /* Value */ | 2097152 /* Alias */); + } + return undefined; + } + /** Returns the target of an export specifier without following aliases */ + function getExportSpecifierLocalTargetSymbol(node) { + return node.parent.parent.moduleSpecifier ? + getExternalModuleMember(node.parent.parent, node) : + resolveEntityName(node.propertyName || node.name, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); + } + function getTypeOfNode(node) { + if (node.flags & 8388608 /* InWithStatement */) { + // We cannot answer semantic questions within a with block, do not proceed any further + return errorType; + } + var classDecl = ts.tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node); + var classType = classDecl && getDeclaredTypeOfClassOrInterface(getSymbolOfNode(classDecl.class)); + if (ts.isPartOfTypeNode(node)) { + var typeFromTypeNode = getTypeFromTypeNode(node); + return classType ? getTypeWithThisArgument(typeFromTypeNode, classType.thisType) : typeFromTypeNode; + } + if (ts.isExpressionNode(node)) { + return getRegularTypeOfExpression(node); + } + if (classType && !classDecl.isImplements) { + // A SyntaxKind.ExpressionWithTypeArguments is considered a type node, except when it occurs in the + // extends clause of a class. We handle that case here. + var baseType = ts.firstOrUndefined(getBaseTypes(classType)); + return baseType ? getTypeWithThisArgument(baseType, classType.thisType) : errorType; + } + if (isTypeDeclaration(node)) { + // In this case, we call getSymbolOfNode instead of getSymbolAtLocation because it is a declaration + var symbol = getSymbolOfNode(node); + return getDeclaredTypeOfSymbol(symbol); + } + if (isTypeDeclarationName(node)) { + var symbol = getSymbolAtLocation(node); + return symbol ? getDeclaredTypeOfSymbol(symbol) : errorType; + } + if (ts.isDeclaration(node)) { + // In this case, we call getSymbolOfNode instead of getSymbolAtLocation because it is a declaration + var symbol = getSymbolOfNode(node); + return getTypeOfSymbol(symbol); + } + if (isDeclarationNameOrImportPropertyName(node)) { + var symbol = getSymbolAtLocation(node); + return symbol ? getTypeOfSymbol(symbol) : errorType; + } + if (ts.isBindingPattern(node)) { + return getTypeForVariableLikeDeclaration(node.parent, /*includeOptionality*/ true) || errorType; + } + if (isInRightSideOfImportOrExportAssignment(node)) { + var symbol = getSymbolAtLocation(node); + if (symbol) { + var declaredType = getDeclaredTypeOfSymbol(symbol); + return declaredType !== errorType ? declaredType : getTypeOfSymbol(symbol); + } + } + return errorType; + } + // Gets the type of object literal or array literal of destructuring assignment. + // { a } from + // for ( { a } of elems) { + // } + // [ a ] from + // [a] = [ some array ...] + function getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr) { + ts.Debug.assert(expr.kind === 188 /* ObjectLiteralExpression */ || expr.kind === 187 /* ArrayLiteralExpression */); + // If this is from "for of" + // for ( { a } of elems) { + // } + if (expr.parent.kind === 227 /* ForOfStatement */) { + var iteratedType = checkRightHandSideOfForOf(expr.parent.expression, expr.parent.awaitModifier); + return checkDestructuringAssignment(expr, iteratedType || errorType); + } + // If this is from "for" initializer + // for ({a } = elems[0];.....) { } + if (expr.parent.kind === 204 /* BinaryExpression */) { + var iteratedType = getTypeOfExpression(expr.parent.right); + return checkDestructuringAssignment(expr, iteratedType || errorType); + } + // If this is from nested object binding pattern + // for ({ skills: { primary, secondary } } = multiRobot, i = 0; i < 1; i++) { + if (expr.parent.kind === 275 /* PropertyAssignment */) { + var typeOfParentObjectLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr.parent.parent); + return checkObjectLiteralDestructuringPropertyAssignment(typeOfParentObjectLiteral || errorType, expr.parent); // TODO: GH#18217 + } + // Array literal assignment - array destructuring pattern + ts.Debug.assert(expr.parent.kind === 187 /* ArrayLiteralExpression */); + // [{ property1: p1, property2 }] = elems; + var typeOfArrayLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr.parent); + var elementType = checkIteratedTypeOrElementType(typeOfArrayLiteral || errorType, expr.parent, /*allowStringInput*/ false, /*allowAsyncIterables*/ false) || errorType; + return checkArrayLiteralDestructuringElementAssignment(expr.parent, typeOfArrayLiteral, expr.parent.elements.indexOf(expr), elementType || errorType); // TODO: GH#18217 + } + // Gets the property symbol corresponding to the property in destructuring assignment + // 'property1' from + // for ( { property1: a } of elems) { + // } + // 'property1' at location 'a' from: + // [a] = [ property1, property2 ] + function getPropertySymbolOfDestructuringAssignment(location) { + // Get the type of the object or array literal and then look for property of given name in the type + var typeOfObjectLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(location.parent.parent); + return typeOfObjectLiteral && getPropertyOfType(typeOfObjectLiteral, location.escapedText); + } + function getRegularTypeOfExpression(expr) { + if (ts.isRightSideOfQualifiedNameOrPropertyAccess(expr)) { + expr = expr.parent; + } + return getRegularTypeOfLiteralType(getTypeOfExpression(expr)); + } + /** + * Gets either the static or instance type of a class element, based on + * whether the element is declared as "static". + */ + function getParentTypeOfClassElement(node) { + var classSymbol = getSymbolOfNode(node.parent); + return ts.hasModifier(node, 32 /* Static */) + ? getTypeOfSymbol(classSymbol) + : getDeclaredTypeOfSymbol(classSymbol); + } + function getClassElementPropertyKeyType(element) { + var name = element.name; + switch (name.kind) { + case 72 /* Identifier */: + return getLiteralType(ts.idText(name)); + case 8 /* NumericLiteral */: + case 10 /* StringLiteral */: + return getLiteralType(name.text); + case 149 /* ComputedPropertyName */: + var nameType = checkComputedPropertyName(name); + return isTypeAssignableToKind(nameType, 12288 /* ESSymbolLike */) ? nameType : stringType; + default: + ts.Debug.fail("Unsupported property name."); + return errorType; + } + } + // Return the list of properties of the given type, augmented with properties from Function + // if the type has call or construct signatures + function getAugmentedPropertiesOfType(type) { + type = getApparentType(type); + var propsByName = ts.createSymbolTable(getPropertiesOfType(type)); + var functionType = getSignaturesOfType(type, 0 /* Call */).length ? globalCallableFunctionType : + getSignaturesOfType(type, 1 /* Construct */).length ? globalNewableFunctionType : + undefined; + if (functionType) { + ts.forEach(getPropertiesOfType(functionType), function (p) { + if (!propsByName.has(p.escapedName)) { + propsByName.set(p.escapedName, p); + } + }); + } + return getNamedMembers(propsByName); + } + function typeHasCallOrConstructSignatures(type) { + return ts.typeHasCallOrConstructSignatures(type, checker); + } + function getRootSymbols(symbol) { + var roots = getImmediateRootSymbols(symbol); + return roots ? ts.flatMap(roots, getRootSymbols) : [symbol]; + } + function getImmediateRootSymbols(symbol) { + if (ts.getCheckFlags(symbol) & 6 /* Synthetic */) { + return ts.mapDefined(getSymbolLinks(symbol).containingType.types, function (type) { return getPropertyOfType(type, symbol.escapedName); }); + } + else if (symbol.flags & 33554432 /* Transient */) { + var _a = symbol, leftSpread = _a.leftSpread, rightSpread = _a.rightSpread, syntheticOrigin = _a.syntheticOrigin; + return leftSpread ? [leftSpread, rightSpread] + : syntheticOrigin ? [syntheticOrigin] + : ts.singleElementArray(tryGetAliasTarget(symbol)); + } + return undefined; + } + function tryGetAliasTarget(symbol) { + var target; + var next = symbol; + while (next = getSymbolLinks(next).target) { + target = next; + } + return target; + } + // Emitter support + function isArgumentsLocalBinding(nodeIn) { + if (!ts.isGeneratedIdentifier(nodeIn)) { + var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier); + if (node) { + var isPropertyName_1 = node.parent.kind === 189 /* PropertyAccessExpression */ && node.parent.name === node; + return !isPropertyName_1 && getReferencedValueSymbol(node) === argumentsSymbol; + } + } + return false; + } + function moduleExportsSomeValue(moduleReferenceExpression) { + var moduleSymbol = resolveExternalModuleName(moduleReferenceExpression.parent, moduleReferenceExpression); + if (!moduleSymbol || ts.isShorthandAmbientModuleSymbol(moduleSymbol)) { + // If the module is not found or is shorthand, assume that it may export a value. + return true; + } + var hasExportAssignment = hasExportAssignmentSymbol(moduleSymbol); + // if module has export assignment then 'resolveExternalModuleSymbol' will return resolved symbol for export assignment + // otherwise it will return moduleSymbol itself + moduleSymbol = resolveExternalModuleSymbol(moduleSymbol); + var symbolLinks = getSymbolLinks(moduleSymbol); + if (symbolLinks.exportsSomeValue === undefined) { + // for export assignments - check if resolved symbol for RHS is itself a value + // otherwise - check if at least one export is value + symbolLinks.exportsSomeValue = hasExportAssignment + ? !!(moduleSymbol.flags & 67220415 /* Value */) + : ts.forEachEntry(getExportsOfModule(moduleSymbol), isValue); + } + return symbolLinks.exportsSomeValue; + function isValue(s) { + s = resolveSymbol(s); + return s && !!(s.flags & 67220415 /* Value */); + } + } + function isNameOfModuleOrEnumDeclaration(node) { + return ts.isModuleOrEnumDeclaration(node.parent) && node === node.parent.name; + } + // When resolved as an expression identifier, if the given node references an exported entity, return the declaration + // node of the exported entity's container. Otherwise, return undefined. + function getReferencedExportContainer(nodeIn, prefixLocals) { + var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier); + if (node) { + // When resolving the export container for the name of a module or enum + // declaration, we need to start resolution at the declaration's container. + // Otherwise, we could incorrectly resolve the export container as the + // declaration if it contains an exported member with the same name. + var symbol = getReferencedValueSymbol(node, /*startInDeclarationContainer*/ isNameOfModuleOrEnumDeclaration(node)); + if (symbol) { + if (symbol.flags & 1048576 /* ExportValue */) { + // If we reference an exported entity within the same module declaration, then whether + // we prefix depends on the kind of entity. SymbolFlags.ExportHasLocal encompasses all the + // kinds that we do NOT prefix. + var exportSymbol = getMergedSymbol(symbol.exportSymbol); + if (!prefixLocals && exportSymbol.flags & 944 /* ExportHasLocal */ && !(exportSymbol.flags & 3 /* Variable */)) { + return undefined; + } + symbol = exportSymbol; + } + var parentSymbol_1 = getParentOfSymbol(symbol); + if (parentSymbol_1) { + if (parentSymbol_1.flags & 512 /* ValueModule */ && parentSymbol_1.valueDeclaration.kind === 279 /* SourceFile */) { + var symbolFile = parentSymbol_1.valueDeclaration; + var referenceFile = ts.getSourceFileOfNode(node); + // If `node` accesses an export and that export isn't in the same file, then symbol is a namespace export, so return undefined. + var symbolIsUmdExport = symbolFile !== referenceFile; + return symbolIsUmdExport ? undefined : symbolFile; + } + return ts.findAncestor(node.parent, function (n) { return ts.isModuleOrEnumDeclaration(n) && getSymbolOfNode(n) === parentSymbol_1; }); + } + } + } + } + // When resolved as an expression identifier, if the given node references an import, return the declaration of + // that import. Otherwise, return undefined. + function getReferencedImportDeclaration(nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier); + if (node) { + var symbol = getReferencedValueSymbol(node); + // We should only get the declaration of an alias if there isn't a local value + // declaration for the symbol + if (isNonLocalAlias(symbol, /*excludes*/ 67220415 /* Value */)) { + return getDeclarationOfAliasSymbol(symbol); + } + } + return undefined; + } + function isSymbolOfDeclarationWithCollidingName(symbol) { + if (symbol.flags & 418 /* BlockScoped */) { + var links = getSymbolLinks(symbol); + if (links.isDeclarationWithCollidingName === undefined) { + var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); + if (ts.isStatementWithLocals(container)) { + var nodeLinks_1 = getNodeLinks(symbol.valueDeclaration); + if (resolveName(container.parent, symbol.escapedName, 67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)) { + // redeclaration - always should be renamed + links.isDeclarationWithCollidingName = true; + } + else if (nodeLinks_1.flags & 262144 /* CapturedBlockScopedBinding */) { + // binding is captured in the function + // should be renamed if: + // - binding is not top level - top level bindings never collide with anything + // AND + // - binding is not declared in loop, should be renamed to avoid name reuse across siblings + // let a, b + // { let x = 1; a = () => x; } + // { let x = 100; b = () => x; } + // console.log(a()); // should print '1' + // console.log(b()); // should print '100' + // OR + // - binding is declared inside loop but not in inside initializer of iteration statement or directly inside loop body + // * variables from initializer are passed to rewritten loop body as parameters so they are not captured directly + // * variables that are declared immediately in loop body will become top level variable after loop is rewritten and thus + // they will not collide with anything + var isDeclaredInLoop = nodeLinks_1.flags & 524288 /* BlockScopedBindingInLoop */; + var inLoopInitializer = ts.isIterationStatement(container, /*lookInLabeledStatements*/ false); + var inLoopBodyBlock = container.kind === 218 /* Block */ && ts.isIterationStatement(container.parent, /*lookInLabeledStatements*/ false); + links.isDeclarationWithCollidingName = !ts.isBlockScopedContainerTopLevel(container) && (!isDeclaredInLoop || (!inLoopInitializer && !inLoopBodyBlock)); + } + else { + links.isDeclarationWithCollidingName = false; + } + } + } + return links.isDeclarationWithCollidingName; + } + return false; + } + // When resolved as an expression identifier, if the given node references a nested block scoped entity with + // a name that either hides an existing name or might hide it when compiled downlevel, + // return the declaration of that entity. Otherwise, return undefined. + function getReferencedDeclarationWithCollidingName(nodeIn) { + if (!ts.isGeneratedIdentifier(nodeIn)) { + var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier); + if (node) { + var symbol = getReferencedValueSymbol(node); + if (symbol && isSymbolOfDeclarationWithCollidingName(symbol)) { + return symbol.valueDeclaration; + } + } + } + return undefined; + } + // Return true if the given node is a declaration of a nested block scoped entity with a name that either hides an + // existing name or might hide a name when compiled downlevel + function isDeclarationWithCollidingName(nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isDeclaration); + if (node) { + var symbol = getSymbolOfNode(node); + if (symbol) { + return isSymbolOfDeclarationWithCollidingName(symbol); + } + } + return false; + } + function isValueAliasDeclaration(node) { + switch (node.kind) { + case 248 /* ImportEqualsDeclaration */: + case 250 /* ImportClause */: + case 251 /* NamespaceImport */: + case 253 /* ImportSpecifier */: + case 257 /* ExportSpecifier */: + return isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol); + case 255 /* ExportDeclaration */: + var exportClause = node.exportClause; + return !!exportClause && ts.some(exportClause.elements, isValueAliasDeclaration); + case 254 /* ExportAssignment */: + return node.expression + && node.expression.kind === 72 /* Identifier */ + ? isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol) + : true; + } + return false; + } + function isTopLevelValueImportEqualsWithEntityName(nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isImportEqualsDeclaration); + if (node === undefined || node.parent.kind !== 279 /* SourceFile */ || !ts.isInternalModuleImportEqualsDeclaration(node)) { + // parent is not source file or it is not reference to internal module + return false; + } + var isValue = isAliasResolvedToValue(getSymbolOfNode(node)); + return isValue && node.moduleReference && !ts.nodeIsMissing(node.moduleReference); + } + function isAliasResolvedToValue(symbol) { + var target = resolveAlias(symbol); + if (target === unknownSymbol) { + return true; + } + // const enums and modules that contain only const enums are not considered values from the emit perspective + // unless 'preserveConstEnums' option is set to true + return !!(target.flags & 67220415 /* Value */) && + (compilerOptions.preserveConstEnums || !isConstEnumOrConstEnumOnlyModule(target)); + } + function isConstEnumOrConstEnumOnlyModule(s) { + return isConstEnumSymbol(s) || !!s.constEnumOnlyModule; + } + function isReferencedAliasDeclaration(node, checkChildren) { + if (ts.isAliasSymbolDeclaration(node)) { + var symbol = getSymbolOfNode(node); + if (symbol && getSymbolLinks(symbol).referenced) { + return true; + } + var target = getSymbolLinks(symbol).target; // TODO: GH#18217 + if (target && ts.getModifierFlags(node) & 1 /* Export */ && + target.flags & 67220415 /* Value */ && (compilerOptions.preserveConstEnums || !isConstEnumOrConstEnumOnlyModule(target))) { + // An `export import ... =` of a value symbol is always considered referenced + return true; + } + } + if (checkChildren) { + return !!ts.forEachChild(node, function (node) { return isReferencedAliasDeclaration(node, checkChildren); }); + } + return false; + } + function isImplementationOfOverload(node) { + if (ts.nodeIsPresent(node.body)) { + if (ts.isGetAccessor(node) || ts.isSetAccessor(node)) + return false; // Get or set accessors can never be overload implementations, but can have up to 2 signatures + var symbol = getSymbolOfNode(node); + var signaturesOfSymbol = getSignaturesOfSymbol(symbol); + // If this function body corresponds to function with multiple signature, it is implementation of overload + // e.g.: function foo(a: string): string; + // function foo(a: number): number; + // function foo(a: any) { // This is implementation of the overloads + // return a; + // } + return signaturesOfSymbol.length > 1 || + // If there is single signature for the symbol, it is overload if that signature isn't coming from the node + // e.g.: function foo(a: string): string; + // function foo(a: any) { // This is implementation of the overloads + // return a; + // } + (signaturesOfSymbol.length === 1 && signaturesOfSymbol[0].declaration !== node); + } + return false; + } + function isRequiredInitializedParameter(parameter) { + return !!strictNullChecks && + !isOptionalParameter(parameter) && + !ts.isJSDocParameterTag(parameter) && + !!parameter.initializer && + !ts.hasModifier(parameter, 92 /* ParameterPropertyModifier */); + } + function isOptionalUninitializedParameterProperty(parameter) { + return strictNullChecks && + isOptionalParameter(parameter) && + !parameter.initializer && + ts.hasModifier(parameter, 92 /* ParameterPropertyModifier */); + } + function isExpandoFunctionDeclaration(node) { + var declaration = ts.getParseTreeNode(node, ts.isFunctionDeclaration); + if (!declaration) { + return false; + } + var symbol = getSymbolOfNode(declaration); + if (!symbol || !(symbol.flags & 16 /* Function */)) { + return false; + } + return !!ts.forEachEntry(getExportsOfSymbol(symbol), function (p) { return p.flags & 67220415 /* Value */ && ts.isPropertyAccessExpression(p.valueDeclaration); }); + } + function getPropertiesOfContainerFunction(node) { + var declaration = ts.getParseTreeNode(node, ts.isFunctionDeclaration); + if (!declaration) { + return ts.emptyArray; + } + var symbol = getSymbolOfNode(declaration); + return symbol && getPropertiesOfType(getTypeOfSymbol(symbol)) || ts.emptyArray; + } + function getNodeCheckFlags(node) { + return getNodeLinks(node).flags || 0; + } + function getEnumMemberValue(node) { + computeEnumMemberValues(node.parent); + return getNodeLinks(node).enumMemberValue; + } + function canHaveConstantValue(node) { + switch (node.kind) { + case 278 /* EnumMember */: + case 189 /* PropertyAccessExpression */: + case 190 /* ElementAccessExpression */: + return true; + } + return false; + } + function getConstantValue(node) { + if (node.kind === 278 /* EnumMember */) { + return getEnumMemberValue(node); + } + var symbol = getNodeLinks(node).resolvedSymbol; + if (symbol && (symbol.flags & 8 /* EnumMember */)) { + // inline property\index accesses only for const enums + var member = symbol.valueDeclaration; + if (ts.isEnumConst(member.parent)) { + return getEnumMemberValue(member); + } + } + return undefined; + } + function isFunctionType(type) { + return !!(type.flags & 524288 /* Object */) && getSignaturesOfType(type, 0 /* Call */).length > 0; + } + function getTypeReferenceSerializationKind(typeNameIn, location) { + // ensure both `typeName` and `location` are parse tree nodes. + var typeName = ts.getParseTreeNode(typeNameIn, ts.isEntityName); + if (!typeName) + return ts.TypeReferenceSerializationKind.Unknown; + if (location) { + location = ts.getParseTreeNode(location); + if (!location) + return ts.TypeReferenceSerializationKind.Unknown; + } + // Resolve the symbol as a value to ensure the type can be reached at runtime during emit. + var valueSymbol = resolveEntityName(typeName, 67220415 /* Value */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location); + // Resolve the symbol as a type so that we can provide a more useful hint for the type serializer. + var typeSymbol = resolveEntityName(typeName, 67897832 /* Type */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location); + if (valueSymbol && valueSymbol === typeSymbol) { + var globalPromiseSymbol = getGlobalPromiseConstructorSymbol(/*reportErrors*/ false); + if (globalPromiseSymbol && valueSymbol === globalPromiseSymbol) { + return ts.TypeReferenceSerializationKind.Promise; + } + var constructorType = getTypeOfSymbol(valueSymbol); + if (constructorType && isConstructorType(constructorType)) { + return ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue; + } + } + // We might not be able to resolve type symbol so use unknown type in that case (eg error case) + if (!typeSymbol) { + return ts.TypeReferenceSerializationKind.Unknown; + } + var type = getDeclaredTypeOfSymbol(typeSymbol); + if (type === errorType) { + return ts.TypeReferenceSerializationKind.Unknown; + } + else if (type.flags & 3 /* AnyOrUnknown */) { + return ts.TypeReferenceSerializationKind.ObjectType; + } + else if (isTypeAssignableToKind(type, 16384 /* Void */ | 98304 /* Nullable */ | 131072 /* Never */)) { + return ts.TypeReferenceSerializationKind.VoidNullableOrNeverType; + } + else if (isTypeAssignableToKind(type, 528 /* BooleanLike */)) { + return ts.TypeReferenceSerializationKind.BooleanType; + } + else if (isTypeAssignableToKind(type, 296 /* NumberLike */)) { + return ts.TypeReferenceSerializationKind.NumberLikeType; + } + else if (isTypeAssignableToKind(type, 2112 /* BigIntLike */)) { + return ts.TypeReferenceSerializationKind.BigIntLikeType; + } + else if (isTypeAssignableToKind(type, 132 /* StringLike */)) { + return ts.TypeReferenceSerializationKind.StringLikeType; + } + else if (isTupleType(type)) { + return ts.TypeReferenceSerializationKind.ArrayLikeType; + } + else if (isTypeAssignableToKind(type, 12288 /* ESSymbolLike */)) { + return ts.TypeReferenceSerializationKind.ESSymbolType; + } + else if (isFunctionType(type)) { + return ts.TypeReferenceSerializationKind.TypeWithCallSignature; + } + else if (isArrayType(type)) { + return ts.TypeReferenceSerializationKind.ArrayLikeType; + } + else { + return ts.TypeReferenceSerializationKind.ObjectType; + } + } + function createTypeOfDeclaration(declarationIn, enclosingDeclaration, flags, tracker, addUndefined) { + var declaration = ts.getParseTreeNode(declarationIn, ts.isVariableLikeOrAccessor); + if (!declaration) { + return ts.createToken(120 /* AnyKeyword */); + } + // Get type of the symbol if this is the valid symbol otherwise get type at location + var symbol = getSymbolOfNode(declaration); + var type = symbol && !(symbol.flags & (2048 /* TypeLiteral */ | 131072 /* Signature */)) + ? getWidenedLiteralType(getTypeOfSymbol(symbol)) + : errorType; + if (type.flags & 8192 /* UniqueESSymbol */ && + type.symbol === symbol) { + flags |= 1048576 /* AllowUniqueESSymbolType */; + } + if (addUndefined) { + type = getOptionalType(type); + } + return nodeBuilder.typeToTypeNode(type, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, tracker); + } + function createReturnTypeOfSignatureDeclaration(signatureDeclarationIn, enclosingDeclaration, flags, tracker) { + var signatureDeclaration = ts.getParseTreeNode(signatureDeclarationIn, ts.isFunctionLike); + if (!signatureDeclaration) { + return ts.createToken(120 /* AnyKeyword */); + } + var signature = getSignatureFromDeclaration(signatureDeclaration); + return nodeBuilder.typeToTypeNode(getReturnTypeOfSignature(signature), enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, tracker); + } + function createTypeOfExpression(exprIn, enclosingDeclaration, flags, tracker) { + var expr = ts.getParseTreeNode(exprIn, ts.isExpression); + if (!expr) { + return ts.createToken(120 /* AnyKeyword */); + } + var type = getWidenedType(getRegularTypeOfExpression(expr)); + return nodeBuilder.typeToTypeNode(type, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, tracker); + } + function hasGlobalName(name) { + return globals.has(ts.escapeLeadingUnderscores(name)); + } + function getReferencedValueSymbol(reference, startInDeclarationContainer) { + var resolvedSymbol = getNodeLinks(reference).resolvedSymbol; + if (resolvedSymbol) { + return resolvedSymbol; + } + var location = reference; + if (startInDeclarationContainer) { + // When resolving the name of a declaration as a value, we need to start resolution + // at a point outside of the declaration. + var parent = reference.parent; + if (ts.isDeclaration(parent) && reference === parent.name) { + location = getDeclarationContainer(parent); + } + } + return resolveName(location, reference.escapedText, 67220415 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */, /*nodeNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); + } + function getReferencedValueDeclaration(referenceIn) { + if (!ts.isGeneratedIdentifier(referenceIn)) { + var reference = ts.getParseTreeNode(referenceIn, ts.isIdentifier); + if (reference) { + var symbol = getReferencedValueSymbol(reference); + if (symbol) { + return getExportSymbolOfValueSymbolIfExported(symbol).valueDeclaration; + } + } + } + return undefined; + } + function isLiteralConstDeclaration(node) { + if (ts.isDeclarationReadonly(node) || ts.isVariableDeclaration(node) && ts.isVarConst(node)) { + return isFreshLiteralType(getTypeOfSymbol(getSymbolOfNode(node))); + } + return false; + } + function literalTypeToNode(type, enclosing, tracker) { + var enumResult = type.flags & 1024 /* EnumLiteral */ ? nodeBuilder.symbolToExpression(type.symbol, 67220415 /* Value */, enclosing, /*flags*/ undefined, tracker) + : type === trueType ? ts.createTrue() : type === falseType && ts.createFalse(); + return enumResult || ts.createLiteral(type.value); + } + function createLiteralConstValue(node, tracker) { + var type = getTypeOfSymbol(getSymbolOfNode(node)); + return literalTypeToNode(type, node, tracker); + } + function createResolver() { + // this variable and functions that use it are deliberately moved here from the outer scope + // to avoid scope pollution + var resolvedTypeReferenceDirectives = host.getResolvedTypeReferenceDirectives(); + var fileToDirective; + if (resolvedTypeReferenceDirectives) { + // populate reverse mapping: file path -> type reference directive that was resolved to this file + fileToDirective = ts.createMap(); + resolvedTypeReferenceDirectives.forEach(function (resolvedDirective, key) { + if (!resolvedDirective || !resolvedDirective.resolvedFileName) { + return; + } + var file = host.getSourceFile(resolvedDirective.resolvedFileName); + fileToDirective.set(file.path, key); + }); + } + return { + getReferencedExportContainer: getReferencedExportContainer, + getReferencedImportDeclaration: getReferencedImportDeclaration, + getReferencedDeclarationWithCollidingName: getReferencedDeclarationWithCollidingName, + isDeclarationWithCollidingName: isDeclarationWithCollidingName, + isValueAliasDeclaration: function (node) { + node = ts.getParseTreeNode(node); + // Synthesized nodes are always treated like values. + return node ? isValueAliasDeclaration(node) : true; + }, + hasGlobalName: hasGlobalName, + isReferencedAliasDeclaration: function (node, checkChildren) { + node = ts.getParseTreeNode(node); + // Synthesized nodes are always treated as referenced. + return node ? isReferencedAliasDeclaration(node, checkChildren) : true; + }, + getNodeCheckFlags: function (node) { + node = ts.getParseTreeNode(node); + return node ? getNodeCheckFlags(node) : 0; + }, + isTopLevelValueImportEqualsWithEntityName: isTopLevelValueImportEqualsWithEntityName, + isDeclarationVisible: isDeclarationVisible, + isImplementationOfOverload: isImplementationOfOverload, + isRequiredInitializedParameter: isRequiredInitializedParameter, + isOptionalUninitializedParameterProperty: isOptionalUninitializedParameterProperty, + isExpandoFunctionDeclaration: isExpandoFunctionDeclaration, + getPropertiesOfContainerFunction: getPropertiesOfContainerFunction, + createTypeOfDeclaration: createTypeOfDeclaration, + createReturnTypeOfSignatureDeclaration: createReturnTypeOfSignatureDeclaration, + createTypeOfExpression: createTypeOfExpression, + createLiteralConstValue: createLiteralConstValue, + isSymbolAccessible: isSymbolAccessible, + isEntityNameVisible: isEntityNameVisible, + getConstantValue: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, canHaveConstantValue); + return node ? getConstantValue(node) : undefined; + }, + collectLinkedAliases: collectLinkedAliases, + getReferencedValueDeclaration: getReferencedValueDeclaration, + getTypeReferenceSerializationKind: getTypeReferenceSerializationKind, + isOptionalParameter: isOptionalParameter, + moduleExportsSomeValue: moduleExportsSomeValue, + isArgumentsLocalBinding: isArgumentsLocalBinding, + getExternalModuleFileFromDeclaration: getExternalModuleFileFromDeclaration, + getTypeReferenceDirectivesForEntityName: getTypeReferenceDirectivesForEntityName, + getTypeReferenceDirectivesForSymbol: getTypeReferenceDirectivesForSymbol, + isLiteralConstDeclaration: isLiteralConstDeclaration, + isLateBound: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isDeclaration); + var symbol = node && getSymbolOfNode(node); + return !!(symbol && ts.getCheckFlags(symbol) & 1024 /* Late */); + }, + getJsxFactoryEntity: function (location) { return location ? (getJsxNamespace(location), (ts.getSourceFileOfNode(location).localJsxFactory || _jsxFactoryEntity)) : _jsxFactoryEntity; }, + getAllAccessorDeclarations: function (accessor) { + accessor = ts.getParseTreeNode(accessor, ts.isGetOrSetAccessorDeclaration); // TODO: GH#18217 + var otherKind = accessor.kind === 159 /* SetAccessor */ ? 158 /* GetAccessor */ : 159 /* SetAccessor */; + var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(accessor), otherKind); + var firstAccessor = otherAccessor && (otherAccessor.pos < accessor.pos) ? otherAccessor : accessor; + var secondAccessor = otherAccessor && (otherAccessor.pos < accessor.pos) ? accessor : otherAccessor; + var setAccessor = accessor.kind === 159 /* SetAccessor */ ? accessor : otherAccessor; + var getAccessor = accessor.kind === 158 /* GetAccessor */ ? accessor : otherAccessor; + return { + firstAccessor: firstAccessor, + secondAccessor: secondAccessor, + setAccessor: setAccessor, + getAccessor: getAccessor + }; + }, + getSymbolOfExternalModuleSpecifier: function (moduleName) { return resolveExternalModuleNameWorker(moduleName, moduleName, /*moduleNotFoundError*/ undefined); }, + isBindingCapturedByNode: function (node, decl) { + var parseNode = ts.getParseTreeNode(node); + var parseDecl = ts.getParseTreeNode(decl); + return !!parseNode && !!parseDecl && (ts.isVariableDeclaration(parseDecl) || ts.isBindingElement(parseDecl)) && isBindingCapturedByNode(parseNode, parseDecl); + } + }; + function isInHeritageClause(node) { + return node.parent && node.parent.kind === 211 /* ExpressionWithTypeArguments */ && node.parent.parent && node.parent.parent.kind === 273 /* HeritageClause */; + } + // defined here to avoid outer scope pollution + function getTypeReferenceDirectivesForEntityName(node) { + // program does not have any files with type reference directives - bail out + if (!fileToDirective) { + return undefined; + } + // property access can only be used as values, or types when within an expression with type arguments inside a heritage clause + // qualified names can only be used as types\namespaces + // identifiers are treated as values only if they appear in type queries + var meaning = 67897832 /* Type */ | 1920 /* Namespace */; + if ((node.kind === 72 /* Identifier */ && isInTypeQuery(node)) || (node.kind === 189 /* PropertyAccessExpression */ && !isInHeritageClause(node))) { + meaning = 67220415 /* Value */ | 1048576 /* ExportValue */; + } + var symbol = resolveEntityName(node, meaning, /*ignoreErrors*/ true); + return symbol && symbol !== unknownSymbol ? getTypeReferenceDirectivesForSymbol(symbol, meaning) : undefined; + } + // defined here to avoid outer scope pollution + function getTypeReferenceDirectivesForSymbol(symbol, meaning) { + // program does not have any files with type reference directives - bail out + if (!fileToDirective) { + return undefined; + } + if (!isSymbolFromTypeDeclarationFile(symbol)) { + return undefined; + } + // check what declarations in the symbol can contribute to the target meaning + var typeReferenceDirectives; + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + // check meaning of the local symbol to see if declaration needs to be analyzed further + if (decl.symbol && decl.symbol.flags & meaning) { + var file = ts.getSourceFileOfNode(decl); + var typeReferenceDirective = fileToDirective.get(file.path); + if (typeReferenceDirective) { + (typeReferenceDirectives || (typeReferenceDirectives = [])).push(typeReferenceDirective); + } + else { + // found at least one entry that does not originate from type reference directive + return undefined; + } + } + } + return typeReferenceDirectives; + } + function isSymbolFromTypeDeclarationFile(symbol) { + // bail out if symbol does not have associated declarations (i.e. this is transient symbol created for property in binding pattern) + if (!symbol.declarations) { + return false; + } + // walk the parent chain for symbols to make sure that top level parent symbol is in the global scope + // external modules cannot define or contribute to type declaration files + var current = symbol; + while (true) { + var parent = getParentOfSymbol(current); + if (parent) { + current = parent; + } + else { + break; + } + } + if (current.valueDeclaration && current.valueDeclaration.kind === 279 /* SourceFile */ && current.flags & 512 /* ValueModule */) { + return false; + } + // check that at least one declaration of top level symbol originates from type declaration file + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + var file = ts.getSourceFileOfNode(decl); + if (fileToDirective.has(file.path)) { + return true; + } + } + return false; + } + } + function getExternalModuleFileFromDeclaration(declaration) { + var specifier = declaration.kind === 244 /* ModuleDeclaration */ ? ts.tryCast(declaration.name, ts.isStringLiteral) : ts.getExternalModuleName(declaration); + var moduleSymbol = resolveExternalModuleNameWorker(specifier, specifier, /*moduleNotFoundError*/ undefined); // TODO: GH#18217 + if (!moduleSymbol) { + return undefined; + } + return ts.getDeclarationOfKind(moduleSymbol, 279 /* SourceFile */); + } + function initializeTypeChecker() { + // Bind all source files and propagate errors + for (var _i = 0, _a = host.getSourceFiles(); _i < _a.length; _i++) { + var file = _a[_i]; + ts.bindSourceFile(file, compilerOptions); + } + amalgamatedDuplicates = ts.createMap(); + // Initialize global symbol table + var augmentations; + for (var _b = 0, _c = host.getSourceFiles(); _b < _c.length; _b++) { + var file = _c[_b]; + if (file.redirectInfo) { + continue; + } + if (!ts.isExternalOrCommonJsModule(file)) { + mergeSymbolTable(globals, file.locals); + } + if (file.jsGlobalAugmentations) { + mergeSymbolTable(globals, file.jsGlobalAugmentations); + } + if (file.patternAmbientModules && file.patternAmbientModules.length) { + patternAmbientModules = ts.concatenate(patternAmbientModules, file.patternAmbientModules); + } + if (file.moduleAugmentations.length) { + (augmentations || (augmentations = [])).push(file.moduleAugmentations); + } + if (file.symbol && file.symbol.globalExports) { + // Merge in UMD exports with first-in-wins semantics (see #9771) + var source = file.symbol.globalExports; + source.forEach(function (sourceSymbol, id) { + if (!globals.has(id)) { + globals.set(id, sourceSymbol); + } + }); + } + } + // We do global augmentations separately from module augmentations (and before creating global types) because they + // 1. Affect global types. We won't have the correct global types until global augmentations are merged. Also, + // 2. Module augmentation instantiation requires creating the type of a module, which, in turn, can require + // checking for an export or property on the module (if export=) which, in turn, can fall back to the + // apparent type of the module - either globalObjectType or globalFunctionType - which wouldn't exist if we + // did module augmentations prior to finalizing the global types. + if (augmentations) { + // merge _global_ module augmentations. + // this needs to be done after global symbol table is initialized to make sure that all ambient modules are indexed + for (var _d = 0, augmentations_1 = augmentations; _d < augmentations_1.length; _d++) { + var list = augmentations_1[_d]; + for (var _e = 0, list_1 = list; _e < list_1.length; _e++) { + var augmentation = list_1[_e]; + if (!ts.isGlobalScopeAugmentation(augmentation.parent)) + continue; + mergeModuleAugmentation(augmentation); + } + } + } + // Setup global builtins + addToSymbolTable(globals, builtinGlobals, ts.Diagnostics.Declaration_name_conflicts_with_built_in_global_identifier_0); + getSymbolLinks(undefinedSymbol).type = undefinedWideningType; + getSymbolLinks(argumentsSymbol).type = getGlobalType("IArguments", /*arity*/ 0, /*reportErrors*/ true); + getSymbolLinks(unknownSymbol).type = errorType; + // Initialize special types + globalArrayType = getGlobalType("Array", /*arity*/ 1, /*reportErrors*/ true); + globalObjectType = getGlobalType("Object", /*arity*/ 0, /*reportErrors*/ true); + globalFunctionType = getGlobalType("Function", /*arity*/ 0, /*reportErrors*/ true); + globalCallableFunctionType = strictBindCallApply && getGlobalType("CallableFunction", /*arity*/ 0, /*reportErrors*/ true) || globalFunctionType; + globalNewableFunctionType = strictBindCallApply && getGlobalType("NewableFunction", /*arity*/ 0, /*reportErrors*/ true) || globalFunctionType; + globalStringType = getGlobalType("String", /*arity*/ 0, /*reportErrors*/ true); + globalNumberType = getGlobalType("Number", /*arity*/ 0, /*reportErrors*/ true); + globalBooleanType = getGlobalType("Boolean", /*arity*/ 0, /*reportErrors*/ true); + globalRegExpType = getGlobalType("RegExp", /*arity*/ 0, /*reportErrors*/ true); + anyArrayType = createArrayType(anyType); + autoArrayType = createArrayType(autoType); + if (autoArrayType === emptyObjectType) { + // autoArrayType is used as a marker, so even if global Array type is not defined, it needs to be a unique type + autoArrayType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + } + globalReadonlyArrayType = getGlobalTypeOrUndefined("ReadonlyArray", /*arity*/ 1); + anyReadonlyArrayType = globalReadonlyArrayType ? createTypeFromGenericGlobalType(globalReadonlyArrayType, [anyType]) : anyArrayType; + globalThisType = getGlobalTypeOrUndefined("ThisType", /*arity*/ 1); + if (augmentations) { + // merge _nonglobal_ module augmentations. + // this needs to be done after global symbol table is initialized to make sure that all ambient modules are indexed + for (var _f = 0, augmentations_2 = augmentations; _f < augmentations_2.length; _f++) { + var list = augmentations_2[_f]; + for (var _g = 0, list_2 = list; _g < list_2.length; _g++) { + var augmentation = list_2[_g]; + if (ts.isGlobalScopeAugmentation(augmentation.parent)) + continue; + mergeModuleAugmentation(augmentation); + } + } + } + amalgamatedDuplicates.forEach(function (_a) { + var firstFile = _a.firstFile, secondFile = _a.secondFile, conflictingSymbols = _a.conflictingSymbols; + // If not many things conflict, issue individual errors + if (conflictingSymbols.size < 8) { + conflictingSymbols.forEach(function (_a, symbolName) { + var isBlockScoped = _a.isBlockScoped, firstFileLocations = _a.firstFileLocations, secondFileLocations = _a.secondFileLocations; + var message = isBlockScoped ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 : ts.Diagnostics.Duplicate_identifier_0; + for (var _i = 0, firstFileLocations_1 = firstFileLocations; _i < firstFileLocations_1.length; _i++) { + var node = firstFileLocations_1[_i]; + addDuplicateDeclarationError(node, message, symbolName, secondFileLocations); + } + for (var _b = 0, secondFileLocations_1 = secondFileLocations; _b < secondFileLocations_1.length; _b++) { + var node = secondFileLocations_1[_b]; + addDuplicateDeclarationError(node, message, symbolName, firstFileLocations); + } + }); + } + else { + // Otherwise issue top-level error since the files appear very identical in terms of what they contain + var list = ts.arrayFrom(conflictingSymbols.keys()).join(", "); + diagnostics.add(addRelatedInfo(ts.createDiagnosticForNode(firstFile, ts.Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list), ts.createDiagnosticForNode(secondFile, ts.Diagnostics.Conflicts_are_in_this_file))); + diagnostics.add(addRelatedInfo(ts.createDiagnosticForNode(secondFile, ts.Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list), ts.createDiagnosticForNode(firstFile, ts.Diagnostics.Conflicts_are_in_this_file))); + } + }); + amalgamatedDuplicates = undefined; + } + function checkExternalEmitHelpers(location, helpers) { + if ((requestedExternalEmitHelpers & helpers) !== helpers && compilerOptions.importHelpers) { + var sourceFile = ts.getSourceFileOfNode(location); + if (ts.isEffectiveExternalModule(sourceFile, compilerOptions) && !(location.flags & 4194304 /* Ambient */)) { + var helpersModule = resolveHelpersModule(sourceFile, location); + if (helpersModule !== unknownSymbol) { + var uncheckedHelpers = helpers & ~requestedExternalEmitHelpers; + for (var helper = 1 /* FirstEmitHelper */; helper <= 65536 /* LastEmitHelper */; helper <<= 1) { + if (uncheckedHelpers & helper) { + var name = getHelperName(helper); + var symbol = getSymbol(helpersModule.exports, ts.escapeLeadingUnderscores(name), 67220415 /* Value */); + if (!symbol) { + error(location, ts.Diagnostics.This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1, ts.externalHelpersModuleNameText, name); + } + } + } + } + requestedExternalEmitHelpers |= helpers; + } + } + } + function getHelperName(helper) { + switch (helper) { + case 1 /* Extends */: return "__extends"; + case 2 /* Assign */: return "__assign"; + case 4 /* Rest */: return "__rest"; + case 8 /* Decorate */: return "__decorate"; + case 16 /* Metadata */: return "__metadata"; + case 32 /* Param */: return "__param"; + case 64 /* Awaiter */: return "__awaiter"; + case 128 /* Generator */: return "__generator"; + case 256 /* Values */: return "__values"; + case 512 /* Read */: return "__read"; + case 1024 /* Spread */: return "__spread"; + case 2048 /* Await */: return "__await"; + case 4096 /* AsyncGenerator */: return "__asyncGenerator"; + case 8192 /* AsyncDelegator */: return "__asyncDelegator"; + case 16384 /* AsyncValues */: return "__asyncValues"; + case 32768 /* ExportStar */: return "__exportStar"; + case 65536 /* MakeTemplateObject */: return "__makeTemplateObject"; + default: return ts.Debug.fail("Unrecognized helper"); + } + } + function resolveHelpersModule(node, errorNode) { + if (!externalHelpersModule) { + externalHelpersModule = resolveExternalModule(node, ts.externalHelpersModuleNameText, ts.Diagnostics.This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found, errorNode) || unknownSymbol; + } + return externalHelpersModule; + } + // GRAMMAR CHECKING + function checkGrammarDecoratorsAndModifiers(node) { + return checkGrammarDecorators(node) || checkGrammarModifiers(node); + } + function checkGrammarDecorators(node) { + if (!node.decorators) { + return false; + } + if (!ts.nodeCanBeDecorated(node, node.parent, node.parent.parent)) { + if (node.kind === 156 /* MethodDeclaration */ && !ts.nodeIsPresent(node.body)) { + return grammarErrorOnFirstToken(node, ts.Diagnostics.A_decorator_can_only_decorate_a_method_implementation_not_an_overload); + } + else { + return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_are_not_valid_here); + } + } + else if (node.kind === 158 /* GetAccessor */ || node.kind === 159 /* SetAccessor */) { + var accessors = ts.getAllAccessorDeclarations(node.parent.members, node); + if (accessors.firstAccessor.decorators && node === accessors.secondAccessor) { + return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name); + } + } + return false; + } + function checkGrammarModifiers(node) { + var quickResult = reportObviousModifierErrors(node); + if (quickResult !== undefined) { + return quickResult; + } + var lastStatic, lastDeclare, lastAsync, lastReadonly; + var flags = 0 /* None */; + for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) { + var modifier = _a[_i]; + if (modifier.kind !== 133 /* ReadonlyKeyword */) { + if (node.kind === 153 /* PropertySignature */ || node.kind === 155 /* MethodSignature */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_type_member, ts.tokenToString(modifier.kind)); + } + if (node.kind === 162 /* IndexSignature */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_an_index_signature, ts.tokenToString(modifier.kind)); + } + } + switch (modifier.kind) { + case 77 /* ConstKeyword */: + if (node.kind !== 243 /* EnumDeclaration */) { + return grammarErrorOnNode(node, ts.Diagnostics.A_class_member_cannot_have_the_0_keyword, ts.tokenToString(77 /* ConstKeyword */)); + } + break; + case 115 /* PublicKeyword */: + case 114 /* ProtectedKeyword */: + case 113 /* PrivateKeyword */: + var text = visibilityToString(ts.modifierToFlag(modifier.kind)); + if (flags & 28 /* AccessibilityModifier */) { + return grammarErrorOnNode(modifier, ts.Diagnostics.Accessibility_modifier_already_seen); + } + else if (flags & 32 /* Static */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "static"); + } + else if (flags & 64 /* Readonly */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "readonly"); + } + else if (flags & 256 /* Async */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "async"); + } + else if (node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 279 /* SourceFile */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, text); + } + else if (flags & 128 /* Abstract */) { + if (modifier.kind === 113 /* PrivateKeyword */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, text, "abstract"); + } + else { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "abstract"); + } + } + flags |= ts.modifierToFlag(modifier.kind); + break; + case 116 /* StaticKeyword */: + if (flags & 32 /* Static */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "static"); + } + else if (flags & 64 /* Readonly */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "readonly"); + } + else if (flags & 256 /* Async */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "async"); + } + else if (node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 279 /* SourceFile */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, "static"); + } + else if (node.kind === 151 /* Parameter */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "static"); + } + else if (flags & 128 /* Abstract */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "abstract"); + } + flags |= 32 /* Static */; + lastStatic = modifier; + break; + case 133 /* ReadonlyKeyword */: + if (flags & 64 /* Readonly */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "readonly"); + } + else if (node.kind !== 154 /* PropertyDeclaration */ && node.kind !== 153 /* PropertySignature */ && node.kind !== 162 /* IndexSignature */ && node.kind !== 151 /* Parameter */) { + // If node.kind === SyntaxKind.Parameter, checkParameter report an error if it's not a parameter property. + return grammarErrorOnNode(modifier, ts.Diagnostics.readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature); + } + flags |= 64 /* Readonly */; + lastReadonly = modifier; + break; + case 85 /* ExportKeyword */: + if (flags & 1 /* Export */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "export"); + } + else if (flags & 2 /* Ambient */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "declare"); + } + else if (flags & 128 /* Abstract */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "abstract"); + } + else if (flags & 256 /* Async */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "async"); + } + else if (node.parent.kind === 240 /* ClassDeclaration */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_class_element, "export"); + } + else if (node.kind === 151 /* Parameter */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "export"); + } + flags |= 1 /* Export */; + break; + case 80 /* DefaultKeyword */: + var container = node.parent.kind === 279 /* SourceFile */ ? node.parent : node.parent.parent; + if (container.kind === 244 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) { + return grammarErrorOnNode(modifier, ts.Diagnostics.A_default_export_can_only_be_used_in_an_ECMAScript_style_module); + } + flags |= 512 /* Default */; + break; + case 125 /* DeclareKeyword */: + if (flags & 2 /* Ambient */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "declare"); + } + else if (flags & 256 /* Async */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async"); + } + else if (node.parent.kind === 240 /* ClassDeclaration */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_class_element, "declare"); + } + else if (node.kind === 151 /* Parameter */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "declare"); + } + else if ((node.parent.flags & 4194304 /* Ambient */) && node.parent.kind === 245 /* ModuleBlock */) { + return grammarErrorOnNode(modifier, ts.Diagnostics.A_declare_modifier_cannot_be_used_in_an_already_ambient_context); + } + flags |= 2 /* Ambient */; + lastDeclare = modifier; + break; + case 118 /* AbstractKeyword */: + if (flags & 128 /* Abstract */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "abstract"); + } + if (node.kind !== 240 /* ClassDeclaration */) { + if (node.kind !== 156 /* MethodDeclaration */ && + node.kind !== 154 /* PropertyDeclaration */ && + node.kind !== 158 /* GetAccessor */ && + node.kind !== 159 /* SetAccessor */) { + return grammarErrorOnNode(modifier, ts.Diagnostics.abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration); + } + if (!(node.parent.kind === 240 /* ClassDeclaration */ && ts.hasModifier(node.parent, 128 /* Abstract */))) { + return grammarErrorOnNode(modifier, ts.Diagnostics.Abstract_methods_can_only_appear_within_an_abstract_class); + } + if (flags & 32 /* Static */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "abstract"); + } + if (flags & 8 /* Private */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "private", "abstract"); + } + } + flags |= 128 /* Abstract */; + break; + case 121 /* AsyncKeyword */: + if (flags & 256 /* Async */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "async"); + } + else if (flags & 2 /* Ambient */ || node.parent.flags & 4194304 /* Ambient */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async"); + } + else if (node.kind === 151 /* Parameter */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "async"); + } + flags |= 256 /* Async */; + lastAsync = modifier; + break; + } + } + if (node.kind === 157 /* Constructor */) { + if (flags & 32 /* Static */) { + return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "static"); + } + if (flags & 128 /* Abstract */) { + return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "abstract"); // TODO: GH#18217 + } + else if (flags & 256 /* Async */) { + return grammarErrorOnNode(lastAsync, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "async"); + } + else if (flags & 64 /* Readonly */) { + return grammarErrorOnNode(lastReadonly, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "readonly"); + } + return false; + } + else if ((node.kind === 249 /* ImportDeclaration */ || node.kind === 248 /* ImportEqualsDeclaration */) && flags & 2 /* Ambient */) { + return grammarErrorOnNode(lastDeclare, ts.Diagnostics.A_0_modifier_cannot_be_used_with_an_import_declaration, "declare"); + } + else if (node.kind === 151 /* Parameter */ && (flags & 92 /* ParameterPropertyModifier */) && ts.isBindingPattern(node.name)) { + return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_may_not_be_declared_using_a_binding_pattern); + } + else if (node.kind === 151 /* Parameter */ && (flags & 92 /* ParameterPropertyModifier */) && node.dotDotDotToken) { + return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_cannot_be_declared_using_a_rest_parameter); + } + if (flags & 256 /* Async */) { + return checkGrammarAsyncModifier(node, lastAsync); + } + return false; + } + /** + * true | false: Early return this value from checkGrammarModifiers. + * undefined: Need to do full checking on the modifiers. + */ + function reportObviousModifierErrors(node) { + return !node.modifiers + ? false + : shouldReportBadModifier(node) + ? grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here) + : undefined; + } + function shouldReportBadModifier(node) { + switch (node.kind) { + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 157 /* Constructor */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 162 /* IndexSignature */: + case 244 /* ModuleDeclaration */: + case 249 /* ImportDeclaration */: + case 248 /* ImportEqualsDeclaration */: + case 255 /* ExportDeclaration */: + case 254 /* ExportAssignment */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 151 /* Parameter */: + return false; + default: + if (node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 279 /* SourceFile */) { + return false; + } + switch (node.kind) { + case 239 /* FunctionDeclaration */: + return nodeHasAnyModifiersExcept(node, 121 /* AsyncKeyword */); + case 240 /* ClassDeclaration */: + return nodeHasAnyModifiersExcept(node, 118 /* AbstractKeyword */); + case 241 /* InterfaceDeclaration */: + case 219 /* VariableStatement */: + case 242 /* TypeAliasDeclaration */: + return true; + case 243 /* EnumDeclaration */: + return nodeHasAnyModifiersExcept(node, 77 /* ConstKeyword */); + default: + ts.Debug.fail(); + return false; + } + } + } + function nodeHasAnyModifiersExcept(node, allowedModifier) { + return node.modifiers.length > 1 || node.modifiers[0].kind !== allowedModifier; + } + function checkGrammarAsyncModifier(node, asyncModifier) { + switch (node.kind) { + case 156 /* MethodDeclaration */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + return false; + } + return grammarErrorOnNode(asyncModifier, ts.Diagnostics._0_modifier_cannot_be_used_here, "async"); + } + function checkGrammarForDisallowedTrailingComma(list, diag) { + if (diag === void 0) { diag = ts.Diagnostics.Trailing_comma_not_allowed; } + if (list && list.hasTrailingComma) { + return grammarErrorAtPos(list[0], list.end - ",".length, ",".length, diag); + } + return false; + } + function checkGrammarTypeParameterList(typeParameters, file) { + if (typeParameters && typeParameters.length === 0) { + var start = typeParameters.pos - "<".length; + var end = ts.skipTrivia(file.text, typeParameters.end) + ">".length; + return grammarErrorAtPos(file, start, end - start, ts.Diagnostics.Type_parameter_list_cannot_be_empty); + } + return false; + } + function checkGrammarParameterList(parameters) { + var seenOptionalParameter = false; + var parameterCount = parameters.length; + for (var i = 0; i < parameterCount; i++) { + var parameter = parameters[i]; + if (parameter.dotDotDotToken) { + if (i !== (parameterCount - 1)) { + return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.A_rest_parameter_must_be_last_in_a_parameter_list); + } + if (!(parameter.flags & 4194304 /* Ambient */)) { // Allow `...foo,` in ambient declarations; see GH#23070 + checkGrammarForDisallowedTrailingComma(parameters, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma); + } + if (ts.isBindingPattern(parameter.name)) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.A_rest_element_cannot_contain_a_binding_pattern); + } + if (parameter.questionToken) { + return grammarErrorOnNode(parameter.questionToken, ts.Diagnostics.A_rest_parameter_cannot_be_optional); + } + if (parameter.initializer) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.A_rest_parameter_cannot_have_an_initializer); + } + } + else if (parameter.questionToken) { + seenOptionalParameter = true; + if (parameter.initializer) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.Parameter_cannot_have_question_mark_and_initializer); + } + } + else if (seenOptionalParameter && !parameter.initializer) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.A_required_parameter_cannot_follow_an_optional_parameter); + } + } + } + function getNonSimpleParameters(parameters) { + return ts.filter(parameters, function (parameter) { return !!parameter.initializer || ts.isBindingPattern(parameter.name) || ts.isRestParameter(parameter); }); + } + function checkGrammarForUseStrictSimpleParameterList(node) { + if (languageVersion >= 3 /* ES2016 */) { + var useStrictDirective_1 = node.body && ts.isBlock(node.body) && ts.findUseStrictPrologue(node.body.statements); + if (useStrictDirective_1) { + var nonSimpleParameters = getNonSimpleParameters(node.parameters); + if (ts.length(nonSimpleParameters)) { + ts.forEach(nonSimpleParameters, function (parameter) { + addRelatedInfo(error(parameter, ts.Diagnostics.This_parameter_is_not_allowed_with_use_strict_directive), ts.createDiagnosticForNode(useStrictDirective_1, ts.Diagnostics.use_strict_directive_used_here)); + }); + var diagnostics_1 = nonSimpleParameters.map(function (parameter, index) { return (index === 0 ? ts.createDiagnosticForNode(parameter, ts.Diagnostics.Non_simple_parameter_declared_here) : ts.createDiagnosticForNode(parameter, ts.Diagnostics.and_here)); }); + addRelatedInfo.apply(void 0, [error(useStrictDirective_1, ts.Diagnostics.use_strict_directive_cannot_be_used_with_non_simple_parameter_list)].concat(diagnostics_1)); + return true; + } + } + } + return false; + } + function checkGrammarFunctionLikeDeclaration(node) { + // Prevent cascading error by short-circuit + var file = ts.getSourceFileOfNode(node); + return checkGrammarDecoratorsAndModifiers(node) || checkGrammarTypeParameterList(node.typeParameters, file) || + checkGrammarParameterList(node.parameters) || checkGrammarArrowFunction(node, file) || + (ts.isFunctionLikeDeclaration(node) && checkGrammarForUseStrictSimpleParameterList(node)); + } + function checkGrammarClassLikeDeclaration(node) { + var file = ts.getSourceFileOfNode(node); + return checkGrammarClassDeclarationHeritageClauses(node) || checkGrammarTypeParameterList(node.typeParameters, file); + } + function checkGrammarArrowFunction(node, file) { + if (!ts.isArrowFunction(node)) { + return false; + } + var equalsGreaterThanToken = node.equalsGreaterThanToken; + var startLine = ts.getLineAndCharacterOfPosition(file, equalsGreaterThanToken.pos).line; + var endLine = ts.getLineAndCharacterOfPosition(file, equalsGreaterThanToken.end).line; + return startLine !== endLine && grammarErrorOnNode(equalsGreaterThanToken, ts.Diagnostics.Line_terminator_not_permitted_before_arrow); + } + function checkGrammarIndexSignatureParameters(node) { + var parameter = node.parameters[0]; + if (node.parameters.length !== 1) { + if (parameter) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_must_have_exactly_one_parameter); + } + else { + return grammarErrorOnNode(node, ts.Diagnostics.An_index_signature_must_have_exactly_one_parameter); + } + } + if (parameter.dotDotDotToken) { + return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.An_index_signature_cannot_have_a_rest_parameter); + } + if (ts.hasModifiers(parameter)) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_cannot_have_an_accessibility_modifier); + } + if (parameter.questionToken) { + return grammarErrorOnNode(parameter.questionToken, ts.Diagnostics.An_index_signature_parameter_cannot_have_a_question_mark); + } + if (parameter.initializer) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_cannot_have_an_initializer); + } + if (!parameter.type) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_must_have_a_type_annotation); + } + if (parameter.type.kind !== 138 /* StringKeyword */ && parameter.type.kind !== 135 /* NumberKeyword */) { + var type = getTypeFromTypeNode(parameter.type); + if (type.flags & 4 /* String */ || type.flags & 8 /* Number */) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead, ts.getTextOfNode(parameter.name), typeToString(type), typeToString(getTypeFromTypeNode(node.type))); + } + if (type.flags & 1048576 /* Union */ && allTypesAssignableToKind(type, 128 /* StringLiteral */, /*strict*/ true)) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead); + } + return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_must_be_string_or_number); + } + if (!node.type) { + return grammarErrorOnNode(node, ts.Diagnostics.An_index_signature_must_have_a_type_annotation); + } + return false; + } + function checkGrammarIndexSignature(node) { + // Prevent cascading error by short-circuit + return checkGrammarDecoratorsAndModifiers(node) || checkGrammarIndexSignatureParameters(node); + } + function checkGrammarForAtLeastOneTypeArgument(node, typeArguments) { + if (typeArguments && typeArguments.length === 0) { + var sourceFile = ts.getSourceFileOfNode(node); + var start = typeArguments.pos - "<".length; + var end = ts.skipTrivia(sourceFile.text, typeArguments.end) + ">".length; + return grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.Type_argument_list_cannot_be_empty); + } + return false; + } + function checkGrammarTypeArguments(node, typeArguments) { + return checkGrammarForDisallowedTrailingComma(typeArguments) || + checkGrammarForAtLeastOneTypeArgument(node, typeArguments); + } + function checkGrammarForOmittedArgument(args) { + if (args) { + for (var _i = 0, args_5 = args; _i < args_5.length; _i++) { + var arg = args_5[_i]; + if (arg.kind === 210 /* OmittedExpression */) { + return grammarErrorAtPos(arg, arg.pos, 0, ts.Diagnostics.Argument_expression_expected); + } + } + } + return false; + } + function checkGrammarArguments(args) { + return checkGrammarForOmittedArgument(args); + } + function checkGrammarHeritageClause(node) { + var types = node.types; + if (checkGrammarForDisallowedTrailingComma(types)) { + return true; + } + if (types && types.length === 0) { + var listType = ts.tokenToString(node.token); + return grammarErrorAtPos(node, types.pos, 0, ts.Diagnostics._0_list_cannot_be_empty, listType); + } + return ts.some(types, checkGrammarExpressionWithTypeArguments); + } + function checkGrammarExpressionWithTypeArguments(node) { + return checkGrammarTypeArguments(node, node.typeArguments); + } + function checkGrammarClassDeclarationHeritageClauses(node) { + var seenExtendsClause = false; + var seenImplementsClause = false; + if (!checkGrammarDecoratorsAndModifiers(node) && node.heritageClauses) { + for (var _i = 0, _a = node.heritageClauses; _i < _a.length; _i++) { + var heritageClause = _a[_i]; + if (heritageClause.token === 86 /* ExtendsKeyword */) { + if (seenExtendsClause) { + return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.extends_clause_already_seen); + } + if (seenImplementsClause) { + return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.extends_clause_must_precede_implements_clause); + } + if (heritageClause.types.length > 1) { + return grammarErrorOnFirstToken(heritageClause.types[1], ts.Diagnostics.Classes_can_only_extend_a_single_class); + } + seenExtendsClause = true; + } + else { + ts.Debug.assert(heritageClause.token === 109 /* ImplementsKeyword */); + if (seenImplementsClause) { + return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.implements_clause_already_seen); + } + seenImplementsClause = true; + } + // Grammar checking heritageClause inside class declaration + checkGrammarHeritageClause(heritageClause); + } + } + } + function checkGrammarInterfaceDeclaration(node) { + var seenExtendsClause = false; + if (node.heritageClauses) { + for (var _i = 0, _a = node.heritageClauses; _i < _a.length; _i++) { + var heritageClause = _a[_i]; + if (heritageClause.token === 86 /* ExtendsKeyword */) { + if (seenExtendsClause) { + return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.extends_clause_already_seen); + } + seenExtendsClause = true; + } + else { + ts.Debug.assert(heritageClause.token === 109 /* ImplementsKeyword */); + return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.Interface_declaration_cannot_have_implements_clause); + } + // Grammar checking heritageClause inside class declaration + checkGrammarHeritageClause(heritageClause); + } + } + return false; + } + function checkGrammarComputedPropertyName(node) { + // If node is not a computedPropertyName, just skip the grammar checking + if (node.kind !== 149 /* ComputedPropertyName */) { + return false; + } + var computedPropertyName = node; + if (computedPropertyName.expression.kind === 204 /* BinaryExpression */ && computedPropertyName.expression.operatorToken.kind === 27 /* CommaToken */) { + return grammarErrorOnNode(computedPropertyName.expression, ts.Diagnostics.A_comma_expression_is_not_allowed_in_a_computed_property_name); + } + return false; + } + function checkGrammarForGenerator(node) { + if (node.asteriskToken) { + ts.Debug.assert(node.kind === 239 /* FunctionDeclaration */ || + node.kind === 196 /* FunctionExpression */ || + node.kind === 156 /* MethodDeclaration */); + if (node.flags & 4194304 /* Ambient */) { + return grammarErrorOnNode(node.asteriskToken, ts.Diagnostics.Generators_are_not_allowed_in_an_ambient_context); + } + if (!node.body) { + return grammarErrorOnNode(node.asteriskToken, ts.Diagnostics.An_overload_signature_cannot_be_declared_as_a_generator); + } + } + } + function checkGrammarForInvalidQuestionMark(questionToken, message) { + return !!questionToken && grammarErrorOnNode(questionToken, message); + } + function checkGrammarForInvalidExclamationToken(exclamationToken, message) { + return !!exclamationToken && grammarErrorOnNode(exclamationToken, message); + } + function checkGrammarObjectLiteralExpression(node, inDestructuring) { + var Flags; + (function (Flags) { + Flags[Flags["Property"] = 1] = "Property"; + Flags[Flags["GetAccessor"] = 2] = "GetAccessor"; + Flags[Flags["SetAccessor"] = 4] = "SetAccessor"; + Flags[Flags["GetOrSetAccessor"] = 6] = "GetOrSetAccessor"; + })(Flags || (Flags = {})); + var seen = ts.createUnderscoreEscapedMap(); + for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { + var prop = _a[_i]; + if (prop.kind === 277 /* SpreadAssignment */) { + continue; + } + var name = prop.name; + if (name.kind === 149 /* ComputedPropertyName */) { + // If the name is not a ComputedPropertyName, the grammar checking will skip it + checkGrammarComputedPropertyName(name); + } + if (prop.kind === 276 /* ShorthandPropertyAssignment */ && !inDestructuring && prop.objectAssignmentInitializer) { + // having objectAssignmentInitializer is only valid in ObjectAssignmentPattern + // outside of destructuring it is a syntax error + return grammarErrorOnNode(prop.equalsToken, ts.Diagnostics.can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment); + } + // Modifiers are never allowed on properties except for 'async' on a method declaration + if (prop.modifiers) { + for (var _b = 0, _c = prop.modifiers; _b < _c.length; _b++) { // TODO: GH#19955 + var mod = _c[_b]; + if (mod.kind !== 121 /* AsyncKeyword */ || prop.kind !== 156 /* MethodDeclaration */) { + grammarErrorOnNode(mod, ts.Diagnostics._0_modifier_cannot_be_used_here, ts.getTextOfNode(mod)); + } + } + } + // ECMA-262 11.1.5 Object Initializer + // If previous is not undefined then throw a SyntaxError exception if any of the following conditions are true + // a.This production is contained in strict code and IsDataDescriptor(previous) is true and + // IsDataDescriptor(propId.descriptor) is true. + // b.IsDataDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true. + // c.IsAccessorDescriptor(previous) is true and IsDataDescriptor(propId.descriptor) is true. + // d.IsAccessorDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true + // and either both previous and propId.descriptor have[[Get]] fields or both previous and propId.descriptor have[[Set]] fields + var currentKind = void 0; + switch (prop.kind) { + case 276 /* ShorthandPropertyAssignment */: + checkGrammarForInvalidExclamationToken(prop.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context); + /* tslint:disable:no-switch-case-fall-through */ + case 275 /* PropertyAssignment */: + // Grammar checking for computedPropertyName and shorthandPropertyAssignment + checkGrammarForInvalidQuestionMark(prop.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional); + if (name.kind === 8 /* NumericLiteral */) { + checkGrammarNumericLiteral(name); + } + // falls through + case 156 /* MethodDeclaration */: + currentKind = 1 /* Property */; + break; + case 158 /* GetAccessor */: + currentKind = 2 /* GetAccessor */; + break; + case 159 /* SetAccessor */: + currentKind = 4 /* SetAccessor */; + break; + default: + throw ts.Debug.assertNever(prop, "Unexpected syntax kind:" + prop.kind); + } + var effectiveName = ts.getPropertyNameForPropertyNameNode(name); + if (effectiveName === undefined) { + continue; + } + var existingKind = seen.get(effectiveName); + if (!existingKind) { + seen.set(effectiveName, currentKind); + } + else { + if (currentKind === 1 /* Property */ && existingKind === 1 /* Property */) { + grammarErrorOnNode(name, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(name)); + } + else if ((currentKind & 6 /* GetOrSetAccessor */) && (existingKind & 6 /* GetOrSetAccessor */)) { + if (existingKind !== 6 /* GetOrSetAccessor */ && currentKind !== existingKind) { + seen.set(effectiveName, currentKind | existingKind); + } + else { + return grammarErrorOnNode(name, ts.Diagnostics.An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name); + } + } + else { + return grammarErrorOnNode(name, ts.Diagnostics.An_object_literal_cannot_have_property_and_accessor_with_the_same_name); + } + } + } + } + function checkGrammarJsxElement(node) { + checkGrammarTypeArguments(node, node.typeArguments); + var seen = ts.createUnderscoreEscapedMap(); + for (var _i = 0, _a = node.attributes.properties; _i < _a.length; _i++) { + var attr = _a[_i]; + if (attr.kind === 269 /* JsxSpreadAttribute */) { + continue; + } + var name = attr.name, initializer = attr.initializer; + if (!seen.get(name.escapedText)) { + seen.set(name.escapedText, true); + } + else { + return grammarErrorOnNode(name, ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name); + } + if (initializer && initializer.kind === 270 /* JsxExpression */ && !initializer.expression) { + return grammarErrorOnNode(initializer, ts.Diagnostics.JSX_attributes_must_only_be_assigned_a_non_empty_expression); + } + } + } + function checkGrammarForInOrForOfStatement(forInOrOfStatement) { + if (checkGrammarStatementInAmbientContext(forInOrOfStatement)) { + return true; + } + if (forInOrOfStatement.kind === 227 /* ForOfStatement */ && forInOrOfStatement.awaitModifier) { + if ((forInOrOfStatement.flags & 16384 /* AwaitContext */) === 0 /* None */) { + return grammarErrorOnNode(forInOrOfStatement.awaitModifier, ts.Diagnostics.A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator); + } + } + if (forInOrOfStatement.initializer.kind === 238 /* VariableDeclarationList */) { + var variableList = forInOrOfStatement.initializer; + if (!checkGrammarVariableDeclarationList(variableList)) { + var declarations = variableList.declarations; + // declarations.length can be zero if there is an error in variable declaration in for-of or for-in + // See http://www.ecma-international.org/ecma-262/6.0/#sec-for-in-and-for-of-statements for details + // For example: + // var let = 10; + // for (let of [1,2,3]) {} // this is invalid ES6 syntax + // for (let in [1,2,3]) {} // this is invalid ES6 syntax + // We will then want to skip on grammar checking on variableList declaration + if (!declarations.length) { + return false; + } + if (declarations.length > 1) { + var diagnostic = forInOrOfStatement.kind === 226 /* ForInStatement */ + ? ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement + : ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement; + return grammarErrorOnFirstToken(variableList.declarations[1], diagnostic); + } + var firstDeclaration = declarations[0]; + if (firstDeclaration.initializer) { + var diagnostic = forInOrOfStatement.kind === 226 /* ForInStatement */ + ? ts.Diagnostics.The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer + : ts.Diagnostics.The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer; + return grammarErrorOnNode(firstDeclaration.name, diagnostic); + } + if (firstDeclaration.type) { + var diagnostic = forInOrOfStatement.kind === 226 /* ForInStatement */ + ? ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation + : ts.Diagnostics.The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation; + return grammarErrorOnNode(firstDeclaration, diagnostic); + } + } + } + return false; + } + function checkGrammarAccessor(accessor) { + var kind = accessor.kind; + if (languageVersion < 1 /* ES5 */) { + return grammarErrorOnNode(accessor.name, ts.Diagnostics.Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher); + } + else if (accessor.flags & 4194304 /* Ambient */) { + return grammarErrorOnNode(accessor.name, ts.Diagnostics.An_accessor_cannot_be_declared_in_an_ambient_context); + } + else if (accessor.body === undefined && !ts.hasModifier(accessor, 128 /* Abstract */)) { + return grammarErrorAtPos(accessor, accessor.end - 1, ";".length, ts.Diagnostics._0_expected, "{"); + } + else if (accessor.body && ts.hasModifier(accessor, 128 /* Abstract */)) { + return grammarErrorOnNode(accessor, ts.Diagnostics.An_abstract_accessor_cannot_have_an_implementation); + } + else if (accessor.typeParameters) { + return grammarErrorOnNode(accessor.name, ts.Diagnostics.An_accessor_cannot_have_type_parameters); + } + else if (!doesAccessorHaveCorrectParameterCount(accessor)) { + return grammarErrorOnNode(accessor.name, kind === 158 /* GetAccessor */ ? + ts.Diagnostics.A_get_accessor_cannot_have_parameters : + ts.Diagnostics.A_set_accessor_must_have_exactly_one_parameter); + } + else if (kind === 159 /* SetAccessor */) { + if (accessor.type) { + return grammarErrorOnNode(accessor.name, ts.Diagnostics.A_set_accessor_cannot_have_a_return_type_annotation); + } + else { + var parameter = accessor.parameters[0]; + if (parameter.dotDotDotToken) { + return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.A_set_accessor_cannot_have_rest_parameter); + } + else if (parameter.questionToken) { + return grammarErrorOnNode(parameter.questionToken, ts.Diagnostics.A_set_accessor_cannot_have_an_optional_parameter); + } + else if (parameter.initializer) { + return grammarErrorOnNode(accessor.name, ts.Diagnostics.A_set_accessor_parameter_cannot_have_an_initializer); + } + } + } + return false; + } + /** Does the accessor have the right number of parameters? + * A get accessor has no parameters or a single `this` parameter. + * A set accessor has one parameter or a `this` parameter and one more parameter. + */ + function doesAccessorHaveCorrectParameterCount(accessor) { + return getAccessorThisParameter(accessor) || accessor.parameters.length === (accessor.kind === 158 /* GetAccessor */ ? 0 : 1); + } + function getAccessorThisParameter(accessor) { + if (accessor.parameters.length === (accessor.kind === 158 /* GetAccessor */ ? 1 : 2)) { + return ts.getThisParameter(accessor); + } + } + function checkGrammarTypeOperatorNode(node) { + if (node.operator === 142 /* UniqueKeyword */) { + if (node.type.kind !== 139 /* SymbolKeyword */) { + return grammarErrorOnNode(node.type, ts.Diagnostics._0_expected, ts.tokenToString(139 /* SymbolKeyword */)); + } + var parent = ts.walkUpParenthesizedTypes(node.parent); + switch (parent.kind) { + case 237 /* VariableDeclaration */: + var decl = parent; + if (decl.name.kind !== 72 /* Identifier */) { + return grammarErrorOnNode(node, ts.Diagnostics.unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name); + } + if (!ts.isVariableDeclarationInVariableStatement(decl)) { + return grammarErrorOnNode(node, ts.Diagnostics.unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement); + } + if (!(decl.parent.flags & 2 /* Const */)) { + return grammarErrorOnNode(parent.name, ts.Diagnostics.A_variable_whose_type_is_a_unique_symbol_type_must_be_const); + } + break; + case 154 /* PropertyDeclaration */: + if (!ts.hasModifier(parent, 32 /* Static */) || + !ts.hasModifier(parent, 64 /* Readonly */)) { + return grammarErrorOnNode(parent.name, ts.Diagnostics.A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly); + } + break; + case 153 /* PropertySignature */: + if (!ts.hasModifier(parent, 64 /* Readonly */)) { + return grammarErrorOnNode(parent.name, ts.Diagnostics.A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly); + } + break; + default: + return grammarErrorOnNode(node, ts.Diagnostics.unique_symbol_types_are_not_allowed_here); + } + } + } + function checkGrammarForInvalidDynamicName(node, message) { + if (isNonBindableDynamicName(node)) { + return grammarErrorOnNode(node, message); + } + } + function checkGrammarMethod(node) { + if (checkGrammarFunctionLikeDeclaration(node)) { + return true; + } + if (node.kind === 156 /* MethodDeclaration */) { + if (node.parent.kind === 188 /* ObjectLiteralExpression */) { + // We only disallow modifier on a method declaration if it is a property of object-literal-expression + if (node.modifiers && !(node.modifiers.length === 1 && ts.first(node.modifiers).kind === 121 /* AsyncKeyword */)) { + return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); + } + else if (checkGrammarForInvalidQuestionMark(node.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional)) { + return true; + } + else if (checkGrammarForInvalidExclamationToken(node.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context)) { + return true; + } + else if (node.body === undefined) { + return grammarErrorAtPos(node, node.end - 1, ";".length, ts.Diagnostics._0_expected, "{"); + } + } + if (checkGrammarForGenerator(node)) { + return true; + } + } + if (ts.isClassLike(node.parent)) { + // Technically, computed properties in ambient contexts is disallowed + // for property declarations and accessors too, not just methods. + // However, property declarations disallow computed names in general, + // and accessors are not allowed in ambient contexts in general, + // so this error only really matters for methods. + if (node.flags & 4194304 /* Ambient */) { + return checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type); + } + else if (node.kind === 156 /* MethodDeclaration */ && !node.body) { + return checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type); + } + } + else if (node.parent.kind === 241 /* InterfaceDeclaration */) { + return checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type); + } + else if (node.parent.kind === 168 /* TypeLiteral */) { + return checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type); + } + } + function checkGrammarBreakOrContinueStatement(node) { + var current = node; + while (current) { + if (ts.isFunctionLike(current)) { + return grammarErrorOnNode(node, ts.Diagnostics.Jump_target_cannot_cross_function_boundary); + } + switch (current.kind) { + case 233 /* LabeledStatement */: + if (node.label && current.label.escapedText === node.label.escapedText) { + // found matching label - verify that label usage is correct + // continue can only target labels that are on iteration statements + var isMisplacedContinueLabel = node.kind === 228 /* ContinueStatement */ + && !ts.isIterationStatement(current.statement, /*lookInLabeledStatement*/ true); + if (isMisplacedContinueLabel) { + return grammarErrorOnNode(node, ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement); + } + return false; + } + break; + case 232 /* SwitchStatement */: + if (node.kind === 229 /* BreakStatement */ && !node.label) { + // unlabeled break within switch statement - ok + return false; + } + break; + default: + if (ts.isIterationStatement(current, /*lookInLabeledStatement*/ false) && !node.label) { + // unlabeled break or continue within iteration statement - ok + return false; + } + break; + } + current = current.parent; + } + if (node.label) { + var message = node.kind === 229 /* BreakStatement */ + ? ts.Diagnostics.A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement + : ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement; + return grammarErrorOnNode(node, message); + } + else { + var message = node.kind === 229 /* BreakStatement */ + ? ts.Diagnostics.A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement + : ts.Diagnostics.A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement; + return grammarErrorOnNode(node, message); + } + } + function checkGrammarBindingElement(node) { + if (node.dotDotDotToken) { + var elements = node.parent.elements; + if (node !== ts.last(elements)) { + return grammarErrorOnNode(node, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern); + } + checkGrammarForDisallowedTrailingComma(elements, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma); + if (node.propertyName) { + return grammarErrorOnNode(node.name, ts.Diagnostics.A_rest_element_cannot_have_a_property_name); + } + if (node.initializer) { + // Error on equals token which immediately precedes the initializer + return grammarErrorAtPos(node, node.initializer.pos - 1, 1, ts.Diagnostics.A_rest_element_cannot_have_an_initializer); + } + } + } + function isStringOrNumberLiteralExpression(expr) { + return expr.kind === 10 /* StringLiteral */ || expr.kind === 8 /* NumericLiteral */ || + expr.kind === 202 /* PrefixUnaryExpression */ && expr.operator === 39 /* MinusToken */ && + expr.operand.kind === 8 /* NumericLiteral */; + } + function isBigIntLiteralExpression(expr) { + return expr.kind === 9 /* BigIntLiteral */ || + expr.kind === 202 /* PrefixUnaryExpression */ && expr.operator === 39 /* MinusToken */ && + expr.operand.kind === 9 /* BigIntLiteral */; + } + function isSimpleLiteralEnumReference(expr) { + if ((ts.isPropertyAccessExpression(expr) || (ts.isElementAccessExpression(expr) && isStringOrNumberLiteralExpression(expr.argumentExpression))) && + ts.isEntityNameExpression(expr.expression)) + return !!(checkExpressionCached(expr).flags & 1024 /* EnumLiteral */); + } + function checkAmbientInitializer(node) { + var initializer = node.initializer; + if (initializer) { + var isInvalidInitializer = !(isStringOrNumberLiteralExpression(initializer) || + isSimpleLiteralEnumReference(initializer) || + initializer.kind === 102 /* TrueKeyword */ || initializer.kind === 87 /* FalseKeyword */ || + isBigIntLiteralExpression(initializer)); + var isConstOrReadonly = ts.isDeclarationReadonly(node) || ts.isVariableDeclaration(node) && ts.isVarConst(node); + if (isConstOrReadonly && !node.type) { + if (isInvalidInitializer) { + return grammarErrorOnNode(initializer, ts.Diagnostics.A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_reference); + } + } + else { + return grammarErrorOnNode(initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); + } + if (!isConstOrReadonly || isInvalidInitializer) { + return grammarErrorOnNode(initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); + } + } + } + function checkGrammarVariableDeclaration(node) { + if (node.parent.parent.kind !== 226 /* ForInStatement */ && node.parent.parent.kind !== 227 /* ForOfStatement */) { + if (node.flags & 4194304 /* Ambient */) { + checkAmbientInitializer(node); + } + else if (!node.initializer) { + if (ts.isBindingPattern(node.name) && !ts.isBindingPattern(node.parent)) { + return grammarErrorOnNode(node, ts.Diagnostics.A_destructuring_declaration_must_have_an_initializer); + } + if (ts.isVarConst(node)) { + return grammarErrorOnNode(node, ts.Diagnostics.const_declarations_must_be_initialized); + } + } + } + if (node.exclamationToken && (node.parent.parent.kind !== 219 /* VariableStatement */ || !node.type || node.initializer || node.flags & 4194304 /* Ambient */)) { + return grammarErrorOnNode(node.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context); + } + if (compilerOptions.module !== ts.ModuleKind.ES2015 && compilerOptions.module !== ts.ModuleKind.ESNext && compilerOptions.module !== ts.ModuleKind.System && !compilerOptions.noEmit && + !(node.parent.parent.flags & 4194304 /* Ambient */) && ts.hasModifier(node.parent.parent, 1 /* Export */)) { + checkESModuleMarker(node.name); + } + var checkLetConstNames = (ts.isLet(node) || ts.isVarConst(node)); + // 1. LexicalDeclaration : LetOrConst BindingList ; + // It is a Syntax Error if the BoundNames of BindingList contains "let". + // 2. ForDeclaration: ForDeclaration : LetOrConst ForBinding + // It is a Syntax Error if the BoundNames of ForDeclaration contains "let". + // It is a SyntaxError if a VariableDeclaration or VariableDeclarationNoIn occurs within strict code + // and its Identifier is eval or arguments + return checkLetConstNames && checkGrammarNameInLetOrConstDeclarations(node.name); + } + function checkESModuleMarker(name) { + if (name.kind === 72 /* Identifier */) { + if (ts.idText(name) === "__esModule") { + return grammarErrorOnNode(name, ts.Diagnostics.Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules); + } + } + else { + var elements = name.elements; + for (var _i = 0, elements_1 = elements; _i < elements_1.length; _i++) { + var element = elements_1[_i]; + if (!ts.isOmittedExpression(element)) { + return checkESModuleMarker(element.name); + } + } + } + return false; + } + function checkGrammarNameInLetOrConstDeclarations(name) { + if (name.kind === 72 /* Identifier */) { + if (name.originalKeywordKind === 111 /* LetKeyword */) { + return grammarErrorOnNode(name, ts.Diagnostics.let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations); + } + } + else { + var elements = name.elements; + for (var _i = 0, elements_2 = elements; _i < elements_2.length; _i++) { + var element = elements_2[_i]; + if (!ts.isOmittedExpression(element)) { + checkGrammarNameInLetOrConstDeclarations(element.name); + } + } + } + return false; + } + function checkGrammarVariableDeclarationList(declarationList) { + var declarations = declarationList.declarations; + if (checkGrammarForDisallowedTrailingComma(declarationList.declarations)) { + return true; + } + if (!declarationList.declarations.length) { + return grammarErrorAtPos(declarationList, declarations.pos, declarations.end - declarations.pos, ts.Diagnostics.Variable_declaration_list_cannot_be_empty); + } + return false; + } + function allowLetAndConstDeclarations(parent) { + switch (parent.kind) { + case 222 /* IfStatement */: + case 223 /* DoStatement */: + case 224 /* WhileStatement */: + case 231 /* WithStatement */: + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + return false; + case 233 /* LabeledStatement */: + return allowLetAndConstDeclarations(parent.parent); + } + return true; + } + function checkGrammarForDisallowedLetOrConstStatement(node) { + if (!allowLetAndConstDeclarations(node.parent)) { + if (ts.isLet(node.declarationList)) { + return grammarErrorOnNode(node, ts.Diagnostics.let_declarations_can_only_be_declared_inside_a_block); + } + else if (ts.isVarConst(node.declarationList)) { + return grammarErrorOnNode(node, ts.Diagnostics.const_declarations_can_only_be_declared_inside_a_block); + } + } + } + function checkGrammarMetaProperty(node) { + var escapedText = node.name.escapedText; + switch (node.keywordToken) { + case 95 /* NewKeyword */: + if (escapedText !== "target") { + return grammarErrorOnNode(node.name, ts.Diagnostics._0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2, node.name.escapedText, ts.tokenToString(node.keywordToken), "target"); + } + break; + case 92 /* ImportKeyword */: + if (escapedText !== "meta") { + return grammarErrorOnNode(node.name, ts.Diagnostics._0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2, node.name.escapedText, ts.tokenToString(node.keywordToken), "meta"); + } + break; + } + } + function hasParseDiagnostics(sourceFile) { + return sourceFile.parseDiagnostics.length > 0; + } + function grammarErrorOnFirstToken(node, message, arg0, arg1, arg2) { + var sourceFile = ts.getSourceFileOfNode(node); + if (!hasParseDiagnostics(sourceFile)) { + var span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos); + diagnostics.add(ts.createFileDiagnostic(sourceFile, span.start, span.length, message, arg0, arg1, arg2)); + return true; + } + return false; + } + function grammarErrorAtPos(nodeForSourceFile, start, length, message, arg0, arg1, arg2) { + var sourceFile = ts.getSourceFileOfNode(nodeForSourceFile); + if (!hasParseDiagnostics(sourceFile)) { + diagnostics.add(ts.createFileDiagnostic(sourceFile, start, length, message, arg0, arg1, arg2)); + return true; + } + return false; + } + function grammarErrorOnNode(node, message, arg0, arg1, arg2) { + var sourceFile = ts.getSourceFileOfNode(node); + if (!hasParseDiagnostics(sourceFile)) { + diagnostics.add(ts.createDiagnosticForNode(node, message, arg0, arg1, arg2)); + return true; + } + return false; + } + function checkGrammarConstructorTypeParameters(node) { + var jsdocTypeParameters = ts.isInJSFile(node) ? ts.getJSDocTypeParameterDeclarations(node) : undefined; + var range = node.typeParameters || jsdocTypeParameters && ts.firstOrUndefined(jsdocTypeParameters); + if (range) { + var pos = range.pos === range.end ? range.pos : ts.skipTrivia(ts.getSourceFileOfNode(node).text, range.pos); + return grammarErrorAtPos(node, pos, range.end - pos, ts.Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration); + } + } + function checkGrammarConstructorTypeAnnotation(node) { + var type = ts.getEffectiveReturnTypeNode(node); + if (type) { + return grammarErrorOnNode(type, ts.Diagnostics.Type_annotation_cannot_appear_on_a_constructor_declaration); + } + } + function checkGrammarProperty(node) { + if (ts.isClassLike(node.parent)) { + if (checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_class_property_declaration_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type)) { + return true; + } + } + else if (node.parent.kind === 241 /* InterfaceDeclaration */) { + if (checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type)) { + return true; + } + if (node.initializer) { + return grammarErrorOnNode(node.initializer, ts.Diagnostics.An_interface_property_cannot_have_an_initializer); + } + } + else if (node.parent.kind === 168 /* TypeLiteral */) { + if (checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type)) { + return true; + } + if (node.initializer) { + return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_type_literal_property_cannot_have_an_initializer); + } + } + if (node.flags & 4194304 /* Ambient */) { + checkAmbientInitializer(node); + } + if (ts.isPropertyDeclaration(node) && node.exclamationToken && (!ts.isClassLike(node.parent) || !node.type || node.initializer || + node.flags & 4194304 /* Ambient */ || ts.hasModifier(node, 32 /* Static */ | 128 /* Abstract */))) { + return grammarErrorOnNode(node.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context); + } + } + function checkGrammarTopLevelElementForRequiredDeclareModifier(node) { + // A declare modifier is required for any top level .d.ts declaration except export=, export default, export as namespace + // interfaces and imports categories: + // + // DeclarationElement: + // ExportAssignment + // export_opt InterfaceDeclaration + // export_opt TypeAliasDeclaration + // export_opt ImportDeclaration + // export_opt ExternalImportDeclaration + // export_opt AmbientDeclaration + // + // TODO: The spec needs to be amended to reflect this grammar. + if (node.kind === 241 /* InterfaceDeclaration */ || + node.kind === 242 /* TypeAliasDeclaration */ || + node.kind === 249 /* ImportDeclaration */ || + node.kind === 248 /* ImportEqualsDeclaration */ || + node.kind === 255 /* ExportDeclaration */ || + node.kind === 254 /* ExportAssignment */ || + node.kind === 247 /* NamespaceExportDeclaration */ || + ts.hasModifier(node, 2 /* Ambient */ | 1 /* Export */ | 512 /* Default */)) { + return false; + } + return grammarErrorOnFirstToken(node, ts.Diagnostics.A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file); + } + function checkGrammarTopLevelElementsForRequiredDeclareModifier(file) { + for (var _i = 0, _a = file.statements; _i < _a.length; _i++) { + var decl = _a[_i]; + if (ts.isDeclaration(decl) || decl.kind === 219 /* VariableStatement */) { + if (checkGrammarTopLevelElementForRequiredDeclareModifier(decl)) { + return true; + } + } + } + return false; + } + function checkGrammarSourceFile(node) { + return !!(node.flags & 4194304 /* Ambient */) && checkGrammarTopLevelElementsForRequiredDeclareModifier(node); + } + function checkGrammarStatementInAmbientContext(node) { + if (node.flags & 4194304 /* Ambient */) { + // An accessors is already reported about the ambient context + if (ts.isAccessor(node.parent)) { + return getNodeLinks(node).hasReportedStatementInAmbientContext = true; + } + // Find containing block which is either Block, ModuleBlock, SourceFile + var links = getNodeLinks(node); + if (!links.hasReportedStatementInAmbientContext && ts.isFunctionLike(node.parent)) { + return getNodeLinks(node).hasReportedStatementInAmbientContext = grammarErrorOnFirstToken(node, ts.Diagnostics.An_implementation_cannot_be_declared_in_ambient_contexts); + } + // We are either parented by another statement, or some sort of block. + // If we're in a block, we only want to really report an error once + // to prevent noisiness. So use a bit on the block to indicate if + // this has already been reported, and don't report if it has. + // + if (node.parent.kind === 218 /* Block */ || node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 279 /* SourceFile */) { + var links_2 = getNodeLinks(node.parent); + // Check if the containing block ever report this error + if (!links_2.hasReportedStatementInAmbientContext) { + return links_2.hasReportedStatementInAmbientContext = grammarErrorOnFirstToken(node, ts.Diagnostics.Statements_are_not_allowed_in_ambient_contexts); + } + } + else { + // We must be parented by a statement. If so, there's no need + // to report the error as our parent will have already done it. + // Debug.assert(isStatement(node.parent)); + } + } + return false; + } + function checkGrammarNumericLiteral(node) { + // Grammar checking + if (node.numericLiteralFlags & 32 /* Octal */) { + var diagnosticMessage = void 0; + if (languageVersion >= 1 /* ES5 */) { + diagnosticMessage = ts.Diagnostics.Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0; + } + else if (ts.isChildOfNodeWithKind(node, 182 /* LiteralType */)) { + diagnosticMessage = ts.Diagnostics.Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0; + } + else if (ts.isChildOfNodeWithKind(node, 278 /* EnumMember */)) { + diagnosticMessage = ts.Diagnostics.Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0; + } + if (diagnosticMessage) { + var withMinus = ts.isPrefixUnaryExpression(node.parent) && node.parent.operator === 39 /* MinusToken */; + var literal = (withMinus ? "-" : "") + "0o" + node.text; + return grammarErrorOnNode(withMinus ? node.parent : node, diagnosticMessage, literal); + } + } + return false; + } + function checkGrammarBigIntLiteral(node) { + var literalType = ts.isLiteralTypeNode(node.parent) || + ts.isPrefixUnaryExpression(node.parent) && ts.isLiteralTypeNode(node.parent.parent); + if (!literalType) { + if (languageVersion < 6 /* ESNext */) { + if (grammarErrorOnNode(node, ts.Diagnostics.BigInt_literals_are_not_available_when_targeting_lower_than_ESNext)) { + return true; + } + } + } + return false; + } + function grammarErrorAfterFirstToken(node, message, arg0, arg1, arg2) { + var sourceFile = ts.getSourceFileOfNode(node); + if (!hasParseDiagnostics(sourceFile)) { + var span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos); + diagnostics.add(ts.createFileDiagnostic(sourceFile, ts.textSpanEnd(span), /*length*/ 0, message, arg0, arg1, arg2)); + return true; + } + return false; + } + function getAmbientModules() { + if (!ambientModulesCache) { + ambientModulesCache = []; + globals.forEach(function (global, sym) { + // No need to `unescapeLeadingUnderscores`, an escaped symbol is never an ambient module. + if (ambientModuleSymbolRegex.test(sym)) { + ambientModulesCache.push(global); + } + }); + } + return ambientModulesCache; + } + function checkGrammarImportCallExpression(node) { + if (moduleKind === ts.ModuleKind.ES2015) { + return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext); + } + if (node.typeArguments) { + return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_import_cannot_have_type_arguments); + } + var nodeArguments = node.arguments; + if (nodeArguments.length !== 1) { + return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_import_must_have_one_specifier_as_an_argument); + } + // see: parseArgumentOrArrayLiteralElement...we use this function which parse arguments of callExpression to parse specifier for dynamic import. + // parseArgumentOrArrayLiteralElement allows spread element to be in an argument list which is not allowed as specifier in dynamic import. + if (ts.isSpreadElement(nodeArguments[0])) { + return grammarErrorOnNode(nodeArguments[0], ts.Diagnostics.Specifier_of_dynamic_import_cannot_be_spread_element); + } + return false; + } + } + ts.createTypeChecker = createTypeChecker; + /** Like 'isDeclarationName', but returns true for LHS of `import { x as y }` or `export { x as y }`. */ + function isDeclarationNameOrImportPropertyName(name) { + switch (name.parent.kind) { + case 253 /* ImportSpecifier */: + case 257 /* ExportSpecifier */: + return ts.isIdentifier(name); + default: + return ts.isDeclarationName(name); + } + } + function isSomeImportDeclaration(decl) { + switch (decl.kind) { + case 250 /* ImportClause */: // For default import + case 248 /* ImportEqualsDeclaration */: + case 251 /* NamespaceImport */: + case 253 /* ImportSpecifier */: // For rename import `x as y` + return true; + case 72 /* Identifier */: + // For regular import, `decl` is an Identifier under the ImportSpecifier. + return decl.parent.kind === 253 /* ImportSpecifier */; + default: + return false; + } + } + var JsxNames; + (function (JsxNames) { + // tslint:disable variable-name + JsxNames.JSX = "JSX"; + JsxNames.IntrinsicElements = "IntrinsicElements"; + JsxNames.ElementClass = "ElementClass"; + JsxNames.ElementAttributesPropertyNameContainer = "ElementAttributesProperty"; // TODO: Deprecate and remove support + JsxNames.ElementChildrenAttributeNameContainer = "ElementChildrenAttribute"; + JsxNames.Element = "Element"; + JsxNames.IntrinsicAttributes = "IntrinsicAttributes"; + JsxNames.IntrinsicClassAttributes = "IntrinsicClassAttributes"; + JsxNames.LibraryManagedAttributes = "LibraryManagedAttributes"; + // tslint:enable variable-name + })(JsxNames || (JsxNames = {})); + function typeIsLiteralType(type) { + return !!(type.flags & 2944 /* Literal */); + } +})(ts || (ts = {})); +var ts; +(function (ts) { + function createSynthesizedNode(kind) { + var node = ts.createNode(kind, -1, -1); + node.flags |= 8 /* Synthesized */; + return node; + } + /* @internal */ + function updateNode(updated, original) { + if (updated !== original) { + setOriginalNode(updated, original); + setTextRange(updated, original); + ts.aggregateTransformFlags(updated); + } + return updated; + } + ts.updateNode = updateNode; + /** + * Make `elements` into a `NodeArray`. If `elements` is `undefined`, returns an empty `NodeArray`. + */ + function createNodeArray(elements, hasTrailingComma) { + if (!elements || elements === ts.emptyArray) { + elements = []; + } + else if (ts.isNodeArray(elements)) { + return elements; + } + var array = elements; + array.pos = -1; + array.end = -1; + array.hasTrailingComma = hasTrailingComma; + return array; + } + ts.createNodeArray = createNodeArray; + /** + * Creates a shallow, memberwise clone of a node with no source map location. + */ + /* @internal */ + function getSynthesizedClone(node) { + // We don't use "clone" from core.ts here, as we need to preserve the prototype chain of + // the original node. We also need to exclude specific properties and only include own- + // properties (to skip members already defined on the shared prototype). + if (node === undefined) { + return node; + } + var clone = createSynthesizedNode(node.kind); + clone.flags |= node.flags; + setOriginalNode(clone, node); + for (var key in node) { + if (clone.hasOwnProperty(key) || !node.hasOwnProperty(key)) { + continue; + } + clone[key] = node[key]; + } + return clone; + } + ts.getSynthesizedClone = getSynthesizedClone; + function createLiteral(value, isSingleQuote) { + if (typeof value === "number") { + return createNumericLiteral(value + ""); + } + if (typeof value === "object" && "base10Value" in value) { // PseudoBigInt + return createBigIntLiteral(ts.pseudoBigIntToString(value) + "n"); + } + if (typeof value === "boolean") { + return value ? createTrue() : createFalse(); + } + if (ts.isString(value)) { + var res = createStringLiteral(value); + if (isSingleQuote) + res.singleQuote = true; + return res; + } + return createLiteralFromNode(value); + } + ts.createLiteral = createLiteral; + function createNumericLiteral(value) { + var node = createSynthesizedNode(8 /* NumericLiteral */); + node.text = value; + node.numericLiteralFlags = 0; + return node; + } + ts.createNumericLiteral = createNumericLiteral; + function createBigIntLiteral(value) { + var node = createSynthesizedNode(9 /* BigIntLiteral */); + node.text = value; + return node; + } + ts.createBigIntLiteral = createBigIntLiteral; + function createStringLiteral(text) { + var node = createSynthesizedNode(10 /* StringLiteral */); + node.text = text; + return node; + } + ts.createStringLiteral = createStringLiteral; + function createRegularExpressionLiteral(text) { + var node = createSynthesizedNode(13 /* RegularExpressionLiteral */); + node.text = text; + return node; + } + ts.createRegularExpressionLiteral = createRegularExpressionLiteral; + function createLiteralFromNode(sourceNode) { + var node = createStringLiteral(ts.getTextOfIdentifierOrLiteral(sourceNode)); + node.textSourceNode = sourceNode; + return node; + } + function createIdentifier(text, typeArguments) { + var node = createSynthesizedNode(72 /* Identifier */); + node.escapedText = ts.escapeLeadingUnderscores(text); + node.originalKeywordKind = text ? ts.stringToToken(text) : 0 /* Unknown */; + node.autoGenerateFlags = 0 /* None */; + node.autoGenerateId = 0; + if (typeArguments) { + node.typeArguments = createNodeArray(typeArguments); + } + return node; + } + ts.createIdentifier = createIdentifier; + function updateIdentifier(node, typeArguments) { + return node.typeArguments !== typeArguments + ? updateNode(createIdentifier(ts.idText(node), typeArguments), node) + : node; + } + ts.updateIdentifier = updateIdentifier; + var nextAutoGenerateId = 0; + function createTempVariable(recordTempVariable, reservedInNestedScopes) { + var name = createIdentifier(""); + name.autoGenerateFlags = 1 /* Auto */; + name.autoGenerateId = nextAutoGenerateId; + nextAutoGenerateId++; + if (recordTempVariable) { + recordTempVariable(name); + } + if (reservedInNestedScopes) { + name.autoGenerateFlags |= 8 /* ReservedInNestedScopes */; + } + return name; + } + ts.createTempVariable = createTempVariable; + /** Create a unique temporary variable for use in a loop. */ + function createLoopVariable() { + var name = createIdentifier(""); + name.autoGenerateFlags = 2 /* Loop */; + name.autoGenerateId = nextAutoGenerateId; + nextAutoGenerateId++; + return name; + } + ts.createLoopVariable = createLoopVariable; + /** Create a unique name based on the supplied text. */ + function createUniqueName(text) { + var name = createIdentifier(text); + name.autoGenerateFlags = 3 /* Unique */; + name.autoGenerateId = nextAutoGenerateId; + nextAutoGenerateId++; + return name; + } + ts.createUniqueName = createUniqueName; + function createOptimisticUniqueName(text) { + var name = createIdentifier(text); + name.autoGenerateFlags = 3 /* Unique */ | 16 /* Optimistic */; + name.autoGenerateId = nextAutoGenerateId; + nextAutoGenerateId++; + return name; + } + ts.createOptimisticUniqueName = createOptimisticUniqueName; + /** Create a unique name based on the supplied text. This does not consider names injected by the transformer. */ + function createFileLevelUniqueName(text) { + var name = createOptimisticUniqueName(text); + name.autoGenerateFlags |= 32 /* FileLevel */; + return name; + } + ts.createFileLevelUniqueName = createFileLevelUniqueName; + function getGeneratedNameForNode(node, flags) { + var name = createIdentifier(node && ts.isIdentifier(node) ? ts.idText(node) : ""); + name.autoGenerateFlags = 4 /* Node */ | flags; + name.autoGenerateId = nextAutoGenerateId; + name.original = node; + nextAutoGenerateId++; + return name; + } + ts.getGeneratedNameForNode = getGeneratedNameForNode; + // Punctuation + function createToken(token) { + return createSynthesizedNode(token); + } + ts.createToken = createToken; + // Reserved words + function createSuper() { + return createSynthesizedNode(98 /* SuperKeyword */); + } + ts.createSuper = createSuper; + function createThis() { + return createSynthesizedNode(100 /* ThisKeyword */); + } + ts.createThis = createThis; + function createNull() { + return createSynthesizedNode(96 /* NullKeyword */); + } + ts.createNull = createNull; + function createTrue() { + return createSynthesizedNode(102 /* TrueKeyword */); + } + ts.createTrue = createTrue; + function createFalse() { + return createSynthesizedNode(87 /* FalseKeyword */); + } + ts.createFalse = createFalse; + // Modifiers + function createModifier(kind) { + return createToken(kind); + } + ts.createModifier = createModifier; + function createModifiersFromModifierFlags(flags) { + var result = []; + if (flags & 1 /* Export */) { + result.push(createModifier(85 /* ExportKeyword */)); + } + if (flags & 2 /* Ambient */) { + result.push(createModifier(125 /* DeclareKeyword */)); + } + if (flags & 512 /* Default */) { + result.push(createModifier(80 /* DefaultKeyword */)); + } + if (flags & 2048 /* Const */) { + result.push(createModifier(77 /* ConstKeyword */)); + } + if (flags & 4 /* Public */) { + result.push(createModifier(115 /* PublicKeyword */)); + } + if (flags & 8 /* Private */) { + result.push(createModifier(113 /* PrivateKeyword */)); + } + if (flags & 16 /* Protected */) { + result.push(createModifier(114 /* ProtectedKeyword */)); + } + if (flags & 128 /* Abstract */) { + result.push(createModifier(118 /* AbstractKeyword */)); + } + if (flags & 32 /* Static */) { + result.push(createModifier(116 /* StaticKeyword */)); + } + if (flags & 64 /* Readonly */) { + result.push(createModifier(133 /* ReadonlyKeyword */)); + } + if (flags & 256 /* Async */) { + result.push(createModifier(121 /* AsyncKeyword */)); + } + return result; + } + ts.createModifiersFromModifierFlags = createModifiersFromModifierFlags; + // Names + function createQualifiedName(left, right) { + var node = createSynthesizedNode(148 /* QualifiedName */); + node.left = left; + node.right = asName(right); + return node; + } + ts.createQualifiedName = createQualifiedName; + function updateQualifiedName(node, left, right) { + return node.left !== left + || node.right !== right + ? updateNode(createQualifiedName(left, right), node) + : node; + } + ts.updateQualifiedName = updateQualifiedName; + function parenthesizeForComputedName(expression) { + return ts.isCommaSequence(expression) + ? createParen(expression) + : expression; + } + function createComputedPropertyName(expression) { + var node = createSynthesizedNode(149 /* ComputedPropertyName */); + node.expression = parenthesizeForComputedName(expression); + return node; + } + ts.createComputedPropertyName = createComputedPropertyName; + function updateComputedPropertyName(node, expression) { + return node.expression !== expression + ? updateNode(createComputedPropertyName(expression), node) + : node; + } + ts.updateComputedPropertyName = updateComputedPropertyName; + // Signature elements + function createTypeParameterDeclaration(name, constraint, defaultType) { + var node = createSynthesizedNode(150 /* TypeParameter */); + node.name = asName(name); + node.constraint = constraint; + node.default = defaultType; + return node; + } + ts.createTypeParameterDeclaration = createTypeParameterDeclaration; + function updateTypeParameterDeclaration(node, name, constraint, defaultType) { + return node.name !== name + || node.constraint !== constraint + || node.default !== defaultType + ? updateNode(createTypeParameterDeclaration(name, constraint, defaultType), node) + : node; + } + ts.updateTypeParameterDeclaration = updateTypeParameterDeclaration; + function createParameter(decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer) { + var node = createSynthesizedNode(151 /* Parameter */); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.dotDotDotToken = dotDotDotToken; + node.name = asName(name); + node.questionToken = questionToken; + node.type = type; + node.initializer = initializer ? ts.parenthesizeExpressionForList(initializer) : undefined; + return node; + } + ts.createParameter = createParameter; + function updateParameter(node, decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.dotDotDotToken !== dotDotDotToken + || node.name !== name + || node.questionToken !== questionToken + || node.type !== type + || node.initializer !== initializer + ? updateNode(createParameter(decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer), node) + : node; + } + ts.updateParameter = updateParameter; + function createDecorator(expression) { + var node = createSynthesizedNode(152 /* Decorator */); + node.expression = ts.parenthesizeForAccess(expression); + return node; + } + ts.createDecorator = createDecorator; + function updateDecorator(node, expression) { + return node.expression !== expression + ? updateNode(createDecorator(expression), node) + : node; + } + ts.updateDecorator = updateDecorator; + // Type Elements + function createPropertySignature(modifiers, name, questionToken, type, initializer) { + var node = createSynthesizedNode(153 /* PropertySignature */); + node.modifiers = asNodeArray(modifiers); + node.name = asName(name); + node.questionToken = questionToken; + node.type = type; + node.initializer = initializer; + return node; + } + ts.createPropertySignature = createPropertySignature; + function updatePropertySignature(node, modifiers, name, questionToken, type, initializer) { + return node.modifiers !== modifiers + || node.name !== name + || node.questionToken !== questionToken + || node.type !== type + || node.initializer !== initializer + ? updateNode(createPropertySignature(modifiers, name, questionToken, type, initializer), node) + : node; + } + ts.updatePropertySignature = updatePropertySignature; + function createProperty(decorators, modifiers, name, questionOrExclamationToken, type, initializer) { + var node = createSynthesizedNode(154 /* PropertyDeclaration */); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.name = asName(name); + node.questionToken = questionOrExclamationToken !== undefined && questionOrExclamationToken.kind === 56 /* QuestionToken */ ? questionOrExclamationToken : undefined; + node.exclamationToken = questionOrExclamationToken !== undefined && questionOrExclamationToken.kind === 52 /* ExclamationToken */ ? questionOrExclamationToken : undefined; + node.type = type; + node.initializer = initializer; + return node; + } + ts.createProperty = createProperty; + function updateProperty(node, decorators, modifiers, name, questionOrExclamationToken, type, initializer) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.name !== name + || node.questionToken !== (questionOrExclamationToken !== undefined && questionOrExclamationToken.kind === 56 /* QuestionToken */ ? questionOrExclamationToken : undefined) + || node.exclamationToken !== (questionOrExclamationToken !== undefined && questionOrExclamationToken.kind === 52 /* ExclamationToken */ ? questionOrExclamationToken : undefined) + || node.type !== type + || node.initializer !== initializer + ? updateNode(createProperty(decorators, modifiers, name, questionOrExclamationToken, type, initializer), node) + : node; + } + ts.updateProperty = updateProperty; + function createMethodSignature(typeParameters, parameters, type, name, questionToken) { + var node = createSignatureDeclaration(155 /* MethodSignature */, typeParameters, parameters, type); + node.name = asName(name); + node.questionToken = questionToken; + return node; + } + ts.createMethodSignature = createMethodSignature; + function updateMethodSignature(node, typeParameters, parameters, type, name, questionToken) { + return node.typeParameters !== typeParameters + || node.parameters !== parameters + || node.type !== type + || node.name !== name + || node.questionToken !== questionToken + ? updateNode(createMethodSignature(typeParameters, parameters, type, name, questionToken), node) + : node; + } + ts.updateMethodSignature = updateMethodSignature; + function createMethod(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { + var node = createSynthesizedNode(156 /* MethodDeclaration */); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.asteriskToken = asteriskToken; + node.name = asName(name); + node.questionToken = questionToken; + node.typeParameters = asNodeArray(typeParameters); + node.parameters = createNodeArray(parameters); + node.type = type; + node.body = body; + return node; + } + ts.createMethod = createMethod; + function updateMethod(node, decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.asteriskToken !== asteriskToken + || node.name !== name + || node.questionToken !== questionToken + || node.typeParameters !== typeParameters + || node.parameters !== parameters + || node.type !== type + || node.body !== body + ? updateNode(createMethod(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body), node) + : node; + } + ts.updateMethod = updateMethod; + function createConstructor(decorators, modifiers, parameters, body) { + var node = createSynthesizedNode(157 /* Constructor */); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.typeParameters = undefined; + node.parameters = createNodeArray(parameters); + node.type = undefined; + node.body = body; + return node; + } + ts.createConstructor = createConstructor; + function updateConstructor(node, decorators, modifiers, parameters, body) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.parameters !== parameters + || node.body !== body + ? updateNode(createConstructor(decorators, modifiers, parameters, body), node) + : node; + } + ts.updateConstructor = updateConstructor; + function createGetAccessor(decorators, modifiers, name, parameters, type, body) { + var node = createSynthesizedNode(158 /* GetAccessor */); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.name = asName(name); + node.typeParameters = undefined; + node.parameters = createNodeArray(parameters); + node.type = type; + node.body = body; + return node; + } + ts.createGetAccessor = createGetAccessor; + function updateGetAccessor(node, decorators, modifiers, name, parameters, type, body) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.name !== name + || node.parameters !== parameters + || node.type !== type + || node.body !== body + ? updateNode(createGetAccessor(decorators, modifiers, name, parameters, type, body), node) + : node; + } + ts.updateGetAccessor = updateGetAccessor; + function createSetAccessor(decorators, modifiers, name, parameters, body) { + var node = createSynthesizedNode(159 /* SetAccessor */); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.name = asName(name); + node.typeParameters = undefined; + node.parameters = createNodeArray(parameters); + node.body = body; + return node; + } + ts.createSetAccessor = createSetAccessor; + function updateSetAccessor(node, decorators, modifiers, name, parameters, body) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.name !== name + || node.parameters !== parameters + || node.body !== body + ? updateNode(createSetAccessor(decorators, modifiers, name, parameters, body), node) + : node; + } + ts.updateSetAccessor = updateSetAccessor; + function createCallSignature(typeParameters, parameters, type) { + return createSignatureDeclaration(160 /* CallSignature */, typeParameters, parameters, type); + } + ts.createCallSignature = createCallSignature; + function updateCallSignature(node, typeParameters, parameters, type) { + return updateSignatureDeclaration(node, typeParameters, parameters, type); + } + ts.updateCallSignature = updateCallSignature; + function createConstructSignature(typeParameters, parameters, type) { + return createSignatureDeclaration(161 /* ConstructSignature */, typeParameters, parameters, type); + } + ts.createConstructSignature = createConstructSignature; + function updateConstructSignature(node, typeParameters, parameters, type) { + return updateSignatureDeclaration(node, typeParameters, parameters, type); + } + ts.updateConstructSignature = updateConstructSignature; + function createIndexSignature(decorators, modifiers, parameters, type) { + var node = createSynthesizedNode(162 /* IndexSignature */); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.parameters = createNodeArray(parameters); + node.type = type; + return node; + } + ts.createIndexSignature = createIndexSignature; + function updateIndexSignature(node, decorators, modifiers, parameters, type) { + return node.parameters !== parameters + || node.type !== type + || node.decorators !== decorators + || node.modifiers !== modifiers + ? updateNode(createIndexSignature(decorators, modifiers, parameters, type), node) + : node; + } + ts.updateIndexSignature = updateIndexSignature; + /* @internal */ + function createSignatureDeclaration(kind, typeParameters, parameters, type, typeArguments) { + var node = createSynthesizedNode(kind); + node.typeParameters = asNodeArray(typeParameters); + node.parameters = asNodeArray(parameters); + node.type = type; + node.typeArguments = asNodeArray(typeArguments); + return node; + } + ts.createSignatureDeclaration = createSignatureDeclaration; + function updateSignatureDeclaration(node, typeParameters, parameters, type) { + return node.typeParameters !== typeParameters + || node.parameters !== parameters + || node.type !== type + ? updateNode(createSignatureDeclaration(node.kind, typeParameters, parameters, type), node) + : node; + } + // Types + function createKeywordTypeNode(kind) { + return createSynthesizedNode(kind); + } + ts.createKeywordTypeNode = createKeywordTypeNode; + function createTypePredicateNode(parameterName, type) { + var node = createSynthesizedNode(163 /* TypePredicate */); + node.parameterName = asName(parameterName); + node.type = type; + return node; + } + ts.createTypePredicateNode = createTypePredicateNode; + function updateTypePredicateNode(node, parameterName, type) { + return node.parameterName !== parameterName + || node.type !== type + ? updateNode(createTypePredicateNode(parameterName, type), node) + : node; + } + ts.updateTypePredicateNode = updateTypePredicateNode; + function createTypeReferenceNode(typeName, typeArguments) { + var node = createSynthesizedNode(164 /* TypeReference */); + node.typeName = asName(typeName); + node.typeArguments = typeArguments && ts.parenthesizeTypeParameters(typeArguments); + return node; + } + ts.createTypeReferenceNode = createTypeReferenceNode; + function updateTypeReferenceNode(node, typeName, typeArguments) { + return node.typeName !== typeName + || node.typeArguments !== typeArguments + ? updateNode(createTypeReferenceNode(typeName, typeArguments), node) + : node; + } + ts.updateTypeReferenceNode = updateTypeReferenceNode; + function createFunctionTypeNode(typeParameters, parameters, type) { + return createSignatureDeclaration(165 /* FunctionType */, typeParameters, parameters, type); + } + ts.createFunctionTypeNode = createFunctionTypeNode; + function updateFunctionTypeNode(node, typeParameters, parameters, type) { + return updateSignatureDeclaration(node, typeParameters, parameters, type); + } + ts.updateFunctionTypeNode = updateFunctionTypeNode; + function createConstructorTypeNode(typeParameters, parameters, type) { + return createSignatureDeclaration(166 /* ConstructorType */, typeParameters, parameters, type); + } + ts.createConstructorTypeNode = createConstructorTypeNode; + function updateConstructorTypeNode(node, typeParameters, parameters, type) { + return updateSignatureDeclaration(node, typeParameters, parameters, type); + } + ts.updateConstructorTypeNode = updateConstructorTypeNode; + function createTypeQueryNode(exprName) { + var node = createSynthesizedNode(167 /* TypeQuery */); + node.exprName = exprName; + return node; + } + ts.createTypeQueryNode = createTypeQueryNode; + function updateTypeQueryNode(node, exprName) { + return node.exprName !== exprName + ? updateNode(createTypeQueryNode(exprName), node) + : node; + } + ts.updateTypeQueryNode = updateTypeQueryNode; + function createTypeLiteralNode(members) { + var node = createSynthesizedNode(168 /* TypeLiteral */); + node.members = createNodeArray(members); + return node; + } + ts.createTypeLiteralNode = createTypeLiteralNode; + function updateTypeLiteralNode(node, members) { + return node.members !== members + ? updateNode(createTypeLiteralNode(members), node) + : node; + } + ts.updateTypeLiteralNode = updateTypeLiteralNode; + function createArrayTypeNode(elementType) { + var node = createSynthesizedNode(169 /* ArrayType */); + node.elementType = ts.parenthesizeArrayTypeMember(elementType); + return node; + } + ts.createArrayTypeNode = createArrayTypeNode; + function updateArrayTypeNode(node, elementType) { + return node.elementType !== elementType + ? updateNode(createArrayTypeNode(elementType), node) + : node; + } + ts.updateArrayTypeNode = updateArrayTypeNode; + function createTupleTypeNode(elementTypes) { + var node = createSynthesizedNode(170 /* TupleType */); + node.elementTypes = createNodeArray(elementTypes); + return node; + } + ts.createTupleTypeNode = createTupleTypeNode; + function updateTupleTypeNode(node, elementTypes) { + return node.elementTypes !== elementTypes + ? updateNode(createTupleTypeNode(elementTypes), node) + : node; + } + ts.updateTupleTypeNode = updateTupleTypeNode; + function createOptionalTypeNode(type) { + var node = createSynthesizedNode(171 /* OptionalType */); + node.type = ts.parenthesizeArrayTypeMember(type); + return node; + } + ts.createOptionalTypeNode = createOptionalTypeNode; + function updateOptionalTypeNode(node, type) { + return node.type !== type + ? updateNode(createOptionalTypeNode(type), node) + : node; + } + ts.updateOptionalTypeNode = updateOptionalTypeNode; + function createRestTypeNode(type) { + var node = createSynthesizedNode(172 /* RestType */); + node.type = type; + return node; + } + ts.createRestTypeNode = createRestTypeNode; + function updateRestTypeNode(node, type) { + return node.type !== type + ? updateNode(createRestTypeNode(type), node) + : node; + } + ts.updateRestTypeNode = updateRestTypeNode; + function createUnionTypeNode(types) { + return createUnionOrIntersectionTypeNode(173 /* UnionType */, types); + } + ts.createUnionTypeNode = createUnionTypeNode; + function updateUnionTypeNode(node, types) { + return updateUnionOrIntersectionTypeNode(node, types); + } + ts.updateUnionTypeNode = updateUnionTypeNode; + function createIntersectionTypeNode(types) { + return createUnionOrIntersectionTypeNode(174 /* IntersectionType */, types); + } + ts.createIntersectionTypeNode = createIntersectionTypeNode; + function updateIntersectionTypeNode(node, types) { + return updateUnionOrIntersectionTypeNode(node, types); + } + ts.updateIntersectionTypeNode = updateIntersectionTypeNode; + function createUnionOrIntersectionTypeNode(kind, types) { + var node = createSynthesizedNode(kind); + node.types = ts.parenthesizeElementTypeMembers(types); + return node; + } + ts.createUnionOrIntersectionTypeNode = createUnionOrIntersectionTypeNode; + function updateUnionOrIntersectionTypeNode(node, types) { + return node.types !== types + ? updateNode(createUnionOrIntersectionTypeNode(node.kind, types), node) + : node; + } + function createConditionalTypeNode(checkType, extendsType, trueType, falseType) { + var node = createSynthesizedNode(175 /* ConditionalType */); + node.checkType = ts.parenthesizeConditionalTypeMember(checkType); + node.extendsType = ts.parenthesizeConditionalTypeMember(extendsType); + node.trueType = trueType; + node.falseType = falseType; + return node; + } + ts.createConditionalTypeNode = createConditionalTypeNode; + function updateConditionalTypeNode(node, checkType, extendsType, trueType, falseType) { + return node.checkType !== checkType + || node.extendsType !== extendsType + || node.trueType !== trueType + || node.falseType !== falseType + ? updateNode(createConditionalTypeNode(checkType, extendsType, trueType, falseType), node) + : node; + } + ts.updateConditionalTypeNode = updateConditionalTypeNode; + function createInferTypeNode(typeParameter) { + var node = createSynthesizedNode(176 /* InferType */); + node.typeParameter = typeParameter; + return node; + } + ts.createInferTypeNode = createInferTypeNode; + function updateInferTypeNode(node, typeParameter) { + return node.typeParameter !== typeParameter + ? updateNode(createInferTypeNode(typeParameter), node) + : node; + } + ts.updateInferTypeNode = updateInferTypeNode; + function createImportTypeNode(argument, qualifier, typeArguments, isTypeOf) { + var node = createSynthesizedNode(183 /* ImportType */); + node.argument = argument; + node.qualifier = qualifier; + node.typeArguments = asNodeArray(typeArguments); + node.isTypeOf = isTypeOf; + return node; + } + ts.createImportTypeNode = createImportTypeNode; + function updateImportTypeNode(node, argument, qualifier, typeArguments, isTypeOf) { + return node.argument !== argument + || node.qualifier !== qualifier + || node.typeArguments !== typeArguments + || node.isTypeOf !== isTypeOf + ? updateNode(createImportTypeNode(argument, qualifier, typeArguments, isTypeOf), node) + : node; + } + ts.updateImportTypeNode = updateImportTypeNode; + function createParenthesizedType(type) { + var node = createSynthesizedNode(177 /* ParenthesizedType */); + node.type = type; + return node; + } + ts.createParenthesizedType = createParenthesizedType; + function updateParenthesizedType(node, type) { + return node.type !== type + ? updateNode(createParenthesizedType(type), node) + : node; + } + ts.updateParenthesizedType = updateParenthesizedType; + function createThisTypeNode() { + return createSynthesizedNode(178 /* ThisType */); + } + ts.createThisTypeNode = createThisTypeNode; + function createTypeOperatorNode(operatorOrType, type) { + var node = createSynthesizedNode(179 /* TypeOperator */); + node.operator = typeof operatorOrType === "number" ? operatorOrType : 129 /* KeyOfKeyword */; + node.type = ts.parenthesizeElementTypeMember(typeof operatorOrType === "number" ? type : operatorOrType); + return node; + } + ts.createTypeOperatorNode = createTypeOperatorNode; + function updateTypeOperatorNode(node, type) { + return node.type !== type ? updateNode(createTypeOperatorNode(node.operator, type), node) : node; + } + ts.updateTypeOperatorNode = updateTypeOperatorNode; + function createIndexedAccessTypeNode(objectType, indexType) { + var node = createSynthesizedNode(180 /* IndexedAccessType */); + node.objectType = ts.parenthesizeElementTypeMember(objectType); + node.indexType = indexType; + return node; + } + ts.createIndexedAccessTypeNode = createIndexedAccessTypeNode; + function updateIndexedAccessTypeNode(node, objectType, indexType) { + return node.objectType !== objectType + || node.indexType !== indexType + ? updateNode(createIndexedAccessTypeNode(objectType, indexType), node) + : node; + } + ts.updateIndexedAccessTypeNode = updateIndexedAccessTypeNode; + function createMappedTypeNode(readonlyToken, typeParameter, questionToken, type) { + var node = createSynthesizedNode(181 /* MappedType */); + node.readonlyToken = readonlyToken; + node.typeParameter = typeParameter; + node.questionToken = questionToken; + node.type = type; + return node; + } + ts.createMappedTypeNode = createMappedTypeNode; + function updateMappedTypeNode(node, readonlyToken, typeParameter, questionToken, type) { + return node.readonlyToken !== readonlyToken + || node.typeParameter !== typeParameter + || node.questionToken !== questionToken + || node.type !== type + ? updateNode(createMappedTypeNode(readonlyToken, typeParameter, questionToken, type), node) + : node; + } + ts.updateMappedTypeNode = updateMappedTypeNode; + function createLiteralTypeNode(literal) { + var node = createSynthesizedNode(182 /* LiteralType */); + node.literal = literal; + return node; + } + ts.createLiteralTypeNode = createLiteralTypeNode; + function updateLiteralTypeNode(node, literal) { + return node.literal !== literal + ? updateNode(createLiteralTypeNode(literal), node) + : node; + } + ts.updateLiteralTypeNode = updateLiteralTypeNode; + // Binding Patterns + function createObjectBindingPattern(elements) { + var node = createSynthesizedNode(184 /* ObjectBindingPattern */); + node.elements = createNodeArray(elements); + return node; + } + ts.createObjectBindingPattern = createObjectBindingPattern; + function updateObjectBindingPattern(node, elements) { + return node.elements !== elements + ? updateNode(createObjectBindingPattern(elements), node) + : node; + } + ts.updateObjectBindingPattern = updateObjectBindingPattern; + function createArrayBindingPattern(elements) { + var node = createSynthesizedNode(185 /* ArrayBindingPattern */); + node.elements = createNodeArray(elements); + return node; + } + ts.createArrayBindingPattern = createArrayBindingPattern; + function updateArrayBindingPattern(node, elements) { + return node.elements !== elements + ? updateNode(createArrayBindingPattern(elements), node) + : node; + } + ts.updateArrayBindingPattern = updateArrayBindingPattern; + function createBindingElement(dotDotDotToken, propertyName, name, initializer) { + var node = createSynthesizedNode(186 /* BindingElement */); + node.dotDotDotToken = dotDotDotToken; + node.propertyName = asName(propertyName); + node.name = asName(name); + node.initializer = initializer; + return node; + } + ts.createBindingElement = createBindingElement; + function updateBindingElement(node, dotDotDotToken, propertyName, name, initializer) { + return node.propertyName !== propertyName + || node.dotDotDotToken !== dotDotDotToken + || node.name !== name + || node.initializer !== initializer + ? updateNode(createBindingElement(dotDotDotToken, propertyName, name, initializer), node) + : node; + } + ts.updateBindingElement = updateBindingElement; + // Expression + function createArrayLiteral(elements, multiLine) { + var node = createSynthesizedNode(187 /* ArrayLiteralExpression */); + node.elements = ts.parenthesizeListElements(createNodeArray(elements)); + if (multiLine) + node.multiLine = true; + return node; + } + ts.createArrayLiteral = createArrayLiteral; + function updateArrayLiteral(node, elements) { + return node.elements !== elements + ? updateNode(createArrayLiteral(elements, node.multiLine), node) + : node; + } + ts.updateArrayLiteral = updateArrayLiteral; + function createObjectLiteral(properties, multiLine) { + var node = createSynthesizedNode(188 /* ObjectLiteralExpression */); + node.properties = createNodeArray(properties); + if (multiLine) + node.multiLine = true; + return node; + } + ts.createObjectLiteral = createObjectLiteral; + function updateObjectLiteral(node, properties) { + return node.properties !== properties + ? updateNode(createObjectLiteral(properties, node.multiLine), node) + : node; + } + ts.updateObjectLiteral = updateObjectLiteral; + function createPropertyAccess(expression, name) { + var node = createSynthesizedNode(189 /* PropertyAccessExpression */); + node.expression = ts.parenthesizeForAccess(expression); + node.name = asName(name); // TODO: GH#18217 + setEmitFlags(node, 131072 /* NoIndentation */); + return node; + } + ts.createPropertyAccess = createPropertyAccess; + function updatePropertyAccess(node, expression, name) { + // Because we are updating existed propertyAccess we want to inherit its emitFlags + // instead of using the default from createPropertyAccess + return node.expression !== expression + || node.name !== name + ? updateNode(setEmitFlags(createPropertyAccess(expression, name), ts.getEmitFlags(node)), node) + : node; + } + ts.updatePropertyAccess = updatePropertyAccess; + function createElementAccess(expression, index) { + var node = createSynthesizedNode(190 /* ElementAccessExpression */); + node.expression = ts.parenthesizeForAccess(expression); + node.argumentExpression = asExpression(index); + return node; + } + ts.createElementAccess = createElementAccess; + function updateElementAccess(node, expression, argumentExpression) { + return node.expression !== expression + || node.argumentExpression !== argumentExpression + ? updateNode(createElementAccess(expression, argumentExpression), node) + : node; + } + ts.updateElementAccess = updateElementAccess; + function createCall(expression, typeArguments, argumentsArray) { + var node = createSynthesizedNode(191 /* CallExpression */); + node.expression = ts.parenthesizeForAccess(expression); + node.typeArguments = asNodeArray(typeArguments); + node.arguments = ts.parenthesizeListElements(createNodeArray(argumentsArray)); + return node; + } + ts.createCall = createCall; + function updateCall(node, expression, typeArguments, argumentsArray) { + return node.expression !== expression + || node.typeArguments !== typeArguments + || node.arguments !== argumentsArray + ? updateNode(createCall(expression, typeArguments, argumentsArray), node) + : node; + } + ts.updateCall = updateCall; + function createNew(expression, typeArguments, argumentsArray) { + var node = createSynthesizedNode(192 /* NewExpression */); + node.expression = ts.parenthesizeForNew(expression); + node.typeArguments = asNodeArray(typeArguments); + node.arguments = argumentsArray ? ts.parenthesizeListElements(createNodeArray(argumentsArray)) : undefined; + return node; + } + ts.createNew = createNew; + function updateNew(node, expression, typeArguments, argumentsArray) { + return node.expression !== expression + || node.typeArguments !== typeArguments + || node.arguments !== argumentsArray + ? updateNode(createNew(expression, typeArguments, argumentsArray), node) + : node; + } + ts.updateNew = updateNew; + function createTaggedTemplate(tag, typeArgumentsOrTemplate, template) { + var node = createSynthesizedNode(193 /* TaggedTemplateExpression */); + node.tag = ts.parenthesizeForAccess(tag); + if (template) { + node.typeArguments = asNodeArray(typeArgumentsOrTemplate); + node.template = template; + } + else { + node.typeArguments = undefined; + node.template = typeArgumentsOrTemplate; + } + return node; + } + ts.createTaggedTemplate = createTaggedTemplate; + function updateTaggedTemplate(node, tag, typeArgumentsOrTemplate, template) { + return node.tag !== tag + || (template + ? node.typeArguments !== typeArgumentsOrTemplate || node.template !== template + : node.typeArguments !== undefined || node.template !== typeArgumentsOrTemplate) + ? updateNode(createTaggedTemplate(tag, typeArgumentsOrTemplate, template), node) + : node; + } + ts.updateTaggedTemplate = updateTaggedTemplate; + function createTypeAssertion(type, expression) { + var node = createSynthesizedNode(194 /* TypeAssertionExpression */); + node.type = type; + node.expression = ts.parenthesizePrefixOperand(expression); + return node; + } + ts.createTypeAssertion = createTypeAssertion; + function updateTypeAssertion(node, type, expression) { + return node.type !== type + || node.expression !== expression + ? updateNode(createTypeAssertion(type, expression), node) + : node; + } + ts.updateTypeAssertion = updateTypeAssertion; + function createParen(expression) { + var node = createSynthesizedNode(195 /* ParenthesizedExpression */); + node.expression = expression; + return node; + } + ts.createParen = createParen; + function updateParen(node, expression) { + return node.expression !== expression + ? updateNode(createParen(expression), node) + : node; + } + ts.updateParen = updateParen; + function createFunctionExpression(modifiers, asteriskToken, name, typeParameters, parameters, type, body) { + var node = createSynthesizedNode(196 /* FunctionExpression */); + node.modifiers = asNodeArray(modifiers); + node.asteriskToken = asteriskToken; + node.name = asName(name); + node.typeParameters = asNodeArray(typeParameters); + node.parameters = createNodeArray(parameters); + node.type = type; + node.body = body; + return node; + } + ts.createFunctionExpression = createFunctionExpression; + function updateFunctionExpression(node, modifiers, asteriskToken, name, typeParameters, parameters, type, body) { + return node.name !== name + || node.modifiers !== modifiers + || node.asteriskToken !== asteriskToken + || node.typeParameters !== typeParameters + || node.parameters !== parameters + || node.type !== type + || node.body !== body + ? updateNode(createFunctionExpression(modifiers, asteriskToken, name, typeParameters, parameters, type, body), node) + : node; + } + ts.updateFunctionExpression = updateFunctionExpression; + function createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body) { + var node = createSynthesizedNode(197 /* ArrowFunction */); + node.modifiers = asNodeArray(modifiers); + node.typeParameters = asNodeArray(typeParameters); + node.parameters = createNodeArray(parameters); + node.type = type; + node.equalsGreaterThanToken = equalsGreaterThanToken || createToken(37 /* EqualsGreaterThanToken */); + node.body = ts.parenthesizeConciseBody(body); + return node; + } + ts.createArrowFunction = createArrowFunction; + function updateArrowFunction(node, modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body) { + return node.modifiers !== modifiers + || node.typeParameters !== typeParameters + || node.parameters !== parameters + || node.type !== type + || node.equalsGreaterThanToken !== equalsGreaterThanToken + || node.body !== body + ? updateNode(createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body), node) + : node; + } + ts.updateArrowFunction = updateArrowFunction; + function createDelete(expression) { + var node = createSynthesizedNode(198 /* DeleteExpression */); + node.expression = ts.parenthesizePrefixOperand(expression); + return node; + } + ts.createDelete = createDelete; + function updateDelete(node, expression) { + return node.expression !== expression + ? updateNode(createDelete(expression), node) + : node; + } + ts.updateDelete = updateDelete; + function createTypeOf(expression) { + var node = createSynthesizedNode(199 /* TypeOfExpression */); + node.expression = ts.parenthesizePrefixOperand(expression); + return node; + } + ts.createTypeOf = createTypeOf; + function updateTypeOf(node, expression) { + return node.expression !== expression + ? updateNode(createTypeOf(expression), node) + : node; + } + ts.updateTypeOf = updateTypeOf; + function createVoid(expression) { + var node = createSynthesizedNode(200 /* VoidExpression */); + node.expression = ts.parenthesizePrefixOperand(expression); + return node; + } + ts.createVoid = createVoid; + function updateVoid(node, expression) { + return node.expression !== expression + ? updateNode(createVoid(expression), node) + : node; + } + ts.updateVoid = updateVoid; + function createAwait(expression) { + var node = createSynthesizedNode(201 /* AwaitExpression */); + node.expression = ts.parenthesizePrefixOperand(expression); + return node; + } + ts.createAwait = createAwait; + function updateAwait(node, expression) { + return node.expression !== expression + ? updateNode(createAwait(expression), node) + : node; + } + ts.updateAwait = updateAwait; + function createPrefix(operator, operand) { + var node = createSynthesizedNode(202 /* PrefixUnaryExpression */); + node.operator = operator; + node.operand = ts.parenthesizePrefixOperand(operand); + return node; + } + ts.createPrefix = createPrefix; + function updatePrefix(node, operand) { + return node.operand !== operand + ? updateNode(createPrefix(node.operator, operand), node) + : node; + } + ts.updatePrefix = updatePrefix; + function createPostfix(operand, operator) { + var node = createSynthesizedNode(203 /* PostfixUnaryExpression */); + node.operand = ts.parenthesizePostfixOperand(operand); + node.operator = operator; + return node; + } + ts.createPostfix = createPostfix; + function updatePostfix(node, operand) { + return node.operand !== operand + ? updateNode(createPostfix(operand, node.operator), node) + : node; + } + ts.updatePostfix = updatePostfix; + function createBinary(left, operator, right) { + var node = createSynthesizedNode(204 /* BinaryExpression */); + var operatorToken = asToken(operator); + var operatorKind = operatorToken.kind; + node.left = ts.parenthesizeBinaryOperand(operatorKind, left, /*isLeftSideOfBinary*/ true, /*leftOperand*/ undefined); + node.operatorToken = operatorToken; + node.right = ts.parenthesizeBinaryOperand(operatorKind, right, /*isLeftSideOfBinary*/ false, node.left); + return node; + } + ts.createBinary = createBinary; + function updateBinary(node, left, right, operator) { + return node.left !== left + || node.right !== right + ? updateNode(createBinary(left, operator || node.operatorToken, right), node) + : node; + } + ts.updateBinary = updateBinary; + function createConditional(condition, questionTokenOrWhenTrue, whenTrueOrWhenFalse, colonToken, whenFalse) { + var node = createSynthesizedNode(205 /* ConditionalExpression */); + node.condition = ts.parenthesizeForConditionalHead(condition); + node.questionToken = whenFalse ? questionTokenOrWhenTrue : createToken(56 /* QuestionToken */); + node.whenTrue = ts.parenthesizeSubexpressionOfConditionalExpression(whenFalse ? whenTrueOrWhenFalse : questionTokenOrWhenTrue); + node.colonToken = whenFalse ? colonToken : createToken(57 /* ColonToken */); + node.whenFalse = ts.parenthesizeSubexpressionOfConditionalExpression(whenFalse ? whenFalse : whenTrueOrWhenFalse); + return node; + } + ts.createConditional = createConditional; + function updateConditional(node, condition, questionToken, whenTrue, colonToken, whenFalse) { + return node.condition !== condition + || node.questionToken !== questionToken + || node.whenTrue !== whenTrue + || node.colonToken !== colonToken + || node.whenFalse !== whenFalse + ? updateNode(createConditional(condition, questionToken, whenTrue, colonToken, whenFalse), node) + : node; + } + ts.updateConditional = updateConditional; + function createTemplateExpression(head, templateSpans) { + var node = createSynthesizedNode(206 /* TemplateExpression */); + node.head = head; + node.templateSpans = createNodeArray(templateSpans); + return node; + } + ts.createTemplateExpression = createTemplateExpression; + function updateTemplateExpression(node, head, templateSpans) { + return node.head !== head + || node.templateSpans !== templateSpans + ? updateNode(createTemplateExpression(head, templateSpans), node) + : node; + } + ts.updateTemplateExpression = updateTemplateExpression; + function createTemplateHead(text) { + var node = createSynthesizedNode(15 /* TemplateHead */); + node.text = text; + return node; + } + ts.createTemplateHead = createTemplateHead; + function createTemplateMiddle(text) { + var node = createSynthesizedNode(16 /* TemplateMiddle */); + node.text = text; + return node; + } + ts.createTemplateMiddle = createTemplateMiddle; + function createTemplateTail(text) { + var node = createSynthesizedNode(17 /* TemplateTail */); + node.text = text; + return node; + } + ts.createTemplateTail = createTemplateTail; + function createNoSubstitutionTemplateLiteral(text) { + var node = createSynthesizedNode(14 /* NoSubstitutionTemplateLiteral */); + node.text = text; + return node; + } + ts.createNoSubstitutionTemplateLiteral = createNoSubstitutionTemplateLiteral; + function createYield(asteriskTokenOrExpression, expression) { + var node = createSynthesizedNode(207 /* YieldExpression */); + node.asteriskToken = asteriskTokenOrExpression && asteriskTokenOrExpression.kind === 40 /* AsteriskToken */ ? asteriskTokenOrExpression : undefined; + node.expression = asteriskTokenOrExpression && asteriskTokenOrExpression.kind !== 40 /* AsteriskToken */ ? asteriskTokenOrExpression : expression; + return node; + } + ts.createYield = createYield; + function updateYield(node, asteriskToken, expression) { + return node.expression !== expression + || node.asteriskToken !== asteriskToken + ? updateNode(createYield(asteriskToken, expression), node) + : node; + } + ts.updateYield = updateYield; + function createSpread(expression) { + var node = createSynthesizedNode(208 /* SpreadElement */); + node.expression = ts.parenthesizeExpressionForList(expression); + return node; + } + ts.createSpread = createSpread; + function updateSpread(node, expression) { + return node.expression !== expression + ? updateNode(createSpread(expression), node) + : node; + } + ts.updateSpread = updateSpread; + function createClassExpression(modifiers, name, typeParameters, heritageClauses, members) { + var node = createSynthesizedNode(209 /* ClassExpression */); + node.decorators = undefined; + node.modifiers = asNodeArray(modifiers); + node.name = asName(name); + node.typeParameters = asNodeArray(typeParameters); + node.heritageClauses = asNodeArray(heritageClauses); + node.members = createNodeArray(members); + return node; + } + ts.createClassExpression = createClassExpression; + function updateClassExpression(node, modifiers, name, typeParameters, heritageClauses, members) { + return node.modifiers !== modifiers + || node.name !== name + || node.typeParameters !== typeParameters + || node.heritageClauses !== heritageClauses + || node.members !== members + ? updateNode(createClassExpression(modifiers, name, typeParameters, heritageClauses, members), node) + : node; + } + ts.updateClassExpression = updateClassExpression; + function createOmittedExpression() { + return createSynthesizedNode(210 /* OmittedExpression */); + } + ts.createOmittedExpression = createOmittedExpression; + function createExpressionWithTypeArguments(typeArguments, expression) { + var node = createSynthesizedNode(211 /* ExpressionWithTypeArguments */); + node.expression = ts.parenthesizeForAccess(expression); + node.typeArguments = asNodeArray(typeArguments); + return node; + } + ts.createExpressionWithTypeArguments = createExpressionWithTypeArguments; + function updateExpressionWithTypeArguments(node, typeArguments, expression) { + return node.typeArguments !== typeArguments + || node.expression !== expression + ? updateNode(createExpressionWithTypeArguments(typeArguments, expression), node) + : node; + } + ts.updateExpressionWithTypeArguments = updateExpressionWithTypeArguments; + function createAsExpression(expression, type) { + var node = createSynthesizedNode(212 /* AsExpression */); + node.expression = expression; + node.type = type; + return node; + } + ts.createAsExpression = createAsExpression; + function updateAsExpression(node, expression, type) { + return node.expression !== expression + || node.type !== type + ? updateNode(createAsExpression(expression, type), node) + : node; + } + ts.updateAsExpression = updateAsExpression; + function createNonNullExpression(expression) { + var node = createSynthesizedNode(213 /* NonNullExpression */); + node.expression = ts.parenthesizeForAccess(expression); + return node; + } + ts.createNonNullExpression = createNonNullExpression; + function updateNonNullExpression(node, expression) { + return node.expression !== expression + ? updateNode(createNonNullExpression(expression), node) + : node; + } + ts.updateNonNullExpression = updateNonNullExpression; + function createMetaProperty(keywordToken, name) { + var node = createSynthesizedNode(214 /* MetaProperty */); + node.keywordToken = keywordToken; + node.name = name; + return node; + } + ts.createMetaProperty = createMetaProperty; + function updateMetaProperty(node, name) { + return node.name !== name + ? updateNode(createMetaProperty(node.keywordToken, name), node) + : node; + } + ts.updateMetaProperty = updateMetaProperty; + // Misc + function createTemplateSpan(expression, literal) { + var node = createSynthesizedNode(216 /* TemplateSpan */); + node.expression = expression; + node.literal = literal; + return node; + } + ts.createTemplateSpan = createTemplateSpan; + function updateTemplateSpan(node, expression, literal) { + return node.expression !== expression + || node.literal !== literal + ? updateNode(createTemplateSpan(expression, literal), node) + : node; + } + ts.updateTemplateSpan = updateTemplateSpan; + function createSemicolonClassElement() { + return createSynthesizedNode(217 /* SemicolonClassElement */); + } + ts.createSemicolonClassElement = createSemicolonClassElement; + // Element + function createBlock(statements, multiLine) { + var block = createSynthesizedNode(218 /* Block */); + block.statements = createNodeArray(statements); + if (multiLine) + block.multiLine = multiLine; + return block; + } + ts.createBlock = createBlock; + function updateBlock(node, statements) { + return node.statements !== statements + ? updateNode(createBlock(statements, node.multiLine), node) + : node; + } + ts.updateBlock = updateBlock; + function createVariableStatement(modifiers, declarationList) { + var node = createSynthesizedNode(219 /* VariableStatement */); + node.decorators = undefined; + node.modifiers = asNodeArray(modifiers); + node.declarationList = ts.isArray(declarationList) ? createVariableDeclarationList(declarationList) : declarationList; + return node; + } + ts.createVariableStatement = createVariableStatement; + function updateVariableStatement(node, modifiers, declarationList) { + return node.modifiers !== modifiers + || node.declarationList !== declarationList + ? updateNode(createVariableStatement(modifiers, declarationList), node) + : node; + } + ts.updateVariableStatement = updateVariableStatement; + function createEmptyStatement() { + return createSynthesizedNode(220 /* EmptyStatement */); + } + ts.createEmptyStatement = createEmptyStatement; + function createExpressionStatement(expression) { + var node = createSynthesizedNode(221 /* ExpressionStatement */); + node.expression = ts.parenthesizeExpressionForExpressionStatement(expression); + return node; + } + ts.createExpressionStatement = createExpressionStatement; + function updateExpressionStatement(node, expression) { + return node.expression !== expression + ? updateNode(createExpressionStatement(expression), node) + : node; + } + ts.updateExpressionStatement = updateExpressionStatement; + /** @deprecated Use `createExpressionStatement` instead. */ + ts.createStatement = createExpressionStatement; + /** @deprecated Use `updateExpressionStatement` instead. */ + ts.updateStatement = updateExpressionStatement; + function createIf(expression, thenStatement, elseStatement) { + var node = createSynthesizedNode(222 /* IfStatement */); + node.expression = expression; + node.thenStatement = thenStatement; + node.elseStatement = elseStatement; + return node; + } + ts.createIf = createIf; + function updateIf(node, expression, thenStatement, elseStatement) { + return node.expression !== expression + || node.thenStatement !== thenStatement + || node.elseStatement !== elseStatement + ? updateNode(createIf(expression, thenStatement, elseStatement), node) + : node; + } + ts.updateIf = updateIf; + function createDo(statement, expression) { + var node = createSynthesizedNode(223 /* DoStatement */); + node.statement = statement; + node.expression = expression; + return node; + } + ts.createDo = createDo; + function updateDo(node, statement, expression) { + return node.statement !== statement + || node.expression !== expression + ? updateNode(createDo(statement, expression), node) + : node; + } + ts.updateDo = updateDo; + function createWhile(expression, statement) { + var node = createSynthesizedNode(224 /* WhileStatement */); + node.expression = expression; + node.statement = statement; + return node; + } + ts.createWhile = createWhile; + function updateWhile(node, expression, statement) { + return node.expression !== expression + || node.statement !== statement + ? updateNode(createWhile(expression, statement), node) + : node; + } + ts.updateWhile = updateWhile; + function createFor(initializer, condition, incrementor, statement) { + var node = createSynthesizedNode(225 /* ForStatement */); + node.initializer = initializer; + node.condition = condition; + node.incrementor = incrementor; + node.statement = statement; + return node; + } + ts.createFor = createFor; + function updateFor(node, initializer, condition, incrementor, statement) { + return node.initializer !== initializer + || node.condition !== condition + || node.incrementor !== incrementor + || node.statement !== statement + ? updateNode(createFor(initializer, condition, incrementor, statement), node) + : node; + } + ts.updateFor = updateFor; + function createForIn(initializer, expression, statement) { + var node = createSynthesizedNode(226 /* ForInStatement */); + node.initializer = initializer; + node.expression = expression; + node.statement = statement; + return node; + } + ts.createForIn = createForIn; + function updateForIn(node, initializer, expression, statement) { + return node.initializer !== initializer + || node.expression !== expression + || node.statement !== statement + ? updateNode(createForIn(initializer, expression, statement), node) + : node; + } + ts.updateForIn = updateForIn; + function createForOf(awaitModifier, initializer, expression, statement) { + var node = createSynthesizedNode(227 /* ForOfStatement */); + node.awaitModifier = awaitModifier; + node.initializer = initializer; + node.expression = expression; + node.statement = statement; + return node; + } + ts.createForOf = createForOf; + function updateForOf(node, awaitModifier, initializer, expression, statement) { + return node.awaitModifier !== awaitModifier + || node.initializer !== initializer + || node.expression !== expression + || node.statement !== statement + ? updateNode(createForOf(awaitModifier, initializer, expression, statement), node) + : node; + } + ts.updateForOf = updateForOf; + function createContinue(label) { + var node = createSynthesizedNode(228 /* ContinueStatement */); + node.label = asName(label); + return node; + } + ts.createContinue = createContinue; + function updateContinue(node, label) { + return node.label !== label + ? updateNode(createContinue(label), node) + : node; + } + ts.updateContinue = updateContinue; + function createBreak(label) { + var node = createSynthesizedNode(229 /* BreakStatement */); + node.label = asName(label); + return node; + } + ts.createBreak = createBreak; + function updateBreak(node, label) { + return node.label !== label + ? updateNode(createBreak(label), node) + : node; + } + ts.updateBreak = updateBreak; + function createReturn(expression) { + var node = createSynthesizedNode(230 /* ReturnStatement */); + node.expression = expression; + return node; + } + ts.createReturn = createReturn; + function updateReturn(node, expression) { + return node.expression !== expression + ? updateNode(createReturn(expression), node) + : node; + } + ts.updateReturn = updateReturn; + function createWith(expression, statement) { + var node = createSynthesizedNode(231 /* WithStatement */); + node.expression = expression; + node.statement = statement; + return node; + } + ts.createWith = createWith; + function updateWith(node, expression, statement) { + return node.expression !== expression + || node.statement !== statement + ? updateNode(createWith(expression, statement), node) + : node; + } + ts.updateWith = updateWith; + function createSwitch(expression, caseBlock) { + var node = createSynthesizedNode(232 /* SwitchStatement */); + node.expression = ts.parenthesizeExpressionForList(expression); + node.caseBlock = caseBlock; + return node; + } + ts.createSwitch = createSwitch; + function updateSwitch(node, expression, caseBlock) { + return node.expression !== expression + || node.caseBlock !== caseBlock + ? updateNode(createSwitch(expression, caseBlock), node) + : node; + } + ts.updateSwitch = updateSwitch; + function createLabel(label, statement) { + var node = createSynthesizedNode(233 /* LabeledStatement */); + node.label = asName(label); + node.statement = statement; + return node; + } + ts.createLabel = createLabel; + function updateLabel(node, label, statement) { + return node.label !== label + || node.statement !== statement + ? updateNode(createLabel(label, statement), node) + : node; + } + ts.updateLabel = updateLabel; + function createThrow(expression) { + var node = createSynthesizedNode(234 /* ThrowStatement */); + node.expression = expression; + return node; + } + ts.createThrow = createThrow; + function updateThrow(node, expression) { + return node.expression !== expression + ? updateNode(createThrow(expression), node) + : node; + } + ts.updateThrow = updateThrow; + function createTry(tryBlock, catchClause, finallyBlock) { + var node = createSynthesizedNode(235 /* TryStatement */); + node.tryBlock = tryBlock; + node.catchClause = catchClause; + node.finallyBlock = finallyBlock; + return node; + } + ts.createTry = createTry; + function updateTry(node, tryBlock, catchClause, finallyBlock) { + return node.tryBlock !== tryBlock + || node.catchClause !== catchClause + || node.finallyBlock !== finallyBlock + ? updateNode(createTry(tryBlock, catchClause, finallyBlock), node) + : node; + } + ts.updateTry = updateTry; + function createDebuggerStatement() { + return createSynthesizedNode(236 /* DebuggerStatement */); + } + ts.createDebuggerStatement = createDebuggerStatement; + function createVariableDeclaration(name, type, initializer) { + var node = createSynthesizedNode(237 /* VariableDeclaration */); + node.name = asName(name); + node.type = type; + node.initializer = initializer !== undefined ? ts.parenthesizeExpressionForList(initializer) : undefined; + return node; + } + ts.createVariableDeclaration = createVariableDeclaration; + function updateVariableDeclaration(node, name, type, initializer) { + return node.name !== name + || node.type !== type + || node.initializer !== initializer + ? updateNode(createVariableDeclaration(name, type, initializer), node) + : node; + } + ts.updateVariableDeclaration = updateVariableDeclaration; + function createVariableDeclarationList(declarations, flags) { + if (flags === void 0) { flags = 0 /* None */; } + var node = createSynthesizedNode(238 /* VariableDeclarationList */); + node.flags |= flags & 3 /* BlockScoped */; + node.declarations = createNodeArray(declarations); + return node; + } + ts.createVariableDeclarationList = createVariableDeclarationList; + function updateVariableDeclarationList(node, declarations) { + return node.declarations !== declarations + ? updateNode(createVariableDeclarationList(declarations, node.flags), node) + : node; + } + ts.updateVariableDeclarationList = updateVariableDeclarationList; + function createFunctionDeclaration(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body) { + var node = createSynthesizedNode(239 /* FunctionDeclaration */); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.asteriskToken = asteriskToken; + node.name = asName(name); + node.typeParameters = asNodeArray(typeParameters); + node.parameters = createNodeArray(parameters); + node.type = type; + node.body = body; + return node; + } + ts.createFunctionDeclaration = createFunctionDeclaration; + function updateFunctionDeclaration(node, decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.asteriskToken !== asteriskToken + || node.name !== name + || node.typeParameters !== typeParameters + || node.parameters !== parameters + || node.type !== type + || node.body !== body + ? updateNode(createFunctionDeclaration(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body), node) + : node; + } + ts.updateFunctionDeclaration = updateFunctionDeclaration; + function createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) { + var node = createSynthesizedNode(240 /* ClassDeclaration */); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.name = asName(name); + node.typeParameters = asNodeArray(typeParameters); + node.heritageClauses = asNodeArray(heritageClauses); + node.members = createNodeArray(members); + return node; + } + ts.createClassDeclaration = createClassDeclaration; + function updateClassDeclaration(node, decorators, modifiers, name, typeParameters, heritageClauses, members) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.name !== name + || node.typeParameters !== typeParameters + || node.heritageClauses !== heritageClauses + || node.members !== members + ? updateNode(createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members), node) + : node; + } + ts.updateClassDeclaration = updateClassDeclaration; + function createInterfaceDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) { + var node = createSynthesizedNode(241 /* InterfaceDeclaration */); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.name = asName(name); + node.typeParameters = asNodeArray(typeParameters); + node.heritageClauses = asNodeArray(heritageClauses); + node.members = createNodeArray(members); + return node; + } + ts.createInterfaceDeclaration = createInterfaceDeclaration; + function updateInterfaceDeclaration(node, decorators, modifiers, name, typeParameters, heritageClauses, members) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.name !== name + || node.typeParameters !== typeParameters + || node.heritageClauses !== heritageClauses + || node.members !== members + ? updateNode(createInterfaceDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members), node) + : node; + } + ts.updateInterfaceDeclaration = updateInterfaceDeclaration; + function createTypeAliasDeclaration(decorators, modifiers, name, typeParameters, type) { + var node = createSynthesizedNode(242 /* TypeAliasDeclaration */); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.name = asName(name); + node.typeParameters = asNodeArray(typeParameters); + node.type = type; + return node; + } + ts.createTypeAliasDeclaration = createTypeAliasDeclaration; + function updateTypeAliasDeclaration(node, decorators, modifiers, name, typeParameters, type) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.name !== name + || node.typeParameters !== typeParameters + || node.type !== type + ? updateNode(createTypeAliasDeclaration(decorators, modifiers, name, typeParameters, type), node) + : node; + } + ts.updateTypeAliasDeclaration = updateTypeAliasDeclaration; + function createEnumDeclaration(decorators, modifiers, name, members) { + var node = createSynthesizedNode(243 /* EnumDeclaration */); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.name = asName(name); + node.members = createNodeArray(members); + return node; + } + ts.createEnumDeclaration = createEnumDeclaration; + function updateEnumDeclaration(node, decorators, modifiers, name, members) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.name !== name + || node.members !== members + ? updateNode(createEnumDeclaration(decorators, modifiers, name, members), node) + : node; + } + ts.updateEnumDeclaration = updateEnumDeclaration; + function createModuleDeclaration(decorators, modifiers, name, body, flags) { + if (flags === void 0) { flags = 0 /* None */; } + var node = createSynthesizedNode(244 /* ModuleDeclaration */); + node.flags |= flags & (16 /* Namespace */ | 4 /* NestedNamespace */ | 512 /* GlobalAugmentation */); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.name = name; + node.body = body; + return node; + } + ts.createModuleDeclaration = createModuleDeclaration; + function updateModuleDeclaration(node, decorators, modifiers, name, body) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.name !== name + || node.body !== body + ? updateNode(createModuleDeclaration(decorators, modifiers, name, body, node.flags), node) + : node; + } + ts.updateModuleDeclaration = updateModuleDeclaration; + function createModuleBlock(statements) { + var node = createSynthesizedNode(245 /* ModuleBlock */); + node.statements = createNodeArray(statements); + return node; + } + ts.createModuleBlock = createModuleBlock; + function updateModuleBlock(node, statements) { + return node.statements !== statements + ? updateNode(createModuleBlock(statements), node) + : node; + } + ts.updateModuleBlock = updateModuleBlock; + function createCaseBlock(clauses) { + var node = createSynthesizedNode(246 /* CaseBlock */); + node.clauses = createNodeArray(clauses); + return node; + } + ts.createCaseBlock = createCaseBlock; + function updateCaseBlock(node, clauses) { + return node.clauses !== clauses + ? updateNode(createCaseBlock(clauses), node) + : node; + } + ts.updateCaseBlock = updateCaseBlock; + function createNamespaceExportDeclaration(name) { + var node = createSynthesizedNode(247 /* NamespaceExportDeclaration */); + node.name = asName(name); + return node; + } + ts.createNamespaceExportDeclaration = createNamespaceExportDeclaration; + function updateNamespaceExportDeclaration(node, name) { + return node.name !== name + ? updateNode(createNamespaceExportDeclaration(name), node) + : node; + } + ts.updateNamespaceExportDeclaration = updateNamespaceExportDeclaration; + function createImportEqualsDeclaration(decorators, modifiers, name, moduleReference) { + var node = createSynthesizedNode(248 /* ImportEqualsDeclaration */); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.name = asName(name); + node.moduleReference = moduleReference; + return node; + } + ts.createImportEqualsDeclaration = createImportEqualsDeclaration; + function updateImportEqualsDeclaration(node, decorators, modifiers, name, moduleReference) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.name !== name + || node.moduleReference !== moduleReference + ? updateNode(createImportEqualsDeclaration(decorators, modifiers, name, moduleReference), node) + : node; + } + ts.updateImportEqualsDeclaration = updateImportEqualsDeclaration; + function createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier) { + var node = createSynthesizedNode(249 /* ImportDeclaration */); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.importClause = importClause; + node.moduleSpecifier = moduleSpecifier; + return node; + } + ts.createImportDeclaration = createImportDeclaration; + function updateImportDeclaration(node, decorators, modifiers, importClause, moduleSpecifier) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.importClause !== importClause + || node.moduleSpecifier !== moduleSpecifier + ? updateNode(createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier), node) + : node; + } + ts.updateImportDeclaration = updateImportDeclaration; + function createImportClause(name, namedBindings) { + var node = createSynthesizedNode(250 /* ImportClause */); + node.name = name; + node.namedBindings = namedBindings; + return node; + } + ts.createImportClause = createImportClause; + function updateImportClause(node, name, namedBindings) { + return node.name !== name + || node.namedBindings !== namedBindings + ? updateNode(createImportClause(name, namedBindings), node) + : node; + } + ts.updateImportClause = updateImportClause; + function createNamespaceImport(name) { + var node = createSynthesizedNode(251 /* NamespaceImport */); + node.name = name; + return node; + } + ts.createNamespaceImport = createNamespaceImport; + function updateNamespaceImport(node, name) { + return node.name !== name + ? updateNode(createNamespaceImport(name), node) + : node; + } + ts.updateNamespaceImport = updateNamespaceImport; + function createNamedImports(elements) { + var node = createSynthesizedNode(252 /* NamedImports */); + node.elements = createNodeArray(elements); + return node; + } + ts.createNamedImports = createNamedImports; + function updateNamedImports(node, elements) { + return node.elements !== elements + ? updateNode(createNamedImports(elements), node) + : node; + } + ts.updateNamedImports = updateNamedImports; + function createImportSpecifier(propertyName, name) { + var node = createSynthesizedNode(253 /* ImportSpecifier */); + node.propertyName = propertyName; + node.name = name; + return node; + } + ts.createImportSpecifier = createImportSpecifier; + function updateImportSpecifier(node, propertyName, name) { + return node.propertyName !== propertyName + || node.name !== name + ? updateNode(createImportSpecifier(propertyName, name), node) + : node; + } + ts.updateImportSpecifier = updateImportSpecifier; + function createExportAssignment(decorators, modifiers, isExportEquals, expression) { + var node = createSynthesizedNode(254 /* ExportAssignment */); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.isExportEquals = isExportEquals; + node.expression = isExportEquals ? ts.parenthesizeBinaryOperand(59 /* EqualsToken */, expression, /*isLeftSideOfBinary*/ false, /*leftOperand*/ undefined) : ts.parenthesizeDefaultExpression(expression); + return node; + } + ts.createExportAssignment = createExportAssignment; + function updateExportAssignment(node, decorators, modifiers, expression) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.expression !== expression + ? updateNode(createExportAssignment(decorators, modifiers, node.isExportEquals, expression), node) + : node; + } + ts.updateExportAssignment = updateExportAssignment; + function createExportDeclaration(decorators, modifiers, exportClause, moduleSpecifier) { + var node = createSynthesizedNode(255 /* ExportDeclaration */); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.exportClause = exportClause; + node.moduleSpecifier = moduleSpecifier; + return node; + } + ts.createExportDeclaration = createExportDeclaration; + function updateExportDeclaration(node, decorators, modifiers, exportClause, moduleSpecifier) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.exportClause !== exportClause + || node.moduleSpecifier !== moduleSpecifier + ? updateNode(createExportDeclaration(decorators, modifiers, exportClause, moduleSpecifier), node) + : node; + } + ts.updateExportDeclaration = updateExportDeclaration; + function createNamedExports(elements) { + var node = createSynthesizedNode(256 /* NamedExports */); + node.elements = createNodeArray(elements); + return node; + } + ts.createNamedExports = createNamedExports; + function updateNamedExports(node, elements) { + return node.elements !== elements + ? updateNode(createNamedExports(elements), node) + : node; + } + ts.updateNamedExports = updateNamedExports; + function createExportSpecifier(propertyName, name) { + var node = createSynthesizedNode(257 /* ExportSpecifier */); + node.propertyName = asName(propertyName); + node.name = asName(name); + return node; + } + ts.createExportSpecifier = createExportSpecifier; + function updateExportSpecifier(node, propertyName, name) { + return node.propertyName !== propertyName + || node.name !== name + ? updateNode(createExportSpecifier(propertyName, name), node) + : node; + } + ts.updateExportSpecifier = updateExportSpecifier; + // Module references + function createExternalModuleReference(expression) { + var node = createSynthesizedNode(259 /* ExternalModuleReference */); + node.expression = expression; + return node; + } + ts.createExternalModuleReference = createExternalModuleReference; + function updateExternalModuleReference(node, expression) { + return node.expression !== expression + ? updateNode(createExternalModuleReference(expression), node) + : node; + } + ts.updateExternalModuleReference = updateExternalModuleReference; + // JSDoc + /* @internal */ + function createJSDocTypeExpression(type) { + var node = createSynthesizedNode(283 /* JSDocTypeExpression */); + node.type = type; + return node; + } + ts.createJSDocTypeExpression = createJSDocTypeExpression; + /* @internal */ + function createJSDocTypeTag(typeExpression, comment) { + var tag = createJSDocTag(302 /* JSDocTypeTag */, "type"); + tag.typeExpression = typeExpression; + tag.comment = comment; + return tag; + } + ts.createJSDocTypeTag = createJSDocTypeTag; + /* @internal */ + function createJSDocReturnTag(typeExpression, comment) { + var tag = createJSDocTag(300 /* JSDocReturnTag */, "returns"); + tag.typeExpression = typeExpression; + tag.comment = comment; + return tag; + } + ts.createJSDocReturnTag = createJSDocReturnTag; + /* @internal */ + function createJSDocParamTag(name, isBracketed, typeExpression, comment) { + var tag = createJSDocTag(299 /* JSDocParameterTag */, "param"); + tag.typeExpression = typeExpression; + tag.name = name; + tag.isBracketed = isBracketed; + tag.comment = comment; + return tag; + } + ts.createJSDocParamTag = createJSDocParamTag; + /* @internal */ + function createJSDocComment(comment, tags) { + var node = createSynthesizedNode(291 /* JSDocComment */); + node.comment = comment; + node.tags = tags; + return node; + } + ts.createJSDocComment = createJSDocComment; + /* @internal */ + function createJSDocTag(kind, tagName) { + var node = createSynthesizedNode(kind); + node.tagName = createIdentifier(tagName); + return node; + } + // JSX + function createJsxElement(openingElement, children, closingElement) { + var node = createSynthesizedNode(260 /* JsxElement */); + node.openingElement = openingElement; + node.children = createNodeArray(children); + node.closingElement = closingElement; + return node; + } + ts.createJsxElement = createJsxElement; + function updateJsxElement(node, openingElement, children, closingElement) { + return node.openingElement !== openingElement + || node.children !== children + || node.closingElement !== closingElement + ? updateNode(createJsxElement(openingElement, children, closingElement), node) + : node; + } + ts.updateJsxElement = updateJsxElement; + function createJsxSelfClosingElement(tagName, typeArguments, attributes) { + var node = createSynthesizedNode(261 /* JsxSelfClosingElement */); + node.tagName = tagName; + node.typeArguments = asNodeArray(typeArguments); + node.attributes = attributes; + return node; + } + ts.createJsxSelfClosingElement = createJsxSelfClosingElement; + function updateJsxSelfClosingElement(node, tagName, typeArguments, attributes) { + return node.tagName !== tagName + || node.typeArguments !== typeArguments + || node.attributes !== attributes + ? updateNode(createJsxSelfClosingElement(tagName, typeArguments, attributes), node) + : node; + } + ts.updateJsxSelfClosingElement = updateJsxSelfClosingElement; + function createJsxOpeningElement(tagName, typeArguments, attributes) { + var node = createSynthesizedNode(262 /* JsxOpeningElement */); + node.tagName = tagName; + node.typeArguments = asNodeArray(typeArguments); + node.attributes = attributes; + return node; + } + ts.createJsxOpeningElement = createJsxOpeningElement; + function updateJsxOpeningElement(node, tagName, typeArguments, attributes) { + return node.tagName !== tagName + || node.typeArguments !== typeArguments + || node.attributes !== attributes + ? updateNode(createJsxOpeningElement(tagName, typeArguments, attributes), node) + : node; + } + ts.updateJsxOpeningElement = updateJsxOpeningElement; + function createJsxClosingElement(tagName) { + var node = createSynthesizedNode(263 /* JsxClosingElement */); + node.tagName = tagName; + return node; + } + ts.createJsxClosingElement = createJsxClosingElement; + function updateJsxClosingElement(node, tagName) { + return node.tagName !== tagName + ? updateNode(createJsxClosingElement(tagName), node) + : node; + } + ts.updateJsxClosingElement = updateJsxClosingElement; + function createJsxFragment(openingFragment, children, closingFragment) { + var node = createSynthesizedNode(264 /* JsxFragment */); + node.openingFragment = openingFragment; + node.children = createNodeArray(children); + node.closingFragment = closingFragment; + return node; + } + ts.createJsxFragment = createJsxFragment; + function updateJsxFragment(node, openingFragment, children, closingFragment) { + return node.openingFragment !== openingFragment + || node.children !== children + || node.closingFragment !== closingFragment + ? updateNode(createJsxFragment(openingFragment, children, closingFragment), node) + : node; + } + ts.updateJsxFragment = updateJsxFragment; + function createJsxAttribute(name, initializer) { + var node = createSynthesizedNode(267 /* JsxAttribute */); + node.name = name; + node.initializer = initializer; + return node; + } + ts.createJsxAttribute = createJsxAttribute; + function updateJsxAttribute(node, name, initializer) { + return node.name !== name + || node.initializer !== initializer + ? updateNode(createJsxAttribute(name, initializer), node) + : node; + } + ts.updateJsxAttribute = updateJsxAttribute; + function createJsxAttributes(properties) { + var node = createSynthesizedNode(268 /* JsxAttributes */); + node.properties = createNodeArray(properties); + return node; + } + ts.createJsxAttributes = createJsxAttributes; + function updateJsxAttributes(node, properties) { + return node.properties !== properties + ? updateNode(createJsxAttributes(properties), node) + : node; + } + ts.updateJsxAttributes = updateJsxAttributes; + function createJsxSpreadAttribute(expression) { + var node = createSynthesizedNode(269 /* JsxSpreadAttribute */); + node.expression = expression; + return node; + } + ts.createJsxSpreadAttribute = createJsxSpreadAttribute; + function updateJsxSpreadAttribute(node, expression) { + return node.expression !== expression + ? updateNode(createJsxSpreadAttribute(expression), node) + : node; + } + ts.updateJsxSpreadAttribute = updateJsxSpreadAttribute; + function createJsxExpression(dotDotDotToken, expression) { + var node = createSynthesizedNode(270 /* JsxExpression */); + node.dotDotDotToken = dotDotDotToken; + node.expression = expression; + return node; + } + ts.createJsxExpression = createJsxExpression; + function updateJsxExpression(node, expression) { + return node.expression !== expression + ? updateNode(createJsxExpression(node.dotDotDotToken, expression), node) + : node; + } + ts.updateJsxExpression = updateJsxExpression; + // Clauses + function createCaseClause(expression, statements) { + var node = createSynthesizedNode(271 /* CaseClause */); + node.expression = ts.parenthesizeExpressionForList(expression); + node.statements = createNodeArray(statements); + return node; + } + ts.createCaseClause = createCaseClause; + function updateCaseClause(node, expression, statements) { + return node.expression !== expression + || node.statements !== statements + ? updateNode(createCaseClause(expression, statements), node) + : node; + } + ts.updateCaseClause = updateCaseClause; + function createDefaultClause(statements) { + var node = createSynthesizedNode(272 /* DefaultClause */); + node.statements = createNodeArray(statements); + return node; + } + ts.createDefaultClause = createDefaultClause; + function updateDefaultClause(node, statements) { + return node.statements !== statements + ? updateNode(createDefaultClause(statements), node) + : node; + } + ts.updateDefaultClause = updateDefaultClause; + function createHeritageClause(token, types) { + var node = createSynthesizedNode(273 /* HeritageClause */); + node.token = token; + node.types = createNodeArray(types); + return node; + } + ts.createHeritageClause = createHeritageClause; + function updateHeritageClause(node, types) { + return node.types !== types + ? updateNode(createHeritageClause(node.token, types), node) + : node; + } + ts.updateHeritageClause = updateHeritageClause; + function createCatchClause(variableDeclaration, block) { + var node = createSynthesizedNode(274 /* CatchClause */); + node.variableDeclaration = ts.isString(variableDeclaration) ? createVariableDeclaration(variableDeclaration) : variableDeclaration; + node.block = block; + return node; + } + ts.createCatchClause = createCatchClause; + function updateCatchClause(node, variableDeclaration, block) { + return node.variableDeclaration !== variableDeclaration + || node.block !== block + ? updateNode(createCatchClause(variableDeclaration, block), node) + : node; + } + ts.updateCatchClause = updateCatchClause; + // Property assignments + function createPropertyAssignment(name, initializer) { + var node = createSynthesizedNode(275 /* PropertyAssignment */); + node.name = asName(name); + node.questionToken = undefined; + node.initializer = ts.parenthesizeExpressionForList(initializer); + return node; + } + ts.createPropertyAssignment = createPropertyAssignment; + function updatePropertyAssignment(node, name, initializer) { + return node.name !== name + || node.initializer !== initializer + ? updateNode(createPropertyAssignment(name, initializer), node) + : node; + } + ts.updatePropertyAssignment = updatePropertyAssignment; + function createShorthandPropertyAssignment(name, objectAssignmentInitializer) { + var node = createSynthesizedNode(276 /* ShorthandPropertyAssignment */); + node.name = asName(name); + node.objectAssignmentInitializer = objectAssignmentInitializer !== undefined ? ts.parenthesizeExpressionForList(objectAssignmentInitializer) : undefined; + return node; + } + ts.createShorthandPropertyAssignment = createShorthandPropertyAssignment; + function updateShorthandPropertyAssignment(node, name, objectAssignmentInitializer) { + return node.name !== name + || node.objectAssignmentInitializer !== objectAssignmentInitializer + ? updateNode(createShorthandPropertyAssignment(name, objectAssignmentInitializer), node) + : node; + } + ts.updateShorthandPropertyAssignment = updateShorthandPropertyAssignment; + function createSpreadAssignment(expression) { + var node = createSynthesizedNode(277 /* SpreadAssignment */); + node.expression = expression !== undefined ? ts.parenthesizeExpressionForList(expression) : undefined; // TODO: GH#18217 + return node; + } + ts.createSpreadAssignment = createSpreadAssignment; + function updateSpreadAssignment(node, expression) { + return node.expression !== expression + ? updateNode(createSpreadAssignment(expression), node) + : node; + } + ts.updateSpreadAssignment = updateSpreadAssignment; + // Enum + function createEnumMember(name, initializer) { + var node = createSynthesizedNode(278 /* EnumMember */); + node.name = asName(name); + node.initializer = initializer && ts.parenthesizeExpressionForList(initializer); + return node; + } + ts.createEnumMember = createEnumMember; + function updateEnumMember(node, name, initializer) { + return node.name !== name + || node.initializer !== initializer + ? updateNode(createEnumMember(name, initializer), node) + : node; + } + ts.updateEnumMember = updateEnumMember; + // Top-level nodes + function updateSourceFileNode(node, statements, isDeclarationFile, referencedFiles, typeReferences, hasNoDefaultLib, libReferences) { + if (node.statements !== statements || + (isDeclarationFile !== undefined && node.isDeclarationFile !== isDeclarationFile) || + (referencedFiles !== undefined && node.referencedFiles !== referencedFiles) || + (typeReferences !== undefined && node.typeReferenceDirectives !== typeReferences) || + (libReferences !== undefined && node.libReferenceDirectives !== libReferences) || + (hasNoDefaultLib !== undefined && node.hasNoDefaultLib !== hasNoDefaultLib)) { + var updated = createSynthesizedNode(279 /* SourceFile */); + updated.flags |= node.flags; + updated.statements = createNodeArray(statements); + updated.endOfFileToken = node.endOfFileToken; + updated.fileName = node.fileName; + updated.path = node.path; + updated.text = node.text; + updated.isDeclarationFile = isDeclarationFile === undefined ? node.isDeclarationFile : isDeclarationFile; + updated.referencedFiles = referencedFiles === undefined ? node.referencedFiles : referencedFiles; + updated.typeReferenceDirectives = typeReferences === undefined ? node.typeReferenceDirectives : typeReferences; + updated.hasNoDefaultLib = hasNoDefaultLib === undefined ? node.hasNoDefaultLib : hasNoDefaultLib; + updated.libReferenceDirectives = libReferences === undefined ? node.libReferenceDirectives : libReferences; + if (node.amdDependencies !== undefined) + updated.amdDependencies = node.amdDependencies; + if (node.moduleName !== undefined) + updated.moduleName = node.moduleName; + if (node.languageVariant !== undefined) + updated.languageVariant = node.languageVariant; + if (node.renamedDependencies !== undefined) + updated.renamedDependencies = node.renamedDependencies; + if (node.languageVersion !== undefined) + updated.languageVersion = node.languageVersion; + if (node.scriptKind !== undefined) + updated.scriptKind = node.scriptKind; + if (node.externalModuleIndicator !== undefined) + updated.externalModuleIndicator = node.externalModuleIndicator; + if (node.commonJsModuleIndicator !== undefined) + updated.commonJsModuleIndicator = node.commonJsModuleIndicator; + if (node.identifiers !== undefined) + updated.identifiers = node.identifiers; + if (node.nodeCount !== undefined) + updated.nodeCount = node.nodeCount; + if (node.identifierCount !== undefined) + updated.identifierCount = node.identifierCount; + if (node.symbolCount !== undefined) + updated.symbolCount = node.symbolCount; + if (node.parseDiagnostics !== undefined) + updated.parseDiagnostics = node.parseDiagnostics; + if (node.bindDiagnostics !== undefined) + updated.bindDiagnostics = node.bindDiagnostics; + if (node.bindSuggestionDiagnostics !== undefined) + updated.bindSuggestionDiagnostics = node.bindSuggestionDiagnostics; + if (node.lineMap !== undefined) + updated.lineMap = node.lineMap; + if (node.classifiableNames !== undefined) + updated.classifiableNames = node.classifiableNames; + if (node.resolvedModules !== undefined) + updated.resolvedModules = node.resolvedModules; + if (node.resolvedTypeReferenceDirectiveNames !== undefined) + updated.resolvedTypeReferenceDirectiveNames = node.resolvedTypeReferenceDirectiveNames; + if (node.imports !== undefined) + updated.imports = node.imports; + if (node.moduleAugmentations !== undefined) + updated.moduleAugmentations = node.moduleAugmentations; + if (node.pragmas !== undefined) + updated.pragmas = node.pragmas; + if (node.localJsxFactory !== undefined) + updated.localJsxFactory = node.localJsxFactory; + if (node.localJsxNamespace !== undefined) + updated.localJsxNamespace = node.localJsxNamespace; + return updateNode(updated, node); + } + return node; + } + ts.updateSourceFileNode = updateSourceFileNode; + /** + * Creates a shallow, memberwise clone of a node for mutation. + */ + function getMutableClone(node) { + var clone = getSynthesizedClone(node); + clone.pos = node.pos; + clone.end = node.end; + clone.parent = node.parent; + return clone; + } + ts.getMutableClone = getMutableClone; + // Transformation nodes + /** + * Creates a synthetic statement to act as a placeholder for a not-emitted statement in + * order to preserve comments. + * + * @param original The original statement. + */ + function createNotEmittedStatement(original) { + var node = createSynthesizedNode(307 /* NotEmittedStatement */); + node.original = original; + setTextRange(node, original); + return node; + } + ts.createNotEmittedStatement = createNotEmittedStatement; + /** + * Creates a synthetic element to act as a placeholder for the end of an emitted declaration in + * order to properly emit exports. + */ + /* @internal */ + function createEndOfDeclarationMarker(original) { + var node = createSynthesizedNode(311 /* EndOfDeclarationMarker */); + node.emitNode = {}; + node.original = original; + return node; + } + ts.createEndOfDeclarationMarker = createEndOfDeclarationMarker; + /** + * Creates a synthetic element to act as a placeholder for the beginning of a merged declaration in + * order to properly emit exports. + */ + /* @internal */ + function createMergeDeclarationMarker(original) { + var node = createSynthesizedNode(310 /* MergeDeclarationMarker */); + node.emitNode = {}; + node.original = original; + return node; + } + ts.createMergeDeclarationMarker = createMergeDeclarationMarker; + /** + * Creates a synthetic expression to act as a placeholder for a not-emitted expression in + * order to preserve comments or sourcemap positions. + * + * @param expression The inner expression to emit. + * @param original The original outer expression. + * @param location The location for the expression. Defaults to the positions from "original" if provided. + */ + function createPartiallyEmittedExpression(expression, original) { + var node = createSynthesizedNode(308 /* PartiallyEmittedExpression */); + node.expression = expression; + node.original = original; + setTextRange(node, original); + return node; + } + ts.createPartiallyEmittedExpression = createPartiallyEmittedExpression; + function updatePartiallyEmittedExpression(node, expression) { + if (node.expression !== expression) { + return updateNode(createPartiallyEmittedExpression(expression, node.original), node); + } + return node; + } + ts.updatePartiallyEmittedExpression = updatePartiallyEmittedExpression; + function flattenCommaElements(node) { + if (ts.nodeIsSynthesized(node) && !ts.isParseTreeNode(node) && !node.original && !node.emitNode && !node.id) { + if (node.kind === 309 /* CommaListExpression */) { + return node.elements; + } + if (ts.isBinaryExpression(node) && node.operatorToken.kind === 27 /* CommaToken */) { + return [node.left, node.right]; + } + } + return node; + } + function createCommaList(elements) { + var node = createSynthesizedNode(309 /* CommaListExpression */); + node.elements = createNodeArray(ts.sameFlatMap(elements, flattenCommaElements)); + return node; + } + ts.createCommaList = createCommaList; + function updateCommaList(node, elements) { + return node.elements !== elements + ? updateNode(createCommaList(elements), node) + : node; + } + ts.updateCommaList = updateCommaList; + function createBundle(sourceFiles, prepends) { + if (prepends === void 0) { prepends = ts.emptyArray; } + var node = ts.createNode(280 /* Bundle */); + node.prepends = prepends; + node.sourceFiles = sourceFiles; + return node; + } + ts.createBundle = createBundle; + function createUnparsedSourceFile(text, mapPath, map) { + var node = ts.createNode(281 /* UnparsedSource */); + node.text = text; + node.sourceMapPath = mapPath; + node.sourceMapText = map; + return node; + } + ts.createUnparsedSourceFile = createUnparsedSourceFile; + function createInputFiles(javascript, declaration, javascriptMapPath, javascriptMapText, declarationMapPath, declarationMapText) { + var node = ts.createNode(282 /* InputFiles */); + node.javascriptText = javascript; + node.javascriptMapPath = javascriptMapPath; + node.javascriptMapText = javascriptMapText; + node.declarationText = declaration; + node.declarationMapPath = declarationMapPath; + node.declarationMapText = declarationMapText; + return node; + } + ts.createInputFiles = createInputFiles; + function updateBundle(node, sourceFiles, prepends) { + if (prepends === void 0) { prepends = ts.emptyArray; } + if (node.sourceFiles !== sourceFiles || node.prepends !== prepends) { + return createBundle(sourceFiles, prepends); + } + return node; + } + ts.updateBundle = updateBundle; + function createImmediatelyInvokedFunctionExpression(statements, param, paramValue) { + return createCall(createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, + /*parameters*/ param ? [param] : [], + /*type*/ undefined, createBlock(statements, /*multiLine*/ true)), + /*typeArguments*/ undefined, + /*argumentsArray*/ paramValue ? [paramValue] : []); + } + ts.createImmediatelyInvokedFunctionExpression = createImmediatelyInvokedFunctionExpression; + function createImmediatelyInvokedArrowFunction(statements, param, paramValue) { + return createCall(createArrowFunction( + /*modifiers*/ undefined, + /*typeParameters*/ undefined, + /*parameters*/ param ? [param] : [], + /*type*/ undefined, + /*equalsGreaterThanToken*/ undefined, createBlock(statements, /*multiLine*/ true)), + /*typeArguments*/ undefined, + /*argumentsArray*/ paramValue ? [paramValue] : []); + } + ts.createImmediatelyInvokedArrowFunction = createImmediatelyInvokedArrowFunction; + function createComma(left, right) { + return createBinary(left, 27 /* CommaToken */, right); + } + ts.createComma = createComma; + function createLessThan(left, right) { + return createBinary(left, 28 /* LessThanToken */, right); + } + ts.createLessThan = createLessThan; + function createAssignment(left, right) { + return createBinary(left, 59 /* EqualsToken */, right); + } + ts.createAssignment = createAssignment; + function createStrictEquality(left, right) { + return createBinary(left, 35 /* EqualsEqualsEqualsToken */, right); + } + ts.createStrictEquality = createStrictEquality; + function createStrictInequality(left, right) { + return createBinary(left, 36 /* ExclamationEqualsEqualsToken */, right); + } + ts.createStrictInequality = createStrictInequality; + function createAdd(left, right) { + return createBinary(left, 38 /* PlusToken */, right); + } + ts.createAdd = createAdd; + function createSubtract(left, right) { + return createBinary(left, 39 /* MinusToken */, right); + } + ts.createSubtract = createSubtract; + function createPostfixIncrement(operand) { + return createPostfix(operand, 44 /* PlusPlusToken */); + } + ts.createPostfixIncrement = createPostfixIncrement; + function createLogicalAnd(left, right) { + return createBinary(left, 54 /* AmpersandAmpersandToken */, right); + } + ts.createLogicalAnd = createLogicalAnd; + function createLogicalOr(left, right) { + return createBinary(left, 55 /* BarBarToken */, right); + } + ts.createLogicalOr = createLogicalOr; + function createLogicalNot(operand) { + return createPrefix(52 /* ExclamationToken */, operand); + } + ts.createLogicalNot = createLogicalNot; + function createVoidZero() { + return createVoid(createLiteral(0)); + } + ts.createVoidZero = createVoidZero; + function createExportDefault(expression) { + return createExportAssignment(/*decorators*/ undefined, /*modifiers*/ undefined, /*isExportEquals*/ false, expression); + } + ts.createExportDefault = createExportDefault; + function createExternalModuleExport(exportName) { + return createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, createNamedExports([createExportSpecifier(/*propertyName*/ undefined, exportName)])); + } + ts.createExternalModuleExport = createExternalModuleExport; + // Utilities + function asName(name) { + return ts.isString(name) ? createIdentifier(name) : name; + } + function asExpression(value) { + return ts.isString(value) || typeof value === "number" ? createLiteral(value) : value; + } + function asNodeArray(array) { + return array ? createNodeArray(array) : undefined; + } + function asToken(value) { + return typeof value === "number" ? createToken(value) : value; + } + /** + * Clears any EmitNode entries from parse-tree nodes. + * @param sourceFile A source file. + */ + function disposeEmitNodes(sourceFile) { + // During transformation we may need to annotate a parse tree node with transient + // transformation properties. As parse tree nodes live longer than transformation + // nodes, we need to make sure we reclaim any memory allocated for custom ranges + // from these nodes to ensure we do not hold onto entire subtrees just for position + // information. We also need to reset these nodes to a pre-transformation state + // for incremental parsing scenarios so that we do not impact later emit. + sourceFile = ts.getSourceFileOfNode(ts.getParseTreeNode(sourceFile)); + var emitNode = sourceFile && sourceFile.emitNode; + var annotatedNodes = emitNode && emitNode.annotatedNodes; + if (annotatedNodes) { + for (var _i = 0, annotatedNodes_1 = annotatedNodes; _i < annotatedNodes_1.length; _i++) { + var node = annotatedNodes_1[_i]; + node.emitNode = undefined; + } + } + } + ts.disposeEmitNodes = disposeEmitNodes; + /** + * Associates a node with the current transformation, initializing + * various transient transformation properties. + */ + /* @internal */ + function getOrCreateEmitNode(node) { + if (!node.emitNode) { + if (ts.isParseTreeNode(node)) { + // To avoid holding onto transformation artifacts, we keep track of any + // parse tree node we are annotating. This allows us to clean them up after + // all transformations have completed. + if (node.kind === 279 /* SourceFile */) { + return node.emitNode = { annotatedNodes: [node] }; + } + var sourceFile = ts.getSourceFileOfNode(node); + getOrCreateEmitNode(sourceFile).annotatedNodes.push(node); + } + node.emitNode = {}; + } + return node.emitNode; + } + ts.getOrCreateEmitNode = getOrCreateEmitNode; + function setTextRange(range, location) { + if (location) { + range.pos = location.pos; + range.end = location.end; + } + return range; + } + ts.setTextRange = setTextRange; + /** + * Sets flags that control emit behavior of a node. + */ + function setEmitFlags(node, emitFlags) { + getOrCreateEmitNode(node).flags = emitFlags; + return node; + } + ts.setEmitFlags = setEmitFlags; + /** + * Sets flags that control emit behavior of a node. + */ + /* @internal */ + function addEmitFlags(node, emitFlags) { + var emitNode = getOrCreateEmitNode(node); + emitNode.flags = emitNode.flags | emitFlags; + return node; + } + ts.addEmitFlags = addEmitFlags; + /** + * Gets a custom text range to use when emitting source maps. + */ + function getSourceMapRange(node) { + var emitNode = node.emitNode; + return (emitNode && emitNode.sourceMapRange) || node; + } + ts.getSourceMapRange = getSourceMapRange; + /** + * Sets a custom text range to use when emitting source maps. + */ + function setSourceMapRange(node, range) { + getOrCreateEmitNode(node).sourceMapRange = range; + return node; + } + ts.setSourceMapRange = setSourceMapRange; + // tslint:disable-next-line variable-name + var SourceMapSource; + /** + * Create an external source map source file reference + */ + function createSourceMapSource(fileName, text, skipTrivia) { + return new (SourceMapSource || (SourceMapSource = ts.objectAllocator.getSourceMapSourceConstructor()))(fileName, text, skipTrivia); + } + ts.createSourceMapSource = createSourceMapSource; + /** + * Gets the TextRange to use for source maps for a token of a node. + */ + function getTokenSourceMapRange(node, token) { + var emitNode = node.emitNode; + var tokenSourceMapRanges = emitNode && emitNode.tokenSourceMapRanges; + return tokenSourceMapRanges && tokenSourceMapRanges[token]; + } + ts.getTokenSourceMapRange = getTokenSourceMapRange; + /** + * Sets the TextRange to use for source maps for a token of a node. + */ + function setTokenSourceMapRange(node, token, range) { + var emitNode = getOrCreateEmitNode(node); + var tokenSourceMapRanges = emitNode.tokenSourceMapRanges || (emitNode.tokenSourceMapRanges = []); + tokenSourceMapRanges[token] = range; + return node; + } + ts.setTokenSourceMapRange = setTokenSourceMapRange; + /** + * Gets a custom text range to use when emitting comments. + */ + /*@internal*/ + function getStartsOnNewLine(node) { + var emitNode = node.emitNode; + return emitNode && emitNode.startsOnNewLine; + } + ts.getStartsOnNewLine = getStartsOnNewLine; + /** + * Sets a custom text range to use when emitting comments. + */ + /*@internal*/ + function setStartsOnNewLine(node, newLine) { + getOrCreateEmitNode(node).startsOnNewLine = newLine; + return node; + } + ts.setStartsOnNewLine = setStartsOnNewLine; + /** + * Gets a custom text range to use when emitting comments. + */ + function getCommentRange(node) { + var emitNode = node.emitNode; + return (emitNode && emitNode.commentRange) || node; + } + ts.getCommentRange = getCommentRange; + /** + * Sets a custom text range to use when emitting comments. + */ + function setCommentRange(node, range) { + getOrCreateEmitNode(node).commentRange = range; + return node; + } + ts.setCommentRange = setCommentRange; + function getSyntheticLeadingComments(node) { + var emitNode = node.emitNode; + return emitNode && emitNode.leadingComments; + } + ts.getSyntheticLeadingComments = getSyntheticLeadingComments; + function setSyntheticLeadingComments(node, comments) { + getOrCreateEmitNode(node).leadingComments = comments; + return node; + } + ts.setSyntheticLeadingComments = setSyntheticLeadingComments; + function addSyntheticLeadingComment(node, kind, text, hasTrailingNewLine) { + return setSyntheticLeadingComments(node, ts.append(getSyntheticLeadingComments(node), { kind: kind, pos: -1, end: -1, hasTrailingNewLine: hasTrailingNewLine, text: text })); + } + ts.addSyntheticLeadingComment = addSyntheticLeadingComment; + function getSyntheticTrailingComments(node) { + var emitNode = node.emitNode; + return emitNode && emitNode.trailingComments; + } + ts.getSyntheticTrailingComments = getSyntheticTrailingComments; + function setSyntheticTrailingComments(node, comments) { + getOrCreateEmitNode(node).trailingComments = comments; + return node; + } + ts.setSyntheticTrailingComments = setSyntheticTrailingComments; + function addSyntheticTrailingComment(node, kind, text, hasTrailingNewLine) { + return setSyntheticTrailingComments(node, ts.append(getSyntheticTrailingComments(node), { kind: kind, pos: -1, end: -1, hasTrailingNewLine: hasTrailingNewLine, text: text })); + } + ts.addSyntheticTrailingComment = addSyntheticTrailingComment; + function moveSyntheticComments(node, original) { + setSyntheticLeadingComments(node, getSyntheticLeadingComments(original)); + setSyntheticTrailingComments(node, getSyntheticTrailingComments(original)); + var emit = getOrCreateEmitNode(original); + emit.leadingComments = undefined; + emit.trailingComments = undefined; + return node; + } + ts.moveSyntheticComments = moveSyntheticComments; + /** + * Gets the constant value to emit for an expression. + */ + function getConstantValue(node) { + var emitNode = node.emitNode; + return emitNode && emitNode.constantValue; + } + ts.getConstantValue = getConstantValue; + /** + * Sets the constant value to emit for an expression. + */ + function setConstantValue(node, value) { + var emitNode = getOrCreateEmitNode(node); + emitNode.constantValue = value; + return node; + } + ts.setConstantValue = setConstantValue; + /** + * Adds an EmitHelper to a node. + */ + function addEmitHelper(node, helper) { + var emitNode = getOrCreateEmitNode(node); + emitNode.helpers = ts.append(emitNode.helpers, helper); + return node; + } + ts.addEmitHelper = addEmitHelper; + /** + * Add EmitHelpers to a node. + */ + function addEmitHelpers(node, helpers) { + if (ts.some(helpers)) { + var emitNode = getOrCreateEmitNode(node); + for (var _i = 0, helpers_1 = helpers; _i < helpers_1.length; _i++) { + var helper = helpers_1[_i]; + emitNode.helpers = ts.appendIfUnique(emitNode.helpers, helper); + } + } + return node; + } + ts.addEmitHelpers = addEmitHelpers; + /** + * Removes an EmitHelper from a node. + */ + function removeEmitHelper(node, helper) { + var emitNode = node.emitNode; + if (emitNode) { + var helpers = emitNode.helpers; + if (helpers) { + return ts.orderedRemoveItem(helpers, helper); + } + } + return false; + } + ts.removeEmitHelper = removeEmitHelper; + /** + * Gets the EmitHelpers of a node. + */ + function getEmitHelpers(node) { + var emitNode = node.emitNode; + return emitNode && emitNode.helpers; + } + ts.getEmitHelpers = getEmitHelpers; + /** + * Moves matching emit helpers from a source node to a target node. + */ + function moveEmitHelpers(source, target, predicate) { + var sourceEmitNode = source.emitNode; + var sourceEmitHelpers = sourceEmitNode && sourceEmitNode.helpers; + if (!ts.some(sourceEmitHelpers)) + return; + var targetEmitNode = getOrCreateEmitNode(target); + var helpersRemoved = 0; + for (var i = 0; i < sourceEmitHelpers.length; i++) { + var helper = sourceEmitHelpers[i]; + if (predicate(helper)) { + helpersRemoved++; + targetEmitNode.helpers = ts.appendIfUnique(targetEmitNode.helpers, helper); + } + else if (helpersRemoved > 0) { + sourceEmitHelpers[i - helpersRemoved] = helper; + } + } + if (helpersRemoved > 0) { + sourceEmitHelpers.length -= helpersRemoved; + } + } + ts.moveEmitHelpers = moveEmitHelpers; + /* @internal */ + function compareEmitHelpers(x, y) { + if (x === y) + return 0 /* EqualTo */; + if (x.priority === y.priority) + return 0 /* EqualTo */; + if (x.priority === undefined) + return 1 /* GreaterThan */; + if (y.priority === undefined) + return -1 /* LessThan */; + return ts.compareValues(x.priority, y.priority); + } + ts.compareEmitHelpers = compareEmitHelpers; + function setOriginalNode(node, original) { + node.original = original; + if (original) { + var emitNode = original.emitNode; + if (emitNode) + node.emitNode = mergeEmitNode(emitNode, node.emitNode); + } + return node; + } + ts.setOriginalNode = setOriginalNode; + function mergeEmitNode(sourceEmitNode, destEmitNode) { + var flags = sourceEmitNode.flags, leadingComments = sourceEmitNode.leadingComments, trailingComments = sourceEmitNode.trailingComments, commentRange = sourceEmitNode.commentRange, sourceMapRange = sourceEmitNode.sourceMapRange, tokenSourceMapRanges = sourceEmitNode.tokenSourceMapRanges, constantValue = sourceEmitNode.constantValue, helpers = sourceEmitNode.helpers, startsOnNewLine = sourceEmitNode.startsOnNewLine; + if (!destEmitNode) + destEmitNode = {}; + // We are using `.slice()` here in case `destEmitNode.leadingComments` is pushed to later. + if (leadingComments) + destEmitNode.leadingComments = ts.addRange(leadingComments.slice(), destEmitNode.leadingComments); + if (trailingComments) + destEmitNode.trailingComments = ts.addRange(trailingComments.slice(), destEmitNode.trailingComments); + if (flags) + destEmitNode.flags = flags; + if (commentRange) + destEmitNode.commentRange = commentRange; + if (sourceMapRange) + destEmitNode.sourceMapRange = sourceMapRange; + if (tokenSourceMapRanges) + destEmitNode.tokenSourceMapRanges = mergeTokenSourceMapRanges(tokenSourceMapRanges, destEmitNode.tokenSourceMapRanges); + if (constantValue !== undefined) + destEmitNode.constantValue = constantValue; + if (helpers) + destEmitNode.helpers = ts.addRange(destEmitNode.helpers, helpers); + if (startsOnNewLine !== undefined) + destEmitNode.startsOnNewLine = startsOnNewLine; + return destEmitNode; + } + function mergeTokenSourceMapRanges(sourceRanges, destRanges) { + if (!destRanges) + destRanges = []; + for (var key in sourceRanges) { + destRanges[key] = sourceRanges[key]; + } + return destRanges; + } +})(ts || (ts = {})); +/* @internal */ +(function (ts) { + ts.nullTransformationContext = { + enableEmitNotification: ts.noop, + enableSubstitution: ts.noop, + endLexicalEnvironment: function () { return undefined; }, + getCompilerOptions: ts.notImplemented, + getEmitHost: ts.notImplemented, + getEmitResolver: ts.notImplemented, + hoistFunctionDeclaration: ts.noop, + hoistVariableDeclaration: ts.noop, + isEmitNotificationEnabled: ts.notImplemented, + isSubstitutionEnabled: ts.notImplemented, + onEmitNode: ts.noop, + onSubstituteNode: ts.notImplemented, + readEmitHelpers: ts.notImplemented, + requestEmitHelper: ts.noop, + resumeLexicalEnvironment: ts.noop, + startLexicalEnvironment: ts.noop, + suspendLexicalEnvironment: ts.noop, + addDiagnostic: ts.noop, + }; + function createTypeCheck(value, tag) { + return tag === "undefined" + ? ts.createStrictEquality(value, ts.createVoidZero()) + : ts.createStrictEquality(ts.createTypeOf(value), ts.createLiteral(tag)); + } + ts.createTypeCheck = createTypeCheck; + function createMemberAccessForPropertyName(target, memberName, location) { + if (ts.isComputedPropertyName(memberName)) { + return ts.setTextRange(ts.createElementAccess(target, memberName.expression), location); + } + else { + var expression = ts.setTextRange(ts.isIdentifier(memberName) + ? ts.createPropertyAccess(target, memberName) + : ts.createElementAccess(target, memberName), memberName); + ts.getOrCreateEmitNode(expression).flags |= 64 /* NoNestedSourceMaps */; + return expression; + } + } + ts.createMemberAccessForPropertyName = createMemberAccessForPropertyName; + function createFunctionCall(func, thisArg, argumentsList, location) { + return ts.setTextRange(ts.createCall(ts.createPropertyAccess(func, "call"), + /*typeArguments*/ undefined, [ + thisArg + ].concat(argumentsList)), location); + } + ts.createFunctionCall = createFunctionCall; + function createFunctionApply(func, thisArg, argumentsExpression, location) { + return ts.setTextRange(ts.createCall(ts.createPropertyAccess(func, "apply"), + /*typeArguments*/ undefined, [ + thisArg, + argumentsExpression + ]), location); + } + ts.createFunctionApply = createFunctionApply; + function createArraySlice(array, start) { + var argumentsList = []; + if (start !== undefined) { + argumentsList.push(typeof start === "number" ? ts.createLiteral(start) : start); + } + return ts.createCall(ts.createPropertyAccess(array, "slice"), /*typeArguments*/ undefined, argumentsList); + } + ts.createArraySlice = createArraySlice; + function createArrayConcat(array, values) { + return ts.createCall(ts.createPropertyAccess(array, "concat"), + /*typeArguments*/ undefined, values); + } + ts.createArrayConcat = createArrayConcat; + function createMathPow(left, right, location) { + return ts.setTextRange(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Math"), "pow"), + /*typeArguments*/ undefined, [left, right]), location); + } + ts.createMathPow = createMathPow; + function createReactNamespace(reactNamespace, parent) { + // To ensure the emit resolver can properly resolve the namespace, we need to + // treat this identifier as if it were a source tree node by clearing the `Synthesized` + // flag and setting a parent node. + var react = ts.createIdentifier(reactNamespace || "React"); + react.flags &= ~8 /* Synthesized */; + // Set the parent that is in parse tree + // this makes sure that parent chain is intact for checker to traverse complete scope tree + react.parent = ts.getParseTreeNode(parent); + return react; + } + function createJsxFactoryExpressionFromEntityName(jsxFactory, parent) { + if (ts.isQualifiedName(jsxFactory)) { + var left = createJsxFactoryExpressionFromEntityName(jsxFactory.left, parent); + var right = ts.createIdentifier(ts.idText(jsxFactory.right)); + right.escapedText = jsxFactory.right.escapedText; + return ts.createPropertyAccess(left, right); + } + else { + return createReactNamespace(ts.idText(jsxFactory), parent); + } + } + function createJsxFactoryExpression(jsxFactoryEntity, reactNamespace, parent) { + return jsxFactoryEntity ? + createJsxFactoryExpressionFromEntityName(jsxFactoryEntity, parent) : + ts.createPropertyAccess(createReactNamespace(reactNamespace, parent), "createElement"); + } + function createExpressionForJsxElement(jsxFactoryEntity, reactNamespace, tagName, props, children, parentElement, location) { + var argumentsList = [tagName]; + if (props) { + argumentsList.push(props); + } + if (children && children.length > 0) { + if (!props) { + argumentsList.push(ts.createNull()); + } + if (children.length > 1) { + for (var _i = 0, children_1 = children; _i < children_1.length; _i++) { + var child = children_1[_i]; + startOnNewLine(child); + argumentsList.push(child); + } + } + else { + argumentsList.push(children[0]); + } + } + return ts.setTextRange(ts.createCall(createJsxFactoryExpression(jsxFactoryEntity, reactNamespace, parentElement), + /*typeArguments*/ undefined, argumentsList), location); + } + ts.createExpressionForJsxElement = createExpressionForJsxElement; + function createExpressionForJsxFragment(jsxFactoryEntity, reactNamespace, children, parentElement, location) { + var tagName = ts.createPropertyAccess(createReactNamespace(reactNamespace, parentElement), "Fragment"); + var argumentsList = [tagName]; + argumentsList.push(ts.createNull()); + if (children && children.length > 0) { + if (children.length > 1) { + for (var _i = 0, children_2 = children; _i < children_2.length; _i++) { + var child = children_2[_i]; + startOnNewLine(child); + argumentsList.push(child); + } + } + else { + argumentsList.push(children[0]); + } + } + return ts.setTextRange(ts.createCall(createJsxFactoryExpression(jsxFactoryEntity, reactNamespace, parentElement), + /*typeArguments*/ undefined, argumentsList), location); + } + ts.createExpressionForJsxFragment = createExpressionForJsxFragment; + // Helpers + function getHelperName(name) { + return ts.setEmitFlags(ts.createIdentifier(name), 4096 /* HelperName */ | 2 /* AdviseOnEmitNode */); + } + ts.getHelperName = getHelperName; + var valuesHelper = { + name: "typescript:values", + scoped: false, + text: "\n var __values = (this && this.__values) || function (o) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator], i = 0;\n if (m) return m.call(o);\n return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n };" + }; + function createValuesHelper(context, expression, location) { + context.requestEmitHelper(valuesHelper); + return ts.setTextRange(ts.createCall(getHelperName("__values"), + /*typeArguments*/ undefined, [expression]), location); + } + ts.createValuesHelper = createValuesHelper; + var readHelper = { + name: "typescript:read", + scoped: false, + text: "\n var __read = (this && this.__read) || function (o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m) return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n }\n catch (error) { e = { error: error }; }\n finally {\n try {\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\n }\n finally { if (e) throw e.error; }\n }\n return ar;\n };" + }; + function createReadHelper(context, iteratorRecord, count, location) { + context.requestEmitHelper(readHelper); + return ts.setTextRange(ts.createCall(getHelperName("__read"), + /*typeArguments*/ undefined, count !== undefined + ? [iteratorRecord, ts.createLiteral(count)] + : [iteratorRecord]), location); + } + ts.createReadHelper = createReadHelper; + var spreadHelper = { + name: "typescript:spread", + scoped: false, + text: "\n var __spread = (this && this.__spread) || function () {\n for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i]));\n return ar;\n };" + }; + function createSpreadHelper(context, argumentList, location) { + context.requestEmitHelper(readHelper); + context.requestEmitHelper(spreadHelper); + return ts.setTextRange(ts.createCall(getHelperName("__spread"), + /*typeArguments*/ undefined, argumentList), location); + } + ts.createSpreadHelper = createSpreadHelper; + // Utilities + function createForOfBindingStatement(node, boundValue) { + if (ts.isVariableDeclarationList(node)) { + var firstDeclaration = ts.first(node.declarations); + var updatedDeclaration = ts.updateVariableDeclaration(firstDeclaration, firstDeclaration.name, + /*typeNode*/ undefined, boundValue); + return ts.setTextRange(ts.createVariableStatement( + /*modifiers*/ undefined, ts.updateVariableDeclarationList(node, [updatedDeclaration])), + /*location*/ node); + } + else { + var updatedExpression = ts.setTextRange(ts.createAssignment(node, boundValue), /*location*/ node); + return ts.setTextRange(ts.createStatement(updatedExpression), /*location*/ node); + } + } + ts.createForOfBindingStatement = createForOfBindingStatement; + function insertLeadingStatement(dest, source) { + if (ts.isBlock(dest)) { + return ts.updateBlock(dest, ts.setTextRange(ts.createNodeArray([source].concat(dest.statements)), dest.statements)); + } + else { + return ts.createBlock(ts.createNodeArray([dest, source]), /*multiLine*/ true); + } + } + ts.insertLeadingStatement = insertLeadingStatement; + function restoreEnclosingLabel(node, outermostLabeledStatement, afterRestoreLabelCallback) { + if (!outermostLabeledStatement) { + return node; + } + var updated = ts.updateLabel(outermostLabeledStatement, outermostLabeledStatement.label, outermostLabeledStatement.statement.kind === 233 /* LabeledStatement */ + ? restoreEnclosingLabel(node, outermostLabeledStatement.statement) + : node); + if (afterRestoreLabelCallback) { + afterRestoreLabelCallback(outermostLabeledStatement); + } + return updated; + } + ts.restoreEnclosingLabel = restoreEnclosingLabel; + function shouldBeCapturedInTempVariable(node, cacheIdentifiers) { + var target = ts.skipParentheses(node); + switch (target.kind) { + case 72 /* Identifier */: + return cacheIdentifiers; + case 100 /* ThisKeyword */: + case 8 /* NumericLiteral */: + case 9 /* BigIntLiteral */: + case 10 /* StringLiteral */: + return false; + case 187 /* ArrayLiteralExpression */: + var elements = target.elements; + if (elements.length === 0) { + return false; + } + return true; + case 188 /* ObjectLiteralExpression */: + return target.properties.length > 0; + default: + return true; + } + } + function createCallBinding(expression, recordTempVariable, languageVersion, cacheIdentifiers) { + if (cacheIdentifiers === void 0) { cacheIdentifiers = false; } + var callee = skipOuterExpressions(expression, 7 /* All */); + var thisArg; + var target; + if (ts.isSuperProperty(callee)) { + thisArg = ts.createThis(); + target = callee; + } + else if (callee.kind === 98 /* SuperKeyword */) { + thisArg = ts.createThis(); + target = languageVersion < 2 /* ES2015 */ + ? ts.setTextRange(ts.createIdentifier("_super"), callee) + : callee; + } + else if (ts.getEmitFlags(callee) & 4096 /* HelperName */) { + thisArg = ts.createVoidZero(); + target = parenthesizeForAccess(callee); + } + else { + switch (callee.kind) { + case 189 /* PropertyAccessExpression */: { + if (shouldBeCapturedInTempVariable(callee.expression, cacheIdentifiers)) { + // for `a.b()` target is `(_a = a).b` and thisArg is `_a` + thisArg = ts.createTempVariable(recordTempVariable); + target = ts.createPropertyAccess(ts.setTextRange(ts.createAssignment(thisArg, callee.expression), callee.expression), callee.name); + ts.setTextRange(target, callee); + } + else { + thisArg = callee.expression; + target = callee; + } + break; + } + case 190 /* ElementAccessExpression */: { + if (shouldBeCapturedInTempVariable(callee.expression, cacheIdentifiers)) { + // for `a[b]()` target is `(_a = a)[b]` and thisArg is `_a` + thisArg = ts.createTempVariable(recordTempVariable); + target = ts.createElementAccess(ts.setTextRange(ts.createAssignment(thisArg, callee.expression), callee.expression), callee.argumentExpression); + ts.setTextRange(target, callee); + } + else { + thisArg = callee.expression; + target = callee; + } + break; + } + default: { + // for `a()` target is `a` and thisArg is `void 0` + thisArg = ts.createVoidZero(); + target = parenthesizeForAccess(expression); + break; + } + } + } + return { target: target, thisArg: thisArg }; + } + ts.createCallBinding = createCallBinding; + function inlineExpressions(expressions) { + // Avoid deeply nested comma expressions as traversing them during emit can result in "Maximum call + // stack size exceeded" errors. + return expressions.length > 10 + ? ts.createCommaList(expressions) + : ts.reduceLeft(expressions, ts.createComma); + } + ts.inlineExpressions = inlineExpressions; + function createExpressionFromEntityName(node) { + if (ts.isQualifiedName(node)) { + var left = createExpressionFromEntityName(node.left); + var right = ts.getMutableClone(node.right); + return ts.setTextRange(ts.createPropertyAccess(left, right), node); + } + else { + return ts.getMutableClone(node); + } + } + ts.createExpressionFromEntityName = createExpressionFromEntityName; + function createExpressionForPropertyName(memberName) { + if (ts.isIdentifier(memberName)) { + return ts.createLiteral(memberName); + } + else if (ts.isComputedPropertyName(memberName)) { + return ts.getMutableClone(memberName.expression); + } + else { + return ts.getMutableClone(memberName); + } + } + ts.createExpressionForPropertyName = createExpressionForPropertyName; + function createExpressionForObjectLiteralElementLike(node, property, receiver) { + switch (property.kind) { + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + return createExpressionForAccessorDeclaration(node.properties, property, receiver, !!node.multiLine); + case 275 /* PropertyAssignment */: + return createExpressionForPropertyAssignment(property, receiver); + case 276 /* ShorthandPropertyAssignment */: + return createExpressionForShorthandPropertyAssignment(property, receiver); + case 156 /* MethodDeclaration */: + return createExpressionForMethodDeclaration(property, receiver); + } + } + ts.createExpressionForObjectLiteralElementLike = createExpressionForObjectLiteralElementLike; + function createExpressionForAccessorDeclaration(properties, property, receiver, multiLine) { + var _a = ts.getAllAccessorDeclarations(properties, property), firstAccessor = _a.firstAccessor, getAccessor = _a.getAccessor, setAccessor = _a.setAccessor; + if (property === firstAccessor) { + var properties_8 = []; + if (getAccessor) { + var getterFunction = ts.createFunctionExpression(getAccessor.modifiers, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, getAccessor.parameters, + /*type*/ undefined, getAccessor.body // TODO: GH#18217 + ); + ts.setTextRange(getterFunction, getAccessor); + ts.setOriginalNode(getterFunction, getAccessor); + var getter = ts.createPropertyAssignment("get", getterFunction); + properties_8.push(getter); + } + if (setAccessor) { + var setterFunction = ts.createFunctionExpression(setAccessor.modifiers, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, setAccessor.parameters, + /*type*/ undefined, setAccessor.body // TODO: GH#18217 + ); + ts.setTextRange(setterFunction, setAccessor); + ts.setOriginalNode(setterFunction, setAccessor); + var setter = ts.createPropertyAssignment("set", setterFunction); + properties_8.push(setter); + } + properties_8.push(ts.createPropertyAssignment("enumerable", ts.createTrue())); + properties_8.push(ts.createPropertyAssignment("configurable", ts.createTrue())); + var expression = ts.setTextRange(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"), + /*typeArguments*/ undefined, [ + receiver, + createExpressionForPropertyName(property.name), + ts.createObjectLiteral(properties_8, multiLine) + ]), + /*location*/ firstAccessor); + return ts.aggregateTransformFlags(expression); + } + return undefined; + } + function createExpressionForPropertyAssignment(property, receiver) { + return ts.aggregateTransformFlags(ts.setOriginalNode(ts.setTextRange(ts.createAssignment(createMemberAccessForPropertyName(receiver, property.name, /*location*/ property.name), property.initializer), property), property)); + } + function createExpressionForShorthandPropertyAssignment(property, receiver) { + return ts.aggregateTransformFlags(ts.setOriginalNode(ts.setTextRange(ts.createAssignment(createMemberAccessForPropertyName(receiver, property.name, /*location*/ property.name), ts.getSynthesizedClone(property.name)), + /*location*/ property), + /*original*/ property)); + } + function createExpressionForMethodDeclaration(method, receiver) { + return ts.aggregateTransformFlags(ts.setOriginalNode(ts.setTextRange(ts.createAssignment(createMemberAccessForPropertyName(receiver, method.name, /*location*/ method.name), ts.setOriginalNode(ts.setTextRange(ts.createFunctionExpression(method.modifiers, method.asteriskToken, + /*name*/ undefined, + /*typeParameters*/ undefined, method.parameters, + /*type*/ undefined, method.body // TODO: GH#18217 + ), + /*location*/ method), + /*original*/ method)), + /*location*/ method), + /*original*/ method)); + } + /** + * Gets the internal name of a declaration. This is primarily used for declarations that can be + * referred to by name in the body of an ES5 class function body. An internal name will *never* + * be prefixed with an module or namespace export modifier like "exports." when emitted as an + * expression. An internal name will also *never* be renamed due to a collision with a block + * scoped variable. + * + * @param node The declaration. + * @param allowComments A value indicating whether comments may be emitted for the name. + * @param allowSourceMaps A value indicating whether source maps may be emitted for the name. + */ + function getInternalName(node, allowComments, allowSourceMaps) { + return getName(node, allowComments, allowSourceMaps, 16384 /* LocalName */ | 32768 /* InternalName */); + } + ts.getInternalName = getInternalName; + /** + * Gets whether an identifier should only be referred to by its internal name. + */ + function isInternalName(node) { + return (ts.getEmitFlags(node) & 32768 /* InternalName */) !== 0; + } + ts.isInternalName = isInternalName; + /** + * Gets the local name of a declaration. This is primarily used for declarations that can be + * referred to by name in the declaration's immediate scope (classes, enums, namespaces). A + * local name will *never* be prefixed with an module or namespace export modifier like + * "exports." when emitted as an expression. + * + * @param node The declaration. + * @param allowComments A value indicating whether comments may be emitted for the name. + * @param allowSourceMaps A value indicating whether source maps may be emitted for the name. + */ + function getLocalName(node, allowComments, allowSourceMaps) { + return getName(node, allowComments, allowSourceMaps, 16384 /* LocalName */); + } + ts.getLocalName = getLocalName; + /** + * Gets whether an identifier should only be referred to by its local name. + */ + function isLocalName(node) { + return (ts.getEmitFlags(node) & 16384 /* LocalName */) !== 0; + } + ts.isLocalName = isLocalName; + /** + * Gets the export name of a declaration. This is primarily used for declarations that can be + * referred to by name in the declaration's immediate scope (classes, enums, namespaces). An + * export name will *always* be prefixed with an module or namespace export modifier like + * `"exports."` when emitted as an expression if the name points to an exported symbol. + * + * @param node The declaration. + * @param allowComments A value indicating whether comments may be emitted for the name. + * @param allowSourceMaps A value indicating whether source maps may be emitted for the name. + */ + function getExportName(node, allowComments, allowSourceMaps) { + return getName(node, allowComments, allowSourceMaps, 8192 /* ExportName */); + } + ts.getExportName = getExportName; + /** + * Gets whether an identifier should only be referred to by its export representation if the + * name points to an exported symbol. + */ + function isExportName(node) { + return (ts.getEmitFlags(node) & 8192 /* ExportName */) !== 0; + } + ts.isExportName = isExportName; + /** + * Gets the name of a declaration for use in declarations. + * + * @param node The declaration. + * @param allowComments A value indicating whether comments may be emitted for the name. + * @param allowSourceMaps A value indicating whether source maps may be emitted for the name. + */ + function getDeclarationName(node, allowComments, allowSourceMaps) { + return getName(node, allowComments, allowSourceMaps); + } + ts.getDeclarationName = getDeclarationName; + function getName(node, allowComments, allowSourceMaps, emitFlags) { + if (emitFlags === void 0) { emitFlags = 0; } + var nodeName = ts.getNameOfDeclaration(node); + if (nodeName && ts.isIdentifier(nodeName) && !ts.isGeneratedIdentifier(nodeName)) { + var name = ts.getMutableClone(nodeName); + emitFlags |= ts.getEmitFlags(nodeName); + if (!allowSourceMaps) + emitFlags |= 48 /* NoSourceMap */; + if (!allowComments) + emitFlags |= 1536 /* NoComments */; + if (emitFlags) + ts.setEmitFlags(name, emitFlags); + return name; + } + return ts.getGeneratedNameForNode(node); + } + /** + * Gets the exported name of a declaration for use in expressions. + * + * An exported name will *always* be prefixed with an module or namespace export modifier like + * "exports." if the name points to an exported symbol. + * + * @param ns The namespace identifier. + * @param node The declaration. + * @param allowComments A value indicating whether comments may be emitted for the name. + * @param allowSourceMaps A value indicating whether source maps may be emitted for the name. + */ + function getExternalModuleOrNamespaceExportName(ns, node, allowComments, allowSourceMaps) { + if (ns && ts.hasModifier(node, 1 /* Export */)) { + return getNamespaceMemberName(ns, getName(node), allowComments, allowSourceMaps); + } + return getExportName(node, allowComments, allowSourceMaps); + } + ts.getExternalModuleOrNamespaceExportName = getExternalModuleOrNamespaceExportName; + /** + * Gets a namespace-qualified name for use in expressions. + * + * @param ns The namespace identifier. + * @param name The name. + * @param allowComments A value indicating whether comments may be emitted for the name. + * @param allowSourceMaps A value indicating whether source maps may be emitted for the name. + */ + function getNamespaceMemberName(ns, name, allowComments, allowSourceMaps) { + var qualifiedName = ts.createPropertyAccess(ns, ts.nodeIsSynthesized(name) ? name : ts.getSynthesizedClone(name)); + ts.setTextRange(qualifiedName, name); + var emitFlags = 0; + if (!allowSourceMaps) + emitFlags |= 48 /* NoSourceMap */; + if (!allowComments) + emitFlags |= 1536 /* NoComments */; + if (emitFlags) + ts.setEmitFlags(qualifiedName, emitFlags); + return qualifiedName; + } + ts.getNamespaceMemberName = getNamespaceMemberName; + function convertToFunctionBody(node, multiLine) { + return ts.isBlock(node) ? node : ts.setTextRange(ts.createBlock([ts.setTextRange(ts.createReturn(node), node)], multiLine), node); + } + ts.convertToFunctionBody = convertToFunctionBody; + function convertFunctionDeclarationToExpression(node) { + if (!node.body) + return ts.Debug.fail(); + var updated = ts.createFunctionExpression(node.modifiers, node.asteriskToken, node.name, node.typeParameters, node.parameters, node.type, node.body); + ts.setOriginalNode(updated, node); + ts.setTextRange(updated, node); + if (ts.getStartsOnNewLine(node)) { + ts.setStartsOnNewLine(updated, /*newLine*/ true); + } + ts.aggregateTransformFlags(updated); + return updated; + } + ts.convertFunctionDeclarationToExpression = convertFunctionDeclarationToExpression; + function isUseStrictPrologue(node) { + return ts.isStringLiteral(node.expression) && node.expression.text === "use strict"; + } + /** + * Add any necessary prologue-directives into target statement-array. + * The function needs to be called during each transformation step. + * This function needs to be called whenever we transform the statement + * list of a source file, namespace, or function-like body. + * + * @param target: result statements array + * @param source: origin statements array + * @param ensureUseStrict: boolean determining whether the function need to add prologue-directives + * @param visitor: Optional callback used to visit any custom prologue directives. + */ + function addPrologue(target, source, ensureUseStrict, visitor) { + var offset = addStandardPrologue(target, source, ensureUseStrict); + return addCustomPrologue(target, source, offset, visitor); + } + ts.addPrologue = addPrologue; + /** + * Add just the standard (string-expression) prologue-directives into target statement-array. + * The function needs to be called during each transformation step. + * This function needs to be called whenever we transform the statement + * list of a source file, namespace, or function-like body. + */ + function addStandardPrologue(target, source, ensureUseStrict) { + ts.Debug.assert(target.length === 0, "Prologue directives should be at the first statement in the target statements array"); + var foundUseStrict = false; + var statementOffset = 0; + var numStatements = source.length; + while (statementOffset < numStatements) { + var statement = source[statementOffset]; + if (ts.isPrologueDirective(statement)) { + if (isUseStrictPrologue(statement)) { + foundUseStrict = true; + } + target.push(statement); + } + else { + break; + } + statementOffset++; + } + if (ensureUseStrict && !foundUseStrict) { + target.push(startOnNewLine(ts.createStatement(ts.createLiteral("use strict")))); + } + return statementOffset; + } + ts.addStandardPrologue = addStandardPrologue; + function addCustomPrologue(target, source, statementOffset, visitor) { + var numStatements = source.length; + while (statementOffset !== undefined && statementOffset < numStatements) { + var statement = source[statementOffset]; + if (ts.getEmitFlags(statement) & 1048576 /* CustomPrologue */) { + ts.append(target, visitor ? ts.visitNode(statement, visitor, ts.isStatement) : statement); + } + else { + break; + } + statementOffset++; + } + return statementOffset; + } + ts.addCustomPrologue = addCustomPrologue; + function findUseStrictPrologue(statements) { + for (var _i = 0, statements_3 = statements; _i < statements_3.length; _i++) { + var statement = statements_3[_i]; + if (ts.isPrologueDirective(statement)) { + if (isUseStrictPrologue(statement)) { + return statement; + } + } + else { + break; + } + } + return undefined; + } + ts.findUseStrictPrologue = findUseStrictPrologue; + function startsWithUseStrict(statements) { + var firstStatement = ts.firstOrUndefined(statements); + return firstStatement !== undefined + && ts.isPrologueDirective(firstStatement) + && isUseStrictPrologue(firstStatement); + } + ts.startsWithUseStrict = startsWithUseStrict; + /** + * Ensures "use strict" directive is added + * + * @param statements An array of statements + */ + function ensureUseStrict(statements) { + var foundUseStrict = findUseStrictPrologue(statements); + if (!foundUseStrict) { + return ts.setTextRange(ts.createNodeArray([ + startOnNewLine(ts.createStatement(ts.createLiteral("use strict"))) + ].concat(statements)), statements); + } + return statements; + } + ts.ensureUseStrict = ensureUseStrict; + /** + * Wraps the operand to a BinaryExpression in parentheses if they are needed to preserve the intended + * order of operations. + * + * @param binaryOperator The operator for the BinaryExpression. + * @param operand The operand for the BinaryExpression. + * @param isLeftSideOfBinary A value indicating whether the operand is the left side of the + * BinaryExpression. + */ + function parenthesizeBinaryOperand(binaryOperator, operand, isLeftSideOfBinary, leftOperand) { + var skipped = ts.skipPartiallyEmittedExpressions(operand); + // If the resulting expression is already parenthesized, we do not need to do any further processing. + if (skipped.kind === 195 /* ParenthesizedExpression */) { + return operand; + } + return binaryOperandNeedsParentheses(binaryOperator, operand, isLeftSideOfBinary, leftOperand) + ? ts.createParen(operand) + : operand; + } + ts.parenthesizeBinaryOperand = parenthesizeBinaryOperand; + /** + * Determines whether the operand to a BinaryExpression needs to be parenthesized. + * + * @param binaryOperator The operator for the BinaryExpression. + * @param operand The operand for the BinaryExpression. + * @param isLeftSideOfBinary A value indicating whether the operand is the left side of the + * BinaryExpression. + */ + function binaryOperandNeedsParentheses(binaryOperator, operand, isLeftSideOfBinary, leftOperand) { + // If the operand has lower precedence, then it needs to be parenthesized to preserve the + // intent of the expression. For example, if the operand is `a + b` and the operator is + // `*`, then we need to parenthesize the operand to preserve the intended order of + // operations: `(a + b) * x`. + // + // If the operand has higher precedence, then it does not need to be parenthesized. For + // example, if the operand is `a * b` and the operator is `+`, then we do not need to + // parenthesize to preserve the intended order of operations: `a * b + x`. + // + // If the operand has the same precedence, then we need to check the associativity of + // the operator based on whether this is the left or right operand of the expression. + // + // For example, if `a / d` is on the right of operator `*`, we need to parenthesize + // to preserve the intended order of operations: `x * (a / d)` + // + // If `a ** d` is on the left of operator `**`, we need to parenthesize to preserve + // the intended order of operations: `(a ** b) ** c` + var binaryOperatorPrecedence = ts.getOperatorPrecedence(204 /* BinaryExpression */, binaryOperator); + var binaryOperatorAssociativity = ts.getOperatorAssociativity(204 /* BinaryExpression */, binaryOperator); + var emittedOperand = ts.skipPartiallyEmittedExpressions(operand); + if (!isLeftSideOfBinary && operand.kind === 197 /* ArrowFunction */ && binaryOperatorPrecedence > 4) { + // We need to parenthesize arrow functions on the right side to avoid it being + // parsed as parenthesized expression: `a && (() => {})` + return true; + } + var operandPrecedence = ts.getExpressionPrecedence(emittedOperand); + switch (ts.compareValues(operandPrecedence, binaryOperatorPrecedence)) { + case -1 /* LessThan */: + // If the operand is the right side of a right-associative binary operation + // and is a yield expression, then we do not need parentheses. + if (!isLeftSideOfBinary + && binaryOperatorAssociativity === 1 /* Right */ + && operand.kind === 207 /* YieldExpression */) { + return false; + } + return true; + case 1 /* GreaterThan */: + return false; + case 0 /* EqualTo */: + if (isLeftSideOfBinary) { + // No need to parenthesize the left operand when the binary operator is + // left associative: + // (a*b)/x -> a*b/x + // (a**b)/x -> a**b/x + // + // Parentheses are needed for the left operand when the binary operator is + // right associative: + // (a/b)**x -> (a/b)**x + // (a**b)**x -> (a**b)**x + return binaryOperatorAssociativity === 1 /* Right */; + } + else { + if (ts.isBinaryExpression(emittedOperand) + && emittedOperand.operatorToken.kind === binaryOperator) { + // No need to parenthesize the right operand when the binary operator and + // operand are the same and one of the following: + // x*(a*b) => x*a*b + // x|(a|b) => x|a|b + // x&(a&b) => x&a&b + // x^(a^b) => x^a^b + if (operatorHasAssociativeProperty(binaryOperator)) { + return false; + } + // No need to parenthesize the right operand when the binary operator + // is plus (+) if both the left and right operands consist solely of either + // literals of the same kind or binary plus (+) expressions for literals of + // the same kind (recursively). + // "a"+(1+2) => "a"+(1+2) + // "a"+("b"+"c") => "a"+"b"+"c" + if (binaryOperator === 38 /* PlusToken */) { + var leftKind = leftOperand ? getLiteralKindOfBinaryPlusOperand(leftOperand) : 0 /* Unknown */; + if (ts.isLiteralKind(leftKind) && leftKind === getLiteralKindOfBinaryPlusOperand(emittedOperand)) { + return false; + } + } + } + // No need to parenthesize the right operand when the operand is right + // associative: + // x/(a**b) -> x/a**b + // x**(a**b) -> x**a**b + // + // Parentheses are needed for the right operand when the operand is left + // associative: + // x/(a*b) -> x/(a*b) + // x**(a/b) -> x**(a/b) + var operandAssociativity = ts.getExpressionAssociativity(emittedOperand); + return operandAssociativity === 0 /* Left */; + } + } + } + /** + * Determines whether a binary operator is mathematically associative. + * + * @param binaryOperator The binary operator. + */ + function operatorHasAssociativeProperty(binaryOperator) { + // The following operators are associative in JavaScript: + // (a*b)*c -> a*(b*c) -> a*b*c + // (a|b)|c -> a|(b|c) -> a|b|c + // (a&b)&c -> a&(b&c) -> a&b&c + // (a^b)^c -> a^(b^c) -> a^b^c + // + // While addition is associative in mathematics, JavaScript's `+` is not + // guaranteed to be associative as it is overloaded with string concatenation. + return binaryOperator === 40 /* AsteriskToken */ + || binaryOperator === 50 /* BarToken */ + || binaryOperator === 49 /* AmpersandToken */ + || binaryOperator === 51 /* CaretToken */; + } + /** + * This function determines whether an expression consists of a homogeneous set of + * literal expressions or binary plus expressions that all share the same literal kind. + * It is used to determine whether the right-hand operand of a binary plus expression can be + * emitted without parentheses. + */ + function getLiteralKindOfBinaryPlusOperand(node) { + node = ts.skipPartiallyEmittedExpressions(node); + if (ts.isLiteralKind(node.kind)) { + return node.kind; + } + if (node.kind === 204 /* BinaryExpression */ && node.operatorToken.kind === 38 /* PlusToken */) { + if (node.cachedLiteralKind !== undefined) { + return node.cachedLiteralKind; + } + var leftKind = getLiteralKindOfBinaryPlusOperand(node.left); + var literalKind = ts.isLiteralKind(leftKind) + && leftKind === getLiteralKindOfBinaryPlusOperand(node.right) + ? leftKind + : 0 /* Unknown */; + node.cachedLiteralKind = literalKind; + return literalKind; + } + return 0 /* Unknown */; + } + function parenthesizeForConditionalHead(condition) { + var conditionalPrecedence = ts.getOperatorPrecedence(205 /* ConditionalExpression */, 56 /* QuestionToken */); + var emittedCondition = ts.skipPartiallyEmittedExpressions(condition); + var conditionPrecedence = ts.getExpressionPrecedence(emittedCondition); + if (ts.compareValues(conditionPrecedence, conditionalPrecedence) === -1 /* LessThan */) { + return ts.createParen(condition); + } + return condition; + } + ts.parenthesizeForConditionalHead = parenthesizeForConditionalHead; + function parenthesizeSubexpressionOfConditionalExpression(e) { + // per ES grammar both 'whenTrue' and 'whenFalse' parts of conditional expression are assignment expressions + // so in case when comma expression is introduced as a part of previous transformations + // if should be wrapped in parens since comma operator has the lowest precedence + var emittedExpression = ts.skipPartiallyEmittedExpressions(e); + return isCommaSequence(emittedExpression) + ? ts.createParen(e) + : e; + } + ts.parenthesizeSubexpressionOfConditionalExpression = parenthesizeSubexpressionOfConditionalExpression; + /** + * [Per the spec](https://tc39.github.io/ecma262/#prod-ExportDeclaration), `export default` accepts _AssigmentExpression_ but + * has a lookahead restriction for `function`, `async function`, and `class`. + * + * Basically, that means we need to parenthesize in the following cases: + * + * - BinaryExpression of CommaToken + * - CommaList (synthetic list of multiple comma expressions) + * - FunctionExpression + * - ClassExpression + */ + function parenthesizeDefaultExpression(e) { + var check = ts.skipPartiallyEmittedExpressions(e); + var needsParens = isCommaSequence(check); + if (!needsParens) { + switch (getLeftmostExpression(check, /*stopAtCallExpression*/ false).kind) { + case 209 /* ClassExpression */: + case 196 /* FunctionExpression */: + needsParens = true; + } + } + return needsParens ? ts.createParen(e) : e; + } + ts.parenthesizeDefaultExpression = parenthesizeDefaultExpression; + /** + * Wraps an expression in parentheses if it is needed in order to use the expression + * as the expression of a NewExpression node. + * + * @param expression The Expression node. + */ + function parenthesizeForNew(expression) { + var leftmostExpr = getLeftmostExpression(expression, /*stopAtCallExpressions*/ true); + switch (leftmostExpr.kind) { + case 191 /* CallExpression */: + return ts.createParen(expression); + case 192 /* NewExpression */: + return !leftmostExpr.arguments + ? ts.createParen(expression) + : expression; + } + return parenthesizeForAccess(expression); + } + ts.parenthesizeForNew = parenthesizeForNew; + /** + * Wraps an expression in parentheses if it is needed in order to use the expression for + * property or element access. + * + * @param expr The expression node. + */ + function parenthesizeForAccess(expression) { + // isLeftHandSideExpression is almost the correct criterion for when it is not necessary + // to parenthesize the expression before a dot. The known exception is: + // + // NewExpression: + // new C.x -> not the same as (new C).x + // + var emittedExpression = ts.skipPartiallyEmittedExpressions(expression); + if (ts.isLeftHandSideExpression(emittedExpression) + && (emittedExpression.kind !== 192 /* NewExpression */ || emittedExpression.arguments)) { + return expression; + } + return ts.setTextRange(ts.createParen(expression), expression); + } + ts.parenthesizeForAccess = parenthesizeForAccess; + function parenthesizePostfixOperand(operand) { + return ts.isLeftHandSideExpression(operand) + ? operand + : ts.setTextRange(ts.createParen(operand), operand); + } + ts.parenthesizePostfixOperand = parenthesizePostfixOperand; + function parenthesizePrefixOperand(operand) { + return ts.isUnaryExpression(operand) + ? operand + : ts.setTextRange(ts.createParen(operand), operand); + } + ts.parenthesizePrefixOperand = parenthesizePrefixOperand; + function parenthesizeListElements(elements) { + var result; + for (var i = 0; i < elements.length; i++) { + var element = parenthesizeExpressionForList(elements[i]); + if (result !== undefined || element !== elements[i]) { + if (result === undefined) { + result = elements.slice(0, i); + } + result.push(element); + } + } + if (result !== undefined) { + return ts.setTextRange(ts.createNodeArray(result, elements.hasTrailingComma), elements); + } + return elements; + } + ts.parenthesizeListElements = parenthesizeListElements; + function parenthesizeExpressionForList(expression) { + var emittedExpression = ts.skipPartiallyEmittedExpressions(expression); + var expressionPrecedence = ts.getExpressionPrecedence(emittedExpression); + var commaPrecedence = ts.getOperatorPrecedence(204 /* BinaryExpression */, 27 /* CommaToken */); + return expressionPrecedence > commaPrecedence + ? expression + : ts.setTextRange(ts.createParen(expression), expression); + } + ts.parenthesizeExpressionForList = parenthesizeExpressionForList; + function parenthesizeExpressionForExpressionStatement(expression) { + var emittedExpression = ts.skipPartiallyEmittedExpressions(expression); + if (ts.isCallExpression(emittedExpression)) { + var callee = emittedExpression.expression; + var kind = ts.skipPartiallyEmittedExpressions(callee).kind; + if (kind === 196 /* FunctionExpression */ || kind === 197 /* ArrowFunction */) { + var mutableCall = ts.getMutableClone(emittedExpression); + mutableCall.expression = ts.setTextRange(ts.createParen(callee), callee); + return recreateOuterExpressions(expression, mutableCall, 4 /* PartiallyEmittedExpressions */); + } + } + var leftmostExpressionKind = getLeftmostExpression(emittedExpression, /*stopAtCallExpressions*/ false).kind; + if (leftmostExpressionKind === 188 /* ObjectLiteralExpression */ || leftmostExpressionKind === 196 /* FunctionExpression */) { + return ts.setTextRange(ts.createParen(expression), expression); + } + return expression; + } + ts.parenthesizeExpressionForExpressionStatement = parenthesizeExpressionForExpressionStatement; + function parenthesizeConditionalTypeMember(member) { + return member.kind === 175 /* ConditionalType */ ? ts.createParenthesizedType(member) : member; + } + ts.parenthesizeConditionalTypeMember = parenthesizeConditionalTypeMember; + function parenthesizeElementTypeMember(member) { + switch (member.kind) { + case 173 /* UnionType */: + case 174 /* IntersectionType */: + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + return ts.createParenthesizedType(member); + } + return parenthesizeConditionalTypeMember(member); + } + ts.parenthesizeElementTypeMember = parenthesizeElementTypeMember; + function parenthesizeArrayTypeMember(member) { + switch (member.kind) { + case 167 /* TypeQuery */: + case 179 /* TypeOperator */: + case 176 /* InferType */: + return ts.createParenthesizedType(member); + } + return parenthesizeElementTypeMember(member); + } + ts.parenthesizeArrayTypeMember = parenthesizeArrayTypeMember; + function parenthesizeElementTypeMembers(members) { + return ts.createNodeArray(ts.sameMap(members, parenthesizeElementTypeMember)); + } + ts.parenthesizeElementTypeMembers = parenthesizeElementTypeMembers; + function parenthesizeTypeParameters(typeParameters) { + if (ts.some(typeParameters)) { + var params = []; + for (var i = 0; i < typeParameters.length; ++i) { + var entry = typeParameters[i]; + params.push(i === 0 && ts.isFunctionOrConstructorTypeNode(entry) && entry.typeParameters ? + ts.createParenthesizedType(entry) : + entry); + } + return ts.createNodeArray(params); + } + } + ts.parenthesizeTypeParameters = parenthesizeTypeParameters; + function getLeftmostExpression(node, stopAtCallExpressions) { + while (true) { + switch (node.kind) { + case 203 /* PostfixUnaryExpression */: + node = node.operand; + continue; + case 204 /* BinaryExpression */: + node = node.left; + continue; + case 205 /* ConditionalExpression */: + node = node.condition; + continue; + case 193 /* TaggedTemplateExpression */: + node = node.tag; + continue; + case 191 /* CallExpression */: + if (stopAtCallExpressions) { + return node; + } + // falls through + case 212 /* AsExpression */: + case 190 /* ElementAccessExpression */: + case 189 /* PropertyAccessExpression */: + case 213 /* NonNullExpression */: + case 308 /* PartiallyEmittedExpression */: + node = node.expression; + continue; + } + return node; + } + } + function parenthesizeConciseBody(body) { + if (!ts.isBlock(body) && (isCommaSequence(body) || getLeftmostExpression(body, /*stopAtCallExpressions*/ false).kind === 188 /* ObjectLiteralExpression */)) { + return ts.setTextRange(ts.createParen(body), body); + } + return body; + } + ts.parenthesizeConciseBody = parenthesizeConciseBody; + function isCommaSequence(node) { + return node.kind === 204 /* BinaryExpression */ && node.operatorToken.kind === 27 /* CommaToken */ || + node.kind === 309 /* CommaListExpression */; + } + ts.isCommaSequence = isCommaSequence; + var OuterExpressionKinds; + (function (OuterExpressionKinds) { + OuterExpressionKinds[OuterExpressionKinds["Parentheses"] = 1] = "Parentheses"; + OuterExpressionKinds[OuterExpressionKinds["Assertions"] = 2] = "Assertions"; + OuterExpressionKinds[OuterExpressionKinds["PartiallyEmittedExpressions"] = 4] = "PartiallyEmittedExpressions"; + OuterExpressionKinds[OuterExpressionKinds["All"] = 7] = "All"; + })(OuterExpressionKinds = ts.OuterExpressionKinds || (ts.OuterExpressionKinds = {})); + function isOuterExpression(node, kinds) { + if (kinds === void 0) { kinds = 7 /* All */; } + switch (node.kind) { + case 195 /* ParenthesizedExpression */: + return (kinds & 1 /* Parentheses */) !== 0; + case 194 /* TypeAssertionExpression */: + case 212 /* AsExpression */: + case 213 /* NonNullExpression */: + return (kinds & 2 /* Assertions */) !== 0; + case 308 /* PartiallyEmittedExpression */: + return (kinds & 4 /* PartiallyEmittedExpressions */) !== 0; + } + return false; + } + ts.isOuterExpression = isOuterExpression; + function skipOuterExpressions(node, kinds) { + if (kinds === void 0) { kinds = 7 /* All */; } + var previousNode; + do { + previousNode = node; + if (kinds & 1 /* Parentheses */) { + node = ts.skipParentheses(node); + } + if (kinds & 2 /* Assertions */) { + node = skipAssertions(node); + } + if (kinds & 4 /* PartiallyEmittedExpressions */) { + node = ts.skipPartiallyEmittedExpressions(node); + } + } while (previousNode !== node); + return node; + } + ts.skipOuterExpressions = skipOuterExpressions; + function skipAssertions(node) { + while (ts.isAssertionExpression(node) || node.kind === 213 /* NonNullExpression */) { + node = node.expression; + } + return node; + } + ts.skipAssertions = skipAssertions; + function updateOuterExpression(outerExpression, expression) { + switch (outerExpression.kind) { + case 195 /* ParenthesizedExpression */: return ts.updateParen(outerExpression, expression); + case 194 /* TypeAssertionExpression */: return ts.updateTypeAssertion(outerExpression, outerExpression.type, expression); + case 212 /* AsExpression */: return ts.updateAsExpression(outerExpression, expression, outerExpression.type); + case 213 /* NonNullExpression */: return ts.updateNonNullExpression(outerExpression, expression); + case 308 /* PartiallyEmittedExpression */: return ts.updatePartiallyEmittedExpression(outerExpression, expression); + } + } + /** + * Determines whether a node is a parenthesized expression that can be ignored when recreating outer expressions. + * + * A parenthesized expression can be ignored when all of the following are true: + * + * - It's `pos` and `end` are not -1 + * - It does not have a custom source map range + * - It does not have a custom comment range + * - It does not have synthetic leading or trailing comments + * + * If an outermost parenthesized expression is ignored, but the containing expression requires a parentheses around + * the expression to maintain precedence, a new parenthesized expression should be created automatically when + * the containing expression is created/updated. + */ + function isIgnorableParen(node) { + return node.kind === 195 /* ParenthesizedExpression */ + && ts.nodeIsSynthesized(node) + && ts.nodeIsSynthesized(ts.getSourceMapRange(node)) + && ts.nodeIsSynthesized(ts.getCommentRange(node)) + && !ts.some(ts.getSyntheticLeadingComments(node)) + && !ts.some(ts.getSyntheticTrailingComments(node)); + } + function recreateOuterExpressions(outerExpression, innerExpression, kinds) { + if (kinds === void 0) { kinds = 7 /* All */; } + if (outerExpression && isOuterExpression(outerExpression, kinds) && !isIgnorableParen(outerExpression)) { + return updateOuterExpression(outerExpression, recreateOuterExpressions(outerExpression.expression, innerExpression)); + } + return innerExpression; + } + ts.recreateOuterExpressions = recreateOuterExpressions; + function startOnNewLine(node) { + return ts.setStartsOnNewLine(node, /*newLine*/ true); + } + ts.startOnNewLine = startOnNewLine; + function getExternalHelpersModuleName(node) { + var parseNode = ts.getOriginalNode(node, ts.isSourceFile); + var emitNode = parseNode && parseNode.emitNode; + return emitNode && emitNode.externalHelpersModuleName; + } + ts.getExternalHelpersModuleName = getExternalHelpersModuleName; + function getOrCreateExternalHelpersModuleNameIfNeeded(node, compilerOptions, hasExportStarsToExportValues, hasImportStarOrImportDefault) { + if (compilerOptions.importHelpers && ts.isEffectiveExternalModule(node, compilerOptions)) { + var externalHelpersModuleName = getExternalHelpersModuleName(node); + if (externalHelpersModuleName) { + return externalHelpersModuleName; + } + var moduleKind = ts.getEmitModuleKind(compilerOptions); + var create = (hasExportStarsToExportValues || (compilerOptions.esModuleInterop && hasImportStarOrImportDefault)) + && moduleKind !== ts.ModuleKind.System + && moduleKind !== ts.ModuleKind.ES2015 + && moduleKind !== ts.ModuleKind.ESNext; + if (!create) { + var helpers = ts.getEmitHelpers(node); + if (helpers) { + for (var _i = 0, helpers_2 = helpers; _i < helpers_2.length; _i++) { + var helper = helpers_2[_i]; + if (!helper.scoped) { + create = true; + break; + } + } + } + } + if (create) { + var parseNode = ts.getOriginalNode(node, ts.isSourceFile); + var emitNode = ts.getOrCreateEmitNode(parseNode); + return emitNode.externalHelpersModuleName || (emitNode.externalHelpersModuleName = ts.createUniqueName(ts.externalHelpersModuleNameText)); + } + } + } + ts.getOrCreateExternalHelpersModuleNameIfNeeded = getOrCreateExternalHelpersModuleNameIfNeeded; + /** + * Get the name of that target module from an import or export declaration + */ + function getLocalNameForExternalImport(node, sourceFile) { + var namespaceDeclaration = ts.getNamespaceDeclarationNode(node); + if (namespaceDeclaration && !ts.isDefaultImport(node)) { + var name = namespaceDeclaration.name; + return ts.isGeneratedIdentifier(name) ? name : ts.createIdentifier(ts.getSourceTextOfNodeFromSourceFile(sourceFile, name) || ts.idText(name)); + } + if (node.kind === 249 /* ImportDeclaration */ && node.importClause) { + return ts.getGeneratedNameForNode(node); + } + if (node.kind === 255 /* ExportDeclaration */ && node.moduleSpecifier) { + return ts.getGeneratedNameForNode(node); + } + return undefined; + } + ts.getLocalNameForExternalImport = getLocalNameForExternalImport; + /** + * Get the name of a target module from an import/export declaration as should be written in the emitted output. + * The emitted output name can be different from the input if: + * 1. The module has a /// + * 2. --out or --outFile is used, making the name relative to the rootDir + * 3- The containing SourceFile has an entry in renamedDependencies for the import as requested by some module loaders (e.g. System). + * Otherwise, a new StringLiteral node representing the module name will be returned. + */ + function getExternalModuleNameLiteral(importNode, sourceFile, host, resolver, compilerOptions) { + var moduleName = ts.getExternalModuleName(importNode); // TODO: GH#18217 + if (moduleName.kind === 10 /* StringLiteral */) { + return tryGetModuleNameFromDeclaration(importNode, host, resolver, compilerOptions) + || tryRenameExternalModule(moduleName, sourceFile) + || ts.getSynthesizedClone(moduleName); + } + return undefined; + } + ts.getExternalModuleNameLiteral = getExternalModuleNameLiteral; + /** + * Some bundlers (SystemJS builder) sometimes want to rename dependencies. + * Here we check if alternative name was provided for a given moduleName and return it if possible. + */ + function tryRenameExternalModule(moduleName, sourceFile) { + var rename = sourceFile.renamedDependencies && sourceFile.renamedDependencies.get(moduleName.text); + return rename && ts.createLiteral(rename); + } + /** + * Get the name of a module as should be written in the emitted output. + * The emitted output name can be different from the input if: + * 1. The module has a /// + * 2. --out or --outFile is used, making the name relative to the rootDir + * Otherwise, a new StringLiteral node representing the module name will be returned. + */ + function tryGetModuleNameFromFile(file, host, options) { + if (!file) { + return undefined; + } + if (file.moduleName) { + return ts.createLiteral(file.moduleName); + } + if (!file.isDeclarationFile && (options.out || options.outFile)) { + return ts.createLiteral(ts.getExternalModuleNameFromPath(host, file.fileName)); + } + return undefined; + } + ts.tryGetModuleNameFromFile = tryGetModuleNameFromFile; + function tryGetModuleNameFromDeclaration(declaration, host, resolver, compilerOptions) { + return tryGetModuleNameFromFile(resolver.getExternalModuleFileFromDeclaration(declaration), host, compilerOptions); + } + /** + * Gets the initializer of an BindingOrAssignmentElement. + */ + function getInitializerOfBindingOrAssignmentElement(bindingElement) { + if (ts.isDeclarationBindingElement(bindingElement)) { + // `1` in `let { a = 1 } = ...` + // `1` in `let { a: b = 1 } = ...` + // `1` in `let { a: {b} = 1 } = ...` + // `1` in `let { a: [b] = 1 } = ...` + // `1` in `let [a = 1] = ...` + // `1` in `let [{a} = 1] = ...` + // `1` in `let [[a] = 1] = ...` + return bindingElement.initializer; + } + if (ts.isPropertyAssignment(bindingElement)) { + // `1` in `({ a: b = 1 } = ...)` + // `1` in `({ a: {b} = 1 } = ...)` + // `1` in `({ a: [b] = 1 } = ...)` + var initializer = bindingElement.initializer; + return ts.isAssignmentExpression(initializer, /*excludeCompoundAssignment*/ true) + ? initializer.right + : undefined; + } + if (ts.isShorthandPropertyAssignment(bindingElement)) { + // `1` in `({ a = 1 } = ...)` + return bindingElement.objectAssignmentInitializer; + } + if (ts.isAssignmentExpression(bindingElement, /*excludeCompoundAssignment*/ true)) { + // `1` in `[a = 1] = ...` + // `1` in `[{a} = 1] = ...` + // `1` in `[[a] = 1] = ...` + return bindingElement.right; + } + if (ts.isSpreadElement(bindingElement)) { + // Recovery consistent with existing emit. + return getInitializerOfBindingOrAssignmentElement(bindingElement.expression); + } + } + ts.getInitializerOfBindingOrAssignmentElement = getInitializerOfBindingOrAssignmentElement; + /** + * Gets the name of an BindingOrAssignmentElement. + */ + function getTargetOfBindingOrAssignmentElement(bindingElement) { + if (ts.isDeclarationBindingElement(bindingElement)) { + // `a` in `let { a } = ...` + // `a` in `let { a = 1 } = ...` + // `b` in `let { a: b } = ...` + // `b` in `let { a: b = 1 } = ...` + // `a` in `let { ...a } = ...` + // `{b}` in `let { a: {b} } = ...` + // `{b}` in `let { a: {b} = 1 } = ...` + // `[b]` in `let { a: [b] } = ...` + // `[b]` in `let { a: [b] = 1 } = ...` + // `a` in `let [a] = ...` + // `a` in `let [a = 1] = ...` + // `a` in `let [...a] = ...` + // `{a}` in `let [{a}] = ...` + // `{a}` in `let [{a} = 1] = ...` + // `[a]` in `let [[a]] = ...` + // `[a]` in `let [[a] = 1] = ...` + return bindingElement.name; + } + if (ts.isObjectLiteralElementLike(bindingElement)) { + switch (bindingElement.kind) { + case 275 /* PropertyAssignment */: + // `b` in `({ a: b } = ...)` + // `b` in `({ a: b = 1 } = ...)` + // `{b}` in `({ a: {b} } = ...)` + // `{b}` in `({ a: {b} = 1 } = ...)` + // `[b]` in `({ a: [b] } = ...)` + // `[b]` in `({ a: [b] = 1 } = ...)` + // `b.c` in `({ a: b.c } = ...)` + // `b.c` in `({ a: b.c = 1 } = ...)` + // `b[0]` in `({ a: b[0] } = ...)` + // `b[0]` in `({ a: b[0] = 1 } = ...)` + return getTargetOfBindingOrAssignmentElement(bindingElement.initializer); + case 276 /* ShorthandPropertyAssignment */: + // `a` in `({ a } = ...)` + // `a` in `({ a = 1 } = ...)` + return bindingElement.name; + case 277 /* SpreadAssignment */: + // `a` in `({ ...a } = ...)` + return getTargetOfBindingOrAssignmentElement(bindingElement.expression); + } + // no target + return undefined; + } + if (ts.isAssignmentExpression(bindingElement, /*excludeCompoundAssignment*/ true)) { + // `a` in `[a = 1] = ...` + // `{a}` in `[{a} = 1] = ...` + // `[a]` in `[[a] = 1] = ...` + // `a.b` in `[a.b = 1] = ...` + // `a[0]` in `[a[0] = 1] = ...` + return getTargetOfBindingOrAssignmentElement(bindingElement.left); + } + if (ts.isSpreadElement(bindingElement)) { + // `a` in `[...a] = ...` + return getTargetOfBindingOrAssignmentElement(bindingElement.expression); + } + // `a` in `[a] = ...` + // `{a}` in `[{a}] = ...` + // `[a]` in `[[a]] = ...` + // `a.b` in `[a.b] = ...` + // `a[0]` in `[a[0]] = ...` + return bindingElement; + } + ts.getTargetOfBindingOrAssignmentElement = getTargetOfBindingOrAssignmentElement; + /** + * Determines whether an BindingOrAssignmentElement is a rest element. + */ + function getRestIndicatorOfBindingOrAssignmentElement(bindingElement) { + switch (bindingElement.kind) { + case 151 /* Parameter */: + case 186 /* BindingElement */: + // `...` in `let [...a] = ...` + return bindingElement.dotDotDotToken; + case 208 /* SpreadElement */: + case 277 /* SpreadAssignment */: + // `...` in `[...a] = ...` + return bindingElement; + } + return undefined; + } + ts.getRestIndicatorOfBindingOrAssignmentElement = getRestIndicatorOfBindingOrAssignmentElement; + /** + * Gets the property name of a BindingOrAssignmentElement + */ + function getPropertyNameOfBindingOrAssignmentElement(bindingElement) { + switch (bindingElement.kind) { + case 186 /* BindingElement */: + // `a` in `let { a: b } = ...` + // `[a]` in `let { [a]: b } = ...` + // `"a"` in `let { "a": b } = ...` + // `1` in `let { 1: b } = ...` + if (bindingElement.propertyName) { + var propertyName = bindingElement.propertyName; + return ts.isComputedPropertyName(propertyName) && isStringOrNumericLiteral(propertyName.expression) + ? propertyName.expression + : propertyName; + } + break; + case 275 /* PropertyAssignment */: + // `a` in `({ a: b } = ...)` + // `[a]` in `({ [a]: b } = ...)` + // `"a"` in `({ "a": b } = ...)` + // `1` in `({ 1: b } = ...)` + if (bindingElement.name) { + var propertyName = bindingElement.name; + return ts.isComputedPropertyName(propertyName) && isStringOrNumericLiteral(propertyName.expression) + ? propertyName.expression + : propertyName; + } + break; + case 277 /* SpreadAssignment */: + // `a` in `({ ...a } = ...)` + return bindingElement.name; + } + var target = getTargetOfBindingOrAssignmentElement(bindingElement); + if (target && ts.isPropertyName(target)) { + return ts.isComputedPropertyName(target) && isStringOrNumericLiteral(target.expression) + ? target.expression + : target; + } + ts.Debug.fail("Invalid property name for binding element."); + } + ts.getPropertyNameOfBindingOrAssignmentElement = getPropertyNameOfBindingOrAssignmentElement; + function isStringOrNumericLiteral(node) { + var kind = node.kind; + return kind === 10 /* StringLiteral */ + || kind === 8 /* NumericLiteral */; + } + /** + * Gets the elements of a BindingOrAssignmentPattern + */ + function getElementsOfBindingOrAssignmentPattern(name) { + switch (name.kind) { + case 184 /* ObjectBindingPattern */: + case 185 /* ArrayBindingPattern */: + case 187 /* ArrayLiteralExpression */: + // `a` in `{a}` + // `a` in `[a]` + return name.elements; + case 188 /* ObjectLiteralExpression */: + // `a` in `{a}` + return name.properties; + } + } + ts.getElementsOfBindingOrAssignmentPattern = getElementsOfBindingOrAssignmentPattern; + function convertToArrayAssignmentElement(element) { + if (ts.isBindingElement(element)) { + if (element.dotDotDotToken) { + ts.Debug.assertNode(element.name, ts.isIdentifier); + return ts.setOriginalNode(ts.setTextRange(ts.createSpread(element.name), element), element); + } + var expression = convertToAssignmentElementTarget(element.name); + return element.initializer + ? ts.setOriginalNode(ts.setTextRange(ts.createAssignment(expression, element.initializer), element), element) + : expression; + } + ts.Debug.assertNode(element, ts.isExpression); + return element; + } + ts.convertToArrayAssignmentElement = convertToArrayAssignmentElement; + function convertToObjectAssignmentElement(element) { + if (ts.isBindingElement(element)) { + if (element.dotDotDotToken) { + ts.Debug.assertNode(element.name, ts.isIdentifier); + return ts.setOriginalNode(ts.setTextRange(ts.createSpreadAssignment(element.name), element), element); + } + if (element.propertyName) { + var expression = convertToAssignmentElementTarget(element.name); + return ts.setOriginalNode(ts.setTextRange(ts.createPropertyAssignment(element.propertyName, element.initializer ? ts.createAssignment(expression, element.initializer) : expression), element), element); + } + ts.Debug.assertNode(element.name, ts.isIdentifier); + return ts.setOriginalNode(ts.setTextRange(ts.createShorthandPropertyAssignment(element.name, element.initializer), element), element); + } + ts.Debug.assertNode(element, ts.isObjectLiteralElementLike); + return element; + } + ts.convertToObjectAssignmentElement = convertToObjectAssignmentElement; + function convertToAssignmentPattern(node) { + switch (node.kind) { + case 185 /* ArrayBindingPattern */: + case 187 /* ArrayLiteralExpression */: + return convertToArrayAssignmentPattern(node); + case 184 /* ObjectBindingPattern */: + case 188 /* ObjectLiteralExpression */: + return convertToObjectAssignmentPattern(node); + } + } + ts.convertToAssignmentPattern = convertToAssignmentPattern; + function convertToObjectAssignmentPattern(node) { + if (ts.isObjectBindingPattern(node)) { + return ts.setOriginalNode(ts.setTextRange(ts.createObjectLiteral(ts.map(node.elements, convertToObjectAssignmentElement)), node), node); + } + ts.Debug.assertNode(node, ts.isObjectLiteralExpression); + return node; + } + ts.convertToObjectAssignmentPattern = convertToObjectAssignmentPattern; + function convertToArrayAssignmentPattern(node) { + if (ts.isArrayBindingPattern(node)) { + return ts.setOriginalNode(ts.setTextRange(ts.createArrayLiteral(ts.map(node.elements, convertToArrayAssignmentElement)), node), node); + } + ts.Debug.assertNode(node, ts.isArrayLiteralExpression); + return node; + } + ts.convertToArrayAssignmentPattern = convertToArrayAssignmentPattern; + function convertToAssignmentElementTarget(node) { + if (ts.isBindingPattern(node)) { + return convertToAssignmentPattern(node); + } + ts.Debug.assertNode(node, ts.isExpression); + return node; + } + ts.convertToAssignmentElementTarget = convertToAssignmentElementTarget; +})(ts || (ts = {})); +var ts; +(function (ts) { + var isTypeNodeOrTypeParameterDeclaration = ts.or(ts.isTypeNode, ts.isTypeParameterDeclaration); + function visitNode(node, visitor, test, lift) { + if (node === undefined || visitor === undefined) { + return node; + } + ts.aggregateTransformFlags(node); + var visited = visitor(node); + if (visited === node) { + return node; + } + var visitedNode; + if (visited === undefined) { + return undefined; + } + else if (ts.isArray(visited)) { + visitedNode = (lift || extractSingleNode)(visited); + } + else { + visitedNode = visited; + } + ts.Debug.assertNode(visitedNode, test); + ts.aggregateTransformFlags(visitedNode); + return visitedNode; + } + ts.visitNode = visitNode; + /** + * Visits a NodeArray using the supplied visitor, possibly returning a new NodeArray in its place. + * + * @param nodes The NodeArray to visit. + * @param visitor The callback used to visit a Node. + * @param test A node test to execute for each node. + * @param start An optional value indicating the starting offset at which to start visiting. + * @param count An optional value indicating the maximum number of nodes to visit. + */ + function visitNodes(nodes, visitor, test, start, count) { + if (nodes === undefined || visitor === undefined) { + return nodes; + } + var updated; + // Ensure start and count have valid values + var length = nodes.length; + if (start === undefined || start < 0) { + start = 0; + } + if (count === undefined || count > length - start) { + count = length - start; + } + if (start > 0 || count < length) { + // If we are not visiting all of the original nodes, we must always create a new array. + // Since this is a fragment of a node array, we do not copy over the previous location + // and will only copy over `hasTrailingComma` if we are including the last element. + updated = ts.createNodeArray([], /*hasTrailingComma*/ nodes.hasTrailingComma && start + count === length); + } + // Visit each original node. + for (var i = 0; i < count; i++) { + var node = nodes[i + start]; + ts.aggregateTransformFlags(node); + var visited = node !== undefined ? visitor(node) : undefined; + if (updated !== undefined || visited === undefined || visited !== node) { + if (updated === undefined) { + // Ensure we have a copy of `nodes`, up to the current index. + updated = ts.createNodeArray(nodes.slice(0, i), nodes.hasTrailingComma); + ts.setTextRange(updated, nodes); + } + if (visited) { + if (ts.isArray(visited)) { + for (var _i = 0, visited_1 = visited; _i < visited_1.length; _i++) { + var visitedNode = visited_1[_i]; + ts.Debug.assertNode(visitedNode, test); + ts.aggregateTransformFlags(visitedNode); + updated.push(visitedNode); + } + } + else { + ts.Debug.assertNode(visited, test); + ts.aggregateTransformFlags(visited); + updated.push(visited); + } + } + } + } + return updated || nodes; + } + ts.visitNodes = visitNodes; + /** + * Starts a new lexical environment and visits a statement list, ending the lexical environment + * and merging hoisted declarations upon completion. + */ + function visitLexicalEnvironment(statements, visitor, context, start, ensureUseStrict) { + context.startLexicalEnvironment(); + statements = visitNodes(statements, visitor, ts.isStatement, start); + if (ensureUseStrict && !ts.startsWithUseStrict(statements)) { + statements = ts.setTextRange(ts.createNodeArray([ts.createExpressionStatement(ts.createLiteral("use strict"))].concat(statements)), statements); + } + var declarations = context.endLexicalEnvironment(); + return ts.setTextRange(ts.createNodeArray(ts.concatenate(declarations, statements)), statements); + } + ts.visitLexicalEnvironment = visitLexicalEnvironment; + /** + * Starts a new lexical environment and visits a parameter list, suspending the lexical + * environment upon completion. + */ + function visitParameterList(nodes, visitor, context, nodesVisitor) { + if (nodesVisitor === void 0) { nodesVisitor = visitNodes; } + context.startLexicalEnvironment(); + var updated = nodesVisitor(nodes, visitor, ts.isParameterDeclaration); + context.suspendLexicalEnvironment(); + return updated; + } + ts.visitParameterList = visitParameterList; + function visitFunctionBody(node, visitor, context) { + context.resumeLexicalEnvironment(); + var updated = visitNode(node, visitor, ts.isConciseBody); + var declarations = context.endLexicalEnvironment(); + if (ts.some(declarations)) { + var block = ts.convertToFunctionBody(updated); + var statements = ts.mergeLexicalEnvironment(block.statements, declarations); + return ts.updateBlock(block, statements); + } + return updated; + } + ts.visitFunctionBody = visitFunctionBody; + function visitEachChild(node, visitor, context, nodesVisitor, tokenVisitor) { + if (nodesVisitor === void 0) { nodesVisitor = visitNodes; } + if (node === undefined) { + return undefined; + } + var kind = node.kind; + // No need to visit nodes with no children. + if ((kind > 0 /* FirstToken */ && kind <= 147 /* LastToken */) || kind === 178 /* ThisType */) { + return node; + } + switch (kind) { + // Names + case 72 /* Identifier */: + return ts.updateIdentifier(node, nodesVisitor(node.typeArguments, visitor, isTypeNodeOrTypeParameterDeclaration)); + case 148 /* QualifiedName */: + return ts.updateQualifiedName(node, visitNode(node.left, visitor, ts.isEntityName), visitNode(node.right, visitor, ts.isIdentifier)); + case 149 /* ComputedPropertyName */: + return ts.updateComputedPropertyName(node, visitNode(node.expression, visitor, ts.isExpression)); + // Signature elements + case 150 /* TypeParameter */: + return ts.updateTypeParameterDeclaration(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.constraint, visitor, ts.isTypeNode), visitNode(node.default, visitor, ts.isTypeNode)); + case 151 /* Parameter */: + return ts.updateParameter(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.dotDotDotToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isBindingName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); + case 152 /* Decorator */: + return ts.updateDecorator(node, visitNode(node.expression, visitor, ts.isExpression)); + // Type elements + case 153 /* PropertySignature */: + return ts.updatePropertySignature(node, nodesVisitor(node.modifiers, visitor, ts.isToken), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); + case 154 /* PropertyDeclaration */: + return ts.updateProperty(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); + case 155 /* MethodSignature */: + return ts.updateMethodSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken)); + case 156 /* MethodDeclaration */: + return ts.updateMethod(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); + case 157 /* Constructor */: + return ts.updateConstructor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context)); + case 158 /* GetAccessor */: + return ts.updateGetAccessor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); + case 159 /* SetAccessor */: + return ts.updateSetAccessor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context)); + case 160 /* CallSignature */: + return ts.updateCallSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); + case 161 /* ConstructSignature */: + return ts.updateConstructSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); + case 162 /* IndexSignature */: + return ts.updateIndexSignature(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); + // Types + case 163 /* TypePredicate */: + return ts.updateTypePredicateNode(node, visitNode(node.parameterName, visitor), visitNode(node.type, visitor, ts.isTypeNode)); + case 164 /* TypeReference */: + return ts.updateTypeReferenceNode(node, visitNode(node.typeName, visitor, ts.isEntityName), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode)); + case 165 /* FunctionType */: + return ts.updateFunctionTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); + case 166 /* ConstructorType */: + return ts.updateConstructorTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); + case 167 /* TypeQuery */: + return ts.updateTypeQueryNode(node, visitNode(node.exprName, visitor, ts.isEntityName)); + case 168 /* TypeLiteral */: + return ts.updateTypeLiteralNode(node, nodesVisitor(node.members, visitor, ts.isTypeElement)); + case 169 /* ArrayType */: + return ts.updateArrayTypeNode(node, visitNode(node.elementType, visitor, ts.isTypeNode)); + case 170 /* TupleType */: + return ts.updateTupleTypeNode(node, nodesVisitor(node.elementTypes, visitor, ts.isTypeNode)); + case 171 /* OptionalType */: + return ts.updateOptionalTypeNode(node, visitNode(node.type, visitor, ts.isTypeNode)); + case 172 /* RestType */: + return ts.updateRestTypeNode(node, visitNode(node.type, visitor, ts.isTypeNode)); + case 173 /* UnionType */: + return ts.updateUnionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode)); + case 174 /* IntersectionType */: + return ts.updateIntersectionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode)); + case 175 /* ConditionalType */: + return ts.updateConditionalTypeNode(node, visitNode(node.checkType, visitor, ts.isTypeNode), visitNode(node.extendsType, visitor, ts.isTypeNode), visitNode(node.trueType, visitor, ts.isTypeNode), visitNode(node.falseType, visitor, ts.isTypeNode)); + case 176 /* InferType */: + return ts.updateInferTypeNode(node, visitNode(node.typeParameter, visitor, ts.isTypeParameterDeclaration)); + case 183 /* ImportType */: + return ts.updateImportTypeNode(node, visitNode(node.argument, visitor, ts.isTypeNode), visitNode(node.qualifier, visitor, ts.isEntityName), visitNodes(node.typeArguments, visitor, ts.isTypeNode), node.isTypeOf); + case 177 /* ParenthesizedType */: + return ts.updateParenthesizedType(node, visitNode(node.type, visitor, ts.isTypeNode)); + case 179 /* TypeOperator */: + return ts.updateTypeOperatorNode(node, visitNode(node.type, visitor, ts.isTypeNode)); + case 180 /* IndexedAccessType */: + return ts.updateIndexedAccessTypeNode(node, visitNode(node.objectType, visitor, ts.isTypeNode), visitNode(node.indexType, visitor, ts.isTypeNode)); + case 181 /* MappedType */: + return ts.updateMappedTypeNode(node, visitNode(node.readonlyToken, tokenVisitor, ts.isToken), visitNode(node.typeParameter, visitor, ts.isTypeParameterDeclaration), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode)); + case 182 /* LiteralType */: + return ts.updateLiteralTypeNode(node, visitNode(node.literal, visitor, ts.isExpression)); + // Binding patterns + case 184 /* ObjectBindingPattern */: + return ts.updateObjectBindingPattern(node, nodesVisitor(node.elements, visitor, ts.isBindingElement)); + case 185 /* ArrayBindingPattern */: + return ts.updateArrayBindingPattern(node, nodesVisitor(node.elements, visitor, ts.isArrayBindingElement)); + case 186 /* BindingElement */: + return ts.updateBindingElement(node, visitNode(node.dotDotDotToken, tokenVisitor, ts.isToken), visitNode(node.propertyName, visitor, ts.isPropertyName), visitNode(node.name, visitor, ts.isBindingName), visitNode(node.initializer, visitor, ts.isExpression)); + // Expression + case 187 /* ArrayLiteralExpression */: + return ts.updateArrayLiteral(node, nodesVisitor(node.elements, visitor, ts.isExpression)); + case 188 /* ObjectLiteralExpression */: + return ts.updateObjectLiteral(node, nodesVisitor(node.properties, visitor, ts.isObjectLiteralElementLike)); + case 189 /* PropertyAccessExpression */: + return ts.updatePropertyAccess(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.name, visitor, ts.isIdentifier)); + case 190 /* ElementAccessExpression */: + return ts.updateElementAccess(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.argumentExpression, visitor, ts.isExpression)); + case 191 /* CallExpression */: + return ts.updateCall(node, visitNode(node.expression, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression)); + case 192 /* NewExpression */: + return ts.updateNew(node, visitNode(node.expression, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression)); + case 193 /* TaggedTemplateExpression */: + return ts.updateTaggedTemplate(node, visitNode(node.tag, visitor, ts.isExpression), visitNodes(node.typeArguments, visitor, ts.isExpression), visitNode(node.template, visitor, ts.isTemplateLiteral)); + case 194 /* TypeAssertionExpression */: + return ts.updateTypeAssertion(node, visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.expression, visitor, ts.isExpression)); + case 195 /* ParenthesizedExpression */: + return ts.updateParen(node, visitNode(node.expression, visitor, ts.isExpression)); + case 196 /* FunctionExpression */: + return ts.updateFunctionExpression(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); + case 197 /* ArrowFunction */: + return ts.updateArrowFunction(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.equalsGreaterThanToken, visitor, ts.isToken), visitFunctionBody(node.body, visitor, context)); + case 198 /* DeleteExpression */: + return ts.updateDelete(node, visitNode(node.expression, visitor, ts.isExpression)); + case 199 /* TypeOfExpression */: + return ts.updateTypeOf(node, visitNode(node.expression, visitor, ts.isExpression)); + case 200 /* VoidExpression */: + return ts.updateVoid(node, visitNode(node.expression, visitor, ts.isExpression)); + case 201 /* AwaitExpression */: + return ts.updateAwait(node, visitNode(node.expression, visitor, ts.isExpression)); + case 202 /* PrefixUnaryExpression */: + return ts.updatePrefix(node, visitNode(node.operand, visitor, ts.isExpression)); + case 203 /* PostfixUnaryExpression */: + return ts.updatePostfix(node, visitNode(node.operand, visitor, ts.isExpression)); + case 204 /* BinaryExpression */: + return ts.updateBinary(node, visitNode(node.left, visitor, ts.isExpression), visitNode(node.right, visitor, ts.isExpression), visitNode(node.operatorToken, visitor, ts.isToken)); + case 205 /* ConditionalExpression */: + return ts.updateConditional(node, visitNode(node.condition, visitor, ts.isExpression), visitNode(node.questionToken, visitor, ts.isToken), visitNode(node.whenTrue, visitor, ts.isExpression), visitNode(node.colonToken, visitor, ts.isToken), visitNode(node.whenFalse, visitor, ts.isExpression)); + case 206 /* TemplateExpression */: + return ts.updateTemplateExpression(node, visitNode(node.head, visitor, ts.isTemplateHead), nodesVisitor(node.templateSpans, visitor, ts.isTemplateSpan)); + case 207 /* YieldExpression */: + return ts.updateYield(node, visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.expression, visitor, ts.isExpression)); + case 208 /* SpreadElement */: + return ts.updateSpread(node, visitNode(node.expression, visitor, ts.isExpression)); + case 209 /* ClassExpression */: + return ts.updateClassExpression(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement)); + case 211 /* ExpressionWithTypeArguments */: + return ts.updateExpressionWithTypeArguments(node, nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), visitNode(node.expression, visitor, ts.isExpression)); + case 212 /* AsExpression */: + return ts.updateAsExpression(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.type, visitor, ts.isTypeNode)); + case 213 /* NonNullExpression */: + return ts.updateNonNullExpression(node, visitNode(node.expression, visitor, ts.isExpression)); + case 214 /* MetaProperty */: + return ts.updateMetaProperty(node, visitNode(node.name, visitor, ts.isIdentifier)); + // Misc + case 216 /* TemplateSpan */: + return ts.updateTemplateSpan(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.literal, visitor, ts.isTemplateMiddleOrTemplateTail)); + // Element + case 218 /* Block */: + return ts.updateBlock(node, nodesVisitor(node.statements, visitor, ts.isStatement)); + case 219 /* VariableStatement */: + return ts.updateVariableStatement(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.declarationList, visitor, ts.isVariableDeclarationList)); + case 221 /* ExpressionStatement */: + return ts.updateExpressionStatement(node, visitNode(node.expression, visitor, ts.isExpression)); + case 222 /* IfStatement */: + return ts.updateIf(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.thenStatement, visitor, ts.isStatement, ts.liftToBlock), visitNode(node.elseStatement, visitor, ts.isStatement, ts.liftToBlock)); + case 223 /* DoStatement */: + return ts.updateDo(node, visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock), visitNode(node.expression, visitor, ts.isExpression)); + case 224 /* WhileStatement */: + return ts.updateWhile(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); + case 225 /* ForStatement */: + return ts.updateFor(node, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.condition, visitor, ts.isExpression), visitNode(node.incrementor, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); + case 226 /* ForInStatement */: + return ts.updateForIn(node, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); + case 227 /* ForOfStatement */: + return ts.updateForOf(node, visitNode(node.awaitModifier, visitor, ts.isToken), visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); + case 228 /* ContinueStatement */: + return ts.updateContinue(node, visitNode(node.label, visitor, ts.isIdentifier)); + case 229 /* BreakStatement */: + return ts.updateBreak(node, visitNode(node.label, visitor, ts.isIdentifier)); + case 230 /* ReturnStatement */: + return ts.updateReturn(node, visitNode(node.expression, visitor, ts.isExpression)); + case 231 /* WithStatement */: + return ts.updateWith(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); + case 232 /* SwitchStatement */: + return ts.updateSwitch(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.caseBlock, visitor, ts.isCaseBlock)); + case 233 /* LabeledStatement */: + return ts.updateLabel(node, visitNode(node.label, visitor, ts.isIdentifier), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); + case 234 /* ThrowStatement */: + return ts.updateThrow(node, visitNode(node.expression, visitor, ts.isExpression)); + case 235 /* TryStatement */: + return ts.updateTry(node, visitNode(node.tryBlock, visitor, ts.isBlock), visitNode(node.catchClause, visitor, ts.isCatchClause), visitNode(node.finallyBlock, visitor, ts.isBlock)); + case 237 /* VariableDeclaration */: + return ts.updateVariableDeclaration(node, visitNode(node.name, visitor, ts.isBindingName), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); + case 238 /* VariableDeclarationList */: + return ts.updateVariableDeclarationList(node, nodesVisitor(node.declarations, visitor, ts.isVariableDeclaration)); + case 239 /* FunctionDeclaration */: + return ts.updateFunctionDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); + case 240 /* ClassDeclaration */: + return ts.updateClassDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement)); + case 241 /* InterfaceDeclaration */: + return ts.updateInterfaceDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isTypeElement)); + case 242 /* TypeAliasDeclaration */: + return ts.updateTypeAliasDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); + case 243 /* EnumDeclaration */: + return ts.updateEnumDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.members, visitor, ts.isEnumMember)); + case 244 /* ModuleDeclaration */: + return ts.updateModuleDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.body, visitor, ts.isModuleBody)); + case 245 /* ModuleBlock */: + return ts.updateModuleBlock(node, nodesVisitor(node.statements, visitor, ts.isStatement)); + case 246 /* CaseBlock */: + return ts.updateCaseBlock(node, nodesVisitor(node.clauses, visitor, ts.isCaseOrDefaultClause)); + case 247 /* NamespaceExportDeclaration */: + return ts.updateNamespaceExportDeclaration(node, visitNode(node.name, visitor, ts.isIdentifier)); + case 248 /* ImportEqualsDeclaration */: + return ts.updateImportEqualsDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.moduleReference, visitor, ts.isModuleReference)); + case 249 /* ImportDeclaration */: + return ts.updateImportDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.importClause, visitor, ts.isImportClause), visitNode(node.moduleSpecifier, visitor, ts.isExpression)); + case 250 /* ImportClause */: + return ts.updateImportClause(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.namedBindings, visitor, ts.isNamedImportBindings)); + case 251 /* NamespaceImport */: + return ts.updateNamespaceImport(node, visitNode(node.name, visitor, ts.isIdentifier)); + case 252 /* NamedImports */: + return ts.updateNamedImports(node, nodesVisitor(node.elements, visitor, ts.isImportSpecifier)); + case 253 /* ImportSpecifier */: + return ts.updateImportSpecifier(node, visitNode(node.propertyName, visitor, ts.isIdentifier), visitNode(node.name, visitor, ts.isIdentifier)); + case 254 /* ExportAssignment */: + return ts.updateExportAssignment(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.expression, visitor, ts.isExpression)); + case 255 /* ExportDeclaration */: + return ts.updateExportDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.exportClause, visitor, ts.isNamedExports), visitNode(node.moduleSpecifier, visitor, ts.isExpression)); + case 256 /* NamedExports */: + return ts.updateNamedExports(node, nodesVisitor(node.elements, visitor, ts.isExportSpecifier)); + case 257 /* ExportSpecifier */: + return ts.updateExportSpecifier(node, visitNode(node.propertyName, visitor, ts.isIdentifier), visitNode(node.name, visitor, ts.isIdentifier)); + // Module references + case 259 /* ExternalModuleReference */: + return ts.updateExternalModuleReference(node, visitNode(node.expression, visitor, ts.isExpression)); + // JSX + case 260 /* JsxElement */: + return ts.updateJsxElement(node, visitNode(node.openingElement, visitor, ts.isJsxOpeningElement), nodesVisitor(node.children, visitor, ts.isJsxChild), visitNode(node.closingElement, visitor, ts.isJsxClosingElement)); + case 261 /* JsxSelfClosingElement */: + return ts.updateJsxSelfClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), visitNode(node.attributes, visitor, ts.isJsxAttributes)); + case 262 /* JsxOpeningElement */: + return ts.updateJsxOpeningElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), visitNode(node.attributes, visitor, ts.isJsxAttributes)); + case 263 /* JsxClosingElement */: + return ts.updateJsxClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression)); + case 264 /* JsxFragment */: + return ts.updateJsxFragment(node, visitNode(node.openingFragment, visitor, ts.isJsxOpeningFragment), nodesVisitor(node.children, visitor, ts.isJsxChild), visitNode(node.closingFragment, visitor, ts.isJsxClosingFragment)); + case 267 /* JsxAttribute */: + return ts.updateJsxAttribute(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.initializer, visitor, ts.isStringLiteralOrJsxExpression)); + case 268 /* JsxAttributes */: + return ts.updateJsxAttributes(node, nodesVisitor(node.properties, visitor, ts.isJsxAttributeLike)); + case 269 /* JsxSpreadAttribute */: + return ts.updateJsxSpreadAttribute(node, visitNode(node.expression, visitor, ts.isExpression)); + case 270 /* JsxExpression */: + return ts.updateJsxExpression(node, visitNode(node.expression, visitor, ts.isExpression)); + // Clauses + case 271 /* CaseClause */: + return ts.updateCaseClause(node, visitNode(node.expression, visitor, ts.isExpression), nodesVisitor(node.statements, visitor, ts.isStatement)); + case 272 /* DefaultClause */: + return ts.updateDefaultClause(node, nodesVisitor(node.statements, visitor, ts.isStatement)); + case 273 /* HeritageClause */: + return ts.updateHeritageClause(node, nodesVisitor(node.types, visitor, ts.isExpressionWithTypeArguments)); + case 274 /* CatchClause */: + return ts.updateCatchClause(node, visitNode(node.variableDeclaration, visitor, ts.isVariableDeclaration), visitNode(node.block, visitor, ts.isBlock)); + // Property assignments + case 275 /* PropertyAssignment */: + return ts.updatePropertyAssignment(node, visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.initializer, visitor, ts.isExpression)); + case 276 /* ShorthandPropertyAssignment */: + return ts.updateShorthandPropertyAssignment(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.objectAssignmentInitializer, visitor, ts.isExpression)); + case 277 /* SpreadAssignment */: + return ts.updateSpreadAssignment(node, visitNode(node.expression, visitor, ts.isExpression)); + // Enum + case 278 /* EnumMember */: + return ts.updateEnumMember(node, visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.initializer, visitor, ts.isExpression)); + // Top-level nodes + case 279 /* SourceFile */: + return ts.updateSourceFileNode(node, visitLexicalEnvironment(node.statements, visitor, context)); + // Transformation nodes + case 308 /* PartiallyEmittedExpression */: + return ts.updatePartiallyEmittedExpression(node, visitNode(node.expression, visitor, ts.isExpression)); + case 309 /* CommaListExpression */: + return ts.updateCommaList(node, nodesVisitor(node.elements, visitor, ts.isExpression)); + default: + // No need to visit nodes with no children. + return node; + } + } + ts.visitEachChild = visitEachChild; + /** + * Extracts the single node from a NodeArray. + * + * @param nodes The NodeArray. + */ + function extractSingleNode(nodes) { + ts.Debug.assert(nodes.length <= 1, "Too many nodes written to output."); + return ts.singleOrUndefined(nodes); + } +})(ts || (ts = {})); +/* @internal */ +(function (ts) { + function reduceNode(node, f, initial) { + return node ? f(initial, node) : initial; + } + function reduceNodeArray(nodes, f, initial) { + return nodes ? f(initial, nodes) : initial; + } + /** + * Similar to `reduceLeft`, performs a reduction against each child of a node. + * NOTE: Unlike `forEachChild`, this does *not* visit every node. + * + * @param node The node containing the children to reduce. + * @param initial The initial value to supply to the reduction. + * @param f The callback function + */ + function reduceEachChild(node, initial, cbNode, cbNodeArray) { + if (node === undefined) { + return initial; + } + var reduceNodes = cbNodeArray ? reduceNodeArray : ts.reduceLeft; + var cbNodes = cbNodeArray || cbNode; + var kind = node.kind; + // No need to visit nodes with no children. + if ((kind > 0 /* FirstToken */ && kind <= 147 /* LastToken */)) { + return initial; + } + // We do not yet support types. + if ((kind >= 163 /* TypePredicate */ && kind <= 182 /* LiteralType */)) { + return initial; + } + var result = initial; + switch (node.kind) { + // Leaf nodes + case 217 /* SemicolonClassElement */: + case 220 /* EmptyStatement */: + case 210 /* OmittedExpression */: + case 236 /* DebuggerStatement */: + case 307 /* NotEmittedStatement */: + // No need to visit nodes with no children. + break; + // Names + case 148 /* QualifiedName */: + result = reduceNode(node.left, cbNode, result); + result = reduceNode(node.right, cbNode, result); + break; + case 149 /* ComputedPropertyName */: + result = reduceNode(node.expression, cbNode, result); + break; + // Signature elements + case 151 /* Parameter */: + result = reduceNodes(node.decorators, cbNodes, result); + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.type, cbNode, result); + result = reduceNode(node.initializer, cbNode, result); + break; + case 152 /* Decorator */: + result = reduceNode(node.expression, cbNode, result); + break; + // Type member + case 153 /* PropertySignature */: + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.questionToken, cbNode, result); + result = reduceNode(node.type, cbNode, result); + result = reduceNode(node.initializer, cbNode, result); + break; + case 154 /* PropertyDeclaration */: + result = reduceNodes(node.decorators, cbNodes, result); + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.type, cbNode, result); + result = reduceNode(node.initializer, cbNode, result); + break; + case 156 /* MethodDeclaration */: + result = reduceNodes(node.decorators, cbNodes, result); + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNodes(node.typeParameters, cbNodes, result); + result = reduceNodes(node.parameters, cbNodes, result); + result = reduceNode(node.type, cbNode, result); + result = reduceNode(node.body, cbNode, result); + break; + case 157 /* Constructor */: + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNodes(node.parameters, cbNodes, result); + result = reduceNode(node.body, cbNode, result); + break; + case 158 /* GetAccessor */: + result = reduceNodes(node.decorators, cbNodes, result); + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNodes(node.parameters, cbNodes, result); + result = reduceNode(node.type, cbNode, result); + result = reduceNode(node.body, cbNode, result); + break; + case 159 /* SetAccessor */: + result = reduceNodes(node.decorators, cbNodes, result); + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNodes(node.parameters, cbNodes, result); + result = reduceNode(node.body, cbNode, result); + break; + // Binding patterns + case 184 /* ObjectBindingPattern */: + case 185 /* ArrayBindingPattern */: + result = reduceNodes(node.elements, cbNodes, result); + break; + case 186 /* BindingElement */: + result = reduceNode(node.propertyName, cbNode, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.initializer, cbNode, result); + break; + // Expression + case 187 /* ArrayLiteralExpression */: + result = reduceNodes(node.elements, cbNodes, result); + break; + case 188 /* ObjectLiteralExpression */: + result = reduceNodes(node.properties, cbNodes, result); + break; + case 189 /* PropertyAccessExpression */: + result = reduceNode(node.expression, cbNode, result); + result = reduceNode(node.name, cbNode, result); + break; + case 190 /* ElementAccessExpression */: + result = reduceNode(node.expression, cbNode, result); + result = reduceNode(node.argumentExpression, cbNode, result); + break; + case 191 /* CallExpression */: + result = reduceNode(node.expression, cbNode, result); + result = reduceNodes(node.typeArguments, cbNodes, result); + result = reduceNodes(node.arguments, cbNodes, result); + break; + case 192 /* NewExpression */: + result = reduceNode(node.expression, cbNode, result); + result = reduceNodes(node.typeArguments, cbNodes, result); + result = reduceNodes(node.arguments, cbNodes, result); + break; + case 193 /* TaggedTemplateExpression */: + result = reduceNode(node.tag, cbNode, result); + result = reduceNodes(node.typeArguments, cbNodes, result); + result = reduceNode(node.template, cbNode, result); + break; + case 194 /* TypeAssertionExpression */: + result = reduceNode(node.type, cbNode, result); + result = reduceNode(node.expression, cbNode, result); + break; + case 196 /* FunctionExpression */: + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNodes(node.typeParameters, cbNodes, result); + result = reduceNodes(node.parameters, cbNodes, result); + result = reduceNode(node.type, cbNode, result); + result = reduceNode(node.body, cbNode, result); + break; + case 197 /* ArrowFunction */: + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNodes(node.typeParameters, cbNodes, result); + result = reduceNodes(node.parameters, cbNodes, result); + result = reduceNode(node.type, cbNode, result); + result = reduceNode(node.body, cbNode, result); + break; + case 195 /* ParenthesizedExpression */: + case 198 /* DeleteExpression */: + case 199 /* TypeOfExpression */: + case 200 /* VoidExpression */: + case 201 /* AwaitExpression */: + case 207 /* YieldExpression */: + case 208 /* SpreadElement */: + case 213 /* NonNullExpression */: + result = reduceNode(node.expression, cbNode, result); + break; + case 202 /* PrefixUnaryExpression */: + case 203 /* PostfixUnaryExpression */: + result = reduceNode(node.operand, cbNode, result); + break; + case 204 /* BinaryExpression */: + result = reduceNode(node.left, cbNode, result); + result = reduceNode(node.right, cbNode, result); + break; + case 205 /* ConditionalExpression */: + result = reduceNode(node.condition, cbNode, result); + result = reduceNode(node.whenTrue, cbNode, result); + result = reduceNode(node.whenFalse, cbNode, result); + break; + case 206 /* TemplateExpression */: + result = reduceNode(node.head, cbNode, result); + result = reduceNodes(node.templateSpans, cbNodes, result); + break; + case 209 /* ClassExpression */: + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNodes(node.typeParameters, cbNodes, result); + result = reduceNodes(node.heritageClauses, cbNodes, result); + result = reduceNodes(node.members, cbNodes, result); + break; + case 211 /* ExpressionWithTypeArguments */: + result = reduceNode(node.expression, cbNode, result); + result = reduceNodes(node.typeArguments, cbNodes, result); + break; + case 212 /* AsExpression */: + result = reduceNode(node.expression, cbNode, result); + result = reduceNode(node.type, cbNode, result); + break; + // Misc + case 216 /* TemplateSpan */: + result = reduceNode(node.expression, cbNode, result); + result = reduceNode(node.literal, cbNode, result); + break; + // Element + case 218 /* Block */: + result = reduceNodes(node.statements, cbNodes, result); + break; + case 219 /* VariableStatement */: + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.declarationList, cbNode, result); + break; + case 221 /* ExpressionStatement */: + result = reduceNode(node.expression, cbNode, result); + break; + case 222 /* IfStatement */: + result = reduceNode(node.expression, cbNode, result); + result = reduceNode(node.thenStatement, cbNode, result); + result = reduceNode(node.elseStatement, cbNode, result); + break; + case 223 /* DoStatement */: + result = reduceNode(node.statement, cbNode, result); + result = reduceNode(node.expression, cbNode, result); + break; + case 224 /* WhileStatement */: + case 231 /* WithStatement */: + result = reduceNode(node.expression, cbNode, result); + result = reduceNode(node.statement, cbNode, result); + break; + case 225 /* ForStatement */: + result = reduceNode(node.initializer, cbNode, result); + result = reduceNode(node.condition, cbNode, result); + result = reduceNode(node.incrementor, cbNode, result); + result = reduceNode(node.statement, cbNode, result); + break; + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + result = reduceNode(node.initializer, cbNode, result); + result = reduceNode(node.expression, cbNode, result); + result = reduceNode(node.statement, cbNode, result); + break; + case 230 /* ReturnStatement */: + case 234 /* ThrowStatement */: + result = reduceNode(node.expression, cbNode, result); + break; + case 232 /* SwitchStatement */: + result = reduceNode(node.expression, cbNode, result); + result = reduceNode(node.caseBlock, cbNode, result); + break; + case 233 /* LabeledStatement */: + result = reduceNode(node.label, cbNode, result); + result = reduceNode(node.statement, cbNode, result); + break; + case 235 /* TryStatement */: + result = reduceNode(node.tryBlock, cbNode, result); + result = reduceNode(node.catchClause, cbNode, result); + result = reduceNode(node.finallyBlock, cbNode, result); + break; + case 237 /* VariableDeclaration */: + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.type, cbNode, result); + result = reduceNode(node.initializer, cbNode, result); + break; + case 238 /* VariableDeclarationList */: + result = reduceNodes(node.declarations, cbNodes, result); + break; + case 239 /* FunctionDeclaration */: + result = reduceNodes(node.decorators, cbNodes, result); + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNodes(node.typeParameters, cbNodes, result); + result = reduceNodes(node.parameters, cbNodes, result); + result = reduceNode(node.type, cbNode, result); + result = reduceNode(node.body, cbNode, result); + break; + case 240 /* ClassDeclaration */: + result = reduceNodes(node.decorators, cbNodes, result); + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNodes(node.typeParameters, cbNodes, result); + result = reduceNodes(node.heritageClauses, cbNodes, result); + result = reduceNodes(node.members, cbNodes, result); + break; + case 243 /* EnumDeclaration */: + result = reduceNodes(node.decorators, cbNodes, result); + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNodes(node.members, cbNodes, result); + break; + case 244 /* ModuleDeclaration */: + result = reduceNodes(node.decorators, cbNodes, result); + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.body, cbNode, result); + break; + case 245 /* ModuleBlock */: + result = reduceNodes(node.statements, cbNodes, result); + break; + case 246 /* CaseBlock */: + result = reduceNodes(node.clauses, cbNodes, result); + break; + case 248 /* ImportEqualsDeclaration */: + result = reduceNodes(node.decorators, cbNodes, result); + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.moduleReference, cbNode, result); + break; + case 249 /* ImportDeclaration */: + result = reduceNodes(node.decorators, cbNodes, result); + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.importClause, cbNode, result); + result = reduceNode(node.moduleSpecifier, cbNode, result); + break; + case 250 /* ImportClause */: + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.namedBindings, cbNode, result); + break; + case 251 /* NamespaceImport */: + result = reduceNode(node.name, cbNode, result); + break; + case 252 /* NamedImports */: + case 256 /* NamedExports */: + result = reduceNodes(node.elements, cbNodes, result); + break; + case 253 /* ImportSpecifier */: + case 257 /* ExportSpecifier */: + result = reduceNode(node.propertyName, cbNode, result); + result = reduceNode(node.name, cbNode, result); + break; + case 254 /* ExportAssignment */: + result = ts.reduceLeft(node.decorators, cbNode, result); + result = ts.reduceLeft(node.modifiers, cbNode, result); + result = reduceNode(node.expression, cbNode, result); + break; + case 255 /* ExportDeclaration */: + result = ts.reduceLeft(node.decorators, cbNode, result); + result = ts.reduceLeft(node.modifiers, cbNode, result); + result = reduceNode(node.exportClause, cbNode, result); + result = reduceNode(node.moduleSpecifier, cbNode, result); + break; + // Module references + case 259 /* ExternalModuleReference */: + result = reduceNode(node.expression, cbNode, result); + break; + // JSX + case 260 /* JsxElement */: + result = reduceNode(node.openingElement, cbNode, result); + result = ts.reduceLeft(node.children, cbNode, result); + result = reduceNode(node.closingElement, cbNode, result); + break; + case 264 /* JsxFragment */: + result = reduceNode(node.openingFragment, cbNode, result); + result = ts.reduceLeft(node.children, cbNode, result); + result = reduceNode(node.closingFragment, cbNode, result); + break; + case 261 /* JsxSelfClosingElement */: + case 262 /* JsxOpeningElement */: + result = reduceNode(node.tagName, cbNode, result); + result = reduceNodes(node.typeArguments, cbNode, result); + result = reduceNode(node.attributes, cbNode, result); + break; + case 268 /* JsxAttributes */: + result = reduceNodes(node.properties, cbNodes, result); + break; + case 263 /* JsxClosingElement */: + result = reduceNode(node.tagName, cbNode, result); + break; + case 267 /* JsxAttribute */: + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.initializer, cbNode, result); + break; + case 269 /* JsxSpreadAttribute */: + result = reduceNode(node.expression, cbNode, result); + break; + case 270 /* JsxExpression */: + result = reduceNode(node.expression, cbNode, result); + break; + // Clauses + case 271 /* CaseClause */: + result = reduceNode(node.expression, cbNode, result); + // falls through + case 272 /* DefaultClause */: + result = reduceNodes(node.statements, cbNodes, result); + break; + case 273 /* HeritageClause */: + result = reduceNodes(node.types, cbNodes, result); + break; + case 274 /* CatchClause */: + result = reduceNode(node.variableDeclaration, cbNode, result); + result = reduceNode(node.block, cbNode, result); + break; + // Property assignments + case 275 /* PropertyAssignment */: + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.initializer, cbNode, result); + break; + case 276 /* ShorthandPropertyAssignment */: + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.objectAssignmentInitializer, cbNode, result); + break; + case 277 /* SpreadAssignment */: + result = reduceNode(node.expression, cbNode, result); + break; + // Enum + case 278 /* EnumMember */: + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.initializer, cbNode, result); + break; + // Top-level nodes + case 279 /* SourceFile */: + result = reduceNodes(node.statements, cbNodes, result); + break; + // Transformation nodes + case 308 /* PartiallyEmittedExpression */: + result = reduceNode(node.expression, cbNode, result); + break; + case 309 /* CommaListExpression */: + result = reduceNodes(node.elements, cbNodes, result); + break; + default: + break; + } + return result; + } + ts.reduceEachChild = reduceEachChild; + function mergeLexicalEnvironment(statements, declarations) { + if (!ts.some(declarations)) { + return statements; + } + return ts.isNodeArray(statements) + ? ts.setTextRange(ts.createNodeArray(ts.addStatementsAfterPrologue(statements.slice(), declarations)), statements) + : ts.addStatementsAfterPrologue(statements, declarations); + } + ts.mergeLexicalEnvironment = mergeLexicalEnvironment; + /** + * Lifts a NodeArray containing only Statement nodes to a block. + * + * @param nodes The NodeArray. + */ + function liftToBlock(nodes) { + Debug.assert(ts.every(nodes, ts.isStatement), "Cannot lift nodes to a Block."); + return ts.singleOrUndefined(nodes) || ts.createBlock(nodes); + } + ts.liftToBlock = liftToBlock; + /** + * Aggregates the TransformFlags for a Node and its subtree. + */ + function aggregateTransformFlags(node) { + aggregateTransformFlagsForNode(node); + return node; + } + ts.aggregateTransformFlags = aggregateTransformFlags; + /** + * Aggregates the TransformFlags for a Node and its subtree. The flags for the subtree are + * computed first, then the transform flags for the current node are computed from the subtree + * flags and the state of the current node. Finally, the transform flags of the node are + * returned, excluding any flags that should not be included in its parent node's subtree + * flags. + */ + function aggregateTransformFlagsForNode(node) { + if (node === undefined) { + return 0 /* None */; + } + if (node.transformFlags & 536870912 /* HasComputedFlags */) { + return node.transformFlags & ~ts.getTransformFlagsSubtreeExclusions(node.kind); + } + var subtreeFlags = aggregateTransformFlagsForSubtree(node); + return ts.computeTransformFlagsForNode(node, subtreeFlags); + } + function aggregateTransformFlagsForNodeArray(nodes) { + if (nodes === undefined) { + return 0 /* None */; + } + var subtreeFlags = 0 /* None */; + var nodeArrayFlags = 0 /* None */; + for (var _i = 0, nodes_3 = nodes; _i < nodes_3.length; _i++) { + var node = nodes_3[_i]; + subtreeFlags |= aggregateTransformFlagsForNode(node); + nodeArrayFlags |= node.transformFlags & ~536870912 /* HasComputedFlags */; + } + nodes.transformFlags = nodeArrayFlags | 536870912 /* HasComputedFlags */; + return subtreeFlags; + } + /** + * Aggregates the transform flags for the subtree of a node. + */ + function aggregateTransformFlagsForSubtree(node) { + // We do not transform ambient declarations or types, so there is no need to + // recursively aggregate transform flags. + if (ts.hasModifier(node, 2 /* Ambient */) || (ts.isTypeNode(node) && node.kind !== 211 /* ExpressionWithTypeArguments */)) { + return 0 /* None */; + } + // Aggregate the transform flags of each child. + return reduceEachChild(node, 0 /* None */, aggregateTransformFlagsForChildNode, aggregateTransformFlagsForChildNodes); + } + /** + * Aggregates the TransformFlags of a child node with the TransformFlags of its + * siblings. + */ + function aggregateTransformFlagsForChildNode(transformFlags, node) { + return transformFlags | aggregateTransformFlagsForNode(node); + } + function aggregateTransformFlagsForChildNodes(transformFlags, nodes) { + return transformFlags | aggregateTransformFlagsForNodeArray(nodes); + } + var Debug; + (function (Debug) { + var isDebugInfoEnabled = false; + function failBadSyntaxKind(node, message) { + return Debug.fail((message || "Unexpected node.") + "\r\nNode " + ts.formatSyntaxKind(node.kind) + " was unexpected.", failBadSyntaxKind); + } + Debug.failBadSyntaxKind = failBadSyntaxKind; + Debug.assertEachNode = Debug.shouldAssert(1 /* Normal */) + ? function (nodes, test, message) { return Debug.assert(test === undefined || ts.every(nodes, test), message || "Unexpected node.", function () { return "Node array did not pass test '" + Debug.getFunctionName(test) + "'."; }, Debug.assertEachNode); } + : ts.noop; + Debug.assertNode = Debug.shouldAssert(1 /* Normal */) + ? function (node, test, message) { return Debug.assert(test === undefined || test(node), message || "Unexpected node.", function () { return "Node " + ts.formatSyntaxKind(node.kind) + " did not pass test '" + Debug.getFunctionName(test) + "'."; }, Debug.assertNode); } + : ts.noop; + Debug.assertOptionalNode = Debug.shouldAssert(1 /* Normal */) + ? function (node, test, message) { return Debug.assert(test === undefined || node === undefined || test(node), message || "Unexpected node.", function () { return "Node " + ts.formatSyntaxKind(node.kind) + " did not pass test '" + Debug.getFunctionName(test) + "'."; }, Debug.assertOptionalNode); } + : ts.noop; + Debug.assertOptionalToken = Debug.shouldAssert(1 /* Normal */) + ? function (node, kind, message) { return Debug.assert(kind === undefined || node === undefined || node.kind === kind, message || "Unexpected node.", function () { return "Node " + ts.formatSyntaxKind(node.kind) + " was not a '" + ts.formatSyntaxKind(kind) + "' token."; }, Debug.assertOptionalToken); } + : ts.noop; + Debug.assertMissingNode = Debug.shouldAssert(1 /* Normal */) + ? function (node, message) { return Debug.assert(node === undefined, message || "Unexpected node.", function () { return "Node " + ts.formatSyntaxKind(node.kind) + " was unexpected'."; }, Debug.assertMissingNode); } + : ts.noop; + /** + * Injects debug information into frequently used types. + */ + function enableDebugInfo() { + if (isDebugInfoEnabled) + return; + // Add additional properties in debug mode to assist with debugging. + Object.defineProperties(ts.objectAllocator.getSymbolConstructor().prototype, { + __debugFlags: { get: function () { return ts.formatSymbolFlags(this.flags); } } + }); + Object.defineProperties(ts.objectAllocator.getTypeConstructor().prototype, { + __debugFlags: { get: function () { return ts.formatTypeFlags(this.flags); } }, + __debugObjectFlags: { get: function () { return this.flags & 524288 /* Object */ ? ts.formatObjectFlags(this.objectFlags) : ""; } }, + __debugTypeToString: { value: function () { return this.checker.typeToString(this); } }, + }); + var nodeConstructors = [ + ts.objectAllocator.getNodeConstructor(), + ts.objectAllocator.getIdentifierConstructor(), + ts.objectAllocator.getTokenConstructor(), + ts.objectAllocator.getSourceFileConstructor() + ]; + for (var _i = 0, nodeConstructors_1 = nodeConstructors; _i < nodeConstructors_1.length; _i++) { + var ctor = nodeConstructors_1[_i]; + if (!ctor.prototype.hasOwnProperty("__debugKind")) { + Object.defineProperties(ctor.prototype, { + __debugKind: { get: function () { return ts.formatSyntaxKind(this.kind); } }, + __debugModifierFlags: { get: function () { return ts.formatModifierFlags(ts.getModifierFlagsNoCache(this)); } }, + __debugTransformFlags: { get: function () { return ts.formatTransformFlags(this.transformFlags); } }, + __debugEmitFlags: { get: function () { return ts.formatEmitFlags(ts.getEmitFlags(this)); } }, + __debugGetText: { + value: function (includeTrivia) { + if (ts.nodeIsSynthesized(this)) + return ""; + var parseNode = ts.getParseTreeNode(this); + var sourceFile = parseNode && ts.getSourceFileOfNode(parseNode); + return sourceFile ? ts.getSourceTextOfNodeFromSourceFile(sourceFile, parseNode, includeTrivia) : ""; + } + } + }); + } + } + isDebugInfoEnabled = true; + } + Debug.enableDebugInfo = enableDebugInfo; + })(Debug = ts.Debug || (ts.Debug = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + function createSourceMapGenerator(host, file, sourceRoot, sourcesDirectoryPath, generatorOptions) { + var _a = generatorOptions.extendedDiagnostics + ? ts.performance.createTimer("Source Map", "beforeSourcemap", "afterSourcemap") + : ts.performance.nullTimer, enter = _a.enter, exit = _a.exit; + // Current source map file and its index in the sources list + var rawSources = []; + var sources = []; + var sourceToSourceIndexMap = ts.createMap(); + var sourcesContent; + var names = []; + var nameToNameIndexMap; + var mappings = ""; + // Last recorded and encoded mappings + var lastGeneratedLine = 0; + var lastGeneratedCharacter = 0; + var lastSourceIndex = 0; + var lastSourceLine = 0; + var lastSourceCharacter = 0; + var lastNameIndex = 0; + var hasLast = false; + var pendingGeneratedLine = 0; + var pendingGeneratedCharacter = 0; + var pendingSourceIndex = 0; + var pendingSourceLine = 0; + var pendingSourceCharacter = 0; + var pendingNameIndex = 0; + var hasPending = false; + var hasPendingSource = false; + var hasPendingName = false; + return { + getSources: function () { return rawSources; }, + addSource: addSource, + setSourceContent: setSourceContent, + addName: addName, + addMapping: addMapping, + appendSourceMap: appendSourceMap, + toJSON: toJSON, + toString: function () { return JSON.stringify(toJSON()); } + }; + function addSource(fileName) { + enter(); + var source = ts.getRelativePathToDirectoryOrUrl(sourcesDirectoryPath, fileName, host.getCurrentDirectory(), host.getCanonicalFileName, + /*isAbsolutePathAnUrl*/ true); + var sourceIndex = sourceToSourceIndexMap.get(source); + if (sourceIndex === undefined) { + sourceIndex = sources.length; + sources.push(source); + rawSources.push(fileName); + sourceToSourceIndexMap.set(source, sourceIndex); + } + exit(); + return sourceIndex; + } + function setSourceContent(sourceIndex, content) { + enter(); + if (content !== null) { + if (!sourcesContent) + sourcesContent = []; + while (sourcesContent.length < sourceIndex) { + // tslint:disable-next-line:no-null-keyword boolean-trivia + sourcesContent.push(null); + } + sourcesContent[sourceIndex] = content; + } + exit(); + } + function addName(name) { + enter(); + if (!nameToNameIndexMap) + nameToNameIndexMap = ts.createMap(); + var nameIndex = nameToNameIndexMap.get(name); + if (nameIndex === undefined) { + nameIndex = names.length; + names.push(name); + nameToNameIndexMap.set(name, nameIndex); + } + exit(); + return nameIndex; + } + function isNewGeneratedPosition(generatedLine, generatedCharacter) { + return !hasPending + || pendingGeneratedLine !== generatedLine + || pendingGeneratedCharacter !== generatedCharacter; + } + function isBacktrackingSourcePosition(sourceIndex, sourceLine, sourceCharacter) { + return sourceIndex !== undefined + && sourceLine !== undefined + && sourceCharacter !== undefined + && pendingSourceIndex === sourceIndex + && (pendingSourceLine > sourceLine + || pendingSourceLine === sourceLine && pendingSourceCharacter > sourceCharacter); + } + function addMapping(generatedLine, generatedCharacter, sourceIndex, sourceLine, sourceCharacter, nameIndex) { + ts.Debug.assert(generatedLine >= pendingGeneratedLine, "generatedLine cannot backtrack"); + ts.Debug.assert(generatedCharacter >= 0, "generatedCharacter cannot be negative"); + ts.Debug.assert(sourceIndex === undefined || sourceIndex >= 0, "sourceIndex cannot be negative"); + ts.Debug.assert(sourceLine === undefined || sourceLine >= 0, "sourceLine cannot be negative"); + ts.Debug.assert(sourceCharacter === undefined || sourceCharacter >= 0, "sourceCharacter cannot be negative"); + enter(); + // If this location wasn't recorded or the location in source is going backwards, record the mapping + if (isNewGeneratedPosition(generatedLine, generatedCharacter) || + isBacktrackingSourcePosition(sourceIndex, sourceLine, sourceCharacter)) { + commitPendingMapping(); + pendingGeneratedLine = generatedLine; + pendingGeneratedCharacter = generatedCharacter; + hasPendingSource = false; + hasPendingName = false; + hasPending = true; + } + if (sourceIndex !== undefined && sourceLine !== undefined && sourceCharacter !== undefined) { + pendingSourceIndex = sourceIndex; + pendingSourceLine = sourceLine; + pendingSourceCharacter = sourceCharacter; + hasPendingSource = true; + if (nameIndex !== undefined) { + pendingNameIndex = nameIndex; + hasPendingName = true; + } + } + exit(); + } + function appendSourceMap(generatedLine, generatedCharacter, map, sourceMapPath) { + var _a; + ts.Debug.assert(generatedLine >= pendingGeneratedLine, "generatedLine cannot backtrack"); + ts.Debug.assert(generatedCharacter >= 0, "generatedCharacter cannot be negative"); + enter(); + // First, decode the old component sourcemap + var sourceIndexToNewSourceIndexMap = []; + var nameIndexToNewNameIndexMap; + var mappingIterator = decodeMappings(map.mappings); + for (var _b = mappingIterator.next(), raw = _b.value, done = _b.done; !done; _a = mappingIterator.next(), raw = _a.value, done = _a.done, _a) { + // Then reencode all the updated mappings into the overall map + var newSourceIndex = void 0; + var newSourceLine = void 0; + var newSourceCharacter = void 0; + var newNameIndex = void 0; + if (raw.sourceIndex !== undefined) { + newSourceIndex = sourceIndexToNewSourceIndexMap[raw.sourceIndex]; + if (newSourceIndex === undefined) { + // Apply offsets to each position and fixup source entries + var rawPath = map.sources[raw.sourceIndex]; + var relativePath = map.sourceRoot ? ts.combinePaths(map.sourceRoot, rawPath) : rawPath; + var combinedPath = ts.combinePaths(ts.getDirectoryPath(sourceMapPath), relativePath); + sourceIndexToNewSourceIndexMap[raw.sourceIndex] = newSourceIndex = addSource(combinedPath); + if (map.sourcesContent && typeof map.sourcesContent[raw.sourceIndex] === "string") { + setSourceContent(newSourceIndex, map.sourcesContent[raw.sourceIndex]); + } + } + newSourceLine = raw.sourceLine; + newSourceCharacter = raw.sourceCharacter; + if (map.names && raw.nameIndex !== undefined) { + if (!nameIndexToNewNameIndexMap) + nameIndexToNewNameIndexMap = []; + newNameIndex = nameIndexToNewNameIndexMap[raw.nameIndex]; + if (newNameIndex === undefined) { + nameIndexToNewNameIndexMap[raw.nameIndex] = newNameIndex = addName(map.names[raw.nameIndex]); + } + } + } + var newGeneratedLine = raw.generatedLine + generatedLine; + var newGeneratedCharacter = raw.generatedLine === 0 ? raw.generatedCharacter + generatedCharacter : raw.generatedCharacter; + addMapping(newGeneratedLine, newGeneratedCharacter, newSourceIndex, newSourceLine, newSourceCharacter, newNameIndex); + } + exit(); + } + function shouldCommitMapping() { + return !hasLast + || lastGeneratedLine !== pendingGeneratedLine + || lastGeneratedCharacter !== pendingGeneratedCharacter + || lastSourceIndex !== pendingSourceIndex + || lastSourceLine !== pendingSourceLine + || lastSourceCharacter !== pendingSourceCharacter + || lastNameIndex !== pendingNameIndex; + } + function commitPendingMapping() { + if (!hasPending || !shouldCommitMapping()) { + return; + } + enter(); + // Line/Comma delimiters + if (lastGeneratedLine < pendingGeneratedLine) { + // Emit line delimiters + do { + mappings += ";"; + lastGeneratedLine++; + lastGeneratedCharacter = 0; + } while (lastGeneratedLine < pendingGeneratedLine); + } + else { + ts.Debug.assertEqual(lastGeneratedLine, pendingGeneratedLine, "generatedLine cannot backtrack"); + // Emit comma to separate the entry + if (hasLast) { + mappings += ","; + } + } + // 1. Relative generated character + mappings += base64VLQFormatEncode(pendingGeneratedCharacter - lastGeneratedCharacter); + lastGeneratedCharacter = pendingGeneratedCharacter; + if (hasPendingSource) { + // 2. Relative sourceIndex + mappings += base64VLQFormatEncode(pendingSourceIndex - lastSourceIndex); + lastSourceIndex = pendingSourceIndex; + // 3. Relative source line + mappings += base64VLQFormatEncode(pendingSourceLine - lastSourceLine); + lastSourceLine = pendingSourceLine; + // 4. Relative source character + mappings += base64VLQFormatEncode(pendingSourceCharacter - lastSourceCharacter); + lastSourceCharacter = pendingSourceCharacter; + if (hasPendingName) { + // 5. Relative nameIndex + mappings += base64VLQFormatEncode(pendingNameIndex - lastNameIndex); + lastNameIndex = pendingNameIndex; + } + } + hasLast = true; + exit(); + } + function toJSON() { + commitPendingMapping(); + return { + version: 3, + file: file, + sourceRoot: sourceRoot, + sources: sources, + names: names, + mappings: mappings, + sourcesContent: sourcesContent, + }; + } + } + ts.createSourceMapGenerator = createSourceMapGenerator; + // Sometimes tools can see the following line as a source mapping url comment, so we mangle it a bit (the [M]) + var sourceMapCommentRegExp = /^\/\/[@#] source[M]appingURL=(.+)\s*$/; + var whitespaceOrMapCommentRegExp = /^\s*(\/\/[@#] .*)?$/; + /** + * Tries to find the sourceMappingURL comment at the end of a file. + * @param text The source text of the file. + * @param lineStarts The line starts of the file. + */ + function tryGetSourceMappingURL(text, lineStarts) { + if (lineStarts === void 0) { lineStarts = ts.computeLineStarts(text); } + for (var index = lineStarts.length - 1; index >= 0; index--) { + var line = text.substring(lineStarts[index], lineStarts[index + 1]); + var comment = sourceMapCommentRegExp.exec(line); + if (comment) { + return comment[1]; + } + // If we see a non-whitespace/map comment-like line, break, to avoid scanning up the entire file + else if (!line.match(whitespaceOrMapCommentRegExp)) { + break; + } + } + } + ts.tryGetSourceMappingURL = tryGetSourceMappingURL; + function isStringOrNull(x) { + // tslint:disable-next-line:no-null-keyword + return typeof x === "string" || x === null; + } + function isRawSourceMap(x) { + // tslint:disable-next-line:no-null-keyword + return x !== null + && typeof x === "object" + && x.version === 3 + && typeof x.file === "string" + && typeof x.mappings === "string" + && ts.isArray(x.sources) && ts.every(x.sources, ts.isString) + && (x.sourceRoot === undefined || x.sourceRoot === null || typeof x.sourceRoot === "string") + && (x.sourcesContent === undefined || x.sourcesContent === null || ts.isArray(x.sourcesContent) && ts.every(x.sourcesContent, isStringOrNull)) + && (x.names === undefined || x.names === null || ts.isArray(x.names) && ts.every(x.names, ts.isString)); + } + ts.isRawSourceMap = isRawSourceMap; + function tryParseRawSourceMap(text) { + try { + var parsed = JSON.parse(text); + if (isRawSourceMap(parsed)) { + return parsed; + } + } + catch (_a) { + // empty + } + return undefined; + } + ts.tryParseRawSourceMap = tryParseRawSourceMap; + function decodeMappings(mappings) { + var done = false; + var pos = 0; + var generatedLine = 0; + var generatedCharacter = 0; + var sourceIndex = 0; + var sourceLine = 0; + var sourceCharacter = 0; + var nameIndex = 0; + var error; + return { + get pos() { return pos; }, + get error() { return error; }, + get state() { return captureMapping(/*hasSource*/ true, /*hasName*/ true); }, + next: function () { + while (!done && pos < mappings.length) { + var ch = mappings.charCodeAt(pos); + if (ch === 59 /* semicolon */) { + // new line + generatedLine++; + generatedCharacter = 0; + pos++; + continue; + } + if (ch === 44 /* comma */) { + // Next entry is on same line - no action needed + pos++; + continue; + } + var hasSource = false; + var hasName = false; + generatedCharacter += base64VLQFormatDecode(); + if (hasReportedError()) + return stopIterating(); + if (generatedCharacter < 0) + return setErrorAndStopIterating("Invalid generatedCharacter found"); + if (!isSourceMappingSegmentEnd()) { + hasSource = true; + sourceIndex += base64VLQFormatDecode(); + if (hasReportedError()) + return stopIterating(); + if (sourceIndex < 0) + return setErrorAndStopIterating("Invalid sourceIndex found"); + if (isSourceMappingSegmentEnd()) + return setErrorAndStopIterating("Unsupported Format: No entries after sourceIndex"); + sourceLine += base64VLQFormatDecode(); + if (hasReportedError()) + return stopIterating(); + if (sourceLine < 0) + return setErrorAndStopIterating("Invalid sourceLine found"); + if (isSourceMappingSegmentEnd()) + return setErrorAndStopIterating("Unsupported Format: No entries after sourceLine"); + sourceCharacter += base64VLQFormatDecode(); + if (hasReportedError()) + return stopIterating(); + if (sourceCharacter < 0) + return setErrorAndStopIterating("Invalid sourceCharacter found"); + if (!isSourceMappingSegmentEnd()) { + hasName = true; + nameIndex += base64VLQFormatDecode(); + if (hasReportedError()) + return stopIterating(); + if (nameIndex < 0) + return setErrorAndStopIterating("Invalid nameIndex found"); + if (!isSourceMappingSegmentEnd()) + return setErrorAndStopIterating("Unsupported Error Format: Entries after nameIndex"); + } + } + return { value: captureMapping(hasSource, hasName), done: done }; + } + return stopIterating(); + } + }; + function captureMapping(hasSource, hasName) { + return { + generatedLine: generatedLine, + generatedCharacter: generatedCharacter, + sourceIndex: hasSource ? sourceIndex : undefined, + sourceLine: hasSource ? sourceLine : undefined, + sourceCharacter: hasSource ? sourceCharacter : undefined, + nameIndex: hasName ? nameIndex : undefined + }; + } + function stopIterating() { + done = true; + return { value: undefined, done: true }; + } + function setError(message) { + if (error === undefined) { + error = message; + } + } + function setErrorAndStopIterating(message) { + setError(message); + return stopIterating(); + } + function hasReportedError() { + return error !== undefined; + } + function isSourceMappingSegmentEnd() { + return (pos === mappings.length || + mappings.charCodeAt(pos) === 44 /* comma */ || + mappings.charCodeAt(pos) === 59 /* semicolon */); + } + function base64VLQFormatDecode() { + var moreDigits = true; + var shiftCount = 0; + var value = 0; + for (; moreDigits; pos++) { + if (pos >= mappings.length) + return setError("Error in decoding base64VLQFormatDecode, past the mapping string"), -1; + // 6 digit number + var currentByte = base64FormatDecode(mappings.charCodeAt(pos)); + if (currentByte === -1) + return setError("Invalid character in VLQ"), -1; + // If msb is set, we still have more bits to continue + moreDigits = (currentByte & 32) !== 0; + // least significant 5 bits are the next msbs in the final value. + value = value | ((currentByte & 31) << shiftCount); + shiftCount += 5; + } + // Least significant bit if 1 represents negative and rest of the msb is actual absolute value + if ((value & 1) === 0) { + // + number + value = value >> 1; + } + else { + // - number + value = value >> 1; + value = -value; + } + return value; + } + } + ts.decodeMappings = decodeMappings; + function sameMapping(left, right) { + return left === right + || left.generatedLine === right.generatedLine + && left.generatedCharacter === right.generatedCharacter + && left.sourceIndex === right.sourceIndex + && left.sourceLine === right.sourceLine + && left.sourceCharacter === right.sourceCharacter + && left.nameIndex === right.nameIndex; + } + ts.sameMapping = sameMapping; + function isSourceMapping(mapping) { + return mapping.sourceIndex !== undefined + && mapping.sourceLine !== undefined + && mapping.sourceCharacter !== undefined; + } + ts.isSourceMapping = isSourceMapping; + function base64FormatEncode(value) { + return value >= 0 && value < 26 ? 65 /* A */ + value : + value >= 26 && value < 52 ? 97 /* a */ + value - 26 : + value >= 52 && value < 62 ? 48 /* _0 */ + value - 52 : + value === 62 ? 43 /* plus */ : + value === 63 ? 47 /* slash */ : + ts.Debug.fail(value + ": not a base64 value"); + } + function base64FormatDecode(ch) { + return ch >= 65 /* A */ && ch <= 90 /* Z */ ? ch - 65 /* A */ : + ch >= 97 /* a */ && ch <= 122 /* z */ ? ch - 97 /* a */ + 26 : + ch >= 48 /* _0 */ && ch <= 57 /* _9 */ ? ch - 48 /* _0 */ + 52 : + ch === 43 /* plus */ ? 62 : + ch === 47 /* slash */ ? 63 : + -1; + } + function base64VLQFormatEncode(inValue) { + // Add a new least significant bit that has the sign of the value. + // if negative number the least significant bit that gets added to the number has value 1 + // else least significant bit value that gets added is 0 + // eg. -1 changes to binary : 01 [1] => 3 + // +1 changes to binary : 01 [0] => 2 + if (inValue < 0) { + inValue = ((-inValue) << 1) + 1; + } + else { + inValue = inValue << 1; + } + // Encode 5 bits at a time starting from least significant bits + var encodedStr = ""; + do { + var currentDigit = inValue & 31; // 11111 + inValue = inValue >> 5; + if (inValue > 0) { + // There are still more digits to decode, set the msb (6th bit) + currentDigit = currentDigit | 32; + } + encodedStr = encodedStr + String.fromCharCode(base64FormatEncode(currentDigit)); + } while (inValue > 0); + return encodedStr; + } + function isSourceMappedPosition(value) { + return value.sourceIndex !== undefined + && value.sourcePosition !== undefined; + } + function sameMappedPosition(left, right) { + return left.generatedPosition === right.generatedPosition + && left.sourceIndex === right.sourceIndex + && left.sourcePosition === right.sourcePosition; + } + function compareSourcePositions(left, right) { + return ts.compareValues(left.sourceIndex, right.sourceIndex); + } + function compareGeneratedPositions(left, right) { + return ts.compareValues(left.generatedPosition, right.generatedPosition); + } + function getSourcePositionOfMapping(value) { + return value.sourcePosition; + } + function getGeneratedPositionOfMapping(value) { + return value.generatedPosition; + } + function createDocumentPositionMapper(host, map, mapPath) { + var mapDirectory = ts.getDirectoryPath(mapPath); + var sourceRoot = map.sourceRoot ? ts.getNormalizedAbsolutePath(map.sourceRoot, mapDirectory) : mapDirectory; + var generatedAbsoluteFilePath = ts.getNormalizedAbsolutePath(map.file, mapDirectory); + var generatedCanonicalFilePath = host.getCanonicalFileName(generatedAbsoluteFilePath); + var generatedFile = host.getSourceFileLike(generatedCanonicalFilePath); + var sourceFileAbsolutePaths = map.sources.map(function (source) { return ts.getNormalizedAbsolutePath(source, sourceRoot); }); + var sourceFileCanonicalPaths = sourceFileAbsolutePaths.map(function (source) { return host.getCanonicalFileName(source); }); + var sourceToSourceIndexMap = ts.createMapFromEntries(sourceFileCanonicalPaths.map(function (source, i) { return [source, i]; })); + var decodedMappings; + var generatedMappings; + var sourceMappings; + return { + getSourcePosition: getSourcePosition, + getGeneratedPosition: getGeneratedPosition + }; + function processMapping(mapping) { + var generatedPosition = generatedFile !== undefined + ? ts.getPositionOfLineAndCharacterWithEdits(generatedFile, mapping.generatedLine, mapping.generatedCharacter) + : -1; + var source; + var sourcePosition; + if (isSourceMapping(mapping)) { + var sourceFilePath = sourceFileCanonicalPaths[mapping.sourceIndex]; + var sourceFile = host.getSourceFileLike(sourceFilePath); + source = map.sources[mapping.sourceIndex]; + sourcePosition = sourceFile !== undefined + ? ts.getPositionOfLineAndCharacterWithEdits(sourceFile, mapping.sourceLine, mapping.sourceCharacter) + : -1; + } + return { + generatedPosition: generatedPosition, + source: source, + sourceIndex: mapping.sourceIndex, + sourcePosition: sourcePosition, + nameIndex: mapping.nameIndex + }; + } + function getDecodedMappings() { + if (decodedMappings === undefined) { + var decoder = decodeMappings(map.mappings); + var mappings = ts.arrayFrom(decoder, processMapping); + if (decoder.error !== undefined) { + if (host.log) { + host.log("Encountered error while decoding sourcemap: " + decoder.error); + } + decodedMappings = ts.emptyArray; + } + else { + decodedMappings = mappings; + } + } + return decodedMappings; + } + function getSourceMappings(sourceIndex) { + if (sourceMappings === undefined) { + var lists = []; + for (var _i = 0, _a = getDecodedMappings(); _i < _a.length; _i++) { + var mapping = _a[_i]; + if (!isSourceMappedPosition(mapping)) + continue; + var list = lists[mapping.sourceIndex]; + if (!list) + lists[mapping.sourceIndex] = list = []; + list.push(mapping); + } + sourceMappings = lists.map(function (list) { return ts.sortAndDeduplicate(list, compareSourcePositions, sameMappedPosition); }); + } + return sourceMappings[sourceIndex]; + } + function getGeneratedMappings() { + if (generatedMappings === undefined) { + var list = []; + for (var _i = 0, _a = getDecodedMappings(); _i < _a.length; _i++) { + var mapping = _a[_i]; + list.push(mapping); + } + generatedMappings = ts.sortAndDeduplicate(list, compareGeneratedPositions, sameMappedPosition); + } + return generatedMappings; + } + function getGeneratedPosition(loc) { + var sourceIndex = sourceToSourceIndexMap.get(host.getCanonicalFileName(loc.fileName)); + if (sourceIndex === undefined) + return loc; + var sourceMappings = getSourceMappings(sourceIndex); + if (!ts.some(sourceMappings)) + return loc; + var targetIndex = ts.binarySearchKey(sourceMappings, loc.pos, getSourcePositionOfMapping, ts.compareValues); + if (targetIndex < 0) { + // if no exact match, closest is 2's complement of result + targetIndex = ~targetIndex; + } + var mapping = sourceMappings[targetIndex]; + if (mapping === undefined || mapping.sourceIndex !== sourceIndex) { + return loc; + } + return { fileName: generatedAbsoluteFilePath, pos: mapping.generatedPosition }; // Closest pos + } + function getSourcePosition(loc) { + var generatedMappings = getGeneratedMappings(); + if (!ts.some(generatedMappings)) + return loc; + var targetIndex = ts.binarySearchKey(generatedMappings, loc.pos, getGeneratedPositionOfMapping, ts.compareValues); + if (targetIndex < 0) { + // if no exact match, closest is 2's complement of result + targetIndex = ~targetIndex; + } + var mapping = generatedMappings[targetIndex]; + if (mapping === undefined || !isSourceMappedPosition(mapping)) { + return loc; + } + return { fileName: sourceFileAbsolutePaths[mapping.sourceIndex], pos: mapping.sourcePosition }; // Closest pos + } + } + ts.createDocumentPositionMapper = createDocumentPositionMapper; + ts.identitySourceMapConsumer = { + getSourcePosition: ts.identity, + getGeneratedPosition: ts.identity + }; +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + function getOriginalNodeId(node) { + node = ts.getOriginalNode(node); + return node ? ts.getNodeId(node) : 0; + } + ts.getOriginalNodeId = getOriginalNodeId; + function containsDefaultReference(node) { + if (!node) + return false; + if (!ts.isNamedImports(node)) + return false; + return ts.some(node.elements, isNamedDefaultReference); + } + function isNamedDefaultReference(e) { + return e.propertyName !== undefined && e.propertyName.escapedText === "default" /* Default */; + } + function chainBundle(transformSourceFile) { + return transformSourceFileOrBundle; + function transformSourceFileOrBundle(node) { + return node.kind === 279 /* SourceFile */ ? transformSourceFile(node) : transformBundle(node); + } + function transformBundle(node) { + return ts.createBundle(ts.map(node.sourceFiles, transformSourceFile), node.prepends); + } + } + ts.chainBundle = chainBundle; + function getImportNeedsImportStarHelper(node) { + if (!!ts.getNamespaceDeclarationNode(node)) { + return true; + } + var bindings = node.importClause && node.importClause.namedBindings; + if (!bindings) { + return false; + } + if (!ts.isNamedImports(bindings)) + return false; + var defaultRefCount = 0; + for (var _i = 0, _a = bindings.elements; _i < _a.length; _i++) { + var binding = _a[_i]; + if (isNamedDefaultReference(binding)) { + defaultRefCount++; + } + } + // Import star is required if there's default named refs mixed with non-default refs, or if theres non-default refs and it has a default import + return (defaultRefCount > 0 && defaultRefCount !== bindings.elements.length) || (!!(bindings.elements.length - defaultRefCount) && ts.isDefaultImport(node)); + } + ts.getImportNeedsImportStarHelper = getImportNeedsImportStarHelper; + function getImportNeedsImportDefaultHelper(node) { + // Import default is needed if there's a default import or a default ref and no other refs (meaning an import star helper wasn't requested) + return !getImportNeedsImportStarHelper(node) && (ts.isDefaultImport(node) || (!!node.importClause && ts.isNamedImports(node.importClause.namedBindings) && containsDefaultReference(node.importClause.namedBindings))); // TODO: GH#18217 + } + ts.getImportNeedsImportDefaultHelper = getImportNeedsImportDefaultHelper; + function collectExternalModuleInfo(sourceFile, resolver, compilerOptions) { + var externalImports = []; + var exportSpecifiers = ts.createMultiMap(); + var exportedBindings = []; + var uniqueExports = ts.createMap(); + var exportedNames; + var hasExportDefault = false; + var exportEquals; + var hasExportStarsToExportValues = false; + var hasImportStarOrImportDefault = false; + for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { + var node = _a[_i]; + switch (node.kind) { + case 249 /* ImportDeclaration */: + // import "mod" + // import x from "mod" + // import * as x from "mod" + // import { x, y } from "mod" + externalImports.push(node); + hasImportStarOrImportDefault = hasImportStarOrImportDefault || getImportNeedsImportStarHelper(node) || getImportNeedsImportDefaultHelper(node); + break; + case 248 /* ImportEqualsDeclaration */: + if (node.moduleReference.kind === 259 /* ExternalModuleReference */) { + // import x = require("mod") + externalImports.push(node); + } + break; + case 255 /* ExportDeclaration */: + if (node.moduleSpecifier) { + if (!node.exportClause) { + // export * from "mod" + externalImports.push(node); + hasExportStarsToExportValues = true; + } + else { + // export { x, y } from "mod" + externalImports.push(node); + } + } + else { + // export { x, y } + for (var _b = 0, _c = node.exportClause.elements; _b < _c.length; _b++) { + var specifier = _c[_b]; + if (!uniqueExports.get(ts.idText(specifier.name))) { + var name = specifier.propertyName || specifier.name; + exportSpecifiers.add(ts.idText(name), specifier); + var decl = resolver.getReferencedImportDeclaration(name) + || resolver.getReferencedValueDeclaration(name); + if (decl) { + multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(decl), specifier.name); + } + uniqueExports.set(ts.idText(specifier.name), true); + exportedNames = ts.append(exportedNames, specifier.name); + } + } + } + break; + case 254 /* ExportAssignment */: + if (node.isExportEquals && !exportEquals) { + // export = x + exportEquals = node; + } + break; + case 219 /* VariableStatement */: + if (ts.hasModifier(node, 1 /* Export */)) { + for (var _d = 0, _e = node.declarationList.declarations; _d < _e.length; _d++) { + var decl = _e[_d]; + exportedNames = collectExportedVariableInfo(decl, uniqueExports, exportedNames); + } + } + break; + case 239 /* FunctionDeclaration */: + if (ts.hasModifier(node, 1 /* Export */)) { + if (ts.hasModifier(node, 512 /* Default */)) { + // export default function() { } + if (!hasExportDefault) { + multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), ts.getDeclarationName(node)); + hasExportDefault = true; + } + } + else { + // export function x() { } + var name = node.name; + if (!uniqueExports.get(ts.idText(name))) { + multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), name); + uniqueExports.set(ts.idText(name), true); + exportedNames = ts.append(exportedNames, name); + } + } + } + break; + case 240 /* ClassDeclaration */: + if (ts.hasModifier(node, 1 /* Export */)) { + if (ts.hasModifier(node, 512 /* Default */)) { + // export default class { } + if (!hasExportDefault) { + multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), ts.getDeclarationName(node)); + hasExportDefault = true; + } + } + else { + // export class x { } + var name = node.name; + if (name && !uniqueExports.get(ts.idText(name))) { + multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), name); + uniqueExports.set(ts.idText(name), true); + exportedNames = ts.append(exportedNames, name); + } + } + } + break; + } + } + var externalHelpersModuleName = ts.getOrCreateExternalHelpersModuleNameIfNeeded(sourceFile, compilerOptions, hasExportStarsToExportValues, hasImportStarOrImportDefault); + var externalHelpersImportDeclaration = externalHelpersModuleName && ts.createImportDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(externalHelpersModuleName)), ts.createLiteral(ts.externalHelpersModuleNameText)); + if (externalHelpersImportDeclaration) { + ts.addEmitFlags(externalHelpersImportDeclaration, 67108864 /* NeverApplyImportHelper */); + externalImports.unshift(externalHelpersImportDeclaration); + } + return { externalImports: externalImports, exportSpecifiers: exportSpecifiers, exportEquals: exportEquals, hasExportStarsToExportValues: hasExportStarsToExportValues, exportedBindings: exportedBindings, exportedNames: exportedNames, externalHelpersImportDeclaration: externalHelpersImportDeclaration }; + } + ts.collectExternalModuleInfo = collectExternalModuleInfo; + function collectExportedVariableInfo(decl, uniqueExports, exportedNames) { + if (ts.isBindingPattern(decl.name)) { + for (var _i = 0, _a = decl.name.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (!ts.isOmittedExpression(element)) { + exportedNames = collectExportedVariableInfo(element, uniqueExports, exportedNames); + } + } + } + else if (!ts.isGeneratedIdentifier(decl.name)) { + var text = ts.idText(decl.name); + if (!uniqueExports.get(text)) { + uniqueExports.set(text, true); + exportedNames = ts.append(exportedNames, decl.name); + } + } + return exportedNames; + } + /** Use a sparse array as a multi-map. */ + function multiMapSparseArrayAdd(map, key, value) { + var values = map[key]; + if (values) { + values.push(value); + } + else { + map[key] = values = [value]; + } + return values; + } + /** + * Used in the module transformer to check if an expression is reasonably without sideeffect, + * and thus better to copy into multiple places rather than to cache in a temporary variable + * - this is mostly subjective beyond the requirement that the expression not be sideeffecting + */ + function isSimpleCopiableExpression(expression) { + return ts.isStringLiteralLike(expression) || + expression.kind === 8 /* NumericLiteral */ || + ts.isKeyword(expression.kind) || + ts.isIdentifier(expression); + } + ts.isSimpleCopiableExpression = isSimpleCopiableExpression; + /** + * @param input Template string input strings + * @param args Names which need to be made file-level unique + */ + function helperString(input) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + return function (uniqueName) { + var result = ""; + for (var i = 0; i < args.length; i++) { + result += input[i]; + result += uniqueName(args[i]); + } + result += input[input.length - 1]; + return result; + }; + } + ts.helperString = helperString; +})(ts || (ts = {})); +/*@internal*/ +var ts; +(function (ts) { + var FlattenLevel; + (function (FlattenLevel) { + FlattenLevel[FlattenLevel["All"] = 0] = "All"; + FlattenLevel[FlattenLevel["ObjectRest"] = 1] = "ObjectRest"; + })(FlattenLevel = ts.FlattenLevel || (ts.FlattenLevel = {})); + /** + * Flattens a DestructuringAssignment or a VariableDeclaration to an expression. + * + * @param node The node to flatten. + * @param visitor An optional visitor used to visit initializers. + * @param context The transformation context. + * @param level Indicates the extent to which flattening should occur. + * @param needsValue An optional value indicating whether the value from the right-hand-side of + * the destructuring assignment is needed as part of a larger expression. + * @param createAssignmentCallback An optional callback used to create the assignment expression. + */ + function flattenDestructuringAssignment(node, visitor, context, level, needsValue, createAssignmentCallback) { + var location = node; + var value; + if (ts.isDestructuringAssignment(node)) { + value = node.right; + while (ts.isEmptyArrayLiteral(node.left) || ts.isEmptyObjectLiteral(node.left)) { + if (ts.isDestructuringAssignment(value)) { + location = node = value; + value = node.right; + } + else { + return ts.visitNode(value, visitor, ts.isExpression); + } + } + } + var expressions; + var flattenContext = { + context: context, + level: level, + downlevelIteration: !!context.getCompilerOptions().downlevelIteration, + hoistTempVariables: true, + emitExpression: emitExpression, + emitBindingOrAssignment: emitBindingOrAssignment, + createArrayBindingOrAssignmentPattern: makeArrayAssignmentPattern, + createObjectBindingOrAssignmentPattern: makeObjectAssignmentPattern, + createArrayBindingOrAssignmentElement: makeAssignmentElement, + visitor: visitor + }; + if (value) { + value = ts.visitNode(value, visitor, ts.isExpression); + if (ts.isIdentifier(value) && bindingOrAssignmentElementAssignsToName(node, value.escapedText)) { + // If the right-hand value of the assignment is also an assignment target then + // we need to cache the right-hand value. + value = ensureIdentifier(flattenContext, value, /*reuseIdentifierExpressions*/ false, location); + } + else if (needsValue) { + // If the right-hand value of the destructuring assignment needs to be preserved (as + // is the case when the destructuring assignment is part of a larger expression), + // then we need to cache the right-hand value. + // + // The source map location for the assignment should point to the entire binary + // expression. + value = ensureIdentifier(flattenContext, value, /*reuseIdentifierExpressions*/ true, location); + } + else if (ts.nodeIsSynthesized(node)) { + // Generally, the source map location for a destructuring assignment is the root + // expression. + // + // However, if the root expression is synthesized (as in the case + // of the initializer when transforming a ForOfStatement), then the source map + // location should point to the right-hand value of the expression. + location = value; + } + } + flattenBindingOrAssignmentElement(flattenContext, node, value, location, /*skipInitializer*/ ts.isDestructuringAssignment(node)); + if (value && needsValue) { + if (!ts.some(expressions)) { + return value; + } + expressions.push(value); + } + return ts.aggregateTransformFlags(ts.inlineExpressions(expressions)) || ts.createOmittedExpression(); + function emitExpression(expression) { + // NOTE: this completely disables source maps, but aligns with the behavior of + // `emitAssignment` in the old emitter. + ts.setEmitFlags(expression, 64 /* NoNestedSourceMaps */); + ts.aggregateTransformFlags(expression); + expressions = ts.append(expressions, expression); + } + function emitBindingOrAssignment(target, value, location, original) { + ts.Debug.assertNode(target, createAssignmentCallback ? ts.isIdentifier : ts.isExpression); + var expression = createAssignmentCallback + ? createAssignmentCallback(target, value, location) + : ts.setTextRange(ts.createAssignment(ts.visitNode(target, visitor, ts.isExpression), value), location); + expression.original = original; + emitExpression(expression); + } + } + ts.flattenDestructuringAssignment = flattenDestructuringAssignment; + function bindingOrAssignmentElementAssignsToName(element, escapedName) { + var target = ts.getTargetOfBindingOrAssignmentElement(element); // TODO: GH#18217 + if (ts.isBindingOrAssignmentPattern(target)) { + return bindingOrAssignmentPatternAssignsToName(target, escapedName); + } + else if (ts.isIdentifier(target)) { + return target.escapedText === escapedName; + } + return false; + } + function bindingOrAssignmentPatternAssignsToName(pattern, escapedName) { + var elements = ts.getElementsOfBindingOrAssignmentPattern(pattern); + for (var _i = 0, elements_3 = elements; _i < elements_3.length; _i++) { + var element = elements_3[_i]; + if (bindingOrAssignmentElementAssignsToName(element, escapedName)) { + return true; + } + } + return false; + } + /** + * Flattens a VariableDeclaration or ParameterDeclaration to one or more variable declarations. + * + * @param node The node to flatten. + * @param visitor An optional visitor used to visit initializers. + * @param context The transformation context. + * @param boundValue The value bound to the declaration. + * @param skipInitializer A value indicating whether to ignore the initializer of `node`. + * @param hoistTempVariables Indicates whether temporary variables should not be recorded in-line. + * @param level Indicates the extent to which flattening should occur. + */ + function flattenDestructuringBinding(node, visitor, context, level, rval, hoistTempVariables, skipInitializer) { + if (hoistTempVariables === void 0) { hoistTempVariables = false; } + var pendingExpressions; + var pendingDeclarations = []; + var declarations = []; + var flattenContext = { + context: context, + level: level, + downlevelIteration: !!context.getCompilerOptions().downlevelIteration, + hoistTempVariables: hoistTempVariables, + emitExpression: emitExpression, + emitBindingOrAssignment: emitBindingOrAssignment, + createArrayBindingOrAssignmentPattern: makeArrayBindingPattern, + createObjectBindingOrAssignmentPattern: makeObjectBindingPattern, + createArrayBindingOrAssignmentElement: makeBindingElement, + visitor: visitor + }; + if (ts.isVariableDeclaration(node)) { + var initializer = ts.getInitializerOfBindingOrAssignmentElement(node); + if (initializer && ts.isIdentifier(initializer) && bindingOrAssignmentElementAssignsToName(node, initializer.escapedText)) { + // If the right-hand value of the assignment is also an assignment target then + // we need to cache the right-hand value. + initializer = ensureIdentifier(flattenContext, initializer, /*reuseIdentifierExpressions*/ false, initializer); + node = ts.updateVariableDeclaration(node, node.name, node.type, initializer); + } + } + flattenBindingOrAssignmentElement(flattenContext, node, rval, node, skipInitializer); + if (pendingExpressions) { + var temp = ts.createTempVariable(/*recordTempVariable*/ undefined); + if (hoistTempVariables) { + var value = ts.inlineExpressions(pendingExpressions); + pendingExpressions = undefined; + emitBindingOrAssignment(temp, value, /*location*/ undefined, /*original*/ undefined); + } + else { + context.hoistVariableDeclaration(temp); + var pendingDeclaration = ts.last(pendingDeclarations); + pendingDeclaration.pendingExpressions = ts.append(pendingDeclaration.pendingExpressions, ts.createAssignment(temp, pendingDeclaration.value)); + ts.addRange(pendingDeclaration.pendingExpressions, pendingExpressions); + pendingDeclaration.value = temp; + } + } + for (var _i = 0, pendingDeclarations_1 = pendingDeclarations; _i < pendingDeclarations_1.length; _i++) { + var _a = pendingDeclarations_1[_i], pendingExpressions_1 = _a.pendingExpressions, name = _a.name, value = _a.value, location = _a.location, original = _a.original; + var variable = ts.createVariableDeclaration(name, + /*type*/ undefined, pendingExpressions_1 ? ts.inlineExpressions(ts.append(pendingExpressions_1, value)) : value); + variable.original = original; + ts.setTextRange(variable, location); + if (ts.isIdentifier(name)) { + ts.setEmitFlags(variable, 64 /* NoNestedSourceMaps */); + } + ts.aggregateTransformFlags(variable); + declarations.push(variable); + } + return declarations; + function emitExpression(value) { + pendingExpressions = ts.append(pendingExpressions, value); + } + function emitBindingOrAssignment(target, value, location, original) { + ts.Debug.assertNode(target, ts.isBindingName); + if (pendingExpressions) { + value = ts.inlineExpressions(ts.append(pendingExpressions, value)); + pendingExpressions = undefined; + } + pendingDeclarations.push({ pendingExpressions: pendingExpressions, name: target, value: value, location: location, original: original }); + } + } + ts.flattenDestructuringBinding = flattenDestructuringBinding; + /** + * Flattens a BindingOrAssignmentElement into zero or more bindings or assignments. + * + * @param flattenContext Options used to control flattening. + * @param element The element to flatten. + * @param value The current RHS value to assign to the element. + * @param location The location to use for source maps and comments. + * @param skipInitializer An optional value indicating whether to include the initializer + * for the element. + */ + function flattenBindingOrAssignmentElement(flattenContext, element, value, location, skipInitializer) { + if (!skipInitializer) { + var initializer = ts.visitNode(ts.getInitializerOfBindingOrAssignmentElement(element), flattenContext.visitor, ts.isExpression); + if (initializer) { + // Combine value and initializer + value = value ? createDefaultValueCheck(flattenContext, value, initializer, location) : initializer; + } + else if (!value) { + // Use 'void 0' in absence of value and initializer + value = ts.createVoidZero(); + } + } + var bindingTarget = ts.getTargetOfBindingOrAssignmentElement(element); // TODO: GH#18217 + if (ts.isObjectBindingOrAssignmentPattern(bindingTarget)) { + flattenObjectBindingOrAssignmentPattern(flattenContext, element, bindingTarget, value, location); + } + else if (ts.isArrayBindingOrAssignmentPattern(bindingTarget)) { + flattenArrayBindingOrAssignmentPattern(flattenContext, element, bindingTarget, value, location); + } + else { + flattenContext.emitBindingOrAssignment(bindingTarget, value, location, /*original*/ element); // TODO: GH#18217 + } + } + /** + * Flattens an ObjectBindingOrAssignmentPattern into zero or more bindings or assignments. + * + * @param flattenContext Options used to control flattening. + * @param parent The parent element of the pattern. + * @param pattern The ObjectBindingOrAssignmentPattern to flatten. + * @param value The current RHS value to assign to the element. + * @param location The location to use for source maps and comments. + */ + function flattenObjectBindingOrAssignmentPattern(flattenContext, parent, pattern, value, location) { + var elements = ts.getElementsOfBindingOrAssignmentPattern(pattern); + var numElements = elements.length; + if (numElements !== 1) { + // For anything other than a single-element destructuring we need to generate a temporary + // to ensure value is evaluated exactly once. Additionally, if we have zero elements + // we need to emit *something* to ensure that in case a 'var' keyword was already emitted, + // so in that case, we'll intentionally create that temporary. + var reuseIdentifierExpressions = !ts.isDeclarationBindingElement(parent) || numElements !== 0; + value = ensureIdentifier(flattenContext, value, reuseIdentifierExpressions, location); + } + var bindingElements; + var computedTempVariables; + for (var i = 0; i < numElements; i++) { + var element = elements[i]; + if (!ts.getRestIndicatorOfBindingOrAssignmentElement(element)) { + var propertyName = ts.getPropertyNameOfBindingOrAssignmentElement(element); + if (flattenContext.level >= 1 /* ObjectRest */ + && !(element.transformFlags & (131072 /* ContainsRestOrSpread */ | 262144 /* ContainsObjectRestOrSpread */)) + && !(ts.getTargetOfBindingOrAssignmentElement(element).transformFlags & (131072 /* ContainsRestOrSpread */ | 262144 /* ContainsObjectRestOrSpread */)) + && !ts.isComputedPropertyName(propertyName)) { + bindingElements = ts.append(bindingElements, element); + } + else { + if (bindingElements) { + flattenContext.emitBindingOrAssignment(flattenContext.createObjectBindingOrAssignmentPattern(bindingElements), value, location, pattern); + bindingElements = undefined; + } + var rhsValue = createDestructuringPropertyAccess(flattenContext, value, propertyName); + if (ts.isComputedPropertyName(propertyName)) { + computedTempVariables = ts.append(computedTempVariables, rhsValue.argumentExpression); + } + flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, /*location*/ element); + } + } + else if (i === numElements - 1) { + if (bindingElements) { + flattenContext.emitBindingOrAssignment(flattenContext.createObjectBindingOrAssignmentPattern(bindingElements), value, location, pattern); + bindingElements = undefined; + } + var rhsValue = createRestCall(flattenContext.context, value, elements, computedTempVariables, pattern); // TODO: GH#18217 + flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, element); + } + } + if (bindingElements) { + flattenContext.emitBindingOrAssignment(flattenContext.createObjectBindingOrAssignmentPattern(bindingElements), value, location, pattern); + } + } + /** + * Flattens an ArrayBindingOrAssignmentPattern into zero or more bindings or assignments. + * + * @param flattenContext Options used to control flattening. + * @param parent The parent element of the pattern. + * @param pattern The ArrayBindingOrAssignmentPattern to flatten. + * @param value The current RHS value to assign to the element. + * @param location The location to use for source maps and comments. + */ + function flattenArrayBindingOrAssignmentPattern(flattenContext, parent, pattern, value, location) { + var elements = ts.getElementsOfBindingOrAssignmentPattern(pattern); + var numElements = elements.length; + if (flattenContext.level < 1 /* ObjectRest */ && flattenContext.downlevelIteration) { + // Read the elements of the iterable into an array + value = ensureIdentifier(flattenContext, ts.createReadHelper(flattenContext.context, value, numElements > 0 && ts.getRestIndicatorOfBindingOrAssignmentElement(elements[numElements - 1]) + ? undefined + : numElements, location), + /*reuseIdentifierExpressions*/ false, location); + } + else if (numElements !== 1 && (flattenContext.level < 1 /* ObjectRest */ || numElements === 0) + || ts.every(elements, ts.isOmittedExpression)) { + // For anything other than a single-element destructuring we need to generate a temporary + // to ensure value is evaluated exactly once. Additionally, if we have zero elements + // we need to emit *something* to ensure that in case a 'var' keyword was already emitted, + // so in that case, we'll intentionally create that temporary. + // Or all the elements of the binding pattern are omitted expression such as "var [,] = [1,2]", + // then we will create temporary variable. + var reuseIdentifierExpressions = !ts.isDeclarationBindingElement(parent) || numElements !== 0; + value = ensureIdentifier(flattenContext, value, reuseIdentifierExpressions, location); + } + var bindingElements; + var restContainingElements; + for (var i = 0; i < numElements; i++) { + var element = elements[i]; + if (flattenContext.level >= 1 /* ObjectRest */) { + // If an array pattern contains an ObjectRest, we must cache the result so that we + // can perform the ObjectRest destructuring in a different declaration + if (element.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { + var temp = ts.createTempVariable(/*recordTempVariable*/ undefined); + if (flattenContext.hoistTempVariables) { + flattenContext.context.hoistVariableDeclaration(temp); + } + restContainingElements = ts.append(restContainingElements, [temp, element]); + bindingElements = ts.append(bindingElements, flattenContext.createArrayBindingOrAssignmentElement(temp)); + } + else { + bindingElements = ts.append(bindingElements, element); + } + } + else if (ts.isOmittedExpression(element)) { + continue; + } + else if (!ts.getRestIndicatorOfBindingOrAssignmentElement(element)) { + var rhsValue = ts.createElementAccess(value, i); + flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, /*location*/ element); + } + else if (i === numElements - 1) { + var rhsValue = ts.createArraySlice(value, i); + flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, /*location*/ element); + } + } + if (bindingElements) { + flattenContext.emitBindingOrAssignment(flattenContext.createArrayBindingOrAssignmentPattern(bindingElements), value, location, pattern); + } + if (restContainingElements) { + for (var _i = 0, restContainingElements_1 = restContainingElements; _i < restContainingElements_1.length; _i++) { + var _a = restContainingElements_1[_i], id = _a[0], element = _a[1]; + flattenBindingOrAssignmentElement(flattenContext, element, id, element); + } + } + } + /** + * Creates an expression used to provide a default value if a value is `undefined` at runtime. + * + * @param flattenContext Options used to control flattening. + * @param value The RHS value to test. + * @param defaultValue The default value to use if `value` is `undefined` at runtime. + * @param location The location to use for source maps and comments. + */ + function createDefaultValueCheck(flattenContext, value, defaultValue, location) { + value = ensureIdentifier(flattenContext, value, /*reuseIdentifierExpressions*/ true, location); + return ts.createConditional(ts.createTypeCheck(value, "undefined"), defaultValue, value); + } + /** + * Creates either a PropertyAccessExpression or an ElementAccessExpression for the + * right-hand side of a transformed destructuring assignment. + * + * @link https://tc39.github.io/ecma262/#sec-runtime-semantics-keyeddestructuringassignmentevaluation + * + * @param flattenContext Options used to control flattening. + * @param value The RHS value that is the source of the property. + * @param propertyName The destructuring property name. + */ + function createDestructuringPropertyAccess(flattenContext, value, propertyName) { + if (ts.isComputedPropertyName(propertyName)) { + var argumentExpression = ensureIdentifier(flattenContext, ts.visitNode(propertyName.expression, flattenContext.visitor), /*reuseIdentifierExpressions*/ false, /*location*/ propertyName); + return ts.createElementAccess(value, argumentExpression); + } + else if (ts.isStringOrNumericLiteralLike(propertyName)) { + var argumentExpression = ts.getSynthesizedClone(propertyName); + argumentExpression.text = argumentExpression.text; + return ts.createElementAccess(value, argumentExpression); + } + else { + var name = ts.createIdentifier(ts.idText(propertyName)); + return ts.createPropertyAccess(value, name); + } + } + /** + * Ensures that there exists a declared identifier whose value holds the given expression. + * This function is useful to ensure that the expression's value can be read from in subsequent expressions. + * Unless 'reuseIdentifierExpressions' is false, 'value' will be returned if it is just an identifier. + * + * @param flattenContext Options used to control flattening. + * @param value the expression whose value needs to be bound. + * @param reuseIdentifierExpressions true if identifier expressions can simply be returned; + * false if it is necessary to always emit an identifier. + * @param location The location to use for source maps and comments. + */ + function ensureIdentifier(flattenContext, value, reuseIdentifierExpressions, location) { + if (ts.isIdentifier(value) && reuseIdentifierExpressions) { + return value; + } + else { + var temp = ts.createTempVariable(/*recordTempVariable*/ undefined); + if (flattenContext.hoistTempVariables) { + flattenContext.context.hoistVariableDeclaration(temp); + flattenContext.emitExpression(ts.setTextRange(ts.createAssignment(temp, value), location)); + } + else { + flattenContext.emitBindingOrAssignment(temp, value, location, /*original*/ undefined); + } + return temp; + } + } + function makeArrayBindingPattern(elements) { + ts.Debug.assertEachNode(elements, ts.isArrayBindingElement); + return ts.createArrayBindingPattern(elements); + } + function makeArrayAssignmentPattern(elements) { + return ts.createArrayLiteral(ts.map(elements, ts.convertToArrayAssignmentElement)); + } + function makeObjectBindingPattern(elements) { + ts.Debug.assertEachNode(elements, ts.isBindingElement); + return ts.createObjectBindingPattern(elements); + } + function makeObjectAssignmentPattern(elements) { + return ts.createObjectLiteral(ts.map(elements, ts.convertToObjectAssignmentElement)); + } + function makeBindingElement(name) { + return ts.createBindingElement(/*dotDotDotToken*/ undefined, /*propertyName*/ undefined, name); + } + function makeAssignmentElement(name) { + return name; + } + var restHelper = { + name: "typescript:rest", + scoped: false, + text: "\n var __rest = (this && this.__rest) || function (s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) if (e.indexOf(p[i]) < 0)\n t[p[i]] = s[p[i]];\n return t;\n };" + }; + /** Given value: o, propName: p, pattern: { a, b, ...p } from the original statement + * `{ a, b, ...p } = o`, create `p = __rest(o, ["a", "b"]);` + */ + function createRestCall(context, value, elements, computedTempVariables, location) { + context.requestEmitHelper(restHelper); + var propertyNames = []; + var computedTempVariableOffset = 0; + for (var i = 0; i < elements.length - 1; i++) { + var propertyName = ts.getPropertyNameOfBindingOrAssignmentElement(elements[i]); + if (propertyName) { + if (ts.isComputedPropertyName(propertyName)) { + var temp = computedTempVariables[computedTempVariableOffset]; + computedTempVariableOffset++; + // typeof _tmp === "symbol" ? _tmp : _tmp + "" + propertyNames.push(ts.createConditional(ts.createTypeCheck(temp, "symbol"), temp, ts.createAdd(temp, ts.createLiteral("")))); + } + else { + propertyNames.push(ts.createLiteral(propertyName)); + } + } + } + return ts.createCall(ts.getHelperName("__rest"), + /*typeArguments*/ undefined, [ + value, + ts.setTextRange(ts.createArrayLiteral(propertyNames), location) + ]); + } +})(ts || (ts = {})); +/*@internal*/ +var ts; +(function (ts) { + /** + * Indicates whether to emit type metadata in the new format. + */ + var USE_NEW_TYPE_METADATA_FORMAT = false; + var TypeScriptSubstitutionFlags; + (function (TypeScriptSubstitutionFlags) { + /** Enables substitutions for decorated classes. */ + TypeScriptSubstitutionFlags[TypeScriptSubstitutionFlags["ClassAliases"] = 1] = "ClassAliases"; + /** Enables substitutions for namespace exports. */ + TypeScriptSubstitutionFlags[TypeScriptSubstitutionFlags["NamespaceExports"] = 2] = "NamespaceExports"; + /* Enables substitutions for unqualified enum members */ + TypeScriptSubstitutionFlags[TypeScriptSubstitutionFlags["NonQualifiedEnumMembers"] = 8] = "NonQualifiedEnumMembers"; + })(TypeScriptSubstitutionFlags || (TypeScriptSubstitutionFlags = {})); + var ClassFacts; + (function (ClassFacts) { + ClassFacts[ClassFacts["None"] = 0] = "None"; + ClassFacts[ClassFacts["HasStaticInitializedProperties"] = 1] = "HasStaticInitializedProperties"; + ClassFacts[ClassFacts["HasConstructorDecorators"] = 2] = "HasConstructorDecorators"; + ClassFacts[ClassFacts["HasMemberDecorators"] = 4] = "HasMemberDecorators"; + ClassFacts[ClassFacts["IsExportOfNamespace"] = 8] = "IsExportOfNamespace"; + ClassFacts[ClassFacts["IsNamedExternalExport"] = 16] = "IsNamedExternalExport"; + ClassFacts[ClassFacts["IsDefaultExternalExport"] = 32] = "IsDefaultExternalExport"; + ClassFacts[ClassFacts["IsDerivedClass"] = 64] = "IsDerivedClass"; + ClassFacts[ClassFacts["UseImmediatelyInvokedFunctionExpression"] = 128] = "UseImmediatelyInvokedFunctionExpression"; + ClassFacts[ClassFacts["HasAnyDecorators"] = 6] = "HasAnyDecorators"; + ClassFacts[ClassFacts["NeedsName"] = 5] = "NeedsName"; + ClassFacts[ClassFacts["MayNeedImmediatelyInvokedFunctionExpression"] = 7] = "MayNeedImmediatelyInvokedFunctionExpression"; + ClassFacts[ClassFacts["IsExported"] = 56] = "IsExported"; + })(ClassFacts || (ClassFacts = {})); + function transformTypeScript(context) { + var startLexicalEnvironment = context.startLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; + var resolver = context.getEmitResolver(); + var compilerOptions = context.getCompilerOptions(); + var strictNullChecks = ts.getStrictOptionValue(compilerOptions, "strictNullChecks"); + var languageVersion = ts.getEmitScriptTarget(compilerOptions); + var moduleKind = ts.getEmitModuleKind(compilerOptions); + // Save the previous transformation hooks. + var previousOnEmitNode = context.onEmitNode; + var previousOnSubstituteNode = context.onSubstituteNode; + // Set new transformation hooks. + context.onEmitNode = onEmitNode; + context.onSubstituteNode = onSubstituteNode; + // Enable substitution for property/element access to emit const enum values. + context.enableSubstitution(189 /* PropertyAccessExpression */); + context.enableSubstitution(190 /* ElementAccessExpression */); + // These variables contain state that changes as we descend into the tree. + var currentSourceFile; + var currentNamespace; + var currentNamespaceContainerName; + var currentLexicalScope; + var currentNameScope; + var currentScopeFirstDeclarationsOfName; + /** + * Keeps track of whether expression substitution has been enabled for specific edge cases. + * They are persisted between each SourceFile transformation and should not be reset. + */ + var enabledSubstitutions; + /** + * A map that keeps track of aliases created for classes with decorators to avoid issues + * with the double-binding behavior of classes. + */ + var classAliases; + /** + * Keeps track of whether we are within any containing namespaces when performing + * just-in-time substitution while printing an expression identifier. + */ + var applicableSubstitutions; + /** + * Tracks what computed name expressions originating from elided names must be inlined + * at the next execution site, in document order + */ + var pendingExpressions; + return transformSourceFileOrBundle; + function transformSourceFileOrBundle(node) { + if (node.kind === 280 /* Bundle */) { + return transformBundle(node); + } + return transformSourceFile(node); + } + function transformBundle(node) { + return ts.createBundle(node.sourceFiles.map(transformSourceFile), ts.mapDefined(node.prepends, function (prepend) { + if (prepend.kind === 282 /* InputFiles */) { + return ts.createUnparsedSourceFile(prepend.javascriptText, prepend.javascriptMapPath, prepend.javascriptMapText); + } + return prepend; + })); + } + /** + * Transform TypeScript-specific syntax in a SourceFile. + * + * @param node A SourceFile node. + */ + function transformSourceFile(node) { + if (node.isDeclarationFile) { + return node; + } + currentSourceFile = node; + var visited = saveStateAndInvoke(node, visitSourceFile); + ts.addEmitHelpers(visited, context.readEmitHelpers()); + currentSourceFile = undefined; + return visited; + } + /** + * Visits a node, saving and restoring state variables on the stack. + * + * @param node The node to visit. + */ + function saveStateAndInvoke(node, f) { + // Save state + var savedCurrentScope = currentLexicalScope; + var savedCurrentNameScope = currentNameScope; + var savedCurrentScopeFirstDeclarationsOfName = currentScopeFirstDeclarationsOfName; + // Handle state changes before visiting a node. + onBeforeVisitNode(node); + var visited = f(node); + // Restore state + if (currentLexicalScope !== savedCurrentScope) { + currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName; + } + currentLexicalScope = savedCurrentScope; + currentNameScope = savedCurrentNameScope; + return visited; + } + /** + * Performs actions that should always occur immediately before visiting a node. + * + * @param node The node to visit. + */ + function onBeforeVisitNode(node) { + switch (node.kind) { + case 279 /* SourceFile */: + case 246 /* CaseBlock */: + case 245 /* ModuleBlock */: + case 218 /* Block */: + currentLexicalScope = node; + currentNameScope = undefined; + currentScopeFirstDeclarationsOfName = undefined; + break; + case 240 /* ClassDeclaration */: + case 239 /* FunctionDeclaration */: + if (ts.hasModifier(node, 2 /* Ambient */)) { + break; + } + // Record these declarations provided that they have a name. + if (node.name) { + recordEmittedDeclarationInScope(node); + } + else { + // These nodes should always have names unless they are default-exports; + // however, class declaration parsing allows for undefined names, so syntactically invalid + // programs may also have an undefined name. + ts.Debug.assert(node.kind === 240 /* ClassDeclaration */ || ts.hasModifier(node, 512 /* Default */)); + } + if (ts.isClassDeclaration(node)) { + // XXX: should probably also cover interfaces and type aliases that can have type variables? + currentNameScope = node; + } + break; + } + } + /** + * General-purpose node visitor. + * + * @param node The node to visit. + */ + function visitor(node) { + return saveStateAndInvoke(node, visitorWorker); + } + /** + * Visits and possibly transforms any node. + * + * @param node The node to visit. + */ + function visitorWorker(node) { + if (node.transformFlags & 1 /* TypeScript */) { + // This node is explicitly marked as TypeScript, so we should transform the node. + return visitTypeScript(node); + } + else if (node.transformFlags & 2 /* ContainsTypeScript */) { + // This node contains TypeScript, so we should visit its children. + return ts.visitEachChild(node, visitor, context); + } + return node; + } + /** + * Specialized visitor that visits the immediate children of a SourceFile. + * + * @param node The node to visit. + */ + function sourceElementVisitor(node) { + return saveStateAndInvoke(node, sourceElementVisitorWorker); + } + /** + * Specialized visitor that visits the immediate children of a SourceFile. + * + * @param node The node to visit. + */ + function sourceElementVisitorWorker(node) { + switch (node.kind) { + case 249 /* ImportDeclaration */: + case 248 /* ImportEqualsDeclaration */: + case 254 /* ExportAssignment */: + case 255 /* ExportDeclaration */: + return visitEllidableStatement(node); + default: + return visitorWorker(node); + } + } + function visitEllidableStatement(node) { + var parsed = ts.getParseTreeNode(node); + if (parsed !== node) { + // If the node has been transformed by a `before` transformer, perform no ellision on it + // As the type information we would attempt to lookup to perform ellision is potentially unavailable for the synthesized nodes + // We do not reuse `visitorWorker`, as the ellidable statement syntax kinds are technically unrecognized by the switch-case in `visitTypeScript`, + // and will trigger debug failures when debug verbosity is turned up + if (node.transformFlags & 2 /* ContainsTypeScript */) { + // This node contains TypeScript, so we should visit its children. + return ts.visitEachChild(node, visitor, context); + } + // Otherwise, we can just return the node + return node; + } + switch (node.kind) { + case 249 /* ImportDeclaration */: + return visitImportDeclaration(node); + case 248 /* ImportEqualsDeclaration */: + return visitImportEqualsDeclaration(node); + case 254 /* ExportAssignment */: + return visitExportAssignment(node); + case 255 /* ExportDeclaration */: + return visitExportDeclaration(node); + default: + ts.Debug.fail("Unhandled ellided statement"); + } + } + /** + * Specialized visitor that visits the immediate children of a namespace. + * + * @param node The node to visit. + */ + function namespaceElementVisitor(node) { + return saveStateAndInvoke(node, namespaceElementVisitorWorker); + } + /** + * Specialized visitor that visits the immediate children of a namespace. + * + * @param node The node to visit. + */ + function namespaceElementVisitorWorker(node) { + if (node.kind === 255 /* ExportDeclaration */ || + node.kind === 249 /* ImportDeclaration */ || + node.kind === 250 /* ImportClause */ || + (node.kind === 248 /* ImportEqualsDeclaration */ && + node.moduleReference.kind === 259 /* ExternalModuleReference */)) { + // do not emit ES6 imports and exports since they are illegal inside a namespace + return undefined; + } + else if (node.transformFlags & 1 /* TypeScript */ || ts.hasModifier(node, 1 /* Export */)) { + // This node is explicitly marked as TypeScript, or is exported at the namespace + // level, so we should transform the node. + return visitTypeScript(node); + } + else if (node.transformFlags & 2 /* ContainsTypeScript */) { + // This node contains TypeScript, so we should visit its children. + return ts.visitEachChild(node, visitor, context); + } + return node; + } + /** + * Specialized visitor that visits the immediate children of a class with TypeScript syntax. + * + * @param node The node to visit. + */ + function classElementVisitor(node) { + return saveStateAndInvoke(node, classElementVisitorWorker); + } + /** + * Specialized visitor that visits the immediate children of a class with TypeScript syntax. + * + * @param node The node to visit. + */ + function classElementVisitorWorker(node) { + switch (node.kind) { + case 157 /* Constructor */: + // TypeScript constructors are transformed in `visitClassDeclaration`. + // We elide them here as `visitorWorker` checks transform flags, which could + // erronously include an ES6 constructor without TypeScript syntax. + return undefined; + case 154 /* PropertyDeclaration */: + case 162 /* IndexSignature */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 156 /* MethodDeclaration */: + // Fallback to the default visit behavior. + return visitorWorker(node); + case 217 /* SemicolonClassElement */: + return node; + default: + return ts.Debug.failBadSyntaxKind(node); + } + } + function modifierVisitor(node) { + if (ts.modifierToFlag(node.kind) & 2270 /* TypeScriptModifier */) { + return undefined; + } + else if (currentNamespace && node.kind === 85 /* ExportKeyword */) { + return undefined; + } + return node; + } + /** + * Branching visitor, visits a TypeScript syntax node. + * + * @param node The node to visit. + */ + function visitTypeScript(node) { + if (ts.hasModifier(node, 2 /* Ambient */) && ts.isStatement(node)) { + // TypeScript ambient declarations are elided, but some comments may be preserved. + // See the implementation of `getLeadingComments` in comments.ts for more details. + return ts.createNotEmittedStatement(node); + } + switch (node.kind) { + case 85 /* ExportKeyword */: + case 80 /* DefaultKeyword */: + // ES6 export and default modifiers are elided when inside a namespace. + return currentNamespace ? undefined : node; + case 115 /* PublicKeyword */: + case 113 /* PrivateKeyword */: + case 114 /* ProtectedKeyword */: + case 118 /* AbstractKeyword */: + case 77 /* ConstKeyword */: + case 125 /* DeclareKeyword */: + case 133 /* ReadonlyKeyword */: + // TypeScript accessibility and readonly modifiers are elided. + case 169 /* ArrayType */: + case 170 /* TupleType */: + case 171 /* OptionalType */: + case 172 /* RestType */: + case 168 /* TypeLiteral */: + case 163 /* TypePredicate */: + case 150 /* TypeParameter */: + case 120 /* AnyKeyword */: + case 143 /* UnknownKeyword */: + case 123 /* BooleanKeyword */: + case 138 /* StringKeyword */: + case 135 /* NumberKeyword */: + case 132 /* NeverKeyword */: + case 106 /* VoidKeyword */: + case 139 /* SymbolKeyword */: + case 166 /* ConstructorType */: + case 165 /* FunctionType */: + case 167 /* TypeQuery */: + case 164 /* TypeReference */: + case 173 /* UnionType */: + case 174 /* IntersectionType */: + case 175 /* ConditionalType */: + case 177 /* ParenthesizedType */: + case 178 /* ThisType */: + case 179 /* TypeOperator */: + case 180 /* IndexedAccessType */: + case 181 /* MappedType */: + case 182 /* LiteralType */: + // TypeScript type nodes are elided. + case 162 /* IndexSignature */: + // TypeScript index signatures are elided. + case 152 /* Decorator */: + // TypeScript decorators are elided. They will be emitted as part of visitClassDeclaration. + case 242 /* TypeAliasDeclaration */: + // TypeScript type-only declarations are elided. + return undefined; + case 154 /* PropertyDeclaration */: + // TypeScript property declarations are elided. However their names are still visited, and can potentially be retained if they could have sideeffects + return visitPropertyDeclaration(node); + case 247 /* NamespaceExportDeclaration */: + // TypeScript namespace export declarations are elided. + return undefined; + case 157 /* Constructor */: + return visitConstructor(node); + case 241 /* InterfaceDeclaration */: + // TypeScript interfaces are elided, but some comments may be preserved. + // See the implementation of `getLeadingComments` in comments.ts for more details. + return ts.createNotEmittedStatement(node); + case 240 /* ClassDeclaration */: + // This is a class declaration with TypeScript syntax extensions. + // + // TypeScript class syntax extensions include: + // - decorators + // - optional `implements` heritage clause + // - parameter property assignments in the constructor + // - property declarations + // - index signatures + // - method overload signatures + return visitClassDeclaration(node); + case 209 /* ClassExpression */: + // This is a class expression with TypeScript syntax extensions. + // + // TypeScript class syntax extensions include: + // - decorators + // - optional `implements` heritage clause + // - parameter property assignments in the constructor + // - property declarations + // - index signatures + // - method overload signatures + return visitClassExpression(node); + case 273 /* HeritageClause */: + // This is a heritage clause with TypeScript syntax extensions. + // + // TypeScript heritage clause extensions include: + // - `implements` clause + return visitHeritageClause(node); + case 211 /* ExpressionWithTypeArguments */: + // TypeScript supports type arguments on an expression in an `extends` heritage clause. + return visitExpressionWithTypeArguments(node); + case 156 /* MethodDeclaration */: + // TypeScript method declarations may have decorators, modifiers + // or type annotations. + return visitMethodDeclaration(node); + case 158 /* GetAccessor */: + // Get Accessors can have TypeScript modifiers, decorators, and type annotations. + return visitGetAccessor(node); + case 159 /* SetAccessor */: + // Set Accessors can have TypeScript modifiers and type annotations. + return visitSetAccessor(node); + case 239 /* FunctionDeclaration */: + // Typescript function declarations can have modifiers, decorators, and type annotations. + return visitFunctionDeclaration(node); + case 196 /* FunctionExpression */: + // TypeScript function expressions can have modifiers and type annotations. + return visitFunctionExpression(node); + case 197 /* ArrowFunction */: + // TypeScript arrow functions can have modifiers and type annotations. + return visitArrowFunction(node); + case 151 /* Parameter */: + // This is a parameter declaration with TypeScript syntax extensions. + // + // TypeScript parameter declaration syntax extensions include: + // - decorators + // - accessibility modifiers + // - the question mark (?) token for optional parameters + // - type annotations + // - this parameters + return visitParameter(node); + case 195 /* ParenthesizedExpression */: + // ParenthesizedExpressions are TypeScript if their expression is a + // TypeAssertion or AsExpression + return visitParenthesizedExpression(node); + case 194 /* TypeAssertionExpression */: + case 212 /* AsExpression */: + // TypeScript type assertions are removed, but their subtrees are preserved. + return visitAssertionExpression(node); + case 191 /* CallExpression */: + return visitCallExpression(node); + case 192 /* NewExpression */: + return visitNewExpression(node); + case 193 /* TaggedTemplateExpression */: + return visitTaggedTemplateExpression(node); + case 213 /* NonNullExpression */: + // TypeScript non-null expressions are removed, but their subtrees are preserved. + return visitNonNullExpression(node); + case 243 /* EnumDeclaration */: + // TypeScript enum declarations do not exist in ES6 and must be rewritten. + return visitEnumDeclaration(node); + case 219 /* VariableStatement */: + // TypeScript namespace exports for variable statements must be transformed. + return visitVariableStatement(node); + case 237 /* VariableDeclaration */: + return visitVariableDeclaration(node); + case 244 /* ModuleDeclaration */: + // TypeScript namespace declarations must be transformed. + return visitModuleDeclaration(node); + case 248 /* ImportEqualsDeclaration */: + // TypeScript namespace or external module import. + return visitImportEqualsDeclaration(node); + default: + return ts.Debug.failBadSyntaxKind(node); + } + } + function visitSourceFile(node) { + var alwaysStrict = ts.getStrictOptionValue(compilerOptions, "alwaysStrict") && + !(ts.isExternalModule(node) && moduleKind >= ts.ModuleKind.ES2015) && + !ts.isJsonSourceFile(node); + return ts.updateSourceFileNode(node, ts.visitLexicalEnvironment(node.statements, sourceElementVisitor, context, /*start*/ 0, alwaysStrict)); + } + /** + * Tests whether we should emit a __decorate call for a class declaration. + */ + function shouldEmitDecorateCallForClass(node) { + if (node.decorators && node.decorators.length > 0) { + return true; + } + var constructor = ts.getFirstConstructorWithBody(node); + if (constructor) { + return ts.forEach(constructor.parameters, shouldEmitDecorateCallForParameter); + } + return false; + } + /** + * Tests whether we should emit a __decorate call for a parameter declaration. + */ + function shouldEmitDecorateCallForParameter(parameter) { + return parameter.decorators !== undefined && parameter.decorators.length > 0; + } + function getClassFacts(node, staticProperties) { + var facts = 0 /* None */; + if (ts.some(staticProperties)) + facts |= 1 /* HasStaticInitializedProperties */; + var extendsClauseElement = ts.getEffectiveBaseTypeNode(node); + if (extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 96 /* NullKeyword */) + facts |= 64 /* IsDerivedClass */; + if (shouldEmitDecorateCallForClass(node)) + facts |= 2 /* HasConstructorDecorators */; + if (ts.childIsDecorated(node)) + facts |= 4 /* HasMemberDecorators */; + if (isExportOfNamespace(node)) + facts |= 8 /* IsExportOfNamespace */; + else if (isDefaultExternalModuleExport(node)) + facts |= 32 /* IsDefaultExternalExport */; + else if (isNamedExternalModuleExport(node)) + facts |= 16 /* IsNamedExternalExport */; + if (languageVersion <= 1 /* ES5 */ && (facts & 7 /* MayNeedImmediatelyInvokedFunctionExpression */)) + facts |= 128 /* UseImmediatelyInvokedFunctionExpression */; + return facts; + } + /** + * Transforms a class declaration with TypeScript syntax into compatible ES6. + * + * This function will only be called when one of the following conditions are met: + * - The class has decorators. + * - The class has property declarations with initializers. + * - The class contains a constructor that contains parameters with accessibility modifiers. + * - The class is an export in a TypeScript namespace. + * + * @param node The node to transform. + */ + function visitClassDeclaration(node) { + var savedPendingExpressions = pendingExpressions; + pendingExpressions = undefined; + var staticProperties = getInitializedProperties(node, /*isStatic*/ true); + var facts = getClassFacts(node, staticProperties); + if (facts & 128 /* UseImmediatelyInvokedFunctionExpression */) { + context.startLexicalEnvironment(); + } + var name = node.name || (facts & 5 /* NeedsName */ ? ts.getGeneratedNameForNode(node) : undefined); + var classStatement = facts & 2 /* HasConstructorDecorators */ + ? createClassDeclarationHeadWithDecorators(node, name, facts) + : createClassDeclarationHeadWithoutDecorators(node, name, facts); + var statements = [classStatement]; + // Write any pending expressions from elided or moved computed property names + if (ts.some(pendingExpressions)) { + statements.push(ts.createExpressionStatement(ts.inlineExpressions(pendingExpressions))); + } + pendingExpressions = savedPendingExpressions; + // Emit static property assignment. Because classDeclaration is lexically evaluated, + // it is safe to emit static property assignment after classDeclaration + // From ES6 specification: + // HasLexicalDeclaration (N) : Determines if the argument identifier has a binding in this environment record that was created using + // a lexical declaration such as a LexicalDeclaration or a ClassDeclaration. + if (facts & 1 /* HasStaticInitializedProperties */) { + addInitializedPropertyStatements(statements, staticProperties, facts & 128 /* UseImmediatelyInvokedFunctionExpression */ ? ts.getInternalName(node) : ts.getLocalName(node)); + } + // Write any decorators of the node. + addClassElementDecorationStatements(statements, node, /*isStatic*/ false); + addClassElementDecorationStatements(statements, node, /*isStatic*/ true); + addConstructorDecorationStatement(statements, node); + if (facts & 128 /* UseImmediatelyInvokedFunctionExpression */) { + // When we emit a TypeScript class down to ES5, we must wrap it in an IIFE so that the + // 'es2015' transformer can properly nest static initializers and decorators. The result + // looks something like: + // + // var C = function () { + // class C { + // } + // C.static_prop = 1; + // return C; + // }(); + // + var closingBraceLocation = ts.createTokenRange(ts.skipTrivia(currentSourceFile.text, node.members.end), 19 /* CloseBraceToken */); + var localName = ts.getInternalName(node); + // The following partially-emitted expression exists purely to align our sourcemap + // emit with the original emitter. + var outer = ts.createPartiallyEmittedExpression(localName); + outer.end = closingBraceLocation.end; + ts.setEmitFlags(outer, 1536 /* NoComments */); + var statement = ts.createReturn(outer); + statement.pos = closingBraceLocation.pos; + ts.setEmitFlags(statement, 1536 /* NoComments */ | 384 /* NoTokenSourceMaps */); + statements.push(statement); + ts.addStatementsAfterPrologue(statements, context.endLexicalEnvironment()); + var iife = ts.createImmediatelyInvokedArrowFunction(statements); + ts.setEmitFlags(iife, 33554432 /* TypeScriptClassWrapper */); + var varStatement = ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ false), + /*type*/ undefined, iife) + ])); + ts.setOriginalNode(varStatement, node); + ts.setCommentRange(varStatement, node); + ts.setSourceMapRange(varStatement, ts.moveRangePastDecorators(node)); + ts.startOnNewLine(varStatement); + statements = [varStatement]; + } + // If the class is exported as part of a TypeScript namespace, emit the namespace export. + // Otherwise, if the class was exported at the top level and was decorated, emit an export + // declaration or export default for the class. + if (facts & 8 /* IsExportOfNamespace */) { + addExportMemberAssignment(statements, node); + } + else if (facts & 128 /* UseImmediatelyInvokedFunctionExpression */ || facts & 2 /* HasConstructorDecorators */) { + if (facts & 32 /* IsDefaultExternalExport */) { + statements.push(ts.createExportDefault(ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true))); + } + else if (facts & 16 /* IsNamedExternalExport */) { + statements.push(ts.createExternalModuleExport(ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true))); + } + } + if (statements.length > 1) { + // Add a DeclarationMarker as a marker for the end of the declaration + statements.push(ts.createEndOfDeclarationMarker(node)); + ts.setEmitFlags(classStatement, ts.getEmitFlags(classStatement) | 4194304 /* HasEndOfDeclarationMarker */); + } + return ts.singleOrMany(statements); + } + /** + * Transforms a non-decorated class declaration and appends the resulting statements. + * + * @param node A ClassDeclaration node. + * @param name The name of the class. + * @param facts Precomputed facts about the class. + */ + function createClassDeclarationHeadWithoutDecorators(node, name, facts) { + // ${modifiers} class ${name} ${heritageClauses} { + // ${members} + // } + // we do not emit modifiers on the declaration if we are emitting an IIFE + var modifiers = !(facts & 128 /* UseImmediatelyInvokedFunctionExpression */) + ? ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier) + : undefined; + var classDeclaration = ts.createClassDeclaration( + /*decorators*/ undefined, modifiers, name, + /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node, (facts & 64 /* IsDerivedClass */) !== 0)); + // To better align with the old emitter, we should not emit a trailing source map + // entry if the class has static properties. + var emitFlags = ts.getEmitFlags(node); + if (facts & 1 /* HasStaticInitializedProperties */) { + emitFlags |= 32 /* NoTrailingSourceMap */; + } + ts.setTextRange(classDeclaration, node); + ts.setOriginalNode(classDeclaration, node); + ts.setEmitFlags(classDeclaration, emitFlags); + return classDeclaration; + } + /** + * Transforms a decorated class declaration and appends the resulting statements. If + * the class requires an alias to avoid issues with double-binding, the alias is returned. + */ + function createClassDeclarationHeadWithDecorators(node, name, facts) { + // When we emit an ES6 class that has a class decorator, we must tailor the + // emit to certain specific cases. + // + // In the simplest case, we emit the class declaration as a let declaration, and + // evaluate decorators after the close of the class body: + // + // [Example 1] + // --------------------------------------------------------------------- + // TypeScript | Javascript + // --------------------------------------------------------------------- + // @dec | let C = class C { + // class C { | } + // } | C = __decorate([dec], C); + // --------------------------------------------------------------------- + // @dec | let C = class C { + // export class C { | } + // } | C = __decorate([dec], C); + // | export { C }; + // --------------------------------------------------------------------- + // + // If a class declaration contains a reference to itself *inside* of the class body, + // this introduces two bindings to the class: One outside of the class body, and one + // inside of the class body. If we apply decorators as in [Example 1] above, there + // is the possibility that the decorator `dec` will return a new value for the + // constructor, which would result in the binding inside of the class no longer + // pointing to the same reference as the binding outside of the class. + // + // As a result, we must instead rewrite all references to the class *inside* of the + // class body to instead point to a local temporary alias for the class: + // + // [Example 2] + // --------------------------------------------------------------------- + // TypeScript | Javascript + // --------------------------------------------------------------------- + // @dec | let C = C_1 = class C { + // class C { | static x() { return C_1.y; } + // static x() { return C.y; } | } + // static y = 1; | C.y = 1; + // } | C = C_1 = __decorate([dec], C); + // | var C_1; + // --------------------------------------------------------------------- + // @dec | let C = class C { + // export class C { | static x() { return C_1.y; } + // static x() { return C.y; } | } + // static y = 1; | C.y = 1; + // } | C = C_1 = __decorate([dec], C); + // | export { C }; + // | var C_1; + // --------------------------------------------------------------------- + // + // If a class declaration is the default export of a module, we instead emit + // the export after the decorated declaration: + // + // [Example 3] + // --------------------------------------------------------------------- + // TypeScript | Javascript + // --------------------------------------------------------------------- + // @dec | let default_1 = class { + // export default class { | } + // } | default_1 = __decorate([dec], default_1); + // | export default default_1; + // --------------------------------------------------------------------- + // @dec | let C = class C { + // export default class C { | } + // } | C = __decorate([dec], C); + // | export default C; + // --------------------------------------------------------------------- + // + // If the class declaration is the default export and a reference to itself + // inside of the class body, we must emit both an alias for the class *and* + // move the export after the declaration: + // + // [Example 4] + // --------------------------------------------------------------------- + // TypeScript | Javascript + // --------------------------------------------------------------------- + // @dec | let C = class C { + // export default class C { | static x() { return C_1.y; } + // static x() { return C.y; } | } + // static y = 1; | C.y = 1; + // } | C = C_1 = __decorate([dec], C); + // | export default C; + // | var C_1; + // --------------------------------------------------------------------- + // + var location = ts.moveRangePastDecorators(node); + var classAlias = getClassAliasIfNeeded(node); + var declName = ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true); + // ... = class ${name} ${heritageClauses} { + // ${members} + // } + var heritageClauses = ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause); + var members = transformClassMembers(node, (facts & 64 /* IsDerivedClass */) !== 0); + var classExpression = ts.createClassExpression(/*modifiers*/ undefined, name, /*typeParameters*/ undefined, heritageClauses, members); + ts.setOriginalNode(classExpression, node); + ts.setTextRange(classExpression, location); + // let ${name} = ${classExpression} where name is either declaredName if the class doesn't contain self-reference + // or decoratedClassAlias if the class contain self-reference. + var statement = ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(declName, + /*type*/ undefined, classAlias ? ts.createAssignment(classAlias, classExpression) : classExpression) + ], 1 /* Let */)); + ts.setOriginalNode(statement, node); + ts.setTextRange(statement, location); + ts.setCommentRange(statement, node); + return statement; + } + /** + * Transforms a class expression with TypeScript syntax into compatible ES6. + * + * This function will only be called when one of the following conditions are met: + * - The class has property declarations with initializers. + * - The class contains a constructor that contains parameters with accessibility modifiers. + * + * @param node The node to transform. + */ + function visitClassExpression(node) { + var savedPendingExpressions = pendingExpressions; + pendingExpressions = undefined; + var staticProperties = getInitializedProperties(node, /*isStatic*/ true); + var heritageClauses = ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause); + var members = transformClassMembers(node, ts.some(heritageClauses, function (c) { return c.token === 86 /* ExtendsKeyword */; })); + var classExpression = ts.createClassExpression( + /*modifiers*/ undefined, node.name, + /*typeParameters*/ undefined, heritageClauses, members); + ts.setOriginalNode(classExpression, node); + ts.setTextRange(classExpression, node); + if (ts.some(staticProperties) || ts.some(pendingExpressions)) { + var expressions = []; + var isClassWithConstructorReference = resolver.getNodeCheckFlags(node) & 16777216 /* ClassWithConstructorReference */; + var temp = ts.createTempVariable(hoistVariableDeclaration, !!isClassWithConstructorReference); + if (isClassWithConstructorReference) { + // record an alias as the class name is not in scope for statics. + enableSubstitutionForClassAliases(); + var alias = ts.getSynthesizedClone(temp); + alias.autoGenerateFlags &= ~8 /* ReservedInNestedScopes */; + classAliases[ts.getOriginalNodeId(node)] = alias; + } + // To preserve the behavior of the old emitter, we explicitly indent + // the body of a class with static initializers. + ts.setEmitFlags(classExpression, 65536 /* Indented */ | ts.getEmitFlags(classExpression)); + expressions.push(ts.startOnNewLine(ts.createAssignment(temp, classExpression))); + // Add any pending expressions leftover from elided or relocated computed property names + ts.addRange(expressions, ts.map(pendingExpressions, ts.startOnNewLine)); + pendingExpressions = savedPendingExpressions; + ts.addRange(expressions, generateInitializedPropertyExpressions(staticProperties, temp)); + expressions.push(ts.startOnNewLine(temp)); + return ts.inlineExpressions(expressions); + } + pendingExpressions = savedPendingExpressions; + return classExpression; + } + /** + * Transforms the members of a class. + * + * @param node The current class. + * @param isDerivedClass A value indicating whether the class has an extends clause that does not extend 'null'. + */ + function transformClassMembers(node, isDerivedClass) { + var members = []; + var constructor = transformConstructor(node, isDerivedClass); + if (constructor) { + members.push(constructor); + } + ts.addRange(members, ts.visitNodes(node.members, classElementVisitor, ts.isClassElement)); + return ts.setTextRange(ts.createNodeArray(members), /*location*/ node.members); + } + /** + * Transforms (or creates) a constructor for a class. + * + * @param node The current class. + * @param isDerivedClass A value indicating whether the class has an extends clause that does not extend 'null'. + */ + function transformConstructor(node, isDerivedClass) { + // Check if we have property assignment inside class declaration. + // If there is a property assignment, we need to emit constructor whether users define it or not + // If there is no property assignment, we can omit constructor if users do not define it + var constructor = ts.getFirstConstructorWithBody(node); + var hasInstancePropertyWithInitializer = ts.forEach(node.members, isInstanceInitializedProperty); + var hasParameterPropertyAssignments = constructor && + constructor.transformFlags & 4096 /* ContainsTypeScriptClassSyntax */ && + ts.forEach(constructor.parameters, isParameterWithPropertyAssignment); + // If the class does not contain nodes that require a synthesized constructor, + // accept the current constructor if it exists. + if (!hasInstancePropertyWithInitializer && !hasParameterPropertyAssignments) { + return ts.visitEachChild(constructor, visitor, context); + } + var parameters = transformConstructorParameters(constructor); + var body = transformConstructorBody(node, constructor, isDerivedClass); + // constructor(${parameters}) { + // ${body} + // } + return ts.startOnNewLine(ts.setOriginalNode(ts.setTextRange(ts.createConstructor( + /*decorators*/ undefined, + /*modifiers*/ undefined, parameters, body), constructor || node), constructor)); + } + /** + * Transforms (or creates) the parameters for the constructor of a class with + * parameter property assignments or instance property initializers. + * + * @param constructor The constructor declaration. + */ + function transformConstructorParameters(constructor) { + // The ES2015 spec specifies in 14.5.14. Runtime Semantics: ClassDefinitionEvaluation: + // If constructor is empty, then + // If ClassHeritag_eopt is present and protoParent is not null, then + // Let constructor be the result of parsing the source text + // constructor(...args) { super (...args);} + // using the syntactic grammar with the goal symbol MethodDefinition[~Yield]. + // Else, + // Let constructor be the result of parsing the source text + // constructor( ){ } + // using the syntactic grammar with the goal symbol MethodDefinition[~Yield]. + // + // While we could emit the '...args' rest parameter, certain later tools in the pipeline might + // downlevel the '...args' portion less efficiently by naively copying the contents of 'arguments' to an array. + // Instead, we'll avoid using a rest parameter and spread into the super call as + // 'super(...arguments)' instead of 'super(...args)', as you can see in "transformConstructorBody". + return ts.visitParameterList(constructor && constructor.parameters, visitor, context) + || []; + } + /** + * Transforms (or creates) a constructor body for a class with parameter property + * assignments or instance property initializers. + * + * @param node The current class. + * @param constructor The current class constructor. + * @param isDerivedClass A value indicating whether the class has an extends clause that does not extend 'null'. + */ + function transformConstructorBody(node, constructor, isDerivedClass) { + var statements = []; + var indexOfFirstStatement = 0; + resumeLexicalEnvironment(); + if (constructor) { + indexOfFirstStatement = addPrologueDirectivesAndInitialSuperCall(constructor, statements); + // Add parameters with property assignments. Transforms this: + // + // constructor (public x, public y) { + // } + // + // Into this: + // + // constructor (x, y) { + // this.x = x; + // this.y = y; + // } + // + var propertyAssignments = getParametersWithPropertyAssignments(constructor); + ts.addRange(statements, ts.map(propertyAssignments, transformParameterWithPropertyAssignment)); + } + else if (isDerivedClass) { + // Add a synthetic `super` call: + // + // super(...arguments); + // + statements.push(ts.createExpressionStatement(ts.createCall(ts.createSuper(), + /*typeArguments*/ undefined, [ts.createSpread(ts.createIdentifier("arguments"))]))); + } + // Add the property initializers. Transforms this: + // + // public x = 1; + // + // Into this: + // + // constructor() { + // this.x = 1; + // } + // + var properties = getInitializedProperties(node, /*isStatic*/ false); + addInitializedPropertyStatements(statements, properties, ts.createThis()); + if (constructor) { + // The class already had a constructor, so we should add the existing statements, skipping the initial super call. + ts.addRange(statements, ts.visitNodes(constructor.body.statements, visitor, ts.isStatement, indexOfFirstStatement)); + } + // End the lexical environment. + statements = ts.mergeLexicalEnvironment(statements, endLexicalEnvironment()); + return ts.setTextRange(ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), + /*location*/ constructor ? constructor.body.statements : node.members), + /*multiLine*/ true), + /*location*/ constructor ? constructor.body : undefined); + } + /** + * Adds super call and preceding prologue directives into the list of statements. + * + * @param ctor The constructor node. + * @returns index of the statement that follows super call + */ + function addPrologueDirectivesAndInitialSuperCall(ctor, result) { + if (ctor.body) { + var statements = ctor.body.statements; + // add prologue directives to the list (if any) + var index = ts.addPrologue(result, statements, /*ensureUseStrict*/ false, visitor); + if (index === statements.length) { + // list contains nothing but prologue directives (or empty) - exit + return index; + } + var statement = statements[index]; + if (statement.kind === 221 /* ExpressionStatement */ && ts.isSuperCall(statement.expression)) { + result.push(ts.visitNode(statement, visitor, ts.isStatement)); + return index + 1; + } + return index; + } + return 0; + } + /** + * Gets all parameters of a constructor that should be transformed into property assignments. + * + * @param node The constructor node. + */ + function getParametersWithPropertyAssignments(node) { + return ts.filter(node.parameters, isParameterWithPropertyAssignment); + } + /** + * Determines whether a parameter should be transformed into a property assignment. + * + * @param parameter The parameter node. + */ + function isParameterWithPropertyAssignment(parameter) { + return ts.hasModifier(parameter, 92 /* ParameterPropertyModifier */) + && ts.isIdentifier(parameter.name); + } + /** + * Transforms a parameter into a property assignment statement. + * + * @param node The parameter declaration. + */ + function transformParameterWithPropertyAssignment(node) { + ts.Debug.assert(ts.isIdentifier(node.name)); + var name = node.name; + var propertyName = ts.getMutableClone(name); + ts.setEmitFlags(propertyName, 1536 /* NoComments */ | 48 /* NoSourceMap */); + var localName = ts.getMutableClone(name); + ts.setEmitFlags(localName, 1536 /* NoComments */); + return ts.startOnNewLine(ts.setEmitFlags(ts.setTextRange(ts.createExpressionStatement(ts.createAssignment(ts.setTextRange(ts.createPropertyAccess(ts.createThis(), propertyName), node.name), localName)), ts.moveRangePos(node, -1)), 1536 /* NoComments */)); + } + /** + * Gets all property declarations with initializers on either the static or instance side of a class. + * + * @param node The class node. + * @param isStatic A value indicating whether to get properties from the static or instance side of the class. + */ + function getInitializedProperties(node, isStatic) { + return ts.filter(node.members, isStatic ? isStaticInitializedProperty : isInstanceInitializedProperty); + } + /** + * Gets a value indicating whether a class element is a static property declaration with an initializer. + * + * @param member The class element node. + */ + function isStaticInitializedProperty(member) { + return isInitializedProperty(member, /*isStatic*/ true); + } + /** + * Gets a value indicating whether a class element is an instance property declaration with an initializer. + * + * @param member The class element node. + */ + function isInstanceInitializedProperty(member) { + return isInitializedProperty(member, /*isStatic*/ false); + } + /** + * Gets a value indicating whether a class element is either a static or an instance property declaration with an initializer. + * + * @param member The class element node. + * @param isStatic A value indicating whether the member should be a static or instance member. + */ + function isInitializedProperty(member, isStatic) { + return member.kind === 154 /* PropertyDeclaration */ + && isStatic === ts.hasModifier(member, 32 /* Static */) + && member.initializer !== undefined; + } + /** + * Generates assignment statements for property initializers. + * + * @param properties An array of property declarations to transform. + * @param receiver The receiver on which each property should be assigned. + */ + function addInitializedPropertyStatements(statements, properties, receiver) { + for (var _i = 0, properties_9 = properties; _i < properties_9.length; _i++) { + var property = properties_9[_i]; + var statement = ts.createExpressionStatement(transformInitializedProperty(property, receiver)); + ts.setSourceMapRange(statement, ts.moveRangePastModifiers(property)); + ts.setCommentRange(statement, property); + ts.setOriginalNode(statement, property); + statements.push(statement); + } + } + /** + * Generates assignment expressions for property initializers. + * + * @param properties An array of property declarations to transform. + * @param receiver The receiver on which each property should be assigned. + */ + function generateInitializedPropertyExpressions(properties, receiver) { + var expressions = []; + for (var _i = 0, properties_10 = properties; _i < properties_10.length; _i++) { + var property = properties_10[_i]; + var expression = transformInitializedProperty(property, receiver); + ts.startOnNewLine(expression); + ts.setSourceMapRange(expression, ts.moveRangePastModifiers(property)); + ts.setCommentRange(expression, property); + ts.setOriginalNode(expression, property); + expressions.push(expression); + } + return expressions; + } + /** + * Transforms a property initializer into an assignment statement. + * + * @param property The property declaration. + * @param receiver The object receiving the property assignment. + */ + function transformInitializedProperty(property, receiver) { + // We generate a name here in order to reuse the value cached by the relocated computed name expression (which uses the same generated name) + var propertyName = ts.isComputedPropertyName(property.name) && !isSimpleInlineableExpression(property.name.expression) + ? ts.updateComputedPropertyName(property.name, ts.getGeneratedNameForNode(property.name)) + : property.name; + var initializer = ts.visitNode(property.initializer, visitor, ts.isExpression); + var memberAccess = ts.createMemberAccessForPropertyName(receiver, propertyName, /*location*/ propertyName); + return ts.createAssignment(memberAccess, initializer); + } + /** + * Gets either the static or instance members of a class that are decorated, or have + * parameters that are decorated. + * + * @param node The class containing the member. + * @param isStatic A value indicating whether to retrieve static or instance members of + * the class. + */ + function getDecoratedClassElements(node, isStatic) { + return ts.filter(node.members, isStatic ? function (m) { return isStaticDecoratedClassElement(m, node); } : function (m) { return isInstanceDecoratedClassElement(m, node); }); + } + /** + * Determines whether a class member is a static member of a class that is decorated, or + * has parameters that are decorated. + * + * @param member The class member. + */ + function isStaticDecoratedClassElement(member, parent) { + return isDecoratedClassElement(member, /*isStatic*/ true, parent); + } + /** + * Determines whether a class member is an instance member of a class that is decorated, + * or has parameters that are decorated. + * + * @param member The class member. + */ + function isInstanceDecoratedClassElement(member, parent) { + return isDecoratedClassElement(member, /*isStatic*/ false, parent); + } + /** + * Determines whether a class member is either a static or an instance member of a class + * that is decorated, or has parameters that are decorated. + * + * @param member The class member. + */ + function isDecoratedClassElement(member, isStatic, parent) { + return ts.nodeOrChildIsDecorated(member, parent) + && isStatic === ts.hasModifier(member, 32 /* Static */); + } + /** + * Gets an array of arrays of decorators for the parameters of a function-like node. + * The offset into the result array should correspond to the offset of the parameter. + * + * @param node The function-like node. + */ + function getDecoratorsOfParameters(node) { + var decorators; + if (node) { + var parameters = node.parameters; + for (var i = 0; i < parameters.length; i++) { + var parameter = parameters[i]; + if (decorators || parameter.decorators) { + if (!decorators) { + decorators = new Array(parameters.length); + } + decorators[i] = parameter.decorators; + } + } + } + return decorators; + } + /** + * Gets an AllDecorators object containing the decorators for the class and the decorators for the + * parameters of the constructor of the class. + * + * @param node The class node. + */ + function getAllDecoratorsOfConstructor(node) { + var decorators = node.decorators; + var parameters = getDecoratorsOfParameters(ts.getFirstConstructorWithBody(node)); + if (!decorators && !parameters) { + return undefined; + } + return { + decorators: decorators, + parameters: parameters + }; + } + /** + * Gets an AllDecorators object containing the decorators for the member and its parameters. + * + * @param node The class node that contains the member. + * @param member The class member. + */ + function getAllDecoratorsOfClassElement(node, member) { + switch (member.kind) { + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + return getAllDecoratorsOfAccessors(node, member); + case 156 /* MethodDeclaration */: + return getAllDecoratorsOfMethod(member); + case 154 /* PropertyDeclaration */: + return getAllDecoratorsOfProperty(member); + default: + return undefined; + } + } + /** + * Gets an AllDecorators object containing the decorators for the accessor and its parameters. + * + * @param node The class node that contains the accessor. + * @param accessor The class accessor member. + */ + function getAllDecoratorsOfAccessors(node, accessor) { + if (!accessor.body) { + return undefined; + } + var _a = ts.getAllAccessorDeclarations(node.members, accessor), firstAccessor = _a.firstAccessor, secondAccessor = _a.secondAccessor, setAccessor = _a.setAccessor; + var firstAccessorWithDecorators = firstAccessor.decorators ? firstAccessor : secondAccessor && secondAccessor.decorators ? secondAccessor : undefined; + if (!firstAccessorWithDecorators || accessor !== firstAccessorWithDecorators) { + return undefined; + } + var decorators = firstAccessorWithDecorators.decorators; + var parameters = getDecoratorsOfParameters(setAccessor); + if (!decorators && !parameters) { + return undefined; + } + return { decorators: decorators, parameters: parameters }; + } + /** + * Gets an AllDecorators object containing the decorators for the method and its parameters. + * + * @param method The class method member. + */ + function getAllDecoratorsOfMethod(method) { + if (!method.body) { + return undefined; + } + var decorators = method.decorators; + var parameters = getDecoratorsOfParameters(method); + if (!decorators && !parameters) { + return undefined; + } + return { decorators: decorators, parameters: parameters }; + } + /** + * Gets an AllDecorators object containing the decorators for the property. + * + * @param property The class property member. + */ + function getAllDecoratorsOfProperty(property) { + var decorators = property.decorators; + if (!decorators) { + return undefined; + } + return { decorators: decorators }; + } + /** + * Transforms all of the decorators for a declaration into an array of expressions. + * + * @param node The declaration node. + * @param allDecorators An object containing all of the decorators for the declaration. + */ + function transformAllDecoratorsOfDeclaration(node, container, allDecorators) { + if (!allDecorators) { + return undefined; + } + var decoratorExpressions = []; + ts.addRange(decoratorExpressions, ts.map(allDecorators.decorators, transformDecorator)); + ts.addRange(decoratorExpressions, ts.flatMap(allDecorators.parameters, transformDecoratorsOfParameter)); + addTypeMetadata(node, container, decoratorExpressions); + return decoratorExpressions; + } + /** + * Generates statements used to apply decorators to either the static or instance members + * of a class. + * + * @param node The class node. + * @param isStatic A value indicating whether to generate statements for static or + * instance members. + */ + function addClassElementDecorationStatements(statements, node, isStatic) { + ts.addRange(statements, ts.map(generateClassElementDecorationExpressions(node, isStatic), expressionToStatement)); + } + /** + * Generates expressions used to apply decorators to either the static or instance members + * of a class. + * + * @param node The class node. + * @param isStatic A value indicating whether to generate expressions for static or + * instance members. + */ + function generateClassElementDecorationExpressions(node, isStatic) { + var members = getDecoratedClassElements(node, isStatic); + var expressions; + for (var _i = 0, members_5 = members; _i < members_5.length; _i++) { + var member = members_5[_i]; + var expression = generateClassElementDecorationExpression(node, member); + if (expression) { + if (!expressions) { + expressions = [expression]; + } + else { + expressions.push(expression); + } + } + } + return expressions; + } + /** + * Generates an expression used to evaluate class element decorators at runtime. + * + * @param node The class node that contains the member. + * @param member The class member. + */ + function generateClassElementDecorationExpression(node, member) { + var allDecorators = getAllDecoratorsOfClassElement(node, member); + var decoratorExpressions = transformAllDecoratorsOfDeclaration(member, node, allDecorators); + if (!decoratorExpressions) { + return undefined; + } + // Emit the call to __decorate. Given the following: + // + // class C { + // @dec method(@dec2 x) {} + // @dec get accessor() {} + // @dec prop; + // } + // + // The emit for a method is: + // + // __decorate([ + // dec, + // __param(0, dec2), + // __metadata("design:type", Function), + // __metadata("design:paramtypes", [Object]), + // __metadata("design:returntype", void 0) + // ], C.prototype, "method", null); + // + // The emit for an accessor is: + // + // __decorate([ + // dec + // ], C.prototype, "accessor", null); + // + // The emit for a property is: + // + // __decorate([ + // dec + // ], C.prototype, "prop"); + // + var prefix = getClassMemberPrefix(node, member); + var memberName = getExpressionForPropertyName(member, /*generateNameForComputedPropertyName*/ true); + var descriptor = languageVersion > 0 /* ES3 */ + ? member.kind === 154 /* PropertyDeclaration */ + // We emit `void 0` here to indicate to `__decorate` that it can invoke `Object.defineProperty` directly, but that it + // should not invoke `Object.getOwnPropertyDescriptor`. + ? ts.createVoidZero() + // We emit `null` here to indicate to `__decorate` that it can invoke `Object.getOwnPropertyDescriptor` directly. + // We have this extra argument here so that we can inject an explicit property descriptor at a later date. + : ts.createNull() + : undefined; + var helper = createDecorateHelper(context, decoratorExpressions, prefix, memberName, descriptor, ts.moveRangePastDecorators(member)); + ts.setEmitFlags(helper, 1536 /* NoComments */); + return helper; + } + /** + * Generates a __decorate helper call for a class constructor. + * + * @param node The class node. + */ + function addConstructorDecorationStatement(statements, node) { + var expression = generateConstructorDecorationExpression(node); + if (expression) { + statements.push(ts.setOriginalNode(ts.createExpressionStatement(expression), node)); + } + } + /** + * Generates a __decorate helper call for a class constructor. + * + * @param node The class node. + */ + function generateConstructorDecorationExpression(node) { + var allDecorators = getAllDecoratorsOfConstructor(node); + var decoratorExpressions = transformAllDecoratorsOfDeclaration(node, node, allDecorators); + if (!decoratorExpressions) { + return undefined; + } + var classAlias = classAliases && classAliases[ts.getOriginalNodeId(node)]; + var localName = ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true); + var decorate = createDecorateHelper(context, decoratorExpressions, localName); + var expression = ts.createAssignment(localName, classAlias ? ts.createAssignment(classAlias, decorate) : decorate); + ts.setEmitFlags(expression, 1536 /* NoComments */); + ts.setSourceMapRange(expression, ts.moveRangePastDecorators(node)); + return expression; + } + /** + * Transforms a decorator into an expression. + * + * @param decorator The decorator node. + */ + function transformDecorator(decorator) { + return ts.visitNode(decorator.expression, visitor, ts.isExpression); + } + /** + * Transforms the decorators of a parameter. + * + * @param decorators The decorators for the parameter at the provided offset. + * @param parameterOffset The offset of the parameter. + */ + function transformDecoratorsOfParameter(decorators, parameterOffset) { + var expressions; + if (decorators) { + expressions = []; + for (var _i = 0, decorators_1 = decorators; _i < decorators_1.length; _i++) { + var decorator = decorators_1[_i]; + var helper = createParamHelper(context, transformDecorator(decorator), parameterOffset, + /*location*/ decorator.expression); + ts.setEmitFlags(helper, 1536 /* NoComments */); + expressions.push(helper); + } + } + return expressions; + } + /** + * Adds optional type metadata for a declaration. + * + * @param node The declaration node. + * @param decoratorExpressions The destination array to which to add new decorator expressions. + */ + function addTypeMetadata(node, container, decoratorExpressions) { + if (USE_NEW_TYPE_METADATA_FORMAT) { + addNewTypeMetadata(node, container, decoratorExpressions); + } + else { + addOldTypeMetadata(node, container, decoratorExpressions); + } + } + function addOldTypeMetadata(node, container, decoratorExpressions) { + if (compilerOptions.emitDecoratorMetadata) { + if (shouldAddTypeMetadata(node)) { + decoratorExpressions.push(createMetadataHelper(context, "design:type", serializeTypeOfNode(node))); + } + if (shouldAddParamTypesMetadata(node)) { + decoratorExpressions.push(createMetadataHelper(context, "design:paramtypes", serializeParameterTypesOfNode(node, container))); + } + if (shouldAddReturnTypeMetadata(node)) { + decoratorExpressions.push(createMetadataHelper(context, "design:returntype", serializeReturnTypeOfNode(node))); + } + } + } + function addNewTypeMetadata(node, container, decoratorExpressions) { + if (compilerOptions.emitDecoratorMetadata) { + var properties = void 0; + if (shouldAddTypeMetadata(node)) { + (properties || (properties = [])).push(ts.createPropertyAssignment("type", ts.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, ts.createToken(37 /* EqualsGreaterThanToken */), serializeTypeOfNode(node)))); + } + if (shouldAddParamTypesMetadata(node)) { + (properties || (properties = [])).push(ts.createPropertyAssignment("paramTypes", ts.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, ts.createToken(37 /* EqualsGreaterThanToken */), serializeParameterTypesOfNode(node, container)))); + } + if (shouldAddReturnTypeMetadata(node)) { + (properties || (properties = [])).push(ts.createPropertyAssignment("returnType", ts.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, ts.createToken(37 /* EqualsGreaterThanToken */), serializeReturnTypeOfNode(node)))); + } + if (properties) { + decoratorExpressions.push(createMetadataHelper(context, "design:typeinfo", ts.createObjectLiteral(properties, /*multiLine*/ true))); + } + } + } + /** + * Determines whether to emit the "design:type" metadata based on the node's kind. + * The caller should have already tested whether the node has decorators and whether the + * emitDecoratorMetadata compiler option is set. + * + * @param node The node to test. + */ + function shouldAddTypeMetadata(node) { + var kind = node.kind; + return kind === 156 /* MethodDeclaration */ + || kind === 158 /* GetAccessor */ + || kind === 159 /* SetAccessor */ + || kind === 154 /* PropertyDeclaration */; + } + /** + * Determines whether to emit the "design:returntype" metadata based on the node's kind. + * The caller should have already tested whether the node has decorators and whether the + * emitDecoratorMetadata compiler option is set. + * + * @param node The node to test. + */ + function shouldAddReturnTypeMetadata(node) { + return node.kind === 156 /* MethodDeclaration */; + } + /** + * Determines whether to emit the "design:paramtypes" metadata based on the node's kind. + * The caller should have already tested whether the node has decorators and whether the + * emitDecoratorMetadata compiler option is set. + * + * @param node The node to test. + */ + function shouldAddParamTypesMetadata(node) { + switch (node.kind) { + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + return ts.getFirstConstructorWithBody(node) !== undefined; + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + return true; + } + return false; + } + function getAccessorTypeNode(node) { + var accessors = resolver.getAllAccessorDeclarations(node); + return accessors.setAccessor && ts.getSetAccessorTypeAnnotationNode(accessors.setAccessor) + || accessors.getAccessor && ts.getEffectiveReturnTypeNode(accessors.getAccessor); + } + /** + * Serializes the type of a node for use with decorator type metadata. + * + * @param node The node that should have its type serialized. + */ + function serializeTypeOfNode(node) { + switch (node.kind) { + case 154 /* PropertyDeclaration */: + case 151 /* Parameter */: + return serializeTypeNode(node.type); + case 159 /* SetAccessor */: + case 158 /* GetAccessor */: + return serializeTypeNode(getAccessorTypeNode(node)); + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 156 /* MethodDeclaration */: + return ts.createIdentifier("Function"); + default: + return ts.createVoidZero(); + } + } + /** + * Serializes the types of the parameters of a node for use with decorator type metadata. + * + * @param node The node that should have its parameter types serialized. + */ + function serializeParameterTypesOfNode(node, container) { + var valueDeclaration = ts.isClassLike(node) + ? ts.getFirstConstructorWithBody(node) + : ts.isFunctionLike(node) && ts.nodeIsPresent(node.body) + ? node + : undefined; + var expressions = []; + if (valueDeclaration) { + var parameters = getParametersOfDecoratedDeclaration(valueDeclaration, container); + var numParameters = parameters.length; + for (var i = 0; i < numParameters; i++) { + var parameter = parameters[i]; + if (i === 0 && ts.isIdentifier(parameter.name) && parameter.name.escapedText === "this") { + continue; + } + if (parameter.dotDotDotToken) { + expressions.push(serializeTypeNode(ts.getRestParameterElementType(parameter.type))); + } + else { + expressions.push(serializeTypeOfNode(parameter)); + } + } + } + return ts.createArrayLiteral(expressions); + } + function getParametersOfDecoratedDeclaration(node, container) { + if (container && node.kind === 158 /* GetAccessor */) { + var setAccessor = ts.getAllAccessorDeclarations(container.members, node).setAccessor; + if (setAccessor) { + return setAccessor.parameters; + } + } + return node.parameters; + } + /** + * Serializes the return type of a node for use with decorator type metadata. + * + * @param node The node that should have its return type serialized. + */ + function serializeReturnTypeOfNode(node) { + if (ts.isFunctionLike(node) && node.type) { + return serializeTypeNode(node.type); + } + else if (ts.isAsyncFunction(node)) { + return ts.createIdentifier("Promise"); + } + return ts.createVoidZero(); + } + /** + * Serializes a type node for use with decorator type metadata. + * + * Types are serialized in the following fashion: + * - Void types point to "undefined" (e.g. "void 0") + * - Function and Constructor types point to the global "Function" constructor. + * - Interface types with a call or construct signature types point to the global + * "Function" constructor. + * - Array and Tuple types point to the global "Array" constructor. + * - Type predicates and booleans point to the global "Boolean" constructor. + * - String literal types and strings point to the global "String" constructor. + * - Enum and number types point to the global "Number" constructor. + * - Symbol types point to the global "Symbol" constructor. + * - Type references to classes (or class-like variables) point to the constructor for the class. + * - Anything else points to the global "Object" constructor. + * + * @param node The type node to serialize. + */ + function serializeTypeNode(node) { + if (node === undefined) { + return ts.createIdentifier("Object"); + } + switch (node.kind) { + case 106 /* VoidKeyword */: + case 141 /* UndefinedKeyword */: + case 96 /* NullKeyword */: + case 132 /* NeverKeyword */: + return ts.createVoidZero(); + case 177 /* ParenthesizedType */: + return serializeTypeNode(node.type); + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + return ts.createIdentifier("Function"); + case 169 /* ArrayType */: + case 170 /* TupleType */: + return ts.createIdentifier("Array"); + case 163 /* TypePredicate */: + case 123 /* BooleanKeyword */: + return ts.createIdentifier("Boolean"); + case 138 /* StringKeyword */: + return ts.createIdentifier("String"); + case 136 /* ObjectKeyword */: + return ts.createIdentifier("Object"); + case 182 /* LiteralType */: + switch (node.literal.kind) { + case 10 /* StringLiteral */: + return ts.createIdentifier("String"); + case 8 /* NumericLiteral */: + return ts.createIdentifier("Number"); + case 9 /* BigIntLiteral */: + return getGlobalBigIntNameWithFallback(); + case 102 /* TrueKeyword */: + case 87 /* FalseKeyword */: + return ts.createIdentifier("Boolean"); + default: + return ts.Debug.failBadSyntaxKind(node.literal); + } + case 135 /* NumberKeyword */: + return ts.createIdentifier("Number"); + case 146 /* BigIntKeyword */: + return getGlobalBigIntNameWithFallback(); + case 139 /* SymbolKeyword */: + return languageVersion < 2 /* ES2015 */ + ? getGlobalSymbolNameWithFallback() + : ts.createIdentifier("Symbol"); + case 164 /* TypeReference */: + return serializeTypeReferenceNode(node); + case 174 /* IntersectionType */: + case 173 /* UnionType */: + return serializeTypeList(node.types); + case 175 /* ConditionalType */: + return serializeTypeList([node.trueType, node.falseType]); + case 167 /* TypeQuery */: + case 179 /* TypeOperator */: + case 180 /* IndexedAccessType */: + case 181 /* MappedType */: + case 168 /* TypeLiteral */: + case 120 /* AnyKeyword */: + case 143 /* UnknownKeyword */: + case 178 /* ThisType */: + case 183 /* ImportType */: + break; + default: + return ts.Debug.failBadSyntaxKind(node); + } + return ts.createIdentifier("Object"); + } + function serializeTypeList(types) { + // Note when updating logic here also update getEntityNameForDecoratorMetadata + // so that aliases can be marked as referenced + var serializedUnion; + for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { + var typeNode = types_17[_i]; + while (typeNode.kind === 177 /* ParenthesizedType */) { + typeNode = typeNode.type; // Skip parens if need be + } + if (typeNode.kind === 132 /* NeverKeyword */) { + continue; // Always elide `never` from the union/intersection if possible + } + if (!strictNullChecks && (typeNode.kind === 96 /* NullKeyword */ || typeNode.kind === 141 /* UndefinedKeyword */)) { + continue; // Elide null and undefined from unions for metadata, just like what we did prior to the implementation of strict null checks + } + var serializedIndividual = serializeTypeNode(typeNode); + if (ts.isIdentifier(serializedIndividual) && serializedIndividual.escapedText === "Object") { + // One of the individual is global object, return immediately + return serializedIndividual; + } + // If there exists union that is not void 0 expression, check if the the common type is identifier. + // anything more complex and we will just default to Object + else if (serializedUnion) { + // Different types + if (!ts.isIdentifier(serializedUnion) || + !ts.isIdentifier(serializedIndividual) || + serializedUnion.escapedText !== serializedIndividual.escapedText) { + return ts.createIdentifier("Object"); + } + } + else { + // Initialize the union type + serializedUnion = serializedIndividual; + } + } + // If we were able to find common type, use it + return serializedUnion || ts.createVoidZero(); // Fallback is only hit if all union constituients are null/undefined/never + } + /** + * Serializes a TypeReferenceNode to an appropriate JS constructor value for use with + * decorator type metadata. + * + * @param node The type reference node. + */ + function serializeTypeReferenceNode(node) { + var kind = resolver.getTypeReferenceSerializationKind(node.typeName, currentNameScope || currentLexicalScope); + switch (kind) { + case ts.TypeReferenceSerializationKind.Unknown: + // From conditional type type reference that cannot be resolved is Similar to any or unknown + if (ts.findAncestor(node, function (n) { return n.parent && ts.isConditionalTypeNode(n.parent) && (n.parent.trueType === n || n.parent.falseType === n); })) { + return ts.createIdentifier("Object"); + } + var serialized = serializeEntityNameAsExpressionFallback(node.typeName); + var temp = ts.createTempVariable(hoistVariableDeclaration); + return ts.createConditional(ts.createTypeCheck(ts.createAssignment(temp, serialized), "function"), temp, ts.createIdentifier("Object")); + case ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue: + return serializeEntityNameAsExpression(node.typeName); + case ts.TypeReferenceSerializationKind.VoidNullableOrNeverType: + return ts.createVoidZero(); + case ts.TypeReferenceSerializationKind.BigIntLikeType: + return getGlobalBigIntNameWithFallback(); + case ts.TypeReferenceSerializationKind.BooleanType: + return ts.createIdentifier("Boolean"); + case ts.TypeReferenceSerializationKind.NumberLikeType: + return ts.createIdentifier("Number"); + case ts.TypeReferenceSerializationKind.StringLikeType: + return ts.createIdentifier("String"); + case ts.TypeReferenceSerializationKind.ArrayLikeType: + return ts.createIdentifier("Array"); + case ts.TypeReferenceSerializationKind.ESSymbolType: + return languageVersion < 2 /* ES2015 */ + ? getGlobalSymbolNameWithFallback() + : ts.createIdentifier("Symbol"); + case ts.TypeReferenceSerializationKind.TypeWithCallSignature: + return ts.createIdentifier("Function"); + case ts.TypeReferenceSerializationKind.Promise: + return ts.createIdentifier("Promise"); + case ts.TypeReferenceSerializationKind.ObjectType: + return ts.createIdentifier("Object"); + default: + return ts.Debug.assertNever(kind); + } + } + function createCheckedValue(left, right) { + return ts.createLogicalAnd(ts.createStrictInequality(ts.createTypeOf(left), ts.createLiteral("undefined")), right); + } + /** + * Serializes an entity name which may not exist at runtime, but whose access shouldn't throw + * + * @param node The entity name to serialize. + */ + function serializeEntityNameAsExpressionFallback(node) { + if (node.kind === 72 /* Identifier */) { + // A -> typeof A !== undefined && A + var copied = serializeEntityNameAsExpression(node); + return createCheckedValue(copied, copied); + } + if (node.left.kind === 72 /* Identifier */) { + // A.B -> typeof A !== undefined && A.B + return createCheckedValue(serializeEntityNameAsExpression(node.left), serializeEntityNameAsExpression(node)); + } + // A.B.C -> typeof A !== undefined && (_a = A.B) !== void 0 && _a.C + var left = serializeEntityNameAsExpressionFallback(node.left); + var temp = ts.createTempVariable(hoistVariableDeclaration); + return ts.createLogicalAnd(ts.createLogicalAnd(left.left, ts.createStrictInequality(ts.createAssignment(temp, left.right), ts.createVoidZero())), ts.createPropertyAccess(temp, node.right)); + } + /** + * Serializes an entity name as an expression for decorator type metadata. + * + * @param node The entity name to serialize. + */ + function serializeEntityNameAsExpression(node) { + switch (node.kind) { + case 72 /* Identifier */: + // Create a clone of the name with a new parent, and treat it as if it were + // a source tree node for the purposes of the checker. + var name = ts.getMutableClone(node); + name.flags &= ~8 /* Synthesized */; + name.original = undefined; + name.parent = ts.getParseTreeNode(currentLexicalScope); // ensure the parent is set to a parse tree node. + return name; + case 148 /* QualifiedName */: + return serializeQualifiedNameAsExpression(node); + } + } + /** + * Serializes an qualified name as an expression for decorator type metadata. + * + * @param node The qualified name to serialize. + * @param useFallback A value indicating whether to use logical operators to test for the + * qualified name at runtime. + */ + function serializeQualifiedNameAsExpression(node) { + return ts.createPropertyAccess(serializeEntityNameAsExpression(node.left), node.right); + } + /** + * Gets an expression that points to the global "Symbol" constructor at runtime if it is + * available. + */ + function getGlobalSymbolNameWithFallback() { + return ts.createConditional(ts.createTypeCheck(ts.createIdentifier("Symbol"), "function"), ts.createIdentifier("Symbol"), ts.createIdentifier("Object")); + } + /** + * Gets an expression that points to the global "BigInt" constructor at runtime if it is + * available. + */ + function getGlobalBigIntNameWithFallback() { + return languageVersion < 6 /* ESNext */ + ? ts.createConditional(ts.createTypeCheck(ts.createIdentifier("BigInt"), "function"), ts.createIdentifier("BigInt"), ts.createIdentifier("Object")) + : ts.createIdentifier("BigInt"); + } + /** + * A simple inlinable expression is an expression which can be copied into multiple locations + * without risk of repeating any sideeffects and whose value could not possibly change between + * any such locations + */ + function isSimpleInlineableExpression(expression) { + return !ts.isIdentifier(expression) && ts.isSimpleCopiableExpression(expression) || + ts.isWellKnownSymbolSyntactically(expression); + } + /** + * Gets an expression that represents a property name. For a computed property, a + * name is generated for the node. + * + * @param member The member whose name should be converted into an expression. + */ + function getExpressionForPropertyName(member, generateNameForComputedPropertyName) { + var name = member.name; + if (ts.isComputedPropertyName(name)) { + return generateNameForComputedPropertyName && !isSimpleInlineableExpression(name.expression) + ? ts.getGeneratedNameForNode(name) + : name.expression; + } + else if (ts.isIdentifier(name)) { + return ts.createLiteral(ts.idText(name)); + } + else { + return ts.getSynthesizedClone(name); + } + } + /** + * If the name is a computed property, this function transforms it, then either returns an expression which caches the + * value of the result or the expression itself if the value is either unused or safe to inline into multiple locations + * @param shouldHoist Does the expression need to be reused? (ie, for an initializer or a decorator) + * @param omitSimple Should expressions with no observable side-effects be elided? (ie, the expression is not hoisted for a decorator or initializer and is a literal) + */ + function getPropertyNameExpressionIfNeeded(name, shouldHoist, omitSimple) { + if (ts.isComputedPropertyName(name)) { + var expression = ts.visitNode(name.expression, visitor, ts.isExpression); + var innerExpression = ts.skipPartiallyEmittedExpressions(expression); + var inlinable = isSimpleInlineableExpression(innerExpression); + if (!inlinable && shouldHoist) { + var generatedName = ts.getGeneratedNameForNode(name); + hoistVariableDeclaration(generatedName); + return ts.createAssignment(generatedName, expression); + } + return (omitSimple && (inlinable || ts.isIdentifier(innerExpression))) ? undefined : expression; + } + } + /** + * Visits the property name of a class element, for use when emitting property + * initializers. For a computed property on a node with decorators, a temporary + * value is stored for later use. + * + * @param member The member whose name should be visited. + */ + function visitPropertyNameOfClassElement(member) { + var name = member.name; + var expr = getPropertyNameExpressionIfNeeded(name, ts.some(member.decorators), /*omitSimple*/ false); + if (expr) { // expr only exists if `name` is a computed property name + // Inline any pending expressions from previous elided or relocated computed property name expressions in order to preserve execution order + if (ts.some(pendingExpressions)) { + expr = ts.inlineExpressions(pendingExpressions.concat([expr])); + pendingExpressions.length = 0; + } + return ts.updateComputedPropertyName(name, expr); + } + else { + return name; + } + } + /** + * Transforms a HeritageClause with TypeScript syntax. + * + * This function will only be called when one of the following conditions are met: + * - The node is a non-`extends` heritage clause that should be elided. + * - The node is an `extends` heritage clause that should be visited, but only allow a single type. + * + * @param node The HeritageClause to transform. + */ + function visitHeritageClause(node) { + if (node.token === 86 /* ExtendsKeyword */) { + var types = ts.visitNodes(node.types, visitor, ts.isExpressionWithTypeArguments, 0, 1); + return ts.setTextRange(ts.createHeritageClause(86 /* ExtendsKeyword */, types), node); + } + return undefined; + } + /** + * Transforms an ExpressionWithTypeArguments with TypeScript syntax. + * + * This function will only be called when one of the following conditions are met: + * - The node contains type arguments that should be elided. + * + * @param node The ExpressionWithTypeArguments to transform. + */ + function visitExpressionWithTypeArguments(node) { + return ts.updateExpressionWithTypeArguments(node, + /*typeArguments*/ undefined, ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression)); + } + /** + * Determines whether to emit a function-like declaration. We should not emit the + * declaration if it does not have a body. + * + * @param node The declaration node. + */ + function shouldEmitFunctionLikeDeclaration(node) { + return !ts.nodeIsMissing(node.body); + } + function visitPropertyDeclaration(node) { + var expr = getPropertyNameExpressionIfNeeded(node.name, ts.some(node.decorators) || !!node.initializer, /*omitSimple*/ true); + if (expr && !isSimpleInlineableExpression(expr)) { + (pendingExpressions || (pendingExpressions = [])).push(expr); + } + return undefined; + } + function visitConstructor(node) { + if (!shouldEmitFunctionLikeDeclaration(node)) { + return undefined; + } + return ts.updateConstructor(node, ts.visitNodes(node.decorators, visitor, ts.isDecorator), ts.visitNodes(node.modifiers, visitor, ts.isModifier), ts.visitParameterList(node.parameters, visitor, context), ts.visitFunctionBody(node.body, visitor, context)); + } + /** + * Visits a method declaration of a class. + * + * This function will be called when one of the following conditions are met: + * - The node is an overload + * - The node is marked as abstract, public, private, protected, or readonly + * - The node has a computed property name + * + * @param node The method node. + */ + function visitMethodDeclaration(node) { + if (!shouldEmitFunctionLikeDeclaration(node)) { + return undefined; + } + var updated = ts.updateMethod(node, + /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, visitPropertyNameOfClassElement(node), + /*questionToken*/ undefined, + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context)); + if (updated !== node) { + // While we emit the source map for the node after skipping decorators and modifiers, + // we need to emit the comments for the original range. + ts.setCommentRange(updated, node); + ts.setSourceMapRange(updated, ts.moveRangePastDecorators(node)); + } + return updated; + } + /** + * Determines whether to emit an accessor declaration. We should not emit the + * declaration if it does not have a body and is abstract. + * + * @param node The declaration node. + */ + function shouldEmitAccessorDeclaration(node) { + return !(ts.nodeIsMissing(node.body) && ts.hasModifier(node, 128 /* Abstract */)); + } + /** + * Visits a get accessor declaration of a class. + * + * This function will be called when one of the following conditions are met: + * - The node is marked as abstract, public, private, or protected + * - The node has a computed property name + * + * @param node The get accessor node. + */ + function visitGetAccessor(node) { + if (!shouldEmitAccessorDeclaration(node)) { + return undefined; + } + var updated = ts.updateGetAccessor(node, + /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), visitPropertyNameOfClassElement(node), ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context) || ts.createBlock([])); + if (updated !== node) { + // While we emit the source map for the node after skipping decorators and modifiers, + // we need to emit the comments for the original range. + ts.setCommentRange(updated, node); + ts.setSourceMapRange(updated, ts.moveRangePastDecorators(node)); + } + return updated; + } + /** + * Visits a set accessor declaration of a class. + * + * This function will be called when one of the following conditions are met: + * - The node is marked as abstract, public, private, or protected + * - The node has a computed property name + * + * @param node The set accessor node. + */ + function visitSetAccessor(node) { + if (!shouldEmitAccessorDeclaration(node)) { + return undefined; + } + var updated = ts.updateSetAccessor(node, + /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), visitPropertyNameOfClassElement(node), ts.visitParameterList(node.parameters, visitor, context), ts.visitFunctionBody(node.body, visitor, context) || ts.createBlock([])); + if (updated !== node) { + // While we emit the source map for the node after skipping decorators and modifiers, + // we need to emit the comments for the original range. + ts.setCommentRange(updated, node); + ts.setSourceMapRange(updated, ts.moveRangePastDecorators(node)); + } + return updated; + } + /** + * Visits a function declaration. + * + * This function will be called when one of the following conditions are met: + * - The node is an overload + * - The node is exported from a TypeScript namespace + * - The node has decorators + * + * @param node The function node. + */ + function visitFunctionDeclaration(node) { + if (!shouldEmitFunctionLikeDeclaration(node)) { + return ts.createNotEmittedStatement(node); + } + var updated = ts.updateFunctionDeclaration(node, + /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, node.name, + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context) || ts.createBlock([])); + if (isExportOfNamespace(node)) { + var statements = [updated]; + addExportMemberAssignment(statements, node); + return statements; + } + return updated; + } + /** + * Visits a function expression node. + * + * This function will be called when one of the following conditions are met: + * - The node has type annotations + * + * @param node The function expression node. + */ + function visitFunctionExpression(node) { + if (!shouldEmitFunctionLikeDeclaration(node)) { + return ts.createOmittedExpression(); + } + var updated = ts.updateFunctionExpression(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, node.name, + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context) || ts.createBlock([])); + return updated; + } + /** + * @remarks + * This function will be called when one of the following conditions are met: + * - The node has type annotations + */ + function visitArrowFunction(node) { + var updated = ts.updateArrowFunction(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, node.equalsGreaterThanToken, ts.visitFunctionBody(node.body, visitor, context)); + return updated; + } + /** + * Visits a parameter declaration node. + * + * This function will be called when one of the following conditions are met: + * - The node has an accessibility modifier. + * - The node has a questionToken. + * - The node's kind is ThisKeyword. + * + * @param node The parameter declaration node. + */ + function visitParameter(node) { + if (ts.parameterIsThisKeyword(node)) { + return undefined; + } + var parameter = ts.createParameter( + /*decorators*/ undefined, + /*modifiers*/ undefined, node.dotDotDotToken, ts.visitNode(node.name, visitor, ts.isBindingName), + /*questionToken*/ undefined, + /*type*/ undefined, ts.visitNode(node.initializer, visitor, ts.isExpression)); + // While we emit the source map for the node after skipping decorators and modifiers, + // we need to emit the comments for the original range. + ts.setOriginalNode(parameter, node); + ts.setTextRange(parameter, ts.moveRangePastModifiers(node)); + ts.setCommentRange(parameter, node); + ts.setSourceMapRange(parameter, ts.moveRangePastModifiers(node)); + ts.setEmitFlags(parameter.name, 32 /* NoTrailingSourceMap */); + return parameter; + } + /** + * Visits a variable statement in a namespace. + * + * This function will be called when one of the following conditions are met: + * - The node is exported from a TypeScript namespace. + */ + function visitVariableStatement(node) { + if (isExportOfNamespace(node)) { + var variables = ts.getInitializedVariables(node.declarationList); + if (variables.length === 0) { + // elide statement if there are no initialized variables. + return undefined; + } + return ts.setTextRange(ts.createExpressionStatement(ts.inlineExpressions(ts.map(variables, transformInitializedVariable))), node); + } + else { + return ts.visitEachChild(node, visitor, context); + } + } + function transformInitializedVariable(node) { + var name = node.name; + if (ts.isBindingPattern(name)) { + return ts.flattenDestructuringAssignment(node, visitor, context, 0 /* All */, + /*needsValue*/ false, createNamespaceExportExpression); + } + else { + return ts.setTextRange(ts.createAssignment(getNamespaceMemberNameWithSourceMapsAndWithoutComments(name), ts.visitNode(node.initializer, visitor, ts.isExpression)), + /*location*/ node); + } + } + function visitVariableDeclaration(node) { + return ts.updateVariableDeclaration(node, ts.visitNode(node.name, visitor, ts.isBindingName), + /*type*/ undefined, ts.visitNode(node.initializer, visitor, ts.isExpression)); + } + /** + * Visits a parenthesized expression that contains either a type assertion or an `as` + * expression. + * + * @param node The parenthesized expression node. + */ + function visitParenthesizedExpression(node) { + var innerExpression = ts.skipOuterExpressions(node.expression, ~2 /* Assertions */); + if (ts.isAssertionExpression(innerExpression)) { + // Make sure we consider all nested cast expressions, e.g.: + // (-A).x; + var expression = ts.visitNode(node.expression, visitor, ts.isExpression); + // We have an expression of the form: (SubExpr). Emitting this as (SubExpr) + // is really not desirable. We would like to emit the subexpression as-is. Omitting + // the parentheses, however, could cause change in the semantics of the generated + // code if the casted expression has a lower precedence than the rest of the + // expression. + // + // To preserve comments, we return a "PartiallyEmittedExpression" here which will + // preserve the position information of the original expression. + // + // Due to the auto-parenthesization rules used by the visitor and factory functions + // we can safely elide the parentheses here, as a new synthetic + // ParenthesizedExpression will be inserted if we remove parentheses too + // aggressively. + // HOWEVER - if there are leading comments on the expression itself, to handle ASI + // correctly for return and throw, we must keep the parenthesis + if (ts.length(ts.getLeadingCommentRangesOfNode(expression, currentSourceFile))) { + return ts.updateParen(node, expression); + } + return ts.createPartiallyEmittedExpression(expression, node); + } + return ts.visitEachChild(node, visitor, context); + } + function visitAssertionExpression(node) { + var expression = ts.visitNode(node.expression, visitor, ts.isExpression); + return ts.createPartiallyEmittedExpression(expression, node); + } + function visitNonNullExpression(node) { + var expression = ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression); + return ts.createPartiallyEmittedExpression(expression, node); + } + function visitCallExpression(node) { + return ts.updateCall(node, ts.visitNode(node.expression, visitor, ts.isExpression), + /*typeArguments*/ undefined, ts.visitNodes(node.arguments, visitor, ts.isExpression)); + } + function visitNewExpression(node) { + return ts.updateNew(node, ts.visitNode(node.expression, visitor, ts.isExpression), + /*typeArguments*/ undefined, ts.visitNodes(node.arguments, visitor, ts.isExpression)); + } + function visitTaggedTemplateExpression(node) { + return ts.updateTaggedTemplate(node, ts.visitNode(node.tag, visitor, ts.isExpression), + /*typeArguments*/ undefined, ts.visitNode(node.template, visitor, ts.isExpression)); + } + /** + * Determines whether to emit an enum declaration. + * + * @param node The enum declaration node. + */ + function shouldEmitEnumDeclaration(node) { + return !ts.isEnumConst(node) + || compilerOptions.preserveConstEnums + || compilerOptions.isolatedModules; + } + /** + * Visits an enum declaration. + * + * This function will be called any time a TypeScript enum is encountered. + * + * @param node The enum declaration node. + */ + function visitEnumDeclaration(node) { + if (!shouldEmitEnumDeclaration(node)) { + return undefined; + } + var statements = []; + // We request to be advised when the printer is about to print this node. This allows + // us to set up the correct state for later substitutions. + var emitFlags = 2 /* AdviseOnEmitNode */; + // If needed, we should emit a variable declaration for the enum. If we emit + // a leading variable declaration, we should not emit leading comments for the + // enum body. + var varAdded = addVarForEnumOrModuleDeclaration(statements, node); + if (varAdded) { + // We should still emit the comments if we are emitting a system module. + if (moduleKind !== ts.ModuleKind.System || currentLexicalScope !== currentSourceFile) { + emitFlags |= 512 /* NoLeadingComments */; + } + } + // `parameterName` is the declaration name used inside of the enum. + var parameterName = getNamespaceParameterName(node); + // `containerName` is the expression used inside of the enum for assignments. + var containerName = getNamespaceContainerName(node); + // `exportName` is the expression used within this node's container for any exported references. + var exportName = ts.hasModifier(node, 1 /* Export */) + ? ts.getExternalModuleOrNamespaceExportName(currentNamespaceContainerName, node, /*allowComments*/ false, /*allowSourceMaps*/ true) + : ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true); + // x || (x = {}) + // exports.x || (exports.x = {}) + var moduleArg = ts.createLogicalOr(exportName, ts.createAssignment(exportName, ts.createObjectLiteral())); + if (hasNamespaceQualifiedExportName(node)) { + // `localName` is the expression used within this node's containing scope for any local references. + var localName = ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true); + // x = (exports.x || (exports.x = {})) + moduleArg = ts.createAssignment(localName, moduleArg); + } + // (function (x) { + // x[x["y"] = 0] = "y"; + // ... + // })(x || (x = {})); + var enumStatement = ts.createExpressionStatement(ts.createCall(ts.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, parameterName)], + /*type*/ undefined, transformEnumBody(node, containerName)), + /*typeArguments*/ undefined, [moduleArg])); + ts.setOriginalNode(enumStatement, node); + if (varAdded) { + // If a variable was added, synthetic comments are emitted on it, not on the moduleStatement. + ts.setSyntheticLeadingComments(enumStatement, undefined); + ts.setSyntheticTrailingComments(enumStatement, undefined); + } + ts.setTextRange(enumStatement, node); + ts.addEmitFlags(enumStatement, emitFlags); + statements.push(enumStatement); + // Add a DeclarationMarker for the enum to preserve trailing comments and mark + // the end of the declaration. + statements.push(ts.createEndOfDeclarationMarker(node)); + return statements; + } + /** + * Transforms the body of an enum declaration. + * + * @param node The enum declaration node. + */ + function transformEnumBody(node, localName) { + var savedCurrentNamespaceLocalName = currentNamespaceContainerName; + currentNamespaceContainerName = localName; + var statements = []; + startLexicalEnvironment(); + var members = ts.map(node.members, transformEnumMember); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + ts.addRange(statements, members); + currentNamespaceContainerName = savedCurrentNamespaceLocalName; + return ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), /*location*/ node.members), + /*multiLine*/ true); + } + /** + * Transforms an enum member into a statement. + * + * @param member The enum member node. + */ + function transformEnumMember(member) { + // enums don't support computed properties + // we pass false as 'generateNameForComputedPropertyName' for a backward compatibility purposes + // old emitter always generate 'expression' part of the name as-is. + var name = getExpressionForPropertyName(member, /*generateNameForComputedPropertyName*/ false); + var valueExpression = transformEnumMemberDeclarationValue(member); + var innerAssignment = ts.createAssignment(ts.createElementAccess(currentNamespaceContainerName, name), valueExpression); + var outerAssignment = valueExpression.kind === 10 /* StringLiteral */ ? + innerAssignment : + ts.createAssignment(ts.createElementAccess(currentNamespaceContainerName, innerAssignment), name); + return ts.setTextRange(ts.createExpressionStatement(ts.setTextRange(outerAssignment, member)), member); + } + /** + * Transforms the value of an enum member. + * + * @param member The enum member node. + */ + function transformEnumMemberDeclarationValue(member) { + var value = resolver.getConstantValue(member); + if (value !== undefined) { + return ts.createLiteral(value); + } + else { + enableSubstitutionForNonQualifiedEnumMembers(); + if (member.initializer) { + return ts.visitNode(member.initializer, visitor, ts.isExpression); + } + else { + return ts.createVoidZero(); + } + } + } + /** + * Determines whether to elide a module declaration. + * + * @param node The module declaration node. + */ + function shouldEmitModuleDeclaration(node) { + return ts.isInstantiatedModule(node, !!compilerOptions.preserveConstEnums || !!compilerOptions.isolatedModules); + } + /** + * Determines whether an exported declaration will have a qualified export name (e.g. `f.x` + * or `exports.x`). + */ + function hasNamespaceQualifiedExportName(node) { + return isExportOfNamespace(node) + || (isExternalModuleExport(node) + && moduleKind !== ts.ModuleKind.ES2015 + && moduleKind !== ts.ModuleKind.ESNext + && moduleKind !== ts.ModuleKind.System); + } + /** + * Records that a declaration was emitted in the current scope, if it was the first + * declaration for the provided symbol. + */ + function recordEmittedDeclarationInScope(node) { + if (!currentScopeFirstDeclarationsOfName) { + currentScopeFirstDeclarationsOfName = ts.createUnderscoreEscapedMap(); + } + var name = declaredNameInScope(node); + if (!currentScopeFirstDeclarationsOfName.has(name)) { + currentScopeFirstDeclarationsOfName.set(name, node); + } + } + /** + * Determines whether a declaration is the first declaration with + * the same name emitted in the current scope. + */ + function isFirstEmittedDeclarationInScope(node) { + if (currentScopeFirstDeclarationsOfName) { + var name = declaredNameInScope(node); + return currentScopeFirstDeclarationsOfName.get(name) === node; + } + return true; + } + function declaredNameInScope(node) { + ts.Debug.assertNode(node.name, ts.isIdentifier); + return node.name.escapedText; + } + /** + * Adds a leading VariableStatement for a enum or module declaration. + */ + function addVarForEnumOrModuleDeclaration(statements, node) { + // Emit a variable statement for the module. We emit top-level enums as a `var` + // declaration to avoid static errors in global scripts scripts due to redeclaration. + // enums in any other scope are emitted as a `let` declaration. + var statement = ts.createVariableStatement(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.createVariableDeclarationList([ + ts.createVariableDeclaration(ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true)) + ], currentLexicalScope.kind === 279 /* SourceFile */ ? 0 /* None */ : 1 /* Let */)); + ts.setOriginalNode(statement, node); + recordEmittedDeclarationInScope(node); + if (isFirstEmittedDeclarationInScope(node)) { + // Adjust the source map emit to match the old emitter. + if (node.kind === 243 /* EnumDeclaration */) { + ts.setSourceMapRange(statement.declarationList, node); + } + else { + ts.setSourceMapRange(statement, node); + } + // Trailing comments for module declaration should be emitted after the function closure + // instead of the variable statement: + // + // /** Module comment*/ + // module m1 { + // function foo4Export() { + // } + // } // trailing comment module + // + // Should emit: + // + // /** Module comment*/ + // var m1; + // (function (m1) { + // function foo4Export() { + // } + // })(m1 || (m1 = {})); // trailing comment module + // + ts.setCommentRange(statement, node); + ts.addEmitFlags(statement, 1024 /* NoTrailingComments */ | 4194304 /* HasEndOfDeclarationMarker */); + statements.push(statement); + return true; + } + else { + // For an EnumDeclaration or ModuleDeclaration that merges with a preceeding + // declaration we do not emit a leading variable declaration. To preserve the + // begin/end semantics of the declararation and to properly handle exports + // we wrap the leading variable declaration in a `MergeDeclarationMarker`. + var mergeMarker = ts.createMergeDeclarationMarker(statement); + ts.setEmitFlags(mergeMarker, 1536 /* NoComments */ | 4194304 /* HasEndOfDeclarationMarker */); + statements.push(mergeMarker); + return false; + } + } + /** + * Visits a module declaration node. + * + * This function will be called any time a TypeScript namespace (ModuleDeclaration) is encountered. + * + * @param node The module declaration node. + */ + function visitModuleDeclaration(node) { + if (!shouldEmitModuleDeclaration(node)) { + return ts.createNotEmittedStatement(node); + } + ts.Debug.assertNode(node.name, ts.isIdentifier, "A TypeScript namespace should have an Identifier name."); + enableSubstitutionForNamespaceExports(); + var statements = []; + // We request to be advised when the printer is about to print this node. This allows + // us to set up the correct state for later substitutions. + var emitFlags = 2 /* AdviseOnEmitNode */; + // If needed, we should emit a variable declaration for the module. If we emit + // a leading variable declaration, we should not emit leading comments for the + // module body. + var varAdded = addVarForEnumOrModuleDeclaration(statements, node); + if (varAdded) { + // We should still emit the comments if we are emitting a system module. + if (moduleKind !== ts.ModuleKind.System || currentLexicalScope !== currentSourceFile) { + emitFlags |= 512 /* NoLeadingComments */; + } + } + // `parameterName` is the declaration name used inside of the namespace. + var parameterName = getNamespaceParameterName(node); + // `containerName` is the expression used inside of the namespace for exports. + var containerName = getNamespaceContainerName(node); + // `exportName` is the expression used within this node's container for any exported references. + var exportName = ts.hasModifier(node, 1 /* Export */) + ? ts.getExternalModuleOrNamespaceExportName(currentNamespaceContainerName, node, /*allowComments*/ false, /*allowSourceMaps*/ true) + : ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true); + // x || (x = {}) + // exports.x || (exports.x = {}) + var moduleArg = ts.createLogicalOr(exportName, ts.createAssignment(exportName, ts.createObjectLiteral())); + if (hasNamespaceQualifiedExportName(node)) { + // `localName` is the expression used within this node's containing scope for any local references. + var localName = ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true); + // x = (exports.x || (exports.x = {})) + moduleArg = ts.createAssignment(localName, moduleArg); + } + // (function (x_1) { + // x_1.y = ...; + // })(x || (x = {})); + var moduleStatement = ts.createExpressionStatement(ts.createCall(ts.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, parameterName)], + /*type*/ undefined, transformModuleBody(node, containerName)), + /*typeArguments*/ undefined, [moduleArg])); + ts.setOriginalNode(moduleStatement, node); + if (varAdded) { + // If a variable was added, synthetic comments are emitted on it, not on the moduleStatement. + ts.setSyntheticLeadingComments(moduleStatement, undefined); + ts.setSyntheticTrailingComments(moduleStatement, undefined); + } + ts.setTextRange(moduleStatement, node); + ts.addEmitFlags(moduleStatement, emitFlags); + statements.push(moduleStatement); + // Add a DeclarationMarker for the namespace to preserve trailing comments and mark + // the end of the declaration. + statements.push(ts.createEndOfDeclarationMarker(node)); + return statements; + } + /** + * Transforms the body of a module declaration. + * + * @param node The module declaration node. + */ + function transformModuleBody(node, namespaceLocalName) { + var savedCurrentNamespaceContainerName = currentNamespaceContainerName; + var savedCurrentNamespace = currentNamespace; + var savedCurrentScopeFirstDeclarationsOfName = currentScopeFirstDeclarationsOfName; + currentNamespaceContainerName = namespaceLocalName; + currentNamespace = node; + currentScopeFirstDeclarationsOfName = undefined; + var statements = []; + startLexicalEnvironment(); + var statementsLocation; + var blockLocation; + var body = node.body; + if (body.kind === 245 /* ModuleBlock */) { + saveStateAndInvoke(body, function (body) { return ts.addRange(statements, ts.visitNodes(body.statements, namespaceElementVisitor, ts.isStatement)); }); + statementsLocation = body.statements; + blockLocation = body; + } + else { + var result = visitModuleDeclaration(body); + if (result) { + if (ts.isArray(result)) { + ts.addRange(statements, result); + } + else { + statements.push(result); + } + } + var moduleBlock = getInnerMostModuleDeclarationFromDottedModule(node).body; + statementsLocation = ts.moveRangePos(moduleBlock.statements, -1); + } + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + currentNamespaceContainerName = savedCurrentNamespaceContainerName; + currentNamespace = savedCurrentNamespace; + currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName; + var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), + /*location*/ statementsLocation), + /*multiLine*/ true); + ts.setTextRange(block, blockLocation); + // namespace hello.hi.world { + // function foo() {} + // + // // TODO, blah + // } + // + // should be emitted as + // + // var hello; + // (function (hello) { + // var hi; + // (function (hi) { + // var world; + // (function (world) { + // function foo() { } + // // TODO, blah + // })(world = hi.world || (hi.world = {})); + // })(hi = hello.hi || (hello.hi = {})); + // })(hello || (hello = {})); + // We only want to emit comment on the namespace which contains block body itself, not the containing namespaces. + if (body.kind !== 245 /* ModuleBlock */) { + ts.setEmitFlags(block, ts.getEmitFlags(block) | 1536 /* NoComments */); + } + return block; + } + function getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration) { + if (moduleDeclaration.body.kind === 244 /* ModuleDeclaration */) { + var recursiveInnerModule = getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration.body); + return recursiveInnerModule || moduleDeclaration.body; + } + } + /** + * Visits an import declaration, eliding it if it is not referenced. + * + * @param node The import declaration node. + */ + function visitImportDeclaration(node) { + if (!node.importClause) { + // Do not elide a side-effect only import declaration. + // import "foo"; + return node; + } + // Elide the declaration if the import clause was elided. + var importClause = ts.visitNode(node.importClause, visitImportClause, ts.isImportClause); + return importClause + ? ts.updateImportDeclaration(node, + /*decorators*/ undefined, + /*modifiers*/ undefined, importClause, node.moduleSpecifier) + : undefined; + } + /** + * Visits an import clause, eliding it if it is not referenced. + * + * @param node The import clause node. + */ + function visitImportClause(node) { + // Elide the import clause if we elide both its name and its named bindings. + var name = resolver.isReferencedAliasDeclaration(node) ? node.name : undefined; + var namedBindings = ts.visitNode(node.namedBindings, visitNamedImportBindings, ts.isNamedImportBindings); + return (name || namedBindings) ? ts.updateImportClause(node, name, namedBindings) : undefined; + } + /** + * Visits named import bindings, eliding it if it is not referenced. + * + * @param node The named import bindings node. + */ + function visitNamedImportBindings(node) { + if (node.kind === 251 /* NamespaceImport */) { + // Elide a namespace import if it is not referenced. + return resolver.isReferencedAliasDeclaration(node) ? node : undefined; + } + else { + // Elide named imports if all of its import specifiers are elided. + var elements = ts.visitNodes(node.elements, visitImportSpecifier, ts.isImportSpecifier); + return ts.some(elements) ? ts.updateNamedImports(node, elements) : undefined; + } + } + /** + * Visits an import specifier, eliding it if it is not referenced. + * + * @param node The import specifier node. + */ + function visitImportSpecifier(node) { + // Elide an import specifier if it is not referenced. + return resolver.isReferencedAliasDeclaration(node) ? node : undefined; + } + /** + * Visits an export assignment, eliding it if it does not contain a clause that resolves + * to a value. + * + * @param node The export assignment node. + */ + function visitExportAssignment(node) { + // Elide the export assignment if it does not reference a value. + return resolver.isValueAliasDeclaration(node) + ? ts.visitEachChild(node, visitor, context) + : undefined; + } + /** + * Visits an export declaration, eliding it if it does not contain a clause that resolves + * to a value. + * + * @param node The export declaration node. + */ + function visitExportDeclaration(node) { + if (!node.exportClause) { + // Elide a star export if the module it references does not export a value. + return compilerOptions.isolatedModules || resolver.moduleExportsSomeValue(node.moduleSpecifier) ? node : undefined; + } + if (!resolver.isValueAliasDeclaration(node)) { + // Elide the export declaration if it does not export a value. + return undefined; + } + // Elide the export declaration if all of its named exports are elided. + var exportClause = ts.visitNode(node.exportClause, visitNamedExports, ts.isNamedExports); + return exportClause + ? ts.updateExportDeclaration(node, + /*decorators*/ undefined, + /*modifiers*/ undefined, exportClause, node.moduleSpecifier) + : undefined; + } + /** + * Visits named exports, eliding it if it does not contain an export specifier that + * resolves to a value. + * + * @param node The named exports node. + */ + function visitNamedExports(node) { + // Elide the named exports if all of its export specifiers were elided. + var elements = ts.visitNodes(node.elements, visitExportSpecifier, ts.isExportSpecifier); + return ts.some(elements) ? ts.updateNamedExports(node, elements) : undefined; + } + /** + * Visits an export specifier, eliding it if it does not resolve to a value. + * + * @param node The export specifier node. + */ + function visitExportSpecifier(node) { + // Elide an export specifier if it does not reference a value. + return resolver.isValueAliasDeclaration(node) ? node : undefined; + } + /** + * Determines whether to emit an import equals declaration. + * + * @param node The import equals declaration node. + */ + function shouldEmitImportEqualsDeclaration(node) { + // preserve old compiler's behavior: emit 'var' for import declaration (even if we do not consider them referenced) when + // - current file is not external module + // - import declaration is top level and target is value imported by entity name + return resolver.isReferencedAliasDeclaration(node) + || (!ts.isExternalModule(currentSourceFile) + && resolver.isTopLevelValueImportEqualsWithEntityName(node)); + } + /** + * Visits an import equals declaration. + * + * @param node The import equals declaration node. + */ + function visitImportEqualsDeclaration(node) { + if (ts.isExternalModuleImportEqualsDeclaration(node)) { + // Elide external module `import=` if it is not referenced. + return resolver.isReferencedAliasDeclaration(node) + ? ts.visitEachChild(node, visitor, context) + : undefined; + } + if (!shouldEmitImportEqualsDeclaration(node)) { + return undefined; + } + var moduleReference = ts.createExpressionFromEntityName(node.moduleReference); + ts.setEmitFlags(moduleReference, 1536 /* NoComments */ | 2048 /* NoNestedComments */); + if (isNamedExternalModuleExport(node) || !isExportOfNamespace(node)) { + // export var ${name} = ${moduleReference}; + // var ${name} = ${moduleReference}; + return ts.setOriginalNode(ts.setTextRange(ts.createVariableStatement(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.createVariableDeclarationList([ + ts.setOriginalNode(ts.createVariableDeclaration(node.name, + /*type*/ undefined, moduleReference), node) + ])), node), node); + } + else { + // exports.${name} = ${moduleReference}; + return ts.setOriginalNode(createNamespaceExport(node.name, moduleReference, node), node); + } + } + /** + * Gets a value indicating whether the node is exported from a namespace. + * + * @param node The node to test. + */ + function isExportOfNamespace(node) { + return currentNamespace !== undefined && ts.hasModifier(node, 1 /* Export */); + } + /** + * Gets a value indicating whether the node is exported from an external module. + * + * @param node The node to test. + */ + function isExternalModuleExport(node) { + return currentNamespace === undefined && ts.hasModifier(node, 1 /* Export */); + } + /** + * Gets a value indicating whether the node is a named export from an external module. + * + * @param node The node to test. + */ + function isNamedExternalModuleExport(node) { + return isExternalModuleExport(node) + && !ts.hasModifier(node, 512 /* Default */); + } + /** + * Gets a value indicating whether the node is the default export of an external module. + * + * @param node The node to test. + */ + function isDefaultExternalModuleExport(node) { + return isExternalModuleExport(node) + && ts.hasModifier(node, 512 /* Default */); + } + /** + * Creates a statement for the provided expression. This is used in calls to `map`. + */ + function expressionToStatement(expression) { + return ts.createExpressionStatement(expression); + } + function addExportMemberAssignment(statements, node) { + var expression = ts.createAssignment(ts.getExternalModuleOrNamespaceExportName(currentNamespaceContainerName, node, /*allowComments*/ false, /*allowSourceMaps*/ true), ts.getLocalName(node)); + ts.setSourceMapRange(expression, ts.createRange(node.name ? node.name.pos : node.pos, node.end)); + var statement = ts.createExpressionStatement(expression); + ts.setSourceMapRange(statement, ts.createRange(-1, node.end)); + statements.push(statement); + } + function createNamespaceExport(exportName, exportValue, location) { + return ts.setTextRange(ts.createExpressionStatement(ts.createAssignment(ts.getNamespaceMemberName(currentNamespaceContainerName, exportName, /*allowComments*/ false, /*allowSourceMaps*/ true), exportValue)), location); + } + function createNamespaceExportExpression(exportName, exportValue, location) { + return ts.setTextRange(ts.createAssignment(getNamespaceMemberNameWithSourceMapsAndWithoutComments(exportName), exportValue), location); + } + function getNamespaceMemberNameWithSourceMapsAndWithoutComments(name) { + return ts.getNamespaceMemberName(currentNamespaceContainerName, name, /*allowComments*/ false, /*allowSourceMaps*/ true); + } + /** + * Gets the declaration name used inside of a namespace or enum. + */ + function getNamespaceParameterName(node) { + var name = ts.getGeneratedNameForNode(node); + ts.setSourceMapRange(name, node.name); + return name; + } + /** + * Gets the expression used to refer to a namespace or enum within the body + * of its declaration. + */ + function getNamespaceContainerName(node) { + return ts.getGeneratedNameForNode(node); + } + /** + * Gets a local alias for a class declaration if it is a decorated class with an internal + * reference to the static side of the class. This is necessary to avoid issues with + * double-binding semantics for the class name. + */ + function getClassAliasIfNeeded(node) { + if (resolver.getNodeCheckFlags(node) & 16777216 /* ClassWithConstructorReference */) { + enableSubstitutionForClassAliases(); + var classAlias = ts.createUniqueName(node.name && !ts.isGeneratedIdentifier(node.name) ? ts.idText(node.name) : "default"); + classAliases[ts.getOriginalNodeId(node)] = classAlias; + hoistVariableDeclaration(classAlias); + return classAlias; + } + } + function getClassPrototype(node) { + return ts.createPropertyAccess(ts.getDeclarationName(node), "prototype"); + } + function getClassMemberPrefix(node, member) { + return ts.hasModifier(member, 32 /* Static */) + ? ts.getDeclarationName(node) + : getClassPrototype(node); + } + function enableSubstitutionForNonQualifiedEnumMembers() { + if ((enabledSubstitutions & 8 /* NonQualifiedEnumMembers */) === 0) { + enabledSubstitutions |= 8 /* NonQualifiedEnumMembers */; + context.enableSubstitution(72 /* Identifier */); + } + } + function enableSubstitutionForClassAliases() { + if ((enabledSubstitutions & 1 /* ClassAliases */) === 0) { + enabledSubstitutions |= 1 /* ClassAliases */; + // We need to enable substitutions for identifiers. This allows us to + // substitute class names inside of a class declaration. + context.enableSubstitution(72 /* Identifier */); + // Keep track of class aliases. + classAliases = []; + } + } + function enableSubstitutionForNamespaceExports() { + if ((enabledSubstitutions & 2 /* NamespaceExports */) === 0) { + enabledSubstitutions |= 2 /* NamespaceExports */; + // We need to enable substitutions for identifiers and shorthand property assignments. This allows us to + // substitute the names of exported members of a namespace. + context.enableSubstitution(72 /* Identifier */); + context.enableSubstitution(276 /* ShorthandPropertyAssignment */); + // We need to be notified when entering and exiting namespaces. + context.enableEmitNotification(244 /* ModuleDeclaration */); + } + } + function isTransformedModuleDeclaration(node) { + return ts.getOriginalNode(node).kind === 244 /* ModuleDeclaration */; + } + function isTransformedEnumDeclaration(node) { + return ts.getOriginalNode(node).kind === 243 /* EnumDeclaration */; + } + /** + * Hook for node emit. + * + * @param hint A hint as to the intended usage of the node. + * @param node The node to emit. + * @param emit A callback used to emit the node in the printer. + */ + function onEmitNode(hint, node, emitCallback) { + var savedApplicableSubstitutions = applicableSubstitutions; + var savedCurrentSourceFile = currentSourceFile; + if (ts.isSourceFile(node)) { + currentSourceFile = node; + } + if (enabledSubstitutions & 2 /* NamespaceExports */ && isTransformedModuleDeclaration(node)) { + applicableSubstitutions |= 2 /* NamespaceExports */; + } + if (enabledSubstitutions & 8 /* NonQualifiedEnumMembers */ && isTransformedEnumDeclaration(node)) { + applicableSubstitutions |= 8 /* NonQualifiedEnumMembers */; + } + previousOnEmitNode(hint, node, emitCallback); + applicableSubstitutions = savedApplicableSubstitutions; + currentSourceFile = savedCurrentSourceFile; + } + /** + * Hooks node substitutions. + * + * @param hint A hint as to the intended usage of the node. + * @param node The node to substitute. + */ + function onSubstituteNode(hint, node) { + node = previousOnSubstituteNode(hint, node); + if (hint === 1 /* Expression */) { + return substituteExpression(node); + } + else if (ts.isShorthandPropertyAssignment(node)) { + return substituteShorthandPropertyAssignment(node); + } + return node; + } + function substituteShorthandPropertyAssignment(node) { + if (enabledSubstitutions & 2 /* NamespaceExports */) { + var name = node.name; + var exportedName = trySubstituteNamespaceExportedName(name); + if (exportedName) { + // A shorthand property with an assignment initializer is probably part of a + // destructuring assignment + if (node.objectAssignmentInitializer) { + var initializer = ts.createAssignment(exportedName, node.objectAssignmentInitializer); + return ts.setTextRange(ts.createPropertyAssignment(name, initializer), node); + } + return ts.setTextRange(ts.createPropertyAssignment(name, exportedName), node); + } + } + return node; + } + function substituteExpression(node) { + switch (node.kind) { + case 72 /* Identifier */: + return substituteExpressionIdentifier(node); + case 189 /* PropertyAccessExpression */: + return substitutePropertyAccessExpression(node); + case 190 /* ElementAccessExpression */: + return substituteElementAccessExpression(node); + } + return node; + } + function substituteExpressionIdentifier(node) { + return trySubstituteClassAlias(node) + || trySubstituteNamespaceExportedName(node) + || node; + } + function trySubstituteClassAlias(node) { + if (enabledSubstitutions & 1 /* ClassAliases */) { + if (resolver.getNodeCheckFlags(node) & 33554432 /* ConstructorReferenceInClass */) { + // Due to the emit for class decorators, any reference to the class from inside of the class body + // must instead be rewritten to point to a temporary variable to avoid issues with the double-bind + // behavior of class names in ES6. + // Also, when emitting statics for class expressions, we must substitute a class alias for + // constructor references in static property initializers. + var declaration = resolver.getReferencedValueDeclaration(node); + if (declaration) { + var classAlias = classAliases[declaration.id]; // TODO: GH#18217 + if (classAlias) { + var clone_1 = ts.getSynthesizedClone(classAlias); + ts.setSourceMapRange(clone_1, node); + ts.setCommentRange(clone_1, node); + return clone_1; + } + } + } + } + return undefined; + } + function trySubstituteNamespaceExportedName(node) { + // If this is explicitly a local name, do not substitute. + if (enabledSubstitutions & applicableSubstitutions && !ts.isGeneratedIdentifier(node) && !ts.isLocalName(node)) { + // If we are nested within a namespace declaration, we may need to qualifiy + // an identifier that is exported from a merged namespace. + var container = resolver.getReferencedExportContainer(node, /*prefixLocals*/ false); + if (container && container.kind !== 279 /* SourceFile */) { + var substitute = (applicableSubstitutions & 2 /* NamespaceExports */ && container.kind === 244 /* ModuleDeclaration */) || + (applicableSubstitutions & 8 /* NonQualifiedEnumMembers */ && container.kind === 243 /* EnumDeclaration */); + if (substitute) { + return ts.setTextRange(ts.createPropertyAccess(ts.getGeneratedNameForNode(container), node), + /*location*/ node); + } + } + } + return undefined; + } + function substitutePropertyAccessExpression(node) { + return substituteConstantValue(node); + } + function substituteElementAccessExpression(node) { + return substituteConstantValue(node); + } + function substituteConstantValue(node) { + var constantValue = tryGetConstEnumValue(node); + if (constantValue !== undefined) { + // track the constant value on the node for the printer in needsDotDotForPropertyAccess + ts.setConstantValue(node, constantValue); + var substitute = ts.createLiteral(constantValue); + if (!compilerOptions.removeComments) { + var propertyName = ts.isPropertyAccessExpression(node) + ? ts.declarationNameToString(node.name) + : ts.getTextOfNode(node.argumentExpression); + ts.addSyntheticTrailingComment(substitute, 3 /* MultiLineCommentTrivia */, " " + propertyName + " "); + } + return substitute; + } + return node; + } + function tryGetConstEnumValue(node) { + if (compilerOptions.isolatedModules) { + return undefined; + } + return ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node) ? resolver.getConstantValue(node) : undefined; + } + } + ts.transformTypeScript = transformTypeScript; + function createDecorateHelper(context, decoratorExpressions, target, memberName, descriptor, location) { + var argumentsArray = []; + argumentsArray.push(ts.createArrayLiteral(decoratorExpressions, /*multiLine*/ true)); + argumentsArray.push(target); + if (memberName) { + argumentsArray.push(memberName); + if (descriptor) { + argumentsArray.push(descriptor); + } + } + context.requestEmitHelper(decorateHelper); + return ts.setTextRange(ts.createCall(ts.getHelperName("__decorate"), + /*typeArguments*/ undefined, argumentsArray), location); + } + var decorateHelper = { + name: "typescript:decorate", + scoped: false, + priority: 2, + text: "\n var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n };" + }; + function createMetadataHelper(context, metadataKey, metadataValue) { + context.requestEmitHelper(metadataHelper); + return ts.createCall(ts.getHelperName("__metadata"), + /*typeArguments*/ undefined, [ + ts.createLiteral(metadataKey), + metadataValue + ]); + } + var metadataHelper = { + name: "typescript:metadata", + scoped: false, + priority: 3, + text: "\n var __metadata = (this && this.__metadata) || function (k, v) {\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(k, v);\n };" + }; + function createParamHelper(context, expression, parameterOffset, location) { + context.requestEmitHelper(paramHelper); + return ts.setTextRange(ts.createCall(ts.getHelperName("__param"), + /*typeArguments*/ undefined, [ + ts.createLiteral(parameterOffset), + expression + ]), location); + } + var paramHelper = { + name: "typescript:param", + scoped: false, + priority: 4, + text: "\n var __param = (this && this.__param) || function (paramIndex, decorator) {\n return function (target, key) { decorator(target, key, paramIndex); }\n };" + }; +})(ts || (ts = {})); +/*@internal*/ +var ts; +(function (ts) { + var ES2017SubstitutionFlags; + (function (ES2017SubstitutionFlags) { + /** Enables substitutions for async methods with `super` calls. */ + ES2017SubstitutionFlags[ES2017SubstitutionFlags["AsyncMethodsWithSuper"] = 1] = "AsyncMethodsWithSuper"; + })(ES2017SubstitutionFlags || (ES2017SubstitutionFlags = {})); + function transformES2017(context) { + var resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; + var resolver = context.getEmitResolver(); + var compilerOptions = context.getCompilerOptions(); + var languageVersion = ts.getEmitScriptTarget(compilerOptions); + /** + * Keeps track of whether expression substitution has been enabled for specific edge cases. + * They are persisted between each SourceFile transformation and should not be reset. + */ + var enabledSubstitutions; + /** + * This keeps track of containers where `super` is valid, for use with + * just-in-time substitution for `super` expressions inside of async methods. + */ + var enclosingSuperContainerFlags = 0; + var enclosingFunctionParameterNames; + /** + * Keeps track of property names accessed on super (`super.x`) within async functions. + */ + var capturedSuperProperties; + /** Whether the async function contains an element access on super (`super[x]`). */ + var hasSuperElementAccess; + /** A set of node IDs for generated super accessors (variable statements). */ + var substitutedSuperAccessors = []; + // Save the previous transformation hooks. + var previousOnEmitNode = context.onEmitNode; + var previousOnSubstituteNode = context.onSubstituteNode; + // Set new transformation hooks. + context.onEmitNode = onEmitNode; + context.onSubstituteNode = onSubstituteNode; + return ts.chainBundle(transformSourceFile); + function transformSourceFile(node) { + if (node.isDeclarationFile) { + return node; + } + var visited = ts.visitEachChild(node, visitor, context); + ts.addEmitHelpers(visited, context.readEmitHelpers()); + return visited; + } + function visitor(node) { + if ((node.transformFlags & 16 /* ContainsES2017 */) === 0) { + return node; + } + switch (node.kind) { + case 121 /* AsyncKeyword */: + // ES2017 async modifier should be elided for targets < ES2017 + return undefined; + case 201 /* AwaitExpression */: + return visitAwaitExpression(node); + case 156 /* MethodDeclaration */: + return visitMethodDeclaration(node); + case 239 /* FunctionDeclaration */: + return visitFunctionDeclaration(node); + case 196 /* FunctionExpression */: + return visitFunctionExpression(node); + case 197 /* ArrowFunction */: + return visitArrowFunction(node); + case 189 /* PropertyAccessExpression */: + if (capturedSuperProperties && ts.isPropertyAccessExpression(node) && node.expression.kind === 98 /* SuperKeyword */) { + capturedSuperProperties.set(node.name.escapedText, true); + } + return ts.visitEachChild(node, visitor, context); + case 190 /* ElementAccessExpression */: + if (capturedSuperProperties && node.expression.kind === 98 /* SuperKeyword */) { + hasSuperElementAccess = true; + } + return ts.visitEachChild(node, visitor, context); + default: + return ts.visitEachChild(node, visitor, context); + } + } + function asyncBodyVisitor(node) { + if (ts.isNodeWithPossibleHoistedDeclaration(node)) { + switch (node.kind) { + case 219 /* VariableStatement */: + return visitVariableStatementInAsyncBody(node); + case 225 /* ForStatement */: + return visitForStatementInAsyncBody(node); + case 226 /* ForInStatement */: + return visitForInStatementInAsyncBody(node); + case 227 /* ForOfStatement */: + return visitForOfStatementInAsyncBody(node); + case 274 /* CatchClause */: + return visitCatchClauseInAsyncBody(node); + case 218 /* Block */: + case 232 /* SwitchStatement */: + case 246 /* CaseBlock */: + case 271 /* CaseClause */: + case 272 /* DefaultClause */: + case 235 /* TryStatement */: + case 223 /* DoStatement */: + case 224 /* WhileStatement */: + case 222 /* IfStatement */: + case 231 /* WithStatement */: + case 233 /* LabeledStatement */: + return ts.visitEachChild(node, asyncBodyVisitor, context); + default: + return ts.Debug.assertNever(node, "Unhandled node."); + } + } + return visitor(node); + } + function visitCatchClauseInAsyncBody(node) { + var catchClauseNames = ts.createUnderscoreEscapedMap(); + recordDeclarationName(node.variableDeclaration, catchClauseNames); // TODO: GH#18217 + // names declared in a catch variable are block scoped + var catchClauseUnshadowedNames; + catchClauseNames.forEach(function (_, escapedName) { + if (enclosingFunctionParameterNames.has(escapedName)) { + if (!catchClauseUnshadowedNames) { + catchClauseUnshadowedNames = ts.cloneMap(enclosingFunctionParameterNames); + } + catchClauseUnshadowedNames.delete(escapedName); + } + }); + if (catchClauseUnshadowedNames) { + var savedEnclosingFunctionParameterNames = enclosingFunctionParameterNames; + enclosingFunctionParameterNames = catchClauseUnshadowedNames; + var result = ts.visitEachChild(node, asyncBodyVisitor, context); + enclosingFunctionParameterNames = savedEnclosingFunctionParameterNames; + return result; + } + else { + return ts.visitEachChild(node, asyncBodyVisitor, context); + } + } + function visitVariableStatementInAsyncBody(node) { + if (isVariableDeclarationListWithCollidingName(node.declarationList)) { + var expression = visitVariableDeclarationListWithCollidingNames(node.declarationList, /*hasReceiver*/ false); + return expression ? ts.createExpressionStatement(expression) : undefined; + } + return ts.visitEachChild(node, visitor, context); + } + function visitForInStatementInAsyncBody(node) { + return ts.updateForIn(node, isVariableDeclarationListWithCollidingName(node.initializer) + ? visitVariableDeclarationListWithCollidingNames(node.initializer, /*hasReceiver*/ true) + : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitNode(node.statement, asyncBodyVisitor, ts.isStatement, ts.liftToBlock)); + } + function visitForOfStatementInAsyncBody(node) { + return ts.updateForOf(node, ts.visitNode(node.awaitModifier, visitor, ts.isToken), isVariableDeclarationListWithCollidingName(node.initializer) + ? visitVariableDeclarationListWithCollidingNames(node.initializer, /*hasReceiver*/ true) + : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitNode(node.statement, asyncBodyVisitor, ts.isStatement, ts.liftToBlock)); + } + function visitForStatementInAsyncBody(node) { + var initializer = node.initializer; // TODO: GH#18217 + return ts.updateFor(node, isVariableDeclarationListWithCollidingName(initializer) + ? visitVariableDeclarationListWithCollidingNames(initializer, /*hasReceiver*/ false) + : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.condition, visitor, ts.isExpression), ts.visitNode(node.incrementor, visitor, ts.isExpression), ts.visitNode(node.statement, asyncBodyVisitor, ts.isStatement, ts.liftToBlock)); + } + /** + * Visits an AwaitExpression node. + * + * This function will be called any time a ES2017 await expression is encountered. + * + * @param node The node to visit. + */ + function visitAwaitExpression(node) { + return ts.setOriginalNode(ts.setTextRange(ts.createYield( + /*asteriskToken*/ undefined, ts.visitNode(node.expression, visitor, ts.isExpression)), node), node); + } + /** + * Visits a MethodDeclaration node. + * + * This function will be called when one of the following conditions are met: + * - The node is marked as async + * + * @param node The node to visit. + */ + function visitMethodDeclaration(node) { + return ts.updateMethod(node, + /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, node.name, + /*questionToken*/ undefined, + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, ts.getFunctionFlags(node) & 2 /* Async */ + ? transformAsyncFunctionBody(node) + : ts.visitFunctionBody(node.body, visitor, context)); + } + /** + * Visits a FunctionDeclaration node. + * + * This function will be called when one of the following conditions are met: + * - The node is marked async + * + * @param node The node to visit. + */ + function visitFunctionDeclaration(node) { + return ts.updateFunctionDeclaration(node, + /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, node.name, + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, ts.getFunctionFlags(node) & 2 /* Async */ + ? transformAsyncFunctionBody(node) + : ts.visitFunctionBody(node.body, visitor, context)); + } + /** + * Visits a FunctionExpression node. + * + * This function will be called when one of the following conditions are met: + * - The node is marked async + * + * @param node The node to visit. + */ + function visitFunctionExpression(node) { + return ts.updateFunctionExpression(node, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, node.name, + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, ts.getFunctionFlags(node) & 2 /* Async */ + ? transformAsyncFunctionBody(node) + : ts.visitFunctionBody(node.body, visitor, context)); + } + /** + * Visits an ArrowFunction. + * + * This function will be called when one of the following conditions are met: + * - The node is marked async + * + * @param node The node to visit. + */ + function visitArrowFunction(node) { + return ts.updateArrowFunction(node, ts.visitNodes(node.modifiers, visitor, ts.isModifier), + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, node.equalsGreaterThanToken, ts.getFunctionFlags(node) & 2 /* Async */ + ? transformAsyncFunctionBody(node) + : ts.visitFunctionBody(node.body, visitor, context)); + } + function recordDeclarationName(_a, names) { + var name = _a.name; + if (ts.isIdentifier(name)) { + names.set(name.escapedText, true); + } + else { + for (var _i = 0, _b = name.elements; _i < _b.length; _i++) { + var element = _b[_i]; + if (!ts.isOmittedExpression(element)) { + recordDeclarationName(element, names); + } + } + } + } + function isVariableDeclarationListWithCollidingName(node) { + return !!node + && ts.isVariableDeclarationList(node) + && !(node.flags & 3 /* BlockScoped */) + && node.declarations.some(collidesWithParameterName); + } + function visitVariableDeclarationListWithCollidingNames(node, hasReceiver) { + hoistVariableDeclarationList(node); + var variables = ts.getInitializedVariables(node); + if (variables.length === 0) { + if (hasReceiver) { + return ts.visitNode(ts.convertToAssignmentElementTarget(node.declarations[0].name), visitor, ts.isExpression); + } + return undefined; + } + return ts.inlineExpressions(ts.map(variables, transformInitializedVariable)); + } + function hoistVariableDeclarationList(node) { + ts.forEach(node.declarations, hoistVariable); + } + function hoistVariable(_a) { + var name = _a.name; + if (ts.isIdentifier(name)) { + hoistVariableDeclaration(name); + } + else { + for (var _i = 0, _b = name.elements; _i < _b.length; _i++) { + var element = _b[_i]; + if (!ts.isOmittedExpression(element)) { + hoistVariable(element); + } + } + } + } + function transformInitializedVariable(node) { + var converted = ts.setSourceMapRange(ts.createAssignment(ts.convertToAssignmentElementTarget(node.name), node.initializer), node); + return ts.visitNode(converted, visitor, ts.isExpression); + } + function collidesWithParameterName(_a) { + var name = _a.name; + if (ts.isIdentifier(name)) { + return enclosingFunctionParameterNames.has(name.escapedText); + } + else { + for (var _i = 0, _b = name.elements; _i < _b.length; _i++) { + var element = _b[_i]; + if (!ts.isOmittedExpression(element) && collidesWithParameterName(element)) { + return true; + } + } + } + return false; + } + function transformAsyncFunctionBody(node) { + resumeLexicalEnvironment(); + var original = ts.getOriginalNode(node, ts.isFunctionLike); + var nodeType = original.type; + var promiseConstructor = languageVersion < 2 /* ES2015 */ ? getPromiseConstructor(nodeType) : undefined; + var isArrowFunction = node.kind === 197 /* ArrowFunction */; + var hasLexicalArguments = (resolver.getNodeCheckFlags(node) & 8192 /* CaptureArguments */) !== 0; + // An async function is emit as an outer function that calls an inner + // generator function. To preserve lexical bindings, we pass the current + // `this` and `arguments` objects to `__awaiter`. The generator function + // passed to `__awaiter` is executed inside of the callback to the + // promise constructor. + var savedEnclosingFunctionParameterNames = enclosingFunctionParameterNames; + enclosingFunctionParameterNames = ts.createUnderscoreEscapedMap(); + for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { + var parameter = _a[_i]; + recordDeclarationName(parameter, enclosingFunctionParameterNames); + } + var savedCapturedSuperProperties = capturedSuperProperties; + var savedHasSuperElementAccess = hasSuperElementAccess; + capturedSuperProperties = ts.createUnderscoreEscapedMap(); + hasSuperElementAccess = false; + var result; + if (!isArrowFunction) { + var statements = []; + var statementOffset = ts.addPrologue(statements, node.body.statements, /*ensureUseStrict*/ false, visitor); + statements.push(ts.createReturn(createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, transformAsyncFunctionBodyWorker(node.body, statementOffset)))); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + // Minor optimization, emit `_super` helper to capture `super` access in an arrow. + // This step isn't needed if we eventually transform this to ES5. + var emitSuperHelpers = languageVersion >= 2 /* ES2015 */ && resolver.getNodeCheckFlags(node) & (4096 /* AsyncMethodWithSuperBinding */ | 2048 /* AsyncMethodWithSuper */); + if (emitSuperHelpers) { + enableSubstitutionForAsyncMethodsWithSuper(); + var variableStatement = createSuperAccessVariableStatement(resolver, node, capturedSuperProperties); + substitutedSuperAccessors[ts.getNodeId(variableStatement)] = true; + ts.addStatementsAfterPrologue(statements, [variableStatement]); + } + var block = ts.createBlock(statements, /*multiLine*/ true); + ts.setTextRange(block, node.body); + if (emitSuperHelpers && hasSuperElementAccess) { + // Emit helpers for super element access expressions (`super[x]`). + if (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) { + ts.addEmitHelper(block, ts.advancedAsyncSuperHelper); + } + else if (resolver.getNodeCheckFlags(node) & 2048 /* AsyncMethodWithSuper */) { + ts.addEmitHelper(block, ts.asyncSuperHelper); + } + } + result = block; + } + else { + var expression = createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, transformAsyncFunctionBodyWorker(node.body)); + var declarations = endLexicalEnvironment(); + if (ts.some(declarations)) { + var block = ts.convertToFunctionBody(expression); + result = ts.updateBlock(block, ts.setTextRange(ts.createNodeArray(ts.concatenate(declarations, block.statements)), block.statements)); + } + else { + result = expression; + } + } + enclosingFunctionParameterNames = savedEnclosingFunctionParameterNames; + capturedSuperProperties = savedCapturedSuperProperties; + hasSuperElementAccess = savedHasSuperElementAccess; + return result; + } + function transformAsyncFunctionBodyWorker(body, start) { + if (ts.isBlock(body)) { + return ts.updateBlock(body, ts.visitNodes(body.statements, asyncBodyVisitor, ts.isStatement, start)); + } + else { + return ts.convertToFunctionBody(ts.visitNode(body, asyncBodyVisitor, ts.isConciseBody)); + } + } + function getPromiseConstructor(type) { + var typeName = type && ts.getEntityNameFromTypeNode(type); + if (typeName && ts.isEntityName(typeName)) { + var serializationKind = resolver.getTypeReferenceSerializationKind(typeName); + if (serializationKind === ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue + || serializationKind === ts.TypeReferenceSerializationKind.Unknown) { + return typeName; + } + } + return undefined; + } + function enableSubstitutionForAsyncMethodsWithSuper() { + if ((enabledSubstitutions & 1 /* AsyncMethodsWithSuper */) === 0) { + enabledSubstitutions |= 1 /* AsyncMethodsWithSuper */; + // We need to enable substitutions for call, property access, and element access + // if we need to rewrite super calls. + context.enableSubstitution(191 /* CallExpression */); + context.enableSubstitution(189 /* PropertyAccessExpression */); + context.enableSubstitution(190 /* ElementAccessExpression */); + // We need to be notified when entering and exiting declarations that bind super. + context.enableEmitNotification(240 /* ClassDeclaration */); + context.enableEmitNotification(156 /* MethodDeclaration */); + context.enableEmitNotification(158 /* GetAccessor */); + context.enableEmitNotification(159 /* SetAccessor */); + context.enableEmitNotification(157 /* Constructor */); + // We need to be notified when entering the generated accessor arrow functions. + context.enableEmitNotification(219 /* VariableStatement */); + } + } + /** + * Hook for node emit. + * + * @param hint A hint as to the intended usage of the node. + * @param node The node to emit. + * @param emit A callback used to emit the node in the printer. + */ + function onEmitNode(hint, node, emitCallback) { + // If we need to support substitutions for `super` in an async method, + // we should track it here. + if (enabledSubstitutions & 1 /* AsyncMethodsWithSuper */ && isSuperContainer(node)) { + var superContainerFlags = resolver.getNodeCheckFlags(node) & (2048 /* AsyncMethodWithSuper */ | 4096 /* AsyncMethodWithSuperBinding */); + if (superContainerFlags !== enclosingSuperContainerFlags) { + var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags; + enclosingSuperContainerFlags = superContainerFlags; + previousOnEmitNode(hint, node, emitCallback); + enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags; + return; + } + } + // Disable substitution in the generated super accessor itself. + else if (enabledSubstitutions && substitutedSuperAccessors[ts.getNodeId(node)]) { + var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags; + enclosingSuperContainerFlags = 0; + previousOnEmitNode(hint, node, emitCallback); + enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags; + return; + } + previousOnEmitNode(hint, node, emitCallback); + } + /** + * Hooks node substitutions. + * + * @param hint A hint as to the intended usage of the node. + * @param node The node to substitute. + */ + function onSubstituteNode(hint, node) { + node = previousOnSubstituteNode(hint, node); + if (hint === 1 /* Expression */ && enclosingSuperContainerFlags) { + return substituteExpression(node); + } + return node; + } + function substituteExpression(node) { + switch (node.kind) { + case 189 /* PropertyAccessExpression */: + return substitutePropertyAccessExpression(node); + case 190 /* ElementAccessExpression */: + return substituteElementAccessExpression(node); + case 191 /* CallExpression */: + return substituteCallExpression(node); + } + return node; + } + function substitutePropertyAccessExpression(node) { + if (node.expression.kind === 98 /* SuperKeyword */) { + return ts.setTextRange(ts.createPropertyAccess(ts.createFileLevelUniqueName("_super"), node.name), node); + } + return node; + } + function substituteElementAccessExpression(node) { + if (node.expression.kind === 98 /* SuperKeyword */) { + return createSuperElementAccessInAsyncMethod(node.argumentExpression, node); + } + return node; + } + function substituteCallExpression(node) { + var expression = node.expression; + if (ts.isSuperProperty(expression)) { + var argumentExpression = ts.isPropertyAccessExpression(expression) + ? substitutePropertyAccessExpression(expression) + : substituteElementAccessExpression(expression); + return ts.createCall(ts.createPropertyAccess(argumentExpression, "call"), + /*typeArguments*/ undefined, [ + ts.createThis() + ].concat(node.arguments)); + } + return node; + } + function isSuperContainer(node) { + var kind = node.kind; + return kind === 240 /* ClassDeclaration */ + || kind === 157 /* Constructor */ + || kind === 156 /* MethodDeclaration */ + || kind === 158 /* GetAccessor */ + || kind === 159 /* SetAccessor */; + } + function createSuperElementAccessInAsyncMethod(argumentExpression, location) { + if (enclosingSuperContainerFlags & 4096 /* AsyncMethodWithSuperBinding */) { + return ts.setTextRange(ts.createPropertyAccess(ts.createCall(ts.createFileLevelUniqueName("_superIndex"), + /*typeArguments*/ undefined, [argumentExpression]), "value"), location); + } + else { + return ts.setTextRange(ts.createCall(ts.createFileLevelUniqueName("_superIndex"), + /*typeArguments*/ undefined, [argumentExpression]), location); + } + } + } + ts.transformES2017 = transformES2017; + /** Creates a variable named `_super` with accessor properties for the given property names. */ + function createSuperAccessVariableStatement(resolver, node, names) { + // Create a variable declaration with a getter/setter (if binding) definition for each name: + // const _super = Object.create(null, { x: { get: () => super.x, set: (v) => super.x = v }, ... }); + var hasBinding = (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) !== 0; + var accessors = []; + names.forEach(function (_, key) { + var name = ts.unescapeLeadingUnderscores(key); + var getterAndSetter = []; + getterAndSetter.push(ts.createPropertyAssignment("get", ts.createArrowFunction( + /* modifiers */ undefined, + /* typeParameters */ undefined, + /* parameters */ [], + /* type */ undefined, + /* equalsGreaterThanToken */ undefined, ts.createPropertyAccess(ts.createSuper(), name)))); + if (hasBinding) { + getterAndSetter.push(ts.createPropertyAssignment("set", ts.createArrowFunction( + /* modifiers */ undefined, + /* typeParameters */ undefined, + /* parameters */ [ + ts.createParameter( + /* decorators */ undefined, + /* modifiers */ undefined, + /* dotDotDotToken */ undefined, "v", + /* questionToken */ undefined, + /* type */ undefined, + /* initializer */ undefined) + ], + /* type */ undefined, + /* equalsGreaterThanToken */ undefined, ts.createAssignment(ts.createPropertyAccess(ts.createSuper(), name), ts.createIdentifier("v"))))); + } + accessors.push(ts.createPropertyAssignment(name, ts.createObjectLiteral(getterAndSetter))); + }); + return ts.createVariableStatement( + /* modifiers */ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(ts.createFileLevelUniqueName("_super"), + /* type */ undefined, ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "create"), + /* typeArguments */ undefined, [ + ts.createNull(), + ts.createObjectLiteral(accessors, /* multiline */ true) + ])) + ], 2 /* Const */)); + } + ts.createSuperAccessVariableStatement = createSuperAccessVariableStatement; + var awaiterHelper = { + name: "typescript:awaiter", + scoped: false, + priority: 5, + text: "\n var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n };" + }; + function createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, body) { + context.requestEmitHelper(awaiterHelper); + var generatorFunc = ts.createFunctionExpression( + /*modifiers*/ undefined, ts.createToken(40 /* AsteriskToken */), + /*name*/ undefined, + /*typeParameters*/ undefined, + /*parameters*/ [], + /*type*/ undefined, body); + // Mark this node as originally an async function + (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 262144 /* AsyncFunctionBody */ | 524288 /* ReuseTempVariableScope */; + return ts.createCall(ts.getHelperName("__awaiter"), + /*typeArguments*/ undefined, [ + ts.createThis(), + hasLexicalArguments ? ts.createIdentifier("arguments") : ts.createVoidZero(), + promiseConstructor ? ts.createExpressionFromEntityName(promiseConstructor) : ts.createVoidZero(), + generatorFunc + ]); + } + ts.asyncSuperHelper = { + name: "typescript:async-super", + scoped: true, + text: ts.helperString(__makeTemplateObject(["\n const ", " = name => super[name];"], ["\n const ", " = name => super[name];"]), "_superIndex") + }; + ts.advancedAsyncSuperHelper = { + name: "typescript:advanced-async-super", + scoped: true, + text: ts.helperString(__makeTemplateObject(["\n const ", " = (function (geti, seti) {\n const cache = Object.create(null);\n return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } });\n })(name => super[name], (name, value) => super[name] = value);"], ["\n const ", " = (function (geti, seti) {\n const cache = Object.create(null);\n return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } });\n })(name => super[name], (name, value) => super[name] = value);"]), "_superIndex") + }; +})(ts || (ts = {})); +/*@internal*/ +var ts; +(function (ts) { + var ESNextSubstitutionFlags; + (function (ESNextSubstitutionFlags) { + /** Enables substitutions for async methods with `super` calls. */ + ESNextSubstitutionFlags[ESNextSubstitutionFlags["AsyncMethodsWithSuper"] = 1] = "AsyncMethodsWithSuper"; + })(ESNextSubstitutionFlags || (ESNextSubstitutionFlags = {})); + function transformESNext(context) { + var resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; + var resolver = context.getEmitResolver(); + var compilerOptions = context.getCompilerOptions(); + var languageVersion = ts.getEmitScriptTarget(compilerOptions); + var previousOnEmitNode = context.onEmitNode; + context.onEmitNode = onEmitNode; + var previousOnSubstituteNode = context.onSubstituteNode; + context.onSubstituteNode = onSubstituteNode; + var enabledSubstitutions; + var enclosingFunctionFlags; + var enclosingSuperContainerFlags = 0; + /** Keeps track of property names accessed on super (`super.x`) within async functions. */ + var capturedSuperProperties; + /** Whether the async function contains an element access on super (`super[x]`). */ + var hasSuperElementAccess; + /** A set of node IDs for generated super accessors. */ + var substitutedSuperAccessors = []; + return ts.chainBundle(transformSourceFile); + function transformSourceFile(node) { + if (node.isDeclarationFile) { + return node; + } + var visited = ts.visitEachChild(node, visitor, context); + ts.addEmitHelpers(visited, context.readEmitHelpers()); + return visited; + } + function visitor(node) { + return visitorWorker(node, /*noDestructuringValue*/ false); + } + function visitorNoDestructuringValue(node) { + return visitorWorker(node, /*noDestructuringValue*/ true); + } + function visitorNoAsyncModifier(node) { + if (node.kind === 121 /* AsyncKeyword */) { + return undefined; + } + return node; + } + function visitorWorker(node, noDestructuringValue) { + if ((node.transformFlags & 8 /* ContainsESNext */) === 0) { + return node; + } + switch (node.kind) { + case 201 /* AwaitExpression */: + return visitAwaitExpression(node); + case 207 /* YieldExpression */: + return visitYieldExpression(node); + case 230 /* ReturnStatement */: + return visitReturnStatement(node); + case 233 /* LabeledStatement */: + return visitLabeledStatement(node); + case 188 /* ObjectLiteralExpression */: + return visitObjectLiteralExpression(node); + case 204 /* BinaryExpression */: + return visitBinaryExpression(node, noDestructuringValue); + case 237 /* VariableDeclaration */: + return visitVariableDeclaration(node); + case 227 /* ForOfStatement */: + return visitForOfStatement(node, /*outermostLabeledStatement*/ undefined); + case 225 /* ForStatement */: + return visitForStatement(node); + case 200 /* VoidExpression */: + return visitVoidExpression(node); + case 157 /* Constructor */: + return visitConstructorDeclaration(node); + case 156 /* MethodDeclaration */: + return visitMethodDeclaration(node); + case 158 /* GetAccessor */: + return visitGetAccessorDeclaration(node); + case 159 /* SetAccessor */: + return visitSetAccessorDeclaration(node); + case 239 /* FunctionDeclaration */: + return visitFunctionDeclaration(node); + case 196 /* FunctionExpression */: + return visitFunctionExpression(node); + case 197 /* ArrowFunction */: + return visitArrowFunction(node); + case 151 /* Parameter */: + return visitParameter(node); + case 221 /* ExpressionStatement */: + return visitExpressionStatement(node); + case 195 /* ParenthesizedExpression */: + return visitParenthesizedExpression(node, noDestructuringValue); + case 274 /* CatchClause */: + return visitCatchClause(node); + case 189 /* PropertyAccessExpression */: + if (capturedSuperProperties && ts.isPropertyAccessExpression(node) && node.expression.kind === 98 /* SuperKeyword */) { + capturedSuperProperties.set(node.name.escapedText, true); + } + return ts.visitEachChild(node, visitor, context); + case 190 /* ElementAccessExpression */: + if (capturedSuperProperties && node.expression.kind === 98 /* SuperKeyword */) { + hasSuperElementAccess = true; + } + return ts.visitEachChild(node, visitor, context); + default: + return ts.visitEachChild(node, visitor, context); + } + } + function visitAwaitExpression(node) { + if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */) { + return ts.setOriginalNode(ts.setTextRange(ts.createYield(createAwaitHelper(context, ts.visitNode(node.expression, visitor, ts.isExpression))), + /*location*/ node), node); + } + return ts.visitEachChild(node, visitor, context); + } + function visitYieldExpression(node) { + if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */) { + if (node.asteriskToken) { + var expression = ts.visitNode(node.expression, visitor, ts.isExpression); + return ts.setOriginalNode(ts.setTextRange(ts.createYield(createAwaitHelper(context, ts.updateYield(node, node.asteriskToken, createAsyncDelegatorHelper(context, createAsyncValuesHelper(context, expression, expression), expression)))), node), node); + } + return ts.setOriginalNode(ts.setTextRange(ts.createYield(createDownlevelAwait(node.expression + ? ts.visitNode(node.expression, visitor, ts.isExpression) + : ts.createVoidZero())), node), node); + } + return ts.visitEachChild(node, visitor, context); + } + function visitReturnStatement(node) { + if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */) { + return ts.updateReturn(node, createDownlevelAwait(node.expression ? ts.visitNode(node.expression, visitor, ts.isExpression) : ts.createVoidZero())); + } + return ts.visitEachChild(node, visitor, context); + } + function visitLabeledStatement(node) { + if (enclosingFunctionFlags & 2 /* Async */) { + var statement = ts.unwrapInnermostStatementOfLabel(node); + if (statement.kind === 227 /* ForOfStatement */ && statement.awaitModifier) { + return visitForOfStatement(statement, node); + } + return ts.restoreEnclosingLabel(ts.visitEachChild(statement, visitor, context), node); + } + return ts.visitEachChild(node, visitor, context); + } + function chunkObjectLiteralElements(elements) { + var chunkObject; + var objects = []; + for (var _i = 0, elements_4 = elements; _i < elements_4.length; _i++) { + var e = elements_4[_i]; + if (e.kind === 277 /* SpreadAssignment */) { + if (chunkObject) { + objects.push(ts.createObjectLiteral(chunkObject)); + chunkObject = undefined; + } + var target = e.expression; + objects.push(ts.visitNode(target, visitor, ts.isExpression)); + } + else { + chunkObject = ts.append(chunkObject, e.kind === 275 /* PropertyAssignment */ + ? ts.createPropertyAssignment(e.name, ts.visitNode(e.initializer, visitor, ts.isExpression)) + : ts.visitNode(e, visitor, ts.isObjectLiteralElementLike)); + } + } + if (chunkObject) { + objects.push(ts.createObjectLiteral(chunkObject)); + } + return objects; + } + function visitObjectLiteralExpression(node) { + if (node.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { + // spread elements emit like so: + // non-spread elements are chunked together into object literals, and then all are passed to __assign: + // { a, ...o, b } => __assign({a}, o, {b}); + // If the first element is a spread element, then the first argument to __assign is {}: + // { ...o, a, b, ...o2 } => __assign({}, o, {a, b}, o2) + var objects = chunkObjectLiteralElements(node.properties); + if (objects.length && objects[0].kind !== 188 /* ObjectLiteralExpression */) { + objects.unshift(ts.createObjectLiteral()); + } + return createAssignHelper(context, objects); + } + return ts.visitEachChild(node, visitor, context); + } + function visitExpressionStatement(node) { + return ts.visitEachChild(node, visitorNoDestructuringValue, context); + } + function visitParenthesizedExpression(node, noDestructuringValue) { + return ts.visitEachChild(node, noDestructuringValue ? visitorNoDestructuringValue : visitor, context); + } + function visitCatchClause(node) { + if (!node.variableDeclaration) { + return ts.updateCatchClause(node, ts.createVariableDeclaration(ts.createTempVariable(/*recordTempVariable*/ undefined)), ts.visitNode(node.block, visitor, ts.isBlock)); + } + return ts.visitEachChild(node, visitor, context); + } + /** + * Visits a BinaryExpression that contains a destructuring assignment. + * + * @param node A BinaryExpression node. + */ + function visitBinaryExpression(node, noDestructuringValue) { + if (ts.isDestructuringAssignment(node) && node.left.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { + return ts.flattenDestructuringAssignment(node, visitor, context, 1 /* ObjectRest */, !noDestructuringValue); + } + else if (node.operatorToken.kind === 27 /* CommaToken */) { + return ts.updateBinary(node, ts.visitNode(node.left, visitorNoDestructuringValue, ts.isExpression), ts.visitNode(node.right, noDestructuringValue ? visitorNoDestructuringValue : visitor, ts.isExpression)); + } + return ts.visitEachChild(node, visitor, context); + } + /** + * Visits a VariableDeclaration node with a binding pattern. + * + * @param node A VariableDeclaration node. + */ + function visitVariableDeclaration(node) { + // If we are here it is because the name contains a binding pattern with a rest somewhere in it. + if (ts.isBindingPattern(node.name) && node.name.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { + return ts.flattenDestructuringBinding(node, visitor, context, 1 /* ObjectRest */); + } + return ts.visitEachChild(node, visitor, context); + } + function visitForStatement(node) { + return ts.updateFor(node, ts.visitNode(node.initializer, visitorNoDestructuringValue, ts.isForInitializer), ts.visitNode(node.condition, visitor, ts.isExpression), ts.visitNode(node.incrementor, visitor, ts.isExpression), ts.visitNode(node.statement, visitor, ts.isStatement)); + } + function visitVoidExpression(node) { + return ts.visitEachChild(node, visitorNoDestructuringValue, context); + } + /** + * Visits a ForOfStatement and converts it into a ES2015-compatible ForOfStatement. + * + * @param node A ForOfStatement. + */ + function visitForOfStatement(node, outermostLabeledStatement) { + if (node.initializer.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { + node = transformForOfStatementWithObjectRest(node); + } + if (node.awaitModifier) { + return transformForAwaitOfStatement(node, outermostLabeledStatement); + } + else { + return ts.restoreEnclosingLabel(ts.visitEachChild(node, visitor, context), outermostLabeledStatement); + } + } + function transformForOfStatementWithObjectRest(node) { + var initializerWithoutParens = ts.skipParentheses(node.initializer); + if (ts.isVariableDeclarationList(initializerWithoutParens) || ts.isAssignmentPattern(initializerWithoutParens)) { + var bodyLocation = void 0; + var statementsLocation = void 0; + var temp = ts.createTempVariable(/*recordTempVariable*/ undefined); + var statements = [ts.createForOfBindingStatement(initializerWithoutParens, temp)]; + if (ts.isBlock(node.statement)) { + ts.addRange(statements, node.statement.statements); + bodyLocation = node.statement; + statementsLocation = node.statement.statements; + } + else if (node.statement) { + ts.append(statements, node.statement); + bodyLocation = node.statement; + statementsLocation = node.statement; + } + return ts.updateForOf(node, node.awaitModifier, ts.setTextRange(ts.createVariableDeclarationList([ + ts.setTextRange(ts.createVariableDeclaration(temp), node.initializer) + ], 1 /* Let */), node.initializer), node.expression, ts.setTextRange(ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), statementsLocation), + /*multiLine*/ true), bodyLocation)); + } + return node; + } + function convertForOfStatementHead(node, boundValue) { + var binding = ts.createForOfBindingStatement(node.initializer, boundValue); + var bodyLocation; + var statementsLocation; + var statements = [ts.visitNode(binding, visitor, ts.isStatement)]; + var statement = ts.visitNode(node.statement, visitor, ts.isStatement); + if (ts.isBlock(statement)) { + ts.addRange(statements, statement.statements); + bodyLocation = statement; + statementsLocation = statement.statements; + } + else { + statements.push(statement); + } + return ts.setEmitFlags(ts.setTextRange(ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), statementsLocation), + /*multiLine*/ true), bodyLocation), 48 /* NoSourceMap */ | 384 /* NoTokenSourceMaps */); + } + function createDownlevelAwait(expression) { + return enclosingFunctionFlags & 1 /* Generator */ + ? ts.createYield(/*asteriskToken*/ undefined, createAwaitHelper(context, expression)) + : ts.createAwait(expression); + } + function transformForAwaitOfStatement(node, outermostLabeledStatement) { + var expression = ts.visitNode(node.expression, visitor, ts.isExpression); + var iterator = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(expression) : ts.createTempVariable(/*recordTempVariable*/ undefined); + var result = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(iterator) : ts.createTempVariable(/*recordTempVariable*/ undefined); + var errorRecord = ts.createUniqueName("e"); + var catchVariable = ts.getGeneratedNameForNode(errorRecord); + var returnMethod = ts.createTempVariable(/*recordTempVariable*/ undefined); + var callValues = createAsyncValuesHelper(context, expression, /*location*/ node.expression); + var callNext = ts.createCall(ts.createPropertyAccess(iterator, "next"), /*typeArguments*/ undefined, []); + var getDone = ts.createPropertyAccess(result, "done"); + var getValue = ts.createPropertyAccess(result, "value"); + var callReturn = ts.createFunctionCall(returnMethod, iterator, []); + hoistVariableDeclaration(errorRecord); + hoistVariableDeclaration(returnMethod); + var forStatement = ts.setEmitFlags(ts.setTextRange(ts.createFor( + /*initializer*/ ts.setEmitFlags(ts.setTextRange(ts.createVariableDeclarationList([ + ts.setTextRange(ts.createVariableDeclaration(iterator, /*type*/ undefined, callValues), node.expression), + ts.createVariableDeclaration(result) + ]), node.expression), 2097152 /* NoHoisting */), + /*condition*/ ts.createComma(ts.createAssignment(result, createDownlevelAwait(callNext)), ts.createLogicalNot(getDone)), + /*incrementor*/ undefined, + /*statement*/ convertForOfStatementHead(node, getValue)), + /*location*/ node), 256 /* NoTokenTrailingSourceMaps */); + return ts.createTry(ts.createBlock([ + ts.restoreEnclosingLabel(forStatement, outermostLabeledStatement) + ]), ts.createCatchClause(ts.createVariableDeclaration(catchVariable), ts.setEmitFlags(ts.createBlock([ + ts.createExpressionStatement(ts.createAssignment(errorRecord, ts.createObjectLiteral([ + ts.createPropertyAssignment("error", catchVariable) + ]))) + ]), 1 /* SingleLine */)), ts.createBlock([ + ts.createTry( + /*tryBlock*/ ts.createBlock([ + ts.setEmitFlags(ts.createIf(ts.createLogicalAnd(ts.createLogicalAnd(result, ts.createLogicalNot(getDone)), ts.createAssignment(returnMethod, ts.createPropertyAccess(iterator, "return"))), ts.createExpressionStatement(createDownlevelAwait(callReturn))), 1 /* SingleLine */) + ]), + /*catchClause*/ undefined, + /*finallyBlock*/ ts.setEmitFlags(ts.createBlock([ + ts.setEmitFlags(ts.createIf(errorRecord, ts.createThrow(ts.createPropertyAccess(errorRecord, "error"))), 1 /* SingleLine */) + ]), 1 /* SingleLine */)) + ])); + } + function visitParameter(node) { + if (node.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { + // Binding patterns are converted into a generated name and are + // evaluated inside the function body. + return ts.updateParameter(node, + /*decorators*/ undefined, + /*modifiers*/ undefined, node.dotDotDotToken, ts.getGeneratedNameForNode(node), + /*questionToken*/ undefined, + /*type*/ undefined, ts.visitNode(node.initializer, visitor, ts.isExpression)); + } + return ts.visitEachChild(node, visitor, context); + } + function visitConstructorDeclaration(node) { + var savedEnclosingFunctionFlags = enclosingFunctionFlags; + enclosingFunctionFlags = 0 /* Normal */; + var updated = ts.updateConstructor(node, + /*decorators*/ undefined, node.modifiers, ts.visitParameterList(node.parameters, visitor, context), transformFunctionBody(node)); + enclosingFunctionFlags = savedEnclosingFunctionFlags; + return updated; + } + function visitGetAccessorDeclaration(node) { + var savedEnclosingFunctionFlags = enclosingFunctionFlags; + enclosingFunctionFlags = 0 /* Normal */; + var updated = ts.updateGetAccessor(node, + /*decorators*/ undefined, node.modifiers, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, transformFunctionBody(node)); + enclosingFunctionFlags = savedEnclosingFunctionFlags; + return updated; + } + function visitSetAccessorDeclaration(node) { + var savedEnclosingFunctionFlags = enclosingFunctionFlags; + enclosingFunctionFlags = 0 /* Normal */; + var updated = ts.updateSetAccessor(node, + /*decorators*/ undefined, node.modifiers, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitParameterList(node.parameters, visitor, context), transformFunctionBody(node)); + enclosingFunctionFlags = savedEnclosingFunctionFlags; + return updated; + } + function visitMethodDeclaration(node) { + var savedEnclosingFunctionFlags = enclosingFunctionFlags; + enclosingFunctionFlags = ts.getFunctionFlags(node); + var updated = ts.updateMethod(node, + /*decorators*/ undefined, enclosingFunctionFlags & 1 /* Generator */ + ? ts.visitNodes(node.modifiers, visitorNoAsyncModifier, ts.isModifier) + : node.modifiers, enclosingFunctionFlags & 2 /* Async */ + ? undefined + : node.asteriskToken, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitNode(/*questionToken*/ undefined, visitor, ts.isToken), + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */ + ? transformAsyncGeneratorFunctionBody(node) + : transformFunctionBody(node)); + enclosingFunctionFlags = savedEnclosingFunctionFlags; + return updated; + } + function visitFunctionDeclaration(node) { + var savedEnclosingFunctionFlags = enclosingFunctionFlags; + enclosingFunctionFlags = ts.getFunctionFlags(node); + var updated = ts.updateFunctionDeclaration(node, + /*decorators*/ undefined, enclosingFunctionFlags & 1 /* Generator */ + ? ts.visitNodes(node.modifiers, visitorNoAsyncModifier, ts.isModifier) + : node.modifiers, enclosingFunctionFlags & 2 /* Async */ + ? undefined + : node.asteriskToken, node.name, + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */ + ? transformAsyncGeneratorFunctionBody(node) + : transformFunctionBody(node)); + enclosingFunctionFlags = savedEnclosingFunctionFlags; + return updated; + } + function visitArrowFunction(node) { + var savedEnclosingFunctionFlags = enclosingFunctionFlags; + enclosingFunctionFlags = ts.getFunctionFlags(node); + var updated = ts.updateArrowFunction(node, node.modifiers, + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, node.equalsGreaterThanToken, transformFunctionBody(node)); + enclosingFunctionFlags = savedEnclosingFunctionFlags; + return updated; + } + function visitFunctionExpression(node) { + var savedEnclosingFunctionFlags = enclosingFunctionFlags; + enclosingFunctionFlags = ts.getFunctionFlags(node); + var updated = ts.updateFunctionExpression(node, enclosingFunctionFlags & 1 /* Generator */ + ? ts.visitNodes(node.modifiers, visitorNoAsyncModifier, ts.isModifier) + : node.modifiers, enclosingFunctionFlags & 2 /* Async */ + ? undefined + : node.asteriskToken, node.name, + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */ + ? transformAsyncGeneratorFunctionBody(node) + : transformFunctionBody(node)); + enclosingFunctionFlags = savedEnclosingFunctionFlags; + return updated; + } + function transformAsyncGeneratorFunctionBody(node) { + resumeLexicalEnvironment(); + var statements = []; + var statementOffset = ts.addPrologue(statements, node.body.statements, /*ensureUseStrict*/ false, visitor); + appendObjectRestAssignmentsIfNeeded(statements, node); + var savedCapturedSuperProperties = capturedSuperProperties; + var savedHasSuperElementAccess = hasSuperElementAccess; + capturedSuperProperties = ts.createUnderscoreEscapedMap(); + hasSuperElementAccess = false; + var returnStatement = ts.createReturn(createAsyncGeneratorHelper(context, ts.createFunctionExpression( + /*modifiers*/ undefined, ts.createToken(40 /* AsteriskToken */), node.name && ts.getGeneratedNameForNode(node.name), + /*typeParameters*/ undefined, + /*parameters*/ [], + /*type*/ undefined, ts.updateBlock(node.body, ts.visitLexicalEnvironment(node.body.statements, visitor, context, statementOffset))))); + // Minor optimization, emit `_super` helper to capture `super` access in an arrow. + // This step isn't needed if we eventually transform this to ES5. + var emitSuperHelpers = languageVersion >= 2 /* ES2015 */ && resolver.getNodeCheckFlags(node) & (4096 /* AsyncMethodWithSuperBinding */ | 2048 /* AsyncMethodWithSuper */); + if (emitSuperHelpers) { + enableSubstitutionForAsyncMethodsWithSuper(); + var variableStatement = ts.createSuperAccessVariableStatement(resolver, node, capturedSuperProperties); + substitutedSuperAccessors[ts.getNodeId(variableStatement)] = true; + ts.addStatementsAfterPrologue(statements, [variableStatement]); + } + statements.push(returnStatement); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + var block = ts.updateBlock(node.body, statements); + if (emitSuperHelpers && hasSuperElementAccess) { + if (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) { + ts.addEmitHelper(block, ts.advancedAsyncSuperHelper); + } + else if (resolver.getNodeCheckFlags(node) & 2048 /* AsyncMethodWithSuper */) { + ts.addEmitHelper(block, ts.asyncSuperHelper); + } + } + capturedSuperProperties = savedCapturedSuperProperties; + hasSuperElementAccess = savedHasSuperElementAccess; + return block; + } + function transformFunctionBody(node) { + resumeLexicalEnvironment(); + var statementOffset = 0; + var statements = []; + var body = ts.visitNode(node.body, visitor, ts.isConciseBody); + if (ts.isBlock(body)) { + statementOffset = ts.addPrologue(statements, body.statements, /*ensureUseStrict*/ false, visitor); + } + ts.addRange(statements, appendObjectRestAssignmentsIfNeeded(/*statements*/ undefined, node)); + var leadingStatements = endLexicalEnvironment(); + if (statementOffset > 0 || ts.some(statements) || ts.some(leadingStatements)) { + var block = ts.convertToFunctionBody(body, /*multiLine*/ true); + ts.addStatementsAfterPrologue(statements, leadingStatements); + ts.addRange(statements, block.statements.slice(statementOffset)); + return ts.updateBlock(block, ts.setTextRange(ts.createNodeArray(statements), block.statements)); + } + return body; + } + function appendObjectRestAssignmentsIfNeeded(statements, node) { + for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { + var parameter = _a[_i]; + if (parameter.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { + var temp = ts.getGeneratedNameForNode(parameter); + var declarations = ts.flattenDestructuringBinding(parameter, visitor, context, 1 /* ObjectRest */, temp, + /*doNotRecordTempVariablesInLine*/ false, + /*skipInitializer*/ true); + if (ts.some(declarations)) { + var statement = ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList(declarations)); + ts.setEmitFlags(statement, 1048576 /* CustomPrologue */); + statements = ts.append(statements, statement); + } + } + } + return statements; + } + function enableSubstitutionForAsyncMethodsWithSuper() { + if ((enabledSubstitutions & 1 /* AsyncMethodsWithSuper */) === 0) { + enabledSubstitutions |= 1 /* AsyncMethodsWithSuper */; + // We need to enable substitutions for call, property access, and element access + // if we need to rewrite super calls. + context.enableSubstitution(191 /* CallExpression */); + context.enableSubstitution(189 /* PropertyAccessExpression */); + context.enableSubstitution(190 /* ElementAccessExpression */); + // We need to be notified when entering and exiting declarations that bind super. + context.enableEmitNotification(240 /* ClassDeclaration */); + context.enableEmitNotification(156 /* MethodDeclaration */); + context.enableEmitNotification(158 /* GetAccessor */); + context.enableEmitNotification(159 /* SetAccessor */); + context.enableEmitNotification(157 /* Constructor */); + // We need to be notified when entering the generated accessor arrow functions. + context.enableEmitNotification(219 /* VariableStatement */); + } + } + /** + * Called by the printer just before a node is printed. + * + * @param hint A hint as to the intended usage of the node. + * @param node The node to be printed. + * @param emitCallback The callback used to emit the node. + */ + function onEmitNode(hint, node, emitCallback) { + // If we need to support substitutions for `super` in an async method, + // we should track it here. + if (enabledSubstitutions & 1 /* AsyncMethodsWithSuper */ && isSuperContainer(node)) { + var superContainerFlags = resolver.getNodeCheckFlags(node) & (2048 /* AsyncMethodWithSuper */ | 4096 /* AsyncMethodWithSuperBinding */); + if (superContainerFlags !== enclosingSuperContainerFlags) { + var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags; + enclosingSuperContainerFlags = superContainerFlags; + previousOnEmitNode(hint, node, emitCallback); + enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags; + return; + } + } + // Disable substitution in the generated super accessor itself. + else if (enabledSubstitutions && substitutedSuperAccessors[ts.getNodeId(node)]) { + var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags; + enclosingSuperContainerFlags = 0; + previousOnEmitNode(hint, node, emitCallback); + enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags; + return; + } + previousOnEmitNode(hint, node, emitCallback); + } + /** + * Hooks node substitutions. + * + * @param hint The context for the emitter. + * @param node The node to substitute. + */ + function onSubstituteNode(hint, node) { + node = previousOnSubstituteNode(hint, node); + if (hint === 1 /* Expression */ && enclosingSuperContainerFlags) { + return substituteExpression(node); + } + return node; + } + function substituteExpression(node) { + switch (node.kind) { + case 189 /* PropertyAccessExpression */: + return substitutePropertyAccessExpression(node); + case 190 /* ElementAccessExpression */: + return substituteElementAccessExpression(node); + case 191 /* CallExpression */: + return substituteCallExpression(node); + } + return node; + } + function substitutePropertyAccessExpression(node) { + if (node.expression.kind === 98 /* SuperKeyword */) { + return ts.setTextRange(ts.createPropertyAccess(ts.createFileLevelUniqueName("_super"), node.name), node); + } + return node; + } + function substituteElementAccessExpression(node) { + if (node.expression.kind === 98 /* SuperKeyword */) { + return createSuperElementAccessInAsyncMethod(node.argumentExpression, node); + } + return node; + } + function substituteCallExpression(node) { + var expression = node.expression; + if (ts.isSuperProperty(expression)) { + var argumentExpression = ts.isPropertyAccessExpression(expression) + ? substitutePropertyAccessExpression(expression) + : substituteElementAccessExpression(expression); + return ts.createCall(ts.createPropertyAccess(argumentExpression, "call"), + /*typeArguments*/ undefined, [ + ts.createThis() + ].concat(node.arguments)); + } + return node; + } + function isSuperContainer(node) { + var kind = node.kind; + return kind === 240 /* ClassDeclaration */ + || kind === 157 /* Constructor */ + || kind === 156 /* MethodDeclaration */ + || kind === 158 /* GetAccessor */ + || kind === 159 /* SetAccessor */; + } + function createSuperElementAccessInAsyncMethod(argumentExpression, location) { + if (enclosingSuperContainerFlags & 4096 /* AsyncMethodWithSuperBinding */) { + return ts.setTextRange(ts.createPropertyAccess(ts.createCall(ts.createIdentifier("_superIndex"), + /*typeArguments*/ undefined, [argumentExpression]), "value"), location); + } + else { + return ts.setTextRange(ts.createCall(ts.createIdentifier("_superIndex"), + /*typeArguments*/ undefined, [argumentExpression]), location); + } + } + } + ts.transformESNext = transformESNext; + var assignHelper = { + name: "typescript:assign", + scoped: false, + priority: 1, + text: "\n var __assign = (this && this.__assign) || function () {\n __assign = Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n };\n return __assign.apply(this, arguments);\n };" + }; + function createAssignHelper(context, attributesSegments) { + if (context.getCompilerOptions().target >= 2 /* ES2015 */) { + return ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "assign"), + /*typeArguments*/ undefined, attributesSegments); + } + context.requestEmitHelper(assignHelper); + return ts.createCall(ts.getHelperName("__assign"), + /*typeArguments*/ undefined, attributesSegments); + } + ts.createAssignHelper = createAssignHelper; + var awaitHelper = { + name: "typescript:await", + scoped: false, + text: "\n var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }" + }; + function createAwaitHelper(context, expression) { + context.requestEmitHelper(awaitHelper); + return ts.createCall(ts.getHelperName("__await"), /*typeArguments*/ undefined, [expression]); + } + var asyncGeneratorHelper = { + name: "typescript:asyncGenerator", + scoped: false, + text: "\n var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\n function fulfill(value) { resume(\"next\", value); }\n function reject(value) { resume(\"throw\", value); }\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\n };" + }; + function createAsyncGeneratorHelper(context, generatorFunc) { + context.requestEmitHelper(awaitHelper); + context.requestEmitHelper(asyncGeneratorHelper); + // Mark this node as originally an async function + (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 262144 /* AsyncFunctionBody */; + return ts.createCall(ts.getHelperName("__asyncGenerator"), + /*typeArguments*/ undefined, [ + ts.createThis(), + ts.createIdentifier("arguments"), + generatorFunc + ]); + } + var asyncDelegator = { + name: "typescript:asyncDelegator", + scoped: false, + text: "\n var __asyncDelegator = (this && this.__asyncDelegator) || function (o) {\n var i, p;\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; } : f; }\n };" + }; + function createAsyncDelegatorHelper(context, expression, location) { + context.requestEmitHelper(awaitHelper); + context.requestEmitHelper(asyncDelegator); + return ts.setTextRange(ts.createCall(ts.getHelperName("__asyncDelegator"), + /*typeArguments*/ undefined, [expression]), location); + } + var asyncValues = { + name: "typescript:asyncValues", + scoped: false, + text: "\n var __asyncValues = (this && this.__asyncValues) || function (o) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var m = o[Symbol.asyncIterator], i;\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\n };" + }; + function createAsyncValuesHelper(context, expression, location) { + context.requestEmitHelper(asyncValues); + return ts.setTextRange(ts.createCall(ts.getHelperName("__asyncValues"), + /*typeArguments*/ undefined, [expression]), location); + } +})(ts || (ts = {})); +/*@internal*/ +var ts; +(function (ts) { + function transformJsx(context) { + var compilerOptions = context.getCompilerOptions(); + var currentSourceFile; + return ts.chainBundle(transformSourceFile); + /** + * Transform JSX-specific syntax in a SourceFile. + * + * @param node A SourceFile node. + */ + function transformSourceFile(node) { + if (node.isDeclarationFile) { + return node; + } + currentSourceFile = node; + var visited = ts.visitEachChild(node, visitor, context); + ts.addEmitHelpers(visited, context.readEmitHelpers()); + return visited; + } + function visitor(node) { + if (node.transformFlags & 4 /* ContainsJsx */) { + return visitorWorker(node); + } + else { + return node; + } + } + function visitorWorker(node) { + switch (node.kind) { + case 260 /* JsxElement */: + return visitJsxElement(node, /*isChild*/ false); + case 261 /* JsxSelfClosingElement */: + return visitJsxSelfClosingElement(node, /*isChild*/ false); + case 264 /* JsxFragment */: + return visitJsxFragment(node, /*isChild*/ false); + case 270 /* JsxExpression */: + return visitJsxExpression(node); + default: + return ts.visitEachChild(node, visitor, context); + } + } + function transformJsxChildToExpression(node) { + switch (node.kind) { + case 11 /* JsxText */: + return visitJsxText(node); + case 270 /* JsxExpression */: + return visitJsxExpression(node); + case 260 /* JsxElement */: + return visitJsxElement(node, /*isChild*/ true); + case 261 /* JsxSelfClosingElement */: + return visitJsxSelfClosingElement(node, /*isChild*/ true); + case 264 /* JsxFragment */: + return visitJsxFragment(node, /*isChild*/ true); + default: + return ts.Debug.failBadSyntaxKind(node); + } + } + function visitJsxElement(node, isChild) { + return visitJsxOpeningLikeElement(node.openingElement, node.children, isChild, /*location*/ node); + } + function visitJsxSelfClosingElement(node, isChild) { + return visitJsxOpeningLikeElement(node, /*children*/ undefined, isChild, /*location*/ node); + } + function visitJsxFragment(node, isChild) { + return visitJsxOpeningFragment(node.openingFragment, node.children, isChild, /*location*/ node); + } + function visitJsxOpeningLikeElement(node, children, isChild, location) { + var tagName = getTagName(node); + var objectProperties; + var attrs = node.attributes.properties; + if (attrs.length === 0) { + // When there are no attributes, React wants "null" + objectProperties = ts.createNull(); + } + else { + // Map spans of JsxAttribute nodes into object literals and spans + // of JsxSpreadAttribute nodes into expressions. + var segments = ts.flatten(ts.spanMap(attrs, ts.isJsxSpreadAttribute, function (attrs, isSpread) { return isSpread + ? ts.map(attrs, transformJsxSpreadAttributeToExpression) + : ts.createObjectLiteral(ts.map(attrs, transformJsxAttributeToObjectLiteralElement)); })); + if (ts.isJsxSpreadAttribute(attrs[0])) { + // We must always emit at least one object literal before a spread + // argument. + segments.unshift(ts.createObjectLiteral()); + } + // Either emit one big object literal (no spread attribs), or + // a call to the __assign helper. + objectProperties = ts.singleOrUndefined(segments); + if (!objectProperties) { + objectProperties = ts.createAssignHelper(context, segments); + } + } + var element = ts.createExpressionForJsxElement(context.getEmitResolver().getJsxFactoryEntity(currentSourceFile), compilerOptions.reactNamespace, // TODO: GH#18217 + tagName, objectProperties, ts.mapDefined(children, transformJsxChildToExpression), node, location); + if (isChild) { + ts.startOnNewLine(element); + } + return element; + } + function visitJsxOpeningFragment(node, children, isChild, location) { + var element = ts.createExpressionForJsxFragment(context.getEmitResolver().getJsxFactoryEntity(currentSourceFile), compilerOptions.reactNamespace, // TODO: GH#18217 + ts.mapDefined(children, transformJsxChildToExpression), node, location); + if (isChild) { + ts.startOnNewLine(element); + } + return element; + } + function transformJsxSpreadAttributeToExpression(node) { + return ts.visitNode(node.expression, visitor, ts.isExpression); + } + function transformJsxAttributeToObjectLiteralElement(node) { + var name = getAttributeName(node); + var expression = transformJsxAttributeInitializer(node.initializer); + return ts.createPropertyAssignment(name, expression); + } + function transformJsxAttributeInitializer(node) { + if (node === undefined) { + return ts.createTrue(); + } + else if (node.kind === 10 /* StringLiteral */) { + // Always recreate the literal to escape any escape sequences or newlines which may be in the original jsx string and which + // Need to be escaped to be handled correctly in a normal string + var literal = ts.createLiteral(tryDecodeEntities(node.text) || node.text); + literal.singleQuote = node.singleQuote !== undefined ? node.singleQuote : !ts.isStringDoubleQuoted(node, currentSourceFile); + return ts.setTextRange(literal, node); + } + else if (node.kind === 270 /* JsxExpression */) { + if (node.expression === undefined) { + return ts.createTrue(); + } + return visitJsxExpression(node); + } + else { + return ts.Debug.failBadSyntaxKind(node); + } + } + function visitJsxText(node) { + var fixed = fixupWhitespaceAndDecodeEntities(ts.getTextOfNode(node, /*includeTrivia*/ true)); + return fixed === undefined ? undefined : ts.createLiteral(fixed); + } + /** + * JSX trims whitespace at the end and beginning of lines, except that the + * start/end of a tag is considered a start/end of a line only if that line is + * on the same line as the closing tag. See examples in + * tests/cases/conformance/jsx/tsxReactEmitWhitespace.tsx + * See also https://www.w3.org/TR/html4/struct/text.html#h-9.1 and https://www.w3.org/TR/CSS2/text.html#white-space-model + * + * An equivalent algorithm would be: + * - If there is only one line, return it. + * - If there is only whitespace (but multiple lines), return `undefined`. + * - Split the text into lines. + * - 'trimRight' the first line, 'trimLeft' the last line, 'trim' middle lines. + * - Decode entities on each line (individually). + * - Remove empty lines and join the rest with " ". + */ + function fixupWhitespaceAndDecodeEntities(text) { + var acc; + // First non-whitespace character on this line. + var firstNonWhitespace = 0; + // Last non-whitespace character on this line. + var lastNonWhitespace = -1; + // These initial values are special because the first line is: + // firstNonWhitespace = 0 to indicate that we want leading whitsepace, + // but lastNonWhitespace = -1 as a special flag to indicate that we *don't* include the line if it's all whitespace. + for (var i = 0; i < text.length; i++) { + var c = text.charCodeAt(i); + if (ts.isLineBreak(c)) { + // If we've seen any non-whitespace characters on this line, add the 'trim' of the line. + // (lastNonWhitespace === -1 is a special flag to detect whether the first line is all whitespace.) + if (firstNonWhitespace !== -1 && lastNonWhitespace !== -1) { + acc = addLineOfJsxText(acc, text.substr(firstNonWhitespace, lastNonWhitespace - firstNonWhitespace + 1)); + } + // Reset firstNonWhitespace for the next line. + // Don't bother to reset lastNonWhitespace because we ignore it if firstNonWhitespace = -1. + firstNonWhitespace = -1; + } + else if (!ts.isWhiteSpaceSingleLine(c)) { + lastNonWhitespace = i; + if (firstNonWhitespace === -1) { + firstNonWhitespace = i; + } + } + } + return firstNonWhitespace !== -1 + // Last line had a non-whitespace character. Emit the 'trimLeft', meaning keep trailing whitespace. + ? addLineOfJsxText(acc, text.substr(firstNonWhitespace)) + // Last line was all whitespace, so ignore it + : acc; + } + function addLineOfJsxText(acc, trimmedLine) { + // We do not escape the string here as that is handled by the printer + // when it emits the literal. We do, however, need to decode JSX entities. + var decoded = decodeEntities(trimmedLine); + return acc === undefined ? decoded : acc + " " + decoded; + } + /** + * Replace entities like " ", "{", and "�" with the characters they encode. + * See https://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references + */ + function decodeEntities(text) { + return text.replace(/&((#((\d+)|x([\da-fA-F]+)))|(\w+));/g, function (match, _all, _number, _digits, decimal, hex, word) { + if (decimal) { + return String.fromCharCode(parseInt(decimal, 10)); + } + else if (hex) { + return String.fromCharCode(parseInt(hex, 16)); + } + else { + var ch = entities.get(word); + // If this is not a valid entity, then just use `match` (replace it with itself, i.e. don't replace) + return ch ? String.fromCharCode(ch) : match; + } + }); + } + /** Like `decodeEntities` but returns `undefined` if there were no entities to decode. */ + function tryDecodeEntities(text) { + var decoded = decodeEntities(text); + return decoded === text ? undefined : decoded; + } + function getTagName(node) { + if (node.kind === 260 /* JsxElement */) { + return getTagName(node.openingElement); + } + else { + var name = node.tagName; + if (ts.isIdentifier(name) && ts.isIntrinsicJsxName(name.escapedText)) { + return ts.createLiteral(ts.idText(name)); + } + else { + return ts.createExpressionFromEntityName(name); + } + } + } + /** + * Emit an attribute name, which is quoted if it needs to be quoted. Because + * these emit into an object literal property name, we don't need to be worried + * about keywords, just non-identifier characters + */ + function getAttributeName(node) { + var name = node.name; + var text = ts.idText(name); + if (/^[A-Za-z_]\w*$/.test(text)) { + return name; + } + else { + return ts.createLiteral(text); + } + } + function visitJsxExpression(node) { + return ts.visitNode(node.expression, visitor, ts.isExpression); + } + } + ts.transformJsx = transformJsx; + var entities = ts.createMapFromTemplate({ + quot: 0x0022, + amp: 0x0026, + apos: 0x0027, + lt: 0x003C, + gt: 0x003E, + nbsp: 0x00A0, + iexcl: 0x00A1, + cent: 0x00A2, + pound: 0x00A3, + curren: 0x00A4, + yen: 0x00A5, + brvbar: 0x00A6, + sect: 0x00A7, + uml: 0x00A8, + copy: 0x00A9, + ordf: 0x00AA, + laquo: 0x00AB, + not: 0x00AC, + shy: 0x00AD, + reg: 0x00AE, + macr: 0x00AF, + deg: 0x00B0, + plusmn: 0x00B1, + sup2: 0x00B2, + sup3: 0x00B3, + acute: 0x00B4, + micro: 0x00B5, + para: 0x00B6, + middot: 0x00B7, + cedil: 0x00B8, + sup1: 0x00B9, + ordm: 0x00BA, + raquo: 0x00BB, + frac14: 0x00BC, + frac12: 0x00BD, + frac34: 0x00BE, + iquest: 0x00BF, + Agrave: 0x00C0, + Aacute: 0x00C1, + Acirc: 0x00C2, + Atilde: 0x00C3, + Auml: 0x00C4, + Aring: 0x00C5, + AElig: 0x00C6, + Ccedil: 0x00C7, + Egrave: 0x00C8, + Eacute: 0x00C9, + Ecirc: 0x00CA, + Euml: 0x00CB, + Igrave: 0x00CC, + Iacute: 0x00CD, + Icirc: 0x00CE, + Iuml: 0x00CF, + ETH: 0x00D0, + Ntilde: 0x00D1, + Ograve: 0x00D2, + Oacute: 0x00D3, + Ocirc: 0x00D4, + Otilde: 0x00D5, + Ouml: 0x00D6, + times: 0x00D7, + Oslash: 0x00D8, + Ugrave: 0x00D9, + Uacute: 0x00DA, + Ucirc: 0x00DB, + Uuml: 0x00DC, + Yacute: 0x00DD, + THORN: 0x00DE, + szlig: 0x00DF, + agrave: 0x00E0, + aacute: 0x00E1, + acirc: 0x00E2, + atilde: 0x00E3, + auml: 0x00E4, + aring: 0x00E5, + aelig: 0x00E6, + ccedil: 0x00E7, + egrave: 0x00E8, + eacute: 0x00E9, + ecirc: 0x00EA, + euml: 0x00EB, + igrave: 0x00EC, + iacute: 0x00ED, + icirc: 0x00EE, + iuml: 0x00EF, + eth: 0x00F0, + ntilde: 0x00F1, + ograve: 0x00F2, + oacute: 0x00F3, + ocirc: 0x00F4, + otilde: 0x00F5, + ouml: 0x00F6, + divide: 0x00F7, + oslash: 0x00F8, + ugrave: 0x00F9, + uacute: 0x00FA, + ucirc: 0x00FB, + uuml: 0x00FC, + yacute: 0x00FD, + thorn: 0x00FE, + yuml: 0x00FF, + OElig: 0x0152, + oelig: 0x0153, + Scaron: 0x0160, + scaron: 0x0161, + Yuml: 0x0178, + fnof: 0x0192, + circ: 0x02C6, + tilde: 0x02DC, + Alpha: 0x0391, + Beta: 0x0392, + Gamma: 0x0393, + Delta: 0x0394, + Epsilon: 0x0395, + Zeta: 0x0396, + Eta: 0x0397, + Theta: 0x0398, + Iota: 0x0399, + Kappa: 0x039A, + Lambda: 0x039B, + Mu: 0x039C, + Nu: 0x039D, + Xi: 0x039E, + Omicron: 0x039F, + Pi: 0x03A0, + Rho: 0x03A1, + Sigma: 0x03A3, + Tau: 0x03A4, + Upsilon: 0x03A5, + Phi: 0x03A6, + Chi: 0x03A7, + Psi: 0x03A8, + Omega: 0x03A9, + alpha: 0x03B1, + beta: 0x03B2, + gamma: 0x03B3, + delta: 0x03B4, + epsilon: 0x03B5, + zeta: 0x03B6, + eta: 0x03B7, + theta: 0x03B8, + iota: 0x03B9, + kappa: 0x03BA, + lambda: 0x03BB, + mu: 0x03BC, + nu: 0x03BD, + xi: 0x03BE, + omicron: 0x03BF, + pi: 0x03C0, + rho: 0x03C1, + sigmaf: 0x03C2, + sigma: 0x03C3, + tau: 0x03C4, + upsilon: 0x03C5, + phi: 0x03C6, + chi: 0x03C7, + psi: 0x03C8, + omega: 0x03C9, + thetasym: 0x03D1, + upsih: 0x03D2, + piv: 0x03D6, + ensp: 0x2002, + emsp: 0x2003, + thinsp: 0x2009, + zwnj: 0x200C, + zwj: 0x200D, + lrm: 0x200E, + rlm: 0x200F, + ndash: 0x2013, + mdash: 0x2014, + lsquo: 0x2018, + rsquo: 0x2019, + sbquo: 0x201A, + ldquo: 0x201C, + rdquo: 0x201D, + bdquo: 0x201E, + dagger: 0x2020, + Dagger: 0x2021, + bull: 0x2022, + hellip: 0x2026, + permil: 0x2030, + prime: 0x2032, + Prime: 0x2033, + lsaquo: 0x2039, + rsaquo: 0x203A, + oline: 0x203E, + frasl: 0x2044, + euro: 0x20AC, + image: 0x2111, + weierp: 0x2118, + real: 0x211C, + trade: 0x2122, + alefsym: 0x2135, + larr: 0x2190, + uarr: 0x2191, + rarr: 0x2192, + darr: 0x2193, + harr: 0x2194, + crarr: 0x21B5, + lArr: 0x21D0, + uArr: 0x21D1, + rArr: 0x21D2, + dArr: 0x21D3, + hArr: 0x21D4, + forall: 0x2200, + part: 0x2202, + exist: 0x2203, + empty: 0x2205, + nabla: 0x2207, + isin: 0x2208, + notin: 0x2209, + ni: 0x220B, + prod: 0x220F, + sum: 0x2211, + minus: 0x2212, + lowast: 0x2217, + radic: 0x221A, + prop: 0x221D, + infin: 0x221E, + ang: 0x2220, + and: 0x2227, + or: 0x2228, + cap: 0x2229, + cup: 0x222A, + int: 0x222B, + there4: 0x2234, + sim: 0x223C, + cong: 0x2245, + asymp: 0x2248, + ne: 0x2260, + equiv: 0x2261, + le: 0x2264, + ge: 0x2265, + sub: 0x2282, + sup: 0x2283, + nsub: 0x2284, + sube: 0x2286, + supe: 0x2287, + oplus: 0x2295, + otimes: 0x2297, + perp: 0x22A5, + sdot: 0x22C5, + lceil: 0x2308, + rceil: 0x2309, + lfloor: 0x230A, + rfloor: 0x230B, + lang: 0x2329, + rang: 0x232A, + loz: 0x25CA, + spades: 0x2660, + clubs: 0x2663, + hearts: 0x2665, + diams: 0x2666 + }); +})(ts || (ts = {})); +/*@internal*/ +var ts; +(function (ts) { + function transformES2016(context) { + var hoistVariableDeclaration = context.hoistVariableDeclaration; + return ts.chainBundle(transformSourceFile); + function transformSourceFile(node) { + if (node.isDeclarationFile) { + return node; + } + return ts.visitEachChild(node, visitor, context); + } + function visitor(node) { + if ((node.transformFlags & 32 /* ContainsES2016 */) === 0) { + return node; + } + switch (node.kind) { + case 204 /* BinaryExpression */: + return visitBinaryExpression(node); + default: + return ts.visitEachChild(node, visitor, context); + } + } + function visitBinaryExpression(node) { + switch (node.operatorToken.kind) { + case 63 /* AsteriskAsteriskEqualsToken */: + return visitExponentiationAssignmentExpression(node); + case 41 /* AsteriskAsteriskToken */: + return visitExponentiationExpression(node); + default: + return ts.visitEachChild(node, visitor, context); + } + } + function visitExponentiationAssignmentExpression(node) { + var target; + var value; + var left = ts.visitNode(node.left, visitor, ts.isExpression); + var right = ts.visitNode(node.right, visitor, ts.isExpression); + if (ts.isElementAccessExpression(left)) { + // Transforms `a[x] **= b` into `(_a = a)[_x = x] = Math.pow(_a[_x], b)` + var expressionTemp = ts.createTempVariable(hoistVariableDeclaration); + var argumentExpressionTemp = ts.createTempVariable(hoistVariableDeclaration); + target = ts.setTextRange(ts.createElementAccess(ts.setTextRange(ts.createAssignment(expressionTemp, left.expression), left.expression), ts.setTextRange(ts.createAssignment(argumentExpressionTemp, left.argumentExpression), left.argumentExpression)), left); + value = ts.setTextRange(ts.createElementAccess(expressionTemp, argumentExpressionTemp), left); + } + else if (ts.isPropertyAccessExpression(left)) { + // Transforms `a.x **= b` into `(_a = a).x = Math.pow(_a.x, b)` + var expressionTemp = ts.createTempVariable(hoistVariableDeclaration); + target = ts.setTextRange(ts.createPropertyAccess(ts.setTextRange(ts.createAssignment(expressionTemp, left.expression), left.expression), left.name), left); + value = ts.setTextRange(ts.createPropertyAccess(expressionTemp, left.name), left); + } + else { + // Transforms `a **= b` into `a = Math.pow(a, b)` + target = left; + value = left; + } + return ts.setTextRange(ts.createAssignment(target, ts.createMathPow(value, right, /*location*/ node)), node); + } + function visitExponentiationExpression(node) { + // Transforms `a ** b` into `Math.pow(a, b)` + var left = ts.visitNode(node.left, visitor, ts.isExpression); + var right = ts.visitNode(node.right, visitor, ts.isExpression); + return ts.createMathPow(left, right, /*location*/ node); + } + } + ts.transformES2016 = transformES2016; +})(ts || (ts = {})); +/*@internal*/ +var ts; +(function (ts) { + var ES2015SubstitutionFlags; + (function (ES2015SubstitutionFlags) { + /** Enables substitutions for captured `this` */ + ES2015SubstitutionFlags[ES2015SubstitutionFlags["CapturedThis"] = 1] = "CapturedThis"; + /** Enables substitutions for block-scoped bindings. */ + ES2015SubstitutionFlags[ES2015SubstitutionFlags["BlockScopedBindings"] = 2] = "BlockScopedBindings"; + })(ES2015SubstitutionFlags || (ES2015SubstitutionFlags = {})); + var LoopOutParameterFlags; + (function (LoopOutParameterFlags) { + LoopOutParameterFlags[LoopOutParameterFlags["Body"] = 1] = "Body"; + LoopOutParameterFlags[LoopOutParameterFlags["Initializer"] = 2] = "Initializer"; + })(LoopOutParameterFlags || (LoopOutParameterFlags = {})); + var CopyDirection; + (function (CopyDirection) { + CopyDirection[CopyDirection["ToOriginal"] = 0] = "ToOriginal"; + CopyDirection[CopyDirection["ToOutParameter"] = 1] = "ToOutParameter"; + })(CopyDirection || (CopyDirection = {})); + var Jump; + (function (Jump) { + Jump[Jump["Break"] = 2] = "Break"; + Jump[Jump["Continue"] = 4] = "Continue"; + Jump[Jump["Return"] = 8] = "Return"; + })(Jump || (Jump = {})); + var SuperCaptureResult; + (function (SuperCaptureResult) { + /** + * A capture may have been added for calls to 'super', but + * the caller should emit subsequent statements normally. + */ + SuperCaptureResult[SuperCaptureResult["NoReplacement"] = 0] = "NoReplacement"; + /** + * A call to 'super()' got replaced with a capturing statement like: + * + * var _this = _super.call(...) || this; + * + * Callers should skip the current statement. + */ + SuperCaptureResult[SuperCaptureResult["ReplaceSuperCapture"] = 1] = "ReplaceSuperCapture"; + /** + * A call to 'super()' got replaced with a capturing statement like: + * + * return _super.call(...) || this; + * + * Callers should skip the current statement and avoid any returns of '_this'. + */ + SuperCaptureResult[SuperCaptureResult["ReplaceWithReturn"] = 2] = "ReplaceWithReturn"; + })(SuperCaptureResult || (SuperCaptureResult = {})); + // Facts we track as we traverse the tree + var HierarchyFacts; + (function (HierarchyFacts) { + HierarchyFacts[HierarchyFacts["None"] = 0] = "None"; + // + // Ancestor facts + // + HierarchyFacts[HierarchyFacts["Function"] = 1] = "Function"; + HierarchyFacts[HierarchyFacts["ArrowFunction"] = 2] = "ArrowFunction"; + HierarchyFacts[HierarchyFacts["AsyncFunctionBody"] = 4] = "AsyncFunctionBody"; + HierarchyFacts[HierarchyFacts["NonStaticClassElement"] = 8] = "NonStaticClassElement"; + HierarchyFacts[HierarchyFacts["CapturesThis"] = 16] = "CapturesThis"; + HierarchyFacts[HierarchyFacts["ExportedVariableStatement"] = 32] = "ExportedVariableStatement"; + HierarchyFacts[HierarchyFacts["TopLevel"] = 64] = "TopLevel"; + HierarchyFacts[HierarchyFacts["Block"] = 128] = "Block"; + HierarchyFacts[HierarchyFacts["IterationStatement"] = 256] = "IterationStatement"; + HierarchyFacts[HierarchyFacts["IterationStatementBlock"] = 512] = "IterationStatementBlock"; + HierarchyFacts[HierarchyFacts["ForStatement"] = 1024] = "ForStatement"; + HierarchyFacts[HierarchyFacts["ForInOrForOfStatement"] = 2048] = "ForInOrForOfStatement"; + HierarchyFacts[HierarchyFacts["ConstructorWithCapturedSuper"] = 4096] = "ConstructorWithCapturedSuper"; + HierarchyFacts[HierarchyFacts["ComputedPropertyName"] = 8192] = "ComputedPropertyName"; + // NOTE: do not add more ancestor flags without also updating AncestorFactsMask below. + // + // Ancestor masks + // + HierarchyFacts[HierarchyFacts["AncestorFactsMask"] = 16383] = "AncestorFactsMask"; + // We are always in *some* kind of block scope, but only specific block-scope containers are + // top-level or Blocks. + HierarchyFacts[HierarchyFacts["BlockScopeIncludes"] = 0] = "BlockScopeIncludes"; + HierarchyFacts[HierarchyFacts["BlockScopeExcludes"] = 4032] = "BlockScopeExcludes"; + // A source file is a top-level block scope. + HierarchyFacts[HierarchyFacts["SourceFileIncludes"] = 64] = "SourceFileIncludes"; + HierarchyFacts[HierarchyFacts["SourceFileExcludes"] = 3968] = "SourceFileExcludes"; + // Functions, methods, and accessors are both new lexical scopes and new block scopes. + HierarchyFacts[HierarchyFacts["FunctionIncludes"] = 65] = "FunctionIncludes"; + HierarchyFacts[HierarchyFacts["FunctionExcludes"] = 16286] = "FunctionExcludes"; + HierarchyFacts[HierarchyFacts["AsyncFunctionBodyIncludes"] = 69] = "AsyncFunctionBodyIncludes"; + HierarchyFacts[HierarchyFacts["AsyncFunctionBodyExcludes"] = 16278] = "AsyncFunctionBodyExcludes"; + // Arrow functions are lexically scoped to their container, but are new block scopes. + HierarchyFacts[HierarchyFacts["ArrowFunctionIncludes"] = 66] = "ArrowFunctionIncludes"; + HierarchyFacts[HierarchyFacts["ArrowFunctionExcludes"] = 16256] = "ArrowFunctionExcludes"; + // Constructors are both new lexical scopes and new block scopes. Constructors are also + // always considered non-static members of a class. + HierarchyFacts[HierarchyFacts["ConstructorIncludes"] = 73] = "ConstructorIncludes"; + HierarchyFacts[HierarchyFacts["ConstructorExcludes"] = 16278] = "ConstructorExcludes"; + // 'do' and 'while' statements are not block scopes. We track that the subtree is contained + // within an IterationStatement to indicate whether the embedded statement is an + // IterationStatementBlock. + HierarchyFacts[HierarchyFacts["DoOrWhileStatementIncludes"] = 256] = "DoOrWhileStatementIncludes"; + HierarchyFacts[HierarchyFacts["DoOrWhileStatementExcludes"] = 0] = "DoOrWhileStatementExcludes"; + // 'for' statements are new block scopes and have special handling for 'let' declarations. + HierarchyFacts[HierarchyFacts["ForStatementIncludes"] = 1280] = "ForStatementIncludes"; + HierarchyFacts[HierarchyFacts["ForStatementExcludes"] = 3008] = "ForStatementExcludes"; + // 'for-in' and 'for-of' statements are new block scopes and have special handling for + // 'let' declarations. + HierarchyFacts[HierarchyFacts["ForInOrForOfStatementIncludes"] = 2304] = "ForInOrForOfStatementIncludes"; + HierarchyFacts[HierarchyFacts["ForInOrForOfStatementExcludes"] = 1984] = "ForInOrForOfStatementExcludes"; + // Blocks (other than function bodies) are new block scopes. + HierarchyFacts[HierarchyFacts["BlockIncludes"] = 128] = "BlockIncludes"; + HierarchyFacts[HierarchyFacts["BlockExcludes"] = 3904] = "BlockExcludes"; + HierarchyFacts[HierarchyFacts["IterationStatementBlockIncludes"] = 512] = "IterationStatementBlockIncludes"; + HierarchyFacts[HierarchyFacts["IterationStatementBlockExcludes"] = 4032] = "IterationStatementBlockExcludes"; + // Computed property names track subtree flags differently than their containing members. + HierarchyFacts[HierarchyFacts["ComputedPropertyNameIncludes"] = 8192] = "ComputedPropertyNameIncludes"; + HierarchyFacts[HierarchyFacts["ComputedPropertyNameExcludes"] = 0] = "ComputedPropertyNameExcludes"; + // + // Subtree facts + // + HierarchyFacts[HierarchyFacts["NewTarget"] = 16384] = "NewTarget"; + HierarchyFacts[HierarchyFacts["NewTargetInComputedPropertyName"] = 32768] = "NewTargetInComputedPropertyName"; + // + // Subtree masks + // + HierarchyFacts[HierarchyFacts["SubtreeFactsMask"] = -16384] = "SubtreeFactsMask"; + HierarchyFacts[HierarchyFacts["PropagateNewTargetMask"] = 49152] = "PropagateNewTargetMask"; + })(HierarchyFacts || (HierarchyFacts = {})); + function transformES2015(context) { + var startLexicalEnvironment = context.startLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; + var compilerOptions = context.getCompilerOptions(); + var resolver = context.getEmitResolver(); + var previousOnSubstituteNode = context.onSubstituteNode; + var previousOnEmitNode = context.onEmitNode; + context.onEmitNode = onEmitNode; + context.onSubstituteNode = onSubstituteNode; + var currentSourceFile; + var currentText; + var hierarchyFacts; + var taggedTemplateStringDeclarations; + function recordTaggedTemplateString(temp) { + taggedTemplateStringDeclarations = ts.append(taggedTemplateStringDeclarations, ts.createVariableDeclaration(temp)); + } + /** + * Used to track if we are emitting body of the converted loop + */ + var convertedLoopState; + /** + * Keeps track of whether substitutions have been enabled for specific cases. + * They are persisted between each SourceFile transformation and should not + * be reset. + */ + var enabledSubstitutions; + return ts.chainBundle(transformSourceFile); + function transformSourceFile(node) { + if (node.isDeclarationFile) { + return node; + } + currentSourceFile = node; + currentText = node.text; + var visited = visitSourceFile(node); + ts.addEmitHelpers(visited, context.readEmitHelpers()); + currentSourceFile = undefined; + currentText = undefined; + taggedTemplateStringDeclarations = undefined; + hierarchyFacts = 0 /* None */; + return visited; + } + /** + * Sets the `HierarchyFacts` for this node prior to visiting this node's subtree, returning the facts set prior to modification. + * @param excludeFacts The existing `HierarchyFacts` to reset before visiting the subtree. + * @param includeFacts The new `HierarchyFacts` to set before visiting the subtree. + */ + function enterSubtree(excludeFacts, includeFacts) { + var ancestorFacts = hierarchyFacts; + hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & 16383 /* AncestorFactsMask */; + return ancestorFacts; + } + /** + * Restores the `HierarchyFacts` for this node's ancestor after visiting this node's + * subtree, propagating specific facts from the subtree. + * @param ancestorFacts The `HierarchyFacts` of the ancestor to restore after visiting the subtree. + * @param excludeFacts The existing `HierarchyFacts` of the subtree that should not be propagated. + * @param includeFacts The new `HierarchyFacts` of the subtree that should be propagated. + */ + function exitSubtree(ancestorFacts, excludeFacts, includeFacts) { + hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & -16384 /* SubtreeFactsMask */ | ancestorFacts; + } + function isReturnVoidStatementInConstructorWithCapturedSuper(node) { + return (hierarchyFacts & 4096 /* ConstructorWithCapturedSuper */) !== 0 + && node.kind === 230 /* ReturnStatement */ + && !node.expression; + } + function shouldVisitNode(node) { + return (node.transformFlags & 128 /* ContainsES2015 */) !== 0 + || convertedLoopState !== undefined + || (hierarchyFacts & 4096 /* ConstructorWithCapturedSuper */ && (ts.isStatement(node) || (node.kind === 218 /* Block */))) + || (ts.isIterationStatement(node, /*lookInLabeledStatements*/ false) && shouldConvertIterationStatement(node)) + || (ts.getEmitFlags(node) & 33554432 /* TypeScriptClassWrapper */) !== 0; + } + function visitor(node) { + if (shouldVisitNode(node)) { + return visitJavaScript(node); + } + else { + return node; + } + } + function functionBodyVisitor(node) { + if (shouldVisitNode(node)) { + return visitBlock(node, /*isFunctionBody*/ true); + } + return node; + } + function callExpressionVisitor(node) { + if (node.kind === 98 /* SuperKeyword */) { + return visitSuperKeyword(/*isExpressionOfCall*/ true); + } + return visitor(node); + } + function visitJavaScript(node) { + switch (node.kind) { + case 116 /* StaticKeyword */: + return undefined; // elide static keyword + case 240 /* ClassDeclaration */: + return visitClassDeclaration(node); + case 209 /* ClassExpression */: + return visitClassExpression(node); + case 151 /* Parameter */: + return visitParameter(node); + case 239 /* FunctionDeclaration */: + return visitFunctionDeclaration(node); + case 197 /* ArrowFunction */: + return visitArrowFunction(node); + case 196 /* FunctionExpression */: + return visitFunctionExpression(node); + case 237 /* VariableDeclaration */: + return visitVariableDeclaration(node); + case 72 /* Identifier */: + return visitIdentifier(node); + case 238 /* VariableDeclarationList */: + return visitVariableDeclarationList(node); + case 232 /* SwitchStatement */: + return visitSwitchStatement(node); + case 246 /* CaseBlock */: + return visitCaseBlock(node); + case 218 /* Block */: + return visitBlock(node, /*isFunctionBody*/ false); + case 229 /* BreakStatement */: + case 228 /* ContinueStatement */: + return visitBreakOrContinueStatement(node); + case 233 /* LabeledStatement */: + return visitLabeledStatement(node); + case 223 /* DoStatement */: + case 224 /* WhileStatement */: + return visitDoOrWhileStatement(node, /*outermostLabeledStatement*/ undefined); + case 225 /* ForStatement */: + return visitForStatement(node, /*outermostLabeledStatement*/ undefined); + case 226 /* ForInStatement */: + return visitForInStatement(node, /*outermostLabeledStatement*/ undefined); + case 227 /* ForOfStatement */: + return visitForOfStatement(node, /*outermostLabeledStatement*/ undefined); + case 221 /* ExpressionStatement */: + return visitExpressionStatement(node); + case 188 /* ObjectLiteralExpression */: + return visitObjectLiteralExpression(node); + case 274 /* CatchClause */: + return visitCatchClause(node); + case 276 /* ShorthandPropertyAssignment */: + return visitShorthandPropertyAssignment(node); + case 149 /* ComputedPropertyName */: + return visitComputedPropertyName(node); + case 187 /* ArrayLiteralExpression */: + return visitArrayLiteralExpression(node); + case 191 /* CallExpression */: + return visitCallExpression(node); + case 192 /* NewExpression */: + return visitNewExpression(node); + case 195 /* ParenthesizedExpression */: + return visitParenthesizedExpression(node, /*needsDestructuringValue*/ true); + case 204 /* BinaryExpression */: + return visitBinaryExpression(node, /*needsDestructuringValue*/ true); + case 14 /* NoSubstitutionTemplateLiteral */: + case 15 /* TemplateHead */: + case 16 /* TemplateMiddle */: + case 17 /* TemplateTail */: + return visitTemplateLiteral(node); + case 10 /* StringLiteral */: + return visitStringLiteral(node); + case 8 /* NumericLiteral */: + return visitNumericLiteral(node); + case 193 /* TaggedTemplateExpression */: + return visitTaggedTemplateExpression(node); + case 206 /* TemplateExpression */: + return visitTemplateExpression(node); + case 207 /* YieldExpression */: + return visitYieldExpression(node); + case 208 /* SpreadElement */: + return visitSpreadElement(node); + case 98 /* SuperKeyword */: + return visitSuperKeyword(/*isExpressionOfCall*/ false); + case 100 /* ThisKeyword */: + return visitThisKeyword(node); + case 214 /* MetaProperty */: + return visitMetaProperty(node); + case 156 /* MethodDeclaration */: + return visitMethodDeclaration(node); + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + return visitAccessorDeclaration(node); + case 219 /* VariableStatement */: + return visitVariableStatement(node); + case 230 /* ReturnStatement */: + return visitReturnStatement(node); + default: + return ts.visitEachChild(node, visitor, context); + } + } + function visitSourceFile(node) { + var ancestorFacts = enterSubtree(3968 /* SourceFileExcludes */, 64 /* SourceFileIncludes */); + var statements = []; + startLexicalEnvironment(); + var statementOffset = ts.addStandardPrologue(statements, node.statements, /*ensureUseStrict*/ false); + addCaptureThisForNodeIfNeeded(statements, node); + statementOffset = ts.addCustomPrologue(statements, node.statements, statementOffset, visitor); + ts.addRange(statements, ts.visitNodes(node.statements, visitor, ts.isStatement, statementOffset)); + if (taggedTemplateStringDeclarations) { + statements.push(ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList(taggedTemplateStringDeclarations))); + } + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */); + return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements)); + } + function visitSwitchStatement(node) { + if (convertedLoopState !== undefined) { + var savedAllowedNonLabeledJumps = convertedLoopState.allowedNonLabeledJumps; + // for switch statement allow only non-labeled break + convertedLoopState.allowedNonLabeledJumps |= 2 /* Break */; + var result = ts.visitEachChild(node, visitor, context); + convertedLoopState.allowedNonLabeledJumps = savedAllowedNonLabeledJumps; + return result; + } + return ts.visitEachChild(node, visitor, context); + } + function visitCaseBlock(node) { + var ancestorFacts = enterSubtree(4032 /* BlockScopeExcludes */, 0 /* BlockScopeIncludes */); + var updated = ts.visitEachChild(node, visitor, context); + exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */); + return updated; + } + function returnCapturedThis(node) { + return ts.setOriginalNode(ts.createReturn(ts.createFileLevelUniqueName("_this")), node); + } + function visitReturnStatement(node) { + if (convertedLoopState) { + convertedLoopState.nonLocalJumps |= 8 /* Return */; + if (isReturnVoidStatementInConstructorWithCapturedSuper(node)) { + node = returnCapturedThis(node); + } + return ts.createReturn(ts.createObjectLiteral([ + ts.createPropertyAssignment(ts.createIdentifier("value"), node.expression + ? ts.visitNode(node.expression, visitor, ts.isExpression) + : ts.createVoidZero()) + ])); + } + else if (isReturnVoidStatementInConstructorWithCapturedSuper(node)) { + return returnCapturedThis(node); + } + return ts.visitEachChild(node, visitor, context); + } + function visitThisKeyword(node) { + if (convertedLoopState) { + if (hierarchyFacts & 2 /* ArrowFunction */) { + // if the enclosing function is an ArrowFunction then we use the captured 'this' keyword. + convertedLoopState.containsLexicalThis = true; + return node; + } + return convertedLoopState.thisName || (convertedLoopState.thisName = ts.createUniqueName("this")); + } + return node; + } + function visitIdentifier(node) { + if (!convertedLoopState) { + return node; + } + if (ts.isGeneratedIdentifier(node)) { + return node; + } + if (node.escapedText !== "arguments" || !resolver.isArgumentsLocalBinding(node)) { + return node; + } + return convertedLoopState.argumentsName || (convertedLoopState.argumentsName = ts.createUniqueName("arguments")); + } + function visitBreakOrContinueStatement(node) { + if (convertedLoopState) { + // check if we can emit break/continue as is + // it is possible if either + // - break/continue is labeled and label is located inside the converted loop + // - break/continue is non-labeled and located in non-converted loop/switch statement + var jump = node.kind === 229 /* BreakStatement */ ? 2 /* Break */ : 4 /* Continue */; + var canUseBreakOrContinue = (node.label && convertedLoopState.labels && convertedLoopState.labels.get(ts.idText(node.label))) || + (!node.label && (convertedLoopState.allowedNonLabeledJumps & jump)); + if (!canUseBreakOrContinue) { + var labelMarker = void 0; + var label = node.label; + if (!label) { + if (node.kind === 229 /* BreakStatement */) { + convertedLoopState.nonLocalJumps |= 2 /* Break */; + labelMarker = "break"; + } + else { + convertedLoopState.nonLocalJumps |= 4 /* Continue */; + // note: return value is emitted only to simplify debugging, call to converted loop body does not do any dispatching on it. + labelMarker = "continue"; + } + } + else { + if (node.kind === 229 /* BreakStatement */) { + labelMarker = "break-" + label.escapedText; + setLabeledJump(convertedLoopState, /*isBreak*/ true, ts.idText(label), labelMarker); + } + else { + labelMarker = "continue-" + label.escapedText; + setLabeledJump(convertedLoopState, /*isBreak*/ false, ts.idText(label), labelMarker); + } + } + var returnExpression = ts.createLiteral(labelMarker); + if (convertedLoopState.loopOutParameters.length) { + var outParams = convertedLoopState.loopOutParameters; + var expr = void 0; + for (var i = 0; i < outParams.length; i++) { + var copyExpr = copyOutParameter(outParams[i], 1 /* ToOutParameter */); + if (i === 0) { + expr = copyExpr; + } + else { + expr = ts.createBinary(expr, 27 /* CommaToken */, copyExpr); + } + } + returnExpression = ts.createBinary(expr, 27 /* CommaToken */, returnExpression); + } + return ts.createReturn(returnExpression); + } + } + return ts.visitEachChild(node, visitor, context); + } + /** + * Visits a ClassDeclaration and transforms it into a variable statement. + * + * @param node A ClassDeclaration node. + */ + function visitClassDeclaration(node) { + // [source] + // class C { } + // + // [output] + // var C = (function () { + // function C() { + // } + // return C; + // }()); + var variable = ts.createVariableDeclaration(ts.getLocalName(node, /*allowComments*/ true), + /*type*/ undefined, transformClassLikeDeclarationToExpression(node)); + ts.setOriginalNode(variable, node); + var statements = []; + var statement = ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([variable])); + ts.setOriginalNode(statement, node); + ts.setTextRange(statement, node); + ts.startOnNewLine(statement); + statements.push(statement); + // Add an `export default` statement for default exports (for `--target es5 --module es6`) + if (ts.hasModifier(node, 1 /* Export */)) { + var exportStatement = ts.hasModifier(node, 512 /* Default */) + ? ts.createExportDefault(ts.getLocalName(node)) + : ts.createExternalModuleExport(ts.getLocalName(node)); + ts.setOriginalNode(exportStatement, statement); + statements.push(exportStatement); + } + var emitFlags = ts.getEmitFlags(node); + if ((emitFlags & 4194304 /* HasEndOfDeclarationMarker */) === 0) { + // Add a DeclarationMarker as a marker for the end of the declaration + statements.push(ts.createEndOfDeclarationMarker(node)); + ts.setEmitFlags(statement, emitFlags | 4194304 /* HasEndOfDeclarationMarker */); + } + return ts.singleOrMany(statements); + } + /** + * Visits a ClassExpression and transforms it into an expression. + * + * @param node A ClassExpression node. + */ + function visitClassExpression(node) { + // [source] + // C = class { } + // + // [output] + // C = (function () { + // function class_1() { + // } + // return class_1; + // }()) + return transformClassLikeDeclarationToExpression(node); + } + /** + * Transforms a ClassExpression or ClassDeclaration into an expression. + * + * @param node A ClassExpression or ClassDeclaration node. + */ + function transformClassLikeDeclarationToExpression(node) { + // [source] + // class C extends D { + // constructor() {} + // method() {} + // get prop() {} + // set prop(v) {} + // } + // + // [output] + // (function (_super) { + // __extends(C, _super); + // function C() { + // } + // C.prototype.method = function () {} + // Object.defineProperty(C.prototype, "prop", { + // get: function() {}, + // set: function() {}, + // enumerable: true, + // configurable: true + // }); + // return C; + // }(D)) + if (node.name) { + enableSubstitutionsForBlockScopedBindings(); + } + var extendsClauseElement = ts.getEffectiveBaseTypeNode(node); + var classFunction = ts.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, extendsClauseElement ? [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, ts.createFileLevelUniqueName("_super"))] : [], + /*type*/ undefined, transformClassBody(node, extendsClauseElement)); + // To preserve the behavior of the old emitter, we explicitly indent + // the body of the function here if it was requested in an earlier + // transformation. + ts.setEmitFlags(classFunction, (ts.getEmitFlags(node) & 65536 /* Indented */) | 524288 /* ReuseTempVariableScope */); + // "inner" and "outer" below are added purely to preserve source map locations from + // the old emitter + var inner = ts.createPartiallyEmittedExpression(classFunction); + inner.end = node.end; + ts.setEmitFlags(inner, 1536 /* NoComments */); + var outer = ts.createPartiallyEmittedExpression(inner); + outer.end = ts.skipTrivia(currentText, node.pos); + ts.setEmitFlags(outer, 1536 /* NoComments */); + var result = ts.createParen(ts.createCall(outer, + /*typeArguments*/ undefined, extendsClauseElement + ? [ts.visitNode(extendsClauseElement.expression, visitor, ts.isExpression)] + : [])); + ts.addSyntheticLeadingComment(result, 3 /* MultiLineCommentTrivia */, "* @class "); + return result; + } + /** + * Transforms a ClassExpression or ClassDeclaration into a function body. + * + * @param node A ClassExpression or ClassDeclaration node. + * @param extendsClauseElement The expression for the class `extends` clause. + */ + function transformClassBody(node, extendsClauseElement) { + var statements = []; + startLexicalEnvironment(); + addExtendsHelperIfNeeded(statements, node, extendsClauseElement); + addConstructor(statements, node, extendsClauseElement); + addClassMembers(statements, node); + // Create a synthetic text range for the return statement. + var closingBraceLocation = ts.createTokenRange(ts.skipTrivia(currentText, node.members.end), 19 /* CloseBraceToken */); + var localName = ts.getInternalName(node); + // The following partially-emitted expression exists purely to align our sourcemap + // emit with the original emitter. + var outer = ts.createPartiallyEmittedExpression(localName); + outer.end = closingBraceLocation.end; + ts.setEmitFlags(outer, 1536 /* NoComments */); + var statement = ts.createReturn(outer); + statement.pos = closingBraceLocation.pos; + ts.setEmitFlags(statement, 1536 /* NoComments */ | 384 /* NoTokenSourceMaps */); + statements.push(statement); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), /*location*/ node.members), /*multiLine*/ true); + ts.setEmitFlags(block, 1536 /* NoComments */); + return block; + } + /** + * Adds a call to the `__extends` helper if needed for a class. + * + * @param statements The statements of the class body function. + * @param node The ClassExpression or ClassDeclaration node. + * @param extendsClauseElement The expression for the class `extends` clause. + */ + function addExtendsHelperIfNeeded(statements, node, extendsClauseElement) { + if (extendsClauseElement) { + statements.push(ts.setTextRange(ts.createExpressionStatement(createExtendsHelper(context, ts.getInternalName(node))), + /*location*/ extendsClauseElement)); + } + } + /** + * Adds the constructor of the class to a class body function. + * + * @param statements The statements of the class body function. + * @param node The ClassExpression or ClassDeclaration node. + * @param extendsClauseElement The expression for the class `extends` clause. + */ + function addConstructor(statements, node, extendsClauseElement) { + var savedConvertedLoopState = convertedLoopState; + convertedLoopState = undefined; + var ancestorFacts = enterSubtree(16278 /* ConstructorExcludes */, 73 /* ConstructorIncludes */); + var constructor = ts.getFirstConstructorWithBody(node); + var hasSynthesizedSuper = hasSynthesizedDefaultSuperCall(constructor, extendsClauseElement !== undefined); + var constructorFunction = ts.createFunctionDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, ts.getInternalName(node), + /*typeParameters*/ undefined, transformConstructorParameters(constructor, hasSynthesizedSuper), + /*type*/ undefined, transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper)); + ts.setTextRange(constructorFunction, constructor || node); + if (extendsClauseElement) { + ts.setEmitFlags(constructorFunction, 8 /* CapturesThis */); + } + statements.push(constructorFunction); + exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, 0 /* None */); + convertedLoopState = savedConvertedLoopState; + } + /** + * Transforms the parameters of the constructor declaration of a class. + * + * @param constructor The constructor for the class. + * @param hasSynthesizedSuper A value indicating whether the constructor starts with a + * synthesized `super` call. + */ + function transformConstructorParameters(constructor, hasSynthesizedSuper) { + // If the TypeScript transformer needed to synthesize a constructor for property + // initializers, it would have also added a synthetic `...args` parameter and + // `super` call. + // If this is the case, we do not include the synthetic `...args` parameter and + // will instead use the `arguments` object in ES5/3. + return ts.visitParameterList(constructor && !hasSynthesizedSuper ? constructor.parameters : undefined, visitor, context) + || []; + } + /** + * Transforms the body of a constructor declaration of a class. + * + * @param constructor The constructor for the class. + * @param node The node which contains the constructor. + * @param extendsClauseElement The expression for the class `extends` clause. + * @param hasSynthesizedSuper A value indicating whether the constructor starts with a + * synthesized `super` call. + */ + function transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper) { + var statements = []; + resumeLexicalEnvironment(); + var statementOffset = -1; + if (hasSynthesizedSuper) { + // If a super call has already been synthesized, + // we're going to assume that we should just transform everything after that. + // The assumption is that no prior step in the pipeline has added any prologue directives. + statementOffset = 0; + } + else if (constructor) { + statementOffset = ts.addStandardPrologue(statements, constructor.body.statements, /*ensureUseStrict*/ false); + } + if (constructor) { + addDefaultValueAssignmentsIfNeeded(statements, constructor); + addRestParameterIfNeeded(statements, constructor, hasSynthesizedSuper); + if (!hasSynthesizedSuper) { + // If no super call has been synthesized, emit custom prologue directives. + statementOffset = ts.addCustomPrologue(statements, constructor.body.statements, statementOffset, visitor); + } + ts.Debug.assert(statementOffset >= 0, "statementOffset not initialized correctly!"); + } + // determine whether the class is known syntactically to be a derived class (e.g. a + // class that extends a value that is not syntactically known to be `null`). + var isDerivedClass = !!extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 96 /* NullKeyword */; + var superCaptureStatus = declareOrCaptureOrReturnThisForConstructorIfNeeded(statements, constructor, isDerivedClass, hasSynthesizedSuper, statementOffset); + // The last statement expression was replaced. Skip it. + if (superCaptureStatus === 1 /* ReplaceSuperCapture */ || superCaptureStatus === 2 /* ReplaceWithReturn */) { + statementOffset++; + } + if (constructor) { + if (superCaptureStatus === 1 /* ReplaceSuperCapture */) { + hierarchyFacts |= 4096 /* ConstructorWithCapturedSuper */; + } + ts.addRange(statements, ts.visitNodes(constructor.body.statements, visitor, ts.isStatement, /*start*/ statementOffset)); + } + // Return `_this` unless we're sure enough that it would be pointless to add a return statement. + // If there's a constructor that we can tell returns in enough places, then we *do not* want to add a return. + if (isDerivedClass + && superCaptureStatus !== 2 /* ReplaceWithReturn */ + && !(constructor && isSufficientlyCoveredByReturnStatements(constructor.body))) { + statements.push(ts.createReturn(ts.createFileLevelUniqueName("_this"))); + } + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + if (constructor) { + prependCaptureNewTargetIfNeeded(statements, constructor, /*copyOnWrite*/ false); + } + var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), + /*location*/ constructor ? constructor.body.statements : node.members), + /*multiLine*/ true); + ts.setTextRange(block, constructor ? constructor.body : node); + if (!constructor) { + ts.setEmitFlags(block, 1536 /* NoComments */); + } + return block; + } + /** + * We want to try to avoid emitting a return statement in certain cases if a user already returned something. + * It would generate obviously dead code, so we'll try to make things a little bit prettier + * by doing a minimal check on whether some common patterns always explicitly return. + */ + function isSufficientlyCoveredByReturnStatements(statement) { + // A return statement is considered covered. + if (statement.kind === 230 /* ReturnStatement */) { + return true; + } + // An if-statement with two covered branches is covered. + else if (statement.kind === 222 /* IfStatement */) { + var ifStatement = statement; + if (ifStatement.elseStatement) { + return isSufficientlyCoveredByReturnStatements(ifStatement.thenStatement) && + isSufficientlyCoveredByReturnStatements(ifStatement.elseStatement); + } + } + // A block is covered if it has a last statement which is covered. + else if (statement.kind === 218 /* Block */) { + var lastStatement = ts.lastOrUndefined(statement.statements); + if (lastStatement && isSufficientlyCoveredByReturnStatements(lastStatement)) { + return true; + } + } + return false; + } + /** + * Declares a `_this` variable for derived classes and for when arrow functions capture `this`. + * + * @returns The new statement offset into the `statements` array. + */ + function declareOrCaptureOrReturnThisForConstructorIfNeeded(statements, ctor, isDerivedClass, hasSynthesizedSuper, statementOffset) { + // If this isn't a derived class, just capture 'this' for arrow functions if necessary. + if (!isDerivedClass) { + if (ctor) { + addCaptureThisForNodeIfNeeded(statements, ctor); + } + return 0 /* NoReplacement */; + } + // We must be here because the user didn't write a constructor + // but we needed to call 'super(...args)' anyway as per 14.5.14 of the ES2016 spec. + // If that's the case we can just immediately return the result of a 'super()' call. + if (!ctor) { + statements.push(ts.createReturn(createDefaultSuperCallOrThis())); + return 2 /* ReplaceWithReturn */; + } + // The constructor exists, but it and the 'super()' call it contains were generated + // for something like property initializers. + // Create a captured '_this' variable and assume it will subsequently be used. + if (hasSynthesizedSuper) { + captureThisForNode(statements, ctor, createDefaultSuperCallOrThis()); + enableSubstitutionsForCapturedThis(); + return 1 /* ReplaceSuperCapture */; + } + // Most of the time, a 'super' call will be the first real statement in a constructor body. + // In these cases, we'd like to transform these into a *single* statement instead of a declaration + // followed by an assignment statement for '_this'. For instance, if we emitted without an initializer, + // we'd get: + // + // var _this; + // _this = _super.call(...) || this; + // + // instead of + // + // var _this = _super.call(...) || this; + // + // Additionally, if the 'super()' call is the last statement, we should just avoid capturing + // entirely and immediately return the result like so: + // + // return _super.call(...) || this; + // + var firstStatement; + var superCallExpression; + var ctorStatements = ctor.body.statements; + if (statementOffset < ctorStatements.length) { + firstStatement = ctorStatements[statementOffset]; + if (firstStatement.kind === 221 /* ExpressionStatement */ && ts.isSuperCall(firstStatement.expression)) { + superCallExpression = visitImmediateSuperCallInBody(firstStatement.expression); + } + } + // Return the result if we have an immediate super() call on the last statement, + // but only if the constructor itself doesn't use 'this' elsewhere. + if (superCallExpression + && statementOffset === ctorStatements.length - 1 + && !(ctor.transformFlags & (8192 /* ContainsLexicalThis */ | 16384 /* ContainsCapturedLexicalThis */))) { + var returnStatement = ts.createReturn(superCallExpression); + if (superCallExpression.kind !== 204 /* BinaryExpression */ + || superCallExpression.left.kind !== 191 /* CallExpression */) { + ts.Debug.fail("Assumed generated super call would have form 'super.call(...) || this'."); + } + // Shift comments from the original super call to the return statement. + ts.setCommentRange(returnStatement, ts.getCommentRange(ts.setEmitFlags(superCallExpression.left, 1536 /* NoComments */))); + statements.push(returnStatement); + return 2 /* ReplaceWithReturn */; + } + // Perform the capture. + captureThisForNode(statements, ctor, superCallExpression || createActualThis()); + // If we're actually replacing the original statement, we need to signal this to the caller. + if (superCallExpression) { + return 1 /* ReplaceSuperCapture */; + } + return 0 /* NoReplacement */; + } + function createActualThis() { + return ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */); + } + function createDefaultSuperCallOrThis() { + return ts.createLogicalOr(ts.createLogicalAnd(ts.createStrictInequality(ts.createFileLevelUniqueName("_super"), ts.createNull()), ts.createFunctionApply(ts.createFileLevelUniqueName("_super"), createActualThis(), ts.createIdentifier("arguments"))), createActualThis()); + } + /** + * Visits a parameter declaration. + * + * @param node A ParameterDeclaration node. + */ + function visitParameter(node) { + if (node.dotDotDotToken) { + // rest parameters are elided + return undefined; + } + else if (ts.isBindingPattern(node.name)) { + // Binding patterns are converted into a generated name and are + // evaluated inside the function body. + return ts.setOriginalNode(ts.setTextRange(ts.createParameter( + /*decorators*/ undefined, + /*modifiers*/ undefined, + /*dotDotDotToken*/ undefined, ts.getGeneratedNameForNode(node), + /*questionToken*/ undefined, + /*type*/ undefined, + /*initializer*/ undefined), + /*location*/ node), + /*original*/ node); + } + else if (node.initializer) { + // Initializers are elided + return ts.setOriginalNode(ts.setTextRange(ts.createParameter( + /*decorators*/ undefined, + /*modifiers*/ undefined, + /*dotDotDotToken*/ undefined, node.name, + /*questionToken*/ undefined, + /*type*/ undefined, + /*initializer*/ undefined), + /*location*/ node), + /*original*/ node); + } + else { + return node; + } + } + /** + * Gets a value indicating whether we need to add default value assignments for a + * function-like node. + * + * @param node A function-like node. + */ + function shouldAddDefaultValueAssignments(node) { + return (node.transformFlags & 65536 /* ContainsDefaultValueAssignments */) !== 0; + } + /** + * Adds statements to the body of a function-like node if it contains parameters with + * binding patterns or initializers. + * + * @param statements The statements for the new function body. + * @param node A function-like node. + */ + function addDefaultValueAssignmentsIfNeeded(statements, node) { + if (!shouldAddDefaultValueAssignments(node)) { + return; + } + for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { + var parameter = _a[_i]; + var name = parameter.name, initializer = parameter.initializer, dotDotDotToken = parameter.dotDotDotToken; + // A rest parameter cannot have a binding pattern or an initializer, + // so let's just ignore it. + if (dotDotDotToken) { + continue; + } + if (ts.isBindingPattern(name)) { + addDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer); + } + else if (initializer) { + addDefaultValueAssignmentForInitializer(statements, parameter, name, initializer); + } + } + } + /** + * Adds statements to the body of a function-like node for parameters with binding patterns + * + * @param statements The statements for the new function body. + * @param parameter The parameter for the function. + * @param name The name of the parameter. + * @param initializer The initializer for the parameter. + */ + function addDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer) { + var temp = ts.getGeneratedNameForNode(parameter); + // In cases where a binding pattern is simply '[]' or '{}', + // we usually don't want to emit a var declaration; however, in the presence + // of an initializer, we must emit that expression to preserve side effects. + if (name.elements.length > 0) { + statements.push(ts.setEmitFlags(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList(ts.flattenDestructuringBinding(parameter, visitor, context, 0 /* All */, temp))), 1048576 /* CustomPrologue */)); + } + else if (initializer) { + statements.push(ts.setEmitFlags(ts.createExpressionStatement(ts.createAssignment(temp, ts.visitNode(initializer, visitor, ts.isExpression))), 1048576 /* CustomPrologue */)); + } + } + /** + * Adds statements to the body of a function-like node for parameters with initializers. + * + * @param statements The statements for the new function body. + * @param parameter The parameter for the function. + * @param name The name of the parameter. + * @param initializer The initializer for the parameter. + */ + function addDefaultValueAssignmentForInitializer(statements, parameter, name, initializer) { + initializer = ts.visitNode(initializer, visitor, ts.isExpression); + var statement = ts.createIf(ts.createTypeCheck(ts.getSynthesizedClone(name), "undefined"), ts.setEmitFlags(ts.setTextRange(ts.createBlock([ + ts.createExpressionStatement(ts.setEmitFlags(ts.setTextRange(ts.createAssignment(ts.setEmitFlags(ts.getMutableClone(name), 48 /* NoSourceMap */), ts.setEmitFlags(initializer, 48 /* NoSourceMap */ | ts.getEmitFlags(initializer) | 1536 /* NoComments */)), parameter), 1536 /* NoComments */)) + ]), parameter), 1 /* SingleLine */ | 32 /* NoTrailingSourceMap */ | 384 /* NoTokenSourceMaps */ | 1536 /* NoComments */)); + ts.startOnNewLine(statement); + ts.setTextRange(statement, parameter); + ts.setEmitFlags(statement, 384 /* NoTokenSourceMaps */ | 32 /* NoTrailingSourceMap */ | 1048576 /* CustomPrologue */ | 1536 /* NoComments */); + statements.push(statement); + } + /** + * Gets a value indicating whether we need to add statements to handle a rest parameter. + * + * @param node A ParameterDeclaration node. + * @param inConstructorWithSynthesizedSuper A value indicating whether the parameter is + * part of a constructor declaration with a + * synthesized call to `super` + */ + function shouldAddRestParameter(node, inConstructorWithSynthesizedSuper) { + return node && node.dotDotDotToken && node.name.kind === 72 /* Identifier */ && !inConstructorWithSynthesizedSuper; + } + /** + * Adds statements to the body of a function-like node if it contains a rest parameter. + * + * @param statements The statements for the new function body. + * @param node A function-like node. + * @param inConstructorWithSynthesizedSuper A value indicating whether the parameter is + * part of a constructor declaration with a + * synthesized call to `super` + */ + function addRestParameterIfNeeded(statements, node, inConstructorWithSynthesizedSuper) { + var parameter = ts.lastOrUndefined(node.parameters); + if (!shouldAddRestParameter(parameter, inConstructorWithSynthesizedSuper)) { + return; + } + // `declarationName` is the name of the local declaration for the parameter. + var declarationName = ts.getMutableClone(parameter.name); + ts.setEmitFlags(declarationName, 48 /* NoSourceMap */); + // `expressionName` is the name of the parameter used in expressions. + var expressionName = ts.getSynthesizedClone(parameter.name); + var restIndex = node.parameters.length - 1; + var temp = ts.createLoopVariable(); + // var param = []; + statements.push(ts.setEmitFlags(ts.setTextRange(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(declarationName, + /*type*/ undefined, ts.createArrayLiteral([])) + ])), + /*location*/ parameter), 1048576 /* CustomPrologue */)); + // for (var _i = restIndex; _i < arguments.length; _i++) { + // param[_i - restIndex] = arguments[_i]; + // } + var forStatement = ts.createFor(ts.setTextRange(ts.createVariableDeclarationList([ + ts.createVariableDeclaration(temp, /*type*/ undefined, ts.createLiteral(restIndex)) + ]), parameter), ts.setTextRange(ts.createLessThan(temp, ts.createPropertyAccess(ts.createIdentifier("arguments"), "length")), parameter), ts.setTextRange(ts.createPostfixIncrement(temp), parameter), ts.createBlock([ + ts.startOnNewLine(ts.setTextRange(ts.createExpressionStatement(ts.createAssignment(ts.createElementAccess(expressionName, restIndex === 0 + ? temp + : ts.createSubtract(temp, ts.createLiteral(restIndex))), ts.createElementAccess(ts.createIdentifier("arguments"), temp))), + /*location*/ parameter)) + ])); + ts.setEmitFlags(forStatement, 1048576 /* CustomPrologue */); + ts.startOnNewLine(forStatement); + statements.push(forStatement); + } + /** + * Adds a statement to capture the `this` of a function declaration if it is needed. + * + * @param statements The statements for the new function body. + * @param node A node. + */ + function addCaptureThisForNodeIfNeeded(statements, node) { + if (node.transformFlags & 16384 /* ContainsCapturedLexicalThis */ && node.kind !== 197 /* ArrowFunction */) { + captureThisForNode(statements, node, ts.createThis()); + } + } + function captureThisForNode(statements, node, initializer) { + enableSubstitutionsForCapturedThis(); + var captureThisStatement = ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(ts.createFileLevelUniqueName("_this"), + /*type*/ undefined, initializer) + ])); + ts.setEmitFlags(captureThisStatement, 1536 /* NoComments */ | 1048576 /* CustomPrologue */); + ts.setSourceMapRange(captureThisStatement, node); + statements.push(captureThisStatement); + } + function prependCaptureNewTargetIfNeeded(statements, node, copyOnWrite) { + if (hierarchyFacts & 16384 /* NewTarget */) { + var newTarget = void 0; + switch (node.kind) { + case 197 /* ArrowFunction */: + return statements; + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + // Methods and accessors cannot be constructors, so 'new.target' will + // always return 'undefined'. + newTarget = ts.createVoidZero(); + break; + case 157 /* Constructor */: + // Class constructors can only be called with `new`, so `this.constructor` + // should be relatively safe to use. + newTarget = ts.createPropertyAccess(ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */), "constructor"); + break; + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + // Functions can be called or constructed, and may have a `this` due to + // being a member or when calling an imported function via `other_1.f()`. + newTarget = ts.createConditional(ts.createLogicalAnd(ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */), ts.createBinary(ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */), 94 /* InstanceOfKeyword */, ts.getLocalName(node))), ts.createPropertyAccess(ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */), "constructor"), ts.createVoidZero()); + break; + default: + return ts.Debug.failBadSyntaxKind(node); + } + var captureNewTargetStatement = ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(ts.createFileLevelUniqueName("_newTarget"), + /*type*/ undefined, newTarget) + ])); + if (copyOnWrite) { + return [captureNewTargetStatement].concat(statements); + } + statements.unshift(captureNewTargetStatement); + } + return statements; + } + /** + * Adds statements to the class body function for a class to define the members of the + * class. + * + * @param statements The statements for the class body function. + * @param node The ClassExpression or ClassDeclaration node. + */ + function addClassMembers(statements, node) { + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + switch (member.kind) { + case 217 /* SemicolonClassElement */: + statements.push(transformSemicolonClassElementToStatement(member)); + break; + case 156 /* MethodDeclaration */: + statements.push(transformClassMethodDeclarationToStatement(getClassMemberPrefix(node, member), member, node)); + break; + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + var accessors = ts.getAllAccessorDeclarations(node.members, member); + if (member === accessors.firstAccessor) { + statements.push(transformAccessorsToStatement(getClassMemberPrefix(node, member), accessors, node)); + } + break; + case 157 /* Constructor */: + // Constructors are handled in visitClassExpression/visitClassDeclaration + break; + default: + ts.Debug.failBadSyntaxKind(node); + break; + } + } + } + /** + * Transforms a SemicolonClassElement into a statement for a class body function. + * + * @param member The SemicolonClassElement node. + */ + function transformSemicolonClassElementToStatement(member) { + return ts.setTextRange(ts.createEmptyStatement(), member); + } + /** + * Transforms a MethodDeclaration into a statement for a class body function. + * + * @param receiver The receiver for the member. + * @param member The MethodDeclaration node. + */ + function transformClassMethodDeclarationToStatement(receiver, member, container) { + var ancestorFacts = enterSubtree(0 /* None */, 0 /* None */); + var commentRange = ts.getCommentRange(member); + var sourceMapRange = ts.getSourceMapRange(member); + var memberName = ts.createMemberAccessForPropertyName(receiver, ts.visitNode(member.name, visitor, ts.isPropertyName), /*location*/ member.name); + var memberFunction = transformFunctionLikeToExpression(member, /*location*/ member, /*name*/ undefined, container); + ts.setEmitFlags(memberFunction, 1536 /* NoComments */); + ts.setSourceMapRange(memberFunction, sourceMapRange); + var statement = ts.setTextRange(ts.createExpressionStatement(ts.createAssignment(memberName, memberFunction)), + /*location*/ member); + ts.setOriginalNode(statement, member); + ts.setCommentRange(statement, commentRange); + // The location for the statement is used to emit comments only. + // No source map should be emitted for this statement to align with the + // old emitter. + ts.setEmitFlags(statement, 48 /* NoSourceMap */); + exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, hierarchyFacts & 49152 /* PropagateNewTargetMask */ ? 16384 /* NewTarget */ : 0 /* None */); + return statement; + } + /** + * Transforms a set of related of get/set accessors into a statement for a class body function. + * + * @param receiver The receiver for the member. + * @param accessors The set of related get/set accessors. + */ + function transformAccessorsToStatement(receiver, accessors, container) { + var statement = ts.createExpressionStatement(transformAccessorsToExpression(receiver, accessors, container, /*startsOnNewLine*/ false)); + // The location for the statement is used to emit source maps only. + // No comments should be emitted for this statement to align with the + // old emitter. + ts.setEmitFlags(statement, 1536 /* NoComments */); + ts.setSourceMapRange(statement, ts.getSourceMapRange(accessors.firstAccessor)); + return statement; + } + /** + * Transforms a set of related get/set accessors into an expression for either a class + * body function or an ObjectLiteralExpression with computed properties. + * + * @param receiver The receiver for the member. + */ + function transformAccessorsToExpression(receiver, _a, container, startsOnNewLine) { + var firstAccessor = _a.firstAccessor, getAccessor = _a.getAccessor, setAccessor = _a.setAccessor; + var ancestorFacts = enterSubtree(0 /* None */, 0 /* None */); + // To align with source maps in the old emitter, the receiver and property name + // arguments are both mapped contiguously to the accessor name. + var target = ts.getMutableClone(receiver); + ts.setEmitFlags(target, 1536 /* NoComments */ | 32 /* NoTrailingSourceMap */); + ts.setSourceMapRange(target, firstAccessor.name); // TODO: GH#18217 + var propertyName = ts.createExpressionForPropertyName(ts.visitNode(firstAccessor.name, visitor, ts.isPropertyName)); + ts.setEmitFlags(propertyName, 1536 /* NoComments */ | 16 /* NoLeadingSourceMap */); + ts.setSourceMapRange(propertyName, firstAccessor.name); + var properties = []; + if (getAccessor) { + var getterFunction = transformFunctionLikeToExpression(getAccessor, /*location*/ undefined, /*name*/ undefined, container); + ts.setSourceMapRange(getterFunction, ts.getSourceMapRange(getAccessor)); + ts.setEmitFlags(getterFunction, 512 /* NoLeadingComments */); + var getter = ts.createPropertyAssignment("get", getterFunction); + ts.setCommentRange(getter, ts.getCommentRange(getAccessor)); + properties.push(getter); + } + if (setAccessor) { + var setterFunction = transformFunctionLikeToExpression(setAccessor, /*location*/ undefined, /*name*/ undefined, container); + ts.setSourceMapRange(setterFunction, ts.getSourceMapRange(setAccessor)); + ts.setEmitFlags(setterFunction, 512 /* NoLeadingComments */); + var setter = ts.createPropertyAssignment("set", setterFunction); + ts.setCommentRange(setter, ts.getCommentRange(setAccessor)); + properties.push(setter); + } + properties.push(ts.createPropertyAssignment("enumerable", ts.createTrue()), ts.createPropertyAssignment("configurable", ts.createTrue())); + var call = ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"), + /*typeArguments*/ undefined, [ + target, + propertyName, + ts.createObjectLiteral(properties, /*multiLine*/ true) + ]); + if (startsOnNewLine) { + ts.startOnNewLine(call); + } + exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, hierarchyFacts & 49152 /* PropagateNewTargetMask */ ? 16384 /* NewTarget */ : 0 /* None */); + return call; + } + /** + * Visits an ArrowFunction and transforms it into a FunctionExpression. + * + * @param node An ArrowFunction node. + */ + function visitArrowFunction(node) { + if (node.transformFlags & 8192 /* ContainsLexicalThis */) { + enableSubstitutionsForCapturedThis(); + } + var savedConvertedLoopState = convertedLoopState; + convertedLoopState = undefined; + var ancestorFacts = enterSubtree(16256 /* ArrowFunctionExcludes */, 66 /* ArrowFunctionIncludes */); + var func = ts.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, transformFunctionBody(node)); + ts.setTextRange(func, node); + ts.setOriginalNode(func, node); + ts.setEmitFlags(func, 8 /* CapturesThis */); + exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */); + convertedLoopState = savedConvertedLoopState; + return func; + } + /** + * Visits a FunctionExpression node. + * + * @param node a FunctionExpression node. + */ + function visitFunctionExpression(node) { + var ancestorFacts = ts.getEmitFlags(node) & 262144 /* AsyncFunctionBody */ + ? enterSubtree(16278 /* AsyncFunctionBodyExcludes */, 69 /* AsyncFunctionBodyIncludes */) + : enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */); + var savedConvertedLoopState = convertedLoopState; + convertedLoopState = undefined; + var parameters = ts.visitParameterList(node.parameters, visitor, context); + var body = node.transformFlags & 64 /* ES2015 */ + ? transformFunctionBody(node) + : visitFunctionBodyDownLevel(node); + var name = hierarchyFacts & 16384 /* NewTarget */ + ? ts.getLocalName(node) + : node.name; + exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, 0 /* None */); + convertedLoopState = savedConvertedLoopState; + return ts.updateFunctionExpression(node, + /*modifiers*/ undefined, node.asteriskToken, name, + /*typeParameters*/ undefined, parameters, + /*type*/ undefined, body); + } + /** + * Visits a FunctionDeclaration node. + * + * @param node a FunctionDeclaration node. + */ + function visitFunctionDeclaration(node) { + var savedConvertedLoopState = convertedLoopState; + convertedLoopState = undefined; + var ancestorFacts = enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */); + var parameters = ts.visitParameterList(node.parameters, visitor, context); + var body = node.transformFlags & 64 /* ES2015 */ + ? transformFunctionBody(node) + : visitFunctionBodyDownLevel(node); + var name = hierarchyFacts & 16384 /* NewTarget */ + ? ts.getLocalName(node) + : node.name; + exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, 0 /* None */); + convertedLoopState = savedConvertedLoopState; + return ts.updateFunctionDeclaration(node, + /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, name, + /*typeParameters*/ undefined, parameters, + /*type*/ undefined, body); + } + /** + * Transforms a function-like node into a FunctionExpression. + * + * @param node The function-like node to transform. + * @param location The source-map location for the new FunctionExpression. + * @param name The name of the new FunctionExpression. + */ + function transformFunctionLikeToExpression(node, location, name, container) { + var savedConvertedLoopState = convertedLoopState; + convertedLoopState = undefined; + var ancestorFacts = container && ts.isClassLike(container) && !ts.hasModifier(node, 32 /* Static */) + ? enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */ | 8 /* NonStaticClassElement */) + : enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */); + var parameters = ts.visitParameterList(node.parameters, visitor, context); + var body = transformFunctionBody(node); + if (hierarchyFacts & 16384 /* NewTarget */ && !name && (node.kind === 239 /* FunctionDeclaration */ || node.kind === 196 /* FunctionExpression */)) { + name = ts.getGeneratedNameForNode(node); + } + exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, 0 /* None */); + convertedLoopState = savedConvertedLoopState; + return ts.setOriginalNode(ts.setTextRange(ts.createFunctionExpression( + /*modifiers*/ undefined, node.asteriskToken, name, + /*typeParameters*/ undefined, parameters, + /*type*/ undefined, body), location), + /*original*/ node); + } + /** + * Transforms the body of a function-like node. + * + * @param node A function-like node. + */ + function transformFunctionBody(node) { + var multiLine = false; // indicates whether the block *must* be emitted as multiple lines + var singleLine = false; // indicates whether the block *may* be emitted as a single line + var statementsLocation; + var closeBraceLocation; + var leadingStatements = []; + var statements = []; + var body = node.body; + var statementOffset; + resumeLexicalEnvironment(); + if (ts.isBlock(body)) { + // ensureUseStrict is false because no new prologue-directive should be added. + // addStandardPrologue will put already-existing directives at the beginning of the target statement-array + statementOffset = ts.addStandardPrologue(leadingStatements, body.statements, /*ensureUseStrict*/ false); + } + addCaptureThisForNodeIfNeeded(leadingStatements, node); + addDefaultValueAssignmentsIfNeeded(leadingStatements, node); + addRestParameterIfNeeded(leadingStatements, node, /*inConstructorWithSynthesizedSuper*/ false); + if (ts.isBlock(body)) { + // addCustomPrologue puts already-existing directives at the beginning of the target statement-array + statementOffset = ts.addCustomPrologue(leadingStatements, body.statements, statementOffset, visitor); + statementsLocation = body.statements; + ts.addRange(statements, ts.visitNodes(body.statements, visitor, ts.isStatement, statementOffset)); + // If the original body was a multi-line block, this must be a multi-line block. + if (!multiLine && body.multiLine) { + multiLine = true; + } + } + else { + ts.Debug.assert(node.kind === 197 /* ArrowFunction */); + // To align with the old emitter, we use a synthetic end position on the location + // for the statement list we synthesize when we down-level an arrow function with + // an expression function body. This prevents both comments and source maps from + // being emitted for the end position only. + statementsLocation = ts.moveRangeEnd(body, -1); + var equalsGreaterThanToken = node.equalsGreaterThanToken; + if (!ts.nodeIsSynthesized(equalsGreaterThanToken) && !ts.nodeIsSynthesized(body)) { + if (ts.rangeEndIsOnSameLineAsRangeStart(equalsGreaterThanToken, body, currentSourceFile)) { + singleLine = true; + } + else { + multiLine = true; + } + } + var expression = ts.visitNode(body, visitor, ts.isExpression); + var returnStatement = ts.createReturn(expression); + ts.setTextRange(returnStatement, body); + ts.moveSyntheticComments(returnStatement, body); + ts.setEmitFlags(returnStatement, 384 /* NoTokenSourceMaps */ | 32 /* NoTrailingSourceMap */ | 1024 /* NoTrailingComments */); + statements.push(returnStatement); + // To align with the source map emit for the old emitter, we set a custom + // source map location for the close brace. + closeBraceLocation = body; + } + var lexicalEnvironment = context.endLexicalEnvironment(); + ts.addStatementsAfterPrologue(statements, lexicalEnvironment); + prependCaptureNewTargetIfNeeded(statements, node, /*copyOnWrite*/ false); + // If we added any final generated statements, this must be a multi-line block + if (ts.some(leadingStatements) || ts.some(lexicalEnvironment)) { + multiLine = true; + } + var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(leadingStatements.concat(statements)), statementsLocation), multiLine); + ts.setTextRange(block, node.body); + if (!multiLine && singleLine) { + ts.setEmitFlags(block, 1 /* SingleLine */); + } + if (closeBraceLocation) { + ts.setTokenSourceMapRange(block, 19 /* CloseBraceToken */, closeBraceLocation); + } + ts.setOriginalNode(block, node.body); + return block; + } + function visitFunctionBodyDownLevel(node) { + var updated = ts.visitFunctionBody(node.body, functionBodyVisitor, context); + return ts.updateBlock(updated, ts.setTextRange(ts.createNodeArray(prependCaptureNewTargetIfNeeded(updated.statements, node, /*copyOnWrite*/ true)), + /*location*/ updated.statements)); + } + function visitBlock(node, isFunctionBody) { + if (isFunctionBody) { + // A function body is not a block scope. + return ts.visitEachChild(node, visitor, context); + } + var ancestorFacts = hierarchyFacts & 256 /* IterationStatement */ + ? enterSubtree(4032 /* IterationStatementBlockExcludes */, 512 /* IterationStatementBlockIncludes */) + : enterSubtree(3904 /* BlockExcludes */, 128 /* BlockIncludes */); + var updated = ts.visitEachChild(node, visitor, context); + exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */); + return updated; + } + /** + * Visits an ExpressionStatement that contains a destructuring assignment. + * + * @param node An ExpressionStatement node. + */ + function visitExpressionStatement(node) { + // If we are here it is most likely because our expression is a destructuring assignment. + switch (node.expression.kind) { + case 195 /* ParenthesizedExpression */: + return ts.updateExpressionStatement(node, visitParenthesizedExpression(node.expression, /*needsDestructuringValue*/ false)); + case 204 /* BinaryExpression */: + return ts.updateExpressionStatement(node, visitBinaryExpression(node.expression, /*needsDestructuringValue*/ false)); + } + return ts.visitEachChild(node, visitor, context); + } + /** + * Visits a ParenthesizedExpression that may contain a destructuring assignment. + * + * @param node A ParenthesizedExpression node. + * @param needsDestructuringValue A value indicating whether we need to hold onto the rhs + * of a destructuring assignment. + */ + function visitParenthesizedExpression(node, needsDestructuringValue) { + // If we are here it is most likely because our expression is a destructuring assignment. + if (!needsDestructuringValue) { + // By default we always emit the RHS at the end of a flattened destructuring + // expression. If we are in a state where we do not need the destructuring value, + // we pass that information along to the children that care about it. + switch (node.expression.kind) { + case 195 /* ParenthesizedExpression */: + return ts.updateParen(node, visitParenthesizedExpression(node.expression, /*needsDestructuringValue*/ false)); + case 204 /* BinaryExpression */: + return ts.updateParen(node, visitBinaryExpression(node.expression, /*needsDestructuringValue*/ false)); + } + } + return ts.visitEachChild(node, visitor, context); + } + /** + * Visits a BinaryExpression that contains a destructuring assignment. + * + * @param node A BinaryExpression node. + * @param needsDestructuringValue A value indicating whether we need to hold onto the rhs + * of a destructuring assignment. + */ + function visitBinaryExpression(node, needsDestructuringValue) { + // If we are here it is because this is a destructuring assignment. + if (ts.isDestructuringAssignment(node)) { + return ts.flattenDestructuringAssignment(node, visitor, context, 0 /* All */, needsDestructuringValue); + } + return ts.visitEachChild(node, visitor, context); + } + function visitVariableStatement(node) { + var ancestorFacts = enterSubtree(0 /* None */, ts.hasModifier(node, 1 /* Export */) ? 32 /* ExportedVariableStatement */ : 0 /* None */); + var updated; + if (convertedLoopState && (node.declarationList.flags & 3 /* BlockScoped */) === 0) { + // we are inside a converted loop - hoist variable declarations + var assignments = void 0; + for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + hoistVariableDeclarationDeclaredInConvertedLoop(convertedLoopState, decl); + if (decl.initializer) { + var assignment = void 0; + if (ts.isBindingPattern(decl.name)) { + assignment = ts.flattenDestructuringAssignment(decl, visitor, context, 0 /* All */); + } + else { + assignment = ts.createBinary(decl.name, 59 /* EqualsToken */, ts.visitNode(decl.initializer, visitor, ts.isExpression)); + ts.setTextRange(assignment, decl); + } + assignments = ts.append(assignments, assignment); + } + } + if (assignments) { + updated = ts.setTextRange(ts.createExpressionStatement(ts.inlineExpressions(assignments)), node); + } + else { + // none of declarations has initializer - the entire variable statement can be deleted + updated = undefined; + } + } + else { + updated = ts.visitEachChild(node, visitor, context); + } + exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */); + return updated; + } + /** + * Visits a VariableDeclarationList that is block scoped (e.g. `let` or `const`). + * + * @param node A VariableDeclarationList node. + */ + function visitVariableDeclarationList(node) { + if (node.transformFlags & 64 /* ES2015 */) { + if (node.flags & 3 /* BlockScoped */) { + enableSubstitutionsForBlockScopedBindings(); + } + var declarations = ts.flatMap(node.declarations, node.flags & 1 /* Let */ + ? visitVariableDeclarationInLetDeclarationList + : visitVariableDeclaration); + var declarationList = ts.createVariableDeclarationList(declarations); + ts.setOriginalNode(declarationList, node); + ts.setTextRange(declarationList, node); + ts.setCommentRange(declarationList, node); + // If the first or last declaration is a binding pattern, we need to modify + // the source map range for the declaration list. + if (node.transformFlags & 2097152 /* ContainsBindingPattern */ + && (ts.isBindingPattern(node.declarations[0].name) || ts.isBindingPattern(ts.last(node.declarations).name))) { + ts.setSourceMapRange(declarationList, getRangeUnion(declarations)); + } + return declarationList; + } + return ts.visitEachChild(node, visitor, context); + } + function getRangeUnion(declarations) { + // declarations may not be sorted by position. + // pos should be the minimum* position over all nodes (that's not -1), end should be the maximum end over all nodes. + var pos = -1, end = -1; + for (var _i = 0, declarations_10 = declarations; _i < declarations_10.length; _i++) { + var node = declarations_10[_i]; + pos = pos === -1 ? node.pos : node.pos === -1 ? pos : Math.min(pos, node.pos); + end = Math.max(end, node.end); + } + return ts.createRange(pos, end); + } + /** + * Gets a value indicating whether we should emit an explicit initializer for a variable + * declaration in a `let` declaration list. + * + * @param node A VariableDeclaration node. + */ + function shouldEmitExplicitInitializerForLetDeclaration(node) { + // Nested let bindings might need to be initialized explicitly to preserve + // ES6 semantic: + // + // { let x = 1; } + // { let x; } // x here should be undefined. not 1 + // + // Top level bindings never collide with anything and thus don't require + // explicit initialization. As for nested let bindings there are two cases: + // + // - Nested let bindings that were not renamed definitely should be + // initialized explicitly: + // + // { let x = 1; } + // { let x; if (some-condition) { x = 1}; if (x) { /*1*/ } } + // + // Without explicit initialization code in /*1*/ can be executed even if + // some-condition is evaluated to false. + // + // - Renaming introduces fresh name that should not collide with any + // existing names, however renamed bindings sometimes also should be + // explicitly initialized. One particular case: non-captured binding + // declared inside loop body (but not in loop initializer): + // + // let x; + // for (;;) { + // let x; + // } + // + // In downlevel codegen inner 'x' will be renamed so it won't collide + // with outer 'x' however it will should be reset on every iteration as + // if it was declared anew. + // + // * Why non-captured binding? + // - Because if loop contains block scoped binding captured in some + // function then loop body will be rewritten to have a fresh scope + // on every iteration so everything will just work. + // + // * Why loop initializer is excluded? + // - Since we've introduced a fresh name it already will be undefined. + var flags = resolver.getNodeCheckFlags(node); + var isCapturedInFunction = flags & 262144 /* CapturedBlockScopedBinding */; + var isDeclaredInLoop = flags & 524288 /* BlockScopedBindingInLoop */; + var emittedAsTopLevel = (hierarchyFacts & 64 /* TopLevel */) !== 0 + || (isCapturedInFunction + && isDeclaredInLoop + && (hierarchyFacts & 512 /* IterationStatementBlock */) !== 0); + var emitExplicitInitializer = !emittedAsTopLevel + && (hierarchyFacts & 2048 /* ForInOrForOfStatement */) === 0 + && (!resolver.isDeclarationWithCollidingName(node) + || (isDeclaredInLoop + && !isCapturedInFunction + && (hierarchyFacts & (1024 /* ForStatement */ | 2048 /* ForInOrForOfStatement */)) === 0)); + return emitExplicitInitializer; + } + /** + * Visits a VariableDeclaration in a `let` declaration list. + * + * @param node A VariableDeclaration node. + */ + function visitVariableDeclarationInLetDeclarationList(node) { + // For binding pattern names that lack initializers there is no point to emit + // explicit initializer since downlevel codegen for destructuring will fail + // in the absence of initializer so all binding elements will say uninitialized + var name = node.name; + if (ts.isBindingPattern(name)) { + return visitVariableDeclaration(node); + } + if (!node.initializer && shouldEmitExplicitInitializerForLetDeclaration(node)) { + var clone_2 = ts.getMutableClone(node); + clone_2.initializer = ts.createVoidZero(); + return clone_2; + } + return ts.visitEachChild(node, visitor, context); + } + /** + * Visits a VariableDeclaration node with a binding pattern. + * + * @param node A VariableDeclaration node. + */ + function visitVariableDeclaration(node) { + var ancestorFacts = enterSubtree(32 /* ExportedVariableStatement */, 0 /* None */); + var updated; + if (ts.isBindingPattern(node.name)) { + updated = ts.flattenDestructuringBinding(node, visitor, context, 0 /* All */, + /*value*/ undefined, (ancestorFacts & 32 /* ExportedVariableStatement */) !== 0); + } + else { + updated = ts.visitEachChild(node, visitor, context); + } + exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */); + return updated; + } + function recordLabel(node) { + convertedLoopState.labels.set(ts.idText(node.label), true); + } + function resetLabel(node) { + convertedLoopState.labels.set(ts.idText(node.label), false); + } + function visitLabeledStatement(node) { + if (convertedLoopState && !convertedLoopState.labels) { + convertedLoopState.labels = ts.createMap(); + } + var statement = ts.unwrapInnermostStatementOfLabel(node, convertedLoopState && recordLabel); + return ts.isIterationStatement(statement, /*lookInLabeledStatements*/ false) + ? visitIterationStatement(statement, /*outermostLabeledStatement*/ node) + : ts.restoreEnclosingLabel(ts.visitNode(statement, visitor, ts.isStatement, ts.liftToBlock), node, convertedLoopState && resetLabel); + } + function visitIterationStatement(node, outermostLabeledStatement) { + switch (node.kind) { + case 223 /* DoStatement */: + case 224 /* WhileStatement */: + return visitDoOrWhileStatement(node, outermostLabeledStatement); + case 225 /* ForStatement */: + return visitForStatement(node, outermostLabeledStatement); + case 226 /* ForInStatement */: + return visitForInStatement(node, outermostLabeledStatement); + case 227 /* ForOfStatement */: + return visitForOfStatement(node, outermostLabeledStatement); + } + } + function visitIterationStatementWithFacts(excludeFacts, includeFacts, node, outermostLabeledStatement, convert) { + var ancestorFacts = enterSubtree(excludeFacts, includeFacts); + var updated = convertIterationStatementBodyIfNecessary(node, outermostLabeledStatement, convert); + exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */); + return updated; + } + function visitDoOrWhileStatement(node, outermostLabeledStatement) { + return visitIterationStatementWithFacts(0 /* DoOrWhileStatementExcludes */, 256 /* DoOrWhileStatementIncludes */, node, outermostLabeledStatement); + } + function visitForStatement(node, outermostLabeledStatement) { + return visitIterationStatementWithFacts(3008 /* ForStatementExcludes */, 1280 /* ForStatementIncludes */, node, outermostLabeledStatement); + } + function visitForInStatement(node, outermostLabeledStatement) { + return visitIterationStatementWithFacts(1984 /* ForInOrForOfStatementExcludes */, 2304 /* ForInOrForOfStatementIncludes */, node, outermostLabeledStatement); + } + function visitForOfStatement(node, outermostLabeledStatement) { + return visitIterationStatementWithFacts(1984 /* ForInOrForOfStatementExcludes */, 2304 /* ForInOrForOfStatementIncludes */, node, outermostLabeledStatement, compilerOptions.downlevelIteration ? convertForOfStatementForIterable : convertForOfStatementForArray); + } + function convertForOfStatementHead(node, boundValue, convertedLoopBodyStatements) { + var statements = []; + var initializer = node.initializer; + if (ts.isVariableDeclarationList(initializer)) { + if (node.initializer.flags & 3 /* BlockScoped */) { + enableSubstitutionsForBlockScopedBindings(); + } + var firstOriginalDeclaration = ts.firstOrUndefined(initializer.declarations); + if (firstOriginalDeclaration && ts.isBindingPattern(firstOriginalDeclaration.name)) { + // This works whether the declaration is a var, let, or const. + // It will use rhsIterationValue _a[_i] as the initializer. + var declarations = ts.flattenDestructuringBinding(firstOriginalDeclaration, visitor, context, 0 /* All */, boundValue); + var declarationList = ts.setTextRange(ts.createVariableDeclarationList(declarations), node.initializer); + ts.setOriginalNode(declarationList, node.initializer); + // Adjust the source map range for the first declaration to align with the old + // emitter. + ts.setSourceMapRange(declarationList, ts.createRange(declarations[0].pos, ts.last(declarations).end)); + statements.push(ts.createVariableStatement( + /*modifiers*/ undefined, declarationList)); + } + else { + // The following call does not include the initializer, so we have + // to emit it separately. + statements.push(ts.setTextRange(ts.createVariableStatement( + /*modifiers*/ undefined, ts.setOriginalNode(ts.setTextRange(ts.createVariableDeclarationList([ + ts.createVariableDeclaration(firstOriginalDeclaration ? firstOriginalDeclaration.name : ts.createTempVariable(/*recordTempVariable*/ undefined), + /*type*/ undefined, boundValue) + ]), ts.moveRangePos(initializer, -1)), initializer)), ts.moveRangeEnd(initializer, -1))); + } + } + else { + // Initializer is an expression. Emit the expression in the body, so that it's + // evaluated on every iteration. + var assignment = ts.createAssignment(initializer, boundValue); + if (ts.isDestructuringAssignment(assignment)) { + ts.aggregateTransformFlags(assignment); + statements.push(ts.createExpressionStatement(visitBinaryExpression(assignment, /*needsDestructuringValue*/ false))); + } + else { + assignment.end = initializer.end; + statements.push(ts.setTextRange(ts.createExpressionStatement(ts.visitNode(assignment, visitor, ts.isExpression)), ts.moveRangeEnd(initializer, -1))); + } + } + if (convertedLoopBodyStatements) { + return createSyntheticBlockForConvertedStatements(ts.addRange(statements, convertedLoopBodyStatements)); + } + else { + var statement = ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock); + if (ts.isBlock(statement)) { + return ts.updateBlock(statement, ts.setTextRange(ts.createNodeArray(ts.concatenate(statements, statement.statements)), statement.statements)); + } + else { + statements.push(statement); + return createSyntheticBlockForConvertedStatements(statements); + } + } + } + function createSyntheticBlockForConvertedStatements(statements) { + return ts.setEmitFlags(ts.createBlock(ts.createNodeArray(statements), + /*multiLine*/ true), 48 /* NoSourceMap */ | 384 /* NoTokenSourceMaps */); + } + function convertForOfStatementForArray(node, outermostLabeledStatement, convertedLoopBodyStatements) { + // The following ES6 code: + // + // for (let v of expr) { } + // + // should be emitted as + // + // for (var _i = 0, _a = expr; _i < _a.length; _i++) { + // var v = _a[_i]; + // } + // + // where _a and _i are temps emitted to capture the RHS and the counter, + // respectively. + // When the left hand side is an expression instead of a let declaration, + // the "let v" is not emitted. + // When the left hand side is a let/const, the v is renamed if there is + // another v in scope. + // Note that all assignments to the LHS are emitted in the body, including + // all destructuring. + // Note also that because an extra statement is needed to assign to the LHS, + // for-of bodies are always emitted as blocks. + var expression = ts.visitNode(node.expression, visitor, ts.isExpression); + // In the case where the user wrote an identifier as the RHS, like this: + // + // for (let v of arr) { } + // + // we don't want to emit a temporary variable for the RHS, just use it directly. + var counter = ts.createLoopVariable(); + var rhsReference = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(expression) : ts.createTempVariable(/*recordTempVariable*/ undefined); + // The old emitter does not emit source maps for the expression + ts.setEmitFlags(expression, 48 /* NoSourceMap */ | ts.getEmitFlags(expression)); + var forStatement = ts.setTextRange(ts.createFor( + /*initializer*/ ts.setEmitFlags(ts.setTextRange(ts.createVariableDeclarationList([ + ts.setTextRange(ts.createVariableDeclaration(counter, /*type*/ undefined, ts.createLiteral(0)), ts.moveRangePos(node.expression, -1)), + ts.setTextRange(ts.createVariableDeclaration(rhsReference, /*type*/ undefined, expression), node.expression) + ]), node.expression), 2097152 /* NoHoisting */), + /*condition*/ ts.setTextRange(ts.createLessThan(counter, ts.createPropertyAccess(rhsReference, "length")), node.expression), + /*incrementor*/ ts.setTextRange(ts.createPostfixIncrement(counter), node.expression), + /*statement*/ convertForOfStatementHead(node, ts.createElementAccess(rhsReference, counter), convertedLoopBodyStatements)), + /*location*/ node); + // Disable trailing source maps for the OpenParenToken to align source map emit with the old emitter. + ts.setEmitFlags(forStatement, 256 /* NoTokenTrailingSourceMaps */); + ts.setTextRange(forStatement, node); + return ts.restoreEnclosingLabel(forStatement, outermostLabeledStatement, convertedLoopState && resetLabel); + } + function convertForOfStatementForIterable(node, outermostLabeledStatement, convertedLoopBodyStatements) { + var expression = ts.visitNode(node.expression, visitor, ts.isExpression); + var iterator = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(expression) : ts.createTempVariable(/*recordTempVariable*/ undefined); + var result = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(iterator) : ts.createTempVariable(/*recordTempVariable*/ undefined); + var errorRecord = ts.createUniqueName("e"); + var catchVariable = ts.getGeneratedNameForNode(errorRecord); + var returnMethod = ts.createTempVariable(/*recordTempVariable*/ undefined); + var values = ts.createValuesHelper(context, expression, node.expression); + var next = ts.createCall(ts.createPropertyAccess(iterator, "next"), /*typeArguments*/ undefined, []); + hoistVariableDeclaration(errorRecord); + hoistVariableDeclaration(returnMethod); + var forStatement = ts.setEmitFlags(ts.setTextRange(ts.createFor( + /*initializer*/ ts.setEmitFlags(ts.setTextRange(ts.createVariableDeclarationList([ + ts.setTextRange(ts.createVariableDeclaration(iterator, /*type*/ undefined, values), node.expression), + ts.createVariableDeclaration(result, /*type*/ undefined, next) + ]), node.expression), 2097152 /* NoHoisting */), + /*condition*/ ts.createLogicalNot(ts.createPropertyAccess(result, "done")), + /*incrementor*/ ts.createAssignment(result, next), + /*statement*/ convertForOfStatementHead(node, ts.createPropertyAccess(result, "value"), convertedLoopBodyStatements)), + /*location*/ node), 256 /* NoTokenTrailingSourceMaps */); + return ts.createTry(ts.createBlock([ + ts.restoreEnclosingLabel(forStatement, outermostLabeledStatement, convertedLoopState && resetLabel) + ]), ts.createCatchClause(ts.createVariableDeclaration(catchVariable), ts.setEmitFlags(ts.createBlock([ + ts.createExpressionStatement(ts.createAssignment(errorRecord, ts.createObjectLiteral([ + ts.createPropertyAssignment("error", catchVariable) + ]))) + ]), 1 /* SingleLine */)), ts.createBlock([ + ts.createTry( + /*tryBlock*/ ts.createBlock([ + ts.setEmitFlags(ts.createIf(ts.createLogicalAnd(ts.createLogicalAnd(result, ts.createLogicalNot(ts.createPropertyAccess(result, "done"))), ts.createAssignment(returnMethod, ts.createPropertyAccess(iterator, "return"))), ts.createExpressionStatement(ts.createFunctionCall(returnMethod, iterator, []))), 1 /* SingleLine */), + ]), + /*catchClause*/ undefined, + /*finallyBlock*/ ts.setEmitFlags(ts.createBlock([ + ts.setEmitFlags(ts.createIf(errorRecord, ts.createThrow(ts.createPropertyAccess(errorRecord, "error"))), 1 /* SingleLine */) + ]), 1 /* SingleLine */)) + ])); + } + /** + * Visits an ObjectLiteralExpression with computed property names. + * + * @param node An ObjectLiteralExpression node. + */ + function visitObjectLiteralExpression(node) { + // We are here because a ComputedPropertyName was used somewhere in the expression. + var properties = node.properties; + var numProperties = properties.length; + // Find the first computed property. + // Everything until that point can be emitted as part of the initial object literal. + var numInitialProperties = numProperties; + var numInitialPropertiesWithoutYield = numProperties; + for (var i = 0; i < numProperties; i++) { + var property = properties[i]; + if ((property.transformFlags & 4194304 /* ContainsYield */ && hierarchyFacts & 4 /* AsyncFunctionBody */) + && i < numInitialPropertiesWithoutYield) { + numInitialPropertiesWithoutYield = i; + } + if (property.name.kind === 149 /* ComputedPropertyName */) { + numInitialProperties = i; + break; + } + } + if (numInitialProperties !== numProperties) { + if (numInitialPropertiesWithoutYield < numInitialProperties) { + numInitialProperties = numInitialPropertiesWithoutYield; + } + // For computed properties, we need to create a unique handle to the object + // literal so we can modify it without risking internal assignments tainting the object. + var temp = ts.createTempVariable(hoistVariableDeclaration); + // Write out the first non-computed properties, then emit the rest through indexing on the temp variable. + var expressions = []; + var assignment = ts.createAssignment(temp, ts.setEmitFlags(ts.createObjectLiteral(ts.visitNodes(properties, visitor, ts.isObjectLiteralElementLike, 0, numInitialProperties), node.multiLine), 65536 /* Indented */)); + if (node.multiLine) { + ts.startOnNewLine(assignment); + } + expressions.push(assignment); + addObjectLiteralMembers(expressions, node, temp, numInitialProperties); + // We need to clone the temporary identifier so that we can write it on a + // new line + expressions.push(node.multiLine ? ts.startOnNewLine(ts.getMutableClone(temp)) : temp); + return ts.inlineExpressions(expressions); + } + return ts.visitEachChild(node, visitor, context); + } + function shouldConvertPartOfIterationStatement(node) { + return (resolver.getNodeCheckFlags(node) & 131072 /* ContainsCapturedBlockScopeBinding */) !== 0; + } + function shouldConvertInitializerOfForStatement(node) { + return ts.isForStatement(node) && !!node.initializer && shouldConvertPartOfIterationStatement(node.initializer); + } + function shouldConvertConditionOfForStatement(node) { + return ts.isForStatement(node) && !!node.condition && shouldConvertPartOfIterationStatement(node.condition); + } + function shouldConvertIncrementorOfForStatement(node) { + return ts.isForStatement(node) && !!node.incrementor && shouldConvertPartOfIterationStatement(node.incrementor); + } + function shouldConvertIterationStatement(node) { + return shouldConvertBodyOfIterationStatement(node) + || shouldConvertInitializerOfForStatement(node); + } + function shouldConvertBodyOfIterationStatement(node) { + return (resolver.getNodeCheckFlags(node) & 65536 /* LoopWithCapturedBlockScopedBinding */) !== 0; + } + /** + * Records constituents of name for the given variable to be hoisted in the outer scope. + */ + function hoistVariableDeclarationDeclaredInConvertedLoop(state, node) { + if (!state.hoistedLocalVariables) { + state.hoistedLocalVariables = []; + } + visit(node.name); + function visit(node) { + if (node.kind === 72 /* Identifier */) { + state.hoistedLocalVariables.push(node); + } + else { + for (var _i = 0, _a = node.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (!ts.isOmittedExpression(element)) { + visit(element.name); + } + } + } + } + } + function convertIterationStatementBodyIfNecessary(node, outermostLabeledStatement, convert) { + if (!shouldConvertIterationStatement(node)) { + var saveAllowedNonLabeledJumps = void 0; + if (convertedLoopState) { + // we get here if we are trying to emit normal loop loop inside converted loop + // set allowedNonLabeledJumps to Break | Continue to mark that break\continue inside the loop should be emitted as is + saveAllowedNonLabeledJumps = convertedLoopState.allowedNonLabeledJumps; + convertedLoopState.allowedNonLabeledJumps = 2 /* Break */ | 4 /* Continue */; + } + var result = convert + ? convert(node, outermostLabeledStatement, /*convertedLoopBodyStatements*/ undefined) + : ts.restoreEnclosingLabel(ts.visitEachChild(node, visitor, context), outermostLabeledStatement, convertedLoopState && resetLabel); + if (convertedLoopState) { + convertedLoopState.allowedNonLabeledJumps = saveAllowedNonLabeledJumps; + } + return result; + } + var currentState = createConvertedLoopState(node); + var statements = []; + var outerConvertedLoopState = convertedLoopState; + convertedLoopState = currentState; + var initializerFunction = shouldConvertInitializerOfForStatement(node) ? createFunctionForInitializerOfForStatement(node, currentState) : undefined; + var bodyFunction = shouldConvertBodyOfIterationStatement(node) ? createFunctionForBodyOfIterationStatement(node, currentState, outerConvertedLoopState) : undefined; + convertedLoopState = outerConvertedLoopState; + if (initializerFunction) + statements.push(initializerFunction.functionDeclaration); + if (bodyFunction) + statements.push(bodyFunction.functionDeclaration); + addExtraDeclarationsForConvertedLoop(statements, currentState, outerConvertedLoopState); + if (initializerFunction) { + statements.push(generateCallToConvertedLoopInitializer(initializerFunction.functionName, initializerFunction.containsYield)); + } + var loop; + if (bodyFunction) { + if (convert) { + loop = convert(node, outermostLabeledStatement, bodyFunction.part); + } + else { + var clone_3 = convertIterationStatementCore(node, initializerFunction, ts.createBlock(bodyFunction.part, /*multiLine*/ true)); + ts.aggregateTransformFlags(clone_3); + loop = ts.restoreEnclosingLabel(clone_3, outermostLabeledStatement, convertedLoopState && resetLabel); + } + } + else { + var clone_4 = convertIterationStatementCore(node, initializerFunction, ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); + ts.aggregateTransformFlags(clone_4); + loop = ts.restoreEnclosingLabel(clone_4, outermostLabeledStatement, convertedLoopState && resetLabel); + } + statements.push(loop); + return statements; + } + function convertIterationStatementCore(node, initializerFunction, convertedLoopBody) { + switch (node.kind) { + case 225 /* ForStatement */: return convertForStatement(node, initializerFunction, convertedLoopBody); + case 226 /* ForInStatement */: return convertForInStatement(node, convertedLoopBody); + case 227 /* ForOfStatement */: return convertForOfStatement(node, convertedLoopBody); + case 223 /* DoStatement */: return convertDoStatement(node, convertedLoopBody); + case 224 /* WhileStatement */: return convertWhileStatement(node, convertedLoopBody); + default: return ts.Debug.failBadSyntaxKind(node, "IterationStatement expected"); + } + } + function convertForStatement(node, initializerFunction, convertedLoopBody) { + var shouldConvertCondition = node.condition && shouldConvertPartOfIterationStatement(node.condition); + var shouldConvertIncrementor = shouldConvertCondition || node.incrementor && shouldConvertPartOfIterationStatement(node.incrementor); + return ts.updateFor(node, ts.visitNode(initializerFunction ? initializerFunction.part : node.initializer, visitor, ts.isForInitializer), ts.visitNode(shouldConvertCondition ? undefined : node.condition, visitor, ts.isExpression), ts.visitNode(shouldConvertIncrementor ? undefined : node.incrementor, visitor, ts.isExpression), convertedLoopBody); + } + function convertForOfStatement(node, convertedLoopBody) { + return ts.updateForOf(node, + /*awaitModifier*/ undefined, ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), convertedLoopBody); + } + function convertForInStatement(node, convertedLoopBody) { + return ts.updateForIn(node, ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), convertedLoopBody); + } + function convertDoStatement(node, convertedLoopBody) { + return ts.updateDo(node, convertedLoopBody, ts.visitNode(node.expression, visitor, ts.isExpression)); + } + function convertWhileStatement(node, convertedLoopBody) { + return ts.updateWhile(node, ts.visitNode(node.expression, visitor, ts.isExpression), convertedLoopBody); + } + function createConvertedLoopState(node) { + var loopInitializer; + switch (node.kind) { + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + var initializer = node.initializer; + if (initializer && initializer.kind === 238 /* VariableDeclarationList */) { + loopInitializer = initializer; + } + break; + } + // variables that will be passed to the loop as parameters + var loopParameters = []; + // variables declared in the loop initializer that will be changed inside the loop + var loopOutParameters = []; + if (loopInitializer && (ts.getCombinedNodeFlags(loopInitializer) & 3 /* BlockScoped */)) { + var hasCapturedBindingsInForInitializer = shouldConvertInitializerOfForStatement(node); + for (var _i = 0, _a = loopInitializer.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + processLoopVariableDeclaration(node, decl, loopParameters, loopOutParameters, hasCapturedBindingsInForInitializer); + } + } + var currentState = { loopParameters: loopParameters, loopOutParameters: loopOutParameters }; + if (convertedLoopState) { + // convertedOuterLoopState !== undefined means that this converted loop is nested in another converted loop. + // if outer converted loop has already accumulated some state - pass it through + if (convertedLoopState.argumentsName) { + // outer loop has already used 'arguments' so we've already have some name to alias it + // use the same name in all nested loops + currentState.argumentsName = convertedLoopState.argumentsName; + } + if (convertedLoopState.thisName) { + // outer loop has already used 'this' so we've already have some name to alias it + // use the same name in all nested loops + currentState.thisName = convertedLoopState.thisName; + } + if (convertedLoopState.hoistedLocalVariables) { + // we've already collected some non-block scoped variable declarations in enclosing loop + // use the same storage in nested loop + currentState.hoistedLocalVariables = convertedLoopState.hoistedLocalVariables; + } + } + return currentState; + } + function addExtraDeclarationsForConvertedLoop(statements, state, outerState) { + var extraVariableDeclarations; + // propagate state from the inner loop to the outer loop if necessary + if (state.argumentsName) { + // if alias for arguments is set + if (outerState) { + // pass it to outer converted loop + outerState.argumentsName = state.argumentsName; + } + else { + // this is top level converted loop and we need to create an alias for 'arguments' object + (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(state.argumentsName, + /*type*/ undefined, ts.createIdentifier("arguments"))); + } + } + if (state.thisName) { + // if alias for this is set + if (outerState) { + // pass it to outer converted loop + outerState.thisName = state.thisName; + } + else { + // this is top level converted loop so we need to create an alias for 'this' here + // NOTE: + // if converted loops were all nested in arrow function then we'll always emit '_this' so convertedLoopState.thisName will not be set. + // If it is set this means that all nested loops are not nested in arrow function and it is safe to capture 'this'. + (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(state.thisName, + /*type*/ undefined, ts.createIdentifier("this"))); + } + } + if (state.hoistedLocalVariables) { + // if hoistedLocalVariables !== undefined this means that we've possibly collected some variable declarations to be hoisted later + if (outerState) { + // pass them to outer converted loop + outerState.hoistedLocalVariables = state.hoistedLocalVariables; + } + else { + if (!extraVariableDeclarations) { + extraVariableDeclarations = []; + } + // hoist collected variable declarations + for (var _i = 0, _a = state.hoistedLocalVariables; _i < _a.length; _i++) { + var identifier = _a[_i]; + extraVariableDeclarations.push(ts.createVariableDeclaration(identifier)); + } + } + } + // add extra variables to hold out parameters if necessary + if (state.loopOutParameters.length) { + if (!extraVariableDeclarations) { + extraVariableDeclarations = []; + } + for (var _b = 0, _c = state.loopOutParameters; _b < _c.length; _b++) { + var outParam = _c[_b]; + extraVariableDeclarations.push(ts.createVariableDeclaration(outParam.outParamName)); + } + } + if (state.conditionVariable) { + if (!extraVariableDeclarations) { + extraVariableDeclarations = []; + } + extraVariableDeclarations.push(ts.createVariableDeclaration(state.conditionVariable, /*type*/ undefined, ts.createFalse())); + } + // create variable statement to hold all introduced variable declarations + if (extraVariableDeclarations) { + statements.push(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList(extraVariableDeclarations))); + } + } + function createOutVariable(p) { + return ts.createVariableDeclaration(p.originalName, /*type*/ undefined, p.outParamName); + } + /** + * Creates a `_loop_init` function for a `ForStatement` with a block-scoped initializer + * that is captured in a closure inside of the initializer. The `_loop_init` function is + * used to preserve the per-iteration environment semantics of + * [13.7.4.8 RS: ForBodyEvaluation](https://tc39.github.io/ecma262/#sec-forbodyevaluation). + */ + function createFunctionForInitializerOfForStatement(node, currentState) { + var functionName = ts.createUniqueName("_loop_init"); + var containsYield = (node.initializer.transformFlags & 4194304 /* ContainsYield */) !== 0; + var emitFlags = 0 /* None */; + if (currentState.containsLexicalThis) + emitFlags |= 8 /* CapturesThis */; + if (containsYield && hierarchyFacts & 4 /* AsyncFunctionBody */) + emitFlags |= 262144 /* AsyncFunctionBody */; + var statements = []; + statements.push(ts.createVariableStatement(/*modifiers*/ undefined, node.initializer)); + copyOutParameters(currentState.loopOutParameters, 2 /* Initializer */, 1 /* ToOutParameter */, statements); + // This transforms the following ES2015 syntax: + // + // for (let i = (setImmediate(() => console.log(i)), 0); i < 2; i++) { + // // loop body + // } + // + // Into the following ES5 syntax: + // + // var _loop_init_1 = function () { + // var i = (setImmediate(() => console.log(i)), 0); + // out_i_1 = i; + // }; + // var out_i_1; + // _loop_init_1(); + // for (var i = out_i_1; i < 2; i++) { + // // loop body + // } + // + // Which prevents mutations to `i` in the per-iteration environment of the body + // from affecting the initial value for `i` outside of the per-iteration environment. + var functionDeclaration = ts.createVariableStatement( + /*modifiers*/ undefined, ts.setEmitFlags(ts.createVariableDeclarationList([ + ts.createVariableDeclaration(functionName, + /*type*/ undefined, ts.setEmitFlags(ts.createFunctionExpression( + /*modifiers*/ undefined, containsYield ? ts.createToken(40 /* AsteriskToken */) : undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, + /*parameters*/ undefined, + /*type*/ undefined, ts.visitNode(ts.createBlock(statements, /*multiLine*/ true), visitor, ts.isBlock)), emitFlags)) + ]), 2097152 /* NoHoisting */)); + var part = ts.createVariableDeclarationList(ts.map(currentState.loopOutParameters, createOutVariable)); + return { functionName: functionName, containsYield: containsYield, functionDeclaration: functionDeclaration, part: part }; + } + /** + * Creates a `_loop` function for an `IterationStatement` with a block-scoped initializer + * that is captured in a closure inside of the loop body. The `_loop` function is used to + * preserve the per-iteration environment semantics of + * [13.7.4.8 RS: ForBodyEvaluation](https://tc39.github.io/ecma262/#sec-forbodyevaluation). + */ + function createFunctionForBodyOfIterationStatement(node, currentState, outerState) { + var functionName = ts.createUniqueName("_loop"); + startLexicalEnvironment(); + var statement = ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock); + var lexicalEnvironment = endLexicalEnvironment(); + var statements = []; + if (shouldConvertConditionOfForStatement(node) || shouldConvertIncrementorOfForStatement(node)) { + // If a block-scoped variable declared in the initializer of `node` is captured in + // the condition or incrementor, we must move the condition and incrementor into + // the body of the for loop. + // + // This transforms the following ES2015 syntax: + // + // for (let i = 0; setImmediate(() => console.log(i)), i < 2; setImmediate(() => console.log(i)), i++) { + // // loop body + // } + // + // Into the following ES5 syntax: + // + // var _loop_1 = function (i) { + // if (inc_1) + // setImmediate(() => console.log(i)), i++; + // else + // inc_1 = true; + // if (!(setImmediate(() => console.log(i)), i < 2)) + // return out_i_1 = i, "break"; + // // loop body + // out_i_1 = i; + // } + // var out_i_1, inc_1 = false; + // for (var i = 0;;) { + // var state_1 = _loop_1(i); + // i = out_i_1; + // if (state_1 === "break") + // break; + // } + // + // Which prevents mutations to `i` in the per-iteration environment of the body + // from affecting the value of `i` in the previous per-iteration environment. + // + // Note that the incrementor of a `for` loop is evaluated in a *new* per-iteration + // environment that is carried over to the next iteration of the loop. As a result, + // we must indicate whether this is the first evaluation of the loop body so that + // we only evaluate the incrementor on subsequent evaluations. + currentState.conditionVariable = ts.createUniqueName("inc"); + statements.push(ts.createIf(currentState.conditionVariable, ts.createStatement(ts.visitNode(node.incrementor, visitor, ts.isExpression)), ts.createStatement(ts.createAssignment(currentState.conditionVariable, ts.createTrue())))); + if (shouldConvertConditionOfForStatement(node)) { + statements.push(ts.createIf(ts.createPrefix(52 /* ExclamationToken */, ts.visitNode(node.condition, visitor, ts.isExpression)), ts.visitNode(ts.createBreak(), visitor, ts.isStatement))); + } + } + if (ts.isBlock(statement)) { + ts.addRange(statements, statement.statements); + } + else { + statements.push(statement); + } + copyOutParameters(currentState.loopOutParameters, 1 /* Body */, 1 /* ToOutParameter */, statements); + ts.addStatementsAfterPrologue(statements, lexicalEnvironment); + var loopBody = ts.createBlock(statements, /*multiLine*/ true); + if (ts.isBlock(statement)) + ts.setOriginalNode(loopBody, statement); + var containsYield = (node.statement.transformFlags & 4194304 /* ContainsYield */) !== 0; + var emitFlags = 0; + if (currentState.containsLexicalThis) + emitFlags |= 8 /* CapturesThis */; + if (containsYield && (hierarchyFacts & 4 /* AsyncFunctionBody */) !== 0) + emitFlags |= 262144 /* AsyncFunctionBody */; + // This transforms the following ES2015 syntax (in addition to other variations): + // + // for (let i = 0; i < 2; i++) { + // setImmediate(() => console.log(i)); + // } + // + // Into the following ES5 syntax: + // + // var _loop_1 = function (i) { + // setImmediate(() => console.log(i)); + // }; + // for (var i = 0; i < 2; i++) { + // _loop_1(i); + // } + var functionDeclaration = ts.createVariableStatement( + /*modifiers*/ undefined, ts.setEmitFlags(ts.createVariableDeclarationList([ + ts.createVariableDeclaration(functionName, + /*type*/ undefined, ts.setEmitFlags(ts.createFunctionExpression( + /*modifiers*/ undefined, containsYield ? ts.createToken(40 /* AsteriskToken */) : undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, currentState.loopParameters, + /*type*/ undefined, loopBody), emitFlags)) + ]), 2097152 /* NoHoisting */)); + var part = generateCallToConvertedLoop(functionName, currentState, outerState, containsYield); + return { functionName: functionName, containsYield: containsYield, functionDeclaration: functionDeclaration, part: part }; + } + function copyOutParameter(outParam, copyDirection) { + var source = copyDirection === 0 /* ToOriginal */ ? outParam.outParamName : outParam.originalName; + var target = copyDirection === 0 /* ToOriginal */ ? outParam.originalName : outParam.outParamName; + return ts.createBinary(target, 59 /* EqualsToken */, source); + } + function copyOutParameters(outParams, partFlags, copyDirection, statements) { + for (var _i = 0, outParams_1 = outParams; _i < outParams_1.length; _i++) { + var outParam = outParams_1[_i]; + if (outParam.flags & partFlags) { + statements.push(ts.createExpressionStatement(copyOutParameter(outParam, copyDirection))); + } + } + } + function generateCallToConvertedLoopInitializer(initFunctionExpressionName, containsYield) { + var call = ts.createCall(initFunctionExpressionName, /*typeArguments*/ undefined, []); + var callResult = containsYield + ? ts.createYield(ts.createToken(40 /* AsteriskToken */), ts.setEmitFlags(call, 8388608 /* Iterator */)) + : call; + return ts.createStatement(callResult); + } + function generateCallToConvertedLoop(loopFunctionExpressionName, state, outerState, containsYield) { + var statements = []; + // loop is considered simple if it does not have any return statements or break\continue that transfer control outside of the loop + // simple loops are emitted as just 'loop()'; + // NOTE: if loop uses only 'continue' it still will be emitted as simple loop + var isSimpleLoop = !(state.nonLocalJumps & ~4 /* Continue */) && + !state.labeledNonLocalBreaks && + !state.labeledNonLocalContinues; + var call = ts.createCall(loopFunctionExpressionName, /*typeArguments*/ undefined, ts.map(state.loopParameters, function (p) { return p.name; })); + var callResult = containsYield + ? ts.createYield(ts.createToken(40 /* AsteriskToken */), ts.setEmitFlags(call, 8388608 /* Iterator */)) + : call; + if (isSimpleLoop) { + statements.push(ts.createExpressionStatement(callResult)); + copyOutParameters(state.loopOutParameters, 1 /* Body */, 0 /* ToOriginal */, statements); + } + else { + var loopResultName = ts.createUniqueName("state"); + var stateVariable = ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(loopResultName, /*type*/ undefined, callResult)])); + statements.push(stateVariable); + copyOutParameters(state.loopOutParameters, 1 /* Body */, 0 /* ToOriginal */, statements); + if (state.nonLocalJumps & 8 /* Return */) { + var returnStatement = void 0; + if (outerState) { + outerState.nonLocalJumps |= 8 /* Return */; + returnStatement = ts.createReturn(loopResultName); + } + else { + returnStatement = ts.createReturn(ts.createPropertyAccess(loopResultName, "value")); + } + statements.push(ts.createIf(ts.createBinary(ts.createTypeOf(loopResultName), 35 /* EqualsEqualsEqualsToken */, ts.createLiteral("object")), returnStatement)); + } + if (state.nonLocalJumps & 2 /* Break */) { + statements.push(ts.createIf(ts.createBinary(loopResultName, 35 /* EqualsEqualsEqualsToken */, ts.createLiteral("break")), ts.createBreak())); + } + if (state.labeledNonLocalBreaks || state.labeledNonLocalContinues) { + var caseClauses = []; + processLabeledJumps(state.labeledNonLocalBreaks, /*isBreak*/ true, loopResultName, outerState, caseClauses); + processLabeledJumps(state.labeledNonLocalContinues, /*isBreak*/ false, loopResultName, outerState, caseClauses); + statements.push(ts.createSwitch(loopResultName, ts.createCaseBlock(caseClauses))); + } + } + return statements; + } + function setLabeledJump(state, isBreak, labelText, labelMarker) { + if (isBreak) { + if (!state.labeledNonLocalBreaks) { + state.labeledNonLocalBreaks = ts.createMap(); + } + state.labeledNonLocalBreaks.set(labelText, labelMarker); + } + else { + if (!state.labeledNonLocalContinues) { + state.labeledNonLocalContinues = ts.createMap(); + } + state.labeledNonLocalContinues.set(labelText, labelMarker); + } + } + function processLabeledJumps(table, isBreak, loopResultName, outerLoop, caseClauses) { + if (!table) { + return; + } + table.forEach(function (labelMarker, labelText) { + var statements = []; + // if there are no outer converted loop or outer label in question is located inside outer converted loop + // then emit labeled break\continue + // otherwise propagate pair 'label -> marker' to outer converted loop and emit 'return labelMarker' so outer loop can later decide what to do + if (!outerLoop || (outerLoop.labels && outerLoop.labels.get(labelText))) { + var label = ts.createIdentifier(labelText); + statements.push(isBreak ? ts.createBreak(label) : ts.createContinue(label)); + } + else { + setLabeledJump(outerLoop, isBreak, labelText, labelMarker); + statements.push(ts.createReturn(loopResultName)); + } + caseClauses.push(ts.createCaseClause(ts.createLiteral(labelMarker), statements)); + }); + } + function processLoopVariableDeclaration(container, decl, loopParameters, loopOutParameters, hasCapturedBindingsInForInitializer) { + var name = decl.name; + if (ts.isBindingPattern(name)) { + for (var _i = 0, _a = name.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (!ts.isOmittedExpression(element)) { + processLoopVariableDeclaration(container, element, loopParameters, loopOutParameters, hasCapturedBindingsInForInitializer); + } + } + } + else { + loopParameters.push(ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, name)); + var checkFlags = resolver.getNodeCheckFlags(decl); + if (checkFlags & 4194304 /* NeedsLoopOutParameter */ || hasCapturedBindingsInForInitializer) { + var outParamName = ts.createUniqueName("out_" + ts.idText(name)); + var flags = 0; + if (checkFlags & 4194304 /* NeedsLoopOutParameter */) { + flags |= 1 /* Body */; + } + if (ts.isForStatement(container) && container.initializer && resolver.isBindingCapturedByNode(container.initializer, decl)) { + flags |= 2 /* Initializer */; + } + loopOutParameters.push({ flags: flags, originalName: name, outParamName: outParamName }); + } + } + } + /** + * Adds the members of an object literal to an array of expressions. + * + * @param expressions An array of expressions. + * @param node An ObjectLiteralExpression node. + * @param receiver The receiver for members of the ObjectLiteralExpression. + * @param numInitialNonComputedProperties The number of initial properties without + * computed property names. + */ + function addObjectLiteralMembers(expressions, node, receiver, start) { + var properties = node.properties; + var numProperties = properties.length; + for (var i = start; i < numProperties; i++) { + var property = properties[i]; + switch (property.kind) { + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + var accessors = ts.getAllAccessorDeclarations(node.properties, property); + if (property === accessors.firstAccessor) { + expressions.push(transformAccessorsToExpression(receiver, accessors, node, !!node.multiLine)); + } + break; + case 156 /* MethodDeclaration */: + expressions.push(transformObjectLiteralMethodDeclarationToExpression(property, receiver, node, node.multiLine)); + break; + case 275 /* PropertyAssignment */: + expressions.push(transformPropertyAssignmentToExpression(property, receiver, node.multiLine)); + break; + case 276 /* ShorthandPropertyAssignment */: + expressions.push(transformShorthandPropertyAssignmentToExpression(property, receiver, node.multiLine)); + break; + default: + ts.Debug.failBadSyntaxKind(node); + break; + } + } + } + /** + * Transforms a PropertyAssignment node into an expression. + * + * @param node The ObjectLiteralExpression that contains the PropertyAssignment. + * @param property The PropertyAssignment node. + * @param receiver The receiver for the assignment. + */ + function transformPropertyAssignmentToExpression(property, receiver, startsOnNewLine) { + var expression = ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(property.name, visitor, ts.isPropertyName)), ts.visitNode(property.initializer, visitor, ts.isExpression)); + ts.setTextRange(expression, property); + if (startsOnNewLine) { + ts.startOnNewLine(expression); + } + return expression; + } + /** + * Transforms a ShorthandPropertyAssignment node into an expression. + * + * @param node The ObjectLiteralExpression that contains the ShorthandPropertyAssignment. + * @param property The ShorthandPropertyAssignment node. + * @param receiver The receiver for the assignment. + */ + function transformShorthandPropertyAssignmentToExpression(property, receiver, startsOnNewLine) { + var expression = ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(property.name, visitor, ts.isPropertyName)), ts.getSynthesizedClone(property.name)); + ts.setTextRange(expression, property); + if (startsOnNewLine) { + ts.startOnNewLine(expression); + } + return expression; + } + /** + * Transforms a MethodDeclaration of an ObjectLiteralExpression into an expression. + * + * @param node The ObjectLiteralExpression that contains the MethodDeclaration. + * @param method The MethodDeclaration node. + * @param receiver The receiver for the assignment. + */ + function transformObjectLiteralMethodDeclarationToExpression(method, receiver, container, startsOnNewLine) { + var ancestorFacts = enterSubtree(0 /* None */, 0 /* None */); + var expression = ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(method.name, visitor, ts.isPropertyName)), transformFunctionLikeToExpression(method, /*location*/ method, /*name*/ undefined, container)); + ts.setTextRange(expression, method); + if (startsOnNewLine) { + ts.startOnNewLine(expression); + } + exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, hierarchyFacts & 49152 /* PropagateNewTargetMask */ ? 16384 /* NewTarget */ : 0 /* None */); + return expression; + } + function visitCatchClause(node) { + var ancestorFacts = enterSubtree(4032 /* BlockScopeExcludes */, 0 /* BlockScopeIncludes */); + var updated; + ts.Debug.assert(!!node.variableDeclaration, "Catch clause variable should always be present when downleveling ES2015."); + if (ts.isBindingPattern(node.variableDeclaration.name)) { + var temp = ts.createTempVariable(/*recordTempVariable*/ undefined); + var newVariableDeclaration = ts.createVariableDeclaration(temp); + ts.setTextRange(newVariableDeclaration, node.variableDeclaration); + var vars = ts.flattenDestructuringBinding(node.variableDeclaration, visitor, context, 0 /* All */, temp); + var list = ts.createVariableDeclarationList(vars); + ts.setTextRange(list, node.variableDeclaration); + var destructure = ts.createVariableStatement(/*modifiers*/ undefined, list); + updated = ts.updateCatchClause(node, newVariableDeclaration, addStatementToStartOfBlock(node.block, destructure)); + } + else { + updated = ts.visitEachChild(node, visitor, context); + } + exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */); + return updated; + } + function addStatementToStartOfBlock(block, statement) { + var transformedStatements = ts.visitNodes(block.statements, visitor, ts.isStatement); + return ts.updateBlock(block, [statement].concat(transformedStatements)); + } + /** + * Visits a MethodDeclaration of an ObjectLiteralExpression and transforms it into a + * PropertyAssignment. + * + * @param node A MethodDeclaration node. + */ + function visitMethodDeclaration(node) { + // We should only get here for methods on an object literal with regular identifier names. + // Methods on classes are handled in visitClassDeclaration/visitClassExpression. + // Methods with computed property names are handled in visitObjectLiteralExpression. + ts.Debug.assert(!ts.isComputedPropertyName(node.name)); + var functionExpression = transformFunctionLikeToExpression(node, /*location*/ ts.moveRangePos(node, -1), /*name*/ undefined, /*container*/ undefined); + ts.setEmitFlags(functionExpression, 512 /* NoLeadingComments */ | ts.getEmitFlags(functionExpression)); + return ts.setTextRange(ts.createPropertyAssignment(node.name, functionExpression), + /*location*/ node); + } + /** + * Visits an AccessorDeclaration of an ObjectLiteralExpression. + * + * @param node An AccessorDeclaration node. + */ + function visitAccessorDeclaration(node) { + ts.Debug.assert(!ts.isComputedPropertyName(node.name)); + var savedConvertedLoopState = convertedLoopState; + convertedLoopState = undefined; + var ancestorFacts = enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */); + var updated; + var parameters = ts.visitParameterList(node.parameters, visitor, context); + var body = node.transformFlags & (16384 /* ContainsCapturedLexicalThis */ | 128 /* ContainsES2015 */) + ? transformFunctionBody(node) + : visitFunctionBodyDownLevel(node); + if (node.kind === 158 /* GetAccessor */) { + updated = ts.updateGetAccessor(node, node.decorators, node.modifiers, node.name, parameters, node.type, body); + } + else { + updated = ts.updateSetAccessor(node, node.decorators, node.modifiers, node.name, parameters, body); + } + exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, 0 /* None */); + convertedLoopState = savedConvertedLoopState; + return updated; + } + /** + * Visits a ShorthandPropertyAssignment and transforms it into a PropertyAssignment. + * + * @param node A ShorthandPropertyAssignment node. + */ + function visitShorthandPropertyAssignment(node) { + return ts.setTextRange(ts.createPropertyAssignment(node.name, ts.getSynthesizedClone(node.name)), + /*location*/ node); + } + function visitComputedPropertyName(node) { + var ancestorFacts = enterSubtree(0 /* ComputedPropertyNameExcludes */, 8192 /* ComputedPropertyNameIncludes */); + var updated = ts.visitEachChild(node, visitor, context); + exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, hierarchyFacts & 49152 /* PropagateNewTargetMask */ ? 32768 /* NewTargetInComputedPropertyName */ : 0 /* None */); + return updated; + } + /** + * Visits a YieldExpression node. + * + * @param node A YieldExpression node. + */ + function visitYieldExpression(node) { + // `yield` expressions are transformed using the generators transformer. + return ts.visitEachChild(node, visitor, context); + } + /** + * Visits an ArrayLiteralExpression that contains a spread element. + * + * @param node An ArrayLiteralExpression node. + */ + function visitArrayLiteralExpression(node) { + if (node.transformFlags & 64 /* ES2015 */) { + // We are here because we contain a SpreadElementExpression. + return transformAndSpreadElements(node.elements, /*needsUniqueCopy*/ true, !!node.multiLine, /*hasTrailingComma*/ !!node.elements.hasTrailingComma); + } + return ts.visitEachChild(node, visitor, context); + } + /** + * Visits a CallExpression that contains either a spread element or `super`. + * + * @param node a CallExpression. + */ + function visitCallExpression(node) { + if (ts.getEmitFlags(node) & 33554432 /* TypeScriptClassWrapper */) { + return visitTypeScriptClassWrapper(node); + } + if (node.transformFlags & 64 /* ES2015 */) { + return visitCallExpressionWithPotentialCapturedThisAssignment(node, /*assignToCapturedThis*/ true); + } + return ts.updateCall(node, ts.visitNode(node.expression, callExpressionVisitor, ts.isExpression), + /*typeArguments*/ undefined, ts.visitNodes(node.arguments, visitor, ts.isExpression)); + } + function visitTypeScriptClassWrapper(node) { + // This is a call to a class wrapper function (an IIFE) created by the 'ts' transformer. + // The wrapper has a form similar to: + // + // (function() { + // class C { // 1 + // } + // C.x = 1; // 2 + // return C; + // }()) + // + // When we transform the class, we end up with something like this: + // + // (function () { + // var C = (function () { // 3 + // function C() { + // } + // return C; // 4 + // }()); + // C.x = 1; + // return C; + // }()) + // + // We want to simplify the two nested IIFEs to end up with something like this: + // + // (function () { + // function C() { + // } + // C.x = 1; + // return C; + // }()) + // We skip any outer expressions in a number of places to get to the innermost + // expression, but we will restore them later to preserve comments and source maps. + var body = ts.cast(ts.cast(ts.skipOuterExpressions(node.expression), ts.isArrowFunction).body, ts.isBlock); + // The class statements are the statements generated by visiting the first statement with initializer of the + // body (1), while all other statements are added to remainingStatements (2) + var isVariableStatementWithInitializer = function (stmt) { return ts.isVariableStatement(stmt) && !!ts.first(stmt.declarationList.declarations).initializer; }; + var bodyStatements = ts.visitNodes(body.statements, visitor, ts.isStatement); + var classStatements = ts.filter(bodyStatements, isVariableStatementWithInitializer); + var remainingStatements = ts.filter(bodyStatements, function (stmt) { return !isVariableStatementWithInitializer(stmt); }); + var varStatement = ts.cast(ts.first(classStatements), ts.isVariableStatement); + // We know there is only one variable declaration here as we verified this in an + // earlier call to isTypeScriptClassWrapper + var variable = varStatement.declarationList.declarations[0]; + var initializer = ts.skipOuterExpressions(variable.initializer); + // Under certain conditions, the 'ts' transformer may introduce a class alias, which + // we see as an assignment, for example: + // + // (function () { + // var C_1; + // var C = C_1 = (function () { + // function C() { + // } + // C.x = function () { return C_1; } + // return C; + // }()); + // C = C_1 = __decorate([dec], C); + // return C; + // }()) + // + var aliasAssignment = ts.tryCast(initializer, ts.isAssignmentExpression); + // The underlying call (3) is another IIFE that may contain a '_super' argument. + var call = ts.cast(aliasAssignment ? ts.skipOuterExpressions(aliasAssignment.right) : initializer, ts.isCallExpression); + var func = ts.cast(ts.skipOuterExpressions(call.expression), ts.isFunctionExpression); + var funcStatements = func.body.statements; + var classBodyStart = 0; + var classBodyEnd = -1; + var statements = []; + if (aliasAssignment) { + // If we have a class alias assignment, we need to move it to the down-level constructor + // function we generated for the class. + var extendsCall = ts.tryCast(funcStatements[classBodyStart], ts.isExpressionStatement); + if (extendsCall) { + statements.push(extendsCall); + classBodyStart++; + } + // The next statement is the function declaration. + statements.push(funcStatements[classBodyStart]); + classBodyStart++; + // Add the class alias following the declaration. + statements.push(ts.createExpressionStatement(ts.createAssignment(aliasAssignment.left, ts.cast(variable.name, ts.isIdentifier)))); + } + // Find the trailing 'return' statement (4) + while (!ts.isReturnStatement(ts.elementAt(funcStatements, classBodyEnd))) { + classBodyEnd--; + } + // When we extract the statements of the inner IIFE, we exclude the 'return' statement (4) + // as we already have one that has been introduced by the 'ts' transformer. + ts.addRange(statements, funcStatements, classBodyStart, classBodyEnd); + if (classBodyEnd < -1) { + // If there were any hoisted declarations following the return statement, we should + // append them. + ts.addRange(statements, funcStatements, classBodyEnd + 1); + } + // Add the remaining statements of the outer wrapper. + ts.addRange(statements, remainingStatements); + // The 'es2015' class transform may add an end-of-declaration marker. If so we will add it + // after the remaining statements from the 'ts' transformer. + ts.addRange(statements, classStatements, /*start*/ 1); + // Recreate any outer parentheses or partially-emitted expressions to preserve source map + // and comment locations. + return ts.recreateOuterExpressions(node.expression, ts.recreateOuterExpressions(variable.initializer, ts.recreateOuterExpressions(aliasAssignment && aliasAssignment.right, ts.updateCall(call, ts.recreateOuterExpressions(call.expression, ts.updateFunctionExpression(func, + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, func.parameters, + /*type*/ undefined, ts.updateBlock(func.body, statements))), + /*typeArguments*/ undefined, call.arguments)))); + } + function visitImmediateSuperCallInBody(node) { + return visitCallExpressionWithPotentialCapturedThisAssignment(node, /*assignToCapturedThis*/ false); + } + function visitCallExpressionWithPotentialCapturedThisAssignment(node, assignToCapturedThis) { + // We are here either because SuperKeyword was used somewhere in the expression, or + // because we contain a SpreadElementExpression. + if (node.transformFlags & 131072 /* ContainsRestOrSpread */ || + node.expression.kind === 98 /* SuperKeyword */ || + ts.isSuperProperty(ts.skipOuterExpressions(node.expression))) { + var _a = ts.createCallBinding(node.expression, hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg; + if (node.expression.kind === 98 /* SuperKeyword */) { + ts.setEmitFlags(thisArg, 4 /* NoSubstitution */); + } + var resultingCall = void 0; + if (node.transformFlags & 131072 /* ContainsRestOrSpread */) { + // [source] + // f(...a, b) + // x.m(...a, b) + // super(...a, b) + // super.m(...a, b) // in static + // super.m(...a, b) // in instance + // + // [output] + // f.apply(void 0, a.concat([b])) + // (_a = x).m.apply(_a, a.concat([b])) + // _super.apply(this, a.concat([b])) + // _super.m.apply(this, a.concat([b])) + // _super.prototype.m.apply(this, a.concat([b])) + resultingCall = ts.createFunctionApply(ts.visitNode(target, callExpressionVisitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), transformAndSpreadElements(node.arguments, /*needsUniqueCopy*/ false, /*multiLine*/ false, /*hasTrailingComma*/ false)); + } + else { + // [source] + // super(a) + // super.m(a) // in static + // super.m(a) // in instance + // + // [output] + // _super.call(this, a) + // _super.m.call(this, a) + // _super.prototype.m.call(this, a) + resultingCall = ts.createFunctionCall(ts.visitNode(target, callExpressionVisitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), ts.visitNodes(node.arguments, visitor, ts.isExpression), + /*location*/ node); + } + if (node.expression.kind === 98 /* SuperKeyword */) { + var actualThis = ts.createThis(); + ts.setEmitFlags(actualThis, 4 /* NoSubstitution */); + var initializer = ts.createLogicalOr(resultingCall, actualThis); + resultingCall = assignToCapturedThis + ? ts.createAssignment(ts.createFileLevelUniqueName("_this"), initializer) + : initializer; + } + return ts.setOriginalNode(resultingCall, node); + } + return ts.visitEachChild(node, visitor, context); + } + /** + * Visits a NewExpression that contains a spread element. + * + * @param node A NewExpression node. + */ + function visitNewExpression(node) { + if (node.transformFlags & 131072 /* ContainsRestOrSpread */) { + // We are here because we contain a SpreadElementExpression. + // [source] + // new C(...a) + // + // [output] + // new ((_a = C).bind.apply(_a, [void 0].concat(a)))() + var _a = ts.createCallBinding(ts.createPropertyAccess(node.expression, "bind"), hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg; + return ts.createNew(ts.createFunctionApply(ts.visitNode(target, visitor, ts.isExpression), thisArg, transformAndSpreadElements(ts.createNodeArray([ts.createVoidZero()].concat(node.arguments)), /*needsUniqueCopy*/ false, /*multiLine*/ false, /*hasTrailingComma*/ false)), + /*typeArguments*/ undefined, []); + } + return ts.visitEachChild(node, visitor, context); + } + /** + * Transforms an array of Expression nodes that contains a SpreadExpression. + * + * @param elements The array of Expression nodes. + * @param needsUniqueCopy A value indicating whether to ensure that the result is a fresh array. + * @param multiLine A value indicating whether the result should be emitted on multiple lines. + */ + function transformAndSpreadElements(elements, needsUniqueCopy, multiLine, hasTrailingComma) { + // [source] + // [a, ...b, c] + // + // [output] + // [a].concat(b, [c]) + // Map spans of spread expressions into their expressions and spans of other + // expressions into an array literal. + var numElements = elements.length; + var segments = ts.flatten(ts.spanMap(elements, partitionSpread, function (partition, visitPartition, _start, end) { + return visitPartition(partition, multiLine, hasTrailingComma && end === numElements); + })); + if (compilerOptions.downlevelIteration) { + if (segments.length === 1) { + var firstSegment = segments[0]; + if (ts.isCallExpression(firstSegment) + && ts.isIdentifier(firstSegment.expression) + && (ts.getEmitFlags(firstSegment.expression) & 4096 /* HelperName */) + && firstSegment.expression.escapedText === "___spread") { + return segments[0]; + } + } + return ts.createSpreadHelper(context, segments); + } + else { + if (segments.length === 1) { + var firstElement = elements[0]; + return needsUniqueCopy && ts.isSpreadElement(firstElement) && firstElement.expression.kind !== 187 /* ArrayLiteralExpression */ + ? ts.createArraySlice(segments[0]) + : segments[0]; + } + // Rewrite using the pattern .concat(, , ...) + return ts.createArrayConcat(segments.shift(), segments); + } + } + function partitionSpread(node) { + return ts.isSpreadElement(node) + ? visitSpanOfSpreads + : visitSpanOfNonSpreads; + } + function visitSpanOfSpreads(chunk) { + return ts.map(chunk, visitExpressionOfSpread); + } + function visitSpanOfNonSpreads(chunk, multiLine, hasTrailingComma) { + return ts.createArrayLiteral(ts.visitNodes(ts.createNodeArray(chunk, hasTrailingComma), visitor, ts.isExpression), multiLine); + } + function visitSpreadElement(node) { + return ts.visitNode(node.expression, visitor, ts.isExpression); + } + /** + * Transforms the expression of a SpreadExpression node. + * + * @param node A SpreadExpression node. + */ + function visitExpressionOfSpread(node) { + return ts.visitNode(node.expression, visitor, ts.isExpression); + } + /** + * Visits a template literal. + * + * @param node A template literal. + */ + function visitTemplateLiteral(node) { + return ts.setTextRange(ts.createLiteral(node.text), node); + } + /** + * Visits a string literal with an extended unicode escape. + * + * @param node A string literal. + */ + function visitStringLiteral(node) { + if (node.hasExtendedUnicodeEscape) { + return ts.setTextRange(ts.createLiteral(node.text), node); + } + return node; + } + /** + * Visits a binary or octal (ES6) numeric literal. + * + * @param node A string literal. + */ + function visitNumericLiteral(node) { + if (node.numericLiteralFlags & 384 /* BinaryOrOctalSpecifier */) { + return ts.setTextRange(ts.createNumericLiteral(node.text), node); + } + return node; + } + /** + * Visits a TaggedTemplateExpression node. + * + * @param node A TaggedTemplateExpression node. + */ + function visitTaggedTemplateExpression(node) { + // Visit the tag expression + var tag = ts.visitNode(node.tag, visitor, ts.isExpression); + // Build up the template arguments and the raw and cooked strings for the template. + // We start out with 'undefined' for the first argument and revisit later + // to avoid walking over the template string twice and shifting all our arguments over after the fact. + var templateArguments = [undefined]; + var cookedStrings = []; + var rawStrings = []; + var template = node.template; + if (ts.isNoSubstitutionTemplateLiteral(template)) { + cookedStrings.push(ts.createLiteral(template.text)); + rawStrings.push(getRawLiteral(template)); + } + else { + cookedStrings.push(ts.createLiteral(template.head.text)); + rawStrings.push(getRawLiteral(template.head)); + for (var _i = 0, _a = template.templateSpans; _i < _a.length; _i++) { + var templateSpan = _a[_i]; + cookedStrings.push(ts.createLiteral(templateSpan.literal.text)); + rawStrings.push(getRawLiteral(templateSpan.literal)); + templateArguments.push(ts.visitNode(templateSpan.expression, visitor, ts.isExpression)); + } + } + var helperCall = createTemplateObjectHelper(context, ts.createArrayLiteral(cookedStrings), ts.createArrayLiteral(rawStrings)); + // Create a variable to cache the template object if we're in a module. + // Do not do this in the global scope, as any variable we currently generate could conflict with + // variables from outside of the current compilation. In the future, we can revisit this behavior. + if (ts.isExternalModule(currentSourceFile)) { + var tempVar = ts.createUniqueName("templateObject"); + recordTaggedTemplateString(tempVar); + templateArguments[0] = ts.createLogicalOr(tempVar, ts.createAssignment(tempVar, helperCall)); + } + else { + templateArguments[0] = helperCall; + } + return ts.createCall(tag, /*typeArguments*/ undefined, templateArguments); + } + /** + * Creates an ES5 compatible literal from an ES6 template literal. + * + * @param node The ES6 template literal. + */ + function getRawLiteral(node) { + // Find original source text, since we need to emit the raw strings of the tagged template. + // The raw strings contain the (escaped) strings of what the user wrote. + // Examples: `\n` is converted to "\\n", a template string with a newline to "\n". + var text = ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node); + // text contains the original source, it will also contain quotes ("`"), dolar signs and braces ("${" and "}"), + // thus we need to remove those characters. + // First template piece starts with "`", others with "}" + // Last template piece ends with "`", others with "${" + var isLast = node.kind === 14 /* NoSubstitutionTemplateLiteral */ || node.kind === 17 /* TemplateTail */; + text = text.substring(1, text.length - (isLast ? 1 : 2)); + // Newline normalization: + // ES6 Spec 11.8.6.1 - Static Semantics of TV's and TRV's + // and LineTerminatorSequences are normalized to for both TV and TRV. + text = text.replace(/\r\n?/g, "\n"); + return ts.setTextRange(ts.createLiteral(text), node); + } + /** + * Visits a TemplateExpression node. + * + * @param node A TemplateExpression node. + */ + function visitTemplateExpression(node) { + var expressions = []; + addTemplateHead(expressions, node); + addTemplateSpans(expressions, node); + // createAdd will check if each expression binds less closely than binary '+'. + // If it does, it wraps the expression in parentheses. Otherwise, something like + // `abc${ 1 << 2 }` + // becomes + // "abc" + 1 << 2 + "" + // which is really + // ("abc" + 1) << (2 + "") + // rather than + // "abc" + (1 << 2) + "" + var expression = ts.reduceLeft(expressions, ts.createAdd); + if (ts.nodeIsSynthesized(expression)) { + expression.pos = node.pos; + expression.end = node.end; + } + return expression; + } + /** + * Gets a value indicating whether we need to include the head of a TemplateExpression. + * + * @param node A TemplateExpression node. + */ + function shouldAddTemplateHead(node) { + // If this expression has an empty head literal and the first template span has a non-empty + // literal, then emitting the empty head literal is not necessary. + // `${ foo } and ${ bar }` + // can be emitted as + // foo + " and " + bar + // This is because it is only required that one of the first two operands in the emit + // output must be a string literal, so that the other operand and all following operands + // are forced into strings. + // + // If the first template span has an empty literal, then the head must still be emitted. + // `${ foo }${ bar }` + // must still be emitted as + // "" + foo + bar + // There is always atleast one templateSpan in this code path, since + // NoSubstitutionTemplateLiterals are directly emitted via emitLiteral() + ts.Debug.assert(node.templateSpans.length !== 0); + return node.head.text.length !== 0 || node.templateSpans[0].literal.text.length === 0; + } + /** + * Adds the head of a TemplateExpression to an array of expressions. + * + * @param expressions An array of expressions. + * @param node A TemplateExpression node. + */ + function addTemplateHead(expressions, node) { + if (!shouldAddTemplateHead(node)) { + return; + } + expressions.push(ts.createLiteral(node.head.text)); + } + /** + * Visits and adds the template spans of a TemplateExpression to an array of expressions. + * + * @param expressions An array of expressions. + * @param node A TemplateExpression node. + */ + function addTemplateSpans(expressions, node) { + for (var _i = 0, _a = node.templateSpans; _i < _a.length; _i++) { + var span = _a[_i]; + expressions.push(ts.visitNode(span.expression, visitor, ts.isExpression)); + // Only emit if the literal is non-empty. + // The binary '+' operator is left-associative, so the first string concatenation + // with the head will force the result up to this point to be a string. + // Emitting a '+ ""' has no semantic effect for middles and tails. + if (span.literal.text.length !== 0) { + expressions.push(ts.createLiteral(span.literal.text)); + } + } + } + /** + * Visits the `super` keyword + */ + function visitSuperKeyword(isExpressionOfCall) { + return hierarchyFacts & 8 /* NonStaticClassElement */ + && !isExpressionOfCall + ? ts.createPropertyAccess(ts.createFileLevelUniqueName("_super"), "prototype") + : ts.createFileLevelUniqueName("_super"); + } + function visitMetaProperty(node) { + if (node.keywordToken === 95 /* NewKeyword */ && node.name.escapedText === "target") { + if (hierarchyFacts & 8192 /* ComputedPropertyName */) { + hierarchyFacts |= 32768 /* NewTargetInComputedPropertyName */; + } + else { + hierarchyFacts |= 16384 /* NewTarget */; + } + return ts.createFileLevelUniqueName("_newTarget"); + } + return node; + } + /** + * Called by the printer just before a node is printed. + * + * @param hint A hint as to the intended usage of the node. + * @param node The node to be printed. + * @param emitCallback The callback used to emit the node. + */ + function onEmitNode(hint, node, emitCallback) { + if (enabledSubstitutions & 1 /* CapturedThis */ && ts.isFunctionLike(node)) { + // If we are tracking a captured `this`, keep track of the enclosing function. + var ancestorFacts = enterSubtree(16286 /* FunctionExcludes */, ts.getEmitFlags(node) & 8 /* CapturesThis */ + ? 65 /* FunctionIncludes */ | 16 /* CapturesThis */ + : 65 /* FunctionIncludes */); + previousOnEmitNode(hint, node, emitCallback); + exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */); + return; + } + previousOnEmitNode(hint, node, emitCallback); + } + /** + * Enables a more costly code path for substitutions when we determine a source file + * contains block-scoped bindings (e.g. `let` or `const`). + */ + function enableSubstitutionsForBlockScopedBindings() { + if ((enabledSubstitutions & 2 /* BlockScopedBindings */) === 0) { + enabledSubstitutions |= 2 /* BlockScopedBindings */; + context.enableSubstitution(72 /* Identifier */); + } + } + /** + * Enables a more costly code path for substitutions when we determine a source file + * contains a captured `this`. + */ + function enableSubstitutionsForCapturedThis() { + if ((enabledSubstitutions & 1 /* CapturedThis */) === 0) { + enabledSubstitutions |= 1 /* CapturedThis */; + context.enableSubstitution(100 /* ThisKeyword */); + context.enableEmitNotification(157 /* Constructor */); + context.enableEmitNotification(156 /* MethodDeclaration */); + context.enableEmitNotification(158 /* GetAccessor */); + context.enableEmitNotification(159 /* SetAccessor */); + context.enableEmitNotification(197 /* ArrowFunction */); + context.enableEmitNotification(196 /* FunctionExpression */); + context.enableEmitNotification(239 /* FunctionDeclaration */); + } + } + /** + * Hooks node substitutions. + * + * @param hint The context for the emitter. + * @param node The node to substitute. + */ + function onSubstituteNode(hint, node) { + node = previousOnSubstituteNode(hint, node); + if (hint === 1 /* Expression */) { + return substituteExpression(node); + } + if (ts.isIdentifier(node)) { + return substituteIdentifier(node); + } + return node; + } + /** + * Hooks substitutions for non-expression identifiers. + */ + function substituteIdentifier(node) { + // Only substitute the identifier if we have enabled substitutions for block-scoped + // bindings. + if (enabledSubstitutions & 2 /* BlockScopedBindings */ && !ts.isInternalName(node)) { + var original = ts.getParseTreeNode(node, ts.isIdentifier); + if (original && isNameOfDeclarationWithCollidingName(original)) { + return ts.setTextRange(ts.getGeneratedNameForNode(original), node); + } + } + return node; + } + /** + * Determines whether a name is the name of a declaration with a colliding name. + * NOTE: This function expects to be called with an original source tree node. + * + * @param node An original source tree node. + */ + function isNameOfDeclarationWithCollidingName(node) { + switch (node.parent.kind) { + case 186 /* BindingElement */: + case 240 /* ClassDeclaration */: + case 243 /* EnumDeclaration */: + case 237 /* VariableDeclaration */: + return node.parent.name === node + && resolver.isDeclarationWithCollidingName(node.parent); + } + return false; + } + /** + * Substitutes an expression. + * + * @param node An Expression node. + */ + function substituteExpression(node) { + switch (node.kind) { + case 72 /* Identifier */: + return substituteExpressionIdentifier(node); + case 100 /* ThisKeyword */: + return substituteThisKeyword(node); + } + return node; + } + /** + * Substitutes an expression identifier. + * + * @param node An Identifier node. + */ + function substituteExpressionIdentifier(node) { + if (enabledSubstitutions & 2 /* BlockScopedBindings */ && !ts.isInternalName(node)) { + var declaration = resolver.getReferencedDeclarationWithCollidingName(node); + if (declaration && !(ts.isClassLike(declaration) && isPartOfClassBody(declaration, node))) { + return ts.setTextRange(ts.getGeneratedNameForNode(ts.getNameOfDeclaration(declaration)), node); + } + } + return node; + } + function isPartOfClassBody(declaration, node) { + var currentNode = ts.getParseTreeNode(node); + if (!currentNode || currentNode === declaration || currentNode.end <= declaration.pos || currentNode.pos >= declaration.end) { + // if the node has no correlation to a parse tree node, its definitely not + // part of the body. + // if the node is outside of the document range of the declaration, its + // definitely not part of the body. + return false; + } + var blockScope = ts.getEnclosingBlockScopeContainer(declaration); + while (currentNode) { + if (currentNode === blockScope || currentNode === declaration) { + // if we are in the enclosing block scope of the declaration, we are definitely + // not inside the class body. + return false; + } + if (ts.isClassElement(currentNode) && currentNode.parent === declaration) { + return true; + } + currentNode = currentNode.parent; + } + return false; + } + /** + * Substitutes `this` when contained within an arrow function. + * + * @param node The ThisKeyword node. + */ + function substituteThisKeyword(node) { + if (enabledSubstitutions & 1 /* CapturedThis */ + && hierarchyFacts & 16 /* CapturesThis */) { + return ts.setTextRange(ts.createFileLevelUniqueName("_this"), node); + } + return node; + } + function getClassMemberPrefix(node, member) { + return ts.hasModifier(member, 32 /* Static */) + ? ts.getInternalName(node) + : ts.createPropertyAccess(ts.getInternalName(node), "prototype"); + } + function hasSynthesizedDefaultSuperCall(constructor, hasExtendsClause) { + if (!constructor || !hasExtendsClause) { + return false; + } + if (ts.some(constructor.parameters)) { + return false; + } + var statement = ts.firstOrUndefined(constructor.body.statements); + if (!statement || !ts.nodeIsSynthesized(statement) || statement.kind !== 221 /* ExpressionStatement */) { + return false; + } + var statementExpression = statement.expression; + if (!ts.nodeIsSynthesized(statementExpression) || statementExpression.kind !== 191 /* CallExpression */) { + return false; + } + var callTarget = statementExpression.expression; + if (!ts.nodeIsSynthesized(callTarget) || callTarget.kind !== 98 /* SuperKeyword */) { + return false; + } + var callArgument = ts.singleOrUndefined(statementExpression.arguments); + if (!callArgument || !ts.nodeIsSynthesized(callArgument) || callArgument.kind !== 208 /* SpreadElement */) { + return false; + } + var expression = callArgument.expression; + return ts.isIdentifier(expression) && expression.escapedText === "arguments"; + } + } + ts.transformES2015 = transformES2015; + function createExtendsHelper(context, name) { + context.requestEmitHelper(extendsHelper); + return ts.createCall(ts.getHelperName("__extends"), + /*typeArguments*/ undefined, [ + name, + ts.createFileLevelUniqueName("_super") + ]); + } + function createTemplateObjectHelper(context, cooked, raw) { + context.requestEmitHelper(templateObjectHelper); + return ts.createCall(ts.getHelperName("__makeTemplateObject"), + /*typeArguments*/ undefined, [ + cooked, + raw + ]); + } + var extendsHelper = { + name: "typescript:extends", + scoped: false, + priority: 0, + text: "\n var __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return extendStatics(d, b);\n };\n\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n })();" + }; + var templateObjectHelper = { + name: "typescript:makeTemplateObject", + scoped: false, + priority: 0, + text: "\n var __makeTemplateObject = (this && this.__makeTemplateObject) || function (cooked, raw) {\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\n return cooked;\n };" + }; +})(ts || (ts = {})); +/*@internal*/ +var ts; +(function (ts) { + /** + * Transforms ES5 syntax into ES3 syntax. + * + * @param context Context and state information for the transformation. + */ + function transformES5(context) { + var compilerOptions = context.getCompilerOptions(); + // enable emit notification only if using --jsx preserve or react-native + var previousOnEmitNode; + var noSubstitution; + if (compilerOptions.jsx === 1 /* Preserve */ || compilerOptions.jsx === 3 /* ReactNative */) { + previousOnEmitNode = context.onEmitNode; + context.onEmitNode = onEmitNode; + context.enableEmitNotification(262 /* JsxOpeningElement */); + context.enableEmitNotification(263 /* JsxClosingElement */); + context.enableEmitNotification(261 /* JsxSelfClosingElement */); + noSubstitution = []; + } + var previousOnSubstituteNode = context.onSubstituteNode; + context.onSubstituteNode = onSubstituteNode; + context.enableSubstitution(189 /* PropertyAccessExpression */); + context.enableSubstitution(275 /* PropertyAssignment */); + return ts.chainBundle(transformSourceFile); + /** + * Transforms an ES5 source file to ES3. + * + * @param node A SourceFile + */ + function transformSourceFile(node) { + return node; + } + /** + * Called by the printer just before a node is printed. + * + * @param hint A hint as to the intended usage of the node. + * @param node The node to emit. + * @param emitCallback A callback used to emit the node. + */ + function onEmitNode(hint, node, emitCallback) { + switch (node.kind) { + case 262 /* JsxOpeningElement */: + case 263 /* JsxClosingElement */: + case 261 /* JsxSelfClosingElement */: + var tagName = node.tagName; + noSubstitution[ts.getOriginalNodeId(tagName)] = true; + break; + } + previousOnEmitNode(hint, node, emitCallback); + } + /** + * Hooks node substitutions. + * + * @param hint A hint as to the intended usage of the node. + * @param node The node to substitute. + */ + function onSubstituteNode(hint, node) { + if (node.id && noSubstitution && noSubstitution[node.id]) { + return previousOnSubstituteNode(hint, node); + } + node = previousOnSubstituteNode(hint, node); + if (ts.isPropertyAccessExpression(node)) { + return substitutePropertyAccessExpression(node); + } + else if (ts.isPropertyAssignment(node)) { + return substitutePropertyAssignment(node); + } + return node; + } + /** + * Substitutes a PropertyAccessExpression whose name is a reserved word. + * + * @param node A PropertyAccessExpression + */ + function substitutePropertyAccessExpression(node) { + var literalName = trySubstituteReservedName(node.name); + if (literalName) { + return ts.setTextRange(ts.createElementAccess(node.expression, literalName), node); + } + return node; + } + /** + * Substitutes a PropertyAssignment whose name is a reserved word. + * + * @param node A PropertyAssignment + */ + function substitutePropertyAssignment(node) { + var literalName = ts.isIdentifier(node.name) && trySubstituteReservedName(node.name); + if (literalName) { + return ts.updatePropertyAssignment(node, literalName, node.initializer); + } + return node; + } + /** + * If an identifier name is a reserved word, returns a string literal for the name. + * + * @param name An Identifier + */ + function trySubstituteReservedName(name) { + var token = name.originalKeywordKind || (ts.nodeIsSynthesized(name) ? ts.stringToToken(ts.idText(name)) : undefined); + if (token !== undefined && token >= 73 /* FirstReservedWord */ && token <= 108 /* LastReservedWord */) { + return ts.setTextRange(ts.createLiteral(name), name); + } + return undefined; + } + } + ts.transformES5 = transformES5; +})(ts || (ts = {})); +// Transforms generator functions into a compatible ES5 representation with similar runtime +// semantics. This is accomplished by first transforming the body of each generator +// function into an intermediate representation that is the compiled into a JavaScript +// switch statement. +// +// Many functions in this transformer will contain comments indicating the expected +// intermediate representation. For illustrative purposes, the following intermediate +// language is used to define this intermediate representation: +// +// .nop - Performs no operation. +// .local NAME, ... - Define local variable declarations. +// .mark LABEL - Mark the location of a label. +// .br LABEL - Jump to a label. If jumping out of a protected +// region, all .finally blocks are executed. +// .brtrue LABEL, (x) - Jump to a label IIF the expression `x` is truthy. +// If jumping out of a protected region, all .finally +// blocks are executed. +// .brfalse LABEL, (x) - Jump to a label IIF the expression `x` is falsey. +// If jumping out of a protected region, all .finally +// blocks are executed. +// .yield (x) - Yield the value of the optional expression `x`. +// Resume at the next label. +// .yieldstar (x) - Delegate yield to the value of the optional +// expression `x`. Resume at the next label. +// NOTE: `x` must be an Iterator, not an Iterable. +// .loop CONTINUE, BREAK - Marks the beginning of a loop. Any "continue" or +// "break" abrupt completions jump to the CONTINUE or +// BREAK labels, respectively. +// .endloop - Marks the end of a loop. +// .with (x) - Marks the beginning of a WithStatement block, using +// the supplied expression. +// .endwith - Marks the end of a WithStatement. +// .switch - Marks the beginning of a SwitchStatement. +// .endswitch - Marks the end of a SwitchStatement. +// .labeled NAME - Marks the beginning of a LabeledStatement with the +// supplied name. +// .endlabeled - Marks the end of a LabeledStatement. +// .try TRY, CATCH, FINALLY, END - Marks the beginning of a protected region, and the +// labels for each block. +// .catch (x) - Marks the beginning of a catch block. +// .finally - Marks the beginning of a finally block. +// .endfinally - Marks the end of a finally block. +// .endtry - Marks the end of a protected region. +// .throw (x) - Throws the value of the expression `x`. +// .return (x) - Returns the value of the expression `x`. +// +// In addition, the illustrative intermediate representation introduces some special +// variables: +// +// %sent% - Either returns the next value sent to the generator, +// returns the result of a delegated yield, or throws +// the exception sent to the generator. +// %error% - Returns the value of the current exception in a +// catch block. +// +// This intermediate representation is then compiled into JavaScript syntax. The resulting +// compilation output looks something like the following: +// +// function f() { +// var /*locals*/; +// /*functions*/ +// return __generator(function (state) { +// switch (state.label) { +// /*cases per label*/ +// } +// }); +// } +// +// Each of the above instructions corresponds to JavaScript emit similar to the following: +// +// .local NAME | var NAME; +// -------------------------------|---------------------------------------------- +// .mark LABEL | case LABEL: +// -------------------------------|---------------------------------------------- +// .br LABEL | return [3 /*break*/, LABEL]; +// -------------------------------|---------------------------------------------- +// .brtrue LABEL, (x) | if (x) return [3 /*break*/, LABEL]; +// -------------------------------|---------------------------------------------- +// .brfalse LABEL, (x) | if (!(x)) return [3, /*break*/, LABEL]; +// -------------------------------|---------------------------------------------- +// .yield (x) | return [4 /*yield*/, x]; +// .mark RESUME | case RESUME: +// a = %sent%; | a = state.sent(); +// -------------------------------|---------------------------------------------- +// .yieldstar (x) | return [5 /*yield**/, x]; +// .mark RESUME | case RESUME: +// a = %sent%; | a = state.sent(); +// -------------------------------|---------------------------------------------- +// .with (_a) | with (_a) { +// a(); | a(); +// | } +// | state.label = LABEL; +// .mark LABEL | case LABEL: +// | with (_a) { +// b(); | b(); +// | } +// .endwith | +// -------------------------------|---------------------------------------------- +// | case 0: +// | state.trys = []; +// | ... +// .try TRY, CATCH, FINALLY, END | +// .mark TRY | case TRY: +// | state.trys.push([TRY, CATCH, FINALLY, END]); +// .nop | +// a(); | a(); +// .br END | return [3 /*break*/, END]; +// .catch (e) | +// .mark CATCH | case CATCH: +// | e = state.sent(); +// b(); | b(); +// .br END | return [3 /*break*/, END]; +// .finally | +// .mark FINALLY | case FINALLY: +// c(); | c(); +// .endfinally | return [7 /*endfinally*/]; +// .endtry | +// .mark END | case END: +/*@internal*/ +var ts; +(function (ts) { + var OpCode; + (function (OpCode) { + OpCode[OpCode["Nop"] = 0] = "Nop"; + OpCode[OpCode["Statement"] = 1] = "Statement"; + OpCode[OpCode["Assign"] = 2] = "Assign"; + OpCode[OpCode["Break"] = 3] = "Break"; + OpCode[OpCode["BreakWhenTrue"] = 4] = "BreakWhenTrue"; + OpCode[OpCode["BreakWhenFalse"] = 5] = "BreakWhenFalse"; + OpCode[OpCode["Yield"] = 6] = "Yield"; + OpCode[OpCode["YieldStar"] = 7] = "YieldStar"; + OpCode[OpCode["Return"] = 8] = "Return"; + OpCode[OpCode["Throw"] = 9] = "Throw"; + OpCode[OpCode["Endfinally"] = 10] = "Endfinally"; // Marks the end of a `finally` block + })(OpCode || (OpCode = {})); + // whether a generated code block is opening or closing at the current operation for a FunctionBuilder + var BlockAction; + (function (BlockAction) { + BlockAction[BlockAction["Open"] = 0] = "Open"; + BlockAction[BlockAction["Close"] = 1] = "Close"; + })(BlockAction || (BlockAction = {})); + // the kind for a generated code block in a FunctionBuilder + var CodeBlockKind; + (function (CodeBlockKind) { + CodeBlockKind[CodeBlockKind["Exception"] = 0] = "Exception"; + CodeBlockKind[CodeBlockKind["With"] = 1] = "With"; + CodeBlockKind[CodeBlockKind["Switch"] = 2] = "Switch"; + CodeBlockKind[CodeBlockKind["Loop"] = 3] = "Loop"; + CodeBlockKind[CodeBlockKind["Labeled"] = 4] = "Labeled"; + })(CodeBlockKind || (CodeBlockKind = {})); + // the state for a generated code exception block + var ExceptionBlockState; + (function (ExceptionBlockState) { + ExceptionBlockState[ExceptionBlockState["Try"] = 0] = "Try"; + ExceptionBlockState[ExceptionBlockState["Catch"] = 1] = "Catch"; + ExceptionBlockState[ExceptionBlockState["Finally"] = 2] = "Finally"; + ExceptionBlockState[ExceptionBlockState["Done"] = 3] = "Done"; + })(ExceptionBlockState || (ExceptionBlockState = {})); + // NOTE: changes to this enum should be reflected in the __generator helper. + var Instruction; + (function (Instruction) { + Instruction[Instruction["Next"] = 0] = "Next"; + Instruction[Instruction["Throw"] = 1] = "Throw"; + Instruction[Instruction["Return"] = 2] = "Return"; + Instruction[Instruction["Break"] = 3] = "Break"; + Instruction[Instruction["Yield"] = 4] = "Yield"; + Instruction[Instruction["YieldStar"] = 5] = "YieldStar"; + Instruction[Instruction["Catch"] = 6] = "Catch"; + Instruction[Instruction["Endfinally"] = 7] = "Endfinally"; + })(Instruction || (Instruction = {})); + function getInstructionName(instruction) { + switch (instruction) { + case 2 /* Return */: return "return"; + case 3 /* Break */: return "break"; + case 4 /* Yield */: return "yield"; + case 5 /* YieldStar */: return "yield*"; + case 7 /* Endfinally */: return "endfinally"; + default: return undefined; // TODO: GH#18217 + } + } + function transformGenerators(context) { + var resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistFunctionDeclaration = context.hoistFunctionDeclaration, hoistVariableDeclaration = context.hoistVariableDeclaration; + var compilerOptions = context.getCompilerOptions(); + var languageVersion = ts.getEmitScriptTarget(compilerOptions); + var resolver = context.getEmitResolver(); + var previousOnSubstituteNode = context.onSubstituteNode; + context.onSubstituteNode = onSubstituteNode; + var renamedCatchVariables; + var renamedCatchVariableDeclarations; + var inGeneratorFunctionBody; + var inStatementContainingYield; + // The following three arrays store information about generated code blocks. + // All three arrays are correlated by their index. This approach is used over allocating + // objects to store the same information to avoid GC overhead. + // + var blocks; // Information about the code block + var blockOffsets; // The operation offset at which a code block begins or ends + var blockActions; // Whether the code block is opened or closed + var blockStack; // A stack of currently open code blocks + // Labels are used to mark locations in the code that can be the target of a Break (jump) + // operation. These are translated into case clauses in a switch statement. + // The following two arrays are correlated by their index. This approach is used over + // allocating objects to store the same information to avoid GC overhead. + // + var labelOffsets; // The operation offset at which the label is defined. + var labelExpressions; // The NumericLiteral nodes bound to each label. + var nextLabelId = 1; // The next label id to use. + // Operations store information about generated code for the function body. This + // Includes things like statements, assignments, breaks (jumps), and yields. + // The following three arrays are correlated by their index. This approach is used over + // allocating objects to store the same information to avoid GC overhead. + // + var operations; // The operation to perform. + var operationArguments; // The arguments to the operation. + var operationLocations; // The source map location for the operation. + var state; // The name of the state object used by the generator at runtime. + // The following variables store information used by the `build` function: + // + var blockIndex = 0; // The index of the current block. + var labelNumber = 0; // The current label number. + var labelNumbers; + var lastOperationWasAbrupt; // Indicates whether the last operation was abrupt (break/continue). + var lastOperationWasCompletion; // Indicates whether the last operation was a completion (return/throw). + var clauses; // The case clauses generated for labels. + var statements; // The statements for the current label. + var exceptionBlockStack; // A stack of containing exception blocks. + var currentExceptionBlock; // The current exception block. + var withBlockStack; // A stack containing `with` blocks. + return ts.chainBundle(transformSourceFile); + function transformSourceFile(node) { + if (node.isDeclarationFile || (node.transformFlags & 512 /* ContainsGenerator */) === 0) { + return node; + } + var visited = ts.visitEachChild(node, visitor, context); + ts.addEmitHelpers(visited, context.readEmitHelpers()); + return visited; + } + /** + * Visits a node. + * + * @param node The node to visit. + */ + function visitor(node) { + var transformFlags = node.transformFlags; + if (inStatementContainingYield) { + return visitJavaScriptInStatementContainingYield(node); + } + else if (inGeneratorFunctionBody) { + return visitJavaScriptInGeneratorFunctionBody(node); + } + else if (transformFlags & 256 /* Generator */) { + return visitGenerator(node); + } + else if (transformFlags & 512 /* ContainsGenerator */) { + return ts.visitEachChild(node, visitor, context); + } + else { + return node; + } + } + /** + * Visits a node that is contained within a statement that contains yield. + * + * @param node The node to visit. + */ + function visitJavaScriptInStatementContainingYield(node) { + switch (node.kind) { + case 223 /* DoStatement */: + return visitDoStatement(node); + case 224 /* WhileStatement */: + return visitWhileStatement(node); + case 232 /* SwitchStatement */: + return visitSwitchStatement(node); + case 233 /* LabeledStatement */: + return visitLabeledStatement(node); + default: + return visitJavaScriptInGeneratorFunctionBody(node); + } + } + /** + * Visits a node that is contained within a generator function. + * + * @param node The node to visit. + */ + function visitJavaScriptInGeneratorFunctionBody(node) { + switch (node.kind) { + case 239 /* FunctionDeclaration */: + return visitFunctionDeclaration(node); + case 196 /* FunctionExpression */: + return visitFunctionExpression(node); + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + return visitAccessorDeclaration(node); + case 219 /* VariableStatement */: + return visitVariableStatement(node); + case 225 /* ForStatement */: + return visitForStatement(node); + case 226 /* ForInStatement */: + return visitForInStatement(node); + case 229 /* BreakStatement */: + return visitBreakStatement(node); + case 228 /* ContinueStatement */: + return visitContinueStatement(node); + case 230 /* ReturnStatement */: + return visitReturnStatement(node); + default: + if (node.transformFlags & 4194304 /* ContainsYield */) { + return visitJavaScriptContainingYield(node); + } + else if (node.transformFlags & (512 /* ContainsGenerator */ | 8388608 /* ContainsHoistedDeclarationOrCompletion */)) { + return ts.visitEachChild(node, visitor, context); + } + else { + return node; + } + } + } + /** + * Visits a node that contains a YieldExpression. + * + * @param node The node to visit. + */ + function visitJavaScriptContainingYield(node) { + switch (node.kind) { + case 204 /* BinaryExpression */: + return visitBinaryExpression(node); + case 205 /* ConditionalExpression */: + return visitConditionalExpression(node); + case 207 /* YieldExpression */: + return visitYieldExpression(node); + case 187 /* ArrayLiteralExpression */: + return visitArrayLiteralExpression(node); + case 188 /* ObjectLiteralExpression */: + return visitObjectLiteralExpression(node); + case 190 /* ElementAccessExpression */: + return visitElementAccessExpression(node); + case 191 /* CallExpression */: + return visitCallExpression(node); + case 192 /* NewExpression */: + return visitNewExpression(node); + default: + return ts.visitEachChild(node, visitor, context); + } + } + /** + * Visits a generator function. + * + * @param node The node to visit. + */ + function visitGenerator(node) { + switch (node.kind) { + case 239 /* FunctionDeclaration */: + return visitFunctionDeclaration(node); + case 196 /* FunctionExpression */: + return visitFunctionExpression(node); + default: + return ts.Debug.failBadSyntaxKind(node); + } + } + /** + * Visits a function declaration. + * + * This will be called when one of the following conditions are met: + * - The function declaration is a generator function. + * - The function declaration is contained within the body of a generator function. + * + * @param node The node to visit. + */ + function visitFunctionDeclaration(node) { + // Currently, we only support generators that were originally async functions. + if (node.asteriskToken) { + node = ts.setOriginalNode(ts.setTextRange(ts.createFunctionDeclaration( + /*decorators*/ undefined, node.modifiers, + /*asteriskToken*/ undefined, node.name, + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, transformGeneratorFunctionBody(node.body)), + /*location*/ node), node); + } + else { + var savedInGeneratorFunctionBody = inGeneratorFunctionBody; + var savedInStatementContainingYield = inStatementContainingYield; + inGeneratorFunctionBody = false; + inStatementContainingYield = false; + node = ts.visitEachChild(node, visitor, context); + inGeneratorFunctionBody = savedInGeneratorFunctionBody; + inStatementContainingYield = savedInStatementContainingYield; + } + if (inGeneratorFunctionBody) { + // Function declarations in a generator function body are hoisted + // to the top of the lexical scope and elided from the current statement. + hoistFunctionDeclaration(node); + return undefined; + } + else { + return node; + } + } + /** + * Visits a function expression. + * + * This will be called when one of the following conditions are met: + * - The function expression is a generator function. + * - The function expression is contained within the body of a generator function. + * + * @param node The node to visit. + */ + function visitFunctionExpression(node) { + // Currently, we only support generators that were originally async functions. + if (node.asteriskToken) { + node = ts.setOriginalNode(ts.setTextRange(ts.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, node.name, + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, transformGeneratorFunctionBody(node.body)), + /*location*/ node), node); + } + else { + var savedInGeneratorFunctionBody = inGeneratorFunctionBody; + var savedInStatementContainingYield = inStatementContainingYield; + inGeneratorFunctionBody = false; + inStatementContainingYield = false; + node = ts.visitEachChild(node, visitor, context); + inGeneratorFunctionBody = savedInGeneratorFunctionBody; + inStatementContainingYield = savedInStatementContainingYield; + } + return node; + } + /** + * Visits a get or set accessor declaration. + * + * This will be called when one of the following conditions are met: + * - The accessor is contained within the body of a generator function. + * + * @param node The node to visit. + */ + function visitAccessorDeclaration(node) { + var savedInGeneratorFunctionBody = inGeneratorFunctionBody; + var savedInStatementContainingYield = inStatementContainingYield; + inGeneratorFunctionBody = false; + inStatementContainingYield = false; + node = ts.visitEachChild(node, visitor, context); + inGeneratorFunctionBody = savedInGeneratorFunctionBody; + inStatementContainingYield = savedInStatementContainingYield; + return node; + } + /** + * Transforms the body of a generator function declaration. + * + * @param node The function body to transform. + */ + function transformGeneratorFunctionBody(body) { + // Save existing generator state + var statements = []; + var savedInGeneratorFunctionBody = inGeneratorFunctionBody; + var savedInStatementContainingYield = inStatementContainingYield; + var savedBlocks = blocks; + var savedBlockOffsets = blockOffsets; + var savedBlockActions = blockActions; + var savedBlockStack = blockStack; + var savedLabelOffsets = labelOffsets; + var savedLabelExpressions = labelExpressions; + var savedNextLabelId = nextLabelId; + var savedOperations = operations; + var savedOperationArguments = operationArguments; + var savedOperationLocations = operationLocations; + var savedState = state; + // Initialize generator state + inGeneratorFunctionBody = true; + inStatementContainingYield = false; + blocks = undefined; + blockOffsets = undefined; + blockActions = undefined; + blockStack = undefined; + labelOffsets = undefined; + labelExpressions = undefined; + nextLabelId = 1; + operations = undefined; + operationArguments = undefined; + operationLocations = undefined; + state = ts.createTempVariable(/*recordTempVariable*/ undefined); + // Build the generator + resumeLexicalEnvironment(); + var statementOffset = ts.addPrologue(statements, body.statements, /*ensureUseStrict*/ false, visitor); + transformAndEmitStatements(body.statements, statementOffset); + var buildResult = build(); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + statements.push(ts.createReturn(buildResult)); + // Restore previous generator state + inGeneratorFunctionBody = savedInGeneratorFunctionBody; + inStatementContainingYield = savedInStatementContainingYield; + blocks = savedBlocks; + blockOffsets = savedBlockOffsets; + blockActions = savedBlockActions; + blockStack = savedBlockStack; + labelOffsets = savedLabelOffsets; + labelExpressions = savedLabelExpressions; + nextLabelId = savedNextLabelId; + operations = savedOperations; + operationArguments = savedOperationArguments; + operationLocations = savedOperationLocations; + state = savedState; + return ts.setTextRange(ts.createBlock(statements, body.multiLine), body); + } + /** + * Visits a variable statement. + * + * This will be called when one of the following conditions are met: + * - The variable statement is contained within the body of a generator function. + * + * @param node The node to visit. + */ + function visitVariableStatement(node) { + if (node.transformFlags & 4194304 /* ContainsYield */) { + transformAndEmitVariableDeclarationList(node.declarationList); + return undefined; + } + else { + // Do not hoist custom prologues. + if (ts.getEmitFlags(node) & 1048576 /* CustomPrologue */) { + return node; + } + for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { + var variable = _a[_i]; + hoistVariableDeclaration(variable.name); + } + var variables = ts.getInitializedVariables(node.declarationList); + if (variables.length === 0) { + return undefined; + } + return ts.setSourceMapRange(ts.createExpressionStatement(ts.inlineExpressions(ts.map(variables, transformInitializedVariable))), node); + } + } + /** + * Visits a binary expression. + * + * This will be called when one of the following conditions are met: + * - The node contains a YieldExpression. + * + * @param node The node to visit. + */ + function visitBinaryExpression(node) { + var assoc = ts.getExpressionAssociativity(node); + switch (assoc) { + case 0 /* Left */: + return visitLeftAssociativeBinaryExpression(node); + case 1 /* Right */: + return visitRightAssociativeBinaryExpression(node); + default: + return ts.Debug.assertNever(assoc); + } + } + function isCompoundAssignment(kind) { + return kind >= 60 /* FirstCompoundAssignment */ + && kind <= 71 /* LastCompoundAssignment */; + } + function getOperatorForCompoundAssignment(kind) { + switch (kind) { + case 60 /* PlusEqualsToken */: return 38 /* PlusToken */; + case 61 /* MinusEqualsToken */: return 39 /* MinusToken */; + case 62 /* AsteriskEqualsToken */: return 40 /* AsteriskToken */; + case 63 /* AsteriskAsteriskEqualsToken */: return 41 /* AsteriskAsteriskToken */; + case 64 /* SlashEqualsToken */: return 42 /* SlashToken */; + case 65 /* PercentEqualsToken */: return 43 /* PercentToken */; + case 66 /* LessThanLessThanEqualsToken */: return 46 /* LessThanLessThanToken */; + case 67 /* GreaterThanGreaterThanEqualsToken */: return 47 /* GreaterThanGreaterThanToken */; + case 68 /* GreaterThanGreaterThanGreaterThanEqualsToken */: return 48 /* GreaterThanGreaterThanGreaterThanToken */; + case 69 /* AmpersandEqualsToken */: return 49 /* AmpersandToken */; + case 70 /* BarEqualsToken */: return 50 /* BarToken */; + case 71 /* CaretEqualsToken */: return 51 /* CaretToken */; + } + } + /** + * Visits a right-associative binary expression containing `yield`. + * + * @param node The node to visit. + */ + function visitRightAssociativeBinaryExpression(node) { + var left = node.left, right = node.right; + if (containsYield(right)) { + var target = void 0; + switch (left.kind) { + case 189 /* PropertyAccessExpression */: + // [source] + // a.b = yield; + // + // [intermediate] + // .local _a + // _a = a; + // .yield resumeLabel + // .mark resumeLabel + // _a.b = %sent%; + target = ts.updatePropertyAccess(left, cacheExpression(ts.visitNode(left.expression, visitor, ts.isLeftHandSideExpression)), left.name); + break; + case 190 /* ElementAccessExpression */: + // [source] + // a[b] = yield; + // + // [intermediate] + // .local _a, _b + // _a = a; + // _b = b; + // .yield resumeLabel + // .mark resumeLabel + // _a[_b] = %sent%; + target = ts.updateElementAccess(left, cacheExpression(ts.visitNode(left.expression, visitor, ts.isLeftHandSideExpression)), cacheExpression(ts.visitNode(left.argumentExpression, visitor, ts.isExpression))); + break; + default: + target = ts.visitNode(left, visitor, ts.isExpression); + break; + } + var operator = node.operatorToken.kind; + if (isCompoundAssignment(operator)) { + return ts.setTextRange(ts.createAssignment(target, ts.setTextRange(ts.createBinary(cacheExpression(target), getOperatorForCompoundAssignment(operator), ts.visitNode(right, visitor, ts.isExpression)), node)), node); + } + else { + return ts.updateBinary(node, target, ts.visitNode(right, visitor, ts.isExpression)); + } + } + return ts.visitEachChild(node, visitor, context); + } + function visitLeftAssociativeBinaryExpression(node) { + if (containsYield(node.right)) { + if (ts.isLogicalOperator(node.operatorToken.kind)) { + return visitLogicalBinaryExpression(node); + } + else if (node.operatorToken.kind === 27 /* CommaToken */) { + return visitCommaExpression(node); + } + // [source] + // a() + (yield) + c() + // + // [intermediate] + // .local _a + // _a = a(); + // .yield resumeLabel + // _a + %sent% + c() + var clone_5 = ts.getMutableClone(node); + clone_5.left = cacheExpression(ts.visitNode(node.left, visitor, ts.isExpression)); + clone_5.right = ts.visitNode(node.right, visitor, ts.isExpression); + return clone_5; + } + return ts.visitEachChild(node, visitor, context); + } + /** + * Visits a logical binary expression containing `yield`. + * + * @param node A node to visit. + */ + function visitLogicalBinaryExpression(node) { + // Logical binary expressions (`&&` and `||`) are shortcutting expressions and need + // to be transformed as such: + // + // [source] + // x = a() && yield; + // + // [intermediate] + // .local _a + // _a = a(); + // .brfalse resultLabel, (_a) + // .yield resumeLabel + // .mark resumeLabel + // _a = %sent%; + // .mark resultLabel + // x = _a; + // + // [source] + // x = a() || yield; + // + // [intermediate] + // .local _a + // _a = a(); + // .brtrue resultLabel, (_a) + // .yield resumeLabel + // .mark resumeLabel + // _a = %sent%; + // .mark resultLabel + // x = _a; + var resultLabel = defineLabel(); + var resultLocal = declareLocal(); + emitAssignment(resultLocal, ts.visitNode(node.left, visitor, ts.isExpression), /*location*/ node.left); + if (node.operatorToken.kind === 54 /* AmpersandAmpersandToken */) { + // Logical `&&` shortcuts when the left-hand operand is falsey. + emitBreakWhenFalse(resultLabel, resultLocal, /*location*/ node.left); + } + else { + // Logical `||` shortcuts when the left-hand operand is truthy. + emitBreakWhenTrue(resultLabel, resultLocal, /*location*/ node.left); + } + emitAssignment(resultLocal, ts.visitNode(node.right, visitor, ts.isExpression), /*location*/ node.right); + markLabel(resultLabel); + return resultLocal; + } + /** + * Visits a comma expression containing `yield`. + * + * @param node The node to visit. + */ + function visitCommaExpression(node) { + // [source] + // x = a(), yield, b(); + // + // [intermediate] + // a(); + // .yield resumeLabel + // .mark resumeLabel + // x = %sent%, b(); + var pendingExpressions = []; + visit(node.left); + visit(node.right); + return ts.inlineExpressions(pendingExpressions); + function visit(node) { + if (ts.isBinaryExpression(node) && node.operatorToken.kind === 27 /* CommaToken */) { + visit(node.left); + visit(node.right); + } + else { + if (containsYield(node) && pendingExpressions.length > 0) { + emitWorker(1 /* Statement */, [ts.createExpressionStatement(ts.inlineExpressions(pendingExpressions))]); + pendingExpressions = []; + } + pendingExpressions.push(ts.visitNode(node, visitor, ts.isExpression)); + } + } + } + /** + * Visits a conditional expression containing `yield`. + * + * @param node The node to visit. + */ + function visitConditionalExpression(node) { + // [source] + // x = a() ? yield : b(); + // + // [intermediate] + // .local _a + // .brfalse whenFalseLabel, (a()) + // .yield resumeLabel + // .mark resumeLabel + // _a = %sent%; + // .br resultLabel + // .mark whenFalseLabel + // _a = b(); + // .mark resultLabel + // x = _a; + // We only need to perform a specific transformation if a `yield` expression exists + // in either the `whenTrue` or `whenFalse` branches. + // A `yield` in the condition will be handled by the normal visitor. + if (containsYield(node.whenTrue) || containsYield(node.whenFalse)) { + var whenFalseLabel = defineLabel(); + var resultLabel = defineLabel(); + var resultLocal = declareLocal(); + emitBreakWhenFalse(whenFalseLabel, ts.visitNode(node.condition, visitor, ts.isExpression), /*location*/ node.condition); + emitAssignment(resultLocal, ts.visitNode(node.whenTrue, visitor, ts.isExpression), /*location*/ node.whenTrue); + emitBreak(resultLabel); + markLabel(whenFalseLabel); + emitAssignment(resultLocal, ts.visitNode(node.whenFalse, visitor, ts.isExpression), /*location*/ node.whenFalse); + markLabel(resultLabel); + return resultLocal; + } + return ts.visitEachChild(node, visitor, context); + } + /** + * Visits a `yield` expression. + * + * @param node The node to visit. + */ + function visitYieldExpression(node) { + // [source] + // x = yield a(); + // + // [intermediate] + // .yield resumeLabel, (a()) + // .mark resumeLabel + // x = %sent%; + var resumeLabel = defineLabel(); + var expression = ts.visitNode(node.expression, visitor, ts.isExpression); + if (node.asteriskToken) { + var iterator = (ts.getEmitFlags(node.expression) & 8388608 /* Iterator */) === 0 + ? ts.createValuesHelper(context, expression, /*location*/ node) + : expression; + emitYieldStar(iterator, /*location*/ node); + } + else { + emitYield(expression, /*location*/ node); + } + markLabel(resumeLabel); + return createGeneratorResume(/*location*/ node); + } + /** + * Visits an ArrayLiteralExpression that contains a YieldExpression. + * + * @param node The node to visit. + */ + function visitArrayLiteralExpression(node) { + return visitElements(node.elements, /*leadingElement*/ undefined, /*location*/ undefined, node.multiLine); + } + /** + * Visits an array of expressions containing one or more YieldExpression nodes + * and returns an expression for the resulting value. + * + * @param elements The elements to visit. + * @param multiLine Whether array literals created should be emitted on multiple lines. + */ + function visitElements(elements, leadingElement, location, multiLine) { + // [source] + // ar = [1, yield, 2]; + // + // [intermediate] + // .local _a + // _a = [1]; + // .yield resumeLabel + // .mark resumeLabel + // ar = _a.concat([%sent%, 2]); + var numInitialElements = countInitialNodesWithoutYield(elements); + var temp; + if (numInitialElements > 0) { + temp = declareLocal(); + var initialElements = ts.visitNodes(elements, visitor, ts.isExpression, 0, numInitialElements); + emitAssignment(temp, ts.createArrayLiteral(leadingElement + ? [leadingElement].concat(initialElements) : initialElements)); + leadingElement = undefined; + } + var expressions = ts.reduceLeft(elements, reduceElement, [], numInitialElements); + return temp + ? ts.createArrayConcat(temp, [ts.createArrayLiteral(expressions, multiLine)]) + : ts.setTextRange(ts.createArrayLiteral(leadingElement ? [leadingElement].concat(expressions) : expressions, multiLine), location); + function reduceElement(expressions, element) { + if (containsYield(element) && expressions.length > 0) { + var hasAssignedTemp = temp !== undefined; + if (!temp) { + temp = declareLocal(); + } + emitAssignment(temp, hasAssignedTemp + ? ts.createArrayConcat(temp, [ts.createArrayLiteral(expressions, multiLine)]) + : ts.createArrayLiteral(leadingElement ? [leadingElement].concat(expressions) : expressions, multiLine)); + leadingElement = undefined; + expressions = []; + } + expressions.push(ts.visitNode(element, visitor, ts.isExpression)); + return expressions; + } + } + function visitObjectLiteralExpression(node) { + // [source] + // o = { + // a: 1, + // b: yield, + // c: 2 + // }; + // + // [intermediate] + // .local _a + // _a = { + // a: 1 + // }; + // .yield resumeLabel + // .mark resumeLabel + // o = (_a.b = %sent%, + // _a.c = 2, + // _a); + var properties = node.properties; + var multiLine = node.multiLine; + var numInitialProperties = countInitialNodesWithoutYield(properties); + var temp = declareLocal(); + emitAssignment(temp, ts.createObjectLiteral(ts.visitNodes(properties, visitor, ts.isObjectLiteralElementLike, 0, numInitialProperties), multiLine)); + var expressions = ts.reduceLeft(properties, reduceProperty, [], numInitialProperties); + expressions.push(multiLine ? ts.startOnNewLine(ts.getMutableClone(temp)) : temp); + return ts.inlineExpressions(expressions); + function reduceProperty(expressions, property) { + if (containsYield(property) && expressions.length > 0) { + emitStatement(ts.createExpressionStatement(ts.inlineExpressions(expressions))); + expressions = []; + } + var expression = ts.createExpressionForObjectLiteralElementLike(node, property, temp); + var visited = ts.visitNode(expression, visitor, ts.isExpression); + if (visited) { + if (multiLine) { + ts.startOnNewLine(visited); + } + expressions.push(visited); + } + return expressions; + } + } + /** + * Visits an ElementAccessExpression that contains a YieldExpression. + * + * @param node The node to visit. + */ + function visitElementAccessExpression(node) { + if (containsYield(node.argumentExpression)) { + // [source] + // a = x[yield]; + // + // [intermediate] + // .local _a + // _a = x; + // .yield resumeLabel + // .mark resumeLabel + // a = _a[%sent%] + var clone_6 = ts.getMutableClone(node); + clone_6.expression = cacheExpression(ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression)); + clone_6.argumentExpression = ts.visitNode(node.argumentExpression, visitor, ts.isExpression); + return clone_6; + } + return ts.visitEachChild(node, visitor, context); + } + function visitCallExpression(node) { + if (!ts.isImportCall(node) && ts.forEach(node.arguments, containsYield)) { + // [source] + // a.b(1, yield, 2); + // + // [intermediate] + // .local _a, _b, _c + // _b = (_a = a).b; + // _c = [1]; + // .yield resumeLabel + // .mark resumeLabel + // _b.apply(_a, _c.concat([%sent%, 2])); + var _a = ts.createCallBinding(node.expression, hoistVariableDeclaration, languageVersion, /*cacheIdentifiers*/ true), target = _a.target, thisArg = _a.thisArg; + return ts.setOriginalNode(ts.createFunctionApply(cacheExpression(ts.visitNode(target, visitor, ts.isLeftHandSideExpression)), thisArg, visitElements(node.arguments), + /*location*/ node), node); + } + return ts.visitEachChild(node, visitor, context); + } + function visitNewExpression(node) { + if (ts.forEach(node.arguments, containsYield)) { + // [source] + // new a.b(1, yield, 2); + // + // [intermediate] + // .local _a, _b, _c + // _b = (_a = a.b).bind; + // _c = [1]; + // .yield resumeLabel + // .mark resumeLabel + // new (_b.apply(_a, _c.concat([%sent%, 2]))); + var _a = ts.createCallBinding(ts.createPropertyAccess(node.expression, "bind"), hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg; + return ts.setOriginalNode(ts.setTextRange(ts.createNew(ts.createFunctionApply(cacheExpression(ts.visitNode(target, visitor, ts.isExpression)), thisArg, visitElements(node.arguments, + /*leadingElement*/ ts.createVoidZero())), + /*typeArguments*/ undefined, []), node), node); + } + return ts.visitEachChild(node, visitor, context); + } + function transformAndEmitStatements(statements, start) { + if (start === void 0) { start = 0; } + var numStatements = statements.length; + for (var i = start; i < numStatements; i++) { + transformAndEmitStatement(statements[i]); + } + } + function transformAndEmitEmbeddedStatement(node) { + if (ts.isBlock(node)) { + transformAndEmitStatements(node.statements); + } + else { + transformAndEmitStatement(node); + } + } + function transformAndEmitStatement(node) { + var savedInStatementContainingYield = inStatementContainingYield; + if (!inStatementContainingYield) { + inStatementContainingYield = containsYield(node); + } + transformAndEmitStatementWorker(node); + inStatementContainingYield = savedInStatementContainingYield; + } + function transformAndEmitStatementWorker(node) { + switch (node.kind) { + case 218 /* Block */: + return transformAndEmitBlock(node); + case 221 /* ExpressionStatement */: + return transformAndEmitExpressionStatement(node); + case 222 /* IfStatement */: + return transformAndEmitIfStatement(node); + case 223 /* DoStatement */: + return transformAndEmitDoStatement(node); + case 224 /* WhileStatement */: + return transformAndEmitWhileStatement(node); + case 225 /* ForStatement */: + return transformAndEmitForStatement(node); + case 226 /* ForInStatement */: + return transformAndEmitForInStatement(node); + case 228 /* ContinueStatement */: + return transformAndEmitContinueStatement(node); + case 229 /* BreakStatement */: + return transformAndEmitBreakStatement(node); + case 230 /* ReturnStatement */: + return transformAndEmitReturnStatement(node); + case 231 /* WithStatement */: + return transformAndEmitWithStatement(node); + case 232 /* SwitchStatement */: + return transformAndEmitSwitchStatement(node); + case 233 /* LabeledStatement */: + return transformAndEmitLabeledStatement(node); + case 234 /* ThrowStatement */: + return transformAndEmitThrowStatement(node); + case 235 /* TryStatement */: + return transformAndEmitTryStatement(node); + default: + return emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + } + function transformAndEmitBlock(node) { + if (containsYield(node)) { + transformAndEmitStatements(node.statements); + } + else { + emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + } + function transformAndEmitExpressionStatement(node) { + emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + function transformAndEmitVariableDeclarationList(node) { + for (var _i = 0, _a = node.declarations; _i < _a.length; _i++) { + var variable = _a[_i]; + var name = ts.getSynthesizedClone(variable.name); + ts.setCommentRange(name, variable.name); + hoistVariableDeclaration(name); + } + var variables = ts.getInitializedVariables(node); + var numVariables = variables.length; + var variablesWritten = 0; + var pendingExpressions = []; + while (variablesWritten < numVariables) { + for (var i = variablesWritten; i < numVariables; i++) { + var variable = variables[i]; + if (containsYield(variable.initializer) && pendingExpressions.length > 0) { + break; + } + pendingExpressions.push(transformInitializedVariable(variable)); + } + if (pendingExpressions.length) { + emitStatement(ts.createExpressionStatement(ts.inlineExpressions(pendingExpressions))); + variablesWritten += pendingExpressions.length; + pendingExpressions = []; + } + } + return undefined; + } + function transformInitializedVariable(node) { + return ts.setSourceMapRange(ts.createAssignment(ts.setSourceMapRange(ts.getSynthesizedClone(node.name), node.name), ts.visitNode(node.initializer, visitor, ts.isExpression)), node); + } + function transformAndEmitIfStatement(node) { + if (containsYield(node)) { + // [source] + // if (x) + // /*thenStatement*/ + // else + // /*elseStatement*/ + // + // [intermediate] + // .brfalse elseLabel, (x) + // /*thenStatement*/ + // .br endLabel + // .mark elseLabel + // /*elseStatement*/ + // .mark endLabel + if (containsYield(node.thenStatement) || containsYield(node.elseStatement)) { + var endLabel = defineLabel(); + var elseLabel = node.elseStatement ? defineLabel() : undefined; + emitBreakWhenFalse(node.elseStatement ? elseLabel : endLabel, ts.visitNode(node.expression, visitor, ts.isExpression), /*location*/ node.expression); + transformAndEmitEmbeddedStatement(node.thenStatement); + if (node.elseStatement) { + emitBreak(endLabel); + markLabel(elseLabel); + transformAndEmitEmbeddedStatement(node.elseStatement); + } + markLabel(endLabel); + } + else { + emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + } + else { + emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + } + function transformAndEmitDoStatement(node) { + if (containsYield(node)) { + // [source] + // do { + // /*body*/ + // } + // while (i < 10); + // + // [intermediate] + // .loop conditionLabel, endLabel + // .mark loopLabel + // /*body*/ + // .mark conditionLabel + // .brtrue loopLabel, (i < 10) + // .endloop + // .mark endLabel + var conditionLabel = defineLabel(); + var loopLabel = defineLabel(); + beginLoopBlock(/*continueLabel*/ conditionLabel); + markLabel(loopLabel); + transformAndEmitEmbeddedStatement(node.statement); + markLabel(conditionLabel); + emitBreakWhenTrue(loopLabel, ts.visitNode(node.expression, visitor, ts.isExpression)); + endLoopBlock(); + } + else { + emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + } + function visitDoStatement(node) { + if (inStatementContainingYield) { + beginScriptLoopBlock(); + node = ts.visitEachChild(node, visitor, context); + endLoopBlock(); + return node; + } + else { + return ts.visitEachChild(node, visitor, context); + } + } + function transformAndEmitWhileStatement(node) { + if (containsYield(node)) { + // [source] + // while (i < 10) { + // /*body*/ + // } + // + // [intermediate] + // .loop loopLabel, endLabel + // .mark loopLabel + // .brfalse endLabel, (i < 10) + // /*body*/ + // .br loopLabel + // .endloop + // .mark endLabel + var loopLabel = defineLabel(); + var endLabel = beginLoopBlock(loopLabel); + markLabel(loopLabel); + emitBreakWhenFalse(endLabel, ts.visitNode(node.expression, visitor, ts.isExpression)); + transformAndEmitEmbeddedStatement(node.statement); + emitBreak(loopLabel); + endLoopBlock(); + } + else { + emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + } + function visitWhileStatement(node) { + if (inStatementContainingYield) { + beginScriptLoopBlock(); + node = ts.visitEachChild(node, visitor, context); + endLoopBlock(); + return node; + } + else { + return ts.visitEachChild(node, visitor, context); + } + } + function transformAndEmitForStatement(node) { + if (containsYield(node)) { + // [source] + // for (var i = 0; i < 10; i++) { + // /*body*/ + // } + // + // [intermediate] + // .local i + // i = 0; + // .loop incrementLabel, endLoopLabel + // .mark conditionLabel + // .brfalse endLoopLabel, (i < 10) + // /*body*/ + // .mark incrementLabel + // i++; + // .br conditionLabel + // .endloop + // .mark endLoopLabel + var conditionLabel = defineLabel(); + var incrementLabel = defineLabel(); + var endLabel = beginLoopBlock(incrementLabel); + if (node.initializer) { + var initializer = node.initializer; + if (ts.isVariableDeclarationList(initializer)) { + transformAndEmitVariableDeclarationList(initializer); + } + else { + emitStatement(ts.setTextRange(ts.createExpressionStatement(ts.visitNode(initializer, visitor, ts.isExpression)), initializer)); + } + } + markLabel(conditionLabel); + if (node.condition) { + emitBreakWhenFalse(endLabel, ts.visitNode(node.condition, visitor, ts.isExpression)); + } + transformAndEmitEmbeddedStatement(node.statement); + markLabel(incrementLabel); + if (node.incrementor) { + emitStatement(ts.setTextRange(ts.createExpressionStatement(ts.visitNode(node.incrementor, visitor, ts.isExpression)), node.incrementor)); + } + emitBreak(conditionLabel); + endLoopBlock(); + } + else { + emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + } + function visitForStatement(node) { + if (inStatementContainingYield) { + beginScriptLoopBlock(); + } + var initializer = node.initializer; + if (initializer && ts.isVariableDeclarationList(initializer)) { + for (var _i = 0, _a = initializer.declarations; _i < _a.length; _i++) { + var variable = _a[_i]; + hoistVariableDeclaration(variable.name); + } + var variables = ts.getInitializedVariables(initializer); + node = ts.updateFor(node, variables.length > 0 + ? ts.inlineExpressions(ts.map(variables, transformInitializedVariable)) + : undefined, ts.visitNode(node.condition, visitor, ts.isExpression), ts.visitNode(node.incrementor, visitor, ts.isExpression), ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); + } + else { + node = ts.visitEachChild(node, visitor, context); + } + if (inStatementContainingYield) { + endLoopBlock(); + } + return node; + } + function transformAndEmitForInStatement(node) { + // TODO(rbuckton): Source map locations + if (containsYield(node)) { + // [source] + // for (var p in o) { + // /*body*/ + // } + // + // [intermediate] + // .local _a, _b, _i + // _a = []; + // for (_b in o) _a.push(_b); + // _i = 0; + // .loop incrementLabel, endLoopLabel + // .mark conditionLabel + // .brfalse endLoopLabel, (_i < _a.length) + // p = _a[_i]; + // /*body*/ + // .mark incrementLabel + // _b++; + // .br conditionLabel + // .endloop + // .mark endLoopLabel + var keysArray = declareLocal(); // _a + var key = declareLocal(); // _b + var keysIndex = ts.createLoopVariable(); // _i + var initializer = node.initializer; + hoistVariableDeclaration(keysIndex); + emitAssignment(keysArray, ts.createArrayLiteral()); + emitStatement(ts.createForIn(key, ts.visitNode(node.expression, visitor, ts.isExpression), ts.createExpressionStatement(ts.createCall(ts.createPropertyAccess(keysArray, "push"), + /*typeArguments*/ undefined, [key])))); + emitAssignment(keysIndex, ts.createLiteral(0)); + var conditionLabel = defineLabel(); + var incrementLabel = defineLabel(); + var endLabel = beginLoopBlock(incrementLabel); + markLabel(conditionLabel); + emitBreakWhenFalse(endLabel, ts.createLessThan(keysIndex, ts.createPropertyAccess(keysArray, "length"))); + var variable = void 0; + if (ts.isVariableDeclarationList(initializer)) { + for (var _i = 0, _a = initializer.declarations; _i < _a.length; _i++) { + var variable_1 = _a[_i]; + hoistVariableDeclaration(variable_1.name); + } + variable = ts.getSynthesizedClone(initializer.declarations[0].name); + } + else { + variable = ts.visitNode(initializer, visitor, ts.isExpression); + ts.Debug.assert(ts.isLeftHandSideExpression(variable)); + } + emitAssignment(variable, ts.createElementAccess(keysArray, keysIndex)); + transformAndEmitEmbeddedStatement(node.statement); + markLabel(incrementLabel); + emitStatement(ts.createExpressionStatement(ts.createPostfixIncrement(keysIndex))); + emitBreak(conditionLabel); + endLoopBlock(); + } + else { + emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + } + function visitForInStatement(node) { + // [source] + // for (var x in a) { + // /*body*/ + // } + // + // [intermediate] + // .local x + // .loop + // for (x in a) { + // /*body*/ + // } + // .endloop + if (inStatementContainingYield) { + beginScriptLoopBlock(); + } + var initializer = node.initializer; + if (ts.isVariableDeclarationList(initializer)) { + for (var _i = 0, _a = initializer.declarations; _i < _a.length; _i++) { + var variable = _a[_i]; + hoistVariableDeclaration(variable.name); + } + node = ts.updateForIn(node, initializer.declarations[0].name, ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); + } + else { + node = ts.visitEachChild(node, visitor, context); + } + if (inStatementContainingYield) { + endLoopBlock(); + } + return node; + } + function transformAndEmitContinueStatement(node) { + var label = findContinueTarget(node.label ? ts.idText(node.label) : undefined); + if (label > 0) { + emitBreak(label, /*location*/ node); + } + else { + // invalid continue without a containing loop. Leave the node as is, per #17875. + emitStatement(node); + } + } + function visitContinueStatement(node) { + if (inStatementContainingYield) { + var label = findContinueTarget(node.label && ts.idText(node.label)); + if (label > 0) { + return createInlineBreak(label, /*location*/ node); + } + } + return ts.visitEachChild(node, visitor, context); + } + function transformAndEmitBreakStatement(node) { + var label = findBreakTarget(node.label ? ts.idText(node.label) : undefined); + if (label > 0) { + emitBreak(label, /*location*/ node); + } + else { + // invalid break without a containing loop, switch, or labeled statement. Leave the node as is, per #17875. + emitStatement(node); + } + } + function visitBreakStatement(node) { + if (inStatementContainingYield) { + var label = findBreakTarget(node.label && ts.idText(node.label)); + if (label > 0) { + return createInlineBreak(label, /*location*/ node); + } + } + return ts.visitEachChild(node, visitor, context); + } + function transformAndEmitReturnStatement(node) { + emitReturn(ts.visitNode(node.expression, visitor, ts.isExpression), + /*location*/ node); + } + function visitReturnStatement(node) { + return createInlineReturn(ts.visitNode(node.expression, visitor, ts.isExpression), + /*location*/ node); + } + function transformAndEmitWithStatement(node) { + if (containsYield(node)) { + // [source] + // with (x) { + // /*body*/ + // } + // + // [intermediate] + // .with (x) + // /*body*/ + // .endwith + beginWithBlock(cacheExpression(ts.visitNode(node.expression, visitor, ts.isExpression))); + transformAndEmitEmbeddedStatement(node.statement); + endWithBlock(); + } + else { + emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + } + function transformAndEmitSwitchStatement(node) { + if (containsYield(node.caseBlock)) { + // [source] + // switch (x) { + // case a: + // /*caseStatements*/ + // case b: + // /*caseStatements*/ + // default: + // /*defaultStatements*/ + // } + // + // [intermediate] + // .local _a + // .switch endLabel + // _a = x; + // switch (_a) { + // case a: + // .br clauseLabels[0] + // } + // switch (_a) { + // case b: + // .br clauseLabels[1] + // } + // .br clauseLabels[2] + // .mark clauseLabels[0] + // /*caseStatements*/ + // .mark clauseLabels[1] + // /*caseStatements*/ + // .mark clauseLabels[2] + // /*caseStatements*/ + // .endswitch + // .mark endLabel + var caseBlock = node.caseBlock; + var numClauses = caseBlock.clauses.length; + var endLabel = beginSwitchBlock(); + var expression = cacheExpression(ts.visitNode(node.expression, visitor, ts.isExpression)); + // Create labels for each clause and find the index of the first default clause. + var clauseLabels = []; + var defaultClauseIndex = -1; + for (var i = 0; i < numClauses; i++) { + var clause = caseBlock.clauses[i]; + clauseLabels.push(defineLabel()); + if (clause.kind === 272 /* DefaultClause */ && defaultClauseIndex === -1) { + defaultClauseIndex = i; + } + } + // Emit switch statements for each run of case clauses either from the first case + // clause or the next case clause with a `yield` in its expression, up to the next + // case clause with a `yield` in its expression. + var clausesWritten = 0; + var pendingClauses = []; + while (clausesWritten < numClauses) { + var defaultClausesSkipped = 0; + for (var i = clausesWritten; i < numClauses; i++) { + var clause = caseBlock.clauses[i]; + if (clause.kind === 271 /* CaseClause */) { + if (containsYield(clause.expression) && pendingClauses.length > 0) { + break; + } + pendingClauses.push(ts.createCaseClause(ts.visitNode(clause.expression, visitor, ts.isExpression), [ + createInlineBreak(clauseLabels[i], /*location*/ clause.expression) + ])); + } + else { + defaultClausesSkipped++; + } + } + if (pendingClauses.length) { + emitStatement(ts.createSwitch(expression, ts.createCaseBlock(pendingClauses))); + clausesWritten += pendingClauses.length; + pendingClauses = []; + } + if (defaultClausesSkipped > 0) { + clausesWritten += defaultClausesSkipped; + defaultClausesSkipped = 0; + } + } + if (defaultClauseIndex >= 0) { + emitBreak(clauseLabels[defaultClauseIndex]); + } + else { + emitBreak(endLabel); + } + for (var i = 0; i < numClauses; i++) { + markLabel(clauseLabels[i]); + transformAndEmitStatements(caseBlock.clauses[i].statements); + } + endSwitchBlock(); + } + else { + emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + } + function visitSwitchStatement(node) { + if (inStatementContainingYield) { + beginScriptSwitchBlock(); + } + node = ts.visitEachChild(node, visitor, context); + if (inStatementContainingYield) { + endSwitchBlock(); + } + return node; + } + function transformAndEmitLabeledStatement(node) { + if (containsYield(node)) { + // [source] + // x: { + // /*body*/ + // } + // + // [intermediate] + // .labeled "x", endLabel + // /*body*/ + // .endlabeled + // .mark endLabel + beginLabeledBlock(ts.idText(node.label)); + transformAndEmitEmbeddedStatement(node.statement); + endLabeledBlock(); + } + else { + emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + } + function visitLabeledStatement(node) { + if (inStatementContainingYield) { + beginScriptLabeledBlock(ts.idText(node.label)); + } + node = ts.visitEachChild(node, visitor, context); + if (inStatementContainingYield) { + endLabeledBlock(); + } + return node; + } + function transformAndEmitThrowStatement(node) { + emitThrow(ts.visitNode(node.expression, visitor, ts.isExpression), + /*location*/ node); + } + function transformAndEmitTryStatement(node) { + if (containsYield(node)) { + // [source] + // try { + // /*tryBlock*/ + // } + // catch (e) { + // /*catchBlock*/ + // } + // finally { + // /*finallyBlock*/ + // } + // + // [intermediate] + // .local _a + // .try tryLabel, catchLabel, finallyLabel, endLabel + // .mark tryLabel + // .nop + // /*tryBlock*/ + // .br endLabel + // .catch + // .mark catchLabel + // _a = %error%; + // /*catchBlock*/ + // .br endLabel + // .finally + // .mark finallyLabel + // /*finallyBlock*/ + // .endfinally + // .endtry + // .mark endLabel + beginExceptionBlock(); + transformAndEmitEmbeddedStatement(node.tryBlock); + if (node.catchClause) { + beginCatchBlock(node.catchClause.variableDeclaration); // TODO: GH#18217 + transformAndEmitEmbeddedStatement(node.catchClause.block); + } + if (node.finallyBlock) { + beginFinallyBlock(); + transformAndEmitEmbeddedStatement(node.finallyBlock); + } + endExceptionBlock(); + } + else { + emitStatement(ts.visitEachChild(node, visitor, context)); + } + } + function containsYield(node) { + return !!node && (node.transformFlags & 4194304 /* ContainsYield */) !== 0; + } + function countInitialNodesWithoutYield(nodes) { + var numNodes = nodes.length; + for (var i = 0; i < numNodes; i++) { + if (containsYield(nodes[i])) { + return i; + } + } + return -1; + } + function onSubstituteNode(hint, node) { + node = previousOnSubstituteNode(hint, node); + if (hint === 1 /* Expression */) { + return substituteExpression(node); + } + return node; + } + function substituteExpression(node) { + if (ts.isIdentifier(node)) { + return substituteExpressionIdentifier(node); + } + return node; + } + function substituteExpressionIdentifier(node) { + if (!ts.isGeneratedIdentifier(node) && renamedCatchVariables && renamedCatchVariables.has(ts.idText(node))) { + var original = ts.getOriginalNode(node); + if (ts.isIdentifier(original) && original.parent) { + var declaration = resolver.getReferencedValueDeclaration(original); + if (declaration) { + var name = renamedCatchVariableDeclarations[ts.getOriginalNodeId(declaration)]; + if (name) { + var clone_7 = ts.getMutableClone(name); + ts.setSourceMapRange(clone_7, node); + ts.setCommentRange(clone_7, node); + return clone_7; + } + } + } + } + return node; + } + function cacheExpression(node) { + var temp; + if (ts.isGeneratedIdentifier(node) || ts.getEmitFlags(node) & 4096 /* HelperName */) { + return node; + } + temp = ts.createTempVariable(hoistVariableDeclaration); + emitAssignment(temp, node, /*location*/ node); + return temp; + } + function declareLocal(name) { + var temp = name + ? ts.createUniqueName(name) + : ts.createTempVariable(/*recordTempVariable*/ undefined); + hoistVariableDeclaration(temp); + return temp; + } + /** + * Defines a label, uses as the target of a Break operation. + */ + function defineLabel() { + if (!labelOffsets) { + labelOffsets = []; + } + var label = nextLabelId; + nextLabelId++; + labelOffsets[label] = -1; + return label; + } + /** + * Marks the current operation with the specified label. + */ + function markLabel(label) { + ts.Debug.assert(labelOffsets !== undefined, "No labels were defined."); + labelOffsets[label] = operations ? operations.length : 0; + } + /** + * Begins a block operation (With, Break/Continue, Try/Catch/Finally) + * + * @param block Information about the block. + */ + function beginBlock(block) { + if (!blocks) { + blocks = []; + blockActions = []; + blockOffsets = []; + blockStack = []; + } + var index = blockActions.length; + blockActions[index] = 0 /* Open */; + blockOffsets[index] = operations ? operations.length : 0; + blocks[index] = block; + blockStack.push(block); + return index; + } + /** + * Ends the current block operation. + */ + function endBlock() { + var block = peekBlock(); + if (block === undefined) + return ts.Debug.fail("beginBlock was never called."); + var index = blockActions.length; + blockActions[index] = 1 /* Close */; + blockOffsets[index] = operations ? operations.length : 0; + blocks[index] = block; + blockStack.pop(); + return block; + } + /** + * Gets the current open block. + */ + function peekBlock() { + return ts.lastOrUndefined(blockStack); + } + /** + * Gets the kind of the current open block. + */ + function peekBlockKind() { + var block = peekBlock(); + return block && block.kind; + } + /** + * Begins a code block for a generated `with` statement. + * + * @param expression An identifier representing expression for the `with` block. + */ + function beginWithBlock(expression) { + var startLabel = defineLabel(); + var endLabel = defineLabel(); + markLabel(startLabel); + beginBlock({ + kind: 1 /* With */, + expression: expression, + startLabel: startLabel, + endLabel: endLabel + }); + } + /** + * Ends a code block for a generated `with` statement. + */ + function endWithBlock() { + ts.Debug.assert(peekBlockKind() === 1 /* With */); + var block = endBlock(); + markLabel(block.endLabel); + } + /** + * Begins a code block for a generated `try` statement. + */ + function beginExceptionBlock() { + var startLabel = defineLabel(); + var endLabel = defineLabel(); + markLabel(startLabel); + beginBlock({ + kind: 0 /* Exception */, + state: 0 /* Try */, + startLabel: startLabel, + endLabel: endLabel + }); + emitNop(); + return endLabel; + } + /** + * Enters the `catch` clause of a generated `try` statement. + * + * @param variable The catch variable. + */ + function beginCatchBlock(variable) { + ts.Debug.assert(peekBlockKind() === 0 /* Exception */); + // generated identifiers should already be unique within a file + var name; + if (ts.isGeneratedIdentifier(variable.name)) { + name = variable.name; + hoistVariableDeclaration(variable.name); + } + else { + var text = ts.idText(variable.name); + name = declareLocal(text); + if (!renamedCatchVariables) { + renamedCatchVariables = ts.createMap(); + renamedCatchVariableDeclarations = []; + context.enableSubstitution(72 /* Identifier */); + } + renamedCatchVariables.set(text, true); + renamedCatchVariableDeclarations[ts.getOriginalNodeId(variable)] = name; + } + var exception = peekBlock(); + ts.Debug.assert(exception.state < 1 /* Catch */); + var endLabel = exception.endLabel; + emitBreak(endLabel); + var catchLabel = defineLabel(); + markLabel(catchLabel); + exception.state = 1 /* Catch */; + exception.catchVariable = name; + exception.catchLabel = catchLabel; + emitAssignment(name, ts.createCall(ts.createPropertyAccess(state, "sent"), /*typeArguments*/ undefined, [])); + emitNop(); + } + /** + * Enters the `finally` block of a generated `try` statement. + */ + function beginFinallyBlock() { + ts.Debug.assert(peekBlockKind() === 0 /* Exception */); + var exception = peekBlock(); + ts.Debug.assert(exception.state < 2 /* Finally */); + var endLabel = exception.endLabel; + emitBreak(endLabel); + var finallyLabel = defineLabel(); + markLabel(finallyLabel); + exception.state = 2 /* Finally */; + exception.finallyLabel = finallyLabel; + } + /** + * Ends the code block for a generated `try` statement. + */ + function endExceptionBlock() { + ts.Debug.assert(peekBlockKind() === 0 /* Exception */); + var exception = endBlock(); + var state = exception.state; + if (state < 2 /* Finally */) { + emitBreak(exception.endLabel); + } + else { + emitEndfinally(); + } + markLabel(exception.endLabel); + emitNop(); + exception.state = 3 /* Done */; + } + /** + * Begins a code block that supports `break` or `continue` statements that are defined in + * the source tree and not from generated code. + * + * @param labelText Names from containing labeled statements. + */ + function beginScriptLoopBlock() { + beginBlock({ + kind: 3 /* Loop */, + isScript: true, + breakLabel: -1, + continueLabel: -1 + }); + } + /** + * Begins a code block that supports `break` or `continue` statements that are defined in + * generated code. Returns a label used to mark the operation to which to jump when a + * `break` statement targets this block. + * + * @param continueLabel A Label used to mark the operation to which to jump when a + * `continue` statement targets this block. + */ + function beginLoopBlock(continueLabel) { + var breakLabel = defineLabel(); + beginBlock({ + kind: 3 /* Loop */, + isScript: false, + breakLabel: breakLabel, + continueLabel: continueLabel, + }); + return breakLabel; + } + /** + * Ends a code block that supports `break` or `continue` statements that are defined in + * generated code or in the source tree. + */ + function endLoopBlock() { + ts.Debug.assert(peekBlockKind() === 3 /* Loop */); + var block = endBlock(); + var breakLabel = block.breakLabel; + if (!block.isScript) { + markLabel(breakLabel); + } + } + /** + * Begins a code block that supports `break` statements that are defined in the source + * tree and not from generated code. + * + */ + function beginScriptSwitchBlock() { + beginBlock({ + kind: 2 /* Switch */, + isScript: true, + breakLabel: -1 + }); + } + /** + * Begins a code block that supports `break` statements that are defined in generated code. + * Returns a label used to mark the operation to which to jump when a `break` statement + * targets this block. + */ + function beginSwitchBlock() { + var breakLabel = defineLabel(); + beginBlock({ + kind: 2 /* Switch */, + isScript: false, + breakLabel: breakLabel, + }); + return breakLabel; + } + /** + * Ends a code block that supports `break` statements that are defined in generated code. + */ + function endSwitchBlock() { + ts.Debug.assert(peekBlockKind() === 2 /* Switch */); + var block = endBlock(); + var breakLabel = block.breakLabel; + if (!block.isScript) { + markLabel(breakLabel); + } + } + function beginScriptLabeledBlock(labelText) { + beginBlock({ + kind: 4 /* Labeled */, + isScript: true, + labelText: labelText, + breakLabel: -1 + }); + } + function beginLabeledBlock(labelText) { + var breakLabel = defineLabel(); + beginBlock({ + kind: 4 /* Labeled */, + isScript: false, + labelText: labelText, + breakLabel: breakLabel + }); + } + function endLabeledBlock() { + ts.Debug.assert(peekBlockKind() === 4 /* Labeled */); + var block = endBlock(); + if (!block.isScript) { + markLabel(block.breakLabel); + } + } + /** + * Indicates whether the provided block supports `break` statements. + * + * @param block A code block. + */ + function supportsUnlabeledBreak(block) { + return block.kind === 2 /* Switch */ + || block.kind === 3 /* Loop */; + } + /** + * Indicates whether the provided block supports `break` statements with labels. + * + * @param block A code block. + */ + function supportsLabeledBreakOrContinue(block) { + return block.kind === 4 /* Labeled */; + } + /** + * Indicates whether the provided block supports `continue` statements. + * + * @param block A code block. + */ + function supportsUnlabeledContinue(block) { + return block.kind === 3 /* Loop */; + } + function hasImmediateContainingLabeledBlock(labelText, start) { + for (var j = start; j >= 0; j--) { + var containingBlock = blockStack[j]; + if (supportsLabeledBreakOrContinue(containingBlock)) { + if (containingBlock.labelText === labelText) { + return true; + } + } + else { + break; + } + } + return false; + } + /** + * Finds the label that is the target for a `break` statement. + * + * @param labelText An optional name of a containing labeled statement. + */ + function findBreakTarget(labelText) { + if (blockStack) { + if (labelText) { + for (var i = blockStack.length - 1; i >= 0; i--) { + var block = blockStack[i]; + if (supportsLabeledBreakOrContinue(block) && block.labelText === labelText) { + return block.breakLabel; + } + else if (supportsUnlabeledBreak(block) && hasImmediateContainingLabeledBlock(labelText, i - 1)) { + return block.breakLabel; + } + } + } + else { + for (var i = blockStack.length - 1; i >= 0; i--) { + var block = blockStack[i]; + if (supportsUnlabeledBreak(block)) { + return block.breakLabel; + } + } + } + } + return 0; + } + /** + * Finds the label that is the target for a `continue` statement. + * + * @param labelText An optional name of a containing labeled statement. + */ + function findContinueTarget(labelText) { + if (blockStack) { + if (labelText) { + for (var i = blockStack.length - 1; i >= 0; i--) { + var block = blockStack[i]; + if (supportsUnlabeledContinue(block) && hasImmediateContainingLabeledBlock(labelText, i - 1)) { + return block.continueLabel; + } + } + } + else { + for (var i = blockStack.length - 1; i >= 0; i--) { + var block = blockStack[i]; + if (supportsUnlabeledContinue(block)) { + return block.continueLabel; + } + } + } + } + return 0; + } + /** + * Creates an expression that can be used to indicate the value for a label. + * + * @param label A label. + */ + function createLabel(label) { + if (label !== undefined && label > 0) { + if (labelExpressions === undefined) { + labelExpressions = []; + } + var expression = ts.createLiteral(-1); + if (labelExpressions[label] === undefined) { + labelExpressions[label] = [expression]; + } + else { + labelExpressions[label].push(expression); + } + return expression; + } + return ts.createOmittedExpression(); + } + /** + * Creates a numeric literal for the provided instruction. + */ + function createInstruction(instruction) { + var literal = ts.createLiteral(instruction); + ts.addSyntheticTrailingComment(literal, 3 /* MultiLineCommentTrivia */, getInstructionName(instruction)); + return literal; + } + /** + * Creates a statement that can be used indicate a Break operation to the provided label. + * + * @param label A label. + * @param location An optional source map location for the statement. + */ + function createInlineBreak(label, location) { + ts.Debug.assertLessThan(0, label, "Invalid label"); + return ts.setTextRange(ts.createReturn(ts.createArrayLiteral([ + createInstruction(3 /* Break */), + createLabel(label) + ])), location); + } + /** + * Creates a statement that can be used indicate a Return operation. + * + * @param expression The expression for the return statement. + * @param location An optional source map location for the statement. + */ + function createInlineReturn(expression, location) { + return ts.setTextRange(ts.createReturn(ts.createArrayLiteral(expression + ? [createInstruction(2 /* Return */), expression] + : [createInstruction(2 /* Return */)])), location); + } + /** + * Creates an expression that can be used to resume from a Yield operation. + */ + function createGeneratorResume(location) { + return ts.setTextRange(ts.createCall(ts.createPropertyAccess(state, "sent"), + /*typeArguments*/ undefined, []), location); + } + /** + * Emits an empty instruction. + */ + function emitNop() { + emitWorker(0 /* Nop */); + } + /** + * Emits a Statement. + * + * @param node A statement. + */ + function emitStatement(node) { + if (node) { + emitWorker(1 /* Statement */, [node]); + } + else { + emitNop(); + } + } + /** + * Emits an Assignment operation. + * + * @param left The left-hand side of the assignment. + * @param right The right-hand side of the assignment. + * @param location An optional source map location for the assignment. + */ + function emitAssignment(left, right, location) { + emitWorker(2 /* Assign */, [left, right], location); + } + /** + * Emits a Break operation to the specified label. + * + * @param label A label. + * @param location An optional source map location for the assignment. + */ + function emitBreak(label, location) { + emitWorker(3 /* Break */, [label], location); + } + /** + * Emits a Break operation to the specified label when a condition evaluates to a truthy + * value at runtime. + * + * @param label A label. + * @param condition The condition. + * @param location An optional source map location for the assignment. + */ + function emitBreakWhenTrue(label, condition, location) { + emitWorker(4 /* BreakWhenTrue */, [label, condition], location); + } + /** + * Emits a Break to the specified label when a condition evaluates to a falsey value at + * runtime. + * + * @param label A label. + * @param condition The condition. + * @param location An optional source map location for the assignment. + */ + function emitBreakWhenFalse(label, condition, location) { + emitWorker(5 /* BreakWhenFalse */, [label, condition], location); + } + /** + * Emits a YieldStar operation for the provided expression. + * + * @param expression An optional value for the yield operation. + * @param location An optional source map location for the assignment. + */ + function emitYieldStar(expression, location) { + emitWorker(7 /* YieldStar */, [expression], location); + } + /** + * Emits a Yield operation for the provided expression. + * + * @param expression An optional value for the yield operation. + * @param location An optional source map location for the assignment. + */ + function emitYield(expression, location) { + emitWorker(6 /* Yield */, [expression], location); + } + /** + * Emits a Return operation for the provided expression. + * + * @param expression An optional value for the operation. + * @param location An optional source map location for the assignment. + */ + function emitReturn(expression, location) { + emitWorker(8 /* Return */, [expression], location); + } + /** + * Emits a Throw operation for the provided expression. + * + * @param expression A value for the operation. + * @param location An optional source map location for the assignment. + */ + function emitThrow(expression, location) { + emitWorker(9 /* Throw */, [expression], location); + } + /** + * Emits an Endfinally operation. This is used to handle `finally` block semantics. + */ + function emitEndfinally() { + emitWorker(10 /* Endfinally */); + } + /** + * Emits an operation. + * + * @param code The OpCode for the operation. + * @param args The optional arguments for the operation. + */ + function emitWorker(code, args, location) { + if (operations === undefined) { + operations = []; + operationArguments = []; + operationLocations = []; + } + if (labelOffsets === undefined) { + // mark entry point + markLabel(defineLabel()); + } + var operationIndex = operations.length; + operations[operationIndex] = code; + operationArguments[operationIndex] = args; + operationLocations[operationIndex] = location; + } + /** + * Builds the generator function body. + */ + function build() { + blockIndex = 0; + labelNumber = 0; + labelNumbers = undefined; + lastOperationWasAbrupt = false; + lastOperationWasCompletion = false; + clauses = undefined; + statements = undefined; + exceptionBlockStack = undefined; + currentExceptionBlock = undefined; + withBlockStack = undefined; + var buildResult = buildStatements(); + return createGeneratorHelper(context, ts.setEmitFlags(ts.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, state)], + /*type*/ undefined, ts.createBlock(buildResult, + /*multiLine*/ buildResult.length > 0)), 524288 /* ReuseTempVariableScope */)); + } + /** + * Builds the statements for the generator function body. + */ + function buildStatements() { + if (operations) { + for (var operationIndex = 0; operationIndex < operations.length; operationIndex++) { + writeOperation(operationIndex); + } + flushFinalLabel(operations.length); + } + else { + flushFinalLabel(0); + } + if (clauses) { + var labelExpression = ts.createPropertyAccess(state, "label"); + var switchStatement = ts.createSwitch(labelExpression, ts.createCaseBlock(clauses)); + return [ts.startOnNewLine(switchStatement)]; + } + if (statements) { + return statements; + } + return []; + } + /** + * Flush the current label and advance to a new label. + */ + function flushLabel() { + if (!statements) { + return; + } + appendLabel(/*markLabelEnd*/ !lastOperationWasAbrupt); + lastOperationWasAbrupt = false; + lastOperationWasCompletion = false; + labelNumber++; + } + /** + * Flush the final label of the generator function body. + */ + function flushFinalLabel(operationIndex) { + if (isFinalLabelReachable(operationIndex)) { + tryEnterLabel(operationIndex); + withBlockStack = undefined; + writeReturn(/*expression*/ undefined, /*operationLocation*/ undefined); + } + if (statements && clauses) { + appendLabel(/*markLabelEnd*/ false); + } + updateLabelExpressions(); + } + /** + * Tests whether the final label of the generator function body + * is reachable by user code. + */ + function isFinalLabelReachable(operationIndex) { + // if the last operation was *not* a completion (return/throw) then + // the final label is reachable. + if (!lastOperationWasCompletion) { + return true; + } + // if there are no labels defined or referenced, then the final label is + // not reachable. + if (!labelOffsets || !labelExpressions) { + return false; + } + // if the label for this offset is referenced, then the final label + // is reachable. + for (var label = 0; label < labelOffsets.length; label++) { + if (labelOffsets[label] === operationIndex && labelExpressions[label]) { + return true; + } + } + return false; + } + /** + * Appends a case clause for the last label and sets the new label. + * + * @param markLabelEnd Indicates that the transition between labels was a fall-through + * from a previous case clause and the change in labels should be + * reflected on the `state` object. + */ + function appendLabel(markLabelEnd) { + if (!clauses) { + clauses = []; + } + if (statements) { + if (withBlockStack) { + // The previous label was nested inside one or more `with` blocks, so we + // surround the statements in generated `with` blocks to create the same environment. + for (var i = withBlockStack.length - 1; i >= 0; i--) { + var withBlock = withBlockStack[i]; + statements = [ts.createWith(withBlock.expression, ts.createBlock(statements))]; + } + } + if (currentExceptionBlock) { + // The previous label was nested inside of an exception block, so we must + // indicate entry into a protected region by pushing the label numbers + // for each block in the protected region. + var startLabel = currentExceptionBlock.startLabel, catchLabel = currentExceptionBlock.catchLabel, finallyLabel = currentExceptionBlock.finallyLabel, endLabel = currentExceptionBlock.endLabel; + statements.unshift(ts.createExpressionStatement(ts.createCall(ts.createPropertyAccess(ts.createPropertyAccess(state, "trys"), "push"), + /*typeArguments*/ undefined, [ + ts.createArrayLiteral([ + createLabel(startLabel), + createLabel(catchLabel), + createLabel(finallyLabel), + createLabel(endLabel) + ]) + ]))); + currentExceptionBlock = undefined; + } + if (markLabelEnd) { + // The case clause for the last label falls through to this label, so we + // add an assignment statement to reflect the change in labels. + statements.push(ts.createExpressionStatement(ts.createAssignment(ts.createPropertyAccess(state, "label"), ts.createLiteral(labelNumber + 1)))); + } + } + clauses.push(ts.createCaseClause(ts.createLiteral(labelNumber), statements || [])); + statements = undefined; + } + /** + * Tries to enter into a new label at the current operation index. + */ + function tryEnterLabel(operationIndex) { + if (!labelOffsets) { + return; + } + for (var label = 0; label < labelOffsets.length; label++) { + if (labelOffsets[label] === operationIndex) { + flushLabel(); + if (labelNumbers === undefined) { + labelNumbers = []; + } + if (labelNumbers[labelNumber] === undefined) { + labelNumbers[labelNumber] = [label]; + } + else { + labelNumbers[labelNumber].push(label); + } + } + } + } + /** + * Updates literal expressions for labels with actual label numbers. + */ + function updateLabelExpressions() { + if (labelExpressions !== undefined && labelNumbers !== undefined) { + for (var labelNumber_1 = 0; labelNumber_1 < labelNumbers.length; labelNumber_1++) { + var labels = labelNumbers[labelNumber_1]; + if (labels !== undefined) { + for (var _i = 0, labels_1 = labels; _i < labels_1.length; _i++) { + var label = labels_1[_i]; + var expressions = labelExpressions[label]; + if (expressions !== undefined) { + for (var _a = 0, expressions_1 = expressions; _a < expressions_1.length; _a++) { + var expression = expressions_1[_a]; + expression.text = String(labelNumber_1); + } + } + } + } + } + } + } + /** + * Tries to enter or leave a code block. + */ + function tryEnterOrLeaveBlock(operationIndex) { + if (blocks) { + for (; blockIndex < blockActions.length && blockOffsets[blockIndex] <= operationIndex; blockIndex++) { + var block = blocks[blockIndex]; + var blockAction = blockActions[blockIndex]; + switch (block.kind) { + case 0 /* Exception */: + if (blockAction === 0 /* Open */) { + if (!exceptionBlockStack) { + exceptionBlockStack = []; + } + if (!statements) { + statements = []; + } + exceptionBlockStack.push(currentExceptionBlock); + currentExceptionBlock = block; + } + else if (blockAction === 1 /* Close */) { + currentExceptionBlock = exceptionBlockStack.pop(); + } + break; + case 1 /* With */: + if (blockAction === 0 /* Open */) { + if (!withBlockStack) { + withBlockStack = []; + } + withBlockStack.push(block); + } + else if (blockAction === 1 /* Close */) { + withBlockStack.pop(); + } + break; + // default: do nothing + } + } + } + } + /** + * Writes an operation as a statement to the current label's statement list. + * + * @param operation The OpCode of the operation + */ + function writeOperation(operationIndex) { + tryEnterLabel(operationIndex); + tryEnterOrLeaveBlock(operationIndex); + // early termination, nothing else to process in this label + if (lastOperationWasAbrupt) { + return; + } + lastOperationWasAbrupt = false; + lastOperationWasCompletion = false; + var opcode = operations[operationIndex]; + if (opcode === 0 /* Nop */) { + return; + } + else if (opcode === 10 /* Endfinally */) { + return writeEndfinally(); + } + var args = operationArguments[operationIndex]; + if (opcode === 1 /* Statement */) { + return writeStatement(args[0]); + } + var location = operationLocations[operationIndex]; + switch (opcode) { + case 2 /* Assign */: + return writeAssign(args[0], args[1], location); + case 3 /* Break */: + return writeBreak(args[0], location); + case 4 /* BreakWhenTrue */: + return writeBreakWhenTrue(args[0], args[1], location); + case 5 /* BreakWhenFalse */: + return writeBreakWhenFalse(args[0], args[1], location); + case 6 /* Yield */: + return writeYield(args[0], location); + case 7 /* YieldStar */: + return writeYieldStar(args[0], location); + case 8 /* Return */: + return writeReturn(args[0], location); + case 9 /* Throw */: + return writeThrow(args[0], location); + } + } + /** + * Writes a statement to the current label's statement list. + * + * @param statement A statement to write. + */ + function writeStatement(statement) { + if (statement) { + if (!statements) { + statements = [statement]; + } + else { + statements.push(statement); + } + } + } + /** + * Writes an Assign operation to the current label's statement list. + * + * @param left The left-hand side of the assignment. + * @param right The right-hand side of the assignment. + * @param operationLocation The source map location for the operation. + */ + function writeAssign(left, right, operationLocation) { + writeStatement(ts.setTextRange(ts.createExpressionStatement(ts.createAssignment(left, right)), operationLocation)); + } + /** + * Writes a Throw operation to the current label's statement list. + * + * @param expression The value to throw. + * @param operationLocation The source map location for the operation. + */ + function writeThrow(expression, operationLocation) { + lastOperationWasAbrupt = true; + lastOperationWasCompletion = true; + writeStatement(ts.setTextRange(ts.createThrow(expression), operationLocation)); + } + /** + * Writes a Return operation to the current label's statement list. + * + * @param expression The value to return. + * @param operationLocation The source map location for the operation. + */ + function writeReturn(expression, operationLocation) { + lastOperationWasAbrupt = true; + lastOperationWasCompletion = true; + writeStatement(ts.setEmitFlags(ts.setTextRange(ts.createReturn(ts.createArrayLiteral(expression + ? [createInstruction(2 /* Return */), expression] + : [createInstruction(2 /* Return */)])), operationLocation), 384 /* NoTokenSourceMaps */)); + } + /** + * Writes a Break operation to the current label's statement list. + * + * @param label The label for the Break. + * @param operationLocation The source map location for the operation. + */ + function writeBreak(label, operationLocation) { + lastOperationWasAbrupt = true; + writeStatement(ts.setEmitFlags(ts.setTextRange(ts.createReturn(ts.createArrayLiteral([ + createInstruction(3 /* Break */), + createLabel(label) + ])), operationLocation), 384 /* NoTokenSourceMaps */)); + } + /** + * Writes a BreakWhenTrue operation to the current label's statement list. + * + * @param label The label for the Break. + * @param condition The condition for the Break. + * @param operationLocation The source map location for the operation. + */ + function writeBreakWhenTrue(label, condition, operationLocation) { + writeStatement(ts.setEmitFlags(ts.createIf(condition, ts.setEmitFlags(ts.setTextRange(ts.createReturn(ts.createArrayLiteral([ + createInstruction(3 /* Break */), + createLabel(label) + ])), operationLocation), 384 /* NoTokenSourceMaps */)), 1 /* SingleLine */)); + } + /** + * Writes a BreakWhenFalse operation to the current label's statement list. + * + * @param label The label for the Break. + * @param condition The condition for the Break. + * @param operationLocation The source map location for the operation. + */ + function writeBreakWhenFalse(label, condition, operationLocation) { + writeStatement(ts.setEmitFlags(ts.createIf(ts.createLogicalNot(condition), ts.setEmitFlags(ts.setTextRange(ts.createReturn(ts.createArrayLiteral([ + createInstruction(3 /* Break */), + createLabel(label) + ])), operationLocation), 384 /* NoTokenSourceMaps */)), 1 /* SingleLine */)); + } + /** + * Writes a Yield operation to the current label's statement list. + * + * @param expression The expression to yield. + * @param operationLocation The source map location for the operation. + */ + function writeYield(expression, operationLocation) { + lastOperationWasAbrupt = true; + writeStatement(ts.setEmitFlags(ts.setTextRange(ts.createReturn(ts.createArrayLiteral(expression + ? [createInstruction(4 /* Yield */), expression] + : [createInstruction(4 /* Yield */)])), operationLocation), 384 /* NoTokenSourceMaps */)); + } + /** + * Writes a YieldStar instruction to the current label's statement list. + * + * @param expression The expression to yield. + * @param operationLocation The source map location for the operation. + */ + function writeYieldStar(expression, operationLocation) { + lastOperationWasAbrupt = true; + writeStatement(ts.setEmitFlags(ts.setTextRange(ts.createReturn(ts.createArrayLiteral([ + createInstruction(5 /* YieldStar */), + expression + ])), operationLocation), 384 /* NoTokenSourceMaps */)); + } + /** + * Writes an Endfinally instruction to the current label's statement list. + */ + function writeEndfinally() { + lastOperationWasAbrupt = true; + writeStatement(ts.createReturn(ts.createArrayLiteral([ + createInstruction(7 /* Endfinally */) + ]))); + } + } + ts.transformGenerators = transformGenerators; + function createGeneratorHelper(context, body) { + context.requestEmitHelper(generatorHelper); + return ts.createCall(ts.getHelperName("__generator"), + /*typeArguments*/ undefined, [ts.createThis(), body]); + } + // The __generator helper is used by down-level transformations to emulate the runtime + // semantics of an ES2015 generator function. When called, this helper returns an + // object that implements the Iterator protocol, in that it has `next`, `return`, and + // `throw` methods that step through the generator when invoked. + // + // parameters: + // @param thisArg The value to use as the `this` binding for the transformed generator body. + // @param body A function that acts as the transformed generator body. + // + // variables: + // _ Persistent state for the generator that is shared between the helper and the + // generator body. The state object has the following members: + // sent() - A method that returns or throws the current completion value. + // label - The next point at which to resume evaluation of the generator body. + // trys - A stack of protected regions (try/catch/finally blocks). + // ops - A stack of pending instructions when inside of a finally block. + // f A value indicating whether the generator is executing. + // y An iterator to delegate for a yield*. + // t A temporary variable that holds one of the following values (note that these + // cases do not overlap): + // - The completion value when resuming from a `yield` or `yield*`. + // - The error value for a catch block. + // - The current protected region (array of try/catch/finally/end labels). + // - The verb (`next`, `throw`, or `return` method) to delegate to the expression + // of a `yield*`. + // - The result of evaluating the verb delegated to the expression of a `yield*`. + // + // functions: + // verb(n) Creates a bound callback to the `step` function for opcode `n`. + // step(op) Evaluates opcodes in a generator body until execution is suspended or + // completed. + // + // The __generator helper understands a limited set of instructions: + // 0: next(value?) - Start or resume the generator with the specified value. + // 1: throw(error) - Resume the generator with an exception. If the generator is + // suspended inside of one or more protected regions, evaluates + // any intervening finally blocks between the current label and + // the nearest catch block or function boundary. If uncaught, the + // exception is thrown to the caller. + // 2: return(value?) - Resume the generator as if with a return. If the generator is + // suspended inside of one or more protected regions, evaluates any + // intervening finally blocks. + // 3: break(label) - Jump to the specified label. If the label is outside of the + // current protected region, evaluates any intervening finally + // blocks. + // 4: yield(value?) - Yield execution to the caller with an optional value. When + // resumed, the generator will continue at the next label. + // 5: yield*(value) - Delegates evaluation to the supplied iterator. When + // delegation completes, the generator will continue at the next + // label. + // 6: catch(error) - Handles an exception thrown from within the generator body. If + // the current label is inside of one or more protected regions, + // evaluates any intervening finally blocks between the current + // label and the nearest catch block or function boundary. If + // uncaught, the exception is thrown to the caller. + // 7: endfinally - Ends a finally block, resuming the last instruction prior to + // entering a finally block. + // + // For examples of how these are used, see the comments in ./transformers/generators.ts + var generatorHelper = { + name: "typescript:generator", + scoped: false, + priority: 6, + text: "\n var __generator = (this && this.__generator) || function (thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (_) try {\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [op[0] & 2, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n };" + }; +})(ts || (ts = {})); +/*@internal*/ +var ts; +(function (ts) { + function transformModule(context) { + function getTransformModuleDelegate(moduleKind) { + switch (moduleKind) { + case ts.ModuleKind.AMD: return transformAMDModule; + case ts.ModuleKind.UMD: return transformUMDModule; + default: return transformCommonJSModule; + } + } + var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; + var compilerOptions = context.getCompilerOptions(); + var resolver = context.getEmitResolver(); + var host = context.getEmitHost(); + var languageVersion = ts.getEmitScriptTarget(compilerOptions); + var moduleKind = ts.getEmitModuleKind(compilerOptions); + var previousOnSubstituteNode = context.onSubstituteNode; + var previousOnEmitNode = context.onEmitNode; + context.onSubstituteNode = onSubstituteNode; + context.onEmitNode = onEmitNode; + context.enableSubstitution(72 /* Identifier */); // Substitutes expression identifiers with imported/exported symbols. + context.enableSubstitution(204 /* BinaryExpression */); // Substitutes assignments to exported symbols. + context.enableSubstitution(202 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols. + context.enableSubstitution(203 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols. + context.enableSubstitution(276 /* ShorthandPropertyAssignment */); // Substitutes shorthand property assignments for imported/exported symbols. + context.enableEmitNotification(279 /* SourceFile */); // Restore state when substituting nodes in a file. + var moduleInfoMap = []; // The ExternalModuleInfo for each file. + var deferredExports = []; // Exports to defer until an EndOfDeclarationMarker is found. + var currentSourceFile; // The current file. + var currentModuleInfo; // The ExternalModuleInfo for the current file. + var noSubstitution; // Set of nodes for which substitution rules should be ignored. + var needUMDDynamicImportHelper; + return ts.chainBundle(transformSourceFile); + /** + * Transforms the module aspects of a SourceFile. + * + * @param node The SourceFile node. + */ + function transformSourceFile(node) { + if (node.isDeclarationFile || + !(ts.isEffectiveExternalModule(node, compilerOptions) || + node.transformFlags & 16777216 /* ContainsDynamicImport */ || + (ts.isJsonSourceFile(node) && ts.hasJsonModuleEmitEnabled(compilerOptions) && (compilerOptions.out || compilerOptions.outFile)))) { + return node; + } + currentSourceFile = node; + currentModuleInfo = ts.collectExternalModuleInfo(node, resolver, compilerOptions); + moduleInfoMap[ts.getOriginalNodeId(node)] = currentModuleInfo; + // Perform the transformation. + var transformModule = getTransformModuleDelegate(moduleKind); + var updated = transformModule(node); + currentSourceFile = undefined; + currentModuleInfo = undefined; + needUMDDynamicImportHelper = false; + return ts.aggregateTransformFlags(updated); + } + function shouldEmitUnderscoreUnderscoreESModule() { + if (!currentModuleInfo.exportEquals && ts.isExternalModule(currentSourceFile)) { + return true; + } + return false; + } + /** + * Transforms a SourceFile into a CommonJS module. + * + * @param node The SourceFile node. + */ + function transformCommonJSModule(node) { + startLexicalEnvironment(); + var statements = []; + var ensureUseStrict = ts.getStrictOptionValue(compilerOptions, "alwaysStrict") || (!compilerOptions.noImplicitUseStrict && ts.isExternalModule(currentSourceFile)); + var statementOffset = ts.addPrologue(statements, node.statements, ensureUseStrict, sourceElementVisitor); + if (shouldEmitUnderscoreUnderscoreESModule()) { + ts.append(statements, createUnderscoreUnderscoreESModule()); + } + ts.append(statements, ts.visitNode(currentModuleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement)); + ts.addRange(statements, ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset)); + addExportEqualsIfNeeded(statements, /*emitAsReturn*/ false); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + var updated = ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements)); + if (currentModuleInfo.hasExportStarsToExportValues && !compilerOptions.importHelpers) { + // If we have any `export * from ...` declarations + // we need to inform the emitter to add the __export helper. + ts.addEmitHelper(updated, exportStarHelper); + } + ts.addEmitHelpers(updated, context.readEmitHelpers()); + return updated; + } + /** + * Transforms a SourceFile into an AMD module. + * + * @param node The SourceFile node. + */ + function transformAMDModule(node) { + var define = ts.createIdentifier("define"); + var moduleName = ts.tryGetModuleNameFromFile(node, host, compilerOptions); + var jsonSourceFile = ts.isJsonSourceFile(node) && node; + // An AMD define function has the following shape: + // + // define(id?, dependencies?, factory); + // + // This has the shape of the following: + // + // define(name, ["module1", "module2"], function (module1Alias) { ... } + // + // The location of the alias in the parameter list in the factory function needs to + // match the position of the module name in the dependency list. + // + // To ensure this is true in cases of modules with no aliases, e.g.: + // + // import "module" + // + // or + // + // /// + // + // we need to add modules without alias names to the end of the dependencies list + var _a = collectAsynchronousDependencies(node, /*includeNonAmdDependencies*/ true), aliasedModuleNames = _a.aliasedModuleNames, unaliasedModuleNames = _a.unaliasedModuleNames, importAliasNames = _a.importAliasNames; + // Create an updated SourceFile: + // + // define(moduleName?, ["module1", "module2"], function ... + var updated = ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray([ + ts.createExpressionStatement(ts.createCall(define, + /*typeArguments*/ undefined, (moduleName ? [moduleName] : []).concat([ + // Add the dependency array argument: + // + // ["require", "exports", module1", "module2", ...] + ts.createArrayLiteral(jsonSourceFile ? ts.emptyArray : [ + ts.createLiteral("require"), + ts.createLiteral("exports") + ].concat(aliasedModuleNames, unaliasedModuleNames)), + // Add the module body function argument: + // + // function (require, exports, module1, module2) ... + jsonSourceFile ? + jsonSourceFile.statements.length ? jsonSourceFile.statements[0].expression : ts.createObjectLiteral() : + ts.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, [ + ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "require"), + ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "exports") + ].concat(importAliasNames), + /*type*/ undefined, transformAsynchronousModuleBody(node)) + ]))) + ]), + /*location*/ node.statements)); + ts.addEmitHelpers(updated, context.readEmitHelpers()); + return updated; + } + /** + * Transforms a SourceFile into a UMD module. + * + * @param node The SourceFile node. + */ + function transformUMDModule(node) { + var _a = collectAsynchronousDependencies(node, /*includeNonAmdDependencies*/ false), aliasedModuleNames = _a.aliasedModuleNames, unaliasedModuleNames = _a.unaliasedModuleNames, importAliasNames = _a.importAliasNames; + var moduleName = ts.tryGetModuleNameFromFile(node, host, compilerOptions); + var umdHeader = ts.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "factory")], + /*type*/ undefined, ts.setTextRange(ts.createBlock([ + ts.createIf(ts.createLogicalAnd(ts.createTypeCheck(ts.createIdentifier("module"), "object"), ts.createTypeCheck(ts.createPropertyAccess(ts.createIdentifier("module"), "exports"), "object")), ts.createBlock([ + ts.createVariableStatement( + /*modifiers*/ undefined, [ + ts.createVariableDeclaration("v", + /*type*/ undefined, ts.createCall(ts.createIdentifier("factory"), + /*typeArguments*/ undefined, [ + ts.createIdentifier("require"), + ts.createIdentifier("exports") + ])) + ]), + ts.setEmitFlags(ts.createIf(ts.createStrictInequality(ts.createIdentifier("v"), ts.createIdentifier("undefined")), ts.createExpressionStatement(ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier("module"), "exports"), ts.createIdentifier("v")))), 1 /* SingleLine */) + ]), ts.createIf(ts.createLogicalAnd(ts.createTypeCheck(ts.createIdentifier("define"), "function"), ts.createPropertyAccess(ts.createIdentifier("define"), "amd")), ts.createBlock([ + ts.createExpressionStatement(ts.createCall(ts.createIdentifier("define"), + /*typeArguments*/ undefined, (moduleName ? [moduleName] : []).concat([ + ts.createArrayLiteral([ + ts.createLiteral("require"), + ts.createLiteral("exports") + ].concat(aliasedModuleNames, unaliasedModuleNames)), + ts.createIdentifier("factory") + ]))) + ]))) + ], + /*multiLine*/ true), + /*location*/ undefined)); + // Create an updated SourceFile: + // + // (function (factory) { + // if (typeof module === "object" && typeof module.exports === "object") { + // var v = factory(require, exports); + // if (v !== undefined) module.exports = v; + // } + // else if (typeof define === 'function' && define.amd) { + // define(["require", "exports"], factory); + // } + // })(function ...) + var updated = ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray([ + ts.createExpressionStatement(ts.createCall(umdHeader, + /*typeArguments*/ undefined, [ + // Add the module body function argument: + // + // function (require, exports) ... + ts.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, [ + ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "require"), + ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "exports") + ].concat(importAliasNames), + /*type*/ undefined, transformAsynchronousModuleBody(node)) + ])) + ]), + /*location*/ node.statements)); + ts.addEmitHelpers(updated, context.readEmitHelpers()); + return updated; + } + /** + * Collect the additional asynchronous dependencies for the module. + * + * @param node The source file. + * @param includeNonAmdDependencies A value indicating whether to include non-AMD dependencies. + */ + function collectAsynchronousDependencies(node, includeNonAmdDependencies) { + // names of modules with corresponding parameter in the factory function + var aliasedModuleNames = []; + // names of modules with no corresponding parameters in factory function + var unaliasedModuleNames = []; + // names of the parameters in the factory function; these + // parameters need to match the indexes of the corresponding + // module names in aliasedModuleNames. + var importAliasNames = []; + // Fill in amd-dependency tags + for (var _i = 0, _a = node.amdDependencies; _i < _a.length; _i++) { + var amdDependency = _a[_i]; + if (amdDependency.name) { + aliasedModuleNames.push(ts.createLiteral(amdDependency.path)); + importAliasNames.push(ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, amdDependency.name)); + } + else { + unaliasedModuleNames.push(ts.createLiteral(amdDependency.path)); + } + } + for (var _b = 0, _c = currentModuleInfo.externalImports; _b < _c.length; _b++) { + var importNode = _c[_b]; + // Find the name of the external module + var externalModuleName = ts.getExternalModuleNameLiteral(importNode, currentSourceFile, host, resolver, compilerOptions); + // Find the name of the module alias, if there is one + var importAliasName = ts.getLocalNameForExternalImport(importNode, currentSourceFile); + // It is possible that externalModuleName is undefined if it is not string literal. + // This can happen in the invalid import syntax. + // E.g : "import * from alias from 'someLib';" + if (externalModuleName) { + if (includeNonAmdDependencies && importAliasName) { + // Set emitFlags on the name of the classDeclaration + // This is so that when printer will not substitute the identifier + ts.setEmitFlags(importAliasName, 4 /* NoSubstitution */); + aliasedModuleNames.push(externalModuleName); + importAliasNames.push(ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, importAliasName)); + } + else { + unaliasedModuleNames.push(externalModuleName); + } + } + } + return { aliasedModuleNames: aliasedModuleNames, unaliasedModuleNames: unaliasedModuleNames, importAliasNames: importAliasNames }; + } + function getAMDImportExpressionForImport(node) { + if (ts.isImportEqualsDeclaration(node) || ts.isExportDeclaration(node) || !ts.getExternalModuleNameLiteral(node, currentSourceFile, host, resolver, compilerOptions)) { + return undefined; + } + var name = ts.getLocalNameForExternalImport(node, currentSourceFile); // TODO: GH#18217 + var expr = getHelperExpressionForImport(node, name); + if (expr === name) { + return undefined; + } + return ts.createExpressionStatement(ts.createAssignment(name, expr)); + } + /** + * Transforms a SourceFile into an AMD or UMD module body. + * + * @param node The SourceFile node. + */ + function transformAsynchronousModuleBody(node) { + startLexicalEnvironment(); + var statements = []; + var statementOffset = ts.addPrologue(statements, node.statements, /*ensureUseStrict*/ !compilerOptions.noImplicitUseStrict, sourceElementVisitor); + if (shouldEmitUnderscoreUnderscoreESModule()) { + ts.append(statements, createUnderscoreUnderscoreESModule()); + } + // Visit each statement of the module body. + ts.append(statements, ts.visitNode(currentModuleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement)); + if (moduleKind === ts.ModuleKind.AMD) { + ts.addRange(statements, ts.mapDefined(currentModuleInfo.externalImports, getAMDImportExpressionForImport)); + } + ts.addRange(statements, ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset)); + // Append the 'export =' statement if provided. + addExportEqualsIfNeeded(statements, /*emitAsReturn*/ true); + // End the lexical environment for the module body + // and merge any new lexical declarations. + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + var body = ts.createBlock(statements, /*multiLine*/ true); + if (currentModuleInfo.hasExportStarsToExportValues && !compilerOptions.importHelpers) { + // If we have any `export * from ...` declarations + // we need to inform the emitter to add the __export helper. + ts.addEmitHelper(body, exportStarHelper); + } + if (needUMDDynamicImportHelper) { + ts.addEmitHelper(body, dynamicImportUMDHelper); + } + return body; + } + /** + * Adds the down-level representation of `export=` to the statement list if one exists + * in the source file. + * + * @param statements The Statement list to modify. + * @param emitAsReturn A value indicating whether to emit the `export=` statement as a + * return statement. + */ + function addExportEqualsIfNeeded(statements, emitAsReturn) { + if (currentModuleInfo.exportEquals) { + var expressionResult = ts.visitNode(currentModuleInfo.exportEquals.expression, moduleExpressionElementVisitor); + if (expressionResult) { + if (emitAsReturn) { + var statement = ts.createReturn(expressionResult); + ts.setTextRange(statement, currentModuleInfo.exportEquals); + ts.setEmitFlags(statement, 384 /* NoTokenSourceMaps */ | 1536 /* NoComments */); + statements.push(statement); + } + else { + var statement = ts.createExpressionStatement(ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier("module"), "exports"), expressionResult)); + ts.setTextRange(statement, currentModuleInfo.exportEquals); + ts.setEmitFlags(statement, 1536 /* NoComments */); + statements.push(statement); + } + } + } + } + // + // Top-Level Source Element Visitors + // + /** + * Visits a node at the top level of the source file. + * + * @param node The node to visit. + */ + function sourceElementVisitor(node) { + switch (node.kind) { + case 249 /* ImportDeclaration */: + return visitImportDeclaration(node); + case 248 /* ImportEqualsDeclaration */: + return visitImportEqualsDeclaration(node); + case 255 /* ExportDeclaration */: + return visitExportDeclaration(node); + case 254 /* ExportAssignment */: + return visitExportAssignment(node); + case 219 /* VariableStatement */: + return visitVariableStatement(node); + case 239 /* FunctionDeclaration */: + return visitFunctionDeclaration(node); + case 240 /* ClassDeclaration */: + return visitClassDeclaration(node); + case 310 /* MergeDeclarationMarker */: + return visitMergeDeclarationMarker(node); + case 311 /* EndOfDeclarationMarker */: + return visitEndOfDeclarationMarker(node); + default: + return ts.visitEachChild(node, moduleExpressionElementVisitor, context); + } + } + function moduleExpressionElementVisitor(node) { + // This visitor does not need to descend into the tree if there is no dynamic import or destructuring assignment, + // as export/import statements are only transformed at the top level of a file. + if (!(node.transformFlags & 16777216 /* ContainsDynamicImport */) && !(node.transformFlags & 2048 /* ContainsDestructuringAssignment */)) { + return node; + } + if (ts.isImportCall(node)) { + return visitImportCallExpression(node); + } + else if (node.transformFlags & 1024 /* DestructuringAssignment */ && ts.isBinaryExpression(node)) { + return visitDestructuringAssignment(node); + } + else { + return ts.visitEachChild(node, moduleExpressionElementVisitor, context); + } + } + function destructuringNeedsFlattening(node) { + if (ts.isObjectLiteralExpression(node)) { + for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { + var elem = _a[_i]; + switch (elem.kind) { + case 275 /* PropertyAssignment */: + if (destructuringNeedsFlattening(elem.initializer)) { + return true; + } + break; + case 276 /* ShorthandPropertyAssignment */: + if (destructuringNeedsFlattening(elem.name)) { + return true; + } + break; + case 277 /* SpreadAssignment */: + if (destructuringNeedsFlattening(elem.expression)) { + return true; + } + break; + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + return false; + default: ts.Debug.assertNever(elem, "Unhandled object member kind"); + } + } + } + else if (ts.isArrayLiteralExpression(node)) { + for (var _b = 0, _c = node.elements; _b < _c.length; _b++) { + var elem = _c[_b]; + if (ts.isSpreadElement(elem)) { + if (destructuringNeedsFlattening(elem.expression)) { + return true; + } + } + else if (destructuringNeedsFlattening(elem)) { + return true; + } + } + } + else if (ts.isIdentifier(node)) { + return ts.length(getExports(node)) > (ts.isExportName(node) ? 1 : 0); + } + return false; + } + function visitDestructuringAssignment(node) { + if (destructuringNeedsFlattening(node.left)) { + return ts.flattenDestructuringAssignment(node, moduleExpressionElementVisitor, context, 0 /* All */, /*needsValue*/ false, createAllExportExpressions); + } + return ts.visitEachChild(node, moduleExpressionElementVisitor, context); + } + function visitImportCallExpression(node) { + var argument = ts.visitNode(ts.firstOrUndefined(node.arguments), moduleExpressionElementVisitor); + var containsLexicalThis = !!(node.transformFlags & 8192 /* ContainsLexicalThis */); + switch (compilerOptions.module) { + case ts.ModuleKind.AMD: + return createImportCallExpressionAMD(argument, containsLexicalThis); + case ts.ModuleKind.UMD: + return createImportCallExpressionUMD(argument, containsLexicalThis); + case ts.ModuleKind.CommonJS: + default: + return createImportCallExpressionCommonJS(argument, containsLexicalThis); + } + } + function createImportCallExpressionUMD(arg, containsLexicalThis) { + // (function (factory) { + // ... (regular UMD) + // } + // })(function (require, exports, useSyncRequire) { + // "use strict"; + // Object.defineProperty(exports, "__esModule", { value: true }); + // var __syncRequire = typeof module === "object" && typeof module.exports === "object"; + // var __resolved = new Promise(function (resolve) { resolve(); }); + // ..... + // __syncRequire + // ? __resolved.then(function () { return require(x); }) /*CommonJs Require*/ + // : new Promise(function (_a, _b) { require([x], _a, _b); }); /*Amd Require*/ + // }); + needUMDDynamicImportHelper = true; + if (ts.isSimpleCopiableExpression(arg)) { + var argClone = ts.isGeneratedIdentifier(arg) ? arg : ts.isStringLiteral(arg) ? ts.createLiteral(arg) : ts.setEmitFlags(ts.setTextRange(ts.getSynthesizedClone(arg), arg), 1536 /* NoComments */); + return ts.createConditional( + /*condition*/ ts.createIdentifier("__syncRequire"), + /*whenTrue*/ createImportCallExpressionCommonJS(arg, containsLexicalThis), + /*whenFalse*/ createImportCallExpressionAMD(argClone, containsLexicalThis)); + } + else { + var temp = ts.createTempVariable(hoistVariableDeclaration); + return ts.createComma(ts.createAssignment(temp, arg), ts.createConditional( + /*condition*/ ts.createIdentifier("__syncRequire"), + /*whenTrue*/ createImportCallExpressionCommonJS(temp, containsLexicalThis), + /*whenFalse*/ createImportCallExpressionAMD(temp, containsLexicalThis))); + } + } + function createImportCallExpressionAMD(arg, containsLexicalThis) { + // improt("./blah") + // emit as + // define(["require", "exports", "blah"], function (require, exports) { + // ... + // new Promise(function (_a, _b) { require([x], _a, _b); }); /*Amd Require*/ + // }); + var resolve = ts.createUniqueName("resolve"); + var reject = ts.createUniqueName("reject"); + var parameters = [ + ts.createParameter(/*decorator*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, /*name*/ resolve), + ts.createParameter(/*decorator*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, /*name*/ reject) + ]; + var body = ts.createBlock([ + ts.createExpressionStatement(ts.createCall(ts.createIdentifier("require"), + /*typeArguments*/ undefined, [ts.createArrayLiteral([arg || ts.createOmittedExpression()]), resolve, reject])) + ]); + var func; + if (languageVersion >= 2 /* ES2015 */) { + func = ts.createArrowFunction( + /*modifiers*/ undefined, + /*typeParameters*/ undefined, parameters, + /*type*/ undefined, + /*equalsGreaterThanToken*/ undefined, body); + } + else { + func = ts.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, parameters, + /*type*/ undefined, body); + // if there is a lexical 'this' in the import call arguments, ensure we indicate + // that this new function expression indicates it captures 'this' so that the + // es2015 transformer will properly substitute 'this' with '_this'. + if (containsLexicalThis) { + ts.setEmitFlags(func, 8 /* CapturesThis */); + } + } + var promise = ts.createNew(ts.createIdentifier("Promise"), /*typeArguments*/ undefined, [func]); + if (compilerOptions.esModuleInterop) { + context.requestEmitHelper(importStarHelper); + return ts.createCall(ts.createPropertyAccess(promise, ts.createIdentifier("then")), /*typeArguments*/ undefined, [ts.getHelperName("__importStar")]); + } + return promise; + } + function createImportCallExpressionCommonJS(arg, containsLexicalThis) { + // import("./blah") + // emit as + // Promise.resolve().then(function () { return require(x); }) /*CommonJs Require*/ + // We have to wrap require in then callback so that require is done in asynchronously + // if we simply do require in resolve callback in Promise constructor. We will execute the loading immediately + var promiseResolveCall = ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Promise"), "resolve"), /*typeArguments*/ undefined, /*argumentsArray*/ []); + var requireCall = ts.createCall(ts.createIdentifier("require"), /*typeArguments*/ undefined, arg ? [arg] : []); + if (compilerOptions.esModuleInterop) { + context.requestEmitHelper(importStarHelper); + requireCall = ts.createCall(ts.getHelperName("__importStar"), /*typeArguments*/ undefined, [requireCall]); + } + var func; + if (languageVersion >= 2 /* ES2015 */) { + func = ts.createArrowFunction( + /*modifiers*/ undefined, + /*typeParameters*/ undefined, + /*parameters*/ [], + /*type*/ undefined, + /*equalsGreaterThanToken*/ undefined, requireCall); + } + else { + func = ts.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, + /*parameters*/ [], + /*type*/ undefined, ts.createBlock([ts.createReturn(requireCall)])); + // if there is a lexical 'this' in the import call arguments, ensure we indicate + // that this new function expression indicates it captures 'this' so that the + // es2015 transformer will properly substitute 'this' with '_this'. + if (containsLexicalThis) { + ts.setEmitFlags(func, 8 /* CapturesThis */); + } + } + return ts.createCall(ts.createPropertyAccess(promiseResolveCall, "then"), /*typeArguments*/ undefined, [func]); + } + function getHelperExpressionForImport(node, innerExpr) { + if (!compilerOptions.esModuleInterop || ts.getEmitFlags(node) & 67108864 /* NeverApplyImportHelper */) { + return innerExpr; + } + if (ts.getImportNeedsImportStarHelper(node)) { + context.requestEmitHelper(importStarHelper); + return ts.createCall(ts.getHelperName("__importStar"), /*typeArguments*/ undefined, [innerExpr]); + } + if (ts.getImportNeedsImportDefaultHelper(node)) { + context.requestEmitHelper(importDefaultHelper); + return ts.createCall(ts.getHelperName("__importDefault"), /*typeArguments*/ undefined, [innerExpr]); + } + return innerExpr; + } + /** + * Visits an ImportDeclaration node. + * + * @param node The node to visit. + */ + function visitImportDeclaration(node) { + var statements; + var namespaceDeclaration = ts.getNamespaceDeclarationNode(node); + if (moduleKind !== ts.ModuleKind.AMD) { + if (!node.importClause) { + // import "mod"; + return ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(createRequireCall(node)), node), node); + } + else { + var variables = []; + if (namespaceDeclaration && !ts.isDefaultImport(node)) { + // import * as n from "mod"; + variables.push(ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name), + /*type*/ undefined, getHelperExpressionForImport(node, createRequireCall(node)))); + } + else { + // import d from "mod"; + // import { x, y } from "mod"; + // import d, { x, y } from "mod"; + // import d, * as n from "mod"; + variables.push(ts.createVariableDeclaration(ts.getGeneratedNameForNode(node), + /*type*/ undefined, getHelperExpressionForImport(node, createRequireCall(node)))); + if (namespaceDeclaration && ts.isDefaultImport(node)) { + variables.push(ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name), + /*type*/ undefined, ts.getGeneratedNameForNode(node))); + } + } + statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList(variables, languageVersion >= 2 /* ES2015 */ ? 2 /* Const */ : 0 /* None */)), + /*location*/ node), + /*original*/ node)); + } + } + else if (namespaceDeclaration && ts.isDefaultImport(node)) { + // import d, * as n from "mod"; + statements = ts.append(statements, ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ + ts.setOriginalNode(ts.setTextRange(ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name), + /*type*/ undefined, ts.getGeneratedNameForNode(node)), + /*location*/ node), + /*original*/ node) + ], languageVersion >= 2 /* ES2015 */ ? 2 /* Const */ : 0 /* None */))); + } + if (hasAssociatedEndOfDeclarationMarker(node)) { + // Defer exports until we encounter an EndOfDeclarationMarker node + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportsOfImportDeclaration(deferredExports[id], node); + } + else { + statements = appendExportsOfImportDeclaration(statements, node); + } + return ts.singleOrMany(statements); + } + /** + * Creates a `require()` call to import an external module. + * + * @param importNode The declararation to import. + */ + function createRequireCall(importNode) { + var moduleName = ts.getExternalModuleNameLiteral(importNode, currentSourceFile, host, resolver, compilerOptions); + var args = []; + if (moduleName) { + args.push(moduleName); + } + return ts.createCall(ts.createIdentifier("require"), /*typeArguments*/ undefined, args); + } + /** + * Visits an ImportEqualsDeclaration node. + * + * @param node The node to visit. + */ + function visitImportEqualsDeclaration(node) { + ts.Debug.assert(ts.isExternalModuleImportEqualsDeclaration(node), "import= for internal module references should be handled in an earlier transformer."); + var statements; + if (moduleKind !== ts.ModuleKind.AMD) { + if (ts.hasModifier(node, 1 /* Export */)) { + statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(createExportExpression(node.name, createRequireCall(node))), node), node)); + } + else { + statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(ts.getSynthesizedClone(node.name), + /*type*/ undefined, createRequireCall(node)) + ], + /*flags*/ languageVersion >= 2 /* ES2015 */ ? 2 /* Const */ : 0 /* None */)), node), node)); + } + } + else { + if (ts.hasModifier(node, 1 /* Export */)) { + statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(createExportExpression(ts.getExportName(node), ts.getLocalName(node))), node), node)); + } + } + if (hasAssociatedEndOfDeclarationMarker(node)) { + // Defer exports until we encounter an EndOfDeclarationMarker node + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportsOfImportEqualsDeclaration(deferredExports[id], node); + } + else { + statements = appendExportsOfImportEqualsDeclaration(statements, node); + } + return ts.singleOrMany(statements); + } + /** + * Visits an ExportDeclaration node. + * + * @param The node to visit. + */ + function visitExportDeclaration(node) { + if (!node.moduleSpecifier) { + // Elide export declarations with no module specifier as they are handled + // elsewhere. + return undefined; + } + var generatedName = ts.getGeneratedNameForNode(node); + if (node.exportClause) { + var statements = []; + // export { x, y } from "mod"; + if (moduleKind !== ts.ModuleKind.AMD) { + statements.push(ts.setOriginalNode(ts.setTextRange(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(generatedName, + /*type*/ undefined, createRequireCall(node)) + ])), + /*location*/ node), + /* original */ node)); + } + for (var _i = 0, _a = node.exportClause.elements; _i < _a.length; _i++) { + var specifier = _a[_i]; + var exportedValue = ts.createPropertyAccess(generatedName, specifier.propertyName || specifier.name); + statements.push(ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(createExportExpression(ts.getExportName(specifier), exportedValue)), specifier), specifier)); + } + return ts.singleOrMany(statements); + } + else { + // export * from "mod"; + return ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(createExportStarHelper(context, moduleKind !== ts.ModuleKind.AMD ? createRequireCall(node) : generatedName)), node), node); + } + } + /** + * Visits an ExportAssignment node. + * + * @param node The node to visit. + */ + function visitExportAssignment(node) { + if (node.isExportEquals) { + return undefined; + } + var statements; + var original = node.original; + if (original && hasAssociatedEndOfDeclarationMarker(original)) { + // Defer exports until we encounter an EndOfDeclarationMarker node + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportStatement(deferredExports[id], ts.createIdentifier("default"), ts.visitNode(node.expression, moduleExpressionElementVisitor), /*location*/ node, /*allowComments*/ true); + } + else { + statements = appendExportStatement(statements, ts.createIdentifier("default"), ts.visitNode(node.expression, moduleExpressionElementVisitor), /*location*/ node, /*allowComments*/ true); + } + return ts.singleOrMany(statements); + } + /** + * Visits a FunctionDeclaration node. + * + * @param node The node to visit. + */ + function visitFunctionDeclaration(node) { + var statements; + if (ts.hasModifier(node, 1 /* Export */)) { + statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createFunctionDeclaration( + /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, ts.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true), + /*typeParameters*/ undefined, ts.visitNodes(node.parameters, moduleExpressionElementVisitor), + /*type*/ undefined, ts.visitEachChild(node.body, moduleExpressionElementVisitor, context)), + /*location*/ node), + /*original*/ node)); + } + else { + statements = ts.append(statements, ts.visitEachChild(node, moduleExpressionElementVisitor, context)); + } + if (hasAssociatedEndOfDeclarationMarker(node)) { + // Defer exports until we encounter an EndOfDeclarationMarker node + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node); + } + else { + statements = appendExportsOfHoistedDeclaration(statements, node); + } + return ts.singleOrMany(statements); + } + /** + * Visits a ClassDeclaration node. + * + * @param node The node to visit. + */ + function visitClassDeclaration(node) { + var statements; + if (ts.hasModifier(node, 1 /* Export */)) { + statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createClassDeclaration( + /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true), + /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, moduleExpressionElementVisitor), ts.visitNodes(node.members, moduleExpressionElementVisitor)), node), node)); + } + else { + statements = ts.append(statements, ts.visitEachChild(node, moduleExpressionElementVisitor, context)); + } + if (hasAssociatedEndOfDeclarationMarker(node)) { + // Defer exports until we encounter an EndOfDeclarationMarker node + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node); + } + else { + statements = appendExportsOfHoistedDeclaration(statements, node); + } + return ts.singleOrMany(statements); + } + /** + * Visits a VariableStatement node. + * + * @param node The node to visit. + */ + function visitVariableStatement(node) { + var statements; + var variables; + var expressions; + if (ts.hasModifier(node, 1 /* Export */)) { + var modifiers = void 0; + // If we're exporting these variables, then these just become assignments to 'exports.x'. + // We only want to emit assignments for variables with initializers. + for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { + var variable = _a[_i]; + if (ts.isIdentifier(variable.name) && ts.isLocalName(variable.name)) { + if (!modifiers) { + modifiers = ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier); + } + variables = ts.append(variables, variable); + } + else if (variable.initializer) { + expressions = ts.append(expressions, transformInitializedVariable(variable)); + } + } + if (variables) { + statements = ts.append(statements, ts.updateVariableStatement(node, modifiers, ts.updateVariableDeclarationList(node.declarationList, variables))); + } + if (expressions) { + statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(ts.inlineExpressions(expressions)), node), node)); + } + } + else { + statements = ts.append(statements, ts.visitEachChild(node, moduleExpressionElementVisitor, context)); + } + if (hasAssociatedEndOfDeclarationMarker(node)) { + // Defer exports until we encounter an EndOfDeclarationMarker node + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node); + } + else { + statements = appendExportsOfVariableStatement(statements, node); + } + return ts.singleOrMany(statements); + } + function createAllExportExpressions(name, value, location) { + var exportedNames = getExports(name); + if (exportedNames) { + // For each additional export of the declaration, apply an export assignment. + var expression = ts.isExportName(name) ? value : ts.createAssignment(name, value); + for (var _i = 0, exportedNames_1 = exportedNames; _i < exportedNames_1.length; _i++) { + var exportName = exportedNames_1[_i]; + // Mark the node to prevent triggering substitution. + ts.setEmitFlags(expression, 4 /* NoSubstitution */); + expression = createExportExpression(exportName, expression, /*location*/ location); + } + return expression; + } + return ts.createAssignment(name, value); + } + /** + * Transforms an exported variable with an initializer into an expression. + * + * @param node The node to transform. + */ + function transformInitializedVariable(node) { + if (ts.isBindingPattern(node.name)) { + return ts.flattenDestructuringAssignment(ts.visitNode(node, moduleExpressionElementVisitor), + /*visitor*/ undefined, context, 0 /* All */, + /*needsValue*/ false, createAllExportExpressions); + } + else { + return ts.createAssignment(ts.setTextRange(ts.createPropertyAccess(ts.createIdentifier("exports"), node.name), + /*location*/ node.name), ts.visitNode(node.initializer, moduleExpressionElementVisitor)); + } + } + /** + * Visits a MergeDeclarationMarker used as a placeholder for the beginning of a merged + * and transformed declaration. + * + * @param node The node to visit. + */ + function visitMergeDeclarationMarker(node) { + // For an EnumDeclaration or ModuleDeclaration that merges with a preceeding + // declaration we do not emit a leading variable declaration. To preserve the + // begin/end semantics of the declararation and to properly handle exports + // we wrapped the leading variable declaration in a `MergeDeclarationMarker`. + // + // To balance the declaration, add the exports of the elided variable + // statement. + if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 219 /* VariableStatement */) { + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node.original); + } + return node; + } + /** + * Determines whether a node has an associated EndOfDeclarationMarker. + * + * @param node The node to test. + */ + function hasAssociatedEndOfDeclarationMarker(node) { + return (ts.getEmitFlags(node) & 4194304 /* HasEndOfDeclarationMarker */) !== 0; + } + /** + * Visits a DeclarationMarker used as a placeholder for the end of a transformed + * declaration. + * + * @param node The node to visit. + */ + function visitEndOfDeclarationMarker(node) { + // For some transformations we emit an `EndOfDeclarationMarker` to mark the actual + // end of the transformed declaration. We use this marker to emit any deferred exports + // of the declaration. + var id = ts.getOriginalNodeId(node); + var statements = deferredExports[id]; + if (statements) { + delete deferredExports[id]; + return ts.append(statements, node); + } + return node; + } + /** + * Appends the exports of an ImportDeclaration to a statement list, returning the + * statement list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param decl The declaration whose exports are to be recorded. + */ + function appendExportsOfImportDeclaration(statements, decl) { + if (currentModuleInfo.exportEquals) { + return statements; + } + var importClause = decl.importClause; + if (!importClause) { + return statements; + } + if (importClause.name) { + statements = appendExportsOfDeclaration(statements, importClause); + } + var namedBindings = importClause.namedBindings; + if (namedBindings) { + switch (namedBindings.kind) { + case 251 /* NamespaceImport */: + statements = appendExportsOfDeclaration(statements, namedBindings); + break; + case 252 /* NamedImports */: + for (var _i = 0, _a = namedBindings.elements; _i < _a.length; _i++) { + var importBinding = _a[_i]; + statements = appendExportsOfDeclaration(statements, importBinding); + } + break; + } + } + return statements; + } + /** + * Appends the exports of an ImportEqualsDeclaration to a statement list, returning the + * statement list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param decl The declaration whose exports are to be recorded. + */ + function appendExportsOfImportEqualsDeclaration(statements, decl) { + if (currentModuleInfo.exportEquals) { + return statements; + } + return appendExportsOfDeclaration(statements, decl); + } + /** + * Appends the exports of a VariableStatement to a statement list, returning the statement + * list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param node The VariableStatement whose exports are to be recorded. + */ + function appendExportsOfVariableStatement(statements, node) { + if (currentModuleInfo.exportEquals) { + return statements; + } + for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + statements = appendExportsOfBindingElement(statements, decl); + } + return statements; + } + /** + * Appends the exports of a VariableDeclaration or BindingElement to a statement list, + * returning the statement list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param decl The declaration whose exports are to be recorded. + */ + function appendExportsOfBindingElement(statements, decl) { + if (currentModuleInfo.exportEquals) { + return statements; + } + if (ts.isBindingPattern(decl.name)) { + for (var _i = 0, _a = decl.name.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (!ts.isOmittedExpression(element)) { + statements = appendExportsOfBindingElement(statements, element); + } + } + } + else if (!ts.isGeneratedIdentifier(decl.name)) { + statements = appendExportsOfDeclaration(statements, decl); + } + return statements; + } + /** + * Appends the exports of a ClassDeclaration or FunctionDeclaration to a statement list, + * returning the statement list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param decl The declaration whose exports are to be recorded. + */ + function appendExportsOfHoistedDeclaration(statements, decl) { + if (currentModuleInfo.exportEquals) { + return statements; + } + if (ts.hasModifier(decl, 1 /* Export */)) { + var exportName = ts.hasModifier(decl, 512 /* Default */) ? ts.createIdentifier("default") : ts.getDeclarationName(decl); + statements = appendExportStatement(statements, exportName, ts.getLocalName(decl), /*location*/ decl); + } + if (decl.name) { + statements = appendExportsOfDeclaration(statements, decl); + } + return statements; + } + /** + * Appends the exports of a declaration to a statement list, returning the statement list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param decl The declaration to export. + */ + function appendExportsOfDeclaration(statements, decl) { + var name = ts.getDeclarationName(decl); + var exportSpecifiers = currentModuleInfo.exportSpecifiers.get(ts.idText(name)); + if (exportSpecifiers) { + for (var _i = 0, exportSpecifiers_1 = exportSpecifiers; _i < exportSpecifiers_1.length; _i++) { + var exportSpecifier = exportSpecifiers_1[_i]; + statements = appendExportStatement(statements, exportSpecifier.name, name, /*location*/ exportSpecifier.name); + } + } + return statements; + } + /** + * Appends the down-level representation of an export to a statement list, returning the + * statement list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param exportName The name of the export. + * @param expression The expression to export. + * @param location The location to use for source maps and comments for the export. + * @param allowComments Whether to allow comments on the export. + */ + function appendExportStatement(statements, exportName, expression, location, allowComments) { + statements = ts.append(statements, createExportStatement(exportName, expression, location, allowComments)); + return statements; + } + function createUnderscoreUnderscoreESModule() { + var statement; + if (languageVersion === 0 /* ES3 */) { + statement = ts.createExpressionStatement(createExportExpression(ts.createIdentifier("__esModule"), ts.createLiteral(/*value*/ true))); + } + else { + statement = ts.createExpressionStatement(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"), + /*typeArguments*/ undefined, [ + ts.createIdentifier("exports"), + ts.createLiteral("__esModule"), + ts.createObjectLiteral([ + ts.createPropertyAssignment("value", ts.createLiteral(/*value*/ true)) + ]) + ])); + } + ts.setEmitFlags(statement, 1048576 /* CustomPrologue */); + return statement; + } + /** + * Creates a call to the current file's export function to export a value. + * + * @param name The bound name of the export. + * @param value The exported value. + * @param location The location to use for source maps and comments for the export. + * @param allowComments An optional value indicating whether to emit comments for the statement. + */ + function createExportStatement(name, value, location, allowComments) { + var statement = ts.setTextRange(ts.createExpressionStatement(createExportExpression(name, value)), location); + ts.startOnNewLine(statement); + if (!allowComments) { + ts.setEmitFlags(statement, 1536 /* NoComments */); + } + return statement; + } + /** + * Creates a call to the current file's export function to export a value. + * + * @param name The bound name of the export. + * @param value The exported value. + * @param location The location to use for source maps and comments for the export. + */ + function createExportExpression(name, value, location) { + return ts.setTextRange(ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier("exports"), ts.getSynthesizedClone(name)), value), location); + } + // + // Modifier Visitors + // + /** + * Visit nodes to elide module-specific modifiers. + * + * @param node The node to visit. + */ + function modifierVisitor(node) { + // Elide module-specific modifiers. + switch (node.kind) { + case 85 /* ExportKeyword */: + case 80 /* DefaultKeyword */: + return undefined; + } + return node; + } + // + // Emit Notification + // + /** + * Hook for node emit notifications. + * + * @param hint A hint as to the intended usage of the node. + * @param node The node to emit. + * @param emit A callback used to emit the node in the printer. + */ + function onEmitNode(hint, node, emitCallback) { + if (node.kind === 279 /* SourceFile */) { + currentSourceFile = node; + currentModuleInfo = moduleInfoMap[ts.getOriginalNodeId(currentSourceFile)]; + noSubstitution = []; + previousOnEmitNode(hint, node, emitCallback); + currentSourceFile = undefined; + currentModuleInfo = undefined; + noSubstitution = undefined; + } + else { + previousOnEmitNode(hint, node, emitCallback); + } + } + // + // Substitutions + // + /** + * Hooks node substitutions. + * + * @param hint A hint as to the intended usage of the node. + * @param node The node to substitute. + */ + function onSubstituteNode(hint, node) { + node = previousOnSubstituteNode(hint, node); + if (node.id && noSubstitution[node.id]) { + return node; + } + if (hint === 1 /* Expression */) { + return substituteExpression(node); + } + else if (ts.isShorthandPropertyAssignment(node)) { + return substituteShorthandPropertyAssignment(node); + } + return node; + } + /** + * Substitution for a ShorthandPropertyAssignment whose declaration name is an imported + * or exported symbol. + * + * @param node The node to substitute. + */ + function substituteShorthandPropertyAssignment(node) { + var name = node.name; + var exportedOrImportedName = substituteExpressionIdentifier(name); + if (exportedOrImportedName !== name) { + // A shorthand property with an assignment initializer is probably part of a + // destructuring assignment + if (node.objectAssignmentInitializer) { + var initializer = ts.createAssignment(exportedOrImportedName, node.objectAssignmentInitializer); + return ts.setTextRange(ts.createPropertyAssignment(name, initializer), node); + } + return ts.setTextRange(ts.createPropertyAssignment(name, exportedOrImportedName), node); + } + return node; + } + /** + * Substitution for an Expression that may contain an imported or exported symbol. + * + * @param node The node to substitute. + */ + function substituteExpression(node) { + switch (node.kind) { + case 72 /* Identifier */: + return substituteExpressionIdentifier(node); + case 204 /* BinaryExpression */: + return substituteBinaryExpression(node); + case 203 /* PostfixUnaryExpression */: + case 202 /* PrefixUnaryExpression */: + return substituteUnaryExpression(node); + } + return node; + } + /** + * Substitution for an Identifier expression that may contain an imported or exported + * symbol. + * + * @param node The node to substitute. + */ + function substituteExpressionIdentifier(node) { + if (ts.getEmitFlags(node) & 4096 /* HelperName */) { + var externalHelpersModuleName = ts.getExternalHelpersModuleName(currentSourceFile); + if (externalHelpersModuleName) { + return ts.createPropertyAccess(externalHelpersModuleName, node); + } + return node; + } + if (!ts.isGeneratedIdentifier(node) && !ts.isLocalName(node)) { + var exportContainer = resolver.getReferencedExportContainer(node, ts.isExportName(node)); + if (exportContainer && exportContainer.kind === 279 /* SourceFile */) { + return ts.setTextRange(ts.createPropertyAccess(ts.createIdentifier("exports"), ts.getSynthesizedClone(node)), + /*location*/ node); + } + var importDeclaration = resolver.getReferencedImportDeclaration(node); + if (importDeclaration) { + if (ts.isImportClause(importDeclaration)) { + return ts.setTextRange(ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent), ts.createIdentifier("default")), + /*location*/ node); + } + else if (ts.isImportSpecifier(importDeclaration)) { + var name = importDeclaration.propertyName || importDeclaration.name; + return ts.setTextRange(ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent.parent.parent), ts.getSynthesizedClone(name)), + /*location*/ node); + } + } + } + return node; + } + /** + * Substitution for a BinaryExpression that may contain an imported or exported symbol. + * + * @param node The node to substitute. + */ + function substituteBinaryExpression(node) { + // When we see an assignment expression whose left-hand side is an exported symbol, + // we should ensure all exports of that symbol are updated with the correct value. + // + // - We do not substitute generated identifiers for any reason. + // - We do not substitute identifiers tagged with the LocalName flag. + // - We do not substitute identifiers that were originally the name of an enum or + // namespace due to how they are transformed in TypeScript. + // - We only substitute identifiers that are exported at the top level. + if (ts.isAssignmentOperator(node.operatorToken.kind) + && ts.isIdentifier(node.left) + && !ts.isGeneratedIdentifier(node.left) + && !ts.isLocalName(node.left) + && !ts.isDeclarationNameOfEnumOrNamespace(node.left)) { + var exportedNames = getExports(node.left); + if (exportedNames) { + // For each additional export of the declaration, apply an export assignment. + var expression = node; + for (var _i = 0, exportedNames_2 = exportedNames; _i < exportedNames_2.length; _i++) { + var exportName = exportedNames_2[_i]; + // Mark the node to prevent triggering this rule again. + noSubstitution[ts.getNodeId(expression)] = true; + expression = createExportExpression(exportName, expression, /*location*/ node); + } + return expression; + } + } + return node; + } + /** + * Substitution for a UnaryExpression that may contain an imported or exported symbol. + * + * @param node The node to substitute. + */ + function substituteUnaryExpression(node) { + // When we see a prefix or postfix increment expression whose operand is an exported + // symbol, we should ensure all exports of that symbol are updated with the correct + // value. + // + // - We do not substitute generated identifiers for any reason. + // - We do not substitute identifiers tagged with the LocalName flag. + // - We do not substitute identifiers that were originally the name of an enum or + // namespace due to how they are transformed in TypeScript. + // - We only substitute identifiers that are exported at the top level. + if ((node.operator === 44 /* PlusPlusToken */ || node.operator === 45 /* MinusMinusToken */) + && ts.isIdentifier(node.operand) + && !ts.isGeneratedIdentifier(node.operand) + && !ts.isLocalName(node.operand) + && !ts.isDeclarationNameOfEnumOrNamespace(node.operand)) { + var exportedNames = getExports(node.operand); + if (exportedNames) { + var expression = node.kind === 203 /* PostfixUnaryExpression */ + ? ts.setTextRange(ts.createBinary(node.operand, ts.createToken(node.operator === 44 /* PlusPlusToken */ ? 60 /* PlusEqualsToken */ : 61 /* MinusEqualsToken */), ts.createLiteral(1)), + /*location*/ node) + : node; + for (var _i = 0, exportedNames_3 = exportedNames; _i < exportedNames_3.length; _i++) { + var exportName = exportedNames_3[_i]; + // Mark the node to prevent triggering this rule again. + noSubstitution[ts.getNodeId(expression)] = true; + expression = createExportExpression(exportName, expression); + } + return expression; + } + } + return node; + } + /** + * Gets the additional exports of a name. + * + * @param name The name. + */ + function getExports(name) { + if (!ts.isGeneratedIdentifier(name)) { + var valueDeclaration = resolver.getReferencedImportDeclaration(name) + || resolver.getReferencedValueDeclaration(name); + if (valueDeclaration) { + return currentModuleInfo + && currentModuleInfo.exportedBindings[ts.getOriginalNodeId(valueDeclaration)]; + } + } + } + } + ts.transformModule = transformModule; + // emit output for the __export helper function + var exportStarHelper = { + name: "typescript:export-star", + scoped: true, + text: "\n function __export(m) {\n for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\n }" + }; + function createExportStarHelper(context, module) { + var compilerOptions = context.getCompilerOptions(); + return compilerOptions.importHelpers + ? ts.createCall(ts.getHelperName("__exportStar"), /*typeArguments*/ undefined, [module, ts.createIdentifier("exports")]) + : ts.createCall(ts.createIdentifier("__export"), /*typeArguments*/ undefined, [module]); + } + // emit helper for dynamic import + var dynamicImportUMDHelper = { + name: "typescript:dynamicimport-sync-require", + scoped: true, + text: "\n var __syncRequire = typeof module === \"object\" && typeof module.exports === \"object\";" + }; + // emit helper for `import * as Name from "foo"` + var importStarHelper = { + name: "typescript:commonjsimportstar", + scoped: false, + text: "\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];\n result[\"default\"] = mod;\n return result;\n};" + }; + // emit helper for `import Name from "foo"` + var importDefaultHelper = { + name: "typescript:commonjsimportdefault", + scoped: false, + text: "\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};" + }; +})(ts || (ts = {})); +/*@internal*/ +var ts; +(function (ts) { + function transformSystemModule(context) { + var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; + var compilerOptions = context.getCompilerOptions(); + var resolver = context.getEmitResolver(); + var host = context.getEmitHost(); + var previousOnSubstituteNode = context.onSubstituteNode; + var previousOnEmitNode = context.onEmitNode; + context.onSubstituteNode = onSubstituteNode; + context.onEmitNode = onEmitNode; + context.enableSubstitution(72 /* Identifier */); // Substitutes expression identifiers for imported symbols. + context.enableSubstitution(276 /* ShorthandPropertyAssignment */); // Substitutes expression identifiers for imported symbols + context.enableSubstitution(204 /* BinaryExpression */); // Substitutes assignments to exported symbols. + context.enableSubstitution(202 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols. + context.enableSubstitution(203 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols. + context.enableEmitNotification(279 /* SourceFile */); // Restore state when substituting nodes in a file. + var moduleInfoMap = []; // The ExternalModuleInfo for each file. + var deferredExports = []; // Exports to defer until an EndOfDeclarationMarker is found. + var exportFunctionsMap = []; // The export function associated with a source file. + var noSubstitutionMap = []; // Set of nodes for which substitution rules should be ignored for each file. + var currentSourceFile; // The current file. + var moduleInfo; // ExternalModuleInfo for the current file. + var exportFunction; // The export function for the current file. + var contextObject; // The context object for the current file. + var hoistedStatements; + var enclosingBlockScopedContainer; + var noSubstitution; // Set of nodes for which substitution rules should be ignored. + return ts.chainBundle(transformSourceFile); + /** + * Transforms the module aspects of a SourceFile. + * + * @param node The SourceFile node. + */ + function transformSourceFile(node) { + if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 16777216 /* ContainsDynamicImport */)) { + return node; + } + var id = ts.getOriginalNodeId(node); + currentSourceFile = node; + enclosingBlockScopedContainer = node; + // System modules have the following shape: + // + // System.register(['dep-1', ... 'dep-n'], function(exports) {/* module body function */}) + // + // The parameter 'exports' here is a callback '(name: string, value: T) => T' that + // is used to publish exported values. 'exports' returns its 'value' argument so in + // most cases expressions that mutate exported values can be rewritten as: + // + // expr -> exports('name', expr) + // + // The only exception in this rule is postfix unary operators, + // see comment to 'substitutePostfixUnaryExpression' for more details + // Collect information about the external module and dependency groups. + moduleInfo = moduleInfoMap[id] = ts.collectExternalModuleInfo(node, resolver, compilerOptions); + // Make sure that the name of the 'exports' function does not conflict with + // existing identifiers. + exportFunction = ts.createUniqueName("exports"); + exportFunctionsMap[id] = exportFunction; + contextObject = ts.createUniqueName("context"); + // Add the body of the module. + var dependencyGroups = collectDependencyGroups(moduleInfo.externalImports); + var moduleBodyBlock = createSystemModuleBody(node, dependencyGroups); + var moduleBodyFunction = ts.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, [ + ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, exportFunction), + ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, contextObject) + ], + /*type*/ undefined, moduleBodyBlock); + // Write the call to `System.register` + // Clear the emit-helpers flag for later passes since we'll have already used it in the module body + // So the helper will be emit at the correct position instead of at the top of the source-file + var moduleName = ts.tryGetModuleNameFromFile(node, host, compilerOptions); + var dependencies = ts.createArrayLiteral(ts.map(dependencyGroups, function (dependencyGroup) { return dependencyGroup.name; })); + var updated = ts.setEmitFlags(ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray([ + ts.createExpressionStatement(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("System"), "register"), + /*typeArguments*/ undefined, moduleName + ? [moduleName, dependencies, moduleBodyFunction] + : [dependencies, moduleBodyFunction])) + ]), node.statements)), 1024 /* NoTrailingComments */); + if (!(compilerOptions.outFile || compilerOptions.out)) { + ts.moveEmitHelpers(updated, moduleBodyBlock, function (helper) { return !helper.scoped; }); + } + if (noSubstitution) { + noSubstitutionMap[id] = noSubstitution; + noSubstitution = undefined; + } + currentSourceFile = undefined; + moduleInfo = undefined; + exportFunction = undefined; + contextObject = undefined; + hoistedStatements = undefined; + enclosingBlockScopedContainer = undefined; + return ts.aggregateTransformFlags(updated); + } + /** + * Collects the dependency groups for this files imports. + * + * @param externalImports The imports for the file. + */ + function collectDependencyGroups(externalImports) { + var groupIndices = ts.createMap(); + var dependencyGroups = []; + for (var _i = 0, externalImports_1 = externalImports; _i < externalImports_1.length; _i++) { + var externalImport = externalImports_1[_i]; + var externalModuleName = ts.getExternalModuleNameLiteral(externalImport, currentSourceFile, host, resolver, compilerOptions); + if (externalModuleName) { + var text = externalModuleName.text; + var groupIndex = groupIndices.get(text); + if (groupIndex !== undefined) { + // deduplicate/group entries in dependency list by the dependency name + dependencyGroups[groupIndex].externalImports.push(externalImport); + } + else { + groupIndices.set(text, dependencyGroups.length); + dependencyGroups.push({ + name: externalModuleName, + externalImports: [externalImport] + }); + } + } + } + return dependencyGroups; + } + /** + * Adds the statements for the module body function for the source file. + * + * @param node The source file for the module. + * @param dependencyGroups The grouped dependencies of the module. + */ + function createSystemModuleBody(node, dependencyGroups) { + // Shape of the body in system modules: + // + // function (exports) { + // + // + // + // return { + // setters: [ + // + // ], + // execute: function() { + // + // } + // } + // + // } + // + // i.e: + // + // import {x} from 'file1' + // var y = 1; + // export function foo() { return y + x(); } + // console.log(y); + // + // Will be transformed to: + // + // function(exports) { + // function foo() { return y + file_1.x(); } + // exports("foo", foo); + // var file_1, y; + // return { + // setters: [ + // function(v) { file_1 = v } + // ], + // execute(): function() { + // y = 1; + // console.log(y); + // } + // }; + // } + var statements = []; + // We start a new lexical environment in this function body, but *not* in the + // body of the execute function. This allows us to emit temporary declarations + // only in the outer module body and not in the inner one. + startLexicalEnvironment(); + // Add any prologue directives. + var ensureUseStrict = ts.getStrictOptionValue(compilerOptions, "alwaysStrict") || (!compilerOptions.noImplicitUseStrict && ts.isExternalModule(currentSourceFile)); + var statementOffset = ts.addPrologue(statements, node.statements, ensureUseStrict, sourceElementVisitor); + // var __moduleName = context_1 && context_1.id; + statements.push(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration("__moduleName", + /*type*/ undefined, ts.createLogicalAnd(contextObject, ts.createPropertyAccess(contextObject, "id"))) + ]))); + // Visit the synthetic external helpers import declaration if present + ts.visitNode(moduleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement); + // Visit the statements of the source file, emitting any transformations into + // the `executeStatements` array. We do this *before* we fill the `setters` array + // as we both emit transformations as well as aggregate some data used when creating + // setters. This allows us to reduce the number of times we need to loop through the + // statements of the source file. + var executeStatements = ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset); + // Emit early exports for function declarations. + ts.addRange(statements, hoistedStatements); + // We emit hoisted variables early to align roughly with our previous emit output. + // Two key differences in this approach are: + // - Temporary variables will appear at the top rather than at the bottom of the file + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + var exportStarFunction = addExportStarIfNeeded(statements); // TODO: GH#18217 + var moduleObject = ts.createObjectLiteral([ + ts.createPropertyAssignment("setters", createSettersArray(exportStarFunction, dependencyGroups)), + ts.createPropertyAssignment("execute", ts.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, + /*parameters*/ [], + /*type*/ undefined, ts.createBlock(executeStatements, /*multiLine*/ true))) + ]); + moduleObject.multiLine = true; + statements.push(ts.createReturn(moduleObject)); + return ts.createBlock(statements, /*multiLine*/ true); + } + /** + * Adds an exportStar function to a statement list if it is needed for the file. + * + * @param statements A statement list. + */ + function addExportStarIfNeeded(statements) { + if (!moduleInfo.hasExportStarsToExportValues) { + return; + } + // when resolving exports local exported entries/indirect exported entries in the module + // should always win over entries with similar names that were added via star exports + // to support this we store names of local/indirect exported entries in a set. + // this set is used to filter names brought by star expors. + // local names set should only be added if we have anything exported + if (!moduleInfo.exportedNames && moduleInfo.exportSpecifiers.size === 0) { + // no exported declarations (export var ...) or export specifiers (export {x}) + // check if we have any non star export declarations. + var hasExportDeclarationWithExportClause = false; + for (var _i = 0, _a = moduleInfo.externalImports; _i < _a.length; _i++) { + var externalImport = _a[_i]; + if (externalImport.kind === 255 /* ExportDeclaration */ && externalImport.exportClause) { + hasExportDeclarationWithExportClause = true; + break; + } + } + if (!hasExportDeclarationWithExportClause) { + // we still need to emit exportStar helper + var exportStarFunction_1 = createExportStarFunction(/*localNames*/ undefined); + statements.push(exportStarFunction_1); + return exportStarFunction_1.name; + } + } + var exportedNames = []; + if (moduleInfo.exportedNames) { + for (var _b = 0, _c = moduleInfo.exportedNames; _b < _c.length; _b++) { + var exportedLocalName = _c[_b]; + if (exportedLocalName.escapedText === "default") { + continue; + } + // write name of exported declaration, i.e 'export var x...' + exportedNames.push(ts.createPropertyAssignment(ts.createLiteral(exportedLocalName), ts.createTrue())); + } + } + for (var _d = 0, _e = moduleInfo.externalImports; _d < _e.length; _d++) { + var externalImport = _e[_d]; + if (externalImport.kind !== 255 /* ExportDeclaration */) { + continue; + } + if (!externalImport.exportClause) { + // export * from ... + continue; + } + for (var _f = 0, _g = externalImport.exportClause.elements; _f < _g.length; _f++) { + var element = _g[_f]; + // write name of indirectly exported entry, i.e. 'export {x} from ...' + exportedNames.push(ts.createPropertyAssignment(ts.createLiteral(ts.idText(element.name || element.propertyName)), ts.createTrue())); + } + } + var exportedNamesStorageRef = ts.createUniqueName("exportedNames"); + statements.push(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(exportedNamesStorageRef, + /*type*/ undefined, ts.createObjectLiteral(exportedNames, /*multiline*/ true)) + ]))); + var exportStarFunction = createExportStarFunction(exportedNamesStorageRef); + statements.push(exportStarFunction); + return exportStarFunction.name; + } + /** + * Creates an exportStar function for the file, with an optional set of excluded local + * names. + * + * @param localNames An optional reference to an object containing a set of excluded local + * names. + */ + function createExportStarFunction(localNames) { + var exportStarFunction = ts.createUniqueName("exportStar"); + var m = ts.createIdentifier("m"); + var n = ts.createIdentifier("n"); + var exports = ts.createIdentifier("exports"); + var condition = ts.createStrictInequality(n, ts.createLiteral("default")); + if (localNames) { + condition = ts.createLogicalAnd(condition, ts.createLogicalNot(ts.createCall(ts.createPropertyAccess(localNames, "hasOwnProperty"), + /*typeArguments*/ undefined, [n]))); + } + return ts.createFunctionDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, exportStarFunction, + /*typeParameters*/ undefined, [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, m)], + /*type*/ undefined, ts.createBlock([ + ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(exports, + /*type*/ undefined, ts.createObjectLiteral([])) + ])), + ts.createForIn(ts.createVariableDeclarationList([ + ts.createVariableDeclaration(n, /*type*/ undefined) + ]), m, ts.createBlock([ + ts.setEmitFlags(ts.createIf(condition, ts.createExpressionStatement(ts.createAssignment(ts.createElementAccess(exports, n), ts.createElementAccess(m, n)))), 1 /* SingleLine */) + ])), + ts.createExpressionStatement(ts.createCall(exportFunction, + /*typeArguments*/ undefined, [exports])) + ], /*multiline*/ true)); + } + /** + * Creates an array setter callbacks for each dependency group. + * + * @param exportStarFunction A reference to an exportStarFunction for the file. + * @param dependencyGroups An array of grouped dependencies. + */ + function createSettersArray(exportStarFunction, dependencyGroups) { + var setters = []; + for (var _i = 0, dependencyGroups_1 = dependencyGroups; _i < dependencyGroups_1.length; _i++) { + var group_1 = dependencyGroups_1[_i]; + // derive a unique name for parameter from the first named entry in the group + var localName = ts.forEach(group_1.externalImports, function (i) { return ts.getLocalNameForExternalImport(i, currentSourceFile); }); + var parameterName = localName ? ts.getGeneratedNameForNode(localName) : ts.createUniqueName(""); + var statements = []; + for (var _a = 0, _b = group_1.externalImports; _a < _b.length; _a++) { + var entry = _b[_a]; + var importVariableName = ts.getLocalNameForExternalImport(entry, currentSourceFile); // TODO: GH#18217 + switch (entry.kind) { + case 249 /* ImportDeclaration */: + if (!entry.importClause) { + // 'import "..."' case + // module is imported only for side-effects, no emit required + break; + } + // falls through + case 248 /* ImportEqualsDeclaration */: + ts.Debug.assert(importVariableName !== undefined); + // save import into the local + statements.push(ts.createExpressionStatement(ts.createAssignment(importVariableName, parameterName))); + break; + case 255 /* ExportDeclaration */: + ts.Debug.assert(importVariableName !== undefined); + if (entry.exportClause) { + // export {a, b as c} from 'foo' + // + // emit as: + // + // exports_({ + // "a": _["a"], + // "c": _["b"] + // }); + var properties = []; + for (var _c = 0, _d = entry.exportClause.elements; _c < _d.length; _c++) { + var e = _d[_c]; + properties.push(ts.createPropertyAssignment(ts.createLiteral(ts.idText(e.name)), ts.createElementAccess(parameterName, ts.createLiteral(ts.idText(e.propertyName || e.name))))); + } + statements.push(ts.createExpressionStatement(ts.createCall(exportFunction, + /*typeArguments*/ undefined, [ts.createObjectLiteral(properties, /*multiline*/ true)]))); + } + else { + // export * from 'foo' + // + // emit as: + // + // exportStar(foo_1_1); + statements.push(ts.createExpressionStatement(ts.createCall(exportStarFunction, + /*typeArguments*/ undefined, [parameterName]))); + } + break; + } + } + setters.push(ts.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, parameterName)], + /*type*/ undefined, ts.createBlock(statements, /*multiLine*/ true))); + } + return ts.createArrayLiteral(setters, /*multiLine*/ true); + } + // + // Top-level Source Element Visitors + // + /** + * Visit source elements at the top-level of a module. + * + * @param node The node to visit. + */ + function sourceElementVisitor(node) { + switch (node.kind) { + case 249 /* ImportDeclaration */: + return visitImportDeclaration(node); + case 248 /* ImportEqualsDeclaration */: + return visitImportEqualsDeclaration(node); + case 255 /* ExportDeclaration */: + // ExportDeclarations are elided as they are handled via + // `appendExportsOfDeclaration`. + return undefined; + case 254 /* ExportAssignment */: + return visitExportAssignment(node); + default: + return nestedElementVisitor(node); + } + } + /** + * Visits an ImportDeclaration node. + * + * @param node The node to visit. + */ + function visitImportDeclaration(node) { + var statements; + if (node.importClause) { + hoistVariableDeclaration(ts.getLocalNameForExternalImport(node, currentSourceFile)); // TODO: GH#18217 + } + if (hasAssociatedEndOfDeclarationMarker(node)) { + // Defer exports until we encounter an EndOfDeclarationMarker node + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportsOfImportDeclaration(deferredExports[id], node); + } + else { + statements = appendExportsOfImportDeclaration(statements, node); + } + return ts.singleOrMany(statements); + } + /** + * Visits an ImportEqualsDeclaration node. + * + * @param node The node to visit. + */ + function visitImportEqualsDeclaration(node) { + ts.Debug.assert(ts.isExternalModuleImportEqualsDeclaration(node), "import= for internal module references should be handled in an earlier transformer."); + var statements; + hoistVariableDeclaration(ts.getLocalNameForExternalImport(node, currentSourceFile)); // TODO: GH#18217 + if (hasAssociatedEndOfDeclarationMarker(node)) { + // Defer exports until we encounter an EndOfDeclarationMarker node + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportsOfImportEqualsDeclaration(deferredExports[id], node); + } + else { + statements = appendExportsOfImportEqualsDeclaration(statements, node); + } + return ts.singleOrMany(statements); + } + /** + * Visits an ExportAssignment node. + * + * @param node The node to visit. + */ + function visitExportAssignment(node) { + if (node.isExportEquals) { + // Elide `export=` as it is illegal in a SystemJS module. + return undefined; + } + var expression = ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression); + var original = node.original; + if (original && hasAssociatedEndOfDeclarationMarker(original)) { + // Defer exports until we encounter an EndOfDeclarationMarker node + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportStatement(deferredExports[id], ts.createIdentifier("default"), expression, /*allowComments*/ true); + } + else { + return createExportStatement(ts.createIdentifier("default"), expression, /*allowComments*/ true); + } + } + /** + * Visits a FunctionDeclaration, hoisting it to the outer module body function. + * + * @param node The node to visit. + */ + function visitFunctionDeclaration(node) { + if (ts.hasModifier(node, 1 /* Export */)) { + hoistedStatements = ts.append(hoistedStatements, ts.updateFunctionDeclaration(node, node.decorators, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, ts.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true), + /*typeParameters*/ undefined, ts.visitNodes(node.parameters, destructuringAndImportCallVisitor, ts.isParameterDeclaration), + /*type*/ undefined, ts.visitNode(node.body, destructuringAndImportCallVisitor, ts.isBlock))); + } + else { + hoistedStatements = ts.append(hoistedStatements, ts.visitEachChild(node, destructuringAndImportCallVisitor, context)); + } + if (hasAssociatedEndOfDeclarationMarker(node)) { + // Defer exports until we encounter an EndOfDeclarationMarker node + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node); + } + else { + hoistedStatements = appendExportsOfHoistedDeclaration(hoistedStatements, node); + } + return undefined; + } + /** + * Visits a ClassDeclaration, hoisting its name to the outer module body function. + * + * @param node The node to visit. + */ + function visitClassDeclaration(node) { + var statements; + // Hoist the name of the class declaration to the outer module body function. + var name = ts.getLocalName(node); + hoistVariableDeclaration(name); + // Rewrite the class declaration into an assignment of a class expression. + statements = ts.append(statements, ts.setTextRange(ts.createExpressionStatement(ts.createAssignment(name, ts.setTextRange(ts.createClassExpression( + /*modifiers*/ undefined, node.name, + /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, destructuringAndImportCallVisitor, ts.isHeritageClause), ts.visitNodes(node.members, destructuringAndImportCallVisitor, ts.isClassElement)), node))), node)); + if (hasAssociatedEndOfDeclarationMarker(node)) { + // Defer exports until we encounter an EndOfDeclarationMarker node + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node); + } + else { + statements = appendExportsOfHoistedDeclaration(statements, node); + } + return ts.singleOrMany(statements); + } + /** + * Visits a variable statement, hoisting declared names to the top-level module body. + * Each declaration is rewritten into an assignment expression. + * + * @param node The node to visit. + */ + function visitVariableStatement(node) { + if (!shouldHoistVariableDeclarationList(node.declarationList)) { + return ts.visitNode(node, destructuringAndImportCallVisitor, ts.isStatement); + } + var expressions; + var isExportedDeclaration = ts.hasModifier(node, 1 /* Export */); + var isMarkedDeclaration = hasAssociatedEndOfDeclarationMarker(node); + for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { + var variable = _a[_i]; + if (variable.initializer) { + expressions = ts.append(expressions, transformInitializedVariable(variable, isExportedDeclaration && !isMarkedDeclaration)); + } + else { + hoistBindingElement(variable); + } + } + var statements; + if (expressions) { + statements = ts.append(statements, ts.setTextRange(ts.createExpressionStatement(ts.inlineExpressions(expressions)), node)); + } + if (isMarkedDeclaration) { + // Defer exports until we encounter an EndOfDeclarationMarker node + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node, isExportedDeclaration); + } + else { + statements = appendExportsOfVariableStatement(statements, node, /*exportSelf*/ false); + } + return ts.singleOrMany(statements); + } + /** + * Hoists the declared names of a VariableDeclaration or BindingElement. + * + * @param node The declaration to hoist. + */ + function hoistBindingElement(node) { + if (ts.isBindingPattern(node.name)) { + for (var _i = 0, _a = node.name.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (!ts.isOmittedExpression(element)) { + hoistBindingElement(element); + } + } + } + else { + hoistVariableDeclaration(ts.getSynthesizedClone(node.name)); + } + } + /** + * Determines whether a VariableDeclarationList should be hoisted. + * + * @param node The node to test. + */ + function shouldHoistVariableDeclarationList(node) { + // hoist only non-block scoped declarations or block scoped declarations parented by source file + return (ts.getEmitFlags(node) & 2097152 /* NoHoisting */) === 0 + && (enclosingBlockScopedContainer.kind === 279 /* SourceFile */ + || (ts.getOriginalNode(node).flags & 3 /* BlockScoped */) === 0); + } + /** + * Transform an initialized variable declaration into an expression. + * + * @param node The node to transform. + * @param isExportedDeclaration A value indicating whether the variable is exported. + */ + function transformInitializedVariable(node, isExportedDeclaration) { + var createAssignment = isExportedDeclaration ? createExportedVariableAssignment : createNonExportedVariableAssignment; + return ts.isBindingPattern(node.name) + ? ts.flattenDestructuringAssignment(node, destructuringAndImportCallVisitor, context, 0 /* All */, + /*needsValue*/ false, createAssignment) + : node.initializer ? createAssignment(node.name, ts.visitNode(node.initializer, destructuringAndImportCallVisitor, ts.isExpression)) : node.name; + } + /** + * Creates an assignment expression for an exported variable declaration. + * + * @param name The name of the variable. + * @param value The value of the variable's initializer. + * @param location The source map location for the assignment. + */ + function createExportedVariableAssignment(name, value, location) { + return createVariableAssignment(name, value, location, /*isExportedDeclaration*/ true); + } + /** + * Creates an assignment expression for a non-exported variable declaration. + * + * @param name The name of the variable. + * @param value The value of the variable's initializer. + * @param location The source map location for the assignment. + */ + function createNonExportedVariableAssignment(name, value, location) { + return createVariableAssignment(name, value, location, /*isExportedDeclaration*/ false); + } + /** + * Creates an assignment expression for a variable declaration. + * + * @param name The name of the variable. + * @param value The value of the variable's initializer. + * @param location The source map location for the assignment. + * @param isExportedDeclaration A value indicating whether the variable is exported. + */ + function createVariableAssignment(name, value, location, isExportedDeclaration) { + hoistVariableDeclaration(ts.getSynthesizedClone(name)); + return isExportedDeclaration + ? createExportExpression(name, preventSubstitution(ts.setTextRange(ts.createAssignment(name, value), location))) + : preventSubstitution(ts.setTextRange(ts.createAssignment(name, value), location)); + } + /** + * Visits a MergeDeclarationMarker used as a placeholder for the beginning of a merged + * and transformed declaration. + * + * @param node The node to visit. + */ + function visitMergeDeclarationMarker(node) { + // For an EnumDeclaration or ModuleDeclaration that merges with a preceeding + // declaration we do not emit a leading variable declaration. To preserve the + // begin/end semantics of the declararation and to properly handle exports + // we wrapped the leading variable declaration in a `MergeDeclarationMarker`. + // + // To balance the declaration, we defer the exports of the elided variable + // statement until we visit this declaration's `EndOfDeclarationMarker`. + if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 219 /* VariableStatement */) { + var id = ts.getOriginalNodeId(node); + var isExportedDeclaration = ts.hasModifier(node.original, 1 /* Export */); + deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node.original, isExportedDeclaration); + } + return node; + } + /** + * Determines whether a node has an associated EndOfDeclarationMarker. + * + * @param node The node to test. + */ + function hasAssociatedEndOfDeclarationMarker(node) { + return (ts.getEmitFlags(node) & 4194304 /* HasEndOfDeclarationMarker */) !== 0; + } + /** + * Visits a DeclarationMarker used as a placeholder for the end of a transformed + * declaration. + * + * @param node The node to visit. + */ + function visitEndOfDeclarationMarker(node) { + // For some transformations we emit an `EndOfDeclarationMarker` to mark the actual + // end of the transformed declaration. We use this marker to emit any deferred exports + // of the declaration. + var id = ts.getOriginalNodeId(node); + var statements = deferredExports[id]; + if (statements) { + delete deferredExports[id]; + return ts.append(statements, node); + } + else { + var original = ts.getOriginalNode(node); + if (ts.isModuleOrEnumDeclaration(original)) { + return ts.append(appendExportsOfDeclaration(statements, original), node); + } + } + return node; + } + /** + * Appends the exports of an ImportDeclaration to a statement list, returning the + * statement list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param decl The declaration whose exports are to be recorded. + */ + function appendExportsOfImportDeclaration(statements, decl) { + if (moduleInfo.exportEquals) { + return statements; + } + var importClause = decl.importClause; + if (!importClause) { + return statements; + } + if (importClause.name) { + statements = appendExportsOfDeclaration(statements, importClause); + } + var namedBindings = importClause.namedBindings; + if (namedBindings) { + switch (namedBindings.kind) { + case 251 /* NamespaceImport */: + statements = appendExportsOfDeclaration(statements, namedBindings); + break; + case 252 /* NamedImports */: + for (var _i = 0, _a = namedBindings.elements; _i < _a.length; _i++) { + var importBinding = _a[_i]; + statements = appendExportsOfDeclaration(statements, importBinding); + } + break; + } + } + return statements; + } + /** + * Appends the export of an ImportEqualsDeclaration to a statement list, returning the + * statement list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param decl The declaration whose exports are to be recorded. + */ + function appendExportsOfImportEqualsDeclaration(statements, decl) { + if (moduleInfo.exportEquals) { + return statements; + } + return appendExportsOfDeclaration(statements, decl); + } + /** + * Appends the exports of a VariableStatement to a statement list, returning the statement + * list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param node The VariableStatement whose exports are to be recorded. + * @param exportSelf A value indicating whether to also export each VariableDeclaration of + * `nodes` declaration list. + */ + function appendExportsOfVariableStatement(statements, node, exportSelf) { + if (moduleInfo.exportEquals) { + return statements; + } + for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + if (decl.initializer || exportSelf) { + statements = appendExportsOfBindingElement(statements, decl, exportSelf); + } + } + return statements; + } + /** + * Appends the exports of a VariableDeclaration or BindingElement to a statement list, + * returning the statement list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param decl The declaration whose exports are to be recorded. + * @param exportSelf A value indicating whether to also export the declaration itself. + */ + function appendExportsOfBindingElement(statements, decl, exportSelf) { + if (moduleInfo.exportEquals) { + return statements; + } + if (ts.isBindingPattern(decl.name)) { + for (var _i = 0, _a = decl.name.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (!ts.isOmittedExpression(element)) { + statements = appendExportsOfBindingElement(statements, element, exportSelf); + } + } + } + else if (!ts.isGeneratedIdentifier(decl.name)) { + var excludeName = void 0; + if (exportSelf) { + statements = appendExportStatement(statements, decl.name, ts.getLocalName(decl)); + excludeName = ts.idText(decl.name); + } + statements = appendExportsOfDeclaration(statements, decl, excludeName); + } + return statements; + } + /** + * Appends the exports of a ClassDeclaration or FunctionDeclaration to a statement list, + * returning the statement list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param decl The declaration whose exports are to be recorded. + */ + function appendExportsOfHoistedDeclaration(statements, decl) { + if (moduleInfo.exportEquals) { + return statements; + } + var excludeName; + if (ts.hasModifier(decl, 1 /* Export */)) { + var exportName = ts.hasModifier(decl, 512 /* Default */) ? ts.createLiteral("default") : decl.name; + statements = appendExportStatement(statements, exportName, ts.getLocalName(decl)); + excludeName = ts.getTextOfIdentifierOrLiteral(exportName); + } + if (decl.name) { + statements = appendExportsOfDeclaration(statements, decl, excludeName); + } + return statements; + } + /** + * Appends the exports of a declaration to a statement list, returning the statement list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param decl The declaration to export. + * @param excludeName An optional name to exclude from exports. + */ + function appendExportsOfDeclaration(statements, decl, excludeName) { + if (moduleInfo.exportEquals) { + return statements; + } + var name = ts.getDeclarationName(decl); + var exportSpecifiers = moduleInfo.exportSpecifiers.get(ts.idText(name)); + if (exportSpecifiers) { + for (var _i = 0, exportSpecifiers_2 = exportSpecifiers; _i < exportSpecifiers_2.length; _i++) { + var exportSpecifier = exportSpecifiers_2[_i]; + if (exportSpecifier.name.escapedText !== excludeName) { + statements = appendExportStatement(statements, exportSpecifier.name, name); + } + } + } + return statements; + } + /** + * Appends the down-level representation of an export to a statement list, returning the + * statement list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param exportName The name of the export. + * @param expression The expression to export. + * @param allowComments Whether to allow comments on the export. + */ + function appendExportStatement(statements, exportName, expression, allowComments) { + statements = ts.append(statements, createExportStatement(exportName, expression, allowComments)); + return statements; + } + /** + * Creates a call to the current file's export function to export a value. + * + * @param name The bound name of the export. + * @param value The exported value. + * @param allowComments An optional value indicating whether to emit comments for the statement. + */ + function createExportStatement(name, value, allowComments) { + var statement = ts.createExpressionStatement(createExportExpression(name, value)); + ts.startOnNewLine(statement); + if (!allowComments) { + ts.setEmitFlags(statement, 1536 /* NoComments */); + } + return statement; + } + /** + * Creates a call to the current file's export function to export a value. + * + * @param name The bound name of the export. + * @param value The exported value. + */ + function createExportExpression(name, value) { + var exportName = ts.isIdentifier(name) ? ts.createLiteral(name) : name; + ts.setEmitFlags(value, ts.getEmitFlags(value) | 1536 /* NoComments */); + return ts.setCommentRange(ts.createCall(exportFunction, /*typeArguments*/ undefined, [exportName, value]), value); + } + // + // Top-Level or Nested Source Element Visitors + // + /** + * Visit nested elements at the top-level of a module. + * + * @param node The node to visit. + */ + function nestedElementVisitor(node) { + switch (node.kind) { + case 219 /* VariableStatement */: + return visitVariableStatement(node); + case 239 /* FunctionDeclaration */: + return visitFunctionDeclaration(node); + case 240 /* ClassDeclaration */: + return visitClassDeclaration(node); + case 225 /* ForStatement */: + return visitForStatement(node); + case 226 /* ForInStatement */: + return visitForInStatement(node); + case 227 /* ForOfStatement */: + return visitForOfStatement(node); + case 223 /* DoStatement */: + return visitDoStatement(node); + case 224 /* WhileStatement */: + return visitWhileStatement(node); + case 233 /* LabeledStatement */: + return visitLabeledStatement(node); + case 231 /* WithStatement */: + return visitWithStatement(node); + case 232 /* SwitchStatement */: + return visitSwitchStatement(node); + case 246 /* CaseBlock */: + return visitCaseBlock(node); + case 271 /* CaseClause */: + return visitCaseClause(node); + case 272 /* DefaultClause */: + return visitDefaultClause(node); + case 235 /* TryStatement */: + return visitTryStatement(node); + case 274 /* CatchClause */: + return visitCatchClause(node); + case 218 /* Block */: + return visitBlock(node); + case 310 /* MergeDeclarationMarker */: + return visitMergeDeclarationMarker(node); + case 311 /* EndOfDeclarationMarker */: + return visitEndOfDeclarationMarker(node); + default: + return destructuringAndImportCallVisitor(node); + } + } + /** + * Visits the body of a ForStatement to hoist declarations. + * + * @param node The node to visit. + */ + function visitForStatement(node) { + var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; + enclosingBlockScopedContainer = node; + node = ts.updateFor(node, node.initializer && visitForInitializer(node.initializer), ts.visitNode(node.condition, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.incrementor, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement)); + enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; + return node; + } + /** + * Visits the body of a ForInStatement to hoist declarations. + * + * @param node The node to visit. + */ + function visitForInStatement(node) { + var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; + enclosingBlockScopedContainer = node; + node = ts.updateForIn(node, visitForInitializer(node.initializer), ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock)); + enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; + return node; + } + /** + * Visits the body of a ForOfStatement to hoist declarations. + * + * @param node The node to visit. + */ + function visitForOfStatement(node) { + var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; + enclosingBlockScopedContainer = node; + node = ts.updateForOf(node, node.awaitModifier, visitForInitializer(node.initializer), ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock)); + enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; + return node; + } + /** + * Determines whether to hoist the initializer of a ForStatement, ForInStatement, or + * ForOfStatement. + * + * @param node The node to test. + */ + function shouldHoistForInitializer(node) { + return ts.isVariableDeclarationList(node) + && shouldHoistVariableDeclarationList(node); + } + /** + * Visits the initializer of a ForStatement, ForInStatement, or ForOfStatement + * + * @param node The node to visit. + */ + function visitForInitializer(node) { + if (shouldHoistForInitializer(node)) { + var expressions = void 0; + for (var _i = 0, _a = node.declarations; _i < _a.length; _i++) { + var variable = _a[_i]; + expressions = ts.append(expressions, transformInitializedVariable(variable, /*isExportedDeclaration*/ false)); + if (!variable.initializer) { + hoistBindingElement(variable); + } + } + return expressions ? ts.inlineExpressions(expressions) : ts.createOmittedExpression(); + } + else { + return ts.visitEachChild(node, nestedElementVisitor, context); + } + } + /** + * Visits the body of a DoStatement to hoist declarations. + * + * @param node The node to visit. + */ + function visitDoStatement(node) { + return ts.updateDo(node, ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock), ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression)); + } + /** + * Visits the body of a WhileStatement to hoist declarations. + * + * @param node The node to visit. + */ + function visitWhileStatement(node) { + return ts.updateWhile(node, ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock)); + } + /** + * Visits the body of a LabeledStatement to hoist declarations. + * + * @param node The node to visit. + */ + function visitLabeledStatement(node) { + return ts.updateLabel(node, node.label, ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock)); + } + /** + * Visits the body of a WithStatement to hoist declarations. + * + * @param node The node to visit. + */ + function visitWithStatement(node) { + return ts.updateWith(node, ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock)); + } + /** + * Visits the body of a SwitchStatement to hoist declarations. + * + * @param node The node to visit. + */ + function visitSwitchStatement(node) { + return ts.updateSwitch(node, ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.caseBlock, nestedElementVisitor, ts.isCaseBlock)); + } + /** + * Visits the body of a CaseBlock to hoist declarations. + * + * @param node The node to visit. + */ + function visitCaseBlock(node) { + var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; + enclosingBlockScopedContainer = node; + node = ts.updateCaseBlock(node, ts.visitNodes(node.clauses, nestedElementVisitor, ts.isCaseOrDefaultClause)); + enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; + return node; + } + /** + * Visits the body of a CaseClause to hoist declarations. + * + * @param node The node to visit. + */ + function visitCaseClause(node) { + return ts.updateCaseClause(node, ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNodes(node.statements, nestedElementVisitor, ts.isStatement)); + } + /** + * Visits the body of a DefaultClause to hoist declarations. + * + * @param node The node to visit. + */ + function visitDefaultClause(node) { + return ts.visitEachChild(node, nestedElementVisitor, context); + } + /** + * Visits the body of a TryStatement to hoist declarations. + * + * @param node The node to visit. + */ + function visitTryStatement(node) { + return ts.visitEachChild(node, nestedElementVisitor, context); + } + /** + * Visits the body of a CatchClause to hoist declarations. + * + * @param node The node to visit. + */ + function visitCatchClause(node) { + var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; + enclosingBlockScopedContainer = node; + node = ts.updateCatchClause(node, node.variableDeclaration, ts.visitNode(node.block, nestedElementVisitor, ts.isBlock)); + enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; + return node; + } + /** + * Visits the body of a Block to hoist declarations. + * + * @param node The node to visit. + */ + function visitBlock(node) { + var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; + enclosingBlockScopedContainer = node; + node = ts.visitEachChild(node, nestedElementVisitor, context); + enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; + return node; + } + // + // Destructuring Assignment Visitors + // + /** + * Visit nodes to flatten destructuring assignments to exported symbols. + * + * @param node The node to visit. + */ + function destructuringAndImportCallVisitor(node) { + if (node.transformFlags & 1024 /* DestructuringAssignment */ + && node.kind === 204 /* BinaryExpression */) { + return visitDestructuringAssignment(node); + } + else if (ts.isImportCall(node)) { + return visitImportCallExpression(node); + } + else if ((node.transformFlags & 2048 /* ContainsDestructuringAssignment */) || (node.transformFlags & 16777216 /* ContainsDynamicImport */)) { + return ts.visitEachChild(node, destructuringAndImportCallVisitor, context); + } + else { + return node; + } + } + function visitImportCallExpression(node) { + // import("./blah") + // emit as + // System.register([], function (_export, _context) { + // return { + // setters: [], + // execute: () => { + // _context.import('./blah'); + // } + // }; + // }); + return ts.createCall(ts.createPropertyAccess(contextObject, ts.createIdentifier("import")), + /*typeArguments*/ undefined, ts.some(node.arguments) ? [ts.visitNode(node.arguments[0], destructuringAndImportCallVisitor)] : []); + } + /** + * Visits a DestructuringAssignment to flatten destructuring to exported symbols. + * + * @param node The node to visit. + */ + function visitDestructuringAssignment(node) { + if (hasExportedReferenceInDestructuringTarget(node.left)) { + return ts.flattenDestructuringAssignment(node, destructuringAndImportCallVisitor, context, 0 /* All */, + /*needsValue*/ true); + } + return ts.visitEachChild(node, destructuringAndImportCallVisitor, context); + } + /** + * Determines whether the target of a destructuring assigment refers to an exported symbol. + * + * @param node The destructuring target. + */ + function hasExportedReferenceInDestructuringTarget(node) { + if (ts.isAssignmentExpression(node, /*excludeCompoundAssignment*/ true)) { + return hasExportedReferenceInDestructuringTarget(node.left); + } + else if (ts.isSpreadElement(node)) { + return hasExportedReferenceInDestructuringTarget(node.expression); + } + else if (ts.isObjectLiteralExpression(node)) { + return ts.some(node.properties, hasExportedReferenceInDestructuringTarget); + } + else if (ts.isArrayLiteralExpression(node)) { + return ts.some(node.elements, hasExportedReferenceInDestructuringTarget); + } + else if (ts.isShorthandPropertyAssignment(node)) { + return hasExportedReferenceInDestructuringTarget(node.name); + } + else if (ts.isPropertyAssignment(node)) { + return hasExportedReferenceInDestructuringTarget(node.initializer); + } + else if (ts.isIdentifier(node)) { + var container = resolver.getReferencedExportContainer(node); + return container !== undefined && container.kind === 279 /* SourceFile */; + } + else { + return false; + } + } + // + // Modifier Visitors + // + /** + * Visit nodes to elide module-specific modifiers. + * + * @param node The node to visit. + */ + function modifierVisitor(node) { + switch (node.kind) { + case 85 /* ExportKeyword */: + case 80 /* DefaultKeyword */: + return undefined; + } + return node; + } + // + // Emit Notification + // + /** + * Hook for node emit notifications. + * + * @param hint A hint as to the intended usage of the node. + * @param node The node to emit. + * @param emitCallback A callback used to emit the node in the printer. + */ + function onEmitNode(hint, node, emitCallback) { + if (node.kind === 279 /* SourceFile */) { + var id = ts.getOriginalNodeId(node); + currentSourceFile = node; + moduleInfo = moduleInfoMap[id]; + exportFunction = exportFunctionsMap[id]; + noSubstitution = noSubstitutionMap[id]; + if (noSubstitution) { + delete noSubstitutionMap[id]; + } + previousOnEmitNode(hint, node, emitCallback); + currentSourceFile = undefined; + moduleInfo = undefined; + exportFunction = undefined; + noSubstitution = undefined; + } + else { + previousOnEmitNode(hint, node, emitCallback); + } + } + // + // Substitutions + // + /** + * Hooks node substitutions. + * + * @param hint A hint as to the intended usage of the node. + * @param node The node to substitute. + */ + function onSubstituteNode(hint, node) { + node = previousOnSubstituteNode(hint, node); + if (isSubstitutionPrevented(node)) { + return node; + } + if (hint === 1 /* Expression */) { + return substituteExpression(node); + } + else if (hint === 4 /* Unspecified */) { + return substituteUnspecified(node); + } + return node; + } + /** + * Substitute the node, if necessary. + * + * @param node The node to substitute. + */ + function substituteUnspecified(node) { + switch (node.kind) { + case 276 /* ShorthandPropertyAssignment */: + return substituteShorthandPropertyAssignment(node); + } + return node; + } + /** + * Substitution for a ShorthandPropertyAssignment whose name that may contain an imported or exported symbol. + * + * @param node The node to substitute. + */ + function substituteShorthandPropertyAssignment(node) { + var name = node.name; + if (!ts.isGeneratedIdentifier(name) && !ts.isLocalName(name)) { + var importDeclaration = resolver.getReferencedImportDeclaration(name); + if (importDeclaration) { + if (ts.isImportClause(importDeclaration)) { + return ts.setTextRange(ts.createPropertyAssignment(ts.getSynthesizedClone(name), ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent), ts.createIdentifier("default"))), + /*location*/ node); + } + else if (ts.isImportSpecifier(importDeclaration)) { + return ts.setTextRange(ts.createPropertyAssignment(ts.getSynthesizedClone(name), ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent.parent.parent), ts.getSynthesizedClone(importDeclaration.propertyName || importDeclaration.name))), + /*location*/ node); + } + } + } + return node; + } + /** + * Substitute the expression, if necessary. + * + * @param node The node to substitute. + */ + function substituteExpression(node) { + switch (node.kind) { + case 72 /* Identifier */: + return substituteExpressionIdentifier(node); + case 204 /* BinaryExpression */: + return substituteBinaryExpression(node); + case 202 /* PrefixUnaryExpression */: + case 203 /* PostfixUnaryExpression */: + return substituteUnaryExpression(node); + } + return node; + } + /** + * Substitution for an Identifier expression that may contain an imported or exported symbol. + * + * @param node The node to substitute. + */ + function substituteExpressionIdentifier(node) { + if (ts.getEmitFlags(node) & 4096 /* HelperName */) { + var externalHelpersModuleName = ts.getExternalHelpersModuleName(currentSourceFile); + if (externalHelpersModuleName) { + return ts.createPropertyAccess(externalHelpersModuleName, node); + } + return node; + } + // When we see an identifier in an expression position that + // points to an imported symbol, we should substitute a qualified + // reference to the imported symbol if one is needed. + // + // - We do not substitute generated identifiers for any reason. + // - We do not substitute identifiers tagged with the LocalName flag. + if (!ts.isGeneratedIdentifier(node) && !ts.isLocalName(node)) { + var importDeclaration = resolver.getReferencedImportDeclaration(node); + if (importDeclaration) { + if (ts.isImportClause(importDeclaration)) { + return ts.setTextRange(ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent), ts.createIdentifier("default")), + /*location*/ node); + } + else if (ts.isImportSpecifier(importDeclaration)) { + return ts.setTextRange(ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent.parent.parent), ts.getSynthesizedClone(importDeclaration.propertyName || importDeclaration.name)), + /*location*/ node); + } + } + } + return node; + } + /** + * Substitution for a BinaryExpression that may contain an imported or exported symbol. + * + * @param node The node to substitute. + */ + function substituteBinaryExpression(node) { + // When we see an assignment expression whose left-hand side is an exported symbol, + // we should ensure all exports of that symbol are updated with the correct value. + // + // - We do not substitute generated identifiers for any reason. + // - We do not substitute identifiers tagged with the LocalName flag. + // - We do not substitute identifiers that were originally the name of an enum or + // namespace due to how they are transformed in TypeScript. + // - We only substitute identifiers that are exported at the top level. + if (ts.isAssignmentOperator(node.operatorToken.kind) + && ts.isIdentifier(node.left) + && !ts.isGeneratedIdentifier(node.left) + && !ts.isLocalName(node.left) + && !ts.isDeclarationNameOfEnumOrNamespace(node.left)) { + var exportedNames = getExports(node.left); + if (exportedNames) { + // For each additional export of the declaration, apply an export assignment. + var expression = node; + for (var _i = 0, exportedNames_4 = exportedNames; _i < exportedNames_4.length; _i++) { + var exportName = exportedNames_4[_i]; + expression = createExportExpression(exportName, preventSubstitution(expression)); + } + return expression; + } + } + return node; + } + /** + * Substitution for a UnaryExpression that may contain an imported or exported symbol. + * + * @param node The node to substitute. + */ + function substituteUnaryExpression(node) { + // When we see a prefix or postfix increment expression whose operand is an exported + // symbol, we should ensure all exports of that symbol are updated with the correct + // value. + // + // - We do not substitute generated identifiers for any reason. + // - We do not substitute identifiers tagged with the LocalName flag. + // - We do not substitute identifiers that were originally the name of an enum or + // namespace due to how they are transformed in TypeScript. + // - We only substitute identifiers that are exported at the top level. + if ((node.operator === 44 /* PlusPlusToken */ || node.operator === 45 /* MinusMinusToken */) + && ts.isIdentifier(node.operand) + && !ts.isGeneratedIdentifier(node.operand) + && !ts.isLocalName(node.operand) + && !ts.isDeclarationNameOfEnumOrNamespace(node.operand)) { + var exportedNames = getExports(node.operand); + if (exportedNames) { + var expression = node.kind === 203 /* PostfixUnaryExpression */ + ? ts.setTextRange(ts.createPrefix(node.operator, node.operand), node) + : node; + for (var _i = 0, exportedNames_5 = exportedNames; _i < exportedNames_5.length; _i++) { + var exportName = exportedNames_5[_i]; + expression = createExportExpression(exportName, preventSubstitution(expression)); + } + if (node.kind === 203 /* PostfixUnaryExpression */) { + expression = node.operator === 44 /* PlusPlusToken */ + ? ts.createSubtract(preventSubstitution(expression), ts.createLiteral(1)) + : ts.createAdd(preventSubstitution(expression), ts.createLiteral(1)); + } + return expression; + } + } + return node; + } + /** + * Gets the exports of a name. + * + * @param name The name. + */ + function getExports(name) { + var exportedNames; + if (!ts.isGeneratedIdentifier(name)) { + var valueDeclaration = resolver.getReferencedImportDeclaration(name) + || resolver.getReferencedValueDeclaration(name); + if (valueDeclaration) { + var exportContainer = resolver.getReferencedExportContainer(name, /*prefixLocals*/ false); + if (exportContainer && exportContainer.kind === 279 /* SourceFile */) { + exportedNames = ts.append(exportedNames, ts.getDeclarationName(valueDeclaration)); + } + exportedNames = ts.addRange(exportedNames, moduleInfo && moduleInfo.exportedBindings[ts.getOriginalNodeId(valueDeclaration)]); + } + } + return exportedNames; + } + /** + * Prevent substitution of a node for this transformer. + * + * @param node The node which should not be substituted. + */ + function preventSubstitution(node) { + if (noSubstitution === undefined) + noSubstitution = []; + noSubstitution[ts.getNodeId(node)] = true; + return node; + } + /** + * Determines whether a node should not be substituted. + * + * @param node The node to test. + */ + function isSubstitutionPrevented(node) { + return noSubstitution && node.id && noSubstitution[node.id]; + } + } + ts.transformSystemModule = transformSystemModule; +})(ts || (ts = {})); +/*@internal*/ +var ts; +(function (ts) { + function transformES2015Module(context) { + var compilerOptions = context.getCompilerOptions(); + var previousOnEmitNode = context.onEmitNode; + var previousOnSubstituteNode = context.onSubstituteNode; + context.onEmitNode = onEmitNode; + context.onSubstituteNode = onSubstituteNode; + context.enableEmitNotification(279 /* SourceFile */); + context.enableSubstitution(72 /* Identifier */); + var currentSourceFile; + return ts.chainBundle(transformSourceFile); + function transformSourceFile(node) { + if (node.isDeclarationFile) { + return node; + } + if (ts.isExternalModule(node) || compilerOptions.isolatedModules) { + var externalHelpersModuleName = ts.getOrCreateExternalHelpersModuleNameIfNeeded(node, compilerOptions); + if (externalHelpersModuleName) { + var statements = []; + var statementOffset = ts.addPrologue(statements, node.statements); + var tslibImport = ts.createImportDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(externalHelpersModuleName)), ts.createLiteral(ts.externalHelpersModuleNameText)); + ts.addEmitFlags(tslibImport, 67108864 /* NeverApplyImportHelper */); + ts.append(statements, tslibImport); + ts.addRange(statements, ts.visitNodes(node.statements, visitor, ts.isStatement, statementOffset)); + return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements)); + } + else { + return ts.visitEachChild(node, visitor, context); + } + } + return node; + } + function visitor(node) { + switch (node.kind) { + case 248 /* ImportEqualsDeclaration */: + // Elide `import=` as it is not legal with --module ES6 + return undefined; + case 254 /* ExportAssignment */: + return visitExportAssignment(node); + } + return node; + } + function visitExportAssignment(node) { + // Elide `export=` as it is not legal with --module ES6 + return node.isExportEquals ? undefined : node; + } + // + // Emit Notification + // + /** + * Hook for node emit. + * + * @param hint A hint as to the intended usage of the node. + * @param node The node to emit. + * @param emit A callback used to emit the node in the printer. + */ + function onEmitNode(hint, node, emitCallback) { + if (ts.isSourceFile(node)) { + currentSourceFile = node; + previousOnEmitNode(hint, node, emitCallback); + currentSourceFile = undefined; + } + else { + previousOnEmitNode(hint, node, emitCallback); + } + } + // + // Substitutions + // + /** + * Hooks node substitutions. + * + * @param hint A hint as to the intended usage of the node. + * @param node The node to substitute. + */ + function onSubstituteNode(hint, node) { + node = previousOnSubstituteNode(hint, node); + if (ts.isIdentifier(node) && hint === 1 /* Expression */) { + return substituteExpressionIdentifier(node); + } + return node; + } + function substituteExpressionIdentifier(node) { + if (ts.getEmitFlags(node) & 4096 /* HelperName */) { + var externalHelpersModuleName = ts.getExternalHelpersModuleName(currentSourceFile); + if (externalHelpersModuleName) { + return ts.createPropertyAccess(externalHelpersModuleName, node); + } + } + return node; + } + } + ts.transformES2015Module = transformES2015Module; +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + function canProduceDiagnostics(node) { + return ts.isVariableDeclaration(node) || + ts.isPropertyDeclaration(node) || + ts.isPropertySignature(node) || + ts.isBindingElement(node) || + ts.isSetAccessor(node) || + ts.isGetAccessor(node) || + ts.isConstructSignatureDeclaration(node) || + ts.isCallSignatureDeclaration(node) || + ts.isMethodDeclaration(node) || + ts.isMethodSignature(node) || + ts.isFunctionDeclaration(node) || + ts.isParameter(node) || + ts.isTypeParameterDeclaration(node) || + ts.isExpressionWithTypeArguments(node) || + ts.isImportEqualsDeclaration(node) || + ts.isTypeAliasDeclaration(node) || + ts.isConstructorDeclaration(node) || + ts.isIndexSignatureDeclaration(node); + } + ts.canProduceDiagnostics = canProduceDiagnostics; + function createGetSymbolAccessibilityDiagnosticForNodeName(node) { + if (ts.isSetAccessor(node) || ts.isGetAccessor(node)) { + return getAccessorNameVisibilityError; + } + else if (ts.isMethodSignature(node) || ts.isMethodDeclaration(node)) { + return getMethodNameVisibilityError; + } + else { + return createGetSymbolAccessibilityDiagnosticForNode(node); + } + function getAccessorNameVisibilityError(symbolAccessibilityResult) { + var diagnosticMessage = getAccessorNameVisibilityDiagnosticMessage(symbolAccessibilityResult); + return diagnosticMessage !== undefined ? { + diagnosticMessage: diagnosticMessage, + errorNode: node, + typeName: node.name + } : undefined; + } + function getAccessorNameVisibilityDiagnosticMessage(symbolAccessibilityResult) { + if (ts.hasModifier(node, 32 /* Static */)) { + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1; + } + else if (node.parent.kind === 240 /* ClassDeclaration */) { + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_private_name_1; + } + else { + return symbolAccessibilityResult.errorModuleName ? + ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_private_name_1; + } + } + function getMethodNameVisibilityError(symbolAccessibilityResult) { + var diagnosticMessage = getMethodNameVisibilityDiagnosticMessage(symbolAccessibilityResult); + return diagnosticMessage !== undefined ? { + diagnosticMessage: diagnosticMessage, + errorNode: node, + typeName: node.name + } : undefined; + } + function getMethodNameVisibilityDiagnosticMessage(symbolAccessibilityResult) { + if (ts.hasModifier(node, 32 /* Static */)) { + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_private_name_1; + } + else if (node.parent.kind === 240 /* ClassDeclaration */) { + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Public_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Public_method_0_of_exported_class_has_or_is_using_private_name_1; + } + else { + return symbolAccessibilityResult.errorModuleName ? + ts.Diagnostics.Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Method_0_of_exported_interface_has_or_is_using_private_name_1; + } + } + } + ts.createGetSymbolAccessibilityDiagnosticForNodeName = createGetSymbolAccessibilityDiagnosticForNodeName; + function createGetSymbolAccessibilityDiagnosticForNode(node) { + if (ts.isVariableDeclaration(node) || ts.isPropertyDeclaration(node) || ts.isPropertySignature(node) || ts.isBindingElement(node) || ts.isConstructorDeclaration(node)) { + return getVariableDeclarationTypeVisibilityError; + } + else if (ts.isSetAccessor(node) || ts.isGetAccessor(node)) { + return getAccessorDeclarationTypeVisibilityError; + } + else if (ts.isConstructSignatureDeclaration(node) || ts.isCallSignatureDeclaration(node) || ts.isMethodDeclaration(node) || ts.isMethodSignature(node) || ts.isFunctionDeclaration(node) || ts.isIndexSignatureDeclaration(node)) { + return getReturnTypeVisibilityError; + } + else if (ts.isParameter(node)) { + if (ts.isParameterPropertyDeclaration(node) && ts.hasModifier(node.parent, 8 /* Private */)) { + return getVariableDeclarationTypeVisibilityError; + } + return getParameterDeclarationTypeVisibilityError; + } + else if (ts.isTypeParameterDeclaration(node)) { + return getTypeParameterConstraintVisibilityError; + } + else if (ts.isExpressionWithTypeArguments(node)) { + return getHeritageClauseVisibilityError; + } + else if (ts.isImportEqualsDeclaration(node)) { + return getImportEntityNameVisibilityError; + } + else if (ts.isTypeAliasDeclaration(node)) { + return getTypeAliasDeclarationVisibilityError; + } + else { + return ts.Debug.assertNever(node, "Attempted to set a declaration diagnostic context for unhandled node kind: " + ts.SyntaxKind[node.kind]); + } + function getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) { + if (node.kind === 237 /* VariableDeclaration */ || node.kind === 186 /* BindingElement */) { + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Exported_variable_0_has_or_is_using_private_name_1; + } + // This check is to ensure we don't report error on constructor parameter property as that error would be reported during parameter emit + // The only exception here is if the constructor was marked as private. we are not emitting the constructor parameters at all. + else if (node.kind === 154 /* PropertyDeclaration */ || node.kind === 153 /* PropertySignature */ || + (node.kind === 151 /* Parameter */ && ts.hasModifier(node.parent, 8 /* Private */))) { + // TODO(jfreeman): Deal with computed properties in error reporting. + if (ts.hasModifier(node, 32 /* Static */)) { + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1; + } + else if (node.parent.kind === 240 /* ClassDeclaration */ || node.kind === 151 /* Parameter */) { + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_private_name_1; + } + else { + // Interfaces cannot have types that cannot be named + return symbolAccessibilityResult.errorModuleName ? + ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_private_name_1; + } + } + } + function getVariableDeclarationTypeVisibilityError(symbolAccessibilityResult) { + var diagnosticMessage = getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult); + return diagnosticMessage !== undefined ? { + diagnosticMessage: diagnosticMessage, + errorNode: node, + typeName: node.name + } : undefined; + } + function getAccessorDeclarationTypeVisibilityError(symbolAccessibilityResult) { + var diagnosticMessage; + if (node.kind === 159 /* SetAccessor */) { + // Getters can infer the return type from the returned expression, but setters cannot, so the + // "_from_external_module_1_but_cannot_be_named" case cannot occur. + if (ts.hasModifier(node, 32 /* Static */)) { + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + ts.Diagnostics.Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1; + } + else { + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + ts.Diagnostics.Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_private_name_1; + } + } + else { + if (ts.hasModifier(node, 32 /* Static */)) { + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_private_name_1; + } + else { + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Return_type_of_public_getter_0_from_exported_class_has_or_is_using_private_name_1; + } + } + return { + diagnosticMessage: diagnosticMessage, + errorNode: node.name, + typeName: node.name + }; + } + function getReturnTypeVisibilityError(symbolAccessibilityResult) { + var diagnosticMessage; + switch (node.kind) { + case 161 /* ConstructSignature */: + // Interfaces cannot have return types that cannot be named + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + ts.Diagnostics.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : + ts.Diagnostics.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0; + break; + case 160 /* CallSignature */: + // Interfaces cannot have return types that cannot be named + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + ts.Diagnostics.Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : + ts.Diagnostics.Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0; + break; + case 162 /* IndexSignature */: + // Interfaces cannot have return types that cannot be named + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + ts.Diagnostics.Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : + ts.Diagnostics.Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0; + break; + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + if (ts.hasModifier(node, 32 /* Static */)) { + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : + ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1 : + ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0; + } + else if (node.parent.kind === 240 /* ClassDeclaration */) { + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : + ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1 : + ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0; + } + else { + // Interfaces cannot have return types that cannot be named + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + ts.Diagnostics.Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : + ts.Diagnostics.Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0; + } + break; + case 239 /* FunctionDeclaration */: + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : + ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1 : + ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_private_name_0; + break; + default: + return ts.Debug.fail("This is unknown kind for signature: " + node.kind); + } + return { + diagnosticMessage: diagnosticMessage, + errorNode: node.name || node + }; + } + function getParameterDeclarationTypeVisibilityError(symbolAccessibilityResult) { + var diagnosticMessage = getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult); + return diagnosticMessage !== undefined ? { + diagnosticMessage: diagnosticMessage, + errorNode: node, + typeName: node.name + } : undefined; + } + function getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) { + switch (node.parent.kind) { + case 157 /* Constructor */: + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1; + case 161 /* ConstructSignature */: + case 166 /* ConstructorType */: + // Interfaces cannot have parameter types that cannot be named + return symbolAccessibilityResult.errorModuleName ? + ts.Diagnostics.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1; + case 160 /* CallSignature */: + // Interfaces cannot have parameter types that cannot be named + return symbolAccessibilityResult.errorModuleName ? + ts.Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1; + case 162 /* IndexSignature */: + // Interfaces cannot have parameter types that cannot be named + return symbolAccessibilityResult.errorModuleName ? + ts.Diagnostics.Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1; + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + if (ts.hasModifier(node.parent, 32 /* Static */)) { + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1; + } + else if (node.parent.parent.kind === 240 /* ClassDeclaration */) { + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1; + } + else { + // Interfaces cannot have parameter types that cannot be named + return symbolAccessibilityResult.errorModuleName ? + ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1; + } + case 239 /* FunctionDeclaration */: + case 165 /* FunctionType */: + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_private_name_1; + default: + return ts.Debug.fail("Unknown parent for parameter: " + ts.SyntaxKind[node.parent.kind]); + } + } + function getTypeParameterConstraintVisibilityError() { + // Type parameter constraints are named by user so we should always be able to name it + var diagnosticMessage; + switch (node.parent.kind) { + case 240 /* ClassDeclaration */: + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_class_has_or_is_using_private_name_1; + break; + case 241 /* InterfaceDeclaration */: + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1; + break; + case 161 /* ConstructSignature */: + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1; + break; + case 160 /* CallSignature */: + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1; + break; + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + if (ts.hasModifier(node.parent, 32 /* Static */)) { + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1; + } + else if (node.parent.parent.kind === 240 /* ClassDeclaration */) { + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1; + } + else { + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1; + } + break; + case 239 /* FunctionDeclaration */: + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_function_has_or_is_using_private_name_1; + break; + case 242 /* TypeAliasDeclaration */: + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1; + break; + default: + return ts.Debug.fail("This is unknown parent for type parameter: " + node.parent.kind); + } + return { + diagnosticMessage: diagnosticMessage, + errorNode: node, + typeName: node.name + }; + } + function getHeritageClauseVisibilityError() { + var diagnosticMessage; + // Heritage clause is written by user so it can always be named + if (node.parent.parent.kind === 240 /* ClassDeclaration */) { + // Class or Interface implemented/extended is inaccessible + diagnosticMessage = ts.isHeritageClause(node.parent) && node.parent.token === 109 /* ImplementsKeyword */ ? + ts.Diagnostics.Implements_clause_of_exported_class_0_has_or_is_using_private_name_1 : + ts.Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1; + } + else { + // interface is inaccessible + diagnosticMessage = ts.Diagnostics.extends_clause_of_exported_interface_0_has_or_is_using_private_name_1; + } + return { + diagnosticMessage: diagnosticMessage, + errorNode: node, + typeName: ts.getNameOfDeclaration(node.parent.parent) + }; + } + function getImportEntityNameVisibilityError() { + return { + diagnosticMessage: ts.Diagnostics.Import_declaration_0_is_using_private_name_1, + errorNode: node, + typeName: node.name + }; + } + function getTypeAliasDeclarationVisibilityError() { + return { + diagnosticMessage: ts.Diagnostics.Exported_type_alias_0_has_or_is_using_private_name_1, + errorNode: node.type, + typeName: node.name + }; + } + } + ts.createGetSymbolAccessibilityDiagnosticForNode = createGetSymbolAccessibilityDiagnosticForNode; +})(ts || (ts = {})); +/*@internal*/ +var ts; +(function (ts) { + function getDeclarationDiagnostics(host, resolver, file) { + if (file && ts.isSourceFileJS(file)) { + return []; // No declaration diagnostics for js for now + } + var compilerOptions = host.getCompilerOptions(); + var result = ts.transformNodes(resolver, host, compilerOptions, file ? [file] : ts.filter(host.getSourceFiles(), ts.isSourceFileNotJS), [transformDeclarations], /*allowDtsFiles*/ false); + return result.diagnostics; + } + ts.getDeclarationDiagnostics = getDeclarationDiagnostics; + var declarationEmitNodeBuilderFlags = 1024 /* MultilineObjectLiterals */ | + 2048 /* WriteClassExpressionAsTypeLiteral */ | + 4096 /* UseTypeOfFunction */ | + 8 /* UseStructuralFallback */ | + 524288 /* AllowEmptyTuple */ | + 4 /* GenerateNamesForShadowedTypeParams */ | + 1 /* NoTruncation */; + /** + * Transforms a ts file into a .d.ts file + * This process requires type information, which is retrieved through the emit resolver. Because of this, + * in many places this transformer assumes it will be operating on parse tree nodes directly. + * This means that _no transforms should be allowed to occur before this one_. + */ + function transformDeclarations(context) { + var throwDiagnostic = function () { return ts.Debug.fail("Diagnostic emitted without context"); }; + var getSymbolAccessibilityDiagnostic = throwDiagnostic; + var needsDeclare = true; + var isBundledEmit = false; + var resultHasExternalModuleIndicator = false; + var needsScopeFixMarker = false; + var resultHasScopeMarker = false; + var enclosingDeclaration; + var necessaryTypeReferences; + var lateMarkedStatements; + var lateStatementReplacementMap; + var suppressNewDiagnosticContexts; + var exportedModulesFromDeclarationEmit; + var host = context.getEmitHost(); + var symbolTracker = { + trackSymbol: trackSymbol, + reportInaccessibleThisError: reportInaccessibleThisError, + reportInaccessibleUniqueSymbolError: reportInaccessibleUniqueSymbolError, + reportPrivateInBaseOfClassExpression: reportPrivateInBaseOfClassExpression, + reportLikelyUnsafeImportRequiredError: reportLikelyUnsafeImportRequiredError, + moduleResolverHost: host, + trackReferencedAmbientModule: trackReferencedAmbientModule, + trackExternalModuleSymbolOfImportTypeNode: trackExternalModuleSymbolOfImportTypeNode + }; + var errorNameNode; + var currentSourceFile; + var refs; + var libs; + var resolver = context.getEmitResolver(); + var options = context.getCompilerOptions(); + var newLine = ts.getNewLineCharacter(options); + var noResolve = options.noResolve, stripInternal = options.stripInternal; + return transformRoot; + function recordTypeReferenceDirectivesIfNecessary(typeReferenceDirectives) { + if (!typeReferenceDirectives) { + return; + } + necessaryTypeReferences = necessaryTypeReferences || ts.createMap(); + for (var _i = 0, typeReferenceDirectives_2 = typeReferenceDirectives; _i < typeReferenceDirectives_2.length; _i++) { + var ref = typeReferenceDirectives_2[_i]; + necessaryTypeReferences.set(ref, true); + } + } + function trackReferencedAmbientModule(node, symbol) { + // If it is visible via `// `, then we should just use that + var directives = resolver.getTypeReferenceDirectivesForSymbol(symbol, 67108863 /* All */); + if (ts.length(directives)) { + return recordTypeReferenceDirectivesIfNecessary(directives); + } + // Otherwise we should emit a path-based reference + var container = ts.getSourceFileOfNode(node); + refs.set("" + ts.getOriginalNodeId(container), container); + } + function handleSymbolAccessibilityError(symbolAccessibilityResult) { + if (symbolAccessibilityResult.accessibility === 0 /* Accessible */) { + // Add aliases back onto the possible imports list if they're not there so we can try them again with updated visibility info + if (symbolAccessibilityResult && symbolAccessibilityResult.aliasesToMakeVisible) { + if (!lateMarkedStatements) { + lateMarkedStatements = symbolAccessibilityResult.aliasesToMakeVisible; + } + else { + for (var _i = 0, _a = symbolAccessibilityResult.aliasesToMakeVisible; _i < _a.length; _i++) { + var ref = _a[_i]; + ts.pushIfUnique(lateMarkedStatements, ref); + } + } + } + // TODO: Do all these accessibility checks inside/after the first pass in the checker when declarations are enabled, if possible + } + else { + // Report error + var errorInfo = getSymbolAccessibilityDiagnostic(symbolAccessibilityResult); + if (errorInfo) { + if (errorInfo.typeName) { + context.addDiagnostic(ts.createDiagnosticForNode(symbolAccessibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, ts.getTextOfNode(errorInfo.typeName), symbolAccessibilityResult.errorSymbolName, symbolAccessibilityResult.errorModuleName)); + } + else { + context.addDiagnostic(ts.createDiagnosticForNode(symbolAccessibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, symbolAccessibilityResult.errorSymbolName, symbolAccessibilityResult.errorModuleName)); + } + } + } + } + function trackExternalModuleSymbolOfImportTypeNode(symbol) { + if (!isBundledEmit) { + (exportedModulesFromDeclarationEmit || (exportedModulesFromDeclarationEmit = [])).push(symbol); + } + } + function trackSymbol(symbol, enclosingDeclaration, meaning) { + if (symbol.flags & 262144 /* TypeParameter */) + return; + handleSymbolAccessibilityError(resolver.isSymbolAccessible(symbol, enclosingDeclaration, meaning, /*shouldComputeAliasesToMakeVisible*/ true)); + recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForSymbol(symbol, meaning)); + } + function reportPrivateInBaseOfClassExpression(propertyName) { + if (errorNameNode) { + context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.Property_0_of_exported_class_expression_may_not_be_private_or_protected, propertyName)); + } + } + function reportInaccessibleUniqueSymbolError() { + if (errorNameNode) { + context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary, ts.declarationNameToString(errorNameNode), "unique symbol")); + } + } + function reportInaccessibleThisError() { + if (errorNameNode) { + context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary, ts.declarationNameToString(errorNameNode), "this")); + } + } + function reportLikelyUnsafeImportRequiredError(specifier) { + if (errorNameNode) { + context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_annotation_is_necessary, ts.declarationNameToString(errorNameNode), specifier)); + } + } + function transformRoot(node) { + if (node.kind === 279 /* SourceFile */ && (node.isDeclarationFile || ts.isSourceFileJS(node))) { + return node; + } + if (node.kind === 280 /* Bundle */) { + isBundledEmit = true; + refs = ts.createMap(); + libs = ts.createMap(); + var hasNoDefaultLib_1 = false; + var bundle = ts.createBundle(ts.map(node.sourceFiles, function (sourceFile) { + if (sourceFile.isDeclarationFile || ts.isSourceFileJS(sourceFile)) + return undefined; // Omit declaration files from bundle results, too // TODO: GH#18217 + hasNoDefaultLib_1 = hasNoDefaultLib_1 || sourceFile.hasNoDefaultLib; + currentSourceFile = sourceFile; + enclosingDeclaration = sourceFile; + lateMarkedStatements = undefined; + suppressNewDiagnosticContexts = false; + lateStatementReplacementMap = ts.createMap(); + getSymbolAccessibilityDiagnostic = throwDiagnostic; + needsScopeFixMarker = false; + resultHasScopeMarker = false; + collectReferences(sourceFile, refs); + collectLibs(sourceFile, libs); + if (ts.isExternalModule(sourceFile)) { + resultHasExternalModuleIndicator = false; // unused in external module bundle emit (all external modules are within module blocks, therefore are known to be modules) + needsDeclare = false; + var statements_4 = ts.visitNodes(sourceFile.statements, visitDeclarationStatements); + var newFile = ts.updateSourceFileNode(sourceFile, [ts.createModuleDeclaration([], [ts.createModifier(125 /* DeclareKeyword */)], ts.createLiteral(ts.getResolvedExternalModuleName(context.getEmitHost(), sourceFile)), ts.createModuleBlock(ts.setTextRange(ts.createNodeArray(transformAndReplaceLatePaintedStatements(statements_4)), sourceFile.statements)))], /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false, /*libReferences*/ []); + return newFile; + } + needsDeclare = true; + var updated = ts.visitNodes(sourceFile.statements, visitDeclarationStatements); + return ts.updateSourceFileNode(sourceFile, transformAndReplaceLatePaintedStatements(updated), /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false, /*libReferences*/ []); + }), ts.mapDefined(node.prepends, function (prepend) { + if (prepend.kind === 282 /* InputFiles */) { + return ts.createUnparsedSourceFile(prepend.declarationText, prepend.declarationMapPath, prepend.declarationMapText); + } + })); + bundle.syntheticFileReferences = []; + bundle.syntheticTypeReferences = getFileReferencesForUsedTypeReferences(); + bundle.syntheticLibReferences = getLibReferences(); + bundle.hasNoDefaultLib = hasNoDefaultLib_1; + var outputFilePath_1 = ts.getDirectoryPath(ts.normalizeSlashes(ts.getOutputPathsFor(node, host, /*forceDtsPaths*/ true).declarationFilePath)); + var referenceVisitor_1 = mapReferencesIntoArray(bundle.syntheticFileReferences, outputFilePath_1); + refs.forEach(referenceVisitor_1); + return bundle; + } + // Single source file + needsDeclare = true; + needsScopeFixMarker = false; + resultHasScopeMarker = false; + enclosingDeclaration = node; + currentSourceFile = node; + getSymbolAccessibilityDiagnostic = throwDiagnostic; + isBundledEmit = false; + resultHasExternalModuleIndicator = false; + suppressNewDiagnosticContexts = false; + lateMarkedStatements = undefined; + lateStatementReplacementMap = ts.createMap(); + necessaryTypeReferences = undefined; + refs = collectReferences(currentSourceFile, ts.createMap()); + libs = collectLibs(currentSourceFile, ts.createMap()); + var references = []; + var outputFilePath = ts.getDirectoryPath(ts.normalizeSlashes(ts.getOutputPathsFor(node, host, /*forceDtsPaths*/ true).declarationFilePath)); + var referenceVisitor = mapReferencesIntoArray(references, outputFilePath); + var statements = ts.visitNodes(node.statements, visitDeclarationStatements); + var combinedStatements = ts.setTextRange(ts.createNodeArray(transformAndReplaceLatePaintedStatements(statements)), node.statements); + refs.forEach(referenceVisitor); + var emittedImports = ts.filter(combinedStatements, ts.isAnyImportSyntax); + if (ts.isExternalModule(node) && (!resultHasExternalModuleIndicator || (needsScopeFixMarker && !resultHasScopeMarker))) { + combinedStatements = ts.setTextRange(ts.createNodeArray(combinedStatements.concat([ts.createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createNamedExports([]), /*moduleSpecifier*/ undefined)])), combinedStatements); + } + var updated = ts.updateSourceFileNode(node, combinedStatements, /*isDeclarationFile*/ true, references, getFileReferencesForUsedTypeReferences(), node.hasNoDefaultLib, getLibReferences()); + updated.exportedModulesFromDeclarationEmit = exportedModulesFromDeclarationEmit; + return updated; + function getLibReferences() { + return ts.map(ts.arrayFrom(libs.keys()), function (lib) { return ({ fileName: lib, pos: -1, end: -1 }); }); + } + function getFileReferencesForUsedTypeReferences() { + return necessaryTypeReferences ? ts.mapDefined(ts.arrayFrom(necessaryTypeReferences.keys()), getFileReferenceForTypeName) : []; + } + function getFileReferenceForTypeName(typeName) { + // Elide type references for which we have imports + if (emittedImports) { + for (var _i = 0, emittedImports_1 = emittedImports; _i < emittedImports_1.length; _i++) { + var importStatement = emittedImports_1[_i]; + if (ts.isImportEqualsDeclaration(importStatement) && ts.isExternalModuleReference(importStatement.moduleReference)) { + var expr = importStatement.moduleReference.expression; + if (ts.isStringLiteralLike(expr) && expr.text === typeName) { + return undefined; + } + } + else if (ts.isImportDeclaration(importStatement) && ts.isStringLiteral(importStatement.moduleSpecifier) && importStatement.moduleSpecifier.text === typeName) { + return undefined; + } + } + } + return { fileName: typeName, pos: -1, end: -1 }; + } + function mapReferencesIntoArray(references, outputFilePath) { + return function (file) { + var declFileName; + if (file.isDeclarationFile) { // Neither decl files or js should have their refs changed + declFileName = file.fileName; + } + else { + if (isBundledEmit && ts.contains(node.sourceFiles, file)) + return; // Omit references to files which are being merged + var paths = ts.getOutputPathsFor(file, host, /*forceDtsPaths*/ true); + declFileName = paths.declarationFilePath || paths.jsFilePath || file.fileName; + } + if (declFileName) { + var fileName = ts.getRelativePathToDirectoryOrUrl(outputFilePath, declFileName, host.getCurrentDirectory(), host.getCanonicalFileName, + /*isAbsolutePathAnUrl*/ false); + if (ts.startsWith(fileName, "./") && ts.hasExtension(fileName)) { + fileName = fileName.substring(2); + } + // omit references to files from node_modules (npm may disambiguate module + // references when installing this package, making the path is unreliable). + if (ts.startsWith(fileName, "node_modules/") || fileName.indexOf("/node_modules/") !== -1) { + return; + } + references.push({ pos: -1, end: -1, fileName: fileName }); + } + }; + } + } + function collectReferences(sourceFile, ret) { + if (noResolve || ts.isSourceFileJS(sourceFile)) + return ret; + ts.forEach(sourceFile.referencedFiles, function (f) { + var elem = ts.tryResolveScriptReference(host, sourceFile, f); + if (elem) { + ret.set("" + ts.getOriginalNodeId(elem), elem); + } + }); + return ret; + } + function collectLibs(sourceFile, ret) { + ts.forEach(sourceFile.libReferenceDirectives, function (ref) { + var lib = host.getLibFileFromReference(ref); + if (lib) { + ret.set(ref.fileName.toLocaleLowerCase(), true); + } + }); + return ret; + } + function filterBindingPatternInitializers(name) { + if (name.kind === 72 /* Identifier */) { + return name; + } + else { + if (name.kind === 185 /* ArrayBindingPattern */) { + return ts.updateArrayBindingPattern(name, ts.visitNodes(name.elements, visitBindingElement)); + } + else { + return ts.updateObjectBindingPattern(name, ts.visitNodes(name.elements, visitBindingElement)); + } + } + function visitBindingElement(elem) { + if (elem.kind === 210 /* OmittedExpression */) { + return elem; + } + return ts.updateBindingElement(elem, elem.dotDotDotToken, elem.propertyName, filterBindingPatternInitializers(elem.name), shouldPrintWithInitializer(elem) ? elem.initializer : undefined); + } + } + function ensureParameter(p, modifierMask) { + var oldDiag; + if (!suppressNewDiagnosticContexts) { + oldDiag = getSymbolAccessibilityDiagnostic; + getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(p); + } + var newParam = ts.updateParameter(p, + /*decorators*/ undefined, maskModifiers(p, modifierMask), p.dotDotDotToken, filterBindingPatternInitializers(p.name), resolver.isOptionalParameter(p) ? (p.questionToken || ts.createToken(56 /* QuestionToken */)) : undefined, ensureType(p, p.type, /*ignorePrivate*/ true), // Ignore private param props, since this type is going straight back into a param + ensureNoInitializer(p)); + if (!suppressNewDiagnosticContexts) { + getSymbolAccessibilityDiagnostic = oldDiag; + } + return newParam; + } + function shouldPrintWithInitializer(node) { + return canHaveLiteralInitializer(node) && resolver.isLiteralConstDeclaration(ts.getParseTreeNode(node)); // TODO: Make safe + } + function ensureNoInitializer(node) { + if (shouldPrintWithInitializer(node)) { + return resolver.createLiteralConstValue(ts.getParseTreeNode(node), symbolTracker); // TODO: Make safe + } + return undefined; + } + function ensureType(node, type, ignorePrivate) { + if (!ignorePrivate && ts.hasModifier(node, 8 /* Private */)) { + // Private nodes emit no types (except private parameter properties, whose parameter types are actually visible) + return; + } + if (shouldPrintWithInitializer(node)) { + // Literal const declarations will have an initializer ensured rather than a type + return; + } + var shouldUseResolverType = node.kind === 151 /* Parameter */ && + (resolver.isRequiredInitializedParameter(node) || + resolver.isOptionalUninitializedParameterProperty(node)); + if (type && !shouldUseResolverType) { + return ts.visitNode(type, visitDeclarationSubtree); + } + if (!ts.getParseTreeNode(node)) { + return type ? ts.visitNode(type, visitDeclarationSubtree) : ts.createKeywordTypeNode(120 /* AnyKeyword */); + } + if (node.kind === 159 /* SetAccessor */) { + // Set accessors with no associated type node (from it's param or get accessor return) are `any` since they are never contextually typed right now + // (The inferred type here will be void, but the old declaration emitter printed `any`, so this replicates that) + return ts.createKeywordTypeNode(120 /* AnyKeyword */); + } + errorNameNode = node.name; + var oldDiag; + if (!suppressNewDiagnosticContexts) { + oldDiag = getSymbolAccessibilityDiagnostic; + getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(node); + } + if (node.kind === 237 /* VariableDeclaration */ || node.kind === 186 /* BindingElement */) { + return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker)); + } + if (node.kind === 151 /* Parameter */ + || node.kind === 154 /* PropertyDeclaration */ + || node.kind === 153 /* PropertySignature */) { + if (!node.initializer) + return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker, shouldUseResolverType)); + return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker, shouldUseResolverType) || resolver.createTypeOfExpression(node.initializer, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker)); + } + return cleanup(resolver.createReturnTypeOfSignatureDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker)); + function cleanup(returnValue) { + errorNameNode = undefined; + if (!suppressNewDiagnosticContexts) { + getSymbolAccessibilityDiagnostic = oldDiag; + } + return returnValue || ts.createKeywordTypeNode(120 /* AnyKeyword */); + } + } + function isDeclarationAndNotVisible(node) { + node = ts.getParseTreeNode(node); + switch (node.kind) { + case 239 /* FunctionDeclaration */: + case 244 /* ModuleDeclaration */: + case 241 /* InterfaceDeclaration */: + case 240 /* ClassDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 243 /* EnumDeclaration */: + return !resolver.isDeclarationVisible(node); + // The following should be doing their own visibility checks based on filtering their members + case 237 /* VariableDeclaration */: + return !getBindingNameVisible(node); + case 248 /* ImportEqualsDeclaration */: + case 249 /* ImportDeclaration */: + case 255 /* ExportDeclaration */: + case 254 /* ExportAssignment */: + return false; + } + return false; + } + function getBindingNameVisible(elem) { + if (ts.isOmittedExpression(elem)) { + return false; + } + if (ts.isBindingPattern(elem.name)) { + // If any child binding pattern element has been marked visible (usually by collect linked aliases), then this is visible + return ts.some(elem.name.elements, getBindingNameVisible); + } + else { + return resolver.isDeclarationVisible(elem); + } + } + function updateParamsList(node, params, modifierMask) { + if (ts.hasModifier(node, 8 /* Private */)) { + return undefined; // TODO: GH#18217 + } + var newParams = ts.map(params, function (p) { return ensureParameter(p, modifierMask); }); + if (!newParams) { + return undefined; // TODO: GH#18217 + } + return ts.createNodeArray(newParams, params.hasTrailingComma); + } + function ensureTypeParams(node, params) { + return ts.hasModifier(node, 8 /* Private */) ? undefined : ts.visitNodes(params, visitDeclarationSubtree); + } + function isEnclosingDeclaration(node) { + return ts.isSourceFile(node) + || ts.isTypeAliasDeclaration(node) + || ts.isModuleDeclaration(node) + || ts.isClassDeclaration(node) + || ts.isInterfaceDeclaration(node) + || ts.isFunctionLike(node) + || ts.isIndexSignatureDeclaration(node) + || ts.isMappedTypeNode(node); + } + function checkEntityNameVisibility(entityName, enclosingDeclaration) { + var visibilityResult = resolver.isEntityNameVisible(entityName, enclosingDeclaration); + handleSymbolAccessibilityError(visibilityResult); + recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForEntityName(entityName)); + } + function preserveJsDoc(updated, original) { + if (ts.hasJSDocNodes(updated) && ts.hasJSDocNodes(original)) { + updated.jsDoc = original.jsDoc; + } + return ts.setCommentRange(updated, ts.getCommentRange(original)); + } + function rewriteModuleSpecifier(parent, input) { + if (!input) + return undefined; // TODO: GH#18217 + resultHasExternalModuleIndicator = resultHasExternalModuleIndicator || (parent.kind !== 244 /* ModuleDeclaration */ && parent.kind !== 183 /* ImportType */); + if (ts.isStringLiteralLike(input)) { + if (isBundledEmit) { + var newName = ts.getExternalModuleNameFromDeclaration(context.getEmitHost(), resolver, parent); + if (newName) { + return ts.createLiteral(newName); + } + } + else { + var symbol = resolver.getSymbolOfExternalModuleSpecifier(input); + if (symbol) { + (exportedModulesFromDeclarationEmit || (exportedModulesFromDeclarationEmit = [])).push(symbol); + } + } + } + return input; + } + function transformImportEqualsDeclaration(decl) { + if (!resolver.isDeclarationVisible(decl)) + return; + if (decl.moduleReference.kind === 259 /* ExternalModuleReference */) { + // Rewrite external module names if necessary + var specifier = ts.getExternalModuleImportEqualsDeclarationExpression(decl); + return ts.updateImportEqualsDeclaration(decl, + /*decorators*/ undefined, decl.modifiers, decl.name, ts.updateExternalModuleReference(decl.moduleReference, rewriteModuleSpecifier(decl, specifier))); + } + else { + var oldDiag = getSymbolAccessibilityDiagnostic; + getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(decl); + checkEntityNameVisibility(decl.moduleReference, enclosingDeclaration); + getSymbolAccessibilityDiagnostic = oldDiag; + return decl; + } + } + function transformImportDeclaration(decl) { + if (!decl.importClause) { + // import "mod" - possibly needed for side effects? (global interface patches, module augmentations, etc) + return ts.updateImportDeclaration(decl, + /*decorators*/ undefined, decl.modifiers, decl.importClause, rewriteModuleSpecifier(decl, decl.moduleSpecifier)); + } + // The `importClause` visibility corresponds to the default's visibility. + var visibleDefaultBinding = decl.importClause && decl.importClause.name && resolver.isDeclarationVisible(decl.importClause) ? decl.importClause.name : undefined; + if (!decl.importClause.namedBindings) { + // No named bindings (either namespace or list), meaning the import is just default or should be elided + return visibleDefaultBinding && ts.updateImportDeclaration(decl, /*decorators*/ undefined, decl.modifiers, ts.updateImportClause(decl.importClause, visibleDefaultBinding, + /*namedBindings*/ undefined), rewriteModuleSpecifier(decl, decl.moduleSpecifier)); + } + if (decl.importClause.namedBindings.kind === 251 /* NamespaceImport */) { + // Namespace import (optionally with visible default) + var namedBindings = resolver.isDeclarationVisible(decl.importClause.namedBindings) ? decl.importClause.namedBindings : /*namedBindings*/ undefined; + return visibleDefaultBinding || namedBindings ? ts.updateImportDeclaration(decl, /*decorators*/ undefined, decl.modifiers, ts.updateImportClause(decl.importClause, visibleDefaultBinding, namedBindings), rewriteModuleSpecifier(decl, decl.moduleSpecifier)) : undefined; + } + // Named imports (optionally with visible default) + var bindingList = ts.mapDefined(decl.importClause.namedBindings.elements, function (b) { return resolver.isDeclarationVisible(b) ? b : undefined; }); + if ((bindingList && bindingList.length) || visibleDefaultBinding) { + return ts.updateImportDeclaration(decl, + /*decorators*/ undefined, decl.modifiers, ts.updateImportClause(decl.importClause, visibleDefaultBinding, bindingList && bindingList.length ? ts.updateNamedImports(decl.importClause.namedBindings, bindingList) : undefined), rewriteModuleSpecifier(decl, decl.moduleSpecifier)); + } + // Nothing visible + } + function transformAndReplaceLatePaintedStatements(statements) { + // This is a `while` loop because `handleSymbolAccessibilityError` can see additional import aliases marked as visible during + // error handling which must now be included in the output and themselves checked for errors. + // For example: + // ``` + // module A { + // export module Q {} + // import B = Q; + // import C = B; + // export import D = C; + // } + // ``` + // In such a scenario, only Q and D are initially visible, but we don't consider imports as private names - instead we say they if they are referenced they must + // be recorded. So while checking D's visibility we mark C as visible, then we must check C which in turn marks B, completing the chain of + // dependent imports and allowing a valid declaration file output. Today, this dependent alias marking only happens for internal import aliases. + while (ts.length(lateMarkedStatements)) { + var i = lateMarkedStatements.shift(); + if (!ts.isLateVisibilityPaintedStatement(i)) { + return ts.Debug.fail("Late replaced statement was found which is not handled by the declaration transformer!: " + (ts.SyntaxKind ? ts.SyntaxKind[i.kind] : i.kind)); + } + var result = transformTopLevelDeclaration(i, /*privateDeclaration*/ true); + lateStatementReplacementMap.set("" + ts.getOriginalNodeId(i), result); + } + // And lastly, we need to get the final form of all those indetermine import declarations from before and add them to the output list + // (and remove them from the set to examine for outter declarations) + return ts.visitNodes(statements, visitLateVisibilityMarkedStatements); + function visitLateVisibilityMarkedStatements(statement) { + if (ts.isLateVisibilityPaintedStatement(statement)) { + var key = "" + ts.getOriginalNodeId(statement); + if (lateStatementReplacementMap.has(key)) { + var result = lateStatementReplacementMap.get(key); + lateStatementReplacementMap.delete(key); + if (result && ts.isSourceFile(statement.parent)) { + if (ts.isArray(result) ? ts.some(result, needsScopeMarker) : needsScopeMarker(result)) { + // Top-level declarations in .d.ts files are always considered exported even without a modifier unless there's an export assignment or specifier + needsScopeFixMarker = true; + } + if (ts.isArray(result) ? ts.some(result, isExternalModuleIndicator) : isExternalModuleIndicator(result)) { + resultHasExternalModuleIndicator = true; + } + } + return result; + } + } + return statement; + } + } + function isExternalModuleIndicator(result) { + // Exported top-level member indicates moduleness + return ts.isAnyImportOrReExport(result) || ts.isExportAssignment(result) || ts.hasModifier(result, 1 /* Export */); + } + function needsScopeMarker(result) { + return !ts.isAnyImportOrReExport(result) && !ts.isExportAssignment(result) && !ts.hasModifier(result, 1 /* Export */) && !ts.isAmbientModule(result); + } + function visitDeclarationSubtree(input) { + if (shouldStripInternal(input)) + return; + if (ts.isDeclaration(input)) { + if (isDeclarationAndNotVisible(input)) + return; + if (ts.hasDynamicName(input) && !resolver.isLateBound(ts.getParseTreeNode(input))) { + return; + } + } + // Elide implementation signatures from overload sets + if (ts.isFunctionLike(input) && resolver.isImplementationOfOverload(input)) + return; + // Elide semicolon class statements + if (ts.isSemicolonClassElement(input)) + return; + var previousEnclosingDeclaration; + if (isEnclosingDeclaration(input)) { + previousEnclosingDeclaration = enclosingDeclaration; + enclosingDeclaration = input; + } + var oldDiag = getSymbolAccessibilityDiagnostic; + // Emit methods which are private as properties with no type information + if (ts.isMethodDeclaration(input) || ts.isMethodSignature(input)) { + if (ts.hasModifier(input, 8 /* Private */)) { + if (input.symbol && input.symbol.declarations && input.symbol.declarations[0] !== input) + return; // Elide all but the first overload + return cleanup(ts.createProperty(/*decorators*/ undefined, ensureModifiers(input), input.name, /*questionToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined)); + } + } + var canProdiceDiagnostic = ts.canProduceDiagnostics(input); + if (canProdiceDiagnostic && !suppressNewDiagnosticContexts) { + getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(input); + } + if (ts.isTypeQueryNode(input)) { + checkEntityNameVisibility(input.exprName, enclosingDeclaration); + } + var oldWithinObjectLiteralType = suppressNewDiagnosticContexts; + var shouldEnterSuppressNewDiagnosticsContextContext = ((input.kind === 168 /* TypeLiteral */ || input.kind === 181 /* MappedType */) && input.parent.kind !== 242 /* TypeAliasDeclaration */); + if (shouldEnterSuppressNewDiagnosticsContextContext) { + // We stop making new diagnostic contexts within object literal types. Unless it's an object type on the RHS of a type alias declaration. Then we do. + suppressNewDiagnosticContexts = true; + } + if (isProcessedComponent(input)) { + switch (input.kind) { + case 211 /* ExpressionWithTypeArguments */: { + if ((ts.isEntityName(input.expression) || ts.isEntityNameExpression(input.expression))) { + checkEntityNameVisibility(input.expression, enclosingDeclaration); + } + var node = ts.visitEachChild(input, visitDeclarationSubtree, context); + return cleanup(ts.updateExpressionWithTypeArguments(node, ts.parenthesizeTypeParameters(node.typeArguments), node.expression)); + } + case 164 /* TypeReference */: { + checkEntityNameVisibility(input.typeName, enclosingDeclaration); + var node = ts.visitEachChild(input, visitDeclarationSubtree, context); + return cleanup(ts.updateTypeReferenceNode(node, node.typeName, ts.parenthesizeTypeParameters(node.typeArguments))); + } + case 161 /* ConstructSignature */: + return cleanup(ts.updateConstructSignature(input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type))); + case 157 /* Constructor */: { + var isPrivate = ts.hasModifier(input, 8 /* Private */); + // A constructor declaration may not have a type annotation + var ctor = ts.createSignatureDeclaration(157 /* Constructor */, isPrivate ? undefined : ensureTypeParams(input, input.typeParameters), + // TODO: GH#18217 + isPrivate ? undefined : updateParamsList(input, input.parameters, 0 /* None */), + /*type*/ undefined); + ctor.modifiers = ts.createNodeArray(ensureModifiers(input)); + return cleanup(ctor); + } + case 156 /* MethodDeclaration */: { + var sig = ts.createSignatureDeclaration(155 /* MethodSignature */, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type)); + sig.name = input.name; + sig.modifiers = ts.createNodeArray(ensureModifiers(input)); + sig.questionToken = input.questionToken; + return cleanup(sig); + } + case 158 /* GetAccessor */: { + var newNode = ensureAccessor(input); + return cleanup(newNode); + } + case 159 /* SetAccessor */: { + var newNode = ensureAccessor(input); + return cleanup(newNode); + } + case 154 /* PropertyDeclaration */: + return cleanup(ts.updateProperty(input, + /*decorators*/ undefined, ensureModifiers(input), input.name, input.questionToken, !ts.hasModifier(input, 8 /* Private */) ? ensureType(input, input.type) : undefined, ensureNoInitializer(input))); + case 153 /* PropertySignature */: + return cleanup(ts.updatePropertySignature(input, ensureModifiers(input), input.name, input.questionToken, !ts.hasModifier(input, 8 /* Private */) ? ensureType(input, input.type) : undefined, ensureNoInitializer(input))); + case 155 /* MethodSignature */: { + return cleanup(ts.updateMethodSignature(input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type), input.name, input.questionToken)); + } + case 160 /* CallSignature */: { + return cleanup(ts.updateCallSignature(input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type))); + } + case 162 /* IndexSignature */: { + return cleanup(ts.updateIndexSignature(input, + /*decorators*/ undefined, ensureModifiers(input), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree) || ts.createKeywordTypeNode(120 /* AnyKeyword */))); + } + case 237 /* VariableDeclaration */: { + if (ts.isBindingPattern(input.name)) { + return recreateBindingPattern(input.name); + } + shouldEnterSuppressNewDiagnosticsContextContext = true; + suppressNewDiagnosticContexts = true; // Variable declaration types also suppress new diagnostic contexts, provided the contexts wouldn't be made for binding pattern types + return cleanup(ts.updateVariableDeclaration(input, input.name, ensureType(input, input.type), ensureNoInitializer(input))); + } + case 150 /* TypeParameter */: { + if (isPrivateMethodTypeParameter(input) && (input.default || input.constraint)) { + return cleanup(ts.updateTypeParameterDeclaration(input, input.name, /*constraint*/ undefined, /*defaultType*/ undefined)); + } + return cleanup(ts.visitEachChild(input, visitDeclarationSubtree, context)); + } + case 175 /* ConditionalType */: { + // We have to process conditional types in a special way because for visibility purposes we need to push a new enclosingDeclaration + // just for the `infer` types in the true branch. It's an implicit declaration scope that only applies to _part_ of the type. + var checkType = ts.visitNode(input.checkType, visitDeclarationSubtree); + var extendsType = ts.visitNode(input.extendsType, visitDeclarationSubtree); + var oldEnclosingDecl = enclosingDeclaration; + enclosingDeclaration = input.trueType; + var trueType = ts.visitNode(input.trueType, visitDeclarationSubtree); + enclosingDeclaration = oldEnclosingDecl; + var falseType = ts.visitNode(input.falseType, visitDeclarationSubtree); + return cleanup(ts.updateConditionalTypeNode(input, checkType, extendsType, trueType, falseType)); + } + case 165 /* FunctionType */: { + return cleanup(ts.updateFunctionTypeNode(input, ts.visitNodes(input.typeParameters, visitDeclarationSubtree), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree))); + } + case 166 /* ConstructorType */: { + return cleanup(ts.updateConstructorTypeNode(input, ts.visitNodes(input.typeParameters, visitDeclarationSubtree), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree))); + } + case 183 /* ImportType */: { + if (!ts.isLiteralImportTypeNode(input)) + return cleanup(input); + return cleanup(ts.updateImportTypeNode(input, ts.updateLiteralTypeNode(input.argument, rewriteModuleSpecifier(input, input.argument.literal)), input.qualifier, ts.visitNodes(input.typeArguments, visitDeclarationSubtree, ts.isTypeNode), input.isTypeOf)); + } + default: ts.Debug.assertNever(input, "Attempted to process unhandled node kind: " + ts.SyntaxKind[input.kind]); + } + } + return cleanup(ts.visitEachChild(input, visitDeclarationSubtree, context)); + function cleanup(returnValue) { + if (returnValue && canProdiceDiagnostic && ts.hasDynamicName(input)) { + checkName(input); + } + if (isEnclosingDeclaration(input)) { + enclosingDeclaration = previousEnclosingDeclaration; + } + if (canProdiceDiagnostic && !suppressNewDiagnosticContexts) { + getSymbolAccessibilityDiagnostic = oldDiag; + } + if (shouldEnterSuppressNewDiagnosticsContextContext) { + suppressNewDiagnosticContexts = oldWithinObjectLiteralType; + } + if (returnValue === input) { + return returnValue; + } + return returnValue && ts.setOriginalNode(preserveJsDoc(returnValue, input), input); + } + } + function isPrivateMethodTypeParameter(node) { + return node.parent.kind === 156 /* MethodDeclaration */ && ts.hasModifier(node.parent, 8 /* Private */); + } + function visitDeclarationStatements(input) { + if (!isPreservedDeclarationStatement(input)) { + // return undefined for unmatched kinds to omit them from the tree + return; + } + if (shouldStripInternal(input)) + return; + switch (input.kind) { + case 255 /* ExportDeclaration */: { + if (ts.isSourceFile(input.parent)) { + resultHasExternalModuleIndicator = true; + resultHasScopeMarker = true; + } + // Always visible if the parent node isn't dropped for being not visible + // Rewrite external module names if necessary + return ts.updateExportDeclaration(input, /*decorators*/ undefined, input.modifiers, input.exportClause, rewriteModuleSpecifier(input, input.moduleSpecifier)); + } + case 254 /* ExportAssignment */: { + // Always visible if the parent node isn't dropped for being not visible + if (ts.isSourceFile(input.parent)) { + resultHasExternalModuleIndicator = true; + resultHasScopeMarker = true; + } + if (input.expression.kind === 72 /* Identifier */) { + return input; + } + else { + var newId = ts.createOptimisticUniqueName("_default"); + getSymbolAccessibilityDiagnostic = function () { return ({ + diagnosticMessage: ts.Diagnostics.Default_export_of_the_module_has_or_is_using_private_name_0, + errorNode: input + }); }; + var varDecl = ts.createVariableDeclaration(newId, resolver.createTypeOfExpression(input.expression, input, declarationEmitNodeBuilderFlags, symbolTracker), /*initializer*/ undefined); + var statement = ts.createVariableStatement(needsDeclare ? [ts.createModifier(125 /* DeclareKeyword */)] : [], ts.createVariableDeclarationList([varDecl], 2 /* Const */)); + return [statement, ts.updateExportAssignment(input, input.decorators, input.modifiers, newId)]; + } + } + } + var result = transformTopLevelDeclaration(input); + // Don't actually transform yet; just leave as original node - will be elided/swapped by late pass + lateStatementReplacementMap.set("" + ts.getOriginalNodeId(input), result); + return input; + } + function transformTopLevelDeclaration(input, isPrivate) { + if (shouldStripInternal(input)) + return; + switch (input.kind) { + case 248 /* ImportEqualsDeclaration */: { + return transformImportEqualsDeclaration(input); + } + case 249 /* ImportDeclaration */: { + return transformImportDeclaration(input); + } + } + if (ts.isDeclaration(input) && isDeclarationAndNotVisible(input)) + return; + // Elide implementation signatures from overload sets + if (ts.isFunctionLike(input) && resolver.isImplementationOfOverload(input)) + return; + var previousEnclosingDeclaration; + if (isEnclosingDeclaration(input)) { + previousEnclosingDeclaration = enclosingDeclaration; + enclosingDeclaration = input; + } + var canProdiceDiagnostic = ts.canProduceDiagnostics(input); + var oldDiag = getSymbolAccessibilityDiagnostic; + if (canProdiceDiagnostic) { + getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(input); + } + var previousNeedsDeclare = needsDeclare; + switch (input.kind) { + case 242 /* TypeAliasDeclaration */: // Type aliases get `declare`d if need be (for legacy support), but that's all + return cleanup(ts.updateTypeAliasDeclaration(input, + /*decorators*/ undefined, ensureModifiers(input, isPrivate), input.name, ts.visitNodes(input.typeParameters, visitDeclarationSubtree, ts.isTypeParameterDeclaration), ts.visitNode(input.type, visitDeclarationSubtree, ts.isTypeNode))); + case 241 /* InterfaceDeclaration */: { + return cleanup(ts.updateInterfaceDeclaration(input, + /*decorators*/ undefined, ensureModifiers(input, isPrivate), input.name, ensureTypeParams(input, input.typeParameters), transformHeritageClauses(input.heritageClauses), ts.visitNodes(input.members, visitDeclarationSubtree))); + } + case 239 /* FunctionDeclaration */: { + // Generators lose their generator-ness, excepting their return type + var clean = cleanup(ts.updateFunctionDeclaration(input, + /*decorators*/ undefined, ensureModifiers(input, isPrivate), + /*asteriskToken*/ undefined, input.name, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type), + /*body*/ undefined)); + if (clean && resolver.isExpandoFunctionDeclaration(input)) { + var declarations = ts.mapDefined(resolver.getPropertiesOfContainerFunction(input), function (p) { + if (!ts.isPropertyAccessExpression(p.valueDeclaration)) { + return undefined; + } + var type = resolver.createTypeOfDeclaration(p.valueDeclaration, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker); + var varDecl = ts.createVariableDeclaration(ts.unescapeLeadingUnderscores(p.escapedName), type, /*initializer*/ undefined); + return ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([varDecl])); + }); + var namespaceDecl = ts.createModuleDeclaration(/*decorators*/ undefined, ensureModifiers(input, isPrivate), input.name, ts.createModuleBlock(declarations), 16 /* Namespace */); + return [clean, namespaceDecl]; + } + else { + return clean; + } + } + case 244 /* ModuleDeclaration */: { + needsDeclare = false; + var inner = input.body; + if (inner && inner.kind === 245 /* ModuleBlock */) { + var statements = ts.visitNodes(inner.statements, visitDeclarationStatements); + var body = ts.updateModuleBlock(inner, transformAndReplaceLatePaintedStatements(statements)); + needsDeclare = previousNeedsDeclare; + var mods = ensureModifiers(input, isPrivate); + return cleanup(ts.updateModuleDeclaration(input, + /*decorators*/ undefined, mods, ts.isExternalModuleAugmentation(input) ? rewriteModuleSpecifier(input, input.name) : input.name, body)); + } + else { + needsDeclare = previousNeedsDeclare; + var mods = ensureModifiers(input, isPrivate); + needsDeclare = false; + ts.visitNode(inner, visitDeclarationStatements); + // eagerly transform nested namespaces (the nesting doesn't need any elision or painting done) + var id = "" + ts.getOriginalNodeId(inner); // TODO: GH#18217 + var body = lateStatementReplacementMap.get(id); + lateStatementReplacementMap.delete(id); + return cleanup(ts.updateModuleDeclaration(input, + /*decorators*/ undefined, mods, input.name, body)); + } + } + case 240 /* ClassDeclaration */: { + var modifiers = ts.createNodeArray(ensureModifiers(input, isPrivate)); + var typeParameters = ensureTypeParams(input, input.typeParameters); + var ctor = ts.getFirstConstructorWithBody(input); + var parameterProperties = void 0; + if (ctor) { + var oldDiag_1 = getSymbolAccessibilityDiagnostic; + parameterProperties = ts.compact(ts.flatMap(ctor.parameters, function (param) { + if (!ts.hasModifier(param, 92 /* ParameterPropertyModifier */)) + return; + getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(param); + if (param.name.kind === 72 /* Identifier */) { + return preserveJsDoc(ts.createProperty( + /*decorators*/ undefined, ensureModifiers(param), param.name, param.questionToken, ensureType(param, param.type), ensureNoInitializer(param)), param); + } + else { + // Pattern - this is currently an error, but we emit declarations for it somewhat correctly + return walkBindingPattern(param.name); + } + function walkBindingPattern(pattern) { + var elems; + for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) { + var elem = _a[_i]; + if (ts.isOmittedExpression(elem)) + continue; + if (ts.isBindingPattern(elem.name)) { + elems = ts.concatenate(elems, walkBindingPattern(elem.name)); + } + elems = elems || []; + elems.push(ts.createProperty( + /*decorators*/ undefined, ensureModifiers(param), elem.name, + /*questionToken*/ undefined, ensureType(elem, /*type*/ undefined), + /*initializer*/ undefined)); + } + return elems; + } + })); + getSymbolAccessibilityDiagnostic = oldDiag_1; + } + var members = ts.createNodeArray(ts.concatenate(parameterProperties, ts.visitNodes(input.members, visitDeclarationSubtree))); + var extendsClause_1 = ts.getEffectiveBaseTypeNode(input); + if (extendsClause_1 && !ts.isEntityNameExpression(extendsClause_1.expression) && extendsClause_1.expression.kind !== 96 /* NullKeyword */) { + // We must add a temporary declaration for the extends clause expression + var newId_1 = ts.createOptimisticUniqueName(ts.unescapeLeadingUnderscores(input.name.escapedText) + "_base"); // TODO: GH#18217 + getSymbolAccessibilityDiagnostic = function () { return ({ + diagnosticMessage: ts.Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1, + errorNode: extendsClause_1, + typeName: input.name + }); }; + var varDecl = ts.createVariableDeclaration(newId_1, resolver.createTypeOfExpression(extendsClause_1.expression, input, declarationEmitNodeBuilderFlags, symbolTracker), /*initializer*/ undefined); + var statement = ts.createVariableStatement(needsDeclare ? [ts.createModifier(125 /* DeclareKeyword */)] : [], ts.createVariableDeclarationList([varDecl], 2 /* Const */)); + var heritageClauses = ts.createNodeArray(ts.map(input.heritageClauses, function (clause) { + if (clause.token === 86 /* ExtendsKeyword */) { + var oldDiag_2 = getSymbolAccessibilityDiagnostic; + getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(clause.types[0]); + var newClause = ts.updateHeritageClause(clause, ts.map(clause.types, function (t) { return ts.updateExpressionWithTypeArguments(t, ts.visitNodes(t.typeArguments, visitDeclarationSubtree), newId_1); })); + getSymbolAccessibilityDiagnostic = oldDiag_2; + return newClause; + } + return ts.updateHeritageClause(clause, ts.visitNodes(ts.createNodeArray(ts.filter(clause.types, function (t) { return ts.isEntityNameExpression(t.expression) || t.expression.kind === 96 /* NullKeyword */; })), visitDeclarationSubtree)); + })); + return [statement, cleanup(ts.updateClassDeclaration(input, + /*decorators*/ undefined, modifiers, input.name, typeParameters, heritageClauses, members))]; // TODO: GH#18217 + } + else { + var heritageClauses = transformHeritageClauses(input.heritageClauses); + return cleanup(ts.updateClassDeclaration(input, + /*decorators*/ undefined, modifiers, input.name, typeParameters, heritageClauses, members)); + } + } + case 219 /* VariableStatement */: { + return cleanup(transformVariableStatement(input, isPrivate)); + } + case 243 /* EnumDeclaration */: { + return cleanup(ts.updateEnumDeclaration(input, /*decorators*/ undefined, ts.createNodeArray(ensureModifiers(input, isPrivate)), input.name, ts.createNodeArray(ts.mapDefined(input.members, function (m) { + if (shouldStripInternal(m)) + return; + // Rewrite enum values to their constants, if available + var constValue = resolver.getConstantValue(m); + return preserveJsDoc(ts.updateEnumMember(m, m.name, constValue !== undefined ? ts.createLiteral(constValue) : undefined), m); + })))); + } + } + // Anything left unhandled is an error, so this should be unreachable + return ts.Debug.assertNever(input, "Unhandled top-level node in declaration emit: " + ts.SyntaxKind[input.kind]); + function cleanup(node) { + if (isEnclosingDeclaration(input)) { + enclosingDeclaration = previousEnclosingDeclaration; + } + if (canProdiceDiagnostic) { + getSymbolAccessibilityDiagnostic = oldDiag; + } + if (input.kind === 244 /* ModuleDeclaration */) { + needsDeclare = previousNeedsDeclare; + } + if (node === input) { + return node; + } + return node && ts.setOriginalNode(preserveJsDoc(node, input), input); + } + } + function transformVariableStatement(input, privateDeclaration) { + if (!ts.forEach(input.declarationList.declarations, getBindingNameVisible)) + return; + var nodes = ts.visitNodes(input.declarationList.declarations, visitDeclarationSubtree); + if (!ts.length(nodes)) + return; + return ts.updateVariableStatement(input, ts.createNodeArray(ensureModifiers(input, privateDeclaration)), ts.updateVariableDeclarationList(input.declarationList, nodes)); + } + function recreateBindingPattern(d) { + return ts.flatten(ts.mapDefined(d.elements, function (e) { return recreateBindingElement(e); })); + } + function recreateBindingElement(e) { + if (e.kind === 210 /* OmittedExpression */) { + return; + } + if (e.name) { + if (!getBindingNameVisible(e)) + return; + if (ts.isBindingPattern(e.name)) { + return recreateBindingPattern(e.name); + } + else { + return ts.createVariableDeclaration(e.name, ensureType(e, /*type*/ undefined), /*initializer*/ undefined); + } + } + } + function checkName(node) { + var oldDiag; + if (!suppressNewDiagnosticContexts) { + oldDiag = getSymbolAccessibilityDiagnostic; + getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNodeName(node); + } + errorNameNode = node.name; + ts.Debug.assert(resolver.isLateBound(ts.getParseTreeNode(node))); // Should only be called with dynamic names + var decl = node; + var entityName = decl.name.expression; + checkEntityNameVisibility(entityName, enclosingDeclaration); + if (!suppressNewDiagnosticContexts) { + getSymbolAccessibilityDiagnostic = oldDiag; + } + errorNameNode = undefined; + } + function hasInternalAnnotation(range) { + var comment = currentSourceFile.text.substring(range.pos, range.end); + return ts.stringContains(comment, "@internal"); + } + function shouldStripInternal(node) { + if (stripInternal && node) { + var leadingCommentRanges = ts.getLeadingCommentRangesOfNode(ts.getParseTreeNode(node), currentSourceFile); + if (ts.forEach(leadingCommentRanges, hasInternalAnnotation)) { + return true; + } + } + return false; + } + function isScopeMarker(node) { + return ts.isExportAssignment(node) || ts.isExportDeclaration(node); + } + function hasScopeMarker(node) { + if (ts.isModuleBlock(node)) { + return ts.some(node.statements, isScopeMarker); + } + return false; + } + function ensureModifiers(node, privateDeclaration) { + var currentFlags = ts.getModifierFlags(node); + var newFlags = ensureModifierFlags(node, privateDeclaration); + if (currentFlags === newFlags) { + return node.modifiers; + } + return ts.createModifiersFromModifierFlags(newFlags); + } + function ensureModifierFlags(node, privateDeclaration) { + var mask = 3071 /* All */ ^ (4 /* Public */ | 256 /* Async */); // No async modifiers in declaration files + var additions = (needsDeclare && !isAlwaysType(node)) ? 2 /* Ambient */ : 0 /* None */; + var parentIsFile = node.parent.kind === 279 /* SourceFile */; + if (!parentIsFile || (isBundledEmit && parentIsFile && ts.isExternalModule(node.parent))) { + mask ^= ((privateDeclaration || (isBundledEmit && parentIsFile) || hasScopeMarker(node.parent) ? 0 : 1 /* Export */) | 2 /* Ambient */); + additions = 0 /* None */; + } + return maskModifierFlags(node, mask, additions); + } + function ensureAccessor(node) { + var accessors = resolver.getAllAccessorDeclarations(node); + if (node.kind !== accessors.firstAccessor.kind) { + return; + } + var accessorType = getTypeAnnotationFromAccessor(node); + if (!accessorType && accessors.secondAccessor) { + accessorType = getTypeAnnotationFromAccessor(accessors.secondAccessor); + // If we end up pulling the type from the second accessor, we also need to change the diagnostic context to get the expected error message + getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(accessors.secondAccessor); + } + var prop = ts.createProperty(/*decorators*/ undefined, maskModifiers(node, /*mask*/ undefined, (!accessors.setAccessor) ? 64 /* Readonly */ : 0 /* None */), node.name, node.questionToken, ensureType(node, accessorType), /*initializer*/ undefined); + var leadingsSyntheticCommentRanges = accessors.secondAccessor && ts.getLeadingCommentRangesOfNode(accessors.secondAccessor, currentSourceFile); + if (leadingsSyntheticCommentRanges) { + var _loop_9 = function (range) { + if (range.kind === 3 /* MultiLineCommentTrivia */) { + var text = currentSourceFile.text.slice(range.pos + 2, range.end - 2); + var lines = text.split(/\r\n?|\n/g); + if (lines.length > 1) { + var lastLines = lines.slice(1); + var indentation_1 = ts.guessIndentation(lastLines); + text = [lines[0]].concat(ts.map(lastLines, function (l) { return l.slice(indentation_1); })).join(newLine); + } + ts.addSyntheticLeadingComment(prop, range.kind, text, range.hasTrailingNewLine); + } + }; + for (var _i = 0, leadingsSyntheticCommentRanges_1 = leadingsSyntheticCommentRanges; _i < leadingsSyntheticCommentRanges_1.length; _i++) { + var range = leadingsSyntheticCommentRanges_1[_i]; + _loop_9(range); + } + } + return prop; + } + function transformHeritageClauses(nodes) { + return ts.createNodeArray(ts.filter(ts.map(nodes, function (clause) { return ts.updateHeritageClause(clause, ts.visitNodes(ts.createNodeArray(ts.filter(clause.types, function (t) { + return ts.isEntityNameExpression(t.expression) || (clause.token === 86 /* ExtendsKeyword */ && t.expression.kind === 96 /* NullKeyword */); + })), visitDeclarationSubtree)); }), function (clause) { return clause.types && !!clause.types.length; })); + } + } + ts.transformDeclarations = transformDeclarations; + function isAlwaysType(node) { + if (node.kind === 241 /* InterfaceDeclaration */) { + return true; + } + return false; + } + // Elide "public" modifier, as it is the default + function maskModifiers(node, modifierMask, modifierAdditions) { + return ts.createModifiersFromModifierFlags(maskModifierFlags(node, modifierMask, modifierAdditions)); + } + function maskModifierFlags(node, modifierMask, modifierAdditions) { + if (modifierMask === void 0) { modifierMask = 3071 /* All */ ^ 4 /* Public */; } + if (modifierAdditions === void 0) { modifierAdditions = 0 /* None */; } + var flags = (ts.getModifierFlags(node) & modifierMask) | modifierAdditions; + if (flags & 512 /* Default */ && !(flags & 1 /* Export */)) { + // A non-exported default is a nonsequitor - we usually try to remove all export modifiers + // from statements in ambient declarations; but a default export must retain its export modifier to be syntactically valid + flags ^= 1 /* Export */; + } + if (flags & 512 /* Default */ && flags & 2 /* Ambient */) { + flags ^= 2 /* Ambient */; // `declare` is never required alongside `default` (and would be an error if printed) + } + return flags; + } + function getTypeAnnotationFromAccessor(accessor) { + if (accessor) { + return accessor.kind === 158 /* GetAccessor */ + ? accessor.type // Getter - return type + : accessor.parameters.length > 0 + ? accessor.parameters[0].type // Setter parameter type + : undefined; + } + } + function canHaveLiteralInitializer(node) { + switch (node.kind) { + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + return !ts.hasModifier(node, 8 /* Private */); + case 151 /* Parameter */: + case 237 /* VariableDeclaration */: + return true; + } + return false; + } + function isPreservedDeclarationStatement(node) { + switch (node.kind) { + case 239 /* FunctionDeclaration */: + case 244 /* ModuleDeclaration */: + case 248 /* ImportEqualsDeclaration */: + case 241 /* InterfaceDeclaration */: + case 240 /* ClassDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 243 /* EnumDeclaration */: + case 219 /* VariableStatement */: + case 249 /* ImportDeclaration */: + case 255 /* ExportDeclaration */: + case 254 /* ExportAssignment */: + return true; + } + return false; + } + function isProcessedComponent(node) { + switch (node.kind) { + case 161 /* ConstructSignature */: + case 157 /* Constructor */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 155 /* MethodSignature */: + case 160 /* CallSignature */: + case 162 /* IndexSignature */: + case 237 /* VariableDeclaration */: + case 150 /* TypeParameter */: + case 211 /* ExpressionWithTypeArguments */: + case 164 /* TypeReference */: + case 175 /* ConditionalType */: + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + case 183 /* ImportType */: + return true; + } + return false; + } +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + function getModuleTransformer(moduleKind) { + switch (moduleKind) { + case ts.ModuleKind.ESNext: + case ts.ModuleKind.ES2015: + return ts.transformES2015Module; + case ts.ModuleKind.System: + return ts.transformSystemModule; + default: + return ts.transformModule; + } + } + var TransformationState; + (function (TransformationState) { + TransformationState[TransformationState["Uninitialized"] = 0] = "Uninitialized"; + TransformationState[TransformationState["Initialized"] = 1] = "Initialized"; + TransformationState[TransformationState["Completed"] = 2] = "Completed"; + TransformationState[TransformationState["Disposed"] = 3] = "Disposed"; + })(TransformationState || (TransformationState = {})); + var SyntaxKindFeatureFlags; + (function (SyntaxKindFeatureFlags) { + SyntaxKindFeatureFlags[SyntaxKindFeatureFlags["Substitution"] = 1] = "Substitution"; + SyntaxKindFeatureFlags[SyntaxKindFeatureFlags["EmitNotifications"] = 2] = "EmitNotifications"; + })(SyntaxKindFeatureFlags || (SyntaxKindFeatureFlags = {})); + function getTransformers(compilerOptions, customTransformers) { + var jsx = compilerOptions.jsx; + var languageVersion = ts.getEmitScriptTarget(compilerOptions); + var moduleKind = ts.getEmitModuleKind(compilerOptions); + var transformers = []; + ts.addRange(transformers, customTransformers && customTransformers.before); + transformers.push(ts.transformTypeScript); + if (jsx === 2 /* React */) { + transformers.push(ts.transformJsx); + } + if (languageVersion < 6 /* ESNext */) { + transformers.push(ts.transformESNext); + } + if (languageVersion < 4 /* ES2017 */) { + transformers.push(ts.transformES2017); + } + if (languageVersion < 3 /* ES2016 */) { + transformers.push(ts.transformES2016); + } + if (languageVersion < 2 /* ES2015 */) { + transformers.push(ts.transformES2015); + transformers.push(ts.transformGenerators); + } + transformers.push(getModuleTransformer(moduleKind)); + // The ES5 transformer is last so that it can substitute expressions like `exports.default` + // for ES3. + if (languageVersion < 1 /* ES5 */) { + transformers.push(ts.transformES5); + } + ts.addRange(transformers, customTransformers && customTransformers.after); + return transformers; + } + ts.getTransformers = getTransformers; + function noEmitSubstitution(_hint, node) { + return node; + } + ts.noEmitSubstitution = noEmitSubstitution; + function noEmitNotification(hint, node, callback) { + callback(hint, node); + } + ts.noEmitNotification = noEmitNotification; + /** + * Transforms an array of SourceFiles by passing them through each transformer. + * + * @param resolver The emit resolver provided by the checker. + * @param host The emit host object used to interact with the file system. + * @param options Compiler options to surface in the `TransformationContext`. + * @param nodes An array of nodes to transform. + * @param transforms An array of `TransformerFactory` callbacks. + * @param allowDtsFiles A value indicating whether to allow the transformation of .d.ts files. + */ + function transformNodes(resolver, host, options, nodes, transformers, allowDtsFiles) { + var enabledSyntaxKindFeatures = new Array(312 /* Count */); + var lexicalEnvironmentVariableDeclarations; + var lexicalEnvironmentFunctionDeclarations; + var lexicalEnvironmentVariableDeclarationsStack = []; + var lexicalEnvironmentFunctionDeclarationsStack = []; + var lexicalEnvironmentStackOffset = 0; + var lexicalEnvironmentSuspended = false; + var emitHelpers; + var onSubstituteNode = noEmitSubstitution; + var onEmitNode = noEmitNotification; + var state = 0 /* Uninitialized */; + var diagnostics = []; + // The transformation context is provided to each transformer as part of transformer + // initialization. + var context = { + getCompilerOptions: function () { return options; }, + getEmitResolver: function () { return resolver; }, + getEmitHost: function () { return host; }, + startLexicalEnvironment: startLexicalEnvironment, + suspendLexicalEnvironment: suspendLexicalEnvironment, + resumeLexicalEnvironment: resumeLexicalEnvironment, + endLexicalEnvironment: endLexicalEnvironment, + hoistVariableDeclaration: hoistVariableDeclaration, + hoistFunctionDeclaration: hoistFunctionDeclaration, + requestEmitHelper: requestEmitHelper, + readEmitHelpers: readEmitHelpers, + enableSubstitution: enableSubstitution, + enableEmitNotification: enableEmitNotification, + isSubstitutionEnabled: isSubstitutionEnabled, + isEmitNotificationEnabled: isEmitNotificationEnabled, + get onSubstituteNode() { return onSubstituteNode; }, + set onSubstituteNode(value) { + ts.Debug.assert(state < 1 /* Initialized */, "Cannot modify transformation hooks after initialization has completed."); + ts.Debug.assert(value !== undefined, "Value must not be 'undefined'"); + onSubstituteNode = value; + }, + get onEmitNode() { return onEmitNode; }, + set onEmitNode(value) { + ts.Debug.assert(state < 1 /* Initialized */, "Cannot modify transformation hooks after initialization has completed."); + ts.Debug.assert(value !== undefined, "Value must not be 'undefined'"); + onEmitNode = value; + }, + addDiagnostic: function (diag) { + diagnostics.push(diag); + } + }; + // Ensure the parse tree is clean before applying transformations + for (var _i = 0, nodes_4 = nodes; _i < nodes_4.length; _i++) { + var node = nodes_4[_i]; + ts.disposeEmitNodes(ts.getSourceFileOfNode(ts.getParseTreeNode(node))); + } + ts.performance.mark("beforeTransform"); + // Chain together and initialize each transformer. + var transformation = ts.chain.apply(void 0, transformers)(context); + // prevent modification of transformation hooks. + state = 1 /* Initialized */; + // Transform each node. + var transformed = ts.map(nodes, allowDtsFiles ? transformation : transformRoot); + // prevent modification of the lexical environment. + state = 2 /* Completed */; + ts.performance.mark("afterTransform"); + ts.performance.measure("transformTime", "beforeTransform", "afterTransform"); + return { + transformed: transformed, + substituteNode: substituteNode, + emitNodeWithNotification: emitNodeWithNotification, + dispose: dispose, + diagnostics: diagnostics + }; + function transformRoot(node) { + return node && (!ts.isSourceFile(node) || !node.isDeclarationFile) ? transformation(node) : node; + } + /** + * Enables expression substitutions in the pretty printer for the provided SyntaxKind. + */ + function enableSubstitution(kind) { + ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the transformation context after transformation has completed."); + enabledSyntaxKindFeatures[kind] |= 1 /* Substitution */; + } + /** + * Determines whether expression substitutions are enabled for the provided node. + */ + function isSubstitutionEnabled(node) { + return (enabledSyntaxKindFeatures[node.kind] & 1 /* Substitution */) !== 0 + && (ts.getEmitFlags(node) & 4 /* NoSubstitution */) === 0; + } + /** + * Emits a node with possible substitution. + * + * @param hint A hint as to the intended usage of the node. + * @param node The node to emit. + * @param emitCallback The callback used to emit the node or its substitute. + */ + function substituteNode(hint, node) { + ts.Debug.assert(state < 3 /* Disposed */, "Cannot substitute a node after the result is disposed."); + return node && isSubstitutionEnabled(node) && onSubstituteNode(hint, node) || node; + } + /** + * Enables before/after emit notifications in the pretty printer for the provided SyntaxKind. + */ + function enableEmitNotification(kind) { + ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the transformation context after transformation has completed."); + enabledSyntaxKindFeatures[kind] |= 2 /* EmitNotifications */; + } + /** + * Determines whether before/after emit notifications should be raised in the pretty + * printer when it emits a node. + */ + function isEmitNotificationEnabled(node) { + return (enabledSyntaxKindFeatures[node.kind] & 2 /* EmitNotifications */) !== 0 + || (ts.getEmitFlags(node) & 2 /* AdviseOnEmitNode */) !== 0; + } + /** + * Emits a node with possible emit notification. + * + * @param hint A hint as to the intended usage of the node. + * @param node The node to emit. + * @param emitCallback The callback used to emit the node. + */ + function emitNodeWithNotification(hint, node, emitCallback) { + ts.Debug.assert(state < 3 /* Disposed */, "Cannot invoke TransformationResult callbacks after the result is disposed."); + if (node) { + if (isEmitNotificationEnabled(node)) { + onEmitNode(hint, node, emitCallback); + } + else { + emitCallback(hint, node); + } + } + } + /** + * Records a hoisted variable declaration for the provided name within a lexical environment. + */ + function hoistVariableDeclaration(name) { + ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization."); + ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed."); + var decl = ts.setEmitFlags(ts.createVariableDeclaration(name), 64 /* NoNestedSourceMaps */); + if (!lexicalEnvironmentVariableDeclarations) { + lexicalEnvironmentVariableDeclarations = [decl]; + } + else { + lexicalEnvironmentVariableDeclarations.push(decl); + } + } + /** + * Records a hoisted function declaration within a lexical environment. + */ + function hoistFunctionDeclaration(func) { + ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization."); + ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed."); + if (!lexicalEnvironmentFunctionDeclarations) { + lexicalEnvironmentFunctionDeclarations = [func]; + } + else { + lexicalEnvironmentFunctionDeclarations.push(func); + } + } + /** + * Starts a new lexical environment. Any existing hoisted variable or function declarations + * are pushed onto a stack, and the related storage variables are reset. + */ + function startLexicalEnvironment() { + ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization."); + ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed."); + ts.Debug.assert(!lexicalEnvironmentSuspended, "Lexical environment is suspended."); + // Save the current lexical environment. Rather than resizing the array we adjust the + // stack size variable. This allows us to reuse existing array slots we've + // already allocated between transformations to avoid allocation and GC overhead during + // transformation. + lexicalEnvironmentVariableDeclarationsStack[lexicalEnvironmentStackOffset] = lexicalEnvironmentVariableDeclarations; + lexicalEnvironmentFunctionDeclarationsStack[lexicalEnvironmentStackOffset] = lexicalEnvironmentFunctionDeclarations; + lexicalEnvironmentStackOffset++; + lexicalEnvironmentVariableDeclarations = undefined; + lexicalEnvironmentFunctionDeclarations = undefined; + } + /** Suspends the current lexical environment, usually after visiting a parameter list. */ + function suspendLexicalEnvironment() { + ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization."); + ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed."); + ts.Debug.assert(!lexicalEnvironmentSuspended, "Lexical environment is already suspended."); + lexicalEnvironmentSuspended = true; + } + /** Resumes a suspended lexical environment, usually before visiting a function body. */ + function resumeLexicalEnvironment() { + ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization."); + ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed."); + ts.Debug.assert(lexicalEnvironmentSuspended, "Lexical environment is not suspended."); + lexicalEnvironmentSuspended = false; + } + /** + * Ends a lexical environment. The previous set of hoisted declarations are restored and + * any hoisted declarations added in this environment are returned. + */ + function endLexicalEnvironment() { + ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization."); + ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed."); + ts.Debug.assert(!lexicalEnvironmentSuspended, "Lexical environment is suspended."); + var statements; + if (lexicalEnvironmentVariableDeclarations || lexicalEnvironmentFunctionDeclarations) { + if (lexicalEnvironmentFunctionDeclarations) { + statements = lexicalEnvironmentFunctionDeclarations.slice(); + } + if (lexicalEnvironmentVariableDeclarations) { + var statement = ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList(lexicalEnvironmentVariableDeclarations)); + if (!statements) { + statements = [statement]; + } + else { + statements.push(statement); + } + } + } + // Restore the previous lexical environment. + lexicalEnvironmentStackOffset--; + lexicalEnvironmentVariableDeclarations = lexicalEnvironmentVariableDeclarationsStack[lexicalEnvironmentStackOffset]; + lexicalEnvironmentFunctionDeclarations = lexicalEnvironmentFunctionDeclarationsStack[lexicalEnvironmentStackOffset]; + if (lexicalEnvironmentStackOffset === 0) { + lexicalEnvironmentVariableDeclarationsStack = []; + lexicalEnvironmentFunctionDeclarationsStack = []; + } + return statements; + } + function requestEmitHelper(helper) { + ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the transformation context during initialization."); + ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the transformation context after transformation has completed."); + ts.Debug.assert(!helper.scoped, "Cannot request a scoped emit helper."); + emitHelpers = ts.append(emitHelpers, helper); + } + function readEmitHelpers() { + ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the transformation context during initialization."); + ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the transformation context after transformation has completed."); + var helpers = emitHelpers; + emitHelpers = undefined; + return helpers; + } + function dispose() { + if (state < 3 /* Disposed */) { + // Clean up emit nodes on parse tree + for (var _i = 0, nodes_5 = nodes; _i < nodes_5.length; _i++) { + var node = nodes_5[_i]; + ts.disposeEmitNodes(ts.getSourceFileOfNode(ts.getParseTreeNode(node))); + } + // Release references to external entries for GC purposes. + lexicalEnvironmentVariableDeclarations = undefined; + lexicalEnvironmentVariableDeclarationsStack = undefined; + lexicalEnvironmentFunctionDeclarations = undefined; + lexicalEnvironmentFunctionDeclarationsStack = undefined; + onSubstituteNode = undefined; + onEmitNode = undefined; + emitHelpers = undefined; + // Prevent further use of the transformation result. + state = 3 /* Disposed */; + } + } + } + ts.transformNodes = transformNodes; +})(ts || (ts = {})); +var ts; +(function (ts) { + var infoExtension = ".tsbundleinfo"; + var brackets = createBracketsMap(); + var syntheticParent = { pos: -1, end: -1 }; + /*@internal*/ + /** + * Iterates over the source files that are expected to have an emit output. + * + * @param host An EmitHost. + * @param action The action to execute. + * @param sourceFilesOrTargetSourceFile + * If an array, the full list of source files to emit. + * Else, calls `getSourceFilesToEmit` with the (optional) target source file to determine the list of source files to emit. + */ + function forEachEmittedFile(host, action, sourceFilesOrTargetSourceFile, emitOnlyDtsFiles) { + if (emitOnlyDtsFiles === void 0) { emitOnlyDtsFiles = false; } + var sourceFiles = ts.isArray(sourceFilesOrTargetSourceFile) ? sourceFilesOrTargetSourceFile : ts.getSourceFilesToEmit(host, sourceFilesOrTargetSourceFile); + var options = host.getCompilerOptions(); + if (options.outFile || options.out) { + if (sourceFiles.length) { + var bundle = ts.createBundle(sourceFiles, host.getPrependNodes()); + var result = action(getOutputPathsFor(bundle, host, emitOnlyDtsFiles), bundle); + if (result) { + return result; + } + } + } + else { + for (var _a = 0, sourceFiles_1 = sourceFiles; _a < sourceFiles_1.length; _a++) { + var sourceFile = sourceFiles_1[_a]; + var result = action(getOutputPathsFor(sourceFile, host, emitOnlyDtsFiles), sourceFile); + if (result) { + return result; + } + } + } + } + ts.forEachEmittedFile = forEachEmittedFile; + /*@internal*/ + function getOutputPathsFor(sourceFile, host, forceDtsPaths) { + var options = host.getCompilerOptions(); + if (sourceFile.kind === 280 /* Bundle */) { + var outPath = options.outFile || options.out; + var jsFilePath = options.emitDeclarationOnly ? undefined : outPath; + var sourceMapFilePath = jsFilePath && getSourceMapFilePath(jsFilePath, options); + var declarationFilePath = (forceDtsPaths || ts.getEmitDeclarations(options)) ? ts.removeFileExtension(outPath) + ".d.ts" /* Dts */ : undefined; + var declarationMapPath = declarationFilePath && ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; + var bundleInfoPath = options.references && jsFilePath ? (ts.removeFileExtension(jsFilePath) + infoExtension) : undefined; + return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, bundleInfoPath: bundleInfoPath }; + } + else { + var ownOutputFilePath = ts.getOwnEmitOutputFilePath(sourceFile.fileName, host, getOutputExtension(sourceFile, options)); + // If json file emits to the same location skip writing it, if emitDeclarationOnly skip writing it + var isJsonEmittedToSameLocation = ts.isJsonSourceFile(sourceFile) && + ts.comparePaths(sourceFile.fileName, ownOutputFilePath, host.getCurrentDirectory(), !host.useCaseSensitiveFileNames()) === 0 /* EqualTo */; + var jsFilePath = options.emitDeclarationOnly || isJsonEmittedToSameLocation ? undefined : ownOutputFilePath; + var sourceMapFilePath = !jsFilePath || ts.isJsonSourceFile(sourceFile) ? undefined : getSourceMapFilePath(jsFilePath, options); + // For legacy reasons (ie, we have baselines capturing the behavior), js files don't report a .d.ts output path - this would only matter if `declaration` and `allowJs` were both on, which is currently an error + var isJs = ts.isSourceFileJS(sourceFile); + var declarationFilePath = ((forceDtsPaths || ts.getEmitDeclarations(options)) && !isJs) ? ts.getDeclarationEmitOutputFilePath(sourceFile.fileName, host) : undefined; + var declarationMapPath = declarationFilePath && ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; + return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, bundleInfoPath: undefined }; + } + } + ts.getOutputPathsFor = getOutputPathsFor; + function getSourceMapFilePath(jsFilePath, options) { + return (options.sourceMap && !options.inlineSourceMap) ? jsFilePath + ".map" : undefined; + } + function createDefaultBundleInfo() { + return { + originalOffset: -1, + totalLength: -1 + }; + } + // JavaScript files are always LanguageVariant.JSX, as JSX syntax is allowed in .js files also. + // So for JavaScript files, '.jsx' is only emitted if the input was '.jsx', and JsxEmit.Preserve. + // For TypeScript, the only time to emit with a '.jsx' extension, is on JSX input, and JsxEmit.Preserve + /* @internal */ + function getOutputExtension(sourceFile, options) { + if (ts.isJsonSourceFile(sourceFile)) { + return ".json" /* Json */; + } + if (options.jsx === 1 /* Preserve */) { + if (ts.isSourceFileJS(sourceFile)) { + if (ts.fileExtensionIs(sourceFile.fileName, ".jsx" /* Jsx */)) { + return ".jsx" /* Jsx */; + } + } + else if (sourceFile.languageVariant === 1 /* JSX */) { + // TypeScript source file preserving JSX syntax + return ".jsx" /* Jsx */; + } + } + return ".js" /* Js */; + } + ts.getOutputExtension = getOutputExtension; + /*@internal*/ + // targetSourceFile is when users only want one file in entire project to be emitted. This is used in compileOnSave feature + function emitFiles(resolver, host, targetSourceFile, emitOnlyDtsFiles, transformers, declarationTransformers) { + var compilerOptions = host.getCompilerOptions(); + var sourceMapDataList = (compilerOptions.sourceMap || compilerOptions.inlineSourceMap || ts.getAreDeclarationMapsEnabled(compilerOptions)) ? [] : undefined; + var emittedFilesList = compilerOptions.listEmittedFiles ? [] : undefined; + var emitterDiagnostics = ts.createDiagnosticCollection(); + var newLine = ts.getNewLineCharacter(compilerOptions, function () { return host.getNewLine(); }); + var writer = ts.createTextWriter(newLine); + var _a = ts.performance.createTimer("printTime", "beforePrint", "afterPrint"), enter = _a.enter, exit = _a.exit; + var bundleInfo = createDefaultBundleInfo(); + var emitSkipped = false; + var exportedModulesFromDeclarationEmit; + // Emit each output file + enter(); + forEachEmittedFile(host, emitSourceFileOrBundle, ts.getSourceFilesToEmit(host, targetSourceFile), emitOnlyDtsFiles); + exit(); + return { + emitSkipped: emitSkipped, + diagnostics: emitterDiagnostics.getDiagnostics(), + emittedFiles: emittedFilesList, + sourceMaps: sourceMapDataList, + exportedModulesFromDeclarationEmit: exportedModulesFromDeclarationEmit + }; + function emitSourceFileOrBundle(_a, sourceFileOrBundle) { + var jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, bundleInfoPath = _a.bundleInfoPath; + emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, bundleInfoPath); + emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath); + if (!emitSkipped && emittedFilesList) { + if (!emitOnlyDtsFiles) { + if (jsFilePath) { + emittedFilesList.push(jsFilePath); + } + if (sourceMapFilePath) { + emittedFilesList.push(sourceMapFilePath); + } + if (bundleInfoPath) { + emittedFilesList.push(bundleInfoPath); + } + } + if (declarationFilePath) { + emittedFilesList.push(declarationFilePath); + } + if (declarationMapPath) { + emittedFilesList.push(declarationMapPath); + } + } + } + function emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, bundleInfoPath) { + if (emitOnlyDtsFiles || !jsFilePath) { + return; + } + // Make sure not to write js file and source map file if any of them cannot be written + if ((jsFilePath && host.isEmitBlocked(jsFilePath)) || compilerOptions.noEmit) { + emitSkipped = true; + return; + } + // Transform the source files + var transform = ts.transformNodes(resolver, host, compilerOptions, [sourceFileOrBundle], transformers, /*allowDtsFiles*/ false); + var printerOptions = { + removeComments: compilerOptions.removeComments, + newLine: compilerOptions.newLine, + noEmitHelpers: compilerOptions.noEmitHelpers, + module: compilerOptions.module, + target: compilerOptions.target, + sourceMap: compilerOptions.sourceMap, + inlineSourceMap: compilerOptions.inlineSourceMap, + inlineSources: compilerOptions.inlineSources, + extendedDiagnostics: compilerOptions.extendedDiagnostics, + }; + // Create a printer to print the nodes + var printer = createPrinter(printerOptions, { + // resolver hooks + hasGlobalName: resolver.hasGlobalName, + // transform hooks + onEmitNode: transform.emitNodeWithNotification, + substituteNode: transform.substituteNode, + }); + ts.Debug.assert(transform.transformed.length === 1, "Should only see one output from the transform"); + printSourceFileOrBundle(jsFilePath, sourceMapFilePath, transform.transformed[0], bundleInfoPath, printer, compilerOptions); + // Clean up emit nodes on parse tree + transform.dispose(); + } + function emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath) { + if (!(declarationFilePath && !ts.isInJSFile(sourceFileOrBundle))) { + return; + } + var sourceFiles = ts.isSourceFile(sourceFileOrBundle) ? [sourceFileOrBundle] : sourceFileOrBundle.sourceFiles; + // Setup and perform the transformation to retrieve declarations from the input files + var nonJsFiles = ts.filter(sourceFiles, ts.isSourceFileNotJS); + var inputListOrBundle = (compilerOptions.outFile || compilerOptions.out) ? [ts.createBundle(nonJsFiles, !ts.isSourceFile(sourceFileOrBundle) ? sourceFileOrBundle.prepends : undefined)] : nonJsFiles; + if (emitOnlyDtsFiles && !ts.getEmitDeclarations(compilerOptions)) { + // Checker wont collect the linked aliases since thats only done when declaration is enabled. + // Do that here when emitting only dts files + nonJsFiles.forEach(collectLinkedAliases); + } + var declarationTransform = ts.transformNodes(resolver, host, compilerOptions, inputListOrBundle, ts.concatenate([ts.transformDeclarations], declarationTransformers), /*allowDtsFiles*/ false); + if (ts.length(declarationTransform.diagnostics)) { + for (var _a = 0, _b = declarationTransform.diagnostics; _a < _b.length; _a++) { + var diagnostic = _b[_a]; + emitterDiagnostics.add(diagnostic); + } + } + var printerOptions = { + removeComments: compilerOptions.removeComments, + newLine: compilerOptions.newLine, + noEmitHelpers: true, + module: compilerOptions.module, + target: compilerOptions.target, + sourceMap: compilerOptions.sourceMap, + inlineSourceMap: compilerOptions.inlineSourceMap, + extendedDiagnostics: compilerOptions.extendedDiagnostics, + onlyPrintJsDocStyle: true, + }; + var declarationPrinter = createPrinter(printerOptions, { + // resolver hooks + hasGlobalName: resolver.hasGlobalName, + // transform hooks + onEmitNode: declarationTransform.emitNodeWithNotification, + substituteNode: declarationTransform.substituteNode, + }); + var declBlocked = (!!declarationTransform.diagnostics && !!declarationTransform.diagnostics.length) || !!host.isEmitBlocked(declarationFilePath) || !!compilerOptions.noEmit; + emitSkipped = emitSkipped || declBlocked; + if (!declBlocked || emitOnlyDtsFiles) { + ts.Debug.assert(declarationTransform.transformed.length === 1, "Should only see one output from the decl transform"); + printSourceFileOrBundle(declarationFilePath, declarationMapPath, declarationTransform.transformed[0], /* bundleInfopath*/ undefined, declarationPrinter, { + sourceMap: compilerOptions.declarationMap, + sourceRoot: compilerOptions.sourceRoot, + mapRoot: compilerOptions.mapRoot, + extendedDiagnostics: compilerOptions.extendedDiagnostics, + }); + if (emitOnlyDtsFiles && declarationTransform.transformed[0].kind === 279 /* SourceFile */) { + var sourceFile = declarationTransform.transformed[0]; + exportedModulesFromDeclarationEmit = sourceFile.exportedModulesFromDeclarationEmit; + } + } + declarationTransform.dispose(); + } + function collectLinkedAliases(node) { + if (ts.isExportAssignment(node)) { + if (node.expression.kind === 72 /* Identifier */) { + resolver.collectLinkedAliases(node.expression, /*setVisibility*/ true); + } + return; + } + else if (ts.isExportSpecifier(node)) { + resolver.collectLinkedAliases(node.propertyName || node.name, /*setVisibility*/ true); + return; + } + ts.forEachChild(node, collectLinkedAliases); + } + function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle, bundleInfoPath, printer, mapOptions) { + var bundle = sourceFileOrBundle.kind === 280 /* Bundle */ ? sourceFileOrBundle : undefined; + var sourceFile = sourceFileOrBundle.kind === 279 /* SourceFile */ ? sourceFileOrBundle : undefined; + var sourceFiles = bundle ? bundle.sourceFiles : [sourceFile]; + var sourceMapGenerator; + if (shouldEmitSourceMaps(mapOptions, sourceFileOrBundle)) { + sourceMapGenerator = ts.createSourceMapGenerator(host, ts.getBaseFileName(ts.normalizeSlashes(jsFilePath)), getSourceRoot(mapOptions), getSourceMapDirectory(mapOptions, jsFilePath, sourceFile), mapOptions); + } + if (bundle) { + printer.writeBundle(bundle, bundleInfo, writer, sourceMapGenerator); + } + else { + printer.writeFile(sourceFile, writer, sourceMapGenerator); + } + if (sourceMapGenerator) { + if (sourceMapDataList) { + sourceMapDataList.push({ + inputSourceFileNames: sourceMapGenerator.getSources(), + sourceMap: sourceMapGenerator.toJSON() + }); + } + var sourceMappingURL = getSourceMappingURL(mapOptions, sourceMapGenerator, jsFilePath, sourceMapFilePath, sourceFile); + if (sourceMappingURL) { + if (!writer.isAtStartOfLine()) + writer.rawWrite(newLine); + writer.writeComment("//# " + "sourceMappingURL" + "=" + sourceMappingURL); // Tools can sometimes see this line as a source mapping url comment + } + // Write the source map + if (sourceMapFilePath) { + var sourceMap = sourceMapGenerator.toString(); + ts.writeFile(host, emitterDiagnostics, sourceMapFilePath, sourceMap, /*writeByteOrderMark*/ false, sourceFiles); + } + } + else { + writer.writeLine(); + } + // Write the output file + ts.writeFile(host, emitterDiagnostics, jsFilePath, writer.getText(), !!compilerOptions.emitBOM, sourceFiles); + // Write bundled offset information if applicable + if (bundleInfoPath) { + bundleInfo.totalLength = writer.getTextPos(); + ts.writeFile(host, emitterDiagnostics, bundleInfoPath, JSON.stringify(bundleInfo, undefined, 2), /*writeByteOrderMark*/ false); + } + // Reset state + writer.clear(); + bundleInfo = createDefaultBundleInfo(); + } + function shouldEmitSourceMaps(mapOptions, sourceFileOrBundle) { + return (mapOptions.sourceMap || mapOptions.inlineSourceMap) + && (sourceFileOrBundle.kind !== 279 /* SourceFile */ || !ts.fileExtensionIs(sourceFileOrBundle.fileName, ".json" /* Json */)); + } + function getSourceRoot(mapOptions) { + // Normalize source root and make sure it has trailing "/" so that it can be used to combine paths with the + // relative paths of the sources list in the sourcemap + var sourceRoot = ts.normalizeSlashes(mapOptions.sourceRoot || ""); + return sourceRoot ? ts.ensureTrailingDirectorySeparator(sourceRoot) : sourceRoot; + } + function getSourceMapDirectory(mapOptions, filePath, sourceFile) { + if (mapOptions.sourceRoot) + return host.getCommonSourceDirectory(); + if (mapOptions.mapRoot) { + var sourceMapDir = ts.normalizeSlashes(mapOptions.mapRoot); + if (sourceFile) { + // For modules or multiple emit files the mapRoot will have directory structure like the sources + // So if src\a.ts and src\lib\b.ts are compiled together user would be moving the maps into mapRoot\a.js.map and mapRoot\lib\b.js.map + sourceMapDir = ts.getDirectoryPath(ts.getSourceFilePathInNewDir(sourceFile.fileName, host, sourceMapDir)); + } + if (ts.getRootLength(sourceMapDir) === 0) { + // The relative paths are relative to the common directory + sourceMapDir = ts.combinePaths(host.getCommonSourceDirectory(), sourceMapDir); + } + return sourceMapDir; + } + return ts.getDirectoryPath(ts.normalizePath(filePath)); + } + function getSourceMappingURL(mapOptions, sourceMapGenerator, filePath, sourceMapFilePath, sourceFile) { + if (mapOptions.inlineSourceMap) { + // Encode the sourceMap into the sourceMap url + var sourceMapText = sourceMapGenerator.toString(); + var base64SourceMapText = ts.base64encode(ts.sys, sourceMapText); + return "data:application/json;base64," + base64SourceMapText; + } + var sourceMapFile = ts.getBaseFileName(ts.normalizeSlashes(ts.Debug.assertDefined(sourceMapFilePath))); + if (mapOptions.mapRoot) { + var sourceMapDir = ts.normalizeSlashes(mapOptions.mapRoot); + if (sourceFile) { + // For modules or multiple emit files the mapRoot will have directory structure like the sources + // So if src\a.ts and src\lib\b.ts are compiled together user would be moving the maps into mapRoot\a.js.map and mapRoot\lib\b.js.map + sourceMapDir = ts.getDirectoryPath(ts.getSourceFilePathInNewDir(sourceFile.fileName, host, sourceMapDir)); + } + if (ts.getRootLength(sourceMapDir) === 0) { + // The relative paths are relative to the common directory + sourceMapDir = ts.combinePaths(host.getCommonSourceDirectory(), sourceMapDir); + return ts.getRelativePathToDirectoryOrUrl(ts.getDirectoryPath(ts.normalizePath(filePath)), // get the relative sourceMapDir path based on jsFilePath + ts.combinePaths(sourceMapDir, sourceMapFile), // this is where user expects to see sourceMap + host.getCurrentDirectory(), host.getCanonicalFileName, + /*isAbsolutePathAnUrl*/ true); + } + else { + return ts.combinePaths(sourceMapDir, sourceMapFile); + } + } + return sourceMapFile; + } + } + ts.emitFiles = emitFiles; + var PipelinePhase; + (function (PipelinePhase) { + PipelinePhase[PipelinePhase["Notification"] = 0] = "Notification"; + PipelinePhase[PipelinePhase["Substitution"] = 1] = "Substitution"; + PipelinePhase[PipelinePhase["Comments"] = 2] = "Comments"; + PipelinePhase[PipelinePhase["SourceMaps"] = 3] = "SourceMaps"; + PipelinePhase[PipelinePhase["Emit"] = 4] = "Emit"; + })(PipelinePhase || (PipelinePhase = {})); + function createPrinter(printerOptions, handlers) { + if (printerOptions === void 0) { printerOptions = {}; } + if (handlers === void 0) { handlers = {}; } + var hasGlobalName = handlers.hasGlobalName, _a = handlers.onEmitNode, onEmitNode = _a === void 0 ? ts.noEmitNotification : _a, _b = handlers.substituteNode, substituteNode = _b === void 0 ? ts.noEmitSubstitution : _b, onBeforeEmitNodeArray = handlers.onBeforeEmitNodeArray, onAfterEmitNodeArray = handlers.onAfterEmitNodeArray, onBeforeEmitToken = handlers.onBeforeEmitToken, onAfterEmitToken = handlers.onAfterEmitToken; + var extendedDiagnostics = !!printerOptions.extendedDiagnostics; + var newLine = ts.getNewLineCharacter(printerOptions); + var moduleKind = ts.getEmitModuleKind(printerOptions); + var bundledHelpers = ts.createMap(); + var currentSourceFile; + var nodeIdToGeneratedName; // Map of generated names for specific nodes. + var autoGeneratedIdToGeneratedName; // Map of generated names for temp and loop variables. + var generatedNames; // Set of names generated by the NameGenerator. + var tempFlagsStack; // Stack of enclosing name generation scopes. + var tempFlags; // TempFlags for the current name generation scope. + var reservedNamesStack; // Stack of TempFlags reserved in enclosing name generation scopes. + var reservedNames; // TempFlags to reserve in nested name generation scopes. + var writer; + var ownWriter; // Reusable `EmitTextWriter` for basic printing. + var write = writeBase; + var isOwnFileEmit; + // Source Maps + var sourceMapsDisabled = true; + var sourceMapGenerator; + var sourceMapSource; + var sourceMapSourceIndex = -1; + // Comments + var containerPos = -1; + var containerEnd = -1; + var declarationListContainerEnd = -1; + var currentLineMap; + var detachedCommentsInfo; + var hasWrittenComment = false; + var commentsDisabled = !!printerOptions.removeComments; + var _c = ts.performance.createTimerIf(extendedDiagnostics, "commentTime", "beforeComment", "afterComment"), enterComment = _c.enter, exitComment = _c.exit; + reset(); + return { + // public API + printNode: printNode, + printList: printList, + printFile: printFile, + printBundle: printBundle, + // internal API + writeNode: writeNode, + writeList: writeList, + writeFile: writeFile, + writeBundle: writeBundle + }; + function printNode(hint, node, sourceFile) { + switch (hint) { + case 0 /* SourceFile */: + ts.Debug.assert(ts.isSourceFile(node), "Expected a SourceFile node."); + break; + case 2 /* IdentifierName */: + ts.Debug.assert(ts.isIdentifier(node), "Expected an Identifier node."); + break; + case 1 /* Expression */: + ts.Debug.assert(ts.isExpression(node), "Expected an Expression node."); + break; + } + switch (node.kind) { + case 279 /* SourceFile */: return printFile(node); + case 280 /* Bundle */: return printBundle(node); + case 281 /* UnparsedSource */: return printUnparsedSource(node); + } + writeNode(hint, node, sourceFile, beginPrint()); + return endPrint(); + } + function printList(format, nodes, sourceFile) { + writeList(format, nodes, sourceFile, beginPrint()); + return endPrint(); + } + function printBundle(bundle) { + writeBundle(bundle, /*bundleInfo*/ undefined, beginPrint(), /*sourceMapEmitter*/ undefined); + return endPrint(); + } + function printFile(sourceFile) { + writeFile(sourceFile, beginPrint(), /*sourceMapEmitter*/ undefined); + return endPrint(); + } + function printUnparsedSource(unparsed) { + writeUnparsedSource(unparsed, beginPrint()); + return endPrint(); + } + function writeNode(hint, node, sourceFile, output) { + var previousWriter = writer; + setWriter(output, /*_sourceMapGenerator*/ undefined); + print(hint, node, sourceFile); + reset(); + writer = previousWriter; + } + function writeList(format, nodes, sourceFile, output) { + var previousWriter = writer; + setWriter(output, /*_sourceMapGenerator*/ undefined); + if (sourceFile) { + setSourceFile(sourceFile); + } + emitList(syntheticParent, nodes, format); + reset(); + writer = previousWriter; + } + function writeBundle(bundle, bundleInfo, output, sourceMapGenerator) { + isOwnFileEmit = false; + var previousWriter = writer; + setWriter(output, sourceMapGenerator); + emitShebangIfNeeded(bundle); + emitPrologueDirectivesIfNeeded(bundle); + emitHelpers(bundle); + emitSyntheticTripleSlashReferencesIfNeeded(bundle); + for (var _a = 0, _b = bundle.prepends; _a < _b.length; _a++) { + var prepend = _b[_a]; + writeLine(); + print(4 /* Unspecified */, prepend, /*sourceFile*/ undefined); + } + if (bundleInfo) { + bundleInfo.originalOffset = writer.getTextPos(); + } + for (var _c = 0, _d = bundle.sourceFiles; _c < _d.length; _c++) { + var sourceFile = _d[_c]; + print(0 /* SourceFile */, sourceFile, sourceFile); + } + reset(); + writer = previousWriter; + } + function writeUnparsedSource(unparsed, output) { + var previousWriter = writer; + setWriter(output, /*_sourceMapGenerator*/ undefined); + print(4 /* Unspecified */, unparsed, /*sourceFile*/ undefined); + reset(); + writer = previousWriter; + } + function writeFile(sourceFile, output, sourceMapGenerator) { + isOwnFileEmit = true; + var previousWriter = writer; + setWriter(output, sourceMapGenerator); + emitShebangIfNeeded(sourceFile); + emitPrologueDirectivesIfNeeded(sourceFile); + print(0 /* SourceFile */, sourceFile, sourceFile); + reset(); + writer = previousWriter; + } + function beginPrint() { + return ownWriter || (ownWriter = ts.createTextWriter(newLine)); + } + function endPrint() { + var text = ownWriter.getText(); + ownWriter.clear(); + return text; + } + function print(hint, node, sourceFile) { + if (sourceFile) { + setSourceFile(sourceFile); + } + var pipelinePhase = getPipelinePhase(0 /* Notification */, node); + pipelinePhase(hint, node); + } + function setSourceFile(sourceFile) { + currentSourceFile = sourceFile; + currentLineMap = undefined; + detachedCommentsInfo = undefined; + if (sourceFile) { + setSourceMapSource(sourceFile); + } + } + function setWriter(_writer, _sourceMapGenerator) { + if (_writer && printerOptions.omitTrailingSemicolon) { + _writer = ts.getTrailingSemicolonOmittingWriter(_writer); + } + writer = _writer; // TODO: GH#18217 + sourceMapGenerator = _sourceMapGenerator; + sourceMapsDisabled = !writer || !sourceMapGenerator; + } + function reset() { + nodeIdToGeneratedName = []; + autoGeneratedIdToGeneratedName = []; + generatedNames = ts.createMap(); + tempFlagsStack = []; + tempFlags = 0 /* Auto */; + reservedNamesStack = []; + currentSourceFile = undefined; + currentLineMap = undefined; + detachedCommentsInfo = undefined; + setWriter(/*output*/ undefined, /*_sourceMapGenerator*/ undefined); + } + function getCurrentLineMap() { + return currentLineMap || (currentLineMap = ts.getLineStarts(currentSourceFile)); + } + function emit(node) { + if (node === undefined) + return; + var pipelinePhase = getPipelinePhase(0 /* Notification */, node); + pipelinePhase(4 /* Unspecified */, node); + } + function emitIdentifierName(node) { + if (node === undefined) + return; + var pipelinePhase = getPipelinePhase(0 /* Notification */, node); + pipelinePhase(2 /* IdentifierName */, node); + } + function emitExpression(node) { + if (node === undefined) + return; + var pipelinePhase = getPipelinePhase(0 /* Notification */, node); + pipelinePhase(1 /* Expression */, node); + } + function getPipelinePhase(phase, node) { + switch (phase) { + case 0 /* Notification */: + if (onEmitNode !== ts.noEmitNotification) { + return pipelineEmitWithNotification; + } + // falls through + case 1 /* Substitution */: + if (substituteNode !== ts.noEmitSubstitution) { + return pipelineEmitWithSubstitution; + } + // falls through + case 2 /* Comments */: + if (!commentsDisabled && node.kind !== 279 /* SourceFile */) { + return pipelineEmitWithComments; + } + // falls through + case 3 /* SourceMaps */: + if (!sourceMapsDisabled && node.kind !== 279 /* SourceFile */ && !ts.isInJsonFile(node)) { + return pipelineEmitWithSourceMap; + } + // falls through + case 4 /* Emit */: + return pipelineEmitWithHint; + default: + return ts.Debug.assertNever(phase); + } + } + function getNextPipelinePhase(currentPhase, node) { + return getPipelinePhase(currentPhase + 1, node); + } + function pipelineEmitWithNotification(hint, node) { + var pipelinePhase = getNextPipelinePhase(0 /* Notification */, node); + onEmitNode(hint, node, pipelinePhase); + } + function pipelineEmitWithHint(hint, node) { + if (hint === 0 /* SourceFile */) + return emitSourceFile(ts.cast(node, ts.isSourceFile)); + if (hint === 2 /* IdentifierName */) + return emitIdentifier(ts.cast(node, ts.isIdentifier)); + if (hint === 3 /* MappedTypeParameter */) + return emitMappedTypeParameter(ts.cast(node, ts.isTypeParameterDeclaration)); + if (hint === 5 /* EmbeddedStatement */) { + ts.Debug.assertNode(node, ts.isEmptyStatement); + return emitEmptyStatement(/*isEmbeddedStatement*/ true); + } + if (hint === 4 /* Unspecified */) { + if (ts.isKeyword(node.kind)) + return writeTokenNode(node, writeKeyword); + switch (node.kind) { + // Pseudo-literals + case 15 /* TemplateHead */: + case 16 /* TemplateMiddle */: + case 17 /* TemplateTail */: + return emitLiteral(node); + case 281 /* UnparsedSource */: + return emitUnparsedSource(node); + // Identifiers + case 72 /* Identifier */: + return emitIdentifier(node); + // Parse tree nodes + // Names + case 148 /* QualifiedName */: + return emitQualifiedName(node); + case 149 /* ComputedPropertyName */: + return emitComputedPropertyName(node); + // Signature elements + case 150 /* TypeParameter */: + return emitTypeParameter(node); + case 151 /* Parameter */: + return emitParameter(node); + case 152 /* Decorator */: + return emitDecorator(node); + // Type members + case 153 /* PropertySignature */: + return emitPropertySignature(node); + case 154 /* PropertyDeclaration */: + return emitPropertyDeclaration(node); + case 155 /* MethodSignature */: + return emitMethodSignature(node); + case 156 /* MethodDeclaration */: + return emitMethodDeclaration(node); + case 157 /* Constructor */: + return emitConstructor(node); + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + return emitAccessorDeclaration(node); + case 160 /* CallSignature */: + return emitCallSignature(node); + case 161 /* ConstructSignature */: + return emitConstructSignature(node); + case 162 /* IndexSignature */: + return emitIndexSignature(node); + // Types + case 163 /* TypePredicate */: + return emitTypePredicate(node); + case 164 /* TypeReference */: + return emitTypeReference(node); + case 165 /* FunctionType */: + return emitFunctionType(node); + case 289 /* JSDocFunctionType */: + return emitJSDocFunctionType(node); + case 166 /* ConstructorType */: + return emitConstructorType(node); + case 167 /* TypeQuery */: + return emitTypeQuery(node); + case 168 /* TypeLiteral */: + return emitTypeLiteral(node); + case 169 /* ArrayType */: + return emitArrayType(node); + case 170 /* TupleType */: + return emitTupleType(node); + case 171 /* OptionalType */: + return emitOptionalType(node); + case 173 /* UnionType */: + return emitUnionType(node); + case 174 /* IntersectionType */: + return emitIntersectionType(node); + case 175 /* ConditionalType */: + return emitConditionalType(node); + case 176 /* InferType */: + return emitInferType(node); + case 177 /* ParenthesizedType */: + return emitParenthesizedType(node); + case 211 /* ExpressionWithTypeArguments */: + return emitExpressionWithTypeArguments(node); + case 178 /* ThisType */: + return emitThisType(); + case 179 /* TypeOperator */: + return emitTypeOperator(node); + case 180 /* IndexedAccessType */: + return emitIndexedAccessType(node); + case 181 /* MappedType */: + return emitMappedType(node); + case 182 /* LiteralType */: + return emitLiteralType(node); + case 183 /* ImportType */: + return emitImportTypeNode(node); + case 284 /* JSDocAllType */: + writePunctuation("*"); + return; + case 285 /* JSDocUnknownType */: + writePunctuation("?"); + return; + case 286 /* JSDocNullableType */: + return emitJSDocNullableType(node); + case 287 /* JSDocNonNullableType */: + return emitJSDocNonNullableType(node); + case 288 /* JSDocOptionalType */: + return emitJSDocOptionalType(node); + case 172 /* RestType */: + case 290 /* JSDocVariadicType */: + return emitRestOrJSDocVariadicType(node); + // Binding patterns + case 184 /* ObjectBindingPattern */: + return emitObjectBindingPattern(node); + case 185 /* ArrayBindingPattern */: + return emitArrayBindingPattern(node); + case 186 /* BindingElement */: + return emitBindingElement(node); + // Misc + case 216 /* TemplateSpan */: + return emitTemplateSpan(node); + case 217 /* SemicolonClassElement */: + return emitSemicolonClassElement(); + // Statements + case 218 /* Block */: + return emitBlock(node); + case 219 /* VariableStatement */: + return emitVariableStatement(node); + case 220 /* EmptyStatement */: + return emitEmptyStatement(/*isEmbeddedStatement*/ false); + case 221 /* ExpressionStatement */: + return emitExpressionStatement(node); + case 222 /* IfStatement */: + return emitIfStatement(node); + case 223 /* DoStatement */: + return emitDoStatement(node); + case 224 /* WhileStatement */: + return emitWhileStatement(node); + case 225 /* ForStatement */: + return emitForStatement(node); + case 226 /* ForInStatement */: + return emitForInStatement(node); + case 227 /* ForOfStatement */: + return emitForOfStatement(node); + case 228 /* ContinueStatement */: + return emitContinueStatement(node); + case 229 /* BreakStatement */: + return emitBreakStatement(node); + case 230 /* ReturnStatement */: + return emitReturnStatement(node); + case 231 /* WithStatement */: + return emitWithStatement(node); + case 232 /* SwitchStatement */: + return emitSwitchStatement(node); + case 233 /* LabeledStatement */: + return emitLabeledStatement(node); + case 234 /* ThrowStatement */: + return emitThrowStatement(node); + case 235 /* TryStatement */: + return emitTryStatement(node); + case 236 /* DebuggerStatement */: + return emitDebuggerStatement(node); + // Declarations + case 237 /* VariableDeclaration */: + return emitVariableDeclaration(node); + case 238 /* VariableDeclarationList */: + return emitVariableDeclarationList(node); + case 239 /* FunctionDeclaration */: + return emitFunctionDeclaration(node); + case 240 /* ClassDeclaration */: + return emitClassDeclaration(node); + case 241 /* InterfaceDeclaration */: + return emitInterfaceDeclaration(node); + case 242 /* TypeAliasDeclaration */: + return emitTypeAliasDeclaration(node); + case 243 /* EnumDeclaration */: + return emitEnumDeclaration(node); + case 244 /* ModuleDeclaration */: + return emitModuleDeclaration(node); + case 245 /* ModuleBlock */: + return emitModuleBlock(node); + case 246 /* CaseBlock */: + return emitCaseBlock(node); + case 247 /* NamespaceExportDeclaration */: + return emitNamespaceExportDeclaration(node); + case 248 /* ImportEqualsDeclaration */: + return emitImportEqualsDeclaration(node); + case 249 /* ImportDeclaration */: + return emitImportDeclaration(node); + case 250 /* ImportClause */: + return emitImportClause(node); + case 251 /* NamespaceImport */: + return emitNamespaceImport(node); + case 252 /* NamedImports */: + return emitNamedImports(node); + case 253 /* ImportSpecifier */: + return emitImportSpecifier(node); + case 254 /* ExportAssignment */: + return emitExportAssignment(node); + case 255 /* ExportDeclaration */: + return emitExportDeclaration(node); + case 256 /* NamedExports */: + return emitNamedExports(node); + case 257 /* ExportSpecifier */: + return emitExportSpecifier(node); + case 258 /* MissingDeclaration */: + return; + // Module references + case 259 /* ExternalModuleReference */: + return emitExternalModuleReference(node); + // JSX (non-expression) + case 11 /* JsxText */: + return emitJsxText(node); + case 262 /* JsxOpeningElement */: + case 265 /* JsxOpeningFragment */: + return emitJsxOpeningElementOrFragment(node); + case 263 /* JsxClosingElement */: + case 266 /* JsxClosingFragment */: + return emitJsxClosingElementOrFragment(node); + case 267 /* JsxAttribute */: + return emitJsxAttribute(node); + case 268 /* JsxAttributes */: + return emitJsxAttributes(node); + case 269 /* JsxSpreadAttribute */: + return emitJsxSpreadAttribute(node); + case 270 /* JsxExpression */: + return emitJsxExpression(node); + // Clauses + case 271 /* CaseClause */: + return emitCaseClause(node); + case 272 /* DefaultClause */: + return emitDefaultClause(node); + case 273 /* HeritageClause */: + return emitHeritageClause(node); + case 274 /* CatchClause */: + return emitCatchClause(node); + // Property assignments + case 275 /* PropertyAssignment */: + return emitPropertyAssignment(node); + case 276 /* ShorthandPropertyAssignment */: + return emitShorthandPropertyAssignment(node); + case 277 /* SpreadAssignment */: + return emitSpreadAssignment(node); + // Enum + case 278 /* EnumMember */: + return emitEnumMember(node); + // JSDoc nodes (only used in codefixes currently) + case 299 /* JSDocParameterTag */: + case 305 /* JSDocPropertyTag */: + return emitJSDocPropertyLikeTag(node); + case 300 /* JSDocReturnTag */: + case 302 /* JSDocTypeTag */: + case 301 /* JSDocThisTag */: + case 298 /* JSDocEnumTag */: + return emitJSDocSimpleTypedTag(node); + case 295 /* JSDocAugmentsTag */: + return emitJSDocAugmentsTag(node); + case 303 /* JSDocTemplateTag */: + return emitJSDocTemplateTag(node); + case 304 /* JSDocTypedefTag */: + return emitJSDocTypedefTag(node); + case 297 /* JSDocCallbackTag */: + return emitJSDocCallbackTag(node); + case 293 /* JSDocSignature */: + return emitJSDocSignature(node); + case 292 /* JSDocTypeLiteral */: + return emitJSDocTypeLiteral(node); + case 296 /* JSDocClassTag */: + case 294 /* JSDocTag */: + return emitJSDocSimpleTag(node); + case 291 /* JSDocComment */: + return emitJSDoc(node); + // Transformation nodes (ignored) + } + if (ts.isExpression(node)) { + hint = 1 /* Expression */; + if (substituteNode !== ts.noEmitSubstitution) { + node = substituteNode(hint, node); + } + } + else if (ts.isToken(node)) { + return writeTokenNode(node, writePunctuation); + } + } + if (hint === 1 /* Expression */) { + switch (node.kind) { + // Literals + case 8 /* NumericLiteral */: + case 9 /* BigIntLiteral */: + return emitNumericOrBigIntLiteral(node); + case 10 /* StringLiteral */: + case 13 /* RegularExpressionLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: + return emitLiteral(node); + // Identifiers + case 72 /* Identifier */: + return emitIdentifier(node); + // Reserved words + case 87 /* FalseKeyword */: + case 96 /* NullKeyword */: + case 98 /* SuperKeyword */: + case 102 /* TrueKeyword */: + case 100 /* ThisKeyword */: + case 92 /* ImportKeyword */: + writeTokenNode(node, writeKeyword); + return; + // Expressions + case 187 /* ArrayLiteralExpression */: + return emitArrayLiteralExpression(node); + case 188 /* ObjectLiteralExpression */: + return emitObjectLiteralExpression(node); + case 189 /* PropertyAccessExpression */: + return emitPropertyAccessExpression(node); + case 190 /* ElementAccessExpression */: + return emitElementAccessExpression(node); + case 191 /* CallExpression */: + return emitCallExpression(node); + case 192 /* NewExpression */: + return emitNewExpression(node); + case 193 /* TaggedTemplateExpression */: + return emitTaggedTemplateExpression(node); + case 194 /* TypeAssertionExpression */: + return emitTypeAssertionExpression(node); + case 195 /* ParenthesizedExpression */: + return emitParenthesizedExpression(node); + case 196 /* FunctionExpression */: + return emitFunctionExpression(node); + case 197 /* ArrowFunction */: + return emitArrowFunction(node); + case 198 /* DeleteExpression */: + return emitDeleteExpression(node); + case 199 /* TypeOfExpression */: + return emitTypeOfExpression(node); + case 200 /* VoidExpression */: + return emitVoidExpression(node); + case 201 /* AwaitExpression */: + return emitAwaitExpression(node); + case 202 /* PrefixUnaryExpression */: + return emitPrefixUnaryExpression(node); + case 203 /* PostfixUnaryExpression */: + return emitPostfixUnaryExpression(node); + case 204 /* BinaryExpression */: + return emitBinaryExpression(node); + case 205 /* ConditionalExpression */: + return emitConditionalExpression(node); + case 206 /* TemplateExpression */: + return emitTemplateExpression(node); + case 207 /* YieldExpression */: + return emitYieldExpression(node); + case 208 /* SpreadElement */: + return emitSpreadExpression(node); + case 209 /* ClassExpression */: + return emitClassExpression(node); + case 210 /* OmittedExpression */: + return; + case 212 /* AsExpression */: + return emitAsExpression(node); + case 213 /* NonNullExpression */: + return emitNonNullExpression(node); + case 214 /* MetaProperty */: + return emitMetaProperty(node); + // JSX + case 260 /* JsxElement */: + return emitJsxElement(node); + case 261 /* JsxSelfClosingElement */: + return emitJsxSelfClosingElement(node); + case 264 /* JsxFragment */: + return emitJsxFragment(node); + // Transformation nodes + case 308 /* PartiallyEmittedExpression */: + return emitPartiallyEmittedExpression(node); + case 309 /* CommaListExpression */: + return emitCommaList(node); + } + } + } + function emitMappedTypeParameter(node) { + emit(node.name); + writeSpace(); + writeKeyword("in"); + writeSpace(); + emit(node.constraint); + } + function pipelineEmitWithSubstitution(hint, node) { + var pipelinePhase = getNextPipelinePhase(1 /* Substitution */, node); + pipelinePhase(hint, substituteNode(hint, node)); + } + function emitHelpers(node) { + var helpersEmitted = false; + var bundle = node.kind === 280 /* Bundle */ ? node : undefined; + if (bundle && moduleKind === ts.ModuleKind.None) { + return; + } + var numNodes = bundle ? bundle.sourceFiles.length : 1; + for (var i = 0; i < numNodes; i++) { + var currentNode = bundle ? bundle.sourceFiles[i] : node; + var sourceFile = ts.isSourceFile(currentNode) ? currentNode : currentSourceFile; + var shouldSkip = printerOptions.noEmitHelpers || ts.getExternalHelpersModuleName(sourceFile) !== undefined; + var shouldBundle = ts.isSourceFile(currentNode) && !isOwnFileEmit; + var helpers = ts.getEmitHelpers(currentNode); + if (helpers) { + for (var _a = 0, _b = ts.stableSort(helpers, ts.compareEmitHelpers); _a < _b.length; _a++) { + var helper = _b[_a]; + if (!helper.scoped) { + // Skip the helper if it can be skipped and the noEmitHelpers compiler + // option is set, or if it can be imported and the importHelpers compiler + // option is set. + if (shouldSkip) + continue; + // Skip the helper if it can be bundled but hasn't already been emitted and we + // are emitting a bundled module. + if (shouldBundle) { + if (bundledHelpers.get(helper.name)) { + continue; + } + bundledHelpers.set(helper.name, true); + } + } + else if (bundle) { + // Skip the helper if it is scoped and we are emitting bundled helpers + continue; + } + if (typeof helper.text === "string") { + writeLines(helper.text); + } + else { + writeLines(helper.text(makeFileLevelOptimisticUniqueName)); + } + helpersEmitted = true; + } + } + } + return helpersEmitted; + } + // + // Literals/Pseudo-literals + // + // SyntaxKind.NumericLiteral + // SyntaxKind.BigIntLiteral + function emitNumericOrBigIntLiteral(node) { + emitLiteral(node); + } + // SyntaxKind.StringLiteral + // SyntaxKind.RegularExpressionLiteral + // SyntaxKind.NoSubstitutionTemplateLiteral + // SyntaxKind.TemplateHead + // SyntaxKind.TemplateMiddle + // SyntaxKind.TemplateTail + function emitLiteral(node) { + var text = getLiteralTextOfNode(node, printerOptions.neverAsciiEscape); + if ((printerOptions.sourceMap || printerOptions.inlineSourceMap) + && (node.kind === 10 /* StringLiteral */ || ts.isTemplateLiteralKind(node.kind))) { + writeLiteral(text); + } + else { + // Quick info expects all literals to be called with writeStringLiteral, as there's no specific type for numberLiterals + writeStringLiteral(text); + } + } + // SyntaxKind.UnparsedSource + function emitUnparsedSource(unparsed) { + writer.rawWrite(unparsed.text); + } + // + // Identifiers + // + function emitIdentifier(node) { + var writeText = node.symbol ? writeSymbol : write; + writeText(getTextOfNode(node, /*includeTrivia*/ false), node.symbol); + emitList(node, node.typeArguments, 53776 /* TypeParameters */); // Call emitList directly since it could be an array of TypeParameterDeclarations _or_ type arguments + } + // + // Names + // + function emitQualifiedName(node) { + emitEntityName(node.left); + writePunctuation("."); + emit(node.right); + } + function emitEntityName(node) { + if (node.kind === 72 /* Identifier */) { + emitExpression(node); + } + else { + emit(node); + } + } + function emitComputedPropertyName(node) { + writePunctuation("["); + emitExpression(node.expression); + writePunctuation("]"); + } + // + // Signature elements + // + function emitTypeParameter(node) { + emit(node.name); + if (node.constraint) { + writeSpace(); + writeKeyword("extends"); + writeSpace(); + emit(node.constraint); + } + if (node.default) { + writeSpace(); + writeOperator("="); + writeSpace(); + emit(node.default); + } + } + function emitParameter(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + emit(node.dotDotDotToken); + emitNodeWithWriter(node.name, writeParameter); + emit(node.questionToken); + if (node.parent && node.parent.kind === 289 /* JSDocFunctionType */ && !node.name) { + emit(node.type); + } + else { + emitTypeAnnotation(node.type); + } + // The comment position has to fallback to any present node within the parameterdeclaration because as it turns out, the parser can make parameter declarations with _just_ an initializer. + emitInitializer(node.initializer, node.type ? node.type.end : node.questionToken ? node.questionToken.end : node.name ? node.name.end : node.modifiers ? node.modifiers.end : node.decorators ? node.decorators.end : node.pos, node); + } + function emitDecorator(decorator) { + writePunctuation("@"); + emitExpression(decorator.expression); + } + // + // Type members + // + function emitPropertySignature(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + emitNodeWithWriter(node.name, writeProperty); + emit(node.questionToken); + emitTypeAnnotation(node.type); + writeTrailingSemicolon(); + } + function emitPropertyDeclaration(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + emit(node.name); + emit(node.questionToken); + emit(node.exclamationToken); + emitTypeAnnotation(node.type); + emitInitializer(node.initializer, node.type ? node.type.end : node.questionToken ? node.questionToken.end : node.name.end, node); + writeTrailingSemicolon(); + } + function emitMethodSignature(node) { + pushNameGenerationScope(node); + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + emit(node.name); + emit(node.questionToken); + emitTypeParameters(node, node.typeParameters); + emitParameters(node, node.parameters); + emitTypeAnnotation(node.type); + writeTrailingSemicolon(); + popNameGenerationScope(node); + } + function emitMethodDeclaration(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + emit(node.asteriskToken); + emit(node.name); + emit(node.questionToken); + emitSignatureAndBody(node, emitSignatureHead); + } + function emitConstructor(node) { + emitModifiers(node, node.modifiers); + writeKeyword("constructor"); + emitSignatureAndBody(node, emitSignatureHead); + } + function emitAccessorDeclaration(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + writeKeyword(node.kind === 158 /* GetAccessor */ ? "get" : "set"); + writeSpace(); + emit(node.name); + emitSignatureAndBody(node, emitSignatureHead); + } + function emitCallSignature(node) { + pushNameGenerationScope(node); + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + emitTypeParameters(node, node.typeParameters); + emitParameters(node, node.parameters); + emitTypeAnnotation(node.type); + writeTrailingSemicolon(); + popNameGenerationScope(node); + } + function emitConstructSignature(node) { + pushNameGenerationScope(node); + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + writeKeyword("new"); + writeSpace(); + emitTypeParameters(node, node.typeParameters); + emitParameters(node, node.parameters); + emitTypeAnnotation(node.type); + writeTrailingSemicolon(); + popNameGenerationScope(node); + } + function emitIndexSignature(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + emitParametersForIndexSignature(node, node.parameters); + emitTypeAnnotation(node.type); + writeTrailingSemicolon(); + } + function emitSemicolonClassElement() { + writeTrailingSemicolon(); + } + // + // Types + // + function emitTypePredicate(node) { + emit(node.parameterName); + writeSpace(); + writeKeyword("is"); + writeSpace(); + emit(node.type); + } + function emitTypeReference(node) { + emit(node.typeName); + emitTypeArguments(node, node.typeArguments); + } + function emitFunctionType(node) { + pushNameGenerationScope(node); + emitTypeParameters(node, node.typeParameters); + emitParametersForArrow(node, node.parameters); + writeSpace(); + writePunctuation("=>"); + writeSpace(); + emit(node.type); + popNameGenerationScope(node); + } + function emitJSDocFunctionType(node) { + writeKeyword("function"); + emitParameters(node, node.parameters); + writePunctuation(":"); + emit(node.type); + } + function emitJSDocNullableType(node) { + writePunctuation("?"); + emit(node.type); + } + function emitJSDocNonNullableType(node) { + writePunctuation("!"); + emit(node.type); + } + function emitJSDocOptionalType(node) { + emit(node.type); + writePunctuation("="); + } + function emitConstructorType(node) { + pushNameGenerationScope(node); + writeKeyword("new"); + writeSpace(); + emitTypeParameters(node, node.typeParameters); + emitParameters(node, node.parameters); + writeSpace(); + writePunctuation("=>"); + writeSpace(); + emit(node.type); + popNameGenerationScope(node); + } + function emitTypeQuery(node) { + writeKeyword("typeof"); + writeSpace(); + emit(node.exprName); + } + function emitTypeLiteral(node) { + writePunctuation("{"); + var flags = ts.getEmitFlags(node) & 1 /* SingleLine */ ? 768 /* SingleLineTypeLiteralMembers */ : 32897 /* MultiLineTypeLiteralMembers */; + emitList(node, node.members, flags | 524288 /* NoSpaceIfEmpty */); + writePunctuation("}"); + } + function emitArrayType(node) { + emit(node.elementType); + writePunctuation("["); + writePunctuation("]"); + } + function emitRestOrJSDocVariadicType(node) { + writePunctuation("..."); + emit(node.type); + } + function emitTupleType(node) { + writePunctuation("["); + emitList(node, node.elementTypes, 528 /* TupleTypeElements */); + writePunctuation("]"); + } + function emitOptionalType(node) { + emit(node.type); + writePunctuation("?"); + } + function emitUnionType(node) { + emitList(node, node.types, 516 /* UnionTypeConstituents */); + } + function emitIntersectionType(node) { + emitList(node, node.types, 520 /* IntersectionTypeConstituents */); + } + function emitConditionalType(node) { + emit(node.checkType); + writeSpace(); + writeKeyword("extends"); + writeSpace(); + emit(node.extendsType); + writeSpace(); + writePunctuation("?"); + writeSpace(); + emit(node.trueType); + writeSpace(); + writePunctuation(":"); + writeSpace(); + emit(node.falseType); + } + function emitInferType(node) { + writeKeyword("infer"); + writeSpace(); + emit(node.typeParameter); + } + function emitParenthesizedType(node) { + writePunctuation("("); + emit(node.type); + writePunctuation(")"); + } + function emitThisType() { + writeKeyword("this"); + } + function emitTypeOperator(node) { + writeTokenText(node.operator, writeKeyword); + writeSpace(); + emit(node.type); + } + function emitIndexedAccessType(node) { + emit(node.objectType); + writePunctuation("["); + emit(node.indexType); + writePunctuation("]"); + } + function emitMappedType(node) { + var emitFlags = ts.getEmitFlags(node); + writePunctuation("{"); + if (emitFlags & 1 /* SingleLine */) { + writeSpace(); + } + else { + writeLine(); + increaseIndent(); + } + if (node.readonlyToken) { + emit(node.readonlyToken); + if (node.readonlyToken.kind !== 133 /* ReadonlyKeyword */) { + writeKeyword("readonly"); + } + writeSpace(); + } + writePunctuation("["); + var pipelinePhase = getPipelinePhase(0 /* Notification */, node.typeParameter); + pipelinePhase(3 /* MappedTypeParameter */, node.typeParameter); + writePunctuation("]"); + if (node.questionToken) { + emit(node.questionToken); + if (node.questionToken.kind !== 56 /* QuestionToken */) { + writePunctuation("?"); + } + } + writePunctuation(":"); + writeSpace(); + emit(node.type); + writeTrailingSemicolon(); + if (emitFlags & 1 /* SingleLine */) { + writeSpace(); + } + else { + writeLine(); + decreaseIndent(); + } + writePunctuation("}"); + } + function emitLiteralType(node) { + emitExpression(node.literal); + } + function emitImportTypeNode(node) { + if (node.isTypeOf) { + writeKeyword("typeof"); + writeSpace(); + } + writeKeyword("import"); + writePunctuation("("); + emit(node.argument); + writePunctuation(")"); + if (node.qualifier) { + writePunctuation("."); + emit(node.qualifier); + } + emitTypeArguments(node, node.typeArguments); + } + // + // Binding patterns + // + function emitObjectBindingPattern(node) { + writePunctuation("{"); + emitList(node, node.elements, 525136 /* ObjectBindingPatternElements */); + writePunctuation("}"); + } + function emitArrayBindingPattern(node) { + writePunctuation("["); + emitList(node, node.elements, 524880 /* ArrayBindingPatternElements */); + writePunctuation("]"); + } + function emitBindingElement(node) { + emit(node.dotDotDotToken); + if (node.propertyName) { + emit(node.propertyName); + writePunctuation(":"); + writeSpace(); + } + emit(node.name); + emitInitializer(node.initializer, node.name.end, node); + } + // + // Expressions + // + function emitArrayLiteralExpression(node) { + var elements = node.elements; + var preferNewLine = node.multiLine ? 65536 /* PreferNewLine */ : 0 /* None */; + emitExpressionList(node, elements, 8914 /* ArrayLiteralExpressionElements */ | preferNewLine); + } + function emitObjectLiteralExpression(node) { + ts.forEach(node.properties, generateMemberNames); + var indentedFlag = ts.getEmitFlags(node) & 65536 /* Indented */; + if (indentedFlag) { + increaseIndent(); + } + var preferNewLine = node.multiLine ? 65536 /* PreferNewLine */ : 0 /* None */; + var allowTrailingComma = currentSourceFile.languageVersion >= 1 /* ES5 */ && !ts.isJsonSourceFile(currentSourceFile) ? 64 /* AllowTrailingComma */ : 0 /* None */; + emitList(node, node.properties, 526226 /* ObjectLiteralExpressionProperties */ | allowTrailingComma | preferNewLine); + if (indentedFlag) { + decreaseIndent(); + } + } + function emitPropertyAccessExpression(node) { + var indentBeforeDot = false; + var indentAfterDot = false; + if (!(ts.getEmitFlags(node) & 131072 /* NoIndentation */)) { + var dotRangeStart = node.expression.end; + var dotRangeEnd = ts.skipTrivia(currentSourceFile.text, node.expression.end) + 1; + var dotToken = ts.createToken(24 /* DotToken */); + dotToken.pos = dotRangeStart; + dotToken.end = dotRangeEnd; + indentBeforeDot = needsIndentation(node, node.expression, dotToken); + indentAfterDot = needsIndentation(node, dotToken, node.name); + } + emitExpression(node.expression); + increaseIndentIf(indentBeforeDot, /*writeSpaceIfNotIndenting*/ false); + var shouldEmitDotDot = !indentBeforeDot && needsDotDotForPropertyAccess(node.expression); + if (shouldEmitDotDot) { + writePunctuation("."); + } + emitTokenWithComment(24 /* DotToken */, node.expression.end, writePunctuation, node); + increaseIndentIf(indentAfterDot, /*writeSpaceIfNotIndenting*/ false); + emit(node.name); + decreaseIndentIf(indentBeforeDot, indentAfterDot); + } + // 1..toString is a valid property access, emit a dot after the literal + // Also emit a dot if expression is a integer const enum value - it will appear in generated code as numeric literal + function needsDotDotForPropertyAccess(expression) { + expression = ts.skipPartiallyEmittedExpressions(expression); + if (ts.isNumericLiteral(expression)) { + // check if numeric literal is a decimal literal that was originally written with a dot + var text = getLiteralTextOfNode(expression, /*neverAsciiEscape*/ true); + return !expression.numericLiteralFlags + && !ts.stringContains(text, ts.tokenToString(24 /* DotToken */)); + } + else if (ts.isPropertyAccessExpression(expression) || ts.isElementAccessExpression(expression)) { + // check if constant enum value is integer + var constantValue = ts.getConstantValue(expression); + // isFinite handles cases when constantValue is undefined + return typeof constantValue === "number" && isFinite(constantValue) + && Math.floor(constantValue) === constantValue + && printerOptions.removeComments; + } + } + function emitElementAccessExpression(node) { + emitExpression(node.expression); + emitTokenWithComment(22 /* OpenBracketToken */, node.expression.end, writePunctuation, node); + emitExpression(node.argumentExpression); + emitTokenWithComment(23 /* CloseBracketToken */, node.argumentExpression.end, writePunctuation, node); + } + function emitCallExpression(node) { + emitExpression(node.expression); + emitTypeArguments(node, node.typeArguments); + emitExpressionList(node, node.arguments, 2576 /* CallExpressionArguments */); + } + function emitNewExpression(node) { + emitTokenWithComment(95 /* NewKeyword */, node.pos, writeKeyword, node); + writeSpace(); + emitExpression(node.expression); + emitTypeArguments(node, node.typeArguments); + emitExpressionList(node, node.arguments, 18960 /* NewExpressionArguments */); + } + function emitTaggedTemplateExpression(node) { + emitExpression(node.tag); + emitTypeArguments(node, node.typeArguments); + writeSpace(); + emitExpression(node.template); + } + function emitTypeAssertionExpression(node) { + writePunctuation("<"); + emit(node.type); + writePunctuation(">"); + emitExpression(node.expression); + } + function emitParenthesizedExpression(node) { + var openParenPos = emitTokenWithComment(20 /* OpenParenToken */, node.pos, writePunctuation, node); + emitExpression(node.expression); + emitTokenWithComment(21 /* CloseParenToken */, node.expression ? node.expression.end : openParenPos, writePunctuation, node); + } + function emitFunctionExpression(node) { + generateNameIfNeeded(node.name); + emitFunctionDeclarationOrExpression(node); + } + function emitArrowFunction(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + emitSignatureAndBody(node, emitArrowFunctionHead); + } + function emitArrowFunctionHead(node) { + emitTypeParameters(node, node.typeParameters); + emitParametersForArrow(node, node.parameters); + emitTypeAnnotation(node.type); + writeSpace(); + emit(node.equalsGreaterThanToken); + } + function emitDeleteExpression(node) { + emitTokenWithComment(81 /* DeleteKeyword */, node.pos, writeKeyword, node); + writeSpace(); + emitExpression(node.expression); + } + function emitTypeOfExpression(node) { + emitTokenWithComment(104 /* TypeOfKeyword */, node.pos, writeKeyword, node); + writeSpace(); + emitExpression(node.expression); + } + function emitVoidExpression(node) { + emitTokenWithComment(106 /* VoidKeyword */, node.pos, writeKeyword, node); + writeSpace(); + emitExpression(node.expression); + } + function emitAwaitExpression(node) { + emitTokenWithComment(122 /* AwaitKeyword */, node.pos, writeKeyword, node); + writeSpace(); + emitExpression(node.expression); + } + function emitPrefixUnaryExpression(node) { + writeTokenText(node.operator, writeOperator); + if (shouldEmitWhitespaceBeforeOperand(node)) { + writeSpace(); + } + emitExpression(node.operand); + } + function shouldEmitWhitespaceBeforeOperand(node) { + // In some cases, we need to emit a space between the operator and the operand. One obvious case + // is when the operator is an identifier, like delete or typeof. We also need to do this for plus + // and minus expressions in certain cases. Specifically, consider the following two cases (parens + // are just for clarity of exposition, and not part of the source code): + // + // (+(+1)) + // (+(++1)) + // + // We need to emit a space in both cases. In the first case, the absence of a space will make + // the resulting expression a prefix increment operation. And in the second, it will make the resulting + // expression a prefix increment whose operand is a plus expression - (++(+x)) + // The same is true of minus of course. + var operand = node.operand; + return operand.kind === 202 /* PrefixUnaryExpression */ + && ((node.operator === 38 /* PlusToken */ && (operand.operator === 38 /* PlusToken */ || operand.operator === 44 /* PlusPlusToken */)) + || (node.operator === 39 /* MinusToken */ && (operand.operator === 39 /* MinusToken */ || operand.operator === 45 /* MinusMinusToken */))); + } + function emitPostfixUnaryExpression(node) { + emitExpression(node.operand); + writeTokenText(node.operator, writeOperator); + } + function emitBinaryExpression(node) { + var isCommaOperator = node.operatorToken.kind !== 27 /* CommaToken */; + var indentBeforeOperator = needsIndentation(node, node.left, node.operatorToken); + var indentAfterOperator = needsIndentation(node, node.operatorToken, node.right); + emitExpression(node.left); + increaseIndentIf(indentBeforeOperator, isCommaOperator); + emitLeadingCommentsOfPosition(node.operatorToken.pos); + writeTokenNode(node.operatorToken, node.operatorToken.kind === 93 /* InKeyword */ ? writeKeyword : writeOperator); + emitTrailingCommentsOfPosition(node.operatorToken.end, /*prefixSpace*/ true); // Binary operators should have a space before the comment starts + increaseIndentIf(indentAfterOperator, /*writeSpaceIfNotIndenting*/ true); + emitExpression(node.right); + decreaseIndentIf(indentBeforeOperator, indentAfterOperator); + } + function emitConditionalExpression(node) { + var indentBeforeQuestion = needsIndentation(node, node.condition, node.questionToken); + var indentAfterQuestion = needsIndentation(node, node.questionToken, node.whenTrue); + var indentBeforeColon = needsIndentation(node, node.whenTrue, node.colonToken); + var indentAfterColon = needsIndentation(node, node.colonToken, node.whenFalse); + emitExpression(node.condition); + increaseIndentIf(indentBeforeQuestion, /*writeSpaceIfNotIndenting*/ true); + emit(node.questionToken); + increaseIndentIf(indentAfterQuestion, /*writeSpaceIfNotIndenting*/ true); + emitExpression(node.whenTrue); + decreaseIndentIf(indentBeforeQuestion, indentAfterQuestion); + increaseIndentIf(indentBeforeColon, /*writeSpaceIfNotIndenting*/ true); + emit(node.colonToken); + increaseIndentIf(indentAfterColon, /*writeSpaceIfNotIndenting*/ true); + emitExpression(node.whenFalse); + decreaseIndentIf(indentBeforeColon, indentAfterColon); + } + function emitTemplateExpression(node) { + emit(node.head); + emitList(node, node.templateSpans, 262144 /* TemplateExpressionSpans */); + } + function emitYieldExpression(node) { + emitTokenWithComment(117 /* YieldKeyword */, node.pos, writeKeyword, node); + emit(node.asteriskToken); + emitExpressionWithLeadingSpace(node.expression); + } + function emitSpreadExpression(node) { + emitTokenWithComment(25 /* DotDotDotToken */, node.pos, writePunctuation, node); + emitExpression(node.expression); + } + function emitClassExpression(node) { + generateNameIfNeeded(node.name); + emitClassDeclarationOrExpression(node); + } + function emitExpressionWithTypeArguments(node) { + emitExpression(node.expression); + emitTypeArguments(node, node.typeArguments); + } + function emitAsExpression(node) { + emitExpression(node.expression); + if (node.type) { + writeSpace(); + writeKeyword("as"); + writeSpace(); + emit(node.type); + } + } + function emitNonNullExpression(node) { + emitExpression(node.expression); + writeOperator("!"); + } + function emitMetaProperty(node) { + writeToken(node.keywordToken, node.pos, writePunctuation); + writePunctuation("."); + emit(node.name); + } + // + // Misc + // + function emitTemplateSpan(node) { + emitExpression(node.expression); + emit(node.literal); + } + // + // Statements + // + function emitBlock(node) { + emitBlockStatements(node, /*forceSingleLine*/ !node.multiLine && isEmptyBlock(node)); + } + function emitBlockStatements(node, forceSingleLine) { + emitTokenWithComment(18 /* OpenBraceToken */, node.pos, writePunctuation, /*contextNode*/ node); + var format = forceSingleLine || ts.getEmitFlags(node) & 1 /* SingleLine */ ? 768 /* SingleLineBlockStatements */ : 129 /* MultiLineBlockStatements */; + emitList(node, node.statements, format); + emitTokenWithComment(19 /* CloseBraceToken */, node.statements.end, writePunctuation, /*contextNode*/ node, /*indentLeading*/ !!(format & 1 /* MultiLine */)); + } + function emitVariableStatement(node) { + emitModifiers(node, node.modifiers); + emit(node.declarationList); + writeTrailingSemicolon(); + } + function emitEmptyStatement(isEmbeddedStatement) { + // While most trailing semicolons are possibly insignificant, an embedded "empty" + // statement is significant and cannot be elided by a trailing-semicolon-omitting writer. + if (isEmbeddedStatement) { + writePunctuation(";"); + } + else { + writeTrailingSemicolon(); + } + } + function emitExpressionStatement(node) { + emitExpression(node.expression); + // Emit semicolon in non json files + // or if json file that created synthesized expression(eg.define expression statement when --out and amd code generation) + if (!ts.isJsonSourceFile(currentSourceFile) || ts.nodeIsSynthesized(node.expression)) { + writeTrailingSemicolon(); + } + } + function emitIfStatement(node) { + var openParenPos = emitTokenWithComment(91 /* IfKeyword */, node.pos, writeKeyword, node); + writeSpace(); + emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node); + emitExpression(node.expression); + emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node); + emitEmbeddedStatement(node, node.thenStatement); + if (node.elseStatement) { + writeLineOrSpace(node); + emitTokenWithComment(83 /* ElseKeyword */, node.thenStatement.end, writeKeyword, node); + if (node.elseStatement.kind === 222 /* IfStatement */) { + writeSpace(); + emit(node.elseStatement); + } + else { + emitEmbeddedStatement(node, node.elseStatement); + } + } + } + function emitWhileClause(node, startPos) { + var openParenPos = emitTokenWithComment(107 /* WhileKeyword */, startPos, writeKeyword, node); + writeSpace(); + emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node); + emitExpression(node.expression); + emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node); + } + function emitDoStatement(node) { + emitTokenWithComment(82 /* DoKeyword */, node.pos, writeKeyword, node); + emitEmbeddedStatement(node, node.statement); + if (ts.isBlock(node.statement)) { + writeSpace(); + } + else { + writeLineOrSpace(node); + } + emitWhileClause(node, node.statement.end); + writePunctuation(";"); + } + function emitWhileStatement(node) { + emitWhileClause(node, node.pos); + emitEmbeddedStatement(node, node.statement); + } + function emitForStatement(node) { + var openParenPos = emitTokenWithComment(89 /* ForKeyword */, node.pos, writeKeyword, node); + writeSpace(); + var pos = emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, /*contextNode*/ node); + emitForBinding(node.initializer); + pos = emitTokenWithComment(26 /* SemicolonToken */, node.initializer ? node.initializer.end : pos, writePunctuation, node); + emitExpressionWithLeadingSpace(node.condition); + pos = emitTokenWithComment(26 /* SemicolonToken */, node.condition ? node.condition.end : pos, writePunctuation, node); + emitExpressionWithLeadingSpace(node.incrementor); + emitTokenWithComment(21 /* CloseParenToken */, node.incrementor ? node.incrementor.end : pos, writePunctuation, node); + emitEmbeddedStatement(node, node.statement); + } + function emitForInStatement(node) { + var openParenPos = emitTokenWithComment(89 /* ForKeyword */, node.pos, writeKeyword, node); + writeSpace(); + emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node); + emitForBinding(node.initializer); + writeSpace(); + emitTokenWithComment(93 /* InKeyword */, node.initializer.end, writeKeyword, node); + writeSpace(); + emitExpression(node.expression); + emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node); + emitEmbeddedStatement(node, node.statement); + } + function emitForOfStatement(node) { + var openParenPos = emitTokenWithComment(89 /* ForKeyword */, node.pos, writeKeyword, node); + writeSpace(); + emitWithTrailingSpace(node.awaitModifier); + emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node); + emitForBinding(node.initializer); + writeSpace(); + emitTokenWithComment(147 /* OfKeyword */, node.initializer.end, writeKeyword, node); + writeSpace(); + emitExpression(node.expression); + emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node); + emitEmbeddedStatement(node, node.statement); + } + function emitForBinding(node) { + if (node !== undefined) { + if (node.kind === 238 /* VariableDeclarationList */) { + emit(node); + } + else { + emitExpression(node); + } + } + } + function emitContinueStatement(node) { + emitTokenWithComment(78 /* ContinueKeyword */, node.pos, writeKeyword, node); + emitWithLeadingSpace(node.label); + writeTrailingSemicolon(); + } + function emitBreakStatement(node) { + emitTokenWithComment(73 /* BreakKeyword */, node.pos, writeKeyword, node); + emitWithLeadingSpace(node.label); + writeTrailingSemicolon(); + } + function emitTokenWithComment(token, pos, writer, contextNode, indentLeading) { + var node = ts.getParseTreeNode(contextNode); + var isSimilarNode = node && node.kind === contextNode.kind; + var startPos = pos; + if (isSimilarNode) { + pos = ts.skipTrivia(currentSourceFile.text, pos); + } + if (emitLeadingCommentsOfPosition && isSimilarNode && contextNode.pos !== startPos) { + var needsIndent = indentLeading && !ts.positionsAreOnSameLine(startPos, pos, currentSourceFile); + if (needsIndent) { + increaseIndent(); + } + emitLeadingCommentsOfPosition(startPos); + if (needsIndent) { + decreaseIndent(); + } + } + pos = writeTokenText(token, writer, pos); + if (emitTrailingCommentsOfPosition && isSimilarNode && contextNode.end !== pos) { + emitTrailingCommentsOfPosition(pos, /*prefixSpace*/ true); + } + return pos; + } + function emitReturnStatement(node) { + emitTokenWithComment(97 /* ReturnKeyword */, node.pos, writeKeyword, /*contextNode*/ node); + emitExpressionWithLeadingSpace(node.expression); + writeTrailingSemicolon(); + } + function emitWithStatement(node) { + var openParenPos = emitTokenWithComment(108 /* WithKeyword */, node.pos, writeKeyword, node); + writeSpace(); + emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node); + emitExpression(node.expression); + emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node); + emitEmbeddedStatement(node, node.statement); + } + function emitSwitchStatement(node) { + var openParenPos = emitTokenWithComment(99 /* SwitchKeyword */, node.pos, writeKeyword, node); + writeSpace(); + emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node); + emitExpression(node.expression); + emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node); + writeSpace(); + emit(node.caseBlock); + } + function emitLabeledStatement(node) { + emit(node.label); + emitTokenWithComment(57 /* ColonToken */, node.label.end, writePunctuation, node); + writeSpace(); + emit(node.statement); + } + function emitThrowStatement(node) { + emitTokenWithComment(101 /* ThrowKeyword */, node.pos, writeKeyword, node); + emitExpressionWithLeadingSpace(node.expression); + writeTrailingSemicolon(); + } + function emitTryStatement(node) { + emitTokenWithComment(103 /* TryKeyword */, node.pos, writeKeyword, node); + writeSpace(); + emit(node.tryBlock); + if (node.catchClause) { + writeLineOrSpace(node); + emit(node.catchClause); + } + if (node.finallyBlock) { + writeLineOrSpace(node); + emitTokenWithComment(88 /* FinallyKeyword */, (node.catchClause || node.tryBlock).end, writeKeyword, node); + writeSpace(); + emit(node.finallyBlock); + } + } + function emitDebuggerStatement(node) { + writeToken(79 /* DebuggerKeyword */, node.pos, writeKeyword); + writeTrailingSemicolon(); + } + // + // Declarations + // + function emitVariableDeclaration(node) { + emit(node.name); + emitTypeAnnotation(node.type); + emitInitializer(node.initializer, node.type ? node.type.end : node.name.end, node); + } + function emitVariableDeclarationList(node) { + writeKeyword(ts.isLet(node) ? "let" : ts.isVarConst(node) ? "const" : "var"); + writeSpace(); + emitList(node, node.declarations, 528 /* VariableDeclarationList */); + } + function emitFunctionDeclaration(node) { + emitFunctionDeclarationOrExpression(node); + } + function emitFunctionDeclarationOrExpression(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + writeKeyword("function"); + emit(node.asteriskToken); + writeSpace(); + emitIdentifierName(node.name); // TODO: GH#18217 + emitSignatureAndBody(node, emitSignatureHead); + } + function emitBlockCallback(_hint, body) { + emitBlockFunctionBody(body); + } + function emitSignatureAndBody(node, emitSignatureHead) { + var body = node.body; + if (body) { + if (ts.isBlock(body)) { + var indentedFlag = ts.getEmitFlags(node) & 65536 /* Indented */; + if (indentedFlag) { + increaseIndent(); + } + pushNameGenerationScope(node); + ts.forEach(node.parameters, generateNames); + generateNames(node.body); + emitSignatureHead(node); + if (onEmitNode) { + onEmitNode(4 /* Unspecified */, body, emitBlockCallback); + } + else { + emitBlockFunctionBody(body); + } + popNameGenerationScope(node); + if (indentedFlag) { + decreaseIndent(); + } + } + else { + emitSignatureHead(node); + writeSpace(); + emitExpression(body); + } + } + else { + emitSignatureHead(node); + writeTrailingSemicolon(); + } + } + function emitSignatureHead(node) { + emitTypeParameters(node, node.typeParameters); + emitParameters(node, node.parameters); + emitTypeAnnotation(node.type); + } + function shouldEmitBlockFunctionBodyOnSingleLine(body) { + // We must emit a function body as a single-line body in the following case: + // * The body has NodeEmitFlags.SingleLine specified. + // We must emit a function body as a multi-line body in the following cases: + // * The body is explicitly marked as multi-line. + // * A non-synthesized body's start and end position are on different lines. + // * Any statement in the body starts on a new line. + if (ts.getEmitFlags(body) & 1 /* SingleLine */) { + return true; + } + if (body.multiLine) { + return false; + } + if (!ts.nodeIsSynthesized(body) && !ts.rangeIsOnSingleLine(body, currentSourceFile)) { + return false; + } + if (shouldWriteLeadingLineTerminator(body, body.statements, 2 /* PreserveLines */) + || shouldWriteClosingLineTerminator(body, body.statements, 2 /* PreserveLines */)) { + return false; + } + var previousStatement; + for (var _a = 0, _b = body.statements; _a < _b.length; _a++) { + var statement = _b[_a]; + if (shouldWriteSeparatingLineTerminator(previousStatement, statement, 2 /* PreserveLines */)) { + return false; + } + previousStatement = statement; + } + return true; + } + function emitBlockFunctionBody(body) { + writeSpace(); + writePunctuation("{"); + increaseIndent(); + var emitBlockFunctionBody = shouldEmitBlockFunctionBodyOnSingleLine(body) + ? emitBlockFunctionBodyOnSingleLine + : emitBlockFunctionBodyWorker; + if (emitBodyWithDetachedComments) { + emitBodyWithDetachedComments(body, body.statements, emitBlockFunctionBody); + } + else { + emitBlockFunctionBody(body); + } + decreaseIndent(); + writeToken(19 /* CloseBraceToken */, body.statements.end, writePunctuation, body); + } + function emitBlockFunctionBodyOnSingleLine(body) { + emitBlockFunctionBodyWorker(body, /*emitBlockFunctionBodyOnSingleLine*/ true); + } + function emitBlockFunctionBodyWorker(body, emitBlockFunctionBodyOnSingleLine) { + // Emit all the prologue directives (like "use strict"). + var statementOffset = emitPrologueDirectives(body.statements, /*startWithNewLine*/ true); + var pos = writer.getTextPos(); + emitHelpers(body); + if (statementOffset === 0 && pos === writer.getTextPos() && emitBlockFunctionBodyOnSingleLine) { + decreaseIndent(); + emitList(body, body.statements, 768 /* SingleLineFunctionBodyStatements */); + increaseIndent(); + } + else { + emitList(body, body.statements, 1 /* MultiLineFunctionBodyStatements */, statementOffset); + } + } + function emitClassDeclaration(node) { + emitClassDeclarationOrExpression(node); + } + function emitClassDeclarationOrExpression(node) { + ts.forEach(node.members, generateMemberNames); + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + writeKeyword("class"); + if (node.name) { + writeSpace(); + emitIdentifierName(node.name); + } + var indentedFlag = ts.getEmitFlags(node) & 65536 /* Indented */; + if (indentedFlag) { + increaseIndent(); + } + emitTypeParameters(node, node.typeParameters); + emitList(node, node.heritageClauses, 0 /* ClassHeritageClauses */); + writeSpace(); + writePunctuation("{"); + emitList(node, node.members, 129 /* ClassMembers */); + writePunctuation("}"); + if (indentedFlag) { + decreaseIndent(); + } + } + function emitInterfaceDeclaration(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + writeKeyword("interface"); + writeSpace(); + emit(node.name); + emitTypeParameters(node, node.typeParameters); + emitList(node, node.heritageClauses, 512 /* HeritageClauses */); + writeSpace(); + writePunctuation("{"); + emitList(node, node.members, 129 /* InterfaceMembers */); + writePunctuation("}"); + } + function emitTypeAliasDeclaration(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + writeKeyword("type"); + writeSpace(); + emit(node.name); + emitTypeParameters(node, node.typeParameters); + writeSpace(); + writePunctuation("="); + writeSpace(); + emit(node.type); + writeTrailingSemicolon(); + } + function emitEnumDeclaration(node) { + emitModifiers(node, node.modifiers); + writeKeyword("enum"); + writeSpace(); + emit(node.name); + writeSpace(); + writePunctuation("{"); + emitList(node, node.members, 145 /* EnumMembers */); + writePunctuation("}"); + } + function emitModuleDeclaration(node) { + emitModifiers(node, node.modifiers); + if (~node.flags & 512 /* GlobalAugmentation */) { + writeKeyword(node.flags & 16 /* Namespace */ ? "namespace" : "module"); + writeSpace(); + } + emit(node.name); + var body = node.body; + if (!body) + return writeTrailingSemicolon(); + while (body.kind === 244 /* ModuleDeclaration */) { + writePunctuation("."); + emit(body.name); + body = body.body; + } + writeSpace(); + emit(body); + } + function emitModuleBlock(node) { + pushNameGenerationScope(node); + ts.forEach(node.statements, generateNames); + emitBlockStatements(node, /*forceSingleLine*/ isEmptyBlock(node)); + popNameGenerationScope(node); + } + function emitCaseBlock(node) { + emitTokenWithComment(18 /* OpenBraceToken */, node.pos, writePunctuation, node); + emitList(node, node.clauses, 129 /* CaseBlockClauses */); + emitTokenWithComment(19 /* CloseBraceToken */, node.clauses.end, writePunctuation, node, /*indentLeading*/ true); + } + function emitImportEqualsDeclaration(node) { + emitModifiers(node, node.modifiers); + emitTokenWithComment(92 /* ImportKeyword */, node.modifiers ? node.modifiers.end : node.pos, writeKeyword, node); + writeSpace(); + emit(node.name); + writeSpace(); + emitTokenWithComment(59 /* EqualsToken */, node.name.end, writePunctuation, node); + writeSpace(); + emitModuleReference(node.moduleReference); + writeTrailingSemicolon(); + } + function emitModuleReference(node) { + if (node.kind === 72 /* Identifier */) { + emitExpression(node); + } + else { + emit(node); + } + } + function emitImportDeclaration(node) { + emitModifiers(node, node.modifiers); + emitTokenWithComment(92 /* ImportKeyword */, node.modifiers ? node.modifiers.end : node.pos, writeKeyword, node); + writeSpace(); + if (node.importClause) { + emit(node.importClause); + writeSpace(); + emitTokenWithComment(144 /* FromKeyword */, node.importClause.end, writeKeyword, node); + writeSpace(); + } + emitExpression(node.moduleSpecifier); + writeTrailingSemicolon(); + } + function emitImportClause(node) { + emit(node.name); + if (node.name && node.namedBindings) { + emitTokenWithComment(27 /* CommaToken */, node.name.end, writePunctuation, node); + writeSpace(); + } + emit(node.namedBindings); + } + function emitNamespaceImport(node) { + var asPos = emitTokenWithComment(40 /* AsteriskToken */, node.pos, writePunctuation, node); + writeSpace(); + emitTokenWithComment(119 /* AsKeyword */, asPos, writeKeyword, node); + writeSpace(); + emit(node.name); + } + function emitNamedImports(node) { + emitNamedImportsOrExports(node); + } + function emitImportSpecifier(node) { + emitImportOrExportSpecifier(node); + } + function emitExportAssignment(node) { + var nextPos = emitTokenWithComment(85 /* ExportKeyword */, node.pos, writeKeyword, node); + writeSpace(); + if (node.isExportEquals) { + emitTokenWithComment(59 /* EqualsToken */, nextPos, writeOperator, node); + } + else { + emitTokenWithComment(80 /* DefaultKeyword */, nextPos, writeKeyword, node); + } + writeSpace(); + emitExpression(node.expression); + writeTrailingSemicolon(); + } + function emitExportDeclaration(node) { + var nextPos = emitTokenWithComment(85 /* ExportKeyword */, node.pos, writeKeyword, node); + writeSpace(); + if (node.exportClause) { + emit(node.exportClause); + } + else { + nextPos = emitTokenWithComment(40 /* AsteriskToken */, nextPos, writePunctuation, node); + } + if (node.moduleSpecifier) { + writeSpace(); + var fromPos = node.exportClause ? node.exportClause.end : nextPos; + emitTokenWithComment(144 /* FromKeyword */, fromPos, writeKeyword, node); + writeSpace(); + emitExpression(node.moduleSpecifier); + } + writeTrailingSemicolon(); + } + function emitNamespaceExportDeclaration(node) { + var nextPos = emitTokenWithComment(85 /* ExportKeyword */, node.pos, writeKeyword, node); + writeSpace(); + nextPos = emitTokenWithComment(119 /* AsKeyword */, nextPos, writeKeyword, node); + writeSpace(); + nextPos = emitTokenWithComment(131 /* NamespaceKeyword */, nextPos, writeKeyword, node); + writeSpace(); + emit(node.name); + writeTrailingSemicolon(); + } + function emitNamedExports(node) { + emitNamedImportsOrExports(node); + } + function emitExportSpecifier(node) { + emitImportOrExportSpecifier(node); + } + function emitNamedImportsOrExports(node) { + writePunctuation("{"); + emitList(node, node.elements, 525136 /* NamedImportsOrExportsElements */); + writePunctuation("}"); + } + function emitImportOrExportSpecifier(node) { + if (node.propertyName) { + emit(node.propertyName); + writeSpace(); + emitTokenWithComment(119 /* AsKeyword */, node.propertyName.end, writeKeyword, node); + writeSpace(); + } + emit(node.name); + } + // + // Module references + // + function emitExternalModuleReference(node) { + writeKeyword("require"); + writePunctuation("("); + emitExpression(node.expression); + writePunctuation(")"); + } + // + // JSX + // + function emitJsxElement(node) { + emit(node.openingElement); + emitList(node, node.children, 262144 /* JsxElementOrFragmentChildren */); + emit(node.closingElement); + } + function emitJsxSelfClosingElement(node) { + writePunctuation("<"); + emitJsxTagName(node.tagName); + writeSpace(); + emit(node.attributes); + writePunctuation("/>"); + } + function emitJsxFragment(node) { + emit(node.openingFragment); + emitList(node, node.children, 262144 /* JsxElementOrFragmentChildren */); + emit(node.closingFragment); + } + function emitJsxOpeningElementOrFragment(node) { + writePunctuation("<"); + if (ts.isJsxOpeningElement(node)) { + emitJsxTagName(node.tagName); + if (node.attributes.properties && node.attributes.properties.length > 0) { + writeSpace(); + } + emit(node.attributes); + } + writePunctuation(">"); + } + function emitJsxText(node) { + writer.writeLiteral(getTextOfNode(node, /*includeTrivia*/ true)); + } + function emitJsxClosingElementOrFragment(node) { + writePunctuation(""); + } + function emitJsxAttributes(node) { + emitList(node, node.properties, 262656 /* JsxElementAttributes */); + } + function emitJsxAttribute(node) { + emit(node.name); + emitNodeWithPrefix("=", writePunctuation, node.initializer, emit); // TODO: GH#18217 + } + function emitJsxSpreadAttribute(node) { + writePunctuation("{..."); + emitExpression(node.expression); + writePunctuation("}"); + } + function emitJsxExpression(node) { + if (node.expression) { + writePunctuation("{"); + emit(node.dotDotDotToken); + emitExpression(node.expression); + writePunctuation("}"); + } + } + function emitJsxTagName(node) { + if (node.kind === 72 /* Identifier */) { + emitExpression(node); + } + else { + emit(node); + } + } + // + // Clauses + // + function emitCaseClause(node) { + emitTokenWithComment(74 /* CaseKeyword */, node.pos, writeKeyword, node); + writeSpace(); + emitExpression(node.expression); + emitCaseOrDefaultClauseRest(node, node.statements, node.expression.end); + } + function emitDefaultClause(node) { + var pos = emitTokenWithComment(80 /* DefaultKeyword */, node.pos, writeKeyword, node); + emitCaseOrDefaultClauseRest(node, node.statements, pos); + } + function emitCaseOrDefaultClauseRest(parentNode, statements, colonPos) { + var emitAsSingleStatement = statements.length === 1 && + ( + // treat synthesized nodes as located on the same line for emit purposes + ts.nodeIsSynthesized(parentNode) || + ts.nodeIsSynthesized(statements[0]) || + ts.rangeStartPositionsAreOnSameLine(parentNode, statements[0], currentSourceFile)); + var format = 163969 /* CaseOrDefaultClauseStatements */; + if (emitAsSingleStatement) { + writeToken(57 /* ColonToken */, colonPos, writePunctuation, parentNode); + writeSpace(); + format &= ~(1 /* MultiLine */ | 128 /* Indented */); + } + else { + emitTokenWithComment(57 /* ColonToken */, colonPos, writePunctuation, parentNode); + } + emitList(parentNode, statements, format); + } + function emitHeritageClause(node) { + writeSpace(); + writeTokenText(node.token, writeKeyword); + writeSpace(); + emitList(node, node.types, 528 /* HeritageClauseTypes */); + } + function emitCatchClause(node) { + var openParenPos = emitTokenWithComment(75 /* CatchKeyword */, node.pos, writeKeyword, node); + writeSpace(); + if (node.variableDeclaration) { + emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node); + emit(node.variableDeclaration); + emitTokenWithComment(21 /* CloseParenToken */, node.variableDeclaration.end, writePunctuation, node); + writeSpace(); + } + emit(node.block); + } + // + // Property assignments + // + function emitPropertyAssignment(node) { + emit(node.name); + writePunctuation(":"); + writeSpace(); + // This is to ensure that we emit comment in the following case: + // For example: + // obj = { + // id: /*comment1*/ ()=>void + // } + // "comment1" is not considered to be leading comment for node.initializer + // but rather a trailing comment on the previous node. + var initializer = node.initializer; + if (emitTrailingCommentsOfPosition && (ts.getEmitFlags(initializer) & 512 /* NoLeadingComments */) === 0) { + var commentRange = ts.getCommentRange(initializer); + emitTrailingCommentsOfPosition(commentRange.pos); + } + emitExpression(initializer); + } + function emitShorthandPropertyAssignment(node) { + emit(node.name); + if (node.objectAssignmentInitializer) { + writeSpace(); + writePunctuation("="); + writeSpace(); + emitExpression(node.objectAssignmentInitializer); + } + } + function emitSpreadAssignment(node) { + if (node.expression) { + emitTokenWithComment(25 /* DotDotDotToken */, node.pos, writePunctuation, node); + emitExpression(node.expression); + } + } + // + // Enum + // + function emitEnumMember(node) { + emit(node.name); + emitInitializer(node.initializer, node.name.end, node); + } + // + // JSDoc + // + function emitJSDoc(node) { + write("/**"); + if (node.comment) { + var lines = node.comment.split(/\r\n?|\n/g); + for (var _a = 0, lines_2 = lines; _a < lines_2.length; _a++) { + var line = lines_2[_a]; + writeLine(); + writeSpace(); + writePunctuation("*"); + writeSpace(); + write(line); + } + } + if (node.tags) { + if (node.tags.length === 1 && node.tags[0].kind === 302 /* JSDocTypeTag */ && !node.comment) { + writeSpace(); + emit(node.tags[0]); + } + else { + emitList(node, node.tags, 33 /* JSDocComment */); + } + } + writeSpace(); + write("*/"); + } + function emitJSDocSimpleTypedTag(tag) { + emitJSDocTagName(tag.tagName); + emitJSDocTypeExpression(tag.typeExpression); + emitJSDocComment(tag.comment); + } + function emitJSDocAugmentsTag(tag) { + emitJSDocTagName(tag.tagName); + writeSpace(); + writePunctuation("{"); + emit(tag.class); + writePunctuation("}"); + emitJSDocComment(tag.comment); + } + function emitJSDocTemplateTag(tag) { + emitJSDocTagName(tag.tagName); + emitJSDocTypeExpression(tag.constraint); + writeSpace(); + emitList(tag, tag.typeParameters, 528 /* CommaListElements */); + emitJSDocComment(tag.comment); + } + function emitJSDocTypedefTag(tag) { + emitJSDocTagName(tag.tagName); + if (tag.typeExpression) { + if (tag.typeExpression.kind === 283 /* JSDocTypeExpression */) { + emitJSDocTypeExpression(tag.typeExpression); + } + else { + writeSpace(); + writePunctuation("{"); + write("Object"); + if (tag.typeExpression.isArrayType) { + writePunctuation("["); + writePunctuation("]"); + } + writePunctuation("}"); + } + } + if (tag.fullName) { + writeSpace(); + emit(tag.fullName); + } + emitJSDocComment(tag.comment); + if (tag.typeExpression && tag.typeExpression.kind === 292 /* JSDocTypeLiteral */) { + emitJSDocTypeLiteral(tag.typeExpression); + } + } + function emitJSDocCallbackTag(tag) { + emitJSDocTagName(tag.tagName); + if (tag.name) { + writeSpace(); + emit(tag.name); + } + emitJSDocComment(tag.comment); + emitJSDocSignature(tag.typeExpression); + } + function emitJSDocSimpleTag(tag) { + emitJSDocTagName(tag.tagName); + emitJSDocComment(tag.comment); + } + function emitJSDocTypeLiteral(lit) { + emitList(lit, ts.createNodeArray(lit.jsDocPropertyTags), 33 /* JSDocComment */); + } + function emitJSDocSignature(sig) { + if (sig.typeParameters) { + emitList(sig, ts.createNodeArray(sig.typeParameters), 33 /* JSDocComment */); + } + if (sig.parameters) { + emitList(sig, ts.createNodeArray(sig.parameters), 33 /* JSDocComment */); + } + if (sig.type) { + writeLine(); + writeSpace(); + writePunctuation("*"); + writeSpace(); + emit(sig.type); + } + } + function emitJSDocPropertyLikeTag(param) { + emitJSDocTagName(param.tagName); + emitJSDocTypeExpression(param.typeExpression); + writeSpace(); + if (param.isBracketed) { + writePunctuation("["); + } + emit(param.name); + if (param.isBracketed) { + writePunctuation("]"); + } + emitJSDocComment(param.comment); + } + function emitJSDocTagName(tagName) { + writePunctuation("@"); + emit(tagName); + } + function emitJSDocComment(comment) { + if (comment) { + writeSpace(); + write(comment); + } + } + function emitJSDocTypeExpression(typeExpression) { + if (typeExpression) { + writeSpace(); + writePunctuation("{"); + emit(typeExpression.type); + writePunctuation("}"); + } + } + // + // Top-level nodes + // + function emitSourceFile(node) { + writeLine(); + var statements = node.statements; + if (emitBodyWithDetachedComments) { + // Emit detached comment if there are no prologue directives or if the first node is synthesized. + // The synthesized node will have no leading comment so some comments may be missed. + var shouldEmitDetachedComment = statements.length === 0 || + !ts.isPrologueDirective(statements[0]) || + ts.nodeIsSynthesized(statements[0]); + if (shouldEmitDetachedComment) { + emitBodyWithDetachedComments(node, statements, emitSourceFileWorker); + return; + } + } + emitSourceFileWorker(node); + } + function emitSyntheticTripleSlashReferencesIfNeeded(node) { + emitTripleSlashDirectives(!!node.hasNoDefaultLib, node.syntheticFileReferences || [], node.syntheticTypeReferences || [], node.syntheticLibReferences || []); + } + function emitTripleSlashDirectivesIfNeeded(node) { + if (node.isDeclarationFile) + emitTripleSlashDirectives(node.hasNoDefaultLib, node.referencedFiles, node.typeReferenceDirectives, node.libReferenceDirectives); + } + function emitTripleSlashDirectives(hasNoDefaultLib, files, types, libs) { + if (hasNoDefaultLib) { + writeComment("/// "); + writeLine(); + } + if (currentSourceFile && currentSourceFile.moduleName) { + writeComment("/// "); + writeLine(); + } + if (currentSourceFile && currentSourceFile.amdDependencies) { + for (var _a = 0, _b = currentSourceFile.amdDependencies; _a < _b.length; _a++) { + var dep = _b[_a]; + if (dep.name) { + writeComment("/// "); + } + else { + writeComment("/// "); + } + writeLine(); + } + } + for (var _c = 0, files_1 = files; _c < files_1.length; _c++) { + var directive = files_1[_c]; + writeComment("/// "); + writeLine(); + } + for (var _d = 0, types_18 = types; _d < types_18.length; _d++) { + var directive = types_18[_d]; + writeComment("/// "); + writeLine(); + } + for (var _e = 0, libs_1 = libs; _e < libs_1.length; _e++) { + var directive = libs_1[_e]; + writeComment("/// "); + writeLine(); + } + } + function emitSourceFileWorker(node) { + var statements = node.statements; + pushNameGenerationScope(node); + ts.forEach(node.statements, generateNames); + emitHelpers(node); + var index = ts.findIndex(statements, function (statement) { return !ts.isPrologueDirective(statement); }); + emitTripleSlashDirectivesIfNeeded(node); + emitList(node, statements, 1 /* MultiLine */, index === -1 ? statements.length : index); + popNameGenerationScope(node); + } + // Transformation nodes + function emitPartiallyEmittedExpression(node) { + emitExpression(node.expression); + } + function emitCommaList(node) { + emitExpressionList(node, node.elements, 528 /* CommaListElements */); + } + /** + * Emits any prologue directives at the start of a Statement list, returning the + * number of prologue directives written to the output. + */ + function emitPrologueDirectives(statements, startWithNewLine, seenPrologueDirectives) { + for (var i = 0; i < statements.length; i++) { + var statement = statements[i]; + if (ts.isPrologueDirective(statement)) { + var shouldEmitPrologueDirective = seenPrologueDirectives ? !seenPrologueDirectives.has(statement.expression.text) : true; + if (shouldEmitPrologueDirective) { + if (startWithNewLine || i > 0) { + writeLine(); + } + emit(statement); + if (seenPrologueDirectives) { + seenPrologueDirectives.set(statement.expression.text, true); + } + } + } + else { + // return index of the first non prologue directive + return i; + } + } + return statements.length; + } + function emitPrologueDirectivesIfNeeded(sourceFileOrBundle) { + if (ts.isSourceFile(sourceFileOrBundle)) { + setSourceFile(sourceFileOrBundle); + emitPrologueDirectives(sourceFileOrBundle.statements); + } + else { + var seenPrologueDirectives = ts.createMap(); + for (var _a = 0, _b = sourceFileOrBundle.sourceFiles; _a < _b.length; _a++) { + var sourceFile = _b[_a]; + setSourceFile(sourceFile); + emitPrologueDirectives(sourceFile.statements, /*startWithNewLine*/ true, seenPrologueDirectives); + } + setSourceFile(undefined); + } + } + function emitShebangIfNeeded(sourceFileOrBundle) { + if (ts.isSourceFile(sourceFileOrBundle)) { + var shebang = ts.getShebang(sourceFileOrBundle.text); + if (shebang) { + writeComment(shebang); + writeLine(); + return true; + } + } + else { + for (var _a = 0, _b = sourceFileOrBundle.sourceFiles; _a < _b.length; _a++) { + var sourceFile = _b[_a]; + // Emit only the first encountered shebang + if (emitShebangIfNeeded(sourceFile)) { + break; + } + } + } + } + // + // Helpers + // + function emitNodeWithWriter(node, writer) { + if (!node) + return; + var savedWrite = write; + write = writer; + emit(node); + write = savedWrite; + } + function emitModifiers(node, modifiers) { + if (modifiers && modifiers.length) { + emitList(node, modifiers, 262656 /* Modifiers */); + writeSpace(); + } + } + function emitTypeAnnotation(node) { + if (node) { + writePunctuation(":"); + writeSpace(); + emit(node); + } + } + function emitInitializer(node, equalCommentStartPos, container) { + if (node) { + writeSpace(); + emitTokenWithComment(59 /* EqualsToken */, equalCommentStartPos, writeOperator, container); + writeSpace(); + emitExpression(node); + } + } + function emitNodeWithPrefix(prefix, prefixWriter, node, emit) { + if (node) { + prefixWriter(prefix); + emit(node); + } + } + function emitWithLeadingSpace(node) { + if (node) { + writeSpace(); + emit(node); + } + } + function emitExpressionWithLeadingSpace(node) { + if (node) { + writeSpace(); + emitExpression(node); + } + } + function emitWithTrailingSpace(node) { + if (node) { + emit(node); + writeSpace(); + } + } + function emitEmbeddedStatement(parent, node) { + if (ts.isBlock(node) || ts.getEmitFlags(parent) & 1 /* SingleLine */) { + writeSpace(); + emit(node); + } + else { + writeLine(); + increaseIndent(); + if (ts.isEmptyStatement(node)) { + var pipelinePhase = getPipelinePhase(0 /* Notification */, node); + pipelinePhase(5 /* EmbeddedStatement */, node); + } + else { + emit(node); + } + decreaseIndent(); + } + } + function emitDecorators(parentNode, decorators) { + emitList(parentNode, decorators, 49153 /* Decorators */); + } + function emitTypeArguments(parentNode, typeArguments) { + emitList(parentNode, typeArguments, 53776 /* TypeArguments */); + } + function emitTypeParameters(parentNode, typeParameters) { + if (ts.isFunctionLike(parentNode) && parentNode.typeArguments) { // Quick info uses type arguments in place of type parameters on instantiated signatures + return emitTypeArguments(parentNode, parentNode.typeArguments); + } + emitList(parentNode, typeParameters, 53776 /* TypeParameters */); + } + function emitParameters(parentNode, parameters) { + emitList(parentNode, parameters, 2576 /* Parameters */); + } + function canEmitSimpleArrowHead(parentNode, parameters) { + var parameter = ts.singleOrUndefined(parameters); + return parameter + && parameter.pos === parentNode.pos // may not have parsed tokens between parent and parameter + && ts.isArrowFunction(parentNode) // only arrow functions may have simple arrow head + && !parentNode.type // arrow function may not have return type annotation + && !ts.some(parentNode.decorators) // parent may not have decorators + && !ts.some(parentNode.modifiers) // parent may not have modifiers + && !ts.some(parentNode.typeParameters) // parent may not have type parameters + && !ts.some(parameter.decorators) // parameter may not have decorators + && !ts.some(parameter.modifiers) // parameter may not have modifiers + && !parameter.dotDotDotToken // parameter may not be rest + && !parameter.questionToken // parameter may not be optional + && !parameter.type // parameter may not have a type annotation + && !parameter.initializer // parameter may not have an initializer + && ts.isIdentifier(parameter.name); // parameter name must be identifier + } + function emitParametersForArrow(parentNode, parameters) { + if (canEmitSimpleArrowHead(parentNode, parameters)) { + emitList(parentNode, parameters, 2576 /* Parameters */ & ~2048 /* Parenthesis */); + } + else { + emitParameters(parentNode, parameters); + } + } + function emitParametersForIndexSignature(parentNode, parameters) { + emitList(parentNode, parameters, 8848 /* IndexSignatureParameters */); + } + function emitList(parentNode, children, format, start, count) { + emitNodeList(emit, parentNode, children, format, start, count); + } + function emitExpressionList(parentNode, children, format, start, count) { + emitNodeList(emitExpression, parentNode, children, format, start, count); // TODO: GH#18217 + } + function writeDelimiter(format) { + switch (format & 60 /* DelimitersMask */) { + case 0 /* None */: + break; + case 16 /* CommaDelimited */: + writePunctuation(","); + break; + case 4 /* BarDelimited */: + writeSpace(); + writePunctuation("|"); + break; + case 32 /* AsteriskDelimited */: + writeSpace(); + writePunctuation("*"); + writeSpace(); + break; + case 8 /* AmpersandDelimited */: + writeSpace(); + writePunctuation("&"); + break; + } + } + function emitNodeList(emit, parentNode, children, format, start, count) { + if (start === void 0) { start = 0; } + if (count === void 0) { count = children ? children.length - start : 0; } + var isUndefined = children === undefined; + if (isUndefined && format & 16384 /* OptionalIfUndefined */) { + return; + } + var isEmpty = children === undefined || start >= children.length || count === 0; + if (isEmpty && format & 32768 /* OptionalIfEmpty */) { + if (onBeforeEmitNodeArray) { + onBeforeEmitNodeArray(children); + } + if (onAfterEmitNodeArray) { + onAfterEmitNodeArray(children); + } + return; + } + if (format & 15360 /* BracketsMask */) { + writePunctuation(getOpeningBracket(format)); + if (isEmpty && !isUndefined) { + // TODO: GH#18217 + emitTrailingCommentsOfPosition(children.pos, /*prefixSpace*/ true); // Emit comments within empty bracketed lists + } + } + if (onBeforeEmitNodeArray) { + onBeforeEmitNodeArray(children); + } + if (isEmpty) { + // Write a line terminator if the parent node was multi-line + if (format & 1 /* MultiLine */) { + writeLine(); + } + else if (format & 256 /* SpaceBetweenBraces */ && !(format & 524288 /* NoSpaceIfEmpty */)) { + writeSpace(); + } + } + else { + // Write the opening line terminator or leading whitespace. + var mayEmitInterveningComments = (format & 262144 /* NoInterveningComments */) === 0; + var shouldEmitInterveningComments = mayEmitInterveningComments; + if (shouldWriteLeadingLineTerminator(parentNode, children, format)) { // TODO: GH#18217 + writeLine(); + shouldEmitInterveningComments = false; + } + else if (format & 256 /* SpaceBetweenBraces */) { + writeSpace(); + } + // Increase the indent, if requested. + if (format & 128 /* Indented */) { + increaseIndent(); + } + // Emit each child. + var previousSibling = void 0; + var shouldDecreaseIndentAfterEmit = false; + for (var i = 0; i < count; i++) { + var child = children[start + i]; + // Write the delimiter if this is not the first node. + if (format & 32 /* AsteriskDelimited */) { + // always write JSDoc in the format "\n *" + writeLine(); + writeDelimiter(format); + } + else if (previousSibling) { + // i.e + // function commentedParameters( + // /* Parameter a */ + // a + // /* End of parameter a */ -> this comment isn't considered to be trailing comment of parameter "a" due to newline + // , + if (format & 60 /* DelimitersMask */ && previousSibling.end !== parentNode.end) { + emitLeadingCommentsOfPosition(previousSibling.end); + } + writeDelimiter(format); + // Write either a line terminator or whitespace to separate the elements. + if (shouldWriteSeparatingLineTerminator(previousSibling, child, format)) { + // If a synthesized node in a single-line list starts on a new + // line, we should increase the indent. + if ((format & (3 /* LinesMask */ | 128 /* Indented */)) === 0 /* SingleLine */) { + increaseIndent(); + shouldDecreaseIndentAfterEmit = true; + } + writeLine(); + shouldEmitInterveningComments = false; + } + else if (previousSibling && format & 512 /* SpaceBetweenSiblings */) { + writeSpace(); + } + } + // Emit this child. + if (shouldEmitInterveningComments) { + if (emitTrailingCommentsOfPosition) { + var commentRange = ts.getCommentRange(child); + emitTrailingCommentsOfPosition(commentRange.pos); + } + } + else { + shouldEmitInterveningComments = mayEmitInterveningComments; + } + emit(child); + if (shouldDecreaseIndentAfterEmit) { + decreaseIndent(); + shouldDecreaseIndentAfterEmit = false; + } + previousSibling = child; + } + // Write a trailing comma, if requested. + var hasTrailingComma = (format & 64 /* AllowTrailingComma */) && children.hasTrailingComma; + if (format & 16 /* CommaDelimited */ && hasTrailingComma) { + writePunctuation(","); + } + // Emit any trailing comment of the last element in the list + // i.e + // var array = [... + // 2 + // /* end of element 2 */ + // ]; + if (previousSibling && format & 60 /* DelimitersMask */ && previousSibling.end !== parentNode.end && !(ts.getEmitFlags(previousSibling) & 1024 /* NoTrailingComments */)) { + emitLeadingCommentsOfPosition(previousSibling.end); + } + // Decrease the indent, if requested. + if (format & 128 /* Indented */) { + decreaseIndent(); + } + // Write the closing line terminator or closing whitespace. + if (shouldWriteClosingLineTerminator(parentNode, children, format)) { + writeLine(); + } + else if (format & 256 /* SpaceBetweenBraces */) { + writeSpace(); + } + } + if (onAfterEmitNodeArray) { + onAfterEmitNodeArray(children); + } + if (format & 15360 /* BracketsMask */) { + if (isEmpty && !isUndefined) { + // TODO: GH#18217 + emitLeadingCommentsOfPosition(children.end); // Emit leading comments within empty lists + } + writePunctuation(getClosingBracket(format)); + } + } + // Writers + function writeLiteral(s) { + writer.writeLiteral(s); + } + function writeStringLiteral(s) { + writer.writeStringLiteral(s); + } + function writeBase(s) { + writer.write(s); + } + function writeSymbol(s, sym) { + writer.writeSymbol(s, sym); + } + function writePunctuation(s) { + writer.writePunctuation(s); + } + function writeTrailingSemicolon() { + writer.writeTrailingSemicolon(";"); + } + function writeKeyword(s) { + writer.writeKeyword(s); + } + function writeOperator(s) { + writer.writeOperator(s); + } + function writeParameter(s) { + writer.writeParameter(s); + } + function writeComment(s) { + writer.writeComment(s); + } + function writeSpace() { + writer.writeSpace(" "); + } + function writeProperty(s) { + writer.writeProperty(s); + } + function writeLine() { + writer.writeLine(); + } + function increaseIndent() { + writer.increaseIndent(); + } + function decreaseIndent() { + writer.decreaseIndent(); + } + function writeToken(token, pos, writer, contextNode) { + return !sourceMapsDisabled + ? emitTokenWithSourceMap(contextNode, token, writer, pos, writeTokenText) + : writeTokenText(token, writer, pos); + } + function writeTokenNode(node, writer) { + if (onBeforeEmitToken) { + onBeforeEmitToken(node); + } + writer(ts.tokenToString(node.kind)); + if (onAfterEmitToken) { + onAfterEmitToken(node); + } + } + function writeTokenText(token, writer, pos) { + var tokenString = ts.tokenToString(token); + writer(tokenString); + return pos < 0 ? pos : pos + tokenString.length; + } + function writeLineOrSpace(node) { + if (ts.getEmitFlags(node) & 1 /* SingleLine */) { + writeSpace(); + } + else { + writeLine(); + } + } + function writeLines(text) { + var lines = text.split(/\r\n?|\n/g); + var indentation = ts.guessIndentation(lines); + for (var _a = 0, lines_3 = lines; _a < lines_3.length; _a++) { + var lineText = lines_3[_a]; + var line = indentation ? lineText.slice(indentation) : lineText; + if (line.length) { + writeLine(); + write(line); + writer.rawWrite(newLine); + } + } + } + function increaseIndentIf(value, writeSpaceIfNotIndenting) { + if (value) { + increaseIndent(); + writeLine(); + } + else if (writeSpaceIfNotIndenting) { + writeSpace(); + } + } + // Helper function to decrease the indent if we previously indented. Allows multiple + // previous indent values to be considered at a time. This also allows caller to just + // call this once, passing in all their appropriate indent values, instead of needing + // to call this helper function multiple times. + function decreaseIndentIf(value1, value2) { + if (value1) { + decreaseIndent(); + } + if (value2) { + decreaseIndent(); + } + } + function shouldWriteLeadingLineTerminator(parentNode, children, format) { + if (format & 1 /* MultiLine */) { + return true; + } + if (format & 2 /* PreserveLines */) { + if (format & 65536 /* PreferNewLine */) { + return true; + } + var firstChild = children[0]; + if (firstChild === undefined) { + return !ts.rangeIsOnSingleLine(parentNode, currentSourceFile); + } + else if (ts.positionIsSynthesized(parentNode.pos) || ts.nodeIsSynthesized(firstChild)) { + return synthesizedNodeStartsOnNewLine(firstChild, format); + } + else { + return !ts.rangeStartPositionsAreOnSameLine(parentNode, firstChild, currentSourceFile); + } + } + else { + return false; + } + } + function shouldWriteSeparatingLineTerminator(previousNode, nextNode, format) { + if (format & 1 /* MultiLine */) { + return true; + } + else if (format & 2 /* PreserveLines */) { + if (previousNode === undefined || nextNode === undefined) { + return false; + } + else if (ts.nodeIsSynthesized(previousNode) || ts.nodeIsSynthesized(nextNode)) { + return synthesizedNodeStartsOnNewLine(previousNode, format) || synthesizedNodeStartsOnNewLine(nextNode, format); + } + else { + return !ts.rangeEndIsOnSameLineAsRangeStart(previousNode, nextNode, currentSourceFile); + } + } + else { + return ts.getStartsOnNewLine(nextNode); + } + } + function shouldWriteClosingLineTerminator(parentNode, children, format) { + if (format & 1 /* MultiLine */) { + return (format & 131072 /* NoTrailingNewLine */) === 0; + } + else if (format & 2 /* PreserveLines */) { + if (format & 65536 /* PreferNewLine */) { + return true; + } + var lastChild = ts.lastOrUndefined(children); + if (lastChild === undefined) { + return !ts.rangeIsOnSingleLine(parentNode, currentSourceFile); + } + else if (ts.positionIsSynthesized(parentNode.pos) || ts.nodeIsSynthesized(lastChild)) { + return synthesizedNodeStartsOnNewLine(lastChild, format); + } + else { + return !ts.rangeEndPositionsAreOnSameLine(parentNode, lastChild, currentSourceFile); + } + } + else { + return false; + } + } + function synthesizedNodeStartsOnNewLine(node, format) { + if (ts.nodeIsSynthesized(node)) { + var startsOnNewLine = ts.getStartsOnNewLine(node); + if (startsOnNewLine === undefined) { + return (format & 65536 /* PreferNewLine */) !== 0; + } + return startsOnNewLine; + } + return (format & 65536 /* PreferNewLine */) !== 0; + } + function needsIndentation(parent, node1, node2) { + parent = skipSynthesizedParentheses(parent); + node1 = skipSynthesizedParentheses(node1); + node2 = skipSynthesizedParentheses(node2); + // Always use a newline for synthesized code if the synthesizer desires it. + if (ts.getStartsOnNewLine(node2)) { + return true; + } + return !ts.nodeIsSynthesized(parent) + && !ts.nodeIsSynthesized(node1) + && !ts.nodeIsSynthesized(node2) + && !ts.rangeEndIsOnSameLineAsRangeStart(node1, node2, currentSourceFile); + } + function isEmptyBlock(block) { + return block.statements.length === 0 + && ts.rangeEndIsOnSameLineAsRangeStart(block, block, currentSourceFile); + } + function skipSynthesizedParentheses(node) { + while (node.kind === 195 /* ParenthesizedExpression */ && ts.nodeIsSynthesized(node)) { + node = node.expression; + } + return node; + } + function getTextOfNode(node, includeTrivia) { + if (ts.isGeneratedIdentifier(node)) { + return generateName(node); + } + else if (ts.isIdentifier(node) && (ts.nodeIsSynthesized(node) || !node.parent || !currentSourceFile || (node.parent && currentSourceFile && ts.getSourceFileOfNode(node) !== ts.getOriginalNode(currentSourceFile)))) { + return ts.idText(node); + } + else if (node.kind === 10 /* StringLiteral */ && node.textSourceNode) { + return getTextOfNode(node.textSourceNode, includeTrivia); + } + else if (ts.isLiteralExpression(node) && (ts.nodeIsSynthesized(node) || !node.parent)) { + return node.text; + } + return ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node, includeTrivia); + } + function getLiteralTextOfNode(node, neverAsciiEscape) { + if (node.kind === 10 /* StringLiteral */ && node.textSourceNode) { + var textSourceNode = node.textSourceNode; + if (ts.isIdentifier(textSourceNode)) { + return neverAsciiEscape || (ts.getEmitFlags(node) & 16777216 /* NoAsciiEscaping */) ? + "\"" + ts.escapeString(getTextOfNode(textSourceNode)) + "\"" : + "\"" + ts.escapeNonAsciiString(getTextOfNode(textSourceNode)) + "\""; + } + else { + return getLiteralTextOfNode(textSourceNode, neverAsciiEscape); + } + } + return ts.getLiteralText(node, currentSourceFile, neverAsciiEscape); + } + /** + * Push a new name generation scope. + */ + function pushNameGenerationScope(node) { + if (node && ts.getEmitFlags(node) & 524288 /* ReuseTempVariableScope */) { + return; + } + tempFlagsStack.push(tempFlags); + tempFlags = 0; + reservedNamesStack.push(reservedNames); + } + /** + * Pop the current name generation scope. + */ + function popNameGenerationScope(node) { + if (node && ts.getEmitFlags(node) & 524288 /* ReuseTempVariableScope */) { + return; + } + tempFlags = tempFlagsStack.pop(); + reservedNames = reservedNamesStack.pop(); + } + function reserveNameInNestedScopes(name) { + if (!reservedNames || reservedNames === ts.lastOrUndefined(reservedNamesStack)) { + reservedNames = ts.createMap(); + } + reservedNames.set(name, true); + } + function generateNames(node) { + if (!node) + return; + switch (node.kind) { + case 218 /* Block */: + ts.forEach(node.statements, generateNames); + break; + case 233 /* LabeledStatement */: + case 231 /* WithStatement */: + case 223 /* DoStatement */: + case 224 /* WhileStatement */: + generateNames(node.statement); + break; + case 222 /* IfStatement */: + generateNames(node.thenStatement); + generateNames(node.elseStatement); + break; + case 225 /* ForStatement */: + case 227 /* ForOfStatement */: + case 226 /* ForInStatement */: + generateNames(node.initializer); + generateNames(node.statement); + break; + case 232 /* SwitchStatement */: + generateNames(node.caseBlock); + break; + case 246 /* CaseBlock */: + ts.forEach(node.clauses, generateNames); + break; + case 271 /* CaseClause */: + case 272 /* DefaultClause */: + ts.forEach(node.statements, generateNames); + break; + case 235 /* TryStatement */: + generateNames(node.tryBlock); + generateNames(node.catchClause); + generateNames(node.finallyBlock); + break; + case 274 /* CatchClause */: + generateNames(node.variableDeclaration); + generateNames(node.block); + break; + case 219 /* VariableStatement */: + generateNames(node.declarationList); + break; + case 238 /* VariableDeclarationList */: + ts.forEach(node.declarations, generateNames); + break; + case 237 /* VariableDeclaration */: + case 151 /* Parameter */: + case 186 /* BindingElement */: + case 240 /* ClassDeclaration */: + generateNameIfNeeded(node.name); + break; + case 239 /* FunctionDeclaration */: + generateNameIfNeeded(node.name); + if (ts.getEmitFlags(node) & 524288 /* ReuseTempVariableScope */) { + ts.forEach(node.parameters, generateNames); + generateNames(node.body); + } + break; + case 184 /* ObjectBindingPattern */: + case 185 /* ArrayBindingPattern */: + ts.forEach(node.elements, generateNames); + break; + case 249 /* ImportDeclaration */: + generateNames(node.importClause); + break; + case 250 /* ImportClause */: + generateNameIfNeeded(node.name); + generateNames(node.namedBindings); + break; + case 251 /* NamespaceImport */: + generateNameIfNeeded(node.name); + break; + case 252 /* NamedImports */: + ts.forEach(node.elements, generateNames); + break; + case 253 /* ImportSpecifier */: + generateNameIfNeeded(node.propertyName || node.name); + break; + } + } + function generateMemberNames(node) { + if (!node) + return; + switch (node.kind) { + case 275 /* PropertyAssignment */: + case 276 /* ShorthandPropertyAssignment */: + case 154 /* PropertyDeclaration */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + generateNameIfNeeded(node.name); + break; + } + } + function generateNameIfNeeded(name) { + if (name) { + if (ts.isGeneratedIdentifier(name)) { + generateName(name); + } + else if (ts.isBindingPattern(name)) { + generateNames(name); + } + } + } + /** + * Generate the text for a generated identifier. + */ + function generateName(name) { + if ((name.autoGenerateFlags & 7 /* KindMask */) === 4 /* Node */) { + // Node names generate unique names based on their original node + // and are cached based on that node's id. + return generateNameCached(getNodeForGeneratedName(name), name.autoGenerateFlags); + } + else { + // Auto, Loop, and Unique names are cached based on their unique + // autoGenerateId. + var autoGenerateId = name.autoGenerateId; + return autoGeneratedIdToGeneratedName[autoGenerateId] || (autoGeneratedIdToGeneratedName[autoGenerateId] = makeName(name)); + } + } + function generateNameCached(node, flags) { + var nodeId = ts.getNodeId(node); + return nodeIdToGeneratedName[nodeId] || (nodeIdToGeneratedName[nodeId] = generateNameForNode(node, flags)); + } + /** + * Returns a value indicating whether a name is unique globally, within the current file, + * or within the NameGenerator. + */ + function isUniqueName(name) { + return isFileLevelUniqueName(name) + && !generatedNames.has(name) + && !(reservedNames && reservedNames.has(name)); + } + /** + * Returns a value indicating whether a name is unique globally or within the current file. + */ + function isFileLevelUniqueName(name) { + return currentSourceFile ? ts.isFileLevelUniqueName(currentSourceFile, name, hasGlobalName) : true; + } + /** + * Returns a value indicating whether a name is unique within a container. + */ + function isUniqueLocalName(name, container) { + for (var node = container; ts.isNodeDescendantOf(node, container); node = node.nextContainer) { + if (node.locals) { + var local = node.locals.get(ts.escapeLeadingUnderscores(name)); + // We conservatively include alias symbols to cover cases where they're emitted as locals + if (local && local.flags & (67220415 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */)) { + return false; + } + } + } + return true; + } + /** + * Return the next available name in the pattern _a ... _z, _0, _1, ... + * TempFlags._i or TempFlags._n may be used to express a preference for that dedicated name. + * Note that names generated by makeTempVariableName and makeUniqueName will never conflict. + */ + function makeTempVariableName(flags, reservedInNestedScopes) { + if (flags && !(tempFlags & flags)) { + var name = flags === 268435456 /* _i */ ? "_i" : "_n"; + if (isUniqueName(name)) { + tempFlags |= flags; + if (reservedInNestedScopes) { + reserveNameInNestedScopes(name); + } + return name; + } + } + while (true) { + var count = tempFlags & 268435455 /* CountMask */; + tempFlags++; + // Skip over 'i' and 'n' + if (count !== 8 && count !== 13) { + var name = count < 26 + ? "_" + String.fromCharCode(97 /* a */ + count) + : "_" + (count - 26); + if (isUniqueName(name)) { + if (reservedInNestedScopes) { + reserveNameInNestedScopes(name); + } + return name; + } + } + } + } + /** + * Generate a name that is unique within the current file and doesn't conflict with any names + * in global scope. The name is formed by adding an '_n' suffix to the specified base name, + * where n is a positive integer. Note that names generated by makeTempVariableName and + * makeUniqueName are guaranteed to never conflict. + * If `optimistic` is set, the first instance will use 'baseName' verbatim instead of 'baseName_1' + */ + function makeUniqueName(baseName, checkFn, optimistic, scoped) { + if (checkFn === void 0) { checkFn = isUniqueName; } + if (optimistic) { + if (checkFn(baseName)) { + if (scoped) { + reserveNameInNestedScopes(baseName); + } + else { + generatedNames.set(baseName, true); + } + return baseName; + } + } + // Find the first unique 'name_n', where n is a positive number + if (baseName.charCodeAt(baseName.length - 1) !== 95 /* _ */) { + baseName += "_"; + } + var i = 1; + while (true) { + var generatedName = baseName + i; + if (checkFn(generatedName)) { + if (scoped) { + reserveNameInNestedScopes(generatedName); + } + else { + generatedNames.set(generatedName, true); + } + return generatedName; + } + i++; + } + } + function makeFileLevelOptimisticUniqueName(name) { + return makeUniqueName(name, isFileLevelUniqueName, /*optimistic*/ true); + } + /** + * Generates a unique name for a ModuleDeclaration or EnumDeclaration. + */ + function generateNameForModuleOrEnum(node) { + var name = getTextOfNode(node.name); + // Use module/enum name itself if it is unique, otherwise make a unique variation + return isUniqueLocalName(name, node) ? name : makeUniqueName(name); + } + /** + * Generates a unique name for an ImportDeclaration or ExportDeclaration. + */ + function generateNameForImportOrExportDeclaration(node) { + var expr = ts.getExternalModuleName(node); // TODO: GH#18217 + var baseName = ts.isStringLiteral(expr) ? + ts.makeIdentifierFromModuleName(expr.text) : "module"; + return makeUniqueName(baseName); + } + /** + * Generates a unique name for a default export. + */ + function generateNameForExportDefault() { + return makeUniqueName("default"); + } + /** + * Generates a unique name for a class expression. + */ + function generateNameForClassExpression() { + return makeUniqueName("class"); + } + function generateNameForMethodOrAccessor(node) { + if (ts.isIdentifier(node.name)) { + return generateNameCached(node.name); + } + return makeTempVariableName(0 /* Auto */); + } + /** + * Generates a unique name from a node. + */ + function generateNameForNode(node, flags) { + switch (node.kind) { + case 72 /* Identifier */: + return makeUniqueName(getTextOfNode(node), isUniqueName, !!(flags & 16 /* Optimistic */), !!(flags & 8 /* ReservedInNestedScopes */)); + case 244 /* ModuleDeclaration */: + case 243 /* EnumDeclaration */: + return generateNameForModuleOrEnum(node); + case 249 /* ImportDeclaration */: + case 255 /* ExportDeclaration */: + return generateNameForImportOrExportDeclaration(node); + case 239 /* FunctionDeclaration */: + case 240 /* ClassDeclaration */: + case 254 /* ExportAssignment */: + return generateNameForExportDefault(); + case 209 /* ClassExpression */: + return generateNameForClassExpression(); + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + return generateNameForMethodOrAccessor(node); + default: + return makeTempVariableName(0 /* Auto */); + } + } + /** + * Generates a unique identifier for a node. + */ + function makeName(name) { + switch (name.autoGenerateFlags & 7 /* KindMask */) { + case 1 /* Auto */: + return makeTempVariableName(0 /* Auto */, !!(name.autoGenerateFlags & 8 /* ReservedInNestedScopes */)); + case 2 /* Loop */: + return makeTempVariableName(268435456 /* _i */, !!(name.autoGenerateFlags & 8 /* ReservedInNestedScopes */)); + case 3 /* Unique */: + return makeUniqueName(ts.idText(name), (name.autoGenerateFlags & 32 /* FileLevel */) ? isFileLevelUniqueName : isUniqueName, !!(name.autoGenerateFlags & 16 /* Optimistic */), !!(name.autoGenerateFlags & 8 /* ReservedInNestedScopes */)); + } + return ts.Debug.fail("Unsupported GeneratedIdentifierKind."); + } + /** + * Gets the node from which a name should be generated. + */ + function getNodeForGeneratedName(name) { + var autoGenerateId = name.autoGenerateId; + var node = name; + var original = node.original; + while (original) { + node = original; + // if "node" is a different generated name (having a different + // "autoGenerateId"), use it and stop traversing. + if (ts.isIdentifier(node) + && !!(node.autoGenerateFlags & 4 /* Node */) + && node.autoGenerateId !== autoGenerateId) { + break; + } + original = node.original; + } + // otherwise, return the original node for the source; + return node; + } + // Comments + function pipelineEmitWithComments(hint, node) { + enterComment(); + hasWrittenComment = false; + var emitFlags = ts.getEmitFlags(node); + var _a = ts.getCommentRange(node), pos = _a.pos, end = _a.end; + var isEmittedNode = node.kind !== 307 /* NotEmittedStatement */; + // We have to explicitly check that the node is JsxText because if the compilerOptions.jsx is "preserve" we will not do any transformation. + // It is expensive to walk entire tree just to set one kind of node to have no comments. + var skipLeadingComments = pos < 0 || (emitFlags & 512 /* NoLeadingComments */) !== 0 || node.kind === 11 /* JsxText */; + var skipTrailingComments = end < 0 || (emitFlags & 1024 /* NoTrailingComments */) !== 0 || node.kind === 11 /* JsxText */; + // Save current container state on the stack. + var savedContainerPos = containerPos; + var savedContainerEnd = containerEnd; + var savedDeclarationListContainerEnd = declarationListContainerEnd; + if ((pos > 0 || end > 0) && pos !== end) { + // Emit leading comments if the position is not synthesized and the node + // has not opted out from emitting leading comments. + if (!skipLeadingComments) { + emitLeadingComments(pos, isEmittedNode); + } + if (!skipLeadingComments || (pos >= 0 && (emitFlags & 512 /* NoLeadingComments */) !== 0)) { + // Advance the container position if comments get emitted or if they've been disabled explicitly using NoLeadingComments. + containerPos = pos; + } + if (!skipTrailingComments || (end >= 0 && (emitFlags & 1024 /* NoTrailingComments */) !== 0)) { + // As above. + containerEnd = end; + // To avoid invalid comment emit in a down-level binding pattern, we + // keep track of the last declaration list container's end + if (node.kind === 238 /* VariableDeclarationList */) { + declarationListContainerEnd = end; + } + } + } + ts.forEach(ts.getSyntheticLeadingComments(node), emitLeadingSynthesizedComment); + exitComment(); + var pipelinePhase = getNextPipelinePhase(2 /* Comments */, node); + if (emitFlags & 2048 /* NoNestedComments */) { + commentsDisabled = true; + pipelinePhase(hint, node); + commentsDisabled = false; + } + else { + pipelinePhase(hint, node); + } + enterComment(); + ts.forEach(ts.getSyntheticTrailingComments(node), emitTrailingSynthesizedComment); + if ((pos > 0 || end > 0) && pos !== end) { + // Restore previous container state. + containerPos = savedContainerPos; + containerEnd = savedContainerEnd; + declarationListContainerEnd = savedDeclarationListContainerEnd; + // Emit trailing comments if the position is not synthesized and the node + // has not opted out from emitting leading comments and is an emitted node. + if (!skipTrailingComments && isEmittedNode) { + emitTrailingComments(end); + } + } + exitComment(); + } + function emitLeadingSynthesizedComment(comment) { + if (comment.kind === 2 /* SingleLineCommentTrivia */) { + writer.writeLine(); + } + writeSynthesizedComment(comment); + if (comment.hasTrailingNewLine || comment.kind === 2 /* SingleLineCommentTrivia */) { + writer.writeLine(); + } + else { + writer.writeSpace(" "); + } + } + function emitTrailingSynthesizedComment(comment) { + if (!writer.isAtStartOfLine()) { + writer.writeSpace(" "); + } + writeSynthesizedComment(comment); + if (comment.hasTrailingNewLine) { + writer.writeLine(); + } + } + function writeSynthesizedComment(comment) { + var text = formatSynthesizedComment(comment); + var lineMap = comment.kind === 3 /* MultiLineCommentTrivia */ ? ts.computeLineStarts(text) : undefined; + ts.writeCommentRange(text, lineMap, writer, 0, text.length, newLine); + } + function formatSynthesizedComment(comment) { + return comment.kind === 3 /* MultiLineCommentTrivia */ + ? "/*" + comment.text + "*/" + : "//" + comment.text; + } + function emitBodyWithDetachedComments(node, detachedRange, emitCallback) { + enterComment(); + var pos = detachedRange.pos, end = detachedRange.end; + var emitFlags = ts.getEmitFlags(node); + var skipLeadingComments = pos < 0 || (emitFlags & 512 /* NoLeadingComments */) !== 0; + var skipTrailingComments = commentsDisabled || end < 0 || (emitFlags & 1024 /* NoTrailingComments */) !== 0; + if (!skipLeadingComments) { + emitDetachedCommentsAndUpdateCommentsInfo(detachedRange); + } + exitComment(); + if (emitFlags & 2048 /* NoNestedComments */ && !commentsDisabled) { + commentsDisabled = true; + emitCallback(node); + commentsDisabled = false; + } + else { + emitCallback(node); + } + enterComment(); + if (!skipTrailingComments) { + emitLeadingComments(detachedRange.end, /*isEmittedNode*/ true); + if (hasWrittenComment && !writer.isAtStartOfLine()) { + writer.writeLine(); + } + } + exitComment(); + } + function emitLeadingComments(pos, isEmittedNode) { + hasWrittenComment = false; + if (isEmittedNode) { + forEachLeadingCommentToEmit(pos, emitLeadingComment); + } + else if (pos === 0) { + // If the node will not be emitted in JS, remove all the comments(normal, pinned and ///) associated with the node, + // unless it is a triple slash comment at the top of the file. + // For Example: + // /// + // declare var x; + // /// + // interface F {} + // The first /// will NOT be removed while the second one will be removed even though both node will not be emitted + forEachLeadingCommentToEmit(pos, emitTripleSlashLeadingComment); + } + } + function emitTripleSlashLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos) { + if (isTripleSlashComment(commentPos, commentEnd)) { + emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos); + } + } + function shouldWriteComment(text, pos) { + if (printerOptions.onlyPrintJsDocStyle) { + return (ts.isJSDocLikeText(text, pos) || ts.isPinnedComment(text, pos)); + } + return true; + } + function emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos) { + if (!shouldWriteComment(currentSourceFile.text, commentPos)) + return; + if (!hasWrittenComment) { + ts.emitNewLineBeforeLeadingCommentOfPosition(getCurrentLineMap(), writer, rangePos, commentPos); + hasWrittenComment = true; + } + // Leading comments are emitted at /*leading comment1 */space/*leading comment*/space + emitPos(commentPos); + ts.writeCommentRange(currentSourceFile.text, getCurrentLineMap(), writer, commentPos, commentEnd, newLine); + emitPos(commentEnd); + if (hasTrailingNewLine) { + writer.writeLine(); + } + else if (kind === 3 /* MultiLineCommentTrivia */) { + writer.writeSpace(" "); + } + } + function emitLeadingCommentsOfPosition(pos) { + if (commentsDisabled || pos === -1) { + return; + } + emitLeadingComments(pos, /*isEmittedNode*/ true); + } + function emitTrailingComments(pos) { + forEachTrailingCommentToEmit(pos, emitTrailingComment); + } + function emitTrailingComment(commentPos, commentEnd, _kind, hasTrailingNewLine) { + if (!shouldWriteComment(currentSourceFile.text, commentPos)) + return; + // trailing comments are emitted at space/*trailing comment1 */space/*trailing comment2*/ + if (!writer.isAtStartOfLine()) { + writer.writeSpace(" "); + } + emitPos(commentPos); + ts.writeCommentRange(currentSourceFile.text, getCurrentLineMap(), writer, commentPos, commentEnd, newLine); + emitPos(commentEnd); + if (hasTrailingNewLine) { + writer.writeLine(); + } + } + function emitTrailingCommentsOfPosition(pos, prefixSpace) { + if (commentsDisabled) { + return; + } + enterComment(); + forEachTrailingCommentToEmit(pos, prefixSpace ? emitTrailingComment : emitTrailingCommentOfPosition); + exitComment(); + } + function emitTrailingCommentOfPosition(commentPos, commentEnd, _kind, hasTrailingNewLine) { + // trailing comments of a position are emitted at /*trailing comment1 */space/*trailing comment*/space + emitPos(commentPos); + ts.writeCommentRange(currentSourceFile.text, getCurrentLineMap(), writer, commentPos, commentEnd, newLine); + emitPos(commentEnd); + if (hasTrailingNewLine) { + writer.writeLine(); + } + else { + writer.writeSpace(" "); + } + } + function forEachLeadingCommentToEmit(pos, cb) { + // Emit the leading comments only if the container's pos doesn't match because the container should take care of emitting these comments + if (currentSourceFile && (containerPos === -1 || pos !== containerPos)) { + if (hasDetachedComments(pos)) { + forEachLeadingCommentWithoutDetachedComments(cb); + } + else { + ts.forEachLeadingCommentRange(currentSourceFile.text, pos, cb, /*state*/ pos); + } + } + } + function forEachTrailingCommentToEmit(end, cb) { + // Emit the trailing comments only if the container's end doesn't match because the container should take care of emitting these comments + if (currentSourceFile && (containerEnd === -1 || (end !== containerEnd && end !== declarationListContainerEnd))) { + ts.forEachTrailingCommentRange(currentSourceFile.text, end, cb); + } + } + function hasDetachedComments(pos) { + return detachedCommentsInfo !== undefined && ts.last(detachedCommentsInfo).nodePos === pos; + } + function forEachLeadingCommentWithoutDetachedComments(cb) { + // get the leading comments from detachedPos + var pos = ts.last(detachedCommentsInfo).detachedCommentEndPos; + if (detachedCommentsInfo.length - 1) { + detachedCommentsInfo.pop(); + } + else { + detachedCommentsInfo = undefined; + } + ts.forEachLeadingCommentRange(currentSourceFile.text, pos, cb, /*state*/ pos); + } + function emitDetachedCommentsAndUpdateCommentsInfo(range) { + var currentDetachedCommentInfo = ts.emitDetachedComments(currentSourceFile.text, getCurrentLineMap(), writer, emitComment, range, newLine, commentsDisabled); + if (currentDetachedCommentInfo) { + if (detachedCommentsInfo) { + detachedCommentsInfo.push(currentDetachedCommentInfo); + } + else { + detachedCommentsInfo = [currentDetachedCommentInfo]; + } + } + } + function emitComment(text, lineMap, writer, commentPos, commentEnd, newLine) { + if (!shouldWriteComment(currentSourceFile.text, commentPos)) + return; + emitPos(commentPos); + ts.writeCommentRange(text, lineMap, writer, commentPos, commentEnd, newLine); + emitPos(commentEnd); + } + /** + * Determine if the given comment is a triple-slash + * + * @return true if the comment is a triple-slash comment else false + */ + function isTripleSlashComment(commentPos, commentEnd) { + return ts.isRecognizedTripleSlashComment(currentSourceFile.text, commentPos, commentEnd); + } + // Source Maps + function pipelineEmitWithSourceMap(hint, node) { + var pipelinePhase = getNextPipelinePhase(3 /* SourceMaps */, node); + if (ts.isUnparsedSource(node) && node.sourceMapText !== undefined) { + var parsed = ts.tryParseRawSourceMap(node.sourceMapText); + if (parsed) { + sourceMapGenerator.appendSourceMap(writer.getLine(), writer.getColumn(), parsed, node.sourceMapPath); + } + pipelinePhase(hint, node); + } + else { + var _a = ts.getSourceMapRange(node), pos = _a.pos, end = _a.end, _b = _a.source, source = _b === void 0 ? sourceMapSource : _b; + var emitFlags = ts.getEmitFlags(node); + if (node.kind !== 307 /* NotEmittedStatement */ + && (emitFlags & 16 /* NoLeadingSourceMap */) === 0 + && pos >= 0) { + emitSourcePos(source, skipSourceTrivia(source, pos)); + } + if (emitFlags & 64 /* NoNestedSourceMaps */) { + sourceMapsDisabled = true; + pipelinePhase(hint, node); + sourceMapsDisabled = false; + } + else { + pipelinePhase(hint, node); + } + if (node.kind !== 307 /* NotEmittedStatement */ + && (emitFlags & 32 /* NoTrailingSourceMap */) === 0 + && end >= 0) { + emitSourcePos(source, end); + } + } + } + /** + * Skips trivia such as comments and white-space that can optionally overriden by the source map source + */ + function skipSourceTrivia(source, pos) { + return source.skipTrivia ? source.skipTrivia(pos) : ts.skipTrivia(sourceMapSource.text, pos); + } + /** + * Emits a mapping. + * + * If the position is synthetic (undefined or a negative value), no mapping will be + * created. + * + * @param pos The position. + */ + function emitPos(pos) { + if (sourceMapsDisabled || ts.positionIsSynthesized(pos) || isJsonSourceMapSource(sourceMapSource)) { + return; + } + var _a = ts.getLineAndCharacterOfPosition(currentSourceFile, pos), sourceLine = _a.line, sourceCharacter = _a.character; + sourceMapGenerator.addMapping(writer.getLine(), writer.getColumn(), sourceMapSourceIndex, sourceLine, sourceCharacter, + /*nameIndex*/ undefined); + } + function emitSourcePos(source, pos) { + if (source !== sourceMapSource) { + var savedSourceMapSource = sourceMapSource; + setSourceMapSource(source); + emitPos(pos); + setSourceMapSource(savedSourceMapSource); + } + else { + emitPos(pos); + } + } + /** + * Emits a token of a node with possible leading and trailing source maps. + * + * @param node The node containing the token. + * @param token The token to emit. + * @param tokenStartPos The start pos of the token. + * @param emitCallback The callback used to emit the token. + */ + function emitTokenWithSourceMap(node, token, writer, tokenPos, emitCallback) { + if (sourceMapsDisabled || node && ts.isInJsonFile(node)) { + return emitCallback(token, writer, tokenPos); + } + var emitNode = node && node.emitNode; + var emitFlags = emitNode && emitNode.flags || 0 /* None */; + var range = emitNode && emitNode.tokenSourceMapRanges && emitNode.tokenSourceMapRanges[token]; + var source = range && range.source || sourceMapSource; + tokenPos = skipSourceTrivia(source, range ? range.pos : tokenPos); + if ((emitFlags & 128 /* NoTokenLeadingSourceMaps */) === 0 && tokenPos >= 0) { + emitSourcePos(source, tokenPos); + } + tokenPos = emitCallback(token, writer, tokenPos); + if (range) + tokenPos = range.end; + if ((emitFlags & 256 /* NoTokenTrailingSourceMaps */) === 0 && tokenPos >= 0) { + emitSourcePos(source, tokenPos); + } + return tokenPos; + } + function setSourceMapSource(source) { + if (sourceMapsDisabled) { + return; + } + sourceMapSource = source; + if (isJsonSourceMapSource(source)) { + return; + } + sourceMapSourceIndex = sourceMapGenerator.addSource(source.fileName); + if (printerOptions.inlineSources) { + sourceMapGenerator.setSourceContent(sourceMapSourceIndex, source.text); + } + } + function isJsonSourceMapSource(sourceFile) { + return ts.fileExtensionIs(sourceFile.fileName, ".json" /* Json */); + } + } + ts.createPrinter = createPrinter; + function createBracketsMap() { + var brackets = []; + brackets[1024 /* Braces */] = ["{", "}"]; + brackets[2048 /* Parenthesis */] = ["(", ")"]; + brackets[4096 /* AngleBrackets */] = ["<", ">"]; + brackets[8192 /* SquareBrackets */] = ["[", "]"]; + return brackets; + } + function getOpeningBracket(format) { + return brackets[format & 15360 /* BracketsMask */][0]; + } + function getClosingBracket(format) { + return brackets[format & 15360 /* BracketsMask */][1]; + } + // Flags enum to track count of temp variables and a few dedicated names + var TempFlags; + (function (TempFlags) { + TempFlags[TempFlags["Auto"] = 0] = "Auto"; + TempFlags[TempFlags["CountMask"] = 268435455] = "CountMask"; + TempFlags[TempFlags["_i"] = 268435456] = "_i"; + })(TempFlags || (TempFlags = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + function createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensitiveFileNames) { + if (!host.getDirectories || !host.readDirectory) { + return undefined; + } + var cachedReadDirectoryResult = ts.createMap(); + var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); + return { + useCaseSensitiveFileNames: useCaseSensitiveFileNames, + fileExists: fileExists, + readFile: function (path, encoding) { return host.readFile(path, encoding); }, + directoryExists: host.directoryExists && directoryExists, + getDirectories: getDirectories, + readDirectory: readDirectory, + createDirectory: host.createDirectory && createDirectory, + writeFile: host.writeFile && writeFile, + addOrDeleteFileOrDirectory: addOrDeleteFileOrDirectory, + addOrDeleteFile: addOrDeleteFile, + clearCache: clearCache + }; + function toPath(fileName) { + return ts.toPath(fileName, currentDirectory, getCanonicalFileName); + } + function getCachedFileSystemEntries(rootDirPath) { + return cachedReadDirectoryResult.get(ts.ensureTrailingDirectorySeparator(rootDirPath)); + } + function getCachedFileSystemEntriesForBaseDir(path) { + return getCachedFileSystemEntries(ts.getDirectoryPath(path)); + } + function getBaseNameOfFileName(fileName) { + return ts.getBaseFileName(ts.normalizePath(fileName)); + } + function createCachedFileSystemEntries(rootDir, rootDirPath) { + var resultFromHost = { + files: ts.map(host.readDirectory(rootDir, /*extensions*/ undefined, /*exclude*/ undefined, /*include*/ ["*.*"]), getBaseNameOfFileName) || [], + directories: host.getDirectories(rootDir) || [] + }; + cachedReadDirectoryResult.set(ts.ensureTrailingDirectorySeparator(rootDirPath), resultFromHost); + return resultFromHost; + } + /** + * If the readDirectory result was already cached, it returns that + * Otherwise gets result from host and caches it. + * The host request is done under try catch block to avoid caching incorrect result + */ + function tryReadDirectory(rootDir, rootDirPath) { + rootDirPath = ts.ensureTrailingDirectorySeparator(rootDirPath); + var cachedResult = getCachedFileSystemEntries(rootDirPath); + if (cachedResult) { + return cachedResult; + } + try { + return createCachedFileSystemEntries(rootDir, rootDirPath); + } + catch (_e) { + // If there is exception to read directories, dont cache the result and direct the calls to host + ts.Debug.assert(!cachedReadDirectoryResult.has(ts.ensureTrailingDirectorySeparator(rootDirPath))); + return undefined; + } + } + function fileNameEqual(name1, name2) { + return getCanonicalFileName(name1) === getCanonicalFileName(name2); + } + function hasEntry(entries, name) { + return ts.some(entries, function (file) { return fileNameEqual(file, name); }); + } + function updateFileSystemEntry(entries, baseName, isValid) { + if (hasEntry(entries, baseName)) { + if (!isValid) { + return ts.filterMutate(entries, function (entry) { return !fileNameEqual(entry, baseName); }); + } + } + else if (isValid) { + return entries.push(baseName); + } + } + function writeFile(fileName, data, writeByteOrderMark) { + var path = toPath(fileName); + var result = getCachedFileSystemEntriesForBaseDir(path); + if (result) { + updateFilesOfFileSystemEntry(result, getBaseNameOfFileName(fileName), /*fileExists*/ true); + } + return host.writeFile(fileName, data, writeByteOrderMark); + } + function fileExists(fileName) { + var path = toPath(fileName); + var result = getCachedFileSystemEntriesForBaseDir(path); + return result && hasEntry(result.files, getBaseNameOfFileName(fileName)) || + host.fileExists(fileName); + } + function directoryExists(dirPath) { + var path = toPath(dirPath); + return cachedReadDirectoryResult.has(ts.ensureTrailingDirectorySeparator(path)) || host.directoryExists(dirPath); + } + function createDirectory(dirPath) { + var path = toPath(dirPath); + var result = getCachedFileSystemEntriesForBaseDir(path); + var baseFileName = getBaseNameOfFileName(dirPath); + if (result) { + updateFileSystemEntry(result.directories, baseFileName, /*isValid*/ true); + } + host.createDirectory(dirPath); + } + function getDirectories(rootDir) { + var rootDirPath = toPath(rootDir); + var result = tryReadDirectory(rootDir, rootDirPath); + if (result) { + return result.directories.slice(); + } + return host.getDirectories(rootDir); + } + function readDirectory(rootDir, extensions, excludes, includes, depth) { + var rootDirPath = toPath(rootDir); + var result = tryReadDirectory(rootDir, rootDirPath); + if (result) { + return ts.matchFiles(rootDir, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries); + } + return host.readDirectory(rootDir, extensions, excludes, includes, depth); + function getFileSystemEntries(dir) { + var path = toPath(dir); + if (path === rootDirPath) { + return result; + } + return tryReadDirectory(dir, path) || ts.emptyFileSystemEntries; + } + } + function addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath) { + var existingResult = getCachedFileSystemEntries(fileOrDirectoryPath); + if (existingResult) { + // Just clear the cache for now + // For now just clear the cache, since this could mean that multiple level entries might need to be re-evaluated + clearCache(); + return undefined; + } + var parentResult = getCachedFileSystemEntriesForBaseDir(fileOrDirectoryPath); + if (!parentResult) { + return undefined; + } + // This was earlier a file (hence not in cached directory contents) + // or we never cached the directory containing it + if (!host.directoryExists) { + // Since host doesnt support directory exists, clear the cache as otherwise it might not be same + clearCache(); + return undefined; + } + var baseName = getBaseNameOfFileName(fileOrDirectory); + var fsQueryResult = { + fileExists: host.fileExists(fileOrDirectoryPath), + directoryExists: host.directoryExists(fileOrDirectoryPath) + }; + if (fsQueryResult.directoryExists || hasEntry(parentResult.directories, baseName)) { + // Folder added or removed, clear the cache instead of updating the folder and its structure + clearCache(); + } + else { + // No need to update the directory structure, just files + updateFilesOfFileSystemEntry(parentResult, baseName, fsQueryResult.fileExists); + } + return fsQueryResult; + } + function addOrDeleteFile(fileName, filePath, eventKind) { + if (eventKind === ts.FileWatcherEventKind.Changed) { + return; + } + var parentResult = getCachedFileSystemEntriesForBaseDir(filePath); + if (parentResult) { + updateFilesOfFileSystemEntry(parentResult, getBaseNameOfFileName(fileName), eventKind === ts.FileWatcherEventKind.Created); + } + } + function updateFilesOfFileSystemEntry(parentResult, baseName, fileExists) { + updateFileSystemEntry(parentResult.files, baseName, fileExists); + } + function clearCache() { + cachedReadDirectoryResult.clear(); + } + } + ts.createCachedDirectoryStructureHost = createCachedDirectoryStructureHost; + var ConfigFileProgramReloadLevel; + (function (ConfigFileProgramReloadLevel) { + ConfigFileProgramReloadLevel[ConfigFileProgramReloadLevel["None"] = 0] = "None"; + /** Update the file name list from the disk */ + ConfigFileProgramReloadLevel[ConfigFileProgramReloadLevel["Partial"] = 1] = "Partial"; + /** Reload completely by re-reading contents of config file from disk and updating program */ + ConfigFileProgramReloadLevel[ConfigFileProgramReloadLevel["Full"] = 2] = "Full"; + })(ConfigFileProgramReloadLevel = ts.ConfigFileProgramReloadLevel || (ts.ConfigFileProgramReloadLevel = {})); + /** + * Updates the existing missing file watches with the new set of missing files after new program is created + */ + function updateMissingFilePathsWatch(program, missingFileWatches, createMissingFileWatch) { + var missingFilePaths = program.getMissingFilePaths(); + var newMissingFilePathMap = ts.arrayToSet(missingFilePaths); + // Update the missing file paths watcher + ts.mutateMap(missingFileWatches, newMissingFilePathMap, { + // Watch the missing files + createNewValue: createMissingFileWatch, + // Files that are no longer missing (e.g. because they are no longer required) + // should no longer be watched. + onDeleteValue: ts.closeFileWatcher + }); + } + ts.updateMissingFilePathsWatch = updateMissingFilePathsWatch; + /** + * Updates the existing wild card directory watches with the new set of wild card directories from the config file + * after new program is created because the config file was reloaded or program was created first time from the config file + * Note that there is no need to call this function when the program is updated with additional files without reloading config files, + * as wildcard directories wont change unless reloading config file + */ + function updateWatchingWildcardDirectories(existingWatchedForWildcards, wildcardDirectories, watchDirectory) { + ts.mutateMap(existingWatchedForWildcards, wildcardDirectories, { + // Create new watch and recursive info + createNewValue: createWildcardDirectoryWatcher, + // Close existing watch thats not needed any more + onDeleteValue: closeFileWatcherOf, + // Close existing watch that doesnt match in the flags + onExistingValue: updateWildcardDirectoryWatcher + }); + function createWildcardDirectoryWatcher(directory, flags) { + // Create new watch and recursive info + return { + watcher: watchDirectory(directory, flags), + flags: flags + }; + } + function updateWildcardDirectoryWatcher(existingWatcher, flags, directory) { + // Watcher needs to be updated if the recursive flags dont match + if (existingWatcher.flags === flags) { + return; + } + existingWatcher.watcher.close(); + existingWatchedForWildcards.set(directory, createWildcardDirectoryWatcher(directory, flags)); + } + } + ts.updateWatchingWildcardDirectories = updateWatchingWildcardDirectories; + function isEmittedFileOfProgram(program, file) { + if (!program) { + return false; + } + return program.isEmittedFile(file); + } + ts.isEmittedFileOfProgram = isEmittedFileOfProgram; + var WatchLogLevel; + (function (WatchLogLevel) { + WatchLogLevel[WatchLogLevel["None"] = 0] = "None"; + WatchLogLevel[WatchLogLevel["TriggerOnly"] = 1] = "TriggerOnly"; + WatchLogLevel[WatchLogLevel["Verbose"] = 2] = "Verbose"; + })(WatchLogLevel = ts.WatchLogLevel || (ts.WatchLogLevel = {})); + function getWatchFactory(watchLogLevel, log, getDetailWatchInfo) { + return getWatchFactoryWith(watchLogLevel, log, getDetailWatchInfo, watchFile, watchDirectory); + } + ts.getWatchFactory = getWatchFactory; + function getWatchFactoryWith(watchLogLevel, log, getDetailWatchInfo, watchFile, watchDirectory) { + var createFileWatcher = getCreateFileWatcher(watchLogLevel, watchFile); + var createFilePathWatcher = watchLogLevel === WatchLogLevel.None ? watchFilePath : createFileWatcher; + var createDirectoryWatcher = getCreateFileWatcher(watchLogLevel, watchDirectory); + return { + watchFile: function (host, file, callback, pollingInterval, detailInfo1, detailInfo2) { + return createFileWatcher(host, file, callback, pollingInterval, /*passThrough*/ undefined, detailInfo1, detailInfo2, watchFile, log, "FileWatcher", getDetailWatchInfo); + }, + watchFilePath: function (host, file, callback, pollingInterval, path, detailInfo1, detailInfo2) { + return createFilePathWatcher(host, file, callback, pollingInterval, path, detailInfo1, detailInfo2, watchFile, log, "FileWatcher", getDetailWatchInfo); + }, + watchDirectory: function (host, directory, callback, flags, detailInfo1, detailInfo2) { + return createDirectoryWatcher(host, directory, callback, flags, /*passThrough*/ undefined, detailInfo1, detailInfo2, watchDirectory, log, "DirectoryWatcher", getDetailWatchInfo); + } + }; + function watchFilePath(host, file, callback, pollingInterval, path) { + return watchFile(host, file, function (fileName, eventKind) { return callback(fileName, eventKind, path); }, pollingInterval); + } + } + function watchFile(host, file, callback, pollingInterval) { + return host.watchFile(file, callback, pollingInterval); + } + function watchDirectory(host, directory, callback, flags) { + return host.watchDirectory(directory, callback, (flags & 1 /* Recursive */) !== 0); + } + function getCreateFileWatcher(watchLogLevel, addWatch) { + switch (watchLogLevel) { + case WatchLogLevel.None: + return addWatch; + case WatchLogLevel.TriggerOnly: + return createFileWatcherWithTriggerLogging; + case WatchLogLevel.Verbose: + return addWatch === watchDirectory ? createDirectoryWatcherWithLogging : createFileWatcherWithLogging; + } + } + function createFileWatcherWithLogging(host, file, cb, flags, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo) { + log(watchCaption + ":: Added:: " + getWatchInfo(file, flags, detailInfo1, detailInfo2, getDetailWatchInfo)); + var watcher = createFileWatcherWithTriggerLogging(host, file, cb, flags, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo); + return { + close: function () { + log(watchCaption + ":: Close:: " + getWatchInfo(file, flags, detailInfo1, detailInfo2, getDetailWatchInfo)); + watcher.close(); + } + }; + } + function createDirectoryWatcherWithLogging(host, file, cb, flags, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo) { + var watchInfo = watchCaption + ":: Added:: " + getWatchInfo(file, flags, detailInfo1, detailInfo2, getDetailWatchInfo); + log(watchInfo); + var start = ts.timestamp(); + var watcher = createFileWatcherWithTriggerLogging(host, file, cb, flags, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo); + var elapsed = ts.timestamp() - start; + log("Elapsed:: " + elapsed + "ms " + watchInfo); + return { + close: function () { + var watchInfo = watchCaption + ":: Close:: " + getWatchInfo(file, flags, detailInfo1, detailInfo2, getDetailWatchInfo); + log(watchInfo); + var start = ts.timestamp(); + watcher.close(); + var elapsed = ts.timestamp() - start; + log("Elapsed:: " + elapsed + "ms " + watchInfo); + } + }; + } + function createFileWatcherWithTriggerLogging(host, file, cb, flags, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo) { + return addWatch(host, file, function (fileName, cbOptional) { + var triggerredInfo = watchCaption + ":: Triggered with " + fileName + " " + (cbOptional !== undefined ? cbOptional : "") + ":: " + getWatchInfo(file, flags, detailInfo1, detailInfo2, getDetailWatchInfo); + log(triggerredInfo); + var start = ts.timestamp(); + cb(fileName, cbOptional, passThrough); + var elapsed = ts.timestamp() - start; + log("Elapsed:: " + elapsed + "ms " + triggerredInfo); + }, flags); + } + function getWatchInfo(file, flags, detailInfo1, detailInfo2, getDetailWatchInfo) { + return "WatchInfo: " + file + " " + flags + " " + (getDetailWatchInfo ? getDetailWatchInfo(detailInfo1, detailInfo2) : detailInfo1); + } + function closeFileWatcherOf(objWithWatcher) { + objWithWatcher.watcher.close(); + } + ts.closeFileWatcherOf = closeFileWatcherOf; +})(ts || (ts = {})); +var ts; +(function (ts) { + var ignoreDiagnosticCommentRegEx = /(^\s*$)|(^\s*\/\/\/?\s*(@ts-ignore)?)/; + function findConfigFile(searchPath, fileExists, configName) { + if (configName === void 0) { configName = "tsconfig.json"; } + return ts.forEachAncestorDirectory(searchPath, function (ancestor) { + var fileName = ts.combinePaths(ancestor, configName); + return fileExists(fileName) ? fileName : undefined; + }); + } + ts.findConfigFile = findConfigFile; + function resolveTripleslashReference(moduleName, containingFile) { + var basePath = ts.getDirectoryPath(containingFile); + var referencedFileName = ts.isRootedDiskPath(moduleName) ? moduleName : ts.combinePaths(basePath, moduleName); + return ts.normalizePath(referencedFileName); + } + ts.resolveTripleslashReference = resolveTripleslashReference; + /* @internal */ + function computeCommonSourceDirectoryOfFilenames(fileNames, currentDirectory, getCanonicalFileName) { + var commonPathComponents; + var failed = ts.forEach(fileNames, function (sourceFile) { + // Each file contributes into common source file path + var sourcePathComponents = ts.getNormalizedPathComponents(sourceFile, currentDirectory); + sourcePathComponents.pop(); // The base file name is not part of the common directory path + if (!commonPathComponents) { + // first file + commonPathComponents = sourcePathComponents; + return; + } + var n = Math.min(commonPathComponents.length, sourcePathComponents.length); + for (var i = 0; i < n; i++) { + if (getCanonicalFileName(commonPathComponents[i]) !== getCanonicalFileName(sourcePathComponents[i])) { + if (i === 0) { + // Failed to find any common path component + return true; + } + // New common path found that is 0 -> i-1 + commonPathComponents.length = i; + break; + } + } + // If the sourcePathComponents was shorter than the commonPathComponents, truncate to the sourcePathComponents + if (sourcePathComponents.length < commonPathComponents.length) { + commonPathComponents.length = sourcePathComponents.length; + } + }); + // A common path can not be found when paths span multiple drives on windows, for example + if (failed) { + return ""; + } + if (!commonPathComponents) { // Can happen when all input files are .d.ts files + return currentDirectory; + } + return ts.getPathFromPathComponents(commonPathComponents); + } + ts.computeCommonSourceDirectoryOfFilenames = computeCommonSourceDirectoryOfFilenames; + function createCompilerHost(options, setParentNodes) { + return createCompilerHostWorker(options, setParentNodes); + } + ts.createCompilerHost = createCompilerHost; + /*@internal*/ + // TODO(shkamat): update this after reworking ts build API + function createCompilerHostWorker(options, setParentNodes, system) { + if (system === void 0) { system = ts.sys; } + var existingDirectories = ts.createMap(); + function getCanonicalFileName(fileName) { + // if underlying system can distinguish between two files whose names differs only in cases then file name already in canonical form. + // otherwise use toLowerCase as a canonical form. + return system.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); + } + function getSourceFile(fileName, languageVersion, onError) { + var text; + try { + ts.performance.mark("beforeIORead"); + text = compilerHost.readFile(fileName); + ts.performance.mark("afterIORead"); + ts.performance.measure("I/O Read", "beforeIORead", "afterIORead"); + } + catch (e) { + if (onError) { + onError(e.message); + } + text = ""; + } + return text !== undefined ? ts.createSourceFile(fileName, text, languageVersion, setParentNodes) : undefined; + } + function directoryExists(directoryPath) { + if (existingDirectories.has(directoryPath)) { + return true; + } + if (system.directoryExists(directoryPath)) { + existingDirectories.set(directoryPath, true); + return true; + } + return false; + } + function ensureDirectoriesExist(directoryPath) { + if (directoryPath.length > ts.getRootLength(directoryPath) && !directoryExists(directoryPath)) { + var parentDirectory = ts.getDirectoryPath(directoryPath); + ensureDirectoriesExist(parentDirectory); + if (compilerHost.createDirectory) { + compilerHost.createDirectory(directoryPath); + } + else { + system.createDirectory(directoryPath); + } + } + } + var outputFingerprints; + function writeFileIfUpdated(fileName, data, writeByteOrderMark) { + if (!outputFingerprints) { + outputFingerprints = ts.createMap(); + } + var hash = system.createHash(data); // TODO: GH#18217 + var mtimeBefore = system.getModifiedTime(fileName); // TODO: GH#18217 + if (mtimeBefore) { + var fingerprint = outputFingerprints.get(fileName); + // If output has not been changed, and the file has no external modification + if (fingerprint && + fingerprint.byteOrderMark === writeByteOrderMark && + fingerprint.hash === hash && + fingerprint.mtime.getTime() === mtimeBefore.getTime()) { + return; + } + } + system.writeFile(fileName, data, writeByteOrderMark); + var mtimeAfter = system.getModifiedTime(fileName) || ts.missingFileModifiedTime; // TODO: GH#18217 + outputFingerprints.set(fileName, { + hash: hash, + byteOrderMark: writeByteOrderMark, + mtime: mtimeAfter + }); + } + function writeFile(fileName, data, writeByteOrderMark, onError) { + try { + ts.performance.mark("beforeIOWrite"); + ensureDirectoriesExist(ts.getDirectoryPath(ts.normalizePath(fileName))); + if (ts.isWatchSet(options) && system.createHash && system.getModifiedTime) { + writeFileIfUpdated(fileName, data, writeByteOrderMark); + } + else { + system.writeFile(fileName, data, writeByteOrderMark); + } + ts.performance.mark("afterIOWrite"); + ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite"); + } + catch (e) { + if (onError) { + onError(e.message); + } + } + } + function getDefaultLibLocation() { + return ts.getDirectoryPath(ts.normalizePath(system.getExecutingFilePath())); + } + var newLine = ts.getNewLineCharacter(options, function () { return system.newLine; }); + var realpath = system.realpath && (function (path) { return system.realpath(path); }); + var compilerHost = { + getSourceFile: getSourceFile, + getDefaultLibLocation: getDefaultLibLocation, + getDefaultLibFileName: function (options) { return ts.combinePaths(getDefaultLibLocation(), ts.getDefaultLibFileName(options)); }, + writeFile: writeFile, + getCurrentDirectory: ts.memoize(function () { return system.getCurrentDirectory(); }), + useCaseSensitiveFileNames: function () { return system.useCaseSensitiveFileNames; }, + getCanonicalFileName: getCanonicalFileName, + getNewLine: function () { return newLine; }, + fileExists: function (fileName) { return system.fileExists(fileName); }, + readFile: function (fileName) { return system.readFile(fileName); }, + trace: function (s) { return system.write(s + newLine); }, + directoryExists: function (directoryName) { return system.directoryExists(directoryName); }, + getEnvironmentVariable: function (name) { return system.getEnvironmentVariable ? system.getEnvironmentVariable(name) : ""; }, + getDirectories: function (path) { return system.getDirectories(path); }, + realpath: realpath, + readDirectory: function (path, extensions, include, exclude, depth) { return system.readDirectory(path, extensions, include, exclude, depth); }, + createDirectory: function (d) { return system.createDirectory(d); } + }; + return compilerHost; + } + ts.createCompilerHostWorker = createCompilerHostWorker; + /*@internal*/ + function changeCompilerHostToUseCache(host, toPath, useCacheForSourceFile) { + var originalReadFile = host.readFile; + var originalFileExists = host.fileExists; + var originalDirectoryExists = host.directoryExists; + var originalCreateDirectory = host.createDirectory; + var originalWriteFile = host.writeFile; + var originalGetSourceFile = host.getSourceFile; + var readFileCache = ts.createMap(); + var fileExistsCache = ts.createMap(); + var directoryExistsCache = ts.createMap(); + var sourceFileCache = ts.createMap(); + var readFileWithCache = function (fileName) { + var key = toPath(fileName); + var value = readFileCache.get(key); + if (value !== undefined) + return value || undefined; + return setReadFileCache(key, fileName); + }; + var setReadFileCache = function (key, fileName) { + var newValue = originalReadFile.call(host, fileName); + readFileCache.set(key, newValue || false); + return newValue; + }; + host.readFile = function (fileName) { + var key = toPath(fileName); + var value = readFileCache.get(key); + if (value !== undefined) + return value; // could be .d.ts from output + if (!ts.fileExtensionIs(fileName, ".json" /* Json */)) { + return originalReadFile.call(host, fileName); + } + return setReadFileCache(key, fileName); + }; + if (useCacheForSourceFile) { + host.getSourceFile = function (fileName, languageVersion, onError, shouldCreateNewSourceFile) { + var key = toPath(fileName); + var value = sourceFileCache.get(key); + if (value) + return value; + var sourceFile = originalGetSourceFile.call(host, fileName, languageVersion, onError, shouldCreateNewSourceFile); + if (sourceFile && (ts.isDeclarationFileName(fileName) || ts.fileExtensionIs(fileName, ".json" /* Json */))) { + sourceFileCache.set(key, sourceFile); + } + return sourceFile; + }; + } + // fileExists for any kind of extension + host.fileExists = function (fileName) { + var key = toPath(fileName); + var value = fileExistsCache.get(key); + if (value !== undefined) + return value; + var newValue = originalFileExists.call(host, fileName); + fileExistsCache.set(key, !!newValue); + return newValue; + }; + host.writeFile = function (fileName, data, writeByteOrderMark, onError, sourceFiles) { + var key = toPath(fileName); + fileExistsCache.delete(key); + var value = readFileCache.get(key); + if (value && value !== data) { + readFileCache.delete(key); + sourceFileCache.delete(key); + } + else if (useCacheForSourceFile) { + var sourceFile = sourceFileCache.get(key); + if (sourceFile && sourceFile.text !== data) { + sourceFileCache.delete(key); + } + } + originalWriteFile.call(host, fileName, data, writeByteOrderMark, onError, sourceFiles); + }; + // directoryExists + if (originalDirectoryExists && originalCreateDirectory) { + host.directoryExists = function (directory) { + var key = toPath(directory); + var value = directoryExistsCache.get(key); + if (value !== undefined) + return value; + var newValue = originalDirectoryExists.call(host, directory); + directoryExistsCache.set(key, !!newValue); + return newValue; + }; + host.createDirectory = function (directory) { + var key = toPath(directory); + directoryExistsCache.delete(key); + originalCreateDirectory.call(host, directory); + }; + } + return { + originalReadFile: originalReadFile, + originalFileExists: originalFileExists, + originalDirectoryExists: originalDirectoryExists, + originalCreateDirectory: originalCreateDirectory, + originalWriteFile: originalWriteFile, + originalGetSourceFile: originalGetSourceFile, + readFileWithCache: readFileWithCache + }; + } + ts.changeCompilerHostToUseCache = changeCompilerHostToUseCache; + function getPreEmitDiagnostics(program, sourceFile, cancellationToken) { + var diagnostics = program.getConfigFileParsingDiagnostics().concat(program.getOptionsDiagnostics(cancellationToken), program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken)); + if (ts.getEmitDeclarations(program.getCompilerOptions())) { + ts.addRange(diagnostics, program.getDeclarationDiagnostics(sourceFile, cancellationToken)); + } + return ts.sortAndDeduplicateDiagnostics(diagnostics); + } + ts.getPreEmitDiagnostics = getPreEmitDiagnostics; + function formatDiagnostics(diagnostics, host) { + var output = ""; + for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { + var diagnostic = diagnostics_2[_i]; + output += formatDiagnostic(diagnostic, host); + } + return output; + } + ts.formatDiagnostics = formatDiagnostics; + function formatDiagnostic(diagnostic, host) { + var errorMessage = ts.diagnosticCategoryName(diagnostic) + " TS" + diagnostic.code + ": " + flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine()) + host.getNewLine(); + if (diagnostic.file) { + var _a = ts.getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start), line = _a.line, character = _a.character; // TODO: GH#18217 + var fileName = diagnostic.file.fileName; + var relativeFileName = ts.convertToRelativePath(fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); }); + return relativeFileName + "(" + (line + 1) + "," + (character + 1) + "): " + errorMessage; + } + return errorMessage; + } + ts.formatDiagnostic = formatDiagnostic; + /** @internal */ + var ForegroundColorEscapeSequences; + (function (ForegroundColorEscapeSequences) { + ForegroundColorEscapeSequences["Grey"] = "\u001B[90m"; + ForegroundColorEscapeSequences["Red"] = "\u001B[91m"; + ForegroundColorEscapeSequences["Yellow"] = "\u001B[93m"; + ForegroundColorEscapeSequences["Blue"] = "\u001B[94m"; + ForegroundColorEscapeSequences["Cyan"] = "\u001B[96m"; + })(ForegroundColorEscapeSequences = ts.ForegroundColorEscapeSequences || (ts.ForegroundColorEscapeSequences = {})); + var gutterStyleSequence = "\u001b[7m"; + var gutterSeparator = " "; + var resetEscapeSequence = "\u001b[0m"; + var ellipsis = "..."; + var halfIndent = " "; + var indent = " "; + function getCategoryFormat(category) { + switch (category) { + case ts.DiagnosticCategory.Error: return ForegroundColorEscapeSequences.Red; + case ts.DiagnosticCategory.Warning: return ForegroundColorEscapeSequences.Yellow; + case ts.DiagnosticCategory.Suggestion: return ts.Debug.fail("Should never get an Info diagnostic on the command line."); + case ts.DiagnosticCategory.Message: return ForegroundColorEscapeSequences.Blue; + } + } + /** @internal */ + function formatColorAndReset(text, formatStyle) { + return formatStyle + text + resetEscapeSequence; + } + ts.formatColorAndReset = formatColorAndReset; + function padLeft(s, length) { + while (s.length < length) { + s = " " + s; + } + return s; + } + function formatCodeSpan(file, start, length, indent, squiggleColor, host) { + var _a = ts.getLineAndCharacterOfPosition(file, start), firstLine = _a.line, firstLineChar = _a.character; + var _b = ts.getLineAndCharacterOfPosition(file, start + length), lastLine = _b.line, lastLineChar = _b.character; + var lastLineInFile = ts.getLineAndCharacterOfPosition(file, file.text.length).line; + var hasMoreThanFiveLines = (lastLine - firstLine) >= 4; + var gutterWidth = (lastLine + 1 + "").length; + if (hasMoreThanFiveLines) { + gutterWidth = Math.max(ellipsis.length, gutterWidth); + } + var context = ""; + for (var i = firstLine; i <= lastLine; i++) { + context += host.getNewLine(); + // If the error spans over 5 lines, we'll only show the first 2 and last 2 lines, + // so we'll skip ahead to the second-to-last line. + if (hasMoreThanFiveLines && firstLine + 1 < i && i < lastLine - 1) { + context += indent + formatColorAndReset(padLeft(ellipsis, gutterWidth), gutterStyleSequence) + gutterSeparator + host.getNewLine(); + i = lastLine - 1; + } + var lineStart = ts.getPositionOfLineAndCharacter(file, i, 0); + var lineEnd = i < lastLineInFile ? ts.getPositionOfLineAndCharacter(file, i + 1, 0) : file.text.length; + var lineContent = file.text.slice(lineStart, lineEnd); + lineContent = lineContent.replace(/\s+$/g, ""); // trim from end + lineContent = lineContent.replace("\t", " "); // convert tabs to single spaces + // Output the gutter and the actual contents of the line. + context += indent + formatColorAndReset(padLeft(i + 1 + "", gutterWidth), gutterStyleSequence) + gutterSeparator; + context += lineContent + host.getNewLine(); + // Output the gutter and the error span for the line using tildes. + context += indent + formatColorAndReset(padLeft("", gutterWidth), gutterStyleSequence) + gutterSeparator; + context += squiggleColor; + if (i === firstLine) { + // If we're on the last line, then limit it to the last character of the last line. + // Otherwise, we'll just squiggle the rest of the line, giving 'slice' no end position. + var lastCharForLine = i === lastLine ? lastLineChar : undefined; + context += lineContent.slice(0, firstLineChar).replace(/\S/g, " "); + context += lineContent.slice(firstLineChar, lastCharForLine).replace(/./g, "~"); + } + else if (i === lastLine) { + context += lineContent.slice(0, lastLineChar).replace(/./g, "~"); + } + else { + // Squiggle the entire line. + context += lineContent.replace(/./g, "~"); + } + context += resetEscapeSequence; + } + return context; + } + /* @internal */ + function formatLocation(file, start, host, color) { + if (color === void 0) { color = formatColorAndReset; } + var _a = ts.getLineAndCharacterOfPosition(file, start), firstLine = _a.line, firstLineChar = _a.character; // TODO: GH#18217 + var relativeFileName = host ? ts.convertToRelativePath(file.fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); }) : file.fileName; + var output = ""; + output += color(relativeFileName, ForegroundColorEscapeSequences.Cyan); + output += ":"; + output += color("" + (firstLine + 1), ForegroundColorEscapeSequences.Yellow); + output += ":"; + output += color("" + (firstLineChar + 1), ForegroundColorEscapeSequences.Yellow); + return output; + } + ts.formatLocation = formatLocation; + function formatDiagnosticsWithColorAndContext(diagnostics, host) { + var output = ""; + for (var _i = 0, diagnostics_3 = diagnostics; _i < diagnostics_3.length; _i++) { + var diagnostic = diagnostics_3[_i]; + if (diagnostic.file) { + var file = diagnostic.file, start = diagnostic.start; + output += formatLocation(file, start, host); // TODO: GH#18217 + output += " - "; + } + output += formatColorAndReset(ts.diagnosticCategoryName(diagnostic), getCategoryFormat(diagnostic.category)); + output += formatColorAndReset(" TS" + diagnostic.code + ": ", ForegroundColorEscapeSequences.Grey); + output += flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine()); + if (diagnostic.file) { + output += host.getNewLine(); + output += formatCodeSpan(diagnostic.file, diagnostic.start, diagnostic.length, "", getCategoryFormat(diagnostic.category), host); // TODO: GH#18217 + if (diagnostic.relatedInformation) { + output += host.getNewLine(); + for (var _a = 0, _b = diagnostic.relatedInformation; _a < _b.length; _a++) { + var _c = _b[_a], file = _c.file, start = _c.start, length_4 = _c.length, messageText = _c.messageText; + if (file) { + output += host.getNewLine(); + output += halfIndent + formatLocation(file, start, host); // TODO: GH#18217 + output += formatCodeSpan(file, start, length_4, indent, ForegroundColorEscapeSequences.Cyan, host); // TODO: GH#18217 + } + output += host.getNewLine(); + output += indent + flattenDiagnosticMessageText(messageText, host.getNewLine()); + } + } + } + output += host.getNewLine(); + } + return output; + } + ts.formatDiagnosticsWithColorAndContext = formatDiagnosticsWithColorAndContext; + function flattenDiagnosticMessageText(messageText, newLine) { + if (ts.isString(messageText)) { + return messageText; + } + else { + var diagnosticChain = messageText; + var result = ""; + var indent_1 = 0; + while (diagnosticChain) { + if (indent_1) { + result += newLine; + for (var i = 0; i < indent_1; i++) { + result += " "; + } + } + result += diagnosticChain.messageText; + indent_1++; + diagnosticChain = diagnosticChain.next; + } + return result; + } + } + ts.flattenDiagnosticMessageText = flattenDiagnosticMessageText; + function loadWithLocalCache(names, containingFile, redirectedReference, loader) { + if (names.length === 0) { + return []; + } + var resolutions = []; + var cache = ts.createMap(); + for (var _i = 0, names_1 = names; _i < names_1.length; _i++) { + var name = names_1[_i]; + var result = void 0; + if (cache.has(name)) { + result = cache.get(name); + } + else { + cache.set(name, result = loader(name, containingFile, redirectedReference)); + } + resolutions.push(result); + } + return resolutions; + } + /** + * Determines if program structure is upto date or needs to be recreated + */ + /* @internal */ + function isProgramUptoDate(program, rootFileNames, newOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, projectReferences) { + // If we haven't created a program yet or have changed automatic type directives, then it is not up-to-date + if (!program || hasChangedAutomaticTypeDirectiveNames) { + return false; + } + // If number of files in the program do not match, it is not up-to-date + if (program.getRootFileNames().length !== rootFileNames.length) { + return false; + } + var seenResolvedRefs; + // If project references dont match + if (!ts.arrayIsEqualTo(program.getProjectReferences(), projectReferences, projectReferenceUptoDate)) { + return false; + } + // If any file is not up-to-date, then the whole program is not up-to-date + if (program.getSourceFiles().some(sourceFileNotUptoDate)) { + return false; + } + // If any of the missing file paths are now created + if (program.getMissingFilePaths().some(fileExists)) { + return false; + } + var currentOptions = program.getCompilerOptions(); + // If the compilation settings do no match, then the program is not up-to-date + if (!ts.compareDataObjects(currentOptions, newOptions)) { + return false; + } + // If everything matches but the text of config file is changed, + // error locations can change for program options, so update the program + if (currentOptions.configFile && newOptions.configFile) { + return currentOptions.configFile.text === newOptions.configFile.text; + } + return true; + function sourceFileNotUptoDate(sourceFile) { + return !sourceFileVersionUptoDate(sourceFile) || + hasInvalidatedResolution(sourceFile.path); + } + function sourceFileVersionUptoDate(sourceFile) { + return sourceFile.version === getSourceVersion(sourceFile.resolvedPath); + } + function projectReferenceUptoDate(oldRef, newRef, index) { + if (!ts.projectReferenceIsEqualTo(oldRef, newRef)) { + return false; + } + return resolvedProjectReferenceUptoDate(program.getResolvedProjectReferences()[index], oldRef); + } + function resolvedProjectReferenceUptoDate(oldResolvedRef, oldRef) { + if (oldResolvedRef) { + if (ts.contains(seenResolvedRefs, oldResolvedRef)) { + // Assume true + return true; + } + // If sourceFile for the oldResolvedRef existed, check the version for uptodate + if (!sourceFileVersionUptoDate(oldResolvedRef.sourceFile)) { + return false; + } + // Add to seen before checking the referenced paths of this config file + (seenResolvedRefs || (seenResolvedRefs = [])).push(oldResolvedRef); + // If child project references are upto date, this project reference is uptodate + return !ts.forEach(oldResolvedRef.references, function (childResolvedRef, index) { + return !resolvedProjectReferenceUptoDate(childResolvedRef, oldResolvedRef.commandLine.projectReferences[index]); + }); + } + // In old program, not able to resolve project reference path, + // so if config file doesnt exist, it is uptodate. + return !fileExists(resolveProjectReferencePath(oldRef)); + } + } + ts.isProgramUptoDate = isProgramUptoDate; + function getConfigFileParsingDiagnostics(configFileParseResult) { + return configFileParseResult.options.configFile ? configFileParseResult.options.configFile.parseDiagnostics.concat(configFileParseResult.errors) : + configFileParseResult.errors; + } + ts.getConfigFileParsingDiagnostics = getConfigFileParsingDiagnostics; + /** + * Determine if source file needs to be re-created even if its text hasn't changed + */ + function shouldProgramCreateNewSourceFiles(program, newOptions) { + if (!program) + return false; + // If any compiler options change, we can't reuse old source file even if version match + // The change in options like these could result in change in syntax tree or `sourceFile.bindDiagnostics`. + var oldOptions = program.getCompilerOptions(); + return !!ts.sourceFileAffectingCompilerOptions.some(function (option) { + return !ts.isJsonEqual(ts.getCompilerOptionValue(oldOptions, option), ts.getCompilerOptionValue(newOptions, option)); + }); + } + function createCreateProgramOptions(rootNames, options, host, oldProgram, configFileParsingDiagnostics) { + return { + rootNames: rootNames, + options: options, + host: host, + oldProgram: oldProgram, + configFileParsingDiagnostics: configFileParsingDiagnostics + }; + } + function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _configFileParsingDiagnostics) { + var createProgramOptions = ts.isArray(rootNamesOrOptions) ? createCreateProgramOptions(rootNamesOrOptions, _options, _host, _oldProgram, _configFileParsingDiagnostics) : rootNamesOrOptions; // TODO: GH#18217 + var rootNames = createProgramOptions.rootNames, options = createProgramOptions.options, configFileParsingDiagnostics = createProgramOptions.configFileParsingDiagnostics, projectReferences = createProgramOptions.projectReferences; + var oldProgram = createProgramOptions.oldProgram; + var program; + var processingDefaultLibFiles; + var processingOtherFiles; + var files; + var commonSourceDirectory; + var diagnosticsProducingTypeChecker; + var noDiagnosticsTypeChecker; + var classifiableNames; + var ambientModuleNameToUnmodifiedFileName = ts.createMap(); + var cachedSemanticDiagnosticsForFile = {}; + var cachedDeclarationDiagnosticsForFile = {}; + var resolvedTypeReferenceDirectives = ts.createMap(); + var fileProcessingDiagnostics = ts.createDiagnosticCollection(); + // The below settings are to track if a .js file should be add to the program if loaded via searching under node_modules. + // This works as imported modules are discovered recursively in a depth first manner, specifically: + // - For each root file, findSourceFile is called. + // - This calls processImportedModules for each module imported in the source file. + // - This calls resolveModuleNames, and then calls findSourceFile for each resolved module. + // As all these operations happen - and are nested - within the createProgram call, they close over the below variables. + // The current resolution depth is tracked by incrementing/decrementing as the depth first search progresses. + var maxNodeModuleJsDepth = typeof options.maxNodeModuleJsDepth === "number" ? options.maxNodeModuleJsDepth : 0; + var currentNodeModulesDepth = 0; + // If a module has some of its imports skipped due to being at the depth limit under node_modules, then track + // this, as it may be imported at a shallower depth later, and then it will need its skipped imports processed. + var modulesWithElidedImports = ts.createMap(); + // Track source files that are source files found by searching under node_modules, as these shouldn't be compiled. + var sourceFilesFoundSearchingNodeModules = ts.createMap(); + ts.performance.mark("beforeProgram"); + var host = createProgramOptions.host || createCompilerHost(options); + var configParsingHost = parseConfigHostFromCompilerHost(host); + var skipDefaultLib = options.noLib; + var getDefaultLibraryFileName = ts.memoize(function () { return host.getDefaultLibFileName(options); }); + var defaultLibraryPath = host.getDefaultLibLocation ? host.getDefaultLibLocation() : ts.getDirectoryPath(getDefaultLibraryFileName()); + var programDiagnostics = ts.createDiagnosticCollection(); + var currentDirectory = host.getCurrentDirectory(); + var supportedExtensions = ts.getSupportedExtensions(options); + var supportedExtensionsWithJsonIfResolveJsonModule = ts.getSuppoertedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions); + // Map storing if there is emit blocking diagnostics for given input + var hasEmitBlockingDiagnostics = ts.createMap(); + var _compilerOptionsObjectLiteralSyntax; + var moduleResolutionCache; + var resolveModuleNamesWorker; + var hasInvalidatedResolution = host.hasInvalidatedResolution || ts.returnFalse; + if (host.resolveModuleNames) { + resolveModuleNamesWorker = function (moduleNames, containingFile, reusedNames, redirectedReference) { return host.resolveModuleNames(ts.Debug.assertEachDefined(moduleNames), containingFile, reusedNames, redirectedReference).map(function (resolved) { + // An older host may have omitted extension, in which case we should infer it from the file extension of resolvedFileName. + if (!resolved || resolved.extension !== undefined) { + return resolved; + } + var withExtension = ts.clone(resolved); + withExtension.extension = ts.extensionFromPath(resolved.resolvedFileName); + return withExtension; + }); }; + } + else { + moduleResolutionCache = ts.createModuleResolutionCache(currentDirectory, function (x) { return host.getCanonicalFileName(x); }); + var loader_1 = function (moduleName, containingFile, redirectedReference) { return ts.resolveModuleName(moduleName, containingFile, options, host, moduleResolutionCache, redirectedReference).resolvedModule; }; // TODO: GH#18217 + resolveModuleNamesWorker = function (moduleNames, containingFile, _reusedNames, redirectedReference) { return loadWithLocalCache(ts.Debug.assertEachDefined(moduleNames), containingFile, redirectedReference, loader_1); }; + } + var resolveTypeReferenceDirectiveNamesWorker; + if (host.resolveTypeReferenceDirectives) { + resolveTypeReferenceDirectiveNamesWorker = function (typeDirectiveNames, containingFile, redirectedReference) { return host.resolveTypeReferenceDirectives(ts.Debug.assertEachDefined(typeDirectiveNames), containingFile, redirectedReference); }; + } + else { + var loader_2 = function (typesRef, containingFile, redirectedReference) { return ts.resolveTypeReferenceDirective(typesRef, containingFile, options, host, redirectedReference).resolvedTypeReferenceDirective; }; // TODO: GH#18217 + resolveTypeReferenceDirectiveNamesWorker = function (typeReferenceDirectiveNames, containingFile, redirectedReference) { return loadWithLocalCache(ts.Debug.assertEachDefined(typeReferenceDirectiveNames), containingFile, redirectedReference, loader_2); }; + } + // Map from a stringified PackageId to the source file with that id. + // Only one source file may have a given packageId. Others become redirects (see createRedirectSourceFile). + // `packageIdToSourceFile` is only used while building the program, while `sourceFileToPackageName` and `isSourceFileTargetOfRedirect` are kept around. + var packageIdToSourceFile = ts.createMap(); + // Maps from a SourceFile's `.path` to the name of the package it was imported with. + var sourceFileToPackageName = ts.createMap(); + // Key is a file name. Value is the (non-empty, or undefined) list of files that redirect to it. + var redirectTargetsMap = ts.createMultiMap(); + var filesByName = ts.createMap(); + var missingFilePaths; + // stores 'filename -> file association' ignoring case + // used to track cases when two file names differ only in casing + var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createMap() : undefined; + // A parallel array to projectReferences storing the results of reading in the referenced tsconfig files + var resolvedProjectReferences; + var projectReferenceRedirects; + var mapFromFileToProjectReferenceRedirects; + var shouldCreateNewSourceFile = shouldProgramCreateNewSourceFiles(oldProgram, options); + var structuralIsReused = tryReuseStructureFromOldProgram(); + if (structuralIsReused !== 2 /* Completely */) { + processingDefaultLibFiles = []; + processingOtherFiles = []; + if (projectReferences) { + if (!resolvedProjectReferences) { + resolvedProjectReferences = projectReferences.map(parseProjectReferenceConfigFile); + } + if (rootNames.length) { + for (var _i = 0, resolvedProjectReferences_1 = resolvedProjectReferences; _i < resolvedProjectReferences_1.length; _i++) { + var parsedRef = resolvedProjectReferences_1[_i]; + if (parsedRef) { + var out = parsedRef.commandLine.options.outFile || parsedRef.commandLine.options.out; + if (out) { + var dtsOutfile = ts.changeExtension(out, ".d.ts"); + processSourceFile(dtsOutfile, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined); + } + } + } + } + } + ts.forEach(rootNames, function (name) { return processRootFile(name, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false); }); + // load type declarations specified via 'types' argument or implicitly from types/ and node_modules/@types folders + var typeReferences = rootNames.length ? ts.getAutomaticTypeDirectiveNames(options, host) : ts.emptyArray; + if (typeReferences.length) { + // This containingFilename needs to match with the one used in managed-side + var containingDirectory = options.configFilePath ? ts.getDirectoryPath(options.configFilePath) : host.getCurrentDirectory(); + var containingFilename = ts.combinePaths(containingDirectory, "__inferred type names__.ts"); + var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeReferences, containingFilename); + for (var i = 0; i < typeReferences.length; i++) { + processTypeReferenceDirective(typeReferences[i], resolutions[i]); + } + } + // Do not process the default library if: + // - The '--noLib' flag is used. + // - A 'no-default-lib' reference comment is encountered in + // processing the root files. + if (rootNames.length && !skipDefaultLib) { + // If '--lib' is not specified, include default library file according to '--target' + // otherwise, using options specified in '--lib' instead of '--target' default library file + var defaultLibraryFileName = getDefaultLibraryFileName(); + if (!options.lib && defaultLibraryFileName) { + processRootFile(defaultLibraryFileName, /*isDefaultLib*/ true, /*ignoreNoDefaultLib*/ false); + } + else { + ts.forEach(options.lib, function (libFileName) { + processRootFile(ts.combinePaths(defaultLibraryPath, libFileName), /*isDefaultLib*/ true, /*ignoreNoDefaultLib*/ false); + }); + } + } + missingFilePaths = ts.arrayFrom(filesByName.keys(), function (p) { return p; }).filter(function (p) { return !filesByName.get(p); }); + files = ts.stableSort(processingDefaultLibFiles, compareDefaultLibFiles).concat(processingOtherFiles); + processingDefaultLibFiles = undefined; + processingOtherFiles = undefined; + } + ts.Debug.assert(!!missingFilePaths); + // Release any files we have acquired in the old program but are + // not part of the new program. + if (oldProgram && host.onReleaseOldSourceFile) { + var oldSourceFiles = oldProgram.getSourceFiles(); + for (var _a = 0, oldSourceFiles_1 = oldSourceFiles; _a < oldSourceFiles_1.length; _a++) { + var oldSourceFile = oldSourceFiles_1[_a]; + var newFile = getSourceFileByPath(oldSourceFile.resolvedPath); + if (shouldCreateNewSourceFile || !newFile || + // old file wasnt redirect but new file is + (oldSourceFile.resolvedPath === oldSourceFile.path && newFile.resolvedPath !== oldSourceFile.path)) { + host.onReleaseOldSourceFile(oldSourceFile, oldProgram.getCompilerOptions(), !!getSourceFileByPath(oldSourceFile.path)); + } + } + oldProgram.forEachResolvedProjectReference(function (resolvedProjectReference, resolvedProjectReferencePath) { + if (resolvedProjectReference && !getResolvedProjectReferenceByPath(resolvedProjectReferencePath)) { + host.onReleaseOldSourceFile(resolvedProjectReference.sourceFile, oldProgram.getCompilerOptions(), /*hasSourceFileByPath*/ false); + } + }); + } + // unconditionally set oldProgram to undefined to prevent it from being captured in closure + oldProgram = undefined; + program = { + getRootFileNames: function () { return rootNames; }, + getSourceFile: getSourceFile, + getSourceFileByPath: getSourceFileByPath, + getSourceFiles: function () { return files; }, + getMissingFilePaths: function () { return missingFilePaths; }, + getCompilerOptions: function () { return options; }, + getSyntacticDiagnostics: getSyntacticDiagnostics, + getOptionsDiagnostics: getOptionsDiagnostics, + getGlobalDiagnostics: getGlobalDiagnostics, + getSemanticDiagnostics: getSemanticDiagnostics, + getSuggestionDiagnostics: getSuggestionDiagnostics, + getDeclarationDiagnostics: getDeclarationDiagnostics, + getTypeChecker: getTypeChecker, + getClassifiableNames: getClassifiableNames, + getDiagnosticsProducingTypeChecker: getDiagnosticsProducingTypeChecker, + getCommonSourceDirectory: getCommonSourceDirectory, + emit: emit, + getCurrentDirectory: function () { return currentDirectory; }, + getNodeCount: function () { return getDiagnosticsProducingTypeChecker().getNodeCount(); }, + getIdentifierCount: function () { return getDiagnosticsProducingTypeChecker().getIdentifierCount(); }, + getSymbolCount: function () { return getDiagnosticsProducingTypeChecker().getSymbolCount(); }, + getTypeCount: function () { return getDiagnosticsProducingTypeChecker().getTypeCount(); }, + getFileProcessingDiagnostics: function () { return fileProcessingDiagnostics; }, + getResolvedTypeReferenceDirectives: function () { return resolvedTypeReferenceDirectives; }, + isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary, + isSourceFileDefaultLibrary: isSourceFileDefaultLibrary, + dropDiagnosticsProducingTypeChecker: dropDiagnosticsProducingTypeChecker, + getSourceFileFromReference: getSourceFileFromReference, + getLibFileFromReference: getLibFileFromReference, + sourceFileToPackageName: sourceFileToPackageName, + redirectTargetsMap: redirectTargetsMap, + isEmittedFile: isEmittedFile, + getConfigFileParsingDiagnostics: getConfigFileParsingDiagnostics, + getResolvedModuleWithFailedLookupLocationsFromCache: getResolvedModuleWithFailedLookupLocationsFromCache, + getProjectReferences: getProjectReferences, + getResolvedProjectReferences: getResolvedProjectReferences, + getProjectReferenceRedirect: getProjectReferenceRedirect, + getResolvedProjectReferenceToRedirect: getResolvedProjectReferenceToRedirect, + getResolvedProjectReferenceByPath: getResolvedProjectReferenceByPath, + forEachResolvedProjectReference: forEachResolvedProjectReference + }; + verifyCompilerOptions(); + ts.performance.mark("afterProgram"); + ts.performance.measure("Program", "beforeProgram", "afterProgram"); + return program; + function compareDefaultLibFiles(a, b) { + return ts.compareValues(getDefaultLibFilePriority(a), getDefaultLibFilePriority(b)); + } + function getDefaultLibFilePriority(a) { + if (ts.containsPath(defaultLibraryPath, a.fileName, /*ignoreCase*/ false)) { + var basename = ts.getBaseFileName(a.fileName); + if (basename === "lib.d.ts" || basename === "lib.es6.d.ts") + return 0; + var name = ts.removeSuffix(ts.removePrefix(basename, "lib."), ".d.ts"); + var index = ts.libs.indexOf(name); + if (index !== -1) + return index + 1; + } + return ts.libs.length + 2; + } + function getResolvedModuleWithFailedLookupLocationsFromCache(moduleName, containingFile) { + return moduleResolutionCache && ts.resolveModuleNameFromCache(moduleName, containingFile, moduleResolutionCache); + } + function toPath(fileName) { + return ts.toPath(fileName, currentDirectory, getCanonicalFileName); + } + function getCommonSourceDirectory() { + if (commonSourceDirectory === undefined) { + var emittedFiles = ts.filter(files, function (file) { return ts.sourceFileMayBeEmitted(file, options, isSourceFileFromExternalLibrary); }); + if (options.rootDir && checkSourceFilesBelongToPath(emittedFiles, options.rootDir)) { + // If a rootDir is specified use it as the commonSourceDirectory + commonSourceDirectory = ts.getNormalizedAbsolutePath(options.rootDir, currentDirectory); + } + else if (options.composite && options.configFilePath) { + // Project compilations never infer their root from the input source paths + commonSourceDirectory = ts.getDirectoryPath(ts.normalizeSlashes(options.configFilePath)); + checkSourceFilesBelongToPath(emittedFiles, commonSourceDirectory); + } + else { + commonSourceDirectory = computeCommonSourceDirectory(emittedFiles); + } + if (commonSourceDirectory && commonSourceDirectory[commonSourceDirectory.length - 1] !== ts.directorySeparator) { + // Make sure directory path ends with directory separator so this string can directly + // used to replace with "" to get the relative path of the source file and the relative path doesn't + // start with / making it rooted path + commonSourceDirectory += ts.directorySeparator; + } + } + return commonSourceDirectory; + } + function getClassifiableNames() { + if (!classifiableNames) { + // Initialize a checker so that all our files are bound. + getTypeChecker(); + classifiableNames = ts.createUnderscoreEscapedMap(); + for (var _i = 0, files_2 = files; _i < files_2.length; _i++) { + var sourceFile = files_2[_i]; + ts.copyEntries(sourceFile.classifiableNames, classifiableNames); + } + } + return classifiableNames; + } + function resolveModuleNamesReusingOldState(moduleNames, containingFile, file) { + if (structuralIsReused === 0 /* Not */ && !file.ambientModuleNames.length) { + // If the old program state does not permit reusing resolutions and `file` does not contain locally defined ambient modules, + // the best we can do is fallback to the default logic. + return resolveModuleNamesWorker(moduleNames, containingFile, /*reusedNames*/ undefined, getResolvedProjectReferenceToRedirect(file.originalFileName)); + } + var oldSourceFile = oldProgram && oldProgram.getSourceFile(containingFile); + if (oldSourceFile !== file && file.resolvedModules) { + // `file` was created for the new program. + // + // We only set `file.resolvedModules` via work from the current function, + // so it is defined iff we already called the current function on `file`. + // That call happened no later than the creation of the `file` object, + // which per above occurred during the current program creation. + // Since we assume the filesystem does not change during program creation, + // it is safe to reuse resolutions from the earlier call. + var result_5 = []; + for (var _i = 0, moduleNames_1 = moduleNames; _i < moduleNames_1.length; _i++) { + var moduleName = moduleNames_1[_i]; + var resolvedModule = file.resolvedModules.get(moduleName); + result_5.push(resolvedModule); + } + return result_5; + } + // At this point, we know at least one of the following hold: + // - file has local declarations for ambient modules + // - old program state is available + // With this information, we can infer some module resolutions without performing resolution. + /** An ordered list of module names for which we cannot recover the resolution. */ + var unknownModuleNames; + /** + * The indexing of elements in this list matches that of `moduleNames`. + * + * Before combining results, result[i] is in one of the following states: + * * undefined: needs to be recomputed, + * * predictedToResolveToAmbientModuleMarker: known to be an ambient module. + * Needs to be reset to undefined before returning, + * * ResolvedModuleFull instance: can be reused. + */ + var result; + var reusedNames; + /** A transient placeholder used to mark predicted resolution in the result list. */ + var predictedToResolveToAmbientModuleMarker = {}; + for (var i = 0; i < moduleNames.length; i++) { + var moduleName = moduleNames[i]; + // If the source file is unchanged and doesnt have invalidated resolution, reuse the module resolutions + if (file === oldSourceFile && !hasInvalidatedResolution(oldSourceFile.path)) { + var oldResolvedModule = oldSourceFile && oldSourceFile.resolvedModules.get(moduleName); + if (oldResolvedModule) { + if (ts.isTraceEnabled(options, host)) { + ts.trace(host, ts.Diagnostics.Reusing_resolution_of_module_0_to_file_1_from_old_program, moduleName, containingFile); + } + (result || (result = new Array(moduleNames.length)))[i] = oldResolvedModule; + (reusedNames || (reusedNames = [])).push(moduleName); + continue; + } + } + // We know moduleName resolves to an ambient module provided that moduleName: + // - is in the list of ambient modules locally declared in the current source file. + // - resolved to an ambient module in the old program whose declaration is in an unmodified file + // (so the same module declaration will land in the new program) + var resolvesToAmbientModuleInNonModifiedFile = false; + if (ts.contains(file.ambientModuleNames, moduleName)) { + resolvesToAmbientModuleInNonModifiedFile = true; + if (ts.isTraceEnabled(options, host)) { + ts.trace(host, ts.Diagnostics.Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1, moduleName, containingFile); + } + } + else { + resolvesToAmbientModuleInNonModifiedFile = moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName); + } + if (resolvesToAmbientModuleInNonModifiedFile) { + (result || (result = new Array(moduleNames.length)))[i] = predictedToResolveToAmbientModuleMarker; + } + else { + // Resolution failed in the old program, or resolved to an ambient module for which we can't reuse the result. + (unknownModuleNames || (unknownModuleNames = [])).push(moduleName); + } + } + var resolutions = unknownModuleNames && unknownModuleNames.length + ? resolveModuleNamesWorker(unknownModuleNames, containingFile, reusedNames, getResolvedProjectReferenceToRedirect(file.originalFileName)) + : ts.emptyArray; + // Combine results of resolutions and predicted results + if (!result) { + // There were no unresolved/ambient resolutions. + ts.Debug.assert(resolutions.length === moduleNames.length); + return resolutions; + } + var j = 0; + for (var i = 0; i < result.length; i++) { + if (result[i]) { + // `result[i]` is either a `ResolvedModuleFull` or a marker. + // If it is the former, we can leave it as is. + if (result[i] === predictedToResolveToAmbientModuleMarker) { + result[i] = undefined; // TODO: GH#18217 + } + } + else { + result[i] = resolutions[j]; + j++; + } + } + ts.Debug.assert(j === resolutions.length); + return result; + // If we change our policy of rechecking failed lookups on each program create, + // we should adjust the value returned here. + function moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName) { + var resolutionToFile = ts.getResolvedModule(oldSourceFile, moduleName); + var resolvedFile = resolutionToFile && oldProgram.getSourceFile(resolutionToFile.resolvedFileName); + if (resolutionToFile && resolvedFile && !resolvedFile.externalModuleIndicator) { + // In the old program, we resolved to an ambient module that was in the same + // place as we expected to find an actual module file. + // We actually need to return 'false' here even though this seems like a 'true' case + // because the normal module resolution algorithm will find this anyway. + return false; + } + // at least one of declarations should come from non-modified source file + var unmodifiedFile = ambientModuleNameToUnmodifiedFileName.get(moduleName); + if (!unmodifiedFile) { + return false; + } + if (ts.isTraceEnabled(options, host)) { + ts.trace(host, ts.Diagnostics.Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified, moduleName, unmodifiedFile); + } + return true; + } + } + function canReuseProjectReferences() { + return !forEachProjectReference(oldProgram.getProjectReferences(), oldProgram.getResolvedProjectReferences(), function (oldResolvedRef, index, parent) { + var newRef = (parent ? parent.commandLine.projectReferences : projectReferences)[index]; + var newResolvedRef = parseProjectReferenceConfigFile(newRef); + if (oldResolvedRef) { + // Resolved project reference has gone missing or changed + return !newResolvedRef || newResolvedRef.sourceFile !== oldResolvedRef.sourceFile; + } + else { + // A previously-unresolved reference may be resolved now + return newResolvedRef !== undefined; + } + }, function (oldProjectReferences, parent) { + // If array of references is changed, we cant resue old program + var newReferences = parent ? getResolvedProjectReferenceByPath(parent.sourceFile.path).commandLine.projectReferences : projectReferences; + return !ts.arrayIsEqualTo(oldProjectReferences, newReferences, ts.projectReferenceIsEqualTo); + }); + } + function tryReuseStructureFromOldProgram() { + if (!oldProgram) { + return 0 /* Not */; + } + // check properties that can affect structure of the program or module resolution strategy + // if any of these properties has changed - structure cannot be reused + var oldOptions = oldProgram.getCompilerOptions(); + if (ts.changesAffectModuleResolution(oldOptions, options)) { + return oldProgram.structureIsReused = 0 /* Not */; + } + ts.Debug.assert(!(oldProgram.structureIsReused & (2 /* Completely */ | 1 /* SafeModules */))); + // there is an old program, check if we can reuse its structure + var oldRootNames = oldProgram.getRootFileNames(); + if (!ts.arrayIsEqualTo(oldRootNames, rootNames)) { + return oldProgram.structureIsReused = 0 /* Not */; + } + if (!ts.arrayIsEqualTo(options.types, oldOptions.types)) { + return oldProgram.structureIsReused = 0 /* Not */; + } + // Check if any referenced project tsconfig files are different + if (!canReuseProjectReferences()) { + return oldProgram.structureIsReused = 0 /* Not */; + } + if (projectReferences) { + resolvedProjectReferences = projectReferences.map(parseProjectReferenceConfigFile); + } + // check if program source files has changed in the way that can affect structure of the program + var newSourceFiles = []; + var modifiedSourceFiles = []; + oldProgram.structureIsReused = 2 /* Completely */; + // If the missing file paths are now present, it can change the progam structure, + // and hence cant reuse the structure. + // This is same as how we dont reuse the structure if one of the file from old program is now missing + if (oldProgram.getMissingFilePaths().some(function (missingFilePath) { return host.fileExists(missingFilePath); })) { + return oldProgram.structureIsReused = 0 /* Not */; + } + var oldSourceFiles = oldProgram.getSourceFiles(); + var SeenPackageName; + (function (SeenPackageName) { + SeenPackageName[SeenPackageName["Exists"] = 0] = "Exists"; + SeenPackageName[SeenPackageName["Modified"] = 1] = "Modified"; + })(SeenPackageName || (SeenPackageName = {})); + var seenPackageNames = ts.createMap(); + for (var _i = 0, oldSourceFiles_2 = oldSourceFiles; _i < oldSourceFiles_2.length; _i++) { + var oldSourceFile = oldSourceFiles_2[_i]; + var newSourceFile = host.getSourceFileByPath + ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.resolvedPath, options.target, /*onError*/ undefined, shouldCreateNewSourceFile) + : host.getSourceFile(oldSourceFile.fileName, options.target, /*onError*/ undefined, shouldCreateNewSourceFile); // TODO: GH#18217 + if (!newSourceFile) { + return oldProgram.structureIsReused = 0 /* Not */; + } + ts.Debug.assert(!newSourceFile.redirectInfo, "Host should not return a redirect source file from `getSourceFile`"); + var fileChanged = void 0; + if (oldSourceFile.redirectInfo) { + // We got `newSourceFile` by path, so it is actually for the unredirected file. + // This lets us know if the unredirected file has changed. If it has we should break the redirect. + if (newSourceFile !== oldSourceFile.redirectInfo.unredirected) { + // Underlying file has changed. Might not redirect anymore. Must rebuild program. + return oldProgram.structureIsReused = 0 /* Not */; + } + fileChanged = false; + newSourceFile = oldSourceFile; // Use the redirect. + } + else if (oldProgram.redirectTargetsMap.has(oldSourceFile.path)) { + // If a redirected-to source file changes, the redirect may be broken. + if (newSourceFile !== oldSourceFile) { + return oldProgram.structureIsReused = 0 /* Not */; + } + fileChanged = false; + } + else { + fileChanged = newSourceFile !== oldSourceFile; + } + // Since the project references havent changed, its right to set originalFileName and resolvedPath here + newSourceFile.path = oldSourceFile.path; + newSourceFile.originalFileName = oldSourceFile.originalFileName; + newSourceFile.resolvedPath = oldSourceFile.resolvedPath; + newSourceFile.fileName = oldSourceFile.fileName; + var packageName = oldProgram.sourceFileToPackageName.get(oldSourceFile.path); + if (packageName !== undefined) { + // If there are 2 different source files for the same package name and at least one of them changes, + // they might become redirects. So we must rebuild the program. + var prevKind = seenPackageNames.get(packageName); + var newKind = fileChanged ? 1 /* Modified */ : 0 /* Exists */; + if ((prevKind !== undefined && newKind === 1 /* Modified */) || prevKind === 1 /* Modified */) { + return oldProgram.structureIsReused = 0 /* Not */; + } + seenPackageNames.set(packageName, newKind); + } + if (fileChanged) { + // The `newSourceFile` object was created for the new program. + if (!ts.arrayIsEqualTo(oldSourceFile.libReferenceDirectives, newSourceFile.libReferenceDirectives, fileReferenceIsEqualTo)) { + // 'lib' references has changed. Matches behavior in changesAffectModuleResolution + return oldProgram.structureIsReused = 0 /* Not */; + } + if (oldSourceFile.hasNoDefaultLib !== newSourceFile.hasNoDefaultLib) { + // value of no-default-lib has changed + // this will affect if default library is injected into the list of files + oldProgram.structureIsReused = 1 /* SafeModules */; + } + // check tripleslash references + if (!ts.arrayIsEqualTo(oldSourceFile.referencedFiles, newSourceFile.referencedFiles, fileReferenceIsEqualTo)) { + // tripleslash references has changed + oldProgram.structureIsReused = 1 /* SafeModules */; + } + // check imports and module augmentations + collectExternalModuleReferences(newSourceFile); + if (!ts.arrayIsEqualTo(oldSourceFile.imports, newSourceFile.imports, moduleNameIsEqualTo)) { + // imports has changed + oldProgram.structureIsReused = 1 /* SafeModules */; + } + if (!ts.arrayIsEqualTo(oldSourceFile.moduleAugmentations, newSourceFile.moduleAugmentations, moduleNameIsEqualTo)) { + // moduleAugmentations has changed + oldProgram.structureIsReused = 1 /* SafeModules */; + } + if ((oldSourceFile.flags & 1572864 /* PermanentlySetIncrementalFlags */) !== (newSourceFile.flags & 1572864 /* PermanentlySetIncrementalFlags */)) { + // dynamicImport has changed + oldProgram.structureIsReused = 1 /* SafeModules */; + } + if (!ts.arrayIsEqualTo(oldSourceFile.typeReferenceDirectives, newSourceFile.typeReferenceDirectives, fileReferenceIsEqualTo)) { + // 'types' references has changed + oldProgram.structureIsReused = 1 /* SafeModules */; + } + // tentatively approve the file + modifiedSourceFiles.push({ oldFile: oldSourceFile, newFile: newSourceFile }); + } + else if (hasInvalidatedResolution(oldSourceFile.path)) { + // 'module/types' references could have changed + oldProgram.structureIsReused = 1 /* SafeModules */; + // add file to the modified list so that we will resolve it later + modifiedSourceFiles.push({ oldFile: oldSourceFile, newFile: newSourceFile }); + } + // if file has passed all checks it should be safe to reuse it + newSourceFiles.push(newSourceFile); + } + if (oldProgram.structureIsReused !== 2 /* Completely */) { + return oldProgram.structureIsReused; + } + var modifiedFiles = modifiedSourceFiles.map(function (f) { return f.oldFile; }); + for (var _a = 0, oldSourceFiles_3 = oldSourceFiles; _a < oldSourceFiles_3.length; _a++) { + var oldFile = oldSourceFiles_3[_a]; + if (!ts.contains(modifiedFiles, oldFile)) { + for (var _b = 0, _c = oldFile.ambientModuleNames; _b < _c.length; _b++) { + var moduleName = _c[_b]; + ambientModuleNameToUnmodifiedFileName.set(moduleName, oldFile.fileName); + } + } + } + // try to verify results of module resolution + for (var _d = 0, modifiedSourceFiles_1 = modifiedSourceFiles; _d < modifiedSourceFiles_1.length; _d++) { + var _e = modifiedSourceFiles_1[_d], oldSourceFile = _e.oldFile, newSourceFile = _e.newFile; + var newSourceFilePath = ts.getNormalizedAbsolutePath(newSourceFile.originalFileName, currentDirectory); + if (resolveModuleNamesWorker) { + var moduleNames = getModuleNames(newSourceFile); + var resolutions = resolveModuleNamesReusingOldState(moduleNames, newSourceFilePath, newSourceFile); + // ensure that module resolution results are still correct + var resolutionsChanged = ts.hasChangesInResolutions(moduleNames, resolutions, oldSourceFile.resolvedModules, ts.moduleResolutionIsEqualTo); + if (resolutionsChanged) { + oldProgram.structureIsReused = 1 /* SafeModules */; + newSourceFile.resolvedModules = ts.zipToMap(moduleNames, resolutions); + } + else { + newSourceFile.resolvedModules = oldSourceFile.resolvedModules; + } + } + if (resolveTypeReferenceDirectiveNamesWorker) { + // We lower-case all type references because npm automatically lowercases all packages. See GH#9824. + var typesReferenceDirectives = ts.map(newSourceFile.typeReferenceDirectives, function (ref) { return ref.fileName.toLocaleLowerCase(); }); + var resolutions = resolveTypeReferenceDirectiveNamesWorker(typesReferenceDirectives, newSourceFilePath, getResolvedProjectReferenceToRedirect(newSourceFile.originalFileName)); + // ensure that types resolutions are still correct + var resolutionsChanged = ts.hasChangesInResolutions(typesReferenceDirectives, resolutions, oldSourceFile.resolvedTypeReferenceDirectiveNames, ts.typeDirectiveIsEqualTo); + if (resolutionsChanged) { + oldProgram.structureIsReused = 1 /* SafeModules */; + newSourceFile.resolvedTypeReferenceDirectiveNames = ts.zipToMap(typesReferenceDirectives, resolutions); + } + else { + newSourceFile.resolvedTypeReferenceDirectiveNames = oldSourceFile.resolvedTypeReferenceDirectiveNames; + } + } + } + if (oldProgram.structureIsReused !== 2 /* Completely */) { + return oldProgram.structureIsReused; + } + if (host.hasChangedAutomaticTypeDirectiveNames) { + return oldProgram.structureIsReused = 1 /* SafeModules */; + } + missingFilePaths = oldProgram.getMissingFilePaths(); + // update fileName -> file mapping + for (var _f = 0, newSourceFiles_1 = newSourceFiles; _f < newSourceFiles_1.length; _f++) { + var newSourceFile = newSourceFiles_1[_f]; + var filePath = newSourceFile.path; + addFileToFilesByName(newSourceFile, filePath, newSourceFile.resolvedPath); + // Set the file as found during node modules search if it was found that way in old progra, + if (oldProgram.isSourceFileFromExternalLibrary(oldProgram.getSourceFileByPath(filePath))) { + sourceFilesFoundSearchingNodeModules.set(filePath, true); + } + } + files = newSourceFiles; + fileProcessingDiagnostics = oldProgram.getFileProcessingDiagnostics(); + for (var _g = 0, modifiedSourceFiles_2 = modifiedSourceFiles; _g < modifiedSourceFiles_2.length; _g++) { + var modifiedFile = modifiedSourceFiles_2[_g]; + fileProcessingDiagnostics.reattachFileDiagnostics(modifiedFile.newFile); + } + resolvedTypeReferenceDirectives = oldProgram.getResolvedTypeReferenceDirectives(); + sourceFileToPackageName = oldProgram.sourceFileToPackageName; + redirectTargetsMap = oldProgram.redirectTargetsMap; + return oldProgram.structureIsReused = 2 /* Completely */; + } + function getEmitHost(writeFileCallback) { + return __assign({ getPrependNodes: getPrependNodes, + getCanonicalFileName: getCanonicalFileName, getCommonSourceDirectory: program.getCommonSourceDirectory, getCompilerOptions: program.getCompilerOptions, getCurrentDirectory: function () { return currentDirectory; }, getNewLine: function () { return host.getNewLine(); }, getSourceFile: program.getSourceFile, getSourceFileByPath: program.getSourceFileByPath, getSourceFiles: program.getSourceFiles, getLibFileFromReference: program.getLibFileFromReference, isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary, writeFile: writeFileCallback || (function (fileName, data, writeByteOrderMark, onError, sourceFiles) { return host.writeFile(fileName, data, writeByteOrderMark, onError, sourceFiles); }), isEmitBlocked: isEmitBlocked, readFile: function (f) { return host.readFile(f); }, fileExists: function (f) { + // Use local caches + var path = toPath(f); + if (getSourceFileByPath(path)) + return true; + if (ts.contains(missingFilePaths, path)) + return false; + // Before falling back to the host + return host.fileExists(f); + } }, (host.directoryExists ? { directoryExists: function (f) { return host.directoryExists(f); } } : {}), { useCaseSensitiveFileNames: function () { return host.useCaseSensitiveFileNames(); } }); + } + function getResolvedProjectReferences() { + return resolvedProjectReferences; + } + function getProjectReferences() { + return projectReferences; + } + function getPrependNodes() { + if (!projectReferences) { + return ts.emptyArray; + } + var nodes = []; + for (var i = 0; i < projectReferences.length; i++) { + var ref = projectReferences[i]; + var resolvedRefOpts = resolvedProjectReferences[i].commandLine; + if (ref.prepend && resolvedRefOpts && resolvedRefOpts.options) { + var out = resolvedRefOpts.options.outFile || resolvedRefOpts.options.out; + // Upstream project didn't have outFile set -- skip (error will have been issued earlier) + if (!out) + continue; + var dtsFilename = ts.changeExtension(out, ".d.ts"); + var js = host.readFile(out) || "/* Input file " + out + " was missing */\r\n"; + var jsMapPath = out + ".map"; // TODO: try to read sourceMappingUrl comment from the file + var jsMap = host.readFile(jsMapPath); + var dts = host.readFile(dtsFilename) || "/* Input file " + dtsFilename + " was missing */\r\n"; + var dtsMapPath = dtsFilename + ".map"; + var dtsMap = host.readFile(dtsMapPath); + var node = ts.createInputFiles(js, dts, jsMap && jsMapPath, jsMap, dtsMap && dtsMapPath, dtsMap); + nodes.push(node); + } + } + return nodes; + } + function isSourceFileFromExternalLibrary(file) { + return !!sourceFilesFoundSearchingNodeModules.get(file.path); + } + function isSourceFileDefaultLibrary(file) { + if (file.hasNoDefaultLib) { + return true; + } + if (!options.noLib) { + return false; + } + // If '--lib' is not specified, include default library file according to '--target' + // otherwise, using options specified in '--lib' instead of '--target' default library file + var equalityComparer = host.useCaseSensitiveFileNames() ? ts.equateStringsCaseSensitive : ts.equateStringsCaseInsensitive; + if (!options.lib) { + return equalityComparer(file.fileName, getDefaultLibraryFileName()); + } + else { + return ts.some(options.lib, function (libFileName) { return equalityComparer(file.fileName, ts.combinePaths(defaultLibraryPath, libFileName)); }); + } + } + function getDiagnosticsProducingTypeChecker() { + return diagnosticsProducingTypeChecker || (diagnosticsProducingTypeChecker = ts.createTypeChecker(program, /*produceDiagnostics:*/ true)); + } + function dropDiagnosticsProducingTypeChecker() { + diagnosticsProducingTypeChecker = undefined; + } + function getTypeChecker() { + return noDiagnosticsTypeChecker || (noDiagnosticsTypeChecker = ts.createTypeChecker(program, /*produceDiagnostics:*/ false)); + } + function emit(sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles, transformers) { + return runWithCancellationToken(function () { return emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles, transformers); }); + } + function isEmitBlocked(emitFileName) { + return hasEmitBlockingDiagnostics.has(toPath(emitFileName)); + } + function emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles, customTransformers) { + var declarationDiagnostics = []; + if (!emitOnlyDtsFiles) { + if (options.noEmit) { + return { diagnostics: declarationDiagnostics, sourceMaps: undefined, emittedFiles: undefined, emitSkipped: true }; + } + // If the noEmitOnError flag is set, then check if we have any errors so far. If so, + // immediately bail out. Note that we pass 'undefined' for 'sourceFile' so that we + // get any preEmit diagnostics, not just the ones + if (options.noEmitOnError) { + var diagnostics = program.getOptionsDiagnostics(cancellationToken).concat(program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken)); + if (diagnostics.length === 0 && ts.getEmitDeclarations(program.getCompilerOptions())) { + declarationDiagnostics = program.getDeclarationDiagnostics(/*sourceFile*/ undefined, cancellationToken); + } + if (diagnostics.length > 0 || declarationDiagnostics.length > 0) { + return { + diagnostics: ts.concatenate(diagnostics, declarationDiagnostics), + sourceMaps: undefined, + emittedFiles: undefined, + emitSkipped: true + }; + } + } + } + // Create the emit resolver outside of the "emitTime" tracking code below. That way + // any cost associated with it (like type checking) are appropriate associated with + // the type-checking counter. + // + // If the -out option is specified, we should not pass the source file to getEmitResolver. + // This is because in the -out scenario all files need to be emitted, and therefore all + // files need to be type checked. And the way to specify that all files need to be type + // checked is to not pass the file to getEmitResolver. + var emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile, cancellationToken); + ts.performance.mark("beforeEmit"); + var transformers = emitOnlyDtsFiles ? [] : ts.getTransformers(options, customTransformers); + var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile, // TODO: GH#18217 + emitOnlyDtsFiles, transformers, customTransformers && customTransformers.afterDeclarations); + ts.performance.mark("afterEmit"); + ts.performance.measure("Emit", "beforeEmit", "afterEmit"); + return emitResult; + } + function getSourceFile(fileName) { + return getSourceFileByPath(toPath(fileName)); + } + function getSourceFileByPath(path) { + return filesByName.get(path); + } + function getDiagnosticsHelper(sourceFile, getDiagnostics, cancellationToken) { + if (sourceFile) { + return getDiagnostics(sourceFile, cancellationToken); + } + return ts.sortAndDeduplicateDiagnostics(ts.flatMap(program.getSourceFiles(), function (sourceFile) { + if (cancellationToken) { + cancellationToken.throwIfCancellationRequested(); + } + return getDiagnostics(sourceFile, cancellationToken); + })); + } + function getSyntacticDiagnostics(sourceFile, cancellationToken) { + return getDiagnosticsHelper(sourceFile, getSyntacticDiagnosticsForFile, cancellationToken); + } + function getSemanticDiagnostics(sourceFile, cancellationToken) { + return getDiagnosticsHelper(sourceFile, getSemanticDiagnosticsForFile, cancellationToken); + } + function getDeclarationDiagnostics(sourceFile, cancellationToken) { + var options = program.getCompilerOptions(); + // collect diagnostics from the program only once if either no source file was specified or out/outFile is set (bundled emit) + if (!sourceFile || options.out || options.outFile) { + return getDeclarationDiagnosticsWorker(sourceFile, cancellationToken); + } + else { + return getDiagnosticsHelper(sourceFile, getDeclarationDiagnosticsForFile, cancellationToken); + } + } + function getSyntacticDiagnosticsForFile(sourceFile) { + // For JavaScript files, we report semantic errors for using TypeScript-only + // constructs from within a JavaScript file as syntactic errors. + if (ts.isSourceFileJS(sourceFile)) { + if (!sourceFile.additionalSyntacticDiagnostics) { + sourceFile.additionalSyntacticDiagnostics = getJSSyntacticDiagnosticsForFile(sourceFile); + } + return ts.concatenate(sourceFile.additionalSyntacticDiagnostics, sourceFile.parseDiagnostics); + } + return sourceFile.parseDiagnostics; + } + function runWithCancellationToken(func) { + try { + return func(); + } + catch (e) { + if (e instanceof ts.OperationCanceledException) { + // We were canceled while performing the operation. Because our type checker + // might be a bad state, we need to throw it away. + // + // Note: we are overly aggressive here. We do not actually *have* to throw away + // the "noDiagnosticsTypeChecker". However, for simplicity, i'd like to keep + // the lifetimes of these two TypeCheckers the same. Also, we generally only + // cancel when the user has made a change anyways. And, in that case, we (the + // program instance) will get thrown away anyways. So trying to keep one of + // these type checkers alive doesn't serve much purpose. + noDiagnosticsTypeChecker = undefined; + diagnosticsProducingTypeChecker = undefined; + } + throw e; + } + } + function getSemanticDiagnosticsForFile(sourceFile, cancellationToken) { + return getAndCacheDiagnostics(sourceFile, cancellationToken, cachedSemanticDiagnosticsForFile, getSemanticDiagnosticsForFileNoCache); + } + function getSemanticDiagnosticsForFileNoCache(sourceFile, cancellationToken) { + return runWithCancellationToken(function () { + if (ts.skipTypeChecking(sourceFile, options)) { + return ts.emptyArray; + } + var typeChecker = getDiagnosticsProducingTypeChecker(); + ts.Debug.assert(!!sourceFile.bindDiagnostics); + var isCheckJs = ts.isCheckJsEnabledForFile(sourceFile, options); + // By default, only type-check .ts, .tsx, 'Deferred' and 'External' files (external files are added by plugins) + var includeBindAndCheckDiagnostics = sourceFile.scriptKind === 3 /* TS */ || sourceFile.scriptKind === 4 /* TSX */ || + sourceFile.scriptKind === 5 /* External */ || isCheckJs || sourceFile.scriptKind === 7 /* Deferred */; + var bindDiagnostics = includeBindAndCheckDiagnostics ? sourceFile.bindDiagnostics : ts.emptyArray; + var checkDiagnostics = includeBindAndCheckDiagnostics ? typeChecker.getDiagnostics(sourceFile, cancellationToken) : ts.emptyArray; + var fileProcessingDiagnosticsInFile = fileProcessingDiagnostics.getDiagnostics(sourceFile.fileName); + var programDiagnosticsInFile = programDiagnostics.getDiagnostics(sourceFile.fileName); + var diagnostics; + for (var _i = 0, _a = [bindDiagnostics, checkDiagnostics, fileProcessingDiagnosticsInFile, programDiagnosticsInFile, isCheckJs ? sourceFile.jsDocDiagnostics : undefined]; _i < _a.length; _i++) { + var diags = _a[_i]; + if (diags) { + for (var _b = 0, diags_1 = diags; _b < diags_1.length; _b++) { + var diag = diags_1[_b]; + if (shouldReportDiagnostic(diag)) { + diagnostics = ts.append(diagnostics, diag); + } + } + } + } + return diagnostics; + }); + } + function getSuggestionDiagnostics(sourceFile, cancellationToken) { + return runWithCancellationToken(function () { + return getDiagnosticsProducingTypeChecker().getSuggestionDiagnostics(sourceFile, cancellationToken); + }); + } + /** + * Skip errors if previous line start with '// @ts-ignore' comment, not counting non-empty non-comment lines + */ + function shouldReportDiagnostic(diagnostic) { + var file = diagnostic.file, start = diagnostic.start; + if (file) { + var lineStarts = ts.getLineStarts(file); + var line = ts.computeLineAndCharacterOfPosition(lineStarts, start).line; // TODO: GH#18217 + while (line > 0) { + var previousLineText = file.text.slice(lineStarts[line - 1], lineStarts[line]); + var result = ignoreDiagnosticCommentRegEx.exec(previousLineText); + if (!result) { + // non-empty line + return true; + } + if (result[3]) { + // @ts-ignore + return false; + } + line--; + } + } + return true; + } + function getJSSyntacticDiagnosticsForFile(sourceFile) { + return runWithCancellationToken(function () { + var diagnostics = []; + var parent = sourceFile; + walk(sourceFile); + return diagnostics; + function walk(node) { + // Return directly from the case if the given node doesnt want to visit each child + // Otherwise break to visit each child + switch (parent.kind) { + case 151 /* Parameter */: + case 154 /* PropertyDeclaration */: + if (parent.questionToken === node) { + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, "?")); + return; + } + // falls through + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 196 /* FunctionExpression */: + case 239 /* FunctionDeclaration */: + case 197 /* ArrowFunction */: + case 237 /* VariableDeclaration */: + // type annotation + if (parent.type === node) { + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.types_can_only_be_used_in_a_ts_file)); + return; + } + } + switch (node.kind) { + case 248 /* ImportEqualsDeclaration */: + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.import_can_only_be_used_in_a_ts_file)); + return; + case 254 /* ExportAssignment */: + if (node.isExportEquals) { + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.export_can_only_be_used_in_a_ts_file)); + return; + } + break; + case 273 /* HeritageClause */: + var heritageClause = node; + if (heritageClause.token === 109 /* ImplementsKeyword */) { + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.implements_clauses_can_only_be_used_in_a_ts_file)); + return; + } + break; + case 241 /* InterfaceDeclaration */: + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.interface_declarations_can_only_be_used_in_a_ts_file)); + return; + case 244 /* ModuleDeclaration */: + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.module_declarations_can_only_be_used_in_a_ts_file)); + return; + case 242 /* TypeAliasDeclaration */: + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.type_aliases_can_only_be_used_in_a_ts_file)); + return; + case 243 /* EnumDeclaration */: + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.enum_declarations_can_only_be_used_in_a_ts_file)); + return; + case 213 /* NonNullExpression */: + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.non_null_assertions_can_only_be_used_in_a_ts_file)); + return; + case 212 /* AsExpression */: + diagnostics.push(createDiagnosticForNode(node.type, ts.Diagnostics.type_assertion_expressions_can_only_be_used_in_a_ts_file)); + return; + case 194 /* TypeAssertionExpression */: + ts.Debug.fail(); // Won't parse these in a JS file anyway, as they are interpreted as JSX. + } + var prevParent = parent; + parent = node; + ts.forEachChild(node, walk, walkArray); + parent = prevParent; + } + function walkArray(nodes) { + if (parent.decorators === nodes && !options.experimentalDecorators) { + diagnostics.push(createDiagnosticForNode(parent, ts.Diagnostics.Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_to_remove_this_warning)); + } + switch (parent.kind) { + case 240 /* ClassDeclaration */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 196 /* FunctionExpression */: + case 239 /* FunctionDeclaration */: + case 197 /* ArrowFunction */: + // Check type parameters + if (nodes === parent.typeParameters) { + diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.type_parameter_declarations_can_only_be_used_in_a_ts_file)); + return; + } + // falls through + case 219 /* VariableStatement */: + // Check modifiers + if (nodes === parent.modifiers) { + return checkModifiers(nodes, parent.kind === 219 /* VariableStatement */); + } + break; + case 154 /* PropertyDeclaration */: + // Check modifiers of property declaration + if (nodes === parent.modifiers) { + for (var _i = 0, _a = nodes; _i < _a.length; _i++) { + var modifier = _a[_i]; + if (modifier.kind !== 116 /* StaticKeyword */) { + diagnostics.push(createDiagnosticForNode(modifier, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, ts.tokenToString(modifier.kind))); + } + } + return; + } + break; + case 151 /* Parameter */: + // Check modifiers of parameter declaration + if (nodes === parent.modifiers) { + diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.parameter_modifiers_can_only_be_used_in_a_ts_file)); + return; + } + break; + case 191 /* CallExpression */: + case 192 /* NewExpression */: + case 211 /* ExpressionWithTypeArguments */: + case 261 /* JsxSelfClosingElement */: + case 262 /* JsxOpeningElement */: + // Check type arguments + if (nodes === parent.typeArguments) { + diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.type_arguments_can_only_be_used_in_a_ts_file)); + return; + } + break; + } + for (var _b = 0, nodes_6 = nodes; _b < nodes_6.length; _b++) { + var node = nodes_6[_b]; + walk(node); + } + } + function checkModifiers(modifiers, isConstValid) { + for (var _i = 0, modifiers_1 = modifiers; _i < modifiers_1.length; _i++) { + var modifier = modifiers_1[_i]; + switch (modifier.kind) { + case 77 /* ConstKeyword */: + if (isConstValid) { + continue; + } + // to report error, + // falls through + case 115 /* PublicKeyword */: + case 113 /* PrivateKeyword */: + case 114 /* ProtectedKeyword */: + case 133 /* ReadonlyKeyword */: + case 125 /* DeclareKeyword */: + case 118 /* AbstractKeyword */: + diagnostics.push(createDiagnosticForNode(modifier, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, ts.tokenToString(modifier.kind))); + break; + // These are all legal modifiers. + case 116 /* StaticKeyword */: + case 85 /* ExportKeyword */: + case 80 /* DefaultKeyword */: + } + } + } + function createDiagnosticForNodeArray(nodes, message, arg0, arg1, arg2) { + var start = nodes.pos; + return ts.createFileDiagnostic(sourceFile, start, nodes.end - start, message, arg0, arg1, arg2); + } + // Since these are syntactic diagnostics, parent might not have been set + // this means the sourceFile cannot be infered from the node + function createDiagnosticForNode(node, message, arg0, arg1, arg2) { + return ts.createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2); + } + }); + } + function getDeclarationDiagnosticsWorker(sourceFile, cancellationToken) { + return getAndCacheDiagnostics(sourceFile, cancellationToken, cachedDeclarationDiagnosticsForFile, getDeclarationDiagnosticsForFileNoCache); + } + function getDeclarationDiagnosticsForFileNoCache(sourceFile, cancellationToken) { + return runWithCancellationToken(function () { + var resolver = getDiagnosticsProducingTypeChecker().getEmitResolver(sourceFile, cancellationToken); + // Don't actually write any files since we're just getting diagnostics. + return ts.getDeclarationDiagnostics(getEmitHost(ts.noop), resolver, sourceFile); + }); + } + function getAndCacheDiagnostics(sourceFile, cancellationToken, cache, getDiagnostics) { + var cachedResult = sourceFile + ? cache.perFile && cache.perFile.get(sourceFile.path) + : cache.allDiagnostics; + if (cachedResult) { + return cachedResult; + } + var result = getDiagnostics(sourceFile, cancellationToken) || ts.emptyArray; // TODO: GH#18217 + if (sourceFile) { + if (!cache.perFile) { + cache.perFile = ts.createMap(); + } + cache.perFile.set(sourceFile.path, result); + } + else { + cache.allDiagnostics = result; + } + return result; + } + function getDeclarationDiagnosticsForFile(sourceFile, cancellationToken) { + return sourceFile.isDeclarationFile ? [] : getDeclarationDiagnosticsWorker(sourceFile, cancellationToken); + } + function getOptionsDiagnostics() { + return ts.sortAndDeduplicateDiagnostics(ts.concatenate(fileProcessingDiagnostics.getGlobalDiagnostics(), ts.concatenate(programDiagnostics.getGlobalDiagnostics(), getOptionsDiagnosticsOfConfigFile()))); + } + function getOptionsDiagnosticsOfConfigFile() { + if (!options.configFile) { + return ts.emptyArray; + } + var diagnostics = programDiagnostics.getDiagnostics(options.configFile.fileName); + forEachResolvedProjectReference(function (resolvedRef) { + if (resolvedRef) { + diagnostics = ts.concatenate(diagnostics, programDiagnostics.getDiagnostics(resolvedRef.sourceFile.fileName)); + } + }); + return diagnostics; + } + function getGlobalDiagnostics() { + return rootNames.length ? ts.sortAndDeduplicateDiagnostics(getDiagnosticsProducingTypeChecker().getGlobalDiagnostics().slice()) : ts.emptyArray; + } + function getConfigFileParsingDiagnostics() { + return configFileParsingDiagnostics || ts.emptyArray; + } + function processRootFile(fileName, isDefaultLib, ignoreNoDefaultLib) { + processSourceFile(ts.normalizePath(fileName), isDefaultLib, ignoreNoDefaultLib, /*packageId*/ undefined); + } + function fileReferenceIsEqualTo(a, b) { + return a.fileName === b.fileName; + } + function moduleNameIsEqualTo(a, b) { + return a.kind === 72 /* Identifier */ + ? b.kind === 72 /* Identifier */ && a.escapedText === b.escapedText + : b.kind === 10 /* StringLiteral */ && a.text === b.text; + } + function collectExternalModuleReferences(file) { + if (file.imports) { + return; + } + var isJavaScriptFile = ts.isSourceFileJS(file); + var isExternalModuleFile = ts.isExternalModule(file); + // file.imports may not be undefined if there exists dynamic import + var imports; + var moduleAugmentations; + var ambientModules; + // If we are importing helpers, we need to add a synthetic reference to resolve the + // helpers library. + if (options.importHelpers + && (options.isolatedModules || isExternalModuleFile) + && !file.isDeclarationFile) { + // synthesize 'import "tslib"' declaration + var externalHelpersModuleReference = ts.createLiteral(ts.externalHelpersModuleNameText); + var importDecl = ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*importClause*/ undefined, externalHelpersModuleReference); + ts.addEmitFlags(importDecl, 67108864 /* NeverApplyImportHelper */); + externalHelpersModuleReference.parent = importDecl; + importDecl.parent = file; + imports = [externalHelpersModuleReference]; + } + for (var _i = 0, _a = file.statements; _i < _a.length; _i++) { + var node = _a[_i]; + collectModuleReferences(node, /*inAmbientModule*/ false); + } + if ((file.flags & 524288 /* PossiblyContainsDynamicImport */) || isJavaScriptFile) { + collectDynamicImportOrRequireCalls(file); + } + file.imports = imports || ts.emptyArray; + file.moduleAugmentations = moduleAugmentations || ts.emptyArray; + file.ambientModuleNames = ambientModules || ts.emptyArray; + return; + function collectModuleReferences(node, inAmbientModule) { + if (ts.isAnyImportOrReExport(node)) { + var moduleNameExpr = ts.getExternalModuleName(node); + // TypeScript 1.0 spec (April 2014): 12.1.6 + // An ExternalImportDeclaration in an AmbientExternalModuleDeclaration may reference other external modules + // only through top - level external module names. Relative external module names are not permitted. + if (moduleNameExpr && ts.isStringLiteral(moduleNameExpr) && moduleNameExpr.text && (!inAmbientModule || !ts.isExternalModuleNameRelative(moduleNameExpr.text))) { + imports = ts.append(imports, moduleNameExpr); + } + } + else if (ts.isModuleDeclaration(node)) { + if (ts.isAmbientModule(node) && (inAmbientModule || ts.hasModifier(node, 2 /* Ambient */) || file.isDeclarationFile)) { + var nameText = ts.getTextOfIdentifierOrLiteral(node.name); + // Ambient module declarations can be interpreted as augmentations for some existing external modules. + // This will happen in two cases: + // - if current file is external module then module augmentation is a ambient module declaration defined in the top level scope + // - if current file is not external module then module augmentation is an ambient module declaration with non-relative module name + // immediately nested in top level ambient module declaration . + if (isExternalModuleFile || (inAmbientModule && !ts.isExternalModuleNameRelative(nameText))) { + (moduleAugmentations || (moduleAugmentations = [])).push(node.name); + } + else if (!inAmbientModule) { + if (file.isDeclarationFile) { + // for global .d.ts files record name of ambient module + (ambientModules || (ambientModules = [])).push(nameText); + } + // An AmbientExternalModuleDeclaration declares an external module. + // This type of declaration is permitted only in the global module. + // The StringLiteral must specify a top - level external module name. + // Relative external module names are not permitted + // NOTE: body of ambient module is always a module block, if it exists + var body = node.body; + if (body) { + for (var _i = 0, _a = body.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + collectModuleReferences(statement, /*inAmbientModule*/ true); + } + } + } + } + } + } + function collectDynamicImportOrRequireCalls(file) { + var r = /import|require/g; + while (r.exec(file.text) !== null) { + var node = getNodeAtPosition(file, r.lastIndex); + if (ts.isRequireCall(node, /*checkArgumentIsStringLiteralLike*/ true)) { + imports = ts.append(imports, node.arguments[0]); + } + // we have to check the argument list has length of 1. We will still have to process these even though we have parsing error. + else if (ts.isImportCall(node) && node.arguments.length === 1 && ts.isStringLiteralLike(node.arguments[0])) { + imports = ts.append(imports, node.arguments[0]); + } + else if (ts.isLiteralImportTypeNode(node)) { + imports = ts.append(imports, node.argument.literal); + } + } + } + /** Returns a token if position is in [start-of-leading-trivia, end), includes JSDoc only in JS files */ + function getNodeAtPosition(sourceFile, position) { + var current = sourceFile; + var getContainingChild = function (child) { + if (child.pos <= position && (position < child.end || (position === child.end && (child.kind === 1 /* EndOfFileToken */)))) { + return child; + } + }; + while (true) { + var child = isJavaScriptFile && ts.hasJSDocNodes(current) && ts.forEach(current.jsDoc, getContainingChild) || ts.forEachChild(current, getContainingChild); + if (!child) { + return current; + } + current = child; + } + } + } + function getLibFileFromReference(ref) { + var libName = ref.fileName.toLocaleLowerCase(); + var libFileName = ts.libMap.get(libName); + if (libFileName) { + return getSourceFile(ts.combinePaths(defaultLibraryPath, libFileName)); + } + } + /** This should have similar behavior to 'processSourceFile' without diagnostics or mutation. */ + function getSourceFileFromReference(referencingFile, ref) { + return getSourceFileFromReferenceWorker(resolveTripleslashReference(ref.fileName, referencingFile.fileName), function (fileName) { return filesByName.get(toPath(fileName)); }); + } + function getSourceFileFromReferenceWorker(fileName, getSourceFile, fail, refFile) { + if (ts.hasExtension(fileName)) { + if (!options.allowNonTsExtensions && !ts.forEach(supportedExtensionsWithJsonIfResolveJsonModule, function (extension) { return ts.fileExtensionIs(host.getCanonicalFileName(fileName), extension); })) { + if (fail) + fail(ts.Diagnostics.File_0_has_unsupported_extension_The_only_supported_extensions_are_1, fileName, "'" + supportedExtensions.join("', '") + "'"); + return undefined; + } + var sourceFile = getSourceFile(fileName); + if (fail) { + if (!sourceFile) { + var redirect = getProjectReferenceRedirect(fileName); + if (redirect) { + fail(ts.Diagnostics.Output_file_0_has_not_been_built_from_source_file_1, redirect, fileName); + } + else { + fail(ts.Diagnostics.File_0_not_found, fileName); + } + } + else if (refFile && host.getCanonicalFileName(fileName) === host.getCanonicalFileName(refFile.fileName)) { + fail(ts.Diagnostics.A_file_cannot_have_a_reference_to_itself); + } + } + return sourceFile; + } + else { + var sourceFileNoExtension = options.allowNonTsExtensions && getSourceFile(fileName); + if (sourceFileNoExtension) + return sourceFileNoExtension; + if (fail && options.allowNonTsExtensions) { + fail(ts.Diagnostics.File_0_not_found, fileName); + return undefined; + } + var sourceFileWithAddedExtension = ts.forEach(supportedExtensions, function (extension) { return getSourceFile(fileName + extension); }); + if (fail && !sourceFileWithAddedExtension) + fail(ts.Diagnostics.File_0_not_found, fileName + ".ts" /* Ts */); + return sourceFileWithAddedExtension; + } + } + /** This has side effects through `findSourceFile`. */ + function processSourceFile(fileName, isDefaultLib, ignoreNoDefaultLib, packageId, refFile, refPos, refEnd) { + getSourceFileFromReferenceWorker(fileName, function (fileName) { return findSourceFile(fileName, toPath(fileName), isDefaultLib, ignoreNoDefaultLib, refFile, refPos, refEnd, packageId); }, // TODO: GH#18217 + function (diagnostic) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + fileProcessingDiagnostics.add(refFile !== undefined && refEnd !== undefined && refPos !== undefined + ? ts.createFileDiagnostic.apply(void 0, [refFile, refPos, refEnd - refPos, diagnostic].concat(args)) : ts.createCompilerDiagnostic.apply(void 0, [diagnostic].concat(args))); + }, refFile); + } + function reportFileNamesDifferOnlyInCasingError(fileName, existingFileName, refFile, refPos, refEnd) { + if (refFile !== undefined && refPos !== undefined && refEnd !== undefined) { + fileProcessingDiagnostics.add(ts.createFileDiagnostic(refFile, refPos, refEnd - refPos, ts.Diagnostics.File_name_0_differs_from_already_included_file_name_1_only_in_casing, fileName, existingFileName)); + } + else { + fileProcessingDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_name_0_differs_from_already_included_file_name_1_only_in_casing, fileName, existingFileName)); + } + } + function createRedirectSourceFile(redirectTarget, unredirected, fileName, path, resolvedPath, originalFileName) { + var redirect = Object.create(redirectTarget); + redirect.fileName = fileName; + redirect.path = path; + redirect.resolvedPath = resolvedPath; + redirect.originalFileName = originalFileName; + redirect.redirectInfo = { redirectTarget: redirectTarget, unredirected: unredirected }; + sourceFilesFoundSearchingNodeModules.set(path, currentNodeModulesDepth > 0); + Object.defineProperties(redirect, { + id: { + get: function () { return this.redirectInfo.redirectTarget.id; }, + set: function (value) { this.redirectInfo.redirectTarget.id = value; }, + }, + symbol: { + get: function () { return this.redirectInfo.redirectTarget.symbol; }, + set: function (value) { this.redirectInfo.redirectTarget.symbol = value; }, + }, + }); + return redirect; + } + // Get source file from normalized fileName + function findSourceFile(fileName, path, isDefaultLib, ignoreNoDefaultLib, refFile, refPos, refEnd, packageId) { + var originalFileName = fileName; + if (filesByName.has(path)) { + var file_1 = filesByName.get(path); + // try to check if we've already seen this file but with a different casing in path + // NOTE: this only makes sense for case-insensitive file systems, and only on files which are not redirected + if (file_1 && options.forceConsistentCasingInFileNames) { + var inputName = fileName; + var checkedName = file_1.fileName; + var isRedirect = toPath(checkedName) !== toPath(inputName); + if (isRedirect) { + inputName = getProjectReferenceRedirect(fileName) || fileName; + } + if (ts.getNormalizedAbsolutePath(checkedName, currentDirectory) !== ts.getNormalizedAbsolutePath(inputName, currentDirectory)) { + reportFileNamesDifferOnlyInCasingError(inputName, checkedName, refFile, refPos, refEnd); + } + } + // If the file was previously found via a node_modules search, but is now being processed as a root file, + // then everything it sucks in may also be marked incorrectly, and needs to be checked again. + if (file_1 && sourceFilesFoundSearchingNodeModules.get(file_1.path) && currentNodeModulesDepth === 0) { + sourceFilesFoundSearchingNodeModules.set(file_1.path, false); + if (!options.noResolve) { + processReferencedFiles(file_1, isDefaultLib); + processTypeReferenceDirectives(file_1); + } + processLibReferenceDirectives(file_1); + modulesWithElidedImports.set(file_1.path, false); + processImportedModules(file_1); + } + // See if we need to reprocess the imports due to prior skipped imports + else if (file_1 && modulesWithElidedImports.get(file_1.path)) { + if (currentNodeModulesDepth < maxNodeModuleJsDepth) { + modulesWithElidedImports.set(file_1.path, false); + processImportedModules(file_1); + } + } + return file_1; + } + var redirectedPath; + if (refFile) { + var redirect = getProjectReferenceRedirect(fileName); + if (redirect) { + (refFile.redirectedReferences || (refFile.redirectedReferences = [])).push(fileName); + fileName = redirect; + // Once we start redirecting to a file, we can potentially come back to it + // via a back-reference from another file in the .d.ts folder. If that happens we'll + // end up trying to add it to the program *again* because we were tracking it via its + // original (un-redirected) name. So we have to map both the original path and the redirected path + // to the source file we're about to find/create + redirectedPath = toPath(redirect); + } + } + // We haven't looked for this file, do so now and cache result + var file = host.getSourceFile(fileName, options.target, function (hostErrorMessage) { + if (refFile !== undefined && refPos !== undefined && refEnd !== undefined) { + fileProcessingDiagnostics.add(ts.createFileDiagnostic(refFile, refPos, refEnd - refPos, ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, hostErrorMessage)); + } + else { + fileProcessingDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, hostErrorMessage)); + } + }, shouldCreateNewSourceFile); + if (packageId) { + var packageIdKey = ts.packageIdToString(packageId); + var fileFromPackageId = packageIdToSourceFile.get(packageIdKey); + if (fileFromPackageId) { + // Some other SourceFile already exists with this package name and version. + // Instead of creating a duplicate, just redirect to the existing one. + var dupFile = createRedirectSourceFile(fileFromPackageId, file, fileName, path, toPath(fileName), originalFileName); // TODO: GH#18217 + redirectTargetsMap.add(fileFromPackageId.path, fileName); + addFileToFilesByName(dupFile, path, redirectedPath); + sourceFileToPackageName.set(path, packageId.name); + processingOtherFiles.push(dupFile); + return dupFile; + } + else if (file) { + // This is the first source file to have this packageId. + packageIdToSourceFile.set(packageIdKey, file); + sourceFileToPackageName.set(path, packageId.name); + } + } + addFileToFilesByName(file, path, redirectedPath); + if (file) { + sourceFilesFoundSearchingNodeModules.set(path, currentNodeModulesDepth > 0); + file.path = path; + file.resolvedPath = toPath(fileName); + file.originalFileName = originalFileName; + if (host.useCaseSensitiveFileNames()) { + var pathLowerCase = path.toLowerCase(); + // for case-sensitive file systems check if we've already seen some file with similar filename ignoring case + var existingFile = filesByNameIgnoreCase.get(pathLowerCase); + if (existingFile) { + reportFileNamesDifferOnlyInCasingError(fileName, existingFile.fileName, refFile, refPos, refEnd); + } + else { + filesByNameIgnoreCase.set(pathLowerCase, file); + } + } + skipDefaultLib = skipDefaultLib || (file.hasNoDefaultLib && !ignoreNoDefaultLib); + if (!options.noResolve) { + processReferencedFiles(file, isDefaultLib); + processTypeReferenceDirectives(file); + } + processLibReferenceDirectives(file); + // always process imported modules to record module name resolutions + processImportedModules(file); + if (isDefaultLib) { + processingDefaultLibFiles.push(file); + } + else { + processingOtherFiles.push(file); + } + } + return file; + } + function addFileToFilesByName(file, path, redirectedPath) { + filesByName.set(path, file); + if (redirectedPath) { + filesByName.set(redirectedPath, file); + } + } + function getProjectReferenceRedirect(fileName) { + // Ignore dts or any of the non ts files + if (!resolvedProjectReferences || !resolvedProjectReferences.length || ts.fileExtensionIs(fileName, ".d.ts" /* Dts */) || !ts.fileExtensionIsOneOf(fileName, ts.supportedTSExtensions)) { + return undefined; + } + // If this file is produced by a referenced project, we need to rewrite it to + // look in the output folder of the referenced project rather than the input + var referencedProject = getResolvedProjectReferenceToRedirect(fileName); + if (!referencedProject) { + return undefined; + } + var out = referencedProject.commandLine.options.outFile || referencedProject.commandLine.options.out; + return out ? + ts.changeExtension(out, ".d.ts" /* Dts */) : + ts.getOutputDeclarationFileName(fileName, referencedProject.commandLine); + } + /** + * Get the referenced project if the file is input file from that reference project + */ + function getResolvedProjectReferenceToRedirect(fileName) { + if (mapFromFileToProjectReferenceRedirects === undefined) { + mapFromFileToProjectReferenceRedirects = ts.createMap(); + forEachResolvedProjectReference(function (referencedProject, referenceProjectPath) { + // not input file from the referenced project, ignore + if (referencedProject && + toPath(options.configFilePath) !== referenceProjectPath) { + referencedProject.commandLine.fileNames.forEach(function (f) { + return mapFromFileToProjectReferenceRedirects.set(toPath(f), referenceProjectPath); + }); + } + }); + } + var referencedProjectPath = mapFromFileToProjectReferenceRedirects.get(toPath(fileName)); + return referencedProjectPath && getResolvedProjectReferenceByPath(referencedProjectPath); + } + function forEachResolvedProjectReference(cb) { + return forEachProjectReference(projectReferences, resolvedProjectReferences, function (resolvedRef, index, parent) { + var ref = (parent ? parent.commandLine.projectReferences : projectReferences)[index]; + var resolvedRefPath = toPath(resolveProjectReferencePath(ref)); + return cb(resolvedRef, resolvedRefPath); + }); + } + function forEachProjectReference(projectReferences, resolvedProjectReferences, cbResolvedRef, cbRef) { + var seenResolvedRefs; + return worker(projectReferences, resolvedProjectReferences, /*parent*/ undefined, cbResolvedRef, cbRef); + function worker(projectReferences, resolvedProjectReferences, parent, cbResolvedRef, cbRef) { + // Visit project references first + if (cbRef) { + var result = cbRef(projectReferences, parent); + if (result) { + return result; + } + } + return ts.forEach(resolvedProjectReferences, function (resolvedRef, index) { + if (ts.contains(seenResolvedRefs, resolvedRef)) { + // ignore recursives + return undefined; + } + var result = cbResolvedRef(resolvedRef, index, parent); + if (result) { + return result; + } + if (!resolvedRef) + return undefined; + (seenResolvedRefs || (seenResolvedRefs = [])).push(resolvedRef); + return worker(resolvedRef.commandLine.projectReferences, resolvedRef.references, resolvedRef, cbResolvedRef, cbRef); + }); + } + } + function getResolvedProjectReferenceByPath(projectReferencePath) { + if (!projectReferenceRedirects) { + return undefined; + } + return projectReferenceRedirects.get(projectReferencePath) || undefined; + } + function processReferencedFiles(file, isDefaultLib) { + ts.forEach(file.referencedFiles, function (ref) { + var referencedFileName = resolveTripleslashReference(ref.fileName, file.originalFileName); + processSourceFile(referencedFileName, isDefaultLib, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined, file, ref.pos, ref.end); + }); + } + function processTypeReferenceDirectives(file) { + // We lower-case all type references because npm automatically lowercases all packages. See GH#9824. + var typeDirectives = ts.map(file.typeReferenceDirectives, function (ref) { return ref.fileName.toLocaleLowerCase(); }); + if (!typeDirectives) { + return; + } + var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeDirectives, file.originalFileName, getResolvedProjectReferenceToRedirect(file.originalFileName)); + for (var i = 0; i < typeDirectives.length; i++) { + var ref = file.typeReferenceDirectives[i]; + var resolvedTypeReferenceDirective = resolutions[i]; + // store resolved type directive on the file + var fileName = ref.fileName.toLocaleLowerCase(); + ts.setResolvedTypeReferenceDirective(file, fileName, resolvedTypeReferenceDirective); + processTypeReferenceDirective(fileName, resolvedTypeReferenceDirective, file, ref.pos, ref.end); + } + } + function processTypeReferenceDirective(typeReferenceDirective, resolvedTypeReferenceDirective, refFile, refPos, refEnd) { + // If we already found this library as a primary reference - nothing to do + var previousResolution = resolvedTypeReferenceDirectives.get(typeReferenceDirective); + if (previousResolution && previousResolution.primary) { + return; + } + var saveResolution = true; + if (resolvedTypeReferenceDirective) { + if (resolvedTypeReferenceDirective.isExternalLibraryImport) + currentNodeModulesDepth++; + if (resolvedTypeReferenceDirective.primary) { + // resolved from the primary path + processSourceFile(resolvedTypeReferenceDirective.resolvedFileName, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, resolvedTypeReferenceDirective.packageId, refFile, refPos, refEnd); // TODO: GH#18217 + } + else { + // If we already resolved to this file, it must have been a secondary reference. Check file contents + // for sameness and possibly issue an error + if (previousResolution) { + // Don't bother reading the file again if it's the same file. + if (resolvedTypeReferenceDirective.resolvedFileName !== previousResolution.resolvedFileName) { + var otherFileText = host.readFile(resolvedTypeReferenceDirective.resolvedFileName); + if (otherFileText !== getSourceFile(previousResolution.resolvedFileName).text) { + fileProcessingDiagnostics.add(createDiagnostic(refFile, refPos, refEnd, // TODO: GH#18217 + ts.Diagnostics.Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict, typeReferenceDirective, resolvedTypeReferenceDirective.resolvedFileName, previousResolution.resolvedFileName)); + } + } + // don't overwrite previous resolution result + saveResolution = false; + } + else { + // First resolution of this library + processSourceFile(resolvedTypeReferenceDirective.resolvedFileName, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, resolvedTypeReferenceDirective.packageId, refFile, refPos, refEnd); + } + } + if (resolvedTypeReferenceDirective.isExternalLibraryImport) + currentNodeModulesDepth--; + } + else { + fileProcessingDiagnostics.add(createDiagnostic(refFile, refPos, refEnd, ts.Diagnostics.Cannot_find_type_definition_file_for_0, typeReferenceDirective)); // TODO: GH#18217 + } + if (saveResolution) { + resolvedTypeReferenceDirectives.set(typeReferenceDirective, resolvedTypeReferenceDirective); + } + } + function processLibReferenceDirectives(file) { + ts.forEach(file.libReferenceDirectives, function (libReference) { + var libName = libReference.fileName.toLocaleLowerCase(); + var libFileName = ts.libMap.get(libName); + if (libFileName) { + // we ignore any 'no-default-lib' reference set on this file. + processRootFile(ts.combinePaths(defaultLibraryPath, libFileName), /*isDefaultLib*/ true, /*ignoreNoDefaultLib*/ true); + } + else { + var unqualifiedLibName = ts.removeSuffix(ts.removePrefix(libName, "lib."), ".d.ts"); + var suggestion = ts.getSpellingSuggestion(unqualifiedLibName, ts.libs, ts.identity); + var message = suggestion ? ts.Diagnostics.Cannot_find_lib_definition_for_0_Did_you_mean_1 : ts.Diagnostics.Cannot_find_lib_definition_for_0; + fileProcessingDiagnostics.add(createDiagnostic(file, libReference.pos, libReference.end, message, libName, suggestion)); + } + }); + } + function createDiagnostic(refFile, refPos, refEnd, message) { + var args = []; + for (var _i = 4; _i < arguments.length; _i++) { + args[_i - 4] = arguments[_i]; + } + if (refFile === undefined || refPos === undefined || refEnd === undefined) { + return ts.createCompilerDiagnostic.apply(void 0, [message].concat(args)); + } + else { + return ts.createFileDiagnostic.apply(void 0, [refFile, refPos, refEnd - refPos, message].concat(args)); + } + } + function getCanonicalFileName(fileName) { + return host.getCanonicalFileName(fileName); + } + function processImportedModules(file) { + collectExternalModuleReferences(file); + if (file.imports.length || file.moduleAugmentations.length) { + // Because global augmentation doesn't have string literal name, we can check for global augmentation as such. + var moduleNames = getModuleNames(file); + var resolutions = resolveModuleNamesReusingOldState(moduleNames, ts.getNormalizedAbsolutePath(file.originalFileName, currentDirectory), file); + ts.Debug.assert(resolutions.length === moduleNames.length); + for (var i = 0; i < moduleNames.length; i++) { + var resolution = resolutions[i]; + ts.setResolvedModule(file, moduleNames[i], resolution); + if (!resolution) { + continue; + } + var isFromNodeModulesSearch = resolution.isExternalLibraryImport; + var isJsFile = !ts.resolutionExtensionIsTSOrJson(resolution.extension); + var isJsFileFromNodeModules = isFromNodeModulesSearch && isJsFile; + var resolvedFileName = resolution.resolvedFileName; + if (isFromNodeModulesSearch) { + currentNodeModulesDepth++; + } + // add file to program only if: + // - resolution was successful + // - noResolve is falsy + // - module name comes from the list of imports + // - it's not a top level JavaScript module that exceeded the search max + var elideImport = isJsFileFromNodeModules && currentNodeModulesDepth > maxNodeModuleJsDepth; + // Don't add the file if it has a bad extension (e.g. 'tsx' if we don't have '--allowJs') + // This may still end up being an untyped module -- the file won't be included but imports will be allowed. + var shouldAddFile = resolvedFileName + && !getResolutionDiagnostic(options, resolution) + && !options.noResolve + && i < file.imports.length + && !elideImport + && !(isJsFile && !options.allowJs) + && (ts.isInJSFile(file.imports[i]) || !(file.imports[i].flags & 2097152 /* JSDoc */)); + if (elideImport) { + modulesWithElidedImports.set(file.path, true); + } + else if (shouldAddFile) { + var path = toPath(resolvedFileName); + var pos = ts.skipTrivia(file.text, file.imports[i].pos); + findSourceFile(resolvedFileName, path, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, file, pos, file.imports[i].end, resolution.packageId); + } + if (isFromNodeModulesSearch) { + currentNodeModulesDepth--; + } + } + } + else { + // no imports - drop cached module resolutions + file.resolvedModules = undefined; + } + } + function computeCommonSourceDirectory(sourceFiles) { + var fileNames = ts.mapDefined(sourceFiles, function (file) { return file.isDeclarationFile ? undefined : file.fileName; }); + return computeCommonSourceDirectoryOfFilenames(fileNames, currentDirectory, getCanonicalFileName); + } + function checkSourceFilesBelongToPath(sourceFiles, rootDirectory) { + var allFilesBelongToPath = true; + var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory)); + for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) { + var sourceFile = sourceFiles_2[_i]; + if (!sourceFile.isDeclarationFile) { + var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); + if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, sourceFile.fileName, rootDirectory)); + allFilesBelongToPath = false; + } + } + } + return allFilesBelongToPath; + } + function parseProjectReferenceConfigFile(ref) { + if (!projectReferenceRedirects) { + projectReferenceRedirects = ts.createMap(); + } + // The actual filename (i.e. add "/tsconfig.json" if necessary) + var refPath = resolveProjectReferencePath(ref); + var sourceFilePath = toPath(refPath); + var fromCache = projectReferenceRedirects.get(sourceFilePath); + if (fromCache !== undefined) { + return fromCache || undefined; + } + // An absolute path pointing to the containing directory of the config file + var basePath = ts.getNormalizedAbsolutePath(ts.getDirectoryPath(refPath), host.getCurrentDirectory()); + var sourceFile = host.getSourceFile(refPath, 100 /* JSON */); + addFileToFilesByName(sourceFile, sourceFilePath, /*redirectedPath*/ undefined); + if (sourceFile === undefined) { + projectReferenceRedirects.set(sourceFilePath, false); + return undefined; + } + sourceFile.path = sourceFilePath; + sourceFile.resolvedPath = sourceFilePath; + sourceFile.originalFileName = refPath; + var commandLine = ts.parseJsonSourceFileConfigFileContent(sourceFile, configParsingHost, basePath, /*existingOptions*/ undefined, refPath); + var resolvedRef = { commandLine: commandLine, sourceFile: sourceFile }; + projectReferenceRedirects.set(sourceFilePath, resolvedRef); + if (commandLine.projectReferences) { + resolvedRef.references = commandLine.projectReferences.map(parseProjectReferenceConfigFile); + } + return resolvedRef; + } + function verifyCompilerOptions() { + if (options.strictPropertyInitialization && !ts.getStrictOptionValue(options, "strictNullChecks")) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "strictPropertyInitialization", "strictNullChecks"); + } + if (options.isolatedModules) { + if (ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, getEmitDeclarationOptionName(options), "isolatedModules"); + } + if (options.noEmitOnError) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmitOnError", "isolatedModules"); + } + if (options.out) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "out", "isolatedModules"); + } + if (options.outFile) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "outFile", "isolatedModules"); + } + } + if (options.inlineSourceMap) { + if (options.sourceMap) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "sourceMap", "inlineSourceMap"); + } + if (options.mapRoot) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "mapRoot", "inlineSourceMap"); + } + } + if (options.paths && options.baseUrl === undefined) { + createDiagnosticForOptionName(ts.Diagnostics.Option_paths_cannot_be_used_without_specifying_baseUrl_option, "paths"); + } + if (options.composite) { + if (options.declaration === false) { + createDiagnosticForOptionName(ts.Diagnostics.Composite_projects_may_not_disable_declaration_emit, "declaration"); + } + } + verifyProjectReferences(); + // List of collected files is complete; validate exhautiveness if this is a project with a file list + if (options.composite) { + var sourceFiles = files.filter(function (f) { return !f.isDeclarationFile; }); + if (rootNames.length < sourceFiles.length) { + var normalizedRootNames = rootNames.map(function (r) { return ts.normalizePath(r).toLowerCase(); }); + for (var _i = 0, _a = sourceFiles.map(function (f) { return ts.normalizePath(f.path).toLowerCase(); }); _i < _a.length; _i++) { + var file = _a[_i]; + if (normalizedRootNames.indexOf(file) === -1) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern, file)); + } + } + } + } + if (options.paths) { + for (var key in options.paths) { + if (!ts.hasProperty(options.paths, key)) { + continue; + } + if (!ts.hasZeroOrOneAsteriskCharacter(key)) { + createDiagnosticForOptionPaths(/*onKey*/ true, key, ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, key); + } + if (ts.isArray(options.paths[key])) { + var len = options.paths[key].length; + if (len === 0) { + createDiagnosticForOptionPaths(/*onKey*/ false, key, ts.Diagnostics.Substitutions_for_pattern_0_shouldn_t_be_an_empty_array, key); + } + for (var i = 0; i < len; i++) { + var subst = options.paths[key][i]; + var typeOfSubst = typeof subst; + if (typeOfSubst === "string") { + if (!ts.hasZeroOrOneAsteriskCharacter(subst)) { + createDiagnosticForOptionPathKeyValue(key, i, ts.Diagnostics.Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character, subst, key); + } + } + else { + createDiagnosticForOptionPathKeyValue(key, i, ts.Diagnostics.Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2, subst, key, typeOfSubst); + } + } + } + else { + createDiagnosticForOptionPaths(/*onKey*/ false, key, ts.Diagnostics.Substitutions_for_pattern_0_should_be_an_array, key); + } + } + } + if (!options.sourceMap && !options.inlineSourceMap) { + if (options.inlineSources) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided, "inlineSources"); + } + if (options.sourceRoot) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided, "sourceRoot"); + } + } + if (options.out && options.outFile) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "out", "outFile"); + } + if (options.mapRoot && !(options.sourceMap || options.declarationMap)) { + // Error to specify --mapRoot without --sourcemap + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "mapRoot", "sourceMap", "declarationMap"); + } + if (options.declarationDir) { + if (!ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "declarationDir", "declaration", "composite"); + } + if (options.out || options.outFile) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "declarationDir", options.out ? "out" : "outFile"); + } + } + if (options.declarationMap && !ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "declarationMap", "declaration", "composite"); + } + if (options.lib && options.noLib) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "lib", "noLib"); + } + if (options.noImplicitUseStrict && ts.getStrictOptionValue(options, "alwaysStrict")) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noImplicitUseStrict", "alwaysStrict"); + } + var languageVersion = options.target || 0 /* ES3 */; + var outFile = options.outFile || options.out; + var firstNonAmbientExternalModuleSourceFile = ts.find(files, function (f) { return ts.isExternalModule(f) && !f.isDeclarationFile; }); + if (options.isolatedModules) { + if (options.module === ts.ModuleKind.None && languageVersion < 2 /* ES2015 */) { + createDiagnosticForOptionName(ts.Diagnostics.Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher, "isolatedModules", "target"); + } + var firstNonExternalModuleSourceFile = ts.find(files, function (f) { return !ts.isExternalModule(f) && !f.isDeclarationFile && f.scriptKind !== 6 /* JSON */; }); + if (firstNonExternalModuleSourceFile) { + var span = ts.getErrorSpanForNode(firstNonExternalModuleSourceFile, firstNonExternalModuleSourceFile); + programDiagnostics.add(ts.createFileDiagnostic(firstNonExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided)); + } + } + else if (firstNonAmbientExternalModuleSourceFile && languageVersion < 2 /* ES2015 */ && options.module === ts.ModuleKind.None) { + // We cannot use createDiagnosticFromNode because nodes do not have parents yet + var span = ts.getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, firstNonAmbientExternalModuleSourceFile.externalModuleIndicator); + programDiagnostics.add(ts.createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_use_imports_exports_or_module_augmentations_when_module_is_none)); + } + // Cannot specify module gen that isn't amd or system with --out + if (outFile && !options.emitDeclarationOnly) { + if (options.module && !(options.module === ts.ModuleKind.AMD || options.module === ts.ModuleKind.System)) { + createDiagnosticForOptionName(ts.Diagnostics.Only_amd_and_system_modules_are_supported_alongside_0, options.out ? "out" : "outFile", "module"); + } + else if (options.module === undefined && firstNonAmbientExternalModuleSourceFile) { + var span = ts.getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, firstNonAmbientExternalModuleSourceFile.externalModuleIndicator); + programDiagnostics.add(ts.createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system, options.out ? "out" : "outFile")); + } + } + if (options.resolveJsonModule) { + if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { + createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy, "resolveJsonModule"); + } + // Any emit other than common js, amd, es2015 or esnext is error + else if (!ts.hasJsonModuleEmitEnabled(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_esNext, "resolveJsonModule", "module"); + } + } + // there has to be common source directory if user specified --outdir || --sourceRoot + // if user specified --mapRoot, there needs to be common source directory if there would be multiple files being emitted + if (options.outDir || // there is --outDir specified + options.sourceRoot || // there is --sourceRoot specified + options.mapRoot) { // there is --mapRoot specified + // Precalculate and cache the common source directory + var dir = getCommonSourceDirectory(); + // If we failed to find a good common directory, but outDir is specified and at least one of our files is on a windows drive/URL/other resource, add a failure + if (options.outDir && dir === "" && files.some(function (file) { return ts.getRootLength(file.fileName) > 1; })) { + createDiagnosticForOptionName(ts.Diagnostics.Cannot_find_the_common_subdirectory_path_for_the_input_files, "outDir"); + } + } + if (!options.noEmit && options.allowJs && ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "allowJs", getEmitDeclarationOptionName(options)); + } + if (options.checkJs && !options.allowJs) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "checkJs", "allowJs")); + } + if (options.emitDeclarationOnly) { + if (!ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "emitDeclarationOnly", "declaration", "composite"); + } + if (options.noEmit) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "emitDeclarationOnly", "noEmit"); + } + } + if (options.emitDecoratorMetadata && + !options.experimentalDecorators) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDecoratorMetadata", "experimentalDecorators"); + } + if (options.jsxFactory) { + if (options.reactNamespace) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "reactNamespace", "jsxFactory"); + } + if (!ts.parseIsolatedEntityName(options.jsxFactory, languageVersion)) { + createOptionValueDiagnostic("jsxFactory", ts.Diagnostics.Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name, options.jsxFactory); + } + } + else if (options.reactNamespace && !ts.isIdentifierText(options.reactNamespace, languageVersion)) { + createOptionValueDiagnostic("reactNamespace", ts.Diagnostics.Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier, options.reactNamespace); + } + // If the emit is enabled make sure that every output file is unique and not overwriting any of the input files + if (!options.noEmit && !options.suppressOutputPathCheck) { + var emitHost = getEmitHost(); + var emitFilesSeen_1 = ts.createMap(); + ts.forEachEmittedFile(emitHost, function (emitFileNames) { + if (!options.emitDeclarationOnly) { + verifyEmitFilePath(emitFileNames.jsFilePath, emitFilesSeen_1); + } + verifyEmitFilePath(emitFileNames.declarationFilePath, emitFilesSeen_1); + }); + } + // Verify that all the emit files are unique and don't overwrite input files + function verifyEmitFilePath(emitFileName, emitFilesSeen) { + if (emitFileName) { + var emitFilePath = toPath(emitFileName); + // Report error if the output overwrites input file + if (filesByName.has(emitFilePath)) { + var chain_2; + if (!options.configFilePath) { + // The program is from either an inferred project or an external project + chain_2 = ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig); + } + chain_2 = ts.chainDiagnosticMessages(chain_2, ts.Diagnostics.Cannot_write_file_0_because_it_would_overwrite_input_file, emitFileName); + blockEmittingOfFile(emitFileName, ts.createCompilerDiagnosticFromMessageChain(chain_2)); + } + var emitFileKey = !host.useCaseSensitiveFileNames() ? emitFilePath.toLocaleLowerCase() : emitFilePath; + // Report error if multiple files write into same file + if (emitFilesSeen.has(emitFileKey)) { + // Already seen the same emit file - report error + blockEmittingOfFile(emitFileName, ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files, emitFileName)); + } + else { + emitFilesSeen.set(emitFileKey, true); + } + } + } + } + function verifyProjectReferences() { + forEachProjectReference(projectReferences, resolvedProjectReferences, function (resolvedRef, index, parent) { + var ref = (parent ? parent.commandLine.projectReferences : projectReferences)[index]; + var parentFile = parent && parent.sourceFile; + if (!resolvedRef) { + createDiagnosticForReference(parentFile, index, ts.Diagnostics.File_0_not_found, ref.path); + return; + } + var options = resolvedRef.commandLine.options; + if (!options.composite) { + // ok to not have composite if the current program is container only + var inputs = parent ? parent.commandLine.fileNames : rootNames; + if (inputs.length) { + createDiagnosticForReference(parentFile, index, ts.Diagnostics.Referenced_project_0_must_have_setting_composite_Colon_true, ref.path); + } + } + if (ref.prepend) { + var out = options.outFile || options.out; + if (out) { + if (!host.fileExists(out)) { + createDiagnosticForReference(parentFile, index, ts.Diagnostics.Output_file_0_from_project_1_does_not_exist, out, ref.path); + } + } + else { + createDiagnosticForReference(parentFile, index, ts.Diagnostics.Cannot_prepend_project_0_because_it_does_not_have_outFile_set, ref.path); + } + } + }); + } + function createDiagnosticForOptionPathKeyValue(key, valueIndex, message, arg0, arg1, arg2) { + var needCompilerDiagnostic = true; + var pathsSyntax = getOptionPathsSyntax(); + for (var _i = 0, pathsSyntax_1 = pathsSyntax; _i < pathsSyntax_1.length; _i++) { + var pathProp = pathsSyntax_1[_i]; + if (ts.isObjectLiteralExpression(pathProp.initializer)) { + for (var _a = 0, _b = ts.getPropertyAssignment(pathProp.initializer, key); _a < _b.length; _a++) { + var keyProps = _b[_a]; + var initializer = keyProps.initializer; + if (ts.isArrayLiteralExpression(initializer) && initializer.elements.length > valueIndex) { + programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(options.configFile, initializer.elements[valueIndex], message, arg0, arg1, arg2)); + needCompilerDiagnostic = false; + } + } + } + } + if (needCompilerDiagnostic) { + programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1, arg2)); + } + } + function createDiagnosticForOptionPaths(onKey, key, message, arg0) { + var needCompilerDiagnostic = true; + var pathsSyntax = getOptionPathsSyntax(); + for (var _i = 0, pathsSyntax_2 = pathsSyntax; _i < pathsSyntax_2.length; _i++) { + var pathProp = pathsSyntax_2[_i]; + if (ts.isObjectLiteralExpression(pathProp.initializer) && + createOptionDiagnosticInObjectLiteralSyntax(pathProp.initializer, onKey, key, /*key2*/ undefined, message, arg0)) { + needCompilerDiagnostic = false; + } + } + if (needCompilerDiagnostic) { + programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0)); + } + } + function getOptionsSyntaxByName(name) { + var compilerOptionsObjectLiteralSyntax = getCompilerOptionsObjectLiteralSyntax(); + if (compilerOptionsObjectLiteralSyntax) { + return ts.getPropertyAssignment(compilerOptionsObjectLiteralSyntax, name); + } + return undefined; + } + function getOptionPathsSyntax() { + return getOptionsSyntaxByName("paths") || ts.emptyArray; + } + function createDiagnosticForOptionName(message, option1, option2, option3) { + createDiagnosticForOption(/*onKey*/ true, option1, option2, message, option1, option2, option3); + } + function createOptionValueDiagnostic(option1, message, arg0) { + createDiagnosticForOption(/*onKey*/ false, option1, /*option2*/ undefined, message, arg0); + } + function createDiagnosticForReference(sourceFile, index, message, arg0, arg1) { + var referencesSyntax = ts.firstDefined(ts.getTsConfigPropArray(sourceFile || options.configFile, "references"), function (property) { return ts.isArrayLiteralExpression(property.initializer) ? property.initializer : undefined; }); + if (referencesSyntax && referencesSyntax.elements.length > index) { + programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(sourceFile || options.configFile, referencesSyntax.elements[index], message, arg0, arg1)); + } + else { + programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1)); + } + } + function createDiagnosticForOption(onKey, option1, option2, message, arg0, arg1, arg2) { + var compilerOptionsObjectLiteralSyntax = getCompilerOptionsObjectLiteralSyntax(); + var needCompilerDiagnostic = !compilerOptionsObjectLiteralSyntax || + !createOptionDiagnosticInObjectLiteralSyntax(compilerOptionsObjectLiteralSyntax, onKey, option1, option2, message, arg0, arg1, arg2); + if (needCompilerDiagnostic) { + programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1, arg2)); + } + } + function getCompilerOptionsObjectLiteralSyntax() { + if (_compilerOptionsObjectLiteralSyntax === undefined) { + _compilerOptionsObjectLiteralSyntax = null; // tslint:disable-line:no-null-keyword + var jsonObjectLiteral = ts.getTsConfigObjectLiteralExpression(options.configFile); + if (jsonObjectLiteral) { + for (var _i = 0, _a = ts.getPropertyAssignment(jsonObjectLiteral, "compilerOptions"); _i < _a.length; _i++) { + var prop = _a[_i]; + if (ts.isObjectLiteralExpression(prop.initializer)) { + _compilerOptionsObjectLiteralSyntax = prop.initializer; + break; + } + } + } + } + return _compilerOptionsObjectLiteralSyntax; + } + function createOptionDiagnosticInObjectLiteralSyntax(objectLiteral, onKey, key1, key2, message, arg0, arg1, arg2) { + var props = ts.getPropertyAssignment(objectLiteral, key1, key2); + for (var _i = 0, props_2 = props; _i < props_2.length; _i++) { + var prop = props_2[_i]; + programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(options.configFile, onKey ? prop.name : prop.initializer, message, arg0, arg1, arg2)); + } + return !!props.length; + } + function blockEmittingOfFile(emitFileName, diag) { + hasEmitBlockingDiagnostics.set(toPath(emitFileName), true); + programDiagnostics.add(diag); + } + function isEmittedFile(file) { + if (options.noEmit) { + return false; + } + // If this is source file, its not emitted file + var filePath = toPath(file); + if (getSourceFileByPath(filePath)) { + return false; + } + // If options have --outFile or --out just check that + var out = options.outFile || options.out; + if (out) { + return isSameFile(filePath, out) || isSameFile(filePath, ts.removeFileExtension(out) + ".d.ts" /* Dts */); + } + // If declarationDir is specified, return if its a file in that directory + if (options.declarationDir && ts.containsPath(options.declarationDir, filePath, currentDirectory, !host.useCaseSensitiveFileNames())) { + return true; + } + // If --outDir, check if file is in that directory + if (options.outDir) { + return ts.containsPath(options.outDir, filePath, currentDirectory, !host.useCaseSensitiveFileNames()); + } + if (ts.fileExtensionIsOneOf(filePath, ts.supportedJSExtensions) || ts.fileExtensionIs(filePath, ".d.ts" /* Dts */)) { + // Otherwise just check if sourceFile with the name exists + var filePathWithoutExtension = ts.removeFileExtension(filePath); + return !!getSourceFileByPath((filePathWithoutExtension + ".ts" /* Ts */)) || + !!getSourceFileByPath((filePathWithoutExtension + ".tsx" /* Tsx */)); + } + return false; + } + function isSameFile(file1, file2) { + return ts.comparePaths(file1, file2, currentDirectory, !host.useCaseSensitiveFileNames()) === 0 /* EqualTo */; + } + } + ts.createProgram = createProgram; + /* @internal */ + function parseConfigHostFromCompilerHost(host) { + return { + fileExists: function (f) { return host.fileExists(f); }, + readDirectory: function (root, extensions, excludes, includes, depth) { + ts.Debug.assertDefined(host.readDirectory, "'CompilerHost.readDirectory' must be implemented to correctly process 'projectReferences'"); + return host.readDirectory(root, extensions, excludes, includes, depth); + }, + readFile: function (f) { return host.readFile(f); }, + useCaseSensitiveFileNames: host.useCaseSensitiveFileNames(), + getCurrentDirectory: function () { return host.getCurrentDirectory(); }, + onUnRecoverableConfigFileDiagnostic: function () { return undefined; }, + trace: host.trace ? function (s) { return host.trace(s); } : undefined + }; + } + ts.parseConfigHostFromCompilerHost = parseConfigHostFromCompilerHost; + function resolveProjectReferencePath(hostOrRef, ref) { + var passedInRef = ref ? ref : hostOrRef; + return ts.resolveConfigFileProjectName(passedInRef.path); + } + ts.resolveProjectReferencePath = resolveProjectReferencePath; + function getEmitDeclarationOptionName(options) { + return options.declaration ? "declaration" : "composite"; + } + /* @internal */ + /** + * Returns a DiagnosticMessage if we won't include a resolved module due to its extension. + * The DiagnosticMessage's parameters are the imported module name, and the filename it resolved to. + * This returns a diagnostic even if the module will be an untyped module. + */ + function getResolutionDiagnostic(options, _a) { + var extension = _a.extension; + switch (extension) { + case ".ts" /* Ts */: + case ".d.ts" /* Dts */: + // These are always allowed. + return undefined; + case ".tsx" /* Tsx */: + return needJsx(); + case ".jsx" /* Jsx */: + return needJsx() || needAllowJs(); + case ".js" /* Js */: + return needAllowJs(); + case ".json" /* Json */: + return needResolveJsonModule(); + } + function needJsx() { + return options.jsx ? undefined : ts.Diagnostics.Module_0_was_resolved_to_1_but_jsx_is_not_set; + } + function needAllowJs() { + return options.allowJs || !ts.getStrictOptionValue(options, "noImplicitAny") ? undefined : ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type; + } + function needResolveJsonModule() { + return options.resolveJsonModule ? undefined : ts.Diagnostics.Module_0_was_resolved_to_1_but_resolveJsonModule_is_not_used; + } + } + ts.getResolutionDiagnostic = getResolutionDiagnostic; + function getModuleNames(_a) { + var imports = _a.imports, moduleAugmentations = _a.moduleAugmentations; + var res = imports.map(function (i) { return i.text; }); + for (var _i = 0, moduleAugmentations_1 = moduleAugmentations; _i < moduleAugmentations_1.length; _i++) { + var aug = moduleAugmentations_1[_i]; + if (aug.kind === 10 /* StringLiteral */) { + res.push(aug.text); + } + // Do nothing if it's an Identifier; we don't need to do module resolution for `declare global`. + } + return res; + } +})(ts || (ts = {})); +/*@internal*/ +var ts; +(function (ts) { + function getFileEmitOutput(program, sourceFile, emitOnlyDtsFiles, cancellationToken, customTransformers) { + var outputFiles = []; + var emitResult = program.emit(sourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); + return { outputFiles: outputFiles, emitSkipped: emitResult.emitSkipped, exportedModulesFromDeclarationEmit: emitResult.exportedModulesFromDeclarationEmit }; + function writeFile(fileName, text, writeByteOrderMark) { + outputFiles.push({ name: fileName, writeByteOrderMark: writeByteOrderMark, text: text }); + } + } + ts.getFileEmitOutput = getFileEmitOutput; +})(ts || (ts = {})); +/*@internal*/ +(function (ts) { + var BuilderState; + (function (BuilderState) { + /** + * Get the referencedFile from the imported module symbol + */ + function getReferencedFileFromImportedModuleSymbol(symbol) { + if (symbol.declarations && symbol.declarations[0]) { + var declarationSourceFile = ts.getSourceFileOfNode(symbol.declarations[0]); + return declarationSourceFile && declarationSourceFile.resolvedPath; + } + } + /** + * Get the referencedFile from the import name node from file + */ + function getReferencedFileFromImportLiteral(checker, importName) { + var symbol = checker.getSymbolAtLocation(importName); + return symbol && getReferencedFileFromImportedModuleSymbol(symbol); + } + /** + * Gets the path to reference file from file name, it could be resolvedPath if present otherwise path + */ + function getReferencedFileFromFileName(program, fileName, sourceFileDirectory, getCanonicalFileName) { + return ts.toPath(program.getProjectReferenceRedirect(fileName) || fileName, sourceFileDirectory, getCanonicalFileName); + } + /** + * Gets the referenced files for a file from the program with values for the keys as referenced file's path to be true + */ + function getReferencedFiles(program, sourceFile, getCanonicalFileName) { + var referencedFiles; + // We need to use a set here since the code can contain the same import twice, + // but that will only be one dependency. + // To avoid invernal conversion, the key of the referencedFiles map must be of type Path + if (sourceFile.imports && sourceFile.imports.length > 0) { + var checker = program.getTypeChecker(); + for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { + var importName = _a[_i]; + var declarationSourceFilePath = getReferencedFileFromImportLiteral(checker, importName); + if (declarationSourceFilePath) { + addReferencedFile(declarationSourceFilePath); + } + } + } + var sourceFileDirectory = ts.getDirectoryPath(sourceFile.path); + // Handle triple slash references + if (sourceFile.referencedFiles && sourceFile.referencedFiles.length > 0) { + for (var _b = 0, _c = sourceFile.referencedFiles; _b < _c.length; _b++) { + var referencedFile = _c[_b]; + var referencedPath = getReferencedFileFromFileName(program, referencedFile.fileName, sourceFileDirectory, getCanonicalFileName); + addReferencedFile(referencedPath); + } + } + // Handle type reference directives + if (sourceFile.resolvedTypeReferenceDirectiveNames) { + sourceFile.resolvedTypeReferenceDirectiveNames.forEach(function (resolvedTypeReferenceDirective) { + if (!resolvedTypeReferenceDirective) { + return; + } + var fileName = resolvedTypeReferenceDirective.resolvedFileName; // TODO: GH#18217 + var typeFilePath = getReferencedFileFromFileName(program, fileName, sourceFileDirectory, getCanonicalFileName); + addReferencedFile(typeFilePath); + }); + } + // Add module augmentation as references + if (sourceFile.moduleAugmentations.length) { + var checker = program.getTypeChecker(); + for (var _d = 0, _e = sourceFile.moduleAugmentations; _d < _e.length; _d++) { + var moduleName = _e[_d]; + if (!ts.isStringLiteral(moduleName)) { + continue; + } + var symbol = checker.getSymbolAtLocation(moduleName); + if (!symbol) { + continue; + } + // Add any file other than our own as reference + addReferenceFromAmbientModule(symbol); + } + } + // From ambient modules + for (var _f = 0, _g = program.getTypeChecker().getAmbientModules(); _f < _g.length; _f++) { + var ambientModule = _g[_f]; + if (ambientModule.declarations.length > 1) { + addReferenceFromAmbientModule(ambientModule); + } + } + return referencedFiles; + function addReferenceFromAmbientModule(symbol) { + // Add any file other than our own as reference + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + var declarationSourceFile = ts.getSourceFileOfNode(declaration); + if (declarationSourceFile && + declarationSourceFile !== sourceFile) { + addReferencedFile(declarationSourceFile.resolvedPath); + } + } + } + function addReferencedFile(referencedPath) { + if (!referencedFiles) { + referencedFiles = ts.createMap(); + } + referencedFiles.set(referencedPath, true); + } + } + /** + * Returns true if oldState is reusable, that is the emitKind = module/non module has not changed + */ + function canReuseOldState(newReferencedMap, oldState) { + return oldState && !oldState.referencedMap === !newReferencedMap; + } + BuilderState.canReuseOldState = canReuseOldState; + /** + * Creates the state of file references and signature for the new program from oldState if it is safe + */ + function create(newProgram, getCanonicalFileName, oldState) { + var fileInfos = ts.createMap(); + var referencedMap = newProgram.getCompilerOptions().module !== ts.ModuleKind.None ? ts.createMap() : undefined; + var exportedModulesMap = referencedMap ? ts.createMap() : undefined; + var hasCalledUpdateShapeSignature = ts.createMap(); + var useOldState = canReuseOldState(referencedMap, oldState); + // Create the reference map, and set the file infos + for (var _i = 0, _a = newProgram.getSourceFiles(); _i < _a.length; _i++) { + var sourceFile = _a[_i]; + var version_1 = sourceFile.version; + var oldInfo = useOldState ? oldState.fileInfos.get(sourceFile.path) : undefined; + if (referencedMap) { + var newReferences = getReferencedFiles(newProgram, sourceFile, getCanonicalFileName); + if (newReferences) { + referencedMap.set(sourceFile.path, newReferences); + } + // Copy old visible to outside files map + if (useOldState) { + var exportedModules = oldState.exportedModulesMap.get(sourceFile.path); + if (exportedModules) { + exportedModulesMap.set(sourceFile.path, exportedModules); + } + } + } + fileInfos.set(sourceFile.path, { version: version_1, signature: oldInfo && oldInfo.signature }); + } + return { + fileInfos: fileInfos, + referencedMap: referencedMap, + exportedModulesMap: exportedModulesMap, + hasCalledUpdateShapeSignature: hasCalledUpdateShapeSignature, + allFilesExcludingDefaultLibraryFile: undefined, + allFileNames: undefined + }; + } + BuilderState.create = create; + /** + * Gets the files affected by the path from the program + */ + function getFilesAffectedBy(state, programOfThisState, path, cancellationToken, computeHash, cacheToUpdateSignature, exportedModulesMapCache) { + // Since the operation could be cancelled, the signatures are always stored in the cache + // They will be commited once it is safe to use them + // eg when calling this api from tsserver, if there is no cancellation of the operation + // In the other cases the affected files signatures are commited only after the iteration through the result is complete + var signatureCache = cacheToUpdateSignature || ts.createMap(); + var sourceFile = programOfThisState.getSourceFileByPath(path); + if (!sourceFile) { + return ts.emptyArray; + } + if (!updateShapeSignature(state, programOfThisState, sourceFile, signatureCache, cancellationToken, computeHash, exportedModulesMapCache)) { + return [sourceFile]; + } + var result = (state.referencedMap ? getFilesAffectedByUpdatedShapeWhenModuleEmit : getFilesAffectedByUpdatedShapeWhenNonModuleEmit)(state, programOfThisState, sourceFile, signatureCache, cancellationToken, computeHash, exportedModulesMapCache); + if (!cacheToUpdateSignature) { + // Commit all the signatures in the signature cache + updateSignaturesFromCache(state, signatureCache); + } + return result; + } + BuilderState.getFilesAffectedBy = getFilesAffectedBy; + /** + * Updates the signatures from the cache into state's fileinfo signatures + * This should be called whenever it is safe to commit the state of the builder + */ + function updateSignaturesFromCache(state, signatureCache) { + signatureCache.forEach(function (signature, path) { + state.fileInfos.get(path).signature = signature; + state.hasCalledUpdateShapeSignature.set(path, true); + }); + } + BuilderState.updateSignaturesFromCache = updateSignaturesFromCache; + /** + * Returns if the shape of the signature has changed since last emit + */ + function updateShapeSignature(state, programOfThisState, sourceFile, cacheToUpdateSignature, cancellationToken, computeHash, exportedModulesMapCache) { + ts.Debug.assert(!!sourceFile); + ts.Debug.assert(!exportedModulesMapCache || !!state.exportedModulesMap, "Compute visible to outside map only if visibleToOutsideReferencedMap present in the state"); + // If we have cached the result for this file, that means hence forth we should assume file shape is uptodate + if (state.hasCalledUpdateShapeSignature.has(sourceFile.path) || cacheToUpdateSignature.has(sourceFile.path)) { + return false; + } + var info = state.fileInfos.get(sourceFile.path); + if (!info) + return ts.Debug.fail(); + var prevSignature = info.signature; + var latestSignature; + if (sourceFile.isDeclarationFile) { + latestSignature = sourceFile.version; + if (exportedModulesMapCache && latestSignature !== prevSignature) { + // All the references in this file are exported + var references = state.referencedMap ? state.referencedMap.get(sourceFile.path) : undefined; + exportedModulesMapCache.set(sourceFile.path, references || false); + } + } + else { + var emitOutput = ts.getFileEmitOutput(programOfThisState, sourceFile, /*emitOnlyDtsFiles*/ true, cancellationToken); + if (emitOutput.outputFiles && emitOutput.outputFiles.length > 0) { + latestSignature = computeHash(emitOutput.outputFiles[0].text); + if (exportedModulesMapCache && latestSignature !== prevSignature) { + updateExportedModules(sourceFile, emitOutput.exportedModulesFromDeclarationEmit, exportedModulesMapCache); + } + } + else { + latestSignature = prevSignature; // TODO: GH#18217 + } + } + cacheToUpdateSignature.set(sourceFile.path, latestSignature); + return !prevSignature || latestSignature !== prevSignature; + } + /** + * Coverts the declaration emit result into exported modules map + */ + function updateExportedModules(sourceFile, exportedModulesFromDeclarationEmit, exportedModulesMapCache) { + if (!exportedModulesFromDeclarationEmit) { + exportedModulesMapCache.set(sourceFile.path, false); + return; + } + var exportedModules; + exportedModulesFromDeclarationEmit.forEach(function (symbol) { return addExportedModule(getReferencedFileFromImportedModuleSymbol(symbol)); }); + exportedModulesMapCache.set(sourceFile.path, exportedModules || false); + function addExportedModule(exportedModulePath) { + if (exportedModulePath) { + if (!exportedModules) { + exportedModules = ts.createMap(); + } + exportedModules.set(exportedModulePath, true); + } + } + } + /** + * Updates the exported modules from cache into state's exported modules map + * This should be called whenever it is safe to commit the state of the builder + */ + function updateExportedFilesMapFromCache(state, exportedModulesMapCache) { + if (exportedModulesMapCache) { + ts.Debug.assert(!!state.exportedModulesMap); + exportedModulesMapCache.forEach(function (exportedModules, path) { + if (exportedModules) { + state.exportedModulesMap.set(path, exportedModules); + } + else { + state.exportedModulesMap.delete(path); + } + }); + } + } + BuilderState.updateExportedFilesMapFromCache = updateExportedFilesMapFromCache; + /** + * Get all the dependencies of the sourceFile + */ + function getAllDependencies(state, programOfThisState, sourceFile) { + var _a; + var compilerOptions = programOfThisState.getCompilerOptions(); + // With --out or --outFile all outputs go into single file, all files depend on each other + if (compilerOptions.outFile || compilerOptions.out) { + return getAllFileNames(state, programOfThisState); + } + // If this is non module emit, or its a global file, it depends on all the source files + if (!state.referencedMap || isFileAffectingGlobalScope(sourceFile)) { + return getAllFileNames(state, programOfThisState); + } + // Get the references, traversing deep from the referenceMap + var seenMap = ts.createMap(); + var queue = [sourceFile.path]; + while (queue.length) { + var path = queue.pop(); + if (!seenMap.has(path)) { + seenMap.set(path, true); + var references = state.referencedMap.get(path); + if (references) { + var iterator = references.keys(); + for (var _b = iterator.next(), value = _b.value, done = _b.done; !done; _a = iterator.next(), value = _a.value, done = _a.done, _a) { + queue.push(value); + } + } + } + } + return ts.arrayFrom(ts.mapDefinedIterator(seenMap.keys(), function (path) { + var file = programOfThisState.getSourceFileByPath(path); + return file ? file.fileName : path; + })); + } + BuilderState.getAllDependencies = getAllDependencies; + /** + * Gets the names of all files from the program + */ + function getAllFileNames(state, programOfThisState) { + if (!state.allFileNames) { + var sourceFiles = programOfThisState.getSourceFiles(); + state.allFileNames = sourceFiles === ts.emptyArray ? ts.emptyArray : sourceFiles.map(function (file) { return file.fileName; }); + } + return state.allFileNames; + } + /** + * Gets the files referenced by the the file path + */ + function getReferencedByPaths(state, referencedFilePath) { + return ts.arrayFrom(ts.mapDefinedIterator(state.referencedMap.entries(), function (_a) { + var filePath = _a[0], referencesInFile = _a[1]; + return referencesInFile.has(referencedFilePath) ? filePath : undefined; + })); + } + /** + * For script files that contains only ambient external modules, although they are not actually external module files, + * they can only be consumed via importing elements from them. Regular script files cannot consume them. Therefore, + * there are no point to rebuild all script files if these special files have changed. However, if any statement + * in the file is not ambient external module, we treat it as a regular script file. + */ + function containsOnlyAmbientModules(sourceFile) { + for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + if (!ts.isModuleWithStringLiteralName(statement)) { + return false; + } + } + return true; + } + /** + * Return true if file contains anything that augments to global scope we need to build them as if + * they are global files as well as module + */ + function containsGlobalScopeAugmentation(sourceFile) { + return ts.some(sourceFile.moduleAugmentations, function (augmentation) { return ts.isGlobalScopeAugmentation(augmentation.parent); }); + } + /** + * Return true if the file will invalidate all files because it affectes global scope + */ + function isFileAffectingGlobalScope(sourceFile) { + return containsGlobalScopeAugmentation(sourceFile) || + !ts.isExternalModule(sourceFile) && !containsOnlyAmbientModules(sourceFile); + } + /** + * Gets all files of the program excluding the default library file + */ + function getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, firstSourceFile) { + // Use cached result + if (state.allFilesExcludingDefaultLibraryFile) { + return state.allFilesExcludingDefaultLibraryFile; + } + var result; + addSourceFile(firstSourceFile); + for (var _i = 0, _a = programOfThisState.getSourceFiles(); _i < _a.length; _i++) { + var sourceFile = _a[_i]; + if (sourceFile !== firstSourceFile) { + addSourceFile(sourceFile); + } + } + state.allFilesExcludingDefaultLibraryFile = result || ts.emptyArray; + return state.allFilesExcludingDefaultLibraryFile; + function addSourceFile(sourceFile) { + if (!programOfThisState.isSourceFileDefaultLibrary(sourceFile)) { + (result || (result = [])).push(sourceFile); + } + } + } + /** + * When program emits non modular code, gets the files affected by the sourceFile whose shape has changed + */ + function getFilesAffectedByUpdatedShapeWhenNonModuleEmit(state, programOfThisState, sourceFileWithUpdatedShape) { + var compilerOptions = programOfThisState.getCompilerOptions(); + // If `--out` or `--outFile` is specified, any new emit will result in re-emitting the entire project, + // so returning the file itself is good enough. + if (compilerOptions && (compilerOptions.out || compilerOptions.outFile)) { + return [sourceFileWithUpdatedShape]; + } + return getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, sourceFileWithUpdatedShape); + } + /** + * When program emits modular code, gets the files affected by the sourceFile whose shape has changed + */ + function getFilesAffectedByUpdatedShapeWhenModuleEmit(state, programOfThisState, sourceFileWithUpdatedShape, cacheToUpdateSignature, cancellationToken, computeHash, exportedModulesMapCache) { + if (isFileAffectingGlobalScope(sourceFileWithUpdatedShape)) { + return getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, sourceFileWithUpdatedShape); + } + var compilerOptions = programOfThisState.getCompilerOptions(); + if (compilerOptions && (compilerOptions.isolatedModules || compilerOptions.out || compilerOptions.outFile)) { + return [sourceFileWithUpdatedShape]; + } + // Now we need to if each file in the referencedBy list has a shape change as well. + // Because if so, its own referencedBy files need to be saved as well to make the + // emitting result consistent with files on disk. + var seenFileNamesMap = ts.createMap(); + // Start with the paths this file was referenced by + seenFileNamesMap.set(sourceFileWithUpdatedShape.path, sourceFileWithUpdatedShape); + var queue = getReferencedByPaths(state, sourceFileWithUpdatedShape.path); + while (queue.length > 0) { + var currentPath = queue.pop(); + if (!seenFileNamesMap.has(currentPath)) { + var currentSourceFile = programOfThisState.getSourceFileByPath(currentPath); + seenFileNamesMap.set(currentPath, currentSourceFile); + if (currentSourceFile && updateShapeSignature(state, programOfThisState, currentSourceFile, cacheToUpdateSignature, cancellationToken, computeHash, exportedModulesMapCache)) { // TODO: GH#18217 + queue.push.apply(// TODO: GH#18217 + queue, getReferencedByPaths(state, currentPath)); + } + } + } + // Return array of values that needs emit + // Return array of values that needs emit + return ts.arrayFrom(ts.mapDefinedIterator(seenFileNamesMap.values(), function (value) { return value; })); + } + })(BuilderState = ts.BuilderState || (ts.BuilderState = {})); +})(ts || (ts = {})); +/*@internal*/ +var ts; +(function (ts) { + function hasSameKeys(map1, map2) { + // Has same size and every key is present in both maps + return map1 === map2 || map1 !== undefined && map2 !== undefined && map1.size === map2.size && !ts.forEachKey(map1, function (key) { return !map2.has(key); }); + } + /** + * Create the state so that we can iterate on changedFiles/affected files + */ + function createBuilderProgramState(newProgram, getCanonicalFileName, oldState) { + var state = ts.BuilderState.create(newProgram, getCanonicalFileName, oldState); + state.program = newProgram; + var compilerOptions = newProgram.getCompilerOptions(); + if (!compilerOptions.outFile && !compilerOptions.out) { + state.semanticDiagnosticsPerFile = ts.createMap(); + } + state.changedFilesSet = ts.createMap(); + var useOldState = ts.BuilderState.canReuseOldState(state.referencedMap, oldState); + var oldCompilerOptions = useOldState ? oldState.program.getCompilerOptions() : undefined; + var canCopySemanticDiagnostics = useOldState && oldState.semanticDiagnosticsPerFile && !!state.semanticDiagnosticsPerFile && + !ts.compilerOptionsAffectSemanticDiagnostics(compilerOptions, oldCompilerOptions); + if (useOldState) { + // Verify the sanity of old state + if (!oldState.currentChangedFilePath) { + ts.Debug.assert(!oldState.affectedFiles && (!oldState.currentAffectedFilesSignatures || !oldState.currentAffectedFilesSignatures.size), "Cannot reuse if only few affected files of currentChangedFile were iterated"); + } + if (canCopySemanticDiagnostics) { + ts.Debug.assert(!ts.forEachKey(oldState.changedFilesSet, function (path) { return oldState.semanticDiagnosticsPerFile.has(path); }), "Semantic diagnostics shouldnt be available for changed files"); + } + // Copy old state's changed files set + ts.copyEntries(oldState.changedFilesSet, state.changedFilesSet); + } + // Update changed files and copy semantic diagnostics if we can + var referencedMap = state.referencedMap; + var oldReferencedMap = useOldState ? oldState.referencedMap : undefined; + var copyDeclarationFileDiagnostics = canCopySemanticDiagnostics && !compilerOptions.skipLibCheck === !oldCompilerOptions.skipLibCheck; + var copyLibFileDiagnostics = copyDeclarationFileDiagnostics && !compilerOptions.skipDefaultLibCheck === !oldCompilerOptions.skipDefaultLibCheck; + state.fileInfos.forEach(function (info, sourceFilePath) { + var oldInfo; + var newReferences; + // if not using old state, every file is changed + if (!useOldState || + // File wasnt present in old state + !(oldInfo = oldState.fileInfos.get(sourceFilePath)) || + // versions dont match + oldInfo.version !== info.version || + // Referenced files changed + !hasSameKeys(newReferences = referencedMap && referencedMap.get(sourceFilePath), oldReferencedMap && oldReferencedMap.get(sourceFilePath)) || + // Referenced file was deleted in the new program + newReferences && ts.forEachKey(newReferences, function (path) { return !state.fileInfos.has(path) && oldState.fileInfos.has(path); })) { + // Register file as changed file and do not copy semantic diagnostics, since all changed files need to be re-evaluated + state.changedFilesSet.set(sourceFilePath, true); + } + else if (canCopySemanticDiagnostics) { + var sourceFile = state.program.getSourceFileByPath(sourceFilePath); + if (sourceFile.isDeclarationFile && !copyDeclarationFileDiagnostics) { + return; + } + if (sourceFile.hasNoDefaultLib && !copyLibFileDiagnostics) { + return; + } + // Unchanged file copy diagnostics + var diagnostics = oldState.semanticDiagnosticsPerFile.get(sourceFilePath); + if (diagnostics) { + state.semanticDiagnosticsPerFile.set(sourceFilePath, diagnostics); + if (!state.semanticDiagnosticsFromOldState) { + state.semanticDiagnosticsFromOldState = ts.createMap(); + } + state.semanticDiagnosticsFromOldState.set(sourceFilePath, true); + } + } + }); + return state; + } + /** + * Verifies that source file is ok to be used in calls that arent handled by next + */ + function assertSourceFileOkWithoutNextAffectedCall(state, sourceFile) { + ts.Debug.assert(!sourceFile || !state.affectedFiles || state.affectedFiles[state.affectedFilesIndex - 1] !== sourceFile || !state.semanticDiagnosticsPerFile.has(sourceFile.path)); + } + /** + * This function returns the next affected file to be processed. + * Note that until doneAffected is called it would keep reporting same result + * This is to allow the callers to be able to actually remove affected file only when the operation is complete + * eg. if during diagnostics check cancellation token ends up cancelling the request, the affected file should be retained + */ + function getNextAffectedFile(state, cancellationToken, computeHash) { + while (true) { + var affectedFiles = state.affectedFiles; + if (affectedFiles) { + var seenAffectedFiles = state.seenAffectedFiles; + var affectedFilesIndex = state.affectedFilesIndex; // TODO: GH#18217 + while (affectedFilesIndex < affectedFiles.length) { + var affectedFile = affectedFiles[affectedFilesIndex]; + if (!seenAffectedFiles.has(affectedFile.path)) { + // Set the next affected file as seen and remove the cached semantic diagnostics + state.affectedFilesIndex = affectedFilesIndex; + cleanSemanticDiagnosticsOfAffectedFile(state, affectedFile); + return affectedFile; + } + seenAffectedFiles.set(affectedFile.path, true); + affectedFilesIndex++; + } + // Remove the changed file from the change set + state.changedFilesSet.delete(state.currentChangedFilePath); + state.currentChangedFilePath = undefined; + // Commit the changes in file signature + ts.BuilderState.updateSignaturesFromCache(state, state.currentAffectedFilesSignatures); + state.currentAffectedFilesSignatures.clear(); + ts.BuilderState.updateExportedFilesMapFromCache(state, state.currentAffectedFilesExportedModulesMap); + state.affectedFiles = undefined; + } + // Get next changed file + var nextKey = state.changedFilesSet.keys().next(); + if (nextKey.done) { + // Done + return undefined; + } + // With --out or --outFile all outputs go into single file + // so operations are performed directly on program, return program + var compilerOptions = state.program.getCompilerOptions(); + if (compilerOptions.outFile || compilerOptions.out) { + ts.Debug.assert(!state.semanticDiagnosticsPerFile); + return state.program; + } + // Get next batch of affected files + state.currentAffectedFilesSignatures = state.currentAffectedFilesSignatures || ts.createMap(); + if (state.exportedModulesMap) { + state.currentAffectedFilesExportedModulesMap = state.currentAffectedFilesExportedModulesMap || ts.createMap(); + } + state.affectedFiles = ts.BuilderState.getFilesAffectedBy(state, state.program, nextKey.value, cancellationToken, computeHash, state.currentAffectedFilesSignatures, state.currentAffectedFilesExportedModulesMap); + state.currentChangedFilePath = nextKey.value; + state.affectedFilesIndex = 0; + state.seenAffectedFiles = state.seenAffectedFiles || ts.createMap(); + } + } + /** + * Remove the semantic diagnostics cached from old state for affected File and the files that are referencing modules that export entities from affected file + */ + function cleanSemanticDiagnosticsOfAffectedFile(state, affectedFile) { + if (removeSemanticDiagnosticsOf(state, affectedFile.path)) { + // If there are no more diagnostics from old cache, done + return; + } + // Clean lib file diagnostics if its all files excluding default files to emit + if (state.allFilesExcludingDefaultLibraryFile === state.affectedFiles && !state.cleanedDiagnosticsOfLibFiles) { + state.cleanedDiagnosticsOfLibFiles = true; + var options_2 = state.program.getCompilerOptions(); + if (ts.forEach(state.program.getSourceFiles(), function (f) { + return state.program.isSourceFileDefaultLibrary(f) && + !ts.skipTypeChecking(f, options_2) && + removeSemanticDiagnosticsOf(state, f.path); + })) { + return; + } + } + // If there was change in signature for the changed file, + // then delete the semantic diagnostics for files that are affected by using exports of this module + if (!state.exportedModulesMap || state.affectedFiles.length === 1 || !state.changedFilesSet.has(affectedFile.path)) { + return; + } + ts.Debug.assert(!!state.currentAffectedFilesExportedModulesMap); + var seenFileAndExportsOfFile = ts.createMap(); + // Go through exported modules from cache first + // If exported modules has path, all files referencing file exported from are affected + if (ts.forEachEntry(state.currentAffectedFilesExportedModulesMap, function (exportedModules, exportedFromPath) { + return exportedModules && + exportedModules.has(affectedFile.path) && + removeSemanticDiagnosticsOfFilesReferencingPath(state, exportedFromPath, seenFileAndExportsOfFile); + })) { + return; + } + // If exported from path is not from cache and exported modules has path, all files referencing file exported from are affected + ts.forEachEntry(state.exportedModulesMap, function (exportedModules, exportedFromPath) { + return !state.currentAffectedFilesExportedModulesMap.has(exportedFromPath) && // If we already iterated this through cache, ignore it + exportedModules.has(affectedFile.path) && + removeSemanticDiagnosticsOfFilesReferencingPath(state, exportedFromPath, seenFileAndExportsOfFile); + }); + } + /** + * removes the semantic diagnostics of files referencing referencedPath and + * returns true if there are no more semantic diagnostics from old state + */ + function removeSemanticDiagnosticsOfFilesReferencingPath(state, referencedPath, seenFileAndExportsOfFile) { + return ts.forEachEntry(state.referencedMap, function (referencesInFile, filePath) { + return referencesInFile.has(referencedPath) && removeSemanticDiagnosticsOfFileAndExportsOfFile(state, filePath, seenFileAndExportsOfFile); + }); + } + /** + * Removes semantic diagnostics of file and anything that exports this file + */ + function removeSemanticDiagnosticsOfFileAndExportsOfFile(state, filePath, seenFileAndExportsOfFile) { + if (!ts.addToSeen(seenFileAndExportsOfFile, filePath)) { + return false; + } + if (removeSemanticDiagnosticsOf(state, filePath)) { + // If there are no more diagnostics from old cache, done + return true; + } + ts.Debug.assert(!!state.currentAffectedFilesExportedModulesMap); + // Go through exported modules from cache first + // If exported modules has path, all files referencing file exported from are affected + if (ts.forEachEntry(state.currentAffectedFilesExportedModulesMap, function (exportedModules, exportedFromPath) { + return exportedModules && + exportedModules.has(filePath) && + removeSemanticDiagnosticsOfFileAndExportsOfFile(state, exportedFromPath, seenFileAndExportsOfFile); + })) { + return true; + } + // If exported from path is not from cache and exported modules has path, all files referencing file exported from are affected + return !!ts.forEachEntry(state.exportedModulesMap, function (exportedModules, exportedFromPath) { + return !state.currentAffectedFilesExportedModulesMap.has(exportedFromPath) && // If we already iterated this through cache, ignore it + exportedModules.has(filePath) && + removeSemanticDiagnosticsOfFileAndExportsOfFile(state, exportedFromPath, seenFileAndExportsOfFile); + }); + } + /** + * Removes semantic diagnostics for path and + * returns true if there are no more semantic diagnostics from the old state + */ + function removeSemanticDiagnosticsOf(state, path) { + if (!state.semanticDiagnosticsFromOldState) { + return true; + } + state.semanticDiagnosticsFromOldState.delete(path); + state.semanticDiagnosticsPerFile.delete(path); + return !state.semanticDiagnosticsFromOldState.size; + } + /** + * This is called after completing operation on the next affected file. + * The operations here are postponed to ensure that cancellation during the iteration is handled correctly + */ + function doneWithAffectedFile(state, affected) { + if (affected === state.program) { + state.changedFilesSet.clear(); + } + else { + state.seenAffectedFiles.set(affected.path, true); + state.affectedFilesIndex++; + } + } + /** + * Returns the result with affected file + */ + function toAffectedFileResult(state, result, affected) { + doneWithAffectedFile(state, affected); + return { result: result, affected: affected }; + } + /** + * Gets the semantic diagnostics either from cache if present, or otherwise from program and caches it + * Note that it is assumed that the when asked about semantic diagnostics, the file has been taken out of affected files/changed file set + */ + function getSemanticDiagnosticsOfFile(state, sourceFile, cancellationToken) { + var path = sourceFile.path; + var cachedDiagnostics = state.semanticDiagnosticsPerFile.get(path); + // Report the semantic diagnostics from the cache if we already have those diagnostics present + if (cachedDiagnostics) { + return cachedDiagnostics; + } + // Diagnostics werent cached, get them from program, and cache the result + var diagnostics = state.program.getSemanticDiagnostics(sourceFile, cancellationToken); + state.semanticDiagnosticsPerFile.set(path, diagnostics); + return diagnostics; + } + var BuilderProgramKind; + (function (BuilderProgramKind) { + BuilderProgramKind[BuilderProgramKind["SemanticDiagnosticsBuilderProgram"] = 0] = "SemanticDiagnosticsBuilderProgram"; + BuilderProgramKind[BuilderProgramKind["EmitAndSemanticDiagnosticsBuilderProgram"] = 1] = "EmitAndSemanticDiagnosticsBuilderProgram"; + })(BuilderProgramKind = ts.BuilderProgramKind || (ts.BuilderProgramKind = {})); + function getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { + var host; + var newProgram; + var oldProgram; + if (newProgramOrRootNames === undefined) { + ts.Debug.assert(hostOrOptions === undefined); + host = oldProgramOrHost; + oldProgram = configFileParsingDiagnosticsOrOldProgram; + ts.Debug.assert(!!oldProgram); + newProgram = oldProgram.getProgram(); + } + else if (ts.isArray(newProgramOrRootNames)) { + oldProgram = configFileParsingDiagnosticsOrOldProgram; + newProgram = ts.createProgram({ + rootNames: newProgramOrRootNames, + options: hostOrOptions, + host: oldProgramOrHost, + oldProgram: oldProgram && oldProgram.getProgram(), + configFileParsingDiagnostics: configFileParsingDiagnostics, + projectReferences: projectReferences + }); + host = oldProgramOrHost; + } + else { + newProgram = newProgramOrRootNames; + host = hostOrOptions; + oldProgram = oldProgramOrHost; + configFileParsingDiagnostics = configFileParsingDiagnosticsOrOldProgram; + } + return { host: host, newProgram: newProgram, oldProgram: oldProgram, configFileParsingDiagnostics: configFileParsingDiagnostics || ts.emptyArray }; + } + ts.getBuilderCreationParameters = getBuilderCreationParameters; + function createBuilderProgram(kind, _a) { + var newProgram = _a.newProgram, host = _a.host, oldProgram = _a.oldProgram, configFileParsingDiagnostics = _a.configFileParsingDiagnostics; + // Return same program if underlying program doesnt change + var oldState = oldProgram && oldProgram.getState(); + if (oldState && newProgram === oldState.program && configFileParsingDiagnostics === newProgram.getConfigFileParsingDiagnostics()) { + newProgram = undefined; // TODO: GH#18217 + oldState = undefined; + return oldProgram; + } + /** + * Create the canonical file name for identity + */ + var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames()); + /** + * Computing hash to for signature verification + */ + var computeHash = host.createHash || ts.identity; + var state = createBuilderProgramState(newProgram, getCanonicalFileName, oldState); + // To ensure that we arent storing any references to old program or new program without state + newProgram = undefined; // TODO: GH#18217 + oldProgram = undefined; + oldState = undefined; + var result = { + getState: function () { return state; }, + getProgram: function () { return state.program; }, + getCompilerOptions: function () { return state.program.getCompilerOptions(); }, + getSourceFile: function (fileName) { return state.program.getSourceFile(fileName); }, + getSourceFiles: function () { return state.program.getSourceFiles(); }, + getOptionsDiagnostics: function (cancellationToken) { return state.program.getOptionsDiagnostics(cancellationToken); }, + getGlobalDiagnostics: function (cancellationToken) { return state.program.getGlobalDiagnostics(cancellationToken); }, + getConfigFileParsingDiagnostics: function () { return configFileParsingDiagnostics || state.program.getConfigFileParsingDiagnostics(); }, + getSyntacticDiagnostics: function (sourceFile, cancellationToken) { return state.program.getSyntacticDiagnostics(sourceFile, cancellationToken); }, + getSemanticDiagnostics: getSemanticDiagnostics, + emit: emit, + getAllDependencies: function (sourceFile) { return ts.BuilderState.getAllDependencies(state, state.program, sourceFile); }, + getCurrentDirectory: function () { return state.program.getCurrentDirectory(); } + }; + if (kind === BuilderProgramKind.SemanticDiagnosticsBuilderProgram) { + result.getSemanticDiagnosticsOfNextAffectedFile = getSemanticDiagnosticsOfNextAffectedFile; + } + else if (kind === BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram) { + result.emitNextAffectedFile = emitNextAffectedFile; + } + else { + ts.notImplemented(); + } + return result; + /** + * Emits the next affected file's emit result (EmitResult and sourceFiles emitted) or returns undefined if iteration is complete + * The first of writeFile if provided, writeFile of BuilderProgramHost if provided, writeFile of compiler host + * in that order would be used to write the files + */ + function emitNextAffectedFile(writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) { + var affected = getNextAffectedFile(state, cancellationToken, computeHash); + if (!affected) { + // Done + return undefined; + } + return toAffectedFileResult(state, + // When whole program is affected, do emit only once (eg when --out or --outFile is specified) + // Otherwise just affected file + state.program.emit(affected === state.program ? undefined : affected, writeFile || host.writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers), affected); + } + /** + * Emits the JavaScript and declaration files. + * When targetSource file is specified, emits the files corresponding to that source file, + * otherwise for the whole program. + * In case of EmitAndSemanticDiagnosticsBuilderProgram, when targetSourceFile is specified, + * it is assumed that that file is handled from affected file list. If targetSourceFile is not specified, + * it will only emit all the affected files instead of whole program + * + * The first of writeFile if provided, writeFile of BuilderProgramHost if provided, writeFile of compiler host + * in that order would be used to write the files + */ + function emit(targetSourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) { + if (kind === BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram) { + assertSourceFileOkWithoutNextAffectedCall(state, targetSourceFile); + if (!targetSourceFile) { + // Emit and report any errors we ran into. + var sourceMaps = []; + var emitSkipped = false; + var diagnostics = void 0; + var emittedFiles = []; + var affectedEmitResult = void 0; + while (affectedEmitResult = emitNextAffectedFile(writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers)) { + emitSkipped = emitSkipped || affectedEmitResult.result.emitSkipped; + diagnostics = ts.addRange(diagnostics, affectedEmitResult.result.diagnostics); + emittedFiles = ts.addRange(emittedFiles, affectedEmitResult.result.emittedFiles); + sourceMaps = ts.addRange(sourceMaps, affectedEmitResult.result.sourceMaps); + } + return { + emitSkipped: emitSkipped, + diagnostics: diagnostics || ts.emptyArray, + emittedFiles: emittedFiles, + sourceMaps: sourceMaps + }; + } + } + return state.program.emit(targetSourceFile, writeFile || host.writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); + } + /** + * Return the semantic diagnostics for the next affected file or undefined if iteration is complete + * If provided ignoreSourceFile would be called before getting the diagnostics and would ignore the sourceFile if the returned value was true + */ + function getSemanticDiagnosticsOfNextAffectedFile(cancellationToken, ignoreSourceFile) { + while (true) { + var affected = getNextAffectedFile(state, cancellationToken, computeHash); + if (!affected) { + // Done + return undefined; + } + else if (affected === state.program) { + // When whole program is affected, get all semantic diagnostics (eg when --out or --outFile is specified) + return toAffectedFileResult(state, state.program.getSemanticDiagnostics(/*targetSourceFile*/ undefined, cancellationToken), affected); + } + // Get diagnostics for the affected file if its not ignored + if (ignoreSourceFile && ignoreSourceFile(affected)) { + // Get next affected file + doneWithAffectedFile(state, affected); + continue; + } + return toAffectedFileResult(state, getSemanticDiagnosticsOfFile(state, affected, cancellationToken), affected); + } + } + /** + * Gets the semantic diagnostics from the program corresponding to this state of file (if provided) or whole program + * The semantic diagnostics are cached and managed here + * Note that it is assumed that when asked about semantic diagnostics through this API, + * the file has been taken out of affected files so it is safe to use cache or get from program and cache the diagnostics + * In case of SemanticDiagnosticsBuilderProgram if the source file is not provided, + * it will iterate through all the affected files, to ensure that cache stays valid and yet provide a way to get all semantic diagnostics + */ + function getSemanticDiagnostics(sourceFile, cancellationToken) { + assertSourceFileOkWithoutNextAffectedCall(state, sourceFile); + var compilerOptions = state.program.getCompilerOptions(); + if (compilerOptions.outFile || compilerOptions.out) { + ts.Debug.assert(!state.semanticDiagnosticsPerFile); + // We dont need to cache the diagnostics just return them from program + return state.program.getSemanticDiagnostics(sourceFile, cancellationToken); + } + if (sourceFile) { + return getSemanticDiagnosticsOfFile(state, sourceFile, cancellationToken); + } + if (kind === BuilderProgramKind.SemanticDiagnosticsBuilderProgram) { + // When semantic builder asks for diagnostics of the whole program, + // ensure that all the affected files are handled + var affected = void 0; + while (affected = getNextAffectedFile(state, cancellationToken, computeHash)) { + doneWithAffectedFile(state, affected); + } + } + var diagnostics; + for (var _i = 0, _a = state.program.getSourceFiles(); _i < _a.length; _i++) { + var sourceFile_2 = _a[_i]; + diagnostics = ts.addRange(diagnostics, getSemanticDiagnosticsOfFile(state, sourceFile_2, cancellationToken)); + } + return diagnostics || ts.emptyArray; + } + } + ts.createBuilderProgram = createBuilderProgram; +})(ts || (ts = {})); +(function (ts) { + function createSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { + return ts.createBuilderProgram(ts.BuilderProgramKind.SemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences)); + } + ts.createSemanticDiagnosticsBuilderProgram = createSemanticDiagnosticsBuilderProgram; + function createEmitAndSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { + return ts.createBuilderProgram(ts.BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences)); + } + ts.createEmitAndSemanticDiagnosticsBuilderProgram = createEmitAndSemanticDiagnosticsBuilderProgram; + function createAbstractBuilder(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { + var program = ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences).newProgram; + return { + // Only return program, all other methods are not implemented + getProgram: function () { return program; }, + getState: ts.notImplemented, + getCompilerOptions: ts.notImplemented, + getSourceFile: ts.notImplemented, + getSourceFiles: ts.notImplemented, + getOptionsDiagnostics: ts.notImplemented, + getGlobalDiagnostics: ts.notImplemented, + getConfigFileParsingDiagnostics: ts.notImplemented, + getSyntacticDiagnostics: ts.notImplemented, + getSemanticDiagnostics: ts.notImplemented, + emit: ts.notImplemented, + getAllDependencies: ts.notImplemented, + getCurrentDirectory: ts.notImplemented + }; + } + ts.createAbstractBuilder = createAbstractBuilder; +})(ts || (ts = {})); +/*@internal*/ +var ts; +(function (ts) { + function isPathInNodeModulesStartingWithDot(path) { + return ts.stringContains(path, "/node_modules/."); + } + ts.isPathInNodeModulesStartingWithDot = isPathInNodeModulesStartingWithDot; + ts.maxNumberOfFilesToIterateForInvalidation = 256; + function createResolutionCache(resolutionHost, rootDirForResolution, logChangesWhenResolvingModule) { + var filesWithChangedSetOfUnresolvedImports; + var filesWithInvalidatedResolutions; + var filesWithInvalidatedNonRelativeUnresolvedImports; + var allFilesHaveInvalidatedResolution = false; + var nonRelativeExternalModuleResolutions = ts.createMultiMap(); + var getCurrentDirectory = ts.memoize(function () { return resolutionHost.getCurrentDirectory(); }); // TODO: GH#18217 + var cachedDirectoryStructureHost = resolutionHost.getCachedDirectoryStructureHost(); + // The resolvedModuleNames and resolvedTypeReferenceDirectives are the cache of resolutions per file. + // The key in the map is source file's path. + // The values are Map of resolutions with key being name lookedup. + var resolvedModuleNames = ts.createMap(); + var perDirectoryResolvedModuleNames = ts.createCacheWithRedirects(); + var nonRelativeModuleNameCache = ts.createCacheWithRedirects(); + var moduleResolutionCache = ts.createModuleResolutionCacheWithMaps(perDirectoryResolvedModuleNames, nonRelativeModuleNameCache, getCurrentDirectory(), resolutionHost.getCanonicalFileName); + var resolvedTypeReferenceDirectives = ts.createMap(); + var perDirectoryResolvedTypeReferenceDirectives = ts.createCacheWithRedirects(); + /** + * These are the extensions that failed lookup files will have by default, + * any other extension of failed lookup will be store that path in custom failed lookup path + * This helps in not having to comb through all resolutions when files are added/removed + * Note that .d.ts file also has .d.ts extension hence will be part of default extensions + */ + var failedLookupDefaultExtensions = [".ts" /* Ts */, ".tsx" /* Tsx */, ".js" /* Js */, ".jsx" /* Jsx */, ".json" /* Json */]; + var customFailedLookupPaths = ts.createMap(); + var directoryWatchesOfFailedLookups = ts.createMap(); + var rootDir = rootDirForResolution && ts.removeTrailingDirectorySeparator(ts.getNormalizedAbsolutePath(rootDirForResolution, getCurrentDirectory())); + var rootPath = (rootDir && resolutionHost.toPath(rootDir)); // TODO: GH#18217 + // TypeRoot watches for the types that get added as part of getAutomaticTypeDirectiveNames + var typeRootsWatches = ts.createMap(); + return { + startRecordingFilesWithChangedResolutions: startRecordingFilesWithChangedResolutions, + finishRecordingFilesWithChangedResolutions: finishRecordingFilesWithChangedResolutions, + // perDirectoryResolvedModuleNames and perDirectoryResolvedTypeReferenceDirectives could be non empty if there was exception during program update + // (between startCachingPerDirectoryResolution and finishCachingPerDirectoryResolution) + startCachingPerDirectoryResolution: clearPerDirectoryResolutions, + finishCachingPerDirectoryResolution: finishCachingPerDirectoryResolution, + resolveModuleNames: resolveModuleNames, + getResolvedModuleWithFailedLookupLocationsFromCache: getResolvedModuleWithFailedLookupLocationsFromCache, + resolveTypeReferenceDirectives: resolveTypeReferenceDirectives, + removeResolutionsFromProjectReferenceRedirects: removeResolutionsFromProjectReferenceRedirects, + removeResolutionsOfFile: removeResolutionsOfFile, + invalidateResolutionOfFile: invalidateResolutionOfFile, + setFilesWithInvalidatedNonRelativeUnresolvedImports: setFilesWithInvalidatedNonRelativeUnresolvedImports, + createHasInvalidatedResolution: createHasInvalidatedResolution, + updateTypeRootsWatch: updateTypeRootsWatch, + closeTypeRootsWatch: closeTypeRootsWatch, + clear: clear + }; + function getResolvedModule(resolution) { + return resolution.resolvedModule; + } + function getResolvedTypeReferenceDirective(resolution) { + return resolution.resolvedTypeReferenceDirective; + } + function isInDirectoryPath(dir, file) { + if (dir === undefined || file.length <= dir.length) { + return false; + } + return ts.startsWith(file, dir) && file[dir.length] === ts.directorySeparator; + } + function clear() { + ts.clearMap(directoryWatchesOfFailedLookups, ts.closeFileWatcherOf); + customFailedLookupPaths.clear(); + nonRelativeExternalModuleResolutions.clear(); + closeTypeRootsWatch(); + resolvedModuleNames.clear(); + resolvedTypeReferenceDirectives.clear(); + allFilesHaveInvalidatedResolution = false; + // perDirectoryResolvedModuleNames and perDirectoryResolvedTypeReferenceDirectives could be non empty if there was exception during program update + // (between startCachingPerDirectoryResolution and finishCachingPerDirectoryResolution) + clearPerDirectoryResolutions(); + } + function startRecordingFilesWithChangedResolutions() { + filesWithChangedSetOfUnresolvedImports = []; + } + function finishRecordingFilesWithChangedResolutions() { + var collected = filesWithChangedSetOfUnresolvedImports; + filesWithChangedSetOfUnresolvedImports = undefined; + return collected; + } + function isFileWithInvalidatedNonRelativeUnresolvedImports(path) { + if (!filesWithInvalidatedNonRelativeUnresolvedImports) { + return false; + } + // Invalidated if file has unresolved imports + var value = filesWithInvalidatedNonRelativeUnresolvedImports.get(path); + return !!value && !!value.length; + } + function createHasInvalidatedResolution(forceAllFilesAsInvalidated) { + if (allFilesHaveInvalidatedResolution || forceAllFilesAsInvalidated) { + // Any file asked would have invalidated resolution + filesWithInvalidatedResolutions = undefined; + return ts.returnTrue; + } + var collected = filesWithInvalidatedResolutions; + filesWithInvalidatedResolutions = undefined; + return function (path) { return (!!collected && collected.has(path)) || + isFileWithInvalidatedNonRelativeUnresolvedImports(path); }; + } + function clearPerDirectoryResolutions() { + perDirectoryResolvedModuleNames.clear(); + nonRelativeModuleNameCache.clear(); + perDirectoryResolvedTypeReferenceDirectives.clear(); + nonRelativeExternalModuleResolutions.forEach(watchFailedLookupLocationOfNonRelativeModuleResolutions); + nonRelativeExternalModuleResolutions.clear(); + } + function finishCachingPerDirectoryResolution() { + allFilesHaveInvalidatedResolution = false; + filesWithInvalidatedNonRelativeUnresolvedImports = undefined; + clearPerDirectoryResolutions(); + directoryWatchesOfFailedLookups.forEach(function (watcher, path) { + if (watcher.refCount === 0) { + directoryWatchesOfFailedLookups.delete(path); + watcher.watcher.close(); + } + }); + } + function resolveModuleName(moduleName, containingFile, compilerOptions, host, redirectedReference) { + var primaryResult = ts.resolveModuleName(moduleName, containingFile, compilerOptions, host, moduleResolutionCache, redirectedReference); + // return result immediately only if global cache support is not enabled or if it is .ts, .tsx or .d.ts + if (!resolutionHost.getGlobalCache) { + return primaryResult; + } + // otherwise try to load typings from @types + var globalCache = resolutionHost.getGlobalCache(); + if (globalCache !== undefined && !ts.isExternalModuleNameRelative(moduleName) && !(primaryResult.resolvedModule && ts.extensionIsTS(primaryResult.resolvedModule.extension))) { + // create different collection of failed lookup locations for second pass + // if it will fail and we've already found something during the first pass - we don't want to pollute its results + var _a = ts.loadModuleFromGlobalCache(moduleName, resolutionHost.projectName, compilerOptions, host, globalCache), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; + if (resolvedModule) { + return { resolvedModule: resolvedModule, failedLookupLocations: ts.addRange(primaryResult.failedLookupLocations, failedLookupLocations) }; + } + } + // Default return the result from the first pass + return primaryResult; + } + function resolveNamesWithLocalCache(names, containingFile, redirectedReference, cache, perDirectoryCacheWithRedirects, loader, getResolutionWithResolvedFileName, shouldRetryResolution, reusedNames, logChanges) { + var path = resolutionHost.toPath(containingFile); + var resolutionsInFile = cache.get(path) || cache.set(path, ts.createMap()).get(path); + var dirPath = ts.getDirectoryPath(path); + var perDirectoryCache = perDirectoryCacheWithRedirects.getOrCreateMapOfCacheRedirects(redirectedReference); + var perDirectoryResolution = perDirectoryCache.get(dirPath); + if (!perDirectoryResolution) { + perDirectoryResolution = ts.createMap(); + perDirectoryCache.set(dirPath, perDirectoryResolution); + } + var resolvedModules = []; + var compilerOptions = resolutionHost.getCompilationSettings(); + var hasInvalidatedNonRelativeUnresolvedImport = logChanges && isFileWithInvalidatedNonRelativeUnresolvedImports(path); + // All the resolutions in this file are invalidated if this file wasnt resolved using same redirect + var program = resolutionHost.getCurrentProgram(); + var oldRedirect = program && program.getResolvedProjectReferenceToRedirect(containingFile); + var unmatchedRedirects = oldRedirect ? + !redirectedReference || redirectedReference.sourceFile.path !== oldRedirect.sourceFile.path : + !!redirectedReference; + var seenNamesInFile = ts.createMap(); + for (var _i = 0, names_2 = names; _i < names_2.length; _i++) { + var name = names_2[_i]; + var resolution = resolutionsInFile.get(name); + // Resolution is valid if it is present and not invalidated + if (!seenNamesInFile.has(name) && + allFilesHaveInvalidatedResolution || unmatchedRedirects || !resolution || resolution.isInvalidated || + // If the name is unresolved import that was invalidated, recalculate + (hasInvalidatedNonRelativeUnresolvedImport && !ts.isExternalModuleNameRelative(name) && shouldRetryResolution(resolution))) { + var existingResolution = resolution; + var resolutionInDirectory = perDirectoryResolution.get(name); + if (resolutionInDirectory) { + resolution = resolutionInDirectory; + } + else { + resolution = loader(name, containingFile, compilerOptions, resolutionHost, redirectedReference); + perDirectoryResolution.set(name, resolution); + } + resolutionsInFile.set(name, resolution); + watchFailedLookupLocationsOfExternalModuleResolutions(name, resolution); + if (existingResolution) { + stopWatchFailedLookupLocationOfResolution(existingResolution); + } + if (logChanges && filesWithChangedSetOfUnresolvedImports && !resolutionIsEqualTo(existingResolution, resolution)) { + filesWithChangedSetOfUnresolvedImports.push(path); + // reset log changes to avoid recording the same file multiple times + logChanges = false; + } + } + ts.Debug.assert(resolution !== undefined && !resolution.isInvalidated); + seenNamesInFile.set(name, true); + resolvedModules.push(getResolutionWithResolvedFileName(resolution)); + } + // Stop watching and remove the unused name + resolutionsInFile.forEach(function (resolution, name) { + if (!seenNamesInFile.has(name) && !ts.contains(reusedNames, name)) { + stopWatchFailedLookupLocationOfResolution(resolution); + resolutionsInFile.delete(name); + } + }); + return resolvedModules; + function resolutionIsEqualTo(oldResolution, newResolution) { + if (oldResolution === newResolution) { + return true; + } + if (!oldResolution || !newResolution) { + return false; + } + var oldResult = getResolutionWithResolvedFileName(oldResolution); + var newResult = getResolutionWithResolvedFileName(newResolution); + if (oldResult === newResult) { + return true; + } + if (!oldResult || !newResult) { + return false; + } + return oldResult.resolvedFileName === newResult.resolvedFileName; + } + } + function resolveTypeReferenceDirectives(typeDirectiveNames, containingFile, redirectedReference) { + return resolveNamesWithLocalCache(typeDirectiveNames, containingFile, redirectedReference, resolvedTypeReferenceDirectives, perDirectoryResolvedTypeReferenceDirectives, ts.resolveTypeReferenceDirective, getResolvedTypeReferenceDirective, + /*shouldRetryResolution*/ function (resolution) { return resolution.resolvedTypeReferenceDirective === undefined; }, + /*reusedNames*/ undefined, /*logChanges*/ false); + } + function resolveModuleNames(moduleNames, containingFile, reusedNames, redirectedReference) { + return resolveNamesWithLocalCache(moduleNames, containingFile, redirectedReference, resolvedModuleNames, perDirectoryResolvedModuleNames, resolveModuleName, getResolvedModule, + /*shouldRetryResolution*/ function (resolution) { return !resolution.resolvedModule || !ts.resolutionExtensionIsTSOrJson(resolution.resolvedModule.extension); }, reusedNames, logChangesWhenResolvingModule); + } + function getResolvedModuleWithFailedLookupLocationsFromCache(moduleName, containingFile) { + var cache = resolvedModuleNames.get(resolutionHost.toPath(containingFile)); + return cache && cache.get(moduleName); + } + function isNodeModulesDirectory(dirPath) { + return ts.endsWith(dirPath, "/node_modules"); + } + function isNodeModulesAtTypesDirectory(dirPath) { + return ts.endsWith(dirPath, "/node_modules/@types"); + } + /** + * Filter out paths like + * "/", "/user", "/user/username", "/user/username/folderAtRoot", + * "c:/", "c:/users", "c:/users/username", "c:/users/username/folderAtRoot", "c:/folderAtRoot" + * @param dirPath + */ + function canWatchDirectory(dirPath) { + var rootLength = ts.getRootLength(dirPath); + if (dirPath.length === rootLength) { + // Ignore "/", "c:/" + return false; + } + var nextDirectorySeparator = dirPath.indexOf(ts.directorySeparator, rootLength); + if (nextDirectorySeparator === -1) { + // ignore "/user", "c:/users" or "c:/folderAtRoot" + return false; + } + if (dirPath.charCodeAt(0) !== 47 /* slash */ && + dirPath.substr(rootLength, nextDirectorySeparator).search(/users/i) === -1) { + // Paths like c:/folderAtRoot/subFolder are allowed + return true; + } + for (var searchIndex = nextDirectorySeparator + 1, searchLevels = 2; searchLevels > 0; searchLevels--) { + searchIndex = dirPath.indexOf(ts.directorySeparator, searchIndex) + 1; + if (searchIndex === 0) { + // Folder isnt at expected minimun levels + return false; + } + } + return true; + } + function getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath) { + if (isInDirectoryPath(rootPath, failedLookupLocationPath)) { + // Ensure failed look up is normalized path + failedLookupLocation = ts.isRootedDiskPath(failedLookupLocation) ? ts.normalizePath(failedLookupLocation) : ts.getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory()); + ts.Debug.assert(failedLookupLocation.length === failedLookupLocationPath.length, "FailedLookup: " + failedLookupLocation + " failedLookupLocationPath: " + failedLookupLocationPath); // tslint:disable-line + var subDirectoryInRoot = failedLookupLocationPath.indexOf(ts.directorySeparator, rootPath.length + 1); + if (subDirectoryInRoot !== -1) { + // Instead of watching root, watch directory in root to avoid watching excluded directories not needed for module resolution + return { dir: failedLookupLocation.substr(0, subDirectoryInRoot), dirPath: failedLookupLocationPath.substr(0, subDirectoryInRoot) }; + } + else { + // Always watch root directory non recursively + return { dir: rootDir, dirPath: rootPath, nonRecursive: false }; // TODO: GH#18217 + } + } + return getDirectoryToWatchFromFailedLookupLocationDirectory(ts.getDirectoryPath(ts.getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory())), ts.getDirectoryPath(failedLookupLocationPath)); + } + function getDirectoryToWatchFromFailedLookupLocationDirectory(dir, dirPath) { + // If directory path contains node module, get the most parent node_modules directory for watching + while (ts.pathContainsNodeModules(dirPath)) { + dir = ts.getDirectoryPath(dir); + dirPath = ts.getDirectoryPath(dirPath); + } + // If the directory is node_modules use it to watch, always watch it recursively + if (isNodeModulesDirectory(dirPath)) { + return canWatchDirectory(ts.getDirectoryPath(dirPath)) ? { dir: dir, dirPath: dirPath } : undefined; + } + var nonRecursive = true; + // Use some ancestor of the root directory + var subDirectoryPath, subDirectory; + if (rootPath !== undefined) { + while (!isInDirectoryPath(dirPath, rootPath)) { + var parentPath = ts.getDirectoryPath(dirPath); + if (parentPath === dirPath) { + break; + } + nonRecursive = false; + subDirectoryPath = dirPath; + subDirectory = dir; + dirPath = parentPath; + dir = ts.getDirectoryPath(dir); + } + } + return canWatchDirectory(dirPath) ? { dir: subDirectory || dir, dirPath: subDirectoryPath || dirPath, nonRecursive: nonRecursive } : undefined; + } + function isPathWithDefaultFailedLookupExtension(path) { + return ts.fileExtensionIsOneOf(path, failedLookupDefaultExtensions); + } + function watchFailedLookupLocationsOfExternalModuleResolutions(name, resolution) { + // No need to set the resolution refCount + if (resolution.failedLookupLocations && resolution.failedLookupLocations.length) { + if (resolution.refCount) { + resolution.refCount++; + } + else { + resolution.refCount = 1; + if (ts.isExternalModuleNameRelative(name)) { + watchFailedLookupLocationOfResolution(resolution); + } + else { + nonRelativeExternalModuleResolutions.add(name, resolution); + } + } + } + } + function watchFailedLookupLocationOfResolution(resolution) { + ts.Debug.assert(!!resolution.refCount); + var failedLookupLocations = resolution.failedLookupLocations; + var setAtRoot = false; + for (var _i = 0, failedLookupLocations_1 = failedLookupLocations; _i < failedLookupLocations_1.length; _i++) { + var failedLookupLocation = failedLookupLocations_1[_i]; + var failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation); + var toWatch = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath); + if (toWatch) { + var dir = toWatch.dir, dirPath = toWatch.dirPath, nonRecursive = toWatch.nonRecursive; + // If the failed lookup location path is not one of the supported extensions, + // store it in the custom path + if (!isPathWithDefaultFailedLookupExtension(failedLookupLocationPath)) { + var refCount = customFailedLookupPaths.get(failedLookupLocationPath) || 0; + customFailedLookupPaths.set(failedLookupLocationPath, refCount + 1); + } + if (dirPath === rootPath) { + ts.Debug.assert(!nonRecursive); + setAtRoot = true; + } + else { + setDirectoryWatcher(dir, dirPath, nonRecursive); + } + } + } + if (setAtRoot) { + // This is always non recursive + setDirectoryWatcher(rootDir, rootPath, /*nonRecursive*/ true); // TODO: GH#18217 + } + } + function setRefCountToUndefined(resolution) { + resolution.refCount = undefined; + } + function watchFailedLookupLocationOfNonRelativeModuleResolutions(resolutions, name) { + var program = resolutionHost.getCurrentProgram(); + var updateResolution = program && program.getTypeChecker().tryFindAmbientModuleWithoutAugmentations(name) ? + setRefCountToUndefined : watchFailedLookupLocationOfResolution; + resolutions.forEach(updateResolution); + } + function setDirectoryWatcher(dir, dirPath, nonRecursive) { + var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath); + if (dirWatcher) { + ts.Debug.assert(!!nonRecursive === !!dirWatcher.nonRecursive); + dirWatcher.refCount++; + } + else { + directoryWatchesOfFailedLookups.set(dirPath, { watcher: createDirectoryWatcher(dir, dirPath, nonRecursive), refCount: 1, nonRecursive: nonRecursive }); + } + } + function stopWatchFailedLookupLocationOfResolution(resolution) { + if (!resolution.refCount) { + return; + } + resolution.refCount--; + if (resolution.refCount) { + return; + } + var failedLookupLocations = resolution.failedLookupLocations; + var removeAtRoot = false; + for (var _i = 0, failedLookupLocations_2 = failedLookupLocations; _i < failedLookupLocations_2.length; _i++) { + var failedLookupLocation = failedLookupLocations_2[_i]; + var failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation); + var toWatch = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath); + if (toWatch) { + var dirPath = toWatch.dirPath; + var refCount = customFailedLookupPaths.get(failedLookupLocationPath); + if (refCount) { + if (refCount === 1) { + customFailedLookupPaths.delete(failedLookupLocationPath); + } + else { + ts.Debug.assert(refCount > 1); + customFailedLookupPaths.set(failedLookupLocationPath, refCount - 1); + } + } + if (dirPath === rootPath) { + removeAtRoot = true; + } + else { + removeDirectoryWatcher(dirPath); + } + } + } + if (removeAtRoot) { + removeDirectoryWatcher(rootPath); + } + } + function removeDirectoryWatcher(dirPath) { + var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath); + // Do not close the watcher yet since it might be needed by other failed lookup locations. + dirWatcher.refCount--; + } + function createDirectoryWatcher(directory, dirPath, nonRecursive) { + return resolutionHost.watchDirectoryOfFailedLookupLocation(directory, function (fileOrDirectory) { + var fileOrDirectoryPath = resolutionHost.toPath(fileOrDirectory); + if (cachedDirectoryStructureHost) { + // Since the file existence changed, update the sourceFiles cache + cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); + } + if (!allFilesHaveInvalidatedResolution && invalidateResolutionOfFailedLookupLocation(fileOrDirectoryPath, dirPath === fileOrDirectoryPath)) { + resolutionHost.onInvalidatedResolution(); + } + }, nonRecursive ? 0 /* None */ : 1 /* Recursive */); + } + function removeResolutionsOfFileFromCache(cache, filePath) { + // Deleted file, stop watching failed lookups for all the resolutions in the file + var resolutions = cache.get(filePath); + if (resolutions) { + resolutions.forEach(stopWatchFailedLookupLocationOfResolution); + cache.delete(filePath); + } + } + function removeResolutionsFromProjectReferenceRedirects(filePath) { + if (!ts.fileExtensionIs(filePath, ".json" /* Json */)) { + return; + } + var program = resolutionHost.getCurrentProgram(); + if (!program) { + return; + } + // If this file is input file for the referenced project, get it + var resolvedProjectReference = program.getResolvedProjectReferenceByPath(filePath); + if (!resolvedProjectReference) { + return; + } + // filePath is for the projectReference and the containing file is from this project reference, invalidate the resolution + resolvedProjectReference.commandLine.fileNames.forEach(function (f) { return removeResolutionsOfFile(resolutionHost.toPath(f)); }); + } + function removeResolutionsOfFile(filePath) { + removeResolutionsOfFileFromCache(resolvedModuleNames, filePath); + removeResolutionsOfFileFromCache(resolvedTypeReferenceDirectives, filePath); + } + function invalidateResolutionCache(cache, isInvalidatedResolution, getResolutionWithResolvedFileName) { + var seen = ts.createMap(); + cache.forEach(function (resolutions, containingFilePath) { + var dirPath = ts.getDirectoryPath(containingFilePath); + var seenInDir = seen.get(dirPath); + if (!seenInDir) { + seenInDir = ts.createMap(); + seen.set(dirPath, seenInDir); + } + resolutions.forEach(function (resolution, name) { + if (seenInDir.has(name)) { + return; + } + seenInDir.set(name, true); + if (!resolution.isInvalidated && isInvalidatedResolution(resolution, getResolutionWithResolvedFileName)) { + // Mark the file as needing re-evaluation of module resolution instead of using it blindly. + resolution.isInvalidated = true; + (filesWithInvalidatedResolutions || (filesWithInvalidatedResolutions = ts.createMap())).set(containingFilePath, true); + } + }); + }); + } + function hasReachedResolutionIterationLimit() { + var maxSize = resolutionHost.maxNumberOfFilesToIterateForInvalidation || ts.maxNumberOfFilesToIterateForInvalidation; + return resolvedModuleNames.size > maxSize || resolvedTypeReferenceDirectives.size > maxSize; + } + function invalidateResolutions(isInvalidatedResolution) { + // If more than maxNumberOfFilesToIterateForInvalidation present, + // just invalidated all files and recalculate the resolutions for files instead + if (hasReachedResolutionIterationLimit()) { + allFilesHaveInvalidatedResolution = true; + return; + } + invalidateResolutionCache(resolvedModuleNames, isInvalidatedResolution, getResolvedModule); + invalidateResolutionCache(resolvedTypeReferenceDirectives, isInvalidatedResolution, getResolvedTypeReferenceDirective); + } + function invalidateResolutionOfFile(filePath) { + removeResolutionsOfFile(filePath); + invalidateResolutions( + // Resolution is invalidated if the resulting file name is same as the deleted file path + function (resolution, getResolutionWithResolvedFileName) { + var result = getResolutionWithResolvedFileName(resolution); + return !!result && resolutionHost.toPath(result.resolvedFileName) === filePath; // TODO: GH#18217 + }); + } + function setFilesWithInvalidatedNonRelativeUnresolvedImports(filesMap) { + ts.Debug.assert(filesWithInvalidatedNonRelativeUnresolvedImports === filesMap || filesWithInvalidatedNonRelativeUnresolvedImports === undefined); + filesWithInvalidatedNonRelativeUnresolvedImports = filesMap; + } + function invalidateResolutionOfFailedLookupLocation(fileOrDirectoryPath, isCreatingWatchedDirectory) { + var isChangedFailedLookupLocation; + if (isCreatingWatchedDirectory) { + // Watching directory is created + // Invalidate any resolution has failed lookup in this directory + isChangedFailedLookupLocation = function (location) { return isInDirectoryPath(fileOrDirectoryPath, resolutionHost.toPath(location)); }; + } + else { + // If something to do with folder/file starting with "." in node_modules folder, skip it + if (isPathInNodeModulesStartingWithDot(fileOrDirectoryPath)) + return false; + // Some file or directory in the watching directory is created + // Return early if it does not have any of the watching extension or not the custom failed lookup path + var dirOfFileOrDirectory = ts.getDirectoryPath(fileOrDirectoryPath); + if (isNodeModulesAtTypesDirectory(fileOrDirectoryPath) || isNodeModulesDirectory(fileOrDirectoryPath) || + isNodeModulesAtTypesDirectory(dirOfFileOrDirectory) || isNodeModulesDirectory(dirOfFileOrDirectory)) { + // Invalidate any resolution from this directory + isChangedFailedLookupLocation = function (location) { + var locationPath = resolutionHost.toPath(location); + return locationPath === fileOrDirectoryPath || ts.startsWith(resolutionHost.toPath(location), fileOrDirectoryPath); + }; + } + else { + if (!isPathWithDefaultFailedLookupExtension(fileOrDirectoryPath) && !customFailedLookupPaths.has(fileOrDirectoryPath)) { + return false; + } + // Ignore emits from the program + if (ts.isEmittedFileOfProgram(resolutionHost.getCurrentProgram(), fileOrDirectoryPath)) { + return false; + } + // Resolution need to be invalidated if failed lookup location is same as the file or directory getting created + isChangedFailedLookupLocation = function (location) { return resolutionHost.toPath(location) === fileOrDirectoryPath; }; + } + } + var hasChangedFailedLookupLocation = function (resolution) { return ts.some(resolution.failedLookupLocations, isChangedFailedLookupLocation); }; + var invalidatedFilesCount = filesWithInvalidatedResolutions && filesWithInvalidatedResolutions.size; + invalidateResolutions( + // Resolution is invalidated if the resulting file name is same as the deleted file path + hasChangedFailedLookupLocation); + return allFilesHaveInvalidatedResolution || filesWithInvalidatedResolutions && filesWithInvalidatedResolutions.size !== invalidatedFilesCount; + } + function closeTypeRootsWatch() { + ts.clearMap(typeRootsWatches, ts.closeFileWatcher); + } + function getDirectoryToWatchFailedLookupLocationFromTypeRoot(typeRoot, typeRootPath) { + if (allFilesHaveInvalidatedResolution) { + return undefined; + } + if (isInDirectoryPath(rootPath, typeRootPath)) { + return rootPath; + } + var toWatch = getDirectoryToWatchFromFailedLookupLocationDirectory(typeRoot, typeRootPath); + return toWatch && directoryWatchesOfFailedLookups.has(toWatch.dirPath) ? toWatch.dirPath : undefined; + } + function createTypeRootsWatch(typeRootPath, typeRoot) { + // Create new watch and recursive info + return resolutionHost.watchTypeRootsDirectory(typeRoot, function (fileOrDirectory) { + var fileOrDirectoryPath = resolutionHost.toPath(fileOrDirectory); + if (cachedDirectoryStructureHost) { + // Since the file existence changed, update the sourceFiles cache + cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); + } + // For now just recompile + // We could potentially store more data here about whether it was/would be really be used or not + // and with that determine to trigger compilation but for now this is enough + resolutionHost.onChangedAutomaticTypeDirectiveNames(); + // Since directory watchers invoked are flaky, the failed lookup location events might not be triggered + // So handle to failed lookup locations here as well to ensure we are invalidating resolutions + var dirPath = getDirectoryToWatchFailedLookupLocationFromTypeRoot(typeRoot, typeRootPath); + if (dirPath && invalidateResolutionOfFailedLookupLocation(fileOrDirectoryPath, dirPath === fileOrDirectoryPath)) { + resolutionHost.onInvalidatedResolution(); + } + }, 1 /* Recursive */); + } + /** + * Watches the types that would get added as part of getAutomaticTypeDirectiveNames + * To be called when compiler options change + */ + function updateTypeRootsWatch() { + var options = resolutionHost.getCompilationSettings(); + if (options.types) { + // No need to do any watch since resolution cache is going to handle the failed lookups + // for the types added by this + closeTypeRootsWatch(); + return; + } + // we need to assume the directories exist to ensure that we can get all the type root directories that get included + // But filter directories that are at root level to say directory doesnt exist, so that we arent watching them + var typeRoots = ts.getEffectiveTypeRoots(options, { directoryExists: directoryExistsForTypeRootWatch, getCurrentDirectory: getCurrentDirectory }); + if (typeRoots) { + ts.mutateMap(typeRootsWatches, ts.arrayToMap(typeRoots, function (tr) { return resolutionHost.toPath(tr); }), { + createNewValue: createTypeRootsWatch, + onDeleteValue: ts.closeFileWatcher + }); + } + else { + closeTypeRootsWatch(); + } + } + /** + * Use this function to return if directory exists to get type roots to watch + * If we return directory exists then only the paths will be added to type roots + * Hence return true for all directories except root directories which are filtered from watching + */ + function directoryExistsForTypeRootWatch(nodeTypesDirectory) { + var dir = ts.getDirectoryPath(ts.getDirectoryPath(nodeTypesDirectory)); + var dirPath = resolutionHost.toPath(dir); + return dirPath === rootPath || canWatchDirectory(dirPath); + } + } + ts.createResolutionCache = createResolutionCache; +})(ts || (ts = {})); +// Used by importFixes, getEditsForFileRename, and declaration emit to synthesize import module specifiers. +/* @internal */ +var ts; +(function (ts) { + var moduleSpecifiers; + (function (moduleSpecifiers) { + var RelativePreference; + (function (RelativePreference) { + RelativePreference[RelativePreference["Relative"] = 0] = "Relative"; + RelativePreference[RelativePreference["NonRelative"] = 1] = "NonRelative"; + RelativePreference[RelativePreference["Auto"] = 2] = "Auto"; + })(RelativePreference || (RelativePreference = {})); + // See UserPreferences#importPathEnding + var Ending; + (function (Ending) { + Ending[Ending["Minimal"] = 0] = "Minimal"; + Ending[Ending["Index"] = 1] = "Index"; + Ending[Ending["JsExtension"] = 2] = "JsExtension"; + })(Ending || (Ending = {})); + function getPreferences(_a, compilerOptions, importingSourceFile) { + var importModuleSpecifierPreference = _a.importModuleSpecifierPreference, importModuleSpecifierEnding = _a.importModuleSpecifierEnding; + return { + relativePreference: importModuleSpecifierPreference === "relative" ? 0 /* Relative */ : importModuleSpecifierPreference === "non-relative" ? 1 /* NonRelative */ : 2 /* Auto */, + ending: getEnding(), + }; + function getEnding() { + switch (importModuleSpecifierEnding) { + case "minimal": return 0 /* Minimal */; + case "index": return 1 /* Index */; + case "js": return 2 /* JsExtension */; + default: return usesJsExtensionOnImports(importingSourceFile) ? 2 /* JsExtension */ + : ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.NodeJs ? 1 /* Index */ : 0 /* Minimal */; + } + } + } + function getPreferencesForUpdate(compilerOptions, oldImportSpecifier) { + return { + relativePreference: ts.isExternalModuleNameRelative(oldImportSpecifier) ? 0 /* Relative */ : 1 /* NonRelative */, + ending: ts.hasJSOrJsonFileExtension(oldImportSpecifier) ? 2 /* JsExtension */ + : ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.NodeJs || ts.endsWith(oldImportSpecifier, "index") ? 1 /* Index */ : 0 /* Minimal */, + }; + } + function updateModuleSpecifier(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, oldImportSpecifier) { + var res = getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, getPreferencesForUpdate(compilerOptions, oldImportSpecifier)); + if (res === oldImportSpecifier) + return undefined; + return res; + } + moduleSpecifiers.updateModuleSpecifier = updateModuleSpecifier; + // Note: importingSourceFile is just for usesJsExtensionOnImports + function getModuleSpecifier(compilerOptions, importingSourceFile, importingSourceFileName, toFileName, host, files, preferences, redirectTargetsMap) { + if (preferences === void 0) { preferences = {}; } + return getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, getPreferences(preferences, compilerOptions, importingSourceFile)); + } + moduleSpecifiers.getModuleSpecifier = getModuleSpecifier; + function getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, preferences) { + var info = getInfo(importingSourceFileName, host); + var modulePaths = getAllModulePaths(files, importingSourceFileName, toFileName, info.getCanonicalFileName, host, redirectTargetsMap); + return ts.firstDefined(modulePaths, function (moduleFileName) { return tryGetModuleNameAsNodeModule(moduleFileName, info, host, compilerOptions); }) || + getLocalModuleSpecifier(toFileName, info, compilerOptions, preferences); + } + // Returns an import for each symlink and for the realpath. + function getModuleSpecifiers(moduleSymbol, compilerOptions, importingSourceFile, host, files, userPreferences, redirectTargetsMap) { + var ambient = tryGetModuleNameFromAmbientModule(moduleSymbol); + if (ambient) + return [ambient]; + var info = getInfo(importingSourceFile.path, host); + var moduleSourceFile = ts.getSourceFileOfNode(moduleSymbol.valueDeclaration || ts.getNonAugmentationDeclaration(moduleSymbol)); + var modulePaths = getAllModulePaths(files, importingSourceFile.path, moduleSourceFile.fileName, info.getCanonicalFileName, host, redirectTargetsMap); + var preferences = getPreferences(userPreferences, compilerOptions, importingSourceFile); + var global = ts.mapDefined(modulePaths, function (moduleFileName) { return tryGetModuleNameAsNodeModule(moduleFileName, info, host, compilerOptions); }); + return global.length ? global : modulePaths.map(function (moduleFileName) { return getLocalModuleSpecifier(moduleFileName, info, compilerOptions, preferences); }); + } + moduleSpecifiers.getModuleSpecifiers = getModuleSpecifiers; + // importingSourceFileName is separate because getEditsForFileRename may need to specify an updated path + function getInfo(importingSourceFileName, host) { + var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames ? host.useCaseSensitiveFileNames() : true); + var sourceDirectory = ts.getDirectoryPath(importingSourceFileName); + return { getCanonicalFileName: getCanonicalFileName, sourceDirectory: sourceDirectory }; + } + function getLocalModuleSpecifier(moduleFileName, _a, compilerOptions, _b) { + var getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory; + var ending = _b.ending, relativePreference = _b.relativePreference; + var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths, rootDirs = compilerOptions.rootDirs; + var relativePath = rootDirs && tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName) || + removeExtensionAndIndexPostFix(ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, moduleFileName, getCanonicalFileName)), ending, compilerOptions); + if (!baseUrl || relativePreference === 0 /* Relative */) { + return relativePath; + } + var relativeToBaseUrl = getRelativePathIfInDirectory(moduleFileName, baseUrl, getCanonicalFileName); + if (!relativeToBaseUrl) { + return relativePath; + } + var importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, ending, compilerOptions); + var fromPaths = paths && tryGetModuleNameFromPaths(ts.removeFileExtension(relativeToBaseUrl), importRelativeToBaseUrl, paths); + var nonRelative = fromPaths === undefined ? importRelativeToBaseUrl : fromPaths; + if (relativePreference === 1 /* NonRelative */) { + return nonRelative; + } + if (relativePreference !== 2 /* Auto */) + ts.Debug.assertNever(relativePreference); + // Prefer a relative import over a baseUrl import if it has fewer components. + return isPathRelativeToParent(nonRelative) || countPathComponents(relativePath) < countPathComponents(nonRelative) ? relativePath : nonRelative; + } + function countPathComponents(path) { + var count = 0; + for (var i = ts.startsWith(path, "./") ? 2 : 0; i < path.length; i++) { + if (path.charCodeAt(i) === 47 /* slash */) + count++; + } + return count; + } + moduleSpecifiers.countPathComponents = countPathComponents; + function usesJsExtensionOnImports(_a) { + var imports = _a.imports; + return ts.firstDefined(imports, function (_a) { + var text = _a.text; + return ts.pathIsRelative(text) ? ts.hasJSOrJsonFileExtension(text) : undefined; + }) || false; + } + function stringsEqual(a, b, getCanonicalFileName) { + return getCanonicalFileName(a) === getCanonicalFileName(b); + } + // KLUDGE: Don't assume one 'node_modules' links to another. More likely a single directory inside the node_modules is the symlink. + // ALso, don't assume that an `@foo` directory is linked. More likely the contents of that are linked. + function isNodeModulesOrScopedPackageDirectory(s, getCanonicalFileName) { + return getCanonicalFileName(s) === "node_modules" || ts.startsWith(s, "@"); + } + function guessDirectorySymlink(a, b, cwd, getCanonicalFileName) { + var aParts = ts.getPathComponents(ts.toPath(a, cwd, getCanonicalFileName)); + var bParts = ts.getPathComponents(ts.toPath(b, cwd, getCanonicalFileName)); + while (!isNodeModulesOrScopedPackageDirectory(aParts[aParts.length - 2], getCanonicalFileName) && + !isNodeModulesOrScopedPackageDirectory(bParts[bParts.length - 2], getCanonicalFileName) && + stringsEqual(aParts[aParts.length - 1], bParts[bParts.length - 1], getCanonicalFileName)) { + aParts.pop(); + bParts.pop(); + } + return [ts.getPathFromPathComponents(aParts), ts.getPathFromPathComponents(bParts)]; + } + function discoverProbableSymlinks(files, getCanonicalFileName, cwd) { + var result = ts.createMap(); + var symlinks = ts.mapDefined(files, function (sf) { + return sf.resolvedModules && ts.firstDefinedIterator(sf.resolvedModules.values(), function (res) { + return res && res.originalPath && res.resolvedFileName !== res.originalPath ? [res.resolvedFileName, res.originalPath] : undefined; + }); + }); + for (var _i = 0, symlinks_1 = symlinks; _i < symlinks_1.length; _i++) { + var _a = symlinks_1[_i], resolvedPath = _a[0], originalPath = _a[1]; + var _b = guessDirectorySymlink(resolvedPath, originalPath, cwd, getCanonicalFileName), commonResolved = _b[0], commonOriginal = _b[1]; + result.set(commonOriginal, commonResolved); + } + return result; + } + /** + * Looks for existing imports that use symlinks to this module. + * Symlinks will be returned first so they are preferred over the real path. + */ + function getAllModulePaths(files, importingFileName, importedFileName, getCanonicalFileName, host, redirectTargetsMap) { + var redirects = redirectTargetsMap.get(importedFileName); + var importedFileNames = redirects ? redirects.concat([importedFileName]) : [importedFileName]; + var cwd = host.getCurrentDirectory ? host.getCurrentDirectory() : ""; + var targets = importedFileNames.map(function (f) { return ts.getNormalizedAbsolutePath(f, cwd); }); + var links = discoverProbableSymlinks(files, getCanonicalFileName, cwd); + var result = []; + var compareStrings = (!host.useCaseSensitiveFileNames || host.useCaseSensitiveFileNames()) ? ts.compareStringsCaseSensitive : ts.compareStringsCaseInsensitive; + links.forEach(function (resolved, path) { + if (ts.startsWithDirectory(importingFileName, resolved, getCanonicalFileName)) { + return; // Don't want to a package to globally import from itself + } + var target = targets.find(function (t) { return compareStrings(t.slice(0, resolved.length + 1), resolved + "/") === 0 /* EqualTo */; }); + if (target === undefined) + return; + var relative = ts.getRelativePathFromDirectory(resolved, target, getCanonicalFileName); + var option = ts.resolvePath(path, relative); + if (!host.fileExists || host.fileExists(option)) { + result.push(option); + } + }); + result.push.apply(result, targets); + return result; + } + function tryGetModuleNameFromAmbientModule(moduleSymbol) { + var decl = ts.find(moduleSymbol.declarations, function (d) { return ts.isNonGlobalAmbientModule(d) && (!ts.isExternalModuleAugmentation(d) || !ts.isExternalModuleNameRelative(ts.getTextOfIdentifierOrLiteral(d.name))); }); + if (decl) { + return decl.name.text; + } + } + function tryGetModuleNameFromPaths(relativeToBaseUrlWithIndex, relativeToBaseUrl, paths) { + for (var key in paths) { + for (var _i = 0, _a = paths[key]; _i < _a.length; _i++) { + var patternText_1 = _a[_i]; + var pattern = ts.removeFileExtension(ts.normalizePath(patternText_1)); + var indexOfStar = pattern.indexOf("*"); + if (indexOfStar !== -1) { + var prefix = pattern.substr(0, indexOfStar); + var suffix = pattern.substr(indexOfStar + 1); + if (relativeToBaseUrl.length >= prefix.length + suffix.length && + ts.startsWith(relativeToBaseUrl, prefix) && + ts.endsWith(relativeToBaseUrl, suffix) || + !suffix && relativeToBaseUrl === ts.removeTrailingDirectorySeparator(prefix)) { + var matchedStar = relativeToBaseUrl.substr(prefix.length, relativeToBaseUrl.length - suffix.length); + return key.replace("*", matchedStar); + } + } + else if (pattern === relativeToBaseUrl || pattern === relativeToBaseUrlWithIndex) { + return key; + } + } + } + } + function tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName) { + var normalizedTargetPath = getPathRelativeToRootDirs(moduleFileName, rootDirs, getCanonicalFileName); + if (normalizedTargetPath === undefined) { + return undefined; + } + var normalizedSourcePath = getPathRelativeToRootDirs(sourceDirectory, rootDirs, getCanonicalFileName); + var relativePath = normalizedSourcePath !== undefined ? ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(normalizedSourcePath, normalizedTargetPath, getCanonicalFileName)) : normalizedTargetPath; + return ts.removeFileExtension(relativePath); + } + function tryGetModuleNameAsNodeModule(moduleFileName, _a, host, options) { + var getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory; + if (!host.fileExists || !host.readFile) { + return undefined; + } + var parts = getNodeModulePathParts(moduleFileName); + if (!parts) { + return undefined; + } + var packageRootPath = moduleFileName.substring(0, parts.packageRootIndex); + var packageJsonPath = ts.combinePaths(packageRootPath, "package.json"); + var packageJsonContent = host.fileExists(packageJsonPath) + ? JSON.parse(host.readFile(packageJsonPath)) + : undefined; + var versionPaths = packageJsonContent && packageJsonContent.typesVersions + ? ts.getPackageJsonTypesVersionsPaths(packageJsonContent.typesVersions) + : undefined; + if (versionPaths) { + var subModuleName = moduleFileName.slice(parts.packageRootIndex + 1); + var fromPaths = tryGetModuleNameFromPaths(ts.removeFileExtension(subModuleName), removeExtensionAndIndexPostFix(subModuleName, 0 /* Minimal */, options), versionPaths.paths); + if (fromPaths !== undefined) { + moduleFileName = ts.combinePaths(moduleFileName.slice(0, parts.packageRootIndex), fromPaths); + } + } + // Simplify the full file path to something that can be resolved by Node. + // If the module could be imported by a directory name, use that directory's name + var moduleSpecifier = getDirectoryOrExtensionlessFileName(moduleFileName); + // Get a path that's relative to node_modules or the importing file's path + // if node_modules folder is in this folder or any of its parent folders, no need to keep it. + if (!ts.startsWith(sourceDirectory, getCanonicalFileName(moduleSpecifier.substring(0, parts.topLevelNodeModulesIndex)))) + return undefined; + // If the module was found in @types, get the actual Node package name + var nodeModulesDirectoryName = moduleSpecifier.substring(parts.topLevelPackageNameIndex + 1); + var packageName = ts.getPackageNameFromTypesPackageName(nodeModulesDirectoryName); + // For classic resolution, only allow importing from node_modules/@types, not other node_modules + return ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs && packageName === nodeModulesDirectoryName ? undefined : packageName; + function getDirectoryOrExtensionlessFileName(path) { + // If the file is the main module, it can be imported by the package name + if (packageJsonContent) { + var mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main; + if (mainFileRelative) { + var mainExportFile = ts.toPath(mainFileRelative, packageRootPath, getCanonicalFileName); + if (ts.removeFileExtension(mainExportFile) === ts.removeFileExtension(getCanonicalFileName(path))) { + return packageRootPath; + } + } + } + // We still have a file name - remove the extension + var fullModulePathWithoutExtension = ts.removeFileExtension(path); + // If the file is /index, it can be imported by its directory name + // IFF there is not _also_ a file by the same name + if (getCanonicalFileName(fullModulePathWithoutExtension.substring(parts.fileNameIndex)) === "/index" && !tryGetAnyFileFromPath(host, fullModulePathWithoutExtension.substring(0, parts.fileNameIndex))) { + return fullModulePathWithoutExtension.substring(0, parts.fileNameIndex); + } + return fullModulePathWithoutExtension; + } + } + function tryGetAnyFileFromPath(host, path) { + if (!host.fileExists) + return; + // We check all js, `node` and `json` extensions in addition to TS, since node module resolution would also choose those over the directory + var extensions = ts.getSupportedExtensions({ allowJs: true }, [{ extension: "node", isMixedContent: false }, { extension: "json", isMixedContent: false, scriptKind: 6 /* JSON */ }]); + for (var _i = 0, extensions_3 = extensions; _i < extensions_3.length; _i++) { + var e = extensions_3[_i]; + var fullPath = path + e; + if (host.fileExists(fullPath)) { + return fullPath; + } + } + } + function getNodeModulePathParts(fullPath) { + // If fullPath can't be valid module file within node_modules, returns undefined. + // Example of expected pattern: /base/path/node_modules/[@scope/otherpackage/@otherscope/node_modules/]package/[subdirectory/]file.js + // Returns indices: ^ ^ ^ ^ + var topLevelNodeModulesIndex = 0; + var topLevelPackageNameIndex = 0; + var packageRootIndex = 0; + var fileNameIndex = 0; + var States; + (function (States) { + States[States["BeforeNodeModules"] = 0] = "BeforeNodeModules"; + States[States["NodeModules"] = 1] = "NodeModules"; + States[States["Scope"] = 2] = "Scope"; + States[States["PackageContent"] = 3] = "PackageContent"; + })(States || (States = {})); + var partStart = 0; + var partEnd = 0; + var state = 0 /* BeforeNodeModules */; + while (partEnd >= 0) { + partStart = partEnd; + partEnd = fullPath.indexOf("/", partStart + 1); + switch (state) { + case 0 /* BeforeNodeModules */: + if (fullPath.indexOf(ts.nodeModulesPathPart, partStart) === partStart) { + topLevelNodeModulesIndex = partStart; + topLevelPackageNameIndex = partEnd; + state = 1 /* NodeModules */; + } + break; + case 1 /* NodeModules */: + case 2 /* Scope */: + if (state === 1 /* NodeModules */ && fullPath.charAt(partStart + 1) === "@") { + state = 2 /* Scope */; + } + else { + packageRootIndex = partEnd; + state = 3 /* PackageContent */; + } + break; + case 3 /* PackageContent */: + if (fullPath.indexOf(ts.nodeModulesPathPart, partStart) === partStart) { + state = 1 /* NodeModules */; + } + else { + state = 3 /* PackageContent */; + } + break; + } + } + fileNameIndex = partStart; + return state > 1 /* NodeModules */ ? { topLevelNodeModulesIndex: topLevelNodeModulesIndex, topLevelPackageNameIndex: topLevelPackageNameIndex, packageRootIndex: packageRootIndex, fileNameIndex: fileNameIndex } : undefined; + } + function getPathRelativeToRootDirs(path, rootDirs, getCanonicalFileName) { + return ts.firstDefined(rootDirs, function (rootDir) { + var relativePath = getRelativePathIfInDirectory(path, rootDir, getCanonicalFileName); // TODO: GH#18217 + return isPathRelativeToParent(relativePath) ? undefined : relativePath; + }); + } + function removeExtensionAndIndexPostFix(fileName, ending, options) { + if (ts.fileExtensionIs(fileName, ".json" /* Json */)) + return fileName; + var noExtension = ts.removeFileExtension(fileName); + switch (ending) { + case 0 /* Minimal */: + return ts.removeSuffix(noExtension, "/index"); + case 1 /* Index */: + return noExtension; + case 2 /* JsExtension */: + return noExtension + getJSExtensionForFile(fileName, options); + default: + return ts.Debug.assertNever(ending); + } + } + function getJSExtensionForFile(fileName, options) { + var ext = ts.extensionFromPath(fileName); + switch (ext) { + case ".ts" /* Ts */: + case ".d.ts" /* Dts */: + return ".js" /* Js */; + case ".tsx" /* Tsx */: + return options.jsx === 1 /* Preserve */ ? ".jsx" /* Jsx */ : ".js" /* Js */; + case ".js" /* Js */: + case ".jsx" /* Jsx */: + case ".json" /* Json */: + return ext; + default: + return ts.Debug.assertNever(ext); + } + } + function getRelativePathIfInDirectory(path, directoryPath, getCanonicalFileName) { + var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); + return ts.isRootedDiskPath(relativePath) ? undefined : relativePath; + } + function isPathRelativeToParent(path) { + return ts.startsWith(path, ".."); + } + })(moduleSpecifiers = ts.moduleSpecifiers || (ts.moduleSpecifiers = {})); +})(ts || (ts = {})); +/*@internal*/ +var ts; +(function (ts) { + var sysFormatDiagnosticsHost = ts.sys ? { + getCurrentDirectory: function () { return ts.sys.getCurrentDirectory(); }, + getNewLine: function () { return ts.sys.newLine; }, + getCanonicalFileName: ts.createGetCanonicalFileName(ts.sys.useCaseSensitiveFileNames) + } : undefined; // TODO: GH#18217 + /** + * Create a function that reports error by writing to the system and handles the formating of the diagnostic + */ + function createDiagnosticReporter(system, pretty) { + var host = system === ts.sys ? sysFormatDiagnosticsHost : { + getCurrentDirectory: function () { return system.getCurrentDirectory(); }, + getNewLine: function () { return system.newLine; }, + getCanonicalFileName: ts.createGetCanonicalFileName(system.useCaseSensitiveFileNames), + }; + if (!pretty) { + return function (diagnostic) { return system.write(ts.formatDiagnostic(diagnostic, host)); }; + } + var diagnostics = new Array(1); + return function (diagnostic) { + diagnostics[0] = diagnostic; + system.write(ts.formatDiagnosticsWithColorAndContext(diagnostics, host) + host.getNewLine()); + diagnostics[0] = undefined; // TODO: GH#18217 + }; + } + ts.createDiagnosticReporter = createDiagnosticReporter; + /** + * @returns Whether the screen was cleared. + */ + function clearScreenIfNotWatchingForFileChanges(system, diagnostic, options) { + if (system.clearScreen && + !options.preserveWatchOutput && + !options.extendedDiagnostics && + !options.diagnostics && + ts.contains(ts.screenStartingMessageCodes, diagnostic.code)) { + system.clearScreen(); + return true; + } + return false; + } + ts.screenStartingMessageCodes = [ + ts.Diagnostics.Starting_compilation_in_watch_mode.code, + ts.Diagnostics.File_change_detected_Starting_incremental_compilation.code, + ]; + function getPlainDiagnosticFollowingNewLines(diagnostic, newLine) { + return ts.contains(ts.screenStartingMessageCodes, diagnostic.code) + ? newLine + newLine + : newLine; + } + /** + * Create a function that reports watch status by writing to the system and handles the formating of the diagnostic + */ + function createWatchStatusReporter(system, pretty) { + return pretty ? + function (diagnostic, newLine, options) { + clearScreenIfNotWatchingForFileChanges(system, diagnostic, options); + var output = "[" + ts.formatColorAndReset(new Date().toLocaleTimeString(), ts.ForegroundColorEscapeSequences.Grey) + "] "; + output += "" + ts.flattenDiagnosticMessageText(diagnostic.messageText, system.newLine) + (newLine + newLine); + system.write(output); + } : + function (diagnostic, newLine, options) { + var output = ""; + if (!clearScreenIfNotWatchingForFileChanges(system, diagnostic, options)) { + output += newLine; + } + output += new Date().toLocaleTimeString() + " - "; + output += "" + ts.flattenDiagnosticMessageText(diagnostic.messageText, system.newLine) + getPlainDiagnosticFollowingNewLines(diagnostic, newLine); + system.write(output); + }; + } + ts.createWatchStatusReporter = createWatchStatusReporter; + /** Parses config file using System interface */ + function parseConfigFileWithSystem(configFileName, optionsToExtend, system, reportDiagnostic) { + var host = system; + host.onUnRecoverableConfigFileDiagnostic = function (diagnostic) { return reportUnrecoverableDiagnostic(ts.sys, reportDiagnostic, diagnostic); }; + var result = ts.getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host); + host.onUnRecoverableConfigFileDiagnostic = undefined; // TODO: GH#18217 + return result; + } + ts.parseConfigFileWithSystem = parseConfigFileWithSystem; + function getErrorCountForSummary(diagnostics) { + return ts.countWhere(diagnostics, function (diagnostic) { return diagnostic.category === ts.DiagnosticCategory.Error; }); + } + ts.getErrorCountForSummary = getErrorCountForSummary; + function getWatchErrorSummaryDiagnosticMessage(errorCount) { + return errorCount === 1 ? + ts.Diagnostics.Found_1_error_Watching_for_file_changes : + ts.Diagnostics.Found_0_errors_Watching_for_file_changes; + } + ts.getWatchErrorSummaryDiagnosticMessage = getWatchErrorSummaryDiagnosticMessage; + function getErrorSummaryText(errorCount, newLine) { + if (errorCount === 0) + return ""; + var d = ts.createCompilerDiagnostic(errorCount === 1 ? ts.Diagnostics.Found_1_error : ts.Diagnostics.Found_0_errors, errorCount); + return "" + newLine + ts.flattenDiagnosticMessageText(d.messageText, newLine) + newLine + newLine; + } + ts.getErrorSummaryText = getErrorSummaryText; + /** + * Helper that emit files, report diagnostics and lists emitted and/or source files depending on compiler options + */ + function emitFilesAndReportErrors(program, reportDiagnostic, writeFileName, reportSummary, writeFile) { + // First get and report any syntactic errors. + var diagnostics = program.getConfigFileParsingDiagnostics().slice(); + var configFileParsingDiagnosticsLength = diagnostics.length; + ts.addRange(diagnostics, program.getSyntacticDiagnostics()); + var reportSemanticDiagnostics = false; + // If we didn't have any syntactic errors, then also try getting the global and + // semantic errors. + if (diagnostics.length === configFileParsingDiagnosticsLength) { + ts.addRange(diagnostics, program.getOptionsDiagnostics()); + ts.addRange(diagnostics, program.getGlobalDiagnostics()); + if (diagnostics.length === configFileParsingDiagnosticsLength) { + reportSemanticDiagnostics = true; + } + } + // Emit and report any errors we ran into. + var _a = program.emit(/*targetSourceFile*/ undefined, writeFile), emittedFiles = _a.emittedFiles, emitSkipped = _a.emitSkipped, emitDiagnostics = _a.diagnostics; + ts.addRange(diagnostics, emitDiagnostics); + if (reportSemanticDiagnostics) { + ts.addRange(diagnostics, program.getSemanticDiagnostics()); + } + ts.sortAndDeduplicateDiagnostics(diagnostics).forEach(reportDiagnostic); + if (writeFileName) { + var currentDir_1 = program.getCurrentDirectory(); + ts.forEach(emittedFiles, function (file) { + var filepath = ts.getNormalizedAbsolutePath(file, currentDir_1); + writeFileName("TSFILE: " + filepath); + }); + if (program.getCompilerOptions().listFiles) { + ts.forEach(program.getSourceFiles(), function (file) { + writeFileName(file.fileName); + }); + } + } + if (reportSummary) { + reportSummary(getErrorCountForSummary(diagnostics)); + } + if (emitSkipped && diagnostics.length > 0) { + // If the emitter didn't emit anything, then pass that value along. + return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; + } + else if (diagnostics.length > 0) { + // The emitter emitted something, inform the caller if that happened in the presence + // of diagnostics or not. + return ts.ExitStatus.DiagnosticsPresent_OutputsGenerated; + } + return ts.ExitStatus.Success; + } + ts.emitFilesAndReportErrors = emitFilesAndReportErrors; + var noopFileWatcher = { close: ts.noop }; + function createWatchHost(system, reportWatchStatus) { + if (system === void 0) { system = ts.sys; } + var onWatchStatusChange = reportWatchStatus || createWatchStatusReporter(system); + return { + onWatchStatusChange: onWatchStatusChange, + watchFile: system.watchFile ? (function (path, callback, pollingInterval) { return system.watchFile(path, callback, pollingInterval); }) : function () { return noopFileWatcher; }, + watchDirectory: system.watchDirectory ? (function (path, callback, recursive) { return system.watchDirectory(path, callback, recursive); }) : function () { return noopFileWatcher; }, + setTimeout: system.setTimeout ? (function (callback, ms) { + var args = []; + for (var _i = 2; _i < arguments.length; _i++) { + args[_i - 2] = arguments[_i]; + } + var _a; + return (_a = system.setTimeout).call.apply(_a, [system, callback, ms].concat(args)); + }) : ts.noop, + clearTimeout: system.clearTimeout ? (function (timeoutId) { return system.clearTimeout(timeoutId); }) : ts.noop + }; + } + ts.createWatchHost = createWatchHost; + /** + * Creates the watch compiler host that can be extended with config file or root file names and options host + */ + function createWatchCompilerHost(system, createProgram, reportDiagnostic, reportWatchStatus) { + if (system === void 0) { system = ts.sys; } + if (!createProgram) { + createProgram = ts.createEmitAndSemanticDiagnosticsBuilderProgram; + } + var host = system; + host; // tslint:disable-line no-unused-expression (TODO: `host` is unused!) + var useCaseSensitiveFileNames = function () { return system.useCaseSensitiveFileNames; }; + var writeFileName = function (s) { return system.write(s + system.newLine); }; + var _a = createWatchHost(system, reportWatchStatus), onWatchStatusChange = _a.onWatchStatusChange, watchFile = _a.watchFile, watchDirectory = _a.watchDirectory, setTimeout = _a.setTimeout, clearTimeout = _a.clearTimeout; + return { + useCaseSensitiveFileNames: useCaseSensitiveFileNames, + getNewLine: function () { return system.newLine; }, + getCurrentDirectory: function () { return system.getCurrentDirectory(); }, + getDefaultLibLocation: getDefaultLibLocation, + getDefaultLibFileName: function (options) { return ts.combinePaths(getDefaultLibLocation(), ts.getDefaultLibFileName(options)); }, + fileExists: function (path) { return system.fileExists(path); }, + readFile: function (path, encoding) { return system.readFile(path, encoding); }, + directoryExists: function (path) { return system.directoryExists(path); }, + getDirectories: function (path) { return system.getDirectories(path); }, + readDirectory: function (path, extensions, exclude, include, depth) { return system.readDirectory(path, extensions, exclude, include, depth); }, + realpath: system.realpath && (function (path) { return system.realpath(path); }), + getEnvironmentVariable: system.getEnvironmentVariable && (function (name) { return system.getEnvironmentVariable(name); }), + watchFile: watchFile, + watchDirectory: watchDirectory, + setTimeout: setTimeout, + clearTimeout: clearTimeout, + trace: function (s) { return system.write(s); }, + onWatchStatusChange: onWatchStatusChange, + createDirectory: function (path) { return system.createDirectory(path); }, + writeFile: function (path, data, writeByteOrderMark) { return system.writeFile(path, data, writeByteOrderMark); }, + onCachedDirectoryStructureHostCreate: function (cacheHost) { return host = cacheHost || system; }, + createHash: system.createHash && (function (s) { return system.createHash(s); }), + createProgram: createProgram, + afterProgramCreate: emitFilesAndReportErrorUsingBuilder + }; + function getDefaultLibLocation() { + return ts.getDirectoryPath(ts.normalizePath(system.getExecutingFilePath())); + } + function emitFilesAndReportErrorUsingBuilder(builderProgram) { + var compilerOptions = builderProgram.getCompilerOptions(); + var newLine = ts.getNewLineCharacter(compilerOptions, function () { return system.newLine; }); + emitFilesAndReportErrors(builderProgram, reportDiagnostic, writeFileName, function (errorCount) { return onWatchStatusChange(ts.createCompilerDiagnostic(getWatchErrorSummaryDiagnosticMessage(errorCount), errorCount), newLine, compilerOptions); }); + } + } + /** + * Report error and exit + */ + function reportUnrecoverableDiagnostic(system, reportDiagnostic, diagnostic) { + reportDiagnostic(diagnostic); + system.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); + } + /** + * Creates the watch compiler host from system for config file in watch mode + */ + function createWatchCompilerHostOfConfigFile(configFileName, optionsToExtend, system, createProgram, reportDiagnostic, reportWatchStatus) { + var diagnosticReporter = reportDiagnostic || createDiagnosticReporter(system); + var host = createWatchCompilerHost(system, createProgram, diagnosticReporter, reportWatchStatus); + host.onUnRecoverableConfigFileDiagnostic = function (diagnostic) { return reportUnrecoverableDiagnostic(system, diagnosticReporter, diagnostic); }; + host.configFileName = configFileName; + host.optionsToExtend = optionsToExtend; + return host; + } + ts.createWatchCompilerHostOfConfigFile = createWatchCompilerHostOfConfigFile; + /** + * Creates the watch compiler host from system for compiling root files and options in watch mode + */ + function createWatchCompilerHostOfFilesAndCompilerOptions(rootFiles, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences) { + var host = createWatchCompilerHost(system, createProgram, reportDiagnostic || createDiagnosticReporter(system), reportWatchStatus); + host.rootFiles = rootFiles; + host.options = options; + host.projectReferences = projectReferences; + return host; + } + ts.createWatchCompilerHostOfFilesAndCompilerOptions = createWatchCompilerHostOfFilesAndCompilerOptions; +})(ts || (ts = {})); +(function (ts) { + function createWatchCompilerHost(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences) { + if (ts.isArray(rootFilesOrConfigFileName)) { + return ts.createWatchCompilerHostOfFilesAndCompilerOptions(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences); // TODO: GH#18217 + } + else { + return ts.createWatchCompilerHostOfConfigFile(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus); + } + } + ts.createWatchCompilerHost = createWatchCompilerHost; + var initialVersion = 1; + function createWatchProgram(host) { + var builderProgram; + var reloadLevel; // level to indicate if the program needs to be reloaded from config file/just filenames etc + var missingFilesMap; // Map of file watchers for the missing files + var watchedWildcardDirectories; // map of watchers for the wild card directories in the config file + var timerToUpdateProgram; // timer callback to recompile the program + var sourceFilesCache = ts.createMap(); // Cache that stores the source file and version info + var missingFilePathsRequestedForRelease; // These paths are held temparirly so that we can remove the entry from source file cache if the file is not tracked by missing files + var hasChangedCompilerOptions = false; // True if the compiler options have changed between compilations + var hasChangedAutomaticTypeDirectiveNames = false; // True if the automatic type directives have changed + var useCaseSensitiveFileNames = host.useCaseSensitiveFileNames(); + var currentDirectory = host.getCurrentDirectory(); + var getCurrentDirectory = function () { return currentDirectory; }; + var readFile = function (path, encoding) { return host.readFile(path, encoding); }; + var configFileName = host.configFileName, _a = host.optionsToExtend, optionsToExtendForConfigFile = _a === void 0 ? {} : _a, createProgram = host.createProgram; + var rootFileNames = host.rootFiles, compilerOptions = host.options, projectReferences = host.projectReferences; + var configFileSpecs; + var configFileParsingDiagnostics; + var canConfigFileJsonReportNoInputFiles = false; + var hasChangedConfigFileParsingErrors = false; + var cachedDirectoryStructureHost = configFileName === undefined ? undefined : ts.createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensitiveFileNames); + if (cachedDirectoryStructureHost && host.onCachedDirectoryStructureHostCreate) { + host.onCachedDirectoryStructureHostCreate(cachedDirectoryStructureHost); + } + var directoryStructureHost = cachedDirectoryStructureHost || host; + var parseConfigFileHost = { + useCaseSensitiveFileNames: useCaseSensitiveFileNames, + readDirectory: function (path, extensions, exclude, include, depth) { return directoryStructureHost.readDirectory(path, extensions, exclude, include, depth); }, + fileExists: function (path) { return host.fileExists(path); }, + readFile: readFile, + getCurrentDirectory: getCurrentDirectory, + onUnRecoverableConfigFileDiagnostic: host.onUnRecoverableConfigFileDiagnostic, + trace: host.trace ? function (s) { return host.trace(s); } : undefined + }; + // From tsc we want to get already parsed result and hence check for rootFileNames + var newLine = updateNewLine(); + if (configFileName && host.configFileParsingResult) { + setConfigFileParsingResult(host.configFileParsingResult); + newLine = updateNewLine(); + } + reportWatchDiagnostic(ts.Diagnostics.Starting_compilation_in_watch_mode); + if (configFileName && !host.configFileParsingResult) { + newLine = ts.getNewLineCharacter(optionsToExtendForConfigFile, function () { return host.getNewLine(); }); + ts.Debug.assert(!rootFileNames); + parseConfigFile(); + newLine = updateNewLine(); + } + var trace = host.trace && (function (s) { host.trace(s + newLine); }); + var watchLogLevel = trace ? compilerOptions.extendedDiagnostics ? ts.WatchLogLevel.Verbose : + compilerOptions.diagnostics ? ts.WatchLogLevel.TriggerOnly : ts.WatchLogLevel.None : ts.WatchLogLevel.None; + var writeLog = watchLogLevel !== ts.WatchLogLevel.None ? trace : ts.noop; // TODO: GH#18217 + var _b = ts.getWatchFactory(watchLogLevel, writeLog), watchFile = _b.watchFile, watchFilePath = _b.watchFilePath, watchDirectory = _b.watchDirectory; + var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); + writeLog("Current directory: " + currentDirectory + " CaseSensitiveFileNames: " + useCaseSensitiveFileNames); + if (configFileName) { + watchFile(host, configFileName, scheduleProgramReload, ts.PollingInterval.High, "Config file"); + } + var compilerHost = { + // Members for CompilerHost + getSourceFile: function (fileName, languageVersion, onError, shouldCreateNewSourceFile) { return getVersionedSourceFileByPath(fileName, toPath(fileName), languageVersion, onError, shouldCreateNewSourceFile); }, + getSourceFileByPath: getVersionedSourceFileByPath, + getDefaultLibLocation: host.getDefaultLibLocation && (function () { return host.getDefaultLibLocation(); }), + getDefaultLibFileName: function (options) { return host.getDefaultLibFileName(options); }, + writeFile: writeFile, + getCurrentDirectory: getCurrentDirectory, + useCaseSensitiveFileNames: function () { return useCaseSensitiveFileNames; }, + getCanonicalFileName: getCanonicalFileName, + getNewLine: function () { return newLine; }, + fileExists: fileExists, + readFile: readFile, + trace: trace, + directoryExists: directoryStructureHost.directoryExists && (function (path) { return directoryStructureHost.directoryExists(path); }), + getDirectories: (directoryStructureHost.getDirectories && (function (path) { return directoryStructureHost.getDirectories(path); })), + realpath: host.realpath && (function (s) { return host.realpath(s); }), + getEnvironmentVariable: host.getEnvironmentVariable ? (function (name) { return host.getEnvironmentVariable(name); }) : (function () { return ""; }), + onReleaseOldSourceFile: onReleaseOldSourceFile, + createHash: host.createHash && (function (data) { return host.createHash(data); }), + // Members for ResolutionCacheHost + toPath: toPath, + getCompilationSettings: function () { return compilerOptions; }, + watchDirectoryOfFailedLookupLocation: function (dir, cb, flags) { return watchDirectory(host, dir, cb, flags, "Failed Lookup Locations"); }, + watchTypeRootsDirectory: function (dir, cb, flags) { return watchDirectory(host, dir, cb, flags, "Type roots"); }, + getCachedDirectoryStructureHost: function () { return cachedDirectoryStructureHost; }, + onInvalidatedResolution: scheduleProgramUpdate, + onChangedAutomaticTypeDirectiveNames: function () { + hasChangedAutomaticTypeDirectiveNames = true; + scheduleProgramUpdate(); + }, + maxNumberOfFilesToIterateForInvalidation: host.maxNumberOfFilesToIterateForInvalidation, + getCurrentProgram: getCurrentProgram, + writeLog: writeLog, + readDirectory: function (path, extensions, exclude, include, depth) { return directoryStructureHost.readDirectory(path, extensions, exclude, include, depth); }, + }; + // Cache for the module resolution + var resolutionCache = ts.createResolutionCache(compilerHost, configFileName ? + ts.getDirectoryPath(ts.getNormalizedAbsolutePath(configFileName, currentDirectory)) : + currentDirectory, + /*logChangesWhenResolvingModule*/ false); + // Resolve module using host module resolution strategy if provided otherwise use resolution cache to resolve module names + compilerHost.resolveModuleNames = host.resolveModuleNames ? + (function (moduleNames, containingFile, reusedNames, redirectedReference) { return host.resolveModuleNames(moduleNames, containingFile, reusedNames, redirectedReference); }) : + (function (moduleNames, containingFile, reusedNames, redirectedReference) { return resolutionCache.resolveModuleNames(moduleNames, containingFile, reusedNames, redirectedReference); }); + compilerHost.resolveTypeReferenceDirectives = host.resolveTypeReferenceDirectives ? + (function (typeDirectiveNames, containingFile, redirectedReference) { return host.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile, redirectedReference); }) : + (function (typeDirectiveNames, containingFile, redirectedReference) { return resolutionCache.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile, redirectedReference); }); + var userProvidedResolution = !!host.resolveModuleNames || !!host.resolveTypeReferenceDirectives; + synchronizeProgram(); + // Update the wild card directory watch + watchConfigFileWildCardDirectories(); + return configFileName ? + { getCurrentProgram: getCurrentBuilderProgram, getProgram: synchronizeProgram } : + { getCurrentProgram: getCurrentBuilderProgram, getProgram: synchronizeProgram, updateRootFileNames: updateRootFileNames }; + function getCurrentBuilderProgram() { + return builderProgram; + } + function getCurrentProgram() { + return builderProgram && builderProgram.getProgram(); + } + function synchronizeProgram() { + writeLog("Synchronizing program"); + var program = getCurrentProgram(); + if (hasChangedCompilerOptions) { + newLine = updateNewLine(); + if (program && ts.changesAffectModuleResolution(program.getCompilerOptions(), compilerOptions)) { + resolutionCache.clear(); + } + } + // All resolutions are invalid if user provided resolutions + var hasInvalidatedResolution = resolutionCache.createHasInvalidatedResolution(userProvidedResolution); + if (ts.isProgramUptoDate(getCurrentProgram(), rootFileNames, compilerOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, projectReferences)) { + if (hasChangedConfigFileParsingErrors) { + builderProgram = createProgram(/*rootNames*/ undefined, /*options*/ undefined, compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences); + hasChangedConfigFileParsingErrors = false; + } + } + else { + createNewProgram(program, hasInvalidatedResolution); + } + if (host.afterProgramCreate) { + host.afterProgramCreate(builderProgram); + } + return builderProgram; + } + function createNewProgram(program, hasInvalidatedResolution) { + // Compile the program + if (watchLogLevel !== ts.WatchLogLevel.None) { + writeLog("CreatingProgramWith::"); + writeLog(" roots: " + JSON.stringify(rootFileNames)); + writeLog(" options: " + JSON.stringify(compilerOptions)); + } + var needsUpdateInTypeRootWatch = hasChangedCompilerOptions || !program; + hasChangedCompilerOptions = false; + hasChangedConfigFileParsingErrors = false; + resolutionCache.startCachingPerDirectoryResolution(); + compilerHost.hasInvalidatedResolution = hasInvalidatedResolution; + compilerHost.hasChangedAutomaticTypeDirectiveNames = hasChangedAutomaticTypeDirectiveNames; + builderProgram = createProgram(rootFileNames, compilerOptions, compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences); + resolutionCache.finishCachingPerDirectoryResolution(); + // Update watches + ts.updateMissingFilePathsWatch(builderProgram.getProgram(), missingFilesMap || (missingFilesMap = ts.createMap()), watchMissingFilePath); + if (needsUpdateInTypeRootWatch) { + resolutionCache.updateTypeRootsWatch(); + } + if (missingFilePathsRequestedForRelease) { + // These are the paths that program creater told us as not in use any more but were missing on the disk. + // We didnt remove the entry for them from sourceFiles cache so that we dont have to do File IO, + // if there is already watcher for it (for missing files) + // At this point our watches were updated, hence now we know that these paths are not tracked and need to be removed + // so that at later time we have correct result of their presence + for (var _i = 0, missingFilePathsRequestedForRelease_1 = missingFilePathsRequestedForRelease; _i < missingFilePathsRequestedForRelease_1.length; _i++) { + var missingFilePath = missingFilePathsRequestedForRelease_1[_i]; + if (!missingFilesMap.has(missingFilePath)) { + sourceFilesCache.delete(missingFilePath); + } + } + missingFilePathsRequestedForRelease = undefined; + } + } + function updateRootFileNames(files) { + ts.Debug.assert(!configFileName, "Cannot update root file names with config file watch mode"); + rootFileNames = files; + scheduleProgramUpdate(); + } + function updateNewLine() { + return ts.getNewLineCharacter(compilerOptions || optionsToExtendForConfigFile, function () { return host.getNewLine(); }); + } + function toPath(fileName) { + return ts.toPath(fileName, currentDirectory, getCanonicalFileName); + } + function isFileMissingOnHost(hostSourceFile) { + return typeof hostSourceFile === "number"; + } + function isFilePresentOnHost(hostSourceFile) { + return !!hostSourceFile.sourceFile; + } + function fileExists(fileName) { + var path = toPath(fileName); + // If file is missing on host from cache, we can definitely say file doesnt exist + // otherwise we need to ensure from the disk + if (isFileMissingOnHost(sourceFilesCache.get(path))) { + return true; + } + return directoryStructureHost.fileExists(fileName); + } + function getVersionedSourceFileByPath(fileName, path, languageVersion, onError, shouldCreateNewSourceFile) { + var hostSourceFile = sourceFilesCache.get(path); + // No source file on the host + if (isFileMissingOnHost(hostSourceFile)) { + return undefined; + } + // Create new source file if requested or the versions dont match + if (!hostSourceFile || shouldCreateNewSourceFile || !isFilePresentOnHost(hostSourceFile) || hostSourceFile.version.toString() !== hostSourceFile.sourceFile.version) { + var sourceFile = getNewSourceFile(); + if (hostSourceFile) { + if (shouldCreateNewSourceFile) { + hostSourceFile.version++; + } + if (sourceFile) { + // Set the source file and create file watcher now that file was present on the disk + hostSourceFile.sourceFile = sourceFile; + sourceFile.version = hostSourceFile.version.toString(); + if (!hostSourceFile.fileWatcher) { + hostSourceFile.fileWatcher = watchFilePath(host, fileName, onSourceFileChange, ts.PollingInterval.Low, path, "Source file"); + } + } + else { + // There is no source file on host any more, close the watch, missing file paths will track it + if (isFilePresentOnHost(hostSourceFile)) { + hostSourceFile.fileWatcher.close(); + } + sourceFilesCache.set(path, hostSourceFile.version); + } + } + else { + if (sourceFile) { + sourceFile.version = initialVersion.toString(); + var fileWatcher = watchFilePath(host, fileName, onSourceFileChange, ts.PollingInterval.Low, path, "Source file"); + sourceFilesCache.set(path, { sourceFile: sourceFile, version: initialVersion, fileWatcher: fileWatcher }); + } + else { + sourceFilesCache.set(path, initialVersion); + } + } + return sourceFile; + } + return hostSourceFile.sourceFile; + function getNewSourceFile() { + var text; + try { + ts.performance.mark("beforeIORead"); + text = host.readFile(fileName, compilerOptions.charset); + ts.performance.mark("afterIORead"); + ts.performance.measure("I/O Read", "beforeIORead", "afterIORead"); + } + catch (e) { + if (onError) { + onError(e.message); + } + } + return text !== undefined ? ts.createSourceFile(fileName, text, languageVersion) : undefined; + } + } + function nextSourceFileVersion(path) { + var hostSourceFile = sourceFilesCache.get(path); + if (hostSourceFile !== undefined) { + if (isFileMissingOnHost(hostSourceFile)) { + // The next version, lets set it as presence unknown file + sourceFilesCache.set(path, { version: Number(hostSourceFile) + 1 }); + } + else { + hostSourceFile.version++; + } + } + } + function getSourceVersion(path) { + var hostSourceFile = sourceFilesCache.get(path); + return !hostSourceFile || isFileMissingOnHost(hostSourceFile) ? undefined : hostSourceFile.version.toString(); + } + function onReleaseOldSourceFile(oldSourceFile, _oldOptions, hasSourceFileByPath) { + var hostSourceFileInfo = sourceFilesCache.get(oldSourceFile.resolvedPath); + // If this is the source file thats in the cache and new program doesnt need it, + // remove the cached entry. + // Note we arent deleting entry if file became missing in new program or + // there was version update and new source file was created. + if (hostSourceFileInfo) { + // record the missing file paths so they can be removed later if watchers arent tracking them + if (isFileMissingOnHost(hostSourceFileInfo)) { + (missingFilePathsRequestedForRelease || (missingFilePathsRequestedForRelease = [])).push(oldSourceFile.path); + } + else if (hostSourceFileInfo.sourceFile === oldSourceFile) { + if (hostSourceFileInfo.fileWatcher) { + hostSourceFileInfo.fileWatcher.close(); + } + sourceFilesCache.delete(oldSourceFile.resolvedPath); + if (!hasSourceFileByPath) { + resolutionCache.removeResolutionsOfFile(oldSourceFile.path); + } + } + } + } + function reportWatchDiagnostic(message) { + if (host.onWatchStatusChange) { + host.onWatchStatusChange(ts.createCompilerDiagnostic(message), newLine, compilerOptions || optionsToExtendForConfigFile); + } + } + // Upon detecting a file change, wait for 250ms and then perform a recompilation. This gives batch + // operations (such as saving all modified files in an editor) a chance to complete before we kick + // off a new compilation. + function scheduleProgramUpdate() { + if (!host.setTimeout || !host.clearTimeout) { + return; + } + if (timerToUpdateProgram) { + host.clearTimeout(timerToUpdateProgram); + } + writeLog("Scheduling update"); + timerToUpdateProgram = host.setTimeout(updateProgram, 250); + } + function scheduleProgramReload() { + ts.Debug.assert(!!configFileName); + reloadLevel = ts.ConfigFileProgramReloadLevel.Full; + scheduleProgramUpdate(); + } + function updateProgram() { + timerToUpdateProgram = undefined; + reportWatchDiagnostic(ts.Diagnostics.File_change_detected_Starting_incremental_compilation); + switch (reloadLevel) { + case ts.ConfigFileProgramReloadLevel.Partial: + return reloadFileNamesFromConfigFile(); + case ts.ConfigFileProgramReloadLevel.Full: + return reloadConfigFile(); + default: + synchronizeProgram(); + return; + } + } + function reloadFileNamesFromConfigFile() { + writeLog("Reloading new file names and options"); + var result = ts.getFileNamesFromConfigSpecs(configFileSpecs, ts.getDirectoryPath(configFileName), compilerOptions, parseConfigFileHost); + if (ts.updateErrorForNoInputFiles(result, configFileName, configFileSpecs, configFileParsingDiagnostics, canConfigFileJsonReportNoInputFiles)) { + hasChangedConfigFileParsingErrors = true; + } + rootFileNames = result.fileNames; + // Update the program + synchronizeProgram(); + } + function reloadConfigFile() { + writeLog("Reloading config file: " + configFileName); + reloadLevel = ts.ConfigFileProgramReloadLevel.None; + if (cachedDirectoryStructureHost) { + cachedDirectoryStructureHost.clearCache(); + } + parseConfigFile(); + hasChangedCompilerOptions = true; + synchronizeProgram(); + // Update the wild card directory watch + watchConfigFileWildCardDirectories(); + } + function parseConfigFile() { + setConfigFileParsingResult(ts.getParsedCommandLineOfConfigFile(configFileName, optionsToExtendForConfigFile, parseConfigFileHost)); // TODO: GH#18217 + } + function setConfigFileParsingResult(configFileParseResult) { + rootFileNames = configFileParseResult.fileNames; + compilerOptions = configFileParseResult.options; + configFileSpecs = configFileParseResult.configFileSpecs; // TODO: GH#18217 + projectReferences = configFileParseResult.projectReferences; + configFileParsingDiagnostics = ts.getConfigFileParsingDiagnostics(configFileParseResult).slice(); + canConfigFileJsonReportNoInputFiles = ts.canJsonReportNoInutFiles(configFileParseResult.raw); + hasChangedConfigFileParsingErrors = true; + } + function onSourceFileChange(fileName, eventKind, path) { + updateCachedSystemWithFile(fileName, path, eventKind); + // Update the source file cache + if (eventKind === ts.FileWatcherEventKind.Deleted && sourceFilesCache.get(path)) { + resolutionCache.invalidateResolutionOfFile(path); + } + resolutionCache.removeResolutionsFromProjectReferenceRedirects(path); + nextSourceFileVersion(path); + // Update the program + scheduleProgramUpdate(); + } + function updateCachedSystemWithFile(fileName, path, eventKind) { + if (cachedDirectoryStructureHost) { + cachedDirectoryStructureHost.addOrDeleteFile(fileName, path, eventKind); + } + } + function watchMissingFilePath(missingFilePath) { + return watchFilePath(host, missingFilePath, onMissingFileChange, ts.PollingInterval.Medium, missingFilePath, "Missing file"); + } + function onMissingFileChange(fileName, eventKind, missingFilePath) { + updateCachedSystemWithFile(fileName, missingFilePath, eventKind); + if (eventKind === ts.FileWatcherEventKind.Created && missingFilesMap.has(missingFilePath)) { + missingFilesMap.get(missingFilePath).close(); + missingFilesMap.delete(missingFilePath); + // Delete the entry in the source files cache so that new source file is created + nextSourceFileVersion(missingFilePath); + // When a missing file is created, we should update the graph. + scheduleProgramUpdate(); + } + } + function watchConfigFileWildCardDirectories() { + if (configFileSpecs) { + ts.updateWatchingWildcardDirectories(watchedWildcardDirectories || (watchedWildcardDirectories = ts.createMap()), ts.createMapFromTemplate(configFileSpecs.wildcardDirectories), watchWildcardDirectory); + } + else if (watchedWildcardDirectories) { + ts.clearMap(watchedWildcardDirectories, ts.closeFileWatcherOf); + } + } + function watchWildcardDirectory(directory, flags) { + return watchDirectory(host, directory, function (fileOrDirectory) { + ts.Debug.assert(!!configFileName); + var fileOrDirectoryPath = toPath(fileOrDirectory); + // Since the file existance changed, update the sourceFiles cache + if (cachedDirectoryStructureHost) { + cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); + } + nextSourceFileVersion(fileOrDirectoryPath); + if (ts.isPathInNodeModulesStartingWithDot(fileOrDirectoryPath)) + return; + // If the the added or created file or directory is not supported file name, ignore the file + // But when watched directory is added/removed, we need to reload the file list + if (fileOrDirectoryPath !== directory && ts.hasExtension(fileOrDirectoryPath) && !ts.isSupportedSourceFileName(fileOrDirectory, compilerOptions)) { + writeLog("Project: " + configFileName + " Detected file add/remove of non supported extension: " + fileOrDirectory); + return; + } + // Reload is pending, do the reload + if (reloadLevel !== ts.ConfigFileProgramReloadLevel.Full) { + reloadLevel = ts.ConfigFileProgramReloadLevel.Partial; + // Schedule Update the program + scheduleProgramUpdate(); + } + }, flags, "Wild card directories"); + } + function ensureDirectoriesExist(directoryPath) { + if (directoryPath.length > ts.getRootLength(directoryPath) && !host.directoryExists(directoryPath)) { + var parentDirectory = ts.getDirectoryPath(directoryPath); + ensureDirectoriesExist(parentDirectory); + host.createDirectory(directoryPath); + } + } + function writeFile(fileName, text, writeByteOrderMark, onError) { + try { + ts.performance.mark("beforeIOWrite"); + ensureDirectoriesExist(ts.getDirectoryPath(ts.normalizePath(fileName))); + host.writeFile(fileName, text, writeByteOrderMark); + ts.performance.mark("afterIOWrite"); + ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite"); + } + catch (e) { + if (onError) { + onError(e.message); + } + } + } + } + ts.createWatchProgram = createWatchProgram; +})(ts || (ts = {})); +// Currently we do not want to expose API for build, we should work out the API, and then expose it just like we did for builder/watch +/*@internal*/ +var ts; +(function (ts) { + var minimumDate = new Date(-8640000000000000); + var maximumDate = new Date(8640000000000000); + var BuildResultFlags; + (function (BuildResultFlags) { + BuildResultFlags[BuildResultFlags["None"] = 0] = "None"; + /** + * No errors of any kind occurred during build + */ + BuildResultFlags[BuildResultFlags["Success"] = 1] = "Success"; + /** + * None of the .d.ts files emitted by this build were + * different from the existing files on disk + */ + BuildResultFlags[BuildResultFlags["DeclarationOutputUnchanged"] = 2] = "DeclarationOutputUnchanged"; + BuildResultFlags[BuildResultFlags["ConfigFileErrors"] = 4] = "ConfigFileErrors"; + BuildResultFlags[BuildResultFlags["SyntaxErrors"] = 8] = "SyntaxErrors"; + BuildResultFlags[BuildResultFlags["TypeErrors"] = 16] = "TypeErrors"; + BuildResultFlags[BuildResultFlags["DeclarationEmitErrors"] = 32] = "DeclarationEmitErrors"; + BuildResultFlags[BuildResultFlags["EmitErrors"] = 64] = "EmitErrors"; + BuildResultFlags[BuildResultFlags["AnyErrors"] = 124] = "AnyErrors"; + })(BuildResultFlags || (BuildResultFlags = {})); + var UpToDateStatusType; + (function (UpToDateStatusType) { + UpToDateStatusType[UpToDateStatusType["Unbuildable"] = 0] = "Unbuildable"; + UpToDateStatusType[UpToDateStatusType["UpToDate"] = 1] = "UpToDate"; + /** + * The project appears out of date because its upstream inputs are newer than its outputs, + * but all of its outputs are actually newer than the previous identical outputs of its (.d.ts) inputs. + * This means we can Pseudo-build (just touch timestamps), as if we had actually built this project. + */ + UpToDateStatusType[UpToDateStatusType["UpToDateWithUpstreamTypes"] = 2] = "UpToDateWithUpstreamTypes"; + UpToDateStatusType[UpToDateStatusType["OutputMissing"] = 3] = "OutputMissing"; + UpToDateStatusType[UpToDateStatusType["OutOfDateWithSelf"] = 4] = "OutOfDateWithSelf"; + UpToDateStatusType[UpToDateStatusType["OutOfDateWithUpstream"] = 5] = "OutOfDateWithUpstream"; + UpToDateStatusType[UpToDateStatusType["UpstreamOutOfDate"] = 6] = "UpstreamOutOfDate"; + UpToDateStatusType[UpToDateStatusType["UpstreamBlocked"] = 7] = "UpstreamBlocked"; + UpToDateStatusType[UpToDateStatusType["ComputingUpstream"] = 8] = "ComputingUpstream"; + /** + * Projects with no outputs (i.e. "solution" files) + */ + UpToDateStatusType[UpToDateStatusType["ContainerOnly"] = 9] = "ContainerOnly"; + })(UpToDateStatusType = ts.UpToDateStatusType || (ts.UpToDateStatusType = {})); + function createFileMap(toPath) { + // tslint:disable-next-line:no-null-keyword + var lookup = ts.createMap(); + return { + setValue: setValue, + getValue: getValue, + removeKey: removeKey, + forEach: forEach, + hasKey: hasKey, + getSize: getSize, + clear: clear + }; + function forEach(action) { + lookup.forEach(action); + } + function hasKey(fileName) { + return lookup.has(toPath(fileName)); + } + function removeKey(fileName) { + lookup.delete(toPath(fileName)); + } + function setValue(fileName, value) { + lookup.set(toPath(fileName), value); + } + function getValue(fileName) { + return lookup.get(toPath(fileName)); + } + function getSize() { + return lookup.size; + } + function clear() { + lookup.clear(); + } + } + function getOrCreateValueFromConfigFileMap(configFileMap, resolved, createT) { + var existingValue = configFileMap.getValue(resolved); + var newValue; + if (!existingValue) { + newValue = createT(); + configFileMap.setValue(resolved, newValue); + } + return existingValue || newValue; + } + function getOrCreateValueMapFromConfigFileMap(configFileMap, resolved) { + return getOrCreateValueFromConfigFileMap(configFileMap, resolved, ts.createMap); + } + function getOutputDeclarationFileName(inputFileName, configFile) { + var relativePath = ts.getRelativePathFromDirectory(rootDirOfOptions(configFile.options, configFile.options.configFilePath), inputFileName, /*ignoreCase*/ true); + var outputPath = ts.resolvePath(configFile.options.declarationDir || configFile.options.outDir || ts.getDirectoryPath(configFile.options.configFilePath), relativePath); + return ts.changeExtension(outputPath, ".d.ts" /* Dts */); + } + ts.getOutputDeclarationFileName = getOutputDeclarationFileName; + function getOutputJSFileName(inputFileName, configFile) { + var relativePath = ts.getRelativePathFromDirectory(rootDirOfOptions(configFile.options, configFile.options.configFilePath), inputFileName, /*ignoreCase*/ true); + var outputPath = ts.resolvePath(configFile.options.outDir || ts.getDirectoryPath(configFile.options.configFilePath), relativePath); + var newExtension = ts.fileExtensionIs(inputFileName, ".json" /* Json */) ? ".json" /* Json */ : + ts.fileExtensionIs(inputFileName, ".tsx" /* Tsx */) && configFile.options.jsx === 1 /* Preserve */ ? ".jsx" /* Jsx */ : ".js" /* Js */; + return ts.changeExtension(outputPath, newExtension); + } + function getOutputFileNames(inputFileName, configFile) { + // outFile is handled elsewhere; .d.ts files don't generate outputs + if (configFile.options.outFile || configFile.options.out || ts.fileExtensionIs(inputFileName, ".d.ts" /* Dts */)) { + return ts.emptyArray; + } + var outputs = []; + var js = getOutputJSFileName(inputFileName, configFile); + outputs.push(js); + if (configFile.options.sourceMap) { + outputs.push(js + ".map"); + } + if (ts.getEmitDeclarations(configFile.options) && !ts.fileExtensionIs(inputFileName, ".json" /* Json */)) { + var dts = getOutputDeclarationFileName(inputFileName, configFile); + outputs.push(dts); + if (configFile.options.declarationMap) { + outputs.push(dts + ".map"); + } + } + return outputs; + } + function getOutFileOutputs(project) { + var out = project.options.outFile || project.options.out; + if (!out) { + return ts.Debug.fail("outFile must be set"); + } + var outputs = []; + outputs.push(out); + if (project.options.sourceMap) { + outputs.push(out + ".map"); + } + if (ts.getEmitDeclarations(project.options)) { + var dts = ts.changeExtension(out, ".d.ts" /* Dts */); + outputs.push(dts); + if (project.options.declarationMap) { + outputs.push(dts + ".map"); + } + } + return outputs; + } + function rootDirOfOptions(opts, configFileName) { + return opts.rootDir || ts.getDirectoryPath(configFileName); + } + function newer(date1, date2) { + return date2 > date1 ? date2 : date1; + } + function isDeclarationFile(fileName) { + return ts.fileExtensionIs(fileName, ".d.ts" /* Dts */); + } + /** + * Create a function that reports watch status by writing to the system and handles the formating of the diagnostic + */ + function createBuilderStatusReporter(system, pretty) { + return function (diagnostic) { + var output = pretty ? "[" + ts.formatColorAndReset(new Date().toLocaleTimeString(), ts.ForegroundColorEscapeSequences.Grey) + "] " : new Date().toLocaleTimeString() + " - "; + output += "" + ts.flattenDiagnosticMessageText(diagnostic.messageText, system.newLine) + (system.newLine + system.newLine); + system.write(output); + }; + } + ts.createBuilderStatusReporter = createBuilderStatusReporter; + function createSolutionBuilderHostBase(system, reportDiagnostic, reportSolutionBuilderStatus) { + if (system === void 0) { system = ts.sys; } + var host = ts.createCompilerHostWorker({}, /*setParentNodes*/ undefined, system); + host.getModifiedTime = system.getModifiedTime ? function (path) { return system.getModifiedTime(path); } : function () { return undefined; }; + host.setModifiedTime = system.setModifiedTime ? function (path, date) { return system.setModifiedTime(path, date); } : ts.noop; + host.deleteFile = system.deleteFile ? function (path) { return system.deleteFile(path); } : ts.noop; + host.reportDiagnostic = reportDiagnostic || ts.createDiagnosticReporter(system); + host.reportSolutionBuilderStatus = reportSolutionBuilderStatus || createBuilderStatusReporter(system); + return host; + } + function createSolutionBuilderHost(system, reportDiagnostic, reportSolutionBuilderStatus, reportErrorSummary) { + if (system === void 0) { system = ts.sys; } + var host = createSolutionBuilderHostBase(system, reportDiagnostic, reportSolutionBuilderStatus); + host.reportErrorSummary = reportErrorSummary; + return host; + } + ts.createSolutionBuilderHost = createSolutionBuilderHost; + function createSolutionBuilderWithWatchHost(system, reportDiagnostic, reportSolutionBuilderStatus, reportWatchStatus) { + var host = createSolutionBuilderHostBase(system, reportDiagnostic, reportSolutionBuilderStatus); + var watchHost = ts.createWatchHost(system, reportWatchStatus); + host.onWatchStatusChange = watchHost.onWatchStatusChange; + host.watchFile = watchHost.watchFile; + host.watchDirectory = watchHost.watchDirectory; + host.setTimeout = watchHost.setTimeout; + host.clearTimeout = watchHost.clearTimeout; + return host; + } + ts.createSolutionBuilderWithWatchHost = createSolutionBuilderWithWatchHost; + function getCompilerOptionsOfBuildOptions(buildOptions) { + var result = {}; + ts.commonOptionsWithBuild.forEach(function (option) { + result[option.name] = buildOptions[option.name]; + }); + return result; + } + function createSolutionBuilder(host, rootNames, defaultOptions) { + var hostWithWatch = host; + var currentDirectory = host.getCurrentDirectory(); + var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames()); + var parseConfigFileHost = ts.parseConfigHostFromCompilerHost(host); + // State of the solution + var options = defaultOptions; + var baseCompilerOptions = getCompilerOptionsOfBuildOptions(options); + var configFileCache = createFileMap(toPath); + /** Map from output file name to its pre-build timestamp */ + var unchangedOutputs = createFileMap(toPath); + /** Map from config file name to up-to-date status */ + var projectStatus = createFileMap(toPath); + var missingRoots = ts.createMap(); + var globalDependencyGraph; + var writeFileName = function (s) { return host.trace && host.trace(s); }; + var readFileWithCache = function (f) { return host.readFile(f); }; + // Watch state + var diagnostics = createFileMap(toPath); + var projectPendingBuild = createFileMap(toPath); + var projectErrorsReported = createFileMap(toPath); + var invalidatedProjectQueue = []; + var nextProjectToBuild = 0; + var timerToBuildInvalidatedProject; + var reportFileChangeDetected = false; + // Watches for the solution + var allWatchedWildcardDirectories = createFileMap(toPath); + var allWatchedInputFiles = createFileMap(toPath); + var allWatchedConfigFiles = createFileMap(toPath); + return { + buildAllProjects: buildAllProjects, + getUpToDateStatusOfFile: getUpToDateStatusOfFile, + cleanAllProjects: cleanAllProjects, + resetBuildContext: resetBuildContext, + getBuildGraph: getBuildGraph, + invalidateProject: invalidateProject, + buildInvalidatedProject: buildInvalidatedProject, + resolveProjectName: resolveProjectName, + startWatching: startWatching + }; + function toPath(fileName) { + return ts.toPath(fileName, currentDirectory, getCanonicalFileName); + } + function resetBuildContext(opts) { + if (opts === void 0) { opts = defaultOptions; } + options = opts; + baseCompilerOptions = getCompilerOptionsOfBuildOptions(options); + configFileCache.clear(); + unchangedOutputs.clear(); + projectStatus.clear(); + missingRoots.clear(); + globalDependencyGraph = undefined; + diagnostics.clear(); + projectPendingBuild.clear(); + projectErrorsReported.clear(); + invalidatedProjectQueue.length = 0; + nextProjectToBuild = 0; + if (timerToBuildInvalidatedProject) { + clearTimeout(timerToBuildInvalidatedProject); + timerToBuildInvalidatedProject = undefined; + } + reportFileChangeDetected = false; + ts.clearMap(allWatchedWildcardDirectories, function (wildCardWatches) { return ts.clearMap(wildCardWatches, ts.closeFileWatcherOf); }); + ts.clearMap(allWatchedInputFiles, function (inputFileWatches) { return ts.clearMap(inputFileWatches, ts.closeFileWatcher); }); + ts.clearMap(allWatchedConfigFiles, ts.closeFileWatcher); + } + function isParsedCommandLine(entry) { + return !!entry.options; + } + function parseConfigFile(configFilePath) { + var value = configFileCache.getValue(configFilePath); + if (value) { + return isParsedCommandLine(value) ? value : undefined; + } + var diagnostic; + parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = function (d) { return diagnostic = d; }; + var parsed = ts.getParsedCommandLineOfConfigFile(configFilePath, baseCompilerOptions, parseConfigFileHost); + parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = ts.noop; + configFileCache.setValue(configFilePath, parsed || diagnostic); + return parsed; + } + function reportStatus(message) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + host.reportSolutionBuilderStatus(ts.createCompilerDiagnostic.apply(void 0, [message].concat(args))); + } + function reportWatchStatus(message) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + if (hostWithWatch.onWatchStatusChange) { + hostWithWatch.onWatchStatusChange(ts.createCompilerDiagnostic.apply(void 0, [message].concat(args)), host.getNewLine(), baseCompilerOptions); + } + } + function startWatching() { + var graph = getGlobalDependencyGraph(); + for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { + var resolved = _a[_i]; + // Watch this file + watchConfigFile(resolved); + var cfg = parseConfigFile(resolved); + if (cfg) { + // Update watchers for wildcard directories + watchWildCardDirectories(resolved, cfg); + // Watch input files + watchInputFiles(resolved, cfg); + } + } + } + function watchConfigFile(resolved) { + if (options.watch && !allWatchedConfigFiles.hasKey(resolved)) { + allWatchedConfigFiles.setValue(resolved, hostWithWatch.watchFile(resolved, function () { + invalidateProjectAndScheduleBuilds(resolved, ts.ConfigFileProgramReloadLevel.Full); + })); + } + } + function watchWildCardDirectories(resolved, parsed) { + if (!options.watch) + return; + ts.updateWatchingWildcardDirectories(getOrCreateValueMapFromConfigFileMap(allWatchedWildcardDirectories, resolved), ts.createMapFromTemplate(parsed.configFileSpecs.wildcardDirectories), function (dir, flags) { + return hostWithWatch.watchDirectory(dir, function (fileOrDirectory) { + var fileOrDirectoryPath = toPath(fileOrDirectory); + if (fileOrDirectoryPath !== toPath(dir) && ts.hasExtension(fileOrDirectoryPath) && !ts.isSupportedSourceFileName(fileOrDirectory, parsed.options)) { + // writeLog(`Project: ${configFileName} Detected file add/remove of non supported extension: ${fileOrDirectory}`); + return; + } + if (isOutputFile(fileOrDirectory, parsed)) { + // writeLog(`${fileOrDirectory} is output file`); + return; + } + invalidateProjectAndScheduleBuilds(resolved, ts.ConfigFileProgramReloadLevel.Partial); + }, !!(flags & 1 /* Recursive */)); + }); + } + function watchInputFiles(resolved, parsed) { + if (!options.watch) + return; + ts.mutateMap(getOrCreateValueMapFromConfigFileMap(allWatchedInputFiles, resolved), ts.arrayToMap(parsed.fileNames, toPath), { + createNewValue: function (_key, input) { return hostWithWatch.watchFile(input, function () { + invalidateProjectAndScheduleBuilds(resolved, ts.ConfigFileProgramReloadLevel.None); + }); }, + onDeleteValue: ts.closeFileWatcher, + }); + } + function isOutputFile(fileName, configFile) { + if (configFile.options.noEmit) + return false; + // ts or tsx files are not output + if (!ts.fileExtensionIs(fileName, ".d.ts" /* Dts */) && + (ts.fileExtensionIs(fileName, ".ts" /* Ts */) || ts.fileExtensionIs(fileName, ".tsx" /* Tsx */))) { + return false; + } + // If options have --outFile or --out, check if its that + var out = configFile.options.outFile || configFile.options.out; + if (out && (isSameFile(fileName, out) || isSameFile(fileName, ts.removeFileExtension(out) + ".d.ts" /* Dts */))) { + return true; + } + // If declarationDir is specified, return if its a file in that directory + if (configFile.options.declarationDir && ts.containsPath(configFile.options.declarationDir, fileName, currentDirectory, !host.useCaseSensitiveFileNames())) { + return true; + } + // If --outDir, check if file is in that directory + if (configFile.options.outDir && ts.containsPath(configFile.options.outDir, fileName, currentDirectory, !host.useCaseSensitiveFileNames())) { + return true; + } + return !ts.forEach(configFile.fileNames, function (inputFile) { return isSameFile(fileName, inputFile); }); + } + function isSameFile(file1, file2) { + return ts.comparePaths(file1, file2, currentDirectory, !host.useCaseSensitiveFileNames()) === 0 /* EqualTo */; + } + function invalidateProjectAndScheduleBuilds(resolved, reloadLevel) { + reportFileChangeDetected = true; + invalidateResolvedProject(resolved, reloadLevel); + scheduleBuildInvalidatedProject(); + } + function getUpToDateStatusOfFile(configFileName) { + return getUpToDateStatus(parseConfigFile(configFileName)); + } + function getBuildGraph(configFileNames) { + return createDependencyGraph(resolveProjectNames(configFileNames)); + } + function getGlobalDependencyGraph() { + return globalDependencyGraph || (globalDependencyGraph = getBuildGraph(rootNames)); + } + function getUpToDateStatus(project) { + if (project === undefined) { + return { type: UpToDateStatusType.Unbuildable, reason: "File deleted mid-build" }; + } + var prior = projectStatus.getValue(project.options.configFilePath); + if (prior !== undefined) { + return prior; + } + var actual = getUpToDateStatusWorker(project); + projectStatus.setValue(project.options.configFilePath, actual); + return actual; + } + function getUpToDateStatusWorker(project) { + var newestInputFileName = undefined; + var newestInputFileTime = minimumDate; + // Get timestamps of input files + for (var _i = 0, _a = project.fileNames; _i < _a.length; _i++) { + var inputFile = _a[_i]; + if (!host.fileExists(inputFile)) { + return { + type: UpToDateStatusType.Unbuildable, + reason: inputFile + " does not exist" + }; + } + var inputTime = host.getModifiedTime(inputFile) || ts.missingFileModifiedTime; + if (inputTime > newestInputFileTime) { + newestInputFileName = inputFile; + newestInputFileTime = inputTime; + } + } + // Collect the expected outputs of this project + var outputs = getAllProjectOutputs(project); + if (outputs.length === 0) { + return { + type: UpToDateStatusType.ContainerOnly + }; + } + // Now see if all outputs are newer than the newest input + var oldestOutputFileName = "(none)"; + var oldestOutputFileTime = maximumDate; + var newestOutputFileName = "(none)"; + var newestOutputFileTime = minimumDate; + var missingOutputFileName; + var newestDeclarationFileContentChangedTime = minimumDate; + var isOutOfDateWithInputs = false; + for (var _b = 0, outputs_1 = outputs; _b < outputs_1.length; _b++) { + var output = outputs_1[_b]; + // Output is missing; can stop checking + // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status + if (!host.fileExists(output)) { + missingOutputFileName = output; + break; + } + var outputTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; + if (outputTime < oldestOutputFileTime) { + oldestOutputFileTime = outputTime; + oldestOutputFileName = output; + } + // If an output is older than the newest input, we can stop checking + // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status + if (outputTime < newestInputFileTime) { + isOutOfDateWithInputs = true; + break; + } + if (outputTime > newestOutputFileTime) { + newestOutputFileTime = outputTime; + newestOutputFileName = output; + } + // Keep track of when the most recent time a .d.ts file was changed. + // In addition to file timestamps, we also keep track of when a .d.ts file + // had its file touched but not had its contents changed - this allows us + // to skip a downstream typecheck + if (isDeclarationFile(output)) { + var unchangedTime = unchangedOutputs.getValue(output); + if (unchangedTime !== undefined) { + newestDeclarationFileContentChangedTime = newer(unchangedTime, newestDeclarationFileContentChangedTime); + } + else { + var outputModifiedTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; + newestDeclarationFileContentChangedTime = newer(newestDeclarationFileContentChangedTime, outputModifiedTime); + } + } + } + var pseudoUpToDate = false; + var usesPrepend = false; + var upstreamChangedProject; + if (project.projectReferences) { + projectStatus.setValue(project.options.configFilePath, { type: UpToDateStatusType.ComputingUpstream }); + for (var _c = 0, _d = project.projectReferences; _c < _d.length; _c++) { + var ref = _d[_c]; + usesPrepend = usesPrepend || !!(ref.prepend); + var resolvedRef = ts.resolveProjectReferencePath(ref); + var refStatus = getUpToDateStatus(parseConfigFile(resolvedRef)); + // Its a circular reference ignore the status of this project + if (refStatus.type === UpToDateStatusType.ComputingUpstream) { + continue; + } + // An upstream project is blocked + if (refStatus.type === UpToDateStatusType.Unbuildable) { + return { + type: UpToDateStatusType.UpstreamBlocked, + upstreamProjectName: ref.path + }; + } + // If the upstream project is out of date, then so are we (someone shouldn't have asked, though?) + if (refStatus.type !== UpToDateStatusType.UpToDate) { + return { + type: UpToDateStatusType.UpstreamOutOfDate, + upstreamProjectName: ref.path + }; + } + // If the upstream project's newest file is older than our oldest output, we + // can't be out of date because of it + if (refStatus.newestInputFileTime && refStatus.newestInputFileTime <= oldestOutputFileTime) { + continue; + } + // If the upstream project has only change .d.ts files, and we've built + // *after* those files, then we're "psuedo up to date" and eligible for a fast rebuild + if (refStatus.newestDeclarationFileContentChangedTime && refStatus.newestDeclarationFileContentChangedTime <= oldestOutputFileTime) { + pseudoUpToDate = true; + upstreamChangedProject = ref.path; + continue; + } + // We have an output older than an upstream output - we are out of date + ts.Debug.assert(oldestOutputFileName !== undefined, "Should have an oldest output filename here"); + return { + type: UpToDateStatusType.OutOfDateWithUpstream, + outOfDateOutputFileName: oldestOutputFileName, + newerProjectName: ref.path + }; + } + } + if (missingOutputFileName !== undefined) { + return { + type: UpToDateStatusType.OutputMissing, + missingOutputFileName: missingOutputFileName + }; + } + if (isOutOfDateWithInputs) { + return { + type: UpToDateStatusType.OutOfDateWithSelf, + outOfDateOutputFileName: oldestOutputFileName, + newerInputFileName: newestInputFileName + }; + } + if (usesPrepend && pseudoUpToDate) { + return { + type: UpToDateStatusType.OutOfDateWithUpstream, + outOfDateOutputFileName: oldestOutputFileName, + newerProjectName: upstreamChangedProject + }; + } + // Up to date + return { + type: pseudoUpToDate ? UpToDateStatusType.UpToDateWithUpstreamTypes : UpToDateStatusType.UpToDate, + newestDeclarationFileContentChangedTime: newestDeclarationFileContentChangedTime, + newestInputFileTime: newestInputFileTime, + newestOutputFileTime: newestOutputFileTime, + newestInputFileName: newestInputFileName, + newestOutputFileName: newestOutputFileName, + oldestOutputFileName: oldestOutputFileName + }; + } + function invalidateProject(configFileName, reloadLevel) { + invalidateResolvedProject(resolveProjectName(configFileName), reloadLevel); + } + function invalidateResolvedProject(resolved, reloadLevel) { + if (reloadLevel === ts.ConfigFileProgramReloadLevel.Full) { + configFileCache.removeKey(resolved); + globalDependencyGraph = undefined; + } + projectStatus.removeKey(resolved); + diagnostics.removeKey(resolved); + addProjToQueue(resolved, reloadLevel); + } + /** + * return true if new addition + */ + function addProjToQueue(proj, reloadLevel) { + var value = projectPendingBuild.getValue(proj); + if (value === undefined) { + projectPendingBuild.setValue(proj, reloadLevel || ts.ConfigFileProgramReloadLevel.None); + invalidatedProjectQueue.push(proj); + } + else if (value < (reloadLevel || ts.ConfigFileProgramReloadLevel.None)) { + projectPendingBuild.setValue(proj, reloadLevel || ts.ConfigFileProgramReloadLevel.None); + } + } + function getNextInvalidatedProject() { + if (nextProjectToBuild < invalidatedProjectQueue.length) { + var project = invalidatedProjectQueue[nextProjectToBuild]; + nextProjectToBuild++; + var reloadLevel = projectPendingBuild.getValue(project); + projectPendingBuild.removeKey(project); + if (!projectPendingBuild.getSize()) { + invalidatedProjectQueue.length = 0; + nextProjectToBuild = 0; + } + return { project: project, reloadLevel: reloadLevel }; + } + } + function hasPendingInvalidatedProjects() { + return !!projectPendingBuild.getSize(); + } + function scheduleBuildInvalidatedProject() { + if (!hostWithWatch.setTimeout || !hostWithWatch.clearTimeout) { + return; + } + if (timerToBuildInvalidatedProject) { + hostWithWatch.clearTimeout(timerToBuildInvalidatedProject); + } + timerToBuildInvalidatedProject = hostWithWatch.setTimeout(buildInvalidatedProject, 250); + } + function buildInvalidatedProject() { + timerToBuildInvalidatedProject = undefined; + if (reportFileChangeDetected) { + reportFileChangeDetected = false; + projectErrorsReported.clear(); + reportWatchStatus(ts.Diagnostics.File_change_detected_Starting_incremental_compilation); + } + var buildProject = getNextInvalidatedProject(); + if (buildProject) { + buildSingleInvalidatedProject(buildProject.project, buildProject.reloadLevel); + if (hasPendingInvalidatedProjects()) { + if (options.watch && !timerToBuildInvalidatedProject) { + scheduleBuildInvalidatedProject(); + } + } + else { + reportErrorSummary(); + } + } + } + function reportErrorSummary() { + if (options.watch || host.reportErrorSummary) { + // Report errors from the other projects + getGlobalDependencyGraph().buildQueue.forEach(function (project) { + if (!projectErrorsReported.hasKey(project)) { + reportErrors(diagnostics.getValue(project) || ts.emptyArray); + } + }); + var totalErrors_1 = 0; + diagnostics.forEach(function (singleProjectErrors) { return totalErrors_1 += ts.getErrorCountForSummary(singleProjectErrors); }); + if (options.watch) { + reportWatchStatus(ts.getWatchErrorSummaryDiagnosticMessage(totalErrors_1), totalErrors_1); + } + else { + host.reportErrorSummary(totalErrors_1); + } + } + } + function buildSingleInvalidatedProject(resolved, reloadLevel) { + var proj = parseConfigFile(resolved); + if (!proj) { + reportParseConfigFileDiagnostic(resolved); + return; + } + if (reloadLevel === ts.ConfigFileProgramReloadLevel.Full) { + watchConfigFile(resolved); + watchWildCardDirectories(resolved, proj); + watchInputFiles(resolved, proj); + } + else if (reloadLevel === ts.ConfigFileProgramReloadLevel.Partial) { + // Update file names + var result = ts.getFileNamesFromConfigSpecs(proj.configFileSpecs, ts.getDirectoryPath(resolved), proj.options, parseConfigFileHost); + ts.updateErrorForNoInputFiles(result, resolved, proj.configFileSpecs, proj.errors, ts.canJsonReportNoInutFiles(proj.raw)); + proj.fileNames = result.fileNames; + watchInputFiles(resolved, proj); + } + var status = getUpToDateStatus(proj); + verboseReportProjectStatus(resolved, status); + if (status.type === UpToDateStatusType.UpstreamBlocked) { + if (options.verbose) + reportStatus(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, resolved, status.upstreamProjectName); + return; + } + var buildResult = buildSingleProject(resolved); + var dependencyGraph = getGlobalDependencyGraph(); + var referencingProjects = dependencyGraph.referencingProjectsMap.getValue(resolved); + if (!referencingProjects) + return; + // Always use build order to queue projects + for (var _i = 0, _a = dependencyGraph.buildQueue; _i < _a.length; _i++) { + var project = _a[_i]; + var prepend = referencingProjects.getValue(project); + // If the project is referenced with prepend, always build downstream projectm, + // otherwise queue it only if declaration output changed + if (prepend || (prepend !== undefined && !(buildResult & BuildResultFlags.DeclarationOutputUnchanged))) { + addProjToQueue(project); + } + } + } + function createDependencyGraph(roots) { + var temporaryMarks = createFileMap(toPath); + var permanentMarks = createFileMap(toPath); + var circularityReportStack = []; + var buildOrder = []; + var referencingProjectsMap = createFileMap(toPath); + for (var _i = 0, roots_1 = roots; _i < roots_1.length; _i++) { + var root = roots_1[_i]; + visit(root); + } + return { + buildQueue: buildOrder, + referencingProjectsMap: referencingProjectsMap + }; + function visit(projPath, inCircularContext) { + // Already visited + if (permanentMarks.hasKey(projPath)) + return; + // Circular + if (temporaryMarks.hasKey(projPath)) { + if (!inCircularContext) { + // TODO:: Do we report this as error? + reportStatus(ts.Diagnostics.Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0, circularityReportStack.join("\r\n")); + } + return; + } + temporaryMarks.setValue(projPath, true); + circularityReportStack.push(projPath); + var parsed = parseConfigFile(projPath); + if (parsed && parsed.projectReferences) { + for (var _i = 0, _a = parsed.projectReferences; _i < _a.length; _i++) { + var ref = _a[_i]; + var resolvedRefPath = resolveProjectName(ref.path); + visit(resolvedRefPath, inCircularContext || ref.circular); + // Get projects referencing resolvedRefPath and add projPath to it + var referencingProjects = getOrCreateValueFromConfigFileMap(referencingProjectsMap, resolvedRefPath, function () { return createFileMap(toPath); }); + referencingProjects.setValue(projPath, !!ref.prepend); + } + } + circularityReportStack.pop(); + permanentMarks.setValue(projPath, true); + buildOrder.push(projPath); + } + } + function buildSingleProject(proj) { + if (options.dry) { + reportStatus(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj); + return BuildResultFlags.Success; + } + if (options.verbose) + reportStatus(ts.Diagnostics.Building_project_0, proj); + var resultFlags = BuildResultFlags.None; + resultFlags |= BuildResultFlags.DeclarationOutputUnchanged; + var configFile = parseConfigFile(proj); + if (!configFile) { + // Failed to read the config file + resultFlags |= BuildResultFlags.ConfigFileErrors; + reportParseConfigFileDiagnostic(proj); + projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Config file errors" }); + return resultFlags; + } + if (configFile.fileNames.length === 0) { + reportAndStoreErrors(proj, configFile.errors); + // Nothing to build - must be a solution file, basically + return BuildResultFlags.None; + } + var programOptions = { + projectReferences: configFile.projectReferences, + host: host, + rootNames: configFile.fileNames, + options: configFile.options, + configFileParsingDiagnostics: configFile.errors + }; + if (host.beforeCreateProgram) { + host.beforeCreateProgram(options); + } + var program = ts.createProgram(programOptions); + // Don't emit anything in the presence of syntactic errors or options diagnostics + var syntaxDiagnostics = program.getOptionsDiagnostics().concat(program.getConfigFileParsingDiagnostics(), program.getSyntacticDiagnostics()); + if (syntaxDiagnostics.length) { + return buildErrors(syntaxDiagnostics, BuildResultFlags.SyntaxErrors, "Syntactic"); + } + // Same as above but now for semantic diagnostics + var semanticDiagnostics = program.getSemanticDiagnostics(); + if (semanticDiagnostics.length) { + return buildErrors(semanticDiagnostics, BuildResultFlags.TypeErrors, "Semantic"); + } + var newestDeclarationFileContentChangedTime = minimumDate; + var anyDtsChanged = false; + var declDiagnostics; + var reportDeclarationDiagnostics = function (d) { return (declDiagnostics || (declDiagnostics = [])).push(d); }; + var outputFiles = []; + ts.emitFilesAndReportErrors(program, reportDeclarationDiagnostics, writeFileName, /*reportSummary*/ undefined, function (name, text, writeByteOrderMark) { return outputFiles.push({ name: name, text: text, writeByteOrderMark: writeByteOrderMark }); }); + // Don't emit .d.ts if there are decl file errors + if (declDiagnostics) { + return buildErrors(declDiagnostics, BuildResultFlags.DeclarationEmitErrors, "Declaration file"); + } + // Actual Emit + var emitterDiagnostics = ts.createDiagnosticCollection(); + outputFiles.forEach(function (_a) { + var name = _a.name, text = _a.text, writeByteOrderMark = _a.writeByteOrderMark; + var priorChangeTime; + if (!anyDtsChanged && isDeclarationFile(name)) { + // Check for unchanged .d.ts files + if (host.fileExists(name) && readFileWithCache(name) === text) { + priorChangeTime = host.getModifiedTime(name); + } + else { + resultFlags &= ~BuildResultFlags.DeclarationOutputUnchanged; + anyDtsChanged = true; + } + } + ts.writeFile(host, emitterDiagnostics, name, text, writeByteOrderMark); + if (priorChangeTime !== undefined) { + newestDeclarationFileContentChangedTime = newer(priorChangeTime, newestDeclarationFileContentChangedTime); + unchangedOutputs.setValue(name, priorChangeTime); + } + }); + var emitDiagnostics = emitterDiagnostics.getDiagnostics(); + if (emitDiagnostics.length) { + return buildErrors(emitDiagnostics, BuildResultFlags.EmitErrors, "Emit"); + } + var status = { + type: UpToDateStatusType.UpToDate, + newestDeclarationFileContentChangedTime: anyDtsChanged ? maximumDate : newestDeclarationFileContentChangedTime + }; + diagnostics.removeKey(proj); + projectStatus.setValue(proj, status); + if (host.afterProgramEmitAndDiagnostics) { + host.afterProgramEmitAndDiagnostics(program); + } + return resultFlags; + function buildErrors(diagnostics, errorFlags, errorType) { + resultFlags |= errorFlags; + reportAndStoreErrors(proj, diagnostics); + projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: errorType + " errors" }); + if (host.afterProgramEmitAndDiagnostics) { + host.afterProgramEmitAndDiagnostics(program); + } + return resultFlags; + } + } + function updateOutputTimestamps(proj) { + if (options.dry) { + return reportStatus(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj.options.configFilePath); + } + if (options.verbose) { + reportStatus(ts.Diagnostics.Updating_output_timestamps_of_project_0, proj.options.configFilePath); + } + var now = new Date(); + var outputs = getAllProjectOutputs(proj); + var priorNewestUpdateTime = minimumDate; + for (var _i = 0, outputs_2 = outputs; _i < outputs_2.length; _i++) { + var file = outputs_2[_i]; + if (isDeclarationFile(file)) { + priorNewestUpdateTime = newer(priorNewestUpdateTime, host.getModifiedTime(file) || ts.missingFileModifiedTime); + } + host.setModifiedTime(file, now); + } + projectStatus.setValue(proj.options.configFilePath, { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: priorNewestUpdateTime }); + } + function getFilesToClean() { + // Get the same graph for cleaning we'd use for building + var graph = getGlobalDependencyGraph(); + var filesToDelete = []; + for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { + var proj = _a[_i]; + var parsed = parseConfigFile(proj); + if (parsed === undefined) { + // File has gone missing; fine to ignore here + reportParseConfigFileDiagnostic(proj); + continue; + } + var outputs = getAllProjectOutputs(parsed); + for (var _b = 0, outputs_3 = outputs; _b < outputs_3.length; _b++) { + var output = outputs_3[_b]; + if (host.fileExists(output)) { + filesToDelete.push(output); + } + } + } + return filesToDelete; + } + function cleanAllProjects() { + var filesToDelete = getFilesToClean(); + if (options.dry) { + reportStatus(ts.Diagnostics.A_non_dry_build_would_delete_the_following_files_Colon_0, filesToDelete.map(function (f) { return "\r\n * " + f; }).join("")); + return ts.ExitStatus.Success; + } + for (var _i = 0, filesToDelete_1 = filesToDelete; _i < filesToDelete_1.length; _i++) { + var output = filesToDelete_1[_i]; + host.deleteFile(output); + } + return ts.ExitStatus.Success; + } + function resolveProjectName(name) { + return resolveConfigFileProjectName(ts.resolvePath(host.getCurrentDirectory(), name)); + } + function resolveProjectNames(configFileNames) { + return configFileNames.map(resolveProjectName); + } + function buildAllProjects() { + if (options.watch) { + reportWatchStatus(ts.Diagnostics.Starting_compilation_in_watch_mode); + } + // TODO:: In watch mode as well to use caches for incremental build once we can invalidate caches correctly and have right api + // Override readFile for json files and output .d.ts to cache the text + var _a = ts.changeCompilerHostToUseCache(host, toPath, /*useCacheForSourceFile*/ true), originalReadFile = _a.originalReadFile, originalFileExists = _a.originalFileExists, originalDirectoryExists = _a.originalDirectoryExists, originalCreateDirectory = _a.originalCreateDirectory, originalWriteFile = _a.originalWriteFile, originalGetSourceFile = _a.originalGetSourceFile, newReadFileWithCache = _a.readFileWithCache; + var savedReadFileWithCache = readFileWithCache; + readFileWithCache = newReadFileWithCache; + var graph = getGlobalDependencyGraph(); + reportBuildQueue(graph); + var anyFailed = false; + for (var _i = 0, _b = graph.buildQueue; _i < _b.length; _i++) { + var next = _b[_i]; + var proj = parseConfigFile(next); + if (proj === undefined) { + reportParseConfigFileDiagnostic(next); + anyFailed = true; + break; + } + // report errors early when using continue or break statements + var errors = proj.errors; + var status = getUpToDateStatus(proj); + verboseReportProjectStatus(next, status); + var projName = proj.options.configFilePath; + if (status.type === UpToDateStatusType.UpToDate && !options.force) { + reportAndStoreErrors(next, errors); + // Up to date, skip + if (defaultOptions.dry) { + // In a dry build, inform the user of this fact + reportStatus(ts.Diagnostics.Project_0_is_up_to_date, projName); + } + continue; + } + if (status.type === UpToDateStatusType.UpToDateWithUpstreamTypes && !options.force) { + reportAndStoreErrors(next, errors); + // Fake build + updateOutputTimestamps(proj); + continue; + } + if (status.type === UpToDateStatusType.UpstreamBlocked) { + reportAndStoreErrors(next, errors); + if (options.verbose) + reportStatus(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, projName, status.upstreamProjectName); + continue; + } + if (status.type === UpToDateStatusType.ContainerOnly) { + reportAndStoreErrors(next, errors); + // Do nothing + continue; + } + var buildResult = buildSingleProject(next); + anyFailed = anyFailed || !!(buildResult & BuildResultFlags.AnyErrors); + } + reportErrorSummary(); + host.readFile = originalReadFile; + host.fileExists = originalFileExists; + host.directoryExists = originalDirectoryExists; + host.createDirectory = originalCreateDirectory; + host.writeFile = originalWriteFile; + readFileWithCache = savedReadFileWithCache; + host.getSourceFile = originalGetSourceFile; + return anyFailed ? ts.ExitStatus.DiagnosticsPresent_OutputsSkipped : ts.ExitStatus.Success; + } + function reportParseConfigFileDiagnostic(proj) { + reportAndStoreErrors(proj, [configFileCache.getValue(proj)]); + } + function reportAndStoreErrors(proj, errors) { + reportErrors(errors); + projectErrorsReported.setValue(proj, true); + diagnostics.setValue(proj, errors); + } + function reportErrors(errors) { + errors.forEach(function (err) { return host.reportDiagnostic(err); }); + } + /** + * Report the build ordering inferred from the current project graph if we're in verbose mode + */ + function reportBuildQueue(graph) { + if (options.verbose) { + reportStatus(ts.Diagnostics.Projects_in_this_build_Colon_0, graph.buildQueue.map(function (s) { return "\r\n * " + relName(s); }).join("")); + } + } + function relName(path) { + return ts.convertToRelativePath(path, host.getCurrentDirectory(), function (f) { return host.getCanonicalFileName(f); }); + } + /** + * Report the up-to-date status of a project if we're in verbose mode + */ + function verboseReportProjectStatus(configFileName, status) { + if (!options.verbose) + return; + return formatUpToDateStatus(configFileName, status, relName, reportStatus); + } + } + ts.createSolutionBuilder = createSolutionBuilder; + function resolveConfigFileProjectName(project) { + if (ts.fileExtensionIs(project, ".json" /* Json */)) { + return project; + } + return ts.combinePaths(project, "tsconfig.json"); + } + ts.resolveConfigFileProjectName = resolveConfigFileProjectName; + function getAllProjectOutputs(project) { + if (project.options.outFile || project.options.out) { + return getOutFileOutputs(project); + } + else { + var outputs = []; + for (var _i = 0, _a = project.fileNames; _i < _a.length; _i++) { + var inputFile = _a[_i]; + outputs.push.apply(outputs, getOutputFileNames(inputFile, project)); + } + return outputs; + } + } + ts.getAllProjectOutputs = getAllProjectOutputs; + function formatUpToDateStatus(configFileName, status, relName, formatMessage) { + switch (status.type) { + case UpToDateStatusType.OutOfDateWithSelf: + return formatMessage(ts.Diagnostics.Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2, relName(configFileName), relName(status.outOfDateOutputFileName), relName(status.newerInputFileName)); + case UpToDateStatusType.OutOfDateWithUpstream: + return formatMessage(ts.Diagnostics.Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2, relName(configFileName), relName(status.outOfDateOutputFileName), relName(status.newerProjectName)); + case UpToDateStatusType.OutputMissing: + return formatMessage(ts.Diagnostics.Project_0_is_out_of_date_because_output_file_1_does_not_exist, relName(configFileName), relName(status.missingOutputFileName)); + case UpToDateStatusType.UpToDate: + if (status.newestInputFileTime !== undefined) { + return formatMessage(ts.Diagnostics.Project_0_is_up_to_date_because_newest_input_1_is_older_than_oldest_output_2, relName(configFileName), relName(status.newestInputFileName || ""), relName(status.oldestOutputFileName || "")); + } + // Don't report anything for "up to date because it was already built" -- too verbose + break; + case UpToDateStatusType.UpToDateWithUpstreamTypes: + return formatMessage(ts.Diagnostics.Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies, relName(configFileName)); + case UpToDateStatusType.UpstreamOutOfDate: + return formatMessage(ts.Diagnostics.Project_0_is_out_of_date_because_its_dependency_1_is_out_of_date, relName(configFileName), relName(status.upstreamProjectName)); + case UpToDateStatusType.UpstreamBlocked: + return formatMessage(ts.Diagnostics.Project_0_can_t_be_built_because_its_dependency_1_has_errors, relName(configFileName), relName(status.upstreamProjectName)); + case UpToDateStatusType.Unbuildable: + return formatMessage(ts.Diagnostics.Failed_to_parse_file_0_Colon_1, relName(configFileName), status.reason); + case UpToDateStatusType.ContainerOnly: + // Don't report status on "solution" projects + case UpToDateStatusType.ComputingUpstream: + // Should never leak from getUptoDateStatusWorker + break; + default: + ts.assertType(status); + } + } + ts.formatUpToDateStatus = formatUpToDateStatus; +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var ValueKind; + (function (ValueKind) { + ValueKind[ValueKind["Const"] = 0] = "Const"; + ValueKind[ValueKind["Array"] = 1] = "Array"; + ValueKind[ValueKind["FunctionOrClass"] = 2] = "FunctionOrClass"; + ValueKind[ValueKind["Object"] = 3] = "Object"; + })(ValueKind = ts.ValueKind || (ts.ValueKind = {})); + function inspectModule(fileNameToRequire) { + return inspectValue(ts.removeFileExtension(ts.getBaseFileName(fileNameToRequire)), tryRequire(fileNameToRequire)); + } + ts.inspectModule = inspectModule; + function inspectValue(name, value) { + return getValueInfo(name, value, getRecurser()); + } + ts.inspectValue = inspectValue; + function getRecurser() { + var seen = new Set(); + var nameStack = []; + return function (obj, name, cbOk, cbFail) { + if (seen.has(obj) || nameStack.length > 4) { + return cbFail(seen.has(obj), nameStack); + } + seen.add(obj); + nameStack.push(name); + var res = cbOk(); + nameStack.pop(); + seen.delete(obj); + return res; + }; + } + function getValueInfo(name, value, recurser) { + return recurser(value, name, function () { + if (typeof value === "function") + return getFunctionOrClassInfo(value, name, recurser); + if (typeof value === "object") { + var builtin = getBuiltinType(name, value, recurser); + if (builtin !== undefined) + return builtin; + var entries = getEntriesOfObject(value); + var hasNontrivialPrototype = Object.getPrototypeOf(value) !== Object.prototype; + var members = ts.flatMap(entries, function (_a) { + var key = _a.key, value = _a.value; + return getValueInfo(key, value, recurser); + }); + return { kind: 3 /* Object */, name: name, hasNontrivialPrototype: hasNontrivialPrototype, members: members }; + } + return { kind: 0 /* Const */, name: name, typeName: isNullOrUndefined(value) ? "any" : typeof value }; + }, function (isCircularReference, keyStack) { return anyValue(name, " " + (isCircularReference ? "Circular reference" : "Too-deep object hierarchy") + " from " + keyStack.join(".")); }); + } + function getFunctionOrClassInfo(fn, name, recurser) { + var prototypeMembers = getPrototypeMembers(fn, recurser); + var namespaceMembers = ts.flatMap(getEntriesOfObject(fn), function (_a) { + var key = _a.key, value = _a.value; + return getValueInfo(key, value, recurser); + }); + var toString = ts.cast(Function.prototype.toString.call(fn), ts.isString); + var source = ts.stringContains(toString, "{ [native code] }") ? getFunctionLength(fn) : toString; + return { kind: 2 /* FunctionOrClass */, name: name, source: source, namespaceMembers: namespaceMembers, prototypeMembers: prototypeMembers }; + } + var builtins = ts.memoize(function () { + var map = ts.createMap(); + for (var _i = 0, _a = getEntriesOfObject(global); _i < _a.length; _i++) { + var _b = _a[_i], key = _b.key, value = _b.value; + if (typeof value === "function" && typeof value.prototype === "object" && value !== Object) { + map.set(key, value); + } + } + return map; + }); + function getBuiltinType(name, value, recurser) { + return ts.isArray(value) + ? { name: name, kind: 1 /* Array */, inner: value.length && getValueInfo("element", ts.first(value), recurser) || anyValue(name) } + : ts.forEachEntry(builtins(), function (builtin, builtinName) { + return value instanceof builtin ? { kind: 0 /* Const */, name: name, typeName: builtinName } : undefined; + }); + } + function getPrototypeMembers(fn, recurser) { + var prototype = fn.prototype; + // tslint:disable-next-line no-unnecessary-type-assertion (TODO: update LKG and it will really be unnecessary) + return typeof prototype !== "object" || prototype === null ? ts.emptyArray : ts.mapDefined(getEntriesOfObject(prototype), function (_a) { + var key = _a.key, value = _a.value; + return key === "constructor" ? undefined : getValueInfo(key, value, recurser); + }); + } + var ignoredProperties = new Set(["arguments", "caller", "constructor", "eval", "super_"]); + var reservedFunctionProperties = new Set(Object.getOwnPropertyNames(ts.noop)); + function getEntriesOfObject(obj) { + var seen = ts.createMap(); + var entries = []; + var chain = obj; + while (!isNullOrUndefined(chain) && chain !== Object.prototype && chain !== Function.prototype) { + for (var _i = 0, _a = Object.getOwnPropertyNames(chain); _i < _a.length; _i++) { + var key = _a[_i]; + if (!isJsPrivate(key) && + !ignoredProperties.has(key) && + (typeof obj !== "function" || !reservedFunctionProperties.has(key)) && + // Don't add property from a higher prototype if it already exists in a lower one + ts.addToSeen(seen, key)) { + var value = safeGetPropertyOfObject(chain, key); + // Don't repeat "toString" that matches signature from Object.prototype + if (!(key === "toString" && typeof value === "function" && value.length === 0)) { + entries.push({ key: key, value: value }); + } + } + } + chain = Object.getPrototypeOf(chain); + } + return entries.sort(function (e1, e2) { return ts.compareStringsCaseSensitive(e1.key, e2.key); }); + } + function getFunctionLength(fn) { + return ts.tryCast(safeGetPropertyOfObject(fn, "length"), ts.isNumber) || 0; + } + function safeGetPropertyOfObject(obj, key) { + var desc = Object.getOwnPropertyDescriptor(obj, key); + return desc && desc.value; + } + function isNullOrUndefined(value) { + return value == null; // tslint:disable-line + } + function anyValue(name, comment) { + return { kind: 0 /* Const */, name: name, typeName: "any", comment: comment }; + } + function isJsPrivate(name) { + return name.startsWith("_"); + } + ts.isJsPrivate = isJsPrivate; + function tryRequire(fileNameToRequire) { + try { + return require(fileNameToRequire); + } + catch (_a) { + return undefined; + } + } +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var server; + (function (server) { + // tslint:disable variable-name + server.ActionSet = "action::set"; + server.ActionInvalidate = "action::invalidate"; + server.ActionPackageInstalled = "action::packageInstalled"; + server.ActionValueInspected = "action::valueInspected"; + server.EventTypesRegistry = "event::typesRegistry"; + server.EventBeginInstallTypes = "event::beginInstallTypes"; + server.EventEndInstallTypes = "event::endInstallTypes"; + server.EventInitializationFailed = "event::initializationFailed"; + var Arguments; + (function (Arguments) { + Arguments.GlobalCacheLocation = "--globalTypingsCacheLocation"; + Arguments.LogFile = "--logFile"; + Arguments.EnableTelemetry = "--enableTelemetry"; + Arguments.TypingSafeListLocation = "--typingSafeListLocation"; + Arguments.TypesMapLocation = "--typesMapLocation"; + /** + * This argument specifies the location of the NPM executable. + * typingsInstaller will run the command with `${npmLocation} install ...`. + */ + Arguments.NpmLocation = "--npmLocation"; + })(Arguments = server.Arguments || (server.Arguments = {})); + function hasArgument(argumentName) { + return ts.sys.args.indexOf(argumentName) >= 0; + } + server.hasArgument = hasArgument; + function findArgument(argumentName) { + var index = ts.sys.args.indexOf(argumentName); + return index >= 0 && index < ts.sys.args.length - 1 + ? ts.sys.args[index + 1] + : undefined; + } + server.findArgument = findArgument; + function nowString() { + // E.g. "12:34:56.789" + var d = new Date(); + return d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds() + "." + d.getMilliseconds(); + } + server.nowString = nowString; + })(server = ts.server || (ts.server = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var JsTyping; + (function (JsTyping) { + function isTypingUpToDate(cachedTyping, availableTypingVersions) { + var availableVersion = new ts.Version(ts.getProperty(availableTypingVersions, "ts" + ts.versionMajorMinor) || ts.getProperty(availableTypingVersions, "latest")); + return availableVersion.compareTo(cachedTyping.version) <= 0; + } + JsTyping.isTypingUpToDate = isTypingUpToDate; + JsTyping.nodeCoreModuleList = [ + "assert", + "async_hooks", + "buffer", + "child_process", + "cluster", + "console", + "constants", + "crypto", + "dgram", + "dns", + "domain", + "events", + "fs", + "http", + "https", + "http2", + "inspector", + "net", + "os", + "path", + "perf_hooks", + "process", + "punycode", + "querystring", + "readline", + "repl", + "stream", + "string_decoder", + "timers", + "tls", + "tty", + "url", + "util", + "v8", + "vm", + "zlib" + ]; + JsTyping.nodeCoreModules = ts.arrayToSet(JsTyping.nodeCoreModuleList); + function loadSafeList(host, safeListPath) { + var result = ts.readConfigFile(safeListPath, function (path) { return host.readFile(path); }); + return ts.createMapFromTemplate(result.config); + } + JsTyping.loadSafeList = loadSafeList; + function loadTypesMap(host, typesMapPath) { + var result = ts.readConfigFile(typesMapPath, function (path) { return host.readFile(path); }); + if (result.config) { + return ts.createMapFromTemplate(result.config.simpleMap); + } + return undefined; + } + JsTyping.loadTypesMap = loadTypesMap; + /** + * @param host is the object providing I/O related operations. + * @param fileNames are the file names that belong to the same project + * @param projectRootPath is the path to the project root directory + * @param safeListPath is the path used to retrieve the safe list + * @param packageNameToTypingLocation is the map of package names to their cached typing locations and installed versions + * @param typeAcquisition is used to customize the typing acquisition process + * @param compilerOptions are used as a source for typing inference + */ + function discoverTypings(host, log, fileNames, projectRootPath, safeList, packageNameToTypingLocation, typeAcquisition, unresolvedImports, typesRegistry) { + if (!typeAcquisition || !typeAcquisition.enable) { + return { cachedTypingPaths: [], newTypingNames: [], filesToWatch: [] }; + } + // A typing name to typing file path mapping + var inferredTypings = ts.createMap(); + // Only infer typings for .js and .jsx files + fileNames = ts.mapDefined(fileNames, function (fileName) { + var path = ts.normalizePath(fileName); + if (ts.hasJSFileExtension(path)) { + return path; + } + }); + var filesToWatch = []; + if (typeAcquisition.include) + addInferredTypings(typeAcquisition.include, "Explicitly included types"); + var exclude = typeAcquisition.exclude || []; + // Directories to search for package.json, bower.json and other typing information + var possibleSearchDirs = ts.arrayToSet(fileNames, ts.getDirectoryPath); + possibleSearchDirs.set(projectRootPath, true); + possibleSearchDirs.forEach(function (_true, searchDir) { + var packageJsonPath = ts.combinePaths(searchDir, "package.json"); + getTypingNamesFromJson(packageJsonPath, filesToWatch); + var bowerJsonPath = ts.combinePaths(searchDir, "bower.json"); + getTypingNamesFromJson(bowerJsonPath, filesToWatch); + var bowerComponentsPath = ts.combinePaths(searchDir, "bower_components"); + getTypingNamesFromPackagesFolder(bowerComponentsPath, filesToWatch); + var nodeModulesPath = ts.combinePaths(searchDir, "node_modules"); + getTypingNamesFromPackagesFolder(nodeModulesPath, filesToWatch); + }); + getTypingNamesFromSourceFileNames(fileNames); + // add typings for unresolved imports + if (unresolvedImports) { + var module_1 = ts.deduplicate(unresolvedImports.map(function (moduleId) { return JsTyping.nodeCoreModules.has(moduleId) ? "node" : moduleId; }), ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive); + addInferredTypings(module_1, "Inferred typings from unresolved imports"); + } + // Add the cached typing locations for inferred typings that are already installed + packageNameToTypingLocation.forEach(function (typing, name) { + var registryEntry = typesRegistry.get(name); + if (inferredTypings.has(name) && inferredTypings.get(name) === undefined && registryEntry !== undefined && isTypingUpToDate(typing, registryEntry)) { + inferredTypings.set(name, typing.typingLocation); + } + }); + // Remove typings that the user has added to the exclude list + for (var _i = 0, exclude_1 = exclude; _i < exclude_1.length; _i++) { + var excludeTypingName = exclude_1[_i]; + var didDelete = inferredTypings.delete(excludeTypingName); + if (didDelete && log) + log("Typing for " + excludeTypingName + " is in exclude list, will be ignored."); + } + var newTypingNames = []; + var cachedTypingPaths = []; + inferredTypings.forEach(function (inferred, typing) { + if (inferred !== undefined) { + cachedTypingPaths.push(inferred); + } + else { + newTypingNames.push(typing); + } + }); + var result = { cachedTypingPaths: cachedTypingPaths, newTypingNames: newTypingNames, filesToWatch: filesToWatch }; + if (log) + log("Result: " + JSON.stringify(result)); + return result; + function addInferredTyping(typingName) { + if (!inferredTypings.has(typingName)) { + inferredTypings.set(typingName, undefined); // TODO: GH#18217 + } + } + function addInferredTypings(typingNames, message) { + if (log) + log(message + ": " + JSON.stringify(typingNames)); + ts.forEach(typingNames, addInferredTyping); + } + /** + * Get the typing info from common package manager json files like package.json or bower.json + */ + function getTypingNamesFromJson(jsonPath, filesToWatch) { + if (!host.fileExists(jsonPath)) { + return; + } + filesToWatch.push(jsonPath); + var jsonConfig = ts.readConfigFile(jsonPath, function (path) { return host.readFile(path); }).config; + var jsonTypingNames = ts.flatMap([jsonConfig.dependencies, jsonConfig.devDependencies, jsonConfig.optionalDependencies, jsonConfig.peerDependencies], ts.getOwnKeys); + addInferredTypings(jsonTypingNames, "Typing names in '" + jsonPath + "' dependencies"); + } + /** + * Infer typing names from given file names. For example, the file name "jquery-min.2.3.4.js" + * should be inferred to the 'jquery' typing name; and "angular-route.1.2.3.js" should be inferred + * to the 'angular-route' typing name. + * @param fileNames are the names for source files in the project + */ + function getTypingNamesFromSourceFileNames(fileNames) { + var fromFileNames = ts.mapDefined(fileNames, function (j) { + if (!ts.hasJSFileExtension(j)) + return undefined; + var inferredTypingName = ts.removeFileExtension(ts.getBaseFileName(j.toLowerCase())); + var cleanedTypingName = ts.removeMinAndVersionNumbers(inferredTypingName); + return safeList.get(cleanedTypingName); + }); + if (fromFileNames.length) { + addInferredTypings(fromFileNames, "Inferred typings from file names"); + } + var hasJsxFile = ts.some(fileNames, function (f) { return ts.fileExtensionIs(f, ".jsx" /* Jsx */); }); + if (hasJsxFile) { + if (log) + log("Inferred 'react' typings due to presence of '.jsx' extension"); + addInferredTyping("react"); + } + } + /** + * Infer typing names from packages folder (ex: node_module, bower_components) + * @param packagesFolderPath is the path to the packages folder + */ + function getTypingNamesFromPackagesFolder(packagesFolderPath, filesToWatch) { + filesToWatch.push(packagesFolderPath); + // Todo: add support for ModuleResolutionHost too + if (!host.directoryExists(packagesFolderPath)) { + return; + } + // depth of 2, so we access `node_modules/foo` but not `node_modules/foo/bar` + var fileNames = host.readDirectory(packagesFolderPath, [".json" /* Json */], /*excludes*/ undefined, /*includes*/ undefined, /*depth*/ 2); + if (log) + log("Searching for typing names in " + packagesFolderPath + "; all files: " + JSON.stringify(fileNames)); + var packageNames = []; + for (var _i = 0, fileNames_1 = fileNames; _i < fileNames_1.length; _i++) { + var fileName = fileNames_1[_i]; + var normalizedFileName = ts.normalizePath(fileName); + var baseFileName = ts.getBaseFileName(normalizedFileName); + if (baseFileName !== "package.json" && baseFileName !== "bower.json") { + continue; + } + var result_6 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); }); + var packageJson = result_6.config; + // npm 3's package.json contains a "_requiredBy" field + // we should include all the top level module names for npm 2, and only module names whose + // "_requiredBy" field starts with "#" or equals "/" for npm 3. + if (baseFileName === "package.json" && packageJson._requiredBy && + ts.filter(packageJson._requiredBy, function (r) { return r[0] === "#" || r === "/"; }).length === 0) { + continue; + } + // If the package has its own d.ts typings, those will take precedence. Otherwise the package name will be used + // to download d.ts files from DefinitelyTyped + if (!packageJson.name) { + continue; + } + var ownTypes = packageJson.types || packageJson.typings; + if (ownTypes) { + var absolutePath = ts.getNormalizedAbsolutePath(ownTypes, ts.getDirectoryPath(normalizedFileName)); + if (log) + log(" Package '" + packageJson.name + "' provides its own types."); + inferredTypings.set(packageJson.name, absolutePath); + } + else { + packageNames.push(packageJson.name); + } + } + addInferredTypings(packageNames, " Found package names"); + } + } + JsTyping.discoverTypings = discoverTypings; + var PackageNameValidationResult; + (function (PackageNameValidationResult) { + PackageNameValidationResult[PackageNameValidationResult["Ok"] = 0] = "Ok"; + PackageNameValidationResult[PackageNameValidationResult["ScopedPackagesNotSupported"] = 1] = "ScopedPackagesNotSupported"; + PackageNameValidationResult[PackageNameValidationResult["EmptyName"] = 2] = "EmptyName"; + PackageNameValidationResult[PackageNameValidationResult["NameTooLong"] = 3] = "NameTooLong"; + PackageNameValidationResult[PackageNameValidationResult["NameStartsWithDot"] = 4] = "NameStartsWithDot"; + PackageNameValidationResult[PackageNameValidationResult["NameStartsWithUnderscore"] = 5] = "NameStartsWithUnderscore"; + PackageNameValidationResult[PackageNameValidationResult["NameContainsNonURISafeCharacters"] = 6] = "NameContainsNonURISafeCharacters"; + })(PackageNameValidationResult = JsTyping.PackageNameValidationResult || (JsTyping.PackageNameValidationResult = {})); + var maxPackageNameLength = 214; + /** + * Validates package name using rules defined at https://docs.npmjs.com/files/package.json + */ + function validatePackageName(packageName) { + if (!packageName) { + return 2 /* EmptyName */; + } + if (packageName.length > maxPackageNameLength) { + return 3 /* NameTooLong */; + } + if (packageName.charCodeAt(0) === 46 /* dot */) { + return 4 /* NameStartsWithDot */; + } + if (packageName.charCodeAt(0) === 95 /* _ */) { + return 5 /* NameStartsWithUnderscore */; + } + // check if name is scope package like: starts with @ and has one '/' in the middle + // scoped packages are not currently supported + // TODO: when support will be added we'll need to split and check both scope and package name + if (/^@[^/]+\/[^/]+$/.test(packageName)) { + return 1 /* ScopedPackagesNotSupported */; + } + if (encodeURIComponent(packageName) !== packageName) { + return 6 /* NameContainsNonURISafeCharacters */; + } + return 0 /* Ok */; + } + JsTyping.validatePackageName = validatePackageName; + function renderPackageNameValidationFailure(result, typing) { + switch (result) { + case 2 /* EmptyName */: + return "Package name '" + typing + "' cannot be empty"; + case 3 /* NameTooLong */: + return "Package name '" + typing + "' should be less than " + maxPackageNameLength + " characters"; + case 4 /* NameStartsWithDot */: + return "Package name '" + typing + "' cannot start with '.'"; + case 5 /* NameStartsWithUnderscore */: + return "Package name '" + typing + "' cannot start with '_'"; + case 1 /* ScopedPackagesNotSupported */: + return "Package '" + typing + "' is scoped and currently is not supported"; + case 6 /* NameContainsNonURISafeCharacters */: + return "Package name '" + typing + "' contains non URI safe characters"; + case 0 /* Ok */: + return ts.Debug.fail(); // Shouldn't have called this. + default: + throw ts.Debug.assertNever(result); + } + } + JsTyping.renderPackageNameValidationFailure = renderPackageNameValidationFailure; + })(JsTyping = ts.JsTyping || (ts.JsTyping = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + var ScriptSnapshot; + (function (ScriptSnapshot) { + var StringScriptSnapshot = /** @class */ (function () { + function StringScriptSnapshot(text) { + this.text = text; + } + StringScriptSnapshot.prototype.getText = function (start, end) { + return start === 0 && end === this.text.length + ? this.text + : this.text.substring(start, end); + }; + StringScriptSnapshot.prototype.getLength = function () { + return this.text.length; + }; + StringScriptSnapshot.prototype.getChangeRange = function () { + // Text-based snapshots do not support incremental parsing. Return undefined + // to signal that to the caller. + return undefined; + }; + return StringScriptSnapshot; + }()); + function fromString(text) { + return new StringScriptSnapshot(text); + } + ScriptSnapshot.fromString = fromString; + })(ScriptSnapshot = ts.ScriptSnapshot || (ts.ScriptSnapshot = {})); + /* @internal */ + ts.emptyOptions = {}; + var HighlightSpanKind; + (function (HighlightSpanKind) { + HighlightSpanKind["none"] = "none"; + HighlightSpanKind["definition"] = "definition"; + HighlightSpanKind["reference"] = "reference"; + HighlightSpanKind["writtenReference"] = "writtenReference"; + })(HighlightSpanKind = ts.HighlightSpanKind || (ts.HighlightSpanKind = {})); + var IndentStyle; + (function (IndentStyle) { + IndentStyle[IndentStyle["None"] = 0] = "None"; + IndentStyle[IndentStyle["Block"] = 1] = "Block"; + IndentStyle[IndentStyle["Smart"] = 2] = "Smart"; + })(IndentStyle = ts.IndentStyle || (ts.IndentStyle = {})); + function getDefaultFormatCodeSettings(newLineCharacter) { + return { + indentSize: 4, + tabSize: 4, + newLineCharacter: newLineCharacter || "\n", + convertTabsToSpaces: true, + indentStyle: IndentStyle.Smart, + insertSpaceAfterConstructor: false, + insertSpaceAfterCommaDelimiter: true, + insertSpaceAfterSemicolonInForStatements: true, + insertSpaceBeforeAndAfterBinaryOperators: true, + insertSpaceAfterKeywordsInControlFlowStatements: true, + insertSpaceAfterFunctionKeywordForAnonymousFunctions: false, + insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: false, + insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: false, + insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces: true, + insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: false, + insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces: false, + insertSpaceBeforeFunctionParenthesis: false, + placeOpenBraceOnNewLineForFunctions: false, + placeOpenBraceOnNewLineForControlBlocks: false, + }; + } + ts.getDefaultFormatCodeSettings = getDefaultFormatCodeSettings; + /* @internal */ + ts.testFormatSettings = getDefaultFormatCodeSettings("\n"); + var SymbolDisplayPartKind; + (function (SymbolDisplayPartKind) { + SymbolDisplayPartKind[SymbolDisplayPartKind["aliasName"] = 0] = "aliasName"; + SymbolDisplayPartKind[SymbolDisplayPartKind["className"] = 1] = "className"; + SymbolDisplayPartKind[SymbolDisplayPartKind["enumName"] = 2] = "enumName"; + SymbolDisplayPartKind[SymbolDisplayPartKind["fieldName"] = 3] = "fieldName"; + SymbolDisplayPartKind[SymbolDisplayPartKind["interfaceName"] = 4] = "interfaceName"; + SymbolDisplayPartKind[SymbolDisplayPartKind["keyword"] = 5] = "keyword"; + SymbolDisplayPartKind[SymbolDisplayPartKind["lineBreak"] = 6] = "lineBreak"; + SymbolDisplayPartKind[SymbolDisplayPartKind["numericLiteral"] = 7] = "numericLiteral"; + SymbolDisplayPartKind[SymbolDisplayPartKind["stringLiteral"] = 8] = "stringLiteral"; + SymbolDisplayPartKind[SymbolDisplayPartKind["localName"] = 9] = "localName"; + SymbolDisplayPartKind[SymbolDisplayPartKind["methodName"] = 10] = "methodName"; + SymbolDisplayPartKind[SymbolDisplayPartKind["moduleName"] = 11] = "moduleName"; + SymbolDisplayPartKind[SymbolDisplayPartKind["operator"] = 12] = "operator"; + SymbolDisplayPartKind[SymbolDisplayPartKind["parameterName"] = 13] = "parameterName"; + SymbolDisplayPartKind[SymbolDisplayPartKind["propertyName"] = 14] = "propertyName"; + SymbolDisplayPartKind[SymbolDisplayPartKind["punctuation"] = 15] = "punctuation"; + SymbolDisplayPartKind[SymbolDisplayPartKind["space"] = 16] = "space"; + SymbolDisplayPartKind[SymbolDisplayPartKind["text"] = 17] = "text"; + SymbolDisplayPartKind[SymbolDisplayPartKind["typeParameterName"] = 18] = "typeParameterName"; + SymbolDisplayPartKind[SymbolDisplayPartKind["enumMemberName"] = 19] = "enumMemberName"; + SymbolDisplayPartKind[SymbolDisplayPartKind["functionName"] = 20] = "functionName"; + SymbolDisplayPartKind[SymbolDisplayPartKind["regularExpressionLiteral"] = 21] = "regularExpressionLiteral"; + })(SymbolDisplayPartKind = ts.SymbolDisplayPartKind || (ts.SymbolDisplayPartKind = {})); + var OutliningSpanKind; + (function (OutliningSpanKind) { + /** Single or multi-line comments */ + OutliningSpanKind["Comment"] = "comment"; + /** Sections marked by '// #region' and '// #endregion' comments */ + OutliningSpanKind["Region"] = "region"; + /** Declarations and expressions */ + OutliningSpanKind["Code"] = "code"; + /** Contiguous blocks of import declarations */ + OutliningSpanKind["Imports"] = "imports"; + })(OutliningSpanKind = ts.OutliningSpanKind || (ts.OutliningSpanKind = {})); + var OutputFileType; + (function (OutputFileType) { + OutputFileType[OutputFileType["JavaScript"] = 0] = "JavaScript"; + OutputFileType[OutputFileType["SourceMap"] = 1] = "SourceMap"; + OutputFileType[OutputFileType["Declaration"] = 2] = "Declaration"; + })(OutputFileType = ts.OutputFileType || (ts.OutputFileType = {})); + var EndOfLineState; + (function (EndOfLineState) { + EndOfLineState[EndOfLineState["None"] = 0] = "None"; + EndOfLineState[EndOfLineState["InMultiLineCommentTrivia"] = 1] = "InMultiLineCommentTrivia"; + EndOfLineState[EndOfLineState["InSingleQuoteStringLiteral"] = 2] = "InSingleQuoteStringLiteral"; + EndOfLineState[EndOfLineState["InDoubleQuoteStringLiteral"] = 3] = "InDoubleQuoteStringLiteral"; + EndOfLineState[EndOfLineState["InTemplateHeadOrNoSubstitutionTemplate"] = 4] = "InTemplateHeadOrNoSubstitutionTemplate"; + EndOfLineState[EndOfLineState["InTemplateMiddleOrTail"] = 5] = "InTemplateMiddleOrTail"; + EndOfLineState[EndOfLineState["InTemplateSubstitutionPosition"] = 6] = "InTemplateSubstitutionPosition"; + })(EndOfLineState = ts.EndOfLineState || (ts.EndOfLineState = {})); + var TokenClass; + (function (TokenClass) { + TokenClass[TokenClass["Punctuation"] = 0] = "Punctuation"; + TokenClass[TokenClass["Keyword"] = 1] = "Keyword"; + TokenClass[TokenClass["Operator"] = 2] = "Operator"; + TokenClass[TokenClass["Comment"] = 3] = "Comment"; + TokenClass[TokenClass["Whitespace"] = 4] = "Whitespace"; + TokenClass[TokenClass["Identifier"] = 5] = "Identifier"; + TokenClass[TokenClass["NumberLiteral"] = 6] = "NumberLiteral"; + TokenClass[TokenClass["BigIntLiteral"] = 7] = "BigIntLiteral"; + TokenClass[TokenClass["StringLiteral"] = 8] = "StringLiteral"; + TokenClass[TokenClass["RegExpLiteral"] = 9] = "RegExpLiteral"; + })(TokenClass = ts.TokenClass || (ts.TokenClass = {})); + var ScriptElementKind; + (function (ScriptElementKind) { + ScriptElementKind["unknown"] = ""; + ScriptElementKind["warning"] = "warning"; + /** predefined type (void) or keyword (class) */ + ScriptElementKind["keyword"] = "keyword"; + /** top level script node */ + ScriptElementKind["scriptElement"] = "script"; + /** module foo {} */ + ScriptElementKind["moduleElement"] = "module"; + /** class X {} */ + ScriptElementKind["classElement"] = "class"; + /** var x = class X {} */ + ScriptElementKind["localClassElement"] = "local class"; + /** interface Y {} */ + ScriptElementKind["interfaceElement"] = "interface"; + /** type T = ... */ + ScriptElementKind["typeElement"] = "type"; + /** enum E */ + ScriptElementKind["enumElement"] = "enum"; + ScriptElementKind["enumMemberElement"] = "enum member"; + /** + * Inside module and script only + * const v = .. + */ + ScriptElementKind["variableElement"] = "var"; + /** Inside function */ + ScriptElementKind["localVariableElement"] = "local var"; + /** + * Inside module and script only + * function f() { } + */ + ScriptElementKind["functionElement"] = "function"; + /** Inside function */ + ScriptElementKind["localFunctionElement"] = "local function"; + /** class X { [public|private]* foo() {} } */ + ScriptElementKind["memberFunctionElement"] = "method"; + /** class X { [public|private]* [get|set] foo:number; } */ + ScriptElementKind["memberGetAccessorElement"] = "getter"; + ScriptElementKind["memberSetAccessorElement"] = "setter"; + /** + * class X { [public|private]* foo:number; } + * interface Y { foo:number; } + */ + ScriptElementKind["memberVariableElement"] = "property"; + /** class X { constructor() { } } */ + ScriptElementKind["constructorImplementationElement"] = "constructor"; + /** interface Y { ():number; } */ + ScriptElementKind["callSignatureElement"] = "call"; + /** interface Y { []:number; } */ + ScriptElementKind["indexSignatureElement"] = "index"; + /** interface Y { new():Y; } */ + ScriptElementKind["constructSignatureElement"] = "construct"; + /** function foo(*Y*: string) */ + ScriptElementKind["parameterElement"] = "parameter"; + ScriptElementKind["typeParameterElement"] = "type parameter"; + ScriptElementKind["primitiveType"] = "primitive type"; + ScriptElementKind["label"] = "label"; + ScriptElementKind["alias"] = "alias"; + ScriptElementKind["constElement"] = "const"; + ScriptElementKind["letElement"] = "let"; + ScriptElementKind["directory"] = "directory"; + ScriptElementKind["externalModuleName"] = "external module name"; + /** + * + */ + ScriptElementKind["jsxAttribute"] = "JSX attribute"; + /** String literal */ + ScriptElementKind["string"] = "string"; + })(ScriptElementKind = ts.ScriptElementKind || (ts.ScriptElementKind = {})); + var ScriptElementKindModifier; + (function (ScriptElementKindModifier) { + ScriptElementKindModifier["none"] = ""; + ScriptElementKindModifier["publicMemberModifier"] = "public"; + ScriptElementKindModifier["privateMemberModifier"] = "private"; + ScriptElementKindModifier["protectedMemberModifier"] = "protected"; + ScriptElementKindModifier["exportedModifier"] = "export"; + ScriptElementKindModifier["ambientModifier"] = "declare"; + ScriptElementKindModifier["staticModifier"] = "static"; + ScriptElementKindModifier["abstractModifier"] = "abstract"; + ScriptElementKindModifier["optionalModifier"] = "optional"; + ScriptElementKindModifier["dtsModifier"] = ".d.ts"; + ScriptElementKindModifier["tsModifier"] = ".ts"; + ScriptElementKindModifier["tsxModifier"] = ".tsx"; + ScriptElementKindModifier["jsModifier"] = ".js"; + ScriptElementKindModifier["jsxModifier"] = ".jsx"; + ScriptElementKindModifier["jsonModifier"] = ".json"; + })(ScriptElementKindModifier = ts.ScriptElementKindModifier || (ts.ScriptElementKindModifier = {})); + var ClassificationTypeNames; + (function (ClassificationTypeNames) { + ClassificationTypeNames["comment"] = "comment"; + ClassificationTypeNames["identifier"] = "identifier"; + ClassificationTypeNames["keyword"] = "keyword"; + ClassificationTypeNames["numericLiteral"] = "number"; + ClassificationTypeNames["bigintLiteral"] = "bigint"; + ClassificationTypeNames["operator"] = "operator"; + ClassificationTypeNames["stringLiteral"] = "string"; + ClassificationTypeNames["whiteSpace"] = "whitespace"; + ClassificationTypeNames["text"] = "text"; + ClassificationTypeNames["punctuation"] = "punctuation"; + ClassificationTypeNames["className"] = "class name"; + ClassificationTypeNames["enumName"] = "enum name"; + ClassificationTypeNames["interfaceName"] = "interface name"; + ClassificationTypeNames["moduleName"] = "module name"; + ClassificationTypeNames["typeParameterName"] = "type parameter name"; + ClassificationTypeNames["typeAliasName"] = "type alias name"; + ClassificationTypeNames["parameterName"] = "parameter name"; + ClassificationTypeNames["docCommentTagName"] = "doc comment tag name"; + ClassificationTypeNames["jsxOpenTagName"] = "jsx open tag name"; + ClassificationTypeNames["jsxCloseTagName"] = "jsx close tag name"; + ClassificationTypeNames["jsxSelfClosingTagName"] = "jsx self closing tag name"; + ClassificationTypeNames["jsxAttribute"] = "jsx attribute"; + ClassificationTypeNames["jsxText"] = "jsx text"; + ClassificationTypeNames["jsxAttributeStringLiteralValue"] = "jsx attribute string literal value"; + })(ClassificationTypeNames = ts.ClassificationTypeNames || (ts.ClassificationTypeNames = {})); + var ClassificationType; + (function (ClassificationType) { + ClassificationType[ClassificationType["comment"] = 1] = "comment"; + ClassificationType[ClassificationType["identifier"] = 2] = "identifier"; + ClassificationType[ClassificationType["keyword"] = 3] = "keyword"; + ClassificationType[ClassificationType["numericLiteral"] = 4] = "numericLiteral"; + ClassificationType[ClassificationType["operator"] = 5] = "operator"; + ClassificationType[ClassificationType["stringLiteral"] = 6] = "stringLiteral"; + ClassificationType[ClassificationType["regularExpressionLiteral"] = 7] = "regularExpressionLiteral"; + ClassificationType[ClassificationType["whiteSpace"] = 8] = "whiteSpace"; + ClassificationType[ClassificationType["text"] = 9] = "text"; + ClassificationType[ClassificationType["punctuation"] = 10] = "punctuation"; + ClassificationType[ClassificationType["className"] = 11] = "className"; + ClassificationType[ClassificationType["enumName"] = 12] = "enumName"; + ClassificationType[ClassificationType["interfaceName"] = 13] = "interfaceName"; + ClassificationType[ClassificationType["moduleName"] = 14] = "moduleName"; + ClassificationType[ClassificationType["typeParameterName"] = 15] = "typeParameterName"; + ClassificationType[ClassificationType["typeAliasName"] = 16] = "typeAliasName"; + ClassificationType[ClassificationType["parameterName"] = 17] = "parameterName"; + ClassificationType[ClassificationType["docCommentTagName"] = 18] = "docCommentTagName"; + ClassificationType[ClassificationType["jsxOpenTagName"] = 19] = "jsxOpenTagName"; + ClassificationType[ClassificationType["jsxCloseTagName"] = 20] = "jsxCloseTagName"; + ClassificationType[ClassificationType["jsxSelfClosingTagName"] = 21] = "jsxSelfClosingTagName"; + ClassificationType[ClassificationType["jsxAttribute"] = 22] = "jsxAttribute"; + ClassificationType[ClassificationType["jsxText"] = 23] = "jsxText"; + ClassificationType[ClassificationType["jsxAttributeStringLiteralValue"] = 24] = "jsxAttributeStringLiteralValue"; + ClassificationType[ClassificationType["bigintLiteral"] = 25] = "bigintLiteral"; + })(ClassificationType = ts.ClassificationType || (ts.ClassificationType = {})); +})(ts || (ts = {})); +// These utilities are common to multiple language service features. +/* @internal */ +var ts; +(function (ts) { + ts.scanner = ts.createScanner(6 /* Latest */, /*skipTrivia*/ true); + var SemanticMeaning; + (function (SemanticMeaning) { + SemanticMeaning[SemanticMeaning["None"] = 0] = "None"; + SemanticMeaning[SemanticMeaning["Value"] = 1] = "Value"; + SemanticMeaning[SemanticMeaning["Type"] = 2] = "Type"; + SemanticMeaning[SemanticMeaning["Namespace"] = 4] = "Namespace"; + SemanticMeaning[SemanticMeaning["All"] = 7] = "All"; + })(SemanticMeaning = ts.SemanticMeaning || (ts.SemanticMeaning = {})); + function getMeaningFromDeclaration(node) { + switch (node.kind) { + case 237 /* VariableDeclaration */: + return ts.isInJSFile(node) && ts.getJSDocEnumTag(node) ? 7 /* All */ : 1 /* Value */; + case 151 /* Parameter */: + case 186 /* BindingElement */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 275 /* PropertyAssignment */: + case 276 /* ShorthandPropertyAssignment */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 274 /* CatchClause */: + case 267 /* JsxAttribute */: + return 1 /* Value */; + case 150 /* TypeParameter */: + case 241 /* InterfaceDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 168 /* TypeLiteral */: + return 2 /* Type */; + case 304 /* JSDocTypedefTag */: + // If it has no name node, it shares the name with the value declaration below it. + return node.name === undefined ? 1 /* Value */ | 2 /* Type */ : 2 /* Type */; + case 278 /* EnumMember */: + case 240 /* ClassDeclaration */: + return 1 /* Value */ | 2 /* Type */; + case 244 /* ModuleDeclaration */: + if (ts.isAmbientModule(node)) { + return 4 /* Namespace */ | 1 /* Value */; + } + else if (ts.getModuleInstanceState(node) === 1 /* Instantiated */) { + return 4 /* Namespace */ | 1 /* Value */; + } + else { + return 4 /* Namespace */; + } + case 243 /* EnumDeclaration */: + case 252 /* NamedImports */: + case 253 /* ImportSpecifier */: + case 248 /* ImportEqualsDeclaration */: + case 249 /* ImportDeclaration */: + case 254 /* ExportAssignment */: + case 255 /* ExportDeclaration */: + return 7 /* All */; + // An external module can be a Value + case 279 /* SourceFile */: + return 4 /* Namespace */ | 1 /* Value */; + } + return 7 /* All */; + } + ts.getMeaningFromDeclaration = getMeaningFromDeclaration; + function getMeaningFromLocation(node) { + if (node.kind === 279 /* SourceFile */) { + return 1 /* Value */; + } + else if (node.parent.kind === 254 /* ExportAssignment */ || node.parent.kind === 259 /* ExternalModuleReference */) { + return 7 /* All */; + } + else if (isInRightSideOfInternalImportEqualsDeclaration(node)) { + return getMeaningFromRightHandSideOfImportEquals(node); + } + else if (ts.isDeclarationName(node)) { + return getMeaningFromDeclaration(node.parent); + } + else if (isTypeReference(node)) { + return 2 /* Type */; + } + else if (isNamespaceReference(node)) { + return 4 /* Namespace */; + } + else if (ts.isTypeParameterDeclaration(node.parent)) { + ts.Debug.assert(ts.isJSDocTemplateTag(node.parent.parent)); // Else would be handled by isDeclarationName + return 2 /* Type */; + } + else if (ts.isLiteralTypeNode(node.parent)) { + // This might be T["name"], which is actually referencing a property and not a type. So allow both meanings. + return 2 /* Type */ | 1 /* Value */; + } + else { + return 1 /* Value */; + } + } + ts.getMeaningFromLocation = getMeaningFromLocation; + function getMeaningFromRightHandSideOfImportEquals(node) { + // import a = |b|; // Namespace + // import a = |b.c|; // Value, type, namespace + // import a = |b.c|.d; // Namespace + var name = node.kind === 148 /* QualifiedName */ ? node : ts.isQualifiedName(node.parent) && node.parent.right === node ? node.parent : undefined; + return name && name.parent.kind === 248 /* ImportEqualsDeclaration */ ? 7 /* All */ : 4 /* Namespace */; + } + function isInRightSideOfInternalImportEqualsDeclaration(node) { + while (node.parent.kind === 148 /* QualifiedName */) { + node = node.parent; + } + return ts.isInternalModuleImportEqualsDeclaration(node.parent) && node.parent.moduleReference === node; + } + ts.isInRightSideOfInternalImportEqualsDeclaration = isInRightSideOfInternalImportEqualsDeclaration; + function isNamespaceReference(node) { + return isQualifiedNameNamespaceReference(node) || isPropertyAccessNamespaceReference(node); + } + function isQualifiedNameNamespaceReference(node) { + var root = node; + var isLastClause = true; + if (root.parent.kind === 148 /* QualifiedName */) { + while (root.parent && root.parent.kind === 148 /* QualifiedName */) { + root = root.parent; + } + isLastClause = root.right === node; + } + return root.parent.kind === 164 /* TypeReference */ && !isLastClause; + } + function isPropertyAccessNamespaceReference(node) { + var root = node; + var isLastClause = true; + if (root.parent.kind === 189 /* PropertyAccessExpression */) { + while (root.parent && root.parent.kind === 189 /* PropertyAccessExpression */) { + root = root.parent; + } + isLastClause = root.name === node; + } + if (!isLastClause && root.parent.kind === 211 /* ExpressionWithTypeArguments */ && root.parent.parent.kind === 273 /* HeritageClause */) { + var decl = root.parent.parent.parent; + return (decl.kind === 240 /* ClassDeclaration */ && root.parent.parent.token === 109 /* ImplementsKeyword */) || + (decl.kind === 241 /* InterfaceDeclaration */ && root.parent.parent.token === 86 /* ExtendsKeyword */); + } + return false; + } + function isTypeReference(node) { + if (ts.isRightSideOfQualifiedNameOrPropertyAccess(node)) { + node = node.parent; + } + switch (node.kind) { + case 100 /* ThisKeyword */: + return !ts.isExpressionNode(node); + case 178 /* ThisType */: + return true; + } + switch (node.parent.kind) { + case 164 /* TypeReference */: + return true; + case 183 /* ImportType */: + return !node.parent.isTypeOf; + case 211 /* ExpressionWithTypeArguments */: + return !ts.isExpressionWithTypeArgumentsInClassExtendsClause(node.parent); + } + return false; + } + function isCallExpressionTarget(node) { + return isCallOrNewExpressionTargetWorker(node, ts.isCallExpression); + } + ts.isCallExpressionTarget = isCallExpressionTarget; + function isNewExpressionTarget(node) { + return isCallOrNewExpressionTargetWorker(node, ts.isNewExpression); + } + ts.isNewExpressionTarget = isNewExpressionTarget; + function isCallOrNewExpressionTarget(node) { + return isCallOrNewExpressionTargetWorker(node, ts.isCallOrNewExpression); + } + ts.isCallOrNewExpressionTarget = isCallOrNewExpressionTarget; + function isCallOrNewExpressionTargetWorker(node, pred) { + var target = climbPastPropertyAccess(node); + return !!target && !!target.parent && pred(target.parent) && target.parent.expression === target; + } + function climbPastPropertyAccess(node) { + return isRightSideOfPropertyAccess(node) ? node.parent : node; + } + ts.climbPastPropertyAccess = climbPastPropertyAccess; + function getTargetLabel(referenceNode, labelName) { + while (referenceNode) { + if (referenceNode.kind === 233 /* LabeledStatement */ && referenceNode.label.escapedText === labelName) { + return referenceNode.label; + } + referenceNode = referenceNode.parent; + } + return undefined; + } + ts.getTargetLabel = getTargetLabel; + function hasPropertyAccessExpressionWithName(node, funcName) { + if (!ts.isPropertyAccessExpression(node.expression)) { + return false; + } + return node.expression.name.text === funcName; + } + ts.hasPropertyAccessExpressionWithName = hasPropertyAccessExpressionWithName; + function isJumpStatementTarget(node) { + return node.kind === 72 /* Identifier */ && ts.isBreakOrContinueStatement(node.parent) && node.parent.label === node; + } + ts.isJumpStatementTarget = isJumpStatementTarget; + function isLabelOfLabeledStatement(node) { + return node.kind === 72 /* Identifier */ && ts.isLabeledStatement(node.parent) && node.parent.label === node; + } + ts.isLabelOfLabeledStatement = isLabelOfLabeledStatement; + function isLabelName(node) { + return isLabelOfLabeledStatement(node) || isJumpStatementTarget(node); + } + ts.isLabelName = isLabelName; + function isTagName(node) { + return ts.isJSDocTag(node.parent) && node.parent.tagName === node; + } + ts.isTagName = isTagName; + function isRightSideOfQualifiedName(node) { + return node.parent.kind === 148 /* QualifiedName */ && node.parent.right === node; + } + ts.isRightSideOfQualifiedName = isRightSideOfQualifiedName; + function isRightSideOfPropertyAccess(node) { + return node && node.parent && node.parent.kind === 189 /* PropertyAccessExpression */ && node.parent.name === node; + } + ts.isRightSideOfPropertyAccess = isRightSideOfPropertyAccess; + function isNameOfModuleDeclaration(node) { + return node.parent.kind === 244 /* ModuleDeclaration */ && node.parent.name === node; + } + ts.isNameOfModuleDeclaration = isNameOfModuleDeclaration; + function isNameOfFunctionDeclaration(node) { + return node.kind === 72 /* Identifier */ && + ts.isFunctionLike(node.parent) && node.parent.name === node; + } + ts.isNameOfFunctionDeclaration = isNameOfFunctionDeclaration; + function isLiteralNameOfPropertyDeclarationOrIndexAccess(node) { + switch (node.parent.kind) { + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 275 /* PropertyAssignment */: + case 278 /* EnumMember */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 244 /* ModuleDeclaration */: + return ts.getNameOfDeclaration(node.parent) === node; + case 190 /* ElementAccessExpression */: + return node.parent.argumentExpression === node; + case 149 /* ComputedPropertyName */: + return true; + case 182 /* LiteralType */: + return node.parent.parent.kind === 180 /* IndexedAccessType */; + default: + return false; + } + } + ts.isLiteralNameOfPropertyDeclarationOrIndexAccess = isLiteralNameOfPropertyDeclarationOrIndexAccess; + function isExpressionOfExternalModuleImportEqualsDeclaration(node) { + return ts.isExternalModuleImportEqualsDeclaration(node.parent.parent) && + ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node; + } + ts.isExpressionOfExternalModuleImportEqualsDeclaration = isExpressionOfExternalModuleImportEqualsDeclaration; + function getContainerNode(node) { + if (ts.isJSDocTypeAlias(node)) { + // This doesn't just apply to the node immediately under the comment, but to everything in its parent's scope. + // node.parent = the JSDoc comment, node.parent.parent = the node having the comment. + // Then we get parent again in the loop. + node = node.parent.parent; + } + while (true) { + node = node.parent; + if (!node) { + return undefined; + } + switch (node.kind) { + case 279 /* SourceFile */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + case 243 /* EnumDeclaration */: + case 244 /* ModuleDeclaration */: + return node; + } + } + } + ts.getContainerNode = getContainerNode; + function getNodeKind(node) { + switch (node.kind) { + case 279 /* SourceFile */: + return ts.isExternalModule(node) ? "module" /* moduleElement */ : "script" /* scriptElement */; + case 244 /* ModuleDeclaration */: + return "module" /* moduleElement */; + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + return "class" /* classElement */; + case 241 /* InterfaceDeclaration */: return "interface" /* interfaceElement */; + case 242 /* TypeAliasDeclaration */: + case 297 /* JSDocCallbackTag */: + case 304 /* JSDocTypedefTag */: + return "type" /* typeElement */; + case 243 /* EnumDeclaration */: return "enum" /* enumElement */; + case 237 /* VariableDeclaration */: + return getKindOfVariableDeclaration(node); + case 186 /* BindingElement */: + return getKindOfVariableDeclaration(ts.getRootDeclaration(node)); + case 197 /* ArrowFunction */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + return "function" /* functionElement */; + case 158 /* GetAccessor */: return "getter" /* memberGetAccessorElement */; + case 159 /* SetAccessor */: return "setter" /* memberSetAccessorElement */; + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + return "method" /* memberFunctionElement */; + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + return "property" /* memberVariableElement */; + case 162 /* IndexSignature */: return "index" /* indexSignatureElement */; + case 161 /* ConstructSignature */: return "construct" /* constructSignatureElement */; + case 160 /* CallSignature */: return "call" /* callSignatureElement */; + case 157 /* Constructor */: return "constructor" /* constructorImplementationElement */; + case 150 /* TypeParameter */: return "type parameter" /* typeParameterElement */; + case 278 /* EnumMember */: return "enum member" /* enumMemberElement */; + case 151 /* Parameter */: return ts.hasModifier(node, 92 /* ParameterPropertyModifier */) ? "property" /* memberVariableElement */ : "parameter" /* parameterElement */; + case 248 /* ImportEqualsDeclaration */: + case 253 /* ImportSpecifier */: + case 257 /* ExportSpecifier */: + case 251 /* NamespaceImport */: + return "alias" /* alias */; + case 204 /* BinaryExpression */: + var kind = ts.getAssignmentDeclarationKind(node); + var right = node.right; + switch (kind) { + case 7 /* ObjectDefinePropertyValue */: + case 8 /* ObjectDefinePropertyExports */: + case 9 /* ObjectDefinePrototypeProperty */: + case 0 /* None */: + return "" /* unknown */; + case 1 /* ExportsProperty */: + case 2 /* ModuleExports */: + var rightKind = getNodeKind(right); + return rightKind === "" /* unknown */ ? "const" /* constElement */ : rightKind; + case 3 /* PrototypeProperty */: + return ts.isFunctionExpression(right) ? "method" /* memberFunctionElement */ : "property" /* memberVariableElement */; + case 4 /* ThisProperty */: + return "property" /* memberVariableElement */; // property + case 5 /* Property */: + // static method / property + return ts.isFunctionExpression(right) ? "method" /* memberFunctionElement */ : "property" /* memberVariableElement */; + case 6 /* Prototype */: + return "local class" /* localClassElement */; + default: { + ts.assertType(kind); + return "" /* unknown */; + } + } + case 72 /* Identifier */: + return ts.isImportClause(node.parent) ? "alias" /* alias */ : "" /* unknown */; + default: + return "" /* unknown */; + } + function getKindOfVariableDeclaration(v) { + return ts.isVarConst(v) + ? "const" /* constElement */ + : ts.isLet(v) + ? "let" /* letElement */ + : "var" /* variableElement */; + } + } + ts.getNodeKind = getNodeKind; + function isThis(node) { + switch (node.kind) { + case 100 /* ThisKeyword */: + // case SyntaxKind.ThisType: TODO: GH#9267 + return true; + case 72 /* Identifier */: + // 'this' as a parameter + return ts.identifierIsThisKeyword(node) && node.parent.kind === 151 /* Parameter */; + default: + return false; + } + } + ts.isThis = isThis; + // Matches the beginning of a triple slash directive + var tripleSlashDirectivePrefixRegex = /^\/\/\/\s*= range.end; + } + ts.startEndContainsRange = startEndContainsRange; + function rangeContainsStartEnd(range, start, end) { + return range.pos <= start && range.end >= end; + } + ts.rangeContainsStartEnd = rangeContainsStartEnd; + function rangeOverlapsWithStartEnd(r1, start, end) { + return startEndOverlapsWithStartEnd(r1.pos, r1.end, start, end); + } + ts.rangeOverlapsWithStartEnd = rangeOverlapsWithStartEnd; + function nodeOverlapsWithStartEnd(node, sourceFile, start, end) { + return startEndOverlapsWithStartEnd(node.getStart(sourceFile), node.end, start, end); + } + ts.nodeOverlapsWithStartEnd = nodeOverlapsWithStartEnd; + function startEndOverlapsWithStartEnd(start1, end1, start2, end2) { + var start = Math.max(start1, start2); + var end = Math.min(end1, end2); + return start < end; + } + ts.startEndOverlapsWithStartEnd = startEndOverlapsWithStartEnd; + /** + * Assumes `candidate.start <= position` holds. + */ + function positionBelongsToNode(candidate, position, sourceFile) { + ts.Debug.assert(candidate.pos <= position); + return position < candidate.end || !isCompletedNode(candidate, sourceFile); + } + ts.positionBelongsToNode = positionBelongsToNode; + function isCompletedNode(n, sourceFile) { + if (n === undefined || ts.nodeIsMissing(n)) { + return false; + } + switch (n.kind) { + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + case 243 /* EnumDeclaration */: + case 188 /* ObjectLiteralExpression */: + case 184 /* ObjectBindingPattern */: + case 168 /* TypeLiteral */: + case 218 /* Block */: + case 245 /* ModuleBlock */: + case 246 /* CaseBlock */: + case 252 /* NamedImports */: + case 256 /* NamedExports */: + return nodeEndsWith(n, 19 /* CloseBraceToken */, sourceFile); + case 274 /* CatchClause */: + return isCompletedNode(n.block, sourceFile); + case 192 /* NewExpression */: + if (!n.arguments) { + return true; + } + // falls through + case 191 /* CallExpression */: + case 195 /* ParenthesizedExpression */: + case 177 /* ParenthesizedType */: + return nodeEndsWith(n, 21 /* CloseParenToken */, sourceFile); + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + return isCompletedNode(n.type, sourceFile); + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 161 /* ConstructSignature */: + case 160 /* CallSignature */: + case 197 /* ArrowFunction */: + if (n.body) { + return isCompletedNode(n.body, sourceFile); + } + if (n.type) { + return isCompletedNode(n.type, sourceFile); + } + // Even though type parameters can be unclosed, we can get away with + // having at least a closing paren. + return hasChildOfKind(n, 21 /* CloseParenToken */, sourceFile); + case 244 /* ModuleDeclaration */: + return !!n.body && isCompletedNode(n.body, sourceFile); + case 222 /* IfStatement */: + if (n.elseStatement) { + return isCompletedNode(n.elseStatement, sourceFile); + } + return isCompletedNode(n.thenStatement, sourceFile); + case 221 /* ExpressionStatement */: + return isCompletedNode(n.expression, sourceFile) || + hasChildOfKind(n, 26 /* SemicolonToken */, sourceFile); + case 187 /* ArrayLiteralExpression */: + case 185 /* ArrayBindingPattern */: + case 190 /* ElementAccessExpression */: + case 149 /* ComputedPropertyName */: + case 170 /* TupleType */: + return nodeEndsWith(n, 23 /* CloseBracketToken */, sourceFile); + case 162 /* IndexSignature */: + if (n.type) { + return isCompletedNode(n.type, sourceFile); + } + return hasChildOfKind(n, 23 /* CloseBracketToken */, sourceFile); + case 271 /* CaseClause */: + case 272 /* DefaultClause */: + // there is no such thing as terminator token for CaseClause/DefaultClause so for simplicity always consider them non-completed + return false; + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + case 224 /* WhileStatement */: + return isCompletedNode(n.statement, sourceFile); + case 223 /* DoStatement */: + // rough approximation: if DoStatement has While keyword - then if node is completed is checking the presence of ')'; + return hasChildOfKind(n, 107 /* WhileKeyword */, sourceFile) + ? nodeEndsWith(n, 21 /* CloseParenToken */, sourceFile) + : isCompletedNode(n.statement, sourceFile); + case 167 /* TypeQuery */: + return isCompletedNode(n.exprName, sourceFile); + case 199 /* TypeOfExpression */: + case 198 /* DeleteExpression */: + case 200 /* VoidExpression */: + case 207 /* YieldExpression */: + case 208 /* SpreadElement */: + var unaryWordExpression = n; + return isCompletedNode(unaryWordExpression.expression, sourceFile); + case 193 /* TaggedTemplateExpression */: + return isCompletedNode(n.template, sourceFile); + case 206 /* TemplateExpression */: + var lastSpan = ts.lastOrUndefined(n.templateSpans); + return isCompletedNode(lastSpan, sourceFile); + case 216 /* TemplateSpan */: + return ts.nodeIsPresent(n.literal); + case 255 /* ExportDeclaration */: + case 249 /* ImportDeclaration */: + return ts.nodeIsPresent(n.moduleSpecifier); + case 202 /* PrefixUnaryExpression */: + return isCompletedNode(n.operand, sourceFile); + case 204 /* BinaryExpression */: + return isCompletedNode(n.right, sourceFile); + case 205 /* ConditionalExpression */: + return isCompletedNode(n.whenFalse, sourceFile); + default: + return true; + } + } + /* + * Checks if node ends with 'expectedLastToken'. + * If child at position 'length - 1' is 'SemicolonToken' it is skipped and 'expectedLastToken' is compared with child at position 'length - 2'. + */ + function nodeEndsWith(n, expectedLastToken, sourceFile) { + var children = n.getChildren(sourceFile); + if (children.length) { + var lastChild = ts.last(children); + if (lastChild.kind === expectedLastToken) { + return true; + } + else if (lastChild.kind === 26 /* SemicolonToken */ && children.length !== 1) { + return children[children.length - 2].kind === expectedLastToken; + } + } + return false; + } + function findListItemInfo(node) { + var list = findContainingList(node); + // It is possible at this point for syntaxList to be undefined, either if + // node.parent had no list child, or if none of its list children contained + // the span of node. If this happens, return undefined. The caller should + // handle this case. + if (!list) { + return undefined; + } + var children = list.getChildren(); + var listItemIndex = ts.indexOfNode(children, node); + return { + listItemIndex: listItemIndex, + list: list + }; + } + ts.findListItemInfo = findListItemInfo; + function hasChildOfKind(n, kind, sourceFile) { + return !!findChildOfKind(n, kind, sourceFile); + } + ts.hasChildOfKind = hasChildOfKind; + function findChildOfKind(n, kind, sourceFile) { + return ts.find(n.getChildren(sourceFile), function (c) { return c.kind === kind; }); + } + ts.findChildOfKind = findChildOfKind; + function findContainingList(node) { + // The node might be a list element (nonsynthetic) or a comma (synthetic). Either way, it will + // be parented by the container of the SyntaxList, not the SyntaxList itself. + // In order to find the list item index, we first need to locate SyntaxList itself and then search + // for the position of the relevant node (or comma). + var syntaxList = ts.find(node.parent.getChildren(), function (c) { return ts.isSyntaxList(c) && rangeContainsRange(c, node); }); + // Either we didn't find an appropriate list, or the list must contain us. + ts.Debug.assert(!syntaxList || ts.contains(syntaxList.getChildren(), node)); + return syntaxList; + } + ts.findContainingList = findContainingList; + /** + * Gets the token whose text has range [start, end) and + * position >= start and (position < end or (position === end && token is literal or keyword or identifier)) + */ + function getTouchingPropertyName(sourceFile, position) { + return getTouchingToken(sourceFile, position, function (n) { return ts.isPropertyNameLiteral(n) || ts.isKeyword(n.kind); }); + } + ts.getTouchingPropertyName = getTouchingPropertyName; + /** + * Returns the token if position is in [start, end). + * If position === end, returns the preceding token if includeItemAtEndPosition(previousToken) === true + */ + function getTouchingToken(sourceFile, position, includePrecedingTokenAtEndPosition) { + return getTokenAtPositionWorker(sourceFile, position, /*allowPositionInLeadingTrivia*/ false, includePrecedingTokenAtEndPosition, /*includeEndPosition*/ false); + } + ts.getTouchingToken = getTouchingToken; + /** Returns a token if position is in [start-of-leading-trivia, end) */ + function getTokenAtPosition(sourceFile, position) { + return getTokenAtPositionWorker(sourceFile, position, /*allowPositionInLeadingTrivia*/ true, /*includePrecedingTokenAtEndPosition*/ undefined, /*includeEndPosition*/ false); + } + ts.getTokenAtPosition = getTokenAtPosition; + /** Get the token whose text contains the position */ + function getTokenAtPositionWorker(sourceFile, position, allowPositionInLeadingTrivia, includePrecedingTokenAtEndPosition, includeEndPosition) { + var current = sourceFile; + outer: while (true) { + // find the child that contains 'position' + for (var _i = 0, _a = current.getChildren(sourceFile); _i < _a.length; _i++) { + var child = _a[_i]; + var start = allowPositionInLeadingTrivia ? child.getFullStart() : child.getStart(sourceFile, /*includeJsDoc*/ true); + if (start > position) { + // If this child begins after position, then all subsequent children will as well. + break; + } + var end = child.getEnd(); + if (position < end || (position === end && (child.kind === 1 /* EndOfFileToken */ || includeEndPosition))) { + current = child; + continue outer; + } + else if (includePrecedingTokenAtEndPosition && end === position) { + var previousToken = findPrecedingToken(position, sourceFile, child); + if (previousToken && includePrecedingTokenAtEndPosition(previousToken)) { + return previousToken; + } + } + } + return current; + } + } + /** + * The token on the left of the position is the token that strictly includes the position + * or sits to the left of the cursor if it is on a boundary. For example + * + * fo|o -> will return foo + * foo |bar -> will return foo + * + */ + function findTokenOnLeftOfPosition(file, position) { + // Ideally, getTokenAtPosition should return a token. However, it is currently + // broken, so we do a check to make sure the result was indeed a token. + var tokenAtPosition = getTokenAtPosition(file, position); + if (ts.isToken(tokenAtPosition) && position > tokenAtPosition.getStart(file) && position < tokenAtPosition.getEnd()) { + return tokenAtPosition; + } + return findPrecedingToken(position, file); + } + ts.findTokenOnLeftOfPosition = findTokenOnLeftOfPosition; + function findNextToken(previousToken, parent, sourceFile) { + return find(parent); + function find(n) { + if (ts.isToken(n) && n.pos === previousToken.end) { + // this is token that starts at the end of previous token - return it + return n; + } + return ts.firstDefined(n.getChildren(), function (child) { + var shouldDiveInChildNode = + // previous token is enclosed somewhere in the child + (child.pos <= previousToken.pos && child.end > previousToken.end) || + // previous token ends exactly at the beginning of child + (child.pos === previousToken.end); + return shouldDiveInChildNode && nodeHasTokens(child, sourceFile) ? find(child) : undefined; + }); + } + } + ts.findNextToken = findNextToken; + /** + * Finds the rightmost token satisfying `token.end <= position`, + * excluding `JsxText` tokens containing only whitespace. + */ + function findPrecedingToken(position, sourceFile, startNode, excludeJsdoc) { + var result = find(startNode || sourceFile); + ts.Debug.assert(!(result && isWhiteSpaceOnlyJsxText(result))); + return result; + function find(n) { + if (isNonWhitespaceToken(n) && n.kind !== 1 /* EndOfFileToken */) { + return n; + } + var children = n.getChildren(sourceFile); + for (var i = 0; i < children.length; i++) { + var child = children[i]; + // Note that the span of a node's tokens is [node.getStart(...), node.end). + // Given that `position < child.end` and child has constituent tokens, we distinguish these cases: + // 1) `position` precedes `child`'s tokens or `child` has no tokens (ie: in a comment or whitespace preceding `child`): + // we need to find the last token in a previous child. + // 2) `position` is within the same span: we recurse on `child`. + if (position < child.end) { + var start = child.getStart(sourceFile, /*includeJsDoc*/ !excludeJsdoc); + var lookInPreviousChild = (start >= position) || // cursor in the leading trivia + !nodeHasTokens(child, sourceFile) || + isWhiteSpaceOnlyJsxText(child); + if (lookInPreviousChild) { + // actual start of the node is past the position - previous token should be at the end of previous child + var candidate_2 = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ i, sourceFile); + return candidate_2 && findRightmostToken(candidate_2, sourceFile); + } + else { + // candidate should be in this node + return find(child); + } + } + } + ts.Debug.assert(startNode !== undefined || n.kind === 279 /* SourceFile */ || n.kind === 1 /* EndOfFileToken */ || ts.isJSDocCommentContainingNode(n)); + // Here we know that none of child token nodes embrace the position, + // the only known case is when position is at the end of the file. + // Try to find the rightmost token in the file without filtering. + // Namely we are skipping the check: 'position < node.end' + var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ children.length, sourceFile); + return candidate && findRightmostToken(candidate, sourceFile); + } + } + ts.findPrecedingToken = findPrecedingToken; + function isNonWhitespaceToken(n) { + return ts.isToken(n) && !isWhiteSpaceOnlyJsxText(n); + } + function findRightmostToken(n, sourceFile) { + if (isNonWhitespaceToken(n)) { + return n; + } + var children = n.getChildren(sourceFile); + var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ children.length, sourceFile); + return candidate && findRightmostToken(candidate, sourceFile); + } + /** + * Finds the rightmost child to the left of `children[exclusiveStartPosition]` which is a non-all-whitespace token or has constituent tokens. + */ + function findRightmostChildNodeWithTokens(children, exclusiveStartPosition, sourceFile) { + for (var i = exclusiveStartPosition - 1; i >= 0; i--) { + var child = children[i]; + if (isWhiteSpaceOnlyJsxText(child)) { + ts.Debug.assert(i > 0, "`JsxText` tokens should not be the first child of `JsxElement | JsxSelfClosingElement`"); + } + else if (nodeHasTokens(children[i], sourceFile)) { + return children[i]; + } + } + } + function isInString(sourceFile, position, previousToken) { + if (previousToken === void 0) { previousToken = findPrecedingToken(position, sourceFile); } + if (previousToken && ts.isStringTextContainingNode(previousToken)) { + var start = previousToken.getStart(sourceFile); + var end = previousToken.getEnd(); + // To be "in" one of these literals, the position has to be: + // 1. entirely within the token text. + // 2. at the end position of an unterminated token. + // 3. at the end of a regular expression (due to trailing flags like '/foo/g'). + if (start < position && position < end) { + return true; + } + if (position === end) { + return !!previousToken.isUnterminated; + } + } + return false; + } + ts.isInString = isInString; + /** + * returns true if the position is in between the open and close elements of an JSX expression. + */ + function isInsideJsxElementOrAttribute(sourceFile, position) { + var token = getTokenAtPosition(sourceFile, position); + if (!token) { + return false; + } + if (token.kind === 11 /* JsxText */) { + return true; + } + //
      Hello |
      + if (token.kind === 28 /* LessThanToken */ && token.parent.kind === 11 /* JsxText */) { + return true; + } + //
      { |
      or
      + if (token.kind === 28 /* LessThanToken */ && token.parent.kind === 270 /* JsxExpression */) { + return true; + } + //
      { + // | + // } < /div> + if (token && token.kind === 19 /* CloseBraceToken */ && token.parent.kind === 270 /* JsxExpression */) { + return true; + } + //
      |
      + if (token.kind === 28 /* LessThanToken */ && token.parent.kind === 263 /* JsxClosingElement */) { + return true; + } + return false; + } + ts.isInsideJsxElementOrAttribute = isInsideJsxElementOrAttribute; + function isWhiteSpaceOnlyJsxText(node) { + return ts.isJsxText(node) && node.containsOnlyWhiteSpaces; + } + function isInTemplateString(sourceFile, position) { + var token = getTokenAtPosition(sourceFile, position); + return ts.isTemplateLiteralKind(token.kind) && position > token.getStart(sourceFile); + } + ts.isInTemplateString = isInTemplateString; + function isInJSXText(sourceFile, position) { + var token = getTokenAtPosition(sourceFile, position); + if (ts.isJsxText(token)) { + return true; + } + if (token.kind === 18 /* OpenBraceToken */ && ts.isJsxExpression(token.parent) && ts.isJsxElement(token.parent.parent)) { + return true; + } + if (token.kind === 28 /* LessThanToken */ && ts.isJsxOpeningLikeElement(token.parent) && ts.isJsxElement(token.parent.parent)) { + return true; + } + return false; + } + ts.isInJSXText = isInJSXText; + function findPrecedingMatchingToken(token, matchingTokenKind, sourceFile) { + var tokenKind = token.kind; + var remainingMatchingTokens = 0; + while (true) { + var preceding = findPrecedingToken(token.getFullStart(), sourceFile); + if (!preceding) { + return undefined; + } + token = preceding; + if (token.kind === matchingTokenKind) { + if (remainingMatchingTokens === 0) { + return token; + } + remainingMatchingTokens--; + } + else if (token.kind === tokenKind) { + remainingMatchingTokens++; + } + } + } + ts.findPrecedingMatchingToken = findPrecedingMatchingToken; + function isPossiblyTypeArgumentPosition(token, sourceFile, checker) { + var info = getPossibleTypeArgumentsInfo(token, sourceFile); + return info !== undefined && (ts.isPartOfTypeNode(info.called) || + getPossibleGenericSignatures(info.called, info.nTypeArguments, checker).length !== 0 || + isPossiblyTypeArgumentPosition(info.called, sourceFile, checker)); + } + ts.isPossiblyTypeArgumentPosition = isPossiblyTypeArgumentPosition; + function getPossibleGenericSignatures(called, typeArgumentCount, checker) { + var type = checker.getTypeAtLocation(called); + var signatures = ts.isNewExpression(called.parent) ? type.getConstructSignatures() : type.getCallSignatures(); + return signatures.filter(function (candidate) { return !!candidate.typeParameters && candidate.typeParameters.length >= typeArgumentCount; }); + } + ts.getPossibleGenericSignatures = getPossibleGenericSignatures; + // Get info for an expression like `f <` that may be the start of type arguments. + function getPossibleTypeArgumentsInfo(tokenIn, sourceFile) { + var token = tokenIn; + // This function determines if the node could be type argument position + // Since during editing, when type argument list is not complete, + // the tree could be of any shape depending on the tokens parsed before current node, + // scanning of the previous identifier followed by "<" before current node would give us better result + // Note that we also balance out the already provided type arguments, arrays, object literals while doing so + var remainingLessThanTokens = 0; + var nTypeArguments = 0; + while (token) { + switch (token.kind) { + case 28 /* LessThanToken */: + // Found the beginning of the generic argument expression + token = findPrecedingToken(token.getFullStart(), sourceFile); + if (!token || !ts.isIdentifier(token)) + return undefined; + if (!remainingLessThanTokens) { + return ts.isDeclarationName(token) ? undefined : { called: token, nTypeArguments: nTypeArguments }; + } + remainingLessThanTokens--; + break; + case 48 /* GreaterThanGreaterThanGreaterThanToken */: + remainingLessThanTokens = +3; + break; + case 47 /* GreaterThanGreaterThanToken */: + remainingLessThanTokens = +2; + break; + case 30 /* GreaterThanToken */: + remainingLessThanTokens++; + break; + case 19 /* CloseBraceToken */: + // This can be object type, skip until we find the matching open brace token + // Skip until the matching open brace token + token = findPrecedingMatchingToken(token, 18 /* OpenBraceToken */, sourceFile); + if (!token) + return undefined; + break; + case 21 /* CloseParenToken */: + // This can be object type, skip until we find the matching open brace token + // Skip until the matching open brace token + token = findPrecedingMatchingToken(token, 20 /* OpenParenToken */, sourceFile); + if (!token) + return undefined; + break; + case 23 /* CloseBracketToken */: + // This can be object type, skip until we find the matching open brace token + // Skip until the matching open brace token + token = findPrecedingMatchingToken(token, 22 /* OpenBracketToken */, sourceFile); + if (!token) + return undefined; + break; + // Valid tokens in a type name. Skip. + case 27 /* CommaToken */: + nTypeArguments++; + break; + case 37 /* EqualsGreaterThanToken */: + case 72 /* Identifier */: + case 10 /* StringLiteral */: + case 8 /* NumericLiteral */: + case 9 /* BigIntLiteral */: + case 102 /* TrueKeyword */: + case 87 /* FalseKeyword */: + case 104 /* TypeOfKeyword */: + case 86 /* ExtendsKeyword */: + case 129 /* KeyOfKeyword */: + case 24 /* DotToken */: + case 50 /* BarToken */: + case 56 /* QuestionToken */: + case 57 /* ColonToken */: + break; + default: + if (ts.isTypeNode(token)) { + break; + } + // Invalid token in type + return undefined; + } + token = findPrecedingToken(token.getFullStart(), sourceFile); + } + return undefined; + } + ts.getPossibleTypeArgumentsInfo = getPossibleTypeArgumentsInfo; + /** + * Returns true if the cursor at position in sourceFile is within a comment. + * + * @param tokenAtPosition Must equal `getTokenAtPosition(sourceFile, position) + * @param predicate Additional predicate to test on the comment range. + */ + function isInComment(sourceFile, position, tokenAtPosition) { + return ts.formatting.getRangeOfEnclosingComment(sourceFile, position, /*precedingToken*/ undefined, tokenAtPosition); + } + ts.isInComment = isInComment; + function hasDocComment(sourceFile, position) { + var token = getTokenAtPosition(sourceFile, position); + return !!ts.findAncestor(token, ts.isJSDoc); + } + ts.hasDocComment = hasDocComment; + function nodeHasTokens(n, sourceFile) { + // If we have a token or node that has a non-zero width, it must have tokens. + // Note: getWidth() does not take trivia into account. + return n.kind === 1 /* EndOfFileToken */ ? !!n.jsDoc : n.getWidth(sourceFile) !== 0; + } + function getNodeModifiers(node) { + var flags = ts.isDeclaration(node) ? ts.getCombinedModifierFlags(node) : 0 /* None */; + var result = []; + if (flags & 8 /* Private */) + result.push("private" /* privateMemberModifier */); + if (flags & 16 /* Protected */) + result.push("protected" /* protectedMemberModifier */); + if (flags & 4 /* Public */) + result.push("public" /* publicMemberModifier */); + if (flags & 32 /* Static */) + result.push("static" /* staticModifier */); + if (flags & 128 /* Abstract */) + result.push("abstract" /* abstractModifier */); + if (flags & 1 /* Export */) + result.push("export" /* exportedModifier */); + if (node.flags & 4194304 /* Ambient */) + result.push("declare" /* ambientModifier */); + return result.length > 0 ? result.join(",") : "" /* none */; + } + ts.getNodeModifiers = getNodeModifiers; + function getTypeArgumentOrTypeParameterList(node) { + if (node.kind === 164 /* TypeReference */ || node.kind === 191 /* CallExpression */) { + return node.typeArguments; + } + if (ts.isFunctionLike(node) || node.kind === 240 /* ClassDeclaration */ || node.kind === 241 /* InterfaceDeclaration */) { + return node.typeParameters; + } + return undefined; + } + ts.getTypeArgumentOrTypeParameterList = getTypeArgumentOrTypeParameterList; + function isComment(kind) { + return kind === 2 /* SingleLineCommentTrivia */ || kind === 3 /* MultiLineCommentTrivia */; + } + ts.isComment = isComment; + function isStringOrRegularExpressionOrTemplateLiteral(kind) { + if (kind === 10 /* StringLiteral */ + || kind === 13 /* RegularExpressionLiteral */ + || ts.isTemplateLiteralKind(kind)) { + return true; + } + return false; + } + ts.isStringOrRegularExpressionOrTemplateLiteral = isStringOrRegularExpressionOrTemplateLiteral; + function isPunctuation(kind) { + return 18 /* FirstPunctuation */ <= kind && kind <= 71 /* LastPunctuation */; + } + ts.isPunctuation = isPunctuation; + function isInsideTemplateLiteral(node, position, sourceFile) { + return ts.isTemplateLiteralKind(node.kind) + && (node.getStart(sourceFile) < position && position < node.end) || (!!node.isUnterminated && position === node.end); + } + ts.isInsideTemplateLiteral = isInsideTemplateLiteral; + function isAccessibilityModifier(kind) { + switch (kind) { + case 115 /* PublicKeyword */: + case 113 /* PrivateKeyword */: + case 114 /* ProtectedKeyword */: + return true; + } + return false; + } + ts.isAccessibilityModifier = isAccessibilityModifier; + function cloneCompilerOptions(options) { + var result = ts.clone(options); + ts.setConfigFileInOptions(result, options && options.configFile); + return result; + } + ts.cloneCompilerOptions = cloneCompilerOptions; + function isArrayLiteralOrObjectLiteralDestructuringPattern(node) { + if (node.kind === 187 /* ArrayLiteralExpression */ || + node.kind === 188 /* ObjectLiteralExpression */) { + // [a,b,c] from: + // [a, b, c] = someExpression; + if (node.parent.kind === 204 /* BinaryExpression */ && + node.parent.left === node && + node.parent.operatorToken.kind === 59 /* EqualsToken */) { + return true; + } + // [a, b, c] from: + // for([a, b, c] of expression) + if (node.parent.kind === 227 /* ForOfStatement */ && + node.parent.initializer === node) { + return true; + } + // [a, b, c] of + // [x, [a, b, c] ] = someExpression + // or + // {x, a: {a, b, c} } = someExpression + if (isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent.kind === 275 /* PropertyAssignment */ ? node.parent.parent : node.parent)) { + return true; + } + } + return false; + } + ts.isArrayLiteralOrObjectLiteralDestructuringPattern = isArrayLiteralOrObjectLiteralDestructuringPattern; + function isInReferenceComment(sourceFile, position) { + return isInReferenceCommentWorker(sourceFile, position, /*shouldBeReference*/ true); + } + ts.isInReferenceComment = isInReferenceComment; + function isInNonReferenceComment(sourceFile, position) { + return isInReferenceCommentWorker(sourceFile, position, /*shouldBeReference*/ false); + } + ts.isInNonReferenceComment = isInNonReferenceComment; + function isInReferenceCommentWorker(sourceFile, position, shouldBeReference) { + var range = isInComment(sourceFile, position, /*tokenAtPosition*/ undefined); + return !!range && shouldBeReference === tripleSlashDirectivePrefixRegex.test(sourceFile.text.substring(range.pos, range.end)); + } + function createTextSpanFromNode(node, sourceFile) { + return ts.createTextSpanFromBounds(node.getStart(sourceFile), node.getEnd()); + } + ts.createTextSpanFromNode = createTextSpanFromNode; + function createTextRangeFromNode(node, sourceFile) { + return ts.createRange(node.getStart(sourceFile), node.end); + } + ts.createTextRangeFromNode = createTextRangeFromNode; + function createTextSpanFromRange(range) { + return ts.createTextSpanFromBounds(range.pos, range.end); + } + ts.createTextSpanFromRange = createTextSpanFromRange; + function createTextRangeFromSpan(span) { + return ts.createRange(span.start, span.start + span.length); + } + ts.createTextRangeFromSpan = createTextRangeFromSpan; + function createTextChangeFromStartLength(start, length, newText) { + return createTextChange(ts.createTextSpan(start, length), newText); + } + ts.createTextChangeFromStartLength = createTextChangeFromStartLength; + function createTextChange(span, newText) { + return { span: span, newText: newText }; + } + ts.createTextChange = createTextChange; + ts.typeKeywords = [ + 120 /* AnyKeyword */, + 146 /* BigIntKeyword */, + 123 /* BooleanKeyword */, + 87 /* FalseKeyword */, + 129 /* KeyOfKeyword */, + 132 /* NeverKeyword */, + 96 /* NullKeyword */, + 135 /* NumberKeyword */, + 136 /* ObjectKeyword */, + 138 /* StringKeyword */, + 139 /* SymbolKeyword */, + 102 /* TrueKeyword */, + 106 /* VoidKeyword */, + 141 /* UndefinedKeyword */, + 142 /* UniqueKeyword */, + 143 /* UnknownKeyword */, + ]; + function isTypeKeyword(kind) { + return ts.contains(ts.typeKeywords, kind); + } + ts.isTypeKeyword = isTypeKeyword; + /** True if the symbol is for an external module, as opposed to a namespace. */ + function isExternalModuleSymbol(moduleSymbol) { + return !!(moduleSymbol.flags & 1536 /* Module */) && moduleSymbol.name.charCodeAt(0) === 34 /* doubleQuote */; + } + ts.isExternalModuleSymbol = isExternalModuleSymbol; + function nodeSeenTracker() { + var seen = []; + return function (node) { + var id = ts.getNodeId(node); + return !seen[id] && (seen[id] = true); + }; + } + ts.nodeSeenTracker = nodeSeenTracker; + function getSnapshotText(snap) { + return snap.getText(0, snap.getLength()); + } + ts.getSnapshotText = getSnapshotText; + function repeatString(str, count) { + var result = ""; + for (var i = 0; i < count; i++) { + result += str; + } + return result; + } + ts.repeatString = repeatString; + function skipConstraint(type) { + return type.isTypeParameter() ? type.getConstraint() || type : type; + } + ts.skipConstraint = skipConstraint; + function getNameFromPropertyName(name) { + return name.kind === 149 /* ComputedPropertyName */ + // treat computed property names where expression is string/numeric literal as just string/numeric literal + ? ts.isStringOrNumericLiteralLike(name.expression) ? name.expression.text : undefined + : ts.getTextOfIdentifierOrLiteral(name); + } + ts.getNameFromPropertyName = getNameFromPropertyName; + function programContainsEs6Modules(program) { + return program.getSourceFiles().some(function (s) { return !s.isDeclarationFile && !program.isSourceFileFromExternalLibrary(s) && !!s.externalModuleIndicator; }); + } + ts.programContainsEs6Modules = programContainsEs6Modules; + function compilerOptionsIndicateEs6Modules(compilerOptions) { + return !!compilerOptions.module || compilerOptions.target >= 2 /* ES2015 */ || !!compilerOptions.noEmit; + } + ts.compilerOptionsIndicateEs6Modules = compilerOptionsIndicateEs6Modules; + function hostUsesCaseSensitiveFileNames(host) { + return host.useCaseSensitiveFileNames ? host.useCaseSensitiveFileNames() : false; + } + ts.hostUsesCaseSensitiveFileNames = hostUsesCaseSensitiveFileNames; + function hostGetCanonicalFileName(host) { + return ts.createGetCanonicalFileName(hostUsesCaseSensitiveFileNames(host)); + } + ts.hostGetCanonicalFileName = hostGetCanonicalFileName; + function makeImportIfNecessary(defaultImport, namedImports, moduleSpecifier, quotePreference) { + return defaultImport || namedImports && namedImports.length ? makeImport(defaultImport, namedImports, moduleSpecifier, quotePreference) : undefined; + } + ts.makeImportIfNecessary = makeImportIfNecessary; + function makeImport(defaultImport, namedImports, moduleSpecifier, quotePreference) { + return ts.createImportDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, defaultImport || namedImports + ? ts.createImportClause(defaultImport, namedImports && namedImports.length ? ts.createNamedImports(namedImports) : undefined) + : undefined, typeof moduleSpecifier === "string" ? makeStringLiteral(moduleSpecifier, quotePreference) : moduleSpecifier); + } + ts.makeImport = makeImport; + function makeStringLiteral(text, quotePreference) { + return ts.createLiteral(text, quotePreference === 0 /* Single */); + } + ts.makeStringLiteral = makeStringLiteral; + var QuotePreference; + (function (QuotePreference) { + QuotePreference[QuotePreference["Single"] = 0] = "Single"; + QuotePreference[QuotePreference["Double"] = 1] = "Double"; + })(QuotePreference = ts.QuotePreference || (ts.QuotePreference = {})); + function quotePreferenceFromString(str, sourceFile) { + return ts.isStringDoubleQuoted(str, sourceFile) ? 1 /* Double */ : 0 /* Single */; + } + ts.quotePreferenceFromString = quotePreferenceFromString; + function getQuotePreference(sourceFile, preferences) { + if (preferences.quotePreference) { + return preferences.quotePreference === "single" ? 0 /* Single */ : 1 /* Double */; + } + else { + var firstModuleSpecifier = sourceFile.imports && ts.find(sourceFile.imports, ts.isStringLiteral); + return firstModuleSpecifier ? quotePreferenceFromString(firstModuleSpecifier, sourceFile) : 1 /* Double */; + } + } + ts.getQuotePreference = getQuotePreference; + function getQuoteFromPreference(qp) { + switch (qp) { + case 0 /* Single */: return "'"; + case 1 /* Double */: return '"'; + default: return ts.Debug.assertNever(qp); + } + } + ts.getQuoteFromPreference = getQuoteFromPreference; + function symbolNameNoDefault(symbol) { + var escaped = symbolEscapedNameNoDefault(symbol); + return escaped === undefined ? undefined : ts.unescapeLeadingUnderscores(escaped); + } + ts.symbolNameNoDefault = symbolNameNoDefault; + function symbolEscapedNameNoDefault(symbol) { + if (symbol.escapedName !== "default" /* Default */) { + return symbol.escapedName; + } + return ts.firstDefined(symbol.declarations, function (decl) { + var name = ts.getNameOfDeclaration(decl); + return name && name.kind === 72 /* Identifier */ ? name.escapedText : undefined; + }); + } + ts.symbolEscapedNameNoDefault = symbolEscapedNameNoDefault; + function isObjectBindingElementWithoutPropertyName(bindingElement) { + return ts.isBindingElement(bindingElement) && + ts.isObjectBindingPattern(bindingElement.parent) && + ts.isIdentifier(bindingElement.name) && + !bindingElement.propertyName; + } + ts.isObjectBindingElementWithoutPropertyName = isObjectBindingElementWithoutPropertyName; + function getPropertySymbolFromBindingElement(checker, bindingElement) { + var typeOfPattern = checker.getTypeAtLocation(bindingElement.parent); + return typeOfPattern && checker.getPropertyOfType(typeOfPattern, bindingElement.name.text); + } + ts.getPropertySymbolFromBindingElement = getPropertySymbolFromBindingElement; + /** + * Find symbol of the given property-name and add the symbol to the given result array + * @param symbol a symbol to start searching for the given propertyName + * @param propertyName a name of property to search for + * @param result an array of symbol of found property symbols + * @param previousIterationSymbolsCache a cache of symbol from previous iterations of calling this function to prevent infinite revisiting of the same symbol. + * The value of previousIterationSymbol is undefined when the function is first called. + */ + function getPropertySymbolsFromBaseTypes(symbol, propertyName, checker, cb) { + var seen = ts.createMap(); + return recur(symbol); + function recur(symbol) { + // Use `addToSeen` to ensure we don't infinitely recurse in this situation: + // interface C extends C { + // /*findRef*/propName: string; + // } + if (!(symbol.flags & (32 /* Class */ | 64 /* Interface */)) || !ts.addToSeen(seen, ts.getSymbolId(symbol))) + return; + return ts.firstDefined(symbol.declarations, function (declaration) { return ts.firstDefined(ts.getAllSuperTypeNodes(declaration), function (typeReference) { + var type = checker.getTypeAtLocation(typeReference); + var propertySymbol = type && type.symbol && checker.getPropertyOfType(type, propertyName); + // Visit the typeReference as well to see if it directly or indirectly uses that property + return type && propertySymbol && (ts.firstDefined(checker.getRootSymbols(propertySymbol), cb) || recur(type.symbol)); + }); }); + } + } + ts.getPropertySymbolsFromBaseTypes = getPropertySymbolsFromBaseTypes; + function isMemberSymbolInBaseType(memberSymbol, checker) { + return getPropertySymbolsFromBaseTypes(memberSymbol.parent, memberSymbol.name, checker, function (_) { return true; }) || false; + } + ts.isMemberSymbolInBaseType = isMemberSymbolInBaseType; + function getParentNodeInSpan(node, file, span) { + if (!node) + return undefined; + while (node.parent) { + if (ts.isSourceFile(node.parent) || !spanContainsNode(span, node.parent, file)) { + return node; + } + node = node.parent; + } + } + ts.getParentNodeInSpan = getParentNodeInSpan; + function spanContainsNode(span, node, file) { + return ts.textSpanContainsPosition(span, node.getStart(file)) && + node.getEnd() <= ts.textSpanEnd(span); + } + function findModifier(node, kind) { + return node.modifiers && ts.find(node.modifiers, function (m) { return m.kind === kind; }); + } + ts.findModifier = findModifier; + function insertImport(changes, sourceFile, importDecl) { + var lastImportDeclaration = ts.findLast(sourceFile.statements, ts.isAnyImportSyntax); + if (lastImportDeclaration) { + changes.insertNodeAfter(sourceFile, lastImportDeclaration, importDecl); + } + else { + changes.insertNodeAtTopOfFile(sourceFile, importDecl, /*blankLineBetween*/ true); + } + } + ts.insertImport = insertImport; + function textSpansEqual(a, b) { + return !!a && !!b && a.start === b.start && a.length === b.length; + } + ts.textSpansEqual = textSpansEqual; + function documentSpansEqual(a, b) { + return a.fileName === b.fileName && textSpansEqual(a.textSpan, b.textSpan); + } + ts.documentSpansEqual = documentSpansEqual; +})(ts || (ts = {})); +// Display-part writer helpers +/* @internal */ +(function (ts) { + function isFirstDeclarationOfSymbolParameter(symbol) { + return symbol.declarations && symbol.declarations.length > 0 && symbol.declarations[0].kind === 151 /* Parameter */; + } + ts.isFirstDeclarationOfSymbolParameter = isFirstDeclarationOfSymbolParameter; + var displayPartWriter = getDisplayPartWriter(); + function getDisplayPartWriter() { + var absoluteMaximumLength = ts.defaultMaximumTruncationLength * 10; // A hard cutoff to avoid overloading the messaging channel in worst-case scenarios + var displayParts; + var lineStart; + var indent; + var length; + resetWriter(); + var unknownWrite = function (text) { return writeKind(text, ts.SymbolDisplayPartKind.text); }; + return { + displayParts: function () { + var finalText = displayParts.length && displayParts[displayParts.length - 1].text; + if (length > absoluteMaximumLength && finalText && finalText !== "...") { + if (!ts.isWhiteSpaceLike(finalText.charCodeAt(finalText.length - 1))) { + displayParts.push(displayPart(" ", ts.SymbolDisplayPartKind.space)); + } + displayParts.push(displayPart("...", ts.SymbolDisplayPartKind.punctuation)); + } + return displayParts; + }, + writeKeyword: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.keyword); }, + writeOperator: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.operator); }, + writePunctuation: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.punctuation); }, + writeTrailingSemicolon: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.punctuation); }, + writeSpace: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.space); }, + writeStringLiteral: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.stringLiteral); }, + writeParameter: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.parameterName); }, + writeProperty: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.propertyName); }, + writeLiteral: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.stringLiteral); }, + writeSymbol: writeSymbol, + writeLine: writeLine, + write: unknownWrite, + writeComment: unknownWrite, + getText: function () { return ""; }, + getTextPos: function () { return 0; }, + getColumn: function () { return 0; }, + getLine: function () { return 0; }, + isAtStartOfLine: function () { return false; }, + rawWrite: ts.notImplemented, + getIndent: function () { return indent; }, + increaseIndent: function () { indent++; }, + decreaseIndent: function () { indent--; }, + clear: resetWriter, + trackSymbol: ts.noop, + reportInaccessibleThisError: ts.noop, + reportInaccessibleUniqueSymbolError: ts.noop, + reportPrivateInBaseOfClassExpression: ts.noop, + }; + function writeIndent() { + if (length > absoluteMaximumLength) + return; + if (lineStart) { + var indentString = ts.getIndentString(indent); + if (indentString) { + length += indentString.length; + displayParts.push(displayPart(indentString, ts.SymbolDisplayPartKind.space)); + } + lineStart = false; + } + } + function writeKind(text, kind) { + if (length > absoluteMaximumLength) + return; + writeIndent(); + length += text.length; + displayParts.push(displayPart(text, kind)); + } + function writeSymbol(text, symbol) { + if (length > absoluteMaximumLength) + return; + writeIndent(); + length += text.length; + displayParts.push(symbolPart(text, symbol)); + } + function writeLine() { + if (length > absoluteMaximumLength) + return; + length += 1; + displayParts.push(lineBreakPart()); + lineStart = true; + } + function resetWriter() { + displayParts = []; + lineStart = true; + indent = 0; + length = 0; + } + } + function symbolPart(text, symbol) { + return displayPart(text, displayPartKind(symbol)); + function displayPartKind(symbol) { + var flags = symbol.flags; + if (flags & 3 /* Variable */) { + return isFirstDeclarationOfSymbolParameter(symbol) ? ts.SymbolDisplayPartKind.parameterName : ts.SymbolDisplayPartKind.localName; + } + else if (flags & 4 /* Property */) { + return ts.SymbolDisplayPartKind.propertyName; + } + else if (flags & 32768 /* GetAccessor */) { + return ts.SymbolDisplayPartKind.propertyName; + } + else if (flags & 65536 /* SetAccessor */) { + return ts.SymbolDisplayPartKind.propertyName; + } + else if (flags & 8 /* EnumMember */) { + return ts.SymbolDisplayPartKind.enumMemberName; + } + else if (flags & 16 /* Function */) { + return ts.SymbolDisplayPartKind.functionName; + } + else if (flags & 32 /* Class */) { + return ts.SymbolDisplayPartKind.className; + } + else if (flags & 64 /* Interface */) { + return ts.SymbolDisplayPartKind.interfaceName; + } + else if (flags & 384 /* Enum */) { + return ts.SymbolDisplayPartKind.enumName; + } + else if (flags & 1536 /* Module */) { + return ts.SymbolDisplayPartKind.moduleName; + } + else if (flags & 8192 /* Method */) { + return ts.SymbolDisplayPartKind.methodName; + } + else if (flags & 262144 /* TypeParameter */) { + return ts.SymbolDisplayPartKind.typeParameterName; + } + else if (flags & 524288 /* TypeAlias */) { + return ts.SymbolDisplayPartKind.aliasName; + } + else if (flags & 2097152 /* Alias */) { + return ts.SymbolDisplayPartKind.aliasName; + } + return ts.SymbolDisplayPartKind.text; + } + } + ts.symbolPart = symbolPart; + function displayPart(text, kind) { + return { text: text, kind: ts.SymbolDisplayPartKind[kind] }; + } + ts.displayPart = displayPart; + function spacePart() { + return displayPart(" ", ts.SymbolDisplayPartKind.space); + } + ts.spacePart = spacePart; + function keywordPart(kind) { + return displayPart(ts.tokenToString(kind), ts.SymbolDisplayPartKind.keyword); + } + ts.keywordPart = keywordPart; + function punctuationPart(kind) { + return displayPart(ts.tokenToString(kind), ts.SymbolDisplayPartKind.punctuation); + } + ts.punctuationPart = punctuationPart; + function operatorPart(kind) { + return displayPart(ts.tokenToString(kind), ts.SymbolDisplayPartKind.operator); + } + ts.operatorPart = operatorPart; + function textOrKeywordPart(text) { + var kind = ts.stringToToken(text); + return kind === undefined + ? textPart(text) + : keywordPart(kind); + } + ts.textOrKeywordPart = textOrKeywordPart; + function textPart(text) { + return displayPart(text, ts.SymbolDisplayPartKind.text); + } + ts.textPart = textPart; + var carriageReturnLineFeed = "\r\n"; + /** + * The default is CRLF. + */ + function getNewLineOrDefaultFromHost(host, formatSettings) { + return (formatSettings && formatSettings.newLineCharacter) || + (host.getNewLine && host.getNewLine()) || + carriageReturnLineFeed; + } + ts.getNewLineOrDefaultFromHost = getNewLineOrDefaultFromHost; + function lineBreakPart() { + return displayPart("\n", ts.SymbolDisplayPartKind.lineBreak); + } + ts.lineBreakPart = lineBreakPart; + function mapToDisplayParts(writeDisplayParts) { + try { + writeDisplayParts(displayPartWriter); + return displayPartWriter.displayParts(); + } + finally { + displayPartWriter.clear(); + } + } + ts.mapToDisplayParts = mapToDisplayParts; + function typeToDisplayParts(typechecker, type, enclosingDeclaration, flags) { + if (flags === void 0) { flags = 0 /* None */; } + return mapToDisplayParts(function (writer) { + typechecker.writeType(type, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */ | 16384 /* UseAliasDefinedOutsideCurrentScope */, writer); + }); + } + ts.typeToDisplayParts = typeToDisplayParts; + function symbolToDisplayParts(typeChecker, symbol, enclosingDeclaration, meaning, flags) { + if (flags === void 0) { flags = 0 /* None */; } + return mapToDisplayParts(function (writer) { + typeChecker.writeSymbol(symbol, enclosingDeclaration, meaning, flags | 8 /* UseAliasDefinedOutsideCurrentScope */, writer); + }); + } + ts.symbolToDisplayParts = symbolToDisplayParts; + function signatureToDisplayParts(typechecker, signature, enclosingDeclaration, flags) { + if (flags === void 0) { flags = 0 /* None */; } + flags |= 16384 /* UseAliasDefinedOutsideCurrentScope */ | 1024 /* MultilineObjectLiterals */ | 32 /* WriteTypeArgumentsOfSignature */ | 8192 /* OmitParameterModifiers */; + return mapToDisplayParts(function (writer) { + typechecker.writeSignature(signature, enclosingDeclaration, flags, /*signatureKind*/ undefined, writer); + }); + } + ts.signatureToDisplayParts = signatureToDisplayParts; + function isImportOrExportSpecifierName(location) { + return !!location.parent && ts.isImportOrExportSpecifier(location.parent) && location.parent.propertyName === location; + } + ts.isImportOrExportSpecifierName = isImportOrExportSpecifierName; + /** + * Strip off existed single quotes or double quotes from a given string + * + * @return non-quoted string + */ + function stripQuotes(name) { + var length = name.length; + if (length >= 2 && name.charCodeAt(0) === name.charCodeAt(length - 1) && startsWithQuote(name)) { + return name.substring(1, length - 1); + } + return name; + } + ts.stripQuotes = stripQuotes; + function startsWithQuote(name) { + return ts.isSingleOrDoubleQuote(name.charCodeAt(0)); + } + ts.startsWithQuote = startsWithQuote; + function scriptKindIs(fileName, host) { + var scriptKinds = []; + for (var _i = 2; _i < arguments.length; _i++) { + scriptKinds[_i - 2] = arguments[_i]; + } + var scriptKind = getScriptKind(fileName, host); + return ts.some(scriptKinds, function (k) { return k === scriptKind; }); + } + ts.scriptKindIs = scriptKindIs; + function getScriptKind(fileName, host) { + // First check to see if the script kind was specified by the host. Chances are the host + // may override the default script kind for the file extension. + return ts.ensureScriptKind(fileName, host && host.getScriptKind && host.getScriptKind(fileName)); + } + ts.getScriptKind = getScriptKind; + function getUniqueSymbolId(symbol, checker) { + return ts.getSymbolId(ts.skipAlias(symbol, checker)); + } + ts.getUniqueSymbolId = getUniqueSymbolId; + function getFirstNonSpaceCharacterPosition(text, position) { + while (ts.isWhiteSpaceLike(text.charCodeAt(position))) { + position += 1; + } + return position; + } + ts.getFirstNonSpaceCharacterPosition = getFirstNonSpaceCharacterPosition; + function getPrecedingNonSpaceCharacterPosition(text, position) { + while (position > -1 && ts.isWhiteSpaceSingleLine(text.charCodeAt(position))) { + position -= 1; + } + return position + 1; + } + ts.getPrecedingNonSpaceCharacterPosition = getPrecedingNonSpaceCharacterPosition; + /** + * Creates a deep, memberwise clone of a node with no source map location. + * + * WARNING: This is an expensive operation and is only intended to be used in refactorings + * and code fixes (because those are triggered by explicit user actions). + */ + function getSynthesizedDeepClone(node, includeTrivia) { + if (includeTrivia === void 0) { includeTrivia = true; } + var clone = node && getSynthesizedDeepCloneWorker(node); + if (clone && !includeTrivia) + suppressLeadingAndTrailingTrivia(clone); + return clone; + } + ts.getSynthesizedDeepClone = getSynthesizedDeepClone; + function getSynthesizedDeepCloneWithRenames(node, includeTrivia, renameMap, checker, callback) { + if (includeTrivia === void 0) { includeTrivia = true; } + var clone; + if (ts.isIdentifier(node) && renameMap && checker) { + var symbol = checker.getSymbolAtLocation(node); + var renameInfo = symbol && renameMap.get(String(ts.getSymbolId(symbol))); + if (renameInfo) { + clone = ts.createIdentifier(renameInfo.text); + } + } + if (!clone) { + clone = getSynthesizedDeepCloneWorker(node, renameMap, checker, callback); + } + if (clone && !includeTrivia) + suppressLeadingAndTrailingTrivia(clone); + if (callback && clone) + callback(node, clone); + return clone; + } + ts.getSynthesizedDeepCloneWithRenames = getSynthesizedDeepCloneWithRenames; + function getSynthesizedDeepCloneWorker(node, renameMap, checker, callback) { + var visited = (renameMap || checker || callback) ? + ts.visitEachChild(node, wrapper, ts.nullTransformationContext) : + ts.visitEachChild(node, getSynthesizedDeepClone, ts.nullTransformationContext); + if (visited === node) { + // This only happens for leaf nodes - internal nodes always see their children change. + var clone_8 = ts.getSynthesizedClone(node); + if (ts.isStringLiteral(clone_8)) { + clone_8.textSourceNode = node; + } + else if (ts.isNumericLiteral(clone_8)) { + clone_8.numericLiteralFlags = node.numericLiteralFlags; + } + return ts.setTextRange(clone_8, node); + } + // PERF: As an optimization, rather than calling getSynthesizedClone, we'll update + // the new node created by visitEachChild with the extra changes getSynthesizedClone + // would have made. + visited.parent = undefined; + return visited; + function wrapper(node) { + return getSynthesizedDeepCloneWithRenames(node, /*includeTrivia*/ true, renameMap, checker, callback); + } + } + function getSynthesizedDeepClones(nodes, includeTrivia) { + if (includeTrivia === void 0) { includeTrivia = true; } + return nodes && ts.createNodeArray(nodes.map(function (n) { return getSynthesizedDeepClone(n, includeTrivia); }), nodes.hasTrailingComma); + } + ts.getSynthesizedDeepClones = getSynthesizedDeepClones; + /** + * Sets EmitFlags to suppress leading and trailing trivia on the node. + */ + function suppressLeadingAndTrailingTrivia(node) { + suppressLeadingTrivia(node); + suppressTrailingTrivia(node); + } + ts.suppressLeadingAndTrailingTrivia = suppressLeadingAndTrailingTrivia; + /** + * Sets EmitFlags to suppress leading trivia on the node. + */ + function suppressLeadingTrivia(node) { + addEmitFlagsRecursively(node, 512 /* NoLeadingComments */, getFirstChild); + } + ts.suppressLeadingTrivia = suppressLeadingTrivia; + /** + * Sets EmitFlags to suppress trailing trivia on the node. + */ + function suppressTrailingTrivia(node) { + addEmitFlagsRecursively(node, 1024 /* NoTrailingComments */, ts.getLastChild); + } + ts.suppressTrailingTrivia = suppressTrailingTrivia; + function addEmitFlagsRecursively(node, flag, getChild) { + ts.addEmitFlags(node, flag); + var child = getChild(node); + if (child) + addEmitFlagsRecursively(child, flag, getChild); + } + function getFirstChild(node) { + return node.forEachChild(function (child) { return child; }); + } + function getUniqueName(baseName, sourceFile) { + var nameText = baseName; + for (var i = 1; !ts.isFileLevelUniqueName(sourceFile, nameText); i++) { + nameText = baseName + "_" + i; + } + return nameText; + } + ts.getUniqueName = getUniqueName; + /** + * @return The index of the (only) reference to the extracted symbol. We want the cursor + * to be on the reference, rather than the declaration, because it's closer to where the + * user was before extracting it. + */ + function getRenameLocation(edits, renameFilename, name, preferLastLocation) { + var delta = 0; + var lastPos = -1; + for (var _i = 0, edits_1 = edits; _i < edits_1.length; _i++) { + var _a = edits_1[_i], fileName = _a.fileName, textChanges_2 = _a.textChanges; + ts.Debug.assert(fileName === renameFilename); + for (var _b = 0, textChanges_1 = textChanges_2; _b < textChanges_1.length; _b++) { + var change = textChanges_1[_b]; + var span = change.span, newText = change.newText; + var index = indexInTextChange(newText, name); + if (index !== -1) { + lastPos = span.start + delta + index; + // If the reference comes first, return immediately. + if (!preferLastLocation) { + return lastPos; + } + } + delta += newText.length - span.length; + } + } + // If the declaration comes first, return the position of the last occurrence. + ts.Debug.assert(preferLastLocation); + ts.Debug.assert(lastPos >= 0); + return lastPos; + } + ts.getRenameLocation = getRenameLocation; + function copyComments(sourceNode, targetNode, sourceFile, commentKind, hasTrailingNewLine) { + ts.forEachLeadingCommentRange(sourceFile.text, sourceNode.pos, function (pos, end, kind, htnl) { + if (kind === 3 /* MultiLineCommentTrivia */) { + // Remove leading /* + pos += 2; + // Remove trailing */ + end -= 2; + } + else { + // Remove leading // + pos += 2; + } + ts.addSyntheticLeadingComment(targetNode, commentKind || kind, sourceFile.text.slice(pos, end), hasTrailingNewLine !== undefined ? hasTrailingNewLine : htnl); + }); + } + ts.copyComments = copyComments; + function indexInTextChange(change, name) { + if (ts.startsWith(change, name)) + return 0; + // Add a " " to avoid references inside words + var idx = change.indexOf(" " + name); + if (idx === -1) + idx = change.indexOf("." + name); + if (idx === -1) + idx = change.indexOf('"' + name); + return idx === -1 ? -1 : idx + 1; + } + function getContextualTypeFromParent(node, checker) { + var parent = node.parent; + switch (parent.kind) { + case 192 /* NewExpression */: + return checker.getContextualType(parent); + case 204 /* BinaryExpression */: { + var _a = parent, left = _a.left, operatorToken = _a.operatorToken, right = _a.right; + return isEqualityOperatorKind(operatorToken.kind) + ? checker.getTypeAtLocation(node === right ? left : right) + : checker.getContextualType(node); + } + case 271 /* CaseClause */: + return parent.expression === node ? getSwitchedType(parent, checker) : undefined; + default: + return checker.getContextualType(node); + } + } + ts.getContextualTypeFromParent = getContextualTypeFromParent; + function quote(text, preferences) { + if (/^\d+$/.test(text)) { + return text; + } + var quoted = JSON.stringify(text); + switch (preferences.quotePreference) { + case undefined: + case "double": + return quoted; + case "single": + return "'" + stripQuotes(quoted).replace("'", "\\'").replace('\\"', '"') + "'"; + default: + return ts.Debug.assertNever(preferences.quotePreference); + } + } + ts.quote = quote; + function isEqualityOperatorKind(kind) { + switch (kind) { + case 35 /* EqualsEqualsEqualsToken */: + case 33 /* EqualsEqualsToken */: + case 36 /* ExclamationEqualsEqualsToken */: + case 34 /* ExclamationEqualsToken */: + return true; + default: + return false; + } + } + ts.isEqualityOperatorKind = isEqualityOperatorKind; + function isStringLiteralOrTemplate(node) { + switch (node.kind) { + case 10 /* StringLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: + case 206 /* TemplateExpression */: + case 193 /* TaggedTemplateExpression */: + return true; + default: + return false; + } + } + ts.isStringLiteralOrTemplate = isStringLiteralOrTemplate; + function hasIndexSignature(type) { + return !!type.getStringIndexType() || !!type.getNumberIndexType(); + } + ts.hasIndexSignature = hasIndexSignature; + function getSwitchedType(caseClause, checker) { + return checker.getTypeAtLocation(caseClause.parent.parent.expression); + } + ts.getSwitchedType = getSwitchedType; +})(ts || (ts = {})); +var ts; +(function (ts) { + function createClassifier() { + var scanner = ts.createScanner(6 /* Latest */, /*skipTrivia*/ false); + function getClassificationsForLine(text, lexState, syntacticClassifierAbsent) { + return convertClassificationsToResult(getEncodedLexicalClassifications(text, lexState, syntacticClassifierAbsent), text); + } + // If there is a syntactic classifier ('syntacticClassifierAbsent' is false), + // we will be more conservative in order to avoid conflicting with the syntactic classifier. + function getEncodedLexicalClassifications(text, lexState, syntacticClassifierAbsent) { + var token = 0 /* Unknown */; + var lastNonTriviaToken = 0 /* Unknown */; + // Just a stack of TemplateHeads and OpenCurlyBraces, used to perform rudimentary (inexact) + // classification on template strings. Because of the context free nature of templates, + // the only precise way to classify a template portion would be by propagating the stack across + // lines, just as we do with the end-of-line state. However, this is a burden for implementers, + // and the behavior is entirely subsumed by the syntactic classifier anyway, so we instead + // flatten any nesting when the template stack is non-empty and encode it in the end-of-line state. + // Situations in which this fails are + // 1) When template strings are nested across different lines: + // `hello ${ `world + // ` }` + // + // Where on the second line, you will get the closing of a template, + // a closing curly, and a new template. + // + // 2) When substitution expressions have curly braces and the curly brace falls on the next line: + // `hello ${ () => { + // return "world" } } ` + // + // Where on the second line, you will get the 'return' keyword, + // a string literal, and a template end consisting of '} } `'. + var templateStack = []; + var _a = getPrefixFromLexState(lexState), prefix = _a.prefix, pushTemplate = _a.pushTemplate; + text = prefix + text; + var offset = prefix.length; + if (pushTemplate) { + templateStack.push(15 /* TemplateHead */); + } + scanner.setText(text); + var endOfLineState = 0 /* None */; + var spans = []; + // We can run into an unfortunate interaction between the lexical and syntactic classifier + // when the user is typing something generic. Consider the case where the user types: + // + // Foo tokens. It's a weak heuristic, but should + // work well enough in practice. + var angleBracketStack = 0; + do { + token = scanner.scan(); + if (!ts.isTrivia(token)) { + handleToken(); + lastNonTriviaToken = token; + } + var end = scanner.getTextPos(); + pushEncodedClassification(scanner.getTokenPos(), end, offset, classFromKind(token), spans); + if (end >= text.length) { + var end_1 = getNewEndOfLineState(scanner, token, ts.lastOrUndefined(templateStack)); + if (end_1 !== undefined) { + endOfLineState = end_1; + } + } + } while (token !== 1 /* EndOfFileToken */); + function handleToken() { + switch (token) { + case 42 /* SlashToken */: + case 64 /* SlashEqualsToken */: + if (!noRegexTable[lastNonTriviaToken] && scanner.reScanSlashToken() === 13 /* RegularExpressionLiteral */) { + token = 13 /* RegularExpressionLiteral */; + } + break; + case 28 /* LessThanToken */: + if (lastNonTriviaToken === 72 /* Identifier */) { + // Could be the start of something generic. Keep track of that by bumping + // up the current count of generic contexts we may be in. + angleBracketStack++; + } + break; + case 30 /* GreaterThanToken */: + if (angleBracketStack > 0) { + // If we think we're currently in something generic, then mark that that + // generic entity is complete. + angleBracketStack--; + } + break; + case 120 /* AnyKeyword */: + case 138 /* StringKeyword */: + case 135 /* NumberKeyword */: + case 123 /* BooleanKeyword */: + case 139 /* SymbolKeyword */: + if (angleBracketStack > 0 && !syntacticClassifierAbsent) { + // If it looks like we're could be in something generic, don't classify this + // as a keyword. We may just get overwritten by the syntactic classifier, + // causing a noisy experience for the user. + token = 72 /* Identifier */; + } + break; + case 15 /* TemplateHead */: + templateStack.push(token); + break; + case 18 /* OpenBraceToken */: + // If we don't have anything on the template stack, + // then we aren't trying to keep track of a previously scanned template head. + if (templateStack.length > 0) { + templateStack.push(token); + } + break; + case 19 /* CloseBraceToken */: + // If we don't have anything on the template stack, + // then we aren't trying to keep track of a previously scanned template head. + if (templateStack.length > 0) { + var lastTemplateStackToken = ts.lastOrUndefined(templateStack); + if (lastTemplateStackToken === 15 /* TemplateHead */) { + token = scanner.reScanTemplateToken(); + // Only pop on a TemplateTail; a TemplateMiddle indicates there is more for us. + if (token === 17 /* TemplateTail */) { + templateStack.pop(); + } + else { + ts.Debug.assertEqual(token, 16 /* TemplateMiddle */, "Should have been a template middle."); + } + } + else { + ts.Debug.assertEqual(lastTemplateStackToken, 18 /* OpenBraceToken */, "Should have been an open brace"); + templateStack.pop(); + } + } + break; + default: + if (!ts.isKeyword(token)) { + break; + } + if (lastNonTriviaToken === 24 /* DotToken */) { + token = 72 /* Identifier */; + } + else if (ts.isKeyword(lastNonTriviaToken) && ts.isKeyword(token) && !canFollow(lastNonTriviaToken, token)) { + // We have two keywords in a row. Only treat the second as a keyword if + // it's a sequence that could legally occur in the language. Otherwise + // treat it as an identifier. This way, if someone writes "private var" + // we recognize that 'var' is actually an identifier here. + token = 72 /* Identifier */; + } + } + } + return { endOfLineState: endOfLineState, spans: spans }; + } + return { getClassificationsForLine: getClassificationsForLine, getEncodedLexicalClassifications: getEncodedLexicalClassifications }; + } + ts.createClassifier = createClassifier; + /// We do not have a full parser support to know when we should parse a regex or not + /// If we consider every slash token to be a regex, we could be missing cases like "1/2/3", where + /// we have a series of divide operator. this list allows us to be more accurate by ruling out + /// locations where a regexp cannot exist. + var noRegexTable = ts.arrayToNumericMap([ + 72 /* Identifier */, + 10 /* StringLiteral */, + 8 /* NumericLiteral */, + 9 /* BigIntLiteral */, + 13 /* RegularExpressionLiteral */, + 100 /* ThisKeyword */, + 44 /* PlusPlusToken */, + 45 /* MinusMinusToken */, + 21 /* CloseParenToken */, + 23 /* CloseBracketToken */, + 19 /* CloseBraceToken */, + 102 /* TrueKeyword */, + 87 /* FalseKeyword */, + ], function (token) { return token; }, function () { return true; }); + function getNewEndOfLineState(scanner, token, lastOnTemplateStack) { + switch (token) { + case 10 /* StringLiteral */: { + // Check to see if we finished up on a multiline string literal. + if (!scanner.isUnterminated()) + return undefined; + var tokenText = scanner.getTokenText(); + var lastCharIndex = tokenText.length - 1; + var numBackslashes = 0; + while (tokenText.charCodeAt(lastCharIndex - numBackslashes) === 92 /* backslash */) { + numBackslashes++; + } + // If we have an odd number of backslashes, then the multiline string is unclosed + if ((numBackslashes & 1) === 0) + return undefined; + return tokenText.charCodeAt(0) === 34 /* doubleQuote */ ? 3 /* InDoubleQuoteStringLiteral */ : 2 /* InSingleQuoteStringLiteral */; + } + case 3 /* MultiLineCommentTrivia */: + // Check to see if the multiline comment was unclosed. + return scanner.isUnterminated() ? 1 /* InMultiLineCommentTrivia */ : undefined; + default: + if (ts.isTemplateLiteralKind(token)) { + if (!scanner.isUnterminated()) { + return undefined; + } + switch (token) { + case 17 /* TemplateTail */: + return 5 /* InTemplateMiddleOrTail */; + case 14 /* NoSubstitutionTemplateLiteral */: + return 4 /* InTemplateHeadOrNoSubstitutionTemplate */; + default: + return ts.Debug.fail("Only 'NoSubstitutionTemplateLiteral's and 'TemplateTail's can be unterminated; got SyntaxKind #" + token); + } + } + return lastOnTemplateStack === 15 /* TemplateHead */ ? 6 /* InTemplateSubstitutionPosition */ : undefined; + } + } + function pushEncodedClassification(start, end, offset, classification, result) { + if (classification === 8 /* whiteSpace */) { + // Don't bother with whitespace classifications. They're not needed. + return; + } + if (start === 0 && offset > 0) { + // We're classifying the first token, and this was a case where we prepended text. + // We should consider the start of this token to be at the start of the original text. + start += offset; + } + var length = end - start; + if (length > 0) { + // All our tokens are in relation to the augmented text. Move them back to be + // relative to the original text. + result.push(start - offset, length, classification); + } + } + function convertClassificationsToResult(classifications, text) { + var entries = []; + var dense = classifications.spans; + var lastEnd = 0; + for (var i = 0; i < dense.length; i += 3) { + var start = dense[i]; + var length_5 = dense[i + 1]; + var type = dense[i + 2]; + // Make a whitespace entry between the last item and this one. + if (lastEnd >= 0) { + var whitespaceLength_1 = start - lastEnd; + if (whitespaceLength_1 > 0) { + entries.push({ length: whitespaceLength_1, classification: ts.TokenClass.Whitespace }); + } + } + entries.push({ length: length_5, classification: convertClassification(type) }); + lastEnd = start + length_5; + } + var whitespaceLength = text.length - lastEnd; + if (whitespaceLength > 0) { + entries.push({ length: whitespaceLength, classification: ts.TokenClass.Whitespace }); + } + return { entries: entries, finalLexState: classifications.endOfLineState }; + } + function convertClassification(type) { + switch (type) { + case 1 /* comment */: return ts.TokenClass.Comment; + case 3 /* keyword */: return ts.TokenClass.Keyword; + case 4 /* numericLiteral */: return ts.TokenClass.NumberLiteral; + case 25 /* bigintLiteral */: return ts.TokenClass.BigIntLiteral; + case 5 /* operator */: return ts.TokenClass.Operator; + case 6 /* stringLiteral */: return ts.TokenClass.StringLiteral; + case 8 /* whiteSpace */: return ts.TokenClass.Whitespace; + case 10 /* punctuation */: return ts.TokenClass.Punctuation; + case 2 /* identifier */: + case 11 /* className */: + case 12 /* enumName */: + case 13 /* interfaceName */: + case 14 /* moduleName */: + case 15 /* typeParameterName */: + case 16 /* typeAliasName */: + case 9 /* text */: + case 17 /* parameterName */: + return ts.TokenClass.Identifier; + default: + return undefined; // TODO: GH#18217 Debug.assertNever(type); + } + } + /** Returns true if 'keyword2' can legally follow 'keyword1' in any language construct. */ + function canFollow(keyword1, keyword2) { + if (!ts.isAccessibilityModifier(keyword1)) { + // Assume any other keyword combination is legal. + // This can be refined in the future if there are more cases we want the classifier to be better at. + return true; + } + switch (keyword2) { + case 126 /* GetKeyword */: + case 137 /* SetKeyword */: + case 124 /* ConstructorKeyword */: + case 116 /* StaticKeyword */: + return true; // Allow things like "public get", "public constructor" and "public static". + default: + return false; // Any other keyword following "public" is actually an identifier, not a real keyword. + } + } + function getPrefixFromLexState(lexState) { + // If we're in a string literal, then prepend: "\ + // (and a newline). That way when we lex we'll think we're still in a string literal. + // + // If we're in a multiline comment, then prepend: /* + // (and a newline). That way when we lex we'll think we're still in a multiline comment. + switch (lexState) { + case 3 /* InDoubleQuoteStringLiteral */: + return { prefix: "\"\\\n" }; + case 2 /* InSingleQuoteStringLiteral */: + return { prefix: "'\\\n" }; + case 1 /* InMultiLineCommentTrivia */: + return { prefix: "/*\n" }; + case 4 /* InTemplateHeadOrNoSubstitutionTemplate */: + return { prefix: "`\n" }; + case 5 /* InTemplateMiddleOrTail */: + return { prefix: "}\n", pushTemplate: true }; + case 6 /* InTemplateSubstitutionPosition */: + return { prefix: "", pushTemplate: true }; + case 0 /* None */: + return { prefix: "" }; + default: + return ts.Debug.assertNever(lexState); + } + } + function isBinaryExpressionOperatorToken(token) { + switch (token) { + case 40 /* AsteriskToken */: + case 42 /* SlashToken */: + case 43 /* PercentToken */: + case 38 /* PlusToken */: + case 39 /* MinusToken */: + case 46 /* LessThanLessThanToken */: + case 47 /* GreaterThanGreaterThanToken */: + case 48 /* GreaterThanGreaterThanGreaterThanToken */: + case 28 /* LessThanToken */: + case 30 /* GreaterThanToken */: + case 31 /* LessThanEqualsToken */: + case 32 /* GreaterThanEqualsToken */: + case 94 /* InstanceOfKeyword */: + case 93 /* InKeyword */: + case 119 /* AsKeyword */: + case 33 /* EqualsEqualsToken */: + case 34 /* ExclamationEqualsToken */: + case 35 /* EqualsEqualsEqualsToken */: + case 36 /* ExclamationEqualsEqualsToken */: + case 49 /* AmpersandToken */: + case 51 /* CaretToken */: + case 50 /* BarToken */: + case 54 /* AmpersandAmpersandToken */: + case 55 /* BarBarToken */: + case 70 /* BarEqualsToken */: + case 69 /* AmpersandEqualsToken */: + case 71 /* CaretEqualsToken */: + case 66 /* LessThanLessThanEqualsToken */: + case 67 /* GreaterThanGreaterThanEqualsToken */: + case 68 /* GreaterThanGreaterThanGreaterThanEqualsToken */: + case 60 /* PlusEqualsToken */: + case 61 /* MinusEqualsToken */: + case 62 /* AsteriskEqualsToken */: + case 64 /* SlashEqualsToken */: + case 65 /* PercentEqualsToken */: + case 59 /* EqualsToken */: + case 27 /* CommaToken */: + return true; + default: + return false; + } + } + function isPrefixUnaryExpressionOperatorToken(token) { + switch (token) { + case 38 /* PlusToken */: + case 39 /* MinusToken */: + case 53 /* TildeToken */: + case 52 /* ExclamationToken */: + case 44 /* PlusPlusToken */: + case 45 /* MinusMinusToken */: + return true; + default: + return false; + } + } + function classFromKind(token) { + if (ts.isKeyword(token)) { + return 3 /* keyword */; + } + else if (isBinaryExpressionOperatorToken(token) || isPrefixUnaryExpressionOperatorToken(token)) { + return 5 /* operator */; + } + else if (token >= 18 /* FirstPunctuation */ && token <= 71 /* LastPunctuation */) { + return 10 /* punctuation */; + } + switch (token) { + case 8 /* NumericLiteral */: + return 4 /* numericLiteral */; + case 9 /* BigIntLiteral */: + return 25 /* bigintLiteral */; + case 10 /* StringLiteral */: + return 6 /* stringLiteral */; + case 13 /* RegularExpressionLiteral */: + return 7 /* regularExpressionLiteral */; + case 7 /* ConflictMarkerTrivia */: + case 3 /* MultiLineCommentTrivia */: + case 2 /* SingleLineCommentTrivia */: + return 1 /* comment */; + case 5 /* WhitespaceTrivia */: + case 4 /* NewLineTrivia */: + return 8 /* whiteSpace */; + case 72 /* Identifier */: + default: + if (ts.isTemplateLiteralKind(token)) { + return 6 /* stringLiteral */; + } + return 2 /* identifier */; + } + } + /* @internal */ + function getSemanticClassifications(typeChecker, cancellationToken, sourceFile, classifiableNames, span) { + return convertClassificationsToSpans(getEncodedSemanticClassifications(typeChecker, cancellationToken, sourceFile, classifiableNames, span)); + } + ts.getSemanticClassifications = getSemanticClassifications; + function checkForClassificationCancellation(cancellationToken, kind) { + // We don't want to actually call back into our host on every node to find out if we've + // been canceled. That would be an enormous amount of chattyness, along with the all + // the overhead of marshalling the data to/from the host. So instead we pick a few + // reasonable node kinds to bother checking on. These node kinds represent high level + // constructs that we would expect to see commonly, but just at a far less frequent + // interval. + // + // For example, in checker.ts (around 750k) we only have around 600 of these constructs. + // That means we're calling back into the host around every 1.2k of the file we process. + // Lib.d.ts has similar numbers. + switch (kind) { + case 244 /* ModuleDeclaration */: + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + case 239 /* FunctionDeclaration */: + cancellationToken.throwIfCancellationRequested(); + } + } + /* @internal */ + function getEncodedSemanticClassifications(typeChecker, cancellationToken, sourceFile, classifiableNames, span) { + var spans = []; + sourceFile.forEachChild(function cb(node) { + // Only walk into nodes that intersect the requested span. + if (!node || !ts.textSpanIntersectsWith(span, node.pos, node.getFullWidth())) { + return; + } + checkForClassificationCancellation(cancellationToken, node.kind); + // Only bother calling into the typechecker if this is an identifier that + // could possibly resolve to a type name. This makes classification run + // in a third of the time it would normally take. + if (ts.isIdentifier(node) && !ts.nodeIsMissing(node) && classifiableNames.has(node.escapedText)) { + var symbol = typeChecker.getSymbolAtLocation(node); + var type = symbol && classifySymbol(symbol, ts.getMeaningFromLocation(node), typeChecker); + if (type) { + pushClassification(node.getStart(sourceFile), node.getEnd(), type); + } + } + node.forEachChild(cb); + }); + return { spans: spans, endOfLineState: 0 /* None */ }; + function pushClassification(start, end, type) { + spans.push(start); + spans.push(end - start); + spans.push(type); + } + } + ts.getEncodedSemanticClassifications = getEncodedSemanticClassifications; + function classifySymbol(symbol, meaningAtPosition, checker) { + var flags = symbol.getFlags(); + if ((flags & 2885600 /* Classifiable */) === 0 /* None */) { + return undefined; + } + else if (flags & 32 /* Class */) { + return 11 /* className */; + } + else if (flags & 384 /* Enum */) { + return 12 /* enumName */; + } + else if (flags & 524288 /* TypeAlias */) { + return 16 /* typeAliasName */; + } + else if (flags & 1536 /* Module */) { + // Only classify a module as such if + // - It appears in a namespace context. + // - There exists a module declaration which actually impacts the value side. + return meaningAtPosition & 4 /* Namespace */ || meaningAtPosition & 1 /* Value */ && hasValueSideModule(symbol) ? 14 /* moduleName */ : undefined; + } + else if (flags & 2097152 /* Alias */) { + return classifySymbol(checker.getAliasedSymbol(symbol), meaningAtPosition, checker); + } + else if (meaningAtPosition & 2 /* Type */) { + return flags & 64 /* Interface */ ? 13 /* interfaceName */ : flags & 262144 /* TypeParameter */ ? 15 /* typeParameterName */ : undefined; + } + else { + return undefined; + } + } + /** Returns true if there exists a module that introduces entities on the value side. */ + function hasValueSideModule(symbol) { + return ts.some(symbol.declarations, function (declaration) { + return ts.isModuleDeclaration(declaration) && ts.getModuleInstanceState(declaration) === 1 /* Instantiated */; + }); + } + function getClassificationTypeName(type) { + switch (type) { + case 1 /* comment */: return "comment" /* comment */; + case 2 /* identifier */: return "identifier" /* identifier */; + case 3 /* keyword */: return "keyword" /* keyword */; + case 4 /* numericLiteral */: return "number" /* numericLiteral */; + case 25 /* bigintLiteral */: return "bigint" /* bigintLiteral */; + case 5 /* operator */: return "operator" /* operator */; + case 6 /* stringLiteral */: return "string" /* stringLiteral */; + case 8 /* whiteSpace */: return "whitespace" /* whiteSpace */; + case 9 /* text */: return "text" /* text */; + case 10 /* punctuation */: return "punctuation" /* punctuation */; + case 11 /* className */: return "class name" /* className */; + case 12 /* enumName */: return "enum name" /* enumName */; + case 13 /* interfaceName */: return "interface name" /* interfaceName */; + case 14 /* moduleName */: return "module name" /* moduleName */; + case 15 /* typeParameterName */: return "type parameter name" /* typeParameterName */; + case 16 /* typeAliasName */: return "type alias name" /* typeAliasName */; + case 17 /* parameterName */: return "parameter name" /* parameterName */; + case 18 /* docCommentTagName */: return "doc comment tag name" /* docCommentTagName */; + case 19 /* jsxOpenTagName */: return "jsx open tag name" /* jsxOpenTagName */; + case 20 /* jsxCloseTagName */: return "jsx close tag name" /* jsxCloseTagName */; + case 21 /* jsxSelfClosingTagName */: return "jsx self closing tag name" /* jsxSelfClosingTagName */; + case 22 /* jsxAttribute */: return "jsx attribute" /* jsxAttribute */; + case 23 /* jsxText */: return "jsx text" /* jsxText */; + case 24 /* jsxAttributeStringLiteralValue */: return "jsx attribute string literal value" /* jsxAttributeStringLiteralValue */; + default: return undefined; // TODO: GH#18217 throw Debug.assertNever(type); + } + } + function convertClassificationsToSpans(classifications) { + ts.Debug.assert(classifications.spans.length % 3 === 0); + var dense = classifications.spans; + var result = []; + for (var i = 0; i < dense.length; i += 3) { + result.push({ + textSpan: ts.createTextSpan(dense[i], dense[i + 1]), + classificationType: getClassificationTypeName(dense[i + 2]) + }); + } + return result; + } + /* @internal */ + function getSyntacticClassifications(cancellationToken, sourceFile, span) { + return convertClassificationsToSpans(getEncodedSyntacticClassifications(cancellationToken, sourceFile, span)); + } + ts.getSyntacticClassifications = getSyntacticClassifications; + /* @internal */ + function getEncodedSyntacticClassifications(cancellationToken, sourceFile, span) { + var spanStart = span.start; + var spanLength = span.length; + // Make a scanner we can get trivia from. + var triviaScanner = ts.createScanner(6 /* Latest */, /*skipTrivia*/ false, sourceFile.languageVariant, sourceFile.text); + var mergeConflictScanner = ts.createScanner(6 /* Latest */, /*skipTrivia*/ false, sourceFile.languageVariant, sourceFile.text); + var result = []; + processElement(sourceFile); + return { spans: result, endOfLineState: 0 /* None */ }; + function pushClassification(start, length, type) { + result.push(start); + result.push(length); + result.push(type); + } + function classifyLeadingTriviaAndGetTokenStart(token) { + triviaScanner.setTextPos(token.pos); + while (true) { + var start = triviaScanner.getTextPos(); + // only bother scanning if we have something that could be trivia. + if (!ts.couldStartTrivia(sourceFile.text, start)) { + return start; + } + var kind = triviaScanner.scan(); + var end = triviaScanner.getTextPos(); + var width = end - start; + // The moment we get something that isn't trivia, then stop processing. + if (!ts.isTrivia(kind)) { + return start; + } + switch (kind) { + case 4 /* NewLineTrivia */: + case 5 /* WhitespaceTrivia */: + // Don't bother with newlines/whitespace. + continue; + case 2 /* SingleLineCommentTrivia */: + case 3 /* MultiLineCommentTrivia */: + // Only bother with the trivia if it at least intersects the span of interest. + classifyComment(token, kind, start, width); + // Classifying a comment might cause us to reuse the trivia scanner + // (because of jsdoc comments). So after we classify the comment make + // sure we set the scanner position back to where it needs to be. + triviaScanner.setTextPos(end); + continue; + case 7 /* ConflictMarkerTrivia */: + var text = sourceFile.text; + var ch = text.charCodeAt(start); + // for the <<<<<<< and >>>>>>> markers, we just add them in as comments + // in the classification stream. + if (ch === 60 /* lessThan */ || ch === 62 /* greaterThan */) { + pushClassification(start, width, 1 /* comment */); + continue; + } + // for the ||||||| and ======== markers, add a comment for the first line, + // and then lex all subsequent lines up until the end of the conflict marker. + ts.Debug.assert(ch === 124 /* bar */ || ch === 61 /* equals */); + classifyDisabledMergeCode(text, start, end); + break; + case 6 /* ShebangTrivia */: + // TODO: Maybe we should classify these. + break; + default: + ts.Debug.assertNever(kind); + } + } + } + function classifyComment(token, kind, start, width) { + if (kind === 3 /* MultiLineCommentTrivia */) { + // See if this is a doc comment. If so, we'll classify certain portions of it + // specially. + var docCommentAndDiagnostics = ts.parseIsolatedJSDocComment(sourceFile.text, start, width); + if (docCommentAndDiagnostics && docCommentAndDiagnostics.jsDoc) { + // TODO: This should be predicated on `token["kind"]` being compatible with `HasJSDoc["kind"]` + docCommentAndDiagnostics.jsDoc.parent = token; + classifyJSDocComment(docCommentAndDiagnostics.jsDoc); + return; + } + } + // Simple comment. Just add as is. + pushCommentRange(start, width); + } + function pushCommentRange(start, width) { + pushClassification(start, width, 1 /* comment */); + } + function classifyJSDocComment(docComment) { + var pos = docComment.pos; + if (docComment.tags) { + for (var _i = 0, _a = docComment.tags; _i < _a.length; _i++) { + var tag = _a[_i]; + // As we walk through each tag, classify the portion of text from the end of + // the last tag (or the start of the entire doc comment) as 'comment'. + if (tag.pos !== pos) { + pushCommentRange(pos, tag.pos - pos); + } + pushClassification(tag.pos, 1, 10 /* punctuation */); // "@" + pushClassification(tag.tagName.pos, tag.tagName.end - tag.tagName.pos, 18 /* docCommentTagName */); // e.g. "param" + pos = tag.tagName.end; + switch (tag.kind) { + case 299 /* JSDocParameterTag */: + processJSDocParameterTag(tag); + break; + case 303 /* JSDocTemplateTag */: + processJSDocTemplateTag(tag); + pos = tag.end; + break; + case 302 /* JSDocTypeTag */: + processElement(tag.typeExpression); + pos = tag.end; + break; + case 300 /* JSDocReturnTag */: + processElement(tag.typeExpression); + pos = tag.end; + break; + } + } + } + if (pos !== docComment.end) { + pushCommentRange(pos, docComment.end - pos); + } + return; + function processJSDocParameterTag(tag) { + if (tag.isNameFirst) { + pushCommentRange(pos, tag.name.pos - pos); + pushClassification(tag.name.pos, tag.name.end - tag.name.pos, 17 /* parameterName */); + pos = tag.name.end; + } + if (tag.typeExpression) { + pushCommentRange(pos, tag.typeExpression.pos - pos); + processElement(tag.typeExpression); + pos = tag.typeExpression.end; + } + if (!tag.isNameFirst) { + pushCommentRange(pos, tag.name.pos - pos); + pushClassification(tag.name.pos, tag.name.end - tag.name.pos, 17 /* parameterName */); + pos = tag.name.end; + } + } + } + function processJSDocTemplateTag(tag) { + for (var _i = 0, _a = tag.getChildren(); _i < _a.length; _i++) { + var child = _a[_i]; + processElement(child); + } + } + function classifyDisabledMergeCode(text, start, end) { + // Classify the line that the ||||||| or ======= marker is on as a comment. + // Then just lex all further tokens and add them to the result. + var i; + for (i = start; i < end; i++) { + if (ts.isLineBreak(text.charCodeAt(i))) { + break; + } + } + pushClassification(start, i - start, 1 /* comment */); + mergeConflictScanner.setTextPos(i); + while (mergeConflictScanner.getTextPos() < end) { + classifyDisabledCodeToken(); + } + } + function classifyDisabledCodeToken() { + var start = mergeConflictScanner.getTextPos(); + var tokenKind = mergeConflictScanner.scan(); + var end = mergeConflictScanner.getTextPos(); + var type = classifyTokenType(tokenKind); + if (type) { + pushClassification(start, end - start, type); + } + } + /** + * Returns true if node should be treated as classified and no further processing is required. + * False will mean that node is not classified and traverse routine should recurse into node contents. + */ + function tryClassifyNode(node) { + if (ts.isJSDoc(node)) { + return true; + } + if (ts.nodeIsMissing(node)) { + return true; + } + var classifiedElementName = tryClassifyJsxElementName(node); + if (!ts.isToken(node) && node.kind !== 11 /* JsxText */ && classifiedElementName === undefined) { + return false; + } + var tokenStart = node.kind === 11 /* JsxText */ ? node.pos : classifyLeadingTriviaAndGetTokenStart(node); + var tokenWidth = node.end - tokenStart; + ts.Debug.assert(tokenWidth >= 0); + if (tokenWidth > 0) { + var type = classifiedElementName || classifyTokenType(node.kind, node); + if (type) { + pushClassification(tokenStart, tokenWidth, type); + } + } + return true; + } + function tryClassifyJsxElementName(token) { + switch (token.parent && token.parent.kind) { + case 262 /* JsxOpeningElement */: + if (token.parent.tagName === token) { + return 19 /* jsxOpenTagName */; + } + break; + case 263 /* JsxClosingElement */: + if (token.parent.tagName === token) { + return 20 /* jsxCloseTagName */; + } + break; + case 261 /* JsxSelfClosingElement */: + if (token.parent.tagName === token) { + return 21 /* jsxSelfClosingTagName */; + } + break; + case 267 /* JsxAttribute */: + if (token.parent.name === token) { + return 22 /* jsxAttribute */; + } + break; + } + return undefined; + } + // for accurate classification, the actual token should be passed in. however, for + // cases like 'disabled merge code' classification, we just get the token kind and + // classify based on that instead. + function classifyTokenType(tokenKind, token) { + if (ts.isKeyword(tokenKind)) { + return 3 /* keyword */; + } + // Special case `<` and `>`: If they appear in a generic context they are punctuation, + // not operators. + if (tokenKind === 28 /* LessThanToken */ || tokenKind === 30 /* GreaterThanToken */) { + // If the node owning the token has a type argument list or type parameter list, then + // we can effectively assume that a '<' and '>' belong to those lists. + if (token && ts.getTypeArgumentOrTypeParameterList(token.parent)) { + return 10 /* punctuation */; + } + } + if (ts.isPunctuation(tokenKind)) { + if (token) { + var parent = token.parent; + if (tokenKind === 59 /* EqualsToken */) { + // the '=' in a variable declaration is special cased here. + if (parent.kind === 237 /* VariableDeclaration */ || + parent.kind === 154 /* PropertyDeclaration */ || + parent.kind === 151 /* Parameter */ || + parent.kind === 267 /* JsxAttribute */) { + return 5 /* operator */; + } + } + if (parent.kind === 204 /* BinaryExpression */ || + parent.kind === 202 /* PrefixUnaryExpression */ || + parent.kind === 203 /* PostfixUnaryExpression */ || + parent.kind === 205 /* ConditionalExpression */) { + return 5 /* operator */; + } + } + return 10 /* punctuation */; + } + else if (tokenKind === 8 /* NumericLiteral */) { + return 4 /* numericLiteral */; + } + else if (tokenKind === 9 /* BigIntLiteral */) { + return 25 /* bigintLiteral */; + } + else if (tokenKind === 10 /* StringLiteral */) { + // TODO: GH#18217 + return token.parent.kind === 267 /* JsxAttribute */ ? 24 /* jsxAttributeStringLiteralValue */ : 6 /* stringLiteral */; + } + else if (tokenKind === 13 /* RegularExpressionLiteral */) { + // TODO: we should get another classification type for these literals. + return 6 /* stringLiteral */; + } + else if (ts.isTemplateLiteralKind(tokenKind)) { + // TODO (drosen): we should *also* get another classification type for these literals. + return 6 /* stringLiteral */; + } + else if (tokenKind === 11 /* JsxText */) { + return 23 /* jsxText */; + } + else if (tokenKind === 72 /* Identifier */) { + if (token) { + switch (token.parent.kind) { + case 240 /* ClassDeclaration */: + if (token.parent.name === token) { + return 11 /* className */; + } + return; + case 150 /* TypeParameter */: + if (token.parent.name === token) { + return 15 /* typeParameterName */; + } + return; + case 241 /* InterfaceDeclaration */: + if (token.parent.name === token) { + return 13 /* interfaceName */; + } + return; + case 243 /* EnumDeclaration */: + if (token.parent.name === token) { + return 12 /* enumName */; + } + return; + case 244 /* ModuleDeclaration */: + if (token.parent.name === token) { + return 14 /* moduleName */; + } + return; + case 151 /* Parameter */: + if (token.parent.name === token) { + return ts.isThisIdentifier(token) ? 3 /* keyword */ : 17 /* parameterName */; + } + return; + } + } + return 2 /* identifier */; + } + } + function processElement(element) { + if (!element) { + return; + } + // Ignore nodes that don't intersect the original span to classify. + if (ts.decodedTextSpanIntersectsWith(spanStart, spanLength, element.pos, element.getFullWidth())) { + checkForClassificationCancellation(cancellationToken, element.kind); + for (var _i = 0, _a = element.getChildren(sourceFile); _i < _a.length; _i++) { + var child = _a[_i]; + if (!tryClassifyNode(child)) { + // Recurse into our child nodes. + processElement(child); + } + } + } + } + } + ts.getEncodedSyntacticClassifications = getEncodedSyntacticClassifications; +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var Completions; + (function (Completions) { + var StringCompletions; + (function (StringCompletions) { + function getStringLiteralCompletions(sourceFile, position, contextToken, checker, options, host, log, preferences) { + if (ts.isInReferenceComment(sourceFile, position)) { + var entries = getTripleSlashReferenceCompletion(sourceFile, position, options, host); + return entries && convertPathCompletions(entries); + } + if (ts.isInString(sourceFile, position, contextToken)) { + return !contextToken || !ts.isStringLiteralLike(contextToken) + ? undefined + : convertStringLiteralCompletions(getStringLiteralCompletionEntries(sourceFile, contextToken, position, checker, options, host), sourceFile, checker, log, preferences); + } + } + StringCompletions.getStringLiteralCompletions = getStringLiteralCompletions; + function convertStringLiteralCompletions(completion, sourceFile, checker, log, preferences) { + if (completion === undefined) { + return undefined; + } + switch (completion.kind) { + case 0 /* Paths */: + return convertPathCompletions(completion.paths); + case 1 /* Properties */: { + var entries = []; + Completions.getCompletionEntriesFromSymbols(completion.symbols, entries, sourceFile, sourceFile, checker, 6 /* ESNext */, log, 4 /* String */, preferences); // Target will not be used, so arbitrary + return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: completion.hasIndexSignature, entries: entries }; + } + case 2 /* Types */: { + var entries = completion.types.map(function (type) { return ({ name: type.value, kindModifiers: "" /* none */, kind: "string" /* string */, sortText: "0" }); }); + return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: completion.isNewIdentifier, entries: entries }; + } + default: + return ts.Debug.assertNever(completion); + } + } + function getStringLiteralCompletionDetails(name, sourceFile, position, contextToken, checker, options, host, cancellationToken) { + if (!contextToken || !ts.isStringLiteralLike(contextToken)) + return undefined; + var completions = getStringLiteralCompletionEntries(sourceFile, contextToken, position, checker, options, host); + return completions && stringLiteralCompletionDetails(name, contextToken, completions, sourceFile, checker, cancellationToken); + } + StringCompletions.getStringLiteralCompletionDetails = getStringLiteralCompletionDetails; + function stringLiteralCompletionDetails(name, location, completion, sourceFile, checker, cancellationToken) { + switch (completion.kind) { + case 0 /* Paths */: { + var match = ts.find(completion.paths, function (p) { return p.name === name; }); + return match && Completions.createCompletionDetails(name, kindModifiersFromExtension(match.extension), match.kind, [ts.textPart(name)]); + } + case 1 /* Properties */: { + var match = ts.find(completion.symbols, function (s) { return s.name === name; }); + return match && Completions.createCompletionDetailsForSymbol(match, checker, sourceFile, location, cancellationToken); + } + case 2 /* Types */: + return ts.find(completion.types, function (t) { return t.value === name; }) ? Completions.createCompletionDetails(name, "" /* none */, "type" /* typeElement */, [ts.textPart(name)]) : undefined; + default: + return ts.Debug.assertNever(completion); + } + } + function convertPathCompletions(pathCompletions) { + var isGlobalCompletion = false; // We don't want the editor to offer any other completions, such as snippets, inside a comment. + var isNewIdentifierLocation = true; // The user may type in a path that doesn't yet exist, creating a "new identifier" with respect to the collection of identifiers the server is aware of. + var entries = pathCompletions.map(function (_a) { + var name = _a.name, kind = _a.kind, span = _a.span, extension = _a.extension; + return ({ name: name, kind: kind, kindModifiers: kindModifiersFromExtension(extension), sortText: "0", replacementSpan: span }); + }); + return { isGlobalCompletion: isGlobalCompletion, isMemberCompletion: false, isNewIdentifierLocation: isNewIdentifierLocation, entries: entries }; + } + function kindModifiersFromExtension(extension) { + switch (extension) { + case ".d.ts" /* Dts */: return ".d.ts" /* dtsModifier */; + case ".js" /* Js */: return ".js" /* jsModifier */; + case ".json" /* Json */: return ".json" /* jsonModifier */; + case ".jsx" /* Jsx */: return ".jsx" /* jsxModifier */; + case ".ts" /* Ts */: return ".ts" /* tsModifier */; + case ".tsx" /* Tsx */: return ".tsx" /* tsxModifier */; + case undefined: return "" /* none */; + default: + return ts.Debug.assertNever(extension); + } + } + var StringLiteralCompletionKind; + (function (StringLiteralCompletionKind) { + StringLiteralCompletionKind[StringLiteralCompletionKind["Paths"] = 0] = "Paths"; + StringLiteralCompletionKind[StringLiteralCompletionKind["Properties"] = 1] = "Properties"; + StringLiteralCompletionKind[StringLiteralCompletionKind["Types"] = 2] = "Types"; + })(StringLiteralCompletionKind || (StringLiteralCompletionKind = {})); + function getStringLiteralCompletionEntries(sourceFile, node, position, typeChecker, compilerOptions, host) { + var parent = node.parent; + switch (parent.kind) { + case 182 /* LiteralType */: + switch (parent.parent.kind) { + case 164 /* TypeReference */: + return { kind: 2 /* Types */, types: getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(parent)), isNewIdentifier: false }; + case 180 /* IndexedAccessType */: + // Get all apparent property names + // i.e. interface Foo { + // foo: string; + // bar: string; + // } + // let x: Foo["/*completion position*/"] + return stringLiteralCompletionsFromProperties(typeChecker.getTypeFromTypeNode(parent.parent.objectType)); + case 183 /* ImportType */: + return { kind: 0 /* Paths */, paths: getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker) }; + case 173 /* UnionType */: { + if (!ts.isTypeReferenceNode(parent.parent.parent)) + return undefined; + var alreadyUsedTypes_1 = getAlreadyUsedTypesInStringLiteralUnion(parent.parent, parent); + var types = getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(parent.parent)).filter(function (t) { return !ts.contains(alreadyUsedTypes_1, t.value); }); + return { kind: 2 /* Types */, types: types, isNewIdentifier: false }; + } + default: + return undefined; + } + case 275 /* PropertyAssignment */: + if (ts.isObjectLiteralExpression(parent.parent) && parent.name === node) { + // Get quoted name of properties of the object literal expression + // i.e. interface ConfigFiles { + // 'jspm:dev': string + // } + // let files: ConfigFiles = { + // '/*completion position*/' + // } + // + // function foo(c: ConfigFiles) {} + // foo({ + // '/*completion position*/' + // }); + return stringLiteralCompletionsFromProperties(typeChecker.getContextualType(parent.parent)); + } + return fromContextualType(); + case 190 /* ElementAccessExpression */: { + var _a = parent, expression = _a.expression, argumentExpression = _a.argumentExpression; + if (node === argumentExpression) { + // Get all names of properties on the expression + // i.e. interface A { + // 'prop1': string + // } + // let a: A; + // a['/*completion position*/'] + return stringLiteralCompletionsFromProperties(typeChecker.getTypeAtLocation(expression)); + } + return undefined; + } + case 191 /* CallExpression */: + case 192 /* NewExpression */: + if (!ts.isRequireCall(parent, /*checkArgumentIsStringLiteralLike*/ false) && !ts.isImportCall(parent)) { + var argumentInfo = ts.SignatureHelp.getArgumentInfoForCompletions(node, position, sourceFile); + // Get string literal completions from specialized signatures of the target + // i.e. declare function f(a: 'A'); + // f("/*completion position*/") + return argumentInfo ? getStringLiteralCompletionsFromSignature(argumentInfo, typeChecker) : fromContextualType(); + } + // falls through (is `require("")` or `import("")`) + case 249 /* ImportDeclaration */: + case 255 /* ExportDeclaration */: + case 259 /* ExternalModuleReference */: + // Get all known external module names or complete a path to a module + // i.e. import * as ns from "/*completion position*/"; + // var y = import("/*completion position*/"); + // import x = require("/*completion position*/"); + // var y = require("/*completion position*/"); + // export * from "/*completion position*/"; + return { kind: 0 /* Paths */, paths: getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker) }; + default: + return fromContextualType(); + } + function fromContextualType() { + // Get completion for string literal from string literal type + // i.e. var x: "hi" | "hello" = "/*completion position*/" + return { kind: 2 /* Types */, types: getStringLiteralTypes(ts.getContextualTypeFromParent(node, typeChecker)), isNewIdentifier: false }; + } + } + function getAlreadyUsedTypesInStringLiteralUnion(union, current) { + return ts.mapDefined(union.types, function (type) { + return type !== current && ts.isLiteralTypeNode(type) && ts.isStringLiteral(type.literal) ? type.literal.text : undefined; + }); + } + function getStringLiteralCompletionsFromSignature(argumentInfo, checker) { + var isNewIdentifier = false; + var uniques = ts.createMap(); + var candidates = []; + checker.getResolvedSignature(argumentInfo.invocation, candidates, argumentInfo.argumentCount); + var types = ts.flatMap(candidates, function (candidate) { + if (!candidate.hasRestParameter && argumentInfo.argumentCount > candidate.parameters.length) + return; + var type = checker.getParameterType(candidate, argumentInfo.argumentIndex); + isNewIdentifier = isNewIdentifier || !!(type.flags & 4 /* String */); + return getStringLiteralTypes(type, uniques); + }); + return { kind: 2 /* Types */, types: types, isNewIdentifier: isNewIdentifier }; + } + function stringLiteralCompletionsFromProperties(type) { + return type && { kind: 1 /* Properties */, symbols: type.getApparentProperties(), hasIndexSignature: ts.hasIndexSignature(type) }; + } + function getStringLiteralTypes(type, uniques) { + if (uniques === void 0) { uniques = ts.createMap(); } + if (!type) + return ts.emptyArray; + type = ts.skipConstraint(type); + return type.isUnion() + ? ts.flatMap(type.types, function (t) { return getStringLiteralTypes(t, uniques); }) + : type.isStringLiteral() && !(type.flags & 1024 /* EnumLiteral */) && ts.addToSeen(uniques, type.value) + ? [type] + : ts.emptyArray; + } + function nameAndKind(name, kind, extension) { + return { name: name, kind: kind, extension: extension }; + } + function directoryResult(name) { + return nameAndKind(name, "directory" /* directory */, /*extension*/ undefined); + } + function addReplacementSpans(text, textStart, names) { + var span = getDirectoryFragmentTextSpan(text, textStart); + return names.map(function (_a) { + var name = _a.name, kind = _a.kind, extension = _a.extension; + return ({ name: name, kind: kind, extension: extension, span: span }); + }); + } + function getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker) { + return addReplacementSpans(node.text, node.getStart(sourceFile) + 1, getStringLiteralCompletionsFromModuleNamesWorker(sourceFile, node, compilerOptions, host, typeChecker)); + } + function getStringLiteralCompletionsFromModuleNamesWorker(sourceFile, node, compilerOptions, host, typeChecker) { + var literalValue = ts.normalizeSlashes(node.text); + var scriptPath = sourceFile.path; + var scriptDirectory = ts.getDirectoryPath(scriptPath); + return isPathRelativeToScript(literalValue) || !compilerOptions.baseUrl && (ts.isRootedDiskPath(literalValue) || ts.isUrl(literalValue)) + ? getCompletionEntriesForRelativeModules(literalValue, scriptDirectory, compilerOptions, host, scriptPath) + : getCompletionEntriesForNonRelativeModules(literalValue, scriptDirectory, compilerOptions, host, typeChecker); + } + function getExtensionOptions(compilerOptions, includeExtensions) { + if (includeExtensions === void 0) { includeExtensions = false; } + return { extensions: getSupportedExtensionsForModuleResolution(compilerOptions), includeExtensions: includeExtensions }; + } + function getCompletionEntriesForRelativeModules(literalValue, scriptDirectory, compilerOptions, host, scriptPath) { + var extensionOptions = getExtensionOptions(compilerOptions); + if (compilerOptions.rootDirs) { + return getCompletionEntriesForDirectoryFragmentWithRootDirs(compilerOptions.rootDirs, literalValue, scriptDirectory, extensionOptions, compilerOptions, host, scriptPath); + } + else { + return getCompletionEntriesForDirectoryFragment(literalValue, scriptDirectory, extensionOptions, host, scriptPath); + } + } + function getSupportedExtensionsForModuleResolution(compilerOptions) { + var extensions = ts.getSupportedExtensions(compilerOptions); + return compilerOptions.resolveJsonModule && ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs ? + extensions.concat(".json" /* Json */) : + extensions; + } + /** + * Takes a script path and returns paths for all potential folders that could be merged with its + * containing folder via the "rootDirs" compiler option + */ + function getBaseDirectoriesFromRootDirs(rootDirs, basePath, scriptDirectory, ignoreCase) { + // Make all paths absolute/normalized if they are not already + rootDirs = rootDirs.map(function (rootDirectory) { return ts.normalizePath(ts.isRootedDiskPath(rootDirectory) ? rootDirectory : ts.combinePaths(basePath, rootDirectory)); }); + // Determine the path to the directory containing the script relative to the root directory it is contained within + var relativeDirectory = ts.firstDefined(rootDirs, function (rootDirectory) { + return ts.containsPath(rootDirectory, scriptDirectory, basePath, ignoreCase) ? scriptDirectory.substr(rootDirectory.length) : undefined; + }); // TODO: GH#18217 + // Now find a path for each potential directory that is to be merged with the one containing the script + return ts.deduplicate(rootDirs.map(function (rootDirectory) { return ts.combinePaths(rootDirectory, relativeDirectory); }).concat([scriptDirectory]), ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive); + } + function getCompletionEntriesForDirectoryFragmentWithRootDirs(rootDirs, fragment, scriptDirectory, extensionOptions, compilerOptions, host, exclude) { + var basePath = compilerOptions.project || host.getCurrentDirectory(); + var ignoreCase = !(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames()); + var baseDirectories = getBaseDirectoriesFromRootDirs(rootDirs, basePath, scriptDirectory, ignoreCase); + return ts.flatMap(baseDirectories, function (baseDirectory) { return getCompletionEntriesForDirectoryFragment(fragment, baseDirectory, extensionOptions, host, exclude); }); + } + /** + * Given a path ending at a directory, gets the completions for the path, and filters for those entries containing the basename. + */ + function getCompletionEntriesForDirectoryFragment(fragment, scriptPath, _a, host, exclude, result) { + var extensions = _a.extensions, includeExtensions = _a.includeExtensions; + if (result === void 0) { result = []; } + if (fragment === undefined) { + fragment = ""; + } + fragment = ts.normalizeSlashes(fragment); + /** + * Remove the basename from the path. Note that we don't use the basename to filter completions; + * the client is responsible for refining completions. + */ + if (!ts.hasTrailingDirectorySeparator(fragment)) { + fragment = ts.getDirectoryPath(fragment); + } + if (fragment === "") { + fragment = "." + ts.directorySeparator; + } + fragment = ts.ensureTrailingDirectorySeparator(fragment); + // const absolutePath = normalizeAndPreserveTrailingSlash(isRootedDiskPath(fragment) ? fragment : combinePaths(scriptPath, fragment)); // TODO(rbuckton): should use resolvePaths + var absolutePath = ts.resolvePath(scriptPath, fragment); + var baseDirectory = ts.hasTrailingDirectorySeparator(absolutePath) ? absolutePath : ts.getDirectoryPath(absolutePath); + var ignoreCase = !(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames()); + if (!tryDirectoryExists(host, baseDirectory)) + return result; + // Enumerate the available files if possible + var files = tryReadDirectory(host, baseDirectory, extensions, /*exclude*/ undefined, /*include*/ ["./*"]); + if (files) { + /** + * Multiple file entries might map to the same truncated name once we remove extensions + * (happens iff includeExtensions === false)so we use a set-like data structure. Eg: + * + * both foo.ts and foo.tsx become foo + */ + var foundFiles = ts.createMap(); // maps file to its extension + for (var _i = 0, files_3 = files; _i < files_3.length; _i++) { + var filePath = files_3[_i]; + filePath = ts.normalizePath(filePath); + if (exclude && ts.comparePaths(filePath, exclude, scriptPath, ignoreCase) === 0 /* EqualTo */) { + continue; + } + var foundFileName = includeExtensions || ts.fileExtensionIs(filePath, ".json" /* Json */) ? ts.getBaseFileName(filePath) : ts.removeFileExtension(ts.getBaseFileName(filePath)); + foundFiles.set(foundFileName, ts.tryGetExtensionFromPath(filePath)); + } + foundFiles.forEach(function (ext, foundFile) { + result.push(nameAndKind(foundFile, "script" /* scriptElement */, ext)); + }); + } + // If possible, get folder completion as well + var directories = tryGetDirectories(host, baseDirectory); + if (directories) { + for (var _b = 0, directories_1 = directories; _b < directories_1.length; _b++) { + var directory = directories_1[_b]; + var directoryName = ts.getBaseFileName(ts.normalizePath(directory)); + if (directoryName !== "@types") { + result.push(directoryResult(directoryName)); + } + } + } + // check for a version redirect + var packageJsonPath = findPackageJson(baseDirectory, host); + if (packageJsonPath) { + var packageJson = ts.readJson(packageJsonPath, host); + var typesVersions = packageJson.typesVersions; + if (typeof typesVersions === "object") { + var versionResult = ts.getPackageJsonTypesVersionsPaths(typesVersions); + var versionPaths = versionResult && versionResult.paths; + var rest = absolutePath.slice(ts.ensureTrailingDirectorySeparator(baseDirectory).length); + if (versionPaths) { + addCompletionEntriesFromPaths(result, rest, baseDirectory, extensions, versionPaths, host); + } + } + } + return result; + } + function addCompletionEntriesFromPaths(result, fragment, baseDirectory, fileExtensions, paths, host) { + for (var path in paths) { + if (!ts.hasProperty(paths, path)) + continue; + var patterns = paths[path]; + if (patterns) { + var _loop_10 = function (name, kind, extension) { + // Path mappings may provide a duplicate way to get to something we've already added, so don't add again. + if (!result.some(function (entry) { return entry.name === name; })) { + result.push(nameAndKind(name, kind, extension)); + } + }; + for (var _i = 0, _a = getCompletionsForPathMapping(path, patterns, fragment, baseDirectory, fileExtensions, host); _i < _a.length; _i++) { + var _b = _a[_i], name = _b.name, kind = _b.kind, extension = _b.extension; + _loop_10(name, kind, extension); + } + } + } + } + /** + * Check all of the declared modules and those in node modules. Possible sources of modules: + * Modules that are found by the type checker + * Modules found relative to "baseUrl" compliler options (including patterns from "paths" compiler option) + * Modules from node_modules (i.e. those listed in package.json) + * This includes all files that are found in node_modules/moduleName/ with acceptable file extensions + */ + function getCompletionEntriesForNonRelativeModules(fragment, scriptPath, compilerOptions, host, typeChecker) { + var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths; + var result = []; + var extensionOptions = getExtensionOptions(compilerOptions); + if (baseUrl) { + var projectDir = compilerOptions.project || host.getCurrentDirectory(); + var absolute = ts.normalizePath(ts.combinePaths(projectDir, baseUrl)); + getCompletionEntriesForDirectoryFragment(fragment, absolute, extensionOptions, host, /*exclude*/ undefined, result); + if (paths) { + addCompletionEntriesFromPaths(result, fragment, absolute, extensionOptions.extensions, paths, host); + } + } + var fragmentDirectory = getFragmentDirectory(fragment); + for (var _i = 0, _a = getAmbientModuleCompletions(fragment, fragmentDirectory, typeChecker); _i < _a.length; _i++) { + var ambientName = _a[_i]; + result.push(nameAndKind(ambientName, "external module name" /* externalModuleName */, /*extension*/ undefined)); + } + getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, fragmentDirectory, extensionOptions, result); + if (ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs) { + // If looking for a global package name, don't just include everything in `node_modules` because that includes dependencies' own dependencies. + // (But do if we didn't find anything, e.g. 'package.json' missing.) + var foundGlobal = false; + if (fragmentDirectory === undefined) { + var _loop_11 = function (moduleName) { + if (!result.some(function (entry) { return entry.name === moduleName; })) { + foundGlobal = true; + result.push(nameAndKind(moduleName, "external module name" /* externalModuleName */, /*extension*/ undefined)); + } + }; + for (var _b = 0, _c = enumerateNodeModulesVisibleToScript(host, scriptPath); _b < _c.length; _b++) { + var moduleName = _c[_b]; + _loop_11(moduleName); + } + } + if (!foundGlobal) { + ts.forEachAncestorDirectory(scriptPath, function (ancestor) { + var nodeModules = ts.combinePaths(ancestor, "node_modules"); + if (tryDirectoryExists(host, nodeModules)) { + getCompletionEntriesForDirectoryFragment(fragment, nodeModules, extensionOptions, host, /*exclude*/ undefined, result); + } + }); + } + } + return result; + } + function getFragmentDirectory(fragment) { + return containsSlash(fragment) ? ts.hasTrailingDirectorySeparator(fragment) ? fragment : ts.getDirectoryPath(fragment) : undefined; + } + function getCompletionsForPathMapping(path, patterns, fragment, baseUrl, fileExtensions, host) { + if (!ts.endsWith(path, "*")) { + // For a path mapping "foo": ["/x/y/z.ts"], add "foo" itself as a completion. + return !ts.stringContains(path, "*") ? justPathMappingName(path) : ts.emptyArray; + } + var pathPrefix = path.slice(0, path.length - 1); + var remainingFragment = ts.tryRemovePrefix(fragment, pathPrefix); + return remainingFragment === undefined ? justPathMappingName(pathPrefix) : ts.flatMap(patterns, function (pattern) { + return getModulesForPathsPattern(remainingFragment, baseUrl, pattern, fileExtensions, host); + }); + function justPathMappingName(name) { + return ts.startsWith(name, fragment) ? [directoryResult(name)] : ts.emptyArray; + } + } + function getModulesForPathsPattern(fragment, baseUrl, pattern, fileExtensions, host) { + if (!host.readDirectory) { + return undefined; + } + var parsed = ts.hasZeroOrOneAsteriskCharacter(pattern) ? ts.tryParsePattern(pattern) : undefined; + if (!parsed) { + return undefined; + } + // The prefix has two effective parts: the directory path and the base component after the filepath that is not a + // full directory component. For example: directory/path/of/prefix/base* + var normalizedPrefix = ts.resolvePath(parsed.prefix); + var normalizedPrefixDirectory = ts.hasTrailingDirectorySeparator(parsed.prefix) ? normalizedPrefix : ts.getDirectoryPath(normalizedPrefix); + var normalizedPrefixBase = ts.hasTrailingDirectorySeparator(parsed.prefix) ? "" : ts.getBaseFileName(normalizedPrefix); + var fragmentHasPath = containsSlash(fragment); + var fragmentDirectory = fragmentHasPath ? ts.hasTrailingDirectorySeparator(fragment) ? fragment : ts.getDirectoryPath(fragment) : undefined; + // Try and expand the prefix to include any path from the fragment so that we can limit the readDirectory call + var expandedPrefixDirectory = fragmentHasPath ? ts.combinePaths(normalizedPrefixDirectory, normalizedPrefixBase + fragmentDirectory) : normalizedPrefixDirectory; + var normalizedSuffix = ts.normalizePath(parsed.suffix); + // Need to normalize after combining: If we combinePaths("a", "../b"), we want "b" and not "a/../b". + var baseDirectory = ts.normalizePath(ts.combinePaths(baseUrl, expandedPrefixDirectory)); + var completePrefix = fragmentHasPath ? baseDirectory : ts.ensureTrailingDirectorySeparator(baseDirectory) + normalizedPrefixBase; + // If we have a suffix, then we need to read the directory all the way down. We could create a glob + // that encodes the suffix, but we would have to escape the character "?" which readDirectory + // doesn't support. For now, this is safer but slower + var includeGlob = normalizedSuffix ? "**/*" : "./*"; + var matches = ts.mapDefined(tryReadDirectory(host, baseDirectory, fileExtensions, /*exclude*/ undefined, [includeGlob]), function (match) { + var extension = ts.tryGetExtensionFromPath(match); + var name = trimPrefixAndSuffix(match); + return name === undefined ? undefined : nameAndKind(ts.removeFileExtension(name), "script" /* scriptElement */, extension); + }); + var directories = ts.mapDefined(tryGetDirectories(host, baseDirectory).map(function (d) { return ts.combinePaths(baseDirectory, d); }), function (dir) { + var name = trimPrefixAndSuffix(dir); + return name === undefined ? undefined : directoryResult(name); + }); + return matches.concat(directories); + function trimPrefixAndSuffix(path) { + var inner = withoutStartAndEnd(ts.normalizePath(path), completePrefix, normalizedSuffix); + return inner === undefined ? undefined : removeLeadingDirectorySeparator(inner); + } + } + function withoutStartAndEnd(s, start, end) { + return ts.startsWith(s, start) && ts.endsWith(s, end) ? s.slice(start.length, s.length - end.length) : undefined; + } + function removeLeadingDirectorySeparator(path) { + return path[0] === ts.directorySeparator ? path.slice(1) : path; + } + function getAmbientModuleCompletions(fragment, fragmentDirectory, checker) { + // Get modules that the type checker picked up + var ambientModules = checker.getAmbientModules().map(function (sym) { return ts.stripQuotes(sym.name); }); + var nonRelativeModuleNames = ambientModules.filter(function (moduleName) { return ts.startsWith(moduleName, fragment); }); + // Nested modules of the form "module-name/sub" need to be adjusted to only return the string + // after the last '/' that appears in the fragment because that's where the replacement span + // starts + if (fragmentDirectory !== undefined) { + var moduleNameWithSeparator_1 = ts.ensureTrailingDirectorySeparator(fragmentDirectory); + return nonRelativeModuleNames.map(function (nonRelativeModuleName) { return ts.removePrefix(nonRelativeModuleName, moduleNameWithSeparator_1); }); + } + return nonRelativeModuleNames; + } + function getTripleSlashReferenceCompletion(sourceFile, position, compilerOptions, host) { + var token = ts.getTokenAtPosition(sourceFile, position); + var commentRanges = ts.getLeadingCommentRanges(sourceFile.text, token.pos); + var range = commentRanges && ts.find(commentRanges, function (commentRange) { return position >= commentRange.pos && position <= commentRange.end; }); + if (!range) { + return undefined; + } + var text = sourceFile.text.slice(range.pos, position); + var match = tripleSlashDirectiveFragmentRegex.exec(text); + if (!match) { + return undefined; + } + var prefix = match[1], kind = match[2], toComplete = match[3]; + var scriptPath = ts.getDirectoryPath(sourceFile.path); + var names = kind === "path" ? getCompletionEntriesForDirectoryFragment(toComplete, scriptPath, getExtensionOptions(compilerOptions, /*includeExtensions*/ true), host, sourceFile.path) + : kind === "types" ? getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, getFragmentDirectory(toComplete), getExtensionOptions(compilerOptions)) + : ts.Debug.fail(); + return addReplacementSpans(toComplete, range.pos + prefix.length, names); + } + function getCompletionEntriesFromTypings(host, options, scriptPath, fragmentDirectory, extensionOptions, result) { + if (result === void 0) { result = []; } + // Check for typings specified in compiler options + var seen = ts.createMap(); + var typeRoots = tryAndIgnoreErrors(function () { return ts.getEffectiveTypeRoots(options, host); }) || ts.emptyArray; + for (var _i = 0, typeRoots_2 = typeRoots; _i < typeRoots_2.length; _i++) { + var root = typeRoots_2[_i]; + getCompletionEntriesFromDirectories(root); + } + // Also get all @types typings installed in visible node_modules directories + for (var _a = 0, _b = findPackageJsons(scriptPath, host); _a < _b.length; _a++) { + var packageJson = _b[_a]; + var typesDir = ts.combinePaths(ts.getDirectoryPath(packageJson), "node_modules/@types"); + getCompletionEntriesFromDirectories(typesDir); + } + return result; + function getCompletionEntriesFromDirectories(directory) { + if (!tryDirectoryExists(host, directory)) + return; + for (var _i = 0, _a = tryGetDirectories(host, directory); _i < _a.length; _i++) { + var typeDirectoryName = _a[_i]; + var packageName = ts.unmangleScopedPackageName(typeDirectoryName); + if (options.types && !ts.contains(options.types, packageName)) + continue; + if (fragmentDirectory === undefined) { + if (!seen.has(packageName)) { + result.push(nameAndKind(packageName, "external module name" /* externalModuleName */, /*extension*/ undefined)); + seen.set(packageName, true); + } + } + else { + var baseDirectory = ts.combinePaths(directory, typeDirectoryName); + var remainingFragment = ts.tryRemoveDirectoryPrefix(fragmentDirectory, packageName, ts.hostGetCanonicalFileName(host)); + if (remainingFragment !== undefined) { + getCompletionEntriesForDirectoryFragment(remainingFragment, baseDirectory, extensionOptions, host, /*exclude*/ undefined, result); + } + } + } + } + } + function findPackageJsons(directory, host) { + var paths = []; + ts.forEachAncestorDirectory(directory, function (ancestor) { + var currentConfigPath = ts.findConfigFile(ancestor, function (f) { return tryFileExists(host, f); }, "package.json"); + if (!currentConfigPath) { + return true; // break out + } + paths.push(currentConfigPath); + }); + return paths; + } + function findPackageJson(directory, host) { + var packageJson; + ts.forEachAncestorDirectory(directory, function (ancestor) { + if (ancestor === "node_modules") + return true; + packageJson = ts.findConfigFile(ancestor, function (f) { return tryFileExists(host, f); }, "package.json"); + if (packageJson) { + return true; // break out + } + }); + return packageJson; + } + function enumerateNodeModulesVisibleToScript(host, scriptPath) { + if (!host.readFile || !host.fileExists) + return ts.emptyArray; + var result = []; + for (var _i = 0, _a = findPackageJsons(scriptPath, host); _i < _a.length; _i++) { + var packageJson = _a[_i]; + var contents = ts.readJson(packageJson, host); // Cast to assert that readFile is defined + // Provide completions for all non @types dependencies + for (var _b = 0, nodeModulesDependencyKeys_1 = nodeModulesDependencyKeys; _b < nodeModulesDependencyKeys_1.length; _b++) { + var key = nodeModulesDependencyKeys_1[_b]; + var dependencies = contents[key]; + if (!dependencies) + continue; + for (var dep in dependencies) { + if (dependencies.hasOwnProperty(dep) && !ts.startsWith(dep, "@types/")) { + result.push(dep); + } + } + } + } + return result; + } + // Replace everything after the last directory separator that appears + function getDirectoryFragmentTextSpan(text, textStart) { + var index = Math.max(text.lastIndexOf(ts.directorySeparator), text.lastIndexOf("\\")); + var offset = index !== -1 ? index + 1 : 0; + // If the range is an identifier, span is unnecessary. + var length = text.length - offset; + return length === 0 || ts.isIdentifierText(text.substr(offset, length), 6 /* ESNext */) ? undefined : ts.createTextSpan(textStart + offset, length); + } + // Returns true if the path is explicitly relative to the script (i.e. relative to . or ..) + function isPathRelativeToScript(path) { + if (path && path.length >= 2 && path.charCodeAt(0) === 46 /* dot */) { + var slashIndex = path.length >= 3 && path.charCodeAt(1) === 46 /* dot */ ? 2 : 1; + var slashCharCode = path.charCodeAt(slashIndex); + return slashCharCode === 47 /* slash */ || slashCharCode === 92 /* backslash */; + } + return false; + } + /** + * Matches a triple slash reference directive with an incomplete string literal for its path. Used + * to determine if the caret is currently within the string literal and capture the literal fragment + * for completions. + * For example, this matches + * + * /// " with type any + // And at `
      ` (with a closing `>`), the completion list will contain "div". + var tagName = location.parent.parent.openingElement.tagName; + var hasClosingAngleBracket = !!ts.findChildOfKind(location.parent, 30 /* GreaterThanToken */, sourceFile); + var entry = { + name: tagName.getFullText(sourceFile) + (hasClosingAngleBracket ? "" : ">"), + kind: "class" /* classElement */, + kindModifiers: undefined, + sortText: "0", + }; + return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: false, entries: [entry] }; + } + var entries = []; + if (isUncheckedFile(sourceFile, compilerOptions)) { + var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, preferences, propertyAccessToConvert, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap); + getJSCompletionEntries(sourceFile, location.pos, uniqueNames, compilerOptions.target, entries); // TODO: GH#18217 + } + else { + if ((!symbols || symbols.length === 0) && keywordFilters === 0 /* None */) { + return undefined; + } + getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, preferences, propertyAccessToConvert, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap); + } + if (keywordFilters !== 0 /* None */) { + var entryNames = ts.arrayToSet(entries, function (e) { return e.name; }); + for (var _i = 0, _a = getKeywordCompletions(keywordFilters); _i < _a.length; _i++) { + var keywordEntry = _a[_i]; + if (!entryNames.has(keywordEntry.name)) { + entries.push(keywordEntry); + } + } + } + for (var _b = 0, literals_1 = literals; _b < literals_1.length; _b++) { + var literal = literals_1[_b]; + entries.push(createCompletionEntryForLiteral(literal)); + } + return { isGlobalCompletion: isInSnippetScope, isMemberCompletion: isMemberCompletionKind(completionKind), isNewIdentifierLocation: isNewIdentifierLocation, entries: entries }; + } + function isUncheckedFile(sourceFile, compilerOptions) { + return ts.isSourceFileJS(sourceFile) && !ts.isCheckJsEnabledForFile(sourceFile, compilerOptions); + } + function isMemberCompletionKind(kind) { + switch (kind) { + case 0 /* ObjectPropertyDeclaration */: + case 3 /* MemberLike */: + case 2 /* PropertyAccess */: + return true; + default: + return false; + } + } + function getJSCompletionEntries(sourceFile, position, uniqueNames, target, entries) { + ts.getNameTable(sourceFile).forEach(function (pos, name) { + // Skip identifiers produced only from the current location + if (pos === position) { + return; + } + var realName = ts.unescapeLeadingUnderscores(name); + if (ts.addToSeen(uniqueNames, realName) && ts.isIdentifierText(realName, target)) { + entries.push({ + name: realName, + kind: "warning" /* warning */, + kindModifiers: "", + sortText: "1" + }); + } + }); + } + var completionNameForLiteral = function (literal) { + return typeof literal === "object" ? ts.pseudoBigIntToString(literal) + "n" : JSON.stringify(literal); + }; + function createCompletionEntryForLiteral(literal) { + return { name: completionNameForLiteral(literal), kind: "string" /* string */, kindModifiers: "" /* none */, sortText: "0" }; + } + function createCompletionEntry(symbol, location, sourceFile, typeChecker, target, kind, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, preferences) { + var info = getCompletionEntryDisplayNameForSymbol(symbol, target, origin, kind); + if (!info) { + return undefined; + } + var name = info.name, needsConvertPropertyAccess = info.needsConvertPropertyAccess; + var insertText; + var replacementSpan; + if (origin && origin.kind === 0 /* ThisType */) { + insertText = needsConvertPropertyAccess ? "this[" + ts.quote(name, preferences) + "]" : "this." + name; + } + // We should only have needsConvertPropertyAccess if there's a property access to convert. But see #21790. + // Somehow there was a global with a non-identifier name. Hopefully someone will complain about getting a "foo bar" global completion and provide a repro. + else if ((origin && originIsSymbolMember(origin) || needsConvertPropertyAccess) && propertyAccessToConvert) { + insertText = needsConvertPropertyAccess ? "[" + ts.quote(name, preferences) + "]" : "[" + name + "]"; + var dot = ts.findChildOfKind(propertyAccessToConvert, 24 /* DotToken */, sourceFile); + // If the text after the '.' starts with this name, write over it. Else, add new text. + var end = ts.startsWith(name, propertyAccessToConvert.name.text) ? propertyAccessToConvert.name.end : dot.end; + replacementSpan = ts.createTextSpanFromBounds(dot.getStart(sourceFile), end); + } + if (isJsxInitializer) { + if (insertText === undefined) + insertText = name; + insertText = "{" + insertText + "}"; + if (typeof isJsxInitializer !== "boolean") { + replacementSpan = ts.createTextSpanFromNode(isJsxInitializer, sourceFile); + } + } + if (insertText !== undefined && !preferences.includeCompletionsWithInsertText) { + return undefined; + } + // TODO(drosen): Right now we just permit *all* semantic meanings when calling + // 'getSymbolKind' which is permissible given that it is backwards compatible; but + // really we should consider passing the meaning for the node so that we don't report + // that a suggestion for a value is an interface. We COULD also just do what + // 'getSymbolModifiers' does, which is to use the first declaration. + // Use a 'sortText' of 0' so that all symbol completion entries come before any other + // entries (like JavaScript identifier entries). + return { + name: name, + kind: ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, location), + kindModifiers: ts.SymbolDisplay.getSymbolModifiers(symbol), + sortText: "0", + source: getSourceFromOrigin(origin), + hasAction: trueOrUndefined(!!origin && originIsExport(origin)), + isRecommended: trueOrUndefined(isRecommendedCompletionMatch(symbol, recommendedCompletion, typeChecker)), + insertText: insertText, + replacementSpan: replacementSpan, + }; + } + function isRecommendedCompletionMatch(localSymbol, recommendedCompletion, checker) { + return localSymbol === recommendedCompletion || + !!(localSymbol.flags & 1048576 /* ExportValue */) && checker.getExportSymbolOfSymbol(localSymbol) === recommendedCompletion; + } + function trueOrUndefined(b) { + return b ? true : undefined; + } + function getSourceFromOrigin(origin) { + return origin && originIsExport(origin) ? ts.stripQuotes(origin.moduleSymbol.name) : undefined; + } + function getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, target, log, kind, preferences, propertyAccessToConvert, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap) { + var start = ts.timestamp(); + // Tracks unique names. + // We don't set this for global variables or completions from external module exports, because we can have multiple of those. + // Based on the order we add things we will always see locals first, then globals, then module exports. + // So adding a completion for a local will prevent us from adding completions for external module exports sharing the same name. + var uniques = ts.createMap(); + for (var _i = 0, symbols_3 = symbols; _i < symbols_3.length; _i++) { + var symbol = symbols_3[_i]; + var origin = symbolToOriginInfoMap ? symbolToOriginInfoMap[ts.getSymbolId(symbol)] : undefined; + var entry = createCompletionEntry(symbol, location, sourceFile, typeChecker, target, kind, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, preferences); + if (!entry) { + continue; + } + var name = entry.name; + if (uniques.has(name)) { + continue; + } + // Latter case tests whether this is a global variable. + if (!origin && !(symbol.parent === undefined && !ts.some(symbol.declarations, function (d) { return d.getSourceFile() === location.getSourceFile(); }))) { // TODO: GH#18217 + uniques.set(name, true); + } + entries.push(entry); + } + log("getCompletionsAtPosition: getCompletionEntriesFromSymbols: " + (ts.timestamp() - start)); + return uniques; + } + Completions.getCompletionEntriesFromSymbols = getCompletionEntriesFromSymbols; + function getLabelCompletionAtPosition(node) { + var entries = getLabelStatementCompletions(node); + if (entries.length) { + return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries }; + } + } + function getLabelStatementCompletions(node) { + var entries = []; + var uniques = ts.createMap(); + var current = node; + while (current) { + if (ts.isFunctionLike(current)) { + break; + } + if (ts.isLabeledStatement(current)) { + var name = current.label.text; + if (!uniques.has(name)) { + uniques.set(name, true); + entries.push({ + name: name, + kindModifiers: "" /* none */, + kind: "label" /* label */, + sortText: "0" + }); + } + } + current = current.parent; + } + return entries; + } + function getSymbolCompletionFromEntryId(program, log, sourceFile, position, entryId) { + var compilerOptions = program.getCompilerOptions(); + var completionData = getCompletionData(program, log, sourceFile, isUncheckedFile(sourceFile, compilerOptions), position, { includeCompletionsForModuleExports: true, includeCompletionsWithInsertText: true }, entryId); + if (!completionData) { + return { type: "none" }; + } + if (completionData.kind !== 0 /* Data */) { + return { type: "request", request: completionData }; + } + var symbols = completionData.symbols, literals = completionData.literals, location = completionData.location, completionKind = completionData.completionKind, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap, previousToken = completionData.previousToken, isJsxInitializer = completionData.isJsxInitializer; + var literal = ts.find(literals, function (l) { return completionNameForLiteral(l) === entryId.name; }); + if (literal !== undefined) + return { type: "literal", literal: literal }; + // Find the symbol with the matching entry name. + // We don't need to perform character checks here because we're only comparing the + // name against 'entryName' (which is known to be good), not building a new + // completion entry. + return ts.firstDefined(symbols, function (symbol) { + var origin = symbolToOriginInfoMap[ts.getSymbolId(symbol)]; + var info = getCompletionEntryDisplayNameForSymbol(symbol, compilerOptions.target, origin, completionKind); + return info && info.name === entryId.name && getSourceFromOrigin(origin) === entryId.source + ? { type: "symbol", symbol: symbol, location: location, symbolToOriginInfoMap: symbolToOriginInfoMap, previousToken: previousToken, isJsxInitializer: isJsxInitializer } + : undefined; + }) || { type: "none" }; + } + function getSymbolName(symbol, origin, target) { + return origin && originIsExport(origin) && origin.isDefaultExport && symbol.escapedName === "default" /* Default */ + // Name of "export default foo;" is "foo". Name of "export default 0" is the filename converted to camelCase. + ? ts.firstDefined(symbol.declarations, function (d) { return ts.isExportAssignment(d) && ts.isIdentifier(d.expression) ? d.expression.text : undefined; }) + || ts.codefix.moduleSymbolToValidIdentifier(origin.moduleSymbol, target) + : symbol.name; + } + function getCompletionEntryDetails(program, log, sourceFile, position, entryId, host, formatContext, preferences, cancellationToken) { + var typeChecker = program.getTypeChecker(); + var compilerOptions = program.getCompilerOptions(); + var name = entryId.name; + var contextToken = ts.findPrecedingToken(position, sourceFile); + if (ts.isInString(sourceFile, position, contextToken)) { + return Completions.StringCompletions.getStringLiteralCompletionDetails(name, sourceFile, position, contextToken, typeChecker, compilerOptions, host, cancellationToken); + } + // Compute all the completion symbols again. + var symbolCompletion = getSymbolCompletionFromEntryId(program, log, sourceFile, position, entryId); + switch (symbolCompletion.type) { + case "request": { + var request = symbolCompletion.request; + switch (request.kind) { + case 1 /* JsDocTagName */: + return ts.JsDoc.getJSDocTagNameCompletionDetails(name); + case 2 /* JsDocTag */: + return ts.JsDoc.getJSDocTagCompletionDetails(name); + case 3 /* JsDocParameterName */: + return ts.JsDoc.getJSDocParameterNameCompletionDetails(name); + default: + return ts.Debug.assertNever(request); + } + } + case "symbol": { + var symbol = symbolCompletion.symbol, location = symbolCompletion.location, symbolToOriginInfoMap = symbolCompletion.symbolToOriginInfoMap, previousToken = symbolCompletion.previousToken; + var _a = getCompletionEntryCodeActionsAndSourceDisplay(symbolToOriginInfoMap, symbol, program, typeChecker, host, compilerOptions, sourceFile, position, previousToken, formatContext, preferences), codeActions = _a.codeActions, sourceDisplay = _a.sourceDisplay; + return createCompletionDetailsForSymbol(symbol, typeChecker, sourceFile, location, cancellationToken, codeActions, sourceDisplay); // TODO: GH#18217 + } + case "literal": { + var literal = symbolCompletion.literal; + return createSimpleDetails(completionNameForLiteral(literal), "string" /* string */, typeof literal === "string" ? ts.SymbolDisplayPartKind.stringLiteral : ts.SymbolDisplayPartKind.numericLiteral); + } + case "none": + // Didn't find a symbol with this name. See if we can find a keyword instead. + return allKeywordsCompletions().some(function (c) { return c.name === name; }) ? createSimpleDetails(name, "keyword" /* keyword */, ts.SymbolDisplayPartKind.keyword) : undefined; + default: + ts.Debug.assertNever(symbolCompletion); + } + } + Completions.getCompletionEntryDetails = getCompletionEntryDetails; + function createSimpleDetails(name, kind, kind2) { + return createCompletionDetails(name, "" /* none */, kind, [ts.displayPart(name, kind2)]); + } + function createCompletionDetailsForSymbol(symbol, checker, sourceFile, location, cancellationToken, codeActions, sourceDisplay) { + var _a = checker.runWithCancellationToken(cancellationToken, function (checker) { + return ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, sourceFile, location, location, 7 /* All */); + }), displayParts = _a.displayParts, documentation = _a.documentation, symbolKind = _a.symbolKind, tags = _a.tags; + return createCompletionDetails(symbol.name, ts.SymbolDisplay.getSymbolModifiers(symbol), symbolKind, displayParts, documentation, tags, codeActions, sourceDisplay); + } + Completions.createCompletionDetailsForSymbol = createCompletionDetailsForSymbol; + function createCompletionDetails(name, kindModifiers, kind, displayParts, documentation, tags, codeActions, source) { + return { name: name, kindModifiers: kindModifiers, kind: kind, displayParts: displayParts, documentation: documentation, tags: tags, codeActions: codeActions, source: source }; + } + Completions.createCompletionDetails = createCompletionDetails; + function getCompletionEntryCodeActionsAndSourceDisplay(symbolToOriginInfoMap, symbol, program, checker, host, compilerOptions, sourceFile, position, previousToken, formatContext, preferences) { + var symbolOriginInfo = symbolToOriginInfoMap[ts.getSymbolId(symbol)]; + if (!symbolOriginInfo || !originIsExport(symbolOriginInfo)) { + return { codeActions: undefined, sourceDisplay: undefined }; + } + var moduleSymbol = symbolOriginInfo.moduleSymbol; + var exportedSymbol = checker.getMergedSymbol(ts.skipAlias(symbol.exportSymbol || symbol, checker)); + var _a = ts.codefix.getImportCompletionAction(exportedSymbol, moduleSymbol, sourceFile, getSymbolName(symbol, symbolOriginInfo, compilerOptions.target), host, program, formatContext, previousToken && ts.isIdentifier(previousToken) ? previousToken.getStart(sourceFile) : position, preferences), moduleSpecifier = _a.moduleSpecifier, codeAction = _a.codeAction; + return { sourceDisplay: [ts.textPart(moduleSpecifier)], codeActions: [codeAction] }; + } + function getCompletionEntrySymbol(program, log, sourceFile, position, entryId) { + var completion = getSymbolCompletionFromEntryId(program, log, sourceFile, position, entryId); + return completion.type === "symbol" ? completion.symbol : undefined; + } + Completions.getCompletionEntrySymbol = getCompletionEntrySymbol; + var CompletionDataKind; + (function (CompletionDataKind) { + CompletionDataKind[CompletionDataKind["Data"] = 0] = "Data"; + CompletionDataKind[CompletionDataKind["JsDocTagName"] = 1] = "JsDocTagName"; + CompletionDataKind[CompletionDataKind["JsDocTag"] = 2] = "JsDocTag"; + CompletionDataKind[CompletionDataKind["JsDocParameterName"] = 3] = "JsDocParameterName"; + })(CompletionDataKind || (CompletionDataKind = {})); + var CompletionKind; + (function (CompletionKind) { + CompletionKind[CompletionKind["ObjectPropertyDeclaration"] = 0] = "ObjectPropertyDeclaration"; + CompletionKind[CompletionKind["Global"] = 1] = "Global"; + CompletionKind[CompletionKind["PropertyAccess"] = 2] = "PropertyAccess"; + CompletionKind[CompletionKind["MemberLike"] = 3] = "MemberLike"; + CompletionKind[CompletionKind["String"] = 4] = "String"; + CompletionKind[CompletionKind["None"] = 5] = "None"; + })(CompletionKind = Completions.CompletionKind || (Completions.CompletionKind = {})); + function getRecommendedCompletion(previousToken, contextualType, checker) { + // For a union, return the first one with a recommended completion. + return ts.firstDefined(contextualType && (contextualType.isUnion() ? contextualType.types : [contextualType]), function (type) { + var symbol = type && type.symbol; + // Don't include make a recommended completion for an abstract class + return symbol && (symbol.flags & (8 /* EnumMember */ | 384 /* Enum */ | 32 /* Class */) && !ts.isAbstractConstructorSymbol(symbol)) + ? getFirstSymbolInChain(symbol, previousToken, checker) + : undefined; + }); + } + function getContextualType(previousToken, position, sourceFile, checker) { + var parent = previousToken.parent; + switch (previousToken.kind) { + case 72 /* Identifier */: + return ts.getContextualTypeFromParent(previousToken, checker); + case 59 /* EqualsToken */: + switch (parent.kind) { + case 237 /* VariableDeclaration */: + return checker.getContextualType(parent.initializer); // TODO: GH#18217 + case 204 /* BinaryExpression */: + return checker.getTypeAtLocation(parent.left); + case 267 /* JsxAttribute */: + return checker.getContextualTypeForJsxAttribute(parent); + default: + return undefined; + } + case 95 /* NewKeyword */: + return checker.getContextualType(parent); + case 74 /* CaseKeyword */: + return ts.getSwitchedType(ts.cast(parent, ts.isCaseClause), checker); + case 18 /* OpenBraceToken */: + return ts.isJsxExpression(parent) && parent.parent.kind !== 260 /* JsxElement */ ? checker.getContextualTypeForJsxAttribute(parent.parent) : undefined; + default: + var argInfo = ts.SignatureHelp.getArgumentInfoForCompletions(previousToken, position, sourceFile); + return argInfo + // At `,`, treat this as the next argument after the comma. + ? checker.getContextualTypeForArgumentAtIndex(argInfo.invocation, argInfo.argumentIndex + (previousToken.kind === 27 /* CommaToken */ ? 1 : 0)) + : ts.isEqualityOperatorKind(previousToken.kind) && ts.isBinaryExpression(parent) && ts.isEqualityOperatorKind(parent.operatorToken.kind) + // completion at `x ===/**/` should be for the right side + ? checker.getTypeAtLocation(parent.left) + : checker.getContextualType(previousToken); + } + } + function getFirstSymbolInChain(symbol, enclosingDeclaration, checker) { + var chain = checker.getAccessibleSymbolChain(symbol, enclosingDeclaration, /*meaning*/ 67108863 /* All */, /*useOnlyExternalAliasing*/ false); + if (chain) + return ts.first(chain); + return symbol.parent && (isModuleSymbol(symbol.parent) ? symbol : getFirstSymbolInChain(symbol.parent, enclosingDeclaration, checker)); + } + function isModuleSymbol(symbol) { + return symbol.declarations.some(function (d) { return d.kind === 279 /* SourceFile */; }); + } + function getCompletionData(program, log, sourceFile, isUncheckedFile, position, preferences, detailsEntryId) { + var typeChecker = program.getTypeChecker(); + var start = ts.timestamp(); + var currentToken = ts.getTokenAtPosition(sourceFile, position); // TODO: GH#15853 + // We will check for jsdoc comments with insideComment and getJsDocTagAtPosition. (TODO: that seems rather inefficient to check the same thing so many times.) + log("getCompletionData: Get current token: " + (ts.timestamp() - start)); + start = ts.timestamp(); + var insideComment = ts.isInComment(sourceFile, position, currentToken); + log("getCompletionData: Is inside comment: " + (ts.timestamp() - start)); + var insideJsDocTagTypeExpression = false; + var isInSnippetScope = false; + if (insideComment) { + if (ts.hasDocComment(sourceFile, position)) { + if (sourceFile.text.charCodeAt(position - 1) === 64 /* at */) { + // The current position is next to the '@' sign, when no tag name being provided yet. + // Provide a full list of tag names + return { kind: 1 /* JsDocTagName */ }; + } + else { + // When completion is requested without "@", we will have check to make sure that + // there are no comments prefix the request position. We will only allow "*" and space. + // e.g + // /** |c| /* + // + // /** + // |c| + // */ + // + // /** + // * |c| + // */ + // + // /** + // * |c| + // */ + var lineStart = ts.getLineStartPositionForPosition(position, sourceFile); + if (!(sourceFile.text.substring(lineStart, position).match(/[^\*|\s|(/\*\*)]/))) { + return { kind: 2 /* JsDocTag */ }; + } + } + } + // Completion should work inside certain JsDoc tags. For example: + // /** @type {number | string} */ + // Completion should work in the brackets + var tag = getJsDocTagAtPosition(currentToken, position); + if (tag) { + if (tag.tagName.pos <= position && position <= tag.tagName.end) { + return { kind: 1 /* JsDocTagName */ }; + } + if (isTagWithTypeExpression(tag) && tag.typeExpression && tag.typeExpression.kind === 283 /* JSDocTypeExpression */) { + currentToken = ts.getTokenAtPosition(sourceFile, position); + if (!currentToken || + (!ts.isDeclarationName(currentToken) && + (currentToken.parent.kind !== 305 /* JSDocPropertyTag */ || + currentToken.parent.name !== currentToken))) { + // Use as type location if inside tag's type expression + insideJsDocTagTypeExpression = isCurrentlyEditingNode(tag.typeExpression); + } + } + if (ts.isJSDocParameterTag(tag) && (ts.nodeIsMissing(tag.name) || tag.name.pos <= position && position <= tag.name.end)) { + return { kind: 3 /* JsDocParameterName */, tag: tag }; + } + } + if (!insideJsDocTagTypeExpression) { + // Proceed if the current position is in jsDoc tag expression; otherwise it is a normal + // comment or the plain text part of a jsDoc comment, so no completion should be available + log("Returning an empty list because completion was inside a regular comment or plain text part of a JsDoc comment."); + return undefined; + } + } + start = ts.timestamp(); + var previousToken = ts.findPrecedingToken(position, sourceFile, /*startNode*/ undefined); // TODO: GH#18217 + log("getCompletionData: Get previous token 1: " + (ts.timestamp() - start)); + // The decision to provide completion depends on the contextToken, which is determined through the previousToken. + // Note: 'previousToken' (and thus 'contextToken') can be undefined if we are the beginning of the file + var contextToken = previousToken; + // Check if the caret is at the end of an identifier; this is a partial identifier that we want to complete: e.g. a.toS| + // Skip this partial identifier and adjust the contextToken to the token that precedes it. + if (contextToken && position <= contextToken.end && (ts.isIdentifier(contextToken) || ts.isKeyword(contextToken.kind))) { + var start_3 = ts.timestamp(); + contextToken = ts.findPrecedingToken(contextToken.getFullStart(), sourceFile, /*startNode*/ undefined); // TODO: GH#18217 + log("getCompletionData: Get previous token 2: " + (ts.timestamp() - start_3)); + } + // Find the node where completion is requested on. + // Also determine whether we are trying to complete with members of that node + // or attributes of a JSX tag. + var node = currentToken; + var propertyAccessToConvert; + var isRightOfDot = false; + var isRightOfOpenTag = false; + var isStartingCloseTag = false; + var isJsxInitializer = false; + var location = ts.getTouchingPropertyName(sourceFile, position); + if (contextToken) { + // Bail out if this is a known invalid completion location + if (isCompletionListBlocker(contextToken)) { + log("Returning an empty list because completion was requested in an invalid position."); + return undefined; + } + var parent = contextToken.parent; + if (contextToken.kind === 24 /* DotToken */) { + isRightOfDot = true; + switch (parent.kind) { + case 189 /* PropertyAccessExpression */: + propertyAccessToConvert = parent; + node = propertyAccessToConvert.expression; + break; + case 148 /* QualifiedName */: + node = parent.left; + break; + case 244 /* ModuleDeclaration */: + node = parent.name; + break; + case 183 /* ImportType */: + case 214 /* MetaProperty */: + node = parent; + break; + default: + // There is nothing that precedes the dot, so this likely just a stray character + // or leading into a '...' token. Just bail out instead. + return undefined; + } + } + else if (sourceFile.languageVariant === 1 /* JSX */) { + // + // If the tagname is a property access expression, we will then walk up to the top most of property access expression. + // Then, try to get a JSX container and its associated attributes type. + if (parent && parent.kind === 189 /* PropertyAccessExpression */) { + contextToken = parent; + parent = parent.parent; + } + // Fix location + if (currentToken.parent === location) { + switch (currentToken.kind) { + case 30 /* GreaterThanToken */: + if (currentToken.parent.kind === 260 /* JsxElement */ || currentToken.parent.kind === 262 /* JsxOpeningElement */) { + location = currentToken; + } + break; + case 42 /* SlashToken */: + if (currentToken.parent.kind === 261 /* JsxSelfClosingElement */) { + location = currentToken; + } + break; + } + } + switch (parent.kind) { + case 263 /* JsxClosingElement */: + if (contextToken.kind === 42 /* SlashToken */) { + isStartingCloseTag = true; + location = contextToken; + } + break; + case 204 /* BinaryExpression */: + if (!binaryExpressionMayBeOpenTag(parent)) { + break; + } + // falls through + case 261 /* JsxSelfClosingElement */: + case 260 /* JsxElement */: + case 262 /* JsxOpeningElement */: + if (contextToken.kind === 28 /* LessThanToken */) { + isRightOfOpenTag = true; + location = contextToken; + } + break; + case 267 /* JsxAttribute */: + switch (previousToken.kind) { + case 59 /* EqualsToken */: + isJsxInitializer = true; + break; + case 72 /* Identifier */: + // For `
      ` we don't want to treat this as a jsx inializer, instead it's the attribute name. + if (parent !== previousToken.parent && + !parent.initializer && + ts.findChildOfKind(parent, 59 /* EqualsToken */, sourceFile)) { + isJsxInitializer = previousToken; + } + } + break; + } + } + } + var semanticStart = ts.timestamp(); + var completionKind = 5 /* None */; + var isNewIdentifierLocation = false; + var keywordFilters = 0 /* None */; + var symbols = []; + var symbolToOriginInfoMap = []; + if (isRightOfDot) { + getTypeScriptMemberSymbols(); + } + else if (isRightOfOpenTag) { + var tagSymbols = ts.Debug.assertEachDefined(typeChecker.getJsxIntrinsicTagNamesAt(location), "getJsxIntrinsicTagNames() should all be defined"); + tryGetGlobalSymbols(); + symbols = tagSymbols.concat(symbols); + completionKind = 3 /* MemberLike */; + keywordFilters = 0 /* None */; + } + else if (isStartingCloseTag) { + var tagName = contextToken.parent.parent.openingElement.tagName; + var tagSymbol = typeChecker.getSymbolAtLocation(tagName); + if (tagSymbol) { + symbols = [tagSymbol]; + } + completionKind = 3 /* MemberLike */; + keywordFilters = 0 /* None */; + } + else { + // For JavaScript or TypeScript, if we're not after a dot, then just try to get the + // global symbols in scope. These results should be valid for either language as + // the set of symbols that can be referenced from this location. + if (!tryGetGlobalSymbols()) { + return undefined; + } + } + log("getCompletionData: Semantic work: " + (ts.timestamp() - semanticStart)); + var contextualType = previousToken && getContextualType(previousToken, position, sourceFile, typeChecker); + var literals = ts.mapDefined(contextualType && (contextualType.isUnion() ? contextualType.types : [contextualType]), function (t) { return t.isLiteral() ? t.value : undefined; }); + var recommendedCompletion = previousToken && contextualType && getRecommendedCompletion(previousToken, contextualType, typeChecker); + return { kind: 0 /* Data */, symbols: symbols, completionKind: completionKind, isInSnippetScope: isInSnippetScope, propertyAccessToConvert: propertyAccessToConvert, isNewIdentifierLocation: isNewIdentifierLocation, location: location, keywordFilters: keywordFilters, literals: literals, symbolToOriginInfoMap: symbolToOriginInfoMap, recommendedCompletion: recommendedCompletion, previousToken: previousToken, isJsxInitializer: isJsxInitializer }; + function isTagWithTypeExpression(tag) { + switch (tag.kind) { + case 299 /* JSDocParameterTag */: + case 305 /* JSDocPropertyTag */: + case 300 /* JSDocReturnTag */: + case 302 /* JSDocTypeTag */: + case 304 /* JSDocTypedefTag */: + return true; + default: + return false; + } + } + function getTypeScriptMemberSymbols() { + // Right of dot member completion list + completionKind = 2 /* PropertyAccess */; + // Since this is qualified name check its a type node location + var isImportType = ts.isLiteralImportTypeNode(node); + var isTypeLocation = insideJsDocTagTypeExpression || (isImportType && !node.isTypeOf) || ts.isPartOfTypeNode(node.parent); + var isRhsOfImportDeclaration = ts.isInRightSideOfInternalImportEqualsDeclaration(node); + var allowTypeOrValue = isRhsOfImportDeclaration || (!isTypeLocation && ts.isPossiblyTypeArgumentPosition(contextToken, sourceFile, typeChecker)); + if (ts.isEntityName(node) || isImportType) { + var isNamespaceName = ts.isModuleDeclaration(node.parent); + if (isNamespaceName) + isNewIdentifierLocation = true; + var symbol = typeChecker.getSymbolAtLocation(node); + if (symbol) { + symbol = ts.skipAlias(symbol, typeChecker); + if (symbol.flags & (1536 /* Module */ | 384 /* Enum */)) { + // Extract module or enum members + var exportedSymbols = ts.Debug.assertEachDefined(typeChecker.getExportsOfModule(symbol), "getExportsOfModule() should all be defined"); + var isValidValueAccess_1 = function (symbol) { return typeChecker.isValidPropertyAccess(isImportType ? node : (node.parent), symbol.name); }; + var isValidTypeAccess_1 = function (symbol) { return symbolCanBeReferencedAtTypeLocation(symbol); }; + var isValidAccess = isNamespaceName + // At `namespace N.M/**/`, if this is the only declaration of `M`, don't include `M` as a completion. + ? function (symbol) { return !!(symbol.flags & 1920 /* Namespace */) && !symbol.declarations.every(function (d) { return d.parent === node.parent; }); } + : allowTypeOrValue ? + // Any kind is allowed when dotting off namespace in internal import equals declaration + function (symbol) { return isValidTypeAccess_1(symbol) || isValidValueAccess_1(symbol); } : + isTypeLocation ? isValidTypeAccess_1 : isValidValueAccess_1; + for (var _i = 0, exportedSymbols_1 = exportedSymbols; _i < exportedSymbols_1.length; _i++) { + var exportedSymbol = exportedSymbols_1[_i]; + if (isValidAccess(exportedSymbol)) { + symbols.push(exportedSymbol); + } + } + // If the module is merged with a value, we must get the type of the class and add its propertes (for inherited static methods). + if (!isTypeLocation && symbol.declarations.some(function (d) { return d.kind !== 279 /* SourceFile */ && d.kind !== 244 /* ModuleDeclaration */ && d.kind !== 243 /* EnumDeclaration */; })) { + addTypeProperties(typeChecker.getTypeOfSymbolAtLocation(symbol, node)); + } + return; + } + } + } + if (ts.isMetaProperty(node) && (node.keywordToken === 95 /* NewKeyword */ || node.keywordToken === 92 /* ImportKeyword */)) { + var completion = (node.keywordToken === 95 /* NewKeyword */) ? "target" : "meta"; + symbols.push(typeChecker.createSymbol(4 /* Property */, ts.escapeLeadingUnderscores(completion))); + return; + } + if (!isTypeLocation) { + addTypeProperties(typeChecker.getTypeAtLocation(node)); + } + } + function addTypeProperties(type) { + isNewIdentifierLocation = !!type.getStringIndexType(); + if (isUncheckedFile) { + // In javascript files, for union types, we don't just get the members that + // the individual types have in common, we also include all the members that + // each individual type has. This is because we're going to add all identifiers + // anyways. So we might as well elevate the members that were at least part + // of the individual types to a higher status since we know what they are. + symbols.push.apply(symbols, getPropertiesForCompletion(type, typeChecker)); + } + else { + for (var _i = 0, _a = type.getApparentProperties(); _i < _a.length; _i++) { + var symbol = _a[_i]; + if (typeChecker.isValidPropertyAccessForCompletions(node.kind === 183 /* ImportType */ ? node : node.parent, type, symbol)) { + addPropertySymbol(symbol); + } + } + } + } + function addPropertySymbol(symbol) { + // For a computed property with an accessible name like `Symbol.iterator`, + // we'll add a completion for the *name* `Symbol` instead of for the property. + // If this is e.g. [Symbol.iterator], add a completion for `Symbol`. + var computedPropertyName = ts.firstDefined(symbol.declarations, function (decl) { return ts.tryCast(ts.getNameOfDeclaration(decl), ts.isComputedPropertyName); }); + if (computedPropertyName) { + var leftMostName = getLeftMostName(computedPropertyName.expression); // The completion is for `Symbol`, not `iterator`. + var nameSymbol = leftMostName && typeChecker.getSymbolAtLocation(leftMostName); + // If this is nested like for `namespace N { export const sym = Symbol(); }`, we'll add the completion for `N`. + var firstAccessibleSymbol = nameSymbol && getFirstSymbolInChain(nameSymbol, contextToken, typeChecker); + if (firstAccessibleSymbol && !symbolToOriginInfoMap[ts.getSymbolId(firstAccessibleSymbol)]) { + symbols.push(firstAccessibleSymbol); + var moduleSymbol = firstAccessibleSymbol.parent; + symbolToOriginInfoMap[ts.getSymbolId(firstAccessibleSymbol)] = + !moduleSymbol || !ts.isExternalModuleSymbol(moduleSymbol) ? { kind: 1 /* SymbolMemberNoExport */ } : { kind: 2 /* SymbolMemberExport */, moduleSymbol: moduleSymbol, isDefaultExport: false }; + } + } + else { + symbols.push(symbol); + } + } + /** Given 'a.b.c', returns 'a'. */ + function getLeftMostName(e) { + return ts.isIdentifier(e) ? e : ts.isPropertyAccessExpression(e) ? getLeftMostName(e.expression) : undefined; + } + function tryGetGlobalSymbols() { + var result = tryGetObjectLikeCompletionSymbols() + || tryGetImportOrExportClauseCompletionSymbols() + || tryGetConstructorCompletion() + || tryGetClassLikeCompletionSymbols() + || tryGetJsxCompletionSymbols() + || (getGlobalCompletions(), 1 /* Success */); + return result === 1 /* Success */; + } + function tryGetConstructorCompletion() { + if (!tryGetConstructorLikeCompletionContainer(contextToken)) + return 0 /* Continue */; + // no members, only keywords + completionKind = 5 /* None */; + // Declaring new property/method/accessor + isNewIdentifierLocation = true; + // Has keywords for constructor parameter + keywordFilters = 4 /* ConstructorParameterKeywords */; + return 1 /* Success */; + } + function tryGetJsxCompletionSymbols() { + var jsxContainer = tryGetContainingJsxElement(contextToken); + // Cursor is inside a JSX self-closing element or opening element + var attrsType = jsxContainer && typeChecker.getContextualType(jsxContainer.attributes); + if (!attrsType) + return 0 /* Continue */; + symbols = filterJsxAttributes(getPropertiesForObjectExpression(attrsType, jsxContainer.attributes, typeChecker), jsxContainer.attributes.properties); + completionKind = 3 /* MemberLike */; + isNewIdentifierLocation = false; + return 1 /* Success */; + } + function getGlobalCompletions() { + keywordFilters = tryGetFunctionLikeBodyCompletionContainer(contextToken) ? 5 /* FunctionLikeBodyKeywords */ : 1 /* All */; + // Get all entities in the current scope. + completionKind = 1 /* Global */; + isNewIdentifierLocation = isNewIdentifierDefinitionLocation(contextToken); + if (previousToken !== contextToken) { + ts.Debug.assert(!!previousToken, "Expected 'contextToken' to be defined when different from 'previousToken'."); + } + // We need to find the node that will give us an appropriate scope to begin + // aggregating completion candidates. This is achieved in 'getScopeNode' + // by finding the first node that encompasses a position, accounting for whether a node + // is "complete" to decide whether a position belongs to the node. + // + // However, at the end of an identifier, we are interested in the scope of the identifier + // itself, but fall outside of the identifier. For instance: + // + // xyz => x$ + // + // the cursor is outside of both the 'x' and the arrow function 'xyz => x', + // so 'xyz' is not returned in our results. + // + // We define 'adjustedPosition' so that we may appropriately account for + // being at the end of an identifier. The intention is that if requesting completion + // at the end of an identifier, it should be effectively equivalent to requesting completion + // anywhere inside/at the beginning of the identifier. So in the previous case, the + // 'adjustedPosition' will work as if requesting completion in the following: + // + // xyz => $x + // + // If previousToken !== contextToken, then + // - 'contextToken' was adjusted to the token prior to 'previousToken' + // because we were at the end of an identifier. + // - 'previousToken' is defined. + var adjustedPosition = previousToken !== contextToken ? + previousToken.getStart() : + position; + var scopeNode = getScopeNode(contextToken, adjustedPosition, sourceFile) || sourceFile; + isInSnippetScope = isSnippetScope(scopeNode); + var isTypeOnly = isTypeOnlyCompletion(); + var symbolMeanings = (isTypeOnly ? 0 /* None */ : 67220415 /* Value */) | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */; + symbols = ts.Debug.assertEachDefined(typeChecker.getSymbolsInScope(scopeNode, symbolMeanings), "getSymbolsInScope() should all be defined"); + // Need to insert 'this.' before properties of `this` type, so only do that if `includeInsertTextCompletions` + if (preferences.includeCompletionsWithInsertText && scopeNode.kind !== 279 /* SourceFile */) { + var thisType = typeChecker.tryGetThisTypeAt(scopeNode); + if (thisType) { + for (var _i = 0, _a = getPropertiesForCompletion(thisType, typeChecker); _i < _a.length; _i++) { + var symbol = _a[_i]; + symbolToOriginInfoMap[ts.getSymbolId(symbol)] = { kind: 0 /* ThisType */ }; + symbols.push(symbol); + } + } + } + if (shouldOfferImportCompletions()) { + getSymbolsFromOtherSourceFileExports(symbols, previousToken && ts.isIdentifier(previousToken) ? previousToken.text : "", program.getCompilerOptions().target); + } + filterGlobalCompletion(symbols); + } + function shouldOfferImportCompletions() { + // If not already a module, must have modules enabled and not currently be in a commonjs module. (TODO: import completions for commonjs) + if (!preferences.includeCompletionsForModuleExports) + return false; + // If already using ES6 modules, OK to continue using them. + if (sourceFile.externalModuleIndicator) + return true; + // If already using commonjs, don't introduce ES6. + if (sourceFile.commonJsModuleIndicator) + return false; + // If module transpilation is enabled or we're targeting es6 or above, or not emitting, OK. + if (ts.compilerOptionsIndicateEs6Modules(program.getCompilerOptions())) + return true; + // If some file is using ES6 modules, assume that it's OK to add more. + return ts.programContainsEs6Modules(program); + } + function isSnippetScope(scopeNode) { + switch (scopeNode.kind) { + case 279 /* SourceFile */: + case 206 /* TemplateExpression */: + case 270 /* JsxExpression */: + case 218 /* Block */: + return true; + default: + return ts.isStatement(scopeNode); + } + } + function filterGlobalCompletion(symbols) { + var isTypeOnly = isTypeOnlyCompletion(); + var allowTypes = isTypeOnly || !isContextTokenValueLocation(contextToken) && ts.isPossiblyTypeArgumentPosition(contextToken, sourceFile, typeChecker); + if (isTypeOnly) + keywordFilters = 6 /* TypeKeywords */; + ts.filterMutate(symbols, function (symbol) { + if (!ts.isSourceFile(location)) { + // export = /**/ here we want to get all meanings, so any symbol is ok + if (ts.isExportAssignment(location.parent)) { + return true; + } + symbol = ts.skipAlias(symbol, typeChecker); + // import m = /**/ <-- It can only access namespace (if typing import = x. this would get member symbols and not namespace) + if (ts.isInRightSideOfInternalImportEqualsDeclaration(location)) { + return !!(symbol.flags & 1920 /* Namespace */); + } + if (allowTypes) { + // Its a type, but you can reach it by namespace.type as well + var symbolAllowedAsType = symbolCanBeReferencedAtTypeLocation(symbol); + if (symbolAllowedAsType || isTypeOnly) { + return symbolAllowedAsType; + } + } + } + // expressions are value space (which includes the value namespaces) + return !!(ts.getCombinedLocalAndExportSymbolFlags(symbol) & 67220415 /* Value */); + }); + } + function isTypeOnlyCompletion() { + return insideJsDocTagTypeExpression || !isContextTokenValueLocation(contextToken) && (ts.isPartOfTypeNode(location) || isContextTokenTypeLocation(contextToken)); + } + function isContextTokenValueLocation(contextToken) { + return contextToken && + contextToken.kind === 104 /* TypeOfKeyword */ && + (contextToken.parent.kind === 167 /* TypeQuery */ || ts.isTypeOfExpression(contextToken.parent)); + } + function isContextTokenTypeLocation(contextToken) { + if (contextToken) { + var parentKind = contextToken.parent.kind; + switch (contextToken.kind) { + case 57 /* ColonToken */: + return parentKind === 154 /* PropertyDeclaration */ || + parentKind === 153 /* PropertySignature */ || + parentKind === 151 /* Parameter */ || + parentKind === 237 /* VariableDeclaration */ || + ts.isFunctionLikeKind(parentKind); + case 59 /* EqualsToken */: + return parentKind === 242 /* TypeAliasDeclaration */; + case 119 /* AsKeyword */: + return parentKind === 212 /* AsExpression */; + } + } + return false; + } + /** True if symbol is a type or a module containing at least one type. */ + function symbolCanBeReferencedAtTypeLocation(symbol, seenModules) { + if (seenModules === void 0) { seenModules = ts.createMap(); } + var sym = ts.skipAlias(symbol.exportSymbol || symbol, typeChecker); + return !!(sym.flags & 67897832 /* Type */) || + !!(sym.flags & 1536 /* Module */) && + ts.addToSeen(seenModules, ts.getSymbolId(sym)) && + typeChecker.getExportsOfModule(sym).some(function (e) { return symbolCanBeReferencedAtTypeLocation(e, seenModules); }); + } + function getSymbolsFromOtherSourceFileExports(symbols, tokenText, target) { + var tokenTextLowerCase = tokenText.toLowerCase(); + var seenResolvedModules = ts.createMap(); + ts.codefix.forEachExternalModuleToImportFrom(typeChecker, sourceFile, program.getSourceFiles(), function (moduleSymbol) { + // Perf -- ignore other modules if this is a request for details + if (detailsEntryId && detailsEntryId.source && ts.stripQuotes(moduleSymbol.name) !== detailsEntryId.source) { + return; + } + var resolvedModuleSymbol = typeChecker.resolveExternalModuleSymbol(moduleSymbol); + // resolvedModuleSymbol may be a namespace. A namespace may be `export =` by multiple module declarations, but only keep the first one. + if (!ts.addToSeen(seenResolvedModules, ts.getSymbolId(resolvedModuleSymbol))) { + return; + } + if (resolvedModuleSymbol !== moduleSymbol && + // Don't add another completion for `export =` of a symbol that's already global. + // So in `declare namespace foo {} declare module "foo" { export = foo; }`, there will just be the global completion for `foo`. + ts.some(resolvedModuleSymbol.declarations, function (d) { return !!d.getSourceFile().externalModuleIndicator; })) { + symbols.push(resolvedModuleSymbol); + symbolToOriginInfoMap[ts.getSymbolId(resolvedModuleSymbol)] = { kind: 3 /* Export */, moduleSymbol: moduleSymbol, isDefaultExport: false }; + } + for (var _i = 0, _a = typeChecker.getExportsOfModule(moduleSymbol); _i < _a.length; _i++) { + var symbol = _a[_i]; + // Don't add a completion for a re-export, only for the original. + // The actual import fix might end up coming from a re-export -- we don't compute that until getting completion details. + // This is just to avoid adding duplicate completion entries. + // + // If `symbol.parent !== ...`, this is an `export * from "foo"` re-export. Those don't create new symbols. + if (typeChecker.getMergedSymbol(symbol.parent) !== resolvedModuleSymbol + || ts.some(symbol.declarations, function (d) { + // If `!!d.name.originalKeywordKind`, this is `export { _break as break };` -- skip this and prefer the keyword completion. + // If `!!d.parent.parent.moduleSpecifier`, this is `export { foo } from "foo"` re-export, which creates a new symbol (thus isn't caught by the first check). + return ts.isExportSpecifier(d) && (d.propertyName ? ts.isIdentifierANonContextualKeyword(d.name) : !!d.parent.parent.moduleSpecifier); + })) { + continue; + } + var isDefaultExport = symbol.escapedName === "default" /* Default */; + if (isDefaultExport) { + symbol = ts.getLocalSymbolForExportDefault(symbol) || symbol; + } + var origin = { kind: 3 /* Export */, moduleSymbol: moduleSymbol, isDefaultExport: isDefaultExport }; + if (detailsEntryId || stringContainsCharactersInOrder(getSymbolName(symbol, origin, target).toLowerCase(), tokenTextLowerCase)) { + symbols.push(symbol); + symbolToOriginInfoMap[ts.getSymbolId(symbol)] = origin; + } + } + }); + } + /** + * True if you could remove some characters in `a` to get `b`. + * E.g., true for "abcdef" and "bdf". + * But not true for "abcdef" and "dbf". + */ + function stringContainsCharactersInOrder(str, characters) { + if (characters.length === 0) { + return true; + } + var characterIndex = 0; + for (var strIndex = 0; strIndex < str.length; strIndex++) { + if (str.charCodeAt(strIndex) === characters.charCodeAt(characterIndex)) { + characterIndex++; + if (characterIndex === characters.length) { + return true; + } + } + } + // Did not find all characters + return false; + } + /** + * Finds the first node that "embraces" the position, so that one may + * accurately aggregate locals from the closest containing scope. + */ + function getScopeNode(initialToken, position, sourceFile) { + var scope = initialToken; + while (scope && !ts.positionBelongsToNode(scope, position, sourceFile)) { + scope = scope.parent; + } + return scope; + } + function isCompletionListBlocker(contextToken) { + var start = ts.timestamp(); + var result = isInStringOrRegularExpressionOrTemplateLiteral(contextToken) || + isSolelyIdentifierDefinitionLocation(contextToken) || + isDotOfNumericLiteral(contextToken) || + isInJsxText(contextToken); + log("getCompletionsAtPosition: isCompletionListBlocker: " + (ts.timestamp() - start)); + return result; + } + function isInJsxText(contextToken) { + if (contextToken.kind === 11 /* JsxText */) { + return true; + } + if (contextToken.kind === 30 /* GreaterThanToken */ && contextToken.parent) { + if (contextToken.parent.kind === 262 /* JsxOpeningElement */) { + return true; + } + if (contextToken.parent.kind === 263 /* JsxClosingElement */ || contextToken.parent.kind === 261 /* JsxSelfClosingElement */) { + return !!contextToken.parent.parent && contextToken.parent.parent.kind === 260 /* JsxElement */; + } + } + return false; + } + function isNewIdentifierDefinitionLocation(previousToken) { + if (previousToken) { + var containingNodeKind = previousToken.parent.kind; + // Previous token may have been a keyword that was converted to an identifier. + switch (keywordForNode(previousToken)) { + case 27 /* CommaToken */: + return containingNodeKind === 191 /* CallExpression */ // func( a, | + || containingNodeKind === 157 /* Constructor */ // constructor( a, | /* public, protected, private keywords are allowed here, so show completion */ + || containingNodeKind === 192 /* NewExpression */ // new C(a, | + || containingNodeKind === 187 /* ArrayLiteralExpression */ // [a, | + || containingNodeKind === 204 /* BinaryExpression */ // const x = (a, | + || containingNodeKind === 165 /* FunctionType */; // var x: (s: string, list| + case 20 /* OpenParenToken */: + return containingNodeKind === 191 /* CallExpression */ // func( | + || containingNodeKind === 157 /* Constructor */ // constructor( | + || containingNodeKind === 192 /* NewExpression */ // new C(a| + || containingNodeKind === 195 /* ParenthesizedExpression */ // const x = (a| + || containingNodeKind === 177 /* ParenthesizedType */; // function F(pred: (a| /* this can become an arrow function, where 'a' is the argument */ + case 22 /* OpenBracketToken */: + return containingNodeKind === 187 /* ArrayLiteralExpression */ // [ | + || containingNodeKind === 162 /* IndexSignature */ // [ | : string ] + || containingNodeKind === 149 /* ComputedPropertyName */; // [ | /* this can become an index signature */ + case 130 /* ModuleKeyword */: // module | + case 131 /* NamespaceKeyword */: // namespace | + return true; + case 24 /* DotToken */: + return containingNodeKind === 244 /* ModuleDeclaration */; // module A.| + case 18 /* OpenBraceToken */: + return containingNodeKind === 240 /* ClassDeclaration */; // class A{ | + case 59 /* EqualsToken */: + return containingNodeKind === 237 /* VariableDeclaration */ // const x = a| + || containingNodeKind === 204 /* BinaryExpression */; // x = a| + case 15 /* TemplateHead */: + return containingNodeKind === 206 /* TemplateExpression */; // `aa ${| + case 16 /* TemplateMiddle */: + return containingNodeKind === 216 /* TemplateSpan */; // `aa ${10} dd ${| + case 115 /* PublicKeyword */: + case 113 /* PrivateKeyword */: + case 114 /* ProtectedKeyword */: + return containingNodeKind === 154 /* PropertyDeclaration */; // class A{ public | + } + } + return false; + } + function isInStringOrRegularExpressionOrTemplateLiteral(contextToken) { + // To be "in" one of these literals, the position has to be: + // 1. entirely within the token text. + // 2. at the end position of an unterminated token. + // 3. at the end of a regular expression (due to trailing flags like '/foo/g'). + return (ts.isRegularExpressionLiteral(contextToken) || ts.isStringTextContainingNode(contextToken)) && (ts.rangeContainsPositionExclusive(ts.createTextRangeFromSpan(ts.createTextSpanFromNode(contextToken)), position) || + position === contextToken.end && (!!contextToken.isUnterminated || ts.isRegularExpressionLiteral(contextToken))); + } + /** + * Aggregates relevant symbols for completion in object literals and object binding patterns. + * Relevant symbols are stored in the captured 'symbols' variable. + * + * @returns true if 'symbols' was successfully populated; false otherwise. + */ + function tryGetObjectLikeCompletionSymbols() { + var objectLikeContainer = tryGetObjectLikeCompletionContainer(contextToken); + if (!objectLikeContainer) + return 0 /* Continue */; + // We're looking up possible property names from contextual/inferred/declared type. + completionKind = 0 /* ObjectPropertyDeclaration */; + var typeMembers; + var existingMembers; + if (objectLikeContainer.kind === 188 /* ObjectLiteralExpression */) { + var typeForObject = typeChecker.getContextualType(objectLikeContainer); + if (!typeForObject) + return 2 /* Fail */; + isNewIdentifierLocation = ts.hasIndexSignature(typeForObject); + typeMembers = getPropertiesForObjectExpression(typeForObject, objectLikeContainer, typeChecker); + existingMembers = objectLikeContainer.properties; + } + else { + ts.Debug.assert(objectLikeContainer.kind === 184 /* ObjectBindingPattern */); + // We are *only* completing on properties from the type being destructured. + isNewIdentifierLocation = false; + var rootDeclaration = ts.getRootDeclaration(objectLikeContainer.parent); + if (!ts.isVariableLike(rootDeclaration)) + return ts.Debug.fail("Root declaration is not variable-like."); + // We don't want to complete using the type acquired by the shape + // of the binding pattern; we are only interested in types acquired + // through type declaration or inference. + // Also proceed if rootDeclaration is a parameter and if its containing function expression/arrow function is contextually typed - + // type of parameter will flow in from the contextual type of the function + var canGetType = ts.hasInitializer(rootDeclaration) || ts.hasType(rootDeclaration) || rootDeclaration.parent.parent.kind === 227 /* ForOfStatement */; + if (!canGetType && rootDeclaration.kind === 151 /* Parameter */) { + if (ts.isExpression(rootDeclaration.parent)) { + canGetType = !!typeChecker.getContextualType(rootDeclaration.parent); + } + else if (rootDeclaration.parent.kind === 156 /* MethodDeclaration */ || rootDeclaration.parent.kind === 159 /* SetAccessor */) { + canGetType = ts.isExpression(rootDeclaration.parent.parent) && !!typeChecker.getContextualType(rootDeclaration.parent.parent); + } + } + if (canGetType) { + var typeForObject = typeChecker.getTypeAtLocation(objectLikeContainer); + if (!typeForObject) + return 2 /* Fail */; + // In a binding pattern, get only known properties. Everywhere else we will get all possible properties. + typeMembers = typeChecker.getPropertiesOfType(typeForObject).filter(function (symbol) { return !(ts.getDeclarationModifierFlagsFromSymbol(symbol) & 24 /* NonPublicAccessibilityModifier */); }); + existingMembers = objectLikeContainer.elements; + } + } + if (typeMembers && typeMembers.length > 0) { + // Add filtered items to the completion list + symbols = filterObjectMembersList(typeMembers, ts.Debug.assertDefined(existingMembers)); + } + return 1 /* Success */; + } + /** + * Aggregates relevant symbols for completion in import clauses and export clauses + * whose declarations have a module specifier; for instance, symbols will be aggregated for + * + * import { | } from "moduleName"; + * export { a as foo, | } from "moduleName"; + * + * but not for + * + * export { | }; + * + * Relevant symbols are stored in the captured 'symbols' variable. + * + * @returns true if 'symbols' was successfully populated; false otherwise. + */ + function tryGetImportOrExportClauseCompletionSymbols() { + // `import { |` or `import { a as 0, | }` + var namedImportsOrExports = contextToken && (contextToken.kind === 18 /* OpenBraceToken */ || contextToken.kind === 27 /* CommaToken */) + ? ts.tryCast(contextToken.parent, ts.isNamedImportsOrExports) : undefined; + if (!namedImportsOrExports) + return 0 /* Continue */; + // cursor is in an import clause + // try to show exported member for imported module + var moduleSpecifier = (namedImportsOrExports.kind === 252 /* NamedImports */ ? namedImportsOrExports.parent.parent : namedImportsOrExports.parent).moduleSpecifier; + var moduleSpecifierSymbol = typeChecker.getSymbolAtLocation(moduleSpecifier); // TODO: GH#18217 + if (!moduleSpecifierSymbol) + return 2 /* Fail */; + completionKind = 3 /* MemberLike */; + isNewIdentifierLocation = false; + var exports = typeChecker.getExportsAndPropertiesOfModule(moduleSpecifierSymbol); + var existing = ts.arrayToSet(namedImportsOrExports.elements, function (n) { return isCurrentlyEditingNode(n) ? undefined : (n.propertyName || n.name).escapedText; }); + symbols = exports.filter(function (e) { return e.escapedName !== "default" /* Default */ && !existing.get(e.escapedName); }); + return 1 /* Success */; + } + /** + * Aggregates relevant symbols for completion in class declaration + * Relevant symbols are stored in the captured 'symbols' variable. + */ + function tryGetClassLikeCompletionSymbols() { + var decl = tryGetObjectTypeDeclarationCompletionContainer(sourceFile, contextToken, location); + if (!decl) + return 0 /* Continue */; + // We're looking up possible property names from parent type. + completionKind = 3 /* MemberLike */; + // Declaring new property/method/accessor + isNewIdentifierLocation = true; + keywordFilters = contextToken.kind === 40 /* AsteriskToken */ ? 0 /* None */ : + ts.isClassLike(decl) ? 2 /* ClassElementKeywords */ : 3 /* InterfaceElementKeywords */; + // If you're in an interface you don't want to repeat things from super-interface. So just stop here. + if (!ts.isClassLike(decl)) + return 1 /* Success */; + var classElement = contextToken.parent; + var classElementModifierFlags = ts.isClassElement(classElement) ? ts.getModifierFlags(classElement) : 0 /* None */; + // If this is context token is not something we are editing now, consider if this would lead to be modifier + if (contextToken.kind === 72 /* Identifier */ && !isCurrentlyEditingNode(contextToken)) { + switch (contextToken.getText()) { + case "private": + classElementModifierFlags = classElementModifierFlags | 8 /* Private */; + break; + case "static": + classElementModifierFlags = classElementModifierFlags | 32 /* Static */; + break; + } + } + // No member list for private methods + if (!(classElementModifierFlags & 8 /* Private */)) { + // List of property symbols of base type that are not private and already implemented + var baseSymbols = ts.flatMap(ts.getAllSuperTypeNodes(decl), function (baseTypeNode) { + var type = typeChecker.getTypeAtLocation(baseTypeNode); + return type && typeChecker.getPropertiesOfType(classElementModifierFlags & 32 /* Static */ ? typeChecker.getTypeOfSymbolAtLocation(type.symbol, decl) : type); + }); + symbols = filterClassMembersList(baseSymbols, decl.members, classElementModifierFlags); + } + return 1 /* Success */; + } + /** + * Returns the immediate owning object literal or binding pattern of a context token, + * on the condition that one exists and that the context implies completion should be given. + */ + function tryGetObjectLikeCompletionContainer(contextToken) { + if (contextToken) { + var parent = contextToken.parent; + switch (contextToken.kind) { + case 18 /* OpenBraceToken */: // const x = { | + case 27 /* CommaToken */: // const x = { a: 0, | + if (ts.isObjectLiteralExpression(parent) || ts.isObjectBindingPattern(parent)) { + return parent; + } + break; + case 40 /* AsteriskToken */: + return ts.isMethodDeclaration(parent) ? ts.tryCast(parent.parent, ts.isObjectLiteralExpression) : undefined; + case 72 /* Identifier */: + return contextToken.text === "async" && ts.isShorthandPropertyAssignment(contextToken.parent) + ? contextToken.parent.parent : undefined; + } + } + return undefined; + } + function isConstructorParameterCompletion(node) { + return !!node.parent && ts.isParameter(node.parent) && ts.isConstructorDeclaration(node.parent.parent) + && (ts.isParameterPropertyModifier(node.kind) || ts.isDeclarationName(node)); + } + /** + * Returns the immediate owning class declaration of a context token, + * on the condition that one exists and that the context implies completion should be given. + */ + function tryGetConstructorLikeCompletionContainer(contextToken) { + if (contextToken) { + var parent = contextToken.parent; + switch (contextToken.kind) { + case 20 /* OpenParenToken */: + case 27 /* CommaToken */: + return ts.isConstructorDeclaration(contextToken.parent) ? contextToken.parent : undefined; + default: + if (isConstructorParameterCompletion(contextToken)) { + return parent.parent; + } + } + } + return undefined; + } + function tryGetFunctionLikeBodyCompletionContainer(contextToken) { + if (contextToken) { + var prev_1; + var container = ts.findAncestor(contextToken.parent, function (node) { + if (ts.isClassLike(node)) { + return "quit"; + } + if (ts.isFunctionLikeDeclaration(node) && prev_1 === node.body) { + return true; + } + prev_1 = node; + return false; + }); + return container && container; + } + } + function tryGetContainingJsxElement(contextToken) { + if (contextToken) { + var parent = contextToken.parent; + switch (contextToken.kind) { + case 30 /* GreaterThanToken */: // End of a type argument list + case 29 /* LessThanSlashToken */: + case 42 /* SlashToken */: + case 72 /* Identifier */: + case 189 /* PropertyAccessExpression */: + case 268 /* JsxAttributes */: + case 267 /* JsxAttribute */: + case 269 /* JsxSpreadAttribute */: + if (parent && (parent.kind === 261 /* JsxSelfClosingElement */ || parent.kind === 262 /* JsxOpeningElement */)) { + if (contextToken.kind === 30 /* GreaterThanToken */) { + var precedingToken = ts.findPrecedingToken(contextToken.pos, sourceFile, /*startNode*/ undefined); + if (!parent.typeArguments || (precedingToken && precedingToken.kind === 42 /* SlashToken */)) + break; + } + return parent; + } + else if (parent.kind === 267 /* JsxAttribute */) { + // Currently we parse JsxOpeningLikeElement as: + // JsxOpeningLikeElement + // attributes: JsxAttributes + // properties: NodeArray + return parent.parent.parent; + } + break; + // The context token is the closing } or " of an attribute, which means + // its parent is a JsxExpression, whose parent is a JsxAttribute, + // whose parent is a JsxOpeningLikeElement + case 10 /* StringLiteral */: + if (parent && ((parent.kind === 267 /* JsxAttribute */) || (parent.kind === 269 /* JsxSpreadAttribute */))) { + // Currently we parse JsxOpeningLikeElement as: + // JsxOpeningLikeElement + // attributes: JsxAttributes + // properties: NodeArray + return parent.parent.parent; + } + break; + case 19 /* CloseBraceToken */: + if (parent && + parent.kind === 270 /* JsxExpression */ && + parent.parent && parent.parent.kind === 267 /* JsxAttribute */) { + // Currently we parse JsxOpeningLikeElement as: + // JsxOpeningLikeElement + // attributes: JsxAttributes + // properties: NodeArray + // each JsxAttribute can have initializer as JsxExpression + return parent.parent.parent.parent; + } + if (parent && parent.kind === 269 /* JsxSpreadAttribute */) { + // Currently we parse JsxOpeningLikeElement as: + // JsxOpeningLikeElement + // attributes: JsxAttributes + // properties: NodeArray + return parent.parent.parent; + } + break; + } + } + return undefined; + } + /** + * @returns true if we are certain that the currently edited location must define a new location; false otherwise. + */ + function isSolelyIdentifierDefinitionLocation(contextToken) { + var parent = contextToken.parent; + var containingNodeKind = parent.kind; + switch (contextToken.kind) { + case 27 /* CommaToken */: + return containingNodeKind === 237 /* VariableDeclaration */ || + containingNodeKind === 238 /* VariableDeclarationList */ || + containingNodeKind === 219 /* VariableStatement */ || + containingNodeKind === 243 /* EnumDeclaration */ || // enum a { foo, | + isFunctionLikeButNotConstructor(containingNodeKind) || + containingNodeKind === 241 /* InterfaceDeclaration */ || // interface A= contextToken.pos); + case 24 /* DotToken */: + return containingNodeKind === 185 /* ArrayBindingPattern */; // var [.| + case 57 /* ColonToken */: + return containingNodeKind === 186 /* BindingElement */; // var {x :html| + case 22 /* OpenBracketToken */: + return containingNodeKind === 185 /* ArrayBindingPattern */; // var [x| + case 20 /* OpenParenToken */: + return containingNodeKind === 274 /* CatchClause */ || + isFunctionLikeButNotConstructor(containingNodeKind); + case 18 /* OpenBraceToken */: + return containingNodeKind === 243 /* EnumDeclaration */; // enum a { | + case 28 /* LessThanToken */: + return containingNodeKind === 240 /* ClassDeclaration */ || // class A< | + containingNodeKind === 209 /* ClassExpression */ || // var C = class D< | + containingNodeKind === 241 /* InterfaceDeclaration */ || // interface A< | + containingNodeKind === 242 /* TypeAliasDeclaration */ || // type List< | + ts.isFunctionLikeKind(containingNodeKind); + case 116 /* StaticKeyword */: + return containingNodeKind === 154 /* PropertyDeclaration */ && !ts.isClassLike(parent.parent); + case 25 /* DotDotDotToken */: + return containingNodeKind === 151 /* Parameter */ || + (!!parent.parent && parent.parent.kind === 185 /* ArrayBindingPattern */); // var [...z| + case 115 /* PublicKeyword */: + case 113 /* PrivateKeyword */: + case 114 /* ProtectedKeyword */: + return containingNodeKind === 151 /* Parameter */ && !ts.isConstructorDeclaration(parent.parent); + case 119 /* AsKeyword */: + return containingNodeKind === 253 /* ImportSpecifier */ || + containingNodeKind === 257 /* ExportSpecifier */ || + containingNodeKind === 251 /* NamespaceImport */; + case 126 /* GetKeyword */: + case 137 /* SetKeyword */: + return !isFromObjectTypeDeclaration(contextToken); + case 76 /* ClassKeyword */: + case 84 /* EnumKeyword */: + case 110 /* InterfaceKeyword */: + case 90 /* FunctionKeyword */: + case 105 /* VarKeyword */: + case 92 /* ImportKeyword */: + case 111 /* LetKeyword */: + case 77 /* ConstKeyword */: + case 117 /* YieldKeyword */: + case 140 /* TypeKeyword */: // type htm| + return true; + case 40 /* AsteriskToken */: + return ts.isFunctionLike(contextToken.parent) && !ts.isMethodDeclaration(contextToken.parent); + } + // If the previous token is keyword correspoding to class member completion keyword + // there will be completion available here + if (isClassMemberCompletionKeyword(keywordForNode(contextToken)) && isFromObjectTypeDeclaration(contextToken)) { + return false; + } + if (isConstructorParameterCompletion(contextToken)) { + // constructor parameter completion is available only if + // - its modifier of the constructor parameter or + // - its name of the parameter and not being edited + // eg. constructor(a |<- this shouldnt show completion + if (!ts.isIdentifier(contextToken) || + ts.isParameterPropertyModifier(keywordForNode(contextToken)) || + isCurrentlyEditingNode(contextToken)) { + return false; + } + } + // Previous token may have been a keyword that was converted to an identifier. + switch (keywordForNode(contextToken)) { + case 118 /* AbstractKeyword */: + case 76 /* ClassKeyword */: + case 77 /* ConstKeyword */: + case 125 /* DeclareKeyword */: + case 84 /* EnumKeyword */: + case 90 /* FunctionKeyword */: + case 110 /* InterfaceKeyword */: + case 111 /* LetKeyword */: + case 113 /* PrivateKeyword */: + case 114 /* ProtectedKeyword */: + case 115 /* PublicKeyword */: + case 116 /* StaticKeyword */: + case 105 /* VarKeyword */: + case 117 /* YieldKeyword */: + return true; + case 121 /* AsyncKeyword */: + return ts.isPropertyDeclaration(contextToken.parent); + } + return ts.isDeclarationName(contextToken) + && !ts.isJsxAttribute(contextToken.parent) + // Don't block completions if we're in `class C /**/`, because we're *past* the end of the identifier and might want to complete `extends`. + // If `contextToken !== previousToken`, this is `class C ex/**/`. + && !(ts.isClassLike(contextToken.parent) && (contextToken !== previousToken || position > previousToken.end)); + } + function isFunctionLikeButNotConstructor(kind) { + return ts.isFunctionLikeKind(kind) && kind !== 157 /* Constructor */; + } + function isDotOfNumericLiteral(contextToken) { + if (contextToken.kind === 8 /* NumericLiteral */) { + var text = contextToken.getFullText(); + return text.charAt(text.length - 1) === "."; + } + return false; + } + /** + * Filters out completion suggestions for named imports or exports. + * + * @returns Symbols to be suggested in an object binding pattern or object literal expression, barring those whose declarations + * do not occur at the current position and have not otherwise been typed. + */ + function filterObjectMembersList(contextualMemberSymbols, existingMembers) { + if (existingMembers.length === 0) { + return contextualMemberSymbols; + } + var existingMemberNames = ts.createUnderscoreEscapedMap(); + for (var _i = 0, existingMembers_1 = existingMembers; _i < existingMembers_1.length; _i++) { + var m = existingMembers_1[_i]; + // Ignore omitted expressions for missing members + if (m.kind !== 275 /* PropertyAssignment */ && + m.kind !== 276 /* ShorthandPropertyAssignment */ && + m.kind !== 186 /* BindingElement */ && + m.kind !== 156 /* MethodDeclaration */ && + m.kind !== 158 /* GetAccessor */ && + m.kind !== 159 /* SetAccessor */) { + continue; + } + // If this is the current item we are editing right now, do not filter it out + if (isCurrentlyEditingNode(m)) { + continue; + } + var existingName = void 0; + if (ts.isBindingElement(m) && m.propertyName) { + // include only identifiers in completion list + if (m.propertyName.kind === 72 /* Identifier */) { + existingName = m.propertyName.escapedText; + } + } + else { + // TODO: Account for computed property name + // NOTE: if one only performs this step when m.name is an identifier, + // things like '__proto__' are not filtered out. + var name = ts.getNameOfDeclaration(m); + existingName = name && ts.isPropertyNameLiteral(name) ? ts.getEscapedTextOfIdentifierOrLiteral(name) : undefined; + } + existingMemberNames.set(existingName, true); // TODO: GH#18217 + } + return contextualMemberSymbols.filter(function (m) { return !existingMemberNames.get(m.escapedName); }); + } + /** + * Filters out completion suggestions for class elements. + * + * @returns Symbols to be suggested in an class element depending on existing memebers and symbol flags + */ + function filterClassMembersList(baseSymbols, existingMembers, currentClassElementModifierFlags) { + var existingMemberNames = ts.createUnderscoreEscapedMap(); + for (var _i = 0, existingMembers_2 = existingMembers; _i < existingMembers_2.length; _i++) { + var m = existingMembers_2[_i]; + // Ignore omitted expressions for missing members + if (m.kind !== 154 /* PropertyDeclaration */ && + m.kind !== 156 /* MethodDeclaration */ && + m.kind !== 158 /* GetAccessor */ && + m.kind !== 159 /* SetAccessor */) { + continue; + } + // If this is the current item we are editing right now, do not filter it out + if (isCurrentlyEditingNode(m)) { + continue; + } + // Dont filter member even if the name matches if it is declared private in the list + if (ts.hasModifier(m, 8 /* Private */)) { + continue; + } + // do not filter it out if the static presence doesnt match + if (ts.hasModifier(m, 32 /* Static */) !== !!(currentClassElementModifierFlags & 32 /* Static */)) { + continue; + } + var existingName = ts.getPropertyNameForPropertyNameNode(m.name); + if (existingName) { + existingMemberNames.set(existingName, true); + } + } + return baseSymbols.filter(function (propertySymbol) { + return !existingMemberNames.has(propertySymbol.escapedName) && + !!propertySymbol.declarations && + !(ts.getDeclarationModifierFlagsFromSymbol(propertySymbol) & 8 /* Private */); + }); + } + /** + * Filters out completion suggestions from 'symbols' according to existing JSX attributes. + * + * @returns Symbols to be suggested in a JSX element, barring those whose attributes + * do not occur at the current position and have not otherwise been typed. + */ + function filterJsxAttributes(symbols, attributes) { + var seenNames = ts.createUnderscoreEscapedMap(); + for (var _i = 0, attributes_1 = attributes; _i < attributes_1.length; _i++) { + var attr = attributes_1[_i]; + // If this is the current item we are editing right now, do not filter it out + if (isCurrentlyEditingNode(attr)) { + continue; + } + if (attr.kind === 267 /* JsxAttribute */) { + seenNames.set(attr.name.escapedText, true); + } + } + return symbols.filter(function (a) { return !seenNames.get(a.escapedName); }); + } + function isCurrentlyEditingNode(node) { + return node.getStart(sourceFile) <= position && position <= node.getEnd(); + } + } + function getCompletionEntryDisplayNameForSymbol(symbol, target, origin, kind) { + var name = getSymbolName(symbol, origin, target); + if (name === undefined + // If the symbol is external module, don't show it in the completion list + // (i.e declare module "http" { const x; } | // <= request completion here, "http" should not be there) + || symbol.flags & 1536 /* Module */ && ts.startsWithQuote(name) + // If the symbol is the internal name of an ES symbol, it is not a valid entry. Internal names for ES symbols start with "__@" + || ts.isKnownSymbol(symbol)) { + return undefined; + } + var validIdentiferResult = { name: name, needsConvertPropertyAccess: false }; + if (ts.isIdentifierText(name, target)) + return validIdentiferResult; + switch (kind) { + case 3 /* MemberLike */: + return undefined; + case 0 /* ObjectPropertyDeclaration */: + // TODO: GH#18169 + return { name: JSON.stringify(name), needsConvertPropertyAccess: false }; + case 2 /* PropertyAccess */: + case 1 /* Global */: // For a 'this.' completion it will be in a global context, but may have a non-identifier name. + // Don't add a completion for a name starting with a space. See https://github.com/Microsoft/TypeScript/pull/20547 + return name.charCodeAt(0) === 32 /* space */ ? undefined : { name: name, needsConvertPropertyAccess: true }; + case 5 /* None */: + case 4 /* String */: + return validIdentiferResult; + default: + ts.Debug.assertNever(kind); + } + } + // A cache of completion entries for keywords, these do not change between sessions + var _keywordCompletions = []; + var allKeywordsCompletions = ts.memoize(function () { + var res = []; + for (var i = 73 /* FirstKeyword */; i <= 147 /* LastKeyword */; i++) { + res.push({ + name: ts.tokenToString(i), + kind: "keyword" /* keyword */, + kindModifiers: "" /* none */, + sortText: "0" + }); + } + return res; + }); + function getKeywordCompletions(keywordFilter) { + return _keywordCompletions[keywordFilter] || (_keywordCompletions[keywordFilter] = allKeywordsCompletions().filter(function (entry) { + var kind = ts.stringToToken(entry.name); + switch (keywordFilter) { + case 0 /* None */: + return false; + case 1 /* All */: + return kind === 121 /* AsyncKeyword */ || 122 /* AwaitKeyword */ || !ts.isContextualKeyword(kind) && !isClassMemberCompletionKeyword(kind) || kind === 125 /* DeclareKeyword */ || kind === 130 /* ModuleKeyword */ + || ts.isTypeKeyword(kind) && kind !== 141 /* UndefinedKeyword */; + case 2 /* ClassElementKeywords */: + return isClassMemberCompletionKeyword(kind); + case 3 /* InterfaceElementKeywords */: + return isInterfaceOrTypeLiteralCompletionKeyword(kind); + case 4 /* ConstructorParameterKeywords */: + return ts.isParameterPropertyModifier(kind); + case 5 /* FunctionLikeBodyKeywords */: + return isFunctionLikeBodyKeyword(kind); + case 6 /* TypeKeywords */: + return ts.isTypeKeyword(kind); + default: + return ts.Debug.assertNever(keywordFilter); + } + })); + } + function isInterfaceOrTypeLiteralCompletionKeyword(kind) { + return kind === 133 /* ReadonlyKeyword */; + } + function isClassMemberCompletionKeyword(kind) { + switch (kind) { + case 118 /* AbstractKeyword */: + case 124 /* ConstructorKeyword */: + case 126 /* GetKeyword */: + case 137 /* SetKeyword */: + case 121 /* AsyncKeyword */: + return true; + default: + return ts.isClassMemberModifier(kind); + } + } + function isFunctionLikeBodyKeyword(kind) { + return kind === 121 /* AsyncKeyword */ || kind === 122 /* AwaitKeyword */ || !ts.isContextualKeyword(kind) && !isClassMemberCompletionKeyword(kind); + } + function keywordForNode(node) { + return ts.isIdentifier(node) ? node.originalKeywordKind || 0 /* Unknown */ : node.kind; + } + /** Get the corresponding JSDocTag node if the position is in a jsDoc comment */ + function getJsDocTagAtPosition(node, position) { + var jsdoc = ts.findAncestor(node, ts.isJSDoc); + return jsdoc && jsdoc.tags && (ts.rangeContainsPosition(jsdoc, position) ? ts.findLast(jsdoc.tags, function (tag) { return tag.pos < position; }) : undefined); + } + function getPropertiesForObjectExpression(contextualType, obj, checker) { + return contextualType.isUnion() + ? checker.getAllPossiblePropertiesOfTypes(contextualType.types.filter(function (memberType) { + // If we're providing completions for an object literal, skip primitive, array-like, or callable types since those shouldn't be implemented by object literals. + return !(memberType.flags & 131068 /* Primitive */ || + checker.isArrayLikeType(memberType) || + ts.typeHasCallOrConstructSignatures(memberType, checker) || + checker.isTypeInvalidDueToUnionDiscriminant(memberType, obj)); + })) + : contextualType.getApparentProperties(); + } + /** + * Gets all properties on a type, but if that type is a union of several types, + * excludes array-like types or callable/constructable types. + */ + function getPropertiesForCompletion(type, checker) { + return type.isUnion() + ? ts.Debug.assertEachDefined(checker.getAllPossiblePropertiesOfTypes(type.types), "getAllPossiblePropertiesOfTypes() should all be defined") + : ts.Debug.assertEachDefined(type.getApparentProperties(), "getApparentProperties() should all be defined"); + } + /** + * Returns the immediate owning class declaration of a context token, + * on the condition that one exists and that the context implies completion should be given. + */ + function tryGetObjectTypeDeclarationCompletionContainer(sourceFile, contextToken, location) { + // class c { method() { } | method2() { } } + switch (location.kind) { + case 306 /* SyntaxList */: + return ts.tryCast(location.parent, ts.isObjectTypeDeclaration); + case 1 /* EndOfFileToken */: + var cls = ts.tryCast(ts.lastOrUndefined(ts.cast(location.parent, ts.isSourceFile).statements), ts.isObjectTypeDeclaration); + if (cls && !ts.findChildOfKind(cls, 19 /* CloseBraceToken */, sourceFile)) { + return cls; + } + } + if (!contextToken) + return undefined; + switch (contextToken.kind) { + case 26 /* SemicolonToken */: // class c {getValue(): number; | } + case 19 /* CloseBraceToken */: // class c { method() { } | } + // class c { method() { } b| } + return isFromObjectTypeDeclaration(location) && location.parent.name === location + ? location.parent.parent + : ts.tryCast(location, ts.isObjectTypeDeclaration); + case 18 /* OpenBraceToken */: // class c { | + case 27 /* CommaToken */: // class c {getValue(): number, | } + return ts.tryCast(contextToken.parent, ts.isObjectTypeDeclaration); + default: + if (!isFromObjectTypeDeclaration(contextToken)) + return undefined; + var isValidKeyword = ts.isClassLike(contextToken.parent.parent) ? isClassMemberCompletionKeyword : isInterfaceOrTypeLiteralCompletionKeyword; + return (isValidKeyword(contextToken.kind) || contextToken.kind === 40 /* AsteriskToken */ || ts.isIdentifier(contextToken) && isValidKeyword(ts.stringToToken(contextToken.text))) // TODO: GH#18217 + ? contextToken.parent.parent : undefined; + } + } + // TODO: GH#19856 Would like to return `node is Node & { parent: (ClassElement | TypeElement) & { parent: ObjectTypeDeclaration } }` but then compilation takes > 10 minutes + function isFromObjectTypeDeclaration(node) { + return node.parent && ts.isClassOrTypeElement(node.parent) && ts.isObjectTypeDeclaration(node.parent.parent); + } + function isValidTrigger(sourceFile, triggerCharacter, contextToken, position) { + switch (triggerCharacter) { + case ".": + case "@": + return true; + case '"': + case "'": + case "`": + // Only automatically bring up completions if this is an opening quote. + return !!contextToken && ts.isStringLiteralOrTemplate(contextToken) && position === contextToken.getStart(sourceFile) + 1; + case "<": + // Opening JSX tag + return !!contextToken && contextToken.kind === 28 /* LessThanToken */ && (!ts.isBinaryExpression(contextToken.parent) || binaryExpressionMayBeOpenTag(contextToken.parent)); + case "/": + return !!contextToken && (ts.isStringLiteralLike(contextToken) + ? !!ts.tryGetImportFromModuleSpecifier(contextToken) + : contextToken.kind === 42 /* SlashToken */ && ts.isJsxClosingElement(contextToken.parent)); + default: + return ts.Debug.assertNever(triggerCharacter); + } + } + function binaryExpressionMayBeOpenTag(_a) { + var left = _a.left; + return ts.nodeIsMissing(left); + } + })(Completions = ts.Completions || (ts.Completions = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var DocumentHighlights; + (function (DocumentHighlights) { + function getDocumentHighlights(program, cancellationToken, sourceFile, position, sourceFilesToSearch) { + var node = ts.getTouchingPropertyName(sourceFile, position); + if (node.parent && (ts.isJsxOpeningElement(node.parent) && node.parent.tagName === node || ts.isJsxClosingElement(node.parent))) { + // For a JSX element, just highlight the matching tag, not all references. + var _a = node.parent.parent, openingElement = _a.openingElement, closingElement = _a.closingElement; + var highlightSpans = [openingElement, closingElement].map(function (_a) { + var tagName = _a.tagName; + return getHighlightSpanForNode(tagName, sourceFile); + }); + return [{ fileName: sourceFile.fileName, highlightSpans: highlightSpans }]; + } + return getSemanticDocumentHighlights(position, node, program, cancellationToken, sourceFilesToSearch) || getSyntacticDocumentHighlights(node, sourceFile); + } + DocumentHighlights.getDocumentHighlights = getDocumentHighlights; + function getHighlightSpanForNode(node, sourceFile) { + return { + fileName: sourceFile.fileName, + textSpan: ts.createTextSpanFromNode(node, sourceFile), + kind: "none" /* none */ + }; + } + function getSemanticDocumentHighlights(position, node, program, cancellationToken, sourceFilesToSearch) { + var sourceFilesSet = ts.arrayToSet(sourceFilesToSearch, function (f) { return f.fileName; }); + var referenceEntries = ts.FindAllReferences.getReferenceEntriesForNode(position, node, program, sourceFilesToSearch, cancellationToken, /*options*/ undefined, sourceFilesSet); + if (!referenceEntries) + return undefined; + var map = ts.arrayToMultiMap(referenceEntries.map(ts.FindAllReferences.toHighlightSpan), function (e) { return e.fileName; }, function (e) { return e.span; }); + return ts.arrayFrom(map.entries(), function (_a) { + var fileName = _a[0], highlightSpans = _a[1]; + if (!sourceFilesSet.has(fileName)) { + ts.Debug.assert(program.redirectTargetsMap.has(fileName)); + var redirectTarget_1 = program.getSourceFile(fileName); + var redirect = ts.find(sourceFilesToSearch, function (f) { return !!f.redirectInfo && f.redirectInfo.redirectTarget === redirectTarget_1; }); + fileName = redirect.fileName; + ts.Debug.assert(sourceFilesSet.has(fileName)); + } + return { fileName: fileName, highlightSpans: highlightSpans }; + }); + } + function getSyntacticDocumentHighlights(node, sourceFile) { + var highlightSpans = getHighlightSpans(node, sourceFile); + return highlightSpans && [{ fileName: sourceFile.fileName, highlightSpans: highlightSpans }]; + } + function getHighlightSpans(node, sourceFile) { + switch (node.kind) { + case 91 /* IfKeyword */: + case 83 /* ElseKeyword */: + return ts.isIfStatement(node.parent) ? getIfElseOccurrences(node.parent, sourceFile) : undefined; + case 97 /* ReturnKeyword */: + return useParent(node.parent, ts.isReturnStatement, getReturnOccurrences); + case 101 /* ThrowKeyword */: + return useParent(node.parent, ts.isThrowStatement, getThrowOccurrences); + case 103 /* TryKeyword */: + case 75 /* CatchKeyword */: + case 88 /* FinallyKeyword */: + var tryStatement = node.kind === 75 /* CatchKeyword */ ? node.parent.parent : node.parent; + return useParent(tryStatement, ts.isTryStatement, getTryCatchFinallyOccurrences); + case 99 /* SwitchKeyword */: + return useParent(node.parent, ts.isSwitchStatement, getSwitchCaseDefaultOccurrences); + case 74 /* CaseKeyword */: + case 80 /* DefaultKeyword */: + return useParent(node.parent.parent.parent, ts.isSwitchStatement, getSwitchCaseDefaultOccurrences); + case 73 /* BreakKeyword */: + case 78 /* ContinueKeyword */: + return useParent(node.parent, ts.isBreakOrContinueStatement, getBreakOrContinueStatementOccurrences); + case 89 /* ForKeyword */: + case 107 /* WhileKeyword */: + case 82 /* DoKeyword */: + return useParent(node.parent, function (n) { return ts.isIterationStatement(n, /*lookInLabeledStatements*/ true); }, getLoopBreakContinueOccurrences); + case 124 /* ConstructorKeyword */: + return getFromAllDeclarations(ts.isConstructorDeclaration, [124 /* ConstructorKeyword */]); + case 126 /* GetKeyword */: + case 137 /* SetKeyword */: + return getFromAllDeclarations(ts.isAccessor, [126 /* GetKeyword */, 137 /* SetKeyword */]); + case 122 /* AwaitKeyword */: + return useParent(node.parent, ts.isAwaitExpression, getAsyncAndAwaitOccurrences); + case 121 /* AsyncKeyword */: + return highlightSpans(getAsyncAndAwaitOccurrences(node)); + case 117 /* YieldKeyword */: + return highlightSpans(getYieldOccurrences(node)); + default: + return ts.isModifierKind(node.kind) && (ts.isDeclaration(node.parent) || ts.isVariableStatement(node.parent)) + ? highlightSpans(getModifierOccurrences(node.kind, node.parent)) + : undefined; + } + function getFromAllDeclarations(nodeTest, keywords) { + return useParent(node.parent, nodeTest, function (decl) { return ts.mapDefined(decl.symbol.declarations, function (d) { + return nodeTest(d) ? ts.find(d.getChildren(sourceFile), function (c) { return ts.contains(keywords, c.kind); }) : undefined; + }); }); + } + function useParent(node, nodeTest, getNodes) { + return nodeTest(node) ? highlightSpans(getNodes(node, sourceFile)) : undefined; + } + function highlightSpans(nodes) { + return nodes && nodes.map(function (node) { return getHighlightSpanForNode(node, sourceFile); }); + } + } + /** + * Aggregates all throw-statements within this node *without* crossing + * into function boundaries and try-blocks with catch-clauses. + */ + function aggregateOwnedThrowStatements(node) { + if (ts.isThrowStatement(node)) { + return [node]; + } + else if (ts.isTryStatement(node)) { + // Exceptions thrown within a try block lacking a catch clause are "owned" in the current context. + return ts.concatenate(node.catchClause ? aggregateOwnedThrowStatements(node.catchClause) : node.tryBlock && aggregateOwnedThrowStatements(node.tryBlock), node.finallyBlock && aggregateOwnedThrowStatements(node.finallyBlock)); + } + // Do not cross function boundaries. + return ts.isFunctionLike(node) ? undefined : flatMapChildren(node, aggregateOwnedThrowStatements); + } + /** + * For lack of a better name, this function takes a throw statement and returns the + * nearest ancestor that is a try-block (whose try statement has a catch clause), + * function-block, or source file. + */ + function getThrowStatementOwner(throwStatement) { + var child = throwStatement; + while (child.parent) { + var parent = child.parent; + if (ts.isFunctionBlock(parent) || parent.kind === 279 /* SourceFile */) { + return parent; + } + // A throw-statement is only owned by a try-statement if the try-statement has + // a catch clause, and if the throw-statement occurs within the try block. + if (ts.isTryStatement(parent) && parent.tryBlock === child && parent.catchClause) { + return child; + } + child = parent; + } + return undefined; + } + function aggregateAllBreakAndContinueStatements(node) { + return ts.isBreakOrContinueStatement(node) ? [node] : ts.isFunctionLike(node) ? undefined : flatMapChildren(node, aggregateAllBreakAndContinueStatements); + } + function flatMapChildren(node, cb) { + var result = []; + node.forEachChild(function (child) { + var value = cb(child); + if (value !== undefined) { + result.push.apply(result, ts.toArray(value)); + } + }); + return result; + } + function ownsBreakOrContinueStatement(owner, statement) { + var actualOwner = getBreakOrContinueOwner(statement); + return !!actualOwner && actualOwner === owner; + } + function getBreakOrContinueOwner(statement) { + return ts.findAncestor(statement, function (node) { + switch (node.kind) { + case 232 /* SwitchStatement */: + if (statement.kind === 228 /* ContinueStatement */) { + return false; + } + // falls through + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + case 224 /* WhileStatement */: + case 223 /* DoStatement */: + return !statement.label || isLabeledBy(node, statement.label.escapedText); + default: + // Don't cross function boundaries. + // TODO: GH#20090 + return ts.isFunctionLike(node) && "quit"; + } + }); + } + function getModifierOccurrences(modifier, declaration) { + return ts.mapDefined(getNodesToSearchForModifier(declaration, ts.modifierToFlag(modifier)), function (node) { return ts.findModifier(node, modifier); }); + } + function getNodesToSearchForModifier(declaration, modifierFlag) { + // Types of node whose children might have modifiers. + var container = declaration.parent; + switch (container.kind) { + case 245 /* ModuleBlock */: + case 279 /* SourceFile */: + case 218 /* Block */: + case 271 /* CaseClause */: + case 272 /* DefaultClause */: + // Container is either a class declaration or the declaration is a classDeclaration + if (modifierFlag & 128 /* Abstract */ && ts.isClassDeclaration(declaration)) { + return declaration.members.concat([declaration]); + } + else { + return container.statements; + } + case 157 /* Constructor */: + case 156 /* MethodDeclaration */: + case 239 /* FunctionDeclaration */: + return container.parameters.concat((ts.isClassLike(container.parent) ? container.parent.members : [])); + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + var nodes = container.members; + // If we're an accessibility modifier, we're in an instance member and should search + // the constructor's parameter list for instance members as well. + if (modifierFlag & 28 /* AccessibilityModifier */) { + var constructor = ts.find(container.members, ts.isConstructorDeclaration); + if (constructor) { + return nodes.concat(constructor.parameters); + } + } + else if (modifierFlag & 128 /* Abstract */) { + return nodes.concat([container]); + } + return nodes; + default: + ts.Debug.assertNever(container, "Invalid container kind."); + } + } + function pushKeywordIf(keywordList, token) { + var expected = []; + for (var _i = 2; _i < arguments.length; _i++) { + expected[_i - 2] = arguments[_i]; + } + if (token && ts.contains(expected, token.kind)) { + keywordList.push(token); + return true; + } + return false; + } + function getLoopBreakContinueOccurrences(loopNode) { + var keywords = []; + if (pushKeywordIf(keywords, loopNode.getFirstToken(), 89 /* ForKeyword */, 107 /* WhileKeyword */, 82 /* DoKeyword */)) { + // If we succeeded and got a do-while loop, then start looking for a 'while' keyword. + if (loopNode.kind === 223 /* DoStatement */) { + var loopTokens = loopNode.getChildren(); + for (var i = loopTokens.length - 1; i >= 0; i--) { + if (pushKeywordIf(keywords, loopTokens[i], 107 /* WhileKeyword */)) { + break; + } + } + } + } + ts.forEach(aggregateAllBreakAndContinueStatements(loopNode.statement), function (statement) { + if (ownsBreakOrContinueStatement(loopNode, statement)) { + pushKeywordIf(keywords, statement.getFirstToken(), 73 /* BreakKeyword */, 78 /* ContinueKeyword */); + } + }); + return keywords; + } + function getBreakOrContinueStatementOccurrences(breakOrContinueStatement) { + var owner = getBreakOrContinueOwner(breakOrContinueStatement); + if (owner) { + switch (owner.kind) { + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + case 223 /* DoStatement */: + case 224 /* WhileStatement */: + return getLoopBreakContinueOccurrences(owner); + case 232 /* SwitchStatement */: + return getSwitchCaseDefaultOccurrences(owner); + } + } + return undefined; + } + function getSwitchCaseDefaultOccurrences(switchStatement) { + var keywords = []; + pushKeywordIf(keywords, switchStatement.getFirstToken(), 99 /* SwitchKeyword */); + // Go through each clause in the switch statement, collecting the 'case'/'default' keywords. + ts.forEach(switchStatement.caseBlock.clauses, function (clause) { + pushKeywordIf(keywords, clause.getFirstToken(), 74 /* CaseKeyword */, 80 /* DefaultKeyword */); + ts.forEach(aggregateAllBreakAndContinueStatements(clause), function (statement) { + if (ownsBreakOrContinueStatement(switchStatement, statement)) { + pushKeywordIf(keywords, statement.getFirstToken(), 73 /* BreakKeyword */); + } + }); + }); + return keywords; + } + function getTryCatchFinallyOccurrences(tryStatement, sourceFile) { + var keywords = []; + pushKeywordIf(keywords, tryStatement.getFirstToken(), 103 /* TryKeyword */); + if (tryStatement.catchClause) { + pushKeywordIf(keywords, tryStatement.catchClause.getFirstToken(), 75 /* CatchKeyword */); + } + if (tryStatement.finallyBlock) { + var finallyKeyword = ts.findChildOfKind(tryStatement, 88 /* FinallyKeyword */, sourceFile); + pushKeywordIf(keywords, finallyKeyword, 88 /* FinallyKeyword */); + } + return keywords; + } + function getThrowOccurrences(throwStatement, sourceFile) { + var owner = getThrowStatementOwner(throwStatement); + if (!owner) { + return undefined; + } + var keywords = []; + ts.forEach(aggregateOwnedThrowStatements(owner), function (throwStatement) { + keywords.push(ts.findChildOfKind(throwStatement, 101 /* ThrowKeyword */, sourceFile)); + }); + // If the "owner" is a function, then we equate 'return' and 'throw' statements in their + // ability to "jump out" of the function, and include occurrences for both. + if (ts.isFunctionBlock(owner)) { + ts.forEachReturnStatement(owner, function (returnStatement) { + keywords.push(ts.findChildOfKind(returnStatement, 97 /* ReturnKeyword */, sourceFile)); + }); + } + return keywords; + } + function getReturnOccurrences(returnStatement, sourceFile) { + var func = ts.getContainingFunction(returnStatement); + if (!func) { + return undefined; + } + var keywords = []; + ts.forEachReturnStatement(ts.cast(func.body, ts.isBlock), function (returnStatement) { + keywords.push(ts.findChildOfKind(returnStatement, 97 /* ReturnKeyword */, sourceFile)); + }); + // Include 'throw' statements that do not occur within a try block. + ts.forEach(aggregateOwnedThrowStatements(func.body), function (throwStatement) { + keywords.push(ts.findChildOfKind(throwStatement, 101 /* ThrowKeyword */, sourceFile)); + }); + return keywords; + } + function getAsyncAndAwaitOccurrences(node) { + var func = ts.getContainingFunction(node); + if (!func) { + return undefined; + } + var keywords = []; + if (func.modifiers) { + func.modifiers.forEach(function (modifier) { + pushKeywordIf(keywords, modifier, 121 /* AsyncKeyword */); + }); + } + ts.forEachChild(func, function (child) { + traverseWithoutCrossingFunction(child, function (node) { + if (ts.isAwaitExpression(node)) { + pushKeywordIf(keywords, node.getFirstToken(), 122 /* AwaitKeyword */); + } + }); + }); + return keywords; + } + function getYieldOccurrences(node) { + var func = ts.getContainingFunction(node); + if (!func) { + return undefined; + } + var keywords = []; + ts.forEachChild(func, function (child) { + traverseWithoutCrossingFunction(child, function (node) { + if (ts.isYieldExpression(node)) { + pushKeywordIf(keywords, node.getFirstToken(), 117 /* YieldKeyword */); + } + }); + }); + return keywords; + } + // Do not cross function/class/interface/module/type boundaries. + function traverseWithoutCrossingFunction(node, cb) { + cb(node); + if (!ts.isFunctionLike(node) && !ts.isClassLike(node) && !ts.isInterfaceDeclaration(node) && !ts.isModuleDeclaration(node) && !ts.isTypeAliasDeclaration(node) && !ts.isTypeNode(node)) { + ts.forEachChild(node, function (child) { return traverseWithoutCrossingFunction(child, cb); }); + } + } + function getIfElseOccurrences(ifStatement, sourceFile) { + var keywords = getIfElseKeywords(ifStatement, sourceFile); + var result = []; + // We'd like to highlight else/ifs together if they are only separated by whitespace + // (i.e. the keywords are separated by no comments, no newlines). + for (var i = 0; i < keywords.length; i++) { + if (keywords[i].kind === 83 /* ElseKeyword */ && i < keywords.length - 1) { + var elseKeyword = keywords[i]; + var ifKeyword = keywords[i + 1]; // this *should* always be an 'if' keyword. + var shouldCombineElseAndIf = true; + // Avoid recalculating getStart() by iterating backwards. + for (var j = ifKeyword.getStart(sourceFile) - 1; j >= elseKeyword.end; j--) { + if (!ts.isWhiteSpaceSingleLine(sourceFile.text.charCodeAt(j))) { + shouldCombineElseAndIf = false; + break; + } + } + if (shouldCombineElseAndIf) { + result.push({ + fileName: sourceFile.fileName, + textSpan: ts.createTextSpanFromBounds(elseKeyword.getStart(), ifKeyword.end), + kind: "reference" /* reference */ + }); + i++; // skip the next keyword + continue; + } + } + // Ordinary case: just highlight the keyword. + result.push(getHighlightSpanForNode(keywords[i], sourceFile)); + } + return result; + } + function getIfElseKeywords(ifStatement, sourceFile) { + var keywords = []; + // Traverse upwards through all parent if-statements linked by their else-branches. + while (ts.isIfStatement(ifStatement.parent) && ifStatement.parent.elseStatement === ifStatement) { + ifStatement = ifStatement.parent; + } + // Now traverse back down through the else branches, aggregating if/else keywords of if-statements. + while (true) { + var children = ifStatement.getChildren(sourceFile); + pushKeywordIf(keywords, children[0], 91 /* IfKeyword */); + // Generally the 'else' keyword is second-to-last, so we traverse backwards. + for (var i = children.length - 1; i >= 0; i--) { + if (pushKeywordIf(keywords, children[i], 83 /* ElseKeyword */)) { + break; + } + } + if (!ifStatement.elseStatement || !ts.isIfStatement(ifStatement.elseStatement)) { + break; + } + ifStatement = ifStatement.elseStatement; + } + return keywords; + } + /** + * Whether or not a 'node' is preceded by a label of the given string. + * Note: 'node' cannot be a SourceFile. + */ + function isLabeledBy(node, labelName) { + return !!ts.findAncestor(node.parent, function (owner) { return !ts.isLabeledStatement(owner) ? "quit" : owner.label.escapedText === labelName; }); + } + })(DocumentHighlights = ts.DocumentHighlights || (ts.DocumentHighlights = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + function createDocumentRegistry(useCaseSensitiveFileNames, currentDirectory) { + return createDocumentRegistryInternal(useCaseSensitiveFileNames, currentDirectory); + } + ts.createDocumentRegistry = createDocumentRegistry; + /*@internal*/ + function createDocumentRegistryInternal(useCaseSensitiveFileNames, currentDirectory, externalCache) { + if (currentDirectory === void 0) { currentDirectory = ""; } + // Maps from compiler setting target (ES3, ES5, etc.) to all the cached documents we have + // for those settings. + var buckets = ts.createMap(); + var getCanonicalFileName = ts.createGetCanonicalFileName(!!useCaseSensitiveFileNames); + function reportStats() { + var bucketInfoArray = ts.arrayFrom(buckets.keys()).filter(function (name) { return name && name.charAt(0) === "_"; }).map(function (name) { + var entries = buckets.get(name); + var sourceFiles = []; + entries.forEach(function (entry, name) { + sourceFiles.push({ + name: name, + refCount: entry.languageServiceRefCount + }); + }); + sourceFiles.sort(function (x, y) { return y.refCount - x.refCount; }); + return { + bucket: name, + sourceFiles: sourceFiles + }; + }); + return JSON.stringify(bucketInfoArray, undefined, 2); + } + function acquireDocument(fileName, compilationSettings, scriptSnapshot, version, scriptKind) { + var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); + var key = getKeyForCompilationSettings(compilationSettings); + return acquireDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind); + } + function acquireDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind) { + return acquireOrUpdateDocument(fileName, path, compilationSettings, key, scriptSnapshot, version, /*acquiring*/ true, scriptKind); + } + function updateDocument(fileName, compilationSettings, scriptSnapshot, version, scriptKind) { + var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); + var key = getKeyForCompilationSettings(compilationSettings); + return updateDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind); + } + function updateDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind) { + return acquireOrUpdateDocument(fileName, path, compilationSettings, key, scriptSnapshot, version, /*acquiring*/ false, scriptKind); + } + function acquireOrUpdateDocument(fileName, path, compilationSettings, key, scriptSnapshot, version, acquiring, scriptKind) { + var bucket = ts.getOrUpdate(buckets, key, ts.createMap); + var entry = bucket.get(path); + var scriptTarget = scriptKind === 6 /* JSON */ ? 100 /* JSON */ : compilationSettings.target || 1 /* ES5 */; + if (!entry && externalCache) { + var sourceFile = externalCache.getDocument(key, path); + if (sourceFile) { + ts.Debug.assert(acquiring); + entry = { + sourceFile: sourceFile, + languageServiceRefCount: 0 + }; + bucket.set(path, entry); + } + } + if (!entry) { + // Have never seen this file with these settings. Create a new source file for it. + var sourceFile = ts.createLanguageServiceSourceFile(fileName, scriptSnapshot, scriptTarget, version, /*setNodeParents*/ false, scriptKind); + if (externalCache) { + externalCache.setDocument(key, path, sourceFile); + } + entry = { + sourceFile: sourceFile, + languageServiceRefCount: 1, + }; + bucket.set(path, entry); + } + else { + // We have an entry for this file. However, it may be for a different version of + // the script snapshot. If so, update it appropriately. Otherwise, we can just + // return it as is. + if (entry.sourceFile.version !== version) { + entry.sourceFile = ts.updateLanguageServiceSourceFile(entry.sourceFile, scriptSnapshot, version, scriptSnapshot.getChangeRange(entry.sourceFile.scriptSnapshot)); // TODO: GH#18217 + if (externalCache) { + externalCache.setDocument(key, path, entry.sourceFile); + } + } + // If we're acquiring, then this is the first time this LS is asking for this document. + // Increase our ref count so we know there's another LS using the document. If we're + // not acquiring, then that means the LS is 'updating' the file instead, and that means + // it has already acquired the document previously. As such, we do not need to increase + // the ref count. + if (acquiring) { + entry.languageServiceRefCount++; + } + } + ts.Debug.assert(entry.languageServiceRefCount !== 0); + return entry.sourceFile; + } + function releaseDocument(fileName, compilationSettings) { + var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); + var key = getKeyForCompilationSettings(compilationSettings); + return releaseDocumentWithKey(path, key); + } + function releaseDocumentWithKey(path, key) { + var bucket = ts.Debug.assertDefined(buckets.get(key)); + var entry = bucket.get(path); + entry.languageServiceRefCount--; + ts.Debug.assert(entry.languageServiceRefCount >= 0); + if (entry.languageServiceRefCount === 0) { + bucket.delete(path); + } + } + function getLanguageServiceRefCounts(path) { + return ts.arrayFrom(buckets.entries(), function (_a) { + var key = _a[0], bucket = _a[1]; + var entry = bucket.get(path); + return [key, entry && entry.languageServiceRefCount]; + }); + } + return { + acquireDocument: acquireDocument, + acquireDocumentWithKey: acquireDocumentWithKey, + updateDocument: updateDocument, + updateDocumentWithKey: updateDocumentWithKey, + releaseDocument: releaseDocument, + releaseDocumentWithKey: releaseDocumentWithKey, + getLanguageServiceRefCounts: getLanguageServiceRefCounts, + reportStats: reportStats, + getKeyForCompilationSettings: getKeyForCompilationSettings + }; + } + ts.createDocumentRegistryInternal = createDocumentRegistryInternal; + function getKeyForCompilationSettings(settings) { + return ts.sourceFileAffectingCompilerOptions.map(function (option) { return ts.getCompilerOptionValue(settings, option); }).join("|"); + } +})(ts || (ts = {})); +/* Code for finding imports of an exported symbol. Used only by FindAllReferences. */ +/* @internal */ +var ts; +(function (ts) { + var FindAllReferences; + (function (FindAllReferences) { + /** Creates the imports map and returns an ImportTracker that uses it. Call this lazily to avoid calling `getDirectImportsMap` unnecessarily. */ + function createImportTracker(sourceFiles, sourceFilesSet, checker, cancellationToken) { + var allDirectImports = getDirectImportsMap(sourceFiles, checker, cancellationToken); + return function (exportSymbol, exportInfo, isForRename) { + var _a = getImportersForExport(sourceFiles, sourceFilesSet, allDirectImports, exportInfo, checker, cancellationToken), directImports = _a.directImports, indirectUsers = _a.indirectUsers; + return __assign({ indirectUsers: indirectUsers }, getSearchesFromDirectImports(directImports, exportSymbol, exportInfo.exportKind, checker, isForRename)); + }; + } + FindAllReferences.createImportTracker = createImportTracker; + var ExportKind; + (function (ExportKind) { + ExportKind[ExportKind["Named"] = 0] = "Named"; + ExportKind[ExportKind["Default"] = 1] = "Default"; + ExportKind[ExportKind["ExportEquals"] = 2] = "ExportEquals"; + })(ExportKind = FindAllReferences.ExportKind || (FindAllReferences.ExportKind = {})); + var ImportExport; + (function (ImportExport) { + ImportExport[ImportExport["Import"] = 0] = "Import"; + ImportExport[ImportExport["Export"] = 1] = "Export"; + })(ImportExport = FindAllReferences.ImportExport || (FindAllReferences.ImportExport = {})); + /** Returns import statements that directly reference the exporting module, and a list of files that may access the module through a namespace. */ + function getImportersForExport(sourceFiles, sourceFilesSet, allDirectImports, _a, checker, cancellationToken) { + var exportingModuleSymbol = _a.exportingModuleSymbol, exportKind = _a.exportKind; + var markSeenDirectImport = ts.nodeSeenTracker(); + var markSeenIndirectUser = ts.nodeSeenTracker(); + var directImports = []; + var isAvailableThroughGlobal = !!exportingModuleSymbol.globalExports; + var indirectUserDeclarations = isAvailableThroughGlobal ? undefined : []; + handleDirectImports(exportingModuleSymbol); + return { directImports: directImports, indirectUsers: getIndirectUsers() }; + function getIndirectUsers() { + if (isAvailableThroughGlobal) { + // It has `export as namespace`, so anything could potentially use it. + return sourceFiles; + } + // Module augmentations may use this module's exports without importing it. + for (var _i = 0, _a = exportingModuleSymbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + if (ts.isExternalModuleAugmentation(decl) && sourceFilesSet.has(decl.getSourceFile().fileName)) { + addIndirectUser(decl); + } + } + // This may return duplicates (if there are multiple module declarations in a single source file, all importing the same thing as a namespace), but `State.markSearchedSymbol` will handle that. + return indirectUserDeclarations.map(ts.getSourceFileOfNode); + } + function handleDirectImports(exportingModuleSymbol) { + var theseDirectImports = getDirectImports(exportingModuleSymbol); + if (theseDirectImports) { + for (var _i = 0, theseDirectImports_1 = theseDirectImports; _i < theseDirectImports_1.length; _i++) { + var direct = theseDirectImports_1[_i]; + if (!markSeenDirectImport(direct)) { + continue; + } + if (cancellationToken) + cancellationToken.throwIfCancellationRequested(); + switch (direct.kind) { + case 191 /* CallExpression */: + if (!isAvailableThroughGlobal) { + var parent = direct.parent; + if (exportKind === 2 /* ExportEquals */ && parent.kind === 237 /* VariableDeclaration */) { + var name = parent.name; + if (name.kind === 72 /* Identifier */) { + directImports.push(name); + break; + } + } + // Don't support re-exporting 'require()' calls, so just add a single indirect user. + addIndirectUser(direct.getSourceFile()); + } + break; + case 72 /* Identifier */: // for 'const x = require("y"); + break; // TODO: GH#23879 + case 248 /* ImportEqualsDeclaration */: + handleNamespaceImport(direct, direct.name, ts.hasModifier(direct, 1 /* Export */), /*alreadyAddedDirect*/ false); + break; + case 249 /* ImportDeclaration */: + directImports.push(direct); + var namedBindings = direct.importClause && direct.importClause.namedBindings; + if (namedBindings && namedBindings.kind === 251 /* NamespaceImport */) { + handleNamespaceImport(direct, namedBindings.name, /*isReExport*/ false, /*alreadyAddedDirect*/ true); + } + else if (!isAvailableThroughGlobal && ts.isDefaultImport(direct)) { + addIndirectUser(getSourceFileLikeForImportDeclaration(direct)); // Add a check for indirect uses to handle synthetic default imports + } + break; + case 255 /* ExportDeclaration */: + if (!direct.exportClause) { + // This is `export * from "foo"`, so imports of this module may import the export too. + handleDirectImports(getContainingModuleSymbol(direct, checker)); + } + else { + // This is `export { foo } from "foo"` and creates an alias symbol, so recursive search will get handle re-exports. + directImports.push(direct); + } + break; + case 183 /* ImportType */: + directImports.push(direct); + break; + default: + ts.Debug.assertNever(direct, "Unexpected import kind: " + ts.Debug.showSyntaxKind(direct)); + } + } + } + } + function handleNamespaceImport(importDeclaration, name, isReExport, alreadyAddedDirect) { + if (exportKind === 2 /* ExportEquals */) { + // This is a direct import, not import-as-namespace. + if (!alreadyAddedDirect) + directImports.push(importDeclaration); + } + else if (!isAvailableThroughGlobal) { + var sourceFileLike = getSourceFileLikeForImportDeclaration(importDeclaration); + ts.Debug.assert(sourceFileLike.kind === 279 /* SourceFile */ || sourceFileLike.kind === 244 /* ModuleDeclaration */); + if (isReExport || findNamespaceReExports(sourceFileLike, name, checker)) { + addIndirectUsers(sourceFileLike); + } + else { + addIndirectUser(sourceFileLike); + } + } + } + function addIndirectUser(sourceFileLike) { + ts.Debug.assert(!isAvailableThroughGlobal); + var isNew = markSeenIndirectUser(sourceFileLike); + if (isNew) { + indirectUserDeclarations.push(sourceFileLike); // TODO: GH#18217 + } + return isNew; + } + /** Adds a module and all of its transitive dependencies as possible indirect users. */ + function addIndirectUsers(sourceFileLike) { + if (!addIndirectUser(sourceFileLike)) { + return; + } + var moduleSymbol = checker.getMergedSymbol(sourceFileLike.symbol); + ts.Debug.assert(!!(moduleSymbol.flags & 1536 /* Module */)); + var directImports = getDirectImports(moduleSymbol); + if (directImports) { + for (var _i = 0, directImports_1 = directImports; _i < directImports_1.length; _i++) { + var directImport = directImports_1[_i]; + addIndirectUsers(getSourceFileLikeForImportDeclaration(directImport)); + } + } + } + function getDirectImports(moduleSymbol) { + return allDirectImports.get(ts.getSymbolId(moduleSymbol).toString()); + } + } + /** + * Given the set of direct imports of a module, we need to find which ones import the particular exported symbol. + * The returned `importSearches` will result in the entire source file being searched. + * But re-exports will be placed in 'singleReferences' since they cannot be locally referenced. + */ + function getSearchesFromDirectImports(directImports, exportSymbol, exportKind, checker, isForRename) { + var importSearches = []; + var singleReferences = []; + function addSearch(location, symbol) { + importSearches.push([location, symbol]); + } + if (directImports) { + for (var _i = 0, directImports_2 = directImports; _i < directImports_2.length; _i++) { + var decl = directImports_2[_i]; + handleImport(decl); + } + } + return { importSearches: importSearches, singleReferences: singleReferences }; + function handleImport(decl) { + if (decl.kind === 248 /* ImportEqualsDeclaration */) { + if (isExternalModuleImportEquals(decl)) { + handleNamespaceImportLike(decl.name); + } + return; + } + if (decl.kind === 72 /* Identifier */) { + handleNamespaceImportLike(decl); + return; + } + if (decl.kind === 183 /* ImportType */) { + if (decl.qualifier) { + if (ts.isIdentifier(decl.qualifier) && decl.qualifier.escapedText === ts.symbolName(exportSymbol)) { + singleReferences.push(decl.qualifier); + } + } + else if (exportKind === 2 /* ExportEquals */) { + singleReferences.push(decl.argument.literal); + } + return; + } + // Ignore if there's a grammar error + if (decl.moduleSpecifier.kind !== 10 /* StringLiteral */) { + return; + } + if (decl.kind === 255 /* ExportDeclaration */) { + searchForNamedImport(decl.exportClause); + return; + } + var _a = decl.importClause || { name: undefined, namedBindings: undefined }, name = _a.name, namedBindings = _a.namedBindings; + if (namedBindings) { + switch (namedBindings.kind) { + case 251 /* NamespaceImport */: + handleNamespaceImportLike(namedBindings.name); + break; + case 252 /* NamedImports */: + // 'default' might be accessed as a named import `{ default as foo }`. + if (exportKind === 0 /* Named */ || exportKind === 1 /* Default */) { + searchForNamedImport(namedBindings); + } + break; + default: + ts.Debug.assertNever(namedBindings); + } + } + // `export =` might be imported by a default import if `--allowSyntheticDefaultImports` is on, so this handles both ExportKind.Default and ExportKind.ExportEquals. + // If a default import has the same name as the default export, allow to rename it. + // Given `import f` and `export default function f`, we will rename both, but for `import g` we will rename just that. + if (name && (exportKind === 1 /* Default */ || exportKind === 2 /* ExportEquals */) && (!isForRename || name.escapedText === ts.symbolEscapedNameNoDefault(exportSymbol))) { + var defaultImportAlias = checker.getSymbolAtLocation(name); + addSearch(name, defaultImportAlias); + } + } + /** + * `import x = require("./x") or `import * as x from "./x"`. + * An `export =` may be imported by this syntax, so it may be a direct import. + * If it's not a direct import, it will be in `indirectUsers`, so we don't have to do anything here. + */ + function handleNamespaceImportLike(importName) { + // Don't rename an import that already has a different name than the export. + if (exportKind === 2 /* ExportEquals */ && (!isForRename || isNameMatch(importName.escapedText))) { + addSearch(importName, checker.getSymbolAtLocation(importName)); + } + } + function searchForNamedImport(namedBindings) { + if (!namedBindings) { + return; + } + for (var _i = 0, _a = namedBindings.elements; _i < _a.length; _i++) { + var element = _a[_i]; + var name = element.name, propertyName = element.propertyName; + if (!isNameMatch((propertyName || name).escapedText)) { + continue; + } + if (propertyName) { + // This is `import { foo as bar } from "./a"` or `export { foo as bar } from "./a"`. `foo` isn't a local in the file, so just add it as a single reference. + singleReferences.push(propertyName); + // If renaming `{ foo as bar }`, don't touch `bar`, just `foo`. + // But do rename `foo` in ` { default as foo }` if that's the original export name. + if (!isForRename || name.escapedText === exportSymbol.escapedName) { + // Search locally for `bar`. + addSearch(name, checker.getSymbolAtLocation(name)); + } + } + else { + var localSymbol = element.kind === 257 /* ExportSpecifier */ && element.propertyName + ? checker.getExportSpecifierLocalTargetSymbol(element) // For re-exporting under a different name, we want to get the re-exported symbol. + : checker.getSymbolAtLocation(name); + addSearch(name, localSymbol); + } + } + } + function isNameMatch(name) { + // Use name of "default" even in `export =` case because we may have allowSyntheticDefaultImports + return name === exportSymbol.escapedName || exportKind !== 0 /* Named */ && name === "default" /* Default */; + } + } + /** Returns 'true' is the namespace 'name' is re-exported from this module, and 'false' if it is only used locally. */ + function findNamespaceReExports(sourceFileLike, name, checker) { + var namespaceImportSymbol = checker.getSymbolAtLocation(name); + return !!forEachPossibleImportOrExportStatement(sourceFileLike, function (statement) { + if (!ts.isExportDeclaration(statement)) + return; + var exportClause = statement.exportClause, moduleSpecifier = statement.moduleSpecifier; + return !moduleSpecifier && exportClause && + exportClause.elements.some(function (element) { return checker.getExportSpecifierLocalTargetSymbol(element) === namespaceImportSymbol; }); + }); + } + function findModuleReferences(program, sourceFiles, searchModuleSymbol) { + var refs = []; + var checker = program.getTypeChecker(); + for (var _i = 0, sourceFiles_3 = sourceFiles; _i < sourceFiles_3.length; _i++) { + var referencingFile = sourceFiles_3[_i]; + var searchSourceFile = searchModuleSymbol.valueDeclaration; + if (searchSourceFile.kind === 279 /* SourceFile */) { + for (var _a = 0, _b = referencingFile.referencedFiles; _a < _b.length; _a++) { + var ref = _b[_a]; + if (program.getSourceFileFromReference(referencingFile, ref) === searchSourceFile) { + refs.push({ kind: "reference", referencingFile: referencingFile, ref: ref }); + } + } + for (var _c = 0, _d = referencingFile.typeReferenceDirectives; _c < _d.length; _c++) { + var ref = _d[_c]; + var referenced = program.getResolvedTypeReferenceDirectives().get(ref.fileName); + if (referenced !== undefined && referenced.resolvedFileName === searchSourceFile.fileName) { + refs.push({ kind: "reference", referencingFile: referencingFile, ref: ref }); + } + } + } + forEachImport(referencingFile, function (_importDecl, moduleSpecifier) { + var moduleSymbol = checker.getSymbolAtLocation(moduleSpecifier); + if (moduleSymbol === searchModuleSymbol) { + refs.push({ kind: "import", literal: moduleSpecifier }); + } + }); + } + return refs; + } + FindAllReferences.findModuleReferences = findModuleReferences; + /** Returns a map from a module symbol Id to all import statements that directly reference the module. */ + function getDirectImportsMap(sourceFiles, checker, cancellationToken) { + var map = ts.createMap(); + for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) { + var sourceFile = sourceFiles_4[_i]; + if (cancellationToken) + cancellationToken.throwIfCancellationRequested(); + forEachImport(sourceFile, function (importDecl, moduleSpecifier) { + var moduleSymbol = checker.getSymbolAtLocation(moduleSpecifier); + if (moduleSymbol) { + var id = ts.getSymbolId(moduleSymbol).toString(); + var imports = map.get(id); + if (!imports) { + map.set(id, imports = []); + } + imports.push(importDecl); + } + }); + } + return map; + } + /** Iterates over all statements at the top level or in module declarations. Returns the first truthy result. */ + function forEachPossibleImportOrExportStatement(sourceFileLike, action) { + return ts.forEach(sourceFileLike.kind === 279 /* SourceFile */ ? sourceFileLike.statements : sourceFileLike.body.statements, function (statement) { + return action(statement) || (isAmbientModuleDeclaration(statement) && ts.forEach(statement.body && statement.body.statements, action)); + }); + } + /** Calls `action` for each import, re-export, or require() in a file. */ + function forEachImport(sourceFile, action) { + if (sourceFile.externalModuleIndicator || sourceFile.imports !== undefined) { + for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { + var i = _a[_i]; + action(ts.importFromModuleSpecifier(i), i); + } + } + else { + forEachPossibleImportOrExportStatement(sourceFile, function (statement) { + switch (statement.kind) { + case 255 /* ExportDeclaration */: + case 249 /* ImportDeclaration */: { + var decl = statement; + if (decl.moduleSpecifier && ts.isStringLiteral(decl.moduleSpecifier)) { + action(decl, decl.moduleSpecifier); + } + break; + } + case 248 /* ImportEqualsDeclaration */: { + var decl = statement; + if (isExternalModuleImportEquals(decl)) { + action(decl, decl.moduleReference.expression); + } + break; + } + } + }); + } + } + /** + * Given a local reference, we might notice that it's an import/export and recursively search for references of that. + * If at an import, look locally for the symbol it imports. + * If an an export, look for all imports of it. + * This doesn't handle export specifiers; that is done in `getReferencesAtExportSpecifier`. + * @param comingFromExport If we are doing a search for all exports, don't bother looking backwards for the imported symbol, since that's the reason we're here. + */ + function getImportOrExportSymbol(node, symbol, checker, comingFromExport) { + return comingFromExport ? getExport() : getExport() || getImport(); + function getExport() { + var parent = node.parent; + var grandParent = parent.parent; + if (symbol.exportSymbol) { + if (parent.kind === 189 /* PropertyAccessExpression */) { + // When accessing an export of a JS module, there's no alias. The symbol will still be flagged as an export even though we're at the use. + // So check that we are at the declaration. + return symbol.declarations.some(function (d) { return d === parent; }) && ts.isBinaryExpression(grandParent) + ? getSpecialPropertyExport(grandParent, /*useLhsSymbol*/ false) + : undefined; + } + else { + return exportInfo(symbol.exportSymbol, getExportKindForDeclaration(parent)); + } + } + else { + var exportNode = getExportNode(parent, node); + if (exportNode && ts.hasModifier(exportNode, 1 /* Export */)) { + if (ts.isImportEqualsDeclaration(exportNode) && exportNode.moduleReference === node) { + // We're at `Y` in `export import X = Y`. This is not the exported symbol, the left-hand-side is. So treat this as an import statement. + if (comingFromExport) { + return undefined; + } + var lhsSymbol = checker.getSymbolAtLocation(exportNode.name); + return { kind: 0 /* Import */, symbol: lhsSymbol }; + } + else { + return exportInfo(symbol, getExportKindForDeclaration(exportNode)); + } + } + // If we are in `export = a;` or `export default a;`, `parent` is the export assignment. + else if (ts.isExportAssignment(parent)) { + return getExportAssignmentExport(parent); + } + // If we are in `export = class A {};` (or `export = class A {};`) at `A`, `parent.parent` is the export assignment. + else if (ts.isExportAssignment(grandParent)) { + return getExportAssignmentExport(grandParent); + } + // Similar for `module.exports =` and `exports.A =`. + else if (ts.isBinaryExpression(parent)) { + return getSpecialPropertyExport(parent, /*useLhsSymbol*/ true); + } + else if (ts.isBinaryExpression(grandParent)) { + return getSpecialPropertyExport(grandParent, /*useLhsSymbol*/ true); + } + else if (ts.isJSDocTypedefTag(parent)) { + return exportInfo(symbol, 0 /* Named */); + } + } + function getExportAssignmentExport(ex) { + // Get the symbol for the `export =` node; its parent is the module it's the export of. + var exportingModuleSymbol = ts.Debug.assertDefined(ex.symbol.parent, "Expected export symbol to have a parent"); + var exportKind = ex.isExportEquals ? 2 /* ExportEquals */ : 1 /* Default */; + return { kind: 1 /* Export */, symbol: symbol, exportInfo: { exportingModuleSymbol: exportingModuleSymbol, exportKind: exportKind } }; + } + function getSpecialPropertyExport(node, useLhsSymbol) { + var kind; + switch (ts.getAssignmentDeclarationKind(node)) { + case 1 /* ExportsProperty */: + kind = 0 /* Named */; + break; + case 2 /* ModuleExports */: + kind = 2 /* ExportEquals */; + break; + default: + return undefined; + } + var sym = useLhsSymbol ? checker.getSymbolAtLocation(ts.cast(node.left, ts.isPropertyAccessExpression).name) : symbol; + // Better detection for GH#20803 + if (sym && !(checker.getMergedSymbol(sym.parent).flags & 1536 /* Module */)) { + ts.Debug.fail("Special property assignment kind does not have a module as its parent. Assignment is " + ts.Debug.showSymbol(sym) + ", parent is " + ts.Debug.showSymbol(sym.parent)); + } + return sym && exportInfo(sym, kind); + } + } + function getImport() { + var isImport = isNodeImport(node); + if (!isImport) + return undefined; + // A symbol being imported is always an alias. So get what that aliases to find the local symbol. + var importedSymbol = checker.getImmediateAliasedSymbol(symbol); + if (!importedSymbol) + return undefined; + // Search on the local symbol in the exporting module, not the exported symbol. + importedSymbol = skipExportSpecifierSymbol(importedSymbol, checker); + // Similarly, skip past the symbol for 'export =' + if (importedSymbol.escapedName === "export=") { + importedSymbol = getExportEqualsLocalSymbol(importedSymbol, checker); + } + // If the import has a different name than the export, do not continue searching. + // If `importedName` is undefined, do continue searching as the export is anonymous. + // (All imports returned from this function will be ignored anyway if we are in rename and this is a not a named export.) + var importedName = ts.symbolEscapedNameNoDefault(importedSymbol); + if (importedName === undefined || importedName === "default" /* Default */ || importedName === symbol.escapedName) { + return { kind: 0 /* Import */, symbol: importedSymbol }; + } + } + function exportInfo(symbol, kind) { + var exportInfo = getExportInfo(symbol, kind, checker); + return exportInfo && { kind: 1 /* Export */, symbol: symbol, exportInfo: exportInfo }; + } + // Not meant for use with export specifiers or export assignment. + function getExportKindForDeclaration(node) { + return ts.hasModifier(node, 512 /* Default */) ? 1 /* Default */ : 0 /* Named */; + } + } + FindAllReferences.getImportOrExportSymbol = getImportOrExportSymbol; + function getExportEqualsLocalSymbol(importedSymbol, checker) { + if (importedSymbol.flags & 2097152 /* Alias */) { + return ts.Debug.assertDefined(checker.getImmediateAliasedSymbol(importedSymbol)); + } + var decl = importedSymbol.valueDeclaration; + if (ts.isExportAssignment(decl)) { // `export = class {}` + return ts.Debug.assertDefined(decl.expression.symbol); + } + else if (ts.isBinaryExpression(decl)) { // `module.exports = class {}` + return ts.Debug.assertDefined(decl.right.symbol); + } + else if (ts.isSourceFile(decl)) { // json module + return ts.Debug.assertDefined(decl.symbol); + } + return ts.Debug.fail(); + } + // If a reference is a class expression, the exported node would be its parent. + // If a reference is a variable declaration, the exported node would be the variable statement. + function getExportNode(parent, node) { + if (parent.kind === 237 /* VariableDeclaration */) { + var p = parent; + return p.name !== node ? undefined : + p.parent.kind === 274 /* CatchClause */ ? undefined : p.parent.parent.kind === 219 /* VariableStatement */ ? p.parent.parent : undefined; + } + else { + return parent; + } + } + function isNodeImport(node) { + var parent = node.parent; + switch (parent.kind) { + case 248 /* ImportEqualsDeclaration */: + return parent.name === node && isExternalModuleImportEquals(parent); + case 253 /* ImportSpecifier */: + // For a rename import `{ foo as bar }`, don't search for the imported symbol. Just find local uses of `bar`. + return !parent.propertyName; + case 250 /* ImportClause */: + case 251 /* NamespaceImport */: + ts.Debug.assert(parent.name === node); + return true; + default: + return false; + } + } + function getExportInfo(exportSymbol, exportKind, checker) { + var moduleSymbol = exportSymbol.parent; + if (!moduleSymbol) + return undefined; // This can happen if an `export` is not at the top-level (which is a compile error). + var exportingModuleSymbol = checker.getMergedSymbol(moduleSymbol); // Need to get merged symbol in case there's an augmentation. + // `export` may appear in a namespace. In that case, just rely on global search. + return ts.isExternalModuleSymbol(exportingModuleSymbol) ? { exportingModuleSymbol: exportingModuleSymbol, exportKind: exportKind } : undefined; + } + FindAllReferences.getExportInfo = getExportInfo; + /** If at an export specifier, go to the symbol it refers to. */ + function skipExportSpecifierSymbol(symbol, checker) { + // For `export { foo } from './bar", there's nothing to skip, because it does not create a new alias. But `export { foo } does. + if (symbol.declarations) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (ts.isExportSpecifier(declaration) && !declaration.propertyName && !declaration.parent.parent.moduleSpecifier) { + return checker.getExportSpecifierLocalTargetSymbol(declaration); + } + } + } + return symbol; + } + function getContainingModuleSymbol(importer, checker) { + return checker.getMergedSymbol(getSourceFileLikeForImportDeclaration(importer).symbol); + } + function getSourceFileLikeForImportDeclaration(node) { + if (node.kind === 191 /* CallExpression */) { + return node.getSourceFile(); + } + var parent = node.parent; + if (parent.kind === 279 /* SourceFile */) { + return parent; + } + ts.Debug.assert(parent.kind === 245 /* ModuleBlock */); + return ts.cast(parent.parent, isAmbientModuleDeclaration); + } + function isAmbientModuleDeclaration(node) { + return node.kind === 244 /* ModuleDeclaration */ && node.name.kind === 10 /* StringLiteral */; + } + function isExternalModuleImportEquals(eq) { + return eq.moduleReference.kind === 259 /* ExternalModuleReference */ && eq.moduleReference.expression.kind === 10 /* StringLiteral */; + } + })(FindAllReferences = ts.FindAllReferences || (ts.FindAllReferences = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var FindAllReferences; + (function (FindAllReferences) { + var DefinitionKind; + (function (DefinitionKind) { + DefinitionKind[DefinitionKind["Symbol"] = 0] = "Symbol"; + DefinitionKind[DefinitionKind["Label"] = 1] = "Label"; + DefinitionKind[DefinitionKind["Keyword"] = 2] = "Keyword"; + DefinitionKind[DefinitionKind["This"] = 3] = "This"; + DefinitionKind[DefinitionKind["String"] = 4] = "String"; + })(DefinitionKind = FindAllReferences.DefinitionKind || (FindAllReferences.DefinitionKind = {})); + var EntryKind; + (function (EntryKind) { + EntryKind[EntryKind["Span"] = 0] = "Span"; + EntryKind[EntryKind["Node"] = 1] = "Node"; + EntryKind[EntryKind["StringLiteral"] = 2] = "StringLiteral"; + EntryKind[EntryKind["SearchedLocalFoundProperty"] = 3] = "SearchedLocalFoundProperty"; + EntryKind[EntryKind["SearchedPropertyFoundLocal"] = 4] = "SearchedPropertyFoundLocal"; + })(EntryKind = FindAllReferences.EntryKind || (FindAllReferences.EntryKind = {})); + function nodeEntry(node, kind) { + if (kind === void 0) { kind = 1 /* Node */; } + return { kind: kind, node: node.name || node }; + } + FindAllReferences.nodeEntry = nodeEntry; + function findReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position) { + var node = ts.getTouchingPropertyName(sourceFile, position); + var referencedSymbols = FindAllReferences.Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken); + var checker = program.getTypeChecker(); + return !referencedSymbols || !referencedSymbols.length ? undefined : ts.mapDefined(referencedSymbols, function (_a) { + var definition = _a.definition, references = _a.references; + // Only include referenced symbols that have a valid definition. + return definition && { + definition: checker.runWithCancellationToken(cancellationToken, function (checker) { return definitionToReferencedSymbolDefinitionInfo(definition, checker, node); }), + references: references.map(toReferenceEntry) + }; + }); + } + FindAllReferences.findReferencedSymbols = findReferencedSymbols; + function getImplementationsAtPosition(program, cancellationToken, sourceFiles, sourceFile, position) { + var node = ts.getTouchingPropertyName(sourceFile, position); + var referenceEntries = getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node, position); + var checker = program.getTypeChecker(); + return ts.map(referenceEntries, function (entry) { return toImplementationLocation(entry, checker); }); + } + FindAllReferences.getImplementationsAtPosition = getImplementationsAtPosition; + function getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node, position) { + if (node.kind === 279 /* SourceFile */) { + return undefined; + } + var checker = program.getTypeChecker(); + // If invoked directly on a shorthand property assignment, then return + // the declaration of the symbol being assigned (not the symbol being assigned to). + if (node.parent.kind === 276 /* ShorthandPropertyAssignment */) { + var result_7 = []; + FindAllReferences.Core.getReferenceEntriesForShorthandPropertyAssignment(node, checker, function (node) { return result_7.push(nodeEntry(node)); }); + return result_7; + } + else if (node.kind === 98 /* SuperKeyword */ || ts.isSuperProperty(node.parent)) { + // References to and accesses on the super keyword only have one possible implementation, so no + // need to "Find all References" + var symbol = checker.getSymbolAtLocation(node); + return symbol.valueDeclaration && [nodeEntry(symbol.valueDeclaration)]; + } + else { + // Perform "Find all References" and retrieve only those that are implementations + return getReferenceEntriesForNode(position, node, program, sourceFiles, cancellationToken, { implementations: true }); + } + } + function findReferenceOrRenameEntries(program, cancellationToken, sourceFiles, node, position, options, convertEntry) { + return ts.map(flattenEntries(FindAllReferences.Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options)), function (entry) { return convertEntry(entry, node, program.getTypeChecker()); }); + } + FindAllReferences.findReferenceOrRenameEntries = findReferenceOrRenameEntries; + function getReferenceEntriesForNode(position, node, program, sourceFiles, cancellationToken, options, sourceFilesSet) { + if (options === void 0) { options = {}; } + if (sourceFilesSet === void 0) { sourceFilesSet = ts.arrayToSet(sourceFiles, function (f) { return f.fileName; }); } + return flattenEntries(FindAllReferences.Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options, sourceFilesSet)); + } + FindAllReferences.getReferenceEntriesForNode = getReferenceEntriesForNode; + function flattenEntries(referenceSymbols) { + return referenceSymbols && ts.flatMap(referenceSymbols, function (r) { return r.references; }); + } + function definitionToReferencedSymbolDefinitionInfo(def, checker, originalNode) { + var info = (function () { + switch (def.type) { + case 0 /* Symbol */: { + var symbol = def.symbol; + var _a = getDefinitionKindAndDisplayParts(symbol, checker, originalNode), displayParts_1 = _a.displayParts, kind_1 = _a.kind; + var name_3 = displayParts_1.map(function (p) { return p.text; }).join(""); + return { node: symbol.declarations ? ts.getNameOfDeclaration(ts.first(symbol.declarations)) || ts.first(symbol.declarations) : originalNode, name: name_3, kind: kind_1, displayParts: displayParts_1 }; + } + case 1 /* Label */: { + var node_3 = def.node; + return { node: node_3, name: node_3.text, kind: "label" /* label */, displayParts: [ts.displayPart(node_3.text, ts.SymbolDisplayPartKind.text)] }; + } + case 2 /* Keyword */: { + var node_4 = def.node; + var name_4 = ts.tokenToString(node_4.kind); + return { node: node_4, name: name_4, kind: "keyword" /* keyword */, displayParts: [{ text: name_4, kind: "keyword" /* keyword */ }] }; + } + case 3 /* This */: { + var node_5 = def.node; + var symbol = checker.getSymbolAtLocation(node_5); + var displayParts_2 = symbol && ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, node_5.getSourceFile(), ts.getContainerNode(node_5), node_5).displayParts || [ts.textPart("this")]; + return { node: node_5, name: "this", kind: "var" /* variableElement */, displayParts: displayParts_2 }; + } + case 4 /* String */: { + var node_6 = def.node; + return { node: node_6, name: node_6.text, kind: "var" /* variableElement */, displayParts: [ts.displayPart(ts.getTextOfNode(node_6), ts.SymbolDisplayPartKind.stringLiteral)] }; + } + default: + return ts.Debug.assertNever(def); + } + })(); + var node = info.node, name = info.name, kind = info.kind, displayParts = info.displayParts; + var sourceFile = node.getSourceFile(); + return { containerKind: "" /* unknown */, containerName: "", fileName: sourceFile.fileName, kind: kind, name: name, textSpan: getTextSpan(ts.isComputedPropertyName(node) ? node.expression : node, sourceFile), displayParts: displayParts }; + } + function getDefinitionKindAndDisplayParts(symbol, checker, node) { + var meaning = FindAllReferences.Core.getIntersectingMeaningFromDeclarations(node, symbol); + var enclosingDeclaration = symbol.declarations && ts.firstOrUndefined(symbol.declarations) || node; + var _a = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, enclosingDeclaration.getSourceFile(), enclosingDeclaration, enclosingDeclaration, meaning), displayParts = _a.displayParts, symbolKind = _a.symbolKind; + return { displayParts: displayParts, kind: symbolKind }; + } + function toRenameLocation(entry, originalNode, checker) { + return __assign({}, entryToDocumentSpan(entry), getPrefixAndSuffixText(entry, originalNode, checker)); + } + FindAllReferences.toRenameLocation = toRenameLocation; + function toReferenceEntry(entry) { + var _a = entryToDocumentSpan(entry), textSpan = _a.textSpan, fileName = _a.fileName; + if (entry.kind === 0 /* Span */) { + return { textSpan: textSpan, fileName: fileName, isWriteAccess: false, isDefinition: false }; + } + var kind = entry.kind, node = entry.node; + return { + textSpan: textSpan, + fileName: fileName, + isWriteAccess: isWriteAccessForReference(node), + isDefinition: node.kind === 80 /* DefaultKeyword */ + || !!ts.getDeclarationFromName(node) + || ts.isLiteralComputedPropertyDeclarationName(node), + isInString: kind === 2 /* StringLiteral */ ? true : undefined, + }; + } + FindAllReferences.toReferenceEntry = toReferenceEntry; + function entryToDocumentSpan(entry) { + if (entry.kind === 0 /* Span */) { + return { textSpan: entry.textSpan, fileName: entry.fileName }; + } + else { + var sourceFile = entry.node.getSourceFile(); + return { textSpan: getTextSpan(entry.node, sourceFile), fileName: sourceFile.fileName }; + } + } + function getPrefixAndSuffixText(entry, originalNode, checker) { + if (entry.kind !== 0 /* Span */ && ts.isIdentifier(originalNode)) { + var node = entry.node, kind = entry.kind; + var name = originalNode.text; + var isShorthandAssignment = ts.isShorthandPropertyAssignment(node.parent); + if (isShorthandAssignment || ts.isObjectBindingElementWithoutPropertyName(node.parent)) { + var prefixColon = { prefixText: name + ": " }; + var suffixColon = { suffixText: ": " + name }; + return kind === 3 /* SearchedLocalFoundProperty */ ? prefixColon + : kind === 4 /* SearchedPropertyFoundLocal */ ? suffixColon + // In `const o = { x }; o.x`, symbolAtLocation at `x` in `{ x }` is the property symbol. + // For a binding element `const { x } = o;`, symbolAtLocation at `x` is the property symbol. + : isShorthandAssignment ? suffixColon : prefixColon; + } + else if (ts.isImportSpecifier(entry.node.parent) && !entry.node.parent.propertyName) { + // If the original symbol was using this alias, just rename the alias. + var originalSymbol = ts.isExportSpecifier(originalNode.parent) ? checker.getExportSpecifierLocalTargetSymbol(originalNode.parent) : checker.getSymbolAtLocation(originalNode); + return ts.contains(originalSymbol.declarations, entry.node.parent) ? { prefixText: name + " as " } : ts.emptyOptions; + } + else if (ts.isExportSpecifier(entry.node.parent) && !entry.node.parent.propertyName) { + return originalNode === entry.node ? { prefixText: name + " as " } : { suffixText: " as " + name }; + } + } + return ts.emptyOptions; + } + function toImplementationLocation(entry, checker) { + if (entry.kind !== 0 /* Span */) { + var node = entry.node; + var sourceFile = node.getSourceFile(); + return __assign({ textSpan: getTextSpan(node, sourceFile), fileName: sourceFile.fileName }, implementationKindDisplayParts(node, checker)); + } + else { + var textSpan = entry.textSpan, fileName = entry.fileName; + return { textSpan: textSpan, fileName: fileName, kind: "" /* unknown */, displayParts: [] }; + } + } + function implementationKindDisplayParts(node, checker) { + var symbol = checker.getSymbolAtLocation(ts.isDeclaration(node) && node.name ? node.name : node); + if (symbol) { + return getDefinitionKindAndDisplayParts(symbol, checker, node); + } + else if (node.kind === 188 /* ObjectLiteralExpression */) { + return { + kind: "interface" /* interfaceElement */, + displayParts: [ts.punctuationPart(20 /* OpenParenToken */), ts.textPart("object literal"), ts.punctuationPart(21 /* CloseParenToken */)] + }; + } + else if (node.kind === 209 /* ClassExpression */) { + return { + kind: "local class" /* localClassElement */, + displayParts: [ts.punctuationPart(20 /* OpenParenToken */), ts.textPart("anonymous local class"), ts.punctuationPart(21 /* CloseParenToken */)] + }; + } + else { + return { kind: ts.getNodeKind(node), displayParts: [] }; + } + } + function toHighlightSpan(entry) { + if (entry.kind === 0 /* Span */) { + var fileName = entry.fileName, textSpan = entry.textSpan; + return { fileName: fileName, span: { textSpan: textSpan, kind: "reference" /* reference */ } }; + } + var node = entry.node, kind = entry.kind; + var sourceFile = node.getSourceFile(); + var writeAccess = isWriteAccessForReference(node); + var span = { + textSpan: getTextSpan(node, sourceFile), + kind: writeAccess ? "writtenReference" /* writtenReference */ : "reference" /* reference */, + isInString: kind === 2 /* StringLiteral */ ? true : undefined, + }; + return { fileName: sourceFile.fileName, span: span }; + } + FindAllReferences.toHighlightSpan = toHighlightSpan; + function getTextSpan(node, sourceFile) { + var start = node.getStart(sourceFile); + var end = node.getEnd(); + if (node.kind === 10 /* StringLiteral */) { + start += 1; + end -= 1; + } + return ts.createTextSpanFromBounds(start, end); + } + /** A node is considered a writeAccess iff it is a name of a declaration or a target of an assignment */ + function isWriteAccessForReference(node) { + var decl = ts.getDeclarationFromName(node); + return !!decl && declarationIsWriteAccess(decl) || node.kind === 80 /* DefaultKeyword */ || ts.isWriteAccess(node); + } + /** + * True if 'decl' provides a value, as in `function f() {}`; + * false if 'decl' is just a location for a future write, as in 'let x;' + */ + function declarationIsWriteAccess(decl) { + // Consider anything in an ambient declaration to be a write access since it may be coming from JS. + if (!!(decl.flags & 4194304 /* Ambient */)) + return true; + switch (decl.kind) { + case 204 /* BinaryExpression */: + case 186 /* BindingElement */: + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 80 /* DefaultKeyword */: + case 243 /* EnumDeclaration */: + case 278 /* EnumMember */: + case 257 /* ExportSpecifier */: + case 250 /* ImportClause */: // default import + case 248 /* ImportEqualsDeclaration */: + case 253 /* ImportSpecifier */: + case 241 /* InterfaceDeclaration */: + case 297 /* JSDocCallbackTag */: + case 304 /* JSDocTypedefTag */: + case 267 /* JsxAttribute */: + case 244 /* ModuleDeclaration */: + case 247 /* NamespaceExportDeclaration */: + case 251 /* NamespaceImport */: + case 151 /* Parameter */: + case 276 /* ShorthandPropertyAssignment */: + case 242 /* TypeAliasDeclaration */: + case 150 /* TypeParameter */: + return true; + case 275 /* PropertyAssignment */: + // In `({ x: y } = 0);`, `x` is not a write access. (Won't call this function for `y`.) + return !ts.isArrayLiteralOrObjectLiteralDestructuringPattern(decl.parent); + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 157 /* Constructor */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + return !!decl.body; + case 237 /* VariableDeclaration */: + case 154 /* PropertyDeclaration */: + return !!decl.initializer || ts.isCatchClause(decl.parent); + case 155 /* MethodSignature */: + case 153 /* PropertySignature */: + case 305 /* JSDocPropertyTag */: + case 299 /* JSDocParameterTag */: + return false; + default: + return ts.Debug.failBadSyntaxKind(decl); + } + } + })(FindAllReferences = ts.FindAllReferences || (ts.FindAllReferences = {})); +})(ts || (ts = {})); +/** Encapsulates the core find-all-references algorithm. */ +/* @internal */ +(function (ts) { + var FindAllReferences; + (function (FindAllReferences) { + var Core; + (function (Core) { + /** Core find-all-references algorithm. Handles special cases before delegating to `getReferencedSymbolsForSymbol`. */ + function getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options, sourceFilesSet) { + if (options === void 0) { options = {}; } + if (sourceFilesSet === void 0) { sourceFilesSet = ts.arrayToSet(sourceFiles, function (f) { return f.fileName; }); } + if (ts.isSourceFile(node)) { + var reference = ts.GoToDefinition.getReferenceAtPosition(node, position, program); + var moduleSymbol = reference && program.getTypeChecker().getMergedSymbol(reference.file.symbol); + return moduleSymbol && getReferencedSymbolsForModule(program, moduleSymbol, /*excludeImportTypeOfExportEquals*/ false, sourceFiles, sourceFilesSet); + } + if (!options.implementations) { + var special = getReferencedSymbolsSpecial(node, sourceFiles, cancellationToken); + if (special) { + return special; + } + } + var checker = program.getTypeChecker(); + var symbol = checker.getSymbolAtLocation(node); + // Could not find a symbol e.g. unknown identifier + if (!symbol) { + // String literal might be a property (and thus have a symbol), so do this here rather than in getReferencedSymbolsSpecial. + return !options.implementations && ts.isStringLiteral(node) ? getReferencesForStringLiteral(node, sourceFiles, cancellationToken) : undefined; + } + if (symbol.escapedName === "export=" /* ExportEquals */) { + return getReferencedSymbolsForModule(program, symbol.parent, /*excludeImportTypeOfExportEquals*/ false, sourceFiles, sourceFilesSet); + } + var moduleReferences = ts.emptyArray; + var moduleSourceFile = isModuleSymbol(symbol); + var referencedNode = node; + if (moduleSourceFile) { + var exportEquals = symbol.exports.get("export=" /* ExportEquals */); + // If !!exportEquals, we're about to add references to `import("mod")` anyway, so don't double-count them. + moduleReferences = getReferencedSymbolsForModule(program, symbol, !!exportEquals, sourceFiles, sourceFilesSet); + if (!exportEquals || !sourceFilesSet.has(moduleSourceFile.fileName)) + return moduleReferences; + // Continue to get references to 'export ='. + symbol = ts.skipAlias(exportEquals, checker); + referencedNode = undefined; + } + return ts.concatenate(moduleReferences, getReferencedSymbolsForSymbol(symbol, referencedNode, sourceFiles, sourceFilesSet, checker, cancellationToken, options)); + } + Core.getReferencedSymbolsForNode = getReferencedSymbolsForNode; + function isModuleSymbol(symbol) { + return symbol.flags & 1536 /* Module */ ? ts.find(symbol.declarations, ts.isSourceFile) : undefined; + } + function getReferencedSymbolsForModule(program, symbol, excludeImportTypeOfExportEquals, sourceFiles, sourceFilesSet) { + ts.Debug.assert(!!symbol.valueDeclaration); + var references = ts.mapDefined(FindAllReferences.findModuleReferences(program, sourceFiles, symbol), function (reference) { + if (reference.kind === "import") { + var parent = reference.literal.parent; + if (ts.isLiteralTypeNode(parent)) { + var importType = ts.cast(parent.parent, ts.isImportTypeNode); + if (excludeImportTypeOfExportEquals && !importType.qualifier) { + return undefined; + } + } + // import("foo") with no qualifier will reference the `export =` of the module, which may be referenced anyway. + return FindAllReferences.nodeEntry(reference.literal); + } + else { + return { + kind: 0 /* Span */, + fileName: reference.referencingFile.fileName, + textSpan: ts.createTextSpanFromRange(reference.ref), + }; + } + }); + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + switch (decl.kind) { + case 279 /* SourceFile */: + // Don't include the source file itself. (This may not be ideal behavior, but awkward to include an entire file as a reference.) + break; + case 244 /* ModuleDeclaration */: + if (sourceFilesSet.has(decl.getSourceFile().fileName)) { + references.push(FindAllReferences.nodeEntry(decl.name)); + } + break; + default: + // This may be merged with something. + ts.Debug.fail("Expected a module symbol to be declared by a SourceFile or ModuleDeclaration."); + } + } + var exported = symbol.exports.get("export=" /* ExportEquals */); + if (exported) { + for (var _b = 0, _c = exported.declarations; _b < _c.length; _b++) { + var decl = _c[_b]; + var sourceFile = decl.getSourceFile(); + if (sourceFilesSet.has(sourceFile.fileName)) { + // At `module.exports = ...`, reference node is `module` + var node = ts.isBinaryExpression(decl) && ts.isPropertyAccessExpression(decl.left) + ? decl.left.expression + : ts.isExportAssignment(decl) + ? ts.Debug.assertDefined(ts.findChildOfKind(decl, 85 /* ExportKeyword */, sourceFile)) + : ts.getNameOfDeclaration(decl) || decl; + references.push(FindAllReferences.nodeEntry(node)); + } + } + } + return references.length ? [{ definition: { type: 0 /* Symbol */, symbol: symbol }, references: references }] : ts.emptyArray; + } + /** getReferencedSymbols for special node kinds. */ + function getReferencedSymbolsSpecial(node, sourceFiles, cancellationToken) { + if (ts.isTypeKeyword(node.kind)) { + return getAllReferencesForKeyword(sourceFiles, node.kind, cancellationToken); + } + // Labels + if (ts.isJumpStatementTarget(node)) { + var labelDefinition = ts.getTargetLabel(node.parent, node.text); + // if we have a label definition, look within its statement for references, if not, then + // the label is undefined and we have no results.. + return labelDefinition && getLabelReferencesInNode(labelDefinition.parent, labelDefinition); + } + else if (ts.isLabelOfLabeledStatement(node)) { + // it is a label definition and not a target, search within the parent labeledStatement + return getLabelReferencesInNode(node.parent, node); + } + if (ts.isThis(node)) { + return getReferencesForThisKeyword(node, sourceFiles, cancellationToken); + } + if (node.kind === 98 /* SuperKeyword */) { + return getReferencesForSuperKeyword(node); + } + return undefined; + } + /** Core find-all-references algorithm for a normal symbol. */ + function getReferencedSymbolsForSymbol(originalSymbol, node, sourceFiles, sourceFilesSet, checker, cancellationToken, options) { + var symbol = node && skipPastExportOrImportSpecifierOrUnion(originalSymbol, node, checker, !!options.isForRename) || originalSymbol; + // Compute the meaning from the location and the symbol it references + var searchMeaning = node ? getIntersectingMeaningFromDeclarations(node, symbol) : 7 /* All */; + var result = []; + var state = new State(sourceFiles, sourceFilesSet, node ? getSpecialSearchKind(node) : 0 /* None */, checker, cancellationToken, searchMeaning, options, result); + var exportSpecifier = !options.isForRename ? undefined : ts.find(symbol.declarations, ts.isExportSpecifier); + if (exportSpecifier) { + // When renaming at an export specifier, rename the export and not the thing being exported. + getReferencesAtExportSpecifier(exportSpecifier.name, symbol, exportSpecifier, state.createSearch(node, originalSymbol, /*comingFrom*/ undefined), state, /*addReferencesHere*/ true, /*alwaysGetReferences*/ true); + } + else if (node && node.kind === 80 /* DefaultKeyword */) { + addReference(node, symbol, state); + searchForImportsOfExport(node, symbol, { exportingModuleSymbol: ts.Debug.assertDefined(symbol.parent, "Expected export symbol to have a parent"), exportKind: 1 /* Default */ }, state); + } + else { + var search = state.createSearch(node, symbol, /*comingFrom*/ undefined, { allSearchSymbols: node ? populateSearchSymbolSet(symbol, node, checker, !!options.isForRename, !!options.implementations) : [symbol] }); + // Try to get the smallest valid scope that we can limit our search to; + // otherwise we'll need to search globally (i.e. include each file). + var scope = getSymbolScope(symbol); + if (scope) { + getReferencesInContainer(scope, scope.getSourceFile(), search, state, /*addReferencesHere*/ !(ts.isSourceFile(scope) && !ts.contains(sourceFiles, scope))); + } + else { + // Global search + for (var _i = 0, _a = state.sourceFiles; _i < _a.length; _i++) { + var sourceFile = _a[_i]; + state.cancellationToken.throwIfCancellationRequested(); + searchForName(sourceFile, search, state); + } + } + } + return result; + } + function getSpecialSearchKind(node) { + switch (node.kind) { + case 124 /* ConstructorKeyword */: + return 1 /* Constructor */; + case 72 /* Identifier */: + if (ts.isClassLike(node.parent)) { + ts.Debug.assert(node.parent.name === node); + return 2 /* Class */; + } + // falls through + default: + return 0 /* None */; + } + } + /** Handle a few special cases relating to export/import specifiers. */ + function skipPastExportOrImportSpecifierOrUnion(symbol, node, checker, isForRename) { + var parent = node.parent; + if (ts.isExportSpecifier(parent) && !isForRename) { + return getLocalSymbolForExportSpecifier(node, symbol, parent, checker); + } + // If the symbol is declared as part of a declaration like `{ type: "a" } | { type: "b" }`, use the property on the union type to get more references. + return ts.firstDefined(symbol.declarations, function (decl) { + if (!decl.parent) { + // Assertions for GH#21814. We should be handling SourceFile symbols in `getReferencedSymbolsForModule` instead of getting here. + ts.Debug.fail("Unexpected symbol at " + ts.Debug.showSyntaxKind(node) + ": " + ts.Debug.showSymbol(symbol)); + } + return ts.isTypeLiteralNode(decl.parent) && ts.isUnionTypeNode(decl.parent.parent) + ? checker.getPropertyOfType(checker.getTypeFromTypeNode(decl.parent.parent), symbol.name) + : undefined; + }); + } + var SpecialSearchKind; + (function (SpecialSearchKind) { + SpecialSearchKind[SpecialSearchKind["None"] = 0] = "None"; + SpecialSearchKind[SpecialSearchKind["Constructor"] = 1] = "Constructor"; + SpecialSearchKind[SpecialSearchKind["Class"] = 2] = "Class"; + })(SpecialSearchKind || (SpecialSearchKind = {})); + /** + * Holds all state needed for the finding references. + * Unlike `Search`, there is only one `State`. + */ + var State = /** @class */ (function () { + function State(sourceFiles, sourceFilesSet, + /** True if we're searching for constructor references. */ + specialSearchKind, checker, cancellationToken, searchMeaning, options, result) { + this.sourceFiles = sourceFiles; + this.sourceFilesSet = sourceFilesSet; + this.specialSearchKind = specialSearchKind; + this.checker = checker; + this.cancellationToken = cancellationToken; + this.searchMeaning = searchMeaning; + this.options = options; + this.result = result; + /** Cache for `explicitlyinheritsFrom`. */ + this.inheritsFromCache = ts.createMap(); + /** + * Type nodes can contain multiple references to the same type. For example: + * let x: Foo & (Foo & Bar) = ... + * Because we are returning the implementation locations and not the identifier locations, + * duplicate entries would be returned here as each of the type references is part of + * the same implementation. For that reason, check before we add a new entry. + */ + this.markSeenContainingTypeReference = ts.nodeSeenTracker(); + /** + * It's possible that we will encounter the right side of `export { foo as bar } from "x";` more than once. + * For example: + * // b.ts + * export { foo as bar } from "./a"; + * import { bar } from "./b"; + * + * Normally at `foo as bar` we directly add `foo` and do not locally search for it (since it doesn't declare a local). + * But another reference to it may appear in the same source file. + * See `tests/cases/fourslash/transitiveExportImports3.ts`. + */ + this.markSeenReExportRHS = ts.nodeSeenTracker(); + this.symbolIdToReferences = []; + // Source file ID → symbol ID → Whether the symbol has been searched for in the source file. + this.sourceFileToSeenSymbols = []; + } + State.prototype.includesSourceFile = function (sourceFile) { + return this.sourceFilesSet.has(sourceFile.fileName); + }; + /** Gets every place to look for references of an exported symbols. See `ImportsResult` in `importTracker.ts` for more documentation. */ + State.prototype.getImportSearches = function (exportSymbol, exportInfo) { + if (!this.importTracker) + this.importTracker = FindAllReferences.createImportTracker(this.sourceFiles, this.sourceFilesSet, this.checker, this.cancellationToken); + return this.importTracker(exportSymbol, exportInfo, !!this.options.isForRename); + }; + /** @param allSearchSymbols set of additional symbols for use by `includes`. */ + State.prototype.createSearch = function (location, symbol, comingFrom, searchOptions) { + if (searchOptions === void 0) { searchOptions = {}; } + // Note: if this is an external module symbol, the name doesn't include quotes. + // Note: getLocalSymbolForExportDefault handles `export default class C {}`, but not `export default C` or `export { C as default }`. + // The other two forms seem to be handled downstream (e.g. in `skipPastExportOrImportSpecifier`), so special-casing the first form + // here appears to be intentional). + var _a = searchOptions.text, text = _a === void 0 ? ts.stripQuotes(ts.unescapeLeadingUnderscores((ts.getLocalSymbolForExportDefault(symbol) || symbol).escapedName)) : _a, _b = searchOptions.allSearchSymbols, allSearchSymbols = _b === void 0 ? [symbol] : _b; + var escapedText = ts.escapeLeadingUnderscores(text); + var parents = this.options.implementations && location ? getParentSymbolsOfPropertyAccess(location, symbol, this.checker) : undefined; + return { symbol: symbol, comingFrom: comingFrom, text: text, escapedText: escapedText, parents: parents, allSearchSymbols: allSearchSymbols, includes: function (sym) { return ts.contains(allSearchSymbols, sym); } }; + }; + /** + * Callback to add references for a particular searched symbol. + * This initializes a reference group, so only call this if you will add at least one reference. + */ + State.prototype.referenceAdder = function (searchSymbol) { + var symbolId = ts.getSymbolId(searchSymbol); + var references = this.symbolIdToReferences[symbolId]; + if (!references) { + references = this.symbolIdToReferences[symbolId] = []; + this.result.push({ definition: { type: 0 /* Symbol */, symbol: searchSymbol }, references: references }); + } + return function (node, kind) { return references.push(FindAllReferences.nodeEntry(node, kind)); }; + }; + /** Add a reference with no associated definition. */ + State.prototype.addStringOrCommentReference = function (fileName, textSpan) { + this.result.push({ + definition: undefined, + references: [{ kind: 0 /* Span */, fileName: fileName, textSpan: textSpan }] + }); + }; + /** Returns `true` the first time we search for a symbol in a file and `false` afterwards. */ + State.prototype.markSearchedSymbols = function (sourceFile, symbols) { + var sourceId = ts.getNodeId(sourceFile); + var seenSymbols = this.sourceFileToSeenSymbols[sourceId] || (this.sourceFileToSeenSymbols[sourceId] = ts.createMap()); + var anyNewSymbols = false; + for (var _i = 0, symbols_4 = symbols; _i < symbols_4.length; _i++) { + var sym = symbols_4[_i]; + anyNewSymbols = ts.addToSeen(seenSymbols, ts.getSymbolId(sym)) || anyNewSymbols; + } + return anyNewSymbols; + }; + return State; + }()); + /** Search for all imports of a given exported symbol using `State.getImportSearches`. */ + function searchForImportsOfExport(exportLocation, exportSymbol, exportInfo, state) { + var _a = state.getImportSearches(exportSymbol, exportInfo), importSearches = _a.importSearches, singleReferences = _a.singleReferences, indirectUsers = _a.indirectUsers; + // For `import { foo as bar }` just add the reference to `foo`, and don't otherwise search in the file. + if (singleReferences.length) { + var addRef = state.referenceAdder(exportSymbol); + for (var _i = 0, singleReferences_1 = singleReferences; _i < singleReferences_1.length; _i++) { + var singleRef = singleReferences_1[_i]; + if (shouldAddSingleReference(singleRef, state)) + addRef(singleRef); + } + } + // For each import, find all references to that import in its source file. + for (var _b = 0, importSearches_1 = importSearches; _b < importSearches_1.length; _b++) { + var _c = importSearches_1[_b], importLocation = _c[0], importSymbol = _c[1]; + getReferencesInSourceFile(importLocation.getSourceFile(), state.createSearch(importLocation, importSymbol, 1 /* Export */), state); + } + if (indirectUsers.length) { + var indirectSearch = void 0; + switch (exportInfo.exportKind) { + case 0 /* Named */: + indirectSearch = state.createSearch(exportLocation, exportSymbol, 1 /* Export */); + break; + case 1 /* Default */: + // Search for a property access to '.default'. This can't be renamed. + indirectSearch = state.options.isForRename ? undefined : state.createSearch(exportLocation, exportSymbol, 1 /* Export */, { text: "default" }); + break; + case 2 /* ExportEquals */: + break; + } + if (indirectSearch) { + for (var _d = 0, indirectUsers_1 = indirectUsers; _d < indirectUsers_1.length; _d++) { + var indirectUser = indirectUsers_1[_d]; + searchForName(indirectUser, indirectSearch, state); + } + } + } + } + function eachExportReference(sourceFiles, checker, cancellationToken, exportSymbol, exportingModuleSymbol, exportName, isDefaultExport, cb) { + var importTracker = FindAllReferences.createImportTracker(sourceFiles, ts.arrayToSet(sourceFiles, function (f) { return f.fileName; }), checker, cancellationToken); + var _a = importTracker(exportSymbol, { exportKind: isDefaultExport ? 1 /* Default */ : 0 /* Named */, exportingModuleSymbol: exportingModuleSymbol }, /*isForRename*/ false), importSearches = _a.importSearches, indirectUsers = _a.indirectUsers; + for (var _i = 0, importSearches_2 = importSearches; _i < importSearches_2.length; _i++) { + var importLocation = importSearches_2[_i][0]; + cb(importLocation); + } + for (var _b = 0, indirectUsers_2 = indirectUsers; _b < indirectUsers_2.length; _b++) { + var indirectUser = indirectUsers_2[_b]; + for (var _c = 0, _d = getPossibleSymbolReferenceNodes(indirectUser, isDefaultExport ? "default" : exportName); _c < _d.length; _c++) { + var node = _d[_c]; + // Import specifiers should be handled by importSearches + if (ts.isIdentifier(node) && !ts.isImportOrExportSpecifier(node.parent) && checker.getSymbolAtLocation(node) === exportSymbol) { + cb(node); + } + } + } + } + Core.eachExportReference = eachExportReference; + function shouldAddSingleReference(singleRef, state) { + if (!hasMatchingMeaning(singleRef, state)) + return false; + if (!state.options.isForRename) + return true; + // Don't rename an import type `import("./module-name")` when renaming `name` in `export = name;` + if (!ts.isIdentifier(singleRef)) + return false; + // At `default` in `import { default as x }` or `export { default as x }`, do add a reference, but do not rename. + return !(ts.isImportOrExportSpecifier(singleRef.parent) && singleRef.escapedText === "default" /* Default */); + } + // Go to the symbol we imported from and find references for it. + function searchForImportedSymbol(symbol, state) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + var exportingFile = declaration.getSourceFile(); + // Need to search in the file even if it's not in the search-file set, because it might export the symbol. + getReferencesInSourceFile(exportingFile, state.createSearch(declaration, symbol, 0 /* Import */), state, state.includesSourceFile(exportingFile)); + } + } + /** Search for all occurences of an identifier in a source file (and filter out the ones that match). */ + function searchForName(sourceFile, search, state) { + if (ts.getNameTable(sourceFile).get(search.escapedText) !== undefined) { + getReferencesInSourceFile(sourceFile, search, state); + } + } + function getPropertySymbolOfDestructuringAssignment(location, checker) { + return ts.isArrayLiteralOrObjectLiteralDestructuringPattern(location.parent.parent) + ? checker.getPropertySymbolOfDestructuringAssignment(location) + : undefined; + } + /** + * Determines the smallest scope in which a symbol may have named references. + * Note that not every construct has been accounted for. This function can + * probably be improved. + * + * @returns undefined if the scope cannot be determined, implying that + * a reference to a symbol can occur anywhere. + */ + function getSymbolScope(symbol) { + // If this is the symbol of a named function expression or named class expression, + // then named references are limited to its own scope. + var declarations = symbol.declarations, flags = symbol.flags, parent = symbol.parent, valueDeclaration = symbol.valueDeclaration; + if (valueDeclaration && (valueDeclaration.kind === 196 /* FunctionExpression */ || valueDeclaration.kind === 209 /* ClassExpression */)) { + return valueDeclaration; + } + if (!declarations) { + return undefined; + } + // If this is private property or method, the scope is the containing class + if (flags & (4 /* Property */ | 8192 /* Method */)) { + var privateDeclaration = ts.find(declarations, function (d) { return ts.hasModifier(d, 8 /* Private */); }); + if (privateDeclaration) { + return ts.getAncestor(privateDeclaration, 240 /* ClassDeclaration */); + } + // Else this is a public property and could be accessed from anywhere. + return undefined; + } + // If symbol is of object binding pattern element without property name we would want to + // look for property too and that could be anywhere + if (declarations.some(ts.isObjectBindingElementWithoutPropertyName)) { + return undefined; + } + /* + If the symbol has a parent, it's globally visible unless: + - It's a private property (handled above). + - It's a type parameter. + - The parent is an external module: then we should only search in the module (and recurse on the export later). + - But if the parent has `export as namespace`, the symbol is globally visible through that namespace. + */ + var exposedByParent = parent && !(symbol.flags & 262144 /* TypeParameter */); + if (exposedByParent && !(ts.isExternalModuleSymbol(parent) && !parent.globalExports)) { + return undefined; + } + var scope; + for (var _i = 0, declarations_11 = declarations; _i < declarations_11.length; _i++) { + var declaration = declarations_11[_i]; + var container = ts.getContainerNode(declaration); + if (scope && scope !== container) { + // Different declarations have different containers, bail out + return undefined; + } + if (!container || container.kind === 279 /* SourceFile */ && !ts.isExternalOrCommonJsModule(container)) { + // This is a global variable and not an external module, any declaration defined + // within this scope is visible outside the file + return undefined; + } + // The search scope is the container node + scope = container; + } + // If symbol.parent, this means we are in an export of an external module. (Otherwise we would have returned `undefined` above.) + // For an export of a module, we may be in a declaration file, and it may be accessed elsewhere. E.g.: + // declare module "a" { export type T = number; } + // declare module "b" { import { T } from "a"; export const x: T; } + // So we must search the whole source file. (Because we will mark the source file as seen, we we won't return to it when searching for imports.) + return exposedByParent ? scope.getSourceFile() : scope; // TODO: GH#18217 + } + /** Used as a quick check for whether a symbol is used at all in a file (besides its definition). */ + function isSymbolReferencedInFile(definition, checker, sourceFile) { + return eachSymbolReferenceInFile(definition, checker, sourceFile, function () { return true; }) || false; + } + Core.isSymbolReferencedInFile = isSymbolReferencedInFile; + function eachSymbolReferenceInFile(definition, checker, sourceFile, cb) { + var symbol = ts.isParameterPropertyDeclaration(definition.parent) + ? ts.first(checker.getSymbolsOfParameterPropertyDeclaration(definition.parent, definition.text)) + : checker.getSymbolAtLocation(definition); + if (!symbol) + return undefined; + for (var _i = 0, _a = getPossibleSymbolReferenceNodes(sourceFile, symbol.name); _i < _a.length; _i++) { + var token = _a[_i]; + if (!ts.isIdentifier(token) || token === definition || token.escapedText !== definition.escapedText) + continue; + var referenceSymbol = checker.getSymbolAtLocation(token); // See GH#19955 for why the type annotation is necessary + if (referenceSymbol === symbol + || checker.getShorthandAssignmentValueSymbol(token.parent) === symbol + || ts.isExportSpecifier(token.parent) && getLocalSymbolForExportSpecifier(token, referenceSymbol, token.parent, checker) === symbol) { + var res = cb(token); + if (res) + return res; + } + } + } + Core.eachSymbolReferenceInFile = eachSymbolReferenceInFile; + function eachSignatureCall(signature, sourceFiles, checker, cb) { + if (!signature.name || !ts.isIdentifier(signature.name)) + return; + var symbol = ts.Debug.assertDefined(checker.getSymbolAtLocation(signature.name)); + for (var _i = 0, sourceFiles_5 = sourceFiles; _i < sourceFiles_5.length; _i++) { + var sourceFile = sourceFiles_5[_i]; + for (var _a = 0, _b = getPossibleSymbolReferenceNodes(sourceFile, symbol.name); _a < _b.length; _a++) { + var name = _b[_a]; + if (!ts.isIdentifier(name) || name === signature.name || name.escapedText !== signature.name.escapedText) + continue; + var called = ts.climbPastPropertyAccess(name); + var call = called.parent; + if (!ts.isCallExpression(call) || call.expression !== called) + continue; + var referenceSymbol = checker.getSymbolAtLocation(name); + if (referenceSymbol && checker.getRootSymbols(referenceSymbol).some(function (s) { return s === symbol; })) { + cb(call); + } + } + } + } + Core.eachSignatureCall = eachSignatureCall; + function getPossibleSymbolReferenceNodes(sourceFile, symbolName, container) { + if (container === void 0) { container = sourceFile; } + return getPossibleSymbolReferencePositions(sourceFile, symbolName, container).map(function (pos) { return ts.getTouchingPropertyName(sourceFile, pos); }); + } + function getPossibleSymbolReferencePositions(sourceFile, symbolName, container) { + if (container === void 0) { container = sourceFile; } + var positions = []; + /// TODO: Cache symbol existence for files to save text search + // Also, need to make this work for unicode escapes. + // Be resilient in the face of a symbol with no name or zero length name + if (!symbolName || !symbolName.length) { + return positions; + } + var text = sourceFile.text; + var sourceLength = text.length; + var symbolNameLength = symbolName.length; + var position = text.indexOf(symbolName, container.pos); + while (position >= 0) { + // If we are past the end, stop looking + if (position > container.end) + break; + // We found a match. Make sure it's not part of a larger word (i.e. the char + // before and after it have to be a non-identifier char). + var endPosition = position + symbolNameLength; + if ((position === 0 || !ts.isIdentifierPart(text.charCodeAt(position - 1), 6 /* Latest */)) && + (endPosition === sourceLength || !ts.isIdentifierPart(text.charCodeAt(endPosition), 6 /* Latest */))) { + // Found a real match. Keep searching. + positions.push(position); + } + position = text.indexOf(symbolName, position + symbolNameLength + 1); + } + return positions; + } + function getLabelReferencesInNode(container, targetLabel) { + var sourceFile = container.getSourceFile(); + var labelName = targetLabel.text; + var references = ts.mapDefined(getPossibleSymbolReferenceNodes(sourceFile, labelName, container), function (node) { + // Only pick labels that are either the target label, or have a target that is the target label + return node === targetLabel || (ts.isJumpStatementTarget(node) && ts.getTargetLabel(node, labelName) === targetLabel) ? FindAllReferences.nodeEntry(node) : undefined; + }); + return [{ definition: { type: 1 /* Label */, node: targetLabel }, references: references }]; + } + function isValidReferencePosition(node, searchSymbolName) { + // Compare the length so we filter out strict superstrings of the symbol we are looking for + switch (node.kind) { + case 72 /* Identifier */: + return node.text.length === searchSymbolName.length; + case 10 /* StringLiteral */: { + var str = node; + return (ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(str) || ts.isNameOfModuleDeclaration(node) || ts.isExpressionOfExternalModuleImportEqualsDeclaration(node) || (ts.isCallExpression(node.parent) && ts.isBindableObjectDefinePropertyCall(node.parent) && node.parent.arguments[1] === node)) && + str.text.length === searchSymbolName.length; + } + case 8 /* NumericLiteral */: + return ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node) && node.text.length === searchSymbolName.length; + case 80 /* DefaultKeyword */: + return "default".length === searchSymbolName.length; + default: + return false; + } + } + function getAllReferencesForKeyword(sourceFiles, keywordKind, cancellationToken) { + var references = ts.flatMap(sourceFiles, function (sourceFile) { + cancellationToken.throwIfCancellationRequested(); + return ts.mapDefined(getPossibleSymbolReferenceNodes(sourceFile, ts.tokenToString(keywordKind), sourceFile), function (referenceLocation) { + return referenceLocation.kind === keywordKind ? FindAllReferences.nodeEntry(referenceLocation) : undefined; + }); + }); + return references.length ? [{ definition: { type: 2 /* Keyword */, node: references[0].node }, references: references }] : undefined; + } + function getReferencesInSourceFile(sourceFile, search, state, addReferencesHere) { + if (addReferencesHere === void 0) { addReferencesHere = true; } + state.cancellationToken.throwIfCancellationRequested(); + return getReferencesInContainer(sourceFile, sourceFile, search, state, addReferencesHere); + } + /** + * Search within node "container" for references for a search value, where the search value is defined as a + * tuple of(searchSymbol, searchText, searchLocation, and searchMeaning). + * searchLocation: a node where the search value + */ + function getReferencesInContainer(container, sourceFile, search, state, addReferencesHere) { + if (!state.markSearchedSymbols(sourceFile, search.allSearchSymbols)) { + return; + } + for (var _i = 0, _a = getPossibleSymbolReferencePositions(sourceFile, search.text, container); _i < _a.length; _i++) { + var position = _a[_i]; + getReferencesAtLocation(sourceFile, position, search, state, addReferencesHere); + } + } + function hasMatchingMeaning(referenceLocation, state) { + return !!(ts.getMeaningFromLocation(referenceLocation) & state.searchMeaning); + } + function getReferencesAtLocation(sourceFile, position, search, state, addReferencesHere) { + var referenceLocation = ts.getTouchingPropertyName(sourceFile, position); + if (!isValidReferencePosition(referenceLocation, search.text)) { + // This wasn't the start of a token. Check to see if it might be a + // match in a comment or string if that's what the caller is asking + // for. + if (!state.options.implementations && (state.options.findInStrings && ts.isInString(sourceFile, position) || state.options.findInComments && ts.isInNonReferenceComment(sourceFile, position))) { + // In the case where we're looking inside comments/strings, we don't have + // an actual definition. So just use 'undefined' here. Features like + // 'Rename' won't care (as they ignore the definitions), and features like + // 'FindReferences' will just filter out these results. + state.addStringOrCommentReference(sourceFile.fileName, ts.createTextSpan(position, search.text.length)); + } + return; + } + if (!hasMatchingMeaning(referenceLocation, state)) + return; + var referenceSymbol = state.checker.getSymbolAtLocation(referenceLocation); + if (!referenceSymbol) { + return; + } + var parent = referenceLocation.parent; + if (ts.isImportSpecifier(parent) && parent.propertyName === referenceLocation) { + // This is added through `singleReferences` in ImportsResult. If we happen to see it again, don't add it again. + return; + } + if (ts.isExportSpecifier(parent)) { + ts.Debug.assert(referenceLocation.kind === 72 /* Identifier */); + getReferencesAtExportSpecifier(referenceLocation, referenceSymbol, parent, search, state, addReferencesHere); + return; + } + var relatedSymbol = getRelatedSymbol(search, referenceSymbol, referenceLocation, state); + if (!relatedSymbol) { + getReferenceForShorthandProperty(referenceSymbol, search, state); + return; + } + switch (state.specialSearchKind) { + case 0 /* None */: + if (addReferencesHere) + addReference(referenceLocation, relatedSymbol, state); + break; + case 1 /* Constructor */: + addConstructorReferences(referenceLocation, sourceFile, search, state); + break; + case 2 /* Class */: + addClassStaticThisReferences(referenceLocation, search, state); + break; + default: + ts.Debug.assertNever(state.specialSearchKind); + } + getImportOrExportReferences(referenceLocation, referenceSymbol, search, state); + } + function getReferencesAtExportSpecifier(referenceLocation, referenceSymbol, exportSpecifier, search, state, addReferencesHere, alwaysGetReferences) { + var parent = exportSpecifier.parent, propertyName = exportSpecifier.propertyName, name = exportSpecifier.name; + var exportDeclaration = parent.parent; + var localSymbol = getLocalSymbolForExportSpecifier(referenceLocation, referenceSymbol, exportSpecifier, state.checker); + if (!alwaysGetReferences && !search.includes(localSymbol)) { + return; + } + if (!propertyName) { + // Don't rename at `export { default } from "m";`. (but do continue to search for imports of the re-export) + if (!(state.options.isForRename && (name.escapedText === "default" /* Default */))) { + addRef(); + } + } + else if (referenceLocation === propertyName) { + // For `export { foo as bar } from "baz"`, "`foo`" will be added from the singleReferences for import searches of the original export. + // For `export { foo as bar };`, where `foo` is a local, so add it now. + if (!exportDeclaration.moduleSpecifier) { + addRef(); + } + if (addReferencesHere && !state.options.isForRename && state.markSeenReExportRHS(name)) { + addReference(name, ts.Debug.assertDefined(exportSpecifier.symbol), state); + } + } + else { + if (state.markSeenReExportRHS(referenceLocation)) { + addRef(); + } + } + // For `export { foo as bar }`, rename `foo`, but not `bar`. + if (!state.options.isForRename || alwaysGetReferences) { + var exportKind = referenceLocation.originalKeywordKind === 80 /* DefaultKeyword */ ? 1 /* Default */ : 0 /* Named */; + var exportSymbol = ts.Debug.assertDefined(exportSpecifier.symbol); + var exportInfo = ts.Debug.assertDefined(FindAllReferences.getExportInfo(exportSymbol, exportKind, state.checker)); + searchForImportsOfExport(referenceLocation, exportSymbol, exportInfo, state); + } + // At `export { x } from "foo"`, also search for the imported symbol `"foo".x`. + if (search.comingFrom !== 1 /* Export */ && exportDeclaration.moduleSpecifier && !propertyName && !state.options.isForRename) { + var imported = state.checker.getExportSpecifierLocalTargetSymbol(exportSpecifier); + if (imported) + searchForImportedSymbol(imported, state); + } + function addRef() { + if (addReferencesHere) + addReference(referenceLocation, localSymbol, state); + } + } + function getLocalSymbolForExportSpecifier(referenceLocation, referenceSymbol, exportSpecifier, checker) { + return isExportSpecifierAlias(referenceLocation, exportSpecifier) && checker.getExportSpecifierLocalTargetSymbol(exportSpecifier) || referenceSymbol; + } + function isExportSpecifierAlias(referenceLocation, exportSpecifier) { + var parent = exportSpecifier.parent, propertyName = exportSpecifier.propertyName, name = exportSpecifier.name; + ts.Debug.assert(propertyName === referenceLocation || name === referenceLocation); + if (propertyName) { + // Given `export { foo as bar } [from "someModule"]`: It's an alias at `foo`, but at `bar` it's a new symbol. + return propertyName === referenceLocation; + } + else { + // `export { foo } from "foo"` is a re-export. + // `export { foo };` is not a re-export, it creates an alias for the local variable `foo`. + return !parent.parent.moduleSpecifier; + } + } + function getImportOrExportReferences(referenceLocation, referenceSymbol, search, state) { + var importOrExport = FindAllReferences.getImportOrExportSymbol(referenceLocation, referenceSymbol, state.checker, search.comingFrom === 1 /* Export */); + if (!importOrExport) + return; + var symbol = importOrExport.symbol; + if (importOrExport.kind === 0 /* Import */) { + if (!state.options.isForRename) { + searchForImportedSymbol(symbol, state); + } + } + else { + searchForImportsOfExport(referenceLocation, symbol, importOrExport.exportInfo, state); + } + } + function getReferenceForShorthandProperty(_a, search, state) { + var flags = _a.flags, valueDeclaration = _a.valueDeclaration; + var shorthandValueSymbol = state.checker.getShorthandAssignmentValueSymbol(valueDeclaration); + var name = valueDeclaration && ts.getNameOfDeclaration(valueDeclaration); + /* + * Because in short-hand property assignment, an identifier which stored as name of the short-hand property assignment + * has two meanings: property name and property value. Therefore when we do findAllReference at the position where + * an identifier is declared, the language service should return the position of the variable declaration as well as + * the position in short-hand property assignment excluding property accessing. However, if we do findAllReference at the + * position of property accessing, the referenceEntry of such position will be handled in the first case. + */ + if (!(flags & 33554432 /* Transient */) && name && search.includes(shorthandValueSymbol)) { + addReference(name, shorthandValueSymbol, state); + } + } + function addReference(referenceLocation, relatedSymbol, state) { + var _a = "kind" in relatedSymbol ? relatedSymbol : { kind: undefined, symbol: relatedSymbol }, kind = _a.kind, symbol = _a.symbol; + var addRef = state.referenceAdder(symbol); + if (state.options.implementations) { + addImplementationReferences(referenceLocation, addRef, state); + } + else { + addRef(referenceLocation, kind); + } + } + /** Adds references when a constructor is used with `new this()` in its own class and `super()` calls in subclasses. */ + function addConstructorReferences(referenceLocation, sourceFile, search, state) { + if (ts.isNewExpressionTarget(referenceLocation)) { + addReference(referenceLocation, search.symbol, state); + } + var pusher = function () { return state.referenceAdder(search.symbol); }; + if (ts.isClassLike(referenceLocation.parent)) { + ts.Debug.assert(referenceLocation.kind === 80 /* DefaultKeyword */ || referenceLocation.parent.name === referenceLocation); + // This is the class declaration containing the constructor. + findOwnConstructorReferences(search.symbol, sourceFile, pusher()); + } + else { + // If this class appears in `extends C`, then the extending class' "super" calls are references. + var classExtending = tryGetClassByExtendingIdentifier(referenceLocation); + if (classExtending) { + findSuperConstructorAccesses(classExtending, pusher()); + } + } + } + function addClassStaticThisReferences(referenceLocation, search, state) { + addReference(referenceLocation, search.symbol, state); + var classLike = referenceLocation.parent; + if (state.options.isForRename || !ts.isClassLike(classLike)) + return; + ts.Debug.assert(classLike.name === referenceLocation); + var addRef = state.referenceAdder(search.symbol); + for (var _i = 0, _a = classLike.members; _i < _a.length; _i++) { + var member = _a[_i]; + if (!(ts.isMethodOrAccessor(member) && ts.hasModifier(member, 32 /* Static */))) { + continue; + } + if (member.body) { + member.body.forEachChild(function cb(node) { + if (node.kind === 100 /* ThisKeyword */) { + addRef(node); + } + else if (!ts.isFunctionLike(node) && !ts.isClassLike(node)) { + node.forEachChild(cb); + } + }); + } + } + } + /** + * `classSymbol` is the class where the constructor was defined. + * Reference the constructor and all calls to `new this()`. + */ + function findOwnConstructorReferences(classSymbol, sourceFile, addNode) { + for (var _i = 0, _a = classSymbol.members.get("__constructor" /* Constructor */).declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + var ctrKeyword = ts.findChildOfKind(decl, 124 /* ConstructorKeyword */, sourceFile); + ts.Debug.assert(decl.kind === 157 /* Constructor */ && !!ctrKeyword); + addNode(ctrKeyword); + } + classSymbol.exports.forEach(function (member) { + var decl = member.valueDeclaration; + if (decl && decl.kind === 156 /* MethodDeclaration */) { + var body = decl.body; + if (body) { + forEachDescendantOfKind(body, 100 /* ThisKeyword */, function (thisKeyword) { + if (ts.isNewExpressionTarget(thisKeyword)) { + addNode(thisKeyword); + } + }); + } + } + }); + } + /** Find references to `super` in the constructor of an extending class. */ + function findSuperConstructorAccesses(cls, addNode) { + var ctr = cls.symbol.members.get("__constructor" /* Constructor */); + if (!ctr) { + return; + } + for (var _i = 0, _a = ctr.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + ts.Debug.assert(decl.kind === 157 /* Constructor */); + var body = decl.body; + if (body) { + forEachDescendantOfKind(body, 98 /* SuperKeyword */, function (node) { + if (ts.isCallExpressionTarget(node)) { + addNode(node); + } + }); + } + } + } + function addImplementationReferences(refNode, addReference, state) { + // Check if we found a function/propertyAssignment/method with an implementation or initializer + if (ts.isDeclarationName(refNode) && isImplementation(refNode.parent)) { + addReference(refNode); + return; + } + if (refNode.kind !== 72 /* Identifier */) { + return; + } + if (refNode.parent.kind === 276 /* ShorthandPropertyAssignment */) { + // Go ahead and dereference the shorthand assignment by going to its definition + getReferenceEntriesForShorthandPropertyAssignment(refNode, state.checker, addReference); + } + // Check if the node is within an extends or implements clause + var containingClass = getContainingClassIfInHeritageClause(refNode); + if (containingClass) { + addReference(containingClass); + return; + } + // If we got a type reference, try and see if the reference applies to any expressions that can implement an interface + // Find the first node whose parent isn't a type node -- i.e., the highest type node. + var typeNode = ts.findAncestor(refNode, function (a) { return !ts.isQualifiedName(a.parent) && !ts.isTypeNode(a.parent) && !ts.isTypeElement(a.parent); }); + var typeHavingNode = typeNode.parent; + if (ts.hasType(typeHavingNode) && typeHavingNode.type === typeNode && state.markSeenContainingTypeReference(typeHavingNode)) { + if (ts.hasInitializer(typeHavingNode)) { + addIfImplementation(typeHavingNode.initializer); + } + else if (ts.isFunctionLike(typeHavingNode) && typeHavingNode.body) { + var body = typeHavingNode.body; + if (body.kind === 218 /* Block */) { + ts.forEachReturnStatement(body, function (returnStatement) { + if (returnStatement.expression) + addIfImplementation(returnStatement.expression); + }); + } + else { + addIfImplementation(body); + } + } + else if (ts.isAssertionExpression(typeHavingNode)) { + addIfImplementation(typeHavingNode.expression); + } + } + function addIfImplementation(e) { + if (isImplementationExpression(e)) + addReference(e); + } + } + function getContainingClassIfInHeritageClause(node) { + return ts.isIdentifier(node) || ts.isPropertyAccessExpression(node) ? getContainingClassIfInHeritageClause(node.parent) + : ts.isExpressionWithTypeArguments(node) ? ts.tryCast(node.parent.parent, ts.isClassLike) : undefined; + } + /** + * Returns true if this is an expression that can be considered an implementation + */ + function isImplementationExpression(node) { + switch (node.kind) { + case 195 /* ParenthesizedExpression */: + return isImplementationExpression(node.expression); + case 197 /* ArrowFunction */: + case 196 /* FunctionExpression */: + case 188 /* ObjectLiteralExpression */: + case 209 /* ClassExpression */: + case 187 /* ArrayLiteralExpression */: + return true; + default: + return false; + } + } + /** + * Determines if the parent symbol occurs somewhere in the child's ancestry. If the parent symbol + * is an interface, determines if some ancestor of the child symbol extends or inherits from it. + * Also takes in a cache of previous results which makes this slightly more efficient and is + * necessary to avoid potential loops like so: + * class A extends B { } + * class B extends A { } + * + * We traverse the AST rather than using the type checker because users are typically only interested + * in explicit implementations of an interface/class when calling "Go to Implementation". Sibling + * implementations of types that share a common ancestor with the type whose implementation we are + * searching for need to be filtered out of the results. The type checker doesn't let us make the + * distinction between structurally compatible implementations and explicit implementations, so we + * must use the AST. + * + * @param symbol A class or interface Symbol + * @param parent Another class or interface Symbol + * @param cachedResults A map of symbol id pairs (i.e. "child,parent") to booleans indicating previous results + */ + function explicitlyInheritsFrom(symbol, parent, cachedResults, checker) { + if (symbol === parent) { + return true; + } + var key = ts.getSymbolId(symbol) + "," + ts.getSymbolId(parent); + var cached = cachedResults.get(key); + if (cached !== undefined) { + return cached; + } + // Set the key so that we don't infinitely recurse + cachedResults.set(key, false); + var inherits = symbol.declarations.some(function (declaration) { + return ts.getAllSuperTypeNodes(declaration).some(function (typeReference) { + var type = checker.getTypeAtLocation(typeReference); + return !!type && !!type.symbol && explicitlyInheritsFrom(type.symbol, parent, cachedResults, checker); + }); + }); + cachedResults.set(key, inherits); + return inherits; + } + function getReferencesForSuperKeyword(superKeyword) { + var searchSpaceNode = ts.getSuperContainer(superKeyword, /*stopOnFunctions*/ false); + if (!searchSpaceNode) { + return undefined; + } + // Whether 'super' occurs in a static context within a class. + var staticFlag = 32 /* Static */; + switch (searchSpaceNode.kind) { + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + staticFlag &= ts.getModifierFlags(searchSpaceNode); + searchSpaceNode = searchSpaceNode.parent; // re-assign to be the owning class + break; + default: + return undefined; + } + var sourceFile = searchSpaceNode.getSourceFile(); + var references = ts.mapDefined(getPossibleSymbolReferenceNodes(sourceFile, "super", searchSpaceNode), function (node) { + if (node.kind !== 98 /* SuperKeyword */) { + return; + } + var container = ts.getSuperContainer(node, /*stopOnFunctions*/ false); + // If we have a 'super' container, we must have an enclosing class. + // Now make sure the owning class is the same as the search-space + // and has the same static qualifier as the original 'super's owner. + return container && (32 /* Static */ & ts.getModifierFlags(container)) === staticFlag && container.parent.symbol === searchSpaceNode.symbol ? FindAllReferences.nodeEntry(node) : undefined; + }); + return [{ definition: { type: 0 /* Symbol */, symbol: searchSpaceNode.symbol }, references: references }]; + } + function getReferencesForThisKeyword(thisOrSuperKeyword, sourceFiles, cancellationToken) { + var searchSpaceNode = ts.getThisContainer(thisOrSuperKeyword, /* includeArrowFunctions */ false); + // Whether 'this' occurs in a static context within a class. + var staticFlag = 32 /* Static */; + switch (searchSpaceNode.kind) { + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + if (ts.isObjectLiteralMethod(searchSpaceNode)) { + break; + } + // falls through + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + staticFlag &= ts.getModifierFlags(searchSpaceNode); + searchSpaceNode = searchSpaceNode.parent; // re-assign to be the owning class + break; + case 279 /* SourceFile */: + if (ts.isExternalModule(searchSpaceNode)) { + return undefined; + } + // falls through + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + break; + // Computed properties in classes are not handled here because references to this are illegal, + // so there is no point finding references to them. + default: + return undefined; + } + var references = ts.flatMap(searchSpaceNode.kind === 279 /* SourceFile */ ? sourceFiles : [searchSpaceNode.getSourceFile()], function (sourceFile) { + cancellationToken.throwIfCancellationRequested(); + return getPossibleSymbolReferenceNodes(sourceFile, "this", ts.isSourceFile(searchSpaceNode) ? sourceFile : searchSpaceNode).filter(function (node) { + if (!ts.isThis(node)) { + return false; + } + var container = ts.getThisContainer(node, /* includeArrowFunctions */ false); + switch (searchSpaceNode.kind) { + case 196 /* FunctionExpression */: + case 239 /* FunctionDeclaration */: + return searchSpaceNode.symbol === container.symbol; + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + return ts.isObjectLiteralMethod(searchSpaceNode) && searchSpaceNode.symbol === container.symbol; + case 209 /* ClassExpression */: + case 240 /* ClassDeclaration */: + // Make sure the container belongs to the same class + // and has the appropriate static modifier from the original container. + return container.parent && searchSpaceNode.symbol === container.parent.symbol && (ts.getModifierFlags(container) & 32 /* Static */) === staticFlag; + case 279 /* SourceFile */: + return container.kind === 279 /* SourceFile */ && !ts.isExternalModule(container); + } + }); + }).map(function (n) { return FindAllReferences.nodeEntry(n); }); + var thisParameter = ts.firstDefined(references, function (r) { return ts.isParameter(r.node.parent) ? r.node : undefined; }); + return [{ + definition: { type: 3 /* This */, node: thisParameter || thisOrSuperKeyword }, + references: references + }]; + } + function getReferencesForStringLiteral(node, sourceFiles, cancellationToken) { + var references = ts.flatMap(sourceFiles, function (sourceFile) { + cancellationToken.throwIfCancellationRequested(); + return ts.mapDefined(getPossibleSymbolReferenceNodes(sourceFile, node.text), function (ref) { + return ts.isStringLiteral(ref) && ref.text === node.text ? FindAllReferences.nodeEntry(ref, 2 /* StringLiteral */) : undefined; + }); + }); + return [{ + definition: { type: 4 /* String */, node: node }, + references: references + }]; + } + // For certain symbol kinds, we need to include other symbols in the search set. + // This is not needed when searching for re-exports. + function populateSearchSymbolSet(symbol, location, checker, isForRename, implementations) { + var result = []; + forEachRelatedSymbol(symbol, location, checker, isForRename, function (sym, root, base) { result.push(base || root || sym); }, + /*allowBaseTypes*/ function () { return !implementations; }); + return result; + } + function forEachRelatedSymbol(symbol, location, checker, isForRenamePopulateSearchSymbolSet, cbSymbol, allowBaseTypes) { + var containingObjectLiteralElement = ts.getContainingObjectLiteralElement(location); + if (containingObjectLiteralElement) { + /* Because in short-hand property assignment, location has two meaning : property name and as value of the property + * When we do findAllReference at the position of the short-hand property assignment, we would want to have references to position of + * property name and variable declaration of the identifier. + * Like in below example, when querying for all references for an identifier 'name', of the property assignment, the language service + * should show both 'name' in 'obj' and 'name' in variable declaration + * const name = "Foo"; + * const obj = { name }; + * In order to do that, we will populate the search set with the value symbol of the identifier as a value of the property assignment + * so that when matching with potential reference symbol, both symbols from property declaration and variable declaration + * will be included correctly. + */ + var shorthandValueSymbol = checker.getShorthandAssignmentValueSymbol(location.parent); // gets the local symbol + if (shorthandValueSymbol && isForRenamePopulateSearchSymbolSet) { + // When renaming 'x' in `const o = { x }`, just rename the local variable, not the property. + return cbSymbol(shorthandValueSymbol, /*rootSymbol*/ undefined, /*baseSymbol*/ undefined, 3 /* SearchedLocalFoundProperty */); + } + // If the location is in a context sensitive location (i.e. in an object literal) try + // to get a contextual type for it, and add the property symbol from the contextual + // type to the search set + var contextualType = checker.getContextualType(containingObjectLiteralElement.parent); + var res_1 = contextualType && ts.firstDefined(ts.getPropertySymbolsFromContextualType(containingObjectLiteralElement, checker, contextualType, /*unionSymbolOk*/ true), function (sym) { return fromRoot(sym, 4 /* SearchedPropertyFoundLocal */); }); + if (res_1) + return res_1; + // If the location is name of property symbol from object literal destructuring pattern + // Search the property symbol + // for ( { property: p2 } of elems) { } + var propertySymbol = getPropertySymbolOfDestructuringAssignment(location, checker); + var res1 = propertySymbol && cbSymbol(propertySymbol, /*rootSymbol*/ undefined, /*baseSymbol*/ undefined, 4 /* SearchedPropertyFoundLocal */); + if (res1) + return res1; + var res2 = shorthandValueSymbol && cbSymbol(shorthandValueSymbol, /*rootSymbol*/ undefined, /*baseSymbol*/ undefined, 3 /* SearchedLocalFoundProperty */); + if (res2) + return res2; + } + var res = fromRoot(symbol); + if (res) + return res; + if (symbol.valueDeclaration && ts.isParameterPropertyDeclaration(symbol.valueDeclaration)) { + // For a parameter property, now try on the other symbol (property if this was a parameter, parameter if this was a property). + var paramProps = checker.getSymbolsOfParameterPropertyDeclaration(ts.cast(symbol.valueDeclaration, ts.isParameter), symbol.name); + ts.Debug.assert(paramProps.length === 2 && !!(paramProps[0].flags & 1 /* FunctionScopedVariable */) && !!(paramProps[1].flags & 4 /* Property */)); // is [parameter, property] + return fromRoot(symbol.flags & 1 /* FunctionScopedVariable */ ? paramProps[1] : paramProps[0]); + } + // symbolAtLocation for a binding element is the local symbol. See if the search symbol is the property. + // Don't do this when populating search set for a rename -- just rename the local. + if (!isForRenamePopulateSearchSymbolSet) { + var bindingElementPropertySymbol = ts.isObjectBindingElementWithoutPropertyName(location.parent) ? ts.getPropertySymbolFromBindingElement(checker, location.parent) : undefined; + return bindingElementPropertySymbol && fromRoot(bindingElementPropertySymbol, 4 /* SearchedPropertyFoundLocal */); + } + function fromRoot(sym, kind) { + // If this is a union property: + // - In populateSearchSymbolsSet we will add all the symbols from all its source symbols in all unioned types. + // - In findRelatedSymbol, we will just use the union symbol if any source symbol is included in the search. + // If the symbol is an instantiation from a another symbol (e.g. widened symbol): + // - In populateSearchSymbolsSet, add the root the list + // - In findRelatedSymbol, return the source symbol if that is in the search. (Do not return the instantiation symbol.) + return ts.firstDefined(checker.getRootSymbols(sym), function (rootSymbol) { + return cbSymbol(sym, rootSymbol, /*baseSymbol*/ undefined, kind) + // Add symbol of properties/methods of the same name in base classes and implemented interfaces definitions + || (rootSymbol.parent && rootSymbol.parent.flags & (32 /* Class */ | 64 /* Interface */) && allowBaseTypes(rootSymbol) + ? ts.getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.name, checker, function (base) { return cbSymbol(sym, rootSymbol, base, kind); }) + : undefined); + }); + } + } + function getRelatedSymbol(search, referenceSymbol, referenceLocation, state) { + var checker = state.checker; + return forEachRelatedSymbol(referenceSymbol, referenceLocation, checker, /*isForRenamePopulateSearchSymbolSet*/ false, function (sym, rootSymbol, baseSymbol, kind) { return search.includes(baseSymbol || rootSymbol || sym) + // For a base type, use the symbol for the derived type. For a synthetic (e.g. union) property, use the union symbol. + ? { symbol: rootSymbol && !(ts.getCheckFlags(sym) & 6 /* Synthetic */) ? rootSymbol : sym, kind: kind } + : undefined; }, + /*allowBaseTypes*/ function (rootSymbol) { + return !(search.parents && !search.parents.some(function (parent) { return explicitlyInheritsFrom(rootSymbol.parent, parent, state.inheritsFromCache, checker); })); + }); + } + /** + * Given an initial searchMeaning, extracted from a location, widen the search scope based on the declarations + * of the corresponding symbol. e.g. if we are searching for "Foo" in value position, but "Foo" references a class + * then we need to widen the search to include type positions as well. + * On the contrary, if we are searching for "Bar" in type position and we trace bar to an interface, and an uninstantiated + * module, we want to keep the search limited to only types, as the two declarations (interface and uninstantiated module) + * do not intersect in any of the three spaces. + */ + function getIntersectingMeaningFromDeclarations(node, symbol) { + var meaning = ts.getMeaningFromLocation(node); + var declarations = symbol.declarations; + if (declarations) { + var lastIterationMeaning = void 0; + do { + // The result is order-sensitive, for instance if initialMeaning === Namespace, and declarations = [class, instantiated module] + // we need to consider both as they initialMeaning intersects with the module in the namespace space, and the module + // intersects with the class in the value space. + // To achieve that we will keep iterating until the result stabilizes. + // Remember the last meaning + lastIterationMeaning = meaning; + for (var _i = 0, declarations_12 = declarations; _i < declarations_12.length; _i++) { + var declaration = declarations_12[_i]; + var declarationMeaning = ts.getMeaningFromDeclaration(declaration); + if (declarationMeaning & meaning) { + meaning |= declarationMeaning; + } + } + } while (meaning !== lastIterationMeaning); + } + return meaning; + } + Core.getIntersectingMeaningFromDeclarations = getIntersectingMeaningFromDeclarations; + function isImplementation(node) { + return !!(node.flags & 4194304 /* Ambient */) + || (ts.isVariableLike(node) ? ts.hasInitializer(node) + : ts.isFunctionLikeDeclaration(node) ? !!node.body + : ts.isClassLike(node) || ts.isModuleOrEnumDeclaration(node)); + } + function getReferenceEntriesForShorthandPropertyAssignment(node, checker, addReference) { + var refSymbol = checker.getSymbolAtLocation(node); + var shorthandSymbol = checker.getShorthandAssignmentValueSymbol(refSymbol.valueDeclaration); + if (shorthandSymbol) { + for (var _i = 0, _a = shorthandSymbol.getDeclarations(); _i < _a.length; _i++) { + var declaration = _a[_i]; + if (ts.getMeaningFromDeclaration(declaration) & 1 /* Value */) { + addReference(declaration); + } + } + } + } + Core.getReferenceEntriesForShorthandPropertyAssignment = getReferenceEntriesForShorthandPropertyAssignment; + function forEachDescendantOfKind(node, kind, action) { + ts.forEachChild(node, function (child) { + if (child.kind === kind) { + action(child); + } + forEachDescendantOfKind(child, kind, action); + }); + } + /** Get `C` given `N` if `N` is in the position `class C extends N` or `class C extends foo.N` where `N` is an identifier. */ + function tryGetClassByExtendingIdentifier(node) { + return ts.tryGetClassExtendingExpressionWithTypeArguments(ts.climbPastPropertyAccess(node).parent); + } + /** + * If we are just looking for implementations and this is a property access expression, we need to get the + * symbol of the local type of the symbol the property is being accessed on. This is because our search + * symbol may have a different parent symbol if the local type's symbol does not declare the property + * being accessed (i.e. it is declared in some parent class or interface) + */ + function getParentSymbolsOfPropertyAccess(location, symbol, checker) { + var propertyAccessExpression = ts.isRightSideOfPropertyAccess(location) ? location.parent : undefined; + var lhsType = propertyAccessExpression && checker.getTypeAtLocation(propertyAccessExpression.expression); + var res = ts.mapDefined(lhsType && (lhsType.isUnionOrIntersection() ? lhsType.types : lhsType.symbol === symbol.parent ? undefined : [lhsType]), function (t) { + return t.symbol && t.symbol.flags & (32 /* Class */ | 64 /* Interface */) ? t.symbol : undefined; + }); + return res.length === 0 ? undefined : res; + } + })(Core = FindAllReferences.Core || (FindAllReferences.Core = {})); + })(FindAllReferences = ts.FindAllReferences || (ts.FindAllReferences = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + function getEditsForFileRename(program, oldFileOrDirPath, newFileOrDirPath, host, formatContext, _preferences, sourceMapper) { + var useCaseSensitiveFileNames = ts.hostUsesCaseSensitiveFileNames(host); + var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); + var oldToNew = getPathUpdater(oldFileOrDirPath, newFileOrDirPath, getCanonicalFileName, sourceMapper); + var newToOld = getPathUpdater(newFileOrDirPath, oldFileOrDirPath, getCanonicalFileName, sourceMapper); + return ts.textChanges.ChangeTracker.with({ host: host, formatContext: formatContext }, function (changeTracker) { + updateTsconfigFiles(program, changeTracker, oldToNew, oldFileOrDirPath, newFileOrDirPath, host.getCurrentDirectory(), useCaseSensitiveFileNames); + updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName); + }); + } + ts.getEditsForFileRename = getEditsForFileRename; + // exported for tests + function getPathUpdater(oldFileOrDirPath, newFileOrDirPath, getCanonicalFileName, sourceMapper) { + var canonicalOldPath = getCanonicalFileName(oldFileOrDirPath); + return function (path) { + var originalPath = sourceMapper && sourceMapper.tryGetSourcePosition({ fileName: path, pos: 0 }); + var updatedPath = getUpdatedPath(originalPath ? originalPath.fileName : path); + return originalPath + ? updatedPath === undefined ? undefined : makeCorrespondingRelativeChange(originalPath.fileName, updatedPath, path, getCanonicalFileName) + : updatedPath; + }; + function getUpdatedPath(pathToUpdate) { + if (getCanonicalFileName(pathToUpdate) === canonicalOldPath) + return newFileOrDirPath; + var suffix = ts.tryRemoveDirectoryPrefix(pathToUpdate, canonicalOldPath, getCanonicalFileName); + return suffix === undefined ? undefined : newFileOrDirPath + "/" + suffix; + } + } + ts.getPathUpdater = getPathUpdater; + // Relative path from a0 to b0 should be same as relative path from a1 to b1. Returns b1. + function makeCorrespondingRelativeChange(a0, b0, a1, getCanonicalFileName) { + var rel = ts.getRelativePathFromFile(a0, b0, getCanonicalFileName); + return combinePathsSafe(ts.getDirectoryPath(a1), rel); + } + function updateTsconfigFiles(program, changeTracker, oldToNew, oldFileOrDirPath, newFileOrDirPath, currentDirectory, useCaseSensitiveFileNames) { + var configFile = program.getCompilerOptions().configFile; + if (!configFile) + return; + var configDir = ts.getDirectoryPath(configFile.fileName); + var jsonObjectLiteral = ts.getTsConfigObjectLiteralExpression(configFile); + if (!jsonObjectLiteral) + return; + forEachProperty(jsonObjectLiteral, function (property, propertyName) { + switch (propertyName) { + case "files": + case "include": + case "exclude": { + var foundExactMatch = updatePaths(property); + if (!foundExactMatch && propertyName === "include" && ts.isArrayLiteralExpression(property.initializer)) { + var includes = ts.mapDefined(property.initializer.elements, function (e) { return ts.isStringLiteral(e) ? e.text : undefined; }); + var matchers = ts.getFileMatcherPatterns(configDir, /*excludes*/ [], includes, useCaseSensitiveFileNames, currentDirectory); + // If there isn't some include for this, add a new one. + if (ts.getRegexFromPattern(ts.Debug.assertDefined(matchers.includeFilePattern), useCaseSensitiveFileNames).test(oldFileOrDirPath) && + !ts.getRegexFromPattern(ts.Debug.assertDefined(matchers.includeFilePattern), useCaseSensitiveFileNames).test(newFileOrDirPath)) { + changeTracker.insertNodeAfter(configFile, ts.last(property.initializer.elements), ts.createStringLiteral(relativePath(newFileOrDirPath))); + } + } + break; + } + case "compilerOptions": + forEachProperty(property.initializer, function (property, propertyName) { + var option = ts.getOptionFromName(propertyName); + if (option && (option.isFilePath || option.type === "list" && option.element.isFilePath)) { + updatePaths(property); + } + else if (propertyName === "paths") { + forEachProperty(property.initializer, function (pathsProperty) { + if (!ts.isArrayLiteralExpression(pathsProperty.initializer)) + return; + for (var _i = 0, _a = pathsProperty.initializer.elements; _i < _a.length; _i++) { + var e = _a[_i]; + tryUpdateString(e); + } + }); + } + }); + break; + } + }); + function updatePaths(property) { + // Type annotation needed due to #7294 + var elements = ts.isArrayLiteralExpression(property.initializer) ? property.initializer.elements : [property.initializer]; + var foundExactMatch = false; + for (var _i = 0, elements_5 = elements; _i < elements_5.length; _i++) { + var element = elements_5[_i]; + foundExactMatch = tryUpdateString(element) || foundExactMatch; + } + return foundExactMatch; + } + function tryUpdateString(element) { + if (!ts.isStringLiteral(element)) + return false; + var elementFileName = combinePathsSafe(configDir, element.text); + var updated = oldToNew(elementFileName); + if (updated !== undefined) { + changeTracker.replaceRangeWithText(configFile, createStringRange(element, configFile), relativePath(updated)); + return true; + } + return false; + } + function relativePath(path) { + return ts.getRelativePathFromDirectory(configDir, path, /*ignoreCase*/ !useCaseSensitiveFileNames); + } + } + function updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName) { + var allFiles = program.getSourceFiles(); + var _loop_12 = function (sourceFile) { + var newFromOld = oldToNew(sourceFile.path); + var newImportFromPath = newFromOld !== undefined ? newFromOld : sourceFile.path; + var newImportFromDirectory = ts.getDirectoryPath(newImportFromPath); + var oldFromNew = newToOld(sourceFile.fileName); + var oldImportFromPath = oldFromNew || sourceFile.fileName; + var oldImportFromDirectory = ts.getDirectoryPath(oldImportFromPath); + var importingSourceFileMoved = newFromOld !== undefined || oldFromNew !== undefined; + updateImportsWorker(sourceFile, changeTracker, function (referenceText) { + if (!ts.pathIsRelative(referenceText)) + return undefined; + var oldAbsolute = combinePathsSafe(oldImportFromDirectory, referenceText); + var newAbsolute = oldToNew(oldAbsolute); + return newAbsolute === undefined ? undefined : ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(newImportFromDirectory, newAbsolute, getCanonicalFileName)); + }, function (importLiteral) { + var importedModuleSymbol = program.getTypeChecker().getSymbolAtLocation(importLiteral); + // No need to update if it's an ambient module^M + if (importedModuleSymbol && importedModuleSymbol.declarations.some(function (d) { return ts.isAmbientModule(d); })) + return undefined; + var toImport = oldFromNew !== undefined + // If we're at the new location (file was already renamed), need to redo module resolution starting from the old location. + // TODO:GH#18217 + ? getSourceFileToImportFromResolved(ts.resolveModuleName(importLiteral.text, oldImportFromPath, program.getCompilerOptions(), host), oldToNew, host) + : getSourceFileToImport(importedModuleSymbol, importLiteral, sourceFile, program, host, oldToNew); + // Need an update if the imported file moved, or the importing file moved and was using a relative path. + return toImport !== undefined && (toImport.updated || (importingSourceFileMoved && ts.pathIsRelative(importLiteral.text))) + ? ts.moduleSpecifiers.updateModuleSpecifier(program.getCompilerOptions(), newImportFromPath, toImport.newFileName, host, allFiles, program.redirectTargetsMap, importLiteral.text) + : undefined; + }); + }; + for (var _i = 0, allFiles_1 = allFiles; _i < allFiles_1.length; _i++) { + var sourceFile = allFiles_1[_i]; + _loop_12(sourceFile); + } + } + function combineNormal(pathA, pathB) { + return ts.normalizePath(ts.combinePaths(pathA, pathB)); + } + function combinePathsSafe(pathA, pathB) { + return ts.ensurePathIsNonModuleName(combineNormal(pathA, pathB)); + } + function getSourceFileToImport(importedModuleSymbol, importLiteral, importingSourceFile, program, host, oldToNew) { + if (importedModuleSymbol) { + // `find` should succeed because we checked for ambient modules before calling this function. + var oldFileName = ts.find(importedModuleSymbol.declarations, ts.isSourceFile).fileName; + var newFileName = oldToNew(oldFileName); + return newFileName === undefined ? { newFileName: oldFileName, updated: false } : { newFileName: newFileName, updated: true }; + } + else { + var resolved = host.resolveModuleNames + ? host.getResolvedModuleWithFailedLookupLocationsFromCache && host.getResolvedModuleWithFailedLookupLocationsFromCache(importLiteral.text, importingSourceFile.fileName) + : program.getResolvedModuleWithFailedLookupLocationsFromCache(importLiteral.text, importingSourceFile.fileName); + return getSourceFileToImportFromResolved(resolved, oldToNew, host); + } + } + function getSourceFileToImportFromResolved(resolved, oldToNew, host) { + // Search through all locations looking for a moved file, and only then test already existing files. + // This is because if `a.ts` is compiled to `a.js` and `a.ts` is moved, we don't want to resolve anything to `a.js`, but to `a.ts`'s new location. + return tryEach(tryGetNewFile) || tryEach(tryGetOldFile); + function tryEach(cb) { + return resolved && ((resolved.resolvedModule && cb(resolved.resolvedModule.resolvedFileName)) || ts.firstDefined(resolved.failedLookupLocations, cb)); + } + function tryGetNewFile(oldFileName) { + var newFileName = oldToNew(oldFileName); + return newFileName !== undefined && host.fileExists(newFileName) ? { newFileName: newFileName, updated: true } : undefined; // TODO: GH#18217 + } + function tryGetOldFile(oldFileName) { + var newFileName = oldToNew(oldFileName); + return host.fileExists(oldFileName) ? newFileName !== undefined ? { newFileName: newFileName, updated: true } : { newFileName: oldFileName, updated: false } : undefined; // TODO: GH#18217 + } + } + function updateImportsWorker(sourceFile, changeTracker, updateRef, updateImport) { + for (var _i = 0, _a = sourceFile.referencedFiles || ts.emptyArray; _i < _a.length; _i++) { // TODO: GH#26162 + var ref = _a[_i]; + var updated = updateRef(ref.fileName); + if (updated !== undefined && updated !== sourceFile.text.slice(ref.pos, ref.end)) + changeTracker.replaceRangeWithText(sourceFile, ref, updated); + } + for (var _b = 0, _c = sourceFile.imports; _b < _c.length; _b++) { + var importStringLiteral = _c[_b]; + var updated = updateImport(importStringLiteral); + if (updated !== undefined && updated !== importStringLiteral.text) + changeTracker.replaceRangeWithText(sourceFile, createStringRange(importStringLiteral, sourceFile), updated); + } + } + function createStringRange(node, sourceFile) { + return ts.createRange(node.getStart(sourceFile) + 1, node.end - 1); + } + function forEachProperty(objectLiteral, cb) { + if (!ts.isObjectLiteralExpression(objectLiteral)) + return; + for (var _i = 0, _a = objectLiteral.properties; _i < _a.length; _i++) { + var property = _a[_i]; + if (ts.isPropertyAssignment(property) && ts.isStringLiteral(property.name)) { + cb(property, property.name.text); + } + } + } +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var GoToDefinition; + (function (GoToDefinition) { + function getDefinitionAtPosition(program, sourceFile, position) { + var reference = getReferenceAtPosition(sourceFile, position, program); + if (reference) { + return [getDefinitionInfoForFileReference(reference.fileName, reference.file.fileName)]; + } + var node = ts.getTouchingPropertyName(sourceFile, position); + if (node === sourceFile) { + return undefined; + } + var parent = node.parent; + // Labels + if (ts.isJumpStatementTarget(node)) { + var label = ts.getTargetLabel(node.parent, node.text); + return label ? [createDefinitionInfoFromName(label, "label" /* label */, node.text, /*containerName*/ undefined)] : undefined; // TODO: GH#18217 + } + var typeChecker = program.getTypeChecker(); + var symbol = getSymbol(node, typeChecker); + // Could not find a symbol e.g. node is string or number keyword, + // or the symbol was an internal symbol and does not have a declaration e.g. undefined symbol + if (!symbol) { + return getDefinitionInfoForIndexSignatures(node, typeChecker); + } + var calledDeclaration = tryGetSignatureDeclaration(typeChecker, node); + // Don't go to the component constructor definition for a JSX element, just go to the component definition. + if (calledDeclaration && !(ts.isJsxOpeningLikeElement(node.parent) && isConstructorLike(calledDeclaration))) { + var sigInfo = createDefinitionFromSignatureDeclaration(typeChecker, calledDeclaration); + // For a function, if this is the original function definition, return just sigInfo. + // If this is the original constructor definition, parent is the class. + if (typeChecker.getRootSymbols(symbol).some(function (s) { return symbolMatchesSignature(s, calledDeclaration); }) || + // TODO: GH#25533 Following check shouldn't be necessary if 'require' is an alias + symbol.declarations && symbol.declarations.some(function (d) { return ts.isVariableDeclaration(d) && !!d.initializer && ts.isRequireCall(d.initializer, /*checkArgumentIsStringLiteralLike*/ false); })) { + return [sigInfo]; + } + else { + var defs = getDefinitionFromSymbol(typeChecker, symbol, node) || ts.emptyArray; + // For a 'super()' call, put the signature first, else put the variable first. + return node.kind === 98 /* SuperKeyword */ ? [sigInfo].concat(defs) : defs.concat([sigInfo]); + } + } + // Because name in short-hand property assignment has two different meanings: property name and property value, + // using go-to-definition at such position should go to the variable declaration of the property value rather than + // go to the declaration of the property name (in this case stay at the same position). However, if go-to-definition + // is performed at the location of property access, we would like to go to definition of the property in the short-hand + // assignment. This case and others are handled by the following code. + if (node.parent.kind === 276 /* ShorthandPropertyAssignment */) { + var shorthandSymbol_1 = typeChecker.getShorthandAssignmentValueSymbol(symbol.valueDeclaration); + return shorthandSymbol_1 ? shorthandSymbol_1.declarations.map(function (decl) { return createDefinitionInfo(decl, typeChecker, shorthandSymbol_1, node); }) : []; + } + // If the node is the name of a BindingElement within an ObjectBindingPattern instead of just returning the + // declaration the symbol (which is itself), we should try to get to the original type of the ObjectBindingPattern + // and return the property declaration for the referenced property. + // For example: + // import('./foo').then(({ b/*goto*/ar }) => undefined); => should get use to the declaration in file "./foo" + // + // function bar(onfulfilled: (value: T) => void) { //....} + // interface Test { + // pr/*destination*/op1: number + // } + // bar(({pr/*goto*/op1})=>{}); + if (ts.isPropertyName(node) && ts.isBindingElement(parent) && ts.isObjectBindingPattern(parent.parent) && + (node === (parent.propertyName || parent.name))) { + var name_5 = ts.getNameFromPropertyName(node); + var type = typeChecker.getTypeAtLocation(parent.parent); + return name_5 === undefined ? ts.emptyArray : ts.flatMap(type.isUnion() ? type.types : [type], function (t) { + var prop = t.getProperty(name_5); + return prop && getDefinitionFromSymbol(typeChecker, prop, node); + }); + } + // If the current location we want to find its definition is in an object literal, try to get the contextual type for the + // object literal, lookup the property symbol in the contextual type, and use this for goto-definition. + // For example + // interface Props{ + // /*first*/prop1: number + // prop2: boolean + // } + // function Foo(arg: Props) {} + // Foo( { pr/*1*/op1: 10, prop2: true }) + var element = ts.getContainingObjectLiteralElement(node); + if (element) { + var contextualType = element && typeChecker.getContextualType(element.parent); + if (contextualType) { + return ts.flatMap(ts.getPropertySymbolsFromContextualType(element, typeChecker, contextualType, /*unionSymbolOk*/ false), function (propertySymbol) { + return getDefinitionFromSymbol(typeChecker, propertySymbol, node); + }); + } + } + return getDefinitionFromSymbol(typeChecker, symbol, node); + } + GoToDefinition.getDefinitionAtPosition = getDefinitionAtPosition; + /** + * True if we should not add definitions for both the signature symbol and the definition symbol. + * True for `const |f = |() => 0`, false for `function |f() {} const |g = f;`. + */ + function symbolMatchesSignature(s, calledDeclaration) { + return s === calledDeclaration.symbol || s === calledDeclaration.symbol.parent || + !ts.isCallLikeExpression(calledDeclaration.parent) && s === calledDeclaration.parent.symbol; + } + function getReferenceAtPosition(sourceFile, position, program) { + var referencePath = findReferenceInPosition(sourceFile.referencedFiles, position); + if (referencePath) { + var file = ts.tryResolveScriptReference(program, sourceFile, referencePath); + return file && { fileName: referencePath.fileName, file: file }; + } + var typeReferenceDirective = findReferenceInPosition(sourceFile.typeReferenceDirectives, position); + if (typeReferenceDirective) { + var reference = program.getResolvedTypeReferenceDirectives().get(typeReferenceDirective.fileName); + var file = reference && program.getSourceFile(reference.resolvedFileName); // TODO:GH#18217 + return file && { fileName: typeReferenceDirective.fileName, file: file }; + } + var libReferenceDirective = findReferenceInPosition(sourceFile.libReferenceDirectives, position); + if (libReferenceDirective) { + var file = program.getLibFileFromReference(libReferenceDirective); + return file && { fileName: libReferenceDirective.fileName, file: file }; + } + return undefined; + } + GoToDefinition.getReferenceAtPosition = getReferenceAtPosition; + /// Goto type + function getTypeDefinitionAtPosition(typeChecker, sourceFile, position) { + var node = ts.getTouchingPropertyName(sourceFile, position); + if (node === sourceFile) { + return undefined; + } + var symbol = typeChecker.getSymbolAtLocation(node); + if (!symbol) + return undefined; + var typeAtLocation = typeChecker.getTypeOfSymbolAtLocation(symbol, node); + var returnType = tryGetReturnTypeOfFunction(symbol, typeAtLocation, typeChecker); + var fromReturnType = returnType && definitionFromType(returnType, typeChecker, node); + // If a function returns 'void' or some other type with no definition, just return the function definition. + return fromReturnType && fromReturnType.length !== 0 ? fromReturnType : definitionFromType(typeAtLocation, typeChecker, node); + } + GoToDefinition.getTypeDefinitionAtPosition = getTypeDefinitionAtPosition; + function definitionFromType(type, checker, node) { + return ts.flatMap(type.isUnion() && !(type.flags & 32 /* Enum */) ? type.types : [type], function (t) { + return t.symbol && getDefinitionFromSymbol(checker, t.symbol, node); + }); + } + function tryGetReturnTypeOfFunction(symbol, type, checker) { + // If the type is just a function's inferred type, + // go-to-type should go to the return type instead, since go-to-definition takes you to the function anyway. + if (type.symbol === symbol || + // At `const f = () => {}`, the symbol is `f` and the type symbol is at `() => {}` + symbol.valueDeclaration && type.symbol && ts.isVariableDeclaration(symbol.valueDeclaration) && symbol.valueDeclaration.initializer === type.symbol.valueDeclaration) { + var sigs = type.getCallSignatures(); + if (sigs.length === 1) + return checker.getReturnTypeOfSignature(ts.first(sigs)); + } + return undefined; + } + function getDefinitionAndBoundSpan(program, sourceFile, position) { + var definitions = getDefinitionAtPosition(program, sourceFile, position); + if (!definitions || definitions.length === 0) { + return undefined; + } + // Check if position is on triple slash reference. + var comment = findReferenceInPosition(sourceFile.referencedFiles, position) || + findReferenceInPosition(sourceFile.typeReferenceDirectives, position) || + findReferenceInPosition(sourceFile.libReferenceDirectives, position); + if (comment) { + return { definitions: definitions, textSpan: ts.createTextSpanFromRange(comment) }; + } + var node = ts.getTouchingPropertyName(sourceFile, position); + var textSpan = ts.createTextSpan(node.getStart(), node.getWidth()); + return { definitions: definitions, textSpan: textSpan }; + } + GoToDefinition.getDefinitionAndBoundSpan = getDefinitionAndBoundSpan; + // At 'x.foo', see if the type of 'x' has an index signature, and if so find its declarations. + function getDefinitionInfoForIndexSignatures(node, checker) { + if (!ts.isPropertyAccessExpression(node.parent) || node.parent.name !== node) + return; + var type = checker.getTypeAtLocation(node.parent.expression); + return ts.mapDefined(type.isUnionOrIntersection() ? type.types : [type], function (nonUnionType) { + var info = checker.getIndexInfoOfType(nonUnionType, 0 /* String */); + return info && info.declaration && createDefinitionFromSignatureDeclaration(checker, info.declaration); + }); + } + function getSymbol(node, checker) { + var symbol = checker.getSymbolAtLocation(node); + // If this is an alias, and the request came at the declaration location + // get the aliased symbol instead. This allows for goto def on an import e.g. + // import {A, B} from "mod"; + // to jump to the implementation directly. + if (symbol && symbol.flags & 2097152 /* Alias */ && shouldSkipAlias(node, symbol.declarations[0])) { + var aliased = checker.getAliasedSymbol(symbol); + if (aliased.declarations) { + return aliased; + } + } + return symbol; + } + // Go to the original declaration for cases: + // + // (1) when the aliased symbol was declared in the location(parent). + // (2) when the aliased symbol is originating from an import. + // + function shouldSkipAlias(node, declaration) { + if (node.kind !== 72 /* Identifier */) { + return false; + } + if (node.parent === declaration) { + return true; + } + switch (declaration.kind) { + case 250 /* ImportClause */: + case 248 /* ImportEqualsDeclaration */: + return true; + case 253 /* ImportSpecifier */: + return declaration.parent.kind === 252 /* NamedImports */; + default: + return false; + } + } + function getDefinitionFromSymbol(typeChecker, symbol, node) { + return getConstructSignatureDefinition() || getCallSignatureDefinition() || ts.map(symbol.declarations, function (declaration) { return createDefinitionInfo(declaration, typeChecker, symbol, node); }); + function getConstructSignatureDefinition() { + // Applicable only if we are in a new expression, or we are on a constructor declaration + // and in either case the symbol has a construct signature definition, i.e. class + if (symbol.flags & 32 /* Class */ && (ts.isNewExpressionTarget(node) || node.kind === 124 /* ConstructorKeyword */)) { + var cls = ts.find(symbol.declarations, ts.isClassLike) || ts.Debug.fail("Expected declaration to have at least one class-like declaration"); + return getSignatureDefinition(cls.members, /*selectConstructors*/ true); + } + } + function getCallSignatureDefinition() { + return ts.isCallOrNewExpressionTarget(node) || ts.isNameOfFunctionDeclaration(node) + ? getSignatureDefinition(symbol.declarations, /*selectConstructors*/ false) + : undefined; + } + function getSignatureDefinition(signatureDeclarations, selectConstructors) { + if (!signatureDeclarations) { + return undefined; + } + var declarations = signatureDeclarations.filter(selectConstructors ? ts.isConstructorDeclaration : ts.isFunctionLike); + return declarations.length + ? [createDefinitionInfo(ts.find(declarations, function (d) { return !!d.body; }) || ts.last(declarations), typeChecker, symbol, node)] + : undefined; + } + } + /** Creates a DefinitionInfo from a Declaration, using the declaration's name if possible. */ + function createDefinitionInfo(declaration, checker, symbol, node) { + var symbolName = checker.symbolToString(symbol); // Do not get scoped name, just the name of the symbol + var symbolKind = ts.SymbolDisplay.getSymbolKind(checker, symbol, node); + var containerName = symbol.parent ? checker.symbolToString(symbol.parent, node) : ""; + return createDefinitionInfoFromName(declaration, symbolKind, symbolName, containerName); + } + /** Creates a DefinitionInfo directly from the name of a declaration. */ + function createDefinitionInfoFromName(declaration, symbolKind, symbolName, containerName) { + var name = ts.getNameOfDeclaration(declaration) || declaration; + var sourceFile = name.getSourceFile(); + return { + fileName: sourceFile.fileName, + textSpan: ts.createTextSpanFromNode(name, sourceFile), + kind: symbolKind, + name: symbolName, + containerKind: undefined, + containerName: containerName + }; + } + function createDefinitionFromSignatureDeclaration(typeChecker, decl) { + return createDefinitionInfo(decl, typeChecker, decl.symbol, decl); + } + function findReferenceInPosition(refs, pos) { + return ts.find(refs, function (ref) { return ts.textRangeContainsPositionInclusive(ref, pos); }); + } + GoToDefinition.findReferenceInPosition = findReferenceInPosition; + function getDefinitionInfoForFileReference(name, targetFileName) { + return { + fileName: targetFileName, + textSpan: ts.createTextSpanFromBounds(0, 0), + kind: "script" /* scriptElement */, + name: name, + containerName: undefined, + containerKind: undefined, + }; + } + /** Returns a CallLikeExpression where `node` is the target being invoked. */ + function getAncestorCallLikeExpression(node) { + var target = climbPastManyPropertyAccesses(node); + var callLike = target.parent; + return callLike && ts.isCallLikeExpression(callLike) && ts.getInvokedExpression(callLike) === target ? callLike : undefined; + } + function climbPastManyPropertyAccesses(node) { + return ts.isRightSideOfPropertyAccess(node) ? climbPastManyPropertyAccesses(node.parent) : node; + } + function tryGetSignatureDeclaration(typeChecker, node) { + var callLike = getAncestorCallLikeExpression(node); + var signature = callLike && typeChecker.getResolvedSignature(callLike); + // Don't go to a function type, go to the value having that type. + return ts.tryCast(signature && signature.declaration, function (d) { return ts.isFunctionLike(d) && !ts.isFunctionTypeNode(d); }); + } + function isConstructorLike(node) { + switch (node.kind) { + case 157 /* Constructor */: + case 166 /* ConstructorType */: + case 161 /* ConstructSignature */: + return true; + default: + return false; + } + } + })(GoToDefinition = ts.GoToDefinition || (ts.GoToDefinition = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var JsDoc; + (function (JsDoc) { + var jsDocTagNames = [ + "abstract", + "access", + "alias", + "argument", + "async", + "augments", + "author", + "borrows", + "callback", + "class", + "classdesc", + "constant", + "constructor", + "constructs", + "copyright", + "default", + "deprecated", + "description", + "emits", + "enum", + "event", + "example", + "exports", + "extends", + "external", + "field", + "file", + "fileoverview", + "fires", + "function", + "generator", + "global", + "hideconstructor", + "host", + "ignore", + "implements", + "inheritdoc", + "inner", + "instance", + "interface", + "kind", + "lends", + "license", + "listens", + "member", + "memberof", + "method", + "mixes", + "module", + "name", + "namespace", + "override", + "package", + "param", + "private", + "property", + "protected", + "public", + "readonly", + "requires", + "returns", + "see", + "since", + "static", + "summary", + "template", + "this", + "throws", + "todo", + "tutorial", + "type", + "typedef", + "var", + "variation", + "version", + "virtual", + "yields" + ]; + var jsDocTagNameCompletionEntries; + var jsDocTagCompletionEntries; + function getJsDocCommentsFromDeclarations(declarations) { + // Only collect doc comments from duplicate declarations once: + // In case of a union property there might be same declaration multiple times + // which only varies in type parameter + // Eg. const a: Array | Array; a.length + // The property length will have two declarations of property length coming + // from Array - Array and Array + var documentationComment = []; + forEachUnique(declarations, function (declaration) { + for (var _i = 0, _a = getCommentHavingNodes(declaration); _i < _a.length; _i++) { + var comment = _a[_i].comment; + if (comment === undefined) + continue; + if (documentationComment.length) { + documentationComment.push(ts.lineBreakPart()); + } + documentationComment.push(ts.textPart(comment)); + } + }); + return documentationComment; + } + JsDoc.getJsDocCommentsFromDeclarations = getJsDocCommentsFromDeclarations; + function getCommentHavingNodes(declaration) { + switch (declaration.kind) { + case 299 /* JSDocParameterTag */: + case 305 /* JSDocPropertyTag */: + return [declaration]; + case 297 /* JSDocCallbackTag */: + case 304 /* JSDocTypedefTag */: + return [declaration, declaration.parent]; + default: + return ts.getJSDocCommentsAndTags(declaration); + } + } + function getJsDocTagsFromDeclarations(declarations) { + // Only collect doc comments from duplicate declarations once. + var tags = []; + forEachUnique(declarations, function (declaration) { + for (var _i = 0, _a = ts.getJSDocTags(declaration); _i < _a.length; _i++) { + var tag = _a[_i]; + tags.push({ name: tag.tagName.text, text: getCommentText(tag) }); + } + }); + return tags; + } + JsDoc.getJsDocTagsFromDeclarations = getJsDocTagsFromDeclarations; + function getCommentText(tag) { + var comment = tag.comment; + switch (tag.kind) { + case 295 /* JSDocAugmentsTag */: + return withNode(tag.class); + case 303 /* JSDocTemplateTag */: + return withList(tag.typeParameters); + case 302 /* JSDocTypeTag */: + return withNode(tag.typeExpression); + case 304 /* JSDocTypedefTag */: + case 297 /* JSDocCallbackTag */: + case 305 /* JSDocPropertyTag */: + case 299 /* JSDocParameterTag */: + var name = tag.name; + return name ? withNode(name) : comment; + default: + return comment; + } + function withNode(node) { + return addComment(node.getText()); + } + function withList(list) { + return addComment(list.map(function (x) { return x.getText(); }).join(", ")); + } + function addComment(s) { + return comment === undefined ? s : s + " " + comment; + } + } + /** + * Iterates through 'array' by index and performs the callback on each element of array until the callback + * returns a truthy value, then returns that value. + * If no such value is found, the callback is applied to each element of array and undefined is returned. + */ + function forEachUnique(array, callback) { + if (array) { + for (var i = 0; i < array.length; i++) { + if (array.indexOf(array[i]) === i) { + var result = callback(array[i], i); + if (result) { + return result; + } + } + } + } + return undefined; + } + function getJSDocTagNameCompletions() { + return jsDocTagNameCompletionEntries || (jsDocTagNameCompletionEntries = ts.map(jsDocTagNames, function (tagName) { + return { + name: tagName, + kind: "keyword" /* keyword */, + kindModifiers: "", + sortText: "0", + }; + })); + } + JsDoc.getJSDocTagNameCompletions = getJSDocTagNameCompletions; + JsDoc.getJSDocTagNameCompletionDetails = getJSDocTagCompletionDetails; + function getJSDocTagCompletions() { + return jsDocTagCompletionEntries || (jsDocTagCompletionEntries = ts.map(jsDocTagNames, function (tagName) { + return { + name: "@" + tagName, + kind: "keyword" /* keyword */, + kindModifiers: "", + sortText: "0" + }; + })); + } + JsDoc.getJSDocTagCompletions = getJSDocTagCompletions; + function getJSDocTagCompletionDetails(name) { + return { + name: name, + kind: "" /* unknown */, + kindModifiers: "", + displayParts: [ts.textPart(name)], + documentation: ts.emptyArray, + tags: undefined, + codeActions: undefined, + }; + } + JsDoc.getJSDocTagCompletionDetails = getJSDocTagCompletionDetails; + function getJSDocParameterNameCompletions(tag) { + if (!ts.isIdentifier(tag.name)) { + return ts.emptyArray; + } + var nameThusFar = tag.name.text; + var jsdoc = tag.parent; + var fn = jsdoc.parent; + if (!ts.isFunctionLike(fn)) + return []; + return ts.mapDefined(fn.parameters, function (param) { + if (!ts.isIdentifier(param.name)) + return undefined; + var name = param.name.text; + if (jsdoc.tags.some(function (t) { return t !== tag && ts.isJSDocParameterTag(t) && ts.isIdentifier(t.name) && t.name.escapedText === name; }) // TODO: GH#18217 + || nameThusFar !== undefined && !ts.startsWith(name, nameThusFar)) { + return undefined; + } + return { name: name, kind: "parameter" /* parameterElement */, kindModifiers: "", sortText: "0" }; + }); + } + JsDoc.getJSDocParameterNameCompletions = getJSDocParameterNameCompletions; + function getJSDocParameterNameCompletionDetails(name) { + return { + name: name, + kind: "parameter" /* parameterElement */, + kindModifiers: "", + displayParts: [ts.textPart(name)], + documentation: ts.emptyArray, + tags: undefined, + codeActions: undefined, + }; + } + JsDoc.getJSDocParameterNameCompletionDetails = getJSDocParameterNameCompletionDetails; + /** + * Checks if position points to a valid position to add JSDoc comments, and if so, + * returns the appropriate template. Otherwise returns an empty string. + * Valid positions are + * - outside of comments, statements, and expressions, and + * - preceding a: + * - function/constructor/method declaration + * - class declarations + * - variable statements + * - namespace declarations + * - interface declarations + * - method signatures + * - type alias declarations + * + * Hosts should ideally check that: + * - The line is all whitespace up to 'position' before performing the insertion. + * - If the keystroke sequence "/\*\*" induced the call, we also check that the next + * non-whitespace character is '*', which (approximately) indicates whether we added + * the second '*' to complete an existing (JSDoc) comment. + * @param fileName The file in which to perform the check. + * @param position The (character-indexed) position in the file where the check should + * be performed. + */ + function getDocCommentTemplateAtPosition(newLine, sourceFile, position) { + var tokenAtPos = ts.getTokenAtPosition(sourceFile, position); + var existingDocComment = ts.findAncestor(tokenAtPos, ts.isJSDoc); + if (existingDocComment && (existingDocComment.comment !== undefined || ts.length(existingDocComment.tags))) { + // Non-empty comment already exists. + return undefined; + } + var tokenStart = tokenAtPos.getStart(sourceFile); + // Don't provide a doc comment template based on a *previous* node. (But an existing empty jsdoc comment will likely start before `position`.) + if (!existingDocComment && tokenStart < position) { + return undefined; + } + var commentOwnerInfo = getCommentOwnerInfo(tokenAtPos); + if (!commentOwnerInfo) { + return undefined; + } + var commentOwner = commentOwnerInfo.commentOwner, parameters = commentOwnerInfo.parameters; + if (commentOwner.getStart(sourceFile) < position) { + return undefined; + } + if (!parameters || parameters.length === 0) { + // if there are no parameters, just complete to a single line JSDoc comment + var singleLineResult = "/** */"; + return { newText: singleLineResult, caretOffset: 3 }; + } + var indentationStr = getIndentationStringAtPosition(sourceFile, position); + // A doc comment consists of the following + // * The opening comment line + // * the first line (without a param) for the object's untagged info (this is also where the caret ends up) + // * the '@param'-tagged lines + // * TODO: other tags. + // * the closing comment line + // * if the caret was directly in front of the object, then we add an extra line and indentation. + var preamble = "/**" + newLine + indentationStr + " * "; + var result = preamble + newLine + + parameterDocComments(parameters, ts.hasJSFileExtension(sourceFile.fileName), indentationStr, newLine) + + indentationStr + " */" + + (tokenStart === position ? newLine + indentationStr : ""); + return { newText: result, caretOffset: preamble.length }; + } + JsDoc.getDocCommentTemplateAtPosition = getDocCommentTemplateAtPosition; + function getIndentationStringAtPosition(sourceFile, position) { + var text = sourceFile.text; + var lineStart = ts.getLineStartPositionForPosition(position, sourceFile); + var pos = lineStart; + for (; pos <= position && ts.isWhiteSpaceSingleLine(text.charCodeAt(pos)); pos++) + ; + return text.slice(lineStart, pos); + } + function parameterDocComments(parameters, isJavaScriptFile, indentationStr, newLine) { + return parameters.map(function (_a, i) { + var name = _a.name, dotDotDotToken = _a.dotDotDotToken; + var paramName = name.kind === 72 /* Identifier */ ? name.text : "param" + i; + var type = isJavaScriptFile ? (dotDotDotToken ? "{...any} " : "{any} ") : ""; + return indentationStr + " * @param " + type + paramName + newLine; + }).join(""); + } + function getCommentOwnerInfo(tokenAtPos) { + return ts.forEachAncestor(tokenAtPos, getCommentOwnerInfoWorker); + } + function getCommentOwnerInfoWorker(commentOwner) { + switch (commentOwner.kind) { + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 156 /* MethodDeclaration */: + case 157 /* Constructor */: + case 155 /* MethodSignature */: + var parameters = commentOwner.parameters; + return { commentOwner: commentOwner, parameters: parameters }; + case 275 /* PropertyAssignment */: + return getCommentOwnerInfoWorker(commentOwner.initializer); + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + case 153 /* PropertySignature */: + case 243 /* EnumDeclaration */: + case 278 /* EnumMember */: + case 242 /* TypeAliasDeclaration */: + return { commentOwner: commentOwner }; + case 219 /* VariableStatement */: { + var varStatement = commentOwner; + var varDeclarations = varStatement.declarationList.declarations; + var parameters_1 = varDeclarations.length === 1 && varDeclarations[0].initializer + ? getParametersFromRightHandSideOfAssignment(varDeclarations[0].initializer) + : undefined; + return { commentOwner: commentOwner, parameters: parameters_1 }; + } + case 279 /* SourceFile */: + return "quit"; + case 244 /* ModuleDeclaration */: + // If in walking up the tree, we hit a a nested namespace declaration, + // then we must be somewhere within a dotted namespace name; however we don't + // want to give back a JSDoc template for the 'b' or 'c' in 'namespace a.b.c { }'. + return commentOwner.parent.kind === 244 /* ModuleDeclaration */ ? undefined : { commentOwner: commentOwner }; + case 204 /* BinaryExpression */: { + var be = commentOwner; + if (ts.getAssignmentDeclarationKind(be) === 0 /* None */) { + return "quit"; + } + var parameters_2 = ts.isFunctionLike(be.right) ? be.right.parameters : ts.emptyArray; + return { commentOwner: commentOwner, parameters: parameters_2 }; + } + } + } + /** + * Digs into an an initializer or RHS operand of an assignment operation + * to get the parameters of an apt signature corresponding to a + * function expression or a class expression. + * + * @param rightHandSide the expression which may contain an appropriate set of parameters + * @returns the parameters of a signature found on the RHS if one exists; otherwise 'emptyArray'. + */ + function getParametersFromRightHandSideOfAssignment(rightHandSide) { + while (rightHandSide.kind === 195 /* ParenthesizedExpression */) { + rightHandSide = rightHandSide.expression; + } + switch (rightHandSide.kind) { + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + return rightHandSide.parameters; + case 209 /* ClassExpression */: { + var ctr = ts.find(rightHandSide.members, ts.isConstructorDeclaration); + return ctr ? ctr.parameters : ts.emptyArray; + } + } + return ts.emptyArray; + } + })(JsDoc = ts.JsDoc || (ts.JsDoc = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var NavigateTo; + (function (NavigateTo) { + function getNavigateToItems(sourceFiles, checker, cancellationToken, searchValue, maxResultCount, excludeDtsFiles) { + var patternMatcher = ts.createPatternMatcher(searchValue); + if (!patternMatcher) + return ts.emptyArray; + var rawItems = []; + var _loop_13 = function (sourceFile) { + cancellationToken.throwIfCancellationRequested(); + if (excludeDtsFiles && sourceFile.isDeclarationFile) { + return "continue"; + } + sourceFile.getNamedDeclarations().forEach(function (declarations, name) { + getItemsFromNamedDeclaration(patternMatcher, name, declarations, checker, sourceFile.fileName, rawItems); + }); + }; + // Search the declarations in all files and output matched NavigateToItem into array of NavigateToItem[] + for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) { + var sourceFile = sourceFiles_6[_i]; + _loop_13(sourceFile); + } + rawItems.sort(compareNavigateToItems); + return (maxResultCount === undefined ? rawItems : rawItems.slice(0, maxResultCount)).map(createNavigateToItem); + } + NavigateTo.getNavigateToItems = getNavigateToItems; + function getItemsFromNamedDeclaration(patternMatcher, name, declarations, checker, fileName, rawItems) { + // First do a quick check to see if the name of the declaration matches the + // last portion of the (possibly) dotted name they're searching for. + var match = patternMatcher.getMatchForLastSegmentOfPattern(name); + if (!match) { + return; // continue to next named declarations + } + for (var _i = 0, declarations_13 = declarations; _i < declarations_13.length; _i++) { + var declaration = declarations_13[_i]; + if (!shouldKeepItem(declaration, checker)) + continue; + if (patternMatcher.patternContainsDots) { + // If the pattern has dots in it, then also see if the declaration container matches as well. + var fullMatch = patternMatcher.getFullMatch(getContainers(declaration), name); + if (fullMatch) { + rawItems.push({ name: name, fileName: fileName, matchKind: fullMatch.kind, isCaseSensitive: fullMatch.isCaseSensitive, declaration: declaration }); + } + } + else { + rawItems.push({ name: name, fileName: fileName, matchKind: match.kind, isCaseSensitive: match.isCaseSensitive, declaration: declaration }); + } + } + } + function shouldKeepItem(declaration, checker) { + switch (declaration.kind) { + case 250 /* ImportClause */: + case 253 /* ImportSpecifier */: + case 248 /* ImportEqualsDeclaration */: + var importer = checker.getSymbolAtLocation(declaration.name); // TODO: GH#18217 + var imported = checker.getAliasedSymbol(importer); + return importer.escapedName !== imported.escapedName; + default: + return true; + } + } + function tryAddSingleDeclarationName(declaration, containers) { + var name = ts.getNameOfDeclaration(declaration); + return !!name && (pushLiteral(name, containers) || name.kind === 149 /* ComputedPropertyName */ && tryAddComputedPropertyName(name.expression, containers)); + } + // Only added the names of computed properties if they're simple dotted expressions, like: + // + // [X.Y.Z]() { } + function tryAddComputedPropertyName(expression, containers) { + return pushLiteral(expression, containers) + || ts.isPropertyAccessExpression(expression) && (containers.push(expression.name.text), true) && tryAddComputedPropertyName(expression.expression, containers); + } + function pushLiteral(node, containers) { + return ts.isPropertyNameLiteral(node) && (containers.push(ts.getTextOfIdentifierOrLiteral(node)), true); + } + function getContainers(declaration) { + var containers = []; + // First, if we started with a computed property name, then add all but the last + // portion into the container array. + var name = ts.getNameOfDeclaration(declaration); + if (name && name.kind === 149 /* ComputedPropertyName */ && !tryAddComputedPropertyName(name.expression, containers)) { + return ts.emptyArray; + } + // Don't include the last portion. + containers.shift(); + // Now, walk up our containers, adding all their names to the container array. + var container = ts.getContainerNode(declaration); + while (container) { + if (!tryAddSingleDeclarationName(container, containers)) { + return ts.emptyArray; + } + container = ts.getContainerNode(container); + } + return containers.reverse(); + } + function compareNavigateToItems(i1, i2) { + // TODO(cyrusn): get the gamut of comparisons that VS already uses here. + return ts.compareValues(i1.matchKind, i2.matchKind) + || ts.compareStringsCaseSensitiveUI(i1.name, i2.name); + } + function createNavigateToItem(rawItem) { + var declaration = rawItem.declaration; + var container = ts.getContainerNode(declaration); + var containerName = container && ts.getNameOfDeclaration(container); + return { + name: rawItem.name, + kind: ts.getNodeKind(declaration), + kindModifiers: ts.getNodeModifiers(declaration), + matchKind: ts.PatternMatchKind[rawItem.matchKind], + isCaseSensitive: rawItem.isCaseSensitive, + fileName: rawItem.fileName, + textSpan: ts.createTextSpanFromNode(declaration), + // TODO(jfreeman): What should be the containerName when the container has a computed name? + containerName: containerName ? containerName.text : "", + containerKind: containerName ? ts.getNodeKind(container) : "" /* unknown */, + }; + } + })(NavigateTo = ts.NavigateTo || (ts.NavigateTo = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var NavigationBar; + (function (NavigationBar) { + /** + * Matches all whitespace characters in a string. Eg: + * + * "app. + * + * onactivated" + * + * matches because of the newline, whereas + * + * "app.onactivated" + * + * does not match. + */ + var whiteSpaceRegex = /\s+/g; + // Keep sourceFile handy so we don't have to search for it every time we need to call `getText`. + var curCancellationToken; + var curSourceFile; + /** + * For performance, we keep navigation bar parents on a stack rather than passing them through each recursion. + * `parent` is the current parent and is *not* stored in parentsStack. + * `startNode` sets a new parent and `endNode` returns to the previous parent. + */ + var parentsStack = []; + var parent; + // NavigationBarItem requires an array, but will not mutate it, so just give it this for performance. + var emptyChildItemArray = []; + function getNavigationBarItems(sourceFile, cancellationToken) { + curCancellationToken = cancellationToken; + curSourceFile = sourceFile; + try { + return ts.map(topLevelItems(rootNavigationBarNode(sourceFile)), convertToTopLevelItem); + } + finally { + reset(); + } + } + NavigationBar.getNavigationBarItems = getNavigationBarItems; + function getNavigationTree(sourceFile, cancellationToken) { + curCancellationToken = cancellationToken; + curSourceFile = sourceFile; + try { + return convertToTree(rootNavigationBarNode(sourceFile)); + } + finally { + reset(); + } + } + NavigationBar.getNavigationTree = getNavigationTree; + function reset() { + curSourceFile = undefined; + curCancellationToken = undefined; + parentsStack = []; + parent = undefined; + emptyChildItemArray = []; + } + function nodeText(node) { + return node.getText(curSourceFile); + } + function navigationBarNodeKind(n) { + return n.node.kind; + } + function pushChild(parent, child) { + if (parent.children) { + parent.children.push(child); + } + else { + parent.children = [child]; + } + } + function rootNavigationBarNode(sourceFile) { + ts.Debug.assert(!parentsStack.length); + var root = { node: sourceFile, name: undefined, additionalNodes: undefined, parent: undefined, children: undefined, indent: 0 }; + parent = root; + for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + addChildrenRecursively(statement); + } + endNode(); + ts.Debug.assert(!parent && !parentsStack.length); + return root; + } + function addLeafNode(node) { + pushChild(parent, emptyNavigationBarNode(node)); + } + function emptyNavigationBarNode(node) { + return { + node: node, + name: ts.isDeclaration(node) || ts.isExpression(node) ? ts.getNameOfDeclaration(node) : undefined, + additionalNodes: undefined, + parent: parent, + children: undefined, + indent: parent.indent + 1 + }; + } + /** + * Add a new level of NavigationBarNodes. + * This pushes to the stack, so you must call `endNode` when you are done adding to this node. + */ + function startNode(node) { + var navNode = emptyNavigationBarNode(node); + pushChild(parent, navNode); + // Save the old parent + parentsStack.push(parent); + parent = navNode; + } + /** Call after calling `startNode` and adding children to it. */ + function endNode() { + if (parent.children) { + mergeChildren(parent.children, parent); + sortChildren(parent.children); + } + parent = parentsStack.pop(); + } + function addNodeWithRecursiveChild(node, child) { + startNode(node); + addChildrenRecursively(child); + endNode(); + } + /** Look for navigation bar items in node's subtree, adding them to the current `parent`. */ + function addChildrenRecursively(node) { + curCancellationToken.throwIfCancellationRequested(); + if (!node || ts.isToken(node)) { + return; + } + switch (node.kind) { + case 157 /* Constructor */: + // Get parameter properties, and treat them as being on the *same* level as the constructor, not under it. + var ctr = node; + addNodeWithRecursiveChild(ctr, ctr.body); + // Parameter properties are children of the class, not the constructor. + for (var _i = 0, _a = ctr.parameters; _i < _a.length; _i++) { + var param = _a[_i]; + if (ts.isParameterPropertyDeclaration(param)) { + addLeafNode(param); + } + } + break; + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 155 /* MethodSignature */: + if (!ts.hasDynamicName(node)) { + addNodeWithRecursiveChild(node, node.body); + } + break; + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + if (!ts.hasDynamicName(node)) { + addLeafNode(node); + } + break; + case 250 /* ImportClause */: + var importClause = node; + // Handle default import case e.g.: + // import d from "mod"; + if (importClause.name) { + addLeafNode(importClause.name); + } + // Handle named bindings in imports e.g.: + // import * as NS from "mod"; + // import {a, b as B} from "mod"; + var namedBindings = importClause.namedBindings; + if (namedBindings) { + if (namedBindings.kind === 251 /* NamespaceImport */) { + addLeafNode(namedBindings); + } + else { + for (var _b = 0, _c = namedBindings.elements; _b < _c.length; _b++) { + var element = _c[_b]; + addLeafNode(element); + } + } + } + break; + case 186 /* BindingElement */: + case 237 /* VariableDeclaration */: + var _d = node, name = _d.name, initializer = _d.initializer; + if (ts.isBindingPattern(name)) { + addChildrenRecursively(name); + } + else if (initializer && isFunctionOrClassExpression(initializer)) { + if (initializer.name) { + // Don't add a node for the VariableDeclaration, just for the initializer. + addChildrenRecursively(initializer); + } + else { + // Add a node for the VariableDeclaration, but not for the initializer. + startNode(node); + ts.forEachChild(initializer, addChildrenRecursively); + endNode(); + } + } + else { + addNodeWithRecursiveChild(node, initializer); + } + break; + case 197 /* ArrowFunction */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + addNodeWithRecursiveChild(node, node.body); + break; + case 243 /* EnumDeclaration */: + startNode(node); + for (var _e = 0, _f = node.members; _e < _f.length; _e++) { + var member = _f[_e]; + if (!isComputedProperty(member)) { + addLeafNode(member); + } + } + endNode(); + break; + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 241 /* InterfaceDeclaration */: + startNode(node); + for (var _g = 0, _h = node.members; _g < _h.length; _g++) { + var member = _h[_g]; + addChildrenRecursively(member); + } + endNode(); + break; + case 244 /* ModuleDeclaration */: + addNodeWithRecursiveChild(node, getInteriorModule(node).body); + break; + case 257 /* ExportSpecifier */: + case 248 /* ImportEqualsDeclaration */: + case 162 /* IndexSignature */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 242 /* TypeAliasDeclaration */: + addLeafNode(node); + break; + case 204 /* BinaryExpression */: { + var special = ts.getAssignmentDeclarationKind(node); + switch (special) { + case 1 /* ExportsProperty */: + case 2 /* ModuleExports */: + case 3 /* PrototypeProperty */: + case 6 /* Prototype */: + addNodeWithRecursiveChild(node, node.right); + return; + case 4 /* ThisProperty */: + case 5 /* Property */: + case 0 /* None */: + case 7 /* ObjectDefinePropertyValue */: + case 8 /* ObjectDefinePropertyExports */: + case 9 /* ObjectDefinePrototypeProperty */: + break; + default: + ts.Debug.assertNever(special); + } + } + // falls through + default: + if (ts.hasJSDocNodes(node)) { + ts.forEach(node.jsDoc, function (jsDoc) { + ts.forEach(jsDoc.tags, function (tag) { + if (ts.isJSDocTypeAlias(tag)) { + addLeafNode(tag); + } + }); + }); + } + ts.forEachChild(node, addChildrenRecursively); + } + } + /** Merge declarations of the same kind. */ + function mergeChildren(children, node) { + var nameToItems = ts.createMap(); + ts.filterMutate(children, function (child) { + var declName = ts.getNameOfDeclaration(child.node); + var name = declName && nodeText(declName); + if (!name) { + // Anonymous items are never merged. + return true; + } + var itemsWithSameName = nameToItems.get(name); + if (!itemsWithSameName) { + nameToItems.set(name, child); + return true; + } + if (itemsWithSameName instanceof Array) { + for (var _i = 0, itemsWithSameName_1 = itemsWithSameName; _i < itemsWithSameName_1.length; _i++) { + var itemWithSameName = itemsWithSameName_1[_i]; + if (tryMerge(itemWithSameName, child, node)) { + return false; + } + } + itemsWithSameName.push(child); + return true; + } + else { + var itemWithSameName = itemsWithSameName; + if (tryMerge(itemWithSameName, child, node)) { + return false; + } + nameToItems.set(name, [itemWithSameName, child]); + return true; + } + }); + } + function tryMerge(a, b, parent) { + if (shouldReallyMerge(a.node, b.node, parent)) { + merge(a, b); + return true; + } + return false; + } + /** a and b have the same name, but they may not be mergeable. */ + function shouldReallyMerge(a, b, parent) { + if (a.kind !== b.kind || a.parent !== b.parent && !(isOwnChild(a, parent) && isOwnChild(b, parent))) { + return false; + } + switch (a.kind) { + case 154 /* PropertyDeclaration */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + return ts.hasModifier(a, 32 /* Static */) === ts.hasModifier(b, 32 /* Static */); + case 244 /* ModuleDeclaration */: + return areSameModule(a, b); + default: + return true; + } + } + // We want to merge own children like `I` in in `module A { interface I {} } module A { interface I {} }` + // We don't want to merge unrelated children like `m` in `const o = { a: { m() {} }, b: { m() {} } };` + function isOwnChild(n, parent) { + var par = ts.isModuleBlock(n.parent) ? n.parent.parent : n.parent; + return par === parent.node || ts.contains(parent.additionalNodes, par); + } + // We use 1 NavNode to represent 'A.B.C', but there are multiple source nodes. + // Only merge module nodes that have the same chain. Don't merge 'A.B.C' with 'A'! + function areSameModule(a, b) { + // TODO: GH#18217 + return a.body.kind === b.body.kind && (a.body.kind !== 244 /* ModuleDeclaration */ || areSameModule(a.body, b.body)); + } + /** Merge source into target. Source should be thrown away after this is called. */ + function merge(target, source) { + var _a; + target.additionalNodes = target.additionalNodes || []; + target.additionalNodes.push(source.node); + if (source.additionalNodes) { + (_a = target.additionalNodes).push.apply(_a, source.additionalNodes); + } + target.children = ts.concatenate(target.children, source.children); + if (target.children) { + mergeChildren(target.children, target); + sortChildren(target.children); + } + } + /** Recursively ensure that each NavNode's children are in sorted order. */ + function sortChildren(children) { + children.sort(compareChildren); + } + function compareChildren(child1, child2) { + return ts.compareStringsCaseSensitiveUI(tryGetName(child1.node), tryGetName(child2.node)) // TODO: GH#18217 + || ts.compareValues(navigationBarNodeKind(child1), navigationBarNodeKind(child2)); + } + /** + * This differs from getItemName because this is just used for sorting. + * We only sort nodes by name that have a more-or-less "direct" name, as opposed to `new()` and the like. + * So `new()` can still come before an `aardvark` method. + */ + function tryGetName(node) { + if (node.kind === 244 /* ModuleDeclaration */) { + return getModuleName(node); + } + var declName = ts.getNameOfDeclaration(node); + if (declName && ts.isPropertyName(declName)) { + return ts.unescapeLeadingUnderscores(ts.getPropertyNameForPropertyNameNode(declName)); // TODO: GH#18217 + } + switch (node.kind) { + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 209 /* ClassExpression */: + return getFunctionOrClassName(node); + default: + return undefined; + } + } + function getItemName(node, name) { + if (node.kind === 244 /* ModuleDeclaration */) { + return getModuleName(node); + } + if (name) { + var text = nodeText(name); + if (text.length > 0) { + return text; + } + } + switch (node.kind) { + case 279 /* SourceFile */: + var sourceFile = node; + return ts.isExternalModule(sourceFile) + ? "\"" + ts.escapeString(ts.getBaseFileName(ts.removeFileExtension(ts.normalizePath(sourceFile.fileName)))) + "\"" + : ""; + case 197 /* ArrowFunction */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + if (ts.getModifierFlags(node) & 512 /* Default */) { + return "default"; + } + // We may get a string with newlines or other whitespace in the case of an object dereference + // (eg: "app\n.onactivated"), so we should remove the whitespace for readabiltiy in the + // navigation bar. + return getFunctionOrClassName(node); + case 157 /* Constructor */: + return "constructor"; + case 161 /* ConstructSignature */: + return "new()"; + case 160 /* CallSignature */: + return "()"; + case 162 /* IndexSignature */: + return "[]"; + default: + return ""; + } + } + /** Flattens the NavNode tree to a list, keeping only the top-level items. */ + function topLevelItems(root) { + var topLevel = []; + function recur(item) { + if (isTopLevel(item)) { + topLevel.push(item); + if (item.children) { + for (var _i = 0, _a = item.children; _i < _a.length; _i++) { + var child = _a[_i]; + recur(child); + } + } + } + } + recur(root); + return topLevel; + function isTopLevel(item) { + switch (navigationBarNodeKind(item)) { + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 243 /* EnumDeclaration */: + case 241 /* InterfaceDeclaration */: + case 244 /* ModuleDeclaration */: + case 279 /* SourceFile */: + case 242 /* TypeAliasDeclaration */: + case 304 /* JSDocTypedefTag */: + case 297 /* JSDocCallbackTag */: + return true; + case 157 /* Constructor */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 237 /* VariableDeclaration */: + return hasSomeImportantChild(item); + case 197 /* ArrowFunction */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + return isTopLevelFunctionDeclaration(item); + default: + return false; + } + function isTopLevelFunctionDeclaration(item) { + if (!item.node.body) { + return false; + } + switch (navigationBarNodeKind(item.parent)) { + case 245 /* ModuleBlock */: + case 279 /* SourceFile */: + case 156 /* MethodDeclaration */: + case 157 /* Constructor */: + return true; + default: + return hasSomeImportantChild(item); + } + } + function hasSomeImportantChild(item) { + return ts.some(item.children, function (child) { + var childKind = navigationBarNodeKind(child); + return childKind !== 237 /* VariableDeclaration */ && childKind !== 186 /* BindingElement */; + }); + } + } + } + function convertToTree(n) { + return { + text: getItemName(n.node, n.name), + kind: ts.getNodeKind(n.node), + kindModifiers: getModifiers(n.node), + spans: getSpans(n), + nameSpan: n.name && getNodeSpan(n.name), + childItems: ts.map(n.children, convertToTree) + }; + } + function convertToTopLevelItem(n) { + return { + text: getItemName(n.node, n.name), + kind: ts.getNodeKind(n.node), + kindModifiers: getModifiers(n.node), + spans: getSpans(n), + childItems: ts.map(n.children, convertToChildItem) || emptyChildItemArray, + indent: n.indent, + bolded: false, + grayed: false + }; + function convertToChildItem(n) { + return { + text: getItemName(n.node, n.name), + kind: ts.getNodeKind(n.node), + kindModifiers: ts.getNodeModifiers(n.node), + spans: getSpans(n), + childItems: emptyChildItemArray, + indent: 0, + bolded: false, + grayed: false + }; + } + } + function getSpans(n) { + var spans = [getNodeSpan(n.node)]; + if (n.additionalNodes) { + for (var _i = 0, _a = n.additionalNodes; _i < _a.length; _i++) { + var node = _a[_i]; + spans.push(getNodeSpan(node)); + } + } + return spans; + } + function getModuleName(moduleDeclaration) { + // We want to maintain quotation marks. + if (ts.isAmbientModule(moduleDeclaration)) { + return ts.getTextOfNode(moduleDeclaration.name); + } + // Otherwise, we need to aggregate each identifier to build up the qualified name. + var result = []; + result.push(ts.getTextOfIdentifierOrLiteral(moduleDeclaration.name)); + while (moduleDeclaration.body && moduleDeclaration.body.kind === 244 /* ModuleDeclaration */) { + moduleDeclaration = moduleDeclaration.body; + result.push(ts.getTextOfIdentifierOrLiteral(moduleDeclaration.name)); + } + return result.join("."); + } + /** + * For 'module A.B.C', we want to get the node for 'C'. + * We store 'A' as associated with a NavNode, and use getModuleName to traverse down again. + */ + function getInteriorModule(decl) { + return decl.body && ts.isModuleDeclaration(decl.body) ? getInteriorModule(decl.body) : decl; + } + function isComputedProperty(member) { + return !member.name || member.name.kind === 149 /* ComputedPropertyName */; + } + function getNodeSpan(node) { + return node.kind === 279 /* SourceFile */ ? ts.createTextSpanFromRange(node) : ts.createTextSpanFromNode(node, curSourceFile); + } + function getModifiers(node) { + if (node.parent && node.parent.kind === 237 /* VariableDeclaration */) { + node = node.parent; + } + return ts.getNodeModifiers(node); + } + function getFunctionOrClassName(node) { + var parent = node.parent; + if (node.name && ts.getFullWidth(node.name) > 0) { + return ts.declarationNameToString(node.name); + } + // See if it is a var initializer. If so, use the var name. + else if (ts.isVariableDeclaration(parent)) { + return ts.declarationNameToString(parent.name); + } + // See if it is of the form " = function(){...}". If so, use the text from the left-hand side. + else if (ts.isBinaryExpression(parent) && parent.operatorToken.kind === 59 /* EqualsToken */) { + return nodeText(parent.left).replace(whiteSpaceRegex, ""); + } + // See if it is a property assignment, and if so use the property name + else if (ts.isPropertyAssignment(parent)) { + return nodeText(parent.name); + } + // Default exports are named "default" + else if (ts.getModifierFlags(node) & 512 /* Default */) { + return "default"; + } + else if (ts.isClassLike(node)) { + return ""; + } + else if (ts.isCallExpression(parent)) { + var name = getCalledExpressionName(parent.expression); + if (name !== undefined) { + var args = ts.mapDefined(parent.arguments, function (a) { return ts.isStringLiteral(a) ? a.getText(curSourceFile) : undefined; }).join(", "); + return name + "(" + args + ") callback"; + } + } + return ""; + } + function getCalledExpressionName(expr) { + if (ts.isIdentifier(expr)) { + return expr.text; + } + else if (ts.isPropertyAccessExpression(expr)) { + var left = getCalledExpressionName(expr.expression); + var right = expr.name.text; + return left === undefined ? right : left + "." + right; + } + else { + return undefined; + } + } + function isFunctionOrClassExpression(node) { + switch (node.kind) { + case 197 /* ArrowFunction */: + case 196 /* FunctionExpression */: + case 209 /* ClassExpression */: + return true; + default: + return false; + } + } + })(NavigationBar = ts.NavigationBar || (ts.NavigationBar = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var OrganizeImports; + (function (OrganizeImports) { + /** + * Organize imports by: + * 1) Removing unused imports + * 2) Coalescing imports from the same module + * 3) Sorting imports + */ + function organizeImports(sourceFile, formatContext, host, program, _preferences) { + var changeTracker = ts.textChanges.ChangeTracker.fromContext({ host: host, formatContext: formatContext }); + var coalesceAndOrganizeImports = function (importGroup) { return coalesceImports(removeUnusedImports(importGroup, sourceFile, program)); }; + // All of the old ImportDeclarations in the file, in syntactic order. + var topLevelImportDecls = sourceFile.statements.filter(ts.isImportDeclaration); + organizeImportsWorker(topLevelImportDecls, coalesceAndOrganizeImports); + // All of the old ExportDeclarations in the file, in syntactic order. + var topLevelExportDecls = sourceFile.statements.filter(ts.isExportDeclaration); + organizeImportsWorker(topLevelExportDecls, coalesceExports); + for (var _i = 0, _a = sourceFile.statements.filter(ts.isAmbientModule); _i < _a.length; _i++) { + var ambientModule = _a[_i]; + var ambientModuleBody = getModuleBlock(ambientModule); // TODO: GH#18217 + var ambientModuleImportDecls = ambientModuleBody.statements.filter(ts.isImportDeclaration); + organizeImportsWorker(ambientModuleImportDecls, coalesceAndOrganizeImports); + var ambientModuleExportDecls = ambientModuleBody.statements.filter(ts.isExportDeclaration); + organizeImportsWorker(ambientModuleExportDecls, coalesceExports); + } + return changeTracker.getChanges(); + function organizeImportsWorker(oldImportDecls, coalesce) { + if (ts.length(oldImportDecls) === 0) { + return; + } + // Special case: normally, we'd expect leading and trailing trivia to follow each import + // around as it's sorted. However, we do not want this to happen for leading trivia + // on the first import because it is probably the header comment for the file. + // Consider: we could do a more careful check that this trivia is actually a header, + // but the consequences of being wrong are very minor. + ts.suppressLeadingTrivia(oldImportDecls[0]); + var oldImportGroups = ts.group(oldImportDecls, function (importDecl) { return getExternalModuleName(importDecl.moduleSpecifier); }); + var sortedImportGroups = ts.stableSort(oldImportGroups, function (group1, group2) { return compareModuleSpecifiers(group1[0].moduleSpecifier, group2[0].moduleSpecifier); }); + var newImportDecls = ts.flatMap(sortedImportGroups, function (importGroup) { + return getExternalModuleName(importGroup[0].moduleSpecifier) + ? coalesce(importGroup) + : importGroup; + }); + // Delete or replace the first import. + if (newImportDecls.length === 0) { + changeTracker.delete(sourceFile, oldImportDecls[0]); + } + else { + // Note: Delete the surrounding trivia because it will have been retained in newImportDecls. + changeTracker.replaceNodeWithNodes(sourceFile, oldImportDecls[0], newImportDecls, { + useNonAdjustedStartPosition: true, + useNonAdjustedEndPosition: false, + suffix: ts.getNewLineOrDefaultFromHost(host, formatContext.options), + }); + } + // Delete any subsequent imports. + for (var i = 1; i < oldImportDecls.length; i++) { + changeTracker.delete(sourceFile, oldImportDecls[i]); + } + } + } + OrganizeImports.organizeImports = organizeImports; + function getModuleBlock(moduleDecl) { + var body = moduleDecl.body; + return body && !ts.isIdentifier(body) ? (ts.isModuleBlock(body) ? body : getModuleBlock(body)) : undefined; + } + function removeUnusedImports(oldImports, sourceFile, program) { + var typeChecker = program.getTypeChecker(); + var jsxNamespace = typeChecker.getJsxNamespace(); + var jsxElementsPresent = !!(sourceFile.transformFlags & 4 /* ContainsJsx */); + var usedImports = []; + for (var _i = 0, oldImports_1 = oldImports; _i < oldImports_1.length; _i++) { + var importDecl = oldImports_1[_i]; + var importClause = importDecl.importClause; + if (!importClause) { + // Imports without import clauses are assumed to be included for their side effects and are not removed. + usedImports.push(importDecl); + continue; + } + var name = importClause.name, namedBindings = importClause.namedBindings; + // Default import + if (name && !isDeclarationUsed(name)) { + name = undefined; + } + if (namedBindings) { + if (ts.isNamespaceImport(namedBindings)) { + // Namespace import + if (!isDeclarationUsed(namedBindings.name)) { + namedBindings = undefined; + } + } + else { + // List of named imports + var newElements = namedBindings.elements.filter(function (e) { return isDeclarationUsed(e.name); }); + if (newElements.length < namedBindings.elements.length) { + namedBindings = newElements.length + ? ts.updateNamedImports(namedBindings, newElements) + : undefined; + } + } + } + if (name || namedBindings) { + usedImports.push(updateImportDeclarationAndClause(importDecl, name, namedBindings)); + } + } + return usedImports; + function isDeclarationUsed(identifier) { + // The JSX factory symbol is always used if JSX elements are present - even if they are not allowed. + return jsxElementsPresent && (identifier.text === jsxNamespace) || ts.FindAllReferences.Core.isSymbolReferencedInFile(identifier, typeChecker, sourceFile); + } + } + function getExternalModuleName(specifier) { + return specifier !== undefined && ts.isStringLiteralLike(specifier) + ? specifier.text + : undefined; + } + // Internal for testing + /** + * @param importGroup a list of ImportDeclarations, all with the same module name. + */ + function coalesceImports(importGroup) { + if (importGroup.length === 0) { + return importGroup; + } + var _a = getCategorizedImports(importGroup), importWithoutClause = _a.importWithoutClause, defaultImports = _a.defaultImports, namespaceImports = _a.namespaceImports, namedImports = _a.namedImports; + var coalescedImports = []; + if (importWithoutClause) { + coalescedImports.push(importWithoutClause); + } + // Normally, we don't combine default and namespace imports, but it would be silly to + // produce two import declarations in this special case. + if (defaultImports.length === 1 && namespaceImports.length === 1 && namedImports.length === 0) { + // Add the namespace import to the existing default ImportDeclaration. + var defaultImport = defaultImports[0]; + coalescedImports.push(updateImportDeclarationAndClause(defaultImport, defaultImport.importClause.name, namespaceImports[0].importClause.namedBindings)); // TODO: GH#18217 + return coalescedImports; + } + var sortedNamespaceImports = ts.stableSort(namespaceImports, function (i1, i2) { + return compareIdentifiers(i1.importClause.namedBindings.name, i2.importClause.namedBindings.name); + }); // TODO: GH#18217 + for (var _i = 0, sortedNamespaceImports_1 = sortedNamespaceImports; _i < sortedNamespaceImports_1.length; _i++) { + var namespaceImport = sortedNamespaceImports_1[_i]; + // Drop the name, if any + coalescedImports.push(updateImportDeclarationAndClause(namespaceImport, /*name*/ undefined, namespaceImport.importClause.namedBindings)); // TODO: GH#18217 + } + if (defaultImports.length === 0 && namedImports.length === 0) { + return coalescedImports; + } + var newDefaultImport; + var newImportSpecifiers = []; + if (defaultImports.length === 1) { + newDefaultImport = defaultImports[0].importClause.name; + } + else { + for (var _b = 0, defaultImports_1 = defaultImports; _b < defaultImports_1.length; _b++) { + var defaultImport = defaultImports_1[_b]; + newImportSpecifiers.push(ts.createImportSpecifier(ts.createIdentifier("default"), defaultImport.importClause.name)); // TODO: GH#18217 + } + } + newImportSpecifiers.push.apply(newImportSpecifiers, ts.flatMap(namedImports, function (i) { return i.importClause.namedBindings.elements; })); // TODO: GH#18217 + var sortedImportSpecifiers = sortSpecifiers(newImportSpecifiers); + var importDecl = defaultImports.length > 0 + ? defaultImports[0] + : namedImports[0]; + var newNamedImports = sortedImportSpecifiers.length === 0 + ? newDefaultImport + ? undefined + : ts.createNamedImports(ts.emptyArray) + : namedImports.length === 0 + ? ts.createNamedImports(sortedImportSpecifiers) + : ts.updateNamedImports(namedImports[0].importClause.namedBindings, sortedImportSpecifiers); // TODO: GH#18217 + coalescedImports.push(updateImportDeclarationAndClause(importDecl, newDefaultImport, newNamedImports)); + return coalescedImports; + /* + * Returns entire import declarations because they may already have been rewritten and + * may lack parent pointers. The desired parts can easily be recovered based on the + * categorization. + * + * NB: There may be overlap between `defaultImports` and `namespaceImports`/`namedImports`. + */ + function getCategorizedImports(importGroup) { + var importWithoutClause; + var defaultImports = []; + var namespaceImports = []; + var namedImports = []; + for (var _i = 0, importGroup_1 = importGroup; _i < importGroup_1.length; _i++) { + var importDeclaration = importGroup_1[_i]; + if (importDeclaration.importClause === undefined) { + // Only the first such import is interesting - the others are redundant. + // Note: Unfortunately, we will lose trivia that was on this node. + importWithoutClause = importWithoutClause || importDeclaration; + continue; + } + var _a = importDeclaration.importClause, name = _a.name, namedBindings = _a.namedBindings; + if (name) { + defaultImports.push(importDeclaration); + } + if (namedBindings) { + if (ts.isNamespaceImport(namedBindings)) { + namespaceImports.push(importDeclaration); + } + else { + namedImports.push(importDeclaration); + } + } + } + return { + importWithoutClause: importWithoutClause, + defaultImports: defaultImports, + namespaceImports: namespaceImports, + namedImports: namedImports, + }; + } + } + OrganizeImports.coalesceImports = coalesceImports; + // Internal for testing + /** + * @param exportGroup a list of ExportDeclarations, all with the same module name. + */ + function coalesceExports(exportGroup) { + if (exportGroup.length === 0) { + return exportGroup; + } + var _a = getCategorizedExports(exportGroup), exportWithoutClause = _a.exportWithoutClause, namedExports = _a.namedExports; + var coalescedExports = []; + if (exportWithoutClause) { + coalescedExports.push(exportWithoutClause); + } + if (namedExports.length === 0) { + return coalescedExports; + } + var newExportSpecifiers = []; + newExportSpecifiers.push.apply(newExportSpecifiers, ts.flatMap(namedExports, function (i) { return (i.exportClause).elements; })); + var sortedExportSpecifiers = sortSpecifiers(newExportSpecifiers); + var exportDecl = namedExports[0]; + coalescedExports.push(ts.updateExportDeclaration(exportDecl, exportDecl.decorators, exportDecl.modifiers, ts.updateNamedExports(exportDecl.exportClause, sortedExportSpecifiers), exportDecl.moduleSpecifier)); + return coalescedExports; + /* + * Returns entire export declarations because they may already have been rewritten and + * may lack parent pointers. The desired parts can easily be recovered based on the + * categorization. + */ + function getCategorizedExports(exportGroup) { + var exportWithoutClause; + var namedExports = []; + for (var _i = 0, exportGroup_1 = exportGroup; _i < exportGroup_1.length; _i++) { + var exportDeclaration = exportGroup_1[_i]; + if (exportDeclaration.exportClause === undefined) { + // Only the first such export is interesting - the others are redundant. + // Note: Unfortunately, we will lose trivia that was on this node. + exportWithoutClause = exportWithoutClause || exportDeclaration; + } + else { + namedExports.push(exportDeclaration); + } + } + return { + exportWithoutClause: exportWithoutClause, + namedExports: namedExports, + }; + } + } + OrganizeImports.coalesceExports = coalesceExports; + function updateImportDeclarationAndClause(importDeclaration, name, namedBindings) { + return ts.updateImportDeclaration(importDeclaration, importDeclaration.decorators, importDeclaration.modifiers, ts.updateImportClause(importDeclaration.importClause, name, namedBindings), // TODO: GH#18217 + importDeclaration.moduleSpecifier); + } + function sortSpecifiers(specifiers) { + return ts.stableSort(specifiers, function (s1, s2) { + return compareIdentifiers(s1.propertyName || s1.name, s2.propertyName || s2.name) || + compareIdentifiers(s1.name, s2.name); + }); + } + /* internal */ // Exported for testing + function compareModuleSpecifiers(m1, m2) { + var name1 = getExternalModuleName(m1); + var name2 = getExternalModuleName(m2); + return ts.compareBooleans(name1 === undefined, name2 === undefined) || + ts.compareBooleans(ts.isExternalModuleNameRelative(name1), ts.isExternalModuleNameRelative(name2)) || + ts.compareStringsCaseInsensitive(name1, name2); + } + OrganizeImports.compareModuleSpecifiers = compareModuleSpecifiers; + function compareIdentifiers(s1, s2) { + return ts.compareStringsCaseInsensitive(s1.text, s2.text); + } + })(OrganizeImports = ts.OrganizeImports || (ts.OrganizeImports = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var OutliningElementsCollector; + (function (OutliningElementsCollector) { + function collectElements(sourceFile, cancellationToken) { + var res = []; + addNodeOutliningSpans(sourceFile, cancellationToken, res); + addRegionOutliningSpans(sourceFile, res); + return res.sort(function (span1, span2) { return span1.textSpan.start - span2.textSpan.start; }); + } + OutliningElementsCollector.collectElements = collectElements; + function addNodeOutliningSpans(sourceFile, cancellationToken, out) { + var depthRemaining = 40; + var current = 0; + var statements = sourceFile.statements; + var n = statements.length; + while (current < n) { + while (current < n && !ts.isAnyImportSyntax(statements[current])) { + visitNonImportNode(statements[current]); + current++; + } + if (current === n) + break; + var firstImport = current; + while (current < n && ts.isAnyImportSyntax(statements[current])) { + addOutliningForLeadingCommentsForNode(statements[current], sourceFile, cancellationToken, out); + current++; + } + var lastImport = current - 1; + if (lastImport !== firstImport) { + out.push(createOutliningSpanFromBounds(ts.findChildOfKind(statements[firstImport], 92 /* ImportKeyword */, sourceFile).getStart(sourceFile), statements[lastImport].getEnd(), "imports" /* Imports */)); + } + } + function visitNonImportNode(n) { + if (depthRemaining === 0) + return; + cancellationToken.throwIfCancellationRequested(); + if (ts.isDeclaration(n)) { + addOutliningForLeadingCommentsForNode(n, sourceFile, cancellationToken, out); + } + var span = getOutliningSpanForNode(n, sourceFile); + if (span) + out.push(span); + depthRemaining--; + if (ts.isIfStatement(n) && n.elseStatement && ts.isIfStatement(n.elseStatement)) { + // Consider an 'else if' to be on the same depth as the 'if'. + visitNonImportNode(n.expression); + visitNonImportNode(n.thenStatement); + depthRemaining++; + visitNonImportNode(n.elseStatement); + depthRemaining--; + } + else { + n.forEachChild(visitNonImportNode); + } + depthRemaining++; + } + } + function addRegionOutliningSpans(sourceFile, out) { + var regions = []; + var lineStarts = sourceFile.getLineStarts(); + for (var i = 0; i < lineStarts.length; i++) { + var currentLineStart = lineStarts[i]; + var lineEnd = i + 1 === lineStarts.length ? sourceFile.getEnd() : lineStarts[i + 1] - 1; + var lineText = sourceFile.text.substring(currentLineStart, lineEnd); + var result = isRegionDelimiter(lineText); + if (!result || ts.isInComment(sourceFile, currentLineStart)) { + continue; + } + if (!result[1]) { + var span = ts.createTextSpanFromBounds(sourceFile.text.indexOf("//", currentLineStart), lineEnd); + regions.push(createOutliningSpan(span, "region" /* Region */, span, /*autoCollapse*/ false, result[2] || "#region")); + } + else { + var region = regions.pop(); + if (region) { + region.textSpan.length = lineEnd - region.textSpan.start; + region.hintSpan.length = lineEnd - region.textSpan.start; + out.push(region); + } + } + } + } + var regionDelimiterRegExp = /^\s*\/\/\s*#(end)?region(?:\s+(.*))?(?:\r)?$/; + function isRegionDelimiter(lineText) { + return regionDelimiterRegExp.exec(lineText); + } + function addOutliningForLeadingCommentsForNode(n, sourceFile, cancellationToken, out) { + var comments = ts.getLeadingCommentRangesOfNode(n, sourceFile); + if (!comments) + return; + var firstSingleLineCommentStart = -1; + var lastSingleLineCommentEnd = -1; + var singleLineCommentCount = 0; + var sourceText = sourceFile.getFullText(); + for (var _i = 0, comments_2 = comments; _i < comments_2.length; _i++) { + var _a = comments_2[_i], kind = _a.kind, pos = _a.pos, end = _a.end; + cancellationToken.throwIfCancellationRequested(); + switch (kind) { + case 2 /* SingleLineCommentTrivia */: + // never fold region delimiters into single-line comment regions + var commentText = sourceText.slice(pos, end); + if (isRegionDelimiter(commentText)) { + combineAndAddMultipleSingleLineComments(); + singleLineCommentCount = 0; + break; + } + // For single line comments, combine consecutive ones (2 or more) into + // a single span from the start of the first till the end of the last + if (singleLineCommentCount === 0) { + firstSingleLineCommentStart = pos; + } + lastSingleLineCommentEnd = end; + singleLineCommentCount++; + break; + case 3 /* MultiLineCommentTrivia */: + combineAndAddMultipleSingleLineComments(); + out.push(createOutliningSpanFromBounds(pos, end, "comment" /* Comment */)); + singleLineCommentCount = 0; + break; + default: + ts.Debug.assertNever(kind); + } + } + combineAndAddMultipleSingleLineComments(); + function combineAndAddMultipleSingleLineComments() { + // Only outline spans of two or more consecutive single line comments + if (singleLineCommentCount > 1) { + out.push(createOutliningSpanFromBounds(firstSingleLineCommentStart, lastSingleLineCommentEnd, "comment" /* Comment */)); + } + } + } + function createOutliningSpanFromBounds(pos, end, kind) { + return createOutliningSpan(ts.createTextSpanFromBounds(pos, end), kind); + } + function getOutliningSpanForNode(n, sourceFile) { + switch (n.kind) { + case 218 /* Block */: + if (ts.isFunctionBlock(n)) { + return spanForNode(n.parent, /*autoCollapse*/ n.parent.kind !== 197 /* ArrowFunction */); + } + // Check if the block is standalone, or 'attached' to some parent statement. + // If the latter, we want to collapse the block, but consider its hint span + // to be the entire span of the parent. + switch (n.parent.kind) { + case 223 /* DoStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + case 225 /* ForStatement */: + case 222 /* IfStatement */: + case 224 /* WhileStatement */: + case 231 /* WithStatement */: + case 274 /* CatchClause */: + return spanForNode(n.parent); + case 235 /* TryStatement */: + // Could be the try-block, or the finally-block. + var tryStatement = n.parent; + if (tryStatement.tryBlock === n) { + return spanForNode(n.parent); + } + else if (tryStatement.finallyBlock === n) { + return spanForNode(ts.findChildOfKind(tryStatement, 88 /* FinallyKeyword */, sourceFile)); + } + // falls through + default: + // Block was a standalone block. In this case we want to only collapse + // the span of the block, independent of any parent span. + return createOutliningSpan(ts.createTextSpanFromNode(n, sourceFile), "code" /* Code */); + } + case 245 /* ModuleBlock */: + return spanForNode(n.parent); + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + case 243 /* EnumDeclaration */: + case 246 /* CaseBlock */: + return spanForNode(n); + case 188 /* ObjectLiteralExpression */: + return spanForObjectOrArrayLiteral(n); + case 187 /* ArrayLiteralExpression */: + return spanForObjectOrArrayLiteral(n, 22 /* OpenBracketToken */); + case 260 /* JsxElement */: + return spanForJSXElement(n); + case 261 /* JsxSelfClosingElement */: + case 262 /* JsxOpeningElement */: + return spanForJSXAttributes(n.attributes); + } + function spanForJSXElement(node) { + var textSpan = ts.createTextSpanFromBounds(node.openingElement.getStart(sourceFile), node.closingElement.getEnd()); + var tagName = node.openingElement.tagName.getText(sourceFile); + var bannerText = "<" + tagName + ">..."; + return createOutliningSpan(textSpan, "code" /* Code */, textSpan, /*autoCollapse*/ false, bannerText); + } + function spanForJSXAttributes(node) { + if (node.properties.length === 0) { + return undefined; + } + return createOutliningSpanFromBounds(node.getStart(sourceFile), node.getEnd(), "code" /* Code */); + } + function spanForObjectOrArrayLiteral(node, open) { + if (open === void 0) { open = 18 /* OpenBraceToken */; } + // If the block has no leading keywords and is inside an array literal, + // we only want to collapse the span of the block. + // Otherwise, the collapsed section will include the end of the previous line. + return spanForNode(node, /*autoCollapse*/ false, /*useFullStart*/ !ts.isArrayLiteralExpression(node.parent), open); + } + function spanForNode(hintSpanNode, autoCollapse, useFullStart, open) { + if (autoCollapse === void 0) { autoCollapse = false; } + if (useFullStart === void 0) { useFullStart = true; } + if (open === void 0) { open = 18 /* OpenBraceToken */; } + var openToken = ts.findChildOfKind(n, open, sourceFile); + var close = open === 18 /* OpenBraceToken */ ? 19 /* CloseBraceToken */ : 23 /* CloseBracketToken */; + var closeToken = ts.findChildOfKind(n, close, sourceFile); + if (!openToken || !closeToken) { + return undefined; + } + var textSpan = ts.createTextSpanFromBounds(useFullStart ? openToken.getFullStart() : openToken.getStart(sourceFile), closeToken.getEnd()); + return createOutliningSpan(textSpan, "code" /* Code */, ts.createTextSpanFromNode(hintSpanNode, sourceFile), autoCollapse); + } + } + function createOutliningSpan(textSpan, kind, hintSpan, autoCollapse, bannerText) { + if (hintSpan === void 0) { hintSpan = textSpan; } + if (autoCollapse === void 0) { autoCollapse = false; } + if (bannerText === void 0) { bannerText = "..."; } + return { textSpan: textSpan, kind: kind, hintSpan: hintSpan, bannerText: bannerText, autoCollapse: autoCollapse }; + } + })(OutliningElementsCollector = ts.OutliningElementsCollector || (ts.OutliningElementsCollector = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + // Note(cyrusn): this enum is ordered from strongest match type to weakest match type. + var PatternMatchKind; + (function (PatternMatchKind) { + PatternMatchKind[PatternMatchKind["exact"] = 0] = "exact"; + PatternMatchKind[PatternMatchKind["prefix"] = 1] = "prefix"; + PatternMatchKind[PatternMatchKind["substring"] = 2] = "substring"; + PatternMatchKind[PatternMatchKind["camelCase"] = 3] = "camelCase"; + })(PatternMatchKind = ts.PatternMatchKind || (ts.PatternMatchKind = {})); + function createPatternMatch(kind, isCaseSensitive) { + return { + kind: kind, + isCaseSensitive: isCaseSensitive + }; + } + function createPatternMatcher(pattern) { + // We'll often see the same candidate string many times when searching (For example, when + // we see the name of a module that is used everywhere, or the name of an overload). As + // such, we cache the information we compute about the candidate for the life of this + // pattern matcher so we don't have to compute it multiple times. + var stringToWordSpans = ts.createMap(); + var dotSeparatedSegments = pattern.trim().split(".").map(function (p) { return createSegment(p.trim()); }); + // A segment is considered invalid if we couldn't find any words in it. + if (dotSeparatedSegments.some(function (segment) { return !segment.subWordTextChunks.length; })) + return undefined; + return { + getFullMatch: function (containers, candidate) { return getFullMatch(containers, candidate, dotSeparatedSegments, stringToWordSpans); }, + getMatchForLastSegmentOfPattern: function (candidate) { return matchSegment(candidate, ts.last(dotSeparatedSegments), stringToWordSpans); }, + patternContainsDots: dotSeparatedSegments.length > 1 + }; + } + ts.createPatternMatcher = createPatternMatcher; + function getFullMatch(candidateContainers, candidate, dotSeparatedSegments, stringToWordSpans) { + // First, check that the last part of the dot separated pattern matches the name of the + // candidate. If not, then there's no point in proceeding and doing the more + // expensive work. + var candidateMatch = matchSegment(candidate, ts.last(dotSeparatedSegments), stringToWordSpans); + if (!candidateMatch) { + return undefined; + } + // -1 because the last part was checked against the name, and only the rest + // of the parts are checked against the container. + if (dotSeparatedSegments.length - 1 > candidateContainers.length) { + // There weren't enough container parts to match against the pattern parts. + // So this definitely doesn't match. + return undefined; + } + var bestMatch; + for (var i = dotSeparatedSegments.length - 2, j = candidateContainers.length - 1; i >= 0; i -= 1, j -= 1) { + bestMatch = betterMatch(bestMatch, matchSegment(candidateContainers[j], dotSeparatedSegments[i], stringToWordSpans)); + } + return bestMatch; + } + function getWordSpans(word, stringToWordSpans) { + var spans = stringToWordSpans.get(word); + if (!spans) { + stringToWordSpans.set(word, spans = breakIntoWordSpans(word)); + } + return spans; + } + function matchTextChunk(candidate, chunk, stringToWordSpans) { + var index = indexOfIgnoringCase(candidate, chunk.textLowerCase); + if (index === 0) { + // a) Check if the word is a prefix of the candidate, in a case insensitive or + // sensitive manner. If it does, return that there was an exact match if the word and candidate are the same length, else a prefix match. + return createPatternMatch(chunk.text.length === candidate.length ? PatternMatchKind.exact : PatternMatchKind.prefix, /*isCaseSensitive:*/ ts.startsWith(candidate, chunk.text)); + } + if (chunk.isLowerCase) { + if (index === -1) + return undefined; + // b) If the part is entirely lowercase, then check if it is contained anywhere in the + // candidate in a case insensitive manner. If so, return that there was a substring + // match. + // + // Note: We only have a substring match if the lowercase part is prefix match of some + // word part. That way we don't match something like 'Class' when the user types 'a'. + // But we would match 'FooAttribute' (since 'Attribute' starts with 'a'). + var wordSpans = getWordSpans(candidate, stringToWordSpans); + for (var _i = 0, wordSpans_1 = wordSpans; _i < wordSpans_1.length; _i++) { + var span = wordSpans_1[_i]; + if (partStartsWith(candidate, span, chunk.text, /*ignoreCase:*/ true)) { + return createPatternMatch(PatternMatchKind.substring, /*isCaseSensitive:*/ partStartsWith(candidate, span, chunk.text, /*ignoreCase:*/ false)); + } + } + // c) Is the pattern a substring of the candidate starting on one of the candidate's word boundaries? + // We could check every character boundary start of the candidate for the pattern. However, that's + // an m * n operation in the wost case. Instead, find the first instance of the pattern + // substring, and see if it starts on a capital letter. It seems unlikely that the user will try to + // filter the list based on a substring that starts on a capital letter and also with a lowercase one. + // (Pattern: fogbar, Candidate: quuxfogbarFogBar). + if (chunk.text.length < candidate.length && isUpperCaseLetter(candidate.charCodeAt(index))) { + return createPatternMatch(PatternMatchKind.substring, /*isCaseSensitive:*/ false); + } + } + else { + // d) If the part was not entirely lowercase, then check if it is contained in the + // candidate in a case *sensitive* manner. If so, return that there was a substring + // match. + if (candidate.indexOf(chunk.text) > 0) { + return createPatternMatch(PatternMatchKind.substring, /*isCaseSensitive:*/ true); + } + // e) If the part was not entirely lowercase, then attempt a camel cased match as well. + if (chunk.characterSpans.length > 0) { + var candidateParts = getWordSpans(candidate, stringToWordSpans); + var isCaseSensitive = tryCamelCaseMatch(candidate, candidateParts, chunk, /*ignoreCase:*/ false) ? true + : tryCamelCaseMatch(candidate, candidateParts, chunk, /*ignoreCase:*/ true) ? false : undefined; + if (isCaseSensitive !== undefined) { + return createPatternMatch(PatternMatchKind.camelCase, isCaseSensitive); + } + } + } + } + function matchSegment(candidate, segment, stringToWordSpans) { + // First check if the segment matches as is. This is also useful if the segment contains + // characters we would normally strip when splitting into parts that we also may want to + // match in the candidate. For example if the segment is "@int" and the candidate is + // "@int", then that will show up as an exact match here. + // + // Note: if the segment contains a space or an asterisk then we must assume that it's a + // multi-word segment. + if (every(segment.totalTextChunk.text, function (ch) { return ch !== 32 /* space */ && ch !== 42 /* asterisk */; })) { + var match = matchTextChunk(candidate, segment.totalTextChunk, stringToWordSpans); + if (match) + return match; + } + // The logic for pattern matching is now as follows: + // + // 1) Break the segment passed in into words. Breaking is rather simple and a + // good way to think about it that if gives you all the individual alphanumeric words + // of the pattern. + // + // 2) For each word try to match the word against the candidate value. + // + // 3) Matching is as follows: + // + // a) Check if the word is a prefix of the candidate, in a case insensitive or + // sensitive manner. If it does, return that there was an exact match if the word and candidate are the same length, else a prefix match. + // + // If the word is entirely lowercase: + // b) Then check if it is contained anywhere in the + // candidate in a case insensitive manner. If so, return that there was a substring + // match. + // + // Note: We only have a substring match if the lowercase part is prefix match of + // some word part. That way we don't match something like 'Class' when the user + // types 'a'. But we would match 'FooAttribute' (since 'Attribute' starts with + // 'a'). + // + // c) The word is all lower case. Is it a case insensitive substring of the candidate starting + // on a part boundary of the candidate? + // + // Else: + // d) If the word was not entirely lowercase, then check if it is contained in the + // candidate in a case *sensitive* manner. If so, return that there was a substring + // match. + // + // e) If the word was not entirely lowercase, then attempt a camel cased match as + // well. + // + // Only if all words have some sort of match is the pattern considered matched. + var subWordTextChunks = segment.subWordTextChunks; + var bestMatch; + for (var _i = 0, subWordTextChunks_1 = subWordTextChunks; _i < subWordTextChunks_1.length; _i++) { + var subWordTextChunk = subWordTextChunks_1[_i]; + bestMatch = betterMatch(bestMatch, matchTextChunk(candidate, subWordTextChunk, stringToWordSpans)); + } + return bestMatch; + } + function betterMatch(a, b) { + return ts.min(a, b, compareMatches); + } + function compareMatches(a, b) { + return a === undefined ? 1 /* GreaterThan */ : b === undefined ? -1 /* LessThan */ + : ts.compareValues(a.kind, b.kind) || ts.compareBooleans(!a.isCaseSensitive, !b.isCaseSensitive); + } + function partStartsWith(candidate, candidateSpan, pattern, ignoreCase, patternSpan) { + if (patternSpan === void 0) { patternSpan = { start: 0, length: pattern.length }; } + return patternSpan.length <= candidateSpan.length // If pattern part is longer than the candidate part there can never be a match. + && everyInRange(0, patternSpan.length, function (i) { return equalChars(pattern.charCodeAt(patternSpan.start + i), candidate.charCodeAt(candidateSpan.start + i), ignoreCase); }); + } + function equalChars(ch1, ch2, ignoreCase) { + return ignoreCase ? toLowerCase(ch1) === toLowerCase(ch2) : ch1 === ch2; + } + function tryCamelCaseMatch(candidate, candidateParts, chunk, ignoreCase) { + var chunkCharacterSpans = chunk.characterSpans; + // Note: we may have more pattern parts than candidate parts. This is because multiple + // pattern parts may match a candidate part. For example "SiUI" against "SimpleUI". + // We'll have 3 pattern parts Si/U/I against two candidate parts Simple/UI. However, U + // and I will both match in UI. + var currentCandidate = 0; + var currentChunkSpan = 0; + var firstMatch; + var contiguous; + while (true) { + // Let's consider our termination cases + if (currentChunkSpan === chunkCharacterSpans.length) { + return true; + } + else if (currentCandidate === candidateParts.length) { + // No match, since we still have more of the pattern to hit + return false; + } + var candidatePart = candidateParts[currentCandidate]; + var gotOneMatchThisCandidate = false; + // Consider the case of matching SiUI against SimpleUIElement. The candidate parts + // will be Simple/UI/Element, and the pattern parts will be Si/U/I. We'll match 'Si' + // against 'Simple' first. Then we'll match 'U' against 'UI'. However, we want to + // still keep matching pattern parts against that candidate part. + for (; currentChunkSpan < chunkCharacterSpans.length; currentChunkSpan++) { + var chunkCharacterSpan = chunkCharacterSpans[currentChunkSpan]; + if (gotOneMatchThisCandidate) { + // We've already gotten one pattern part match in this candidate. We will + // only continue trying to consumer pattern parts if the last part and this + // part are both upper case. + if (!isUpperCaseLetter(chunk.text.charCodeAt(chunkCharacterSpans[currentChunkSpan - 1].start)) || + !isUpperCaseLetter(chunk.text.charCodeAt(chunkCharacterSpans[currentChunkSpan].start))) { + break; + } + } + if (!partStartsWith(candidate, candidatePart, chunk.text, ignoreCase, chunkCharacterSpan)) { + break; + } + gotOneMatchThisCandidate = true; + firstMatch = firstMatch === undefined ? currentCandidate : firstMatch; + // If we were contiguous, then keep that value. If we weren't, then keep that + // value. If we don't know, then set the value to 'true' as an initial match is + // obviously contiguous. + contiguous = contiguous === undefined ? true : contiguous; + candidatePart = ts.createTextSpan(candidatePart.start + chunkCharacterSpan.length, candidatePart.length - chunkCharacterSpan.length); + } + // Check if we matched anything at all. If we didn't, then we need to unset the + // contiguous bit if we currently had it set. + // If we haven't set the bit yet, then that means we haven't matched anything so + // far, and we don't want to change that. + if (!gotOneMatchThisCandidate && contiguous !== undefined) { + contiguous = false; + } + // Move onto the next candidate. + currentCandidate++; + } + } + function createSegment(text) { + return { + totalTextChunk: createTextChunk(text), + subWordTextChunks: breakPatternIntoTextChunks(text) + }; + } + function isUpperCaseLetter(ch) { + // Fast check for the ascii range. + if (ch >= 65 /* A */ && ch <= 90 /* Z */) { + return true; + } + if (ch < 127 /* maxAsciiCharacter */ || !ts.isUnicodeIdentifierStart(ch, 6 /* Latest */)) { + return false; + } + // TODO: find a way to determine this for any unicode characters in a + // non-allocating manner. + var str = String.fromCharCode(ch); + return str === str.toUpperCase(); + } + function isLowerCaseLetter(ch) { + // Fast check for the ascii range. + if (ch >= 97 /* a */ && ch <= 122 /* z */) { + return true; + } + if (ch < 127 /* maxAsciiCharacter */ || !ts.isUnicodeIdentifierStart(ch, 6 /* Latest */)) { + return false; + } + // TODO: find a way to determine this for any unicode characters in a + // non-allocating manner. + var str = String.fromCharCode(ch); + return str === str.toLowerCase(); + } + // Assumes 'value' is already lowercase. + function indexOfIgnoringCase(str, value) { + var n = str.length - value.length; + var _loop_14 = function (start) { + if (every(value, function (valueChar, i) { return toLowerCase(str.charCodeAt(i + start)) === valueChar; })) { + return { value: start }; + } + }; + for (var start = 0; start <= n; start++) { + var state_3 = _loop_14(start); + if (typeof state_3 === "object") + return state_3.value; + } + return -1; + } + function toLowerCase(ch) { + // Fast convert for the ascii range. + if (ch >= 65 /* A */ && ch <= 90 /* Z */) { + return 97 /* a */ + (ch - 65 /* A */); + } + if (ch < 127 /* maxAsciiCharacter */) { + return ch; + } + // TODO: find a way to compute this for any unicode characters in a + // non-allocating manner. + return String.fromCharCode(ch).toLowerCase().charCodeAt(0); + } + function isDigit(ch) { + // TODO(cyrusn): Find a way to support this for unicode digits. + return ch >= 48 /* _0 */ && ch <= 57 /* _9 */; + } + function isWordChar(ch) { + return isUpperCaseLetter(ch) || isLowerCaseLetter(ch) || isDigit(ch) || ch === 95 /* _ */ || ch === 36 /* $ */; + } + function breakPatternIntoTextChunks(pattern) { + var result = []; + var wordStart = 0; + var wordLength = 0; + for (var i = 0; i < pattern.length; i++) { + var ch = pattern.charCodeAt(i); + if (isWordChar(ch)) { + if (wordLength === 0) { + wordStart = i; + } + wordLength++; + } + else { + if (wordLength > 0) { + result.push(createTextChunk(pattern.substr(wordStart, wordLength))); + wordLength = 0; + } + } + } + if (wordLength > 0) { + result.push(createTextChunk(pattern.substr(wordStart, wordLength))); + } + return result; + } + function createTextChunk(text) { + var textLowerCase = text.toLowerCase(); + return { + text: text, + textLowerCase: textLowerCase, + isLowerCase: text === textLowerCase, + characterSpans: breakIntoCharacterSpans(text) + }; + } + function breakIntoCharacterSpans(identifier) { + return breakIntoSpans(identifier, /*word:*/ false); + } + ts.breakIntoCharacterSpans = breakIntoCharacterSpans; + function breakIntoWordSpans(identifier) { + return breakIntoSpans(identifier, /*word:*/ true); + } + ts.breakIntoWordSpans = breakIntoWordSpans; + function breakIntoSpans(identifier, word) { + var result = []; + var wordStart = 0; + for (var i = 1; i < identifier.length; i++) { + var lastIsDigit = isDigit(identifier.charCodeAt(i - 1)); + var currentIsDigit = isDigit(identifier.charCodeAt(i)); + var hasTransitionFromLowerToUpper = transitionFromLowerToUpper(identifier, word, i); + var hasTransitionFromUpperToLower = word && transitionFromUpperToLower(identifier, i, wordStart); + if (charIsPunctuation(identifier.charCodeAt(i - 1)) || + charIsPunctuation(identifier.charCodeAt(i)) || + lastIsDigit !== currentIsDigit || + hasTransitionFromLowerToUpper || + hasTransitionFromUpperToLower) { + if (!isAllPunctuation(identifier, wordStart, i)) { + result.push(ts.createTextSpan(wordStart, i - wordStart)); + } + wordStart = i; + } + } + if (!isAllPunctuation(identifier, wordStart, identifier.length)) { + result.push(ts.createTextSpan(wordStart, identifier.length - wordStart)); + } + return result; + } + function charIsPunctuation(ch) { + switch (ch) { + case 33 /* exclamation */: + case 34 /* doubleQuote */: + case 35 /* hash */: + case 37 /* percent */: + case 38 /* ampersand */: + case 39 /* singleQuote */: + case 40 /* openParen */: + case 41 /* closeParen */: + case 42 /* asterisk */: + case 44 /* comma */: + case 45 /* minus */: + case 46 /* dot */: + case 47 /* slash */: + case 58 /* colon */: + case 59 /* semicolon */: + case 63 /* question */: + case 64 /* at */: + case 91 /* openBracket */: + case 92 /* backslash */: + case 93 /* closeBracket */: + case 95 /* _ */: + case 123 /* openBrace */: + case 125 /* closeBrace */: + return true; + } + return false; + } + function isAllPunctuation(identifier, start, end) { + return every(identifier, function (ch) { return charIsPunctuation(ch) && ch !== 95 /* _ */; }, start, end); + } + function transitionFromUpperToLower(identifier, index, wordStart) { + // Cases this supports: + // 1) IDisposable -> I, Disposable + // 2) UIElement -> UI, Element + // 3) HTMLDocument -> HTML, Document + // + // etc. + // We have a transition from an upper to a lower letter here. But we only + // want to break if all the letters that preceded are uppercase. i.e. if we + // have "Foo" we don't want to break that into "F, oo". But if we have + // "IFoo" or "UIFoo", then we want to break that into "I, Foo" and "UI, + // Foo". i.e. the last uppercase letter belongs to the lowercase letters + // that follows. Note: this will make the following not split properly: + // "HELLOthere". However, these sorts of names do not show up in .Net + // programs. + return index !== wordStart + && index + 1 < identifier.length + && isUpperCaseLetter(identifier.charCodeAt(index)) + && isLowerCaseLetter(identifier.charCodeAt(index + 1)) + && every(identifier, isUpperCaseLetter, wordStart, index); + } + function transitionFromLowerToUpper(identifier, word, index) { + var lastIsUpper = isUpperCaseLetter(identifier.charCodeAt(index - 1)); + var currentIsUpper = isUpperCaseLetter(identifier.charCodeAt(index)); + // See if the casing indicates we're starting a new word. Note: if we're breaking on + // words, then just seeing an upper case character isn't enough. Instead, it has to + // be uppercase and the previous character can't be uppercase. + // + // For example, breaking "AddMetadata" on words would make: Add Metadata + // + // on characters would be: A dd M etadata + // + // Break "AM" on words would be: AM + // + // on characters would be: A M + // + // We break the search string on characters. But we break the symbol name on words. + return currentIsUpper && (!word || !lastIsUpper); + } + function everyInRange(start, end, pred) { + for (var i = start; i < end; i++) { + if (!pred(i)) { + return false; + } + } + return true; + } + function every(s, pred, start, end) { + if (start === void 0) { start = 0; } + if (end === void 0) { end = s.length; } + return everyInRange(start, end, function (i) { return pred(s.charCodeAt(i), i); }); + } +})(ts || (ts = {})); +var ts; +(function (ts) { + function preProcessFile(sourceText, readImportFiles, detectJavaScriptImports) { + if (readImportFiles === void 0) { readImportFiles = true; } + if (detectJavaScriptImports === void 0) { detectJavaScriptImports = false; } + var pragmaContext = { + languageVersion: 1 /* ES5 */, + pragmas: undefined, + checkJsDirective: undefined, + referencedFiles: [], + typeReferenceDirectives: [], + libReferenceDirectives: [], + amdDependencies: [], + hasNoDefaultLib: undefined, + moduleName: undefined + }; + var importedFiles = []; + var ambientExternalModules; + var lastToken; + var currentToken; + var braceNesting = 0; + // assume that text represent an external module if it contains at least one top level import/export + // ambient modules that are found inside external modules are interpreted as module augmentations + var externalModule = false; + function nextToken() { + lastToken = currentToken; + currentToken = ts.scanner.scan(); + if (currentToken === 18 /* OpenBraceToken */) { + braceNesting++; + } + else if (currentToken === 19 /* CloseBraceToken */) { + braceNesting--; + } + return currentToken; + } + function getFileReference() { + var fileName = ts.scanner.getTokenValue(); + var pos = ts.scanner.getTokenPos(); + return { fileName: fileName, pos: pos, end: pos + fileName.length }; + } + function recordAmbientExternalModule() { + if (!ambientExternalModules) { + ambientExternalModules = []; + } + ambientExternalModules.push({ ref: getFileReference(), depth: braceNesting }); + } + function recordModuleName() { + importedFiles.push(getFileReference()); + markAsExternalModuleIfTopLevel(); + } + function markAsExternalModuleIfTopLevel() { + if (braceNesting === 0) { + externalModule = true; + } + } + /** + * Returns true if at least one token was consumed from the stream + */ + function tryConsumeDeclare() { + var token = ts.scanner.getToken(); + if (token === 125 /* DeclareKeyword */) { + // declare module "mod" + token = nextToken(); + if (token === 130 /* ModuleKeyword */) { + token = nextToken(); + if (token === 10 /* StringLiteral */) { + recordAmbientExternalModule(); + } + } + return true; + } + return false; + } + /** + * Returns true if at least one token was consumed from the stream + */ + function tryConsumeImport() { + if (lastToken === 24 /* DotToken */) { + return false; + } + var token = ts.scanner.getToken(); + if (token === 92 /* ImportKeyword */) { + token = nextToken(); + if (token === 20 /* OpenParenToken */) { + token = nextToken(); + if (token === 10 /* StringLiteral */) { + // import("mod"); + recordModuleName(); + return true; + } + } + else if (token === 10 /* StringLiteral */) { + // import "mod"; + recordModuleName(); + return true; + } + else { + if (token === 72 /* Identifier */ || ts.isKeyword(token)) { + token = nextToken(); + if (token === 144 /* FromKeyword */) { + token = nextToken(); + if (token === 10 /* StringLiteral */) { + // import d from "mod"; + recordModuleName(); + return true; + } + } + else if (token === 59 /* EqualsToken */) { + if (tryConsumeRequireCall(/*skipCurrentToken*/ true)) { + return true; + } + } + else if (token === 27 /* CommaToken */) { + // consume comma and keep going + token = nextToken(); + } + else { + // unknown syntax + return true; + } + } + if (token === 18 /* OpenBraceToken */) { + token = nextToken(); + // consume "{ a as B, c, d as D}" clauses + // make sure that it stops on EOF + while (token !== 19 /* CloseBraceToken */ && token !== 1 /* EndOfFileToken */) { + token = nextToken(); + } + if (token === 19 /* CloseBraceToken */) { + token = nextToken(); + if (token === 144 /* FromKeyword */) { + token = nextToken(); + if (token === 10 /* StringLiteral */) { + // import {a as A} from "mod"; + // import d, {a, b as B} from "mod" + recordModuleName(); + } + } + } + } + else if (token === 40 /* AsteriskToken */) { + token = nextToken(); + if (token === 119 /* AsKeyword */) { + token = nextToken(); + if (token === 72 /* Identifier */ || ts.isKeyword(token)) { + token = nextToken(); + if (token === 144 /* FromKeyword */) { + token = nextToken(); + if (token === 10 /* StringLiteral */) { + // import * as NS from "mod" + // import d, * as NS from "mod" + recordModuleName(); + } + } + } + } + } + } + return true; + } + return false; + } + function tryConsumeExport() { + var token = ts.scanner.getToken(); + if (token === 85 /* ExportKeyword */) { + markAsExternalModuleIfTopLevel(); + token = nextToken(); + if (token === 18 /* OpenBraceToken */) { + token = nextToken(); + // consume "{ a as B, c, d as D}" clauses + // make sure it stops on EOF + while (token !== 19 /* CloseBraceToken */ && token !== 1 /* EndOfFileToken */) { + token = nextToken(); + } + if (token === 19 /* CloseBraceToken */) { + token = nextToken(); + if (token === 144 /* FromKeyword */) { + token = nextToken(); + if (token === 10 /* StringLiteral */) { + // export {a as A} from "mod"; + // export {a, b as B} from "mod" + recordModuleName(); + } + } + } + } + else if (token === 40 /* AsteriskToken */) { + token = nextToken(); + if (token === 144 /* FromKeyword */) { + token = nextToken(); + if (token === 10 /* StringLiteral */) { + // export * from "mod" + recordModuleName(); + } + } + } + else if (token === 92 /* ImportKeyword */) { + token = nextToken(); + if (token === 72 /* Identifier */ || ts.isKeyword(token)) { + token = nextToken(); + if (token === 59 /* EqualsToken */) { + if (tryConsumeRequireCall(/*skipCurrentToken*/ true)) { + return true; + } + } + } + } + return true; + } + return false; + } + function tryConsumeRequireCall(skipCurrentToken) { + var token = skipCurrentToken ? nextToken() : ts.scanner.getToken(); + if (token === 134 /* RequireKeyword */) { + token = nextToken(); + if (token === 20 /* OpenParenToken */) { + token = nextToken(); + if (token === 10 /* StringLiteral */) { + // require("mod"); + recordModuleName(); + } + } + return true; + } + return false; + } + function tryConsumeDefine() { + var token = ts.scanner.getToken(); + if (token === 72 /* Identifier */ && ts.scanner.getTokenValue() === "define") { + token = nextToken(); + if (token !== 20 /* OpenParenToken */) { + return true; + } + token = nextToken(); + if (token === 10 /* StringLiteral */) { + // looks like define ("modname", ... - skip string literal and comma + token = nextToken(); + if (token === 27 /* CommaToken */) { + token = nextToken(); + } + else { + // unexpected token + return true; + } + } + // should be start of dependency list + if (token !== 22 /* OpenBracketToken */) { + return true; + } + // skip open bracket + token = nextToken(); + // scan until ']' or EOF + while (token !== 23 /* CloseBracketToken */ && token !== 1 /* EndOfFileToken */) { + // record string literals as module names + if (token === 10 /* StringLiteral */) { + recordModuleName(); + } + token = nextToken(); + } + return true; + } + return false; + } + function processImports() { + ts.scanner.setText(sourceText); + nextToken(); + // Look for: + // import "mod"; + // import d from "mod" + // import {a as A } from "mod"; + // import * as NS from "mod" + // import d, {a, b as B} from "mod" + // import i = require("mod"); + // import("mod"); + // export * from "mod" + // export {a as b} from "mod" + // export import i = require("mod") + // (for JavaScript files) require("mod") + // Do not look for: + // AnySymbol.import("mod") + // AnySymbol.nested.import("mod") + while (true) { + if (ts.scanner.getToken() === 1 /* EndOfFileToken */) { + break; + } + // check if at least one of alternative have moved scanner forward + if (tryConsumeDeclare() || + tryConsumeImport() || + tryConsumeExport() || + (detectJavaScriptImports && (tryConsumeRequireCall(/*skipCurrentToken*/ false) || tryConsumeDefine()))) { + continue; + } + else { + nextToken(); + } + } + ts.scanner.setText(undefined); + } + if (readImportFiles) { + processImports(); + } + ts.processCommentPragmas(pragmaContext, sourceText); + ts.processPragmasIntoFields(pragmaContext, ts.noop); + if (externalModule) { + // for external modules module all nested ambient modules are augmentations + if (ambientExternalModules) { + // move all detected ambient modules to imported files since they need to be resolved + for (var _i = 0, ambientExternalModules_1 = ambientExternalModules; _i < ambientExternalModules_1.length; _i++) { + var decl = ambientExternalModules_1[_i]; + importedFiles.push(decl.ref); + } + } + return { referencedFiles: pragmaContext.referencedFiles, typeReferenceDirectives: pragmaContext.typeReferenceDirectives, libReferenceDirectives: pragmaContext.libReferenceDirectives, importedFiles: importedFiles, isLibFile: !!pragmaContext.hasNoDefaultLib, ambientExternalModules: undefined }; + } + else { + // for global scripts ambient modules still can have augmentations - look for ambient modules with depth > 0 + var ambientModuleNames = void 0; + if (ambientExternalModules) { + for (var _a = 0, ambientExternalModules_2 = ambientExternalModules; _a < ambientExternalModules_2.length; _a++) { + var decl = ambientExternalModules_2[_a]; + if (decl.depth === 0) { + if (!ambientModuleNames) { + ambientModuleNames = []; + } + ambientModuleNames.push(decl.ref.fileName); + } + else { + importedFiles.push(decl.ref); + } + } + } + return { referencedFiles: pragmaContext.referencedFiles, typeReferenceDirectives: pragmaContext.typeReferenceDirectives, libReferenceDirectives: pragmaContext.libReferenceDirectives, importedFiles: importedFiles, isLibFile: !!pragmaContext.hasNoDefaultLib, ambientExternalModules: ambientModuleNames }; + } + } + ts.preProcessFile = preProcessFile; +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var Rename; + (function (Rename) { + function getRenameInfo(program, sourceFile, position) { + var node = ts.getTouchingPropertyName(sourceFile, position); + var renameInfo = node && nodeIsEligibleForRename(node) + ? getRenameInfoForNode(node, program.getTypeChecker(), sourceFile, function (declaration) { return program.isSourceFileDefaultLibrary(declaration.getSourceFile()); }) + : undefined; + return renameInfo || getRenameInfoError(ts.Diagnostics.You_cannot_rename_this_element); + } + Rename.getRenameInfo = getRenameInfo; + function getRenameInfoForNode(node, typeChecker, sourceFile, isDefinedInLibraryFile) { + var symbol = typeChecker.getSymbolAtLocation(node); + if (!symbol) + return; + // Only allow a symbol to be renamed if it actually has at least one declaration. + var declarations = symbol.declarations; + if (!declarations || declarations.length === 0) + return; + // Disallow rename for elements that are defined in the standard TypeScript library. + if (declarations.some(isDefinedInLibraryFile)) { + return getRenameInfoError(ts.Diagnostics.You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library); + } + // Cannot rename `default` as in `import { default as foo } from "./someModule"; + if (ts.isIdentifier(node) && node.originalKeywordKind === 80 /* DefaultKeyword */ && symbol.parent.flags & 1536 /* Module */) { + return undefined; + } + if (ts.isStringLiteralLike(node) && ts.tryGetImportFromModuleSpecifier(node)) { + return getRenameInfoForModule(node, sourceFile, symbol); + } + var kind = ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, node); + var specifierName = (ts.isImportOrExportSpecifierName(node) || ts.isStringOrNumericLiteralLike(node) && node.parent.kind === 149 /* ComputedPropertyName */) + ? ts.stripQuotes(ts.getTextOfIdentifierOrLiteral(node)) + : undefined; + var displayName = specifierName || typeChecker.symbolToString(symbol); + var fullDisplayName = specifierName || typeChecker.getFullyQualifiedName(symbol); + return getRenameInfoSuccess(displayName, fullDisplayName, kind, ts.SymbolDisplay.getSymbolModifiers(symbol), node, sourceFile); + } + function getRenameInfoForModule(node, sourceFile, moduleSymbol) { + if (!ts.isExternalModuleNameRelative(node.text)) { + return getRenameInfoError(ts.Diagnostics.You_cannot_rename_a_module_via_a_global_import); + } + var moduleSourceFile = ts.find(moduleSymbol.declarations, ts.isSourceFile); + if (!moduleSourceFile) + return undefined; + var withoutIndex = node.text.endsWith("/index") || node.text.endsWith("/index.js") ? undefined : ts.tryRemoveSuffix(ts.removeFileExtension(moduleSourceFile.fileName), "/index"); + var name = withoutIndex === undefined ? moduleSourceFile.fileName : withoutIndex; + var kind = withoutIndex === undefined ? "module" /* moduleElement */ : "directory" /* directory */; + var indexAfterLastSlash = node.text.lastIndexOf("/") + 1; + // Span should only be the last component of the path. + 1 to account for the quote character. + var triggerSpan = ts.createTextSpan(node.getStart(sourceFile) + 1 + indexAfterLastSlash, node.text.length - indexAfterLastSlash); + return { + canRename: true, + fileToRename: name, + kind: kind, + displayName: name, + fullDisplayName: name, + kindModifiers: "" /* none */, + triggerSpan: triggerSpan, + }; + } + function getRenameInfoSuccess(displayName, fullDisplayName, kind, kindModifiers, node, sourceFile) { + return { + canRename: true, + fileToRename: undefined, + kind: kind, + displayName: displayName, + fullDisplayName: fullDisplayName, + kindModifiers: kindModifiers, + triggerSpan: createTriggerSpanForNode(node, sourceFile) + }; + } + function getRenameInfoError(diagnostic) { + return { canRename: false, localizedErrorMessage: ts.getLocaleSpecificMessage(diagnostic) }; + } + function createTriggerSpanForNode(node, sourceFile) { + var start = node.getStart(sourceFile); + var width = node.getWidth(sourceFile); + if (node.kind === 10 /* StringLiteral */) { + // Exclude the quotes + start += 1; + width -= 2; + } + return ts.createTextSpan(start, width); + } + function nodeIsEligibleForRename(node) { + switch (node.kind) { + case 72 /* Identifier */: + case 10 /* StringLiteral */: + case 100 /* ThisKeyword */: + return true; + case 8 /* NumericLiteral */: + return ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node); + default: + return false; + } + } + })(Rename = ts.Rename || (ts.Rename = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var SignatureHelp; + (function (SignatureHelp) { + var InvocationKind; + (function (InvocationKind) { + InvocationKind[InvocationKind["Call"] = 0] = "Call"; + InvocationKind[InvocationKind["TypeArgs"] = 1] = "TypeArgs"; + InvocationKind[InvocationKind["Contextual"] = 2] = "Contextual"; + })(InvocationKind || (InvocationKind = {})); + function getSignatureHelpItems(program, sourceFile, position, triggerReason, cancellationToken) { + var typeChecker = program.getTypeChecker(); + // Decide whether to show signature help + var startingToken = ts.findTokenOnLeftOfPosition(sourceFile, position); + if (!startingToken) { + // We are at the beginning of the file + return undefined; + } + // Only need to be careful if the user typed a character and signature help wasn't showing. + var onlyUseSyntacticOwners = !!triggerReason && triggerReason.kind === "characterTyped"; + // Bail out quickly in the middle of a string or comment, don't provide signature help unless the user explicitly requested it. + if (onlyUseSyntacticOwners && (ts.isInString(sourceFile, position, startingToken) || ts.isInComment(sourceFile, position))) { + return undefined; + } + var isManuallyInvoked = !!triggerReason && triggerReason.kind === "invoked"; + var argumentInfo = getContainingArgumentInfo(startingToken, position, sourceFile, typeChecker, isManuallyInvoked); + if (!argumentInfo) + return undefined; + cancellationToken.throwIfCancellationRequested(); + // Extra syntactic and semantic filtering of signature help + var candidateInfo = getCandidateOrTypeInfo(argumentInfo, typeChecker, sourceFile, startingToken, onlyUseSyntacticOwners); + cancellationToken.throwIfCancellationRequested(); + if (!candidateInfo) { + // We didn't have any sig help items produced by the TS compiler. If this is a JS + // file, then see if we can figure out anything better. + return ts.isSourceFileJS(sourceFile) ? createJSSignatureHelpItems(argumentInfo, program, cancellationToken) : undefined; + } + return typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { + return candidateInfo.kind === 0 /* Candidate */ + ? createSignatureHelpItems(candidateInfo.candidates, candidateInfo.resolvedSignature, argumentInfo, sourceFile, typeChecker) + : createTypeHelpItems(candidateInfo.symbol, argumentInfo, sourceFile, typeChecker); + }); + } + SignatureHelp.getSignatureHelpItems = getSignatureHelpItems; + var CandidateOrTypeKind; + (function (CandidateOrTypeKind) { + CandidateOrTypeKind[CandidateOrTypeKind["Candidate"] = 0] = "Candidate"; + CandidateOrTypeKind[CandidateOrTypeKind["Type"] = 1] = "Type"; + })(CandidateOrTypeKind || (CandidateOrTypeKind = {})); + function getCandidateOrTypeInfo(_a, checker, sourceFile, startingToken, onlyUseSyntacticOwners) { + var invocation = _a.invocation, argumentCount = _a.argumentCount; + switch (invocation.kind) { + case 0 /* Call */: { + if (onlyUseSyntacticOwners && !isSyntacticOwner(startingToken, invocation.node, sourceFile)) { + return undefined; + } + var candidates = []; + var resolvedSignature = checker.getResolvedSignatureForSignatureHelp(invocation.node, candidates, argumentCount); // TODO: GH#18217 + return candidates.length === 0 ? undefined : { kind: 0 /* Candidate */, candidates: candidates, resolvedSignature: resolvedSignature }; + } + case 1 /* TypeArgs */: { + var called = invocation.called; + if (onlyUseSyntacticOwners && !containsPrecedingToken(startingToken, sourceFile, ts.isIdentifier(called) ? called.parent : called)) { + return undefined; + } + var candidates = ts.getPossibleGenericSignatures(called, argumentCount, checker); + if (candidates.length !== 0) + return { kind: 0 /* Candidate */, candidates: candidates, resolvedSignature: ts.first(candidates) }; + var symbol = checker.getSymbolAtLocation(called); + return symbol && { kind: 1 /* Type */, symbol: symbol }; + } + case 2 /* Contextual */: + return { kind: 0 /* Candidate */, candidates: [invocation.signature], resolvedSignature: invocation.signature }; + default: + return ts.Debug.assertNever(invocation); + } + } + function isSyntacticOwner(startingToken, node, sourceFile) { + if (!ts.isCallOrNewExpression(node)) + return false; + var invocationChildren = node.getChildren(sourceFile); + switch (startingToken.kind) { + case 20 /* OpenParenToken */: + return ts.contains(invocationChildren, startingToken); + case 27 /* CommaToken */: { + var containingList = ts.findContainingList(startingToken); + return !!containingList && ts.contains(invocationChildren, containingList); + } + case 28 /* LessThanToken */: + return containsPrecedingToken(startingToken, sourceFile, node.expression); + default: + return false; + } + } + function createJSSignatureHelpItems(argumentInfo, program, cancellationToken) { + if (argumentInfo.invocation.kind === 2 /* Contextual */) + return undefined; + // See if we can find some symbol with the call expression name that has call signatures. + var expression = getExpressionFromInvocation(argumentInfo.invocation); + var name = ts.isIdentifier(expression) ? expression.text : ts.isPropertyAccessExpression(expression) ? expression.name.text : undefined; + var typeChecker = program.getTypeChecker(); + return name === undefined ? undefined : ts.firstDefined(program.getSourceFiles(), function (sourceFile) { + return ts.firstDefined(sourceFile.getNamedDeclarations().get(name), function (declaration) { + var type = declaration.symbol && typeChecker.getTypeOfSymbolAtLocation(declaration.symbol, declaration); + var callSignatures = type && type.getCallSignatures(); + if (callSignatures && callSignatures.length) { + return typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { return createSignatureHelpItems(callSignatures, callSignatures[0], argumentInfo, sourceFile, typeChecker); }); + } + }); + }); + } + function containsPrecedingToken(startingToken, sourceFile, container) { + var precedingToken = ts.Debug.assertDefined(ts.findPrecedingToken(startingToken.getFullStart(), sourceFile, startingToken.parent, /*excludeJsdoc*/ true)); + return ts.rangeContainsRange(container, precedingToken); + } + function getArgumentInfoForCompletions(node, position, sourceFile) { + var info = getImmediatelyContainingArgumentInfo(node, position, sourceFile); + return !info || info.isTypeParameterList || info.invocation.kind !== 0 /* Call */ ? undefined + : { invocation: info.invocation.node, argumentCount: info.argumentCount, argumentIndex: info.argumentIndex }; + } + SignatureHelp.getArgumentInfoForCompletions = getArgumentInfoForCompletions; + function getArgumentOrParameterListInfo(node, sourceFile) { + var info = getArgumentOrParameterListAndIndex(node, sourceFile); + if (!info) + return undefined; + var list = info.list, argumentIndex = info.argumentIndex; + var argumentCount = getArgumentCount(list); + if (argumentIndex !== 0) { + ts.Debug.assertLessThan(argumentIndex, argumentCount); + } + var argumentsSpan = getApplicableSpanForArguments(list, sourceFile); + return { list: list, argumentIndex: argumentIndex, argumentCount: argumentCount, argumentsSpan: argumentsSpan }; + } + function getArgumentOrParameterListAndIndex(node, sourceFile) { + if (node.kind === 28 /* LessThanToken */ || node.kind === 20 /* OpenParenToken */) { + // Find the list that starts right *after* the < or ( token. + // If the user has just opened a list, consider this item 0. + return { list: getChildListThatStartsWithOpenerToken(node.parent, node, sourceFile), argumentIndex: 0 }; + } + else { + // findListItemInfo can return undefined if we are not in parent's argument list + // or type argument list. This includes cases where the cursor is: + // - To the right of the closing parenthesis, non-substitution template, or template tail. + // - Between the type arguments and the arguments (greater than token) + // - On the target of the call (parent.func) + // - On the 'new' keyword in a 'new' expression + var list = ts.findContainingList(node); + return list && { list: list, argumentIndex: getArgumentIndex(list, node) }; + } + } + /** + * Returns relevant information for the argument list and the current argument if we are + * in the argument of an invocation; returns undefined otherwise. + */ + function getImmediatelyContainingArgumentInfo(node, position, sourceFile) { + var parent = node.parent; + if (ts.isCallOrNewExpression(parent)) { + var invocation = parent; + // There are 3 cases to handle: + // 1. The token introduces a list, and should begin a signature help session + // 2. The token is either not associated with a list, or ends a list, so the session should end + // 3. The token is buried inside a list, and should give signature help + // + // The following are examples of each: + // + // Case 1: + // foo<#T, U>(#a, b) -> The token introduces a list, and should begin a signature help session + // Case 2: + // fo#o#(a, b)# -> The token is either not associated with a list, or ends a list, so the session should end + // Case 3: + // foo(a#, #b#) -> The token is buried inside a list, and should give signature help + // Find out if 'node' is an argument, a type argument, or neither + var info = getArgumentOrParameterListInfo(node, sourceFile); + if (!info) + return undefined; + var list = info.list, argumentIndex = info.argumentIndex, argumentCount = info.argumentCount, argumentsSpan = info.argumentsSpan; + var isTypeParameterList = !!parent.typeArguments && parent.typeArguments.pos === list.pos; + return { isTypeParameterList: isTypeParameterList, invocation: { kind: 0 /* Call */, node: invocation }, argumentsSpan: argumentsSpan, argumentIndex: argumentIndex, argumentCount: argumentCount }; + } + else if (ts.isNoSubstitutionTemplateLiteral(node) && ts.isTaggedTemplateExpression(parent)) { + // Check if we're actually inside the template; + // otherwise we'll fall out and return undefined. + if (ts.isInsideTemplateLiteral(node, position, sourceFile)) { + return getArgumentListInfoForTemplate(parent, /*argumentIndex*/ 0, sourceFile); + } + return undefined; + } + else if (ts.isTemplateHead(node) && parent.parent.kind === 193 /* TaggedTemplateExpression */) { + var templateExpression = parent; + var tagExpression = templateExpression.parent; + ts.Debug.assert(templateExpression.kind === 206 /* TemplateExpression */); + var argumentIndex = ts.isInsideTemplateLiteral(node, position, sourceFile) ? 0 : 1; + return getArgumentListInfoForTemplate(tagExpression, argumentIndex, sourceFile); + } + else if (ts.isTemplateSpan(parent) && ts.isTaggedTemplateExpression(parent.parent.parent)) { + var templateSpan = parent; + var tagExpression = parent.parent.parent; + // If we're just after a template tail, don't show signature help. + if (ts.isTemplateTail(node) && !ts.isInsideTemplateLiteral(node, position, sourceFile)) { + return undefined; + } + var spanIndex = templateSpan.parent.templateSpans.indexOf(templateSpan); + var argumentIndex = getArgumentIndexForTemplatePiece(spanIndex, node, position, sourceFile); + return getArgumentListInfoForTemplate(tagExpression, argumentIndex, sourceFile); + } + else if (ts.isJsxOpeningLikeElement(parent)) { + // Provide a signature help for JSX opening element or JSX self-closing element. + // This is not guarantee that JSX tag-name is resolved into stateless function component. (that is done in "getSignatureHelpItems") + // i.e + // export function MainButton(props: ButtonProps, context: any): JSX.Element { ... } + // ' 'b'. So, in this case the arg count will be 2. However, there + // is a small subtlety. If you have "Foo(a,)", then the child list will just have + // 'a' ''. So, in the case where the last child is a comma, we increase the + // arg count by one to compensate. + // + // Note: this subtlety only applies to the last comma. If you had "Foo(a,," then + // we'll have: 'a' '' '' + // That will give us 2 non-commas. We then add one for the last comma, giving us an + // arg count of 3. + var listChildren = argumentsList.getChildren(); + var argumentCount = ts.countWhere(listChildren, function (arg) { return arg.kind !== 27 /* CommaToken */; }); + if (listChildren.length > 0 && ts.last(listChildren).kind === 27 /* CommaToken */) { + argumentCount++; + } + return argumentCount; + } + // spanIndex is either the index for a given template span. + // This does not give appropriate results for a NoSubstitutionTemplateLiteral + function getArgumentIndexForTemplatePiece(spanIndex, node, position, sourceFile) { + // Because the TemplateStringsArray is the first argument, we have to offset each substitution expression by 1. + // There are three cases we can encounter: + // 1. We are precisely in the template literal (argIndex = 0). + // 2. We are in or to the right of the substitution expression (argIndex = spanIndex + 1). + // 3. We are directly to the right of the template literal, but because we look for the token on the left, + // not enough to put us in the substitution expression; we should consider ourselves part of + // the *next* span's expression by offsetting the index (argIndex = (spanIndex + 1) + 1). + // + // tslint:disable no-double-space + // Example: f `# abcd $#{# 1 + 1# }# efghi ${ #"#hello"# } # ` + // ^ ^ ^ ^ ^ ^ ^ ^ ^ + // Case: 1 1 3 2 1 3 2 2 1 + // tslint:enable no-double-space + ts.Debug.assert(position >= node.getStart(), "Assumed 'position' could not occur before node."); + if (ts.isTemplateLiteralToken(node)) { + if (ts.isInsideTemplateLiteral(node, position, sourceFile)) { + return 0; + } + return spanIndex + 2; + } + return spanIndex + 1; + } + function getArgumentListInfoForTemplate(tagExpression, argumentIndex, sourceFile) { + // argumentCount is either 1 or (numSpans + 1) to account for the template strings array argument. + var argumentCount = ts.isNoSubstitutionTemplateLiteral(tagExpression.template) ? 1 : tagExpression.template.templateSpans.length + 1; + if (argumentIndex !== 0) { + ts.Debug.assertLessThan(argumentIndex, argumentCount); + } + return { + isTypeParameterList: false, + invocation: { kind: 0 /* Call */, node: tagExpression }, + argumentsSpan: getApplicableSpanForTaggedTemplate(tagExpression, sourceFile), + argumentIndex: argumentIndex, + argumentCount: argumentCount + }; + } + function getApplicableSpanForArguments(argumentsList, sourceFile) { + // We use full start and skip trivia on the end because we want to include trivia on + // both sides. For example, + // + // foo( /*comment */ a, b, c /*comment*/ ) + // | | + // + // The applicable span is from the first bar to the second bar (inclusive, + // but not including parentheses) + var applicableSpanStart = argumentsList.getFullStart(); + var applicableSpanEnd = ts.skipTrivia(sourceFile.text, argumentsList.getEnd(), /*stopAfterLineBreak*/ false); + return ts.createTextSpan(applicableSpanStart, applicableSpanEnd - applicableSpanStart); + } + function getApplicableSpanForTaggedTemplate(taggedTemplate, sourceFile) { + var template = taggedTemplate.template; + var applicableSpanStart = template.getStart(); + var applicableSpanEnd = template.getEnd(); + // We need to adjust the end position for the case where the template does not have a tail. + // Otherwise, we will not show signature help past the expression. + // For example, + // + // ` ${ 1 + 1 foo(10) + // | | + // This is because a Missing node has no width. However, what we actually want is to include trivia + // leading up to the next token in case the user is about to type in a TemplateMiddle or TemplateTail. + if (template.kind === 206 /* TemplateExpression */) { + var lastSpan = ts.last(template.templateSpans); + if (lastSpan.literal.getFullWidth() === 0) { + applicableSpanEnd = ts.skipTrivia(sourceFile.text, applicableSpanEnd, /*stopAfterLineBreak*/ false); + } + } + return ts.createTextSpan(applicableSpanStart, applicableSpanEnd - applicableSpanStart); + } + function getContainingArgumentInfo(node, position, sourceFile, checker, isManuallyInvoked) { + var _loop_15 = function (n) { + // If the node is not a subspan of its parent, this is a big problem. + // There have been crashes that might be caused by this violation. + ts.Debug.assert(ts.rangeContainsRange(n.parent, n), "Not a subspan", function () { return "Child: " + ts.Debug.showSyntaxKind(n) + ", parent: " + ts.Debug.showSyntaxKind(n.parent); }); + var argumentInfo = getImmediatelyContainingArgumentOrContextualParameterInfo(n, position, sourceFile, checker); + if (argumentInfo) { + return { value: argumentInfo }; + } + }; + for (var n = node; isManuallyInvoked || (!ts.isBlock(n) && !ts.isSourceFile(n)); n = n.parent) { + var state_4 = _loop_15(n); + if (typeof state_4 === "object") + return state_4.value; + } + return undefined; + } + function getChildListThatStartsWithOpenerToken(parent, openerToken, sourceFile) { + var children = parent.getChildren(sourceFile); + var indexOfOpenerToken = children.indexOf(openerToken); + ts.Debug.assert(indexOfOpenerToken >= 0 && children.length > indexOfOpenerToken + 1); + return children[indexOfOpenerToken + 1]; + } + function getExpressionFromInvocation(invocation) { + return invocation.kind === 0 /* Call */ ? ts.getInvokedExpression(invocation.node) : invocation.called; + } + function getEnclosingDeclarationFromInvocation(invocation) { + return invocation.kind === 0 /* Call */ ? invocation.node : invocation.kind === 1 /* TypeArgs */ ? invocation.called : invocation.node; + } + var signatureHelpNodeBuilderFlags = 8192 /* OmitParameterModifiers */ | 70221824 /* IgnoreErrors */ | 16384 /* UseAliasDefinedOutsideCurrentScope */; + function createSignatureHelpItems(candidates, resolvedSignature, _a, sourceFile, typeChecker) { + var isTypeParameterList = _a.isTypeParameterList, argumentCount = _a.argumentCount, applicableSpan = _a.argumentsSpan, invocation = _a.invocation, argumentIndex = _a.argumentIndex; + var enclosingDeclaration = getEnclosingDeclarationFromInvocation(invocation); + var callTargetSymbol = invocation.kind === 2 /* Contextual */ ? invocation.symbol : typeChecker.getSymbolAtLocation(getExpressionFromInvocation(invocation)); + var callTargetDisplayParts = callTargetSymbol ? ts.symbolToDisplayParts(typeChecker, callTargetSymbol, /*enclosingDeclaration*/ undefined, /*meaning*/ undefined) : ts.emptyArray; + var items = candidates.map(function (candidateSignature) { return getSignatureHelpItem(candidateSignature, callTargetDisplayParts, isTypeParameterList, typeChecker, enclosingDeclaration, sourceFile); }); + if (argumentIndex !== 0) { + ts.Debug.assertLessThan(argumentIndex, argumentCount); + } + var selectedItemIndex = candidates.indexOf(resolvedSignature); + ts.Debug.assert(selectedItemIndex !== -1); // If candidates is non-empty it should always include bestSignature. We check for an empty candidates before calling this function. + return { items: items, applicableSpan: applicableSpan, selectedItemIndex: selectedItemIndex, argumentIndex: argumentIndex, argumentCount: argumentCount }; + } + function createTypeHelpItems(symbol, _a, sourceFile, checker) { + var argumentCount = _a.argumentCount, applicableSpan = _a.argumentsSpan, invocation = _a.invocation, argumentIndex = _a.argumentIndex; + var typeParameters = checker.getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); + if (!typeParameters) + return undefined; + var items = [getTypeHelpItem(symbol, typeParameters, checker, getEnclosingDeclarationFromInvocation(invocation), sourceFile)]; + return { items: items, applicableSpan: applicableSpan, selectedItemIndex: 0, argumentIndex: argumentIndex, argumentCount: argumentCount }; + } + function getTypeHelpItem(symbol, typeParameters, checker, enclosingDeclaration, sourceFile) { + var typeSymbolDisplay = ts.symbolToDisplayParts(checker, symbol); + var printer = ts.createPrinter({ removeComments: true }); + var parameters = typeParameters.map(function (t) { return createSignatureHelpParameterForTypeParameter(t, checker, enclosingDeclaration, sourceFile, printer); }); + var documentation = symbol.getDocumentationComment(checker); + var tags = symbol.getJsDocTags(); + var prefixDisplayParts = typeSymbolDisplay.concat([ts.punctuationPart(28 /* LessThanToken */)]); + return { isVariadic: false, prefixDisplayParts: prefixDisplayParts, suffixDisplayParts: [ts.punctuationPart(30 /* GreaterThanToken */)], separatorDisplayParts: separatorDisplayParts, parameters: parameters, documentation: documentation, tags: tags }; + } + var separatorDisplayParts = [ts.punctuationPart(27 /* CommaToken */), ts.spacePart()]; + function getSignatureHelpItem(candidateSignature, callTargetDisplayParts, isTypeParameterList, checker, enclosingDeclaration, sourceFile) { + var _a = (isTypeParameterList ? itemInfoForTypeParameters : itemInfoForParameters)(candidateSignature, checker, enclosingDeclaration, sourceFile), isVariadic = _a.isVariadic, parameters = _a.parameters, prefix = _a.prefix, suffix = _a.suffix; + var prefixDisplayParts = callTargetDisplayParts.concat(prefix); + var suffixDisplayParts = suffix.concat(returnTypeToDisplayParts(candidateSignature, enclosingDeclaration, checker)); + var documentation = candidateSignature.getDocumentationComment(checker); + var tags = candidateSignature.getJsDocTags(); + return { isVariadic: isVariadic, prefixDisplayParts: prefixDisplayParts, suffixDisplayParts: suffixDisplayParts, separatorDisplayParts: separatorDisplayParts, parameters: parameters, documentation: documentation, tags: tags }; + } + function returnTypeToDisplayParts(candidateSignature, enclosingDeclaration, checker) { + return ts.mapToDisplayParts(function (writer) { + writer.writePunctuation(":"); + writer.writeSpace(" "); + var predicate = checker.getTypePredicateOfSignature(candidateSignature); + if (predicate) { + checker.writeTypePredicate(predicate, enclosingDeclaration, /*flags*/ undefined, writer); + } + else { + checker.writeType(checker.getReturnTypeOfSignature(candidateSignature), enclosingDeclaration, /*flags*/ undefined, writer); + } + }); + } + function itemInfoForTypeParameters(candidateSignature, checker, enclosingDeclaration, sourceFile) { + var typeParameters = (candidateSignature.target || candidateSignature).typeParameters; + var printer = ts.createPrinter({ removeComments: true }); + var parameters = (typeParameters || ts.emptyArray).map(function (t) { return createSignatureHelpParameterForTypeParameter(t, checker, enclosingDeclaration, sourceFile, printer); }); + var parameterParts = ts.mapToDisplayParts(function (writer) { + var thisParameter = candidateSignature.thisParameter ? [checker.symbolToParameterDeclaration(candidateSignature.thisParameter, enclosingDeclaration, signatureHelpNodeBuilderFlags)] : []; + var params = ts.createNodeArray(thisParameter.concat(candidateSignature.parameters.map(function (param) { return checker.symbolToParameterDeclaration(param, enclosingDeclaration, signatureHelpNodeBuilderFlags); }))); + printer.writeList(2576 /* CallExpressionArguments */, params, sourceFile, writer); + }); + return { isVariadic: false, parameters: parameters, prefix: [ts.punctuationPart(28 /* LessThanToken */)], suffix: [ts.punctuationPart(30 /* GreaterThanToken */)].concat(parameterParts) }; + } + function itemInfoForParameters(candidateSignature, checker, enclosingDeclaration, sourceFile) { + var isVariadic = candidateSignature.hasRestParameter; + var printer = ts.createPrinter({ removeComments: true }); + var typeParameterParts = ts.mapToDisplayParts(function (writer) { + if (candidateSignature.typeParameters && candidateSignature.typeParameters.length) { + var args = ts.createNodeArray(candidateSignature.typeParameters.map(function (p) { return checker.typeParameterToDeclaration(p, enclosingDeclaration); })); + printer.writeList(53776 /* TypeParameters */, args, sourceFile, writer); + } + }); + var parameters = candidateSignature.parameters.map(function (p) { return createSignatureHelpParameterForParameter(p, checker, enclosingDeclaration, sourceFile, printer); }); + return { isVariadic: isVariadic, parameters: parameters, prefix: typeParameterParts.concat([ts.punctuationPart(20 /* OpenParenToken */)]), suffix: [ts.punctuationPart(21 /* CloseParenToken */)] }; + } + function createSignatureHelpParameterForParameter(parameter, checker, enclosingDeclaration, sourceFile, printer) { + var displayParts = ts.mapToDisplayParts(function (writer) { + var param = checker.symbolToParameterDeclaration(parameter, enclosingDeclaration, signatureHelpNodeBuilderFlags); + printer.writeNode(4 /* Unspecified */, param, sourceFile, writer); + }); + var isOptional = checker.isOptionalParameter(parameter.valueDeclaration); + return { name: parameter.name, documentation: parameter.getDocumentationComment(checker), displayParts: displayParts, isOptional: isOptional }; + } + function createSignatureHelpParameterForTypeParameter(typeParameter, checker, enclosingDeclaration, sourceFile, printer) { + var displayParts = ts.mapToDisplayParts(function (writer) { + var param = checker.typeParameterToDeclaration(typeParameter, enclosingDeclaration); + printer.writeNode(4 /* Unspecified */, param, sourceFile, writer); + }); + return { name: typeParameter.symbol.name, documentation: typeParameter.symbol.getDocumentationComment(checker), displayParts: displayParts, isOptional: false }; + } + })(SignatureHelp = ts.SignatureHelp || (ts.SignatureHelp = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var base64UrlRegExp = /^data:(?:application\/json(?:;charset=[uU][tT][fF]-8);base64,([A-Za-z0-9+\/=]+)$)?/; + function getSourceMapper(useCaseSensitiveFileNames, currentDirectory, log, host, getProgram) { + var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); + var sourcemappedFileCache; + return { tryGetSourcePosition: tryGetSourcePosition, tryGetGeneratedPosition: tryGetGeneratedPosition, toLineColumnOffset: toLineColumnOffset, clearCache: clearCache }; + function toPath(fileName) { + return ts.toPath(fileName, currentDirectory, getCanonicalFileName); + } + function scanForSourcemapURL(fileName) { + var mappedFile = sourcemappedFileCache.get(toPath(fileName)); + if (!mappedFile) { + return; + } + return ts.tryGetSourceMappingURL(mappedFile.text, ts.getLineStarts(mappedFile)); + } + function convertDocumentToSourceMapper(file, contents, mapFileName) { + var map = ts.tryParseRawSourceMap(contents); + if (!map || !map.sources || !map.file || !map.mappings) { + // obviously invalid map + return file.sourceMapper = ts.identitySourceMapConsumer; + } + var program = getProgram(); + return file.sourceMapper = ts.createDocumentPositionMapper({ + getSourceFileLike: function (s) { + // Lookup file in program, if provided + var file = program && program.getSourceFileByPath(s); + // file returned here could be .d.ts when asked for .ts file if projectReferences and module resolution created this source file + if (file === undefined || file.resolvedPath !== s) { + // Otherwise check the cache (which may hit disk) + return sourcemappedFileCache.get(s); + } + return file; + }, + getCanonicalFileName: getCanonicalFileName, + log: log, + }, map, mapFileName); + } + function getSourceMapper(fileName, file) { + if (!host.readFile || !host.fileExists) { + return file.sourceMapper = ts.identitySourceMapConsumer; + } + if (file.sourceMapper) { + return file.sourceMapper; + } + var mapFileName = scanForSourcemapURL(fileName); + if (mapFileName) { + var match = base64UrlRegExp.exec(mapFileName); + if (match) { + if (match[1]) { + var base64Object = match[1]; + return convertDocumentToSourceMapper(file, ts.base64decode(ts.sys, base64Object), fileName); + } + // Not a data URL we can parse, skip it + mapFileName = undefined; + } + } + var possibleMapLocations = []; + if (mapFileName) { + possibleMapLocations.push(mapFileName); + } + possibleMapLocations.push(fileName + ".map"); + for (var _i = 0, possibleMapLocations_1 = possibleMapLocations; _i < possibleMapLocations_1.length; _i++) { + var location = possibleMapLocations_1[_i]; + var mapPath = ts.toPath(location, ts.getDirectoryPath(fileName), getCanonicalFileName); + if (host.fileExists(mapPath)) { + return convertDocumentToSourceMapper(file, host.readFile(mapPath), mapPath); // TODO: GH#18217 + } + } + return file.sourceMapper = ts.identitySourceMapConsumer; + } + function tryGetSourcePosition(info) { + if (!ts.isDeclarationFileName(info.fileName)) + return undefined; + var file = getFile(info.fileName); + if (!file) + return undefined; + var newLoc = getSourceMapper(info.fileName, file).getSourcePosition(info); + return newLoc === info ? undefined : tryGetSourcePosition(newLoc) || newLoc; + } + function tryGetGeneratedPosition(info) { + var program = getProgram(); + var options = program.getCompilerOptions(); + var outPath = options.outFile || options.out; + var declarationPath = outPath ? + ts.removeFileExtension(outPath) + ".d.ts" /* Dts */ : + ts.getDeclarationEmitOutputFilePathWorker(info.fileName, program.getCompilerOptions(), currentDirectory, program.getCommonSourceDirectory(), getCanonicalFileName); + if (declarationPath === undefined) + return undefined; + var declarationFile = getFile(declarationPath); + if (!declarationFile) + return undefined; + var newLoc = getSourceMapper(declarationPath, declarationFile).getGeneratedPosition(info); + return newLoc === info ? undefined : newLoc; + } + function getFile(fileName) { + var path = toPath(fileName); + var file = getProgram().getSourceFileByPath(path); + if (file && file.resolvedPath === path) { + return file; + } + return sourcemappedFileCache.get(path); + } + function toLineColumnOffset(fileName, position) { + var file = getFile(fileName); // TODO: GH#18217 + return file.getLineAndCharacterOfPosition(position); + } + function clearCache() { + sourcemappedFileCache = createSourceFileLikeCache(host); + } + } + ts.getSourceMapper = getSourceMapper; + function createSourceFileLikeCache(host) { + var cached = ts.createMap(); + return { + get: function (path) { + if (cached.has(path)) { + return cached.get(path); + } + if (!host.fileExists || !host.readFile || !host.fileExists(path)) + return; + // And failing that, check the disk + var text = host.readFile(path); // TODO: GH#18217 + var file = { + text: text, + lineMap: undefined, + getLineAndCharacterOfPosition: function (pos) { + return ts.computeLineAndCharacterOfPosition(ts.getLineStarts(this), pos); + } + }; + cached.set(path, file); + return file; + } + }; + } +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + function computeSuggestionDiagnostics(sourceFile, program, cancellationToken) { + program.getSemanticDiagnostics(sourceFile, cancellationToken); + var diags = []; + var checker = program.getTypeChecker(); + if (sourceFile.commonJsModuleIndicator && + (ts.programContainsEs6Modules(program) || ts.compilerOptionsIndicateEs6Modules(program.getCompilerOptions())) && + containsTopLevelCommonjs(sourceFile)) { + diags.push(ts.createDiagnosticForNode(getErrorNodeFromCommonJsIndicator(sourceFile.commonJsModuleIndicator), ts.Diagnostics.File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module)); + } + var isJsFile = ts.isSourceFileJS(sourceFile); + check(sourceFile); + if (ts.getAllowSyntheticDefaultImports(program.getCompilerOptions())) { + for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { + var moduleSpecifier = _a[_i]; + var importNode = ts.importFromModuleSpecifier(moduleSpecifier); + var name = importNameForConvertToDefaultImport(importNode); + if (!name) + continue; + var module_2 = ts.getResolvedModule(sourceFile, moduleSpecifier.text); + var resolvedFile = module_2 && program.getSourceFile(module_2.resolvedFileName); + if (resolvedFile && resolvedFile.externalModuleIndicator && ts.isExportAssignment(resolvedFile.externalModuleIndicator) && resolvedFile.externalModuleIndicator.isExportEquals) { + diags.push(ts.createDiagnosticForNode(name, ts.Diagnostics.Import_may_be_converted_to_a_default_import)); + } + } + } + ts.addRange(diags, sourceFile.bindSuggestionDiagnostics); + ts.addRange(diags, program.getSuggestionDiagnostics(sourceFile, cancellationToken)); + return diags.sort(function (d1, d2) { return d1.start - d2.start; }); + function check(node) { + if (isJsFile) { + switch (node.kind) { + case 196 /* FunctionExpression */: + var decl = ts.getDeclarationOfExpando(node); + if (decl) { + var symbol_2 = decl.symbol; + if (symbol_2 && (symbol_2.exports && symbol_2.exports.size || symbol_2.members && symbol_2.members.size)) { + diags.push(ts.createDiagnosticForNode(ts.isVariableDeclaration(node.parent) ? node.parent.name : node, ts.Diagnostics.This_constructor_function_may_be_converted_to_a_class_declaration)); + break; + } + } + // falls through if no diagnostic was created + case 239 /* FunctionDeclaration */: + var symbol = node.symbol; + if (symbol.members && (symbol.members.size > 0)) { + diags.push(ts.createDiagnosticForNode(ts.isVariableDeclaration(node.parent) ? node.parent.name : node, ts.Diagnostics.This_constructor_function_may_be_converted_to_a_class_declaration)); + } + break; + } + } + else { + if (ts.isVariableStatement(node) && + node.parent === sourceFile && + node.declarationList.flags & 2 /* Const */ && + node.declarationList.declarations.length === 1) { + var init = node.declarationList.declarations[0].initializer; + if (init && ts.isRequireCall(init, /*checkArgumentIsStringLiteralLike*/ true)) { + diags.push(ts.createDiagnosticForNode(init, ts.Diagnostics.require_call_may_be_converted_to_an_import)); + } + } + if (ts.codefix.parameterShouldGetTypeFromJSDoc(node)) { + diags.push(ts.createDiagnosticForNode(node.name || node, ts.Diagnostics.JSDoc_types_may_be_moved_to_TypeScript_types)); + } + } + if (ts.isFunctionLikeDeclaration(node)) { + addConvertToAsyncFunctionDiagnostics(node, checker, diags); + } + node.forEachChild(check); + } + } + ts.computeSuggestionDiagnostics = computeSuggestionDiagnostics; + // convertToEs6Module only works on top-level, so don't trigger it if commonjs code only appears in nested scopes. + function containsTopLevelCommonjs(sourceFile) { + return sourceFile.statements.some(function (statement) { + switch (statement.kind) { + case 219 /* VariableStatement */: + return statement.declarationList.declarations.some(function (decl) { + return !!decl.initializer && ts.isRequireCall(propertyAccessLeftHandSide(decl.initializer), /*checkArgumentIsStringLiteralLike*/ true); + }); + case 221 /* ExpressionStatement */: { + var expression = statement.expression; + if (!ts.isBinaryExpression(expression)) + return ts.isRequireCall(expression, /*checkArgumentIsStringLiteralLike*/ true); + var kind = ts.getAssignmentDeclarationKind(expression); + return kind === 1 /* ExportsProperty */ || kind === 2 /* ModuleExports */; + } + default: + return false; + } + }); + } + function propertyAccessLeftHandSide(node) { + return ts.isPropertyAccessExpression(node) ? propertyAccessLeftHandSide(node.expression) : node; + } + function importNameForConvertToDefaultImport(node) { + switch (node.kind) { + case 249 /* ImportDeclaration */: + var importClause = node.importClause, moduleSpecifier = node.moduleSpecifier; + return importClause && !importClause.name && importClause.namedBindings && importClause.namedBindings.kind === 251 /* NamespaceImport */ && ts.isStringLiteral(moduleSpecifier) + ? importClause.namedBindings.name + : undefined; + case 248 /* ImportEqualsDeclaration */: + return node.name; + default: + return undefined; + } + } + function addConvertToAsyncFunctionDiagnostics(node, checker, diags) { + if (!ts.isAsyncFunction(node) && + node.body && + ts.isBlock(node.body) && + hasReturnStatementWithPromiseHandler(node.body) && + returnsPromise(node, checker)) { + diags.push(ts.createDiagnosticForNode(!node.name && ts.isVariableDeclaration(node.parent) && ts.isIdentifier(node.parent.name) ? node.parent.name : node, ts.Diagnostics.This_may_be_converted_to_an_async_function)); + } + } + function returnsPromise(node, checker) { + var functionType = checker.getTypeAtLocation(node); + var callSignatures = checker.getSignaturesOfType(functionType, 0 /* Call */); + var returnType = callSignatures.length ? checker.getReturnTypeOfSignature(callSignatures[0]) : undefined; + return !!returnType && !!checker.getPromisedTypeOfPromise(returnType); + } + function getErrorNodeFromCommonJsIndicator(commonJsModuleIndicator) { + return ts.isBinaryExpression(commonJsModuleIndicator) ? commonJsModuleIndicator.left : commonJsModuleIndicator; + } + function hasReturnStatementWithPromiseHandler(body) { + return !!ts.forEachReturnStatement(body, isReturnStatementWithFixablePromiseHandler); + } + function isReturnStatementWithFixablePromiseHandler(node) { + return ts.isReturnStatement(node) && !!node.expression && isFixablePromiseHandler(node.expression); + } + ts.isReturnStatementWithFixablePromiseHandler = isReturnStatementWithFixablePromiseHandler; + // Should be kept up to date with transformExpression in convertToAsyncFunction.ts + function isFixablePromiseHandler(node) { + // ensure outermost call exists and is a promise handler + if (!isPromiseHandler(node) || !node.arguments.every(isFixablePromiseArgument)) { + return false; + } + // ensure all chained calls are valid + var currentNode = node.expression; + while (isPromiseHandler(currentNode) || ts.isPropertyAccessExpression(currentNode)) { + if (ts.isCallExpression(currentNode) && !currentNode.arguments.every(isFixablePromiseArgument)) { + return false; + } + currentNode = currentNode.expression; + } + return true; + } + ts.isFixablePromiseHandler = isFixablePromiseHandler; + function isPromiseHandler(node) { + return ts.isCallExpression(node) && (ts.hasPropertyAccessExpressionWithName(node, "then") || ts.hasPropertyAccessExpressionWithName(node, "catch")); + } + // should be kept up to date with getTransformationBody in convertToAsyncFunction.ts + function isFixablePromiseArgument(arg) { + switch (arg.kind) { + case 96 /* NullKeyword */: + case 72 /* Identifier */: // identifier includes undefined + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + return true; + default: + return false; + } + } +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var SymbolDisplay; + (function (SymbolDisplay) { + // TODO(drosen): use contextual SemanticMeaning. + function getSymbolKind(typeChecker, symbol, location) { + var result = getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, location); + if (result !== "" /* unknown */) { + return result; + } + var flags = ts.getCombinedLocalAndExportSymbolFlags(symbol); + if (flags & 32 /* Class */) { + return ts.getDeclarationOfKind(symbol, 209 /* ClassExpression */) ? + "local class" /* localClassElement */ : "class" /* classElement */; + } + if (flags & 384 /* Enum */) + return "enum" /* enumElement */; + if (flags & 524288 /* TypeAlias */) + return "type" /* typeElement */; + if (flags & 64 /* Interface */) + return "interface" /* interfaceElement */; + if (flags & 262144 /* TypeParameter */) + return "type parameter" /* typeParameterElement */; + if (flags & 262144 /* TypeParameter */) + return "type parameter" /* typeParameterElement */; + if (flags & 8 /* EnumMember */) + return "enum member" /* enumMemberElement */; + if (flags & 2097152 /* Alias */) + return "alias" /* alias */; + if (flags & 1536 /* Module */) + return "module" /* moduleElement */; + return result; + } + SymbolDisplay.getSymbolKind = getSymbolKind; + function getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, location) { + var roots = typeChecker.getRootSymbols(symbol); + // If this is a method from a mapped type, leave as a method so long as it still has a call signature. + if (roots.length === 1 + && ts.first(roots).flags & 8192 /* Method */ + // Ensure the mapped version is still a method, as opposed to `{ [K in keyof I]: number }`. + && typeChecker.getTypeOfSymbolAtLocation(symbol, location).getNonNullableType().getCallSignatures().length !== 0) { + return "method" /* memberFunctionElement */; + } + if (typeChecker.isUndefinedSymbol(symbol)) { + return "var" /* variableElement */; + } + if (typeChecker.isArgumentsSymbol(symbol)) { + return "local var" /* localVariableElement */; + } + if (location.kind === 100 /* ThisKeyword */ && ts.isExpression(location)) { + return "parameter" /* parameterElement */; + } + var flags = ts.getCombinedLocalAndExportSymbolFlags(symbol); + if (flags & 3 /* Variable */) { + if (ts.isFirstDeclarationOfSymbolParameter(symbol)) { + return "parameter" /* parameterElement */; + } + else if (symbol.valueDeclaration && ts.isVarConst(symbol.valueDeclaration)) { + return "const" /* constElement */; + } + else if (ts.forEach(symbol.declarations, ts.isLet)) { + return "let" /* letElement */; + } + return isLocalVariableOrFunction(symbol) ? "local var" /* localVariableElement */ : "var" /* variableElement */; + } + if (flags & 16 /* Function */) + return isLocalVariableOrFunction(symbol) ? "local function" /* localFunctionElement */ : "function" /* functionElement */; + if (flags & 32768 /* GetAccessor */) + return "getter" /* memberGetAccessorElement */; + if (flags & 65536 /* SetAccessor */) + return "setter" /* memberSetAccessorElement */; + if (flags & 8192 /* Method */) + return "method" /* memberFunctionElement */; + if (flags & 16384 /* Constructor */) + return "constructor" /* constructorImplementationElement */; + if (flags & 4 /* Property */) { + if (flags & 33554432 /* Transient */ && symbol.checkFlags & 6 /* Synthetic */) { + // If union property is result of union of non method (property/accessors/variables), it is labeled as property + var unionPropertyKind = ts.forEach(typeChecker.getRootSymbols(symbol), function (rootSymbol) { + var rootSymbolFlags = rootSymbol.getFlags(); + if (rootSymbolFlags & (98308 /* PropertyOrAccessor */ | 3 /* Variable */)) { + return "property" /* memberVariableElement */; + } + // May be a Function if this was from `typeof N` with `namespace N { function f();. }`. + ts.Debug.assert(!!(rootSymbolFlags & (8192 /* Method */ | 16 /* Function */))); + }); + if (!unionPropertyKind) { + // If this was union of all methods, + // make sure it has call signatures before we can label it as method + var typeOfUnionProperty = typeChecker.getTypeOfSymbolAtLocation(symbol, location); + if (typeOfUnionProperty.getCallSignatures().length) { + return "method" /* memberFunctionElement */; + } + return "property" /* memberVariableElement */; + } + return unionPropertyKind; + } + // If we requested completions after `x.` at the top-level, we may be at a source file location. + switch (location.parent && location.parent.kind) { + // If we've typed a character of the attribute name, will be 'JsxAttribute', else will be 'JsxOpeningElement'. + case 262 /* JsxOpeningElement */: + case 260 /* JsxElement */: + case 261 /* JsxSelfClosingElement */: + return location.kind === 72 /* Identifier */ ? "property" /* memberVariableElement */ : "JSX attribute" /* jsxAttribute */; + case 267 /* JsxAttribute */: + return "JSX attribute" /* jsxAttribute */; + default: + return "property" /* memberVariableElement */; + } + } + return "" /* unknown */; + } + function getSymbolModifiers(symbol) { + var nodeModifiers = symbol && symbol.declarations && symbol.declarations.length > 0 + ? ts.getNodeModifiers(symbol.declarations[0]) + : "" /* none */; + var symbolModifiers = symbol && symbol.flags & 16777216 /* Optional */ ? + "optional" /* optionalModifier */ + : "" /* none */; + return nodeModifiers && symbolModifiers ? nodeModifiers + "," + symbolModifiers : nodeModifiers || symbolModifiers; + } + SymbolDisplay.getSymbolModifiers = getSymbolModifiers; + // TODO(drosen): Currently completion entry details passes the SemanticMeaning.All instead of using semanticMeaning of location + function getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, enclosingDeclaration, location, semanticMeaning, alias) { + if (semanticMeaning === void 0) { semanticMeaning = ts.getMeaningFromLocation(location); } + var displayParts = []; + var documentation; + var tags; + var symbolFlags = ts.getCombinedLocalAndExportSymbolFlags(symbol); + var symbolKind = semanticMeaning & 1 /* Value */ ? getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, location) : "" /* unknown */; + var hasAddedSymbolInfo = false; + var isThisExpression = location.kind === 100 /* ThisKeyword */ && ts.isInExpressionContext(location); + var type; + var printer; + var documentationFromAlias; + var tagsFromAlias; + if (location.kind === 100 /* ThisKeyword */ && !isThisExpression) { + return { displayParts: [ts.keywordPart(100 /* ThisKeyword */)], documentation: [], symbolKind: "primitive type" /* primitiveType */, tags: undefined }; + } + // Class at constructor site need to be shown as constructor apart from property,method, vars + if (symbolKind !== "" /* unknown */ || symbolFlags & 32 /* Class */ || symbolFlags & 2097152 /* Alias */) { + // If it is accessor they are allowed only if location is at name of the accessor + if (symbolKind === "getter" /* memberGetAccessorElement */ || symbolKind === "setter" /* memberSetAccessorElement */) { + symbolKind = "property" /* memberVariableElement */; + } + var signature = void 0; + type = isThisExpression ? typeChecker.getTypeAtLocation(location) : typeChecker.getTypeOfSymbolAtLocation(symbol.exportSymbol || symbol, location); + if (location.parent && location.parent.kind === 189 /* PropertyAccessExpression */) { + var right = location.parent.name; + // Either the location is on the right of a property access, or on the left and the right is missing + if (right === location || (right && right.getFullWidth() === 0)) { + location = location.parent; + } + } + // try get the call/construct signature from the type if it matches + var callExpressionLike = void 0; + if (ts.isCallOrNewExpression(location)) { + callExpressionLike = location; + } + else if (ts.isCallExpressionTarget(location) || ts.isNewExpressionTarget(location)) { + callExpressionLike = location.parent; + } + else if (location.parent && ts.isJsxOpeningLikeElement(location.parent) && ts.isFunctionLike(symbol.valueDeclaration)) { + callExpressionLike = location.parent; + } + if (callExpressionLike) { + var candidateSignatures = []; + signature = typeChecker.getResolvedSignature(callExpressionLike, candidateSignatures); // TODO: GH#18217 + var useConstructSignatures = callExpressionLike.kind === 192 /* NewExpression */ || (ts.isCallExpression(callExpressionLike) && callExpressionLike.expression.kind === 98 /* SuperKeyword */); + var allSignatures = useConstructSignatures ? type.getConstructSignatures() : type.getCallSignatures(); + if (!ts.contains(allSignatures, signature.target) && !ts.contains(allSignatures, signature)) { + // Get the first signature if there is one -- allSignatures may contain + // either the original signature or its target, so check for either + signature = allSignatures.length ? allSignatures[0] : undefined; + } + if (signature) { + if (useConstructSignatures && (symbolFlags & 32 /* Class */)) { + // Constructor + symbolKind = "constructor" /* constructorImplementationElement */; + addPrefixForAnyFunctionOrVar(type.symbol, symbolKind); + } + else if (symbolFlags & 2097152 /* Alias */) { + symbolKind = "alias" /* alias */; + pushSymbolKind(symbolKind); + displayParts.push(ts.spacePart()); + if (useConstructSignatures) { + displayParts.push(ts.keywordPart(95 /* NewKeyword */)); + displayParts.push(ts.spacePart()); + } + addFullSymbolName(symbol); + } + else { + addPrefixForAnyFunctionOrVar(symbol, symbolKind); + } + switch (symbolKind) { + case "JSX attribute" /* jsxAttribute */: + case "property" /* memberVariableElement */: + case "var" /* variableElement */: + case "const" /* constElement */: + case "let" /* letElement */: + case "parameter" /* parameterElement */: + case "local var" /* localVariableElement */: + // If it is call or construct signature of lambda's write type name + displayParts.push(ts.punctuationPart(57 /* ColonToken */)); + displayParts.push(ts.spacePart()); + if (!(ts.getObjectFlags(type) & 16 /* Anonymous */) && type.symbol) { + ts.addRange(displayParts, ts.symbolToDisplayParts(typeChecker, type.symbol, enclosingDeclaration, /*meaning*/ undefined, 4 /* AllowAnyNodeKind */ | 1 /* WriteTypeParametersOrArguments */)); + displayParts.push(ts.lineBreakPart()); + } + if (useConstructSignatures) { + displayParts.push(ts.keywordPart(95 /* NewKeyword */)); + displayParts.push(ts.spacePart()); + } + addSignatureDisplayParts(signature, allSignatures, 262144 /* WriteArrowStyleSignature */); + break; + default: + // Just signature + addSignatureDisplayParts(signature, allSignatures); + } + hasAddedSymbolInfo = true; + } + } + else if ((ts.isNameOfFunctionDeclaration(location) && !(symbolFlags & 98304 /* Accessor */)) || // name of function declaration + (location.kind === 124 /* ConstructorKeyword */ && location.parent.kind === 157 /* Constructor */)) { // At constructor keyword of constructor declaration + // get the signature from the declaration and write it + var functionDeclaration_1 = location.parent; + // Use function declaration to write the signatures only if the symbol corresponding to this declaration + var locationIsSymbolDeclaration = ts.find(symbol.declarations, function (declaration) { + return declaration === (location.kind === 124 /* ConstructorKeyword */ ? functionDeclaration_1.parent : functionDeclaration_1); + }); + if (locationIsSymbolDeclaration) { + var allSignatures = functionDeclaration_1.kind === 157 /* Constructor */ ? type.getNonNullableType().getConstructSignatures() : type.getNonNullableType().getCallSignatures(); + if (!typeChecker.isImplementationOfOverload(functionDeclaration_1)) { + signature = typeChecker.getSignatureFromDeclaration(functionDeclaration_1); // TODO: GH#18217 + } + else { + signature = allSignatures[0]; + } + if (functionDeclaration_1.kind === 157 /* Constructor */) { + // show (constructor) Type(...) signature + symbolKind = "constructor" /* constructorImplementationElement */; + addPrefixForAnyFunctionOrVar(type.symbol, symbolKind); + } + else { + // (function/method) symbol(..signature) + addPrefixForAnyFunctionOrVar(functionDeclaration_1.kind === 160 /* CallSignature */ && + !(type.symbol.flags & 2048 /* TypeLiteral */ || type.symbol.flags & 4096 /* ObjectLiteral */) ? type.symbol : symbol, symbolKind); + } + addSignatureDisplayParts(signature, allSignatures); + hasAddedSymbolInfo = true; + } + } + } + if (symbolFlags & 32 /* Class */ && !hasAddedSymbolInfo && !isThisExpression) { + addAliasPrefixIfNecessary(); + if (ts.getDeclarationOfKind(symbol, 209 /* ClassExpression */)) { + // Special case for class expressions because we would like to indicate that + // the class name is local to the class body (similar to function expression) + // (local class) class + pushSymbolKind("local class" /* localClassElement */); + } + else { + // Class declaration has name which is not local. + displayParts.push(ts.keywordPart(76 /* ClassKeyword */)); + } + displayParts.push(ts.spacePart()); + addFullSymbolName(symbol); + writeTypeParametersOfSymbol(symbol, sourceFile); + } + if ((symbolFlags & 64 /* Interface */) && (semanticMeaning & 2 /* Type */)) { + prefixNextMeaning(); + displayParts.push(ts.keywordPart(110 /* InterfaceKeyword */)); + displayParts.push(ts.spacePart()); + addFullSymbolName(symbol); + writeTypeParametersOfSymbol(symbol, sourceFile); + } + if ((symbolFlags & 524288 /* TypeAlias */) && (semanticMeaning & 2 /* Type */)) { + prefixNextMeaning(); + displayParts.push(ts.keywordPart(140 /* TypeKeyword */)); + displayParts.push(ts.spacePart()); + addFullSymbolName(symbol); + writeTypeParametersOfSymbol(symbol, sourceFile); + displayParts.push(ts.spacePart()); + displayParts.push(ts.operatorPart(59 /* EqualsToken */)); + displayParts.push(ts.spacePart()); + ts.addRange(displayParts, ts.typeToDisplayParts(typeChecker, typeChecker.getDeclaredTypeOfSymbol(symbol), enclosingDeclaration, 8388608 /* InTypeAlias */)); + } + if (symbolFlags & 384 /* Enum */) { + prefixNextMeaning(); + if (ts.some(symbol.declarations, function (d) { return ts.isEnumDeclaration(d) && ts.isEnumConst(d); })) { + displayParts.push(ts.keywordPart(77 /* ConstKeyword */)); + displayParts.push(ts.spacePart()); + } + displayParts.push(ts.keywordPart(84 /* EnumKeyword */)); + displayParts.push(ts.spacePart()); + addFullSymbolName(symbol); + } + if (symbolFlags & 1536 /* Module */) { + prefixNextMeaning(); + var declaration = ts.getDeclarationOfKind(symbol, 244 /* ModuleDeclaration */); + var isNamespace = declaration && declaration.name && declaration.name.kind === 72 /* Identifier */; + displayParts.push(ts.keywordPart(isNamespace ? 131 /* NamespaceKeyword */ : 130 /* ModuleKeyword */)); + displayParts.push(ts.spacePart()); + addFullSymbolName(symbol); + } + if ((symbolFlags & 262144 /* TypeParameter */) && (semanticMeaning & 2 /* Type */)) { + prefixNextMeaning(); + displayParts.push(ts.punctuationPart(20 /* OpenParenToken */)); + displayParts.push(ts.textPart("type parameter")); + displayParts.push(ts.punctuationPart(21 /* CloseParenToken */)); + displayParts.push(ts.spacePart()); + addFullSymbolName(symbol); + if (symbol.parent) { + // Class/Interface type parameter + addInPrefix(); + addFullSymbolName(symbol.parent, enclosingDeclaration); + writeTypeParametersOfSymbol(symbol.parent, enclosingDeclaration); + } + else { + // Method/function type parameter + var decl = ts.getDeclarationOfKind(symbol, 150 /* TypeParameter */); + if (decl === undefined) + return ts.Debug.fail(); + var declaration = decl.parent; + if (declaration) { + if (ts.isFunctionLikeKind(declaration.kind)) { + addInPrefix(); + var signature = typeChecker.getSignatureFromDeclaration(declaration); // TODO: GH#18217 + if (declaration.kind === 161 /* ConstructSignature */) { + displayParts.push(ts.keywordPart(95 /* NewKeyword */)); + displayParts.push(ts.spacePart()); + } + else if (declaration.kind !== 160 /* CallSignature */ && declaration.name) { + addFullSymbolName(declaration.symbol); + } + ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, sourceFile, 32 /* WriteTypeArgumentsOfSignature */)); + } + else if (declaration.kind === 242 /* TypeAliasDeclaration */) { + // Type alias type parameter + // For example + // type list = T[]; // Both T will go through same code path + addInPrefix(); + displayParts.push(ts.keywordPart(140 /* TypeKeyword */)); + displayParts.push(ts.spacePart()); + addFullSymbolName(declaration.symbol); + writeTypeParametersOfSymbol(declaration.symbol, sourceFile); + } + } + } + } + if (symbolFlags & 8 /* EnumMember */) { + symbolKind = "enum member" /* enumMemberElement */; + addPrefixForAnyFunctionOrVar(symbol, "enum member"); + var declaration = symbol.declarations[0]; + if (declaration.kind === 278 /* EnumMember */) { + var constantValue = typeChecker.getConstantValue(declaration); + if (constantValue !== undefined) { + displayParts.push(ts.spacePart()); + displayParts.push(ts.operatorPart(59 /* EqualsToken */)); + displayParts.push(ts.spacePart()); + displayParts.push(ts.displayPart(ts.getTextOfConstantValue(constantValue), typeof constantValue === "number" ? ts.SymbolDisplayPartKind.numericLiteral : ts.SymbolDisplayPartKind.stringLiteral)); + } + } + } + if (symbolFlags & 2097152 /* Alias */) { + prefixNextMeaning(); + if (!hasAddedSymbolInfo) { + var resolvedSymbol = typeChecker.getAliasedSymbol(symbol); + if (resolvedSymbol !== symbol && resolvedSymbol.declarations && resolvedSymbol.declarations.length > 0) { + var resolvedNode = resolvedSymbol.declarations[0]; + var declarationName = ts.getNameOfDeclaration(resolvedNode); + if (declarationName) { + var isExternalModuleDeclaration = ts.isModuleWithStringLiteralName(resolvedNode) && + ts.hasModifier(resolvedNode, 2 /* Ambient */); + var shouldUseAliasName = symbol.name !== "default" && !isExternalModuleDeclaration; + var resolvedInfo = getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, resolvedSymbol, ts.getSourceFileOfNode(resolvedNode), resolvedNode, declarationName, semanticMeaning, shouldUseAliasName ? symbol : resolvedSymbol); + displayParts.push.apply(displayParts, resolvedInfo.displayParts); + displayParts.push(ts.lineBreakPart()); + documentationFromAlias = resolvedInfo.documentation; + tagsFromAlias = resolvedInfo.tags; + } + } + } + switch (symbol.declarations[0].kind) { + case 247 /* NamespaceExportDeclaration */: + displayParts.push(ts.keywordPart(85 /* ExportKeyword */)); + displayParts.push(ts.spacePart()); + displayParts.push(ts.keywordPart(131 /* NamespaceKeyword */)); + break; + case 254 /* ExportAssignment */: + displayParts.push(ts.keywordPart(85 /* ExportKeyword */)); + displayParts.push(ts.spacePart()); + displayParts.push(ts.keywordPart(symbol.declarations[0].isExportEquals ? 59 /* EqualsToken */ : 80 /* DefaultKeyword */)); + break; + case 257 /* ExportSpecifier */: + displayParts.push(ts.keywordPart(85 /* ExportKeyword */)); + break; + default: + displayParts.push(ts.keywordPart(92 /* ImportKeyword */)); + } + displayParts.push(ts.spacePart()); + addFullSymbolName(symbol); + ts.forEach(symbol.declarations, function (declaration) { + if (declaration.kind === 248 /* ImportEqualsDeclaration */) { + var importEqualsDeclaration = declaration; + if (ts.isExternalModuleImportEqualsDeclaration(importEqualsDeclaration)) { + displayParts.push(ts.spacePart()); + displayParts.push(ts.operatorPart(59 /* EqualsToken */)); + displayParts.push(ts.spacePart()); + displayParts.push(ts.keywordPart(134 /* RequireKeyword */)); + displayParts.push(ts.punctuationPart(20 /* OpenParenToken */)); + displayParts.push(ts.displayPart(ts.getTextOfNode(ts.getExternalModuleImportEqualsDeclarationExpression(importEqualsDeclaration)), ts.SymbolDisplayPartKind.stringLiteral)); + displayParts.push(ts.punctuationPart(21 /* CloseParenToken */)); + } + else { + var internalAliasSymbol = typeChecker.getSymbolAtLocation(importEqualsDeclaration.moduleReference); + if (internalAliasSymbol) { + displayParts.push(ts.spacePart()); + displayParts.push(ts.operatorPart(59 /* EqualsToken */)); + displayParts.push(ts.spacePart()); + addFullSymbolName(internalAliasSymbol, enclosingDeclaration); + } + } + return true; + } + }); + } + if (!hasAddedSymbolInfo) { + if (symbolKind !== "" /* unknown */) { + if (type) { + if (isThisExpression) { + prefixNextMeaning(); + displayParts.push(ts.keywordPart(100 /* ThisKeyword */)); + } + else { + addPrefixForAnyFunctionOrVar(symbol, symbolKind); + } + // For properties, variables and local vars: show the type + if (symbolKind === "property" /* memberVariableElement */ || + symbolKind === "JSX attribute" /* jsxAttribute */ || + symbolFlags & 3 /* Variable */ || + symbolKind === "local var" /* localVariableElement */ || + isThisExpression) { + displayParts.push(ts.punctuationPart(57 /* ColonToken */)); + displayParts.push(ts.spacePart()); + // If the type is type parameter, format it specially + if (type.symbol && type.symbol.flags & 262144 /* TypeParameter */) { + var typeParameterParts = ts.mapToDisplayParts(function (writer) { + var param = typeChecker.typeParameterToDeclaration(type, enclosingDeclaration); + getPrinter().writeNode(4 /* Unspecified */, param, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosingDeclaration)), writer); + }); + ts.addRange(displayParts, typeParameterParts); + } + else { + ts.addRange(displayParts, ts.typeToDisplayParts(typeChecker, type, enclosingDeclaration)); + } + } + else if (symbolFlags & 16 /* Function */ || + symbolFlags & 8192 /* Method */ || + symbolFlags & 16384 /* Constructor */ || + symbolFlags & 131072 /* Signature */ || + symbolFlags & 98304 /* Accessor */ || + symbolKind === "method" /* memberFunctionElement */) { + var allSignatures = type.getNonNullableType().getCallSignatures(); + if (allSignatures.length) { + addSignatureDisplayParts(allSignatures[0], allSignatures); + } + } + } + } + else { + symbolKind = getSymbolKind(typeChecker, symbol, location); + } + } + if (!documentation) { + documentation = symbol.getDocumentationComment(typeChecker); + tags = symbol.getJsDocTags(); + if (documentation.length === 0 && symbolFlags & 4 /* Property */) { + // For some special property access expressions like `exports.foo = foo` or `module.exports.foo = foo` + // there documentation comments might be attached to the right hand side symbol of their declarations. + // The pattern of such special property access is that the parent symbol is the symbol of the file. + if (symbol.parent && ts.forEach(symbol.parent.declarations, function (declaration) { return declaration.kind === 279 /* SourceFile */; })) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (!declaration.parent || declaration.parent.kind !== 204 /* BinaryExpression */) { + continue; + } + var rhsSymbol = typeChecker.getSymbolAtLocation(declaration.parent.right); + if (!rhsSymbol) { + continue; + } + documentation = rhsSymbol.getDocumentationComment(typeChecker); + tags = rhsSymbol.getJsDocTags(); + if (documentation.length > 0) { + break; + } + } + } + } + } + if (documentation.length === 0 && documentationFromAlias) { + documentation = documentationFromAlias; + } + if (tags.length === 0 && tagsFromAlias) { + tags = tagsFromAlias; + } + return { displayParts: displayParts, documentation: documentation, symbolKind: symbolKind, tags: tags.length === 0 ? undefined : tags }; + function getPrinter() { + if (!printer) { + printer = ts.createPrinter({ removeComments: true }); + } + return printer; + } + function prefixNextMeaning() { + if (displayParts.length) { + displayParts.push(ts.lineBreakPart()); + } + addAliasPrefixIfNecessary(); + } + function addAliasPrefixIfNecessary() { + if (alias) { + pushSymbolKind("alias" /* alias */); + displayParts.push(ts.spacePart()); + } + } + function addInPrefix() { + displayParts.push(ts.spacePart()); + displayParts.push(ts.keywordPart(93 /* InKeyword */)); + displayParts.push(ts.spacePart()); + } + function addFullSymbolName(symbolToDisplay, enclosingDeclaration) { + if (alias && symbolToDisplay === symbol) { + symbolToDisplay = alias; + } + var fullSymbolDisplayParts = ts.symbolToDisplayParts(typeChecker, symbolToDisplay, enclosingDeclaration || sourceFile, /*meaning*/ undefined, 1 /* WriteTypeParametersOrArguments */ | 2 /* UseOnlyExternalAliasing */ | 4 /* AllowAnyNodeKind */); + ts.addRange(displayParts, fullSymbolDisplayParts); + if (symbol.flags & 16777216 /* Optional */) { + displayParts.push(ts.punctuationPart(56 /* QuestionToken */)); + } + } + function addPrefixForAnyFunctionOrVar(symbol, symbolKind) { + prefixNextMeaning(); + if (symbolKind) { + pushSymbolKind(symbolKind); + if (symbol && !ts.some(symbol.declarations, function (d) { return ts.isArrowFunction(d) || (ts.isFunctionExpression(d) || ts.isClassExpression(d)) && !d.name; })) { + displayParts.push(ts.spacePart()); + addFullSymbolName(symbol); + } + } + } + function pushSymbolKind(symbolKind) { + switch (symbolKind) { + case "var" /* variableElement */: + case "function" /* functionElement */: + case "let" /* letElement */: + case "const" /* constElement */: + case "constructor" /* constructorImplementationElement */: + displayParts.push(ts.textOrKeywordPart(symbolKind)); + return; + default: + displayParts.push(ts.punctuationPart(20 /* OpenParenToken */)); + displayParts.push(ts.textOrKeywordPart(symbolKind)); + displayParts.push(ts.punctuationPart(21 /* CloseParenToken */)); + return; + } + } + function addSignatureDisplayParts(signature, allSignatures, flags) { + if (flags === void 0) { flags = 0 /* None */; } + ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, enclosingDeclaration, flags | 32 /* WriteTypeArgumentsOfSignature */)); + if (allSignatures.length > 1) { + displayParts.push(ts.spacePart()); + displayParts.push(ts.punctuationPart(20 /* OpenParenToken */)); + displayParts.push(ts.operatorPart(38 /* PlusToken */)); + displayParts.push(ts.displayPart((allSignatures.length - 1).toString(), ts.SymbolDisplayPartKind.numericLiteral)); + displayParts.push(ts.spacePart()); + displayParts.push(ts.textPart(allSignatures.length === 2 ? "overload" : "overloads")); + displayParts.push(ts.punctuationPart(21 /* CloseParenToken */)); + } + var docComment = signature.getDocumentationComment(typeChecker); + documentation = docComment.length === 0 ? undefined : docComment; + tags = signature.getJsDocTags(); + } + function writeTypeParametersOfSymbol(symbol, enclosingDeclaration) { + var typeParameterParts = ts.mapToDisplayParts(function (writer) { + var params = typeChecker.symbolToTypeParameterDeclarations(symbol, enclosingDeclaration); + getPrinter().writeList(53776 /* TypeParameters */, params, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosingDeclaration)), writer); + }); + ts.addRange(displayParts, typeParameterParts); + } + } + SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind = getSymbolDisplayPartsDocumentationAndSymbolKind; + function isLocalVariableOrFunction(symbol) { + if (symbol.parent) { + return false; // This is exported symbol + } + return ts.forEach(symbol.declarations, function (declaration) { + // Function expressions are local + if (declaration.kind === 196 /* FunctionExpression */) { + return true; + } + if (declaration.kind !== 237 /* VariableDeclaration */ && declaration.kind !== 239 /* FunctionDeclaration */) { + return false; + } + // If the parent is not sourceFile or module block it is local variable + for (var parent = declaration.parent; !ts.isFunctionBlock(parent); parent = parent.parent) { + // Reached source file or module block + if (parent.kind === 279 /* SourceFile */ || parent.kind === 245 /* ModuleBlock */) { + return false; + } + } + // parent is in function block + return true; + }); + } + })(SymbolDisplay = ts.SymbolDisplay || (ts.SymbolDisplay = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + /* + * This function will compile source text from 'input' argument using specified compiler options. + * If not options are provided - it will use a set of default compiler options. + * Extra compiler options that will unconditionally be used by this function are: + * - isolatedModules = true + * - allowNonTsExtensions = true + * - noLib = true + * - noResolve = true + */ + function transpileModule(input, transpileOptions) { + var diagnostics = []; + var options = transpileOptions.compilerOptions ? fixupCompilerOptions(transpileOptions.compilerOptions, diagnostics) : ts.getDefaultCompilerOptions(); + options.isolatedModules = true; + // transpileModule does not write anything to disk so there is no need to verify that there are no conflicts between input and output paths. + options.suppressOutputPathCheck = true; + // Filename can be non-ts file. + options.allowNonTsExtensions = true; + // We are not returning a sourceFile for lib file when asked by the program, + // so pass --noLib to avoid reporting a file not found error. + options.noLib = true; + // Clear out other settings that would not be used in transpiling this module + options.lib = undefined; + options.types = undefined; + options.noEmit = undefined; + options.noEmitOnError = undefined; + options.paths = undefined; + options.rootDirs = undefined; + options.declaration = undefined; + options.composite = undefined; + options.declarationDir = undefined; + options.out = undefined; + options.outFile = undefined; + // We are not doing a full typecheck, we are not resolving the whole context, + // so pass --noResolve to avoid reporting missing file errors. + options.noResolve = true; + // if jsx is specified then treat file as .tsx + var inputFileName = transpileOptions.fileName || (options.jsx ? "module.tsx" : "module.ts"); + var sourceFile = ts.createSourceFile(inputFileName, input, options.target); // TODO: GH#18217 + if (transpileOptions.moduleName) { + sourceFile.moduleName = transpileOptions.moduleName; + } + if (transpileOptions.renamedDependencies) { + sourceFile.renamedDependencies = ts.createMapFromTemplate(transpileOptions.renamedDependencies); + } + var newLine = ts.getNewLineCharacter(options); + // Output + var outputText; + var sourceMapText; + // Create a compilerHost object to allow the compiler to read and write files + var compilerHost = { + getSourceFile: function (fileName) { return fileName === ts.normalizePath(inputFileName) ? sourceFile : undefined; }, + writeFile: function (name, text) { + if (ts.fileExtensionIs(name, ".map")) { + ts.Debug.assertEqual(sourceMapText, undefined, "Unexpected multiple source map outputs, file:", name); + sourceMapText = text; + } + else { + ts.Debug.assertEqual(outputText, undefined, "Unexpected multiple outputs, file:", name); + outputText = text; + } + }, + getDefaultLibFileName: function () { return "lib.d.ts"; }, + useCaseSensitiveFileNames: function () { return false; }, + getCanonicalFileName: function (fileName) { return fileName; }, + getCurrentDirectory: function () { return ""; }, + getNewLine: function () { return newLine; }, + fileExists: function (fileName) { return fileName === inputFileName; }, + readFile: function () { return ""; }, + directoryExists: function () { return true; }, + getDirectories: function () { return []; } + }; + var program = ts.createProgram([inputFileName], options, compilerHost); + if (transpileOptions.reportDiagnostics) { + ts.addRange(/*to*/ diagnostics, /*from*/ program.getSyntacticDiagnostics(sourceFile)); + ts.addRange(/*to*/ diagnostics, /*from*/ program.getOptionsDiagnostics()); + } + // Emit + program.emit(/*targetSourceFile*/ undefined, /*writeFile*/ undefined, /*cancellationToken*/ undefined, /*emitOnlyDtsFiles*/ undefined, transpileOptions.transformers); + if (outputText === undefined) + return ts.Debug.fail("Output generation failed"); + return { outputText: outputText, diagnostics: diagnostics, sourceMapText: sourceMapText }; + } + ts.transpileModule = transpileModule; + /* + * This is a shortcut function for transpileModule - it accepts transpileOptions as parameters and returns only outputText part of the result. + */ + function transpile(input, compilerOptions, fileName, diagnostics, moduleName) { + var output = transpileModule(input, { compilerOptions: compilerOptions, fileName: fileName, reportDiagnostics: !!diagnostics, moduleName: moduleName }); + // addRange correctly handles cases when wither 'from' or 'to' argument is missing + ts.addRange(diagnostics, output.diagnostics); + return output.outputText; + } + ts.transpile = transpile; + var commandLineOptionsStringToEnum; + /** JS users may pass in string values for enum compiler options (such as ModuleKind), so convert. */ + /*@internal*/ + function fixupCompilerOptions(options, diagnostics) { + // Lazily create this value to fix module loading errors. + commandLineOptionsStringToEnum = commandLineOptionsStringToEnum || ts.filter(ts.optionDeclarations, function (o) { + return typeof o.type === "object" && !ts.forEachEntry(o.type, function (v) { return typeof v !== "number"; }); + }); + options = ts.cloneCompilerOptions(options); + var _loop_16 = function (opt) { + if (!ts.hasProperty(options, opt.name)) { + return "continue"; + } + var value = options[opt.name]; + // Value should be a key of opt.type + if (ts.isString(value)) { + // If value is not a string, this will fail + options[opt.name] = ts.parseCustomTypeOption(opt, value, diagnostics); + } + else { + if (!ts.forEachEntry(opt.type, function (v) { return v === value; })) { + // Supplied value isn't a valid enum value. + diagnostics.push(ts.createCompilerDiagnosticForInvalidCustomType(opt)); + } + } + }; + for (var _i = 0, commandLineOptionsStringToEnum_1 = commandLineOptionsStringToEnum; _i < commandLineOptionsStringToEnum_1.length; _i++) { + var opt = commandLineOptionsStringToEnum_1[_i]; + _loop_16(opt); + } + return options; + } + ts.fixupCompilerOptions = fixupCompilerOptions; +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var formatting; + (function (formatting) { + var FormattingRequestKind; + (function (FormattingRequestKind) { + FormattingRequestKind[FormattingRequestKind["FormatDocument"] = 0] = "FormatDocument"; + FormattingRequestKind[FormattingRequestKind["FormatSelection"] = 1] = "FormatSelection"; + FormattingRequestKind[FormattingRequestKind["FormatOnEnter"] = 2] = "FormatOnEnter"; + FormattingRequestKind[FormattingRequestKind["FormatOnSemicolon"] = 3] = "FormatOnSemicolon"; + FormattingRequestKind[FormattingRequestKind["FormatOnOpeningCurlyBrace"] = 4] = "FormatOnOpeningCurlyBrace"; + FormattingRequestKind[FormattingRequestKind["FormatOnClosingCurlyBrace"] = 5] = "FormatOnClosingCurlyBrace"; + })(FormattingRequestKind = formatting.FormattingRequestKind || (formatting.FormattingRequestKind = {})); + var FormattingContext = /** @class */ (function () { + function FormattingContext(sourceFile, formattingRequestKind, options) { + this.sourceFile = sourceFile; + this.formattingRequestKind = formattingRequestKind; + this.options = options; + } + FormattingContext.prototype.updateContext = function (currentRange, currentTokenParent, nextRange, nextTokenParent, commonParent) { + this.currentTokenSpan = ts.Debug.assertDefined(currentRange); + this.currentTokenParent = ts.Debug.assertDefined(currentTokenParent); + this.nextTokenSpan = ts.Debug.assertDefined(nextRange); + this.nextTokenParent = ts.Debug.assertDefined(nextTokenParent); + this.contextNode = ts.Debug.assertDefined(commonParent); + // drop cached results + this.contextNodeAllOnSameLine = undefined; + this.nextNodeAllOnSameLine = undefined; + this.tokensAreOnSameLine = undefined; + this.contextNodeBlockIsOnOneLine = undefined; + this.nextNodeBlockIsOnOneLine = undefined; + }; + FormattingContext.prototype.ContextNodeAllOnSameLine = function () { + if (this.contextNodeAllOnSameLine === undefined) { + this.contextNodeAllOnSameLine = this.NodeIsOnOneLine(this.contextNode); + } + return this.contextNodeAllOnSameLine; + }; + FormattingContext.prototype.NextNodeAllOnSameLine = function () { + if (this.nextNodeAllOnSameLine === undefined) { + this.nextNodeAllOnSameLine = this.NodeIsOnOneLine(this.nextTokenParent); + } + return this.nextNodeAllOnSameLine; + }; + FormattingContext.prototype.TokensAreOnSameLine = function () { + if (this.tokensAreOnSameLine === undefined) { + var startLine = this.sourceFile.getLineAndCharacterOfPosition(this.currentTokenSpan.pos).line; + var endLine = this.sourceFile.getLineAndCharacterOfPosition(this.nextTokenSpan.pos).line; + this.tokensAreOnSameLine = (startLine === endLine); + } + return this.tokensAreOnSameLine; + }; + FormattingContext.prototype.ContextNodeBlockIsOnOneLine = function () { + if (this.contextNodeBlockIsOnOneLine === undefined) { + this.contextNodeBlockIsOnOneLine = this.BlockIsOnOneLine(this.contextNode); + } + return this.contextNodeBlockIsOnOneLine; + }; + FormattingContext.prototype.NextNodeBlockIsOnOneLine = function () { + if (this.nextNodeBlockIsOnOneLine === undefined) { + this.nextNodeBlockIsOnOneLine = this.BlockIsOnOneLine(this.nextTokenParent); + } + return this.nextNodeBlockIsOnOneLine; + }; + FormattingContext.prototype.NodeIsOnOneLine = function (node) { + var startLine = this.sourceFile.getLineAndCharacterOfPosition(node.getStart(this.sourceFile)).line; + var endLine = this.sourceFile.getLineAndCharacterOfPosition(node.getEnd()).line; + return startLine === endLine; + }; + FormattingContext.prototype.BlockIsOnOneLine = function (node) { + var openBrace = ts.findChildOfKind(node, 18 /* OpenBraceToken */, this.sourceFile); + var closeBrace = ts.findChildOfKind(node, 19 /* CloseBraceToken */, this.sourceFile); + if (openBrace && closeBrace) { + var startLine = this.sourceFile.getLineAndCharacterOfPosition(openBrace.getEnd()).line; + var endLine = this.sourceFile.getLineAndCharacterOfPosition(closeBrace.getStart(this.sourceFile)).line; + return startLine === endLine; + } + return false; + }; + return FormattingContext; + }()); + formatting.FormattingContext = FormattingContext; + })(formatting = ts.formatting || (ts.formatting = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var formatting; + (function (formatting) { + var standardScanner = ts.createScanner(6 /* Latest */, /*skipTrivia*/ false, 0 /* Standard */); + var jsxScanner = ts.createScanner(6 /* Latest */, /*skipTrivia*/ false, 1 /* JSX */); + var ScanAction; + (function (ScanAction) { + ScanAction[ScanAction["Scan"] = 0] = "Scan"; + ScanAction[ScanAction["RescanGreaterThanToken"] = 1] = "RescanGreaterThanToken"; + ScanAction[ScanAction["RescanSlashToken"] = 2] = "RescanSlashToken"; + ScanAction[ScanAction["RescanTemplateToken"] = 3] = "RescanTemplateToken"; + ScanAction[ScanAction["RescanJsxIdentifier"] = 4] = "RescanJsxIdentifier"; + ScanAction[ScanAction["RescanJsxText"] = 5] = "RescanJsxText"; + })(ScanAction || (ScanAction = {})); + function getFormattingScanner(text, languageVariant, startPos, endPos, cb) { + var scanner = languageVariant === 1 /* JSX */ ? jsxScanner : standardScanner; + scanner.setText(text); + scanner.setTextPos(startPos); + var wasNewLine = true; + var leadingTrivia; + var trailingTrivia; + var savedPos; + var lastScanAction; + var lastTokenInfo; + var res = cb({ + advance: advance, + readTokenInfo: readTokenInfo, + isOnToken: isOnToken, + getCurrentLeadingTrivia: function () { return leadingTrivia; }, + lastTrailingTriviaWasNewLine: function () { return wasNewLine; }, + skipToEndOf: skipToEndOf, + }); + lastTokenInfo = undefined; + scanner.setText(undefined); + return res; + function advance() { + lastTokenInfo = undefined; + var isStarted = scanner.getStartPos() !== startPos; + if (isStarted) { + wasNewLine = !!trailingTrivia && ts.last(trailingTrivia).kind === 4 /* NewLineTrivia */; + } + else { + scanner.scan(); + } + leadingTrivia = undefined; + trailingTrivia = undefined; + var pos = scanner.getStartPos(); + // Read leading trivia and token + while (pos < endPos) { + var t = scanner.getToken(); + if (!ts.isTrivia(t)) { + break; + } + // consume leading trivia + scanner.scan(); + var item = { + pos: pos, + end: scanner.getStartPos(), + kind: t + }; + pos = scanner.getStartPos(); + leadingTrivia = ts.append(leadingTrivia, item); + } + savedPos = scanner.getStartPos(); + } + function shouldRescanGreaterThanToken(node) { + switch (node.kind) { + case 32 /* GreaterThanEqualsToken */: + case 67 /* GreaterThanGreaterThanEqualsToken */: + case 68 /* GreaterThanGreaterThanGreaterThanEqualsToken */: + case 48 /* GreaterThanGreaterThanGreaterThanToken */: + case 47 /* GreaterThanGreaterThanToken */: + return true; + } + return false; + } + function shouldRescanJsxIdentifier(node) { + if (node.parent) { + switch (node.parent.kind) { + case 267 /* JsxAttribute */: + case 262 /* JsxOpeningElement */: + case 263 /* JsxClosingElement */: + case 261 /* JsxSelfClosingElement */: + // May parse an identifier like `module-layout`; that will be scanned as a keyword at first, but we should parse the whole thing to get an identifier. + return ts.isKeyword(node.kind) || node.kind === 72 /* Identifier */; + } + } + return false; + } + function shouldRescanJsxText(node) { + return node.kind === 11 /* JsxText */; + } + function shouldRescanSlashToken(container) { + return container.kind === 13 /* RegularExpressionLiteral */; + } + function shouldRescanTemplateToken(container) { + return container.kind === 16 /* TemplateMiddle */ || + container.kind === 17 /* TemplateTail */; + } + function startsWithSlashToken(t) { + return t === 42 /* SlashToken */ || t === 64 /* SlashEqualsToken */; + } + function readTokenInfo(n) { + ts.Debug.assert(isOnToken()); + // normally scanner returns the smallest available token + // check the kind of context node to determine if scanner should have more greedy behavior and consume more text. + var expectedScanAction = shouldRescanGreaterThanToken(n) + ? 1 /* RescanGreaterThanToken */ + : shouldRescanSlashToken(n) + ? 2 /* RescanSlashToken */ + : shouldRescanTemplateToken(n) + ? 3 /* RescanTemplateToken */ + : shouldRescanJsxIdentifier(n) + ? 4 /* RescanJsxIdentifier */ + : shouldRescanJsxText(n) + ? 5 /* RescanJsxText */ + : 0 /* Scan */; + if (lastTokenInfo && expectedScanAction === lastScanAction) { + // readTokenInfo was called before with the same expected scan action. + // No need to re-scan text, return existing 'lastTokenInfo' + // it is ok to call fixTokenKind here since it does not affect + // what portion of text is consumed. In contrast rescanning can change it, + // i.e. for '>=' when originally scanner eats just one character + // and rescanning forces it to consume more. + return fixTokenKind(lastTokenInfo, n); + } + if (scanner.getStartPos() !== savedPos) { + ts.Debug.assert(lastTokenInfo !== undefined); + // readTokenInfo was called before but scan action differs - rescan text + scanner.setTextPos(savedPos); + scanner.scan(); + } + var currentToken = getNextToken(n, expectedScanAction); + var token = { + pos: scanner.getStartPos(), + end: scanner.getTextPos(), + kind: currentToken + }; + // consume trailing trivia + if (trailingTrivia) { + trailingTrivia = undefined; + } + while (scanner.getStartPos() < endPos) { + currentToken = scanner.scan(); + if (!ts.isTrivia(currentToken)) { + break; + } + var trivia = { + pos: scanner.getStartPos(), + end: scanner.getTextPos(), + kind: currentToken + }; + if (!trailingTrivia) { + trailingTrivia = []; + } + trailingTrivia.push(trivia); + if (currentToken === 4 /* NewLineTrivia */) { + // move past new line + scanner.scan(); + break; + } + } + lastTokenInfo = { leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia, token: token }; + return fixTokenKind(lastTokenInfo, n); + } + function getNextToken(n, expectedScanAction) { + var token = scanner.getToken(); + lastScanAction = 0 /* Scan */; + switch (expectedScanAction) { + case 1 /* RescanGreaterThanToken */: + if (token === 30 /* GreaterThanToken */) { + lastScanAction = 1 /* RescanGreaterThanToken */; + var newToken = scanner.reScanGreaterToken(); + ts.Debug.assert(n.kind === newToken); + return newToken; + } + break; + case 2 /* RescanSlashToken */: + if (startsWithSlashToken(token)) { + lastScanAction = 2 /* RescanSlashToken */; + var newToken = scanner.reScanSlashToken(); + ts.Debug.assert(n.kind === newToken); + return newToken; + } + break; + case 3 /* RescanTemplateToken */: + if (token === 19 /* CloseBraceToken */) { + lastScanAction = 3 /* RescanTemplateToken */; + return scanner.reScanTemplateToken(); + } + break; + case 4 /* RescanJsxIdentifier */: + lastScanAction = 4 /* RescanJsxIdentifier */; + return scanner.scanJsxIdentifier(); + case 5 /* RescanJsxText */: + lastScanAction = 5 /* RescanJsxText */; + return scanner.reScanJsxToken(); + case 0 /* Scan */: + break; + default: + ts.Debug.assertNever(expectedScanAction); + } + return token; + } + function isOnToken() { + var current = lastTokenInfo ? lastTokenInfo.token.kind : scanner.getToken(); + var startPos = lastTokenInfo ? lastTokenInfo.token.pos : scanner.getStartPos(); + return startPos < endPos && current !== 1 /* EndOfFileToken */ && !ts.isTrivia(current); + } + // when containing node in the tree is token + // but its kind differs from the kind that was returned by the scanner, + // then kind needs to be fixed. This might happen in cases + // when parser interprets token differently, i.e keyword treated as identifier + function fixTokenKind(tokenInfo, container) { + if (ts.isToken(container) && tokenInfo.token.kind !== container.kind) { + tokenInfo.token.kind = container.kind; + } + return tokenInfo; + } + function skipToEndOf(node) { + scanner.setTextPos(node.end); + savedPos = scanner.getStartPos(); + lastScanAction = undefined; + lastTokenInfo = undefined; + wasNewLine = false; + leadingTrivia = undefined; + trailingTrivia = undefined; + } + } + formatting.getFormattingScanner = getFormattingScanner; + })(formatting = ts.formatting || (ts.formatting = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var formatting; + (function (formatting) { + formatting.anyContext = ts.emptyArray; + var RuleAction; + (function (RuleAction) { + RuleAction[RuleAction["Ignore"] = 1] = "Ignore"; + RuleAction[RuleAction["Space"] = 2] = "Space"; + RuleAction[RuleAction["NewLine"] = 4] = "NewLine"; + RuleAction[RuleAction["Delete"] = 8] = "Delete"; + })(RuleAction = formatting.RuleAction || (formatting.RuleAction = {})); + var RuleFlags; + (function (RuleFlags) { + RuleFlags[RuleFlags["None"] = 0] = "None"; + RuleFlags[RuleFlags["CanDeleteNewLines"] = 1] = "CanDeleteNewLines"; + })(RuleFlags = formatting.RuleFlags || (formatting.RuleFlags = {})); + })(formatting = ts.formatting || (ts.formatting = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var formatting; + (function (formatting) { + function getAllRules() { + var allTokens = []; + for (var token = 0 /* FirstToken */; token <= 147 /* LastToken */; token++) { + allTokens.push(token); + } + function anyTokenExcept() { + var tokens = []; + for (var _i = 0; _i < arguments.length; _i++) { + tokens[_i] = arguments[_i]; + } + return { tokens: allTokens.filter(function (t) { return !tokens.some(function (t2) { return t2 === t; }); }), isSpecific: false }; + } + var anyToken = { tokens: allTokens, isSpecific: false }; + var anyTokenIncludingMultilineComments = tokenRangeFrom(allTokens.concat([3 /* MultiLineCommentTrivia */])); + var keywords = tokenRangeFromRange(73 /* FirstKeyword */, 147 /* LastKeyword */); + var binaryOperators = tokenRangeFromRange(28 /* FirstBinaryOperator */, 71 /* LastBinaryOperator */); + var binaryKeywordOperators = [93 /* InKeyword */, 94 /* InstanceOfKeyword */, 147 /* OfKeyword */, 119 /* AsKeyword */, 128 /* IsKeyword */]; + var unaryPrefixOperators = [44 /* PlusPlusToken */, 45 /* MinusMinusToken */, 53 /* TildeToken */, 52 /* ExclamationToken */]; + var unaryPrefixExpressions = [ + 8 /* NumericLiteral */, 9 /* BigIntLiteral */, 72 /* Identifier */, 20 /* OpenParenToken */, + 22 /* OpenBracketToken */, 18 /* OpenBraceToken */, 100 /* ThisKeyword */, 95 /* NewKeyword */ + ]; + var unaryPreincrementExpressions = [72 /* Identifier */, 20 /* OpenParenToken */, 100 /* ThisKeyword */, 95 /* NewKeyword */]; + var unaryPostincrementExpressions = [72 /* Identifier */, 21 /* CloseParenToken */, 23 /* CloseBracketToken */, 95 /* NewKeyword */]; + var unaryPredecrementExpressions = [72 /* Identifier */, 20 /* OpenParenToken */, 100 /* ThisKeyword */, 95 /* NewKeyword */]; + var unaryPostdecrementExpressions = [72 /* Identifier */, 21 /* CloseParenToken */, 23 /* CloseBracketToken */, 95 /* NewKeyword */]; + var comments = [2 /* SingleLineCommentTrivia */, 3 /* MultiLineCommentTrivia */]; + var typeNames = [72 /* Identifier */].concat(ts.typeKeywords); + // Place a space before open brace in a function declaration + // TypeScript: Function can have return types, which can be made of tons of different token kinds + var functionOpenBraceLeftTokenRange = anyTokenIncludingMultilineComments; + // Place a space before open brace in a TypeScript declaration that has braces as children (class, module, enum, etc) + var typeScriptOpenBraceLeftTokenRange = tokenRangeFrom([72 /* Identifier */, 3 /* MultiLineCommentTrivia */, 76 /* ClassKeyword */, 85 /* ExportKeyword */, 92 /* ImportKeyword */]); + // Place a space before open brace in a control flow construct + var controlOpenBraceLeftTokenRange = tokenRangeFrom([21 /* CloseParenToken */, 3 /* MultiLineCommentTrivia */, 82 /* DoKeyword */, 103 /* TryKeyword */, 88 /* FinallyKeyword */, 83 /* ElseKeyword */]); + // These rules are higher in priority than user-configurable + var highPriorityCommonRules = [ + // Leave comments alone + rule("IgnoreBeforeComment", anyToken, comments, formatting.anyContext, 1 /* Ignore */), + rule("IgnoreAfterLineComment", 2 /* SingleLineCommentTrivia */, anyToken, formatting.anyContext, 1 /* Ignore */), + rule("NotSpaceBeforeColon", anyToken, 57 /* ColonToken */, [isNonJsxSameLineTokenContext, isNotBinaryOpContext, isNotTypeAnnotationContext], 8 /* Delete */), + rule("SpaceAfterColon", 57 /* ColonToken */, anyToken, [isNonJsxSameLineTokenContext, isNotBinaryOpContext], 2 /* Space */), + rule("NoSpaceBeforeQuestionMark", anyToken, 56 /* QuestionToken */, [isNonJsxSameLineTokenContext, isNotBinaryOpContext], 8 /* Delete */), + // insert space after '?' only when it is used in conditional operator + rule("SpaceAfterQuestionMarkInConditionalOperator", 56 /* QuestionToken */, anyToken, [isNonJsxSameLineTokenContext, isConditionalOperatorContext], 2 /* Space */), + // in other cases there should be no space between '?' and next token + rule("NoSpaceAfterQuestionMark", 56 /* QuestionToken */, anyToken, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceBeforeDot", anyToken, 24 /* DotToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceAfterDot", 24 /* DotToken */, anyToken, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceBetweenImportParenInImportType", 92 /* ImportKeyword */, 20 /* OpenParenToken */, [isNonJsxSameLineTokenContext, isImportTypeContext], 8 /* Delete */), + // Special handling of unary operators. + // Prefix operators generally shouldn't have a space between + // them and their target unary expression. + rule("NoSpaceAfterUnaryPrefixOperator", unaryPrefixOperators, unaryPrefixExpressions, [isNonJsxSameLineTokenContext, isNotBinaryOpContext], 8 /* Delete */), + rule("NoSpaceAfterUnaryPreincrementOperator", 44 /* PlusPlusToken */, unaryPreincrementExpressions, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceAfterUnaryPredecrementOperator", 45 /* MinusMinusToken */, unaryPredecrementExpressions, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceBeforeUnaryPostincrementOperator", unaryPostincrementExpressions, 44 /* PlusPlusToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceBeforeUnaryPostdecrementOperator", unaryPostdecrementExpressions, 45 /* MinusMinusToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + // More unary operator special-casing. + // DevDiv 181814: Be careful when removing leading whitespace + // around unary operators. Examples: + // 1 - -2 --X--> 1--2 + // a + ++b --X--> a+++b + rule("SpaceAfterPostincrementWhenFollowedByAdd", 44 /* PlusPlusToken */, 38 /* PlusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), + rule("SpaceAfterAddWhenFollowedByUnaryPlus", 38 /* PlusToken */, 38 /* PlusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), + rule("SpaceAfterAddWhenFollowedByPreincrement", 38 /* PlusToken */, 44 /* PlusPlusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), + rule("SpaceAfterPostdecrementWhenFollowedBySubtract", 45 /* MinusMinusToken */, 39 /* MinusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), + rule("SpaceAfterSubtractWhenFollowedByUnaryMinus", 39 /* MinusToken */, 39 /* MinusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), + rule("SpaceAfterSubtractWhenFollowedByPredecrement", 39 /* MinusToken */, 45 /* MinusMinusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), + rule("NoSpaceAfterCloseBrace", 19 /* CloseBraceToken */, [27 /* CommaToken */, 26 /* SemicolonToken */], [isNonJsxSameLineTokenContext], 8 /* Delete */), + // For functions and control block place } on a new line [multi-line rule] + rule("NewLineBeforeCloseBraceInBlockContext", anyTokenIncludingMultilineComments, 19 /* CloseBraceToken */, [isMultilineBlockContext], 4 /* NewLine */), + // Space/new line after }. + rule("SpaceAfterCloseBrace", 19 /* CloseBraceToken */, anyTokenExcept(21 /* CloseParenToken */), [isNonJsxSameLineTokenContext, isAfterCodeBlockContext], 2 /* Space */), + // Special case for (}, else) and (}, while) since else & while tokens are not part of the tree which makes SpaceAfterCloseBrace rule not applied + // Also should not apply to }) + rule("SpaceBetweenCloseBraceAndElse", 19 /* CloseBraceToken */, 83 /* ElseKeyword */, [isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceBetweenCloseBraceAndWhile", 19 /* CloseBraceToken */, 107 /* WhileKeyword */, [isNonJsxSameLineTokenContext], 2 /* Space */), + rule("NoSpaceBetweenEmptyBraceBrackets", 18 /* OpenBraceToken */, 19 /* CloseBraceToken */, [isNonJsxSameLineTokenContext, isObjectContext], 8 /* Delete */), + // Add a space after control dec context if the next character is an open bracket ex: 'if (false)[a, b] = [1, 2];' -> 'if (false) [a, b] = [1, 2];' + rule("SpaceAfterConditionalClosingParen", 21 /* CloseParenToken */, 22 /* OpenBracketToken */, [isControlDeclContext], 2 /* Space */), + rule("NoSpaceBetweenFunctionKeywordAndStar", 90 /* FunctionKeyword */, 40 /* AsteriskToken */, [isFunctionDeclarationOrFunctionExpressionContext], 8 /* Delete */), + rule("SpaceAfterStarInGeneratorDeclaration", 40 /* AsteriskToken */, [72 /* Identifier */, 20 /* OpenParenToken */], [isFunctionDeclarationOrFunctionExpressionContext], 2 /* Space */), + rule("SpaceAfterFunctionInFuncDecl", 90 /* FunctionKeyword */, anyToken, [isFunctionDeclContext], 2 /* Space */), + // Insert new line after { and before } in multi-line contexts. + rule("NewLineAfterOpenBraceInBlockContext", 18 /* OpenBraceToken */, anyToken, [isMultilineBlockContext], 4 /* NewLine */), + // For get/set members, we check for (identifier,identifier) since get/set don't have tokens and they are represented as just an identifier token. + // Though, we do extra check on the context to make sure we are dealing with get/set node. Example: + // get x() {} + // set x(val) {} + rule("SpaceAfterGetSetInMember", [126 /* GetKeyword */, 137 /* SetKeyword */], 72 /* Identifier */, [isFunctionDeclContext], 2 /* Space */), + rule("NoSpaceBetweenYieldKeywordAndStar", 117 /* YieldKeyword */, 40 /* AsteriskToken */, [isNonJsxSameLineTokenContext, isYieldOrYieldStarWithOperand], 8 /* Delete */), + rule("SpaceBetweenYieldOrYieldStarAndOperand", [117 /* YieldKeyword */, 40 /* AsteriskToken */], anyToken, [isNonJsxSameLineTokenContext, isYieldOrYieldStarWithOperand], 2 /* Space */), + rule("NoSpaceBetweenReturnAndSemicolon", 97 /* ReturnKeyword */, 26 /* SemicolonToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("SpaceAfterCertainKeywords", [105 /* VarKeyword */, 101 /* ThrowKeyword */, 95 /* NewKeyword */, 81 /* DeleteKeyword */, 97 /* ReturnKeyword */, 104 /* TypeOfKeyword */, 122 /* AwaitKeyword */], anyToken, [isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceAfterLetConstInVariableDeclaration", [111 /* LetKeyword */, 77 /* ConstKeyword */], anyToken, [isNonJsxSameLineTokenContext, isStartOfVariableDeclarationList], 2 /* Space */), + rule("NoSpaceBeforeOpenParenInFuncCall", anyToken, 20 /* OpenParenToken */, [isNonJsxSameLineTokenContext, isFunctionCallOrNewContext, isPreviousTokenNotComma], 8 /* Delete */), + // Special case for binary operators (that are keywords). For these we have to add a space and shouldn't follow any user options. + rule("SpaceBeforeBinaryKeywordOperator", anyToken, binaryKeywordOperators, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), + rule("SpaceAfterBinaryKeywordOperator", binaryKeywordOperators, anyToken, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), + rule("SpaceAfterVoidOperator", 106 /* VoidKeyword */, anyToken, [isNonJsxSameLineTokenContext, isVoidOpContext], 2 /* Space */), + // Async-await + rule("SpaceBetweenAsyncAndOpenParen", 121 /* AsyncKeyword */, 20 /* OpenParenToken */, [isArrowFunctionContext, isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceBetweenAsyncAndFunctionKeyword", 121 /* AsyncKeyword */, 90 /* FunctionKeyword */, [isNonJsxSameLineTokenContext], 2 /* Space */), + // Template string + rule("NoSpaceBetweenTagAndTemplateString", [72 /* Identifier */, 21 /* CloseParenToken */], [14 /* NoSubstitutionTemplateLiteral */, 15 /* TemplateHead */], [isNonJsxSameLineTokenContext], 8 /* Delete */), + // JSX opening elements + rule("SpaceBeforeJsxAttribute", anyToken, 72 /* Identifier */, [isNextTokenParentJsxAttribute, isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceBeforeSlashInJsxOpeningElement", anyToken, 42 /* SlashToken */, [isJsxSelfClosingElementContext, isNonJsxSameLineTokenContext], 2 /* Space */), + rule("NoSpaceBeforeGreaterThanTokenInJsxOpeningElement", 42 /* SlashToken */, 30 /* GreaterThanToken */, [isJsxSelfClosingElementContext, isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceBeforeEqualInJsxAttribute", anyToken, 59 /* EqualsToken */, [isJsxAttributeContext, isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceAfterEqualInJsxAttribute", 59 /* EqualsToken */, anyToken, [isJsxAttributeContext, isNonJsxSameLineTokenContext], 8 /* Delete */), + // TypeScript-specific rules + // Use of module as a function call. e.g.: import m2 = module("m2"); + rule("NoSpaceAfterModuleImport", [130 /* ModuleKeyword */, 134 /* RequireKeyword */], 20 /* OpenParenToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + // Add a space around certain TypeScript keywords + rule("SpaceAfterCertainTypeScriptKeywords", [ + 118 /* AbstractKeyword */, + 76 /* ClassKeyword */, + 125 /* DeclareKeyword */, + 80 /* DefaultKeyword */, + 84 /* EnumKeyword */, + 85 /* ExportKeyword */, + 86 /* ExtendsKeyword */, + 126 /* GetKeyword */, + 109 /* ImplementsKeyword */, + 92 /* ImportKeyword */, + 110 /* InterfaceKeyword */, + 130 /* ModuleKeyword */, + 131 /* NamespaceKeyword */, + 113 /* PrivateKeyword */, + 115 /* PublicKeyword */, + 114 /* ProtectedKeyword */, + 133 /* ReadonlyKeyword */, + 137 /* SetKeyword */, + 116 /* StaticKeyword */, + 140 /* TypeKeyword */, + 144 /* FromKeyword */, + 129 /* KeyOfKeyword */, + 127 /* InferKeyword */, + ], anyToken, [isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceBeforeCertainTypeScriptKeywords", anyToken, [86 /* ExtendsKeyword */, 109 /* ImplementsKeyword */, 144 /* FromKeyword */], [isNonJsxSameLineTokenContext], 2 /* Space */), + // Treat string literals in module names as identifiers, and add a space between the literal and the opening Brace braces, e.g.: module "m2" { + rule("SpaceAfterModuleName", 10 /* StringLiteral */, 18 /* OpenBraceToken */, [isModuleDeclContext], 2 /* Space */), + // Lambda expressions + rule("SpaceBeforeArrow", anyToken, 37 /* EqualsGreaterThanToken */, [isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceAfterArrow", 37 /* EqualsGreaterThanToken */, anyToken, [isNonJsxSameLineTokenContext], 2 /* Space */), + // Optional parameters and let args + rule("NoSpaceAfterEllipsis", 25 /* DotDotDotToken */, 72 /* Identifier */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceAfterOptionalParameters", 56 /* QuestionToken */, [21 /* CloseParenToken */, 27 /* CommaToken */], [isNonJsxSameLineTokenContext, isNotBinaryOpContext], 8 /* Delete */), + // Remove spaces in empty interface literals. e.g.: x: {} + rule("NoSpaceBetweenEmptyInterfaceBraceBrackets", 18 /* OpenBraceToken */, 19 /* CloseBraceToken */, [isNonJsxSameLineTokenContext, isObjectTypeContext], 8 /* Delete */), + // generics and type assertions + rule("NoSpaceBeforeOpenAngularBracket", typeNames, 28 /* LessThanToken */, [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext], 8 /* Delete */), + rule("NoSpaceBetweenCloseParenAndAngularBracket", 21 /* CloseParenToken */, 28 /* LessThanToken */, [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext], 8 /* Delete */), + rule("NoSpaceAfterOpenAngularBracket", 28 /* LessThanToken */, anyToken, [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext], 8 /* Delete */), + rule("NoSpaceBeforeCloseAngularBracket", anyToken, 30 /* GreaterThanToken */, [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext], 8 /* Delete */), + rule("NoSpaceAfterCloseAngularBracket", 30 /* GreaterThanToken */, [20 /* OpenParenToken */, 22 /* OpenBracketToken */, 30 /* GreaterThanToken */, 27 /* CommaToken */], [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext, isNotFunctionDeclContext /*To prevent an interference with the SpaceBeforeOpenParenInFuncDecl rule*/], 8 /* Delete */), + // decorators + rule("SpaceBeforeAt", [21 /* CloseParenToken */, 72 /* Identifier */], 58 /* AtToken */, [isNonJsxSameLineTokenContext], 2 /* Space */), + rule("NoSpaceAfterAt", 58 /* AtToken */, anyToken, [isNonJsxSameLineTokenContext], 8 /* Delete */), + // Insert space after @ in decorator + rule("SpaceAfterDecorator", anyToken, [ + 118 /* AbstractKeyword */, + 72 /* Identifier */, + 85 /* ExportKeyword */, + 80 /* DefaultKeyword */, + 76 /* ClassKeyword */, + 116 /* StaticKeyword */, + 115 /* PublicKeyword */, + 113 /* PrivateKeyword */, + 114 /* ProtectedKeyword */, + 126 /* GetKeyword */, + 137 /* SetKeyword */, + 22 /* OpenBracketToken */, + 40 /* AsteriskToken */, + ], [isEndOfDecoratorContextOnSameLine], 2 /* Space */), + rule("NoSpaceBeforeNonNullAssertionOperator", anyToken, 52 /* ExclamationToken */, [isNonJsxSameLineTokenContext, isNonNullAssertionContext], 8 /* Delete */), + rule("NoSpaceAfterNewKeywordOnConstructorSignature", 95 /* NewKeyword */, 20 /* OpenParenToken */, [isNonJsxSameLineTokenContext, isConstructorSignatureContext], 8 /* Delete */), + ]; + // These rules are applied after high priority + var userConfigurableRules = [ + // Treat constructor as an identifier in a function declaration, and remove spaces between constructor and following left parentheses + rule("SpaceAfterConstructor", 124 /* ConstructorKeyword */, 20 /* OpenParenToken */, [isOptionEnabled("insertSpaceAfterConstructor"), isNonJsxSameLineTokenContext], 2 /* Space */), + rule("NoSpaceAfterConstructor", 124 /* ConstructorKeyword */, 20 /* OpenParenToken */, [isOptionDisabledOrUndefined("insertSpaceAfterConstructor"), isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("SpaceAfterComma", 27 /* CommaToken */, anyToken, [isOptionEnabled("insertSpaceAfterCommaDelimiter"), isNonJsxSameLineTokenContext, isNonJsxElementOrFragmentContext, isNextTokenNotCloseBracket], 2 /* Space */), + rule("NoSpaceAfterComma", 27 /* CommaToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterCommaDelimiter"), isNonJsxSameLineTokenContext, isNonJsxElementOrFragmentContext], 8 /* Delete */), + // Insert space after function keyword for anonymous functions + rule("SpaceAfterAnonymousFunctionKeyword", 90 /* FunctionKeyword */, 20 /* OpenParenToken */, [isOptionEnabled("insertSpaceAfterFunctionKeywordForAnonymousFunctions"), isFunctionDeclContext], 2 /* Space */), + rule("NoSpaceAfterAnonymousFunctionKeyword", 90 /* FunctionKeyword */, 20 /* OpenParenToken */, [isOptionDisabledOrUndefined("insertSpaceAfterFunctionKeywordForAnonymousFunctions"), isFunctionDeclContext], 8 /* Delete */), + // Insert space after keywords in control flow statements + rule("SpaceAfterKeywordInControl", keywords, 20 /* OpenParenToken */, [isOptionEnabled("insertSpaceAfterKeywordsInControlFlowStatements"), isControlDeclContext], 2 /* Space */), + rule("NoSpaceAfterKeywordInControl", keywords, 20 /* OpenParenToken */, [isOptionDisabledOrUndefined("insertSpaceAfterKeywordsInControlFlowStatements"), isControlDeclContext], 8 /* Delete */), + // Insert space after opening and before closing nonempty parenthesis + rule("SpaceAfterOpenParen", 20 /* OpenParenToken */, anyToken, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceBeforeCloseParen", anyToken, 21 /* CloseParenToken */, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceBetweenOpenParens", 20 /* OpenParenToken */, 20 /* OpenParenToken */, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext], 2 /* Space */), + rule("NoSpaceBetweenParens", 20 /* OpenParenToken */, 21 /* CloseParenToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceAfterOpenParen", 20 /* OpenParenToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceBeforeCloseParen", anyToken, 21 /* CloseParenToken */, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext], 8 /* Delete */), + // Insert space after opening and before closing nonempty brackets + rule("SpaceAfterOpenBracket", 22 /* OpenBracketToken */, anyToken, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceBeforeCloseBracket", anyToken, 23 /* CloseBracketToken */, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), isNonJsxSameLineTokenContext], 2 /* Space */), + rule("NoSpaceBetweenBrackets", 22 /* OpenBracketToken */, 23 /* CloseBracketToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceAfterOpenBracket", 22 /* OpenBracketToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceBeforeCloseBracket", anyToken, 23 /* CloseBracketToken */, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), isNonJsxSameLineTokenContext], 8 /* Delete */), + // Insert a space after { and before } in single-line contexts, but remove space from empty object literals {}. + rule("SpaceAfterOpenBrace", 18 /* OpenBraceToken */, anyToken, [isOptionEnabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), isBraceWrappedContext], 2 /* Space */), + rule("SpaceBeforeCloseBrace", anyToken, 19 /* CloseBraceToken */, [isOptionEnabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), isBraceWrappedContext], 2 /* Space */), + rule("NoSpaceBetweenEmptyBraceBrackets", 18 /* OpenBraceToken */, 19 /* CloseBraceToken */, [isNonJsxSameLineTokenContext, isObjectContext], 8 /* Delete */), + rule("NoSpaceAfterOpenBrace", 18 /* OpenBraceToken */, anyToken, [isOptionDisabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceBeforeCloseBrace", anyToken, 19 /* CloseBraceToken */, [isOptionDisabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), isNonJsxSameLineTokenContext], 8 /* Delete */), + // Insert space after opening and before closing template string braces + rule("SpaceAfterTemplateHeadAndMiddle", [15 /* TemplateHead */, 16 /* TemplateMiddle */], anyToken, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceBeforeTemplateMiddleAndTail", anyToken, [16 /* TemplateMiddle */, 17 /* TemplateTail */], [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), isNonJsxSameLineTokenContext], 2 /* Space */), + rule("NoSpaceAfterTemplateHeadAndMiddle", [15 /* TemplateHead */, 16 /* TemplateMiddle */], anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceBeforeTemplateMiddleAndTail", anyToken, [16 /* TemplateMiddle */, 17 /* TemplateTail */], [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), isNonJsxSameLineTokenContext], 8 /* Delete */), + // No space after { and before } in JSX expression + rule("SpaceAfterOpenBraceInJsxExpression", 18 /* OpenBraceToken */, anyToken, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), isNonJsxSameLineTokenContext, isJsxExpressionContext], 2 /* Space */), + rule("SpaceBeforeCloseBraceInJsxExpression", anyToken, 19 /* CloseBraceToken */, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), isNonJsxSameLineTokenContext, isJsxExpressionContext], 2 /* Space */), + rule("NoSpaceAfterOpenBraceInJsxExpression", 18 /* OpenBraceToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), isNonJsxSameLineTokenContext, isJsxExpressionContext], 8 /* Delete */), + rule("NoSpaceBeforeCloseBraceInJsxExpression", anyToken, 19 /* CloseBraceToken */, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), isNonJsxSameLineTokenContext, isJsxExpressionContext], 8 /* Delete */), + // Insert space after semicolon in for statement + rule("SpaceAfterSemicolonInFor", 26 /* SemicolonToken */, anyToken, [isOptionEnabled("insertSpaceAfterSemicolonInForStatements"), isNonJsxSameLineTokenContext, isForContext], 2 /* Space */), + rule("NoSpaceAfterSemicolonInFor", 26 /* SemicolonToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterSemicolonInForStatements"), isNonJsxSameLineTokenContext, isForContext], 8 /* Delete */), + // Insert space before and after binary operators + rule("SpaceBeforeBinaryOperator", anyToken, binaryOperators, [isOptionEnabled("insertSpaceBeforeAndAfterBinaryOperators"), isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), + rule("SpaceAfterBinaryOperator", binaryOperators, anyToken, [isOptionEnabled("insertSpaceBeforeAndAfterBinaryOperators"), isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), + rule("NoSpaceBeforeBinaryOperator", anyToken, binaryOperators, [isOptionDisabledOrUndefined("insertSpaceBeforeAndAfterBinaryOperators"), isNonJsxSameLineTokenContext, isBinaryOpContext], 8 /* Delete */), + rule("NoSpaceAfterBinaryOperator", binaryOperators, anyToken, [isOptionDisabledOrUndefined("insertSpaceBeforeAndAfterBinaryOperators"), isNonJsxSameLineTokenContext, isBinaryOpContext], 8 /* Delete */), + rule("SpaceBeforeOpenParenInFuncDecl", anyToken, 20 /* OpenParenToken */, [isOptionEnabled("insertSpaceBeforeFunctionParenthesis"), isNonJsxSameLineTokenContext, isFunctionDeclContext], 2 /* Space */), + rule("NoSpaceBeforeOpenParenInFuncDecl", anyToken, 20 /* OpenParenToken */, [isOptionDisabledOrUndefined("insertSpaceBeforeFunctionParenthesis"), isNonJsxSameLineTokenContext, isFunctionDeclContext], 8 /* Delete */), + // Open Brace braces after control block + rule("NewLineBeforeOpenBraceInControl", controlOpenBraceLeftTokenRange, 18 /* OpenBraceToken */, [isOptionEnabled("placeOpenBraceOnNewLineForControlBlocks"), isControlDeclContext, isBeforeMultilineBlockContext], 4 /* NewLine */, 1 /* CanDeleteNewLines */), + // Open Brace braces after function + // TypeScript: Function can have return types, which can be made of tons of different token kinds + rule("NewLineBeforeOpenBraceInFunction", functionOpenBraceLeftTokenRange, 18 /* OpenBraceToken */, [isOptionEnabled("placeOpenBraceOnNewLineForFunctions"), isFunctionDeclContext, isBeforeMultilineBlockContext], 4 /* NewLine */, 1 /* CanDeleteNewLines */), + // Open Brace braces after TypeScript module/class/interface + rule("NewLineBeforeOpenBraceInTypeScriptDeclWithBlock", typeScriptOpenBraceLeftTokenRange, 18 /* OpenBraceToken */, [isOptionEnabled("placeOpenBraceOnNewLineForFunctions"), isTypeScriptDeclWithBlockContext, isBeforeMultilineBlockContext], 4 /* NewLine */, 1 /* CanDeleteNewLines */), + rule("SpaceAfterTypeAssertion", 30 /* GreaterThanToken */, anyToken, [isOptionEnabled("insertSpaceAfterTypeAssertion"), isNonJsxSameLineTokenContext, isTypeAssertionContext], 2 /* Space */), + rule("NoSpaceAfterTypeAssertion", 30 /* GreaterThanToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterTypeAssertion"), isNonJsxSameLineTokenContext, isTypeAssertionContext], 8 /* Delete */), + rule("SpaceBeforeTypeAnnotation", anyToken, 57 /* ColonToken */, [isOptionEnabled("insertSpaceBeforeTypeAnnotation"), isNonJsxSameLineTokenContext, isTypeAnnotationContext], 2 /* Space */), + rule("NoSpaceBeforeTypeAnnotation", anyToken, 57 /* ColonToken */, [isOptionDisabledOrUndefined("insertSpaceBeforeTypeAnnotation"), isNonJsxSameLineTokenContext, isTypeAnnotationContext], 8 /* Delete */), + ]; + // These rules are lower in priority than user-configurable. Rules earlier in this list have priority over rules later in the list. + var lowPriorityCommonRules = [ + // Space after keyword but not before ; or : or ? + rule("NoSpaceBeforeSemicolon", anyToken, 26 /* SemicolonToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("SpaceBeforeOpenBraceInControl", controlOpenBraceLeftTokenRange, 18 /* OpenBraceToken */, [isOptionDisabledOrUndefinedOrTokensOnSameLine("placeOpenBraceOnNewLineForControlBlocks"), isControlDeclContext, isNotFormatOnEnter, isSameLineTokenOrBeforeBlockContext], 2 /* Space */, 1 /* CanDeleteNewLines */), + rule("SpaceBeforeOpenBraceInFunction", functionOpenBraceLeftTokenRange, 18 /* OpenBraceToken */, [isOptionDisabledOrUndefinedOrTokensOnSameLine("placeOpenBraceOnNewLineForFunctions"), isFunctionDeclContext, isBeforeBlockContext, isNotFormatOnEnter, isSameLineTokenOrBeforeBlockContext], 2 /* Space */, 1 /* CanDeleteNewLines */), + rule("SpaceBeforeOpenBraceInTypeScriptDeclWithBlock", typeScriptOpenBraceLeftTokenRange, 18 /* OpenBraceToken */, [isOptionDisabledOrUndefinedOrTokensOnSameLine("placeOpenBraceOnNewLineForFunctions"), isTypeScriptDeclWithBlockContext, isNotFormatOnEnter, isSameLineTokenOrBeforeBlockContext], 2 /* Space */, 1 /* CanDeleteNewLines */), + rule("NoSpaceBeforeComma", anyToken, 27 /* CommaToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + // No space before and after indexer `x[]` + rule("NoSpaceBeforeOpenBracket", anyTokenExcept(121 /* AsyncKeyword */, 74 /* CaseKeyword */), 22 /* OpenBracketToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceAfterCloseBracket", 23 /* CloseBracketToken */, anyToken, [isNonJsxSameLineTokenContext, isNotBeforeBlockInFunctionDeclarationContext], 8 /* Delete */), + rule("SpaceAfterSemicolon", 26 /* SemicolonToken */, anyToken, [isNonJsxSameLineTokenContext], 2 /* Space */), + // Remove extra space between for and await + rule("SpaceBetweenForAndAwaitKeyword", 89 /* ForKeyword */, 122 /* AwaitKeyword */, [isNonJsxSameLineTokenContext], 2 /* Space */), + // Add a space between statements. All keywords except (do,else,case) has open/close parens after them. + // So, we have a rule to add a space for [),Any], [do,Any], [else,Any], and [case,Any] + rule("SpaceBetweenStatements", [21 /* CloseParenToken */, 82 /* DoKeyword */, 83 /* ElseKeyword */, 74 /* CaseKeyword */], anyToken, [isNonJsxSameLineTokenContext, isNonJsxElementOrFragmentContext, isNotForContext], 2 /* Space */), + // This low-pri rule takes care of "try {" and "finally {" in case the rule SpaceBeforeOpenBraceInControl didn't execute on FormatOnEnter. + rule("SpaceAfterTryFinally", [103 /* TryKeyword */, 88 /* FinallyKeyword */], 18 /* OpenBraceToken */, [isNonJsxSameLineTokenContext], 2 /* Space */), + ]; + return highPriorityCommonRules.concat(userConfigurableRules, lowPriorityCommonRules); + } + formatting.getAllRules = getAllRules; + function rule(debugName, left, right, context, action, flags) { + if (flags === void 0) { flags = 0 /* None */; } + return { leftTokenRange: toTokenRange(left), rightTokenRange: toTokenRange(right), rule: { debugName: debugName, context: context, action: action, flags: flags } }; + } + function tokenRangeFrom(tokens) { + return { tokens: tokens, isSpecific: true }; + } + function toTokenRange(arg) { + return typeof arg === "number" ? tokenRangeFrom([arg]) : ts.isArray(arg) ? tokenRangeFrom(arg) : arg; + } + function tokenRangeFromRange(from, to, except) { + if (except === void 0) { except = []; } + var tokens = []; + for (var token = from; token <= to; token++) { + if (!ts.contains(except, token)) { + tokens.push(token); + } + } + return tokenRangeFrom(tokens); + } + /// + /// Contexts + /// + function isOptionEnabled(optionName) { + return function (context) { return context.options && context.options.hasOwnProperty(optionName) && !!context.options[optionName]; }; + } + function isOptionDisabled(optionName) { + return function (context) { return context.options && context.options.hasOwnProperty(optionName) && !context.options[optionName]; }; + } + function isOptionDisabledOrUndefined(optionName) { + return function (context) { return !context.options || !context.options.hasOwnProperty(optionName) || !context.options[optionName]; }; + } + function isOptionDisabledOrUndefinedOrTokensOnSameLine(optionName) { + return function (context) { return !context.options || !context.options.hasOwnProperty(optionName) || !context.options[optionName] || context.TokensAreOnSameLine(); }; + } + function isOptionEnabledOrUndefined(optionName) { + return function (context) { return !context.options || !context.options.hasOwnProperty(optionName) || !!context.options[optionName]; }; + } + function isForContext(context) { + return context.contextNode.kind === 225 /* ForStatement */; + } + function isNotForContext(context) { + return !isForContext(context); + } + function isBinaryOpContext(context) { + switch (context.contextNode.kind) { + case 204 /* BinaryExpression */: + case 205 /* ConditionalExpression */: + case 175 /* ConditionalType */: + case 212 /* AsExpression */: + case 257 /* ExportSpecifier */: + case 253 /* ImportSpecifier */: + case 163 /* TypePredicate */: + case 173 /* UnionType */: + case 174 /* IntersectionType */: + return true; + // equals in binding elements: function foo([[x, y] = [1, 2]]) + case 186 /* BindingElement */: + // equals in type X = ... + case 242 /* TypeAliasDeclaration */: + // equal in import a = module('a'); + case 248 /* ImportEqualsDeclaration */: + // equal in let a = 0; + case 237 /* VariableDeclaration */: + // equal in p = 0; + case 151 /* Parameter */: + case 278 /* EnumMember */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + return context.currentTokenSpan.kind === 59 /* EqualsToken */ || context.nextTokenSpan.kind === 59 /* EqualsToken */; + // "in" keyword in for (let x in []) { } + case 226 /* ForInStatement */: + // "in" keyword in [P in keyof T]: T[P] + case 150 /* TypeParameter */: + return context.currentTokenSpan.kind === 93 /* InKeyword */ || context.nextTokenSpan.kind === 93 /* InKeyword */; + // Technically, "of" is not a binary operator, but format it the same way as "in" + case 227 /* ForOfStatement */: + return context.currentTokenSpan.kind === 147 /* OfKeyword */ || context.nextTokenSpan.kind === 147 /* OfKeyword */; + } + return false; + } + function isNotBinaryOpContext(context) { + return !isBinaryOpContext(context); + } + function isNotTypeAnnotationContext(context) { + return !isTypeAnnotationContext(context); + } + function isTypeAnnotationContext(context) { + var contextKind = context.contextNode.kind; + return contextKind === 154 /* PropertyDeclaration */ || + contextKind === 153 /* PropertySignature */ || + contextKind === 151 /* Parameter */ || + contextKind === 237 /* VariableDeclaration */ || + ts.isFunctionLikeKind(contextKind); + } + function isConditionalOperatorContext(context) { + return context.contextNode.kind === 205 /* ConditionalExpression */ || + context.contextNode.kind === 175 /* ConditionalType */; + } + function isSameLineTokenOrBeforeBlockContext(context) { + return context.TokensAreOnSameLine() || isBeforeBlockContext(context); + } + function isBraceWrappedContext(context) { + return context.contextNode.kind === 184 /* ObjectBindingPattern */ || + context.contextNode.kind === 181 /* MappedType */ || + isSingleLineBlockContext(context); + } + // This check is done before an open brace in a control construct, a function, or a typescript block declaration + function isBeforeMultilineBlockContext(context) { + return isBeforeBlockContext(context) && !(context.NextNodeAllOnSameLine() || context.NextNodeBlockIsOnOneLine()); + } + function isMultilineBlockContext(context) { + return isBlockContext(context) && !(context.ContextNodeAllOnSameLine() || context.ContextNodeBlockIsOnOneLine()); + } + function isSingleLineBlockContext(context) { + return isBlockContext(context) && (context.ContextNodeAllOnSameLine() || context.ContextNodeBlockIsOnOneLine()); + } + function isBlockContext(context) { + return nodeIsBlockContext(context.contextNode); + } + function isBeforeBlockContext(context) { + return nodeIsBlockContext(context.nextTokenParent); + } + // IMPORTANT!!! This method must return true ONLY for nodes with open and close braces as immediate children + function nodeIsBlockContext(node) { + if (nodeIsTypeScriptDeclWithBlockContext(node)) { + // This means we are in a context that looks like a block to the user, but in the grammar is actually not a node (it's a class, module, enum, object type literal, etc). + return true; + } + switch (node.kind) { + case 218 /* Block */: + case 246 /* CaseBlock */: + case 188 /* ObjectLiteralExpression */: + case 245 /* ModuleBlock */: + return true; + } + return false; + } + function isFunctionDeclContext(context) { + switch (context.contextNode.kind) { + case 239 /* FunctionDeclaration */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + // case SyntaxKind.MemberFunctionDeclaration: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + // case SyntaxKind.MethodSignature: + case 160 /* CallSignature */: + case 196 /* FunctionExpression */: + case 157 /* Constructor */: + case 197 /* ArrowFunction */: + // case SyntaxKind.ConstructorDeclaration: + // case SyntaxKind.SimpleArrowFunctionExpression: + // case SyntaxKind.ParenthesizedArrowFunctionExpression: + case 241 /* InterfaceDeclaration */: // This one is not truly a function, but for formatting purposes, it acts just like one + return true; + } + return false; + } + function isNotFunctionDeclContext(context) { + return !isFunctionDeclContext(context); + } + function isFunctionDeclarationOrFunctionExpressionContext(context) { + return context.contextNode.kind === 239 /* FunctionDeclaration */ || context.contextNode.kind === 196 /* FunctionExpression */; + } + function isTypeScriptDeclWithBlockContext(context) { + return nodeIsTypeScriptDeclWithBlockContext(context.contextNode); + } + function nodeIsTypeScriptDeclWithBlockContext(node) { + switch (node.kind) { + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 241 /* InterfaceDeclaration */: + case 243 /* EnumDeclaration */: + case 168 /* TypeLiteral */: + case 244 /* ModuleDeclaration */: + case 255 /* ExportDeclaration */: + case 256 /* NamedExports */: + case 249 /* ImportDeclaration */: + case 252 /* NamedImports */: + return true; + } + return false; + } + function isAfterCodeBlockContext(context) { + switch (context.currentTokenParent.kind) { + case 240 /* ClassDeclaration */: + case 244 /* ModuleDeclaration */: + case 243 /* EnumDeclaration */: + case 274 /* CatchClause */: + case 245 /* ModuleBlock */: + case 232 /* SwitchStatement */: + return true; + case 218 /* Block */: { + var blockParent = context.currentTokenParent.parent; + // In a codefix scenario, we can't rely on parents being set. So just always return true. + if (!blockParent || blockParent.kind !== 197 /* ArrowFunction */ && blockParent.kind !== 196 /* FunctionExpression */) { + return true; + } + } + } + return false; + } + function isControlDeclContext(context) { + switch (context.contextNode.kind) { + case 222 /* IfStatement */: + case 232 /* SwitchStatement */: + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + case 224 /* WhileStatement */: + case 235 /* TryStatement */: + case 223 /* DoStatement */: + case 231 /* WithStatement */: + // TODO + // case SyntaxKind.ElseClause: + case 274 /* CatchClause */: + return true; + default: + return false; + } + } + function isObjectContext(context) { + return context.contextNode.kind === 188 /* ObjectLiteralExpression */; + } + function isFunctionCallContext(context) { + return context.contextNode.kind === 191 /* CallExpression */; + } + function isNewContext(context) { + return context.contextNode.kind === 192 /* NewExpression */; + } + function isFunctionCallOrNewContext(context) { + return isFunctionCallContext(context) || isNewContext(context); + } + function isPreviousTokenNotComma(context) { + return context.currentTokenSpan.kind !== 27 /* CommaToken */; + } + function isNextTokenNotCloseBracket(context) { + return context.nextTokenSpan.kind !== 23 /* CloseBracketToken */; + } + function isArrowFunctionContext(context) { + return context.contextNode.kind === 197 /* ArrowFunction */; + } + function isImportTypeContext(context) { + return context.contextNode.kind === 183 /* ImportType */; + } + function isNonJsxSameLineTokenContext(context) { + return context.TokensAreOnSameLine() && context.contextNode.kind !== 11 /* JsxText */; + } + function isNonJsxElementOrFragmentContext(context) { + return context.contextNode.kind !== 260 /* JsxElement */ && context.contextNode.kind !== 264 /* JsxFragment */; + } + function isJsxExpressionContext(context) { + return context.contextNode.kind === 270 /* JsxExpression */ || context.contextNode.kind === 269 /* JsxSpreadAttribute */; + } + function isNextTokenParentJsxAttribute(context) { + return context.nextTokenParent.kind === 267 /* JsxAttribute */; + } + function isJsxAttributeContext(context) { + return context.contextNode.kind === 267 /* JsxAttribute */; + } + function isJsxSelfClosingElementContext(context) { + return context.contextNode.kind === 261 /* JsxSelfClosingElement */; + } + function isNotBeforeBlockInFunctionDeclarationContext(context) { + return !isFunctionDeclContext(context) && !isBeforeBlockContext(context); + } + function isEndOfDecoratorContextOnSameLine(context) { + return context.TokensAreOnSameLine() && + !!context.contextNode.decorators && + nodeIsInDecoratorContext(context.currentTokenParent) && + !nodeIsInDecoratorContext(context.nextTokenParent); + } + function nodeIsInDecoratorContext(node) { + while (ts.isExpressionNode(node)) { + node = node.parent; + } + return node.kind === 152 /* Decorator */; + } + function isStartOfVariableDeclarationList(context) { + return context.currentTokenParent.kind === 238 /* VariableDeclarationList */ && + context.currentTokenParent.getStart(context.sourceFile) === context.currentTokenSpan.pos; + } + function isNotFormatOnEnter(context) { + return context.formattingRequestKind !== 2 /* FormatOnEnter */; + } + function isModuleDeclContext(context) { + return context.contextNode.kind === 244 /* ModuleDeclaration */; + } + function isObjectTypeContext(context) { + return context.contextNode.kind === 168 /* TypeLiteral */; // && context.contextNode.parent.kind !== SyntaxKind.InterfaceDeclaration; + } + function isConstructorSignatureContext(context) { + return context.contextNode.kind === 161 /* ConstructSignature */; + } + function isTypeArgumentOrParameterOrAssertion(token, parent) { + if (token.kind !== 28 /* LessThanToken */ && token.kind !== 30 /* GreaterThanToken */) { + return false; + } + switch (parent.kind) { + case 164 /* TypeReference */: + case 194 /* TypeAssertionExpression */: + case 242 /* TypeAliasDeclaration */: + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 241 /* InterfaceDeclaration */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 191 /* CallExpression */: + case 192 /* NewExpression */: + case 211 /* ExpressionWithTypeArguments */: + return true; + default: + return false; + } + } + function isTypeArgumentOrParameterOrAssertionContext(context) { + return isTypeArgumentOrParameterOrAssertion(context.currentTokenSpan, context.currentTokenParent) || + isTypeArgumentOrParameterOrAssertion(context.nextTokenSpan, context.nextTokenParent); + } + function isTypeAssertionContext(context) { + return context.contextNode.kind === 194 /* TypeAssertionExpression */; + } + function isVoidOpContext(context) { + return context.currentTokenSpan.kind === 106 /* VoidKeyword */ && context.currentTokenParent.kind === 200 /* VoidExpression */; + } + function isYieldOrYieldStarWithOperand(context) { + return context.contextNode.kind === 207 /* YieldExpression */ && context.contextNode.expression !== undefined; + } + function isNonNullAssertionContext(context) { + return context.contextNode.kind === 213 /* NonNullExpression */; + } + })(formatting = ts.formatting || (ts.formatting = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var formatting; + (function (formatting) { + function getFormatContext(options) { + return { options: options, getRule: getRulesMap() }; + } + formatting.getFormatContext = getFormatContext; + var rulesMapCache; + function getRulesMap() { + if (rulesMapCache === undefined) { + rulesMapCache = createRulesMap(formatting.getAllRules()); + } + return rulesMapCache; + } + function createRulesMap(rules) { + var map = buildMap(rules); + return function (context) { + var bucket = map[getRuleBucketIndex(context.currentTokenSpan.kind, context.nextTokenSpan.kind)]; + return bucket && ts.find(bucket, function (rule) { return ts.every(rule.context, function (c) { return c(context); }); }); + }; + } + function buildMap(rules) { + // Map from bucket index to array of rules + var map = new Array(mapRowLength * mapRowLength); + // This array is used only during construction of the rulesbucket in the map + var rulesBucketConstructionStateList = new Array(map.length); + for (var _i = 0, rules_1 = rules; _i < rules_1.length; _i++) { + var rule = rules_1[_i]; + var specificRule = rule.leftTokenRange.isSpecific && rule.rightTokenRange.isSpecific; + for (var _a = 0, _b = rule.leftTokenRange.tokens; _a < _b.length; _a++) { + var left = _b[_a]; + for (var _c = 0, _d = rule.rightTokenRange.tokens; _c < _d.length; _c++) { + var right = _d[_c]; + var index = getRuleBucketIndex(left, right); + var rulesBucket = map[index]; + if (rulesBucket === undefined) { + rulesBucket = map[index] = []; + } + addRule(rulesBucket, rule.rule, specificRule, rulesBucketConstructionStateList, index); + } + } + } + return map; + } + function getRuleBucketIndex(row, column) { + ts.Debug.assert(row <= 147 /* LastKeyword */ && column <= 147 /* LastKeyword */, "Must compute formatting context from tokens"); + return (row * mapRowLength) + column; + } + var maskBitSize = 5; + var mask = 31; // MaskBitSize bits + var mapRowLength = 147 /* LastToken */ + 1; + var RulesPosition; + (function (RulesPosition) { + RulesPosition[RulesPosition["IgnoreRulesSpecific"] = 0] = "IgnoreRulesSpecific"; + RulesPosition[RulesPosition["IgnoreRulesAny"] = maskBitSize * 1] = "IgnoreRulesAny"; + RulesPosition[RulesPosition["ContextRulesSpecific"] = maskBitSize * 2] = "ContextRulesSpecific"; + RulesPosition[RulesPosition["ContextRulesAny"] = maskBitSize * 3] = "ContextRulesAny"; + RulesPosition[RulesPosition["NoContextRulesSpecific"] = maskBitSize * 4] = "NoContextRulesSpecific"; + RulesPosition[RulesPosition["NoContextRulesAny"] = maskBitSize * 5] = "NoContextRulesAny"; + })(RulesPosition || (RulesPosition = {})); + // The Rules list contains all the inserted rules into a rulebucket in the following order: + // 1- Ignore rules with specific token combination + // 2- Ignore rules with any token combination + // 3- Context rules with specific token combination + // 4- Context rules with any token combination + // 5- Non-context rules with specific token combination + // 6- Non-context rules with any token combination + // + // The member rulesInsertionIndexBitmap is used to describe the number of rules + // in each sub-bucket (above) hence can be used to know the index of where to insert + // the next rule. It's a bitmap which contains 6 different sections each is given 5 bits. + // + // Example: + // In order to insert a rule to the end of sub-bucket (3), we get the index by adding + // the values in the bitmap segments 3rd, 2nd, and 1st. + function addRule(rules, rule, specificTokens, constructionState, rulesBucketIndex) { + var position = rule.action === 1 /* Ignore */ + ? specificTokens ? RulesPosition.IgnoreRulesSpecific : RulesPosition.IgnoreRulesAny + : rule.context !== formatting.anyContext + ? specificTokens ? RulesPosition.ContextRulesSpecific : RulesPosition.ContextRulesAny + : specificTokens ? RulesPosition.NoContextRulesSpecific : RulesPosition.NoContextRulesAny; + var state = constructionState[rulesBucketIndex] || 0; + rules.splice(getInsertionIndex(state, position), 0, rule); + constructionState[rulesBucketIndex] = increaseInsertionIndex(state, position); + } + function getInsertionIndex(indexBitmap, maskPosition) { + var index = 0; + for (var pos = 0; pos <= maskPosition; pos += maskBitSize) { + index += indexBitmap & mask; + indexBitmap >>= maskBitSize; + } + return index; + } + function increaseInsertionIndex(indexBitmap, maskPosition) { + var value = ((indexBitmap >> maskPosition) & mask) + 1; + ts.Debug.assert((value & mask) === value, "Adding more rules into the sub-bucket than allowed. Maximum allowed is 32 rules."); + return (indexBitmap & ~(mask << maskPosition)) | (value << maskPosition); + } + })(formatting = ts.formatting || (ts.formatting = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var formatting; + (function (formatting) { + var Constants; + (function (Constants) { + Constants[Constants["Unknown"] = -1] = "Unknown"; + })(Constants || (Constants = {})); + function formatOnEnter(position, sourceFile, formatContext) { + var line = sourceFile.getLineAndCharacterOfPosition(position).line; + if (line === 0) { + return []; + } + // After the enter key, the cursor is now at a new line. The new line may or may not contain non-whitespace characters. + // If the new line has only whitespaces, we won't want to format this line, because that would remove the indentation as + // trailing whitespaces. So the end of the formatting span should be the later one between: + // 1. the end of the previous line + // 2. the last non-whitespace character in the current line + var endOfFormatSpan = ts.getEndLinePosition(line, sourceFile); + while (ts.isWhiteSpaceSingleLine(sourceFile.text.charCodeAt(endOfFormatSpan))) { + endOfFormatSpan--; + } + // if the character at the end of the span is a line break, we shouldn't include it, because it indicates we don't want to + // touch the current line at all. Also, on some OSes the line break consists of two characters (\r\n), we should test if the + // previous character before the end of format span is line break character as well. + if (ts.isLineBreak(sourceFile.text.charCodeAt(endOfFormatSpan))) { + endOfFormatSpan--; + } + var span = { + // get start position for the previous line + pos: ts.getStartPositionOfLine(line - 1, sourceFile), + // end value is exclusive so add 1 to the result + end: endOfFormatSpan + 1 + }; + return formatSpan(span, sourceFile, formatContext, 2 /* FormatOnEnter */); + } + formatting.formatOnEnter = formatOnEnter; + function formatOnSemicolon(position, sourceFile, formatContext) { + var semicolon = findImmediatelyPrecedingTokenOfKind(position, 26 /* SemicolonToken */, sourceFile); + return formatNodeLines(findOutermostNodeWithinListLevel(semicolon), sourceFile, formatContext, 3 /* FormatOnSemicolon */); + } + formatting.formatOnSemicolon = formatOnSemicolon; + function formatOnOpeningCurly(position, sourceFile, formatContext) { + var openingCurly = findImmediatelyPrecedingTokenOfKind(position, 18 /* OpenBraceToken */, sourceFile); + if (!openingCurly) { + return []; + } + var curlyBraceRange = openingCurly.parent; + var outermostNode = findOutermostNodeWithinListLevel(curlyBraceRange); + /** + * We limit the span to end at the opening curly to handle the case where + * the brace matched to that just typed will be incorrect after further edits. + * For example, we could type the opening curly for the following method + * body without brace-matching activated: + * ``` + * class C { + * foo() + * } + * ``` + * and we wouldn't want to move the closing brace. + */ + var textRange = { + pos: ts.getLineStartPositionForPosition(outermostNode.getStart(sourceFile), sourceFile), + end: position + }; + return formatSpan(textRange, sourceFile, formatContext, 4 /* FormatOnOpeningCurlyBrace */); + } + formatting.formatOnOpeningCurly = formatOnOpeningCurly; + function formatOnClosingCurly(position, sourceFile, formatContext) { + var precedingToken = findImmediatelyPrecedingTokenOfKind(position, 19 /* CloseBraceToken */, sourceFile); + return formatNodeLines(findOutermostNodeWithinListLevel(precedingToken), sourceFile, formatContext, 5 /* FormatOnClosingCurlyBrace */); + } + formatting.formatOnClosingCurly = formatOnClosingCurly; + function formatDocument(sourceFile, formatContext) { + var span = { + pos: 0, + end: sourceFile.text.length + }; + return formatSpan(span, sourceFile, formatContext, 0 /* FormatDocument */); + } + formatting.formatDocument = formatDocument; + function formatSelection(start, end, sourceFile, formatContext) { + // format from the beginning of the line + var span = { + pos: ts.getLineStartPositionForPosition(start, sourceFile), + end: end, + }; + return formatSpan(span, sourceFile, formatContext, 1 /* FormatSelection */); + } + formatting.formatSelection = formatSelection; + /** + * Validating `expectedTokenKind` ensures the token was typed in the context we expect (eg: not a comment). + * @param expectedTokenKind The kind of the last token constituting the desired parent node. + */ + function findImmediatelyPrecedingTokenOfKind(end, expectedTokenKind, sourceFile) { + var precedingToken = ts.findPrecedingToken(end, sourceFile); + return precedingToken && precedingToken.kind === expectedTokenKind && end === precedingToken.getEnd() ? + precedingToken : + undefined; + } + /** + * Finds the highest node enclosing `node` at the same list level as `node` + * and whose end does not exceed `node.end`. + * + * Consider typing the following + * ``` + * let x = 1; + * while (true) { + * } + * ``` + * Upon typing the closing curly, we want to format the entire `while`-statement, but not the preceding + * variable declaration. + */ + function findOutermostNodeWithinListLevel(node) { + var current = node; + while (current && + current.parent && + current.parent.end === node.end && + !isListElement(current.parent, current)) { + current = current.parent; + } + return current; + } + // Returns true if node is a element in some list in parent + // i.e. parent is class declaration with the list of members and node is one of members. + function isListElement(parent, node) { + switch (parent.kind) { + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + return ts.rangeContainsRange(parent.members, node); + case 244 /* ModuleDeclaration */: + var body = parent.body; + return !!body && body.kind === 245 /* ModuleBlock */ && ts.rangeContainsRange(body.statements, node); + case 279 /* SourceFile */: + case 218 /* Block */: + case 245 /* ModuleBlock */: + return ts.rangeContainsRange(parent.statements, node); + case 274 /* CatchClause */: + return ts.rangeContainsRange(parent.block.statements, node); + } + return false; + } + /** find node that fully contains given text range */ + function findEnclosingNode(range, sourceFile) { + return find(sourceFile); + function find(n) { + var candidate = ts.forEachChild(n, function (c) { return ts.startEndContainsRange(c.getStart(sourceFile), c.end, range) && c; }); + if (candidate) { + var result = find(candidate); + if (result) { + return result; + } + } + return n; + } + } + /** formatting is not applied to ranges that contain parse errors. + * This function will return a predicate that for a given text range will tell + * if there are any parse errors that overlap with the range. + */ + function prepareRangeContainsErrorFunction(errors, originalRange) { + if (!errors.length) { + return rangeHasNoErrors; + } + // pick only errors that fall in range + var sorted = errors + .filter(function (d) { return ts.rangeOverlapsWithStartEnd(originalRange, d.start, d.start + d.length); }) // TODO: GH#18217 + .sort(function (e1, e2) { return e1.start - e2.start; }); + if (!sorted.length) { + return rangeHasNoErrors; + } + var index = 0; + return function (r) { + // in current implementation sequence of arguments [r1, r2...] is monotonically increasing. + // 'index' tracks the index of the most recent error that was checked. + while (true) { + if (index >= sorted.length) { + // all errors in the range were already checked -> no error in specified range + return false; + } + var error = sorted[index]; + if (r.end <= error.start) { + // specified range ends before the error refered by 'index' - no error in range + return false; + } + if (ts.startEndOverlapsWithStartEnd(r.pos, r.end, error.start, error.start + error.length)) { + // specified range overlaps with error range + return true; + } + index++; + } + }; + function rangeHasNoErrors() { + return false; + } + } + /** + * Start of the original range might fall inside the comment - scanner will not yield appropriate results + * This function will look for token that is located before the start of target range + * and return its end as start position for the scanner. + */ + function getScanStartPosition(enclosingNode, originalRange, sourceFile) { + var start = enclosingNode.getStart(sourceFile); + if (start === originalRange.pos && enclosingNode.end === originalRange.end) { + return start; + } + var precedingToken = ts.findPrecedingToken(originalRange.pos, sourceFile); + if (!precedingToken) { + // no preceding token found - start from the beginning of enclosing node + return enclosingNode.pos; + } + // preceding token ends after the start of original range (i.e when originalRange.pos falls in the middle of literal) + // start from the beginning of enclosingNode to handle the entire 'originalRange' + if (precedingToken.end >= originalRange.pos) { + return enclosingNode.pos; + } + return precedingToken.end; + } + /* + * For cases like + * if (a || + * b ||$ + * c) {...} + * If we hit Enter at $ we want line ' b ||' to be indented. + * Formatting will be applied to the last two lines. + * Node that fully encloses these lines is binary expression 'a ||...'. + * Initial indentation for this node will be 0. + * Binary expressions don't introduce new indentation scopes, however it is possible + * that some parent node on the same line does - like if statement in this case. + * Note that we are considering parents only from the same line with initial node - + * if parent is on the different line - its delta was already contributed + * to the initial indentation. + */ + function getOwnOrInheritedDelta(n, options, sourceFile) { + var previousLine = -1 /* Unknown */; + var child; + while (n) { + var line = sourceFile.getLineAndCharacterOfPosition(n.getStart(sourceFile)).line; + if (previousLine !== -1 /* Unknown */ && line !== previousLine) { + break; + } + if (formatting.SmartIndenter.shouldIndentChildNode(options, n, child, sourceFile)) { + return options.indentSize; + } + previousLine = line; + child = n; + n = n.parent; + } + return 0; + } + function formatNodeGivenIndentation(node, sourceFileLike, languageVariant, initialIndentation, delta, formatContext) { + var range = { pos: 0, end: sourceFileLike.text.length }; + return formatting.getFormattingScanner(sourceFileLike.text, languageVariant, range.pos, range.end, function (scanner) { return formatSpanWorker(range, node, initialIndentation, delta, scanner, formatContext, 1 /* FormatSelection */, function (_) { return false; }, // assume that node does not have any errors + sourceFileLike); }); + } + formatting.formatNodeGivenIndentation = formatNodeGivenIndentation; + function formatNodeLines(node, sourceFile, formatContext, requestKind) { + if (!node) { + return []; + } + var span = { + pos: ts.getLineStartPositionForPosition(node.getStart(sourceFile), sourceFile), + end: node.end + }; + return formatSpan(span, sourceFile, formatContext, requestKind); + } + function formatSpan(originalRange, sourceFile, formatContext, requestKind) { + // find the smallest node that fully wraps the range and compute the initial indentation for the node + var enclosingNode = findEnclosingNode(originalRange, sourceFile); + return formatting.getFormattingScanner(sourceFile.text, sourceFile.languageVariant, getScanStartPosition(enclosingNode, originalRange, sourceFile), originalRange.end, function (scanner) { return formatSpanWorker(originalRange, enclosingNode, formatting.SmartIndenter.getIndentationForNode(enclosingNode, originalRange, sourceFile, formatContext.options), getOwnOrInheritedDelta(enclosingNode, formatContext.options, sourceFile), scanner, formatContext, requestKind, prepareRangeContainsErrorFunction(sourceFile.parseDiagnostics, originalRange), sourceFile); }); + } + function formatSpanWorker(originalRange, enclosingNode, initialIndentation, delta, formattingScanner, _a, requestKind, rangeContainsError, sourceFile) { + var options = _a.options, getRule = _a.getRule; + // formatting context is used by rules provider + var formattingContext = new formatting.FormattingContext(sourceFile, requestKind, options); + var previousRange; + var previousParent; + var previousRangeStartLine; + var lastIndentedLine; + var indentationOnLastIndentedLine = -1 /* Unknown */; + var edits = []; + formattingScanner.advance(); + if (formattingScanner.isOnToken()) { + var startLine = sourceFile.getLineAndCharacterOfPosition(enclosingNode.getStart(sourceFile)).line; + var undecoratedStartLine = startLine; + if (enclosingNode.decorators) { + undecoratedStartLine = sourceFile.getLineAndCharacterOfPosition(ts.getNonDecoratorTokenPosOfNode(enclosingNode, sourceFile)).line; + } + processNode(enclosingNode, enclosingNode, startLine, undecoratedStartLine, initialIndentation, delta); + } + if (!formattingScanner.isOnToken()) { + var leadingTrivia = formattingScanner.getCurrentLeadingTrivia(); + if (leadingTrivia) { + indentTriviaItems(leadingTrivia, initialIndentation, /*indentNextTokenOrTrivia*/ false, function (item) { return processRange(item, sourceFile.getLineAndCharacterOfPosition(item.pos), enclosingNode, enclosingNode, /*dynamicIndentation*/ undefined); }); + trimTrailingWhitespacesForRemainingRange(); + } + } + return edits; + // local functions + /** Tries to compute the indentation for a list element. + * If list element is not in range then + * function will pick its actual indentation + * so it can be pushed downstream as inherited indentation. + * If list element is in the range - its indentation will be equal + * to inherited indentation from its predecessors. + */ + function tryComputeIndentationForListItem(startPos, endPos, parentStartLine, range, inheritedIndentation) { + if (ts.rangeOverlapsWithStartEnd(range, startPos, endPos) || + ts.rangeContainsStartEnd(range, startPos, endPos) /* Not to miss zero-range nodes e.g. JsxText */) { + if (inheritedIndentation !== -1 /* Unknown */) { + return inheritedIndentation; + } + } + else { + var startLine = sourceFile.getLineAndCharacterOfPosition(startPos).line; + var startLinePosition = ts.getLineStartPositionForPosition(startPos, sourceFile); + var column = formatting.SmartIndenter.findFirstNonWhitespaceColumn(startLinePosition, startPos, sourceFile, options); + if (startLine !== parentStartLine || startPos === column) { + // Use the base indent size if it is greater than + // the indentation of the inherited predecessor. + var baseIndentSize = formatting.SmartIndenter.getBaseIndentation(options); + return baseIndentSize > column ? baseIndentSize : column; + } + } + return -1 /* Unknown */; + } + function computeIndentation(node, startLine, inheritedIndentation, parent, parentDynamicIndentation, effectiveParentStartLine) { + var delta = formatting.SmartIndenter.shouldIndentChildNode(options, node) ? options.indentSize : 0; + if (effectiveParentStartLine === startLine) { + // if node is located on the same line with the parent + // - inherit indentation from the parent + // - push children if either parent of node itself has non-zero delta + return { + indentation: startLine === lastIndentedLine ? indentationOnLastIndentedLine : parentDynamicIndentation.getIndentation(), + delta: Math.min(options.indentSize, parentDynamicIndentation.getDelta(node) + delta) + }; + } + else if (inheritedIndentation === -1 /* Unknown */) { + if (node.kind === 20 /* OpenParenToken */ && startLine === lastIndentedLine) { + // the is used for chaining methods formatting + // - we need to get the indentation on last line and the delta of parent + return { indentation: indentationOnLastIndentedLine, delta: parentDynamicIndentation.getDelta(node) }; + } + else if (formatting.SmartIndenter.childStartsOnTheSameLineWithElseInIfStatement(parent, node, startLine, sourceFile)) { + return { indentation: parentDynamicIndentation.getIndentation(), delta: delta }; + } + else { + return { indentation: parentDynamicIndentation.getIndentation() + parentDynamicIndentation.getDelta(node), delta: delta }; + } + } + else { + return { indentation: inheritedIndentation, delta: delta }; + } + } + function getFirstNonDecoratorTokenOfNode(node) { + if (node.modifiers && node.modifiers.length) { + return node.modifiers[0].kind; + } + switch (node.kind) { + case 240 /* ClassDeclaration */: return 76 /* ClassKeyword */; + case 241 /* InterfaceDeclaration */: return 110 /* InterfaceKeyword */; + case 239 /* FunctionDeclaration */: return 90 /* FunctionKeyword */; + case 243 /* EnumDeclaration */: return 243 /* EnumDeclaration */; + case 158 /* GetAccessor */: return 126 /* GetKeyword */; + case 159 /* SetAccessor */: return 137 /* SetKeyword */; + case 156 /* MethodDeclaration */: + if (node.asteriskToken) { + return 40 /* AsteriskToken */; + } + // falls through + case 154 /* PropertyDeclaration */: + case 151 /* Parameter */: + var name = ts.getNameOfDeclaration(node); + if (name) { + return name.kind; + } + } + } + function getDynamicIndentation(node, nodeStartLine, indentation, delta) { + return { + getIndentationForComment: function (kind, tokenIndentation, container) { + switch (kind) { + // preceding comment to the token that closes the indentation scope inherits the indentation from the scope + // .. { + // // comment + // } + case 19 /* CloseBraceToken */: + case 23 /* CloseBracketToken */: + case 21 /* CloseParenToken */: + return indentation + getDelta(container); + } + return tokenIndentation !== -1 /* Unknown */ ? tokenIndentation : indentation; + }, + // if list end token is LessThanToken '>' then its delta should be explicitly suppressed + // so that LessThanToken as a binary operator can still be indented. + // foo.then + // < + // number, + // string, + // >(); + // vs + // var a = xValue + // > yValue; + getIndentationForToken: function (line, kind, container, suppressDelta) { + return !suppressDelta && shouldAddDelta(line, kind, container) ? indentation + getDelta(container) : indentation; + }, + getIndentation: function () { return indentation; }, + getDelta: getDelta, + recomputeIndentation: function (lineAdded) { + if (node.parent && formatting.SmartIndenter.shouldIndentChildNode(options, node.parent, node, sourceFile)) { + indentation += lineAdded ? options.indentSize : -options.indentSize; + delta = formatting.SmartIndenter.shouldIndentChildNode(options, node) ? options.indentSize : 0; + } + } + }; + function shouldAddDelta(line, kind, container) { + switch (kind) { + // open and close brace, 'else' and 'while' (in do statement) tokens has indentation of the parent + case 18 /* OpenBraceToken */: + case 19 /* CloseBraceToken */: + case 21 /* CloseParenToken */: + case 83 /* ElseKeyword */: + case 107 /* WhileKeyword */: + case 58 /* AtToken */: + return false; + case 42 /* SlashToken */: + case 30 /* GreaterThanToken */: + switch (container.kind) { + case 262 /* JsxOpeningElement */: + case 263 /* JsxClosingElement */: + case 261 /* JsxSelfClosingElement */: + return false; + } + break; + case 22 /* OpenBracketToken */: + case 23 /* CloseBracketToken */: + if (container.kind !== 181 /* MappedType */) { + return false; + } + break; + } + // if token line equals to the line of containing node (this is a first token in the node) - use node indentation + return nodeStartLine !== line + // if this token is the first token following the list of decorators, we do not need to indent + && !(node.decorators && kind === getFirstNonDecoratorTokenOfNode(node)); + } + function getDelta(child) { + // Delta value should be zero when the node explicitly prevents indentation of the child node + return formatting.SmartIndenter.nodeWillIndentChild(options, node, child, sourceFile, /*indentByDefault*/ true) ? delta : 0; + } + } + function processNode(node, contextNode, nodeStartLine, undecoratedNodeStartLine, indentation, delta) { + if (!ts.rangeOverlapsWithStartEnd(originalRange, node.getStart(sourceFile), node.getEnd())) { + return; + } + var nodeDynamicIndentation = getDynamicIndentation(node, nodeStartLine, indentation, delta); + // a useful observations when tracking context node + // / + // [a] + // / | \ + // [b] [c] [d] + // node 'a' is a context node for nodes 'b', 'c', 'd' + // except for the leftmost leaf token in [b] - in this case context node ('e') is located somewhere above 'a' + // this rule can be applied recursively to child nodes of 'a'. + // + // context node is set to parent node value after processing every child node + // context node is set to parent of the token after processing every token + var childContextNode = contextNode; + // if there are any tokens that logically belong to node and interleave child nodes + // such tokens will be consumed in processChildNode for the child that follows them + ts.forEachChild(node, function (child) { + processChildNode(child, /*inheritedIndentation*/ -1 /* Unknown */, node, nodeDynamicIndentation, nodeStartLine, undecoratedNodeStartLine, /*isListItem*/ false); + }, function (nodes) { + processChildNodes(nodes, node, nodeStartLine, nodeDynamicIndentation); + }); + // proceed any tokens in the node that are located after child nodes + while (formattingScanner.isOnToken()) { + var tokenInfo = formattingScanner.readTokenInfo(node); + if (tokenInfo.token.end > node.end) { + break; + } + consumeTokenAndAdvanceScanner(tokenInfo, node, nodeDynamicIndentation, node); + } + function processChildNode(child, inheritedIndentation, parent, parentDynamicIndentation, parentStartLine, undecoratedParentStartLine, isListItem, isFirstListItem) { + var childStartPos = child.getStart(sourceFile); + var childStartLine = sourceFile.getLineAndCharacterOfPosition(childStartPos).line; + var undecoratedChildStartLine = childStartLine; + if (child.decorators) { + undecoratedChildStartLine = sourceFile.getLineAndCharacterOfPosition(ts.getNonDecoratorTokenPosOfNode(child, sourceFile)).line; + } + // if child is a list item - try to get its indentation, only if parent is within the original range. + var childIndentationAmount = -1 /* Unknown */; + if (isListItem && ts.rangeContainsRange(originalRange, parent)) { + childIndentationAmount = tryComputeIndentationForListItem(childStartPos, child.end, parentStartLine, originalRange, inheritedIndentation); + if (childIndentationAmount !== -1 /* Unknown */) { + inheritedIndentation = childIndentationAmount; + } + } + // child node is outside the target range - do not dive inside + if (!ts.rangeOverlapsWithStartEnd(originalRange, child.pos, child.end)) { + if (child.end < originalRange.pos) { + formattingScanner.skipToEndOf(child); + } + return inheritedIndentation; + } + if (child.getFullWidth() === 0) { + return inheritedIndentation; + } + while (formattingScanner.isOnToken()) { + // proceed any parent tokens that are located prior to child.getStart() + var tokenInfo = formattingScanner.readTokenInfo(node); + if (tokenInfo.token.end > childStartPos) { + // stop when formatting scanner advances past the beginning of the child + break; + } + consumeTokenAndAdvanceScanner(tokenInfo, node, parentDynamicIndentation, node); + } + if (!formattingScanner.isOnToken()) { + return inheritedIndentation; + } + // JSX text shouldn't affect indenting + if (ts.isToken(child) && child.kind !== 11 /* JsxText */) { + // if child node is a token, it does not impact indentation, proceed it using parent indentation scope rules + var tokenInfo = formattingScanner.readTokenInfo(child); + ts.Debug.assert(tokenInfo.token.end === child.end, "Token end is child end"); + consumeTokenAndAdvanceScanner(tokenInfo, node, parentDynamicIndentation, child); + return inheritedIndentation; + } + var effectiveParentStartLine = child.kind === 152 /* Decorator */ ? childStartLine : undecoratedParentStartLine; + var childIndentation = computeIndentation(child, childStartLine, childIndentationAmount, node, parentDynamicIndentation, effectiveParentStartLine); + processNode(child, childContextNode, childStartLine, undecoratedChildStartLine, childIndentation.indentation, childIndentation.delta); + if (child.kind === 11 /* JsxText */) { + var range = { pos: child.getStart(), end: child.getEnd() }; + indentMultilineCommentOrJsxText(range, childIndentation.indentation, /*firstLineIsIndented*/ true, /*indentFinalLine*/ false); + } + childContextNode = node; + if (isFirstListItem && parent.kind === 187 /* ArrayLiteralExpression */ && inheritedIndentation === -1 /* Unknown */) { + inheritedIndentation = childIndentation.indentation; + } + return inheritedIndentation; + } + function processChildNodes(nodes, parent, parentStartLine, parentDynamicIndentation) { + ts.Debug.assert(ts.isNodeArray(nodes)); + var listStartToken = getOpenTokenForList(parent, nodes); + var listDynamicIndentation = parentDynamicIndentation; + var startLine = parentStartLine; + if (listStartToken !== 0 /* Unknown */) { + // introduce a new indentation scope for lists (including list start and end tokens) + while (formattingScanner.isOnToken()) { + var tokenInfo = formattingScanner.readTokenInfo(parent); + if (tokenInfo.token.end > nodes.pos) { + // stop when formatting scanner moves past the beginning of node list + break; + } + else if (tokenInfo.token.kind === listStartToken) { + // consume list start token + startLine = sourceFile.getLineAndCharacterOfPosition(tokenInfo.token.pos).line; + consumeTokenAndAdvanceScanner(tokenInfo, parent, parentDynamicIndentation, parent); + var indentationOnListStartToken = void 0; + if (indentationOnLastIndentedLine !== -1 /* Unknown */) { + // scanner just processed list start token so consider last indentation as list indentation + // function foo(): { // last indentation was 0, list item will be indented based on this value + // foo: number; + // }: {}; + indentationOnListStartToken = indentationOnLastIndentedLine; + } + else { + var startLinePosition = ts.getLineStartPositionForPosition(tokenInfo.token.pos, sourceFile); + indentationOnListStartToken = formatting.SmartIndenter.findFirstNonWhitespaceColumn(startLinePosition, tokenInfo.token.pos, sourceFile, options); + } + listDynamicIndentation = getDynamicIndentation(parent, parentStartLine, indentationOnListStartToken, options.indentSize); // TODO: GH#18217 + } + else { + // consume any tokens that precede the list as child elements of 'node' using its indentation scope + consumeTokenAndAdvanceScanner(tokenInfo, parent, parentDynamicIndentation, parent); + } + } + } + var inheritedIndentation = -1 /* Unknown */; + for (var i = 0; i < nodes.length; i++) { + var child = nodes[i]; + inheritedIndentation = processChildNode(child, inheritedIndentation, node, listDynamicIndentation, startLine, startLine, /*isListItem*/ true, /*isFirstListItem*/ i === 0); + } + var listEndToken = getCloseTokenForOpenToken(listStartToken); + if (listEndToken !== 0 /* Unknown */ && formattingScanner.isOnToken()) { + var tokenInfo = formattingScanner.readTokenInfo(parent); + if (tokenInfo.token.kind === 27 /* CommaToken */ && ts.isCallLikeExpression(parent)) { + formattingScanner.advance(); + tokenInfo = formattingScanner.isOnToken() ? formattingScanner.readTokenInfo(parent) : undefined; + } + // consume the list end token only if it is still belong to the parent + // there might be the case when current token matches end token but does not considered as one + // function (x: function) <-- + // without this check close paren will be interpreted as list end token for function expression which is wrong + if (tokenInfo && tokenInfo.token.kind === listEndToken && ts.rangeContainsRange(parent, tokenInfo.token)) { + // consume list end token + consumeTokenAndAdvanceScanner(tokenInfo, parent, listDynamicIndentation, parent, /*isListEndToken*/ true); + } + } + } + function consumeTokenAndAdvanceScanner(currentTokenInfo, parent, dynamicIndentation, container, isListEndToken) { + ts.Debug.assert(ts.rangeContainsRange(parent, currentTokenInfo.token)); + var lastTriviaWasNewLine = formattingScanner.lastTrailingTriviaWasNewLine(); + var indentToken = false; + if (currentTokenInfo.leadingTrivia) { + processTrivia(currentTokenInfo.leadingTrivia, parent, childContextNode, dynamicIndentation); + } + var lineAction = 0 /* None */; + var isTokenInRange = ts.rangeContainsRange(originalRange, currentTokenInfo.token); + var tokenStart = sourceFile.getLineAndCharacterOfPosition(currentTokenInfo.token.pos); + if (isTokenInRange) { + var rangeHasError = rangeContainsError(currentTokenInfo.token); + // save previousRange since processRange will overwrite this value with current one + var savePreviousRange = previousRange; + lineAction = processRange(currentTokenInfo.token, tokenStart, parent, childContextNode, dynamicIndentation); + // do not indent comments\token if token range overlaps with some error + if (!rangeHasError) { + if (lineAction === 0 /* None */) { + // indent token only if end line of previous range does not match start line of the token + var prevEndLine = savePreviousRange && sourceFile.getLineAndCharacterOfPosition(savePreviousRange.end).line; + indentToken = lastTriviaWasNewLine && tokenStart.line !== prevEndLine; + } + else { + indentToken = lineAction === 1 /* LineAdded */; + } + } + } + if (currentTokenInfo.trailingTrivia) { + processTrivia(currentTokenInfo.trailingTrivia, parent, childContextNode, dynamicIndentation); + } + if (indentToken) { + var tokenIndentation = (isTokenInRange && !rangeContainsError(currentTokenInfo.token)) ? + dynamicIndentation.getIndentationForToken(tokenStart.line, currentTokenInfo.token.kind, container, !!isListEndToken) : + -1 /* Unknown */; + var indentNextTokenOrTrivia = true; + if (currentTokenInfo.leadingTrivia) { + var commentIndentation_1 = dynamicIndentation.getIndentationForComment(currentTokenInfo.token.kind, tokenIndentation, container); + indentNextTokenOrTrivia = indentTriviaItems(currentTokenInfo.leadingTrivia, commentIndentation_1, indentNextTokenOrTrivia, function (item) { return insertIndentation(item.pos, commentIndentation_1, /*lineAdded*/ false); }); + } + // indent token only if is it is in target range and does not overlap with any error ranges + if (tokenIndentation !== -1 /* Unknown */ && indentNextTokenOrTrivia) { + insertIndentation(currentTokenInfo.token.pos, tokenIndentation, lineAction === 1 /* LineAdded */); + lastIndentedLine = tokenStart.line; + indentationOnLastIndentedLine = tokenIndentation; + } + } + formattingScanner.advance(); + childContextNode = parent; + } + } + function indentTriviaItems(trivia, commentIndentation, indentNextTokenOrTrivia, indentSingleLine) { + for (var _i = 0, trivia_1 = trivia; _i < trivia_1.length; _i++) { + var triviaItem = trivia_1[_i]; + var triviaInRange = ts.rangeContainsRange(originalRange, triviaItem); + switch (triviaItem.kind) { + case 3 /* MultiLineCommentTrivia */: + if (triviaInRange) { + indentMultilineCommentOrJsxText(triviaItem, commentIndentation, /*firstLineIsIndented*/ !indentNextTokenOrTrivia); + } + indentNextTokenOrTrivia = false; + break; + case 2 /* SingleLineCommentTrivia */: + if (indentNextTokenOrTrivia && triviaInRange) { + indentSingleLine(triviaItem); + } + indentNextTokenOrTrivia = false; + break; + case 4 /* NewLineTrivia */: + indentNextTokenOrTrivia = true; + break; + } + } + return indentNextTokenOrTrivia; + } + function processTrivia(trivia, parent, contextNode, dynamicIndentation) { + for (var _i = 0, trivia_2 = trivia; _i < trivia_2.length; _i++) { + var triviaItem = trivia_2[_i]; + if (ts.isComment(triviaItem.kind) && ts.rangeContainsRange(originalRange, triviaItem)) { + var triviaItemStart = sourceFile.getLineAndCharacterOfPosition(triviaItem.pos); + processRange(triviaItem, triviaItemStart, parent, contextNode, dynamicIndentation); + } + } + } + function processRange(range, rangeStart, parent, contextNode, dynamicIndentation) { + var rangeHasError = rangeContainsError(range); + var lineAction = 0 /* None */; + if (!rangeHasError) { + if (!previousRange) { + // trim whitespaces starting from the beginning of the span up to the current line + var originalStart = sourceFile.getLineAndCharacterOfPosition(originalRange.pos); + trimTrailingWhitespacesForLines(originalStart.line, rangeStart.line); + } + else { + lineAction = + processPair(range, rangeStart.line, parent, previousRange, previousRangeStartLine, previousParent, contextNode, dynamicIndentation); + } + } + previousRange = range; + previousParent = parent; + previousRangeStartLine = rangeStart.line; + return lineAction; + } + function processPair(currentItem, currentStartLine, currentParent, previousItem, previousStartLine, previousParent, contextNode, dynamicIndentation) { + formattingContext.updateContext(previousItem, previousParent, currentItem, currentParent, contextNode); + var rule = getRule(formattingContext); + var trimTrailingWhitespaces; + var lineAction = 0 /* None */; + if (rule) { + lineAction = applyRuleEdits(rule, previousItem, previousStartLine, currentItem, currentStartLine); + switch (lineAction) { + case 2 /* LineRemoved */: + // Handle the case where the next line is moved to be the end of this line. + // In this case we don't indent the next line in the next pass. + if (currentParent.getStart(sourceFile) === currentItem.pos) { + dynamicIndentation.recomputeIndentation(/*lineAddedByFormatting*/ false); + } + break; + case 1 /* LineAdded */: + // Handle the case where token2 is moved to the new line. + // In this case we indent token2 in the next pass but we set + // sameLineIndent flag to notify the indenter that the indentation is within the line. + if (currentParent.getStart(sourceFile) === currentItem.pos) { + dynamicIndentation.recomputeIndentation(/*lineAddedByFormatting*/ true); + } + break; + default: + ts.Debug.assert(lineAction === 0 /* None */); + } + // We need to trim trailing whitespace between the tokens if they were on different lines, and no rule was applied to put them on the same line + trimTrailingWhitespaces = !(rule.action & 8 /* Delete */) && rule.flags !== 1 /* CanDeleteNewLines */; + } + else { + trimTrailingWhitespaces = true; + } + if (currentStartLine !== previousStartLine && trimTrailingWhitespaces) { + // We need to trim trailing whitespace between the tokens if they were on different lines, and no rule was applied to put them on the same line + trimTrailingWhitespacesForLines(previousStartLine, currentStartLine, previousItem); + } + return lineAction; + } + function insertIndentation(pos, indentation, lineAdded) { + var indentationString = getIndentationString(indentation, options); + if (lineAdded) { + // new line is added before the token by the formatting rules + // insert indentation string at the very beginning of the token + recordReplace(pos, 0, indentationString); + } + else { + var tokenStart = sourceFile.getLineAndCharacterOfPosition(pos); + var startLinePosition = ts.getStartPositionOfLine(tokenStart.line, sourceFile); + if (indentation !== characterToColumn(startLinePosition, tokenStart.character) || indentationIsDifferent(indentationString, startLinePosition)) { + recordReplace(startLinePosition, tokenStart.character, indentationString); + } + } + } + function characterToColumn(startLinePosition, characterInLine) { + var column = 0; + for (var i = 0; i < characterInLine; i++) { + if (sourceFile.text.charCodeAt(startLinePosition + i) === 9 /* tab */) { + column += options.tabSize - column % options.tabSize; + } + else { + column++; + } + } + return column; + } + function indentationIsDifferent(indentationString, startLinePosition) { + return indentationString !== sourceFile.text.substr(startLinePosition, indentationString.length); + } + function indentMultilineCommentOrJsxText(commentRange, indentation, firstLineIsIndented, indentFinalLine) { + if (indentFinalLine === void 0) { indentFinalLine = true; } + // split comment in lines + var startLine = sourceFile.getLineAndCharacterOfPosition(commentRange.pos).line; + var endLine = sourceFile.getLineAndCharacterOfPosition(commentRange.end).line; + if (startLine === endLine) { + if (!firstLineIsIndented) { + // treat as single line comment + insertIndentation(commentRange.pos, indentation, /*lineAdded*/ false); + } + return; + } + var parts = []; + var startPos = commentRange.pos; + for (var line = startLine; line < endLine; line++) { + var endOfLine = ts.getEndLinePosition(line, sourceFile); + parts.push({ pos: startPos, end: endOfLine }); + startPos = ts.getStartPositionOfLine(line + 1, sourceFile); + } + if (indentFinalLine) { + parts.push({ pos: startPos, end: commentRange.end }); + } + if (parts.length === 0) + return; + var startLinePos = ts.getStartPositionOfLine(startLine, sourceFile); + var nonWhitespaceColumnInFirstPart = formatting.SmartIndenter.findFirstNonWhitespaceCharacterAndColumn(startLinePos, parts[0].pos, sourceFile, options); + if (indentation === nonWhitespaceColumnInFirstPart.column) { + return; + } + var startIndex = 0; + if (firstLineIsIndented) { + startIndex = 1; + startLine++; + } + // shift all parts on the delta size + var delta = indentation - nonWhitespaceColumnInFirstPart.column; + for (var i = startIndex; i < parts.length; i++, startLine++) { + var startLinePos_1 = ts.getStartPositionOfLine(startLine, sourceFile); + var nonWhitespaceCharacterAndColumn = i === 0 + ? nonWhitespaceColumnInFirstPart + : formatting.SmartIndenter.findFirstNonWhitespaceCharacterAndColumn(parts[i].pos, parts[i].end, sourceFile, options); + var newIndentation = nonWhitespaceCharacterAndColumn.column + delta; + if (newIndentation > 0) { + var indentationString = getIndentationString(newIndentation, options); + recordReplace(startLinePos_1, nonWhitespaceCharacterAndColumn.character, indentationString); + } + else { + recordDelete(startLinePos_1, nonWhitespaceCharacterAndColumn.character); + } + } + } + function trimTrailingWhitespacesForLines(line1, line2, range) { + for (var line = line1; line < line2; line++) { + var lineStartPosition = ts.getStartPositionOfLine(line, sourceFile); + var lineEndPosition = ts.getEndLinePosition(line, sourceFile); + // do not trim whitespaces in comments or template expression + if (range && (ts.isComment(range.kind) || ts.isStringOrRegularExpressionOrTemplateLiteral(range.kind)) && range.pos <= lineEndPosition && range.end > lineEndPosition) { + continue; + } + var whitespaceStart = getTrailingWhitespaceStartPosition(lineStartPosition, lineEndPosition); + if (whitespaceStart !== -1) { + ts.Debug.assert(whitespaceStart === lineStartPosition || !ts.isWhiteSpaceSingleLine(sourceFile.text.charCodeAt(whitespaceStart - 1))); + recordDelete(whitespaceStart, lineEndPosition + 1 - whitespaceStart); + } + } + } + /** + * @param start The position of the first character in range + * @param end The position of the last character in range + */ + function getTrailingWhitespaceStartPosition(start, end) { + var pos = end; + while (pos >= start && ts.isWhiteSpaceSingleLine(sourceFile.text.charCodeAt(pos))) { + pos--; + } + if (pos !== end) { + return pos + 1; + } + return -1; + } + /** + * Trimming will be done for lines after the previous range + */ + function trimTrailingWhitespacesForRemainingRange() { + var startPosition = previousRange ? previousRange.end : originalRange.pos; + var startLine = sourceFile.getLineAndCharacterOfPosition(startPosition).line; + var endLine = sourceFile.getLineAndCharacterOfPosition(originalRange.end).line; + trimTrailingWhitespacesForLines(startLine, endLine + 1, previousRange); + } + function recordDelete(start, len) { + if (len) { + edits.push(ts.createTextChangeFromStartLength(start, len, "")); + } + } + function recordReplace(start, len, newText) { + if (len || newText) { + edits.push(ts.createTextChangeFromStartLength(start, len, newText)); + } + } + function applyRuleEdits(rule, previousRange, previousStartLine, currentRange, currentStartLine) { + var onLaterLine = currentStartLine !== previousStartLine; + switch (rule.action) { + case 1 /* Ignore */: + // no action required + return 0 /* None */; + case 8 /* Delete */: + if (previousRange.end !== currentRange.pos) { + // delete characters starting from t1.end up to t2.pos exclusive + recordDelete(previousRange.end, currentRange.pos - previousRange.end); + return onLaterLine ? 2 /* LineRemoved */ : 0 /* None */; + } + break; + case 4 /* NewLine */: + // exit early if we on different lines and rule cannot change number of newlines + // if line1 and line2 are on subsequent lines then no edits are required - ok to exit + // if line1 and line2 are separated with more than one newline - ok to exit since we cannot delete extra new lines + if (rule.flags !== 1 /* CanDeleteNewLines */ && previousStartLine !== currentStartLine) { + return 0 /* None */; + } + // edit should not be applied if we have one line feed between elements + var lineDelta = currentStartLine - previousStartLine; + if (lineDelta !== 1) { + recordReplace(previousRange.end, currentRange.pos - previousRange.end, options.newLineCharacter); + return onLaterLine ? 0 /* None */ : 1 /* LineAdded */; + } + break; + case 2 /* Space */: + // exit early if we on different lines and rule cannot change number of newlines + if (rule.flags !== 1 /* CanDeleteNewLines */ && previousStartLine !== currentStartLine) { + return 0 /* None */; + } + var posDelta = currentRange.pos - previousRange.end; + if (posDelta !== 1 || sourceFile.text.charCodeAt(previousRange.end) !== 32 /* space */) { + recordReplace(previousRange.end, currentRange.pos - previousRange.end, " "); + return onLaterLine ? 2 /* LineRemoved */ : 0 /* None */; + } + } + return 0 /* None */; + } + } + var LineAction; + (function (LineAction) { + LineAction[LineAction["None"] = 0] = "None"; + LineAction[LineAction["LineAdded"] = 1] = "LineAdded"; + LineAction[LineAction["LineRemoved"] = 2] = "LineRemoved"; + })(LineAction || (LineAction = {})); + /** + * @param precedingToken pass `null` if preceding token was already computed and result was `undefined`. + */ + function getRangeOfEnclosingComment(sourceFile, position, precedingToken, // tslint:disable-line:no-null-keyword + tokenAtPosition) { + if (tokenAtPosition === void 0) { tokenAtPosition = ts.getTokenAtPosition(sourceFile, position); } + var jsdoc = ts.findAncestor(tokenAtPosition, ts.isJSDoc); + if (jsdoc) + tokenAtPosition = jsdoc.parent; + var tokenStart = tokenAtPosition.getStart(sourceFile); + if (tokenStart <= position && position < tokenAtPosition.getEnd()) { + return undefined; + } + precedingToken = precedingToken === null ? undefined : precedingToken === undefined ? ts.findPrecedingToken(position, sourceFile) : precedingToken; + // Between two consecutive tokens, all comments are either trailing on the former + // or leading on the latter (and none are in both lists). + var trailingRangesOfPreviousToken = precedingToken && ts.getTrailingCommentRanges(sourceFile.text, precedingToken.end); + var leadingCommentRangesOfNextToken = ts.getLeadingCommentRangesOfNode(tokenAtPosition, sourceFile); + var commentRanges = ts.concatenate(trailingRangesOfPreviousToken, leadingCommentRangesOfNextToken); + return commentRanges && ts.find(commentRanges, function (range) { return ts.rangeContainsPositionExclusive(range, position) || + // The end marker of a single-line comment does not include the newline character. + // With caret at `^`, in the following case, we are inside a comment (^ denotes the cursor position): + // + // // asdf ^\n + // + // But for closed multi-line comments, we don't want to be inside the comment in the following case: + // + // /* asdf */^ + // + // However, unterminated multi-line comments *do* contain their end. + // + // Internally, we represent the end of the comment at the newline and closing '/', respectively. + // + position === range.end && (range.kind === 2 /* SingleLineCommentTrivia */ || position === sourceFile.getFullWidth()); }); + } + formatting.getRangeOfEnclosingComment = getRangeOfEnclosingComment; + function getOpenTokenForList(node, list) { + switch (node.kind) { + case 157 /* Constructor */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 197 /* ArrowFunction */: + if (node.typeParameters === list) { + return 28 /* LessThanToken */; + } + else if (node.parameters === list) { + return 20 /* OpenParenToken */; + } + break; + case 191 /* CallExpression */: + case 192 /* NewExpression */: + if (node.typeArguments === list) { + return 28 /* LessThanToken */; + } + else if (node.arguments === list) { + return 20 /* OpenParenToken */; + } + break; + case 164 /* TypeReference */: + if (node.typeArguments === list) { + return 28 /* LessThanToken */; + } + break; + case 168 /* TypeLiteral */: + return 18 /* OpenBraceToken */; + } + return 0 /* Unknown */; + } + function getCloseTokenForOpenToken(kind) { + switch (kind) { + case 20 /* OpenParenToken */: + return 21 /* CloseParenToken */; + case 28 /* LessThanToken */: + return 30 /* GreaterThanToken */; + case 18 /* OpenBraceToken */: + return 19 /* CloseBraceToken */; + } + return 0 /* Unknown */; + } + var internedSizes; + var internedTabsIndentation; + var internedSpacesIndentation; + function getIndentationString(indentation, options) { + // reset interned strings if FormatCodeOptions were changed + var resetInternedStrings = !internedSizes || (internedSizes.tabSize !== options.tabSize || internedSizes.indentSize !== options.indentSize); + if (resetInternedStrings) { + internedSizes = { tabSize: options.tabSize, indentSize: options.indentSize }; + internedTabsIndentation = internedSpacesIndentation = undefined; + } + if (!options.convertTabsToSpaces) { + var tabs = Math.floor(indentation / options.tabSize); + var spaces = indentation - tabs * options.tabSize; + var tabString = void 0; + if (!internedTabsIndentation) { + internedTabsIndentation = []; + } + if (internedTabsIndentation[tabs] === undefined) { + internedTabsIndentation[tabs] = tabString = ts.repeatString("\t", tabs); + } + else { + tabString = internedTabsIndentation[tabs]; + } + return spaces ? tabString + ts.repeatString(" ", spaces) : tabString; + } + else { + var spacesString = void 0; + var quotient = Math.floor(indentation / options.indentSize); + var remainder = indentation % options.indentSize; + if (!internedSpacesIndentation) { + internedSpacesIndentation = []; + } + if (internedSpacesIndentation[quotient] === undefined) { + spacesString = ts.repeatString(" ", options.indentSize * quotient); + internedSpacesIndentation[quotient] = spacesString; + } + else { + spacesString = internedSpacesIndentation[quotient]; + } + return remainder ? spacesString + ts.repeatString(" ", remainder) : spacesString; + } + } + formatting.getIndentationString = getIndentationString; + })(formatting = ts.formatting || (ts.formatting = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var formatting; + (function (formatting) { + var SmartIndenter; + (function (SmartIndenter) { + var Value; + (function (Value) { + Value[Value["Unknown"] = -1] = "Unknown"; + })(Value || (Value = {})); + /** + * @param assumeNewLineBeforeCloseBrace + * `false` when called on text from a real source file. + * `true` when we need to assume `position` is on a newline. + * + * This is useful for codefixes. Consider + * ``` + * function f() { + * |} + * ``` + * with `position` at `|`. + * + * When inserting some text after an open brace, we would like to get indentation as if a newline was already there. + * By default indentation at `position` will be 0 so 'assumeNewLineBeforeCloseBrace' overrides this behavior. + */ + function getIndentation(position, sourceFile, options, assumeNewLineBeforeCloseBrace) { + if (assumeNewLineBeforeCloseBrace === void 0) { assumeNewLineBeforeCloseBrace = false; } + if (position > sourceFile.text.length) { + return getBaseIndentation(options); // past EOF + } + // no indentation when the indent style is set to none, + // so we can return fast + if (options.indentStyle === ts.IndentStyle.None) { + return 0; + } + var precedingToken = ts.findPrecedingToken(position, sourceFile, /*startNode*/ undefined, /*excludeJsdoc*/ true); + var enclosingCommentRange = formatting.getRangeOfEnclosingComment(sourceFile, position, precedingToken || null); // tslint:disable-line:no-null-keyword + if (enclosingCommentRange && enclosingCommentRange.kind === 3 /* MultiLineCommentTrivia */) { + return getCommentIndent(sourceFile, position, options, enclosingCommentRange); + } + if (!precedingToken) { + return getBaseIndentation(options); + } + // no indentation in string \regex\template literals + var precedingTokenIsLiteral = ts.isStringOrRegularExpressionOrTemplateLiteral(precedingToken.kind); + if (precedingTokenIsLiteral && precedingToken.getStart(sourceFile) <= position && position < precedingToken.end) { + return 0; + } + var lineAtPosition = sourceFile.getLineAndCharacterOfPosition(position).line; + // indentation is first non-whitespace character in a previous line + // for block indentation, we should look for a line which contains something that's not + // whitespace. + if (options.indentStyle === ts.IndentStyle.Block) { + return getBlockIndent(sourceFile, position, options); + } + if (precedingToken.kind === 27 /* CommaToken */ && precedingToken.parent.kind !== 204 /* BinaryExpression */) { + // previous token is comma that separates items in list - find the previous item and try to derive indentation from it + var actualIndentation = getActualIndentationForListItemBeforeComma(precedingToken, sourceFile, options); + if (actualIndentation !== -1 /* Unknown */) { + return actualIndentation; + } + } + var containerList = getListByPosition(position, precedingToken.parent, sourceFile); + // use list position if the preceding token is before any list items + if (containerList && !ts.rangeContainsRange(containerList, precedingToken)) { + return getActualIndentationForListStartLine(containerList, sourceFile, options) + options.indentSize; // TODO: GH#18217 + } + return getSmartIndent(sourceFile, position, precedingToken, lineAtPosition, assumeNewLineBeforeCloseBrace, options); + } + SmartIndenter.getIndentation = getIndentation; + function getCommentIndent(sourceFile, position, options, enclosingCommentRange) { + var previousLine = ts.getLineAndCharacterOfPosition(sourceFile, position).line - 1; + var commentStartLine = ts.getLineAndCharacterOfPosition(sourceFile, enclosingCommentRange.pos).line; + ts.Debug.assert(commentStartLine >= 0); + if (previousLine <= commentStartLine) { + return findFirstNonWhitespaceColumn(ts.getStartPositionOfLine(commentStartLine, sourceFile), position, sourceFile, options); + } + var startPositionOfLine = ts.getStartPositionOfLine(previousLine, sourceFile); + var _a = findFirstNonWhitespaceCharacterAndColumn(startPositionOfLine, position, sourceFile, options), column = _a.column, character = _a.character; + if (column === 0) { + return column; + } + var firstNonWhitespaceCharacterCode = sourceFile.text.charCodeAt(startPositionOfLine + character); + return firstNonWhitespaceCharacterCode === 42 /* asterisk */ ? column - 1 : column; + } + function getBlockIndent(sourceFile, position, options) { + // move backwards until we find a line with a non-whitespace character, + // then find the first non-whitespace character for that line. + var current = position; + while (current > 0) { + var char = sourceFile.text.charCodeAt(current); + if (!ts.isWhiteSpaceLike(char)) { + break; + } + current--; + } + var lineStart = ts.getLineStartPositionForPosition(current, sourceFile); + return findFirstNonWhitespaceColumn(lineStart, current, sourceFile, options); + } + function getSmartIndent(sourceFile, position, precedingToken, lineAtPosition, assumeNewLineBeforeCloseBrace, options) { + // try to find node that can contribute to indentation and includes 'position' starting from 'precedingToken' + // if such node is found - compute initial indentation for 'position' inside this node + var previous; + var current = precedingToken; + while (current) { + if (ts.positionBelongsToNode(current, position, sourceFile) && shouldIndentChildNode(options, current, previous, sourceFile, /*isNextChild*/ true)) { + var currentStart = getStartLineAndCharacterForNode(current, sourceFile); + var nextTokenKind = nextTokenIsCurlyBraceOnSameLineAsCursor(precedingToken, current, lineAtPosition, sourceFile); + var indentationDelta = nextTokenKind !== 0 /* Unknown */ + // handle cases when codefix is about to be inserted before the close brace + ? assumeNewLineBeforeCloseBrace && nextTokenKind === 2 /* CloseBrace */ ? options.indentSize : 0 + : lineAtPosition !== currentStart.line ? options.indentSize : 0; + return getIndentationForNodeWorker(current, currentStart, /*ignoreActualIndentationRange*/ undefined, indentationDelta, sourceFile, /*isNextChild*/ true, options); // TODO: GH#18217 + } + // check if current node is a list item - if yes, take indentation from it + // do not consider parent-child line sharing yet: + // function foo(a + // | preceding node 'a' does share line with its parent but indentation is expected + var actualIndentation = getActualIndentationForListItem(current, sourceFile, options, /*listIndentsChild*/ true); + if (actualIndentation !== -1 /* Unknown */) { + return actualIndentation; + } + previous = current; + current = current.parent; + } + // no parent was found - return the base indentation of the SourceFile + return getBaseIndentation(options); + } + function getIndentationForNode(n, ignoreActualIndentationRange, sourceFile, options) { + var start = sourceFile.getLineAndCharacterOfPosition(n.getStart(sourceFile)); + return getIndentationForNodeWorker(n, start, ignoreActualIndentationRange, /*indentationDelta*/ 0, sourceFile, /*isNextChild*/ false, options); + } + SmartIndenter.getIndentationForNode = getIndentationForNode; + function getBaseIndentation(options) { + return options.baseIndentSize || 0; + } + SmartIndenter.getBaseIndentation = getBaseIndentation; + function getIndentationForNodeWorker(current, currentStart, ignoreActualIndentationRange, indentationDelta, sourceFile, isNextChild, options) { + var parent = current.parent; + // Walk up the tree and collect indentation for parent-child node pairs. Indentation is not added if + // * parent and child nodes start on the same line, or + // * parent is an IfStatement and child starts on the same line as an 'else clause'. + while (parent) { + var useActualIndentation = true; + if (ignoreActualIndentationRange) { + var start = current.getStart(sourceFile); + useActualIndentation = start < ignoreActualIndentationRange.pos || start > ignoreActualIndentationRange.end; + } + var containingListOrParentStart = getContainingListOrParentStart(parent, current, sourceFile); + var parentAndChildShareLine = containingListOrParentStart.line === currentStart.line || + childStartsOnTheSameLineWithElseInIfStatement(parent, current, currentStart.line, sourceFile); + if (useActualIndentation) { + // check if current node is a list item - if yes, take indentation from it + var actualIndentation = getActualIndentationForListItem(current, sourceFile, options, !parentAndChildShareLine); + if (actualIndentation !== -1 /* Unknown */) { + return actualIndentation + indentationDelta; + } + // try to fetch actual indentation for current node from source text + actualIndentation = getActualIndentationForNode(current, parent, currentStart, parentAndChildShareLine, sourceFile, options); + if (actualIndentation !== -1 /* Unknown */) { + return actualIndentation + indentationDelta; + } + } + // increase indentation if parent node wants its content to be indented and parent and child nodes don't start on the same line + if (shouldIndentChildNode(options, parent, current, sourceFile, isNextChild) && !parentAndChildShareLine) { + indentationDelta += options.indentSize; + } + // In our AST, a call argument's `parent` is the call-expression, not the argument list. + // We would like to increase indentation based on the relationship between an argument and its argument-list, + // so we spoof the starting position of the (parent) call-expression to match the (non-parent) argument-list. + // But, the spoofed start-value could then cause a problem when comparing the start position of the call-expression + // to *its* parent (in the case of an iife, an expression statement), adding an extra level of indentation. + // + // Instead, when at an argument, we unspoof the starting position of the enclosing call expression + // *after* applying indentation for the argument. + var useTrueStart = isArgumentAndStartLineOverlapsExpressionBeingCalled(parent, current, currentStart.line, sourceFile); + current = parent; + parent = current.parent; + currentStart = useTrueStart ? sourceFile.getLineAndCharacterOfPosition(current.getStart(sourceFile)) : containingListOrParentStart; + } + return indentationDelta + getBaseIndentation(options); + } + function getContainingListOrParentStart(parent, child, sourceFile) { + var containingList = getContainingList(child, sourceFile); + var startPos = containingList ? containingList.pos : parent.getStart(sourceFile); + return sourceFile.getLineAndCharacterOfPosition(startPos); + } + /* + * Function returns Value.Unknown if indentation cannot be determined + */ + function getActualIndentationForListItemBeforeComma(commaToken, sourceFile, options) { + // previous token is comma that separates items in list - find the previous item and try to derive indentation from it + var commaItemInfo = ts.findListItemInfo(commaToken); + if (commaItemInfo && commaItemInfo.listItemIndex > 0) { + return deriveActualIndentationFromList(commaItemInfo.list.getChildren(), commaItemInfo.listItemIndex - 1, sourceFile, options); + } + else { + // handle broken code gracefully + return -1 /* Unknown */; + } + } + /* + * Function returns Value.Unknown if actual indentation for node should not be used (i.e because node is nested expression) + */ + function getActualIndentationForNode(current, parent, currentLineAndChar, parentAndChildShareLine, sourceFile, options) { + // actual indentation is used for statements\declarations if one of cases below is true: + // - parent is SourceFile - by default immediate children of SourceFile are not indented except when user indents them manually + // - parent and child are not on the same line + var useActualIndentation = (ts.isDeclaration(current) || ts.isStatementButNotDeclaration(current)) && + (parent.kind === 279 /* SourceFile */ || !parentAndChildShareLine); + if (!useActualIndentation) { + return -1 /* Unknown */; + } + return findColumnForFirstNonWhitespaceCharacterInLine(currentLineAndChar, sourceFile, options); + } + var NextTokenKind; + (function (NextTokenKind) { + NextTokenKind[NextTokenKind["Unknown"] = 0] = "Unknown"; + NextTokenKind[NextTokenKind["OpenBrace"] = 1] = "OpenBrace"; + NextTokenKind[NextTokenKind["CloseBrace"] = 2] = "CloseBrace"; + })(NextTokenKind || (NextTokenKind = {})); + function nextTokenIsCurlyBraceOnSameLineAsCursor(precedingToken, current, lineAtPosition, sourceFile) { + var nextToken = ts.findNextToken(precedingToken, current, sourceFile); + if (!nextToken) { + return 0 /* Unknown */; + } + if (nextToken.kind === 18 /* OpenBraceToken */) { + // open braces are always indented at the parent level + return 1 /* OpenBrace */; + } + else if (nextToken.kind === 19 /* CloseBraceToken */) { + // close braces are indented at the parent level if they are located on the same line with cursor + // this means that if new line will be added at $ position, this case will be indented + // class A { + // $ + // } + /// and this one - not + // class A { + // $} + var nextTokenStartLine = getStartLineAndCharacterForNode(nextToken, sourceFile).line; + return lineAtPosition === nextTokenStartLine ? 2 /* CloseBrace */ : 0 /* Unknown */; + } + return 0 /* Unknown */; + } + function getStartLineAndCharacterForNode(n, sourceFile) { + return sourceFile.getLineAndCharacterOfPosition(n.getStart(sourceFile)); + } + function isArgumentAndStartLineOverlapsExpressionBeingCalled(parent, child, childStartLine, sourceFile) { + if (!(ts.isCallExpression(parent) && ts.contains(parent.arguments, child))) { + return false; + } + var expressionOfCallExpressionEnd = parent.expression.getEnd(); + var expressionOfCallExpressionEndLine = ts.getLineAndCharacterOfPosition(sourceFile, expressionOfCallExpressionEnd).line; + return expressionOfCallExpressionEndLine === childStartLine; + } + SmartIndenter.isArgumentAndStartLineOverlapsExpressionBeingCalled = isArgumentAndStartLineOverlapsExpressionBeingCalled; + function childStartsOnTheSameLineWithElseInIfStatement(parent, child, childStartLine, sourceFile) { + if (parent.kind === 222 /* IfStatement */ && parent.elseStatement === child) { + var elseKeyword = ts.findChildOfKind(parent, 83 /* ElseKeyword */, sourceFile); + ts.Debug.assert(elseKeyword !== undefined); + var elseKeywordStartLine = getStartLineAndCharacterForNode(elseKeyword, sourceFile).line; + return elseKeywordStartLine === childStartLine; + } + return false; + } + SmartIndenter.childStartsOnTheSameLineWithElseInIfStatement = childStartsOnTheSameLineWithElseInIfStatement; + function getContainingList(node, sourceFile) { + return node.parent && getListByRange(node.getStart(sourceFile), node.getEnd(), node.parent, sourceFile); + } + SmartIndenter.getContainingList = getContainingList; + function getListByPosition(pos, node, sourceFile) { + return node && getListByRange(pos, pos, node, sourceFile); + } + function getListByRange(start, end, node, sourceFile) { + switch (node.kind) { + case 164 /* TypeReference */: + return getList(node.typeArguments); + case 188 /* ObjectLiteralExpression */: + return getList(node.properties); + case 187 /* ArrayLiteralExpression */: + return getList(node.elements); + case 168 /* TypeLiteral */: + return getList(node.members); + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 160 /* CallSignature */: + case 157 /* Constructor */: + case 166 /* ConstructorType */: + case 161 /* ConstructSignature */: + return getList(node.typeParameters) || getList(node.parameters); + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 241 /* InterfaceDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 303 /* JSDocTemplateTag */: + return getList(node.typeParameters); + case 192 /* NewExpression */: + case 191 /* CallExpression */: + return getList(node.typeArguments) || getList(node.arguments); + case 238 /* VariableDeclarationList */: + return getList(node.declarations); + case 252 /* NamedImports */: + case 256 /* NamedExports */: + return getList(node.elements); + case 184 /* ObjectBindingPattern */: + case 185 /* ArrayBindingPattern */: + return getList(node.elements); + } + function getList(list) { + return list && ts.rangeContainsStartEnd(getVisualListRange(node, list, sourceFile), start, end) ? list : undefined; + } + } + function getVisualListRange(node, list, sourceFile) { + var children = node.getChildren(sourceFile); + for (var i = 1; i < children.length - 1; i++) { + if (children[i].pos === list.pos && children[i].end === list.end) { + return { pos: children[i - 1].end, end: children[i + 1].getStart(sourceFile) }; + } + } + return list; + } + function getActualIndentationForListStartLine(list, sourceFile, options) { + if (!list) { + return -1 /* Unknown */; + } + return findColumnForFirstNonWhitespaceCharacterInLine(sourceFile.getLineAndCharacterOfPosition(list.pos), sourceFile, options); + } + function getActualIndentationForListItem(node, sourceFile, options, listIndentsChild) { + if (node.parent && node.parent.kind === 238 /* VariableDeclarationList */) { + // VariableDeclarationList has no wrapping tokens + return -1 /* Unknown */; + } + var containingList = getContainingList(node, sourceFile); + if (containingList) { + var index = containingList.indexOf(node); + if (index !== -1) { + var result = deriveActualIndentationFromList(containingList, index, sourceFile, options); + if (result !== -1 /* Unknown */) { + return result; + } + } + return getActualIndentationForListStartLine(containingList, sourceFile, options) + (listIndentsChild ? options.indentSize : 0); // TODO: GH#18217 + } + return -1 /* Unknown */; + } + function deriveActualIndentationFromList(list, index, sourceFile, options) { + ts.Debug.assert(index >= 0 && index < list.length); + var node = list[index]; + // walk toward the start of the list starting from current node and check if the line is the same for all items. + // if end line for item [i - 1] differs from the start line for item [i] - find column of the first non-whitespace character on the line of item [i] + var lineAndCharacter = getStartLineAndCharacterForNode(node, sourceFile); + for (var i = index - 1; i >= 0; i--) { + if (list[i].kind === 27 /* CommaToken */) { + continue; + } + // skip list items that ends on the same line with the current list element + var prevEndLine = sourceFile.getLineAndCharacterOfPosition(list[i].end).line; + if (prevEndLine !== lineAndCharacter.line) { + return findColumnForFirstNonWhitespaceCharacterInLine(lineAndCharacter, sourceFile, options); + } + lineAndCharacter = getStartLineAndCharacterForNode(list[i], sourceFile); + } + return -1 /* Unknown */; + } + function findColumnForFirstNonWhitespaceCharacterInLine(lineAndCharacter, sourceFile, options) { + var lineStart = sourceFile.getPositionOfLineAndCharacter(lineAndCharacter.line, 0); + return findFirstNonWhitespaceColumn(lineStart, lineStart + lineAndCharacter.character, sourceFile, options); + } + /** + * Character is the actual index of the character since the beginning of the line. + * Column - position of the character after expanding tabs to spaces. + * "0\t2$" + * value of 'character' for '$' is 3 + * value of 'column' for '$' is 6 (assuming that tab size is 4) + */ + function findFirstNonWhitespaceCharacterAndColumn(startPos, endPos, sourceFile, options) { + var character = 0; + var column = 0; + for (var pos = startPos; pos < endPos; pos++) { + var ch = sourceFile.text.charCodeAt(pos); + if (!ts.isWhiteSpaceSingleLine(ch)) { + break; + } + if (ch === 9 /* tab */) { + column += options.tabSize + (column % options.tabSize); + } + else { + column++; + } + character++; + } + return { column: column, character: character }; + } + SmartIndenter.findFirstNonWhitespaceCharacterAndColumn = findFirstNonWhitespaceCharacterAndColumn; + function findFirstNonWhitespaceColumn(startPos, endPos, sourceFile, options) { + return findFirstNonWhitespaceCharacterAndColumn(startPos, endPos, sourceFile, options).column; + } + SmartIndenter.findFirstNonWhitespaceColumn = findFirstNonWhitespaceColumn; + function nodeWillIndentChild(settings, parent, child, sourceFile, indentByDefault) { + var childKind = child ? child.kind : 0 /* Unknown */; + switch (parent.kind) { + case 221 /* ExpressionStatement */: + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 241 /* InterfaceDeclaration */: + case 243 /* EnumDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 187 /* ArrayLiteralExpression */: + case 218 /* Block */: + case 245 /* ModuleBlock */: + case 188 /* ObjectLiteralExpression */: + case 168 /* TypeLiteral */: + case 181 /* MappedType */: + case 170 /* TupleType */: + case 246 /* CaseBlock */: + case 272 /* DefaultClause */: + case 271 /* CaseClause */: + case 195 /* ParenthesizedExpression */: + case 189 /* PropertyAccessExpression */: + case 191 /* CallExpression */: + case 192 /* NewExpression */: + case 219 /* VariableStatement */: + case 254 /* ExportAssignment */: + case 230 /* ReturnStatement */: + case 205 /* ConditionalExpression */: + case 185 /* ArrayBindingPattern */: + case 184 /* ObjectBindingPattern */: + case 262 /* JsxOpeningElement */: + case 265 /* JsxOpeningFragment */: + case 261 /* JsxSelfClosingElement */: + case 270 /* JsxExpression */: + case 155 /* MethodSignature */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 151 /* Parameter */: + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + case 177 /* ParenthesizedType */: + case 193 /* TaggedTemplateExpression */: + case 201 /* AwaitExpression */: + case 256 /* NamedExports */: + case 252 /* NamedImports */: + case 257 /* ExportSpecifier */: + case 253 /* ImportSpecifier */: + case 154 /* PropertyDeclaration */: + return true; + case 237 /* VariableDeclaration */: + case 275 /* PropertyAssignment */: + if (!settings.indentMultiLineObjectLiteralBeginningOnBlankLine && sourceFile && childKind === 188 /* ObjectLiteralExpression */) { // TODO: GH#18217 + return rangeIsOnOneLine(sourceFile, child); + } + return true; + case 223 /* DoStatement */: + case 224 /* WhileStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + case 225 /* ForStatement */: + case 222 /* IfStatement */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 156 /* MethodDeclaration */: + case 197 /* ArrowFunction */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + return childKind !== 218 /* Block */; + case 255 /* ExportDeclaration */: + return childKind !== 256 /* NamedExports */; + case 249 /* ImportDeclaration */: + return childKind !== 250 /* ImportClause */ || + (!!child.namedBindings && child.namedBindings.kind !== 252 /* NamedImports */); + case 260 /* JsxElement */: + return childKind !== 263 /* JsxClosingElement */; + case 264 /* JsxFragment */: + return childKind !== 266 /* JsxClosingFragment */; + case 174 /* IntersectionType */: + case 173 /* UnionType */: + if (childKind === 168 /* TypeLiteral */) { + return false; + } + // falls through + } + // No explicit rule for given nodes so the result will follow the default value argument + return indentByDefault; + } + SmartIndenter.nodeWillIndentChild = nodeWillIndentChild; + function isControlFlowEndingStatement(kind, parent) { + switch (kind) { + case 230 /* ReturnStatement */: + case 234 /* ThrowStatement */: + case 228 /* ContinueStatement */: + case 229 /* BreakStatement */: + return parent.kind !== 218 /* Block */; + default: + return false; + } + } + /** + * True when the parent node should indent the given child by an explicit rule. + * @param isNextChild If true, we are judging indent of a hypothetical child *after* this one, not the current child. + */ + function shouldIndentChildNode(settings, parent, child, sourceFile, isNextChild) { + if (isNextChild === void 0) { isNextChild = false; } + return nodeWillIndentChild(settings, parent, child, sourceFile, /*indentByDefault*/ false) + && !(isNextChild && child && isControlFlowEndingStatement(child.kind, parent)); + } + SmartIndenter.shouldIndentChildNode = shouldIndentChildNode; + function rangeIsOnOneLine(sourceFile, range) { + var rangeStart = ts.skipTrivia(sourceFile.text, range.pos); + var startLine = sourceFile.getLineAndCharacterOfPosition(rangeStart).line; + var endLine = sourceFile.getLineAndCharacterOfPosition(range.end).line; + return startLine === endLine; + } + })(SmartIndenter = formatting.SmartIndenter || (formatting.SmartIndenter = {})); + })(formatting = ts.formatting || (ts.formatting = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var textChanges; + (function (textChanges_3) { + /** + * Currently for simplicity we store recovered positions on the node itself. + * It can be changed to side-table later if we decide that current design is too invasive. + */ + function getPos(n) { + var result = n.__pos; + ts.Debug.assert(typeof result === "number"); + return result; + } + function setPos(n, pos) { + ts.Debug.assert(typeof pos === "number"); + n.__pos = pos; + } + function getEnd(n) { + var result = n.__end; + ts.Debug.assert(typeof result === "number"); + return result; + } + function setEnd(n, end) { + ts.Debug.assert(typeof end === "number"); + n.__end = end; + } + var Position; + (function (Position) { + Position[Position["FullStart"] = 0] = "FullStart"; + Position[Position["Start"] = 1] = "Start"; + })(Position = textChanges_3.Position || (textChanges_3.Position = {})); + function skipWhitespacesAndLineBreaks(text, start) { + return ts.skipTrivia(text, start, /*stopAfterLineBreak*/ false, /*stopAtComments*/ true); + } + function hasCommentsBeforeLineBreak(text, start) { + var i = start; + while (i < text.length) { + var ch = text.charCodeAt(i); + if (ts.isWhiteSpaceSingleLine(ch)) { + i++; + continue; + } + return ch === 47 /* slash */; + } + return false; + } + textChanges_3.useNonAdjustedPositions = { + useNonAdjustedStartPosition: true, + useNonAdjustedEndPosition: true, + }; + var ChangeKind; + (function (ChangeKind) { + ChangeKind[ChangeKind["Remove"] = 0] = "Remove"; + ChangeKind[ChangeKind["ReplaceWithSingleNode"] = 1] = "ReplaceWithSingleNode"; + ChangeKind[ChangeKind["ReplaceWithMultipleNodes"] = 2] = "ReplaceWithMultipleNodes"; + ChangeKind[ChangeKind["Text"] = 3] = "Text"; + })(ChangeKind || (ChangeKind = {})); + function getAdjustedRange(sourceFile, startNode, endNode, options) { + return { pos: getAdjustedStartPosition(sourceFile, startNode, options, Position.Start), end: getAdjustedEndPosition(sourceFile, endNode, options) }; + } + function getAdjustedStartPosition(sourceFile, node, options, position) { + if (options.useNonAdjustedStartPosition) { + return node.getStart(sourceFile); + } + var fullStart = node.getFullStart(); + var start = node.getStart(sourceFile); + if (fullStart === start) { + return start; + } + var fullStartLine = ts.getLineStartPositionForPosition(fullStart, sourceFile); + var startLine = ts.getLineStartPositionForPosition(start, sourceFile); + if (startLine === fullStartLine) { + // full start and start of the node are on the same line + // a, b; + // ^ ^ + // | start + // fullstart + // when b is replaced - we usually want to keep the leading trvia + // when b is deleted - we delete it + return position === Position.Start ? start : fullStart; + } + // get start position of the line following the line that contains fullstart position + // (but only if the fullstart isn't the very beginning of the file) + var nextLineStart = fullStart > 0 ? 1 : 0; + var adjustedStartPosition = ts.getStartPositionOfLine(ts.getLineOfLocalPosition(sourceFile, fullStartLine) + nextLineStart, sourceFile); + // skip whitespaces/newlines + adjustedStartPosition = skipWhitespacesAndLineBreaks(sourceFile.text, adjustedStartPosition); + return ts.getStartPositionOfLine(ts.getLineOfLocalPosition(sourceFile, adjustedStartPosition), sourceFile); + } + function getAdjustedEndPosition(sourceFile, node, options) { + var end = node.end; + if (options.useNonAdjustedEndPosition || ts.isExpression(node)) { + return end; + } + var newEnd = ts.skipTrivia(sourceFile.text, end, /*stopAfterLineBreak*/ true); + return newEnd !== end && ts.isLineBreak(sourceFile.text.charCodeAt(newEnd - 1)) + ? newEnd + : end; + } + /** + * Checks if 'candidate' argument is a legal separator in the list that contains 'node' as an element + */ + function isSeparator(node, candidate) { + return !!candidate && !!node.parent && (candidate.kind === 27 /* CommaToken */ || (candidate.kind === 26 /* SemicolonToken */ && node.parent.kind === 188 /* ObjectLiteralExpression */)); + } + function spaces(count) { + var s = ""; + for (var i = 0; i < count; i++) { + s += " "; + } + return s; + } + var ChangeTracker = /** @class */ (function () { + /** Public for tests only. Other callers should use `ChangeTracker.with`. */ + function ChangeTracker(newLineCharacter, formatContext) { + this.newLineCharacter = newLineCharacter; + this.formatContext = formatContext; + this.changes = []; + this.newFiles = []; + this.classesWithNodesInsertedAtStart = ts.createMap(); // Set implemented as Map + this.deletedNodes = []; + } + ChangeTracker.fromContext = function (context) { + return new ChangeTracker(ts.getNewLineOrDefaultFromHost(context.host, context.formatContext.options), context.formatContext); + }; + ChangeTracker.with = function (context, cb) { + var tracker = ChangeTracker.fromContext(context); + cb(tracker); + return tracker.getChanges(); + }; + ChangeTracker.prototype.deleteRange = function (sourceFile, range) { + this.changes.push({ kind: ChangeKind.Remove, sourceFile: sourceFile, range: range }); + }; + ChangeTracker.prototype.delete = function (sourceFile, node) { + this.deletedNodes.push({ sourceFile: sourceFile, node: node }); + }; + ChangeTracker.prototype.deleteModifier = function (sourceFile, modifier) { + this.deleteRange(sourceFile, { pos: modifier.getStart(sourceFile), end: ts.skipTrivia(sourceFile.text, modifier.end, /*stopAfterLineBreak*/ true) }); + }; + ChangeTracker.prototype.deleteNodeRange = function (sourceFile, startNode, endNode, options) { + if (options === void 0) { options = {}; } + var startPosition = getAdjustedStartPosition(sourceFile, startNode, options, Position.FullStart); + var endPosition = getAdjustedEndPosition(sourceFile, endNode, options); + this.deleteRange(sourceFile, { pos: startPosition, end: endPosition }); + }; + ChangeTracker.prototype.deleteNodeRangeExcludingEnd = function (sourceFile, startNode, afterEndNode, options) { + if (options === void 0) { options = {}; } + var startPosition = getAdjustedStartPosition(sourceFile, startNode, options, Position.FullStart); + var endPosition = afterEndNode === undefined ? sourceFile.text.length : getAdjustedStartPosition(sourceFile, afterEndNode, options, Position.FullStart); + this.deleteRange(sourceFile, { pos: startPosition, end: endPosition }); + }; + ChangeTracker.prototype.replaceRange = function (sourceFile, range, newNode, options) { + if (options === void 0) { options = {}; } + this.changes.push({ kind: ChangeKind.ReplaceWithSingleNode, sourceFile: sourceFile, range: range, options: options, node: newNode }); + }; + ChangeTracker.prototype.replaceNode = function (sourceFile, oldNode, newNode, options) { + if (options === void 0) { options = textChanges_3.useNonAdjustedPositions; } + this.replaceRange(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, options), newNode, options); + }; + ChangeTracker.prototype.replaceNodeRange = function (sourceFile, startNode, endNode, newNode, options) { + if (options === void 0) { options = textChanges_3.useNonAdjustedPositions; } + this.replaceRange(sourceFile, getAdjustedRange(sourceFile, startNode, endNode, options), newNode, options); + }; + ChangeTracker.prototype.replaceRangeWithNodes = function (sourceFile, range, newNodes, options) { + if (options === void 0) { options = {}; } + this.changes.push({ kind: ChangeKind.ReplaceWithMultipleNodes, sourceFile: sourceFile, range: range, options: options, nodes: newNodes }); + }; + ChangeTracker.prototype.replaceNodeWithNodes = function (sourceFile, oldNode, newNodes, options) { + if (options === void 0) { options = textChanges_3.useNonAdjustedPositions; } + this.replaceRangeWithNodes(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, options), newNodes, options); + }; + ChangeTracker.prototype.replaceNodeWithText = function (sourceFile, oldNode, text) { + this.replaceRangeWithText(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, textChanges_3.useNonAdjustedPositions), text); + }; + ChangeTracker.prototype.replaceNodeRangeWithNodes = function (sourceFile, startNode, endNode, newNodes, options) { + if (options === void 0) { options = textChanges_3.useNonAdjustedPositions; } + this.replaceRangeWithNodes(sourceFile, getAdjustedRange(sourceFile, startNode, endNode, options), newNodes, options); + }; + ChangeTracker.prototype.nextCommaToken = function (sourceFile, node) { + var next = ts.findNextToken(node, node.parent, sourceFile); + return next && next.kind === 27 /* CommaToken */ ? next : undefined; + }; + ChangeTracker.prototype.replacePropertyAssignment = function (sourceFile, oldNode, newNode) { + var suffix = this.nextCommaToken(sourceFile, oldNode) ? "" : ("," + this.newLineCharacter); + this.replaceNode(sourceFile, oldNode, newNode, { suffix: suffix }); + }; + ChangeTracker.prototype.insertNodeAt = function (sourceFile, pos, newNode, options) { + if (options === void 0) { options = {}; } + this.replaceRange(sourceFile, ts.createRange(pos), newNode, options); + }; + ChangeTracker.prototype.insertNodesAt = function (sourceFile, pos, newNodes, options) { + if (options === void 0) { options = {}; } + this.replaceRangeWithNodes(sourceFile, ts.createRange(pos), newNodes, options); + }; + ChangeTracker.prototype.insertNodeAtTopOfFile = function (sourceFile, newNode, blankLineBetween) { + var pos = getInsertionPositionAtSourceFileTop(sourceFile); + this.insertNodeAt(sourceFile, pos, newNode, { + prefix: pos === 0 ? undefined : this.newLineCharacter, + suffix: (ts.isLineBreak(sourceFile.text.charCodeAt(pos)) ? "" : this.newLineCharacter) + (blankLineBetween ? this.newLineCharacter : ""), + }); + }; + ChangeTracker.prototype.insertNodeBefore = function (sourceFile, before, newNode, blankLineBetween) { + if (blankLineBetween === void 0) { blankLineBetween = false; } + this.insertNodeAt(sourceFile, getAdjustedStartPosition(sourceFile, before, {}, Position.Start), newNode, this.getOptionsForInsertNodeBefore(before, blankLineBetween)); + }; + ChangeTracker.prototype.insertModifierBefore = function (sourceFile, modifier, before) { + var pos = before.getStart(sourceFile); + this.insertNodeAt(sourceFile, pos, ts.createToken(modifier), { suffix: " " }); + }; + ChangeTracker.prototype.insertLastModifierBefore = function (sourceFile, modifier, before) { + if (!before.modifiers) { + this.insertModifierBefore(sourceFile, modifier, before); + return; + } + var pos = before.modifiers.end; + this.insertNodeAt(sourceFile, pos, ts.createToken(modifier), { prefix: " " }); + }; + ChangeTracker.prototype.insertCommentBeforeLine = function (sourceFile, lineNumber, position, commentText) { + var lineStartPosition = ts.getStartPositionOfLine(lineNumber, sourceFile); + var startPosition = ts.getFirstNonSpaceCharacterPosition(sourceFile.text, lineStartPosition); + // First try to see if we can put the comment on the previous line. + // We need to make sure that we are not in the middle of a string literal or a comment. + // If so, we do not want to separate the node from its comment if we can. + // Otherwise, add an extra new line immediately before the error span. + var insertAtLineStart = isValidLocationToAddComment(sourceFile, startPosition); + var token = ts.getTouchingToken(sourceFile, insertAtLineStart ? startPosition : position); + var indent = sourceFile.text.slice(lineStartPosition, startPosition); + var text = (insertAtLineStart ? "" : this.newLineCharacter) + "//" + commentText + this.newLineCharacter + indent; + this.insertText(sourceFile, token.getStart(sourceFile), text); + }; + ChangeTracker.prototype.insertJsdocCommentBefore = function (sourceFile, node, tag) { + var fnStart = node.getStart(sourceFile); + if (node.jsDoc) { + for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { + var jsdoc = _a[_i]; + this.deleteRange(sourceFile, { + pos: ts.getLineStartPositionForPosition(jsdoc.getStart(sourceFile), sourceFile), + end: getAdjustedEndPosition(sourceFile, jsdoc, /*options*/ {}) + }); + } + } + var startPosition = ts.getPrecedingNonSpaceCharacterPosition(sourceFile.text, fnStart - 1); + var indent = sourceFile.text.slice(startPosition, fnStart); + this.insertNodeAt(sourceFile, fnStart, tag, { preserveLeadingWhitespace: false, suffix: this.newLineCharacter + indent }); + }; + ChangeTracker.prototype.replaceRangeWithText = function (sourceFile, range, text) { + this.changes.push({ kind: ChangeKind.Text, sourceFile: sourceFile, range: range, text: text }); + }; + ChangeTracker.prototype.insertText = function (sourceFile, pos, text) { + this.replaceRangeWithText(sourceFile, ts.createRange(pos), text); + }; + /** Prefer this over replacing a node with another that has a type annotation, as it avoids reformatting the other parts of the node. */ + ChangeTracker.prototype.tryInsertTypeAnnotation = function (sourceFile, node, type) { + var endNode; + if (ts.isFunctionLike(node)) { + endNode = ts.findChildOfKind(node, 21 /* CloseParenToken */, sourceFile); + if (!endNode) { + if (!ts.isArrowFunction(node)) + return; // Function missing parentheses, give up + // If no `)`, is an arrow function `x => x`, so use the end of the first parameter + endNode = ts.first(node.parameters); + } + } + else { + endNode = node.kind !== 237 /* VariableDeclaration */ && node.questionToken ? node.questionToken : node.name; + } + this.insertNodeAt(sourceFile, endNode.end, type, { prefix: ": " }); + }; + ChangeTracker.prototype.insertTypeParameters = function (sourceFile, node, typeParameters) { + // If no `(`, is an arrow function `x => x`, so use the pos of the first parameter + var start = (ts.findChildOfKind(node, 20 /* OpenParenToken */, sourceFile) || ts.first(node.parameters)).getStart(sourceFile); + this.insertNodesAt(sourceFile, start, typeParameters, { prefix: "<", suffix: ">" }); + }; + ChangeTracker.prototype.getOptionsForInsertNodeBefore = function (before, doubleNewlines) { + if (ts.isStatement(before) || ts.isClassElement(before)) { + return { suffix: doubleNewlines ? this.newLineCharacter + this.newLineCharacter : this.newLineCharacter }; + } + else if (ts.isVariableDeclaration(before)) { // insert `x = 1, ` into `const x = 1, y = 2; + return { suffix: ", " }; + } + else if (ts.isParameter(before)) { + return {}; + } + else if (ts.isStringLiteral(before) && ts.isImportDeclaration(before.parent) || ts.isNamedImports(before)) { + return { suffix: ", " }; + } + return ts.Debug.failBadSyntaxKind(before); // We haven't handled this kind of node yet -- add it + }; + ChangeTracker.prototype.insertNodeAtConstructorStart = function (sourceFile, ctr, newStatement) { + var firstStatement = ts.firstOrUndefined(ctr.body.statements); + if (!firstStatement || !ctr.body.multiLine) { + this.replaceConstructorBody(sourceFile, ctr, [newStatement].concat(ctr.body.statements)); + } + else { + this.insertNodeBefore(sourceFile, firstStatement, newStatement); + } + }; + ChangeTracker.prototype.insertNodeAtConstructorEnd = function (sourceFile, ctr, newStatement) { + var lastStatement = ts.lastOrUndefined(ctr.body.statements); + if (!lastStatement || !ctr.body.multiLine) { + this.replaceConstructorBody(sourceFile, ctr, ctr.body.statements.concat([newStatement])); + } + else { + this.insertNodeAfter(sourceFile, lastStatement, newStatement); + } + }; + ChangeTracker.prototype.replaceConstructorBody = function (sourceFile, ctr, statements) { + this.replaceNode(sourceFile, ctr.body, ts.createBlock(statements, /*multiLine*/ true)); + }; + ChangeTracker.prototype.insertNodeAtEndOfScope = function (sourceFile, scope, newNode) { + var pos = getAdjustedStartPosition(sourceFile, scope.getLastToken(), {}, Position.Start); + this.insertNodeAt(sourceFile, pos, newNode, { + prefix: ts.isLineBreak(sourceFile.text.charCodeAt(scope.getLastToken().pos)) ? this.newLineCharacter : this.newLineCharacter + this.newLineCharacter, + suffix: this.newLineCharacter + }); + }; + ChangeTracker.prototype.insertNodeAtClassStart = function (sourceFile, cls, newElement) { + this.insertNodeAtStartWorker(sourceFile, cls, newElement); + }; + ChangeTracker.prototype.insertNodeAtObjectStart = function (sourceFile, obj, newElement) { + this.insertNodeAtStartWorker(sourceFile, obj, newElement); + }; + ChangeTracker.prototype.insertNodeAtStartWorker = function (sourceFile, cls, newElement) { + var clsStart = cls.getStart(sourceFile); + var indentation = ts.formatting.SmartIndenter.findFirstNonWhitespaceColumn(ts.getLineStartPositionForPosition(clsStart, sourceFile), clsStart, sourceFile, this.formatContext.options) + + this.formatContext.options.indentSize; + this.insertNodeAt(sourceFile, getMembersOrProperties(cls).pos, newElement, __assign({ indentation: indentation }, this.getInsertNodeAtStartPrefixSuffix(sourceFile, cls))); + }; + ChangeTracker.prototype.getInsertNodeAtStartPrefixSuffix = function (sourceFile, cls) { + var comma = ts.isObjectLiteralExpression(cls) ? "," : ""; + if (getMembersOrProperties(cls).length === 0) { + if (ts.addToSeen(this.classesWithNodesInsertedAtStart, ts.getNodeId(cls), { node: cls, sourceFile: sourceFile })) { + // For `class C {\n}`, don't add the trailing "\n" + var shouldSuffix = ts.positionsAreOnSameLine.apply(void 0, getClassOrObjectBraceEnds(cls, sourceFile).concat([sourceFile])); // TODO: GH#4130 remove 'as any' + return { prefix: this.newLineCharacter, suffix: comma + (shouldSuffix ? this.newLineCharacter : "") }; + } + else { + return { prefix: "", suffix: comma + this.newLineCharacter }; + } + } + else { + return { prefix: this.newLineCharacter, suffix: comma }; + } + }; + ChangeTracker.prototype.insertNodeAfterComma = function (sourceFile, after, newNode) { + var endPosition = this.insertNodeAfterWorker(sourceFile, this.nextCommaToken(sourceFile, after) || after, newNode); + this.insertNodeAt(sourceFile, endPosition, newNode, this.getInsertNodeAfterOptions(sourceFile, after)); + }; + ChangeTracker.prototype.insertNodeAfter = function (sourceFile, after, newNode) { + var endPosition = this.insertNodeAfterWorker(sourceFile, after, newNode); + this.insertNodeAt(sourceFile, endPosition, newNode, this.getInsertNodeAfterOptions(sourceFile, after)); + }; + ChangeTracker.prototype.insertNodeAtEndOfList = function (sourceFile, list, newNode) { + this.insertNodeAt(sourceFile, list.end, newNode, { prefix: ", " }); + }; + ChangeTracker.prototype.insertNodesAfter = function (sourceFile, after, newNodes) { + var endPosition = this.insertNodeAfterWorker(sourceFile, after, ts.first(newNodes)); + this.insertNodesAt(sourceFile, endPosition, newNodes, this.getInsertNodeAfterOptions(sourceFile, after)); + }; + ChangeTracker.prototype.insertNodeAfterWorker = function (sourceFile, after, newNode) { + if (needSemicolonBetween(after, newNode)) { + // check if previous statement ends with semicolon + // if not - insert semicolon to preserve the code from changing the meaning due to ASI + if (sourceFile.text.charCodeAt(after.end - 1) !== 59 /* semicolon */) { + this.replaceRange(sourceFile, ts.createRange(after.end), ts.createToken(26 /* SemicolonToken */)); + } + } + var endPosition = getAdjustedEndPosition(sourceFile, after, {}); + return endPosition; + }; + ChangeTracker.prototype.getInsertNodeAfterOptions = function (sourceFile, after) { + var options = this.getInsertNodeAfterOptionsWorker(after); + return __assign({}, options, { prefix: after.end === sourceFile.end && ts.isStatement(after) ? (options.prefix ? "\n" + options.prefix : "\n") : options.prefix }); + }; + ChangeTracker.prototype.getInsertNodeAfterOptionsWorker = function (node) { + switch (node.kind) { + case 240 /* ClassDeclaration */: + case 244 /* ModuleDeclaration */: + return { prefix: this.newLineCharacter, suffix: this.newLineCharacter }; + case 237 /* VariableDeclaration */: + case 10 /* StringLiteral */: + case 72 /* Identifier */: + return { prefix: ", " }; + case 275 /* PropertyAssignment */: + return { suffix: "," + this.newLineCharacter }; + case 85 /* ExportKeyword */: + return { prefix: " " }; + case 151 /* Parameter */: + return {}; + default: + ts.Debug.assert(ts.isStatement(node) || ts.isClassOrTypeElement(node)); // Else we haven't handled this kind of node yet -- add it + return { suffix: this.newLineCharacter }; + } + }; + ChangeTracker.prototype.insertName = function (sourceFile, node, name) { + ts.Debug.assert(!node.name); + if (node.kind === 197 /* ArrowFunction */) { + var arrow = ts.findChildOfKind(node, 37 /* EqualsGreaterThanToken */, sourceFile); + var lparen = ts.findChildOfKind(node, 20 /* OpenParenToken */, sourceFile); + if (lparen) { + // `() => {}` --> `function f() {}` + this.insertNodesAt(sourceFile, lparen.getStart(sourceFile), [ts.createToken(90 /* FunctionKeyword */), ts.createIdentifier(name)], { joiner: " " }); + deleteNode(this, sourceFile, arrow); + } + else { + // `x => {}` -> `function f(x) {}` + this.insertText(sourceFile, ts.first(node.parameters).getStart(sourceFile), "function " + name + "("); + // Replacing full range of arrow to get rid of the leading space -- replace ` =>` with `)` + this.replaceRange(sourceFile, arrow, ts.createToken(21 /* CloseParenToken */)); + } + if (node.body.kind !== 218 /* Block */) { + // `() => 0` => `function f() { return 0; }` + this.insertNodesAt(sourceFile, node.body.getStart(sourceFile), [ts.createToken(18 /* OpenBraceToken */), ts.createToken(97 /* ReturnKeyword */)], { joiner: " ", suffix: " " }); + this.insertNodesAt(sourceFile, node.body.end, [ts.createToken(26 /* SemicolonToken */), ts.createToken(19 /* CloseBraceToken */)], { joiner: " " }); + } + } + else { + var pos = ts.findChildOfKind(node, node.kind === 196 /* FunctionExpression */ ? 90 /* FunctionKeyword */ : 76 /* ClassKeyword */, sourceFile).end; + this.insertNodeAt(sourceFile, pos, ts.createIdentifier(name), { prefix: " " }); + } + }; + ChangeTracker.prototype.insertExportModifier = function (sourceFile, node) { + this.insertText(sourceFile, node.getStart(sourceFile), "export "); + }; + /** + * This function should be used to insert nodes in lists when nodes don't carry separators as the part of the node range, + * i.e. arguments in arguments lists, parameters in parameter lists etc. + * Note that separators are part of the node in statements and class elements. + */ + ChangeTracker.prototype.insertNodeInListAfter = function (sourceFile, after, newNode, containingList) { + if (containingList === void 0) { containingList = ts.formatting.SmartIndenter.getContainingList(after, sourceFile); } + if (!containingList) { + ts.Debug.fail("node is not a list element"); + return; + } + var index = ts.indexOfNode(containingList, after); + if (index < 0) { + return; + } + var end = after.getEnd(); + if (index !== containingList.length - 1) { + // any element except the last one + // use next sibling as an anchor + var nextToken = ts.getTokenAtPosition(sourceFile, after.end); + if (nextToken && isSeparator(after, nextToken)) { + // for list + // a, b, c + // create change for adding 'e' after 'a' as + // - find start of next element after a (it is b) + // - use this start as start and end position in final change + // - build text of change by formatting the text of node + separator + whitespace trivia of b + // in multiline case it will work as + // a, + // b, + // c, + // result - '*' denotes leading trivia that will be inserted after new text (displayed as '#') + // a,* + // ***insertedtext# + // ###b, + // c, + // find line and character of the next element + var lineAndCharOfNextElement = ts.getLineAndCharacterOfPosition(sourceFile, skipWhitespacesAndLineBreaks(sourceFile.text, containingList[index + 1].getFullStart())); + // find line and character of the token that precedes next element (usually it is separator) + var lineAndCharOfNextToken = ts.getLineAndCharacterOfPosition(sourceFile, nextToken.end); + var prefix = void 0; + var startPos = void 0; + if (lineAndCharOfNextToken.line === lineAndCharOfNextElement.line) { + // next element is located on the same line with separator: + // a,$$$$b + // ^ ^ + // | |-next element + // |-separator + // where $$$ is some leading trivia + // for a newly inserted node we'll maintain the same relative position comparing to separator and replace leading trivia with spaces + // a, x,$$$$b + // ^ ^ ^ + // | | |-next element + // | |-new inserted node padded with spaces + // |-separator + startPos = nextToken.end; + prefix = spaces(lineAndCharOfNextElement.character - lineAndCharOfNextToken.character); + } + else { + // next element is located on different line that separator + // let insert position be the beginning of the line that contains next element + startPos = ts.getStartPositionOfLine(lineAndCharOfNextElement.line, sourceFile); + } + // write separator and leading trivia of the next element as suffix + var suffix = "" + ts.tokenToString(nextToken.kind) + sourceFile.text.substring(nextToken.end, containingList[index + 1].getStart(sourceFile)); + this.replaceRange(sourceFile, ts.createRange(startPos, containingList[index + 1].getStart(sourceFile)), newNode, { prefix: prefix, suffix: suffix }); + } + } + else { + var afterStart = after.getStart(sourceFile); + var afterStartLinePosition = ts.getLineStartPositionForPosition(afterStart, sourceFile); + var separator = void 0; + var multilineList = false; + // insert element after the last element in the list that has more than one item + // pick the element preceding the after element to: + // - pick the separator + // - determine if list is a multiline + if (containingList.length === 1) { + // if list has only one element then we'll format is as multiline if node has comment in trailing trivia, or as singleline otherwise + // i.e. var x = 1 // this is x + // | new element will be inserted at this position + separator = 27 /* CommaToken */; + } + else { + // element has more than one element, pick separator from the list + var tokenBeforeInsertPosition = ts.findPrecedingToken(after.pos, sourceFile); + separator = isSeparator(after, tokenBeforeInsertPosition) ? tokenBeforeInsertPosition.kind : 27 /* CommaToken */; + // determine if list is multiline by checking lines of after element and element that precedes it. + var afterMinusOneStartLinePosition = ts.getLineStartPositionForPosition(containingList[index - 1].getStart(sourceFile), sourceFile); + multilineList = afterMinusOneStartLinePosition !== afterStartLinePosition; + } + if (hasCommentsBeforeLineBreak(sourceFile.text, after.end)) { + // in this case we'll always treat containing list as multiline + multilineList = true; + } + if (multilineList) { + // insert separator immediately following the 'after' node to preserve comments in trailing trivia + this.replaceRange(sourceFile, ts.createRange(end), ts.createToken(separator)); + // use the same indentation as 'after' item + var indentation = ts.formatting.SmartIndenter.findFirstNonWhitespaceColumn(afterStartLinePosition, afterStart, sourceFile, this.formatContext.options); + // insert element before the line break on the line that contains 'after' element + var insertPos = ts.skipTrivia(sourceFile.text, end, /*stopAfterLineBreak*/ true, /*stopAtComments*/ false); + if (insertPos !== end && ts.isLineBreak(sourceFile.text.charCodeAt(insertPos - 1))) { + insertPos--; + } + this.replaceRange(sourceFile, ts.createRange(insertPos), newNode, { indentation: indentation, prefix: this.newLineCharacter }); + } + else { + this.replaceRange(sourceFile, ts.createRange(end), newNode, { prefix: ts.tokenToString(separator) + " " }); + } + } + }; + ChangeTracker.prototype.finishClassesWithNodesInsertedAtStart = function () { + var _this = this; + this.classesWithNodesInsertedAtStart.forEach(function (_a) { + var node = _a.node, sourceFile = _a.sourceFile; + var _b = getClassOrObjectBraceEnds(node, sourceFile), openBraceEnd = _b[0], closeBraceEnd = _b[1]; + // For `class C { }` remove the whitespace inside the braces. + if (ts.positionsAreOnSameLine(openBraceEnd, closeBraceEnd, sourceFile) && openBraceEnd !== closeBraceEnd - 1) { + _this.deleteRange(sourceFile, ts.createRange(openBraceEnd, closeBraceEnd - 1)); + } + }); + }; + ChangeTracker.prototype.finishDeleteDeclarations = function () { + var _this = this; + var deletedNodesInLists = new ts.NodeSet(); // Stores nodes in lists that we already deleted. Used to avoid deleting `, ` twice in `a, b`. + var _loop_17 = function (sourceFile, node) { + if (!this_1.deletedNodes.some(function (d) { return d.sourceFile === sourceFile && ts.rangeContainsRangeExclusive(d.node, node); })) { + if (ts.isArray(node)) { + this_1.deleteRange(sourceFile, ts.rangeOfTypeParameters(node)); + } + else { + deleteDeclaration.deleteDeclaration(this_1, deletedNodesInLists, sourceFile, node); + } + } + }; + var this_1 = this; + for (var _i = 0, _a = this.deletedNodes; _i < _a.length; _i++) { + var _b = _a[_i], sourceFile = _b.sourceFile, node = _b.node; + _loop_17(sourceFile, node); + } + deletedNodesInLists.forEach(function (node) { + var sourceFile = node.getSourceFile(); + var list = ts.formatting.SmartIndenter.getContainingList(node, sourceFile); + if (node !== ts.last(list)) + return; + var lastNonDeletedIndex = ts.findLastIndex(list, function (n) { return !deletedNodesInLists.has(n); }, list.length - 2); + if (lastNonDeletedIndex !== -1) { + _this.deleteRange(sourceFile, { pos: list[lastNonDeletedIndex].end, end: startPositionToDeleteNodeInList(sourceFile, list[lastNonDeletedIndex + 1]) }); + } + }); + }; + /** + * Note: after calling this, the TextChanges object must be discarded! + * @param validate only for tests + * The reason we must validate as part of this method is that `getNonFormattedText` changes the node's positions, + * so we can only call this once and can't get the non-formatted text separately. + */ + ChangeTracker.prototype.getChanges = function (validate) { + this.finishDeleteDeclarations(); + this.finishClassesWithNodesInsertedAtStart(); + var changes = changesToText.getTextChangesFromChanges(this.changes, this.newLineCharacter, this.formatContext, validate); + for (var _i = 0, _a = this.newFiles; _i < _a.length; _i++) { + var _b = _a[_i], oldFile = _b.oldFile, fileName = _b.fileName, statements = _b.statements; + changes.push(changesToText.newFileChanges(oldFile, fileName, statements, this.newLineCharacter, this.formatContext)); + } + return changes; + }; + ChangeTracker.prototype.createNewFile = function (oldFile, fileName, statements) { + this.newFiles.push({ oldFile: oldFile, fileName: fileName, statements: statements }); + }; + return ChangeTracker; + }()); + textChanges_3.ChangeTracker = ChangeTracker; + // find first non-whitespace position in the leading trivia of the node + function startPositionToDeleteNodeInList(sourceFile, node) { + return ts.skipTrivia(sourceFile.text, getAdjustedStartPosition(sourceFile, node, {}, Position.FullStart), /*stopAfterLineBreak*/ false, /*stopAtComments*/ true); + } + function getClassOrObjectBraceEnds(cls, sourceFile) { + return [ts.findChildOfKind(cls, 18 /* OpenBraceToken */, sourceFile).end, ts.findChildOfKind(cls, 19 /* CloseBraceToken */, sourceFile).end]; + } + function getMembersOrProperties(cls) { + return ts.isObjectLiteralExpression(cls) ? cls.properties : cls.members; + } + function getNewFileText(statements, scriptKind, newLineCharacter, formatContext) { + return changesToText.newFileChangesWorker(/*oldFile*/ undefined, scriptKind, statements, newLineCharacter, formatContext); + } + textChanges_3.getNewFileText = getNewFileText; + var changesToText; + (function (changesToText) { + function getTextChangesFromChanges(changes, newLineCharacter, formatContext, validate) { + return ts.group(changes, function (c) { return c.sourceFile.path; }).map(function (changesInFile) { + var sourceFile = changesInFile[0].sourceFile; + // order changes by start position + // If the start position is the same, put the shorter range first, since an empty range (x, x) may precede (x, y) but not vice-versa. + var normalized = ts.stableSort(changesInFile, function (a, b) { return (a.range.pos - b.range.pos) || (a.range.end - b.range.end); }); + var _loop_18 = function (i) { + ts.Debug.assert(normalized[i].range.end <= normalized[i + 1].range.pos, "Changes overlap", function () { + return JSON.stringify(normalized[i].range) + " and " + JSON.stringify(normalized[i + 1].range); + }); + }; + // verify that change intervals do not overlap, except possibly at end points. + for (var i = 0; i < normalized.length - 1; i++) { + _loop_18(i); + } + var textChanges = normalized.map(function (c) { + return ts.createTextChange(ts.createTextSpanFromRange(c.range), computeNewText(c, sourceFile, newLineCharacter, formatContext, validate)); + }); + return { fileName: sourceFile.fileName, textChanges: textChanges }; + }); + } + changesToText.getTextChangesFromChanges = getTextChangesFromChanges; + function newFileChanges(oldFile, fileName, statements, newLineCharacter, formatContext) { + var text = newFileChangesWorker(oldFile, ts.getScriptKindFromFileName(fileName), statements, newLineCharacter, formatContext); + return { fileName: fileName, textChanges: [ts.createTextChange(ts.createTextSpan(0, 0), text)], isNewFile: true }; + } + changesToText.newFileChanges = newFileChanges; + function newFileChangesWorker(oldFile, scriptKind, statements, newLineCharacter, formatContext) { + // TODO: this emits the file, parses it back, then formats it that -- may be a less roundabout way to do this + var nonFormattedText = statements.map(function (s) { return getNonformattedText(s, oldFile, newLineCharacter).text; }).join(newLineCharacter); + var sourceFile = ts.createSourceFile("any file name", nonFormattedText, 6 /* ESNext */, /*setParentNodes*/ true, scriptKind); + var changes = ts.formatting.formatDocument(sourceFile, formatContext); + return applyChanges(nonFormattedText, changes) + newLineCharacter; + } + changesToText.newFileChangesWorker = newFileChangesWorker; + function computeNewText(change, sourceFile, newLineCharacter, formatContext, validate) { + if (change.kind === ChangeKind.Remove) { + return ""; + } + if (change.kind === ChangeKind.Text) { + return change.text; + } + var _a = change.options, options = _a === void 0 ? {} : _a, pos = change.range.pos; + var format = function (n) { return getFormattedTextOfNode(n, sourceFile, pos, options, newLineCharacter, formatContext, validate); }; + var text = change.kind === ChangeKind.ReplaceWithMultipleNodes + ? change.nodes.map(function (n) { return ts.removeSuffix(format(n), newLineCharacter); }).join(change.options.joiner || newLineCharacter) // TODO: GH#18217 + : format(change.node); + // strip initial indentation (spaces or tabs) if text will be inserted in the middle of the line + var noIndent = (options.preserveLeadingWhitespace || options.indentation !== undefined || ts.getLineStartPositionForPosition(pos, sourceFile) === pos) ? text : text.replace(/^\s+/, ""); + return (options.prefix || "") + noIndent + (options.suffix || ""); + } + /** Note: this may mutate `nodeIn`. */ + function getFormattedTextOfNode(nodeIn, sourceFile, pos, _a, newLineCharacter, formatContext, validate) { + var indentation = _a.indentation, prefix = _a.prefix, delta = _a.delta; + var _b = getNonformattedText(nodeIn, sourceFile, newLineCharacter), node = _b.node, text = _b.text; + if (validate) + validate(node, text); + var formatOptions = formatContext.options; + var initialIndentation = indentation !== undefined + ? indentation + : ts.formatting.SmartIndenter.getIndentation(pos, sourceFile, formatOptions, prefix === newLineCharacter || ts.getLineStartPositionForPosition(pos, sourceFile) === pos); + if (delta === undefined) { + delta = ts.formatting.SmartIndenter.shouldIndentChildNode(formatContext.options, nodeIn) ? (formatOptions.indentSize || 0) : 0; + } + var file = { text: text, getLineAndCharacterOfPosition: function (pos) { return ts.getLineAndCharacterOfPosition(this, pos); } }; + var changes = ts.formatting.formatNodeGivenIndentation(node, file, sourceFile.languageVariant, initialIndentation, delta, formatContext); + return applyChanges(text, changes); + } + /** Note: output node may be mutated input node. */ + function getNonformattedText(node, sourceFile, newLineCharacter) { + var writer = new Writer(newLineCharacter); + var newLine = newLineCharacter === "\n" ? 1 /* LineFeed */ : 0 /* CarriageReturnLineFeed */; + ts.createPrinter({ newLine: newLine, neverAsciiEscape: true }, writer).writeNode(4 /* Unspecified */, node, sourceFile, writer); + return { text: writer.getText(), node: assignPositionsToNode(node) }; + } + changesToText.getNonformattedText = getNonformattedText; + })(changesToText || (changesToText = {})); + function applyChanges(text, changes) { + for (var i = changes.length - 1; i >= 0; i--) { + var _a = changes[i], span = _a.span, newText = _a.newText; + text = "" + text.substring(0, span.start) + newText + text.substring(ts.textSpanEnd(span)); + } + return text; + } + textChanges_3.applyChanges = applyChanges; + function isTrivia(s) { + return ts.skipTrivia(s, 0) === s.length; + } + function assignPositionsToNode(node) { + var visited = ts.visitEachChild(node, assignPositionsToNode, ts.nullTransformationContext, assignPositionsToNodeArray, assignPositionsToNode); // TODO: GH#18217 + // create proxy node for non synthesized nodes + var newNode = ts.nodeIsSynthesized(visited) ? visited : Object.create(visited); + newNode.pos = getPos(node); + newNode.end = getEnd(node); + return newNode; + } + function assignPositionsToNodeArray(nodes, visitor, test, start, count) { + var visited = ts.visitNodes(nodes, visitor, test, start, count); + if (!visited) { + return visited; + } + // clone nodearray if necessary + var nodeArray = visited === nodes ? ts.createNodeArray(visited.slice(0)) : visited; + nodeArray.pos = getPos(nodes); + nodeArray.end = getEnd(nodes); + return nodeArray; + } + var Writer = /** @class */ (function () { + function Writer(newLine) { + var _this = this; + this.lastNonTriviaPosition = 0; + this.writer = ts.createTextWriter(newLine); + this.onEmitNode = function (hint, node, printCallback) { + if (node) { + setPos(node, _this.lastNonTriviaPosition); + } + printCallback(hint, node); + if (node) { + setEnd(node, _this.lastNonTriviaPosition); + } + }; + this.onBeforeEmitNodeArray = function (nodes) { + if (nodes) { + setPos(nodes, _this.lastNonTriviaPosition); + } + }; + this.onAfterEmitNodeArray = function (nodes) { + if (nodes) { + setEnd(nodes, _this.lastNonTriviaPosition); + } + }; + this.onBeforeEmitToken = function (node) { + if (node) { + setPos(node, _this.lastNonTriviaPosition); + } + }; + this.onAfterEmitToken = function (node) { + if (node) { + setEnd(node, _this.lastNonTriviaPosition); + } + }; + } + Writer.prototype.setLastNonTriviaPosition = function (s, force) { + if (force || !isTrivia(s)) { + this.lastNonTriviaPosition = this.writer.getTextPos(); + var i = 0; + while (ts.isWhiteSpaceLike(s.charCodeAt(s.length - i - 1))) { + i++; + } + // trim trailing whitespaces + this.lastNonTriviaPosition -= i; + } + }; + Writer.prototype.write = function (s) { + this.writer.write(s); + this.setLastNonTriviaPosition(s, /*force*/ false); + }; + Writer.prototype.writeComment = function (s) { + this.writer.writeComment(s); + }; + Writer.prototype.writeKeyword = function (s) { + this.writer.writeKeyword(s); + this.setLastNonTriviaPosition(s, /*force*/ false); + }; + Writer.prototype.writeOperator = function (s) { + this.writer.writeOperator(s); + this.setLastNonTriviaPosition(s, /*force*/ false); + }; + Writer.prototype.writePunctuation = function (s) { + this.writer.writePunctuation(s); + this.setLastNonTriviaPosition(s, /*force*/ false); + }; + Writer.prototype.writeTrailingSemicolon = function (s) { + this.writer.writeTrailingSemicolon(s); + this.setLastNonTriviaPosition(s, /*force*/ false); + }; + Writer.prototype.writeParameter = function (s) { + this.writer.writeParameter(s); + this.setLastNonTriviaPosition(s, /*force*/ false); + }; + Writer.prototype.writeProperty = function (s) { + this.writer.writeProperty(s); + this.setLastNonTriviaPosition(s, /*force*/ false); + }; + Writer.prototype.writeSpace = function (s) { + this.writer.writeSpace(s); + this.setLastNonTriviaPosition(s, /*force*/ false); + }; + Writer.prototype.writeStringLiteral = function (s) { + this.writer.writeStringLiteral(s); + this.setLastNonTriviaPosition(s, /*force*/ false); + }; + Writer.prototype.writeSymbol = function (s, sym) { + this.writer.writeSymbol(s, sym); + this.setLastNonTriviaPosition(s, /*force*/ false); + }; + Writer.prototype.writeLine = function () { + this.writer.writeLine(); + }; + Writer.prototype.increaseIndent = function () { + this.writer.increaseIndent(); + }; + Writer.prototype.decreaseIndent = function () { + this.writer.decreaseIndent(); + }; + Writer.prototype.getText = function () { + return this.writer.getText(); + }; + Writer.prototype.rawWrite = function (s) { + this.writer.rawWrite(s); + this.setLastNonTriviaPosition(s, /*force*/ false); + }; + Writer.prototype.writeLiteral = function (s) { + this.writer.writeLiteral(s); + this.setLastNonTriviaPosition(s, /*force*/ true); + }; + Writer.prototype.getTextPos = function () { + return this.writer.getTextPos(); + }; + Writer.prototype.getLine = function () { + return this.writer.getLine(); + }; + Writer.prototype.getColumn = function () { + return this.writer.getColumn(); + }; + Writer.prototype.getIndent = function () { + return this.writer.getIndent(); + }; + Writer.prototype.isAtStartOfLine = function () { + return this.writer.isAtStartOfLine(); + }; + Writer.prototype.clear = function () { + this.writer.clear(); + this.lastNonTriviaPosition = 0; + }; + return Writer; + }()); + function getInsertionPositionAtSourceFileTop(sourceFile) { + var lastPrologue; + for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { + var node = _a[_i]; + if (ts.isPrologueDirective(node)) { + lastPrologue = node; + } + else { + break; + } + } + var position = 0; + var text = sourceFile.text; + if (lastPrologue) { + position = lastPrologue.end; + advancePastLineBreak(); + return position; + } + var shebang = ts.getShebang(text); + if (shebang !== undefined) { + position = shebang.length; + advancePastLineBreak(); + } + // For a source file, it is possible there are detached comments we should not skip + var ranges = ts.getLeadingCommentRanges(text, position); + if (!ranges) + return position; + // However we should still skip a pinned comment at the top + if (ranges.length && ranges[0].kind === 3 /* MultiLineCommentTrivia */ && ts.isPinnedComment(text, ranges[0].pos)) { + position = ranges[0].end; + advancePastLineBreak(); + ranges = ranges.slice(1); + } + // As well as any triple slash references + for (var _b = 0, ranges_1 = ranges; _b < ranges_1.length; _b++) { + var range = ranges_1[_b]; + if (range.kind === 2 /* SingleLineCommentTrivia */ && ts.isRecognizedTripleSlashComment(text, range.pos, range.end)) { + position = range.end; + advancePastLineBreak(); + continue; + } + break; + } + return position; + function advancePastLineBreak() { + if (position < text.length) { + var charCode = text.charCodeAt(position); + if (ts.isLineBreak(charCode)) { + position++; + if (position < text.length && charCode === 13 /* carriageReturn */ && text.charCodeAt(position) === 10 /* lineFeed */) { + position++; + } + } + } + } + } + function isValidLocationToAddComment(sourceFile, position) { + return !ts.isInComment(sourceFile, position) && !ts.isInString(sourceFile, position) && !ts.isInTemplateString(sourceFile, position) && !ts.isInJSXText(sourceFile, position); + } + textChanges_3.isValidLocationToAddComment = isValidLocationToAddComment; + function needSemicolonBetween(a, b) { + return (ts.isPropertySignature(a) || ts.isPropertyDeclaration(a)) && ts.isClassOrTypeElement(b) && b.name.kind === 149 /* ComputedPropertyName */ + || ts.isStatementButNotDeclaration(a) && ts.isStatementButNotDeclaration(b); // TODO: only if b would start with a `(` or `[` + } + var deleteDeclaration; + (function (deleteDeclaration_1) { + function deleteDeclaration(changes, deletedNodesInLists, sourceFile, node) { + switch (node.kind) { + case 151 /* Parameter */: { + var oldFunction = node.parent; + if (ts.isArrowFunction(oldFunction) && + oldFunction.parameters.length === 1 && + !ts.findChildOfKind(oldFunction, 20 /* OpenParenToken */, sourceFile)) { + // Lambdas with exactly one parameter are special because, after removal, there + // must be an empty parameter list (i.e. `()`) and this won't necessarily be the + // case if the parameter is simply removed (e.g. in `x => 1`). + changes.replaceNodeWithText(sourceFile, node, "()"); + } + else { + deleteNodeInList(changes, deletedNodesInLists, sourceFile, node); + } + break; + } + case 249 /* ImportDeclaration */: + deleteNode(changes, sourceFile, node, + // For first import, leave header comment in place + node === sourceFile.imports[0].parent ? { useNonAdjustedStartPosition: true, useNonAdjustedEndPosition: false } : undefined); + break; + case 186 /* BindingElement */: + var pattern = node.parent; + var preserveComma = pattern.kind === 185 /* ArrayBindingPattern */ && node !== ts.last(pattern.elements); + if (preserveComma) { + deleteNode(changes, sourceFile, node); + } + else { + deleteNodeInList(changes, deletedNodesInLists, sourceFile, node); + } + break; + case 237 /* VariableDeclaration */: + deleteVariableDeclaration(changes, deletedNodesInLists, sourceFile, node); + break; + case 150 /* TypeParameter */: + deleteNodeInList(changes, deletedNodesInLists, sourceFile, node); + break; + case 253 /* ImportSpecifier */: + var namedImports = node.parent; + if (namedImports.elements.length === 1) { + deleteImportBinding(changes, sourceFile, namedImports); + } + else { + deleteNodeInList(changes, deletedNodesInLists, sourceFile, node); + } + break; + case 251 /* NamespaceImport */: + deleteImportBinding(changes, sourceFile, node); + break; + default: + if (ts.isImportClause(node.parent) && node.parent.name === node) { + deleteDefaultImport(changes, sourceFile, node.parent); + } + else if (ts.isCallLikeExpression(node.parent)) { + deleteNodeInList(changes, deletedNodesInLists, sourceFile, node); + } + else { + deleteNode(changes, sourceFile, node, node.kind === 26 /* SemicolonToken */ ? { useNonAdjustedEndPosition: true } : undefined); + } + } + } + deleteDeclaration_1.deleteDeclaration = deleteDeclaration; + function deleteDefaultImport(changes, sourceFile, importClause) { + if (!importClause.namedBindings) { + // Delete the whole import + deleteNode(changes, sourceFile, importClause.parent); + } + else { + // import |d,| * as ns from './file' + var start = importClause.name.getStart(sourceFile); + var nextToken = ts.getTokenAtPosition(sourceFile, importClause.name.end); + if (nextToken && nextToken.kind === 27 /* CommaToken */) { + // shift first non-whitespace position after comma to the start position of the node + var end = ts.skipTrivia(sourceFile.text, nextToken.end, /*stopAfterLineBreaks*/ false, /*stopAtComments*/ true); + changes.deleteRange(sourceFile, { pos: start, end: end }); + } + else { + deleteNode(changes, sourceFile, importClause.name); + } + } + } + function deleteImportBinding(changes, sourceFile, node) { + if (node.parent.name) { + // Delete named imports while preserving the default import + // import d|, * as ns| from './file' + // import d|, { a }| from './file' + var previousToken = ts.Debug.assertDefined(ts.getTokenAtPosition(sourceFile, node.pos - 1)); + changes.deleteRange(sourceFile, { pos: previousToken.getStart(sourceFile), end: node.end }); + } + else { + // Delete the entire import declaration + // |import * as ns from './file'| + // |import { a } from './file'| + var importDecl = ts.getAncestor(node, 249 /* ImportDeclaration */); + deleteNode(changes, sourceFile, importDecl); + } + } + function deleteVariableDeclaration(changes, deletedNodesInLists, sourceFile, node) { + var parent = node.parent; + if (parent.kind === 274 /* CatchClause */) { + // TODO: There's currently no unused diagnostic for this, could be a suggestion + changes.deleteNodeRange(sourceFile, ts.findChildOfKind(parent, 20 /* OpenParenToken */, sourceFile), ts.findChildOfKind(parent, 21 /* CloseParenToken */, sourceFile)); + return; + } + if (parent.declarations.length !== 1) { + deleteNodeInList(changes, deletedNodesInLists, sourceFile, node); + return; + } + var gp = parent.parent; + switch (gp.kind) { + case 227 /* ForOfStatement */: + case 226 /* ForInStatement */: + changes.replaceNode(sourceFile, node, ts.createObjectLiteral()); + break; + case 225 /* ForStatement */: + deleteNode(changes, sourceFile, parent); + break; + case 219 /* VariableStatement */: + deleteNode(changes, sourceFile, gp); + break; + default: + ts.Debug.assertNever(gp); + } + } + })(deleteDeclaration || (deleteDeclaration = {})); + /** Warning: This deletes comments too. See `copyComments` in `convertFunctionToEs6Class`. */ + // Exported for tests only! (TODO: improve tests to not need this) + function deleteNode(changes, sourceFile, node, options) { + if (options === void 0) { options = {}; } + var startPosition = getAdjustedStartPosition(sourceFile, node, options, Position.FullStart); + var endPosition = getAdjustedEndPosition(sourceFile, node, options); + changes.deleteRange(sourceFile, { pos: startPosition, end: endPosition }); + } + textChanges_3.deleteNode = deleteNode; + function deleteNodeInList(changes, deletedNodesInLists, sourceFile, node) { + var containingList = ts.Debug.assertDefined(ts.formatting.SmartIndenter.getContainingList(node, sourceFile)); + var index = ts.indexOfNode(containingList, node); + ts.Debug.assert(index !== -1); + if (containingList.length === 1) { + deleteNode(changes, sourceFile, node); + return; + } + // Note: We will only delete a comma *after* a node. This will leave a trailing comma if we delete the last node. + // That's handled in the end by `finishTrailingCommaAfterDeletingNodesInList`. + ts.Debug.assert(!deletedNodesInLists.has(node), "Deleting a node twice"); + deletedNodesInLists.add(node); + changes.deleteRange(sourceFile, { + pos: startPositionToDeleteNodeInList(sourceFile, node), + end: index === containingList.length - 1 ? getAdjustedEndPosition(sourceFile, node, {}) : startPositionToDeleteNodeInList(sourceFile, containingList[index + 1]), + }); + } + })(textChanges = ts.textChanges || (ts.textChanges = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var errorCodeToFixes = ts.createMultiMap(); + var fixIdToRegistration = ts.createMap(); + function diagnosticToString(diag) { + return ts.isArray(diag) + ? ts.formatStringFromArgs(ts.getLocaleSpecificMessage(diag[0]), diag.slice(1)) + : ts.getLocaleSpecificMessage(diag); + } + function createCodeFixActionNoFixId(fixName, changes, description) { + return createCodeFixActionWorker(fixName, diagnosticToString(description), changes, /*fixId*/ undefined, /*fixAllDescription*/ undefined); + } + codefix.createCodeFixActionNoFixId = createCodeFixActionNoFixId; + function createCodeFixAction(fixName, changes, description, fixId, fixAllDescription, command) { + return createCodeFixActionWorker(fixName, diagnosticToString(description), changes, fixId, diagnosticToString(fixAllDescription), command); + } + codefix.createCodeFixAction = createCodeFixAction; + function createCodeFixActionWorker(fixName, description, changes, fixId, fixAllDescription, command) { + return { fixName: fixName, description: description, changes: changes, fixId: fixId, fixAllDescription: fixAllDescription, commands: command ? [command] : undefined }; + } + function registerCodeFix(reg) { + for (var _i = 0, _a = reg.errorCodes; _i < _a.length; _i++) { + var error = _a[_i]; + errorCodeToFixes.add(String(error), reg); + } + if (reg.fixIds) { + for (var _b = 0, _c = reg.fixIds; _b < _c.length; _b++) { + var fixId = _c[_b]; + ts.Debug.assert(!fixIdToRegistration.has(fixId)); + fixIdToRegistration.set(fixId, reg); + } + } + } + codefix.registerCodeFix = registerCodeFix; + function getSupportedErrorCodes() { + return ts.arrayFrom(errorCodeToFixes.keys()); + } + codefix.getSupportedErrorCodes = getSupportedErrorCodes; + function getFixes(context) { + return ts.flatMap(errorCodeToFixes.get(String(context.errorCode)) || ts.emptyArray, function (f) { return f.getCodeActions(context); }); + } + codefix.getFixes = getFixes; + function getAllFixes(context) { + // Currently fixId is always a string. + return fixIdToRegistration.get(ts.cast(context.fixId, ts.isString)).getAllCodeActions(context); + } + codefix.getAllFixes = getAllFixes; + function createCombinedCodeActions(changes, commands) { + return { changes: changes, commands: commands }; + } + codefix.createCombinedCodeActions = createCombinedCodeActions; + function createFileTextChanges(fileName, textChanges) { + return { fileName: fileName, textChanges: textChanges }; + } + codefix.createFileTextChanges = createFileTextChanges; + function codeFixAll(context, errorCodes, use) { + var commands = []; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return eachDiagnostic(context, errorCodes, function (diag) { return use(t, diag, commands); }); }); + return createCombinedCodeActions(changes, commands.length === 0 ? undefined : commands); + } + codefix.codeFixAll = codeFixAll; + function eachDiagnostic(_a, errorCodes, cb) { + var program = _a.program, sourceFile = _a.sourceFile, cancellationToken = _a.cancellationToken; + for (var _i = 0, _b = program.getSemanticDiagnostics(sourceFile, cancellationToken).concat(ts.computeSuggestionDiagnostics(sourceFile, program, cancellationToken)); _i < _b.length; _i++) { + var diag = _b[_i]; + if (ts.contains(errorCodes, diag.code)) { + cb(diag); + } + } + } + codefix.eachDiagnostic = eachDiagnostic; + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var refactor; + (function (refactor_1) { + // A map with the refactor code as key, the refactor itself as value + // e.g. nonSuggestableRefactors[refactorCode] -> the refactor you want + var refactors = ts.createMap(); + /** @param name An unique code associated with each refactor. Does not have to be human-readable. */ + function registerRefactor(name, refactor) { + refactors.set(name, refactor); + } + refactor_1.registerRefactor = registerRefactor; + function getApplicableRefactors(context) { + return ts.arrayFrom(ts.flatMapIterator(refactors.values(), function (refactor) { + return context.cancellationToken && context.cancellationToken.isCancellationRequested() ? undefined : refactor.getAvailableActions(context); + })); + } + refactor_1.getApplicableRefactors = getApplicableRefactors; + function getEditsForRefactor(context, refactorName, actionName) { + var refactor = refactors.get(refactorName); + return refactor && refactor.getEditsForAction(context, actionName); + } + refactor_1.getEditsForRefactor = getEditsForRefactor; + })(refactor = ts.refactor || (ts.refactor = {})); + function getRefactorContextSpan(_a) { + var startPosition = _a.startPosition, endPosition = _a.endPosition; + return ts.createTextSpanFromBounds(startPosition, endPosition === undefined ? startPosition : endPosition); + } + ts.getRefactorContextSpan = getRefactorContextSpan; +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "addConvertToUnknownForNonOverlappingTypes"; + var errorCodes = [ts.Diagnostics.Conversion_of_type_0_to_type_1_may_be_a_mistake_because_neither_type_sufficiently_overlaps_with_the_other_If_this_was_intentional_convert_the_expression_to_unknown_first.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return makeChange(t, context.sourceFile, context.span.start); }); + return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Add_unknown_conversion_for_non_overlapping_types, fixId, ts.Diagnostics.Add_unknown_to_all_conversions_of_non_overlapping_types)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { return makeChange(changes, diag.file, diag.start); }); }, + }); + function makeChange(changeTracker, sourceFile, pos) { + var token = ts.getTokenAtPosition(sourceFile, pos); + var assertion = ts.Debug.assertDefined(ts.findAncestor(token, function (n) { return ts.isAsExpression(n) || ts.isTypeAssertion(n); })); + var replacement = ts.isAsExpression(assertion) + ? ts.createAsExpression(assertion.expression, ts.createKeywordTypeNode(143 /* UnknownKeyword */)) + : ts.createTypeAssertion(ts.createKeywordTypeNode(143 /* UnknownKeyword */), assertion.expression); + changeTracker.replaceNode(sourceFile, assertion.expression, replacement); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "addMissingInvocationForDecorator"; + var errorCodes = [ts.Diagnostics._0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write_0.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return makeChange(t, context.sourceFile, context.span.start); }); + return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Call_decorator_expression, fixId, ts.Diagnostics.Add_to_all_uncalled_decorators)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { return makeChange(changes, diag.file, diag.start); }); }, + }); + function makeChange(changeTracker, sourceFile, pos) { + var token = ts.getTokenAtPosition(sourceFile, pos); + var decorator = ts.findAncestor(token, ts.isDecorator); + ts.Debug.assert(!!decorator, "Expected position to be owned by a decorator."); + var replacement = ts.createCall(decorator.expression, /*typeArguments*/ undefined, /*argumentsArray*/ undefined); + changeTracker.replaceNode(sourceFile, decorator.expression, replacement); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "annotateWithTypeFromJSDoc"; + var errorCodes = [ts.Diagnostics.JSDoc_types_may_be_moved_to_TypeScript_types.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var decl = getDeclaration(context.sourceFile, context.span.start); + if (!decl) + return; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, context.sourceFile, decl); }); + return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Annotate_with_type_from_JSDoc, fixId, ts.Diagnostics.Annotate_everything_with_types_from_JSDoc)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var decl = getDeclaration(diag.file, diag.start); + if (decl) + doChange(changes, diag.file, decl); + }); }, + }); + function getDeclaration(file, pos) { + var name = ts.getTokenAtPosition(file, pos); + // For an arrow function with no name, 'name' lands on the first parameter. + return ts.tryCast(ts.isParameter(name.parent) ? name.parent.parent : name.parent, parameterShouldGetTypeFromJSDoc); + } + function parameterShouldGetTypeFromJSDoc(node) { + return isDeclarationWithType(node) && hasUsableJSDoc(node); + } + codefix.parameterShouldGetTypeFromJSDoc = parameterShouldGetTypeFromJSDoc; + function hasUsableJSDoc(decl) { + return ts.isFunctionLikeDeclaration(decl) + ? decl.parameters.some(hasUsableJSDoc) || (!decl.type && !!ts.getJSDocReturnType(decl)) + : !decl.type && !!ts.getJSDocType(decl); + } + function doChange(changes, sourceFile, decl) { + if (ts.isFunctionLikeDeclaration(decl) && (ts.getJSDocReturnType(decl) || decl.parameters.some(function (p) { return !!ts.getJSDocType(p); }))) { + if (!decl.typeParameters) { + var typeParameters = ts.getJSDocTypeParameterDeclarations(decl); + if (typeParameters.length) + changes.insertTypeParameters(sourceFile, decl, typeParameters); + } + var needParens = ts.isArrowFunction(decl) && !ts.findChildOfKind(decl, 20 /* OpenParenToken */, sourceFile); + if (needParens) + changes.insertNodeBefore(sourceFile, ts.first(decl.parameters), ts.createToken(20 /* OpenParenToken */)); + for (var _i = 0, _a = decl.parameters; _i < _a.length; _i++) { + var param = _a[_i]; + if (!param.type) { + var paramType = ts.getJSDocType(param); + if (paramType) + changes.tryInsertTypeAnnotation(sourceFile, param, transformJSDocType(paramType)); + } + } + if (needParens) + changes.insertNodeAfter(sourceFile, ts.last(decl.parameters), ts.createToken(21 /* CloseParenToken */)); + if (!decl.type) { + var returnType = ts.getJSDocReturnType(decl); + if (returnType) + changes.tryInsertTypeAnnotation(sourceFile, decl, transformJSDocType(returnType)); + } + } + else { + var jsdocType = ts.Debug.assertDefined(ts.getJSDocType(decl)); // If not defined, shouldn't have been an error to fix + ts.Debug.assert(!decl.type); // If defined, shouldn't have been an error to fix. + changes.tryInsertTypeAnnotation(sourceFile, decl, transformJSDocType(jsdocType)); + } + } + function isDeclarationWithType(node) { + return ts.isFunctionLikeDeclaration(node) || + node.kind === 237 /* VariableDeclaration */ || + node.kind === 153 /* PropertySignature */ || + node.kind === 154 /* PropertyDeclaration */; + } + function transformJSDocType(node) { + switch (node.kind) { + case 284 /* JSDocAllType */: + case 285 /* JSDocUnknownType */: + return ts.createTypeReferenceNode("any", ts.emptyArray); + case 288 /* JSDocOptionalType */: + return transformJSDocOptionalType(node); + case 287 /* JSDocNonNullableType */: + return transformJSDocType(node.type); + case 286 /* JSDocNullableType */: + return transformJSDocNullableType(node); + case 290 /* JSDocVariadicType */: + return transformJSDocVariadicType(node); + case 289 /* JSDocFunctionType */: + return transformJSDocFunctionType(node); + case 164 /* TypeReference */: + return transformJSDocTypeReference(node); + default: + var visited = ts.visitEachChild(node, transformJSDocType, /*context*/ undefined); // TODO: GH#18217 + ts.setEmitFlags(visited, 1 /* SingleLine */); + return visited; + } + } + function transformJSDocOptionalType(node) { + return ts.createUnionTypeNode([ts.visitNode(node.type, transformJSDocType), ts.createTypeReferenceNode("undefined", ts.emptyArray)]); + } + function transformJSDocNullableType(node) { + return ts.createUnionTypeNode([ts.visitNode(node.type, transformJSDocType), ts.createTypeReferenceNode("null", ts.emptyArray)]); + } + function transformJSDocVariadicType(node) { + return ts.createArrayTypeNode(ts.visitNode(node.type, transformJSDocType)); + } + function transformJSDocFunctionType(node) { + return ts.createFunctionTypeNode(ts.emptyArray, node.parameters.map(transformJSDocParameter), node.type); + } + function transformJSDocParameter(node) { + var index = node.parent.parameters.indexOf(node); + var isRest = node.type.kind === 290 /* JSDocVariadicType */ && index === node.parent.parameters.length - 1; // TODO: GH#18217 + var name = node.name || (isRest ? "rest" : "arg" + index); + var dotdotdot = isRest ? ts.createToken(25 /* DotDotDotToken */) : node.dotDotDotToken; + return ts.createParameter(node.decorators, node.modifiers, dotdotdot, name, node.questionToken, ts.visitNode(node.type, transformJSDocType), node.initializer); + } + function transformJSDocTypeReference(node) { + var name = node.typeName; + var args = node.typeArguments; + if (ts.isIdentifier(node.typeName)) { + if (ts.isJSDocIndexSignature(node)) { + return transformJSDocIndexSignature(node); + } + var text = node.typeName.text; + switch (node.typeName.text) { + case "String": + case "Boolean": + case "Object": + case "Number": + text = text.toLowerCase(); + break; + case "array": + case "date": + case "promise": + text = text[0].toUpperCase() + text.slice(1); + break; + } + name = ts.createIdentifier(text); + if ((text === "Array" || text === "Promise") && !node.typeArguments) { + args = ts.createNodeArray([ts.createTypeReferenceNode("any", ts.emptyArray)]); + } + else { + args = ts.visitNodes(node.typeArguments, transformJSDocType); + } + } + return ts.createTypeReferenceNode(name, args); + } + function transformJSDocIndexSignature(node) { + var index = ts.createParameter( + /*decorators*/ undefined, + /*modifiers*/ undefined, + /*dotDotDotToken*/ undefined, node.typeArguments[0].kind === 135 /* NumberKeyword */ ? "n" : "s", + /*questionToken*/ undefined, ts.createTypeReferenceNode(node.typeArguments[0].kind === 135 /* NumberKeyword */ ? "number" : "string", []), + /*initializer*/ undefined); + var indexSignature = ts.createTypeLiteralNode([ts.createIndexSignature(/*decorators*/ undefined, /*modifiers*/ undefined, [index], node.typeArguments[1])]); + ts.setEmitFlags(indexSignature, 1 /* SingleLine */); + return indexSignature; + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "inferFromUsage"; + var errorCodes = [ + // Variable declarations + ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code, + // Variable uses + ts.Diagnostics.Variable_0_implicitly_has_an_1_type.code, + // Parameter declarations + ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code, + ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code, + // Get Accessor declarations + ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation.code, + ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type.code, + // Set Accessor declarations + ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code, + // Property declarations + ts.Diagnostics.Member_0_implicitly_has_an_1_type.code, + //// Suggestions + // Variable declarations + ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_but_a_better_type_may_be_inferred_from_usage.code, + // Variable uses + ts.Diagnostics.Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code, + // Parameter declarations + ts.Diagnostics.Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code, + ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage.code, + // Get Accessor declarations + ts.Diagnostics.Property_0_implicitly_has_type_any_but_a_better_type_for_its_get_accessor_may_be_inferred_from_usage.code, + ts.Diagnostics._0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage.code, + // Set Accessor declarations + ts.Diagnostics.Property_0_implicitly_has_type_any_but_a_better_type_for_its_set_accessor_may_be_inferred_from_usage.code, + // Property declarations + ts.Diagnostics.Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code, + ]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var sourceFile = context.sourceFile, program = context.program, start = context.span.start, errorCode = context.errorCode, cancellationToken = context.cancellationToken, host = context.host; + var token = ts.getTokenAtPosition(sourceFile, start); + var declaration; + var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { declaration = doChange(changes, sourceFile, token, errorCode, program, cancellationToken, /*markSeen*/ ts.returnTrue, host); }); + var name = declaration && ts.getNameOfDeclaration(declaration); + return !name || changes.length === 0 ? undefined + : [codefix.createCodeFixAction(fixId, changes, [getDiagnostic(errorCode, token), name.getText(sourceFile)], fixId, ts.Diagnostics.Infer_all_types_from_usage)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { + var sourceFile = context.sourceFile, program = context.program, cancellationToken = context.cancellationToken, host = context.host; + var markSeen = ts.nodeSeenTracker(); + return codefix.codeFixAll(context, errorCodes, function (changes, err) { + doChange(changes, sourceFile, ts.getTokenAtPosition(err.file, err.start), err.code, program, cancellationToken, markSeen, host); + }); + }, + }); + function getDiagnostic(errorCode, token) { + switch (errorCode) { + case ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code: + case ts.Diagnostics.Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code: + return ts.isSetAccessorDeclaration(ts.getContainingFunction(token)) ? ts.Diagnostics.Infer_type_of_0_from_usage : ts.Diagnostics.Infer_parameter_types_from_usage; // TODO: GH#18217 + case ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code: + case ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage.code: + return ts.Diagnostics.Infer_parameter_types_from_usage; + default: + return ts.Diagnostics.Infer_type_of_0_from_usage; + } + } + /** Map suggestion code to error code */ + function mapSuggestionDiagnostic(errorCode) { + switch (errorCode) { + case ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_but_a_better_type_may_be_inferred_from_usage.code: + return ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code; + case ts.Diagnostics.Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code: + return ts.Diagnostics.Variable_0_implicitly_has_an_1_type.code; + case ts.Diagnostics.Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code: + return ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code; + case ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage.code: + return ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code; + case ts.Diagnostics.Property_0_implicitly_has_type_any_but_a_better_type_for_its_get_accessor_may_be_inferred_from_usage.code: + return ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation.code; + case ts.Diagnostics._0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage.code: + return ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type.code; + case ts.Diagnostics.Property_0_implicitly_has_type_any_but_a_better_type_for_its_set_accessor_may_be_inferred_from_usage.code: + return ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code; + case ts.Diagnostics.Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code: + return ts.Diagnostics.Member_0_implicitly_has_an_1_type.code; + } + return errorCode; + } + function doChange(changes, sourceFile, token, errorCode, program, cancellationToken, markSeen, host) { + if (!ts.isParameterPropertyModifier(token.kind) && token.kind !== 72 /* Identifier */ && token.kind !== 25 /* DotDotDotToken */ && token.kind !== 100 /* ThisKeyword */) { + return undefined; + } + var parent = token.parent; + errorCode = mapSuggestionDiagnostic(errorCode); + switch (errorCode) { + // Variable and Property declarations + case ts.Diagnostics.Member_0_implicitly_has_an_1_type.code: + case ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code: + if ((ts.isVariableDeclaration(parent) && markSeen(parent)) || ts.isPropertyDeclaration(parent) || ts.isPropertySignature(parent)) { // handle bad location + annotateVariableDeclaration(changes, sourceFile, parent, program, host, cancellationToken); + return parent; + } + if (ts.isPropertyAccessExpression(parent)) { + var type = inferTypeForVariableFromUsage(parent.name, program, cancellationToken); + var typeNode = getTypeNodeIfAccessible(type, parent, program, host); + if (typeNode) { + // Note that the codefix will never fire with an existing `@type` tag, so there is no need to merge tags + var typeTag = ts.createJSDocTypeTag(ts.createJSDocTypeExpression(typeNode), /*comment*/ ""); + addJSDocTags(changes, sourceFile, ts.cast(parent.parent.parent, ts.isExpressionStatement), [typeTag]); + } + return parent; + } + return undefined; + case ts.Diagnostics.Variable_0_implicitly_has_an_1_type.code: { + var symbol = program.getTypeChecker().getSymbolAtLocation(token); + if (symbol && symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && markSeen(symbol.valueDeclaration)) { + annotateVariableDeclaration(changes, sourceFile, symbol.valueDeclaration, program, host, cancellationToken); + return symbol.valueDeclaration; + } + return undefined; + } + } + var containingFunction = ts.getContainingFunction(token); + if (containingFunction === undefined) { + return undefined; + } + switch (errorCode) { + // Parameter declarations + case ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code: + if (ts.isSetAccessorDeclaration(containingFunction)) { + annotateSetAccessor(changes, sourceFile, containingFunction, program, host, cancellationToken); + return containingFunction; + } + // falls through + case ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code: + if (markSeen(containingFunction)) { + var param = ts.cast(parent, ts.isParameter); + annotateParameters(changes, sourceFile, param, containingFunction, program, host, cancellationToken); + return param; + } + return undefined; + // Get Accessor declarations + case ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation.code: + case ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type.code: + if (ts.isGetAccessorDeclaration(containingFunction) && ts.isIdentifier(containingFunction.name)) { + annotate(changes, sourceFile, containingFunction, inferTypeForVariableFromUsage(containingFunction.name, program, cancellationToken), program, host); + return containingFunction; + } + return undefined; + // Set Accessor declarations + case ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code: + if (ts.isSetAccessorDeclaration(containingFunction)) { + annotateSetAccessor(changes, sourceFile, containingFunction, program, host, cancellationToken); + return containingFunction; + } + return undefined; + default: + return ts.Debug.fail(String(errorCode)); + } + } + function annotateVariableDeclaration(changes, sourceFile, declaration, program, host, cancellationToken) { + if (ts.isIdentifier(declaration.name)) { + annotate(changes, sourceFile, declaration, inferTypeForVariableFromUsage(declaration.name, program, cancellationToken), program, host); + } + } + function annotateParameters(changes, sourceFile, parameterDeclaration, containingFunction, program, host, cancellationToken) { + if (!ts.isIdentifier(parameterDeclaration.name)) { + return; + } + var parameterInferences = inferTypeForParametersFromUsage(containingFunction, sourceFile, program, cancellationToken) || + containingFunction.parameters.map(function (p) { return ({ + declaration: p, + type: ts.isIdentifier(p.name) ? inferTypeForVariableFromUsage(p.name, program, cancellationToken) : program.getTypeChecker().getAnyType() + }); }); + ts.Debug.assert(containingFunction.parameters.length === parameterInferences.length); + if (ts.isInJSFile(containingFunction)) { + annotateJSDocParameters(changes, sourceFile, parameterInferences, program, host); + } + else { + var needParens = ts.isArrowFunction(containingFunction) && !ts.findChildOfKind(containingFunction, 20 /* OpenParenToken */, sourceFile); + if (needParens) + changes.insertNodeBefore(sourceFile, ts.first(containingFunction.parameters), ts.createToken(20 /* OpenParenToken */)); + for (var _i = 0, parameterInferences_1 = parameterInferences; _i < parameterInferences_1.length; _i++) { + var _a = parameterInferences_1[_i], declaration = _a.declaration, type = _a.type; + if (declaration && !declaration.type && !declaration.initializer) { + annotate(changes, sourceFile, declaration, type, program, host); + } + } + if (needParens) + changes.insertNodeAfter(sourceFile, ts.last(containingFunction.parameters), ts.createToken(21 /* CloseParenToken */)); + } + } + function annotateSetAccessor(changes, sourceFile, setAccessorDeclaration, program, host, cancellationToken) { + var param = ts.firstOrUndefined(setAccessorDeclaration.parameters); + if (param && ts.isIdentifier(setAccessorDeclaration.name) && ts.isIdentifier(param.name)) { + var type = inferTypeForVariableFromUsage(setAccessorDeclaration.name, program, cancellationToken); + if (type === program.getTypeChecker().getAnyType()) { + type = inferTypeForVariableFromUsage(param.name, program, cancellationToken); + } + if (ts.isInJSFile(setAccessorDeclaration)) { + annotateJSDocParameters(changes, sourceFile, [{ declaration: param, type: type }], program, host); + } + else { + annotate(changes, sourceFile, param, type, program, host); + } + } + } + function annotate(changes, sourceFile, declaration, type, program, host) { + var typeNode = getTypeNodeIfAccessible(type, declaration, program, host); + if (typeNode) { + if (ts.isInJSFile(sourceFile) && declaration.kind !== 153 /* PropertySignature */) { + var parent = ts.isVariableDeclaration(declaration) ? ts.tryCast(declaration.parent.parent, ts.isVariableStatement) : declaration; + if (!parent) { + return; + } + var typeExpression = ts.createJSDocTypeExpression(typeNode); + var typeTag = ts.isGetAccessorDeclaration(declaration) ? ts.createJSDocReturnTag(typeExpression, "") : ts.createJSDocTypeTag(typeExpression, ""); + addJSDocTags(changes, sourceFile, parent, [typeTag]); + } + else { + changes.tryInsertTypeAnnotation(sourceFile, declaration, typeNode); + } + } + } + function annotateJSDocParameters(changes, sourceFile, parameterInferences, program, host) { + var signature = parameterInferences.length && parameterInferences[0].declaration.parent; + if (!signature) { + return; + } + var paramTags = ts.mapDefined(parameterInferences, function (inference) { + var param = inference.declaration; + // only infer parameters that have (1) no type and (2) an accessible inferred type + if (param.initializer || ts.getJSDocType(param) || !ts.isIdentifier(param.name)) + return; + var typeNode = inference.type && getTypeNodeIfAccessible(inference.type, param, program, host); + var name = ts.getSynthesizedClone(param.name); + ts.setEmitFlags(name, 1536 /* NoComments */ | 2048 /* NoNestedComments */); + return typeNode && ts.createJSDocParamTag(name, !!inference.isOptional, ts.createJSDocTypeExpression(typeNode), ""); + }); + addJSDocTags(changes, sourceFile, signature, paramTags); + } + function addJSDocTags(changes, sourceFile, parent, newTags) { + var comments = ts.mapDefined(parent.jsDoc, function (j) { return j.comment; }); + var oldTags = ts.flatMapToMutable(parent.jsDoc, function (j) { return j.tags; }); + var unmergedNewTags = newTags.filter(function (newTag) { return !oldTags || !oldTags.some(function (tag, i) { + var merged = tryMergeJsdocTags(tag, newTag); + if (merged) + oldTags[i] = merged; + return !!merged; + }); }); + var tag = ts.createJSDocComment(comments.join("\n"), ts.createNodeArray((oldTags || ts.emptyArray).concat(unmergedNewTags))); + changes.insertJsdocCommentBefore(sourceFile, parent, tag); + } + function tryMergeJsdocTags(oldTag, newTag) { + if (oldTag.kind !== newTag.kind) { + return undefined; + } + switch (oldTag.kind) { + case 299 /* JSDocParameterTag */: { + var oldParam = oldTag; + var newParam = newTag; + return ts.isIdentifier(oldParam.name) && ts.isIdentifier(newParam.name) && oldParam.name.escapedText === newParam.name.escapedText + ? ts.createJSDocParamTag(newParam.name, newParam.isBracketed, newParam.typeExpression, oldParam.comment) + : undefined; + } + case 300 /* JSDocReturnTag */: + return ts.createJSDocReturnTag(newTag.typeExpression, oldTag.comment); + } + } + function getTypeNodeIfAccessible(type, enclosingScope, program, host) { + var checker = program.getTypeChecker(); + var typeIsAccessible = true; + var notAccessible = function () { typeIsAccessible = false; }; + var res = checker.typeToTypeNode(type, enclosingScope, /*flags*/ undefined, { + trackSymbol: function (symbol, declaration, meaning) { + // TODO: GH#18217 + typeIsAccessible = typeIsAccessible && checker.isSymbolAccessible(symbol, declaration, meaning, /*shouldComputeAliasToMarkVisible*/ false).accessibility === 0 /* Accessible */; + }, + reportInaccessibleThisError: notAccessible, + reportPrivateInBaseOfClassExpression: notAccessible, + reportInaccessibleUniqueSymbolError: notAccessible, + moduleResolverHost: { + readFile: host.readFile, + fileExists: host.fileExists, + directoryExists: host.directoryExists, + getSourceFiles: program.getSourceFiles, + getCurrentDirectory: program.getCurrentDirectory, + getCommonSourceDirectory: program.getCommonSourceDirectory, + } + }); + return typeIsAccessible ? res : undefined; + } + function getReferences(token, program, cancellationToken) { + // Position shouldn't matter since token is not a SourceFile. + return ts.mapDefined(ts.FindAllReferences.getReferenceEntriesForNode(-1, token, program, program.getSourceFiles(), cancellationToken), function (entry) { + return entry.kind !== 0 /* Span */ ? ts.tryCast(entry.node, ts.isIdentifier) : undefined; + }); + } + function inferTypeForVariableFromUsage(token, program, cancellationToken) { + var references = getReferences(token, program, cancellationToken); + var checker = program.getTypeChecker(); + var types = InferFromReference.inferTypesFromReferences(references, checker, cancellationToken); + return InferFromReference.unifyFromContext(types, checker); + } + function inferTypeForParametersFromUsage(containingFunction, sourceFile, program, cancellationToken) { + var searchToken; + switch (containingFunction.kind) { + case 157 /* Constructor */: + searchToken = ts.findChildOfKind(containingFunction, 124 /* ConstructorKeyword */, sourceFile); + break; + case 197 /* ArrowFunction */: + case 196 /* FunctionExpression */: + var parent = containingFunction.parent; + searchToken = ts.isVariableDeclaration(parent) && ts.isIdentifier(parent.name) ? + parent.name : + containingFunction.name; + break; + case 239 /* FunctionDeclaration */: + case 156 /* MethodDeclaration */: + searchToken = containingFunction.name; + break; + } + if (searchToken) { + return InferFromReference.inferTypeForParametersFromReferences(getReferences(searchToken, program, cancellationToken), containingFunction, program, cancellationToken); + } + } + var InferFromReference; + (function (InferFromReference) { + function inferTypesFromReferences(references, checker, cancellationToken) { + var usageContext = {}; + for (var _i = 0, references_1 = references; _i < references_1.length; _i++) { + var reference = references_1[_i]; + cancellationToken.throwIfCancellationRequested(); + inferTypeFromContext(reference, checker, usageContext); + } + return inferFromContext(usageContext, checker); + } + InferFromReference.inferTypesFromReferences = inferTypesFromReferences; + function inferTypeForParametersFromReferences(references, declaration, program, cancellationToken) { + var checker = program.getTypeChecker(); + if (references.length === 0) { + return undefined; + } + if (!declaration.parameters) { + return undefined; + } + var usageContext = {}; + for (var _i = 0, references_2 = references; _i < references_2.length; _i++) { + var reference = references_2[_i]; + cancellationToken.throwIfCancellationRequested(); + inferTypeFromContext(reference, checker, usageContext); + } + var callContexts = (usageContext.constructContexts || []).concat(usageContext.callContexts || []); + return declaration.parameters.map(function (parameter, parameterIndex) { + var types = []; + var isRest = ts.isRestParameter(parameter); + var isOptional = false; + for (var _i = 0, callContexts_1 = callContexts; _i < callContexts_1.length; _i++) { + var callContext = callContexts_1[_i]; + if (callContext.argumentTypes.length <= parameterIndex) { + isOptional = ts.isInJSFile(declaration); + types.push(checker.getUndefinedType()); + } + else if (isRest) { + for (var i = parameterIndex; i < callContext.argumentTypes.length; i++) { + types.push(checker.getBaseTypeOfLiteralType(callContext.argumentTypes[i])); + } + } + else { + types.push(checker.getBaseTypeOfLiteralType(callContext.argumentTypes[parameterIndex])); + } + } + if (ts.isIdentifier(parameter.name)) { + var inferred = inferTypesFromReferences(getReferences(parameter.name, program, cancellationToken), checker, cancellationToken); + types.push.apply(types, (isRest ? ts.mapDefined(inferred, checker.getElementTypeOfArrayType) : inferred)); + } + var type = unifyFromContext(types, checker); + return { + type: isRest ? checker.createArrayType(type) : type, + isOptional: isOptional && !isRest, + declaration: parameter + }; + }); + } + InferFromReference.inferTypeForParametersFromReferences = inferTypeForParametersFromReferences; + function inferTypeFromContext(node, checker, usageContext) { + while (ts.isRightSideOfQualifiedNameOrPropertyAccess(node)) { + node = node.parent; + } + switch (node.parent.kind) { + case 203 /* PostfixUnaryExpression */: + usageContext.isNumber = true; + break; + case 202 /* PrefixUnaryExpression */: + inferTypeFromPrefixUnaryExpressionContext(node.parent, usageContext); + break; + case 204 /* BinaryExpression */: + inferTypeFromBinaryExpressionContext(node, node.parent, checker, usageContext); + break; + case 271 /* CaseClause */: + case 272 /* DefaultClause */: + inferTypeFromSwitchStatementLabelContext(node.parent, checker, usageContext); + break; + case 191 /* CallExpression */: + case 192 /* NewExpression */: + if (node.parent.expression === node) { + inferTypeFromCallExpressionContext(node.parent, checker, usageContext); + } + else { + inferTypeFromContextualType(node, checker, usageContext); + } + break; + case 189 /* PropertyAccessExpression */: + inferTypeFromPropertyAccessExpressionContext(node.parent, checker, usageContext); + break; + case 190 /* ElementAccessExpression */: + inferTypeFromPropertyElementExpressionContext(node.parent, node, checker, usageContext); + break; + case 237 /* VariableDeclaration */: { + var _a = node.parent, name = _a.name, initializer = _a.initializer; + if (node === name) { + if (initializer) { // This can happen for `let x = null;` which still has an implicit-any error. + addCandidateType(usageContext, checker.getTypeAtLocation(initializer)); + } + break; + } + } + // falls through + default: + return inferTypeFromContextualType(node, checker, usageContext); + } + } + function inferTypeFromContextualType(node, checker, usageContext) { + if (ts.isExpressionNode(node)) { + addCandidateType(usageContext, checker.getContextualType(node)); + } + } + function inferTypeFromPrefixUnaryExpressionContext(node, usageContext) { + switch (node.operator) { + case 44 /* PlusPlusToken */: + case 45 /* MinusMinusToken */: + case 39 /* MinusToken */: + case 53 /* TildeToken */: + usageContext.isNumber = true; + break; + case 38 /* PlusToken */: + usageContext.isNumberOrString = true; + break; + // case SyntaxKind.ExclamationToken: + // no inferences here; + } + } + function inferTypeFromBinaryExpressionContext(node, parent, checker, usageContext) { + switch (parent.operatorToken.kind) { + // ExponentiationOperator + case 41 /* AsteriskAsteriskToken */: + // MultiplicativeOperator + case 40 /* AsteriskToken */: + case 42 /* SlashToken */: + case 43 /* PercentToken */: + // ShiftOperator + case 46 /* LessThanLessThanToken */: + case 47 /* GreaterThanGreaterThanToken */: + case 48 /* GreaterThanGreaterThanGreaterThanToken */: + // BitwiseOperator + case 49 /* AmpersandToken */: + case 50 /* BarToken */: + case 51 /* CaretToken */: + // CompoundAssignmentOperator + case 61 /* MinusEqualsToken */: + case 63 /* AsteriskAsteriskEqualsToken */: + case 62 /* AsteriskEqualsToken */: + case 64 /* SlashEqualsToken */: + case 65 /* PercentEqualsToken */: + case 69 /* AmpersandEqualsToken */: + case 70 /* BarEqualsToken */: + case 71 /* CaretEqualsToken */: + case 66 /* LessThanLessThanEqualsToken */: + case 68 /* GreaterThanGreaterThanGreaterThanEqualsToken */: + case 67 /* GreaterThanGreaterThanEqualsToken */: + // AdditiveOperator + case 39 /* MinusToken */: + // RelationalOperator + case 28 /* LessThanToken */: + case 31 /* LessThanEqualsToken */: + case 30 /* GreaterThanToken */: + case 32 /* GreaterThanEqualsToken */: + var operandType = checker.getTypeAtLocation(parent.left === node ? parent.right : parent.left); + if (operandType.flags & 1056 /* EnumLike */) { + addCandidateType(usageContext, operandType); + } + else { + usageContext.isNumber = true; + } + break; + case 60 /* PlusEqualsToken */: + case 38 /* PlusToken */: + var otherOperandType = checker.getTypeAtLocation(parent.left === node ? parent.right : parent.left); + if (otherOperandType.flags & 1056 /* EnumLike */) { + addCandidateType(usageContext, otherOperandType); + } + else if (otherOperandType.flags & 296 /* NumberLike */) { + usageContext.isNumber = true; + } + else if (otherOperandType.flags & 132 /* StringLike */) { + usageContext.isString = true; + } + else { + usageContext.isNumberOrString = true; + } + break; + // AssignmentOperators + case 59 /* EqualsToken */: + case 33 /* EqualsEqualsToken */: + case 35 /* EqualsEqualsEqualsToken */: + case 36 /* ExclamationEqualsEqualsToken */: + case 34 /* ExclamationEqualsToken */: + addCandidateType(usageContext, checker.getTypeAtLocation(parent.left === node ? parent.right : parent.left)); + break; + case 93 /* InKeyword */: + if (node === parent.left) { + usageContext.isString = true; + } + break; + // LogicalOperator + case 55 /* BarBarToken */: + if (node === parent.left && + (node.parent.parent.kind === 237 /* VariableDeclaration */ || ts.isAssignmentExpression(node.parent.parent, /*excludeCompoundAssignment*/ true))) { + // var x = x || {}; + // TODO: use getFalsyflagsOfType + addCandidateType(usageContext, checker.getTypeAtLocation(parent.right)); + } + break; + case 54 /* AmpersandAmpersandToken */: + case 27 /* CommaToken */: + case 94 /* InstanceOfKeyword */: + // nothing to infer here + break; + } + } + function inferTypeFromSwitchStatementLabelContext(parent, checker, usageContext) { + addCandidateType(usageContext, checker.getTypeAtLocation(parent.parent.parent.expression)); + } + function inferTypeFromCallExpressionContext(parent, checker, usageContext) { + var callContext = { + argumentTypes: [], + returnType: {} + }; + if (parent.arguments) { + for (var _i = 0, _a = parent.arguments; _i < _a.length; _i++) { + var argument = _a[_i]; + callContext.argumentTypes.push(checker.getTypeAtLocation(argument)); + } + } + inferTypeFromContext(parent, checker, callContext.returnType); + if (parent.kind === 191 /* CallExpression */) { + (usageContext.callContexts || (usageContext.callContexts = [])).push(callContext); + } + else { + (usageContext.constructContexts || (usageContext.constructContexts = [])).push(callContext); + } + } + function inferTypeFromPropertyAccessExpressionContext(parent, checker, usageContext) { + var name = ts.escapeLeadingUnderscores(parent.name.text); + if (!usageContext.properties) { + usageContext.properties = ts.createUnderscoreEscapedMap(); + } + var propertyUsageContext = usageContext.properties.get(name) || {}; + inferTypeFromContext(parent, checker, propertyUsageContext); + usageContext.properties.set(name, propertyUsageContext); + } + function inferTypeFromPropertyElementExpressionContext(parent, node, checker, usageContext) { + if (node === parent.argumentExpression) { + usageContext.isNumberOrString = true; + return; + } + else { + var indexType = checker.getTypeAtLocation(parent.argumentExpression); + var indexUsageContext = {}; + inferTypeFromContext(parent, checker, indexUsageContext); + if (indexType.flags & 296 /* NumberLike */) { + usageContext.numberIndexContext = indexUsageContext; + } + else { + usageContext.stringIndexContext = indexUsageContext; + } + } + } + function removeLowPriorityInferences(inferences, priorities) { + var toRemove = []; + for (var _i = 0, inferences_2 = inferences; _i < inferences_2.length; _i++) { + var i = inferences_2[_i]; + for (var _a = 0, priorities_1 = priorities; _a < priorities_1.length; _a++) { + var _b = priorities_1[_a], high = _b.high, low = _b.low; + if (high(i)) { + ts.Debug.assert(!low(i)); + toRemove.push(low); + } + } + } + return inferences.filter(function (i) { return toRemove.every(function (f) { return !f(i); }); }); + } + function unifyFromContext(inferences, checker, fallback) { + if (fallback === void 0) { fallback = checker.getAnyType(); } + if (!inferences.length) + return fallback; + // 1. string or number individually override string | number + // 2. non-any, non-void overrides any or void + // 3. non-nullable, non-any, non-void, non-anonymous overrides anonymous types + var stringNumber = checker.getUnionType([checker.getStringType(), checker.getNumberType()]); + var priorities = [ + { + high: function (t) { return t === checker.getStringType() || t === checker.getNumberType(); }, + low: function (t) { return t === stringNumber; } + }, + { + high: function (t) { return !(t.flags & (1 /* Any */ | 16384 /* Void */)); }, + low: function (t) { return !!(t.flags & (1 /* Any */ | 16384 /* Void */)); } + }, + { + high: function (t) { return !(t.flags & (98304 /* Nullable */ | 1 /* Any */ | 16384 /* Void */)) && !(checker.getObjectFlags(t) & 16 /* Anonymous */); }, + low: function (t) { return !!(checker.getObjectFlags(t) & 16 /* Anonymous */); } + } + ]; + var good = removeLowPriorityInferences(inferences, priorities); + var anons = good.filter(function (i) { return checker.getObjectFlags(i) & 16 /* Anonymous */; }); + if (anons.length) { + good = good.filter(function (i) { return !(checker.getObjectFlags(i) & 16 /* Anonymous */); }); + good.push(unifyAnonymousTypes(anons, checker)); + } + return checker.getWidenedType(checker.getUnionType(good)); + } + InferFromReference.unifyFromContext = unifyFromContext; + function unifyAnonymousTypes(anons, checker) { + if (anons.length === 1) { + return anons[0]; + } + var calls = []; + var constructs = []; + var stringIndices = []; + var numberIndices = []; + var stringIndexReadonly = false; + var numberIndexReadonly = false; + var props = ts.createMultiMap(); + for (var _i = 0, anons_1 = anons; _i < anons_1.length; _i++) { + var anon = anons_1[_i]; + for (var _a = 0, _b = checker.getPropertiesOfType(anon); _a < _b.length; _a++) { + var p = _b[_a]; + props.add(p.name, checker.getTypeOfSymbolAtLocation(p, p.valueDeclaration)); + } + calls.push.apply(calls, checker.getSignaturesOfType(anon, 0 /* Call */)); + constructs.push.apply(constructs, checker.getSignaturesOfType(anon, 1 /* Construct */)); + if (anon.stringIndexInfo) { + stringIndices.push(anon.stringIndexInfo.type); + stringIndexReadonly = stringIndexReadonly || anon.stringIndexInfo.isReadonly; + } + if (anon.numberIndexInfo) { + numberIndices.push(anon.numberIndexInfo.type); + numberIndexReadonly = numberIndexReadonly || anon.numberIndexInfo.isReadonly; + } + } + var members = ts.mapEntries(props, function (name, types) { + var isOptional = types.length < anons.length ? 16777216 /* Optional */ : 0; + var s = checker.createSymbol(4 /* Property */ | isOptional, name); + s.type = checker.getUnionType(types); + return [name, s]; + }); + return checker.createAnonymousType(anons[0].symbol, members, calls, constructs, stringIndices.length ? checker.createIndexInfo(checker.getUnionType(stringIndices), stringIndexReadonly) : undefined, numberIndices.length ? checker.createIndexInfo(checker.getUnionType(numberIndices), numberIndexReadonly) : undefined); + } + function inferFromContext(usageContext, checker) { + var types = []; + if (usageContext.isNumber) { + types.push(checker.getNumberType()); + } + if (usageContext.isString) { + types.push(checker.getStringType()); + } + if (usageContext.isNumberOrString) { + types.push(checker.getUnionType([checker.getStringType(), checker.getNumberType()])); + } + types.push.apply(types, (usageContext.candidateTypes || []).map(function (t) { return checker.getBaseTypeOfLiteralType(t); })); + if (usageContext.properties && hasCallContext(usageContext.properties.get("then"))) { + var paramType = getParameterTypeFromCallContexts(0, usageContext.properties.get("then").callContexts, /*isRestParameter*/ false, checker); // TODO: GH#18217 + var types_19 = paramType.getCallSignatures().map(function (c) { return c.getReturnType(); }); + types_19.push(checker.createPromiseType(types_19.length ? checker.getUnionType(types_19, 2 /* Subtype */) : checker.getAnyType())); + } + else if (usageContext.properties && hasCallContext(usageContext.properties.get("push"))) { + types.push(checker.createArrayType(getParameterTypeFromCallContexts(0, usageContext.properties.get("push").callContexts, /*isRestParameter*/ false, checker))); + } + if (usageContext.numberIndexContext) { + types.push(checker.createArrayType(recur(usageContext.numberIndexContext))); + } + else if (usageContext.properties || usageContext.callContexts || usageContext.constructContexts || usageContext.stringIndexContext) { + var members_6 = ts.createUnderscoreEscapedMap(); + var callSignatures = []; + var constructSignatures = []; + var stringIndexInfo = void 0; + if (usageContext.properties) { + usageContext.properties.forEach(function (context, name) { + var symbol = checker.createSymbol(4 /* Property */, name); + symbol.type = recur(context); + members_6.set(name, symbol); + }); + } + if (usageContext.callContexts) { + for (var _i = 0, _a = usageContext.callContexts; _i < _a.length; _i++) { + var callContext = _a[_i]; + callSignatures.push(getSignatureFromCallContext(callContext, checker)); + } + } + if (usageContext.constructContexts) { + for (var _b = 0, _c = usageContext.constructContexts; _b < _c.length; _b++) { + var constructContext = _c[_b]; + constructSignatures.push(getSignatureFromCallContext(constructContext, checker)); + } + } + if (usageContext.stringIndexContext) { + stringIndexInfo = checker.createIndexInfo(recur(usageContext.stringIndexContext), /*isReadonly*/ false); + } + types.push(checker.createAnonymousType(/*symbol*/ undefined, members_6, callSignatures, constructSignatures, stringIndexInfo, /*numberIndexInfo*/ undefined)); // TODO: GH#18217 + } + return types; + function recur(innerContext) { + return unifyFromContext(inferFromContext(innerContext, checker), checker); + } + } + function getParameterTypeFromCallContexts(parameterIndex, callContexts, isRestParameter, checker) { + var types = []; + if (callContexts) { + for (var _i = 0, callContexts_2 = callContexts; _i < callContexts_2.length; _i++) { + var callContext = callContexts_2[_i]; + if (callContext.argumentTypes.length > parameterIndex) { + if (isRestParameter) { + types = ts.concatenate(types, ts.map(callContext.argumentTypes.slice(parameterIndex), function (a) { return checker.getBaseTypeOfLiteralType(a); })); + } + else { + types.push(checker.getBaseTypeOfLiteralType(callContext.argumentTypes[parameterIndex])); + } + } + } + } + if (types.length) { + var type = checker.getWidenedType(checker.getUnionType(types, 2 /* Subtype */)); + return isRestParameter ? checker.createArrayType(type) : type; + } + return undefined; + } + function getSignatureFromCallContext(callContext, checker) { + var parameters = []; + for (var i = 0; i < callContext.argumentTypes.length; i++) { + var symbol = checker.createSymbol(1 /* FunctionScopedVariable */, ts.escapeLeadingUnderscores("arg" + i)); + symbol.type = checker.getWidenedType(checker.getBaseTypeOfLiteralType(callContext.argumentTypes[i])); + parameters.push(symbol); + } + var returnType = unifyFromContext(inferFromContext(callContext.returnType, checker), checker, checker.getVoidType()); + // TODO: GH#18217 + return checker.createSignature(/*declaration*/ undefined, /*typeParameters*/ undefined, /*thisParameter*/ undefined, parameters, returnType, /*typePredicate*/ undefined, callContext.argumentTypes.length, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + } + function addCandidateType(context, type) { + if (type && !(type.flags & 1 /* Any */) && !(type.flags & 131072 /* Never */)) { + (context.candidateTypes || (context.candidateTypes = [])).push(type); + } + } + function hasCallContext(usageContext) { + return !!usageContext && !!usageContext.callContexts; + } + })(InferFromReference || (InferFromReference = {})); + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "convertFunctionToEs6Class"; + var errorCodes = [ts.Diagnostics.This_constructor_function_may_be_converted_to_a_class_declaration.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, context.sourceFile, context.span.start, context.program.getTypeChecker()); }); + return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Convert_function_to_an_ES2015_class, fixId, ts.Diagnostics.Convert_all_constructor_functions_to_classes)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, err) { return doChange(changes, err.file, err.start, context.program.getTypeChecker()); }); }, + }); + function doChange(changes, sourceFile, position, checker) { + var ctorSymbol = checker.getSymbolAtLocation(ts.getTokenAtPosition(sourceFile, position)); + if (!ctorSymbol || !(ctorSymbol.flags & (16 /* Function */ | 3 /* Variable */))) { + // Bad input + return undefined; + } + var ctorDeclaration = ctorSymbol.valueDeclaration; + var precedingNode; + var newClassDeclaration; + switch (ctorDeclaration.kind) { + case 239 /* FunctionDeclaration */: + precedingNode = ctorDeclaration; + changes.delete(sourceFile, ctorDeclaration); + newClassDeclaration = createClassFromFunctionDeclaration(ctorDeclaration); + break; + case 237 /* VariableDeclaration */: + precedingNode = ctorDeclaration.parent.parent; + newClassDeclaration = createClassFromVariableDeclaration(ctorDeclaration); + if (ctorDeclaration.parent.declarations.length === 1) { + ts.copyComments(precedingNode, newClassDeclaration, sourceFile); // TODO: GH#18217 + changes.delete(sourceFile, precedingNode); + } + else { + changes.delete(sourceFile, ctorDeclaration); + } + break; + } + if (!newClassDeclaration) { + return undefined; + } + ts.copyComments(ctorDeclaration, newClassDeclaration, sourceFile); + // Because the preceding node could be touched, we need to insert nodes before delete nodes. + changes.insertNodeAfter(sourceFile, precedingNode, newClassDeclaration); + function createClassElementsFromSymbol(symbol) { + var memberElements = []; + // all instance members are stored in the "member" array of symbol + if (symbol.members) { + symbol.members.forEach(function (member) { + var memberElement = createClassElement(member, /*modifiers*/ undefined); + if (memberElement) { + memberElements.push(memberElement); + } + }); + } + // all static members are stored in the "exports" array of symbol + if (symbol.exports) { + symbol.exports.forEach(function (member) { + var memberElement = createClassElement(member, [ts.createToken(116 /* StaticKeyword */)]); + if (memberElement) { + memberElements.push(memberElement); + } + }); + } + return memberElements; + function shouldConvertDeclaration(_target, source) { + // Right now the only thing we can convert are function expressions - other values shouldn't get + // transformed. We can update this once ES public class properties are available. + return ts.isFunctionLike(source); + } + function createClassElement(symbol, modifiers) { + // Right now the only thing we can convert are function expressions, which are marked as methods + if (!(symbol.flags & 8192 /* Method */)) { + return; + } + var memberDeclaration = symbol.valueDeclaration; + var assignmentBinaryExpression = memberDeclaration.parent; + if (!shouldConvertDeclaration(memberDeclaration, assignmentBinaryExpression.right)) { + return; + } + // delete the entire statement if this expression is the sole expression to take care of the semicolon at the end + var nodeToDelete = assignmentBinaryExpression.parent && assignmentBinaryExpression.parent.kind === 221 /* ExpressionStatement */ + ? assignmentBinaryExpression.parent : assignmentBinaryExpression; + changes.delete(sourceFile, nodeToDelete); + if (!assignmentBinaryExpression.right) { + return ts.createProperty([], modifiers, symbol.name, /*questionToken*/ undefined, + /*type*/ undefined, /*initializer*/ undefined); + } + switch (assignmentBinaryExpression.right.kind) { + case 196 /* FunctionExpression */: { + var functionExpression = assignmentBinaryExpression.right; + var fullModifiers = ts.concatenate(modifiers, getModifierKindFromSource(functionExpression, 121 /* AsyncKeyword */)); + var method = ts.createMethod(/*decorators*/ undefined, fullModifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined, + /*typeParameters*/ undefined, functionExpression.parameters, /*type*/ undefined, functionExpression.body); + ts.copyComments(assignmentBinaryExpression, method, sourceFile); + return method; + } + case 197 /* ArrowFunction */: { + var arrowFunction = assignmentBinaryExpression.right; + var arrowFunctionBody = arrowFunction.body; + var bodyBlock = void 0; + // case 1: () => { return [1,2,3] } + if (arrowFunctionBody.kind === 218 /* Block */) { + bodyBlock = arrowFunctionBody; + } + // case 2: () => [1,2,3] + else { + bodyBlock = ts.createBlock([ts.createReturn(arrowFunctionBody)]); + } + var fullModifiers = ts.concatenate(modifiers, getModifierKindFromSource(arrowFunction, 121 /* AsyncKeyword */)); + var method = ts.createMethod(/*decorators*/ undefined, fullModifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined, + /*typeParameters*/ undefined, arrowFunction.parameters, /*type*/ undefined, bodyBlock); + ts.copyComments(assignmentBinaryExpression, method, sourceFile); + return method; + } + default: { + // Don't try to declare members in JavaScript files + if (ts.isSourceFileJS(sourceFile)) { + return; + } + var prop = ts.createProperty(/*decorators*/ undefined, modifiers, memberDeclaration.name, /*questionToken*/ undefined, + /*type*/ undefined, assignmentBinaryExpression.right); + ts.copyComments(assignmentBinaryExpression.parent, prop, sourceFile); + return prop; + } + } + } + } + function createClassFromVariableDeclaration(node) { + var initializer = node.initializer; + if (!initializer || initializer.kind !== 196 /* FunctionExpression */) { + return undefined; + } + if (node.name.kind !== 72 /* Identifier */) { + return undefined; + } + var memberElements = createClassElementsFromSymbol(node.symbol); + if (initializer.body) { + memberElements.unshift(ts.createConstructor(/*decorators*/ undefined, /*modifiers*/ undefined, initializer.parameters, initializer.body)); + } + var modifiers = getModifierKindFromSource(precedingNode, 85 /* ExportKeyword */); + var cls = ts.createClassDeclaration(/*decorators*/ undefined, modifiers, node.name, + /*typeParameters*/ undefined, /*heritageClauses*/ undefined, memberElements); + // Don't call copyComments here because we'll already leave them in place + return cls; + } + function createClassFromFunctionDeclaration(node) { + var memberElements = createClassElementsFromSymbol(ctorSymbol); + if (node.body) { + memberElements.unshift(ts.createConstructor(/*decorators*/ undefined, /*modifiers*/ undefined, node.parameters, node.body)); + } + var modifiers = getModifierKindFromSource(node, 85 /* ExportKeyword */); + var cls = ts.createClassDeclaration(/*decorators*/ undefined, modifiers, node.name, + /*typeParameters*/ undefined, /*heritageClauses*/ undefined, memberElements); + // Don't call copyComments here because we'll already leave them in place + return cls; + } + } + function getModifierKindFromSource(source, kind) { + return ts.filter(source.modifiers, function (modifier) { return modifier.kind === kind; }); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "convertToAsyncFunction"; + var errorCodes = [ts.Diagnostics.This_may_be_converted_to_an_async_function.code]; + var codeActionSucceeded = true; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + codeActionSucceeded = true; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return convertToAsyncFunction(t, context.sourceFile, context.span.start, context.program.getTypeChecker(), context); }); + return codeActionSucceeded ? [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Convert_to_async_function, fixId, ts.Diagnostics.Convert_all_to_async_functions)] : []; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, err) { return convertToAsyncFunction(changes, err.file, err.start, context.program.getTypeChecker(), context); }); }, + }); + function convertToAsyncFunction(changes, sourceFile, position, checker, context) { + // get the function declaration - returns a promise + var tokenAtPosition = ts.getTokenAtPosition(sourceFile, position); + var functionToConvert; + // if the parent of a FunctionLikeDeclaration is a variable declaration, the convertToAsync diagnostic will be reported on the variable name + if (ts.isIdentifier(tokenAtPosition) && ts.isVariableDeclaration(tokenAtPosition.parent) && + tokenAtPosition.parent.initializer && ts.isFunctionLikeDeclaration(tokenAtPosition.parent.initializer)) { + functionToConvert = tokenAtPosition.parent.initializer; + } + else { + functionToConvert = ts.tryCast(ts.getContainingFunction(ts.getTokenAtPosition(sourceFile, position)), ts.isFunctionLikeDeclaration); + } + if (!functionToConvert) { + return; + } + var synthNamesMap = ts.createMap(); + var originalTypeMap = ts.createMap(); + var allVarNames = []; + var isInJavascript = ts.isInJSFile(functionToConvert); + var setOfExpressionsToReturn = getAllPromiseExpressionsToReturn(functionToConvert, checker); + var functionToConvertRenamed = renameCollidingVarNames(functionToConvert, checker, synthNamesMap, context, setOfExpressionsToReturn, originalTypeMap, allVarNames); + var constIdentifiers = getConstIdentifiers(synthNamesMap); + var returnStatements = functionToConvertRenamed.body && ts.isBlock(functionToConvertRenamed.body) ? getReturnStatementsWithPromiseHandlers(functionToConvertRenamed.body) : ts.emptyArray; + var transformer = { checker: checker, synthNamesMap: synthNamesMap, allVarNames: allVarNames, setOfExpressionsToReturn: setOfExpressionsToReturn, constIdentifiers: constIdentifiers, originalTypeMap: originalTypeMap, isInJSFile: isInJavascript }; + if (!returnStatements.length) { + return; + } + // add the async keyword + changes.insertLastModifierBefore(sourceFile, 121 /* AsyncKeyword */, functionToConvert); + function startTransformation(node, nodeToReplace) { + var newNodes = transformExpression(node, transformer, node); + changes.replaceNodeWithNodes(sourceFile, nodeToReplace, newNodes); + } + var _loop_19 = function (statement) { + ts.forEachChild(statement, function visit(node) { + if (ts.isCallExpression(node)) { + startTransformation(node, statement); + } + else if (!ts.isFunctionLike(node)) { + ts.forEachChild(node, visit); + } + }); + }; + for (var _i = 0, returnStatements_1 = returnStatements; _i < returnStatements_1.length; _i++) { + var statement = returnStatements_1[_i]; + _loop_19(statement); + } + } + function getReturnStatementsWithPromiseHandlers(body) { + var res = []; + ts.forEachReturnStatement(body, function (ret) { + if (ts.isReturnStatementWithFixablePromiseHandler(ret)) + res.push(ret); + }); + return res; + } + // Returns the identifiers that are never reassigned in the refactor + function getConstIdentifiers(synthNamesMap) { + var constIdentifiers = []; + synthNamesMap.forEach(function (val) { + if (val.numberOfAssignmentsOriginal === 0) { + constIdentifiers.push(val.identifier); + } + }); + return constIdentifiers; + } + /* + Finds all of the expressions of promise type that should not be saved in a variable during the refactor + */ + function getAllPromiseExpressionsToReturn(func, checker) { + if (!func.body) { + return ts.createMap(); + } + var setOfExpressionsToReturn = ts.createMap(); + ts.forEachChild(func.body, function visit(node) { + if (isPromiseReturningExpression(node, checker, "then")) { + setOfExpressionsToReturn.set(ts.getNodeId(node).toString(), true); + ts.forEach(node.arguments, visit); + } + else if (isPromiseReturningExpression(node, checker, "catch")) { + setOfExpressionsToReturn.set(ts.getNodeId(node).toString(), true); + // if .catch() is the last call in the chain, move leftward in the chain until we hit something else that should be returned + ts.forEachChild(node, visit); + } + else if (isPromiseReturningExpression(node, checker)) { + setOfExpressionsToReturn.set(ts.getNodeId(node).toString(), true); + // don't recurse here, since we won't refactor any children or arguments of the expression + } + else { + ts.forEachChild(node, visit); + } + }); + return setOfExpressionsToReturn; + } + /* + Returns true if node is a promise returning expression + If name is not undefined, node is a promise returning call of name + */ + function isPromiseReturningExpression(node, checker, name) { + var isNodeExpression = name ? ts.isCallExpression(node) : ts.isExpression(node); + var isExpressionOfName = isNodeExpression && (!name || ts.hasPropertyAccessExpressionWithName(node, name)); + var nodeType = isExpressionOfName && checker.getTypeAtLocation(node); + return !!(nodeType && checker.getPromisedTypeOfPromise(nodeType)); + } + function declaredInFile(symbol, sourceFile) { + return symbol.valueDeclaration && symbol.valueDeclaration.getSourceFile() === sourceFile; + } + /* + Renaming of identifiers may be neccesary as the refactor changes scopes - + This function collects all existing identifier names and names of identifiers that will be created in the refactor. + It then checks for any collisions and renames them through getSynthesizedDeepClone + */ + function renameCollidingVarNames(nodeToRename, checker, synthNamesMap, context, setOfAllExpressionsToReturn, originalType, allVarNames) { + var identsToRenameMap = ts.createMap(); // key is the symbol id + var collidingSymbolMap = ts.createMap(); + ts.forEachChild(nodeToRename, function visit(node) { + if (!ts.isIdentifier(node)) { + ts.forEachChild(node, visit); + return; + } + var symbol = checker.getSymbolAtLocation(node); + var isDefinedInFile = symbol && declaredInFile(symbol, context.sourceFile); + if (symbol && isDefinedInFile) { + var type = checker.getTypeAtLocation(node); + var lastCallSignature = getLastCallSignature(type, checker); + var symbolIdString = ts.getSymbolId(symbol).toString(); + // if the identifier refers to a function we want to add the new synthesized variable for the declaration (ex. blob in let blob = res(arg)) + // Note - the choice of the last call signature is arbitrary + if (lastCallSignature && !ts.isFunctionLikeDeclaration(node.parent) && !synthNamesMap.has(symbolIdString)) { + var firstParameter = ts.firstOrUndefined(lastCallSignature.parameters); + var ident = firstParameter && ts.isParameter(firstParameter.valueDeclaration) && ts.tryCast(firstParameter.valueDeclaration.name, ts.isIdentifier) || ts.createOptimisticUniqueName("result"); + var synthName = getNewNameIfConflict(ident, collidingSymbolMap); + synthNamesMap.set(symbolIdString, synthName); + allVarNames.push({ identifier: synthName.identifier, symbol: symbol }); + addNameToFrequencyMap(collidingSymbolMap, ident.text, symbol); + } + // we only care about identifiers that are parameters and declarations (don't care about other uses) + else if (node.parent && (ts.isParameter(node.parent) || ts.isVariableDeclaration(node.parent))) { + var originalName = node.text; + var collidingSymbols = collidingSymbolMap.get(originalName); + // if the identifier name conflicts with a different identifier that we've already seen + if (collidingSymbols && collidingSymbols.some(function (prevSymbol) { return prevSymbol !== symbol; })) { + var newName = getNewNameIfConflict(node, collidingSymbolMap); + identsToRenameMap.set(symbolIdString, newName.identifier); + synthNamesMap.set(symbolIdString, newName); + allVarNames.push({ identifier: newName.identifier, symbol: symbol }); + addNameToFrequencyMap(collidingSymbolMap, originalName, symbol); + } + else { + var identifier = ts.getSynthesizedDeepClone(node); + identsToRenameMap.set(symbolIdString, identifier); + synthNamesMap.set(symbolIdString, { identifier: identifier, types: [], numberOfAssignmentsOriginal: allVarNames.filter(function (elem) { return elem.identifier.text === node.text; }).length /*, numberOfAssignmentsSynthesized: 0*/ }); + if ((ts.isParameter(node.parent) && isExpressionOrCallOnTypePromise(node.parent.parent)) || ts.isVariableDeclaration(node.parent)) { + allVarNames.push({ identifier: identifier, symbol: symbol }); + addNameToFrequencyMap(collidingSymbolMap, originalName, symbol); + } + } + } + } + }); + return ts.getSynthesizedDeepCloneWithRenames(nodeToRename, /*includeTrivia*/ true, identsToRenameMap, checker, deepCloneCallback); + function isExpressionOrCallOnTypePromise(child) { + var node = child.parent; + if (ts.isCallExpression(node) || ts.isIdentifier(node) && !setOfAllExpressionsToReturn.get(ts.getNodeId(node).toString())) { + var nodeType = checker.getTypeAtLocation(node); + var isPromise = nodeType && checker.getPromisedTypeOfPromise(nodeType); + return !!isPromise; + } + return false; + } + function deepCloneCallback(node, clone) { + if (ts.isIdentifier(node)) { + var symbol = checker.getSymbolAtLocation(node); + var symboldIdString = symbol && ts.getSymbolId(symbol).toString(); + var renameInfo = symbol && synthNamesMap.get(symboldIdString); + if (renameInfo) { + var type = checker.getTypeAtLocation(node); + originalType.set(ts.getNodeId(clone).toString(), type); + } + } + var val = setOfAllExpressionsToReturn.get(ts.getNodeId(node).toString()); + if (val !== undefined) { + setOfAllExpressionsToReturn.delete(ts.getNodeId(node).toString()); + setOfAllExpressionsToReturn.set(ts.getNodeId(clone).toString(), val); + } + } + } + function addNameToFrequencyMap(renamedVarNameFrequencyMap, originalName, symbol) { + if (renamedVarNameFrequencyMap.has(originalName)) { + renamedVarNameFrequencyMap.get(originalName).push(symbol); + } + else { + renamedVarNameFrequencyMap.set(originalName, [symbol]); + } + } + function getNewNameIfConflict(name, originalNames) { + var numVarsSameName = (originalNames.get(name.text) || ts.emptyArray).length; + var numberOfAssignmentsOriginal = 0; + var identifier = numVarsSameName === 0 ? name : ts.createIdentifier(name.text + "_" + numVarsSameName); + return { identifier: identifier, types: [], numberOfAssignmentsOriginal: numberOfAssignmentsOriginal }; + } + // dispatch function to recursively build the refactoring + // should be kept up to date with isFixablePromiseHandler in suggestionDiagnostics.ts + function transformExpression(node, transformer, outermostParent, prevArgName) { + if (!node) { + return ts.emptyArray; + } + var originalType = ts.isIdentifier(node) && transformer.originalTypeMap.get(ts.getNodeId(node).toString()); + var nodeType = originalType || transformer.checker.getTypeAtLocation(node); + if (ts.isCallExpression(node) && ts.hasPropertyAccessExpressionWithName(node, "then") && nodeType && !!transformer.checker.getPromisedTypeOfPromise(nodeType)) { + return transformThen(node, transformer, outermostParent, prevArgName); + } + else if (ts.isCallExpression(node) && ts.hasPropertyAccessExpressionWithName(node, "catch") && nodeType && !!transformer.checker.getPromisedTypeOfPromise(nodeType)) { + return transformCatch(node, transformer, prevArgName); + } + else if (ts.isPropertyAccessExpression(node)) { + return transformExpression(node.expression, transformer, outermostParent, prevArgName); + } + else if (nodeType && transformer.checker.getPromisedTypeOfPromise(nodeType)) { + return transformPromiseCall(node, transformer, prevArgName); + } + codeActionSucceeded = false; + return ts.emptyArray; + } + function transformCatch(node, transformer, prevArgName) { + var func = node.arguments[0]; + var argName = getArgName(func, transformer); + var shouldReturn = transformer.setOfExpressionsToReturn.get(ts.getNodeId(node).toString()); + /* + If there is another call in the chain after the .catch() we are transforming, we will need to save the result of both paths (try block and catch block) + To do this, we will need to synthesize a variable that we were not aware of while we were adding identifiers to the synthNamesMap + We will use the prevArgName and then update the synthNamesMap with a new variable name for the next transformation step + */ + if (prevArgName && !shouldReturn) { + prevArgName.numberOfAssignmentsOriginal = 2; // Try block and catch block + transformer.synthNamesMap.forEach(function (val, key) { + if (val.identifier.text === prevArgName.identifier.text) { + var newSynthName = createUniqueSynthName(prevArgName); + transformer.synthNamesMap.set(key, newSynthName); + } + }); + // update the constIdentifiers list + if (transformer.constIdentifiers.some(function (elem) { return elem.text === prevArgName.identifier.text; })) { + transformer.constIdentifiers.push(createUniqueSynthName(prevArgName).identifier); + } + } + var tryBlock = ts.createBlock(transformExpression(node.expression, transformer, node, prevArgName)); + var transformationBody = getTransformationBody(func, prevArgName, argName, node, transformer); + var catchArg = argName ? argName.identifier.text : "e"; + var catchClause = ts.createCatchClause(catchArg, ts.createBlock(transformationBody)); + /* + In order to avoid an implicit any, we will synthesize a type for the declaration using the unions of the types of both paths (try block and catch block) + */ + var varDeclList; + if (prevArgName && !shouldReturn) { + var typeArray = prevArgName.types; + var unionType = transformer.checker.getUnionType(typeArray, 2 /* Subtype */); + var unionTypeNode = transformer.isInJSFile ? undefined : transformer.checker.typeToTypeNode(unionType); + var varDecl = [ts.createVariableDeclaration(ts.getSynthesizedDeepClone(prevArgName.identifier), unionTypeNode)]; + varDeclList = ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList(varDecl, 1 /* Let */)); + } + var tryStatement = ts.createTry(tryBlock, catchClause, /*finallyBlock*/ undefined); + return varDeclList ? [varDeclList, tryStatement] : [tryStatement]; + } + function createUniqueSynthName(prevArgName) { + var renamedPrevArg = ts.createOptimisticUniqueName(prevArgName.identifier.text); + var newSynthName = { identifier: renamedPrevArg, types: [], numberOfAssignmentsOriginal: 0 }; + return newSynthName; + } + function transformThen(node, transformer, outermostParent, prevArgName) { + var _a = node.arguments, res = _a[0], rej = _a[1]; + if (!res) { + return transformExpression(node.expression, transformer, outermostParent); + } + var argNameRes = getArgName(res, transformer); + var transformationBody = getTransformationBody(res, prevArgName, argNameRes, node, transformer); + if (rej) { + var argNameRej = getArgName(rej, transformer); + var tryBlock = ts.createBlock(transformExpression(node.expression, transformer, node, argNameRes).concat(transformationBody)); + var transformationBody2 = getTransformationBody(rej, prevArgName, argNameRej, node, transformer); + var catchArg = argNameRej ? argNameRej.identifier.text : "e"; + var catchClause = ts.createCatchClause(catchArg, ts.createBlock(transformationBody2)); + return [ts.createTry(tryBlock, catchClause, /* finallyBlock */ undefined)]; + } + return transformExpression(node.expression, transformer, node, argNameRes).concat(transformationBody); + } + function getFlagOfIdentifier(node, constIdentifiers) { + var inArr = constIdentifiers.some(function (elem) { return elem.text === node.text; }); + return inArr ? 2 /* Const */ : 1 /* Let */; + } + function transformPromiseCall(node, transformer, prevArgName) { + var shouldReturn = transformer.setOfExpressionsToReturn.get(ts.getNodeId(node).toString()); + // the identifier is empty when the handler (.then()) ignores the argument - In this situation we do not need to save the result of the promise returning call + var originalNodeParent = node.original ? node.original.parent : node.parent; + if (prevArgName && !shouldReturn && (!originalNodeParent || ts.isPropertyAccessExpression(originalNodeParent))) { + return createTransformedStatement(prevArgName, ts.createAwait(node), transformer); + } + else if (!prevArgName && !shouldReturn && (!originalNodeParent || ts.isPropertyAccessExpression(originalNodeParent))) { + return [ts.createStatement(ts.createAwait(node))]; + } + return [ts.createReturn(ts.getSynthesizedDeepClone(node))]; + } + function createTransformedStatement(prevArgName, rightHandSide, transformer) { + if (!prevArgName || prevArgName.identifier.text.length === 0) { + // if there's no argName to assign to, there still might be side effects + return [ts.createStatement(rightHandSide)]; + } + if (prevArgName.types.length < prevArgName.numberOfAssignmentsOriginal) { + // if the variable has already been declared, we don't need "let" or "const" + return [ts.createStatement(ts.createAssignment(ts.getSynthesizedDeepClone(prevArgName.identifier), rightHandSide))]; + } + return [ts.createVariableStatement(/*modifiers*/ undefined, (ts.createVariableDeclarationList([ts.createVariableDeclaration(ts.getSynthesizedDeepClone(prevArgName.identifier), /*type*/ undefined, rightHandSide)], getFlagOfIdentifier(prevArgName.identifier, transformer.constIdentifiers))))]; + } + // should be kept up to date with isFixablePromiseArgument in suggestionDiagnostics.ts + function getTransformationBody(func, prevArgName, argName, parent, transformer) { + var shouldReturn = transformer.setOfExpressionsToReturn.get(ts.getNodeId(parent).toString()); + switch (func.kind) { + case 96 /* NullKeyword */: + // do not produce a transformed statement for a null argument + break; + case 72 /* Identifier */: // identifier includes undefined + if (!argName) { + // undefined was argument passed to promise handler + break; + } + var synthCall = ts.createCall(ts.getSynthesizedDeepClone(func), /*typeArguments*/ undefined, [argName.identifier]); + if (shouldReturn) { + return [ts.createReturn(synthCall)]; + } + var type = transformer.originalTypeMap.get(ts.getNodeId(func).toString()) || transformer.checker.getTypeAtLocation(func); + var callSignatures = transformer.checker.getSignaturesOfType(type, 0 /* Call */); + if (!callSignatures.length) { + // if identifier in handler has no call signatures, it's invalid + codeActionSucceeded = false; + break; + } + var returnType = callSignatures[0].getReturnType(); + var varDeclOrAssignment = createTransformedStatement(prevArgName, ts.createAwait(synthCall), transformer); + if (prevArgName) { + prevArgName.types.push(returnType); + } + return varDeclOrAssignment; + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: { + var funcBody = func.body; + // Arrow functions with block bodies { } will enter this control flow + if (ts.isBlock(funcBody)) { + var refactoredStmts = []; + var seenReturnStatement = false; + for (var _i = 0, _a = funcBody.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + if (ts.isReturnStatement(statement)) { + seenReturnStatement = true; + } + if (ts.isReturnStatementWithFixablePromiseHandler(statement)) { + refactoredStmts = refactoredStmts.concat(getInnerTransformationBody(transformer, [statement], prevArgName)); + } + else { + refactoredStmts.push(statement); + } + } + return shouldReturn ? refactoredStmts.map(function (s) { return ts.getSynthesizedDeepClone(s); }) : + removeReturns(refactoredStmts, prevArgName === undefined ? undefined : prevArgName.identifier, transformer, seenReturnStatement); + } + else { + var innerRetStmts = ts.isFixablePromiseHandler(funcBody) ? [ts.createReturn(funcBody)] : ts.emptyArray; + var innerCbBody = getInnerTransformationBody(transformer, innerRetStmts, prevArgName); + if (innerCbBody.length > 0) { + return innerCbBody; + } + var type_6 = transformer.checker.getTypeAtLocation(func); + var returnType_1 = getLastCallSignature(type_6, transformer.checker).getReturnType(); + var rightHandSide = ts.getSynthesizedDeepClone(funcBody); + var possiblyAwaitedRightHandSide = !!transformer.checker.getPromisedTypeOfPromise(returnType_1) ? ts.createAwait(rightHandSide) : rightHandSide; + if (!shouldReturn) { + var transformedStatement = createTransformedStatement(prevArgName, possiblyAwaitedRightHandSide, transformer); + if (prevArgName) { + prevArgName.types.push(returnType_1); + } + return transformedStatement; + } + else { + return [ts.createReturn(possiblyAwaitedRightHandSide)]; + } + } + } + default: + // If no cases apply, we've found a transformation body we don't know how to handle, so the refactoring should no-op to avoid deleting code. + codeActionSucceeded = false; + break; + } + return ts.emptyArray; + } + function getLastCallSignature(type, checker) { + var callSignatures = checker.getSignaturesOfType(type, 0 /* Call */); + return ts.lastOrUndefined(callSignatures); + } + function removeReturns(stmts, prevArgName, transformer, seenReturnStatement) { + var ret = []; + for (var _i = 0, stmts_1 = stmts; _i < stmts_1.length; _i++) { + var stmt = stmts_1[_i]; + if (ts.isReturnStatement(stmt)) { + if (stmt.expression) { + var possiblyAwaitedExpression = isPromiseReturningExpression(stmt.expression, transformer.checker) ? ts.createAwait(stmt.expression) : stmt.expression; + if (prevArgName === undefined) { + ret.push(ts.createExpressionStatement(possiblyAwaitedExpression)); + } + else { + ret.push(ts.createVariableStatement(/*modifiers*/ undefined, (ts.createVariableDeclarationList([ts.createVariableDeclaration(prevArgName, /*type*/ undefined, possiblyAwaitedExpression)], getFlagOfIdentifier(prevArgName, transformer.constIdentifiers))))); + } + } + } + else { + ret.push(ts.getSynthesizedDeepClone(stmt)); + } + } + // if block has no return statement, need to define prevArgName as undefined to prevent undeclared variables + if (!seenReturnStatement && prevArgName !== undefined) { + ret.push(ts.createVariableStatement(/*modifiers*/ undefined, (ts.createVariableDeclarationList([ts.createVariableDeclaration(prevArgName, /*type*/ undefined, ts.createIdentifier("undefined"))], getFlagOfIdentifier(prevArgName, transformer.constIdentifiers))))); + } + return ret; + } + function getInnerTransformationBody(transformer, innerRetStmts, prevArgName) { + var innerCbBody = []; + for (var _i = 0, innerRetStmts_1 = innerRetStmts; _i < innerRetStmts_1.length; _i++) { + var stmt = innerRetStmts_1[_i]; + ts.forEachChild(stmt, function visit(node) { + if (ts.isCallExpression(node)) { + var temp = transformExpression(node, transformer, node, prevArgName); + innerCbBody = innerCbBody.concat(temp); + if (innerCbBody.length > 0) { + return; + } + } + else if (!ts.isFunctionLike(node)) { + ts.forEachChild(node, visit); + } + }); + } + return innerCbBody; + } + function getArgName(funcNode, transformer) { + var numberOfAssignmentsOriginal = 0; + var types = []; + var name; + if (ts.isFunctionLikeDeclaration(funcNode)) { + if (funcNode.parameters.length > 0) { + var param = funcNode.parameters[0].name; + name = getMapEntryOrDefault(param); + } + } + else if (ts.isIdentifier(funcNode)) { + name = getMapEntryOrDefault(funcNode); + } + // return undefined argName when arg is null or undefined + if (!name || name.identifier.text === "undefined") { + return undefined; + } + return name; + function getMapEntryOrDefault(identifier) { + var originalNode = getOriginalNode(identifier); + var symbol = getSymbol(originalNode); + if (!symbol) { + return { identifier: identifier, types: types, numberOfAssignmentsOriginal: numberOfAssignmentsOriginal }; + } + var mapEntry = transformer.synthNamesMap.get(ts.getSymbolId(symbol).toString()); + return mapEntry || { identifier: identifier, types: types, numberOfAssignmentsOriginal: numberOfAssignmentsOriginal }; + } + function getSymbol(node) { + return node.symbol ? node.symbol : transformer.checker.getSymbolAtLocation(node); + } + function getOriginalNode(node) { + return node.original ? node.original : node; + } + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + codefix.registerCodeFix({ + errorCodes: [ts.Diagnostics.File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module.code], + getCodeActions: function (context) { + var sourceFile = context.sourceFile, program = context.program, preferences = context.preferences; + var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { + var moduleExportsChangedToDefault = convertFileToEs6Module(sourceFile, program.getTypeChecker(), changes, program.getCompilerOptions().target, ts.getQuotePreference(sourceFile, preferences)); + if (moduleExportsChangedToDefault) { + for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { + var importingFile = _a[_i]; + fixImportOfModuleExports(importingFile, sourceFile, changes, ts.getQuotePreference(importingFile, preferences)); + } + } + }); + // No support for fix-all since this applies to the whole file at once anyway. + return [codefix.createCodeFixActionNoFixId("convertToEs6Module", changes, ts.Diagnostics.Convert_to_ES6_module)]; + }, + }); + function fixImportOfModuleExports(importingFile, exportingFile, changes, quotePreference) { + for (var _i = 0, _a = importingFile.imports; _i < _a.length; _i++) { + var moduleSpecifier = _a[_i]; + var imported = ts.getResolvedModule(importingFile, moduleSpecifier.text); + if (!imported || imported.resolvedFileName !== exportingFile.fileName) { + continue; + } + var importNode = ts.importFromModuleSpecifier(moduleSpecifier); + switch (importNode.kind) { + case 248 /* ImportEqualsDeclaration */: + changes.replaceNode(importingFile, importNode, ts.makeImport(importNode.name, /*namedImports*/ undefined, moduleSpecifier, quotePreference)); + break; + case 191 /* CallExpression */: + if (ts.isRequireCall(importNode, /*checkArgumentIsStringLiteralLike*/ false)) { + changes.replaceNode(importingFile, importNode, ts.createPropertyAccess(ts.getSynthesizedDeepClone(importNode), "default")); + } + break; + } + } + } + /** @returns Whether we converted a `module.exports =` to a default export. */ + function convertFileToEs6Module(sourceFile, checker, changes, target, quotePreference) { + var identifiers = { original: collectFreeIdentifiers(sourceFile), additional: ts.createMap() }; + var exports = collectExportRenames(sourceFile, checker, identifiers); + convertExportsAccesses(sourceFile, exports, changes); + var moduleExportsChangedToDefault = false; + for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + var moduleExportsChanged = convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports, quotePreference); + moduleExportsChangedToDefault = moduleExportsChangedToDefault || moduleExportsChanged; + } + return moduleExportsChangedToDefault; + } + function collectExportRenames(sourceFile, checker, identifiers) { + var res = ts.createMap(); + forEachExportReference(sourceFile, function (node) { + var _a = node.name, text = _a.text, originalKeywordKind = _a.originalKeywordKind; + if (!res.has(text) && (originalKeywordKind !== undefined && ts.isNonContextualKeyword(originalKeywordKind) + || checker.resolveName(node.name.text, node, 67220415 /* Value */, /*excludeGlobals*/ true))) { + // Unconditionally add an underscore in case `text` is a keyword. + res.set(text, makeUniqueName("_" + text, identifiers)); + } + }); + return res; + } + function convertExportsAccesses(sourceFile, exports, changes) { + forEachExportReference(sourceFile, function (node, isAssignmentLhs) { + if (isAssignmentLhs) { + return; + } + var text = node.name.text; + changes.replaceNode(sourceFile, node, ts.createIdentifier(exports.get(text) || text)); + }); + } + function forEachExportReference(sourceFile, cb) { + sourceFile.forEachChild(function recur(node) { + if (ts.isPropertyAccessExpression(node) && ts.isExportsOrModuleExportsOrAlias(sourceFile, node.expression)) { + var parent = node.parent; + cb(node, ts.isBinaryExpression(parent) && parent.left === node && parent.operatorToken.kind === 59 /* EqualsToken */); + } + node.forEachChild(recur); + }); + } + function convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports, quotePreference) { + switch (statement.kind) { + case 219 /* VariableStatement */: + convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target, quotePreference); + return false; + case 221 /* ExpressionStatement */: { + var expression = statement.expression; + switch (expression.kind) { + case 191 /* CallExpression */: { + if (ts.isRequireCall(expression, /*checkArgumentIsStringLiteralLike*/ true)) { + // For side-effecting require() call, just make a side-effecting import. + changes.replaceNode(sourceFile, statement, ts.makeImport(/*name*/ undefined, /*namedImports*/ undefined, expression.arguments[0], quotePreference)); + } + return false; + } + case 204 /* BinaryExpression */: { + var operatorToken = expression.operatorToken; + return operatorToken.kind === 59 /* EqualsToken */ && convertAssignment(sourceFile, checker, expression, changes, exports); + } + } + } + // falls through + default: + return false; + } + } + function convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target, quotePreference) { + var declarationList = statement.declarationList; + var foundImport = false; + var newNodes = ts.flatMap(declarationList.declarations, function (decl) { + var name = decl.name, initializer = decl.initializer; + if (initializer) { + if (ts.isExportsOrModuleExportsOrAlias(sourceFile, initializer)) { + // `const alias = module.exports;` can be removed. + foundImport = true; + return []; + } + else if (ts.isRequireCall(initializer, /*checkArgumentIsStringLiteralLike*/ true)) { + foundImport = true; + return convertSingleImport(sourceFile, name, initializer.arguments[0], changes, checker, identifiers, target, quotePreference); + } + else if (ts.isPropertyAccessExpression(initializer) && ts.isRequireCall(initializer.expression, /*checkArgumentIsStringLiteralLike*/ true)) { + foundImport = true; + return convertPropertyAccessImport(name, initializer.name.text, initializer.expression.arguments[0], identifiers, quotePreference); + } + } + // Move it out to its own variable statement. (This will not be used if `!foundImport`) + return ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([decl], declarationList.flags)); + }); + if (foundImport) { + // useNonAdjustedEndPosition to ensure we don't eat the newline after the statement. + changes.replaceNodeWithNodes(sourceFile, statement, newNodes); + } + } + /** Converts `const name = require("moduleSpecifier").propertyName` */ + function convertPropertyAccessImport(name, propertyName, moduleSpecifier, identifiers, quotePreference) { + switch (name.kind) { + case 184 /* ObjectBindingPattern */: + case 185 /* ArrayBindingPattern */: { + // `const [a, b] = require("c").d` --> `import { d } from "c"; const [a, b] = d;` + var tmp = makeUniqueName(propertyName, identifiers); + return [ + makeSingleImport(tmp, propertyName, moduleSpecifier, quotePreference), + makeConst(/*modifiers*/ undefined, name, ts.createIdentifier(tmp)), + ]; + } + case 72 /* Identifier */: + // `const a = require("b").c` --> `import { c as a } from "./b"; + return [makeSingleImport(name.text, propertyName, moduleSpecifier, quotePreference)]; + default: + return ts.Debug.assertNever(name); + } + } + function convertAssignment(sourceFile, checker, assignment, changes, exports) { + var left = assignment.left, right = assignment.right; + if (!ts.isPropertyAccessExpression(left)) { + return false; + } + if (ts.isExportsOrModuleExportsOrAlias(sourceFile, left)) { + if (ts.isExportsOrModuleExportsOrAlias(sourceFile, right)) { + // `const alias = module.exports;` or `module.exports = alias;` can be removed. + changes.delete(sourceFile, assignment.parent); + } + else { + var replacement = ts.isObjectLiteralExpression(right) ? tryChangeModuleExportsObject(right) + : ts.isRequireCall(right, /*checkArgumentIsStringLiteralLike*/ true) ? convertReExportAll(right.arguments[0], checker) + : undefined; + if (replacement) { + changes.replaceNodeWithNodes(sourceFile, assignment.parent, replacement[0]); + return replacement[1]; + } + else { + changes.replaceRangeWithText(sourceFile, ts.createRange(left.getStart(sourceFile), right.pos), "export default"); + return true; + } + } + } + else if (ts.isExportsOrModuleExportsOrAlias(sourceFile, left.expression)) { + convertNamedExport(sourceFile, assignment, changes, exports); + } + return false; + } + /** + * Convert `module.exports = { ... }` to individual exports.. + * We can't always do this if the module has interesting members -- then it will be a default export instead. + */ + function tryChangeModuleExportsObject(object) { + var statements = ts.mapAllOrFail(object.properties, function (prop) { + switch (prop.kind) { + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + // TODO: Maybe we should handle this? See fourslash test `refactorConvertToEs6Module_export_object_shorthand.ts`. + case 276 /* ShorthandPropertyAssignment */: + case 277 /* SpreadAssignment */: + return undefined; + case 275 /* PropertyAssignment */: + return !ts.isIdentifier(prop.name) ? undefined : convertExportsDotXEquals_replaceNode(prop.name.text, prop.initializer); + case 156 /* MethodDeclaration */: + return !ts.isIdentifier(prop.name) ? undefined : functionExpressionToDeclaration(prop.name.text, [ts.createToken(85 /* ExportKeyword */)], prop); + default: + ts.Debug.assertNever(prop); + } + }); + return statements && [statements, false]; + } + function convertNamedExport(sourceFile, assignment, changes, exports) { + // If "originalKeywordKind" was set, this is e.g. `exports. + var text = assignment.left.name.text; + var rename = exports.get(text); + if (rename !== undefined) { + /* + const _class = 0; + export { _class as class }; + */ + var newNodes = [ + makeConst(/*modifiers*/ undefined, rename, assignment.right), + makeExportDeclaration([ts.createExportSpecifier(rename, text)]), + ]; + changes.replaceNodeWithNodes(sourceFile, assignment.parent, newNodes); + } + else { + convertExportsPropertyAssignment(assignment, sourceFile, changes); + } + } + function convertReExportAll(reExported, checker) { + // `module.exports = require("x");` ==> `export * from "x"; export { default } from "x";` + var moduleSpecifier = reExported.text; + var moduleSymbol = checker.getSymbolAtLocation(reExported); + var exports = moduleSymbol ? moduleSymbol.exports : ts.emptyUnderscoreEscapedMap; + return exports.has("export=") + ? [[reExportDefault(moduleSpecifier)], true] + : !exports.has("default") + ? [[reExportStar(moduleSpecifier)], false] + // If there's some non-default export, must include both `export *` and `export default`. + : exports.size > 1 ? [[reExportStar(moduleSpecifier), reExportDefault(moduleSpecifier)], true] : [[reExportDefault(moduleSpecifier)], true]; + } + function reExportStar(moduleSpecifier) { + return makeExportDeclaration(/*exportClause*/ undefined, moduleSpecifier); + } + function reExportDefault(moduleSpecifier) { + return makeExportDeclaration([ts.createExportSpecifier(/*propertyName*/ undefined, "default")], moduleSpecifier); + } + function convertExportsPropertyAssignment(_a, sourceFile, changes) { + var left = _a.left, right = _a.right, parent = _a.parent; + var name = left.name.text; + if ((ts.isFunctionExpression(right) || ts.isArrowFunction(right) || ts.isClassExpression(right)) && (!right.name || right.name.text === name)) { + // `exports.f = function() {}` -> `export function f() {}` -- Replace `exports.f = ` with `export `, and insert the name after `function`. + changes.replaceRange(sourceFile, { pos: left.getStart(sourceFile), end: right.getStart(sourceFile) }, ts.createToken(85 /* ExportKeyword */), { suffix: " " }); + if (!right.name) + changes.insertName(sourceFile, right, name); + var semi = ts.findChildOfKind(parent, 26 /* SemicolonToken */, sourceFile); + if (semi) + changes.delete(sourceFile, semi); + } + else { + // `exports.f = function g() {}` -> `export const f = function g() {}` -- just replace `exports.` with `export const ` + changes.replaceNodeRangeWithNodes(sourceFile, left.expression, ts.findChildOfKind(left, 24 /* DotToken */, sourceFile), [ts.createToken(85 /* ExportKeyword */), ts.createToken(77 /* ConstKeyword */)], { joiner: " ", suffix: " " }); + } + } + // TODO: GH#22492 this will cause an error if a change has been made inside the body of the node. + function convertExportsDotXEquals_replaceNode(name, exported) { + var modifiers = [ts.createToken(85 /* ExportKeyword */)]; + switch (exported.kind) { + case 196 /* FunctionExpression */: { + var expressionName = exported.name; + if (expressionName && expressionName.text !== name) { + // `exports.f = function g() {}` -> `export const f = function g() {}` + return exportConst(); + } + } + // falls through + case 197 /* ArrowFunction */: + // `exports.f = function() {}` --> `export function f() {}` + return functionExpressionToDeclaration(name, modifiers, exported); + case 209 /* ClassExpression */: + // `exports.C = class {}` --> `export class C {}` + return classExpressionToDeclaration(name, modifiers, exported); + default: + return exportConst(); + } + function exportConst() { + // `exports.x = 0;` --> `export const x = 0;` + return makeConst(modifiers, ts.createIdentifier(name), exported); // TODO: GH#18217 + } + } + /** + * Converts `const <> = require("x");`. + * Returns nodes that will replace the variable declaration for the commonjs import. + * May also make use `changes` to remove qualifiers at the use sites of imports, to change `mod.x` to `x`. + */ + function convertSingleImport(file, name, moduleSpecifier, changes, checker, identifiers, target, quotePreference) { + switch (name.kind) { + case 184 /* ObjectBindingPattern */: { + var importSpecifiers = ts.mapAllOrFail(name.elements, function (e) { + return e.dotDotDotToken || e.initializer || e.propertyName && !ts.isIdentifier(e.propertyName) || !ts.isIdentifier(e.name) + ? undefined + : makeImportSpecifier(e.propertyName && e.propertyName.text, e.name.text); + }); // tslint:disable-line no-unnecessary-type-assertion (TODO: GH#18217) + if (importSpecifiers) { + return [ts.makeImport(/*name*/ undefined, importSpecifiers, moduleSpecifier, quotePreference)]; + } + } + // falls through -- object destructuring has an interesting pattern and must be a variable declaration + case 185 /* ArrayBindingPattern */: { + /* + import x from "x"; + const [a, b, c] = x; + */ + var tmp = makeUniqueName(codefix.moduleSpecifierToValidIdentifier(moduleSpecifier.text, target), identifiers); + return [ + ts.makeImport(ts.createIdentifier(tmp), /*namedImports*/ undefined, moduleSpecifier, quotePreference), + makeConst(/*modifiers*/ undefined, ts.getSynthesizedDeepClone(name), ts.createIdentifier(tmp)), + ]; + } + case 72 /* Identifier */: + return convertSingleIdentifierImport(file, name, moduleSpecifier, changes, checker, identifiers, quotePreference); + default: + return ts.Debug.assertNever(name); + } + } + /** + * Convert `import x = require("x").` + * Also converts uses like `x.y()` to `y()` and uses a named import. + */ + function convertSingleIdentifierImport(file, name, moduleSpecifier, changes, checker, identifiers, quotePreference) { + var nameSymbol = checker.getSymbolAtLocation(name); + // Maps from module property name to name actually used. (The same if there isn't shadowing.) + var namedBindingsNames = ts.createMap(); + // True if there is some non-property use like `x()` or `f(x)`. + var needDefaultImport = false; + for (var _i = 0, _a = identifiers.original.get(name.text); _i < _a.length; _i++) { + var use = _a[_i]; + if (checker.getSymbolAtLocation(use) !== nameSymbol || use === name) { + // This was a use of a different symbol with the same name, due to shadowing. Ignore. + continue; + } + var parent = use.parent; + if (ts.isPropertyAccessExpression(parent)) { + var expression = parent.expression, propertyName = parent.name.text; + ts.Debug.assert(expression === use); // Else shouldn't have been in `collectIdentifiers` + var idName = namedBindingsNames.get(propertyName); + if (idName === undefined) { + idName = makeUniqueName(propertyName, identifiers); + namedBindingsNames.set(propertyName, idName); + } + changes.replaceNode(file, parent, ts.createIdentifier(idName)); + } + else { + needDefaultImport = true; + } + } + var namedBindings = namedBindingsNames.size === 0 ? undefined : ts.arrayFrom(ts.mapIterator(namedBindingsNames.entries(), function (_a) { + var propertyName = _a[0], idName = _a[1]; + return ts.createImportSpecifier(propertyName === idName ? undefined : ts.createIdentifier(propertyName), ts.createIdentifier(idName)); + })); + if (!namedBindings) { + // If it was unused, ensure that we at least import *something*. + needDefaultImport = true; + } + return [ts.makeImport(needDefaultImport ? ts.getSynthesizedDeepClone(name) : undefined, namedBindings, moduleSpecifier, quotePreference)]; + } + // Identifiers helpers + function makeUniqueName(name, identifiers) { + while (identifiers.original.has(name) || identifiers.additional.has(name)) { + name = "_" + name; + } + identifiers.additional.set(name, true); + return name; + } + function collectFreeIdentifiers(file) { + var map = ts.createMultiMap(); + forEachFreeIdentifier(file, function (id) { return map.add(id.text, id); }); + return map; + } + /** + * A free identifier is an identifier that can be accessed through name lookup as a local variable. + * In the expression `x.y`, `x` is a free identifier, but `y` is not. + */ + function forEachFreeIdentifier(node, cb) { + if (ts.isIdentifier(node) && isFreeIdentifier(node)) + cb(node); + node.forEachChild(function (child) { return forEachFreeIdentifier(child, cb); }); + } + function isFreeIdentifier(node) { + var parent = node.parent; + switch (parent.kind) { + case 189 /* PropertyAccessExpression */: + return parent.name !== node; + case 186 /* BindingElement */: + return parent.propertyName !== node; + case 253 /* ImportSpecifier */: + return parent.propertyName !== node; + default: + return true; + } + } + // Node helpers + function functionExpressionToDeclaration(name, additionalModifiers, fn) { + return ts.createFunctionDeclaration(ts.getSynthesizedDeepClones(fn.decorators), // TODO: GH#19915 Don't think this is even legal. + ts.concatenate(additionalModifiers, ts.getSynthesizedDeepClones(fn.modifiers)), ts.getSynthesizedDeepClone(fn.asteriskToken), name, ts.getSynthesizedDeepClones(fn.typeParameters), ts.getSynthesizedDeepClones(fn.parameters), ts.getSynthesizedDeepClone(fn.type), ts.convertToFunctionBody(ts.getSynthesizedDeepClone(fn.body))); + } + function classExpressionToDeclaration(name, additionalModifiers, cls) { + return ts.createClassDeclaration(ts.getSynthesizedDeepClones(cls.decorators), // TODO: GH#19915 Don't think this is even legal. + ts.concatenate(additionalModifiers, ts.getSynthesizedDeepClones(cls.modifiers)), name, ts.getSynthesizedDeepClones(cls.typeParameters), ts.getSynthesizedDeepClones(cls.heritageClauses), ts.getSynthesizedDeepClones(cls.members)); + } + function makeSingleImport(localName, propertyName, moduleSpecifier, quotePreference) { + return propertyName === "default" + ? ts.makeImport(ts.createIdentifier(localName), /*namedImports*/ undefined, moduleSpecifier, quotePreference) + : ts.makeImport(/*name*/ undefined, [makeImportSpecifier(propertyName, localName)], moduleSpecifier, quotePreference); + } + function makeImportSpecifier(propertyName, name) { + return ts.createImportSpecifier(propertyName !== undefined && propertyName !== name ? ts.createIdentifier(propertyName) : undefined, ts.createIdentifier(name)); + } + function makeConst(modifiers, name, init) { + return ts.createVariableStatement(modifiers, ts.createVariableDeclarationList([ts.createVariableDeclaration(name, /*type*/ undefined, init)], 2 /* Const */)); + } + function makeExportDeclaration(exportSpecifiers, moduleSpecifier) { + return ts.createExportDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, exportSpecifiers && ts.createNamedExports(exportSpecifiers), moduleSpecifier === undefined ? undefined : ts.createLiteral(moduleSpecifier)); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "correctQualifiedNameToIndexedAccessType"; + var errorCodes = [ts.Diagnostics.Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_property_1_in_0_with_0_1.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var qualifiedName = getQualifiedName(context.sourceFile, context.span.start); + if (!qualifiedName) + return undefined; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, context.sourceFile, qualifiedName); }); + var newText = qualifiedName.left.text + "[\"" + qualifiedName.right.text + "\"]"; + return [codefix.createCodeFixAction(fixId, changes, [ts.Diagnostics.Rewrite_as_the_indexed_access_type_0, newText], fixId, ts.Diagnostics.Rewrite_all_as_indexed_access_types)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var q = getQualifiedName(diag.file, diag.start); + if (q) { + doChange(changes, diag.file, q); + } + }); }, + }); + function getQualifiedName(sourceFile, pos) { + var qualifiedName = ts.findAncestor(ts.getTokenAtPosition(sourceFile, pos), ts.isQualifiedName); + ts.Debug.assert(!!qualifiedName, "Expected position to be owned by a qualified name."); + return ts.isIdentifier(qualifiedName.left) ? qualifiedName : undefined; + } + function doChange(changeTracker, sourceFile, qualifiedName) { + var rightText = qualifiedName.right.text; + var replacement = ts.createIndexedAccessTypeNode(ts.createTypeReferenceNode(qualifiedName.left, /*typeArguments*/ undefined), ts.createLiteralTypeNode(ts.createLiteral(rightText))); + changeTracker.replaceNode(sourceFile, qualifiedName, replacement); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var errorCodes = [ts.Diagnostics.Class_0_incorrectly_implements_interface_1.code, + ts.Diagnostics.Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass.code]; + var fixId = "fixClassIncorrectlyImplementsInterface"; // TODO: share a group with fixClassDoesntImplementInheritedAbstractMember? + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var program = context.program, sourceFile = context.sourceFile, span = context.span; + var classDeclaration = getClass(sourceFile, span.start); + var checker = program.getTypeChecker(); + return ts.mapDefined(ts.getClassImplementsHeritageClauseElements(classDeclaration), function (implementedTypeNode) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMissingDeclarations(checker, implementedTypeNode, sourceFile, classDeclaration, t, context.preferences); }); + return changes.length === 0 ? undefined : codefix.createCodeFixAction(fixId, changes, [ts.Diagnostics.Implement_interface_0, implementedTypeNode.getText(sourceFile)], fixId, ts.Diagnostics.Implement_all_unimplemented_interfaces); + }); + }, + fixIds: [fixId], + getAllCodeActions: function (context) { + var seenClassDeclarations = ts.createMap(); + return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var classDeclaration = getClass(diag.file, diag.start); + if (ts.addToSeen(seenClassDeclarations, ts.getNodeId(classDeclaration))) { + for (var _i = 0, _a = ts.getClassImplementsHeritageClauseElements(classDeclaration); _i < _a.length; _i++) { + var implementedTypeNode = _a[_i]; + addMissingDeclarations(context.program.getTypeChecker(), implementedTypeNode, diag.file, classDeclaration, changes, context.preferences); + } + } + }); + }, + }); + function getClass(sourceFile, pos) { + return ts.Debug.assertDefined(ts.getContainingClass(ts.getTokenAtPosition(sourceFile, pos))); + } + function symbolPointsToNonPrivateMember(symbol) { + return !(ts.getModifierFlags(symbol.valueDeclaration) & 8 /* Private */); + } + function addMissingDeclarations(checker, implementedTypeNode, sourceFile, classDeclaration, changeTracker, preferences) { + var maybeHeritageClauseSymbol = getHeritageClauseSymbolTable(classDeclaration, checker); + // Note that this is ultimately derived from a map indexed by symbol names, + // so duplicates cannot occur. + var implementedType = checker.getTypeAtLocation(implementedTypeNode); + var implementedTypeSymbols = checker.getPropertiesOfType(implementedType); + var nonPrivateAndNotExistedInHeritageClauseMembers = implementedTypeSymbols.filter(ts.and(symbolPointsToNonPrivateMember, function (symbol) { return !maybeHeritageClauseSymbol.has(symbol.escapedName); })); + var classType = checker.getTypeAtLocation(classDeclaration); + if (!classType.getNumberIndexType()) { + createMissingIndexSignatureDeclaration(implementedType, 1 /* Number */); + } + if (!classType.getStringIndexType()) { + createMissingIndexSignatureDeclaration(implementedType, 0 /* String */); + } + codefix.createMissingMemberNodes(classDeclaration, nonPrivateAndNotExistedInHeritageClauseMembers, checker, preferences, function (member) { return changeTracker.insertNodeAtClassStart(sourceFile, classDeclaration, member); }); + function createMissingIndexSignatureDeclaration(type, kind) { + var indexInfoOfKind = checker.getIndexInfoOfType(type, kind); + if (indexInfoOfKind) { + changeTracker.insertNodeAtClassStart(sourceFile, classDeclaration, checker.indexInfoToIndexSignatureDeclaration(indexInfoOfKind, kind, classDeclaration)); + } + } + } + function getHeritageClauseSymbolTable(classDeclaration, checker) { + var heritageClauseNode = ts.getEffectiveBaseTypeNode(classDeclaration); + if (!heritageClauseNode) + return ts.createSymbolTable(); + var heritageClauseType = checker.getTypeAtLocation(heritageClauseNode); + var heritageClauseTypeSymbols = checker.getPropertiesOfType(heritageClauseType); + return ts.createSymbolTable(heritageClauseTypeSymbols.filter(symbolPointsToNonPrivateMember)); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + codefix.importFixId = "fixMissingImport"; + var errorCodes = [ + ts.Diagnostics.Cannot_find_name_0.code, + ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1.code, + ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0.code, + ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_static_member_1_0.code, + ts.Diagnostics.Cannot_find_namespace_0.code, + ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code, + ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here.code, + ]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var errorCode = context.errorCode, preferences = context.preferences, sourceFile = context.sourceFile, span = context.span; + var info = getFixesInfo(context, errorCode, span.start); + if (!info) + return undefined; + var fixes = info.fixes, symbolName = info.symbolName; + var quotePreference = ts.getQuotePreference(sourceFile, preferences); + return fixes.map(function (fix) { return codeActionForFix(context, sourceFile, symbolName, fix, quotePreference); }); + }, + fixIds: [codefix.importFixId], + getAllCodeActions: function (context) { + var sourceFile = context.sourceFile, preferences = context.preferences; + // Namespace fixes don't conflict, so just build a list. + var addToNamespace = []; + var importType = []; + // Keys are import clause node IDs. + var addToExisting = ts.createMap(); + // Keys are module specifiers. + var newImports = ts.createMap(); + codefix.eachDiagnostic(context, errorCodes, function (diag) { + var info = getFixesInfo(context, diag.code, diag.start); + if (!info || !info.fixes.length) + return; + var fixes = info.fixes, symbolName = info.symbolName; + var fix = ts.first(fixes); + switch (fix.kind) { + case 0 /* UseNamespace */: + addToNamespace.push(fix); + break; + case 1 /* ImportType */: + importType.push(fix); + break; + case 2 /* AddToExisting */: { + var importClause = fix.importClause, importKind = fix.importKind; + var key = String(ts.getNodeId(importClause)); + var entry = addToExisting.get(key); + if (!entry) { + addToExisting.set(key, entry = { importClause: importClause, defaultImport: undefined, namedImports: [] }); + } + if (importKind === 0 /* Named */) { + ts.pushIfUnique(entry.namedImports, symbolName); + } + else { + ts.Debug.assert(entry.defaultImport === undefined || entry.defaultImport === symbolName); + entry.defaultImport = symbolName; + } + break; + } + case 3 /* AddNew */: { + var moduleSpecifier = fix.moduleSpecifier, importKind = fix.importKind; + var entry = newImports.get(moduleSpecifier); + if (!entry) { + newImports.set(moduleSpecifier, entry = { defaultImport: undefined, namedImports: [], namespaceLikeImport: undefined }); + } + switch (importKind) { + case 1 /* Default */: + ts.Debug.assert(entry.defaultImport === undefined || entry.defaultImport === symbolName); + entry.defaultImport = symbolName; + break; + case 0 /* Named */: + ts.pushIfUnique(entry.namedImports, symbolName); + break; + case 3 /* Equals */: + case 2 /* Namespace */: + ts.Debug.assert(entry.namespaceLikeImport === undefined || entry.namespaceLikeImport.name === symbolName); + entry.namespaceLikeImport = { importKind: importKind, name: symbolName }; + break; + } + break; + } + default: + ts.Debug.assertNever(fix); + } + }); + return codefix.createCombinedCodeActions(ts.textChanges.ChangeTracker.with(context, function (changes) { + var quotePreference = ts.getQuotePreference(sourceFile, preferences); + for (var _i = 0, addToNamespace_1 = addToNamespace; _i < addToNamespace_1.length; _i++) { + var fix = addToNamespace_1[_i]; + addNamespaceQualifier(changes, sourceFile, fix); + } + for (var _a = 0, importType_1 = importType; _a < importType_1.length; _a++) { + var fix = importType_1[_a]; + addImportType(changes, sourceFile, fix, quotePreference); + } + addToExisting.forEach(function (_a) { + var importClause = _a.importClause, defaultImport = _a.defaultImport, namedImports = _a.namedImports; + doAddExistingFix(changes, sourceFile, importClause, defaultImport, namedImports); + }); + newImports.forEach(function (imports, moduleSpecifier) { + addNewImports(changes, sourceFile, moduleSpecifier, quotePreference, imports); + }); + })); + }, + }); + // Sorted with the preferred fix coming first. + var ImportFixKind; + (function (ImportFixKind) { + ImportFixKind[ImportFixKind["UseNamespace"] = 0] = "UseNamespace"; + ImportFixKind[ImportFixKind["ImportType"] = 1] = "ImportType"; + ImportFixKind[ImportFixKind["AddToExisting"] = 2] = "AddToExisting"; + ImportFixKind[ImportFixKind["AddNew"] = 3] = "AddNew"; + })(ImportFixKind || (ImportFixKind = {})); + var ImportKind; + (function (ImportKind) { + ImportKind[ImportKind["Named"] = 0] = "Named"; + ImportKind[ImportKind["Default"] = 1] = "Default"; + ImportKind[ImportKind["Namespace"] = 2] = "Namespace"; + ImportKind[ImportKind["Equals"] = 3] = "Equals"; + })(ImportKind || (ImportKind = {})); + function getImportCompletionAction(exportedSymbol, moduleSymbol, sourceFile, symbolName, host, program, formatContext, position, preferences) { + var exportInfos = getAllReExportingModules(exportedSymbol, moduleSymbol, symbolName, sourceFile, program.getCompilerOptions(), program.getTypeChecker(), program.getSourceFiles()); + ts.Debug.assert(exportInfos.some(function (info) { return info.moduleSymbol === moduleSymbol; })); + // We sort the best codefixes first, so taking `first` is best for completions. + var moduleSpecifier = ts.first(getNewImportInfos(program, sourceFile, position, exportInfos, host, preferences)).moduleSpecifier; + var fix = ts.first(getFixForImport(exportInfos, symbolName, position, program, sourceFile, host, preferences)); + return { moduleSpecifier: moduleSpecifier, codeAction: codeFixActionToCodeAction(codeActionForFix({ host: host, formatContext: formatContext }, sourceFile, symbolName, fix, ts.getQuotePreference(sourceFile, preferences))) }; + } + codefix.getImportCompletionAction = getImportCompletionAction; + function codeFixActionToCodeAction(_a) { + var description = _a.description, changes = _a.changes, commands = _a.commands; + return { description: description, changes: changes, commands: commands }; + } + function getAllReExportingModules(exportedSymbol, exportingModuleSymbol, symbolName, sourceFile, compilerOptions, checker, allSourceFiles) { + var result = []; + forEachExternalModule(checker, allSourceFiles, function (moduleSymbol, moduleFile) { + // Don't import from a re-export when looking "up" like to `./index` or `../index`. + if (moduleFile && moduleSymbol !== exportingModuleSymbol && ts.startsWith(sourceFile.fileName, ts.getDirectoryPath(moduleFile.fileName))) { + return; + } + var defaultInfo = getDefaultLikeExportInfo(moduleSymbol, checker, compilerOptions); + if (defaultInfo && defaultInfo.name === symbolName && ts.skipAlias(defaultInfo.symbol, checker) === exportedSymbol) { + result.push({ moduleSymbol: moduleSymbol, importKind: defaultInfo.kind, exportedSymbolIsTypeOnly: isTypeOnlySymbol(defaultInfo.symbol, checker) }); + } + for (var _i = 0, _a = checker.getExportsOfModule(moduleSymbol); _i < _a.length; _i++) { + var exported = _a[_i]; + if (exported.name === symbolName && ts.skipAlias(exported, checker) === exportedSymbol) { + result.push({ moduleSymbol: moduleSymbol, importKind: 0 /* Named */, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exported, checker) }); + } + } + }); + return result; + } + function isTypeOnlySymbol(s, checker) { + return !(ts.skipAlias(s, checker).flags & 67220415 /* Value */); + } + function getFixForImport(exportInfos, symbolName, position, program, sourceFile, host, preferences) { + var checker = program.getTypeChecker(); + var existingImports = ts.flatMap(exportInfos, function (info) { return getExistingImportDeclarations(info, checker, sourceFile); }); + var useNamespace = position === undefined ? undefined : tryUseExistingNamespaceImport(existingImports, symbolName, position, checker); + var addToExisting = tryAddToExistingImport(existingImports); + // Don't bother providing an action to add a new import if we can add to an existing one. + var addImport = addToExisting ? [addToExisting] : getFixesForAddImport(exportInfos, existingImports, program, sourceFile, position, host, preferences); + return (useNamespace ? [useNamespace] : ts.emptyArray).concat(addImport); + } + function tryUseExistingNamespaceImport(existingImports, symbolName, position, checker) { + // It is possible that multiple import statements with the same specifier exist in the file. + // e.g. + // + // import * as ns from "foo"; + // import { member1, member2 } from "foo"; + // + // member3/**/ <-- cusor here + // + // in this case we should provie 2 actions: + // 1. change "member3" to "ns.member3" + // 2. add "member3" to the second import statement's import list + // and it is up to the user to decide which one fits best. + return ts.firstDefined(existingImports, function (_a) { + var declaration = _a.declaration; + var namespace = getNamespaceImportName(declaration); + if (namespace) { + var moduleSymbol = checker.getAliasedSymbol(checker.getSymbolAtLocation(namespace)); + if (moduleSymbol && moduleSymbol.exports.has(ts.escapeLeadingUnderscores(symbolName))) { + return { kind: 0 /* UseNamespace */, namespacePrefix: namespace.text, position: position }; + } + } + }); + } + function tryAddToExistingImport(existingImports) { + return ts.firstDefined(existingImports, function (_a) { + var declaration = _a.declaration, importKind = _a.importKind; + if (declaration.kind !== 249 /* ImportDeclaration */) + return undefined; + var importClause = declaration.importClause; + if (!importClause) + return undefined; + var name = importClause.name, namedBindings = importClause.namedBindings; + return importKind === 1 /* Default */ && !name || importKind === 0 /* Named */ && (!namedBindings || namedBindings.kind === 252 /* NamedImports */) + ? { kind: 2 /* AddToExisting */, importClause: importClause, importKind: importKind } + : undefined; + }); + } + function getNamespaceImportName(declaration) { + if (declaration.kind === 249 /* ImportDeclaration */) { + var namedBindings = declaration.importClause && ts.isImportClause(declaration.importClause) && declaration.importClause.namedBindings; + return namedBindings && namedBindings.kind === 251 /* NamespaceImport */ ? namedBindings.name : undefined; + } + else { + return declaration.name; + } + } + function getExistingImportDeclarations(_a, checker, sourceFile) { + var moduleSymbol = _a.moduleSymbol, importKind = _a.importKind, exportedSymbolIsTypeOnly = _a.exportedSymbolIsTypeOnly; + // Can't use an es6 import for a type in JS. + return exportedSymbolIsTypeOnly && ts.isSourceFileJS(sourceFile) ? ts.emptyArray : ts.mapDefined(sourceFile.imports, function (moduleSpecifier) { + var i = ts.importFromModuleSpecifier(moduleSpecifier); + return (i.kind === 249 /* ImportDeclaration */ || i.kind === 248 /* ImportEqualsDeclaration */) + && checker.getSymbolAtLocation(moduleSpecifier) === moduleSymbol ? { declaration: i, importKind: importKind } : undefined; + }); + } + function getNewImportInfos(program, sourceFile, position, moduleSymbols, host, preferences) { + var isJs = ts.isSourceFileJS(sourceFile); + var choicesForEachExportingModule = ts.flatMap(moduleSymbols, function (_a) { + var moduleSymbol = _a.moduleSymbol, importKind = _a.importKind, exportedSymbolIsTypeOnly = _a.exportedSymbolIsTypeOnly; + return ts.moduleSpecifiers.getModuleSpecifiers(moduleSymbol, program.getCompilerOptions(), sourceFile, host, program.getSourceFiles(), preferences, program.redirectTargetsMap) + .map(function (moduleSpecifier) { + // `position` should only be undefined at a missing jsx namespace, in which case we shouldn't be looking for pure types. + return exportedSymbolIsTypeOnly && isJs ? { kind: 1 /* ImportType */, moduleSpecifier: moduleSpecifier, position: ts.Debug.assertDefined(position) } : { kind: 3 /* AddNew */, moduleSpecifier: moduleSpecifier, importKind: importKind }; + }); + }); + // Sort to keep the shortest paths first + return ts.sort(choicesForEachExportingModule, function (a, b) { return a.moduleSpecifier.length - b.moduleSpecifier.length; }); + } + function getFixesForAddImport(exportInfos, existingImports, program, sourceFile, position, host, preferences) { + var existingDeclaration = ts.firstDefined(existingImports, newImportInfoFromExistingSpecifier); + return existingDeclaration ? [existingDeclaration] : getNewImportInfos(program, sourceFile, position, exportInfos, host, preferences); + } + function newImportInfoFromExistingSpecifier(_a) { + var declaration = _a.declaration, importKind = _a.importKind; + var expression = declaration.kind === 249 /* ImportDeclaration */ + ? declaration.moduleSpecifier + : declaration.moduleReference.kind === 259 /* ExternalModuleReference */ + ? declaration.moduleReference.expression + : undefined; + return expression && ts.isStringLiteral(expression) ? { kind: 3 /* AddNew */, moduleSpecifier: expression.text, importKind: importKind } : undefined; + } + function getFixesInfo(context, errorCode, pos) { + var symbolToken = ts.getTokenAtPosition(context.sourceFile, pos); + var info = errorCode === ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code + ? getFixesInfoForUMDImport(context, symbolToken) + : ts.isIdentifier(symbolToken) ? getFixesInfoForNonUMDImport(context, symbolToken) : undefined; + return info && __assign({}, info, { fixes: ts.sort(info.fixes, function (a, b) { return a.kind - b.kind; }) }); + } + function getFixesInfoForUMDImport(_a, token) { + var sourceFile = _a.sourceFile, program = _a.program, host = _a.host, preferences = _a.preferences; + var checker = program.getTypeChecker(); + var umdSymbol = getUmdSymbol(token, checker); + if (!umdSymbol) + return undefined; + var symbol = checker.getAliasedSymbol(umdSymbol); + var symbolName = umdSymbol.name; + var exportInfos = [{ moduleSymbol: symbol, importKind: getUmdImportKind(program.getCompilerOptions()), exportedSymbolIsTypeOnly: false }]; + var fixes = getFixForImport(exportInfos, symbolName, ts.isIdentifier(token) ? token.getStart(sourceFile) : undefined, program, sourceFile, host, preferences); + return { fixes: fixes, symbolName: symbolName }; + } + function getUmdSymbol(token, checker) { + // try the identifier to see if it is the umd symbol + var umdSymbol = ts.isIdentifier(token) ? checker.getSymbolAtLocation(token) : undefined; + if (ts.isUMDExportSymbol(umdSymbol)) + return umdSymbol; + // The error wasn't for the symbolAtLocation, it was for the JSX tag itself, which needs access to e.g. `React`. + var parent = token.parent; + return (ts.isJsxOpeningLikeElement(parent) && parent.tagName === token) || ts.isJsxOpeningFragment(parent) + ? ts.tryCast(checker.resolveName(checker.getJsxNamespace(parent), ts.isJsxOpeningLikeElement(parent) ? token : parent, 67220415 /* Value */, /*excludeGlobals*/ false), ts.isUMDExportSymbol) + : undefined; + } + function getUmdImportKind(compilerOptions) { + // Import a synthetic `default` if enabled. + if (ts.getAllowSyntheticDefaultImports(compilerOptions)) { + return 1 /* Default */; + } + // When a synthetic `default` is unavailable, use `import..require` if the module kind supports it. + var moduleKind = ts.getEmitModuleKind(compilerOptions); + switch (moduleKind) { + case ts.ModuleKind.AMD: + case ts.ModuleKind.CommonJS: + case ts.ModuleKind.UMD: + return 3 /* Equals */; + case ts.ModuleKind.System: + case ts.ModuleKind.ES2015: + case ts.ModuleKind.ESNext: + case ts.ModuleKind.None: + // Fall back to the `import * as ns` style import. + return 2 /* Namespace */; + default: + return ts.Debug.assertNever(moduleKind); + } + } + function getFixesInfoForNonUMDImport(_a, symbolToken) { + var sourceFile = _a.sourceFile, program = _a.program, cancellationToken = _a.cancellationToken, host = _a.host, preferences = _a.preferences; + var checker = program.getTypeChecker(); + // If we're at ``, we must check if `Foo` is already in scope, and if so, get an import for `React` instead. + var symbolName = ts.isJsxOpeningLikeElement(symbolToken.parent) + && symbolToken.parent.tagName === symbolToken + && (ts.isIntrinsicJsxName(symbolToken.text) || checker.resolveName(symbolToken.text, symbolToken, 67108863 /* All */, /*excludeGlobals*/ false)) + ? checker.getJsxNamespace() + : symbolToken.text; + // "default" is a keyword and not a legal identifier for the import, so we don't expect it here + ts.Debug.assert(symbolName !== "default" /* Default */); + var fixes = ts.arrayFrom(ts.flatMapIterator(getExportInfos(symbolName, ts.getMeaningFromLocation(symbolToken), cancellationToken, sourceFile, checker, program).entries(), function (_a) { + var _ = _a[0], exportInfos = _a[1]; + return getFixForImport(exportInfos, symbolName, symbolToken.getStart(sourceFile), program, sourceFile, host, preferences); + })); + return { fixes: fixes, symbolName: symbolName }; + } + // Returns a map from an exported symbol's ID to a list of every way it's (re-)exported. + function getExportInfos(symbolName, currentTokenMeaning, cancellationToken, sourceFile, checker, program) { + // For each original symbol, keep all re-exports of that symbol together so we can call `getCodeActionsForImport` on the whole group at once. + // Maps symbol id to info for modules providing that symbol (original export + re-exports). + var originalSymbolToExportInfos = ts.createMultiMap(); + function addSymbol(moduleSymbol, exportedSymbol, importKind) { + originalSymbolToExportInfos.add(ts.getUniqueSymbolId(exportedSymbol, checker).toString(), { moduleSymbol: moduleSymbol, importKind: importKind, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exportedSymbol, checker) }); + } + forEachExternalModuleToImportFrom(checker, sourceFile, program.getSourceFiles(), function (moduleSymbol) { + cancellationToken.throwIfCancellationRequested(); + var defaultInfo = getDefaultLikeExportInfo(moduleSymbol, checker, program.getCompilerOptions()); + if (defaultInfo && defaultInfo.name === symbolName && symbolHasMeaning(defaultInfo.symbolForMeaning, currentTokenMeaning)) { + addSymbol(moduleSymbol, defaultInfo.symbol, defaultInfo.kind); + } + // check exports with the same name + var exportSymbolWithIdenticalName = checker.tryGetMemberInModuleExportsAndProperties(symbolName, moduleSymbol); + if (exportSymbolWithIdenticalName && symbolHasMeaning(exportSymbolWithIdenticalName, currentTokenMeaning)) { + addSymbol(moduleSymbol, exportSymbolWithIdenticalName, 0 /* Named */); + } + }); + return originalSymbolToExportInfos; + } + function getDefaultLikeExportInfo(moduleSymbol, checker, compilerOptions) { + var exported = getDefaultLikeExportWorker(moduleSymbol, checker); + if (!exported) + return undefined; + var symbol = exported.symbol, kind = exported.kind; + var info = getDefaultExportInfoWorker(symbol, moduleSymbol, checker, compilerOptions); + return info && __assign({ symbol: symbol, kind: kind }, info); + } + function getDefaultLikeExportWorker(moduleSymbol, checker) { + var defaultExport = checker.tryGetMemberInModuleExports("default" /* Default */, moduleSymbol); + if (defaultExport) + return { symbol: defaultExport, kind: 1 /* Default */ }; + var exportEquals = checker.resolveExternalModuleSymbol(moduleSymbol); + return exportEquals === moduleSymbol ? undefined : { symbol: exportEquals, kind: 3 /* Equals */ }; + } + function getDefaultExportInfoWorker(defaultExport, moduleSymbol, checker, compilerOptions) { + var localSymbol = ts.getLocalSymbolForExportDefault(defaultExport); + if (localSymbol) + return { symbolForMeaning: localSymbol, name: localSymbol.name }; + var name = getNameForExportDefault(defaultExport); + if (name !== undefined) + return { symbolForMeaning: defaultExport, name: name }; + if (defaultExport.flags & 2097152 /* Alias */) { + var aliased = checker.getImmediateAliasedSymbol(defaultExport); + return aliased && getDefaultExportInfoWorker(aliased, ts.Debug.assertDefined(aliased.parent), checker, compilerOptions); + } + else { + return { symbolForMeaning: defaultExport, name: moduleSymbolToValidIdentifier(moduleSymbol, compilerOptions.target) }; + } + } + function getNameForExportDefault(symbol) { + return symbol.declarations && ts.firstDefined(symbol.declarations, function (declaration) { + if (ts.isExportAssignment(declaration)) { + if (ts.isIdentifier(declaration.expression)) { + return declaration.expression.text; + } + } + else if (ts.isExportSpecifier(declaration)) { + ts.Debug.assert(declaration.name.text === "default" /* Default */); + return declaration.propertyName && declaration.propertyName.text; + } + }); + } + function codeActionForFix(context, sourceFile, symbolName, fix, quotePreference) { + var diag; + var changes = ts.textChanges.ChangeTracker.with(context, function (tracker) { + diag = codeActionForFixWorker(tracker, sourceFile, symbolName, fix, quotePreference); + }); + return codefix.createCodeFixAction("import", changes, diag, codefix.importFixId, ts.Diagnostics.Add_all_missing_imports); + } + function codeActionForFixWorker(changes, sourceFile, symbolName, fix, quotePreference) { + switch (fix.kind) { + case 0 /* UseNamespace */: + addNamespaceQualifier(changes, sourceFile, fix); + return [ts.Diagnostics.Change_0_to_1, symbolName, fix.namespacePrefix + "." + symbolName]; + case 1 /* ImportType */: + addImportType(changes, sourceFile, fix, quotePreference); + return [ts.Diagnostics.Change_0_to_1, symbolName, getImportTypePrefix(fix.moduleSpecifier, quotePreference) + symbolName]; + case 2 /* AddToExisting */: { + var importClause = fix.importClause, importKind = fix.importKind; + doAddExistingFix(changes, sourceFile, importClause, importKind === 1 /* Default */ ? symbolName : undefined, importKind === 0 /* Named */ ? [symbolName] : ts.emptyArray); + var moduleSpecifierWithoutQuotes = ts.stripQuotes(importClause.parent.moduleSpecifier.getText()); + return [importKind === 1 /* Default */ ? ts.Diagnostics.Add_default_import_0_to_existing_import_declaration_from_1 : ts.Diagnostics.Add_0_to_existing_import_declaration_from_1, symbolName, moduleSpecifierWithoutQuotes]; // you too! + } + case 3 /* AddNew */: { + var importKind = fix.importKind, moduleSpecifier = fix.moduleSpecifier; + addNewImports(changes, sourceFile, moduleSpecifier, quotePreference, importKind === 1 /* Default */ ? { defaultImport: symbolName, namedImports: ts.emptyArray, namespaceLikeImport: undefined } + : importKind === 0 /* Named */ ? { defaultImport: undefined, namedImports: [symbolName], namespaceLikeImport: undefined } + : { defaultImport: undefined, namedImports: ts.emptyArray, namespaceLikeImport: { importKind: importKind, name: symbolName } }); + return [importKind === 1 /* Default */ ? ts.Diagnostics.Import_default_0_from_module_1 : ts.Diagnostics.Import_0_from_module_1, symbolName, moduleSpecifier]; + } + default: + return ts.Debug.assertNever(fix); + } + } + function doAddExistingFix(changes, sourceFile, clause, defaultImport, namedImports) { + if (defaultImport) { + ts.Debug.assert(!clause.name); + changes.insertNodeAt(sourceFile, clause.getStart(sourceFile), ts.createIdentifier(defaultImport), { suffix: ", " }); + } + if (namedImports.length) { + var specifiers = namedImports.map(function (name) { return ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(name)); }); + if (clause.namedBindings && ts.cast(clause.namedBindings, ts.isNamedImports).elements.length) { + for (var _i = 0, specifiers_1 = specifiers; _i < specifiers_1.length; _i++) { + var spec = specifiers_1[_i]; + changes.insertNodeInListAfter(sourceFile, ts.last(ts.cast(clause.namedBindings, ts.isNamedImports).elements), spec); + } + } + else { + if (specifiers.length) { + var namedImports_1 = ts.createNamedImports(specifiers); + if (clause.namedBindings) { + changes.replaceNode(sourceFile, clause.namedBindings, namedImports_1); + } + else { + changes.insertNodeAfter(sourceFile, ts.Debug.assertDefined(clause.name), namedImports_1); + } + } + } + } + } + function addNamespaceQualifier(changes, sourceFile, _a) { + var namespacePrefix = _a.namespacePrefix, position = _a.position; + changes.insertText(sourceFile, position, namespacePrefix + "."); + } + function addImportType(changes, sourceFile, _a, quotePreference) { + var moduleSpecifier = _a.moduleSpecifier, position = _a.position; + changes.insertText(sourceFile, position, getImportTypePrefix(moduleSpecifier, quotePreference)); + } + function getImportTypePrefix(moduleSpecifier, quotePreference) { + var quote = ts.getQuoteFromPreference(quotePreference); + return "import(" + quote + moduleSpecifier + quote + ")."; + } + function addNewImports(changes, sourceFile, moduleSpecifier, quotePreference, _a) { + var defaultImport = _a.defaultImport, namedImports = _a.namedImports, namespaceLikeImport = _a.namespaceLikeImport; + var quotedModuleSpecifier = ts.makeStringLiteral(moduleSpecifier, quotePreference); + if (defaultImport !== undefined || namedImports.length) { + ts.insertImport(changes, sourceFile, ts.makeImport(defaultImport === undefined ? undefined : ts.createIdentifier(defaultImport), namedImports.map(function (n) { return ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(n)); }), moduleSpecifier, quotePreference)); + } + if (namespaceLikeImport) { + ts.insertImport(changes, sourceFile, namespaceLikeImport.importKind === 3 /* Equals */ + ? ts.createImportEqualsDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createIdentifier(namespaceLikeImport.name), ts.createExternalModuleReference(quotedModuleSpecifier)) + : ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(ts.createIdentifier(namespaceLikeImport.name))), quotedModuleSpecifier)); + } + } + function symbolHasMeaning(_a, meaning) { + var declarations = _a.declarations; + return ts.some(declarations, function (decl) { return !!(ts.getMeaningFromDeclaration(decl) & meaning); }); + } + function forEachExternalModuleToImportFrom(checker, from, allSourceFiles, cb) { + forEachExternalModule(checker, allSourceFiles, function (module, sourceFile) { + if (sourceFile === undefined || sourceFile !== from && isImportablePath(from.fileName, sourceFile.fileName)) { + cb(module); + } + }); + } + codefix.forEachExternalModuleToImportFrom = forEachExternalModuleToImportFrom; + function forEachExternalModule(checker, allSourceFiles, cb) { + for (var _i = 0, _a = checker.getAmbientModules(); _i < _a.length; _i++) { + var ambient = _a[_i]; + cb(ambient, /*sourceFile*/ undefined); + } + for (var _b = 0, allSourceFiles_1 = allSourceFiles; _b < allSourceFiles_1.length; _b++) { + var sourceFile = allSourceFiles_1[_b]; + if (ts.isExternalOrCommonJsModule(sourceFile)) { + cb(checker.getMergedSymbol(sourceFile.symbol), sourceFile); + } + } + } + /** + * Don't include something from a `node_modules` that isn't actually reachable by a global import. + * A relative import to node_modules is usually a bad idea. + */ + function isImportablePath(fromPath, toPath) { + // If it's in a `node_modules` but is not reachable from here via a global import, don't bother. + var toNodeModules = ts.forEachAncestorDirectory(toPath, function (ancestor) { return ts.getBaseFileName(ancestor) === "node_modules" ? ancestor : undefined; }); + return toNodeModules === undefined || ts.startsWith(fromPath, ts.getDirectoryPath(toNodeModules)); + } + function moduleSymbolToValidIdentifier(moduleSymbol, target) { + return moduleSpecifierToValidIdentifier(ts.removeFileExtension(ts.stripQuotes(moduleSymbol.name)), target); + } + codefix.moduleSymbolToValidIdentifier = moduleSymbolToValidIdentifier; + function moduleSpecifierToValidIdentifier(moduleSpecifier, target) { + var baseName = ts.getBaseFileName(ts.removeSuffix(moduleSpecifier, "/index")); + var res = ""; + var lastCharWasValid = true; + var firstCharCode = baseName.charCodeAt(0); + if (ts.isIdentifierStart(firstCharCode, target)) { + res += String.fromCharCode(firstCharCode); + } + else { + lastCharWasValid = false; + } + for (var i = 1; i < baseName.length; i++) { + var ch = baseName.charCodeAt(i); + var isValid = ts.isIdentifierPart(ch, target); + if (isValid) { + var char = String.fromCharCode(ch); + if (!lastCharWasValid) { + char = char.toUpperCase(); + } + res += char; + } + lastCharWasValid = isValid; + } + // Need `|| "_"` to ensure result isn't empty. + return !ts.isStringANonContextualKeyword(res) ? res || "_" : "_" + res; + } + codefix.moduleSpecifierToValidIdentifier = moduleSpecifierToValidIdentifier; + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "fixSpelling"; + var errorCodes = [ + ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2.code, + ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1.code, + ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0.code, + ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_static_member_1_0.code, + ts.Diagnostics.Module_0_has_no_exported_member_1_Did_you_mean_2.code, + ]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var sourceFile = context.sourceFile; + var info = getInfo(sourceFile, context.span.start, context); + if (!info) + return undefined; + var node = info.node, suggestion = info.suggestion; + var target = context.host.getCompilationSettings().target; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, node, suggestion, target); }); + return [codefix.createCodeFixAction("spelling", changes, [ts.Diagnostics.Change_spelling_to_0, suggestion], fixId, ts.Diagnostics.Fix_all_detected_spelling_errors)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var info = getInfo(diag.file, diag.start, context); + var target = context.host.getCompilationSettings().target; + if (info) + doChange(changes, context.sourceFile, info.node, info.suggestion, target); + }); }, + }); + function getInfo(sourceFile, pos, context) { + // This is the identifier of the misspelled word. eg: + // this.speling = 1; + // ^^^^^^^ + var node = ts.getTokenAtPosition(sourceFile, pos); + var checker = context.program.getTypeChecker(); + var suggestion; + if (ts.isPropertyAccessExpression(node.parent) && node.parent.name === node) { + ts.Debug.assert(node.kind === 72 /* Identifier */); + var containingType = checker.getTypeAtLocation(node.parent.expression); + suggestion = checker.getSuggestionForNonexistentProperty(node, containingType); + } + else if (ts.isImportSpecifier(node.parent) && node.parent.name === node) { + ts.Debug.assert(node.kind === 72 /* Identifier */); + var importDeclaration = ts.findAncestor(node, ts.isImportDeclaration); + var resolvedSourceFile = getResolvedSourceFileFromImportDeclaration(sourceFile, context, importDeclaration); + if (resolvedSourceFile && resolvedSourceFile.symbol) { + suggestion = checker.getSuggestionForNonexistentExport(node, resolvedSourceFile.symbol); + } + } + else { + var meaning = ts.getMeaningFromLocation(node); + var name = ts.getTextOfNode(node); + ts.Debug.assert(name !== undefined, "name should be defined"); + suggestion = checker.getSuggestionForNonexistentSymbol(node, name, convertSemanticMeaningToSymbolFlags(meaning)); + } + return suggestion === undefined ? undefined : { node: node, suggestion: suggestion }; + } + function doChange(changes, sourceFile, node, suggestion, target) { + if (!ts.isIdentifierText(suggestion, target) && ts.isPropertyAccessExpression(node.parent)) { + changes.replaceNode(sourceFile, node.parent, ts.createElementAccess(node.parent.expression, ts.createLiteral(suggestion))); + } + else { + changes.replaceNode(sourceFile, node, ts.createIdentifier(suggestion)); + } + } + function convertSemanticMeaningToSymbolFlags(meaning) { + var flags = 0; + if (meaning & 4 /* Namespace */) { + flags |= 1920 /* Namespace */; + } + if (meaning & 2 /* Type */) { + flags |= 67897832 /* Type */; + } + if (meaning & 1 /* Value */) { + flags |= 67220415 /* Value */; + } + return flags; + } + function getResolvedSourceFileFromImportDeclaration(sourceFile, context, importDeclaration) { + if (!importDeclaration || !ts.isStringLiteralLike(importDeclaration.moduleSpecifier)) + return undefined; + var resolvedModule = ts.getResolvedModule(sourceFile, importDeclaration.moduleSpecifier.text); + if (!resolvedModule) + return undefined; + return context.program.getSourceFile(resolvedModule.resolvedFileName); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixName = "addMissingMember"; + var errorCodes = [ + ts.Diagnostics.Property_0_does_not_exist_on_type_1.code, + ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2.code, + ts.Diagnostics.Property_0_is_missing_in_type_1_but_required_in_type_2.code, + ts.Diagnostics.Type_0_is_missing_the_following_properties_from_type_1_Colon_2.code, + ts.Diagnostics.Type_0_is_missing_the_following_properties_from_type_1_Colon_2_and_3_more.code + ]; + var fixId = "addMissingMember"; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var info = getInfo(context.sourceFile, context.span.start, context.program.getTypeChecker()); + if (!info) + return undefined; + if (info.kind === 0 /* Enum */) { + var token_1 = info.token, parentDeclaration_1 = info.parentDeclaration; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addEnumMemberDeclaration(t, context.program.getTypeChecker(), token_1, parentDeclaration_1); }); + return [codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Add_missing_enum_member_0, token_1.text], fixId, ts.Diagnostics.Add_all_missing_members)]; + } + var parentDeclaration = info.parentDeclaration, declSourceFile = info.declSourceFile, inJs = info.inJs, makeStatic = info.makeStatic, token = info.token, call = info.call; + var methodCodeAction = call && getActionForMethodDeclaration(context, declSourceFile, parentDeclaration, token, call, makeStatic, inJs, context.preferences); + var addMember = inJs && !ts.isInterfaceDeclaration(parentDeclaration) ? + ts.singleElementArray(getActionsForAddMissingMemberInJavascriptFile(context, declSourceFile, parentDeclaration, token.text, makeStatic)) : + getActionsForAddMissingMemberInTypeScriptFile(context, declSourceFile, parentDeclaration, token, makeStatic); + return ts.concatenate(ts.singleElementArray(methodCodeAction), addMember); + }, + fixIds: [fixId], + getAllCodeActions: function (context) { + var program = context.program, preferences = context.preferences; + var checker = program.getTypeChecker(); + var seen = ts.createMap(); + var typeDeclToMembers = new ts.NodeMap(); + return codefix.createCombinedCodeActions(ts.textChanges.ChangeTracker.with(context, function (changes) { + codefix.eachDiagnostic(context, errorCodes, function (diag) { + var info = getInfo(diag.file, diag.start, checker); + if (!info || !ts.addToSeen(seen, ts.getNodeId(info.parentDeclaration) + "#" + info.token.text)) { + return; + } + if (info.kind === 0 /* Enum */) { + var token = info.token, parentDeclaration = info.parentDeclaration; + addEnumMemberDeclaration(changes, checker, token, parentDeclaration); + } + else { + var parentDeclaration = info.parentDeclaration, token_2 = info.token; + var infos = typeDeclToMembers.getOrUpdate(parentDeclaration, function () { return []; }); + if (!infos.some(function (i) { return i.token.text === token_2.text; })) + infos.push(info); + } + }); + typeDeclToMembers.forEach(function (infos, classDeclaration) { + var supers = getAllSupers(classDeclaration, checker); + var _loop_20 = function (info) { + // If some superclass added this property, don't add it again. + if (supers.some(function (superClassOrInterface) { + var superInfos = typeDeclToMembers.get(superClassOrInterface); + return !!superInfos && superInfos.some(function (_a) { + var token = _a.token; + return token.text === info.token.text; + }); + })) + return "continue"; + var parentDeclaration = info.parentDeclaration, declSourceFile = info.declSourceFile, inJs = info.inJs, makeStatic = info.makeStatic, token = info.token, call = info.call; + // Always prefer to add a method declaration if possible. + if (call) { + addMethodDeclaration(context, changes, declSourceFile, parentDeclaration, token, call, makeStatic, inJs, preferences); + } + else { + if (inJs && !ts.isInterfaceDeclaration(parentDeclaration)) { + addMissingMemberInJs(changes, declSourceFile, parentDeclaration, token.text, makeStatic); + } + else { + var typeNode = getTypeNode(program.getTypeChecker(), parentDeclaration, token); + addPropertyDeclaration(changes, declSourceFile, parentDeclaration, token.text, typeNode, makeStatic); + } + } + }; + for (var _i = 0, infos_1 = infos; _i < infos_1.length; _i++) { + var info = infos_1[_i]; + _loop_20(info); + } + }); + })); + }, + }); + function getAllSupers(decl, checker) { + var res = []; + while (decl) { + var superElement = ts.getClassExtendsHeritageElement(decl); + var superSymbol = superElement && checker.getSymbolAtLocation(superElement.expression); + var superDecl = superSymbol && ts.find(superSymbol.declarations, ts.isClassLike); + if (superDecl) { + res.push(superDecl); + } + decl = superDecl; + } + return res; + } + var InfoKind; + (function (InfoKind) { + InfoKind[InfoKind["Enum"] = 0] = "Enum"; + InfoKind[InfoKind["ClassOrInterface"] = 1] = "ClassOrInterface"; + })(InfoKind || (InfoKind = {})); + function getInfo(tokenSourceFile, tokenPos, checker) { + // The identifier of the missing property. eg: + // this.missing = 1; + // ^^^^^^^ + var token = ts.getTokenAtPosition(tokenSourceFile, tokenPos); + if (!ts.isIdentifier(token)) { + return undefined; + } + var parent = token.parent; + if (!ts.isPropertyAccessExpression(parent)) + return undefined; + var leftExpressionType = ts.skipConstraint(checker.getTypeAtLocation(parent.expression)); + var symbol = leftExpressionType.symbol; + if (!symbol || !symbol.declarations) + return undefined; + // Prefer to change the class instead of the interface if they are merged + var classOrInterface = ts.find(symbol.declarations, ts.isClassLike) || ts.find(symbol.declarations, ts.isInterfaceDeclaration); + if (classOrInterface) { + var makeStatic = (leftExpressionType.target || leftExpressionType) !== checker.getDeclaredTypeOfSymbol(symbol); + var declSourceFile = classOrInterface.getSourceFile(); + var inJs = ts.isSourceFileJS(declSourceFile); + var call = ts.tryCast(parent.parent, ts.isCallExpression); + return { kind: 1 /* ClassOrInterface */, token: token, parentDeclaration: classOrInterface, makeStatic: makeStatic, declSourceFile: declSourceFile, inJs: inJs, call: call }; + } + var enumDeclaration = ts.find(symbol.declarations, ts.isEnumDeclaration); + if (enumDeclaration) { + return { kind: 0 /* Enum */, token: token, parentDeclaration: enumDeclaration }; + } + return undefined; + } + function getActionsForAddMissingMemberInJavascriptFile(context, declSourceFile, classDeclaration, tokenName, makeStatic) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMissingMemberInJs(t, declSourceFile, classDeclaration, tokenName, makeStatic); }); + return changes.length === 0 ? undefined + : codefix.createCodeFixAction(fixName, changes, [makeStatic ? ts.Diagnostics.Initialize_static_property_0 : ts.Diagnostics.Initialize_property_0_in_the_constructor, tokenName], fixId, ts.Diagnostics.Add_all_missing_members); + } + function addMissingMemberInJs(changeTracker, declSourceFile, classDeclaration, tokenName, makeStatic) { + if (makeStatic) { + if (classDeclaration.kind === 209 /* ClassExpression */) { + return; + } + var className = classDeclaration.name.getText(); + var staticInitialization = initializePropertyToUndefined(ts.createIdentifier(className), tokenName); + changeTracker.insertNodeAfter(declSourceFile, classDeclaration, staticInitialization); + } + else { + var classConstructor = ts.getFirstConstructorWithBody(classDeclaration); + if (!classConstructor) { + return; + } + var propertyInitialization = initializePropertyToUndefined(ts.createThis(), tokenName); + changeTracker.insertNodeAtConstructorEnd(declSourceFile, classConstructor, propertyInitialization); + } + } + function initializePropertyToUndefined(obj, propertyName) { + return ts.createStatement(ts.createAssignment(ts.createPropertyAccess(obj, propertyName), ts.createIdentifier("undefined"))); + } + function getActionsForAddMissingMemberInTypeScriptFile(context, declSourceFile, classDeclaration, token, makeStatic) { + var typeNode = getTypeNode(context.program.getTypeChecker(), classDeclaration, token); + var addProp = createAddPropertyDeclarationAction(context, declSourceFile, classDeclaration, makeStatic, token.text, typeNode); + return makeStatic ? [addProp] : [addProp, createAddIndexSignatureAction(context, declSourceFile, classDeclaration, token.text, typeNode)]; + } + function getTypeNode(checker, classDeclaration, token) { + var typeNode; + if (token.parent.parent.kind === 204 /* BinaryExpression */) { + var binaryExpression = token.parent.parent; + var otherExpression = token.parent === binaryExpression.left ? binaryExpression.right : binaryExpression.left; + var widenedType = checker.getWidenedType(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(otherExpression))); + typeNode = checker.typeToTypeNode(widenedType, classDeclaration); + } + else { + var contextualType = checker.getContextualType(token.parent); + typeNode = contextualType ? checker.typeToTypeNode(contextualType) : undefined; + } + return typeNode || ts.createKeywordTypeNode(120 /* AnyKeyword */); + } + function createAddPropertyDeclarationAction(context, declSourceFile, classDeclaration, makeStatic, tokenName, typeNode) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addPropertyDeclaration(t, declSourceFile, classDeclaration, tokenName, typeNode, makeStatic); }); + return codefix.createCodeFixAction(fixName, changes, [makeStatic ? ts.Diagnostics.Declare_static_property_0 : ts.Diagnostics.Declare_property_0, tokenName], fixId, ts.Diagnostics.Add_all_missing_members); + } + function addPropertyDeclaration(changeTracker, declSourceFile, classDeclaration, tokenName, typeNode, makeStatic) { + var property = ts.createProperty( + /*decorators*/ undefined, + /*modifiers*/ makeStatic ? [ts.createToken(116 /* StaticKeyword */)] : undefined, tokenName, + /*questionToken*/ undefined, typeNode, + /*initializer*/ undefined); + var lastProp = getNodeToInsertPropertyAfter(classDeclaration); + if (lastProp) { + changeTracker.insertNodeAfter(declSourceFile, lastProp, property); + } + else { + changeTracker.insertNodeAtClassStart(declSourceFile, classDeclaration, property); + } + } + // Gets the last of the first run of PropertyDeclarations, or undefined if the class does not start with a PropertyDeclaration. + function getNodeToInsertPropertyAfter(cls) { + var res; + for (var _i = 0, _a = cls.members; _i < _a.length; _i++) { + var member = _a[_i]; + if (!ts.isPropertyDeclaration(member)) + break; + res = member; + } + return res; + } + function createAddIndexSignatureAction(context, declSourceFile, classDeclaration, tokenName, typeNode) { + // Index signatures cannot have the static modifier. + var stringTypeNode = ts.createKeywordTypeNode(138 /* StringKeyword */); + var indexingParameter = ts.createParameter( + /*decorators*/ undefined, + /*modifiers*/ undefined, + /*dotDotDotToken*/ undefined, "x", + /*questionToken*/ undefined, stringTypeNode, + /*initializer*/ undefined); + var indexSignature = ts.createIndexSignature( + /*decorators*/ undefined, + /*modifiers*/ undefined, [indexingParameter], typeNode); + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.insertNodeAtClassStart(declSourceFile, classDeclaration, indexSignature); }); + // No fixId here because code-fix-all currently only works on adding individual named properties. + return codefix.createCodeFixActionNoFixId(fixName, changes, [ts.Diagnostics.Add_index_signature_for_property_0, tokenName]); + } + function getActionForMethodDeclaration(context, declSourceFile, classDeclaration, token, callExpression, makeStatic, inJs, preferences) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMethodDeclaration(context, t, declSourceFile, classDeclaration, token, callExpression, makeStatic, inJs, preferences); }); + return codefix.createCodeFixAction(fixName, changes, [makeStatic ? ts.Diagnostics.Declare_static_method_0 : ts.Diagnostics.Declare_method_0, token.text], fixId, ts.Diagnostics.Add_all_missing_members); + } + function addMethodDeclaration(context, changeTracker, declSourceFile, typeDecl, token, callExpression, makeStatic, inJs, preferences) { + var methodDeclaration = codefix.createMethodFromCallExpression(context, callExpression, token.text, inJs, makeStatic, preferences, !ts.isInterfaceDeclaration(typeDecl)); + var containingMethodDeclaration = ts.getAncestor(callExpression, 156 /* MethodDeclaration */); + if (containingMethodDeclaration && containingMethodDeclaration.parent === typeDecl) { + changeTracker.insertNodeAfter(declSourceFile, containingMethodDeclaration, methodDeclaration); + } + else { + changeTracker.insertNodeAtClassStart(declSourceFile, typeDecl, methodDeclaration); + } + } + function addEnumMemberDeclaration(changes, checker, token, enumDeclaration) { + /** + * create initializer only literal enum that has string initializer. + * value of initializer is a string literal that equal to name of enum member. + * numeric enum or empty enum will not create initializer. + */ + var hasStringInitializer = ts.some(enumDeclaration.members, function (member) { + var type = checker.getTypeAtLocation(member); + return !!(type && type.flags & 132 /* StringLike */); + }); + var enumMember = ts.createEnumMember(token, hasStringInitializer ? ts.createStringLiteral(token.text) : undefined); + changes.replaceNode(enumDeclaration.getSourceFile(), enumDeclaration, ts.updateEnumDeclaration(enumDeclaration, enumDeclaration.decorators, enumDeclaration.modifiers, enumDeclaration.name, ts.concatenate(enumDeclaration.members, ts.singleElementArray(enumMember)))); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixName = "fixCannotFindModule"; + var fixIdInstallTypesPackage = "installTypesPackage"; + var fixIdGenerateTypes = "generateTypes"; + var errorCodeCannotFindModule = ts.Diagnostics.Cannot_find_module_0.code; + var errorCodes = [ + errorCodeCannotFindModule, + ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type.code, + ]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var host = context.host, sourceFile = context.sourceFile, start = context.span.start; + var packageName = tryGetImportedPackageName(sourceFile, start); + if (packageName === undefined) + return undefined; + var typesPackageName = getTypesPackageNameToInstall(packageName, host, context.errorCode); + return typesPackageName === undefined + ? ts.singleElementArray(tryGetGenerateTypesAction(context, packageName)) + : [codefix.createCodeFixAction(fixName, /*changes*/ [], [ts.Diagnostics.Install_0, typesPackageName], fixIdInstallTypesPackage, ts.Diagnostics.Install_all_missing_types_packages, getInstallCommand(sourceFile.fileName, typesPackageName))]; + }, + fixIds: [fixIdInstallTypesPackage, fixIdGenerateTypes], + getAllCodeActions: function (context) { + var savedTypesDir = null; // tslint:disable-line no-null-keyword + return codefix.codeFixAll(context, errorCodes, function (changes, diag, commands) { + var packageName = tryGetImportedPackageName(diag.file, diag.start); + if (packageName === undefined) + return undefined; + switch (context.fixId) { + case fixIdInstallTypesPackage: { + var pkg = getTypesPackageNameToInstall(packageName, context.host, diag.code); + if (pkg) { + commands.push(getInstallCommand(diag.file.fileName, pkg)); + } + break; + } + case fixIdGenerateTypes: { + var typesDir = savedTypesDir !== null ? savedTypesDir : savedTypesDir = getOrCreateTypesDirectory(changes, context); + var command = typesDir === undefined ? undefined : tryGenerateTypes(typesDir, packageName, context); + if (command) + commands.push(command); + break; + } + default: + ts.Debug.fail("Bad fixId: " + context.fixId); + } + }); + }, + }); + function tryGetGenerateTypesAction(context, packageName) { + var command; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { + var typesDir = getOrCreateTypesDirectory(t, context); + command = typesDir === undefined ? undefined : tryGenerateTypes(typesDir, packageName, context); + }); + return command && codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Generate_types_for_0, packageName], fixIdGenerateTypes, ts.Diagnostics.Generate_types_for_all_packages_without_types, command); + } + function tryGenerateTypes(typesDir, packageName, context) { + var file = context.sourceFile.fileName; + var fileToGenerateTypesFor = ts.tryResolveJSModule(packageName, ts.getDirectoryPath(file), context.host); // TODO: GH#18217 + if (fileToGenerateTypesFor === undefined) + return undefined; + var outputFileName = ts.resolvePath(ts.getDirectoryPath(context.program.getCompilerOptions().configFile.fileName), typesDir, packageName + ".d.ts"); + if (context.host.fileExists(outputFileName)) + return undefined; + return { type: "generate types", file: file, fileToGenerateTypesFor: fileToGenerateTypesFor, outputFileName: outputFileName }; + } + // If no types directory exists yet, adds it to tsconfig.json + function getOrCreateTypesDirectory(changes, context) { + var configFile = context.program.getCompilerOptions().configFile; + if (!configFile) + return undefined; + var tsconfigObjectLiteral = ts.getTsConfigObjectLiteralExpression(configFile); + if (!tsconfigObjectLiteral) + return undefined; + var compilerOptionsProperty = findProperty(tsconfigObjectLiteral, "compilerOptions"); + if (!compilerOptionsProperty) { + var newCompilerOptions = ts.createObjectLiteral([makeDefaultBaseUrl(), makeDefaultPaths()]); + changes.insertNodeAtObjectStart(configFile, tsconfigObjectLiteral, createJsonPropertyAssignment("compilerOptions", newCompilerOptions)); + return defaultTypesDirectoryName; + } + var compilerOptions = compilerOptionsProperty.initializer; + if (!ts.isObjectLiteralExpression(compilerOptions)) + return defaultTypesDirectoryName; + var baseUrl = getOrAddBaseUrl(changes, configFile, compilerOptions); + var typesDirectoryFromPathMapping = getOrAddPathMapping(changes, configFile, compilerOptions); + return ts.combinePaths(baseUrl, typesDirectoryFromPathMapping); + } + var defaultBaseUrl = "."; + function makeDefaultBaseUrl() { + return createJsonPropertyAssignment("baseUrl", ts.createStringLiteral(defaultBaseUrl)); + } + function getOrAddBaseUrl(changes, tsconfig, compilerOptions) { + var baseUrlProp = findProperty(compilerOptions, "baseUrl"); + if (baseUrlProp) { + return ts.isStringLiteral(baseUrlProp.initializer) ? baseUrlProp.initializer.text : defaultBaseUrl; + } + else { + changes.insertNodeAtObjectStart(tsconfig, compilerOptions, makeDefaultBaseUrl()); + return defaultBaseUrl; + } + } + var defaultTypesDirectoryName = "types"; + function makeDefaultPathMapping() { + return createJsonPropertyAssignment("*", ts.createArrayLiteral([ts.createStringLiteral(defaultTypesDirectoryName + "/*")])); + } + function makeDefaultPaths() { + return createJsonPropertyAssignment("paths", ts.createObjectLiteral([makeDefaultPathMapping()])); + } + function getOrAddPathMapping(changes, tsconfig, compilerOptions) { + var paths = findProperty(compilerOptions, "paths"); + if (!paths || !ts.isObjectLiteralExpression(paths.initializer)) { + changes.insertNodeAtObjectStart(tsconfig, compilerOptions, makeDefaultPaths()); + return defaultTypesDirectoryName; + } + // Look for an existing path mapping. Should look like `"*": "foo/*"`. + var existing = ts.firstDefined(paths.initializer.properties, function (prop) { + return ts.isPropertyAssignment(prop) && ts.isStringLiteral(prop.name) && prop.name.text === "*" && ts.isArrayLiteralExpression(prop.initializer) + ? ts.firstDefined(prop.initializer.elements, function (value) { return ts.isStringLiteral(value) ? ts.tryRemoveSuffix(value.text, "/*") : undefined; }) + : undefined; + }); + if (existing) + return existing; + changes.insertNodeAtObjectStart(tsconfig, paths.initializer, makeDefaultPathMapping()); + return defaultTypesDirectoryName; + } + function createJsonPropertyAssignment(name, initializer) { + return ts.createPropertyAssignment(ts.createStringLiteral(name), initializer); + } + function findProperty(obj, name) { + return ts.find(obj.properties, function (p) { return ts.isPropertyAssignment(p) && !!p.name && ts.isStringLiteral(p.name) && p.name.text === name; }); + } + function getInstallCommand(fileName, packageName) { + return { type: "install package", file: fileName, packageName: packageName }; + } + function tryGetImportedPackageName(sourceFile, pos) { + var moduleName = ts.cast(ts.getTokenAtPosition(sourceFile, pos), ts.isStringLiteral).text; + var packageName = ts.parsePackageName(moduleName).packageName; + return ts.isExternalModuleNameRelative(packageName) ? undefined : packageName; + } + function getTypesPackageNameToInstall(packageName, host, diagCode) { + return diagCode === errorCodeCannotFindModule + ? (ts.JsTyping.nodeCoreModules.has(packageName) ? "@types/node" : undefined) + : (host.isKnownTypesPackageName(packageName) ? ts.getTypesPackageName(packageName) : undefined); // TODO: GH#18217 + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var errorCodes = [ + ts.Diagnostics.Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2.code, + ts.Diagnostics.Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1.code, + ]; + var fixId = "fixClassDoesntImplementInheritedAbstractMember"; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var program = context.program, sourceFile = context.sourceFile, span = context.span; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { + return addMissingMembers(getClass(sourceFile, span.start), sourceFile, program.getTypeChecker(), t, context.preferences); + }); + return changes.length === 0 ? undefined : [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Implement_inherited_abstract_class, fixId, ts.Diagnostics.Implement_all_inherited_abstract_classes)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { + var seenClassDeclarations = ts.createMap(); + return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var classDeclaration = getClass(diag.file, diag.start); + if (ts.addToSeen(seenClassDeclarations, ts.getNodeId(classDeclaration))) { + addMissingMembers(classDeclaration, context.sourceFile, context.program.getTypeChecker(), changes, context.preferences); + } + }); + }, + }); + function getClass(sourceFile, pos) { + // Token is the identifier in the case of a class declaration + // or the class keyword token in the case of a class expression. + var token = ts.getTokenAtPosition(sourceFile, pos); + return ts.cast(token.parent, ts.isClassLike); + } + function addMissingMembers(classDeclaration, sourceFile, checker, changeTracker, preferences) { + var extendsNode = ts.getEffectiveBaseTypeNode(classDeclaration); + var instantiatedExtendsType = checker.getTypeAtLocation(extendsNode); + // Note that this is ultimately derived from a map indexed by symbol names, + // so duplicates cannot occur. + var abstractAndNonPrivateExtendsSymbols = checker.getPropertiesOfType(instantiatedExtendsType).filter(symbolPointsToNonPrivateAndAbstractMember); + codefix.createMissingMemberNodes(classDeclaration, abstractAndNonPrivateExtendsSymbols, checker, preferences, function (member) { return changeTracker.insertNodeAtClassStart(sourceFile, classDeclaration, member); }); + } + function symbolPointsToNonPrivateAndAbstractMember(symbol) { + // See `codeFixClassExtendAbstractProtectedProperty.ts` in https://github.com/Microsoft/TypeScript/pull/11547/files + // (now named `codeFixClassExtendAbstractPrivateProperty.ts`) + var flags = ts.getModifierFlags(ts.first(symbol.getDeclarations())); + return !(flags & 8 /* Private */) && !!(flags & 128 /* Abstract */); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "classSuperMustPrecedeThisAccess"; + var errorCodes = [ts.Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var sourceFile = context.sourceFile, span = context.span; + var nodes = getNodes(sourceFile, span.start); + if (!nodes) + return undefined; + var constructor = nodes.constructor, superCall = nodes.superCall; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, constructor, superCall); }); + return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Make_super_call_the_first_statement_in_the_constructor, fixId, ts.Diagnostics.Make_all_super_calls_the_first_statement_in_their_constructor)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { + var sourceFile = context.sourceFile; + var seenClasses = ts.createMap(); // Ensure we only do this once per class. + return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var nodes = getNodes(diag.file, diag.start); + if (!nodes) + return; + var constructor = nodes.constructor, superCall = nodes.superCall; + if (ts.addToSeen(seenClasses, ts.getNodeId(constructor.parent))) { + doChange(changes, sourceFile, constructor, superCall); + } + }); + }, + }); + function doChange(changes, sourceFile, constructor, superCall) { + changes.insertNodeAtConstructorStart(sourceFile, constructor, superCall); + changes.delete(sourceFile, superCall); + } + function getNodes(sourceFile, pos) { + var token = ts.getTokenAtPosition(sourceFile, pos); + if (token.kind !== 100 /* ThisKeyword */) + return undefined; + var constructor = ts.getContainingFunction(token); + var superCall = findSuperCall(constructor.body); + // figure out if the `this` access is actually inside the supercall + // i.e. super(this.a), since in that case we won't suggest a fix + return superCall && !superCall.expression.arguments.some(function (arg) { return ts.isPropertyAccessExpression(arg) && arg.expression === token; }) ? { constructor: constructor, superCall: superCall } : undefined; + } + function findSuperCall(n) { + return ts.isExpressionStatement(n) && ts.isSuperCall(n.expression) + ? n + : ts.isFunctionLike(n) + ? undefined + : ts.forEachChild(n, findSuperCall); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "constructorForDerivedNeedSuperCall"; + var errorCodes = [ts.Diagnostics.Constructors_for_derived_classes_must_contain_a_super_call.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var sourceFile = context.sourceFile, span = context.span; + var ctr = getNode(sourceFile, span.start); + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, ctr); }); + return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Add_missing_super_call, fixId, ts.Diagnostics.Add_all_missing_super_calls)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + return doChange(changes, context.sourceFile, getNode(diag.file, diag.start)); + }); }, + }); + function getNode(sourceFile, pos) { + var token = ts.getTokenAtPosition(sourceFile, pos); + ts.Debug.assert(token.kind === 124 /* ConstructorKeyword */); + return token.parent; + } + function doChange(changes, sourceFile, ctr) { + var superCall = ts.createStatement(ts.createCall(ts.createSuper(), /*typeArguments*/ undefined, /*argumentsArray*/ ts.emptyArray)); + changes.insertNodeAtConstructorStart(sourceFile, ctr, superCall); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "extendsInterfaceBecomesImplements"; + var errorCodes = [ts.Diagnostics.Cannot_extend_an_interface_0_Did_you_mean_implements.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var sourceFile = context.sourceFile; + var nodes = getNodes(sourceFile, context.span.start); + if (!nodes) + return undefined; + var extendsToken = nodes.extendsToken, heritageClauses = nodes.heritageClauses; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChanges(t, sourceFile, extendsToken, heritageClauses); }); + return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Change_extends_to_implements, fixId, ts.Diagnostics.Change_all_extended_interfaces_to_implements)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var nodes = getNodes(diag.file, diag.start); + if (nodes) + doChanges(changes, diag.file, nodes.extendsToken, nodes.heritageClauses); + }); }, + }); + function getNodes(sourceFile, pos) { + var token = ts.getTokenAtPosition(sourceFile, pos); + var heritageClauses = ts.getContainingClass(token).heritageClauses; + var extendsToken = heritageClauses[0].getFirstToken(); + return extendsToken.kind === 86 /* ExtendsKeyword */ ? { extendsToken: extendsToken, heritageClauses: heritageClauses } : undefined; + } + function doChanges(changes, sourceFile, extendsToken, heritageClauses) { + changes.replaceNode(sourceFile, extendsToken, ts.createToken(109 /* ImplementsKeyword */)); + // If there is already an implements clause, replace the implements keyword with a comma. + if (heritageClauses.length === 2 && + heritageClauses[0].token === 86 /* ExtendsKeyword */ && + heritageClauses[1].token === 109 /* ImplementsKeyword */) { + var implementsToken = heritageClauses[1].getFirstToken(); + var implementsFullStart = implementsToken.getFullStart(); + changes.replaceRange(sourceFile, { pos: implementsFullStart, end: implementsFullStart }, ts.createToken(27 /* CommaToken */)); + // Rough heuristic: delete trailing whitespace after keyword so that it's not excessive. + // (Trailing because leading might be indentation, which is more sensitive.) + var text = sourceFile.text; + var end = implementsToken.end; + while (end < text.length && ts.isWhiteSpaceSingleLine(text.charCodeAt(end))) { + end++; + } + changes.deleteRange(sourceFile, { pos: implementsToken.getStart(), end: end }); + } + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "forgottenThisPropertyAccess"; + var didYouMeanStaticMemberCode = ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_static_member_1_0.code; + var errorCodes = [ + ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0.code, + didYouMeanStaticMemberCode, + ]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var sourceFile = context.sourceFile; + var info = getInfo(sourceFile, context.span.start, context.errorCode); + if (!info) { + return undefined; + } + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, info); }); + return [codefix.createCodeFixAction(fixId, changes, [ts.Diagnostics.Add_0_to_unresolved_variable, info.className || "this"], fixId, ts.Diagnostics.Add_qualifier_to_all_unresolved_variables_matching_a_member_name)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var info = getInfo(diag.file, diag.start, diag.code); + if (info) + doChange(changes, context.sourceFile, info); + }); }, + }); + function getInfo(sourceFile, pos, diagCode) { + var node = ts.getTokenAtPosition(sourceFile, pos); + if (!ts.isIdentifier(node)) + return undefined; + return { node: node, className: diagCode === didYouMeanStaticMemberCode ? ts.getContainingClass(node).name.text : undefined }; + } + function doChange(changes, sourceFile, _a) { + var node = _a.node, className = _a.className; + // TODO (https://github.com/Microsoft/TypeScript/issues/21246): use shared helper + ts.suppressLeadingAndTrailingTrivia(node); + changes.replaceNode(sourceFile, node, ts.createPropertyAccess(className ? ts.createIdentifier(className) : ts.createThis(), node)); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixName = "unusedIdentifier"; + var fixIdPrefix = "unusedIdentifier_prefix"; + var fixIdDelete = "unusedIdentifier_delete"; + var fixIdInfer = "unusedIdentifier_infer"; + var errorCodes = [ + ts.Diagnostics._0_is_declared_but_its_value_is_never_read.code, + ts.Diagnostics._0_is_declared_but_never_used.code, + ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read.code, + ts.Diagnostics.All_imports_in_import_declaration_are_unused.code, + ts.Diagnostics.All_destructured_elements_are_unused.code, + ts.Diagnostics.All_variables_are_unused.code, + ts.Diagnostics.All_type_parameters_are_unused.code, + ]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var errorCode = context.errorCode, sourceFile = context.sourceFile, program = context.program; + var checker = program.getTypeChecker(); + var sourceFiles = program.getSourceFiles(); + var token = ts.getTokenAtPosition(sourceFile, context.span.start); + if (ts.isJSDocTemplateTag(token)) { + return [createDeleteFix(ts.textChanges.ChangeTracker.with(context, function (t) { return t.delete(sourceFile, token); }), ts.Diagnostics.Remove_template_tag)]; + } + if (token.kind === 28 /* LessThanToken */) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return deleteTypeParameters(t, sourceFile, token); }); + return [createDeleteFix(changes, ts.Diagnostics.Remove_type_parameters)]; + } + var importDecl = tryGetFullImport(token); + if (importDecl) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.delete(sourceFile, importDecl); }); + return [createDeleteFix(changes, [ts.Diagnostics.Remove_import_from_0, ts.showModuleSpecifier(importDecl)])]; + } + var delDestructure = ts.textChanges.ChangeTracker.with(context, function (t) { + return tryDeleteFullDestructure(token, t, sourceFile, checker, sourceFiles, /*isFixAll*/ false); + }); + if (delDestructure.length) { + return [createDeleteFix(delDestructure, ts.Diagnostics.Remove_destructuring)]; + } + var delVar = ts.textChanges.ChangeTracker.with(context, function (t) { return tryDeleteFullVariableStatement(sourceFile, token, t); }); + if (delVar.length) { + return [createDeleteFix(delVar, ts.Diagnostics.Remove_variable_statement)]; + } + var result = []; + if (token.kind === 127 /* InferKeyword */) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return changeInferToUnknown(t, sourceFile, token); }); + var name = ts.cast(token.parent, ts.isInferTypeNode).typeParameter.name.text; + result.push(codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Replace_infer_0_with_unknown, name], fixIdInfer, ts.Diagnostics.Replace_all_unused_infer_with_unknown)); + } + else { + var deletion = ts.textChanges.ChangeTracker.with(context, function (t) { + return tryDeleteDeclaration(sourceFile, token, t, checker, sourceFiles, /*isFixAll*/ false); + }); + if (deletion.length) { + var name = ts.isComputedPropertyName(token.parent) ? token.parent : token; + result.push(createDeleteFix(deletion, [ts.Diagnostics.Remove_declaration_for_Colon_0, name.getText(sourceFile)])); + } + } + var prefix = ts.textChanges.ChangeTracker.with(context, function (t) { return tryPrefixDeclaration(t, errorCode, sourceFile, token); }); + if (prefix.length) { + result.push(codefix.createCodeFixAction(fixName, prefix, [ts.Diagnostics.Prefix_0_with_an_underscore, token.getText(sourceFile)], fixIdPrefix, ts.Diagnostics.Prefix_all_unused_declarations_with_where_possible)); + } + return result; + }, + fixIds: [fixIdPrefix, fixIdDelete, fixIdInfer], + getAllCodeActions: function (context) { + var sourceFile = context.sourceFile, program = context.program; + var checker = program.getTypeChecker(); + var sourceFiles = program.getSourceFiles(); + return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var token = ts.getTokenAtPosition(sourceFile, diag.start); + switch (context.fixId) { + case fixIdPrefix: + tryPrefixDeclaration(changes, diag.code, sourceFile, token); + break; + case fixIdDelete: { + if (token.kind === 127 /* InferKeyword */) + break; // Can't delete + var importDecl = tryGetFullImport(token); + if (importDecl) { + changes.delete(sourceFile, importDecl); + } + else if (ts.isJSDocTemplateTag(token)) { + changes.delete(sourceFile, token); + } + else if (token.kind === 28 /* LessThanToken */) { + deleteTypeParameters(changes, sourceFile, token); + } + else if (!tryDeleteFullDestructure(token, changes, sourceFile, checker, sourceFiles, /*isFixAll*/ true) && + !tryDeleteFullVariableStatement(sourceFile, token, changes)) { + tryDeleteDeclaration(sourceFile, token, changes, checker, sourceFiles, /*isFixAll*/ true); + } + break; + } + case fixIdInfer: + if (token.kind === 127 /* InferKeyword */) { + changeInferToUnknown(changes, sourceFile, token); + } + break; + default: + ts.Debug.fail(JSON.stringify(context.fixId)); + } + }); + }, + }); + function changeInferToUnknown(changes, sourceFile, token) { + changes.replaceNode(sourceFile, token.parent, ts.createKeywordTypeNode(143 /* UnknownKeyword */)); + } + function createDeleteFix(changes, diag) { + return codefix.createCodeFixAction(fixName, changes, diag, fixIdDelete, ts.Diagnostics.Delete_all_unused_declarations); + } + function deleteTypeParameters(changes, sourceFile, token) { + changes.delete(sourceFile, ts.Debug.assertDefined(ts.cast(token.parent, ts.isDeclarationWithTypeParameterChildren).typeParameters)); + } + // Sometimes the diagnostic span is an entire ImportDeclaration, so we should remove the whole thing. + function tryGetFullImport(token) { + return token.kind === 92 /* ImportKeyword */ ? ts.tryCast(token.parent, ts.isImportDeclaration) : undefined; + } + function tryDeleteFullDestructure(token, changes, sourceFile, checker, sourceFiles, isFixAll) { + if (token.kind !== 18 /* OpenBraceToken */ || !ts.isObjectBindingPattern(token.parent)) + return false; + var decl = token.parent.parent; + if (decl.kind === 151 /* Parameter */) { + tryDeleteParameter(changes, sourceFile, decl, checker, sourceFiles, isFixAll); + } + else { + changes.delete(sourceFile, decl); + } + return true; + } + function tryDeleteFullVariableStatement(sourceFile, token, changes) { + var declarationList = ts.tryCast(token.parent, ts.isVariableDeclarationList); + if (declarationList && declarationList.getChildren(sourceFile)[0] === token) { + changes.delete(sourceFile, declarationList.parent.kind === 219 /* VariableStatement */ ? declarationList.parent : declarationList); + return true; + } + return false; + } + function tryPrefixDeclaration(changes, errorCode, sourceFile, token) { + // Don't offer to prefix a property. + if (errorCode === ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read.code) + return; + if (token.kind === 127 /* InferKeyword */) { + token = ts.cast(token.parent, ts.isInferTypeNode).typeParameter.name; + } + if (ts.isIdentifier(token) && canPrefix(token)) { + changes.replaceNode(sourceFile, token, ts.createIdentifier("_" + token.text)); + } + } + function canPrefix(token) { + switch (token.parent.kind) { + case 151 /* Parameter */: + case 150 /* TypeParameter */: + return true; + case 237 /* VariableDeclaration */: { + var varDecl = token.parent; + switch (varDecl.parent.parent.kind) { + case 227 /* ForOfStatement */: + case 226 /* ForInStatement */: + return true; + } + } + } + return false; + } + function tryDeleteDeclaration(sourceFile, token, changes, checker, sourceFiles, isFixAll) { + tryDeleteDeclarationWorker(token, changes, sourceFile, checker, sourceFiles, isFixAll); + if (ts.isIdentifier(token)) + deleteAssignments(changes, sourceFile, token, checker); + } + function deleteAssignments(changes, sourceFile, token, checker) { + ts.FindAllReferences.Core.eachSymbolReferenceInFile(token, checker, sourceFile, function (ref) { + if (ts.isPropertyAccessExpression(ref.parent) && ref.parent.name === ref) + ref = ref.parent; + if (ts.isBinaryExpression(ref.parent) && ts.isExpressionStatement(ref.parent.parent) && ref.parent.left === ref) { + changes.delete(sourceFile, ref.parent.parent); + } + }); + } + function tryDeleteDeclarationWorker(token, changes, sourceFile, checker, sourceFiles, isFixAll) { + var parent = token.parent; + if (ts.isParameter(parent)) { + tryDeleteParameter(changes, sourceFile, parent, checker, sourceFiles, isFixAll); + } + else { + changes.delete(sourceFile, ts.isImportClause(parent) ? token : ts.isComputedPropertyName(parent) ? parent.parent : parent); + } + } + function tryDeleteParameter(changes, sourceFile, p, checker, sourceFiles, isFixAll) { + if (mayDeleteParameter(p, checker, isFixAll)) { + if (p.modifiers && p.modifiers.length > 0 + && (!ts.isIdentifier(p.name) || ts.FindAllReferences.Core.isSymbolReferencedInFile(p.name, checker, sourceFile))) { + p.modifiers.forEach(function (modifier) { + changes.deleteModifier(sourceFile, modifier); + }); + } + else { + changes.delete(sourceFile, p); + deleteUnusedArguments(changes, sourceFile, p, sourceFiles, checker); + } + } + } + function mayDeleteParameter(p, checker, isFixAll) { + var parent = p.parent; + switch (parent.kind) { + case 156 /* MethodDeclaration */: + // Don't remove a parameter if this overrides something. + var symbol = checker.getSymbolAtLocation(parent.name); + if (ts.isMemberSymbolInBaseType(symbol, checker)) + return false; + // falls through + case 157 /* Constructor */: + case 239 /* FunctionDeclaration */: + return true; + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: { + // Can't remove a non-last parameter in a callback. Can remove a parameter in code-fix-all if future parameters are also unused. + var parameters = parent.parameters; + var index = parameters.indexOf(p); + ts.Debug.assert(index !== -1); + return isFixAll + ? parameters.slice(index + 1).every(function (p) { return p.name.kind === 72 /* Identifier */ && !p.symbol.isReferenced; }) + : index === parameters.length - 1; + } + case 159 /* SetAccessor */: + // Setter must have a parameter + return false; + default: + return ts.Debug.failBadSyntaxKind(parent); + } + } + function deleteUnusedArguments(changes, sourceFile, deletedParameter, sourceFiles, checker) { + ts.FindAllReferences.Core.eachSignatureCall(deletedParameter.parent, sourceFiles, checker, function (call) { + var index = deletedParameter.parent.parameters.indexOf(deletedParameter); + if (call.arguments.length > index) { // Just in case the call didn't provide enough arguments. + changes.delete(sourceFile, call.arguments[index]); + } + }); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "fixUnreachableCode"; + var errorCodes = [ts.Diagnostics.Unreachable_code_detected.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, context.sourceFile, context.span.start, context.span.length); }); + return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Remove_unreachable_code, fixId, ts.Diagnostics.Remove_all_unreachable_code)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { return doChange(changes, diag.file, diag.start, diag.length); }); }, + }); + function doChange(changes, sourceFile, start, length) { + var token = ts.getTokenAtPosition(sourceFile, start); + var statement = ts.findAncestor(token, ts.isStatement); + ts.Debug.assert(statement.getStart(sourceFile) === token.getStart(sourceFile)); + var container = (ts.isBlock(statement.parent) ? statement.parent : statement).parent; + if (!ts.isBlock(statement.parent) || statement === ts.first(statement.parent.statements)) { + switch (container.kind) { + case 222 /* IfStatement */: + if (container.elseStatement) { + if (ts.isBlock(statement.parent)) { + break; + } + else { + changes.replaceNode(sourceFile, statement, ts.createBlock(ts.emptyArray)); + } + return; + } + // falls through + case 224 /* WhileStatement */: + case 225 /* ForStatement */: + changes.delete(sourceFile, container); + return; + } + } + if (ts.isBlock(statement.parent)) { + var end_2 = start + length; + var lastStatement = ts.Debug.assertDefined(lastWhere(ts.sliceAfter(statement.parent.statements, statement), function (s) { return s.pos < end_2; })); + changes.deleteNodeRange(sourceFile, statement, lastStatement); + } + else { + changes.delete(sourceFile, statement); + } + } + function lastWhere(a, pred) { + var last; + for (var _i = 0, a_1 = a; _i < a_1.length; _i++) { + var value = a_1[_i]; + if (!pred(value)) + break; + last = value; + } + return last; + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "fixUnusedLabel"; + var errorCodes = [ts.Diagnostics.Unused_label.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, context.sourceFile, context.span.start); }); + return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Remove_unused_label, fixId, ts.Diagnostics.Remove_all_unused_labels)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { return doChange(changes, diag.file, diag.start); }); }, + }); + function doChange(changes, sourceFile, start) { + var token = ts.getTokenAtPosition(sourceFile, start); + var labeledStatement = ts.cast(token.parent, ts.isLabeledStatement); + var pos = token.getStart(sourceFile); + var statementPos = labeledStatement.statement.getStart(sourceFile); + // If label is on a separate line, just delete the rest of that line, but not the indentation of the labeled statement. + var end = ts.positionsAreOnSameLine(pos, statementPos, sourceFile) ? statementPos + : ts.skipTrivia(sourceFile.text, ts.findChildOfKind(labeledStatement, 57 /* ColonToken */, sourceFile).end, /*stopAfterLineBreak*/ true); + changes.deleteRange(sourceFile, { pos: pos, end: end }); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixIdPlain = "fixJSDocTypes_plain"; + var fixIdNullable = "fixJSDocTypes_nullable"; + var errorCodes = [ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var sourceFile = context.sourceFile; + var checker = context.program.getTypeChecker(); + var info = getInfo(sourceFile, context.span.start, checker); + if (!info) + return undefined; + var typeNode = info.typeNode, type = info.type; + var original = typeNode.getText(sourceFile); + var actions = [fix(type, fixIdPlain, ts.Diagnostics.Change_all_jsdoc_style_types_to_TypeScript)]; + if (typeNode.kind === 286 /* JSDocNullableType */) { + // for nullable types, suggest the flow-compatible `T | null | undefined` + // in addition to the jsdoc/closure-compatible `T | null` + actions.push(fix(checker.getNullableType(type, 32768 /* Undefined */), fixIdNullable, ts.Diagnostics.Change_all_jsdoc_style_types_to_TypeScript_and_add_undefined_to_nullable_types)); + } + return actions; + function fix(type, fixId, fixAllDescription) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, typeNode, type, checker); }); + return codefix.createCodeFixAction("jdocTypes", changes, [ts.Diagnostics.Change_0_to_1, original, checker.typeToString(type)], fixId, fixAllDescription); + } + }, + fixIds: [fixIdPlain, fixIdNullable], + getAllCodeActions: function (context) { + var fixId = context.fixId, program = context.program, sourceFile = context.sourceFile; + var checker = program.getTypeChecker(); + return codefix.codeFixAll(context, errorCodes, function (changes, err) { + var info = getInfo(err.file, err.start, checker); + if (!info) + return; + var typeNode = info.typeNode, type = info.type; + var fixedType = typeNode.kind === 286 /* JSDocNullableType */ && fixId === fixIdNullable ? checker.getNullableType(type, 32768 /* Undefined */) : type; + doChange(changes, sourceFile, typeNode, fixedType, checker); + }); + } + }); + function doChange(changes, sourceFile, oldTypeNode, newType, checker) { + changes.replaceNode(sourceFile, oldTypeNode, checker.typeToTypeNode(newType, /*enclosingDeclaration*/ oldTypeNode)); // TODO: GH#18217 + } + function getInfo(sourceFile, pos, checker) { + var decl = ts.findAncestor(ts.getTokenAtPosition(sourceFile, pos), isTypeContainer); + var typeNode = decl && decl.type; + return typeNode && { typeNode: typeNode, type: checker.getTypeFromTypeNode(typeNode) }; + } + function isTypeContainer(node) { + // NOTE: Some locations are not handled yet: + // MappedTypeNode.typeParameters and SignatureDeclaration.typeParameters, as well as CallExpression.typeArguments + switch (node.kind) { + case 212 /* AsExpression */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 239 /* FunctionDeclaration */: + case 158 /* GetAccessor */: + case 162 /* IndexSignature */: + case 181 /* MappedType */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 151 /* Parameter */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 159 /* SetAccessor */: + case 242 /* TypeAliasDeclaration */: + case 194 /* TypeAssertionExpression */: + case 237 /* VariableDeclaration */: + return true; + default: + return false; + } + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "fixAwaitInSyncFunction"; + var errorCodes = [ + ts.Diagnostics.await_expression_is_only_allowed_within_an_async_function.code, + ts.Diagnostics.A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator.code, + ]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var sourceFile = context.sourceFile, span = context.span; + var nodes = getNodes(sourceFile, span.start); + if (!nodes) + return undefined; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, nodes); }); + return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Add_async_modifier_to_containing_function, fixId, ts.Diagnostics.Add_all_missing_async_modifiers)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var nodes = getNodes(diag.file, diag.start); + if (!nodes) + return; + doChange(changes, context.sourceFile, nodes); + }); }, + }); + function getReturnType(expr) { + if (expr.type) { + return expr.type; + } + if (ts.isVariableDeclaration(expr.parent) && + expr.parent.type && + ts.isFunctionTypeNode(expr.parent.type)) { + return expr.parent.type.type; + } + } + function getNodes(sourceFile, start) { + var token = ts.getTokenAtPosition(sourceFile, start); + var containingFunction = ts.getContainingFunction(token); + if (!containingFunction) { + return; + } + var insertBefore; + switch (containingFunction.kind) { + case 156 /* MethodDeclaration */: + insertBefore = containingFunction.name; + break; + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + insertBefore = ts.findChildOfKind(containingFunction, 90 /* FunctionKeyword */, sourceFile); + break; + case 197 /* ArrowFunction */: + insertBefore = ts.findChildOfKind(containingFunction, 20 /* OpenParenToken */, sourceFile) || ts.first(containingFunction.parameters); + break; + default: + return; + } + return insertBefore && { + insertBefore: insertBefore, + returnType: getReturnType(containingFunction) + }; + } + function doChange(changes, sourceFile, _a) { + var insertBefore = _a.insertBefore, returnType = _a.returnType; + if (returnType) { + var entityName = ts.getEntityNameFromTypeNode(returnType); + if (!entityName || entityName.kind !== 72 /* Identifier */ || entityName.text !== "Promise") { + changes.replaceNode(sourceFile, returnType, ts.createTypeReferenceNode("Promise", ts.createNodeArray([returnType]))); + } + } + changes.insertModifierBefore(sourceFile, 121 /* AsyncKeyword */, insertBefore); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixName = "disableJsDiagnostics"; + var fixId = "disableJsDiagnostics"; + var errorCodes = ts.mapDefined(Object.keys(ts.Diagnostics), function (key) { + var diag = ts.Diagnostics[key]; + return diag.category === ts.DiagnosticCategory.Error ? diag.code : undefined; + }); + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var sourceFile = context.sourceFile, program = context.program, span = context.span, host = context.host, formatContext = context.formatContext; + if (!ts.isInJSFile(sourceFile) || !ts.isCheckJsEnabledForFile(sourceFile, program.getCompilerOptions())) { + return undefined; + } + var fixes = [ + // fixId unnecessary because adding `// @ts-nocheck` even once will ignore every error in the file. + codefix.createCodeFixActionNoFixId(fixName, [codefix.createFileTextChanges(sourceFile.fileName, [ + ts.createTextChange(sourceFile.checkJsDirective + ? ts.createTextSpanFromBounds(sourceFile.checkJsDirective.pos, sourceFile.checkJsDirective.end) + : ts.createTextSpan(0, 0), "// @ts-nocheck" + ts.getNewLineOrDefaultFromHost(host, formatContext.options)), + ])], ts.Diagnostics.Disable_checking_for_this_file), + ]; + if (ts.textChanges.isValidLocationToAddComment(sourceFile, span.start)) { + fixes.unshift(codefix.createCodeFixAction(fixName, ts.textChanges.ChangeTracker.with(context, function (t) { return makeChange(t, sourceFile, span.start); }), ts.Diagnostics.Ignore_this_error_message, fixId, ts.Diagnostics.Add_ts_ignore_to_all_error_messages)); + } + return fixes; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { + var seenLines = ts.createMap(); + return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + if (ts.textChanges.isValidLocationToAddComment(diag.file, diag.start)) { + makeChange(changes, diag.file, diag.start, seenLines); + } + }); + }, + }); + function makeChange(changes, sourceFile, position, seenLines) { + var lineNumber = ts.getLineAndCharacterOfPosition(sourceFile, position).line; + // Only need to add `// @ts-ignore` for a line once. + if (!seenLines || ts.addToSeen(seenLines, lineNumber)) { + changes.insertCommentBeforeLine(sourceFile, lineNumber, position, " @ts-ignore"); + } + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + /** + * Finds members of the resolved type that are missing in the class pointed to by class decl + * and generates source code for the missing members. + * @param possiblyMissingSymbols The collection of symbols to filter and then get insertions for. + * @returns Empty string iff there are no member insertions. + */ + function createMissingMemberNodes(classDeclaration, possiblyMissingSymbols, checker, preferences, out) { + var classMembers = classDeclaration.symbol.members; + for (var _i = 0, possiblyMissingSymbols_1 = possiblyMissingSymbols; _i < possiblyMissingSymbols_1.length; _i++) { + var symbol = possiblyMissingSymbols_1[_i]; + if (!classMembers.has(symbol.escapedName)) { + addNewNodeForMemberSymbol(symbol, classDeclaration, checker, preferences, out); + } + } + } + codefix.createMissingMemberNodes = createMissingMemberNodes; + /** + * @returns Empty string iff there we can't figure out a representation for `symbol` in `enclosingDeclaration`. + */ + function addNewNodeForMemberSymbol(symbol, enclosingDeclaration, checker, preferences, out) { + var declarations = symbol.getDeclarations(); + if (!(declarations && declarations.length)) { + return undefined; + } + var declaration = declarations[0]; + var name = ts.getSynthesizedDeepClone(ts.getNameOfDeclaration(declaration), /*includeTrivia*/ false); + var visibilityModifier = createVisibilityModifier(ts.getModifierFlags(declaration)); + var modifiers = visibilityModifier ? ts.createNodeArray([visibilityModifier]) : undefined; + var type = checker.getWidenedType(checker.getTypeOfSymbolAtLocation(symbol, enclosingDeclaration)); + var optional = !!(symbol.flags & 16777216 /* Optional */); + switch (declaration.kind) { + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 153 /* PropertySignature */: + case 154 /* PropertyDeclaration */: + var typeNode = checker.typeToTypeNode(type, enclosingDeclaration); + out(ts.createProperty( + /*decorators*/ undefined, modifiers, name, optional ? ts.createToken(56 /* QuestionToken */) : undefined, typeNode, + /*initializer*/ undefined)); + break; + case 155 /* MethodSignature */: + case 156 /* MethodDeclaration */: + // The signature for the implementation appears as an entry in `signatures` iff + // there is only one signature. + // If there are overloads and an implementation signature, it appears as an + // extra declaration that isn't a signature for `type`. + // If there is more than one overload but no implementation signature + // (eg: an abstract method or interface declaration), there is a 1-1 + // correspondence of declarations and signatures. + var signatures = checker.getSignaturesOfType(type, 0 /* Call */); + if (!ts.some(signatures)) { + break; + } + if (declarations.length === 1) { + ts.Debug.assert(signatures.length === 1); + var signature = signatures[0]; + outputMethod(signature, modifiers, name, createStubbedMethodBody(preferences)); + break; + } + for (var _i = 0, signatures_7 = signatures; _i < signatures_7.length; _i++) { + var signature = signatures_7[_i]; + // Need to ensure nodes are fresh each time so they can have different positions. + outputMethod(signature, ts.getSynthesizedDeepClones(modifiers, /*includeTrivia*/ false), ts.getSynthesizedDeepClone(name, /*includeTrivia*/ false)); + } + if (declarations.length > signatures.length) { + var signature = checker.getSignatureFromDeclaration(declarations[declarations.length - 1]); + outputMethod(signature, modifiers, name, createStubbedMethodBody(preferences)); + } + else { + ts.Debug.assert(declarations.length === signatures.length); + out(createMethodImplementingSignatures(signatures, name, optional, modifiers, preferences)); + } + break; + } + function outputMethod(signature, modifiers, name, body) { + var method = signatureToMethodDeclaration(checker, signature, enclosingDeclaration, modifiers, name, optional, body); + if (method) + out(method); + } + } + function signatureToMethodDeclaration(checker, signature, enclosingDeclaration, modifiers, name, optional, body) { + var signatureDeclaration = checker.signatureToSignatureDeclaration(signature, 156 /* MethodDeclaration */, enclosingDeclaration, 256 /* SuppressAnyReturnType */); + if (!signatureDeclaration) { + return undefined; + } + signatureDeclaration.decorators = undefined; + signatureDeclaration.modifiers = modifiers; + signatureDeclaration.name = name; + signatureDeclaration.questionToken = optional ? ts.createToken(56 /* QuestionToken */) : undefined; + signatureDeclaration.body = body; + return signatureDeclaration; + } + function createMethodFromCallExpression(context, call, methodName, inJs, makeStatic, preferences, body) { + var typeArguments = call.typeArguments, args = call.arguments, parent = call.parent; + var checker = context.program.getTypeChecker(); + var types = ts.map(args, function (arg) { + // Widen the type so we don't emit nonsense annotations like "function fn(x: 3) {" + return checker.typeToTypeNode(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(arg))); + }); + var names = ts.map(args, function (arg) { + return ts.isIdentifier(arg) ? arg.text : + ts.isPropertyAccessExpression(arg) ? arg.name.text : undefined; + }); + var contextualType = checker.getContextualType(call); + var returnType = inJs ? undefined : contextualType && checker.typeToTypeNode(contextualType, call) || ts.createKeywordTypeNode(120 /* AnyKeyword */); + return ts.createMethod( + /*decorators*/ undefined, + /*modifiers*/ makeStatic ? [ts.createToken(116 /* StaticKeyword */)] : undefined, + /*asteriskToken*/ ts.isYieldExpression(parent) ? ts.createToken(40 /* AsteriskToken */) : undefined, methodName, + /*questionToken*/ undefined, + /*typeParameters*/ inJs ? undefined : ts.map(typeArguments, function (_, i) { + return ts.createTypeParameterDeclaration(84 /* T */ + typeArguments.length - 1 <= 90 /* Z */ ? String.fromCharCode(84 /* T */ + i) : "T" + i); + }), + /*parameters*/ createDummyParameters(args.length, names, types, /*minArgumentCount*/ undefined, inJs), + /*type*/ returnType, body ? createStubbedMethodBody(preferences) : undefined); + } + codefix.createMethodFromCallExpression = createMethodFromCallExpression; + function createDummyParameters(argCount, names, types, minArgumentCount, inJs) { + var parameters = []; + for (var i = 0; i < argCount; i++) { + var newParameter = ts.createParameter( + /*decorators*/ undefined, + /*modifiers*/ undefined, + /*dotDotDotToken*/ undefined, + /*name*/ names && names[i] || "arg" + i, + /*questionToken*/ minArgumentCount !== undefined && i >= minArgumentCount ? ts.createToken(56 /* QuestionToken */) : undefined, + /*type*/ inJs ? undefined : types && types[i] || ts.createKeywordTypeNode(120 /* AnyKeyword */), + /*initializer*/ undefined); + parameters.push(newParameter); + } + return parameters; + } + function createMethodImplementingSignatures(signatures, name, optional, modifiers, preferences) { + /** This is *a* signature with the maximal number of arguments, + * such that if there is a "maximal" signature without rest arguments, + * this is one of them. + */ + var maxArgsSignature = signatures[0]; + var minArgumentCount = signatures[0].minArgumentCount; + var someSigHasRestParameter = false; + for (var _i = 0, signatures_8 = signatures; _i < signatures_8.length; _i++) { + var sig = signatures_8[_i]; + minArgumentCount = Math.min(sig.minArgumentCount, minArgumentCount); + if (sig.hasRestParameter) { + someSigHasRestParameter = true; + } + if (sig.parameters.length >= maxArgsSignature.parameters.length && (!sig.hasRestParameter || maxArgsSignature.hasRestParameter)) { + maxArgsSignature = sig; + } + } + var maxNonRestArgs = maxArgsSignature.parameters.length - (maxArgsSignature.hasRestParameter ? 1 : 0); + var maxArgsParameterSymbolNames = maxArgsSignature.parameters.map(function (symbol) { return symbol.name; }); + var parameters = createDummyParameters(maxNonRestArgs, maxArgsParameterSymbolNames, /* types */ undefined, minArgumentCount, /*inJs*/ false); + if (someSigHasRestParameter) { + var anyArrayType = ts.createArrayTypeNode(ts.createKeywordTypeNode(120 /* AnyKeyword */)); + var restParameter = ts.createParameter( + /*decorators*/ undefined, + /*modifiers*/ undefined, ts.createToken(25 /* DotDotDotToken */), maxArgsParameterSymbolNames[maxNonRestArgs] || "rest", + /*questionToken*/ maxNonRestArgs >= minArgumentCount ? ts.createToken(56 /* QuestionToken */) : undefined, anyArrayType, + /*initializer*/ undefined); + parameters.push(restParameter); + } + return createStubbedMethod(modifiers, name, optional, + /*typeParameters*/ undefined, parameters, + /*returnType*/ undefined, preferences); + } + function createStubbedMethod(modifiers, name, optional, typeParameters, parameters, returnType, preferences) { + return ts.createMethod( + /*decorators*/ undefined, modifiers, + /*asteriskToken*/ undefined, name, optional ? ts.createToken(56 /* QuestionToken */) : undefined, typeParameters, parameters, returnType, createStubbedMethodBody(preferences)); + } + function createStubbedMethodBody(preferences) { + return ts.createBlock([ts.createThrow(ts.createNew(ts.createIdentifier("Error"), + /*typeArguments*/ undefined, [ts.createLiteral("Method not implemented.", /*isSingleQuote*/ preferences.quotePreference === "single")]))], + /*multiline*/ true); + } + function createVisibilityModifier(flags) { + if (flags & 4 /* Public */) { + return ts.createToken(115 /* PublicKeyword */); + } + else if (flags & 16 /* Protected */) { + return ts.createToken(114 /* ProtectedKeyword */); + } + return undefined; + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixName = "invalidImportSyntax"; + function getCodeFixesForImportDeclaration(context, node) { + var sourceFile = ts.getSourceFileOfNode(node); + var namespace = ts.getNamespaceDeclarationNode(node); + var opts = context.program.getCompilerOptions(); + var variations = []; + // import Bluebird from "bluebird"; + variations.push(createAction(context, sourceFile, node, ts.makeImport(namespace.name, /*namedImports*/ undefined, node.moduleSpecifier, ts.getQuotePreference(sourceFile, context.preferences)))); + if (ts.getEmitModuleKind(opts) === ts.ModuleKind.CommonJS) { + // import Bluebird = require("bluebird"); + variations.push(createAction(context, sourceFile, node, ts.createImportEqualsDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, namespace.name, ts.createExternalModuleReference(node.moduleSpecifier)))); + } + return variations; + } + function createAction(context, sourceFile, node, replacement) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.replaceNode(sourceFile, node, replacement); }); + return codefix.createCodeFixActionNoFixId(fixName, changes, [ts.Diagnostics.Replace_import_with_0, changes[0].textChanges[0].newText]); + } + codefix.registerCodeFix({ + errorCodes: [ + ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures.code, + ts.Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature.code, + ], + getCodeActions: getActionsForUsageOfInvalidImport + }); + function getActionsForUsageOfInvalidImport(context) { + var sourceFile = context.sourceFile; + var targetKind = ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures.code === context.errorCode ? 191 /* CallExpression */ : 192 /* NewExpression */; + var node = ts.findAncestor(ts.getTokenAtPosition(sourceFile, context.span.start), function (a) { return a.kind === targetKind && a.getStart() === context.span.start && a.getEnd() === (context.span.start + context.span.length); }); + if (!node) { + return []; + } + var expr = node.expression; + return getImportCodeFixesForExpression(context, expr); + } + codefix.registerCodeFix({ + errorCodes: [ + // The following error codes cover pretty much all assignability errors that could involve an expression + ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1.code, + ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1.code, + ts.Diagnostics.Type_0_is_not_assignable_to_type_1.code, + ts.Diagnostics.Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated.code, + ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1.code, + ts.Diagnostics.Property_0_of_type_1_is_not_assignable_to_string_index_type_2.code, + ts.Diagnostics.Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2.code, + ts.Diagnostics.Numeric_index_type_0_is_not_assignable_to_string_index_type_1.code, + ts.Diagnostics.Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2.code, + ts.Diagnostics.Property_0_in_type_1_is_not_assignable_to_type_2.code, + ts.Diagnostics.Property_0_of_JSX_spread_attribute_is_not_assignable_to_target_property.code, + ts.Diagnostics.The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1.code, + ], + getCodeActions: getActionsForInvalidImportLocation + }); + function getActionsForInvalidImportLocation(context) { + var sourceFile = context.sourceFile; + var node = ts.findAncestor(ts.getTokenAtPosition(sourceFile, context.span.start), function (a) { return a.getStart() === context.span.start && a.getEnd() === (context.span.start + context.span.length); }); + if (!node) { + return []; + } + return getImportCodeFixesForExpression(context, node); + } + function getImportCodeFixesForExpression(context, expr) { + var type = context.program.getTypeChecker().getTypeAtLocation(expr); + if (!(type.symbol && type.symbol.originatingImport)) { + return []; + } + var fixes = []; + var relatedImport = type.symbol.originatingImport; // TODO: GH#18217 + if (!ts.isImportCall(relatedImport)) { + ts.addRange(fixes, getCodeFixesForImportDeclaration(context, relatedImport)); + } + if (ts.isExpression(expr) && !(ts.isNamedDeclaration(expr.parent) && expr.parent.name === expr)) { + var sourceFile_3 = context.sourceFile; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.replaceNode(sourceFile_3, expr, ts.createPropertyAccess(expr, "default"), {}); }); + fixes.push(codefix.createCodeFixActionNoFixId(fixName, changes, ts.Diagnostics.Use_synthetic_default_member)); + } + return fixes; + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixName = "strictClassInitialization"; + var fixIdAddDefiniteAssignmentAssertions = "addMissingPropertyDefiniteAssignmentAssertions"; + var fixIdAddUndefinedType = "addMissingPropertyUndefinedType"; + var fixIdAddInitializer = "addMissingPropertyInitializer"; + var errorCodes = [ts.Diagnostics.Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var propertyDeclaration = getPropertyDeclaration(context.sourceFile, context.span.start); + if (!propertyDeclaration) + return; + var result = [ + getActionForAddMissingUndefinedType(context, propertyDeclaration), + getActionForAddMissingDefiniteAssignmentAssertion(context, propertyDeclaration) + ]; + ts.append(result, getActionForAddMissingInitializer(context, propertyDeclaration)); + return result; + }, + fixIds: [fixIdAddDefiniteAssignmentAssertions, fixIdAddUndefinedType, fixIdAddInitializer], + getAllCodeActions: function (context) { + return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var propertyDeclaration = getPropertyDeclaration(diag.file, diag.start); + if (!propertyDeclaration) + return; + switch (context.fixId) { + case fixIdAddDefiniteAssignmentAssertions: + addDefiniteAssignmentAssertion(changes, diag.file, propertyDeclaration); + break; + case fixIdAddUndefinedType: + addUndefinedType(changes, diag.file, propertyDeclaration); + break; + case fixIdAddInitializer: + var checker = context.program.getTypeChecker(); + var initializer = getInitializer(checker, propertyDeclaration); + if (!initializer) + return; + addInitializer(changes, diag.file, propertyDeclaration, initializer); + break; + default: + ts.Debug.fail(JSON.stringify(context.fixId)); + } + }); + }, + }); + function getPropertyDeclaration(sourceFile, pos) { + var token = ts.getTokenAtPosition(sourceFile, pos); + return ts.isIdentifier(token) ? ts.cast(token.parent, ts.isPropertyDeclaration) : undefined; + } + function getActionForAddMissingDefiniteAssignmentAssertion(context, propertyDeclaration) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addDefiniteAssignmentAssertion(t, context.sourceFile, propertyDeclaration); }); + return codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Add_definite_assignment_assertion_to_property_0, propertyDeclaration.getText()], fixIdAddDefiniteAssignmentAssertions, ts.Diagnostics.Add_definite_assignment_assertions_to_all_uninitialized_properties); + } + function addDefiniteAssignmentAssertion(changeTracker, propertyDeclarationSourceFile, propertyDeclaration) { + var property = ts.updateProperty(propertyDeclaration, propertyDeclaration.decorators, propertyDeclaration.modifiers, propertyDeclaration.name, ts.createToken(52 /* ExclamationToken */), propertyDeclaration.type, propertyDeclaration.initializer); + changeTracker.replaceNode(propertyDeclarationSourceFile, propertyDeclaration, property); + } + function getActionForAddMissingUndefinedType(context, propertyDeclaration) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addUndefinedType(t, context.sourceFile, propertyDeclaration); }); + return codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Add_undefined_type_to_property_0, propertyDeclaration.name.getText()], fixIdAddUndefinedType, ts.Diagnostics.Add_undefined_type_to_all_uninitialized_properties); + } + function addUndefinedType(changeTracker, propertyDeclarationSourceFile, propertyDeclaration) { + var undefinedTypeNode = ts.createKeywordTypeNode(141 /* UndefinedKeyword */); + var type = propertyDeclaration.type; // TODO: GH#18217 + var types = ts.isUnionTypeNode(type) ? type.types.concat(undefinedTypeNode) : [type, undefinedTypeNode]; + changeTracker.replaceNode(propertyDeclarationSourceFile, type, ts.createUnionTypeNode(types)); + } + function getActionForAddMissingInitializer(context, propertyDeclaration) { + var checker = context.program.getTypeChecker(); + var initializer = getInitializer(checker, propertyDeclaration); + if (!initializer) + return undefined; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addInitializer(t, context.sourceFile, propertyDeclaration, initializer); }); + return codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Add_initializer_to_property_0, propertyDeclaration.name.getText()], fixIdAddInitializer, ts.Diagnostics.Add_initializers_to_all_uninitialized_properties); + } + function addInitializer(changeTracker, propertyDeclarationSourceFile, propertyDeclaration, initializer) { + var property = ts.updateProperty(propertyDeclaration, propertyDeclaration.decorators, propertyDeclaration.modifiers, propertyDeclaration.name, propertyDeclaration.questionToken, propertyDeclaration.type, initializer); + changeTracker.replaceNode(propertyDeclarationSourceFile, propertyDeclaration, property); + } + function getInitializer(checker, propertyDeclaration) { + return getDefaultValueFromType(checker, checker.getTypeFromTypeNode(propertyDeclaration.type)); // TODO: GH#18217 + } + function getDefaultValueFromType(checker, type) { + if (type.flags & 512 /* BooleanLiteral */) { + return (type === checker.getFalseType() || type === checker.getFalseType(/*fresh*/ true)) ? ts.createFalse() : ts.createTrue(); + } + else if (type.isLiteral()) { + return ts.createLiteral(type.value); + } + else if (type.isUnion()) { + return ts.firstDefined(type.types, function (t) { return getDefaultValueFromType(checker, t); }); + } + else if (type.isClass()) { + var classDeclaration = ts.getClassLikeDeclarationOfSymbol(type.symbol); + if (!classDeclaration || ts.hasModifier(classDeclaration, 128 /* Abstract */)) + return undefined; + var constructorDeclaration = ts.getFirstConstructorWithBody(classDeclaration); + if (constructorDeclaration && constructorDeclaration.parameters.length) + return undefined; + return ts.createNew(ts.createIdentifier(type.symbol.name), /*typeArguments*/ undefined, /*argumentsArray*/ undefined); + } + else if (checker.isArrayLikeType(type)) { + return ts.createArrayLiteral(); + } + return undefined; + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + function generateTypesForModule(name, moduleValue, formatSettings) { + return generateTypesForModuleOrGlobal(name, moduleValue, formatSettings, 0 /* ExportEquals */); + } + ts.generateTypesForModule = generateTypesForModule; + function generateTypesForGlobal(name, globalValue, formatSettings) { + return generateTypesForModuleOrGlobal(name, globalValue, formatSettings, 3 /* Global */); + } + ts.generateTypesForGlobal = generateTypesForGlobal; + function generateTypesForModuleOrGlobal(name, globalValue, formatSettings, outputKind) { + return valueInfoToDeclarationFileText(ts.inspectValue(name, globalValue), formatSettings, outputKind); + } + /* @internal */ + function valueInfoToDeclarationFileText(valueInfo, formatSettings, outputKind) { + if (outputKind === void 0) { outputKind = 0 /* ExportEquals */; } + return ts.textChanges.getNewFileText(toStatements(valueInfo, outputKind), 3 /* TS */, formatSettings.newLineCharacter || "\n", ts.formatting.getFormatContext(formatSettings)); + } + ts.valueInfoToDeclarationFileText = valueInfoToDeclarationFileText; + var OutputKind; + (function (OutputKind) { + OutputKind[OutputKind["ExportEquals"] = 0] = "ExportEquals"; + OutputKind[OutputKind["NamedExport"] = 1] = "NamedExport"; + OutputKind[OutputKind["NamespaceMember"] = 2] = "NamespaceMember"; + OutputKind[OutputKind["Global"] = 3] = "Global"; + })(OutputKind || (OutputKind = {})); + function toNamespaceMemberStatements(info) { + return toStatements(info, 2 /* NamespaceMember */); + } + function toStatements(info, kind) { + var isDefault = info.name === "default" /* Default */; + var name = isDefault ? "_default" : info.name; + if (!isValidIdentifier(name) || isDefault && kind !== 1 /* NamedExport */) + return ts.emptyArray; + var modifiers = isDefault && info.kind === 2 /* FunctionOrClass */ ? [ts.createModifier(85 /* ExportKeyword */), ts.createModifier(80 /* DefaultKeyword */)] + : kind === 3 /* Global */ || kind === 0 /* ExportEquals */ ? [ts.createModifier(125 /* DeclareKeyword */)] + : kind === 1 /* NamedExport */ ? [ts.createModifier(85 /* ExportKeyword */)] + : undefined; + var exportEquals = function () { return kind === 0 /* ExportEquals */ ? [exportEqualsOrDefault(info.name, /*isExportEquals*/ true)] : ts.emptyArray; }; + var exportDefault = function () { return isDefault ? [exportEqualsOrDefault("_default", /*isExportEquals*/ false)] : ts.emptyArray; }; + switch (info.kind) { + case 2 /* FunctionOrClass */: + return exportEquals().concat(functionOrClassToStatements(modifiers, name, info)); + case 3 /* Object */: + var members = info.members, hasNontrivialPrototype = info.hasNontrivialPrototype; + if (!hasNontrivialPrototype) { + if (kind === 0 /* ExportEquals */) { + return ts.flatMap(members, function (v) { return toStatements(v, 1 /* NamedExport */); }); + } + if (members.some(function (m) { return m.kind === 2 /* FunctionOrClass */; })) { + // If some member is a function, use a namespace so it gets a FunctionDeclaration or ClassDeclaration. + return exportDefault().concat([createNamespace(modifiers, name, ts.flatMap(members, toNamespaceMemberStatements))]); + } + } + // falls through + case 0 /* Const */: + case 1 /* Array */: { + var comment = info.kind === 0 /* Const */ ? info.comment : undefined; + var constVar = ts.createVariableStatement(modifiers, ts.createVariableDeclarationList([ts.createVariableDeclaration(name, toType(info))], 2 /* Const */)); + return exportEquals().concat(exportDefault(), [addComment(constVar, comment)]); + } + default: + return ts.Debug.assertNever(info); + } + } + function exportEqualsOrDefault(name, isExportEquals) { + return ts.createExportAssignment(/*decorators*/ undefined, /*modifiers*/ undefined, isExportEquals, ts.createIdentifier(name)); + } + function functionOrClassToStatements(modifiers, name, _a) { + var source = _a.source, prototypeMembers = _a.prototypeMembers, namespaceMembers = _a.namespaceMembers; + var fnAst = parseClassOrFunctionBody(source); + var _b = fnAst === undefined ? { parameters: ts.emptyArray, returnType: anyType() } : getParametersAndReturnType(fnAst), parameters = _b.parameters, returnType = _b.returnType; + var protoOrInstanceMembers = ts.createMap(); + if (typeof fnAst === "object") + getConstructorFunctionInstanceProperties(fnAst, protoOrInstanceMembers); + for (var _i = 0, prototypeMembers_1 = prototypeMembers; _i < prototypeMembers_1.length; _i++) { + var p = prototypeMembers_1[_i]; + // ignore non-functions on the prototype + if (p.kind === 2 /* FunctionOrClass */) { + var m = tryGetMethod(p); + if (m) { + protoOrInstanceMembers.set(p.name, m); + } + } + } + var classStaticMembers = protoOrInstanceMembers.size !== 0 || fnAst === undefined || typeof fnAst !== "number" && fnAst.kind === 157 /* Constructor */ ? [] : undefined; + var namespaceStatements = ts.flatMap(namespaceMembers, function (info) { + if (!isValidIdentifier(info.name)) + return undefined; + if (classStaticMembers) { + switch (info.kind) { + case 3 /* Object */: + if (info.members.some(function (m) { return m.kind === 2 /* FunctionOrClass */; })) { + break; + } + // falls through + case 1 /* Array */: + case 0 /* Const */: + classStaticMembers.push(addComment(ts.createProperty(/*decorators*/ undefined, [ts.createModifier(116 /* StaticKeyword */)], info.name, /*questionOrExclamationToken*/ undefined, toType(info), /*initializer*/ undefined), info.kind === 0 /* Const */ ? info.comment : undefined)); + return undefined; + case 2 /* FunctionOrClass */: + if (!info.namespaceMembers.length) { // Else, can't merge a static method with a namespace. Must make it a function on the namespace. + var sig = tryGetMethod(info, [ts.createModifier(116 /* StaticKeyword */)]); + if (sig) { + classStaticMembers.push(sig); + return undefined; + } + } + break; + default: + ts.Debug.assertNever(info); + } + } + return toStatements(info, 2 /* NamespaceMember */); + }); + var decl = classStaticMembers + ? ts.createClassDeclaration( + /*decorators*/ undefined, modifiers, name, + /*typeParameters*/ undefined, + /*heritageClauses*/ undefined, classStaticMembers.concat((parameters.length ? [ts.createConstructor(/*decorators*/ undefined, /*modifiers*/ undefined, parameters, /*body*/ undefined)] : ts.emptyArray), ts.arrayFrom(protoOrInstanceMembers.values()))) + : ts.createFunctionDeclaration(/*decorators*/ undefined, modifiers, /*asteriskToken*/ undefined, name, /*typeParameters*/ undefined, parameters, returnType, /*body*/ undefined); + return [decl].concat((namespaceStatements.length === 0 ? ts.emptyArray : [createNamespace(modifiers && modifiers.map(function (m) { return ts.getSynthesizedDeepClone(m); }), name, namespaceStatements)])); + } + function tryGetMethod(_a, modifiers) { + var name = _a.name, source = _a.source; + if (!isValidIdentifier(name)) + return undefined; + var fnAst = parseClassOrFunctionBody(source); + if (fnAst === undefined || (typeof fnAst !== "number" && fnAst.kind === 157 /* Constructor */)) + return undefined; + var sig = getParametersAndReturnType(fnAst); + return sig && ts.createMethod( + /*decorators*/ undefined, modifiers, + /*asteriskToken*/ undefined, name, + /*questionToken*/ undefined, + /*typeParameters*/ undefined, sig.parameters, sig.returnType, + /*body*/ undefined); + } + function toType(info) { + switch (info.kind) { + case 0 /* Const */: + return ts.createTypeReferenceNode(info.typeName, /*typeArguments*/ undefined); + case 1 /* Array */: + return ts.createArrayTypeNode(toType(info.inner)); + case 2 /* FunctionOrClass */: + return ts.createTypeReferenceNode("Function", /*typeArguments*/ undefined); // Normally we create a FunctionDeclaration, but this can happen for a function in an array. + case 3 /* Object */: + return ts.createTypeLiteralNode(info.members.map(function (m) { return ts.createPropertySignature(/*modifiers*/ undefined, toPropertyName(m.name), /*questionToken*/ undefined, toType(m), /*initializer*/ undefined); })); + default: + return ts.Debug.assertNever(info); + } + } + function toPropertyName(name) { + return ts.isIdentifierText(name, 6 /* ESNext */) ? ts.createIdentifier(name) : ts.createStringLiteral(name); + } + // Parses assignments to "this.x" in the constructor into class property declarations + function getConstructorFunctionInstanceProperties(fnAst, members) { + forEachOwnNodeOfFunction(fnAst, function (node) { + if (ts.isAssignmentExpression(node, /*excludeCompoundAssignment*/ true) && + ts.isPropertyAccessExpression(node.left) && node.left.expression.kind === 100 /* ThisKeyword */) { + var name_6 = node.left.name.text; + if (!ts.isJsPrivate(name_6)) { + ts.getOrUpdate(members, name_6, function () { return ts.createProperty(/*decorators*/ undefined, /*modifiers*/ undefined, name_6, /*questionOrExclamationToken*/ undefined, anyType(), /*initializer*/ undefined); }); + } + } + }); + } + function getParametersAndReturnType(fnAst) { + if (typeof fnAst === "number") { + return { parameters: ts.fill(fnAst, function (i) { return makeParameter("p" + i, anyType()); }), returnType: anyType() }; + } + var usedArguments = false, hasReturn = false; + forEachOwnNodeOfFunction(fnAst, function (node) { + usedArguments = usedArguments || ts.isIdentifier(node) && node.text === "arguments"; + hasReturn = hasReturn || ts.isReturnStatement(node) && !!node.expression && node.expression.kind !== 200 /* VoidExpression */; + }); + var parameters = fnAst.parameters.map(function (p) { return makeParameter("" + p.name.getText(), inferParameterType(fnAst, p)); }).concat((usedArguments ? [makeRestParameter()] : ts.emptyArray)); + return { parameters: parameters, returnType: hasReturn ? anyType() : ts.createKeywordTypeNode(106 /* VoidKeyword */) }; + } + function makeParameter(name, type) { + return ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, name, /*questionToken*/ undefined, type); + } + function makeRestParameter() { + return ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createToken(25 /* DotDotDotToken */), "args", /*questionToken*/ undefined, ts.createArrayTypeNode(anyType())); + } + /** Returns 'undefined' for class with no declared constructor */ + function parseClassOrFunctionBody(source) { + if (typeof source === "number") + return source; + var classOrFunction = ts.tryCast(parseExpression(source), function (node) { return ts.isFunctionExpression(node) || ts.isArrowFunction(node) || ts.isClassExpression(node); }); + return classOrFunction + ? ts.isClassExpression(classOrFunction) ? ts.find(classOrFunction.members, ts.isConstructorDeclaration) : classOrFunction + // If that didn't parse, it's a method `m() {}`. Parse again inside of an object literal. + : ts.cast(ts.first(ts.cast(parseExpression("{ " + source + " }"), ts.isObjectLiteralExpression).properties), ts.isMethodDeclaration); + } + function parseExpression(expr) { + var text = "const _ = " + expr; + var srcFile = ts.createSourceFile("test.ts", text, 6 /* Latest */, /*setParentNodes*/ true); + return ts.first(ts.cast(ts.first(srcFile.statements), ts.isVariableStatement).declarationList.declarations).initializer; + } + function inferParameterType(_fn, _param) { + // TODO: Inspect function body for clues (see inferFromUsage.ts) + return anyType(); + } + // Descends through all nodes in a function, but not in nested functions. + function forEachOwnNodeOfFunction(fnAst, cb) { + fnAst.body.forEachChild(function recur(node) { + cb(node); + if (!ts.isFunctionLike(node)) + node.forEachChild(recur); + }); + } + function isValidIdentifier(name) { + var keyword = ts.stringToToken(name); + return !(keyword && ts.isNonContextualKeyword(keyword)) && ts.isIdentifierText(name, 6 /* ESNext */); + } + function addComment(node, comment) { + if (comment !== undefined) + ts.addSyntheticLeadingComment(node, 2 /* SingleLineCommentTrivia */, comment); + return node; + } + function anyType() { + return ts.createKeywordTypeNode(120 /* AnyKeyword */); + } + function createNamespace(modifiers, name, statements) { + return ts.createModuleDeclaration(/*decorators*/ undefined, modifiers, ts.createIdentifier(name), ts.createModuleBlock(statements), 16 /* Namespace */); + } +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "requireInTs"; + var errorCodes = [ts.Diagnostics.require_call_may_be_converted_to_an_import.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, context.sourceFile, context.span.start, context.program); }); + return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Convert_require_to_import, fixId, ts.Diagnostics.Convert_all_require_to_import)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { return doChange(changes, diag.file, diag.start, context.program); }); }, + }); + function doChange(changes, sourceFile, pos, program) { + var _a = getInfo(sourceFile, pos), statement = _a.statement, name = _a.name, required = _a.required; + changes.replaceNode(sourceFile, statement, ts.getAllowSyntheticDefaultImports(program.getCompilerOptions()) + ? ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createImportClause(name, /*namedBindings*/ undefined), required) + : ts.createImportEqualsDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, name, ts.createExternalModuleReference(required))); + } + function getInfo(sourceFile, pos) { + var parent = ts.getTokenAtPosition(sourceFile, pos).parent; + if (!ts.isRequireCall(parent, /*checkArgumentIsStringLiteralLike*/ true)) + throw ts.Debug.failBadSyntaxKind(parent); + var decl = ts.cast(parent.parent, ts.isVariableDeclaration); + return { statement: ts.cast(decl.parent.parent, ts.isVariableStatement), name: ts.cast(decl.name, ts.isIdentifier), required: parent.arguments[0] }; + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "useDefaultImport"; + var errorCodes = [ts.Diagnostics.Import_may_be_converted_to_a_default_import.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var sourceFile = context.sourceFile, start = context.span.start; + var info = getInfo(sourceFile, start); + if (!info) + return undefined; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, info, context.preferences); }); + return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Convert_to_default_import, fixId, ts.Diagnostics.Convert_all_to_default_imports)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var info = getInfo(diag.file, diag.start); + if (info) + doChange(changes, diag.file, info, context.preferences); + }); }, + }); + function getInfo(sourceFile, pos) { + var name = ts.getTokenAtPosition(sourceFile, pos); + if (!ts.isIdentifier(name)) + return undefined; // bad input + var parent = name.parent; + if (ts.isImportEqualsDeclaration(parent) && ts.isExternalModuleReference(parent.moduleReference)) { + return { importNode: parent, name: name, moduleSpecifier: parent.moduleReference.expression }; + } + else if (ts.isNamespaceImport(parent)) { + var importNode = parent.parent.parent; + return { importNode: importNode, name: name, moduleSpecifier: importNode.moduleSpecifier }; + } + } + function doChange(changes, sourceFile, info, preferences) { + changes.replaceNode(sourceFile, info.importNode, ts.makeImport(info.name, /*namedImports*/ undefined, info.moduleSpecifier, ts.getQuotePreference(sourceFile, preferences))); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixIdAddMissingTypeof = "fixAddModuleReferTypeMissingTypeof"; + var fixId = fixIdAddMissingTypeof; + var errorCodes = [ts.Diagnostics.Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var sourceFile = context.sourceFile, span = context.span; + var importType = getImportTypeNode(sourceFile, span.start); + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, importType); }); + return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Add_missing_typeof, fixId, ts.Diagnostics.Add_missing_typeof)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + return doChange(changes, context.sourceFile, getImportTypeNode(diag.file, diag.start)); + }); }, + }); + function getImportTypeNode(sourceFile, pos) { + var token = ts.getTokenAtPosition(sourceFile, pos); + ts.Debug.assert(token.kind === 92 /* ImportKeyword */); + ts.Debug.assert(token.parent.kind === 183 /* ImportType */); + return token.parent; + } + function doChange(changes, sourceFile, importType) { + var newTypeNode = ts.updateImportTypeNode(importType, importType.argument, importType.qualifier, importType.typeArguments, /* isTypeOf */ true); + changes.replaceNode(sourceFile, importType, newTypeNode); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixIdAddMissingTypeof = "fixConvertToMappedObjectType"; + var fixId = fixIdAddMissingTypeof; + var errorCodes = [ts.Diagnostics.An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var sourceFile = context.sourceFile, span = context.span; + var info = getInfo(sourceFile, span.start); + if (!info) + return undefined; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, info); }); + var name = ts.idText(info.container.name); + return [codefix.createCodeFixAction(fixId, changes, [ts.Diagnostics.Convert_0_to_mapped_object_type, name], fixId, [ts.Diagnostics.Convert_0_to_mapped_object_type, name])]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var info = getInfo(diag.file, diag.start); + if (info) + doChange(changes, diag.file, info); + }); } + }); + function getInfo(sourceFile, pos) { + var token = ts.getTokenAtPosition(sourceFile, pos); + var indexSignature = ts.cast(token.parent.parent, ts.isIndexSignatureDeclaration); + if (ts.isClassDeclaration(indexSignature.parent)) + return undefined; + var container = ts.isInterfaceDeclaration(indexSignature.parent) ? indexSignature.parent : ts.cast(indexSignature.parent.parent, ts.isTypeAliasDeclaration); + return { indexSignature: indexSignature, container: container }; + } + function createTypeAliasFromInterface(declaration, type) { + return ts.createTypeAliasDeclaration(declaration.decorators, declaration.modifiers, declaration.name, declaration.typeParameters, type); + } + function doChange(changes, sourceFile, _a) { + var indexSignature = _a.indexSignature, container = _a.container; + var members = ts.isInterfaceDeclaration(container) ? container.members : container.type.members; + var otherMembers = members.filter(function (member) { return !ts.isIndexSignatureDeclaration(member); }); + var parameter = ts.first(indexSignature.parameters); + var mappedTypeParameter = ts.createTypeParameterDeclaration(ts.cast(parameter.name, ts.isIdentifier), parameter.type); + var mappedIntersectionType = ts.createMappedTypeNode(ts.hasReadonlyModifier(indexSignature) ? ts.createModifier(133 /* ReadonlyKeyword */) : undefined, mappedTypeParameter, indexSignature.questionToken, indexSignature.type); + var intersectionType = ts.createIntersectionTypeNode(ts.getAllSuperTypeNodes(container).concat([ + mappedIntersectionType + ], (otherMembers.length ? [ts.createTypeLiteralNode(otherMembers)] : ts.emptyArray))); + changes.replaceNode(sourceFile, container, createTypeAliasFromInterface(container, intersectionType)); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var refactor; + (function (refactor) { + var refactorName = "Convert export"; + var actionNameDefaultToNamed = "Convert default export to named export"; + var actionNameNamedToDefault = "Convert named export to default export"; + refactor.registerRefactor(refactorName, { + getAvailableActions: function (context) { + var info = getInfo(context); + if (!info) + return ts.emptyArray; + var description = info.wasDefault ? ts.Diagnostics.Convert_default_export_to_named_export.message : ts.Diagnostics.Convert_named_export_to_default_export.message; + var actionName = info.wasDefault ? actionNameDefaultToNamed : actionNameNamedToDefault; + return [{ name: refactorName, description: description, actions: [{ name: actionName, description: description }] }]; + }, + getEditsForAction: function (context, actionName) { + ts.Debug.assert(actionName === actionNameDefaultToNamed || actionName === actionNameNamedToDefault); + var edits = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(context.file, context.program, ts.Debug.assertDefined(getInfo(context)), t, context.cancellationToken); }); + return { edits: edits, renameFilename: undefined, renameLocation: undefined }; + }, + }); + function getInfo(context) { + var file = context.file; + var span = ts.getRefactorContextSpan(context); + var token = ts.getTokenAtPosition(file, span.start); + var exportNode = ts.getParentNodeInSpan(token, file, span); + if (!exportNode || (!ts.isSourceFile(exportNode.parent) && !(ts.isModuleBlock(exportNode.parent) && ts.isAmbientModule(exportNode.parent.parent)))) { + return undefined; + } + var exportingModuleSymbol = ts.isSourceFile(exportNode.parent) ? exportNode.parent.symbol : exportNode.parent.parent.symbol; + var flags = ts.getModifierFlags(exportNode); + var wasDefault = !!(flags & 512 /* Default */); + // If source file already has a default export, don't offer refactor. + if (!(flags & 1 /* Export */) || !wasDefault && exportingModuleSymbol.exports.has("default" /* Default */)) { + return undefined; + } + switch (exportNode.kind) { + case 239 /* FunctionDeclaration */: + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + case 243 /* EnumDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 244 /* ModuleDeclaration */: { + var node = exportNode; + return node.name && ts.isIdentifier(node.name) ? { exportNode: node, exportName: node.name, wasDefault: wasDefault, exportingModuleSymbol: exportingModuleSymbol } : undefined; + } + case 219 /* VariableStatement */: { + var vs = exportNode; + // Must be `export const x = something;`. + if (!(vs.declarationList.flags & 2 /* Const */) || vs.declarationList.declarations.length !== 1) { + return undefined; + } + var decl = ts.first(vs.declarationList.declarations); + if (!decl.initializer) + return undefined; + ts.Debug.assert(!wasDefault); + return ts.isIdentifier(decl.name) ? { exportNode: vs, exportName: decl.name, wasDefault: wasDefault, exportingModuleSymbol: exportingModuleSymbol } : undefined; + } + default: + return undefined; + } + } + function doChange(exportingSourceFile, program, info, changes, cancellationToken) { + changeExport(exportingSourceFile, info, changes, program.getTypeChecker()); + changeImports(program, info, changes, cancellationToken); + } + function changeExport(exportingSourceFile, _a, changes, checker) { + var wasDefault = _a.wasDefault, exportNode = _a.exportNode, exportName = _a.exportName; + if (wasDefault) { + changes.delete(exportingSourceFile, ts.Debug.assertDefined(ts.findModifier(exportNode, 80 /* DefaultKeyword */))); + } + else { + var exportKeyword = ts.Debug.assertDefined(ts.findModifier(exportNode, 85 /* ExportKeyword */)); + switch (exportNode.kind) { + case 239 /* FunctionDeclaration */: + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + changes.insertNodeAfter(exportingSourceFile, exportKeyword, ts.createToken(80 /* DefaultKeyword */)); + break; + case 219 /* VariableStatement */: + // If 'x' isn't used in this file, `export const x = 0;` --> `export default 0;` + if (!ts.FindAllReferences.Core.isSymbolReferencedInFile(exportName, checker, exportingSourceFile)) { + // We checked in `getInfo` that an initializer exists. + changes.replaceNode(exportingSourceFile, exportNode, ts.createExportDefault(ts.Debug.assertDefined(ts.first(exportNode.declarationList.declarations).initializer))); + break; + } + // falls through + case 243 /* EnumDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 244 /* ModuleDeclaration */: + // `export type T = number;` -> `type T = number; export default T;` + changes.deleteModifier(exportingSourceFile, exportKeyword); + changes.insertNodeAfter(exportingSourceFile, exportNode, ts.createExportDefault(ts.createIdentifier(exportName.text))); + break; + default: + ts.Debug.assertNever(exportNode); + } + } + } + function changeImports(program, _a, changes, cancellationToken) { + var wasDefault = _a.wasDefault, exportName = _a.exportName, exportingModuleSymbol = _a.exportingModuleSymbol; + var checker = program.getTypeChecker(); + var exportSymbol = ts.Debug.assertDefined(checker.getSymbolAtLocation(exportName)); + ts.FindAllReferences.Core.eachExportReference(program.getSourceFiles(), checker, cancellationToken, exportSymbol, exportingModuleSymbol, exportName.text, wasDefault, function (ref) { + var importingSourceFile = ref.getSourceFile(); + if (wasDefault) { + changeDefaultToNamedImport(importingSourceFile, ref, changes, exportName.text); + } + else { + changeNamedToDefaultImport(importingSourceFile, ref, changes); + } + }); + } + function changeDefaultToNamedImport(importingSourceFile, ref, changes, exportName) { + var parent = ref.parent; + switch (parent.kind) { + case 189 /* PropertyAccessExpression */: + // `a.default` --> `a.foo` + changes.replaceNode(importingSourceFile, ref, ts.createIdentifier(exportName)); + break; + case 253 /* ImportSpecifier */: + case 257 /* ExportSpecifier */: { + var spec = parent; + // `default as foo` --> `foo`, `default as bar` --> `foo as bar` + changes.replaceNode(importingSourceFile, spec, makeImportSpecifier(exportName, spec.name.text)); + break; + } + case 250 /* ImportClause */: { + var clause = parent; + ts.Debug.assert(clause.name === ref); + var spec = makeImportSpecifier(exportName, ref.text); + var namedBindings = clause.namedBindings; + if (!namedBindings) { + // `import foo from "./a";` --> `import { foo } from "./a";` + changes.replaceNode(importingSourceFile, ref, ts.createNamedImports([spec])); + } + else if (namedBindings.kind === 251 /* NamespaceImport */) { + // `import foo, * as a from "./a";` --> `import * as a from ".a/"; import { foo } from "./a";` + changes.deleteRange(importingSourceFile, { pos: ref.getStart(importingSourceFile), end: namedBindings.getStart(importingSourceFile) }); + var quotePreference = ts.isStringLiteral(clause.parent.moduleSpecifier) ? ts.quotePreferenceFromString(clause.parent.moduleSpecifier, importingSourceFile) : 1 /* Double */; + var newImport = ts.makeImport(/*default*/ undefined, [makeImportSpecifier(exportName, ref.text)], clause.parent.moduleSpecifier, quotePreference); + changes.insertNodeAfter(importingSourceFile, clause.parent, newImport); + } + else { + // `import foo, { bar } from "./a"` --> `import { bar, foo } from "./a";` + changes.delete(importingSourceFile, ref); + changes.insertNodeAtEndOfList(importingSourceFile, namedBindings.elements, spec); + } + break; + } + default: + ts.Debug.failBadSyntaxKind(parent); + } + } + function changeNamedToDefaultImport(importingSourceFile, ref, changes) { + var parent = ref.parent; + switch (parent.kind) { + case 189 /* PropertyAccessExpression */: + // `a.foo` --> `a.default` + changes.replaceNode(importingSourceFile, ref, ts.createIdentifier("default")); + break; + case 253 /* ImportSpecifier */: { + // `import { foo } from "./a";` --> `import foo from "./a";` + // `import { foo as bar } from "./a";` --> `import bar from "./a";` + var defaultImport = ts.createIdentifier(parent.name.text); + if (parent.parent.elements.length === 1) { + changes.replaceNode(importingSourceFile, parent.parent, defaultImport); + } + else { + changes.delete(importingSourceFile, parent); + changes.insertNodeBefore(importingSourceFile, parent.parent, defaultImport); + } + break; + } + case 257 /* ExportSpecifier */: { + // `export { foo } from "./a";` --> `export { default as foo } from "./a";` + // `export { foo as bar } from "./a";` --> `export { default as bar } from "./a";` + // `export { foo as default } from "./a";` --> `export { default } from "./a";` + // (Because `export foo from "./a";` isn't valid syntax.) + changes.replaceNode(importingSourceFile, parent, makeExportSpecifier("default", parent.name.text)); + break; + } + default: + ts.Debug.assertNever(parent); + } + } + function makeImportSpecifier(propertyName, name) { + return ts.createImportSpecifier(propertyName === name ? undefined : ts.createIdentifier(propertyName), ts.createIdentifier(name)); + } + function makeExportSpecifier(propertyName, name) { + return ts.createExportSpecifier(propertyName === name ? undefined : ts.createIdentifier(propertyName), ts.createIdentifier(name)); + } + })(refactor = ts.refactor || (ts.refactor = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var refactor; + (function (refactor) { + var refactorName = "Convert import"; + var actionNameNamespaceToNamed = "Convert namespace import to named imports"; + var actionNameNamedToNamespace = "Convert named imports to namespace import"; + refactor.registerRefactor(refactorName, { + getAvailableActions: function (context) { + var i = getImportToConvert(context); + if (!i) + return ts.emptyArray; + var description = i.kind === 251 /* NamespaceImport */ ? ts.Diagnostics.Convert_namespace_import_to_named_imports.message : ts.Diagnostics.Convert_named_imports_to_namespace_import.message; + var actionName = i.kind === 251 /* NamespaceImport */ ? actionNameNamespaceToNamed : actionNameNamedToNamespace; + return [{ name: refactorName, description: description, actions: [{ name: actionName, description: description }] }]; + }, + getEditsForAction: function (context, actionName) { + ts.Debug.assert(actionName === actionNameNamespaceToNamed || actionName === actionNameNamedToNamespace); + var edits = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(context.file, context.program, t, ts.Debug.assertDefined(getImportToConvert(context))); }); + return { edits: edits, renameFilename: undefined, renameLocation: undefined }; + } + }); + // Can convert imports of the form `import * as m from "m";` or `import d, { x, y } from "m";`. + function getImportToConvert(context) { + var file = context.file; + var span = ts.getRefactorContextSpan(context); + var token = ts.getTokenAtPosition(file, span.start); + var importDecl = ts.getParentNodeInSpan(token, file, span); + if (!importDecl || !ts.isImportDeclaration(importDecl)) + return undefined; + var importClause = importDecl.importClause; + return importClause && importClause.namedBindings; + } + function doChange(sourceFile, program, changes, toConvert) { + var checker = program.getTypeChecker(); + if (toConvert.kind === 251 /* NamespaceImport */) { + doChangeNamespaceToNamed(sourceFile, checker, changes, toConvert, ts.getAllowSyntheticDefaultImports(program.getCompilerOptions())); + } + else { + doChangeNamedToNamespace(sourceFile, checker, changes, toConvert); + } + } + function doChangeNamespaceToNamed(sourceFile, checker, changes, toConvert, allowSyntheticDefaultImports) { + var usedAsNamespaceOrDefault = false; + var nodesToReplace = []; + var conflictingNames = ts.createMap(); + ts.FindAllReferences.Core.eachSymbolReferenceInFile(toConvert.name, checker, sourceFile, function (id) { + if (!ts.isPropertyAccessExpression(id.parent)) { + usedAsNamespaceOrDefault = true; + } + else { + var parent = ts.cast(id.parent, ts.isPropertyAccessExpression); + var exportName = parent.name.text; + if (checker.resolveName(exportName, id, 67108863 /* All */, /*excludeGlobals*/ true)) { + conflictingNames.set(exportName, true); + } + ts.Debug.assert(parent.expression === id); + nodesToReplace.push(parent); + } + }); + // We may need to change `mod.x` to `_x` to avoid a name conflict. + var exportNameToImportName = ts.createMap(); + for (var _i = 0, nodesToReplace_1 = nodesToReplace; _i < nodesToReplace_1.length; _i++) { + var propertyAccess = nodesToReplace_1[_i]; + var exportName = propertyAccess.name.text; + var importName = exportNameToImportName.get(exportName); + if (importName === undefined) { + exportNameToImportName.set(exportName, importName = conflictingNames.has(exportName) ? ts.getUniqueName(exportName, sourceFile) : exportName); + } + changes.replaceNode(sourceFile, propertyAccess, ts.createIdentifier(importName)); + } + var importSpecifiers = []; + exportNameToImportName.forEach(function (name, propertyName) { + importSpecifiers.push(ts.createImportSpecifier(name === propertyName ? undefined : ts.createIdentifier(propertyName), ts.createIdentifier(name))); + }); + var importDecl = toConvert.parent.parent; + if (usedAsNamespaceOrDefault && !allowSyntheticDefaultImports) { + // Need to leave the namespace import alone + changes.insertNodeAfter(sourceFile, importDecl, updateImport(importDecl, /*defaultImportName*/ undefined, importSpecifiers)); + } + else { + changes.replaceNode(sourceFile, importDecl, updateImport(importDecl, usedAsNamespaceOrDefault ? ts.createIdentifier(toConvert.name.text) : undefined, importSpecifiers)); + } + } + function doChangeNamedToNamespace(sourceFile, checker, changes, toConvert) { + var importDecl = toConvert.parent.parent; + var moduleSpecifier = importDecl.moduleSpecifier; + var preferredName = moduleSpecifier && ts.isStringLiteral(moduleSpecifier) ? ts.codefix.moduleSpecifierToValidIdentifier(moduleSpecifier.text, 6 /* ESNext */) : "module"; + var namespaceNameConflicts = toConvert.elements.some(function (element) { + return ts.FindAllReferences.Core.eachSymbolReferenceInFile(element.name, checker, sourceFile, function (id) { + return !!checker.resolveName(preferredName, id, 67108863 /* All */, /*excludeGlobals*/ true); + }) || false; + }); + var namespaceImportName = namespaceNameConflicts ? ts.getUniqueName(preferredName, sourceFile) : preferredName; + var neededNamedImports = []; + var _loop_21 = function (element) { + var propertyName = (element.propertyName || element.name).text; + ts.FindAllReferences.Core.eachSymbolReferenceInFile(element.name, checker, sourceFile, function (id) { + var access = ts.createPropertyAccess(ts.createIdentifier(namespaceImportName), propertyName); + if (ts.isShorthandPropertyAssignment(id.parent)) { + changes.replaceNode(sourceFile, id.parent, ts.createPropertyAssignment(id.text, access)); + } + else if (ts.isExportSpecifier(id.parent) && !id.parent.propertyName) { + if (!neededNamedImports.some(function (n) { return n.name === element.name; })) { + neededNamedImports.push(ts.createImportSpecifier(element.propertyName && ts.createIdentifier(element.propertyName.text), ts.createIdentifier(element.name.text))); + } + } + else { + changes.replaceNode(sourceFile, id, access); + } + }); + }; + for (var _i = 0, _a = toConvert.elements; _i < _a.length; _i++) { + var element = _a[_i]; + _loop_21(element); + } + changes.replaceNode(sourceFile, toConvert, ts.createNamespaceImport(ts.createIdentifier(namespaceImportName))); + if (neededNamedImports.length) { + changes.insertNodeAfter(sourceFile, toConvert.parent.parent, updateImport(importDecl, /*defaultImportName*/ undefined, neededNamedImports)); + } + } + function updateImport(old, defaultImportName, elements) { + return ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createImportClause(defaultImportName, elements && elements.length ? ts.createNamedImports(elements) : undefined), old.moduleSpecifier); + } + })(refactor = ts.refactor || (ts.refactor = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var refactor; + (function (refactor) { + var extractSymbol; + (function (extractSymbol) { + var refactorName = "Extract Symbol"; + refactor.registerRefactor(refactorName, { getAvailableActions: getAvailableActions, getEditsForAction: getEditsForAction }); + /** + * Compute the associated code actions + * Exported for tests. + */ + function getAvailableActions(context) { + var rangeToExtract = getRangeToExtract(context.file, ts.getRefactorContextSpan(context)); + var targetRange = rangeToExtract.targetRange; + if (targetRange === undefined) { + return ts.emptyArray; + } + var extractions = getPossibleExtractions(targetRange, context); + if (extractions === undefined) { + // No extractions possible + return ts.emptyArray; + } + var functionActions = []; + var usedFunctionNames = ts.createMap(); + var constantActions = []; + var usedConstantNames = ts.createMap(); + var i = 0; + for (var _i = 0, extractions_1 = extractions; _i < extractions_1.length; _i++) { + var _a = extractions_1[_i], functionExtraction = _a.functionExtraction, constantExtraction = _a.constantExtraction; + // Skip these since we don't have a way to report errors yet + if (functionExtraction.errors.length === 0) { + // Don't issue refactorings with duplicated names. + // Scopes come back in "innermost first" order, so extractions will + // preferentially go into nearer scopes + var description = functionExtraction.description; + if (!usedFunctionNames.has(description)) { + usedFunctionNames.set(description, true); + functionActions.push({ + description: description, + name: "function_scope_" + i + }); + } + } + // Skip these since we don't have a way to report errors yet + if (constantExtraction.errors.length === 0) { + // Don't issue refactorings with duplicated names. + // Scopes come back in "innermost first" order, so extractions will + // preferentially go into nearer scopes + var description = constantExtraction.description; + if (!usedConstantNames.has(description)) { + usedConstantNames.set(description, true); + constantActions.push({ + description: description, + name: "constant_scope_" + i + }); + } + } + // *do* increment i anyway because we'll look for the i-th scope + // later when actually doing the refactoring if the user requests it + i++; + } + var infos = []; + if (functionActions.length) { + infos.push({ + name: refactorName, + description: ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_function), + actions: functionActions + }); + } + if (constantActions.length) { + infos.push({ + name: refactorName, + description: ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_constant), + actions: constantActions + }); + } + return infos.length ? infos : ts.emptyArray; + } + extractSymbol.getAvailableActions = getAvailableActions; + /* Exported for tests */ + function getEditsForAction(context, actionName) { + var rangeToExtract = getRangeToExtract(context.file, ts.getRefactorContextSpan(context)); + var targetRange = rangeToExtract.targetRange; // TODO:GH#18217 + var parsedFunctionIndexMatch = /^function_scope_(\d+)$/.exec(actionName); + if (parsedFunctionIndexMatch) { + var index = +parsedFunctionIndexMatch[1]; + ts.Debug.assert(isFinite(index), "Expected to parse a finite number from the function scope index"); + return getFunctionExtractionAtIndex(targetRange, context, index); + } + var parsedConstantIndexMatch = /^constant_scope_(\d+)$/.exec(actionName); + if (parsedConstantIndexMatch) { + var index = +parsedConstantIndexMatch[1]; + ts.Debug.assert(isFinite(index), "Expected to parse a finite number from the constant scope index"); + return getConstantExtractionAtIndex(targetRange, context, index); + } + ts.Debug.fail("Unrecognized action name"); + } + extractSymbol.getEditsForAction = getEditsForAction; + // Move these into diagnostic messages if they become user-facing + var Messages; + (function (Messages) { + function createMessage(message) { + return { message: message, code: 0, category: ts.DiagnosticCategory.Message, key: message }; + } + Messages.cannotExtractRange = createMessage("Cannot extract range."); + Messages.cannotExtractImport = createMessage("Cannot extract import statement."); + Messages.cannotExtractSuper = createMessage("Cannot extract super call."); + Messages.cannotExtractEmpty = createMessage("Cannot extract empty range."); + Messages.expressionExpected = createMessage("expression expected."); + Messages.uselessConstantType = createMessage("No reason to extract constant of type."); + Messages.statementOrExpressionExpected = createMessage("Statement or expression expected."); + Messages.cannotExtractRangeContainingConditionalBreakOrContinueStatements = createMessage("Cannot extract range containing conditional break or continue statements."); + Messages.cannotExtractRangeContainingConditionalReturnStatement = createMessage("Cannot extract range containing conditional return statement."); + Messages.cannotExtractRangeContainingLabeledBreakOrContinueStatementWithTargetOutsideOfTheRange = createMessage("Cannot extract range containing labeled break or continue with target outside of the range."); + Messages.cannotExtractRangeThatContainsWritesToReferencesLocatedOutsideOfTheTargetRangeInGenerators = createMessage("Cannot extract range containing writes to references located outside of the target range in generators."); + Messages.typeWillNotBeVisibleInTheNewScope = createMessage("Type will not visible in the new scope."); + Messages.functionWillNotBeVisibleInTheNewScope = createMessage("Function will not visible in the new scope."); + Messages.cannotExtractIdentifier = createMessage("Select more than a single identifier."); + Messages.cannotExtractExportedEntity = createMessage("Cannot extract exported declaration"); + Messages.cannotWriteInExpression = createMessage("Cannot write back side-effects when extracting an expression"); + Messages.cannotExtractReadonlyPropertyInitializerOutsideConstructor = createMessage("Cannot move initialization of read-only class property outside of the constructor"); + Messages.cannotExtractAmbientBlock = createMessage("Cannot extract code from ambient contexts"); + Messages.cannotAccessVariablesFromNestedScopes = createMessage("Cannot access variables from nested scopes"); + Messages.cannotExtractToOtherFunctionLike = createMessage("Cannot extract method to a function-like scope that is not a function"); + Messages.cannotExtractToJSClass = createMessage("Cannot extract constant to a class scope in JS"); + Messages.cannotExtractToExpressionArrowFunction = createMessage("Cannot extract constant to an arrow function without a block"); + })(Messages = extractSymbol.Messages || (extractSymbol.Messages = {})); + var RangeFacts; + (function (RangeFacts) { + RangeFacts[RangeFacts["None"] = 0] = "None"; + RangeFacts[RangeFacts["HasReturn"] = 1] = "HasReturn"; + RangeFacts[RangeFacts["IsGenerator"] = 2] = "IsGenerator"; + RangeFacts[RangeFacts["IsAsyncFunction"] = 4] = "IsAsyncFunction"; + RangeFacts[RangeFacts["UsesThis"] = 8] = "UsesThis"; + /** + * The range is in a function which needs the 'static' modifier in a class + */ + RangeFacts[RangeFacts["InStaticRegion"] = 16] = "InStaticRegion"; + })(RangeFacts || (RangeFacts = {})); + /** + * getRangeToExtract takes a span inside a text file and returns either an expression or an array + * of statements representing the minimum set of nodes needed to extract the entire span. This + * process may fail, in which case a set of errors is returned instead (these are currently + * not shown to the user, but can be used by us diagnostically) + */ + // exported only for tests + function getRangeToExtract(sourceFile, span) { + var length = span.length; + if (length === 0) { + return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractEmpty)] }; + } + // Walk up starting from the the start position until we find a non-SourceFile node that subsumes the selected span. + // This may fail (e.g. you select two statements in the root of a source file) + var start = ts.getParentNodeInSpan(ts.getTokenAtPosition(sourceFile, span.start), sourceFile, span); + // Do the same for the ending position + var end = ts.getParentNodeInSpan(ts.findTokenOnLeftOfPosition(sourceFile, ts.textSpanEnd(span)), sourceFile, span); + var declarations = []; + // We'll modify these flags as we walk the tree to collect data + // about what things need to be done as part of the extraction. + var rangeFacts = RangeFacts.None; + if (!start || !end) { + // cannot find either start or end node + return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractRange)] }; + } + if (start.parent !== end.parent) { + // start and end nodes belong to different subtrees + return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractRange)] }; + } + if (start !== end) { + // start and end should be statements and parent should be either block or a source file + if (!isBlockLike(start.parent)) { + return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractRange)] }; + } + var statements = []; + var start2 = start; // TODO: GH#18217 Need to alias `start` to get this to compile. See https://github.com/Microsoft/TypeScript/issues/19955#issuecomment-344118248 + for (var _i = 0, _a = start2.parent.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + if (statement === start || statements.length) { + var errors_1 = checkNode(statement); + if (errors_1) { + return { errors: errors_1 }; + } + statements.push(statement); + } + if (statement === end) { + break; + } + } + if (!statements.length) { + // https://github.com/Microsoft/TypeScript/issues/20559 + // Ranges like [|case 1: break;|] will fail to populate `statements` because + // they will never find `start` in `start.parent.statements`. + // Consider: We could support ranges like [|case 1:|] by refining them to just + // the expression. + return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractRange)] }; + } + return { targetRange: { range: statements, facts: rangeFacts, declarations: declarations } }; + } + if (ts.isReturnStatement(start) && !start.expression) { + // Makes no sense to extract an expression-less return statement. + return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractRange)] }; + } + // We have a single node (start) + var node = refineNode(start); + var errors = checkRootNode(node) || checkNode(node); + if (errors) { + return { errors: errors }; + } + return { targetRange: { range: getStatementOrExpressionRange(node), facts: rangeFacts, declarations: declarations } }; // TODO: GH#18217 + /** + * Attempt to refine the extraction node (generally, by shrinking it) to produce better results. + * @param node The unrefined extraction node. + */ + function refineNode(node) { + if (ts.isReturnStatement(node)) { + if (node.expression) { + return node.expression; + } + } + else if (ts.isVariableStatement(node)) { + var numInitializers = 0; + var lastInitializer = void 0; + for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (declaration.initializer) { + numInitializers++; + lastInitializer = declaration.initializer; + } + } + if (numInitializers === 1) { + return lastInitializer; + } + // No special handling if there are multiple initializers. + } + else if (ts.isVariableDeclaration(node)) { + if (node.initializer) { + return node.initializer; + } + } + return node; + } + function checkRootNode(node) { + if (ts.isIdentifier(ts.isExpressionStatement(node) ? node.expression : node)) { + return [ts.createDiagnosticForNode(node, Messages.cannotExtractIdentifier)]; + } + return undefined; + } + function checkForStaticContext(nodeToCheck, containingClass) { + var current = nodeToCheck; + while (current !== containingClass) { + if (current.kind === 154 /* PropertyDeclaration */) { + if (ts.hasModifier(current, 32 /* Static */)) { + rangeFacts |= RangeFacts.InStaticRegion; + } + break; + } + else if (current.kind === 151 /* Parameter */) { + var ctorOrMethod = ts.getContainingFunction(current); + if (ctorOrMethod.kind === 157 /* Constructor */) { + rangeFacts |= RangeFacts.InStaticRegion; + } + break; + } + else if (current.kind === 156 /* MethodDeclaration */) { + if (ts.hasModifier(current, 32 /* Static */)) { + rangeFacts |= RangeFacts.InStaticRegion; + } + } + current = current.parent; + } + } + // Verifies whether we can actually extract this node or not. + function checkNode(nodeToCheck) { + var PermittedJumps; + (function (PermittedJumps) { + PermittedJumps[PermittedJumps["None"] = 0] = "None"; + PermittedJumps[PermittedJumps["Break"] = 1] = "Break"; + PermittedJumps[PermittedJumps["Continue"] = 2] = "Continue"; + PermittedJumps[PermittedJumps["Return"] = 4] = "Return"; + })(PermittedJumps || (PermittedJumps = {})); + // We believe it's true because the node is from the (unmodified) tree. + ts.Debug.assert(nodeToCheck.pos <= nodeToCheck.end, "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809"); + // For understanding how skipTrivia functioned: + ts.Debug.assert(!ts.positionIsSynthesized(nodeToCheck.pos), "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809"); + if (!ts.isStatement(nodeToCheck) && !(ts.isExpressionNode(nodeToCheck) && isExtractableExpression(nodeToCheck))) { + return [ts.createDiagnosticForNode(nodeToCheck, Messages.statementOrExpressionExpected)]; + } + if (nodeToCheck.flags & 4194304 /* Ambient */) { + return [ts.createDiagnosticForNode(nodeToCheck, Messages.cannotExtractAmbientBlock)]; + } + // If we're in a class, see whether we're in a static region (static property initializer, static method, class constructor parameter default) + var containingClass = ts.getContainingClass(nodeToCheck); + if (containingClass) { + checkForStaticContext(nodeToCheck, containingClass); + } + var errors; + var permittedJumps = 4 /* Return */; + var seenLabels; + visit(nodeToCheck); + return errors; + function visit(node) { + if (errors) { + // already found an error - can stop now + return true; + } + if (ts.isDeclaration(node)) { + var declaringNode = (node.kind === 237 /* VariableDeclaration */) ? node.parent.parent : node; + if (ts.hasModifier(declaringNode, 1 /* Export */)) { + // TODO: GH#18217 Silly to use `errors ||` since it's definitely not defined (see top of `visit`) + // Also, if we're only pushing one error, just use `let error: Diagnostic | undefined`! + // Also TODO: GH#19956 + (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractExportedEntity)); + return true; + } + declarations.push(node.symbol); + } + // Some things can't be extracted in certain situations + switch (node.kind) { + case 249 /* ImportDeclaration */: + (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractImport)); + return true; + case 98 /* SuperKeyword */: + // For a super *constructor call*, we have to be extracting the entire class, + // but a super *method call* simply implies a 'this' reference + if (node.parent.kind === 191 /* CallExpression */) { + // Super constructor call + var containingClass_1 = ts.getContainingClass(node); // TODO:GH#18217 + if (containingClass_1.pos < span.start || containingClass_1.end >= (span.start + span.length)) { + (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractSuper)); + return true; + } + } + else { + rangeFacts |= RangeFacts.UsesThis; + } + break; + } + if (ts.isFunctionLikeDeclaration(node) || ts.isClassLike(node)) { + switch (node.kind) { + case 239 /* FunctionDeclaration */: + case 240 /* ClassDeclaration */: + if (ts.isSourceFile(node.parent) && node.parent.externalModuleIndicator === undefined) { + // You cannot extract global declarations + (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.functionWillNotBeVisibleInTheNewScope)); + } + break; + } + // do not dive into functions or classes + return false; + } + var savedPermittedJumps = permittedJumps; + switch (node.kind) { + case 222 /* IfStatement */: + permittedJumps = 0 /* None */; + break; + case 235 /* TryStatement */: + // forbid all jumps inside try blocks + permittedJumps = 0 /* None */; + break; + case 218 /* Block */: + if (node.parent && node.parent.kind === 235 /* TryStatement */ && node.parent.finallyBlock === node) { + // allow unconditional returns from finally blocks + permittedJumps = 4 /* Return */; + } + break; + case 271 /* CaseClause */: + // allow unlabeled break inside case clauses + permittedJumps |= 1 /* Break */; + break; + default: + if (ts.isIterationStatement(node, /*lookInLabeledStatements*/ false)) { + // allow unlabeled break/continue inside loops + permittedJumps |= 1 /* Break */ | 2 /* Continue */; + } + break; + } + switch (node.kind) { + case 178 /* ThisType */: + case 100 /* ThisKeyword */: + rangeFacts |= RangeFacts.UsesThis; + break; + case 233 /* LabeledStatement */: + { + var label = node.label; + (seenLabels || (seenLabels = [])).push(label.escapedText); + ts.forEachChild(node, visit); + seenLabels.pop(); + break; + } + case 229 /* BreakStatement */: + case 228 /* ContinueStatement */: + { + var label = node.label; + if (label) { + if (!ts.contains(seenLabels, label.escapedText)) { + // attempts to jump to label that is not in range to be extracted + (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractRangeContainingLabeledBreakOrContinueStatementWithTargetOutsideOfTheRange)); + } + } + else { + if (!(permittedJumps & (node.kind === 229 /* BreakStatement */ ? 1 /* Break */ : 2 /* Continue */))) { + // attempt to break or continue in a forbidden context + (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractRangeContainingConditionalBreakOrContinueStatements)); + } + } + break; + } + case 201 /* AwaitExpression */: + rangeFacts |= RangeFacts.IsAsyncFunction; + break; + case 207 /* YieldExpression */: + rangeFacts |= RangeFacts.IsGenerator; + break; + case 230 /* ReturnStatement */: + if (permittedJumps & 4 /* Return */) { + rangeFacts |= RangeFacts.HasReturn; + } + else { + (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractRangeContainingConditionalReturnStatement)); + } + break; + default: + ts.forEachChild(node, visit); + break; + } + permittedJumps = savedPermittedJumps; + } + } + } + extractSymbol.getRangeToExtract = getRangeToExtract; + function getStatementOrExpressionRange(node) { + if (ts.isStatement(node)) { + return [node]; + } + else if (ts.isExpressionNode(node)) { + // If our selection is the expression in an ExpressionStatement, expand + // the selection to include the enclosing Statement (this stops us + // from trying to care about the return value of the extracted function + // and eliminates double semicolon insertion in certain scenarios) + return ts.isExpressionStatement(node.parent) ? [node.parent] : node; + } + return undefined; + } + function isScope(node) { + return ts.isFunctionLikeDeclaration(node) || ts.isSourceFile(node) || ts.isModuleBlock(node) || ts.isClassLike(node); + } + /** + * Computes possible places we could extract the function into. For example, + * you may be able to extract into a class method *or* local closure *or* namespace function, + * depending on what's in the extracted body. + */ + function collectEnclosingScopes(range) { + var current = isReadonlyArray(range.range) ? ts.first(range.range) : range.range; + if (range.facts & RangeFacts.UsesThis) { + // if range uses this as keyword or as type inside the class then it can only be extracted to a method of the containing class + var containingClass = ts.getContainingClass(current); + if (containingClass) { + var containingFunction = ts.findAncestor(current, ts.isFunctionLikeDeclaration); + return containingFunction + ? [containingFunction, containingClass] + : [containingClass]; + } + } + var scopes = []; + while (true) { + current = current.parent; + // A function parameter's initializer is actually in the outer scope, not the function declaration + if (current.kind === 151 /* Parameter */) { + // Skip all the way to the outer scope of the function that declared this parameter + current = ts.findAncestor(current, function (parent) { return ts.isFunctionLikeDeclaration(parent); }).parent; + } + // We want to find the nearest parent where we can place an "equivalent" sibling to the node we're extracting out of. + // Walk up to the closest parent of a place where we can logically put a sibling: + // * Function declaration + // * Class declaration or expression + // * Module/namespace or source file + if (isScope(current)) { + scopes.push(current); + if (current.kind === 279 /* SourceFile */) { + return scopes; + } + } + } + } + function getFunctionExtractionAtIndex(targetRange, context, requestedChangesIndex) { + var _a = getPossibleExtractionsWorker(targetRange, context), scopes = _a.scopes, _b = _a.readsAndWrites, target = _b.target, usagesPerScope = _b.usagesPerScope, functionErrorsPerScope = _b.functionErrorsPerScope, exposedVariableDeclarations = _b.exposedVariableDeclarations; + ts.Debug.assert(!functionErrorsPerScope[requestedChangesIndex].length, "The extraction went missing? How?"); + context.cancellationToken.throwIfCancellationRequested(); // TODO: GH#18217 + return extractFunctionInScope(target, scopes[requestedChangesIndex], usagesPerScope[requestedChangesIndex], exposedVariableDeclarations, targetRange, context); + } + function getConstantExtractionAtIndex(targetRange, context, requestedChangesIndex) { + var _a = getPossibleExtractionsWorker(targetRange, context), scopes = _a.scopes, _b = _a.readsAndWrites, target = _b.target, usagesPerScope = _b.usagesPerScope, constantErrorsPerScope = _b.constantErrorsPerScope, exposedVariableDeclarations = _b.exposedVariableDeclarations; + ts.Debug.assert(!constantErrorsPerScope[requestedChangesIndex].length, "The extraction went missing? How?"); + ts.Debug.assert(exposedVariableDeclarations.length === 0, "Extract constant accepted a range containing a variable declaration?"); + context.cancellationToken.throwIfCancellationRequested(); + var expression = ts.isExpression(target) + ? target + : target.statements[0].expression; + return extractConstantInScope(expression, scopes[requestedChangesIndex], usagesPerScope[requestedChangesIndex], targetRange.facts, context); + } + /** + * Given a piece of text to extract ('targetRange'), computes a list of possible extractions. + * Each returned ExtractResultForScope corresponds to a possible target scope and is either a set of changes + * or an error explaining why we can't extract into that scope. + */ + function getPossibleExtractions(targetRange, context) { + var _a = getPossibleExtractionsWorker(targetRange, context), scopes = _a.scopes, _b = _a.readsAndWrites, functionErrorsPerScope = _b.functionErrorsPerScope, constantErrorsPerScope = _b.constantErrorsPerScope; + // Need the inner type annotation to avoid https://github.com/Microsoft/TypeScript/issues/7547 + var extractions = scopes.map(function (scope, i) { + var functionDescriptionPart = getDescriptionForFunctionInScope(scope); + var constantDescriptionPart = getDescriptionForConstantInScope(scope); + var scopeDescription = ts.isFunctionLikeDeclaration(scope) + ? getDescriptionForFunctionLikeDeclaration(scope) + : ts.isClassLike(scope) + ? getDescriptionForClassLikeDeclaration(scope) + : getDescriptionForModuleLikeDeclaration(scope); + var functionDescription; + var constantDescription; + if (scopeDescription === 1 /* Global */) { + functionDescription = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_to_0_in_1_scope), [functionDescriptionPart, "global"]); + constantDescription = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_to_0_in_1_scope), [constantDescriptionPart, "global"]); + } + else if (scopeDescription === 0 /* Module */) { + functionDescription = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_to_0_in_1_scope), [functionDescriptionPart, "module"]); + constantDescription = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_to_0_in_1_scope), [constantDescriptionPart, "module"]); + } + else { + functionDescription = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_to_0_in_1), [functionDescriptionPart, scopeDescription]); + constantDescription = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_to_0_in_1), [constantDescriptionPart, scopeDescription]); + } + // Customize the phrasing for the innermost scope to increase clarity. + if (i === 0 && !ts.isClassLike(scope)) { + constantDescription = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_to_0_in_enclosing_scope), [constantDescriptionPart]); + } + return { + functionExtraction: { + description: functionDescription, + errors: functionErrorsPerScope[i], + }, + constantExtraction: { + description: constantDescription, + errors: constantErrorsPerScope[i], + }, + }; + }); + return extractions; + } + function getPossibleExtractionsWorker(targetRange, context) { + var sourceFile = context.file; + var scopes = collectEnclosingScopes(targetRange); + var enclosingTextRange = getEnclosingTextRange(targetRange, sourceFile); + var readsAndWrites = collectReadsAndWrites(targetRange, scopes, enclosingTextRange, sourceFile, context.program.getTypeChecker(), context.cancellationToken); + return { scopes: scopes, readsAndWrites: readsAndWrites }; + } + function getDescriptionForFunctionInScope(scope) { + return ts.isFunctionLikeDeclaration(scope) + ? "inner function" + : ts.isClassLike(scope) + ? "method" + : "function"; + } + function getDescriptionForConstantInScope(scope) { + return ts.isClassLike(scope) + ? "readonly field" + : "constant"; + } + function getDescriptionForFunctionLikeDeclaration(scope) { + switch (scope.kind) { + case 157 /* Constructor */: + return "constructor"; + case 196 /* FunctionExpression */: + case 239 /* FunctionDeclaration */: + return scope.name + ? "function '" + scope.name.text + "'" + : "anonymous function"; + case 197 /* ArrowFunction */: + return "arrow function"; + case 156 /* MethodDeclaration */: + return "method '" + scope.name.getText() + "'"; + case 158 /* GetAccessor */: + return "'get " + scope.name.getText() + "'"; + case 159 /* SetAccessor */: + return "'set " + scope.name.getText() + "'"; + default: + throw ts.Debug.assertNever(scope); + } + } + function getDescriptionForClassLikeDeclaration(scope) { + return scope.kind === 240 /* ClassDeclaration */ + ? scope.name ? "class '" + scope.name.text + "'" : "anonymous class declaration" + : scope.name ? "class expression '" + scope.name.text + "'" : "anonymous class expression"; + } + function getDescriptionForModuleLikeDeclaration(scope) { + return scope.kind === 245 /* ModuleBlock */ + ? "namespace '" + scope.parent.name.getText() + "'" + : scope.externalModuleIndicator ? 0 /* Module */ : 1 /* Global */; + } + var SpecialScope; + (function (SpecialScope) { + SpecialScope[SpecialScope["Module"] = 0] = "Module"; + SpecialScope[SpecialScope["Global"] = 1] = "Global"; + })(SpecialScope || (SpecialScope = {})); + /** + * Result of 'extractRange' operation for a specific scope. + * Stores either a list of changes that should be applied to extract a range or a list of errors + */ + function extractFunctionInScope(node, scope, _a, exposedVariableDeclarations, range, context) { + var usagesInScope = _a.usages, typeParameterUsages = _a.typeParameterUsages, substitutions = _a.substitutions; + var checker = context.program.getTypeChecker(); + // Make a unique name for the extracted function + var file = scope.getSourceFile(); + var functionNameText = ts.getUniqueName(ts.isClassLike(scope) ? "newMethod" : "newFunction", file); + var isJS = ts.isInJSFile(scope); + var functionName = ts.createIdentifier(functionNameText); + var returnType; + var parameters = []; + var callArguments = []; + var writes; + usagesInScope.forEach(function (usage, name) { + var typeNode; + if (!isJS) { + var type = checker.getTypeOfSymbolAtLocation(usage.symbol, usage.node); + // Widen the type so we don't emit nonsense annotations like "function fn(x: 3) {" + type = checker.getBaseTypeOfLiteralType(type); + typeNode = checker.typeToTypeNode(type, scope, 1 /* NoTruncation */); + } + var paramDecl = ts.createParameter( + /*decorators*/ undefined, + /*modifiers*/ undefined, + /*dotDotDotToken*/ undefined, + /*name*/ name, + /*questionToken*/ undefined, typeNode); + parameters.push(paramDecl); + if (usage.usage === 2 /* Write */) { + (writes || (writes = [])).push(usage); + } + callArguments.push(ts.createIdentifier(name)); + }); + var typeParametersAndDeclarations = ts.arrayFrom(typeParameterUsages.values()).map(function (type) { return ({ type: type, declaration: getFirstDeclaration(type) }); }); + var sortedTypeParametersAndDeclarations = typeParametersAndDeclarations.sort(compareTypesByDeclarationOrder); + var typeParameters = sortedTypeParametersAndDeclarations.length === 0 + ? undefined + : sortedTypeParametersAndDeclarations.map(function (t) { return t.declaration; }); + // Strictly speaking, we should check whether each name actually binds to the appropriate type + // parameter. In cases of shadowing, they may not. + var callTypeArguments = typeParameters !== undefined + ? typeParameters.map(function (decl) { return ts.createTypeReferenceNode(decl.name, /*typeArguments*/ undefined); }) + : undefined; + // Provide explicit return types for contextually-typed functions + // to avoid problems when there are literal types present + if (ts.isExpression(node) && !isJS) { + var contextualType = checker.getContextualType(node); + returnType = checker.typeToTypeNode(contextualType, scope, 1 /* NoTruncation */); // TODO: GH#18217 + } + var _b = transformFunctionBody(node, exposedVariableDeclarations, writes, substitutions, !!(range.facts & RangeFacts.HasReturn)), body = _b.body, returnValueProperty = _b.returnValueProperty; + ts.suppressLeadingAndTrailingTrivia(body); + var newFunction; + if (ts.isClassLike(scope)) { + // always create private method in TypeScript files + var modifiers = isJS ? [] : [ts.createToken(113 /* PrivateKeyword */)]; + if (range.facts & RangeFacts.InStaticRegion) { + modifiers.push(ts.createToken(116 /* StaticKeyword */)); + } + if (range.facts & RangeFacts.IsAsyncFunction) { + modifiers.push(ts.createToken(121 /* AsyncKeyword */)); + } + newFunction = ts.createMethod( + /*decorators*/ undefined, modifiers.length ? modifiers : undefined, range.facts & RangeFacts.IsGenerator ? ts.createToken(40 /* AsteriskToken */) : undefined, functionName, + /*questionToken*/ undefined, typeParameters, parameters, returnType, body); + } + else { + newFunction = ts.createFunctionDeclaration( + /*decorators*/ undefined, range.facts & RangeFacts.IsAsyncFunction ? [ts.createToken(121 /* AsyncKeyword */)] : undefined, range.facts & RangeFacts.IsGenerator ? ts.createToken(40 /* AsteriskToken */) : undefined, functionName, typeParameters, parameters, returnType, body); + } + var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); + var minInsertionPos = (isReadonlyArray(range.range) ? ts.last(range.range) : range.range).end; + var nodeToInsertBefore = getNodeToInsertFunctionBefore(minInsertionPos, scope); + if (nodeToInsertBefore) { + changeTracker.insertNodeBefore(context.file, nodeToInsertBefore, newFunction, /*blankLineBetween*/ true); + } + else { + changeTracker.insertNodeAtEndOfScope(context.file, scope, newFunction); + } + var newNodes = []; + // replace range with function call + var called = getCalledExpression(scope, range, functionNameText); + var call = ts.createCall(called, callTypeArguments, // Note that no attempt is made to take advantage of type argument inference + callArguments); + if (range.facts & RangeFacts.IsGenerator) { + call = ts.createYield(ts.createToken(40 /* AsteriskToken */), call); + } + if (range.facts & RangeFacts.IsAsyncFunction) { + call = ts.createAwait(call); + } + if (exposedVariableDeclarations.length && !writes) { + // No need to mix declarations and writes. + // How could any variables be exposed if there's a return statement? + ts.Debug.assert(!returnValueProperty); + ts.Debug.assert(!(range.facts & RangeFacts.HasReturn)); + if (exposedVariableDeclarations.length === 1) { + // Declaring exactly one variable: let x = newFunction(); + var variableDeclaration = exposedVariableDeclarations[0]; + newNodes.push(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(ts.getSynthesizedDeepClone(variableDeclaration.name), /*type*/ ts.getSynthesizedDeepClone(variableDeclaration.type), /*initializer*/ call)], // TODO (acasey): test binding patterns + variableDeclaration.parent.flags))); + } + else { + // Declaring multiple variables / return properties: + // let {x, y} = newFunction(); + var bindingElements = []; + var typeElements = []; + var commonNodeFlags = exposedVariableDeclarations[0].parent.flags; + var sawExplicitType = false; + for (var _i = 0, exposedVariableDeclarations_1 = exposedVariableDeclarations; _i < exposedVariableDeclarations_1.length; _i++) { + var variableDeclaration = exposedVariableDeclarations_1[_i]; + bindingElements.push(ts.createBindingElement( + /*dotDotDotToken*/ undefined, + /*propertyName*/ undefined, + /*name*/ ts.getSynthesizedDeepClone(variableDeclaration.name))); + // Being returned through an object literal will have widened the type. + var variableType = checker.typeToTypeNode(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(variableDeclaration)), scope, 1 /* NoTruncation */); + typeElements.push(ts.createPropertySignature( + /*modifiers*/ undefined, + /*name*/ variableDeclaration.symbol.name, + /*questionToken*/ undefined, + /*type*/ variableType, + /*initializer*/ undefined)); + sawExplicitType = sawExplicitType || variableDeclaration.type !== undefined; + commonNodeFlags = commonNodeFlags & variableDeclaration.parent.flags; + } + var typeLiteral = sawExplicitType ? ts.createTypeLiteralNode(typeElements) : undefined; + if (typeLiteral) { + ts.setEmitFlags(typeLiteral, 1 /* SingleLine */); + } + newNodes.push(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(ts.createObjectBindingPattern(bindingElements), + /*type*/ typeLiteral, + /*initializer*/ call)], commonNodeFlags))); + } + } + else if (exposedVariableDeclarations.length || writes) { + if (exposedVariableDeclarations.length) { + // CONSIDER: we're going to create one statement per variable, but we could actually preserve their original grouping. + for (var _c = 0, exposedVariableDeclarations_2 = exposedVariableDeclarations; _c < exposedVariableDeclarations_2.length; _c++) { + var variableDeclaration = exposedVariableDeclarations_2[_c]; + var flags = variableDeclaration.parent.flags; + if (flags & 2 /* Const */) { + flags = (flags & ~2 /* Const */) | 1 /* Let */; + } + newNodes.push(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(variableDeclaration.symbol.name, getTypeDeepCloneUnionUndefined(variableDeclaration.type))], flags))); + } + } + if (returnValueProperty) { + // has both writes and return, need to create variable declaration to hold return value; + newNodes.push(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(returnValueProperty, getTypeDeepCloneUnionUndefined(returnType))], 1 /* Let */))); + } + var assignments = getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes); + if (returnValueProperty) { + assignments.unshift(ts.createShorthandPropertyAssignment(returnValueProperty)); + } + // propagate writes back + if (assignments.length === 1) { + // We would only have introduced a return value property if there had been + // other assignments to make. + ts.Debug.assert(!returnValueProperty); + newNodes.push(ts.createStatement(ts.createAssignment(assignments[0].name, call))); + if (range.facts & RangeFacts.HasReturn) { + newNodes.push(ts.createReturn()); + } + } + else { + // emit e.g. + // { a, b, __return } = newFunction(a, b); + // return __return; + newNodes.push(ts.createStatement(ts.createAssignment(ts.createObjectLiteral(assignments), call))); + if (returnValueProperty) { + newNodes.push(ts.createReturn(ts.createIdentifier(returnValueProperty))); + } + } + } + else { + if (range.facts & RangeFacts.HasReturn) { + newNodes.push(ts.createReturn(call)); + } + else if (isReadonlyArray(range.range)) { + newNodes.push(ts.createStatement(call)); + } + else { + newNodes.push(call); + } + } + if (isReadonlyArray(range.range)) { + changeTracker.replaceNodeRangeWithNodes(context.file, ts.first(range.range), ts.last(range.range), newNodes); + } + else { + changeTracker.replaceNodeWithNodes(context.file, range.range, newNodes); + } + var edits = changeTracker.getChanges(); + var renameRange = isReadonlyArray(range.range) ? ts.first(range.range) : range.range; + var renameFilename = renameRange.getSourceFile().fileName; + var renameLocation = ts.getRenameLocation(edits, renameFilename, functionNameText, /*isDeclaredBeforeUse*/ false); + return { renameFilename: renameFilename, renameLocation: renameLocation, edits: edits }; + function getTypeDeepCloneUnionUndefined(typeNode) { + if (typeNode === undefined) { + return undefined; + } + var clone = ts.getSynthesizedDeepClone(typeNode); + var withoutParens = clone; + while (ts.isParenthesizedTypeNode(withoutParens)) { + withoutParens = withoutParens.type; + } + return ts.isUnionTypeNode(withoutParens) && ts.find(withoutParens.types, function (t) { return t.kind === 141 /* UndefinedKeyword */; }) + ? clone + : ts.createUnionTypeNode([clone, ts.createKeywordTypeNode(141 /* UndefinedKeyword */)]); + } + } + /** + * Result of 'extractRange' operation for a specific scope. + * Stores either a list of changes that should be applied to extract a range or a list of errors + */ + function extractConstantInScope(node, scope, _a, rangeFacts, context) { + var substitutions = _a.substitutions; + var checker = context.program.getTypeChecker(); + // Make a unique name for the extracted variable + var file = scope.getSourceFile(); + var localNameText = ts.getUniqueName(ts.isClassLike(scope) ? "newProperty" : "newLocal", file); + var isJS = ts.isInJSFile(scope); + var variableType = isJS || !checker.isContextSensitive(node) + ? undefined + : checker.typeToTypeNode(checker.getContextualType(node), scope, 1 /* NoTruncation */); // TODO: GH#18217 + var initializer = transformConstantInitializer(node, substitutions); + ts.suppressLeadingAndTrailingTrivia(initializer); + var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); + if (ts.isClassLike(scope)) { + ts.Debug.assert(!isJS); // See CannotExtractToJSClass + var modifiers = []; + modifiers.push(ts.createToken(113 /* PrivateKeyword */)); + if (rangeFacts & RangeFacts.InStaticRegion) { + modifiers.push(ts.createToken(116 /* StaticKeyword */)); + } + modifiers.push(ts.createToken(133 /* ReadonlyKeyword */)); + var newVariable = ts.createProperty( + /*decorators*/ undefined, modifiers, localNameText, + /*questionToken*/ undefined, variableType, initializer); + var localReference = ts.createPropertyAccess(rangeFacts & RangeFacts.InStaticRegion + ? ts.createIdentifier(scope.name.getText()) // TODO: GH#18217 + : ts.createThis(), ts.createIdentifier(localNameText)); + // Declare + var maxInsertionPos = node.pos; + var nodeToInsertBefore = getNodeToInsertPropertyBefore(maxInsertionPos, scope); + changeTracker.insertNodeBefore(context.file, nodeToInsertBefore, newVariable, /*blankLineBetween*/ true); + // Consume + changeTracker.replaceNode(context.file, node, localReference); + } + else { + var newVariableDeclaration = ts.createVariableDeclaration(localNameText, variableType, initializer); + // If the node is part of an initializer in a list of variable declarations, insert a new + // variable declaration into the list (in case it depends on earlier ones). + // CONSIDER: If the declaration list isn't const, we might want to split it into multiple + // lists so that the newly extracted one can be const. + var oldVariableDeclaration = getContainingVariableDeclarationIfInList(node, scope); + if (oldVariableDeclaration) { + // Declare + // CONSIDER: could detect that each is on a separate line (See `extractConstant_VariableList_MultipleLines` in `extractConstants.ts`) + changeTracker.insertNodeBefore(context.file, oldVariableDeclaration, newVariableDeclaration); + // Consume + var localReference = ts.createIdentifier(localNameText); + changeTracker.replaceNode(context.file, node, localReference); + } + else if (node.parent.kind === 221 /* ExpressionStatement */ && scope === ts.findAncestor(node, isScope)) { + // If the parent is an expression statement and the target scope is the immediately enclosing one, + // replace the statement with the declaration. + var newVariableStatement = ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([newVariableDeclaration], 2 /* Const */)); + changeTracker.replaceNode(context.file, node.parent, newVariableStatement); + } + else { + var newVariableStatement = ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([newVariableDeclaration], 2 /* Const */)); + // Declare + var nodeToInsertBefore = getNodeToInsertConstantBefore(node, scope); + if (nodeToInsertBefore.pos === 0) { + changeTracker.insertNodeAtTopOfFile(context.file, newVariableStatement, /*blankLineBetween*/ false); + } + else { + changeTracker.insertNodeBefore(context.file, nodeToInsertBefore, newVariableStatement, /*blankLineBetween*/ false); + } + // Consume + if (node.parent.kind === 221 /* ExpressionStatement */) { + // If the parent is an expression statement, delete it. + changeTracker.delete(context.file, node.parent); + } + else { + var localReference = ts.createIdentifier(localNameText); + changeTracker.replaceNode(context.file, node, localReference); + } + } + } + var edits = changeTracker.getChanges(); + var renameFilename = node.getSourceFile().fileName; + var renameLocation = ts.getRenameLocation(edits, renameFilename, localNameText, /*isDeclaredBeforeUse*/ true); + return { renameFilename: renameFilename, renameLocation: renameLocation, edits: edits }; + } + function getContainingVariableDeclarationIfInList(node, scope) { + var prevNode; + while (node !== undefined && node !== scope) { + if (ts.isVariableDeclaration(node) && + node.initializer === prevNode && + ts.isVariableDeclarationList(node.parent) && + node.parent.declarations.length > 1) { + return node; + } + prevNode = node; + node = node.parent; + } + } + function getFirstDeclaration(type) { + var firstDeclaration; + var symbol = type.symbol; + if (symbol && symbol.declarations) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (firstDeclaration === undefined || declaration.pos < firstDeclaration.pos) { + firstDeclaration = declaration; + } + } + } + return firstDeclaration; + } + function compareTypesByDeclarationOrder(_a, _b) { + var type1 = _a.type, declaration1 = _a.declaration; + var type2 = _b.type, declaration2 = _b.declaration; + return ts.compareProperties(declaration1, declaration2, "pos", ts.compareValues) + || ts.compareStringsCaseSensitive(type1.symbol ? type1.symbol.getName() : "", type2.symbol ? type2.symbol.getName() : "") + || ts.compareValues(type1.id, type2.id); + } + function getCalledExpression(scope, range, functionNameText) { + var functionReference = ts.createIdentifier(functionNameText); + if (ts.isClassLike(scope)) { + var lhs = range.facts & RangeFacts.InStaticRegion ? ts.createIdentifier(scope.name.text) : ts.createThis(); // TODO: GH#18217 + return ts.createPropertyAccess(lhs, functionReference); + } + else { + return functionReference; + } + } + function transformFunctionBody(body, exposedVariableDeclarations, writes, substitutions, hasReturn) { + var hasWritesOrVariableDeclarations = writes !== undefined || exposedVariableDeclarations.length > 0; + if (ts.isBlock(body) && !hasWritesOrVariableDeclarations && substitutions.size === 0) { + // already block, no declarations or writes to propagate back, no substitutions - can use node as is + return { body: ts.createBlock(body.statements, /*multLine*/ true), returnValueProperty: undefined }; + } + var returnValueProperty; + var ignoreReturns = false; + var statements = ts.createNodeArray(ts.isBlock(body) ? body.statements.slice(0) : [ts.isStatement(body) ? body : ts.createReturn(body)]); + // rewrite body if either there are writes that should be propagated back via return statements or there are substitutions + if (hasWritesOrVariableDeclarations || substitutions.size) { + var rewrittenStatements = ts.visitNodes(statements, visitor).slice(); + if (hasWritesOrVariableDeclarations && !hasReturn && ts.isStatement(body)) { + // add return at the end to propagate writes back in case if control flow falls out of the function body + // it is ok to know that range has at least one return since it we only allow unconditional returns + var assignments = getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes); + if (assignments.length === 1) { + rewrittenStatements.push(ts.createReturn(assignments[0].name)); + } + else { + rewrittenStatements.push(ts.createReturn(ts.createObjectLiteral(assignments))); + } + } + return { body: ts.createBlock(rewrittenStatements, /*multiLine*/ true), returnValueProperty: returnValueProperty }; + } + else { + return { body: ts.createBlock(statements, /*multiLine*/ true), returnValueProperty: undefined }; + } + function visitor(node) { + if (!ignoreReturns && node.kind === 230 /* ReturnStatement */ && hasWritesOrVariableDeclarations) { + var assignments = getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes); + if (node.expression) { + if (!returnValueProperty) { + returnValueProperty = "__return"; + } + assignments.unshift(ts.createPropertyAssignment(returnValueProperty, ts.visitNode(node.expression, visitor))); + } + if (assignments.length === 1) { + return ts.createReturn(assignments[0].name); + } + else { + return ts.createReturn(ts.createObjectLiteral(assignments)); + } + } + else { + var oldIgnoreReturns = ignoreReturns; + ignoreReturns = ignoreReturns || ts.isFunctionLikeDeclaration(node) || ts.isClassLike(node); + var substitution = substitutions.get(ts.getNodeId(node).toString()); + var result = substitution ? ts.getSynthesizedDeepClone(substitution) : ts.visitEachChild(node, visitor, ts.nullTransformationContext); + ignoreReturns = oldIgnoreReturns; + return result; + } + } + } + function transformConstantInitializer(initializer, substitutions) { + return substitutions.size + ? visitor(initializer) + : initializer; + function visitor(node) { + var substitution = substitutions.get(ts.getNodeId(node).toString()); + return substitution ? ts.getSynthesizedDeepClone(substitution) : ts.visitEachChild(node, visitor, ts.nullTransformationContext); + } + } + function getStatementsOrClassElements(scope) { + if (ts.isFunctionLikeDeclaration(scope)) { + var body = scope.body; // TODO: GH#18217 + if (ts.isBlock(body)) { + return body.statements; + } + } + else if (ts.isModuleBlock(scope) || ts.isSourceFile(scope)) { + return scope.statements; + } + else if (ts.isClassLike(scope)) { + return scope.members; + } + else { + ts.assertType(scope); + } + return ts.emptyArray; + } + /** + * If `scope` contains a function after `minPos`, then return the first such function. + * Otherwise, return `undefined`. + */ + function getNodeToInsertFunctionBefore(minPos, scope) { + return ts.find(getStatementsOrClassElements(scope), function (child) { + return child.pos >= minPos && ts.isFunctionLikeDeclaration(child) && !ts.isConstructorDeclaration(child); + }); + } + function getNodeToInsertPropertyBefore(maxPos, scope) { + var members = scope.members; + ts.Debug.assert(members.length > 0); // There must be at least one child, since we extracted from one. + var prevMember; + var allProperties = true; + for (var _i = 0, members_7 = members; _i < members_7.length; _i++) { + var member = members_7[_i]; + if (member.pos > maxPos) { + return prevMember || members[0]; + } + if (allProperties && !ts.isPropertyDeclaration(member)) { + // If it is non-vacuously true that all preceding members are properties, + // insert before the current member (i.e. at the end of the list of properties). + if (prevMember !== undefined) { + return member; + } + allProperties = false; + } + prevMember = member; + } + if (prevMember === undefined) + return ts.Debug.fail(); // If the loop didn't return, then it did set prevMember. + return prevMember; + } + function getNodeToInsertConstantBefore(node, scope) { + ts.Debug.assert(!ts.isClassLike(scope)); + var prevScope; + for (var curr = node; curr !== scope; curr = curr.parent) { + if (isScope(curr)) { + prevScope = curr; + } + } + for (var curr = (prevScope || node).parent;; curr = curr.parent) { + if (isBlockLike(curr)) { + var prevStatement = void 0; + for (var _i = 0, _a = curr.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + if (statement.pos > node.pos) { + break; + } + prevStatement = statement; + } + if (!prevStatement && ts.isCaseClause(curr)) { + // We must have been in the expression of the case clause. + ts.Debug.assert(ts.isSwitchStatement(curr.parent.parent)); + return curr.parent.parent; + } + // There must be at least one statement since we started in one. + return ts.Debug.assertDefined(prevStatement); + } + ts.Debug.assert(curr !== scope, "Didn't encounter a block-like before encountering scope"); + } + } + function getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes) { + var variableAssignments = ts.map(exposedVariableDeclarations, function (v) { return ts.createShorthandPropertyAssignment(v.symbol.name); }); + var writeAssignments = ts.map(writes, function (w) { return ts.createShorthandPropertyAssignment(w.symbol.name); }); + // TODO: GH#18217 `variableAssignments` not possibly undefined! + return variableAssignments === undefined + ? writeAssignments + : writeAssignments === undefined + ? variableAssignments + : variableAssignments.concat(writeAssignments); + } + function isReadonlyArray(v) { + return ts.isArray(v); + } + /** + * Produces a range that spans the entirety of nodes, given a selection + * that might start/end in the middle of nodes. + * + * For example, when the user makes a selection like this + * v---v + * var someThing = foo + bar; + * this returns ^-------^ + */ + function getEnclosingTextRange(targetRange, sourceFile) { + return isReadonlyArray(targetRange.range) + ? { pos: ts.first(targetRange.range).getStart(sourceFile), end: ts.last(targetRange.range).getEnd() } + : targetRange.range; + } + var Usage; + (function (Usage) { + // value should be passed to extracted method + Usage[Usage["Read"] = 1] = "Read"; + // value should be passed to extracted method and propagated back + Usage[Usage["Write"] = 2] = "Write"; + })(Usage || (Usage = {})); + function collectReadsAndWrites(targetRange, scopes, enclosingTextRange, sourceFile, checker, cancellationToken) { + var allTypeParameterUsages = ts.createMap(); // Key is type ID + var usagesPerScope = []; + var substitutionsPerScope = []; + var functionErrorsPerScope = []; + var constantErrorsPerScope = []; + var visibleDeclarationsInExtractedRange = []; + var exposedVariableSymbolSet = ts.createMap(); // Key is symbol ID + var exposedVariableDeclarations = []; + var firstExposedNonVariableDeclaration; + var expression = !isReadonlyArray(targetRange.range) + ? targetRange.range + : targetRange.range.length === 1 && ts.isExpressionStatement(targetRange.range[0]) + ? targetRange.range[0].expression + : undefined; + var expressionDiagnostic; + if (expression === undefined) { + var statements = targetRange.range; + var start = ts.first(statements).getStart(); + var end = ts.last(statements).end; + expressionDiagnostic = ts.createFileDiagnostic(sourceFile, start, end - start, Messages.expressionExpected); + } + else if (checker.getTypeAtLocation(expression).flags & (16384 /* Void */ | 131072 /* Never */)) { + expressionDiagnostic = ts.createDiagnosticForNode(expression, Messages.uselessConstantType); + } + // initialize results + for (var _i = 0, scopes_1 = scopes; _i < scopes_1.length; _i++) { + var scope = scopes_1[_i]; + usagesPerScope.push({ usages: ts.createMap(), typeParameterUsages: ts.createMap(), substitutions: ts.createMap() }); + substitutionsPerScope.push(ts.createMap()); + functionErrorsPerScope.push(ts.isFunctionLikeDeclaration(scope) && scope.kind !== 239 /* FunctionDeclaration */ + ? [ts.createDiagnosticForNode(scope, Messages.cannotExtractToOtherFunctionLike)] + : []); + var constantErrors = []; + if (expressionDiagnostic) { + constantErrors.push(expressionDiagnostic); + } + if (ts.isClassLike(scope) && ts.isInJSFile(scope)) { + constantErrors.push(ts.createDiagnosticForNode(scope, Messages.cannotExtractToJSClass)); + } + if (ts.isArrowFunction(scope) && !ts.isBlock(scope.body)) { + // TODO (https://github.com/Microsoft/TypeScript/issues/18924): allow this + constantErrors.push(ts.createDiagnosticForNode(scope, Messages.cannotExtractToExpressionArrowFunction)); + } + constantErrorsPerScope.push(constantErrors); + } + var seenUsages = ts.createMap(); + var target = isReadonlyArray(targetRange.range) ? ts.createBlock(targetRange.range) : targetRange.range; + var unmodifiedNode = isReadonlyArray(targetRange.range) ? ts.first(targetRange.range) : targetRange.range; + var inGenericContext = isInGenericContext(unmodifiedNode); + collectUsages(target); + // Unfortunately, this code takes advantage of the knowledge that the generated method + // will use the contextual type of an expression as the return type of the extracted + // method (and will therefore "use" all the types involved). + if (inGenericContext && !isReadonlyArray(targetRange.range)) { + var contextualType = checker.getContextualType(targetRange.range); // TODO: GH#18217 + recordTypeParameterUsages(contextualType); + } + if (allTypeParameterUsages.size > 0) { + var seenTypeParameterUsages = ts.createMap(); // Key is type ID + var i_1 = 0; + for (var curr = unmodifiedNode; curr !== undefined && i_1 < scopes.length; curr = curr.parent) { + if (curr === scopes[i_1]) { + // Copy current contents of seenTypeParameterUsages into scope. + seenTypeParameterUsages.forEach(function (typeParameter, id) { + usagesPerScope[i_1].typeParameterUsages.set(id, typeParameter); + }); + i_1++; + } + // Note that we add the current node's type parameters *after* updating the corresponding scope. + if (ts.isDeclarationWithTypeParameters(curr)) { + for (var _a = 0, _b = ts.getEffectiveTypeParameterDeclarations(curr); _a < _b.length; _a++) { + var typeParameterDecl = _b[_a]; + var typeParameter = checker.getTypeAtLocation(typeParameterDecl); + if (allTypeParameterUsages.has(typeParameter.id.toString())) { + seenTypeParameterUsages.set(typeParameter.id.toString(), typeParameter); + } + } + } + } + // If we didn't get through all the scopes, then there were some that weren't in our + // parent chain (impossible at time of writing). A conservative solution would be to + // copy allTypeParameterUsages into all remaining scopes. + ts.Debug.assert(i_1 === scopes.length); + } + // If there are any declarations in the extracted block that are used in the same enclosing + // lexical scope, we can't move the extraction "up" as those declarations will become unreachable + if (visibleDeclarationsInExtractedRange.length) { + var containingLexicalScopeOfExtraction = ts.isBlockScope(scopes[0], scopes[0].parent) + ? scopes[0] + : ts.getEnclosingBlockScopeContainer(scopes[0]); + ts.forEachChild(containingLexicalScopeOfExtraction, checkForUsedDeclarations); + } + var _loop_22 = function (i) { + var scopeUsages = usagesPerScope[i]; + // Special case: in the innermost scope, all usages are available. + // (The computed value reflects the value at the top-level of the scope, but the + // local will actually be declared at the same level as the extracted expression). + if (i > 0 && (scopeUsages.usages.size > 0 || scopeUsages.typeParameterUsages.size > 0)) { + var errorNode = isReadonlyArray(targetRange.range) ? targetRange.range[0] : targetRange.range; + constantErrorsPerScope[i].push(ts.createDiagnosticForNode(errorNode, Messages.cannotAccessVariablesFromNestedScopes)); + } + var hasWrite = false; + var readonlyClassPropertyWrite; + usagesPerScope[i].usages.forEach(function (value) { + if (value.usage === 2 /* Write */) { + hasWrite = true; + if (value.symbol.flags & 106500 /* ClassMember */ && + value.symbol.valueDeclaration && + ts.hasModifier(value.symbol.valueDeclaration, 64 /* Readonly */)) { + readonlyClassPropertyWrite = value.symbol.valueDeclaration; + } + } + }); + // If an expression was extracted, then there shouldn't have been any variable declarations. + ts.Debug.assert(isReadonlyArray(targetRange.range) || exposedVariableDeclarations.length === 0); + if (hasWrite && !isReadonlyArray(targetRange.range)) { + var diag = ts.createDiagnosticForNode(targetRange.range, Messages.cannotWriteInExpression); + functionErrorsPerScope[i].push(diag); + constantErrorsPerScope[i].push(diag); + } + else if (readonlyClassPropertyWrite && i > 0) { + var diag = ts.createDiagnosticForNode(readonlyClassPropertyWrite, Messages.cannotExtractReadonlyPropertyInitializerOutsideConstructor); + functionErrorsPerScope[i].push(diag); + constantErrorsPerScope[i].push(diag); + } + else if (firstExposedNonVariableDeclaration) { + var diag = ts.createDiagnosticForNode(firstExposedNonVariableDeclaration, Messages.cannotExtractExportedEntity); + functionErrorsPerScope[i].push(diag); + constantErrorsPerScope[i].push(diag); + } + }; + for (var i = 0; i < scopes.length; i++) { + _loop_22(i); + } + return { target: target, usagesPerScope: usagesPerScope, functionErrorsPerScope: functionErrorsPerScope, constantErrorsPerScope: constantErrorsPerScope, exposedVariableDeclarations: exposedVariableDeclarations }; + function isInGenericContext(node) { + return !!ts.findAncestor(node, function (n) { return ts.isDeclarationWithTypeParameters(n) && ts.getEffectiveTypeParameterDeclarations(n).length !== 0; }); + } + function recordTypeParameterUsages(type) { + // PERF: This is potentially very expensive. `type` could be a library type with + // a lot of properties, each of which the walker will visit. Unfortunately, the + // solution isn't as trivial as filtering to user types because of (e.g.) Array. + var symbolWalker = checker.getSymbolWalker(function () { return (cancellationToken.throwIfCancellationRequested(), true); }); + var visitedTypes = symbolWalker.walkType(type).visitedTypes; + for (var _i = 0, visitedTypes_1 = visitedTypes; _i < visitedTypes_1.length; _i++) { + var visitedType = visitedTypes_1[_i]; + if (visitedType.isTypeParameter()) { + allTypeParameterUsages.set(visitedType.id.toString(), visitedType); + } + } + } + function collectUsages(node, valueUsage) { + if (valueUsage === void 0) { valueUsage = 1 /* Read */; } + if (inGenericContext) { + var type = checker.getTypeAtLocation(node); + recordTypeParameterUsages(type); + } + if (ts.isDeclaration(node) && node.symbol) { + visibleDeclarationsInExtractedRange.push(node); + } + if (ts.isAssignmentExpression(node)) { + // use 'write' as default usage for values + collectUsages(node.left, 2 /* Write */); + collectUsages(node.right); + } + else if (ts.isUnaryExpressionWithWrite(node)) { + collectUsages(node.operand, 2 /* Write */); + } + else if (ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node)) { + // use 'write' as default usage for values + ts.forEachChild(node, collectUsages); + } + else if (ts.isIdentifier(node)) { + if (!node.parent) { + return; + } + if (ts.isQualifiedName(node.parent) && node !== node.parent.left) { + return; + } + if (ts.isPropertyAccessExpression(node.parent) && node !== node.parent.expression) { + return; + } + recordUsage(node, valueUsage, /*isTypeNode*/ ts.isPartOfTypeNode(node)); + } + else { + ts.forEachChild(node, collectUsages); + } + } + function recordUsage(n, usage, isTypeNode) { + var symbolId = recordUsagebySymbol(n, usage, isTypeNode); + if (symbolId) { + for (var i = 0; i < scopes.length; i++) { + // push substitution from map to map to simplify rewriting + var substitution = substitutionsPerScope[i].get(symbolId); + if (substitution) { + usagesPerScope[i].substitutions.set(ts.getNodeId(n).toString(), substitution); + } + } + } + } + function recordUsagebySymbol(identifier, usage, isTypeName) { + var symbol = getSymbolReferencedByIdentifier(identifier); + if (!symbol) { + // cannot find symbol - do nothing + return undefined; + } + var symbolId = ts.getSymbolId(symbol).toString(); + var lastUsage = seenUsages.get(symbolId); + // there are two kinds of value usages + // - reads - if range contains a read from the value located outside of the range then value should be passed as a parameter + // - writes - if range contains a write to a value located outside the range the value should be passed as a parameter and + // returned as a return value + // 'write' case is a superset of 'read' so if we already have processed 'write' of some symbol there is not need to handle 'read' + // since all information is already recorded + if (lastUsage && lastUsage >= usage) { + return symbolId; + } + seenUsages.set(symbolId, usage); + if (lastUsage) { + // if we get here this means that we are trying to handle 'write' and 'read' was already processed + // walk scopes and update existing records. + for (var _i = 0, usagesPerScope_1 = usagesPerScope; _i < usagesPerScope_1.length; _i++) { + var perScope = usagesPerScope_1[_i]; + var prevEntry = perScope.usages.get(identifier.text); + if (prevEntry) { + perScope.usages.set(identifier.text, { usage: usage, symbol: symbol, node: identifier }); + } + } + return symbolId; + } + // find first declaration in this file + var decls = symbol.getDeclarations(); + var declInFile = decls && ts.find(decls, function (d) { return d.getSourceFile() === sourceFile; }); + if (!declInFile) { + return undefined; + } + if (ts.rangeContainsStartEnd(enclosingTextRange, declInFile.getStart(), declInFile.end)) { + // declaration is located in range to be extracted - do nothing + return undefined; + } + if (targetRange.facts & RangeFacts.IsGenerator && usage === 2 /* Write */) { + // this is write to a reference located outside of the target scope and range is extracted into generator + // currently this is unsupported scenario + var diag = ts.createDiagnosticForNode(identifier, Messages.cannotExtractRangeThatContainsWritesToReferencesLocatedOutsideOfTheTargetRangeInGenerators); + for (var _a = 0, functionErrorsPerScope_1 = functionErrorsPerScope; _a < functionErrorsPerScope_1.length; _a++) { + var errors = functionErrorsPerScope_1[_a]; + errors.push(diag); + } + for (var _b = 0, constantErrorsPerScope_1 = constantErrorsPerScope; _b < constantErrorsPerScope_1.length; _b++) { + var errors = constantErrorsPerScope_1[_b]; + errors.push(diag); + } + } + for (var i = 0; i < scopes.length; i++) { + var scope = scopes[i]; + var resolvedSymbol = checker.resolveName(symbol.name, scope, symbol.flags, /*excludeGlobals*/ false); + if (resolvedSymbol === symbol) { + continue; + } + if (!substitutionsPerScope[i].has(symbolId)) { + var substitution = tryReplaceWithQualifiedNameOrPropertyAccess(symbol.exportSymbol || symbol, scope, isTypeName); + if (substitution) { + substitutionsPerScope[i].set(symbolId, substitution); + } + else if (isTypeName) { + // If the symbol is a type parameter that won't be in scope, we'll pass it as a type argument + // so there's no problem. + if (!(symbol.flags & 262144 /* TypeParameter */)) { + var diag = ts.createDiagnosticForNode(identifier, Messages.typeWillNotBeVisibleInTheNewScope); + functionErrorsPerScope[i].push(diag); + constantErrorsPerScope[i].push(diag); + } + } + else { + usagesPerScope[i].usages.set(identifier.text, { usage: usage, symbol: symbol, node: identifier }); + } + } + } + return symbolId; + } + function checkForUsedDeclarations(node) { + // If this node is entirely within the original extraction range, we don't need to do anything. + if (node === targetRange.range || (isReadonlyArray(targetRange.range) && targetRange.range.indexOf(node) >= 0)) { + return; + } + // Otherwise check and recurse. + var sym = ts.isIdentifier(node) + ? getSymbolReferencedByIdentifier(node) + : checker.getSymbolAtLocation(node); + if (sym) { + var decl = ts.find(visibleDeclarationsInExtractedRange, function (d) { return d.symbol === sym; }); + if (decl) { + if (ts.isVariableDeclaration(decl)) { + var idString = decl.symbol.id.toString(); + if (!exposedVariableSymbolSet.has(idString)) { + exposedVariableDeclarations.push(decl); + exposedVariableSymbolSet.set(idString, true); + } + } + else { + // CONSIDER: this includes binding elements, which we could + // expose in the same way as variables. + firstExposedNonVariableDeclaration = firstExposedNonVariableDeclaration || decl; + } + } + } + ts.forEachChild(node, checkForUsedDeclarations); + } + /** + * Return the symbol referenced by an identifier (even if it declares a different symbol). + */ + function getSymbolReferencedByIdentifier(identifier) { + // If the identifier is both a property name and its value, we're only interested in its value + // (since the name is a declaration and will be included in the extracted range). + return identifier.parent && ts.isShorthandPropertyAssignment(identifier.parent) && identifier.parent.name === identifier + ? checker.getShorthandAssignmentValueSymbol(identifier.parent) + : checker.getSymbolAtLocation(identifier); + } + function tryReplaceWithQualifiedNameOrPropertyAccess(symbol, scopeDecl, isTypeNode) { + if (!symbol) { + return undefined; + } + var decls = symbol.getDeclarations(); + if (decls && decls.some(function (d) { return d.parent === scopeDecl; })) { + return ts.createIdentifier(symbol.name); + } + var prefix = tryReplaceWithQualifiedNameOrPropertyAccess(symbol.parent, scopeDecl, isTypeNode); + if (prefix === undefined) { + return undefined; + } + return isTypeNode + ? ts.createQualifiedName(prefix, ts.createIdentifier(symbol.name)) + : ts.createPropertyAccess(prefix, symbol.name); + } + } + /** + * Computes whether or not a node represents an expression in a position where it could + * be extracted. + * The isExpression() in utilities.ts returns some false positives we need to handle, + * such as `import x from 'y'` -- the 'y' is a StringLiteral but is *not* an expression + * in the sense of something that you could extract on + */ + function isExtractableExpression(node) { + var parent = node.parent; + switch (parent.kind) { + case 278 /* EnumMember */: + return false; + } + switch (node.kind) { + case 10 /* StringLiteral */: + return parent.kind !== 249 /* ImportDeclaration */ && + parent.kind !== 253 /* ImportSpecifier */; + case 208 /* SpreadElement */: + case 184 /* ObjectBindingPattern */: + case 186 /* BindingElement */: + return false; + case 72 /* Identifier */: + return parent.kind !== 186 /* BindingElement */ && + parent.kind !== 253 /* ImportSpecifier */ && + parent.kind !== 257 /* ExportSpecifier */; + } + return true; + } + function isBlockLike(node) { + switch (node.kind) { + case 218 /* Block */: + case 279 /* SourceFile */: + case 245 /* ModuleBlock */: + case 271 /* CaseClause */: + return true; + default: + return false; + } + } + })(extractSymbol = refactor.extractSymbol || (refactor.extractSymbol = {})); + })(refactor = ts.refactor || (ts.refactor = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var refactor; + (function (refactor) { + var generateGetAccessorAndSetAccessor; + (function (generateGetAccessorAndSetAccessor) { + var actionName = "Generate 'get' and 'set' accessors"; + var actionDescription = ts.Diagnostics.Generate_get_and_set_accessors.message; + refactor.registerRefactor(actionName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions }); + function getAvailableActions(context) { + if (!getConvertibleFieldAtPosition(context)) + return ts.emptyArray; + return [{ + name: actionName, + description: actionDescription, + actions: [ + { + name: actionName, + description: actionDescription + } + ] + }]; + } + function getEditsForAction(context, _actionName) { + var file = context.file; + var fieldInfo = getConvertibleFieldAtPosition(context); + if (!fieldInfo) + return undefined; + var isJS = ts.isSourceFileJS(file); + var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); + var isStatic = fieldInfo.isStatic, isReadonly = fieldInfo.isReadonly, fieldName = fieldInfo.fieldName, accessorName = fieldInfo.accessorName, originalName = fieldInfo.originalName, type = fieldInfo.type, container = fieldInfo.container, declaration = fieldInfo.declaration, renameAccessor = fieldInfo.renameAccessor; + ts.suppressLeadingAndTrailingTrivia(fieldName); + ts.suppressLeadingAndTrailingTrivia(declaration); + ts.suppressLeadingAndTrailingTrivia(container); + var isInClassLike = ts.isClassLike(container); + // avoid Readonly modifier because it will convert to get accessor + var modifierFlags = ts.getModifierFlags(declaration) & ~64 /* Readonly */; + var accessorModifiers = isInClassLike + ? !modifierFlags || modifierFlags & 8 /* Private */ + ? getModifiers(isJS, isStatic, 115 /* PublicKeyword */) + : ts.createNodeArray(ts.createModifiersFromModifierFlags(modifierFlags)) + : undefined; + var fieldModifiers = isInClassLike ? getModifiers(isJS, isStatic, 113 /* PrivateKeyword */) : undefined; + updateFieldDeclaration(changeTracker, file, declaration, fieldName, fieldModifiers); + var getAccessor = generateGetAccessor(fieldName, accessorName, type, accessorModifiers, isStatic, container); + ts.suppressLeadingAndTrailingTrivia(getAccessor); + insertAccessor(changeTracker, file, getAccessor, declaration, container); + if (isReadonly) { + // readonly modifier only existed in classLikeDeclaration + var constructor = ts.getFirstConstructorWithBody(container); + if (constructor) { + updateReadonlyPropertyInitializerStatementConstructor(changeTracker, file, constructor, fieldName.text, originalName); + } + } + else { + var setAccessor = generateSetAccessor(fieldName, accessorName, type, accessorModifiers, isStatic, container); + ts.suppressLeadingAndTrailingTrivia(setAccessor); + insertAccessor(changeTracker, file, setAccessor, declaration, container); + } + var edits = changeTracker.getChanges(); + var renameFilename = file.fileName; + var nameNeedRename = renameAccessor ? accessorName : fieldName; + var renameLocationOffset = ts.isIdentifier(nameNeedRename) ? 0 : -1; + var renameLocation = renameLocationOffset + ts.getRenameLocation(edits, renameFilename, nameNeedRename.text, /*preferLastLocation*/ ts.isParameter(declaration)); + return { renameFilename: renameFilename, renameLocation: renameLocation, edits: edits }; + } + function isConvertibleName(name) { + return ts.isIdentifier(name) || ts.isStringLiteral(name); + } + function isAcceptedDeclaration(node) { + return ts.isParameterPropertyDeclaration(node) || ts.isPropertyDeclaration(node) || ts.isPropertyAssignment(node); + } + function createPropertyName(name, originalName) { + return ts.isIdentifier(originalName) ? ts.createIdentifier(name) : ts.createLiteral(name); + } + function createAccessorAccessExpression(fieldName, isStatic, container) { + var leftHead = isStatic ? container.name : ts.createThis(); // TODO: GH#18217 + return ts.isIdentifier(fieldName) ? ts.createPropertyAccess(leftHead, fieldName) : ts.createElementAccess(leftHead, ts.createLiteral(fieldName)); + } + function getModifiers(isJS, isStatic, accessModifier) { + var modifiers = ts.append(!isJS ? [ts.createToken(accessModifier)] : undefined, isStatic ? ts.createToken(116 /* StaticKeyword */) : undefined); + return modifiers && ts.createNodeArray(modifiers); + } + function startsWithUnderscore(name) { + return name.charCodeAt(0) === 95 /* _ */; + } + function getConvertibleFieldAtPosition(context) { + var file = context.file, startPosition = context.startPosition, endPosition = context.endPosition; + var node = ts.getTokenAtPosition(file, startPosition); + var declaration = ts.findAncestor(node.parent, isAcceptedDeclaration); + // make sure declaration have AccessibilityModifier or Static Modifier or Readonly Modifier + var meaning = 28 /* AccessibilityModifier */ | 32 /* Static */ | 64 /* Readonly */; + if (!declaration || !ts.nodeOverlapsWithStartEnd(declaration.name, file, startPosition, endPosition) // TODO: GH#18217 + || !isConvertibleName(declaration.name) || (ts.getModifierFlags(declaration) | meaning) !== meaning) + return undefined; + var name = declaration.name.text; + var startWithUnderscore = startsWithUnderscore(name); + var fieldName = createPropertyName(startWithUnderscore ? name : ts.getUniqueName("_" + name, file), declaration.name); + var accessorName = createPropertyName(startWithUnderscore ? ts.getUniqueName(name.substring(1), file) : name, declaration.name); + return { + isStatic: ts.hasStaticModifier(declaration), + isReadonly: ts.hasReadonlyModifier(declaration), + type: ts.getTypeAnnotationNode(declaration), + container: declaration.kind === 151 /* Parameter */ ? declaration.parent.parent : declaration.parent, + originalName: declaration.name.text, + declaration: declaration, + fieldName: fieldName, + accessorName: accessorName, + renameAccessor: startWithUnderscore + }; + } + function generateGetAccessor(fieldName, accessorName, type, modifiers, isStatic, container) { + return ts.createGetAccessor( + /*decorators*/ undefined, modifiers, accessorName, + /*parameters*/ undefined, // TODO: GH#18217 + type, ts.createBlock([ + ts.createReturn(createAccessorAccessExpression(fieldName, isStatic, container)) + ], /*multiLine*/ true)); + } + function generateSetAccessor(fieldName, accessorName, type, modifiers, isStatic, container) { + return ts.createSetAccessor( + /*decorators*/ undefined, modifiers, accessorName, [ts.createParameter( + /*decorators*/ undefined, + /*modifiers*/ undefined, + /*dotDotDotToken*/ undefined, ts.createIdentifier("value"), + /*questionToken*/ undefined, type)], ts.createBlock([ + ts.createStatement(ts.createAssignment(createAccessorAccessExpression(fieldName, isStatic, container), ts.createIdentifier("value"))) + ], /*multiLine*/ true)); + } + function updatePropertyDeclaration(changeTracker, file, declaration, fieldName, modifiers) { + var property = ts.updateProperty(declaration, declaration.decorators, modifiers, fieldName, declaration.questionToken || declaration.exclamationToken, declaration.type, declaration.initializer); + changeTracker.replaceNode(file, declaration, property); + } + function updatePropertyAssignmentDeclaration(changeTracker, file, declaration, fieldName) { + var assignment = ts.updatePropertyAssignment(declaration, fieldName, declaration.initializer); + changeTracker.replacePropertyAssignment(file, declaration, assignment); + } + function updateFieldDeclaration(changeTracker, file, declaration, fieldName, modifiers) { + if (ts.isPropertyDeclaration(declaration)) { + updatePropertyDeclaration(changeTracker, file, declaration, fieldName, modifiers); + } + else if (ts.isPropertyAssignment(declaration)) { + updatePropertyAssignmentDeclaration(changeTracker, file, declaration, fieldName); + } + else { + changeTracker.replaceNode(file, declaration, ts.updateParameter(declaration, declaration.decorators, modifiers, declaration.dotDotDotToken, ts.cast(fieldName, ts.isIdentifier), declaration.questionToken, declaration.type, declaration.initializer)); + } + } + function insertAccessor(changeTracker, file, accessor, declaration, container) { + ts.isParameterPropertyDeclaration(declaration) + ? changeTracker.insertNodeAtClassStart(file, container, accessor) + : ts.isPropertyAssignment(declaration) + ? changeTracker.insertNodeAfterComma(file, declaration, accessor) + : changeTracker.insertNodeAfter(file, declaration, accessor); + } + function updateReadonlyPropertyInitializerStatementConstructor(changeTracker, file, constructor, fieldName, originalName) { + if (!constructor.body) + return; + constructor.body.forEachChild(function recur(node) { + if (ts.isElementAccessExpression(node) && + node.expression.kind === 100 /* ThisKeyword */ && + ts.isStringLiteral(node.argumentExpression) && + node.argumentExpression.text === originalName && + ts.isWriteAccess(node)) { + changeTracker.replaceNode(file, node.argumentExpression, ts.createStringLiteral(fieldName)); + } + if (ts.isPropertyAccessExpression(node) && node.expression.kind === 100 /* ThisKeyword */ && node.name.text === originalName && ts.isWriteAccess(node)) { + changeTracker.replaceNode(file, node.name, ts.createIdentifier(fieldName)); + } + if (!ts.isFunctionLike(node) && !ts.isClassLike(node)) { + node.forEachChild(recur); + } + }); + } + })(generateGetAccessorAndSetAccessor = refactor.generateGetAccessorAndSetAccessor || (refactor.generateGetAccessorAndSetAccessor = {})); + })(refactor = ts.refactor || (ts.refactor = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var refactor; + (function (refactor) { + var refactorName = "Move to a new file"; + refactor.registerRefactor(refactorName, { + getAvailableActions: function (context) { + if (!context.preferences.allowTextChangesInNewFiles || getStatementsToMove(context) === undefined) + return ts.emptyArray; + var description = ts.getLocaleSpecificMessage(ts.Diagnostics.Move_to_a_new_file); + return [{ name: refactorName, description: description, actions: [{ name: refactorName, description: description }] }]; + }, + getEditsForAction: function (context, actionName) { + ts.Debug.assert(actionName === refactorName); + var statements = ts.Debug.assertDefined(getStatementsToMove(context)); + var edits = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(context.file, context.program, statements, t, context.host, context.preferences); }); + return { edits: edits, renameFilename: undefined, renameLocation: undefined }; + } + }); + function getRangeToMove(context) { + var file = context.file; + var range = ts.createTextRangeFromSpan(ts.getRefactorContextSpan(context)); + var statements = file.statements; + var startNodeIndex = ts.findIndex(statements, function (s) { return s.end > range.pos; }); + if (startNodeIndex === -1) + return undefined; + var startStatement = statements[startNodeIndex]; + if (ts.isNamedDeclaration(startStatement) && startStatement.name && ts.rangeContainsRange(startStatement.name, range)) { + return { toMove: [statements[startNodeIndex]], afterLast: statements[startNodeIndex + 1] }; + } + // Can't only partially include the start node or be partially into the next node + if (range.pos > startStatement.getStart(file)) + return undefined; + var afterEndNodeIndex = ts.findIndex(statements, function (s) { return s.end > range.end; }, startNodeIndex); + // Can't be partially into the next node + if (afterEndNodeIndex !== -1 && (afterEndNodeIndex === 0 || statements[afterEndNodeIndex].getStart(file) < range.end)) + return undefined; + return { + toMove: statements.slice(startNodeIndex, afterEndNodeIndex === -1 ? statements.length : afterEndNodeIndex), + afterLast: afterEndNodeIndex === -1 ? undefined : statements[afterEndNodeIndex], + }; + } + function doChange(oldFile, program, toMove, changes, host, preferences) { + var checker = program.getTypeChecker(); + var usage = getUsageInfo(oldFile, toMove.all, checker); + var currentDirectory = ts.getDirectoryPath(oldFile.fileName); + var extension = ts.extensionFromPath(oldFile.fileName); + var newModuleName = makeUniqueModuleName(getNewModuleName(usage.movedSymbols), extension, currentDirectory, host); + var newFileNameWithExtension = newModuleName + extension; + // If previous file was global, this is easy. + changes.createNewFile(oldFile, ts.combinePaths(currentDirectory, newFileNameWithExtension), getNewStatementsAndRemoveFromOldFile(oldFile, usage, changes, toMove, program, newModuleName, preferences)); + addNewFileToTsconfig(program, changes, oldFile.fileName, newFileNameWithExtension, ts.hostGetCanonicalFileName(host)); + } + // Filters imports out of the range of statements to move. Imports will be copied to the new file anyway, and may still be needed in the old file. + function getStatementsToMove(context) { + var rangeToMove = getRangeToMove(context); + if (rangeToMove === undefined) + return undefined; + var all = []; + var ranges = []; + var toMove = rangeToMove.toMove, afterLast = rangeToMove.afterLast; + ts.getRangesWhere(toMove, function (s) { return !isPureImport(s); }, function (start, afterEndIndex) { + for (var i = start; i < afterEndIndex; i++) + all.push(toMove[i]); + ranges.push({ first: toMove[start], afterLast: afterLast }); + }); + return all.length === 0 ? undefined : { all: all, ranges: ranges }; + } + function isPureImport(node) { + switch (node.kind) { + case 249 /* ImportDeclaration */: + return true; + case 248 /* ImportEqualsDeclaration */: + return !ts.hasModifier(node, 1 /* Export */); + case 219 /* VariableStatement */: + return node.declarationList.declarations.every(function (d) { return !!d.initializer && ts.isRequireCall(d.initializer, /*checkArgumentIsStringLiteralLike*/ true); }); + default: + return false; + } + } + function addNewFileToTsconfig(program, changes, oldFileName, newFileNameWithExtension, getCanonicalFileName) { + var cfg = program.getCompilerOptions().configFile; + if (!cfg) + return; + var newFileAbsolutePath = ts.normalizePath(ts.combinePaths(oldFileName, "..", newFileNameWithExtension)); + var newFilePath = ts.getRelativePathFromFile(cfg.fileName, newFileAbsolutePath, getCanonicalFileName); + var cfgObject = cfg.statements[0] && ts.tryCast(cfg.statements[0].expression, ts.isObjectLiteralExpression); + var filesProp = cfgObject && ts.find(cfgObject.properties, function (prop) { + return ts.isPropertyAssignment(prop) && ts.isStringLiteral(prop.name) && prop.name.text === "files"; + }); + if (filesProp && ts.isArrayLiteralExpression(filesProp.initializer)) { + changes.insertNodeInListAfter(cfg, ts.last(filesProp.initializer.elements), ts.createLiteral(newFilePath), filesProp.initializer.elements); + } + } + function getNewStatementsAndRemoveFromOldFile(oldFile, usage, changes, toMove, program, newModuleName, preferences) { + var checker = program.getTypeChecker(); + if (!oldFile.externalModuleIndicator && !oldFile.commonJsModuleIndicator) { + deleteMovedStatements(oldFile, toMove.ranges, changes); + return toMove.all; + } + var useEs6ModuleSyntax = !!oldFile.externalModuleIndicator; + var quotePreference = ts.getQuotePreference(oldFile, preferences); + var importsFromNewFile = createOldFileImportsFromNewFile(usage.oldFileImportsFromNewFile, newModuleName, useEs6ModuleSyntax, quotePreference); + if (importsFromNewFile) { + ts.insertImport(changes, oldFile, importsFromNewFile); + } + deleteUnusedOldImports(oldFile, toMove.all, changes, usage.unusedImportsFromOldFile, checker); + deleteMovedStatements(oldFile, toMove.ranges, changes); + updateImportsInOtherFiles(changes, program, oldFile, usage.movedSymbols, newModuleName); + return getNewFileImportsAndAddExportInOldFile(oldFile, usage.oldImportsNeededByNewFile, usage.newFileImportsFromOldFile, changes, checker, useEs6ModuleSyntax, quotePreference).concat(addExports(oldFile, toMove.all, usage.oldFileImportsFromNewFile, useEs6ModuleSyntax)); + } + function deleteMovedStatements(sourceFile, moved, changes) { + for (var _i = 0, moved_1 = moved; _i < moved_1.length; _i++) { + var _a = moved_1[_i], first_1 = _a.first, afterLast = _a.afterLast; + changes.deleteNodeRangeExcludingEnd(sourceFile, first_1, afterLast); + } + } + function deleteUnusedOldImports(oldFile, toMove, changes, toDelete, checker) { + for (var _i = 0, _a = oldFile.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + if (ts.contains(toMove, statement)) + continue; + forEachImportInStatement(statement, function (i) { return deleteUnusedImports(oldFile, i, changes, function (name) { return toDelete.has(checker.getSymbolAtLocation(name)); }); }); + } + } + function updateImportsInOtherFiles(changes, program, oldFile, movedSymbols, newModuleName) { + var checker = program.getTypeChecker(); + var _loop_23 = function (sourceFile) { + if (sourceFile === oldFile) + return "continue"; + var _loop_24 = function (statement) { + forEachImportInStatement(statement, function (importNode) { + if (checker.getSymbolAtLocation(moduleSpecifierFromImport(importNode)) !== oldFile.symbol) + return; + var shouldMove = function (name) { + var symbol = ts.isBindingElement(name.parent) + ? ts.getPropertySymbolFromBindingElement(checker, name.parent) + : ts.skipAlias(checker.getSymbolAtLocation(name), checker); // TODO: GH#18217 + return !!symbol && movedSymbols.has(symbol); + }; + deleteUnusedImports(sourceFile, importNode, changes, shouldMove); // These will be changed to imports from the new file + var newModuleSpecifier = ts.combinePaths(ts.getDirectoryPath(moduleSpecifierFromImport(importNode).text), newModuleName); + var newImportDeclaration = filterImport(importNode, ts.createLiteral(newModuleSpecifier), shouldMove); + if (newImportDeclaration) + changes.insertNodeAfter(sourceFile, statement, newImportDeclaration); + var ns = getNamespaceLikeImport(importNode); + if (ns) + updateNamespaceLikeImport(changes, sourceFile, checker, movedSymbols, newModuleName, newModuleSpecifier, ns, importNode); + }); + }; + for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + _loop_24(statement); + } + }; + for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { + var sourceFile = _a[_i]; + _loop_23(sourceFile); + } + } + function getNamespaceLikeImport(node) { + switch (node.kind) { + case 249 /* ImportDeclaration */: + return node.importClause && node.importClause.namedBindings && node.importClause.namedBindings.kind === 251 /* NamespaceImport */ ? + node.importClause.namedBindings.name : undefined; + case 248 /* ImportEqualsDeclaration */: + return node.name; + case 237 /* VariableDeclaration */: + return ts.tryCast(node.name, ts.isIdentifier); + default: + return ts.Debug.assertNever(node); + } + } + function updateNamespaceLikeImport(changes, sourceFile, checker, movedSymbols, newModuleName, newModuleSpecifier, oldImportId, oldImportNode) { + var preferredNewNamespaceName = ts.codefix.moduleSpecifierToValidIdentifier(newModuleName, 6 /* ESNext */); + var needUniqueName = false; + var toChange = []; + ts.FindAllReferences.Core.eachSymbolReferenceInFile(oldImportId, checker, sourceFile, function (ref) { + if (!ts.isPropertyAccessExpression(ref.parent)) + return; + needUniqueName = needUniqueName || !!checker.resolveName(preferredNewNamespaceName, ref, 67108863 /* All */, /*excludeGlobals*/ true); + if (movedSymbols.has(checker.getSymbolAtLocation(ref.parent.name))) { + toChange.push(ref); + } + }); + if (toChange.length) { + var newNamespaceName = needUniqueName ? ts.getUniqueName(preferredNewNamespaceName, sourceFile) : preferredNewNamespaceName; + for (var _i = 0, toChange_1 = toChange; _i < toChange_1.length; _i++) { + var ref = toChange_1[_i]; + changes.replaceNode(sourceFile, ref, ts.createIdentifier(newNamespaceName)); + } + changes.insertNodeAfter(sourceFile, oldImportNode, updateNamespaceLikeImportNode(oldImportNode, newModuleName, newModuleSpecifier)); + } + } + function updateNamespaceLikeImportNode(node, newNamespaceName, newModuleSpecifier) { + var newNamespaceId = ts.createIdentifier(newNamespaceName); + var newModuleString = ts.createLiteral(newModuleSpecifier); + switch (node.kind) { + case 249 /* ImportDeclaration */: + return ts.createImportDeclaration( + /*decorators*/ undefined, /*modifiers*/ undefined, ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(newNamespaceId)), newModuleString); + case 248 /* ImportEqualsDeclaration */: + return ts.createImportEqualsDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, newNamespaceId, ts.createExternalModuleReference(newModuleString)); + case 237 /* VariableDeclaration */: + return ts.createVariableDeclaration(newNamespaceId, /*type*/ undefined, createRequireCall(newModuleString)); + default: + return ts.Debug.assertNever(node); + } + } + function moduleSpecifierFromImport(i) { + return (i.kind === 249 /* ImportDeclaration */ ? i.moduleSpecifier + : i.kind === 248 /* ImportEqualsDeclaration */ ? i.moduleReference.expression + : i.initializer.arguments[0]); + } + function forEachImportInStatement(statement, cb) { + if (ts.isImportDeclaration(statement)) { + if (ts.isStringLiteral(statement.moduleSpecifier)) + cb(statement); + } + else if (ts.isImportEqualsDeclaration(statement)) { + if (ts.isExternalModuleReference(statement.moduleReference) && ts.isStringLiteralLike(statement.moduleReference.expression)) { + cb(statement); + } + } + else if (ts.isVariableStatement(statement)) { + for (var _i = 0, _a = statement.declarationList.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + if (decl.initializer && ts.isRequireCall(decl.initializer, /*checkArgumentIsStringLiteralLike*/ true)) { + cb(decl); + } + } + } + } + function createOldFileImportsFromNewFile(newFileNeedExport, newFileNameWithExtension, useEs6Imports, quotePreference) { + var defaultImport; + var imports = []; + newFileNeedExport.forEach(function (symbol) { + if (symbol.escapedName === "default" /* Default */) { + defaultImport = ts.createIdentifier(ts.symbolNameNoDefault(symbol)); // TODO: GH#18217 + } + else { + imports.push(symbol.name); + } + }); + return makeImportOrRequire(defaultImport, imports, newFileNameWithExtension, useEs6Imports, quotePreference); + } + function makeImportOrRequire(defaultImport, imports, path, useEs6Imports, quotePreference) { + path = ts.ensurePathIsNonModuleName(path); + if (useEs6Imports) { + var specifiers = imports.map(function (i) { return ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(i)); }); + return ts.makeImportIfNecessary(defaultImport, specifiers, path, quotePreference); + } + else { + ts.Debug.assert(!defaultImport); // If there's a default export, it should have been an es6 module. + var bindingElements = imports.map(function (i) { return ts.createBindingElement(/*dotDotDotToken*/ undefined, /*propertyName*/ undefined, i); }); + return bindingElements.length + ? makeVariableStatement(ts.createObjectBindingPattern(bindingElements), /*type*/ undefined, createRequireCall(ts.createLiteral(path))) + : undefined; + } + } + function makeVariableStatement(name, type, initializer, flags) { + if (flags === void 0) { flags = 2 /* Const */; } + return ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(name, type, initializer)], flags)); + } + function createRequireCall(moduleSpecifier) { + return ts.createCall(ts.createIdentifier("require"), /*typeArguments*/ undefined, [moduleSpecifier]); + } + function addExports(sourceFile, toMove, needExport, useEs6Exports) { + return ts.flatMap(toMove, function (statement) { + if (isTopLevelDeclarationStatement(statement) && + !isExported(sourceFile, statement, useEs6Exports) && + forEachTopLevelDeclaration(statement, function (d) { return needExport.has(ts.Debug.assertDefined(d.symbol)); })) { + var exports_2 = addExport(statement, useEs6Exports); + if (exports_2) + return exports_2; + } + return statement; + }); + } + function deleteUnusedImports(sourceFile, importDecl, changes, isUnused) { + switch (importDecl.kind) { + case 249 /* ImportDeclaration */: + deleteUnusedImportsInDeclaration(sourceFile, importDecl, changes, isUnused); + break; + case 248 /* ImportEqualsDeclaration */: + if (isUnused(importDecl.name)) { + changes.delete(sourceFile, importDecl); + } + break; + case 237 /* VariableDeclaration */: + deleteUnusedImportsInVariableDeclaration(sourceFile, importDecl, changes, isUnused); + break; + default: + ts.Debug.assertNever(importDecl); + } + } + function deleteUnusedImportsInDeclaration(sourceFile, importDecl, changes, isUnused) { + if (!importDecl.importClause) + return; + var _a = importDecl.importClause, name = _a.name, namedBindings = _a.namedBindings; + var defaultUnused = !name || isUnused(name); + var namedBindingsUnused = !namedBindings || + (namedBindings.kind === 251 /* NamespaceImport */ ? isUnused(namedBindings.name) : namedBindings.elements.length !== 0 && namedBindings.elements.every(function (e) { return isUnused(e.name); })); + if (defaultUnused && namedBindingsUnused) { + changes.delete(sourceFile, importDecl); + } + else { + if (name && defaultUnused) { + changes.delete(sourceFile, name); + } + if (namedBindings) { + if (namedBindingsUnused) { + changes.delete(sourceFile, namedBindings); + } + else if (namedBindings.kind === 252 /* NamedImports */) { + for (var _i = 0, _b = namedBindings.elements; _i < _b.length; _i++) { + var element = _b[_i]; + if (isUnused(element.name)) + changes.delete(sourceFile, element); + } + } + } + } + } + function deleteUnusedImportsInVariableDeclaration(sourceFile, varDecl, changes, isUnused) { + var name = varDecl.name; + switch (name.kind) { + case 72 /* Identifier */: + if (isUnused(name)) { + changes.delete(sourceFile, name); + } + break; + case 185 /* ArrayBindingPattern */: + break; + case 184 /* ObjectBindingPattern */: + if (name.elements.every(function (e) { return ts.isIdentifier(e.name) && isUnused(e.name); })) { + changes.delete(sourceFile, ts.isVariableDeclarationList(varDecl.parent) && varDecl.parent.declarations.length === 1 ? varDecl.parent.parent : varDecl); + } + else { + for (var _i = 0, _a = name.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (ts.isIdentifier(element.name) && isUnused(element.name)) { + changes.delete(sourceFile, element.name); + } + } + } + break; + } + } + function getNewFileImportsAndAddExportInOldFile(oldFile, importsToCopy, newFileImportsFromOldFile, changes, checker, useEs6ModuleSyntax, quotePreference) { + var copiedOldImports = []; + for (var _i = 0, _a = oldFile.statements; _i < _a.length; _i++) { + var oldStatement = _a[_i]; + forEachImportInStatement(oldStatement, function (i) { + ts.append(copiedOldImports, filterImport(i, moduleSpecifierFromImport(i), function (name) { return importsToCopy.has(checker.getSymbolAtLocation(name)); })); + }); + } + // Also, import things used from the old file, and insert 'export' modifiers as necessary in the old file. + var oldFileDefault; + var oldFileNamedImports = []; + var markSeenTop = ts.nodeSeenTracker(); // Needed because multiple declarations may appear in `const x = 0, y = 1;`. + newFileImportsFromOldFile.forEach(function (symbol) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + if (!isTopLevelDeclaration(decl)) + continue; + var name = nameOfTopLevelDeclaration(decl); + if (!name) + continue; + var top = getTopLevelDeclarationStatement(decl); + if (markSeenTop(top)) { + addExportToChanges(oldFile, top, changes, useEs6ModuleSyntax); + } + if (ts.hasModifier(decl, 512 /* Default */)) { + oldFileDefault = name; + } + else { + oldFileNamedImports.push(name.text); + } + } + }); + ts.append(copiedOldImports, makeImportOrRequire(oldFileDefault, oldFileNamedImports, ts.removeFileExtension(ts.getBaseFileName(oldFile.fileName)), useEs6ModuleSyntax, quotePreference)); + return copiedOldImports; + } + function makeUniqueModuleName(moduleName, extension, inDirectory, host) { + var newModuleName = moduleName; + for (var i = 1;; i++) { + var name = ts.combinePaths(inDirectory, newModuleName + extension); + if (!host.fileExists(name)) + return newModuleName; // TODO: GH#18217 + newModuleName = moduleName + "." + i; + } + } + function getNewModuleName(movedSymbols) { + return movedSymbols.forEachEntry(ts.symbolNameNoDefault) || "newFile"; + } + function getUsageInfo(oldFile, toMove, checker) { + var movedSymbols = new SymbolSet(); + var oldImportsNeededByNewFile = new SymbolSet(); + var newFileImportsFromOldFile = new SymbolSet(); + for (var _i = 0, toMove_1 = toMove; _i < toMove_1.length; _i++) { + var statement = toMove_1[_i]; + forEachTopLevelDeclaration(statement, function (decl) { + movedSymbols.add(ts.Debug.assertDefined(ts.isExpressionStatement(decl) ? checker.getSymbolAtLocation(decl.expression.left) : decl.symbol)); + }); + } + for (var _a = 0, toMove_2 = toMove; _a < toMove_2.length; _a++) { + var statement = toMove_2[_a]; + forEachReference(statement, checker, function (symbol) { + if (!symbol.declarations) + return; + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + if (isInImport(decl)) { + oldImportsNeededByNewFile.add(symbol); + } + else if (isTopLevelDeclaration(decl) && sourceFileOfTopLevelDeclaration(decl) === oldFile && !movedSymbols.has(symbol)) { + newFileImportsFromOldFile.add(symbol); + } + } + }); + } + var unusedImportsFromOldFile = oldImportsNeededByNewFile.clone(); + var oldFileImportsFromNewFile = new SymbolSet(); + for (var _b = 0, _c = oldFile.statements; _b < _c.length; _b++) { + var statement = _c[_b]; + if (ts.contains(toMove, statement)) + continue; + forEachReference(statement, checker, function (symbol) { + if (movedSymbols.has(symbol)) + oldFileImportsFromNewFile.add(symbol); + unusedImportsFromOldFile.delete(symbol); + }); + } + return { movedSymbols: movedSymbols, newFileImportsFromOldFile: newFileImportsFromOldFile, oldFileImportsFromNewFile: oldFileImportsFromNewFile, oldImportsNeededByNewFile: oldImportsNeededByNewFile, unusedImportsFromOldFile: unusedImportsFromOldFile }; + } + // Below should all be utilities + function isInImport(decl) { + switch (decl.kind) { + case 248 /* ImportEqualsDeclaration */: + case 253 /* ImportSpecifier */: + case 250 /* ImportClause */: + return true; + case 237 /* VariableDeclaration */: + return isVariableDeclarationInImport(decl); + case 186 /* BindingElement */: + return ts.isVariableDeclaration(decl.parent.parent) && isVariableDeclarationInImport(decl.parent.parent); + default: + return false; + } + } + function isVariableDeclarationInImport(decl) { + return ts.isSourceFile(decl.parent.parent.parent) && + decl.initializer && ts.isRequireCall(decl.initializer, /*checkArgumentIsStringLiteralLike*/ true); + } + function filterImport(i, moduleSpecifier, keep) { + switch (i.kind) { + case 249 /* ImportDeclaration */: { + var clause = i.importClause; + if (!clause) + return undefined; + var defaultImport = clause.name && keep(clause.name) ? clause.name : undefined; + var namedBindings = clause.namedBindings && filterNamedBindings(clause.namedBindings, keep); + return defaultImport || namedBindings + ? ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createImportClause(defaultImport, namedBindings), moduleSpecifier) + : undefined; + } + case 248 /* ImportEqualsDeclaration */: + return keep(i.name) ? i : undefined; + case 237 /* VariableDeclaration */: { + var name = filterBindingName(i.name, keep); + return name ? makeVariableStatement(name, i.type, createRequireCall(moduleSpecifier), i.parent.flags) : undefined; + } + default: + return ts.Debug.assertNever(i); + } + } + function filterNamedBindings(namedBindings, keep) { + if (namedBindings.kind === 251 /* NamespaceImport */) { + return keep(namedBindings.name) ? namedBindings : undefined; + } + else { + var newElements = namedBindings.elements.filter(function (e) { return keep(e.name); }); + return newElements.length ? ts.createNamedImports(newElements) : undefined; + } + } + function filterBindingName(name, keep) { + switch (name.kind) { + case 72 /* Identifier */: + return keep(name) ? name : undefined; + case 185 /* ArrayBindingPattern */: + return name; + case 184 /* ObjectBindingPattern */: { + // We can't handle nested destructurings or property names well here, so just copy them all. + var newElements = name.elements.filter(function (prop) { return prop.propertyName || !ts.isIdentifier(prop.name) || keep(prop.name); }); + return newElements.length ? ts.createObjectBindingPattern(newElements) : undefined; + } + } + } + function forEachReference(node, checker, onReference) { + node.forEachChild(function cb(node) { + if (ts.isIdentifier(node) && !ts.isDeclarationName(node)) { + var sym = checker.getSymbolAtLocation(node); + if (sym) + onReference(sym); + } + else { + node.forEachChild(cb); + } + }); + } + var SymbolSet = /** @class */ (function () { + function SymbolSet() { + this.map = ts.createMap(); + } + SymbolSet.prototype.add = function (symbol) { + this.map.set(String(ts.getSymbolId(symbol)), symbol); + }; + SymbolSet.prototype.has = function (symbol) { + return this.map.has(String(ts.getSymbolId(symbol))); + }; + SymbolSet.prototype.delete = function (symbol) { + this.map.delete(String(ts.getSymbolId(symbol))); + }; + SymbolSet.prototype.forEach = function (cb) { + this.map.forEach(cb); + }; + SymbolSet.prototype.forEachEntry = function (cb) { + return ts.forEachEntry(this.map, cb); + }; + SymbolSet.prototype.clone = function () { + var clone = new SymbolSet(); + ts.copyEntries(this.map, clone.map); + return clone; + }; + return SymbolSet; + }()); + function isTopLevelDeclaration(node) { + return isNonVariableTopLevelDeclaration(node) && ts.isSourceFile(node.parent) || ts.isVariableDeclaration(node) && ts.isSourceFile(node.parent.parent.parent); + } + function sourceFileOfTopLevelDeclaration(node) { + return ts.isVariableDeclaration(node) ? node.parent.parent.parent : node.parent; + } + function isTopLevelDeclarationStatement(node) { + ts.Debug.assert(ts.isSourceFile(node.parent)); + return isNonVariableTopLevelDeclaration(node) || ts.isVariableStatement(node); + } + function isNonVariableTopLevelDeclaration(node) { + switch (node.kind) { + case 239 /* FunctionDeclaration */: + case 240 /* ClassDeclaration */: + case 244 /* ModuleDeclaration */: + case 243 /* EnumDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 241 /* InterfaceDeclaration */: + case 248 /* ImportEqualsDeclaration */: + return true; + default: + return false; + } + } + function forEachTopLevelDeclaration(statement, cb) { + switch (statement.kind) { + case 239 /* FunctionDeclaration */: + case 240 /* ClassDeclaration */: + case 244 /* ModuleDeclaration */: + case 243 /* EnumDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 241 /* InterfaceDeclaration */: + case 248 /* ImportEqualsDeclaration */: + return cb(statement); + case 219 /* VariableStatement */: + return ts.firstDefined(statement.declarationList.declarations, function (decl) { return forEachTopLevelDeclarationInBindingName(decl.name, cb); }); + case 221 /* ExpressionStatement */: { + var expression = statement.expression; + return ts.isBinaryExpression(expression) && ts.getAssignmentDeclarationKind(expression) === 1 /* ExportsProperty */ + ? cb(statement) + : undefined; + } + } + } + function forEachTopLevelDeclarationInBindingName(name, cb) { + switch (name.kind) { + case 72 /* Identifier */: + return cb(ts.cast(name.parent, function (x) { return ts.isVariableDeclaration(x) || ts.isBindingElement(x); })); + case 185 /* ArrayBindingPattern */: + case 184 /* ObjectBindingPattern */: + return ts.firstDefined(name.elements, function (em) { return ts.isOmittedExpression(em) ? undefined : forEachTopLevelDeclarationInBindingName(em.name, cb); }); + default: + return ts.Debug.assertNever(name); + } + } + function nameOfTopLevelDeclaration(d) { + return ts.isExpressionStatement(d) ? d.expression.left.name : ts.tryCast(d.name, ts.isIdentifier); + } + function getTopLevelDeclarationStatement(d) { + switch (d.kind) { + case 237 /* VariableDeclaration */: + return d.parent.parent; + case 186 /* BindingElement */: + return getTopLevelDeclarationStatement(ts.cast(d.parent.parent, function (p) { return ts.isVariableDeclaration(p) || ts.isBindingElement(p); })); + default: + return d; + } + } + function addExportToChanges(sourceFile, decl, changes, useEs6Exports) { + if (isExported(sourceFile, decl, useEs6Exports)) + return; + if (useEs6Exports) { + if (!ts.isExpressionStatement(decl)) + changes.insertExportModifier(sourceFile, decl); + } + else { + var names = getNamesToExportInCommonJS(decl); + if (names.length !== 0) + changes.insertNodesAfter(sourceFile, decl, names.map(createExportAssignment)); + } + } + function isExported(sourceFile, decl, useEs6Exports) { + if (useEs6Exports) { + return !ts.isExpressionStatement(decl) && ts.hasModifier(decl, 1 /* Export */); + } + else { + return getNamesToExportInCommonJS(decl).some(function (name) { return sourceFile.symbol.exports.has(ts.escapeLeadingUnderscores(name)); }); + } + } + function addExport(decl, useEs6Exports) { + return useEs6Exports ? [addEs6Export(decl)] : addCommonjsExport(decl); + } + function addEs6Export(d) { + var modifiers = ts.concatenate([ts.createModifier(85 /* ExportKeyword */)], d.modifiers); + switch (d.kind) { + case 239 /* FunctionDeclaration */: + return ts.updateFunctionDeclaration(d, d.decorators, modifiers, d.asteriskToken, d.name, d.typeParameters, d.parameters, d.type, d.body); + case 240 /* ClassDeclaration */: + return ts.updateClassDeclaration(d, d.decorators, modifiers, d.name, d.typeParameters, d.heritageClauses, d.members); + case 219 /* VariableStatement */: + return ts.updateVariableStatement(d, modifiers, d.declarationList); + case 244 /* ModuleDeclaration */: + return ts.updateModuleDeclaration(d, d.decorators, modifiers, d.name, d.body); + case 243 /* EnumDeclaration */: + return ts.updateEnumDeclaration(d, d.decorators, modifiers, d.name, d.members); + case 242 /* TypeAliasDeclaration */: + return ts.updateTypeAliasDeclaration(d, d.decorators, modifiers, d.name, d.typeParameters, d.type); + case 241 /* InterfaceDeclaration */: + return ts.updateInterfaceDeclaration(d, d.decorators, modifiers, d.name, d.typeParameters, d.heritageClauses, d.members); + case 248 /* ImportEqualsDeclaration */: + return ts.updateImportEqualsDeclaration(d, d.decorators, modifiers, d.name, d.moduleReference); + case 221 /* ExpressionStatement */: + return ts.Debug.fail(); // Shouldn't try to add 'export' keyword to `exports.x = ...` + default: + return ts.Debug.assertNever(d); + } + } + function addCommonjsExport(decl) { + return [decl].concat(getNamesToExportInCommonJS(decl).map(createExportAssignment)); + } + function getNamesToExportInCommonJS(decl) { + switch (decl.kind) { + case 239 /* FunctionDeclaration */: + case 240 /* ClassDeclaration */: + return [decl.name.text]; // TODO: GH#18217 + case 219 /* VariableStatement */: + return ts.mapDefined(decl.declarationList.declarations, function (d) { return ts.isIdentifier(d.name) ? d.name.text : undefined; }); + case 244 /* ModuleDeclaration */: + case 243 /* EnumDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 241 /* InterfaceDeclaration */: + case 248 /* ImportEqualsDeclaration */: + return ts.emptyArray; + case 221 /* ExpressionStatement */: + return ts.Debug.fail(); // Shouldn't try to add 'export' keyword to `exports.x = ...` + default: + return ts.Debug.assertNever(decl); + } + } + /** Creates `exports.x = x;` */ + function createExportAssignment(name) { + return ts.createExpressionStatement(ts.createBinary(ts.createPropertyAccess(ts.createIdentifier("exports"), ts.createIdentifier(name)), 59 /* EqualsToken */, ts.createIdentifier(name))); + } + })(refactor = ts.refactor || (ts.refactor = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var refactor; + (function (refactor) { + var addOrRemoveBracesToArrowFunction; + (function (addOrRemoveBracesToArrowFunction) { + var refactorName = "Add or remove braces in an arrow function"; + var refactorDescription = ts.Diagnostics.Add_or_remove_braces_in_an_arrow_function.message; + var addBracesActionName = "Add braces to arrow function"; + var removeBracesActionName = "Remove braces from arrow function"; + var addBracesActionDescription = ts.Diagnostics.Add_braces_to_arrow_function.message; + var removeBracesActionDescription = ts.Diagnostics.Remove_braces_from_arrow_function.message; + refactor.registerRefactor(refactorName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions }); + function getAvailableActions(context) { + var file = context.file, startPosition = context.startPosition; + var info = getConvertibleArrowFunctionAtPosition(file, startPosition); + if (!info) + return ts.emptyArray; + return [{ + name: refactorName, + description: refactorDescription, + actions: [ + info.addBraces ? + { + name: addBracesActionName, + description: addBracesActionDescription + } : { + name: removeBracesActionName, + description: removeBracesActionDescription + } + ] + }]; + } + function getEditsForAction(context, actionName) { + var file = context.file, startPosition = context.startPosition; + var info = getConvertibleArrowFunctionAtPosition(file, startPosition); + if (!info) + return undefined; + var expression = info.expression, returnStatement = info.returnStatement, func = info.func; + var body; + if (actionName === addBracesActionName) { + var returnStatement_1 = ts.createReturn(expression); + body = ts.createBlock([returnStatement_1], /* multiLine */ true); + ts.suppressLeadingAndTrailingTrivia(body); + ts.copyComments(expression, returnStatement_1, file, 3 /* MultiLineCommentTrivia */, /* hasTrailingNewLine */ true); + } + else if (actionName === removeBracesActionName && returnStatement) { + var actualExpression = expression || ts.createVoidZero(); + body = needsParentheses(actualExpression) ? ts.createParen(actualExpression) : actualExpression; + ts.suppressLeadingAndTrailingTrivia(body); + ts.copyComments(returnStatement, body, file, 3 /* MultiLineCommentTrivia */, /* hasTrailingNewLine */ false); + } + else { + ts.Debug.fail("invalid action"); + } + var edits = ts.textChanges.ChangeTracker.with(context, function (t) { return t.replaceNode(file, func.body, body); }); + return { renameFilename: undefined, renameLocation: undefined, edits: edits }; + } + function needsParentheses(expression) { + return ts.isBinaryExpression(expression) && expression.operatorToken.kind === 27 /* CommaToken */ || ts.isObjectLiteralExpression(expression); + } + function getConvertibleArrowFunctionAtPosition(file, startPosition) { + var node = ts.getTokenAtPosition(file, startPosition); + var func = ts.getContainingFunction(node); + if (!func || !ts.isArrowFunction(func) || (!ts.rangeContainsRange(func, node) || ts.rangeContainsRange(func.body, node))) + return undefined; + if (ts.isExpression(func.body)) { + return { + func: func, + addBraces: true, + expression: func.body + }; + } + else if (func.body.statements.length === 1) { + var firstStatement = ts.first(func.body.statements); + if (ts.isReturnStatement(firstStatement)) { + return { + func: func, + addBraces: false, + expression: firstStatement.expression, + returnStatement: firstStatement + }; + } + } + return undefined; + } + })(addOrRemoveBracesToArrowFunction = refactor.addOrRemoveBracesToArrowFunction || (refactor.addOrRemoveBracesToArrowFunction = {})); + })(refactor = ts.refactor || (ts.refactor = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + /** The version of the language service API */ + ts.servicesVersion = "0.8"; + function createNode(kind, pos, end, parent) { + var node = ts.isNodeKind(kind) ? new NodeObject(kind, pos, end) : + kind === 72 /* Identifier */ ? new IdentifierObject(72 /* Identifier */, pos, end) : + new TokenObject(kind, pos, end); + node.parent = parent; + node.flags = parent.flags & 12679168 /* ContextFlags */; + return node; + } + var NodeObject = /** @class */ (function () { + function NodeObject(kind, pos, end) { + this.pos = pos; + this.end = end; + this.flags = 0 /* None */; + this.transformFlags = undefined; // TODO: GH#18217 + this.parent = undefined; + this.kind = kind; + } + NodeObject.prototype.assertHasRealPosition = function (message) { + // tslint:disable-next-line:debug-assert + ts.Debug.assert(!ts.positionIsSynthesized(this.pos) && !ts.positionIsSynthesized(this.end), message || "Node must have a real position for this operation"); + }; + NodeObject.prototype.getSourceFile = function () { + return ts.getSourceFileOfNode(this); + }; + NodeObject.prototype.getStart = function (sourceFile, includeJsDocComment) { + this.assertHasRealPosition(); + return ts.getTokenPosOfNode(this, sourceFile, includeJsDocComment); + }; + NodeObject.prototype.getFullStart = function () { + this.assertHasRealPosition(); + return this.pos; + }; + NodeObject.prototype.getEnd = function () { + this.assertHasRealPosition(); + return this.end; + }; + NodeObject.prototype.getWidth = function (sourceFile) { + this.assertHasRealPosition(); + return this.getEnd() - this.getStart(sourceFile); + }; + NodeObject.prototype.getFullWidth = function () { + this.assertHasRealPosition(); + return this.end - this.pos; + }; + NodeObject.prototype.getLeadingTriviaWidth = function (sourceFile) { + this.assertHasRealPosition(); + return this.getStart(sourceFile) - this.pos; + }; + NodeObject.prototype.getFullText = function (sourceFile) { + this.assertHasRealPosition(); + return (sourceFile || this.getSourceFile()).text.substring(this.pos, this.end); + }; + NodeObject.prototype.getText = function (sourceFile) { + this.assertHasRealPosition(); + if (!sourceFile) { + sourceFile = this.getSourceFile(); + } + return sourceFile.text.substring(this.getStart(sourceFile), this.getEnd()); + }; + NodeObject.prototype.getChildCount = function (sourceFile) { + return this.getChildren(sourceFile).length; + }; + NodeObject.prototype.getChildAt = function (index, sourceFile) { + return this.getChildren(sourceFile)[index]; + }; + NodeObject.prototype.getChildren = function (sourceFile) { + this.assertHasRealPosition("Node without a real position cannot be scanned and thus has no token nodes - use forEachChild and collect the result if that's fine"); + return this._children || (this._children = createChildren(this, sourceFile)); + }; + NodeObject.prototype.getFirstToken = function (sourceFile) { + this.assertHasRealPosition(); + var children = this.getChildren(sourceFile); + if (!children.length) { + return undefined; + } + var child = ts.find(children, function (kid) { return kid.kind < 283 /* FirstJSDocNode */ || kid.kind > 305 /* LastJSDocNode */; }); + return child.kind < 148 /* FirstNode */ ? + child : + child.getFirstToken(sourceFile); + }; + NodeObject.prototype.getLastToken = function (sourceFile) { + this.assertHasRealPosition(); + var children = this.getChildren(sourceFile); + var child = ts.lastOrUndefined(children); + if (!child) { + return undefined; + } + return child.kind < 148 /* FirstNode */ ? child : child.getLastToken(sourceFile); + }; + NodeObject.prototype.forEachChild = function (cbNode, cbNodeArray) { + return ts.forEachChild(this, cbNode, cbNodeArray); + }; + return NodeObject; + }()); + function createChildren(node, sourceFile) { + if (!ts.isNodeKind(node.kind)) { + return ts.emptyArray; + } + var children = []; + if (ts.isJSDocCommentContainingNode(node)) { + /** Don't add trivia for "tokens" since this is in a comment. */ + node.forEachChild(function (child) { children.push(child); }); + return children; + } + ts.scanner.setText((sourceFile || node.getSourceFile()).text); + var pos = node.pos; + var processNode = function (child) { + addSyntheticNodes(children, pos, child.pos, node); + children.push(child); + pos = child.end; + }; + var processNodes = function (nodes) { + addSyntheticNodes(children, pos, nodes.pos, node); + children.push(createSyntaxList(nodes, node)); + pos = nodes.end; + }; + // jsDocComments need to be the first children + ts.forEach(node.jsDoc, processNode); + // For syntactic classifications, all trivia are classified together, including jsdoc comments. + // For that to work, the jsdoc comments should still be the leading trivia of the first child. + // Restoring the scanner position ensures that. + pos = node.pos; + node.forEachChild(processNode, processNodes); + addSyntheticNodes(children, pos, node.end, node); + ts.scanner.setText(undefined); + return children; + } + function addSyntheticNodes(nodes, pos, end, parent) { + ts.scanner.setTextPos(pos); + while (pos < end) { + var token = ts.scanner.scan(); + var textPos = ts.scanner.getTextPos(); + if (textPos <= end) { + if (token === 72 /* Identifier */) { + ts.Debug.fail("Did not expect " + ts.Debug.showSyntaxKind(parent) + " to have an Identifier in its trivia"); + } + nodes.push(createNode(token, pos, textPos, parent)); + } + pos = textPos; + if (token === 1 /* EndOfFileToken */) { + break; + } + } + } + function createSyntaxList(nodes, parent) { + var list = createNode(306 /* SyntaxList */, nodes.pos, nodes.end, parent); + list._children = []; + var pos = nodes.pos; + for (var _i = 0, nodes_7 = nodes; _i < nodes_7.length; _i++) { + var node = nodes_7[_i]; + addSyntheticNodes(list._children, pos, node.pos, parent); + list._children.push(node); + pos = node.end; + } + addSyntheticNodes(list._children, pos, nodes.end, parent); + return list; + } + var TokenOrIdentifierObject = /** @class */ (function () { + function TokenOrIdentifierObject(pos, end) { + // Set properties in same order as NodeObject + this.pos = pos; + this.end = end; + this.flags = 0 /* None */; + this.parent = undefined; + } + TokenOrIdentifierObject.prototype.getSourceFile = function () { + return ts.getSourceFileOfNode(this); + }; + TokenOrIdentifierObject.prototype.getStart = function (sourceFile, includeJsDocComment) { + return ts.getTokenPosOfNode(this, sourceFile, includeJsDocComment); + }; + TokenOrIdentifierObject.prototype.getFullStart = function () { + return this.pos; + }; + TokenOrIdentifierObject.prototype.getEnd = function () { + return this.end; + }; + TokenOrIdentifierObject.prototype.getWidth = function (sourceFile) { + return this.getEnd() - this.getStart(sourceFile); + }; + TokenOrIdentifierObject.prototype.getFullWidth = function () { + return this.end - this.pos; + }; + TokenOrIdentifierObject.prototype.getLeadingTriviaWidth = function (sourceFile) { + return this.getStart(sourceFile) - this.pos; + }; + TokenOrIdentifierObject.prototype.getFullText = function (sourceFile) { + return (sourceFile || this.getSourceFile()).text.substring(this.pos, this.end); + }; + TokenOrIdentifierObject.prototype.getText = function (sourceFile) { + if (!sourceFile) { + sourceFile = this.getSourceFile(); + } + return sourceFile.text.substring(this.getStart(sourceFile), this.getEnd()); + }; + TokenOrIdentifierObject.prototype.getChildCount = function () { + return 0; + }; + TokenOrIdentifierObject.prototype.getChildAt = function () { + return undefined; // TODO: GH#18217 + }; + TokenOrIdentifierObject.prototype.getChildren = function () { + return this.kind === 1 /* EndOfFileToken */ ? this.jsDoc || ts.emptyArray : ts.emptyArray; + }; + TokenOrIdentifierObject.prototype.getFirstToken = function () { + return undefined; + }; + TokenOrIdentifierObject.prototype.getLastToken = function () { + return undefined; + }; + TokenOrIdentifierObject.prototype.forEachChild = function () { + return undefined; + }; + return TokenOrIdentifierObject; + }()); + var SymbolObject = /** @class */ (function () { + function SymbolObject(flags, name) { + this.flags = flags; + this.escapedName = name; + } + SymbolObject.prototype.getFlags = function () { + return this.flags; + }; + Object.defineProperty(SymbolObject.prototype, "name", { + get: function () { + return ts.symbolName(this); + }, + enumerable: true, + configurable: true + }); + SymbolObject.prototype.getEscapedName = function () { + return this.escapedName; + }; + SymbolObject.prototype.getName = function () { + return this.name; + }; + SymbolObject.prototype.getDeclarations = function () { + return this.declarations; + }; + SymbolObject.prototype.getDocumentationComment = function (checker) { + if (!this.documentationComment) { + this.documentationComment = ts.emptyArray; // Set temporarily to avoid an infinite loop finding inherited docs + this.documentationComment = getDocumentationComment(this.declarations, checker); + } + return this.documentationComment; + }; + SymbolObject.prototype.getJsDocTags = function () { + if (this.tags === undefined) { + this.tags = ts.JsDoc.getJsDocTagsFromDeclarations(this.declarations); + } + return this.tags; + }; + return SymbolObject; + }()); + var TokenObject = /** @class */ (function (_super) { + __extends(TokenObject, _super); + function TokenObject(kind, pos, end) { + var _this = _super.call(this, pos, end) || this; + _this.kind = kind; + return _this; + } + return TokenObject; + }(TokenOrIdentifierObject)); + var IdentifierObject = /** @class */ (function (_super) { + __extends(IdentifierObject, _super); + function IdentifierObject(_kind, pos, end) { + return _super.call(this, pos, end) || this; + } + Object.defineProperty(IdentifierObject.prototype, "text", { + get: function () { + return ts.idText(this); + }, + enumerable: true, + configurable: true + }); + return IdentifierObject; + }(TokenOrIdentifierObject)); + IdentifierObject.prototype.kind = 72 /* Identifier */; + var TypeObject = /** @class */ (function () { + function TypeObject(checker, flags) { + this.checker = checker; + this.flags = flags; + } + TypeObject.prototype.getFlags = function () { + return this.flags; + }; + TypeObject.prototype.getSymbol = function () { + return this.symbol; + }; + TypeObject.prototype.getProperties = function () { + return this.checker.getPropertiesOfType(this); + }; + TypeObject.prototype.getProperty = function (propertyName) { + return this.checker.getPropertyOfType(this, propertyName); + }; + TypeObject.prototype.getApparentProperties = function () { + return this.checker.getAugmentedPropertiesOfType(this); + }; + TypeObject.prototype.getCallSignatures = function () { + return this.checker.getSignaturesOfType(this, 0 /* Call */); + }; + TypeObject.prototype.getConstructSignatures = function () { + return this.checker.getSignaturesOfType(this, 1 /* Construct */); + }; + TypeObject.prototype.getStringIndexType = function () { + return this.checker.getIndexTypeOfType(this, 0 /* String */); + }; + TypeObject.prototype.getNumberIndexType = function () { + return this.checker.getIndexTypeOfType(this, 1 /* Number */); + }; + TypeObject.prototype.getBaseTypes = function () { + return this.isClassOrInterface() ? this.checker.getBaseTypes(this) : undefined; + }; + TypeObject.prototype.getNonNullableType = function () { + return this.checker.getNonNullableType(this); + }; + TypeObject.prototype.getConstraint = function () { + return this.checker.getBaseConstraintOfType(this); + }; + TypeObject.prototype.getDefault = function () { + return this.checker.getDefaultFromTypeParameter(this); + }; + TypeObject.prototype.isUnion = function () { + return !!(this.flags & 1048576 /* Union */); + }; + TypeObject.prototype.isIntersection = function () { + return !!(this.flags & 2097152 /* Intersection */); + }; + TypeObject.prototype.isUnionOrIntersection = function () { + return !!(this.flags & 3145728 /* UnionOrIntersection */); + }; + TypeObject.prototype.isLiteral = function () { + return !!(this.flags & 384 /* StringOrNumberLiteral */); + }; + TypeObject.prototype.isStringLiteral = function () { + return !!(this.flags & 128 /* StringLiteral */); + }; + TypeObject.prototype.isNumberLiteral = function () { + return !!(this.flags & 256 /* NumberLiteral */); + }; + TypeObject.prototype.isTypeParameter = function () { + return !!(this.flags & 262144 /* TypeParameter */); + }; + TypeObject.prototype.isClassOrInterface = function () { + return !!(ts.getObjectFlags(this) & 3 /* ClassOrInterface */); + }; + TypeObject.prototype.isClass = function () { + return !!(ts.getObjectFlags(this) & 1 /* Class */); + }; + return TypeObject; + }()); + var SignatureObject = /** @class */ (function () { + function SignatureObject(checker) { + this.checker = checker; + } + SignatureObject.prototype.getDeclaration = function () { + return this.declaration; + }; + SignatureObject.prototype.getTypeParameters = function () { + return this.typeParameters; + }; + SignatureObject.prototype.getParameters = function () { + return this.parameters; + }; + SignatureObject.prototype.getReturnType = function () { + return this.checker.getReturnTypeOfSignature(this); + }; + SignatureObject.prototype.getDocumentationComment = function () { + return this.documentationComment || (this.documentationComment = getDocumentationComment(ts.singleElementArray(this.declaration), this.checker)); + }; + SignatureObject.prototype.getJsDocTags = function () { + if (this.jsDocTags === undefined) { + this.jsDocTags = this.declaration ? ts.JsDoc.getJsDocTagsFromDeclarations([this.declaration]) : []; + } + return this.jsDocTags; + }; + return SignatureObject; + }()); + /** + * Returns whether or not the given node has a JSDoc "inheritDoc" tag on it. + * @param node the Node in question. + * @returns `true` if `node` has a JSDoc "inheritDoc" tag on it, otherwise `false`. + */ + function hasJSDocInheritDocTag(node) { + return ts.getJSDocTags(node).some(function (tag) { return tag.tagName.text === "inheritDoc"; }); + } + function getDocumentationComment(declarations, checker) { + if (!declarations) + return ts.emptyArray; + var doc = ts.JsDoc.getJsDocCommentsFromDeclarations(declarations); + if (doc.length === 0 || declarations.some(hasJSDocInheritDocTag)) { + for (var _i = 0, declarations_14 = declarations; _i < declarations_14.length; _i++) { + var declaration = declarations_14[_i]; + var inheritedDocs = findInheritedJSDocComments(declaration, declaration.symbol.name, checker); // TODO: GH#18217 + // TODO: GH#16312 Return a ReadonlyArray, avoid copying inheritedDocs + if (inheritedDocs) + doc = doc.length === 0 ? inheritedDocs.slice() : inheritedDocs.concat(ts.lineBreakPart(), doc); + } + } + return doc; + } + /** + * Attempts to find JSDoc comments for possibly-inherited properties. Checks superclasses then traverses + * implemented interfaces until a symbol is found with the same name and with documentation. + * @param declaration The possibly-inherited declaration to find comments for. + * @param propertyName The name of the possibly-inherited property. + * @param typeChecker A TypeChecker, used to find inherited properties. + * @returns A filled array of documentation comments if any were found, otherwise an empty array. + */ + function findInheritedJSDocComments(declaration, propertyName, typeChecker) { + return ts.firstDefined(declaration.parent ? ts.getAllSuperTypeNodes(declaration.parent) : ts.emptyArray, function (superTypeNode) { + var superType = typeChecker.getTypeAtLocation(superTypeNode); + var baseProperty = superType && typeChecker.getPropertyOfType(superType, propertyName); + var inheritedDocs = baseProperty && baseProperty.getDocumentationComment(typeChecker); + return inheritedDocs && inheritedDocs.length ? inheritedDocs : undefined; + }); + } + var SourceFileObject = /** @class */ (function (_super) { + __extends(SourceFileObject, _super); + function SourceFileObject(kind, pos, end) { + return _super.call(this, kind, pos, end) || this; + } + SourceFileObject.prototype.update = function (newText, textChangeRange) { + return ts.updateSourceFile(this, newText, textChangeRange); + }; + SourceFileObject.prototype.getLineAndCharacterOfPosition = function (position) { + return ts.getLineAndCharacterOfPosition(this, position); + }; + SourceFileObject.prototype.getLineStarts = function () { + return ts.getLineStarts(this); + }; + SourceFileObject.prototype.getPositionOfLineAndCharacter = function (line, character) { + return ts.getPositionOfLineAndCharacter(this, line, character); + }; + SourceFileObject.prototype.getLineEndOfPosition = function (pos) { + var line = this.getLineAndCharacterOfPosition(pos).line; + var lineStarts = this.getLineStarts(); + var lastCharPos; + if (line + 1 >= lineStarts.length) { + lastCharPos = this.getEnd(); + } + if (!lastCharPos) { + lastCharPos = lineStarts[line + 1] - 1; + } + var fullText = this.getFullText(); + // if the new line is "\r\n", we should return the last non-new-line-character position + return fullText[lastCharPos] === "\n" && fullText[lastCharPos - 1] === "\r" ? lastCharPos - 1 : lastCharPos; + }; + SourceFileObject.prototype.getNamedDeclarations = function () { + if (!this.namedDeclarations) { + this.namedDeclarations = this.computeNamedDeclarations(); + } + return this.namedDeclarations; + }; + SourceFileObject.prototype.computeNamedDeclarations = function () { + var result = ts.createMultiMap(); + this.forEachChild(visit); + return result; + function addDeclaration(declaration) { + var name = getDeclarationName(declaration); + if (name) { + result.add(name, declaration); + } + } + function getDeclarations(name) { + var declarations = result.get(name); + if (!declarations) { + result.set(name, declarations = []); + } + return declarations; + } + function getDeclarationName(declaration) { + var name = ts.getNonAssignedNameOfDeclaration(declaration); + return name && (ts.isComputedPropertyName(name) && ts.isPropertyAccessExpression(name.expression) ? name.expression.name.text + : ts.isPropertyName(name) ? ts.getNameFromPropertyName(name) : undefined); + } + function visit(node) { + switch (node.kind) { + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + var functionDeclaration = node; + var declarationName = getDeclarationName(functionDeclaration); + if (declarationName) { + var declarations = getDeclarations(declarationName); + var lastDeclaration = ts.lastOrUndefined(declarations); + // Check whether this declaration belongs to an "overload group". + if (lastDeclaration && functionDeclaration.parent === lastDeclaration.parent && functionDeclaration.symbol === lastDeclaration.symbol) { + // Overwrite the last declaration if it was an overload + // and this one is an implementation. + if (functionDeclaration.body && !lastDeclaration.body) { + declarations[declarations.length - 1] = functionDeclaration; + } + } + else { + declarations.push(functionDeclaration); + } + } + ts.forEachChild(node, visit); + break; + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 241 /* InterfaceDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 243 /* EnumDeclaration */: + case 244 /* ModuleDeclaration */: + case 248 /* ImportEqualsDeclaration */: + case 257 /* ExportSpecifier */: + case 253 /* ImportSpecifier */: + case 250 /* ImportClause */: + case 251 /* NamespaceImport */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 168 /* TypeLiteral */: + addDeclaration(node); + ts.forEachChild(node, visit); + break; + case 151 /* Parameter */: + // Only consider parameter properties + if (!ts.hasModifier(node, 92 /* ParameterPropertyModifier */)) { + break; + } + // falls through + case 237 /* VariableDeclaration */: + case 186 /* BindingElement */: { + var decl = node; + if (ts.isBindingPattern(decl.name)) { + ts.forEachChild(decl.name, visit); + break; + } + if (decl.initializer) { + visit(decl.initializer); + } + } + // falls through + case 278 /* EnumMember */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + addDeclaration(node); + break; + case 255 /* ExportDeclaration */: + // Handle named exports case e.g.: + // export {a, b as B} from "mod"; + if (node.exportClause) { + ts.forEach(node.exportClause.elements, visit); + } + break; + case 249 /* ImportDeclaration */: + var importClause = node.importClause; + if (importClause) { + // Handle default import case e.g.: + // import d from "mod"; + if (importClause.name) { + addDeclaration(importClause.name); + } + // Handle named bindings in imports e.g.: + // import * as NS from "mod"; + // import {a, b as B} from "mod"; + if (importClause.namedBindings) { + if (importClause.namedBindings.kind === 251 /* NamespaceImport */) { + addDeclaration(importClause.namedBindings); + } + else { + ts.forEach(importClause.namedBindings.elements, visit); + } + } + } + break; + case 204 /* BinaryExpression */: + if (ts.getAssignmentDeclarationKind(node) !== 0 /* None */) { + addDeclaration(node); + } + // falls through + default: + ts.forEachChild(node, visit); + } + } + }; + return SourceFileObject; + }(NodeObject)); + var SourceMapSourceObject = /** @class */ (function () { + function SourceMapSourceObject(fileName, text, skipTrivia) { + this.fileName = fileName; + this.text = text; + this.skipTrivia = skipTrivia; + } + SourceMapSourceObject.prototype.getLineAndCharacterOfPosition = function (pos) { + return ts.getLineAndCharacterOfPosition(this, pos); + }; + return SourceMapSourceObject; + }()); + function getServicesObjectAllocator() { + return { + getNodeConstructor: function () { return NodeObject; }, + getTokenConstructor: function () { return TokenObject; }, + getIdentifierConstructor: function () { return IdentifierObject; }, + getSourceFileConstructor: function () { return SourceFileObject; }, + getSymbolConstructor: function () { return SymbolObject; }, + getTypeConstructor: function () { return TypeObject; }, + getSignatureConstructor: function () { return SignatureObject; }, + getSourceMapSourceConstructor: function () { return SourceMapSourceObject; }, + }; + } + function toEditorSettings(optionsAsMap) { + var allPropertiesAreCamelCased = true; + for (var key in optionsAsMap) { + if (ts.hasProperty(optionsAsMap, key) && !isCamelCase(key)) { + allPropertiesAreCamelCased = false; + break; + } + } + if (allPropertiesAreCamelCased) { + return optionsAsMap; + } + var settings = {}; + for (var key in optionsAsMap) { + if (ts.hasProperty(optionsAsMap, key)) { + var newKey = isCamelCase(key) ? key : key.charAt(0).toLowerCase() + key.substr(1); + settings[newKey] = optionsAsMap[key]; + } + } + return settings; + } + ts.toEditorSettings = toEditorSettings; + function isCamelCase(s) { + return !s.length || s.charAt(0) === s.charAt(0).toLowerCase(); + } + function displayPartsToString(displayParts) { + if (displayParts) { + return ts.map(displayParts, function (displayPart) { return displayPart.text; }).join(""); + } + return ""; + } + ts.displayPartsToString = displayPartsToString; + function getDefaultCompilerOptions() { + // Always default to "ScriptTarget.ES5" for the language service + return { + target: 1 /* ES5 */, + jsx: 1 /* Preserve */ + }; + } + ts.getDefaultCompilerOptions = getDefaultCompilerOptions; + function getSupportedCodeFixes() { + return ts.codefix.getSupportedErrorCodes(); + } + ts.getSupportedCodeFixes = getSupportedCodeFixes; + // Cache host information about script Should be refreshed + // at each language service public entry point, since we don't know when + // the set of scripts handled by the host changes. + var HostCache = /** @class */ (function () { + function HostCache(host, getCanonicalFileName) { + this.host = host; + // script id => script index + this.currentDirectory = host.getCurrentDirectory(); + this.fileNameToEntry = ts.createMap(); + // Initialize the list with the root file names + var rootFileNames = host.getScriptFileNames(); + for (var _i = 0, rootFileNames_1 = rootFileNames; _i < rootFileNames_1.length; _i++) { + var fileName = rootFileNames_1[_i]; + this.createEntry(fileName, ts.toPath(fileName, this.currentDirectory, getCanonicalFileName)); + } + // store the compilation settings + this._compilationSettings = host.getCompilationSettings() || getDefaultCompilerOptions(); + } + HostCache.prototype.compilationSettings = function () { + return this._compilationSettings; + }; + HostCache.prototype.getProjectReferences = function () { + return this.host.getProjectReferences && this.host.getProjectReferences(); + }; + HostCache.prototype.createEntry = function (fileName, path) { + var entry; + var scriptSnapshot = this.host.getScriptSnapshot(fileName); + if (scriptSnapshot) { + entry = { + hostFileName: fileName, + version: this.host.getScriptVersion(fileName), + scriptSnapshot: scriptSnapshot, + scriptKind: ts.getScriptKind(fileName, this.host) + }; + } + else { + entry = fileName; + } + this.fileNameToEntry.set(path, entry); + return entry; + }; + HostCache.prototype.getEntryByPath = function (path) { + return this.fileNameToEntry.get(path); + }; + HostCache.prototype.getHostFileInformation = function (path) { + var entry = this.fileNameToEntry.get(path); + return !ts.isString(entry) ? entry : undefined; + }; + HostCache.prototype.getOrCreateEntryByPath = function (fileName, path) { + var info = this.getEntryByPath(path) || this.createEntry(fileName, path); + return ts.isString(info) ? undefined : info; // TODO: GH#18217 + }; + HostCache.prototype.getRootFileNames = function () { + var names = []; + this.fileNameToEntry.forEach(function (entry) { + if (ts.isString(entry)) { + names.push(entry); + } + else { + if (entry.scriptKind !== 6 /* JSON */) { + names.push(entry.hostFileName); + } + } + }); + return names; + }; + HostCache.prototype.getVersion = function (path) { + var file = this.getHostFileInformation(path); + return (file && file.version); // TODO: GH#18217 + }; + HostCache.prototype.getScriptSnapshot = function (path) { + var file = this.getHostFileInformation(path); + return (file && file.scriptSnapshot); // TODO: GH#18217 + }; + return HostCache; + }()); + var SyntaxTreeCache = /** @class */ (function () { + function SyntaxTreeCache(host) { + this.host = host; + } + SyntaxTreeCache.prototype.getCurrentSourceFile = function (fileName) { + var scriptSnapshot = this.host.getScriptSnapshot(fileName); + if (!scriptSnapshot) { + // The host does not know about this file. + throw new Error("Could not find file: '" + fileName + "'."); + } + var scriptKind = ts.getScriptKind(fileName, this.host); + var version = this.host.getScriptVersion(fileName); + var sourceFile; + if (this.currentFileName !== fileName) { + // This is a new file, just parse it + sourceFile = createLanguageServiceSourceFile(fileName, scriptSnapshot, 6 /* Latest */, version, /*setNodeParents*/ true, scriptKind); + } + else if (this.currentFileVersion !== version) { + // This is the same file, just a newer version. Incrementally parse the file. + var editRange = scriptSnapshot.getChangeRange(this.currentFileScriptSnapshot); + sourceFile = updateLanguageServiceSourceFile(this.currentSourceFile, scriptSnapshot, version, editRange); + } + if (sourceFile) { + // All done, ensure state is up to date + this.currentFileVersion = version; + this.currentFileName = fileName; + this.currentFileScriptSnapshot = scriptSnapshot; + this.currentSourceFile = sourceFile; + } + return this.currentSourceFile; + }; + return SyntaxTreeCache; + }()); + function setSourceFileFields(sourceFile, scriptSnapshot, version) { + sourceFile.version = version; + sourceFile.scriptSnapshot = scriptSnapshot; + } + function createLanguageServiceSourceFile(fileName, scriptSnapshot, scriptTarget, version, setNodeParents, scriptKind) { + var sourceFile = ts.createSourceFile(fileName, ts.getSnapshotText(scriptSnapshot), scriptTarget, setNodeParents, scriptKind); + setSourceFileFields(sourceFile, scriptSnapshot, version); + return sourceFile; + } + ts.createLanguageServiceSourceFile = createLanguageServiceSourceFile; + ts.disableIncrementalParsing = false; + function updateLanguageServiceSourceFile(sourceFile, scriptSnapshot, version, textChangeRange, aggressiveChecks) { + // If we were given a text change range, and our version or open-ness changed, then + // incrementally parse this file. + if (textChangeRange) { + if (version !== sourceFile.version) { + // Once incremental parsing is ready, then just call into this function. + if (!ts.disableIncrementalParsing) { + var newText = void 0; + // grab the fragment from the beginning of the original text to the beginning of the span + var prefix = textChangeRange.span.start !== 0 + ? sourceFile.text.substr(0, textChangeRange.span.start) + : ""; + // grab the fragment from the end of the span till the end of the original text + var suffix = ts.textSpanEnd(textChangeRange.span) !== sourceFile.text.length + ? sourceFile.text.substr(ts.textSpanEnd(textChangeRange.span)) + : ""; + if (textChangeRange.newLength === 0) { + // edit was a deletion - just combine prefix and suffix + newText = prefix && suffix ? prefix + suffix : prefix || suffix; + } + else { + // it was actual edit, fetch the fragment of new text that correspond to new span + var changedText = scriptSnapshot.getText(textChangeRange.span.start, textChangeRange.span.start + textChangeRange.newLength); + // combine prefix, changed text and suffix + newText = prefix && suffix + ? prefix + changedText + suffix + : prefix + ? (prefix + changedText) + : (changedText + suffix); + } + var newSourceFile = ts.updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks); + setSourceFileFields(newSourceFile, scriptSnapshot, version); + // after incremental parsing nameTable might not be up-to-date + // drop it so it can be lazily recreated later + newSourceFile.nameTable = undefined; + // dispose all resources held by old script snapshot + if (sourceFile !== newSourceFile && sourceFile.scriptSnapshot) { + if (sourceFile.scriptSnapshot.dispose) { + sourceFile.scriptSnapshot.dispose(); + } + sourceFile.scriptSnapshot = undefined; + } + return newSourceFile; + } + } + } + // Otherwise, just create a new source file. + return createLanguageServiceSourceFile(sourceFile.fileName, scriptSnapshot, sourceFile.languageVersion, version, /*setNodeParents*/ true, sourceFile.scriptKind); + } + ts.updateLanguageServiceSourceFile = updateLanguageServiceSourceFile; + var CancellationTokenObject = /** @class */ (function () { + function CancellationTokenObject(cancellationToken) { + this.cancellationToken = cancellationToken; + } + CancellationTokenObject.prototype.isCancellationRequested = function () { + return !!this.cancellationToken && this.cancellationToken.isCancellationRequested(); + }; + CancellationTokenObject.prototype.throwIfCancellationRequested = function () { + if (this.isCancellationRequested()) { + throw new ts.OperationCanceledException(); + } + }; + return CancellationTokenObject; + }()); + /* @internal */ + /** A cancellation that throttles calls to the host */ + var ThrottledCancellationToken = /** @class */ (function () { + function ThrottledCancellationToken(hostCancellationToken, throttleWaitMilliseconds) { + if (throttleWaitMilliseconds === void 0) { throttleWaitMilliseconds = 20; } + this.hostCancellationToken = hostCancellationToken; + this.throttleWaitMilliseconds = throttleWaitMilliseconds; + // Store when we last tried to cancel. Checking cancellation can be expensive (as we have + // to marshall over to the host layer). So we only bother actually checking once enough + // time has passed. + this.lastCancellationCheckTime = 0; + } + ThrottledCancellationToken.prototype.isCancellationRequested = function () { + var time = ts.timestamp(); + var duration = Math.abs(time - this.lastCancellationCheckTime); + if (duration >= this.throttleWaitMilliseconds) { + // Check no more than once every throttle wait milliseconds + this.lastCancellationCheckTime = time; + return this.hostCancellationToken.isCancellationRequested(); + } + return false; + }; + ThrottledCancellationToken.prototype.throwIfCancellationRequested = function () { + if (this.isCancellationRequested()) { + throw new ts.OperationCanceledException(); + } + }; + return ThrottledCancellationToken; + }()); + ts.ThrottledCancellationToken = ThrottledCancellationToken; + function createLanguageService(host, documentRegistry, syntaxOnly) { + if (documentRegistry === void 0) { documentRegistry = ts.createDocumentRegistry(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames(), host.getCurrentDirectory()); } + if (syntaxOnly === void 0) { syntaxOnly = false; } + var _a; + var syntaxTreeCache = new SyntaxTreeCache(host); + var program; + var lastProjectVersion; + var lastTypesRootVersion = 0; + var cancellationToken = new CancellationTokenObject(host.getCancellationToken && host.getCancellationToken()); + var currentDirectory = host.getCurrentDirectory(); + // Check if the localized messages json is set, otherwise query the host for it + if (!ts.localizedDiagnosticMessages && host.getLocalizedDiagnosticMessages) { + ts.localizedDiagnosticMessages = host.getLocalizedDiagnosticMessages(); + } + function log(message) { + if (host.log) { + host.log(message); + } + } + var useCaseSensitiveFileNames = ts.hostUsesCaseSensitiveFileNames(host); + var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); + var sourceMapper = ts.getSourceMapper(useCaseSensitiveFileNames, currentDirectory, log, host, function () { return program; }); + function getValidSourceFile(fileName) { + var sourceFile = program.getSourceFile(fileName); + if (!sourceFile) { + throw new Error("Could not find file: '" + fileName + "'."); + } + return sourceFile; + } + function synchronizeHostData() { + ts.Debug.assert(!syntaxOnly); + // perform fast check if host supports it + if (host.getProjectVersion) { + var hostProjectVersion = host.getProjectVersion(); + if (hostProjectVersion) { + if (lastProjectVersion === hostProjectVersion && !host.hasChangedAutomaticTypeDirectiveNames) { + return; + } + lastProjectVersion = hostProjectVersion; + } + } + var typeRootsVersion = host.getTypeRootsVersion ? host.getTypeRootsVersion() : 0; + if (lastTypesRootVersion !== typeRootsVersion) { + log("TypeRoots version has changed; provide new program"); + program = undefined; // TODO: GH#18217 + lastTypesRootVersion = typeRootsVersion; + } + // Get a fresh cache of the host information + var hostCache = new HostCache(host, getCanonicalFileName); + var rootFileNames = hostCache.getRootFileNames(); + var hasInvalidatedResolution = host.hasInvalidatedResolution || ts.returnFalse; + var projectReferences = hostCache.getProjectReferences(); + // If the program is already up-to-date, we can reuse it + if (ts.isProgramUptoDate(program, rootFileNames, hostCache.compilationSettings(), function (path) { return hostCache.getVersion(path); }, fileExists, hasInvalidatedResolution, !!host.hasChangedAutomaticTypeDirectiveNames, projectReferences)) { + return; + } + // IMPORTANT - It is critical from this moment onward that we do not check + // cancellation tokens. We are about to mutate source files from a previous program + // instance. If we cancel midway through, we may end up in an inconsistent state where + // the program points to old source files that have been invalidated because of + // incremental parsing. + var newSettings = hostCache.compilationSettings(); + // Now create a new compiler + var compilerHost = { + getSourceFile: getOrCreateSourceFile, + getSourceFileByPath: getOrCreateSourceFileByPath, + getCancellationToken: function () { return cancellationToken; }, + getCanonicalFileName: getCanonicalFileName, + useCaseSensitiveFileNames: function () { return useCaseSensitiveFileNames; }, + getNewLine: function () { return ts.getNewLineCharacter(newSettings, function () { return ts.getNewLineOrDefaultFromHost(host); }); }, + getDefaultLibFileName: function (options) { return host.getDefaultLibFileName(options); }, + writeFile: ts.noop, + getCurrentDirectory: function () { return currentDirectory; }, + fileExists: fileExists, + readFile: function (fileName) { + // stub missing host functionality + var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); + var entry = hostCache && hostCache.getEntryByPath(path); + if (entry) { + return ts.isString(entry) ? undefined : ts.getSnapshotText(entry.scriptSnapshot); + } + return host.readFile && host.readFile(fileName); + }, + realpath: host.realpath && (function (path) { return host.realpath(path); }), + directoryExists: function (directoryName) { + return ts.directoryProbablyExists(directoryName, host); + }, + getDirectories: function (path) { + return host.getDirectories ? host.getDirectories(path) : []; + }, + readDirectory: function (path, extensions, exclude, include, depth) { + ts.Debug.assertDefined(host.readDirectory, "'LanguageServiceHost.readDirectory' must be implemented to correctly process 'projectReferences'"); + return host.readDirectory(path, extensions, exclude, include, depth); + }, + onReleaseOldSourceFile: onReleaseOldSourceFile, + hasInvalidatedResolution: hasInvalidatedResolution, + hasChangedAutomaticTypeDirectiveNames: host.hasChangedAutomaticTypeDirectiveNames + }; + if (host.trace) { + compilerHost.trace = function (message) { return host.trace(message); }; + } + if (host.resolveModuleNames) { + compilerHost.resolveModuleNames = function (moduleNames, containingFile, reusedNames, redirectedReference) { return host.resolveModuleNames(moduleNames, containingFile, reusedNames, redirectedReference); }; + } + if (host.resolveTypeReferenceDirectives) { + compilerHost.resolveTypeReferenceDirectives = function (typeReferenceDirectiveNames, containingFile, redirectedReference) { + return host.resolveTypeReferenceDirectives(typeReferenceDirectiveNames, containingFile, redirectedReference); + }; + } + var documentRegistryBucketKey = documentRegistry.getKeyForCompilationSettings(newSettings); + var options = { + rootNames: rootFileNames, + options: newSettings, + host: compilerHost, + oldProgram: program, + projectReferences: projectReferences + }; + program = ts.createProgram(options); + // hostCache is captured in the closure for 'getOrCreateSourceFile' but it should not be used past this point. + // It needs to be cleared to allow all collected snapshots to be released + hostCache = undefined; + // We reset this cache on structure invalidation so we don't hold on to outdated files for long; however we can't use the `compilerHost` above, + // Because it only functions until `hostCache` is cleared, while we'll potentially need the functionality to lazily read sourcemap files during + // the course of whatever called `synchronizeHostData` + sourceMapper.clearCache(); + // Make sure all the nodes in the program are both bound, and have their parent + // pointers set property. + program.getTypeChecker(); + return; + function fileExists(fileName) { + var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); + var entry = hostCache && hostCache.getEntryByPath(path); + return entry ? + !ts.isString(entry) : + (!!host.fileExists && host.fileExists(fileName)); + } + // Release any files we have acquired in the old program but are + // not part of the new program. + function onReleaseOldSourceFile(oldSourceFile, oldOptions) { + var oldSettingsKey = documentRegistry.getKeyForCompilationSettings(oldOptions); + documentRegistry.releaseDocumentWithKey(oldSourceFile.resolvedPath, oldSettingsKey); + } + function getOrCreateSourceFile(fileName, languageVersion, onError, shouldCreateNewSourceFile) { + return getOrCreateSourceFileByPath(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), languageVersion, onError, shouldCreateNewSourceFile); + } + function getOrCreateSourceFileByPath(fileName, path, _languageVersion, _onError, shouldCreateNewSourceFile) { + ts.Debug.assert(hostCache !== undefined, "getOrCreateSourceFileByPath called after typical CompilerHost lifetime, check the callstack something with a reference to an old host."); + // The program is asking for this file, check first if the host can locate it. + // If the host can not locate the file, then it does not exist. return undefined + // to the program to allow reporting of errors for missing files. + var hostFileInformation = hostCache && hostCache.getOrCreateEntryByPath(fileName, path); + if (!hostFileInformation) { + return undefined; + } + // Check if the language version has changed since we last created a program; if they are the same, + // it is safe to reuse the sourceFiles; if not, then the shape of the AST can change, and the oldSourceFile + // can not be reused. we have to dump all syntax trees and create new ones. + if (!shouldCreateNewSourceFile) { + // Check if the old program had this file already + var oldSourceFile = program && program.getSourceFileByPath(path); + if (oldSourceFile) { + // We already had a source file for this file name. Go to the registry to + // ensure that we get the right up to date version of it. We need this to + // address the following race-condition. Specifically, say we have the following: + // + // LS1 + // \ + // DocumentRegistry + // / + // LS2 + // + // Each LS has a reference to file 'foo.ts' at version 1. LS2 then updates + // it's version of 'foo.ts' to version 2. This will cause LS2 and the + // DocumentRegistry to have version 2 of the document. HOwever, LS1 will + // have version 1. And *importantly* this source file will be *corrupt*. + // The act of creating version 2 of the file irrevocably damages the version + // 1 file. + // + // So, later when we call into LS1, we need to make sure that it doesn't use + // it's source file any more, and instead defers to DocumentRegistry to get + // either version 1, version 2 (or some other version) depending on what the + // host says should be used. + // We do not support the scenario where a host can modify a registered + // file's script kind, i.e. in one project some file is treated as ".ts" + // and in another as ".js" + ts.Debug.assertEqual(hostFileInformation.scriptKind, oldSourceFile.scriptKind, "Registered script kind should match new script kind.", path); + return documentRegistry.updateDocumentWithKey(fileName, path, newSettings, documentRegistryBucketKey, hostFileInformation.scriptSnapshot, hostFileInformation.version, hostFileInformation.scriptKind); + } + // We didn't already have the file. Fall through and acquire it from the registry. + } + // Could not find this file in the old program, create a new SourceFile for it. + return documentRegistry.acquireDocumentWithKey(fileName, path, newSettings, documentRegistryBucketKey, hostFileInformation.scriptSnapshot, hostFileInformation.version, hostFileInformation.scriptKind); + } + } + // TODO: GH#18217 frequently asserted as defined + function getProgram() { + if (syntaxOnly) { + ts.Debug.assert(program === undefined); + return undefined; + } + synchronizeHostData(); + return program; + } + function cleanupSemanticCache() { + program = undefined; // TODO: GH#18217 + } + function dispose() { + if (program) { + ts.forEach(program.getSourceFiles(), function (f) { + return documentRegistry.releaseDocument(f.fileName, program.getCompilerOptions()); + }); + program = undefined; // TODO: GH#18217 + } + host = undefined; + } + /// Diagnostics + function getSyntacticDiagnostics(fileName) { + synchronizeHostData(); + return program.getSyntacticDiagnostics(getValidSourceFile(fileName), cancellationToken).slice(); + } + /** + * getSemanticDiagnostics return array of Diagnostics. If '-d' is not enabled, only report semantic errors + * If '-d' enabled, report both semantic and emitter errors + */ + function getSemanticDiagnostics(fileName) { + synchronizeHostData(); + var targetSourceFile = getValidSourceFile(fileName); + // Only perform the action per file regardless of '-out' flag as LanguageServiceHost is expected to call this function per file. + // Therefore only get diagnostics for given file. + var semanticDiagnostics = program.getSemanticDiagnostics(targetSourceFile, cancellationToken); + if (!ts.getEmitDeclarations(program.getCompilerOptions())) { + return semanticDiagnostics.slice(); + } + // If '-d' is enabled, check for emitter error. One example of emitter error is export class implements non-export interface + var declarationDiagnostics = program.getDeclarationDiagnostics(targetSourceFile, cancellationToken); + return semanticDiagnostics.concat(declarationDiagnostics); + } + function getSuggestionDiagnostics(fileName) { + synchronizeHostData(); + return ts.computeSuggestionDiagnostics(getValidSourceFile(fileName), program, cancellationToken); + } + function getCompilerOptionsDiagnostics() { + synchronizeHostData(); + return program.getOptionsDiagnostics(cancellationToken).concat(program.getGlobalDiagnostics(cancellationToken)); + } + function getCompletionsAtPosition(fileName, position, options) { + if (options === void 0) { options = ts.emptyOptions; } + // Convert from deprecated options names to new names + var fullPreferences = __assign({}, ts.identity(options), { includeCompletionsForModuleExports: options.includeCompletionsForModuleExports || options.includeExternalModuleExports, includeCompletionsWithInsertText: options.includeCompletionsWithInsertText || options.includeInsertTextCompletions }); + synchronizeHostData(); + return ts.Completions.getCompletionsAtPosition(host, program, log, getValidSourceFile(fileName), position, fullPreferences, options.triggerCharacter); + } + function getCompletionEntryDetails(fileName, position, name, formattingOptions, source, preferences) { + if (preferences === void 0) { preferences = ts.emptyOptions; } + synchronizeHostData(); + return ts.Completions.getCompletionEntryDetails(program, log, getValidSourceFile(fileName), position, { name: name, source: source }, host, (formattingOptions && ts.formatting.getFormatContext(formattingOptions)), // TODO: GH#18217 + preferences, cancellationToken); + } + function getCompletionEntrySymbol(fileName, position, name, source) { + synchronizeHostData(); + return ts.Completions.getCompletionEntrySymbol(program, log, getValidSourceFile(fileName), position, { name: name, source: source }); + } + function getQuickInfoAtPosition(fileName, position) { + synchronizeHostData(); + var sourceFile = getValidSourceFile(fileName); + var node = ts.getTouchingPropertyName(sourceFile, position); + if (node === sourceFile) { + // Avoid giving quickInfo for the sourceFile as a whole. + return undefined; + } + var typeChecker = program.getTypeChecker(); + var symbol = getSymbolAtLocationForQuickInfo(node, typeChecker); + if (!symbol || typeChecker.isUnknownSymbol(symbol)) { + var type_7 = shouldGetType(sourceFile, node, position) ? typeChecker.getTypeAtLocation(node) : undefined; + return type_7 && { + kind: "" /* unknown */, + kindModifiers: "" /* none */, + textSpan: ts.createTextSpanFromNode(node, sourceFile), + displayParts: typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { return ts.typeToDisplayParts(typeChecker, type_7, ts.getContainerNode(node)); }), + documentation: type_7.symbol ? type_7.symbol.getDocumentationComment(typeChecker) : undefined, + tags: type_7.symbol ? type_7.symbol.getJsDocTags() : undefined + }; + } + var _a = typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { + return ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, ts.getContainerNode(node), node); + }), symbolKind = _a.symbolKind, displayParts = _a.displayParts, documentation = _a.documentation, tags = _a.tags; + return { + kind: symbolKind, + kindModifiers: ts.SymbolDisplay.getSymbolModifiers(symbol), + textSpan: ts.createTextSpanFromNode(node, sourceFile), + displayParts: displayParts, + documentation: documentation, + tags: tags, + }; + } + function shouldGetType(sourceFile, node, position) { + switch (node.kind) { + case 72 /* Identifier */: + return !ts.isLabelName(node) && !ts.isTagName(node); + case 189 /* PropertyAccessExpression */: + case 148 /* QualifiedName */: + // Don't return quickInfo if inside the comment in `a/**/.b` + return !ts.isInComment(sourceFile, position); + case 100 /* ThisKeyword */: + case 178 /* ThisType */: + case 98 /* SuperKeyword */: + return true; + default: + return false; + } + } + /// Goto definition + function getDefinitionAtPosition(fileName, position) { + synchronizeHostData(); + return ts.GoToDefinition.getDefinitionAtPosition(program, getValidSourceFile(fileName), position); + } + function getDefinitionAndBoundSpan(fileName, position) { + synchronizeHostData(); + return ts.GoToDefinition.getDefinitionAndBoundSpan(program, getValidSourceFile(fileName), position); + } + function getTypeDefinitionAtPosition(fileName, position) { + synchronizeHostData(); + return ts.GoToDefinition.getTypeDefinitionAtPosition(program.getTypeChecker(), getValidSourceFile(fileName), position); + } + /// Goto implementation + function getImplementationAtPosition(fileName, position) { + synchronizeHostData(); + return ts.FindAllReferences.getImplementationsAtPosition(program, cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position); + } + /// References and Occurrences + function getOccurrencesAtPosition(fileName, position) { + return ts.flatMap(getDocumentHighlights(fileName, position, [fileName]), function (entry) { return entry.highlightSpans.map(function (highlightSpan) { return ({ + fileName: entry.fileName, + textSpan: highlightSpan.textSpan, + isWriteAccess: highlightSpan.kind === "writtenReference" /* writtenReference */, + isDefinition: false, + isInString: highlightSpan.isInString, + }); }); }); + } + function getDocumentHighlights(fileName, position, filesToSearch) { + var normalizedFileName = ts.normalizePath(fileName); + ts.Debug.assert(filesToSearch.some(function (f) { return ts.normalizePath(f) === normalizedFileName; })); + synchronizeHostData(); + var sourceFilesToSearch = filesToSearch.map(getValidSourceFile); + var sourceFile = getValidSourceFile(fileName); + return ts.DocumentHighlights.getDocumentHighlights(program, cancellationToken, sourceFile, position, sourceFilesToSearch); + } + function findRenameLocations(fileName, position, findInStrings, findInComments) { + synchronizeHostData(); + var sourceFile = getValidSourceFile(fileName); + var node = ts.getTouchingPropertyName(sourceFile, position); + if (ts.isIdentifier(node) && (ts.isJsxOpeningElement(node.parent) || ts.isJsxClosingElement(node.parent)) && ts.isIntrinsicJsxName(node.escapedText)) { + var _a = node.parent.parent, openingElement = _a.openingElement, closingElement = _a.closingElement; + return [openingElement, closingElement].map(function (node) { + return ({ fileName: sourceFile.fileName, textSpan: ts.createTextSpanFromNode(node.tagName, sourceFile) }); + }); + } + else { + return getReferencesWorker(node, position, { findInStrings: findInStrings, findInComments: findInComments, isForRename: true }, ts.FindAllReferences.toRenameLocation); + } + } + function getReferencesAtPosition(fileName, position) { + synchronizeHostData(); + return getReferencesWorker(ts.getTouchingPropertyName(getValidSourceFile(fileName), position), position, {}, ts.FindAllReferences.toReferenceEntry); + } + function getReferencesWorker(node, position, options, cb) { + synchronizeHostData(); + // Exclude default library when renaming as commonly user don't want to change that file. + var sourceFiles = options && options.isForRename + ? program.getSourceFiles().filter(function (sourceFile) { return !program.isSourceFileDefaultLibrary(sourceFile); }) + : program.getSourceFiles(); + return ts.FindAllReferences.findReferenceOrRenameEntries(program, cancellationToken, sourceFiles, node, position, options, cb); + } + function findReferences(fileName, position) { + synchronizeHostData(); + return ts.FindAllReferences.findReferencedSymbols(program, cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position); + } + function getNavigateToItems(searchValue, maxResultCount, fileName, excludeDtsFiles) { + if (excludeDtsFiles === void 0) { excludeDtsFiles = false; } + synchronizeHostData(); + var sourceFiles = fileName ? [getValidSourceFile(fileName)] : program.getSourceFiles(); + return ts.NavigateTo.getNavigateToItems(sourceFiles, program.getTypeChecker(), cancellationToken, searchValue, maxResultCount, excludeDtsFiles); + } + function getEmitOutput(fileName, emitOnlyDtsFiles) { + if (emitOnlyDtsFiles === void 0) { emitOnlyDtsFiles = false; } + synchronizeHostData(); + var sourceFile = getValidSourceFile(fileName); + var customTransformers = host.getCustomTransformers && host.getCustomTransformers(); + return ts.getFileEmitOutput(program, sourceFile, emitOnlyDtsFiles, cancellationToken, customTransformers); + } + // Signature help + /** + * This is a semantic operation. + */ + function getSignatureHelpItems(fileName, position, _a) { + var triggerReason = (_a === void 0 ? ts.emptyOptions : _a).triggerReason; + synchronizeHostData(); + var sourceFile = getValidSourceFile(fileName); + return ts.SignatureHelp.getSignatureHelpItems(program, sourceFile, position, triggerReason, cancellationToken); + } + /// Syntactic features + function getNonBoundSourceFile(fileName) { + return syntaxTreeCache.getCurrentSourceFile(fileName); + } + function getNameOrDottedNameSpan(fileName, startPos, _endPos) { + var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); + // Get node at the location + var node = ts.getTouchingPropertyName(sourceFile, startPos); + if (node === sourceFile) { + return undefined; + } + switch (node.kind) { + case 189 /* PropertyAccessExpression */: + case 148 /* QualifiedName */: + case 10 /* StringLiteral */: + case 87 /* FalseKeyword */: + case 102 /* TrueKeyword */: + case 96 /* NullKeyword */: + case 98 /* SuperKeyword */: + case 100 /* ThisKeyword */: + case 178 /* ThisType */: + case 72 /* Identifier */: + break; + // Cant create the text span + default: + return undefined; + } + var nodeForStartPos = node; + while (true) { + if (ts.isRightSideOfPropertyAccess(nodeForStartPos) || ts.isRightSideOfQualifiedName(nodeForStartPos)) { + // If on the span is in right side of the the property or qualified name, return the span from the qualified name pos to end of this node + nodeForStartPos = nodeForStartPos.parent; + } + else if (ts.isNameOfModuleDeclaration(nodeForStartPos)) { + // If this is name of a module declarations, check if this is right side of dotted module name + // If parent of the module declaration which is parent of this node is module declaration and its body is the module declaration that this node is name of + // Then this name is name from dotted module + if (nodeForStartPos.parent.parent.kind === 244 /* ModuleDeclaration */ && + nodeForStartPos.parent.parent.body === nodeForStartPos.parent) { + // Use parent module declarations name for start pos + nodeForStartPos = nodeForStartPos.parent.parent.name; + } + else { + // We have to use this name for start pos + break; + } + } + else { + // Is not a member expression so we have found the node for start pos + break; + } + } + return ts.createTextSpanFromBounds(nodeForStartPos.getStart(), node.getEnd()); + } + function getBreakpointStatementAtPosition(fileName, position) { + // doesn't use compiler - no need to synchronize with host + var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); + return ts.BreakpointResolver.spanInSourceFileAtLocation(sourceFile, position); + } + function getNavigationBarItems(fileName) { + return ts.NavigationBar.getNavigationBarItems(syntaxTreeCache.getCurrentSourceFile(fileName), cancellationToken); + } + function getNavigationTree(fileName) { + return ts.NavigationBar.getNavigationTree(syntaxTreeCache.getCurrentSourceFile(fileName), cancellationToken); + } + function isTsOrTsxFile(fileName) { + var kind = ts.getScriptKind(fileName, host); + return kind === 3 /* TS */ || kind === 4 /* TSX */; + } + function getSemanticClassifications(fileName, span) { + if (!isTsOrTsxFile(fileName)) { + // do not run semantic classification on non-ts-or-tsx files + return []; + } + synchronizeHostData(); + return ts.getSemanticClassifications(program.getTypeChecker(), cancellationToken, getValidSourceFile(fileName), program.getClassifiableNames(), span); + } + function getEncodedSemanticClassifications(fileName, span) { + if (!isTsOrTsxFile(fileName)) { + // do not run semantic classification on non-ts-or-tsx files + return { spans: [], endOfLineState: 0 /* None */ }; + } + synchronizeHostData(); + return ts.getEncodedSemanticClassifications(program.getTypeChecker(), cancellationToken, getValidSourceFile(fileName), program.getClassifiableNames(), span); + } + function getSyntacticClassifications(fileName, span) { + // doesn't use compiler - no need to synchronize with host + return ts.getSyntacticClassifications(cancellationToken, syntaxTreeCache.getCurrentSourceFile(fileName), span); + } + function getEncodedSyntacticClassifications(fileName, span) { + // doesn't use compiler - no need to synchronize with host + return ts.getEncodedSyntacticClassifications(cancellationToken, syntaxTreeCache.getCurrentSourceFile(fileName), span); + } + function getOutliningSpans(fileName) { + // doesn't use compiler - no need to synchronize with host + var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); + return ts.OutliningElementsCollector.collectElements(sourceFile, cancellationToken); + } + var braceMatching = ts.createMapFromTemplate((_a = {}, + _a[18 /* OpenBraceToken */] = 19 /* CloseBraceToken */, + _a[20 /* OpenParenToken */] = 21 /* CloseParenToken */, + _a[22 /* OpenBracketToken */] = 23 /* CloseBracketToken */, + _a[30 /* GreaterThanToken */] = 28 /* LessThanToken */, + _a)); + braceMatching.forEach(function (value, key) { return braceMatching.set(value.toString(), Number(key)); }); + function getBraceMatchingAtPosition(fileName, position) { + var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); + var token = ts.getTouchingToken(sourceFile, position); + var matchKind = token.getStart(sourceFile) === position ? braceMatching.get(token.kind.toString()) : undefined; + var match = matchKind && ts.findChildOfKind(token.parent, matchKind, sourceFile); + // We want to order the braces when we return the result. + return match ? [ts.createTextSpanFromNode(token, sourceFile), ts.createTextSpanFromNode(match, sourceFile)].sort(function (a, b) { return a.start - b.start; }) : ts.emptyArray; + } + function getIndentationAtPosition(fileName, position, editorOptions) { + var start = ts.timestamp(); + var settings = toEditorSettings(editorOptions); + var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); + log("getIndentationAtPosition: getCurrentSourceFile: " + (ts.timestamp() - start)); + start = ts.timestamp(); + var result = ts.formatting.SmartIndenter.getIndentation(position, sourceFile, settings); + log("getIndentationAtPosition: computeIndentation : " + (ts.timestamp() - start)); + return result; + } + function getFormattingEditsForRange(fileName, start, end, options) { + var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); + return ts.formatting.formatSelection(start, end, sourceFile, ts.formatting.getFormatContext(toEditorSettings(options))); + } + function getFormattingEditsForDocument(fileName, options) { + return ts.formatting.formatDocument(syntaxTreeCache.getCurrentSourceFile(fileName), ts.formatting.getFormatContext(toEditorSettings(options))); + } + function getFormattingEditsAfterKeystroke(fileName, position, key, options) { + var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); + var formatContext = ts.formatting.getFormatContext(toEditorSettings(options)); + if (!ts.isInComment(sourceFile, position)) { + switch (key) { + case "{": + return ts.formatting.formatOnOpeningCurly(position, sourceFile, formatContext); + case "}": + return ts.formatting.formatOnClosingCurly(position, sourceFile, formatContext); + case ";": + return ts.formatting.formatOnSemicolon(position, sourceFile, formatContext); + case "\n": + return ts.formatting.formatOnEnter(position, sourceFile, formatContext); + } + } + return []; + } + function getCodeFixesAtPosition(fileName, start, end, errorCodes, formatOptions, preferences) { + if (preferences === void 0) { preferences = ts.emptyOptions; } + synchronizeHostData(); + var sourceFile = getValidSourceFile(fileName); + var span = ts.createTextSpanFromBounds(start, end); + var formatContext = ts.formatting.getFormatContext(formatOptions); + return ts.flatMap(ts.deduplicate(errorCodes, ts.equateValues, ts.compareValues), function (errorCode) { + cancellationToken.throwIfCancellationRequested(); + return ts.codefix.getFixes({ errorCode: errorCode, sourceFile: sourceFile, span: span, program: program, host: host, cancellationToken: cancellationToken, formatContext: formatContext, preferences: preferences }); + }); + } + function getCombinedCodeFix(scope, fixId, formatOptions, preferences) { + if (preferences === void 0) { preferences = ts.emptyOptions; } + synchronizeHostData(); + ts.Debug.assert(scope.type === "file"); + var sourceFile = getValidSourceFile(scope.fileName); + var formatContext = ts.formatting.getFormatContext(formatOptions); + return ts.codefix.getAllFixes({ fixId: fixId, sourceFile: sourceFile, program: program, host: host, cancellationToken: cancellationToken, formatContext: formatContext, preferences: preferences }); + } + function organizeImports(scope, formatOptions, preferences) { + if (preferences === void 0) { preferences = ts.emptyOptions; } + synchronizeHostData(); + ts.Debug.assert(scope.type === "file"); + var sourceFile = getValidSourceFile(scope.fileName); + var formatContext = ts.formatting.getFormatContext(formatOptions); + return ts.OrganizeImports.organizeImports(sourceFile, formatContext, host, program, preferences); + } + function getEditsForFileRename(oldFilePath, newFilePath, formatOptions, preferences) { + if (preferences === void 0) { preferences = ts.emptyOptions; } + return ts.getEditsForFileRename(getProgram(), oldFilePath, newFilePath, host, ts.formatting.getFormatContext(formatOptions), preferences, sourceMapper); + } + function applyCodeActionCommand(fileName, actionOrFormatSettingsOrUndefined) { + var action = typeof fileName === "string" ? actionOrFormatSettingsOrUndefined : fileName; + var formatSettings = typeof fileName !== "string" ? actionOrFormatSettingsOrUndefined : undefined; + return ts.isArray(action) ? Promise.all(action.map(function (a) { return applySingleCodeActionCommand(a, formatSettings); })) : applySingleCodeActionCommand(action, formatSettings); + } + function applySingleCodeActionCommand(action, formatSettings) { + var getPath = function (path) { return ts.toPath(path, currentDirectory, getCanonicalFileName); }; + switch (action.type) { + case "install package": + return host.installPackage + ? host.installPackage({ fileName: getPath(action.file), packageName: action.packageName }) + : Promise.reject("Host does not implement `installPackage`"); + case "generate types": { + var fileToGenerateTypesFor = action.fileToGenerateTypesFor, outputFileName_1 = action.outputFileName; + if (!host.inspectValue) + return Promise.reject("Host does not implement `installPackage`"); + var valueInfoPromise = host.inspectValue({ fileNameToRequire: fileToGenerateTypesFor }); + return valueInfoPromise.then(function (valueInfo) { + var fullOut = getPath(outputFileName_1); + host.writeFile(fullOut, ts.valueInfoToDeclarationFileText(valueInfo, formatSettings || ts.testFormatSettings)); // TODO: GH#18217 + return { successMessage: "Wrote types to '" + fullOut + "'" }; + }); + } + default: + return ts.Debug.assertNever(action); + } + } + function getDocCommentTemplateAtPosition(fileName, position) { + return ts.JsDoc.getDocCommentTemplateAtPosition(ts.getNewLineOrDefaultFromHost(host), syntaxTreeCache.getCurrentSourceFile(fileName), position); + } + function isValidBraceCompletionAtPosition(fileName, position, openingBrace) { + // '<' is currently not supported, figuring out if we're in a Generic Type vs. a comparison is too + // expensive to do during typing scenarios + // i.e. whether we're dealing with: + // var x = new foo<| ( with class foo{} ) + // or + // var y = 3 <| + if (openingBrace === 60 /* lessThan */) { + return false; + } + var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); + // Check if in a context where we don't want to perform any insertion + if (ts.isInString(sourceFile, position)) { + return false; + } + if (ts.isInsideJsxElementOrAttribute(sourceFile, position)) { + return openingBrace === 123 /* openBrace */; + } + if (ts.isInTemplateString(sourceFile, position)) { + return false; + } + switch (openingBrace) { + case 39 /* singleQuote */: + case 34 /* doubleQuote */: + case 96 /* backtick */: + return !ts.isInComment(sourceFile, position); + } + return true; + } + function getJsxClosingTagAtPosition(fileName, position) { + var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); + var token = ts.findPrecedingToken(position, sourceFile); + if (!token) + return undefined; + var element = token.kind === 30 /* GreaterThanToken */ && ts.isJsxOpeningElement(token.parent) ? token.parent.parent + : ts.isJsxText(token) ? token.parent : undefined; + if (element && isUnclosedTag(element)) { + return { newText: "" }; + } + } + function isUnclosedTag(_a) { + var openingElement = _a.openingElement, closingElement = _a.closingElement, parent = _a.parent; + return !ts.tagNamesAreEquivalent(openingElement.tagName, closingElement.tagName) || + ts.isJsxElement(parent) && ts.tagNamesAreEquivalent(openingElement.tagName, parent.openingElement.tagName) && isUnclosedTag(parent); + } + function getSpanOfEnclosingComment(fileName, position, onlyMultiLine) { + var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); + var range = ts.formatting.getRangeOfEnclosingComment(sourceFile, position); + return range && (!onlyMultiLine || range.kind === 3 /* MultiLineCommentTrivia */) ? ts.createTextSpanFromRange(range) : undefined; + } + function getTodoComments(fileName, descriptors) { + // Note: while getting todo comments seems like a syntactic operation, we actually + // treat it as a semantic operation here. This is because we expect our host to call + // this on every single file. If we treat this syntactically, then that will cause + // us to populate and throw away the tree in our syntax tree cache for each file. By + // treating this as a semantic operation, we can access any tree without throwing + // anything away. + synchronizeHostData(); + var sourceFile = getValidSourceFile(fileName); + cancellationToken.throwIfCancellationRequested(); + var fileContents = sourceFile.text; + var result = []; + // Exclude node_modules files as we don't want to show the todos of external libraries. + if (descriptors.length > 0 && !isNodeModulesFile(sourceFile.fileName)) { + var regExp = getTodoCommentsRegExp(); + var matchArray = void 0; + while (matchArray = regExp.exec(fileContents)) { + cancellationToken.throwIfCancellationRequested(); + // If we got a match, here is what the match array will look like. Say the source text is: + // + // " // hack 1" + // + // The result array with the regexp: will be: + // + // ["// hack 1", "// ", "hack 1", undefined, "hack"] + // + // Here are the relevant capture groups: + // 0) The full match for the entire regexp. + // 1) The preamble to the message portion. + // 2) The message portion. + // 3...N) The descriptor that was matched - by index. 'undefined' for each + // descriptor that didn't match. an actual value if it did match. + // + // i.e. 'undefined' in position 3 above means TODO(jason) didn't match. + // "hack" in position 4 means HACK did match. + var firstDescriptorCaptureIndex = 3; + ts.Debug.assert(matchArray.length === descriptors.length + firstDescriptorCaptureIndex); + var preamble = matchArray[1]; + var matchPosition = matchArray.index + preamble.length; + // OK, we have found a match in the file. This is only an acceptable match if + // it is contained within a comment. + if (!ts.isInComment(sourceFile, matchPosition)) { + continue; + } + var descriptor = void 0; + for (var i = 0; i < descriptors.length; i++) { + if (matchArray[i + firstDescriptorCaptureIndex]) { + descriptor = descriptors[i]; + } + } + if (descriptor === undefined) + return ts.Debug.fail(); + // We don't want to match something like 'TODOBY', so we make sure a non + // letter/digit follows the match. + if (isLetterOrDigit(fileContents.charCodeAt(matchPosition + descriptor.text.length))) { + continue; + } + var message = matchArray[2]; + result.push({ descriptor: descriptor, message: message, position: matchPosition }); + } + } + return result; + function escapeRegExp(str) { + return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"); + } + function getTodoCommentsRegExp() { + // NOTE: `?:` means 'non-capture group'. It allows us to have groups without having to + // filter them out later in the final result array. + // TODO comments can appear in one of the following forms: + // + // 1) // TODO or /////////// TODO + // + // 2) /* TODO or /********** TODO + // + // 3) /* + // * TODO + // */ + // + // The following three regexps are used to match the start of the text up to the TODO + // comment portion. + var singleLineCommentStart = /(?:\/\/+\s*)/.source; + var multiLineCommentStart = /(?:\/\*+\s*)/.source; + var anyNumberOfSpacesAndAsterisksAtStartOfLine = /(?:^(?:\s|\*)*)/.source; + // Match any of the above three TODO comment start regexps. + // Note that the outermost group *is* a capture group. We want to capture the preamble + // so that we can determine the starting position of the TODO comment match. + var preamble = "(" + anyNumberOfSpacesAndAsterisksAtStartOfLine + "|" + singleLineCommentStart + "|" + multiLineCommentStart + ")"; + // Takes the descriptors and forms a regexp that matches them as if they were literals. + // For example, if the descriptors are "TODO(jason)" and "HACK", then this will be: + // + // (?:(TODO\(jason\))|(HACK)) + // + // Note that the outermost group is *not* a capture group, but the innermost groups + // *are* capture groups. By capturing the inner literals we can determine after + // matching which descriptor we are dealing with. + var literals = "(?:" + ts.map(descriptors, function (d) { return "(" + escapeRegExp(d.text) + ")"; }).join("|") + ")"; + // After matching a descriptor literal, the following regexp matches the rest of the + // text up to the end of the line (or */). + var endOfLineOrEndOfComment = /(?:$|\*\/)/.source; + var messageRemainder = /(?:.*?)/.source; + // This is the portion of the match we'll return as part of the TODO comment result. We + // match the literal portion up to the end of the line or end of comment. + var messagePortion = "(" + literals + messageRemainder + ")"; + var regExpString = preamble + messagePortion + endOfLineOrEndOfComment; + // The final regexp will look like this: + // /((?:\/\/+\s*)|(?:\/\*+\s*)|(?:^(?:\s|\*)*))((?:(TODO\(jason\))|(HACK))(?:.*?))(?:$|\*\/)/gim + // The flags of the regexp are important here. + // 'g' is so that we are doing a global search and can find matches several times + // in the input. + // + // 'i' is for case insensitivity (We do this to match C# TODO comment code). + // + // 'm' is so we can find matches in a multi-line input. + return new RegExp(regExpString, "gim"); + } + function isLetterOrDigit(char) { + return (char >= 97 /* a */ && char <= 122 /* z */) || + (char >= 65 /* A */ && char <= 90 /* Z */) || + (char >= 48 /* _0 */ && char <= 57 /* _9 */); + } + function isNodeModulesFile(path) { + return ts.stringContains(path, "/node_modules/"); + } + } + function getRenameInfo(fileName, position) { + synchronizeHostData(); + return ts.Rename.getRenameInfo(program, getValidSourceFile(fileName), position); + } + function getRefactorContext(file, positionOrRange, preferences, formatOptions) { + var _a = typeof positionOrRange === "number" ? [positionOrRange, undefined] : [positionOrRange.pos, positionOrRange.end], startPosition = _a[0], endPosition = _a[1]; + return { + file: file, + startPosition: startPosition, + endPosition: endPosition, + program: getProgram(), + host: host, + formatContext: ts.formatting.getFormatContext(formatOptions), + cancellationToken: cancellationToken, + preferences: preferences, + }; + } + function getApplicableRefactors(fileName, positionOrRange, preferences) { + if (preferences === void 0) { preferences = ts.emptyOptions; } + synchronizeHostData(); + var file = getValidSourceFile(fileName); + return ts.refactor.getApplicableRefactors(getRefactorContext(file, positionOrRange, preferences)); + } + function getEditsForRefactor(fileName, formatOptions, positionOrRange, refactorName, actionName, preferences) { + if (preferences === void 0) { preferences = ts.emptyOptions; } + synchronizeHostData(); + var file = getValidSourceFile(fileName); + return ts.refactor.getEditsForRefactor(getRefactorContext(file, positionOrRange, preferences, formatOptions), refactorName, actionName); + } + return { + dispose: dispose, + cleanupSemanticCache: cleanupSemanticCache, + getSyntacticDiagnostics: getSyntacticDiagnostics, + getSemanticDiagnostics: getSemanticDiagnostics, + getSuggestionDiagnostics: getSuggestionDiagnostics, + getCompilerOptionsDiagnostics: getCompilerOptionsDiagnostics, + getSyntacticClassifications: getSyntacticClassifications, + getSemanticClassifications: getSemanticClassifications, + getEncodedSyntacticClassifications: getEncodedSyntacticClassifications, + getEncodedSemanticClassifications: getEncodedSemanticClassifications, + getCompletionsAtPosition: getCompletionsAtPosition, + getCompletionEntryDetails: getCompletionEntryDetails, + getCompletionEntrySymbol: getCompletionEntrySymbol, + getSignatureHelpItems: getSignatureHelpItems, + getQuickInfoAtPosition: getQuickInfoAtPosition, + getDefinitionAtPosition: getDefinitionAtPosition, + getDefinitionAndBoundSpan: getDefinitionAndBoundSpan, + getImplementationAtPosition: getImplementationAtPosition, + getTypeDefinitionAtPosition: getTypeDefinitionAtPosition, + getReferencesAtPosition: getReferencesAtPosition, + findReferences: findReferences, + getOccurrencesAtPosition: getOccurrencesAtPosition, + getDocumentHighlights: getDocumentHighlights, + getNameOrDottedNameSpan: getNameOrDottedNameSpan, + getBreakpointStatementAtPosition: getBreakpointStatementAtPosition, + getNavigateToItems: getNavigateToItems, + getRenameInfo: getRenameInfo, + findRenameLocations: findRenameLocations, + getNavigationBarItems: getNavigationBarItems, + getNavigationTree: getNavigationTree, + getOutliningSpans: getOutliningSpans, + getTodoComments: getTodoComments, + getBraceMatchingAtPosition: getBraceMatchingAtPosition, + getIndentationAtPosition: getIndentationAtPosition, + getFormattingEditsForRange: getFormattingEditsForRange, + getFormattingEditsForDocument: getFormattingEditsForDocument, + getFormattingEditsAfterKeystroke: getFormattingEditsAfterKeystroke, + getDocCommentTemplateAtPosition: getDocCommentTemplateAtPosition, + isValidBraceCompletionAtPosition: isValidBraceCompletionAtPosition, + getJsxClosingTagAtPosition: getJsxClosingTagAtPosition, + getSpanOfEnclosingComment: getSpanOfEnclosingComment, + getCodeFixesAtPosition: getCodeFixesAtPosition, + getCombinedCodeFix: getCombinedCodeFix, + applyCodeActionCommand: applyCodeActionCommand, + organizeImports: organizeImports, + getEditsForFileRename: getEditsForFileRename, + getEmitOutput: getEmitOutput, + getNonBoundSourceFile: getNonBoundSourceFile, + getProgram: getProgram, + getApplicableRefactors: getApplicableRefactors, + getEditsForRefactor: getEditsForRefactor, + toLineColumnOffset: sourceMapper.toLineColumnOffset, + getSourceMapper: function () { return sourceMapper; }, + }; + } + ts.createLanguageService = createLanguageService; + /* @internal */ + /** Names in the name table are escaped, so an identifier `__foo` will have a name table entry `___foo`. */ + function getNameTable(sourceFile) { + if (!sourceFile.nameTable) { + initializeNameTable(sourceFile); + } + return sourceFile.nameTable; // TODO: GH#18217 + } + ts.getNameTable = getNameTable; + function initializeNameTable(sourceFile) { + var nameTable = sourceFile.nameTable = ts.createUnderscoreEscapedMap(); + sourceFile.forEachChild(function walk(node) { + if (ts.isIdentifier(node) && !ts.isTagName(node) && node.escapedText || ts.isStringOrNumericLiteralLike(node) && literalIsName(node)) { + var text = ts.getEscapedTextOfIdentifierOrLiteral(node); + nameTable.set(text, nameTable.get(text) === undefined ? node.pos : -1); + } + ts.forEachChild(node, walk); + if (ts.hasJSDocNodes(node)) { + for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { + var jsDoc = _a[_i]; + ts.forEachChild(jsDoc, walk); + } + } + }); + } + /** + * We want to store any numbers/strings if they were a name that could be + * related to a declaration. So, if we have 'import x = require("something")' + * then we want 'something' to be in the name table. Similarly, if we have + * "a['propname']" then we want to store "propname" in the name table. + */ + function literalIsName(node) { + return ts.isDeclarationName(node) || + node.parent.kind === 259 /* ExternalModuleReference */ || + isArgumentOfElementAccessExpression(node) || + ts.isLiteralComputedPropertyDeclarationName(node); + } + /** + * Returns the containing object literal property declaration given a possible name node, e.g. "a" in x = { "a": 1 } + */ + /* @internal */ + function getContainingObjectLiteralElement(node) { + var element = getContainingObjectLiteralElementWorker(node); + return element && (ts.isObjectLiteralExpression(element.parent) || ts.isJsxAttributes(element.parent)) ? element : undefined; + } + ts.getContainingObjectLiteralElement = getContainingObjectLiteralElement; + function getContainingObjectLiteralElementWorker(node) { + switch (node.kind) { + case 10 /* StringLiteral */: + case 8 /* NumericLiteral */: + if (node.parent.kind === 149 /* ComputedPropertyName */) { + return ts.isObjectLiteralElement(node.parent.parent) ? node.parent.parent : undefined; + } + // falls through + case 72 /* Identifier */: + return ts.isObjectLiteralElement(node.parent) && + (node.parent.parent.kind === 188 /* ObjectLiteralExpression */ || node.parent.parent.kind === 268 /* JsxAttributes */) && + node.parent.name === node ? node.parent : undefined; + } + return undefined; + } + function getSymbolAtLocationForQuickInfo(node, checker) { + var object = getContainingObjectLiteralElement(node); + if (object) { + var contextualType = checker.getContextualType(object.parent); + var properties = contextualType && getPropertySymbolsFromContextualType(object, checker, contextualType, /*unionSymbolOk*/ false); + if (properties && properties.length === 1) { + return ts.first(properties); + } + } + return checker.getSymbolAtLocation(node); + } + /** Gets all symbols for one property. Does not get symbols for every property. */ + /* @internal */ + function getPropertySymbolsFromContextualType(node, checker, contextualType, unionSymbolOk) { + var name = ts.getNameFromPropertyName(node.name); + if (!name) + return ts.emptyArray; + if (!contextualType.isUnion()) { + var symbol = contextualType.getProperty(name); + return symbol ? [symbol] : ts.emptyArray; + } + var discriminatedPropertySymbols = ts.mapDefined(contextualType.types, function (t) { return ts.isObjectLiteralExpression(node.parent) && checker.isTypeInvalidDueToUnionDiscriminant(t, node.parent) ? undefined : t.getProperty(name); }); + if (unionSymbolOk && (discriminatedPropertySymbols.length === 0 || discriminatedPropertySymbols.length === contextualType.types.length)) { + var symbol = contextualType.getProperty(name); + if (symbol) + return [symbol]; + } + if (discriminatedPropertySymbols.length === 0) { + // Bad discriminant -- do again without discriminating + return ts.mapDefined(contextualType.types, function (t) { return t.getProperty(name); }); + } + return discriminatedPropertySymbols; + } + ts.getPropertySymbolsFromContextualType = getPropertySymbolsFromContextualType; + function isArgumentOfElementAccessExpression(node) { + return node && + node.parent && + node.parent.kind === 190 /* ElementAccessExpression */ && + node.parent.argumentExpression === node; + } + /** + * Get the path of the default library files (lib.d.ts) as distributed with the typescript + * node package. + * The functionality is not supported if the ts module is consumed outside of a node module. + */ + function getDefaultLibFilePath(options) { + // Check __dirname is defined and that we are on a node.js system. + if (typeof __dirname !== "undefined") { + return __dirname + ts.directorySeparator + ts.getDefaultLibFileName(options); + } + throw new Error("getDefaultLibFilePath is only supported when consumed as a node module. "); + } + ts.getDefaultLibFilePath = getDefaultLibFilePath; + ts.objectAllocator = getServicesObjectAllocator(); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var BreakpointResolver; + (function (BreakpointResolver) { + /** + * Get the breakpoint span in given sourceFile + */ + function spanInSourceFileAtLocation(sourceFile, position) { + // Cannot set breakpoint in dts file + if (sourceFile.isDeclarationFile) { + return undefined; + } + var tokenAtLocation = ts.getTokenAtPosition(sourceFile, position); + var lineOfPosition = sourceFile.getLineAndCharacterOfPosition(position).line; + if (sourceFile.getLineAndCharacterOfPosition(tokenAtLocation.getStart(sourceFile)).line > lineOfPosition) { + // Get previous token if the token is returned starts on new line + // eg: let x =10; |--- cursor is here + // let y = 10; + // token at position will return let keyword on second line as the token but we would like to use + // token on same line if trailing trivia (comments or white spaces on same line) part of the last token on that line + var preceding = ts.findPrecedingToken(tokenAtLocation.pos, sourceFile); + // It's a blank line + if (!preceding || sourceFile.getLineAndCharacterOfPosition(preceding.getEnd()).line !== lineOfPosition) { + return undefined; + } + tokenAtLocation = preceding; + } + // Cannot set breakpoint in ambient declarations + if (tokenAtLocation.flags & 4194304 /* Ambient */) { + return undefined; + } + // Get the span in the node based on its syntax + return spanInNode(tokenAtLocation); + function textSpan(startNode, endNode) { + var start = startNode.decorators ? + ts.skipTrivia(sourceFile.text, startNode.decorators.end) : + startNode.getStart(sourceFile); + return ts.createTextSpanFromBounds(start, (endNode || startNode).getEnd()); + } + function textSpanEndingAtNextToken(startNode, previousTokenToFindNextEndToken) { + return textSpan(startNode, ts.findNextToken(previousTokenToFindNextEndToken, previousTokenToFindNextEndToken.parent, sourceFile)); + } + function spanInNodeIfStartsOnSameLine(node, otherwiseOnNode) { + if (node && lineOfPosition === sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile)).line) { + return spanInNode(node); + } + return spanInNode(otherwiseOnNode); + } + function spanInNodeArray(nodeArray) { + return ts.createTextSpanFromBounds(ts.skipTrivia(sourceFile.text, nodeArray.pos), nodeArray.end); + } + function spanInPreviousNode(node) { + return spanInNode(ts.findPrecedingToken(node.pos, sourceFile)); + } + function spanInNextNode(node) { + return spanInNode(ts.findNextToken(node, node.parent, sourceFile)); + } + function spanInNode(node) { + if (node) { + var parent = node.parent; + switch (node.kind) { + case 219 /* VariableStatement */: + // Span on first variable declaration + return spanInVariableDeclaration(node.declarationList.declarations[0]); + case 237 /* VariableDeclaration */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + return spanInVariableDeclaration(node); + case 151 /* Parameter */: + return spanInParameterDeclaration(node); + case 239 /* FunctionDeclaration */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 157 /* Constructor */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + return spanInFunctionDeclaration(node); + case 218 /* Block */: + if (ts.isFunctionBlock(node)) { + return spanInFunctionBlock(node); + } + // falls through + case 245 /* ModuleBlock */: + return spanInBlock(node); + case 274 /* CatchClause */: + return spanInBlock(node.block); + case 221 /* ExpressionStatement */: + // span on the expression + return textSpan(node.expression); + case 230 /* ReturnStatement */: + // span on return keyword and expression if present + return textSpan(node.getChildAt(0), node.expression); + case 224 /* WhileStatement */: + // Span on while(...) + return textSpanEndingAtNextToken(node, node.expression); + case 223 /* DoStatement */: + // span in statement of the do statement + return spanInNode(node.statement); + case 236 /* DebuggerStatement */: + // span on debugger keyword + return textSpan(node.getChildAt(0)); + case 222 /* IfStatement */: + // set on if(..) span + return textSpanEndingAtNextToken(node, node.expression); + case 233 /* LabeledStatement */: + // span in statement + return spanInNode(node.statement); + case 229 /* BreakStatement */: + case 228 /* ContinueStatement */: + // On break or continue keyword and label if present + return textSpan(node.getChildAt(0), node.label); + case 225 /* ForStatement */: + return spanInForStatement(node); + case 226 /* ForInStatement */: + // span of for (a in ...) + return textSpanEndingAtNextToken(node, node.expression); + case 227 /* ForOfStatement */: + // span in initializer + return spanInInitializerOfForLike(node); + case 232 /* SwitchStatement */: + // span on switch(...) + return textSpanEndingAtNextToken(node, node.expression); + case 271 /* CaseClause */: + case 272 /* DefaultClause */: + // span in first statement of the clause + return spanInNode(node.statements[0]); + case 235 /* TryStatement */: + // span in try block + return spanInBlock(node.tryBlock); + case 234 /* ThrowStatement */: + // span in throw ... + return textSpan(node, node.expression); + case 254 /* ExportAssignment */: + // span on export = id + return textSpan(node, node.expression); + case 248 /* ImportEqualsDeclaration */: + // import statement without including semicolon + return textSpan(node, node.moduleReference); + case 249 /* ImportDeclaration */: + // import statement without including semicolon + return textSpan(node, node.moduleSpecifier); + case 255 /* ExportDeclaration */: + // import statement without including semicolon + return textSpan(node, node.moduleSpecifier); + case 244 /* ModuleDeclaration */: + // span on complete module if it is instantiated + if (ts.getModuleInstanceState(node) !== 1 /* Instantiated */) { + return undefined; + } + // falls through + case 240 /* ClassDeclaration */: + case 243 /* EnumDeclaration */: + case 278 /* EnumMember */: + case 186 /* BindingElement */: + // span on complete node + return textSpan(node); + case 231 /* WithStatement */: + // span in statement + return spanInNode(node.statement); + case 152 /* Decorator */: + return spanInNodeArray(parent.decorators); + case 184 /* ObjectBindingPattern */: + case 185 /* ArrayBindingPattern */: + return spanInBindingPattern(node); + // No breakpoint in interface, type alias + case 241 /* InterfaceDeclaration */: + case 242 /* TypeAliasDeclaration */: + return undefined; + // Tokens: + case 26 /* SemicolonToken */: + case 1 /* EndOfFileToken */: + return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(node.pos, sourceFile)); + case 27 /* CommaToken */: + return spanInPreviousNode(node); + case 18 /* OpenBraceToken */: + return spanInOpenBraceToken(node); + case 19 /* CloseBraceToken */: + return spanInCloseBraceToken(node); + case 23 /* CloseBracketToken */: + return spanInCloseBracketToken(node); + case 20 /* OpenParenToken */: + return spanInOpenParenToken(node); + case 21 /* CloseParenToken */: + return spanInCloseParenToken(node); + case 57 /* ColonToken */: + return spanInColonToken(node); + case 30 /* GreaterThanToken */: + case 28 /* LessThanToken */: + return spanInGreaterThanOrLessThanToken(node); + // Keywords: + case 107 /* WhileKeyword */: + return spanInWhileKeyword(node); + case 83 /* ElseKeyword */: + case 75 /* CatchKeyword */: + case 88 /* FinallyKeyword */: + return spanInNextNode(node); + case 147 /* OfKeyword */: + return spanInOfKeyword(node); + default: + // Destructuring pattern in destructuring assignment + // [a, b, c] of + // [a, b, c] = expression + if (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node)) { + return spanInArrayLiteralOrObjectLiteralDestructuringPattern(node); + } + // Set breakpoint on identifier element of destructuring pattern + // `a` or `...c` or `d: x` from + // `[a, b, ...c]` or `{ a, b }` or `{ d: x }` from destructuring pattern + if ((node.kind === 72 /* Identifier */ || + node.kind === 208 /* SpreadElement */ || + node.kind === 275 /* PropertyAssignment */ || + node.kind === 276 /* ShorthandPropertyAssignment */) && + ts.isArrayLiteralOrObjectLiteralDestructuringPattern(parent)) { + return textSpan(node); + } + if (node.kind === 204 /* BinaryExpression */) { + var _a = node, left = _a.left, operatorToken = _a.operatorToken; + // Set breakpoint in destructuring pattern if its destructuring assignment + // [a, b, c] or {a, b, c} of + // [a, b, c] = expression or + // {a, b, c} = expression + if (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(left)) { + return spanInArrayLiteralOrObjectLiteralDestructuringPattern(left); + } + if (operatorToken.kind === 59 /* EqualsToken */ && ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent)) { + // Set breakpoint on assignment expression element of destructuring pattern + // a = expression of + // [a = expression, b, c] = someExpression or + // { a = expression, b, c } = someExpression + return textSpan(node); + } + if (operatorToken.kind === 27 /* CommaToken */) { + return spanInNode(left); + } + } + if (ts.isExpressionNode(node)) { + switch (parent.kind) { + case 223 /* DoStatement */: + // Set span as if on while keyword + return spanInPreviousNode(node); + case 152 /* Decorator */: + // Set breakpoint on the decorator emit + return spanInNode(node.parent); + case 225 /* ForStatement */: + case 227 /* ForOfStatement */: + return textSpan(node); + case 204 /* BinaryExpression */: + if (node.parent.operatorToken.kind === 27 /* CommaToken */) { + // If this is a comma expression, the breakpoint is possible in this expression + return textSpan(node); + } + break; + case 197 /* ArrowFunction */: + if (node.parent.body === node) { + // If this is body of arrow function, it is allowed to have the breakpoint + return textSpan(node); + } + break; + } + } + switch (node.parent.kind) { + case 275 /* PropertyAssignment */: + // If this is name of property assignment, set breakpoint in the initializer + if (node.parent.name === node && + !ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent.parent)) { + return spanInNode(node.parent.initializer); + } + break; + case 194 /* TypeAssertionExpression */: + // Breakpoint in type assertion goes to its operand + if (node.parent.type === node) { + return spanInNextNode(node.parent.type); + } + break; + case 237 /* VariableDeclaration */: + case 151 /* Parameter */: { + // initializer of variable/parameter declaration go to previous node + var _b = node.parent, initializer = _b.initializer, type = _b.type; + if (initializer === node || type === node || ts.isAssignmentOperator(node.kind)) { + return spanInPreviousNode(node); + } + break; + } + case 204 /* BinaryExpression */: { + var left = node.parent.left; + if (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(left) && node !== left) { + // If initializer of destructuring assignment move to previous token + return spanInPreviousNode(node); + } + break; + } + default: + // return type of function go to previous token + if (ts.isFunctionLike(node.parent) && node.parent.type === node) { + return spanInPreviousNode(node); + } + } + // Default go to parent to set the breakpoint + return spanInNode(node.parent); + } + } + function textSpanFromVariableDeclaration(variableDeclaration) { + if (ts.isVariableDeclarationList(variableDeclaration.parent) && variableDeclaration.parent.declarations[0] === variableDeclaration) { + // First declaration - include let keyword + return textSpan(ts.findPrecedingToken(variableDeclaration.pos, sourceFile, variableDeclaration.parent), variableDeclaration); + } + else { + // Span only on this declaration + return textSpan(variableDeclaration); + } + } + function spanInVariableDeclaration(variableDeclaration) { + // If declaration of for in statement, just set the span in parent + if (variableDeclaration.parent.parent.kind === 226 /* ForInStatement */) { + return spanInNode(variableDeclaration.parent.parent); + } + var parent = variableDeclaration.parent; + // If this is a destructuring pattern, set breakpoint in binding pattern + if (ts.isBindingPattern(variableDeclaration.name)) { + return spanInBindingPattern(variableDeclaration.name); + } + // Breakpoint is possible in variableDeclaration only if there is initialization + // or its declaration from 'for of' + if (variableDeclaration.initializer || + ts.hasModifier(variableDeclaration, 1 /* Export */) || + parent.parent.kind === 227 /* ForOfStatement */) { + return textSpanFromVariableDeclaration(variableDeclaration); + } + if (ts.isVariableDeclarationList(variableDeclaration.parent) && + variableDeclaration.parent.declarations[0] !== variableDeclaration) { + // If we cannot set breakpoint on this declaration, set it on previous one + // Because the variable declaration may be binding pattern and + // we would like to set breakpoint in last binding element if that's the case, + // use preceding token instead + return spanInNode(ts.findPrecedingToken(variableDeclaration.pos, sourceFile, variableDeclaration.parent)); + } + } + function canHaveSpanInParameterDeclaration(parameter) { + // Breakpoint is possible on parameter only if it has initializer, is a rest parameter, or has public or private modifier + return !!parameter.initializer || parameter.dotDotDotToken !== undefined || + ts.hasModifier(parameter, 4 /* Public */ | 8 /* Private */); + } + function spanInParameterDeclaration(parameter) { + if (ts.isBindingPattern(parameter.name)) { + // Set breakpoint in binding pattern + return spanInBindingPattern(parameter.name); + } + else if (canHaveSpanInParameterDeclaration(parameter)) { + return textSpan(parameter); + } + else { + var functionDeclaration = parameter.parent; + var indexOfParameter = functionDeclaration.parameters.indexOf(parameter); + ts.Debug.assert(indexOfParameter !== -1); + if (indexOfParameter !== 0) { + // Not a first parameter, go to previous parameter + return spanInParameterDeclaration(functionDeclaration.parameters[indexOfParameter - 1]); + } + else { + // Set breakpoint in the function declaration body + return spanInNode(functionDeclaration.body); + } + } + } + function canFunctionHaveSpanInWholeDeclaration(functionDeclaration) { + return ts.hasModifier(functionDeclaration, 1 /* Export */) || + (functionDeclaration.parent.kind === 240 /* ClassDeclaration */ && functionDeclaration.kind !== 157 /* Constructor */); + } + function spanInFunctionDeclaration(functionDeclaration) { + // No breakpoints in the function signature + if (!functionDeclaration.body) { + return undefined; + } + if (canFunctionHaveSpanInWholeDeclaration(functionDeclaration)) { + // Set the span on whole function declaration + return textSpan(functionDeclaration); + } + // Set span in function body + return spanInNode(functionDeclaration.body); + } + function spanInFunctionBlock(block) { + var nodeForSpanInBlock = block.statements.length ? block.statements[0] : block.getLastToken(); + if (canFunctionHaveSpanInWholeDeclaration(block.parent)) { + return spanInNodeIfStartsOnSameLine(block.parent, nodeForSpanInBlock); + } + return spanInNode(nodeForSpanInBlock); + } + function spanInBlock(block) { + switch (block.parent.kind) { + case 244 /* ModuleDeclaration */: + if (ts.getModuleInstanceState(block.parent) !== 1 /* Instantiated */) { + return undefined; + } + // falls through + // Set on parent if on same line otherwise on first statement + case 224 /* WhileStatement */: + case 222 /* IfStatement */: + case 226 /* ForInStatement */: + return spanInNodeIfStartsOnSameLine(block.parent, block.statements[0]); + // Set span on previous token if it starts on same line otherwise on the first statement of the block + case 225 /* ForStatement */: + case 227 /* ForOfStatement */: + return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(block.pos, sourceFile, block.parent), block.statements[0]); + } + // Default action is to set on first statement + return spanInNode(block.statements[0]); + } + function spanInInitializerOfForLike(forLikeStatement) { + if (forLikeStatement.initializer.kind === 238 /* VariableDeclarationList */) { + // Declaration list - set breakpoint in first declaration + var variableDeclarationList = forLikeStatement.initializer; + if (variableDeclarationList.declarations.length > 0) { + return spanInNode(variableDeclarationList.declarations[0]); + } + } + else { + // Expression - set breakpoint in it + return spanInNode(forLikeStatement.initializer); + } + } + function spanInForStatement(forStatement) { + if (forStatement.initializer) { + return spanInInitializerOfForLike(forStatement); + } + if (forStatement.condition) { + return textSpan(forStatement.condition); + } + if (forStatement.incrementor) { + return textSpan(forStatement.incrementor); + } + } + function spanInBindingPattern(bindingPattern) { + // Set breakpoint in first binding element + var firstBindingElement = ts.forEach(bindingPattern.elements, function (element) { return element.kind !== 210 /* OmittedExpression */ ? element : undefined; }); + if (firstBindingElement) { + return spanInNode(firstBindingElement); + } + // Empty binding pattern of binding element, set breakpoint on binding element + if (bindingPattern.parent.kind === 186 /* BindingElement */) { + return textSpan(bindingPattern.parent); + } + // Variable declaration is used as the span + return textSpanFromVariableDeclaration(bindingPattern.parent); + } + function spanInArrayLiteralOrObjectLiteralDestructuringPattern(node) { + ts.Debug.assert(node.kind !== 185 /* ArrayBindingPattern */ && node.kind !== 184 /* ObjectBindingPattern */); + var elements = node.kind === 187 /* ArrayLiteralExpression */ ? node.elements : node.properties; + var firstBindingElement = ts.forEach(elements, function (element) { return element.kind !== 210 /* OmittedExpression */ ? element : undefined; }); + if (firstBindingElement) { + return spanInNode(firstBindingElement); + } + // Could be ArrayLiteral from destructuring assignment or + // just nested element in another destructuring assignment + // set breakpoint on assignment when parent is destructuring assignment + // Otherwise set breakpoint for this element + return textSpan(node.parent.kind === 204 /* BinaryExpression */ ? node.parent : node); + } + // Tokens: + function spanInOpenBraceToken(node) { + switch (node.parent.kind) { + case 243 /* EnumDeclaration */: + var enumDeclaration = node.parent; + return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(node.pos, sourceFile, node.parent), enumDeclaration.members.length ? enumDeclaration.members[0] : enumDeclaration.getLastToken(sourceFile)); + case 240 /* ClassDeclaration */: + var classDeclaration = node.parent; + return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(node.pos, sourceFile, node.parent), classDeclaration.members.length ? classDeclaration.members[0] : classDeclaration.getLastToken(sourceFile)); + case 246 /* CaseBlock */: + return spanInNodeIfStartsOnSameLine(node.parent.parent, node.parent.clauses[0]); + } + // Default to parent node + return spanInNode(node.parent); + } + function spanInCloseBraceToken(node) { + switch (node.parent.kind) { + case 245 /* ModuleBlock */: + // If this is not an instantiated module block, no bp span + if (ts.getModuleInstanceState(node.parent.parent) !== 1 /* Instantiated */) { + return undefined; + } + // falls through + case 243 /* EnumDeclaration */: + case 240 /* ClassDeclaration */: + // Span on close brace token + return textSpan(node); + case 218 /* Block */: + if (ts.isFunctionBlock(node.parent)) { + // Span on close brace token + return textSpan(node); + } + // falls through + case 274 /* CatchClause */: + return spanInNode(ts.lastOrUndefined(node.parent.statements)); + case 246 /* CaseBlock */: + // breakpoint in last statement of the last clause + var caseBlock = node.parent; + var lastClause = ts.lastOrUndefined(caseBlock.clauses); + if (lastClause) { + return spanInNode(ts.lastOrUndefined(lastClause.statements)); + } + return undefined; + case 184 /* ObjectBindingPattern */: + // Breakpoint in last binding element or binding pattern if it contains no elements + var bindingPattern = node.parent; + return spanInNode(ts.lastOrUndefined(bindingPattern.elements) || bindingPattern); + // Default to parent node + default: + if (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent)) { + // Breakpoint in last binding element or binding pattern if it contains no elements + var objectLiteral = node.parent; + return textSpan(ts.lastOrUndefined(objectLiteral.properties) || objectLiteral); + } + return spanInNode(node.parent); + } + } + function spanInCloseBracketToken(node) { + switch (node.parent.kind) { + case 185 /* ArrayBindingPattern */: + // Breakpoint in last binding element or binding pattern if it contains no elements + var bindingPattern = node.parent; + return textSpan(ts.lastOrUndefined(bindingPattern.elements) || bindingPattern); + default: + if (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent)) { + // Breakpoint in last binding element or binding pattern if it contains no elements + var arrayLiteral = node.parent; + return textSpan(ts.lastOrUndefined(arrayLiteral.elements) || arrayLiteral); + } + // Default to parent node + return spanInNode(node.parent); + } + } + function spanInOpenParenToken(node) { + if (node.parent.kind === 223 /* DoStatement */ || // Go to while keyword and do action instead + node.parent.kind === 191 /* CallExpression */ || + node.parent.kind === 192 /* NewExpression */) { + return spanInPreviousNode(node); + } + if (node.parent.kind === 195 /* ParenthesizedExpression */) { + return spanInNextNode(node); + } + // Default to parent node + return spanInNode(node.parent); + } + function spanInCloseParenToken(node) { + // Is this close paren token of parameter list, set span in previous token + switch (node.parent.kind) { + case 196 /* FunctionExpression */: + case 239 /* FunctionDeclaration */: + case 197 /* ArrowFunction */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 157 /* Constructor */: + case 224 /* WhileStatement */: + case 223 /* DoStatement */: + case 225 /* ForStatement */: + case 227 /* ForOfStatement */: + case 191 /* CallExpression */: + case 192 /* NewExpression */: + case 195 /* ParenthesizedExpression */: + return spanInPreviousNode(node); + // Default to parent node + default: + return spanInNode(node.parent); + } + } + function spanInColonToken(node) { + // Is this : specifying return annotation of the function declaration + if (ts.isFunctionLike(node.parent) || + node.parent.kind === 275 /* PropertyAssignment */ || + node.parent.kind === 151 /* Parameter */) { + return spanInPreviousNode(node); + } + return spanInNode(node.parent); + } + function spanInGreaterThanOrLessThanToken(node) { + if (node.parent.kind === 194 /* TypeAssertionExpression */) { + return spanInNextNode(node); + } + return spanInNode(node.parent); + } + function spanInWhileKeyword(node) { + if (node.parent.kind === 223 /* DoStatement */) { + // Set span on while expression + return textSpanEndingAtNextToken(node, node.parent.expression); + } + // Default to parent node + return spanInNode(node.parent); + } + function spanInOfKeyword(node) { + if (node.parent.kind === 227 /* ForOfStatement */) { + // Set using next token + return spanInNextNode(node); + } + // Default to parent node + return spanInNode(node.parent); + } + } + } + BreakpointResolver.spanInSourceFileAtLocation = spanInSourceFileAtLocation; + })(BreakpointResolver = ts.BreakpointResolver || (ts.BreakpointResolver = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + /** + * Transform one or more nodes using the supplied transformers. + * @param source A single `Node` or an array of `Node` objects. + * @param transformers An array of `TransformerFactory` callbacks used to process the transformation. + * @param compilerOptions Optional compiler options. + */ + function transform(source, transformers, compilerOptions) { + var diagnostics = []; + compilerOptions = ts.fixupCompilerOptions(compilerOptions, diagnostics); // TODO: GH#18217 + var nodes = ts.isArray(source) ? source : [source]; + var result = ts.transformNodes(/*resolver*/ undefined, /*emitHost*/ undefined, compilerOptions, nodes, transformers, /*allowDtsFiles*/ true); + result.diagnostics = ts.concatenate(result.diagnostics, diagnostics); + return result; + } + ts.transform = transform; +})(ts || (ts = {})); +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +/* @internal */ +var debugObjectHost = (function () { return this; })(); +// We need to use 'null' to interface with the managed side. +/* tslint:disable:no-null-keyword */ +/* tslint:disable:no-in-operator */ +/* @internal */ +var ts; +(function (ts) { + function logInternalError(logger, err) { + if (logger) { + logger.log("*INTERNAL ERROR* - Exception in typescript services: " + err.message); + } + } + var ScriptSnapshotShimAdapter = /** @class */ (function () { + function ScriptSnapshotShimAdapter(scriptSnapshotShim) { + this.scriptSnapshotShim = scriptSnapshotShim; + } + ScriptSnapshotShimAdapter.prototype.getText = function (start, end) { + return this.scriptSnapshotShim.getText(start, end); + }; + ScriptSnapshotShimAdapter.prototype.getLength = function () { + return this.scriptSnapshotShim.getLength(); + }; + ScriptSnapshotShimAdapter.prototype.getChangeRange = function (oldSnapshot) { + var oldSnapshotShim = oldSnapshot; + var encoded = this.scriptSnapshotShim.getChangeRange(oldSnapshotShim.scriptSnapshotShim); + if (encoded === null) { + return null; // TODO: GH#18217 + } + var decoded = JSON.parse(encoded); // TODO: GH#18217 + return ts.createTextChangeRange(ts.createTextSpan(decoded.span.start, decoded.span.length), decoded.newLength); + }; + ScriptSnapshotShimAdapter.prototype.dispose = function () { + // if scriptSnapshotShim is a COM object then property check becomes method call with no arguments + // 'in' does not have this effect + if ("dispose" in this.scriptSnapshotShim) { + this.scriptSnapshotShim.dispose(); // TODO: GH#18217 Can we just use `if (this.scriptSnapshotShim.dispose)`? + } + }; + return ScriptSnapshotShimAdapter; + }()); + var LanguageServiceShimHostAdapter = /** @class */ (function () { + function LanguageServiceShimHostAdapter(shimHost) { + var _this = this; + this.shimHost = shimHost; + this.loggingEnabled = false; + this.tracingEnabled = false; + // if shimHost is a COM object then property check will become method call with no arguments. + // 'in' does not have this effect. + if ("getModuleResolutionsForFile" in this.shimHost) { + this.resolveModuleNames = function (moduleNames, containingFile) { + var resolutionsInFile = JSON.parse(_this.shimHost.getModuleResolutionsForFile(containingFile)); // TODO: GH#18217 + return ts.map(moduleNames, function (name) { + var result = ts.getProperty(resolutionsInFile, name); + return result ? { resolvedFileName: result, extension: ts.extensionFromPath(result), isExternalLibraryImport: false } : undefined; + }); + }; + } + if ("directoryExists" in this.shimHost) { + this.directoryExists = function (directoryName) { return _this.shimHost.directoryExists(directoryName); }; + } + if ("getTypeReferenceDirectiveResolutionsForFile" in this.shimHost) { + this.resolveTypeReferenceDirectives = function (typeDirectiveNames, containingFile) { + var typeDirectivesForFile = JSON.parse(_this.shimHost.getTypeReferenceDirectiveResolutionsForFile(containingFile)); // TODO: GH#18217 + return ts.map(typeDirectiveNames, function (name) { return ts.getProperty(typeDirectivesForFile, name); }); + }; + } + } + LanguageServiceShimHostAdapter.prototype.log = function (s) { + if (this.loggingEnabled) { + this.shimHost.log(s); + } + }; + LanguageServiceShimHostAdapter.prototype.trace = function (s) { + if (this.tracingEnabled) { + this.shimHost.trace(s); + } + }; + LanguageServiceShimHostAdapter.prototype.error = function (s) { + this.shimHost.error(s); + }; + LanguageServiceShimHostAdapter.prototype.getProjectVersion = function () { + if (!this.shimHost.getProjectVersion) { + // shimmed host does not support getProjectVersion + return undefined; // TODO: GH#18217 + } + return this.shimHost.getProjectVersion(); + }; + LanguageServiceShimHostAdapter.prototype.getTypeRootsVersion = function () { + if (!this.shimHost.getTypeRootsVersion) { + return 0; + } + return this.shimHost.getTypeRootsVersion(); + }; + LanguageServiceShimHostAdapter.prototype.useCaseSensitiveFileNames = function () { + return this.shimHost.useCaseSensitiveFileNames ? this.shimHost.useCaseSensitiveFileNames() : false; + }; + LanguageServiceShimHostAdapter.prototype.getCompilationSettings = function () { + var settingsJson = this.shimHost.getCompilationSettings(); + if (settingsJson === null || settingsJson === "") { + throw Error("LanguageServiceShimHostAdapter.getCompilationSettings: empty compilationSettings"); + } + var compilerOptions = JSON.parse(settingsJson); + // permit language service to handle all files (filtering should be performed on the host side) + compilerOptions.allowNonTsExtensions = true; + return compilerOptions; + }; + LanguageServiceShimHostAdapter.prototype.getScriptFileNames = function () { + var encoded = this.shimHost.getScriptFileNames(); + return JSON.parse(encoded); + }; + LanguageServiceShimHostAdapter.prototype.getScriptSnapshot = function (fileName) { + var scriptSnapshot = this.shimHost.getScriptSnapshot(fileName); + return scriptSnapshot && new ScriptSnapshotShimAdapter(scriptSnapshot); + }; + LanguageServiceShimHostAdapter.prototype.getScriptKind = function (fileName) { + if ("getScriptKind" in this.shimHost) { + return this.shimHost.getScriptKind(fileName); // TODO: GH#18217 + } + else { + return 0 /* Unknown */; + } + }; + LanguageServiceShimHostAdapter.prototype.getScriptVersion = function (fileName) { + return this.shimHost.getScriptVersion(fileName); + }; + LanguageServiceShimHostAdapter.prototype.getLocalizedDiagnosticMessages = function () { + var diagnosticMessagesJson = this.shimHost.getLocalizedDiagnosticMessages(); + if (diagnosticMessagesJson === null || diagnosticMessagesJson === "") { + return null; + } + try { + return JSON.parse(diagnosticMessagesJson); + } + catch (e) { + this.log(e.description || "diagnosticMessages.generated.json has invalid JSON format"); + return null; + } + }; + LanguageServiceShimHostAdapter.prototype.getCancellationToken = function () { + var hostCancellationToken = this.shimHost.getCancellationToken(); + return new ts.ThrottledCancellationToken(hostCancellationToken); + }; + LanguageServiceShimHostAdapter.prototype.getCurrentDirectory = function () { + return this.shimHost.getCurrentDirectory(); + }; + LanguageServiceShimHostAdapter.prototype.getDirectories = function (path) { + return JSON.parse(this.shimHost.getDirectories(path)); + }; + LanguageServiceShimHostAdapter.prototype.getDefaultLibFileName = function (options) { + return this.shimHost.getDefaultLibFileName(JSON.stringify(options)); + }; + LanguageServiceShimHostAdapter.prototype.readDirectory = function (path, extensions, exclude, include, depth) { + var pattern = ts.getFileMatcherPatterns(path, exclude, include, this.shimHost.useCaseSensitiveFileNames(), this.shimHost.getCurrentDirectory()); // TODO: GH#18217 + return JSON.parse(this.shimHost.readDirectory(path, JSON.stringify(extensions), JSON.stringify(pattern.basePaths), pattern.excludePattern, pattern.includeFilePattern, pattern.includeDirectoryPattern, depth)); + }; + LanguageServiceShimHostAdapter.prototype.readFile = function (path, encoding) { + return this.shimHost.readFile(path, encoding); + }; + LanguageServiceShimHostAdapter.prototype.fileExists = function (path) { + return this.shimHost.fileExists(path); + }; + return LanguageServiceShimHostAdapter; + }()); + ts.LanguageServiceShimHostAdapter = LanguageServiceShimHostAdapter; + var CoreServicesShimHostAdapter = /** @class */ (function () { + function CoreServicesShimHostAdapter(shimHost) { + var _this = this; + this.shimHost = shimHost; + this.useCaseSensitiveFileNames = this.shimHost.useCaseSensitiveFileNames ? this.shimHost.useCaseSensitiveFileNames() : false; + if ("directoryExists" in this.shimHost) { + this.directoryExists = function (directoryName) { return _this.shimHost.directoryExists(directoryName); }; + } + else { + this.directoryExists = undefined; // TODO: GH#18217 + } + if ("realpath" in this.shimHost) { + this.realpath = function (path) { return _this.shimHost.realpath(path); }; // TODO: GH#18217 + } + else { + this.realpath = undefined; // TODO: GH#18217 + } + } + CoreServicesShimHostAdapter.prototype.readDirectory = function (rootDir, extensions, exclude, include, depth) { + var pattern = ts.getFileMatcherPatterns(rootDir, exclude, include, this.shimHost.useCaseSensitiveFileNames(), this.shimHost.getCurrentDirectory()); // TODO: GH#18217 + return JSON.parse(this.shimHost.readDirectory(rootDir, JSON.stringify(extensions), JSON.stringify(pattern.basePaths), pattern.excludePattern, pattern.includeFilePattern, pattern.includeDirectoryPattern, depth)); + }; + CoreServicesShimHostAdapter.prototype.fileExists = function (fileName) { + return this.shimHost.fileExists(fileName); + }; + CoreServicesShimHostAdapter.prototype.readFile = function (fileName) { + return this.shimHost.readFile(fileName); + }; + CoreServicesShimHostAdapter.prototype.getDirectories = function (path) { + return JSON.parse(this.shimHost.getDirectories(path)); + }; + return CoreServicesShimHostAdapter; + }()); + ts.CoreServicesShimHostAdapter = CoreServicesShimHostAdapter; + function simpleForwardCall(logger, actionDescription, action, logPerformance) { + var start; + if (logPerformance) { + logger.log(actionDescription); + start = ts.timestamp(); + } + var result = action(); + if (logPerformance) { + var end = ts.timestamp(); + logger.log(actionDescription + " completed in " + (end - start) + " msec"); + if (ts.isString(result)) { + var str = result; + if (str.length > 128) { + str = str.substring(0, 128) + "..."; + } + logger.log(" result.length=" + str.length + ", result='" + JSON.stringify(str) + "'"); + } + } + return result; + } + function forwardJSONCall(logger, actionDescription, action, logPerformance) { + return forwardCall(logger, actionDescription, /*returnJson*/ true, action, logPerformance); + } + function forwardCall(logger, actionDescription, returnJson, action, logPerformance) { + try { + var result = simpleForwardCall(logger, actionDescription, action, logPerformance); + return returnJson ? JSON.stringify({ result: result }) : result; + } + catch (err) { + if (err instanceof ts.OperationCanceledException) { + return JSON.stringify({ canceled: true }); + } + logInternalError(logger, err); + err.description = actionDescription; + return JSON.stringify({ error: err }); + } + } + var ShimBase = /** @class */ (function () { + function ShimBase(factory) { + this.factory = factory; + factory.registerShim(this); + } + ShimBase.prototype.dispose = function (_dummy) { + this.factory.unregisterShim(this); + }; + return ShimBase; + }()); + function realizeDiagnostics(diagnostics, newLine) { + return diagnostics.map(function (d) { return realizeDiagnostic(d, newLine); }); + } + ts.realizeDiagnostics = realizeDiagnostics; + function realizeDiagnostic(diagnostic, newLine) { + return { + message: ts.flattenDiagnosticMessageText(diagnostic.messageText, newLine), + start: diagnostic.start, + length: diagnostic.length, + category: ts.diagnosticCategoryName(diagnostic), + code: diagnostic.code, + reportsUnnecessary: diagnostic.reportsUnnecessary, + }; + } + var LanguageServiceShimObject = /** @class */ (function (_super) { + __extends(LanguageServiceShimObject, _super); + function LanguageServiceShimObject(factory, host, languageService) { + var _this = _super.call(this, factory) || this; + _this.host = host; + _this.languageService = languageService; + _this.logPerformance = false; + _this.logger = _this.host; + return _this; + } + LanguageServiceShimObject.prototype.forwardJSONCall = function (actionDescription, action) { + return forwardJSONCall(this.logger, actionDescription, action, this.logPerformance); + }; + /// DISPOSE + /** + * Ensure (almost) deterministic release of internal Javascript resources when + * some external native objects holds onto us (e.g. Com/Interop). + */ + LanguageServiceShimObject.prototype.dispose = function (dummy) { + this.logger.log("dispose()"); + this.languageService.dispose(); + this.languageService = null; + // force a GC + if (debugObjectHost && debugObjectHost.CollectGarbage) { + debugObjectHost.CollectGarbage(); + this.logger.log("CollectGarbage()"); + } + this.logger = null; + _super.prototype.dispose.call(this, dummy); + }; + /// REFRESH + /** + * Update the list of scripts known to the compiler + */ + LanguageServiceShimObject.prototype.refresh = function (throwOnError) { + this.forwardJSONCall("refresh(" + throwOnError + ")", function () { return null; }); + }; + LanguageServiceShimObject.prototype.cleanupSemanticCache = function () { + var _this = this; + this.forwardJSONCall("cleanupSemanticCache()", function () { + _this.languageService.cleanupSemanticCache(); + return null; + }); + }; + LanguageServiceShimObject.prototype.realizeDiagnostics = function (diagnostics) { + var newLine = ts.getNewLineOrDefaultFromHost(this.host); + return realizeDiagnostics(diagnostics, newLine); + }; + LanguageServiceShimObject.prototype.getSyntacticClassifications = function (fileName, start, length) { + var _this = this; + return this.forwardJSONCall("getSyntacticClassifications('" + fileName + "', " + start + ", " + length + ")", function () { return _this.languageService.getSyntacticClassifications(fileName, ts.createTextSpan(start, length)); }); + }; + LanguageServiceShimObject.prototype.getSemanticClassifications = function (fileName, start, length) { + var _this = this; + return this.forwardJSONCall("getSemanticClassifications('" + fileName + "', " + start + ", " + length + ")", function () { return _this.languageService.getSemanticClassifications(fileName, ts.createTextSpan(start, length)); }); + }; + LanguageServiceShimObject.prototype.getEncodedSyntacticClassifications = function (fileName, start, length) { + var _this = this; + return this.forwardJSONCall("getEncodedSyntacticClassifications('" + fileName + "', " + start + ", " + length + ")", + // directly serialize the spans out to a string. This is much faster to decode + // on the managed side versus a full JSON array. + function () { return convertClassifications(_this.languageService.getEncodedSyntacticClassifications(fileName, ts.createTextSpan(start, length))); }); + }; + LanguageServiceShimObject.prototype.getEncodedSemanticClassifications = function (fileName, start, length) { + var _this = this; + return this.forwardJSONCall("getEncodedSemanticClassifications('" + fileName + "', " + start + ", " + length + ")", + // directly serialize the spans out to a string. This is much faster to decode + // on the managed side versus a full JSON array. + function () { return convertClassifications(_this.languageService.getEncodedSemanticClassifications(fileName, ts.createTextSpan(start, length))); }); + }; + LanguageServiceShimObject.prototype.getSyntacticDiagnostics = function (fileName) { + var _this = this; + return this.forwardJSONCall("getSyntacticDiagnostics('" + fileName + "')", function () { + var diagnostics = _this.languageService.getSyntacticDiagnostics(fileName); + return _this.realizeDiagnostics(diagnostics); + }); + }; + LanguageServiceShimObject.prototype.getSemanticDiagnostics = function (fileName) { + var _this = this; + return this.forwardJSONCall("getSemanticDiagnostics('" + fileName + "')", function () { + var diagnostics = _this.languageService.getSemanticDiagnostics(fileName); + return _this.realizeDiagnostics(diagnostics); + }); + }; + LanguageServiceShimObject.prototype.getSuggestionDiagnostics = function (fileName) { + var _this = this; + return this.forwardJSONCall("getSuggestionDiagnostics('" + fileName + "')", function () { return _this.realizeDiagnostics(_this.languageService.getSuggestionDiagnostics(fileName)); }); + }; + LanguageServiceShimObject.prototype.getCompilerOptionsDiagnostics = function () { + var _this = this; + return this.forwardJSONCall("getCompilerOptionsDiagnostics()", function () { + var diagnostics = _this.languageService.getCompilerOptionsDiagnostics(); + return _this.realizeDiagnostics(diagnostics); + }); + }; + /// QUICKINFO + /** + * Computes a string representation of the type at the requested position + * in the active file. + */ + LanguageServiceShimObject.prototype.getQuickInfoAtPosition = function (fileName, position) { + var _this = this; + return this.forwardJSONCall("getQuickInfoAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getQuickInfoAtPosition(fileName, position); }); + }; + /// NAMEORDOTTEDNAMESPAN + /** + * Computes span information of the name or dotted name at the requested position + * in the active file. + */ + LanguageServiceShimObject.prototype.getNameOrDottedNameSpan = function (fileName, startPos, endPos) { + var _this = this; + return this.forwardJSONCall("getNameOrDottedNameSpan('" + fileName + "', " + startPos + ", " + endPos + ")", function () { return _this.languageService.getNameOrDottedNameSpan(fileName, startPos, endPos); }); + }; + /** + * STATEMENTSPAN + * Computes span information of statement at the requested position in the active file. + */ + LanguageServiceShimObject.prototype.getBreakpointStatementAtPosition = function (fileName, position) { + var _this = this; + return this.forwardJSONCall("getBreakpointStatementAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getBreakpointStatementAtPosition(fileName, position); }); + }; + /// SIGNATUREHELP + LanguageServiceShimObject.prototype.getSignatureHelpItems = function (fileName, position, options) { + var _this = this; + return this.forwardJSONCall("getSignatureHelpItems('" + fileName + "', " + position + ")", function () { return _this.languageService.getSignatureHelpItems(fileName, position, options); }); + }; + /// GOTO DEFINITION + /** + * Computes the definition location and file for the symbol + * at the requested position. + */ + LanguageServiceShimObject.prototype.getDefinitionAtPosition = function (fileName, position) { + var _this = this; + return this.forwardJSONCall("getDefinitionAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getDefinitionAtPosition(fileName, position); }); + }; + /** + * Computes the definition location and file for the symbol + * at the requested position. + */ + LanguageServiceShimObject.prototype.getDefinitionAndBoundSpan = function (fileName, position) { + var _this = this; + return this.forwardJSONCall("getDefinitionAndBoundSpan('" + fileName + "', " + position + ")", function () { return _this.languageService.getDefinitionAndBoundSpan(fileName, position); }); + }; + /// GOTO Type + /** + * Computes the definition location of the type of the symbol + * at the requested position. + */ + LanguageServiceShimObject.prototype.getTypeDefinitionAtPosition = function (fileName, position) { + var _this = this; + return this.forwardJSONCall("getTypeDefinitionAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getTypeDefinitionAtPosition(fileName, position); }); + }; + /// GOTO Implementation + /** + * Computes the implementation location of the symbol + * at the requested position. + */ + LanguageServiceShimObject.prototype.getImplementationAtPosition = function (fileName, position) { + var _this = this; + return this.forwardJSONCall("getImplementationAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getImplementationAtPosition(fileName, position); }); + }; + LanguageServiceShimObject.prototype.getRenameInfo = function (fileName, position) { + var _this = this; + return this.forwardJSONCall("getRenameInfo('" + fileName + "', " + position + ")", function () { return _this.languageService.getRenameInfo(fileName, position); }); + }; + LanguageServiceShimObject.prototype.findRenameLocations = function (fileName, position, findInStrings, findInComments) { + var _this = this; + return this.forwardJSONCall("findRenameLocations('" + fileName + "', " + position + ", " + findInStrings + ", " + findInComments + ")", function () { return _this.languageService.findRenameLocations(fileName, position, findInStrings, findInComments); }); + }; + /// GET BRACE MATCHING + LanguageServiceShimObject.prototype.getBraceMatchingAtPosition = function (fileName, position) { + var _this = this; + return this.forwardJSONCall("getBraceMatchingAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getBraceMatchingAtPosition(fileName, position); }); + }; + LanguageServiceShimObject.prototype.isValidBraceCompletionAtPosition = function (fileName, position, openingBrace) { + var _this = this; + return this.forwardJSONCall("isValidBraceCompletionAtPosition('" + fileName + "', " + position + ", " + openingBrace + ")", function () { return _this.languageService.isValidBraceCompletionAtPosition(fileName, position, openingBrace); }); + }; + LanguageServiceShimObject.prototype.getSpanOfEnclosingComment = function (fileName, position, onlyMultiLine) { + var _this = this; + return this.forwardJSONCall("getSpanOfEnclosingComment('" + fileName + "', " + position + ")", function () { return _this.languageService.getSpanOfEnclosingComment(fileName, position, onlyMultiLine); }); + }; + /// GET SMART INDENT + LanguageServiceShimObject.prototype.getIndentationAtPosition = function (fileName, position, options /*Services.EditorOptions*/) { + var _this = this; + return this.forwardJSONCall("getIndentationAtPosition('" + fileName + "', " + position + ")", function () { + var localOptions = JSON.parse(options); + return _this.languageService.getIndentationAtPosition(fileName, position, localOptions); + }); + }; + /// GET REFERENCES + LanguageServiceShimObject.prototype.getReferencesAtPosition = function (fileName, position) { + var _this = this; + return this.forwardJSONCall("getReferencesAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getReferencesAtPosition(fileName, position); }); + }; + LanguageServiceShimObject.prototype.findReferences = function (fileName, position) { + var _this = this; + return this.forwardJSONCall("findReferences('" + fileName + "', " + position + ")", function () { return _this.languageService.findReferences(fileName, position); }); + }; + LanguageServiceShimObject.prototype.getOccurrencesAtPosition = function (fileName, position) { + var _this = this; + return this.forwardJSONCall("getOccurrencesAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getOccurrencesAtPosition(fileName, position); }); + }; + LanguageServiceShimObject.prototype.getDocumentHighlights = function (fileName, position, filesToSearch) { + var _this = this; + return this.forwardJSONCall("getDocumentHighlights('" + fileName + "', " + position + ")", function () { + var results = _this.languageService.getDocumentHighlights(fileName, position, JSON.parse(filesToSearch)); + // workaround for VS document highlighting issue - keep only items from the initial file + var normalizedName = ts.normalizeSlashes(fileName).toLowerCase(); + return ts.filter(results, function (r) { return ts.normalizeSlashes(r.fileName).toLowerCase() === normalizedName; }); + }); + }; + /// COMPLETION LISTS + /** + * Get a string based representation of the completions + * to provide at the given source position and providing a member completion + * list if requested. + */ + LanguageServiceShimObject.prototype.getCompletionsAtPosition = function (fileName, position, preferences) { + var _this = this; + return this.forwardJSONCall("getCompletionsAtPosition('" + fileName + "', " + position + ", " + preferences + ")", function () { return _this.languageService.getCompletionsAtPosition(fileName, position, preferences); }); + }; + /** Get a string based representation of a completion list entry details */ + LanguageServiceShimObject.prototype.getCompletionEntryDetails = function (fileName, position, entryName, formatOptions, source, preferences) { + var _this = this; + return this.forwardJSONCall("getCompletionEntryDetails('" + fileName + "', " + position + ", '" + entryName + "')", function () { + var localOptions = formatOptions === undefined ? undefined : JSON.parse(formatOptions); + return _this.languageService.getCompletionEntryDetails(fileName, position, entryName, localOptions, source, preferences); + }); + }; + LanguageServiceShimObject.prototype.getFormattingEditsForRange = function (fileName, start, end, options /*Services.FormatCodeOptions*/) { + var _this = this; + return this.forwardJSONCall("getFormattingEditsForRange('" + fileName + "', " + start + ", " + end + ")", function () { + var localOptions = JSON.parse(options); + return _this.languageService.getFormattingEditsForRange(fileName, start, end, localOptions); + }); + }; + LanguageServiceShimObject.prototype.getFormattingEditsForDocument = function (fileName, options /*Services.FormatCodeOptions*/) { + var _this = this; + return this.forwardJSONCall("getFormattingEditsForDocument('" + fileName + "')", function () { + var localOptions = JSON.parse(options); + return _this.languageService.getFormattingEditsForDocument(fileName, localOptions); + }); + }; + LanguageServiceShimObject.prototype.getFormattingEditsAfterKeystroke = function (fileName, position, key, options /*Services.FormatCodeOptions*/) { + var _this = this; + return this.forwardJSONCall("getFormattingEditsAfterKeystroke('" + fileName + "', " + position + ", '" + key + "')", function () { + var localOptions = JSON.parse(options); + return _this.languageService.getFormattingEditsAfterKeystroke(fileName, position, key, localOptions); + }); + }; + LanguageServiceShimObject.prototype.getDocCommentTemplateAtPosition = function (fileName, position) { + var _this = this; + return this.forwardJSONCall("getDocCommentTemplateAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getDocCommentTemplateAtPosition(fileName, position); }); + }; + /// NAVIGATE TO + /** Return a list of symbols that are interesting to navigate to */ + LanguageServiceShimObject.prototype.getNavigateToItems = function (searchValue, maxResultCount, fileName) { + var _this = this; + return this.forwardJSONCall("getNavigateToItems('" + searchValue + "', " + maxResultCount + ", " + fileName + ")", function () { return _this.languageService.getNavigateToItems(searchValue, maxResultCount, fileName); }); + }; + LanguageServiceShimObject.prototype.getNavigationBarItems = function (fileName) { + var _this = this; + return this.forwardJSONCall("getNavigationBarItems('" + fileName + "')", function () { return _this.languageService.getNavigationBarItems(fileName); }); + }; + LanguageServiceShimObject.prototype.getNavigationTree = function (fileName) { + var _this = this; + return this.forwardJSONCall("getNavigationTree('" + fileName + "')", function () { return _this.languageService.getNavigationTree(fileName); }); + }; + LanguageServiceShimObject.prototype.getOutliningSpans = function (fileName) { + var _this = this; + return this.forwardJSONCall("getOutliningSpans('" + fileName + "')", function () { return _this.languageService.getOutliningSpans(fileName); }); + }; + LanguageServiceShimObject.prototype.getTodoComments = function (fileName, descriptors) { + var _this = this; + return this.forwardJSONCall("getTodoComments('" + fileName + "')", function () { return _this.languageService.getTodoComments(fileName, JSON.parse(descriptors)); }); + }; + /// Emit + LanguageServiceShimObject.prototype.getEmitOutput = function (fileName) { + var _this = this; + return this.forwardJSONCall("getEmitOutput('" + fileName + "')", function () { return _this.languageService.getEmitOutput(fileName); }); + }; + LanguageServiceShimObject.prototype.getEmitOutputObject = function (fileName) { + var _this = this; + return forwardCall(this.logger, "getEmitOutput('" + fileName + "')", + /*returnJson*/ false, function () { return _this.languageService.getEmitOutput(fileName); }, this.logPerformance); + }; + return LanguageServiceShimObject; + }(ShimBase)); + function convertClassifications(classifications) { + return { spans: classifications.spans.join(","), endOfLineState: classifications.endOfLineState }; + } + var ClassifierShimObject = /** @class */ (function (_super) { + __extends(ClassifierShimObject, _super); + function ClassifierShimObject(factory, logger) { + var _this = _super.call(this, factory) || this; + _this.logger = logger; + _this.logPerformance = false; + _this.classifier = ts.createClassifier(); + return _this; + } + ClassifierShimObject.prototype.getEncodedLexicalClassifications = function (text, lexState, syntacticClassifierAbsent) { + var _this = this; + if (syntacticClassifierAbsent === void 0) { syntacticClassifierAbsent = false; } + return forwardJSONCall(this.logger, "getEncodedLexicalClassifications", function () { return convertClassifications(_this.classifier.getEncodedLexicalClassifications(text, lexState, syntacticClassifierAbsent)); }, this.logPerformance); + }; + /// COLORIZATION + ClassifierShimObject.prototype.getClassificationsForLine = function (text, lexState, classifyKeywordsInGenerics) { + if (classifyKeywordsInGenerics === void 0) { classifyKeywordsInGenerics = false; } + var classification = this.classifier.getClassificationsForLine(text, lexState, classifyKeywordsInGenerics); + var result = ""; + for (var _i = 0, _a = classification.entries; _i < _a.length; _i++) { + var item = _a[_i]; + result += item.length + "\n"; + result += item.classification + "\n"; + } + result += classification.finalLexState; + return result; + }; + return ClassifierShimObject; + }(ShimBase)); + var CoreServicesShimObject = /** @class */ (function (_super) { + __extends(CoreServicesShimObject, _super); + function CoreServicesShimObject(factory, logger, host) { + var _this = _super.call(this, factory) || this; + _this.logger = logger; + _this.host = host; + _this.logPerformance = false; + return _this; + } + CoreServicesShimObject.prototype.forwardJSONCall = function (actionDescription, action) { + return forwardJSONCall(this.logger, actionDescription, action, this.logPerformance); + }; + CoreServicesShimObject.prototype.resolveModuleName = function (fileName, moduleName, compilerOptionsJson) { + var _this = this; + return this.forwardJSONCall("resolveModuleName('" + fileName + "')", function () { + var compilerOptions = JSON.parse(compilerOptionsJson); + var result = ts.resolveModuleName(moduleName, ts.normalizeSlashes(fileName), compilerOptions, _this.host); + var resolvedFileName = result.resolvedModule ? result.resolvedModule.resolvedFileName : undefined; + if (result.resolvedModule && result.resolvedModule.extension !== ".ts" /* Ts */ && result.resolvedModule.extension !== ".tsx" /* Tsx */ && result.resolvedModule.extension !== ".d.ts" /* Dts */) { + resolvedFileName = undefined; + } + return { + resolvedFileName: resolvedFileName, + failedLookupLocations: result.failedLookupLocations + }; + }); + }; + CoreServicesShimObject.prototype.resolveTypeReferenceDirective = function (fileName, typeReferenceDirective, compilerOptionsJson) { + var _this = this; + return this.forwardJSONCall("resolveTypeReferenceDirective(" + fileName + ")", function () { + var compilerOptions = JSON.parse(compilerOptionsJson); + var result = ts.resolveTypeReferenceDirective(typeReferenceDirective, ts.normalizeSlashes(fileName), compilerOptions, _this.host); + return { + resolvedFileName: result.resolvedTypeReferenceDirective ? result.resolvedTypeReferenceDirective.resolvedFileName : undefined, + primary: result.resolvedTypeReferenceDirective ? result.resolvedTypeReferenceDirective.primary : true, + failedLookupLocations: result.failedLookupLocations + }; + }); + }; + CoreServicesShimObject.prototype.getPreProcessedFileInfo = function (fileName, sourceTextSnapshot) { + var _this = this; + return this.forwardJSONCall("getPreProcessedFileInfo('" + fileName + "')", function () { + // for now treat files as JavaScript + var result = ts.preProcessFile(ts.getSnapshotText(sourceTextSnapshot), /* readImportFiles */ true, /* detectJavaScriptImports */ true); + return { + referencedFiles: _this.convertFileReferences(result.referencedFiles), + importedFiles: _this.convertFileReferences(result.importedFiles), + ambientExternalModules: result.ambientExternalModules, + isLibFile: result.isLibFile, + typeReferenceDirectives: _this.convertFileReferences(result.typeReferenceDirectives), + libReferenceDirectives: _this.convertFileReferences(result.libReferenceDirectives) + }; + }); + }; + CoreServicesShimObject.prototype.getAutomaticTypeDirectiveNames = function (compilerOptionsJson) { + var _this = this; + return this.forwardJSONCall("getAutomaticTypeDirectiveNames('" + compilerOptionsJson + "')", function () { + var compilerOptions = JSON.parse(compilerOptionsJson); + return ts.getAutomaticTypeDirectiveNames(compilerOptions, _this.host); + }); + }; + CoreServicesShimObject.prototype.convertFileReferences = function (refs) { + if (!refs) { + return undefined; + } + var result = []; + for (var _i = 0, refs_1 = refs; _i < refs_1.length; _i++) { + var ref = refs_1[_i]; + result.push({ + path: ts.normalizeSlashes(ref.fileName), + position: ref.pos, + length: ref.end - ref.pos + }); + } + return result; + }; + CoreServicesShimObject.prototype.getTSConfigFileInfo = function (fileName, sourceTextSnapshot) { + var _this = this; + return this.forwardJSONCall("getTSConfigFileInfo('" + fileName + "')", function () { + var result = ts.parseJsonText(fileName, ts.getSnapshotText(sourceTextSnapshot)); + var normalizedFileName = ts.normalizeSlashes(fileName); + var configFile = ts.parseJsonSourceFileConfigFileContent(result, _this.host, ts.getDirectoryPath(normalizedFileName), /*existingOptions*/ {}, normalizedFileName); + return { + options: configFile.options, + typeAcquisition: configFile.typeAcquisition, + files: configFile.fileNames, + raw: configFile.raw, + errors: realizeDiagnostics(result.parseDiagnostics.concat(configFile.errors), "\r\n") + }; + }); + }; + CoreServicesShimObject.prototype.getDefaultCompilationSettings = function () { + return this.forwardJSONCall("getDefaultCompilationSettings()", function () { return ts.getDefaultCompilerOptions(); }); + }; + CoreServicesShimObject.prototype.discoverTypings = function (discoverTypingsJson) { + var _this = this; + var getCanonicalFileName = ts.createGetCanonicalFileName(/*useCaseSensitivefileNames:*/ false); + return this.forwardJSONCall("discoverTypings()", function () { + var info = JSON.parse(discoverTypingsJson); + if (_this.safeList === undefined) { + _this.safeList = ts.JsTyping.loadSafeList(_this.host, ts.toPath(info.safeListPath, info.safeListPath, getCanonicalFileName)); + } + return ts.JsTyping.discoverTypings(_this.host, function (msg) { return _this.logger.log(msg); }, info.fileNames, ts.toPath(info.projectRootPath, info.projectRootPath, getCanonicalFileName), _this.safeList, info.packageNameToTypingLocation, info.typeAcquisition, info.unresolvedImports, info.typesRegistry); + }); + }; + return CoreServicesShimObject; + }(ShimBase)); + var TypeScriptServicesFactory = /** @class */ (function () { + function TypeScriptServicesFactory() { + this._shims = []; + } + /* + * Returns script API version. + */ + TypeScriptServicesFactory.prototype.getServicesVersion = function () { + return ts.servicesVersion; + }; + TypeScriptServicesFactory.prototype.createLanguageServiceShim = function (host) { + try { + if (this.documentRegistry === undefined) { + this.documentRegistry = ts.createDocumentRegistry(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames(), host.getCurrentDirectory()); + } + var hostAdapter = new LanguageServiceShimHostAdapter(host); + var languageService = ts.createLanguageService(hostAdapter, this.documentRegistry, /*syntaxOnly*/ false); + return new LanguageServiceShimObject(this, host, languageService); + } + catch (err) { + logInternalError(host, err); + throw err; + } + }; + TypeScriptServicesFactory.prototype.createClassifierShim = function (logger) { + try { + return new ClassifierShimObject(this, logger); + } + catch (err) { + logInternalError(logger, err); + throw err; + } + }; + TypeScriptServicesFactory.prototype.createCoreServicesShim = function (host) { + try { + var adapter = new CoreServicesShimHostAdapter(host); + return new CoreServicesShimObject(this, host, adapter); + } + catch (err) { + logInternalError(host, err); + throw err; + } + }; + TypeScriptServicesFactory.prototype.close = function () { + // Forget all the registered shims + ts.clear(this._shims); + this.documentRegistry = undefined; + }; + TypeScriptServicesFactory.prototype.registerShim = function (shim) { + this._shims.push(shim); + }; + TypeScriptServicesFactory.prototype.unregisterShim = function (shim) { + for (var i = 0; i < this._shims.length; i++) { + if (this._shims[i] === shim) { + delete this._shims[i]; + return; + } + } + throw new Error("Invalid operation"); + }; + return TypeScriptServicesFactory; + }()); + ts.TypeScriptServicesFactory = TypeScriptServicesFactory; + if (typeof module !== "undefined" && module.exports) { + module.exports = ts; + } +})(ts || (ts = {})); +/* tslint:enable:no-in-operator */ +/* tslint:enable:no-null */ +/// TODO: this is used by VS, clean this up on both sides of the interface +/* @internal */ +var TypeScript; +(function (TypeScript) { + var Services; + (function (Services) { + Services.TypeScriptServicesFactory = ts.TypeScriptServicesFactory; + })(Services = TypeScript.Services || (TypeScript.Services = {})); +})(TypeScript || (TypeScript = {})); +// 'toolsVersion' gets consumed by the managed side, so it's not unused. +// TODO: it should be moved into a namespace though. +/* @internal */ +var toolsVersion = ts.versionMajorMinor; +//# sourceMappingURL=typescriptServices.out.js.map \ No newline at end of file diff --git a/node_modules/typescript/lib/typingsInstaller.js b/node_modules/typescript/lib/typingsInstaller.js new file mode 100644 index 0000000..7de5d45 --- /dev/null +++ b/node_modules/typescript/lib/typingsInstaller.js @@ -0,0 +1,93209 @@ +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + + +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +var __assign = (this && this.__assign) || function () { + __assign = Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; + }; + return __assign.apply(this, arguments); +}; +"use strict"; +var __assign = (this && this.__assign) || function () { + __assign = Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; + }; + return __assign.apply(this, arguments); +}; +var __generator = (this && this.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } +}; +var __makeTemplateObject = (this && this.__makeTemplateObject) || function (cooked, raw) { + if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } + return cooked; +}; +var ts; +(function (ts) { + // WARNING: The script `configureNightly.ts` uses a regexp to parse out these values. + // If changing the text in this section, be sure to test `configureNightly` too. + ts.versionMajorMinor = "3.2"; + /** The version of the TypeScript compiler release */ + ts.version = ts.versionMajorMinor + ".2"; +})(ts || (ts = {})); +(function (ts) { + /* @internal */ + var Comparison; + (function (Comparison) { + Comparison[Comparison["LessThan"] = -1] = "LessThan"; + Comparison[Comparison["EqualTo"] = 0] = "EqualTo"; + Comparison[Comparison["GreaterThan"] = 1] = "GreaterThan"; + })(Comparison = ts.Comparison || (ts.Comparison = {})); +})(ts || (ts = {})); +/* @internal */ +(function (ts) { + ts.emptyArray = []; + /** Create a MapLike with good performance. */ + function createDictionaryObject() { + var map = Object.create(/*prototype*/ null); // tslint:disable-line:no-null-keyword + // Using 'delete' on an object causes V8 to put the object in dictionary mode. + // This disables creation of hidden classes, which are expensive when an object is + // constantly changing shape. + map.__ = undefined; + delete map.__; + return map; + } + /** Create a new map. If a template object is provided, the map will copy entries from it. */ + function createMap() { + return new ts.MapCtr(); + } + ts.createMap = createMap; + function createMapFromEntries(entries) { + var map = createMap(); + for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) { + var _a = entries_1[_i], key = _a[0], value = _a[1]; + map.set(key, value); + } + return map; + } + ts.createMapFromEntries = createMapFromEntries; + function createMapFromTemplate(template) { + var map = new ts.MapCtr(); + // Copies keys/values from template. Note that for..in will not throw if + // template is undefined, and instead will just exit the loop. + for (var key in template) { + if (hasOwnProperty.call(template, key)) { + map.set(key, template[key]); + } + } + return map; + } + ts.createMapFromTemplate = createMapFromTemplate; + // Internet Explorer's Map doesn't support iteration, so don't use it. + // tslint:disable-next-line no-in-operator variable-name + ts.MapCtr = typeof Map !== "undefined" && "entries" in Map.prototype ? Map : shimMap(); + // Keep the class inside a function so it doesn't get compiled if it's not used. + function shimMap() { + var MapIterator = /** @class */ (function () { + function MapIterator(data, selector) { + this.index = 0; + this.data = data; + this.selector = selector; + this.keys = Object.keys(data); + } + MapIterator.prototype.next = function () { + var index = this.index; + if (index < this.keys.length) { + this.index++; + return { value: this.selector(this.data, this.keys[index]), done: false }; + } + return { value: undefined, done: true }; + }; + return MapIterator; + }()); + return /** @class */ (function () { + function class_1() { + this.data = createDictionaryObject(); + this.size = 0; + } + class_1.prototype.get = function (key) { + return this.data[key]; + }; + class_1.prototype.set = function (key, value) { + if (!this.has(key)) { + this.size++; + } + this.data[key] = value; + return this; + }; + class_1.prototype.has = function (key) { + // tslint:disable-next-line:no-in-operator + return key in this.data; + }; + class_1.prototype.delete = function (key) { + if (this.has(key)) { + this.size--; + delete this.data[key]; + return true; + } + return false; + }; + class_1.prototype.clear = function () { + this.data = createDictionaryObject(); + this.size = 0; + }; + class_1.prototype.keys = function () { + return new MapIterator(this.data, function (_data, key) { return key; }); + }; + class_1.prototype.values = function () { + return new MapIterator(this.data, function (data, key) { return data[key]; }); + }; + class_1.prototype.entries = function () { + return new MapIterator(this.data, function (data, key) { return [key, data[key]]; }); + }; + class_1.prototype.forEach = function (action) { + for (var key in this.data) { + action(this.data[key], key); + } + }; + return class_1; + }()); + } + function length(array) { + return array ? array.length : 0; + } + ts.length = length; + /** + * Iterates through 'array' by index and performs the callback on each element of array until the callback + * returns a truthy value, then returns that value. + * If no such value is found, the callback is applied to each element of array and undefined is returned. + */ + function forEach(array, callback) { + if (array) { + for (var i = 0; i < array.length; i++) { + var result = callback(array[i], i); + if (result) { + return result; + } + } + } + return undefined; + } + ts.forEach = forEach; + /** Like `forEach`, but suitable for use with numbers and strings (which may be falsy). */ + function firstDefined(array, callback) { + if (array === undefined) { + return undefined; + } + for (var i = 0; i < array.length; i++) { + var result = callback(array[i], i); + if (result !== undefined) { + return result; + } + } + return undefined; + } + ts.firstDefined = firstDefined; + function firstDefinedIterator(iter, callback) { + while (true) { + var _a = iter.next(), value = _a.value, done = _a.done; + if (done) { + return undefined; + } + var result = callback(value); + if (result !== undefined) { + return result; + } + } + } + ts.firstDefinedIterator = firstDefinedIterator; + function zipWith(arrayA, arrayB, callback) { + var result = []; + Debug.assertEqual(arrayA.length, arrayB.length); + for (var i = 0; i < arrayA.length; i++) { + result.push(callback(arrayA[i], arrayB[i], i)); + } + return result; + } + ts.zipWith = zipWith; + function zipToIterator(arrayA, arrayB) { + Debug.assertEqual(arrayA.length, arrayB.length); + var i = 0; + return { + next: function () { + if (i === arrayA.length) { + return { value: undefined, done: true }; + } + i++; + return { value: [arrayA[i - 1], arrayB[i - 1]], done: false }; + } + }; + } + ts.zipToIterator = zipToIterator; + function zipToMap(keys, values) { + Debug.assert(keys.length === values.length); + var map = createMap(); + for (var i = 0; i < keys.length; ++i) { + map.set(keys[i], values[i]); + } + return map; + } + ts.zipToMap = zipToMap; + /** + * Iterates through `array` by index and performs the callback on each element of array until the callback + * returns a falsey value, then returns false. + * If no such value is found, the callback is applied to each element of array and `true` is returned. + */ + function every(array, callback) { + if (array) { + for (var i = 0; i < array.length; i++) { + if (!callback(array[i], i)) { + return false; + } + } + } + return true; + } + ts.every = every; + function find(array, predicate) { + for (var i = 0; i < array.length; i++) { + var value = array[i]; + if (predicate(value, i)) { + return value; + } + } + return undefined; + } + ts.find = find; + function findLast(array, predicate) { + for (var i = array.length - 1; i >= 0; i--) { + var value = array[i]; + if (predicate(value, i)) { + return value; + } + } + return undefined; + } + ts.findLast = findLast; + /** Works like Array.prototype.findIndex, returning `-1` if no element satisfying the predicate is found. */ + function findIndex(array, predicate, startIndex) { + for (var i = startIndex || 0; i < array.length; i++) { + if (predicate(array[i], i)) { + return i; + } + } + return -1; + } + ts.findIndex = findIndex; + function findLastIndex(array, predicate, startIndex) { + for (var i = startIndex === undefined ? array.length - 1 : startIndex; i >= 0; i--) { + if (predicate(array[i], i)) { + return i; + } + } + return -1; + } + ts.findLastIndex = findLastIndex; + /** + * Returns the first truthy result of `callback`, or else fails. + * This is like `forEach`, but never returns undefined. + */ + function findMap(array, callback) { + for (var i = 0; i < array.length; i++) { + var result = callback(array[i], i); + if (result) { + return result; + } + } + return Debug.fail(); + } + ts.findMap = findMap; + function contains(array, value, equalityComparer) { + if (equalityComparer === void 0) { equalityComparer = equateValues; } + if (array) { + for (var _i = 0, array_1 = array; _i < array_1.length; _i++) { + var v = array_1[_i]; + if (equalityComparer(v, value)) { + return true; + } + } + } + return false; + } + ts.contains = contains; + function arraysEqual(a, b, equalityComparer) { + if (equalityComparer === void 0) { equalityComparer = equateValues; } + return a.length === b.length && a.every(function (x, i) { return equalityComparer(x, b[i]); }); + } + ts.arraysEqual = arraysEqual; + function indexOfAnyCharCode(text, charCodes, start) { + for (var i = start || 0; i < text.length; i++) { + if (contains(charCodes, text.charCodeAt(i))) { + return i; + } + } + return -1; + } + ts.indexOfAnyCharCode = indexOfAnyCharCode; + function countWhere(array, predicate) { + var count = 0; + if (array) { + for (var i = 0; i < array.length; i++) { + var v = array[i]; + if (predicate(v, i)) { + count++; + } + } + } + return count; + } + ts.countWhere = countWhere; + function filter(array, f) { + if (array) { + var len = array.length; + var i = 0; + while (i < len && f(array[i])) + i++; + if (i < len) { + var result = array.slice(0, i); + i++; + while (i < len) { + var item = array[i]; + if (f(item)) { + result.push(item); + } + i++; + } + return result; + } + } + return array; + } + ts.filter = filter; + function filterMutate(array, f) { + var outIndex = 0; + for (var i = 0; i < array.length; i++) { + if (f(array[i], i, array)) { + array[outIndex] = array[i]; + outIndex++; + } + } + array.length = outIndex; + } + ts.filterMutate = filterMutate; + function clear(array) { + array.length = 0; + } + ts.clear = clear; + function map(array, f) { + var result; + if (array) { + result = []; + for (var i = 0; i < array.length; i++) { + result.push(f(array[i], i)); + } + } + return result; + } + ts.map = map; + function mapIterator(iter, mapFn) { + return { + next: function () { + var iterRes = iter.next(); + return iterRes.done ? iterRes : { value: mapFn(iterRes.value), done: false }; + } + }; + } + ts.mapIterator = mapIterator; + function sameMap(array, f) { + if (array) { + for (var i = 0; i < array.length; i++) { + var item = array[i]; + var mapped = f(item, i); + if (item !== mapped) { + var result = array.slice(0, i); + result.push(mapped); + for (i++; i < array.length; i++) { + result.push(f(array[i], i)); + } + return result; + } + } + } + return array; + } + ts.sameMap = sameMap; + function flatten(array) { + var result; + if (array) { + result = []; + for (var _i = 0, array_2 = array; _i < array_2.length; _i++) { + var v = array_2[_i]; + if (v) { + if (isArray(v)) { + addRange(result, v); + } + else { + result.push(v); + } + } + } + } + return result; + } + ts.flatten = flatten; + /** + * Maps an array. If the mapped value is an array, it is spread into the result. + * + * @param array The array to map. + * @param mapfn The callback used to map the result into one or more values. + */ + function flatMap(array, mapfn) { + var result; + if (array) { + for (var i = 0; i < array.length; i++) { + var v = mapfn(array[i], i); + if (v) { + if (isArray(v)) { + result = addRange(result, v); + } + else { + result = append(result, v); + } + } + } + } + return result || ts.emptyArray; + } + ts.flatMap = flatMap; + function flatMapToMutable(array, mapfn) { + var result = []; + if (array) { + for (var i = 0; i < array.length; i++) { + var v = mapfn(array[i], i); + if (v) { + if (isArray(v)) { + addRange(result, v); + } + else { + result.push(v); + } + } + } + } + return result; + } + ts.flatMapToMutable = flatMapToMutable; + function flatMapIterator(iter, mapfn) { + var first = iter.next(); + if (first.done) { + return ts.emptyIterator; + } + var currentIter = getIterator(first.value); + return { + next: function () { + while (true) { + var currentRes = currentIter.next(); + if (!currentRes.done) { + return currentRes; + } + var iterRes = iter.next(); + if (iterRes.done) { + return iterRes; + } + currentIter = getIterator(iterRes.value); + } + }, + }; + function getIterator(x) { + var res = mapfn(x); + return res === undefined ? ts.emptyIterator : isArray(res) ? arrayIterator(res) : res; + } + } + ts.flatMapIterator = flatMapIterator; + function sameFlatMap(array, mapfn) { + var result; + if (array) { + for (var i = 0; i < array.length; i++) { + var item = array[i]; + var mapped = mapfn(item, i); + if (result || item !== mapped || isArray(mapped)) { + if (!result) { + result = array.slice(0, i); + } + if (isArray(mapped)) { + addRange(result, mapped); + } + else { + result.push(mapped); + } + } + } + } + return result || array; + } + ts.sameFlatMap = sameFlatMap; + function mapAllOrFail(array, mapFn) { + var result = []; + for (var i = 0; i < array.length; i++) { + var mapped = mapFn(array[i], i); + if (mapped === undefined) { + return undefined; + } + result.push(mapped); + } + return result; + } + ts.mapAllOrFail = mapAllOrFail; + function mapDefined(array, mapFn) { + var result = []; + if (array) { + for (var i = 0; i < array.length; i++) { + var mapped = mapFn(array[i], i); + if (mapped !== undefined) { + result.push(mapped); + } + } + } + return result; + } + ts.mapDefined = mapDefined; + function mapDefinedIterator(iter, mapFn) { + return { + next: function () { + while (true) { + var res = iter.next(); + if (res.done) { + return res; + } + var value = mapFn(res.value); + if (value !== undefined) { + return { value: value, done: false }; + } + } + } + }; + } + ts.mapDefinedIterator = mapDefinedIterator; + ts.emptyIterator = { next: function () { return ({ value: undefined, done: true }); } }; + function singleIterator(value) { + var done = false; + return { + next: function () { + var wasDone = done; + done = true; + return wasDone ? { value: undefined, done: true } : { value: value, done: false }; + } + }; + } + ts.singleIterator = singleIterator; + function spanMap(array, keyfn, mapfn) { + var result; + if (array) { + result = []; + var len = array.length; + var previousKey = void 0; + var key = void 0; + var start = 0; + var pos = 0; + while (start < len) { + while (pos < len) { + var value = array[pos]; + key = keyfn(value, pos); + if (pos === 0) { + previousKey = key; + } + else if (key !== previousKey) { + break; + } + pos++; + } + if (start < pos) { + var v = mapfn(array.slice(start, pos), previousKey, start, pos); + if (v) { + result.push(v); + } + start = pos; + } + previousKey = key; + pos++; + } + } + return result; + } + ts.spanMap = spanMap; + function mapEntries(map, f) { + if (!map) { + return undefined; + } + var result = createMap(); + map.forEach(function (value, key) { + var _a = f(key, value), newKey = _a[0], newValue = _a[1]; + result.set(newKey, newValue); + }); + return result; + } + ts.mapEntries = mapEntries; + function some(array, predicate) { + if (array) { + if (predicate) { + for (var _i = 0, array_3 = array; _i < array_3.length; _i++) { + var v = array_3[_i]; + if (predicate(v)) { + return true; + } + } + } + else { + return array.length > 0; + } + } + return false; + } + ts.some = some; + /** Calls the callback with (start, afterEnd) index pairs for each range where 'pred' is true. */ + function getRangesWhere(arr, pred, cb) { + var start; + for (var i = 0; i < arr.length; i++) { + if (pred(arr[i])) { + start = start === undefined ? i : start; + } + else { + if (start !== undefined) { + cb(start, i); + start = undefined; + } + } + } + if (start !== undefined) + cb(start, arr.length); + } + ts.getRangesWhere = getRangesWhere; + function concatenate(array1, array2) { + if (!some(array2)) + return array1; + if (!some(array1)) + return array2; + return array1.concat(array2); + } + ts.concatenate = concatenate; + function deduplicateRelational(array, equalityComparer, comparer) { + // Perform a stable sort of the array. This ensures the first entry in a list of + // duplicates remains the first entry in the result. + var indices = array.map(function (_, i) { return i; }); + stableSortIndices(array, indices, comparer); + var last = array[indices[0]]; + var deduplicated = [indices[0]]; + for (var i = 1; i < indices.length; i++) { + var index = indices[i]; + var item = array[index]; + if (!equalityComparer(last, item)) { + deduplicated.push(index); + last = item; + } + } + // restore original order + deduplicated.sort(); + return deduplicated.map(function (i) { return array[i]; }); + } + function deduplicateEquality(array, equalityComparer) { + var result = []; + for (var _i = 0, array_4 = array; _i < array_4.length; _i++) { + var item = array_4[_i]; + pushIfUnique(result, item, equalityComparer); + } + return result; + } + /** + * Deduplicates an unsorted array. + * @param equalityComparer An optional `EqualityComparer` used to determine if two values are duplicates. + * @param comparer An optional `Comparer` used to sort entries before comparison, though the + * result will remain in the original order in `array`. + */ + function deduplicate(array, equalityComparer, comparer) { + return array.length === 0 ? [] : + array.length === 1 ? array.slice() : + comparer ? deduplicateRelational(array, equalityComparer, comparer) : + deduplicateEquality(array, equalityComparer); + } + ts.deduplicate = deduplicate; + /** + * Deduplicates an array that has already been sorted. + */ + function deduplicateSorted(array, comparer) { + if (array.length === 0) + return ts.emptyArray; + var last = array[0]; + var deduplicated = [last]; + for (var i = 1; i < array.length; i++) { + var next = array[i]; + switch (comparer(next, last)) { + // equality comparison + case true: + // relational comparison + case 0 /* EqualTo */: + continue; + case -1 /* LessThan */: + // If `array` is sorted, `next` should **never** be less than `last`. + return Debug.fail("Array is unsorted."); + } + deduplicated.push(last = next); + } + return deduplicated; + } + function insertSorted(array, insert, compare) { + if (array.length === 0) { + array.push(insert); + return; + } + var insertIndex = binarySearch(array, insert, identity, compare); + if (insertIndex < 0) { + array.splice(~insertIndex, 0, insert); + } + } + ts.insertSorted = insertSorted; + function sortAndDeduplicate(array, comparer, equalityComparer) { + return deduplicateSorted(sort(array, comparer), equalityComparer || comparer || compareStringsCaseSensitive); + } + ts.sortAndDeduplicate = sortAndDeduplicate; + function arrayIsEqualTo(array1, array2, equalityComparer) { + if (equalityComparer === void 0) { equalityComparer = equateValues; } + if (!array1 || !array2) { + return array1 === array2; + } + if (array1.length !== array2.length) { + return false; + } + for (var i = 0; i < array1.length; i++) { + if (!equalityComparer(array1[i], array2[i], i)) { + return false; + } + } + return true; + } + ts.arrayIsEqualTo = arrayIsEqualTo; + function compact(array) { + var result; + if (array) { + for (var i = 0; i < array.length; i++) { + var v = array[i]; + if (result || !v) { + if (!result) { + result = array.slice(0, i); + } + if (v) { + result.push(v); + } + } + } + } + return result || array; + } + ts.compact = compact; + /** + * Gets the relative complement of `arrayA` with respect to `arrayB`, returning the elements that + * are not present in `arrayA` but are present in `arrayB`. Assumes both arrays are sorted + * based on the provided comparer. + */ + function relativeComplement(arrayA, arrayB, comparer) { + if (!arrayB || !arrayA || arrayB.length === 0 || arrayA.length === 0) + return arrayB; + var result = []; + loopB: for (var offsetA = 0, offsetB = 0; offsetB < arrayB.length; offsetB++) { + if (offsetB > 0) { + // Ensure `arrayB` is properly sorted. + Debug.assertGreaterThanOrEqual(comparer(arrayB[offsetB], arrayB[offsetB - 1]), 0 /* EqualTo */); + } + loopA: for (var startA = offsetA; offsetA < arrayA.length; offsetA++) { + if (offsetA > startA) { + // Ensure `arrayA` is properly sorted. We only need to perform this check if + // `offsetA` has changed since we entered the loop. + Debug.assertGreaterThanOrEqual(comparer(arrayA[offsetA], arrayA[offsetA - 1]), 0 /* EqualTo */); + } + switch (comparer(arrayB[offsetB], arrayA[offsetA])) { + case -1 /* LessThan */: + // If B is less than A, B does not exist in arrayA. Add B to the result and + // move to the next element in arrayB without changing the current position + // in arrayA. + result.push(arrayB[offsetB]); + continue loopB; + case 0 /* EqualTo */: + // If B is equal to A, B exists in arrayA. Move to the next element in + // arrayB without adding B to the result or changing the current position + // in arrayA. + continue loopB; + case 1 /* GreaterThan */: + // If B is greater than A, we need to keep looking for B in arrayA. Move to + // the next element in arrayA and recheck. + continue loopA; + } + } + } + return result; + } + ts.relativeComplement = relativeComplement; + function sum(array, prop) { + var result = 0; + for (var _i = 0, array_5 = array; _i < array_5.length; _i++) { + var v = array_5[_i]; + result += v[prop]; + } + return result; + } + ts.sum = sum; + function append(to, value) { + if (value === undefined) + return to; + if (to === undefined) + return [value]; + to.push(value); + return to; + } + ts.append = append; + /** + * Gets the actual offset into an array for a relative offset. Negative offsets indicate a + * position offset from the end of the array. + */ + function toOffset(array, offset) { + return offset < 0 ? array.length + offset : offset; + } + function addRange(to, from, start, end) { + if (from === undefined || from.length === 0) + return to; + if (to === undefined) + return from.slice(start, end); + start = start === undefined ? 0 : toOffset(from, start); + end = end === undefined ? from.length : toOffset(from, end); + for (var i = start; i < end && i < from.length; i++) { + if (from[i] !== undefined) { + to.push(from[i]); + } + } + return to; + } + ts.addRange = addRange; + /** + * @return Whether the value was added. + */ + function pushIfUnique(array, toAdd, equalityComparer) { + if (contains(array, toAdd, equalityComparer)) { + return false; + } + else { + array.push(toAdd); + return true; + } + } + ts.pushIfUnique = pushIfUnique; + /** + * Unlike `pushIfUnique`, this can take `undefined` as an input, and returns a new array. + */ + function appendIfUnique(array, toAdd, equalityComparer) { + if (array) { + pushIfUnique(array, toAdd, equalityComparer); + return array; + } + else { + return [toAdd]; + } + } + ts.appendIfUnique = appendIfUnique; + function stableSortIndices(array, indices, comparer) { + // sort indices by value then position + indices.sort(function (x, y) { return comparer(array[x], array[y]) || compareValues(x, y); }); + } + /** + * Returns a new sorted array. + */ + function sort(array, comparer) { + return (array.length === 0 ? array : array.slice().sort(comparer)); + } + ts.sort = sort; + function arrayIterator(array) { + var i = 0; + return { next: function () { + if (i === array.length) { + return { value: undefined, done: true }; + } + else { + i++; + return { value: array[i - 1], done: false }; + } + } }; + } + ts.arrayIterator = arrayIterator; + /** + * Stable sort of an array. Elements equal to each other maintain their relative position in the array. + */ + function stableSort(array, comparer) { + var indices = array.map(function (_, i) { return i; }); + stableSortIndices(array, indices, comparer); + return indices.map(function (i) { return array[i]; }); + } + ts.stableSort = stableSort; + function rangeEquals(array1, array2, pos, end) { + while (pos < end) { + if (array1[pos] !== array2[pos]) { + return false; + } + pos++; + } + return true; + } + ts.rangeEquals = rangeEquals; + /** + * Returns the element at a specific offset in an array if non-empty, `undefined` otherwise. + * A negative offset indicates the element should be retrieved from the end of the array. + */ + function elementAt(array, offset) { + if (array) { + offset = toOffset(array, offset); + if (offset < array.length) { + return array[offset]; + } + } + return undefined; + } + ts.elementAt = elementAt; + /** + * Returns the first element of an array if non-empty, `undefined` otherwise. + */ + function firstOrUndefined(array) { + return array.length === 0 ? undefined : array[0]; + } + ts.firstOrUndefined = firstOrUndefined; + function first(array) { + Debug.assert(array.length !== 0); + return array[0]; + } + ts.first = first; + /** + * Returns the last element of an array if non-empty, `undefined` otherwise. + */ + function lastOrUndefined(array) { + return array.length === 0 ? undefined : array[array.length - 1]; + } + ts.lastOrUndefined = lastOrUndefined; + function last(array) { + Debug.assert(array.length !== 0); + return array[array.length - 1]; + } + ts.last = last; + /** + * Returns the only element of an array if it contains only one element, `undefined` otherwise. + */ + function singleOrUndefined(array) { + return array && array.length === 1 + ? array[0] + : undefined; + } + ts.singleOrUndefined = singleOrUndefined; + function singleOrMany(array) { + return array && array.length === 1 + ? array[0] + : array; + } + ts.singleOrMany = singleOrMany; + function replaceElement(array, index, value) { + var result = array.slice(0); + result[index] = value; + return result; + } + ts.replaceElement = replaceElement; + /** + * Performs a binary search, finding the index at which `value` occurs in `array`. + * If no such index is found, returns the 2's-complement of first index at which + * `array[index]` exceeds `value`. + * @param array A sorted array whose first element must be no larger than number + * @param value The value to be searched for in the array. + * @param keySelector A callback used to select the search key from `value` and each element of + * `array`. + * @param keyComparer A callback used to compare two keys in a sorted array. + * @param offset An offset into `array` at which to start the search. + */ + function binarySearch(array, value, keySelector, keyComparer, offset) { + return binarySearchKey(array, keySelector(value), keySelector, keyComparer, offset); + } + ts.binarySearch = binarySearch; + /** + * Performs a binary search, finding the index at which an object with `key` occurs in `array`. + * If no such index is found, returns the 2's-complement of first index at which + * `array[index]` exceeds `key`. + * @param array A sorted array whose first element must be no larger than number + * @param key The key to be searched for in the array. + * @param keySelector A callback used to select the search key from each element of `array`. + * @param keyComparer A callback used to compare two keys in a sorted array. + * @param offset An offset into `array` at which to start the search. + */ + function binarySearchKey(array, key, keySelector, keyComparer, offset) { + if (!some(array)) { + return -1; + } + var low = offset || 0; + var high = array.length - 1; + while (low <= high) { + var middle = low + ((high - low) >> 1); + var midKey = keySelector(array[middle]); + switch (keyComparer(midKey, key)) { + case -1 /* LessThan */: + low = middle + 1; + break; + case 0 /* EqualTo */: + return middle; + case 1 /* GreaterThan */: + high = middle - 1; + break; + } + } + return ~low; + } + ts.binarySearchKey = binarySearchKey; + function reduceLeft(array, f, initial, start, count) { + if (array && array.length > 0) { + var size = array.length; + if (size > 0) { + var pos = start === undefined || start < 0 ? 0 : start; + var end = count === undefined || pos + count > size - 1 ? size - 1 : pos + count; + var result = void 0; + if (arguments.length <= 2) { + result = array[pos]; + pos++; + } + else { + result = initial; + } + while (pos <= end) { + result = f(result, array[pos], pos); + pos++; + } + return result; + } + } + return initial; + } + ts.reduceLeft = reduceLeft; + var hasOwnProperty = Object.prototype.hasOwnProperty; + /** + * Indicates whether a map-like contains an own property with the specified key. + * + * @param map A map-like. + * @param key A property key. + */ + function hasProperty(map, key) { + return hasOwnProperty.call(map, key); + } + ts.hasProperty = hasProperty; + /** + * Gets the value of an owned property in a map-like. + * + * @param map A map-like. + * @param key A property key. + */ + function getProperty(map, key) { + return hasOwnProperty.call(map, key) ? map[key] : undefined; + } + ts.getProperty = getProperty; + /** + * Gets the owned, enumerable property keys of a map-like. + */ + function getOwnKeys(map) { + var keys = []; + for (var key in map) { + if (hasOwnProperty.call(map, key)) { + keys.push(key); + } + } + return keys; + } + ts.getOwnKeys = getOwnKeys; + function getOwnValues(sparseArray) { + var values = []; + for (var key in sparseArray) { + if (hasOwnProperty.call(sparseArray, key)) { + values.push(sparseArray[key]); + } + } + return values; + } + ts.getOwnValues = getOwnValues; + function arrayFrom(iterator, map) { + var _a; + var result = []; + for (var _b = iterator.next(), value = _b.value, done = _b.done; !done; _a = iterator.next(), value = _a.value, done = _a.done, _a) { + result.push(map ? map(value) : value); + } + return result; + } + ts.arrayFrom = arrayFrom; + function assign(t) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + for (var _a = 0, args_1 = args; _a < args_1.length; _a++) { + var arg = args_1[_a]; + for (var p in arg) { + if (hasProperty(arg, p)) { + t[p] = arg[p]; // TODO: GH#23368 + } + } + } + return t; + } + ts.assign = assign; + /** + * Performs a shallow equality comparison of the contents of two map-likes. + * + * @param left A map-like whose properties should be compared. + * @param right A map-like whose properties should be compared. + */ + function equalOwnProperties(left, right, equalityComparer) { + if (equalityComparer === void 0) { equalityComparer = equateValues; } + if (left === right) + return true; + if (!left || !right) + return false; + for (var key in left) { + if (hasOwnProperty.call(left, key)) { + if (!hasOwnProperty.call(right, key)) + return false; + if (!equalityComparer(left[key], right[key])) + return false; + } + } + for (var key in right) { + if (hasOwnProperty.call(right, key)) { + if (!hasOwnProperty.call(left, key)) + return false; + } + } + return true; + } + ts.equalOwnProperties = equalOwnProperties; + function arrayToMap(array, makeKey, makeValue) { + if (makeValue === void 0) { makeValue = identity; } + var result = createMap(); + for (var _i = 0, array_6 = array; _i < array_6.length; _i++) { + var value = array_6[_i]; + var key = makeKey(value); + if (key !== undefined) + result.set(key, makeValue(value)); + } + return result; + } + ts.arrayToMap = arrayToMap; + function arrayToNumericMap(array, makeKey, makeValue) { + if (makeValue === void 0) { makeValue = identity; } + var result = []; + for (var _i = 0, array_7 = array; _i < array_7.length; _i++) { + var value = array_7[_i]; + result[makeKey(value)] = makeValue(value); + } + return result; + } + ts.arrayToNumericMap = arrayToNumericMap; + function arrayToMultiMap(values, makeKey, makeValue) { + if (makeValue === void 0) { makeValue = identity; } + var result = createMultiMap(); + for (var _i = 0, values_1 = values; _i < values_1.length; _i++) { + var value = values_1[_i]; + result.add(makeKey(value), makeValue(value)); + } + return result; + } + ts.arrayToMultiMap = arrayToMultiMap; + function group(values, getGroupId) { + return arrayFrom(arrayToMultiMap(values, getGroupId).values()); + } + ts.group = group; + function clone(object) { + var result = {}; + for (var id in object) { + if (hasOwnProperty.call(object, id)) { + result[id] = object[id]; + } + } + return result; + } + ts.clone = clone; + function extend(first, second) { + var result = {}; + for (var id in second) { + if (hasOwnProperty.call(second, id)) { + result[id] = second[id]; + } + } + for (var id in first) { + if (hasOwnProperty.call(first, id)) { + result[id] = first[id]; + } + } + return result; + } + ts.extend = extend; + function createMultiMap() { + var map = createMap(); + map.add = multiMapAdd; + map.remove = multiMapRemove; + return map; + } + ts.createMultiMap = createMultiMap; + function multiMapAdd(key, value) { + var values = this.get(key); + if (values) { + values.push(value); + } + else { + this.set(key, values = [value]); + } + return values; + } + function multiMapRemove(key, value) { + var values = this.get(key); + if (values) { + unorderedRemoveItem(values, value); + if (!values.length) { + this.delete(key); + } + } + } + /** + * Tests whether a value is an array. + */ + function isArray(value) { + return Array.isArray ? Array.isArray(value) : value instanceof Array; + } + ts.isArray = isArray; + function toArray(value) { + return isArray(value) ? value : [value]; + } + ts.toArray = toArray; + /** + * Tests whether a value is string + */ + function isString(text) { + return typeof text === "string"; + } + ts.isString = isString; + function isNumber(x) { + return typeof x === "number"; + } + ts.isNumber = isNumber; + function tryCast(value, test) { + return value !== undefined && test(value) ? value : undefined; + } + ts.tryCast = tryCast; + function cast(value, test) { + if (value !== undefined && test(value)) + return value; + return Debug.fail("Invalid cast. The supplied value " + value + " did not pass the test '" + Debug.getFunctionName(test) + "'."); + } + ts.cast = cast; + /** Does nothing. */ + function noop(_) { } // tslint:disable-line no-empty + ts.noop = noop; + /** Do nothing and return false */ + function returnFalse() { return false; } + ts.returnFalse = returnFalse; + /** Do nothing and return true */ + function returnTrue() { return true; } + ts.returnTrue = returnTrue; + /** Returns its argument. */ + function identity(x) { return x; } + ts.identity = identity; + /** Returns lower case string */ + function toLowerCase(x) { return x.toLowerCase(); } + ts.toLowerCase = toLowerCase; + /** Throws an error because a function is not implemented. */ + function notImplemented() { + throw new Error("Not implemented"); + } + ts.notImplemented = notImplemented; + function memoize(callback) { + var value; + return function () { + if (callback) { + value = callback(); + callback = undefined; + } + return value; + }; + } + ts.memoize = memoize; + function chain(a, b, c, d, e) { + if (e) { + var args_2 = []; + for (var i = 0; i < arguments.length; i++) { + args_2[i] = arguments[i]; + } + return function (t) { return compose.apply(void 0, map(args_2, function (f) { return f(t); })); }; + } + else if (d) { + return function (t) { return compose(a(t), b(t), c(t), d(t)); }; + } + else if (c) { + return function (t) { return compose(a(t), b(t), c(t)); }; + } + else if (b) { + return function (t) { return compose(a(t), b(t)); }; + } + else if (a) { + return function (t) { return compose(a(t)); }; + } + else { + return function (_) { return function (u) { return u; }; }; + } + } + ts.chain = chain; + function compose(a, b, c, d, e) { + if (e) { + var args_3 = []; + for (var i = 0; i < arguments.length; i++) { + args_3[i] = arguments[i]; + } + return function (t) { return reduceLeft(args_3, function (u, f) { return f(u); }, t); }; + } + else if (d) { + return function (t) { return d(c(b(a(t)))); }; + } + else if (c) { + return function (t) { return c(b(a(t))); }; + } + else if (b) { + return function (t) { return b(a(t)); }; + } + else if (a) { + return function (t) { return a(t); }; + } + else { + return function (t) { return t; }; + } + } + ts.compose = compose; + var AssertionLevel; + (function (AssertionLevel) { + AssertionLevel[AssertionLevel["None"] = 0] = "None"; + AssertionLevel[AssertionLevel["Normal"] = 1] = "Normal"; + AssertionLevel[AssertionLevel["Aggressive"] = 2] = "Aggressive"; + AssertionLevel[AssertionLevel["VeryAggressive"] = 3] = "VeryAggressive"; + })(AssertionLevel = ts.AssertionLevel || (ts.AssertionLevel = {})); + var Debug; + (function (Debug) { + Debug.currentAssertionLevel = 0 /* None */; + Debug.isDebugging = false; + function shouldAssert(level) { + return Debug.currentAssertionLevel >= level; + } + Debug.shouldAssert = shouldAssert; + function assert(expression, message, verboseDebugInfo, stackCrawlMark) { + if (!expression) { + if (verboseDebugInfo) { + message += "\r\nVerbose Debug Information: " + (typeof verboseDebugInfo === "string" ? verboseDebugInfo : verboseDebugInfo()); + } + fail(message ? "False expression: " + message : "False expression.", stackCrawlMark || assert); + } + } + Debug.assert = assert; + function assertEqual(a, b, msg, msg2) { + if (a !== b) { + var message = msg ? msg2 ? msg + " " + msg2 : msg : ""; + fail("Expected " + a + " === " + b + ". " + message); + } + } + Debug.assertEqual = assertEqual; + function assertLessThan(a, b, msg) { + if (a >= b) { + fail("Expected " + a + " < " + b + ". " + (msg || "")); + } + } + Debug.assertLessThan = assertLessThan; + function assertLessThanOrEqual(a, b) { + if (a > b) { + fail("Expected " + a + " <= " + b); + } + } + Debug.assertLessThanOrEqual = assertLessThanOrEqual; + function assertGreaterThanOrEqual(a, b) { + if (a < b) { + fail("Expected " + a + " >= " + b); + } + } + Debug.assertGreaterThanOrEqual = assertGreaterThanOrEqual; + function fail(message, stackCrawlMark) { + debugger; + var e = new Error(message ? "Debug Failure. " + message : "Debug Failure."); + if (Error.captureStackTrace) { + Error.captureStackTrace(e, stackCrawlMark || fail); + } + throw e; + } + Debug.fail = fail; + function assertDefined(value, message) { + if (value === undefined || value === null) + return fail(message); + return value; + } + Debug.assertDefined = assertDefined; + function assertEachDefined(value, message) { + for (var _i = 0, value_1 = value; _i < value_1.length; _i++) { + var v = value_1[_i]; + assertDefined(v, message); + } + return value; + } + Debug.assertEachDefined = assertEachDefined; + function assertNever(member, message, stackCrawlMark) { + if (message === void 0) { message = "Illegal value:"; } + var detail = "kind" in member && "pos" in member ? "SyntaxKind: " + Debug.showSyntaxKind(member) : JSON.stringify(member); + return fail(message + " " + detail, stackCrawlMark || assertNever); + } + Debug.assertNever = assertNever; + function getFunctionName(func) { + if (typeof func !== "function") { + return ""; + } + else if (func.hasOwnProperty("name")) { + return func.name; + } + else { + var text = Function.prototype.toString.call(func); + var match = /^function\s+([\w\$]+)\s*\(/.exec(text); + return match ? match[1] : ""; + } + } + Debug.getFunctionName = getFunctionName; + })(Debug = ts.Debug || (ts.Debug = {})); + function equateValues(a, b) { + return a === b; + } + ts.equateValues = equateValues; + /** + * Compare the equality of two strings using a case-sensitive ordinal comparison. + * + * Case-sensitive comparisons compare both strings one code-point at a time using the integer + * value of each code-point after applying `toUpperCase` to each string. We always map both + * strings to their upper-case form as some unicode characters do not properly round-trip to + * lowercase (such as `ẞ` (German sharp capital s)). + */ + function equateStringsCaseInsensitive(a, b) { + return a === b + || a !== undefined + && b !== undefined + && a.toUpperCase() === b.toUpperCase(); + } + ts.equateStringsCaseInsensitive = equateStringsCaseInsensitive; + /** + * Compare the equality of two strings using a case-sensitive ordinal comparison. + * + * Case-sensitive comparisons compare both strings one code-point at a time using the + * integer value of each code-point. + */ + function equateStringsCaseSensitive(a, b) { + return equateValues(a, b); + } + ts.equateStringsCaseSensitive = equateStringsCaseSensitive; + function compareComparableValues(a, b) { + return a === b ? 0 /* EqualTo */ : + a === undefined ? -1 /* LessThan */ : + b === undefined ? 1 /* GreaterThan */ : + a < b ? -1 /* LessThan */ : + 1 /* GreaterThan */; + } + /** + * Compare two numeric values for their order relative to each other. + * To compare strings, use any of the `compareStrings` functions. + */ + function compareValues(a, b) { + return compareComparableValues(a, b); + } + ts.compareValues = compareValues; + function min(a, b, compare) { + return compare(a, b) === -1 /* LessThan */ ? a : b; + } + ts.min = min; + /** + * Compare two strings using a case-insensitive ordinal comparison. + * + * Ordinal comparisons are based on the difference between the unicode code points of both + * strings. Characters with multiple unicode representations are considered unequal. Ordinal + * comparisons provide predictable ordering, but place "a" after "B". + * + * Case-insensitive comparisons compare both strings one code-point at a time using the integer + * value of each code-point after applying `toUpperCase` to each string. We always map both + * strings to their upper-case form as some unicode characters do not properly round-trip to + * lowercase (such as `ẞ` (German sharp capital s)). + */ + function compareStringsCaseInsensitive(a, b) { + if (a === b) + return 0 /* EqualTo */; + if (a === undefined) + return -1 /* LessThan */; + if (b === undefined) + return 1 /* GreaterThan */; + a = a.toUpperCase(); + b = b.toUpperCase(); + return a < b ? -1 /* LessThan */ : a > b ? 1 /* GreaterThan */ : 0 /* EqualTo */; + } + ts.compareStringsCaseInsensitive = compareStringsCaseInsensitive; + /** + * Compare two strings using a case-sensitive ordinal comparison. + * + * Ordinal comparisons are based on the difference between the unicode code points of both + * strings. Characters with multiple unicode representations are considered unequal. Ordinal + * comparisons provide predictable ordering, but place "a" after "B". + * + * Case-sensitive comparisons compare both strings one code-point at a time using the integer + * value of each code-point. + */ + function compareStringsCaseSensitive(a, b) { + return compareComparableValues(a, b); + } + ts.compareStringsCaseSensitive = compareStringsCaseSensitive; + function getStringComparer(ignoreCase) { + return ignoreCase ? compareStringsCaseInsensitive : compareStringsCaseSensitive; + } + ts.getStringComparer = getStringComparer; + /** + * Creates a string comparer for use with string collation in the UI. + */ + var createUIStringComparer = (function () { + var defaultComparer; + var enUSComparer; + var stringComparerFactory = getStringComparerFactory(); + return createStringComparer; + function compareWithCallback(a, b, comparer) { + if (a === b) + return 0 /* EqualTo */; + if (a === undefined) + return -1 /* LessThan */; + if (b === undefined) + return 1 /* GreaterThan */; + var value = comparer(a, b); + return value < 0 ? -1 /* LessThan */ : value > 0 ? 1 /* GreaterThan */ : 0 /* EqualTo */; + } + function createIntlCollatorStringComparer(locale) { + // Intl.Collator.prototype.compare is bound to the collator. See NOTE in + // http://www.ecma-international.org/ecma-402/2.0/#sec-Intl.Collator.prototype.compare + var comparer = new Intl.Collator(locale, { usage: "sort", sensitivity: "variant" }).compare; + return function (a, b) { return compareWithCallback(a, b, comparer); }; + } + function createLocaleCompareStringComparer(locale) { + // if the locale is not the default locale (`undefined`), use the fallback comparer. + if (locale !== undefined) + return createFallbackStringComparer(); + return function (a, b) { return compareWithCallback(a, b, compareStrings); }; + function compareStrings(a, b) { + return a.localeCompare(b); + } + } + function createFallbackStringComparer() { + // An ordinal comparison puts "A" after "b", but for the UI we want "A" before "b". + // We first sort case insensitively. So "Aaa" will come before "baa". + // Then we sort case sensitively, so "aaa" will come before "Aaa". + // + // For case insensitive comparisons we always map both strings to their + // upper-case form as some unicode characters do not properly round-trip to + // lowercase (such as `ẞ` (German sharp capital s)). + return function (a, b) { return compareWithCallback(a, b, compareDictionaryOrder); }; + function compareDictionaryOrder(a, b) { + return compareStrings(a.toUpperCase(), b.toUpperCase()) || compareStrings(a, b); + } + function compareStrings(a, b) { + return a < b ? -1 /* LessThan */ : a > b ? 1 /* GreaterThan */ : 0 /* EqualTo */; + } + } + function getStringComparerFactory() { + // If the host supports Intl, we use it for comparisons using the default locale. + if (typeof Intl === "object" && typeof Intl.Collator === "function") { + return createIntlCollatorStringComparer; + } + // If the host does not support Intl, we fall back to localeCompare. + // localeCompare in Node v0.10 is just an ordinal comparison, so don't use it. + if (typeof String.prototype.localeCompare === "function" && + typeof String.prototype.toLocaleUpperCase === "function" && + "a".localeCompare("B") < 0) { + return createLocaleCompareStringComparer; + } + // Otherwise, fall back to ordinal comparison: + return createFallbackStringComparer; + } + function createStringComparer(locale) { + // Hold onto common string comparers. This avoids constantly reallocating comparers during + // tests. + if (locale === undefined) { + return defaultComparer || (defaultComparer = stringComparerFactory(locale)); + } + else if (locale === "en-US") { + return enUSComparer || (enUSComparer = stringComparerFactory(locale)); + } + else { + return stringComparerFactory(locale); + } + } + })(); + var uiComparerCaseSensitive; + var uiLocale; + function getUILocale() { + return uiLocale; + } + ts.getUILocale = getUILocale; + function setUILocale(value) { + if (uiLocale !== value) { + uiLocale = value; + uiComparerCaseSensitive = undefined; + } + } + ts.setUILocale = setUILocale; + /** + * Compare two strings in a using the case-sensitive sort behavior of the UI locale. + * + * Ordering is not predictable between different host locales, but is best for displaying + * ordered data for UI presentation. Characters with multiple unicode representations may + * be considered equal. + * + * Case-sensitive comparisons compare strings that differ in base characters, or + * accents/diacritic marks, or case as unequal. + */ + function compareStringsCaseSensitiveUI(a, b) { + var comparer = uiComparerCaseSensitive || (uiComparerCaseSensitive = createUIStringComparer(uiLocale)); + return comparer(a, b); + } + ts.compareStringsCaseSensitiveUI = compareStringsCaseSensitiveUI; + function compareProperties(a, b, key, comparer) { + return a === b ? 0 /* EqualTo */ : + a === undefined ? -1 /* LessThan */ : + b === undefined ? 1 /* GreaterThan */ : + comparer(a[key], b[key]); + } + ts.compareProperties = compareProperties; + /** True is greater than false. */ + function compareBooleans(a, b) { + return compareValues(a ? 1 : 0, b ? 1 : 0); + } + ts.compareBooleans = compareBooleans; + /** + * Given a name and a list of names that are *not* equal to the name, return a spelling suggestion if there is one that is close enough. + * Names less than length 3 only check for case-insensitive equality, not Levenshtein distance. + * + * If there is a candidate that's the same except for case, return that. + * If there is a candidate that's within one edit of the name, return that. + * Otherwise, return the candidate with the smallest Levenshtein distance, + * except for candidates: + * * With no name + * * Whose length differs from the target name by more than 0.34 of the length of the name. + * * Whose levenshtein distance is more than 0.4 of the length of the name + * (0.4 allows 1 substitution/transposition for every 5 characters, + * and 1 insertion/deletion at 3 characters) + */ + function getSpellingSuggestion(name, candidates, getName) { + var maximumLengthDifference = Math.min(2, Math.floor(name.length * 0.34)); + var bestDistance = Math.floor(name.length * 0.4) + 1; // If the best result isn't better than this, don't bother. + var bestCandidate; + var justCheckExactMatches = false; + var nameLowerCase = name.toLowerCase(); + for (var _i = 0, candidates_1 = candidates; _i < candidates_1.length; _i++) { + var candidate = candidates_1[_i]; + var candidateName = getName(candidate); + if (candidateName !== undefined && Math.abs(candidateName.length - nameLowerCase.length) <= maximumLengthDifference) { + var candidateNameLowerCase = candidateName.toLowerCase(); + if (candidateNameLowerCase === nameLowerCase) { + if (candidateName === name) { + continue; + } + return candidate; + } + if (justCheckExactMatches) { + continue; + } + if (candidateName.length < 3) { + // Don't bother, user would have noticed a 2-character name having an extra character + continue; + } + // Only care about a result better than the best so far. + var distance = levenshteinWithMax(nameLowerCase, candidateNameLowerCase, bestDistance - 1); + if (distance === undefined) { + continue; + } + if (distance < 3) { + justCheckExactMatches = true; + bestCandidate = candidate; + } + else { + Debug.assert(distance < bestDistance); // Else `levenshteinWithMax` should return undefined + bestDistance = distance; + bestCandidate = candidate; + } + } + } + return bestCandidate; + } + ts.getSpellingSuggestion = getSpellingSuggestion; + function levenshteinWithMax(s1, s2, max) { + var previous = new Array(s2.length + 1); + var current = new Array(s2.length + 1); + /** Represents any value > max. We don't care about the particular value. */ + var big = max + 1; + for (var i = 0; i <= s2.length; i++) { + previous[i] = i; + } + for (var i = 1; i <= s1.length; i++) { + var c1 = s1.charCodeAt(i - 1); + var minJ = i > max ? i - max : 1; + var maxJ = s2.length > max + i ? max + i : s2.length; + current[0] = i; + /** Smallest value of the matrix in the ith column. */ + var colMin = i; + for (var j = 1; j < minJ; j++) { + current[j] = big; + } + for (var j = minJ; j <= maxJ; j++) { + var dist = c1 === s2.charCodeAt(j - 1) + ? previous[j - 1] + : Math.min(/*delete*/ previous[j] + 1, /*insert*/ current[j - 1] + 1, /*substitute*/ previous[j - 1] + 2); + current[j] = dist; + colMin = Math.min(colMin, dist); + } + for (var j = maxJ + 1; j <= s2.length; j++) { + current[j] = big; + } + if (colMin > max) { + // Give up -- everything in this column is > max and it can't get better in future columns. + return undefined; + } + var temp = previous; + previous = current; + current = temp; + } + var res = previous[s2.length]; + return res > max ? undefined : res; + } + function endsWith(str, suffix) { + var expectedPos = str.length - suffix.length; + return expectedPos >= 0 && str.indexOf(suffix, expectedPos) === expectedPos; + } + ts.endsWith = endsWith; + function removeSuffix(str, suffix) { + return endsWith(str, suffix) ? str.slice(0, str.length - suffix.length) : str; + } + ts.removeSuffix = removeSuffix; + function tryRemoveSuffix(str, suffix) { + return endsWith(str, suffix) ? str.slice(0, str.length - suffix.length) : undefined; + } + ts.tryRemoveSuffix = tryRemoveSuffix; + function stringContains(str, substring) { + return str.indexOf(substring) !== -1; + } + ts.stringContains = stringContains; + function fileExtensionIs(path, extension) { + return path.length > extension.length && endsWith(path, extension); + } + ts.fileExtensionIs = fileExtensionIs; + function fileExtensionIsOneOf(path, extensions) { + for (var _i = 0, extensions_1 = extensions; _i < extensions_1.length; _i++) { + var extension = extensions_1[_i]; + if (fileExtensionIs(path, extension)) { + return true; + } + } + return false; + } + ts.fileExtensionIsOneOf = fileExtensionIsOneOf; + /** + * Takes a string like "jquery-min.4.2.3" and returns "jquery" + */ + function removeMinAndVersionNumbers(fileName) { + // Match a "." or "-" followed by a version number or 'min' at the end of the name + var trailingMinOrVersion = /[.-]((min)|(\d+(\.\d+)*))$/; + // The "min" or version may both be present, in either order, so try applying the above twice. + return fileName.replace(trailingMinOrVersion, "").replace(trailingMinOrVersion, ""); + } + ts.removeMinAndVersionNumbers = removeMinAndVersionNumbers; + /** Remove an item from an array, moving everything to its right one space left. */ + function orderedRemoveItem(array, item) { + for (var i = 0; i < array.length; i++) { + if (array[i] === item) { + orderedRemoveItemAt(array, i); + return true; + } + } + return false; + } + ts.orderedRemoveItem = orderedRemoveItem; + /** Remove an item by index from an array, moving everything to its right one space left. */ + function orderedRemoveItemAt(array, index) { + // This seems to be faster than either `array.splice(i, 1)` or `array.copyWithin(i, i+ 1)`. + for (var i = index; i < array.length - 1; i++) { + array[i] = array[i + 1]; + } + array.pop(); + } + ts.orderedRemoveItemAt = orderedRemoveItemAt; + function unorderedRemoveItemAt(array, index) { + // Fill in the "hole" left at `index`. + array[index] = array[array.length - 1]; + array.pop(); + } + ts.unorderedRemoveItemAt = unorderedRemoveItemAt; + /** Remove the *first* occurrence of `item` from the array. */ + function unorderedRemoveItem(array, item) { + return unorderedRemoveFirstItemWhere(array, function (element) { return element === item; }); + } + ts.unorderedRemoveItem = unorderedRemoveItem; + /** Remove the *first* element satisfying `predicate`. */ + function unorderedRemoveFirstItemWhere(array, predicate) { + for (var i = 0; i < array.length; i++) { + if (predicate(array[i])) { + unorderedRemoveItemAt(array, i); + return true; + } + } + return false; + } + function createGetCanonicalFileName(useCaseSensitiveFileNames) { + return useCaseSensitiveFileNames ? identity : toLowerCase; + } + ts.createGetCanonicalFileName = createGetCanonicalFileName; + function patternText(_a) { + var prefix = _a.prefix, suffix = _a.suffix; + return prefix + "*" + suffix; + } + ts.patternText = patternText; + /** + * Given that candidate matches pattern, returns the text matching the '*'. + * E.g.: matchedText(tryParsePattern("foo*baz"), "foobarbaz") === "bar" + */ + function matchedText(pattern, candidate) { + Debug.assert(isPatternMatch(pattern, candidate)); + return candidate.substring(pattern.prefix.length, candidate.length - pattern.suffix.length); + } + ts.matchedText = matchedText; + /** Return the object corresponding to the best pattern to match `candidate`. */ + function findBestPatternMatch(values, getPattern, candidate) { + var matchedValue; + // use length of prefix as betterness criteria + var longestMatchPrefixLength = -1; + for (var _i = 0, values_2 = values; _i < values_2.length; _i++) { + var v = values_2[_i]; + var pattern = getPattern(v); + if (isPatternMatch(pattern, candidate) && pattern.prefix.length > longestMatchPrefixLength) { + longestMatchPrefixLength = pattern.prefix.length; + matchedValue = v; + } + } + return matchedValue; + } + ts.findBestPatternMatch = findBestPatternMatch; + function startsWith(str, prefix) { + return str.lastIndexOf(prefix, 0) === 0; + } + ts.startsWith = startsWith; + function removePrefix(str, prefix) { + return startsWith(str, prefix) ? str.substr(prefix.length) : str; + } + ts.removePrefix = removePrefix; + function tryRemovePrefix(str, prefix, getCanonicalFileName) { + if (getCanonicalFileName === void 0) { getCanonicalFileName = identity; } + return startsWith(getCanonicalFileName(str), getCanonicalFileName(prefix)) ? str.substring(prefix.length) : undefined; + } + ts.tryRemovePrefix = tryRemovePrefix; + function isPatternMatch(_a, candidate) { + var prefix = _a.prefix, suffix = _a.suffix; + return candidate.length >= prefix.length + suffix.length && + startsWith(candidate, prefix) && + endsWith(candidate, suffix); + } + function and(f, g) { + return function (arg) { return f(arg) && g(arg); }; + } + ts.and = and; + function or(f, g) { + return function (arg) { return f(arg) || g(arg); }; + } + ts.or = or; + function assertType(_) { } // tslint:disable-line no-empty + ts.assertType = assertType; + function singleElementArray(t) { + return t === undefined ? undefined : [t]; + } + ts.singleElementArray = singleElementArray; + function enumerateInsertsAndDeletes(newItems, oldItems, comparer, inserted, deleted, unchanged) { + unchanged = unchanged || noop; + var newIndex = 0; + var oldIndex = 0; + var newLen = newItems.length; + var oldLen = oldItems.length; + while (newIndex < newLen && oldIndex < oldLen) { + var newItem = newItems[newIndex]; + var oldItem = oldItems[oldIndex]; + var compareResult = comparer(newItem, oldItem); + if (compareResult === -1 /* LessThan */) { + inserted(newItem); + newIndex++; + } + else if (compareResult === 1 /* GreaterThan */) { + deleted(oldItem); + oldIndex++; + } + else { + unchanged(oldItem, newItem); + newIndex++; + oldIndex++; + } + } + while (newIndex < newLen) { + inserted(newItems[newIndex++]); + } + while (oldIndex < oldLen) { + deleted(oldItems[oldIndex++]); + } + } + ts.enumerateInsertsAndDeletes = enumerateInsertsAndDeletes; + function fill(length, cb) { + return new Array(length).fill(0).map(function (_, i) { return cb(i); }); + } + ts.fill = fill; +})(ts || (ts = {})); +/*@internal*/ +var ts; +(function (ts) { + /** Gets a timestamp with (at least) ms resolution */ + ts.timestamp = typeof performance !== "undefined" && performance.now ? function () { return performance.now(); } : Date.now ? Date.now : function () { return +(new Date()); }; +})(ts || (ts = {})); +/*@internal*/ +/** Performance measurements for the compiler. */ +(function (ts) { + var performance; + (function (performance) { + // NOTE: cannot use ts.noop as core.ts loads after this + var profilerEvent = typeof onProfilerEvent === "function" && onProfilerEvent.profiler === true ? onProfilerEvent : function () { }; + var enabled = false; + var profilerStart = 0; + var counts; + var marks; + var measures; + function createTimerIf(condition, measureName, startMarkName, endMarkName) { + return condition ? createTimer(measureName, startMarkName, endMarkName) : performance.nullTimer; + } + performance.createTimerIf = createTimerIf; + function createTimer(measureName, startMarkName, endMarkName) { + var enterCount = 0; + return { + enter: enter, + exit: exit + }; + function enter() { + if (++enterCount === 1) { + mark(startMarkName); + } + } + function exit() { + if (--enterCount === 0) { + mark(endMarkName); + measure(measureName, startMarkName, endMarkName); + } + else if (enterCount < 0) { + ts.Debug.fail("enter/exit count does not match."); + } + } + } + performance.createTimer = createTimer; + performance.nullTimer = { enter: ts.noop, exit: ts.noop }; + /** + * Marks a performance event. + * + * @param markName The name of the mark. + */ + function mark(markName) { + if (enabled) { + marks.set(markName, ts.timestamp()); + counts.set(markName, (counts.get(markName) || 0) + 1); + profilerEvent(markName); + } + } + performance.mark = mark; + /** + * Adds a performance measurement with the specified name. + * + * @param measureName The name of the performance measurement. + * @param startMarkName The name of the starting mark. If not supplied, the point at which the + * profiler was enabled is used. + * @param endMarkName The name of the ending mark. If not supplied, the current timestamp is + * used. + */ + function measure(measureName, startMarkName, endMarkName) { + if (enabled) { + var end = endMarkName && marks.get(endMarkName) || ts.timestamp(); + var start = startMarkName && marks.get(startMarkName) || profilerStart; + measures.set(measureName, (measures.get(measureName) || 0) + (end - start)); + } + } + performance.measure = measure; + /** + * Gets the number of times a marker was encountered. + * + * @param markName The name of the mark. + */ + function getCount(markName) { + return counts && counts.get(markName) || 0; + } + performance.getCount = getCount; + /** + * Gets the total duration of all measurements with the supplied name. + * + * @param measureName The name of the measure whose durations should be accumulated. + */ + function getDuration(measureName) { + return measures && measures.get(measureName) || 0; + } + performance.getDuration = getDuration; + /** + * Iterate over each measure, performing some action + * + * @param cb The action to perform for each measure + */ + function forEachMeasure(cb) { + measures.forEach(function (measure, key) { + cb(key, measure); + }); + } + performance.forEachMeasure = forEachMeasure; + /** Enables (and resets) performance measurements for the compiler. */ + function enable() { + counts = ts.createMap(); + marks = ts.createMap(); + measures = ts.createMap(); + enabled = true; + profilerStart = ts.timestamp(); + } + performance.enable = enable; + /** Disables performance measurements for the compiler. */ + function disable() { + enabled = false; + } + performance.disable = disable; + })(performance = ts.performance || (ts.performance = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + // https://semver.org/#spec-item-2 + // > A normal version number MUST take the form X.Y.Z where X, Y, and Z are non-negative + // > integers, and MUST NOT contain leading zeroes. X is the major version, Y is the minor + // > version, and Z is the patch version. Each element MUST increase numerically. + // + // NOTE: We differ here in that we allow X and X.Y, with missing parts having the default + // value of `0`. + var versionRegExp = /^(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\-([a-z0-9-.]+))?(?:\+([a-z0-9-.]+))?)?)?$/i; + // https://semver.org/#spec-item-9 + // > A pre-release version MAY be denoted by appending a hyphen and a series of dot separated + // > identifiers immediately following the patch version. Identifiers MUST comprise only ASCII + // > alphanumerics and hyphen [0-9A-Za-z-]. Identifiers MUST NOT be empty. Numeric identifiers + // > MUST NOT include leading zeroes. + var prereleaseRegExp = /^(?:0|[1-9]\d*|[a-z-][a-z0-9-]*)(?:\.(?:0|[1-9]\d*|[a-z-][a-z0-9-]*))*$/i; + // https://semver.org/#spec-item-10 + // > Build metadata MAY be denoted by appending a plus sign and a series of dot separated + // > identifiers immediately following the patch or pre-release version. Identifiers MUST + // > comprise only ASCII alphanumerics and hyphen [0-9A-Za-z-]. Identifiers MUST NOT be empty. + var buildRegExp = /^[a-z0-9-]+(?:\.[a-z0-9-]+)*$/i; + // https://semver.org/#spec-item-9 + // > Numeric identifiers MUST NOT include leading zeroes. + var numericIdentifierRegExp = /^(0|[1-9]\d*)$/; + /** + * Describes a precise semantic version number, https://semver.org + */ + var Version = /** @class */ (function () { + function Version(major, minor, patch, prerelease, build) { + if (minor === void 0) { minor = 0; } + if (patch === void 0) { patch = 0; } + if (prerelease === void 0) { prerelease = ""; } + if (build === void 0) { build = ""; } + if (typeof major === "string") { + var result = ts.Debug.assertDefined(tryParseComponents(major), "Invalid version"); + (major = result.major, minor = result.minor, patch = result.patch, prerelease = result.prerelease, build = result.build); + } + ts.Debug.assert(major >= 0, "Invalid argument: major"); + ts.Debug.assert(minor >= 0, "Invalid argument: minor"); + ts.Debug.assert(patch >= 0, "Invalid argument: patch"); + ts.Debug.assert(!prerelease || prereleaseRegExp.test(prerelease), "Invalid argument: prerelease"); + ts.Debug.assert(!build || buildRegExp.test(build), "Invalid argument: build"); + this.major = major; + this.minor = minor; + this.patch = patch; + this.prerelease = prerelease ? prerelease.split(".") : ts.emptyArray; + this.build = build ? build.split(".") : ts.emptyArray; + } + Version.tryParse = function (text) { + var result = tryParseComponents(text); + if (!result) + return undefined; + var major = result.major, minor = result.minor, patch = result.patch, prerelease = result.prerelease, build = result.build; + return new Version(major, minor, patch, prerelease, build); + }; + Version.prototype.compareTo = function (other) { + // https://semver.org/#spec-item-11 + // > Precedence is determined by the first difference when comparing each of these + // > identifiers from left to right as follows: Major, minor, and patch versions are + // > always compared numerically. + // + // https://semver.org/#spec-item-11 + // > Precedence for two pre-release versions with the same major, minor, and patch version + // > MUST be determined by comparing each dot separated identifier from left to right until + // > a difference is found [...] + // + // https://semver.org/#spec-item-11 + // > Build metadata does not figure into precedence + if (this === other) + return 0 /* EqualTo */; + if (other === undefined) + return 1 /* GreaterThan */; + return ts.compareValues(this.major, other.major) + || ts.compareValues(this.minor, other.minor) + || ts.compareValues(this.patch, other.patch) + || comparePrerelaseIdentifiers(this.prerelease, other.prerelease); + }; + Version.prototype.increment = function (field) { + switch (field) { + case "major": return new Version(this.major + 1, 0, 0); + case "minor": return new Version(this.major, this.minor + 1, 0); + case "patch": return new Version(this.major, this.minor, this.patch + 1); + default: return ts.Debug.assertNever(field); + } + }; + Version.prototype.toString = function () { + var result = this.major + "." + this.minor + "." + this.patch; + if (ts.some(this.prerelease)) + result += "-" + this.prerelease.join("."); + if (ts.some(this.build)) + result += "+" + this.build.join("."); + return result; + }; + Version.zero = new Version(0, 0, 0); + return Version; + }()); + ts.Version = Version; + function tryParseComponents(text) { + var match = versionRegExp.exec(text); + if (!match) + return undefined; + var major = match[1], _a = match[2], minor = _a === void 0 ? "0" : _a, _b = match[3], patch = _b === void 0 ? "0" : _b, _c = match[4], prerelease = _c === void 0 ? "" : _c, _d = match[5], build = _d === void 0 ? "" : _d; + if (prerelease && !prereleaseRegExp.test(prerelease)) + return undefined; + if (build && !buildRegExp.test(build)) + return undefined; + return { + major: parseInt(major, 10), + minor: parseInt(minor, 10), + patch: parseInt(patch, 10), + prerelease: prerelease, + build: build + }; + } + function comparePrerelaseIdentifiers(left, right) { + // https://semver.org/#spec-item-11 + // > When major, minor, and patch are equal, a pre-release version has lower precedence + // > than a normal version. + if (left === right) + return 0 /* EqualTo */; + if (left.length === 0) + return right.length === 0 ? 0 /* EqualTo */ : 1 /* GreaterThan */; + if (right.length === 0) + return -1 /* LessThan */; + // https://semver.org/#spec-item-11 + // > Precedence for two pre-release versions with the same major, minor, and patch version + // > MUST be determined by comparing each dot separated identifier from left to right until + // > a difference is found [...] + var length = Math.min(left.length, right.length); + for (var i = 0; i < length; i++) { + var leftIdentifier = left[i]; + var rightIdentifier = right[i]; + if (leftIdentifier === rightIdentifier) + continue; + var leftIsNumeric = numericIdentifierRegExp.test(leftIdentifier); + var rightIsNumeric = numericIdentifierRegExp.test(rightIdentifier); + if (leftIsNumeric || rightIsNumeric) { + // https://semver.org/#spec-item-11 + // > Numeric identifiers always have lower precedence than non-numeric identifiers. + if (leftIsNumeric !== rightIsNumeric) + return leftIsNumeric ? -1 /* LessThan */ : 1 /* GreaterThan */; + // https://semver.org/#spec-item-11 + // > identifiers consisting of only digits are compared numerically + var result = ts.compareValues(+leftIdentifier, +rightIdentifier); + if (result) + return result; + } + else { + // https://semver.org/#spec-item-11 + // > identifiers with letters or hyphens are compared lexically in ASCII sort order. + var result = ts.compareStringsCaseSensitive(leftIdentifier, rightIdentifier); + if (result) + return result; + } + } + // https://semver.org/#spec-item-11 + // > A larger set of pre-release fields has a higher precedence than a smaller set, if all + // > of the preceding identifiers are equal. + return ts.compareValues(left.length, right.length); + } + /** + * Describes a semantic version range, per https://github.com/npm/node-semver#ranges + */ + var VersionRange = /** @class */ (function () { + function VersionRange(spec) { + this._alternatives = spec ? ts.Debug.assertDefined(parseRange(spec), "Invalid range spec.") : ts.emptyArray; + } + VersionRange.tryParse = function (text) { + var sets = parseRange(text); + if (sets) { + var range = new VersionRange(""); + range._alternatives = sets; + return range; + } + return undefined; + }; + VersionRange.prototype.test = function (version) { + if (typeof version === "string") + version = new Version(version); + return testDisjunction(version, this._alternatives); + }; + VersionRange.prototype.toString = function () { + return formatDisjunction(this._alternatives); + }; + return VersionRange; + }()); + ts.VersionRange = VersionRange; + // https://github.com/npm/node-semver#range-grammar + // + // range-set ::= range ( logical-or range ) * + // range ::= hyphen | simple ( ' ' simple ) * | '' + // logical-or ::= ( ' ' ) * '||' ( ' ' ) * + var logicalOrRegExp = /\s*\|\|\s*/g; + var whitespaceRegExp = /\s+/g; + // https://github.com/npm/node-semver#range-grammar + // + // partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )? + // xr ::= 'x' | 'X' | '*' | nr + // nr ::= '0' | ['1'-'9'] ( ['0'-'9'] ) * + // qualifier ::= ( '-' pre )? ( '+' build )? + // pre ::= parts + // build ::= parts + // parts ::= part ( '.' part ) * + // part ::= nr | [-0-9A-Za-z]+ + var partialRegExp = /^([xX*0]|[1-9]\d*)(?:\.([xX*0]|[1-9]\d*)(?:\.([xX*0]|[1-9]\d*)(?:-([a-z0-9-.]+))?(?:\+([a-z0-9-.]+))?)?)?$/i; + // https://github.com/npm/node-semver#range-grammar + // + // hyphen ::= partial ' - ' partial + var hyphenRegExp = /^\s*([a-z0-9-+.*]+)\s+-\s+([a-z0-9-+.*]+)\s*$/i; + // https://github.com/npm/node-semver#range-grammar + // + // simple ::= primitive | partial | tilde | caret + // primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial + // tilde ::= '~' partial + // caret ::= '^' partial + var rangeRegExp = /^\s*(~|\^|<|<=|>|>=|=)?\s*([a-z0-9-+.*]+)$/i; + function parseRange(text) { + var alternatives = []; + for (var _i = 0, _a = text.trim().split(logicalOrRegExp); _i < _a.length; _i++) { + var range = _a[_i]; + if (!range) + continue; + var comparators = []; + var match = hyphenRegExp.exec(range); + if (match) { + if (!parseHyphen(match[1], match[2], comparators)) + return undefined; + } + else { + for (var _b = 0, _c = range.split(whitespaceRegExp); _b < _c.length; _b++) { + var simple = _c[_b]; + var match_1 = rangeRegExp.exec(simple); + if (!match_1 || !parseComparator(match_1[1], match_1[2], comparators)) + return undefined; + } + } + alternatives.push(comparators); + } + return alternatives; + } + function parsePartial(text) { + var match = partialRegExp.exec(text); + if (!match) + return undefined; + var major = match[1], _a = match[2], minor = _a === void 0 ? "*" : _a, _b = match[3], patch = _b === void 0 ? "*" : _b, prerelease = match[4], build = match[5]; + var version = new Version(isWildcard(major) ? 0 : parseInt(major, 10), isWildcard(major) || isWildcard(minor) ? 0 : parseInt(minor, 10), isWildcard(major) || isWildcard(minor) || isWildcard(patch) ? 0 : parseInt(patch, 10), prerelease, build); + return { version: version, major: major, minor: minor, patch: patch }; + } + function parseHyphen(left, right, comparators) { + var leftResult = parsePartial(left); + if (!leftResult) + return false; + var rightResult = parsePartial(right); + if (!rightResult) + return false; + if (!isWildcard(leftResult.major)) { + comparators.push(createComparator(">=", leftResult.version)); + } + if (!isWildcard(rightResult.major)) { + comparators.push(isWildcard(rightResult.minor) ? createComparator("<", rightResult.version.increment("major")) : + isWildcard(rightResult.patch) ? createComparator("<", rightResult.version.increment("minor")) : + createComparator("<=", rightResult.version)); + } + return true; + } + function parseComparator(operator, text, comparators) { + var result = parsePartial(text); + if (!result) + return false; + var version = result.version, major = result.major, minor = result.minor, patch = result.patch; + if (!isWildcard(major)) { + switch (operator) { + case "~": + comparators.push(createComparator(">=", version)); + comparators.push(createComparator("<", version.increment(isWildcard(minor) ? "major" : + "minor"))); + break; + case "^": + comparators.push(createComparator(">=", version)); + comparators.push(createComparator("<", version.increment(version.major > 0 || isWildcard(minor) ? "major" : + version.minor > 0 || isWildcard(patch) ? "minor" : + "patch"))); + break; + case "<": + case ">=": + comparators.push(createComparator(operator, version)); + break; + case "<=": + case ">": + comparators.push(isWildcard(minor) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("major")) : + isWildcard(patch) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("minor")) : + createComparator(operator, version)); + break; + case "=": + case undefined: + if (isWildcard(minor) || isWildcard(patch)) { + comparators.push(createComparator(">=", version)); + comparators.push(createComparator("<", version.increment(isWildcard(minor) ? "major" : "minor"))); + } + else { + comparators.push(createComparator("=", version)); + } + break; + default: + // unrecognized + return false; + } + } + else if (operator === "<" || operator === ">") { + comparators.push(createComparator("<", Version.zero)); + } + return true; + } + function isWildcard(part) { + return part === "*" || part === "x" || part === "X"; + } + function createComparator(operator, operand) { + return { operator: operator, operand: operand }; + } + function testDisjunction(version, alternatives) { + // an empty disjunction is treated as "*" (all versions) + if (alternatives.length === 0) + return true; + for (var _i = 0, alternatives_1 = alternatives; _i < alternatives_1.length; _i++) { + var alternative = alternatives_1[_i]; + if (testAlternative(version, alternative)) + return true; + } + return false; + } + function testAlternative(version, comparators) { + for (var _i = 0, comparators_1 = comparators; _i < comparators_1.length; _i++) { + var comparator = comparators_1[_i]; + if (!testComparator(version, comparator.operator, comparator.operand)) + return false; + } + return true; + } + function testComparator(version, operator, operand) { + var cmp = version.compareTo(operand); + switch (operator) { + case "<": return cmp < 0; + case "<=": return cmp <= 0; + case ">": return cmp > 0; + case ">=": return cmp >= 0; + case "=": return cmp === 0; + default: return ts.Debug.assertNever(operator); + } + } + function formatDisjunction(alternatives) { + return ts.map(alternatives, formatAlternative).join(" || ") || "*"; + } + function formatAlternative(comparators) { + return ts.map(comparators, formatComparator).join(" "); + } + function formatComparator(comparator) { + return "" + comparator.operator + comparator.operand; + } +})(ts || (ts = {})); +var ts; +(function (ts) { + // token > SyntaxKind.Identifier => token is a keyword + // Also, If you add a new SyntaxKind be sure to keep the `Markers` section at the bottom in sync + var SyntaxKind; + (function (SyntaxKind) { + SyntaxKind[SyntaxKind["Unknown"] = 0] = "Unknown"; + SyntaxKind[SyntaxKind["EndOfFileToken"] = 1] = "EndOfFileToken"; + SyntaxKind[SyntaxKind["SingleLineCommentTrivia"] = 2] = "SingleLineCommentTrivia"; + SyntaxKind[SyntaxKind["MultiLineCommentTrivia"] = 3] = "MultiLineCommentTrivia"; + SyntaxKind[SyntaxKind["NewLineTrivia"] = 4] = "NewLineTrivia"; + SyntaxKind[SyntaxKind["WhitespaceTrivia"] = 5] = "WhitespaceTrivia"; + // We detect and preserve #! on the first line + SyntaxKind[SyntaxKind["ShebangTrivia"] = 6] = "ShebangTrivia"; + // We detect and provide better error recovery when we encounter a git merge marker. This + // allows us to edit files with git-conflict markers in them in a much more pleasant manner. + SyntaxKind[SyntaxKind["ConflictMarkerTrivia"] = 7] = "ConflictMarkerTrivia"; + // Literals + SyntaxKind[SyntaxKind["NumericLiteral"] = 8] = "NumericLiteral"; + SyntaxKind[SyntaxKind["BigIntLiteral"] = 9] = "BigIntLiteral"; + SyntaxKind[SyntaxKind["StringLiteral"] = 10] = "StringLiteral"; + SyntaxKind[SyntaxKind["JsxText"] = 11] = "JsxText"; + SyntaxKind[SyntaxKind["JsxTextAllWhiteSpaces"] = 12] = "JsxTextAllWhiteSpaces"; + SyntaxKind[SyntaxKind["RegularExpressionLiteral"] = 13] = "RegularExpressionLiteral"; + SyntaxKind[SyntaxKind["NoSubstitutionTemplateLiteral"] = 14] = "NoSubstitutionTemplateLiteral"; + // Pseudo-literals + SyntaxKind[SyntaxKind["TemplateHead"] = 15] = "TemplateHead"; + SyntaxKind[SyntaxKind["TemplateMiddle"] = 16] = "TemplateMiddle"; + SyntaxKind[SyntaxKind["TemplateTail"] = 17] = "TemplateTail"; + // Punctuation + SyntaxKind[SyntaxKind["OpenBraceToken"] = 18] = "OpenBraceToken"; + SyntaxKind[SyntaxKind["CloseBraceToken"] = 19] = "CloseBraceToken"; + SyntaxKind[SyntaxKind["OpenParenToken"] = 20] = "OpenParenToken"; + SyntaxKind[SyntaxKind["CloseParenToken"] = 21] = "CloseParenToken"; + SyntaxKind[SyntaxKind["OpenBracketToken"] = 22] = "OpenBracketToken"; + SyntaxKind[SyntaxKind["CloseBracketToken"] = 23] = "CloseBracketToken"; + SyntaxKind[SyntaxKind["DotToken"] = 24] = "DotToken"; + SyntaxKind[SyntaxKind["DotDotDotToken"] = 25] = "DotDotDotToken"; + SyntaxKind[SyntaxKind["SemicolonToken"] = 26] = "SemicolonToken"; + SyntaxKind[SyntaxKind["CommaToken"] = 27] = "CommaToken"; + SyntaxKind[SyntaxKind["LessThanToken"] = 28] = "LessThanToken"; + SyntaxKind[SyntaxKind["LessThanSlashToken"] = 29] = "LessThanSlashToken"; + SyntaxKind[SyntaxKind["GreaterThanToken"] = 30] = "GreaterThanToken"; + SyntaxKind[SyntaxKind["LessThanEqualsToken"] = 31] = "LessThanEqualsToken"; + SyntaxKind[SyntaxKind["GreaterThanEqualsToken"] = 32] = "GreaterThanEqualsToken"; + SyntaxKind[SyntaxKind["EqualsEqualsToken"] = 33] = "EqualsEqualsToken"; + SyntaxKind[SyntaxKind["ExclamationEqualsToken"] = 34] = "ExclamationEqualsToken"; + SyntaxKind[SyntaxKind["EqualsEqualsEqualsToken"] = 35] = "EqualsEqualsEqualsToken"; + SyntaxKind[SyntaxKind["ExclamationEqualsEqualsToken"] = 36] = "ExclamationEqualsEqualsToken"; + SyntaxKind[SyntaxKind["EqualsGreaterThanToken"] = 37] = "EqualsGreaterThanToken"; + SyntaxKind[SyntaxKind["PlusToken"] = 38] = "PlusToken"; + SyntaxKind[SyntaxKind["MinusToken"] = 39] = "MinusToken"; + SyntaxKind[SyntaxKind["AsteriskToken"] = 40] = "AsteriskToken"; + SyntaxKind[SyntaxKind["AsteriskAsteriskToken"] = 41] = "AsteriskAsteriskToken"; + SyntaxKind[SyntaxKind["SlashToken"] = 42] = "SlashToken"; + SyntaxKind[SyntaxKind["PercentToken"] = 43] = "PercentToken"; + SyntaxKind[SyntaxKind["PlusPlusToken"] = 44] = "PlusPlusToken"; + SyntaxKind[SyntaxKind["MinusMinusToken"] = 45] = "MinusMinusToken"; + SyntaxKind[SyntaxKind["LessThanLessThanToken"] = 46] = "LessThanLessThanToken"; + SyntaxKind[SyntaxKind["GreaterThanGreaterThanToken"] = 47] = "GreaterThanGreaterThanToken"; + SyntaxKind[SyntaxKind["GreaterThanGreaterThanGreaterThanToken"] = 48] = "GreaterThanGreaterThanGreaterThanToken"; + SyntaxKind[SyntaxKind["AmpersandToken"] = 49] = "AmpersandToken"; + SyntaxKind[SyntaxKind["BarToken"] = 50] = "BarToken"; + SyntaxKind[SyntaxKind["CaretToken"] = 51] = "CaretToken"; + SyntaxKind[SyntaxKind["ExclamationToken"] = 52] = "ExclamationToken"; + SyntaxKind[SyntaxKind["TildeToken"] = 53] = "TildeToken"; + SyntaxKind[SyntaxKind["AmpersandAmpersandToken"] = 54] = "AmpersandAmpersandToken"; + SyntaxKind[SyntaxKind["BarBarToken"] = 55] = "BarBarToken"; + SyntaxKind[SyntaxKind["QuestionToken"] = 56] = "QuestionToken"; + SyntaxKind[SyntaxKind["ColonToken"] = 57] = "ColonToken"; + SyntaxKind[SyntaxKind["AtToken"] = 58] = "AtToken"; + // Assignments + SyntaxKind[SyntaxKind["EqualsToken"] = 59] = "EqualsToken"; + SyntaxKind[SyntaxKind["PlusEqualsToken"] = 60] = "PlusEqualsToken"; + SyntaxKind[SyntaxKind["MinusEqualsToken"] = 61] = "MinusEqualsToken"; + SyntaxKind[SyntaxKind["AsteriskEqualsToken"] = 62] = "AsteriskEqualsToken"; + SyntaxKind[SyntaxKind["AsteriskAsteriskEqualsToken"] = 63] = "AsteriskAsteriskEqualsToken"; + SyntaxKind[SyntaxKind["SlashEqualsToken"] = 64] = "SlashEqualsToken"; + SyntaxKind[SyntaxKind["PercentEqualsToken"] = 65] = "PercentEqualsToken"; + SyntaxKind[SyntaxKind["LessThanLessThanEqualsToken"] = 66] = "LessThanLessThanEqualsToken"; + SyntaxKind[SyntaxKind["GreaterThanGreaterThanEqualsToken"] = 67] = "GreaterThanGreaterThanEqualsToken"; + SyntaxKind[SyntaxKind["GreaterThanGreaterThanGreaterThanEqualsToken"] = 68] = "GreaterThanGreaterThanGreaterThanEqualsToken"; + SyntaxKind[SyntaxKind["AmpersandEqualsToken"] = 69] = "AmpersandEqualsToken"; + SyntaxKind[SyntaxKind["BarEqualsToken"] = 70] = "BarEqualsToken"; + SyntaxKind[SyntaxKind["CaretEqualsToken"] = 71] = "CaretEqualsToken"; + // Identifiers + SyntaxKind[SyntaxKind["Identifier"] = 72] = "Identifier"; + // Reserved words + SyntaxKind[SyntaxKind["BreakKeyword"] = 73] = "BreakKeyword"; + SyntaxKind[SyntaxKind["CaseKeyword"] = 74] = "CaseKeyword"; + SyntaxKind[SyntaxKind["CatchKeyword"] = 75] = "CatchKeyword"; + SyntaxKind[SyntaxKind["ClassKeyword"] = 76] = "ClassKeyword"; + SyntaxKind[SyntaxKind["ConstKeyword"] = 77] = "ConstKeyword"; + SyntaxKind[SyntaxKind["ContinueKeyword"] = 78] = "ContinueKeyword"; + SyntaxKind[SyntaxKind["DebuggerKeyword"] = 79] = "DebuggerKeyword"; + SyntaxKind[SyntaxKind["DefaultKeyword"] = 80] = "DefaultKeyword"; + SyntaxKind[SyntaxKind["DeleteKeyword"] = 81] = "DeleteKeyword"; + SyntaxKind[SyntaxKind["DoKeyword"] = 82] = "DoKeyword"; + SyntaxKind[SyntaxKind["ElseKeyword"] = 83] = "ElseKeyword"; + SyntaxKind[SyntaxKind["EnumKeyword"] = 84] = "EnumKeyword"; + SyntaxKind[SyntaxKind["ExportKeyword"] = 85] = "ExportKeyword"; + SyntaxKind[SyntaxKind["ExtendsKeyword"] = 86] = "ExtendsKeyword"; + SyntaxKind[SyntaxKind["FalseKeyword"] = 87] = "FalseKeyword"; + SyntaxKind[SyntaxKind["FinallyKeyword"] = 88] = "FinallyKeyword"; + SyntaxKind[SyntaxKind["ForKeyword"] = 89] = "ForKeyword"; + SyntaxKind[SyntaxKind["FunctionKeyword"] = 90] = "FunctionKeyword"; + SyntaxKind[SyntaxKind["IfKeyword"] = 91] = "IfKeyword"; + SyntaxKind[SyntaxKind["ImportKeyword"] = 92] = "ImportKeyword"; + SyntaxKind[SyntaxKind["InKeyword"] = 93] = "InKeyword"; + SyntaxKind[SyntaxKind["InstanceOfKeyword"] = 94] = "InstanceOfKeyword"; + SyntaxKind[SyntaxKind["NewKeyword"] = 95] = "NewKeyword"; + SyntaxKind[SyntaxKind["NullKeyword"] = 96] = "NullKeyword"; + SyntaxKind[SyntaxKind["ReturnKeyword"] = 97] = "ReturnKeyword"; + SyntaxKind[SyntaxKind["SuperKeyword"] = 98] = "SuperKeyword"; + SyntaxKind[SyntaxKind["SwitchKeyword"] = 99] = "SwitchKeyword"; + SyntaxKind[SyntaxKind["ThisKeyword"] = 100] = "ThisKeyword"; + SyntaxKind[SyntaxKind["ThrowKeyword"] = 101] = "ThrowKeyword"; + SyntaxKind[SyntaxKind["TrueKeyword"] = 102] = "TrueKeyword"; + SyntaxKind[SyntaxKind["TryKeyword"] = 103] = "TryKeyword"; + SyntaxKind[SyntaxKind["TypeOfKeyword"] = 104] = "TypeOfKeyword"; + SyntaxKind[SyntaxKind["VarKeyword"] = 105] = "VarKeyword"; + SyntaxKind[SyntaxKind["VoidKeyword"] = 106] = "VoidKeyword"; + SyntaxKind[SyntaxKind["WhileKeyword"] = 107] = "WhileKeyword"; + SyntaxKind[SyntaxKind["WithKeyword"] = 108] = "WithKeyword"; + // Strict mode reserved words + SyntaxKind[SyntaxKind["ImplementsKeyword"] = 109] = "ImplementsKeyword"; + SyntaxKind[SyntaxKind["InterfaceKeyword"] = 110] = "InterfaceKeyword"; + SyntaxKind[SyntaxKind["LetKeyword"] = 111] = "LetKeyword"; + SyntaxKind[SyntaxKind["PackageKeyword"] = 112] = "PackageKeyword"; + SyntaxKind[SyntaxKind["PrivateKeyword"] = 113] = "PrivateKeyword"; + SyntaxKind[SyntaxKind["ProtectedKeyword"] = 114] = "ProtectedKeyword"; + SyntaxKind[SyntaxKind["PublicKeyword"] = 115] = "PublicKeyword"; + SyntaxKind[SyntaxKind["StaticKeyword"] = 116] = "StaticKeyword"; + SyntaxKind[SyntaxKind["YieldKeyword"] = 117] = "YieldKeyword"; + // Contextual keywords + SyntaxKind[SyntaxKind["AbstractKeyword"] = 118] = "AbstractKeyword"; + SyntaxKind[SyntaxKind["AsKeyword"] = 119] = "AsKeyword"; + SyntaxKind[SyntaxKind["AnyKeyword"] = 120] = "AnyKeyword"; + SyntaxKind[SyntaxKind["AsyncKeyword"] = 121] = "AsyncKeyword"; + SyntaxKind[SyntaxKind["AwaitKeyword"] = 122] = "AwaitKeyword"; + SyntaxKind[SyntaxKind["BooleanKeyword"] = 123] = "BooleanKeyword"; + SyntaxKind[SyntaxKind["ConstructorKeyword"] = 124] = "ConstructorKeyword"; + SyntaxKind[SyntaxKind["DeclareKeyword"] = 125] = "DeclareKeyword"; + SyntaxKind[SyntaxKind["GetKeyword"] = 126] = "GetKeyword"; + SyntaxKind[SyntaxKind["InferKeyword"] = 127] = "InferKeyword"; + SyntaxKind[SyntaxKind["IsKeyword"] = 128] = "IsKeyword"; + SyntaxKind[SyntaxKind["KeyOfKeyword"] = 129] = "KeyOfKeyword"; + SyntaxKind[SyntaxKind["ModuleKeyword"] = 130] = "ModuleKeyword"; + SyntaxKind[SyntaxKind["NamespaceKeyword"] = 131] = "NamespaceKeyword"; + SyntaxKind[SyntaxKind["NeverKeyword"] = 132] = "NeverKeyword"; + SyntaxKind[SyntaxKind["ReadonlyKeyword"] = 133] = "ReadonlyKeyword"; + SyntaxKind[SyntaxKind["RequireKeyword"] = 134] = "RequireKeyword"; + SyntaxKind[SyntaxKind["NumberKeyword"] = 135] = "NumberKeyword"; + SyntaxKind[SyntaxKind["ObjectKeyword"] = 136] = "ObjectKeyword"; + SyntaxKind[SyntaxKind["SetKeyword"] = 137] = "SetKeyword"; + SyntaxKind[SyntaxKind["StringKeyword"] = 138] = "StringKeyword"; + SyntaxKind[SyntaxKind["SymbolKeyword"] = 139] = "SymbolKeyword"; + SyntaxKind[SyntaxKind["TypeKeyword"] = 140] = "TypeKeyword"; + SyntaxKind[SyntaxKind["UndefinedKeyword"] = 141] = "UndefinedKeyword"; + SyntaxKind[SyntaxKind["UniqueKeyword"] = 142] = "UniqueKeyword"; + SyntaxKind[SyntaxKind["UnknownKeyword"] = 143] = "UnknownKeyword"; + SyntaxKind[SyntaxKind["FromKeyword"] = 144] = "FromKeyword"; + SyntaxKind[SyntaxKind["GlobalKeyword"] = 145] = "GlobalKeyword"; + SyntaxKind[SyntaxKind["BigIntKeyword"] = 146] = "BigIntKeyword"; + SyntaxKind[SyntaxKind["OfKeyword"] = 147] = "OfKeyword"; + // Parse tree nodes + // Names + SyntaxKind[SyntaxKind["QualifiedName"] = 148] = "QualifiedName"; + SyntaxKind[SyntaxKind["ComputedPropertyName"] = 149] = "ComputedPropertyName"; + // Signature elements + SyntaxKind[SyntaxKind["TypeParameter"] = 150] = "TypeParameter"; + SyntaxKind[SyntaxKind["Parameter"] = 151] = "Parameter"; + SyntaxKind[SyntaxKind["Decorator"] = 152] = "Decorator"; + // TypeMember + SyntaxKind[SyntaxKind["PropertySignature"] = 153] = "PropertySignature"; + SyntaxKind[SyntaxKind["PropertyDeclaration"] = 154] = "PropertyDeclaration"; + SyntaxKind[SyntaxKind["MethodSignature"] = 155] = "MethodSignature"; + SyntaxKind[SyntaxKind["MethodDeclaration"] = 156] = "MethodDeclaration"; + SyntaxKind[SyntaxKind["Constructor"] = 157] = "Constructor"; + SyntaxKind[SyntaxKind["GetAccessor"] = 158] = "GetAccessor"; + SyntaxKind[SyntaxKind["SetAccessor"] = 159] = "SetAccessor"; + SyntaxKind[SyntaxKind["CallSignature"] = 160] = "CallSignature"; + SyntaxKind[SyntaxKind["ConstructSignature"] = 161] = "ConstructSignature"; + SyntaxKind[SyntaxKind["IndexSignature"] = 162] = "IndexSignature"; + // Type + SyntaxKind[SyntaxKind["TypePredicate"] = 163] = "TypePredicate"; + SyntaxKind[SyntaxKind["TypeReference"] = 164] = "TypeReference"; + SyntaxKind[SyntaxKind["FunctionType"] = 165] = "FunctionType"; + SyntaxKind[SyntaxKind["ConstructorType"] = 166] = "ConstructorType"; + SyntaxKind[SyntaxKind["TypeQuery"] = 167] = "TypeQuery"; + SyntaxKind[SyntaxKind["TypeLiteral"] = 168] = "TypeLiteral"; + SyntaxKind[SyntaxKind["ArrayType"] = 169] = "ArrayType"; + SyntaxKind[SyntaxKind["TupleType"] = 170] = "TupleType"; + SyntaxKind[SyntaxKind["OptionalType"] = 171] = "OptionalType"; + SyntaxKind[SyntaxKind["RestType"] = 172] = "RestType"; + SyntaxKind[SyntaxKind["UnionType"] = 173] = "UnionType"; + SyntaxKind[SyntaxKind["IntersectionType"] = 174] = "IntersectionType"; + SyntaxKind[SyntaxKind["ConditionalType"] = 175] = "ConditionalType"; + SyntaxKind[SyntaxKind["InferType"] = 176] = "InferType"; + SyntaxKind[SyntaxKind["ParenthesizedType"] = 177] = "ParenthesizedType"; + SyntaxKind[SyntaxKind["ThisType"] = 178] = "ThisType"; + SyntaxKind[SyntaxKind["TypeOperator"] = 179] = "TypeOperator"; + SyntaxKind[SyntaxKind["IndexedAccessType"] = 180] = "IndexedAccessType"; + SyntaxKind[SyntaxKind["MappedType"] = 181] = "MappedType"; + SyntaxKind[SyntaxKind["LiteralType"] = 182] = "LiteralType"; + SyntaxKind[SyntaxKind["ImportType"] = 183] = "ImportType"; + // Binding patterns + SyntaxKind[SyntaxKind["ObjectBindingPattern"] = 184] = "ObjectBindingPattern"; + SyntaxKind[SyntaxKind["ArrayBindingPattern"] = 185] = "ArrayBindingPattern"; + SyntaxKind[SyntaxKind["BindingElement"] = 186] = "BindingElement"; + // Expression + SyntaxKind[SyntaxKind["ArrayLiteralExpression"] = 187] = "ArrayLiteralExpression"; + SyntaxKind[SyntaxKind["ObjectLiteralExpression"] = 188] = "ObjectLiteralExpression"; + SyntaxKind[SyntaxKind["PropertyAccessExpression"] = 189] = "PropertyAccessExpression"; + SyntaxKind[SyntaxKind["ElementAccessExpression"] = 190] = "ElementAccessExpression"; + SyntaxKind[SyntaxKind["CallExpression"] = 191] = "CallExpression"; + SyntaxKind[SyntaxKind["NewExpression"] = 192] = "NewExpression"; + SyntaxKind[SyntaxKind["TaggedTemplateExpression"] = 193] = "TaggedTemplateExpression"; + SyntaxKind[SyntaxKind["TypeAssertionExpression"] = 194] = "TypeAssertionExpression"; + SyntaxKind[SyntaxKind["ParenthesizedExpression"] = 195] = "ParenthesizedExpression"; + SyntaxKind[SyntaxKind["FunctionExpression"] = 196] = "FunctionExpression"; + SyntaxKind[SyntaxKind["ArrowFunction"] = 197] = "ArrowFunction"; + SyntaxKind[SyntaxKind["DeleteExpression"] = 198] = "DeleteExpression"; + SyntaxKind[SyntaxKind["TypeOfExpression"] = 199] = "TypeOfExpression"; + SyntaxKind[SyntaxKind["VoidExpression"] = 200] = "VoidExpression"; + SyntaxKind[SyntaxKind["AwaitExpression"] = 201] = "AwaitExpression"; + SyntaxKind[SyntaxKind["PrefixUnaryExpression"] = 202] = "PrefixUnaryExpression"; + SyntaxKind[SyntaxKind["PostfixUnaryExpression"] = 203] = "PostfixUnaryExpression"; + SyntaxKind[SyntaxKind["BinaryExpression"] = 204] = "BinaryExpression"; + SyntaxKind[SyntaxKind["ConditionalExpression"] = 205] = "ConditionalExpression"; + SyntaxKind[SyntaxKind["TemplateExpression"] = 206] = "TemplateExpression"; + SyntaxKind[SyntaxKind["YieldExpression"] = 207] = "YieldExpression"; + SyntaxKind[SyntaxKind["SpreadElement"] = 208] = "SpreadElement"; + SyntaxKind[SyntaxKind["ClassExpression"] = 209] = "ClassExpression"; + SyntaxKind[SyntaxKind["OmittedExpression"] = 210] = "OmittedExpression"; + SyntaxKind[SyntaxKind["ExpressionWithTypeArguments"] = 211] = "ExpressionWithTypeArguments"; + SyntaxKind[SyntaxKind["AsExpression"] = 212] = "AsExpression"; + SyntaxKind[SyntaxKind["NonNullExpression"] = 213] = "NonNullExpression"; + SyntaxKind[SyntaxKind["MetaProperty"] = 214] = "MetaProperty"; + SyntaxKind[SyntaxKind["SyntheticExpression"] = 215] = "SyntheticExpression"; + // Misc + SyntaxKind[SyntaxKind["TemplateSpan"] = 216] = "TemplateSpan"; + SyntaxKind[SyntaxKind["SemicolonClassElement"] = 217] = "SemicolonClassElement"; + // Element + SyntaxKind[SyntaxKind["Block"] = 218] = "Block"; + SyntaxKind[SyntaxKind["VariableStatement"] = 219] = "VariableStatement"; + SyntaxKind[SyntaxKind["EmptyStatement"] = 220] = "EmptyStatement"; + SyntaxKind[SyntaxKind["ExpressionStatement"] = 221] = "ExpressionStatement"; + SyntaxKind[SyntaxKind["IfStatement"] = 222] = "IfStatement"; + SyntaxKind[SyntaxKind["DoStatement"] = 223] = "DoStatement"; + SyntaxKind[SyntaxKind["WhileStatement"] = 224] = "WhileStatement"; + SyntaxKind[SyntaxKind["ForStatement"] = 225] = "ForStatement"; + SyntaxKind[SyntaxKind["ForInStatement"] = 226] = "ForInStatement"; + SyntaxKind[SyntaxKind["ForOfStatement"] = 227] = "ForOfStatement"; + SyntaxKind[SyntaxKind["ContinueStatement"] = 228] = "ContinueStatement"; + SyntaxKind[SyntaxKind["BreakStatement"] = 229] = "BreakStatement"; + SyntaxKind[SyntaxKind["ReturnStatement"] = 230] = "ReturnStatement"; + SyntaxKind[SyntaxKind["WithStatement"] = 231] = "WithStatement"; + SyntaxKind[SyntaxKind["SwitchStatement"] = 232] = "SwitchStatement"; + SyntaxKind[SyntaxKind["LabeledStatement"] = 233] = "LabeledStatement"; + SyntaxKind[SyntaxKind["ThrowStatement"] = 234] = "ThrowStatement"; + SyntaxKind[SyntaxKind["TryStatement"] = 235] = "TryStatement"; + SyntaxKind[SyntaxKind["DebuggerStatement"] = 236] = "DebuggerStatement"; + SyntaxKind[SyntaxKind["VariableDeclaration"] = 237] = "VariableDeclaration"; + SyntaxKind[SyntaxKind["VariableDeclarationList"] = 238] = "VariableDeclarationList"; + SyntaxKind[SyntaxKind["FunctionDeclaration"] = 239] = "FunctionDeclaration"; + SyntaxKind[SyntaxKind["ClassDeclaration"] = 240] = "ClassDeclaration"; + SyntaxKind[SyntaxKind["InterfaceDeclaration"] = 241] = "InterfaceDeclaration"; + SyntaxKind[SyntaxKind["TypeAliasDeclaration"] = 242] = "TypeAliasDeclaration"; + SyntaxKind[SyntaxKind["EnumDeclaration"] = 243] = "EnumDeclaration"; + SyntaxKind[SyntaxKind["ModuleDeclaration"] = 244] = "ModuleDeclaration"; + SyntaxKind[SyntaxKind["ModuleBlock"] = 245] = "ModuleBlock"; + SyntaxKind[SyntaxKind["CaseBlock"] = 246] = "CaseBlock"; + SyntaxKind[SyntaxKind["NamespaceExportDeclaration"] = 247] = "NamespaceExportDeclaration"; + SyntaxKind[SyntaxKind["ImportEqualsDeclaration"] = 248] = "ImportEqualsDeclaration"; + SyntaxKind[SyntaxKind["ImportDeclaration"] = 249] = "ImportDeclaration"; + SyntaxKind[SyntaxKind["ImportClause"] = 250] = "ImportClause"; + SyntaxKind[SyntaxKind["NamespaceImport"] = 251] = "NamespaceImport"; + SyntaxKind[SyntaxKind["NamedImports"] = 252] = "NamedImports"; + SyntaxKind[SyntaxKind["ImportSpecifier"] = 253] = "ImportSpecifier"; + SyntaxKind[SyntaxKind["ExportAssignment"] = 254] = "ExportAssignment"; + SyntaxKind[SyntaxKind["ExportDeclaration"] = 255] = "ExportDeclaration"; + SyntaxKind[SyntaxKind["NamedExports"] = 256] = "NamedExports"; + SyntaxKind[SyntaxKind["ExportSpecifier"] = 257] = "ExportSpecifier"; + SyntaxKind[SyntaxKind["MissingDeclaration"] = 258] = "MissingDeclaration"; + // Module references + SyntaxKind[SyntaxKind["ExternalModuleReference"] = 259] = "ExternalModuleReference"; + // JSX + SyntaxKind[SyntaxKind["JsxElement"] = 260] = "JsxElement"; + SyntaxKind[SyntaxKind["JsxSelfClosingElement"] = 261] = "JsxSelfClosingElement"; + SyntaxKind[SyntaxKind["JsxOpeningElement"] = 262] = "JsxOpeningElement"; + SyntaxKind[SyntaxKind["JsxClosingElement"] = 263] = "JsxClosingElement"; + SyntaxKind[SyntaxKind["JsxFragment"] = 264] = "JsxFragment"; + SyntaxKind[SyntaxKind["JsxOpeningFragment"] = 265] = "JsxOpeningFragment"; + SyntaxKind[SyntaxKind["JsxClosingFragment"] = 266] = "JsxClosingFragment"; + SyntaxKind[SyntaxKind["JsxAttribute"] = 267] = "JsxAttribute"; + SyntaxKind[SyntaxKind["JsxAttributes"] = 268] = "JsxAttributes"; + SyntaxKind[SyntaxKind["JsxSpreadAttribute"] = 269] = "JsxSpreadAttribute"; + SyntaxKind[SyntaxKind["JsxExpression"] = 270] = "JsxExpression"; + // Clauses + SyntaxKind[SyntaxKind["CaseClause"] = 271] = "CaseClause"; + SyntaxKind[SyntaxKind["DefaultClause"] = 272] = "DefaultClause"; + SyntaxKind[SyntaxKind["HeritageClause"] = 273] = "HeritageClause"; + SyntaxKind[SyntaxKind["CatchClause"] = 274] = "CatchClause"; + // Property assignments + SyntaxKind[SyntaxKind["PropertyAssignment"] = 275] = "PropertyAssignment"; + SyntaxKind[SyntaxKind["ShorthandPropertyAssignment"] = 276] = "ShorthandPropertyAssignment"; + SyntaxKind[SyntaxKind["SpreadAssignment"] = 277] = "SpreadAssignment"; + // Enum + SyntaxKind[SyntaxKind["EnumMember"] = 278] = "EnumMember"; + // Top-level nodes + SyntaxKind[SyntaxKind["SourceFile"] = 279] = "SourceFile"; + SyntaxKind[SyntaxKind["Bundle"] = 280] = "Bundle"; + SyntaxKind[SyntaxKind["UnparsedSource"] = 281] = "UnparsedSource"; + SyntaxKind[SyntaxKind["InputFiles"] = 282] = "InputFiles"; + // JSDoc nodes + SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 283] = "JSDocTypeExpression"; + // The * type + SyntaxKind[SyntaxKind["JSDocAllType"] = 284] = "JSDocAllType"; + // The ? type + SyntaxKind[SyntaxKind["JSDocUnknownType"] = 285] = "JSDocUnknownType"; + SyntaxKind[SyntaxKind["JSDocNullableType"] = 286] = "JSDocNullableType"; + SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 287] = "JSDocNonNullableType"; + SyntaxKind[SyntaxKind["JSDocOptionalType"] = 288] = "JSDocOptionalType"; + SyntaxKind[SyntaxKind["JSDocFunctionType"] = 289] = "JSDocFunctionType"; + SyntaxKind[SyntaxKind["JSDocVariadicType"] = 290] = "JSDocVariadicType"; + SyntaxKind[SyntaxKind["JSDocComment"] = 291] = "JSDocComment"; + SyntaxKind[SyntaxKind["JSDocTypeLiteral"] = 292] = "JSDocTypeLiteral"; + SyntaxKind[SyntaxKind["JSDocSignature"] = 293] = "JSDocSignature"; + SyntaxKind[SyntaxKind["JSDocTag"] = 294] = "JSDocTag"; + SyntaxKind[SyntaxKind["JSDocAugmentsTag"] = 295] = "JSDocAugmentsTag"; + SyntaxKind[SyntaxKind["JSDocClassTag"] = 296] = "JSDocClassTag"; + SyntaxKind[SyntaxKind["JSDocCallbackTag"] = 297] = "JSDocCallbackTag"; + SyntaxKind[SyntaxKind["JSDocEnumTag"] = 298] = "JSDocEnumTag"; + SyntaxKind[SyntaxKind["JSDocParameterTag"] = 299] = "JSDocParameterTag"; + SyntaxKind[SyntaxKind["JSDocReturnTag"] = 300] = "JSDocReturnTag"; + SyntaxKind[SyntaxKind["JSDocThisTag"] = 301] = "JSDocThisTag"; + SyntaxKind[SyntaxKind["JSDocTypeTag"] = 302] = "JSDocTypeTag"; + SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 303] = "JSDocTemplateTag"; + SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 304] = "JSDocTypedefTag"; + SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 305] = "JSDocPropertyTag"; + // Synthesized list + SyntaxKind[SyntaxKind["SyntaxList"] = 306] = "SyntaxList"; + // Transformation nodes + SyntaxKind[SyntaxKind["NotEmittedStatement"] = 307] = "NotEmittedStatement"; + SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 308] = "PartiallyEmittedExpression"; + SyntaxKind[SyntaxKind["CommaListExpression"] = 309] = "CommaListExpression"; + SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 310] = "MergeDeclarationMarker"; + SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 311] = "EndOfDeclarationMarker"; + // Enum value count + SyntaxKind[SyntaxKind["Count"] = 312] = "Count"; + // Markers + SyntaxKind[SyntaxKind["FirstAssignment"] = 59] = "FirstAssignment"; + SyntaxKind[SyntaxKind["LastAssignment"] = 71] = "LastAssignment"; + SyntaxKind[SyntaxKind["FirstCompoundAssignment"] = 60] = "FirstCompoundAssignment"; + SyntaxKind[SyntaxKind["LastCompoundAssignment"] = 71] = "LastCompoundAssignment"; + SyntaxKind[SyntaxKind["FirstReservedWord"] = 73] = "FirstReservedWord"; + SyntaxKind[SyntaxKind["LastReservedWord"] = 108] = "LastReservedWord"; + SyntaxKind[SyntaxKind["FirstKeyword"] = 73] = "FirstKeyword"; + SyntaxKind[SyntaxKind["LastKeyword"] = 147] = "LastKeyword"; + SyntaxKind[SyntaxKind["FirstFutureReservedWord"] = 109] = "FirstFutureReservedWord"; + SyntaxKind[SyntaxKind["LastFutureReservedWord"] = 117] = "LastFutureReservedWord"; + SyntaxKind[SyntaxKind["FirstTypeNode"] = 163] = "FirstTypeNode"; + SyntaxKind[SyntaxKind["LastTypeNode"] = 183] = "LastTypeNode"; + SyntaxKind[SyntaxKind["FirstPunctuation"] = 18] = "FirstPunctuation"; + SyntaxKind[SyntaxKind["LastPunctuation"] = 71] = "LastPunctuation"; + SyntaxKind[SyntaxKind["FirstToken"] = 0] = "FirstToken"; + SyntaxKind[SyntaxKind["LastToken"] = 147] = "LastToken"; + SyntaxKind[SyntaxKind["FirstTriviaToken"] = 2] = "FirstTriviaToken"; + SyntaxKind[SyntaxKind["LastTriviaToken"] = 7] = "LastTriviaToken"; + SyntaxKind[SyntaxKind["FirstLiteralToken"] = 8] = "FirstLiteralToken"; + SyntaxKind[SyntaxKind["LastLiteralToken"] = 14] = "LastLiteralToken"; + SyntaxKind[SyntaxKind["FirstTemplateToken"] = 14] = "FirstTemplateToken"; + SyntaxKind[SyntaxKind["LastTemplateToken"] = 17] = "LastTemplateToken"; + SyntaxKind[SyntaxKind["FirstBinaryOperator"] = 28] = "FirstBinaryOperator"; + SyntaxKind[SyntaxKind["LastBinaryOperator"] = 71] = "LastBinaryOperator"; + SyntaxKind[SyntaxKind["FirstNode"] = 148] = "FirstNode"; + SyntaxKind[SyntaxKind["FirstJSDocNode"] = 283] = "FirstJSDocNode"; + SyntaxKind[SyntaxKind["LastJSDocNode"] = 305] = "LastJSDocNode"; + SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 294] = "FirstJSDocTagNode"; + SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 305] = "LastJSDocTagNode"; + /* @internal */ SyntaxKind[SyntaxKind["FirstContextualKeyword"] = 118] = "FirstContextualKeyword"; + /* @internal */ SyntaxKind[SyntaxKind["LastContextualKeyword"] = 147] = "LastContextualKeyword"; + })(SyntaxKind = ts.SyntaxKind || (ts.SyntaxKind = {})); + var NodeFlags; + (function (NodeFlags) { + NodeFlags[NodeFlags["None"] = 0] = "None"; + NodeFlags[NodeFlags["Let"] = 1] = "Let"; + NodeFlags[NodeFlags["Const"] = 2] = "Const"; + NodeFlags[NodeFlags["NestedNamespace"] = 4] = "NestedNamespace"; + NodeFlags[NodeFlags["Synthesized"] = 8] = "Synthesized"; + NodeFlags[NodeFlags["Namespace"] = 16] = "Namespace"; + NodeFlags[NodeFlags["ExportContext"] = 32] = "ExportContext"; + NodeFlags[NodeFlags["ContainsThis"] = 64] = "ContainsThis"; + NodeFlags[NodeFlags["HasImplicitReturn"] = 128] = "HasImplicitReturn"; + NodeFlags[NodeFlags["HasExplicitReturn"] = 256] = "HasExplicitReturn"; + NodeFlags[NodeFlags["GlobalAugmentation"] = 512] = "GlobalAugmentation"; + NodeFlags[NodeFlags["HasAsyncFunctions"] = 1024] = "HasAsyncFunctions"; + NodeFlags[NodeFlags["DisallowInContext"] = 2048] = "DisallowInContext"; + NodeFlags[NodeFlags["YieldContext"] = 4096] = "YieldContext"; + NodeFlags[NodeFlags["DecoratorContext"] = 8192] = "DecoratorContext"; + NodeFlags[NodeFlags["AwaitContext"] = 16384] = "AwaitContext"; + NodeFlags[NodeFlags["ThisNodeHasError"] = 32768] = "ThisNodeHasError"; + NodeFlags[NodeFlags["JavaScriptFile"] = 65536] = "JavaScriptFile"; + NodeFlags[NodeFlags["ThisNodeOrAnySubNodesHasError"] = 131072] = "ThisNodeOrAnySubNodesHasError"; + NodeFlags[NodeFlags["HasAggregatedChildData"] = 262144] = "HasAggregatedChildData"; + // These flags will be set when the parser encounters a dynamic import expression or 'import.meta' to avoid + // walking the tree if the flags are not set. However, these flags are just a approximation + // (hence why it's named "PossiblyContainsDynamicImport") because once set, the flags never get cleared. + // During editing, if a dynamic import is removed, incremental parsing will *NOT* clear this flag. + // This means that the tree will always be traversed during module resolution, or when looking for external module indicators. + // However, the removal operation should not occur often and in the case of the + // removal, it is likely that users will add the import anyway. + // The advantage of this approach is its simplicity. For the case of batch compilation, + // we guarantee that users won't have to pay the price of walking the tree if a dynamic import isn't used. + /* @internal */ NodeFlags[NodeFlags["PossiblyContainsDynamicImport"] = 524288] = "PossiblyContainsDynamicImport"; + /* @internal */ NodeFlags[NodeFlags["PossiblyContainsImportMeta"] = 1048576] = "PossiblyContainsImportMeta"; + NodeFlags[NodeFlags["JSDoc"] = 2097152] = "JSDoc"; + /* @internal */ NodeFlags[NodeFlags["Ambient"] = 4194304] = "Ambient"; + /* @internal */ NodeFlags[NodeFlags["InWithStatement"] = 8388608] = "InWithStatement"; + NodeFlags[NodeFlags["JsonFile"] = 16777216] = "JsonFile"; + NodeFlags[NodeFlags["BlockScoped"] = 3] = "BlockScoped"; + NodeFlags[NodeFlags["ReachabilityCheckFlags"] = 384] = "ReachabilityCheckFlags"; + NodeFlags[NodeFlags["ReachabilityAndEmitFlags"] = 1408] = "ReachabilityAndEmitFlags"; + // Parsing context flags + NodeFlags[NodeFlags["ContextFlags"] = 12679168] = "ContextFlags"; + // Exclude these flags when parsing a Type + NodeFlags[NodeFlags["TypeExcludesFlags"] = 20480] = "TypeExcludesFlags"; + // Represents all flags that are potentially set once and + // never cleared on SourceFiles which get re-used in between incremental parses. + // See the comment above on `PossiblyContainsDynamicImport` and `PossiblyContainsImportMeta`. + /* @internal */ NodeFlags[NodeFlags["PermanentlySetIncrementalFlags"] = 1572864] = "PermanentlySetIncrementalFlags"; + })(NodeFlags = ts.NodeFlags || (ts.NodeFlags = {})); + var ModifierFlags; + (function (ModifierFlags) { + ModifierFlags[ModifierFlags["None"] = 0] = "None"; + ModifierFlags[ModifierFlags["Export"] = 1] = "Export"; + ModifierFlags[ModifierFlags["Ambient"] = 2] = "Ambient"; + ModifierFlags[ModifierFlags["Public"] = 4] = "Public"; + ModifierFlags[ModifierFlags["Private"] = 8] = "Private"; + ModifierFlags[ModifierFlags["Protected"] = 16] = "Protected"; + ModifierFlags[ModifierFlags["Static"] = 32] = "Static"; + ModifierFlags[ModifierFlags["Readonly"] = 64] = "Readonly"; + ModifierFlags[ModifierFlags["Abstract"] = 128] = "Abstract"; + ModifierFlags[ModifierFlags["Async"] = 256] = "Async"; + ModifierFlags[ModifierFlags["Default"] = 512] = "Default"; + ModifierFlags[ModifierFlags["Const"] = 2048] = "Const"; + ModifierFlags[ModifierFlags["HasComputedFlags"] = 536870912] = "HasComputedFlags"; + ModifierFlags[ModifierFlags["AccessibilityModifier"] = 28] = "AccessibilityModifier"; + // Accessibility modifiers and 'readonly' can be attached to a parameter in a constructor to make it a property. + ModifierFlags[ModifierFlags["ParameterPropertyModifier"] = 92] = "ParameterPropertyModifier"; + ModifierFlags[ModifierFlags["NonPublicAccessibilityModifier"] = 24] = "NonPublicAccessibilityModifier"; + ModifierFlags[ModifierFlags["TypeScriptModifier"] = 2270] = "TypeScriptModifier"; + ModifierFlags[ModifierFlags["ExportDefault"] = 513] = "ExportDefault"; + ModifierFlags[ModifierFlags["All"] = 3071] = "All"; + })(ModifierFlags = ts.ModifierFlags || (ts.ModifierFlags = {})); + var JsxFlags; + (function (JsxFlags) { + JsxFlags[JsxFlags["None"] = 0] = "None"; + /** An element from a named property of the JSX.IntrinsicElements interface */ + JsxFlags[JsxFlags["IntrinsicNamedElement"] = 1] = "IntrinsicNamedElement"; + /** An element inferred from the string index signature of the JSX.IntrinsicElements interface */ + JsxFlags[JsxFlags["IntrinsicIndexedElement"] = 2] = "IntrinsicIndexedElement"; + JsxFlags[JsxFlags["IntrinsicElement"] = 3] = "IntrinsicElement"; + })(JsxFlags = ts.JsxFlags || (ts.JsxFlags = {})); + /* @internal */ + var RelationComparisonResult; + (function (RelationComparisonResult) { + RelationComparisonResult[RelationComparisonResult["Succeeded"] = 1] = "Succeeded"; + RelationComparisonResult[RelationComparisonResult["Failed"] = 2] = "Failed"; + RelationComparisonResult[RelationComparisonResult["FailedAndReported"] = 3] = "FailedAndReported"; + })(RelationComparisonResult = ts.RelationComparisonResult || (ts.RelationComparisonResult = {})); + /*@internal*/ + var GeneratedIdentifierFlags; + (function (GeneratedIdentifierFlags) { + // Kinds + GeneratedIdentifierFlags[GeneratedIdentifierFlags["None"] = 0] = "None"; + GeneratedIdentifierFlags[GeneratedIdentifierFlags["Auto"] = 1] = "Auto"; + GeneratedIdentifierFlags[GeneratedIdentifierFlags["Loop"] = 2] = "Loop"; + GeneratedIdentifierFlags[GeneratedIdentifierFlags["Unique"] = 3] = "Unique"; + GeneratedIdentifierFlags[GeneratedIdentifierFlags["Node"] = 4] = "Node"; + GeneratedIdentifierFlags[GeneratedIdentifierFlags["KindMask"] = 7] = "KindMask"; + // Flags + GeneratedIdentifierFlags[GeneratedIdentifierFlags["ReservedInNestedScopes"] = 8] = "ReservedInNestedScopes"; + GeneratedIdentifierFlags[GeneratedIdentifierFlags["Optimistic"] = 16] = "Optimistic"; + GeneratedIdentifierFlags[GeneratedIdentifierFlags["FileLevel"] = 32] = "FileLevel"; + })(GeneratedIdentifierFlags = ts.GeneratedIdentifierFlags || (ts.GeneratedIdentifierFlags = {})); + /* @internal */ + var TokenFlags; + (function (TokenFlags) { + TokenFlags[TokenFlags["None"] = 0] = "None"; + TokenFlags[TokenFlags["PrecedingLineBreak"] = 1] = "PrecedingLineBreak"; + TokenFlags[TokenFlags["PrecedingJSDocComment"] = 2] = "PrecedingJSDocComment"; + TokenFlags[TokenFlags["Unterminated"] = 4] = "Unterminated"; + TokenFlags[TokenFlags["ExtendedUnicodeEscape"] = 8] = "ExtendedUnicodeEscape"; + TokenFlags[TokenFlags["Scientific"] = 16] = "Scientific"; + TokenFlags[TokenFlags["Octal"] = 32] = "Octal"; + TokenFlags[TokenFlags["HexSpecifier"] = 64] = "HexSpecifier"; + TokenFlags[TokenFlags["BinarySpecifier"] = 128] = "BinarySpecifier"; + TokenFlags[TokenFlags["OctalSpecifier"] = 256] = "OctalSpecifier"; + TokenFlags[TokenFlags["ContainsSeparator"] = 512] = "ContainsSeparator"; + TokenFlags[TokenFlags["BinaryOrOctalSpecifier"] = 384] = "BinaryOrOctalSpecifier"; + TokenFlags[TokenFlags["NumericLiteralFlags"] = 1008] = "NumericLiteralFlags"; + })(TokenFlags = ts.TokenFlags || (ts.TokenFlags = {})); + var FlowFlags; + (function (FlowFlags) { + FlowFlags[FlowFlags["Unreachable"] = 1] = "Unreachable"; + FlowFlags[FlowFlags["Start"] = 2] = "Start"; + FlowFlags[FlowFlags["BranchLabel"] = 4] = "BranchLabel"; + FlowFlags[FlowFlags["LoopLabel"] = 8] = "LoopLabel"; + FlowFlags[FlowFlags["Assignment"] = 16] = "Assignment"; + FlowFlags[FlowFlags["TrueCondition"] = 32] = "TrueCondition"; + FlowFlags[FlowFlags["FalseCondition"] = 64] = "FalseCondition"; + FlowFlags[FlowFlags["SwitchClause"] = 128] = "SwitchClause"; + FlowFlags[FlowFlags["ArrayMutation"] = 256] = "ArrayMutation"; + FlowFlags[FlowFlags["Referenced"] = 512] = "Referenced"; + FlowFlags[FlowFlags["Shared"] = 1024] = "Shared"; + FlowFlags[FlowFlags["PreFinally"] = 2048] = "PreFinally"; + FlowFlags[FlowFlags["AfterFinally"] = 4096] = "AfterFinally"; + FlowFlags[FlowFlags["Label"] = 12] = "Label"; + FlowFlags[FlowFlags["Condition"] = 96] = "Condition"; + })(FlowFlags = ts.FlowFlags || (ts.FlowFlags = {})); + var OperationCanceledException = /** @class */ (function () { + function OperationCanceledException() { + } + return OperationCanceledException; + }()); + ts.OperationCanceledException = OperationCanceledException; + /* @internal */ + var StructureIsReused; + (function (StructureIsReused) { + StructureIsReused[StructureIsReused["Not"] = 0] = "Not"; + StructureIsReused[StructureIsReused["SafeModules"] = 1] = "SafeModules"; + StructureIsReused[StructureIsReused["Completely"] = 2] = "Completely"; + })(StructureIsReused = ts.StructureIsReused || (ts.StructureIsReused = {})); + /** Return code used by getEmitOutput function to indicate status of the function */ + var ExitStatus; + (function (ExitStatus) { + // Compiler ran successfully. Either this was a simple do-nothing compilation (for example, + // when -version or -help was provided, or this was a normal compilation, no diagnostics + // were produced, and all outputs were generated successfully. + ExitStatus[ExitStatus["Success"] = 0] = "Success"; + // Diagnostics were produced and because of them no code was generated. + ExitStatus[ExitStatus["DiagnosticsPresent_OutputsSkipped"] = 1] = "DiagnosticsPresent_OutputsSkipped"; + // Diagnostics were produced and outputs were generated in spite of them. + ExitStatus[ExitStatus["DiagnosticsPresent_OutputsGenerated"] = 2] = "DiagnosticsPresent_OutputsGenerated"; + })(ExitStatus = ts.ExitStatus || (ts.ExitStatus = {})); + /* @internal */ + var UnionReduction; + (function (UnionReduction) { + UnionReduction[UnionReduction["None"] = 0] = "None"; + UnionReduction[UnionReduction["Literal"] = 1] = "Literal"; + UnionReduction[UnionReduction["Subtype"] = 2] = "Subtype"; + })(UnionReduction = ts.UnionReduction || (ts.UnionReduction = {})); + // NOTE: If modifying this enum, must modify `TypeFormatFlags` too! + var NodeBuilderFlags; + (function (NodeBuilderFlags) { + NodeBuilderFlags[NodeBuilderFlags["None"] = 0] = "None"; + // Options + NodeBuilderFlags[NodeBuilderFlags["NoTruncation"] = 1] = "NoTruncation"; + NodeBuilderFlags[NodeBuilderFlags["WriteArrayAsGenericType"] = 2] = "WriteArrayAsGenericType"; + NodeBuilderFlags[NodeBuilderFlags["GenerateNamesForShadowedTypeParams"] = 4] = "GenerateNamesForShadowedTypeParams"; + NodeBuilderFlags[NodeBuilderFlags["UseStructuralFallback"] = 8] = "UseStructuralFallback"; + NodeBuilderFlags[NodeBuilderFlags["ForbidIndexedAccessSymbolReferences"] = 16] = "ForbidIndexedAccessSymbolReferences"; + NodeBuilderFlags[NodeBuilderFlags["WriteTypeArgumentsOfSignature"] = 32] = "WriteTypeArgumentsOfSignature"; + NodeBuilderFlags[NodeBuilderFlags["UseFullyQualifiedType"] = 64] = "UseFullyQualifiedType"; + NodeBuilderFlags[NodeBuilderFlags["UseOnlyExternalAliasing"] = 128] = "UseOnlyExternalAliasing"; + NodeBuilderFlags[NodeBuilderFlags["SuppressAnyReturnType"] = 256] = "SuppressAnyReturnType"; + NodeBuilderFlags[NodeBuilderFlags["WriteTypeParametersInQualifiedName"] = 512] = "WriteTypeParametersInQualifiedName"; + NodeBuilderFlags[NodeBuilderFlags["MultilineObjectLiterals"] = 1024] = "MultilineObjectLiterals"; + NodeBuilderFlags[NodeBuilderFlags["WriteClassExpressionAsTypeLiteral"] = 2048] = "WriteClassExpressionAsTypeLiteral"; + NodeBuilderFlags[NodeBuilderFlags["UseTypeOfFunction"] = 4096] = "UseTypeOfFunction"; + NodeBuilderFlags[NodeBuilderFlags["OmitParameterModifiers"] = 8192] = "OmitParameterModifiers"; + NodeBuilderFlags[NodeBuilderFlags["UseAliasDefinedOutsideCurrentScope"] = 16384] = "UseAliasDefinedOutsideCurrentScope"; + // Error handling + NodeBuilderFlags[NodeBuilderFlags["AllowThisInObjectLiteral"] = 32768] = "AllowThisInObjectLiteral"; + NodeBuilderFlags[NodeBuilderFlags["AllowQualifedNameInPlaceOfIdentifier"] = 65536] = "AllowQualifedNameInPlaceOfIdentifier"; + NodeBuilderFlags[NodeBuilderFlags["AllowAnonymousIdentifier"] = 131072] = "AllowAnonymousIdentifier"; + NodeBuilderFlags[NodeBuilderFlags["AllowEmptyUnionOrIntersection"] = 262144] = "AllowEmptyUnionOrIntersection"; + NodeBuilderFlags[NodeBuilderFlags["AllowEmptyTuple"] = 524288] = "AllowEmptyTuple"; + NodeBuilderFlags[NodeBuilderFlags["AllowUniqueESSymbolType"] = 1048576] = "AllowUniqueESSymbolType"; + NodeBuilderFlags[NodeBuilderFlags["AllowEmptyIndexInfoType"] = 2097152] = "AllowEmptyIndexInfoType"; + // Errors (cont.) + NodeBuilderFlags[NodeBuilderFlags["AllowNodeModulesRelativePaths"] = 67108864] = "AllowNodeModulesRelativePaths"; + /* @internal */ NodeBuilderFlags[NodeBuilderFlags["DoNotIncludeSymbolChain"] = 134217728] = "DoNotIncludeSymbolChain"; + NodeBuilderFlags[NodeBuilderFlags["IgnoreErrors"] = 70221824] = "IgnoreErrors"; + // State + NodeBuilderFlags[NodeBuilderFlags["InObjectTypeLiteral"] = 4194304] = "InObjectTypeLiteral"; + NodeBuilderFlags[NodeBuilderFlags["InTypeAlias"] = 8388608] = "InTypeAlias"; + NodeBuilderFlags[NodeBuilderFlags["InInitialEntityName"] = 16777216] = "InInitialEntityName"; + NodeBuilderFlags[NodeBuilderFlags["InReverseMappedType"] = 33554432] = "InReverseMappedType"; + })(NodeBuilderFlags = ts.NodeBuilderFlags || (ts.NodeBuilderFlags = {})); + // Ensure the shared flags between this and `NodeBuilderFlags` stay in alignment + var TypeFormatFlags; + (function (TypeFormatFlags) { + TypeFormatFlags[TypeFormatFlags["None"] = 0] = "None"; + TypeFormatFlags[TypeFormatFlags["NoTruncation"] = 1] = "NoTruncation"; + TypeFormatFlags[TypeFormatFlags["WriteArrayAsGenericType"] = 2] = "WriteArrayAsGenericType"; + // hole because there's a hole in node builder flags + TypeFormatFlags[TypeFormatFlags["UseStructuralFallback"] = 8] = "UseStructuralFallback"; + // hole because there's a hole in node builder flags + TypeFormatFlags[TypeFormatFlags["WriteTypeArgumentsOfSignature"] = 32] = "WriteTypeArgumentsOfSignature"; + TypeFormatFlags[TypeFormatFlags["UseFullyQualifiedType"] = 64] = "UseFullyQualifiedType"; + // hole because `UseOnlyExternalAliasing` is here in node builder flags, but functions which take old flags use `SymbolFormatFlags` instead + TypeFormatFlags[TypeFormatFlags["SuppressAnyReturnType"] = 256] = "SuppressAnyReturnType"; + // hole because `WriteTypeParametersInQualifiedName` is here in node builder flags, but functions which take old flags use `SymbolFormatFlags` for this instead + TypeFormatFlags[TypeFormatFlags["MultilineObjectLiterals"] = 1024] = "MultilineObjectLiterals"; + TypeFormatFlags[TypeFormatFlags["WriteClassExpressionAsTypeLiteral"] = 2048] = "WriteClassExpressionAsTypeLiteral"; + TypeFormatFlags[TypeFormatFlags["UseTypeOfFunction"] = 4096] = "UseTypeOfFunction"; + TypeFormatFlags[TypeFormatFlags["OmitParameterModifiers"] = 8192] = "OmitParameterModifiers"; + TypeFormatFlags[TypeFormatFlags["UseAliasDefinedOutsideCurrentScope"] = 16384] = "UseAliasDefinedOutsideCurrentScope"; + // even though `T` can't be accessed in the current scope. + // Error Handling + TypeFormatFlags[TypeFormatFlags["AllowUniqueESSymbolType"] = 1048576] = "AllowUniqueESSymbolType"; + // TypeFormatFlags exclusive + TypeFormatFlags[TypeFormatFlags["AddUndefined"] = 131072] = "AddUndefined"; + TypeFormatFlags[TypeFormatFlags["WriteArrowStyleSignature"] = 262144] = "WriteArrowStyleSignature"; + // State + TypeFormatFlags[TypeFormatFlags["InArrayType"] = 524288] = "InArrayType"; + TypeFormatFlags[TypeFormatFlags["InElementType"] = 2097152] = "InElementType"; + TypeFormatFlags[TypeFormatFlags["InFirstTypeArgument"] = 4194304] = "InFirstTypeArgument"; + TypeFormatFlags[TypeFormatFlags["InTypeAlias"] = 8388608] = "InTypeAlias"; + /** @deprecated */ TypeFormatFlags[TypeFormatFlags["WriteOwnNameForAnyLike"] = 0] = "WriteOwnNameForAnyLike"; + TypeFormatFlags[TypeFormatFlags["NodeBuilderFlagsMask"] = 9469291] = "NodeBuilderFlagsMask"; + })(TypeFormatFlags = ts.TypeFormatFlags || (ts.TypeFormatFlags = {})); + var SymbolFormatFlags; + (function (SymbolFormatFlags) { + SymbolFormatFlags[SymbolFormatFlags["None"] = 0] = "None"; + // Write symbols's type argument if it is instantiated symbol + // eg. class C { p: T } <-- Show p as C.p here + // var a: C; + // var p = a.p; <--- Here p is property of C so show it as C.p instead of just C.p + SymbolFormatFlags[SymbolFormatFlags["WriteTypeParametersOrArguments"] = 1] = "WriteTypeParametersOrArguments"; + // Use only external alias information to get the symbol name in the given context + // eg. module m { export class c { } } import x = m.c; + // When this flag is specified m.c will be used to refer to the class instead of alias symbol x + SymbolFormatFlags[SymbolFormatFlags["UseOnlyExternalAliasing"] = 2] = "UseOnlyExternalAliasing"; + // Build symbol name using any nodes needed, instead of just components of an entity name + SymbolFormatFlags[SymbolFormatFlags["AllowAnyNodeKind"] = 4] = "AllowAnyNodeKind"; + // Prefer aliases which are not directly visible + SymbolFormatFlags[SymbolFormatFlags["UseAliasDefinedOutsideCurrentScope"] = 8] = "UseAliasDefinedOutsideCurrentScope"; + // Skip building an accessible symbol chain + /* @internal */ SymbolFormatFlags[SymbolFormatFlags["DoNotIncludeSymbolChain"] = 16] = "DoNotIncludeSymbolChain"; + })(SymbolFormatFlags = ts.SymbolFormatFlags || (ts.SymbolFormatFlags = {})); + /* @internal */ + var SymbolAccessibility; + (function (SymbolAccessibility) { + SymbolAccessibility[SymbolAccessibility["Accessible"] = 0] = "Accessible"; + SymbolAccessibility[SymbolAccessibility["NotAccessible"] = 1] = "NotAccessible"; + SymbolAccessibility[SymbolAccessibility["CannotBeNamed"] = 2] = "CannotBeNamed"; + })(SymbolAccessibility = ts.SymbolAccessibility || (ts.SymbolAccessibility = {})); + /* @internal */ + var SyntheticSymbolKind; + (function (SyntheticSymbolKind) { + SyntheticSymbolKind[SyntheticSymbolKind["UnionOrIntersection"] = 0] = "UnionOrIntersection"; + SyntheticSymbolKind[SyntheticSymbolKind["Spread"] = 1] = "Spread"; + })(SyntheticSymbolKind = ts.SyntheticSymbolKind || (ts.SyntheticSymbolKind = {})); + var TypePredicateKind; + (function (TypePredicateKind) { + TypePredicateKind[TypePredicateKind["This"] = 0] = "This"; + TypePredicateKind[TypePredicateKind["Identifier"] = 1] = "Identifier"; + })(TypePredicateKind = ts.TypePredicateKind || (ts.TypePredicateKind = {})); + /** Indicates how to serialize the name for a TypeReferenceNode when emitting decorator metadata */ + /* @internal */ + var TypeReferenceSerializationKind; + (function (TypeReferenceSerializationKind) { + TypeReferenceSerializationKind[TypeReferenceSerializationKind["Unknown"] = 0] = "Unknown"; + // should be emitted using a safe fallback. + TypeReferenceSerializationKind[TypeReferenceSerializationKind["TypeWithConstructSignatureAndValue"] = 1] = "TypeWithConstructSignatureAndValue"; + // function that can be reached at runtime (e.g. a `class` + // declaration or a `var` declaration for the static side + // of a type, such as the global `Promise` type in lib.d.ts). + TypeReferenceSerializationKind[TypeReferenceSerializationKind["VoidNullableOrNeverType"] = 2] = "VoidNullableOrNeverType"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["NumberLikeType"] = 3] = "NumberLikeType"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["BigIntLikeType"] = 4] = "BigIntLikeType"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["StringLikeType"] = 5] = "StringLikeType"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["BooleanType"] = 6] = "BooleanType"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["ArrayLikeType"] = 7] = "ArrayLikeType"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["ESSymbolType"] = 8] = "ESSymbolType"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["Promise"] = 9] = "Promise"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["TypeWithCallSignature"] = 10] = "TypeWithCallSignature"; + // with call signatures. + TypeReferenceSerializationKind[TypeReferenceSerializationKind["ObjectType"] = 11] = "ObjectType"; + })(TypeReferenceSerializationKind = ts.TypeReferenceSerializationKind || (ts.TypeReferenceSerializationKind = {})); + var SymbolFlags; + (function (SymbolFlags) { + SymbolFlags[SymbolFlags["None"] = 0] = "None"; + SymbolFlags[SymbolFlags["FunctionScopedVariable"] = 1] = "FunctionScopedVariable"; + SymbolFlags[SymbolFlags["BlockScopedVariable"] = 2] = "BlockScopedVariable"; + SymbolFlags[SymbolFlags["Property"] = 4] = "Property"; + SymbolFlags[SymbolFlags["EnumMember"] = 8] = "EnumMember"; + SymbolFlags[SymbolFlags["Function"] = 16] = "Function"; + SymbolFlags[SymbolFlags["Class"] = 32] = "Class"; + SymbolFlags[SymbolFlags["Interface"] = 64] = "Interface"; + SymbolFlags[SymbolFlags["ConstEnum"] = 128] = "ConstEnum"; + SymbolFlags[SymbolFlags["RegularEnum"] = 256] = "RegularEnum"; + SymbolFlags[SymbolFlags["ValueModule"] = 512] = "ValueModule"; + SymbolFlags[SymbolFlags["NamespaceModule"] = 1024] = "NamespaceModule"; + SymbolFlags[SymbolFlags["TypeLiteral"] = 2048] = "TypeLiteral"; + SymbolFlags[SymbolFlags["ObjectLiteral"] = 4096] = "ObjectLiteral"; + SymbolFlags[SymbolFlags["Method"] = 8192] = "Method"; + SymbolFlags[SymbolFlags["Constructor"] = 16384] = "Constructor"; + SymbolFlags[SymbolFlags["GetAccessor"] = 32768] = "GetAccessor"; + SymbolFlags[SymbolFlags["SetAccessor"] = 65536] = "SetAccessor"; + SymbolFlags[SymbolFlags["Signature"] = 131072] = "Signature"; + SymbolFlags[SymbolFlags["TypeParameter"] = 262144] = "TypeParameter"; + SymbolFlags[SymbolFlags["TypeAlias"] = 524288] = "TypeAlias"; + SymbolFlags[SymbolFlags["ExportValue"] = 1048576] = "ExportValue"; + SymbolFlags[SymbolFlags["Alias"] = 2097152] = "Alias"; + SymbolFlags[SymbolFlags["Prototype"] = 4194304] = "Prototype"; + SymbolFlags[SymbolFlags["ExportStar"] = 8388608] = "ExportStar"; + SymbolFlags[SymbolFlags["Optional"] = 16777216] = "Optional"; + SymbolFlags[SymbolFlags["Transient"] = 33554432] = "Transient"; + SymbolFlags[SymbolFlags["Assignment"] = 67108864] = "Assignment"; + SymbolFlags[SymbolFlags["ModuleExports"] = 134217728] = "ModuleExports"; + /* @internal */ + SymbolFlags[SymbolFlags["All"] = 67108863] = "All"; + SymbolFlags[SymbolFlags["Enum"] = 384] = "Enum"; + SymbolFlags[SymbolFlags["Variable"] = 3] = "Variable"; + SymbolFlags[SymbolFlags["Value"] = 67220415] = "Value"; + SymbolFlags[SymbolFlags["Type"] = 67897832] = "Type"; + SymbolFlags[SymbolFlags["Namespace"] = 1920] = "Namespace"; + SymbolFlags[SymbolFlags["Module"] = 1536] = "Module"; + SymbolFlags[SymbolFlags["Accessor"] = 98304] = "Accessor"; + // Variables can be redeclared, but can not redeclare a block-scoped declaration with the + // same name, or any other value that is not a variable, e.g. ValueModule or Class + SymbolFlags[SymbolFlags["FunctionScopedVariableExcludes"] = 67220414] = "FunctionScopedVariableExcludes"; + // Block-scoped declarations are not allowed to be re-declared + // they can not merge with anything in the value space + SymbolFlags[SymbolFlags["BlockScopedVariableExcludes"] = 67220415] = "BlockScopedVariableExcludes"; + SymbolFlags[SymbolFlags["ParameterExcludes"] = 67220415] = "ParameterExcludes"; + SymbolFlags[SymbolFlags["PropertyExcludes"] = 0] = "PropertyExcludes"; + SymbolFlags[SymbolFlags["EnumMemberExcludes"] = 68008959] = "EnumMemberExcludes"; + SymbolFlags[SymbolFlags["FunctionExcludes"] = 67219887] = "FunctionExcludes"; + SymbolFlags[SymbolFlags["ClassExcludes"] = 68008383] = "ClassExcludes"; + SymbolFlags[SymbolFlags["InterfaceExcludes"] = 67897736] = "InterfaceExcludes"; + SymbolFlags[SymbolFlags["RegularEnumExcludes"] = 68008191] = "RegularEnumExcludes"; + SymbolFlags[SymbolFlags["ConstEnumExcludes"] = 68008831] = "ConstEnumExcludes"; + SymbolFlags[SymbolFlags["ValueModuleExcludes"] = 110735] = "ValueModuleExcludes"; + SymbolFlags[SymbolFlags["NamespaceModuleExcludes"] = 0] = "NamespaceModuleExcludes"; + SymbolFlags[SymbolFlags["MethodExcludes"] = 67212223] = "MethodExcludes"; + SymbolFlags[SymbolFlags["GetAccessorExcludes"] = 67154879] = "GetAccessorExcludes"; + SymbolFlags[SymbolFlags["SetAccessorExcludes"] = 67187647] = "SetAccessorExcludes"; + SymbolFlags[SymbolFlags["TypeParameterExcludes"] = 67635688] = "TypeParameterExcludes"; + SymbolFlags[SymbolFlags["TypeAliasExcludes"] = 67897832] = "TypeAliasExcludes"; + SymbolFlags[SymbolFlags["AliasExcludes"] = 2097152] = "AliasExcludes"; + SymbolFlags[SymbolFlags["ModuleMember"] = 2623475] = "ModuleMember"; + SymbolFlags[SymbolFlags["ExportHasLocal"] = 944] = "ExportHasLocal"; + SymbolFlags[SymbolFlags["BlockScoped"] = 418] = "BlockScoped"; + SymbolFlags[SymbolFlags["PropertyOrAccessor"] = 98308] = "PropertyOrAccessor"; + SymbolFlags[SymbolFlags["ClassMember"] = 106500] = "ClassMember"; + /* @internal */ + // The set of things we consider semantically classifiable. Used to speed up the LS during + // classification. + SymbolFlags[SymbolFlags["Classifiable"] = 2885600] = "Classifiable"; + /* @internal */ + SymbolFlags[SymbolFlags["LateBindingContainer"] = 6240] = "LateBindingContainer"; + })(SymbolFlags = ts.SymbolFlags || (ts.SymbolFlags = {})); + /* @internal */ + var EnumKind; + (function (EnumKind) { + EnumKind[EnumKind["Numeric"] = 0] = "Numeric"; + EnumKind[EnumKind["Literal"] = 1] = "Literal"; // Literal enum (each member has a TypeFlags.EnumLiteral type) + })(EnumKind = ts.EnumKind || (ts.EnumKind = {})); + /* @internal */ + var CheckFlags; + (function (CheckFlags) { + CheckFlags[CheckFlags["Instantiated"] = 1] = "Instantiated"; + CheckFlags[CheckFlags["SyntheticProperty"] = 2] = "SyntheticProperty"; + CheckFlags[CheckFlags["SyntheticMethod"] = 4] = "SyntheticMethod"; + CheckFlags[CheckFlags["Readonly"] = 8] = "Readonly"; + CheckFlags[CheckFlags["Partial"] = 16] = "Partial"; + CheckFlags[CheckFlags["HasNonUniformType"] = 32] = "HasNonUniformType"; + CheckFlags[CheckFlags["ContainsPublic"] = 64] = "ContainsPublic"; + CheckFlags[CheckFlags["ContainsProtected"] = 128] = "ContainsProtected"; + CheckFlags[CheckFlags["ContainsPrivate"] = 256] = "ContainsPrivate"; + CheckFlags[CheckFlags["ContainsStatic"] = 512] = "ContainsStatic"; + CheckFlags[CheckFlags["Late"] = 1024] = "Late"; + CheckFlags[CheckFlags["ReverseMapped"] = 2048] = "ReverseMapped"; + CheckFlags[CheckFlags["OptionalParameter"] = 4096] = "OptionalParameter"; + CheckFlags[CheckFlags["RestParameter"] = 8192] = "RestParameter"; + CheckFlags[CheckFlags["Synthetic"] = 6] = "Synthetic"; + })(CheckFlags = ts.CheckFlags || (ts.CheckFlags = {})); + var InternalSymbolName; + (function (InternalSymbolName) { + InternalSymbolName["Call"] = "__call"; + InternalSymbolName["Constructor"] = "__constructor"; + InternalSymbolName["New"] = "__new"; + InternalSymbolName["Index"] = "__index"; + InternalSymbolName["ExportStar"] = "__export"; + InternalSymbolName["Global"] = "__global"; + InternalSymbolName["Missing"] = "__missing"; + InternalSymbolName["Type"] = "__type"; + InternalSymbolName["Object"] = "__object"; + InternalSymbolName["JSXAttributes"] = "__jsxAttributes"; + InternalSymbolName["Class"] = "__class"; + InternalSymbolName["Function"] = "__function"; + InternalSymbolName["Computed"] = "__computed"; + InternalSymbolName["Resolving"] = "__resolving__"; + InternalSymbolName["ExportEquals"] = "export="; + InternalSymbolName["Default"] = "default"; + InternalSymbolName["This"] = "this"; + })(InternalSymbolName = ts.InternalSymbolName || (ts.InternalSymbolName = {})); + /* @internal */ + var NodeCheckFlags; + (function (NodeCheckFlags) { + NodeCheckFlags[NodeCheckFlags["TypeChecked"] = 1] = "TypeChecked"; + NodeCheckFlags[NodeCheckFlags["LexicalThis"] = 2] = "LexicalThis"; + NodeCheckFlags[NodeCheckFlags["CaptureThis"] = 4] = "CaptureThis"; + NodeCheckFlags[NodeCheckFlags["CaptureNewTarget"] = 8] = "CaptureNewTarget"; + NodeCheckFlags[NodeCheckFlags["SuperInstance"] = 256] = "SuperInstance"; + NodeCheckFlags[NodeCheckFlags["SuperStatic"] = 512] = "SuperStatic"; + NodeCheckFlags[NodeCheckFlags["ContextChecked"] = 1024] = "ContextChecked"; + NodeCheckFlags[NodeCheckFlags["AsyncMethodWithSuper"] = 2048] = "AsyncMethodWithSuper"; + NodeCheckFlags[NodeCheckFlags["AsyncMethodWithSuperBinding"] = 4096] = "AsyncMethodWithSuperBinding"; + NodeCheckFlags[NodeCheckFlags["CaptureArguments"] = 8192] = "CaptureArguments"; + NodeCheckFlags[NodeCheckFlags["EnumValuesComputed"] = 16384] = "EnumValuesComputed"; + NodeCheckFlags[NodeCheckFlags["LexicalModuleMergesWithClass"] = 32768] = "LexicalModuleMergesWithClass"; + NodeCheckFlags[NodeCheckFlags["LoopWithCapturedBlockScopedBinding"] = 65536] = "LoopWithCapturedBlockScopedBinding"; + NodeCheckFlags[NodeCheckFlags["ContainsCapturedBlockScopeBinding"] = 131072] = "ContainsCapturedBlockScopeBinding"; + NodeCheckFlags[NodeCheckFlags["CapturedBlockScopedBinding"] = 262144] = "CapturedBlockScopedBinding"; + NodeCheckFlags[NodeCheckFlags["BlockScopedBindingInLoop"] = 524288] = "BlockScopedBindingInLoop"; + NodeCheckFlags[NodeCheckFlags["ClassWithBodyScopedClassBinding"] = 1048576] = "ClassWithBodyScopedClassBinding"; + NodeCheckFlags[NodeCheckFlags["BodyScopedClassBinding"] = 2097152] = "BodyScopedClassBinding"; + NodeCheckFlags[NodeCheckFlags["NeedsLoopOutParameter"] = 4194304] = "NeedsLoopOutParameter"; + NodeCheckFlags[NodeCheckFlags["AssignmentsMarked"] = 8388608] = "AssignmentsMarked"; + NodeCheckFlags[NodeCheckFlags["ClassWithConstructorReference"] = 16777216] = "ClassWithConstructorReference"; + NodeCheckFlags[NodeCheckFlags["ConstructorReferenceInClass"] = 33554432] = "ConstructorReferenceInClass"; + })(NodeCheckFlags = ts.NodeCheckFlags || (ts.NodeCheckFlags = {})); + var TypeFlags; + (function (TypeFlags) { + TypeFlags[TypeFlags["Any"] = 1] = "Any"; + TypeFlags[TypeFlags["Unknown"] = 2] = "Unknown"; + TypeFlags[TypeFlags["String"] = 4] = "String"; + TypeFlags[TypeFlags["Number"] = 8] = "Number"; + TypeFlags[TypeFlags["Boolean"] = 16] = "Boolean"; + TypeFlags[TypeFlags["Enum"] = 32] = "Enum"; + TypeFlags[TypeFlags["BigInt"] = 64] = "BigInt"; + TypeFlags[TypeFlags["StringLiteral"] = 128] = "StringLiteral"; + TypeFlags[TypeFlags["NumberLiteral"] = 256] = "NumberLiteral"; + TypeFlags[TypeFlags["BooleanLiteral"] = 512] = "BooleanLiteral"; + TypeFlags[TypeFlags["EnumLiteral"] = 1024] = "EnumLiteral"; + TypeFlags[TypeFlags["BigIntLiteral"] = 2048] = "BigIntLiteral"; + TypeFlags[TypeFlags["ESSymbol"] = 4096] = "ESSymbol"; + TypeFlags[TypeFlags["UniqueESSymbol"] = 8192] = "UniqueESSymbol"; + TypeFlags[TypeFlags["Void"] = 16384] = "Void"; + TypeFlags[TypeFlags["Undefined"] = 32768] = "Undefined"; + TypeFlags[TypeFlags["Null"] = 65536] = "Null"; + TypeFlags[TypeFlags["Never"] = 131072] = "Never"; + TypeFlags[TypeFlags["TypeParameter"] = 262144] = "TypeParameter"; + TypeFlags[TypeFlags["Object"] = 524288] = "Object"; + TypeFlags[TypeFlags["Union"] = 1048576] = "Union"; + TypeFlags[TypeFlags["Intersection"] = 2097152] = "Intersection"; + TypeFlags[TypeFlags["Index"] = 4194304] = "Index"; + TypeFlags[TypeFlags["IndexedAccess"] = 8388608] = "IndexedAccess"; + TypeFlags[TypeFlags["Conditional"] = 16777216] = "Conditional"; + TypeFlags[TypeFlags["Substitution"] = 33554432] = "Substitution"; + TypeFlags[TypeFlags["NonPrimitive"] = 67108864] = "NonPrimitive"; + /* @internal */ + TypeFlags[TypeFlags["ContainsWideningType"] = 134217728] = "ContainsWideningType"; + /* @internal */ + TypeFlags[TypeFlags["ContainsObjectLiteral"] = 268435456] = "ContainsObjectLiteral"; + /* @internal */ + TypeFlags[TypeFlags["ContainsAnyFunctionType"] = 536870912] = "ContainsAnyFunctionType"; + /* @internal */ + TypeFlags[TypeFlags["AnyOrUnknown"] = 3] = "AnyOrUnknown"; + /* @internal */ + TypeFlags[TypeFlags["Nullable"] = 98304] = "Nullable"; + TypeFlags[TypeFlags["Literal"] = 2944] = "Literal"; + TypeFlags[TypeFlags["Unit"] = 109440] = "Unit"; + TypeFlags[TypeFlags["StringOrNumberLiteral"] = 384] = "StringOrNumberLiteral"; + /* @internal */ + TypeFlags[TypeFlags["StringOrNumberLiteralOrUnique"] = 8576] = "StringOrNumberLiteralOrUnique"; + /* @internal */ + TypeFlags[TypeFlags["DefinitelyFalsy"] = 117632] = "DefinitelyFalsy"; + TypeFlags[TypeFlags["PossiblyFalsy"] = 117724] = "PossiblyFalsy"; + /* @internal */ + TypeFlags[TypeFlags["Intrinsic"] = 67359327] = "Intrinsic"; + /* @internal */ + TypeFlags[TypeFlags["Primitive"] = 131068] = "Primitive"; + TypeFlags[TypeFlags["StringLike"] = 132] = "StringLike"; + TypeFlags[TypeFlags["NumberLike"] = 296] = "NumberLike"; + TypeFlags[TypeFlags["BigIntLike"] = 2112] = "BigIntLike"; + TypeFlags[TypeFlags["BooleanLike"] = 528] = "BooleanLike"; + TypeFlags[TypeFlags["EnumLike"] = 1056] = "EnumLike"; + TypeFlags[TypeFlags["ESSymbolLike"] = 12288] = "ESSymbolLike"; + TypeFlags[TypeFlags["VoidLike"] = 49152] = "VoidLike"; + /* @internal */ + TypeFlags[TypeFlags["DisjointDomains"] = 67238908] = "DisjointDomains"; + TypeFlags[TypeFlags["UnionOrIntersection"] = 3145728] = "UnionOrIntersection"; + TypeFlags[TypeFlags["StructuredType"] = 3670016] = "StructuredType"; + TypeFlags[TypeFlags["TypeVariable"] = 8650752] = "TypeVariable"; + TypeFlags[TypeFlags["InstantiableNonPrimitive"] = 58982400] = "InstantiableNonPrimitive"; + TypeFlags[TypeFlags["InstantiablePrimitive"] = 4194304] = "InstantiablePrimitive"; + TypeFlags[TypeFlags["Instantiable"] = 63176704] = "Instantiable"; + TypeFlags[TypeFlags["StructuredOrInstantiable"] = 66846720] = "StructuredOrInstantiable"; + // 'Narrowable' types are types where narrowing actually narrows. + // This *should* be every type other than null, undefined, void, and never + TypeFlags[TypeFlags["Narrowable"] = 133970943] = "Narrowable"; + TypeFlags[TypeFlags["NotUnionOrUnit"] = 67637251] = "NotUnionOrUnit"; + /* @internal */ + TypeFlags[TypeFlags["NotPrimitiveUnion"] = 66994211] = "NotPrimitiveUnion"; + /* @internal */ + TypeFlags[TypeFlags["RequiresWidening"] = 402653184] = "RequiresWidening"; + /* @internal */ + TypeFlags[TypeFlags["PropagatingFlags"] = 939524096] = "PropagatingFlags"; + // The following flags are used for different purposes during union and intersection type construction + /* @internal */ + TypeFlags[TypeFlags["NonWideningType"] = 134217728] = "NonWideningType"; + /* @internal */ + TypeFlags[TypeFlags["Wildcard"] = 268435456] = "Wildcard"; + /* @internal */ + TypeFlags[TypeFlags["EmptyObject"] = 536870912] = "EmptyObject"; + /* @internal */ + TypeFlags[TypeFlags["ConstructionFlags"] = 939524096] = "ConstructionFlags"; + // The following flag is used for different purposes by maybeTypeOfKind + /* @internal */ + TypeFlags[TypeFlags["GenericMappedType"] = 134217728] = "GenericMappedType"; + })(TypeFlags = ts.TypeFlags || (ts.TypeFlags = {})); + var ObjectFlags; + (function (ObjectFlags) { + ObjectFlags[ObjectFlags["Class"] = 1] = "Class"; + ObjectFlags[ObjectFlags["Interface"] = 2] = "Interface"; + ObjectFlags[ObjectFlags["Reference"] = 4] = "Reference"; + ObjectFlags[ObjectFlags["Tuple"] = 8] = "Tuple"; + ObjectFlags[ObjectFlags["Anonymous"] = 16] = "Anonymous"; + ObjectFlags[ObjectFlags["Mapped"] = 32] = "Mapped"; + ObjectFlags[ObjectFlags["Instantiated"] = 64] = "Instantiated"; + ObjectFlags[ObjectFlags["ObjectLiteral"] = 128] = "ObjectLiteral"; + ObjectFlags[ObjectFlags["EvolvingArray"] = 256] = "EvolvingArray"; + ObjectFlags[ObjectFlags["ObjectLiteralPatternWithComputedProperties"] = 512] = "ObjectLiteralPatternWithComputedProperties"; + ObjectFlags[ObjectFlags["ContainsSpread"] = 1024] = "ContainsSpread"; + ObjectFlags[ObjectFlags["ReverseMapped"] = 2048] = "ReverseMapped"; + ObjectFlags[ObjectFlags["JsxAttributes"] = 4096] = "JsxAttributes"; + ObjectFlags[ObjectFlags["MarkerType"] = 8192] = "MarkerType"; + ObjectFlags[ObjectFlags["JSLiteral"] = 16384] = "JSLiteral"; + ObjectFlags[ObjectFlags["FreshLiteral"] = 32768] = "FreshLiteral"; + ObjectFlags[ObjectFlags["ClassOrInterface"] = 3] = "ClassOrInterface"; + })(ObjectFlags = ts.ObjectFlags || (ts.ObjectFlags = {})); + /* @internal */ + var Variance; + (function (Variance) { + Variance[Variance["Invariant"] = 0] = "Invariant"; + Variance[Variance["Covariant"] = 1] = "Covariant"; + Variance[Variance["Contravariant"] = 2] = "Contravariant"; + Variance[Variance["Bivariant"] = 3] = "Bivariant"; + Variance[Variance["Independent"] = 4] = "Independent"; + })(Variance = ts.Variance || (ts.Variance = {})); + /* @internal */ + var JsxReferenceKind; + (function (JsxReferenceKind) { + JsxReferenceKind[JsxReferenceKind["Component"] = 0] = "Component"; + JsxReferenceKind[JsxReferenceKind["Function"] = 1] = "Function"; + JsxReferenceKind[JsxReferenceKind["Mixed"] = 2] = "Mixed"; + })(JsxReferenceKind = ts.JsxReferenceKind || (ts.JsxReferenceKind = {})); + var SignatureKind; + (function (SignatureKind) { + SignatureKind[SignatureKind["Call"] = 0] = "Call"; + SignatureKind[SignatureKind["Construct"] = 1] = "Construct"; + })(SignatureKind = ts.SignatureKind || (ts.SignatureKind = {})); + var IndexKind; + (function (IndexKind) { + IndexKind[IndexKind["String"] = 0] = "String"; + IndexKind[IndexKind["Number"] = 1] = "Number"; + })(IndexKind = ts.IndexKind || (ts.IndexKind = {})); + var InferencePriority; + (function (InferencePriority) { + InferencePriority[InferencePriority["NakedTypeVariable"] = 1] = "NakedTypeVariable"; + InferencePriority[InferencePriority["HomomorphicMappedType"] = 2] = "HomomorphicMappedType"; + InferencePriority[InferencePriority["MappedTypeConstraint"] = 4] = "MappedTypeConstraint"; + InferencePriority[InferencePriority["ReturnType"] = 8] = "ReturnType"; + InferencePriority[InferencePriority["LiteralKeyof"] = 16] = "LiteralKeyof"; + InferencePriority[InferencePriority["NoConstraints"] = 32] = "NoConstraints"; + InferencePriority[InferencePriority["AlwaysStrict"] = 64] = "AlwaysStrict"; + InferencePriority[InferencePriority["PriorityImpliesCombination"] = 28] = "PriorityImpliesCombination"; + })(InferencePriority = ts.InferencePriority || (ts.InferencePriority = {})); + /* @internal */ + var InferenceFlags; + (function (InferenceFlags) { + InferenceFlags[InferenceFlags["None"] = 0] = "None"; + InferenceFlags[InferenceFlags["NoDefault"] = 1] = "NoDefault"; + InferenceFlags[InferenceFlags["AnyDefault"] = 2] = "AnyDefault"; + })(InferenceFlags = ts.InferenceFlags || (ts.InferenceFlags = {})); + /** + * Ternary values are defined such that + * x & y is False if either x or y is False. + * x & y is Maybe if either x or y is Maybe, but neither x or y is False. + * x & y is True if both x and y are True. + * x | y is False if both x and y are False. + * x | y is Maybe if either x or y is Maybe, but neither x or y is True. + * x | y is True if either x or y is True. + */ + /* @internal */ + var Ternary; + (function (Ternary) { + Ternary[Ternary["False"] = 0] = "False"; + Ternary[Ternary["Maybe"] = 1] = "Maybe"; + Ternary[Ternary["True"] = -1] = "True"; + })(Ternary = ts.Ternary || (ts.Ternary = {})); + /* @internal */ + var AssignmentDeclarationKind; + (function (AssignmentDeclarationKind) { + AssignmentDeclarationKind[AssignmentDeclarationKind["None"] = 0] = "None"; + /// exports.name = expr + AssignmentDeclarationKind[AssignmentDeclarationKind["ExportsProperty"] = 1] = "ExportsProperty"; + /// module.exports = expr + AssignmentDeclarationKind[AssignmentDeclarationKind["ModuleExports"] = 2] = "ModuleExports"; + /// className.prototype.name = expr + AssignmentDeclarationKind[AssignmentDeclarationKind["PrototypeProperty"] = 3] = "PrototypeProperty"; + /// this.name = expr + AssignmentDeclarationKind[AssignmentDeclarationKind["ThisProperty"] = 4] = "ThisProperty"; + // F.name = expr + AssignmentDeclarationKind[AssignmentDeclarationKind["Property"] = 5] = "Property"; + // F.prototype = { ... } + AssignmentDeclarationKind[AssignmentDeclarationKind["Prototype"] = 6] = "Prototype"; + // Object.defineProperty(x, 'name', { value: any, writable?: boolean (false by default) }); + // Object.defineProperty(x, 'name', { get: Function, set: Function }); + // Object.defineProperty(x, 'name', { get: Function }); + // Object.defineProperty(x, 'name', { set: Function }); + AssignmentDeclarationKind[AssignmentDeclarationKind["ObjectDefinePropertyValue"] = 7] = "ObjectDefinePropertyValue"; + // Object.defineProperty(exports || module.exports, 'name', ...); + AssignmentDeclarationKind[AssignmentDeclarationKind["ObjectDefinePropertyExports"] = 8] = "ObjectDefinePropertyExports"; + // Object.defineProperty(Foo.prototype, 'name', ...); + AssignmentDeclarationKind[AssignmentDeclarationKind["ObjectDefinePrototypeProperty"] = 9] = "ObjectDefinePrototypeProperty"; + })(AssignmentDeclarationKind = ts.AssignmentDeclarationKind || (ts.AssignmentDeclarationKind = {})); + var DiagnosticCategory; + (function (DiagnosticCategory) { + DiagnosticCategory[DiagnosticCategory["Warning"] = 0] = "Warning"; + DiagnosticCategory[DiagnosticCategory["Error"] = 1] = "Error"; + DiagnosticCategory[DiagnosticCategory["Suggestion"] = 2] = "Suggestion"; + DiagnosticCategory[DiagnosticCategory["Message"] = 3] = "Message"; + })(DiagnosticCategory = ts.DiagnosticCategory || (ts.DiagnosticCategory = {})); + /* @internal */ + function diagnosticCategoryName(d, lowerCase) { + if (lowerCase === void 0) { lowerCase = true; } + var name = DiagnosticCategory[d.category]; + return lowerCase ? name.toLowerCase() : name; + } + ts.diagnosticCategoryName = diagnosticCategoryName; + var ModuleResolutionKind; + (function (ModuleResolutionKind) { + ModuleResolutionKind[ModuleResolutionKind["Classic"] = 1] = "Classic"; + ModuleResolutionKind[ModuleResolutionKind["NodeJs"] = 2] = "NodeJs"; + })(ModuleResolutionKind = ts.ModuleResolutionKind || (ts.ModuleResolutionKind = {})); + var ModuleKind; + (function (ModuleKind) { + ModuleKind[ModuleKind["None"] = 0] = "None"; + ModuleKind[ModuleKind["CommonJS"] = 1] = "CommonJS"; + ModuleKind[ModuleKind["AMD"] = 2] = "AMD"; + ModuleKind[ModuleKind["UMD"] = 3] = "UMD"; + ModuleKind[ModuleKind["System"] = 4] = "System"; + ModuleKind[ModuleKind["ES2015"] = 5] = "ES2015"; + ModuleKind[ModuleKind["ESNext"] = 6] = "ESNext"; + })(ModuleKind = ts.ModuleKind || (ts.ModuleKind = {})); + var JsxEmit; + (function (JsxEmit) { + JsxEmit[JsxEmit["None"] = 0] = "None"; + JsxEmit[JsxEmit["Preserve"] = 1] = "Preserve"; + JsxEmit[JsxEmit["React"] = 2] = "React"; + JsxEmit[JsxEmit["ReactNative"] = 3] = "ReactNative"; + })(JsxEmit = ts.JsxEmit || (ts.JsxEmit = {})); + var NewLineKind; + (function (NewLineKind) { + NewLineKind[NewLineKind["CarriageReturnLineFeed"] = 0] = "CarriageReturnLineFeed"; + NewLineKind[NewLineKind["LineFeed"] = 1] = "LineFeed"; + })(NewLineKind = ts.NewLineKind || (ts.NewLineKind = {})); + var ScriptKind; + (function (ScriptKind) { + ScriptKind[ScriptKind["Unknown"] = 0] = "Unknown"; + ScriptKind[ScriptKind["JS"] = 1] = "JS"; + ScriptKind[ScriptKind["JSX"] = 2] = "JSX"; + ScriptKind[ScriptKind["TS"] = 3] = "TS"; + ScriptKind[ScriptKind["TSX"] = 4] = "TSX"; + ScriptKind[ScriptKind["External"] = 5] = "External"; + ScriptKind[ScriptKind["JSON"] = 6] = "JSON"; + /** + * Used on extensions that doesn't define the ScriptKind but the content defines it. + * Deferred extensions are going to be included in all project contexts. + */ + ScriptKind[ScriptKind["Deferred"] = 7] = "Deferred"; + })(ScriptKind = ts.ScriptKind || (ts.ScriptKind = {})); + var ScriptTarget; + (function (ScriptTarget) { + ScriptTarget[ScriptTarget["ES3"] = 0] = "ES3"; + ScriptTarget[ScriptTarget["ES5"] = 1] = "ES5"; + ScriptTarget[ScriptTarget["ES2015"] = 2] = "ES2015"; + ScriptTarget[ScriptTarget["ES2016"] = 3] = "ES2016"; + ScriptTarget[ScriptTarget["ES2017"] = 4] = "ES2017"; + ScriptTarget[ScriptTarget["ES2018"] = 5] = "ES2018"; + ScriptTarget[ScriptTarget["ESNext"] = 6] = "ESNext"; + ScriptTarget[ScriptTarget["JSON"] = 100] = "JSON"; + ScriptTarget[ScriptTarget["Latest"] = 6] = "Latest"; + })(ScriptTarget = ts.ScriptTarget || (ts.ScriptTarget = {})); + var LanguageVariant; + (function (LanguageVariant) { + LanguageVariant[LanguageVariant["Standard"] = 0] = "Standard"; + LanguageVariant[LanguageVariant["JSX"] = 1] = "JSX"; + })(LanguageVariant = ts.LanguageVariant || (ts.LanguageVariant = {})); + var WatchDirectoryFlags; + (function (WatchDirectoryFlags) { + WatchDirectoryFlags[WatchDirectoryFlags["None"] = 0] = "None"; + WatchDirectoryFlags[WatchDirectoryFlags["Recursive"] = 1] = "Recursive"; + })(WatchDirectoryFlags = ts.WatchDirectoryFlags || (ts.WatchDirectoryFlags = {})); + /* @internal */ + var CharacterCodes; + (function (CharacterCodes) { + CharacterCodes[CharacterCodes["nullCharacter"] = 0] = "nullCharacter"; + CharacterCodes[CharacterCodes["maxAsciiCharacter"] = 127] = "maxAsciiCharacter"; + CharacterCodes[CharacterCodes["lineFeed"] = 10] = "lineFeed"; + CharacterCodes[CharacterCodes["carriageReturn"] = 13] = "carriageReturn"; + CharacterCodes[CharacterCodes["lineSeparator"] = 8232] = "lineSeparator"; + CharacterCodes[CharacterCodes["paragraphSeparator"] = 8233] = "paragraphSeparator"; + CharacterCodes[CharacterCodes["nextLine"] = 133] = "nextLine"; + // Unicode 3.0 space characters + CharacterCodes[CharacterCodes["space"] = 32] = "space"; + CharacterCodes[CharacterCodes["nonBreakingSpace"] = 160] = "nonBreakingSpace"; + CharacterCodes[CharacterCodes["enQuad"] = 8192] = "enQuad"; + CharacterCodes[CharacterCodes["emQuad"] = 8193] = "emQuad"; + CharacterCodes[CharacterCodes["enSpace"] = 8194] = "enSpace"; + CharacterCodes[CharacterCodes["emSpace"] = 8195] = "emSpace"; + CharacterCodes[CharacterCodes["threePerEmSpace"] = 8196] = "threePerEmSpace"; + CharacterCodes[CharacterCodes["fourPerEmSpace"] = 8197] = "fourPerEmSpace"; + CharacterCodes[CharacterCodes["sixPerEmSpace"] = 8198] = "sixPerEmSpace"; + CharacterCodes[CharacterCodes["figureSpace"] = 8199] = "figureSpace"; + CharacterCodes[CharacterCodes["punctuationSpace"] = 8200] = "punctuationSpace"; + CharacterCodes[CharacterCodes["thinSpace"] = 8201] = "thinSpace"; + CharacterCodes[CharacterCodes["hairSpace"] = 8202] = "hairSpace"; + CharacterCodes[CharacterCodes["zeroWidthSpace"] = 8203] = "zeroWidthSpace"; + CharacterCodes[CharacterCodes["narrowNoBreakSpace"] = 8239] = "narrowNoBreakSpace"; + CharacterCodes[CharacterCodes["ideographicSpace"] = 12288] = "ideographicSpace"; + CharacterCodes[CharacterCodes["mathematicalSpace"] = 8287] = "mathematicalSpace"; + CharacterCodes[CharacterCodes["ogham"] = 5760] = "ogham"; + CharacterCodes[CharacterCodes["_"] = 95] = "_"; + CharacterCodes[CharacterCodes["$"] = 36] = "$"; + CharacterCodes[CharacterCodes["_0"] = 48] = "_0"; + CharacterCodes[CharacterCodes["_1"] = 49] = "_1"; + CharacterCodes[CharacterCodes["_2"] = 50] = "_2"; + CharacterCodes[CharacterCodes["_3"] = 51] = "_3"; + CharacterCodes[CharacterCodes["_4"] = 52] = "_4"; + CharacterCodes[CharacterCodes["_5"] = 53] = "_5"; + CharacterCodes[CharacterCodes["_6"] = 54] = "_6"; + CharacterCodes[CharacterCodes["_7"] = 55] = "_7"; + CharacterCodes[CharacterCodes["_8"] = 56] = "_8"; + CharacterCodes[CharacterCodes["_9"] = 57] = "_9"; + CharacterCodes[CharacterCodes["a"] = 97] = "a"; + CharacterCodes[CharacterCodes["b"] = 98] = "b"; + CharacterCodes[CharacterCodes["c"] = 99] = "c"; + CharacterCodes[CharacterCodes["d"] = 100] = "d"; + CharacterCodes[CharacterCodes["e"] = 101] = "e"; + CharacterCodes[CharacterCodes["f"] = 102] = "f"; + CharacterCodes[CharacterCodes["g"] = 103] = "g"; + CharacterCodes[CharacterCodes["h"] = 104] = "h"; + CharacterCodes[CharacterCodes["i"] = 105] = "i"; + CharacterCodes[CharacterCodes["j"] = 106] = "j"; + CharacterCodes[CharacterCodes["k"] = 107] = "k"; + CharacterCodes[CharacterCodes["l"] = 108] = "l"; + CharacterCodes[CharacterCodes["m"] = 109] = "m"; + CharacterCodes[CharacterCodes["n"] = 110] = "n"; + CharacterCodes[CharacterCodes["o"] = 111] = "o"; + CharacterCodes[CharacterCodes["p"] = 112] = "p"; + CharacterCodes[CharacterCodes["q"] = 113] = "q"; + CharacterCodes[CharacterCodes["r"] = 114] = "r"; + CharacterCodes[CharacterCodes["s"] = 115] = "s"; + CharacterCodes[CharacterCodes["t"] = 116] = "t"; + CharacterCodes[CharacterCodes["u"] = 117] = "u"; + CharacterCodes[CharacterCodes["v"] = 118] = "v"; + CharacterCodes[CharacterCodes["w"] = 119] = "w"; + CharacterCodes[CharacterCodes["x"] = 120] = "x"; + CharacterCodes[CharacterCodes["y"] = 121] = "y"; + CharacterCodes[CharacterCodes["z"] = 122] = "z"; + CharacterCodes[CharacterCodes["A"] = 65] = "A"; + CharacterCodes[CharacterCodes["B"] = 66] = "B"; + CharacterCodes[CharacterCodes["C"] = 67] = "C"; + CharacterCodes[CharacterCodes["D"] = 68] = "D"; + CharacterCodes[CharacterCodes["E"] = 69] = "E"; + CharacterCodes[CharacterCodes["F"] = 70] = "F"; + CharacterCodes[CharacterCodes["G"] = 71] = "G"; + CharacterCodes[CharacterCodes["H"] = 72] = "H"; + CharacterCodes[CharacterCodes["I"] = 73] = "I"; + CharacterCodes[CharacterCodes["J"] = 74] = "J"; + CharacterCodes[CharacterCodes["K"] = 75] = "K"; + CharacterCodes[CharacterCodes["L"] = 76] = "L"; + CharacterCodes[CharacterCodes["M"] = 77] = "M"; + CharacterCodes[CharacterCodes["N"] = 78] = "N"; + CharacterCodes[CharacterCodes["O"] = 79] = "O"; + CharacterCodes[CharacterCodes["P"] = 80] = "P"; + CharacterCodes[CharacterCodes["Q"] = 81] = "Q"; + CharacterCodes[CharacterCodes["R"] = 82] = "R"; + CharacterCodes[CharacterCodes["S"] = 83] = "S"; + CharacterCodes[CharacterCodes["T"] = 84] = "T"; + CharacterCodes[CharacterCodes["U"] = 85] = "U"; + CharacterCodes[CharacterCodes["V"] = 86] = "V"; + CharacterCodes[CharacterCodes["W"] = 87] = "W"; + CharacterCodes[CharacterCodes["X"] = 88] = "X"; + CharacterCodes[CharacterCodes["Y"] = 89] = "Y"; + CharacterCodes[CharacterCodes["Z"] = 90] = "Z"; + CharacterCodes[CharacterCodes["ampersand"] = 38] = "ampersand"; + CharacterCodes[CharacterCodes["asterisk"] = 42] = "asterisk"; + CharacterCodes[CharacterCodes["at"] = 64] = "at"; + CharacterCodes[CharacterCodes["backslash"] = 92] = "backslash"; + CharacterCodes[CharacterCodes["backtick"] = 96] = "backtick"; + CharacterCodes[CharacterCodes["bar"] = 124] = "bar"; + CharacterCodes[CharacterCodes["caret"] = 94] = "caret"; + CharacterCodes[CharacterCodes["closeBrace"] = 125] = "closeBrace"; + CharacterCodes[CharacterCodes["closeBracket"] = 93] = "closeBracket"; + CharacterCodes[CharacterCodes["closeParen"] = 41] = "closeParen"; + CharacterCodes[CharacterCodes["colon"] = 58] = "colon"; + CharacterCodes[CharacterCodes["comma"] = 44] = "comma"; + CharacterCodes[CharacterCodes["dot"] = 46] = "dot"; + CharacterCodes[CharacterCodes["doubleQuote"] = 34] = "doubleQuote"; + CharacterCodes[CharacterCodes["equals"] = 61] = "equals"; + CharacterCodes[CharacterCodes["exclamation"] = 33] = "exclamation"; + CharacterCodes[CharacterCodes["greaterThan"] = 62] = "greaterThan"; + CharacterCodes[CharacterCodes["hash"] = 35] = "hash"; + CharacterCodes[CharacterCodes["lessThan"] = 60] = "lessThan"; + CharacterCodes[CharacterCodes["minus"] = 45] = "minus"; + CharacterCodes[CharacterCodes["openBrace"] = 123] = "openBrace"; + CharacterCodes[CharacterCodes["openBracket"] = 91] = "openBracket"; + CharacterCodes[CharacterCodes["openParen"] = 40] = "openParen"; + CharacterCodes[CharacterCodes["percent"] = 37] = "percent"; + CharacterCodes[CharacterCodes["plus"] = 43] = "plus"; + CharacterCodes[CharacterCodes["question"] = 63] = "question"; + CharacterCodes[CharacterCodes["semicolon"] = 59] = "semicolon"; + CharacterCodes[CharacterCodes["singleQuote"] = 39] = "singleQuote"; + CharacterCodes[CharacterCodes["slash"] = 47] = "slash"; + CharacterCodes[CharacterCodes["tilde"] = 126] = "tilde"; + CharacterCodes[CharacterCodes["backspace"] = 8] = "backspace"; + CharacterCodes[CharacterCodes["formFeed"] = 12] = "formFeed"; + CharacterCodes[CharacterCodes["byteOrderMark"] = 65279] = "byteOrderMark"; + CharacterCodes[CharacterCodes["tab"] = 9] = "tab"; + CharacterCodes[CharacterCodes["verticalTab"] = 11] = "verticalTab"; + })(CharacterCodes = ts.CharacterCodes || (ts.CharacterCodes = {})); + var Extension; + (function (Extension) { + Extension["Ts"] = ".ts"; + Extension["Tsx"] = ".tsx"; + Extension["Dts"] = ".d.ts"; + Extension["Js"] = ".js"; + Extension["Jsx"] = ".jsx"; + Extension["Json"] = ".json"; + })(Extension = ts.Extension || (ts.Extension = {})); + /* @internal */ + var TransformFlags; + (function (TransformFlags) { + TransformFlags[TransformFlags["None"] = 0] = "None"; + // Facts + // - Flags used to indicate that a node or subtree contains syntax that requires transformation. + TransformFlags[TransformFlags["TypeScript"] = 1] = "TypeScript"; + TransformFlags[TransformFlags["ContainsTypeScript"] = 2] = "ContainsTypeScript"; + TransformFlags[TransformFlags["ContainsJsx"] = 4] = "ContainsJsx"; + TransformFlags[TransformFlags["ContainsESNext"] = 8] = "ContainsESNext"; + TransformFlags[TransformFlags["ContainsES2017"] = 16] = "ContainsES2017"; + TransformFlags[TransformFlags["ContainsES2016"] = 32] = "ContainsES2016"; + TransformFlags[TransformFlags["ES2015"] = 64] = "ES2015"; + TransformFlags[TransformFlags["ContainsES2015"] = 128] = "ContainsES2015"; + TransformFlags[TransformFlags["Generator"] = 256] = "Generator"; + TransformFlags[TransformFlags["ContainsGenerator"] = 512] = "ContainsGenerator"; + TransformFlags[TransformFlags["DestructuringAssignment"] = 1024] = "DestructuringAssignment"; + TransformFlags[TransformFlags["ContainsDestructuringAssignment"] = 2048] = "ContainsDestructuringAssignment"; + // Markers + // - Flags used to indicate that a subtree contains a specific transformation. + TransformFlags[TransformFlags["ContainsTypeScriptClassSyntax"] = 4096] = "ContainsTypeScriptClassSyntax"; + TransformFlags[TransformFlags["ContainsLexicalThis"] = 8192] = "ContainsLexicalThis"; + TransformFlags[TransformFlags["ContainsCapturedLexicalThis"] = 16384] = "ContainsCapturedLexicalThis"; + TransformFlags[TransformFlags["ContainsLexicalThisInComputedPropertyName"] = 32768] = "ContainsLexicalThisInComputedPropertyName"; + TransformFlags[TransformFlags["ContainsDefaultValueAssignments"] = 65536] = "ContainsDefaultValueAssignments"; + TransformFlags[TransformFlags["ContainsRestOrSpread"] = 131072] = "ContainsRestOrSpread"; + TransformFlags[TransformFlags["ContainsObjectRestOrSpread"] = 262144] = "ContainsObjectRestOrSpread"; + TransformFlags[TransformFlags["ContainsComputedPropertyName"] = 524288] = "ContainsComputedPropertyName"; + TransformFlags[TransformFlags["ContainsBlockScopedBinding"] = 1048576] = "ContainsBlockScopedBinding"; + TransformFlags[TransformFlags["ContainsBindingPattern"] = 2097152] = "ContainsBindingPattern"; + TransformFlags[TransformFlags["ContainsYield"] = 4194304] = "ContainsYield"; + TransformFlags[TransformFlags["ContainsHoistedDeclarationOrCompletion"] = 8388608] = "ContainsHoistedDeclarationOrCompletion"; + TransformFlags[TransformFlags["ContainsDynamicImport"] = 16777216] = "ContainsDynamicImport"; + TransformFlags[TransformFlags["Super"] = 33554432] = "Super"; + TransformFlags[TransformFlags["ContainsSuper"] = 67108864] = "ContainsSuper"; + // Please leave this as 1 << 29. + // It is the maximum bit we can set before we outgrow the size of a v8 small integer (SMI) on an x86 system. + // It is a good reminder of how much room we have left + TransformFlags[TransformFlags["HasComputedFlags"] = 536870912] = "HasComputedFlags"; + // Assertions + // - Bitmasks that are used to assert facts about the syntax of a node and its subtree. + TransformFlags[TransformFlags["AssertTypeScript"] = 3] = "AssertTypeScript"; + TransformFlags[TransformFlags["AssertJsx"] = 4] = "AssertJsx"; + TransformFlags[TransformFlags["AssertESNext"] = 8] = "AssertESNext"; + TransformFlags[TransformFlags["AssertES2017"] = 16] = "AssertES2017"; + TransformFlags[TransformFlags["AssertES2016"] = 32] = "AssertES2016"; + TransformFlags[TransformFlags["AssertES2015"] = 192] = "AssertES2015"; + TransformFlags[TransformFlags["AssertGenerator"] = 768] = "AssertGenerator"; + TransformFlags[TransformFlags["AssertDestructuringAssignment"] = 3072] = "AssertDestructuringAssignment"; + // Scope Exclusions + // - Bitmasks that exclude flags from propagating out of a specific context + // into the subtree flags of their container. + TransformFlags[TransformFlags["OuterExpressionExcludes"] = 536872257] = "OuterExpressionExcludes"; + TransformFlags[TransformFlags["PropertyAccessExcludes"] = 570426689] = "PropertyAccessExcludes"; + TransformFlags[TransformFlags["NodeExcludes"] = 637535553] = "NodeExcludes"; + TransformFlags[TransformFlags["ArrowFunctionExcludes"] = 653604161] = "ArrowFunctionExcludes"; + TransformFlags[TransformFlags["FunctionExcludes"] = 653620545] = "FunctionExcludes"; + TransformFlags[TransformFlags["ConstructorExcludes"] = 653616449] = "ConstructorExcludes"; + TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = 653616449] = "MethodOrAccessorExcludes"; + TransformFlags[TransformFlags["ClassExcludes"] = 638121281] = "ClassExcludes"; + TransformFlags[TransformFlags["ModuleExcludes"] = 647001409] = "ModuleExcludes"; + TransformFlags[TransformFlags["TypeExcludes"] = -3] = "TypeExcludes"; + TransformFlags[TransformFlags["ObjectLiteralExcludes"] = 638358849] = "ObjectLiteralExcludes"; + TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = 637666625] = "ArrayLiteralOrCallOrNewExcludes"; + TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = 639894849] = "VariableDeclarationListExcludes"; + TransformFlags[TransformFlags["ParameterExcludes"] = 637535553] = "ParameterExcludes"; + TransformFlags[TransformFlags["CatchClauseExcludes"] = 637797697] = "CatchClauseExcludes"; + TransformFlags[TransformFlags["BindingPatternExcludes"] = 637666625] = "BindingPatternExcludes"; + // Masks + // - Additional bitmasks + TransformFlags[TransformFlags["ES2015FunctionSyntaxMask"] = 81920] = "ES2015FunctionSyntaxMask"; + })(TransformFlags = ts.TransformFlags || (ts.TransformFlags = {})); + var EmitFlags; + (function (EmitFlags) { + EmitFlags[EmitFlags["None"] = 0] = "None"; + EmitFlags[EmitFlags["SingleLine"] = 1] = "SingleLine"; + EmitFlags[EmitFlags["AdviseOnEmitNode"] = 2] = "AdviseOnEmitNode"; + EmitFlags[EmitFlags["NoSubstitution"] = 4] = "NoSubstitution"; + EmitFlags[EmitFlags["CapturesThis"] = 8] = "CapturesThis"; + EmitFlags[EmitFlags["NoLeadingSourceMap"] = 16] = "NoLeadingSourceMap"; + EmitFlags[EmitFlags["NoTrailingSourceMap"] = 32] = "NoTrailingSourceMap"; + EmitFlags[EmitFlags["NoSourceMap"] = 48] = "NoSourceMap"; + EmitFlags[EmitFlags["NoNestedSourceMaps"] = 64] = "NoNestedSourceMaps"; + EmitFlags[EmitFlags["NoTokenLeadingSourceMaps"] = 128] = "NoTokenLeadingSourceMaps"; + EmitFlags[EmitFlags["NoTokenTrailingSourceMaps"] = 256] = "NoTokenTrailingSourceMaps"; + EmitFlags[EmitFlags["NoTokenSourceMaps"] = 384] = "NoTokenSourceMaps"; + EmitFlags[EmitFlags["NoLeadingComments"] = 512] = "NoLeadingComments"; + EmitFlags[EmitFlags["NoTrailingComments"] = 1024] = "NoTrailingComments"; + EmitFlags[EmitFlags["NoComments"] = 1536] = "NoComments"; + EmitFlags[EmitFlags["NoNestedComments"] = 2048] = "NoNestedComments"; + EmitFlags[EmitFlags["HelperName"] = 4096] = "HelperName"; + EmitFlags[EmitFlags["ExportName"] = 8192] = "ExportName"; + EmitFlags[EmitFlags["LocalName"] = 16384] = "LocalName"; + EmitFlags[EmitFlags["InternalName"] = 32768] = "InternalName"; + EmitFlags[EmitFlags["Indented"] = 65536] = "Indented"; + EmitFlags[EmitFlags["NoIndentation"] = 131072] = "NoIndentation"; + EmitFlags[EmitFlags["AsyncFunctionBody"] = 262144] = "AsyncFunctionBody"; + EmitFlags[EmitFlags["ReuseTempVariableScope"] = 524288] = "ReuseTempVariableScope"; + EmitFlags[EmitFlags["CustomPrologue"] = 1048576] = "CustomPrologue"; + EmitFlags[EmitFlags["NoHoisting"] = 2097152] = "NoHoisting"; + EmitFlags[EmitFlags["HasEndOfDeclarationMarker"] = 4194304] = "HasEndOfDeclarationMarker"; + EmitFlags[EmitFlags["Iterator"] = 8388608] = "Iterator"; + EmitFlags[EmitFlags["NoAsciiEscaping"] = 16777216] = "NoAsciiEscaping"; + /*@internal*/ EmitFlags[EmitFlags["TypeScriptClassWrapper"] = 33554432] = "TypeScriptClassWrapper"; + /*@internal*/ EmitFlags[EmitFlags["NeverApplyImportHelper"] = 67108864] = "NeverApplyImportHelper"; + })(EmitFlags = ts.EmitFlags || (ts.EmitFlags = {})); + /** + * Used by the checker, this enum keeps track of external emit helpers that should be type + * checked. + */ + /* @internal */ + var ExternalEmitHelpers; + (function (ExternalEmitHelpers) { + ExternalEmitHelpers[ExternalEmitHelpers["Extends"] = 1] = "Extends"; + ExternalEmitHelpers[ExternalEmitHelpers["Assign"] = 2] = "Assign"; + ExternalEmitHelpers[ExternalEmitHelpers["Rest"] = 4] = "Rest"; + ExternalEmitHelpers[ExternalEmitHelpers["Decorate"] = 8] = "Decorate"; + ExternalEmitHelpers[ExternalEmitHelpers["Metadata"] = 16] = "Metadata"; + ExternalEmitHelpers[ExternalEmitHelpers["Param"] = 32] = "Param"; + ExternalEmitHelpers[ExternalEmitHelpers["Awaiter"] = 64] = "Awaiter"; + ExternalEmitHelpers[ExternalEmitHelpers["Generator"] = 128] = "Generator"; + ExternalEmitHelpers[ExternalEmitHelpers["Values"] = 256] = "Values"; + ExternalEmitHelpers[ExternalEmitHelpers["Read"] = 512] = "Read"; + ExternalEmitHelpers[ExternalEmitHelpers["Spread"] = 1024] = "Spread"; + ExternalEmitHelpers[ExternalEmitHelpers["Await"] = 2048] = "Await"; + ExternalEmitHelpers[ExternalEmitHelpers["AsyncGenerator"] = 4096] = "AsyncGenerator"; + ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegator"] = 8192] = "AsyncDelegator"; + ExternalEmitHelpers[ExternalEmitHelpers["AsyncValues"] = 16384] = "AsyncValues"; + ExternalEmitHelpers[ExternalEmitHelpers["ExportStar"] = 32768] = "ExportStar"; + ExternalEmitHelpers[ExternalEmitHelpers["MakeTemplateObject"] = 65536] = "MakeTemplateObject"; + ExternalEmitHelpers[ExternalEmitHelpers["FirstEmitHelper"] = 1] = "FirstEmitHelper"; + ExternalEmitHelpers[ExternalEmitHelpers["LastEmitHelper"] = 65536] = "LastEmitHelper"; + // Helpers included by ES2015 for..of + ExternalEmitHelpers[ExternalEmitHelpers["ForOfIncludes"] = 256] = "ForOfIncludes"; + // Helpers included by ES2017 for..await..of + ExternalEmitHelpers[ExternalEmitHelpers["ForAwaitOfIncludes"] = 16384] = "ForAwaitOfIncludes"; + // Helpers included by ES2017 async generators + ExternalEmitHelpers[ExternalEmitHelpers["AsyncGeneratorIncludes"] = 6144] = "AsyncGeneratorIncludes"; + // Helpers included by yield* in ES2017 async generators + ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegatorIncludes"] = 26624] = "AsyncDelegatorIncludes"; + // Helpers included by ES2015 spread + ExternalEmitHelpers[ExternalEmitHelpers["SpreadIncludes"] = 1536] = "SpreadIncludes"; + })(ExternalEmitHelpers = ts.ExternalEmitHelpers || (ts.ExternalEmitHelpers = {})); + var EmitHint; + (function (EmitHint) { + EmitHint[EmitHint["SourceFile"] = 0] = "SourceFile"; + EmitHint[EmitHint["Expression"] = 1] = "Expression"; + EmitHint[EmitHint["IdentifierName"] = 2] = "IdentifierName"; + EmitHint[EmitHint["MappedTypeParameter"] = 3] = "MappedTypeParameter"; + EmitHint[EmitHint["Unspecified"] = 4] = "Unspecified"; + EmitHint[EmitHint["EmbeddedStatement"] = 5] = "EmbeddedStatement"; + })(EmitHint = ts.EmitHint || (ts.EmitHint = {})); + var ListFormat; + (function (ListFormat) { + ListFormat[ListFormat["None"] = 0] = "None"; + // Line separators + ListFormat[ListFormat["SingleLine"] = 0] = "SingleLine"; + ListFormat[ListFormat["MultiLine"] = 1] = "MultiLine"; + ListFormat[ListFormat["PreserveLines"] = 2] = "PreserveLines"; + ListFormat[ListFormat["LinesMask"] = 3] = "LinesMask"; + // Delimiters + ListFormat[ListFormat["NotDelimited"] = 0] = "NotDelimited"; + ListFormat[ListFormat["BarDelimited"] = 4] = "BarDelimited"; + ListFormat[ListFormat["AmpersandDelimited"] = 8] = "AmpersandDelimited"; + ListFormat[ListFormat["CommaDelimited"] = 16] = "CommaDelimited"; + ListFormat[ListFormat["AsteriskDelimited"] = 32] = "AsteriskDelimited"; + ListFormat[ListFormat["DelimitersMask"] = 60] = "DelimitersMask"; + ListFormat[ListFormat["AllowTrailingComma"] = 64] = "AllowTrailingComma"; + // Whitespace + ListFormat[ListFormat["Indented"] = 128] = "Indented"; + ListFormat[ListFormat["SpaceBetweenBraces"] = 256] = "SpaceBetweenBraces"; + ListFormat[ListFormat["SpaceBetweenSiblings"] = 512] = "SpaceBetweenSiblings"; + // Brackets/Braces + ListFormat[ListFormat["Braces"] = 1024] = "Braces"; + ListFormat[ListFormat["Parenthesis"] = 2048] = "Parenthesis"; + ListFormat[ListFormat["AngleBrackets"] = 4096] = "AngleBrackets"; + ListFormat[ListFormat["SquareBrackets"] = 8192] = "SquareBrackets"; + ListFormat[ListFormat["BracketsMask"] = 15360] = "BracketsMask"; + ListFormat[ListFormat["OptionalIfUndefined"] = 16384] = "OptionalIfUndefined"; + ListFormat[ListFormat["OptionalIfEmpty"] = 32768] = "OptionalIfEmpty"; + ListFormat[ListFormat["Optional"] = 49152] = "Optional"; + // Other + ListFormat[ListFormat["PreferNewLine"] = 65536] = "PreferNewLine"; + ListFormat[ListFormat["NoTrailingNewLine"] = 131072] = "NoTrailingNewLine"; + ListFormat[ListFormat["NoInterveningComments"] = 262144] = "NoInterveningComments"; + ListFormat[ListFormat["NoSpaceIfEmpty"] = 524288] = "NoSpaceIfEmpty"; + ListFormat[ListFormat["SingleElement"] = 1048576] = "SingleElement"; + // Precomputed Formats + ListFormat[ListFormat["Modifiers"] = 262656] = "Modifiers"; + ListFormat[ListFormat["HeritageClauses"] = 512] = "HeritageClauses"; + ListFormat[ListFormat["SingleLineTypeLiteralMembers"] = 768] = "SingleLineTypeLiteralMembers"; + ListFormat[ListFormat["MultiLineTypeLiteralMembers"] = 32897] = "MultiLineTypeLiteralMembers"; + ListFormat[ListFormat["TupleTypeElements"] = 528] = "TupleTypeElements"; + ListFormat[ListFormat["UnionTypeConstituents"] = 516] = "UnionTypeConstituents"; + ListFormat[ListFormat["IntersectionTypeConstituents"] = 520] = "IntersectionTypeConstituents"; + ListFormat[ListFormat["ObjectBindingPatternElements"] = 525136] = "ObjectBindingPatternElements"; + ListFormat[ListFormat["ArrayBindingPatternElements"] = 524880] = "ArrayBindingPatternElements"; + ListFormat[ListFormat["ObjectLiteralExpressionProperties"] = 526226] = "ObjectLiteralExpressionProperties"; + ListFormat[ListFormat["ArrayLiteralExpressionElements"] = 8914] = "ArrayLiteralExpressionElements"; + ListFormat[ListFormat["CommaListElements"] = 528] = "CommaListElements"; + ListFormat[ListFormat["CallExpressionArguments"] = 2576] = "CallExpressionArguments"; + ListFormat[ListFormat["NewExpressionArguments"] = 18960] = "NewExpressionArguments"; + ListFormat[ListFormat["TemplateExpressionSpans"] = 262144] = "TemplateExpressionSpans"; + ListFormat[ListFormat["SingleLineBlockStatements"] = 768] = "SingleLineBlockStatements"; + ListFormat[ListFormat["MultiLineBlockStatements"] = 129] = "MultiLineBlockStatements"; + ListFormat[ListFormat["VariableDeclarationList"] = 528] = "VariableDeclarationList"; + ListFormat[ListFormat["SingleLineFunctionBodyStatements"] = 768] = "SingleLineFunctionBodyStatements"; + ListFormat[ListFormat["MultiLineFunctionBodyStatements"] = 1] = "MultiLineFunctionBodyStatements"; + ListFormat[ListFormat["ClassHeritageClauses"] = 0] = "ClassHeritageClauses"; + ListFormat[ListFormat["ClassMembers"] = 129] = "ClassMembers"; + ListFormat[ListFormat["InterfaceMembers"] = 129] = "InterfaceMembers"; + ListFormat[ListFormat["EnumMembers"] = 145] = "EnumMembers"; + ListFormat[ListFormat["CaseBlockClauses"] = 129] = "CaseBlockClauses"; + ListFormat[ListFormat["NamedImportsOrExportsElements"] = 525136] = "NamedImportsOrExportsElements"; + ListFormat[ListFormat["JsxElementOrFragmentChildren"] = 262144] = "JsxElementOrFragmentChildren"; + ListFormat[ListFormat["JsxElementAttributes"] = 262656] = "JsxElementAttributes"; + ListFormat[ListFormat["CaseOrDefaultClauseStatements"] = 163969] = "CaseOrDefaultClauseStatements"; + ListFormat[ListFormat["HeritageClauseTypes"] = 528] = "HeritageClauseTypes"; + ListFormat[ListFormat["SourceFileStatements"] = 131073] = "SourceFileStatements"; + ListFormat[ListFormat["Decorators"] = 49153] = "Decorators"; + ListFormat[ListFormat["TypeArguments"] = 53776] = "TypeArguments"; + ListFormat[ListFormat["TypeParameters"] = 53776] = "TypeParameters"; + ListFormat[ListFormat["Parameters"] = 2576] = "Parameters"; + ListFormat[ListFormat["IndexSignatureParameters"] = 8848] = "IndexSignatureParameters"; + ListFormat[ListFormat["JSDocComment"] = 33] = "JSDocComment"; + })(ListFormat = ts.ListFormat || (ts.ListFormat = {})); + /* @internal */ + var PragmaKindFlags; + (function (PragmaKindFlags) { + PragmaKindFlags[PragmaKindFlags["None"] = 0] = "None"; + /** + * Triple slash comment of the form + * /// + */ + PragmaKindFlags[PragmaKindFlags["TripleSlashXML"] = 1] = "TripleSlashXML"; + /** + * Single line comment of the form + * // @pragma-name argval1 argval2 + * or + * /// @pragma-name argval1 argval2 + */ + PragmaKindFlags[PragmaKindFlags["SingleLine"] = 2] = "SingleLine"; + /** + * Multiline non-jsdoc pragma of the form + * /* @pragma-name argval1 argval2 * / + */ + PragmaKindFlags[PragmaKindFlags["MultiLine"] = 4] = "MultiLine"; + PragmaKindFlags[PragmaKindFlags["All"] = 7] = "All"; + PragmaKindFlags[PragmaKindFlags["Default"] = 7] = "Default"; + })(PragmaKindFlags = ts.PragmaKindFlags || (ts.PragmaKindFlags = {})); + /** + * This function only exists to cause exact types to be inferred for all the literals within `commentPragmas` + */ + /* @internal */ + function _contextuallyTypePragmas(args) { + return args; + } + // While not strictly a type, this is here because `PragmaMap` needs to be here to be used with `SourceFile`, and we don't + // fancy effectively defining it twice, once in value-space and once in type-space + /* @internal */ + ts.commentPragmas = _contextuallyTypePragmas({ + "reference": { + args: [ + { name: "types", optional: true, captureSpan: true }, + { name: "lib", optional: true, captureSpan: true }, + { name: "path", optional: true, captureSpan: true }, + { name: "no-default-lib", optional: true } + ], + kind: 1 /* TripleSlashXML */ + }, + "amd-dependency": { + args: [{ name: "path" }, { name: "name", optional: true }], + kind: 1 /* TripleSlashXML */ + }, + "amd-module": { + args: [{ name: "name" }], + kind: 1 /* TripleSlashXML */ + }, + "ts-check": { + kind: 2 /* SingleLine */ + }, + "ts-nocheck": { + kind: 2 /* SingleLine */ + }, + "jsx": { + args: [{ name: "factory" }], + kind: 4 /* MultiLine */ + }, + }); +})(ts || (ts = {})); +var ts; +(function (ts) { + /** + * Set a high stack trace limit to provide more information in case of an error. + * Called for command-line and server use cases. + * Not called if TypeScript is used as a library. + */ + /* @internal */ + function setStackTraceLimit() { + if (Error.stackTraceLimit < 100) { // Also tests that we won't set the property if it doesn't exist. + Error.stackTraceLimit = 100; + } + } + ts.setStackTraceLimit = setStackTraceLimit; + var FileWatcherEventKind; + (function (FileWatcherEventKind) { + FileWatcherEventKind[FileWatcherEventKind["Created"] = 0] = "Created"; + FileWatcherEventKind[FileWatcherEventKind["Changed"] = 1] = "Changed"; + FileWatcherEventKind[FileWatcherEventKind["Deleted"] = 2] = "Deleted"; + })(FileWatcherEventKind = ts.FileWatcherEventKind || (ts.FileWatcherEventKind = {})); + /* @internal */ + var PollingInterval; + (function (PollingInterval) { + PollingInterval[PollingInterval["High"] = 2000] = "High"; + PollingInterval[PollingInterval["Medium"] = 500] = "Medium"; + PollingInterval[PollingInterval["Low"] = 250] = "Low"; + })(PollingInterval = ts.PollingInterval || (ts.PollingInterval = {})); + /* @internal */ + ts.missingFileModifiedTime = new Date(0); // Any subsequent modification will occur after this time + function createPollingIntervalBasedLevels(levels) { + var _a; + return _a = {}, + _a[PollingInterval.Low] = levels.Low, + _a[PollingInterval.Medium] = levels.Medium, + _a[PollingInterval.High] = levels.High, + _a; + } + var defaultChunkLevels = { Low: 32, Medium: 64, High: 256 }; + var pollingChunkSize = createPollingIntervalBasedLevels(defaultChunkLevels); + /* @internal */ + ts.unchangedPollThresholds = createPollingIntervalBasedLevels(defaultChunkLevels); + /* @internal */ + function setCustomPollingValues(system) { + if (!system.getEnvironmentVariable) { + return; + } + var pollingIntervalChanged = setCustomLevels("TSC_WATCH_POLLINGINTERVAL", PollingInterval); + pollingChunkSize = getCustomPollingBasedLevels("TSC_WATCH_POLLINGCHUNKSIZE", defaultChunkLevels) || pollingChunkSize; + ts.unchangedPollThresholds = getCustomPollingBasedLevels("TSC_WATCH_UNCHANGEDPOLLTHRESHOLDS", defaultChunkLevels) || ts.unchangedPollThresholds; + function getLevel(envVar, level) { + return system.getEnvironmentVariable(envVar + "_" + level.toUpperCase()); + } + function getCustomLevels(baseVariable) { + var customLevels; + setCustomLevel("Low"); + setCustomLevel("Medium"); + setCustomLevel("High"); + return customLevels; + function setCustomLevel(level) { + var customLevel = getLevel(baseVariable, level); + if (customLevel) { + (customLevels || (customLevels = {}))[level] = Number(customLevel); + } + } + } + function setCustomLevels(baseVariable, levels) { + var customLevels = getCustomLevels(baseVariable); + if (customLevels) { + setLevel("Low"); + setLevel("Medium"); + setLevel("High"); + return true; + } + return false; + function setLevel(level) { + levels[level] = customLevels[level] || levels[level]; + } + } + function getCustomPollingBasedLevels(baseVariable, defaultLevels) { + var customLevels = getCustomLevels(baseVariable); + return (pollingIntervalChanged || customLevels) && + createPollingIntervalBasedLevels(customLevels ? __assign({}, defaultLevels, customLevels) : defaultLevels); + } + } + ts.setCustomPollingValues = setCustomPollingValues; + /* @internal */ + function createDynamicPriorityPollingWatchFile(host) { + var watchedFiles = []; + var changedFilesInLastPoll = []; + var lowPollingIntervalQueue = createPollingIntervalQueue(PollingInterval.Low); + var mediumPollingIntervalQueue = createPollingIntervalQueue(PollingInterval.Medium); + var highPollingIntervalQueue = createPollingIntervalQueue(PollingInterval.High); + return watchFile; + function watchFile(fileName, callback, defaultPollingInterval) { + var file = { + fileName: fileName, + callback: callback, + unchangedPolls: 0, + mtime: getModifiedTime(fileName) + }; + watchedFiles.push(file); + addToPollingIntervalQueue(file, defaultPollingInterval); + return { + close: function () { + file.isClosed = true; + // Remove from watchedFiles + ts.unorderedRemoveItem(watchedFiles, file); + // Do not update polling interval queue since that will happen as part of polling + } + }; + } + function createPollingIntervalQueue(pollingInterval) { + var queue = []; + queue.pollingInterval = pollingInterval; + queue.pollIndex = 0; + queue.pollScheduled = false; + return queue; + } + function pollPollingIntervalQueue(queue) { + queue.pollIndex = pollQueue(queue, queue.pollingInterval, queue.pollIndex, pollingChunkSize[queue.pollingInterval]); + // Set the next polling index and timeout + if (queue.length) { + scheduleNextPoll(queue.pollingInterval); + } + else { + ts.Debug.assert(queue.pollIndex === 0); + queue.pollScheduled = false; + } + } + function pollLowPollingIntervalQueue(queue) { + // Always poll complete list of changedFilesInLastPoll + pollQueue(changedFilesInLastPoll, PollingInterval.Low, /*pollIndex*/ 0, changedFilesInLastPoll.length); + // Finally do the actual polling of the queue + pollPollingIntervalQueue(queue); + // Schedule poll if there are files in changedFilesInLastPoll but no files in the actual queue + // as pollPollingIntervalQueue wont schedule for next poll + if (!queue.pollScheduled && changedFilesInLastPoll.length) { + scheduleNextPoll(PollingInterval.Low); + } + } + function pollQueue(queue, pollingInterval, pollIndex, chunkSize) { + // Max visit would be all elements of the queue + var needsVisit = queue.length; + var definedValueCopyToIndex = pollIndex; + for (var polled = 0; polled < chunkSize && needsVisit > 0; nextPollIndex(), needsVisit--) { + var watchedFile = queue[pollIndex]; + if (!watchedFile) { + continue; + } + else if (watchedFile.isClosed) { + queue[pollIndex] = undefined; + continue; + } + polled++; + var fileChanged = onWatchedFileStat(watchedFile, getModifiedTime(watchedFile.fileName)); + if (watchedFile.isClosed) { + // Closed watcher as part of callback + queue[pollIndex] = undefined; + } + else if (fileChanged) { + watchedFile.unchangedPolls = 0; + // Changed files go to changedFilesInLastPoll queue + if (queue !== changedFilesInLastPoll) { + queue[pollIndex] = undefined; + addChangedFileToLowPollingIntervalQueue(watchedFile); + } + } + else if (watchedFile.unchangedPolls !== ts.unchangedPollThresholds[pollingInterval]) { + watchedFile.unchangedPolls++; + } + else if (queue === changedFilesInLastPoll) { + // Restart unchangedPollCount for unchanged file and move to low polling interval queue + watchedFile.unchangedPolls = 1; + queue[pollIndex] = undefined; + addToPollingIntervalQueue(watchedFile, PollingInterval.Low); + } + else if (pollingInterval !== PollingInterval.High) { + watchedFile.unchangedPolls++; + queue[pollIndex] = undefined; + addToPollingIntervalQueue(watchedFile, pollingInterval === PollingInterval.Low ? PollingInterval.Medium : PollingInterval.High); + } + if (queue[pollIndex]) { + // Copy this file to the non hole location + if (definedValueCopyToIndex < pollIndex) { + queue[definedValueCopyToIndex] = watchedFile; + queue[pollIndex] = undefined; + } + definedValueCopyToIndex++; + } + } + // Return next poll index + return pollIndex; + function nextPollIndex() { + pollIndex++; + if (pollIndex === queue.length) { + if (definedValueCopyToIndex < pollIndex) { + // There are holes from nextDefinedValueIndex to end of queue, change queue size + queue.length = definedValueCopyToIndex; + } + pollIndex = 0; + definedValueCopyToIndex = 0; + } + } + } + function pollingIntervalQueue(pollingInterval) { + switch (pollingInterval) { + case PollingInterval.Low: + return lowPollingIntervalQueue; + case PollingInterval.Medium: + return mediumPollingIntervalQueue; + case PollingInterval.High: + return highPollingIntervalQueue; + } + } + function addToPollingIntervalQueue(file, pollingInterval) { + pollingIntervalQueue(pollingInterval).push(file); + scheduleNextPollIfNotAlreadyScheduled(pollingInterval); + } + function addChangedFileToLowPollingIntervalQueue(file) { + changedFilesInLastPoll.push(file); + scheduleNextPollIfNotAlreadyScheduled(PollingInterval.Low); + } + function scheduleNextPollIfNotAlreadyScheduled(pollingInterval) { + if (!pollingIntervalQueue(pollingInterval).pollScheduled) { + scheduleNextPoll(pollingInterval); + } + } + function scheduleNextPoll(pollingInterval) { + pollingIntervalQueue(pollingInterval).pollScheduled = host.setTimeout(pollingInterval === PollingInterval.Low ? pollLowPollingIntervalQueue : pollPollingIntervalQueue, pollingInterval, pollingIntervalQueue(pollingInterval)); + } + function getModifiedTime(fileName) { + return host.getModifiedTime(fileName) || ts.missingFileModifiedTime; + } + } + ts.createDynamicPriorityPollingWatchFile = createDynamicPriorityPollingWatchFile; + /** + * Returns true if file status changed + */ + /*@internal*/ + function onWatchedFileStat(watchedFile, modifiedTime) { + var oldTime = watchedFile.mtime.getTime(); + var newTime = modifiedTime.getTime(); + if (oldTime !== newTime) { + watchedFile.mtime = modifiedTime; + watchedFile.callback(watchedFile.fileName, getFileWatcherEventKind(oldTime, newTime)); + return true; + } + return false; + } + ts.onWatchedFileStat = onWatchedFileStat; + /*@internal*/ + function getFileWatcherEventKind(oldTime, newTime) { + return oldTime === 0 + ? FileWatcherEventKind.Created + : newTime === 0 + ? FileWatcherEventKind.Deleted + : FileWatcherEventKind.Changed; + } + ts.getFileWatcherEventKind = getFileWatcherEventKind; + /** + * Watch the directory recursively using host provided method to watch child directories + * that means if this is recursive watcher, watch the children directories as well + * (eg on OS that dont support recursive watch using fs.watch use fs.watchFile) + */ + /*@internal*/ + function createRecursiveDirectoryWatcher(host) { + var cache = ts.createMap(); + var callbackCache = ts.createMultiMap(); + var filePathComparer = ts.getStringComparer(!host.useCaseSensitiveFileNames); + var toCanonicalFilePath = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); + return createDirectoryWatcher; + /** + * Create the directory watcher for the dirPath. + */ + function createDirectoryWatcher(dirName, callback) { + var dirPath = toCanonicalFilePath(dirName); + var directoryWatcher = cache.get(dirPath); + if (directoryWatcher) { + directoryWatcher.refCount++; + } + else { + directoryWatcher = { + watcher: host.watchDirectory(dirName, function (fileName) { + // Call the actual callback + callbackCache.forEach(function (callbacks, rootDirName) { + if (rootDirName === dirPath || (ts.startsWith(dirPath, rootDirName) && dirPath[rootDirName.length] === ts.directorySeparator)) { + callbacks.forEach(function (callback) { return callback(fileName); }); + } + }); + // Iterate through existing children and update the watches if needed + updateChildWatches(dirName, dirPath); + }), + refCount: 1, + childWatches: ts.emptyArray + }; + cache.set(dirPath, directoryWatcher); + updateChildWatches(dirName, dirPath); + } + if (callback) { + callbackCache.add(dirPath, callback); + } + return { + dirName: dirName, + close: function () { + var directoryWatcher = ts.Debug.assertDefined(cache.get(dirPath)); + if (callback) + callbackCache.remove(dirPath, callback); + directoryWatcher.refCount--; + if (directoryWatcher.refCount) + return; + cache.delete(dirPath); + ts.closeFileWatcherOf(directoryWatcher); + directoryWatcher.childWatches.forEach(ts.closeFileWatcher); + } + }; + } + function updateChildWatches(dirName, dirPath) { + // Iterate through existing children and update the watches if needed + var parentWatcher = cache.get(dirPath); + if (parentWatcher) { + parentWatcher.childWatches = watchChildDirectories(dirName, parentWatcher.childWatches); + } + } + /** + * Watch the directories in the parentDir + */ + function watchChildDirectories(parentDir, existingChildWatches) { + var newChildWatches; + ts.enumerateInsertsAndDeletes(host.directoryExists(parentDir) ? ts.mapDefined(host.getAccessibleSortedChildDirectories(parentDir), function (child) { + var childFullName = ts.getNormalizedAbsolutePath(child, parentDir); + // Filter our the symbolic link directories since those arent included in recursive watch + // which is same behaviour when recursive: true is passed to fs.watch + return filePathComparer(childFullName, ts.normalizePath(host.realpath(childFullName))) === 0 /* EqualTo */ ? childFullName : undefined; + }) : ts.emptyArray, existingChildWatches, function (child, childWatcher) { return filePathComparer(child, childWatcher.dirName); }, createAndAddChildDirectoryWatcher, ts.closeFileWatcher, addChildDirectoryWatcher); + return newChildWatches || ts.emptyArray; + /** + * Create new childDirectoryWatcher and add it to the new ChildDirectoryWatcher list + */ + function createAndAddChildDirectoryWatcher(childName) { + var result = createDirectoryWatcher(childName); + addChildDirectoryWatcher(result); + } + /** + * Add child directory watcher to the new ChildDirectoryWatcher list + */ + function addChildDirectoryWatcher(childWatcher) { + (newChildWatches || (newChildWatches = [])).push(childWatcher); + } + } + } + ts.createRecursiveDirectoryWatcher = createRecursiveDirectoryWatcher; + function getNodeMajorVersion() { + if (typeof process === "undefined") { + return undefined; + } + var version = process.version; + if (!version) { + return undefined; + } + var dot = version.indexOf("."); + if (dot === -1) { + return undefined; + } + return parseInt(version.substring(1, dot)); + } + ts.getNodeMajorVersion = getNodeMajorVersion; + // TODO: GH#18217 this is used as if it's certainly defined in many places. + ts.sys = (function () { + // NodeJS detects "\uFEFF" at the start of the string and *replaces* it with the actual + // byte order mark from the specified encoding. Using any other byte order mark does + // not actually work. + var byteOrderMarkIndicator = "\uFEFF"; + function getNodeSystem() { + var _fs = require("fs"); + var _path = require("path"); + var _os = require("os"); + // crypto can be absent on reduced node installations + var _crypto; + try { + _crypto = require("crypto"); + } + catch (_a) { + _crypto = undefined; + } + var Buffer = require("buffer").Buffer; + var nodeVersion = getNodeMajorVersion(); + var isNode4OrLater = nodeVersion >= 4; + var platform = _os.platform(); + var useCaseSensitiveFileNames = isFileSystemCaseSensitive(); + var FileSystemEntryKind; + (function (FileSystemEntryKind) { + FileSystemEntryKind[FileSystemEntryKind["File"] = 0] = "File"; + FileSystemEntryKind[FileSystemEntryKind["Directory"] = 1] = "Directory"; + })(FileSystemEntryKind || (FileSystemEntryKind = {})); + var useNonPollingWatchers = process.env.TSC_NONPOLLING_WATCHER; + var tscWatchFile = process.env.TSC_WATCHFILE; + var tscWatchDirectory = process.env.TSC_WATCHDIRECTORY; + var dynamicPollingWatchFile; + var nodeSystem = { + args: process.argv.slice(2), + newLine: _os.EOL, + useCaseSensitiveFileNames: useCaseSensitiveFileNames, + write: function (s) { + process.stdout.write(s); + }, + writeOutputIsTTY: function () { + return process.stdout.isTTY; + }, + readFile: readFile, + writeFile: writeFile, + watchFile: getWatchFile(), + watchDirectory: getWatchDirectory(), + resolvePath: function (path) { return _path.resolve(path); }, + fileExists: fileExists, + directoryExists: directoryExists, + createDirectory: function (directoryName) { + if (!nodeSystem.directoryExists(directoryName)) { + _fs.mkdirSync(directoryName); + } + }, + getExecutingFilePath: function () { + return __filename; + }, + getCurrentDirectory: function () { + return process.cwd(); + }, + getDirectories: getDirectories, + getEnvironmentVariable: function (name) { + return process.env[name] || ""; + }, + readDirectory: readDirectory, + getModifiedTime: getModifiedTime, + setModifiedTime: setModifiedTime, + deleteFile: deleteFile, + createHash: _crypto ? createMD5HashUsingNativeCrypto : generateDjb2Hash, + createSHA256Hash: _crypto ? createSHA256Hash : undefined, + getMemoryUsage: function () { + if (global.gc) { + global.gc(); + } + return process.memoryUsage().heapUsed; + }, + getFileSize: function (path) { + try { + var stat = _fs.statSync(path); + if (stat.isFile()) { + return stat.size; + } + } + catch ( /*ignore*/_a) { /*ignore*/ } + return 0; + }, + exit: function (exitCode) { + process.exit(exitCode); + }, + realpath: realpath, + debugMode: ts.some(process.execArgv, function (arg) { return /^--(inspect|debug)(-brk)?(=\d+)?$/i.test(arg); }), + tryEnableSourceMapsForHost: function () { + try { + require("source-map-support").install(); + } + catch (_a) { + // Could not enable source maps. + } + }, + setTimeout: setTimeout, + clearTimeout: clearTimeout, + clearScreen: function () { + process.stdout.write("\x1Bc"); + }, + setBlocking: function () { + if (process.stdout && process.stdout._handle && process.stdout._handle.setBlocking) { + process.stdout._handle.setBlocking(true); + } + }, + bufferFrom: bufferFrom, + base64decode: function (input) { return bufferFrom(input, "base64").toString("utf8"); }, + base64encode: function (input) { return bufferFrom(input).toString("base64"); }, + }; + return nodeSystem; + function bufferFrom(input, encoding) { + // See https://github.com/Microsoft/TypeScript/issues/25652 + return Buffer.from && Buffer.from !== Int8Array.from + ? Buffer.from(input, encoding) + : new Buffer(input, encoding); + } + function isFileSystemCaseSensitive() { + // win32\win64 are case insensitive platforms + if (platform === "win32" || platform === "win64") { + return false; + } + // If this file exists under a different case, we must be case-insensitve. + return !fileExists(swapCase(__filename)); + } + /** Convert all lowercase chars to uppercase, and vice-versa */ + function swapCase(s) { + return s.replace(/\w/g, function (ch) { + var up = ch.toUpperCase(); + return ch === up ? ch.toLowerCase() : up; + }); + } + function getWatchFile() { + switch (tscWatchFile) { + case "PriorityPollingInterval": + // Use polling interval based on priority when create watch using host.watchFile + return fsWatchFile; + case "DynamicPriorityPolling": + // Use polling interval but change the interval depending on file changes and their default polling interval + return createDynamicPriorityPollingWatchFile({ getModifiedTime: getModifiedTime, setTimeout: setTimeout }); + case "UseFsEvents": + // Use notifications from FS to watch with falling back to fs.watchFile + return watchFileUsingFsWatch; + case "UseFsEventsWithFallbackDynamicPolling": + // Use notifications from FS to watch with falling back to dynamic watch file + dynamicPollingWatchFile = createDynamicPriorityPollingWatchFile({ getModifiedTime: getModifiedTime, setTimeout: setTimeout }); + return createWatchFileUsingDynamicWatchFile(dynamicPollingWatchFile); + case "UseFsEventsOnParentDirectory": + // Use notifications from FS to watch with falling back to fs.watchFile + return createNonPollingWatchFile(); + } + return useNonPollingWatchers ? + createNonPollingWatchFile() : + // Default to do not use polling interval as it is before this experiment branch + function (fileName, callback) { return fsWatchFile(fileName, callback); }; + } + function getWatchDirectory() { + // Node 4.0 `fs.watch` function supports the "recursive" option on both OSX and Windows + // (ref: https://github.com/nodejs/node/pull/2649 and https://github.com/Microsoft/TypeScript/issues/4643) + var fsSupportsRecursive = isNode4OrLater && (process.platform === "win32" || process.platform === "darwin"); + if (fsSupportsRecursive) { + return watchDirectoryUsingFsWatch; + } + var watchDirectory = tscWatchDirectory === "RecursiveDirectoryUsingFsWatchFile" ? + createWatchDirectoryUsing(fsWatchFile) : + tscWatchDirectory === "RecursiveDirectoryUsingDynamicPriorityPolling" ? + createWatchDirectoryUsing(dynamicPollingWatchFile || createDynamicPriorityPollingWatchFile({ getModifiedTime: getModifiedTime, setTimeout: setTimeout })) : + watchDirectoryUsingFsWatch; + var watchDirectoryRecursively = createRecursiveDirectoryWatcher({ + useCaseSensitiveFileNames: useCaseSensitiveFileNames, + directoryExists: directoryExists, + getAccessibleSortedChildDirectories: function (path) { return getAccessibleFileSystemEntries(path).directories; }, + watchDirectory: watchDirectory, + realpath: realpath + }); + return function (directoryName, callback, recursive) { + if (recursive) { + return watchDirectoryRecursively(directoryName, callback); + } + return watchDirectory(directoryName, callback); + }; + } + function createNonPollingWatchFile() { + // One file can have multiple watchers + var fileWatcherCallbacks = ts.createMultiMap(); + var dirWatchers = ts.createMap(); + var toCanonicalName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); + return nonPollingWatchFile; + function nonPollingWatchFile(fileName, callback) { + var filePath = toCanonicalName(fileName); + fileWatcherCallbacks.add(filePath, callback); + var dirPath = ts.getDirectoryPath(filePath) || "."; + var watcher = dirWatchers.get(dirPath) || createDirectoryWatcher(ts.getDirectoryPath(fileName) || ".", dirPath); + watcher.referenceCount++; + return { + close: function () { + if (watcher.referenceCount === 1) { + watcher.close(); + dirWatchers.delete(dirPath); + } + else { + watcher.referenceCount--; + } + fileWatcherCallbacks.remove(filePath, callback); + } + }; + } + function createDirectoryWatcher(dirName, dirPath) { + var watcher = fsWatchDirectory(dirName, function (_eventName, relativeFileName) { + // When files are deleted from disk, the triggered "rename" event would have a relativefileName of "undefined" + if (!ts.isString(relativeFileName)) { + return; + } + var fileName = ts.getNormalizedAbsolutePath(relativeFileName, dirName); + // Some applications save a working file via rename operations + var callbacks = fileName && fileWatcherCallbacks.get(toCanonicalName(fileName)); + if (callbacks) { + for (var _i = 0, callbacks_1 = callbacks; _i < callbacks_1.length; _i++) { + var fileCallback = callbacks_1[_i]; + fileCallback(fileName, FileWatcherEventKind.Changed); + } + } + }); + watcher.referenceCount = 0; + dirWatchers.set(dirPath, watcher); + return watcher; + } + } + function fsWatchFile(fileName, callback, pollingInterval) { + _fs.watchFile(fileName, { persistent: true, interval: pollingInterval || 250 }, fileChanged); + var eventKind; + return { + close: function () { return _fs.unwatchFile(fileName, fileChanged); } + }; + function fileChanged(curr, prev) { + // previous event kind check is to ensure we recongnize the file as previously also missing when it is restored or renamed twice (that is it disappears and reappears) + // In such case, prevTime returned is same as prev time of event when file was deleted as per node documentation + var isPreviouslyDeleted = +prev.mtime === 0 || eventKind === FileWatcherEventKind.Deleted; + if (+curr.mtime === 0) { + if (isPreviouslyDeleted) { + // Already deleted file, no need to callback again + return; + } + eventKind = FileWatcherEventKind.Deleted; + } + else if (isPreviouslyDeleted) { + eventKind = FileWatcherEventKind.Created; + } + // If there is no change in modified time, ignore the event + else if (+curr.mtime === +prev.mtime) { + return; + } + else { + // File changed + eventKind = FileWatcherEventKind.Changed; + } + callback(fileName, eventKind); + } + } + function createFileWatcherCallback(callback) { + return function (_fileName, eventKind) { return callback(eventKind === FileWatcherEventKind.Changed ? "change" : "rename", ""); }; + } + function createFsWatchCallbackForFileWatcherCallback(fileName, callback) { + return function (eventName) { + if (eventName === "rename") { + callback(fileName, fileExists(fileName) ? FileWatcherEventKind.Created : FileWatcherEventKind.Deleted); + } + else { + // Change + callback(fileName, FileWatcherEventKind.Changed); + } + }; + } + function createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback) { + return function (eventName, relativeFileName) { + // In watchDirectory we only care about adding and removing files (when event name is + // "rename"); changes made within files are handled by corresponding fileWatchers (when + // event name is "change") + if (eventName === "rename") { + // When deleting a file, the passed baseFileName is null + callback(!relativeFileName ? directoryName : ts.normalizePath(ts.combinePaths(directoryName, relativeFileName))); + } + }; + } + function fsWatch(fileOrDirectory, entryKind, callback, recursive, fallbackPollingWatchFile, pollingInterval) { + var options; + /** Watcher for the file system entry depending on whether it is missing or present */ + var watcher = !fileSystemEntryExists(fileOrDirectory, entryKind) ? + watchMissingFileSystemEntry() : + watchPresentFileSystemEntry(); + return { + close: function () { + // Close the watcher (either existing file system entry watcher or missing file system entry watcher) + watcher.close(); + watcher = undefined; + } + }; + /** + * Invoke the callback with rename and update the watcher if not closed + * @param createWatcher + */ + function invokeCallbackAndUpdateWatcher(createWatcher) { + // Call the callback for current directory + callback("rename", ""); + // If watcher is not closed, update it + if (watcher) { + watcher.close(); + watcher = createWatcher(); + } + } + /** + * Watch the file or directory that is currently present + * and when the watched file or directory is deleted, switch to missing file system entry watcher + */ + function watchPresentFileSystemEntry() { + // Node 4.0 `fs.watch` function supports the "recursive" option on both OSX and Windows + // (ref: https://github.com/nodejs/node/pull/2649 and https://github.com/Microsoft/TypeScript/issues/4643) + if (options === undefined) { + if (isNode4OrLater && (process.platform === "win32" || process.platform === "darwin")) { + options = { persistent: true, recursive: !!recursive }; + } + else { + options = { persistent: true }; + } + } + try { + var presentWatcher = _fs.watch(fileOrDirectory, options, callback); + // Watch the missing file or directory or error + presentWatcher.on("error", function () { return invokeCallbackAndUpdateWatcher(watchMissingFileSystemEntry); }); + return presentWatcher; + } + catch (e) { + // Catch the exception and use polling instead + // Eg. on linux the number of watches are limited and one could easily exhaust watches and the exception ENOSPC is thrown when creating watcher at that point + // so instead of throwing error, use fs.watchFile + return watchPresentFileSystemEntryWithFsWatchFile(); + } + } + /** + * Watch the file or directory using fs.watchFile since fs.watch threw exception + * Eg. on linux the number of watches are limited and one could easily exhaust watches and the exception ENOSPC is thrown when creating watcher at that point + */ + function watchPresentFileSystemEntryWithFsWatchFile() { + return fallbackPollingWatchFile(fileOrDirectory, createFileWatcherCallback(callback), pollingInterval); + } + /** + * Watch the file or directory that is missing + * and switch to existing file or directory when the missing filesystem entry is created + */ + function watchMissingFileSystemEntry() { + return fallbackPollingWatchFile(fileOrDirectory, function (_fileName, eventKind) { + if (eventKind === FileWatcherEventKind.Created && fileSystemEntryExists(fileOrDirectory, entryKind)) { + // Call the callback for current file or directory + // For now it could be callback for the inner directory creation, + // but just return current directory, better than current no-op + invokeCallbackAndUpdateWatcher(watchPresentFileSystemEntry); + } + }, pollingInterval); + } + } + function watchFileUsingFsWatch(fileName, callback, pollingInterval) { + return fsWatch(fileName, 0 /* File */, createFsWatchCallbackForFileWatcherCallback(fileName, callback), /*recursive*/ false, fsWatchFile, pollingInterval); + } + function createWatchFileUsingDynamicWatchFile(watchFile) { + return function (fileName, callback, pollingInterval) { return fsWatch(fileName, 0 /* File */, createFsWatchCallbackForFileWatcherCallback(fileName, callback), /*recursive*/ false, watchFile, pollingInterval); }; + } + function fsWatchDirectory(directoryName, callback, recursive) { + return fsWatch(directoryName, 1 /* Directory */, callback, !!recursive, fsWatchFile); + } + function watchDirectoryUsingFsWatch(directoryName, callback, recursive) { + return fsWatchDirectory(directoryName, createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback), recursive); + } + function createWatchDirectoryUsing(fsWatchFile) { + return function (directoryName, callback) { return fsWatchFile(directoryName, function () { return callback(directoryName); }, PollingInterval.Medium); }; + } + function readFile(fileName, _encoding) { + if (!fileExists(fileName)) { + return undefined; + } + var buffer = _fs.readFileSync(fileName); + var len = buffer.length; + if (len >= 2 && buffer[0] === 0xFE && buffer[1] === 0xFF) { + // Big endian UTF-16 byte order mark detected. Since big endian is not supported by node.js, + // flip all byte pairs and treat as little endian. + len &= ~1; // Round down to a multiple of 2 + for (var i = 0; i < len; i += 2) { + var temp = buffer[i]; + buffer[i] = buffer[i + 1]; + buffer[i + 1] = temp; + } + return buffer.toString("utf16le", 2); + } + if (len >= 2 && buffer[0] === 0xFF && buffer[1] === 0xFE) { + // Little endian UTF-16 byte order mark detected + return buffer.toString("utf16le", 2); + } + if (len >= 3 && buffer[0] === 0xEF && buffer[1] === 0xBB && buffer[2] === 0xBF) { + // UTF-8 byte order mark detected + return buffer.toString("utf8", 3); + } + // Default is UTF-8 with no byte order mark + return buffer.toString("utf8"); + } + function writeFile(fileName, data, writeByteOrderMark) { + // If a BOM is required, emit one + if (writeByteOrderMark) { + data = byteOrderMarkIndicator + data; + } + var fd; + try { + fd = _fs.openSync(fileName, "w"); + _fs.writeSync(fd, data, /*position*/ undefined, "utf8"); + } + finally { + if (fd !== undefined) { + _fs.closeSync(fd); + } + } + } + function getAccessibleFileSystemEntries(path) { + try { + var entries = _fs.readdirSync(path || ".").sort(); + var files = []; + var directories = []; + for (var _i = 0, entries_2 = entries; _i < entries_2.length; _i++) { + var entry = entries_2[_i]; + // This is necessary because on some file system node fails to exclude + // "." and "..". See https://github.com/nodejs/node/issues/4002 + if (entry === "." || entry === "..") { + continue; + } + var name = ts.combinePaths(path, entry); + var stat = void 0; + try { + stat = _fs.statSync(name); + } + catch (e) { + continue; + } + if (stat.isFile()) { + files.push(entry); + } + else if (stat.isDirectory()) { + directories.push(entry); + } + } + return { files: files, directories: directories }; + } + catch (e) { + return ts.emptyFileSystemEntries; + } + } + function readDirectory(path, extensions, excludes, includes, depth) { + return ts.matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, process.cwd(), depth, getAccessibleFileSystemEntries); + } + function fileSystemEntryExists(path, entryKind) { + try { + var stat = _fs.statSync(path); + switch (entryKind) { + case 0 /* File */: return stat.isFile(); + case 1 /* Directory */: return stat.isDirectory(); + default: return false; + } + } + catch (e) { + return false; + } + } + function fileExists(path) { + return fileSystemEntryExists(path, 0 /* File */); + } + function directoryExists(path) { + return fileSystemEntryExists(path, 1 /* Directory */); + } + function getDirectories(path) { + return ts.filter(_fs.readdirSync(path), function (dir) { return fileSystemEntryExists(ts.combinePaths(path, dir), 1 /* Directory */); }); + } + function realpath(path) { + try { + return _fs.realpathSync(path); + } + catch (_a) { + return path; + } + } + function getModifiedTime(path) { + try { + return _fs.statSync(path).mtime; + } + catch (e) { + return undefined; + } + } + function setModifiedTime(path, time) { + try { + _fs.utimesSync(path, time, time); + } + catch (e) { + return; + } + } + function deleteFile(path) { + try { + return _fs.unlinkSync(path); + } + catch (e) { + return; + } + } + /** + * djb2 hashing algorithm + * http://www.cse.yorku.ca/~oz/hash.html + */ + function generateDjb2Hash(data) { + var chars = data.split("").map(function (str) { return str.charCodeAt(0); }); + return "" + chars.reduce(function (prev, curr) { return ((prev << 5) + prev) + curr; }, 5381); + } + function createMD5HashUsingNativeCrypto(data) { + var hash = _crypto.createHash("md5"); + hash.update(data); + return hash.digest("hex"); + } + function createSHA256Hash(data) { + var hash = _crypto.createHash("sha256"); + hash.update(data); + return hash.digest("hex"); + } + } + function getChakraSystem() { + var realpath = ChakraHost.realpath && (function (path) { return ChakraHost.realpath(path); }); + return { + newLine: ChakraHost.newLine || "\r\n", + args: ChakraHost.args, + useCaseSensitiveFileNames: !!ChakraHost.useCaseSensitiveFileNames, + write: ChakraHost.echo, + readFile: function (path, _encoding) { + // encoding is automatically handled by the implementation in ChakraHost + return ChakraHost.readFile(path); + }, + writeFile: function (path, data, writeByteOrderMark) { + // If a BOM is required, emit one + if (writeByteOrderMark) { + data = byteOrderMarkIndicator + data; + } + ChakraHost.writeFile(path, data); + }, + resolvePath: ChakraHost.resolvePath, + fileExists: ChakraHost.fileExists, + deleteFile: ChakraHost.deleteFile, + getModifiedTime: ChakraHost.getModifiedTime, + setModifiedTime: ChakraHost.setModifiedTime, + directoryExists: ChakraHost.directoryExists, + createDirectory: ChakraHost.createDirectory, + getExecutingFilePath: function () { return ChakraHost.executingFile; }, + getCurrentDirectory: function () { return ChakraHost.currentDirectory; }, + getDirectories: ChakraHost.getDirectories, + getEnvironmentVariable: ChakraHost.getEnvironmentVariable || (function () { return ""; }), + readDirectory: function (path, extensions, excludes, includes, _depth) { + var pattern = ts.getFileMatcherPatterns(path, excludes, includes, !!ChakraHost.useCaseSensitiveFileNames, ChakraHost.currentDirectory); + return ChakraHost.readDirectory(path, extensions, pattern.basePaths, pattern.excludePattern, pattern.includeFilePattern, pattern.includeDirectoryPattern); + }, + exit: ChakraHost.quit, + realpath: realpath + }; + } + function recursiveCreateDirectory(directoryPath, sys) { + var basePath = ts.getDirectoryPath(directoryPath); + var shouldCreateParent = basePath !== "" && directoryPath !== basePath && !sys.directoryExists(basePath); + if (shouldCreateParent) { + recursiveCreateDirectory(basePath, sys); + } + if (shouldCreateParent || !sys.directoryExists(directoryPath)) { + sys.createDirectory(directoryPath); + } + } + var sys; + if (typeof ChakraHost !== "undefined") { + sys = getChakraSystem(); + } + else if (typeof process !== "undefined" && process.nextTick && !process.browser && typeof require !== "undefined") { + // process and process.nextTick checks if current environment is node-like + // process.browser check excludes webpack and browserify + sys = getNodeSystem(); + } + if (sys) { + // patch writefile to create folder before writing the file + var originalWriteFile_1 = sys.writeFile; + sys.writeFile = function (path, data, writeBom) { + var directoryPath = ts.getDirectoryPath(ts.normalizeSlashes(path)); + if (directoryPath && !sys.directoryExists(directoryPath)) { + recursiveCreateDirectory(directoryPath, sys); + } + originalWriteFile_1.call(sys, path, data, writeBom); + }; + } + return sys; + })(); + if (ts.sys && ts.sys.getEnvironmentVariable) { + setCustomPollingValues(ts.sys); + ts.Debug.currentAssertionLevel = /^development$/i.test(ts.sys.getEnvironmentVariable("NODE_ENV")) + ? 1 /* Normal */ + : 0 /* None */; + } + if (ts.sys && ts.sys.debugMode) { + ts.Debug.isDebugging = true; + } +})(ts || (ts = {})); +// +// generated from './diagnosticInformationMap.generated.ts' by 'src/compiler' +/* @internal */ +var ts; +(function (ts) { + function diag(code, category, key, message, reportsUnnecessary) { + return { code: code, category: category, key: key, message: message, reportsUnnecessary: reportsUnnecessary }; + } + // tslint:disable-next-line variable-name + ts.Diagnostics = { + Unterminated_string_literal: diag(1002, ts.DiagnosticCategory.Error, "Unterminated_string_literal_1002", "Unterminated string literal."), + Identifier_expected: diag(1003, ts.DiagnosticCategory.Error, "Identifier_expected_1003", "Identifier expected."), + _0_expected: diag(1005, ts.DiagnosticCategory.Error, "_0_expected_1005", "'{0}' expected."), + A_file_cannot_have_a_reference_to_itself: diag(1006, ts.DiagnosticCategory.Error, "A_file_cannot_have_a_reference_to_itself_1006", "A file cannot have a reference to itself."), + Trailing_comma_not_allowed: diag(1009, ts.DiagnosticCategory.Error, "Trailing_comma_not_allowed_1009", "Trailing comma not allowed."), + Asterisk_Slash_expected: diag(1010, ts.DiagnosticCategory.Error, "Asterisk_Slash_expected_1010", "'*/' expected."), + An_element_access_expression_should_take_an_argument: diag(1011, ts.DiagnosticCategory.Error, "An_element_access_expression_should_take_an_argument_1011", "An element access expression should take an argument."), + Unexpected_token: diag(1012, ts.DiagnosticCategory.Error, "Unexpected_token_1012", "Unexpected token."), + A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma: diag(1013, ts.DiagnosticCategory.Error, "A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma_1013", "A rest parameter or binding pattern may not have a trailing comma."), + A_rest_parameter_must_be_last_in_a_parameter_list: diag(1014, ts.DiagnosticCategory.Error, "A_rest_parameter_must_be_last_in_a_parameter_list_1014", "A rest parameter must be last in a parameter list."), + Parameter_cannot_have_question_mark_and_initializer: diag(1015, ts.DiagnosticCategory.Error, "Parameter_cannot_have_question_mark_and_initializer_1015", "Parameter cannot have question mark and initializer."), + A_required_parameter_cannot_follow_an_optional_parameter: diag(1016, ts.DiagnosticCategory.Error, "A_required_parameter_cannot_follow_an_optional_parameter_1016", "A required parameter cannot follow an optional parameter."), + An_index_signature_cannot_have_a_rest_parameter: diag(1017, ts.DiagnosticCategory.Error, "An_index_signature_cannot_have_a_rest_parameter_1017", "An index signature cannot have a rest parameter."), + An_index_signature_parameter_cannot_have_an_accessibility_modifier: diag(1018, ts.DiagnosticCategory.Error, "An_index_signature_parameter_cannot_have_an_accessibility_modifier_1018", "An index signature parameter cannot have an accessibility modifier."), + An_index_signature_parameter_cannot_have_a_question_mark: diag(1019, ts.DiagnosticCategory.Error, "An_index_signature_parameter_cannot_have_a_question_mark_1019", "An index signature parameter cannot have a question mark."), + An_index_signature_parameter_cannot_have_an_initializer: diag(1020, ts.DiagnosticCategory.Error, "An_index_signature_parameter_cannot_have_an_initializer_1020", "An index signature parameter cannot have an initializer."), + An_index_signature_must_have_a_type_annotation: diag(1021, ts.DiagnosticCategory.Error, "An_index_signature_must_have_a_type_annotation_1021", "An index signature must have a type annotation."), + An_index_signature_parameter_must_have_a_type_annotation: diag(1022, ts.DiagnosticCategory.Error, "An_index_signature_parameter_must_have_a_type_annotation_1022", "An index signature parameter must have a type annotation."), + An_index_signature_parameter_type_must_be_string_or_number: diag(1023, ts.DiagnosticCategory.Error, "An_index_signature_parameter_type_must_be_string_or_number_1023", "An index signature parameter type must be 'string' or 'number'."), + readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature: diag(1024, ts.DiagnosticCategory.Error, "readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024", "'readonly' modifier can only appear on a property declaration or index signature."), + Accessibility_modifier_already_seen: diag(1028, ts.DiagnosticCategory.Error, "Accessibility_modifier_already_seen_1028", "Accessibility modifier already seen."), + _0_modifier_must_precede_1_modifier: diag(1029, ts.DiagnosticCategory.Error, "_0_modifier_must_precede_1_modifier_1029", "'{0}' modifier must precede '{1}' modifier."), + _0_modifier_already_seen: diag(1030, ts.DiagnosticCategory.Error, "_0_modifier_already_seen_1030", "'{0}' modifier already seen."), + _0_modifier_cannot_appear_on_a_class_element: diag(1031, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_a_class_element_1031", "'{0}' modifier cannot appear on a class element."), + super_must_be_followed_by_an_argument_list_or_member_access: diag(1034, ts.DiagnosticCategory.Error, "super_must_be_followed_by_an_argument_list_or_member_access_1034", "'super' must be followed by an argument list or member access."), + Only_ambient_modules_can_use_quoted_names: diag(1035, ts.DiagnosticCategory.Error, "Only_ambient_modules_can_use_quoted_names_1035", "Only ambient modules can use quoted names."), + Statements_are_not_allowed_in_ambient_contexts: diag(1036, ts.DiagnosticCategory.Error, "Statements_are_not_allowed_in_ambient_contexts_1036", "Statements are not allowed in ambient contexts."), + A_declare_modifier_cannot_be_used_in_an_already_ambient_context: diag(1038, ts.DiagnosticCategory.Error, "A_declare_modifier_cannot_be_used_in_an_already_ambient_context_1038", "A 'declare' modifier cannot be used in an already ambient context."), + Initializers_are_not_allowed_in_ambient_contexts: diag(1039, ts.DiagnosticCategory.Error, "Initializers_are_not_allowed_in_ambient_contexts_1039", "Initializers are not allowed in ambient contexts."), + _0_modifier_cannot_be_used_in_an_ambient_context: diag(1040, ts.DiagnosticCategory.Error, "_0_modifier_cannot_be_used_in_an_ambient_context_1040", "'{0}' modifier cannot be used in an ambient context."), + _0_modifier_cannot_be_used_with_a_class_declaration: diag(1041, ts.DiagnosticCategory.Error, "_0_modifier_cannot_be_used_with_a_class_declaration_1041", "'{0}' modifier cannot be used with a class declaration."), + _0_modifier_cannot_be_used_here: diag(1042, ts.DiagnosticCategory.Error, "_0_modifier_cannot_be_used_here_1042", "'{0}' modifier cannot be used here."), + _0_modifier_cannot_appear_on_a_data_property: diag(1043, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_a_data_property_1043", "'{0}' modifier cannot appear on a data property."), + _0_modifier_cannot_appear_on_a_module_or_namespace_element: diag(1044, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_a_module_or_namespace_element_1044", "'{0}' modifier cannot appear on a module or namespace element."), + A_0_modifier_cannot_be_used_with_an_interface_declaration: diag(1045, ts.DiagnosticCategory.Error, "A_0_modifier_cannot_be_used_with_an_interface_declaration_1045", "A '{0}' modifier cannot be used with an interface declaration."), + A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file: diag(1046, ts.DiagnosticCategory.Error, "A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file_1046", "A 'declare' modifier is required for a top level declaration in a .d.ts file."), + A_rest_parameter_cannot_be_optional: diag(1047, ts.DiagnosticCategory.Error, "A_rest_parameter_cannot_be_optional_1047", "A rest parameter cannot be optional."), + A_rest_parameter_cannot_have_an_initializer: diag(1048, ts.DiagnosticCategory.Error, "A_rest_parameter_cannot_have_an_initializer_1048", "A rest parameter cannot have an initializer."), + A_set_accessor_must_have_exactly_one_parameter: diag(1049, ts.DiagnosticCategory.Error, "A_set_accessor_must_have_exactly_one_parameter_1049", "A 'set' accessor must have exactly one parameter."), + A_set_accessor_cannot_have_an_optional_parameter: diag(1051, ts.DiagnosticCategory.Error, "A_set_accessor_cannot_have_an_optional_parameter_1051", "A 'set' accessor cannot have an optional parameter."), + A_set_accessor_parameter_cannot_have_an_initializer: diag(1052, ts.DiagnosticCategory.Error, "A_set_accessor_parameter_cannot_have_an_initializer_1052", "A 'set' accessor parameter cannot have an initializer."), + A_set_accessor_cannot_have_rest_parameter: diag(1053, ts.DiagnosticCategory.Error, "A_set_accessor_cannot_have_rest_parameter_1053", "A 'set' accessor cannot have rest parameter."), + A_get_accessor_cannot_have_parameters: diag(1054, ts.DiagnosticCategory.Error, "A_get_accessor_cannot_have_parameters_1054", "A 'get' accessor cannot have parameters."), + Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value: diag(1055, ts.DiagnosticCategory.Error, "Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Prom_1055", "Type '{0}' is not a valid async function return type in ES5/ES3 because it does not refer to a Promise-compatible constructor value."), + Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher: diag(1056, ts.DiagnosticCategory.Error, "Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher_1056", "Accessors are only available when targeting ECMAScript 5 and higher."), + An_async_function_or_method_must_have_a_valid_awaitable_return_type: diag(1057, ts.DiagnosticCategory.Error, "An_async_function_or_method_must_have_a_valid_awaitable_return_type_1057", "An async function or method must have a valid awaitable return type."), + The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1058, ts.DiagnosticCategory.Error, "The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_t_1058", "The return type of an async function must either be a valid promise or must not contain a callable 'then' member."), + A_promise_must_have_a_then_method: diag(1059, ts.DiagnosticCategory.Error, "A_promise_must_have_a_then_method_1059", "A promise must have a 'then' method."), + The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback: diag(1060, ts.DiagnosticCategory.Error, "The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback_1060", "The first parameter of the 'then' method of a promise must be a callback."), + Enum_member_must_have_initializer: diag(1061, ts.DiagnosticCategory.Error, "Enum_member_must_have_initializer_1061", "Enum member must have initializer."), + Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method: diag(1062, ts.DiagnosticCategory.Error, "Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method_1062", "Type is referenced directly or indirectly in the fulfillment callback of its own 'then' method."), + An_export_assignment_cannot_be_used_in_a_namespace: diag(1063, ts.DiagnosticCategory.Error, "An_export_assignment_cannot_be_used_in_a_namespace_1063", "An export assignment cannot be used in a namespace."), + The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type: diag(1064, ts.DiagnosticCategory.Error, "The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_1064", "The return type of an async function or method must be the global Promise type."), + In_ambient_enum_declarations_member_initializer_must_be_constant_expression: diag(1066, ts.DiagnosticCategory.Error, "In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066", "In ambient enum declarations member initializer must be constant expression."), + Unexpected_token_A_constructor_method_accessor_or_property_was_expected: diag(1068, ts.DiagnosticCategory.Error, "Unexpected_token_A_constructor_method_accessor_or_property_was_expected_1068", "Unexpected token. A constructor, method, accessor, or property was expected."), + Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces: diag(1069, ts.DiagnosticCategory.Error, "Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces_1069", "Unexpected token. A type parameter name was expected without curly braces."), + _0_modifier_cannot_appear_on_a_type_member: diag(1070, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_a_type_member_1070", "'{0}' modifier cannot appear on a type member."), + _0_modifier_cannot_appear_on_an_index_signature: diag(1071, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_an_index_signature_1071", "'{0}' modifier cannot appear on an index signature."), + A_0_modifier_cannot_be_used_with_an_import_declaration: diag(1079, ts.DiagnosticCategory.Error, "A_0_modifier_cannot_be_used_with_an_import_declaration_1079", "A '{0}' modifier cannot be used with an import declaration."), + Invalid_reference_directive_syntax: diag(1084, ts.DiagnosticCategory.Error, "Invalid_reference_directive_syntax_1084", "Invalid 'reference' directive syntax."), + Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0: diag(1085, ts.DiagnosticCategory.Error, "Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0_1085", "Octal literals are not available when targeting ECMAScript 5 and higher. Use the syntax '{0}'."), + An_accessor_cannot_be_declared_in_an_ambient_context: diag(1086, ts.DiagnosticCategory.Error, "An_accessor_cannot_be_declared_in_an_ambient_context_1086", "An accessor cannot be declared in an ambient context."), + _0_modifier_cannot_appear_on_a_constructor_declaration: diag(1089, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_a_constructor_declaration_1089", "'{0}' modifier cannot appear on a constructor declaration."), + _0_modifier_cannot_appear_on_a_parameter: diag(1090, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_a_parameter_1090", "'{0}' modifier cannot appear on a parameter."), + Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement: diag(1091, ts.DiagnosticCategory.Error, "Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement_1091", "Only a single variable declaration is allowed in a 'for...in' statement."), + Type_parameters_cannot_appear_on_a_constructor_declaration: diag(1092, ts.DiagnosticCategory.Error, "Type_parameters_cannot_appear_on_a_constructor_declaration_1092", "Type parameters cannot appear on a constructor declaration."), + Type_annotation_cannot_appear_on_a_constructor_declaration: diag(1093, ts.DiagnosticCategory.Error, "Type_annotation_cannot_appear_on_a_constructor_declaration_1093", "Type annotation cannot appear on a constructor declaration."), + An_accessor_cannot_have_type_parameters: diag(1094, ts.DiagnosticCategory.Error, "An_accessor_cannot_have_type_parameters_1094", "An accessor cannot have type parameters."), + A_set_accessor_cannot_have_a_return_type_annotation: diag(1095, ts.DiagnosticCategory.Error, "A_set_accessor_cannot_have_a_return_type_annotation_1095", "A 'set' accessor cannot have a return type annotation."), + An_index_signature_must_have_exactly_one_parameter: diag(1096, ts.DiagnosticCategory.Error, "An_index_signature_must_have_exactly_one_parameter_1096", "An index signature must have exactly one parameter."), + _0_list_cannot_be_empty: diag(1097, ts.DiagnosticCategory.Error, "_0_list_cannot_be_empty_1097", "'{0}' list cannot be empty."), + Type_parameter_list_cannot_be_empty: diag(1098, ts.DiagnosticCategory.Error, "Type_parameter_list_cannot_be_empty_1098", "Type parameter list cannot be empty."), + Type_argument_list_cannot_be_empty: diag(1099, ts.DiagnosticCategory.Error, "Type_argument_list_cannot_be_empty_1099", "Type argument list cannot be empty."), + Invalid_use_of_0_in_strict_mode: diag(1100, ts.DiagnosticCategory.Error, "Invalid_use_of_0_in_strict_mode_1100", "Invalid use of '{0}' in strict mode."), + with_statements_are_not_allowed_in_strict_mode: diag(1101, ts.DiagnosticCategory.Error, "with_statements_are_not_allowed_in_strict_mode_1101", "'with' statements are not allowed in strict mode."), + delete_cannot_be_called_on_an_identifier_in_strict_mode: diag(1102, ts.DiagnosticCategory.Error, "delete_cannot_be_called_on_an_identifier_in_strict_mode_1102", "'delete' cannot be called on an identifier in strict mode."), + A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator: diag(1103, ts.DiagnosticCategory.Error, "A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator_1103", "A 'for-await-of' statement is only allowed within an async function or async generator."), + A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement: diag(1104, ts.DiagnosticCategory.Error, "A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement_1104", "A 'continue' statement can only be used within an enclosing iteration statement."), + A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement: diag(1105, ts.DiagnosticCategory.Error, "A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement_1105", "A 'break' statement can only be used within an enclosing iteration or switch statement."), + Jump_target_cannot_cross_function_boundary: diag(1107, ts.DiagnosticCategory.Error, "Jump_target_cannot_cross_function_boundary_1107", "Jump target cannot cross function boundary."), + A_return_statement_can_only_be_used_within_a_function_body: diag(1108, ts.DiagnosticCategory.Error, "A_return_statement_can_only_be_used_within_a_function_body_1108", "A 'return' statement can only be used within a function body."), + Expression_expected: diag(1109, ts.DiagnosticCategory.Error, "Expression_expected_1109", "Expression expected."), + Type_expected: diag(1110, ts.DiagnosticCategory.Error, "Type_expected_1110", "Type expected."), + A_default_clause_cannot_appear_more_than_once_in_a_switch_statement: diag(1113, ts.DiagnosticCategory.Error, "A_default_clause_cannot_appear_more_than_once_in_a_switch_statement_1113", "A 'default' clause cannot appear more than once in a 'switch' statement."), + Duplicate_label_0: diag(1114, ts.DiagnosticCategory.Error, "Duplicate_label_0_1114", "Duplicate label '{0}'."), + A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement: diag(1115, ts.DiagnosticCategory.Error, "A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement_1115", "A 'continue' statement can only jump to a label of an enclosing iteration statement."), + A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement: diag(1116, ts.DiagnosticCategory.Error, "A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement_1116", "A 'break' statement can only jump to a label of an enclosing statement."), + An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode: diag(1117, ts.DiagnosticCategory.Error, "An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode_1117", "An object literal cannot have multiple properties with the same name in strict mode."), + An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name: diag(1118, ts.DiagnosticCategory.Error, "An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name_1118", "An object literal cannot have multiple get/set accessors with the same name."), + An_object_literal_cannot_have_property_and_accessor_with_the_same_name: diag(1119, ts.DiagnosticCategory.Error, "An_object_literal_cannot_have_property_and_accessor_with_the_same_name_1119", "An object literal cannot have property and accessor with the same name."), + An_export_assignment_cannot_have_modifiers: diag(1120, ts.DiagnosticCategory.Error, "An_export_assignment_cannot_have_modifiers_1120", "An export assignment cannot have modifiers."), + Octal_literals_are_not_allowed_in_strict_mode: diag(1121, ts.DiagnosticCategory.Error, "Octal_literals_are_not_allowed_in_strict_mode_1121", "Octal literals are not allowed in strict mode."), + Variable_declaration_list_cannot_be_empty: diag(1123, ts.DiagnosticCategory.Error, "Variable_declaration_list_cannot_be_empty_1123", "Variable declaration list cannot be empty."), + Digit_expected: diag(1124, ts.DiagnosticCategory.Error, "Digit_expected_1124", "Digit expected."), + Hexadecimal_digit_expected: diag(1125, ts.DiagnosticCategory.Error, "Hexadecimal_digit_expected_1125", "Hexadecimal digit expected."), + Unexpected_end_of_text: diag(1126, ts.DiagnosticCategory.Error, "Unexpected_end_of_text_1126", "Unexpected end of text."), + Invalid_character: diag(1127, ts.DiagnosticCategory.Error, "Invalid_character_1127", "Invalid character."), + Declaration_or_statement_expected: diag(1128, ts.DiagnosticCategory.Error, "Declaration_or_statement_expected_1128", "Declaration or statement expected."), + Statement_expected: diag(1129, ts.DiagnosticCategory.Error, "Statement_expected_1129", "Statement expected."), + case_or_default_expected: diag(1130, ts.DiagnosticCategory.Error, "case_or_default_expected_1130", "'case' or 'default' expected."), + Property_or_signature_expected: diag(1131, ts.DiagnosticCategory.Error, "Property_or_signature_expected_1131", "Property or signature expected."), + Enum_member_expected: diag(1132, ts.DiagnosticCategory.Error, "Enum_member_expected_1132", "Enum member expected."), + Variable_declaration_expected: diag(1134, ts.DiagnosticCategory.Error, "Variable_declaration_expected_1134", "Variable declaration expected."), + Argument_expression_expected: diag(1135, ts.DiagnosticCategory.Error, "Argument_expression_expected_1135", "Argument expression expected."), + Property_assignment_expected: diag(1136, ts.DiagnosticCategory.Error, "Property_assignment_expected_1136", "Property assignment expected."), + Expression_or_comma_expected: diag(1137, ts.DiagnosticCategory.Error, "Expression_or_comma_expected_1137", "Expression or comma expected."), + Parameter_declaration_expected: diag(1138, ts.DiagnosticCategory.Error, "Parameter_declaration_expected_1138", "Parameter declaration expected."), + Type_parameter_declaration_expected: diag(1139, ts.DiagnosticCategory.Error, "Type_parameter_declaration_expected_1139", "Type parameter declaration expected."), + Type_argument_expected: diag(1140, ts.DiagnosticCategory.Error, "Type_argument_expected_1140", "Type argument expected."), + String_literal_expected: diag(1141, ts.DiagnosticCategory.Error, "String_literal_expected_1141", "String literal expected."), + Line_break_not_permitted_here: diag(1142, ts.DiagnosticCategory.Error, "Line_break_not_permitted_here_1142", "Line break not permitted here."), + or_expected: diag(1144, ts.DiagnosticCategory.Error, "or_expected_1144", "'{' or ';' expected."), + Declaration_expected: diag(1146, ts.DiagnosticCategory.Error, "Declaration_expected_1146", "Declaration expected."), + Import_declarations_in_a_namespace_cannot_reference_a_module: diag(1147, ts.DiagnosticCategory.Error, "Import_declarations_in_a_namespace_cannot_reference_a_module_1147", "Import declarations in a namespace cannot reference a module."), + Cannot_use_imports_exports_or_module_augmentations_when_module_is_none: diag(1148, ts.DiagnosticCategory.Error, "Cannot_use_imports_exports_or_module_augmentations_when_module_is_none_1148", "Cannot use imports, exports, or module augmentations when '--module' is 'none'."), + File_name_0_differs_from_already_included_file_name_1_only_in_casing: diag(1149, ts.DiagnosticCategory.Error, "File_name_0_differs_from_already_included_file_name_1_only_in_casing_1149", "File name '{0}' differs from already included file name '{1}' only in casing."), + new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead: diag(1150, ts.DiagnosticCategory.Error, "new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead_1150", "'new T[]' cannot be used to create an array. Use 'new Array()' instead."), + const_declarations_must_be_initialized: diag(1155, ts.DiagnosticCategory.Error, "const_declarations_must_be_initialized_1155", "'const' declarations must be initialized."), + const_declarations_can_only_be_declared_inside_a_block: diag(1156, ts.DiagnosticCategory.Error, "const_declarations_can_only_be_declared_inside_a_block_1156", "'const' declarations can only be declared inside a block."), + let_declarations_can_only_be_declared_inside_a_block: diag(1157, ts.DiagnosticCategory.Error, "let_declarations_can_only_be_declared_inside_a_block_1157", "'let' declarations can only be declared inside a block."), + Unterminated_template_literal: diag(1160, ts.DiagnosticCategory.Error, "Unterminated_template_literal_1160", "Unterminated template literal."), + Unterminated_regular_expression_literal: diag(1161, ts.DiagnosticCategory.Error, "Unterminated_regular_expression_literal_1161", "Unterminated regular expression literal."), + An_object_member_cannot_be_declared_optional: diag(1162, ts.DiagnosticCategory.Error, "An_object_member_cannot_be_declared_optional_1162", "An object member cannot be declared optional."), + A_yield_expression_is_only_allowed_in_a_generator_body: diag(1163, ts.DiagnosticCategory.Error, "A_yield_expression_is_only_allowed_in_a_generator_body_1163", "A 'yield' expression is only allowed in a generator body."), + Computed_property_names_are_not_allowed_in_enums: diag(1164, ts.DiagnosticCategory.Error, "Computed_property_names_are_not_allowed_in_enums_1164", "Computed property names are not allowed in enums."), + A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: diag(1165, ts.DiagnosticCategory.Error, "A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_t_1165", "A computed property name in an ambient context must refer to an expression whose type is a literal type or a 'unique symbol' type."), + A_computed_property_name_in_a_class_property_declaration_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: diag(1166, ts.DiagnosticCategory.Error, "A_computed_property_name_in_a_class_property_declaration_must_refer_to_an_expression_whose_type_is_a_1166", "A computed property name in a class property declaration must refer to an expression whose type is a literal type or a 'unique symbol' type."), + A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: diag(1168, ts.DiagnosticCategory.Error, "A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_ty_1168", "A computed property name in a method overload must refer to an expression whose type is a literal type or a 'unique symbol' type."), + A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: diag(1169, ts.DiagnosticCategory.Error, "A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_1169", "A computed property name in an interface must refer to an expression whose type is a literal type or a 'unique symbol' type."), + A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: diag(1170, ts.DiagnosticCategory.Error, "A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type__1170", "A computed property name in a type literal must refer to an expression whose type is a literal type or a 'unique symbol' type."), + A_comma_expression_is_not_allowed_in_a_computed_property_name: diag(1171, ts.DiagnosticCategory.Error, "A_comma_expression_is_not_allowed_in_a_computed_property_name_1171", "A comma expression is not allowed in a computed property name."), + extends_clause_already_seen: diag(1172, ts.DiagnosticCategory.Error, "extends_clause_already_seen_1172", "'extends' clause already seen."), + extends_clause_must_precede_implements_clause: diag(1173, ts.DiagnosticCategory.Error, "extends_clause_must_precede_implements_clause_1173", "'extends' clause must precede 'implements' clause."), + Classes_can_only_extend_a_single_class: diag(1174, ts.DiagnosticCategory.Error, "Classes_can_only_extend_a_single_class_1174", "Classes can only extend a single class."), + implements_clause_already_seen: diag(1175, ts.DiagnosticCategory.Error, "implements_clause_already_seen_1175", "'implements' clause already seen."), + Interface_declaration_cannot_have_implements_clause: diag(1176, ts.DiagnosticCategory.Error, "Interface_declaration_cannot_have_implements_clause_1176", "Interface declaration cannot have 'implements' clause."), + Binary_digit_expected: diag(1177, ts.DiagnosticCategory.Error, "Binary_digit_expected_1177", "Binary digit expected."), + Octal_digit_expected: diag(1178, ts.DiagnosticCategory.Error, "Octal_digit_expected_1178", "Octal digit expected."), + Unexpected_token_expected: diag(1179, ts.DiagnosticCategory.Error, "Unexpected_token_expected_1179", "Unexpected token. '{' expected."), + Property_destructuring_pattern_expected: diag(1180, ts.DiagnosticCategory.Error, "Property_destructuring_pattern_expected_1180", "Property destructuring pattern expected."), + Array_element_destructuring_pattern_expected: diag(1181, ts.DiagnosticCategory.Error, "Array_element_destructuring_pattern_expected_1181", "Array element destructuring pattern expected."), + A_destructuring_declaration_must_have_an_initializer: diag(1182, ts.DiagnosticCategory.Error, "A_destructuring_declaration_must_have_an_initializer_1182", "A destructuring declaration must have an initializer."), + An_implementation_cannot_be_declared_in_ambient_contexts: diag(1183, ts.DiagnosticCategory.Error, "An_implementation_cannot_be_declared_in_ambient_contexts_1183", "An implementation cannot be declared in ambient contexts."), + Modifiers_cannot_appear_here: diag(1184, ts.DiagnosticCategory.Error, "Modifiers_cannot_appear_here_1184", "Modifiers cannot appear here."), + Merge_conflict_marker_encountered: diag(1185, ts.DiagnosticCategory.Error, "Merge_conflict_marker_encountered_1185", "Merge conflict marker encountered."), + A_rest_element_cannot_have_an_initializer: diag(1186, ts.DiagnosticCategory.Error, "A_rest_element_cannot_have_an_initializer_1186", "A rest element cannot have an initializer."), + A_parameter_property_may_not_be_declared_using_a_binding_pattern: diag(1187, ts.DiagnosticCategory.Error, "A_parameter_property_may_not_be_declared_using_a_binding_pattern_1187", "A parameter property may not be declared using a binding pattern."), + Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement: diag(1188, ts.DiagnosticCategory.Error, "Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement_1188", "Only a single variable declaration is allowed in a 'for...of' statement."), + The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer: diag(1189, ts.DiagnosticCategory.Error, "The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer_1189", "The variable declaration of a 'for...in' statement cannot have an initializer."), + The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer: diag(1190, ts.DiagnosticCategory.Error, "The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer_1190", "The variable declaration of a 'for...of' statement cannot have an initializer."), + An_import_declaration_cannot_have_modifiers: diag(1191, ts.DiagnosticCategory.Error, "An_import_declaration_cannot_have_modifiers_1191", "An import declaration cannot have modifiers."), + Module_0_has_no_default_export: diag(1192, ts.DiagnosticCategory.Error, "Module_0_has_no_default_export_1192", "Module '{0}' has no default export."), + An_export_declaration_cannot_have_modifiers: diag(1193, ts.DiagnosticCategory.Error, "An_export_declaration_cannot_have_modifiers_1193", "An export declaration cannot have modifiers."), + Export_declarations_are_not_permitted_in_a_namespace: diag(1194, ts.DiagnosticCategory.Error, "Export_declarations_are_not_permitted_in_a_namespace_1194", "Export declarations are not permitted in a namespace."), + Catch_clause_variable_cannot_have_a_type_annotation: diag(1196, ts.DiagnosticCategory.Error, "Catch_clause_variable_cannot_have_a_type_annotation_1196", "Catch clause variable cannot have a type annotation."), + Catch_clause_variable_cannot_have_an_initializer: diag(1197, ts.DiagnosticCategory.Error, "Catch_clause_variable_cannot_have_an_initializer_1197", "Catch clause variable cannot have an initializer."), + An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive: diag(1198, ts.DiagnosticCategory.Error, "An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive_1198", "An extended Unicode escape value must be between 0x0 and 0x10FFFF inclusive."), + Unterminated_Unicode_escape_sequence: diag(1199, ts.DiagnosticCategory.Error, "Unterminated_Unicode_escape_sequence_1199", "Unterminated Unicode escape sequence."), + Line_terminator_not_permitted_before_arrow: diag(1200, ts.DiagnosticCategory.Error, "Line_terminator_not_permitted_before_arrow_1200", "Line terminator not permitted before arrow."), + Import_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_import_Asterisk_as_ns_from_mod_import_a_from_mod_import_d_from_mod_or_another_module_format_instead: diag(1202, ts.DiagnosticCategory.Error, "Import_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_import_Asterisk_as_1202", "Import assignment cannot be used when targeting ECMAScript modules. Consider using 'import * as ns from \"mod\"', 'import {a} from \"mod\"', 'import d from \"mod\"', or another module format instead."), + Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or_another_module_format_instead: diag(1203, ts.DiagnosticCategory.Error, "Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or__1203", "Export assignment cannot be used when targeting ECMAScript modules. Consider using 'export default' or another module format instead."), + Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided: diag(1205, ts.DiagnosticCategory.Error, "Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205", "Cannot re-export a type when the '--isolatedModules' flag is provided."), + Decorators_are_not_valid_here: diag(1206, ts.DiagnosticCategory.Error, "Decorators_are_not_valid_here_1206", "Decorators are not valid here."), + Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name: diag(1207, ts.DiagnosticCategory.Error, "Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name_1207", "Decorators cannot be applied to multiple get/set accessors of the same name."), + Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided: diag(1208, ts.DiagnosticCategory.Error, "Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided_1208", "Cannot compile namespaces when the '--isolatedModules' flag is provided."), + Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided: diag(1209, ts.DiagnosticCategory.Error, "Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided_1209", "Ambient const enums are not allowed when the '--isolatedModules' flag is provided."), + Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode: diag(1210, ts.DiagnosticCategory.Error, "Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode_1210", "Invalid use of '{0}'. Class definitions are automatically in strict mode."), + A_class_declaration_without_the_default_modifier_must_have_a_name: diag(1211, ts.DiagnosticCategory.Error, "A_class_declaration_without_the_default_modifier_must_have_a_name_1211", "A class declaration without the 'default' modifier must have a name."), + Identifier_expected_0_is_a_reserved_word_in_strict_mode: diag(1212, ts.DiagnosticCategory.Error, "Identifier_expected_0_is_a_reserved_word_in_strict_mode_1212", "Identifier expected. '{0}' is a reserved word in strict mode."), + Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode: diag(1213, ts.DiagnosticCategory.Error, "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_stric_1213", "Identifier expected. '{0}' is a reserved word in strict mode. Class definitions are automatically in strict mode."), + Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode: diag(1214, ts.DiagnosticCategory.Error, "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode_1214", "Identifier expected. '{0}' is a reserved word in strict mode. Modules are automatically in strict mode."), + Invalid_use_of_0_Modules_are_automatically_in_strict_mode: diag(1215, ts.DiagnosticCategory.Error, "Invalid_use_of_0_Modules_are_automatically_in_strict_mode_1215", "Invalid use of '{0}'. Modules are automatically in strict mode."), + Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules: diag(1216, ts.DiagnosticCategory.Error, "Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules_1216", "Identifier expected. '__esModule' is reserved as an exported marker when transforming ECMAScript modules."), + Export_assignment_is_not_supported_when_module_flag_is_system: diag(1218, ts.DiagnosticCategory.Error, "Export_assignment_is_not_supported_when_module_flag_is_system_1218", "Export assignment is not supported when '--module' flag is 'system'."), + Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_to_remove_this_warning: diag(1219, ts.DiagnosticCategory.Error, "Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_t_1219", "Experimental support for decorators is a feature that is subject to change in a future release. Set the 'experimentalDecorators' option to remove this warning."), + Generators_are_only_available_when_targeting_ECMAScript_2015_or_higher: diag(1220, ts.DiagnosticCategory.Error, "Generators_are_only_available_when_targeting_ECMAScript_2015_or_higher_1220", "Generators are only available when targeting ECMAScript 2015 or higher."), + Generators_are_not_allowed_in_an_ambient_context: diag(1221, ts.DiagnosticCategory.Error, "Generators_are_not_allowed_in_an_ambient_context_1221", "Generators are not allowed in an ambient context."), + An_overload_signature_cannot_be_declared_as_a_generator: diag(1222, ts.DiagnosticCategory.Error, "An_overload_signature_cannot_be_declared_as_a_generator_1222", "An overload signature cannot be declared as a generator."), + _0_tag_already_specified: diag(1223, ts.DiagnosticCategory.Error, "_0_tag_already_specified_1223", "'{0}' tag already specified."), + Signature_0_must_be_a_type_predicate: diag(1224, ts.DiagnosticCategory.Error, "Signature_0_must_be_a_type_predicate_1224", "Signature '{0}' must be a type predicate."), + Cannot_find_parameter_0: diag(1225, ts.DiagnosticCategory.Error, "Cannot_find_parameter_0_1225", "Cannot find parameter '{0}'."), + Type_predicate_0_is_not_assignable_to_1: diag(1226, ts.DiagnosticCategory.Error, "Type_predicate_0_is_not_assignable_to_1_1226", "Type predicate '{0}' is not assignable to '{1}'."), + Parameter_0_is_not_in_the_same_position_as_parameter_1: diag(1227, ts.DiagnosticCategory.Error, "Parameter_0_is_not_in_the_same_position_as_parameter_1_1227", "Parameter '{0}' is not in the same position as parameter '{1}'."), + A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods: diag(1228, ts.DiagnosticCategory.Error, "A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods_1228", "A type predicate is only allowed in return type position for functions and methods."), + A_type_predicate_cannot_reference_a_rest_parameter: diag(1229, ts.DiagnosticCategory.Error, "A_type_predicate_cannot_reference_a_rest_parameter_1229", "A type predicate cannot reference a rest parameter."), + A_type_predicate_cannot_reference_element_0_in_a_binding_pattern: diag(1230, ts.DiagnosticCategory.Error, "A_type_predicate_cannot_reference_element_0_in_a_binding_pattern_1230", "A type predicate cannot reference element '{0}' in a binding pattern."), + An_export_assignment_can_only_be_used_in_a_module: diag(1231, ts.DiagnosticCategory.Error, "An_export_assignment_can_only_be_used_in_a_module_1231", "An export assignment can only be used in a module."), + An_import_declaration_can_only_be_used_in_a_namespace_or_module: diag(1232, ts.DiagnosticCategory.Error, "An_import_declaration_can_only_be_used_in_a_namespace_or_module_1232", "An import declaration can only be used in a namespace or module."), + An_export_declaration_can_only_be_used_in_a_module: diag(1233, ts.DiagnosticCategory.Error, "An_export_declaration_can_only_be_used_in_a_module_1233", "An export declaration can only be used in a module."), + An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file: diag(1234, ts.DiagnosticCategory.Error, "An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file_1234", "An ambient module declaration is only allowed at the top level in a file."), + A_namespace_declaration_is_only_allowed_in_a_namespace_or_module: diag(1235, ts.DiagnosticCategory.Error, "A_namespace_declaration_is_only_allowed_in_a_namespace_or_module_1235", "A namespace declaration is only allowed in a namespace or module."), + The_return_type_of_a_property_decorator_function_must_be_either_void_or_any: diag(1236, ts.DiagnosticCategory.Error, "The_return_type_of_a_property_decorator_function_must_be_either_void_or_any_1236", "The return type of a property decorator function must be either 'void' or 'any'."), + The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any: diag(1237, ts.DiagnosticCategory.Error, "The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any_1237", "The return type of a parameter decorator function must be either 'void' or 'any'."), + Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression: diag(1238, ts.DiagnosticCategory.Error, "Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression_1238", "Unable to resolve signature of class decorator when called as an expression."), + Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression: diag(1239, ts.DiagnosticCategory.Error, "Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression_1239", "Unable to resolve signature of parameter decorator when called as an expression."), + Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression: diag(1240, ts.DiagnosticCategory.Error, "Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression_1240", "Unable to resolve signature of property decorator when called as an expression."), + Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression: diag(1241, ts.DiagnosticCategory.Error, "Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression_1241", "Unable to resolve signature of method decorator when called as an expression."), + abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration: diag(1242, ts.DiagnosticCategory.Error, "abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration_1242", "'abstract' modifier can only appear on a class, method, or property declaration."), + _0_modifier_cannot_be_used_with_1_modifier: diag(1243, ts.DiagnosticCategory.Error, "_0_modifier_cannot_be_used_with_1_modifier_1243", "'{0}' modifier cannot be used with '{1}' modifier."), + Abstract_methods_can_only_appear_within_an_abstract_class: diag(1244, ts.DiagnosticCategory.Error, "Abstract_methods_can_only_appear_within_an_abstract_class_1244", "Abstract methods can only appear within an abstract class."), + Method_0_cannot_have_an_implementation_because_it_is_marked_abstract: diag(1245, ts.DiagnosticCategory.Error, "Method_0_cannot_have_an_implementation_because_it_is_marked_abstract_1245", "Method '{0}' cannot have an implementation because it is marked abstract."), + An_interface_property_cannot_have_an_initializer: diag(1246, ts.DiagnosticCategory.Error, "An_interface_property_cannot_have_an_initializer_1246", "An interface property cannot have an initializer."), + A_type_literal_property_cannot_have_an_initializer: diag(1247, ts.DiagnosticCategory.Error, "A_type_literal_property_cannot_have_an_initializer_1247", "A type literal property cannot have an initializer."), + A_class_member_cannot_have_the_0_keyword: diag(1248, ts.DiagnosticCategory.Error, "A_class_member_cannot_have_the_0_keyword_1248", "A class member cannot have the '{0}' keyword."), + A_decorator_can_only_decorate_a_method_implementation_not_an_overload: diag(1249, ts.DiagnosticCategory.Error, "A_decorator_can_only_decorate_a_method_implementation_not_an_overload_1249", "A decorator can only decorate a method implementation, not an overload."), + Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5: diag(1250, ts.DiagnosticCategory.Error, "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_1250", "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'."), + Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_definitions_are_automatically_in_strict_mode: diag(1251, ts.DiagnosticCategory.Error, "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_d_1251", "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Class definitions are automatically in strict mode."), + Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_are_automatically_in_strict_mode: diag(1252, ts.DiagnosticCategory.Error, "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_1252", "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Modules are automatically in strict mode."), + _0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag: diag(1253, ts.DiagnosticCategory.Error, "_0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag_1253", "'{0}' tag cannot be used independently as a top level JSDoc tag."), + A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_reference: diag(1254, ts.DiagnosticCategory.Error, "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_refere_1254", "A 'const' initializer in an ambient context must be a string or numeric literal or literal enum reference."), + A_definite_assignment_assertion_is_not_permitted_in_this_context: diag(1255, ts.DiagnosticCategory.Error, "A_definite_assignment_assertion_is_not_permitted_in_this_context_1255", "A definite assignment assertion '!' is not permitted in this context."), + A_rest_element_must_be_last_in_a_tuple_type: diag(1256, ts.DiagnosticCategory.Error, "A_rest_element_must_be_last_in_a_tuple_type_1256", "A rest element must be last in a tuple type."), + A_required_element_cannot_follow_an_optional_element: diag(1257, ts.DiagnosticCategory.Error, "A_required_element_cannot_follow_an_optional_element_1257", "A required element cannot follow an optional element."), + with_statements_are_not_allowed_in_an_async_function_block: diag(1300, ts.DiagnosticCategory.Error, "with_statements_are_not_allowed_in_an_async_function_block_1300", "'with' statements are not allowed in an async function block."), + await_expression_is_only_allowed_within_an_async_function: diag(1308, ts.DiagnosticCategory.Error, "await_expression_is_only_allowed_within_an_async_function_1308", "'await' expression is only allowed within an async function."), + can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment: diag(1312, ts.DiagnosticCategory.Error, "can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment_1312", "'=' can only be used in an object literal property inside a destructuring assignment."), + The_body_of_an_if_statement_cannot_be_the_empty_statement: diag(1313, ts.DiagnosticCategory.Error, "The_body_of_an_if_statement_cannot_be_the_empty_statement_1313", "The body of an 'if' statement cannot be the empty statement."), + Global_module_exports_may_only_appear_in_module_files: diag(1314, ts.DiagnosticCategory.Error, "Global_module_exports_may_only_appear_in_module_files_1314", "Global module exports may only appear in module files."), + Global_module_exports_may_only_appear_in_declaration_files: diag(1315, ts.DiagnosticCategory.Error, "Global_module_exports_may_only_appear_in_declaration_files_1315", "Global module exports may only appear in declaration files."), + Global_module_exports_may_only_appear_at_top_level: diag(1316, ts.DiagnosticCategory.Error, "Global_module_exports_may_only_appear_at_top_level_1316", "Global module exports may only appear at top level."), + A_parameter_property_cannot_be_declared_using_a_rest_parameter: diag(1317, ts.DiagnosticCategory.Error, "A_parameter_property_cannot_be_declared_using_a_rest_parameter_1317", "A parameter property cannot be declared using a rest parameter."), + An_abstract_accessor_cannot_have_an_implementation: diag(1318, ts.DiagnosticCategory.Error, "An_abstract_accessor_cannot_have_an_implementation_1318", "An abstract accessor cannot have an implementation."), + A_default_export_can_only_be_used_in_an_ECMAScript_style_module: diag(1319, ts.DiagnosticCategory.Error, "A_default_export_can_only_be_used_in_an_ECMAScript_style_module_1319", "A default export can only be used in an ECMAScript-style module."), + Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1320, ts.DiagnosticCategory.Error, "Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member_1320", "Type of 'await' operand must either be a valid promise or must not contain a callable 'then' member."), + Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1321, ts.DiagnosticCategory.Error, "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321", "Type of 'yield' operand in an async generator must either be a valid promise or must not contain a callable 'then' member."), + Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1322, ts.DiagnosticCategory.Error, "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322", "Type of iterated elements of a 'yield*' operand must either be a valid promise or must not contain a callable 'then' member."), + Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext: diag(1323, ts.DiagnosticCategory.Error, "Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext_1323", "Dynamic import is only supported when '--module' flag is 'commonjs' or 'esNext'."), + Dynamic_import_must_have_one_specifier_as_an_argument: diag(1324, ts.DiagnosticCategory.Error, "Dynamic_import_must_have_one_specifier_as_an_argument_1324", "Dynamic import must have one specifier as an argument."), + Specifier_of_dynamic_import_cannot_be_spread_element: diag(1325, ts.DiagnosticCategory.Error, "Specifier_of_dynamic_import_cannot_be_spread_element_1325", "Specifier of dynamic import cannot be spread element."), + Dynamic_import_cannot_have_type_arguments: diag(1326, ts.DiagnosticCategory.Error, "Dynamic_import_cannot_have_type_arguments_1326", "Dynamic import cannot have type arguments"), + String_literal_with_double_quotes_expected: diag(1327, ts.DiagnosticCategory.Error, "String_literal_with_double_quotes_expected_1327", "String literal with double quotes expected."), + Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_literal: diag(1328, ts.DiagnosticCategory.Error, "Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_li_1328", "Property value can only be string literal, numeric literal, 'true', 'false', 'null', object literal or array literal."), + _0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write_0: diag(1329, ts.DiagnosticCategory.Error, "_0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write__1329", "'{0}' accepts too few arguments to be used as a decorator here. Did you mean to call it first and write '@{0}()'?"), + A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly: diag(1330, ts.DiagnosticCategory.Error, "A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly_1330", "A property of an interface or type literal whose type is a 'unique symbol' type must be 'readonly'."), + A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly: diag(1331, ts.DiagnosticCategory.Error, "A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly_1331", "A property of a class whose type is a 'unique symbol' type must be both 'static' and 'readonly'."), + A_variable_whose_type_is_a_unique_symbol_type_must_be_const: diag(1332, ts.DiagnosticCategory.Error, "A_variable_whose_type_is_a_unique_symbol_type_must_be_const_1332", "A variable whose type is a 'unique symbol' type must be 'const'."), + unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name: diag(1333, ts.DiagnosticCategory.Error, "unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name_1333", "'unique symbol' types may not be used on a variable declaration with a binding name."), + unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement: diag(1334, ts.DiagnosticCategory.Error, "unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement_1334", "'unique symbol' types are only allowed on variables in a variable statement."), + unique_symbol_types_are_not_allowed_here: diag(1335, ts.DiagnosticCategory.Error, "unique_symbol_types_are_not_allowed_here_1335", "'unique symbol' types are not allowed here."), + An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead: diag(1336, ts.DiagnosticCategory.Error, "An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead_1336", "An index signature parameter type cannot be a type alias. Consider writing '[{0}: {1}]: {2}' instead."), + An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead: diag(1337, ts.DiagnosticCategory.Error, "An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead_1337", "An index signature parameter type cannot be a union type. Consider using a mapped object type instead."), + infer_declarations_are_only_permitted_in_the_extends_clause_of_a_conditional_type: diag(1338, ts.DiagnosticCategory.Error, "infer_declarations_are_only_permitted_in_the_extends_clause_of_a_conditional_type_1338", "'infer' declarations are only permitted in the 'extends' clause of a conditional type."), + Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here: diag(1339, ts.DiagnosticCategory.Error, "Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here_1339", "Module '{0}' does not refer to a value, but is used as a value here."), + Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0: diag(1340, ts.DiagnosticCategory.Error, "Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0_1340", "Module '{0}' does not refer to a type, but is used as a type here. Did you mean 'typeof import('{0}')'?"), + Type_arguments_cannot_be_used_here: diag(1342, ts.DiagnosticCategory.Error, "Type_arguments_cannot_be_used_here_1342", "Type arguments cannot be used here."), + The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_options: diag(1343, ts.DiagnosticCategory.Error, "The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_option_1343", "The 'import.meta' meta-property is only allowed using 'ESNext' for the 'target' and 'module' compiler options."), + A_label_is_not_allowed_here: diag(1344, ts.DiagnosticCategory.Error, "A_label_is_not_allowed_here_1344", "'A label is not allowed here."), + An_expression_of_type_void_cannot_be_tested_for_truthiness: diag(1345, ts.DiagnosticCategory.Error, "An_expression_of_type_void_cannot_be_tested_for_truthiness_1345", "An expression of type 'void' cannot be tested for truthiness"), + This_parameter_is_not_allowed_with_use_strict_directive: diag(1346, ts.DiagnosticCategory.Error, "This_parameter_is_not_allowed_with_use_strict_directive_1346", "This parameter is not allowed with 'use strict' directive."), + use_strict_directive_cannot_be_used_with_non_simple_parameter_list: diag(1347, ts.DiagnosticCategory.Error, "use_strict_directive_cannot_be_used_with_non_simple_parameter_list_1347", "'use strict' directive cannot be used with non-simple parameter list."), + Non_simple_parameter_declared_here: diag(1348, ts.DiagnosticCategory.Error, "Non_simple_parameter_declared_here_1348", "Non-simple parameter declared here."), + use_strict_directive_used_here: diag(1349, ts.DiagnosticCategory.Error, "use_strict_directive_used_here_1349", "'use strict' directive used here."), + Print_the_final_configuration_instead_of_building: diag(1350, ts.DiagnosticCategory.Message, "Print_the_final_configuration_instead_of_building_1350", "Print the final configuration instead of building."), + Duplicate_identifier_0: diag(2300, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_2300", "Duplicate identifier '{0}'."), + Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: diag(2301, ts.DiagnosticCategory.Error, "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301", "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor."), + Static_members_cannot_reference_class_type_parameters: diag(2302, ts.DiagnosticCategory.Error, "Static_members_cannot_reference_class_type_parameters_2302", "Static members cannot reference class type parameters."), + Circular_definition_of_import_alias_0: diag(2303, ts.DiagnosticCategory.Error, "Circular_definition_of_import_alias_0_2303", "Circular definition of import alias '{0}'."), + Cannot_find_name_0: diag(2304, ts.DiagnosticCategory.Error, "Cannot_find_name_0_2304", "Cannot find name '{0}'."), + Module_0_has_no_exported_member_1: diag(2305, ts.DiagnosticCategory.Error, "Module_0_has_no_exported_member_1_2305", "Module '{0}' has no exported member '{1}'."), + File_0_is_not_a_module: diag(2306, ts.DiagnosticCategory.Error, "File_0_is_not_a_module_2306", "File '{0}' is not a module."), + Cannot_find_module_0: diag(2307, ts.DiagnosticCategory.Error, "Cannot_find_module_0_2307", "Cannot find module '{0}'."), + Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambiguity: diag(2308, ts.DiagnosticCategory.Error, "Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambig_2308", "Module {0} has already exported a member named '{1}'. Consider explicitly re-exporting to resolve the ambiguity."), + An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements: diag(2309, ts.DiagnosticCategory.Error, "An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements_2309", "An export assignment cannot be used in a module with other exported elements."), + Type_0_recursively_references_itself_as_a_base_type: diag(2310, ts.DiagnosticCategory.Error, "Type_0_recursively_references_itself_as_a_base_type_2310", "Type '{0}' recursively references itself as a base type."), + A_class_may_only_extend_another_class: diag(2311, ts.DiagnosticCategory.Error, "A_class_may_only_extend_another_class_2311", "A class may only extend another class."), + An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_members: diag(2312, ts.DiagnosticCategory.Error, "An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_me_2312", "An interface can only extend an object type or intersection of object types with statically known members."), + Type_parameter_0_has_a_circular_constraint: diag(2313, ts.DiagnosticCategory.Error, "Type_parameter_0_has_a_circular_constraint_2313", "Type parameter '{0}' has a circular constraint."), + Generic_type_0_requires_1_type_argument_s: diag(2314, ts.DiagnosticCategory.Error, "Generic_type_0_requires_1_type_argument_s_2314", "Generic type '{0}' requires {1} type argument(s)."), + Type_0_is_not_generic: diag(2315, ts.DiagnosticCategory.Error, "Type_0_is_not_generic_2315", "Type '{0}' is not generic."), + Global_type_0_must_be_a_class_or_interface_type: diag(2316, ts.DiagnosticCategory.Error, "Global_type_0_must_be_a_class_or_interface_type_2316", "Global type '{0}' must be a class or interface type."), + Global_type_0_must_have_1_type_parameter_s: diag(2317, ts.DiagnosticCategory.Error, "Global_type_0_must_have_1_type_parameter_s_2317", "Global type '{0}' must have {1} type parameter(s)."), + Cannot_find_global_type_0: diag(2318, ts.DiagnosticCategory.Error, "Cannot_find_global_type_0_2318", "Cannot find global type '{0}'."), + Named_property_0_of_types_1_and_2_are_not_identical: diag(2319, ts.DiagnosticCategory.Error, "Named_property_0_of_types_1_and_2_are_not_identical_2319", "Named property '{0}' of types '{1}' and '{2}' are not identical."), + Interface_0_cannot_simultaneously_extend_types_1_and_2: diag(2320, ts.DiagnosticCategory.Error, "Interface_0_cannot_simultaneously_extend_types_1_and_2_2320", "Interface '{0}' cannot simultaneously extend types '{1}' and '{2}'."), + Excessive_stack_depth_comparing_types_0_and_1: diag(2321, ts.DiagnosticCategory.Error, "Excessive_stack_depth_comparing_types_0_and_1_2321", "Excessive stack depth comparing types '{0}' and '{1}'."), + Type_0_is_not_assignable_to_type_1: diag(2322, ts.DiagnosticCategory.Error, "Type_0_is_not_assignable_to_type_1_2322", "Type '{0}' is not assignable to type '{1}'."), + Cannot_redeclare_exported_variable_0: diag(2323, ts.DiagnosticCategory.Error, "Cannot_redeclare_exported_variable_0_2323", "Cannot redeclare exported variable '{0}'."), + Property_0_is_missing_in_type_1: diag(2324, ts.DiagnosticCategory.Error, "Property_0_is_missing_in_type_1_2324", "Property '{0}' is missing in type '{1}'."), + Property_0_is_private_in_type_1_but_not_in_type_2: diag(2325, ts.DiagnosticCategory.Error, "Property_0_is_private_in_type_1_but_not_in_type_2_2325", "Property '{0}' is private in type '{1}' but not in type '{2}'."), + Types_of_property_0_are_incompatible: diag(2326, ts.DiagnosticCategory.Error, "Types_of_property_0_are_incompatible_2326", "Types of property '{0}' are incompatible."), + Property_0_is_optional_in_type_1_but_required_in_type_2: diag(2327, ts.DiagnosticCategory.Error, "Property_0_is_optional_in_type_1_but_required_in_type_2_2327", "Property '{0}' is optional in type '{1}' but required in type '{2}'."), + Types_of_parameters_0_and_1_are_incompatible: diag(2328, ts.DiagnosticCategory.Error, "Types_of_parameters_0_and_1_are_incompatible_2328", "Types of parameters '{0}' and '{1}' are incompatible."), + Index_signature_is_missing_in_type_0: diag(2329, ts.DiagnosticCategory.Error, "Index_signature_is_missing_in_type_0_2329", "Index signature is missing in type '{0}'."), + Index_signatures_are_incompatible: diag(2330, ts.DiagnosticCategory.Error, "Index_signatures_are_incompatible_2330", "Index signatures are incompatible."), + this_cannot_be_referenced_in_a_module_or_namespace_body: diag(2331, ts.DiagnosticCategory.Error, "this_cannot_be_referenced_in_a_module_or_namespace_body_2331", "'this' cannot be referenced in a module or namespace body."), + this_cannot_be_referenced_in_current_location: diag(2332, ts.DiagnosticCategory.Error, "this_cannot_be_referenced_in_current_location_2332", "'this' cannot be referenced in current location."), + this_cannot_be_referenced_in_constructor_arguments: diag(2333, ts.DiagnosticCategory.Error, "this_cannot_be_referenced_in_constructor_arguments_2333", "'this' cannot be referenced in constructor arguments."), + this_cannot_be_referenced_in_a_static_property_initializer: diag(2334, ts.DiagnosticCategory.Error, "this_cannot_be_referenced_in_a_static_property_initializer_2334", "'this' cannot be referenced in a static property initializer."), + super_can_only_be_referenced_in_a_derived_class: diag(2335, ts.DiagnosticCategory.Error, "super_can_only_be_referenced_in_a_derived_class_2335", "'super' can only be referenced in a derived class."), + super_cannot_be_referenced_in_constructor_arguments: diag(2336, ts.DiagnosticCategory.Error, "super_cannot_be_referenced_in_constructor_arguments_2336", "'super' cannot be referenced in constructor arguments."), + Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors: diag(2337, ts.DiagnosticCategory.Error, "Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors_2337", "Super calls are not permitted outside constructors or in nested functions inside constructors."), + super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_derived_class: diag(2338, ts.DiagnosticCategory.Error, "super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_der_2338", "'super' property access is permitted only in a constructor, member function, or member accessor of a derived class."), + Property_0_does_not_exist_on_type_1: diag(2339, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_2339", "Property '{0}' does not exist on type '{1}'."), + Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword: diag(2340, ts.DiagnosticCategory.Error, "Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword_2340", "Only public and protected methods of the base class are accessible via the 'super' keyword."), + Property_0_is_private_and_only_accessible_within_class_1: diag(2341, ts.DiagnosticCategory.Error, "Property_0_is_private_and_only_accessible_within_class_1_2341", "Property '{0}' is private and only accessible within class '{1}'."), + An_index_expression_argument_must_be_of_type_string_number_symbol_or_any: diag(2342, ts.DiagnosticCategory.Error, "An_index_expression_argument_must_be_of_type_string_number_symbol_or_any_2342", "An index expression argument must be of type 'string', 'number', 'symbol', or 'any'."), + This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1: diag(2343, ts.DiagnosticCategory.Error, "This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1_2343", "This syntax requires an imported helper named '{1}', but module '{0}' has no exported member '{1}'."), + Type_0_does_not_satisfy_the_constraint_1: diag(2344, ts.DiagnosticCategory.Error, "Type_0_does_not_satisfy_the_constraint_1_2344", "Type '{0}' does not satisfy the constraint '{1}'."), + Argument_of_type_0_is_not_assignable_to_parameter_of_type_1: diag(2345, ts.DiagnosticCategory.Error, "Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_2345", "Argument of type '{0}' is not assignable to parameter of type '{1}'."), + Call_target_does_not_contain_any_signatures: diag(2346, ts.DiagnosticCategory.Error, "Call_target_does_not_contain_any_signatures_2346", "Call target does not contain any signatures."), + Untyped_function_calls_may_not_accept_type_arguments: diag(2347, ts.DiagnosticCategory.Error, "Untyped_function_calls_may_not_accept_type_arguments_2347", "Untyped function calls may not accept type arguments."), + Value_of_type_0_is_not_callable_Did_you_mean_to_include_new: diag(2348, ts.DiagnosticCategory.Error, "Value_of_type_0_is_not_callable_Did_you_mean_to_include_new_2348", "Value of type '{0}' is not callable. Did you mean to include 'new'?"), + Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures: diag(2349, ts.DiagnosticCategory.Error, "Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatur_2349", "Cannot invoke an expression whose type lacks a call signature. Type '{0}' has no compatible call signatures."), + Only_a_void_function_can_be_called_with_the_new_keyword: diag(2350, ts.DiagnosticCategory.Error, "Only_a_void_function_can_be_called_with_the_new_keyword_2350", "Only a void function can be called with the 'new' keyword."), + Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature: diag(2351, ts.DiagnosticCategory.Error, "Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature_2351", "Cannot use 'new' with an expression whose type lacks a call or construct signature."), + Conversion_of_type_0_to_type_1_may_be_a_mistake_because_neither_type_sufficiently_overlaps_with_the_other_If_this_was_intentional_convert_the_expression_to_unknown_first: diag(2352, ts.DiagnosticCategory.Error, "Conversion_of_type_0_to_type_1_may_be_a_mistake_because_neither_type_sufficiently_overlaps_with_the__2352", "Conversion of type '{0}' to type '{1}' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first."), + Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1: diag(2353, ts.DiagnosticCategory.Error, "Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1_2353", "Object literal may only specify known properties, and '{0}' does not exist in type '{1}'."), + This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found: diag(2354, ts.DiagnosticCategory.Error, "This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found_2354", "This syntax requires an imported helper but module '{0}' cannot be found."), + A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value: diag(2355, ts.DiagnosticCategory.Error, "A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value_2355", "A function whose declared type is neither 'void' nor 'any' must return a value."), + An_arithmetic_operand_must_be_of_type_any_number_bigint_or_an_enum_type: diag(2356, ts.DiagnosticCategory.Error, "An_arithmetic_operand_must_be_of_type_any_number_bigint_or_an_enum_type_2356", "An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type."), + The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access: diag(2357, ts.DiagnosticCategory.Error, "The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access_2357", "The operand of an increment or decrement operator must be a variable or a property access."), + The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter: diag(2358, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_paramete_2358", "The left-hand side of an 'instanceof' expression must be of type 'any', an object type or a type parameter."), + The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_Function_interface_type: diag(2359, ts.DiagnosticCategory.Error, "The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_F_2359", "The right-hand side of an 'instanceof' expression must be of type 'any' or of a type assignable to the 'Function' interface type."), + The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol: diag(2360, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol_2360", "The left-hand side of an 'in' expression must be of type 'any', 'string', 'number', or 'symbol'."), + The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter: diag(2361, ts.DiagnosticCategory.Error, "The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter_2361", "The right-hand side of an 'in' expression must be of type 'any', an object type or a type parameter."), + The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type: diag(2362, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type_2362", "The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type."), + The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type: diag(2363, ts.DiagnosticCategory.Error, "The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type_2363", "The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type."), + The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access: diag(2364, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access_2364", "The left-hand side of an assignment expression must be a variable or a property access."), + Operator_0_cannot_be_applied_to_types_1_and_2: diag(2365, ts.DiagnosticCategory.Error, "Operator_0_cannot_be_applied_to_types_1_and_2_2365", "Operator '{0}' cannot be applied to types '{1}' and '{2}'."), + Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined: diag(2366, ts.DiagnosticCategory.Error, "Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined_2366", "Function lacks ending return statement and return type does not include 'undefined'."), + This_condition_will_always_return_0_since_the_types_1_and_2_have_no_overlap: diag(2367, ts.DiagnosticCategory.Error, "This_condition_will_always_return_0_since_the_types_1_and_2_have_no_overlap_2367", "This condition will always return '{0}' since the types '{1}' and '{2}' have no overlap."), + Type_parameter_name_cannot_be_0: diag(2368, ts.DiagnosticCategory.Error, "Type_parameter_name_cannot_be_0_2368", "Type parameter name cannot be '{0}'."), + A_parameter_property_is_only_allowed_in_a_constructor_implementation: diag(2369, ts.DiagnosticCategory.Error, "A_parameter_property_is_only_allowed_in_a_constructor_implementation_2369", "A parameter property is only allowed in a constructor implementation."), + A_rest_parameter_must_be_of_an_array_type: diag(2370, ts.DiagnosticCategory.Error, "A_rest_parameter_must_be_of_an_array_type_2370", "A rest parameter must be of an array type."), + A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation: diag(2371, ts.DiagnosticCategory.Error, "A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation_2371", "A parameter initializer is only allowed in a function or constructor implementation."), + Parameter_0_cannot_be_referenced_in_its_initializer: diag(2372, ts.DiagnosticCategory.Error, "Parameter_0_cannot_be_referenced_in_its_initializer_2372", "Parameter '{0}' cannot be referenced in its initializer."), + Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it: diag(2373, ts.DiagnosticCategory.Error, "Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it_2373", "Initializer of parameter '{0}' cannot reference identifier '{1}' declared after it."), + Duplicate_string_index_signature: diag(2374, ts.DiagnosticCategory.Error, "Duplicate_string_index_signature_2374", "Duplicate string index signature."), + Duplicate_number_index_signature: diag(2375, ts.DiagnosticCategory.Error, "Duplicate_number_index_signature_2375", "Duplicate number index signature."), + A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_properties_or_has_parameter_properties: diag(2376, ts.DiagnosticCategory.Error, "A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_proper_2376", "A 'super' call must be the first statement in the constructor when a class contains initialized properties or has parameter properties."), + Constructors_for_derived_classes_must_contain_a_super_call: diag(2377, ts.DiagnosticCategory.Error, "Constructors_for_derived_classes_must_contain_a_super_call_2377", "Constructors for derived classes must contain a 'super' call."), + A_get_accessor_must_return_a_value: diag(2378, ts.DiagnosticCategory.Error, "A_get_accessor_must_return_a_value_2378", "A 'get' accessor must return a value."), + Getter_and_setter_accessors_do_not_agree_in_visibility: diag(2379, ts.DiagnosticCategory.Error, "Getter_and_setter_accessors_do_not_agree_in_visibility_2379", "Getter and setter accessors do not agree in visibility."), + get_and_set_accessor_must_have_the_same_type: diag(2380, ts.DiagnosticCategory.Error, "get_and_set_accessor_must_have_the_same_type_2380", "'get' and 'set' accessor must have the same type."), + A_signature_with_an_implementation_cannot_use_a_string_literal_type: diag(2381, ts.DiagnosticCategory.Error, "A_signature_with_an_implementation_cannot_use_a_string_literal_type_2381", "A signature with an implementation cannot use a string literal type."), + Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature: diag(2382, ts.DiagnosticCategory.Error, "Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature_2382", "Specialized overload signature is not assignable to any non-specialized signature."), + Overload_signatures_must_all_be_exported_or_non_exported: diag(2383, ts.DiagnosticCategory.Error, "Overload_signatures_must_all_be_exported_or_non_exported_2383", "Overload signatures must all be exported or non-exported."), + Overload_signatures_must_all_be_ambient_or_non_ambient: diag(2384, ts.DiagnosticCategory.Error, "Overload_signatures_must_all_be_ambient_or_non_ambient_2384", "Overload signatures must all be ambient or non-ambient."), + Overload_signatures_must_all_be_public_private_or_protected: diag(2385, ts.DiagnosticCategory.Error, "Overload_signatures_must_all_be_public_private_or_protected_2385", "Overload signatures must all be public, private or protected."), + Overload_signatures_must_all_be_optional_or_required: diag(2386, ts.DiagnosticCategory.Error, "Overload_signatures_must_all_be_optional_or_required_2386", "Overload signatures must all be optional or required."), + Function_overload_must_be_static: diag(2387, ts.DiagnosticCategory.Error, "Function_overload_must_be_static_2387", "Function overload must be static."), + Function_overload_must_not_be_static: diag(2388, ts.DiagnosticCategory.Error, "Function_overload_must_not_be_static_2388", "Function overload must not be static."), + Function_implementation_name_must_be_0: diag(2389, ts.DiagnosticCategory.Error, "Function_implementation_name_must_be_0_2389", "Function implementation name must be '{0}'."), + Constructor_implementation_is_missing: diag(2390, ts.DiagnosticCategory.Error, "Constructor_implementation_is_missing_2390", "Constructor implementation is missing."), + Function_implementation_is_missing_or_not_immediately_following_the_declaration: diag(2391, ts.DiagnosticCategory.Error, "Function_implementation_is_missing_or_not_immediately_following_the_declaration_2391", "Function implementation is missing or not immediately following the declaration."), + Multiple_constructor_implementations_are_not_allowed: diag(2392, ts.DiagnosticCategory.Error, "Multiple_constructor_implementations_are_not_allowed_2392", "Multiple constructor implementations are not allowed."), + Duplicate_function_implementation: diag(2393, ts.DiagnosticCategory.Error, "Duplicate_function_implementation_2393", "Duplicate function implementation."), + Overload_signature_is_not_compatible_with_function_implementation: diag(2394, ts.DiagnosticCategory.Error, "Overload_signature_is_not_compatible_with_function_implementation_2394", "Overload signature is not compatible with function implementation."), + Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local: diag(2395, ts.DiagnosticCategory.Error, "Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local_2395", "Individual declarations in merged declaration '{0}' must be all exported or all local."), + Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters: diag(2396, ts.DiagnosticCategory.Error, "Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters_2396", "Duplicate identifier 'arguments'. Compiler uses 'arguments' to initialize rest parameters."), + Declaration_name_conflicts_with_built_in_global_identifier_0: diag(2397, ts.DiagnosticCategory.Error, "Declaration_name_conflicts_with_built_in_global_identifier_0_2397", "Declaration name conflicts with built-in global identifier '{0}'."), + Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference: diag(2399, ts.DiagnosticCategory.Error, "Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference_2399", "Duplicate identifier '_this'. Compiler uses variable declaration '_this' to capture 'this' reference."), + Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference: diag(2400, ts.DiagnosticCategory.Error, "Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference_2400", "Expression resolves to variable declaration '_this' that compiler uses to capture 'this' reference."), + Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference: diag(2401, ts.DiagnosticCategory.Error, "Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference_2401", "Duplicate identifier '_super'. Compiler uses '_super' to capture base class reference."), + Expression_resolves_to_super_that_compiler_uses_to_capture_base_class_reference: diag(2402, ts.DiagnosticCategory.Error, "Expression_resolves_to_super_that_compiler_uses_to_capture_base_class_reference_2402", "Expression resolves to '_super' that compiler uses to capture base class reference."), + Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2: diag(2403, ts.DiagnosticCategory.Error, "Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_t_2403", "Subsequent variable declarations must have the same type. Variable '{0}' must be of type '{1}', but here has type '{2}'."), + The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation: diag(2404, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation_2404", "The left-hand side of a 'for...in' statement cannot use a type annotation."), + The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any: diag(2405, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any_2405", "The left-hand side of a 'for...in' statement must be of type 'string' or 'any'."), + The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access: diag(2406, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access_2406", "The left-hand side of a 'for...in' statement must be a variable or a property access."), + The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_but_here_has_type_0: diag(2407, ts.DiagnosticCategory.Error, "The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_but_2407", "The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter, but here has type '{0}'."), + Setters_cannot_return_a_value: diag(2408, ts.DiagnosticCategory.Error, "Setters_cannot_return_a_value_2408", "Setters cannot return a value."), + Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class: diag(2409, ts.DiagnosticCategory.Error, "Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class_2409", "Return type of constructor signature must be assignable to the instance type of the class."), + The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any: diag(2410, ts.DiagnosticCategory.Error, "The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any_2410", "The 'with' statement is not supported. All symbols in a 'with' block will have type 'any'."), + Property_0_of_type_1_is_not_assignable_to_string_index_type_2: diag(2411, ts.DiagnosticCategory.Error, "Property_0_of_type_1_is_not_assignable_to_string_index_type_2_2411", "Property '{0}' of type '{1}' is not assignable to string index type '{2}'."), + Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2: diag(2412, ts.DiagnosticCategory.Error, "Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2_2412", "Property '{0}' of type '{1}' is not assignable to numeric index type '{2}'."), + Numeric_index_type_0_is_not_assignable_to_string_index_type_1: diag(2413, ts.DiagnosticCategory.Error, "Numeric_index_type_0_is_not_assignable_to_string_index_type_1_2413", "Numeric index type '{0}' is not assignable to string index type '{1}'."), + Class_name_cannot_be_0: diag(2414, ts.DiagnosticCategory.Error, "Class_name_cannot_be_0_2414", "Class name cannot be '{0}'."), + Class_0_incorrectly_extends_base_class_1: diag(2415, ts.DiagnosticCategory.Error, "Class_0_incorrectly_extends_base_class_1_2415", "Class '{0}' incorrectly extends base class '{1}'."), + Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2: diag(2416, ts.DiagnosticCategory.Error, "Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2_2416", "Property '{0}' in type '{1}' is not assignable to the same property in base type '{2}'."), + Class_static_side_0_incorrectly_extends_base_class_static_side_1: diag(2417, ts.DiagnosticCategory.Error, "Class_static_side_0_incorrectly_extends_base_class_static_side_1_2417", "Class static side '{0}' incorrectly extends base class static side '{1}'."), + Type_of_computed_property_s_value_is_0_which_is_not_assignable_to_type_1: diag(2418, ts.DiagnosticCategory.Error, "Type_of_computed_property_s_value_is_0_which_is_not_assignable_to_type_1_2418", "Type of computed property's value is '{0}', which is not assignable to type '{1}'."), + Class_0_incorrectly_implements_interface_1: diag(2420, ts.DiagnosticCategory.Error, "Class_0_incorrectly_implements_interface_1_2420", "Class '{0}' incorrectly implements interface '{1}'."), + A_class_can_only_implement_an_object_type_or_intersection_of_object_types_with_statically_known_members: diag(2422, ts.DiagnosticCategory.Error, "A_class_can_only_implement_an_object_type_or_intersection_of_object_types_with_statically_known_memb_2422", "A class can only implement an object type or intersection of object types with statically known members."), + Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor: diag(2423, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_access_2423", "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member accessor."), + Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_property: diag(2424, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_proper_2424", "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member property."), + Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_function: diag(2425, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_functi_2425", "Class '{0}' defines instance member property '{1}', but extended class '{2}' defines it as instance member function."), + Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function: diag(2426, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_functi_2426", "Class '{0}' defines instance member accessor '{1}', but extended class '{2}' defines it as instance member function."), + Interface_name_cannot_be_0: diag(2427, ts.DiagnosticCategory.Error, "Interface_name_cannot_be_0_2427", "Interface name cannot be '{0}'."), + All_declarations_of_0_must_have_identical_type_parameters: diag(2428, ts.DiagnosticCategory.Error, "All_declarations_of_0_must_have_identical_type_parameters_2428", "All declarations of '{0}' must have identical type parameters."), + Interface_0_incorrectly_extends_interface_1: diag(2430, ts.DiagnosticCategory.Error, "Interface_0_incorrectly_extends_interface_1_2430", "Interface '{0}' incorrectly extends interface '{1}'."), + Enum_name_cannot_be_0: diag(2431, ts.DiagnosticCategory.Error, "Enum_name_cannot_be_0_2431", "Enum name cannot be '{0}'."), + In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enum_element: diag(2432, ts.DiagnosticCategory.Error, "In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enu_2432", "In an enum with multiple declarations, only one declaration can omit an initializer for its first enum element."), + A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merged: diag(2433, ts.DiagnosticCategory.Error, "A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merg_2433", "A namespace declaration cannot be in a different file from a class or function with which it is merged."), + A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged: diag(2434, ts.DiagnosticCategory.Error, "A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged_2434", "A namespace declaration cannot be located prior to a class or function with which it is merged."), + Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces: diag(2435, ts.DiagnosticCategory.Error, "Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces_2435", "Ambient modules cannot be nested in other modules or namespaces."), + Ambient_module_declaration_cannot_specify_relative_module_name: diag(2436, ts.DiagnosticCategory.Error, "Ambient_module_declaration_cannot_specify_relative_module_name_2436", "Ambient module declaration cannot specify relative module name."), + Module_0_is_hidden_by_a_local_declaration_with_the_same_name: diag(2437, ts.DiagnosticCategory.Error, "Module_0_is_hidden_by_a_local_declaration_with_the_same_name_2437", "Module '{0}' is hidden by a local declaration with the same name."), + Import_name_cannot_be_0: diag(2438, ts.DiagnosticCategory.Error, "Import_name_cannot_be_0_2438", "Import name cannot be '{0}'."), + Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relative_module_name: diag(2439, ts.DiagnosticCategory.Error, "Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relati_2439", "Import or export declaration in an ambient module declaration cannot reference module through relative module name."), + Import_declaration_conflicts_with_local_declaration_of_0: diag(2440, ts.DiagnosticCategory.Error, "Import_declaration_conflicts_with_local_declaration_of_0_2440", "Import declaration conflicts with local declaration of '{0}'."), + Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module: diag(2441, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_2441", "Duplicate identifier '{0}'. Compiler reserves name '{1}' in top level scope of a module."), + Types_have_separate_declarations_of_a_private_property_0: diag(2442, ts.DiagnosticCategory.Error, "Types_have_separate_declarations_of_a_private_property_0_2442", "Types have separate declarations of a private property '{0}'."), + Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2: diag(2443, ts.DiagnosticCategory.Error, "Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2_2443", "Property '{0}' is protected but type '{1}' is not a class derived from '{2}'."), + Property_0_is_protected_in_type_1_but_public_in_type_2: diag(2444, ts.DiagnosticCategory.Error, "Property_0_is_protected_in_type_1_but_public_in_type_2_2444", "Property '{0}' is protected in type '{1}' but public in type '{2}'."), + Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses: diag(2445, ts.DiagnosticCategory.Error, "Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses_2445", "Property '{0}' is protected and only accessible within class '{1}' and its subclasses."), + Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1: diag(2446, ts.DiagnosticCategory.Error, "Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1_2446", "Property '{0}' is protected and only accessible through an instance of class '{1}'."), + The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead: diag(2447, ts.DiagnosticCategory.Error, "The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead_2447", "The '{0}' operator is not allowed for boolean types. Consider using '{1}' instead."), + Block_scoped_variable_0_used_before_its_declaration: diag(2448, ts.DiagnosticCategory.Error, "Block_scoped_variable_0_used_before_its_declaration_2448", "Block-scoped variable '{0}' used before its declaration."), + Class_0_used_before_its_declaration: diag(2449, ts.DiagnosticCategory.Error, "Class_0_used_before_its_declaration_2449", "Class '{0}' used before its declaration."), + Enum_0_used_before_its_declaration: diag(2450, ts.DiagnosticCategory.Error, "Enum_0_used_before_its_declaration_2450", "Enum '{0}' used before its declaration."), + Cannot_redeclare_block_scoped_variable_0: diag(2451, ts.DiagnosticCategory.Error, "Cannot_redeclare_block_scoped_variable_0_2451", "Cannot redeclare block-scoped variable '{0}'."), + An_enum_member_cannot_have_a_numeric_name: diag(2452, ts.DiagnosticCategory.Error, "An_enum_member_cannot_have_a_numeric_name_2452", "An enum member cannot have a numeric name."), + The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_type_arguments_explicitly: diag(2453, ts.DiagnosticCategory.Error, "The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_typ_2453", "The type argument for type parameter '{0}' cannot be inferred from the usage. Consider specifying the type arguments explicitly."), + Variable_0_is_used_before_being_assigned: diag(2454, ts.DiagnosticCategory.Error, "Variable_0_is_used_before_being_assigned_2454", "Variable '{0}' is used before being assigned."), + Type_argument_candidate_1_is_not_a_valid_type_argument_because_it_is_not_a_supertype_of_candidate_0: diag(2455, ts.DiagnosticCategory.Error, "Type_argument_candidate_1_is_not_a_valid_type_argument_because_it_is_not_a_supertype_of_candidate_0_2455", "Type argument candidate '{1}' is not a valid type argument because it is not a supertype of candidate '{0}'."), + Type_alias_0_circularly_references_itself: diag(2456, ts.DiagnosticCategory.Error, "Type_alias_0_circularly_references_itself_2456", "Type alias '{0}' circularly references itself."), + Type_alias_name_cannot_be_0: diag(2457, ts.DiagnosticCategory.Error, "Type_alias_name_cannot_be_0_2457", "Type alias name cannot be '{0}'."), + An_AMD_module_cannot_have_multiple_name_assignments: diag(2458, ts.DiagnosticCategory.Error, "An_AMD_module_cannot_have_multiple_name_assignments_2458", "An AMD module cannot have multiple name assignments."), + Type_0_has_no_property_1_and_no_string_index_signature: diag(2459, ts.DiagnosticCategory.Error, "Type_0_has_no_property_1_and_no_string_index_signature_2459", "Type '{0}' has no property '{1}' and no string index signature."), + Type_0_has_no_property_1: diag(2460, ts.DiagnosticCategory.Error, "Type_0_has_no_property_1_2460", "Type '{0}' has no property '{1}'."), + Type_0_is_not_an_array_type: diag(2461, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_2461", "Type '{0}' is not an array type."), + A_rest_element_must_be_last_in_a_destructuring_pattern: diag(2462, ts.DiagnosticCategory.Error, "A_rest_element_must_be_last_in_a_destructuring_pattern_2462", "A rest element must be last in a destructuring pattern."), + A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature: diag(2463, ts.DiagnosticCategory.Error, "A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature_2463", "A binding pattern parameter cannot be optional in an implementation signature."), + A_computed_property_name_must_be_of_type_string_number_symbol_or_any: diag(2464, ts.DiagnosticCategory.Error, "A_computed_property_name_must_be_of_type_string_number_symbol_or_any_2464", "A computed property name must be of type 'string', 'number', 'symbol', or 'any'."), + this_cannot_be_referenced_in_a_computed_property_name: diag(2465, ts.DiagnosticCategory.Error, "this_cannot_be_referenced_in_a_computed_property_name_2465", "'this' cannot be referenced in a computed property name."), + super_cannot_be_referenced_in_a_computed_property_name: diag(2466, ts.DiagnosticCategory.Error, "super_cannot_be_referenced_in_a_computed_property_name_2466", "'super' cannot be referenced in a computed property name."), + A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type: diag(2467, ts.DiagnosticCategory.Error, "A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type_2467", "A computed property name cannot reference a type parameter from its containing type."), + Cannot_find_global_value_0: diag(2468, ts.DiagnosticCategory.Error, "Cannot_find_global_value_0_2468", "Cannot find global value '{0}'."), + The_0_operator_cannot_be_applied_to_type_symbol: diag(2469, ts.DiagnosticCategory.Error, "The_0_operator_cannot_be_applied_to_type_symbol_2469", "The '{0}' operator cannot be applied to type 'symbol'."), + Symbol_reference_does_not_refer_to_the_global_Symbol_constructor_object: diag(2470, ts.DiagnosticCategory.Error, "Symbol_reference_does_not_refer_to_the_global_Symbol_constructor_object_2470", "'Symbol' reference does not refer to the global Symbol constructor object."), + A_computed_property_name_of_the_form_0_must_be_of_type_symbol: diag(2471, ts.DiagnosticCategory.Error, "A_computed_property_name_of_the_form_0_must_be_of_type_symbol_2471", "A computed property name of the form '{0}' must be of type 'symbol'."), + Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher: diag(2472, ts.DiagnosticCategory.Error, "Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher_2472", "Spread operator in 'new' expressions is only available when targeting ECMAScript 5 and higher."), + Enum_declarations_must_all_be_const_or_non_const: diag(2473, ts.DiagnosticCategory.Error, "Enum_declarations_must_all_be_const_or_non_const_2473", "Enum declarations must all be const or non-const."), + In_const_enum_declarations_member_initializer_must_be_constant_expression: diag(2474, ts.DiagnosticCategory.Error, "In_const_enum_declarations_member_initializer_must_be_constant_expression_2474", "In 'const' enum declarations member initializer must be constant expression."), + const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment_or_type_query: diag(2475, ts.DiagnosticCategory.Error, "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475", "'const' enums can only be used in property or index access expressions or the right hand side of an import declaration or export assignment or type query."), + A_const_enum_member_can_only_be_accessed_using_a_string_literal: diag(2476, ts.DiagnosticCategory.Error, "A_const_enum_member_can_only_be_accessed_using_a_string_literal_2476", "A const enum member can only be accessed using a string literal."), + const_enum_member_initializer_was_evaluated_to_a_non_finite_value: diag(2477, ts.DiagnosticCategory.Error, "const_enum_member_initializer_was_evaluated_to_a_non_finite_value_2477", "'const' enum member initializer was evaluated to a non-finite value."), + const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN: diag(2478, ts.DiagnosticCategory.Error, "const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN_2478", "'const' enum member initializer was evaluated to disallowed value 'NaN'."), + Property_0_does_not_exist_on_const_enum_1: diag(2479, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_const_enum_1_2479", "Property '{0}' does not exist on 'const' enum '{1}'."), + let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations: diag(2480, ts.DiagnosticCategory.Error, "let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations_2480", "'let' is not allowed to be used as a name in 'let' or 'const' declarations."), + Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1: diag(2481, ts.DiagnosticCategory.Error, "Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1_2481", "Cannot initialize outer scoped variable '{0}' in the same scope as block scoped declaration '{1}'."), + The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation: diag(2483, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation_2483", "The left-hand side of a 'for...of' statement cannot use a type annotation."), + Export_declaration_conflicts_with_exported_declaration_of_0: diag(2484, ts.DiagnosticCategory.Error, "Export_declaration_conflicts_with_exported_declaration_of_0_2484", "Export declaration conflicts with exported declaration of '{0}'."), + The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access: diag(2487, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access_2487", "The left-hand side of a 'for...of' statement must be a variable or a property access."), + Type_0_must_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2488, ts.DiagnosticCategory.Error, "Type_0_must_have_a_Symbol_iterator_method_that_returns_an_iterator_2488", "Type '{0}' must have a '[Symbol.iterator]()' method that returns an iterator."), + An_iterator_must_have_a_next_method: diag(2489, ts.DiagnosticCategory.Error, "An_iterator_must_have_a_next_method_2489", "An iterator must have a 'next()' method."), + The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property: diag(2490, ts.DiagnosticCategory.Error, "The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property_2490", "The type returned by the 'next()' method of an iterator must have a 'value' property."), + The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern: diag(2491, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern_2491", "The left-hand side of a 'for...in' statement cannot be a destructuring pattern."), + Cannot_redeclare_identifier_0_in_catch_clause: diag(2492, ts.DiagnosticCategory.Error, "Cannot_redeclare_identifier_0_in_catch_clause_2492", "Cannot redeclare identifier '{0}' in catch clause."), + Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2: diag(2493, ts.DiagnosticCategory.Error, "Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2_2493", "Tuple type '{0}' with length '{1}' cannot be assigned to tuple with length '{2}'."), + Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher: diag(2494, ts.DiagnosticCategory.Error, "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494", "Using a string in a 'for...of' statement is only supported in ECMAScript 5 and higher."), + Type_0_is_not_an_array_type_or_a_string_type: diag(2495, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_a_string_type_2495", "Type '{0}' is not an array type or a string type."), + The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_standard_function_expression: diag(2496, ts.DiagnosticCategory.Error, "The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_stand_2496", "The 'arguments' object cannot be referenced in an arrow function in ES3 and ES5. Consider using a standard function expression."), + Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct: diag(2497, ts.DiagnosticCategory.Error, "Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct_2497", "Module '{0}' resolves to a non-module entity and cannot be imported using this construct."), + Module_0_uses_export_and_cannot_be_used_with_export_Asterisk: diag(2498, ts.DiagnosticCategory.Error, "Module_0_uses_export_and_cannot_be_used_with_export_Asterisk_2498", "Module '{0}' uses 'export =' and cannot be used with 'export *'."), + An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments: diag(2499, ts.DiagnosticCategory.Error, "An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments_2499", "An interface can only extend an identifier/qualified-name with optional type arguments."), + A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments: diag(2500, ts.DiagnosticCategory.Error, "A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments_2500", "A class can only implement an identifier/qualified-name with optional type arguments."), + A_rest_element_cannot_contain_a_binding_pattern: diag(2501, ts.DiagnosticCategory.Error, "A_rest_element_cannot_contain_a_binding_pattern_2501", "A rest element cannot contain a binding pattern."), + _0_is_referenced_directly_or_indirectly_in_its_own_type_annotation: diag(2502, ts.DiagnosticCategory.Error, "_0_is_referenced_directly_or_indirectly_in_its_own_type_annotation_2502", "'{0}' is referenced directly or indirectly in its own type annotation."), + Cannot_find_namespace_0: diag(2503, ts.DiagnosticCategory.Error, "Cannot_find_namespace_0_2503", "Cannot find namespace '{0}'."), + Type_0_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator: diag(2504, ts.DiagnosticCategory.Error, "Type_0_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator_2504", "Type '{0}' must have a '[Symbol.asyncIterator]()' method that returns an async iterator."), + A_generator_cannot_have_a_void_type_annotation: diag(2505, ts.DiagnosticCategory.Error, "A_generator_cannot_have_a_void_type_annotation_2505", "A generator cannot have a 'void' type annotation."), + _0_is_referenced_directly_or_indirectly_in_its_own_base_expression: diag(2506, ts.DiagnosticCategory.Error, "_0_is_referenced_directly_or_indirectly_in_its_own_base_expression_2506", "'{0}' is referenced directly or indirectly in its own base expression."), + Type_0_is_not_a_constructor_function_type: diag(2507, ts.DiagnosticCategory.Error, "Type_0_is_not_a_constructor_function_type_2507", "Type '{0}' is not a constructor function type."), + No_base_constructor_has_the_specified_number_of_type_arguments: diag(2508, ts.DiagnosticCategory.Error, "No_base_constructor_has_the_specified_number_of_type_arguments_2508", "No base constructor has the specified number of type arguments."), + Base_constructor_return_type_0_is_not_an_object_type_or_intersection_of_object_types_with_statically_known_members: diag(2509, ts.DiagnosticCategory.Error, "Base_constructor_return_type_0_is_not_an_object_type_or_intersection_of_object_types_with_statically_2509", "Base constructor return type '{0}' is not an object type or intersection of object types with statically known members."), + Base_constructors_must_all_have_the_same_return_type: diag(2510, ts.DiagnosticCategory.Error, "Base_constructors_must_all_have_the_same_return_type_2510", "Base constructors must all have the same return type."), + Cannot_create_an_instance_of_an_abstract_class: diag(2511, ts.DiagnosticCategory.Error, "Cannot_create_an_instance_of_an_abstract_class_2511", "Cannot create an instance of an abstract class."), + Overload_signatures_must_all_be_abstract_or_non_abstract: diag(2512, ts.DiagnosticCategory.Error, "Overload_signatures_must_all_be_abstract_or_non_abstract_2512", "Overload signatures must all be abstract or non-abstract."), + Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression: diag(2513, ts.DiagnosticCategory.Error, "Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression_2513", "Abstract method '{0}' in class '{1}' cannot be accessed via super expression."), + Classes_containing_abstract_methods_must_be_marked_abstract: diag(2514, ts.DiagnosticCategory.Error, "Classes_containing_abstract_methods_must_be_marked_abstract_2514", "Classes containing abstract methods must be marked abstract."), + Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2: diag(2515, ts.DiagnosticCategory.Error, "Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2_2515", "Non-abstract class '{0}' does not implement inherited abstract member '{1}' from class '{2}'."), + All_declarations_of_an_abstract_method_must_be_consecutive: diag(2516, ts.DiagnosticCategory.Error, "All_declarations_of_an_abstract_method_must_be_consecutive_2516", "All declarations of an abstract method must be consecutive."), + Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type: diag(2517, ts.DiagnosticCategory.Error, "Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type_2517", "Cannot assign an abstract constructor type to a non-abstract constructor type."), + A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard: diag(2518, ts.DiagnosticCategory.Error, "A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard_2518", "A 'this'-based type guard is not compatible with a parameter-based type guard."), + An_async_iterator_must_have_a_next_method: diag(2519, ts.DiagnosticCategory.Error, "An_async_iterator_must_have_a_next_method_2519", "An async iterator must have a 'next()' method."), + Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions: diag(2520, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions_2520", "Duplicate identifier '{0}'. Compiler uses declaration '{1}' to support async functions."), + Expression_resolves_to_variable_declaration_0_that_compiler_uses_to_support_async_functions: diag(2521, ts.DiagnosticCategory.Error, "Expression_resolves_to_variable_declaration_0_that_compiler_uses_to_support_async_functions_2521", "Expression resolves to variable declaration '{0}' that compiler uses to support async functions."), + The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_using_a_standard_function_or_method: diag(2522, ts.DiagnosticCategory.Error, "The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_usi_2522", "The 'arguments' object cannot be referenced in an async function or method in ES3 and ES5. Consider using a standard function or method."), + yield_expressions_cannot_be_used_in_a_parameter_initializer: diag(2523, ts.DiagnosticCategory.Error, "yield_expressions_cannot_be_used_in_a_parameter_initializer_2523", "'yield' expressions cannot be used in a parameter initializer."), + await_expressions_cannot_be_used_in_a_parameter_initializer: diag(2524, ts.DiagnosticCategory.Error, "await_expressions_cannot_be_used_in_a_parameter_initializer_2524", "'await' expressions cannot be used in a parameter initializer."), + Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value: diag(2525, ts.DiagnosticCategory.Error, "Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value_2525", "Initializer provides no value for this binding element and the binding element has no default value."), + A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface: diag(2526, ts.DiagnosticCategory.Error, "A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface_2526", "A 'this' type is available only in a non-static member of a class or interface."), + The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary: diag(2527, ts.DiagnosticCategory.Error, "The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary_2527", "The inferred type of '{0}' references an inaccessible '{1}' type. A type annotation is necessary."), + A_module_cannot_have_multiple_default_exports: diag(2528, ts.DiagnosticCategory.Error, "A_module_cannot_have_multiple_default_exports_2528", "A module cannot have multiple default exports."), + Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_functions: diag(2529, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_func_2529", "Duplicate identifier '{0}'. Compiler reserves name '{1}' in top level scope of a module containing async functions."), + Property_0_is_incompatible_with_index_signature: diag(2530, ts.DiagnosticCategory.Error, "Property_0_is_incompatible_with_index_signature_2530", "Property '{0}' is incompatible with index signature."), + Object_is_possibly_null: diag(2531, ts.DiagnosticCategory.Error, "Object_is_possibly_null_2531", "Object is possibly 'null'."), + Object_is_possibly_undefined: diag(2532, ts.DiagnosticCategory.Error, "Object_is_possibly_undefined_2532", "Object is possibly 'undefined'."), + Object_is_possibly_null_or_undefined: diag(2533, ts.DiagnosticCategory.Error, "Object_is_possibly_null_or_undefined_2533", "Object is possibly 'null' or 'undefined'."), + A_function_returning_never_cannot_have_a_reachable_end_point: diag(2534, ts.DiagnosticCategory.Error, "A_function_returning_never_cannot_have_a_reachable_end_point_2534", "A function returning 'never' cannot have a reachable end point."), + Enum_type_0_has_members_with_initializers_that_are_not_literals: diag(2535, ts.DiagnosticCategory.Error, "Enum_type_0_has_members_with_initializers_that_are_not_literals_2535", "Enum type '{0}' has members with initializers that are not literals."), + Type_0_cannot_be_used_to_index_type_1: diag(2536, ts.DiagnosticCategory.Error, "Type_0_cannot_be_used_to_index_type_1_2536", "Type '{0}' cannot be used to index type '{1}'."), + Type_0_has_no_matching_index_signature_for_type_1: diag(2537, ts.DiagnosticCategory.Error, "Type_0_has_no_matching_index_signature_for_type_1_2537", "Type '{0}' has no matching index signature for type '{1}'."), + Type_0_cannot_be_used_as_an_index_type: diag(2538, ts.DiagnosticCategory.Error, "Type_0_cannot_be_used_as_an_index_type_2538", "Type '{0}' cannot be used as an index type."), + Cannot_assign_to_0_because_it_is_not_a_variable: diag(2539, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_not_a_variable_2539", "Cannot assign to '{0}' because it is not a variable."), + Cannot_assign_to_0_because_it_is_a_read_only_property: diag(2540, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_a_read_only_property_2540", "Cannot assign to '{0}' because it is a read-only property."), + The_target_of_an_assignment_must_be_a_variable_or_a_property_access: diag(2541, ts.DiagnosticCategory.Error, "The_target_of_an_assignment_must_be_a_variable_or_a_property_access_2541", "The target of an assignment must be a variable or a property access."), + Index_signature_in_type_0_only_permits_reading: diag(2542, ts.DiagnosticCategory.Error, "Index_signature_in_type_0_only_permits_reading_2542", "Index signature in type '{0}' only permits reading."), + Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference: diag(2543, ts.DiagnosticCategory.Error, "Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_me_2543", "Duplicate identifier '_newTarget'. Compiler uses variable declaration '_newTarget' to capture 'new.target' meta-property reference."), + Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta_property_reference: diag(2544, ts.DiagnosticCategory.Error, "Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta__2544", "Expression resolves to variable declaration '_newTarget' that compiler uses to capture 'new.target' meta-property reference."), + A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any: diag(2545, ts.DiagnosticCategory.Error, "A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any_2545", "A mixin class must have a constructor with a single rest parameter of type 'any[]'."), + Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1: diag(2546, ts.DiagnosticCategory.Error, "Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1_2546", "Property '{0}' has conflicting declarations and is inaccessible in type '{1}'."), + The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property: diag(2547, ts.DiagnosticCategory.Error, "The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value__2547", "The type returned by the 'next()' method of an async iterator must be a promise for a type with a 'value' property."), + Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2548, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548", "Type '{0}' is not an array type or does not have a '[Symbol.iterator]()' method that returns an iterator."), + Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2549, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549", "Type '{0}' is not an array type or a string type or does not have a '[Symbol.iterator]()' method that returns an iterator."), + Property_0_does_not_exist_on_type_1_Did_you_mean_2: diag(2551, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551", "Property '{0}' does not exist on type '{1}'. Did you mean '{2}'?"), + Cannot_find_name_0_Did_you_mean_1: diag(2552, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Did_you_mean_1_2552", "Cannot find name '{0}'. Did you mean '{1}'?"), + Computed_values_are_not_permitted_in_an_enum_with_string_valued_members: diag(2553, ts.DiagnosticCategory.Error, "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553", "Computed values are not permitted in an enum with string valued members."), + Expected_0_arguments_but_got_1: diag(2554, ts.DiagnosticCategory.Error, "Expected_0_arguments_but_got_1_2554", "Expected {0} arguments, but got {1}."), + Expected_at_least_0_arguments_but_got_1: diag(2555, ts.DiagnosticCategory.Error, "Expected_at_least_0_arguments_but_got_1_2555", "Expected at least {0} arguments, but got {1}."), + Expected_0_arguments_but_got_1_or_more: diag(2556, ts.DiagnosticCategory.Error, "Expected_0_arguments_but_got_1_or_more_2556", "Expected {0} arguments, but got {1} or more."), + Expected_at_least_0_arguments_but_got_1_or_more: diag(2557, ts.DiagnosticCategory.Error, "Expected_at_least_0_arguments_but_got_1_or_more_2557", "Expected at least {0} arguments, but got {1} or more."), + Expected_0_type_arguments_but_got_1: diag(2558, ts.DiagnosticCategory.Error, "Expected_0_type_arguments_but_got_1_2558", "Expected {0} type arguments, but got {1}."), + Type_0_has_no_properties_in_common_with_type_1: diag(2559, ts.DiagnosticCategory.Error, "Type_0_has_no_properties_in_common_with_type_1_2559", "Type '{0}' has no properties in common with type '{1}'."), + Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it: diag(2560, ts.DiagnosticCategory.Error, "Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it_2560", "Value of type '{0}' has no properties in common with type '{1}'. Did you mean to call it?"), + Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_write_2: diag(2561, ts.DiagnosticCategory.Error, "Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_writ_2561", "Object literal may only specify known properties, but '{0}' does not exist in type '{1}'. Did you mean to write '{2}'?"), + Base_class_expressions_cannot_reference_class_type_parameters: diag(2562, ts.DiagnosticCategory.Error, "Base_class_expressions_cannot_reference_class_type_parameters_2562", "Base class expressions cannot reference class type parameters."), + The_containing_function_or_module_body_is_too_large_for_control_flow_analysis: diag(2563, ts.DiagnosticCategory.Error, "The_containing_function_or_module_body_is_too_large_for_control_flow_analysis_2563", "The containing function or module body is too large for control flow analysis."), + Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor: diag(2564, ts.DiagnosticCategory.Error, "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor_2564", "Property '{0}' has no initializer and is not definitely assigned in the constructor."), + Property_0_is_used_before_being_assigned: diag(2565, ts.DiagnosticCategory.Error, "Property_0_is_used_before_being_assigned_2565", "Property '{0}' is used before being assigned."), + A_rest_element_cannot_have_a_property_name: diag(2566, ts.DiagnosticCategory.Error, "A_rest_element_cannot_have_a_property_name_2566", "A rest element cannot have a property name."), + Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations: diag(2567, ts.DiagnosticCategory.Error, "Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations_2567", "Enum declarations can only merge with namespace or other enum declarations."), + Type_0_is_not_an_array_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators: diag(2568, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators_2568", "Type '{0}' is not an array type. Use compiler option '--downlevelIteration' to allow iterating of iterators."), + Type_0_is_not_an_array_type_or_a_string_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators: diag(2569, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_a_string_type_Use_compiler_option_downlevelIteration_to_allow_iterati_2569", "Type '{0}' is not an array type or a string type. Use compiler option '--downlevelIteration' to allow iterating of iterators."), + Property_0_does_not_exist_on_type_1_Did_you_forget_to_use_await: diag(2570, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_Did_you_forget_to_use_await_2570", "Property '{0}' does not exist on type '{1}'. Did you forget to use 'await'?"), + Object_is_of_type_unknown: diag(2571, ts.DiagnosticCategory.Error, "Object_is_of_type_unknown_2571", "Object is of type 'unknown'."), + Rest_signatures_are_incompatible: diag(2572, ts.DiagnosticCategory.Error, "Rest_signatures_are_incompatible_2572", "Rest signatures are incompatible."), + Property_0_is_incompatible_with_rest_element_type: diag(2573, ts.DiagnosticCategory.Error, "Property_0_is_incompatible_with_rest_element_type_2573", "Property '{0}' is incompatible with rest element type."), + A_rest_element_type_must_be_an_array_type: diag(2574, ts.DiagnosticCategory.Error, "A_rest_element_type_must_be_an_array_type_2574", "A rest element type must be an array type."), + No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments: diag(2575, ts.DiagnosticCategory.Error, "No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments_2575", "No overload expects {0} arguments, but overloads do exist that expect either {1} or {2} arguments."), + Property_0_is_a_static_member_of_type_1: diag(2576, ts.DiagnosticCategory.Error, "Property_0_is_a_static_member_of_type_1_2576", "Property '{0}' is a static member of type '{1}'"), + Return_type_annotation_circularly_references_itself: diag(2577, ts.DiagnosticCategory.Error, "Return_type_annotation_circularly_references_itself_2577", "Return type annotation circularly references itself."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_and_then_add_node_to_the_types_field_in_your_tsconfig: diag(2580, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_and_th_2580", "Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i @types/node` and then add `node` to the types field in your tsconfig."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_and_then_add_jquery_to_the_types_field_in_your_tsconfig: diag(2581, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_an_2581", "Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i @types/jquery` and then add `jquery` to the types field in your tsconfig."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha_and_then_add_jest_or_mocha_to_the_types_field_in_your_tsconfig: diag(2582, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashje_2582", "Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha` and then add `jest` or `mocha` to the types field in your tsconfig."), + Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later: diag(2583, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2583", "Cannot find name '{0}'. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later."), + Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom: diag(2584, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2584", "Cannot find name '{0}'. Do you need to change your target library? Try changing the `lib` compiler option to include 'dom'."), + _0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later: diag(2585, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_2585", "'{0}' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later."), + Enum_type_0_circularly_references_itself: diag(2586, ts.DiagnosticCategory.Error, "Enum_type_0_circularly_references_itself_2586", "Enum type '{0}' circularly references itself."), + JSDoc_type_0_circularly_references_itself: diag(2587, ts.DiagnosticCategory.Error, "JSDoc_type_0_circularly_references_itself_2587", "JSDoc type '{0}' circularly references itself."), + Cannot_assign_to_0_because_it_is_a_constant: diag(2588, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_a_constant_2588", "Cannot assign to '{0}' because it is a constant."), + JSX_element_attributes_type_0_may_not_be_a_union_type: diag(2600, ts.DiagnosticCategory.Error, "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", "JSX element attributes type '{0}' may not be a union type."), + The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: diag(2601, ts.DiagnosticCategory.Error, "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", "The return type of a JSX element constructor must return an object type."), + JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: diag(2602, ts.DiagnosticCategory.Error, "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist."), + Property_0_in_type_1_is_not_assignable_to_type_2: diag(2603, ts.DiagnosticCategory.Error, "Property_0_in_type_1_is_not_assignable_to_type_2_2603", "Property '{0}' in type '{1}' is not assignable to type '{2}'."), + JSX_element_type_0_does_not_have_any_construct_or_call_signatures: diag(2604, ts.DiagnosticCategory.Error, "JSX_element_type_0_does_not_have_any_construct_or_call_signatures_2604", "JSX element type '{0}' does not have any construct or call signatures."), + JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements: diag(2605, ts.DiagnosticCategory.Error, "JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements_2605", "JSX element type '{0}' is not a constructor function for JSX elements."), + Property_0_of_JSX_spread_attribute_is_not_assignable_to_target_property: diag(2606, ts.DiagnosticCategory.Error, "Property_0_of_JSX_spread_attribute_is_not_assignable_to_target_property_2606", "Property '{0}' of JSX spread attribute is not assignable to target property."), + JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property: diag(2607, ts.DiagnosticCategory.Error, "JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property_2607", "JSX element class does not support attributes because it does not have a '{0}' property."), + The_global_type_JSX_0_may_not_have_more_than_one_property: diag(2608, ts.DiagnosticCategory.Error, "The_global_type_JSX_0_may_not_have_more_than_one_property_2608", "The global type 'JSX.{0}' may not have more than one property."), + JSX_spread_child_must_be_an_array_type: diag(2609, ts.DiagnosticCategory.Error, "JSX_spread_child_must_be_an_array_type_2609", "JSX spread child must be an array type."), + Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity: diag(2649, ts.DiagnosticCategory.Error, "Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity_2649", "Cannot augment module '{0}' with value exports because it resolves to a non-module entity."), + A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums: diag(2651, ts.DiagnosticCategory.Error, "A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_memb_2651", "A member initializer in a enum declaration cannot reference members declared after it, including members defined in other enums."), + Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead: diag(2652, ts.DiagnosticCategory.Error, "Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_d_2652", "Merged declaration '{0}' cannot include a default export declaration. Consider adding a separate 'export default {0}' declaration instead."), + Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1: diag(2653, ts.DiagnosticCategory.Error, "Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1_2653", "Non-abstract class expression does not implement inherited abstract member '{0}' from class '{1}'."), + Exported_external_package_typings_file_cannot_contain_tripleslash_references_Please_contact_the_package_author_to_update_the_package_definition: diag(2654, ts.DiagnosticCategory.Error, "Exported_external_package_typings_file_cannot_contain_tripleslash_references_Please_contact_the_pack_2654", "Exported external package typings file cannot contain tripleslash references. Please contact the package author to update the package definition."), + Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_the_package_definition: diag(2656, ts.DiagnosticCategory.Error, "Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_2656", "Exported external package typings file '{0}' is not a module. Please contact the package author to update the package definition."), + JSX_expressions_must_have_one_parent_element: diag(2657, ts.DiagnosticCategory.Error, "JSX_expressions_must_have_one_parent_element_2657", "JSX expressions must have one parent element."), + Type_0_provides_no_match_for_the_signature_1: diag(2658, ts.DiagnosticCategory.Error, "Type_0_provides_no_match_for_the_signature_1_2658", "Type '{0}' provides no match for the signature '{1}'."), + super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_higher: diag(2659, ts.DiagnosticCategory.Error, "super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_highe_2659", "'super' is only allowed in members of object literal expressions when option 'target' is 'ES2015' or higher."), + super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions: diag(2660, ts.DiagnosticCategory.Error, "super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions_2660", "'super' can only be referenced in members of derived classes or object literal expressions."), + Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module: diag(2661, ts.DiagnosticCategory.Error, "Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module_2661", "Cannot export '{0}'. Only local declarations can be exported from a module."), + Cannot_find_name_0_Did_you_mean_the_static_member_1_0: diag(2662, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Did_you_mean_the_static_member_1_0_2662", "Cannot find name '{0}'. Did you mean the static member '{1}.{0}'?"), + Cannot_find_name_0_Did_you_mean_the_instance_member_this_0: diag(2663, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Did_you_mean_the_instance_member_this_0_2663", "Cannot find name '{0}'. Did you mean the instance member 'this.{0}'?"), + Invalid_module_name_in_augmentation_module_0_cannot_be_found: diag(2664, ts.DiagnosticCategory.Error, "Invalid_module_name_in_augmentation_module_0_cannot_be_found_2664", "Invalid module name in augmentation, module '{0}' cannot be found."), + Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented: diag(2665, ts.DiagnosticCategory.Error, "Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augm_2665", "Invalid module name in augmentation. Module '{0}' resolves to an untyped module at '{1}', which cannot be augmented."), + Exports_and_export_assignments_are_not_permitted_in_module_augmentations: diag(2666, ts.DiagnosticCategory.Error, "Exports_and_export_assignments_are_not_permitted_in_module_augmentations_2666", "Exports and export assignments are not permitted in module augmentations."), + Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_module: diag(2667, ts.DiagnosticCategory.Error, "Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_mod_2667", "Imports are not permitted in module augmentations. Consider moving them to the enclosing external module."), + export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always_visible: diag(2668, ts.DiagnosticCategory.Error, "export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always__2668", "'export' modifier cannot be applied to ambient modules and module augmentations since they are always visible."), + Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_declarations: diag(2669, ts.DiagnosticCategory.Error, "Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_2669", "Augmentations for the global scope can only be directly nested in external modules or ambient module declarations."), + Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambient_context: diag(2670, ts.DiagnosticCategory.Error, "Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambien_2670", "Augmentations for the global scope should have 'declare' modifier unless they appear in already ambient context."), + Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity: diag(2671, ts.DiagnosticCategory.Error, "Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity_2671", "Cannot augment module '{0}' because it resolves to a non-module entity."), + Cannot_assign_a_0_constructor_type_to_a_1_constructor_type: diag(2672, ts.DiagnosticCategory.Error, "Cannot_assign_a_0_constructor_type_to_a_1_constructor_type_2672", "Cannot assign a '{0}' constructor type to a '{1}' constructor type."), + Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration: diag(2673, ts.DiagnosticCategory.Error, "Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration_2673", "Constructor of class '{0}' is private and only accessible within the class declaration."), + Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration: diag(2674, ts.DiagnosticCategory.Error, "Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration_2674", "Constructor of class '{0}' is protected and only accessible within the class declaration."), + Cannot_extend_a_class_0_Class_constructor_is_marked_as_private: diag(2675, ts.DiagnosticCategory.Error, "Cannot_extend_a_class_0_Class_constructor_is_marked_as_private_2675", "Cannot extend a class '{0}'. Class constructor is marked as private."), + Accessors_must_both_be_abstract_or_non_abstract: diag(2676, ts.DiagnosticCategory.Error, "Accessors_must_both_be_abstract_or_non_abstract_2676", "Accessors must both be abstract or non-abstract."), + A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type: diag(2677, ts.DiagnosticCategory.Error, "A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type_2677", "A type predicate's type must be assignable to its parameter's type."), + Type_0_is_not_comparable_to_type_1: diag(2678, ts.DiagnosticCategory.Error, "Type_0_is_not_comparable_to_type_1_2678", "Type '{0}' is not comparable to type '{1}'."), + A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void: diag(2679, ts.DiagnosticCategory.Error, "A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void_2679", "A function that is called with the 'new' keyword cannot have a 'this' type that is 'void'."), + A_0_parameter_must_be_the_first_parameter: diag(2680, ts.DiagnosticCategory.Error, "A_0_parameter_must_be_the_first_parameter_2680", "A '{0}' parameter must be the first parameter."), + A_constructor_cannot_have_a_this_parameter: diag(2681, ts.DiagnosticCategory.Error, "A_constructor_cannot_have_a_this_parameter_2681", "A constructor cannot have a 'this' parameter."), + get_and_set_accessor_must_have_the_same_this_type: diag(2682, ts.DiagnosticCategory.Error, "get_and_set_accessor_must_have_the_same_this_type_2682", "'get' and 'set' accessor must have the same 'this' type."), + this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation: diag(2683, ts.DiagnosticCategory.Error, "this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_2683", "'this' implicitly has type 'any' because it does not have a type annotation."), + The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1: diag(2684, ts.DiagnosticCategory.Error, "The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1_2684", "The 'this' context of type '{0}' is not assignable to method's 'this' of type '{1}'."), + The_this_types_of_each_signature_are_incompatible: diag(2685, ts.DiagnosticCategory.Error, "The_this_types_of_each_signature_are_incompatible_2685", "The 'this' types of each signature are incompatible."), + _0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead: diag(2686, ts.DiagnosticCategory.Error, "_0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead_2686", "'{0}' refers to a UMD global, but the current file is a module. Consider adding an import instead."), + All_declarations_of_0_must_have_identical_modifiers: diag(2687, ts.DiagnosticCategory.Error, "All_declarations_of_0_must_have_identical_modifiers_2687", "All declarations of '{0}' must have identical modifiers."), + Cannot_find_type_definition_file_for_0: diag(2688, ts.DiagnosticCategory.Error, "Cannot_find_type_definition_file_for_0_2688", "Cannot find type definition file for '{0}'."), + Cannot_extend_an_interface_0_Did_you_mean_implements: diag(2689, ts.DiagnosticCategory.Error, "Cannot_extend_an_interface_0_Did_you_mean_implements_2689", "Cannot extend an interface '{0}'. Did you mean 'implements'?"), + An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead: diag(2691, ts.DiagnosticCategory.Error, "An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead_2691", "An import path cannot end with a '{0}' extension. Consider importing '{1}' instead."), + _0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible: diag(2692, ts.DiagnosticCategory.Error, "_0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible_2692", "'{0}' is a primitive, but '{1}' is a wrapper object. Prefer using '{0}' when possible."), + _0_only_refers_to_a_type_but_is_being_used_as_a_value_here: diag(2693, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_2693", "'{0}' only refers to a type, but is being used as a value here."), + Namespace_0_has_no_exported_member_1: diag(2694, ts.DiagnosticCategory.Error, "Namespace_0_has_no_exported_member_1_2694", "Namespace '{0}' has no exported member '{1}'."), + Left_side_of_comma_operator_is_unused_and_has_no_side_effects: diag(2695, ts.DiagnosticCategory.Error, "Left_side_of_comma_operator_is_unused_and_has_no_side_effects_2695", "Left side of comma operator is unused and has no side effects.", /*reportsUnnecessary*/ true), + The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead: diag(2696, ts.DiagnosticCategory.Error, "The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead_2696", "The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead?"), + An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option: diag(2697, ts.DiagnosticCategory.Error, "An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_in_2697", "An async function or method must return a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your `--lib` option."), + Spread_types_may_only_be_created_from_object_types: diag(2698, ts.DiagnosticCategory.Error, "Spread_types_may_only_be_created_from_object_types_2698", "Spread types may only be created from object types."), + Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1: diag(2699, ts.DiagnosticCategory.Error, "Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1_2699", "Static property '{0}' conflicts with built-in property 'Function.{0}' of constructor function '{1}'."), + Rest_types_may_only_be_created_from_object_types: diag(2700, ts.DiagnosticCategory.Error, "Rest_types_may_only_be_created_from_object_types_2700", "Rest types may only be created from object types."), + The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access: diag(2701, ts.DiagnosticCategory.Error, "The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access_2701", "The target of an object rest assignment must be a variable or a property access."), + _0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here: diag(2702, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here_2702", "'{0}' only refers to a type, but is being used as a namespace here."), + The_operand_of_a_delete_operator_must_be_a_property_reference: diag(2703, ts.DiagnosticCategory.Error, "The_operand_of_a_delete_operator_must_be_a_property_reference_2703", "The operand of a delete operator must be a property reference."), + The_operand_of_a_delete_operator_cannot_be_a_read_only_property: diag(2704, ts.DiagnosticCategory.Error, "The_operand_of_a_delete_operator_cannot_be_a_read_only_property_2704", "The operand of a delete operator cannot be a read-only property."), + An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option: diag(2705, ts.DiagnosticCategory.Error, "An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_de_2705", "An async function or method in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your `--lib` option."), + Required_type_parameters_may_not_follow_optional_type_parameters: diag(2706, ts.DiagnosticCategory.Error, "Required_type_parameters_may_not_follow_optional_type_parameters_2706", "Required type parameters may not follow optional type parameters."), + Generic_type_0_requires_between_1_and_2_type_arguments: diag(2707, ts.DiagnosticCategory.Error, "Generic_type_0_requires_between_1_and_2_type_arguments_2707", "Generic type '{0}' requires between {1} and {2} type arguments."), + Cannot_use_namespace_0_as_a_value: diag(2708, ts.DiagnosticCategory.Error, "Cannot_use_namespace_0_as_a_value_2708", "Cannot use namespace '{0}' as a value."), + Cannot_use_namespace_0_as_a_type: diag(2709, ts.DiagnosticCategory.Error, "Cannot_use_namespace_0_as_a_type_2709", "Cannot use namespace '{0}' as a type."), + _0_are_specified_twice_The_attribute_named_0_will_be_overwritten: diag(2710, ts.DiagnosticCategory.Error, "_0_are_specified_twice_The_attribute_named_0_will_be_overwritten_2710", "'{0}' are specified twice. The attribute named '{0}' will be overwritten."), + A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option: diag(2711, ts.DiagnosticCategory.Error, "A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES20_2711", "A dynamic import call returns a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your `--lib` option."), + A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option: diag(2712, ts.DiagnosticCategory.Error, "A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declarat_2712", "A dynamic import call in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your `--lib` option."), + Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_property_1_in_0_with_0_1: diag(2713, ts.DiagnosticCategory.Error, "Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_p_2713", "Cannot access '{0}.{1}' because '{0}' is a type, but not a namespace. Did you mean to retrieve the type of the property '{1}' in '{0}' with '{0}[\"{1}\"]'?"), + The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context: diag(2714, ts.DiagnosticCategory.Error, "The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context_2714", "The expression of an export assignment must be an identifier or qualified name in an ambient context."), + Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor: diag(2715, ts.DiagnosticCategory.Error, "Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor_2715", "Abstract property '{0}' in class '{1}' cannot be accessed in the constructor."), + Type_parameter_0_has_a_circular_default: diag(2716, ts.DiagnosticCategory.Error, "Type_parameter_0_has_a_circular_default_2716", "Type parameter '{0}' has a circular default."), + Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_type_2: diag(2717, ts.DiagnosticCategory.Error, "Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_t_2717", "Subsequent property declarations must have the same type. Property '{0}' must be of type '{1}', but here has type '{2}'."), + Duplicate_declaration_0: diag(2718, ts.DiagnosticCategory.Error, "Duplicate_declaration_0_2718", "Duplicate declaration '{0}'."), + Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated: diag(2719, ts.DiagnosticCategory.Error, "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_2719", "Type '{0}' is not assignable to type '{1}'. Two different types with this name exist, but they are unrelated."), + Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass: diag(2720, ts.DiagnosticCategory.Error, "Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclas_2720", "Class '{0}' incorrectly implements class '{1}'. Did you mean to extend '{1}' and inherit its members as a subclass?"), + Cannot_invoke_an_object_which_is_possibly_null: diag(2721, ts.DiagnosticCategory.Error, "Cannot_invoke_an_object_which_is_possibly_null_2721", "Cannot invoke an object which is possibly 'null'."), + Cannot_invoke_an_object_which_is_possibly_undefined: diag(2722, ts.DiagnosticCategory.Error, "Cannot_invoke_an_object_which_is_possibly_undefined_2722", "Cannot invoke an object which is possibly 'undefined'."), + Cannot_invoke_an_object_which_is_possibly_null_or_undefined: diag(2723, ts.DiagnosticCategory.Error, "Cannot_invoke_an_object_which_is_possibly_null_or_undefined_2723", "Cannot invoke an object which is possibly 'null' or 'undefined'."), + Module_0_has_no_exported_member_1_Did_you_mean_2: diag(2724, ts.DiagnosticCategory.Error, "Module_0_has_no_exported_member_1_Did_you_mean_2_2724", "Module '{0}' has no exported member '{1}'. Did you mean '{2}'?"), + Class_name_cannot_be_Object_when_targeting_ES5_with_module_0: diag(2725, ts.DiagnosticCategory.Error, "Class_name_cannot_be_Object_when_targeting_ES5_with_module_0_2725", "Class name cannot be 'Object' when targeting ES5 with module {0}."), + Cannot_find_lib_definition_for_0: diag(2726, ts.DiagnosticCategory.Error, "Cannot_find_lib_definition_for_0_2726", "Cannot find lib definition for '{0}'."), + Cannot_find_lib_definition_for_0_Did_you_mean_1: diag(2727, ts.DiagnosticCategory.Error, "Cannot_find_lib_definition_for_0_Did_you_mean_1_2727", "Cannot find lib definition for '{0}'. Did you mean '{1}'?"), + _0_is_declared_here: diag(2728, ts.DiagnosticCategory.Message, "_0_is_declared_here_2728", "'{0}' is declared here."), + Property_0_is_used_before_its_initialization: diag(2729, ts.DiagnosticCategory.Error, "Property_0_is_used_before_its_initialization_2729", "Property '{0}' is used before its initialization."), + An_arrow_function_cannot_have_a_this_parameter: diag(2730, ts.DiagnosticCategory.Error, "An_arrow_function_cannot_have_a_this_parameter_2730", "An arrow function cannot have a 'this' parameter."), + Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_in_String: diag(2731, ts.DiagnosticCategory.Error, "Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_i_2731", "Implicit conversion of a 'symbol' to a 'string' will fail at runtime. Consider wrapping this expression in 'String(...)'."), + Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension: diag(2732, ts.DiagnosticCategory.Error, "Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension_2732", "Cannot find module '{0}'. Consider using '--resolveJsonModule' to import module with '.json' extension"), + It_is_highly_likely_that_you_are_missing_a_semicolon: diag(2734, ts.DiagnosticCategory.Error, "It_is_highly_likely_that_you_are_missing_a_semicolon_2734", "It is highly likely that you are missing a semicolon."), + Did_you_mean_for_0_to_be_constrained_to_type_new_args_Colon_any_1: diag(2735, ts.DiagnosticCategory.Error, "Did_you_mean_for_0_to_be_constrained_to_type_new_args_Colon_any_1_2735", "Did you mean for '{0}' to be constrained to type 'new (...args: any[]) => {1}'?"), + Operator_0_cannot_be_applied_to_type_1: diag(2736, ts.DiagnosticCategory.Error, "Operator_0_cannot_be_applied_to_type_1_2736", "Operator '{0}' cannot be applied to type '{1}'."), + BigInt_literals_are_not_available_when_targeting_lower_than_ESNext: diag(2737, ts.DiagnosticCategory.Error, "BigInt_literals_are_not_available_when_targeting_lower_than_ESNext_2737", "BigInt literals are not available when targeting lower than ESNext."), + An_outer_value_of_this_is_shadowed_by_this_container: diag(2738, ts.DiagnosticCategory.Message, "An_outer_value_of_this_is_shadowed_by_this_container_2738", "An outer value of 'this' is shadowed by this container."), + Type_0_is_missing_the_following_properties_from_type_1_Colon_2: diag(2739, ts.DiagnosticCategory.Error, "Type_0_is_missing_the_following_properties_from_type_1_Colon_2_2739", "Type '{0}' is missing the following properties from type '{1}': {2}"), + Type_0_is_missing_the_following_properties_from_type_1_Colon_2_and_3_more: diag(2740, ts.DiagnosticCategory.Error, "Type_0_is_missing_the_following_properties_from_type_1_Colon_2_and_3_more_2740", "Type '{0}' is missing the following properties from type '{1}': {2}, and {3} more."), + Property_0_is_missing_in_type_1_but_required_in_type_2: diag(2741, ts.DiagnosticCategory.Error, "Property_0_is_missing_in_type_1_but_required_in_type_2_2741", "Property '{0}' is missing in type '{1}' but required in type '{2}'."), + The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_annotation_is_necessary: diag(2742, ts.DiagnosticCategory.Error, "The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_a_2742", "The inferred type of '{0}' cannot be named without a reference to '{1}'. This is likely not portable. A type annotation is necessary."), + Import_declaration_0_is_using_private_name_1: diag(4000, ts.DiagnosticCategory.Error, "Import_declaration_0_is_using_private_name_1_4000", "Import declaration '{0}' is using private name '{1}'."), + Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: diag(4002, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", "Type parameter '{0}' of exported class has or is using private name '{1}'."), + Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: diag(4004, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", "Type parameter '{0}' of exported interface has or is using private name '{1}'."), + Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1: diag(4006, ts.DiagnosticCategory.Error, "Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4006", "Type parameter '{0}' of constructor signature from exported interface has or is using private name '{1}'."), + Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1: diag(4008, ts.DiagnosticCategory.Error, "Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4008", "Type parameter '{0}' of call signature from exported interface has or is using private name '{1}'."), + Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1: diag(4010, ts.DiagnosticCategory.Error, "Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4010", "Type parameter '{0}' of public static method from exported class has or is using private name '{1}'."), + Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1: diag(4012, ts.DiagnosticCategory.Error, "Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4012", "Type parameter '{0}' of public method from exported class has or is using private name '{1}'."), + Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1: diag(4014, ts.DiagnosticCategory.Error, "Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4014", "Type parameter '{0}' of method from exported interface has or is using private name '{1}'."), + Type_parameter_0_of_exported_function_has_or_is_using_private_name_1: diag(4016, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_function_has_or_is_using_private_name_1_4016", "Type parameter '{0}' of exported function has or is using private name '{1}'."), + Implements_clause_of_exported_class_0_has_or_is_using_private_name_1: diag(4019, ts.DiagnosticCategory.Error, "Implements_clause_of_exported_class_0_has_or_is_using_private_name_1_4019", "Implements clause of exported class '{0}' has or is using private name '{1}'."), + extends_clause_of_exported_class_0_has_or_is_using_private_name_1: diag(4020, ts.DiagnosticCategory.Error, "extends_clause_of_exported_class_0_has_or_is_using_private_name_1_4020", "'extends' clause of exported class '{0}' has or is using private name '{1}'."), + extends_clause_of_exported_interface_0_has_or_is_using_private_name_1: diag(4022, ts.DiagnosticCategory.Error, "extends_clause_of_exported_interface_0_has_or_is_using_private_name_1_4022", "'extends' clause of exported interface '{0}' has or is using private name '{1}'."), + Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4023, ts.DiagnosticCategory.Error, "Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4023", "Exported variable '{0}' has or is using name '{1}' from external module {2} but cannot be named."), + Exported_variable_0_has_or_is_using_name_1_from_private_module_2: diag(4024, ts.DiagnosticCategory.Error, "Exported_variable_0_has_or_is_using_name_1_from_private_module_2_4024", "Exported variable '{0}' has or is using name '{1}' from private module '{2}'."), + Exported_variable_0_has_or_is_using_private_name_1: diag(4025, ts.DiagnosticCategory.Error, "Exported_variable_0_has_or_is_using_private_name_1_4025", "Exported variable '{0}' has or is using private name '{1}'."), + Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4026, ts.DiagnosticCategory.Error, "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot__4026", "Public static property '{0}' of exported class has or is using name '{1}' from external module {2} but cannot be named."), + Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4027, ts.DiagnosticCategory.Error, "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4027", "Public static property '{0}' of exported class has or is using name '{1}' from private module '{2}'."), + Public_static_property_0_of_exported_class_has_or_is_using_private_name_1: diag(4028, ts.DiagnosticCategory.Error, "Public_static_property_0_of_exported_class_has_or_is_using_private_name_1_4028", "Public static property '{0}' of exported class has or is using private name '{1}'."), + Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4029, ts.DiagnosticCategory.Error, "Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_name_4029", "Public property '{0}' of exported class has or is using name '{1}' from external module {2} but cannot be named."), + Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4030, ts.DiagnosticCategory.Error, "Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4030", "Public property '{0}' of exported class has or is using name '{1}' from private module '{2}'."), + Public_property_0_of_exported_class_has_or_is_using_private_name_1: diag(4031, ts.DiagnosticCategory.Error, "Public_property_0_of_exported_class_has_or_is_using_private_name_1_4031", "Public property '{0}' of exported class has or is using private name '{1}'."), + Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4032, ts.DiagnosticCategory.Error, "Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4032", "Property '{0}' of exported interface has or is using name '{1}' from private module '{2}'."), + Property_0_of_exported_interface_has_or_is_using_private_name_1: diag(4033, ts.DiagnosticCategory.Error, "Property_0_of_exported_interface_has_or_is_using_private_name_1_4033", "Property '{0}' of exported interface has or is using private name '{1}'."), + Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4034, ts.DiagnosticCategory.Error, "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_name_1_from_private_mod_4034", "Parameter type of public static setter '{0}' from exported class has or is using name '{1}' from private module '{2}'."), + Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1: diag(4035, ts.DiagnosticCategory.Error, "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1_4035", "Parameter type of public static setter '{0}' from exported class has or is using private name '{1}'."), + Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4036, ts.DiagnosticCategory.Error, "Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2_4036", "Parameter type of public setter '{0}' from exported class has or is using name '{1}' from private module '{2}'."), + Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_private_name_1: diag(4037, ts.DiagnosticCategory.Error, "Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_private_name_1_4037", "Parameter type of public setter '{0}' from exported class has or is using private name '{1}'."), + Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4038, ts.DiagnosticCategory.Error, "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_external_modul_4038", "Return type of public static getter '{0}' from exported class has or is using name '{1}' from external module {2} but cannot be named."), + Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4039, ts.DiagnosticCategory.Error, "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_4039", "Return type of public static getter '{0}' from exported class has or is using name '{1}' from private module '{2}'."), + Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_private_name_1: diag(4040, ts.DiagnosticCategory.Error, "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_private_name_1_4040", "Return type of public static getter '{0}' from exported class has or is using private name '{1}'."), + Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4041, ts.DiagnosticCategory.Error, "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_4041", "Return type of public getter '{0}' from exported class has or is using name '{1}' from external module {2} but cannot be named."), + Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4042, ts.DiagnosticCategory.Error, "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2_4042", "Return type of public getter '{0}' from exported class has or is using name '{1}' from private module '{2}'."), + Return_type_of_public_getter_0_from_exported_class_has_or_is_using_private_name_1: diag(4043, ts.DiagnosticCategory.Error, "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_private_name_1_4043", "Return type of public getter '{0}' from exported class has or is using private name '{1}'."), + Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1: diag(4044, ts.DiagnosticCategory.Error, "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_mod_4044", "Return type of constructor signature from exported interface has or is using name '{0}' from private module '{1}'."), + Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0: diag(4045, ts.DiagnosticCategory.Error, "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0_4045", "Return type of constructor signature from exported interface has or is using private name '{0}'."), + Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1: diag(4046, ts.DiagnosticCategory.Error, "Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4046", "Return type of call signature from exported interface has or is using name '{0}' from private module '{1}'."), + Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0: diag(4047, ts.DiagnosticCategory.Error, "Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0_4047", "Return type of call signature from exported interface has or is using private name '{0}'."), + Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1: diag(4048, ts.DiagnosticCategory.Error, "Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4048", "Return type of index signature from exported interface has or is using name '{0}' from private module '{1}'."), + Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0: diag(4049, ts.DiagnosticCategory.Error, "Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0_4049", "Return type of index signature from exported interface has or is using private name '{0}'."), + Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: diag(4050, ts.DiagnosticCategory.Error, "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module__4050", "Return type of public static method from exported class has or is using name '{0}' from external module {1} but cannot be named."), + Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1: diag(4051, ts.DiagnosticCategory.Error, "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4051", "Return type of public static method from exported class has or is using name '{0}' from private module '{1}'."), + Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0: diag(4052, ts.DiagnosticCategory.Error, "Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0_4052", "Return type of public static method from exported class has or is using private name '{0}'."), + Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: diag(4053, ts.DiagnosticCategory.Error, "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_c_4053", "Return type of public method from exported class has or is using name '{0}' from external module {1} but cannot be named."), + Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1: diag(4054, ts.DiagnosticCategory.Error, "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4054", "Return type of public method from exported class has or is using name '{0}' from private module '{1}'."), + Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0: diag(4055, ts.DiagnosticCategory.Error, "Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0_4055", "Return type of public method from exported class has or is using private name '{0}'."), + Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1: diag(4056, ts.DiagnosticCategory.Error, "Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4056", "Return type of method from exported interface has or is using name '{0}' from private module '{1}'."), + Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0: diag(4057, ts.DiagnosticCategory.Error, "Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0_4057", "Return type of method from exported interface has or is using private name '{0}'."), + Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: diag(4058, ts.DiagnosticCategory.Error, "Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named_4058", "Return type of exported function has or is using name '{0}' from external module {1} but cannot be named."), + Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1: diag(4059, ts.DiagnosticCategory.Error, "Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1_4059", "Return type of exported function has or is using name '{0}' from private module '{1}'."), + Return_type_of_exported_function_has_or_is_using_private_name_0: diag(4060, ts.DiagnosticCategory.Error, "Return_type_of_exported_function_has_or_is_using_private_name_0_4060", "Return type of exported function has or is using private name '{0}'."), + Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4061, ts.DiagnosticCategory.Error, "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_can_4061", "Parameter '{0}' of constructor from exported class has or is using name '{1}' from external module {2} but cannot be named."), + Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4062, ts.DiagnosticCategory.Error, "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2_4062", "Parameter '{0}' of constructor from exported class has or is using name '{1}' from private module '{2}'."), + Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1: diag(4063, ts.DiagnosticCategory.Error, "Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1_4063", "Parameter '{0}' of constructor from exported class has or is using private name '{1}'."), + Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4064, ts.DiagnosticCategory.Error, "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_mod_4064", "Parameter '{0}' of constructor signature from exported interface has or is using name '{1}' from private module '{2}'."), + Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1: diag(4065, ts.DiagnosticCategory.Error, "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4065", "Parameter '{0}' of constructor signature from exported interface has or is using private name '{1}'."), + Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4066, ts.DiagnosticCategory.Error, "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4066", "Parameter '{0}' of call signature from exported interface has or is using name '{1}' from private module '{2}'."), + Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1: diag(4067, ts.DiagnosticCategory.Error, "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4067", "Parameter '{0}' of call signature from exported interface has or is using private name '{1}'."), + Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4068, ts.DiagnosticCategory.Error, "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module__4068", "Parameter '{0}' of public static method from exported class has or is using name '{1}' from external module {2} but cannot be named."), + Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4069, ts.DiagnosticCategory.Error, "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4069", "Parameter '{0}' of public static method from exported class has or is using name '{1}' from private module '{2}'."), + Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1: diag(4070, ts.DiagnosticCategory.Error, "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4070", "Parameter '{0}' of public static method from exported class has or is using private name '{1}'."), + Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4071, ts.DiagnosticCategory.Error, "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_c_4071", "Parameter '{0}' of public method from exported class has or is using name '{1}' from external module {2} but cannot be named."), + Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4072, ts.DiagnosticCategory.Error, "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4072", "Parameter '{0}' of public method from exported class has or is using name '{1}' from private module '{2}'."), + Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1: diag(4073, ts.DiagnosticCategory.Error, "Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4073", "Parameter '{0}' of public method from exported class has or is using private name '{1}'."), + Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4074, ts.DiagnosticCategory.Error, "Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4074", "Parameter '{0}' of method from exported interface has or is using name '{1}' from private module '{2}'."), + Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1: diag(4075, ts.DiagnosticCategory.Error, "Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4075", "Parameter '{0}' of method from exported interface has or is using private name '{1}'."), + Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4076, ts.DiagnosticCategory.Error, "Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4076", "Parameter '{0}' of exported function has or is using name '{1}' from external module {2} but cannot be named."), + Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2: diag(4077, ts.DiagnosticCategory.Error, "Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2_4077", "Parameter '{0}' of exported function has or is using name '{1}' from private module '{2}'."), + Parameter_0_of_exported_function_has_or_is_using_private_name_1: diag(4078, ts.DiagnosticCategory.Error, "Parameter_0_of_exported_function_has_or_is_using_private_name_1_4078", "Parameter '{0}' of exported function has or is using private name '{1}'."), + Exported_type_alias_0_has_or_is_using_private_name_1: diag(4081, ts.DiagnosticCategory.Error, "Exported_type_alias_0_has_or_is_using_private_name_1_4081", "Exported type alias '{0}' has or is using private name '{1}'."), + Default_export_of_the_module_has_or_is_using_private_name_0: diag(4082, ts.DiagnosticCategory.Error, "Default_export_of_the_module_has_or_is_using_private_name_0_4082", "Default export of the module has or is using private name '{0}'."), + Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1: diag(4083, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1_4083", "Type parameter '{0}' of exported type alias has or is using private name '{1}'."), + Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict: diag(4090, ts.DiagnosticCategory.Error, "Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_librar_4090", "Conflicting definitions for '{0}' found at '{1}' and '{2}'. Consider installing a specific version of this library to resolve the conflict."), + Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4091, ts.DiagnosticCategory.Error, "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4091", "Parameter '{0}' of index signature from exported interface has or is using name '{1}' from private module '{2}'."), + Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1: diag(4092, ts.DiagnosticCategory.Error, "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1_4092", "Parameter '{0}' of index signature from exported interface has or is using private name '{1}'."), + Property_0_of_exported_class_expression_may_not_be_private_or_protected: diag(4094, ts.DiagnosticCategory.Error, "Property_0_of_exported_class_expression_may_not_be_private_or_protected_4094", "Property '{0}' of exported class expression may not be private or protected."), + Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4095, ts.DiagnosticCategory.Error, "Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_4095", "Public static method '{0}' of exported class has or is using name '{1}' from external module {2} but cannot be named."), + Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4096, ts.DiagnosticCategory.Error, "Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4096", "Public static method '{0}' of exported class has or is using name '{1}' from private module '{2}'."), + Public_static_method_0_of_exported_class_has_or_is_using_private_name_1: diag(4097, ts.DiagnosticCategory.Error, "Public_static_method_0_of_exported_class_has_or_is_using_private_name_1_4097", "Public static method '{0}' of exported class has or is using private name '{1}'."), + Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4098, ts.DiagnosticCategory.Error, "Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4098", "Public method '{0}' of exported class has or is using name '{1}' from external module {2} but cannot be named."), + Public_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4099, ts.DiagnosticCategory.Error, "Public_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4099", "Public method '{0}' of exported class has or is using name '{1}' from private module '{2}'."), + Public_method_0_of_exported_class_has_or_is_using_private_name_1: diag(4100, ts.DiagnosticCategory.Error, "Public_method_0_of_exported_class_has_or_is_using_private_name_1_4100", "Public method '{0}' of exported class has or is using private name '{1}'."), + Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4101, ts.DiagnosticCategory.Error, "Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4101", "Method '{0}' of exported interface has or is using name '{1}' from private module '{2}'."), + Method_0_of_exported_interface_has_or_is_using_private_name_1: diag(4102, ts.DiagnosticCategory.Error, "Method_0_of_exported_interface_has_or_is_using_private_name_1_4102", "Method '{0}' of exported interface has or is using private name '{1}'."), + The_current_host_does_not_support_the_0_option: diag(5001, ts.DiagnosticCategory.Error, "The_current_host_does_not_support_the_0_option_5001", "The current host does not support the '{0}' option."), + Cannot_find_the_common_subdirectory_path_for_the_input_files: diag(5009, ts.DiagnosticCategory.Error, "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009", "Cannot find the common subdirectory path for the input files."), + File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: diag(5010, ts.DiagnosticCategory.Error, "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010", "File specification cannot end in a recursive directory wildcard ('**'): '{0}'."), + Cannot_read_file_0_Colon_1: diag(5012, ts.DiagnosticCategory.Error, "Cannot_read_file_0_Colon_1_5012", "Cannot read file '{0}': {1}."), + Failed_to_parse_file_0_Colon_1: diag(5014, ts.DiagnosticCategory.Error, "Failed_to_parse_file_0_Colon_1_5014", "Failed to parse file '{0}': {1}."), + Unknown_compiler_option_0: diag(5023, ts.DiagnosticCategory.Error, "Unknown_compiler_option_0_5023", "Unknown compiler option '{0}'."), + Compiler_option_0_requires_a_value_of_type_1: diag(5024, ts.DiagnosticCategory.Error, "Compiler_option_0_requires_a_value_of_type_1_5024", "Compiler option '{0}' requires a value of type {1}."), + Could_not_write_file_0_Colon_1: diag(5033, ts.DiagnosticCategory.Error, "Could_not_write_file_0_Colon_1_5033", "Could not write file '{0}': {1}."), + Option_project_cannot_be_mixed_with_source_files_on_a_command_line: diag(5042, ts.DiagnosticCategory.Error, "Option_project_cannot_be_mixed_with_source_files_on_a_command_line_5042", "Option 'project' cannot be mixed with source files on a command line."), + Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher: diag(5047, ts.DiagnosticCategory.Error, "Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES_5047", "Option 'isolatedModules' can only be used when either option '--module' is provided or option 'target' is 'ES2015' or higher."), + Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided: diag(5051, ts.DiagnosticCategory.Error, "Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided_5051", "Option '{0} can only be used when either option '--inlineSourceMap' or option '--sourceMap' is provided."), + Option_0_cannot_be_specified_without_specifying_option_1: diag(5052, ts.DiagnosticCategory.Error, "Option_0_cannot_be_specified_without_specifying_option_1_5052", "Option '{0}' cannot be specified without specifying option '{1}'."), + Option_0_cannot_be_specified_with_option_1: diag(5053, ts.DiagnosticCategory.Error, "Option_0_cannot_be_specified_with_option_1_5053", "Option '{0}' cannot be specified with option '{1}'."), + A_tsconfig_json_file_is_already_defined_at_Colon_0: diag(5054, ts.DiagnosticCategory.Error, "A_tsconfig_json_file_is_already_defined_at_Colon_0_5054", "A 'tsconfig.json' file is already defined at: '{0}'."), + Cannot_write_file_0_because_it_would_overwrite_input_file: diag(5055, ts.DiagnosticCategory.Error, "Cannot_write_file_0_because_it_would_overwrite_input_file_5055", "Cannot write file '{0}' because it would overwrite input file."), + Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files: diag(5056, ts.DiagnosticCategory.Error, "Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files_5056", "Cannot write file '{0}' because it would be overwritten by multiple input files."), + Cannot_find_a_tsconfig_json_file_at_the_specified_directory_Colon_0: diag(5057, ts.DiagnosticCategory.Error, "Cannot_find_a_tsconfig_json_file_at_the_specified_directory_Colon_0_5057", "Cannot find a tsconfig.json file at the specified directory: '{0}'."), + The_specified_path_does_not_exist_Colon_0: diag(5058, ts.DiagnosticCategory.Error, "The_specified_path_does_not_exist_Colon_0_5058", "The specified path does not exist: '{0}'."), + Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier: diag(5059, ts.DiagnosticCategory.Error, "Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier_5059", "Invalid value for '--reactNamespace'. '{0}' is not a valid identifier."), + Option_paths_cannot_be_used_without_specifying_baseUrl_option: diag(5060, ts.DiagnosticCategory.Error, "Option_paths_cannot_be_used_without_specifying_baseUrl_option_5060", "Option 'paths' cannot be used without specifying '--baseUrl' option."), + Pattern_0_can_have_at_most_one_Asterisk_character: diag(5061, ts.DiagnosticCategory.Error, "Pattern_0_can_have_at_most_one_Asterisk_character_5061", "Pattern '{0}' can have at most one '*' character."), + Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character: diag(5062, ts.DiagnosticCategory.Error, "Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character_5062", "Substitution '{0}' in pattern '{1}' in can have at most one '*' character."), + Substitutions_for_pattern_0_should_be_an_array: diag(5063, ts.DiagnosticCategory.Error, "Substitutions_for_pattern_0_should_be_an_array_5063", "Substitutions for pattern '{0}' should be an array."), + Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2: diag(5064, ts.DiagnosticCategory.Error, "Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2_5064", "Substitution '{0}' for pattern '{1}' has incorrect type, expected 'string', got '{2}'."), + File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: diag(5065, ts.DiagnosticCategory.Error, "File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildca_5065", "File specification cannot contain a parent directory ('..') that appears after a recursive directory wildcard ('**'): '{0}'."), + Substitutions_for_pattern_0_shouldn_t_be_an_empty_array: diag(5066, ts.DiagnosticCategory.Error, "Substitutions_for_pattern_0_shouldn_t_be_an_empty_array_5066", "Substitutions for pattern '{0}' shouldn't be an empty array."), + Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name: diag(5067, ts.DiagnosticCategory.Error, "Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name_5067", "Invalid value for 'jsxFactory'. '{0}' is not a valid identifier or qualified-name."), + Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig: diag(5068, ts.DiagnosticCategory.Error, "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068", "Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig."), + Option_0_cannot_be_specified_without_specifying_option_1_or_option_2: diag(5069, ts.DiagnosticCategory.Error, "Option_0_cannot_be_specified_without_specifying_option_1_or_option_2_5069", "Option '{0}' cannot be specified without specifying option '{1}' or option '{2}'."), + Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy: diag(5070, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070", "Option '--resolveJsonModule' cannot be specified without 'node' module resolution strategy."), + Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_esNext: diag(5071, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_5071", "Option '--resolveJsonModule' can only be specified when module code generation is 'commonjs', 'amd', 'es2015' or 'esNext'."), + Unknown_build_option_0: diag(5072, ts.DiagnosticCategory.Error, "Unknown_build_option_0_5072", "Unknown build option '{0}'."), + Build_option_0_requires_a_value_of_type_1: diag(5073, ts.DiagnosticCategory.Error, "Build_option_0_requires_a_value_of_type_1_5073", "Build option '{0}' requires a value of type {1}."), + Generates_a_sourcemap_for_each_corresponding_d_ts_file: diag(6000, ts.DiagnosticCategory.Message, "Generates_a_sourcemap_for_each_corresponding_d_ts_file_6000", "Generates a sourcemap for each corresponding '.d.ts' file."), + Concatenate_and_emit_output_to_single_file: diag(6001, ts.DiagnosticCategory.Message, "Concatenate_and_emit_output_to_single_file_6001", "Concatenate and emit output to single file."), + Generates_corresponding_d_ts_file: diag(6002, ts.DiagnosticCategory.Message, "Generates_corresponding_d_ts_file_6002", "Generates corresponding '.d.ts' file."), + Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations: diag(6003, ts.DiagnosticCategory.Message, "Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations_6003", "Specify the location where debugger should locate map files instead of generated locations."), + Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations: diag(6004, ts.DiagnosticCategory.Message, "Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations_6004", "Specify the location where debugger should locate TypeScript files instead of source locations."), + Watch_input_files: diag(6005, ts.DiagnosticCategory.Message, "Watch_input_files_6005", "Watch input files."), + Redirect_output_structure_to_the_directory: diag(6006, ts.DiagnosticCategory.Message, "Redirect_output_structure_to_the_directory_6006", "Redirect output structure to the directory."), + Do_not_erase_const_enum_declarations_in_generated_code: diag(6007, ts.DiagnosticCategory.Message, "Do_not_erase_const_enum_declarations_in_generated_code_6007", "Do not erase const enum declarations in generated code."), + Do_not_emit_outputs_if_any_errors_were_reported: diag(6008, ts.DiagnosticCategory.Message, "Do_not_emit_outputs_if_any_errors_were_reported_6008", "Do not emit outputs if any errors were reported."), + Do_not_emit_comments_to_output: diag(6009, ts.DiagnosticCategory.Message, "Do_not_emit_comments_to_output_6009", "Do not emit comments to output."), + Do_not_emit_outputs: diag(6010, ts.DiagnosticCategory.Message, "Do_not_emit_outputs_6010", "Do not emit outputs."), + Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking: diag(6011, ts.DiagnosticCategory.Message, "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011", "Allow default imports from modules with no default export. This does not affect code emit, just typechecking."), + Skip_type_checking_of_declaration_files: diag(6012, ts.DiagnosticCategory.Message, "Skip_type_checking_of_declaration_files_6012", "Skip type checking of declaration files."), + Do_not_resolve_the_real_path_of_symlinks: diag(6013, ts.DiagnosticCategory.Message, "Do_not_resolve_the_real_path_of_symlinks_6013", "Do not resolve the real path of symlinks."), + Only_emit_d_ts_declaration_files: diag(6014, ts.DiagnosticCategory.Message, "Only_emit_d_ts_declaration_files_6014", "Only emit '.d.ts' declaration files."), + Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_or_ESNEXT: diag(6015, ts.DiagnosticCategory.Message, "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_or_ESNEXT_6015", "Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'."), + Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext: diag(6016, ts.DiagnosticCategory.Message, "Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext_6016", "Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'."), + Print_this_message: diag(6017, ts.DiagnosticCategory.Message, "Print_this_message_6017", "Print this message."), + Print_the_compiler_s_version: diag(6019, ts.DiagnosticCategory.Message, "Print_the_compiler_s_version_6019", "Print the compiler's version."), + Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json: diag(6020, ts.DiagnosticCategory.Message, "Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json_6020", "Compile the project given the path to its configuration file, or to a folder with a 'tsconfig.json'."), + Syntax_Colon_0: diag(6023, ts.DiagnosticCategory.Message, "Syntax_Colon_0_6023", "Syntax: {0}"), + options: diag(6024, ts.DiagnosticCategory.Message, "options_6024", "options"), + file: diag(6025, ts.DiagnosticCategory.Message, "file_6025", "file"), + Examples_Colon_0: diag(6026, ts.DiagnosticCategory.Message, "Examples_Colon_0_6026", "Examples: {0}"), + Options_Colon: diag(6027, ts.DiagnosticCategory.Message, "Options_Colon_6027", "Options:"), + Version_0: diag(6029, ts.DiagnosticCategory.Message, "Version_0_6029", "Version {0}"), + Insert_command_line_options_and_files_from_a_file: diag(6030, ts.DiagnosticCategory.Message, "Insert_command_line_options_and_files_from_a_file_6030", "Insert command line options and files from a file."), + Starting_compilation_in_watch_mode: diag(6031, ts.DiagnosticCategory.Message, "Starting_compilation_in_watch_mode_6031", "Starting compilation in watch mode..."), + File_change_detected_Starting_incremental_compilation: diag(6032, ts.DiagnosticCategory.Message, "File_change_detected_Starting_incremental_compilation_6032", "File change detected. Starting incremental compilation..."), + KIND: diag(6034, ts.DiagnosticCategory.Message, "KIND_6034", "KIND"), + FILE: diag(6035, ts.DiagnosticCategory.Message, "FILE_6035", "FILE"), + VERSION: diag(6036, ts.DiagnosticCategory.Message, "VERSION_6036", "VERSION"), + LOCATION: diag(6037, ts.DiagnosticCategory.Message, "LOCATION_6037", "LOCATION"), + DIRECTORY: diag(6038, ts.DiagnosticCategory.Message, "DIRECTORY_6038", "DIRECTORY"), + STRATEGY: diag(6039, ts.DiagnosticCategory.Message, "STRATEGY_6039", "STRATEGY"), + FILE_OR_DIRECTORY: diag(6040, ts.DiagnosticCategory.Message, "FILE_OR_DIRECTORY_6040", "FILE OR DIRECTORY"), + Generates_corresponding_map_file: diag(6043, ts.DiagnosticCategory.Message, "Generates_corresponding_map_file_6043", "Generates corresponding '.map' file."), + Compiler_option_0_expects_an_argument: diag(6044, ts.DiagnosticCategory.Error, "Compiler_option_0_expects_an_argument_6044", "Compiler option '{0}' expects an argument."), + Unterminated_quoted_string_in_response_file_0: diag(6045, ts.DiagnosticCategory.Error, "Unterminated_quoted_string_in_response_file_0_6045", "Unterminated quoted string in response file '{0}'."), + Argument_for_0_option_must_be_Colon_1: diag(6046, ts.DiagnosticCategory.Error, "Argument_for_0_option_must_be_Colon_1_6046", "Argument for '{0}' option must be: {1}."), + Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1: diag(6048, ts.DiagnosticCategory.Error, "Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1_6048", "Locale must be of the form or -. For example '{0}' or '{1}'."), + Unsupported_locale_0: diag(6049, ts.DiagnosticCategory.Error, "Unsupported_locale_0_6049", "Unsupported locale '{0}'."), + Unable_to_open_file_0: diag(6050, ts.DiagnosticCategory.Error, "Unable_to_open_file_0_6050", "Unable to open file '{0}'."), + Corrupted_locale_file_0: diag(6051, ts.DiagnosticCategory.Error, "Corrupted_locale_file_0_6051", "Corrupted locale file {0}."), + Raise_error_on_expressions_and_declarations_with_an_implied_any_type: diag(6052, ts.DiagnosticCategory.Message, "Raise_error_on_expressions_and_declarations_with_an_implied_any_type_6052", "Raise error on expressions and declarations with an implied 'any' type."), + File_0_not_found: diag(6053, ts.DiagnosticCategory.Error, "File_0_not_found_6053", "File '{0}' not found."), + File_0_has_unsupported_extension_The_only_supported_extensions_are_1: diag(6054, ts.DiagnosticCategory.Error, "File_0_has_unsupported_extension_The_only_supported_extensions_are_1_6054", "File '{0}' has unsupported extension. The only supported extensions are {1}."), + Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures: diag(6055, ts.DiagnosticCategory.Message, "Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures_6055", "Suppress noImplicitAny errors for indexing objects lacking index signatures."), + Do_not_emit_declarations_for_code_that_has_an_internal_annotation: diag(6056, ts.DiagnosticCategory.Message, "Do_not_emit_declarations_for_code_that_has_an_internal_annotation_6056", "Do not emit declarations for code that has an '@internal' annotation."), + Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir: diag(6058, ts.DiagnosticCategory.Message, "Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir_6058", "Specify the root directory of input files. Use to control the output directory structure with --outDir."), + File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files: diag(6059, ts.DiagnosticCategory.Error, "File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files_6059", "File '{0}' is not under 'rootDir' '{1}'. 'rootDir' is expected to contain all source files."), + Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix: diag(6060, ts.DiagnosticCategory.Message, "Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix_6060", "Specify the end of line sequence to be used when emitting files: 'CRLF' (dos) or 'LF' (unix)."), + NEWLINE: diag(6061, ts.DiagnosticCategory.Message, "NEWLINE_6061", "NEWLINE"), + Option_0_can_only_be_specified_in_tsconfig_json_file: diag(6064, ts.DiagnosticCategory.Error, "Option_0_can_only_be_specified_in_tsconfig_json_file_6064", "Option '{0}' can only be specified in 'tsconfig.json' file."), + Enables_experimental_support_for_ES7_decorators: diag(6065, ts.DiagnosticCategory.Message, "Enables_experimental_support_for_ES7_decorators_6065", "Enables experimental support for ES7 decorators."), + Enables_experimental_support_for_emitting_type_metadata_for_decorators: diag(6066, ts.DiagnosticCategory.Message, "Enables_experimental_support_for_emitting_type_metadata_for_decorators_6066", "Enables experimental support for emitting type metadata for decorators."), + Enables_experimental_support_for_ES7_async_functions: diag(6068, ts.DiagnosticCategory.Message, "Enables_experimental_support_for_ES7_async_functions_6068", "Enables experimental support for ES7 async functions."), + Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6: diag(6069, ts.DiagnosticCategory.Message, "Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6_6069", "Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6)."), + Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file: diag(6070, ts.DiagnosticCategory.Message, "Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file_6070", "Initializes a TypeScript project and creates a tsconfig.json file."), + Successfully_created_a_tsconfig_json_file: diag(6071, ts.DiagnosticCategory.Message, "Successfully_created_a_tsconfig_json_file_6071", "Successfully created a tsconfig.json file."), + Suppress_excess_property_checks_for_object_literals: diag(6072, ts.DiagnosticCategory.Message, "Suppress_excess_property_checks_for_object_literals_6072", "Suppress excess property checks for object literals."), + Stylize_errors_and_messages_using_color_and_context_experimental: diag(6073, ts.DiagnosticCategory.Message, "Stylize_errors_and_messages_using_color_and_context_experimental_6073", "Stylize errors and messages using color and context (experimental)."), + Do_not_report_errors_on_unused_labels: diag(6074, ts.DiagnosticCategory.Message, "Do_not_report_errors_on_unused_labels_6074", "Do not report errors on unused labels."), + Report_error_when_not_all_code_paths_in_function_return_a_value: diag(6075, ts.DiagnosticCategory.Message, "Report_error_when_not_all_code_paths_in_function_return_a_value_6075", "Report error when not all code paths in function return a value."), + Report_errors_for_fallthrough_cases_in_switch_statement: diag(6076, ts.DiagnosticCategory.Message, "Report_errors_for_fallthrough_cases_in_switch_statement_6076", "Report errors for fallthrough cases in switch statement."), + Do_not_report_errors_on_unreachable_code: diag(6077, ts.DiagnosticCategory.Message, "Do_not_report_errors_on_unreachable_code_6077", "Do not report errors on unreachable code."), + Disallow_inconsistently_cased_references_to_the_same_file: diag(6078, ts.DiagnosticCategory.Message, "Disallow_inconsistently_cased_references_to_the_same_file_6078", "Disallow inconsistently-cased references to the same file."), + Specify_library_files_to_be_included_in_the_compilation: diag(6079, ts.DiagnosticCategory.Message, "Specify_library_files_to_be_included_in_the_compilation_6079", "Specify library files to be included in the compilation."), + Specify_JSX_code_generation_Colon_preserve_react_native_or_react: diag(6080, ts.DiagnosticCategory.Message, "Specify_JSX_code_generation_Colon_preserve_react_native_or_react_6080", "Specify JSX code generation: 'preserve', 'react-native', or 'react'."), + File_0_has_an_unsupported_extension_so_skipping_it: diag(6081, ts.DiagnosticCategory.Message, "File_0_has_an_unsupported_extension_so_skipping_it_6081", "File '{0}' has an unsupported extension, so skipping it."), + Only_amd_and_system_modules_are_supported_alongside_0: diag(6082, ts.DiagnosticCategory.Error, "Only_amd_and_system_modules_are_supported_alongside_0_6082", "Only 'amd' and 'system' modules are supported alongside --{0}."), + Base_directory_to_resolve_non_absolute_module_names: diag(6083, ts.DiagnosticCategory.Message, "Base_directory_to_resolve_non_absolute_module_names_6083", "Base directory to resolve non-absolute module names."), + Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react_JSX_emit: diag(6084, ts.DiagnosticCategory.Message, "Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react__6084", "[Deprecated] Use '--jsxFactory' instead. Specify the object invoked for createElement when targeting 'react' JSX emit"), + Enable_tracing_of_the_name_resolution_process: diag(6085, ts.DiagnosticCategory.Message, "Enable_tracing_of_the_name_resolution_process_6085", "Enable tracing of the name resolution process."), + Resolving_module_0_from_1: diag(6086, ts.DiagnosticCategory.Message, "Resolving_module_0_from_1_6086", "======== Resolving module '{0}' from '{1}'. ========"), + Explicitly_specified_module_resolution_kind_Colon_0: diag(6087, ts.DiagnosticCategory.Message, "Explicitly_specified_module_resolution_kind_Colon_0_6087", "Explicitly specified module resolution kind: '{0}'."), + Module_resolution_kind_is_not_specified_using_0: diag(6088, ts.DiagnosticCategory.Message, "Module_resolution_kind_is_not_specified_using_0_6088", "Module resolution kind is not specified, using '{0}'."), + Module_name_0_was_successfully_resolved_to_1: diag(6089, ts.DiagnosticCategory.Message, "Module_name_0_was_successfully_resolved_to_1_6089", "======== Module name '{0}' was successfully resolved to '{1}'. ========"), + Module_name_0_was_not_resolved: diag(6090, ts.DiagnosticCategory.Message, "Module_name_0_was_not_resolved_6090", "======== Module name '{0}' was not resolved. ========"), + paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0: diag(6091, ts.DiagnosticCategory.Message, "paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0_6091", "'paths' option is specified, looking for a pattern to match module name '{0}'."), + Module_name_0_matched_pattern_1: diag(6092, ts.DiagnosticCategory.Message, "Module_name_0_matched_pattern_1_6092", "Module name '{0}', matched pattern '{1}'."), + Trying_substitution_0_candidate_module_location_Colon_1: diag(6093, ts.DiagnosticCategory.Message, "Trying_substitution_0_candidate_module_location_Colon_1_6093", "Trying substitution '{0}', candidate module location: '{1}'."), + Resolving_module_name_0_relative_to_base_url_1_2: diag(6094, ts.DiagnosticCategory.Message, "Resolving_module_name_0_relative_to_base_url_1_2_6094", "Resolving module name '{0}' relative to base url '{1}' - '{2}'."), + Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1: diag(6095, ts.DiagnosticCategory.Message, "Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1_6095", "Loading module as file / folder, candidate module location '{0}', target file type '{1}'."), + File_0_does_not_exist: diag(6096, ts.DiagnosticCategory.Message, "File_0_does_not_exist_6096", "File '{0}' does not exist."), + File_0_exist_use_it_as_a_name_resolution_result: diag(6097, ts.DiagnosticCategory.Message, "File_0_exist_use_it_as_a_name_resolution_result_6097", "File '{0}' exist - use it as a name resolution result."), + Loading_module_0_from_node_modules_folder_target_file_type_1: diag(6098, ts.DiagnosticCategory.Message, "Loading_module_0_from_node_modules_folder_target_file_type_1_6098", "Loading module '{0}' from 'node_modules' folder, target file type '{1}'."), + Found_package_json_at_0: diag(6099, ts.DiagnosticCategory.Message, "Found_package_json_at_0_6099", "Found 'package.json' at '{0}'."), + package_json_does_not_have_a_0_field: diag(6100, ts.DiagnosticCategory.Message, "package_json_does_not_have_a_0_field_6100", "'package.json' does not have a '{0}' field."), + package_json_has_0_field_1_that_references_2: diag(6101, ts.DiagnosticCategory.Message, "package_json_has_0_field_1_that_references_2_6101", "'package.json' has '{0}' field '{1}' that references '{2}'."), + Allow_javascript_files_to_be_compiled: diag(6102, ts.DiagnosticCategory.Message, "Allow_javascript_files_to_be_compiled_6102", "Allow javascript files to be compiled."), + Option_0_should_have_array_of_strings_as_a_value: diag(6103, ts.DiagnosticCategory.Error, "Option_0_should_have_array_of_strings_as_a_value_6103", "Option '{0}' should have array of strings as a value."), + Checking_if_0_is_the_longest_matching_prefix_for_1_2: diag(6104, ts.DiagnosticCategory.Message, "Checking_if_0_is_the_longest_matching_prefix_for_1_2_6104", "Checking if '{0}' is the longest matching prefix for '{1}' - '{2}'."), + Expected_type_of_0_field_in_package_json_to_be_1_got_2: diag(6105, ts.DiagnosticCategory.Message, "Expected_type_of_0_field_in_package_json_to_be_1_got_2_6105", "Expected type of '{0}' field in 'package.json' to be '{1}', got '{2}'."), + baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1: diag(6106, ts.DiagnosticCategory.Message, "baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1_6106", "'baseUrl' option is set to '{0}', using this value to resolve non-relative module name '{1}'."), + rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0: diag(6107, ts.DiagnosticCategory.Message, "rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107", "'rootDirs' option is set, using it to resolve relative module name '{0}'."), + Longest_matching_prefix_for_0_is_1: diag(6108, ts.DiagnosticCategory.Message, "Longest_matching_prefix_for_0_is_1_6108", "Longest matching prefix for '{0}' is '{1}'."), + Loading_0_from_the_root_dir_1_candidate_location_2: diag(6109, ts.DiagnosticCategory.Message, "Loading_0_from_the_root_dir_1_candidate_location_2_6109", "Loading '{0}' from the root dir '{1}', candidate location '{2}'."), + Trying_other_entries_in_rootDirs: diag(6110, ts.DiagnosticCategory.Message, "Trying_other_entries_in_rootDirs_6110", "Trying other entries in 'rootDirs'."), + Module_resolution_using_rootDirs_has_failed: diag(6111, ts.DiagnosticCategory.Message, "Module_resolution_using_rootDirs_has_failed_6111", "Module resolution using 'rootDirs' has failed."), + Do_not_emit_use_strict_directives_in_module_output: diag(6112, ts.DiagnosticCategory.Message, "Do_not_emit_use_strict_directives_in_module_output_6112", "Do not emit 'use strict' directives in module output."), + Enable_strict_null_checks: diag(6113, ts.DiagnosticCategory.Message, "Enable_strict_null_checks_6113", "Enable strict null checks."), + Unknown_option_excludes_Did_you_mean_exclude: diag(6114, ts.DiagnosticCategory.Error, "Unknown_option_excludes_Did_you_mean_exclude_6114", "Unknown option 'excludes'. Did you mean 'exclude'?"), + Raise_error_on_this_expressions_with_an_implied_any_type: diag(6115, ts.DiagnosticCategory.Message, "Raise_error_on_this_expressions_with_an_implied_any_type_6115", "Raise error on 'this' expressions with an implied 'any' type."), + Resolving_type_reference_directive_0_containing_file_1_root_directory_2: diag(6116, ts.DiagnosticCategory.Message, "Resolving_type_reference_directive_0_containing_file_1_root_directory_2_6116", "======== Resolving type reference directive '{0}', containing file '{1}', root directory '{2}'. ========"), + Resolving_using_primary_search_paths: diag(6117, ts.DiagnosticCategory.Message, "Resolving_using_primary_search_paths_6117", "Resolving using primary search paths..."), + Resolving_from_node_modules_folder: diag(6118, ts.DiagnosticCategory.Message, "Resolving_from_node_modules_folder_6118", "Resolving from node_modules folder..."), + Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2: diag(6119, ts.DiagnosticCategory.Message, "Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2_6119", "======== Type reference directive '{0}' was successfully resolved to '{1}', primary: {2}. ========"), + Type_reference_directive_0_was_not_resolved: diag(6120, ts.DiagnosticCategory.Message, "Type_reference_directive_0_was_not_resolved_6120", "======== Type reference directive '{0}' was not resolved. ========"), + Resolving_with_primary_search_path_0: diag(6121, ts.DiagnosticCategory.Message, "Resolving_with_primary_search_path_0_6121", "Resolving with primary search path '{0}'."), + Root_directory_cannot_be_determined_skipping_primary_search_paths: diag(6122, ts.DiagnosticCategory.Message, "Root_directory_cannot_be_determined_skipping_primary_search_paths_6122", "Root directory cannot be determined, skipping primary search paths."), + Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set: diag(6123, ts.DiagnosticCategory.Message, "Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set_6123", "======== Resolving type reference directive '{0}', containing file '{1}', root directory not set. ========"), + Type_declaration_files_to_be_included_in_compilation: diag(6124, ts.DiagnosticCategory.Message, "Type_declaration_files_to_be_included_in_compilation_6124", "Type declaration files to be included in compilation."), + Looking_up_in_node_modules_folder_initial_location_0: diag(6125, ts.DiagnosticCategory.Message, "Looking_up_in_node_modules_folder_initial_location_0_6125", "Looking up in 'node_modules' folder, initial location '{0}'."), + Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder: diag(6126, ts.DiagnosticCategory.Message, "Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126", "Containing file is not specified and root directory cannot be determined, skipping lookup in 'node_modules' folder."), + Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1: diag(6127, ts.DiagnosticCategory.Message, "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1_6127", "======== Resolving type reference directive '{0}', containing file not set, root directory '{1}'. ========"), + Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set: diag(6128, ts.DiagnosticCategory.Message, "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set_6128", "======== Resolving type reference directive '{0}', containing file not set, root directory not set. ========"), + Resolving_real_path_for_0_result_1: diag(6130, ts.DiagnosticCategory.Message, "Resolving_real_path_for_0_result_1_6130", "Resolving real path for '{0}', result '{1}'."), + Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system: diag(6131, ts.DiagnosticCategory.Error, "Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system_6131", "Cannot compile modules using option '{0}' unless the '--module' flag is 'amd' or 'system'."), + File_name_0_has_a_1_extension_stripping_it: diag(6132, ts.DiagnosticCategory.Message, "File_name_0_has_a_1_extension_stripping_it_6132", "File name '{0}' has a '{1}' extension - stripping it."), + _0_is_declared_but_its_value_is_never_read: diag(6133, ts.DiagnosticCategory.Error, "_0_is_declared_but_its_value_is_never_read_6133", "'{0}' is declared but its value is never read.", /*reportsUnnecessary*/ true), + Report_errors_on_unused_locals: diag(6134, ts.DiagnosticCategory.Message, "Report_errors_on_unused_locals_6134", "Report errors on unused locals."), + Report_errors_on_unused_parameters: diag(6135, ts.DiagnosticCategory.Message, "Report_errors_on_unused_parameters_6135", "Report errors on unused parameters."), + The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files: diag(6136, ts.DiagnosticCategory.Message, "The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files_6136", "The maximum dependency depth to search under node_modules and load JavaScript files."), + Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1: diag(6137, ts.DiagnosticCategory.Error, "Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1_6137", "Cannot import type declaration files. Consider importing '{0}' instead of '{1}'."), + Property_0_is_declared_but_its_value_is_never_read: diag(6138, ts.DiagnosticCategory.Error, "Property_0_is_declared_but_its_value_is_never_read_6138", "Property '{0}' is declared but its value is never read.", /*reportsUnnecessary*/ true), + Import_emit_helpers_from_tslib: diag(6139, ts.DiagnosticCategory.Message, "Import_emit_helpers_from_tslib_6139", "Import emit helpers from 'tslib'."), + Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2: diag(6140, ts.DiagnosticCategory.Error, "Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using__6140", "Auto discovery for typings is enabled in project '{0}'. Running extra resolution pass for module '{1}' using cache location '{2}'."), + Parse_in_strict_mode_and_emit_use_strict_for_each_source_file: diag(6141, ts.DiagnosticCategory.Message, "Parse_in_strict_mode_and_emit_use_strict_for_each_source_file_6141", "Parse in strict mode and emit \"use strict\" for each source file."), + Module_0_was_resolved_to_1_but_jsx_is_not_set: diag(6142, ts.DiagnosticCategory.Error, "Module_0_was_resolved_to_1_but_jsx_is_not_set_6142", "Module '{0}' was resolved to '{1}', but '--jsx' is not set."), + Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1: diag(6144, ts.DiagnosticCategory.Message, "Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1_6144", "Module '{0}' was resolved as locally declared ambient module in file '{1}'."), + Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified: diag(6145, ts.DiagnosticCategory.Message, "Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified_6145", "Module '{0}' was resolved as ambient module declared in '{1}' since this file was not modified."), + Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h: diag(6146, ts.DiagnosticCategory.Message, "Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h_6146", "Specify the JSX factory function to use when targeting 'react' JSX emit, e.g. 'React.createElement' or 'h'."), + Resolution_for_module_0_was_found_in_cache_from_location_1: diag(6147, ts.DiagnosticCategory.Message, "Resolution_for_module_0_was_found_in_cache_from_location_1_6147", "Resolution for module '{0}' was found in cache from location '{1}'."), + Directory_0_does_not_exist_skipping_all_lookups_in_it: diag(6148, ts.DiagnosticCategory.Message, "Directory_0_does_not_exist_skipping_all_lookups_in_it_6148", "Directory '{0}' does not exist, skipping all lookups in it."), + Show_diagnostic_information: diag(6149, ts.DiagnosticCategory.Message, "Show_diagnostic_information_6149", "Show diagnostic information."), + Show_verbose_diagnostic_information: diag(6150, ts.DiagnosticCategory.Message, "Show_verbose_diagnostic_information_6150", "Show verbose diagnostic information."), + Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file: diag(6151, ts.DiagnosticCategory.Message, "Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file_6151", "Emit a single file with source maps instead of having a separate file."), + Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap_to_be_set: diag(6152, ts.DiagnosticCategory.Message, "Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap__6152", "Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set."), + Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule: diag(6153, ts.DiagnosticCategory.Message, "Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule_6153", "Transpile each file as a separate module (similar to 'ts.transpileModule')."), + Print_names_of_generated_files_part_of_the_compilation: diag(6154, ts.DiagnosticCategory.Message, "Print_names_of_generated_files_part_of_the_compilation_6154", "Print names of generated files part of the compilation."), + Print_names_of_files_part_of_the_compilation: diag(6155, ts.DiagnosticCategory.Message, "Print_names_of_files_part_of_the_compilation_6155", "Print names of files part of the compilation."), + The_locale_used_when_displaying_messages_to_the_user_e_g_en_us: diag(6156, ts.DiagnosticCategory.Message, "The_locale_used_when_displaying_messages_to_the_user_e_g_en_us_6156", "The locale used when displaying messages to the user (e.g. 'en-us')"), + Do_not_generate_custom_helper_functions_like_extends_in_compiled_output: diag(6157, ts.DiagnosticCategory.Message, "Do_not_generate_custom_helper_functions_like_extends_in_compiled_output_6157", "Do not generate custom helper functions like '__extends' in compiled output."), + Do_not_include_the_default_library_file_lib_d_ts: diag(6158, ts.DiagnosticCategory.Message, "Do_not_include_the_default_library_file_lib_d_ts_6158", "Do not include the default library file (lib.d.ts)."), + Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files: diag(6159, ts.DiagnosticCategory.Message, "Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files_6159", "Do not add triple-slash references or imported modules to the list of compiled files."), + Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files: diag(6160, ts.DiagnosticCategory.Message, "Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files_6160", "[Deprecated] Use '--skipLibCheck' instead. Skip type checking of default library declaration files."), + List_of_folders_to_include_type_definitions_from: diag(6161, ts.DiagnosticCategory.Message, "List_of_folders_to_include_type_definitions_from_6161", "List of folders to include type definitions from."), + Disable_size_limitations_on_JavaScript_projects: diag(6162, ts.DiagnosticCategory.Message, "Disable_size_limitations_on_JavaScript_projects_6162", "Disable size limitations on JavaScript projects."), + The_character_set_of_the_input_files: diag(6163, ts.DiagnosticCategory.Message, "The_character_set_of_the_input_files_6163", "The character set of the input files."), + Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files: diag(6164, ts.DiagnosticCategory.Message, "Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files_6164", "Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files."), + Do_not_truncate_error_messages: diag(6165, ts.DiagnosticCategory.Message, "Do_not_truncate_error_messages_6165", "Do not truncate error messages."), + Output_directory_for_generated_declaration_files: diag(6166, ts.DiagnosticCategory.Message, "Output_directory_for_generated_declaration_files_6166", "Output directory for generated declaration files."), + A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl: diag(6167, ts.DiagnosticCategory.Message, "A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl_6167", "A series of entries which re-map imports to lookup locations relative to the 'baseUrl'."), + List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime: diag(6168, ts.DiagnosticCategory.Message, "List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime_6168", "List of root folders whose combined content represents the structure of the project at runtime."), + Show_all_compiler_options: diag(6169, ts.DiagnosticCategory.Message, "Show_all_compiler_options_6169", "Show all compiler options."), + Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file: diag(6170, ts.DiagnosticCategory.Message, "Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file_6170", "[Deprecated] Use '--outFile' instead. Concatenate and emit output to single file"), + Command_line_Options: diag(6171, ts.DiagnosticCategory.Message, "Command_line_Options_6171", "Command-line Options"), + Basic_Options: diag(6172, ts.DiagnosticCategory.Message, "Basic_Options_6172", "Basic Options"), + Strict_Type_Checking_Options: diag(6173, ts.DiagnosticCategory.Message, "Strict_Type_Checking_Options_6173", "Strict Type-Checking Options"), + Module_Resolution_Options: diag(6174, ts.DiagnosticCategory.Message, "Module_Resolution_Options_6174", "Module Resolution Options"), + Source_Map_Options: diag(6175, ts.DiagnosticCategory.Message, "Source_Map_Options_6175", "Source Map Options"), + Additional_Checks: diag(6176, ts.DiagnosticCategory.Message, "Additional_Checks_6176", "Additional Checks"), + Experimental_Options: diag(6177, ts.DiagnosticCategory.Message, "Experimental_Options_6177", "Experimental Options"), + Advanced_Options: diag(6178, ts.DiagnosticCategory.Message, "Advanced_Options_6178", "Advanced Options"), + Provide_full_support_for_iterables_in_for_of_spread_and_destructuring_when_targeting_ES5_or_ES3: diag(6179, ts.DiagnosticCategory.Message, "Provide_full_support_for_iterables_in_for_of_spread_and_destructuring_when_targeting_ES5_or_ES3_6179", "Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'."), + Enable_all_strict_type_checking_options: diag(6180, ts.DiagnosticCategory.Message, "Enable_all_strict_type_checking_options_6180", "Enable all strict type-checking options."), + List_of_language_service_plugins: diag(6181, ts.DiagnosticCategory.Message, "List_of_language_service_plugins_6181", "List of language service plugins."), + Scoped_package_detected_looking_in_0: diag(6182, ts.DiagnosticCategory.Message, "Scoped_package_detected_looking_in_0_6182", "Scoped package detected, looking in '{0}'"), + Reusing_resolution_of_module_0_to_file_1_from_old_program: diag(6183, ts.DiagnosticCategory.Message, "Reusing_resolution_of_module_0_to_file_1_from_old_program_6183", "Reusing resolution of module '{0}' to file '{1}' from old program."), + Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program: diag(6184, ts.DiagnosticCategory.Message, "Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program_6184", "Reusing module resolutions originating in '{0}' since resolutions are unchanged from old program."), + Disable_strict_checking_of_generic_signatures_in_function_types: diag(6185, ts.DiagnosticCategory.Message, "Disable_strict_checking_of_generic_signatures_in_function_types_6185", "Disable strict checking of generic signatures in function types."), + Enable_strict_checking_of_function_types: diag(6186, ts.DiagnosticCategory.Message, "Enable_strict_checking_of_function_types_6186", "Enable strict checking of function types."), + Enable_strict_checking_of_property_initialization_in_classes: diag(6187, ts.DiagnosticCategory.Message, "Enable_strict_checking_of_property_initialization_in_classes_6187", "Enable strict checking of property initialization in classes."), + Numeric_separators_are_not_allowed_here: diag(6188, ts.DiagnosticCategory.Error, "Numeric_separators_are_not_allowed_here_6188", "Numeric separators are not allowed here."), + Multiple_consecutive_numeric_separators_are_not_permitted: diag(6189, ts.DiagnosticCategory.Error, "Multiple_consecutive_numeric_separators_are_not_permitted_6189", "Multiple consecutive numeric separators are not permitted."), + Found_package_json_at_0_Package_ID_is_1: diag(6190, ts.DiagnosticCategory.Message, "Found_package_json_at_0_Package_ID_is_1_6190", "Found 'package.json' at '{0}'. Package ID is '{1}'."), + Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen: diag(6191, ts.DiagnosticCategory.Message, "Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen_6191", "Whether to keep outdated console output in watch mode instead of clearing the screen."), + All_imports_in_import_declaration_are_unused: diag(6192, ts.DiagnosticCategory.Error, "All_imports_in_import_declaration_are_unused_6192", "All imports in import declaration are unused.", /*reportsUnnecessary*/ true), + Found_1_error_Watching_for_file_changes: diag(6193, ts.DiagnosticCategory.Message, "Found_1_error_Watching_for_file_changes_6193", "Found 1 error. Watching for file changes."), + Found_0_errors_Watching_for_file_changes: diag(6194, ts.DiagnosticCategory.Message, "Found_0_errors_Watching_for_file_changes_6194", "Found {0} errors. Watching for file changes."), + Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols: diag(6195, ts.DiagnosticCategory.Message, "Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols_6195", "Resolve 'keyof' to string valued property names only (no numbers or symbols)."), + _0_is_declared_but_never_used: diag(6196, ts.DiagnosticCategory.Error, "_0_is_declared_but_never_used_6196", "'{0}' is declared but never used.", /*reportsUnnecessary*/ true), + Include_modules_imported_with_json_extension: diag(6197, ts.DiagnosticCategory.Message, "Include_modules_imported_with_json_extension_6197", "Include modules imported with '.json' extension"), + All_destructured_elements_are_unused: diag(6198, ts.DiagnosticCategory.Error, "All_destructured_elements_are_unused_6198", "All destructured elements are unused.", /*reportsUnnecessary*/ true), + All_variables_are_unused: diag(6199, ts.DiagnosticCategory.Error, "All_variables_are_unused_6199", "All variables are unused.", /*reportsUnnecessary*/ true), + Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0: diag(6200, ts.DiagnosticCategory.Error, "Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0_6200", "Definitions of the following identifiers conflict with those in another file: {0}"), + Conflicts_are_in_this_file: diag(6201, ts.DiagnosticCategory.Message, "Conflicts_are_in_this_file_6201", "Conflicts are in this file."), + _0_was_also_declared_here: diag(6203, ts.DiagnosticCategory.Message, "_0_was_also_declared_here_6203", "'{0}' was also declared here."), + and_here: diag(6204, ts.DiagnosticCategory.Message, "and_here_6204", "and here."), + All_type_parameters_are_unused: diag(6205, ts.DiagnosticCategory.Error, "All_type_parameters_are_unused_6205", "All type parameters are unused"), + package_json_has_a_typesVersions_field_with_version_specific_path_mappings: diag(6206, ts.DiagnosticCategory.Message, "package_json_has_a_typesVersions_field_with_version_specific_path_mappings_6206", "'package.json' has a 'typesVersions' field with version-specific path mappings."), + package_json_does_not_have_a_typesVersions_entry_that_matches_version_0: diag(6207, ts.DiagnosticCategory.Message, "package_json_does_not_have_a_typesVersions_entry_that_matches_version_0_6207", "'package.json' does not have a 'typesVersions' entry that matches version '{0}'."), + package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2: diag(6208, ts.DiagnosticCategory.Message, "package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_ma_6208", "'package.json' has a 'typesVersions' entry '{0}' that matches compiler version '{1}', looking for a pattern to match module name '{2}'."), + package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range: diag(6209, ts.DiagnosticCategory.Message, "package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range_6209", "'package.json' has a 'typesVersions' entry '{0}' that is not a valid semver range."), + An_argument_for_0_was_not_provided: diag(6210, ts.DiagnosticCategory.Message, "An_argument_for_0_was_not_provided_6210", "An argument for '{0}' was not provided."), + An_argument_matching_this_binding_pattern_was_not_provided: diag(6211, ts.DiagnosticCategory.Message, "An_argument_matching_this_binding_pattern_was_not_provided_6211", "An argument matching this binding pattern was not provided."), + Did_you_mean_to_call_this_expression: diag(6212, ts.DiagnosticCategory.Message, "Did_you_mean_to_call_this_expression_6212", "Did you mean to call this expression?"), + Did_you_mean_to_use_new_with_this_expression: diag(6213, ts.DiagnosticCategory.Message, "Did_you_mean_to_use_new_with_this_expression_6213", "Did you mean to use 'new' with this expression?"), + Enable_strict_bind_call_and_apply_methods_on_functions: diag(6214, ts.DiagnosticCategory.Message, "Enable_strict_bind_call_and_apply_methods_on_functions_6214", "Enable strict 'bind', 'call', and 'apply' methods on functions."), + Using_compiler_options_of_project_reference_redirect_0: diag(6215, ts.DiagnosticCategory.Message, "Using_compiler_options_of_project_reference_redirect_0_6215", "Using compiler options of project reference redirect '{0}'."), + Found_1_error: diag(6216, ts.DiagnosticCategory.Message, "Found_1_error_6216", "Found 1 error."), + Found_0_errors: diag(6217, ts.DiagnosticCategory.Message, "Found_0_errors_6217", "Found {0} errors."), + Projects_to_reference: diag(6300, ts.DiagnosticCategory.Message, "Projects_to_reference_6300", "Projects to reference"), + Enable_project_compilation: diag(6302, ts.DiagnosticCategory.Message, "Enable_project_compilation_6302", "Enable project compilation"), + Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0: diag(6202, ts.DiagnosticCategory.Error, "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202", "Project references may not form a circular graph. Cycle detected: {0}"), + Composite_projects_may_not_disable_declaration_emit: diag(6304, ts.DiagnosticCategory.Error, "Composite_projects_may_not_disable_declaration_emit_6304", "Composite projects may not disable declaration emit."), + Output_file_0_has_not_been_built_from_source_file_1: diag(6305, ts.DiagnosticCategory.Error, "Output_file_0_has_not_been_built_from_source_file_1_6305", "Output file '{0}' has not been built from source file '{1}'."), + Referenced_project_0_must_have_setting_composite_Colon_true: diag(6306, ts.DiagnosticCategory.Error, "Referenced_project_0_must_have_setting_composite_Colon_true_6306", "Referenced project '{0}' must have setting \"composite\": true."), + File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern: diag(6307, ts.DiagnosticCategory.Error, "File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern_6307", "File '{0}' is not in project file list. Projects must list all files or use an 'include' pattern."), + Cannot_prepend_project_0_because_it_does_not_have_outFile_set: diag(6308, ts.DiagnosticCategory.Error, "Cannot_prepend_project_0_because_it_does_not_have_outFile_set_6308", "Cannot prepend project '{0}' because it does not have 'outFile' set"), + Output_file_0_from_project_1_does_not_exist: diag(6309, ts.DiagnosticCategory.Error, "Output_file_0_from_project_1_does_not_exist_6309", "Output file '{0}' from project '{1}' does not exist"), + Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2: diag(6350, ts.DiagnosticCategory.Message, "Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2_6350", "Project '{0}' is out of date because oldest output '{1}' is older than newest input '{2}'"), + Project_0_is_up_to_date_because_newest_input_1_is_older_than_oldest_output_2: diag(6351, ts.DiagnosticCategory.Message, "Project_0_is_up_to_date_because_newest_input_1_is_older_than_oldest_output_2_6351", "Project '{0}' is up to date because newest input '{1}' is older than oldest output '{2}'"), + Project_0_is_out_of_date_because_output_file_1_does_not_exist: diag(6352, ts.DiagnosticCategory.Message, "Project_0_is_out_of_date_because_output_file_1_does_not_exist_6352", "Project '{0}' is out of date because output file '{1}' does not exist"), + Project_0_is_out_of_date_because_its_dependency_1_is_out_of_date: diag(6353, ts.DiagnosticCategory.Message, "Project_0_is_out_of_date_because_its_dependency_1_is_out_of_date_6353", "Project '{0}' is out of date because its dependency '{1}' is out of date"), + Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies: diag(6354, ts.DiagnosticCategory.Message, "Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies_6354", "Project '{0}' is up to date with .d.ts files from its dependencies"), + Projects_in_this_build_Colon_0: diag(6355, ts.DiagnosticCategory.Message, "Projects_in_this_build_Colon_0_6355", "Projects in this build: {0}"), + A_non_dry_build_would_delete_the_following_files_Colon_0: diag(6356, ts.DiagnosticCategory.Message, "A_non_dry_build_would_delete_the_following_files_Colon_0_6356", "A non-dry build would delete the following files: {0}"), + A_non_dry_build_would_build_project_0: diag(6357, ts.DiagnosticCategory.Message, "A_non_dry_build_would_build_project_0_6357", "A non-dry build would build project '{0}'"), + Building_project_0: diag(6358, ts.DiagnosticCategory.Message, "Building_project_0_6358", "Building project '{0}'..."), + Updating_output_timestamps_of_project_0: diag(6359, ts.DiagnosticCategory.Message, "Updating_output_timestamps_of_project_0_6359", "Updating output timestamps of project '{0}'..."), + delete_this_Project_0_is_up_to_date_because_it_was_previously_built: diag(6360, ts.DiagnosticCategory.Message, "delete_this_Project_0_is_up_to_date_because_it_was_previously_built_6360", "delete this - Project '{0}' is up to date because it was previously built"), + Project_0_is_up_to_date: diag(6361, ts.DiagnosticCategory.Message, "Project_0_is_up_to_date_6361", "Project '{0}' is up to date"), + Skipping_build_of_project_0_because_its_dependency_1_has_errors: diag(6362, ts.DiagnosticCategory.Message, "Skipping_build_of_project_0_because_its_dependency_1_has_errors_6362", "Skipping build of project '{0}' because its dependency '{1}' has errors"), + Project_0_can_t_be_built_because_its_dependency_1_has_errors: diag(6363, ts.DiagnosticCategory.Message, "Project_0_can_t_be_built_because_its_dependency_1_has_errors_6363", "Project '{0}' can't be built because its dependency '{1}' has errors"), + Build_one_or_more_projects_and_their_dependencies_if_out_of_date: diag(6364, ts.DiagnosticCategory.Message, "Build_one_or_more_projects_and_their_dependencies_if_out_of_date_6364", "Build one or more projects and their dependencies, if out of date"), + Delete_the_outputs_of_all_projects: diag(6365, ts.DiagnosticCategory.Message, "Delete_the_outputs_of_all_projects_6365", "Delete the outputs of all projects"), + Enable_verbose_logging: diag(6366, ts.DiagnosticCategory.Message, "Enable_verbose_logging_6366", "Enable verbose logging"), + Show_what_would_be_built_or_deleted_if_specified_with_clean: diag(6367, ts.DiagnosticCategory.Message, "Show_what_would_be_built_or_deleted_if_specified_with_clean_6367", "Show what would be built (or deleted, if specified with '--clean')"), + Build_all_projects_including_those_that_appear_to_be_up_to_date: diag(6368, ts.DiagnosticCategory.Message, "Build_all_projects_including_those_that_appear_to_be_up_to_date_6368", "Build all projects, including those that appear to be up to date"), + Option_build_must_be_the_first_command_line_argument: diag(6369, ts.DiagnosticCategory.Error, "Option_build_must_be_the_first_command_line_argument_6369", "Option '--build' must be the first command line argument."), + Options_0_and_1_cannot_be_combined: diag(6370, ts.DiagnosticCategory.Error, "Options_0_and_1_cannot_be_combined_6370", "Options '{0}' and '{1}' cannot be combined."), + The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1: diag(6500, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1_6500", "The expected type comes from property '{0}' which is declared here on type '{1}'"), + The_expected_type_comes_from_this_index_signature: diag(6501, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_this_index_signature_6501", "The expected type comes from this index signature."), + The_expected_type_comes_from_the_return_type_of_this_signature: diag(6502, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_the_return_type_of_this_signature_6502", "The expected type comes from the return type of this signature."), + Variable_0_implicitly_has_an_1_type: diag(7005, ts.DiagnosticCategory.Error, "Variable_0_implicitly_has_an_1_type_7005", "Variable '{0}' implicitly has an '{1}' type."), + Parameter_0_implicitly_has_an_1_type: diag(7006, ts.DiagnosticCategory.Error, "Parameter_0_implicitly_has_an_1_type_7006", "Parameter '{0}' implicitly has an '{1}' type."), + Member_0_implicitly_has_an_1_type: diag(7008, ts.DiagnosticCategory.Error, "Member_0_implicitly_has_an_1_type_7008", "Member '{0}' implicitly has an '{1}' type."), + new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type: diag(7009, ts.DiagnosticCategory.Error, "new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type_7009", "'new' expression, whose target lacks a construct signature, implicitly has an 'any' type."), + _0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type: diag(7010, ts.DiagnosticCategory.Error, "_0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type_7010", "'{0}', which lacks return-type annotation, implicitly has an '{1}' return type."), + Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type: diag(7011, ts.DiagnosticCategory.Error, "Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type_7011", "Function expression, which lacks return-type annotation, implicitly has an '{0}' return type."), + Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: diag(7013, ts.DiagnosticCategory.Error, "Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7013", "Construct signature, which lacks return-type annotation, implicitly has an 'any' return type."), + Function_type_which_lacks_return_type_annotation_implicitly_has_an_0_return_type: diag(7014, ts.DiagnosticCategory.Error, "Function_type_which_lacks_return_type_annotation_implicitly_has_an_0_return_type_7014", "Function type, which lacks return-type annotation, implicitly has an '{0}' return type."), + Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number: diag(7015, ts.DiagnosticCategory.Error, "Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015", "Element implicitly has an 'any' type because index expression is not of type 'number'."), + Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type: diag(7016, ts.DiagnosticCategory.Error, "Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type_7016", "Could not find a declaration file for module '{0}'. '{1}' implicitly has an 'any' type."), + Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature: diag(7017, ts.DiagnosticCategory.Error, "Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature_7017", "Element implicitly has an 'any' type because type '{0}' has no index signature."), + Object_literal_s_property_0_implicitly_has_an_1_type: diag(7018, ts.DiagnosticCategory.Error, "Object_literal_s_property_0_implicitly_has_an_1_type_7018", "Object literal's property '{0}' implicitly has an '{1}' type."), + Rest_parameter_0_implicitly_has_an_any_type: diag(7019, ts.DiagnosticCategory.Error, "Rest_parameter_0_implicitly_has_an_any_type_7019", "Rest parameter '{0}' implicitly has an 'any[]' type."), + Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: diag(7020, ts.DiagnosticCategory.Error, "Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7020", "Call signature, which lacks return-type annotation, implicitly has an 'any' return type."), + _0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer: diag(7022, ts.DiagnosticCategory.Error, "_0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or__7022", "'{0}' implicitly has type 'any' because it does not have a type annotation and is referenced directly or indirectly in its own initializer."), + _0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions: diag(7023, ts.DiagnosticCategory.Error, "_0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_reference_7023", "'{0}' implicitly has return type 'any' because it does not have a return type annotation and is referenced directly or indirectly in one of its return expressions."), + Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions: diag(7024, ts.DiagnosticCategory.Error, "Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_ref_7024", "Function implicitly has return type 'any' because it does not have a return type annotation and is referenced directly or indirectly in one of its return expressions."), + Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_type: diag(7025, ts.DiagnosticCategory.Error, "Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_typ_7025", "Generator implicitly has type '{0}' because it does not yield any values. Consider supplying a return type."), + JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists: diag(7026, ts.DiagnosticCategory.Error, "JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists_7026", "JSX element implicitly has type 'any' because no interface 'JSX.{0}' exists."), + Unreachable_code_detected: diag(7027, ts.DiagnosticCategory.Error, "Unreachable_code_detected_7027", "Unreachable code detected.", /*reportsUnnecessary*/ true), + Unused_label: diag(7028, ts.DiagnosticCategory.Error, "Unused_label_7028", "Unused label.", /*reportsUnnecessary*/ true), + Fallthrough_case_in_switch: diag(7029, ts.DiagnosticCategory.Error, "Fallthrough_case_in_switch_7029", "Fallthrough case in switch."), + Not_all_code_paths_return_a_value: diag(7030, ts.DiagnosticCategory.Error, "Not_all_code_paths_return_a_value_7030", "Not all code paths return a value."), + Binding_element_0_implicitly_has_an_1_type: diag(7031, ts.DiagnosticCategory.Error, "Binding_element_0_implicitly_has_an_1_type_7031", "Binding element '{0}' implicitly has an '{1}' type."), + Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation: diag(7032, ts.DiagnosticCategory.Error, "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032", "Property '{0}' implicitly has type 'any', because its set accessor lacks a parameter type annotation."), + Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation: diag(7033, ts.DiagnosticCategory.Error, "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033", "Property '{0}' implicitly has type 'any', because its get accessor lacks a return type annotation."), + Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined: diag(7034, ts.DiagnosticCategory.Error, "Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined_7034", "Variable '{0}' implicitly has type '{1}' in some locations where its type cannot be determined."), + Try_npm_install_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0: diag(7035, ts.DiagnosticCategory.Error, "Try_npm_install_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_mod_7035", "Try `npm install @types/{1}` if it exists or add a new declaration (.d.ts) file containing `declare module '{0}';`"), + Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0: diag(7036, ts.DiagnosticCategory.Error, "Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036", "Dynamic import's specifier must be of type 'string', but here has type '{0}'."), + Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for_all_imports_Implies_allowSyntheticDefaultImports: diag(7037, ts.DiagnosticCategory.Message, "Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for__7037", "Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'."), + Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_Consider_using_a_default_import_or_import_require_here_instead: diag(7038, ts.DiagnosticCategory.Message, "Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cau_7038", "Type originates at this import. A namespace-style import cannot be called or constructed, and will cause a failure at runtime. Consider using a default import or import require here instead."), + Mapped_object_type_implicitly_has_an_any_template_type: diag(7039, ts.DiagnosticCategory.Error, "Mapped_object_type_implicitly_has_an_any_template_type_7039", "Mapped object type implicitly has an 'any' template type."), + If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1: diag(7040, ts.DiagnosticCategory.Error, "If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_S_7040", "If the '{0}' package actually exposes this module, consider sending a pull request to amend 'https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/{1}`"), + The_containing_arrow_function_captures_the_global_value_of_this_which_implicitly_has_type_any: diag(7041, ts.DiagnosticCategory.Error, "The_containing_arrow_function_captures_the_global_value_of_this_which_implicitly_has_type_any_7041", "The containing arrow function captures the global value of 'this' which implicitly has type 'any'."), + Module_0_was_resolved_to_1_but_resolveJsonModule_is_not_used: diag(7042, ts.DiagnosticCategory.Error, "Module_0_was_resolved_to_1_but_resolveJsonModule_is_not_used_7042", "Module '{0}' was resolved to '{1}', but '--resolveJsonModule' is not used."), + Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage: diag(7043, ts.DiagnosticCategory.Suggestion, "Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7043", "Variable '{0}' implicitly has an '{1}' type, but a better type may be inferred from usage."), + Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage: diag(7044, ts.DiagnosticCategory.Suggestion, "Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7044", "Parameter '{0}' implicitly has an '{1}' type, but a better type may be inferred from usage."), + Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage: diag(7045, ts.DiagnosticCategory.Suggestion, "Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7045", "Member '{0}' implicitly has an '{1}' type, but a better type may be inferred from usage."), + Variable_0_implicitly_has_type_1_in_some_locations_but_a_better_type_may_be_inferred_from_usage: diag(7046, ts.DiagnosticCategory.Suggestion, "Variable_0_implicitly_has_type_1_in_some_locations_but_a_better_type_may_be_inferred_from_usage_7046", "Variable '{0}' implicitly has type '{1}' in some locations, but a better type may be inferred from usage."), + Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage: diag(7047, ts.DiagnosticCategory.Suggestion, "Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage_7047", "Rest parameter '{0}' implicitly has an 'any[]' type, but a better type may be inferred from usage."), + Property_0_implicitly_has_type_any_but_a_better_type_for_its_get_accessor_may_be_inferred_from_usage: diag(7048, ts.DiagnosticCategory.Suggestion, "Property_0_implicitly_has_type_any_but_a_better_type_for_its_get_accessor_may_be_inferred_from_usage_7048", "Property '{0}' implicitly has type 'any', but a better type for its get accessor may be inferred from usage."), + Property_0_implicitly_has_type_any_but_a_better_type_for_its_set_accessor_may_be_inferred_from_usage: diag(7049, ts.DiagnosticCategory.Suggestion, "Property_0_implicitly_has_type_any_but_a_better_type_for_its_set_accessor_may_be_inferred_from_usage_7049", "Property '{0}' implicitly has type 'any', but a better type for its set accessor may be inferred from usage."), + _0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage: diag(7050, ts.DiagnosticCategory.Suggestion, "_0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage_7050", "'{0}' implicitly has an '{1}' return type, but a better type may be inferred from usage."), + Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1: diag(7051, ts.DiagnosticCategory.Error, "Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1_7051", "Parameter has a name but no type. Did you mean '{0}: {1}'?"), + You_cannot_rename_this_element: diag(8000, ts.DiagnosticCategory.Error, "You_cannot_rename_this_element_8000", "You cannot rename this element."), + You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library: diag(8001, ts.DiagnosticCategory.Error, "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001", "You cannot rename elements that are defined in the standard TypeScript library."), + import_can_only_be_used_in_a_ts_file: diag(8002, ts.DiagnosticCategory.Error, "import_can_only_be_used_in_a_ts_file_8002", "'import ... =' can only be used in a .ts file."), + export_can_only_be_used_in_a_ts_file: diag(8003, ts.DiagnosticCategory.Error, "export_can_only_be_used_in_a_ts_file_8003", "'export=' can only be used in a .ts file."), + type_parameter_declarations_can_only_be_used_in_a_ts_file: diag(8004, ts.DiagnosticCategory.Error, "type_parameter_declarations_can_only_be_used_in_a_ts_file_8004", "'type parameter declarations' can only be used in a .ts file."), + implements_clauses_can_only_be_used_in_a_ts_file: diag(8005, ts.DiagnosticCategory.Error, "implements_clauses_can_only_be_used_in_a_ts_file_8005", "'implements clauses' can only be used in a .ts file."), + interface_declarations_can_only_be_used_in_a_ts_file: diag(8006, ts.DiagnosticCategory.Error, "interface_declarations_can_only_be_used_in_a_ts_file_8006", "'interface declarations' can only be used in a .ts file."), + module_declarations_can_only_be_used_in_a_ts_file: diag(8007, ts.DiagnosticCategory.Error, "module_declarations_can_only_be_used_in_a_ts_file_8007", "'module declarations' can only be used in a .ts file."), + type_aliases_can_only_be_used_in_a_ts_file: diag(8008, ts.DiagnosticCategory.Error, "type_aliases_can_only_be_used_in_a_ts_file_8008", "'type aliases' can only be used in a .ts file."), + _0_can_only_be_used_in_a_ts_file: diag(8009, ts.DiagnosticCategory.Error, "_0_can_only_be_used_in_a_ts_file_8009", "'{0}' can only be used in a .ts file."), + types_can_only_be_used_in_a_ts_file: diag(8010, ts.DiagnosticCategory.Error, "types_can_only_be_used_in_a_ts_file_8010", "'types' can only be used in a .ts file."), + type_arguments_can_only_be_used_in_a_ts_file: diag(8011, ts.DiagnosticCategory.Error, "type_arguments_can_only_be_used_in_a_ts_file_8011", "'type arguments' can only be used in a .ts file."), + parameter_modifiers_can_only_be_used_in_a_ts_file: diag(8012, ts.DiagnosticCategory.Error, "parameter_modifiers_can_only_be_used_in_a_ts_file_8012", "'parameter modifiers' can only be used in a .ts file."), + non_null_assertions_can_only_be_used_in_a_ts_file: diag(8013, ts.DiagnosticCategory.Error, "non_null_assertions_can_only_be_used_in_a_ts_file_8013", "'non-null assertions' can only be used in a .ts file."), + enum_declarations_can_only_be_used_in_a_ts_file: diag(8015, ts.DiagnosticCategory.Error, "enum_declarations_can_only_be_used_in_a_ts_file_8015", "'enum declarations' can only be used in a .ts file."), + type_assertion_expressions_can_only_be_used_in_a_ts_file: diag(8016, ts.DiagnosticCategory.Error, "type_assertion_expressions_can_only_be_used_in_a_ts_file_8016", "'type assertion expressions' can only be used in a .ts file."), + Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0: diag(8017, ts.DiagnosticCategory.Error, "Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0_8017", "Octal literal types must use ES2015 syntax. Use the syntax '{0}'."), + Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0: diag(8018, ts.DiagnosticCategory.Error, "Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0_8018", "Octal literals are not allowed in enums members initializer. Use the syntax '{0}'."), + Report_errors_in_js_files: diag(8019, ts.DiagnosticCategory.Message, "Report_errors_in_js_files_8019", "Report errors in .js files."), + JSDoc_types_can_only_be_used_inside_documentation_comments: diag(8020, ts.DiagnosticCategory.Error, "JSDoc_types_can_only_be_used_inside_documentation_comments_8020", "JSDoc types can only be used inside documentation comments."), + JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags: diag(8021, ts.DiagnosticCategory.Error, "JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags_8021", "JSDoc '@typedef' tag should either have a type annotation or be followed by '@property' or '@member' tags."), + JSDoc_0_is_not_attached_to_a_class: diag(8022, ts.DiagnosticCategory.Error, "JSDoc_0_is_not_attached_to_a_class_8022", "JSDoc '@{0}' is not attached to a class."), + JSDoc_0_1_does_not_match_the_extends_2_clause: diag(8023, ts.DiagnosticCategory.Error, "JSDoc_0_1_does_not_match_the_extends_2_clause_8023", "JSDoc '@{0} {1}' does not match the 'extends {2}' clause."), + JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name: diag(8024, ts.DiagnosticCategory.Error, "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_8024", "JSDoc '@param' tag has name '{0}', but there is no parameter with that name."), + Class_declarations_cannot_have_more_than_one_augments_or_extends_tag: diag(8025, ts.DiagnosticCategory.Error, "Class_declarations_cannot_have_more_than_one_augments_or_extends_tag_8025", "Class declarations cannot have more than one `@augments` or `@extends` tag."), + Expected_0_type_arguments_provide_these_with_an_extends_tag: diag(8026, ts.DiagnosticCategory.Error, "Expected_0_type_arguments_provide_these_with_an_extends_tag_8026", "Expected {0} type arguments; provide these with an '@extends' tag."), + Expected_0_1_type_arguments_provide_these_with_an_extends_tag: diag(8027, ts.DiagnosticCategory.Error, "Expected_0_1_type_arguments_provide_these_with_an_extends_tag_8027", "Expected {0}-{1} type arguments; provide these with an '@extends' tag."), + JSDoc_may_only_appear_in_the_last_parameter_of_a_signature: diag(8028, ts.DiagnosticCategory.Error, "JSDoc_may_only_appear_in_the_last_parameter_of_a_signature_8028", "JSDoc '...' may only appear in the last parameter of a signature."), + JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_had_an_array_type: diag(8029, ts.DiagnosticCategory.Error, "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_h_8029", "JSDoc '@param' tag has name '{0}', but there is no parameter with that name. It would match 'arguments' if it had an array type."), + The_type_of_a_function_declaration_must_match_the_function_s_signature: diag(8030, ts.DiagnosticCategory.Error, "The_type_of_a_function_declaration_must_match_the_function_s_signature_8030", "The type of a function declaration must match the function's signature."), + You_cannot_rename_a_module_via_a_global_import: diag(8031, ts.DiagnosticCategory.Error, "You_cannot_rename_a_module_via_a_global_import_8031", "You cannot rename a module via a global import."), + Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_class_extends_clause: diag(9002, ts.DiagnosticCategory.Error, "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002", "Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clause."), + class_expressions_are_not_currently_supported: diag(9003, ts.DiagnosticCategory.Error, "class_expressions_are_not_currently_supported_9003", "'class' expressions are not currently supported."), + Language_service_is_disabled: diag(9004, ts.DiagnosticCategory.Error, "Language_service_is_disabled_9004", "Language service is disabled."), + JSX_attributes_must_only_be_assigned_a_non_empty_expression: diag(17000, ts.DiagnosticCategory.Error, "JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000", "JSX attributes must only be assigned a non-empty 'expression'."), + JSX_elements_cannot_have_multiple_attributes_with_the_same_name: diag(17001, ts.DiagnosticCategory.Error, "JSX_elements_cannot_have_multiple_attributes_with_the_same_name_17001", "JSX elements cannot have multiple attributes with the same name."), + Expected_corresponding_JSX_closing_tag_for_0: diag(17002, ts.DiagnosticCategory.Error, "Expected_corresponding_JSX_closing_tag_for_0_17002", "Expected corresponding JSX closing tag for '{0}'."), + JSX_attribute_expected: diag(17003, ts.DiagnosticCategory.Error, "JSX_attribute_expected_17003", "JSX attribute expected."), + Cannot_use_JSX_unless_the_jsx_flag_is_provided: diag(17004, ts.DiagnosticCategory.Error, "Cannot_use_JSX_unless_the_jsx_flag_is_provided_17004", "Cannot use JSX unless the '--jsx' flag is provided."), + A_constructor_cannot_contain_a_super_call_when_its_class_extends_null: diag(17005, ts.DiagnosticCategory.Error, "A_constructor_cannot_contain_a_super_call_when_its_class_extends_null_17005", "A constructor cannot contain a 'super' call when its class extends 'null'."), + An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses: diag(17006, ts.DiagnosticCategory.Error, "An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_ex_17006", "An unary expression with the '{0}' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses."), + A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses: diag(17007, ts.DiagnosticCategory.Error, "A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Con_17007", "A type assertion expression is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses."), + JSX_element_0_has_no_corresponding_closing_tag: diag(17008, ts.DiagnosticCategory.Error, "JSX_element_0_has_no_corresponding_closing_tag_17008", "JSX element '{0}' has no corresponding closing tag."), + super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class: diag(17009, ts.DiagnosticCategory.Error, "super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class_17009", "'super' must be called before accessing 'this' in the constructor of a derived class."), + Unknown_type_acquisition_option_0: diag(17010, ts.DiagnosticCategory.Error, "Unknown_type_acquisition_option_0_17010", "Unknown type acquisition option '{0}'."), + super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class: diag(17011, ts.DiagnosticCategory.Error, "super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class_17011", "'super' must be called before accessing a property of 'super' in the constructor of a derived class."), + _0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2: diag(17012, ts.DiagnosticCategory.Error, "_0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2_17012", "'{0}' is not a valid meta-property for keyword '{1}'. Did you mean '{2}'?"), + Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constructor: diag(17013, ts.DiagnosticCategory.Error, "Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constru_17013", "Meta-property '{0}' is only allowed in the body of a function declaration, function expression, or constructor."), + JSX_fragment_has_no_corresponding_closing_tag: diag(17014, ts.DiagnosticCategory.Error, "JSX_fragment_has_no_corresponding_closing_tag_17014", "JSX fragment has no corresponding closing tag."), + Expected_corresponding_closing_tag_for_JSX_fragment: diag(17015, ts.DiagnosticCategory.Error, "Expected_corresponding_closing_tag_for_JSX_fragment_17015", "Expected corresponding closing tag for JSX fragment."), + JSX_fragment_is_not_supported_when_using_jsxFactory: diag(17016, ts.DiagnosticCategory.Error, "JSX_fragment_is_not_supported_when_using_jsxFactory_17016", "JSX fragment is not supported when using --jsxFactory"), + JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma: diag(17017, ts.DiagnosticCategory.Error, "JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma_17017", "JSX fragment is not supported when using an inline JSX factory pragma"), + Circularity_detected_while_resolving_configuration_Colon_0: diag(18000, ts.DiagnosticCategory.Error, "Circularity_detected_while_resolving_configuration_Colon_0_18000", "Circularity detected while resolving configuration: {0}"), + A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not: diag(18001, ts.DiagnosticCategory.Error, "A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not_18001", "A path in an 'extends' option must be relative or rooted, but '{0}' is not."), + The_files_list_in_config_file_0_is_empty: diag(18002, ts.DiagnosticCategory.Error, "The_files_list_in_config_file_0_is_empty_18002", "The 'files' list in config file '{0}' is empty."), + No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2: diag(18003, ts.DiagnosticCategory.Error, "No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2_18003", "No inputs were found in config file '{0}'. Specified 'include' paths were '{1}' and 'exclude' paths were '{2}'."), + File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module: diag(80001, ts.DiagnosticCategory.Suggestion, "File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module_80001", "File is a CommonJS module; it may be converted to an ES6 module."), + This_constructor_function_may_be_converted_to_a_class_declaration: diag(80002, ts.DiagnosticCategory.Suggestion, "This_constructor_function_may_be_converted_to_a_class_declaration_80002", "This constructor function may be converted to a class declaration."), + Import_may_be_converted_to_a_default_import: diag(80003, ts.DiagnosticCategory.Suggestion, "Import_may_be_converted_to_a_default_import_80003", "Import may be converted to a default import."), + JSDoc_types_may_be_moved_to_TypeScript_types: diag(80004, ts.DiagnosticCategory.Suggestion, "JSDoc_types_may_be_moved_to_TypeScript_types_80004", "JSDoc types may be moved to TypeScript types."), + require_call_may_be_converted_to_an_import: diag(80005, ts.DiagnosticCategory.Suggestion, "require_call_may_be_converted_to_an_import_80005", "'require' call may be converted to an import."), + This_may_be_converted_to_an_async_function: diag(80006, ts.DiagnosticCategory.Suggestion, "This_may_be_converted_to_an_async_function_80006", "This may be converted to an async function."), + Add_missing_super_call: diag(90001, ts.DiagnosticCategory.Message, "Add_missing_super_call_90001", "Add missing 'super()' call"), + Make_super_call_the_first_statement_in_the_constructor: diag(90002, ts.DiagnosticCategory.Message, "Make_super_call_the_first_statement_in_the_constructor_90002", "Make 'super()' call the first statement in the constructor"), + Change_extends_to_implements: diag(90003, ts.DiagnosticCategory.Message, "Change_extends_to_implements_90003", "Change 'extends' to 'implements'"), + Remove_declaration_for_Colon_0: diag(90004, ts.DiagnosticCategory.Message, "Remove_declaration_for_Colon_0_90004", "Remove declaration for: '{0}'"), + Remove_import_from_0: diag(90005, ts.DiagnosticCategory.Message, "Remove_import_from_0_90005", "Remove import from '{0}'"), + Implement_interface_0: diag(90006, ts.DiagnosticCategory.Message, "Implement_interface_0_90006", "Implement interface '{0}'"), + Implement_inherited_abstract_class: diag(90007, ts.DiagnosticCategory.Message, "Implement_inherited_abstract_class_90007", "Implement inherited abstract class"), + Add_0_to_unresolved_variable: diag(90008, ts.DiagnosticCategory.Message, "Add_0_to_unresolved_variable_90008", "Add '{0}.' to unresolved variable"), + Remove_destructuring: diag(90009, ts.DiagnosticCategory.Message, "Remove_destructuring_90009", "Remove destructuring"), + Remove_variable_statement: diag(90010, ts.DiagnosticCategory.Message, "Remove_variable_statement_90010", "Remove variable statement"), + Remove_template_tag: diag(90011, ts.DiagnosticCategory.Message, "Remove_template_tag_90011", "Remove template tag"), + Remove_type_parameters: diag(90012, ts.DiagnosticCategory.Message, "Remove_type_parameters_90012", "Remove type parameters"), + Import_0_from_module_1: diag(90013, ts.DiagnosticCategory.Message, "Import_0_from_module_1_90013", "Import '{0}' from module \"{1}\""), + Change_0_to_1: diag(90014, ts.DiagnosticCategory.Message, "Change_0_to_1_90014", "Change '{0}' to '{1}'"), + Add_0_to_existing_import_declaration_from_1: diag(90015, ts.DiagnosticCategory.Message, "Add_0_to_existing_import_declaration_from_1_90015", "Add '{0}' to existing import declaration from \"{1}\""), + Declare_property_0: diag(90016, ts.DiagnosticCategory.Message, "Declare_property_0_90016", "Declare property '{0}'"), + Add_index_signature_for_property_0: diag(90017, ts.DiagnosticCategory.Message, "Add_index_signature_for_property_0_90017", "Add index signature for property '{0}'"), + Disable_checking_for_this_file: diag(90018, ts.DiagnosticCategory.Message, "Disable_checking_for_this_file_90018", "Disable checking for this file"), + Ignore_this_error_message: diag(90019, ts.DiagnosticCategory.Message, "Ignore_this_error_message_90019", "Ignore this error message"), + Initialize_property_0_in_the_constructor: diag(90020, ts.DiagnosticCategory.Message, "Initialize_property_0_in_the_constructor_90020", "Initialize property '{0}' in the constructor"), + Initialize_static_property_0: diag(90021, ts.DiagnosticCategory.Message, "Initialize_static_property_0_90021", "Initialize static property '{0}'"), + Change_spelling_to_0: diag(90022, ts.DiagnosticCategory.Message, "Change_spelling_to_0_90022", "Change spelling to '{0}'"), + Declare_method_0: diag(90023, ts.DiagnosticCategory.Message, "Declare_method_0_90023", "Declare method '{0}'"), + Declare_static_method_0: diag(90024, ts.DiagnosticCategory.Message, "Declare_static_method_0_90024", "Declare static method '{0}'"), + Prefix_0_with_an_underscore: diag(90025, ts.DiagnosticCategory.Message, "Prefix_0_with_an_underscore_90025", "Prefix '{0}' with an underscore"), + Rewrite_as_the_indexed_access_type_0: diag(90026, ts.DiagnosticCategory.Message, "Rewrite_as_the_indexed_access_type_0_90026", "Rewrite as the indexed access type '{0}'"), + Declare_static_property_0: diag(90027, ts.DiagnosticCategory.Message, "Declare_static_property_0_90027", "Declare static property '{0}'"), + Call_decorator_expression: diag(90028, ts.DiagnosticCategory.Message, "Call_decorator_expression_90028", "Call decorator expression"), + Add_async_modifier_to_containing_function: diag(90029, ts.DiagnosticCategory.Message, "Add_async_modifier_to_containing_function_90029", "Add async modifier to containing function"), + Replace_infer_0_with_unknown: diag(90030, ts.DiagnosticCategory.Message, "Replace_infer_0_with_unknown_90030", "Replace 'infer {0}' with 'unknown'"), + Replace_all_unused_infer_with_unknown: diag(90031, ts.DiagnosticCategory.Message, "Replace_all_unused_infer_with_unknown_90031", "Replace all unused 'infer' with 'unknown'"), + Import_default_0_from_module_1: diag(90032, ts.DiagnosticCategory.Message, "Import_default_0_from_module_1_90032", "Import default '{0}' from module \"{1}\""), + Add_default_import_0_to_existing_import_declaration_from_1: diag(90033, ts.DiagnosticCategory.Message, "Add_default_import_0_to_existing_import_declaration_from_1_90033", "Add default import '{0}' to existing import declaration from \"{1}\""), + Add_parameter_name: diag(90034, ts.DiagnosticCategory.Message, "Add_parameter_name_90034", "Add parameter name"), + Convert_function_to_an_ES2015_class: diag(95001, ts.DiagnosticCategory.Message, "Convert_function_to_an_ES2015_class_95001", "Convert function to an ES2015 class"), + Convert_function_0_to_class: diag(95002, ts.DiagnosticCategory.Message, "Convert_function_0_to_class_95002", "Convert function '{0}' to class"), + Extract_to_0_in_1: diag(95004, ts.DiagnosticCategory.Message, "Extract_to_0_in_1_95004", "Extract to {0} in {1}"), + Extract_function: diag(95005, ts.DiagnosticCategory.Message, "Extract_function_95005", "Extract function"), + Extract_constant: diag(95006, ts.DiagnosticCategory.Message, "Extract_constant_95006", "Extract constant"), + Extract_to_0_in_enclosing_scope: diag(95007, ts.DiagnosticCategory.Message, "Extract_to_0_in_enclosing_scope_95007", "Extract to {0} in enclosing scope"), + Extract_to_0_in_1_scope: diag(95008, ts.DiagnosticCategory.Message, "Extract_to_0_in_1_scope_95008", "Extract to {0} in {1} scope"), + Annotate_with_type_from_JSDoc: diag(95009, ts.DiagnosticCategory.Message, "Annotate_with_type_from_JSDoc_95009", "Annotate with type from JSDoc"), + Annotate_with_types_from_JSDoc: diag(95010, ts.DiagnosticCategory.Message, "Annotate_with_types_from_JSDoc_95010", "Annotate with types from JSDoc"), + Infer_type_of_0_from_usage: diag(95011, ts.DiagnosticCategory.Message, "Infer_type_of_0_from_usage_95011", "Infer type of '{0}' from usage"), + Infer_parameter_types_from_usage: diag(95012, ts.DiagnosticCategory.Message, "Infer_parameter_types_from_usage_95012", "Infer parameter types from usage"), + Convert_to_default_import: diag(95013, ts.DiagnosticCategory.Message, "Convert_to_default_import_95013", "Convert to default import"), + Install_0: diag(95014, ts.DiagnosticCategory.Message, "Install_0_95014", "Install '{0}'"), + Replace_import_with_0: diag(95015, ts.DiagnosticCategory.Message, "Replace_import_with_0_95015", "Replace import with '{0}'."), + Use_synthetic_default_member: diag(95016, ts.DiagnosticCategory.Message, "Use_synthetic_default_member_95016", "Use synthetic 'default' member."), + Convert_to_ES6_module: diag(95017, ts.DiagnosticCategory.Message, "Convert_to_ES6_module_95017", "Convert to ES6 module"), + Add_undefined_type_to_property_0: diag(95018, ts.DiagnosticCategory.Message, "Add_undefined_type_to_property_0_95018", "Add 'undefined' type to property '{0}'"), + Add_initializer_to_property_0: diag(95019, ts.DiagnosticCategory.Message, "Add_initializer_to_property_0_95019", "Add initializer to property '{0}'"), + Add_definite_assignment_assertion_to_property_0: diag(95020, ts.DiagnosticCategory.Message, "Add_definite_assignment_assertion_to_property_0_95020", "Add definite assignment assertion to property '{0}'"), + Add_all_missing_members: diag(95022, ts.DiagnosticCategory.Message, "Add_all_missing_members_95022", "Add all missing members"), + Infer_all_types_from_usage: diag(95023, ts.DiagnosticCategory.Message, "Infer_all_types_from_usage_95023", "Infer all types from usage"), + Delete_all_unused_declarations: diag(95024, ts.DiagnosticCategory.Message, "Delete_all_unused_declarations_95024", "Delete all unused declarations"), + Prefix_all_unused_declarations_with_where_possible: diag(95025, ts.DiagnosticCategory.Message, "Prefix_all_unused_declarations_with_where_possible_95025", "Prefix all unused declarations with '_' where possible"), + Fix_all_detected_spelling_errors: diag(95026, ts.DiagnosticCategory.Message, "Fix_all_detected_spelling_errors_95026", "Fix all detected spelling errors"), + Add_initializers_to_all_uninitialized_properties: diag(95027, ts.DiagnosticCategory.Message, "Add_initializers_to_all_uninitialized_properties_95027", "Add initializers to all uninitialized properties"), + Add_definite_assignment_assertions_to_all_uninitialized_properties: diag(95028, ts.DiagnosticCategory.Message, "Add_definite_assignment_assertions_to_all_uninitialized_properties_95028", "Add definite assignment assertions to all uninitialized properties"), + Add_undefined_type_to_all_uninitialized_properties: diag(95029, ts.DiagnosticCategory.Message, "Add_undefined_type_to_all_uninitialized_properties_95029", "Add undefined type to all uninitialized properties"), + Change_all_jsdoc_style_types_to_TypeScript: diag(95030, ts.DiagnosticCategory.Message, "Change_all_jsdoc_style_types_to_TypeScript_95030", "Change all jsdoc-style types to TypeScript"), + Change_all_jsdoc_style_types_to_TypeScript_and_add_undefined_to_nullable_types: diag(95031, ts.DiagnosticCategory.Message, "Change_all_jsdoc_style_types_to_TypeScript_and_add_undefined_to_nullable_types_95031", "Change all jsdoc-style types to TypeScript (and add '| undefined' to nullable types)"), + Implement_all_unimplemented_interfaces: diag(95032, ts.DiagnosticCategory.Message, "Implement_all_unimplemented_interfaces_95032", "Implement all unimplemented interfaces"), + Install_all_missing_types_packages: diag(95033, ts.DiagnosticCategory.Message, "Install_all_missing_types_packages_95033", "Install all missing types packages"), + Rewrite_all_as_indexed_access_types: diag(95034, ts.DiagnosticCategory.Message, "Rewrite_all_as_indexed_access_types_95034", "Rewrite all as indexed access types"), + Convert_all_to_default_imports: diag(95035, ts.DiagnosticCategory.Message, "Convert_all_to_default_imports_95035", "Convert all to default imports"), + Make_all_super_calls_the_first_statement_in_their_constructor: diag(95036, ts.DiagnosticCategory.Message, "Make_all_super_calls_the_first_statement_in_their_constructor_95036", "Make all 'super()' calls the first statement in their constructor"), + Add_qualifier_to_all_unresolved_variables_matching_a_member_name: diag(95037, ts.DiagnosticCategory.Message, "Add_qualifier_to_all_unresolved_variables_matching_a_member_name_95037", "Add qualifier to all unresolved variables matching a member name"), + Change_all_extended_interfaces_to_implements: diag(95038, ts.DiagnosticCategory.Message, "Change_all_extended_interfaces_to_implements_95038", "Change all extended interfaces to 'implements'"), + Add_all_missing_super_calls: diag(95039, ts.DiagnosticCategory.Message, "Add_all_missing_super_calls_95039", "Add all missing super calls"), + Implement_all_inherited_abstract_classes: diag(95040, ts.DiagnosticCategory.Message, "Implement_all_inherited_abstract_classes_95040", "Implement all inherited abstract classes"), + Add_all_missing_async_modifiers: diag(95041, ts.DiagnosticCategory.Message, "Add_all_missing_async_modifiers_95041", "Add all missing 'async' modifiers"), + Add_ts_ignore_to_all_error_messages: diag(95042, ts.DiagnosticCategory.Message, "Add_ts_ignore_to_all_error_messages_95042", "Add '@ts-ignore' to all error messages"), + Annotate_everything_with_types_from_JSDoc: diag(95043, ts.DiagnosticCategory.Message, "Annotate_everything_with_types_from_JSDoc_95043", "Annotate everything with types from JSDoc"), + Add_to_all_uncalled_decorators: diag(95044, ts.DiagnosticCategory.Message, "Add_to_all_uncalled_decorators_95044", "Add '()' to all uncalled decorators"), + Convert_all_constructor_functions_to_classes: diag(95045, ts.DiagnosticCategory.Message, "Convert_all_constructor_functions_to_classes_95045", "Convert all constructor functions to classes"), + Generate_get_and_set_accessors: diag(95046, ts.DiagnosticCategory.Message, "Generate_get_and_set_accessors_95046", "Generate 'get' and 'set' accessors"), + Convert_require_to_import: diag(95047, ts.DiagnosticCategory.Message, "Convert_require_to_import_95047", "Convert 'require' to 'import'"), + Convert_all_require_to_import: diag(95048, ts.DiagnosticCategory.Message, "Convert_all_require_to_import_95048", "Convert all 'require' to 'import'"), + Move_to_a_new_file: diag(95049, ts.DiagnosticCategory.Message, "Move_to_a_new_file_95049", "Move to a new file"), + Remove_unreachable_code: diag(95050, ts.DiagnosticCategory.Message, "Remove_unreachable_code_95050", "Remove unreachable code"), + Remove_all_unreachable_code: diag(95051, ts.DiagnosticCategory.Message, "Remove_all_unreachable_code_95051", "Remove all unreachable code"), + Add_missing_typeof: diag(95052, ts.DiagnosticCategory.Message, "Add_missing_typeof_95052", "Add missing 'typeof'"), + Remove_unused_label: diag(95053, ts.DiagnosticCategory.Message, "Remove_unused_label_95053", "Remove unused label"), + Remove_all_unused_labels: diag(95054, ts.DiagnosticCategory.Message, "Remove_all_unused_labels_95054", "Remove all unused labels"), + Convert_0_to_mapped_object_type: diag(95055, ts.DiagnosticCategory.Message, "Convert_0_to_mapped_object_type_95055", "Convert '{0}' to mapped object type"), + Convert_namespace_import_to_named_imports: diag(95056, ts.DiagnosticCategory.Message, "Convert_namespace_import_to_named_imports_95056", "Convert namespace import to named imports"), + Convert_named_imports_to_namespace_import: diag(95057, ts.DiagnosticCategory.Message, "Convert_named_imports_to_namespace_import_95057", "Convert named imports to namespace import"), + Add_or_remove_braces_in_an_arrow_function: diag(95058, ts.DiagnosticCategory.Message, "Add_or_remove_braces_in_an_arrow_function_95058", "Add or remove braces in an arrow function"), + Add_braces_to_arrow_function: diag(95059, ts.DiagnosticCategory.Message, "Add_braces_to_arrow_function_95059", "Add braces to arrow function"), + Remove_braces_from_arrow_function: diag(95060, ts.DiagnosticCategory.Message, "Remove_braces_from_arrow_function_95060", "Remove braces from arrow function"), + Convert_default_export_to_named_export: diag(95061, ts.DiagnosticCategory.Message, "Convert_default_export_to_named_export_95061", "Convert default export to named export"), + Convert_named_export_to_default_export: diag(95062, ts.DiagnosticCategory.Message, "Convert_named_export_to_default_export_95062", "Convert named export to default export"), + Add_missing_enum_member_0: diag(95063, ts.DiagnosticCategory.Message, "Add_missing_enum_member_0_95063", "Add missing enum member '{0}'"), + Add_all_missing_imports: diag(95064, ts.DiagnosticCategory.Message, "Add_all_missing_imports_95064", "Add all missing imports"), + Convert_to_async_function: diag(95065, ts.DiagnosticCategory.Message, "Convert_to_async_function_95065", "Convert to async function"), + Convert_all_to_async_functions: diag(95066, ts.DiagnosticCategory.Message, "Convert_all_to_async_functions_95066", "Convert all to async functions"), + Generate_types_for_0: diag(95067, ts.DiagnosticCategory.Message, "Generate_types_for_0_95067", "Generate types for '{0}'"), + Generate_types_for_all_packages_without_types: diag(95068, ts.DiagnosticCategory.Message, "Generate_types_for_all_packages_without_types_95068", "Generate types for all packages without types"), + Add_unknown_conversion_for_non_overlapping_types: diag(95069, ts.DiagnosticCategory.Message, "Add_unknown_conversion_for_non_overlapping_types_95069", "Add 'unknown' conversion for non-overlapping types"), + Add_unknown_to_all_conversions_of_non_overlapping_types: diag(95070, ts.DiagnosticCategory.Message, "Add_unknown_to_all_conversions_of_non_overlapping_types_95070", "Add 'unknown' to all conversions of non-overlapping types"), + Add_missing_new_operator_to_call: diag(95071, ts.DiagnosticCategory.Message, "Add_missing_new_operator_to_call_95071", "Add missing 'new' operator to call"), + Add_missing_new_operator_to_all_calls: diag(95072, ts.DiagnosticCategory.Message, "Add_missing_new_operator_to_all_calls_95072", "Add missing 'new' operator to all calls"), + Add_names_to_all_parameters_without_names: diag(95073, ts.DiagnosticCategory.Message, "Add_names_to_all_parameters_without_names_95073", "Add names to all parameters without names"), + }; +})(ts || (ts = {})); +var ts; +(function (ts) { + var _a; + /* @internal */ + function tokenIsIdentifierOrKeyword(token) { + return token >= 72 /* Identifier */; + } + ts.tokenIsIdentifierOrKeyword = tokenIsIdentifierOrKeyword; + /* @internal */ + function tokenIsIdentifierOrKeywordOrGreaterThan(token) { + return token === 30 /* GreaterThanToken */ || tokenIsIdentifierOrKeyword(token); + } + ts.tokenIsIdentifierOrKeywordOrGreaterThan = tokenIsIdentifierOrKeywordOrGreaterThan; + var textToKeywordObj = (_a = { + abstract: 118 /* AbstractKeyword */, + any: 120 /* AnyKeyword */, + as: 119 /* AsKeyword */, + bigint: 146 /* BigIntKeyword */, + boolean: 123 /* BooleanKeyword */, + break: 73 /* BreakKeyword */, + case: 74 /* CaseKeyword */, + catch: 75 /* CatchKeyword */, + class: 76 /* ClassKeyword */, + continue: 78 /* ContinueKeyword */, + const: 77 /* ConstKeyword */ + }, + _a["" + "constructor"] = 124 /* ConstructorKeyword */, + _a.debugger = 79 /* DebuggerKeyword */, + _a.declare = 125 /* DeclareKeyword */, + _a.default = 80 /* DefaultKeyword */, + _a.delete = 81 /* DeleteKeyword */, + _a.do = 82 /* DoKeyword */, + _a.else = 83 /* ElseKeyword */, + _a.enum = 84 /* EnumKeyword */, + _a.export = 85 /* ExportKeyword */, + _a.extends = 86 /* ExtendsKeyword */, + _a.false = 87 /* FalseKeyword */, + _a.finally = 88 /* FinallyKeyword */, + _a.for = 89 /* ForKeyword */, + _a.from = 144 /* FromKeyword */, + _a.function = 90 /* FunctionKeyword */, + _a.get = 126 /* GetKeyword */, + _a.if = 91 /* IfKeyword */, + _a.implements = 109 /* ImplementsKeyword */, + _a.import = 92 /* ImportKeyword */, + _a.in = 93 /* InKeyword */, + _a.infer = 127 /* InferKeyword */, + _a.instanceof = 94 /* InstanceOfKeyword */, + _a.interface = 110 /* InterfaceKeyword */, + _a.is = 128 /* IsKeyword */, + _a.keyof = 129 /* KeyOfKeyword */, + _a.let = 111 /* LetKeyword */, + _a.module = 130 /* ModuleKeyword */, + _a.namespace = 131 /* NamespaceKeyword */, + _a.never = 132 /* NeverKeyword */, + _a.new = 95 /* NewKeyword */, + _a.null = 96 /* NullKeyword */, + _a.number = 135 /* NumberKeyword */, + _a.object = 136 /* ObjectKeyword */, + _a.package = 112 /* PackageKeyword */, + _a.private = 113 /* PrivateKeyword */, + _a.protected = 114 /* ProtectedKeyword */, + _a.public = 115 /* PublicKeyword */, + _a.readonly = 133 /* ReadonlyKeyword */, + _a.require = 134 /* RequireKeyword */, + _a.global = 145 /* GlobalKeyword */, + _a.return = 97 /* ReturnKeyword */, + _a.set = 137 /* SetKeyword */, + _a.static = 116 /* StaticKeyword */, + _a.string = 138 /* StringKeyword */, + _a.super = 98 /* SuperKeyword */, + _a.switch = 99 /* SwitchKeyword */, + _a.symbol = 139 /* SymbolKeyword */, + _a.this = 100 /* ThisKeyword */, + _a.throw = 101 /* ThrowKeyword */, + _a.true = 102 /* TrueKeyword */, + _a.try = 103 /* TryKeyword */, + _a.type = 140 /* TypeKeyword */, + _a.typeof = 104 /* TypeOfKeyword */, + _a.undefined = 141 /* UndefinedKeyword */, + _a.unique = 142 /* UniqueKeyword */, + _a.unknown = 143 /* UnknownKeyword */, + _a.var = 105 /* VarKeyword */, + _a.void = 106 /* VoidKeyword */, + _a.while = 107 /* WhileKeyword */, + _a.with = 108 /* WithKeyword */, + _a.yield = 117 /* YieldKeyword */, + _a.async = 121 /* AsyncKeyword */, + _a.await = 122 /* AwaitKeyword */, + _a.of = 147 /* OfKeyword */, + _a); + var textToKeyword = ts.createMapFromTemplate(textToKeywordObj); + var textToToken = ts.createMapFromTemplate(__assign({}, textToKeywordObj, { "{": 18 /* OpenBraceToken */, "}": 19 /* CloseBraceToken */, "(": 20 /* OpenParenToken */, ")": 21 /* CloseParenToken */, "[": 22 /* OpenBracketToken */, "]": 23 /* CloseBracketToken */, ".": 24 /* DotToken */, "...": 25 /* DotDotDotToken */, ";": 26 /* SemicolonToken */, ",": 27 /* CommaToken */, "<": 28 /* LessThanToken */, ">": 30 /* GreaterThanToken */, "<=": 31 /* LessThanEqualsToken */, ">=": 32 /* GreaterThanEqualsToken */, "==": 33 /* EqualsEqualsToken */, "!=": 34 /* ExclamationEqualsToken */, "===": 35 /* EqualsEqualsEqualsToken */, "!==": 36 /* ExclamationEqualsEqualsToken */, "=>": 37 /* EqualsGreaterThanToken */, "+": 38 /* PlusToken */, "-": 39 /* MinusToken */, "**": 41 /* AsteriskAsteriskToken */, "*": 40 /* AsteriskToken */, "/": 42 /* SlashToken */, "%": 43 /* PercentToken */, "++": 44 /* PlusPlusToken */, "--": 45 /* MinusMinusToken */, "<<": 46 /* LessThanLessThanToken */, ">": 47 /* GreaterThanGreaterThanToken */, ">>>": 48 /* GreaterThanGreaterThanGreaterThanToken */, "&": 49 /* AmpersandToken */, "|": 50 /* BarToken */, "^": 51 /* CaretToken */, "!": 52 /* ExclamationToken */, "~": 53 /* TildeToken */, "&&": 54 /* AmpersandAmpersandToken */, "||": 55 /* BarBarToken */, "?": 56 /* QuestionToken */, ":": 57 /* ColonToken */, "=": 59 /* EqualsToken */, "+=": 60 /* PlusEqualsToken */, "-=": 61 /* MinusEqualsToken */, "*=": 62 /* AsteriskEqualsToken */, "**=": 63 /* AsteriskAsteriskEqualsToken */, "/=": 64 /* SlashEqualsToken */, "%=": 65 /* PercentEqualsToken */, "<<=": 66 /* LessThanLessThanEqualsToken */, ">>=": 67 /* GreaterThanGreaterThanEqualsToken */, ">>>=": 68 /* GreaterThanGreaterThanGreaterThanEqualsToken */, "&=": 69 /* AmpersandEqualsToken */, "|=": 70 /* BarEqualsToken */, "^=": 71 /* CaretEqualsToken */, "@": 58 /* AtToken */ })); + /* + As per ECMAScript Language Specification 3th Edition, Section 7.6: Identifiers + IdentifierStart :: + Can contain Unicode 3.0.0 categories: + Uppercase letter (Lu), + Lowercase letter (Ll), + Titlecase letter (Lt), + Modifier letter (Lm), + Other letter (Lo), or + Letter number (Nl). + IdentifierPart :: = + Can contain IdentifierStart + Unicode 3.0.0 categories: + Non-spacing mark (Mn), + Combining spacing mark (Mc), + Decimal number (Nd), or + Connector punctuation (Pc). + + Codepoint ranges for ES3 Identifiers are extracted from the Unicode 3.0.0 specification at: + http://www.unicode.org/Public/3.0-Update/UnicodeData-3.0.0.txt + */ + var unicodeES3IdentifierStart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 543, 546, 563, 592, 685, 688, 696, 699, 705, 720, 721, 736, 740, 750, 750, 890, 890, 902, 902, 904, 906, 908, 908, 910, 929, 931, 974, 976, 983, 986, 1011, 1024, 1153, 1164, 1220, 1223, 1224, 1227, 1228, 1232, 1269, 1272, 1273, 1329, 1366, 1369, 1369, 1377, 1415, 1488, 1514, 1520, 1522, 1569, 1594, 1600, 1610, 1649, 1747, 1749, 1749, 1765, 1766, 1786, 1788, 1808, 1808, 1810, 1836, 1920, 1957, 2309, 2361, 2365, 2365, 2384, 2384, 2392, 2401, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2524, 2525, 2527, 2529, 2544, 2545, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2649, 2652, 2654, 2654, 2674, 2676, 2693, 2699, 2701, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2749, 2749, 2768, 2768, 2784, 2784, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2870, 2873, 2877, 2877, 2908, 2909, 2911, 2913, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 2997, 2999, 3001, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3168, 3169, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3294, 3294, 3296, 3297, 3333, 3340, 3342, 3344, 3346, 3368, 3370, 3385, 3424, 3425, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3585, 3632, 3634, 3635, 3648, 3654, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3760, 3762, 3763, 3773, 3773, 3776, 3780, 3782, 3782, 3804, 3805, 3840, 3840, 3904, 3911, 3913, 3946, 3976, 3979, 4096, 4129, 4131, 4135, 4137, 4138, 4176, 4181, 4256, 4293, 4304, 4342, 4352, 4441, 4447, 4514, 4520, 4601, 4608, 4614, 4616, 4678, 4680, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4742, 4744, 4744, 4746, 4749, 4752, 4782, 4784, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4814, 4816, 4822, 4824, 4846, 4848, 4878, 4880, 4880, 4882, 4885, 4888, 4894, 4896, 4934, 4936, 4954, 5024, 5108, 5121, 5740, 5743, 5750, 5761, 5786, 5792, 5866, 6016, 6067, 6176, 6263, 6272, 6312, 7680, 7835, 7840, 7929, 7936, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8319, 8319, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8497, 8499, 8505, 8544, 8579, 12293, 12295, 12321, 12329, 12337, 12341, 12344, 12346, 12353, 12436, 12445, 12446, 12449, 12538, 12540, 12542, 12549, 12588, 12593, 12686, 12704, 12727, 13312, 19893, 19968, 40869, 40960, 42124, 44032, 55203, 63744, 64045, 64256, 64262, 64275, 64279, 64285, 64285, 64287, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65136, 65138, 65140, 65140, 65142, 65276, 65313, 65338, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500,]; + var unicodeES3IdentifierPart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 543, 546, 563, 592, 685, 688, 696, 699, 705, 720, 721, 736, 740, 750, 750, 768, 846, 864, 866, 890, 890, 902, 902, 904, 906, 908, 908, 910, 929, 931, 974, 976, 983, 986, 1011, 1024, 1153, 1155, 1158, 1164, 1220, 1223, 1224, 1227, 1228, 1232, 1269, 1272, 1273, 1329, 1366, 1369, 1369, 1377, 1415, 1425, 1441, 1443, 1465, 1467, 1469, 1471, 1471, 1473, 1474, 1476, 1476, 1488, 1514, 1520, 1522, 1569, 1594, 1600, 1621, 1632, 1641, 1648, 1747, 1749, 1756, 1759, 1768, 1770, 1773, 1776, 1788, 1808, 1836, 1840, 1866, 1920, 1968, 2305, 2307, 2309, 2361, 2364, 2381, 2384, 2388, 2392, 2403, 2406, 2415, 2433, 2435, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2492, 2492, 2494, 2500, 2503, 2504, 2507, 2509, 2519, 2519, 2524, 2525, 2527, 2531, 2534, 2545, 2562, 2562, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2620, 2620, 2622, 2626, 2631, 2632, 2635, 2637, 2649, 2652, 2654, 2654, 2662, 2676, 2689, 2691, 2693, 2699, 2701, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2748, 2757, 2759, 2761, 2763, 2765, 2768, 2768, 2784, 2784, 2790, 2799, 2817, 2819, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2870, 2873, 2876, 2883, 2887, 2888, 2891, 2893, 2902, 2903, 2908, 2909, 2911, 2913, 2918, 2927, 2946, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 2997, 2999, 3001, 3006, 3010, 3014, 3016, 3018, 3021, 3031, 3031, 3047, 3055, 3073, 3075, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3134, 3140, 3142, 3144, 3146, 3149, 3157, 3158, 3168, 3169, 3174, 3183, 3202, 3203, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3262, 3268, 3270, 3272, 3274, 3277, 3285, 3286, 3294, 3294, 3296, 3297, 3302, 3311, 3330, 3331, 3333, 3340, 3342, 3344, 3346, 3368, 3370, 3385, 3390, 3395, 3398, 3400, 3402, 3405, 3415, 3415, 3424, 3425, 3430, 3439, 3458, 3459, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3530, 3530, 3535, 3540, 3542, 3542, 3544, 3551, 3570, 3571, 3585, 3642, 3648, 3662, 3664, 3673, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3769, 3771, 3773, 3776, 3780, 3782, 3782, 3784, 3789, 3792, 3801, 3804, 3805, 3840, 3840, 3864, 3865, 3872, 3881, 3893, 3893, 3895, 3895, 3897, 3897, 3902, 3911, 3913, 3946, 3953, 3972, 3974, 3979, 3984, 3991, 3993, 4028, 4038, 4038, 4096, 4129, 4131, 4135, 4137, 4138, 4140, 4146, 4150, 4153, 4160, 4169, 4176, 4185, 4256, 4293, 4304, 4342, 4352, 4441, 4447, 4514, 4520, 4601, 4608, 4614, 4616, 4678, 4680, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4742, 4744, 4744, 4746, 4749, 4752, 4782, 4784, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4814, 4816, 4822, 4824, 4846, 4848, 4878, 4880, 4880, 4882, 4885, 4888, 4894, 4896, 4934, 4936, 4954, 4969, 4977, 5024, 5108, 5121, 5740, 5743, 5750, 5761, 5786, 5792, 5866, 6016, 6099, 6112, 6121, 6160, 6169, 6176, 6263, 6272, 6313, 7680, 7835, 7840, 7929, 7936, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8255, 8256, 8319, 8319, 8400, 8412, 8417, 8417, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8497, 8499, 8505, 8544, 8579, 12293, 12295, 12321, 12335, 12337, 12341, 12344, 12346, 12353, 12436, 12441, 12442, 12445, 12446, 12449, 12542, 12549, 12588, 12593, 12686, 12704, 12727, 13312, 19893, 19968, 40869, 40960, 42124, 44032, 55203, 63744, 64045, 64256, 64262, 64275, 64279, 64285, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65056, 65059, 65075, 65076, 65101, 65103, 65136, 65138, 65140, 65140, 65142, 65276, 65296, 65305, 65313, 65338, 65343, 65343, 65345, 65370, 65381, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500,]; + /* + As per ECMAScript Language Specification 5th Edition, Section 7.6: ISyntaxToken Names and Identifiers + IdentifierStart :: + Can contain Unicode 6.2 categories: + Uppercase letter (Lu), + Lowercase letter (Ll), + Titlecase letter (Lt), + Modifier letter (Lm), + Other letter (Lo), or + Letter number (Nl). + IdentifierPart :: + Can contain IdentifierStart + Unicode 6.2 categories: + Non-spacing mark (Mn), + Combining spacing mark (Mc), + Decimal number (Nd), + Connector punctuation (Pc), + , or + . + + Codepoint ranges for ES5 Identifiers are extracted from the Unicode 6.2 specification at: + http://www.unicode.org/Public/6.2.0/ucd/UnicodeData.txt + */ + var unicodeES5IdentifierStart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 705, 710, 721, 736, 740, 748, 748, 750, 750, 880, 884, 886, 887, 890, 893, 902, 902, 904, 906, 908, 908, 910, 929, 931, 1013, 1015, 1153, 1162, 1319, 1329, 1366, 1369, 1369, 1377, 1415, 1488, 1514, 1520, 1522, 1568, 1610, 1646, 1647, 1649, 1747, 1749, 1749, 1765, 1766, 1774, 1775, 1786, 1788, 1791, 1791, 1808, 1808, 1810, 1839, 1869, 1957, 1969, 1969, 1994, 2026, 2036, 2037, 2042, 2042, 2048, 2069, 2074, 2074, 2084, 2084, 2088, 2088, 2112, 2136, 2208, 2208, 2210, 2220, 2308, 2361, 2365, 2365, 2384, 2384, 2392, 2401, 2417, 2423, 2425, 2431, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2493, 2493, 2510, 2510, 2524, 2525, 2527, 2529, 2544, 2545, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2649, 2652, 2654, 2654, 2674, 2676, 2693, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2749, 2749, 2768, 2768, 2784, 2785, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2869, 2873, 2877, 2877, 2908, 2909, 2911, 2913, 2929, 2929, 2947, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 3001, 3024, 3024, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3133, 3133, 3160, 3161, 3168, 3169, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3261, 3261, 3294, 3294, 3296, 3297, 3313, 3314, 3333, 3340, 3342, 3344, 3346, 3386, 3389, 3389, 3406, 3406, 3424, 3425, 3450, 3455, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3585, 3632, 3634, 3635, 3648, 3654, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3760, 3762, 3763, 3773, 3773, 3776, 3780, 3782, 3782, 3804, 3807, 3840, 3840, 3904, 3911, 3913, 3948, 3976, 3980, 4096, 4138, 4159, 4159, 4176, 4181, 4186, 4189, 4193, 4193, 4197, 4198, 4206, 4208, 4213, 4225, 4238, 4238, 4256, 4293, 4295, 4295, 4301, 4301, 4304, 4346, 4348, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4744, 4746, 4749, 4752, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4822, 4824, 4880, 4882, 4885, 4888, 4954, 4992, 5007, 5024, 5108, 5121, 5740, 5743, 5759, 5761, 5786, 5792, 5866, 5870, 5872, 5888, 5900, 5902, 5905, 5920, 5937, 5952, 5969, 5984, 5996, 5998, 6000, 6016, 6067, 6103, 6103, 6108, 6108, 6176, 6263, 6272, 6312, 6314, 6314, 6320, 6389, 6400, 6428, 6480, 6509, 6512, 6516, 6528, 6571, 6593, 6599, 6656, 6678, 6688, 6740, 6823, 6823, 6917, 6963, 6981, 6987, 7043, 7072, 7086, 7087, 7098, 7141, 7168, 7203, 7245, 7247, 7258, 7293, 7401, 7404, 7406, 7409, 7413, 7414, 7424, 7615, 7680, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8305, 8305, 8319, 8319, 8336, 8348, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8505, 8508, 8511, 8517, 8521, 8526, 8526, 8544, 8584, 11264, 11310, 11312, 11358, 11360, 11492, 11499, 11502, 11506, 11507, 11520, 11557, 11559, 11559, 11565, 11565, 11568, 11623, 11631, 11631, 11648, 11670, 11680, 11686, 11688, 11694, 11696, 11702, 11704, 11710, 11712, 11718, 11720, 11726, 11728, 11734, 11736, 11742, 11823, 11823, 12293, 12295, 12321, 12329, 12337, 12341, 12344, 12348, 12353, 12438, 12445, 12447, 12449, 12538, 12540, 12543, 12549, 12589, 12593, 12686, 12704, 12730, 12784, 12799, 13312, 19893, 19968, 40908, 40960, 42124, 42192, 42237, 42240, 42508, 42512, 42527, 42538, 42539, 42560, 42606, 42623, 42647, 42656, 42735, 42775, 42783, 42786, 42888, 42891, 42894, 42896, 42899, 42912, 42922, 43000, 43009, 43011, 43013, 43015, 43018, 43020, 43042, 43072, 43123, 43138, 43187, 43250, 43255, 43259, 43259, 43274, 43301, 43312, 43334, 43360, 43388, 43396, 43442, 43471, 43471, 43520, 43560, 43584, 43586, 43588, 43595, 43616, 43638, 43642, 43642, 43648, 43695, 43697, 43697, 43701, 43702, 43705, 43709, 43712, 43712, 43714, 43714, 43739, 43741, 43744, 43754, 43762, 43764, 43777, 43782, 43785, 43790, 43793, 43798, 43808, 43814, 43816, 43822, 43968, 44002, 44032, 55203, 55216, 55238, 55243, 55291, 63744, 64109, 64112, 64217, 64256, 64262, 64275, 64279, 64285, 64285, 64287, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65136, 65140, 65142, 65276, 65313, 65338, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500,]; + var unicodeES5IdentifierPart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 705, 710, 721, 736, 740, 748, 748, 750, 750, 768, 884, 886, 887, 890, 893, 902, 902, 904, 906, 908, 908, 910, 929, 931, 1013, 1015, 1153, 1155, 1159, 1162, 1319, 1329, 1366, 1369, 1369, 1377, 1415, 1425, 1469, 1471, 1471, 1473, 1474, 1476, 1477, 1479, 1479, 1488, 1514, 1520, 1522, 1552, 1562, 1568, 1641, 1646, 1747, 1749, 1756, 1759, 1768, 1770, 1788, 1791, 1791, 1808, 1866, 1869, 1969, 1984, 2037, 2042, 2042, 2048, 2093, 2112, 2139, 2208, 2208, 2210, 2220, 2276, 2302, 2304, 2403, 2406, 2415, 2417, 2423, 2425, 2431, 2433, 2435, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2492, 2500, 2503, 2504, 2507, 2510, 2519, 2519, 2524, 2525, 2527, 2531, 2534, 2545, 2561, 2563, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2620, 2620, 2622, 2626, 2631, 2632, 2635, 2637, 2641, 2641, 2649, 2652, 2654, 2654, 2662, 2677, 2689, 2691, 2693, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2748, 2757, 2759, 2761, 2763, 2765, 2768, 2768, 2784, 2787, 2790, 2799, 2817, 2819, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2869, 2873, 2876, 2884, 2887, 2888, 2891, 2893, 2902, 2903, 2908, 2909, 2911, 2915, 2918, 2927, 2929, 2929, 2946, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 3001, 3006, 3010, 3014, 3016, 3018, 3021, 3024, 3024, 3031, 3031, 3046, 3055, 3073, 3075, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3133, 3140, 3142, 3144, 3146, 3149, 3157, 3158, 3160, 3161, 3168, 3171, 3174, 3183, 3202, 3203, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3260, 3268, 3270, 3272, 3274, 3277, 3285, 3286, 3294, 3294, 3296, 3299, 3302, 3311, 3313, 3314, 3330, 3331, 3333, 3340, 3342, 3344, 3346, 3386, 3389, 3396, 3398, 3400, 3402, 3406, 3415, 3415, 3424, 3427, 3430, 3439, 3450, 3455, 3458, 3459, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3530, 3530, 3535, 3540, 3542, 3542, 3544, 3551, 3570, 3571, 3585, 3642, 3648, 3662, 3664, 3673, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3769, 3771, 3773, 3776, 3780, 3782, 3782, 3784, 3789, 3792, 3801, 3804, 3807, 3840, 3840, 3864, 3865, 3872, 3881, 3893, 3893, 3895, 3895, 3897, 3897, 3902, 3911, 3913, 3948, 3953, 3972, 3974, 3991, 3993, 4028, 4038, 4038, 4096, 4169, 4176, 4253, 4256, 4293, 4295, 4295, 4301, 4301, 4304, 4346, 4348, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4744, 4746, 4749, 4752, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4822, 4824, 4880, 4882, 4885, 4888, 4954, 4957, 4959, 4992, 5007, 5024, 5108, 5121, 5740, 5743, 5759, 5761, 5786, 5792, 5866, 5870, 5872, 5888, 5900, 5902, 5908, 5920, 5940, 5952, 5971, 5984, 5996, 5998, 6000, 6002, 6003, 6016, 6099, 6103, 6103, 6108, 6109, 6112, 6121, 6155, 6157, 6160, 6169, 6176, 6263, 6272, 6314, 6320, 6389, 6400, 6428, 6432, 6443, 6448, 6459, 6470, 6509, 6512, 6516, 6528, 6571, 6576, 6601, 6608, 6617, 6656, 6683, 6688, 6750, 6752, 6780, 6783, 6793, 6800, 6809, 6823, 6823, 6912, 6987, 6992, 7001, 7019, 7027, 7040, 7155, 7168, 7223, 7232, 7241, 7245, 7293, 7376, 7378, 7380, 7414, 7424, 7654, 7676, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8204, 8205, 8255, 8256, 8276, 8276, 8305, 8305, 8319, 8319, 8336, 8348, 8400, 8412, 8417, 8417, 8421, 8432, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8505, 8508, 8511, 8517, 8521, 8526, 8526, 8544, 8584, 11264, 11310, 11312, 11358, 11360, 11492, 11499, 11507, 11520, 11557, 11559, 11559, 11565, 11565, 11568, 11623, 11631, 11631, 11647, 11670, 11680, 11686, 11688, 11694, 11696, 11702, 11704, 11710, 11712, 11718, 11720, 11726, 11728, 11734, 11736, 11742, 11744, 11775, 11823, 11823, 12293, 12295, 12321, 12335, 12337, 12341, 12344, 12348, 12353, 12438, 12441, 12442, 12445, 12447, 12449, 12538, 12540, 12543, 12549, 12589, 12593, 12686, 12704, 12730, 12784, 12799, 13312, 19893, 19968, 40908, 40960, 42124, 42192, 42237, 42240, 42508, 42512, 42539, 42560, 42607, 42612, 42621, 42623, 42647, 42655, 42737, 42775, 42783, 42786, 42888, 42891, 42894, 42896, 42899, 42912, 42922, 43000, 43047, 43072, 43123, 43136, 43204, 43216, 43225, 43232, 43255, 43259, 43259, 43264, 43309, 43312, 43347, 43360, 43388, 43392, 43456, 43471, 43481, 43520, 43574, 43584, 43597, 43600, 43609, 43616, 43638, 43642, 43643, 43648, 43714, 43739, 43741, 43744, 43759, 43762, 43766, 43777, 43782, 43785, 43790, 43793, 43798, 43808, 43814, 43816, 43822, 43968, 44010, 44012, 44013, 44016, 44025, 44032, 55203, 55216, 55238, 55243, 55291, 63744, 64109, 64112, 64217, 64256, 64262, 64275, 64279, 64285, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65024, 65039, 65056, 65062, 65075, 65076, 65101, 65103, 65136, 65140, 65142, 65276, 65296, 65305, 65313, 65338, 65343, 65343, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500,]; + function lookupInUnicodeMap(code, map) { + // Bail out quickly if it couldn't possibly be in the map. + if (code < map[0]) { + return false; + } + // Perform binary search in one of the Unicode range maps + var lo = 0; + var hi = map.length; + var mid; + while (lo + 1 < hi) { + mid = lo + (hi - lo) / 2; + // mid has to be even to catch a range's beginning + mid -= mid % 2; + if (map[mid] <= code && code <= map[mid + 1]) { + return true; + } + if (code < map[mid]) { + hi = mid; + } + else { + lo = mid + 2; + } + } + return false; + } + /* @internal */ function isUnicodeIdentifierStart(code, languageVersion) { + return languageVersion >= 1 /* ES5 */ ? + lookupInUnicodeMap(code, unicodeES5IdentifierStart) : + lookupInUnicodeMap(code, unicodeES3IdentifierStart); + } + ts.isUnicodeIdentifierStart = isUnicodeIdentifierStart; + function isUnicodeIdentifierPart(code, languageVersion) { + return languageVersion >= 1 /* ES5 */ ? + lookupInUnicodeMap(code, unicodeES5IdentifierPart) : + lookupInUnicodeMap(code, unicodeES3IdentifierPart); + } + function makeReverseMap(source) { + var result = []; + source.forEach(function (value, name) { + result[value] = name; + }); + return result; + } + var tokenStrings = makeReverseMap(textToToken); + function tokenToString(t) { + return tokenStrings[t]; + } + ts.tokenToString = tokenToString; + /* @internal */ + function stringToToken(s) { + return textToToken.get(s); + } + ts.stringToToken = stringToToken; + /* @internal */ + function computeLineStarts(text) { + var result = new Array(); + var pos = 0; + var lineStart = 0; + while (pos < text.length) { + var ch = text.charCodeAt(pos); + pos++; + switch (ch) { + case 13 /* carriageReturn */: + if (text.charCodeAt(pos) === 10 /* lineFeed */) { + pos++; + } + // falls through + case 10 /* lineFeed */: + result.push(lineStart); + lineStart = pos; + break; + default: + if (ch > 127 /* maxAsciiCharacter */ && isLineBreak(ch)) { + result.push(lineStart); + lineStart = pos; + } + break; + } + } + result.push(lineStart); + return result; + } + ts.computeLineStarts = computeLineStarts; + function getPositionOfLineAndCharacter(sourceFile, line, character) { + return computePositionOfLineAndCharacter(getLineStarts(sourceFile), line, character, sourceFile.text); + } + ts.getPositionOfLineAndCharacter = getPositionOfLineAndCharacter; + /* @internal */ + function getPositionOfLineAndCharacterWithEdits(sourceFile, line, character) { + return computePositionOfLineAndCharacter(getLineStarts(sourceFile), line, character, sourceFile.text, /*allowEdits*/ true); + } + ts.getPositionOfLineAndCharacterWithEdits = getPositionOfLineAndCharacterWithEdits; + /* @internal */ + function computePositionOfLineAndCharacter(lineStarts, line, character, debugText, allowEdits) { + if (line < 0 || line >= lineStarts.length) { + if (allowEdits) { + // Clamp line to nearest allowable value + line = line < 0 ? 0 : line >= lineStarts.length ? lineStarts.length - 1 : line; + } + else { + ts.Debug.fail("Bad line number. Line: " + line + ", lineStarts.length: " + lineStarts.length + " , line map is correct? " + (debugText !== undefined ? ts.arraysEqual(lineStarts, computeLineStarts(debugText)) : "unknown")); + } + } + var res = lineStarts[line] + character; + if (allowEdits) { + // Clamp to nearest allowable values to allow the underlying to be edited without crashing (accuracy is lost, instead) + // TODO: Somehow track edits between file as it was during the creation of sourcemap we have and the current file and + // apply them to the computed position to improve accuracy + return res > lineStarts[line + 1] ? lineStarts[line + 1] : typeof debugText === "string" && res > debugText.length ? debugText.length : res; + } + if (line < lineStarts.length - 1) { + ts.Debug.assert(res < lineStarts[line + 1]); + } + else if (debugText !== undefined) { + ts.Debug.assert(res <= debugText.length); // Allow single character overflow for trailing newline + } + return res; + } + ts.computePositionOfLineAndCharacter = computePositionOfLineAndCharacter; + /* @internal */ + function getLineStarts(sourceFile) { + return sourceFile.lineMap || (sourceFile.lineMap = computeLineStarts(sourceFile.text)); + } + ts.getLineStarts = getLineStarts; + /* @internal */ + /** + * We assume the first line starts at position 0 and 'position' is non-negative. + */ + function computeLineAndCharacterOfPosition(lineStarts, position) { + var lineNumber = ts.binarySearch(lineStarts, position, ts.identity, ts.compareValues); + if (lineNumber < 0) { + // If the actual position was not found, + // the binary search returns the 2's-complement of the next line start + // e.g. if the line starts at [5, 10, 23, 80] and the position requested was 20 + // then the search will return -2. + // + // We want the index of the previous line start, so we subtract 1. + // Review 2's-complement if this is confusing. + lineNumber = ~lineNumber - 1; + ts.Debug.assert(lineNumber !== -1, "position cannot precede the beginning of the file"); + } + return { + line: lineNumber, + character: position - lineStarts[lineNumber] + }; + } + ts.computeLineAndCharacterOfPosition = computeLineAndCharacterOfPosition; + function getLineAndCharacterOfPosition(sourceFile, position) { + return computeLineAndCharacterOfPosition(getLineStarts(sourceFile), position); + } + ts.getLineAndCharacterOfPosition = getLineAndCharacterOfPosition; + function isWhiteSpaceLike(ch) { + return isWhiteSpaceSingleLine(ch) || isLineBreak(ch); + } + ts.isWhiteSpaceLike = isWhiteSpaceLike; + /** Does not include line breaks. For that, see isWhiteSpaceLike. */ + function isWhiteSpaceSingleLine(ch) { + // Note: nextLine is in the Zs space, and should be considered to be a whitespace. + // It is explicitly not a line-break as it isn't in the exact set specified by EcmaScript. + return ch === 32 /* space */ || + ch === 9 /* tab */ || + ch === 11 /* verticalTab */ || + ch === 12 /* formFeed */ || + ch === 160 /* nonBreakingSpace */ || + ch === 133 /* nextLine */ || + ch === 5760 /* ogham */ || + ch >= 8192 /* enQuad */ && ch <= 8203 /* zeroWidthSpace */ || + ch === 8239 /* narrowNoBreakSpace */ || + ch === 8287 /* mathematicalSpace */ || + ch === 12288 /* ideographicSpace */ || + ch === 65279 /* byteOrderMark */; + } + ts.isWhiteSpaceSingleLine = isWhiteSpaceSingleLine; + function isLineBreak(ch) { + // ES5 7.3: + // The ECMAScript line terminator characters are listed in Table 3. + // Table 3: Line Terminator Characters + // Code Unit Value Name Formal Name + // \u000A Line Feed + // \u000D Carriage Return + // \u2028 Line separator + // \u2029 Paragraph separator + // Only the characters in Table 3 are treated as line terminators. Other new line or line + // breaking characters are treated as white space but not as line terminators. + return ch === 10 /* lineFeed */ || + ch === 13 /* carriageReturn */ || + ch === 8232 /* lineSeparator */ || + ch === 8233 /* paragraphSeparator */; + } + ts.isLineBreak = isLineBreak; + function isDigit(ch) { + return ch >= 48 /* _0 */ && ch <= 57 /* _9 */; + } + /* @internal */ + function isOctalDigit(ch) { + return ch >= 48 /* _0 */ && ch <= 55 /* _7 */; + } + ts.isOctalDigit = isOctalDigit; + function couldStartTrivia(text, pos) { + // Keep in sync with skipTrivia + var ch = text.charCodeAt(pos); + switch (ch) { + case 13 /* carriageReturn */: + case 10 /* lineFeed */: + case 9 /* tab */: + case 11 /* verticalTab */: + case 12 /* formFeed */: + case 32 /* space */: + case 47 /* slash */: + // starts of normal trivia + case 60 /* lessThan */: + case 124 /* bar */: + case 61 /* equals */: + case 62 /* greaterThan */: + // Starts of conflict marker trivia + return true; + case 35 /* hash */: + // Only if its the beginning can we have #! trivia + return pos === 0; + default: + return ch > 127 /* maxAsciiCharacter */; + } + } + ts.couldStartTrivia = couldStartTrivia; + /* @internal */ + function skipTrivia(text, pos, stopAfterLineBreak, stopAtComments) { + if (stopAtComments === void 0) { stopAtComments = false; } + if (ts.positionIsSynthesized(pos)) { + return pos; + } + // Keep in sync with couldStartTrivia + while (true) { + var ch = text.charCodeAt(pos); + switch (ch) { + case 13 /* carriageReturn */: + if (text.charCodeAt(pos + 1) === 10 /* lineFeed */) { + pos++; + } + // falls through + case 10 /* lineFeed */: + pos++; + if (stopAfterLineBreak) { + return pos; + } + continue; + case 9 /* tab */: + case 11 /* verticalTab */: + case 12 /* formFeed */: + case 32 /* space */: + pos++; + continue; + case 47 /* slash */: + if (stopAtComments) { + break; + } + if (text.charCodeAt(pos + 1) === 47 /* slash */) { + pos += 2; + while (pos < text.length) { + if (isLineBreak(text.charCodeAt(pos))) { + break; + } + pos++; + } + continue; + } + if (text.charCodeAt(pos + 1) === 42 /* asterisk */) { + pos += 2; + while (pos < text.length) { + if (text.charCodeAt(pos) === 42 /* asterisk */ && text.charCodeAt(pos + 1) === 47 /* slash */) { + pos += 2; + break; + } + pos++; + } + continue; + } + break; + case 60 /* lessThan */: + case 124 /* bar */: + case 61 /* equals */: + case 62 /* greaterThan */: + if (isConflictMarkerTrivia(text, pos)) { + pos = scanConflictMarkerTrivia(text, pos); + continue; + } + break; + case 35 /* hash */: + if (pos === 0 && isShebangTrivia(text, pos)) { + pos = scanShebangTrivia(text, pos); + continue; + } + break; + default: + if (ch > 127 /* maxAsciiCharacter */ && (isWhiteSpaceLike(ch))) { + pos++; + continue; + } + break; + } + return pos; + } + } + ts.skipTrivia = skipTrivia; + // All conflict markers consist of the same character repeated seven times. If it is + // a <<<<<<< or >>>>>>> marker then it is also followed by a space. + var mergeConflictMarkerLength = "<<<<<<<".length; + function isConflictMarkerTrivia(text, pos) { + ts.Debug.assert(pos >= 0); + // Conflict markers must be at the start of a line. + if (pos === 0 || isLineBreak(text.charCodeAt(pos - 1))) { + var ch = text.charCodeAt(pos); + if ((pos + mergeConflictMarkerLength) < text.length) { + for (var i = 0; i < mergeConflictMarkerLength; i++) { + if (text.charCodeAt(pos + i) !== ch) { + return false; + } + } + return ch === 61 /* equals */ || + text.charCodeAt(pos + mergeConflictMarkerLength) === 32 /* space */; + } + } + return false; + } + function scanConflictMarkerTrivia(text, pos, error) { + if (error) { + error(ts.Diagnostics.Merge_conflict_marker_encountered, pos, mergeConflictMarkerLength); + } + var ch = text.charCodeAt(pos); + var len = text.length; + if (ch === 60 /* lessThan */ || ch === 62 /* greaterThan */) { + while (pos < len && !isLineBreak(text.charCodeAt(pos))) { + pos++; + } + } + else { + ts.Debug.assert(ch === 124 /* bar */ || ch === 61 /* equals */); + // Consume everything from the start of a ||||||| or ======= marker to the start + // of the next ======= or >>>>>>> marker. + while (pos < len) { + var currentChar = text.charCodeAt(pos); + if ((currentChar === 61 /* equals */ || currentChar === 62 /* greaterThan */) && currentChar !== ch && isConflictMarkerTrivia(text, pos)) { + break; + } + pos++; + } + } + return pos; + } + var shebangTriviaRegex = /^#!.*/; + function isShebangTrivia(text, pos) { + // Shebangs check must only be done at the start of the file + ts.Debug.assert(pos === 0); + return shebangTriviaRegex.test(text); + } + function scanShebangTrivia(text, pos) { + var shebang = shebangTriviaRegex.exec(text)[0]; + pos = pos + shebang.length; + return pos; + } + /** + * Invokes a callback for each comment range following the provided position. + * + * Single-line comment ranges include the leading double-slash characters but not the ending + * line break. Multi-line comment ranges include the leading slash-asterisk and trailing + * asterisk-slash characters. + * + * @param reduce If true, accumulates the result of calling the callback in a fashion similar + * to reduceLeft. If false, iteration stops when the callback returns a truthy value. + * @param text The source text to scan. + * @param pos The position at which to start scanning. + * @param trailing If false, whitespace is skipped until the first line break and comments + * between that location and the next token are returned. If true, comments occurring + * between the given position and the next line break are returned. + * @param cb The callback to execute as each comment range is encountered. + * @param state A state value to pass to each iteration of the callback. + * @param initial An initial value to pass when accumulating results (when "reduce" is true). + * @returns If "reduce" is true, the accumulated value. If "reduce" is false, the first truthy + * return value of the callback. + */ + function iterateCommentRanges(reduce, text, pos, trailing, cb, state, initial) { + var pendingPos; + var pendingEnd; + var pendingKind; + var pendingHasTrailingNewLine; + var hasPendingCommentRange = false; + var collecting = trailing || pos === 0; + var accumulator = initial; + scan: while (pos >= 0 && pos < text.length) { + var ch = text.charCodeAt(pos); + switch (ch) { + case 13 /* carriageReturn */: + if (text.charCodeAt(pos + 1) === 10 /* lineFeed */) { + pos++; + } + // falls through + case 10 /* lineFeed */: + pos++; + if (trailing) { + break scan; + } + collecting = true; + if (hasPendingCommentRange) { + pendingHasTrailingNewLine = true; + } + continue; + case 9 /* tab */: + case 11 /* verticalTab */: + case 12 /* formFeed */: + case 32 /* space */: + pos++; + continue; + case 47 /* slash */: + var nextChar = text.charCodeAt(pos + 1); + var hasTrailingNewLine = false; + if (nextChar === 47 /* slash */ || nextChar === 42 /* asterisk */) { + var kind = nextChar === 47 /* slash */ ? 2 /* SingleLineCommentTrivia */ : 3 /* MultiLineCommentTrivia */; + var startPos = pos; + pos += 2; + if (nextChar === 47 /* slash */) { + while (pos < text.length) { + if (isLineBreak(text.charCodeAt(pos))) { + hasTrailingNewLine = true; + break; + } + pos++; + } + } + else { + while (pos < text.length) { + if (text.charCodeAt(pos) === 42 /* asterisk */ && text.charCodeAt(pos + 1) === 47 /* slash */) { + pos += 2; + break; + } + pos++; + } + } + if (collecting) { + if (hasPendingCommentRange) { + accumulator = cb(pendingPos, pendingEnd, pendingKind, pendingHasTrailingNewLine, state, accumulator); + if (!reduce && accumulator) { + // If we are not reducing and we have a truthy result, return it. + return accumulator; + } + } + pendingPos = startPos; + pendingEnd = pos; + pendingKind = kind; + pendingHasTrailingNewLine = hasTrailingNewLine; + hasPendingCommentRange = true; + } + continue; + } + break scan; + default: + if (ch > 127 /* maxAsciiCharacter */ && (isWhiteSpaceLike(ch))) { + if (hasPendingCommentRange && isLineBreak(ch)) { + pendingHasTrailingNewLine = true; + } + pos++; + continue; + } + break scan; + } + } + if (hasPendingCommentRange) { + accumulator = cb(pendingPos, pendingEnd, pendingKind, pendingHasTrailingNewLine, state, accumulator); + } + return accumulator; + } + function forEachLeadingCommentRange(text, pos, cb, state) { + return iterateCommentRanges(/*reduce*/ false, text, pos, /*trailing*/ false, cb, state); + } + ts.forEachLeadingCommentRange = forEachLeadingCommentRange; + function forEachTrailingCommentRange(text, pos, cb, state) { + return iterateCommentRanges(/*reduce*/ false, text, pos, /*trailing*/ true, cb, state); + } + ts.forEachTrailingCommentRange = forEachTrailingCommentRange; + function reduceEachLeadingCommentRange(text, pos, cb, state, initial) { + return iterateCommentRanges(/*reduce*/ true, text, pos, /*trailing*/ false, cb, state, initial); + } + ts.reduceEachLeadingCommentRange = reduceEachLeadingCommentRange; + function reduceEachTrailingCommentRange(text, pos, cb, state, initial) { + return iterateCommentRanges(/*reduce*/ true, text, pos, /*trailing*/ true, cb, state, initial); + } + ts.reduceEachTrailingCommentRange = reduceEachTrailingCommentRange; + function appendCommentRange(pos, end, kind, hasTrailingNewLine, _state, comments) { + if (!comments) { + comments = []; + } + comments.push({ kind: kind, pos: pos, end: end, hasTrailingNewLine: hasTrailingNewLine }); + return comments; + } + function getLeadingCommentRanges(text, pos) { + return reduceEachLeadingCommentRange(text, pos, appendCommentRange, /*state*/ undefined, /*initial*/ undefined); + } + ts.getLeadingCommentRanges = getLeadingCommentRanges; + function getTrailingCommentRanges(text, pos) { + return reduceEachTrailingCommentRange(text, pos, appendCommentRange, /*state*/ undefined, /*initial*/ undefined); + } + ts.getTrailingCommentRanges = getTrailingCommentRanges; + /** Optionally, get the shebang */ + function getShebang(text) { + var match = shebangTriviaRegex.exec(text); + if (match) { + return match[0]; + } + } + ts.getShebang = getShebang; + function isIdentifierStart(ch, languageVersion) { + return ch >= 65 /* A */ && ch <= 90 /* Z */ || ch >= 97 /* a */ && ch <= 122 /* z */ || + ch === 36 /* $ */ || ch === 95 /* _ */ || + ch > 127 /* maxAsciiCharacter */ && isUnicodeIdentifierStart(ch, languageVersion); + } + ts.isIdentifierStart = isIdentifierStart; + function isIdentifierPart(ch, languageVersion) { + return ch >= 65 /* A */ && ch <= 90 /* Z */ || ch >= 97 /* a */ && ch <= 122 /* z */ || + ch >= 48 /* _0 */ && ch <= 57 /* _9 */ || ch === 36 /* $ */ || ch === 95 /* _ */ || + ch > 127 /* maxAsciiCharacter */ && isUnicodeIdentifierPart(ch, languageVersion); + } + ts.isIdentifierPart = isIdentifierPart; + /* @internal */ + function isIdentifierText(name, languageVersion) { + if (!isIdentifierStart(name.charCodeAt(0), languageVersion)) { + return false; + } + for (var i = 1; i < name.length; i++) { + if (!isIdentifierPart(name.charCodeAt(i), languageVersion)) { + return false; + } + } + return true; + } + ts.isIdentifierText = isIdentifierText; + // Creates a scanner over a (possibly unspecified) range of a piece of text. + function createScanner(languageVersion, skipTrivia, languageVariant, textInitial, onError, start, length) { + if (languageVariant === void 0) { languageVariant = 0 /* Standard */; } + var text = textInitial; + // Current position (end position of text of current token) + var pos; + // end of text + var end; + // Start position of whitespace before current token + var startPos; + // Start position of text of current token + var tokenPos; + var token; + var tokenValue; + var tokenFlags; + var inJSDocType = 0; + setText(text, start, length); + return { + getStartPos: function () { return startPos; }, + getTextPos: function () { return pos; }, + getToken: function () { return token; }, + getTokenPos: function () { return tokenPos; }, + getTokenText: function () { return text.substring(tokenPos, pos); }, + getTokenValue: function () { return tokenValue; }, + hasExtendedUnicodeEscape: function () { return (tokenFlags & 8 /* ExtendedUnicodeEscape */) !== 0; }, + hasPrecedingLineBreak: function () { return (tokenFlags & 1 /* PrecedingLineBreak */) !== 0; }, + isIdentifier: function () { return token === 72 /* Identifier */ || token > 108 /* LastReservedWord */; }, + isReservedWord: function () { return token >= 73 /* FirstReservedWord */ && token <= 108 /* LastReservedWord */; }, + isUnterminated: function () { return (tokenFlags & 4 /* Unterminated */) !== 0; }, + getTokenFlags: function () { return tokenFlags; }, + reScanGreaterToken: reScanGreaterToken, + reScanSlashToken: reScanSlashToken, + reScanTemplateToken: reScanTemplateToken, + scanJsxIdentifier: scanJsxIdentifier, + scanJsxAttributeValue: scanJsxAttributeValue, + reScanJsxToken: reScanJsxToken, + scanJsxToken: scanJsxToken, + scanJSDocToken: scanJSDocToken, + scan: scan, + getText: getText, + setText: setText, + setScriptTarget: setScriptTarget, + setLanguageVariant: setLanguageVariant, + setOnError: setOnError, + setTextPos: setTextPos, + setInJSDocType: setInJSDocType, + tryScan: tryScan, + lookAhead: lookAhead, + scanRange: scanRange, + }; + function error(message, errPos, length) { + if (errPos === void 0) { errPos = pos; } + if (onError) { + var oldPos = pos; + pos = errPos; + onError(message, length || 0); + pos = oldPos; + } + } + function scanNumberFragment() { + var start = pos; + var allowSeparator = false; + var isPreviousTokenSeparator = false; + var result = ""; + while (true) { + var ch = text.charCodeAt(pos); + if (ch === 95 /* _ */) { + tokenFlags |= 512 /* ContainsSeparator */; + if (allowSeparator) { + allowSeparator = false; + isPreviousTokenSeparator = true; + result += text.substring(start, pos); + } + else if (isPreviousTokenSeparator) { + error(ts.Diagnostics.Multiple_consecutive_numeric_separators_are_not_permitted, pos, 1); + } + else { + error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos, 1); + } + pos++; + start = pos; + continue; + } + if (isDigit(ch)) { + allowSeparator = true; + isPreviousTokenSeparator = false; + pos++; + continue; + } + break; + } + if (text.charCodeAt(pos - 1) === 95 /* _ */) { + error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos - 1, 1); + } + return result + text.substring(start, pos); + } + function scanNumber() { + var start = pos; + var mainFragment = scanNumberFragment(); + var decimalFragment; + var scientificFragment; + if (text.charCodeAt(pos) === 46 /* dot */) { + pos++; + decimalFragment = scanNumberFragment(); + } + var end = pos; + if (text.charCodeAt(pos) === 69 /* E */ || text.charCodeAt(pos) === 101 /* e */) { + pos++; + tokenFlags |= 16 /* Scientific */; + if (text.charCodeAt(pos) === 43 /* plus */ || text.charCodeAt(pos) === 45 /* minus */) + pos++; + var preNumericPart = pos; + var finalFragment = scanNumberFragment(); + if (!finalFragment) { + error(ts.Diagnostics.Digit_expected); + } + else { + scientificFragment = text.substring(end, preNumericPart) + finalFragment; + end = pos; + } + } + var result; + if (tokenFlags & 512 /* ContainsSeparator */) { + result = mainFragment; + if (decimalFragment) { + result += "." + decimalFragment; + } + if (scientificFragment) { + result += scientificFragment; + } + } + else { + result = text.substring(start, end); // No need to use all the fragments; no _ removal needed + } + if (decimalFragment !== undefined || tokenFlags & 16 /* Scientific */) { + return { + type: 8 /* NumericLiteral */, + value: "" + +result // if value is not an integer, it can be safely coerced to a number + }; + } + else { + tokenValue = result; + var type = checkBigIntSuffix(); // if value is an integer, check whether it is a bigint + return { type: type, value: tokenValue }; + } + } + function scanOctalDigits() { + var start = pos; + while (isOctalDigit(text.charCodeAt(pos))) { + pos++; + } + return +(text.substring(start, pos)); + } + /** + * Scans the given number of hexadecimal digits in the text, + * returning -1 if the given number is unavailable. + */ + function scanExactNumberOfHexDigits(count, canHaveSeparators) { + var valueString = scanHexDigits(/*minCount*/ count, /*scanAsManyAsPossible*/ false, canHaveSeparators); + return valueString ? parseInt(valueString, 16) : -1; + } + /** + * Scans as many hexadecimal digits as are available in the text, + * returning "" if the given number of digits was unavailable. + */ + function scanMinimumNumberOfHexDigits(count, canHaveSeparators) { + return scanHexDigits(/*minCount*/ count, /*scanAsManyAsPossible*/ true, canHaveSeparators); + } + function scanHexDigits(minCount, scanAsManyAsPossible, canHaveSeparators) { + var valueChars = []; + var allowSeparator = false; + var isPreviousTokenSeparator = false; + while (valueChars.length < minCount || scanAsManyAsPossible) { + var ch = text.charCodeAt(pos); + if (canHaveSeparators && ch === 95 /* _ */) { + tokenFlags |= 512 /* ContainsSeparator */; + if (allowSeparator) { + allowSeparator = false; + isPreviousTokenSeparator = true; + } + else if (isPreviousTokenSeparator) { + error(ts.Diagnostics.Multiple_consecutive_numeric_separators_are_not_permitted, pos, 1); + } + else { + error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos, 1); + } + pos++; + continue; + } + allowSeparator = canHaveSeparators; + if (ch >= 65 /* A */ && ch <= 70 /* F */) { + ch += 97 /* a */ - 65 /* A */; // standardize hex literals to lowercase + } + else if (!((ch >= 48 /* _0 */ && ch <= 57 /* _9 */) || + (ch >= 97 /* a */ && ch <= 102 /* f */))) { + break; + } + valueChars.push(ch); + pos++; + isPreviousTokenSeparator = false; + } + if (valueChars.length < minCount) { + valueChars = []; + } + if (text.charCodeAt(pos - 1) === 95 /* _ */) { + error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos - 1, 1); + } + return String.fromCharCode.apply(String, valueChars); + } + function scanString(jsxAttributeString) { + if (jsxAttributeString === void 0) { jsxAttributeString = false; } + var quote = text.charCodeAt(pos); + pos++; + var result = ""; + var start = pos; + while (true) { + if (pos >= end) { + result += text.substring(start, pos); + tokenFlags |= 4 /* Unterminated */; + error(ts.Diagnostics.Unterminated_string_literal); + break; + } + var ch = text.charCodeAt(pos); + if (ch === quote) { + result += text.substring(start, pos); + pos++; + break; + } + if (ch === 92 /* backslash */ && !jsxAttributeString) { + result += text.substring(start, pos); + result += scanEscapeSequence(); + start = pos; + continue; + } + if (isLineBreak(ch) && !jsxAttributeString) { + result += text.substring(start, pos); + tokenFlags |= 4 /* Unterminated */; + error(ts.Diagnostics.Unterminated_string_literal); + break; + } + pos++; + } + return result; + } + /** + * Sets the current 'tokenValue' and returns a NoSubstitutionTemplateLiteral or + * a literal component of a TemplateExpression. + */ + function scanTemplateAndSetTokenValue() { + var startedWithBacktick = text.charCodeAt(pos) === 96 /* backtick */; + pos++; + var start = pos; + var contents = ""; + var resultingToken; + while (true) { + if (pos >= end) { + contents += text.substring(start, pos); + tokenFlags |= 4 /* Unterminated */; + error(ts.Diagnostics.Unterminated_template_literal); + resultingToken = startedWithBacktick ? 14 /* NoSubstitutionTemplateLiteral */ : 17 /* TemplateTail */; + break; + } + var currChar = text.charCodeAt(pos); + // '`' + if (currChar === 96 /* backtick */) { + contents += text.substring(start, pos); + pos++; + resultingToken = startedWithBacktick ? 14 /* NoSubstitutionTemplateLiteral */ : 17 /* TemplateTail */; + break; + } + // '${' + if (currChar === 36 /* $ */ && pos + 1 < end && text.charCodeAt(pos + 1) === 123 /* openBrace */) { + contents += text.substring(start, pos); + pos += 2; + resultingToken = startedWithBacktick ? 15 /* TemplateHead */ : 16 /* TemplateMiddle */; + break; + } + // Escape character + if (currChar === 92 /* backslash */) { + contents += text.substring(start, pos); + contents += scanEscapeSequence(); + start = pos; + continue; + } + // Speculated ECMAScript 6 Spec 11.8.6.1: + // and LineTerminatorSequences are normalized to for Template Values + if (currChar === 13 /* carriageReturn */) { + contents += text.substring(start, pos); + pos++; + if (pos < end && text.charCodeAt(pos) === 10 /* lineFeed */) { + pos++; + } + contents += "\n"; + start = pos; + continue; + } + pos++; + } + ts.Debug.assert(resultingToken !== undefined); + tokenValue = contents; + return resultingToken; + } + function scanEscapeSequence() { + pos++; + if (pos >= end) { + error(ts.Diagnostics.Unexpected_end_of_text); + return ""; + } + var ch = text.charCodeAt(pos); + pos++; + switch (ch) { + case 48 /* _0 */: + return "\0"; + case 98 /* b */: + return "\b"; + case 116 /* t */: + return "\t"; + case 110 /* n */: + return "\n"; + case 118 /* v */: + return "\v"; + case 102 /* f */: + return "\f"; + case 114 /* r */: + return "\r"; + case 39 /* singleQuote */: + return "\'"; + case 34 /* doubleQuote */: + return "\""; + case 117 /* u */: + // '\u{DDDDDDDD}' + if (pos < end && text.charCodeAt(pos) === 123 /* openBrace */) { + tokenFlags |= 8 /* ExtendedUnicodeEscape */; + pos++; + return scanExtendedUnicodeEscape(); + } + // '\uDDDD' + return scanHexadecimalEscape(/*numDigits*/ 4); + case 120 /* x */: + // '\xDD' + return scanHexadecimalEscape(/*numDigits*/ 2); + // when encountering a LineContinuation (i.e. a backslash and a line terminator sequence), + // the line terminator is interpreted to be "the empty code unit sequence". + case 13 /* carriageReturn */: + if (pos < end && text.charCodeAt(pos) === 10 /* lineFeed */) { + pos++; + } + // falls through + case 10 /* lineFeed */: + case 8232 /* lineSeparator */: + case 8233 /* paragraphSeparator */: + return ""; + default: + return String.fromCharCode(ch); + } + } + function scanHexadecimalEscape(numDigits) { + var escapedValue = scanExactNumberOfHexDigits(numDigits, /*canHaveSeparators*/ false); + if (escapedValue >= 0) { + return String.fromCharCode(escapedValue); + } + else { + error(ts.Diagnostics.Hexadecimal_digit_expected); + return ""; + } + } + function scanExtendedUnicodeEscape() { + var escapedValueString = scanMinimumNumberOfHexDigits(1, /*canHaveSeparators*/ false); + var escapedValue = escapedValueString ? parseInt(escapedValueString, 16) : -1; + var isInvalidExtendedEscape = false; + // Validate the value of the digit + if (escapedValue < 0) { + error(ts.Diagnostics.Hexadecimal_digit_expected); + isInvalidExtendedEscape = true; + } + else if (escapedValue > 0x10FFFF) { + error(ts.Diagnostics.An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive); + isInvalidExtendedEscape = true; + } + if (pos >= end) { + error(ts.Diagnostics.Unexpected_end_of_text); + isInvalidExtendedEscape = true; + } + else if (text.charCodeAt(pos) === 125 /* closeBrace */) { + // Only swallow the following character up if it's a '}'. + pos++; + } + else { + error(ts.Diagnostics.Unterminated_Unicode_escape_sequence); + isInvalidExtendedEscape = true; + } + if (isInvalidExtendedEscape) { + return ""; + } + return utf16EncodeAsString(escapedValue); + } + // Derived from the 10.1.1 UTF16Encoding of the ES6 Spec. + function utf16EncodeAsString(codePoint) { + ts.Debug.assert(0x0 <= codePoint && codePoint <= 0x10FFFF); + if (codePoint <= 65535) { + return String.fromCharCode(codePoint); + } + var codeUnit1 = Math.floor((codePoint - 65536) / 1024) + 0xD800; + var codeUnit2 = ((codePoint - 65536) % 1024) + 0xDC00; + return String.fromCharCode(codeUnit1, codeUnit2); + } + // Current character is known to be a backslash. Check for Unicode escape of the form '\uXXXX' + // and return code point value if valid Unicode escape is found. Otherwise return -1. + function peekUnicodeEscape() { + if (pos + 5 < end && text.charCodeAt(pos + 1) === 117 /* u */) { + var start_1 = pos; + pos += 2; + var value = scanExactNumberOfHexDigits(4, /*canHaveSeparators*/ false); + pos = start_1; + return value; + } + return -1; + } + function scanIdentifierParts() { + var result = ""; + var start = pos; + while (pos < end) { + var ch = text.charCodeAt(pos); + if (isIdentifierPart(ch, languageVersion)) { + pos++; + } + else if (ch === 92 /* backslash */) { + ch = peekUnicodeEscape(); + if (!(ch >= 0 && isIdentifierPart(ch, languageVersion))) { + break; + } + result += text.substring(start, pos); + result += String.fromCharCode(ch); + // Valid Unicode escape is always six characters + pos += 6; + start = pos; + } + else { + break; + } + } + result += text.substring(start, pos); + return result; + } + function getIdentifierToken() { + // Reserved words are between 2 and 11 characters long and start with a lowercase letter + var len = tokenValue.length; + if (len >= 2 && len <= 11) { + var ch = tokenValue.charCodeAt(0); + if (ch >= 97 /* a */ && ch <= 122 /* z */) { + var keyword = textToKeyword.get(tokenValue); + if (keyword !== undefined) { + return token = keyword; + } + } + } + return token = 72 /* Identifier */; + } + function scanBinaryOrOctalDigits(base) { + var value = ""; + // For counting number of digits; Valid binaryIntegerLiteral must have at least one binary digit following B or b. + // Similarly valid octalIntegerLiteral must have at least one octal digit following o or O. + var separatorAllowed = false; + var isPreviousTokenSeparator = false; + while (true) { + var ch = text.charCodeAt(pos); + // Numeric separators are allowed anywhere within a numeric literal, except not at the beginning, or following another separator + if (ch === 95 /* _ */) { + tokenFlags |= 512 /* ContainsSeparator */; + if (separatorAllowed) { + separatorAllowed = false; + isPreviousTokenSeparator = true; + } + else if (isPreviousTokenSeparator) { + error(ts.Diagnostics.Multiple_consecutive_numeric_separators_are_not_permitted, pos, 1); + } + else { + error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos, 1); + } + pos++; + continue; + } + separatorAllowed = true; + if (!isDigit(ch) || ch - 48 /* _0 */ >= base) { + break; + } + value += text[pos]; + pos++; + isPreviousTokenSeparator = false; + } + if (text.charCodeAt(pos - 1) === 95 /* _ */) { + // Literal ends with underscore - not allowed + error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos - 1, 1); + } + return value; + } + function checkBigIntSuffix() { + if (text.charCodeAt(pos) === 110 /* n */) { + tokenValue += "n"; + // Use base 10 instead of base 2 or base 8 for shorter literals + if (tokenFlags & 384 /* BinaryOrOctalSpecifier */) { + tokenValue = ts.parsePseudoBigInt(tokenValue) + "n"; + } + pos++; + return 9 /* BigIntLiteral */; + } + else { // not a bigint, so can convert to number in simplified form + // Number() may not support 0b or 0o, so use parseInt() instead + var numericValue = tokenFlags & 128 /* BinarySpecifier */ + ? parseInt(tokenValue.slice(2), 2) // skip "0b" + : tokenFlags & 256 /* OctalSpecifier */ + ? parseInt(tokenValue.slice(2), 8) // skip "0o" + : +tokenValue; + tokenValue = "" + numericValue; + return 8 /* NumericLiteral */; + } + } + function scan() { + var _a; + startPos = pos; + tokenFlags = 0; + var asteriskSeen = false; + while (true) { + tokenPos = pos; + if (pos >= end) { + return token = 1 /* EndOfFileToken */; + } + var ch = text.charCodeAt(pos); + // Special handling for shebang + if (ch === 35 /* hash */ && pos === 0 && isShebangTrivia(text, pos)) { + pos = scanShebangTrivia(text, pos); + if (skipTrivia) { + continue; + } + else { + return token = 6 /* ShebangTrivia */; + } + } + switch (ch) { + case 10 /* lineFeed */: + case 13 /* carriageReturn */: + tokenFlags |= 1 /* PrecedingLineBreak */; + if (skipTrivia) { + pos++; + continue; + } + else { + if (ch === 13 /* carriageReturn */ && pos + 1 < end && text.charCodeAt(pos + 1) === 10 /* lineFeed */) { + // consume both CR and LF + pos += 2; + } + else { + pos++; + } + return token = 4 /* NewLineTrivia */; + } + case 9 /* tab */: + case 11 /* verticalTab */: + case 12 /* formFeed */: + case 32 /* space */: + case 160 /* nonBreakingSpace */: + case 5760 /* ogham */: + case 8192 /* enQuad */: + case 8193 /* emQuad */: + case 8194 /* enSpace */: + case 8195 /* emSpace */: + case 8196 /* threePerEmSpace */: + case 8197 /* fourPerEmSpace */: + case 8198 /* sixPerEmSpace */: + case 8199 /* figureSpace */: + case 8200 /* punctuationSpace */: + case 8201 /* thinSpace */: + case 8202 /* hairSpace */: + case 8203 /* zeroWidthSpace */: + case 8239 /* narrowNoBreakSpace */: + case 8287 /* mathematicalSpace */: + case 12288 /* ideographicSpace */: + case 65279 /* byteOrderMark */: + if (skipTrivia) { + pos++; + continue; + } + else { + while (pos < end && isWhiteSpaceSingleLine(text.charCodeAt(pos))) { + pos++; + } + return token = 5 /* WhitespaceTrivia */; + } + case 33 /* exclamation */: + if (text.charCodeAt(pos + 1) === 61 /* equals */) { + if (text.charCodeAt(pos + 2) === 61 /* equals */) { + return pos += 3, token = 36 /* ExclamationEqualsEqualsToken */; + } + return pos += 2, token = 34 /* ExclamationEqualsToken */; + } + pos++; + return token = 52 /* ExclamationToken */; + case 34 /* doubleQuote */: + case 39 /* singleQuote */: + tokenValue = scanString(); + return token = 10 /* StringLiteral */; + case 96 /* backtick */: + return token = scanTemplateAndSetTokenValue(); + case 37 /* percent */: + if (text.charCodeAt(pos + 1) === 61 /* equals */) { + return pos += 2, token = 65 /* PercentEqualsToken */; + } + pos++; + return token = 43 /* PercentToken */; + case 38 /* ampersand */: + if (text.charCodeAt(pos + 1) === 38 /* ampersand */) { + return pos += 2, token = 54 /* AmpersandAmpersandToken */; + } + if (text.charCodeAt(pos + 1) === 61 /* equals */) { + return pos += 2, token = 69 /* AmpersandEqualsToken */; + } + pos++; + return token = 49 /* AmpersandToken */; + case 40 /* openParen */: + pos++; + return token = 20 /* OpenParenToken */; + case 41 /* closeParen */: + pos++; + return token = 21 /* CloseParenToken */; + case 42 /* asterisk */: + if (text.charCodeAt(pos + 1) === 61 /* equals */) { + return pos += 2, token = 62 /* AsteriskEqualsToken */; + } + if (text.charCodeAt(pos + 1) === 42 /* asterisk */) { + if (text.charCodeAt(pos + 2) === 61 /* equals */) { + return pos += 3, token = 63 /* AsteriskAsteriskEqualsToken */; + } + return pos += 2, token = 41 /* AsteriskAsteriskToken */; + } + pos++; + if (inJSDocType && !asteriskSeen && (tokenFlags & 1 /* PrecedingLineBreak */)) { + // decoration at the start of a JSDoc comment line + asteriskSeen = true; + continue; + } + return token = 40 /* AsteriskToken */; + case 43 /* plus */: + if (text.charCodeAt(pos + 1) === 43 /* plus */) { + return pos += 2, token = 44 /* PlusPlusToken */; + } + if (text.charCodeAt(pos + 1) === 61 /* equals */) { + return pos += 2, token = 60 /* PlusEqualsToken */; + } + pos++; + return token = 38 /* PlusToken */; + case 44 /* comma */: + pos++; + return token = 27 /* CommaToken */; + case 45 /* minus */: + if (text.charCodeAt(pos + 1) === 45 /* minus */) { + return pos += 2, token = 45 /* MinusMinusToken */; + } + if (text.charCodeAt(pos + 1) === 61 /* equals */) { + return pos += 2, token = 61 /* MinusEqualsToken */; + } + pos++; + return token = 39 /* MinusToken */; + case 46 /* dot */: + if (isDigit(text.charCodeAt(pos + 1))) { + tokenValue = scanNumber().value; + return token = 8 /* NumericLiteral */; + } + if (text.charCodeAt(pos + 1) === 46 /* dot */ && text.charCodeAt(pos + 2) === 46 /* dot */) { + return pos += 3, token = 25 /* DotDotDotToken */; + } + pos++; + return token = 24 /* DotToken */; + case 47 /* slash */: + // Single-line comment + if (text.charCodeAt(pos + 1) === 47 /* slash */) { + pos += 2; + while (pos < end) { + if (isLineBreak(text.charCodeAt(pos))) { + break; + } + pos++; + } + if (skipTrivia) { + continue; + } + else { + return token = 2 /* SingleLineCommentTrivia */; + } + } + // Multi-line comment + if (text.charCodeAt(pos + 1) === 42 /* asterisk */) { + pos += 2; + if (text.charCodeAt(pos) === 42 /* asterisk */ && text.charCodeAt(pos + 1) !== 47 /* slash */) { + tokenFlags |= 2 /* PrecedingJSDocComment */; + } + var commentClosed = false; + while (pos < end) { + var ch_1 = text.charCodeAt(pos); + if (ch_1 === 42 /* asterisk */ && text.charCodeAt(pos + 1) === 47 /* slash */) { + pos += 2; + commentClosed = true; + break; + } + if (isLineBreak(ch_1)) { + tokenFlags |= 1 /* PrecedingLineBreak */; + } + pos++; + } + if (!commentClosed) { + error(ts.Diagnostics.Asterisk_Slash_expected); + } + if (skipTrivia) { + continue; + } + else { + if (!commentClosed) { + tokenFlags |= 4 /* Unterminated */; + } + return token = 3 /* MultiLineCommentTrivia */; + } + } + if (text.charCodeAt(pos + 1) === 61 /* equals */) { + return pos += 2, token = 64 /* SlashEqualsToken */; + } + pos++; + return token = 42 /* SlashToken */; + case 48 /* _0 */: + if (pos + 2 < end && (text.charCodeAt(pos + 1) === 88 /* X */ || text.charCodeAt(pos + 1) === 120 /* x */)) { + pos += 2; + tokenValue = scanMinimumNumberOfHexDigits(1, /*canHaveSeparators*/ true); + if (!tokenValue) { + error(ts.Diagnostics.Hexadecimal_digit_expected); + tokenValue = "0"; + } + tokenValue = "0x" + tokenValue; + tokenFlags |= 64 /* HexSpecifier */; + return token = checkBigIntSuffix(); + } + else if (pos + 2 < end && (text.charCodeAt(pos + 1) === 66 /* B */ || text.charCodeAt(pos + 1) === 98 /* b */)) { + pos += 2; + tokenValue = scanBinaryOrOctalDigits(/* base */ 2); + if (!tokenValue) { + error(ts.Diagnostics.Binary_digit_expected); + tokenValue = "0"; + } + tokenValue = "0b" + tokenValue; + tokenFlags |= 128 /* BinarySpecifier */; + return token = checkBigIntSuffix(); + } + else if (pos + 2 < end && (text.charCodeAt(pos + 1) === 79 /* O */ || text.charCodeAt(pos + 1) === 111 /* o */)) { + pos += 2; + tokenValue = scanBinaryOrOctalDigits(/* base */ 8); + if (!tokenValue) { + error(ts.Diagnostics.Octal_digit_expected); + tokenValue = "0"; + } + tokenValue = "0o" + tokenValue; + tokenFlags |= 256 /* OctalSpecifier */; + return token = checkBigIntSuffix(); + } + // Try to parse as an octal + if (pos + 1 < end && isOctalDigit(text.charCodeAt(pos + 1))) { + tokenValue = "" + scanOctalDigits(); + tokenFlags |= 32 /* Octal */; + return token = 8 /* NumericLiteral */; + } + // This fall-through is a deviation from the EcmaScript grammar. The grammar says that a leading zero + // can only be followed by an octal digit, a dot, or the end of the number literal. However, we are being + // permissive and allowing decimal digits of the form 08* and 09* (which many browsers also do). + // falls through + case 49 /* _1 */: + case 50 /* _2 */: + case 51 /* _3 */: + case 52 /* _4 */: + case 53 /* _5 */: + case 54 /* _6 */: + case 55 /* _7 */: + case 56 /* _8 */: + case 57 /* _9 */: + (_a = scanNumber(), token = _a.type, tokenValue = _a.value); + return token; + case 58 /* colon */: + pos++; + return token = 57 /* ColonToken */; + case 59 /* semicolon */: + pos++; + return token = 26 /* SemicolonToken */; + case 60 /* lessThan */: + if (isConflictMarkerTrivia(text, pos)) { + pos = scanConflictMarkerTrivia(text, pos, error); + if (skipTrivia) { + continue; + } + else { + return token = 7 /* ConflictMarkerTrivia */; + } + } + if (text.charCodeAt(pos + 1) === 60 /* lessThan */) { + if (text.charCodeAt(pos + 2) === 61 /* equals */) { + return pos += 3, token = 66 /* LessThanLessThanEqualsToken */; + } + return pos += 2, token = 46 /* LessThanLessThanToken */; + } + if (text.charCodeAt(pos + 1) === 61 /* equals */) { + return pos += 2, token = 31 /* LessThanEqualsToken */; + } + if (languageVariant === 1 /* JSX */ && + text.charCodeAt(pos + 1) === 47 /* slash */ && + text.charCodeAt(pos + 2) !== 42 /* asterisk */) { + return pos += 2, token = 29 /* LessThanSlashToken */; + } + pos++; + return token = 28 /* LessThanToken */; + case 61 /* equals */: + if (isConflictMarkerTrivia(text, pos)) { + pos = scanConflictMarkerTrivia(text, pos, error); + if (skipTrivia) { + continue; + } + else { + return token = 7 /* ConflictMarkerTrivia */; + } + } + if (text.charCodeAt(pos + 1) === 61 /* equals */) { + if (text.charCodeAt(pos + 2) === 61 /* equals */) { + return pos += 3, token = 35 /* EqualsEqualsEqualsToken */; + } + return pos += 2, token = 33 /* EqualsEqualsToken */; + } + if (text.charCodeAt(pos + 1) === 62 /* greaterThan */) { + return pos += 2, token = 37 /* EqualsGreaterThanToken */; + } + pos++; + return token = 59 /* EqualsToken */; + case 62 /* greaterThan */: + if (isConflictMarkerTrivia(text, pos)) { + pos = scanConflictMarkerTrivia(text, pos, error); + if (skipTrivia) { + continue; + } + else { + return token = 7 /* ConflictMarkerTrivia */; + } + } + pos++; + return token = 30 /* GreaterThanToken */; + case 63 /* question */: + pos++; + return token = 56 /* QuestionToken */; + case 91 /* openBracket */: + pos++; + return token = 22 /* OpenBracketToken */; + case 93 /* closeBracket */: + pos++; + return token = 23 /* CloseBracketToken */; + case 94 /* caret */: + if (text.charCodeAt(pos + 1) === 61 /* equals */) { + return pos += 2, token = 71 /* CaretEqualsToken */; + } + pos++; + return token = 51 /* CaretToken */; + case 123 /* openBrace */: + pos++; + return token = 18 /* OpenBraceToken */; + case 124 /* bar */: + if (isConflictMarkerTrivia(text, pos)) { + pos = scanConflictMarkerTrivia(text, pos, error); + if (skipTrivia) { + continue; + } + else { + return token = 7 /* ConflictMarkerTrivia */; + } + } + if (text.charCodeAt(pos + 1) === 124 /* bar */) { + return pos += 2, token = 55 /* BarBarToken */; + } + if (text.charCodeAt(pos + 1) === 61 /* equals */) { + return pos += 2, token = 70 /* BarEqualsToken */; + } + pos++; + return token = 50 /* BarToken */; + case 125 /* closeBrace */: + pos++; + return token = 19 /* CloseBraceToken */; + case 126 /* tilde */: + pos++; + return token = 53 /* TildeToken */; + case 64 /* at */: + pos++; + return token = 58 /* AtToken */; + case 92 /* backslash */: + var cookedChar = peekUnicodeEscape(); + if (cookedChar >= 0 && isIdentifierStart(cookedChar, languageVersion)) { + pos += 6; + tokenValue = String.fromCharCode(cookedChar) + scanIdentifierParts(); + return token = getIdentifierToken(); + } + error(ts.Diagnostics.Invalid_character); + pos++; + return token = 0 /* Unknown */; + default: + if (isIdentifierStart(ch, languageVersion)) { + pos++; + while (pos < end && isIdentifierPart(ch = text.charCodeAt(pos), languageVersion)) + pos++; + tokenValue = text.substring(tokenPos, pos); + if (ch === 92 /* backslash */) { + tokenValue += scanIdentifierParts(); + } + return token = getIdentifierToken(); + } + else if (isWhiteSpaceSingleLine(ch)) { + pos++; + continue; + } + else if (isLineBreak(ch)) { + tokenFlags |= 1 /* PrecedingLineBreak */; + pos++; + continue; + } + error(ts.Diagnostics.Invalid_character); + pos++; + return token = 0 /* Unknown */; + } + } + } + function reScanGreaterToken() { + if (token === 30 /* GreaterThanToken */) { + if (text.charCodeAt(pos) === 62 /* greaterThan */) { + if (text.charCodeAt(pos + 1) === 62 /* greaterThan */) { + if (text.charCodeAt(pos + 2) === 61 /* equals */) { + return pos += 3, token = 68 /* GreaterThanGreaterThanGreaterThanEqualsToken */; + } + return pos += 2, token = 48 /* GreaterThanGreaterThanGreaterThanToken */; + } + if (text.charCodeAt(pos + 1) === 61 /* equals */) { + return pos += 2, token = 67 /* GreaterThanGreaterThanEqualsToken */; + } + pos++; + return token = 47 /* GreaterThanGreaterThanToken */; + } + if (text.charCodeAt(pos) === 61 /* equals */) { + pos++; + return token = 32 /* GreaterThanEqualsToken */; + } + } + return token; + } + function reScanSlashToken() { + if (token === 42 /* SlashToken */ || token === 64 /* SlashEqualsToken */) { + var p = tokenPos + 1; + var inEscape = false; + var inCharacterClass = false; + while (true) { + // If we reach the end of a file, or hit a newline, then this is an unterminated + // regex. Report error and return what we have so far. + if (p >= end) { + tokenFlags |= 4 /* Unterminated */; + error(ts.Diagnostics.Unterminated_regular_expression_literal); + break; + } + var ch = text.charCodeAt(p); + if (isLineBreak(ch)) { + tokenFlags |= 4 /* Unterminated */; + error(ts.Diagnostics.Unterminated_regular_expression_literal); + break; + } + if (inEscape) { + // Parsing an escape character; + // reset the flag and just advance to the next char. + inEscape = false; + } + else if (ch === 47 /* slash */ && !inCharacterClass) { + // A slash within a character class is permissible, + // but in general it signals the end of the regexp literal. + p++; + break; + } + else if (ch === 91 /* openBracket */) { + inCharacterClass = true; + } + else if (ch === 92 /* backslash */) { + inEscape = true; + } + else if (ch === 93 /* closeBracket */) { + inCharacterClass = false; + } + p++; + } + while (p < end && isIdentifierPart(text.charCodeAt(p), languageVersion)) { + p++; + } + pos = p; + tokenValue = text.substring(tokenPos, pos); + token = 13 /* RegularExpressionLiteral */; + } + return token; + } + /** + * Unconditionally back up and scan a template expression portion. + */ + function reScanTemplateToken() { + ts.Debug.assert(token === 19 /* CloseBraceToken */, "'reScanTemplateToken' should only be called on a '}'"); + pos = tokenPos; + return token = scanTemplateAndSetTokenValue(); + } + function reScanJsxToken() { + pos = tokenPos = startPos; + return token = scanJsxToken(); + } + function scanJsxToken() { + startPos = tokenPos = pos; + if (pos >= end) { + return token = 1 /* EndOfFileToken */; + } + var char = text.charCodeAt(pos); + if (char === 60 /* lessThan */) { + if (text.charCodeAt(pos + 1) === 47 /* slash */) { + pos += 2; + return token = 29 /* LessThanSlashToken */; + } + pos++; + return token = 28 /* LessThanToken */; + } + if (char === 123 /* openBrace */) { + pos++; + return token = 18 /* OpenBraceToken */; + } + // First non-whitespace character on this line. + var firstNonWhitespace = 0; + // These initial values are special because the first line is: + // firstNonWhitespace = 0 to indicate that we want leading whitspace, + while (pos < end) { + char = text.charCodeAt(pos); + if (char === 123 /* openBrace */) { + break; + } + if (char === 60 /* lessThan */) { + if (isConflictMarkerTrivia(text, pos)) { + pos = scanConflictMarkerTrivia(text, pos, error); + return token = 7 /* ConflictMarkerTrivia */; + } + break; + } + // FirstNonWhitespace is 0, then we only see whitespaces so far. If we see a linebreak, we want to ignore that whitespaces. + // i.e (- : whitespace) + //
      ---- + //
      becomes
      + // + //
      ----
      becomes
      ----
      + if (isLineBreak(char) && firstNonWhitespace === 0) { + firstNonWhitespace = -1; + } + else if (!isWhiteSpaceLike(char)) { + firstNonWhitespace = pos; + } + pos++; + } + return firstNonWhitespace === -1 ? 12 /* JsxTextAllWhiteSpaces */ : 11 /* JsxText */; + } + // Scans a JSX identifier; these differ from normal identifiers in that + // they allow dashes + function scanJsxIdentifier() { + if (tokenIsIdentifierOrKeyword(token)) { + var firstCharPosition = pos; + while (pos < end) { + var ch = text.charCodeAt(pos); + if (ch === 45 /* minus */ || ((firstCharPosition === pos) ? isIdentifierStart(ch, languageVersion) : isIdentifierPart(ch, languageVersion))) { + pos++; + } + else { + break; + } + } + tokenValue += text.substring(firstCharPosition, pos); + } + return token; + } + function scanJsxAttributeValue() { + startPos = pos; + switch (text.charCodeAt(pos)) { + case 34 /* doubleQuote */: + case 39 /* singleQuote */: + tokenValue = scanString(/*jsxAttributeString*/ true); + return token = 10 /* StringLiteral */; + default: + // If this scans anything other than `{`, it's a parse error. + return scan(); + } + } + function scanJSDocToken() { + startPos = tokenPos = pos; + tokenFlags = 0; + if (pos >= end) { + return token = 1 /* EndOfFileToken */; + } + var ch = text.charCodeAt(pos); + pos++; + switch (ch) { + case 9 /* tab */: + case 11 /* verticalTab */: + case 12 /* formFeed */: + case 32 /* space */: + while (pos < end && isWhiteSpaceSingleLine(text.charCodeAt(pos))) { + pos++; + } + return token = 5 /* WhitespaceTrivia */; + case 64 /* at */: + return token = 58 /* AtToken */; + case 10 /* lineFeed */: + case 13 /* carriageReturn */: + tokenFlags |= 1 /* PrecedingLineBreak */; + return token = 4 /* NewLineTrivia */; + case 42 /* asterisk */: + return token = 40 /* AsteriskToken */; + case 123 /* openBrace */: + return token = 18 /* OpenBraceToken */; + case 125 /* closeBrace */: + return token = 19 /* CloseBraceToken */; + case 91 /* openBracket */: + return token = 22 /* OpenBracketToken */; + case 93 /* closeBracket */: + return token = 23 /* CloseBracketToken */; + case 60 /* lessThan */: + return token = 28 /* LessThanToken */; + case 61 /* equals */: + return token = 59 /* EqualsToken */; + case 44 /* comma */: + return token = 27 /* CommaToken */; + case 46 /* dot */: + return token = 24 /* DotToken */; + case 96 /* backtick */: + while (pos < end && text.charCodeAt(pos) !== 96 /* backtick */) { + pos++; + } + tokenValue = text.substring(tokenPos + 1, pos); + pos++; + return token = 14 /* NoSubstitutionTemplateLiteral */; + } + if (isIdentifierStart(ch, 6 /* Latest */)) { + while (isIdentifierPart(text.charCodeAt(pos), 6 /* Latest */) && pos < end) { + pos++; + } + tokenValue = text.substring(tokenPos, pos); + return token = getIdentifierToken(); + } + else { + return token = 0 /* Unknown */; + } + } + function speculationHelper(callback, isLookahead) { + var savePos = pos; + var saveStartPos = startPos; + var saveTokenPos = tokenPos; + var saveToken = token; + var saveTokenValue = tokenValue; + var saveTokenFlags = tokenFlags; + var result = callback(); + // If our callback returned something 'falsy' or we're just looking ahead, + // then unconditionally restore us to where we were. + if (!result || isLookahead) { + pos = savePos; + startPos = saveStartPos; + tokenPos = saveTokenPos; + token = saveToken; + tokenValue = saveTokenValue; + tokenFlags = saveTokenFlags; + } + return result; + } + function scanRange(start, length, callback) { + var saveEnd = end; + var savePos = pos; + var saveStartPos = startPos; + var saveTokenPos = tokenPos; + var saveToken = token; + var saveTokenValue = tokenValue; + var saveTokenFlags = tokenFlags; + setText(text, start, length); + var result = callback(); + end = saveEnd; + pos = savePos; + startPos = saveStartPos; + tokenPos = saveTokenPos; + token = saveToken; + tokenValue = saveTokenValue; + tokenFlags = saveTokenFlags; + return result; + } + function lookAhead(callback) { + return speculationHelper(callback, /*isLookahead*/ true); + } + function tryScan(callback) { + return speculationHelper(callback, /*isLookahead*/ false); + } + function getText() { + return text; + } + function setText(newText, start, length) { + text = newText || ""; + end = length === undefined ? text.length : start + length; + setTextPos(start || 0); + } + function setOnError(errorCallback) { + onError = errorCallback; + } + function setScriptTarget(scriptTarget) { + languageVersion = scriptTarget; + } + function setLanguageVariant(variant) { + languageVariant = variant; + } + function setTextPos(textPos) { + ts.Debug.assert(textPos >= 0); + pos = textPos; + startPos = textPos; + tokenPos = textPos; + token = 0 /* Unknown */; + tokenValue = undefined; + tokenFlags = 0; + } + function setInJSDocType(inType) { + inJSDocType += inType ? 1 : -1; + } + } + ts.createScanner = createScanner; +})(ts || (ts = {})); +var ts; +(function (ts) { + function isExternalModuleNameRelative(moduleName) { + // TypeScript 1.0 spec (April 2014): 11.2.1 + // An external module name is "relative" if the first term is "." or "..". + // Update: We also consider a path like `C:\foo.ts` "relative" because we do not search for it in `node_modules` or treat it as an ambient module. + return ts.pathIsRelative(moduleName) || ts.isRootedDiskPath(moduleName); + } + ts.isExternalModuleNameRelative = isExternalModuleNameRelative; + function sortAndDeduplicateDiagnostics(diagnostics) { + return ts.sortAndDeduplicate(diagnostics, ts.compareDiagnostics); + } + ts.sortAndDeduplicateDiagnostics = sortAndDeduplicateDiagnostics; +})(ts || (ts = {})); +/* @internal */ +(function (ts) { + ts.resolvingEmptyArray = []; + ts.emptyMap = ts.createMap(); + ts.emptyUnderscoreEscapedMap = ts.emptyMap; + ts.externalHelpersModuleNameText = "tslib"; + ts.defaultMaximumTruncationLength = 160; + function getDeclarationOfKind(symbol, kind) { + var declarations = symbol.declarations; + if (declarations) { + for (var _i = 0, declarations_1 = declarations; _i < declarations_1.length; _i++) { + var declaration = declarations_1[_i]; + if (declaration.kind === kind) { + return declaration; + } + } + } + return undefined; + } + ts.getDeclarationOfKind = getDeclarationOfKind; + /** Create a new escaped identifier map. */ + function createUnderscoreEscapedMap() { + return new ts.MapCtr(); + } + ts.createUnderscoreEscapedMap = createUnderscoreEscapedMap; + function hasEntries(map) { + return !!map && !!map.size; + } + ts.hasEntries = hasEntries; + function createSymbolTable(symbols) { + var result = ts.createMap(); + if (symbols) { + for (var _i = 0, symbols_1 = symbols; _i < symbols_1.length; _i++) { + var symbol = symbols_1[_i]; + result.set(symbol.escapedName, symbol); + } + } + return result; + } + ts.createSymbolTable = createSymbolTable; + var stringWriter = createSingleLineStringWriter(); + function createSingleLineStringWriter() { + var str = ""; + var writeText = function (text) { return str += text; }; + return { + getText: function () { return str; }, + write: writeText, + rawWrite: writeText, + writeKeyword: writeText, + writeOperator: writeText, + writePunctuation: writeText, + writeSpace: writeText, + writeStringLiteral: writeText, + writeLiteral: writeText, + writeParameter: writeText, + writeProperty: writeText, + writeSymbol: function (s, _) { return writeText(s); }, + writeTrailingSemicolon: writeText, + writeComment: writeText, + getTextPos: function () { return str.length; }, + getLine: function () { return 0; }, + getColumn: function () { return 0; }, + getIndent: function () { return 0; }, + isAtStartOfLine: function () { return false; }, + // Completely ignore indentation for string writers. And map newlines to + // a single space. + writeLine: function () { return str += " "; }, + increaseIndent: ts.noop, + decreaseIndent: ts.noop, + clear: function () { return str = ""; }, + trackSymbol: ts.noop, + reportInaccessibleThisError: ts.noop, + reportInaccessibleUniqueSymbolError: ts.noop, + reportPrivateInBaseOfClassExpression: ts.noop, + }; + } + function toPath(fileName, basePath, getCanonicalFileName) { + var nonCanonicalizedPath = ts.isRootedDiskPath(fileName) + ? ts.normalizePath(fileName) + : ts.getNormalizedAbsolutePath(fileName, basePath); + return getCanonicalFileName(nonCanonicalizedPath); + } + ts.toPath = toPath; + function changesAffectModuleResolution(oldOptions, newOptions) { + return oldOptions.configFilePath !== newOptions.configFilePath || ts.moduleResolutionOptionDeclarations.some(function (o) { + return !ts.isJsonEqual(ts.getCompilerOptionValue(oldOptions, o), ts.getCompilerOptionValue(newOptions, o)); + }); + } + ts.changesAffectModuleResolution = changesAffectModuleResolution; + function findAncestor(node, callback) { + while (node) { + var result = callback(node); + if (result === "quit") { + return undefined; + } + else if (result) { + return node; + } + node = node.parent; + } + return undefined; + } + ts.findAncestor = findAncestor; + function forEachAncestor(node, callback) { + while (true) { + var res = callback(node); + if (res === "quit") + return undefined; + if (res !== undefined) + return res; + if (ts.isSourceFile(node)) + return undefined; + node = node.parent; + } + } + ts.forEachAncestor = forEachAncestor; + function forEachEntry(map, callback) { + var _a; + var iterator = map.entries(); + for (var _b = iterator.next(), pair = _b.value, done = _b.done; !done; _a = iterator.next(), pair = _a.value, done = _a.done, _a) { + var key = pair[0], value = pair[1]; + var result = callback(value, key); + if (result) { + return result; + } + } + return undefined; + } + ts.forEachEntry = forEachEntry; + function forEachKey(map, callback) { + var _a; + var iterator = map.keys(); + for (var _b = iterator.next(), key = _b.value, done = _b.done; !done; _a = iterator.next(), key = _a.value, done = _a.done, _a) { + var result = callback(key); + if (result) { + return result; + } + } + return undefined; + } + ts.forEachKey = forEachKey; + function copyEntries(source, target) { + source.forEach(function (value, key) { + target.set(key, value); + }); + } + ts.copyEntries = copyEntries; + function arrayToSet(array, makeKey) { + return ts.arrayToMap(array, makeKey || (function (s) { return s; }), function () { return true; }); + } + ts.arrayToSet = arrayToSet; + function cloneMap(map) { + var clone = ts.createMap(); + copyEntries(map, clone); + return clone; + } + ts.cloneMap = cloneMap; + function usingSingleLineStringWriter(action) { + var oldString = stringWriter.getText(); + try { + action(stringWriter); + return stringWriter.getText(); + } + finally { + stringWriter.clear(); + stringWriter.writeKeyword(oldString); + } + } + ts.usingSingleLineStringWriter = usingSingleLineStringWriter; + function getFullWidth(node) { + return node.end - node.pos; + } + ts.getFullWidth = getFullWidth; + function getResolvedModule(sourceFile, moduleNameText) { + return sourceFile && sourceFile.resolvedModules && sourceFile.resolvedModules.get(moduleNameText); + } + ts.getResolvedModule = getResolvedModule; + function setResolvedModule(sourceFile, moduleNameText, resolvedModule) { + if (!sourceFile.resolvedModules) { + sourceFile.resolvedModules = ts.createMap(); + } + sourceFile.resolvedModules.set(moduleNameText, resolvedModule); + } + ts.setResolvedModule = setResolvedModule; + function setResolvedTypeReferenceDirective(sourceFile, typeReferenceDirectiveName, resolvedTypeReferenceDirective) { + if (!sourceFile.resolvedTypeReferenceDirectiveNames) { + sourceFile.resolvedTypeReferenceDirectiveNames = ts.createMap(); + } + sourceFile.resolvedTypeReferenceDirectiveNames.set(typeReferenceDirectiveName, resolvedTypeReferenceDirective); + } + ts.setResolvedTypeReferenceDirective = setResolvedTypeReferenceDirective; + function projectReferenceIsEqualTo(oldRef, newRef) { + return oldRef.path === newRef.path && + !oldRef.prepend === !newRef.prepend && + !oldRef.circular === !newRef.circular; + } + ts.projectReferenceIsEqualTo = projectReferenceIsEqualTo; + function moduleResolutionIsEqualTo(oldResolution, newResolution) { + return oldResolution.isExternalLibraryImport === newResolution.isExternalLibraryImport && + oldResolution.extension === newResolution.extension && + oldResolution.resolvedFileName === newResolution.resolvedFileName && + oldResolution.originalPath === newResolution.originalPath && + packageIdIsEqual(oldResolution.packageId, newResolution.packageId); + } + ts.moduleResolutionIsEqualTo = moduleResolutionIsEqualTo; + function packageIdIsEqual(a, b) { + return a === b || !!a && !!b && a.name === b.name && a.subModuleName === b.subModuleName && a.version === b.version; + } + function packageIdToString(_a) { + var name = _a.name, subModuleName = _a.subModuleName, version = _a.version; + var fullName = subModuleName ? name + "/" + subModuleName : name; + return fullName + "@" + version; + } + ts.packageIdToString = packageIdToString; + function typeDirectiveIsEqualTo(oldResolution, newResolution) { + return oldResolution.resolvedFileName === newResolution.resolvedFileName && oldResolution.primary === newResolution.primary; + } + ts.typeDirectiveIsEqualTo = typeDirectiveIsEqualTo; + function hasChangesInResolutions(names, newResolutions, oldResolutions, comparer) { + ts.Debug.assert(names.length === newResolutions.length); + for (var i = 0; i < names.length; i++) { + var newResolution = newResolutions[i]; + var oldResolution = oldResolutions && oldResolutions.get(names[i]); + var changed = oldResolution + ? !newResolution || !comparer(oldResolution, newResolution) + : newResolution; + if (changed) { + return true; + } + } + return false; + } + ts.hasChangesInResolutions = hasChangesInResolutions; + // Returns true if this node contains a parse error anywhere underneath it. + function containsParseError(node) { + aggregateChildData(node); + return (node.flags & 131072 /* ThisNodeOrAnySubNodesHasError */) !== 0; + } + ts.containsParseError = containsParseError; + function aggregateChildData(node) { + if (!(node.flags & 262144 /* HasAggregatedChildData */)) { + // A node is considered to contain a parse error if: + // a) the parser explicitly marked that it had an error + // b) any of it's children reported that it had an error. + var thisNodeOrAnySubNodesHasError = ((node.flags & 32768 /* ThisNodeHasError */) !== 0) || + ts.forEachChild(node, containsParseError); + // If so, mark ourselves accordingly. + if (thisNodeOrAnySubNodesHasError) { + node.flags |= 131072 /* ThisNodeOrAnySubNodesHasError */; + } + // Also mark that we've propagated the child information to this node. This way we can + // always consult the bit directly on this node without needing to check its children + // again. + node.flags |= 262144 /* HasAggregatedChildData */; + } + } + function getSourceFileOfNode(node) { + while (node && node.kind !== 279 /* SourceFile */) { + node = node.parent; + } + return node; + } + ts.getSourceFileOfNode = getSourceFileOfNode; + function isStatementWithLocals(node) { + switch (node.kind) { + case 218 /* Block */: + case 246 /* CaseBlock */: + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + return true; + } + return false; + } + ts.isStatementWithLocals = isStatementWithLocals; + function getStartPositionOfLine(line, sourceFile) { + ts.Debug.assert(line >= 0); + return ts.getLineStarts(sourceFile)[line]; + } + ts.getStartPositionOfLine = getStartPositionOfLine; + // This is a useful function for debugging purposes. + function nodePosToString(node) { + var file = getSourceFileOfNode(node); + var loc = ts.getLineAndCharacterOfPosition(file, node.pos); + return file.fileName + "(" + (loc.line + 1) + "," + (loc.character + 1) + ")"; + } + ts.nodePosToString = nodePosToString; + function getEndLinePosition(line, sourceFile) { + ts.Debug.assert(line >= 0); + var lineStarts = ts.getLineStarts(sourceFile); + var lineIndex = line; + var sourceText = sourceFile.text; + if (lineIndex + 1 === lineStarts.length) { + // last line - return EOF + return sourceText.length - 1; + } + else { + // current line start + var start = lineStarts[lineIndex]; + // take the start position of the next line - 1 = it should be some line break + var pos = lineStarts[lineIndex + 1] - 1; + ts.Debug.assert(ts.isLineBreak(sourceText.charCodeAt(pos))); + // walk backwards skipping line breaks, stop the the beginning of current line. + // i.e: + // + // $ <- end of line for this position should match the start position + while (start <= pos && ts.isLineBreak(sourceText.charCodeAt(pos))) { + pos--; + } + return pos; + } + } + ts.getEndLinePosition = getEndLinePosition; + /** + * Returns a value indicating whether a name is unique globally or within the current file. + * Note: This does not consider whether a name appears as a free identifier or not, so at the expression `x.y` this includes both `x` and `y`. + */ + function isFileLevelUniqueName(sourceFile, name, hasGlobalName) { + return !(hasGlobalName && hasGlobalName(name)) && !sourceFile.identifiers.has(name); + } + ts.isFileLevelUniqueName = isFileLevelUniqueName; + // Returns true if this node is missing from the actual source code. A 'missing' node is different + // from 'undefined/defined'. When a node is undefined (which can happen for optional nodes + // in the tree), it is definitely missing. However, a node may be defined, but still be + // missing. This happens whenever the parser knows it needs to parse something, but can't + // get anything in the source code that it expects at that location. For example: + // + // let a: ; + // + // Here, the Type in the Type-Annotation is not-optional (as there is a colon in the source + // code). So the parser will attempt to parse out a type, and will create an actual node. + // However, this node will be 'missing' in the sense that no actual source-code/tokens are + // contained within it. + function nodeIsMissing(node) { + if (node === undefined) { + return true; + } + return node.pos === node.end && node.pos >= 0 && node.kind !== 1 /* EndOfFileToken */; + } + ts.nodeIsMissing = nodeIsMissing; + function nodeIsPresent(node) { + return !nodeIsMissing(node); + } + ts.nodeIsPresent = nodeIsPresent; + /** + * Prepends statements to an array while taking care of prologue directives. + */ + function addStatementsAfterPrologue(to, from) { + if (from === undefined || from.length === 0) + return to; + var statementIndex = 0; + // skip all prologue directives to insert at the correct position + for (; statementIndex < to.length; ++statementIndex) { + if (!isPrologueDirective(to[statementIndex])) { + break; + } + } + to.splice.apply(to, [statementIndex, 0].concat(from)); + return to; + } + ts.addStatementsAfterPrologue = addStatementsAfterPrologue; + /** + * Determine if the given comment is a triple-slash + * + * @return true if the comment is a triple-slash comment else false + */ + function isRecognizedTripleSlashComment(text, commentPos, commentEnd) { + // Verify this is /// comment, but do the regexp match only when we first can find /// in the comment text + // so that we don't end up computing comment string and doing match for all // comments + if (text.charCodeAt(commentPos + 1) === 47 /* slash */ && + commentPos + 2 < commentEnd && + text.charCodeAt(commentPos + 2) === 47 /* slash */) { + var textSubStr = text.substring(commentPos, commentEnd); + return textSubStr.match(ts.fullTripleSlashReferencePathRegEx) || + textSubStr.match(ts.fullTripleSlashAMDReferencePathRegEx) || + textSubStr.match(fullTripleSlashReferenceTypeReferenceDirectiveRegEx) || + textSubStr.match(defaultLibReferenceRegEx) ? + true : false; + } + return false; + } + ts.isRecognizedTripleSlashComment = isRecognizedTripleSlashComment; + function isPinnedComment(text, start) { + return text.charCodeAt(start + 1) === 42 /* asterisk */ && + text.charCodeAt(start + 2) === 33 /* exclamation */; + } + ts.isPinnedComment = isPinnedComment; + function getTokenPosOfNode(node, sourceFile, includeJsDoc) { + // With nodes that have no width (i.e. 'Missing' nodes), we actually *don't* + // want to skip trivia because this will launch us forward to the next token. + if (nodeIsMissing(node)) { + return node.pos; + } + if (ts.isJSDocNode(node)) { + return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos, /*stopAfterLineBreak*/ false, /*stopAtComments*/ true); + } + if (includeJsDoc && ts.hasJSDocNodes(node)) { + return getTokenPosOfNode(node.jsDoc[0]); + } + // For a syntax list, it is possible that one of its children has JSDocComment nodes, while + // the syntax list itself considers them as normal trivia. Therefore if we simply skip + // trivia for the list, we may have skipped the JSDocComment as well. So we should process its + // first child to determine the actual position of its first token. + if (node.kind === 306 /* SyntaxList */ && node._children.length > 0) { + return getTokenPosOfNode(node._children[0], sourceFile, includeJsDoc); + } + return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos); + } + ts.getTokenPosOfNode = getTokenPosOfNode; + function getNonDecoratorTokenPosOfNode(node, sourceFile) { + if (nodeIsMissing(node) || !node.decorators) { + return getTokenPosOfNode(node, sourceFile); + } + return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.decorators.end); + } + ts.getNonDecoratorTokenPosOfNode = getNonDecoratorTokenPosOfNode; + function getSourceTextOfNodeFromSourceFile(sourceFile, node, includeTrivia) { + if (includeTrivia === void 0) { includeTrivia = false; } + return getTextOfNodeFromSourceText(sourceFile.text, node, includeTrivia); + } + ts.getSourceTextOfNodeFromSourceFile = getSourceTextOfNodeFromSourceFile; + function isJSDocTypeExpressionOrChild(node) { + return node.kind === 283 /* JSDocTypeExpression */ || (node.parent && isJSDocTypeExpressionOrChild(node.parent)); + } + function getTextOfNodeFromSourceText(sourceText, node, includeTrivia) { + if (includeTrivia === void 0) { includeTrivia = false; } + if (nodeIsMissing(node)) { + return ""; + } + var text = sourceText.substring(includeTrivia ? node.pos : ts.skipTrivia(sourceText, node.pos), node.end); + if (isJSDocTypeExpressionOrChild(node)) { + // strip space + asterisk at line start + text = text.replace(/(^|\r?\n|\r)\s*\*\s*/g, "$1"); + } + return text; + } + ts.getTextOfNodeFromSourceText = getTextOfNodeFromSourceText; + function getTextOfNode(node, includeTrivia) { + if (includeTrivia === void 0) { includeTrivia = false; } + return getSourceTextOfNodeFromSourceFile(getSourceFileOfNode(node), node, includeTrivia); + } + ts.getTextOfNode = getTextOfNode; + function getPos(range) { + return range.pos; + } + /** + * Note: it is expected that the `nodeArray` and the `node` are within the same file. + * For example, searching for a `SourceFile` in a `SourceFile[]` wouldn't work. + */ + function indexOfNode(nodeArray, node) { + return ts.binarySearch(nodeArray, node, getPos, ts.compareValues); + } + ts.indexOfNode = indexOfNode; + /** + * Gets flags that control emit behavior of a node. + */ + function getEmitFlags(node) { + var emitNode = node.emitNode; + return emitNode && emitNode.flags || 0; + } + ts.getEmitFlags = getEmitFlags; + function getLiteralText(node, sourceFile, neverAsciiEscape) { + // If we don't need to downlevel and we can reach the original source text using + // the node's parent reference, then simply get the text as it was originally written. + if (!nodeIsSynthesized(node) && node.parent && !((ts.isNumericLiteral(node) && node.numericLiteralFlags & 512 /* ContainsSeparator */) || + ts.isBigIntLiteral(node))) { + return getSourceTextOfNodeFromSourceFile(sourceFile, node); + } + var escapeText = neverAsciiEscape || (getEmitFlags(node) & 16777216 /* NoAsciiEscaping */) ? escapeString : escapeNonAsciiString; + // If we can't reach the original source text, use the canonical form if it's a number, + // or a (possibly escaped) quoted form of the original text if it's string-like. + switch (node.kind) { + case 10 /* StringLiteral */: + if (node.singleQuote) { + return "'" + escapeText(node.text, 39 /* singleQuote */) + "'"; + } + else { + return '"' + escapeText(node.text, 34 /* doubleQuote */) + '"'; + } + case 14 /* NoSubstitutionTemplateLiteral */: + return "`" + escapeText(node.text, 96 /* backtick */) + "`"; + case 15 /* TemplateHead */: + // tslint:disable-next-line no-invalid-template-strings + return "`" + escapeText(node.text, 96 /* backtick */) + "${"; + case 16 /* TemplateMiddle */: + // tslint:disable-next-line no-invalid-template-strings + return "}" + escapeText(node.text, 96 /* backtick */) + "${"; + case 17 /* TemplateTail */: + return "}" + escapeText(node.text, 96 /* backtick */) + "`"; + case 8 /* NumericLiteral */: + case 9 /* BigIntLiteral */: + case 13 /* RegularExpressionLiteral */: + return node.text; + } + return ts.Debug.fail("Literal kind '" + node.kind + "' not accounted for."); + } + ts.getLiteralText = getLiteralText; + function getTextOfConstantValue(value) { + return ts.isString(value) ? '"' + escapeNonAsciiString(value) + '"' : "" + value; + } + ts.getTextOfConstantValue = getTextOfConstantValue; + // Make an identifier from an external module name by extracting the string after the last "/" and replacing + // all non-alphanumeric characters with underscores + function makeIdentifierFromModuleName(moduleName) { + return ts.getBaseFileName(moduleName).replace(/^(\d)/, "_$1").replace(/\W/g, "_"); + } + ts.makeIdentifierFromModuleName = makeIdentifierFromModuleName; + function isBlockOrCatchScoped(declaration) { + return (ts.getCombinedNodeFlags(declaration) & 3 /* BlockScoped */) !== 0 || + isCatchClauseVariableDeclarationOrBindingElement(declaration); + } + ts.isBlockOrCatchScoped = isBlockOrCatchScoped; + function isCatchClauseVariableDeclarationOrBindingElement(declaration) { + var node = getRootDeclaration(declaration); + return node.kind === 237 /* VariableDeclaration */ && node.parent.kind === 274 /* CatchClause */; + } + ts.isCatchClauseVariableDeclarationOrBindingElement = isCatchClauseVariableDeclarationOrBindingElement; + function isAmbientModule(node) { + return ts.isModuleDeclaration(node) && (node.name.kind === 10 /* StringLiteral */ || isGlobalScopeAugmentation(node)); + } + ts.isAmbientModule = isAmbientModule; + function isModuleWithStringLiteralName(node) { + return ts.isModuleDeclaration(node) && node.name.kind === 10 /* StringLiteral */; + } + ts.isModuleWithStringLiteralName = isModuleWithStringLiteralName; + function isNonGlobalAmbientModule(node) { + return ts.isModuleDeclaration(node) && ts.isStringLiteral(node.name); + } + ts.isNonGlobalAmbientModule = isNonGlobalAmbientModule; + /** + * An effective module (namespace) declaration is either + * 1. An actual declaration: namespace X { ... } + * 2. A Javascript declaration, which is: + * An identifier in a nested property access expression: Y in `X.Y.Z = { ... }` + */ + function isEffectiveModuleDeclaration(node) { + return ts.isModuleDeclaration(node) || ts.isIdentifier(node); + } + ts.isEffectiveModuleDeclaration = isEffectiveModuleDeclaration; + /** Given a symbol for a module, checks that it is a shorthand ambient module. */ + function isShorthandAmbientModuleSymbol(moduleSymbol) { + return isShorthandAmbientModule(moduleSymbol.valueDeclaration); + } + ts.isShorthandAmbientModuleSymbol = isShorthandAmbientModuleSymbol; + function isShorthandAmbientModule(node) { + // The only kind of module that can be missing a body is a shorthand ambient module. + return node && node.kind === 244 /* ModuleDeclaration */ && (!node.body); + } + function isBlockScopedContainerTopLevel(node) { + return node.kind === 279 /* SourceFile */ || + node.kind === 244 /* ModuleDeclaration */ || + ts.isFunctionLike(node); + } + ts.isBlockScopedContainerTopLevel = isBlockScopedContainerTopLevel; + function isGlobalScopeAugmentation(module) { + return !!(module.flags & 512 /* GlobalAugmentation */); + } + ts.isGlobalScopeAugmentation = isGlobalScopeAugmentation; + function isExternalModuleAugmentation(node) { + return isAmbientModule(node) && isModuleAugmentationExternal(node); + } + ts.isExternalModuleAugmentation = isExternalModuleAugmentation; + function isModuleAugmentationExternal(node) { + // external module augmentation is a ambient module declaration that is either: + // - defined in the top level scope and source file is an external module + // - defined inside ambient module declaration located in the top level scope and source file not an external module + switch (node.parent.kind) { + case 279 /* SourceFile */: + return ts.isExternalModule(node.parent); + case 245 /* ModuleBlock */: + return isAmbientModule(node.parent.parent) && ts.isSourceFile(node.parent.parent.parent) && !ts.isExternalModule(node.parent.parent.parent); + } + return false; + } + ts.isModuleAugmentationExternal = isModuleAugmentationExternal; + function getNonAugmentationDeclaration(symbol) { + return ts.find(symbol.declarations, function (d) { return !isExternalModuleAugmentation(d) && !(ts.isModuleDeclaration(d) && isGlobalScopeAugmentation(d)); }); + } + ts.getNonAugmentationDeclaration = getNonAugmentationDeclaration; + function isEffectiveExternalModule(node, compilerOptions) { + return ts.isExternalModule(node) || compilerOptions.isolatedModules || ((ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS) && !!node.commonJsModuleIndicator); + } + ts.isEffectiveExternalModule = isEffectiveExternalModule; + function isBlockScope(node, parentNode) { + switch (node.kind) { + case 279 /* SourceFile */: + case 246 /* CaseBlock */: + case 274 /* CatchClause */: + case 244 /* ModuleDeclaration */: + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + case 157 /* Constructor */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + return true; + case 218 /* Block */: + // function block is not considered block-scope container + // see comment in binder.ts: bind(...), case for SyntaxKind.Block + return !ts.isFunctionLike(parentNode); + } + return false; + } + ts.isBlockScope = isBlockScope; + function isDeclarationWithTypeParameters(node) { + switch (node.kind) { + case 297 /* JSDocCallbackTag */: + case 304 /* JSDocTypedefTag */: + case 293 /* JSDocSignature */: + return true; + default: + ts.assertType(node); + return isDeclarationWithTypeParameterChildren(node); + } + } + ts.isDeclarationWithTypeParameters = isDeclarationWithTypeParameters; + function isDeclarationWithTypeParameterChildren(node) { + switch (node.kind) { + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 155 /* MethodSignature */: + case 162 /* IndexSignature */: + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + case 289 /* JSDocFunctionType */: + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 241 /* InterfaceDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 303 /* JSDocTemplateTag */: + case 239 /* FunctionDeclaration */: + case 156 /* MethodDeclaration */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + return true; + default: + ts.assertType(node); + return false; + } + } + ts.isDeclarationWithTypeParameterChildren = isDeclarationWithTypeParameterChildren; + function isAnyImportSyntax(node) { + switch (node.kind) { + case 249 /* ImportDeclaration */: + case 248 /* ImportEqualsDeclaration */: + return true; + default: + return false; + } + } + ts.isAnyImportSyntax = isAnyImportSyntax; + function isLateVisibilityPaintedStatement(node) { + switch (node.kind) { + case 249 /* ImportDeclaration */: + case 248 /* ImportEqualsDeclaration */: + case 219 /* VariableStatement */: + case 240 /* ClassDeclaration */: + case 239 /* FunctionDeclaration */: + case 244 /* ModuleDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 241 /* InterfaceDeclaration */: + case 243 /* EnumDeclaration */: + return true; + default: + return false; + } + } + ts.isLateVisibilityPaintedStatement = isLateVisibilityPaintedStatement; + function isAnyImportOrReExport(node) { + return isAnyImportSyntax(node) || ts.isExportDeclaration(node); + } + ts.isAnyImportOrReExport = isAnyImportOrReExport; + // Gets the nearest enclosing block scope container that has the provided node + // as a descendant, that is not the provided node. + function getEnclosingBlockScopeContainer(node) { + return findAncestor(node.parent, function (current) { return isBlockScope(current, current.parent); }); + } + ts.getEnclosingBlockScopeContainer = getEnclosingBlockScopeContainer; + // Return display name of an identifier + // Computed property names will just be emitted as "[]", where is the source + // text of the expression in the computed property. + function declarationNameToString(name) { + return !name || getFullWidth(name) === 0 ? "(Missing)" : getTextOfNode(name); + } + ts.declarationNameToString = declarationNameToString; + function getNameFromIndexInfo(info) { + return info.declaration ? declarationNameToString(info.declaration.parameters[0].name) : undefined; + } + ts.getNameFromIndexInfo = getNameFromIndexInfo; + function getTextOfPropertyName(name) { + switch (name.kind) { + case 72 /* Identifier */: + return name.escapedText; + case 10 /* StringLiteral */: + case 8 /* NumericLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: + return ts.escapeLeadingUnderscores(name.text); + case 149 /* ComputedPropertyName */: + return isStringOrNumericLiteralLike(name.expression) ? ts.escapeLeadingUnderscores(name.expression.text) : undefined; // TODO: GH#18217 Almost all uses of this assume the result to be defined! + default: + return ts.Debug.assertNever(name); + } + } + ts.getTextOfPropertyName = getTextOfPropertyName; + function entityNameToString(name) { + switch (name.kind) { + case 72 /* Identifier */: + return getFullWidth(name) === 0 ? ts.idText(name) : getTextOfNode(name); + case 148 /* QualifiedName */: + return entityNameToString(name.left) + "." + entityNameToString(name.right); + case 189 /* PropertyAccessExpression */: + return entityNameToString(name.expression) + "." + entityNameToString(name.name); + default: + throw ts.Debug.assertNever(name); + } + } + ts.entityNameToString = entityNameToString; + function createDiagnosticForNode(node, message, arg0, arg1, arg2, arg3) { + var sourceFile = getSourceFileOfNode(node); + return createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2, arg3); + } + ts.createDiagnosticForNode = createDiagnosticForNode; + function createDiagnosticForNodeArray(sourceFile, nodes, message, arg0, arg1, arg2, arg3) { + var start = ts.skipTrivia(sourceFile.text, nodes.pos); + return ts.createFileDiagnostic(sourceFile, start, nodes.end - start, message, arg0, arg1, arg2, arg3); + } + ts.createDiagnosticForNodeArray = createDiagnosticForNodeArray; + function createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2, arg3) { + var span = getErrorSpanForNode(sourceFile, node); + return ts.createFileDiagnostic(sourceFile, span.start, span.length, message, arg0, arg1, arg2, arg3); + } + ts.createDiagnosticForNodeInSourceFile = createDiagnosticForNodeInSourceFile; + function createDiagnosticForNodeFromMessageChain(node, messageChain, relatedInformation) { + var sourceFile = getSourceFileOfNode(node); + var span = getErrorSpanForNode(sourceFile, node); + return { + file: sourceFile, + start: span.start, + length: span.length, + code: messageChain.code, + category: messageChain.category, + messageText: messageChain.next ? messageChain : messageChain.messageText, + relatedInformation: relatedInformation + }; + } + ts.createDiagnosticForNodeFromMessageChain = createDiagnosticForNodeFromMessageChain; + function getSpanOfTokenAtPosition(sourceFile, pos) { + var scanner = ts.createScanner(sourceFile.languageVersion, /*skipTrivia*/ true, sourceFile.languageVariant, sourceFile.text, /*onError:*/ undefined, pos); + scanner.scan(); + var start = scanner.getTokenPos(); + return ts.createTextSpanFromBounds(start, scanner.getTextPos()); + } + ts.getSpanOfTokenAtPosition = getSpanOfTokenAtPosition; + function getErrorSpanForArrowFunction(sourceFile, node) { + var pos = ts.skipTrivia(sourceFile.text, node.pos); + if (node.body && node.body.kind === 218 /* Block */) { + var startLine = ts.getLineAndCharacterOfPosition(sourceFile, node.body.pos).line; + var endLine = ts.getLineAndCharacterOfPosition(sourceFile, node.body.end).line; + if (startLine < endLine) { + // The arrow function spans multiple lines, + // make the error span be the first line, inclusive. + return ts.createTextSpan(pos, getEndLinePosition(startLine, sourceFile) - pos + 1); + } + } + return ts.createTextSpanFromBounds(pos, node.end); + } + function getErrorSpanForNode(sourceFile, node) { + var errorNode = node; + switch (node.kind) { + case 279 /* SourceFile */: + var pos_1 = ts.skipTrivia(sourceFile.text, 0, /*stopAfterLineBreak*/ false); + if (pos_1 === sourceFile.text.length) { + // file is empty - return span for the beginning of the file + return ts.createTextSpan(0, 0); + } + return getSpanOfTokenAtPosition(sourceFile, pos_1); + // This list is a work in progress. Add missing node kinds to improve their error + // spans. + case 237 /* VariableDeclaration */: + case 186 /* BindingElement */: + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 241 /* InterfaceDeclaration */: + case 244 /* ModuleDeclaration */: + case 243 /* EnumDeclaration */: + case 278 /* EnumMember */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 242 /* TypeAliasDeclaration */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + errorNode = node.name; + break; + case 197 /* ArrowFunction */: + return getErrorSpanForArrowFunction(sourceFile, node); + } + if (errorNode === undefined) { + // If we don't have a better node, then just set the error on the first token of + // construct. + return getSpanOfTokenAtPosition(sourceFile, node.pos); + } + var isMissing = nodeIsMissing(errorNode); + var pos = isMissing + ? errorNode.pos + : ts.skipTrivia(sourceFile.text, errorNode.pos); + // These asserts should all be satisfied for a properly constructed `errorNode`. + if (isMissing) { + ts.Debug.assert(pos === errorNode.pos, "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809"); + ts.Debug.assert(pos === errorNode.end, "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809"); + } + else { + ts.Debug.assert(pos >= errorNode.pos, "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809"); + ts.Debug.assert(pos <= errorNode.end, "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809"); + } + return ts.createTextSpanFromBounds(pos, errorNode.end); + } + ts.getErrorSpanForNode = getErrorSpanForNode; + function isExternalOrCommonJsModule(file) { + return (file.externalModuleIndicator || file.commonJsModuleIndicator) !== undefined; + } + ts.isExternalOrCommonJsModule = isExternalOrCommonJsModule; + function isJsonSourceFile(file) { + return file.scriptKind === 6 /* JSON */; + } + ts.isJsonSourceFile = isJsonSourceFile; + function isEnumConst(node) { + return !!(ts.getCombinedModifierFlags(node) & 2048 /* Const */); + } + ts.isEnumConst = isEnumConst; + function isDeclarationReadonly(declaration) { + return !!(ts.getCombinedModifierFlags(declaration) & 64 /* Readonly */ && !ts.isParameterPropertyDeclaration(declaration)); + } + ts.isDeclarationReadonly = isDeclarationReadonly; + function isVarConst(node) { + return !!(ts.getCombinedNodeFlags(node) & 2 /* Const */); + } + ts.isVarConst = isVarConst; + function isLet(node) { + return !!(ts.getCombinedNodeFlags(node) & 1 /* Let */); + } + ts.isLet = isLet; + function isSuperCall(n) { + return n.kind === 191 /* CallExpression */ && n.expression.kind === 98 /* SuperKeyword */; + } + ts.isSuperCall = isSuperCall; + function isImportCall(n) { + return n.kind === 191 /* CallExpression */ && n.expression.kind === 92 /* ImportKeyword */; + } + ts.isImportCall = isImportCall; + function isLiteralImportTypeNode(n) { + return ts.isImportTypeNode(n) && ts.isLiteralTypeNode(n.argument) && ts.isStringLiteral(n.argument.literal); + } + ts.isLiteralImportTypeNode = isLiteralImportTypeNode; + function isPrologueDirective(node) { + return node.kind === 221 /* ExpressionStatement */ + && node.expression.kind === 10 /* StringLiteral */; + } + ts.isPrologueDirective = isPrologueDirective; + function getLeadingCommentRangesOfNode(node, sourceFileOfNode) { + return node.kind !== 11 /* JsxText */ ? ts.getLeadingCommentRanges(sourceFileOfNode.text, node.pos) : undefined; + } + ts.getLeadingCommentRangesOfNode = getLeadingCommentRangesOfNode; + function getJSDocCommentRanges(node, text) { + var commentRanges = (node.kind === 151 /* Parameter */ || + node.kind === 150 /* TypeParameter */ || + node.kind === 196 /* FunctionExpression */ || + node.kind === 197 /* ArrowFunction */ || + node.kind === 195 /* ParenthesizedExpression */) ? + ts.concatenate(ts.getTrailingCommentRanges(text, node.pos), ts.getLeadingCommentRanges(text, node.pos)) : + ts.getLeadingCommentRanges(text, node.pos); + // True if the comment starts with '/**' but not if it is '/**/' + return ts.filter(commentRanges, function (comment) { + return text.charCodeAt(comment.pos + 1) === 42 /* asterisk */ && + text.charCodeAt(comment.pos + 2) === 42 /* asterisk */ && + text.charCodeAt(comment.pos + 3) !== 47 /* slash */; + }); + } + ts.getJSDocCommentRanges = getJSDocCommentRanges; + ts.fullTripleSlashReferencePathRegEx = /^(\/\/\/\s*/; + var fullTripleSlashReferenceTypeReferenceDirectiveRegEx = /^(\/\/\/\s*/; + ts.fullTripleSlashAMDReferencePathRegEx = /^(\/\/\/\s*/; + var defaultLibReferenceRegEx = /^(\/\/\/\s*/; + function isPartOfTypeNode(node) { + if (163 /* FirstTypeNode */ <= node.kind && node.kind <= 183 /* LastTypeNode */) { + return true; + } + switch (node.kind) { + case 120 /* AnyKeyword */: + case 143 /* UnknownKeyword */: + case 135 /* NumberKeyword */: + case 146 /* BigIntKeyword */: + case 138 /* StringKeyword */: + case 123 /* BooleanKeyword */: + case 139 /* SymbolKeyword */: + case 136 /* ObjectKeyword */: + case 141 /* UndefinedKeyword */: + case 132 /* NeverKeyword */: + return true; + case 106 /* VoidKeyword */: + return node.parent.kind !== 200 /* VoidExpression */; + case 211 /* ExpressionWithTypeArguments */: + return !isExpressionWithTypeArgumentsInClassExtendsClause(node); + case 150 /* TypeParameter */: + return node.parent.kind === 181 /* MappedType */ || node.parent.kind === 176 /* InferType */; + // Identifiers and qualified names may be type nodes, depending on their context. Climb + // above them to find the lowest container + case 72 /* Identifier */: + // If the identifier is the RHS of a qualified name, then it's a type iff its parent is. + if (node.parent.kind === 148 /* QualifiedName */ && node.parent.right === node) { + node = node.parent; + } + else if (node.parent.kind === 189 /* PropertyAccessExpression */ && node.parent.name === node) { + node = node.parent; + } + // At this point, node is either a qualified name or an identifier + ts.Debug.assert(node.kind === 72 /* Identifier */ || node.kind === 148 /* QualifiedName */ || node.kind === 189 /* PropertyAccessExpression */, "'node' was expected to be a qualified name, identifier or property access in 'isPartOfTypeNode'."); + // falls through + case 148 /* QualifiedName */: + case 189 /* PropertyAccessExpression */: + case 100 /* ThisKeyword */: { + var parent = node.parent; + if (parent.kind === 167 /* TypeQuery */) { + return false; + } + if (parent.kind === 183 /* ImportType */) { + return !parent.isTypeOf; + } + // Do not recursively call isPartOfTypeNode on the parent. In the example: + // + // let a: A.B.C; + // + // Calling isPartOfTypeNode would consider the qualified name A.B a type node. + // Only C and A.B.C are type nodes. + if (163 /* FirstTypeNode */ <= parent.kind && parent.kind <= 183 /* LastTypeNode */) { + return true; + } + switch (parent.kind) { + case 211 /* ExpressionWithTypeArguments */: + return !isExpressionWithTypeArgumentsInClassExtendsClause(parent); + case 150 /* TypeParameter */: + return node === parent.constraint; + case 303 /* JSDocTemplateTag */: + return node === parent.constraint; + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 151 /* Parameter */: + case 237 /* VariableDeclaration */: + return node === parent.type; + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 157 /* Constructor */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + return node === parent.type; + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 162 /* IndexSignature */: + return node === parent.type; + case 194 /* TypeAssertionExpression */: + return node === parent.type; + case 191 /* CallExpression */: + case 192 /* NewExpression */: + return ts.contains(parent.typeArguments, node); + case 193 /* TaggedTemplateExpression */: + // TODO (drosen): TaggedTemplateExpressions may eventually support type arguments. + return false; + } + } + } + return false; + } + ts.isPartOfTypeNode = isPartOfTypeNode; + function isChildOfNodeWithKind(node, kind) { + while (node) { + if (node.kind === kind) { + return true; + } + node = node.parent; + } + return false; + } + ts.isChildOfNodeWithKind = isChildOfNodeWithKind; + // Warning: This has the same semantics as the forEach family of functions, + // in that traversal terminates in the event that 'visitor' supplies a truthy value. + function forEachReturnStatement(body, visitor) { + return traverse(body); + function traverse(node) { + switch (node.kind) { + case 230 /* ReturnStatement */: + return visitor(node); + case 246 /* CaseBlock */: + case 218 /* Block */: + case 222 /* IfStatement */: + case 223 /* DoStatement */: + case 224 /* WhileStatement */: + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + case 231 /* WithStatement */: + case 232 /* SwitchStatement */: + case 271 /* CaseClause */: + case 272 /* DefaultClause */: + case 233 /* LabeledStatement */: + case 235 /* TryStatement */: + case 274 /* CatchClause */: + return ts.forEachChild(node, traverse); + } + } + } + ts.forEachReturnStatement = forEachReturnStatement; + function forEachYieldExpression(body, visitor) { + return traverse(body); + function traverse(node) { + switch (node.kind) { + case 207 /* YieldExpression */: + visitor(node); + var operand = node.expression; + if (operand) { + traverse(operand); + } + return; + case 243 /* EnumDeclaration */: + case 241 /* InterfaceDeclaration */: + case 244 /* ModuleDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + // These are not allowed inside a generator now, but eventually they may be allowed + // as local types. Regardless, any yield statements contained within them should be + // skipped in this traversal. + return; + default: + if (ts.isFunctionLike(node)) { + if (node.name && node.name.kind === 149 /* ComputedPropertyName */) { + // Note that we will not include methods/accessors of a class because they would require + // first descending into the class. This is by design. + traverse(node.name.expression); + return; + } + } + else if (!isPartOfTypeNode(node)) { + // This is the general case, which should include mostly expressions and statements. + // Also includes NodeArrays. + ts.forEachChild(node, traverse); + } + } + } + } + ts.forEachYieldExpression = forEachYieldExpression; + /** + * Gets the most likely element type for a TypeNode. This is not an exhaustive test + * as it assumes a rest argument can only be an array type (either T[], or Array). + * + * @param node The type node. + */ + function getRestParameterElementType(node) { + if (node && node.kind === 169 /* ArrayType */) { + return node.elementType; + } + else if (node && node.kind === 164 /* TypeReference */) { + return ts.singleOrUndefined(node.typeArguments); + } + else { + return undefined; + } + } + ts.getRestParameterElementType = getRestParameterElementType; + function getMembersOfDeclaration(node) { + switch (node.kind) { + case 241 /* InterfaceDeclaration */: + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 168 /* TypeLiteral */: + return node.members; + case 188 /* ObjectLiteralExpression */: + return node.properties; + } + } + ts.getMembersOfDeclaration = getMembersOfDeclaration; + function isVariableLike(node) { + if (node) { + switch (node.kind) { + case 186 /* BindingElement */: + case 278 /* EnumMember */: + case 151 /* Parameter */: + case 275 /* PropertyAssignment */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 276 /* ShorthandPropertyAssignment */: + case 237 /* VariableDeclaration */: + return true; + } + } + return false; + } + ts.isVariableLike = isVariableLike; + function isVariableLikeOrAccessor(node) { + return isVariableLike(node) || ts.isAccessor(node); + } + ts.isVariableLikeOrAccessor = isVariableLikeOrAccessor; + function isVariableDeclarationInVariableStatement(node) { + return node.parent.kind === 238 /* VariableDeclarationList */ + && node.parent.parent.kind === 219 /* VariableStatement */; + } + ts.isVariableDeclarationInVariableStatement = isVariableDeclarationInVariableStatement; + function isValidESSymbolDeclaration(node) { + return ts.isVariableDeclaration(node) ? isVarConst(node) && ts.isIdentifier(node.name) && isVariableDeclarationInVariableStatement(node) : + ts.isPropertyDeclaration(node) ? hasReadonlyModifier(node) && hasStaticModifier(node) : + ts.isPropertySignature(node) && hasReadonlyModifier(node); + } + ts.isValidESSymbolDeclaration = isValidESSymbolDeclaration; + function introducesArgumentsExoticObject(node) { + switch (node.kind) { + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + return true; + } + return false; + } + ts.introducesArgumentsExoticObject = introducesArgumentsExoticObject; + function unwrapInnermostStatementOfLabel(node, beforeUnwrapLabelCallback) { + while (true) { + if (beforeUnwrapLabelCallback) { + beforeUnwrapLabelCallback(node); + } + if (node.statement.kind !== 233 /* LabeledStatement */) { + return node.statement; + } + node = node.statement; + } + } + ts.unwrapInnermostStatementOfLabel = unwrapInnermostStatementOfLabel; + function isFunctionBlock(node) { + return node && node.kind === 218 /* Block */ && ts.isFunctionLike(node.parent); + } + ts.isFunctionBlock = isFunctionBlock; + function isObjectLiteralMethod(node) { + return node && node.kind === 156 /* MethodDeclaration */ && node.parent.kind === 188 /* ObjectLiteralExpression */; + } + ts.isObjectLiteralMethod = isObjectLiteralMethod; + function isObjectLiteralOrClassExpressionMethod(node) { + return node.kind === 156 /* MethodDeclaration */ && + (node.parent.kind === 188 /* ObjectLiteralExpression */ || + node.parent.kind === 209 /* ClassExpression */); + } + ts.isObjectLiteralOrClassExpressionMethod = isObjectLiteralOrClassExpressionMethod; + function isIdentifierTypePredicate(predicate) { + return predicate && predicate.kind === 1 /* Identifier */; + } + ts.isIdentifierTypePredicate = isIdentifierTypePredicate; + function isThisTypePredicate(predicate) { + return predicate && predicate.kind === 0 /* This */; + } + ts.isThisTypePredicate = isThisTypePredicate; + function getPropertyAssignment(objectLiteral, key, key2) { + return objectLiteral.properties.filter(function (property) { + if (property.kind === 275 /* PropertyAssignment */) { + var propName = getTextOfPropertyName(property.name); + return key === propName || (!!key2 && key2 === propName); + } + return false; + }); + } + ts.getPropertyAssignment = getPropertyAssignment; + function getTsConfigObjectLiteralExpression(tsConfigSourceFile) { + if (tsConfigSourceFile && tsConfigSourceFile.statements.length) { + var expression = tsConfigSourceFile.statements[0].expression; + return ts.tryCast(expression, ts.isObjectLiteralExpression); + } + } + ts.getTsConfigObjectLiteralExpression = getTsConfigObjectLiteralExpression; + function getTsConfigPropArrayElementValue(tsConfigSourceFile, propKey, elementValue) { + return ts.firstDefined(getTsConfigPropArray(tsConfigSourceFile, propKey), function (property) { + return ts.isArrayLiteralExpression(property.initializer) ? + ts.find(property.initializer.elements, function (element) { return ts.isStringLiteral(element) && element.text === elementValue; }) : + undefined; + }); + } + ts.getTsConfigPropArrayElementValue = getTsConfigPropArrayElementValue; + function getTsConfigPropArray(tsConfigSourceFile, propKey) { + var jsonObjectLiteral = getTsConfigObjectLiteralExpression(tsConfigSourceFile); + return jsonObjectLiteral ? getPropertyAssignment(jsonObjectLiteral, propKey) : ts.emptyArray; + } + ts.getTsConfigPropArray = getTsConfigPropArray; + function getContainingFunction(node) { + return findAncestor(node.parent, ts.isFunctionLike); + } + ts.getContainingFunction = getContainingFunction; + function getContainingClass(node) { + return findAncestor(node.parent, ts.isClassLike); + } + ts.getContainingClass = getContainingClass; + function getThisContainer(node, includeArrowFunctions) { + ts.Debug.assert(node.kind !== 279 /* SourceFile */); + while (true) { + node = node.parent; + if (!node) { + return ts.Debug.fail(); // If we never pass in a SourceFile, this should be unreachable, since we'll stop when we reach that. + } + switch (node.kind) { + case 149 /* ComputedPropertyName */: + // If the grandparent node is an object literal (as opposed to a class), + // then the computed property is not a 'this' container. + // A computed property name in a class needs to be a this container + // so that we can error on it. + if (ts.isClassLike(node.parent.parent)) { + return node; + } + // If this is a computed property, then the parent should not + // make it a this container. The parent might be a property + // in an object literal, like a method or accessor. But in order for + // such a parent to be a this container, the reference must be in + // the *body* of the container. + node = node.parent; + break; + case 152 /* Decorator */: + // Decorators are always applied outside of the body of a class or method. + if (node.parent.kind === 151 /* Parameter */ && ts.isClassElement(node.parent.parent)) { + // If the decorator's parent is a Parameter, we resolve the this container from + // the grandparent class declaration. + node = node.parent.parent; + } + else if (ts.isClassElement(node.parent)) { + // If the decorator's parent is a class element, we resolve the 'this' container + // from the parent class declaration. + node = node.parent; + } + break; + case 197 /* ArrowFunction */: + if (!includeArrowFunctions) { + continue; + } + // falls through + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 244 /* ModuleDeclaration */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 162 /* IndexSignature */: + case 243 /* EnumDeclaration */: + case 279 /* SourceFile */: + return node; + } + } + } + ts.getThisContainer = getThisContainer; + function getNewTargetContainer(node) { + var container = getThisContainer(node, /*includeArrowFunctions*/ false); + if (container) { + switch (container.kind) { + case 157 /* Constructor */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + return container; + } + } + return undefined; + } + ts.getNewTargetContainer = getNewTargetContainer; + /** + * Given an super call/property node, returns the closest node where + * - a super call/property access is legal in the node and not legal in the parent node the node. + * i.e. super call is legal in constructor but not legal in the class body. + * - the container is an arrow function (so caller might need to call getSuperContainer again in case it needs to climb higher) + * - a super call/property is definitely illegal in the container (but might be legal in some subnode) + * i.e. super property access is illegal in function declaration but can be legal in the statement list + */ + function getSuperContainer(node, stopOnFunctions) { + while (true) { + node = node.parent; + if (!node) { + return node; + } + switch (node.kind) { + case 149 /* ComputedPropertyName */: + node = node.parent; + break; + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + if (!stopOnFunctions) { + continue; + } + // falls through + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + return node; + case 152 /* Decorator */: + // Decorators are always applied outside of the body of a class or method. + if (node.parent.kind === 151 /* Parameter */ && ts.isClassElement(node.parent.parent)) { + // If the decorator's parent is a Parameter, we resolve the this container from + // the grandparent class declaration. + node = node.parent.parent; + } + else if (ts.isClassElement(node.parent)) { + // If the decorator's parent is a class element, we resolve the 'this' container + // from the parent class declaration. + node = node.parent; + } + break; + } + } + } + ts.getSuperContainer = getSuperContainer; + function getImmediatelyInvokedFunctionExpression(func) { + if (func.kind === 196 /* FunctionExpression */ || func.kind === 197 /* ArrowFunction */) { + var prev = func; + var parent = func.parent; + while (parent.kind === 195 /* ParenthesizedExpression */) { + prev = parent; + parent = parent.parent; + } + if (parent.kind === 191 /* CallExpression */ && parent.expression === prev) { + return parent; + } + } + } + ts.getImmediatelyInvokedFunctionExpression = getImmediatelyInvokedFunctionExpression; + /** + * Determines whether a node is a property or element access expression for `super`. + */ + function isSuperProperty(node) { + var kind = node.kind; + return (kind === 189 /* PropertyAccessExpression */ || kind === 190 /* ElementAccessExpression */) + && node.expression.kind === 98 /* SuperKeyword */; + } + ts.isSuperProperty = isSuperProperty; + /** + * Determines whether a node is a property or element access expression for `this`. + */ + function isThisProperty(node) { + var kind = node.kind; + return (kind === 189 /* PropertyAccessExpression */ || kind === 190 /* ElementAccessExpression */) + && node.expression.kind === 100 /* ThisKeyword */; + } + ts.isThisProperty = isThisProperty; + function getEntityNameFromTypeNode(node) { + switch (node.kind) { + case 164 /* TypeReference */: + return node.typeName; + case 211 /* ExpressionWithTypeArguments */: + return isEntityNameExpression(node.expression) + ? node.expression + : undefined; + case 72 /* Identifier */: + case 148 /* QualifiedName */: + return node; + } + return undefined; + } + ts.getEntityNameFromTypeNode = getEntityNameFromTypeNode; + function getInvokedExpression(node) { + switch (node.kind) { + case 193 /* TaggedTemplateExpression */: + return node.tag; + case 262 /* JsxOpeningElement */: + case 261 /* JsxSelfClosingElement */: + return node.tagName; + default: + return node.expression; + } + } + ts.getInvokedExpression = getInvokedExpression; + function nodeCanBeDecorated(node, parent, grandparent) { + switch (node.kind) { + case 240 /* ClassDeclaration */: + // classes are valid targets + return true; + case 154 /* PropertyDeclaration */: + // property declarations are valid if their parent is a class declaration. + return parent.kind === 240 /* ClassDeclaration */; + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 156 /* MethodDeclaration */: + // if this method has a body and its parent is a class declaration, this is a valid target. + return node.body !== undefined + && parent.kind === 240 /* ClassDeclaration */; + case 151 /* Parameter */: + // if the parameter's parent has a body and its grandparent is a class declaration, this is a valid target; + return parent.body !== undefined + && (parent.kind === 157 /* Constructor */ + || parent.kind === 156 /* MethodDeclaration */ + || parent.kind === 159 /* SetAccessor */) + && grandparent.kind === 240 /* ClassDeclaration */; + } + return false; + } + ts.nodeCanBeDecorated = nodeCanBeDecorated; + function nodeIsDecorated(node, parent, grandparent) { + return node.decorators !== undefined + && nodeCanBeDecorated(node, parent, grandparent); // TODO: GH#18217 + } + ts.nodeIsDecorated = nodeIsDecorated; + function nodeOrChildIsDecorated(node, parent, grandparent) { + return nodeIsDecorated(node, parent, grandparent) || childIsDecorated(node, parent); // TODO: GH#18217 + } + ts.nodeOrChildIsDecorated = nodeOrChildIsDecorated; + function childIsDecorated(node, parent) { + switch (node.kind) { + case 240 /* ClassDeclaration */: + return ts.some(node.members, function (m) { return nodeOrChildIsDecorated(m, node, parent); }); // TODO: GH#18217 + case 156 /* MethodDeclaration */: + case 159 /* SetAccessor */: + return ts.some(node.parameters, function (p) { return nodeIsDecorated(p, node, parent); }); // TODO: GH#18217 + default: + return false; + } + } + ts.childIsDecorated = childIsDecorated; + function isJSXTagName(node) { + var parent = node.parent; + if (parent.kind === 262 /* JsxOpeningElement */ || + parent.kind === 261 /* JsxSelfClosingElement */ || + parent.kind === 263 /* JsxClosingElement */) { + return parent.tagName === node; + } + return false; + } + ts.isJSXTagName = isJSXTagName; + function isExpressionNode(node) { + switch (node.kind) { + case 98 /* SuperKeyword */: + case 96 /* NullKeyword */: + case 102 /* TrueKeyword */: + case 87 /* FalseKeyword */: + case 13 /* RegularExpressionLiteral */: + case 187 /* ArrayLiteralExpression */: + case 188 /* ObjectLiteralExpression */: + case 189 /* PropertyAccessExpression */: + case 190 /* ElementAccessExpression */: + case 191 /* CallExpression */: + case 192 /* NewExpression */: + case 193 /* TaggedTemplateExpression */: + case 212 /* AsExpression */: + case 194 /* TypeAssertionExpression */: + case 213 /* NonNullExpression */: + case 195 /* ParenthesizedExpression */: + case 196 /* FunctionExpression */: + case 209 /* ClassExpression */: + case 197 /* ArrowFunction */: + case 200 /* VoidExpression */: + case 198 /* DeleteExpression */: + case 199 /* TypeOfExpression */: + case 202 /* PrefixUnaryExpression */: + case 203 /* PostfixUnaryExpression */: + case 204 /* BinaryExpression */: + case 205 /* ConditionalExpression */: + case 208 /* SpreadElement */: + case 206 /* TemplateExpression */: + case 14 /* NoSubstitutionTemplateLiteral */: + case 210 /* OmittedExpression */: + case 260 /* JsxElement */: + case 261 /* JsxSelfClosingElement */: + case 264 /* JsxFragment */: + case 207 /* YieldExpression */: + case 201 /* AwaitExpression */: + case 214 /* MetaProperty */: + return true; + case 148 /* QualifiedName */: + while (node.parent.kind === 148 /* QualifiedName */) { + node = node.parent; + } + return node.parent.kind === 167 /* TypeQuery */ || isJSXTagName(node); + case 72 /* Identifier */: + if (node.parent.kind === 167 /* TypeQuery */ || isJSXTagName(node)) { + return true; + } + // falls through + case 8 /* NumericLiteral */: + case 9 /* BigIntLiteral */: + case 10 /* StringLiteral */: + case 100 /* ThisKeyword */: + return isInExpressionContext(node); + default: + return false; + } + } + ts.isExpressionNode = isExpressionNode; + function isInExpressionContext(node) { + var parent = node.parent; + switch (parent.kind) { + case 237 /* VariableDeclaration */: + case 151 /* Parameter */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 278 /* EnumMember */: + case 275 /* PropertyAssignment */: + case 186 /* BindingElement */: + return parent.initializer === node; + case 221 /* ExpressionStatement */: + case 222 /* IfStatement */: + case 223 /* DoStatement */: + case 224 /* WhileStatement */: + case 230 /* ReturnStatement */: + case 231 /* WithStatement */: + case 232 /* SwitchStatement */: + case 271 /* CaseClause */: + case 234 /* ThrowStatement */: + return parent.expression === node; + case 225 /* ForStatement */: + var forStatement = parent; + return (forStatement.initializer === node && forStatement.initializer.kind !== 238 /* VariableDeclarationList */) || + forStatement.condition === node || + forStatement.incrementor === node; + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + var forInStatement = parent; + return (forInStatement.initializer === node && forInStatement.initializer.kind !== 238 /* VariableDeclarationList */) || + forInStatement.expression === node; + case 194 /* TypeAssertionExpression */: + case 212 /* AsExpression */: + return node === parent.expression; + case 216 /* TemplateSpan */: + return node === parent.expression; + case 149 /* ComputedPropertyName */: + return node === parent.expression; + case 152 /* Decorator */: + case 270 /* JsxExpression */: + case 269 /* JsxSpreadAttribute */: + case 277 /* SpreadAssignment */: + return true; + case 211 /* ExpressionWithTypeArguments */: + return parent.expression === node && isExpressionWithTypeArgumentsInClassExtendsClause(parent); + case 276 /* ShorthandPropertyAssignment */: + return parent.objectAssignmentInitializer === node; + default: + return isExpressionNode(parent); + } + } + ts.isInExpressionContext = isInExpressionContext; + function isExternalModuleImportEqualsDeclaration(node) { + return node.kind === 248 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 259 /* ExternalModuleReference */; + } + ts.isExternalModuleImportEqualsDeclaration = isExternalModuleImportEqualsDeclaration; + function getExternalModuleImportEqualsDeclarationExpression(node) { + ts.Debug.assert(isExternalModuleImportEqualsDeclaration(node)); + return node.moduleReference.expression; + } + ts.getExternalModuleImportEqualsDeclarationExpression = getExternalModuleImportEqualsDeclarationExpression; + function isInternalModuleImportEqualsDeclaration(node) { + return node.kind === 248 /* ImportEqualsDeclaration */ && node.moduleReference.kind !== 259 /* ExternalModuleReference */; + } + ts.isInternalModuleImportEqualsDeclaration = isInternalModuleImportEqualsDeclaration; + function isSourceFileJS(file) { + return isInJSFile(file); + } + ts.isSourceFileJS = isSourceFileJS; + function isSourceFileNotJS(file) { + return !isInJSFile(file); + } + ts.isSourceFileNotJS = isSourceFileNotJS; + function isInJSFile(node) { + return !!node && !!(node.flags & 65536 /* JavaScriptFile */); + } + ts.isInJSFile = isInJSFile; + function isInJsonFile(node) { + return !!node && !!(node.flags & 16777216 /* JsonFile */); + } + ts.isInJsonFile = isInJsonFile; + function isInJSDoc(node) { + return !!node && !!(node.flags & 2097152 /* JSDoc */); + } + ts.isInJSDoc = isInJSDoc; + function isJSDocIndexSignature(node) { + return ts.isTypeReferenceNode(node) && + ts.isIdentifier(node.typeName) && + node.typeName.escapedText === "Object" && + node.typeArguments && node.typeArguments.length === 2 && + (node.typeArguments[0].kind === 138 /* StringKeyword */ || node.typeArguments[0].kind === 135 /* NumberKeyword */); + } + ts.isJSDocIndexSignature = isJSDocIndexSignature; + function isRequireCall(callExpression, checkArgumentIsStringLiteralLike) { + if (callExpression.kind !== 191 /* CallExpression */) { + return false; + } + var _a = callExpression, expression = _a.expression, args = _a.arguments; + if (expression.kind !== 72 /* Identifier */ || expression.escapedText !== "require") { + return false; + } + if (args.length !== 1) { + return false; + } + var arg = args[0]; + return !checkArgumentIsStringLiteralLike || ts.isStringLiteralLike(arg); + } + ts.isRequireCall = isRequireCall; + function isSingleOrDoubleQuote(charCode) { + return charCode === 39 /* singleQuote */ || charCode === 34 /* doubleQuote */; + } + ts.isSingleOrDoubleQuote = isSingleOrDoubleQuote; + function isStringDoubleQuoted(str, sourceFile) { + return getSourceTextOfNodeFromSourceFile(sourceFile, str).charCodeAt(0) === 34 /* doubleQuote */; + } + ts.isStringDoubleQuoted = isStringDoubleQuoted; + function getDeclarationOfExpando(node) { + if (!node.parent) { + return undefined; + } + var name; + var decl; + if (ts.isVariableDeclaration(node.parent) && node.parent.initializer === node) { + if (!isInJSFile(node) && !isVarConst(node.parent)) { + return undefined; + } + name = node.parent.name; + decl = node.parent; + } + else if (ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 59 /* EqualsToken */ && node.parent.right === node) { + name = node.parent.left; + decl = name; + } + else if (ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 55 /* BarBarToken */) { + if (ts.isVariableDeclaration(node.parent.parent) && node.parent.parent.initializer === node.parent) { + name = node.parent.parent.name; + decl = node.parent.parent; + } + else if (ts.isBinaryExpression(node.parent.parent) && node.parent.parent.operatorToken.kind === 59 /* EqualsToken */ && node.parent.parent.right === node.parent) { + name = node.parent.parent.left; + decl = name; + } + if (!name || !isEntityNameExpression(name) || !isSameEntityName(name, node.parent.left)) { + return undefined; + } + } + if (!name || !getExpandoInitializer(node, isPrototypeAccess(name))) { + return undefined; + } + return decl; + } + ts.getDeclarationOfExpando = getDeclarationOfExpando; + function isAssignmentDeclaration(decl) { + return ts.isBinaryExpression(decl) || ts.isPropertyAccessExpression(decl) || ts.isIdentifier(decl) || ts.isCallExpression(decl); + } + ts.isAssignmentDeclaration = isAssignmentDeclaration; + /** Get the initializer, taking into account defaulted Javascript initializers */ + function getEffectiveInitializer(node) { + if (isInJSFile(node) && node.initializer && + ts.isBinaryExpression(node.initializer) && node.initializer.operatorToken.kind === 55 /* BarBarToken */ && + node.name && isEntityNameExpression(node.name) && isSameEntityName(node.name, node.initializer.left)) { + return node.initializer.right; + } + return node.initializer; + } + ts.getEffectiveInitializer = getEffectiveInitializer; + /** Get the declaration initializer when it is container-like (See getExpandoInitializer). */ + function getDeclaredExpandoInitializer(node) { + var init = getEffectiveInitializer(node); + return init && getExpandoInitializer(init, isPrototypeAccess(node.name)); + } + ts.getDeclaredExpandoInitializer = getDeclaredExpandoInitializer; + function hasExpandoValueProperty(node, isPrototypeAssignment) { + return ts.forEach(node.properties, function (p) { return ts.isPropertyAssignment(p) && ts.isIdentifier(p.name) && p.name.escapedText === "value" && p.initializer && getExpandoInitializer(p.initializer, isPrototypeAssignment); }); + } + /** + * Get the assignment 'initializer' -- the righthand side-- when the initializer is container-like (See getExpandoInitializer). + * We treat the right hand side of assignments with container-like initalizers as declarations. + */ + function getAssignedExpandoInitializer(node) { + if (node && node.parent && ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 59 /* EqualsToken */) { + var isPrototypeAssignment = isPrototypeAccess(node.parent.left); + return getExpandoInitializer(node.parent.right, isPrototypeAssignment) || + getDefaultedExpandoInitializer(node.parent.left, node.parent.right, isPrototypeAssignment); + } + if (node && ts.isCallExpression(node) && isBindableObjectDefinePropertyCall(node)) { + var result = hasExpandoValueProperty(node.arguments[2], node.arguments[1].text === "prototype"); + if (result) { + return result; + } + } + } + ts.getAssignedExpandoInitializer = getAssignedExpandoInitializer; + /** + * Recognized expando initializers are: + * 1. (function() {})() -- IIFEs + * 2. function() { } -- Function expressions + * 3. class { } -- Class expressions + * 4. {} -- Empty object literals + * 5. { ... } -- Non-empty object literals, when used to initialize a prototype, like `C.prototype = { m() { } }` + * + * This function returns the provided initializer, or undefined if it is not valid. + */ + function getExpandoInitializer(initializer, isPrototypeAssignment) { + if (ts.isCallExpression(initializer)) { + var e = skipParentheses(initializer.expression); + return e.kind === 196 /* FunctionExpression */ || e.kind === 197 /* ArrowFunction */ ? initializer : undefined; + } + if (initializer.kind === 196 /* FunctionExpression */ || + initializer.kind === 209 /* ClassExpression */ || + initializer.kind === 197 /* ArrowFunction */) { + return initializer; + } + if (ts.isObjectLiteralExpression(initializer) && (initializer.properties.length === 0 || isPrototypeAssignment)) { + return initializer; + } + } + ts.getExpandoInitializer = getExpandoInitializer; + /** + * A defaulted expando initializer matches the pattern + * `Lhs = Lhs || ExpandoInitializer` + * or `var Lhs = Lhs || ExpandoInitializer` + * + * The second Lhs is required to be the same as the first except that it may be prefixed with + * 'window.', 'global.' or 'self.' The second Lhs is otherwise ignored by the binder and checker. + */ + function getDefaultedExpandoInitializer(name, initializer, isPrototypeAssignment) { + var e = ts.isBinaryExpression(initializer) && initializer.operatorToken.kind === 55 /* BarBarToken */ && getExpandoInitializer(initializer.right, isPrototypeAssignment); + if (e && isSameEntityName(name, initializer.left)) { + return e; + } + } + function isDefaultedExpandoInitializer(node) { + var name = ts.isVariableDeclaration(node.parent) ? node.parent.name : + ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 59 /* EqualsToken */ ? node.parent.left : + undefined; + return name && getExpandoInitializer(node.right, isPrototypeAccess(name)) && isEntityNameExpression(name) && isSameEntityName(name, node.left); + } + ts.isDefaultedExpandoInitializer = isDefaultedExpandoInitializer; + /** Given an expando initializer, return its declaration name, or the left-hand side of the assignment if it's part of an assignment declaration. */ + function getNameOfExpando(node) { + if (ts.isBinaryExpression(node.parent)) { + var parent = (node.parent.operatorToken.kind === 55 /* BarBarToken */ && ts.isBinaryExpression(node.parent.parent)) ? node.parent.parent : node.parent; + if (parent.operatorToken.kind === 59 /* EqualsToken */ && ts.isIdentifier(parent.left)) { + return parent.left; + } + } + else if (ts.isVariableDeclaration(node.parent)) { + return node.parent.name; + } + } + ts.getNameOfExpando = getNameOfExpando; + /** + * Is the 'declared' name the same as the one in the initializer? + * @return true for identical entity names, as well as ones where the initializer is prefixed with + * 'window', 'self' or 'global'. For example: + * + * var my = my || {} + * var min = window.min || {} + * my.app = self.my.app || class { } + */ + function isSameEntityName(name, initializer) { + if (ts.isIdentifier(name) && ts.isIdentifier(initializer)) { + return name.escapedText === initializer.escapedText; + } + if (ts.isIdentifier(name) && ts.isPropertyAccessExpression(initializer)) { + return (initializer.expression.kind === 100 /* ThisKeyword */ || + ts.isIdentifier(initializer.expression) && + (initializer.expression.escapedText === "window" || + initializer.expression.escapedText === "self" || + initializer.expression.escapedText === "global")) && + isSameEntityName(name, initializer.name); + } + if (ts.isPropertyAccessExpression(name) && ts.isPropertyAccessExpression(initializer)) { + return name.name.escapedText === initializer.name.escapedText && isSameEntityName(name.expression, initializer.expression); + } + return false; + } + function getRightMostAssignedExpression(node) { + while (isAssignmentExpression(node, /*excludeCompoundAssignments*/ true)) { + node = node.right; + } + return node; + } + ts.getRightMostAssignedExpression = getRightMostAssignedExpression; + function isExportsIdentifier(node) { + return ts.isIdentifier(node) && node.escapedText === "exports"; + } + ts.isExportsIdentifier = isExportsIdentifier; + function isModuleExportsPropertyAccessExpression(node) { + return ts.isPropertyAccessExpression(node) && ts.isIdentifier(node.expression) && node.expression.escapedText === "module" && node.name.escapedText === "exports"; + } + ts.isModuleExportsPropertyAccessExpression = isModuleExportsPropertyAccessExpression; + /// Given a BinaryExpression, returns SpecialPropertyAssignmentKind for the various kinds of property + /// assignments we treat as special in the binder + function getAssignmentDeclarationKind(expr) { + var special = getAssignmentDeclarationKindWorker(expr); + return special === 5 /* Property */ || isInJSFile(expr) ? special : 0 /* None */; + } + ts.getAssignmentDeclarationKind = getAssignmentDeclarationKind; + function isBindableObjectDefinePropertyCall(expr) { + return ts.length(expr.arguments) === 3 && + ts.isPropertyAccessExpression(expr.expression) && + ts.isIdentifier(expr.expression.expression) && + ts.idText(expr.expression.expression) === "Object" && + ts.idText(expr.expression.name) === "defineProperty" && + isStringOrNumericLiteralLike(expr.arguments[1]) && + isEntityNameExpression(expr.arguments[0]); + } + ts.isBindableObjectDefinePropertyCall = isBindableObjectDefinePropertyCall; + function getAssignmentDeclarationKindWorker(expr) { + if (ts.isCallExpression(expr)) { + if (!isBindableObjectDefinePropertyCall(expr)) { + return 0 /* None */; + } + var entityName = expr.arguments[0]; + if (isExportsIdentifier(entityName) || isModuleExportsPropertyAccessExpression(entityName)) { + return 8 /* ObjectDefinePropertyExports */; + } + if (ts.isPropertyAccessExpression(entityName) && entityName.name.escapedText === "prototype" && isEntityNameExpression(entityName.expression)) { + return 9 /* ObjectDefinePrototypeProperty */; + } + return 7 /* ObjectDefinePropertyValue */; + } + if (expr.operatorToken.kind !== 59 /* EqualsToken */ || + !ts.isPropertyAccessExpression(expr.left)) { + return 0 /* None */; + } + var lhs = expr.left; + if (isEntityNameExpression(lhs.expression) && lhs.name.escapedText === "prototype" && ts.isObjectLiteralExpression(getInitializerOfBinaryExpression(expr))) { + // F.prototype = { ... } + return 6 /* Prototype */; + } + return getAssignmentDeclarationPropertyAccessKind(lhs); + } + function getAssignmentDeclarationPropertyAccessKind(lhs) { + if (lhs.expression.kind === 100 /* ThisKeyword */) { + return 4 /* ThisProperty */; + } + else if (isModuleExportsPropertyAccessExpression(lhs)) { + // module.exports = expr + return 2 /* ModuleExports */; + } + else if (isEntityNameExpression(lhs.expression)) { + if (isPrototypeAccess(lhs.expression)) { + // F.G....prototype.x = expr + return 3 /* PrototypeProperty */; + } + var nextToLast = lhs; + while (ts.isPropertyAccessExpression(nextToLast.expression)) { + nextToLast = nextToLast.expression; + } + ts.Debug.assert(ts.isIdentifier(nextToLast.expression)); + var id = nextToLast.expression; + if (id.escapedText === "exports" || + id.escapedText === "module" && nextToLast.name.escapedText === "exports") { + // exports.name = expr OR module.exports.name = expr + return 1 /* ExportsProperty */; + } + // F.G...x = expr + return 5 /* Property */; + } + return 0 /* None */; + } + ts.getAssignmentDeclarationPropertyAccessKind = getAssignmentDeclarationPropertyAccessKind; + function getInitializerOfBinaryExpression(expr) { + while (ts.isBinaryExpression(expr.right)) { + expr = expr.right; + } + return expr.right; + } + ts.getInitializerOfBinaryExpression = getInitializerOfBinaryExpression; + function isPrototypePropertyAssignment(node) { + return ts.isBinaryExpression(node) && getAssignmentDeclarationKind(node) === 3 /* PrototypeProperty */; + } + ts.isPrototypePropertyAssignment = isPrototypePropertyAssignment; + function isSpecialPropertyDeclaration(expr) { + return isInJSFile(expr) && + expr.parent && expr.parent.kind === 221 /* ExpressionStatement */ && + !!ts.getJSDocTypeTag(expr.parent); + } + ts.isSpecialPropertyDeclaration = isSpecialPropertyDeclaration; + function isFunctionSymbol(symbol) { + if (!symbol || !symbol.valueDeclaration) { + return false; + } + var decl = symbol.valueDeclaration; + return decl.kind === 239 /* FunctionDeclaration */ || ts.isVariableDeclaration(decl) && decl.initializer && ts.isFunctionLike(decl.initializer); + } + ts.isFunctionSymbol = isFunctionSymbol; + function importFromModuleSpecifier(node) { + return tryGetImportFromModuleSpecifier(node) || ts.Debug.fail(ts.Debug.showSyntaxKind(node.parent)); + } + ts.importFromModuleSpecifier = importFromModuleSpecifier; + function tryGetImportFromModuleSpecifier(node) { + switch (node.parent.kind) { + case 249 /* ImportDeclaration */: + case 255 /* ExportDeclaration */: + return node.parent; + case 259 /* ExternalModuleReference */: + return node.parent.parent; + case 191 /* CallExpression */: + return isImportCall(node.parent) || isRequireCall(node.parent, /*checkArg*/ false) ? node.parent : undefined; + case 182 /* LiteralType */: + ts.Debug.assert(ts.isStringLiteral(node)); + return ts.tryCast(node.parent.parent, ts.isImportTypeNode); + default: + return undefined; + } + } + ts.tryGetImportFromModuleSpecifier = tryGetImportFromModuleSpecifier; + function getExternalModuleName(node) { + switch (node.kind) { + case 249 /* ImportDeclaration */: + case 255 /* ExportDeclaration */: + return node.moduleSpecifier; + case 248 /* ImportEqualsDeclaration */: + return node.moduleReference.kind === 259 /* ExternalModuleReference */ ? node.moduleReference.expression : undefined; + case 183 /* ImportType */: + return isLiteralImportTypeNode(node) ? node.argument.literal : undefined; + default: + return ts.Debug.assertNever(node); + } + } + ts.getExternalModuleName = getExternalModuleName; + function getNamespaceDeclarationNode(node) { + switch (node.kind) { + case 249 /* ImportDeclaration */: + return node.importClause && ts.tryCast(node.importClause.namedBindings, ts.isNamespaceImport); + case 248 /* ImportEqualsDeclaration */: + return node; + case 255 /* ExportDeclaration */: + return undefined; + default: + return ts.Debug.assertNever(node); + } + } + ts.getNamespaceDeclarationNode = getNamespaceDeclarationNode; + function isDefaultImport(node) { + return node.kind === 249 /* ImportDeclaration */ && !!node.importClause && !!node.importClause.name; + } + ts.isDefaultImport = isDefaultImport; + function hasQuestionToken(node) { + if (node) { + switch (node.kind) { + case 151 /* Parameter */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 276 /* ShorthandPropertyAssignment */: + case 275 /* PropertyAssignment */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + return node.questionToken !== undefined; + } + } + return false; + } + ts.hasQuestionToken = hasQuestionToken; + function isJSDocConstructSignature(node) { + var param = ts.isJSDocFunctionType(node) ? ts.firstOrUndefined(node.parameters) : undefined; + var name = ts.tryCast(param && param.name, ts.isIdentifier); + return !!name && name.escapedText === "new"; + } + ts.isJSDocConstructSignature = isJSDocConstructSignature; + function isJSDocTypeAlias(node) { + return node.kind === 304 /* JSDocTypedefTag */ || node.kind === 297 /* JSDocCallbackTag */; + } + ts.isJSDocTypeAlias = isJSDocTypeAlias; + function isTypeAlias(node) { + return isJSDocTypeAlias(node) || ts.isTypeAliasDeclaration(node); + } + ts.isTypeAlias = isTypeAlias; + function getSourceOfAssignment(node) { + return ts.isExpressionStatement(node) && + node.expression && ts.isBinaryExpression(node.expression) && + node.expression.operatorToken.kind === 59 /* EqualsToken */ + ? node.expression.right + : undefined; + } + function getSourceOfDefaultedAssignment(node) { + return ts.isExpressionStatement(node) && + ts.isBinaryExpression(node.expression) && + getAssignmentDeclarationKind(node.expression) !== 0 /* None */ && + ts.isBinaryExpression(node.expression.right) && + node.expression.right.operatorToken.kind === 55 /* BarBarToken */ + ? node.expression.right.right + : undefined; + } + function getSingleInitializerOfVariableStatementOrPropertyDeclaration(node) { + switch (node.kind) { + case 219 /* VariableStatement */: + var v = getSingleVariableOfVariableStatement(node); + return v && v.initializer; + case 154 /* PropertyDeclaration */: + return node.initializer; + case 275 /* PropertyAssignment */: + return node.initializer; + } + } + function getSingleVariableOfVariableStatement(node) { + return ts.isVariableStatement(node) ? ts.firstOrUndefined(node.declarationList.declarations) : undefined; + } + function getNestedModuleDeclaration(node) { + return ts.isModuleDeclaration(node) && + node.body && + node.body.kind === 244 /* ModuleDeclaration */ + ? node.body + : undefined; + } + function getJSDocCommentsAndTags(hostNode) { + var result; + // Pull parameter comments from declaring function as well + if (isVariableLike(hostNode) && ts.hasInitializer(hostNode) && ts.hasJSDocNodes(hostNode.initializer)) { + result = ts.addRange(result, hostNode.initializer.jsDoc); + } + var node = hostNode; + while (node && node.parent) { + if (ts.hasJSDocNodes(node)) { + result = ts.addRange(result, node.jsDoc); + } + if (node.kind === 151 /* Parameter */) { + result = ts.addRange(result, ts.getJSDocParameterTags(node)); + break; + } + if (node.kind === 150 /* TypeParameter */) { + result = ts.addRange(result, ts.getJSDocTypeParameterTags(node)); + break; + } + node = getNextJSDocCommentLocation(node); + } + return result || ts.emptyArray; + } + ts.getJSDocCommentsAndTags = getJSDocCommentsAndTags; + function getNextJSDocCommentLocation(node) { + var parent = node.parent; + if (parent.kind === 275 /* PropertyAssignment */ || + parent.kind === 154 /* PropertyDeclaration */ || + parent.kind === 221 /* ExpressionStatement */ && node.kind === 189 /* PropertyAccessExpression */ || + getNestedModuleDeclaration(parent) || + ts.isBinaryExpression(node) && node.operatorToken.kind === 59 /* EqualsToken */) { + return parent; + } + // Try to recognize this pattern when node is initializer of variable declaration and JSDoc comments are on containing variable statement. + // /** + // * @param {number} name + // * @returns {number} + // */ + // var x = function(name) { return name.length; } + else if (parent.parent && + (getSingleVariableOfVariableStatement(parent.parent) === node || + ts.isBinaryExpression(parent) && parent.operatorToken.kind === 59 /* EqualsToken */)) { + return parent.parent; + } + else if (parent.parent && parent.parent.parent && + (getSingleVariableOfVariableStatement(parent.parent.parent) || + getSingleInitializerOfVariableStatementOrPropertyDeclaration(parent.parent.parent) === node || + getSourceOfDefaultedAssignment(parent.parent.parent))) { + return parent.parent.parent; + } + } + /** Does the opposite of `getJSDocParameterTags`: given a JSDoc parameter, finds the parameter corresponding to it. */ + function getParameterSymbolFromJSDoc(node) { + if (node.symbol) { + return node.symbol; + } + if (!ts.isIdentifier(node.name)) { + return undefined; + } + var name = node.name.escapedText; + var decl = getHostSignatureFromJSDoc(node); + if (!decl) { + return undefined; + } + var parameter = ts.find(decl.parameters, function (p) { return p.name.kind === 72 /* Identifier */ && p.name.escapedText === name; }); + return parameter && parameter.symbol; + } + ts.getParameterSymbolFromJSDoc = getParameterSymbolFromJSDoc; + function getHostSignatureFromJSDoc(node) { + return getHostSignatureFromJSDocHost(getJSDocHost(node)); + } + ts.getHostSignatureFromJSDoc = getHostSignatureFromJSDoc; + function getHostSignatureFromJSDocHost(host) { + var decl = getSourceOfDefaultedAssignment(host) || + getSourceOfAssignment(host) || + getSingleInitializerOfVariableStatementOrPropertyDeclaration(host) || + getSingleVariableOfVariableStatement(host) || + getNestedModuleDeclaration(host) || + host; + return decl && ts.isFunctionLike(decl) ? decl : undefined; + } + ts.getHostSignatureFromJSDocHost = getHostSignatureFromJSDocHost; + function getJSDocHost(node) { + return ts.Debug.assertDefined(findAncestor(node.parent, ts.isJSDoc)).parent; + } + ts.getJSDocHost = getJSDocHost; + function getTypeParameterFromJsDoc(node) { + var name = node.name.escapedText; + var typeParameters = node.parent.parent.parent.typeParameters; + return ts.find(typeParameters, function (p) { return p.name.escapedText === name; }); + } + ts.getTypeParameterFromJsDoc = getTypeParameterFromJsDoc; + function hasRestParameter(s) { + var last = ts.lastOrUndefined(s.parameters); + return !!last && isRestParameter(last); + } + ts.hasRestParameter = hasRestParameter; + function isRestParameter(node) { + var type = ts.isJSDocParameterTag(node) ? (node.typeExpression && node.typeExpression.type) : node.type; + return node.dotDotDotToken !== undefined || !!type && type.kind === 290 /* JSDocVariadicType */; + } + ts.isRestParameter = isRestParameter; + var AssignmentKind; + (function (AssignmentKind) { + AssignmentKind[AssignmentKind["None"] = 0] = "None"; + AssignmentKind[AssignmentKind["Definite"] = 1] = "Definite"; + AssignmentKind[AssignmentKind["Compound"] = 2] = "Compound"; + })(AssignmentKind = ts.AssignmentKind || (ts.AssignmentKind = {})); + function getAssignmentTargetKind(node) { + var parent = node.parent; + while (true) { + switch (parent.kind) { + case 204 /* BinaryExpression */: + var binaryOperator = parent.operatorToken.kind; + return isAssignmentOperator(binaryOperator) && parent.left === node ? + binaryOperator === 59 /* EqualsToken */ ? 1 /* Definite */ : 2 /* Compound */ : + 0 /* None */; + case 202 /* PrefixUnaryExpression */: + case 203 /* PostfixUnaryExpression */: + var unaryOperator = parent.operator; + return unaryOperator === 44 /* PlusPlusToken */ || unaryOperator === 45 /* MinusMinusToken */ ? 2 /* Compound */ : 0 /* None */; + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + return parent.initializer === node ? 1 /* Definite */ : 0 /* None */; + case 195 /* ParenthesizedExpression */: + case 187 /* ArrayLiteralExpression */: + case 208 /* SpreadElement */: + case 213 /* NonNullExpression */: + node = parent; + break; + case 276 /* ShorthandPropertyAssignment */: + if (parent.name !== node) { + return 0 /* None */; + } + node = parent.parent; + break; + case 275 /* PropertyAssignment */: + if (parent.name === node) { + return 0 /* None */; + } + node = parent.parent; + break; + default: + return 0 /* None */; + } + parent = node.parent; + } + } + ts.getAssignmentTargetKind = getAssignmentTargetKind; + // A node is an assignment target if it is on the left hand side of an '=' token, if it is parented by a property + // assignment in an object literal that is an assignment target, or if it is parented by an array literal that is + // an assignment target. Examples include 'a = xxx', '{ p: a } = xxx', '[{ a }] = xxx'. + // (Note that `p` is not a target in the above examples, only `a`.) + function isAssignmentTarget(node) { + return getAssignmentTargetKind(node) !== 0 /* None */; + } + ts.isAssignmentTarget = isAssignmentTarget; + /** + * Indicates whether a node could contain a `var` VariableDeclarationList that contributes to + * the same `var` declaration scope as the node's parent. + */ + function isNodeWithPossibleHoistedDeclaration(node) { + switch (node.kind) { + case 218 /* Block */: + case 219 /* VariableStatement */: + case 231 /* WithStatement */: + case 222 /* IfStatement */: + case 232 /* SwitchStatement */: + case 246 /* CaseBlock */: + case 271 /* CaseClause */: + case 272 /* DefaultClause */: + case 233 /* LabeledStatement */: + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + case 223 /* DoStatement */: + case 224 /* WhileStatement */: + case 235 /* TryStatement */: + case 274 /* CatchClause */: + return true; + } + return false; + } + ts.isNodeWithPossibleHoistedDeclaration = isNodeWithPossibleHoistedDeclaration; + function isValueSignatureDeclaration(node) { + return ts.isFunctionExpression(node) || ts.isArrowFunction(node) || ts.isMethodOrAccessor(node) || ts.isFunctionDeclaration(node) || ts.isConstructorDeclaration(node); + } + ts.isValueSignatureDeclaration = isValueSignatureDeclaration; + function walkUp(node, kind) { + while (node && node.kind === kind) { + node = node.parent; + } + return node; + } + function walkUpParenthesizedTypes(node) { + return walkUp(node, 177 /* ParenthesizedType */); + } + ts.walkUpParenthesizedTypes = walkUpParenthesizedTypes; + function walkUpParenthesizedExpressions(node) { + return walkUp(node, 195 /* ParenthesizedExpression */); + } + ts.walkUpParenthesizedExpressions = walkUpParenthesizedExpressions; + function skipParentheses(node) { + while (node.kind === 195 /* ParenthesizedExpression */) { + node = node.expression; + } + return node; + } + ts.skipParentheses = skipParentheses; + function skipParenthesesUp(node) { + while (node.kind === 195 /* ParenthesizedExpression */) { + node = node.parent; + } + return node; + } + // a node is delete target iff. it is PropertyAccessExpression/ElementAccessExpression with parentheses skipped + function isDeleteTarget(node) { + if (node.kind !== 189 /* PropertyAccessExpression */ && node.kind !== 190 /* ElementAccessExpression */) { + return false; + } + node = walkUpParenthesizedExpressions(node.parent); + return node && node.kind === 198 /* DeleteExpression */; + } + ts.isDeleteTarget = isDeleteTarget; + function isNodeDescendantOf(node, ancestor) { + while (node) { + if (node === ancestor) + return true; + node = node.parent; + } + return false; + } + ts.isNodeDescendantOf = isNodeDescendantOf; + // True if `name` is the name of a declaration node + function isDeclarationName(name) { + return !ts.isSourceFile(name) && !ts.isBindingPattern(name) && ts.isDeclaration(name.parent) && name.parent.name === name; + } + ts.isDeclarationName = isDeclarationName; + // See GH#16030 + function getDeclarationFromName(name) { + var parent = name.parent; + switch (name.kind) { + case 10 /* StringLiteral */: + case 8 /* NumericLiteral */: + if (ts.isComputedPropertyName(parent)) + return parent.parent; + // falls through + case 72 /* Identifier */: + if (ts.isDeclaration(parent)) { + return parent.name === name ? parent : undefined; + } + else if (ts.isQualifiedName(parent)) { + var tag = parent.parent; + return ts.isJSDocParameterTag(tag) && tag.name === parent ? tag : undefined; + } + else { + var binExp = parent.parent; + return ts.isBinaryExpression(binExp) && + getAssignmentDeclarationKind(binExp) !== 0 /* None */ && + (binExp.left.symbol || binExp.symbol) && + ts.getNameOfDeclaration(binExp) === name + ? binExp + : undefined; + } + default: + return undefined; + } + } + ts.getDeclarationFromName = getDeclarationFromName; + function isLiteralComputedPropertyDeclarationName(node) { + return (node.kind === 10 /* StringLiteral */ || node.kind === 8 /* NumericLiteral */) && + node.parent.kind === 149 /* ComputedPropertyName */ && + ts.isDeclaration(node.parent.parent); + } + ts.isLiteralComputedPropertyDeclarationName = isLiteralComputedPropertyDeclarationName; + // Return true if the given identifier is classified as an IdentifierName + function isIdentifierName(node) { + var parent = node.parent; + switch (parent.kind) { + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 278 /* EnumMember */: + case 275 /* PropertyAssignment */: + case 189 /* PropertyAccessExpression */: + // Name in member declaration or property name in property access + return parent.name === node; + case 148 /* QualifiedName */: + // Name on right hand side of dot in a type query or type reference + if (parent.right === node) { + while (parent.kind === 148 /* QualifiedName */) { + parent = parent.parent; + } + return parent.kind === 167 /* TypeQuery */ || parent.kind === 164 /* TypeReference */; + } + return false; + case 186 /* BindingElement */: + case 253 /* ImportSpecifier */: + // Property name in binding element or import specifier + return parent.propertyName === node; + case 257 /* ExportSpecifier */: + case 267 /* JsxAttribute */: + // Any name in an export specifier or JSX Attribute + return true; + } + return false; + } + ts.isIdentifierName = isIdentifierName; + // An alias symbol is created by one of the following declarations: + // import = ... + // import from ... + // import * as from ... + // import { x as } from ... + // export { x as } from ... + // export = + // export default + // module.exports = + function isAliasSymbolDeclaration(node) { + return node.kind === 248 /* ImportEqualsDeclaration */ || + node.kind === 247 /* NamespaceExportDeclaration */ || + node.kind === 250 /* ImportClause */ && !!node.name || + node.kind === 251 /* NamespaceImport */ || + node.kind === 253 /* ImportSpecifier */ || + node.kind === 257 /* ExportSpecifier */ || + node.kind === 254 /* ExportAssignment */ && exportAssignmentIsAlias(node) || + ts.isBinaryExpression(node) && getAssignmentDeclarationKind(node) === 2 /* ModuleExports */ && exportAssignmentIsAlias(node); + } + ts.isAliasSymbolDeclaration = isAliasSymbolDeclaration; + function exportAssignmentIsAlias(node) { + var e = ts.isExportAssignment(node) ? node.expression : node.right; + return isEntityNameExpression(e) || ts.isClassExpression(e); + } + ts.exportAssignmentIsAlias = exportAssignmentIsAlias; + function getEffectiveBaseTypeNode(node) { + if (isInJSFile(node)) { + // Prefer an @augments tag because it may have type parameters. + var tag = ts.getJSDocAugmentsTag(node); + if (tag) { + return tag.class; + } + } + return getClassExtendsHeritageElement(node); + } + ts.getEffectiveBaseTypeNode = getEffectiveBaseTypeNode; + function getClassExtendsHeritageElement(node) { + var heritageClause = getHeritageClause(node.heritageClauses, 86 /* ExtendsKeyword */); + return heritageClause && heritageClause.types.length > 0 ? heritageClause.types[0] : undefined; + } + ts.getClassExtendsHeritageElement = getClassExtendsHeritageElement; + function getClassImplementsHeritageClauseElements(node) { + var heritageClause = getHeritageClause(node.heritageClauses, 109 /* ImplementsKeyword */); + return heritageClause ? heritageClause.types : undefined; + } + ts.getClassImplementsHeritageClauseElements = getClassImplementsHeritageClauseElements; + /** Returns the node in an `extends` or `implements` clause of a class or interface. */ + function getAllSuperTypeNodes(node) { + return ts.isInterfaceDeclaration(node) ? getInterfaceBaseTypeNodes(node) || ts.emptyArray + : ts.isClassLike(node) ? ts.concatenate(ts.singleElementArray(getEffectiveBaseTypeNode(node)), getClassImplementsHeritageClauseElements(node)) || ts.emptyArray + : ts.emptyArray; + } + ts.getAllSuperTypeNodes = getAllSuperTypeNodes; + function getInterfaceBaseTypeNodes(node) { + var heritageClause = getHeritageClause(node.heritageClauses, 86 /* ExtendsKeyword */); + return heritageClause ? heritageClause.types : undefined; + } + ts.getInterfaceBaseTypeNodes = getInterfaceBaseTypeNodes; + function getHeritageClause(clauses, kind) { + if (clauses) { + for (var _i = 0, clauses_1 = clauses; _i < clauses_1.length; _i++) { + var clause = clauses_1[_i]; + if (clause.token === kind) { + return clause; + } + } + } + return undefined; + } + ts.getHeritageClause = getHeritageClause; + function tryResolveScriptReference(host, sourceFile, reference) { + if (!host.getCompilerOptions().noResolve) { + var referenceFileName = ts.isRootedDiskPath(reference.fileName) ? reference.fileName : ts.combinePaths(ts.getDirectoryPath(sourceFile.fileName), reference.fileName); + return host.getSourceFile(referenceFileName); + } + } + ts.tryResolveScriptReference = tryResolveScriptReference; + function getAncestor(node, kind) { + while (node) { + if (node.kind === kind) { + return node; + } + node = node.parent; + } + return undefined; + } + ts.getAncestor = getAncestor; + function isKeyword(token) { + return 73 /* FirstKeyword */ <= token && token <= 147 /* LastKeyword */; + } + ts.isKeyword = isKeyword; + function isContextualKeyword(token) { + return 118 /* FirstContextualKeyword */ <= token && token <= 147 /* LastContextualKeyword */; + } + ts.isContextualKeyword = isContextualKeyword; + function isNonContextualKeyword(token) { + return isKeyword(token) && !isContextualKeyword(token); + } + ts.isNonContextualKeyword = isNonContextualKeyword; + function isStringANonContextualKeyword(name) { + var token = ts.stringToToken(name); + return token !== undefined && isNonContextualKeyword(token); + } + ts.isStringANonContextualKeyword = isStringANonContextualKeyword; + function isIdentifierANonContextualKeyword(_a) { + var originalKeywordKind = _a.originalKeywordKind; + return !!originalKeywordKind && !isContextualKeyword(originalKeywordKind); + } + ts.isIdentifierANonContextualKeyword = isIdentifierANonContextualKeyword; + function isTrivia(token) { + return 2 /* FirstTriviaToken */ <= token && token <= 7 /* LastTriviaToken */; + } + ts.isTrivia = isTrivia; + var FunctionFlags; + (function (FunctionFlags) { + FunctionFlags[FunctionFlags["Normal"] = 0] = "Normal"; + FunctionFlags[FunctionFlags["Generator"] = 1] = "Generator"; + FunctionFlags[FunctionFlags["Async"] = 2] = "Async"; + FunctionFlags[FunctionFlags["Invalid"] = 4] = "Invalid"; + FunctionFlags[FunctionFlags["AsyncGenerator"] = 3] = "AsyncGenerator"; + })(FunctionFlags = ts.FunctionFlags || (ts.FunctionFlags = {})); + function getFunctionFlags(node) { + if (!node) { + return 4 /* Invalid */; + } + var flags = 0 /* Normal */; + switch (node.kind) { + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 156 /* MethodDeclaration */: + if (node.asteriskToken) { + flags |= 1 /* Generator */; + } + // falls through + case 197 /* ArrowFunction */: + if (hasModifier(node, 256 /* Async */)) { + flags |= 2 /* Async */; + } + break; + } + if (!node.body) { + flags |= 4 /* Invalid */; + } + return flags; + } + ts.getFunctionFlags = getFunctionFlags; + function isAsyncFunction(node) { + switch (node.kind) { + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 156 /* MethodDeclaration */: + return node.body !== undefined + && node.asteriskToken === undefined + && hasModifier(node, 256 /* Async */); + } + return false; + } + ts.isAsyncFunction = isAsyncFunction; + function isStringOrNumericLiteralLike(node) { + return ts.isStringLiteralLike(node) || ts.isNumericLiteral(node); + } + ts.isStringOrNumericLiteralLike = isStringOrNumericLiteralLike; + /** + * A declaration has a dynamic name if both of the following are true: + * 1. The declaration has a computed property name + * 2. The computed name is *not* expressed as Symbol., where name + * is a property of the Symbol constructor that denotes a built in + * Symbol. + */ + function hasDynamicName(declaration) { + var name = ts.getNameOfDeclaration(declaration); + return !!name && isDynamicName(name); + } + ts.hasDynamicName = hasDynamicName; + function isDynamicName(name) { + return name.kind === 149 /* ComputedPropertyName */ && + !isStringOrNumericLiteralLike(name.expression) && + !isWellKnownSymbolSyntactically(name.expression); + } + ts.isDynamicName = isDynamicName; + /** + * Checks if the expression is of the form: + * Symbol.name + * where Symbol is literally the word "Symbol", and name is any identifierName + */ + function isWellKnownSymbolSyntactically(node) { + return ts.isPropertyAccessExpression(node) && isESSymbolIdentifier(node.expression); + } + ts.isWellKnownSymbolSyntactically = isWellKnownSymbolSyntactically; + function getPropertyNameForPropertyNameNode(name) { + switch (name.kind) { + case 72 /* Identifier */: + return name.escapedText; + case 10 /* StringLiteral */: + case 8 /* NumericLiteral */: + return ts.escapeLeadingUnderscores(name.text); + case 149 /* ComputedPropertyName */: + var nameExpression = name.expression; + if (isWellKnownSymbolSyntactically(nameExpression)) { + return getPropertyNameForKnownSymbolName(ts.idText(nameExpression.name)); + } + else if (isStringOrNumericLiteralLike(nameExpression)) { + return ts.escapeLeadingUnderscores(nameExpression.text); + } + return undefined; + default: + return ts.Debug.assertNever(name); + } + } + ts.getPropertyNameForPropertyNameNode = getPropertyNameForPropertyNameNode; + function isPropertyNameLiteral(node) { + switch (node.kind) { + case 72 /* Identifier */: + case 10 /* StringLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: + case 8 /* NumericLiteral */: + return true; + default: + return false; + } + } + ts.isPropertyNameLiteral = isPropertyNameLiteral; + function getTextOfIdentifierOrLiteral(node) { + return node.kind === 72 /* Identifier */ ? ts.idText(node) : node.text; + } + ts.getTextOfIdentifierOrLiteral = getTextOfIdentifierOrLiteral; + function getEscapedTextOfIdentifierOrLiteral(node) { + return node.kind === 72 /* Identifier */ ? node.escapedText : ts.escapeLeadingUnderscores(node.text); + } + ts.getEscapedTextOfIdentifierOrLiteral = getEscapedTextOfIdentifierOrLiteral; + function getPropertyNameForKnownSymbolName(symbolName) { + return "__@" + symbolName; + } + ts.getPropertyNameForKnownSymbolName = getPropertyNameForKnownSymbolName; + function isKnownSymbol(symbol) { + return ts.startsWith(symbol.escapedName, "__@"); + } + ts.isKnownSymbol = isKnownSymbol; + /** + * Includes the word "Symbol" with unicode escapes + */ + function isESSymbolIdentifier(node) { + return node.kind === 72 /* Identifier */ && node.escapedText === "Symbol"; + } + ts.isESSymbolIdentifier = isESSymbolIdentifier; + function isPushOrUnshiftIdentifier(node) { + return node.escapedText === "push" || node.escapedText === "unshift"; + } + ts.isPushOrUnshiftIdentifier = isPushOrUnshiftIdentifier; + function isParameterDeclaration(node) { + var root = getRootDeclaration(node); + return root.kind === 151 /* Parameter */; + } + ts.isParameterDeclaration = isParameterDeclaration; + function getRootDeclaration(node) { + while (node.kind === 186 /* BindingElement */) { + node = node.parent.parent; + } + return node; + } + ts.getRootDeclaration = getRootDeclaration; + function nodeStartsNewLexicalEnvironment(node) { + var kind = node.kind; + return kind === 157 /* Constructor */ + || kind === 196 /* FunctionExpression */ + || kind === 239 /* FunctionDeclaration */ + || kind === 197 /* ArrowFunction */ + || kind === 156 /* MethodDeclaration */ + || kind === 158 /* GetAccessor */ + || kind === 159 /* SetAccessor */ + || kind === 244 /* ModuleDeclaration */ + || kind === 279 /* SourceFile */; + } + ts.nodeStartsNewLexicalEnvironment = nodeStartsNewLexicalEnvironment; + function nodeIsSynthesized(range) { + return ts.positionIsSynthesized(range.pos) + || ts.positionIsSynthesized(range.end); + } + ts.nodeIsSynthesized = nodeIsSynthesized; + function getOriginalSourceFile(sourceFile) { + return ts.getParseTreeNode(sourceFile, ts.isSourceFile) || sourceFile; + } + ts.getOriginalSourceFile = getOriginalSourceFile; + var Associativity; + (function (Associativity) { + Associativity[Associativity["Left"] = 0] = "Left"; + Associativity[Associativity["Right"] = 1] = "Right"; + })(Associativity = ts.Associativity || (ts.Associativity = {})); + function getExpressionAssociativity(expression) { + var operator = getOperator(expression); + var hasArguments = expression.kind === 192 /* NewExpression */ && expression.arguments !== undefined; + return getOperatorAssociativity(expression.kind, operator, hasArguments); + } + ts.getExpressionAssociativity = getExpressionAssociativity; + function getOperatorAssociativity(kind, operator, hasArguments) { + switch (kind) { + case 192 /* NewExpression */: + return hasArguments ? 0 /* Left */ : 1 /* Right */; + case 202 /* PrefixUnaryExpression */: + case 199 /* TypeOfExpression */: + case 200 /* VoidExpression */: + case 198 /* DeleteExpression */: + case 201 /* AwaitExpression */: + case 205 /* ConditionalExpression */: + case 207 /* YieldExpression */: + return 1 /* Right */; + case 204 /* BinaryExpression */: + switch (operator) { + case 41 /* AsteriskAsteriskToken */: + case 59 /* EqualsToken */: + case 60 /* PlusEqualsToken */: + case 61 /* MinusEqualsToken */: + case 63 /* AsteriskAsteriskEqualsToken */: + case 62 /* AsteriskEqualsToken */: + case 64 /* SlashEqualsToken */: + case 65 /* PercentEqualsToken */: + case 66 /* LessThanLessThanEqualsToken */: + case 67 /* GreaterThanGreaterThanEqualsToken */: + case 68 /* GreaterThanGreaterThanGreaterThanEqualsToken */: + case 69 /* AmpersandEqualsToken */: + case 71 /* CaretEqualsToken */: + case 70 /* BarEqualsToken */: + return 1 /* Right */; + } + } + return 0 /* Left */; + } + ts.getOperatorAssociativity = getOperatorAssociativity; + function getExpressionPrecedence(expression) { + var operator = getOperator(expression); + var hasArguments = expression.kind === 192 /* NewExpression */ && expression.arguments !== undefined; + return getOperatorPrecedence(expression.kind, operator, hasArguments); + } + ts.getExpressionPrecedence = getExpressionPrecedence; + function getOperator(expression) { + if (expression.kind === 204 /* BinaryExpression */) { + return expression.operatorToken.kind; + } + else if (expression.kind === 202 /* PrefixUnaryExpression */ || expression.kind === 203 /* PostfixUnaryExpression */) { + return expression.operator; + } + else { + return expression.kind; + } + } + ts.getOperator = getOperator; + function getOperatorPrecedence(nodeKind, operatorKind, hasArguments) { + switch (nodeKind) { + case 309 /* CommaListExpression */: + return 0; + case 208 /* SpreadElement */: + return 1; + case 207 /* YieldExpression */: + return 2; + case 205 /* ConditionalExpression */: + return 4; + case 204 /* BinaryExpression */: + switch (operatorKind) { + case 27 /* CommaToken */: + return 0; + case 59 /* EqualsToken */: + case 60 /* PlusEqualsToken */: + case 61 /* MinusEqualsToken */: + case 63 /* AsteriskAsteriskEqualsToken */: + case 62 /* AsteriskEqualsToken */: + case 64 /* SlashEqualsToken */: + case 65 /* PercentEqualsToken */: + case 66 /* LessThanLessThanEqualsToken */: + case 67 /* GreaterThanGreaterThanEqualsToken */: + case 68 /* GreaterThanGreaterThanGreaterThanEqualsToken */: + case 69 /* AmpersandEqualsToken */: + case 71 /* CaretEqualsToken */: + case 70 /* BarEqualsToken */: + return 3; + default: + return getBinaryOperatorPrecedence(operatorKind); + } + case 202 /* PrefixUnaryExpression */: + case 199 /* TypeOfExpression */: + case 200 /* VoidExpression */: + case 198 /* DeleteExpression */: + case 201 /* AwaitExpression */: + return 16; + case 203 /* PostfixUnaryExpression */: + return 17; + case 191 /* CallExpression */: + return 18; + case 192 /* NewExpression */: + return hasArguments ? 19 : 18; + case 193 /* TaggedTemplateExpression */: + case 189 /* PropertyAccessExpression */: + case 190 /* ElementAccessExpression */: + return 19; + case 100 /* ThisKeyword */: + case 98 /* SuperKeyword */: + case 72 /* Identifier */: + case 96 /* NullKeyword */: + case 102 /* TrueKeyword */: + case 87 /* FalseKeyword */: + case 8 /* NumericLiteral */: + case 9 /* BigIntLiteral */: + case 10 /* StringLiteral */: + case 187 /* ArrayLiteralExpression */: + case 188 /* ObjectLiteralExpression */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 209 /* ClassExpression */: + case 260 /* JsxElement */: + case 261 /* JsxSelfClosingElement */: + case 264 /* JsxFragment */: + case 13 /* RegularExpressionLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: + case 206 /* TemplateExpression */: + case 195 /* ParenthesizedExpression */: + case 210 /* OmittedExpression */: + return 20; + default: + return -1; + } + } + ts.getOperatorPrecedence = getOperatorPrecedence; + function getBinaryOperatorPrecedence(kind) { + switch (kind) { + case 55 /* BarBarToken */: + return 5; + case 54 /* AmpersandAmpersandToken */: + return 6; + case 50 /* BarToken */: + return 7; + case 51 /* CaretToken */: + return 8; + case 49 /* AmpersandToken */: + return 9; + case 33 /* EqualsEqualsToken */: + case 34 /* ExclamationEqualsToken */: + case 35 /* EqualsEqualsEqualsToken */: + case 36 /* ExclamationEqualsEqualsToken */: + return 10; + case 28 /* LessThanToken */: + case 30 /* GreaterThanToken */: + case 31 /* LessThanEqualsToken */: + case 32 /* GreaterThanEqualsToken */: + case 94 /* InstanceOfKeyword */: + case 93 /* InKeyword */: + case 119 /* AsKeyword */: + return 11; + case 46 /* LessThanLessThanToken */: + case 47 /* GreaterThanGreaterThanToken */: + case 48 /* GreaterThanGreaterThanGreaterThanToken */: + return 12; + case 38 /* PlusToken */: + case 39 /* MinusToken */: + return 13; + case 40 /* AsteriskToken */: + case 42 /* SlashToken */: + case 43 /* PercentToken */: + return 14; + case 41 /* AsteriskAsteriskToken */: + return 15; + } + // -1 is lower than all other precedences. Returning it will cause binary expression + // parsing to stop. + return -1; + } + ts.getBinaryOperatorPrecedence = getBinaryOperatorPrecedence; + function createDiagnosticCollection() { + var nonFileDiagnostics = []; // See GH#19873 + var filesWithDiagnostics = []; + var fileDiagnostics = ts.createMap(); + var hasReadNonFileDiagnostics = false; + return { + add: add, + lookup: lookup, + getGlobalDiagnostics: getGlobalDiagnostics, + getDiagnostics: getDiagnostics, + reattachFileDiagnostics: reattachFileDiagnostics + }; + function reattachFileDiagnostics(newFile) { + ts.forEach(fileDiagnostics.get(newFile.fileName), function (diagnostic) { return diagnostic.file = newFile; }); + } + function lookup(diagnostic) { + var diagnostics; + if (diagnostic.file) { + diagnostics = fileDiagnostics.get(diagnostic.file.fileName); + } + else { + diagnostics = nonFileDiagnostics; + } + if (!diagnostics) { + return undefined; + } + var result = ts.binarySearch(diagnostics, diagnostic, ts.identity, ts.compareDiagnosticsSkipRelatedInformation); + if (result >= 0) { + return diagnostics[result]; + } + return undefined; + } + function add(diagnostic) { + var diagnostics; + if (diagnostic.file) { + diagnostics = fileDiagnostics.get(diagnostic.file.fileName); + if (!diagnostics) { + diagnostics = []; // See GH#19873 + fileDiagnostics.set(diagnostic.file.fileName, diagnostics); + ts.insertSorted(filesWithDiagnostics, diagnostic.file.fileName, ts.compareStringsCaseSensitive); + } + } + else { + // If we've already read the non-file diagnostics, do not modify the existing array. + if (hasReadNonFileDiagnostics) { + hasReadNonFileDiagnostics = false; + nonFileDiagnostics = nonFileDiagnostics.slice(); + } + diagnostics = nonFileDiagnostics; + } + ts.insertSorted(diagnostics, diagnostic, ts.compareDiagnostics); + } + function getGlobalDiagnostics() { + hasReadNonFileDiagnostics = true; + return nonFileDiagnostics; + } + function getDiagnostics(fileName) { + if (fileName) { + return fileDiagnostics.get(fileName) || []; + } + var fileDiags = ts.flatMapToMutable(filesWithDiagnostics, function (f) { return fileDiagnostics.get(f); }); + if (!nonFileDiagnostics.length) { + return fileDiags; + } + fileDiags.unshift.apply(fileDiags, nonFileDiagnostics); + return fileDiags; + } + } + ts.createDiagnosticCollection = createDiagnosticCollection; + // This consists of the first 19 unprintable ASCII characters, canonical escapes, lineSeparator, + // paragraphSeparator, and nextLine. The latter three are just desirable to suppress new lines in + // the language service. These characters should be escaped when printing, and if any characters are added, + // the map below must be updated. Note that this regexp *does not* include the 'delete' character. + // There is no reason for this other than that JSON.stringify does not handle it either. + var doubleQuoteEscapedCharsRegExp = /[\\\"\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g; + var singleQuoteEscapedCharsRegExp = /[\\\'\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g; + var backtickQuoteEscapedCharsRegExp = /[\\\`\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g; + var escapedCharsMap = ts.createMapFromTemplate({ + "\t": "\\t", + "\v": "\\v", + "\f": "\\f", + "\b": "\\b", + "\r": "\\r", + "\n": "\\n", + "\\": "\\\\", + "\"": "\\\"", + "\'": "\\\'", + "\`": "\\\`", + "\u2028": "\\u2028", + "\u2029": "\\u2029", + "\u0085": "\\u0085" // nextLine + }); + /** + * Based heavily on the abstract 'Quote'/'QuoteJSONString' operation from ECMA-262 (24.3.2.2), + * but augmented for a few select characters (e.g. lineSeparator, paragraphSeparator, nextLine) + * Note that this doesn't actually wrap the input in double quotes. + */ + function escapeString(s, quoteChar) { + var escapedCharsRegExp = quoteChar === 96 /* backtick */ ? backtickQuoteEscapedCharsRegExp : + quoteChar === 39 /* singleQuote */ ? singleQuoteEscapedCharsRegExp : + doubleQuoteEscapedCharsRegExp; + return s.replace(escapedCharsRegExp, getReplacement); + } + ts.escapeString = escapeString; + function getReplacement(c, offset, input) { + if (c.charCodeAt(0) === 0 /* nullCharacter */) { + var lookAhead = input.charCodeAt(offset + c.length); + if (lookAhead >= 48 /* _0 */ && lookAhead <= 57 /* _9 */) { + // If the null character is followed by digits, print as a hex escape to prevent the result from parsing as an octal (which is forbidden in strict mode) + return "\\x00"; + } + // Otherwise, keep printing a literal \0 for the null character + return "\\0"; + } + return escapedCharsMap.get(c) || get16BitUnicodeEscapeSequence(c.charCodeAt(0)); + } + function isIntrinsicJsxName(name) { + var ch = name.charCodeAt(0); + return (ch >= 97 /* a */ && ch <= 122 /* z */) || ts.stringContains(name, "-"); + } + ts.isIntrinsicJsxName = isIntrinsicJsxName; + function get16BitUnicodeEscapeSequence(charCode) { + var hexCharCode = charCode.toString(16).toUpperCase(); + var paddedHexCode = ("0000" + hexCharCode).slice(-4); + return "\\u" + paddedHexCode; + } + var nonAsciiCharacters = /[^\u0000-\u007F]/g; + function escapeNonAsciiString(s, quoteChar) { + s = escapeString(s, quoteChar); + // Replace non-ASCII characters with '\uNNNN' escapes if any exist. + // Otherwise just return the original string. + return nonAsciiCharacters.test(s) ? + s.replace(nonAsciiCharacters, function (c) { return get16BitUnicodeEscapeSequence(c.charCodeAt(0)); }) : + s; + } + ts.escapeNonAsciiString = escapeNonAsciiString; + var indentStrings = ["", " "]; + function getIndentString(level) { + if (indentStrings[level] === undefined) { + indentStrings[level] = getIndentString(level - 1) + indentStrings[1]; + } + return indentStrings[level]; + } + ts.getIndentString = getIndentString; + function getIndentSize() { + return indentStrings[1].length; + } + ts.getIndentSize = getIndentSize; + function createTextWriter(newLine) { + var output; + var indent; + var lineStart; + var lineCount; + var linePos; + function updateLineCountAndPosFor(s) { + var lineStartsOfS = ts.computeLineStarts(s); + if (lineStartsOfS.length > 1) { + lineCount = lineCount + lineStartsOfS.length - 1; + linePos = output.length - s.length + ts.last(lineStartsOfS); + lineStart = (linePos - output.length) === 0; + } + else { + lineStart = false; + } + } + function write(s) { + if (s && s.length) { + if (lineStart) { + s = getIndentString(indent) + s; + lineStart = false; + } + output += s; + updateLineCountAndPosFor(s); + } + } + function reset() { + output = ""; + indent = 0; + lineStart = true; + lineCount = 0; + linePos = 0; + } + function rawWrite(s) { + if (s !== undefined) { + output += s; + updateLineCountAndPosFor(s); + } + } + function writeLiteral(s) { + if (s && s.length) { + write(s); + } + } + function writeLine() { + if (!lineStart) { + output += newLine; + lineCount++; + linePos = output.length; + lineStart = true; + } + } + reset(); + return { + write: write, + rawWrite: rawWrite, + writeLiteral: writeLiteral, + writeLine: writeLine, + increaseIndent: function () { indent++; }, + decreaseIndent: function () { indent--; }, + getIndent: function () { return indent; }, + getTextPos: function () { return output.length; }, + getLine: function () { return lineCount; }, + getColumn: function () { return lineStart ? indent * getIndentSize() : output.length - linePos; }, + getText: function () { return output; }, + isAtStartOfLine: function () { return lineStart; }, + clear: reset, + reportInaccessibleThisError: ts.noop, + reportPrivateInBaseOfClassExpression: ts.noop, + reportInaccessibleUniqueSymbolError: ts.noop, + trackSymbol: ts.noop, + writeKeyword: write, + writeOperator: write, + writeParameter: write, + writeProperty: write, + writePunctuation: write, + writeSpace: write, + writeStringLiteral: write, + writeSymbol: function (s, _) { return write(s); }, + writeTrailingSemicolon: write, + writeComment: write + }; + } + ts.createTextWriter = createTextWriter; + function getTrailingSemicolonOmittingWriter(writer) { + var pendingTrailingSemicolon = false; + function commitPendingTrailingSemicolon() { + if (pendingTrailingSemicolon) { + writer.writeTrailingSemicolon(";"); + pendingTrailingSemicolon = false; + } + } + return __assign({}, writer, { writeTrailingSemicolon: function () { + pendingTrailingSemicolon = true; + }, + writeLiteral: function (s) { + commitPendingTrailingSemicolon(); + writer.writeLiteral(s); + }, + writeStringLiteral: function (s) { + commitPendingTrailingSemicolon(); + writer.writeStringLiteral(s); + }, + writeSymbol: function (s, sym) { + commitPendingTrailingSemicolon(); + writer.writeSymbol(s, sym); + }, + writePunctuation: function (s) { + commitPendingTrailingSemicolon(); + writer.writePunctuation(s); + }, + writeKeyword: function (s) { + commitPendingTrailingSemicolon(); + writer.writeKeyword(s); + }, + writeOperator: function (s) { + commitPendingTrailingSemicolon(); + writer.writeOperator(s); + }, + writeParameter: function (s) { + commitPendingTrailingSemicolon(); + writer.writeParameter(s); + }, + writeSpace: function (s) { + commitPendingTrailingSemicolon(); + writer.writeSpace(s); + }, + writeProperty: function (s) { + commitPendingTrailingSemicolon(); + writer.writeProperty(s); + }, + writeComment: function (s) { + commitPendingTrailingSemicolon(); + writer.writeComment(s); + }, + writeLine: function () { + commitPendingTrailingSemicolon(); + writer.writeLine(); + }, + increaseIndent: function () { + commitPendingTrailingSemicolon(); + writer.increaseIndent(); + }, + decreaseIndent: function () { + commitPendingTrailingSemicolon(); + writer.decreaseIndent(); + } }); + } + ts.getTrailingSemicolonOmittingWriter = getTrailingSemicolonOmittingWriter; + function getResolvedExternalModuleName(host, file, referenceFile) { + return file.moduleName || getExternalModuleNameFromPath(host, file.fileName, referenceFile && referenceFile.fileName); + } + ts.getResolvedExternalModuleName = getResolvedExternalModuleName; + function getExternalModuleNameFromDeclaration(host, resolver, declaration) { + var file = resolver.getExternalModuleFileFromDeclaration(declaration); + if (!file || file.isDeclarationFile) { + return undefined; + } + return getResolvedExternalModuleName(host, file); + } + ts.getExternalModuleNameFromDeclaration = getExternalModuleNameFromDeclaration; + /** + * Resolves a local path to a path which is absolute to the base of the emit + */ + function getExternalModuleNameFromPath(host, fileName, referencePath) { + var getCanonicalFileName = function (f) { return host.getCanonicalFileName(f); }; + var dir = toPath(referencePath ? ts.getDirectoryPath(referencePath) : host.getCommonSourceDirectory(), host.getCurrentDirectory(), getCanonicalFileName); + var filePath = ts.getNormalizedAbsolutePath(fileName, host.getCurrentDirectory()); + var relativePath = ts.getRelativePathToDirectoryOrUrl(dir, filePath, dir, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); + var extensionless = ts.removeFileExtension(relativePath); + return referencePath ? ts.ensurePathIsNonModuleName(extensionless) : extensionless; + } + ts.getExternalModuleNameFromPath = getExternalModuleNameFromPath; + function getOwnEmitOutputFilePath(fileName, host, extension) { + var compilerOptions = host.getCompilerOptions(); + var emitOutputFilePathWithoutExtension; + if (compilerOptions.outDir) { + emitOutputFilePathWithoutExtension = ts.removeFileExtension(getSourceFilePathInNewDir(fileName, host, compilerOptions.outDir)); + } + else { + emitOutputFilePathWithoutExtension = ts.removeFileExtension(fileName); + } + return emitOutputFilePathWithoutExtension + extension; + } + ts.getOwnEmitOutputFilePath = getOwnEmitOutputFilePath; + function getDeclarationEmitOutputFilePath(fileName, host) { + return getDeclarationEmitOutputFilePathWorker(fileName, host.getCompilerOptions(), host.getCurrentDirectory(), host.getCommonSourceDirectory(), function (f) { return host.getCanonicalFileName(f); }); + } + ts.getDeclarationEmitOutputFilePath = getDeclarationEmitOutputFilePath; + function getDeclarationEmitOutputFilePathWorker(fileName, options, currentDirectory, commonSourceDirectory, getCanonicalFileName) { + var outputDir = options.declarationDir || options.outDir; // Prefer declaration folder if specified + var path = outputDir + ? getSourceFilePathInNewDirWorker(fileName, outputDir, currentDirectory, commonSourceDirectory, getCanonicalFileName) + : fileName; + return ts.removeFileExtension(path) + ".d.ts" /* Dts */; + } + ts.getDeclarationEmitOutputFilePathWorker = getDeclarationEmitOutputFilePathWorker; + /** + * Gets the source files that are expected to have an emit output. + * + * Originally part of `forEachExpectedEmitFile`, this functionality was extracted to support + * transformations. + * + * @param host An EmitHost. + * @param targetSourceFile An optional target source file to emit. + */ + function getSourceFilesToEmit(host, targetSourceFile) { + var options = host.getCompilerOptions(); + var isSourceFileFromExternalLibrary = function (file) { return host.isSourceFileFromExternalLibrary(file); }; + if (options.outFile || options.out) { + var moduleKind = ts.getEmitModuleKind(options); + var moduleEmitEnabled_1 = options.emitDeclarationOnly || moduleKind === ts.ModuleKind.AMD || moduleKind === ts.ModuleKind.System; + // Can emit only sources that are not declaration file and are either non module code or module with --module or --target es6 specified + return ts.filter(host.getSourceFiles(), function (sourceFile) { + return (moduleEmitEnabled_1 || !ts.isExternalModule(sourceFile)) && sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary); + }); + } + else { + var sourceFiles = targetSourceFile === undefined ? host.getSourceFiles() : [targetSourceFile]; + return ts.filter(sourceFiles, function (sourceFile) { return sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary); }); + } + } + ts.getSourceFilesToEmit = getSourceFilesToEmit; + /** Don't call this for `--outFile`, just for `--outDir` or plain emit. `--outFile` needs additional checks. */ + function sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary) { + return !(options.noEmitForJsFiles && isSourceFileJS(sourceFile)) && !sourceFile.isDeclarationFile && !isSourceFileFromExternalLibrary(sourceFile); + } + ts.sourceFileMayBeEmitted = sourceFileMayBeEmitted; + function getSourceFilePathInNewDir(fileName, host, newDirPath) { + return getSourceFilePathInNewDirWorker(fileName, newDirPath, host.getCurrentDirectory(), host.getCommonSourceDirectory(), function (f) { return host.getCanonicalFileName(f); }); + } + ts.getSourceFilePathInNewDir = getSourceFilePathInNewDir; + function getSourceFilePathInNewDirWorker(fileName, newDirPath, currentDirectory, commonSourceDirectory, getCanonicalFileName) { + var sourceFilePath = ts.getNormalizedAbsolutePath(fileName, currentDirectory); + var isSourceFileInCommonSourceDirectory = getCanonicalFileName(sourceFilePath).indexOf(getCanonicalFileName(commonSourceDirectory)) === 0; + sourceFilePath = isSourceFileInCommonSourceDirectory ? sourceFilePath.substring(commonSourceDirectory.length) : sourceFilePath; + return ts.combinePaths(newDirPath, sourceFilePath); + } + ts.getSourceFilePathInNewDirWorker = getSourceFilePathInNewDirWorker; + function writeFile(host, diagnostics, fileName, data, writeByteOrderMark, sourceFiles) { + host.writeFile(fileName, data, writeByteOrderMark, function (hostErrorMessage) { + diagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Could_not_write_file_0_Colon_1, fileName, hostErrorMessage)); + }, sourceFiles); + } + ts.writeFile = writeFile; + function getLineOfLocalPosition(currentSourceFile, pos) { + return ts.getLineAndCharacterOfPosition(currentSourceFile, pos).line; + } + ts.getLineOfLocalPosition = getLineOfLocalPosition; + function getLineOfLocalPositionFromLineMap(lineMap, pos) { + return ts.computeLineAndCharacterOfPosition(lineMap, pos).line; + } + ts.getLineOfLocalPositionFromLineMap = getLineOfLocalPositionFromLineMap; + function getFirstConstructorWithBody(node) { + return ts.find(node.members, function (member) { return ts.isConstructorDeclaration(member) && nodeIsPresent(member.body); }); + } + ts.getFirstConstructorWithBody = getFirstConstructorWithBody; + function getSetAccessorValueParameter(accessor) { + if (accessor && accessor.parameters.length > 0) { + var hasThis = accessor.parameters.length === 2 && parameterIsThisKeyword(accessor.parameters[0]); + return accessor.parameters[hasThis ? 1 : 0]; + } + } + /** Get the type annotation for the value parameter. */ + function getSetAccessorTypeAnnotationNode(accessor) { + var parameter = getSetAccessorValueParameter(accessor); + return parameter && parameter.type; + } + ts.getSetAccessorTypeAnnotationNode = getSetAccessorTypeAnnotationNode; + function getThisParameter(signature) { + // callback tags do not currently support this parameters + if (signature.parameters.length && !ts.isJSDocSignature(signature)) { + var thisParameter = signature.parameters[0]; + if (parameterIsThisKeyword(thisParameter)) { + return thisParameter; + } + } + } + ts.getThisParameter = getThisParameter; + function parameterIsThisKeyword(parameter) { + return isThisIdentifier(parameter.name); + } + ts.parameterIsThisKeyword = parameterIsThisKeyword; + function isThisIdentifier(node) { + return !!node && node.kind === 72 /* Identifier */ && identifierIsThisKeyword(node); + } + ts.isThisIdentifier = isThisIdentifier; + function identifierIsThisKeyword(id) { + return id.originalKeywordKind === 100 /* ThisKeyword */; + } + ts.identifierIsThisKeyword = identifierIsThisKeyword; + function getAllAccessorDeclarations(declarations, accessor) { + // TODO: GH#18217 + var firstAccessor; + var secondAccessor; + var getAccessor; + var setAccessor; + if (hasDynamicName(accessor)) { + firstAccessor = accessor; + if (accessor.kind === 158 /* GetAccessor */) { + getAccessor = accessor; + } + else if (accessor.kind === 159 /* SetAccessor */) { + setAccessor = accessor; + } + else { + ts.Debug.fail("Accessor has wrong kind"); + } + } + else { + ts.forEach(declarations, function (member) { + if (ts.isAccessor(member) + && hasModifier(member, 32 /* Static */) === hasModifier(accessor, 32 /* Static */)) { + var memberName = getPropertyNameForPropertyNameNode(member.name); + var accessorName = getPropertyNameForPropertyNameNode(accessor.name); + if (memberName === accessorName) { + if (!firstAccessor) { + firstAccessor = member; + } + else if (!secondAccessor) { + secondAccessor = member; + } + if (member.kind === 158 /* GetAccessor */ && !getAccessor) { + getAccessor = member; + } + if (member.kind === 159 /* SetAccessor */ && !setAccessor) { + setAccessor = member; + } + } + } + }); + } + return { + firstAccessor: firstAccessor, + secondAccessor: secondAccessor, + getAccessor: getAccessor, + setAccessor: setAccessor + }; + } + ts.getAllAccessorDeclarations = getAllAccessorDeclarations; + /** + * Gets the effective type annotation of a variable, parameter, or property. If the node was + * parsed in a JavaScript file, gets the type annotation from JSDoc. + */ + function getEffectiveTypeAnnotationNode(node) { + var type = node.type; + if (type || !isInJSFile(node)) + return type; + return ts.isJSDocPropertyLikeTag(node) ? node.typeExpression && node.typeExpression.type : ts.getJSDocType(node); + } + ts.getEffectiveTypeAnnotationNode = getEffectiveTypeAnnotationNode; + function getTypeAnnotationNode(node) { + return node.type; + } + ts.getTypeAnnotationNode = getTypeAnnotationNode; + /** + * Gets the effective return type annotation of a signature. If the node was parsed in a + * JavaScript file, gets the return type annotation from JSDoc. + */ + function getEffectiveReturnTypeNode(node) { + return ts.isJSDocSignature(node) ? + node.type && node.type.typeExpression && node.type.typeExpression.type : + node.type || (isInJSFile(node) ? ts.getJSDocReturnType(node) : undefined); + } + ts.getEffectiveReturnTypeNode = getEffectiveReturnTypeNode; + function getJSDocTypeParameterDeclarations(node) { + return ts.flatMap(ts.getJSDocTags(node), function (tag) { return isNonTypeAliasTemplate(tag) ? tag.typeParameters : undefined; }); + } + ts.getJSDocTypeParameterDeclarations = getJSDocTypeParameterDeclarations; + /** template tags are only available when a typedef isn't already using them */ + function isNonTypeAliasTemplate(tag) { + return ts.isJSDocTemplateTag(tag) && !(tag.parent.kind === 291 /* JSDocComment */ && tag.parent.tags.some(isJSDocTypeAlias)); + } + /** + * Gets the effective type annotation of the value parameter of a set accessor. If the node + * was parsed in a JavaScript file, gets the type annotation from JSDoc. + */ + function getEffectiveSetAccessorTypeAnnotationNode(node) { + var parameter = getSetAccessorValueParameter(node); + return parameter && getEffectiveTypeAnnotationNode(parameter); + } + ts.getEffectiveSetAccessorTypeAnnotationNode = getEffectiveSetAccessorTypeAnnotationNode; + function emitNewLineBeforeLeadingComments(lineMap, writer, node, leadingComments) { + emitNewLineBeforeLeadingCommentsOfPosition(lineMap, writer, node.pos, leadingComments); + } + ts.emitNewLineBeforeLeadingComments = emitNewLineBeforeLeadingComments; + function emitNewLineBeforeLeadingCommentsOfPosition(lineMap, writer, pos, leadingComments) { + // If the leading comments start on different line than the start of node, write new line + if (leadingComments && leadingComments.length && pos !== leadingComments[0].pos && + getLineOfLocalPositionFromLineMap(lineMap, pos) !== getLineOfLocalPositionFromLineMap(lineMap, leadingComments[0].pos)) { + writer.writeLine(); + } + } + ts.emitNewLineBeforeLeadingCommentsOfPosition = emitNewLineBeforeLeadingCommentsOfPosition; + function emitNewLineBeforeLeadingCommentOfPosition(lineMap, writer, pos, commentPos) { + // If the leading comments start on different line than the start of node, write new line + if (pos !== commentPos && + getLineOfLocalPositionFromLineMap(lineMap, pos) !== getLineOfLocalPositionFromLineMap(lineMap, commentPos)) { + writer.writeLine(); + } + } + ts.emitNewLineBeforeLeadingCommentOfPosition = emitNewLineBeforeLeadingCommentOfPosition; + function emitComments(text, lineMap, writer, comments, leadingSeparator, trailingSeparator, newLine, writeComment) { + if (comments && comments.length > 0) { + if (leadingSeparator) { + writer.writeSpace(" "); + } + var emitInterveningSeparator = false; + for (var _i = 0, comments_1 = comments; _i < comments_1.length; _i++) { + var comment = comments_1[_i]; + if (emitInterveningSeparator) { + writer.writeSpace(" "); + emitInterveningSeparator = false; + } + writeComment(text, lineMap, writer, comment.pos, comment.end, newLine); + if (comment.hasTrailingNewLine) { + writer.writeLine(); + } + else { + emitInterveningSeparator = true; + } + } + if (emitInterveningSeparator && trailingSeparator) { + writer.writeSpace(" "); + } + } + } + ts.emitComments = emitComments; + /** + * Detached comment is a comment at the top of file or function body that is separated from + * the next statement by space. + */ + function emitDetachedComments(text, lineMap, writer, writeComment, node, newLine, removeComments) { + var leadingComments; + var currentDetachedCommentInfo; + if (removeComments) { + // removeComments is true, only reserve pinned comment at the top of file + // For example: + // /*! Pinned Comment */ + // + // var x = 10; + if (node.pos === 0) { + leadingComments = ts.filter(ts.getLeadingCommentRanges(text, node.pos), isPinnedCommentLocal); + } + } + else { + // removeComments is false, just get detached as normal and bypass the process to filter comment + leadingComments = ts.getLeadingCommentRanges(text, node.pos); + } + if (leadingComments) { + var detachedComments = []; + var lastComment = void 0; + for (var _i = 0, leadingComments_1 = leadingComments; _i < leadingComments_1.length; _i++) { + var comment = leadingComments_1[_i]; + if (lastComment) { + var lastCommentLine = getLineOfLocalPositionFromLineMap(lineMap, lastComment.end); + var commentLine = getLineOfLocalPositionFromLineMap(lineMap, comment.pos); + if (commentLine >= lastCommentLine + 2) { + // There was a blank line between the last comment and this comment. This + // comment is not part of the copyright comments. Return what we have so + // far. + break; + } + } + detachedComments.push(comment); + lastComment = comment; + } + if (detachedComments.length) { + // All comments look like they could have been part of the copyright header. Make + // sure there is at least one blank line between it and the node. If not, it's not + // a copyright header. + var lastCommentLine = getLineOfLocalPositionFromLineMap(lineMap, ts.last(detachedComments).end); + var nodeLine = getLineOfLocalPositionFromLineMap(lineMap, ts.skipTrivia(text, node.pos)); + if (nodeLine >= lastCommentLine + 2) { + // Valid detachedComments + emitNewLineBeforeLeadingComments(lineMap, writer, node, leadingComments); + emitComments(text, lineMap, writer, detachedComments, /*leadingSeparator*/ false, /*trailingSeparator*/ true, newLine, writeComment); + currentDetachedCommentInfo = { nodePos: node.pos, detachedCommentEndPos: ts.last(detachedComments).end }; + } + } + } + return currentDetachedCommentInfo; + function isPinnedCommentLocal(comment) { + return isPinnedComment(text, comment.pos); + } + } + ts.emitDetachedComments = emitDetachedComments; + function writeCommentRange(text, lineMap, writer, commentPos, commentEnd, newLine) { + if (text.charCodeAt(commentPos + 1) === 42 /* asterisk */) { + var firstCommentLineAndCharacter = ts.computeLineAndCharacterOfPosition(lineMap, commentPos); + var lineCount = lineMap.length; + var firstCommentLineIndent = void 0; + for (var pos = commentPos, currentLine = firstCommentLineAndCharacter.line; pos < commentEnd; currentLine++) { + var nextLineStart = (currentLine + 1) === lineCount + ? text.length + 1 + : lineMap[currentLine + 1]; + if (pos !== commentPos) { + // If we are not emitting first line, we need to write the spaces to adjust the alignment + if (firstCommentLineIndent === undefined) { + firstCommentLineIndent = calculateIndent(text, lineMap[firstCommentLineAndCharacter.line], commentPos); + } + // These are number of spaces writer is going to write at current indent + var currentWriterIndentSpacing = writer.getIndent() * getIndentSize(); + // Number of spaces we want to be writing + // eg: Assume writer indent + // module m { + // /* starts at character 9 this is line 1 + // * starts at character pos 4 line --1 = 8 - 8 + 3 + // More left indented comment */ --2 = 8 - 8 + 2 + // class c { } + // } + // module m { + // /* this is line 1 -- Assume current writer indent 8 + // * line --3 = 8 - 4 + 5 + // More right indented comment */ --4 = 8 - 4 + 11 + // class c { } + // } + var spacesToEmit = currentWriterIndentSpacing - firstCommentLineIndent + calculateIndent(text, pos, nextLineStart); + if (spacesToEmit > 0) { + var numberOfSingleSpacesToEmit = spacesToEmit % getIndentSize(); + var indentSizeSpaceString = getIndentString((spacesToEmit - numberOfSingleSpacesToEmit) / getIndentSize()); + // Write indent size string ( in eg 1: = "", 2: "" , 3: string with 8 spaces 4: string with 12 spaces + writer.rawWrite(indentSizeSpaceString); + // Emit the single spaces (in eg: 1: 3 spaces, 2: 2 spaces, 3: 1 space, 4: 3 spaces) + while (numberOfSingleSpacesToEmit) { + writer.rawWrite(" "); + numberOfSingleSpacesToEmit--; + } + } + else { + // No spaces to emit write empty string + writer.rawWrite(""); + } + } + // Write the comment line text + writeTrimmedCurrentLine(text, commentEnd, writer, newLine, pos, nextLineStart); + pos = nextLineStart; + } + } + else { + // Single line comment of style //.... + writer.writeComment(text.substring(commentPos, commentEnd)); + } + } + ts.writeCommentRange = writeCommentRange; + function writeTrimmedCurrentLine(text, commentEnd, writer, newLine, pos, nextLineStart) { + var end = Math.min(commentEnd, nextLineStart - 1); + var currentLineText = text.substring(pos, end).replace(/^\s+|\s+$/g, ""); + if (currentLineText) { + // trimmed forward and ending spaces text + writer.writeComment(currentLineText); + if (end !== commentEnd) { + writer.writeLine(); + } + } + else { + // Empty string - make sure we write empty line + writer.rawWrite(newLine); + } + } + function calculateIndent(text, pos, end) { + var currentLineIndent = 0; + for (; pos < end && ts.isWhiteSpaceSingleLine(text.charCodeAt(pos)); pos++) { + if (text.charCodeAt(pos) === 9 /* tab */) { + // Tabs = TabSize = indent size and go to next tabStop + currentLineIndent += getIndentSize() - (currentLineIndent % getIndentSize()); + } + else { + // Single space + currentLineIndent++; + } + } + return currentLineIndent; + } + function hasModifiers(node) { + return getModifierFlags(node) !== 0 /* None */; + } + ts.hasModifiers = hasModifiers; + function hasModifier(node, flags) { + return !!getSelectedModifierFlags(node, flags); + } + ts.hasModifier = hasModifier; + function hasStaticModifier(node) { + return hasModifier(node, 32 /* Static */); + } + ts.hasStaticModifier = hasStaticModifier; + function hasReadonlyModifier(node) { + return hasModifier(node, 64 /* Readonly */); + } + ts.hasReadonlyModifier = hasReadonlyModifier; + function getSelectedModifierFlags(node, flags) { + return getModifierFlags(node) & flags; + } + ts.getSelectedModifierFlags = getSelectedModifierFlags; + function getModifierFlags(node) { + if (node.modifierFlagsCache & 536870912 /* HasComputedFlags */) { + return node.modifierFlagsCache & ~536870912 /* HasComputedFlags */; + } + var flags = getModifierFlagsNoCache(node); + node.modifierFlagsCache = flags | 536870912 /* HasComputedFlags */; + return flags; + } + ts.getModifierFlags = getModifierFlags; + function getModifierFlagsNoCache(node) { + var flags = 0 /* None */; + if (node.modifiers) { + for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) { + var modifier = _a[_i]; + flags |= modifierToFlag(modifier.kind); + } + } + if (node.flags & 4 /* NestedNamespace */ || (node.kind === 72 /* Identifier */ && node.isInJSDocNamespace)) { + flags |= 1 /* Export */; + } + return flags; + } + ts.getModifierFlagsNoCache = getModifierFlagsNoCache; + function modifierToFlag(token) { + switch (token) { + case 116 /* StaticKeyword */: return 32 /* Static */; + case 115 /* PublicKeyword */: return 4 /* Public */; + case 114 /* ProtectedKeyword */: return 16 /* Protected */; + case 113 /* PrivateKeyword */: return 8 /* Private */; + case 118 /* AbstractKeyword */: return 128 /* Abstract */; + case 85 /* ExportKeyword */: return 1 /* Export */; + case 125 /* DeclareKeyword */: return 2 /* Ambient */; + case 77 /* ConstKeyword */: return 2048 /* Const */; + case 80 /* DefaultKeyword */: return 512 /* Default */; + case 121 /* AsyncKeyword */: return 256 /* Async */; + case 133 /* ReadonlyKeyword */: return 64 /* Readonly */; + } + return 0 /* None */; + } + ts.modifierToFlag = modifierToFlag; + function isLogicalOperator(token) { + return token === 55 /* BarBarToken */ + || token === 54 /* AmpersandAmpersandToken */ + || token === 52 /* ExclamationToken */; + } + ts.isLogicalOperator = isLogicalOperator; + function isAssignmentOperator(token) { + return token >= 59 /* FirstAssignment */ && token <= 71 /* LastAssignment */; + } + ts.isAssignmentOperator = isAssignmentOperator; + /** Get `C` given `N` if `N` is in the position `class C extends N` where `N` is an ExpressionWithTypeArguments. */ + function tryGetClassExtendingExpressionWithTypeArguments(node) { + var cls = tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node); + return cls && !cls.isImplements ? cls.class : undefined; + } + ts.tryGetClassExtendingExpressionWithTypeArguments = tryGetClassExtendingExpressionWithTypeArguments; + function tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node) { + return ts.isExpressionWithTypeArguments(node) + && ts.isHeritageClause(node.parent) + && ts.isClassLike(node.parent.parent) + ? { class: node.parent.parent, isImplements: node.parent.token === 109 /* ImplementsKeyword */ } + : undefined; + } + ts.tryGetClassImplementingOrExtendingExpressionWithTypeArguments = tryGetClassImplementingOrExtendingExpressionWithTypeArguments; + function isAssignmentExpression(node, excludeCompoundAssignment) { + return ts.isBinaryExpression(node) + && (excludeCompoundAssignment + ? node.operatorToken.kind === 59 /* EqualsToken */ + : isAssignmentOperator(node.operatorToken.kind)) + && ts.isLeftHandSideExpression(node.left); + } + ts.isAssignmentExpression = isAssignmentExpression; + function isDestructuringAssignment(node) { + if (isAssignmentExpression(node, /*excludeCompoundAssignment*/ true)) { + var kind = node.left.kind; + return kind === 188 /* ObjectLiteralExpression */ + || kind === 187 /* ArrayLiteralExpression */; + } + return false; + } + ts.isDestructuringAssignment = isDestructuringAssignment; + function isExpressionWithTypeArgumentsInClassExtendsClause(node) { + return tryGetClassExtendingExpressionWithTypeArguments(node) !== undefined; + } + ts.isExpressionWithTypeArgumentsInClassExtendsClause = isExpressionWithTypeArgumentsInClassExtendsClause; + function isEntityNameExpression(node) { + return node.kind === 72 /* Identifier */ || isPropertyAccessEntityNameExpression(node); + } + ts.isEntityNameExpression = isEntityNameExpression; + function isPropertyAccessEntityNameExpression(node) { + return ts.isPropertyAccessExpression(node) && isEntityNameExpression(node.expression); + } + ts.isPropertyAccessEntityNameExpression = isPropertyAccessEntityNameExpression; + function isPrototypeAccess(node) { + return ts.isPropertyAccessExpression(node) && node.name.escapedText === "prototype"; + } + ts.isPrototypeAccess = isPrototypeAccess; + function isRightSideOfQualifiedNameOrPropertyAccess(node) { + return (node.parent.kind === 148 /* QualifiedName */ && node.parent.right === node) || + (node.parent.kind === 189 /* PropertyAccessExpression */ && node.parent.name === node); + } + ts.isRightSideOfQualifiedNameOrPropertyAccess = isRightSideOfQualifiedNameOrPropertyAccess; + function isEmptyObjectLiteral(expression) { + return expression.kind === 188 /* ObjectLiteralExpression */ && + expression.properties.length === 0; + } + ts.isEmptyObjectLiteral = isEmptyObjectLiteral; + function isEmptyArrayLiteral(expression) { + return expression.kind === 187 /* ArrayLiteralExpression */ && + expression.elements.length === 0; + } + ts.isEmptyArrayLiteral = isEmptyArrayLiteral; + function getLocalSymbolForExportDefault(symbol) { + return isExportDefaultSymbol(symbol) ? symbol.declarations[0].localSymbol : undefined; + } + ts.getLocalSymbolForExportDefault = getLocalSymbolForExportDefault; + function isExportDefaultSymbol(symbol) { + return symbol && ts.length(symbol.declarations) > 0 && hasModifier(symbol.declarations[0], 512 /* Default */); + } + /** Return ".ts", ".d.ts", or ".tsx", if that is the extension. */ + function tryExtractTSExtension(fileName) { + return ts.find(ts.supportedTSExtensionsForExtractExtension, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + } + ts.tryExtractTSExtension = tryExtractTSExtension; + /** + * Replace each instance of non-ascii characters by one, two, three, or four escape sequences + * representing the UTF-8 encoding of the character, and return the expanded char code list. + */ + function getExpandedCharCodes(input) { + var output = []; + var length = input.length; + for (var i = 0; i < length; i++) { + var charCode = input.charCodeAt(i); + // handle utf8 + if (charCode < 0x80) { + output.push(charCode); + } + else if (charCode < 0x800) { + output.push((charCode >> 6) | 192); + output.push((charCode & 63) | 128); + } + else if (charCode < 0x10000) { + output.push((charCode >> 12) | 224); + output.push(((charCode >> 6) & 63) | 128); + output.push((charCode & 63) | 128); + } + else if (charCode < 0x20000) { + output.push((charCode >> 18) | 240); + output.push(((charCode >> 12) & 63) | 128); + output.push(((charCode >> 6) & 63) | 128); + output.push((charCode & 63) | 128); + } + else { + ts.Debug.assert(false, "Unexpected code point"); + } + } + return output; + } + var base64Digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; + /** + * Converts a string to a base-64 encoded ASCII string. + */ + function convertToBase64(input) { + var result = ""; + var charCodes = getExpandedCharCodes(input); + var i = 0; + var length = charCodes.length; + var byte1, byte2, byte3, byte4; + while (i < length) { + // Convert every 6-bits in the input 3 character points + // into a base64 digit + byte1 = charCodes[i] >> 2; + byte2 = (charCodes[i] & 3) << 4 | charCodes[i + 1] >> 4; + byte3 = (charCodes[i + 1] & 15) << 2 | charCodes[i + 2] >> 6; + byte4 = charCodes[i + 2] & 63; + // We are out of characters in the input, set the extra + // digits to 64 (padding character). + if (i + 1 >= length) { + byte3 = byte4 = 64; + } + else if (i + 2 >= length) { + byte4 = 64; + } + // Write to the output + result += base64Digits.charAt(byte1) + base64Digits.charAt(byte2) + base64Digits.charAt(byte3) + base64Digits.charAt(byte4); + i += 3; + } + return result; + } + ts.convertToBase64 = convertToBase64; + function getStringFromExpandedCharCodes(codes) { + var output = ""; + var i = 0; + var length = codes.length; + while (i < length) { + var charCode = codes[i]; + if (charCode < 0x80) { + output += String.fromCharCode(charCode); + i++; + } + else if ((charCode & 192) === 192) { + var value = charCode & 63; + i++; + var nextCode = codes[i]; + while ((nextCode & 192) === 128) { + value = (value << 6) | (nextCode & 63); + i++; + nextCode = codes[i]; + } + // `value` may be greater than 10FFFF (the maximum unicode codepoint) - JS will just make this into an invalid character for us + output += String.fromCharCode(value); + } + else { + // We don't want to kill the process when decoding fails (due to a following char byte not + // following a leading char), so we just print the (bad) value + output += String.fromCharCode(charCode); + i++; + } + } + return output; + } + function base64encode(host, input) { + if (host && host.base64encode) { + return host.base64encode(input); + } + return convertToBase64(input); + } + ts.base64encode = base64encode; + function base64decode(host, input) { + if (host && host.base64decode) { + return host.base64decode(input); + } + var length = input.length; + var expandedCharCodes = []; + var i = 0; + while (i < length) { + // Stop decoding once padding characters are present + if (input.charCodeAt(i) === base64Digits.charCodeAt(64)) { + break; + } + // convert 4 input digits into three characters, ignoring padding characters at the end + var ch1 = base64Digits.indexOf(input[i]); + var ch2 = base64Digits.indexOf(input[i + 1]); + var ch3 = base64Digits.indexOf(input[i + 2]); + var ch4 = base64Digits.indexOf(input[i + 3]); + var code1 = ((ch1 & 63) << 2) | ((ch2 >> 4) & 3); + var code2 = ((ch2 & 15) << 4) | ((ch3 >> 2) & 15); + var code3 = ((ch3 & 3) << 6) | (ch4 & 63); + if (code2 === 0 && ch3 !== 0) { // code2 decoded to zero, but ch3 was padding - elide code2 and code3 + expandedCharCodes.push(code1); + } + else if (code3 === 0 && ch4 !== 0) { // code3 decoded to zero, but ch4 was padding, elide code3 + expandedCharCodes.push(code1, code2); + } + else { + expandedCharCodes.push(code1, code2, code3); + } + i += 4; + } + return getStringFromExpandedCharCodes(expandedCharCodes); + } + ts.base64decode = base64decode; + function readJson(path, host) { + try { + var jsonText = host.readFile(path); + if (!jsonText) + return {}; + var result = ts.parseConfigFileTextToJson(path, jsonText); + if (result.error) { + return {}; + } + return result.config; + } + catch (e) { + // gracefully handle if readFile fails or returns not JSON + return {}; + } + } + ts.readJson = readJson; + function directoryProbablyExists(directoryName, host) { + // if host does not support 'directoryExists' assume that directory will exist + return !host.directoryExists || host.directoryExists(directoryName); + } + ts.directoryProbablyExists = directoryProbablyExists; + var carriageReturnLineFeed = "\r\n"; + var lineFeed = "\n"; + function getNewLineCharacter(options, getNewLine) { + switch (options.newLine) { + case 0 /* CarriageReturnLineFeed */: + return carriageReturnLineFeed; + case 1 /* LineFeed */: + return lineFeed; + } + return getNewLine ? getNewLine() : ts.sys ? ts.sys.newLine : carriageReturnLineFeed; + } + ts.getNewLineCharacter = getNewLineCharacter; + /** + * Formats an enum value as a string for debugging and debug assertions. + */ + function formatEnum(value, enumObject, isFlags) { + if (value === void 0) { value = 0; } + var members = getEnumMembers(enumObject); + if (value === 0) { + return members.length > 0 && members[0][0] === 0 ? members[0][1] : "0"; + } + if (isFlags) { + var result = ""; + var remainingFlags = value; + for (var i = members.length - 1; i >= 0 && remainingFlags !== 0; i--) { + var _a = members[i], enumValue = _a[0], enumName = _a[1]; + if (enumValue !== 0 && (remainingFlags & enumValue) === enumValue) { + remainingFlags &= ~enumValue; + result = "" + enumName + (result ? ", " : "") + result; + } + } + if (remainingFlags === 0) { + return result; + } + } + else { + for (var _i = 0, members_1 = members; _i < members_1.length; _i++) { + var _b = members_1[_i], enumValue = _b[0], enumName = _b[1]; + if (enumValue === value) { + return enumName; + } + } + } + return value.toString(); + } + function getEnumMembers(enumObject) { + var result = []; + for (var name in enumObject) { + var value = enumObject[name]; + if (typeof value === "number") { + result.push([value, name]); + } + } + return ts.stableSort(result, function (x, y) { return ts.compareValues(x[0], y[0]); }); + } + function formatSyntaxKind(kind) { + return formatEnum(kind, ts.SyntaxKind, /*isFlags*/ false); + } + ts.formatSyntaxKind = formatSyntaxKind; + function formatModifierFlags(flags) { + return formatEnum(flags, ts.ModifierFlags, /*isFlags*/ true); + } + ts.formatModifierFlags = formatModifierFlags; + function formatTransformFlags(flags) { + return formatEnum(flags, ts.TransformFlags, /*isFlags*/ true); + } + ts.formatTransformFlags = formatTransformFlags; + function formatEmitFlags(flags) { + return formatEnum(flags, ts.EmitFlags, /*isFlags*/ true); + } + ts.formatEmitFlags = formatEmitFlags; + function formatSymbolFlags(flags) { + return formatEnum(flags, ts.SymbolFlags, /*isFlags*/ true); + } + ts.formatSymbolFlags = formatSymbolFlags; + function formatTypeFlags(flags) { + return formatEnum(flags, ts.TypeFlags, /*isFlags*/ true); + } + ts.formatTypeFlags = formatTypeFlags; + function formatObjectFlags(flags) { + return formatEnum(flags, ts.ObjectFlags, /*isFlags*/ true); + } + ts.formatObjectFlags = formatObjectFlags; + /** + * Creates a new TextRange from the provided pos and end. + * + * @param pos The start position. + * @param end The end position. + */ + function createRange(pos, end) { + if (end === void 0) { end = pos; } + ts.Debug.assert(end >= pos || end === -1); + return { pos: pos, end: end }; + } + ts.createRange = createRange; + /** + * Creates a new TextRange from a provided range with a new end position. + * + * @param range A TextRange. + * @param end The new end position. + */ + function moveRangeEnd(range, end) { + return createRange(range.pos, end); + } + ts.moveRangeEnd = moveRangeEnd; + /** + * Creates a new TextRange from a provided range with a new start position. + * + * @param range A TextRange. + * @param pos The new Start position. + */ + function moveRangePos(range, pos) { + return createRange(pos, range.end); + } + ts.moveRangePos = moveRangePos; + /** + * Moves the start position of a range past any decorators. + */ + function moveRangePastDecorators(node) { + return node.decorators && node.decorators.length > 0 + ? moveRangePos(node, node.decorators.end) + : node; + } + ts.moveRangePastDecorators = moveRangePastDecorators; + /** + * Moves the start position of a range past any decorators or modifiers. + */ + function moveRangePastModifiers(node) { + return node.modifiers && node.modifiers.length > 0 + ? moveRangePos(node, node.modifiers.end) + : moveRangePastDecorators(node); + } + ts.moveRangePastModifiers = moveRangePastModifiers; + /** + * Determines whether a TextRange has the same start and end positions. + * + * @param range A TextRange. + */ + function isCollapsedRange(range) { + return range.pos === range.end; + } + ts.isCollapsedRange = isCollapsedRange; + /** + * Creates a new TextRange for a token at the provides start position. + * + * @param pos The start position. + * @param token The token. + */ + function createTokenRange(pos, token) { + return createRange(pos, pos + ts.tokenToString(token).length); + } + ts.createTokenRange = createTokenRange; + function rangeIsOnSingleLine(range, sourceFile) { + return rangeStartIsOnSameLineAsRangeEnd(range, range, sourceFile); + } + ts.rangeIsOnSingleLine = rangeIsOnSingleLine; + function rangeStartPositionsAreOnSameLine(range1, range2, sourceFile) { + return positionsAreOnSameLine(getStartPositionOfRange(range1, sourceFile), getStartPositionOfRange(range2, sourceFile), sourceFile); + } + ts.rangeStartPositionsAreOnSameLine = rangeStartPositionsAreOnSameLine; + function rangeEndPositionsAreOnSameLine(range1, range2, sourceFile) { + return positionsAreOnSameLine(range1.end, range2.end, sourceFile); + } + ts.rangeEndPositionsAreOnSameLine = rangeEndPositionsAreOnSameLine; + function rangeStartIsOnSameLineAsRangeEnd(range1, range2, sourceFile) { + return positionsAreOnSameLine(getStartPositionOfRange(range1, sourceFile), range2.end, sourceFile); + } + ts.rangeStartIsOnSameLineAsRangeEnd = rangeStartIsOnSameLineAsRangeEnd; + function rangeEndIsOnSameLineAsRangeStart(range1, range2, sourceFile) { + return positionsAreOnSameLine(range1.end, getStartPositionOfRange(range2, sourceFile), sourceFile); + } + ts.rangeEndIsOnSameLineAsRangeStart = rangeEndIsOnSameLineAsRangeStart; + function positionsAreOnSameLine(pos1, pos2, sourceFile) { + return pos1 === pos2 || + getLineOfLocalPosition(sourceFile, pos1) === getLineOfLocalPosition(sourceFile, pos2); + } + ts.positionsAreOnSameLine = positionsAreOnSameLine; + function getStartPositionOfRange(range, sourceFile) { + return ts.positionIsSynthesized(range.pos) ? -1 : ts.skipTrivia(sourceFile.text, range.pos); + } + ts.getStartPositionOfRange = getStartPositionOfRange; + /** + * Determines whether a name was originally the declaration name of an enum or namespace + * declaration. + */ + function isDeclarationNameOfEnumOrNamespace(node) { + var parseNode = ts.getParseTreeNode(node); + if (parseNode) { + switch (parseNode.parent.kind) { + case 243 /* EnumDeclaration */: + case 244 /* ModuleDeclaration */: + return parseNode === parseNode.parent.name; + } + } + return false; + } + ts.isDeclarationNameOfEnumOrNamespace = isDeclarationNameOfEnumOrNamespace; + function getInitializedVariables(node) { + return ts.filter(node.declarations, isInitializedVariable); + } + ts.getInitializedVariables = getInitializedVariables; + function isInitializedVariable(node) { + return node.initializer !== undefined; + } + function isWatchSet(options) { + // Firefox has Object.prototype.watch + return options.watch && options.hasOwnProperty("watch"); + } + ts.isWatchSet = isWatchSet; + function closeFileWatcher(watcher) { + watcher.close(); + } + ts.closeFileWatcher = closeFileWatcher; + function getCheckFlags(symbol) { + return symbol.flags & 33554432 /* Transient */ ? symbol.checkFlags : 0; + } + ts.getCheckFlags = getCheckFlags; + function getDeclarationModifierFlagsFromSymbol(s) { + if (s.valueDeclaration) { + var flags = ts.getCombinedModifierFlags(s.valueDeclaration); + return s.parent && s.parent.flags & 32 /* Class */ ? flags : flags & ~28 /* AccessibilityModifier */; + } + if (getCheckFlags(s) & 6 /* Synthetic */) { + var checkFlags = s.checkFlags; + var accessModifier = checkFlags & 256 /* ContainsPrivate */ ? 8 /* Private */ : + checkFlags & 64 /* ContainsPublic */ ? 4 /* Public */ : + 16 /* Protected */; + var staticModifier = checkFlags & 512 /* ContainsStatic */ ? 32 /* Static */ : 0; + return accessModifier | staticModifier; + } + if (s.flags & 4194304 /* Prototype */) { + return 4 /* Public */ | 32 /* Static */; + } + return 0; + } + ts.getDeclarationModifierFlagsFromSymbol = getDeclarationModifierFlagsFromSymbol; + function skipAlias(symbol, checker) { + return symbol.flags & 2097152 /* Alias */ ? checker.getAliasedSymbol(symbol) : symbol; + } + ts.skipAlias = skipAlias; + /** See comment on `declareModuleMember` in `binder.ts`. */ + function getCombinedLocalAndExportSymbolFlags(symbol) { + return symbol.exportSymbol ? symbol.exportSymbol.flags | symbol.flags : symbol.flags; + } + ts.getCombinedLocalAndExportSymbolFlags = getCombinedLocalAndExportSymbolFlags; + function isWriteOnlyAccess(node) { + return accessKind(node) === 1 /* Write */; + } + ts.isWriteOnlyAccess = isWriteOnlyAccess; + function isWriteAccess(node) { + return accessKind(node) !== 0 /* Read */; + } + ts.isWriteAccess = isWriteAccess; + var AccessKind; + (function (AccessKind) { + /** Only reads from a variable. */ + AccessKind[AccessKind["Read"] = 0] = "Read"; + /** Only writes to a variable without using the result. E.g.: `x++;`. */ + AccessKind[AccessKind["Write"] = 1] = "Write"; + /** Writes to a variable and uses the result as an expression. E.g.: `f(x++);`. */ + AccessKind[AccessKind["ReadWrite"] = 2] = "ReadWrite"; + })(AccessKind || (AccessKind = {})); + function accessKind(node) { + var parent = node.parent; + if (!parent) + return 0 /* Read */; + switch (parent.kind) { + case 195 /* ParenthesizedExpression */: + return accessKind(parent); + case 203 /* PostfixUnaryExpression */: + case 202 /* PrefixUnaryExpression */: + var operator = parent.operator; + return operator === 44 /* PlusPlusToken */ || operator === 45 /* MinusMinusToken */ ? writeOrReadWrite() : 0 /* Read */; + case 204 /* BinaryExpression */: + var _a = parent, left = _a.left, operatorToken = _a.operatorToken; + return left === node && isAssignmentOperator(operatorToken.kind) ? + operatorToken.kind === 59 /* EqualsToken */ ? 1 /* Write */ : writeOrReadWrite() + : 0 /* Read */; + case 189 /* PropertyAccessExpression */: + return parent.name !== node ? 0 /* Read */ : accessKind(parent); + case 275 /* PropertyAssignment */: { + var parentAccess = accessKind(parent.parent); + // In `({ x: varname }) = { x: 1 }`, the left `x` is a read, the right `x` is a write. + return node === parent.name ? reverseAccessKind(parentAccess) : parentAccess; + } + case 276 /* ShorthandPropertyAssignment */: + // Assume it's the local variable being accessed, since we don't check public properties for --noUnusedLocals. + return node === parent.objectAssignmentInitializer ? 0 /* Read */ : accessKind(parent.parent); + case 187 /* ArrayLiteralExpression */: + return accessKind(parent); + default: + return 0 /* Read */; + } + function writeOrReadWrite() { + // If grandparent is not an ExpressionStatement, this is used as an expression in addition to having a side effect. + return parent.parent && skipParenthesesUp(parent.parent).kind === 221 /* ExpressionStatement */ ? 1 /* Write */ : 2 /* ReadWrite */; + } + } + function reverseAccessKind(a) { + switch (a) { + case 0 /* Read */: + return 1 /* Write */; + case 1 /* Write */: + return 0 /* Read */; + case 2 /* ReadWrite */: + return 2 /* ReadWrite */; + default: + return ts.Debug.assertNever(a); + } + } + function compareDataObjects(dst, src) { + if (!dst || !src || Object.keys(dst).length !== Object.keys(src).length) { + return false; + } + for (var e in dst) { + if (typeof dst[e] === "object") { + if (!compareDataObjects(dst[e], src[e])) { + return false; + } + } + else if (typeof dst[e] !== "function") { + if (dst[e] !== src[e]) { + return false; + } + } + } + return true; + } + ts.compareDataObjects = compareDataObjects; + /** + * clears already present map by calling onDeleteExistingValue callback before deleting that key/value + */ + function clearMap(map, onDeleteValue) { + // Remove all + map.forEach(onDeleteValue); + map.clear(); + } + ts.clearMap = clearMap; + /** + * Mutates the map with newMap such that keys in map will be same as newMap. + */ + function mutateMap(map, newMap, options) { + var createNewValue = options.createNewValue, onDeleteValue = options.onDeleteValue, onExistingValue = options.onExistingValue; + // Needs update + map.forEach(function (existingValue, key) { + var valueInNewMap = newMap.get(key); + // Not present any more in new map, remove it + if (valueInNewMap === undefined) { + map.delete(key); + onDeleteValue(existingValue, key); + } + // If present notify about existing values + else if (onExistingValue) { + onExistingValue(existingValue, valueInNewMap, key); + } + }); + // Add new values that are not already present + newMap.forEach(function (valueInNewMap, key) { + if (!map.has(key)) { + // New values + map.set(key, createNewValue(key, valueInNewMap)); + } + }); + } + ts.mutateMap = mutateMap; + /** Calls `callback` on `directory` and every ancestor directory it has, returning the first defined result. */ + function forEachAncestorDirectory(directory, callback) { + while (true) { + var result = callback(directory); + if (result !== undefined) { + return result; + } + var parentPath = ts.getDirectoryPath(directory); + if (parentPath === directory) { + return undefined; + } + directory = parentPath; + } + } + ts.forEachAncestorDirectory = forEachAncestorDirectory; + // Return true if the given type is the constructor type for an abstract class + function isAbstractConstructorType(type) { + return !!(getObjectFlags(type) & 16 /* Anonymous */) && !!type.symbol && isAbstractConstructorSymbol(type.symbol); + } + ts.isAbstractConstructorType = isAbstractConstructorType; + function isAbstractConstructorSymbol(symbol) { + if (symbol.flags & 32 /* Class */) { + var declaration = getClassLikeDeclarationOfSymbol(symbol); + return !!declaration && hasModifier(declaration, 128 /* Abstract */); + } + return false; + } + ts.isAbstractConstructorSymbol = isAbstractConstructorSymbol; + function getClassLikeDeclarationOfSymbol(symbol) { + return ts.find(symbol.declarations, ts.isClassLike); + } + ts.getClassLikeDeclarationOfSymbol = getClassLikeDeclarationOfSymbol; + function getObjectFlags(type) { + return type.flags & 524288 /* Object */ ? type.objectFlags : 0; + } + ts.getObjectFlags = getObjectFlags; + function typeHasCallOrConstructSignatures(type, checker) { + return checker.getSignaturesOfType(type, 0 /* Call */).length !== 0 || checker.getSignaturesOfType(type, 1 /* Construct */).length !== 0; + } + ts.typeHasCallOrConstructSignatures = typeHasCallOrConstructSignatures; + function forSomeAncestorDirectory(directory, callback) { + return !!forEachAncestorDirectory(directory, function (d) { return callback(d) ? true : undefined; }); + } + ts.forSomeAncestorDirectory = forSomeAncestorDirectory; + function isUMDExportSymbol(symbol) { + return !!symbol && !!symbol.declarations && !!symbol.declarations[0] && ts.isNamespaceExportDeclaration(symbol.declarations[0]); + } + ts.isUMDExportSymbol = isUMDExportSymbol; + function showModuleSpecifier(_a) { + var moduleSpecifier = _a.moduleSpecifier; + return ts.isStringLiteral(moduleSpecifier) ? moduleSpecifier.text : getTextOfNode(moduleSpecifier); + } + ts.showModuleSpecifier = showModuleSpecifier; + function getLastChild(node) { + var lastChild; + ts.forEachChild(node, function (child) { + if (nodeIsPresent(child)) + lastChild = child; + }, function (children) { + // As an optimization, jump straight to the end of the list. + for (var i = children.length - 1; i >= 0; i--) { + if (nodeIsPresent(children[i])) { + lastChild = children[i]; + break; + } + } + }); + return lastChild; + } + ts.getLastChild = getLastChild; + function addToSeen(seen, key, value) { + if (value === void 0) { value = true; } + key = String(key); + if (seen.has(key)) { + return false; + } + seen.set(key, value); + return true; + } + ts.addToSeen = addToSeen; + function isObjectTypeDeclaration(node) { + return ts.isClassLike(node) || ts.isInterfaceDeclaration(node) || ts.isTypeLiteralNode(node); + } + ts.isObjectTypeDeclaration = isObjectTypeDeclaration; + function isTypeNodeKind(kind) { + return (kind >= 163 /* FirstTypeNode */ && kind <= 183 /* LastTypeNode */) + || kind === 120 /* AnyKeyword */ + || kind === 143 /* UnknownKeyword */ + || kind === 135 /* NumberKeyword */ + || kind === 146 /* BigIntKeyword */ + || kind === 136 /* ObjectKeyword */ + || kind === 123 /* BooleanKeyword */ + || kind === 138 /* StringKeyword */ + || kind === 139 /* SymbolKeyword */ + || kind === 100 /* ThisKeyword */ + || kind === 106 /* VoidKeyword */ + || kind === 141 /* UndefinedKeyword */ + || kind === 96 /* NullKeyword */ + || kind === 132 /* NeverKeyword */ + || kind === 211 /* ExpressionWithTypeArguments */ + || kind === 284 /* JSDocAllType */ + || kind === 285 /* JSDocUnknownType */ + || kind === 286 /* JSDocNullableType */ + || kind === 287 /* JSDocNonNullableType */ + || kind === 288 /* JSDocOptionalType */ + || kind === 289 /* JSDocFunctionType */ + || kind === 290 /* JSDocVariadicType */; + } + ts.isTypeNodeKind = isTypeNodeKind; +})(ts || (ts = {})); +(function (ts) { + function getDefaultLibFileName(options) { + switch (options.target) { + case 6 /* ESNext */: + return "lib.esnext.full.d.ts"; + case 5 /* ES2018 */: + return "lib.es2018.full.d.ts"; + case 4 /* ES2017 */: + return "lib.es2017.full.d.ts"; + case 3 /* ES2016 */: + return "lib.es2016.full.d.ts"; + case 2 /* ES2015 */: + return "lib.es6.d.ts"; // We don't use lib.es2015.full.d.ts due to breaking change. + default: + return "lib.d.ts"; + } + } + ts.getDefaultLibFileName = getDefaultLibFileName; + function textSpanEnd(span) { + return span.start + span.length; + } + ts.textSpanEnd = textSpanEnd; + function textSpanIsEmpty(span) { + return span.length === 0; + } + ts.textSpanIsEmpty = textSpanIsEmpty; + function textSpanContainsPosition(span, position) { + return position >= span.start && position < textSpanEnd(span); + } + ts.textSpanContainsPosition = textSpanContainsPosition; + /* @internal */ + function textRangeContainsPositionInclusive(span, position) { + return position >= span.pos && position <= span.end; + } + ts.textRangeContainsPositionInclusive = textRangeContainsPositionInclusive; + // Returns true if 'span' contains 'other'. + function textSpanContainsTextSpan(span, other) { + return other.start >= span.start && textSpanEnd(other) <= textSpanEnd(span); + } + ts.textSpanContainsTextSpan = textSpanContainsTextSpan; + function textSpanOverlapsWith(span, other) { + return textSpanOverlap(span, other) !== undefined; + } + ts.textSpanOverlapsWith = textSpanOverlapsWith; + function textSpanOverlap(span1, span2) { + var overlap = textSpanIntersection(span1, span2); + return overlap && overlap.length === 0 ? undefined : overlap; + } + ts.textSpanOverlap = textSpanOverlap; + function textSpanIntersectsWithTextSpan(span, other) { + return decodedTextSpanIntersectsWith(span.start, span.length, other.start, other.length); + } + ts.textSpanIntersectsWithTextSpan = textSpanIntersectsWithTextSpan; + function textSpanIntersectsWith(span, start, length) { + return decodedTextSpanIntersectsWith(span.start, span.length, start, length); + } + ts.textSpanIntersectsWith = textSpanIntersectsWith; + function decodedTextSpanIntersectsWith(start1, length1, start2, length2) { + var end1 = start1 + length1; + var end2 = start2 + length2; + return start2 <= end1 && end2 >= start1; + } + ts.decodedTextSpanIntersectsWith = decodedTextSpanIntersectsWith; + function textSpanIntersectsWithPosition(span, position) { + return position <= textSpanEnd(span) && position >= span.start; + } + ts.textSpanIntersectsWithPosition = textSpanIntersectsWithPosition; + function textSpanIntersection(span1, span2) { + var start = Math.max(span1.start, span2.start); + var end = Math.min(textSpanEnd(span1), textSpanEnd(span2)); + return start <= end ? createTextSpanFromBounds(start, end) : undefined; + } + ts.textSpanIntersection = textSpanIntersection; + function createTextSpan(start, length) { + if (start < 0) { + throw new Error("start < 0"); + } + if (length < 0) { + throw new Error("length < 0"); + } + return { start: start, length: length }; + } + ts.createTextSpan = createTextSpan; + function createTextSpanFromBounds(start, end) { + return createTextSpan(start, end - start); + } + ts.createTextSpanFromBounds = createTextSpanFromBounds; + function textChangeRangeNewSpan(range) { + return createTextSpan(range.span.start, range.newLength); + } + ts.textChangeRangeNewSpan = textChangeRangeNewSpan; + function textChangeRangeIsUnchanged(range) { + return textSpanIsEmpty(range.span) && range.newLength === 0; + } + ts.textChangeRangeIsUnchanged = textChangeRangeIsUnchanged; + function createTextChangeRange(span, newLength) { + if (newLength < 0) { + throw new Error("newLength < 0"); + } + return { span: span, newLength: newLength }; + } + ts.createTextChangeRange = createTextChangeRange; + ts.unchangedTextChangeRange = createTextChangeRange(createTextSpan(0, 0), 0); + /** + * Called to merge all the changes that occurred across several versions of a script snapshot + * into a single change. i.e. if a user keeps making successive edits to a script we will + * have a text change from V1 to V2, V2 to V3, ..., Vn. + * + * This function will then merge those changes into a single change range valid between V1 and + * Vn. + */ + function collapseTextChangeRangesAcrossMultipleVersions(changes) { + if (changes.length === 0) { + return ts.unchangedTextChangeRange; + } + if (changes.length === 1) { + return changes[0]; + } + // We change from talking about { { oldStart, oldLength }, newLength } to { oldStart, oldEnd, newEnd } + // as it makes things much easier to reason about. + var change0 = changes[0]; + var oldStartN = change0.span.start; + var oldEndN = textSpanEnd(change0.span); + var newEndN = oldStartN + change0.newLength; + for (var i = 1; i < changes.length; i++) { + var nextChange = changes[i]; + // Consider the following case: + // i.e. two edits. The first represents the text change range { { 10, 50 }, 30 }. i.e. The span starting + // at 10, with length 50 is reduced to length 30. The second represents the text change range { { 30, 30 }, 40 }. + // i.e. the span starting at 30 with length 30 is increased to length 40. + // + // 0 10 20 30 40 50 60 70 80 90 100 + // ------------------------------------------------------------------------------------------------------- + // | / + // | /---- + // T1 | /---- + // | /---- + // | /---- + // ------------------------------------------------------------------------------------------------------- + // | \ + // | \ + // T2 | \ + // | \ + // | \ + // ------------------------------------------------------------------------------------------------------- + // + // Merging these turns out to not be too difficult. First, determining the new start of the change is trivial + // it's just the min of the old and new starts. i.e.: + // + // 0 10 20 30 40 50 60 70 80 90 100 + // ------------------------------------------------------------*------------------------------------------ + // | / + // | /---- + // T1 | /---- + // | /---- + // | /---- + // ----------------------------------------$-------------------$------------------------------------------ + // . | \ + // . | \ + // T2 . | \ + // . | \ + // . | \ + // ----------------------------------------------------------------------*-------------------------------- + // + // (Note the dots represent the newly inferred start. + // Determining the new and old end is also pretty simple. Basically it boils down to paying attention to the + // absolute positions at the asterisks, and the relative change between the dollar signs. Basically, we see + // which if the two $'s precedes the other, and we move that one forward until they line up. in this case that + // means: + // + // 0 10 20 30 40 50 60 70 80 90 100 + // --------------------------------------------------------------------------------*---------------------- + // | / + // | /---- + // T1 | /---- + // | /---- + // | /---- + // ------------------------------------------------------------$------------------------------------------ + // . | \ + // . | \ + // T2 . | \ + // . | \ + // . | \ + // ----------------------------------------------------------------------*-------------------------------- + // + // In other words (in this case), we're recognizing that the second edit happened after where the first edit + // ended with a delta of 20 characters (60 - 40). Thus, if we go back in time to where the first edit started + // that's the same as if we started at char 80 instead of 60. + // + // As it so happens, the same logic applies if the second edit precedes the first edit. In that case rather + // than pushing the first edit forward to match the second, we'll push the second edit forward to match the + // first. + // + // In this case that means we have { oldStart: 10, oldEnd: 80, newEnd: 70 } or, in TextChangeRange + // semantics: { { start: 10, length: 70 }, newLength: 60 } + // + // The math then works out as follows. + // If we have { oldStart1, oldEnd1, newEnd1 } and { oldStart2, oldEnd2, newEnd2 } then we can compute the + // final result like so: + // + // { + // oldStart3: Min(oldStart1, oldStart2), + // oldEnd3: Max(oldEnd1, oldEnd1 + (oldEnd2 - newEnd1)), + // newEnd3: Max(newEnd2, newEnd2 + (newEnd1 - oldEnd2)) + // } + var oldStart1 = oldStartN; + var oldEnd1 = oldEndN; + var newEnd1 = newEndN; + var oldStart2 = nextChange.span.start; + var oldEnd2 = textSpanEnd(nextChange.span); + var newEnd2 = oldStart2 + nextChange.newLength; + oldStartN = Math.min(oldStart1, oldStart2); + oldEndN = Math.max(oldEnd1, oldEnd1 + (oldEnd2 - newEnd1)); + newEndN = Math.max(newEnd2, newEnd2 + (newEnd1 - oldEnd2)); + } + return createTextChangeRange(createTextSpanFromBounds(oldStartN, oldEndN), /*newLength*/ newEndN - oldStartN); + } + ts.collapseTextChangeRangesAcrossMultipleVersions = collapseTextChangeRangesAcrossMultipleVersions; + function getTypeParameterOwner(d) { + if (d && d.kind === 150 /* TypeParameter */) { + for (var current = d; current; current = current.parent) { + if (ts.isFunctionLike(current) || ts.isClassLike(current) || current.kind === 241 /* InterfaceDeclaration */) { + return current; + } + } + } + } + ts.getTypeParameterOwner = getTypeParameterOwner; + function isParameterPropertyDeclaration(node) { + return ts.hasModifier(node, 92 /* ParameterPropertyModifier */) && node.parent.kind === 157 /* Constructor */; + } + ts.isParameterPropertyDeclaration = isParameterPropertyDeclaration; + function isEmptyBindingPattern(node) { + if (ts.isBindingPattern(node)) { + return ts.every(node.elements, isEmptyBindingElement); + } + return false; + } + ts.isEmptyBindingPattern = isEmptyBindingPattern; + function isEmptyBindingElement(node) { + if (ts.isOmittedExpression(node)) { + return true; + } + return isEmptyBindingPattern(node.name); + } + ts.isEmptyBindingElement = isEmptyBindingElement; + function walkUpBindingElementsAndPatterns(binding) { + var node = binding.parent; + while (ts.isBindingElement(node.parent)) { + node = node.parent.parent; + } + return node.parent; + } + ts.walkUpBindingElementsAndPatterns = walkUpBindingElementsAndPatterns; + function getCombinedFlags(node, getFlags) { + if (ts.isBindingElement(node)) { + node = walkUpBindingElementsAndPatterns(node); + } + var flags = getFlags(node); + if (node.kind === 237 /* VariableDeclaration */) { + node = node.parent; + } + if (node && node.kind === 238 /* VariableDeclarationList */) { + flags |= getFlags(node); + node = node.parent; + } + if (node && node.kind === 219 /* VariableStatement */) { + flags |= getFlags(node); + } + return flags; + } + function getCombinedModifierFlags(node) { + return getCombinedFlags(node, ts.getModifierFlags); + } + ts.getCombinedModifierFlags = getCombinedModifierFlags; + // Returns the node flags for this node and all relevant parent nodes. This is done so that + // nodes like variable declarations and binding elements can returned a view of their flags + // that includes the modifiers from their container. i.e. flags like export/declare aren't + // stored on the variable declaration directly, but on the containing variable statement + // (if it has one). Similarly, flags for let/const are store on the variable declaration + // list. By calling this function, all those flags are combined so that the client can treat + // the node as if it actually had those flags. + function getCombinedNodeFlags(node) { + return getCombinedFlags(node, function (n) { return n.flags; }); + } + ts.getCombinedNodeFlags = getCombinedNodeFlags; + /** + * Checks to see if the locale is in the appropriate format, + * and if it is, attempts to set the appropriate language. + */ + function validateLocaleAndSetLanguage(locale, sys, errors) { + var matchResult = /^([a-z]+)([_\-]([a-z]+))?$/.exec(locale.toLowerCase()); + if (!matchResult) { + if (errors) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1, "en", "ja-jp")); + } + return; + } + var language = matchResult[1]; + var territory = matchResult[3]; + // First try the entire locale, then fall back to just language if that's all we have. + // Either ways do not fail, and fallback to the English diagnostic strings. + if (!trySetLanguageAndTerritory(language, territory, errors)) { + trySetLanguageAndTerritory(language, /*territory*/ undefined, errors); + } + // Set the UI locale for string collation + ts.setUILocale(locale); + function trySetLanguageAndTerritory(language, territory, errors) { + var compilerFilePath = ts.normalizePath(sys.getExecutingFilePath()); + var containingDirectoryPath = ts.getDirectoryPath(compilerFilePath); + var filePath = ts.combinePaths(containingDirectoryPath, language); + if (territory) { + filePath = filePath + "-" + territory; + } + filePath = sys.resolvePath(ts.combinePaths(filePath, "diagnosticMessages.generated.json")); + if (!sys.fileExists(filePath)) { + return false; + } + // TODO: Add codePage support for readFile? + var fileContents = ""; + try { + fileContents = sys.readFile(filePath); + } + catch (e) { + if (errors) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unable_to_open_file_0, filePath)); + } + return false; + } + try { + // tslint:disable-next-line no-unnecessary-qualifier (making clear this is a global mutation!) + ts.localizedDiagnosticMessages = JSON.parse(fileContents); + } + catch (_a) { + if (errors) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Corrupted_locale_file_0, filePath)); + } + return false; + } + return true; + } + } + ts.validateLocaleAndSetLanguage = validateLocaleAndSetLanguage; + function getOriginalNode(node, nodeTest) { + if (node) { + while (node.original !== undefined) { + node = node.original; + } + } + return !nodeTest || nodeTest(node) ? node : undefined; + } + ts.getOriginalNode = getOriginalNode; + /** + * Gets a value indicating whether a node originated in the parse tree. + * + * @param node The node to test. + */ + function isParseTreeNode(node) { + return (node.flags & 8 /* Synthesized */) === 0; + } + ts.isParseTreeNode = isParseTreeNode; + function getParseTreeNode(node, nodeTest) { + if (node === undefined || isParseTreeNode(node)) { + return node; + } + node = getOriginalNode(node); + if (isParseTreeNode(node) && (!nodeTest || nodeTest(node))) { + return node; + } + return undefined; + } + ts.getParseTreeNode = getParseTreeNode; + /** Add an extra underscore to identifiers that start with two underscores to avoid issues with magic names like '__proto__' */ + function escapeLeadingUnderscores(identifier) { + return (identifier.length >= 2 && identifier.charCodeAt(0) === 95 /* _ */ && identifier.charCodeAt(1) === 95 /* _ */ ? "_" + identifier : identifier); + } + ts.escapeLeadingUnderscores = escapeLeadingUnderscores; + /** + * Remove extra underscore from escaped identifier text content. + * + * @param identifier The escaped identifier text. + * @returns The unescaped identifier text. + */ + function unescapeLeadingUnderscores(identifier) { + var id = identifier; + return id.length >= 3 && id.charCodeAt(0) === 95 /* _ */ && id.charCodeAt(1) === 95 /* _ */ && id.charCodeAt(2) === 95 /* _ */ ? id.substr(1) : id; + } + ts.unescapeLeadingUnderscores = unescapeLeadingUnderscores; + function idText(identifier) { + return unescapeLeadingUnderscores(identifier.escapedText); + } + ts.idText = idText; + function symbolName(symbol) { + return unescapeLeadingUnderscores(symbol.escapedName); + } + ts.symbolName = symbolName; + /** + * A JSDocTypedef tag has an _optional_ name field - if a name is not directly present, we should + * attempt to draw the name from the node the declaration is on (as that declaration is what its' symbol + * will be merged with) + */ + function nameForNamelessJSDocTypedef(declaration) { + var hostNode = declaration.parent.parent; + if (!hostNode) { + return undefined; + } + // Covers classes, functions - any named declaration host node + if (ts.isDeclaration(hostNode)) { + return getDeclarationIdentifier(hostNode); + } + // Covers remaining cases (returning undefined if none match). + switch (hostNode.kind) { + case 219 /* VariableStatement */: + if (hostNode.declarationList && hostNode.declarationList.declarations[0]) { + return getDeclarationIdentifier(hostNode.declarationList.declarations[0]); + } + break; + case 221 /* ExpressionStatement */: + var expr = hostNode.expression; + switch (expr.kind) { + case 189 /* PropertyAccessExpression */: + return expr.name; + case 190 /* ElementAccessExpression */: + var arg = expr.argumentExpression; + if (ts.isIdentifier(arg)) { + return arg; + } + } + break; + case 195 /* ParenthesizedExpression */: { + return getDeclarationIdentifier(hostNode.expression); + } + case 233 /* LabeledStatement */: { + if (ts.isDeclaration(hostNode.statement) || ts.isExpression(hostNode.statement)) { + return getDeclarationIdentifier(hostNode.statement); + } + break; + } + } + } + function getDeclarationIdentifier(node) { + var name = getNameOfDeclaration(node); + return name && ts.isIdentifier(name) ? name : undefined; + } + function getNameOfJSDocTypedef(declaration) { + return declaration.name || nameForNamelessJSDocTypedef(declaration); + } + ts.getNameOfJSDocTypedef = getNameOfJSDocTypedef; + /** @internal */ + function isNamedDeclaration(node) { + return !!node.name; // A 'name' property should always be a DeclarationName. + } + ts.isNamedDeclaration = isNamedDeclaration; + /** @internal */ + function getNonAssignedNameOfDeclaration(declaration) { + switch (declaration.kind) { + case 72 /* Identifier */: + return declaration; + case 305 /* JSDocPropertyTag */: + case 299 /* JSDocParameterTag */: { + var name = declaration.name; + if (name.kind === 148 /* QualifiedName */) { + return name.right; + } + break; + } + case 191 /* CallExpression */: + case 204 /* BinaryExpression */: { + var expr = declaration; + switch (ts.getAssignmentDeclarationKind(expr)) { + case 1 /* ExportsProperty */: + case 4 /* ThisProperty */: + case 5 /* Property */: + case 3 /* PrototypeProperty */: + return expr.left.name; + case 7 /* ObjectDefinePropertyValue */: + case 8 /* ObjectDefinePropertyExports */: + case 9 /* ObjectDefinePrototypeProperty */: + return expr.arguments[1]; + default: + return undefined; + } + } + case 304 /* JSDocTypedefTag */: + return getNameOfJSDocTypedef(declaration); + case 254 /* ExportAssignment */: { + var expression = declaration.expression; + return ts.isIdentifier(expression) ? expression : undefined; + } + } + return declaration.name; + } + ts.getNonAssignedNameOfDeclaration = getNonAssignedNameOfDeclaration; + function getNameOfDeclaration(declaration) { + if (declaration === undefined) + return undefined; + return getNonAssignedNameOfDeclaration(declaration) || + (ts.isFunctionExpression(declaration) || ts.isClassExpression(declaration) ? getAssignedName(declaration) : undefined); + } + ts.getNameOfDeclaration = getNameOfDeclaration; + function getAssignedName(node) { + if (!node.parent) { + return undefined; + } + else if (ts.isPropertyAssignment(node.parent) || ts.isBindingElement(node.parent)) { + return node.parent.name; + } + else if (ts.isBinaryExpression(node.parent) && node === node.parent.right) { + if (ts.isIdentifier(node.parent.left)) { + return node.parent.left; + } + else if (ts.isPropertyAccessExpression(node.parent.left)) { + return node.parent.left.name; + } + } + } + /** + * Gets the JSDoc parameter tags for the node if present. + * + * @remarks Returns any JSDoc param tag whose name matches the provided + * parameter, whether a param tag on a containing function + * expression, or a param tag on a variable declaration whose + * initializer is the containing function. The tags closest to the + * node are returned first, so in the previous example, the param + * tag on the containing function expression would be first. + * + * For binding patterns, parameter tags are matched by position. + */ + function getJSDocParameterTags(param) { + if (param.name) { + if (ts.isIdentifier(param.name)) { + var name_1 = param.name.escapedText; + return getJSDocTags(param.parent).filter(function (tag) { return ts.isJSDocParameterTag(tag) && ts.isIdentifier(tag.name) && tag.name.escapedText === name_1; }); + } + else { + var i = param.parent.parameters.indexOf(param); + ts.Debug.assert(i > -1, "Parameters should always be in their parents' parameter list"); + var paramTags = getJSDocTags(param.parent).filter(ts.isJSDocParameterTag); + if (i < paramTags.length) { + return [paramTags[i]]; + } + } + } + // return empty array for: out-of-order binding patterns and JSDoc function syntax, which has un-named parameters + return ts.emptyArray; + } + ts.getJSDocParameterTags = getJSDocParameterTags; + /** + * Gets the JSDoc type parameter tags for the node if present. + * + * @remarks Returns any JSDoc template tag whose names match the provided + * parameter, whether a template tag on a containing function + * expression, or a template tag on a variable declaration whose + * initializer is the containing function. The tags closest to the + * node are returned first, so in the previous example, the template + * tag on the containing function expression would be first. + */ + function getJSDocTypeParameterTags(param) { + var name = param.name.escapedText; + return getJSDocTags(param.parent).filter(function (tag) { + return ts.isJSDocTemplateTag(tag) && tag.typeParameters.some(function (tp) { return tp.name.escapedText === name; }); + }); + } + ts.getJSDocTypeParameterTags = getJSDocTypeParameterTags; + /** + * Return true if the node has JSDoc parameter tags. + * + * @remarks Includes parameter tags that are not directly on the node, + * for example on a variable declaration whose initializer is a function expression. + */ + function hasJSDocParameterTags(node) { + return !!getFirstJSDocTag(node, ts.isJSDocParameterTag); + } + ts.hasJSDocParameterTags = hasJSDocParameterTags; + /** Gets the JSDoc augments tag for the node if present */ + function getJSDocAugmentsTag(node) { + return getFirstJSDocTag(node, ts.isJSDocAugmentsTag); + } + ts.getJSDocAugmentsTag = getJSDocAugmentsTag; + /** Gets the JSDoc class tag for the node if present */ + function getJSDocClassTag(node) { + return getFirstJSDocTag(node, ts.isJSDocClassTag); + } + ts.getJSDocClassTag = getJSDocClassTag; + /** Gets the JSDoc enum tag for the node if present */ + function getJSDocEnumTag(node) { + return getFirstJSDocTag(node, ts.isJSDocEnumTag); + } + ts.getJSDocEnumTag = getJSDocEnumTag; + /** Gets the JSDoc this tag for the node if present */ + function getJSDocThisTag(node) { + return getFirstJSDocTag(node, ts.isJSDocThisTag); + } + ts.getJSDocThisTag = getJSDocThisTag; + /** Gets the JSDoc return tag for the node if present */ + function getJSDocReturnTag(node) { + return getFirstJSDocTag(node, ts.isJSDocReturnTag); + } + ts.getJSDocReturnTag = getJSDocReturnTag; + /** Gets the JSDoc template tag for the node if present */ + function getJSDocTemplateTag(node) { + return getFirstJSDocTag(node, ts.isJSDocTemplateTag); + } + ts.getJSDocTemplateTag = getJSDocTemplateTag; + /** Gets the JSDoc type tag for the node if present and valid */ + function getJSDocTypeTag(node) { + // We should have already issued an error if there were multiple type jsdocs, so just use the first one. + var tag = getFirstJSDocTag(node, ts.isJSDocTypeTag); + if (tag && tag.typeExpression && tag.typeExpression.type) { + return tag; + } + return undefined; + } + ts.getJSDocTypeTag = getJSDocTypeTag; + /** + * Gets the type node for the node if provided via JSDoc. + * + * @remarks The search includes any JSDoc param tag that relates + * to the provided parameter, for example a type tag on the + * parameter itself, or a param tag on a containing function + * expression, or a param tag on a variable declaration whose + * initializer is the containing function. The tags closest to the + * node are examined first, so in the previous example, the type + * tag directly on the node would be returned. + */ + function getJSDocType(node) { + var tag = getFirstJSDocTag(node, ts.isJSDocTypeTag); + if (!tag && ts.isParameter(node)) { + tag = ts.find(getJSDocParameterTags(node), function (tag) { return !!tag.typeExpression; }); + } + return tag && tag.typeExpression && tag.typeExpression.type; + } + ts.getJSDocType = getJSDocType; + /** + * Gets the return type node for the node if provided via JSDoc return tag or type tag. + * + * @remarks `getJSDocReturnTag` just gets the whole JSDoc tag. This function + * gets the type from inside the braces, after the fat arrow, etc. + */ + function getJSDocReturnType(node) { + var returnTag = getJSDocReturnTag(node); + if (returnTag && returnTag.typeExpression) { + return returnTag.typeExpression.type; + } + var typeTag = getJSDocTypeTag(node); + if (typeTag && typeTag.typeExpression) { + var type = typeTag.typeExpression.type; + if (ts.isTypeLiteralNode(type)) { + var sig = ts.find(type.members, ts.isCallSignatureDeclaration); + return sig && sig.type; + } + if (ts.isFunctionTypeNode(type)) { + return type.type; + } + } + } + ts.getJSDocReturnType = getJSDocReturnType; + /** Get all JSDoc tags related to a node, including those on parent nodes. */ + function getJSDocTags(node) { + var tags = node.jsDocCache; + // If cache is 'null', that means we did the work of searching for JSDoc tags and came up with nothing. + if (tags === undefined) { + var comments = ts.getJSDocCommentsAndTags(node); + ts.Debug.assert(comments.length < 2 || comments[0] !== comments[1]); + node.jsDocCache = tags = ts.flatMap(comments, function (j) { return ts.isJSDoc(j) ? j.tags : j; }); + } + return tags; + } + ts.getJSDocTags = getJSDocTags; + /** Get the first JSDoc tag of a specified kind, or undefined if not present. */ + function getFirstJSDocTag(node, predicate) { + return ts.find(getJSDocTags(node), predicate); + } + /** Gets all JSDoc tags of a specified kind, or undefined if not present. */ + function getAllJSDocTagsOfKind(node, kind) { + return getJSDocTags(node).filter(function (doc) { return doc.kind === kind; }); + } + ts.getAllJSDocTagsOfKind = getAllJSDocTagsOfKind; + /** + * Gets the effective type parameters. If the node was parsed in a + * JavaScript file, gets the type parameters from the `@template` tag from JSDoc. + */ + function getEffectiveTypeParameterDeclarations(node) { + if (ts.isJSDocSignature(node)) { + return ts.emptyArray; + } + if (ts.isJSDocTypeAlias(node)) { + ts.Debug.assert(node.parent.kind === 291 /* JSDocComment */); + return ts.flatMap(node.parent.tags, function (tag) { return ts.isJSDocTemplateTag(tag) ? tag.typeParameters : undefined; }); + } + if (node.typeParameters) { + return node.typeParameters; + } + if (ts.isInJSFile(node)) { + var decls = ts.getJSDocTypeParameterDeclarations(node); + if (decls.length) { + return decls; + } + var typeTag = getJSDocType(node); + if (typeTag && ts.isFunctionTypeNode(typeTag) && typeTag.typeParameters) { + return typeTag.typeParameters; + } + } + return ts.emptyArray; + } + ts.getEffectiveTypeParameterDeclarations = getEffectiveTypeParameterDeclarations; + function getEffectiveConstraintOfTypeParameter(node) { + return node.constraint ? node.constraint + : ts.isJSDocTemplateTag(node.parent) && node === node.parent.typeParameters[0] + ? node.parent.constraint + : undefined; + } + ts.getEffectiveConstraintOfTypeParameter = getEffectiveConstraintOfTypeParameter; +})(ts || (ts = {})); +// Simple node tests of the form `node.kind === SyntaxKind.Foo`. +(function (ts) { + // Literals + function isNumericLiteral(node) { + return node.kind === 8 /* NumericLiteral */; + } + ts.isNumericLiteral = isNumericLiteral; + function isBigIntLiteral(node) { + return node.kind === 9 /* BigIntLiteral */; + } + ts.isBigIntLiteral = isBigIntLiteral; + function isStringLiteral(node) { + return node.kind === 10 /* StringLiteral */; + } + ts.isStringLiteral = isStringLiteral; + function isJsxText(node) { + return node.kind === 11 /* JsxText */; + } + ts.isJsxText = isJsxText; + function isRegularExpressionLiteral(node) { + return node.kind === 13 /* RegularExpressionLiteral */; + } + ts.isRegularExpressionLiteral = isRegularExpressionLiteral; + function isNoSubstitutionTemplateLiteral(node) { + return node.kind === 14 /* NoSubstitutionTemplateLiteral */; + } + ts.isNoSubstitutionTemplateLiteral = isNoSubstitutionTemplateLiteral; + // Pseudo-literals + function isTemplateHead(node) { + return node.kind === 15 /* TemplateHead */; + } + ts.isTemplateHead = isTemplateHead; + function isTemplateMiddle(node) { + return node.kind === 16 /* TemplateMiddle */; + } + ts.isTemplateMiddle = isTemplateMiddle; + function isTemplateTail(node) { + return node.kind === 17 /* TemplateTail */; + } + ts.isTemplateTail = isTemplateTail; + function isIdentifier(node) { + return node.kind === 72 /* Identifier */; + } + ts.isIdentifier = isIdentifier; + // Names + function isQualifiedName(node) { + return node.kind === 148 /* QualifiedName */; + } + ts.isQualifiedName = isQualifiedName; + function isComputedPropertyName(node) { + return node.kind === 149 /* ComputedPropertyName */; + } + ts.isComputedPropertyName = isComputedPropertyName; + // Signature elements + function isTypeParameterDeclaration(node) { + return node.kind === 150 /* TypeParameter */; + } + ts.isTypeParameterDeclaration = isTypeParameterDeclaration; + function isParameter(node) { + return node.kind === 151 /* Parameter */; + } + ts.isParameter = isParameter; + function isDecorator(node) { + return node.kind === 152 /* Decorator */; + } + ts.isDecorator = isDecorator; + // TypeMember + function isPropertySignature(node) { + return node.kind === 153 /* PropertySignature */; + } + ts.isPropertySignature = isPropertySignature; + function isPropertyDeclaration(node) { + return node.kind === 154 /* PropertyDeclaration */; + } + ts.isPropertyDeclaration = isPropertyDeclaration; + function isMethodSignature(node) { + return node.kind === 155 /* MethodSignature */; + } + ts.isMethodSignature = isMethodSignature; + function isMethodDeclaration(node) { + return node.kind === 156 /* MethodDeclaration */; + } + ts.isMethodDeclaration = isMethodDeclaration; + function isConstructorDeclaration(node) { + return node.kind === 157 /* Constructor */; + } + ts.isConstructorDeclaration = isConstructorDeclaration; + function isGetAccessorDeclaration(node) { + return node.kind === 158 /* GetAccessor */; + } + ts.isGetAccessorDeclaration = isGetAccessorDeclaration; + function isSetAccessorDeclaration(node) { + return node.kind === 159 /* SetAccessor */; + } + ts.isSetAccessorDeclaration = isSetAccessorDeclaration; + function isCallSignatureDeclaration(node) { + return node.kind === 160 /* CallSignature */; + } + ts.isCallSignatureDeclaration = isCallSignatureDeclaration; + function isConstructSignatureDeclaration(node) { + return node.kind === 161 /* ConstructSignature */; + } + ts.isConstructSignatureDeclaration = isConstructSignatureDeclaration; + function isIndexSignatureDeclaration(node) { + return node.kind === 162 /* IndexSignature */; + } + ts.isIndexSignatureDeclaration = isIndexSignatureDeclaration; + /* @internal */ + function isGetOrSetAccessorDeclaration(node) { + return node.kind === 159 /* SetAccessor */ || node.kind === 158 /* GetAccessor */; + } + ts.isGetOrSetAccessorDeclaration = isGetOrSetAccessorDeclaration; + // Type + function isTypePredicateNode(node) { + return node.kind === 163 /* TypePredicate */; + } + ts.isTypePredicateNode = isTypePredicateNode; + function isTypeReferenceNode(node) { + return node.kind === 164 /* TypeReference */; + } + ts.isTypeReferenceNode = isTypeReferenceNode; + function isFunctionTypeNode(node) { + return node.kind === 165 /* FunctionType */; + } + ts.isFunctionTypeNode = isFunctionTypeNode; + function isConstructorTypeNode(node) { + return node.kind === 166 /* ConstructorType */; + } + ts.isConstructorTypeNode = isConstructorTypeNode; + function isTypeQueryNode(node) { + return node.kind === 167 /* TypeQuery */; + } + ts.isTypeQueryNode = isTypeQueryNode; + function isTypeLiteralNode(node) { + return node.kind === 168 /* TypeLiteral */; + } + ts.isTypeLiteralNode = isTypeLiteralNode; + function isArrayTypeNode(node) { + return node.kind === 169 /* ArrayType */; + } + ts.isArrayTypeNode = isArrayTypeNode; + function isTupleTypeNode(node) { + return node.kind === 170 /* TupleType */; + } + ts.isTupleTypeNode = isTupleTypeNode; + function isUnionTypeNode(node) { + return node.kind === 173 /* UnionType */; + } + ts.isUnionTypeNode = isUnionTypeNode; + function isIntersectionTypeNode(node) { + return node.kind === 174 /* IntersectionType */; + } + ts.isIntersectionTypeNode = isIntersectionTypeNode; + function isConditionalTypeNode(node) { + return node.kind === 175 /* ConditionalType */; + } + ts.isConditionalTypeNode = isConditionalTypeNode; + function isInferTypeNode(node) { + return node.kind === 176 /* InferType */; + } + ts.isInferTypeNode = isInferTypeNode; + function isParenthesizedTypeNode(node) { + return node.kind === 177 /* ParenthesizedType */; + } + ts.isParenthesizedTypeNode = isParenthesizedTypeNode; + function isThisTypeNode(node) { + return node.kind === 178 /* ThisType */; + } + ts.isThisTypeNode = isThisTypeNode; + function isTypeOperatorNode(node) { + return node.kind === 179 /* TypeOperator */; + } + ts.isTypeOperatorNode = isTypeOperatorNode; + function isIndexedAccessTypeNode(node) { + return node.kind === 180 /* IndexedAccessType */; + } + ts.isIndexedAccessTypeNode = isIndexedAccessTypeNode; + function isMappedTypeNode(node) { + return node.kind === 181 /* MappedType */; + } + ts.isMappedTypeNode = isMappedTypeNode; + function isLiteralTypeNode(node) { + return node.kind === 182 /* LiteralType */; + } + ts.isLiteralTypeNode = isLiteralTypeNode; + function isImportTypeNode(node) { + return node.kind === 183 /* ImportType */; + } + ts.isImportTypeNode = isImportTypeNode; + // Binding patterns + function isObjectBindingPattern(node) { + return node.kind === 184 /* ObjectBindingPattern */; + } + ts.isObjectBindingPattern = isObjectBindingPattern; + function isArrayBindingPattern(node) { + return node.kind === 185 /* ArrayBindingPattern */; + } + ts.isArrayBindingPattern = isArrayBindingPattern; + function isBindingElement(node) { + return node.kind === 186 /* BindingElement */; + } + ts.isBindingElement = isBindingElement; + // Expression + function isArrayLiteralExpression(node) { + return node.kind === 187 /* ArrayLiteralExpression */; + } + ts.isArrayLiteralExpression = isArrayLiteralExpression; + function isObjectLiteralExpression(node) { + return node.kind === 188 /* ObjectLiteralExpression */; + } + ts.isObjectLiteralExpression = isObjectLiteralExpression; + function isPropertyAccessExpression(node) { + return node.kind === 189 /* PropertyAccessExpression */; + } + ts.isPropertyAccessExpression = isPropertyAccessExpression; + function isElementAccessExpression(node) { + return node.kind === 190 /* ElementAccessExpression */; + } + ts.isElementAccessExpression = isElementAccessExpression; + function isCallExpression(node) { + return node.kind === 191 /* CallExpression */; + } + ts.isCallExpression = isCallExpression; + function isNewExpression(node) { + return node.kind === 192 /* NewExpression */; + } + ts.isNewExpression = isNewExpression; + function isTaggedTemplateExpression(node) { + return node.kind === 193 /* TaggedTemplateExpression */; + } + ts.isTaggedTemplateExpression = isTaggedTemplateExpression; + function isTypeAssertion(node) { + return node.kind === 194 /* TypeAssertionExpression */; + } + ts.isTypeAssertion = isTypeAssertion; + function isParenthesizedExpression(node) { + return node.kind === 195 /* ParenthesizedExpression */; + } + ts.isParenthesizedExpression = isParenthesizedExpression; + function skipPartiallyEmittedExpressions(node) { + while (node.kind === 308 /* PartiallyEmittedExpression */) { + node = node.expression; + } + return node; + } + ts.skipPartiallyEmittedExpressions = skipPartiallyEmittedExpressions; + function isFunctionExpression(node) { + return node.kind === 196 /* FunctionExpression */; + } + ts.isFunctionExpression = isFunctionExpression; + function isArrowFunction(node) { + return node.kind === 197 /* ArrowFunction */; + } + ts.isArrowFunction = isArrowFunction; + function isDeleteExpression(node) { + return node.kind === 198 /* DeleteExpression */; + } + ts.isDeleteExpression = isDeleteExpression; + function isTypeOfExpression(node) { + return node.kind === 199 /* TypeOfExpression */; + } + ts.isTypeOfExpression = isTypeOfExpression; + function isVoidExpression(node) { + return node.kind === 200 /* VoidExpression */; + } + ts.isVoidExpression = isVoidExpression; + function isAwaitExpression(node) { + return node.kind === 201 /* AwaitExpression */; + } + ts.isAwaitExpression = isAwaitExpression; + function isPrefixUnaryExpression(node) { + return node.kind === 202 /* PrefixUnaryExpression */; + } + ts.isPrefixUnaryExpression = isPrefixUnaryExpression; + function isPostfixUnaryExpression(node) { + return node.kind === 203 /* PostfixUnaryExpression */; + } + ts.isPostfixUnaryExpression = isPostfixUnaryExpression; + function isBinaryExpression(node) { + return node.kind === 204 /* BinaryExpression */; + } + ts.isBinaryExpression = isBinaryExpression; + function isConditionalExpression(node) { + return node.kind === 205 /* ConditionalExpression */; + } + ts.isConditionalExpression = isConditionalExpression; + function isTemplateExpression(node) { + return node.kind === 206 /* TemplateExpression */; + } + ts.isTemplateExpression = isTemplateExpression; + function isYieldExpression(node) { + return node.kind === 207 /* YieldExpression */; + } + ts.isYieldExpression = isYieldExpression; + function isSpreadElement(node) { + return node.kind === 208 /* SpreadElement */; + } + ts.isSpreadElement = isSpreadElement; + function isClassExpression(node) { + return node.kind === 209 /* ClassExpression */; + } + ts.isClassExpression = isClassExpression; + function isOmittedExpression(node) { + return node.kind === 210 /* OmittedExpression */; + } + ts.isOmittedExpression = isOmittedExpression; + function isExpressionWithTypeArguments(node) { + return node.kind === 211 /* ExpressionWithTypeArguments */; + } + ts.isExpressionWithTypeArguments = isExpressionWithTypeArguments; + function isAsExpression(node) { + return node.kind === 212 /* AsExpression */; + } + ts.isAsExpression = isAsExpression; + function isNonNullExpression(node) { + return node.kind === 213 /* NonNullExpression */; + } + ts.isNonNullExpression = isNonNullExpression; + function isMetaProperty(node) { + return node.kind === 214 /* MetaProperty */; + } + ts.isMetaProperty = isMetaProperty; + // Misc + function isTemplateSpan(node) { + return node.kind === 216 /* TemplateSpan */; + } + ts.isTemplateSpan = isTemplateSpan; + function isSemicolonClassElement(node) { + return node.kind === 217 /* SemicolonClassElement */; + } + ts.isSemicolonClassElement = isSemicolonClassElement; + // Block + function isBlock(node) { + return node.kind === 218 /* Block */; + } + ts.isBlock = isBlock; + function isVariableStatement(node) { + return node.kind === 219 /* VariableStatement */; + } + ts.isVariableStatement = isVariableStatement; + function isEmptyStatement(node) { + return node.kind === 220 /* EmptyStatement */; + } + ts.isEmptyStatement = isEmptyStatement; + function isExpressionStatement(node) { + return node.kind === 221 /* ExpressionStatement */; + } + ts.isExpressionStatement = isExpressionStatement; + function isIfStatement(node) { + return node.kind === 222 /* IfStatement */; + } + ts.isIfStatement = isIfStatement; + function isDoStatement(node) { + return node.kind === 223 /* DoStatement */; + } + ts.isDoStatement = isDoStatement; + function isWhileStatement(node) { + return node.kind === 224 /* WhileStatement */; + } + ts.isWhileStatement = isWhileStatement; + function isForStatement(node) { + return node.kind === 225 /* ForStatement */; + } + ts.isForStatement = isForStatement; + function isForInStatement(node) { + return node.kind === 226 /* ForInStatement */; + } + ts.isForInStatement = isForInStatement; + function isForOfStatement(node) { + return node.kind === 227 /* ForOfStatement */; + } + ts.isForOfStatement = isForOfStatement; + function isContinueStatement(node) { + return node.kind === 228 /* ContinueStatement */; + } + ts.isContinueStatement = isContinueStatement; + function isBreakStatement(node) { + return node.kind === 229 /* BreakStatement */; + } + ts.isBreakStatement = isBreakStatement; + function isBreakOrContinueStatement(node) { + return node.kind === 229 /* BreakStatement */ || node.kind === 228 /* ContinueStatement */; + } + ts.isBreakOrContinueStatement = isBreakOrContinueStatement; + function isReturnStatement(node) { + return node.kind === 230 /* ReturnStatement */; + } + ts.isReturnStatement = isReturnStatement; + function isWithStatement(node) { + return node.kind === 231 /* WithStatement */; + } + ts.isWithStatement = isWithStatement; + function isSwitchStatement(node) { + return node.kind === 232 /* SwitchStatement */; + } + ts.isSwitchStatement = isSwitchStatement; + function isLabeledStatement(node) { + return node.kind === 233 /* LabeledStatement */; + } + ts.isLabeledStatement = isLabeledStatement; + function isThrowStatement(node) { + return node.kind === 234 /* ThrowStatement */; + } + ts.isThrowStatement = isThrowStatement; + function isTryStatement(node) { + return node.kind === 235 /* TryStatement */; + } + ts.isTryStatement = isTryStatement; + function isDebuggerStatement(node) { + return node.kind === 236 /* DebuggerStatement */; + } + ts.isDebuggerStatement = isDebuggerStatement; + function isVariableDeclaration(node) { + return node.kind === 237 /* VariableDeclaration */; + } + ts.isVariableDeclaration = isVariableDeclaration; + function isVariableDeclarationList(node) { + return node.kind === 238 /* VariableDeclarationList */; + } + ts.isVariableDeclarationList = isVariableDeclarationList; + function isFunctionDeclaration(node) { + return node.kind === 239 /* FunctionDeclaration */; + } + ts.isFunctionDeclaration = isFunctionDeclaration; + function isClassDeclaration(node) { + return node.kind === 240 /* ClassDeclaration */; + } + ts.isClassDeclaration = isClassDeclaration; + function isInterfaceDeclaration(node) { + return node.kind === 241 /* InterfaceDeclaration */; + } + ts.isInterfaceDeclaration = isInterfaceDeclaration; + function isTypeAliasDeclaration(node) { + return node.kind === 242 /* TypeAliasDeclaration */; + } + ts.isTypeAliasDeclaration = isTypeAliasDeclaration; + function isEnumDeclaration(node) { + return node.kind === 243 /* EnumDeclaration */; + } + ts.isEnumDeclaration = isEnumDeclaration; + function isModuleDeclaration(node) { + return node.kind === 244 /* ModuleDeclaration */; + } + ts.isModuleDeclaration = isModuleDeclaration; + function isModuleBlock(node) { + return node.kind === 245 /* ModuleBlock */; + } + ts.isModuleBlock = isModuleBlock; + function isCaseBlock(node) { + return node.kind === 246 /* CaseBlock */; + } + ts.isCaseBlock = isCaseBlock; + function isNamespaceExportDeclaration(node) { + return node.kind === 247 /* NamespaceExportDeclaration */; + } + ts.isNamespaceExportDeclaration = isNamespaceExportDeclaration; + function isImportEqualsDeclaration(node) { + return node.kind === 248 /* ImportEqualsDeclaration */; + } + ts.isImportEqualsDeclaration = isImportEqualsDeclaration; + function isImportDeclaration(node) { + return node.kind === 249 /* ImportDeclaration */; + } + ts.isImportDeclaration = isImportDeclaration; + function isImportClause(node) { + return node.kind === 250 /* ImportClause */; + } + ts.isImportClause = isImportClause; + function isNamespaceImport(node) { + return node.kind === 251 /* NamespaceImport */; + } + ts.isNamespaceImport = isNamespaceImport; + function isNamedImports(node) { + return node.kind === 252 /* NamedImports */; + } + ts.isNamedImports = isNamedImports; + function isImportSpecifier(node) { + return node.kind === 253 /* ImportSpecifier */; + } + ts.isImportSpecifier = isImportSpecifier; + function isExportAssignment(node) { + return node.kind === 254 /* ExportAssignment */; + } + ts.isExportAssignment = isExportAssignment; + function isExportDeclaration(node) { + return node.kind === 255 /* ExportDeclaration */; + } + ts.isExportDeclaration = isExportDeclaration; + function isNamedExports(node) { + return node.kind === 256 /* NamedExports */; + } + ts.isNamedExports = isNamedExports; + function isExportSpecifier(node) { + return node.kind === 257 /* ExportSpecifier */; + } + ts.isExportSpecifier = isExportSpecifier; + function isMissingDeclaration(node) { + return node.kind === 258 /* MissingDeclaration */; + } + ts.isMissingDeclaration = isMissingDeclaration; + // Module References + function isExternalModuleReference(node) { + return node.kind === 259 /* ExternalModuleReference */; + } + ts.isExternalModuleReference = isExternalModuleReference; + // JSX + function isJsxElement(node) { + return node.kind === 260 /* JsxElement */; + } + ts.isJsxElement = isJsxElement; + function isJsxSelfClosingElement(node) { + return node.kind === 261 /* JsxSelfClosingElement */; + } + ts.isJsxSelfClosingElement = isJsxSelfClosingElement; + function isJsxOpeningElement(node) { + return node.kind === 262 /* JsxOpeningElement */; + } + ts.isJsxOpeningElement = isJsxOpeningElement; + function isJsxClosingElement(node) { + return node.kind === 263 /* JsxClosingElement */; + } + ts.isJsxClosingElement = isJsxClosingElement; + function isJsxFragment(node) { + return node.kind === 264 /* JsxFragment */; + } + ts.isJsxFragment = isJsxFragment; + function isJsxOpeningFragment(node) { + return node.kind === 265 /* JsxOpeningFragment */; + } + ts.isJsxOpeningFragment = isJsxOpeningFragment; + function isJsxClosingFragment(node) { + return node.kind === 266 /* JsxClosingFragment */; + } + ts.isJsxClosingFragment = isJsxClosingFragment; + function isJsxAttribute(node) { + return node.kind === 267 /* JsxAttribute */; + } + ts.isJsxAttribute = isJsxAttribute; + function isJsxAttributes(node) { + return node.kind === 268 /* JsxAttributes */; + } + ts.isJsxAttributes = isJsxAttributes; + function isJsxSpreadAttribute(node) { + return node.kind === 269 /* JsxSpreadAttribute */; + } + ts.isJsxSpreadAttribute = isJsxSpreadAttribute; + function isJsxExpression(node) { + return node.kind === 270 /* JsxExpression */; + } + ts.isJsxExpression = isJsxExpression; + // Clauses + function isCaseClause(node) { + return node.kind === 271 /* CaseClause */; + } + ts.isCaseClause = isCaseClause; + function isDefaultClause(node) { + return node.kind === 272 /* DefaultClause */; + } + ts.isDefaultClause = isDefaultClause; + function isHeritageClause(node) { + return node.kind === 273 /* HeritageClause */; + } + ts.isHeritageClause = isHeritageClause; + function isCatchClause(node) { + return node.kind === 274 /* CatchClause */; + } + ts.isCatchClause = isCatchClause; + // Property assignments + function isPropertyAssignment(node) { + return node.kind === 275 /* PropertyAssignment */; + } + ts.isPropertyAssignment = isPropertyAssignment; + function isShorthandPropertyAssignment(node) { + return node.kind === 276 /* ShorthandPropertyAssignment */; + } + ts.isShorthandPropertyAssignment = isShorthandPropertyAssignment; + function isSpreadAssignment(node) { + return node.kind === 277 /* SpreadAssignment */; + } + ts.isSpreadAssignment = isSpreadAssignment; + // Enum + function isEnumMember(node) { + return node.kind === 278 /* EnumMember */; + } + ts.isEnumMember = isEnumMember; + // Top-level nodes + function isSourceFile(node) { + return node.kind === 279 /* SourceFile */; + } + ts.isSourceFile = isSourceFile; + function isBundle(node) { + return node.kind === 280 /* Bundle */; + } + ts.isBundle = isBundle; + function isUnparsedSource(node) { + return node.kind === 281 /* UnparsedSource */; + } + ts.isUnparsedSource = isUnparsedSource; + // JSDoc + function isJSDocTypeExpression(node) { + return node.kind === 283 /* JSDocTypeExpression */; + } + ts.isJSDocTypeExpression = isJSDocTypeExpression; + function isJSDocAllType(node) { + return node.kind === 284 /* JSDocAllType */; + } + ts.isJSDocAllType = isJSDocAllType; + function isJSDocUnknownType(node) { + return node.kind === 285 /* JSDocUnknownType */; + } + ts.isJSDocUnknownType = isJSDocUnknownType; + function isJSDocNullableType(node) { + return node.kind === 286 /* JSDocNullableType */; + } + ts.isJSDocNullableType = isJSDocNullableType; + function isJSDocNonNullableType(node) { + return node.kind === 287 /* JSDocNonNullableType */; + } + ts.isJSDocNonNullableType = isJSDocNonNullableType; + function isJSDocOptionalType(node) { + return node.kind === 288 /* JSDocOptionalType */; + } + ts.isJSDocOptionalType = isJSDocOptionalType; + function isJSDocFunctionType(node) { + return node.kind === 289 /* JSDocFunctionType */; + } + ts.isJSDocFunctionType = isJSDocFunctionType; + function isJSDocVariadicType(node) { + return node.kind === 290 /* JSDocVariadicType */; + } + ts.isJSDocVariadicType = isJSDocVariadicType; + function isJSDoc(node) { + return node.kind === 291 /* JSDocComment */; + } + ts.isJSDoc = isJSDoc; + function isJSDocAugmentsTag(node) { + return node.kind === 295 /* JSDocAugmentsTag */; + } + ts.isJSDocAugmentsTag = isJSDocAugmentsTag; + function isJSDocClassTag(node) { + return node.kind === 296 /* JSDocClassTag */; + } + ts.isJSDocClassTag = isJSDocClassTag; + function isJSDocEnumTag(node) { + return node.kind === 298 /* JSDocEnumTag */; + } + ts.isJSDocEnumTag = isJSDocEnumTag; + function isJSDocThisTag(node) { + return node.kind === 301 /* JSDocThisTag */; + } + ts.isJSDocThisTag = isJSDocThisTag; + function isJSDocParameterTag(node) { + return node.kind === 299 /* JSDocParameterTag */; + } + ts.isJSDocParameterTag = isJSDocParameterTag; + function isJSDocReturnTag(node) { + return node.kind === 300 /* JSDocReturnTag */; + } + ts.isJSDocReturnTag = isJSDocReturnTag; + function isJSDocTypeTag(node) { + return node.kind === 302 /* JSDocTypeTag */; + } + ts.isJSDocTypeTag = isJSDocTypeTag; + function isJSDocTemplateTag(node) { + return node.kind === 303 /* JSDocTemplateTag */; + } + ts.isJSDocTemplateTag = isJSDocTemplateTag; + function isJSDocTypedefTag(node) { + return node.kind === 304 /* JSDocTypedefTag */; + } + ts.isJSDocTypedefTag = isJSDocTypedefTag; + function isJSDocPropertyTag(node) { + return node.kind === 305 /* JSDocPropertyTag */; + } + ts.isJSDocPropertyTag = isJSDocPropertyTag; + function isJSDocPropertyLikeTag(node) { + return node.kind === 305 /* JSDocPropertyTag */ || node.kind === 299 /* JSDocParameterTag */; + } + ts.isJSDocPropertyLikeTag = isJSDocPropertyLikeTag; + function isJSDocTypeLiteral(node) { + return node.kind === 292 /* JSDocTypeLiteral */; + } + ts.isJSDocTypeLiteral = isJSDocTypeLiteral; + function isJSDocCallbackTag(node) { + return node.kind === 297 /* JSDocCallbackTag */; + } + ts.isJSDocCallbackTag = isJSDocCallbackTag; + function isJSDocSignature(node) { + return node.kind === 293 /* JSDocSignature */; + } + ts.isJSDocSignature = isJSDocSignature; +})(ts || (ts = {})); +// Node tests +// +// All node tests in the following list should *not* reference parent pointers so that +// they may be used with transformations. +(function (ts) { + /* @internal */ + function isSyntaxList(n) { + return n.kind === 306 /* SyntaxList */; + } + ts.isSyntaxList = isSyntaxList; + /* @internal */ + function isNode(node) { + return isNodeKind(node.kind); + } + ts.isNode = isNode; + /* @internal */ + function isNodeKind(kind) { + return kind >= 148 /* FirstNode */; + } + ts.isNodeKind = isNodeKind; + /** + * True if node is of some token syntax kind. + * For example, this is true for an IfKeyword but not for an IfStatement. + * Literals are considered tokens, except TemplateLiteral, but does include TemplateHead/Middle/Tail. + */ + function isToken(n) { + return n.kind >= 0 /* FirstToken */ && n.kind <= 147 /* LastToken */; + } + ts.isToken = isToken; + // Node Arrays + /* @internal */ + function isNodeArray(array) { + return array.hasOwnProperty("pos") && array.hasOwnProperty("end"); + } + ts.isNodeArray = isNodeArray; + // Literals + /* @internal */ + function isLiteralKind(kind) { + return 8 /* FirstLiteralToken */ <= kind && kind <= 14 /* LastLiteralToken */; + } + ts.isLiteralKind = isLiteralKind; + function isLiteralExpression(node) { + return isLiteralKind(node.kind); + } + ts.isLiteralExpression = isLiteralExpression; + // Pseudo-literals + /* @internal */ + function isTemplateLiteralKind(kind) { + return 14 /* FirstTemplateToken */ <= kind && kind <= 17 /* LastTemplateToken */; + } + ts.isTemplateLiteralKind = isTemplateLiteralKind; + function isTemplateLiteralToken(node) { + return isTemplateLiteralKind(node.kind); + } + ts.isTemplateLiteralToken = isTemplateLiteralToken; + function isTemplateMiddleOrTemplateTail(node) { + var kind = node.kind; + return kind === 16 /* TemplateMiddle */ + || kind === 17 /* TemplateTail */; + } + ts.isTemplateMiddleOrTemplateTail = isTemplateMiddleOrTemplateTail; + function isImportOrExportSpecifier(node) { + return ts.isImportSpecifier(node) || ts.isExportSpecifier(node); + } + ts.isImportOrExportSpecifier = isImportOrExportSpecifier; + function isStringTextContainingNode(node) { + return node.kind === 10 /* StringLiteral */ || isTemplateLiteralKind(node.kind); + } + ts.isStringTextContainingNode = isStringTextContainingNode; + // Identifiers + /* @internal */ + function isGeneratedIdentifier(node) { + return ts.isIdentifier(node) && (node.autoGenerateFlags & 7 /* KindMask */) > 0 /* None */; + } + ts.isGeneratedIdentifier = isGeneratedIdentifier; + // Keywords + /* @internal */ + function isModifierKind(token) { + switch (token) { + case 118 /* AbstractKeyword */: + case 121 /* AsyncKeyword */: + case 77 /* ConstKeyword */: + case 125 /* DeclareKeyword */: + case 80 /* DefaultKeyword */: + case 85 /* ExportKeyword */: + case 115 /* PublicKeyword */: + case 113 /* PrivateKeyword */: + case 114 /* ProtectedKeyword */: + case 133 /* ReadonlyKeyword */: + case 116 /* StaticKeyword */: + return true; + } + return false; + } + ts.isModifierKind = isModifierKind; + /* @internal */ + function isParameterPropertyModifier(kind) { + return !!(ts.modifierToFlag(kind) & 92 /* ParameterPropertyModifier */); + } + ts.isParameterPropertyModifier = isParameterPropertyModifier; + /* @internal */ + function isClassMemberModifier(idToken) { + return isParameterPropertyModifier(idToken) || idToken === 116 /* StaticKeyword */; + } + ts.isClassMemberModifier = isClassMemberModifier; + function isModifier(node) { + return isModifierKind(node.kind); + } + ts.isModifier = isModifier; + function isEntityName(node) { + var kind = node.kind; + return kind === 148 /* QualifiedName */ + || kind === 72 /* Identifier */; + } + ts.isEntityName = isEntityName; + function isPropertyName(node) { + var kind = node.kind; + return kind === 72 /* Identifier */ + || kind === 10 /* StringLiteral */ + || kind === 8 /* NumericLiteral */ + || kind === 149 /* ComputedPropertyName */; + } + ts.isPropertyName = isPropertyName; + function isBindingName(node) { + var kind = node.kind; + return kind === 72 /* Identifier */ + || kind === 184 /* ObjectBindingPattern */ + || kind === 185 /* ArrayBindingPattern */; + } + ts.isBindingName = isBindingName; + // Functions + function isFunctionLike(node) { + return node && isFunctionLikeKind(node.kind); + } + ts.isFunctionLike = isFunctionLike; + /* @internal */ + function isFunctionLikeDeclaration(node) { + return node && isFunctionLikeDeclarationKind(node.kind); + } + ts.isFunctionLikeDeclaration = isFunctionLikeDeclaration; + function isFunctionLikeDeclarationKind(kind) { + switch (kind) { + case 239 /* FunctionDeclaration */: + case 156 /* MethodDeclaration */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + return true; + default: + return false; + } + } + /* @internal */ + function isFunctionLikeKind(kind) { + switch (kind) { + case 155 /* MethodSignature */: + case 160 /* CallSignature */: + case 293 /* JSDocSignature */: + case 161 /* ConstructSignature */: + case 162 /* IndexSignature */: + case 165 /* FunctionType */: + case 289 /* JSDocFunctionType */: + case 166 /* ConstructorType */: + return true; + default: + return isFunctionLikeDeclarationKind(kind); + } + } + ts.isFunctionLikeKind = isFunctionLikeKind; + /* @internal */ + function isFunctionOrModuleBlock(node) { + return ts.isSourceFile(node) || ts.isModuleBlock(node) || ts.isBlock(node) && isFunctionLike(node.parent); + } + ts.isFunctionOrModuleBlock = isFunctionOrModuleBlock; + // Classes + function isClassElement(node) { + var kind = node.kind; + return kind === 157 /* Constructor */ + || kind === 154 /* PropertyDeclaration */ + || kind === 156 /* MethodDeclaration */ + || kind === 158 /* GetAccessor */ + || kind === 159 /* SetAccessor */ + || kind === 162 /* IndexSignature */ + || kind === 217 /* SemicolonClassElement */; + } + ts.isClassElement = isClassElement; + function isClassLike(node) { + return node && (node.kind === 240 /* ClassDeclaration */ || node.kind === 209 /* ClassExpression */); + } + ts.isClassLike = isClassLike; + function isAccessor(node) { + return node && (node.kind === 158 /* GetAccessor */ || node.kind === 159 /* SetAccessor */); + } + ts.isAccessor = isAccessor; + /* @internal */ + function isMethodOrAccessor(node) { + switch (node.kind) { + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + return true; + default: + return false; + } + } + ts.isMethodOrAccessor = isMethodOrAccessor; + // Type members + function isTypeElement(node) { + var kind = node.kind; + return kind === 161 /* ConstructSignature */ + || kind === 160 /* CallSignature */ + || kind === 153 /* PropertySignature */ + || kind === 155 /* MethodSignature */ + || kind === 162 /* IndexSignature */; + } + ts.isTypeElement = isTypeElement; + function isClassOrTypeElement(node) { + return isTypeElement(node) || isClassElement(node); + } + ts.isClassOrTypeElement = isClassOrTypeElement; + function isObjectLiteralElementLike(node) { + var kind = node.kind; + return kind === 275 /* PropertyAssignment */ + || kind === 276 /* ShorthandPropertyAssignment */ + || kind === 277 /* SpreadAssignment */ + || kind === 156 /* MethodDeclaration */ + || kind === 158 /* GetAccessor */ + || kind === 159 /* SetAccessor */; + } + ts.isObjectLiteralElementLike = isObjectLiteralElementLike; + // Type + /** + * Node test that determines whether a node is a valid type node. + * This differs from the `isPartOfTypeNode` function which determines whether a node is *part* + * of a TypeNode. + */ + function isTypeNode(node) { + return ts.isTypeNodeKind(node.kind); + } + ts.isTypeNode = isTypeNode; + function isFunctionOrConstructorTypeNode(node) { + switch (node.kind) { + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + return true; + } + return false; + } + ts.isFunctionOrConstructorTypeNode = isFunctionOrConstructorTypeNode; + // Binding patterns + /* @internal */ + function isBindingPattern(node) { + if (node) { + var kind = node.kind; + return kind === 185 /* ArrayBindingPattern */ + || kind === 184 /* ObjectBindingPattern */; + } + return false; + } + ts.isBindingPattern = isBindingPattern; + /* @internal */ + function isAssignmentPattern(node) { + var kind = node.kind; + return kind === 187 /* ArrayLiteralExpression */ + || kind === 188 /* ObjectLiteralExpression */; + } + ts.isAssignmentPattern = isAssignmentPattern; + /* @internal */ + function isArrayBindingElement(node) { + var kind = node.kind; + return kind === 186 /* BindingElement */ + || kind === 210 /* OmittedExpression */; + } + ts.isArrayBindingElement = isArrayBindingElement; + /** + * Determines whether the BindingOrAssignmentElement is a BindingElement-like declaration + */ + /* @internal */ + function isDeclarationBindingElement(bindingElement) { + switch (bindingElement.kind) { + case 237 /* VariableDeclaration */: + case 151 /* Parameter */: + case 186 /* BindingElement */: + return true; + } + return false; + } + ts.isDeclarationBindingElement = isDeclarationBindingElement; + /** + * Determines whether a node is a BindingOrAssignmentPattern + */ + /* @internal */ + function isBindingOrAssignmentPattern(node) { + return isObjectBindingOrAssignmentPattern(node) + || isArrayBindingOrAssignmentPattern(node); + } + ts.isBindingOrAssignmentPattern = isBindingOrAssignmentPattern; + /** + * Determines whether a node is an ObjectBindingOrAssignmentPattern + */ + /* @internal */ + function isObjectBindingOrAssignmentPattern(node) { + switch (node.kind) { + case 184 /* ObjectBindingPattern */: + case 188 /* ObjectLiteralExpression */: + return true; + } + return false; + } + ts.isObjectBindingOrAssignmentPattern = isObjectBindingOrAssignmentPattern; + /** + * Determines whether a node is an ArrayBindingOrAssignmentPattern + */ + /* @internal */ + function isArrayBindingOrAssignmentPattern(node) { + switch (node.kind) { + case 185 /* ArrayBindingPattern */: + case 187 /* ArrayLiteralExpression */: + return true; + } + return false; + } + ts.isArrayBindingOrAssignmentPattern = isArrayBindingOrAssignmentPattern; + /* @internal */ + function isPropertyAccessOrQualifiedNameOrImportTypeNode(node) { + var kind = node.kind; + return kind === 189 /* PropertyAccessExpression */ + || kind === 148 /* QualifiedName */ + || kind === 183 /* ImportType */; + } + ts.isPropertyAccessOrQualifiedNameOrImportTypeNode = isPropertyAccessOrQualifiedNameOrImportTypeNode; + // Expression + function isPropertyAccessOrQualifiedName(node) { + var kind = node.kind; + return kind === 189 /* PropertyAccessExpression */ + || kind === 148 /* QualifiedName */; + } + ts.isPropertyAccessOrQualifiedName = isPropertyAccessOrQualifiedName; + function isCallLikeExpression(node) { + switch (node.kind) { + case 262 /* JsxOpeningElement */: + case 261 /* JsxSelfClosingElement */: + case 191 /* CallExpression */: + case 192 /* NewExpression */: + case 193 /* TaggedTemplateExpression */: + case 152 /* Decorator */: + return true; + default: + return false; + } + } + ts.isCallLikeExpression = isCallLikeExpression; + function isCallOrNewExpression(node) { + return node.kind === 191 /* CallExpression */ || node.kind === 192 /* NewExpression */; + } + ts.isCallOrNewExpression = isCallOrNewExpression; + function isTemplateLiteral(node) { + var kind = node.kind; + return kind === 206 /* TemplateExpression */ + || kind === 14 /* NoSubstitutionTemplateLiteral */; + } + ts.isTemplateLiteral = isTemplateLiteral; + /* @internal */ + function isLeftHandSideExpression(node) { + return isLeftHandSideExpressionKind(ts.skipPartiallyEmittedExpressions(node).kind); + } + ts.isLeftHandSideExpression = isLeftHandSideExpression; + function isLeftHandSideExpressionKind(kind) { + switch (kind) { + case 189 /* PropertyAccessExpression */: + case 190 /* ElementAccessExpression */: + case 192 /* NewExpression */: + case 191 /* CallExpression */: + case 260 /* JsxElement */: + case 261 /* JsxSelfClosingElement */: + case 264 /* JsxFragment */: + case 193 /* TaggedTemplateExpression */: + case 187 /* ArrayLiteralExpression */: + case 195 /* ParenthesizedExpression */: + case 188 /* ObjectLiteralExpression */: + case 209 /* ClassExpression */: + case 196 /* FunctionExpression */: + case 72 /* Identifier */: + case 13 /* RegularExpressionLiteral */: + case 8 /* NumericLiteral */: + case 9 /* BigIntLiteral */: + case 10 /* StringLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: + case 206 /* TemplateExpression */: + case 87 /* FalseKeyword */: + case 96 /* NullKeyword */: + case 100 /* ThisKeyword */: + case 102 /* TrueKeyword */: + case 98 /* SuperKeyword */: + case 213 /* NonNullExpression */: + case 214 /* MetaProperty */: + case 92 /* ImportKeyword */: // technically this is only an Expression if it's in a CallExpression + return true; + default: + return false; + } + } + /* @internal */ + function isUnaryExpression(node) { + return isUnaryExpressionKind(ts.skipPartiallyEmittedExpressions(node).kind); + } + ts.isUnaryExpression = isUnaryExpression; + function isUnaryExpressionKind(kind) { + switch (kind) { + case 202 /* PrefixUnaryExpression */: + case 203 /* PostfixUnaryExpression */: + case 198 /* DeleteExpression */: + case 199 /* TypeOfExpression */: + case 200 /* VoidExpression */: + case 201 /* AwaitExpression */: + case 194 /* TypeAssertionExpression */: + return true; + default: + return isLeftHandSideExpressionKind(kind); + } + } + /* @internal */ + function isUnaryExpressionWithWrite(expr) { + switch (expr.kind) { + case 203 /* PostfixUnaryExpression */: + return true; + case 202 /* PrefixUnaryExpression */: + return expr.operator === 44 /* PlusPlusToken */ || + expr.operator === 45 /* MinusMinusToken */; + default: + return false; + } + } + ts.isUnaryExpressionWithWrite = isUnaryExpressionWithWrite; + /* @internal */ + /** + * Determines whether a node is an expression based only on its kind. + * Use `isExpressionNode` if not in transforms. + */ + function isExpression(node) { + return isExpressionKind(ts.skipPartiallyEmittedExpressions(node).kind); + } + ts.isExpression = isExpression; + function isExpressionKind(kind) { + switch (kind) { + case 205 /* ConditionalExpression */: + case 207 /* YieldExpression */: + case 197 /* ArrowFunction */: + case 204 /* BinaryExpression */: + case 208 /* SpreadElement */: + case 212 /* AsExpression */: + case 210 /* OmittedExpression */: + case 309 /* CommaListExpression */: + case 308 /* PartiallyEmittedExpression */: + return true; + default: + return isUnaryExpressionKind(kind); + } + } + function isAssertionExpression(node) { + var kind = node.kind; + return kind === 194 /* TypeAssertionExpression */ + || kind === 212 /* AsExpression */; + } + ts.isAssertionExpression = isAssertionExpression; + /* @internal */ + function isPartiallyEmittedExpression(node) { + return node.kind === 308 /* PartiallyEmittedExpression */; + } + ts.isPartiallyEmittedExpression = isPartiallyEmittedExpression; + /* @internal */ + function isNotEmittedStatement(node) { + return node.kind === 307 /* NotEmittedStatement */; + } + ts.isNotEmittedStatement = isNotEmittedStatement; + /* @internal */ + function isNotEmittedOrPartiallyEmittedNode(node) { + return isNotEmittedStatement(node) + || isPartiallyEmittedExpression(node); + } + ts.isNotEmittedOrPartiallyEmittedNode = isNotEmittedOrPartiallyEmittedNode; + function isIterationStatement(node, lookInLabeledStatements) { + switch (node.kind) { + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + case 223 /* DoStatement */: + case 224 /* WhileStatement */: + return true; + case 233 /* LabeledStatement */: + return lookInLabeledStatements && isIterationStatement(node.statement, lookInLabeledStatements); + } + return false; + } + ts.isIterationStatement = isIterationStatement; + /* @internal */ + function isForInOrOfStatement(node) { + return node.kind === 226 /* ForInStatement */ || node.kind === 227 /* ForOfStatement */; + } + ts.isForInOrOfStatement = isForInOrOfStatement; + // Element + /* @internal */ + function isConciseBody(node) { + return ts.isBlock(node) + || isExpression(node); + } + ts.isConciseBody = isConciseBody; + /* @internal */ + function isFunctionBody(node) { + return ts.isBlock(node); + } + ts.isFunctionBody = isFunctionBody; + /* @internal */ + function isForInitializer(node) { + return ts.isVariableDeclarationList(node) + || isExpression(node); + } + ts.isForInitializer = isForInitializer; + /* @internal */ + function isModuleBody(node) { + var kind = node.kind; + return kind === 245 /* ModuleBlock */ + || kind === 244 /* ModuleDeclaration */ + || kind === 72 /* Identifier */; + } + ts.isModuleBody = isModuleBody; + /* @internal */ + function isNamespaceBody(node) { + var kind = node.kind; + return kind === 245 /* ModuleBlock */ + || kind === 244 /* ModuleDeclaration */; + } + ts.isNamespaceBody = isNamespaceBody; + /* @internal */ + function isJSDocNamespaceBody(node) { + var kind = node.kind; + return kind === 72 /* Identifier */ + || kind === 244 /* ModuleDeclaration */; + } + ts.isJSDocNamespaceBody = isJSDocNamespaceBody; + /* @internal */ + function isNamedImportBindings(node) { + var kind = node.kind; + return kind === 252 /* NamedImports */ + || kind === 251 /* NamespaceImport */; + } + ts.isNamedImportBindings = isNamedImportBindings; + /* @internal */ + function isModuleOrEnumDeclaration(node) { + return node.kind === 244 /* ModuleDeclaration */ || node.kind === 243 /* EnumDeclaration */; + } + ts.isModuleOrEnumDeclaration = isModuleOrEnumDeclaration; + function isDeclarationKind(kind) { + return kind === 197 /* ArrowFunction */ + || kind === 186 /* BindingElement */ + || kind === 240 /* ClassDeclaration */ + || kind === 209 /* ClassExpression */ + || kind === 157 /* Constructor */ + || kind === 243 /* EnumDeclaration */ + || kind === 278 /* EnumMember */ + || kind === 257 /* ExportSpecifier */ + || kind === 239 /* FunctionDeclaration */ + || kind === 196 /* FunctionExpression */ + || kind === 158 /* GetAccessor */ + || kind === 250 /* ImportClause */ + || kind === 248 /* ImportEqualsDeclaration */ + || kind === 253 /* ImportSpecifier */ + || kind === 241 /* InterfaceDeclaration */ + || kind === 267 /* JsxAttribute */ + || kind === 156 /* MethodDeclaration */ + || kind === 155 /* MethodSignature */ + || kind === 244 /* ModuleDeclaration */ + || kind === 247 /* NamespaceExportDeclaration */ + || kind === 251 /* NamespaceImport */ + || kind === 151 /* Parameter */ + || kind === 275 /* PropertyAssignment */ + || kind === 154 /* PropertyDeclaration */ + || kind === 153 /* PropertySignature */ + || kind === 159 /* SetAccessor */ + || kind === 276 /* ShorthandPropertyAssignment */ + || kind === 242 /* TypeAliasDeclaration */ + || kind === 150 /* TypeParameter */ + || kind === 237 /* VariableDeclaration */ + || kind === 304 /* JSDocTypedefTag */ + || kind === 297 /* JSDocCallbackTag */ + || kind === 305 /* JSDocPropertyTag */; + } + function isDeclarationStatementKind(kind) { + return kind === 239 /* FunctionDeclaration */ + || kind === 258 /* MissingDeclaration */ + || kind === 240 /* ClassDeclaration */ + || kind === 241 /* InterfaceDeclaration */ + || kind === 242 /* TypeAliasDeclaration */ + || kind === 243 /* EnumDeclaration */ + || kind === 244 /* ModuleDeclaration */ + || kind === 249 /* ImportDeclaration */ + || kind === 248 /* ImportEqualsDeclaration */ + || kind === 255 /* ExportDeclaration */ + || kind === 254 /* ExportAssignment */ + || kind === 247 /* NamespaceExportDeclaration */; + } + function isStatementKindButNotDeclarationKind(kind) { + return kind === 229 /* BreakStatement */ + || kind === 228 /* ContinueStatement */ + || kind === 236 /* DebuggerStatement */ + || kind === 223 /* DoStatement */ + || kind === 221 /* ExpressionStatement */ + || kind === 220 /* EmptyStatement */ + || kind === 226 /* ForInStatement */ + || kind === 227 /* ForOfStatement */ + || kind === 225 /* ForStatement */ + || kind === 222 /* IfStatement */ + || kind === 233 /* LabeledStatement */ + || kind === 230 /* ReturnStatement */ + || kind === 232 /* SwitchStatement */ + || kind === 234 /* ThrowStatement */ + || kind === 235 /* TryStatement */ + || kind === 219 /* VariableStatement */ + || kind === 224 /* WhileStatement */ + || kind === 231 /* WithStatement */ + || kind === 307 /* NotEmittedStatement */ + || kind === 311 /* EndOfDeclarationMarker */ + || kind === 310 /* MergeDeclarationMarker */; + } + /* @internal */ + function isDeclaration(node) { + if (node.kind === 150 /* TypeParameter */) { + return node.parent.kind !== 303 /* JSDocTemplateTag */ || ts.isInJSFile(node); + } + return isDeclarationKind(node.kind); + } + ts.isDeclaration = isDeclaration; + /* @internal */ + function isDeclarationStatement(node) { + return isDeclarationStatementKind(node.kind); + } + ts.isDeclarationStatement = isDeclarationStatement; + /** + * Determines whether the node is a statement that is not also a declaration + */ + /* @internal */ + function isStatementButNotDeclaration(node) { + return isStatementKindButNotDeclarationKind(node.kind); + } + ts.isStatementButNotDeclaration = isStatementButNotDeclaration; + /* @internal */ + function isStatement(node) { + var kind = node.kind; + return isStatementKindButNotDeclarationKind(kind) + || isDeclarationStatementKind(kind) + || isBlockStatement(node); + } + ts.isStatement = isStatement; + function isBlockStatement(node) { + if (node.kind !== 218 /* Block */) + return false; + if (node.parent !== undefined) { + if (node.parent.kind === 235 /* TryStatement */ || node.parent.kind === 274 /* CatchClause */) { + return false; + } + } + return !ts.isFunctionBlock(node); + } + // Module references + /* @internal */ + function isModuleReference(node) { + var kind = node.kind; + return kind === 259 /* ExternalModuleReference */ + || kind === 148 /* QualifiedName */ + || kind === 72 /* Identifier */; + } + ts.isModuleReference = isModuleReference; + // JSX + /* @internal */ + function isJsxTagNameExpression(node) { + var kind = node.kind; + return kind === 100 /* ThisKeyword */ + || kind === 72 /* Identifier */ + || kind === 189 /* PropertyAccessExpression */; + } + ts.isJsxTagNameExpression = isJsxTagNameExpression; + /* @internal */ + function isJsxChild(node) { + var kind = node.kind; + return kind === 260 /* JsxElement */ + || kind === 270 /* JsxExpression */ + || kind === 261 /* JsxSelfClosingElement */ + || kind === 11 /* JsxText */ + || kind === 264 /* JsxFragment */; + } + ts.isJsxChild = isJsxChild; + /* @internal */ + function isJsxAttributeLike(node) { + var kind = node.kind; + return kind === 267 /* JsxAttribute */ + || kind === 269 /* JsxSpreadAttribute */; + } + ts.isJsxAttributeLike = isJsxAttributeLike; + /* @internal */ + function isStringLiteralOrJsxExpression(node) { + var kind = node.kind; + return kind === 10 /* StringLiteral */ + || kind === 270 /* JsxExpression */; + } + ts.isStringLiteralOrJsxExpression = isStringLiteralOrJsxExpression; + function isJsxOpeningLikeElement(node) { + var kind = node.kind; + return kind === 262 /* JsxOpeningElement */ + || kind === 261 /* JsxSelfClosingElement */; + } + ts.isJsxOpeningLikeElement = isJsxOpeningLikeElement; + // Clauses + function isCaseOrDefaultClause(node) { + var kind = node.kind; + return kind === 271 /* CaseClause */ + || kind === 272 /* DefaultClause */; + } + ts.isCaseOrDefaultClause = isCaseOrDefaultClause; + // JSDoc + /** True if node is of some JSDoc syntax kind. */ + /* @internal */ + function isJSDocNode(node) { + return node.kind >= 283 /* FirstJSDocNode */ && node.kind <= 305 /* LastJSDocNode */; + } + ts.isJSDocNode = isJSDocNode; + /** True if node is of a kind that may contain comment text. */ + function isJSDocCommentContainingNode(node) { + return node.kind === 291 /* JSDocComment */ || isJSDocTag(node) || ts.isJSDocTypeLiteral(node) || ts.isJSDocSignature(node); + } + ts.isJSDocCommentContainingNode = isJSDocCommentContainingNode; + // TODO: determine what this does before making it public. + /* @internal */ + function isJSDocTag(node) { + return node.kind >= 294 /* FirstJSDocTagNode */ && node.kind <= 305 /* LastJSDocTagNode */; + } + ts.isJSDocTag = isJSDocTag; + function isSetAccessor(node) { + return node.kind === 159 /* SetAccessor */; + } + ts.isSetAccessor = isSetAccessor; + function isGetAccessor(node) { + return node.kind === 158 /* GetAccessor */; + } + ts.isGetAccessor = isGetAccessor; + /** True if has jsdoc nodes attached to it. */ + /* @internal */ + // TODO: GH#19856 Would like to return `node is Node & { jsDoc: JSDoc[] }` but it causes long compile times + function hasJSDocNodes(node) { + var jsDoc = node.jsDoc; + return !!jsDoc && jsDoc.length > 0; + } + ts.hasJSDocNodes = hasJSDocNodes; + /** True if has type node attached to it. */ + /* @internal */ + function hasType(node) { + return !!node.type; + } + ts.hasType = hasType; + /** True if has initializer node attached to it. */ + /* @internal */ + function hasInitializer(node) { + return !!node.initializer; + } + ts.hasInitializer = hasInitializer; + /** True if has initializer node attached to it. */ + /* @internal */ + function hasOnlyExpressionInitializer(node) { + return hasInitializer(node) && !ts.isForStatement(node) && !ts.isForInStatement(node) && !ts.isForOfStatement(node) && !ts.isJsxAttribute(node); + } + ts.hasOnlyExpressionInitializer = hasOnlyExpressionInitializer; + function isObjectLiteralElement(node) { + return node.kind === 267 /* JsxAttribute */ || node.kind === 269 /* JsxSpreadAttribute */ || isObjectLiteralElementLike(node); + } + ts.isObjectLiteralElement = isObjectLiteralElement; + /* @internal */ + function isTypeReferenceType(node) { + return node.kind === 164 /* TypeReference */ || node.kind === 211 /* ExpressionWithTypeArguments */; + } + ts.isTypeReferenceType = isTypeReferenceType; + var MAX_SMI_X86 = 1073741823; + /* @internal */ + function guessIndentation(lines) { + var indentation = MAX_SMI_X86; + for (var _i = 0, lines_1 = lines; _i < lines_1.length; _i++) { + var line = lines_1[_i]; + if (!line.length) { + continue; + } + var i = 0; + for (; i < line.length && i < indentation; i++) { + if (!ts.isWhiteSpaceLike(line.charCodeAt(i))) { + break; + } + } + if (i < indentation) { + indentation = i; + } + if (indentation === 0) { + return 0; + } + } + return indentation === MAX_SMI_X86 ? undefined : indentation; + } + ts.guessIndentation = guessIndentation; + function isStringLiteralLike(node) { + return node.kind === 10 /* StringLiteral */ || node.kind === 14 /* NoSubstitutionTemplateLiteral */; + } + ts.isStringLiteralLike = isStringLiteralLike; +})(ts || (ts = {})); +/* @internal */ +(function (ts) { + function isNamedImportsOrExports(node) { + return node.kind === 252 /* NamedImports */ || node.kind === 256 /* NamedExports */; + } + ts.isNamedImportsOrExports = isNamedImportsOrExports; + function Symbol(flags, name) { + this.flags = flags; + this.escapedName = name; + this.declarations = undefined; + this.valueDeclaration = undefined; + this.id = undefined; + this.mergeId = undefined; + this.parent = undefined; + } + function Type(checker, flags) { + this.flags = flags; + if (ts.Debug.isDebugging) { + this.checker = checker; + } + } + function Signature() { } // tslint:disable-line no-empty + function Node(kind, pos, end) { + this.pos = pos; + this.end = end; + this.kind = kind; + this.id = 0; + this.flags = 0 /* None */; + this.modifierFlagsCache = 0 /* None */; + this.transformFlags = 0 /* None */; + this.parent = undefined; + this.original = undefined; + } + function SourceMapSource(fileName, text, skipTrivia) { + this.fileName = fileName; + this.text = text; + this.skipTrivia = skipTrivia || (function (pos) { return pos; }); + } + ts.objectAllocator = { + getNodeConstructor: function () { return Node; }, + getTokenConstructor: function () { return Node; }, + getIdentifierConstructor: function () { return Node; }, + getSourceFileConstructor: function () { return Node; }, + getSymbolConstructor: function () { return Symbol; }, + getTypeConstructor: function () { return Type; }, + getSignatureConstructor: function () { return Signature; }, + getSourceMapSourceConstructor: function () { return SourceMapSource; }, + }; + function formatStringFromArgs(text, args, baseIndex) { + if (baseIndex === void 0) { baseIndex = 0; } + return text.replace(/{(\d+)}/g, function (_match, index) { return "" + ts.Debug.assertDefined(args[+index + baseIndex]); }); + } + ts.formatStringFromArgs = formatStringFromArgs; + function getLocaleSpecificMessage(message) { + return ts.localizedDiagnosticMessages && ts.localizedDiagnosticMessages[message.key] || message.message; + } + ts.getLocaleSpecificMessage = getLocaleSpecificMessage; + function createFileDiagnostic(file, start, length, message) { + ts.Debug.assertGreaterThanOrEqual(start, 0); + ts.Debug.assertGreaterThanOrEqual(length, 0); + if (file) { + ts.Debug.assertLessThanOrEqual(start, file.text.length); + ts.Debug.assertLessThanOrEqual(start + length, file.text.length); + } + var text = getLocaleSpecificMessage(message); + if (arguments.length > 4) { + text = formatStringFromArgs(text, arguments, 4); + } + return { + file: file, + start: start, + length: length, + messageText: text, + category: message.category, + code: message.code, + reportsUnnecessary: message.reportsUnnecessary, + }; + } + ts.createFileDiagnostic = createFileDiagnostic; + function formatMessage(_dummy, message) { + var text = getLocaleSpecificMessage(message); + if (arguments.length > 2) { + text = formatStringFromArgs(text, arguments, 2); + } + return text; + } + ts.formatMessage = formatMessage; + function createCompilerDiagnostic(message) { + var text = getLocaleSpecificMessage(message); + if (arguments.length > 1) { + text = formatStringFromArgs(text, arguments, 1); + } + return { + file: undefined, + start: undefined, + length: undefined, + messageText: text, + category: message.category, + code: message.code, + reportsUnnecessary: message.reportsUnnecessary, + }; + } + ts.createCompilerDiagnostic = createCompilerDiagnostic; + function createCompilerDiagnosticFromMessageChain(chain) { + return { + file: undefined, + start: undefined, + length: undefined, + code: chain.code, + category: chain.category, + messageText: chain.next ? chain : chain.messageText, + }; + } + ts.createCompilerDiagnosticFromMessageChain = createCompilerDiagnosticFromMessageChain; + function chainDiagnosticMessages(details, message) { + var text = getLocaleSpecificMessage(message); + if (arguments.length > 2) { + text = formatStringFromArgs(text, arguments, 2); + } + return { + messageText: text, + category: message.category, + code: message.code, + next: details + }; + } + ts.chainDiagnosticMessages = chainDiagnosticMessages; + function concatenateDiagnosticMessageChains(headChain, tailChain) { + var lastChain = headChain; + while (lastChain.next) { + lastChain = lastChain.next; + } + lastChain.next = tailChain; + return headChain; + } + ts.concatenateDiagnosticMessageChains = concatenateDiagnosticMessageChains; + function getDiagnosticFilePath(diagnostic) { + return diagnostic.file ? diagnostic.file.path : undefined; + } + function compareDiagnostics(d1, d2) { + return compareDiagnosticsSkipRelatedInformation(d1, d2) || + compareRelatedInformation(d1, d2) || + 0 /* EqualTo */; + } + ts.compareDiagnostics = compareDiagnostics; + function compareDiagnosticsSkipRelatedInformation(d1, d2) { + return ts.compareStringsCaseSensitive(getDiagnosticFilePath(d1), getDiagnosticFilePath(d2)) || + ts.compareValues(d1.start, d2.start) || + ts.compareValues(d1.length, d2.length) || + ts.compareValues(d1.code, d2.code) || + compareMessageText(d1.messageText, d2.messageText) || + 0 /* EqualTo */; + } + ts.compareDiagnosticsSkipRelatedInformation = compareDiagnosticsSkipRelatedInformation; + function compareRelatedInformation(d1, d2) { + if (!d1.relatedInformation && !d2.relatedInformation) { + return 0 /* EqualTo */; + } + if (d1.relatedInformation && d2.relatedInformation) { + return ts.compareValues(d1.relatedInformation.length, d2.relatedInformation.length) || ts.forEach(d1.relatedInformation, function (d1i, index) { + var d2i = d2.relatedInformation[index]; + return compareDiagnostics(d1i, d2i); // EqualTo is 0, so falsy, and will cause the next item to be compared + }) || 0 /* EqualTo */; + } + return d1.relatedInformation ? -1 /* LessThan */ : 1 /* GreaterThan */; + } + function compareMessageText(t1, t2) { + var text1 = t1; + var text2 = t2; + while (text1 && text2) { + // We still have both chains. + var string1 = ts.isString(text1) ? text1 : text1.messageText; + var string2 = ts.isString(text2) ? text2 : text2.messageText; + var res = ts.compareStringsCaseSensitive(string1, string2); + if (res) { + return res; + } + text1 = ts.isString(text1) ? undefined : text1.next; + text2 = ts.isString(text2) ? undefined : text2.next; + } + if (!text1 && !text2) { + // if the chains are done, then these messages are the same. + return 0 /* EqualTo */; + } + // We still have one chain remaining. The shorter chain should come first. + return text1 ? 1 /* GreaterThan */ : -1 /* LessThan */; + } + function getEmitScriptTarget(compilerOptions) { + return compilerOptions.target || 0 /* ES3 */; + } + ts.getEmitScriptTarget = getEmitScriptTarget; + function getEmitModuleKind(compilerOptions) { + return typeof compilerOptions.module === "number" ? + compilerOptions.module : + getEmitScriptTarget(compilerOptions) >= 2 /* ES2015 */ ? ts.ModuleKind.ES2015 : ts.ModuleKind.CommonJS; + } + ts.getEmitModuleKind = getEmitModuleKind; + function getEmitModuleResolutionKind(compilerOptions) { + var moduleResolution = compilerOptions.moduleResolution; + if (moduleResolution === undefined) { + moduleResolution = getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS ? ts.ModuleResolutionKind.NodeJs : ts.ModuleResolutionKind.Classic; + } + return moduleResolution; + } + ts.getEmitModuleResolutionKind = getEmitModuleResolutionKind; + function hasJsonModuleEmitEnabled(options) { + switch (getEmitModuleKind(options)) { + case ts.ModuleKind.CommonJS: + case ts.ModuleKind.AMD: + case ts.ModuleKind.ES2015: + case ts.ModuleKind.ESNext: + return true; + default: + return false; + } + } + ts.hasJsonModuleEmitEnabled = hasJsonModuleEmitEnabled; + function unreachableCodeIsError(options) { + return options.allowUnreachableCode === false; + } + ts.unreachableCodeIsError = unreachableCodeIsError; + function unusedLabelIsError(options) { + return options.allowUnusedLabels === false; + } + ts.unusedLabelIsError = unusedLabelIsError; + function getAreDeclarationMapsEnabled(options) { + return !!(getEmitDeclarations(options) && options.declarationMap); + } + ts.getAreDeclarationMapsEnabled = getAreDeclarationMapsEnabled; + function getAllowSyntheticDefaultImports(compilerOptions) { + var moduleKind = getEmitModuleKind(compilerOptions); + return compilerOptions.allowSyntheticDefaultImports !== undefined + ? compilerOptions.allowSyntheticDefaultImports + : compilerOptions.esModuleInterop || + moduleKind === ts.ModuleKind.System; + } + ts.getAllowSyntheticDefaultImports = getAllowSyntheticDefaultImports; + function getEmitDeclarations(compilerOptions) { + return !!(compilerOptions.declaration || compilerOptions.composite); + } + ts.getEmitDeclarations = getEmitDeclarations; + function getStrictOptionValue(compilerOptions, flag) { + return compilerOptions[flag] === undefined ? !!compilerOptions.strict : !!compilerOptions[flag]; + } + ts.getStrictOptionValue = getStrictOptionValue; + function compilerOptionsAffectSemanticDiagnostics(newOptions, oldOptions) { + return oldOptions !== newOptions && + ts.semanticDiagnosticsOptionDeclarations.some(function (option) { return !ts.isJsonEqual(getCompilerOptionValue(oldOptions, option), getCompilerOptionValue(newOptions, option)); }); + } + ts.compilerOptionsAffectSemanticDiagnostics = compilerOptionsAffectSemanticDiagnostics; + function getCompilerOptionValue(options, option) { + return option.strictFlag ? getStrictOptionValue(options, option.name) : options[option.name]; + } + ts.getCompilerOptionValue = getCompilerOptionValue; + function hasZeroOrOneAsteriskCharacter(str) { + var seenAsterisk = false; + for (var i = 0; i < str.length; i++) { + if (str.charCodeAt(i) === 42 /* asterisk */) { + if (!seenAsterisk) { + seenAsterisk = true; + } + else { + // have already seen asterisk + return false; + } + } + } + return true; + } + ts.hasZeroOrOneAsteriskCharacter = hasZeroOrOneAsteriskCharacter; + /** + * Internally, we represent paths as strings with '/' as the directory separator. + * When we make system calls (eg: LanguageServiceHost.getDirectory()), + * we expect the host to correctly handle paths in our specified format. + */ + ts.directorySeparator = "/"; + var altDirectorySeparator = "\\"; + var urlSchemeSeparator = "://"; + var backslashRegExp = /\\/g; + /** + * Normalize path separators. + */ + function normalizeSlashes(path) { + return path.replace(backslashRegExp, ts.directorySeparator); + } + ts.normalizeSlashes = normalizeSlashes; + function isVolumeCharacter(charCode) { + return (charCode >= 97 /* a */ && charCode <= 122 /* z */) || + (charCode >= 65 /* A */ && charCode <= 90 /* Z */); + } + function getFileUrlVolumeSeparatorEnd(url, start) { + var ch0 = url.charCodeAt(start); + if (ch0 === 58 /* colon */) + return start + 1; + if (ch0 === 37 /* percent */ && url.charCodeAt(start + 1) === 51 /* _3 */) { + var ch2 = url.charCodeAt(start + 2); + if (ch2 === 97 /* a */ || ch2 === 65 /* A */) + return start + 3; + } + return -1; + } + /** + * Returns length of the root part of a path or URL (i.e. length of "/", "x:/", "//server/share/, file:///user/files"). + * If the root is part of a URL, the twos-complement of the root length is returned. + */ + function getEncodedRootLength(path) { + if (!path) + return 0; + var ch0 = path.charCodeAt(0); + // POSIX or UNC + if (ch0 === 47 /* slash */ || ch0 === 92 /* backslash */) { + if (path.charCodeAt(1) !== ch0) + return 1; // POSIX: "/" (or non-normalized "\") + var p1 = path.indexOf(ch0 === 47 /* slash */ ? ts.directorySeparator : altDirectorySeparator, 2); + if (p1 < 0) + return path.length; // UNC: "//server" or "\\server" + return p1 + 1; // UNC: "//server/" or "\\server\" + } + // DOS + if (isVolumeCharacter(ch0) && path.charCodeAt(1) === 58 /* colon */) { + var ch2 = path.charCodeAt(2); + if (ch2 === 47 /* slash */ || ch2 === 92 /* backslash */) + return 3; // DOS: "c:/" or "c:\" + if (path.length === 2) + return 2; // DOS: "c:" (but not "c:d") + } + // URL + var schemeEnd = path.indexOf(urlSchemeSeparator); + if (schemeEnd !== -1) { + var authorityStart = schemeEnd + urlSchemeSeparator.length; + var authorityEnd = path.indexOf(ts.directorySeparator, authorityStart); + if (authorityEnd !== -1) { // URL: "file:///", "file://server/", "file://server/path" + // For local "file" URLs, include the leading DOS volume (if present). + // Per https://www.ietf.org/rfc/rfc1738.txt, a host of "" or "localhost" is a + // special case interpreted as "the machine from which the URL is being interpreted". + var scheme = path.slice(0, schemeEnd); + var authority = path.slice(authorityStart, authorityEnd); + if (scheme === "file" && (authority === "" || authority === "localhost") && + isVolumeCharacter(path.charCodeAt(authorityEnd + 1))) { + var volumeSeparatorEnd = getFileUrlVolumeSeparatorEnd(path, authorityEnd + 2); + if (volumeSeparatorEnd !== -1) { + if (path.charCodeAt(volumeSeparatorEnd) === 47 /* slash */) { + // URL: "file:///c:/", "file://localhost/c:/", "file:///c%3a/", "file://localhost/c%3a/" + return ~(volumeSeparatorEnd + 1); + } + if (volumeSeparatorEnd === path.length) { + // URL: "file:///c:", "file://localhost/c:", "file:///c$3a", "file://localhost/c%3a" + // but not "file:///c:d" or "file:///c%3ad" + return ~volumeSeparatorEnd; + } + } + } + return ~(authorityEnd + 1); // URL: "file://server/", "http://server/" + } + return ~path.length; // URL: "file://server", "http://server" + } + // relative + return 0; + } + /** + * Returns length of the root part of a path or URL (i.e. length of "/", "x:/", "//server/share/, file:///user/files"). + * + * For example: + * ```ts + * getRootLength("a") === 0 // "" + * getRootLength("/") === 1 // "/" + * getRootLength("c:") === 2 // "c:" + * getRootLength("c:d") === 0 // "" + * getRootLength("c:/") === 3 // "c:/" + * getRootLength("c:\\") === 3 // "c:\\" + * getRootLength("//server") === 7 // "//server" + * getRootLength("//server/share") === 8 // "//server/" + * getRootLength("\\\\server") === 7 // "\\\\server" + * getRootLength("\\\\server\\share") === 8 // "\\\\server\\" + * getRootLength("file:///path") === 8 // "file:///" + * getRootLength("file:///c:") === 10 // "file:///c:" + * getRootLength("file:///c:d") === 8 // "file:///" + * getRootLength("file:///c:/path") === 11 // "file:///c:/" + * getRootLength("file://server") === 13 // "file://server" + * getRootLength("file://server/path") === 14 // "file://server/" + * getRootLength("http://server") === 13 // "http://server" + * getRootLength("http://server/path") === 14 // "http://server/" + * ``` + */ + function getRootLength(path) { + var rootLength = getEncodedRootLength(path); + return rootLength < 0 ? ~rootLength : rootLength; + } + ts.getRootLength = getRootLength; + // TODO(rbuckton): replace references with `resolvePath` + function normalizePath(path) { + return ts.resolvePath(path); + } + ts.normalizePath = normalizePath; + function normalizePathAndParts(path) { + path = normalizeSlashes(path); + var _a = reducePathComponents(getPathComponents(path)), root = _a[0], parts = _a.slice(1); + if (parts.length) { + var joinedParts = root + parts.join(ts.directorySeparator); + return { path: ts.hasTrailingDirectorySeparator(path) ? ts.ensureTrailingDirectorySeparator(joinedParts) : joinedParts, parts: parts }; + } + else { + return { path: root, parts: parts }; + } + } + ts.normalizePathAndParts = normalizePathAndParts; + function getDirectoryPath(path) { + path = normalizeSlashes(path); + // If the path provided is itself the root, then return it. + var rootLength = getRootLength(path); + if (rootLength === path.length) + return path; + // return the leading portion of the path up to the last (non-terminal) directory separator + // but not including any trailing directory separator. + path = ts.removeTrailingDirectorySeparator(path); + return path.slice(0, Math.max(rootLength, path.lastIndexOf(ts.directorySeparator))); + } + ts.getDirectoryPath = getDirectoryPath; + function startsWithDirectory(fileName, directoryName, getCanonicalFileName) { + var canonicalFileName = getCanonicalFileName(fileName); + var canonicalDirectoryName = getCanonicalFileName(directoryName); + return ts.startsWith(canonicalFileName, canonicalDirectoryName + "/") || ts.startsWith(canonicalFileName, canonicalDirectoryName + "\\"); + } + ts.startsWithDirectory = startsWithDirectory; + function isUrl(path) { + return getEncodedRootLength(path) < 0; + } + ts.isUrl = isUrl; + function pathIsRelative(path) { + return /^\.\.?($|[\\/])/.test(path); + } + ts.pathIsRelative = pathIsRelative; + /** + * Determines whether a path is an absolute path (e.g. starts with `/`, or a dos path + * like `c:`, `c:\` or `c:/`). + */ + function isRootedDiskPath(path) { + return getEncodedRootLength(path) > 0; + } + ts.isRootedDiskPath = isRootedDiskPath; + /** + * Determines whether a path consists only of a path root. + */ + function isDiskPathRoot(path) { + var rootLength = getEncodedRootLength(path); + return rootLength > 0 && rootLength === path.length; + } + ts.isDiskPathRoot = isDiskPathRoot; + function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) { + return !isRootedDiskPath(absoluteOrRelativePath) + ? absoluteOrRelativePath + : ts.getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); + } + ts.convertToRelativePath = convertToRelativePath; + function pathComponents(path, rootLength) { + var root = path.substring(0, rootLength); + var rest = path.substring(rootLength).split(ts.directorySeparator); + if (rest.length && !ts.lastOrUndefined(rest)) + rest.pop(); + return [root].concat(rest); + } + /** + * Parse a path into an array containing a root component (at index 0) and zero or more path + * components (at indices > 0). The result is not normalized. + * If the path is relative, the root component is `""`. + * If the path is absolute, the root component includes the first path separator (`/`). + */ + function getPathComponents(path, currentDirectory) { + if (currentDirectory === void 0) { currentDirectory = ""; } + path = ts.combinePaths(currentDirectory, path); + var rootLength = getRootLength(path); + return pathComponents(path, rootLength); + } + ts.getPathComponents = getPathComponents; + /** + * Reduce an array of path components to a more simplified path by navigating any + * `"."` or `".."` entries in the path. + */ + function reducePathComponents(components) { + if (!ts.some(components)) + return []; + var reduced = [components[0]]; + for (var i = 1; i < components.length; i++) { + var component = components[i]; + if (!component) + continue; + if (component === ".") + continue; + if (component === "..") { + if (reduced.length > 1) { + if (reduced[reduced.length - 1] !== "..") { + reduced.pop(); + continue; + } + } + else if (reduced[0]) + continue; + } + reduced.push(component); + } + return reduced; + } + ts.reducePathComponents = reducePathComponents; + /** + * Parse a path into an array containing a root component (at index 0) and zero or more path + * components (at indices > 0). The result is normalized. + * If the path is relative, the root component is `""`. + * If the path is absolute, the root component includes the first path separator (`/`). + */ + function getNormalizedPathComponents(path, currentDirectory) { + return reducePathComponents(getPathComponents(path, currentDirectory)); + } + ts.getNormalizedPathComponents = getNormalizedPathComponents; + function getNormalizedAbsolutePath(fileName, currentDirectory) { + return getPathFromPathComponents(getNormalizedPathComponents(fileName, currentDirectory)); + } + ts.getNormalizedAbsolutePath = getNormalizedAbsolutePath; + /** + * Formats a parsed path consisting of a root component (at index 0) and zero or more path + * segments (at indices > 0). + */ + function getPathFromPathComponents(pathComponents) { + if (pathComponents.length === 0) + return ""; + var root = pathComponents[0] && ts.ensureTrailingDirectorySeparator(pathComponents[0]); + return root + pathComponents.slice(1).join(ts.directorySeparator); + } + ts.getPathFromPathComponents = getPathFromPathComponents; +})(ts || (ts = {})); +/* @internal */ +(function (ts) { + function getPathComponentsRelativeTo(from, to, stringEqualityComparer, getCanonicalFileName) { + var fromComponents = ts.reducePathComponents(ts.getPathComponents(from)); + var toComponents = ts.reducePathComponents(ts.getPathComponents(to)); + var start; + for (start = 0; start < fromComponents.length && start < toComponents.length; start++) { + var fromComponent = getCanonicalFileName(fromComponents[start]); + var toComponent = getCanonicalFileName(toComponents[start]); + var comparer = start === 0 ? ts.equateStringsCaseInsensitive : stringEqualityComparer; + if (!comparer(fromComponent, toComponent)) + break; + } + if (start === 0) { + return toComponents; + } + var components = toComponents.slice(start); + var relative = []; + for (; start < fromComponents.length; start++) { + relative.push(".."); + } + return [""].concat(relative, components); + } + ts.getPathComponentsRelativeTo = getPathComponentsRelativeTo; + function getRelativePathFromFile(from, to, getCanonicalFileName) { + return ensurePathIsNonModuleName(getRelativePathFromDirectory(ts.getDirectoryPath(from), to, getCanonicalFileName)); + } + ts.getRelativePathFromFile = getRelativePathFromFile; + function getRelativePathFromDirectory(fromDirectory, to, getCanonicalFileNameOrIgnoreCase) { + Debug.assert((ts.getRootLength(fromDirectory) > 0) === (ts.getRootLength(to) > 0), "Paths must either both be absolute or both be relative"); + var getCanonicalFileName = typeof getCanonicalFileNameOrIgnoreCase === "function" ? getCanonicalFileNameOrIgnoreCase : ts.identity; + var ignoreCase = typeof getCanonicalFileNameOrIgnoreCase === "boolean" ? getCanonicalFileNameOrIgnoreCase : false; + var pathComponents = getPathComponentsRelativeTo(fromDirectory, to, ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive, getCanonicalFileName); + return ts.getPathFromPathComponents(pathComponents); + } + ts.getRelativePathFromDirectory = getRelativePathFromDirectory; + function getRelativePathToDirectoryOrUrl(directoryPathOrUrl, relativeOrAbsolutePath, currentDirectory, getCanonicalFileName, isAbsolutePathAnUrl) { + var pathComponents = getPathComponentsRelativeTo(resolvePath(currentDirectory, directoryPathOrUrl), resolvePath(currentDirectory, relativeOrAbsolutePath), ts.equateStringsCaseSensitive, getCanonicalFileName); + var firstComponent = pathComponents[0]; + if (isAbsolutePathAnUrl && ts.isRootedDiskPath(firstComponent)) { + var prefix = firstComponent.charAt(0) === ts.directorySeparator ? "file://" : "file:///"; + pathComponents[0] = prefix + firstComponent; + } + return ts.getPathFromPathComponents(pathComponents); + } + ts.getRelativePathToDirectoryOrUrl = getRelativePathToDirectoryOrUrl; + /** + * Ensures a path is either absolute (prefixed with `/` or `c:`) or dot-relative (prefixed + * with `./` or `../`) so as not to be confused with an unprefixed module name. + */ + function ensurePathIsNonModuleName(path) { + return ts.getRootLength(path) === 0 && !ts.pathIsRelative(path) ? "./" + path : path; + } + ts.ensurePathIsNonModuleName = ensurePathIsNonModuleName; + function getBaseFileName(path, extensions, ignoreCase) { + path = ts.normalizeSlashes(path); + // if the path provided is itself the root, then it has not file name. + var rootLength = ts.getRootLength(path); + if (rootLength === path.length) + return ""; + // return the trailing portion of the path starting after the last (non-terminal) directory + // separator but not including any trailing directory separator. + path = removeTrailingDirectorySeparator(path); + var name = path.slice(Math.max(ts.getRootLength(path), path.lastIndexOf(ts.directorySeparator) + 1)); + var extension = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(name, extensions, ignoreCase) : undefined; + return extension ? name.slice(0, name.length - extension.length) : name; + } + ts.getBaseFileName = getBaseFileName; + /** + * Combines paths. If a path is absolute, it replaces any previous path. + */ + function combinePaths(path) { + var paths = []; + for (var _i = 1; _i < arguments.length; _i++) { + paths[_i - 1] = arguments[_i]; + } + if (path) + path = ts.normalizeSlashes(path); + for (var _a = 0, paths_1 = paths; _a < paths_1.length; _a++) { + var relativePath = paths_1[_a]; + if (!relativePath) + continue; + relativePath = ts.normalizeSlashes(relativePath); + if (!path || ts.getRootLength(relativePath) !== 0) { + path = relativePath; + } + else { + path = ensureTrailingDirectorySeparator(path) + relativePath; + } + } + return path; + } + ts.combinePaths = combinePaths; + /** + * Combines and resolves paths. If a path is absolute, it replaces any previous path. Any + * `.` and `..` path components are resolved. + */ + function resolvePath(path) { + var paths = []; + for (var _i = 1; _i < arguments.length; _i++) { + paths[_i - 1] = arguments[_i]; + } + var combined = ts.some(paths) ? combinePaths.apply(void 0, [path].concat(paths)) : ts.normalizeSlashes(path); + var normalized = ts.getPathFromPathComponents(ts.reducePathComponents(ts.getPathComponents(combined))); + return normalized && hasTrailingDirectorySeparator(combined) ? ensureTrailingDirectorySeparator(normalized) : normalized; + } + ts.resolvePath = resolvePath; + /** + * Determines whether a path has a trailing separator (`/` or `\\`). + */ + function hasTrailingDirectorySeparator(path) { + if (path.length === 0) + return false; + var ch = path.charCodeAt(path.length - 1); + return ch === 47 /* slash */ || ch === 92 /* backslash */; + } + ts.hasTrailingDirectorySeparator = hasTrailingDirectorySeparator; + function removeTrailingDirectorySeparator(path) { + if (hasTrailingDirectorySeparator(path)) { + return path.substr(0, path.length - 1); + } + return path; + } + ts.removeTrailingDirectorySeparator = removeTrailingDirectorySeparator; + function ensureTrailingDirectorySeparator(path) { + if (!hasTrailingDirectorySeparator(path)) { + return path + ts.directorySeparator; + } + return path; + } + ts.ensureTrailingDirectorySeparator = ensureTrailingDirectorySeparator; + function comparePathsWorker(a, b, componentComparer) { + if (a === b) + return 0 /* EqualTo */; + if (a === undefined) + return -1 /* LessThan */; + if (b === undefined) + return 1 /* GreaterThan */; + var aComponents = ts.reducePathComponents(ts.getPathComponents(a)); + var bComponents = ts.reducePathComponents(ts.getPathComponents(b)); + var sharedLength = Math.min(aComponents.length, bComponents.length); + for (var i = 0; i < sharedLength; i++) { + var stringComparer = i === 0 ? ts.compareStringsCaseInsensitive : componentComparer; + var result = stringComparer(aComponents[i], bComponents[i]); + if (result !== 0 /* EqualTo */) { + return result; + } + } + return ts.compareValues(aComponents.length, bComponents.length); + } + /** + * Performs a case-sensitive comparison of two paths. + */ + function comparePathsCaseSensitive(a, b) { + return comparePathsWorker(a, b, ts.compareStringsCaseSensitive); + } + ts.comparePathsCaseSensitive = comparePathsCaseSensitive; + /** + * Performs a case-insensitive comparison of two paths. + */ + function comparePathsCaseInsensitive(a, b) { + return comparePathsWorker(a, b, ts.compareStringsCaseInsensitive); + } + ts.comparePathsCaseInsensitive = comparePathsCaseInsensitive; + function comparePaths(a, b, currentDirectory, ignoreCase) { + if (typeof currentDirectory === "string") { + a = combinePaths(currentDirectory, a); + b = combinePaths(currentDirectory, b); + } + else if (typeof currentDirectory === "boolean") { + ignoreCase = currentDirectory; + } + return comparePathsWorker(a, b, ts.getStringComparer(ignoreCase)); + } + ts.comparePaths = comparePaths; + function containsPath(parent, child, currentDirectory, ignoreCase) { + if (typeof currentDirectory === "string") { + parent = combinePaths(currentDirectory, parent); + child = combinePaths(currentDirectory, child); + } + else if (typeof currentDirectory === "boolean") { + ignoreCase = currentDirectory; + } + if (parent === undefined || child === undefined) + return false; + if (parent === child) + return true; + var parentComponents = ts.reducePathComponents(ts.getPathComponents(parent)); + var childComponents = ts.reducePathComponents(ts.getPathComponents(child)); + if (childComponents.length < parentComponents.length) { + return false; + } + var componentEqualityComparer = ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive; + for (var i = 0; i < parentComponents.length; i++) { + var equalityComparer = i === 0 ? ts.equateStringsCaseInsensitive : componentEqualityComparer; + if (!equalityComparer(parentComponents[i], childComponents[i])) { + return false; + } + } + return true; + } + ts.containsPath = containsPath; + function isDirectorySeparator(charCode) { + return charCode === 47 /* slash */ || charCode === 92 /* backslash */; + } + function stripLeadingDirectorySeparator(s) { + return isDirectorySeparator(s.charCodeAt(0)) ? s.slice(1) : undefined; + } + function tryRemoveDirectoryPrefix(path, dirPath, getCanonicalFileName) { + var withoutPrefix = ts.tryRemovePrefix(path, dirPath, getCanonicalFileName); + return withoutPrefix === undefined ? undefined : stripLeadingDirectorySeparator(withoutPrefix); + } + ts.tryRemoveDirectoryPrefix = tryRemoveDirectoryPrefix; + // Reserved characters, forces escaping of any non-word (or digit), non-whitespace character. + // It may be inefficient (we could just match (/[-[\]{}()*+?.,\\^$|#\s]/g), but this is future + // proof. + var reservedCharacterPattern = /[^\w\s\/]/g; + function regExpEscape(text) { + return text.replace(reservedCharacterPattern, escapeRegExpCharacter); + } + ts.regExpEscape = regExpEscape; + function escapeRegExpCharacter(match) { + return "\\" + match; + } + var wildcardCharCodes = [42 /* asterisk */, 63 /* question */]; + function hasExtension(fileName) { + return ts.stringContains(getBaseFileName(fileName), "."); + } + ts.hasExtension = hasExtension; + ts.commonPackageFolders = ["node_modules", "bower_components", "jspm_packages"]; + var implicitExcludePathRegexPattern = "(?!(" + ts.commonPackageFolders.join("|") + ")(/|$))"; + var filesMatcher = { + /** + * Matches any single directory segment unless it is the last segment and a .min.js file + * Breakdown: + * [^./] # matches everything up to the first . character (excluding directory separators) + * (\\.(?!min\\.js$))? # matches . characters but not if they are part of the .min.js file extension + */ + singleAsteriskRegexFragment: "([^./]|(\\.(?!min\\.js$))?)*", + /** + * Regex for the ** wildcard. Matches any number of subdirectories. When used for including + * files or directories, does not match subdirectories that start with a . character + */ + doubleAsteriskRegexFragment: "(/" + implicitExcludePathRegexPattern + "[^/.][^/]*)*?", + replaceWildcardCharacter: function (match) { return replaceWildcardCharacter(match, filesMatcher.singleAsteriskRegexFragment); } + }; + var directoriesMatcher = { + singleAsteriskRegexFragment: "[^/]*", + /** + * Regex for the ** wildcard. Matches any number of subdirectories. When used for including + * files or directories, does not match subdirectories that start with a . character + */ + doubleAsteriskRegexFragment: "(/" + implicitExcludePathRegexPattern + "[^/.][^/]*)*?", + replaceWildcardCharacter: function (match) { return replaceWildcardCharacter(match, directoriesMatcher.singleAsteriskRegexFragment); } + }; + var excludeMatcher = { + singleAsteriskRegexFragment: "[^/]*", + doubleAsteriskRegexFragment: "(/.+?)?", + replaceWildcardCharacter: function (match) { return replaceWildcardCharacter(match, excludeMatcher.singleAsteriskRegexFragment); } + }; + var wildcardMatchers = { + files: filesMatcher, + directories: directoriesMatcher, + exclude: excludeMatcher + }; + function getRegularExpressionForWildcard(specs, basePath, usage) { + var patterns = getRegularExpressionsForWildcards(specs, basePath, usage); + if (!patterns || !patterns.length) { + return undefined; + } + var pattern = patterns.map(function (pattern) { return "(" + pattern + ")"; }).join("|"); + // If excluding, match "foo/bar/baz...", but if including, only allow "foo". + var terminator = usage === "exclude" ? "($|/)" : "$"; + return "^(" + pattern + ")" + terminator; + } + ts.getRegularExpressionForWildcard = getRegularExpressionForWildcard; + function getRegularExpressionsForWildcards(specs, basePath, usage) { + if (specs === undefined || specs.length === 0) { + return undefined; + } + return ts.flatMap(specs, function (spec) { + return spec && getSubPatternFromSpec(spec, basePath, usage, wildcardMatchers[usage]); + }); + } + ts.getRegularExpressionsForWildcards = getRegularExpressionsForWildcards; + /** + * An "includes" path "foo" is implicitly a glob "foo/** /*" (without the space) if its last component has no extension, + * and does not contain any glob characters itself. + */ + function isImplicitGlob(lastPathComponent) { + return !/[.*?]/.test(lastPathComponent); + } + ts.isImplicitGlob = isImplicitGlob; + function getSubPatternFromSpec(spec, basePath, usage, _a) { + var singleAsteriskRegexFragment = _a.singleAsteriskRegexFragment, doubleAsteriskRegexFragment = _a.doubleAsteriskRegexFragment, replaceWildcardCharacter = _a.replaceWildcardCharacter; + var subpattern = ""; + var hasWrittenComponent = false; + var components = ts.getNormalizedPathComponents(spec, basePath); + var lastComponent = ts.last(components); + if (usage !== "exclude" && lastComponent === "**") { + return undefined; + } + // getNormalizedPathComponents includes the separator for the root component. + // We need to remove to create our regex correctly. + components[0] = removeTrailingDirectorySeparator(components[0]); + if (isImplicitGlob(lastComponent)) { + components.push("**", "*"); + } + var optionalCount = 0; + for (var _i = 0, components_1 = components; _i < components_1.length; _i++) { + var component = components_1[_i]; + if (component === "**") { + subpattern += doubleAsteriskRegexFragment; + } + else { + if (usage === "directories") { + subpattern += "("; + optionalCount++; + } + if (hasWrittenComponent) { + subpattern += ts.directorySeparator; + } + if (usage !== "exclude") { + var componentPattern = ""; + // The * and ? wildcards should not match directories or files that start with . if they + // appear first in a component. Dotted directories and files can be included explicitly + // like so: **/.*/.* + if (component.charCodeAt(0) === 42 /* asterisk */) { + componentPattern += "([^./]" + singleAsteriskRegexFragment + ")?"; + component = component.substr(1); + } + else if (component.charCodeAt(0) === 63 /* question */) { + componentPattern += "[^./]"; + component = component.substr(1); + } + componentPattern += component.replace(reservedCharacterPattern, replaceWildcardCharacter); + // Patterns should not include subfolders like node_modules unless they are + // explicitly included as part of the path. + // + // As an optimization, if the component pattern is the same as the component, + // then there definitely were no wildcard characters and we do not need to + // add the exclusion pattern. + if (componentPattern !== component) { + subpattern += implicitExcludePathRegexPattern; + } + subpattern += componentPattern; + } + else { + subpattern += component.replace(reservedCharacterPattern, replaceWildcardCharacter); + } + } + hasWrittenComponent = true; + } + while (optionalCount > 0) { + subpattern += ")?"; + optionalCount--; + } + return subpattern; + } + function replaceWildcardCharacter(match, singleAsteriskRegexFragment) { + return match === "*" ? singleAsteriskRegexFragment : match === "?" ? "[^/]" : "\\" + match; + } + /** @param path directory of the tsconfig.json */ + function getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory) { + path = ts.normalizePath(path); + currentDirectory = ts.normalizePath(currentDirectory); + var absolutePath = combinePaths(currentDirectory, path); + return { + includeFilePatterns: ts.map(getRegularExpressionsForWildcards(includes, absolutePath, "files"), function (pattern) { return "^" + pattern + "$"; }), + includeFilePattern: getRegularExpressionForWildcard(includes, absolutePath, "files"), + includeDirectoryPattern: getRegularExpressionForWildcard(includes, absolutePath, "directories"), + excludePattern: getRegularExpressionForWildcard(excludes, absolutePath, "exclude"), + basePaths: getBasePaths(path, includes, useCaseSensitiveFileNames) + }; + } + ts.getFileMatcherPatterns = getFileMatcherPatterns; + function getRegexFromPattern(pattern, useCaseSensitiveFileNames) { + return new RegExp(pattern, useCaseSensitiveFileNames ? "" : "i"); + } + ts.getRegexFromPattern = getRegexFromPattern; + /** @param path directory of the tsconfig.json */ + function matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries) { + path = ts.normalizePath(path); + currentDirectory = ts.normalizePath(currentDirectory); + var patterns = getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory); + var includeFileRegexes = patterns.includeFilePatterns && patterns.includeFilePatterns.map(function (pattern) { return getRegexFromPattern(pattern, useCaseSensitiveFileNames); }); + var includeDirectoryRegex = patterns.includeDirectoryPattern && getRegexFromPattern(patterns.includeDirectoryPattern, useCaseSensitiveFileNames); + var excludeRegex = patterns.excludePattern && getRegexFromPattern(patterns.excludePattern, useCaseSensitiveFileNames); + // Associate an array of results with each include regex. This keeps results in order of the "include" order. + // If there are no "includes", then just put everything in results[0]. + var results = includeFileRegexes ? includeFileRegexes.map(function () { return []; }) : [[]]; + for (var _i = 0, _a = patterns.basePaths; _i < _a.length; _i++) { + var basePath = _a[_i]; + visitDirectory(basePath, combinePaths(currentDirectory, basePath), depth); + } + return ts.flatten(results); + function visitDirectory(path, absolutePath, depth) { + var _a = getFileSystemEntries(path), files = _a.files, directories = _a.directories; + var _loop_1 = function (current) { + var name = combinePaths(path, current); + var absoluteName = combinePaths(absolutePath, current); + if (extensions && !ts.fileExtensionIsOneOf(name, extensions)) + return "continue"; + if (excludeRegex && excludeRegex.test(absoluteName)) + return "continue"; + if (!includeFileRegexes) { + results[0].push(name); + } + else { + var includeIndex = ts.findIndex(includeFileRegexes, function (re) { return re.test(absoluteName); }); + if (includeIndex !== -1) { + results[includeIndex].push(name); + } + } + }; + for (var _i = 0, _b = ts.sort(files, ts.compareStringsCaseSensitive); _i < _b.length; _i++) { + var current = _b[_i]; + _loop_1(current); + } + if (depth !== undefined) { + depth--; + if (depth === 0) { + return; + } + } + for (var _c = 0, _d = ts.sort(directories, ts.compareStringsCaseSensitive); _c < _d.length; _c++) { + var current = _d[_c]; + var name = combinePaths(path, current); + var absoluteName = combinePaths(absolutePath, current); + if ((!includeDirectoryRegex || includeDirectoryRegex.test(absoluteName)) && + (!excludeRegex || !excludeRegex.test(absoluteName))) { + visitDirectory(name, absoluteName, depth); + } + } + } + } + ts.matchFiles = matchFiles; + /** + * Computes the unique non-wildcard base paths amongst the provided include patterns. + */ + function getBasePaths(path, includes, useCaseSensitiveFileNames) { + // Storage for our results in the form of literal paths (e.g. the paths as written by the user). + var basePaths = [path]; + if (includes) { + // Storage for literal base paths amongst the include patterns. + var includeBasePaths = []; + for (var _i = 0, includes_1 = includes; _i < includes_1.length; _i++) { + var include = includes_1[_i]; + // We also need to check the relative paths by converting them to absolute and normalizing + // in case they escape the base path (e.g "..\somedirectory") + var absolute = ts.isRootedDiskPath(include) ? include : ts.normalizePath(combinePaths(path, include)); + // Append the literal and canonical candidate base paths. + includeBasePaths.push(getIncludeBasePath(absolute)); + } + // Sort the offsets array using either the literal or canonical path representations. + includeBasePaths.sort(ts.getStringComparer(!useCaseSensitiveFileNames)); + var _loop_2 = function (includeBasePath) { + if (ts.every(basePaths, function (basePath) { return !containsPath(basePath, includeBasePath, path, !useCaseSensitiveFileNames); })) { + basePaths.push(includeBasePath); + } + }; + // Iterate over each include base path and include unique base paths that are not a + // subpath of an existing base path + for (var _a = 0, includeBasePaths_1 = includeBasePaths; _a < includeBasePaths_1.length; _a++) { + var includeBasePath = includeBasePaths_1[_a]; + _loop_2(includeBasePath); + } + } + return basePaths; + } + function getIncludeBasePath(absolute) { + var wildcardOffset = ts.indexOfAnyCharCode(absolute, wildcardCharCodes); + if (wildcardOffset < 0) { + // No "*" or "?" in the path + return !hasExtension(absolute) + ? absolute + : removeTrailingDirectorySeparator(ts.getDirectoryPath(absolute)); + } + return absolute.substring(0, absolute.lastIndexOf(ts.directorySeparator, wildcardOffset)); + } + function ensureScriptKind(fileName, scriptKind) { + // Using scriptKind as a condition handles both: + // - 'scriptKind' is unspecified and thus it is `undefined` + // - 'scriptKind' is set and it is `Unknown` (0) + // If the 'scriptKind' is 'undefined' or 'Unknown' then we attempt + // to get the ScriptKind from the file name. If it cannot be resolved + // from the file name then the default 'TS' script kind is returned. + return scriptKind || getScriptKindFromFileName(fileName) || 3 /* TS */; + } + ts.ensureScriptKind = ensureScriptKind; + function getScriptKindFromFileName(fileName) { + var ext = fileName.substr(fileName.lastIndexOf(".")); + switch (ext.toLowerCase()) { + case ".js" /* Js */: + return 1 /* JS */; + case ".jsx" /* Jsx */: + return 2 /* JSX */; + case ".ts" /* Ts */: + return 3 /* TS */; + case ".tsx" /* Tsx */: + return 4 /* TSX */; + case ".json" /* Json */: + return 6 /* JSON */; + default: + return 0 /* Unknown */; + } + } + ts.getScriptKindFromFileName = getScriptKindFromFileName; + /** + * List of supported extensions in order of file resolution precedence. + */ + ts.supportedTSExtensions = [".ts" /* Ts */, ".tsx" /* Tsx */, ".d.ts" /* Dts */]; + ts.supportedTSExtensionsWithJson = [".ts" /* Ts */, ".tsx" /* Tsx */, ".d.ts" /* Dts */, ".json" /* Json */]; + /** Must have ".d.ts" first because if ".ts" goes first, that will be detected as the extension instead of ".d.ts". */ + ts.supportedTSExtensionsForExtractExtension = [".d.ts" /* Dts */, ".ts" /* Ts */, ".tsx" /* Tsx */]; + ts.supportedJSExtensions = [".js" /* Js */, ".jsx" /* Jsx */]; + ts.supportedJSAndJsonExtensions = [".js" /* Js */, ".jsx" /* Jsx */, ".json" /* Json */]; + var allSupportedExtensions = ts.supportedTSExtensions.concat(ts.supportedJSExtensions); + var allSupportedExtensionsWithJson = ts.supportedTSExtensions.concat(ts.supportedJSExtensions, [".json" /* Json */]); + function getSupportedExtensions(options, extraFileExtensions) { + var needJsExtensions = options && options.allowJs; + if (!extraFileExtensions || extraFileExtensions.length === 0) { + return needJsExtensions ? allSupportedExtensions : ts.supportedTSExtensions; + } + var extensions = (needJsExtensions ? allSupportedExtensions : ts.supportedTSExtensions).concat(ts.mapDefined(extraFileExtensions, function (x) { return x.scriptKind === 7 /* Deferred */ || needJsExtensions && isJSLike(x.scriptKind) ? x.extension : undefined; })); + return ts.deduplicate(extensions, ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive); + } + ts.getSupportedExtensions = getSupportedExtensions; + function getSuppoertedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions) { + if (!options || !options.resolveJsonModule) { + return supportedExtensions; + } + if (supportedExtensions === allSupportedExtensions) { + return allSupportedExtensionsWithJson; + } + if (supportedExtensions === ts.supportedTSExtensions) { + return ts.supportedTSExtensionsWithJson; + } + return supportedExtensions.concat([".json" /* Json */]); + } + ts.getSuppoertedExtensionsWithJsonIfResolveJsonModule = getSuppoertedExtensionsWithJsonIfResolveJsonModule; + function isJSLike(scriptKind) { + return scriptKind === 1 /* JS */ || scriptKind === 2 /* JSX */; + } + function hasJSFileExtension(fileName) { + return ts.some(ts.supportedJSExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + } + ts.hasJSFileExtension = hasJSFileExtension; + function hasJSOrJsonFileExtension(fileName) { + return ts.supportedJSAndJsonExtensions.some(function (ext) { return ts.fileExtensionIs(fileName, ext); }); + } + ts.hasJSOrJsonFileExtension = hasJSOrJsonFileExtension; + function hasTSFileExtension(fileName) { + return ts.some(ts.supportedTSExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + } + ts.hasTSFileExtension = hasTSFileExtension; + function isSupportedSourceFileName(fileName, compilerOptions, extraFileExtensions) { + if (!fileName) { + return false; + } + var supportedExtensions = getSupportedExtensions(compilerOptions, extraFileExtensions); + for (var _i = 0, _a = getSuppoertedExtensionsWithJsonIfResolveJsonModule(compilerOptions, supportedExtensions); _i < _a.length; _i++) { + var extension = _a[_i]; + if (ts.fileExtensionIs(fileName, extension)) { + return true; + } + } + return false; + } + ts.isSupportedSourceFileName = isSupportedSourceFileName; + /** + * Extension boundaries by priority. Lower numbers indicate higher priorities, and are + * aligned to the offset of the highest priority extension in the + * allSupportedExtensions array. + */ + var ExtensionPriority; + (function (ExtensionPriority) { + ExtensionPriority[ExtensionPriority["TypeScriptFiles"] = 0] = "TypeScriptFiles"; + ExtensionPriority[ExtensionPriority["DeclarationAndJavaScriptFiles"] = 2] = "DeclarationAndJavaScriptFiles"; + ExtensionPriority[ExtensionPriority["Highest"] = 0] = "Highest"; + ExtensionPriority[ExtensionPriority["Lowest"] = 2] = "Lowest"; + })(ExtensionPriority = ts.ExtensionPriority || (ts.ExtensionPriority = {})); + function getExtensionPriority(path, supportedExtensions) { + for (var i = supportedExtensions.length - 1; i >= 0; i--) { + if (ts.fileExtensionIs(path, supportedExtensions[i])) { + return adjustExtensionPriority(i, supportedExtensions); + } + } + // If its not in the list of supported extensions, this is likely a + // TypeScript file with a non-ts extension + return 0 /* Highest */; + } + ts.getExtensionPriority = getExtensionPriority; + /** + * Adjusts an extension priority to be the highest priority within the same range. + */ + function adjustExtensionPriority(extensionPriority, supportedExtensions) { + if (extensionPriority < 2 /* DeclarationAndJavaScriptFiles */) { + return 0 /* TypeScriptFiles */; + } + else if (extensionPriority < supportedExtensions.length) { + return 2 /* DeclarationAndJavaScriptFiles */; + } + else { + return supportedExtensions.length; + } + } + ts.adjustExtensionPriority = adjustExtensionPriority; + /** + * Gets the next lowest extension priority for a given priority. + */ + function getNextLowestExtensionPriority(extensionPriority, supportedExtensions) { + if (extensionPriority < 2 /* DeclarationAndJavaScriptFiles */) { + return 2 /* DeclarationAndJavaScriptFiles */; + } + else { + return supportedExtensions.length; + } + } + ts.getNextLowestExtensionPriority = getNextLowestExtensionPriority; + var extensionsToRemove = [".d.ts" /* Dts */, ".ts" /* Ts */, ".js" /* Js */, ".tsx" /* Tsx */, ".jsx" /* Jsx */, ".json" /* Json */]; + function removeFileExtension(path) { + for (var _i = 0, extensionsToRemove_1 = extensionsToRemove; _i < extensionsToRemove_1.length; _i++) { + var ext = extensionsToRemove_1[_i]; + var extensionless = tryRemoveExtension(path, ext); + if (extensionless !== undefined) { + return extensionless; + } + } + return path; + } + ts.removeFileExtension = removeFileExtension; + function tryRemoveExtension(path, extension) { + return ts.fileExtensionIs(path, extension) ? removeExtension(path, extension) : undefined; + } + ts.tryRemoveExtension = tryRemoveExtension; + function removeExtension(path, extension) { + return path.substring(0, path.length - extension.length); + } + ts.removeExtension = removeExtension; + function changeExtension(path, newExtension) { + return changeAnyExtension(path, newExtension, extensionsToRemove, /*ignoreCase*/ false); + } + ts.changeExtension = changeExtension; + function changeAnyExtension(path, ext, extensions, ignoreCase) { + var pathext = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(path, extensions, ignoreCase) : getAnyExtensionFromPath(path); + return pathext ? path.slice(0, path.length - pathext.length) + (ts.startsWith(ext, ".") ? ext : "." + ext) : path; + } + ts.changeAnyExtension = changeAnyExtension; + var Debug; + (function (Debug) { + function showSymbol(symbol) { + var symbolFlags = ts.SymbolFlags; + return "{ flags: " + (symbolFlags ? showFlags(symbol.flags, symbolFlags) : symbol.flags) + "; declarations: " + ts.map(symbol.declarations, showSyntaxKind) + " }"; + } + Debug.showSymbol = showSymbol; + function showFlags(flags, flagsEnum) { + var out = []; + for (var pow = 0; pow <= 30; pow++) { + var n = 1 << pow; + if (flags & n) { + out.push(flagsEnum[n]); + } + } + return out.join("|"); + } + function showSyntaxKind(node) { + var syntaxKind = ts.SyntaxKind; + return syntaxKind ? syntaxKind[node.kind] : node.kind.toString(); + } + Debug.showSyntaxKind = showSyntaxKind; + })(Debug = ts.Debug || (ts.Debug = {})); + function tryParsePattern(pattern) { + // This should be verified outside of here and a proper error thrown. + Debug.assert(ts.hasZeroOrOneAsteriskCharacter(pattern)); + var indexOfStar = pattern.indexOf("*"); + return indexOfStar === -1 ? undefined : { + prefix: pattern.substr(0, indexOfStar), + suffix: pattern.substr(indexOfStar + 1) + }; + } + ts.tryParsePattern = tryParsePattern; + function positionIsSynthesized(pos) { + // This is a fast way of testing the following conditions: + // pos === undefined || pos === null || isNaN(pos) || pos < 0; + return !(pos >= 0); + } + ts.positionIsSynthesized = positionIsSynthesized; + /** True if an extension is one of the supported TypeScript extensions. */ + function extensionIsTS(ext) { + return ext === ".ts" /* Ts */ || ext === ".tsx" /* Tsx */ || ext === ".d.ts" /* Dts */; + } + ts.extensionIsTS = extensionIsTS; + function resolutionExtensionIsTSOrJson(ext) { + return extensionIsTS(ext) || ext === ".json" /* Json */; + } + ts.resolutionExtensionIsTSOrJson = resolutionExtensionIsTSOrJson; + /** + * Gets the extension from a path. + * Path must have a valid extension. + */ + function extensionFromPath(path) { + var ext = tryGetExtensionFromPath(path); + return ext !== undefined ? ext : Debug.fail("File " + path + " has unknown extension."); + } + ts.extensionFromPath = extensionFromPath; + function isAnySupportedFileExtension(path) { + return tryGetExtensionFromPath(path) !== undefined; + } + ts.isAnySupportedFileExtension = isAnySupportedFileExtension; + function tryGetExtensionFromPath(path) { + return ts.find(extensionsToRemove, function (e) { return ts.fileExtensionIs(path, e); }); + } + ts.tryGetExtensionFromPath = tryGetExtensionFromPath; + function getAnyExtensionFromPathWorker(path, extensions, stringEqualityComparer) { + if (typeof extensions === "string") + extensions = [extensions]; + for (var _i = 0, extensions_2 = extensions; _i < extensions_2.length; _i++) { + var extension = extensions_2[_i]; + if (!ts.startsWith(extension, ".")) + extension = "." + extension; + if (path.length >= extension.length && path.charAt(path.length - extension.length) === ".") { + var pathExtension = path.slice(path.length - extension.length); + if (stringEqualityComparer(pathExtension, extension)) { + return pathExtension; + } + } + } + return ""; + } + function getAnyExtensionFromPath(path, extensions, ignoreCase) { + // Retrieves any string from the final "." onwards from a base file name. + // Unlike extensionFromPath, which throws an exception on unrecognized extensions. + if (extensions) { + return getAnyExtensionFromPathWorker(path, extensions, ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive); + } + var baseFileName = getBaseFileName(path); + var extensionIndex = baseFileName.lastIndexOf("."); + if (extensionIndex >= 0) { + return baseFileName.substring(extensionIndex); + } + return ""; + } + ts.getAnyExtensionFromPath = getAnyExtensionFromPath; + function isCheckJsEnabledForFile(sourceFile, compilerOptions) { + return sourceFile.checkJsDirective ? sourceFile.checkJsDirective.enabled : compilerOptions.checkJs; + } + ts.isCheckJsEnabledForFile = isCheckJsEnabledForFile; + ts.emptyFileSystemEntries = { + files: ts.emptyArray, + directories: ts.emptyArray + }; + /** + * patternStrings contains both pattern strings (containing "*") and regular strings. + * Return an exact match if possible, or a pattern match, or undefined. + * (These are verified by verifyCompilerOptions to have 0 or 1 "*" characters.) + */ + function matchPatternOrExact(patternStrings, candidate) { + var patterns = []; + for (var _i = 0, patternStrings_1 = patternStrings; _i < patternStrings_1.length; _i++) { + var patternString = patternStrings_1[_i]; + var pattern = tryParsePattern(patternString); + if (pattern) { + patterns.push(pattern); + } + else if (patternString === candidate) { + // pattern was matched as is - no need to search further + return patternString; + } + } + return ts.findBestPatternMatch(patterns, function (_) { return _; }, candidate); + } + ts.matchPatternOrExact = matchPatternOrExact; + function sliceAfter(arr, value) { + var index = arr.indexOf(value); + Debug.assert(index !== -1); + return arr.slice(index); + } + ts.sliceAfter = sliceAfter; + function minAndMax(arr, getValue) { + Debug.assert(arr.length !== 0); + var min = getValue(arr[0]); + var max = min; + for (var i = 1; i < arr.length; i++) { + var value = getValue(arr[i]); + if (value < min) { + min = value; + } + else if (value > max) { + max = value; + } + } + return { min: min, max: max }; + } + ts.minAndMax = minAndMax; + var NodeSet = /** @class */ (function () { + function NodeSet() { + this.map = ts.createMap(); + } + NodeSet.prototype.add = function (node) { + this.map.set(String(ts.getNodeId(node)), node); + }; + NodeSet.prototype.tryAdd = function (node) { + if (this.has(node)) + return false; + this.add(node); + return true; + }; + NodeSet.prototype.has = function (node) { + return this.map.has(String(ts.getNodeId(node))); + }; + NodeSet.prototype.forEach = function (cb) { + this.map.forEach(cb); + }; + NodeSet.prototype.some = function (pred) { + return ts.forEachEntry(this.map, pred) || false; + }; + return NodeSet; + }()); + ts.NodeSet = NodeSet; + var NodeMap = /** @class */ (function () { + function NodeMap() { + this.map = ts.createMap(); + } + NodeMap.prototype.get = function (node) { + var res = this.map.get(String(ts.getNodeId(node))); + return res && res.value; + }; + NodeMap.prototype.getOrUpdate = function (node, setValue) { + var res = this.get(node); + if (res) + return res; + var value = setValue(); + this.set(node, value); + return value; + }; + NodeMap.prototype.set = function (node, value) { + this.map.set(String(ts.getNodeId(node)), { node: node, value: value }); + }; + NodeMap.prototype.has = function (node) { + return this.map.has(String(ts.getNodeId(node))); + }; + NodeMap.prototype.forEach = function (cb) { + this.map.forEach(function (_a) { + var node = _a.node, value = _a.value; + return cb(value, node); + }); + }; + return NodeMap; + }()); + ts.NodeMap = NodeMap; + function rangeOfNode(node) { + return { pos: ts.getTokenPosOfNode(node), end: node.end }; + } + ts.rangeOfNode = rangeOfNode; + function rangeOfTypeParameters(typeParameters) { + // Include the `<>` + return { pos: typeParameters.pos - 1, end: typeParameters.end + 1 }; + } + ts.rangeOfTypeParameters = rangeOfTypeParameters; + function skipTypeChecking(sourceFile, options) { + // If skipLibCheck is enabled, skip reporting errors if file is a declaration file. + // If skipDefaultLibCheck is enabled, skip reporting errors if file contains a + // '/// ' directive. + return options.skipLibCheck && sourceFile.isDeclarationFile || options.skipDefaultLibCheck && sourceFile.hasNoDefaultLib; + } + ts.skipTypeChecking = skipTypeChecking; + function isJsonEqual(a, b) { + return a === b || typeof a === "object" && a !== null && typeof b === "object" && b !== null && ts.equalOwnProperties(a, b, isJsonEqual); + } + ts.isJsonEqual = isJsonEqual; + function getOrUpdate(map, key, getDefault) { + var got = map.get(key); + if (got === undefined) { + var value = getDefault(); + map.set(key, value); + return value; + } + else { + return got; + } + } + ts.getOrUpdate = getOrUpdate; + /** + * Converts a bigint literal string, e.g. `0x1234n`, + * to its decimal string representation, e.g. `4660`. + */ + function parsePseudoBigInt(stringValue) { + var log2Base; + switch (stringValue.charCodeAt(1)) { // "x" in "0x123" + case 98 /* b */: + case 66 /* B */: // 0b or 0B + log2Base = 1; + break; + case 111 /* o */: + case 79 /* O */: // 0o or 0O + log2Base = 3; + break; + case 120 /* x */: + case 88 /* X */: // 0x or 0X + log2Base = 4; + break; + default: // already in decimal; omit trailing "n" + var nIndex = stringValue.length - 1; + // Skip leading 0s + var nonZeroStart = 0; + while (stringValue.charCodeAt(nonZeroStart) === 48 /* _0 */) { + nonZeroStart++; + } + return stringValue.slice(nonZeroStart, nIndex) || "0"; + } + // Omit leading "0b", "0o", or "0x", and trailing "n" + var startIndex = 2, endIndex = stringValue.length - 1; + var bitsNeeded = (endIndex - startIndex) * log2Base; + // Stores the value specified by the string as a LE array of 16-bit integers + // using Uint16 instead of Uint32 so combining steps can use bitwise operators + var segments = new Uint16Array((bitsNeeded >>> 4) + (bitsNeeded & 15 ? 1 : 0)); + // Add the digits, one at a time + for (var i = endIndex - 1, bitOffset = 0; i >= startIndex; i--, bitOffset += log2Base) { + var segment = bitOffset >>> 4; + var digitChar = stringValue.charCodeAt(i); + // Find character range: 0-9 < A-F < a-f + var digit = digitChar <= 57 /* _9 */ + ? digitChar - 48 /* _0 */ + : 10 + digitChar - + (digitChar <= 70 /* F */ ? 65 /* A */ : 97 /* a */); + var shiftedDigit = digit << (bitOffset & 15); + segments[segment] |= shiftedDigit; + var residual = shiftedDigit >>> 16; + if (residual) + segments[segment + 1] |= residual; // overflows segment + } + // Repeatedly divide segments by 10 and add remainder to base10Value + var base10Value = ""; + var firstNonzeroSegment = segments.length - 1; + var segmentsRemaining = true; + while (segmentsRemaining) { + var mod10 = 0; + segmentsRemaining = false; + for (var segment = firstNonzeroSegment; segment >= 0; segment--) { + var newSegment = mod10 << 16 | segments[segment]; + var segmentValue = (newSegment / 10) | 0; + segments[segment] = segmentValue; + mod10 = newSegment - segmentValue * 10; + if (segmentValue && !segmentsRemaining) { + firstNonzeroSegment = segment; + segmentsRemaining = true; + } + } + base10Value = mod10 + base10Value; + } + return base10Value; + } + ts.parsePseudoBigInt = parsePseudoBigInt; + function pseudoBigIntToString(_a) { + var negative = _a.negative, base10Value = _a.base10Value; + return (negative && base10Value !== "0" ? "-" : "") + base10Value; + } + ts.pseudoBigIntToString = pseudoBigIntToString; +})(ts || (ts = {})); +var ts; +(function (ts) { + var SignatureFlags; + (function (SignatureFlags) { + SignatureFlags[SignatureFlags["None"] = 0] = "None"; + SignatureFlags[SignatureFlags["Yield"] = 1] = "Yield"; + SignatureFlags[SignatureFlags["Await"] = 2] = "Await"; + SignatureFlags[SignatureFlags["Type"] = 4] = "Type"; + SignatureFlags[SignatureFlags["IgnoreMissingOpenBrace"] = 16] = "IgnoreMissingOpenBrace"; + SignatureFlags[SignatureFlags["JSDoc"] = 32] = "JSDoc"; + })(SignatureFlags || (SignatureFlags = {})); + // tslint:disable variable-name + var NodeConstructor; + var TokenConstructor; + var IdentifierConstructor; + var SourceFileConstructor; + // tslint:enable variable-name + function createNode(kind, pos, end) { + if (kind === 279 /* SourceFile */) { + return new (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor()))(kind, pos, end); + } + else if (kind === 72 /* Identifier */) { + return new (IdentifierConstructor || (IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor()))(kind, pos, end); + } + else if (!ts.isNodeKind(kind)) { + return new (TokenConstructor || (TokenConstructor = ts.objectAllocator.getTokenConstructor()))(kind, pos, end); + } + else { + return new (NodeConstructor || (NodeConstructor = ts.objectAllocator.getNodeConstructor()))(kind, pos, end); + } + } + ts.createNode = createNode; + function visitNode(cbNode, node) { + return node && cbNode(node); + } + function visitNodes(cbNode, cbNodes, nodes) { + if (nodes) { + if (cbNodes) { + return cbNodes(nodes); + } + for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) { + var node = nodes_1[_i]; + var result = cbNode(node); + if (result) { + return result; + } + } + } + } + /*@internal*/ + function isJSDocLikeText(text, start) { + return text.charCodeAt(start + 1) === 42 /* asterisk */ && + text.charCodeAt(start + 2) === 42 /* asterisk */ && + text.charCodeAt(start + 3) !== 47 /* slash */; + } + ts.isJSDocLikeText = isJSDocLikeText; + /** + * Invokes a callback for each child of the given node. The 'cbNode' callback is invoked for all child nodes + * stored in properties. If a 'cbNodes' callback is specified, it is invoked for embedded arrays; otherwise, + * embedded arrays are flattened and the 'cbNode' callback is invoked for each element. If a callback returns + * a truthy value, iteration stops and that value is returned. Otherwise, undefined is returned. + * + * @param node a given node to visit its children + * @param cbNode a callback to be invoked for all child nodes + * @param cbNodes a callback to be invoked for embedded array + * + * @remarks `forEachChild` must visit the children of a node in the order + * that they appear in the source code. The language service depends on this property to locate nodes by position. + */ + function forEachChild(node, cbNode, cbNodes) { + if (!node || node.kind <= 147 /* LastToken */) { + return; + } + switch (node.kind) { + case 148 /* QualifiedName */: + return visitNode(cbNode, node.left) || + visitNode(cbNode, node.right); + case 150 /* TypeParameter */: + return visitNode(cbNode, node.name) || + visitNode(cbNode, node.constraint) || + visitNode(cbNode, node.default) || + visitNode(cbNode, node.expression); + case 276 /* ShorthandPropertyAssignment */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.exclamationToken) || + visitNode(cbNode, node.equalsToken) || + visitNode(cbNode, node.objectAssignmentInitializer); + case 277 /* SpreadAssignment */: + return visitNode(cbNode, node.expression); + case 151 /* Parameter */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.dotDotDotToken) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.type) || + visitNode(cbNode, node.initializer); + case 154 /* PropertyDeclaration */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.exclamationToken) || + visitNode(cbNode, node.type) || + visitNode(cbNode, node.initializer); + case 153 /* PropertySignature */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.type) || + visitNode(cbNode, node.initializer); + case 275 /* PropertyAssignment */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.initializer); + case 237 /* VariableDeclaration */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.exclamationToken) || + visitNode(cbNode, node.type) || + visitNode(cbNode, node.initializer); + case 186 /* BindingElement */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.dotDotDotToken) || + visitNode(cbNode, node.propertyName) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.initializer); + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 162 /* IndexSignature */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type); + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 196 /* FunctionExpression */: + case 239 /* FunctionDeclaration */: + case 197 /* ArrowFunction */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.asteriskToken) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.exclamationToken) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type) || + visitNode(cbNode, node.equalsGreaterThanToken) || + visitNode(cbNode, node.body); + case 164 /* TypeReference */: + return visitNode(cbNode, node.typeName) || + visitNodes(cbNode, cbNodes, node.typeArguments); + case 163 /* TypePredicate */: + return visitNode(cbNode, node.parameterName) || + visitNode(cbNode, node.type); + case 167 /* TypeQuery */: + return visitNode(cbNode, node.exprName); + case 168 /* TypeLiteral */: + return visitNodes(cbNode, cbNodes, node.members); + case 169 /* ArrayType */: + return visitNode(cbNode, node.elementType); + case 170 /* TupleType */: + return visitNodes(cbNode, cbNodes, node.elementTypes); + case 173 /* UnionType */: + case 174 /* IntersectionType */: + return visitNodes(cbNode, cbNodes, node.types); + case 175 /* ConditionalType */: + return visitNode(cbNode, node.checkType) || + visitNode(cbNode, node.extendsType) || + visitNode(cbNode, node.trueType) || + visitNode(cbNode, node.falseType); + case 176 /* InferType */: + return visitNode(cbNode, node.typeParameter); + case 183 /* ImportType */: + return visitNode(cbNode, node.argument) || + visitNode(cbNode, node.qualifier) || + visitNodes(cbNode, cbNodes, node.typeArguments); + case 177 /* ParenthesizedType */: + case 179 /* TypeOperator */: + return visitNode(cbNode, node.type); + case 180 /* IndexedAccessType */: + return visitNode(cbNode, node.objectType) || + visitNode(cbNode, node.indexType); + case 181 /* MappedType */: + return visitNode(cbNode, node.readonlyToken) || + visitNode(cbNode, node.typeParameter) || + visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.type); + case 182 /* LiteralType */: + return visitNode(cbNode, node.literal); + case 184 /* ObjectBindingPattern */: + case 185 /* ArrayBindingPattern */: + return visitNodes(cbNode, cbNodes, node.elements); + case 187 /* ArrayLiteralExpression */: + return visitNodes(cbNode, cbNodes, node.elements); + case 188 /* ObjectLiteralExpression */: + return visitNodes(cbNode, cbNodes, node.properties); + case 189 /* PropertyAccessExpression */: + return visitNode(cbNode, node.expression) || + visitNode(cbNode, node.name); + case 190 /* ElementAccessExpression */: + return visitNode(cbNode, node.expression) || + visitNode(cbNode, node.argumentExpression); + case 191 /* CallExpression */: + case 192 /* NewExpression */: + return visitNode(cbNode, node.expression) || + visitNodes(cbNode, cbNodes, node.typeArguments) || + visitNodes(cbNode, cbNodes, node.arguments); + case 193 /* TaggedTemplateExpression */: + return visitNode(cbNode, node.tag) || + visitNodes(cbNode, cbNodes, node.typeArguments) || + visitNode(cbNode, node.template); + case 194 /* TypeAssertionExpression */: + return visitNode(cbNode, node.type) || + visitNode(cbNode, node.expression); + case 195 /* ParenthesizedExpression */: + return visitNode(cbNode, node.expression); + case 198 /* DeleteExpression */: + return visitNode(cbNode, node.expression); + case 199 /* TypeOfExpression */: + return visitNode(cbNode, node.expression); + case 200 /* VoidExpression */: + return visitNode(cbNode, node.expression); + case 202 /* PrefixUnaryExpression */: + return visitNode(cbNode, node.operand); + case 207 /* YieldExpression */: + return visitNode(cbNode, node.asteriskToken) || + visitNode(cbNode, node.expression); + case 201 /* AwaitExpression */: + return visitNode(cbNode, node.expression); + case 203 /* PostfixUnaryExpression */: + return visitNode(cbNode, node.operand); + case 204 /* BinaryExpression */: + return visitNode(cbNode, node.left) || + visitNode(cbNode, node.operatorToken) || + visitNode(cbNode, node.right); + case 212 /* AsExpression */: + return visitNode(cbNode, node.expression) || + visitNode(cbNode, node.type); + case 213 /* NonNullExpression */: + return visitNode(cbNode, node.expression); + case 214 /* MetaProperty */: + return visitNode(cbNode, node.name); + case 205 /* ConditionalExpression */: + return visitNode(cbNode, node.condition) || + visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.whenTrue) || + visitNode(cbNode, node.colonToken) || + visitNode(cbNode, node.whenFalse); + case 208 /* SpreadElement */: + return visitNode(cbNode, node.expression); + case 218 /* Block */: + case 245 /* ModuleBlock */: + return visitNodes(cbNode, cbNodes, node.statements); + case 279 /* SourceFile */: + return visitNodes(cbNode, cbNodes, node.statements) || + visitNode(cbNode, node.endOfFileToken); + case 219 /* VariableStatement */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.declarationList); + case 238 /* VariableDeclarationList */: + return visitNodes(cbNode, cbNodes, node.declarations); + case 221 /* ExpressionStatement */: + return visitNode(cbNode, node.expression); + case 222 /* IfStatement */: + return visitNode(cbNode, node.expression) || + visitNode(cbNode, node.thenStatement) || + visitNode(cbNode, node.elseStatement); + case 223 /* DoStatement */: + return visitNode(cbNode, node.statement) || + visitNode(cbNode, node.expression); + case 224 /* WhileStatement */: + return visitNode(cbNode, node.expression) || + visitNode(cbNode, node.statement); + case 225 /* ForStatement */: + return visitNode(cbNode, node.initializer) || + visitNode(cbNode, node.condition) || + visitNode(cbNode, node.incrementor) || + visitNode(cbNode, node.statement); + case 226 /* ForInStatement */: + return visitNode(cbNode, node.initializer) || + visitNode(cbNode, node.expression) || + visitNode(cbNode, node.statement); + case 227 /* ForOfStatement */: + return visitNode(cbNode, node.awaitModifier) || + visitNode(cbNode, node.initializer) || + visitNode(cbNode, node.expression) || + visitNode(cbNode, node.statement); + case 228 /* ContinueStatement */: + case 229 /* BreakStatement */: + return visitNode(cbNode, node.label); + case 230 /* ReturnStatement */: + return visitNode(cbNode, node.expression); + case 231 /* WithStatement */: + return visitNode(cbNode, node.expression) || + visitNode(cbNode, node.statement); + case 232 /* SwitchStatement */: + return visitNode(cbNode, node.expression) || + visitNode(cbNode, node.caseBlock); + case 246 /* CaseBlock */: + return visitNodes(cbNode, cbNodes, node.clauses); + case 271 /* CaseClause */: + return visitNode(cbNode, node.expression) || + visitNodes(cbNode, cbNodes, node.statements); + case 272 /* DefaultClause */: + return visitNodes(cbNode, cbNodes, node.statements); + case 233 /* LabeledStatement */: + return visitNode(cbNode, node.label) || + visitNode(cbNode, node.statement); + case 234 /* ThrowStatement */: + return visitNode(cbNode, node.expression); + case 235 /* TryStatement */: + return visitNode(cbNode, node.tryBlock) || + visitNode(cbNode, node.catchClause) || + visitNode(cbNode, node.finallyBlock); + case 274 /* CatchClause */: + return visitNode(cbNode, node.variableDeclaration) || + visitNode(cbNode, node.block); + case 152 /* Decorator */: + return visitNode(cbNode, node.expression); + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.heritageClauses) || + visitNodes(cbNode, cbNodes, node.members); + case 241 /* InterfaceDeclaration */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.heritageClauses) || + visitNodes(cbNode, cbNodes, node.members); + case 242 /* TypeAliasDeclaration */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNode(cbNode, node.type); + case 243 /* EnumDeclaration */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNodes(cbNode, cbNodes, node.members); + case 278 /* EnumMember */: + return visitNode(cbNode, node.name) || + visitNode(cbNode, node.initializer); + case 244 /* ModuleDeclaration */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.body); + case 248 /* ImportEqualsDeclaration */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.moduleReference); + case 249 /* ImportDeclaration */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.importClause) || + visitNode(cbNode, node.moduleSpecifier); + case 250 /* ImportClause */: + return visitNode(cbNode, node.name) || + visitNode(cbNode, node.namedBindings); + case 247 /* NamespaceExportDeclaration */: + return visitNode(cbNode, node.name); + case 251 /* NamespaceImport */: + return visitNode(cbNode, node.name); + case 252 /* NamedImports */: + case 256 /* NamedExports */: + return visitNodes(cbNode, cbNodes, node.elements); + case 255 /* ExportDeclaration */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.exportClause) || + visitNode(cbNode, node.moduleSpecifier); + case 253 /* ImportSpecifier */: + case 257 /* ExportSpecifier */: + return visitNode(cbNode, node.propertyName) || + visitNode(cbNode, node.name); + case 254 /* ExportAssignment */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.expression); + case 206 /* TemplateExpression */: + return visitNode(cbNode, node.head) || visitNodes(cbNode, cbNodes, node.templateSpans); + case 216 /* TemplateSpan */: + return visitNode(cbNode, node.expression) || visitNode(cbNode, node.literal); + case 149 /* ComputedPropertyName */: + return visitNode(cbNode, node.expression); + case 273 /* HeritageClause */: + return visitNodes(cbNode, cbNodes, node.types); + case 211 /* ExpressionWithTypeArguments */: + return visitNode(cbNode, node.expression) || + visitNodes(cbNode, cbNodes, node.typeArguments); + case 259 /* ExternalModuleReference */: + return visitNode(cbNode, node.expression); + case 258 /* MissingDeclaration */: + return visitNodes(cbNode, cbNodes, node.decorators); + case 309 /* CommaListExpression */: + return visitNodes(cbNode, cbNodes, node.elements); + case 260 /* JsxElement */: + return visitNode(cbNode, node.openingElement) || + visitNodes(cbNode, cbNodes, node.children) || + visitNode(cbNode, node.closingElement); + case 264 /* JsxFragment */: + return visitNode(cbNode, node.openingFragment) || + visitNodes(cbNode, cbNodes, node.children) || + visitNode(cbNode, node.closingFragment); + case 261 /* JsxSelfClosingElement */: + case 262 /* JsxOpeningElement */: + return visitNode(cbNode, node.tagName) || + visitNodes(cbNode, cbNodes, node.typeArguments) || + visitNode(cbNode, node.attributes); + case 268 /* JsxAttributes */: + return visitNodes(cbNode, cbNodes, node.properties); + case 267 /* JsxAttribute */: + return visitNode(cbNode, node.name) || + visitNode(cbNode, node.initializer); + case 269 /* JsxSpreadAttribute */: + return visitNode(cbNode, node.expression); + case 270 /* JsxExpression */: + return visitNode(cbNode, node.dotDotDotToken) || + visitNode(cbNode, node.expression); + case 263 /* JsxClosingElement */: + return visitNode(cbNode, node.tagName); + case 171 /* OptionalType */: + case 172 /* RestType */: + case 283 /* JSDocTypeExpression */: + case 287 /* JSDocNonNullableType */: + case 286 /* JSDocNullableType */: + case 288 /* JSDocOptionalType */: + case 290 /* JSDocVariadicType */: + return visitNode(cbNode, node.type); + case 289 /* JSDocFunctionType */: + return visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type); + case 291 /* JSDocComment */: + return visitNodes(cbNode, cbNodes, node.tags); + case 299 /* JSDocParameterTag */: + case 305 /* JSDocPropertyTag */: + return visitNode(cbNode, node.tagName) || + (node.isNameFirst + ? visitNode(cbNode, node.name) || + visitNode(cbNode, node.typeExpression) + : visitNode(cbNode, node.typeExpression) || + visitNode(cbNode, node.name)); + case 295 /* JSDocAugmentsTag */: + return visitNode(cbNode, node.tagName) || + visitNode(cbNode, node.class); + case 303 /* JSDocTemplateTag */: + return visitNode(cbNode, node.tagName) || + visitNode(cbNode, node.constraint) || + visitNodes(cbNode, cbNodes, node.typeParameters); + case 304 /* JSDocTypedefTag */: + return visitNode(cbNode, node.tagName) || + (node.typeExpression && + node.typeExpression.kind === 283 /* JSDocTypeExpression */ + ? visitNode(cbNode, node.typeExpression) || + visitNode(cbNode, node.fullName) + : visitNode(cbNode, node.fullName) || + visitNode(cbNode, node.typeExpression)); + case 297 /* JSDocCallbackTag */: + return visitNode(cbNode, node.tagName) || + visitNode(cbNode, node.fullName) || + visitNode(cbNode, node.typeExpression); + case 300 /* JSDocReturnTag */: + case 302 /* JSDocTypeTag */: + case 301 /* JSDocThisTag */: + case 298 /* JSDocEnumTag */: + return visitNode(cbNode, node.tagName) || + visitNode(cbNode, node.typeExpression); + case 293 /* JSDocSignature */: + return ts.forEach(node.typeParameters, cbNode) || + ts.forEach(node.parameters, cbNode) || + visitNode(cbNode, node.type); + case 292 /* JSDocTypeLiteral */: + return ts.forEach(node.jsDocPropertyTags, cbNode); + case 294 /* JSDocTag */: + case 296 /* JSDocClassTag */: + return visitNode(cbNode, node.tagName); + case 308 /* PartiallyEmittedExpression */: + return visitNode(cbNode, node.expression); + } + } + ts.forEachChild = forEachChild; + function createSourceFile(fileName, sourceText, languageVersion, setParentNodes, scriptKind) { + if (setParentNodes === void 0) { setParentNodes = false; } + ts.performance.mark("beforeParse"); + var result; + if (languageVersion === 100 /* JSON */) { + result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes, 6 /* JSON */); + } + else { + result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes, scriptKind); + } + ts.performance.mark("afterParse"); + ts.performance.measure("Parse", "beforeParse", "afterParse"); + return result; + } + ts.createSourceFile = createSourceFile; + function parseIsolatedEntityName(text, languageVersion) { + return Parser.parseIsolatedEntityName(text, languageVersion); + } + ts.parseIsolatedEntityName = parseIsolatedEntityName; + /** + * Parse json text into SyntaxTree and return node and parse errors if any + * @param fileName + * @param sourceText + */ + function parseJsonText(fileName, sourceText) { + return Parser.parseJsonText(fileName, sourceText); + } + ts.parseJsonText = parseJsonText; + // See also `isExternalOrCommonJsModule` in utilities.ts + function isExternalModule(file) { + return file.externalModuleIndicator !== undefined; + } + ts.isExternalModule = isExternalModule; + // Produces a new SourceFile for the 'newText' provided. The 'textChangeRange' parameter + // indicates what changed between the 'text' that this SourceFile has and the 'newText'. + // The SourceFile will be created with the compiler attempting to reuse as many nodes from + // this file as possible. + // + // Note: this function mutates nodes from this SourceFile. That means any existing nodes + // from this SourceFile that are being held onto may change as a result (including + // becoming detached from any SourceFile). It is recommended that this SourceFile not + // be used once 'update' is called on it. + function updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks) { + if (aggressiveChecks === void 0) { aggressiveChecks = false; } + var newSourceFile = IncrementalParser.updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks); + // Because new source file node is created, it may not have the flag PossiblyContainDynamicImport. This is the case if there is no new edit to add dynamic import. + // We will manually port the flag to the new source file. + newSourceFile.flags |= (sourceFile.flags & 1572864 /* PermanentlySetIncrementalFlags */); + return newSourceFile; + } + ts.updateSourceFile = updateSourceFile; + /* @internal */ + function parseIsolatedJSDocComment(content, start, length) { + var result = Parser.JSDocParser.parseIsolatedJSDocComment(content, start, length); + if (result && result.jsDoc) { + // because the jsDocComment was parsed out of the source file, it might + // not be covered by the fixupParentReferences. + Parser.fixupParentReferences(result.jsDoc); + } + return result; + } + ts.parseIsolatedJSDocComment = parseIsolatedJSDocComment; + /* @internal */ + // Exposed only for testing. + function parseJSDocTypeExpressionForTests(content, start, length) { + return Parser.JSDocParser.parseJSDocTypeExpressionForTests(content, start, length); + } + ts.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests; + // Implement the parser as a singleton module. We do this for perf reasons because creating + // parser instances can actually be expensive enough to impact us on projects with many source + // files. + var Parser; + (function (Parser) { + // Share a single scanner across all calls to parse a source file. This helps speed things + // up by avoiding the cost of creating/compiling scanners over and over again. + var scanner = ts.createScanner(6 /* Latest */, /*skipTrivia*/ true); + var disallowInAndDecoratorContext = 2048 /* DisallowInContext */ | 8192 /* DecoratorContext */; + // capture constructors in 'initializeState' to avoid null checks + // tslint:disable variable-name + var NodeConstructor; + var TokenConstructor; + var IdentifierConstructor; + var SourceFileConstructor; + // tslint:enable variable-name + var sourceFile; + var parseDiagnostics; + var syntaxCursor; + var currentToken; + var sourceText; + var nodeCount; + var identifiers; + var identifierCount; + var parsingContext; + // Flags that dictate what parsing context we're in. For example: + // Whether or not we are in strict parsing mode. All that changes in strict parsing mode is + // that some tokens that would be considered identifiers may be considered keywords. + // + // When adding more parser context flags, consider which is the more common case that the + // flag will be in. This should be the 'false' state for that flag. The reason for this is + // that we don't store data in our nodes unless the value is in the *non-default* state. So, + // for example, more often than code 'allows-in' (or doesn't 'disallow-in'). We opt for + // 'disallow-in' set to 'false'. Otherwise, if we had 'allowsIn' set to 'true', then almost + // all nodes would need extra state on them to store this info. + // + // Note: 'allowIn' and 'allowYield' track 1:1 with the [in] and [yield] concepts in the ES6 + // grammar specification. + // + // An important thing about these context concepts. By default they are effectively inherited + // while parsing through every grammar production. i.e. if you don't change them, then when + // you parse a sub-production, it will have the same context values as the parent production. + // This is great most of the time. After all, consider all the 'expression' grammar productions + // and how nearly all of them pass along the 'in' and 'yield' context values: + // + // EqualityExpression[In, Yield] : + // RelationalExpression[?In, ?Yield] + // EqualityExpression[?In, ?Yield] == RelationalExpression[?In, ?Yield] + // EqualityExpression[?In, ?Yield] != RelationalExpression[?In, ?Yield] + // EqualityExpression[?In, ?Yield] === RelationalExpression[?In, ?Yield] + // EqualityExpression[?In, ?Yield] !== RelationalExpression[?In, ?Yield] + // + // Where you have to be careful is then understanding what the points are in the grammar + // where the values are *not* passed along. For example: + // + // SingleNameBinding[Yield,GeneratorParameter] + // [+GeneratorParameter]BindingIdentifier[Yield] Initializer[In]opt + // [~GeneratorParameter]BindingIdentifier[?Yield]Initializer[In, ?Yield]opt + // + // Here this is saying that if the GeneratorParameter context flag is set, that we should + // explicitly set the 'yield' context flag to false before calling into the BindingIdentifier + // and we should explicitly unset the 'yield' context flag before calling into the Initializer. + // production. Conversely, if the GeneratorParameter context flag is not set, then we + // should leave the 'yield' context flag alone. + // + // Getting this all correct is tricky and requires careful reading of the grammar to + // understand when these values should be changed versus when they should be inherited. + // + // Note: it should not be necessary to save/restore these flags during speculative/lookahead + // parsing. These context flags are naturally stored and restored through normal recursive + // descent parsing and unwinding. + var contextFlags; + // Whether or not we've had a parse error since creating the last AST node. If we have + // encountered an error, it will be stored on the next AST node we create. Parse errors + // can be broken down into three categories: + // + // 1) An error that occurred during scanning. For example, an unterminated literal, or a + // character that was completely not understood. + // + // 2) A token was expected, but was not present. This type of error is commonly produced + // by the 'parseExpected' function. + // + // 3) A token was present that no parsing function was able to consume. This type of error + // only occurs in the 'abortParsingListOrMoveToNextToken' function when the parser + // decides to skip the token. + // + // In all of these cases, we want to mark the next node as having had an error before it. + // With this mark, we can know in incremental settings if this node can be reused, or if + // we have to reparse it. If we don't keep this information around, we may just reuse the + // node. in that event we would then not produce the same errors as we did before, causing + // significant confusion problems. + // + // Note: it is necessary that this value be saved/restored during speculative/lookahead + // parsing. During lookahead parsing, we will often create a node. That node will have + // this value attached, and then this value will be set back to 'false'. If we decide to + // rewind, we must get back to the same value we had prior to the lookahead. + // + // Note: any errors at the end of the file that do not precede a regular node, should get + // attached to the EOF token. + var parseErrorBeforeNextFinishedNode = false; + function parseSourceFile(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes, scriptKind) { + if (setParentNodes === void 0) { setParentNodes = false; } + scriptKind = ts.ensureScriptKind(fileName, scriptKind); + if (scriptKind === 6 /* JSON */) { + var result_1 = parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes); + ts.convertToObjectWorker(result_1, result_1.parseDiagnostics, /*returnValue*/ false, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined); + result_1.referencedFiles = ts.emptyArray; + result_1.typeReferenceDirectives = ts.emptyArray; + result_1.libReferenceDirectives = ts.emptyArray; + result_1.amdDependencies = ts.emptyArray; + result_1.hasNoDefaultLib = false; + result_1.pragmas = ts.emptyMap; + return result_1; + } + initializeState(sourceText, languageVersion, syntaxCursor, scriptKind); + var result = parseSourceFileWorker(fileName, languageVersion, setParentNodes, scriptKind); + clearState(); + return result; + } + Parser.parseSourceFile = parseSourceFile; + function parseIsolatedEntityName(content, languageVersion) { + // Choice of `isDeclarationFile` should be arbitrary + initializeState(content, languageVersion, /*syntaxCursor*/ undefined, 1 /* JS */); + // Prime the scanner. + nextToken(); + var entityName = parseEntityName(/*allowReservedWords*/ true); + var isInvalid = token() === 1 /* EndOfFileToken */ && !parseDiagnostics.length; + clearState(); + return isInvalid ? entityName : undefined; + } + Parser.parseIsolatedEntityName = parseIsolatedEntityName; + function parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes) { + if (languageVersion === void 0) { languageVersion = 2 /* ES2015 */; } + initializeState(sourceText, languageVersion, syntaxCursor, 6 /* JSON */); + // Set source file so that errors will be reported with this file name + sourceFile = createSourceFile(fileName, 2 /* ES2015 */, 6 /* JSON */, /*isDeclaration*/ false); + sourceFile.flags = contextFlags; + // Prime the scanner. + nextToken(); + var pos = getNodePos(); + if (token() === 1 /* EndOfFileToken */) { + sourceFile.statements = createNodeArray([], pos, pos); + sourceFile.endOfFileToken = parseTokenNode(); + } + else { + var statement = createNode(221 /* ExpressionStatement */); + switch (token()) { + case 22 /* OpenBracketToken */: + statement.expression = parseArrayLiteralExpression(); + break; + case 102 /* TrueKeyword */: + case 87 /* FalseKeyword */: + case 96 /* NullKeyword */: + statement.expression = parseTokenNode(); + break; + case 39 /* MinusToken */: + if (lookAhead(function () { return nextToken() === 8 /* NumericLiteral */ && nextToken() !== 57 /* ColonToken */; })) { + statement.expression = parsePrefixUnaryExpression(); + } + else { + statement.expression = parseObjectLiteralExpression(); + } + break; + case 8 /* NumericLiteral */: + case 10 /* StringLiteral */: + if (lookAhead(function () { return nextToken() !== 57 /* ColonToken */; })) { + statement.expression = parseLiteralNode(); + break; + } + // falls through + default: + statement.expression = parseObjectLiteralExpression(); + break; + } + finishNode(statement); + sourceFile.statements = createNodeArray([statement], pos); + sourceFile.endOfFileToken = parseExpectedToken(1 /* EndOfFileToken */, ts.Diagnostics.Unexpected_token); + } + if (setParentNodes) { + fixupParentReferences(sourceFile); + } + sourceFile.parseDiagnostics = parseDiagnostics; + var result = sourceFile; + clearState(); + return result; + } + Parser.parseJsonText = parseJsonText; + function getLanguageVariant(scriptKind) { + // .tsx and .jsx files are treated as jsx language variant. + return scriptKind === 4 /* TSX */ || scriptKind === 2 /* JSX */ || scriptKind === 1 /* JS */ || scriptKind === 6 /* JSON */ ? 1 /* JSX */ : 0 /* Standard */; + } + function initializeState(_sourceText, languageVersion, _syntaxCursor, scriptKind) { + NodeConstructor = ts.objectAllocator.getNodeConstructor(); + TokenConstructor = ts.objectAllocator.getTokenConstructor(); + IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor(); + SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor(); + sourceText = _sourceText; + syntaxCursor = _syntaxCursor; + parseDiagnostics = []; + parsingContext = 0; + identifiers = ts.createMap(); + identifierCount = 0; + nodeCount = 0; + switch (scriptKind) { + case 1 /* JS */: + case 2 /* JSX */: + contextFlags = 65536 /* JavaScriptFile */; + break; + case 6 /* JSON */: + contextFlags = 65536 /* JavaScriptFile */ | 16777216 /* JsonFile */; + break; + default: + contextFlags = 0 /* None */; + break; + } + parseErrorBeforeNextFinishedNode = false; + // Initialize and prime the scanner before parsing the source elements. + scanner.setText(sourceText); + scanner.setOnError(scanError); + scanner.setScriptTarget(languageVersion); + scanner.setLanguageVariant(getLanguageVariant(scriptKind)); + } + function clearState() { + // Clear out the text the scanner is pointing at, so it doesn't keep anything alive unnecessarily. + scanner.setText(""); + scanner.setOnError(undefined); + // Clear any data. We don't want to accidentally hold onto it for too long. + parseDiagnostics = undefined; + sourceFile = undefined; + identifiers = undefined; + syntaxCursor = undefined; + sourceText = undefined; + } + function parseSourceFileWorker(fileName, languageVersion, setParentNodes, scriptKind) { + var isDeclarationFile = isDeclarationFileName(fileName); + if (isDeclarationFile) { + contextFlags |= 4194304 /* Ambient */; + } + sourceFile = createSourceFile(fileName, languageVersion, scriptKind, isDeclarationFile); + sourceFile.flags = contextFlags; + // Prime the scanner. + nextToken(); + // A member of ReadonlyArray isn't assignable to a member of T[] (and prevents a direct cast) - but this is where we set up those members so they can be readonly in the future + processCommentPragmas(sourceFile, sourceText); + processPragmasIntoFields(sourceFile, reportPragmaDiagnostic); + sourceFile.statements = parseList(0 /* SourceElements */, parseStatement); + ts.Debug.assert(token() === 1 /* EndOfFileToken */); + sourceFile.endOfFileToken = addJSDocComment(parseTokenNode()); + setExternalModuleIndicator(sourceFile); + sourceFile.nodeCount = nodeCount; + sourceFile.identifierCount = identifierCount; + sourceFile.identifiers = identifiers; + sourceFile.parseDiagnostics = parseDiagnostics; + if (setParentNodes) { + fixupParentReferences(sourceFile); + } + return sourceFile; + function reportPragmaDiagnostic(pos, end, diagnostic) { + parseDiagnostics.push(ts.createFileDiagnostic(sourceFile, pos, end, diagnostic)); + } + } + function addJSDocComment(node) { + ts.Debug.assert(!node.jsDoc); // Should only be called once per node + var jsDoc = ts.mapDefined(ts.getJSDocCommentRanges(node, sourceFile.text), function (comment) { return JSDocParser.parseJSDocComment(node, comment.pos, comment.end - comment.pos); }); + if (jsDoc.length) + node.jsDoc = jsDoc; + return node; + } + function fixupParentReferences(rootNode) { + // normally parent references are set during binding. However, for clients that only need + // a syntax tree, and no semantic features, then the binding process is an unnecessary + // overhead. This functions allows us to set all the parents, without all the expense of + // binding. + var parent = rootNode; + forEachChild(rootNode, visitNode); + return; + function visitNode(n) { + // walk down setting parents that differ from the parent we think it should be. This + // allows us to quickly bail out of setting parents for subtrees during incremental + // parsing + if (n.parent !== parent) { + n.parent = parent; + var saveParent = parent; + parent = n; + forEachChild(n, visitNode); + if (ts.hasJSDocNodes(n)) { + for (var _i = 0, _a = n.jsDoc; _i < _a.length; _i++) { + var jsDoc = _a[_i]; + jsDoc.parent = n; + parent = jsDoc; + forEachChild(jsDoc, visitNode); + } + } + parent = saveParent; + } + } + } + Parser.fixupParentReferences = fixupParentReferences; + function createSourceFile(fileName, languageVersion, scriptKind, isDeclarationFile) { + // code from createNode is inlined here so createNode won't have to deal with special case of creating source files + // this is quite rare comparing to other nodes and createNode should be as fast as possible + var sourceFile = new SourceFileConstructor(279 /* SourceFile */, /*pos*/ 0, /* end */ sourceText.length); + nodeCount++; + sourceFile.text = sourceText; + sourceFile.bindDiagnostics = []; + sourceFile.bindSuggestionDiagnostics = undefined; + sourceFile.languageVersion = languageVersion; + sourceFile.fileName = ts.normalizePath(fileName); + sourceFile.languageVariant = getLanguageVariant(scriptKind); + sourceFile.isDeclarationFile = isDeclarationFile; + sourceFile.scriptKind = scriptKind; + return sourceFile; + } + function setContextFlag(val, flag) { + if (val) { + contextFlags |= flag; + } + else { + contextFlags &= ~flag; + } + } + function setDisallowInContext(val) { + setContextFlag(val, 2048 /* DisallowInContext */); + } + function setYieldContext(val) { + setContextFlag(val, 4096 /* YieldContext */); + } + function setDecoratorContext(val) { + setContextFlag(val, 8192 /* DecoratorContext */); + } + function setAwaitContext(val) { + setContextFlag(val, 16384 /* AwaitContext */); + } + function doOutsideOfContext(context, func) { + // contextFlagsToClear will contain only the context flags that are + // currently set that we need to temporarily clear + // We don't just blindly reset to the previous flags to ensure + // that we do not mutate cached flags for the incremental + // parser (ThisNodeHasError, ThisNodeOrAnySubNodesHasError, and + // HasAggregatedChildData). + var contextFlagsToClear = context & contextFlags; + if (contextFlagsToClear) { + // clear the requested context flags + setContextFlag(/*val*/ false, contextFlagsToClear); + var result = func(); + // restore the context flags we just cleared + setContextFlag(/*val*/ true, contextFlagsToClear); + return result; + } + // no need to do anything special as we are not in any of the requested contexts + return func(); + } + function doInsideOfContext(context, func) { + // contextFlagsToSet will contain only the context flags that + // are not currently set that we need to temporarily enable. + // We don't just blindly reset to the previous flags to ensure + // that we do not mutate cached flags for the incremental + // parser (ThisNodeHasError, ThisNodeOrAnySubNodesHasError, and + // HasAggregatedChildData). + var contextFlagsToSet = context & ~contextFlags; + if (contextFlagsToSet) { + // set the requested context flags + setContextFlag(/*val*/ true, contextFlagsToSet); + var result = func(); + // reset the context flags we just set + setContextFlag(/*val*/ false, contextFlagsToSet); + return result; + } + // no need to do anything special as we are already in all of the requested contexts + return func(); + } + function allowInAnd(func) { + return doOutsideOfContext(2048 /* DisallowInContext */, func); + } + function disallowInAnd(func) { + return doInsideOfContext(2048 /* DisallowInContext */, func); + } + function doInYieldContext(func) { + return doInsideOfContext(4096 /* YieldContext */, func); + } + function doInDecoratorContext(func) { + return doInsideOfContext(8192 /* DecoratorContext */, func); + } + function doInAwaitContext(func) { + return doInsideOfContext(16384 /* AwaitContext */, func); + } + function doOutsideOfAwaitContext(func) { + return doOutsideOfContext(16384 /* AwaitContext */, func); + } + function doInYieldAndAwaitContext(func) { + return doInsideOfContext(4096 /* YieldContext */ | 16384 /* AwaitContext */, func); + } + function inContext(flags) { + return (contextFlags & flags) !== 0; + } + function inYieldContext() { + return inContext(4096 /* YieldContext */); + } + function inDisallowInContext() { + return inContext(2048 /* DisallowInContext */); + } + function inDecoratorContext() { + return inContext(8192 /* DecoratorContext */); + } + function inAwaitContext() { + return inContext(16384 /* AwaitContext */); + } + function parseErrorAtCurrentToken(message, arg0) { + parseErrorAt(scanner.getTokenPos(), scanner.getTextPos(), message, arg0); + } + function parseErrorAtPosition(start, length, message, arg0) { + // Don't report another error if it would just be at the same position as the last error. + var lastError = ts.lastOrUndefined(parseDiagnostics); + if (!lastError || start !== lastError.start) { + parseDiagnostics.push(ts.createFileDiagnostic(sourceFile, start, length, message, arg0)); + } + // Mark that we've encountered an error. We'll set an appropriate bit on the next + // node we finish so that it can't be reused incrementally. + parseErrorBeforeNextFinishedNode = true; + } + function parseErrorAt(start, end, message, arg0) { + parseErrorAtPosition(start, end - start, message, arg0); + } + function parseErrorAtRange(range, message, arg0) { + parseErrorAt(range.pos, range.end, message, arg0); + } + function scanError(message, length) { + parseErrorAtPosition(scanner.getTextPos(), length, message); + } + function getNodePos() { + return scanner.getStartPos(); + } + // Use this function to access the current token instead of reading the currentToken + // variable. Since function results aren't narrowed in control flow analysis, this ensures + // that the type checker doesn't make wrong assumptions about the type of the current + // token (e.g. a call to nextToken() changes the current token but the checker doesn't + // reason about this side effect). Mainstream VMs inline simple functions like this, so + // there is no performance penalty. + function token() { + return currentToken; + } + function nextToken() { + return currentToken = scanner.scan(); + } + function reScanGreaterToken() { + return currentToken = scanner.reScanGreaterToken(); + } + function reScanSlashToken() { + return currentToken = scanner.reScanSlashToken(); + } + function reScanTemplateToken() { + return currentToken = scanner.reScanTemplateToken(); + } + function scanJsxIdentifier() { + return currentToken = scanner.scanJsxIdentifier(); + } + function scanJsxText() { + return currentToken = scanner.scanJsxToken(); + } + function scanJsxAttributeValue() { + return currentToken = scanner.scanJsxAttributeValue(); + } + function speculationHelper(callback, isLookAhead) { + // Keep track of the state we'll need to rollback to if lookahead fails (or if the + // caller asked us to always reset our state). + var saveToken = currentToken; + var saveParseDiagnosticsLength = parseDiagnostics.length; + var saveParseErrorBeforeNextFinishedNode = parseErrorBeforeNextFinishedNode; + // Note: it is not actually necessary to save/restore the context flags here. That's + // because the saving/restoring of these flags happens naturally through the recursive + // descent nature of our parser. However, we still store this here just so we can + // assert that invariant holds. + var saveContextFlags = contextFlags; + // If we're only looking ahead, then tell the scanner to only lookahead as well. + // Otherwise, if we're actually speculatively parsing, then tell the scanner to do the + // same. + var result = isLookAhead + ? scanner.lookAhead(callback) + : scanner.tryScan(callback); + ts.Debug.assert(saveContextFlags === contextFlags); + // If our callback returned something 'falsy' or we're just looking ahead, + // then unconditionally restore us to where we were. + if (!result || isLookAhead) { + currentToken = saveToken; + parseDiagnostics.length = saveParseDiagnosticsLength; + parseErrorBeforeNextFinishedNode = saveParseErrorBeforeNextFinishedNode; + } + return result; + } + /** Invokes the provided callback then unconditionally restores the parser to the state it + * was in immediately prior to invoking the callback. The result of invoking the callback + * is returned from this function. + */ + function lookAhead(callback) { + return speculationHelper(callback, /*isLookAhead*/ true); + } + /** Invokes the provided callback. If the callback returns something falsy, then it restores + * the parser to the state it was in immediately prior to invoking the callback. If the + * callback returns something truthy, then the parser state is not rolled back. The result + * of invoking the callback is returned from this function. + */ + function tryParse(callback) { + return speculationHelper(callback, /*isLookAhead*/ false); + } + // Ignore strict mode flag because we will report an error in type checker instead. + function isIdentifier() { + if (token() === 72 /* Identifier */) { + return true; + } + // If we have a 'yield' keyword, and we're in the [yield] context, then 'yield' is + // considered a keyword and is not an identifier. + if (token() === 117 /* YieldKeyword */ && inYieldContext()) { + return false; + } + // If we have a 'await' keyword, and we're in the [Await] context, then 'await' is + // considered a keyword and is not an identifier. + if (token() === 122 /* AwaitKeyword */ && inAwaitContext()) { + return false; + } + return token() > 108 /* LastReservedWord */; + } + function parseExpected(kind, diagnosticMessage, shouldAdvance) { + if (shouldAdvance === void 0) { shouldAdvance = true; } + if (token() === kind) { + if (shouldAdvance) { + nextToken(); + } + return true; + } + // Report specific message if provided with one. Otherwise, report generic fallback message. + if (diagnosticMessage) { + parseErrorAtCurrentToken(diagnosticMessage); + } + else { + parseErrorAtCurrentToken(ts.Diagnostics._0_expected, ts.tokenToString(kind)); + } + return false; + } + function parseOptional(t) { + if (token() === t) { + nextToken(); + return true; + } + return false; + } + function parseOptionalToken(t) { + if (token() === t) { + return parseTokenNode(); + } + return undefined; + } + function parseExpectedToken(t, diagnosticMessage, arg0) { + return parseOptionalToken(t) || + createMissingNode(t, /*reportAtCurrentPosition*/ false, diagnosticMessage || ts.Diagnostics._0_expected, arg0 || ts.tokenToString(t)); + } + function parseTokenNode() { + var node = createNode(token()); + nextToken(); + return finishNode(node); + } + function canParseSemicolon() { + // If there's a real semicolon, then we can always parse it out. + if (token() === 26 /* SemicolonToken */) { + return true; + } + // We can parse out an optional semicolon in ASI cases in the following cases. + return token() === 19 /* CloseBraceToken */ || token() === 1 /* EndOfFileToken */ || scanner.hasPrecedingLineBreak(); + } + function parseSemicolon() { + if (canParseSemicolon()) { + if (token() === 26 /* SemicolonToken */) { + // consume the semicolon if it was explicitly provided. + nextToken(); + } + return true; + } + else { + return parseExpected(26 /* SemicolonToken */); + } + } + function createNode(kind, pos) { + nodeCount++; + var p = pos >= 0 ? pos : scanner.getStartPos(); + return ts.isNodeKind(kind) || kind === 0 /* Unknown */ ? new NodeConstructor(kind, p, p) : + kind === 72 /* Identifier */ ? new IdentifierConstructor(kind, p, p) : + new TokenConstructor(kind, p, p); + } + function createNodeWithJSDoc(kind, pos) { + var node = createNode(kind, pos); + if (scanner.getTokenFlags() & 2 /* PrecedingJSDocComment */) { + addJSDocComment(node); + } + return node; + } + function createNodeArray(elements, pos, end) { + // Since the element list of a node array is typically created by starting with an empty array and + // repeatedly calling push(), the list may not have the optimal memory layout. We invoke slice() for + // small arrays (1 to 4 elements) to give the VM a chance to allocate an optimal representation. + var length = elements.length; + var array = (length >= 1 && length <= 4 ? elements.slice() : elements); + array.pos = pos; + array.end = end === undefined ? scanner.getStartPos() : end; + return array; + } + function finishNode(node, end) { + node.end = end === undefined ? scanner.getStartPos() : end; + if (contextFlags) { + node.flags |= contextFlags; + } + // Keep track on the node if we encountered an error while parsing it. If we did, then + // we cannot reuse the node incrementally. Once we've marked this node, clear out the + // flag so that we don't mark any subsequent nodes. + if (parseErrorBeforeNextFinishedNode) { + parseErrorBeforeNextFinishedNode = false; + node.flags |= 32768 /* ThisNodeHasError */; + } + return node; + } + function createMissingNode(kind, reportAtCurrentPosition, diagnosticMessage, arg0) { + if (reportAtCurrentPosition) { + parseErrorAtPosition(scanner.getStartPos(), 0, diagnosticMessage, arg0); + } + else if (diagnosticMessage) { + parseErrorAtCurrentToken(diagnosticMessage, arg0); + } + var result = createNode(kind); + if (kind === 72 /* Identifier */) { + result.escapedText = ""; + } + else if (ts.isLiteralKind(kind) || ts.isTemplateLiteralKind(kind)) { + result.text = ""; + } + return finishNode(result); + } + function internIdentifier(text) { + var identifier = identifiers.get(text); + if (identifier === undefined) { + identifiers.set(text, identifier = text); + } + return identifier; + } + // An identifier that starts with two underscores has an extra underscore character prepended to it to avoid issues + // with magic property names like '__proto__'. The 'identifiers' object is used to share a single string instance for + // each identifier in order to reduce memory consumption. + function createIdentifier(isIdentifier, diagnosticMessage) { + identifierCount++; + if (isIdentifier) { + var node = createNode(72 /* Identifier */); + // Store original token kind if it is not just an Identifier so we can report appropriate error later in type checker + if (token() !== 72 /* Identifier */) { + node.originalKeywordKind = token(); + } + node.escapedText = ts.escapeLeadingUnderscores(internIdentifier(scanner.getTokenValue())); + nextToken(); + return finishNode(node); + } + // Only for end of file because the error gets reported incorrectly on embedded script tags. + var reportAtCurrentPosition = token() === 1 /* EndOfFileToken */; + return createMissingNode(72 /* Identifier */, reportAtCurrentPosition, diagnosticMessage || ts.Diagnostics.Identifier_expected); + } + function parseIdentifier(diagnosticMessage) { + return createIdentifier(isIdentifier(), diagnosticMessage); + } + function parseIdentifierName(diagnosticMessage) { + return createIdentifier(ts.tokenIsIdentifierOrKeyword(token()), diagnosticMessage); + } + function isLiteralPropertyName() { + return ts.tokenIsIdentifierOrKeyword(token()) || + token() === 10 /* StringLiteral */ || + token() === 8 /* NumericLiteral */; + } + function parsePropertyNameWorker(allowComputedPropertyNames) { + if (token() === 10 /* StringLiteral */ || token() === 8 /* NumericLiteral */) { + var node = parseLiteralNode(); + node.text = internIdentifier(node.text); + return node; + } + if (allowComputedPropertyNames && token() === 22 /* OpenBracketToken */) { + return parseComputedPropertyName(); + } + return parseIdentifierName(); + } + function parsePropertyName() { + return parsePropertyNameWorker(/*allowComputedPropertyNames*/ true); + } + function parseComputedPropertyName() { + // PropertyName [Yield]: + // LiteralPropertyName + // ComputedPropertyName[?Yield] + var node = createNode(149 /* ComputedPropertyName */); + parseExpected(22 /* OpenBracketToken */); + // We parse any expression (including a comma expression). But the grammar + // says that only an assignment expression is allowed, so the grammar checker + // will error if it sees a comma expression. + node.expression = allowInAnd(parseExpression); + parseExpected(23 /* CloseBracketToken */); + return finishNode(node); + } + function parseContextualModifier(t) { + return token() === t && tryParse(nextTokenCanFollowModifier); + } + function nextTokenIsOnSameLineAndCanFollowModifier() { + nextToken(); + if (scanner.hasPrecedingLineBreak()) { + return false; + } + return canFollowModifier(); + } + function nextTokenCanFollowModifier() { + switch (token()) { + case 77 /* ConstKeyword */: + // 'const' is only a modifier if followed by 'enum'. + return nextToken() === 84 /* EnumKeyword */; + case 85 /* ExportKeyword */: + nextToken(); + if (token() === 80 /* DefaultKeyword */) { + return lookAhead(nextTokenCanFollowDefaultKeyword); + } + return token() !== 40 /* AsteriskToken */ && token() !== 119 /* AsKeyword */ && token() !== 18 /* OpenBraceToken */ && canFollowModifier(); + case 80 /* DefaultKeyword */: + return nextTokenCanFollowDefaultKeyword(); + case 116 /* StaticKeyword */: + case 126 /* GetKeyword */: + case 137 /* SetKeyword */: + nextToken(); + return canFollowModifier(); + default: + return nextTokenIsOnSameLineAndCanFollowModifier(); + } + } + function parseAnyContextualModifier() { + return ts.isModifierKind(token()) && tryParse(nextTokenCanFollowModifier); + } + function canFollowModifier() { + return token() === 22 /* OpenBracketToken */ + || token() === 18 /* OpenBraceToken */ + || token() === 40 /* AsteriskToken */ + || token() === 25 /* DotDotDotToken */ + || isLiteralPropertyName(); + } + function nextTokenCanFollowDefaultKeyword() { + nextToken(); + return token() === 76 /* ClassKeyword */ || token() === 90 /* FunctionKeyword */ || + token() === 110 /* InterfaceKeyword */ || + (token() === 118 /* AbstractKeyword */ && lookAhead(nextTokenIsClassKeywordOnSameLine)) || + (token() === 121 /* AsyncKeyword */ && lookAhead(nextTokenIsFunctionKeywordOnSameLine)); + } + // True if positioned at the start of a list element + function isListElement(parsingContext, inErrorRecovery) { + var node = currentNode(parsingContext); + if (node) { + return true; + } + switch (parsingContext) { + case 0 /* SourceElements */: + case 1 /* BlockStatements */: + case 3 /* SwitchClauseStatements */: + // If we're in error recovery, then we don't want to treat ';' as an empty statement. + // The problem is that ';' can show up in far too many contexts, and if we see one + // and assume it's a statement, then we may bail out inappropriately from whatever + // we're parsing. For example, if we have a semicolon in the middle of a class, then + // we really don't want to assume the class is over and we're on a statement in the + // outer module. We just want to consume and move on. + return !(token() === 26 /* SemicolonToken */ && inErrorRecovery) && isStartOfStatement(); + case 2 /* SwitchClauses */: + return token() === 74 /* CaseKeyword */ || token() === 80 /* DefaultKeyword */; + case 4 /* TypeMembers */: + return lookAhead(isTypeMemberStart); + case 5 /* ClassMembers */: + // We allow semicolons as class elements (as specified by ES6) as long as we're + // not in error recovery. If we're in error recovery, we don't want an errant + // semicolon to be treated as a class member (since they're almost always used + // for statements. + return lookAhead(isClassMemberStart) || (token() === 26 /* SemicolonToken */ && !inErrorRecovery); + case 6 /* EnumMembers */: + // Include open bracket computed properties. This technically also lets in indexers, + // which would be a candidate for improved error reporting. + return token() === 22 /* OpenBracketToken */ || isLiteralPropertyName(); + case 12 /* ObjectLiteralMembers */: + switch (token()) { + case 22 /* OpenBracketToken */: + case 40 /* AsteriskToken */: + case 25 /* DotDotDotToken */: + case 24 /* DotToken */: // Not an object literal member, but don't want to close the object (see `tests/cases/fourslash/completionsDotInObjectLiteral.ts`) + return true; + default: + return isLiteralPropertyName(); + } + case 18 /* RestProperties */: + return isLiteralPropertyName(); + case 9 /* ObjectBindingElements */: + return token() === 22 /* OpenBracketToken */ || token() === 25 /* DotDotDotToken */ || isLiteralPropertyName(); + case 7 /* HeritageClauseElement */: + // If we see `{ ... }` then only consume it as an expression if it is followed by `,` or `{` + // That way we won't consume the body of a class in its heritage clause. + if (token() === 18 /* OpenBraceToken */) { + return lookAhead(isValidHeritageClauseObjectLiteral); + } + if (!inErrorRecovery) { + return isStartOfLeftHandSideExpression() && !isHeritageClauseExtendsOrImplementsKeyword(); + } + else { + // If we're in error recovery we tighten up what we're willing to match. + // That way we don't treat something like "this" as a valid heritage clause + // element during recovery. + return isIdentifier() && !isHeritageClauseExtendsOrImplementsKeyword(); + } + case 8 /* VariableDeclarations */: + return isIdentifierOrPattern(); + case 10 /* ArrayBindingElements */: + return token() === 27 /* CommaToken */ || token() === 25 /* DotDotDotToken */ || isIdentifierOrPattern(); + case 19 /* TypeParameters */: + return isIdentifier(); + case 15 /* ArrayLiteralMembers */: + switch (token()) { + case 27 /* CommaToken */: + case 24 /* DotToken */: // Not an array literal member, but don't want to close the array (see `tests/cases/fourslash/completionsDotInArrayLiteralInObjectLiteral.ts`) + return true; + } + // falls through + case 11 /* ArgumentExpressions */: + return token() === 25 /* DotDotDotToken */ || isStartOfExpression(); + case 16 /* Parameters */: + return isStartOfParameter(/*isJSDocParameter*/ false); + case 17 /* JSDocParameters */: + return isStartOfParameter(/*isJSDocParameter*/ true); + case 20 /* TypeArguments */: + case 21 /* TupleElementTypes */: + return token() === 27 /* CommaToken */ || isStartOfType(); + case 22 /* HeritageClauses */: + return isHeritageClause(); + case 23 /* ImportOrExportSpecifiers */: + return ts.tokenIsIdentifierOrKeyword(token()); + case 13 /* JsxAttributes */: + return ts.tokenIsIdentifierOrKeyword(token()) || token() === 18 /* OpenBraceToken */; + case 14 /* JsxChildren */: + return true; + } + return ts.Debug.fail("Non-exhaustive case in 'isListElement'."); + } + function isValidHeritageClauseObjectLiteral() { + ts.Debug.assert(token() === 18 /* OpenBraceToken */); + if (nextToken() === 19 /* CloseBraceToken */) { + // if we see "extends {}" then only treat the {} as what we're extending (and not + // the class body) if we have: + // + // extends {} { + // extends {}, + // extends {} extends + // extends {} implements + var next = nextToken(); + return next === 27 /* CommaToken */ || next === 18 /* OpenBraceToken */ || next === 86 /* ExtendsKeyword */ || next === 109 /* ImplementsKeyword */; + } + return true; + } + function nextTokenIsIdentifier() { + nextToken(); + return isIdentifier(); + } + function nextTokenIsIdentifierOrKeyword() { + nextToken(); + return ts.tokenIsIdentifierOrKeyword(token()); + } + function nextTokenIsIdentifierOrKeywordOrGreaterThan() { + nextToken(); + return ts.tokenIsIdentifierOrKeywordOrGreaterThan(token()); + } + function isHeritageClauseExtendsOrImplementsKeyword() { + if (token() === 109 /* ImplementsKeyword */ || + token() === 86 /* ExtendsKeyword */) { + return lookAhead(nextTokenIsStartOfExpression); + } + return false; + } + function nextTokenIsStartOfExpression() { + nextToken(); + return isStartOfExpression(); + } + function nextTokenIsStartOfType() { + nextToken(); + return isStartOfType(); + } + // True if positioned at a list terminator + function isListTerminator(kind) { + if (token() === 1 /* EndOfFileToken */) { + // Being at the end of the file ends all lists. + return true; + } + switch (kind) { + case 1 /* BlockStatements */: + case 2 /* SwitchClauses */: + case 4 /* TypeMembers */: + case 5 /* ClassMembers */: + case 6 /* EnumMembers */: + case 12 /* ObjectLiteralMembers */: + case 9 /* ObjectBindingElements */: + case 23 /* ImportOrExportSpecifiers */: + return token() === 19 /* CloseBraceToken */; + case 3 /* SwitchClauseStatements */: + return token() === 19 /* CloseBraceToken */ || token() === 74 /* CaseKeyword */ || token() === 80 /* DefaultKeyword */; + case 7 /* HeritageClauseElement */: + return token() === 18 /* OpenBraceToken */ || token() === 86 /* ExtendsKeyword */ || token() === 109 /* ImplementsKeyword */; + case 8 /* VariableDeclarations */: + return isVariableDeclaratorListTerminator(); + case 19 /* TypeParameters */: + // Tokens other than '>' are here for better error recovery + return token() === 30 /* GreaterThanToken */ || token() === 20 /* OpenParenToken */ || token() === 18 /* OpenBraceToken */ || token() === 86 /* ExtendsKeyword */ || token() === 109 /* ImplementsKeyword */; + case 11 /* ArgumentExpressions */: + // Tokens other than ')' are here for better error recovery + return token() === 21 /* CloseParenToken */ || token() === 26 /* SemicolonToken */; + case 15 /* ArrayLiteralMembers */: + case 21 /* TupleElementTypes */: + case 10 /* ArrayBindingElements */: + return token() === 23 /* CloseBracketToken */; + case 17 /* JSDocParameters */: + case 16 /* Parameters */: + case 18 /* RestProperties */: + // Tokens other than ')' and ']' (the latter for index signatures) are here for better error recovery + return token() === 21 /* CloseParenToken */ || token() === 23 /* CloseBracketToken */ /*|| token === SyntaxKind.OpenBraceToken*/; + case 20 /* TypeArguments */: + // All other tokens should cause the type-argument to terminate except comma token + return token() !== 27 /* CommaToken */; + case 22 /* HeritageClauses */: + return token() === 18 /* OpenBraceToken */ || token() === 19 /* CloseBraceToken */; + case 13 /* JsxAttributes */: + return token() === 30 /* GreaterThanToken */ || token() === 42 /* SlashToken */; + case 14 /* JsxChildren */: + return token() === 28 /* LessThanToken */ && lookAhead(nextTokenIsSlash); + default: + return false; + } + } + function isVariableDeclaratorListTerminator() { + // If we can consume a semicolon (either explicitly, or with ASI), then consider us done + // with parsing the list of variable declarators. + if (canParseSemicolon()) { + return true; + } + // in the case where we're parsing the variable declarator of a 'for-in' statement, we + // are done if we see an 'in' keyword in front of us. Same with for-of + if (isInOrOfKeyword(token())) { + return true; + } + // ERROR RECOVERY TWEAK: + // For better error recovery, if we see an '=>' then we just stop immediately. We've got an + // arrow function here and it's going to be very unlikely that we'll resynchronize and get + // another variable declaration. + if (token() === 37 /* EqualsGreaterThanToken */) { + return true; + } + // Keep trying to parse out variable declarators. + return false; + } + // True if positioned at element or terminator of the current list or any enclosing list + function isInSomeParsingContext() { + for (var kind = 0; kind < 24 /* Count */; kind++) { + if (parsingContext & (1 << kind)) { + if (isListElement(kind, /*inErrorRecovery*/ true) || isListTerminator(kind)) { + return true; + } + } + } + return false; + } + // Parses a list of elements + function parseList(kind, parseElement) { + var saveParsingContext = parsingContext; + parsingContext |= 1 << kind; + var list = []; + var listPos = getNodePos(); + while (!isListTerminator(kind)) { + if (isListElement(kind, /*inErrorRecovery*/ false)) { + var element = parseListElement(kind, parseElement); + list.push(element); + continue; + } + if (abortParsingListOrMoveToNextToken(kind)) { + break; + } + } + parsingContext = saveParsingContext; + return createNodeArray(list, listPos); + } + function parseListElement(parsingContext, parseElement) { + var node = currentNode(parsingContext); + if (node) { + return consumeNode(node); + } + return parseElement(); + } + function currentNode(parsingContext) { + // If there is an outstanding parse error that we've encountered, but not attached to + // some node, then we cannot get a node from the old source tree. This is because we + // want to mark the next node we encounter as being unusable. + // + // Note: This may be too conservative. Perhaps we could reuse the node and set the bit + // on it (or its leftmost child) as having the error. For now though, being conservative + // is nice and likely won't ever affect perf. + if (parseErrorBeforeNextFinishedNode) { + return undefined; + } + if (!syntaxCursor) { + // if we don't have a cursor, we could never return a node from the old tree. + return undefined; + } + var node = syntaxCursor.currentNode(scanner.getStartPos()); + // Can't reuse a missing node. + if (ts.nodeIsMissing(node)) { + return undefined; + } + // Can't reuse a node that intersected the change range. + if (node.intersectsChange) { + return undefined; + } + // Can't reuse a node that contains a parse error. This is necessary so that we + // produce the same set of errors again. + if (ts.containsParseError(node)) { + return undefined; + } + // We can only reuse a node if it was parsed under the same strict mode that we're + // currently in. i.e. if we originally parsed a node in non-strict mode, but then + // the user added 'using strict' at the top of the file, then we can't use that node + // again as the presence of strict mode may cause us to parse the tokens in the file + // differently. + // + // Note: we *can* reuse tokens when the strict mode changes. That's because tokens + // are unaffected by strict mode. It's just the parser will decide what to do with it + // differently depending on what mode it is in. + // + // This also applies to all our other context flags as well. + var nodeContextFlags = node.flags & 12679168 /* ContextFlags */; + if (nodeContextFlags !== contextFlags) { + return undefined; + } + // Ok, we have a node that looks like it could be reused. Now verify that it is valid + // in the current list parsing context that we're currently at. + if (!canReuseNode(node, parsingContext)) { + return undefined; + } + if (node.jsDocCache) { + // jsDocCache may include tags from parent nodes, which might have been modified. + node.jsDocCache = undefined; + } + return node; + } + function consumeNode(node) { + // Move the scanner so it is after the node we just consumed. + scanner.setTextPos(node.end); + nextToken(); + return node; + } + function canReuseNode(node, parsingContext) { + switch (parsingContext) { + case 5 /* ClassMembers */: + return isReusableClassMember(node); + case 2 /* SwitchClauses */: + return isReusableSwitchClause(node); + case 0 /* SourceElements */: + case 1 /* BlockStatements */: + case 3 /* SwitchClauseStatements */: + return isReusableStatement(node); + case 6 /* EnumMembers */: + return isReusableEnumMember(node); + case 4 /* TypeMembers */: + return isReusableTypeMember(node); + case 8 /* VariableDeclarations */: + return isReusableVariableDeclaration(node); + case 17 /* JSDocParameters */: + case 16 /* Parameters */: + return isReusableParameter(node); + case 18 /* RestProperties */: + return false; + // Any other lists we do not care about reusing nodes in. But feel free to add if + // you can do so safely. Danger areas involve nodes that may involve speculative + // parsing. If speculative parsing is involved with the node, then the range the + // parser reached while looking ahead might be in the edited range (see the example + // in canReuseVariableDeclaratorNode for a good case of this). + case 22 /* HeritageClauses */: + // This would probably be safe to reuse. There is no speculative parsing with + // heritage clauses. + case 19 /* TypeParameters */: + // This would probably be safe to reuse. There is no speculative parsing with + // type parameters. Note that that's because type *parameters* only occur in + // unambiguous *type* contexts. While type *arguments* occur in very ambiguous + // *expression* contexts. + case 21 /* TupleElementTypes */: + // This would probably be safe to reuse. There is no speculative parsing with + // tuple types. + // Technically, type argument list types are probably safe to reuse. While + // speculative parsing is involved with them (since type argument lists are only + // produced from speculative parsing a < as a type argument list), we only have + // the types because speculative parsing succeeded. Thus, the lookahead never + // went past the end of the list and rewound. + case 20 /* TypeArguments */: + // Note: these are almost certainly not safe to ever reuse. Expressions commonly + // need a large amount of lookahead, and we should not reuse them as they may + // have actually intersected the edit. + case 11 /* ArgumentExpressions */: + // This is not safe to reuse for the same reason as the 'AssignmentExpression' + // cases. i.e. a property assignment may end with an expression, and thus might + // have lookahead far beyond it's old node. + case 12 /* ObjectLiteralMembers */: + // This is probably not safe to reuse. There can be speculative parsing with + // type names in a heritage clause. There can be generic names in the type + // name list, and there can be left hand side expressions (which can have type + // arguments.) + case 7 /* HeritageClauseElement */: + // Perhaps safe to reuse, but it's unlikely we'd see more than a dozen attributes + // on any given element. Same for children. + case 13 /* JsxAttributes */: + case 14 /* JsxChildren */: + } + return false; + } + function isReusableClassMember(node) { + if (node) { + switch (node.kind) { + case 157 /* Constructor */: + case 162 /* IndexSignature */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 154 /* PropertyDeclaration */: + case 217 /* SemicolonClassElement */: + return true; + case 156 /* MethodDeclaration */: + // Method declarations are not necessarily reusable. An object-literal + // may have a method calls "constructor(...)" and we must reparse that + // into an actual .ConstructorDeclaration. + var methodDeclaration = node; + var nameIsConstructor = methodDeclaration.name.kind === 72 /* Identifier */ && + methodDeclaration.name.originalKeywordKind === 124 /* ConstructorKeyword */; + return !nameIsConstructor; + } + } + return false; + } + function isReusableSwitchClause(node) { + if (node) { + switch (node.kind) { + case 271 /* CaseClause */: + case 272 /* DefaultClause */: + return true; + } + } + return false; + } + function isReusableStatement(node) { + if (node) { + switch (node.kind) { + case 239 /* FunctionDeclaration */: + case 219 /* VariableStatement */: + case 218 /* Block */: + case 222 /* IfStatement */: + case 221 /* ExpressionStatement */: + case 234 /* ThrowStatement */: + case 230 /* ReturnStatement */: + case 232 /* SwitchStatement */: + case 229 /* BreakStatement */: + case 228 /* ContinueStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + case 225 /* ForStatement */: + case 224 /* WhileStatement */: + case 231 /* WithStatement */: + case 220 /* EmptyStatement */: + case 235 /* TryStatement */: + case 233 /* LabeledStatement */: + case 223 /* DoStatement */: + case 236 /* DebuggerStatement */: + case 249 /* ImportDeclaration */: + case 248 /* ImportEqualsDeclaration */: + case 255 /* ExportDeclaration */: + case 254 /* ExportAssignment */: + case 244 /* ModuleDeclaration */: + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + case 243 /* EnumDeclaration */: + case 242 /* TypeAliasDeclaration */: + return true; + } + } + return false; + } + function isReusableEnumMember(node) { + return node.kind === 278 /* EnumMember */; + } + function isReusableTypeMember(node) { + if (node) { + switch (node.kind) { + case 161 /* ConstructSignature */: + case 155 /* MethodSignature */: + case 162 /* IndexSignature */: + case 153 /* PropertySignature */: + case 160 /* CallSignature */: + return true; + } + } + return false; + } + function isReusableVariableDeclaration(node) { + if (node.kind !== 237 /* VariableDeclaration */) { + return false; + } + // Very subtle incremental parsing bug. Consider the following code: + // + // let v = new List < A, B + // + // This is actually legal code. It's a list of variable declarators "v = new List() + // + // then we have a problem. "v = new List= 0) { + // Always preserve a trailing comma by marking it on the NodeArray + result.hasTrailingComma = true; + } + return result; + } + function createMissingList() { + var list = createNodeArray([], getNodePos()); + list.isMissingList = true; + return list; + } + function isMissingList(arr) { + return !!arr.isMissingList; + } + function parseBracketedList(kind, parseElement, open, close) { + if (parseExpected(open)) { + var result = parseDelimitedList(kind, parseElement); + parseExpected(close); + return result; + } + return createMissingList(); + } + function parseEntityName(allowReservedWords, diagnosticMessage) { + var entity = allowReservedWords ? parseIdentifierName(diagnosticMessage) : parseIdentifier(diagnosticMessage); + var dotPos = scanner.getStartPos(); + while (parseOptional(24 /* DotToken */)) { + if (token() === 28 /* LessThanToken */) { + // the entity is part of a JSDoc-style generic, so record the trailing dot for later error reporting + entity.jsdocDotPos = dotPos; + break; + } + dotPos = scanner.getStartPos(); + entity = createQualifiedName(entity, parseRightSideOfDot(allowReservedWords)); + } + return entity; + } + function createQualifiedName(entity, name) { + var node = createNode(148 /* QualifiedName */, entity.pos); + node.left = entity; + node.right = name; + return finishNode(node); + } + function parseRightSideOfDot(allowIdentifierNames) { + // Technically a keyword is valid here as all identifiers and keywords are identifier names. + // However, often we'll encounter this in error situations when the identifier or keyword + // is actually starting another valid construct. + // + // So, we check for the following specific case: + // + // name. + // identifierOrKeyword identifierNameOrKeyword + // + // Note: the newlines are important here. For example, if that above code + // were rewritten into: + // + // name.identifierOrKeyword + // identifierNameOrKeyword + // + // Then we would consider it valid. That's because ASI would take effect and + // the code would be implicitly: "name.identifierOrKeyword; identifierNameOrKeyword". + // In the first case though, ASI will not take effect because there is not a + // line terminator after the identifier or keyword. + if (scanner.hasPrecedingLineBreak() && ts.tokenIsIdentifierOrKeyword(token())) { + var matchesPattern = lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine); + if (matchesPattern) { + // Report that we need an identifier. However, report it right after the dot, + // and not on the next token. This is because the next token might actually + // be an identifier and the error would be quite confusing. + return createMissingNode(72 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Identifier_expected); + } + } + return allowIdentifierNames ? parseIdentifierName() : parseIdentifier(); + } + function parseTemplateExpression() { + var template = createNode(206 /* TemplateExpression */); + template.head = parseTemplateHead(); + ts.Debug.assert(template.head.kind === 15 /* TemplateHead */, "Template head has wrong token kind"); + var list = []; + var listPos = getNodePos(); + do { + list.push(parseTemplateSpan()); + } while (ts.last(list).literal.kind === 16 /* TemplateMiddle */); + template.templateSpans = createNodeArray(list, listPos); + return finishNode(template); + } + function parseTemplateSpan() { + var span = createNode(216 /* TemplateSpan */); + span.expression = allowInAnd(parseExpression); + var literal; + if (token() === 19 /* CloseBraceToken */) { + reScanTemplateToken(); + literal = parseTemplateMiddleOrTemplateTail(); + } + else { + literal = parseExpectedToken(17 /* TemplateTail */, ts.Diagnostics._0_expected, ts.tokenToString(19 /* CloseBraceToken */)); + } + span.literal = literal; + return finishNode(span); + } + function parseLiteralNode() { + return parseLiteralLikeNode(token()); + } + function parseTemplateHead() { + var fragment = parseLiteralLikeNode(token()); + ts.Debug.assert(fragment.kind === 15 /* TemplateHead */, "Template head has wrong token kind"); + return fragment; + } + function parseTemplateMiddleOrTemplateTail() { + var fragment = parseLiteralLikeNode(token()); + ts.Debug.assert(fragment.kind === 16 /* TemplateMiddle */ || fragment.kind === 17 /* TemplateTail */, "Template fragment has wrong token kind"); + return fragment; + } + function parseLiteralLikeNode(kind) { + var node = createNode(kind); + node.text = scanner.getTokenValue(); + if (scanner.hasExtendedUnicodeEscape()) { + node.hasExtendedUnicodeEscape = true; + } + if (scanner.isUnterminated()) { + node.isUnterminated = true; + } + // Octal literals are not allowed in strict mode or ES5 + // Note that theoretically the following condition would hold true literals like 009, + // which is not octal.But because of how the scanner separates the tokens, we would + // never get a token like this. Instead, we would get 00 and 9 as two separate tokens. + // We also do not need to check for negatives because any prefix operator would be part of a + // parent unary expression. + if (node.kind === 8 /* NumericLiteral */) { + node.numericLiteralFlags = scanner.getTokenFlags() & 1008 /* NumericLiteralFlags */; + } + nextToken(); + finishNode(node); + return node; + } + // TYPES + function parseTypeReference() { + var node = createNode(164 /* TypeReference */); + node.typeName = parseEntityName(/*allowReservedWords*/ true, ts.Diagnostics.Type_expected); + if (!scanner.hasPrecedingLineBreak() && token() === 28 /* LessThanToken */) { + node.typeArguments = parseBracketedList(20 /* TypeArguments */, parseType, 28 /* LessThanToken */, 30 /* GreaterThanToken */); + } + return finishNode(node); + } + // If true, we should abort parsing an error function. + function typeHasArrowFunctionBlockingParseError(node) { + switch (node.kind) { + case 164 /* TypeReference */: + return ts.nodeIsMissing(node.typeName); + case 165 /* FunctionType */: + case 166 /* ConstructorType */: { + var _a = node, parameters = _a.parameters, type = _a.type; + return isMissingList(parameters) || typeHasArrowFunctionBlockingParseError(type); + } + case 177 /* ParenthesizedType */: + return typeHasArrowFunctionBlockingParseError(node.type); + default: + return false; + } + } + function parseThisTypePredicate(lhs) { + nextToken(); + var node = createNode(163 /* TypePredicate */, lhs.pos); + node.parameterName = lhs; + node.type = parseType(); + return finishNode(node); + } + function parseThisTypeNode() { + var node = createNode(178 /* ThisType */); + nextToken(); + return finishNode(node); + } + function parseJSDocAllType(postFixEquals) { + var result = createNode(284 /* JSDocAllType */); + if (postFixEquals) { + return createPostfixType(288 /* JSDocOptionalType */, result); + } + else { + nextToken(); + } + return finishNode(result); + } + function parseJSDocNonNullableType() { + var result = createNode(287 /* JSDocNonNullableType */); + nextToken(); + result.type = parseNonArrayType(); + return finishNode(result); + } + function parseJSDocUnknownOrNullableType() { + var pos = scanner.getStartPos(); + // skip the ? + nextToken(); + // Need to lookahead to decide if this is a nullable or unknown type. + // Here are cases where we'll pick the unknown type: + // + // Foo(?, + // { a: ? } + // Foo(?) + // Foo + // Foo(?= + // (?| + if (token() === 27 /* CommaToken */ || + token() === 19 /* CloseBraceToken */ || + token() === 21 /* CloseParenToken */ || + token() === 30 /* GreaterThanToken */ || + token() === 59 /* EqualsToken */ || + token() === 50 /* BarToken */) { + var result = createNode(285 /* JSDocUnknownType */, pos); + return finishNode(result); + } + else { + var result = createNode(286 /* JSDocNullableType */, pos); + result.type = parseType(); + return finishNode(result); + } + } + function parseJSDocFunctionType() { + if (lookAhead(nextTokenIsOpenParen)) { + var result = createNodeWithJSDoc(289 /* JSDocFunctionType */); + nextToken(); + fillSignature(57 /* ColonToken */, 4 /* Type */ | 32 /* JSDoc */, result); + return finishNode(result); + } + var node = createNode(164 /* TypeReference */); + node.typeName = parseIdentifierName(); + return finishNode(node); + } + function parseJSDocParameter() { + var parameter = createNode(151 /* Parameter */); + if (token() === 100 /* ThisKeyword */ || token() === 95 /* NewKeyword */) { + parameter.name = parseIdentifierName(); + parseExpected(57 /* ColonToken */); + } + parameter.type = parseJSDocType(); + return finishNode(parameter); + } + function parseJSDocType() { + scanner.setInJSDocType(true); + var dotdotdot = parseOptionalToken(25 /* DotDotDotToken */); + var type = parseTypeOrTypePredicate(); + scanner.setInJSDocType(false); + if (dotdotdot) { + var variadic = createNode(290 /* JSDocVariadicType */, dotdotdot.pos); + variadic.type = type; + type = finishNode(variadic); + } + if (token() === 59 /* EqualsToken */) { + return createPostfixType(288 /* JSDocOptionalType */, type); + } + return type; + } + function parseTypeQuery() { + var node = createNode(167 /* TypeQuery */); + parseExpected(104 /* TypeOfKeyword */); + node.exprName = parseEntityName(/*allowReservedWords*/ true); + return finishNode(node); + } + function parseTypeParameter() { + var node = createNode(150 /* TypeParameter */); + node.name = parseIdentifier(); + if (parseOptional(86 /* ExtendsKeyword */)) { + // It's not uncommon for people to write improper constraints to a generic. If the + // user writes a constraint that is an expression and not an actual type, then parse + // it out as an expression (so we can recover well), but report that a type is needed + // instead. + if (isStartOfType() || !isStartOfExpression()) { + node.constraint = parseType(); + } + else { + // It was not a type, and it looked like an expression. Parse out an expression + // here so we recover well. Note: it is important that we call parseUnaryExpression + // and not parseExpression here. If the user has: + // + // + // + // We do *not* want to consume the `>` as we're consuming the expression for "". + node.expression = parseUnaryExpressionOrHigher(); + } + } + if (parseOptional(59 /* EqualsToken */)) { + node.default = parseType(); + } + return finishNode(node); + } + function parseTypeParameters() { + if (token() === 28 /* LessThanToken */) { + return parseBracketedList(19 /* TypeParameters */, parseTypeParameter, 28 /* LessThanToken */, 30 /* GreaterThanToken */); + } + } + function parseParameterType() { + if (parseOptional(57 /* ColonToken */)) { + return parseType(); + } + return undefined; + } + function isStartOfParameter(isJSDocParameter) { + return token() === 25 /* DotDotDotToken */ || + isIdentifierOrPattern() || + ts.isModifierKind(token()) || + token() === 58 /* AtToken */ || + isStartOfType(/*inStartOfParameter*/ !isJSDocParameter); + } + function parseParameter() { + var node = createNodeWithJSDoc(151 /* Parameter */); + if (token() === 100 /* ThisKeyword */) { + node.name = createIdentifier(/*isIdentifier*/ true); + node.type = parseParameterType(); + return finishNode(node); + } + node.decorators = parseDecorators(); + node.modifiers = parseModifiers(); + node.dotDotDotToken = parseOptionalToken(25 /* DotDotDotToken */); + // FormalParameter [Yield,Await]: + // BindingElement[?Yield,?Await] + node.name = parseIdentifierOrPattern(); + if (ts.getFullWidth(node.name) === 0 && !ts.hasModifiers(node) && ts.isModifierKind(token())) { + // in cases like + // 'use strict' + // function foo(static) + // isParameter('static') === true, because of isModifier('static') + // however 'static' is not a legal identifier in a strict mode. + // so result of this function will be ParameterDeclaration (flags = 0, name = missing, type = undefined, initializer = undefined) + // and current token will not change => parsing of the enclosing parameter list will last till the end of time (or OOM) + // to avoid this we'll advance cursor to the next token. + nextToken(); + } + node.questionToken = parseOptionalToken(56 /* QuestionToken */); + node.type = parseParameterType(); + node.initializer = parseInitializer(); + return finishNode(node); + } + /** + * Note: If returnToken is EqualsGreaterThanToken, `signature.type` will always be defined. + * @returns If return type parsing succeeds + */ + function fillSignature(returnToken, flags, signature) { + if (!(flags & 32 /* JSDoc */)) { + signature.typeParameters = parseTypeParameters(); + } + var parametersParsedSuccessfully = parseParameterList(signature, flags); + if (shouldParseReturnType(returnToken, !!(flags & 4 /* Type */))) { + signature.type = parseTypeOrTypePredicate(); + if (typeHasArrowFunctionBlockingParseError(signature.type)) + return false; + } + return parametersParsedSuccessfully; + } + function shouldParseReturnType(returnToken, isType) { + if (returnToken === 37 /* EqualsGreaterThanToken */) { + parseExpected(returnToken); + return true; + } + else if (parseOptional(57 /* ColonToken */)) { + return true; + } + else if (isType && token() === 37 /* EqualsGreaterThanToken */) { + // This is easy to get backward, especially in type contexts, so parse the type anyway + parseErrorAtCurrentToken(ts.Diagnostics._0_expected, ts.tokenToString(57 /* ColonToken */)); + nextToken(); + return true; + } + return false; + } + // Returns true on success. + function parseParameterList(signature, flags) { + // FormalParameters [Yield,Await]: (modified) + // [empty] + // FormalParameterList[?Yield,Await] + // + // FormalParameter[Yield,Await]: (modified) + // BindingElement[?Yield,Await] + // + // BindingElement [Yield,Await]: (modified) + // SingleNameBinding[?Yield,?Await] + // BindingPattern[?Yield,?Await]Initializer [In, ?Yield,?Await] opt + // + // SingleNameBinding [Yield,Await]: + // BindingIdentifier[?Yield,?Await]Initializer [In, ?Yield,?Await] opt + if (!parseExpected(20 /* OpenParenToken */)) { + signature.parameters = createMissingList(); + return false; + } + var savedYieldContext = inYieldContext(); + var savedAwaitContext = inAwaitContext(); + setYieldContext(!!(flags & 1 /* Yield */)); + setAwaitContext(!!(flags & 2 /* Await */)); + signature.parameters = flags & 32 /* JSDoc */ ? + parseDelimitedList(17 /* JSDocParameters */, parseJSDocParameter) : + parseDelimitedList(16 /* Parameters */, parseParameter); + setYieldContext(savedYieldContext); + setAwaitContext(savedAwaitContext); + return parseExpected(21 /* CloseParenToken */); + } + function parseTypeMemberSemicolon() { + // We allow type members to be separated by commas or (possibly ASI) semicolons. + // First check if it was a comma. If so, we're done with the member. + if (parseOptional(27 /* CommaToken */)) { + return; + } + // Didn't have a comma. We must have a (possible ASI) semicolon. + parseSemicolon(); + } + function parseSignatureMember(kind) { + var node = createNodeWithJSDoc(kind); + if (kind === 161 /* ConstructSignature */) { + parseExpected(95 /* NewKeyword */); + } + fillSignature(57 /* ColonToken */, 4 /* Type */, node); + parseTypeMemberSemicolon(); + return finishNode(node); + } + function isIndexSignature() { + return token() === 22 /* OpenBracketToken */ && lookAhead(isUnambiguouslyIndexSignature); + } + function isUnambiguouslyIndexSignature() { + // The only allowed sequence is: + // + // [id: + // + // However, for error recovery, we also check the following cases: + // + // [... + // [id, + // [id?, + // [id?: + // [id?] + // [public id + // [private id + // [protected id + // [] + // + nextToken(); + if (token() === 25 /* DotDotDotToken */ || token() === 23 /* CloseBracketToken */) { + return true; + } + if (ts.isModifierKind(token())) { + nextToken(); + if (isIdentifier()) { + return true; + } + } + else if (!isIdentifier()) { + return false; + } + else { + // Skip the identifier + nextToken(); + } + // A colon signifies a well formed indexer + // A comma should be a badly formed indexer because comma expressions are not allowed + // in computed properties. + if (token() === 57 /* ColonToken */ || token() === 27 /* CommaToken */) { + return true; + } + // Question mark could be an indexer with an optional property, + // or it could be a conditional expression in a computed property. + if (token() !== 56 /* QuestionToken */) { + return false; + } + // If any of the following tokens are after the question mark, it cannot + // be a conditional expression, so treat it as an indexer. + nextToken(); + return token() === 57 /* ColonToken */ || token() === 27 /* CommaToken */ || token() === 23 /* CloseBracketToken */; + } + function parseIndexSignatureDeclaration(node) { + node.kind = 162 /* IndexSignature */; + node.parameters = parseBracketedList(16 /* Parameters */, parseParameter, 22 /* OpenBracketToken */, 23 /* CloseBracketToken */); + node.type = parseTypeAnnotation(); + parseTypeMemberSemicolon(); + return finishNode(node); + } + function parsePropertyOrMethodSignature(node) { + node.name = parsePropertyName(); + node.questionToken = parseOptionalToken(56 /* QuestionToken */); + if (token() === 20 /* OpenParenToken */ || token() === 28 /* LessThanToken */) { + node.kind = 155 /* MethodSignature */; + // Method signatures don't exist in expression contexts. So they have neither + // [Yield] nor [Await] + fillSignature(57 /* ColonToken */, 4 /* Type */, node); + } + else { + node.kind = 153 /* PropertySignature */; + node.type = parseTypeAnnotation(); + if (token() === 59 /* EqualsToken */) { + // Although type literal properties cannot not have initializers, we attempt + // to parse an initializer so we can report in the checker that an interface + // property or type literal property cannot have an initializer. + node.initializer = parseInitializer(); + } + } + parseTypeMemberSemicolon(); + return finishNode(node); + } + function isTypeMemberStart() { + // Return true if we have the start of a signature member + if (token() === 20 /* OpenParenToken */ || token() === 28 /* LessThanToken */) { + return true; + } + var idToken = false; + // Eat up all modifiers, but hold on to the last one in case it is actually an identifier + while (ts.isModifierKind(token())) { + idToken = true; + nextToken(); + } + // Index signatures and computed property names are type members + if (token() === 22 /* OpenBracketToken */) { + return true; + } + // Try to get the first property-like token following all modifiers + if (isLiteralPropertyName()) { + idToken = true; + nextToken(); + } + // If we were able to get any potential identifier, check that it is + // the start of a member declaration + if (idToken) { + return token() === 20 /* OpenParenToken */ || + token() === 28 /* LessThanToken */ || + token() === 56 /* QuestionToken */ || + token() === 57 /* ColonToken */ || + token() === 27 /* CommaToken */ || + canParseSemicolon(); + } + return false; + } + function parseTypeMember() { + if (token() === 20 /* OpenParenToken */ || token() === 28 /* LessThanToken */) { + return parseSignatureMember(160 /* CallSignature */); + } + if (token() === 95 /* NewKeyword */ && lookAhead(nextTokenIsOpenParenOrLessThan)) { + return parseSignatureMember(161 /* ConstructSignature */); + } + var node = createNodeWithJSDoc(0 /* Unknown */); + node.modifiers = parseModifiers(); + if (isIndexSignature()) { + return parseIndexSignatureDeclaration(node); + } + return parsePropertyOrMethodSignature(node); + } + function nextTokenIsOpenParenOrLessThan() { + nextToken(); + return token() === 20 /* OpenParenToken */ || token() === 28 /* LessThanToken */; + } + function nextTokenIsDot() { + return nextToken() === 24 /* DotToken */; + } + function nextTokenIsOpenParenOrLessThanOrDot() { + switch (nextToken()) { + case 20 /* OpenParenToken */: + case 28 /* LessThanToken */: + case 24 /* DotToken */: + return true; + } + return false; + } + function parseTypeLiteral() { + var node = createNode(168 /* TypeLiteral */); + node.members = parseObjectTypeMembers(); + return finishNode(node); + } + function parseObjectTypeMembers() { + var members; + if (parseExpected(18 /* OpenBraceToken */)) { + members = parseList(4 /* TypeMembers */, parseTypeMember); + parseExpected(19 /* CloseBraceToken */); + } + else { + members = createMissingList(); + } + return members; + } + function isStartOfMappedType() { + nextToken(); + if (token() === 38 /* PlusToken */ || token() === 39 /* MinusToken */) { + return nextToken() === 133 /* ReadonlyKeyword */; + } + if (token() === 133 /* ReadonlyKeyword */) { + nextToken(); + } + return token() === 22 /* OpenBracketToken */ && nextTokenIsIdentifier() && nextToken() === 93 /* InKeyword */; + } + function parseMappedTypeParameter() { + var node = createNode(150 /* TypeParameter */); + node.name = parseIdentifier(); + parseExpected(93 /* InKeyword */); + node.constraint = parseType(); + return finishNode(node); + } + function parseMappedType() { + var node = createNode(181 /* MappedType */); + parseExpected(18 /* OpenBraceToken */); + if (token() === 133 /* ReadonlyKeyword */ || token() === 38 /* PlusToken */ || token() === 39 /* MinusToken */) { + node.readonlyToken = parseTokenNode(); + if (node.readonlyToken.kind !== 133 /* ReadonlyKeyword */) { + parseExpectedToken(133 /* ReadonlyKeyword */); + } + } + parseExpected(22 /* OpenBracketToken */); + node.typeParameter = parseMappedTypeParameter(); + parseExpected(23 /* CloseBracketToken */); + if (token() === 56 /* QuestionToken */ || token() === 38 /* PlusToken */ || token() === 39 /* MinusToken */) { + node.questionToken = parseTokenNode(); + if (node.questionToken.kind !== 56 /* QuestionToken */) { + parseExpectedToken(56 /* QuestionToken */); + } + } + node.type = parseTypeAnnotation(); + parseSemicolon(); + parseExpected(19 /* CloseBraceToken */); + return finishNode(node); + } + function parseTupleElementType() { + var pos = getNodePos(); + if (parseOptional(25 /* DotDotDotToken */)) { + var node = createNode(172 /* RestType */, pos); + node.type = parseType(); + return finishNode(node); + } + var type = parseType(); + if (!(contextFlags & 2097152 /* JSDoc */) && type.kind === 286 /* JSDocNullableType */ && type.pos === type.type.pos) { + type.kind = 171 /* OptionalType */; + } + return type; + } + function parseTupleType() { + var node = createNode(170 /* TupleType */); + node.elementTypes = parseBracketedList(21 /* TupleElementTypes */, parseTupleElementType, 22 /* OpenBracketToken */, 23 /* CloseBracketToken */); + return finishNode(node); + } + function parseParenthesizedType() { + var node = createNode(177 /* ParenthesizedType */); + parseExpected(20 /* OpenParenToken */); + node.type = parseType(); + parseExpected(21 /* CloseParenToken */); + return finishNode(node); + } + function parseFunctionOrConstructorType() { + var pos = getNodePos(); + var kind = parseOptional(95 /* NewKeyword */) ? 166 /* ConstructorType */ : 165 /* FunctionType */; + var node = createNodeWithJSDoc(kind, pos); + fillSignature(37 /* EqualsGreaterThanToken */, 4 /* Type */, node); + return finishNode(node); + } + function parseKeywordAndNoDot() { + var node = parseTokenNode(); + return token() === 24 /* DotToken */ ? undefined : node; + } + function parseLiteralTypeNode(negative) { + var node = createNode(182 /* LiteralType */); + var unaryMinusExpression; + if (negative) { + unaryMinusExpression = createNode(202 /* PrefixUnaryExpression */); + unaryMinusExpression.operator = 39 /* MinusToken */; + nextToken(); + } + var expression = token() === 102 /* TrueKeyword */ || token() === 87 /* FalseKeyword */ + ? parseTokenNode() + : parseLiteralLikeNode(token()); + if (negative) { + unaryMinusExpression.operand = expression; + finishNode(unaryMinusExpression); + expression = unaryMinusExpression; + } + node.literal = expression; + return finishNode(node); + } + function isStartOfTypeOfImportType() { + nextToken(); + return token() === 92 /* ImportKeyword */; + } + function parseImportType() { + sourceFile.flags |= 524288 /* PossiblyContainsDynamicImport */; + var node = createNode(183 /* ImportType */); + if (parseOptional(104 /* TypeOfKeyword */)) { + node.isTypeOf = true; + } + parseExpected(92 /* ImportKeyword */); + parseExpected(20 /* OpenParenToken */); + node.argument = parseType(); + parseExpected(21 /* CloseParenToken */); + if (parseOptional(24 /* DotToken */)) { + node.qualifier = parseEntityName(/*allowReservedWords*/ true, ts.Diagnostics.Type_expected); + } + node.typeArguments = tryParseTypeArguments(); + return finishNode(node); + } + function nextTokenIsNumericOrBigIntLiteral() { + nextToken(); + return token() === 8 /* NumericLiteral */ || token() === 9 /* BigIntLiteral */; + } + function parseNonArrayType() { + switch (token()) { + case 120 /* AnyKeyword */: + case 143 /* UnknownKeyword */: + case 138 /* StringKeyword */: + case 135 /* NumberKeyword */: + case 146 /* BigIntKeyword */: + case 139 /* SymbolKeyword */: + case 123 /* BooleanKeyword */: + case 141 /* UndefinedKeyword */: + case 132 /* NeverKeyword */: + case 136 /* ObjectKeyword */: + // If these are followed by a dot, then parse these out as a dotted type reference instead. + return tryParse(parseKeywordAndNoDot) || parseTypeReference(); + case 40 /* AsteriskToken */: + return parseJSDocAllType(/*postfixEquals*/ false); + case 62 /* AsteriskEqualsToken */: + return parseJSDocAllType(/*postfixEquals*/ true); + case 56 /* QuestionToken */: + return parseJSDocUnknownOrNullableType(); + case 90 /* FunctionKeyword */: + return parseJSDocFunctionType(); + case 52 /* ExclamationToken */: + return parseJSDocNonNullableType(); + case 14 /* NoSubstitutionTemplateLiteral */: + case 10 /* StringLiteral */: + case 8 /* NumericLiteral */: + case 9 /* BigIntLiteral */: + case 102 /* TrueKeyword */: + case 87 /* FalseKeyword */: + return parseLiteralTypeNode(); + case 39 /* MinusToken */: + return lookAhead(nextTokenIsNumericOrBigIntLiteral) ? parseLiteralTypeNode(/*negative*/ true) : parseTypeReference(); + case 106 /* VoidKeyword */: + case 96 /* NullKeyword */: + return parseTokenNode(); + case 100 /* ThisKeyword */: { + var thisKeyword = parseThisTypeNode(); + if (token() === 128 /* IsKeyword */ && !scanner.hasPrecedingLineBreak()) { + return parseThisTypePredicate(thisKeyword); + } + else { + return thisKeyword; + } + } + case 104 /* TypeOfKeyword */: + return lookAhead(isStartOfTypeOfImportType) ? parseImportType() : parseTypeQuery(); + case 18 /* OpenBraceToken */: + return lookAhead(isStartOfMappedType) ? parseMappedType() : parseTypeLiteral(); + case 22 /* OpenBracketToken */: + return parseTupleType(); + case 20 /* OpenParenToken */: + return parseParenthesizedType(); + case 92 /* ImportKeyword */: + return parseImportType(); + default: + return parseTypeReference(); + } + } + function isStartOfType(inStartOfParameter) { + switch (token()) { + case 120 /* AnyKeyword */: + case 143 /* UnknownKeyword */: + case 138 /* StringKeyword */: + case 135 /* NumberKeyword */: + case 146 /* BigIntKeyword */: + case 123 /* BooleanKeyword */: + case 139 /* SymbolKeyword */: + case 142 /* UniqueKeyword */: + case 106 /* VoidKeyword */: + case 141 /* UndefinedKeyword */: + case 96 /* NullKeyword */: + case 100 /* ThisKeyword */: + case 104 /* TypeOfKeyword */: + case 132 /* NeverKeyword */: + case 18 /* OpenBraceToken */: + case 22 /* OpenBracketToken */: + case 28 /* LessThanToken */: + case 50 /* BarToken */: + case 49 /* AmpersandToken */: + case 95 /* NewKeyword */: + case 10 /* StringLiteral */: + case 8 /* NumericLiteral */: + case 9 /* BigIntLiteral */: + case 102 /* TrueKeyword */: + case 87 /* FalseKeyword */: + case 136 /* ObjectKeyword */: + case 40 /* AsteriskToken */: + case 56 /* QuestionToken */: + case 52 /* ExclamationToken */: + case 25 /* DotDotDotToken */: + case 127 /* InferKeyword */: + case 92 /* ImportKeyword */: + return true; + case 90 /* FunctionKeyword */: + return !inStartOfParameter; + case 39 /* MinusToken */: + return !inStartOfParameter && lookAhead(nextTokenIsNumericOrBigIntLiteral); + case 20 /* OpenParenToken */: + // Only consider '(' the start of a type if followed by ')', '...', an identifier, a modifier, + // or something that starts a type. We don't want to consider things like '(1)' a type. + return !inStartOfParameter && lookAhead(isStartOfParenthesizedOrFunctionType); + default: + return isIdentifier(); + } + } + function isStartOfParenthesizedOrFunctionType() { + nextToken(); + return token() === 21 /* CloseParenToken */ || isStartOfParameter(/*isJSDocParameter*/ false) || isStartOfType(); + } + function parsePostfixTypeOrHigher() { + var type = parseNonArrayType(); + while (!scanner.hasPrecedingLineBreak()) { + switch (token()) { + case 52 /* ExclamationToken */: + type = createPostfixType(287 /* JSDocNonNullableType */, type); + break; + case 56 /* QuestionToken */: + // If not in JSDoc and next token is start of a type we have a conditional type + if (!(contextFlags & 2097152 /* JSDoc */) && lookAhead(nextTokenIsStartOfType)) { + return type; + } + type = createPostfixType(286 /* JSDocNullableType */, type); + break; + case 22 /* OpenBracketToken */: + parseExpected(22 /* OpenBracketToken */); + if (isStartOfType()) { + var node = createNode(180 /* IndexedAccessType */, type.pos); + node.objectType = type; + node.indexType = parseType(); + parseExpected(23 /* CloseBracketToken */); + type = finishNode(node); + } + else { + var node = createNode(169 /* ArrayType */, type.pos); + node.elementType = type; + parseExpected(23 /* CloseBracketToken */); + type = finishNode(node); + } + break; + default: + return type; + } + } + return type; + } + function createPostfixType(kind, type) { + nextToken(); + var postfix = createNode(kind, type.pos); + postfix.type = type; + return finishNode(postfix); + } + function parseTypeOperator(operator) { + var node = createNode(179 /* TypeOperator */); + parseExpected(operator); + node.operator = operator; + node.type = parseTypeOperatorOrHigher(); + return finishNode(node); + } + function parseInferType() { + var node = createNode(176 /* InferType */); + parseExpected(127 /* InferKeyword */); + var typeParameter = createNode(150 /* TypeParameter */); + typeParameter.name = parseIdentifier(); + node.typeParameter = finishNode(typeParameter); + return finishNode(node); + } + function parseTypeOperatorOrHigher() { + var operator = token(); + switch (operator) { + case 129 /* KeyOfKeyword */: + case 142 /* UniqueKeyword */: + return parseTypeOperator(operator); + case 127 /* InferKeyword */: + return parseInferType(); + } + return parsePostfixTypeOrHigher(); + } + function parseUnionOrIntersectionType(kind, parseConstituentType, operator) { + parseOptional(operator); + var type = parseConstituentType(); + if (token() === operator) { + var types = [type]; + while (parseOptional(operator)) { + types.push(parseConstituentType()); + } + var node = createNode(kind, type.pos); + node.types = createNodeArray(types, type.pos); + type = finishNode(node); + } + return type; + } + function parseIntersectionTypeOrHigher() { + return parseUnionOrIntersectionType(174 /* IntersectionType */, parseTypeOperatorOrHigher, 49 /* AmpersandToken */); + } + function parseUnionTypeOrHigher() { + return parseUnionOrIntersectionType(173 /* UnionType */, parseIntersectionTypeOrHigher, 50 /* BarToken */); + } + function isStartOfFunctionType() { + if (token() === 28 /* LessThanToken */) { + return true; + } + return token() === 20 /* OpenParenToken */ && lookAhead(isUnambiguouslyStartOfFunctionType); + } + function skipParameterStart() { + if (ts.isModifierKind(token())) { + // Skip modifiers + parseModifiers(); + } + if (isIdentifier() || token() === 100 /* ThisKeyword */) { + nextToken(); + return true; + } + if (token() === 22 /* OpenBracketToken */ || token() === 18 /* OpenBraceToken */) { + // Return true if we can parse an array or object binding pattern with no errors + var previousErrorCount = parseDiagnostics.length; + parseIdentifierOrPattern(); + return previousErrorCount === parseDiagnostics.length; + } + return false; + } + function isUnambiguouslyStartOfFunctionType() { + nextToken(); + if (token() === 21 /* CloseParenToken */ || token() === 25 /* DotDotDotToken */) { + // ( ) + // ( ... + return true; + } + if (skipParameterStart()) { + // We successfully skipped modifiers (if any) and an identifier or binding pattern, + // now see if we have something that indicates a parameter declaration + if (token() === 57 /* ColonToken */ || token() === 27 /* CommaToken */ || + token() === 56 /* QuestionToken */ || token() === 59 /* EqualsToken */) { + // ( xxx : + // ( xxx , + // ( xxx ? + // ( xxx = + return true; + } + if (token() === 21 /* CloseParenToken */) { + nextToken(); + if (token() === 37 /* EqualsGreaterThanToken */) { + // ( xxx ) => + return true; + } + } + } + return false; + } + function parseTypeOrTypePredicate() { + var typePredicateVariable = isIdentifier() && tryParse(parseTypePredicatePrefix); + var type = parseType(); + if (typePredicateVariable) { + var node = createNode(163 /* TypePredicate */, typePredicateVariable.pos); + node.parameterName = typePredicateVariable; + node.type = type; + return finishNode(node); + } + else { + return type; + } + } + function parseTypePredicatePrefix() { + var id = parseIdentifier(); + if (token() === 128 /* IsKeyword */ && !scanner.hasPrecedingLineBreak()) { + nextToken(); + return id; + } + } + function parseType() { + // The rules about 'yield' only apply to actual code/expression contexts. They don't + // apply to 'type' contexts. So we disable these parameters here before moving on. + return doOutsideOfContext(20480 /* TypeExcludesFlags */, parseTypeWorker); + } + function parseTypeWorker(noConditionalTypes) { + if (isStartOfFunctionType() || token() === 95 /* NewKeyword */) { + return parseFunctionOrConstructorType(); + } + var type = parseUnionTypeOrHigher(); + if (!noConditionalTypes && !scanner.hasPrecedingLineBreak() && parseOptional(86 /* ExtendsKeyword */)) { + var node = createNode(175 /* ConditionalType */, type.pos); + node.checkType = type; + // The type following 'extends' is not permitted to be another conditional type + node.extendsType = parseTypeWorker(/*noConditionalTypes*/ true); + parseExpected(56 /* QuestionToken */); + node.trueType = parseTypeWorker(); + parseExpected(57 /* ColonToken */); + node.falseType = parseTypeWorker(); + return finishNode(node); + } + return type; + } + function parseTypeAnnotation() { + return parseOptional(57 /* ColonToken */) ? parseType() : undefined; + } + // EXPRESSIONS + function isStartOfLeftHandSideExpression() { + switch (token()) { + case 100 /* ThisKeyword */: + case 98 /* SuperKeyword */: + case 96 /* NullKeyword */: + case 102 /* TrueKeyword */: + case 87 /* FalseKeyword */: + case 8 /* NumericLiteral */: + case 9 /* BigIntLiteral */: + case 10 /* StringLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: + case 15 /* TemplateHead */: + case 20 /* OpenParenToken */: + case 22 /* OpenBracketToken */: + case 18 /* OpenBraceToken */: + case 90 /* FunctionKeyword */: + case 76 /* ClassKeyword */: + case 95 /* NewKeyword */: + case 42 /* SlashToken */: + case 64 /* SlashEqualsToken */: + case 72 /* Identifier */: + return true; + case 92 /* ImportKeyword */: + return lookAhead(nextTokenIsOpenParenOrLessThanOrDot); + default: + return isIdentifier(); + } + } + function isStartOfExpression() { + if (isStartOfLeftHandSideExpression()) { + return true; + } + switch (token()) { + case 38 /* PlusToken */: + case 39 /* MinusToken */: + case 53 /* TildeToken */: + case 52 /* ExclamationToken */: + case 81 /* DeleteKeyword */: + case 104 /* TypeOfKeyword */: + case 106 /* VoidKeyword */: + case 44 /* PlusPlusToken */: + case 45 /* MinusMinusToken */: + case 28 /* LessThanToken */: + case 122 /* AwaitKeyword */: + case 117 /* YieldKeyword */: + // Yield/await always starts an expression. Either it is an identifier (in which case + // it is definitely an expression). Or it's a keyword (either because we're in + // a generator or async function, or in strict mode (or both)) and it started a yield or await expression. + return true; + default: + // Error tolerance. If we see the start of some binary operator, we consider + // that the start of an expression. That way we'll parse out a missing identifier, + // give a good message about an identifier being missing, and then consume the + // rest of the binary expression. + if (isBinaryOperator()) { + return true; + } + return isIdentifier(); + } + } + function isStartOfExpressionStatement() { + // As per the grammar, none of '{' or 'function' or 'class' can start an expression statement. + return token() !== 18 /* OpenBraceToken */ && + token() !== 90 /* FunctionKeyword */ && + token() !== 76 /* ClassKeyword */ && + token() !== 58 /* AtToken */ && + isStartOfExpression(); + } + function parseExpression() { + // Expression[in]: + // AssignmentExpression[in] + // Expression[in] , AssignmentExpression[in] + // clear the decorator context when parsing Expression, as it should be unambiguous when parsing a decorator + var saveDecoratorContext = inDecoratorContext(); + if (saveDecoratorContext) { + setDecoratorContext(/*val*/ false); + } + var expr = parseAssignmentExpressionOrHigher(); + var operatorToken; + while ((operatorToken = parseOptionalToken(27 /* CommaToken */))) { + expr = makeBinaryExpression(expr, operatorToken, parseAssignmentExpressionOrHigher()); + } + if (saveDecoratorContext) { + setDecoratorContext(/*val*/ true); + } + return expr; + } + function parseInitializer() { + return parseOptional(59 /* EqualsToken */) ? parseAssignmentExpressionOrHigher() : undefined; + } + function parseAssignmentExpressionOrHigher() { + // AssignmentExpression[in,yield]: + // 1) ConditionalExpression[?in,?yield] + // 2) LeftHandSideExpression = AssignmentExpression[?in,?yield] + // 3) LeftHandSideExpression AssignmentOperator AssignmentExpression[?in,?yield] + // 4) ArrowFunctionExpression[?in,?yield] + // 5) AsyncArrowFunctionExpression[in,yield,await] + // 6) [+Yield] YieldExpression[?In] + // + // Note: for ease of implementation we treat productions '2' and '3' as the same thing. + // (i.e. they're both BinaryExpressions with an assignment operator in it). + // First, do the simple check if we have a YieldExpression (production '6'). + if (isYieldExpression()) { + return parseYieldExpression(); + } + // Then, check if we have an arrow function (production '4' and '5') that starts with a parenthesized + // parameter list or is an async arrow function. + // AsyncArrowFunctionExpression: + // 1) async[no LineTerminator here]AsyncArrowBindingIdentifier[?Yield][no LineTerminator here]=>AsyncConciseBody[?In] + // 2) CoverCallExpressionAndAsyncArrowHead[?Yield, ?Await][no LineTerminator here]=>AsyncConciseBody[?In] + // Production (1) of AsyncArrowFunctionExpression is parsed in "tryParseAsyncSimpleArrowFunctionExpression". + // And production (2) is parsed in "tryParseParenthesizedArrowFunctionExpression". + // + // If we do successfully parse arrow-function, we must *not* recurse for productions 1, 2 or 3. An ArrowFunction is + // not a LeftHandSideExpression, nor does it start a ConditionalExpression. So we are done + // with AssignmentExpression if we see one. + var arrowExpression = tryParseParenthesizedArrowFunctionExpression() || tryParseAsyncSimpleArrowFunctionExpression(); + if (arrowExpression) { + return arrowExpression; + } + // Now try to see if we're in production '1', '2' or '3'. A conditional expression can + // start with a LogicalOrExpression, while the assignment productions can only start with + // LeftHandSideExpressions. + // + // So, first, we try to just parse out a BinaryExpression. If we get something that is a + // LeftHandSide or higher, then we can try to parse out the assignment expression part. + // Otherwise, we try to parse out the conditional expression bit. We want to allow any + // binary expression here, so we pass in the 'lowest' precedence here so that it matches + // and consumes anything. + var expr = parseBinaryExpressionOrHigher(/*precedence*/ 0); + // To avoid a look-ahead, we did not handle the case of an arrow function with a single un-parenthesized + // parameter ('x => ...') above. We handle it here by checking if the parsed expression was a single + // identifier and the current token is an arrow. + if (expr.kind === 72 /* Identifier */ && token() === 37 /* EqualsGreaterThanToken */) { + return parseSimpleArrowFunctionExpression(expr); + } + // Now see if we might be in cases '2' or '3'. + // If the expression was a LHS expression, and we have an assignment operator, then + // we're in '2' or '3'. Consume the assignment and return. + // + // Note: we call reScanGreaterToken so that we get an appropriately merged token + // for cases like `> > =` becoming `>>=` + if (ts.isLeftHandSideExpression(expr) && ts.isAssignmentOperator(reScanGreaterToken())) { + return makeBinaryExpression(expr, parseTokenNode(), parseAssignmentExpressionOrHigher()); + } + // It wasn't an assignment or a lambda. This is a conditional expression: + return parseConditionalExpressionRest(expr); + } + function isYieldExpression() { + if (token() === 117 /* YieldKeyword */) { + // If we have a 'yield' keyword, and this is a context where yield expressions are + // allowed, then definitely parse out a yield expression. + if (inYieldContext()) { + return true; + } + // We're in a context where 'yield expr' is not allowed. However, if we can + // definitely tell that the user was trying to parse a 'yield expr' and not + // just a normal expr that start with a 'yield' identifier, then parse out + // a 'yield expr'. We can then report an error later that they are only + // allowed in generator expressions. + // + // for example, if we see 'yield(foo)', then we'll have to treat that as an + // invocation expression of something called 'yield'. However, if we have + // 'yield foo' then that is not legal as a normal expression, so we can + // definitely recognize this as a yield expression. + // + // for now we just check if the next token is an identifier. More heuristics + // can be added here later as necessary. We just need to make sure that we + // don't accidentally consume something legal. + return lookAhead(nextTokenIsIdentifierOrKeywordOrLiteralOnSameLine); + } + return false; + } + function nextTokenIsIdentifierOnSameLine() { + nextToken(); + return !scanner.hasPrecedingLineBreak() && isIdentifier(); + } + function parseYieldExpression() { + var node = createNode(207 /* YieldExpression */); + // YieldExpression[In] : + // yield + // yield [no LineTerminator here] [Lexical goal InputElementRegExp]AssignmentExpression[?In, Yield] + // yield [no LineTerminator here] * [Lexical goal InputElementRegExp]AssignmentExpression[?In, Yield] + nextToken(); + if (!scanner.hasPrecedingLineBreak() && + (token() === 40 /* AsteriskToken */ || isStartOfExpression())) { + node.asteriskToken = parseOptionalToken(40 /* AsteriskToken */); + node.expression = parseAssignmentExpressionOrHigher(); + return finishNode(node); + } + else { + // if the next token is not on the same line as yield. or we don't have an '*' or + // the start of an expression, then this is just a simple "yield" expression. + return finishNode(node); + } + } + function parseSimpleArrowFunctionExpression(identifier, asyncModifier) { + ts.Debug.assert(token() === 37 /* EqualsGreaterThanToken */, "parseSimpleArrowFunctionExpression should only have been called if we had a =>"); + var node; + if (asyncModifier) { + node = createNode(197 /* ArrowFunction */, asyncModifier.pos); + node.modifiers = asyncModifier; + } + else { + node = createNode(197 /* ArrowFunction */, identifier.pos); + } + var parameter = createNode(151 /* Parameter */, identifier.pos); + parameter.name = identifier; + finishNode(parameter); + node.parameters = createNodeArray([parameter], parameter.pos, parameter.end); + node.equalsGreaterThanToken = parseExpectedToken(37 /* EqualsGreaterThanToken */); + node.body = parseArrowFunctionExpressionBody(/*isAsync*/ !!asyncModifier); + return addJSDocComment(finishNode(node)); + } + function tryParseParenthesizedArrowFunctionExpression() { + var triState = isParenthesizedArrowFunctionExpression(); + if (triState === 0 /* False */) { + // It's definitely not a parenthesized arrow function expression. + return undefined; + } + // If we definitely have an arrow function, then we can just parse one, not requiring a + // following => or { token. Otherwise, we *might* have an arrow function. Try to parse + // it out, but don't allow any ambiguity, and return 'undefined' if this could be an + // expression instead. + var arrowFunction = triState === 1 /* True */ + ? parseParenthesizedArrowFunctionExpressionHead(/*allowAmbiguity*/ true) + : tryParse(parsePossibleParenthesizedArrowFunctionExpressionHead); + if (!arrowFunction) { + // Didn't appear to actually be a parenthesized arrow function. Just bail out. + return undefined; + } + var isAsync = ts.hasModifier(arrowFunction, 256 /* Async */); + // If we have an arrow, then try to parse the body. Even if not, try to parse if we + // have an opening brace, just in case we're in an error state. + var lastToken = token(); + arrowFunction.equalsGreaterThanToken = parseExpectedToken(37 /* EqualsGreaterThanToken */); + arrowFunction.body = (lastToken === 37 /* EqualsGreaterThanToken */ || lastToken === 18 /* OpenBraceToken */) + ? parseArrowFunctionExpressionBody(isAsync) + : parseIdentifier(); + return finishNode(arrowFunction); + } + // True -> We definitely expect a parenthesized arrow function here. + // False -> There *cannot* be a parenthesized arrow function here. + // Unknown -> There *might* be a parenthesized arrow function here. + // Speculatively look ahead to be sure, and rollback if not. + function isParenthesizedArrowFunctionExpression() { + if (token() === 20 /* OpenParenToken */ || token() === 28 /* LessThanToken */ || token() === 121 /* AsyncKeyword */) { + return lookAhead(isParenthesizedArrowFunctionExpressionWorker); + } + if (token() === 37 /* EqualsGreaterThanToken */) { + // ERROR RECOVERY TWEAK: + // If we see a standalone => try to parse it as an arrow function expression as that's + // likely what the user intended to write. + return 1 /* True */; + } + // Definitely not a parenthesized arrow function. + return 0 /* False */; + } + function isParenthesizedArrowFunctionExpressionWorker() { + if (token() === 121 /* AsyncKeyword */) { + nextToken(); + if (scanner.hasPrecedingLineBreak()) { + return 0 /* False */; + } + if (token() !== 20 /* OpenParenToken */ && token() !== 28 /* LessThanToken */) { + return 0 /* False */; + } + } + var first = token(); + var second = nextToken(); + if (first === 20 /* OpenParenToken */) { + if (second === 21 /* CloseParenToken */) { + // Simple cases: "() =>", "(): ", and "() {". + // This is an arrow function with no parameters. + // The last one is not actually an arrow function, + // but this is probably what the user intended. + var third = nextToken(); + switch (third) { + case 37 /* EqualsGreaterThanToken */: + case 57 /* ColonToken */: + case 18 /* OpenBraceToken */: + return 1 /* True */; + default: + return 0 /* False */; + } + } + // If encounter "([" or "({", this could be the start of a binding pattern. + // Examples: + // ([ x ]) => { } + // ({ x }) => { } + // ([ x ]) + // ({ x }) + if (second === 22 /* OpenBracketToken */ || second === 18 /* OpenBraceToken */) { + return 2 /* Unknown */; + } + // Simple case: "(..." + // This is an arrow function with a rest parameter. + if (second === 25 /* DotDotDotToken */) { + return 1 /* True */; + } + // Check for "(xxx yyy", where xxx is a modifier and yyy is an identifier. This + // isn't actually allowed, but we want to treat it as a lambda so we can provide + // a good error message. + if (ts.isModifierKind(second) && second !== 121 /* AsyncKeyword */ && lookAhead(nextTokenIsIdentifier)) { + return 1 /* True */; + } + // If we had "(" followed by something that's not an identifier, + // then this definitely doesn't look like a lambda. "this" is not + // valid, but we want to parse it and then give a semantic error. + if (!isIdentifier() && second !== 100 /* ThisKeyword */) { + return 0 /* False */; + } + switch (nextToken()) { + case 57 /* ColonToken */: + // If we have something like "(a:", then we must have a + // type-annotated parameter in an arrow function expression. + return 1 /* True */; + case 56 /* QuestionToken */: + nextToken(); + // If we have "(a?:" or "(a?," or "(a?=" or "(a?)" then it is definitely a lambda. + if (token() === 57 /* ColonToken */ || token() === 27 /* CommaToken */ || token() === 59 /* EqualsToken */ || token() === 21 /* CloseParenToken */) { + return 1 /* True */; + } + // Otherwise it is definitely not a lambda. + return 0 /* False */; + case 27 /* CommaToken */: + case 59 /* EqualsToken */: + case 21 /* CloseParenToken */: + // If we have "(a," or "(a=" or "(a)" this *could* be an arrow function + return 2 /* Unknown */; + } + // It is definitely not an arrow function + return 0 /* False */; + } + else { + ts.Debug.assert(first === 28 /* LessThanToken */); + // If we have "<" not followed by an identifier, + // then this definitely is not an arrow function. + if (!isIdentifier()) { + return 0 /* False */; + } + // JSX overrides + if (sourceFile.languageVariant === 1 /* JSX */) { + var isArrowFunctionInJsx = lookAhead(function () { + var third = nextToken(); + if (third === 86 /* ExtendsKeyword */) { + var fourth = nextToken(); + switch (fourth) { + case 59 /* EqualsToken */: + case 30 /* GreaterThanToken */: + return false; + default: + return true; + } + } + else if (third === 27 /* CommaToken */) { + return true; + } + return false; + }); + if (isArrowFunctionInJsx) { + return 1 /* True */; + } + return 0 /* False */; + } + // This *could* be a parenthesized arrow function. + return 2 /* Unknown */; + } + } + function parsePossibleParenthesizedArrowFunctionExpressionHead() { + return parseParenthesizedArrowFunctionExpressionHead(/*allowAmbiguity*/ false); + } + function tryParseAsyncSimpleArrowFunctionExpression() { + // We do a check here so that we won't be doing unnecessarily call to "lookAhead" + if (token() === 121 /* AsyncKeyword */) { + if (lookAhead(isUnParenthesizedAsyncArrowFunctionWorker) === 1 /* True */) { + var asyncModifier = parseModifiersForArrowFunction(); + var expr = parseBinaryExpressionOrHigher(/*precedence*/ 0); + return parseSimpleArrowFunctionExpression(expr, asyncModifier); + } + } + return undefined; + } + function isUnParenthesizedAsyncArrowFunctionWorker() { + // AsyncArrowFunctionExpression: + // 1) async[no LineTerminator here]AsyncArrowBindingIdentifier[?Yield][no LineTerminator here]=>AsyncConciseBody[?In] + // 2) CoverCallExpressionAndAsyncArrowHead[?Yield, ?Await][no LineTerminator here]=>AsyncConciseBody[?In] + if (token() === 121 /* AsyncKeyword */) { + nextToken(); + // If the "async" is followed by "=>" token then it is not a beginning of an async arrow-function + // but instead a simple arrow-function which will be parsed inside "parseAssignmentExpressionOrHigher" + if (scanner.hasPrecedingLineBreak() || token() === 37 /* EqualsGreaterThanToken */) { + return 0 /* False */; + } + // Check for un-parenthesized AsyncArrowFunction + var expr = parseBinaryExpressionOrHigher(/*precedence*/ 0); + if (!scanner.hasPrecedingLineBreak() && expr.kind === 72 /* Identifier */ && token() === 37 /* EqualsGreaterThanToken */) { + return 1 /* True */; + } + } + return 0 /* False */; + } + function parseParenthesizedArrowFunctionExpressionHead(allowAmbiguity) { + var node = createNodeWithJSDoc(197 /* ArrowFunction */); + node.modifiers = parseModifiersForArrowFunction(); + var isAsync = ts.hasModifier(node, 256 /* Async */) ? 2 /* Await */ : 0 /* None */; + // Arrow functions are never generators. + // + // If we're speculatively parsing a signature for a parenthesized arrow function, then + // we have to have a complete parameter list. Otherwise we might see something like + // a => (b => c) + // And think that "(b =>" was actually a parenthesized arrow function with a missing + // close paren. + if (!fillSignature(57 /* ColonToken */, isAsync, node) && !allowAmbiguity) { + return undefined; + } + // Parsing a signature isn't enough. + // Parenthesized arrow signatures often look like other valid expressions. + // For instance: + // - "(x = 10)" is an assignment expression parsed as a signature with a default parameter value. + // - "(x,y)" is a comma expression parsed as a signature with two parameters. + // - "a ? (b): c" will have "(b):" parsed as a signature with a return type annotation. + // + // So we need just a bit of lookahead to ensure that it can only be a signature. + if (!allowAmbiguity && token() !== 37 /* EqualsGreaterThanToken */ && token() !== 18 /* OpenBraceToken */) { + // Returning undefined here will cause our caller to rewind to where we started from. + return undefined; + } + return node; + } + function parseArrowFunctionExpressionBody(isAsync) { + if (token() === 18 /* OpenBraceToken */) { + return parseFunctionBlock(isAsync ? 2 /* Await */ : 0 /* None */); + } + if (token() !== 26 /* SemicolonToken */ && + token() !== 90 /* FunctionKeyword */ && + token() !== 76 /* ClassKeyword */ && + isStartOfStatement() && + !isStartOfExpressionStatement()) { + // Check if we got a plain statement (i.e. no expression-statements, no function/class expressions/declarations) + // + // Here we try to recover from a potential error situation in the case where the + // user meant to supply a block. For example, if the user wrote: + // + // a => + // let v = 0; + // } + // + // they may be missing an open brace. Check to see if that's the case so we can + // try to recover better. If we don't do this, then the next close curly we see may end + // up preemptively closing the containing construct. + // + // Note: even when 'IgnoreMissingOpenBrace' is passed, parseBody will still error. + return parseFunctionBlock(16 /* IgnoreMissingOpenBrace */ | (isAsync ? 2 /* Await */ : 0 /* None */)); + } + return isAsync + ? doInAwaitContext(parseAssignmentExpressionOrHigher) + : doOutsideOfAwaitContext(parseAssignmentExpressionOrHigher); + } + function parseConditionalExpressionRest(leftOperand) { + // Note: we are passed in an expression which was produced from parseBinaryExpressionOrHigher. + var questionToken = parseOptionalToken(56 /* QuestionToken */); + if (!questionToken) { + return leftOperand; + } + // Note: we explicitly 'allowIn' in the whenTrue part of the condition expression, and + // we do not that for the 'whenFalse' part. + var node = createNode(205 /* ConditionalExpression */, leftOperand.pos); + node.condition = leftOperand; + node.questionToken = questionToken; + node.whenTrue = doOutsideOfContext(disallowInAndDecoratorContext, parseAssignmentExpressionOrHigher); + node.colonToken = parseExpectedToken(57 /* ColonToken */); + node.whenFalse = ts.nodeIsPresent(node.colonToken) + ? parseAssignmentExpressionOrHigher() + : createMissingNode(72 /* Identifier */, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, ts.tokenToString(57 /* ColonToken */)); + return finishNode(node); + } + function parseBinaryExpressionOrHigher(precedence) { + var leftOperand = parseUnaryExpressionOrHigher(); + return parseBinaryExpressionRest(precedence, leftOperand); + } + function isInOrOfKeyword(t) { + return t === 93 /* InKeyword */ || t === 147 /* OfKeyword */; + } + function parseBinaryExpressionRest(precedence, leftOperand) { + while (true) { + // We either have a binary operator here, or we're finished. We call + // reScanGreaterToken so that we merge token sequences like > and = into >= + reScanGreaterToken(); + var newPrecedence = ts.getBinaryOperatorPrecedence(token()); + // Check the precedence to see if we should "take" this operator + // - For left associative operator (all operator but **), consume the operator, + // recursively call the function below, and parse binaryExpression as a rightOperand + // of the caller if the new precedence of the operator is greater then or equal to the current precedence. + // For example: + // a - b - c; + // ^token; leftOperand = b. Return b to the caller as a rightOperand + // a * b - c + // ^token; leftOperand = b. Return b to the caller as a rightOperand + // a - b * c; + // ^token; leftOperand = b. Return b * c to the caller as a rightOperand + // - For right associative operator (**), consume the operator, recursively call the function + // and parse binaryExpression as a rightOperand of the caller if the new precedence of + // the operator is strictly grater than the current precedence + // For example: + // a ** b ** c; + // ^^token; leftOperand = b. Return b ** c to the caller as a rightOperand + // a - b ** c; + // ^^token; leftOperand = b. Return b ** c to the caller as a rightOperand + // a ** b - c + // ^token; leftOperand = b. Return b to the caller as a rightOperand + var consumeCurrentOperator = token() === 41 /* AsteriskAsteriskToken */ ? + newPrecedence >= precedence : + newPrecedence > precedence; + if (!consumeCurrentOperator) { + break; + } + if (token() === 93 /* InKeyword */ && inDisallowInContext()) { + break; + } + if (token() === 119 /* AsKeyword */) { + // Make sure we *do* perform ASI for constructs like this: + // var x = foo + // as (Bar) + // This should be parsed as an initialized variable, followed + // by a function call to 'as' with the argument 'Bar' + if (scanner.hasPrecedingLineBreak()) { + break; + } + else { + nextToken(); + leftOperand = makeAsExpression(leftOperand, parseType()); + } + } + else { + leftOperand = makeBinaryExpression(leftOperand, parseTokenNode(), parseBinaryExpressionOrHigher(newPrecedence)); + } + } + return leftOperand; + } + function isBinaryOperator() { + if (inDisallowInContext() && token() === 93 /* InKeyword */) { + return false; + } + return ts.getBinaryOperatorPrecedence(token()) > 0; + } + function makeBinaryExpression(left, operatorToken, right) { + var node = createNode(204 /* BinaryExpression */, left.pos); + node.left = left; + node.operatorToken = operatorToken; + node.right = right; + return finishNode(node); + } + function makeAsExpression(left, right) { + var node = createNode(212 /* AsExpression */, left.pos); + node.expression = left; + node.type = right; + return finishNode(node); + } + function parsePrefixUnaryExpression() { + var node = createNode(202 /* PrefixUnaryExpression */); + node.operator = token(); + nextToken(); + node.operand = parseSimpleUnaryExpression(); + return finishNode(node); + } + function parseDeleteExpression() { + var node = createNode(198 /* DeleteExpression */); + nextToken(); + node.expression = parseSimpleUnaryExpression(); + return finishNode(node); + } + function parseTypeOfExpression() { + var node = createNode(199 /* TypeOfExpression */); + nextToken(); + node.expression = parseSimpleUnaryExpression(); + return finishNode(node); + } + function parseVoidExpression() { + var node = createNode(200 /* VoidExpression */); + nextToken(); + node.expression = parseSimpleUnaryExpression(); + return finishNode(node); + } + function isAwaitExpression() { + if (token() === 122 /* AwaitKeyword */) { + if (inAwaitContext()) { + return true; + } + // here we are using similar heuristics as 'isYieldExpression' + return lookAhead(nextTokenIsIdentifierOrKeywordOrLiteralOnSameLine); + } + return false; + } + function parseAwaitExpression() { + var node = createNode(201 /* AwaitExpression */); + nextToken(); + node.expression = parseSimpleUnaryExpression(); + return finishNode(node); + } + /** + * Parse ES7 exponential expression and await expression + * + * ES7 ExponentiationExpression: + * 1) UnaryExpression[?Yield] + * 2) UpdateExpression[?Yield] ** ExponentiationExpression[?Yield] + * + */ + function parseUnaryExpressionOrHigher() { + /** + * ES7 UpdateExpression: + * 1) LeftHandSideExpression[?Yield] + * 2) LeftHandSideExpression[?Yield][no LineTerminator here]++ + * 3) LeftHandSideExpression[?Yield][no LineTerminator here]-- + * 4) ++UnaryExpression[?Yield] + * 5) --UnaryExpression[?Yield] + */ + if (isUpdateExpression()) { + var updateExpression = parseUpdateExpression(); + return token() === 41 /* AsteriskAsteriskToken */ ? + parseBinaryExpressionRest(ts.getBinaryOperatorPrecedence(token()), updateExpression) : + updateExpression; + } + /** + * ES7 UnaryExpression: + * 1) UpdateExpression[?yield] + * 2) delete UpdateExpression[?yield] + * 3) void UpdateExpression[?yield] + * 4) typeof UpdateExpression[?yield] + * 5) + UpdateExpression[?yield] + * 6) - UpdateExpression[?yield] + * 7) ~ UpdateExpression[?yield] + * 8) ! UpdateExpression[?yield] + */ + var unaryOperator = token(); + var simpleUnaryExpression = parseSimpleUnaryExpression(); + if (token() === 41 /* AsteriskAsteriskToken */) { + var pos = ts.skipTrivia(sourceText, simpleUnaryExpression.pos); + var end = simpleUnaryExpression.end; + if (simpleUnaryExpression.kind === 194 /* TypeAssertionExpression */) { + parseErrorAt(pos, end, ts.Diagnostics.A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses); + } + else { + parseErrorAt(pos, end, ts.Diagnostics.An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses, ts.tokenToString(unaryOperator)); + } + } + return simpleUnaryExpression; + } + /** + * Parse ES7 simple-unary expression or higher: + * + * ES7 UnaryExpression: + * 1) UpdateExpression[?yield] + * 2) delete UnaryExpression[?yield] + * 3) void UnaryExpression[?yield] + * 4) typeof UnaryExpression[?yield] + * 5) + UnaryExpression[?yield] + * 6) - UnaryExpression[?yield] + * 7) ~ UnaryExpression[?yield] + * 8) ! UnaryExpression[?yield] + * 9) [+Await] await UnaryExpression[?yield] + */ + function parseSimpleUnaryExpression() { + switch (token()) { + case 38 /* PlusToken */: + case 39 /* MinusToken */: + case 53 /* TildeToken */: + case 52 /* ExclamationToken */: + return parsePrefixUnaryExpression(); + case 81 /* DeleteKeyword */: + return parseDeleteExpression(); + case 104 /* TypeOfKeyword */: + return parseTypeOfExpression(); + case 106 /* VoidKeyword */: + return parseVoidExpression(); + case 28 /* LessThanToken */: + // This is modified UnaryExpression grammar in TypeScript + // UnaryExpression (modified): + // < type > UnaryExpression + return parseTypeAssertion(); + case 122 /* AwaitKeyword */: + if (isAwaitExpression()) { + return parseAwaitExpression(); + } + // falls through + default: + return parseUpdateExpression(); + } + } + /** + * Check if the current token can possibly be an ES7 increment expression. + * + * ES7 UpdateExpression: + * LeftHandSideExpression[?Yield] + * LeftHandSideExpression[?Yield][no LineTerminator here]++ + * LeftHandSideExpression[?Yield][no LineTerminator here]-- + * ++LeftHandSideExpression[?Yield] + * --LeftHandSideExpression[?Yield] + */ + function isUpdateExpression() { + // This function is called inside parseUnaryExpression to decide + // whether to call parseSimpleUnaryExpression or call parseUpdateExpression directly + switch (token()) { + case 38 /* PlusToken */: + case 39 /* MinusToken */: + case 53 /* TildeToken */: + case 52 /* ExclamationToken */: + case 81 /* DeleteKeyword */: + case 104 /* TypeOfKeyword */: + case 106 /* VoidKeyword */: + case 122 /* AwaitKeyword */: + return false; + case 28 /* LessThanToken */: + // If we are not in JSX context, we are parsing TypeAssertion which is an UnaryExpression + if (sourceFile.languageVariant !== 1 /* JSX */) { + return false; + } + // We are in JSX context and the token is part of JSXElement. + // falls through + default: + return true; + } + } + /** + * Parse ES7 UpdateExpression. UpdateExpression is used instead of ES6's PostFixExpression. + * + * ES7 UpdateExpression[yield]: + * 1) LeftHandSideExpression[?yield] + * 2) LeftHandSideExpression[?yield] [[no LineTerminator here]]++ + * 3) LeftHandSideExpression[?yield] [[no LineTerminator here]]-- + * 4) ++LeftHandSideExpression[?yield] + * 5) --LeftHandSideExpression[?yield] + * In TypeScript (2), (3) are parsed as PostfixUnaryExpression. (4), (5) are parsed as PrefixUnaryExpression + */ + function parseUpdateExpression() { + if (token() === 44 /* PlusPlusToken */ || token() === 45 /* MinusMinusToken */) { + var node = createNode(202 /* PrefixUnaryExpression */); + node.operator = token(); + nextToken(); + node.operand = parseLeftHandSideExpressionOrHigher(); + return finishNode(node); + } + else if (sourceFile.languageVariant === 1 /* JSX */ && token() === 28 /* LessThanToken */ && lookAhead(nextTokenIsIdentifierOrKeywordOrGreaterThan)) { + // JSXElement is part of primaryExpression + return parseJsxElementOrSelfClosingElementOrFragment(/*inExpressionContext*/ true); + } + var expression = parseLeftHandSideExpressionOrHigher(); + ts.Debug.assert(ts.isLeftHandSideExpression(expression)); + if ((token() === 44 /* PlusPlusToken */ || token() === 45 /* MinusMinusToken */) && !scanner.hasPrecedingLineBreak()) { + var node = createNode(203 /* PostfixUnaryExpression */, expression.pos); + node.operand = expression; + node.operator = token(); + nextToken(); + return finishNode(node); + } + return expression; + } + function parseLeftHandSideExpressionOrHigher() { + // Original Ecma: + // LeftHandSideExpression: See 11.2 + // NewExpression + // CallExpression + // + // Our simplification: + // + // LeftHandSideExpression: See 11.2 + // MemberExpression + // CallExpression + // + // See comment in parseMemberExpressionOrHigher on how we replaced NewExpression with + // MemberExpression to make our lives easier. + // + // to best understand the below code, it's important to see how CallExpression expands + // out into its own productions: + // + // CallExpression: + // MemberExpression Arguments + // CallExpression Arguments + // CallExpression[Expression] + // CallExpression.IdentifierName + // import (AssignmentExpression) + // super Arguments + // super.IdentifierName + // + // Because of the recursion in these calls, we need to bottom out first. There are three + // bottom out states we can run into: 1) We see 'super' which must start either of + // the last two CallExpression productions. 2) We see 'import' which must start import call. + // 3)we have a MemberExpression which either completes the LeftHandSideExpression, + // or starts the beginning of the first four CallExpression productions. + var expression; + if (token() === 92 /* ImportKeyword */) { + if (lookAhead(nextTokenIsOpenParenOrLessThan)) { + // We don't want to eagerly consume all import keyword as import call expression so we look ahead to find "(" + // For example: + // var foo3 = require("subfolder + // import * as foo1 from "module-from-node + // We want this import to be a statement rather than import call expression + sourceFile.flags |= 524288 /* PossiblyContainsDynamicImport */; + expression = parseTokenNode(); + } + else if (lookAhead(nextTokenIsDot)) { + // This is an 'import.*' metaproperty (i.e. 'import.meta') + var fullStart = scanner.getStartPos(); + nextToken(); // advance past the 'import' + nextToken(); // advance past the dot + var node = createNode(214 /* MetaProperty */, fullStart); + node.keywordToken = 92 /* ImportKeyword */; + node.name = parseIdentifierName(); + expression = finishNode(node); + sourceFile.flags |= 1048576 /* PossiblyContainsImportMeta */; + } + else { + expression = parseMemberExpressionOrHigher(); + } + } + else { + expression = token() === 98 /* SuperKeyword */ ? parseSuperExpression() : parseMemberExpressionOrHigher(); + } + // Now, we *may* be complete. However, we might have consumed the start of a + // CallExpression. As such, we need to consume the rest of it here to be complete. + return parseCallExpressionRest(expression); + } + function parseMemberExpressionOrHigher() { + // Note: to make our lives simpler, we decompose the NewExpression productions and + // place ObjectCreationExpression and FunctionExpression into PrimaryExpression. + // like so: + // + // PrimaryExpression : See 11.1 + // this + // Identifier + // Literal + // ArrayLiteral + // ObjectLiteral + // (Expression) + // FunctionExpression + // new MemberExpression Arguments? + // + // MemberExpression : See 11.2 + // PrimaryExpression + // MemberExpression[Expression] + // MemberExpression.IdentifierName + // + // CallExpression : See 11.2 + // MemberExpression + // CallExpression Arguments + // CallExpression[Expression] + // CallExpression.IdentifierName + // + // Technically this is ambiguous. i.e. CallExpression defines: + // + // CallExpression: + // CallExpression Arguments + // + // If you see: "new Foo()" + // + // Then that could be treated as a single ObjectCreationExpression, or it could be + // treated as the invocation of "new Foo". We disambiguate that in code (to match + // the original grammar) by making sure that if we see an ObjectCreationExpression + // we always consume arguments if they are there. So we treat "new Foo()" as an + // object creation only, and not at all as an invocation. Another way to think + // about this is that for every "new" that we see, we will consume an argument list if + // it is there as part of the *associated* object creation node. Any additional + // argument lists we see, will become invocation expressions. + // + // Because there are no other places in the grammar now that refer to FunctionExpression + // or ObjectCreationExpression, it is safe to push down into the PrimaryExpression + // production. + // + // Because CallExpression and MemberExpression are left recursive, we need to bottom out + // of the recursion immediately. So we parse out a primary expression to start with. + var expression = parsePrimaryExpression(); + return parseMemberExpressionRest(expression); + } + function parseSuperExpression() { + var expression = parseTokenNode(); + if (token() === 20 /* OpenParenToken */ || token() === 24 /* DotToken */ || token() === 22 /* OpenBracketToken */) { + return expression; + } + // If we have seen "super" it must be followed by '(' or '.'. + // If it wasn't then just try to parse out a '.' and report an error. + var node = createNode(189 /* PropertyAccessExpression */, expression.pos); + node.expression = expression; + parseExpectedToken(24 /* DotToken */, ts.Diagnostics.super_must_be_followed_by_an_argument_list_or_member_access); + node.name = parseRightSideOfDot(/*allowIdentifierNames*/ true); + return finishNode(node); + } + function parseJsxElementOrSelfClosingElementOrFragment(inExpressionContext) { + var opening = parseJsxOpeningOrSelfClosingElementOrOpeningFragment(inExpressionContext); + var result; + if (opening.kind === 262 /* JsxOpeningElement */) { + var node = createNode(260 /* JsxElement */, opening.pos); + node.openingElement = opening; + node.children = parseJsxChildren(node.openingElement); + node.closingElement = parseJsxClosingElement(inExpressionContext); + if (!tagNamesAreEquivalent(node.openingElement.tagName, node.closingElement.tagName)) { + parseErrorAtRange(node.closingElement, ts.Diagnostics.Expected_corresponding_JSX_closing_tag_for_0, ts.getTextOfNodeFromSourceText(sourceText, node.openingElement.tagName)); + } + result = finishNode(node); + } + else if (opening.kind === 265 /* JsxOpeningFragment */) { + var node = createNode(264 /* JsxFragment */, opening.pos); + node.openingFragment = opening; + node.children = parseJsxChildren(node.openingFragment); + node.closingFragment = parseJsxClosingFragment(inExpressionContext); + result = finishNode(node); + } + else { + ts.Debug.assert(opening.kind === 261 /* JsxSelfClosingElement */); + // Nothing else to do for self-closing elements + result = opening; + } + // If the user writes the invalid code '
      ' in an expression context (i.e. not wrapped in + // an enclosing tag), we'll naively try to parse ^ this as a 'less than' operator and the remainder of the tag + // as garbage, which will cause the formatter to badly mangle the JSX. Perform a speculative parse of a JSX + // element if we see a < token so that we can wrap it in a synthetic binary expression so the formatter + // does less damage and we can report a better error. + // Since JSX elements are invalid < operands anyway, this lookahead parse will only occur in error scenarios + // of one sort or another. + if (inExpressionContext && token() === 28 /* LessThanToken */) { + var invalidElement = tryParse(function () { return parseJsxElementOrSelfClosingElementOrFragment(/*inExpressionContext*/ true); }); + if (invalidElement) { + parseErrorAtCurrentToken(ts.Diagnostics.JSX_expressions_must_have_one_parent_element); + var badNode = createNode(204 /* BinaryExpression */, result.pos); + badNode.end = invalidElement.end; + badNode.left = result; + badNode.right = invalidElement; + badNode.operatorToken = createMissingNode(27 /* CommaToken */, /*reportAtCurrentPosition*/ false, /*diagnosticMessage*/ undefined); // TODO: GH#18217 + badNode.operatorToken.pos = badNode.operatorToken.end = badNode.right.pos; + return badNode; + } + } + return result; + } + function parseJsxText() { + var node = createNode(11 /* JsxText */); + node.containsOnlyWhiteSpaces = currentToken === 12 /* JsxTextAllWhiteSpaces */; + currentToken = scanner.scanJsxToken(); + return finishNode(node); + } + function parseJsxChild(openingTag, token) { + switch (token) { + case 1 /* EndOfFileToken */: + // If we hit EOF, issue the error at the tag that lacks the closing element + // rather than at the end of the file (which is useless) + if (ts.isJsxOpeningFragment(openingTag)) { + parseErrorAtRange(openingTag, ts.Diagnostics.JSX_fragment_has_no_corresponding_closing_tag); + } + else { + parseErrorAtRange(openingTag.tagName, ts.Diagnostics.JSX_element_0_has_no_corresponding_closing_tag, ts.getTextOfNodeFromSourceText(sourceText, openingTag.tagName)); + } + return undefined; + case 29 /* LessThanSlashToken */: + case 7 /* ConflictMarkerTrivia */: + return undefined; + case 11 /* JsxText */: + case 12 /* JsxTextAllWhiteSpaces */: + return parseJsxText(); + case 18 /* OpenBraceToken */: + return parseJsxExpression(/*inExpressionContext*/ false); + case 28 /* LessThanToken */: + return parseJsxElementOrSelfClosingElementOrFragment(/*inExpressionContext*/ false); + default: + return ts.Debug.assertNever(token); + } + } + function parseJsxChildren(openingTag) { + var list = []; + var listPos = getNodePos(); + var saveParsingContext = parsingContext; + parsingContext |= 1 << 14 /* JsxChildren */; + while (true) { + var child = parseJsxChild(openingTag, currentToken = scanner.reScanJsxToken()); + if (!child) + break; + list.push(child); + } + parsingContext = saveParsingContext; + return createNodeArray(list, listPos); + } + function parseJsxAttributes() { + var jsxAttributes = createNode(268 /* JsxAttributes */); + jsxAttributes.properties = parseList(13 /* JsxAttributes */, parseJsxAttribute); + return finishNode(jsxAttributes); + } + function parseJsxOpeningOrSelfClosingElementOrOpeningFragment(inExpressionContext) { + var fullStart = scanner.getStartPos(); + parseExpected(28 /* LessThanToken */); + if (token() === 30 /* GreaterThanToken */) { + // See below for explanation of scanJsxText + var node_1 = createNode(265 /* JsxOpeningFragment */, fullStart); + scanJsxText(); + return finishNode(node_1); + } + var tagName = parseJsxElementName(); + var typeArguments = tryParseTypeArguments(); + var attributes = parseJsxAttributes(); + var node; + if (token() === 30 /* GreaterThanToken */) { + // Closing tag, so scan the immediately-following text with the JSX scanning instead + // of regular scanning to avoid treating illegal characters (e.g. '#') as immediate + // scanning errors + node = createNode(262 /* JsxOpeningElement */, fullStart); + scanJsxText(); + } + else { + parseExpected(42 /* SlashToken */); + if (inExpressionContext) { + parseExpected(30 /* GreaterThanToken */); + } + else { + parseExpected(30 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false); + scanJsxText(); + } + node = createNode(261 /* JsxSelfClosingElement */, fullStart); + } + node.tagName = tagName; + node.typeArguments = typeArguments; + node.attributes = attributes; + return finishNode(node); + } + function parseJsxElementName() { + scanJsxIdentifier(); + // JsxElement can have name in the form of + // propertyAccessExpression + // primaryExpression in the form of an identifier and "this" keyword + // We can't just simply use parseLeftHandSideExpressionOrHigher because then we will start consider class,function etc as a keyword + // We only want to consider "this" as a primaryExpression + var expression = token() === 100 /* ThisKeyword */ ? + parseTokenNode() : parseIdentifierName(); + while (parseOptional(24 /* DotToken */)) { + var propertyAccess = createNode(189 /* PropertyAccessExpression */, expression.pos); + propertyAccess.expression = expression; + propertyAccess.name = parseRightSideOfDot(/*allowIdentifierNames*/ true); + expression = finishNode(propertyAccess); + } + return expression; + } + function parseJsxExpression(inExpressionContext) { + var node = createNode(270 /* JsxExpression */); + if (!parseExpected(18 /* OpenBraceToken */)) { + return undefined; + } + if (token() !== 19 /* CloseBraceToken */) { + node.dotDotDotToken = parseOptionalToken(25 /* DotDotDotToken */); + node.expression = parseAssignmentExpressionOrHigher(); + } + if (inExpressionContext) { + parseExpected(19 /* CloseBraceToken */); + } + else { + parseExpected(19 /* CloseBraceToken */, /*message*/ undefined, /*shouldAdvance*/ false); + scanJsxText(); + } + return finishNode(node); + } + function parseJsxAttribute() { + if (token() === 18 /* OpenBraceToken */) { + return parseJsxSpreadAttribute(); + } + scanJsxIdentifier(); + var node = createNode(267 /* JsxAttribute */); + node.name = parseIdentifierName(); + if (token() === 59 /* EqualsToken */) { + switch (scanJsxAttributeValue()) { + case 10 /* StringLiteral */: + node.initializer = parseLiteralNode(); + break; + default: + node.initializer = parseJsxExpression(/*inExpressionContext*/ true); + break; + } + } + return finishNode(node); + } + function parseJsxSpreadAttribute() { + var node = createNode(269 /* JsxSpreadAttribute */); + parseExpected(18 /* OpenBraceToken */); + parseExpected(25 /* DotDotDotToken */); + node.expression = parseExpression(); + parseExpected(19 /* CloseBraceToken */); + return finishNode(node); + } + function parseJsxClosingElement(inExpressionContext) { + var node = createNode(263 /* JsxClosingElement */); + parseExpected(29 /* LessThanSlashToken */); + node.tagName = parseJsxElementName(); + if (inExpressionContext) { + parseExpected(30 /* GreaterThanToken */); + } + else { + parseExpected(30 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false); + scanJsxText(); + } + return finishNode(node); + } + function parseJsxClosingFragment(inExpressionContext) { + var node = createNode(266 /* JsxClosingFragment */); + parseExpected(29 /* LessThanSlashToken */); + if (ts.tokenIsIdentifierOrKeyword(token())) { + parseErrorAtRange(parseJsxElementName(), ts.Diagnostics.Expected_corresponding_closing_tag_for_JSX_fragment); + } + if (inExpressionContext) { + parseExpected(30 /* GreaterThanToken */); + } + else { + parseExpected(30 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false); + scanJsxText(); + } + return finishNode(node); + } + function parseTypeAssertion() { + var node = createNode(194 /* TypeAssertionExpression */); + parseExpected(28 /* LessThanToken */); + node.type = parseType(); + parseExpected(30 /* GreaterThanToken */); + node.expression = parseSimpleUnaryExpression(); + return finishNode(node); + } + function parseMemberExpressionRest(expression) { + while (true) { + var dotToken = parseOptionalToken(24 /* DotToken */); + if (dotToken) { + var propertyAccess = createNode(189 /* PropertyAccessExpression */, expression.pos); + propertyAccess.expression = expression; + propertyAccess.name = parseRightSideOfDot(/*allowIdentifierNames*/ true); + expression = finishNode(propertyAccess); + continue; + } + if (token() === 52 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) { + nextToken(); + var nonNullExpression = createNode(213 /* NonNullExpression */, expression.pos); + nonNullExpression.expression = expression; + expression = finishNode(nonNullExpression); + continue; + } + // when in the [Decorator] context, we do not parse ElementAccess as it could be part of a ComputedPropertyName + if (!inDecoratorContext() && parseOptional(22 /* OpenBracketToken */)) { + var indexedAccess = createNode(190 /* ElementAccessExpression */, expression.pos); + indexedAccess.expression = expression; + if (token() === 23 /* CloseBracketToken */) { + indexedAccess.argumentExpression = createMissingNode(72 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.An_element_access_expression_should_take_an_argument); + } + else { + var argument = allowInAnd(parseExpression); + if (ts.isStringOrNumericLiteralLike(argument)) { + argument.text = internIdentifier(argument.text); + } + indexedAccess.argumentExpression = argument; + } + parseExpected(23 /* CloseBracketToken */); + expression = finishNode(indexedAccess); + continue; + } + if (isTemplateStartOfTaggedTemplate()) { + expression = parseTaggedTemplateRest(expression, /*typeArguments*/ undefined); + continue; + } + return expression; + } + } + function isTemplateStartOfTaggedTemplate() { + return token() === 14 /* NoSubstitutionTemplateLiteral */ || token() === 15 /* TemplateHead */; + } + function parseTaggedTemplateRest(tag, typeArguments) { + var tagExpression = createNode(193 /* TaggedTemplateExpression */, tag.pos); + tagExpression.tag = tag; + tagExpression.typeArguments = typeArguments; + tagExpression.template = token() === 14 /* NoSubstitutionTemplateLiteral */ + ? parseLiteralNode() + : parseTemplateExpression(); + return finishNode(tagExpression); + } + function parseCallExpressionRest(expression) { + while (true) { + expression = parseMemberExpressionRest(expression); + if (token() === 28 /* LessThanToken */) { + // See if this is the start of a generic invocation. If so, consume it and + // keep checking for postfix expressions. Otherwise, it's just a '<' that's + // part of an arithmetic expression. Break out so we consume it higher in the + // stack. + var typeArguments = tryParse(parseTypeArgumentsInExpression); + if (!typeArguments) { + return expression; + } + if (isTemplateStartOfTaggedTemplate()) { + expression = parseTaggedTemplateRest(expression, typeArguments); + continue; + } + var callExpr = createNode(191 /* CallExpression */, expression.pos); + callExpr.expression = expression; + callExpr.typeArguments = typeArguments; + callExpr.arguments = parseArgumentList(); + expression = finishNode(callExpr); + continue; + } + else if (token() === 20 /* OpenParenToken */) { + var callExpr = createNode(191 /* CallExpression */, expression.pos); + callExpr.expression = expression; + callExpr.arguments = parseArgumentList(); + expression = finishNode(callExpr); + continue; + } + return expression; + } + } + function parseArgumentList() { + parseExpected(20 /* OpenParenToken */); + var result = parseDelimitedList(11 /* ArgumentExpressions */, parseArgumentExpression); + parseExpected(21 /* CloseParenToken */); + return result; + } + function parseTypeArgumentsInExpression() { + if (!parseOptional(28 /* LessThanToken */)) { + return undefined; + } + var typeArguments = parseDelimitedList(20 /* TypeArguments */, parseType); + if (!parseExpected(30 /* GreaterThanToken */)) { + // If it doesn't have the closing `>` then it's definitely not an type argument list. + return undefined; + } + // If we have a '<', then only parse this as a argument list if the type arguments + // are complete and we have an open paren. if we don't, rewind and return nothing. + return typeArguments && canFollowTypeArgumentsInExpression() + ? typeArguments + : undefined; + } + function canFollowTypeArgumentsInExpression() { + switch (token()) { + case 20 /* OpenParenToken */: // foo( + case 14 /* NoSubstitutionTemplateLiteral */: // foo `...` + case 15 /* TemplateHead */: // foo `...${100}...` + // these are the only tokens can legally follow a type argument + // list. So we definitely want to treat them as type arg lists. + case 24 /* DotToken */: // foo. + case 21 /* CloseParenToken */: // foo) + case 23 /* CloseBracketToken */: // foo] + case 57 /* ColonToken */: // foo: + case 26 /* SemicolonToken */: // foo; + case 56 /* QuestionToken */: // foo? + case 33 /* EqualsEqualsToken */: // foo == + case 35 /* EqualsEqualsEqualsToken */: // foo === + case 34 /* ExclamationEqualsToken */: // foo != + case 36 /* ExclamationEqualsEqualsToken */: // foo !== + case 54 /* AmpersandAmpersandToken */: // foo && + case 55 /* BarBarToken */: // foo || + case 51 /* CaretToken */: // foo ^ + case 49 /* AmpersandToken */: // foo & + case 50 /* BarToken */: // foo | + case 19 /* CloseBraceToken */: // foo } + case 1 /* EndOfFileToken */: // foo + // these cases can't legally follow a type arg list. However, they're not legal + // expressions either. The user is probably in the middle of a generic type. So + // treat it as such. + return true; + case 27 /* CommaToken */: // foo, + case 18 /* OpenBraceToken */: // foo { + // We don't want to treat these as type arguments. Otherwise we'll parse this + // as an invocation expression. Instead, we want to parse out the expression + // in isolation from the type arguments. + default: + // Anything else treat as an expression. + return false; + } + } + function parsePrimaryExpression() { + switch (token()) { + case 8 /* NumericLiteral */: + case 9 /* BigIntLiteral */: + case 10 /* StringLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: + return parseLiteralNode(); + case 100 /* ThisKeyword */: + case 98 /* SuperKeyword */: + case 96 /* NullKeyword */: + case 102 /* TrueKeyword */: + case 87 /* FalseKeyword */: + return parseTokenNode(); + case 20 /* OpenParenToken */: + return parseParenthesizedExpression(); + case 22 /* OpenBracketToken */: + return parseArrayLiteralExpression(); + case 18 /* OpenBraceToken */: + return parseObjectLiteralExpression(); + case 121 /* AsyncKeyword */: + // Async arrow functions are parsed earlier in parseAssignmentExpressionOrHigher. + // If we encounter `async [no LineTerminator here] function` then this is an async + // function; otherwise, its an identifier. + if (!lookAhead(nextTokenIsFunctionKeywordOnSameLine)) { + break; + } + return parseFunctionExpression(); + case 76 /* ClassKeyword */: + return parseClassExpression(); + case 90 /* FunctionKeyword */: + return parseFunctionExpression(); + case 95 /* NewKeyword */: + return parseNewExpressionOrNewDotTarget(); + case 42 /* SlashToken */: + case 64 /* SlashEqualsToken */: + if (reScanSlashToken() === 13 /* RegularExpressionLiteral */) { + return parseLiteralNode(); + } + break; + case 15 /* TemplateHead */: + return parseTemplateExpression(); + } + return parseIdentifier(ts.Diagnostics.Expression_expected); + } + function parseParenthesizedExpression() { + var node = createNodeWithJSDoc(195 /* ParenthesizedExpression */); + parseExpected(20 /* OpenParenToken */); + node.expression = allowInAnd(parseExpression); + parseExpected(21 /* CloseParenToken */); + return finishNode(node); + } + function parseSpreadElement() { + var node = createNode(208 /* SpreadElement */); + parseExpected(25 /* DotDotDotToken */); + node.expression = parseAssignmentExpressionOrHigher(); + return finishNode(node); + } + function parseArgumentOrArrayLiteralElement() { + return token() === 25 /* DotDotDotToken */ ? parseSpreadElement() : + token() === 27 /* CommaToken */ ? createNode(210 /* OmittedExpression */) : + parseAssignmentExpressionOrHigher(); + } + function parseArgumentExpression() { + return doOutsideOfContext(disallowInAndDecoratorContext, parseArgumentOrArrayLiteralElement); + } + function parseArrayLiteralExpression() { + var node = createNode(187 /* ArrayLiteralExpression */); + parseExpected(22 /* OpenBracketToken */); + if (scanner.hasPrecedingLineBreak()) { + node.multiLine = true; + } + node.elements = parseDelimitedList(15 /* ArrayLiteralMembers */, parseArgumentOrArrayLiteralElement); + parseExpected(23 /* CloseBracketToken */); + return finishNode(node); + } + function parseObjectLiteralElement() { + var node = createNodeWithJSDoc(0 /* Unknown */); + if (parseOptionalToken(25 /* DotDotDotToken */)) { + node.kind = 277 /* SpreadAssignment */; + node.expression = parseAssignmentExpressionOrHigher(); + return finishNode(node); + } + node.decorators = parseDecorators(); + node.modifiers = parseModifiers(); + if (parseContextualModifier(126 /* GetKeyword */)) { + return parseAccessorDeclaration(node, 158 /* GetAccessor */); + } + if (parseContextualModifier(137 /* SetKeyword */)) { + return parseAccessorDeclaration(node, 159 /* SetAccessor */); + } + var asteriskToken = parseOptionalToken(40 /* AsteriskToken */); + var tokenIsIdentifier = isIdentifier(); + node.name = parsePropertyName(); + // Disallowing of optional property assignments and definite assignment assertion happens in the grammar checker. + node.questionToken = parseOptionalToken(56 /* QuestionToken */); + node.exclamationToken = parseOptionalToken(52 /* ExclamationToken */); + if (asteriskToken || token() === 20 /* OpenParenToken */ || token() === 28 /* LessThanToken */) { + return parseMethodDeclaration(node, asteriskToken); + } + // check if it is short-hand property assignment or normal property assignment + // NOTE: if token is EqualsToken it is interpreted as CoverInitializedName production + // CoverInitializedName[Yield] : + // IdentifierReference[?Yield] Initializer[In, ?Yield] + // this is necessary because ObjectLiteral productions are also used to cover grammar for ObjectAssignmentPattern + var isShorthandPropertyAssignment = tokenIsIdentifier && (token() !== 57 /* ColonToken */); + if (isShorthandPropertyAssignment) { + node.kind = 276 /* ShorthandPropertyAssignment */; + var equalsToken = parseOptionalToken(59 /* EqualsToken */); + if (equalsToken) { + node.equalsToken = equalsToken; + node.objectAssignmentInitializer = allowInAnd(parseAssignmentExpressionOrHigher); + } + } + else { + node.kind = 275 /* PropertyAssignment */; + parseExpected(57 /* ColonToken */); + node.initializer = allowInAnd(parseAssignmentExpressionOrHigher); + } + return finishNode(node); + } + function parseObjectLiteralExpression() { + var node = createNode(188 /* ObjectLiteralExpression */); + parseExpected(18 /* OpenBraceToken */); + if (scanner.hasPrecedingLineBreak()) { + node.multiLine = true; + } + node.properties = parseDelimitedList(12 /* ObjectLiteralMembers */, parseObjectLiteralElement, /*considerSemicolonAsDelimiter*/ true); + parseExpected(19 /* CloseBraceToken */); + return finishNode(node); + } + function parseFunctionExpression() { + // GeneratorExpression: + // function* BindingIdentifier [Yield][opt](FormalParameters[Yield]){ GeneratorBody } + // + // FunctionExpression: + // function BindingIdentifier[opt](FormalParameters){ FunctionBody } + var saveDecoratorContext = inDecoratorContext(); + if (saveDecoratorContext) { + setDecoratorContext(/*val*/ false); + } + var node = createNodeWithJSDoc(196 /* FunctionExpression */); + node.modifiers = parseModifiers(); + parseExpected(90 /* FunctionKeyword */); + node.asteriskToken = parseOptionalToken(40 /* AsteriskToken */); + var isGenerator = node.asteriskToken ? 1 /* Yield */ : 0 /* None */; + var isAsync = ts.hasModifier(node, 256 /* Async */) ? 2 /* Await */ : 0 /* None */; + node.name = + isGenerator && isAsync ? doInYieldAndAwaitContext(parseOptionalIdentifier) : + isGenerator ? doInYieldContext(parseOptionalIdentifier) : + isAsync ? doInAwaitContext(parseOptionalIdentifier) : + parseOptionalIdentifier(); + fillSignature(57 /* ColonToken */, isGenerator | isAsync, node); + node.body = parseFunctionBlock(isGenerator | isAsync); + if (saveDecoratorContext) { + setDecoratorContext(/*val*/ true); + } + return finishNode(node); + } + function parseOptionalIdentifier() { + return isIdentifier() ? parseIdentifier() : undefined; + } + function parseNewExpressionOrNewDotTarget() { + var fullStart = scanner.getStartPos(); + parseExpected(95 /* NewKeyword */); + if (parseOptional(24 /* DotToken */)) { + var node_2 = createNode(214 /* MetaProperty */, fullStart); + node_2.keywordToken = 95 /* NewKeyword */; + node_2.name = parseIdentifierName(); + return finishNode(node_2); + } + var expression = parsePrimaryExpression(); + var typeArguments; + while (true) { + expression = parseMemberExpressionRest(expression); + typeArguments = tryParse(parseTypeArgumentsInExpression); + if (isTemplateStartOfTaggedTemplate()) { + ts.Debug.assert(!!typeArguments, "Expected a type argument list; all plain tagged template starts should be consumed in 'parseMemberExpressionRest'"); + expression = parseTaggedTemplateRest(expression, typeArguments); + typeArguments = undefined; + } + break; + } + var node = createNode(192 /* NewExpression */, fullStart); + node.expression = expression; + node.typeArguments = typeArguments; + if (node.typeArguments || token() === 20 /* OpenParenToken */) { + node.arguments = parseArgumentList(); + } + return finishNode(node); + } + // STATEMENTS + function parseBlock(ignoreMissingOpenBrace, diagnosticMessage) { + var node = createNode(218 /* Block */); + if (parseExpected(18 /* OpenBraceToken */, diagnosticMessage) || ignoreMissingOpenBrace) { + if (scanner.hasPrecedingLineBreak()) { + node.multiLine = true; + } + node.statements = parseList(1 /* BlockStatements */, parseStatement); + parseExpected(19 /* CloseBraceToken */); + } + else { + node.statements = createMissingList(); + } + return finishNode(node); + } + function parseFunctionBlock(flags, diagnosticMessage) { + var savedYieldContext = inYieldContext(); + setYieldContext(!!(flags & 1 /* Yield */)); + var savedAwaitContext = inAwaitContext(); + setAwaitContext(!!(flags & 2 /* Await */)); + // We may be in a [Decorator] context when parsing a function expression or + // arrow function. The body of the function is not in [Decorator] context. + var saveDecoratorContext = inDecoratorContext(); + if (saveDecoratorContext) { + setDecoratorContext(/*val*/ false); + } + var block = parseBlock(!!(flags & 16 /* IgnoreMissingOpenBrace */), diagnosticMessage); + if (saveDecoratorContext) { + setDecoratorContext(/*val*/ true); + } + setYieldContext(savedYieldContext); + setAwaitContext(savedAwaitContext); + return block; + } + function parseEmptyStatement() { + var node = createNode(220 /* EmptyStatement */); + parseExpected(26 /* SemicolonToken */); + return finishNode(node); + } + function parseIfStatement() { + var node = createNode(222 /* IfStatement */); + parseExpected(91 /* IfKeyword */); + parseExpected(20 /* OpenParenToken */); + node.expression = allowInAnd(parseExpression); + parseExpected(21 /* CloseParenToken */); + node.thenStatement = parseStatement(); + node.elseStatement = parseOptional(83 /* ElseKeyword */) ? parseStatement() : undefined; + return finishNode(node); + } + function parseDoStatement() { + var node = createNode(223 /* DoStatement */); + parseExpected(82 /* DoKeyword */); + node.statement = parseStatement(); + parseExpected(107 /* WhileKeyword */); + parseExpected(20 /* OpenParenToken */); + node.expression = allowInAnd(parseExpression); + parseExpected(21 /* CloseParenToken */); + // From: https://mail.mozilla.org/pipermail/es-discuss/2011-August/016188.html + // 157 min --- All allen at wirfs-brock.com CONF --- "do{;}while(false)false" prohibited in + // spec but allowed in consensus reality. Approved -- this is the de-facto standard whereby + // do;while(0)x will have a semicolon inserted before x. + parseOptional(26 /* SemicolonToken */); + return finishNode(node); + } + function parseWhileStatement() { + var node = createNode(224 /* WhileStatement */); + parseExpected(107 /* WhileKeyword */); + parseExpected(20 /* OpenParenToken */); + node.expression = allowInAnd(parseExpression); + parseExpected(21 /* CloseParenToken */); + node.statement = parseStatement(); + return finishNode(node); + } + function parseForOrForInOrForOfStatement() { + var pos = getNodePos(); + parseExpected(89 /* ForKeyword */); + var awaitToken = parseOptionalToken(122 /* AwaitKeyword */); + parseExpected(20 /* OpenParenToken */); + var initializer; + if (token() !== 26 /* SemicolonToken */) { + if (token() === 105 /* VarKeyword */ || token() === 111 /* LetKeyword */ || token() === 77 /* ConstKeyword */) { + initializer = parseVariableDeclarationList(/*inForStatementInitializer*/ true); + } + else { + initializer = disallowInAnd(parseExpression); + } + } + var forOrForInOrForOfStatement; + if (awaitToken ? parseExpected(147 /* OfKeyword */) : parseOptional(147 /* OfKeyword */)) { + var forOfStatement = createNode(227 /* ForOfStatement */, pos); + forOfStatement.awaitModifier = awaitToken; + forOfStatement.initializer = initializer; + forOfStatement.expression = allowInAnd(parseAssignmentExpressionOrHigher); + parseExpected(21 /* CloseParenToken */); + forOrForInOrForOfStatement = forOfStatement; + } + else if (parseOptional(93 /* InKeyword */)) { + var forInStatement = createNode(226 /* ForInStatement */, pos); + forInStatement.initializer = initializer; + forInStatement.expression = allowInAnd(parseExpression); + parseExpected(21 /* CloseParenToken */); + forOrForInOrForOfStatement = forInStatement; + } + else { + var forStatement = createNode(225 /* ForStatement */, pos); + forStatement.initializer = initializer; + parseExpected(26 /* SemicolonToken */); + if (token() !== 26 /* SemicolonToken */ && token() !== 21 /* CloseParenToken */) { + forStatement.condition = allowInAnd(parseExpression); + } + parseExpected(26 /* SemicolonToken */); + if (token() !== 21 /* CloseParenToken */) { + forStatement.incrementor = allowInAnd(parseExpression); + } + parseExpected(21 /* CloseParenToken */); + forOrForInOrForOfStatement = forStatement; + } + forOrForInOrForOfStatement.statement = parseStatement(); + return finishNode(forOrForInOrForOfStatement); + } + function parseBreakOrContinueStatement(kind) { + var node = createNode(kind); + parseExpected(kind === 229 /* BreakStatement */ ? 73 /* BreakKeyword */ : 78 /* ContinueKeyword */); + if (!canParseSemicolon()) { + node.label = parseIdentifier(); + } + parseSemicolon(); + return finishNode(node); + } + function parseReturnStatement() { + var node = createNode(230 /* ReturnStatement */); + parseExpected(97 /* ReturnKeyword */); + if (!canParseSemicolon()) { + node.expression = allowInAnd(parseExpression); + } + parseSemicolon(); + return finishNode(node); + } + function parseWithStatement() { + var node = createNode(231 /* WithStatement */); + parseExpected(108 /* WithKeyword */); + parseExpected(20 /* OpenParenToken */); + node.expression = allowInAnd(parseExpression); + parseExpected(21 /* CloseParenToken */); + node.statement = doInsideOfContext(8388608 /* InWithStatement */, parseStatement); + return finishNode(node); + } + function parseCaseClause() { + var node = createNode(271 /* CaseClause */); + parseExpected(74 /* CaseKeyword */); + node.expression = allowInAnd(parseExpression); + parseExpected(57 /* ColonToken */); + node.statements = parseList(3 /* SwitchClauseStatements */, parseStatement); + return finishNode(node); + } + function parseDefaultClause() { + var node = createNode(272 /* DefaultClause */); + parseExpected(80 /* DefaultKeyword */); + parseExpected(57 /* ColonToken */); + node.statements = parseList(3 /* SwitchClauseStatements */, parseStatement); + return finishNode(node); + } + function parseCaseOrDefaultClause() { + return token() === 74 /* CaseKeyword */ ? parseCaseClause() : parseDefaultClause(); + } + function parseSwitchStatement() { + var node = createNode(232 /* SwitchStatement */); + parseExpected(99 /* SwitchKeyword */); + parseExpected(20 /* OpenParenToken */); + node.expression = allowInAnd(parseExpression); + parseExpected(21 /* CloseParenToken */); + var caseBlock = createNode(246 /* CaseBlock */); + parseExpected(18 /* OpenBraceToken */); + caseBlock.clauses = parseList(2 /* SwitchClauses */, parseCaseOrDefaultClause); + parseExpected(19 /* CloseBraceToken */); + node.caseBlock = finishNode(caseBlock); + return finishNode(node); + } + function parseThrowStatement() { + // ThrowStatement[Yield] : + // throw [no LineTerminator here]Expression[In, ?Yield]; + // Because of automatic semicolon insertion, we need to report error if this + // throw could be terminated with a semicolon. Note: we can't call 'parseExpression' + // directly as that might consume an expression on the following line. + // We just return 'undefined' in that case. The actual error will be reported in the + // grammar walker. + var node = createNode(234 /* ThrowStatement */); + parseExpected(101 /* ThrowKeyword */); + node.expression = scanner.hasPrecedingLineBreak() ? undefined : allowInAnd(parseExpression); + parseSemicolon(); + return finishNode(node); + } + // TODO: Review for error recovery + function parseTryStatement() { + var node = createNode(235 /* TryStatement */); + parseExpected(103 /* TryKeyword */); + node.tryBlock = parseBlock(/*ignoreMissingOpenBrace*/ false); + node.catchClause = token() === 75 /* CatchKeyword */ ? parseCatchClause() : undefined; + // If we don't have a catch clause, then we must have a finally clause. Try to parse + // one out no matter what. + if (!node.catchClause || token() === 88 /* FinallyKeyword */) { + parseExpected(88 /* FinallyKeyword */); + node.finallyBlock = parseBlock(/*ignoreMissingOpenBrace*/ false); + } + return finishNode(node); + } + function parseCatchClause() { + var result = createNode(274 /* CatchClause */); + parseExpected(75 /* CatchKeyword */); + if (parseOptional(20 /* OpenParenToken */)) { + result.variableDeclaration = parseVariableDeclaration(); + parseExpected(21 /* CloseParenToken */); + } + else { + // Keep shape of node to avoid degrading performance. + result.variableDeclaration = undefined; + } + result.block = parseBlock(/*ignoreMissingOpenBrace*/ false); + return finishNode(result); + } + function parseDebuggerStatement() { + var node = createNode(236 /* DebuggerStatement */); + parseExpected(79 /* DebuggerKeyword */); + parseSemicolon(); + return finishNode(node); + } + function parseExpressionOrLabeledStatement() { + // Avoiding having to do the lookahead for a labeled statement by just trying to parse + // out an expression, seeing if it is identifier and then seeing if it is followed by + // a colon. + var node = createNodeWithJSDoc(0 /* Unknown */); + var expression = allowInAnd(parseExpression); + if (expression.kind === 72 /* Identifier */ && parseOptional(57 /* ColonToken */)) { + node.kind = 233 /* LabeledStatement */; + node.label = expression; + node.statement = parseStatement(); + } + else { + node.kind = 221 /* ExpressionStatement */; + node.expression = expression; + parseSemicolon(); + } + return finishNode(node); + } + function nextTokenIsIdentifierOrKeywordOnSameLine() { + nextToken(); + return ts.tokenIsIdentifierOrKeyword(token()) && !scanner.hasPrecedingLineBreak(); + } + function nextTokenIsClassKeywordOnSameLine() { + nextToken(); + return token() === 76 /* ClassKeyword */ && !scanner.hasPrecedingLineBreak(); + } + function nextTokenIsFunctionKeywordOnSameLine() { + nextToken(); + return token() === 90 /* FunctionKeyword */ && !scanner.hasPrecedingLineBreak(); + } + function nextTokenIsIdentifierOrKeywordOrLiteralOnSameLine() { + nextToken(); + return (ts.tokenIsIdentifierOrKeyword(token()) || token() === 8 /* NumericLiteral */ || token() === 9 /* BigIntLiteral */ || token() === 10 /* StringLiteral */) && !scanner.hasPrecedingLineBreak(); + } + function isDeclaration() { + while (true) { + switch (token()) { + case 105 /* VarKeyword */: + case 111 /* LetKeyword */: + case 77 /* ConstKeyword */: + case 90 /* FunctionKeyword */: + case 76 /* ClassKeyword */: + case 84 /* EnumKeyword */: + return true; + // 'declare', 'module', 'namespace', 'interface'* and 'type' are all legal JavaScript identifiers; + // however, an identifier cannot be followed by another identifier on the same line. This is what we + // count on to parse out the respective declarations. For instance, we exploit this to say that + // + // namespace n + // + // can be none other than the beginning of a namespace declaration, but need to respect that JavaScript sees + // + // namespace + // n + // + // as the identifier 'namespace' on one line followed by the identifier 'n' on another. + // We need to look one token ahead to see if it permissible to try parsing a declaration. + // + // *Note*: 'interface' is actually a strict mode reserved word. So while + // + // "use strict" + // interface + // I {} + // + // could be legal, it would add complexity for very little gain. + case 110 /* InterfaceKeyword */: + case 140 /* TypeKeyword */: + return nextTokenIsIdentifierOnSameLine(); + case 130 /* ModuleKeyword */: + case 131 /* NamespaceKeyword */: + return nextTokenIsIdentifierOrStringLiteralOnSameLine(); + case 118 /* AbstractKeyword */: + case 121 /* AsyncKeyword */: + case 125 /* DeclareKeyword */: + case 113 /* PrivateKeyword */: + case 114 /* ProtectedKeyword */: + case 115 /* PublicKeyword */: + case 133 /* ReadonlyKeyword */: + nextToken(); + // ASI takes effect for this modifier. + if (scanner.hasPrecedingLineBreak()) { + return false; + } + continue; + case 145 /* GlobalKeyword */: + nextToken(); + return token() === 18 /* OpenBraceToken */ || token() === 72 /* Identifier */ || token() === 85 /* ExportKeyword */; + case 92 /* ImportKeyword */: + nextToken(); + return token() === 10 /* StringLiteral */ || token() === 40 /* AsteriskToken */ || + token() === 18 /* OpenBraceToken */ || ts.tokenIsIdentifierOrKeyword(token()); + case 85 /* ExportKeyword */: + nextToken(); + if (token() === 59 /* EqualsToken */ || token() === 40 /* AsteriskToken */ || + token() === 18 /* OpenBraceToken */ || token() === 80 /* DefaultKeyword */ || + token() === 119 /* AsKeyword */) { + return true; + } + continue; + case 116 /* StaticKeyword */: + nextToken(); + continue; + default: + return false; + } + } + } + function isStartOfDeclaration() { + return lookAhead(isDeclaration); + } + function isStartOfStatement() { + switch (token()) { + case 58 /* AtToken */: + case 26 /* SemicolonToken */: + case 18 /* OpenBraceToken */: + case 105 /* VarKeyword */: + case 111 /* LetKeyword */: + case 90 /* FunctionKeyword */: + case 76 /* ClassKeyword */: + case 84 /* EnumKeyword */: + case 91 /* IfKeyword */: + case 82 /* DoKeyword */: + case 107 /* WhileKeyword */: + case 89 /* ForKeyword */: + case 78 /* ContinueKeyword */: + case 73 /* BreakKeyword */: + case 97 /* ReturnKeyword */: + case 108 /* WithKeyword */: + case 99 /* SwitchKeyword */: + case 101 /* ThrowKeyword */: + case 103 /* TryKeyword */: + case 79 /* DebuggerKeyword */: + // 'catch' and 'finally' do not actually indicate that the code is part of a statement, + // however, we say they are here so that we may gracefully parse them and error later. + case 75 /* CatchKeyword */: + case 88 /* FinallyKeyword */: + return true; + case 92 /* ImportKeyword */: + return isStartOfDeclaration() || lookAhead(nextTokenIsOpenParenOrLessThanOrDot); + case 77 /* ConstKeyword */: + case 85 /* ExportKeyword */: + return isStartOfDeclaration(); + case 121 /* AsyncKeyword */: + case 125 /* DeclareKeyword */: + case 110 /* InterfaceKeyword */: + case 130 /* ModuleKeyword */: + case 131 /* NamespaceKeyword */: + case 140 /* TypeKeyword */: + case 145 /* GlobalKeyword */: + // When these don't start a declaration, they're an identifier in an expression statement + return true; + case 115 /* PublicKeyword */: + case 113 /* PrivateKeyword */: + case 114 /* ProtectedKeyword */: + case 116 /* StaticKeyword */: + case 133 /* ReadonlyKeyword */: + // When these don't start a declaration, they may be the start of a class member if an identifier + // immediately follows. Otherwise they're an identifier in an expression statement. + return isStartOfDeclaration() || !lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine); + default: + return isStartOfExpression(); + } + } + function nextTokenIsIdentifierOrStartOfDestructuring() { + nextToken(); + return isIdentifier() || token() === 18 /* OpenBraceToken */ || token() === 22 /* OpenBracketToken */; + } + function isLetDeclaration() { + // In ES6 'let' always starts a lexical declaration if followed by an identifier or { + // or [. + return lookAhead(nextTokenIsIdentifierOrStartOfDestructuring); + } + function parseStatement() { + switch (token()) { + case 26 /* SemicolonToken */: + return parseEmptyStatement(); + case 18 /* OpenBraceToken */: + return parseBlock(/*ignoreMissingOpenBrace*/ false); + case 105 /* VarKeyword */: + return parseVariableStatement(createNodeWithJSDoc(237 /* VariableDeclaration */)); + case 111 /* LetKeyword */: + if (isLetDeclaration()) { + return parseVariableStatement(createNodeWithJSDoc(237 /* VariableDeclaration */)); + } + break; + case 90 /* FunctionKeyword */: + return parseFunctionDeclaration(createNodeWithJSDoc(239 /* FunctionDeclaration */)); + case 76 /* ClassKeyword */: + return parseClassDeclaration(createNodeWithJSDoc(240 /* ClassDeclaration */)); + case 91 /* IfKeyword */: + return parseIfStatement(); + case 82 /* DoKeyword */: + return parseDoStatement(); + case 107 /* WhileKeyword */: + return parseWhileStatement(); + case 89 /* ForKeyword */: + return parseForOrForInOrForOfStatement(); + case 78 /* ContinueKeyword */: + return parseBreakOrContinueStatement(228 /* ContinueStatement */); + case 73 /* BreakKeyword */: + return parseBreakOrContinueStatement(229 /* BreakStatement */); + case 97 /* ReturnKeyword */: + return parseReturnStatement(); + case 108 /* WithKeyword */: + return parseWithStatement(); + case 99 /* SwitchKeyword */: + return parseSwitchStatement(); + case 101 /* ThrowKeyword */: + return parseThrowStatement(); + case 103 /* TryKeyword */: + // Include 'catch' and 'finally' for error recovery. + case 75 /* CatchKeyword */: + case 88 /* FinallyKeyword */: + return parseTryStatement(); + case 79 /* DebuggerKeyword */: + return parseDebuggerStatement(); + case 58 /* AtToken */: + return parseDeclaration(); + case 121 /* AsyncKeyword */: + case 110 /* InterfaceKeyword */: + case 140 /* TypeKeyword */: + case 130 /* ModuleKeyword */: + case 131 /* NamespaceKeyword */: + case 125 /* DeclareKeyword */: + case 77 /* ConstKeyword */: + case 84 /* EnumKeyword */: + case 85 /* ExportKeyword */: + case 92 /* ImportKeyword */: + case 113 /* PrivateKeyword */: + case 114 /* ProtectedKeyword */: + case 115 /* PublicKeyword */: + case 118 /* AbstractKeyword */: + case 116 /* StaticKeyword */: + case 133 /* ReadonlyKeyword */: + case 145 /* GlobalKeyword */: + if (isStartOfDeclaration()) { + return parseDeclaration(); + } + break; + } + return parseExpressionOrLabeledStatement(); + } + function isDeclareModifier(modifier) { + return modifier.kind === 125 /* DeclareKeyword */; + } + function parseDeclaration() { + var node = createNodeWithJSDoc(0 /* Unknown */); + node.decorators = parseDecorators(); + node.modifiers = parseModifiers(); + if (ts.some(node.modifiers, isDeclareModifier)) { + for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) { + var m = _a[_i]; + m.flags |= 4194304 /* Ambient */; + } + return doInsideOfContext(4194304 /* Ambient */, function () { return parseDeclarationWorker(node); }); + } + else { + return parseDeclarationWorker(node); + } + } + function parseDeclarationWorker(node) { + switch (token()) { + case 105 /* VarKeyword */: + case 111 /* LetKeyword */: + case 77 /* ConstKeyword */: + return parseVariableStatement(node); + case 90 /* FunctionKeyword */: + return parseFunctionDeclaration(node); + case 76 /* ClassKeyword */: + return parseClassDeclaration(node); + case 110 /* InterfaceKeyword */: + return parseInterfaceDeclaration(node); + case 140 /* TypeKeyword */: + return parseTypeAliasDeclaration(node); + case 84 /* EnumKeyword */: + return parseEnumDeclaration(node); + case 145 /* GlobalKeyword */: + case 130 /* ModuleKeyword */: + case 131 /* NamespaceKeyword */: + return parseModuleDeclaration(node); + case 92 /* ImportKeyword */: + return parseImportDeclarationOrImportEqualsDeclaration(node); + case 85 /* ExportKeyword */: + nextToken(); + switch (token()) { + case 80 /* DefaultKeyword */: + case 59 /* EqualsToken */: + return parseExportAssignment(node); + case 119 /* AsKeyword */: + return parseNamespaceExportDeclaration(node); + default: + return parseExportDeclaration(node); + } + default: + if (node.decorators || node.modifiers) { + // We reached this point because we encountered decorators and/or modifiers and assumed a declaration + // would follow. For recovery and error reporting purposes, return an incomplete declaration. + var missing = createMissingNode(258 /* MissingDeclaration */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected); + missing.pos = node.pos; + missing.decorators = node.decorators; + missing.modifiers = node.modifiers; + return finishNode(missing); + } + return undefined; // TODO: GH#18217 + } + } + function nextTokenIsIdentifierOrStringLiteralOnSameLine() { + nextToken(); + return !scanner.hasPrecedingLineBreak() && (isIdentifier() || token() === 10 /* StringLiteral */); + } + function parseFunctionBlockOrSemicolon(flags, diagnosticMessage) { + if (token() !== 18 /* OpenBraceToken */ && canParseSemicolon()) { + parseSemicolon(); + return; + } + return parseFunctionBlock(flags, diagnosticMessage); + } + // DECLARATIONS + function parseArrayBindingElement() { + if (token() === 27 /* CommaToken */) { + return createNode(210 /* OmittedExpression */); + } + var node = createNode(186 /* BindingElement */); + node.dotDotDotToken = parseOptionalToken(25 /* DotDotDotToken */); + node.name = parseIdentifierOrPattern(); + node.initializer = parseInitializer(); + return finishNode(node); + } + function parseObjectBindingElement() { + var node = createNode(186 /* BindingElement */); + node.dotDotDotToken = parseOptionalToken(25 /* DotDotDotToken */); + var tokenIsIdentifier = isIdentifier(); + var propertyName = parsePropertyName(); + if (tokenIsIdentifier && token() !== 57 /* ColonToken */) { + node.name = propertyName; + } + else { + parseExpected(57 /* ColonToken */); + node.propertyName = propertyName; + node.name = parseIdentifierOrPattern(); + } + node.initializer = parseInitializer(); + return finishNode(node); + } + function parseObjectBindingPattern() { + var node = createNode(184 /* ObjectBindingPattern */); + parseExpected(18 /* OpenBraceToken */); + node.elements = parseDelimitedList(9 /* ObjectBindingElements */, parseObjectBindingElement); + parseExpected(19 /* CloseBraceToken */); + return finishNode(node); + } + function parseArrayBindingPattern() { + var node = createNode(185 /* ArrayBindingPattern */); + parseExpected(22 /* OpenBracketToken */); + node.elements = parseDelimitedList(10 /* ArrayBindingElements */, parseArrayBindingElement); + parseExpected(23 /* CloseBracketToken */); + return finishNode(node); + } + function isIdentifierOrPattern() { + return token() === 18 /* OpenBraceToken */ || token() === 22 /* OpenBracketToken */ || isIdentifier(); + } + function parseIdentifierOrPattern() { + if (token() === 22 /* OpenBracketToken */) { + return parseArrayBindingPattern(); + } + if (token() === 18 /* OpenBraceToken */) { + return parseObjectBindingPattern(); + } + return parseIdentifier(); + } + function parseVariableDeclarationAllowExclamation() { + return parseVariableDeclaration(/*allowExclamation*/ true); + } + function parseVariableDeclaration(allowExclamation) { + var node = createNode(237 /* VariableDeclaration */); + node.name = parseIdentifierOrPattern(); + if (allowExclamation && node.name.kind === 72 /* Identifier */ && + token() === 52 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) { + node.exclamationToken = parseTokenNode(); + } + node.type = parseTypeAnnotation(); + if (!isInOrOfKeyword(token())) { + node.initializer = parseInitializer(); + } + return finishNode(node); + } + function parseVariableDeclarationList(inForStatementInitializer) { + var node = createNode(238 /* VariableDeclarationList */); + switch (token()) { + case 105 /* VarKeyword */: + break; + case 111 /* LetKeyword */: + node.flags |= 1 /* Let */; + break; + case 77 /* ConstKeyword */: + node.flags |= 2 /* Const */; + break; + default: + ts.Debug.fail(); + } + nextToken(); + // The user may have written the following: + // + // for (let of X) { } + // + // In this case, we want to parse an empty declaration list, and then parse 'of' + // as a keyword. The reason this is not automatic is that 'of' is a valid identifier. + // So we need to look ahead to determine if 'of' should be treated as a keyword in + // this context. + // The checker will then give an error that there is an empty declaration list. + if (token() === 147 /* OfKeyword */ && lookAhead(canFollowContextualOfKeyword)) { + node.declarations = createMissingList(); + } + else { + var savedDisallowIn = inDisallowInContext(); + setDisallowInContext(inForStatementInitializer); + node.declarations = parseDelimitedList(8 /* VariableDeclarations */, inForStatementInitializer ? parseVariableDeclaration : parseVariableDeclarationAllowExclamation); + setDisallowInContext(savedDisallowIn); + } + return finishNode(node); + } + function canFollowContextualOfKeyword() { + return nextTokenIsIdentifier() && nextToken() === 21 /* CloseParenToken */; + } + function parseVariableStatement(node) { + node.kind = 219 /* VariableStatement */; + node.declarationList = parseVariableDeclarationList(/*inForStatementInitializer*/ false); + parseSemicolon(); + return finishNode(node); + } + function parseFunctionDeclaration(node) { + node.kind = 239 /* FunctionDeclaration */; + parseExpected(90 /* FunctionKeyword */); + node.asteriskToken = parseOptionalToken(40 /* AsteriskToken */); + node.name = ts.hasModifier(node, 512 /* Default */) ? parseOptionalIdentifier() : parseIdentifier(); + var isGenerator = node.asteriskToken ? 1 /* Yield */ : 0 /* None */; + var isAsync = ts.hasModifier(node, 256 /* Async */) ? 2 /* Await */ : 0 /* None */; + fillSignature(57 /* ColonToken */, isGenerator | isAsync, node); + node.body = parseFunctionBlockOrSemicolon(isGenerator | isAsync, ts.Diagnostics.or_expected); + return finishNode(node); + } + function parseConstructorDeclaration(node) { + node.kind = 157 /* Constructor */; + parseExpected(124 /* ConstructorKeyword */); + fillSignature(57 /* ColonToken */, 0 /* None */, node); + node.body = parseFunctionBlockOrSemicolon(0 /* None */, ts.Diagnostics.or_expected); + return finishNode(node); + } + function parseMethodDeclaration(node, asteriskToken, diagnosticMessage) { + node.kind = 156 /* MethodDeclaration */; + node.asteriskToken = asteriskToken; + var isGenerator = asteriskToken ? 1 /* Yield */ : 0 /* None */; + var isAsync = ts.hasModifier(node, 256 /* Async */) ? 2 /* Await */ : 0 /* None */; + fillSignature(57 /* ColonToken */, isGenerator | isAsync, node); + node.body = parseFunctionBlockOrSemicolon(isGenerator | isAsync, diagnosticMessage); + return finishNode(node); + } + function parsePropertyDeclaration(node) { + node.kind = 154 /* PropertyDeclaration */; + if (!node.questionToken && token() === 52 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) { + node.exclamationToken = parseTokenNode(); + } + node.type = parseTypeAnnotation(); + // For instance properties specifically, since they are evaluated inside the constructor, + // we do *not * want to parse yield expressions, so we specifically turn the yield context + // off. The grammar would look something like this: + // + // MemberVariableDeclaration[Yield]: + // AccessibilityModifier_opt PropertyName TypeAnnotation_opt Initializer_opt[In]; + // AccessibilityModifier_opt static_opt PropertyName TypeAnnotation_opt Initializer_opt[In, ?Yield]; + // + // The checker may still error in the static case to explicitly disallow the yield expression. + node.initializer = ts.hasModifier(node, 32 /* Static */) + ? allowInAnd(parseInitializer) + : doOutsideOfContext(4096 /* YieldContext */ | 2048 /* DisallowInContext */, parseInitializer); + parseSemicolon(); + return finishNode(node); + } + function parsePropertyOrMethodDeclaration(node) { + var asteriskToken = parseOptionalToken(40 /* AsteriskToken */); + node.name = parsePropertyName(); + // Note: this is not legal as per the grammar. But we allow it in the parser and + // report an error in the grammar checker. + node.questionToken = parseOptionalToken(56 /* QuestionToken */); + if (asteriskToken || token() === 20 /* OpenParenToken */ || token() === 28 /* LessThanToken */) { + return parseMethodDeclaration(node, asteriskToken, ts.Diagnostics.or_expected); + } + return parsePropertyDeclaration(node); + } + function parseAccessorDeclaration(node, kind) { + node.kind = kind; + node.name = parsePropertyName(); + fillSignature(57 /* ColonToken */, 0 /* None */, node); + node.body = parseFunctionBlockOrSemicolon(0 /* None */); + return finishNode(node); + } + function isClassMemberStart() { + var idToken; + if (token() === 58 /* AtToken */) { + return true; + } + // Eat up all modifiers, but hold on to the last one in case it is actually an identifier. + while (ts.isModifierKind(token())) { + idToken = token(); + // If the idToken is a class modifier (protected, private, public, and static), it is + // certain that we are starting to parse class member. This allows better error recovery + // Example: + // public foo() ... // true + // public @dec blah ... // true; we will then report an error later + // export public ... // true; we will then report an error later + if (ts.isClassMemberModifier(idToken)) { + return true; + } + nextToken(); + } + if (token() === 40 /* AsteriskToken */) { + return true; + } + // Try to get the first property-like token following all modifiers. + // This can either be an identifier or the 'get' or 'set' keywords. + if (isLiteralPropertyName()) { + idToken = token(); + nextToken(); + } + // Index signatures and computed properties are class members; we can parse. + if (token() === 22 /* OpenBracketToken */) { + return true; + } + // If we were able to get any potential identifier... + if (idToken !== undefined) { + // If we have a non-keyword identifier, or if we have an accessor, then it's safe to parse. + if (!ts.isKeyword(idToken) || idToken === 137 /* SetKeyword */ || idToken === 126 /* GetKeyword */) { + return true; + } + // If it *is* a keyword, but not an accessor, check a little farther along + // to see if it should actually be parsed as a class member. + switch (token()) { + case 20 /* OpenParenToken */: // Method declaration + case 28 /* LessThanToken */: // Generic Method declaration + case 52 /* ExclamationToken */: // Non-null assertion on property name + case 57 /* ColonToken */: // Type Annotation for declaration + case 59 /* EqualsToken */: // Initializer for declaration + case 56 /* QuestionToken */: // Not valid, but permitted so that it gets caught later on. + return true; + default: + // Covers + // - Semicolons (declaration termination) + // - Closing braces (end-of-class, must be declaration) + // - End-of-files (not valid, but permitted so that it gets caught later on) + // - Line-breaks (enabling *automatic semicolon insertion*) + return canParseSemicolon(); + } + } + return false; + } + function parseDecorators() { + var list; + var listPos = getNodePos(); + while (true) { + var decoratorStart = getNodePos(); + if (!parseOptional(58 /* AtToken */)) { + break; + } + var decorator = createNode(152 /* Decorator */, decoratorStart); + decorator.expression = doInDecoratorContext(parseLeftHandSideExpressionOrHigher); + finishNode(decorator); + (list || (list = [])).push(decorator); + } + return list && createNodeArray(list, listPos); + } + /* + * There are situations in which a modifier like 'const' will appear unexpectedly, such as on a class member. + * In those situations, if we are entirely sure that 'const' is not valid on its own (such as when ASI takes effect + * and turns it into a standalone declaration), then it is better to parse it and report an error later. + * + * In such situations, 'permitInvalidConstAsModifier' should be set to true. + */ + function parseModifiers(permitInvalidConstAsModifier) { + var list; + var listPos = getNodePos(); + while (true) { + var modifierStart = scanner.getStartPos(); + var modifierKind = token(); + if (token() === 77 /* ConstKeyword */ && permitInvalidConstAsModifier) { + // We need to ensure that any subsequent modifiers appear on the same line + // so that when 'const' is a standalone declaration, we don't issue an error. + if (!tryParse(nextTokenIsOnSameLineAndCanFollowModifier)) { + break; + } + } + else { + if (!parseAnyContextualModifier()) { + break; + } + } + var modifier = finishNode(createNode(modifierKind, modifierStart)); + (list || (list = [])).push(modifier); + } + return list && createNodeArray(list, listPos); + } + function parseModifiersForArrowFunction() { + var modifiers; + if (token() === 121 /* AsyncKeyword */) { + var modifierStart = scanner.getStartPos(); + var modifierKind = token(); + nextToken(); + var modifier = finishNode(createNode(modifierKind, modifierStart)); + modifiers = createNodeArray([modifier], modifierStart); + } + return modifiers; + } + function parseClassElement() { + if (token() === 26 /* SemicolonToken */) { + var result = createNode(217 /* SemicolonClassElement */); + nextToken(); + return finishNode(result); + } + var node = createNodeWithJSDoc(0 /* Unknown */); + node.decorators = parseDecorators(); + node.modifiers = parseModifiers(/*permitInvalidConstAsModifier*/ true); + if (parseContextualModifier(126 /* GetKeyword */)) { + return parseAccessorDeclaration(node, 158 /* GetAccessor */); + } + if (parseContextualModifier(137 /* SetKeyword */)) { + return parseAccessorDeclaration(node, 159 /* SetAccessor */); + } + if (token() === 124 /* ConstructorKeyword */) { + return parseConstructorDeclaration(node); + } + if (isIndexSignature()) { + return parseIndexSignatureDeclaration(node); + } + // It is very important that we check this *after* checking indexers because + // the [ token can start an index signature or a computed property name + if (ts.tokenIsIdentifierOrKeyword(token()) || + token() === 10 /* StringLiteral */ || + token() === 8 /* NumericLiteral */ || + token() === 40 /* AsteriskToken */ || + token() === 22 /* OpenBracketToken */) { + return parsePropertyOrMethodDeclaration(node); + } + if (node.decorators || node.modifiers) { + // treat this as a property declaration with a missing name. + node.name = createMissingNode(72 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected); + return parsePropertyDeclaration(node); + } + // 'isClassMemberStart' should have hinted not to attempt parsing. + return ts.Debug.fail("Should not have attempted to parse class member declaration."); + } + function parseClassExpression() { + return parseClassDeclarationOrExpression(createNodeWithJSDoc(0 /* Unknown */), 209 /* ClassExpression */); + } + function parseClassDeclaration(node) { + return parseClassDeclarationOrExpression(node, 240 /* ClassDeclaration */); + } + function parseClassDeclarationOrExpression(node, kind) { + node.kind = kind; + parseExpected(76 /* ClassKeyword */); + node.name = parseNameOfClassDeclarationOrExpression(); + node.typeParameters = parseTypeParameters(); + node.heritageClauses = parseHeritageClauses(); + if (parseExpected(18 /* OpenBraceToken */)) { + // ClassTail[Yield,Await] : (Modified) See 14.5 + // ClassHeritage[?Yield,?Await]opt { ClassBody[?Yield,?Await]opt } + node.members = parseClassMembers(); + parseExpected(19 /* CloseBraceToken */); + } + else { + node.members = createMissingList(); + } + return finishNode(node); + } + function parseNameOfClassDeclarationOrExpression() { + // implements is a future reserved word so + // 'class implements' might mean either + // - class expression with omitted name, 'implements' starts heritage clause + // - class with name 'implements' + // 'isImplementsClause' helps to disambiguate between these two cases + return isIdentifier() && !isImplementsClause() + ? parseIdentifier() + : undefined; + } + function isImplementsClause() { + return token() === 109 /* ImplementsKeyword */ && lookAhead(nextTokenIsIdentifierOrKeyword); + } + function parseHeritageClauses() { + // ClassTail[Yield,Await] : (Modified) See 14.5 + // ClassHeritage[?Yield,?Await]opt { ClassBody[?Yield,?Await]opt } + if (isHeritageClause()) { + return parseList(22 /* HeritageClauses */, parseHeritageClause); + } + return undefined; + } + function parseHeritageClause() { + var tok = token(); + ts.Debug.assert(tok === 86 /* ExtendsKeyword */ || tok === 109 /* ImplementsKeyword */); // isListElement() should ensure this. + var node = createNode(273 /* HeritageClause */); + node.token = tok; + nextToken(); + node.types = parseDelimitedList(7 /* HeritageClauseElement */, parseExpressionWithTypeArguments); + return finishNode(node); + } + function parseExpressionWithTypeArguments() { + var node = createNode(211 /* ExpressionWithTypeArguments */); + node.expression = parseLeftHandSideExpressionOrHigher(); + node.typeArguments = tryParseTypeArguments(); + return finishNode(node); + } + function tryParseTypeArguments() { + return token() === 28 /* LessThanToken */ + ? parseBracketedList(20 /* TypeArguments */, parseType, 28 /* LessThanToken */, 30 /* GreaterThanToken */) + : undefined; + } + function isHeritageClause() { + return token() === 86 /* ExtendsKeyword */ || token() === 109 /* ImplementsKeyword */; + } + function parseClassMembers() { + return parseList(5 /* ClassMembers */, parseClassElement); + } + function parseInterfaceDeclaration(node) { + node.kind = 241 /* InterfaceDeclaration */; + parseExpected(110 /* InterfaceKeyword */); + node.name = parseIdentifier(); + node.typeParameters = parseTypeParameters(); + node.heritageClauses = parseHeritageClauses(); + node.members = parseObjectTypeMembers(); + return finishNode(node); + } + function parseTypeAliasDeclaration(node) { + node.kind = 242 /* TypeAliasDeclaration */; + parseExpected(140 /* TypeKeyword */); + node.name = parseIdentifier(); + node.typeParameters = parseTypeParameters(); + parseExpected(59 /* EqualsToken */); + node.type = parseType(); + parseSemicolon(); + return finishNode(node); + } + // In an ambient declaration, the grammar only allows integer literals as initializers. + // In a non-ambient declaration, the grammar allows uninitialized members only in a + // ConstantEnumMemberSection, which starts at the beginning of an enum declaration + // or any time an integer literal initializer is encountered. + function parseEnumMember() { + var node = createNodeWithJSDoc(278 /* EnumMember */); + node.name = parsePropertyName(); + node.initializer = allowInAnd(parseInitializer); + return finishNode(node); + } + function parseEnumDeclaration(node) { + node.kind = 243 /* EnumDeclaration */; + parseExpected(84 /* EnumKeyword */); + node.name = parseIdentifier(); + if (parseExpected(18 /* OpenBraceToken */)) { + node.members = parseDelimitedList(6 /* EnumMembers */, parseEnumMember); + parseExpected(19 /* CloseBraceToken */); + } + else { + node.members = createMissingList(); + } + return finishNode(node); + } + function parseModuleBlock() { + var node = createNode(245 /* ModuleBlock */); + if (parseExpected(18 /* OpenBraceToken */)) { + node.statements = parseList(1 /* BlockStatements */, parseStatement); + parseExpected(19 /* CloseBraceToken */); + } + else { + node.statements = createMissingList(); + } + return finishNode(node); + } + function parseModuleOrNamespaceDeclaration(node, flags) { + node.kind = 244 /* ModuleDeclaration */; + // If we are parsing a dotted namespace name, we want to + // propagate the 'Namespace' flag across the names if set. + var namespaceFlag = flags & 16 /* Namespace */; + node.flags |= flags; + node.name = parseIdentifier(); + node.body = parseOptional(24 /* DotToken */) + ? parseModuleOrNamespaceDeclaration(createNode(0 /* Unknown */), 4 /* NestedNamespace */ | namespaceFlag) + : parseModuleBlock(); + return finishNode(node); + } + function parseAmbientExternalModuleDeclaration(node) { + node.kind = 244 /* ModuleDeclaration */; + if (token() === 145 /* GlobalKeyword */) { + // parse 'global' as name of global scope augmentation + node.name = parseIdentifier(); + node.flags |= 512 /* GlobalAugmentation */; + } + else { + node.name = parseLiteralNode(); + node.name.text = internIdentifier(node.name.text); + } + if (token() === 18 /* OpenBraceToken */) { + node.body = parseModuleBlock(); + } + else { + parseSemicolon(); + } + return finishNode(node); + } + function parseModuleDeclaration(node) { + var flags = 0; + if (token() === 145 /* GlobalKeyword */) { + // global augmentation + return parseAmbientExternalModuleDeclaration(node); + } + else if (parseOptional(131 /* NamespaceKeyword */)) { + flags |= 16 /* Namespace */; + } + else { + parseExpected(130 /* ModuleKeyword */); + if (token() === 10 /* StringLiteral */) { + return parseAmbientExternalModuleDeclaration(node); + } + } + return parseModuleOrNamespaceDeclaration(node, flags); + } + function isExternalModuleReference() { + return token() === 134 /* RequireKeyword */ && + lookAhead(nextTokenIsOpenParen); + } + function nextTokenIsOpenParen() { + return nextToken() === 20 /* OpenParenToken */; + } + function nextTokenIsSlash() { + return nextToken() === 42 /* SlashToken */; + } + function parseNamespaceExportDeclaration(node) { + node.kind = 247 /* NamespaceExportDeclaration */; + parseExpected(119 /* AsKeyword */); + parseExpected(131 /* NamespaceKeyword */); + node.name = parseIdentifier(); + parseSemicolon(); + return finishNode(node); + } + function parseImportDeclarationOrImportEqualsDeclaration(node) { + parseExpected(92 /* ImportKeyword */); + var afterImportPos = scanner.getStartPos(); + var identifier; + if (isIdentifier()) { + identifier = parseIdentifier(); + if (token() !== 27 /* CommaToken */ && token() !== 144 /* FromKeyword */) { + return parseImportEqualsDeclaration(node, identifier); + } + } + // Import statement + node.kind = 249 /* ImportDeclaration */; + // ImportDeclaration: + // import ImportClause from ModuleSpecifier ; + // import ModuleSpecifier; + if (identifier || // import id + token() === 40 /* AsteriskToken */ || // import * + token() === 18 /* OpenBraceToken */) { // import { + node.importClause = parseImportClause(identifier, afterImportPos); + parseExpected(144 /* FromKeyword */); + } + node.moduleSpecifier = parseModuleSpecifier(); + parseSemicolon(); + return finishNode(node); + } + function parseImportEqualsDeclaration(node, identifier) { + node.kind = 248 /* ImportEqualsDeclaration */; + node.name = identifier; + parseExpected(59 /* EqualsToken */); + node.moduleReference = parseModuleReference(); + parseSemicolon(); + return finishNode(node); + } + function parseImportClause(identifier, fullStart) { + // ImportClause: + // ImportedDefaultBinding + // NameSpaceImport + // NamedImports + // ImportedDefaultBinding, NameSpaceImport + // ImportedDefaultBinding, NamedImports + var importClause = createNode(250 /* ImportClause */, fullStart); + if (identifier) { + // ImportedDefaultBinding: + // ImportedBinding + importClause.name = identifier; + } + // If there was no default import or if there is comma token after default import + // parse namespace or named imports + if (!importClause.name || + parseOptional(27 /* CommaToken */)) { + importClause.namedBindings = token() === 40 /* AsteriskToken */ ? parseNamespaceImport() : parseNamedImportsOrExports(252 /* NamedImports */); + } + return finishNode(importClause); + } + function parseModuleReference() { + return isExternalModuleReference() + ? parseExternalModuleReference() + : parseEntityName(/*allowReservedWords*/ false); + } + function parseExternalModuleReference() { + var node = createNode(259 /* ExternalModuleReference */); + parseExpected(134 /* RequireKeyword */); + parseExpected(20 /* OpenParenToken */); + node.expression = parseModuleSpecifier(); + parseExpected(21 /* CloseParenToken */); + return finishNode(node); + } + function parseModuleSpecifier() { + if (token() === 10 /* StringLiteral */) { + var result = parseLiteralNode(); + result.text = internIdentifier(result.text); + return result; + } + else { + // We allow arbitrary expressions here, even though the grammar only allows string + // literals. We check to ensure that it is only a string literal later in the grammar + // check pass. + return parseExpression(); + } + } + function parseNamespaceImport() { + // NameSpaceImport: + // * as ImportedBinding + var namespaceImport = createNode(251 /* NamespaceImport */); + parseExpected(40 /* AsteriskToken */); + parseExpected(119 /* AsKeyword */); + namespaceImport.name = parseIdentifier(); + return finishNode(namespaceImport); + } + function parseNamedImportsOrExports(kind) { + var node = createNode(kind); + // NamedImports: + // { } + // { ImportsList } + // { ImportsList, } + // ImportsList: + // ImportSpecifier + // ImportsList, ImportSpecifier + node.elements = parseBracketedList(23 /* ImportOrExportSpecifiers */, kind === 252 /* NamedImports */ ? parseImportSpecifier : parseExportSpecifier, 18 /* OpenBraceToken */, 19 /* CloseBraceToken */); + return finishNode(node); + } + function parseExportSpecifier() { + return parseImportOrExportSpecifier(257 /* ExportSpecifier */); + } + function parseImportSpecifier() { + return parseImportOrExportSpecifier(253 /* ImportSpecifier */); + } + function parseImportOrExportSpecifier(kind) { + var node = createNode(kind); + // ImportSpecifier: + // BindingIdentifier + // IdentifierName as BindingIdentifier + // ExportSpecifier: + // IdentifierName + // IdentifierName as IdentifierName + var checkIdentifierIsKeyword = ts.isKeyword(token()) && !isIdentifier(); + var checkIdentifierStart = scanner.getTokenPos(); + var checkIdentifierEnd = scanner.getTextPos(); + var identifierName = parseIdentifierName(); + if (token() === 119 /* AsKeyword */) { + node.propertyName = identifierName; + parseExpected(119 /* AsKeyword */); + checkIdentifierIsKeyword = ts.isKeyword(token()) && !isIdentifier(); + checkIdentifierStart = scanner.getTokenPos(); + checkIdentifierEnd = scanner.getTextPos(); + node.name = parseIdentifierName(); + } + else { + node.name = identifierName; + } + if (kind === 253 /* ImportSpecifier */ && checkIdentifierIsKeyword) { + parseErrorAt(checkIdentifierStart, checkIdentifierEnd, ts.Diagnostics.Identifier_expected); + } + return finishNode(node); + } + function parseExportDeclaration(node) { + node.kind = 255 /* ExportDeclaration */; + if (parseOptional(40 /* AsteriskToken */)) { + parseExpected(144 /* FromKeyword */); + node.moduleSpecifier = parseModuleSpecifier(); + } + else { + node.exportClause = parseNamedImportsOrExports(256 /* NamedExports */); + // It is not uncommon to accidentally omit the 'from' keyword. Additionally, in editing scenarios, + // the 'from' keyword can be parsed as a named export when the export clause is unterminated (i.e. `export { from "moduleName";`) + // If we don't have a 'from' keyword, see if we have a string literal such that ASI won't take effect. + if (token() === 144 /* FromKeyword */ || (token() === 10 /* StringLiteral */ && !scanner.hasPrecedingLineBreak())) { + parseExpected(144 /* FromKeyword */); + node.moduleSpecifier = parseModuleSpecifier(); + } + } + parseSemicolon(); + return finishNode(node); + } + function parseExportAssignment(node) { + node.kind = 254 /* ExportAssignment */; + if (parseOptional(59 /* EqualsToken */)) { + node.isExportEquals = true; + } + else { + parseExpected(80 /* DefaultKeyword */); + } + node.expression = parseAssignmentExpressionOrHigher(); + parseSemicolon(); + return finishNode(node); + } + function setExternalModuleIndicator(sourceFile) { + // Try to use the first top-level import/export when available, then + // fall back to looking for an 'import.meta' somewhere in the tree if necessary. + sourceFile.externalModuleIndicator = + ts.forEach(sourceFile.statements, isAnExternalModuleIndicatorNode) || + getImportMetaIfNecessary(sourceFile); + } + function isAnExternalModuleIndicatorNode(node) { + return ts.hasModifier(node, 1 /* Export */) + || node.kind === 248 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 259 /* ExternalModuleReference */ + || node.kind === 249 /* ImportDeclaration */ + || node.kind === 254 /* ExportAssignment */ + || node.kind === 255 /* ExportDeclaration */ + ? node + : undefined; + } + function getImportMetaIfNecessary(sourceFile) { + return sourceFile.flags & 1048576 /* PossiblyContainsImportMeta */ ? + walkTreeForExternalModuleIndicators(sourceFile) : + undefined; + } + function walkTreeForExternalModuleIndicators(node) { + return isImportMeta(node) ? node : forEachChild(node, walkTreeForExternalModuleIndicators); + } + function isImportMeta(node) { + return ts.isMetaProperty(node) && node.keywordToken === 92 /* ImportKeyword */ && node.name.escapedText === "meta"; + } + var ParsingContext; + (function (ParsingContext) { + ParsingContext[ParsingContext["SourceElements"] = 0] = "SourceElements"; + ParsingContext[ParsingContext["BlockStatements"] = 1] = "BlockStatements"; + ParsingContext[ParsingContext["SwitchClauses"] = 2] = "SwitchClauses"; + ParsingContext[ParsingContext["SwitchClauseStatements"] = 3] = "SwitchClauseStatements"; + ParsingContext[ParsingContext["TypeMembers"] = 4] = "TypeMembers"; + ParsingContext[ParsingContext["ClassMembers"] = 5] = "ClassMembers"; + ParsingContext[ParsingContext["EnumMembers"] = 6] = "EnumMembers"; + ParsingContext[ParsingContext["HeritageClauseElement"] = 7] = "HeritageClauseElement"; + ParsingContext[ParsingContext["VariableDeclarations"] = 8] = "VariableDeclarations"; + ParsingContext[ParsingContext["ObjectBindingElements"] = 9] = "ObjectBindingElements"; + ParsingContext[ParsingContext["ArrayBindingElements"] = 10] = "ArrayBindingElements"; + ParsingContext[ParsingContext["ArgumentExpressions"] = 11] = "ArgumentExpressions"; + ParsingContext[ParsingContext["ObjectLiteralMembers"] = 12] = "ObjectLiteralMembers"; + ParsingContext[ParsingContext["JsxAttributes"] = 13] = "JsxAttributes"; + ParsingContext[ParsingContext["JsxChildren"] = 14] = "JsxChildren"; + ParsingContext[ParsingContext["ArrayLiteralMembers"] = 15] = "ArrayLiteralMembers"; + ParsingContext[ParsingContext["Parameters"] = 16] = "Parameters"; + ParsingContext[ParsingContext["JSDocParameters"] = 17] = "JSDocParameters"; + ParsingContext[ParsingContext["RestProperties"] = 18] = "RestProperties"; + ParsingContext[ParsingContext["TypeParameters"] = 19] = "TypeParameters"; + ParsingContext[ParsingContext["TypeArguments"] = 20] = "TypeArguments"; + ParsingContext[ParsingContext["TupleElementTypes"] = 21] = "TupleElementTypes"; + ParsingContext[ParsingContext["HeritageClauses"] = 22] = "HeritageClauses"; + ParsingContext[ParsingContext["ImportOrExportSpecifiers"] = 23] = "ImportOrExportSpecifiers"; + ParsingContext[ParsingContext["Count"] = 24] = "Count"; // Number of parsing contexts + })(ParsingContext || (ParsingContext = {})); + var Tristate; + (function (Tristate) { + Tristate[Tristate["False"] = 0] = "False"; + Tristate[Tristate["True"] = 1] = "True"; + Tristate[Tristate["Unknown"] = 2] = "Unknown"; + })(Tristate || (Tristate = {})); + var JSDocParser; + (function (JSDocParser) { + function parseJSDocTypeExpressionForTests(content, start, length) { + initializeState(content, 6 /* Latest */, /*_syntaxCursor:*/ undefined, 1 /* JS */); + sourceFile = createSourceFile("file.js", 6 /* Latest */, 1 /* JS */, /*isDeclarationFile*/ false); + scanner.setText(content, start, length); + currentToken = scanner.scan(); + var jsDocTypeExpression = parseJSDocTypeExpression(); + var diagnostics = parseDiagnostics; + clearState(); + return jsDocTypeExpression ? { jsDocTypeExpression: jsDocTypeExpression, diagnostics: diagnostics } : undefined; + } + JSDocParser.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests; + // Parses out a JSDoc type expression. + function parseJSDocTypeExpression(mayOmitBraces) { + var result = createNode(283 /* JSDocTypeExpression */); + var hasBrace = (mayOmitBraces ? parseOptional : parseExpected)(18 /* OpenBraceToken */); + result.type = doInsideOfContext(2097152 /* JSDoc */, parseJSDocType); + if (!mayOmitBraces || hasBrace) { + parseExpected(19 /* CloseBraceToken */); + } + fixupParentReferences(result); + return finishNode(result); + } + JSDocParser.parseJSDocTypeExpression = parseJSDocTypeExpression; + function parseIsolatedJSDocComment(content, start, length) { + initializeState(content, 6 /* Latest */, /*_syntaxCursor:*/ undefined, 1 /* JS */); + sourceFile = { languageVariant: 0 /* Standard */, text: content }; // tslint:disable-line no-object-literal-type-assertion + var jsDoc = parseJSDocCommentWorker(start, length); + var diagnostics = parseDiagnostics; + clearState(); + return jsDoc ? { jsDoc: jsDoc, diagnostics: diagnostics } : undefined; + } + JSDocParser.parseIsolatedJSDocComment = parseIsolatedJSDocComment; + function parseJSDocComment(parent, start, length) { + var _a; + var saveToken = currentToken; + var saveParseDiagnosticsLength = parseDiagnostics.length; + var saveParseErrorBeforeNextFinishedNode = parseErrorBeforeNextFinishedNode; + var comment = parseJSDocCommentWorker(start, length); + if (comment) { + comment.parent = parent; + } + if (contextFlags & 65536 /* JavaScriptFile */) { + if (!sourceFile.jsDocDiagnostics) { + sourceFile.jsDocDiagnostics = []; + } + (_a = sourceFile.jsDocDiagnostics).push.apply(_a, parseDiagnostics); + } + currentToken = saveToken; + parseDiagnostics.length = saveParseDiagnosticsLength; + parseErrorBeforeNextFinishedNode = saveParseErrorBeforeNextFinishedNode; + return comment; + } + JSDocParser.parseJSDocComment = parseJSDocComment; + var JSDocState; + (function (JSDocState) { + JSDocState[JSDocState["BeginningOfLine"] = 0] = "BeginningOfLine"; + JSDocState[JSDocState["SawAsterisk"] = 1] = "SawAsterisk"; + JSDocState[JSDocState["SavingComments"] = 2] = "SavingComments"; + })(JSDocState || (JSDocState = {})); + var PropertyLikeParse; + (function (PropertyLikeParse) { + PropertyLikeParse[PropertyLikeParse["Property"] = 1] = "Property"; + PropertyLikeParse[PropertyLikeParse["Parameter"] = 2] = "Parameter"; + PropertyLikeParse[PropertyLikeParse["CallbackParameter"] = 4] = "CallbackParameter"; + })(PropertyLikeParse || (PropertyLikeParse = {})); + function parseJSDocCommentWorker(start, length) { + if (start === void 0) { start = 0; } + var content = sourceText; + var end = length === undefined ? content.length : start + length; + length = end - start; + ts.Debug.assert(start >= 0); + ts.Debug.assert(start <= end); + ts.Debug.assert(end <= content.length); + // Check for /** (JSDoc opening part) + if (!isJSDocLikeText(content, start)) { + return undefined; + } + var tags; + var tagsPos; + var tagsEnd; + var comments = []; + // + 3 for leading /**, - 5 in total for /** */ + return scanner.scanRange(start + 3, length - 5, function () { + // Initially we can parse out a tag. We also have seen a starting asterisk. + // This is so that /** * @type */ doesn't parse. + var state = 1 /* SawAsterisk */; + var margin; + // + 4 for leading '/** ' + var indent = start - Math.max(content.lastIndexOf("\n", start), 0) + 4; + function pushComment(text) { + if (!margin) { + margin = indent; + } + comments.push(text); + indent += text.length; + } + nextJSDocToken(); + while (parseOptionalJsdoc(5 /* WhitespaceTrivia */)) + ; + if (parseOptionalJsdoc(4 /* NewLineTrivia */)) { + state = 0 /* BeginningOfLine */; + indent = 0; + } + loop: while (true) { + switch (token()) { + case 58 /* AtToken */: + if (state === 0 /* BeginningOfLine */ || state === 1 /* SawAsterisk */) { + removeTrailingWhitespace(comments); + addTag(parseTag(indent)); + // NOTE: According to usejsdoc.org, a tag goes to end of line, except the last tag. + // Real-world comments may break this rule, so "BeginningOfLine" will not be a real line beginning + // for malformed examples like `/** @param {string} x @returns {number} the length */` + state = 0 /* BeginningOfLine */; + margin = undefined; + indent++; + } + else { + pushComment(scanner.getTokenText()); + } + break; + case 4 /* NewLineTrivia */: + comments.push(scanner.getTokenText()); + state = 0 /* BeginningOfLine */; + indent = 0; + break; + case 40 /* AsteriskToken */: + var asterisk = scanner.getTokenText(); + if (state === 1 /* SawAsterisk */ || state === 2 /* SavingComments */) { + // If we've already seen an asterisk, then we can no longer parse a tag on this line + state = 2 /* SavingComments */; + pushComment(asterisk); + } + else { + // Ignore the first asterisk on a line + state = 1 /* SawAsterisk */; + indent += asterisk.length; + } + break; + case 5 /* WhitespaceTrivia */: + // only collect whitespace if we're already saving comments or have just crossed the comment indent margin + var whitespace = scanner.getTokenText(); + if (state === 2 /* SavingComments */) { + comments.push(whitespace); + } + else if (margin !== undefined && indent + whitespace.length > margin) { + comments.push(whitespace.slice(margin - indent - 1)); + } + indent += whitespace.length; + break; + case 1 /* EndOfFileToken */: + break loop; + default: + // Anything else is doc comment text. We just save it. Because it + // wasn't a tag, we can no longer parse a tag on this line until we hit the next + // line break. + state = 2 /* SavingComments */; + pushComment(scanner.getTokenText()); + break; + } + nextJSDocToken(); + } + removeLeadingNewlines(comments); + removeTrailingWhitespace(comments); + return createJSDocComment(); + }); + function removeLeadingNewlines(comments) { + while (comments.length && (comments[0] === "\n" || comments[0] === "\r")) { + comments.shift(); + } + } + function removeTrailingWhitespace(comments) { + while (comments.length && comments[comments.length - 1].trim() === "") { + comments.pop(); + } + } + function createJSDocComment() { + var result = createNode(291 /* JSDocComment */, start); + result.tags = tags && createNodeArray(tags, tagsPos, tagsEnd); + result.comment = comments.length ? comments.join("") : undefined; + return finishNode(result, end); + } + function isNextNonwhitespaceTokenEndOfFile() { + // We must use infinite lookahead, as there could be any number of newlines :( + while (true) { + nextJSDocToken(); + if (token() === 1 /* EndOfFileToken */) { + return true; + } + if (!(token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */)) { + return false; + } + } + } + function skipWhitespace() { + if (token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) { + if (lookAhead(isNextNonwhitespaceTokenEndOfFile)) { + return; // Don't skip whitespace prior to EoF (or end of comment) - that shouldn't be included in any node's range + } + } + while (token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) { + nextJSDocToken(); + } + } + function skipWhitespaceOrAsterisk() { + if (token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) { + if (lookAhead(isNextNonwhitespaceTokenEndOfFile)) { + return; // Don't skip whitespace prior to EoF (or end of comment) - that shouldn't be included in any node's range + } + } + var precedingLineBreak = scanner.hasPrecedingLineBreak(); + while ((precedingLineBreak && token() === 40 /* AsteriskToken */) || token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) { + if (token() === 4 /* NewLineTrivia */) { + precedingLineBreak = true; + } + else if (token() === 40 /* AsteriskToken */) { + precedingLineBreak = false; + } + nextJSDocToken(); + } + } + function parseTag(indent) { + ts.Debug.assert(token() === 58 /* AtToken */); + var start = scanner.getTokenPos(); + nextJSDocToken(); + var tagName = parseJSDocIdentifierName(/*message*/ undefined); + skipWhitespaceOrAsterisk(); + var tag; + switch (tagName.escapedText) { + case "augments": + case "extends": + tag = parseAugmentsTag(start, tagName); + break; + case "class": + case "constructor": + tag = parseClassTag(start, tagName); + break; + case "this": + tag = parseThisTag(start, tagName); + break; + case "enum": + tag = parseEnumTag(start, tagName); + break; + case "arg": + case "argument": + case "param": + return parseParameterOrPropertyTag(start, tagName, 2 /* Parameter */, indent); + case "return": + case "returns": + tag = parseReturnTag(start, tagName); + break; + case "template": + tag = parseTemplateTag(start, tagName); + break; + case "type": + tag = parseTypeTag(start, tagName); + break; + case "typedef": + tag = parseTypedefTag(start, tagName, indent); + break; + case "callback": + tag = parseCallbackTag(start, tagName, indent); + break; + default: + tag = parseUnknownTag(start, tagName); + break; + } + if (!tag.comment) { + // some tags, like typedef and callback, have already parsed their comments earlier + tag.comment = parseTagComments(indent + tag.end - tag.pos); + } + return tag; + } + function parseTagComments(indent) { + var comments = []; + var state = 0 /* BeginningOfLine */; + var margin; + function pushComment(text) { + if (!margin) { + margin = indent; + } + comments.push(text); + indent += text.length; + } + var tok = token(); + loop: while (true) { + switch (tok) { + case 4 /* NewLineTrivia */: + if (state >= 1 /* SawAsterisk */) { + state = 0 /* BeginningOfLine */; + comments.push(scanner.getTokenText()); + } + indent = 0; + break; + case 58 /* AtToken */: + scanner.setTextPos(scanner.getTextPos() - 1); + // falls through + case 1 /* EndOfFileToken */: + // Done + break loop; + case 5 /* WhitespaceTrivia */: + if (state === 2 /* SavingComments */) { + pushComment(scanner.getTokenText()); + } + else { + var whitespace = scanner.getTokenText(); + // if the whitespace crosses the margin, take only the whitespace that passes the margin + if (margin !== undefined && indent + whitespace.length > margin) { + comments.push(whitespace.slice(margin - indent - 1)); + } + indent += whitespace.length; + } + break; + case 18 /* OpenBraceToken */: + state = 2 /* SavingComments */; + if (lookAhead(function () { return nextJSDocToken() === 58 /* AtToken */ && ts.tokenIsIdentifierOrKeyword(nextJSDocToken()) && scanner.getTokenText() === "link"; })) { + pushComment(scanner.getTokenText()); + nextJSDocToken(); + pushComment(scanner.getTokenText()); + nextJSDocToken(); + } + pushComment(scanner.getTokenText()); + break; + case 40 /* AsteriskToken */: + if (state === 0 /* BeginningOfLine */) { + // leading asterisks start recording on the *next* (non-whitespace) token + state = 1 /* SawAsterisk */; + indent += 1; + break; + } + // record the * as a comment + // falls through + default: + state = 2 /* SavingComments */; // leading identifiers start recording as well + pushComment(scanner.getTokenText()); + break; + } + tok = nextJSDocToken(); + } + removeLeadingNewlines(comments); + removeTrailingWhitespace(comments); + return comments.length === 0 ? undefined : comments.join(""); + } + function parseUnknownTag(start, tagName) { + var result = createNode(294 /* JSDocTag */, start); + result.tagName = tagName; + return finishNode(result); + } + function addTag(tag) { + if (!tag) { + return; + } + if (!tags) { + tags = [tag]; + tagsPos = tag.pos; + } + else { + tags.push(tag); + } + tagsEnd = tag.end; + } + function tryParseTypeExpression() { + skipWhitespaceOrAsterisk(); + return token() === 18 /* OpenBraceToken */ ? parseJSDocTypeExpression() : undefined; + } + function parseBracketNameInPropertyAndParamTag() { + if (token() === 14 /* NoSubstitutionTemplateLiteral */) { + // a markdown-quoted name: `arg` is not legal jsdoc, but occurs in the wild + return { name: createIdentifier(/*isIdentifier*/ true), isBracketed: false }; + } + // Looking for something like '[foo]', 'foo', '[foo.bar]' or 'foo.bar' + var isBracketed = parseOptional(22 /* OpenBracketToken */); + var name = parseJSDocEntityName(); + if (isBracketed) { + skipWhitespace(); + // May have an optional default, e.g. '[foo = 42]' + if (parseOptionalToken(59 /* EqualsToken */)) { + parseExpression(); + } + parseExpected(23 /* CloseBracketToken */); + } + return { name: name, isBracketed: isBracketed }; + } + function isObjectOrObjectArrayTypeReference(node) { + switch (node.kind) { + case 136 /* ObjectKeyword */: + return true; + case 169 /* ArrayType */: + return isObjectOrObjectArrayTypeReference(node.elementType); + default: + return ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) && node.typeName.escapedText === "Object"; + } + } + function parseParameterOrPropertyTag(start, tagName, target, indent) { + var typeExpression = tryParseTypeExpression(); + var isNameFirst = !typeExpression; + skipWhitespaceOrAsterisk(); + var _a = parseBracketNameInPropertyAndParamTag(), name = _a.name, isBracketed = _a.isBracketed; + skipWhitespace(); + if (isNameFirst) { + typeExpression = tryParseTypeExpression(); + } + var result = target === 1 /* Property */ ? + createNode(305 /* JSDocPropertyTag */, start) : + createNode(299 /* JSDocParameterTag */, start); + var comment = parseTagComments(indent + scanner.getStartPos() - start); + var nestedTypeLiteral = target !== 4 /* CallbackParameter */ && parseNestedTypeLiteral(typeExpression, name, target, indent); + if (nestedTypeLiteral) { + typeExpression = nestedTypeLiteral; + isNameFirst = true; + } + result.tagName = tagName; + result.typeExpression = typeExpression; + result.name = name; + result.isNameFirst = isNameFirst; + result.isBracketed = isBracketed; + result.comment = comment; + return finishNode(result); + } + function parseNestedTypeLiteral(typeExpression, name, target, indent) { + if (typeExpression && isObjectOrObjectArrayTypeReference(typeExpression.type)) { + var typeLiteralExpression = createNode(283 /* JSDocTypeExpression */, scanner.getTokenPos()); + var child = void 0; + var jsdocTypeLiteral = void 0; + var start_2 = scanner.getStartPos(); + var children = void 0; + while (child = tryParse(function () { return parseChildParameterOrPropertyTag(target, indent, name); })) { + if (child.kind === 299 /* JSDocParameterTag */ || child.kind === 305 /* JSDocPropertyTag */) { + children = ts.append(children, child); + } + } + if (children) { + jsdocTypeLiteral = createNode(292 /* JSDocTypeLiteral */, start_2); + jsdocTypeLiteral.jsDocPropertyTags = children; + if (typeExpression.type.kind === 169 /* ArrayType */) { + jsdocTypeLiteral.isArrayType = true; + } + typeLiteralExpression.type = finishNode(jsdocTypeLiteral); + return finishNode(typeLiteralExpression); + } + } + } + function parseReturnTag(start, tagName) { + if (ts.forEach(tags, function (t) { return t.kind === 300 /* JSDocReturnTag */; })) { + parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText); + } + var result = createNode(300 /* JSDocReturnTag */, start); + result.tagName = tagName; + result.typeExpression = tryParseTypeExpression(); + return finishNode(result); + } + function parseTypeTag(start, tagName) { + if (ts.forEach(tags, function (t) { return t.kind === 302 /* JSDocTypeTag */; })) { + parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText); + } + var result = createNode(302 /* JSDocTypeTag */, start); + result.tagName = tagName; + result.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true); + return finishNode(result); + } + function parseAugmentsTag(start, tagName) { + var result = createNode(295 /* JSDocAugmentsTag */, start); + result.tagName = tagName; + result.class = parseExpressionWithTypeArgumentsForAugments(); + return finishNode(result); + } + function parseExpressionWithTypeArgumentsForAugments() { + var usedBrace = parseOptional(18 /* OpenBraceToken */); + var node = createNode(211 /* ExpressionWithTypeArguments */); + node.expression = parsePropertyAccessEntityNameExpression(); + node.typeArguments = tryParseTypeArguments(); + var res = finishNode(node); + if (usedBrace) { + parseExpected(19 /* CloseBraceToken */); + } + return res; + } + function parsePropertyAccessEntityNameExpression() { + var node = parseJSDocIdentifierName(); + while (parseOptional(24 /* DotToken */)) { + var prop = createNode(189 /* PropertyAccessExpression */, node.pos); + prop.expression = node; + prop.name = parseJSDocIdentifierName(); + node = finishNode(prop); + } + return node; + } + function parseClassTag(start, tagName) { + var tag = createNode(296 /* JSDocClassTag */, start); + tag.tagName = tagName; + return finishNode(tag); + } + function parseThisTag(start, tagName) { + var tag = createNode(301 /* JSDocThisTag */, start); + tag.tagName = tagName; + tag.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true); + skipWhitespace(); + return finishNode(tag); + } + function parseEnumTag(start, tagName) { + var tag = createNode(298 /* JSDocEnumTag */, start); + tag.tagName = tagName; + tag.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true); + skipWhitespace(); + return finishNode(tag); + } + function parseTypedefTag(start, tagName, indent) { + var typeExpression = tryParseTypeExpression(); + skipWhitespaceOrAsterisk(); + var typedefTag = createNode(304 /* JSDocTypedefTag */, start); + typedefTag.tagName = tagName; + typedefTag.fullName = parseJSDocTypeNameWithNamespace(); + typedefTag.name = getJSDocTypeAliasName(typedefTag.fullName); + skipWhitespace(); + typedefTag.comment = parseTagComments(indent); + typedefTag.typeExpression = typeExpression; + var end; + if (!typeExpression || isObjectOrObjectArrayTypeReference(typeExpression.type)) { + var child = void 0; + var jsdocTypeLiteral = void 0; + var childTypeTag = void 0; + while (child = tryParse(function () { return parseChildPropertyTag(indent); })) { + if (!jsdocTypeLiteral) { + jsdocTypeLiteral = createNode(292 /* JSDocTypeLiteral */, start); + } + if (child.kind === 302 /* JSDocTypeTag */) { + if (childTypeTag) { + break; + } + else { + childTypeTag = child; + } + } + else { + jsdocTypeLiteral.jsDocPropertyTags = ts.append(jsdocTypeLiteral.jsDocPropertyTags, child); + } + } + if (jsdocTypeLiteral) { + if (typeExpression && typeExpression.type.kind === 169 /* ArrayType */) { + jsdocTypeLiteral.isArrayType = true; + } + typedefTag.typeExpression = childTypeTag && childTypeTag.typeExpression && !isObjectOrObjectArrayTypeReference(childTypeTag.typeExpression.type) ? + childTypeTag.typeExpression : + finishNode(jsdocTypeLiteral); + end = typedefTag.typeExpression.end; + } + } + // Only include the characters between the name end and the next token if a comment was actually parsed out - otherwise it's just whitespace + return finishNode(typedefTag, end || typedefTag.comment !== undefined ? scanner.getStartPos() : (typedefTag.fullName || typedefTag.typeExpression || typedefTag.tagName).end); + } + function parseJSDocTypeNameWithNamespace(nested) { + var pos = scanner.getTokenPos(); + if (!ts.tokenIsIdentifierOrKeyword(token())) { + return undefined; + } + var typeNameOrNamespaceName = parseJSDocIdentifierName(); + if (parseOptional(24 /* DotToken */)) { + var jsDocNamespaceNode = createNode(244 /* ModuleDeclaration */, pos); + if (nested) { + jsDocNamespaceNode.flags |= 4 /* NestedNamespace */; + } + jsDocNamespaceNode.name = typeNameOrNamespaceName; + jsDocNamespaceNode.body = parseJSDocTypeNameWithNamespace(/*nested*/ true); + return finishNode(jsDocNamespaceNode); + } + if (nested) { + typeNameOrNamespaceName.isInJSDocNamespace = true; + } + return typeNameOrNamespaceName; + } + function parseCallbackTag(start, tagName, indent) { + var callbackTag = createNode(297 /* JSDocCallbackTag */, start); + callbackTag.tagName = tagName; + callbackTag.fullName = parseJSDocTypeNameWithNamespace(); + callbackTag.name = getJSDocTypeAliasName(callbackTag.fullName); + skipWhitespace(); + callbackTag.comment = parseTagComments(indent); + var child; + var jsdocSignature = createNode(293 /* JSDocSignature */, start); + jsdocSignature.parameters = []; + while (child = tryParse(function () { return parseChildParameterOrPropertyTag(4 /* CallbackParameter */, indent); })) { + jsdocSignature.parameters = ts.append(jsdocSignature.parameters, child); + } + var returnTag = tryParse(function () { + if (parseOptionalJsdoc(58 /* AtToken */)) { + var tag = parseTag(indent); + if (tag && tag.kind === 300 /* JSDocReturnTag */) { + return tag; + } + } + }); + if (returnTag) { + jsdocSignature.type = returnTag; + } + callbackTag.typeExpression = finishNode(jsdocSignature); + return finishNode(callbackTag); + } + function getJSDocTypeAliasName(fullName) { + if (fullName) { + var rightNode = fullName; + while (true) { + if (ts.isIdentifier(rightNode) || !rightNode.body) { + return ts.isIdentifier(rightNode) ? rightNode : rightNode.name; + } + rightNode = rightNode.body; + } + } + } + function escapedTextsEqual(a, b) { + while (!ts.isIdentifier(a) || !ts.isIdentifier(b)) { + if (!ts.isIdentifier(a) && !ts.isIdentifier(b) && a.right.escapedText === b.right.escapedText) { + a = a.left; + b = b.left; + } + else { + return false; + } + } + return a.escapedText === b.escapedText; + } + function parseChildPropertyTag(indent) { + return parseChildParameterOrPropertyTag(1 /* Property */, indent); + } + function parseChildParameterOrPropertyTag(target, indent, name) { + var canParseTag = true; + var seenAsterisk = false; + while (true) { + switch (nextJSDocToken()) { + case 58 /* AtToken */: + if (canParseTag) { + var child = tryParseChildTag(target, indent); + if (child && (child.kind === 299 /* JSDocParameterTag */ || child.kind === 305 /* JSDocPropertyTag */) && + target !== 4 /* CallbackParameter */ && + name && (ts.isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) { + return false; + } + return child; + } + seenAsterisk = false; + break; + case 4 /* NewLineTrivia */: + canParseTag = true; + seenAsterisk = false; + break; + case 40 /* AsteriskToken */: + if (seenAsterisk) { + canParseTag = false; + } + seenAsterisk = true; + break; + case 72 /* Identifier */: + canParseTag = false; + break; + case 1 /* EndOfFileToken */: + return false; + } + } + } + function tryParseChildTag(target, indent) { + ts.Debug.assert(token() === 58 /* AtToken */); + var start = scanner.getStartPos(); + nextJSDocToken(); + var tagName = parseJSDocIdentifierName(); + skipWhitespace(); + var t; + switch (tagName.escapedText) { + case "type": + return target === 1 /* Property */ && parseTypeTag(start, tagName); + case "prop": + case "property": + t = 1 /* Property */; + break; + case "arg": + case "argument": + case "param": + t = 2 /* Parameter */ | 4 /* CallbackParameter */; + break; + default: + return false; + } + if (!(target & t)) { + return false; + } + return parseParameterOrPropertyTag(start, tagName, target, indent); + } + function parseTemplateTag(start, tagName) { + // the template tag looks like '@template {Constraint} T,U,V' + var constraint; + if (token() === 18 /* OpenBraceToken */) { + constraint = parseJSDocTypeExpression(); + } + var typeParameters = []; + var typeParametersPos = getNodePos(); + do { + skipWhitespace(); + var typeParameter = createNode(150 /* TypeParameter */); + typeParameter.name = parseJSDocIdentifierName(ts.Diagnostics.Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces); + finishNode(typeParameter); + skipWhitespace(); + typeParameters.push(typeParameter); + } while (parseOptionalJsdoc(27 /* CommaToken */)); + var result = createNode(303 /* JSDocTemplateTag */, start); + result.tagName = tagName; + result.constraint = constraint; + result.typeParameters = createNodeArray(typeParameters, typeParametersPos); + finishNode(result); + return result; + } + function nextJSDocToken() { + return currentToken = scanner.scanJSDocToken(); + } + function parseOptionalJsdoc(t) { + if (token() === t) { + nextJSDocToken(); + return true; + } + return false; + } + function parseJSDocEntityName() { + var entity = parseJSDocIdentifierName(); + if (parseOptional(22 /* OpenBracketToken */)) { + parseExpected(23 /* CloseBracketToken */); + // Note that y[] is accepted as an entity name, but the postfix brackets are not saved for checking. + // Technically usejsdoc.org requires them for specifying a property of a type equivalent to Array<{ x: ...}> + // but it's not worth it to enforce that restriction. + } + while (parseOptional(24 /* DotToken */)) { + var name = parseJSDocIdentifierName(); + if (parseOptional(22 /* OpenBracketToken */)) { + parseExpected(23 /* CloseBracketToken */); + } + entity = createQualifiedName(entity, name); + } + return entity; + } + function parseJSDocIdentifierName(message) { + if (!ts.tokenIsIdentifierOrKeyword(token())) { + return createMissingNode(72 /* Identifier */, /*reportAtCurrentPosition*/ !message, message || ts.Diagnostics.Identifier_expected); + } + var pos = scanner.getTokenPos(); + var end = scanner.getTextPos(); + var result = createNode(72 /* Identifier */, pos); + result.escapedText = ts.escapeLeadingUnderscores(scanner.getTokenText()); + finishNode(result, end); + nextJSDocToken(); + return result; + } + } + JSDocParser.parseJSDocCommentWorker = parseJSDocCommentWorker; + })(JSDocParser = Parser.JSDocParser || (Parser.JSDocParser = {})); + })(Parser || (Parser = {})); + var IncrementalParser; + (function (IncrementalParser) { + function updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks) { + aggressiveChecks = aggressiveChecks || ts.Debug.shouldAssert(2 /* Aggressive */); + checkChangeRange(sourceFile, newText, textChangeRange, aggressiveChecks); + if (ts.textChangeRangeIsUnchanged(textChangeRange)) { + // if the text didn't change, then we can just return our current source file as-is. + return sourceFile; + } + if (sourceFile.statements.length === 0) { + // If we don't have any statements in the current source file, then there's no real + // way to incrementally parse. So just do a full parse instead. + return Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, /*syntaxCursor*/ undefined, /*setParentNodes*/ true, sourceFile.scriptKind); + } + // Make sure we're not trying to incrementally update a source file more than once. Once + // we do an update the original source file is considered unusable from that point onwards. + // + // This is because we do incremental parsing in-place. i.e. we take nodes from the old + // tree and give them new positions and parents. From that point on, trusting the old + // tree at all is not possible as far too much of it may violate invariants. + var incrementalSourceFile = sourceFile; + ts.Debug.assert(!incrementalSourceFile.hasBeenIncrementallyParsed); + incrementalSourceFile.hasBeenIncrementallyParsed = true; + var oldText = sourceFile.text; + var syntaxCursor = createSyntaxCursor(sourceFile); + // Make the actual change larger so that we know to reparse anything whose lookahead + // might have intersected the change. + var changeRange = extendToAffectedRange(sourceFile, textChangeRange); + checkChangeRange(sourceFile, newText, changeRange, aggressiveChecks); + // Ensure that extending the affected range only moved the start of the change range + // earlier in the file. + ts.Debug.assert(changeRange.span.start <= textChangeRange.span.start); + ts.Debug.assert(ts.textSpanEnd(changeRange.span) === ts.textSpanEnd(textChangeRange.span)); + ts.Debug.assert(ts.textSpanEnd(ts.textChangeRangeNewSpan(changeRange)) === ts.textSpanEnd(ts.textChangeRangeNewSpan(textChangeRange))); + // The is the amount the nodes after the edit range need to be adjusted. It can be + // positive (if the edit added characters), negative (if the edit deleted characters) + // or zero (if this was a pure overwrite with nothing added/removed). + var delta = ts.textChangeRangeNewSpan(changeRange).length - changeRange.span.length; + // If we added or removed characters during the edit, then we need to go and adjust all + // the nodes after the edit. Those nodes may move forward (if we inserted chars) or they + // may move backward (if we deleted chars). + // + // Doing this helps us out in two ways. First, it means that any nodes/tokens we want + // to reuse are already at the appropriate position in the new text. That way when we + // reuse them, we don't have to figure out if they need to be adjusted. Second, it makes + // it very easy to determine if we can reuse a node. If the node's position is at where + // we are in the text, then we can reuse it. Otherwise we can't. If the node's position + // is ahead of us, then we'll need to rescan tokens. If the node's position is behind + // us, then we'll need to skip it or crumble it as appropriate + // + // We will also adjust the positions of nodes that intersect the change range as well. + // By doing this, we ensure that all the positions in the old tree are consistent, not + // just the positions of nodes entirely before/after the change range. By being + // consistent, we can then easily map from positions to nodes in the old tree easily. + // + // Also, mark any syntax elements that intersect the changed span. We know, up front, + // that we cannot reuse these elements. + updateTokenPositionsAndMarkElements(incrementalSourceFile, changeRange.span.start, ts.textSpanEnd(changeRange.span), ts.textSpanEnd(ts.textChangeRangeNewSpan(changeRange)), delta, oldText, newText, aggressiveChecks); + // Now that we've set up our internal incremental state just proceed and parse the + // source file in the normal fashion. When possible the parser will retrieve and + // reuse nodes from the old tree. + // + // Note: passing in 'true' for setNodeParents is very important. When incrementally + // parsing, we will be reusing nodes from the old tree, and placing it into new + // parents. If we don't set the parents now, we'll end up with an observably + // inconsistent tree. Setting the parents on the new tree should be very fast. We + // will immediately bail out of walking any subtrees when we can see that their parents + // are already correct. + var result = Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, syntaxCursor, /*setParentNodes*/ true, sourceFile.scriptKind); + return result; + } + IncrementalParser.updateSourceFile = updateSourceFile; + function moveElementEntirelyPastChangeRange(element, isArray, delta, oldText, newText, aggressiveChecks) { + if (isArray) { + visitArray(element); + } + else { + visitNode(element); + } + return; + function visitNode(node) { + var text = ""; + if (aggressiveChecks && shouldCheckNode(node)) { + text = oldText.substring(node.pos, node.end); + } + // Ditch any existing LS children we may have created. This way we can avoid + // moving them forward. + if (node._children) { + node._children = undefined; + } + node.pos += delta; + node.end += delta; + if (aggressiveChecks && shouldCheckNode(node)) { + ts.Debug.assert(text === newText.substring(node.pos, node.end)); + } + forEachChild(node, visitNode, visitArray); + if (ts.hasJSDocNodes(node)) { + for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { + var jsDocComment = _a[_i]; + visitNode(jsDocComment); + } + } + checkNodePositions(node, aggressiveChecks); + } + function visitArray(array) { + array._children = undefined; + array.pos += delta; + array.end += delta; + for (var _i = 0, array_8 = array; _i < array_8.length; _i++) { + var node = array_8[_i]; + visitNode(node); + } + } + } + function shouldCheckNode(node) { + switch (node.kind) { + case 10 /* StringLiteral */: + case 8 /* NumericLiteral */: + case 72 /* Identifier */: + return true; + } + return false; + } + function adjustIntersectingElement(element, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta) { + ts.Debug.assert(element.end >= changeStart, "Adjusting an element that was entirely before the change range"); + ts.Debug.assert(element.pos <= changeRangeOldEnd, "Adjusting an element that was entirely after the change range"); + ts.Debug.assert(element.pos <= element.end); + // We have an element that intersects the change range in some way. It may have its + // start, or its end (or both) in the changed range. We want to adjust any part + // that intersects such that the final tree is in a consistent state. i.e. all + // children have spans within the span of their parent, and all siblings are ordered + // properly. + // We may need to update both the 'pos' and the 'end' of the element. + // If the 'pos' is before the start of the change, then we don't need to touch it. + // If it isn't, then the 'pos' must be inside the change. How we update it will + // depend if delta is positive or negative. If delta is positive then we have + // something like: + // + // -------------------AAA----------------- + // -------------------BBBCCCCCCC----------------- + // + // In this case, we consider any node that started in the change range to still be + // starting at the same position. + // + // however, if the delta is negative, then we instead have something like this: + // + // -------------------XXXYYYYYYY----------------- + // -------------------ZZZ----------------- + // + // In this case, any element that started in the 'X' range will keep its position. + // However any element that started after that will have their pos adjusted to be + // at the end of the new range. i.e. any node that started in the 'Y' range will + // be adjusted to have their start at the end of the 'Z' range. + // + // The element will keep its position if possible. Or Move backward to the new-end + // if it's in the 'Y' range. + element.pos = Math.min(element.pos, changeRangeNewEnd); + // If the 'end' is after the change range, then we always adjust it by the delta + // amount. However, if the end is in the change range, then how we adjust it + // will depend on if delta is positive or negative. If delta is positive then we + // have something like: + // + // -------------------AAA----------------- + // -------------------BBBCCCCCCC----------------- + // + // In this case, we consider any node that ended inside the change range to keep its + // end position. + // + // however, if the delta is negative, then we instead have something like this: + // + // -------------------XXXYYYYYYY----------------- + // -------------------ZZZ----------------- + // + // In this case, any element that ended in the 'X' range will keep its position. + // However any element that ended after that will have their pos adjusted to be + // at the end of the new range. i.e. any node that ended in the 'Y' range will + // be adjusted to have their end at the end of the 'Z' range. + if (element.end >= changeRangeOldEnd) { + // Element ends after the change range. Always adjust the end pos. + element.end += delta; + } + else { + // Element ends in the change range. The element will keep its position if + // possible. Or Move backward to the new-end if it's in the 'Y' range. + element.end = Math.min(element.end, changeRangeNewEnd); + } + ts.Debug.assert(element.pos <= element.end); + if (element.parent) { + ts.Debug.assert(element.pos >= element.parent.pos); + ts.Debug.assert(element.end <= element.parent.end); + } + } + function checkNodePositions(node, aggressiveChecks) { + if (aggressiveChecks) { + var pos_2 = node.pos; + var visitNode_1 = function (child) { + ts.Debug.assert(child.pos >= pos_2); + pos_2 = child.end; + }; + if (ts.hasJSDocNodes(node)) { + for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { + var jsDocComment = _a[_i]; + visitNode_1(jsDocComment); + } + } + forEachChild(node, visitNode_1); + ts.Debug.assert(pos_2 <= node.end); + } + } + function updateTokenPositionsAndMarkElements(sourceFile, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta, oldText, newText, aggressiveChecks) { + visitNode(sourceFile); + return; + function visitNode(child) { + ts.Debug.assert(child.pos <= child.end); + if (child.pos > changeRangeOldEnd) { + // Node is entirely past the change range. We need to move both its pos and + // end, forward or backward appropriately. + moveElementEntirelyPastChangeRange(child, /*isArray*/ false, delta, oldText, newText, aggressiveChecks); + return; + } + // Check if the element intersects the change range. If it does, then it is not + // reusable. Also, we'll need to recurse to see what constituent portions we may + // be able to use. + var fullEnd = child.end; + if (fullEnd >= changeStart) { + child.intersectsChange = true; + child._children = undefined; + // Adjust the pos or end (or both) of the intersecting element accordingly. + adjustIntersectingElement(child, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta); + forEachChild(child, visitNode, visitArray); + if (ts.hasJSDocNodes(child)) { + for (var _i = 0, _a = child.jsDoc; _i < _a.length; _i++) { + var jsDocComment = _a[_i]; + visitNode(jsDocComment); + } + } + checkNodePositions(child, aggressiveChecks); + return; + } + // Otherwise, the node is entirely before the change range. No need to do anything with it. + ts.Debug.assert(fullEnd < changeStart); + } + function visitArray(array) { + ts.Debug.assert(array.pos <= array.end); + if (array.pos > changeRangeOldEnd) { + // Array is entirely after the change range. We need to move it, and move any of + // its children. + moveElementEntirelyPastChangeRange(array, /*isArray*/ true, delta, oldText, newText, aggressiveChecks); + return; + } + // Check if the element intersects the change range. If it does, then it is not + // reusable. Also, we'll need to recurse to see what constituent portions we may + // be able to use. + var fullEnd = array.end; + if (fullEnd >= changeStart) { + array.intersectsChange = true; + array._children = undefined; + // Adjust the pos or end (or both) of the intersecting array accordingly. + adjustIntersectingElement(array, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta); + for (var _i = 0, array_9 = array; _i < array_9.length; _i++) { + var node = array_9[_i]; + visitNode(node); + } + return; + } + // Otherwise, the array is entirely before the change range. No need to do anything with it. + ts.Debug.assert(fullEnd < changeStart); + } + } + function extendToAffectedRange(sourceFile, changeRange) { + // Consider the following code: + // void foo() { /; } + // + // If the text changes with an insertion of / just before the semicolon then we end up with: + // void foo() { //; } + // + // If we were to just use the changeRange a is, then we would not rescan the { token + // (as it does not intersect the actual original change range). Because an edit may + // change the token touching it, we actually need to look back *at least* one token so + // that the prior token sees that change. + var maxLookahead = 1; + var start = changeRange.span.start; + // the first iteration aligns us with the change start. subsequent iteration move us to + // the left by maxLookahead tokens. We only need to do this as long as we're not at the + // start of the tree. + for (var i = 0; start > 0 && i <= maxLookahead; i++) { + var nearestNode = findNearestNodeStartingBeforeOrAtPosition(sourceFile, start); + ts.Debug.assert(nearestNode.pos <= start); + var position = nearestNode.pos; + start = Math.max(0, position - 1); + } + var finalSpan = ts.createTextSpanFromBounds(start, ts.textSpanEnd(changeRange.span)); + var finalLength = changeRange.newLength + (changeRange.span.start - start); + return ts.createTextChangeRange(finalSpan, finalLength); + } + function findNearestNodeStartingBeforeOrAtPosition(sourceFile, position) { + var bestResult = sourceFile; + var lastNodeEntirelyBeforePosition; + forEachChild(sourceFile, visit); + if (lastNodeEntirelyBeforePosition) { + var lastChildOfLastEntireNodeBeforePosition = getLastDescendant(lastNodeEntirelyBeforePosition); + if (lastChildOfLastEntireNodeBeforePosition.pos > bestResult.pos) { + bestResult = lastChildOfLastEntireNodeBeforePosition; + } + } + return bestResult; + function getLastDescendant(node) { + while (true) { + var lastChild = ts.getLastChild(node); + if (lastChild) { + node = lastChild; + } + else { + return node; + } + } + } + function visit(child) { + if (ts.nodeIsMissing(child)) { + // Missing nodes are effectively invisible to us. We never even consider them + // When trying to find the nearest node before us. + return; + } + // If the child intersects this position, then this node is currently the nearest + // node that starts before the position. + if (child.pos <= position) { + if (child.pos >= bestResult.pos) { + // This node starts before the position, and is closer to the position than + // the previous best node we found. It is now the new best node. + bestResult = child; + } + // Now, the node may overlap the position, or it may end entirely before the + // position. If it overlaps with the position, then either it, or one of its + // children must be the nearest node before the position. So we can just + // recurse into this child to see if we can find something better. + if (position < child.end) { + // The nearest node is either this child, or one of the children inside + // of it. We've already marked this child as the best so far. Recurse + // in case one of the children is better. + forEachChild(child, visit); + // Once we look at the children of this node, then there's no need to + // continue any further. + return true; + } + else { + ts.Debug.assert(child.end <= position); + // The child ends entirely before this position. Say you have the following + // (where $ is the position) + // + // ? $ : <...> <...> + // + // We would want to find the nearest preceding node in "complex expr 2". + // To support that, we keep track of this node, and once we're done searching + // for a best node, we recurse down this node to see if we can find a good + // result in it. + // + // This approach allows us to quickly skip over nodes that are entirely + // before the position, while still allowing us to find any nodes in the + // last one that might be what we want. + lastNodeEntirelyBeforePosition = child; + } + } + else { + ts.Debug.assert(child.pos > position); + // We're now at a node that is entirely past the position we're searching for. + // This node (and all following nodes) could never contribute to the result, + // so just skip them by returning 'true' here. + return true; + } + } + } + function checkChangeRange(sourceFile, newText, textChangeRange, aggressiveChecks) { + var oldText = sourceFile.text; + if (textChangeRange) { + ts.Debug.assert((oldText.length - textChangeRange.span.length + textChangeRange.newLength) === newText.length); + if (aggressiveChecks || ts.Debug.shouldAssert(3 /* VeryAggressive */)) { + var oldTextPrefix = oldText.substr(0, textChangeRange.span.start); + var newTextPrefix = newText.substr(0, textChangeRange.span.start); + ts.Debug.assert(oldTextPrefix === newTextPrefix); + var oldTextSuffix = oldText.substring(ts.textSpanEnd(textChangeRange.span), oldText.length); + var newTextSuffix = newText.substring(ts.textSpanEnd(ts.textChangeRangeNewSpan(textChangeRange)), newText.length); + ts.Debug.assert(oldTextSuffix === newTextSuffix); + } + } + } + function createSyntaxCursor(sourceFile) { + var currentArray = sourceFile.statements; + var currentArrayIndex = 0; + ts.Debug.assert(currentArrayIndex < currentArray.length); + var current = currentArray[currentArrayIndex]; + var lastQueriedPosition = -1 /* Value */; + return { + currentNode: function (position) { + // Only compute the current node if the position is different than the last time + // we were asked. The parser commonly asks for the node at the same position + // twice. Once to know if can read an appropriate list element at a certain point, + // and then to actually read and consume the node. + if (position !== lastQueriedPosition) { + // Much of the time the parser will need the very next node in the array that + // we just returned a node from.So just simply check for that case and move + // forward in the array instead of searching for the node again. + if (current && current.end === position && currentArrayIndex < (currentArray.length - 1)) { + currentArrayIndex++; + current = currentArray[currentArrayIndex]; + } + // If we don't have a node, or the node we have isn't in the right position, + // then try to find a viable node at the position requested. + if (!current || current.pos !== position) { + findHighestListElementThatStartsAtPosition(position); + } + } + // Cache this query so that we don't do any extra work if the parser calls back + // into us. Note: this is very common as the parser will make pairs of calls like + // 'isListElement -> parseListElement'. If we were unable to find a node when + // called with 'isListElement', we don't want to redo the work when parseListElement + // is called immediately after. + lastQueriedPosition = position; + // Either we don'd have a node, or we have a node at the position being asked for. + ts.Debug.assert(!current || current.pos === position); + return current; + } + }; + // Finds the highest element in the tree we can find that starts at the provided position. + // The element must be a direct child of some node list in the tree. This way after we + // return it, we can easily return its next sibling in the list. + function findHighestListElementThatStartsAtPosition(position) { + // Clear out any cached state about the last node we found. + currentArray = undefined; + currentArrayIndex = -1 /* Value */; + current = undefined; + // Recurse into the source file to find the highest node at this position. + forEachChild(sourceFile, visitNode, visitArray); + return; + function visitNode(node) { + if (position >= node.pos && position < node.end) { + // Position was within this node. Keep searching deeper to find the node. + forEachChild(node, visitNode, visitArray); + // don't proceed any further in the search. + return true; + } + // position wasn't in this node, have to keep searching. + return false; + } + function visitArray(array) { + if (position >= array.pos && position < array.end) { + // position was in this array. Search through this array to see if we find a + // viable element. + for (var i = 0; i < array.length; i++) { + var child = array[i]; + if (child) { + if (child.pos === position) { + // Found the right node. We're done. + currentArray = array; + currentArrayIndex = i; + current = child; + return true; + } + else { + if (child.pos < position && position < child.end) { + // Position in somewhere within this child. Search in it and + // stop searching in this array. + forEachChild(child, visitNode, visitArray); + return true; + } + } + } + } + } + // position wasn't in this array, have to keep searching. + return false; + } + } + } + var InvalidPosition; + (function (InvalidPosition) { + InvalidPosition[InvalidPosition["Value"] = -1] = "Value"; + })(InvalidPosition || (InvalidPosition = {})); + })(IncrementalParser || (IncrementalParser = {})); + /** @internal */ + function isDeclarationFileName(fileName) { + return ts.fileExtensionIs(fileName, ".d.ts" /* Dts */); + } + ts.isDeclarationFileName = isDeclarationFileName; + /*@internal*/ + function processCommentPragmas(context, sourceText) { + var triviaScanner = ts.createScanner(context.languageVersion, /*skipTrivia*/ false, 0 /* Standard */, sourceText); + var pragmas = []; + // Keep scanning all the leading trivia in the file until we get to something that + // isn't trivia. Any single line comment will be analyzed to see if it is a + // reference comment. + while (true) { + var kind = triviaScanner.scan(); + if (!ts.isTrivia(kind)) { + break; + } + var range = { + kind: triviaScanner.getToken(), + pos: triviaScanner.getTokenPos(), + end: triviaScanner.getTextPos(), + }; + var comment = sourceText.substring(range.pos, range.end); + extractPragmas(pragmas, range, comment); + } + context.pragmas = ts.createMap(); + for (var _i = 0, pragmas_1 = pragmas; _i < pragmas_1.length; _i++) { + var pragma = pragmas_1[_i]; + if (context.pragmas.has(pragma.name)) { // TODO: GH#18217 + var currentValue = context.pragmas.get(pragma.name); + if (currentValue instanceof Array) { + currentValue.push(pragma.args); + } + else { + context.pragmas.set(pragma.name, [currentValue, pragma.args]); + } + continue; + } + context.pragmas.set(pragma.name, pragma.args); + } + } + ts.processCommentPragmas = processCommentPragmas; + /*@internal*/ + function processPragmasIntoFields(context, reportDiagnostic) { + context.checkJsDirective = undefined; + context.referencedFiles = []; + context.typeReferenceDirectives = []; + context.libReferenceDirectives = []; + context.amdDependencies = []; + context.hasNoDefaultLib = false; + context.pragmas.forEach(function (entryOrList, key) { + // TODO: The below should be strongly type-guarded and not need casts/explicit annotations, since entryOrList is related to + // key and key is constrained to a union; but it's not (see GH#21483 for at least partial fix) :( + switch (key) { + case "reference": { + var referencedFiles_1 = context.referencedFiles; + var typeReferenceDirectives_1 = context.typeReferenceDirectives; + var libReferenceDirectives_1 = context.libReferenceDirectives; + ts.forEach(ts.toArray(entryOrList), function (arg) { + // TODO: GH#18217 + if (arg.arguments["no-default-lib"]) { + context.hasNoDefaultLib = true; + } + else if (arg.arguments.types) { + typeReferenceDirectives_1.push({ pos: arg.arguments.types.pos, end: arg.arguments.types.end, fileName: arg.arguments.types.value }); + } + else if (arg.arguments.lib) { + libReferenceDirectives_1.push({ pos: arg.arguments.lib.pos, end: arg.arguments.lib.end, fileName: arg.arguments.lib.value }); + } + else if (arg.arguments.path) { + referencedFiles_1.push({ pos: arg.arguments.path.pos, end: arg.arguments.path.end, fileName: arg.arguments.path.value }); + } + else { + reportDiagnostic(arg.range.pos, arg.range.end - arg.range.pos, ts.Diagnostics.Invalid_reference_directive_syntax); + } + }); + break; + } + case "amd-dependency": { + context.amdDependencies = ts.map(ts.toArray(entryOrList), function (x) { return ({ name: x.arguments.name, path: x.arguments.path }); }); // TODO: GH#18217 + break; + } + case "amd-module": { + if (entryOrList instanceof Array) { + for (var _i = 0, entryOrList_1 = entryOrList; _i < entryOrList_1.length; _i++) { + var entry = entryOrList_1[_i]; + if (context.moduleName) { + // TODO: It's probably fine to issue this diagnostic on all instances of the pragma + reportDiagnostic(entry.range.pos, entry.range.end - entry.range.pos, ts.Diagnostics.An_AMD_module_cannot_have_multiple_name_assignments); + } + context.moduleName = entry.arguments.name; + } + } + else { + context.moduleName = entryOrList.arguments.name; + } + break; + } + case "ts-nocheck": + case "ts-check": { + // _last_ of either nocheck or check in a file is the "winner" + ts.forEach(ts.toArray(entryOrList), function (entry) { + if (!context.checkJsDirective || entry.range.pos > context.checkJsDirective.pos) { // TODO: GH#18217 + context.checkJsDirective = { + enabled: key === "ts-check", + end: entry.range.end, + pos: entry.range.pos + }; + } + }); + break; + } + case "jsx": return; // Accessed directly + default: ts.Debug.fail("Unhandled pragma kind"); // Can this be made into an assertNever in the future? + } + }); + } + ts.processPragmasIntoFields = processPragmasIntoFields; + var namedArgRegExCache = ts.createMap(); + function getNamedArgRegEx(name) { + if (namedArgRegExCache.has(name)) { + return namedArgRegExCache.get(name); + } + var result = new RegExp("(\\s" + name + "\\s*=\\s*)('|\")(.+?)\\2", "im"); + namedArgRegExCache.set(name, result); + return result; + } + var tripleSlashXMLCommentStartRegEx = /^\/\/\/\s*<(\S+)\s.*?\/>/im; + var singleLinePragmaRegEx = /^\/\/\/?\s*@(\S+)\s*(.*)\s*$/im; + function extractPragmas(pragmas, range, text) { + var tripleSlash = range.kind === 2 /* SingleLineCommentTrivia */ && tripleSlashXMLCommentStartRegEx.exec(text); + if (tripleSlash) { + var name = tripleSlash[1].toLowerCase(); // Technically unsafe cast, but we do it so the below check to make it safe typechecks + var pragma = ts.commentPragmas[name]; + if (!pragma || !(pragma.kind & 1 /* TripleSlashXML */)) { + return; + } + if (pragma.args) { + var argument = {}; + for (var _i = 0, _a = pragma.args; _i < _a.length; _i++) { + var arg = _a[_i]; + var matcher = getNamedArgRegEx(arg.name); + var matchResult = matcher.exec(text); + if (!matchResult && !arg.optional) { + return; // Missing required argument, don't parse + } + else if (matchResult) { + if (arg.captureSpan) { + var startPos = range.pos + matchResult.index + matchResult[1].length + matchResult[2].length; + argument[arg.name] = { + value: matchResult[3], + pos: startPos, + end: startPos + matchResult[3].length + }; + } + else { + argument[arg.name] = matchResult[3]; + } + } + } + pragmas.push({ name: name, args: { arguments: argument, range: range } }); + } + else { + pragmas.push({ name: name, args: { arguments: {}, range: range } }); + } + return; + } + var singleLine = range.kind === 2 /* SingleLineCommentTrivia */ && singleLinePragmaRegEx.exec(text); + if (singleLine) { + return addPragmaForMatch(pragmas, range, 2 /* SingleLine */, singleLine); + } + if (range.kind === 3 /* MultiLineCommentTrivia */) { + var multiLinePragmaRegEx = /\s*@(\S+)\s*(.*)\s*$/gim; // Defined inline since it uses the "g" flag, which keeps a persistent index (for iterating) + var multiLineMatch = void 0; + while (multiLineMatch = multiLinePragmaRegEx.exec(text)) { + addPragmaForMatch(pragmas, range, 4 /* MultiLine */, multiLineMatch); + } + } + } + function addPragmaForMatch(pragmas, range, kind, match) { + if (!match) + return; + var name = match[1].toLowerCase(); // Technically unsafe cast, but we do it so they below check to make it safe typechecks + var pragma = ts.commentPragmas[name]; + if (!pragma || !(pragma.kind & kind)) { + return; + } + var args = match[2]; // Split on spaces and match up positionally with definition + var argument = getNamedPragmaArguments(pragma, args); + if (argument === "fail") + return; // Missing required argument, fail to parse it + pragmas.push({ name: name, args: { arguments: argument, range: range } }); + return; + } + function getNamedPragmaArguments(pragma, text) { + if (!text) + return {}; + if (!pragma.args) + return {}; + var args = text.split(/\s+/); + var argMap = {}; + for (var i = 0; i < pragma.args.length; i++) { + var argument = pragma.args[i]; + if (!args[i] && !argument.optional) { + return "fail"; + } + if (argument.captureSpan) { + return ts.Debug.fail("Capture spans not yet implemented for non-xml pragmas"); + } + argMap[argument.name] = args[i]; + } + return argMap; + } + /** @internal */ + function tagNamesAreEquivalent(lhs, rhs) { + if (lhs.kind !== rhs.kind) { + return false; + } + if (lhs.kind === 72 /* Identifier */) { + return lhs.escapedText === rhs.escapedText; + } + if (lhs.kind === 100 /* ThisKeyword */) { + return true; + } + // If we are at this statement then we must have PropertyAccessExpression and because tag name in Jsx element can only + // take forms of JsxTagNameExpression which includes an identifier, "this" expression, or another propertyAccessExpression + // it is safe to case the expression property as such. See parseJsxElementName for how we parse tag name in Jsx element + return lhs.name.escapedText === rhs.name.escapedText && + tagNamesAreEquivalent(lhs.expression, rhs.expression); + } + ts.tagNamesAreEquivalent = tagNamesAreEquivalent; +})(ts || (ts = {})); +var ts; +(function (ts) { + /* @internal */ + ts.compileOnSaveCommandLineOption = { name: "compileOnSave", type: "boolean" }; + // NOTE: The order here is important to default lib ordering as entries will have the same + // order in the generated program (see `getDefaultLibPriority` in program.ts). This + // order also affects overload resolution when a type declared in one lib is + // augmented in another lib. + var libEntries = [ + // JavaScript only + ["es5", "lib.es5.d.ts"], + ["es6", "lib.es2015.d.ts"], + ["es2015", "lib.es2015.d.ts"], + ["es7", "lib.es2016.d.ts"], + ["es2016", "lib.es2016.d.ts"], + ["es2017", "lib.es2017.d.ts"], + ["es2018", "lib.es2018.d.ts"], + ["esnext", "lib.esnext.d.ts"], + // Host only + ["dom", "lib.dom.d.ts"], + ["dom.iterable", "lib.dom.iterable.d.ts"], + ["webworker", "lib.webworker.d.ts"], + ["webworker.importscripts", "lib.webworker.importscripts.d.ts"], + ["scripthost", "lib.scripthost.d.ts"], + // ES2015 Or ESNext By-feature options + ["es2015.core", "lib.es2015.core.d.ts"], + ["es2015.collection", "lib.es2015.collection.d.ts"], + ["es2015.generator", "lib.es2015.generator.d.ts"], + ["es2015.iterable", "lib.es2015.iterable.d.ts"], + ["es2015.promise", "lib.es2015.promise.d.ts"], + ["es2015.proxy", "lib.es2015.proxy.d.ts"], + ["es2015.reflect", "lib.es2015.reflect.d.ts"], + ["es2015.symbol", "lib.es2015.symbol.d.ts"], + ["es2015.symbol.wellknown", "lib.es2015.symbol.wellknown.d.ts"], + ["es2016.array.include", "lib.es2016.array.include.d.ts"], + ["es2017.object", "lib.es2017.object.d.ts"], + ["es2017.sharedmemory", "lib.es2017.sharedmemory.d.ts"], + ["es2017.string", "lib.es2017.string.d.ts"], + ["es2017.intl", "lib.es2017.intl.d.ts"], + ["es2017.typedarrays", "lib.es2017.typedarrays.d.ts"], + ["es2018.intl", "lib.es2018.intl.d.ts"], + ["es2018.promise", "lib.es2018.promise.d.ts"], + ["es2018.regexp", "lib.es2018.regexp.d.ts"], + ["esnext.array", "lib.esnext.array.d.ts"], + ["esnext.symbol", "lib.esnext.symbol.d.ts"], + ["esnext.asynciterable", "lib.esnext.asynciterable.d.ts"], + ["esnext.intl", "lib.esnext.intl.d.ts"], + ["esnext.bigint", "lib.esnext.bigint.d.ts"] + ]; + /** + * An array of supported "lib" reference file names used to determine the order for inclusion + * when referenced, as well as for spelling suggestions. This ensures the correct ordering for + * overload resolution when a type declared in one lib is extended by another. + */ + /* @internal */ + ts.libs = libEntries.map(function (entry) { return entry[0]; }); + /** + * A map of lib names to lib files. This map is used both for parsing the "lib" command line + * option as well as for resolving lib reference directives. + */ + /* @internal */ + ts.libMap = ts.createMapFromEntries(libEntries); + /* @internal */ + ts.commonOptionsWithBuild = [ + { + name: "help", + shortName: "h", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Print_this_message, + }, + { + name: "help", + shortName: "?", + type: "boolean" + }, + { + name: "watch", + shortName: "w", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Watch_input_files, + }, + { + name: "preserveWatchOutput", + type: "boolean", + showInSimplifiedHelpView: false, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen, + }, + { + name: "listFiles", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Print_names_of_files_part_of_the_compilation + }, + { + name: "listEmittedFiles", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Print_names_of_generated_files_part_of_the_compilation + }, + { + name: "pretty", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Stylize_errors_and_messages_using_color_and_context_experimental + }, + { + name: "traceResolution", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Enable_tracing_of_the_name_resolution_process + }, + { + name: "diagnostics", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Show_diagnostic_information + }, + { + name: "extendedDiagnostics", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Show_verbose_diagnostic_information + }, + ]; + /* @internal */ + ts.optionDeclarations = ts.commonOptionsWithBuild.concat([ + { + name: "all", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Show_all_compiler_options, + }, + { + name: "version", + shortName: "v", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Print_the_compiler_s_version, + }, + { + name: "init", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file, + }, + { + name: "project", + shortName: "p", + type: "string", + isFilePath: true, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Command_line_Options, + paramType: ts.Diagnostics.FILE_OR_DIRECTORY, + description: ts.Diagnostics.Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json, + }, + { + name: "build", + type: "boolean", + shortName: "b", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Build_one_or_more_projects_and_their_dependencies_if_out_of_date + }, + { + name: "showConfig", + type: "boolean", + category: ts.Diagnostics.Command_line_Options, + isCommandLineOnly: true, + description: ts.Diagnostics.Print_the_final_configuration_instead_of_building + }, + // Basic + { + name: "target", + shortName: "t", + type: ts.createMapFromTemplate({ + es3: 0 /* ES3 */, + es5: 1 /* ES5 */, + es6: 2 /* ES2015 */, + es2015: 2 /* ES2015 */, + es2016: 3 /* ES2016 */, + es2017: 4 /* ES2017 */, + es2018: 5 /* ES2018 */, + esnext: 6 /* ESNext */, + }), + affectsSourceFile: true, + affectsModuleResolution: true, + paramType: ts.Diagnostics.VERSION, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_or_ESNEXT, + }, + { + name: "module", + shortName: "m", + type: ts.createMapFromTemplate({ + none: ts.ModuleKind.None, + commonjs: ts.ModuleKind.CommonJS, + amd: ts.ModuleKind.AMD, + system: ts.ModuleKind.System, + umd: ts.ModuleKind.UMD, + es6: ts.ModuleKind.ES2015, + es2015: ts.ModuleKind.ES2015, + esnext: ts.ModuleKind.ESNext + }), + affectsModuleResolution: true, + paramType: ts.Diagnostics.KIND, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext, + }, + { + name: "lib", + type: "list", + element: { + name: "lib", + type: ts.libMap + }, + affectsModuleResolution: true, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Specify_library_files_to_be_included_in_the_compilation + }, + { + name: "allowJs", + type: "boolean", + affectsModuleResolution: true, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Allow_javascript_files_to_be_compiled + }, + { + name: "checkJs", + type: "boolean", + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Report_errors_in_js_files + }, + { + name: "jsx", + type: ts.createMapFromTemplate({ + "preserve": 1 /* Preserve */, + "react-native": 3 /* ReactNative */, + "react": 2 /* React */ + }), + affectsSourceFile: true, + paramType: ts.Diagnostics.KIND, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Specify_JSX_code_generation_Colon_preserve_react_native_or_react, + }, + { + name: "declaration", + shortName: "d", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Generates_corresponding_d_ts_file, + }, + { + name: "declarationMap", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Generates_a_sourcemap_for_each_corresponding_d_ts_file, + }, + { + name: "emitDeclarationOnly", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Only_emit_d_ts_declaration_files, + }, + { + name: "sourceMap", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Generates_corresponding_map_file, + }, + { + name: "outFile", + type: "string", + isFilePath: true, + paramType: ts.Diagnostics.FILE, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Concatenate_and_emit_output_to_single_file, + }, + { + name: "outDir", + type: "string", + isFilePath: true, + paramType: ts.Diagnostics.DIRECTORY, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Redirect_output_structure_to_the_directory, + }, + { + name: "rootDir", + type: "string", + isFilePath: true, + paramType: ts.Diagnostics.LOCATION, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir, + }, + { + name: "composite", + type: "boolean", + isTSConfigOnly: true, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Enable_project_compilation, + }, + { + name: "removeComments", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Do_not_emit_comments_to_output, + }, + { + name: "noEmit", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Do_not_emit_outputs, + }, + { + name: "importHelpers", + type: "boolean", + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Import_emit_helpers_from_tslib + }, + { + name: "downlevelIteration", + type: "boolean", + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Provide_full_support_for_iterables_in_for_of_spread_and_destructuring_when_targeting_ES5_or_ES3 + }, + { + name: "isolatedModules", + type: "boolean", + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule + }, + // Strict Type Checks + { + name: "strict", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Strict_Type_Checking_Options, + description: ts.Diagnostics.Enable_all_strict_type_checking_options + }, + { + name: "noImplicitAny", + type: "boolean", + affectsSemanticDiagnostics: true, + strictFlag: true, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Strict_Type_Checking_Options, + description: ts.Diagnostics.Raise_error_on_expressions_and_declarations_with_an_implied_any_type + }, + { + name: "strictNullChecks", + type: "boolean", + affectsSemanticDiagnostics: true, + strictFlag: true, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Strict_Type_Checking_Options, + description: ts.Diagnostics.Enable_strict_null_checks + }, + { + name: "strictFunctionTypes", + type: "boolean", + affectsSemanticDiagnostics: true, + strictFlag: true, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Strict_Type_Checking_Options, + description: ts.Diagnostics.Enable_strict_checking_of_function_types + }, + { + name: "strictBindCallApply", + type: "boolean", + strictFlag: true, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Strict_Type_Checking_Options, + description: ts.Diagnostics.Enable_strict_bind_call_and_apply_methods_on_functions + }, + { + name: "strictPropertyInitialization", + type: "boolean", + affectsSemanticDiagnostics: true, + strictFlag: true, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Strict_Type_Checking_Options, + description: ts.Diagnostics.Enable_strict_checking_of_property_initialization_in_classes + }, + { + name: "noImplicitThis", + type: "boolean", + affectsSemanticDiagnostics: true, + strictFlag: true, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Strict_Type_Checking_Options, + description: ts.Diagnostics.Raise_error_on_this_expressions_with_an_implied_any_type, + }, + { + name: "alwaysStrict", + type: "boolean", + affectsSourceFile: true, + strictFlag: true, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Strict_Type_Checking_Options, + description: ts.Diagnostics.Parse_in_strict_mode_and_emit_use_strict_for_each_source_file + }, + // Additional Checks + { + name: "noUnusedLocals", + type: "boolean", + affectsSemanticDiagnostics: true, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Additional_Checks, + description: ts.Diagnostics.Report_errors_on_unused_locals, + }, + { + name: "noUnusedParameters", + type: "boolean", + affectsSemanticDiagnostics: true, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Additional_Checks, + description: ts.Diagnostics.Report_errors_on_unused_parameters, + }, + { + name: "noImplicitReturns", + type: "boolean", + affectsSemanticDiagnostics: true, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Additional_Checks, + description: ts.Diagnostics.Report_error_when_not_all_code_paths_in_function_return_a_value + }, + { + name: "noFallthroughCasesInSwitch", + type: "boolean", + affectsBindDiagnostics: true, + affectsSemanticDiagnostics: true, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Additional_Checks, + description: ts.Diagnostics.Report_errors_for_fallthrough_cases_in_switch_statement + }, + // Module Resolution + { + name: "moduleResolution", + type: ts.createMapFromTemplate({ + node: ts.ModuleResolutionKind.NodeJs, + classic: ts.ModuleResolutionKind.Classic, + }), + affectsModuleResolution: true, + paramType: ts.Diagnostics.STRATEGY, + category: ts.Diagnostics.Module_Resolution_Options, + description: ts.Diagnostics.Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6, + }, + { + name: "baseUrl", + type: "string", + affectsModuleResolution: true, + isFilePath: true, + category: ts.Diagnostics.Module_Resolution_Options, + description: ts.Diagnostics.Base_directory_to_resolve_non_absolute_module_names + }, + { + // this option can only be specified in tsconfig.json + // use type = object to copy the value as-is + name: "paths", + type: "object", + affectsModuleResolution: true, + isTSConfigOnly: true, + category: ts.Diagnostics.Module_Resolution_Options, + description: ts.Diagnostics.A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl + }, + { + // this option can only be specified in tsconfig.json + // use type = object to copy the value as-is + name: "rootDirs", + type: "list", + isTSConfigOnly: true, + element: { + name: "rootDirs", + type: "string", + isFilePath: true + }, + affectsModuleResolution: true, + category: ts.Diagnostics.Module_Resolution_Options, + description: ts.Diagnostics.List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime + }, + { + name: "typeRoots", + type: "list", + element: { + name: "typeRoots", + type: "string", + isFilePath: true + }, + affectsModuleResolution: true, + category: ts.Diagnostics.Module_Resolution_Options, + description: ts.Diagnostics.List_of_folders_to_include_type_definitions_from + }, + { + name: "types", + type: "list", + element: { + name: "types", + type: "string" + }, + affectsModuleResolution: true, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Module_Resolution_Options, + description: ts.Diagnostics.Type_declaration_files_to_be_included_in_compilation + }, + { + name: "allowSyntheticDefaultImports", + type: "boolean", + affectsSemanticDiagnostics: true, + category: ts.Diagnostics.Module_Resolution_Options, + description: ts.Diagnostics.Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking + }, + { + name: "esModuleInterop", + type: "boolean", + affectsSemanticDiagnostics: true, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Module_Resolution_Options, + description: ts.Diagnostics.Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for_all_imports_Implies_allowSyntheticDefaultImports + }, + { + name: "preserveSymlinks", + type: "boolean", + category: ts.Diagnostics.Module_Resolution_Options, + description: ts.Diagnostics.Do_not_resolve_the_real_path_of_symlinks, + }, + // Source Maps + { + name: "sourceRoot", + type: "string", + paramType: ts.Diagnostics.LOCATION, + category: ts.Diagnostics.Source_Map_Options, + description: ts.Diagnostics.Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations, + }, + { + name: "mapRoot", + type: "string", + paramType: ts.Diagnostics.LOCATION, + category: ts.Diagnostics.Source_Map_Options, + description: ts.Diagnostics.Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations, + }, + { + name: "inlineSourceMap", + type: "boolean", + category: ts.Diagnostics.Source_Map_Options, + description: ts.Diagnostics.Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file + }, + { + name: "inlineSources", + type: "boolean", + category: ts.Diagnostics.Source_Map_Options, + description: ts.Diagnostics.Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap_to_be_set + }, + // Experimental + { + name: "experimentalDecorators", + type: "boolean", + category: ts.Diagnostics.Experimental_Options, + description: ts.Diagnostics.Enables_experimental_support_for_ES7_decorators + }, + { + name: "emitDecoratorMetadata", + type: "boolean", + category: ts.Diagnostics.Experimental_Options, + description: ts.Diagnostics.Enables_experimental_support_for_emitting_type_metadata_for_decorators + }, + // Advanced + { + name: "jsxFactory", + type: "string", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h + }, + { + name: "resolveJsonModule", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Include_modules_imported_with_json_extension + }, + { + name: "out", + type: "string", + isFilePath: false, + // for correct behaviour, please use outFile + category: ts.Diagnostics.Advanced_Options, + paramType: ts.Diagnostics.FILE, + description: ts.Diagnostics.Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file, + }, + { + name: "reactNamespace", + type: "string", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react_JSX_emit + }, + { + name: "skipDefaultLibCheck", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files + }, + { + name: "charset", + type: "string", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.The_character_set_of_the_input_files + }, + { + name: "emitBOM", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files + }, + { + name: "locale", + type: "string", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.The_locale_used_when_displaying_messages_to_the_user_e_g_en_us + }, + { + name: "newLine", + type: ts.createMapFromTemplate({ + crlf: 0 /* CarriageReturnLineFeed */, + lf: 1 /* LineFeed */ + }), + paramType: ts.Diagnostics.NEWLINE, + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix, + }, + { + name: "noErrorTruncation", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Do_not_truncate_error_messages + }, + { + name: "noLib", + type: "boolean", + affectsModuleResolution: true, + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Do_not_include_the_default_library_file_lib_d_ts + }, + { + name: "noResolve", + type: "boolean", + affectsModuleResolution: true, + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files + }, + { + name: "stripInternal", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Do_not_emit_declarations_for_code_that_has_an_internal_annotation, + }, + { + name: "disableSizeLimit", + type: "boolean", + affectsSourceFile: true, + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Disable_size_limitations_on_JavaScript_projects + }, + { + name: "noImplicitUseStrict", + type: "boolean", + affectsSemanticDiagnostics: true, + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Do_not_emit_use_strict_directives_in_module_output + }, + { + name: "noEmitHelpers", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Do_not_generate_custom_helper_functions_like_extends_in_compiled_output + }, + { + name: "noEmitOnError", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Do_not_emit_outputs_if_any_errors_were_reported, + }, + { + name: "preserveConstEnums", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Do_not_erase_const_enum_declarations_in_generated_code + }, + { + name: "declarationDir", + type: "string", + isFilePath: true, + paramType: ts.Diagnostics.DIRECTORY, + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Output_directory_for_generated_declaration_files + }, + { + name: "skipLibCheck", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Skip_type_checking_of_declaration_files, + }, + { + name: "allowUnusedLabels", + type: "boolean", + affectsBindDiagnostics: true, + affectsSemanticDiagnostics: true, + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Do_not_report_errors_on_unused_labels + }, + { + name: "allowUnreachableCode", + type: "boolean", + affectsBindDiagnostics: true, + affectsSemanticDiagnostics: true, + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Do_not_report_errors_on_unreachable_code + }, + { + name: "suppressExcessPropertyErrors", + type: "boolean", + affectsSemanticDiagnostics: true, + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Suppress_excess_property_checks_for_object_literals, + }, + { + name: "suppressImplicitAnyIndexErrors", + type: "boolean", + affectsSemanticDiagnostics: true, + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures, + }, + { + name: "forceConsistentCasingInFileNames", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Disallow_inconsistently_cased_references_to_the_same_file + }, + { + name: "maxNodeModuleJsDepth", + type: "number", + affectsModuleResolution: true, + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files + }, + { + name: "noStrictGenericChecks", + type: "boolean", + affectsSemanticDiagnostics: true, + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Disable_strict_checking_of_generic_signatures_in_function_types, + }, + { + name: "keyofStringsOnly", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols, + }, + { + // A list of plugins to load in the language service + name: "plugins", + type: "list", + isTSConfigOnly: true, + element: { + name: "plugin", + type: "object" + }, + description: ts.Diagnostics.List_of_language_service_plugins + } + ]); + /* @internal */ + ts.semanticDiagnosticsOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsSemanticDiagnostics; }); + /* @internal */ + ts.moduleResolutionOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsModuleResolution; }); + /* @internal */ + ts.sourceFileAffectingCompilerOptions = ts.optionDeclarations.filter(function (option) { + return !!option.affectsSourceFile || !!option.affectsModuleResolution || !!option.affectsBindDiagnostics; + }); + /* @internal */ + ts.buildOpts = ts.commonOptionsWithBuild.concat([ + { + name: "verbose", + shortName: "v", + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Enable_verbose_logging, + type: "boolean" + }, + { + name: "dry", + shortName: "d", + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Show_what_would_be_built_or_deleted_if_specified_with_clean, + type: "boolean" + }, + { + name: "force", + shortName: "f", + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Build_all_projects_including_those_that_appear_to_be_up_to_date, + type: "boolean" + }, + { + name: "clean", + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Delete_the_outputs_of_all_projects, + type: "boolean" + } + ]); + /* @internal */ + ts.typeAcquisitionDeclarations = [ + { + /* @deprecated typingOptions.enableAutoDiscovery + * Use typeAcquisition.enable instead. + */ + name: "enableAutoDiscovery", + type: "boolean", + }, + { + name: "enable", + type: "boolean", + }, + { + name: "include", + type: "list", + element: { + name: "include", + type: "string" + } + }, + { + name: "exclude", + type: "list", + element: { + name: "exclude", + type: "string" + } + } + ]; + /* @internal */ + ts.defaultInitCompilerOptions = { + module: ts.ModuleKind.CommonJS, + target: 1 /* ES5 */, + strict: true, + esModuleInterop: true + }; + var optionNameMapCache; + /* @internal */ + function convertEnableAutoDiscoveryToEnable(typeAcquisition) { + // Convert deprecated typingOptions.enableAutoDiscovery to typeAcquisition.enable + if (typeAcquisition && typeAcquisition.enableAutoDiscovery !== undefined && typeAcquisition.enable === undefined) { + return { + enable: typeAcquisition.enableAutoDiscovery, + include: typeAcquisition.include || [], + exclude: typeAcquisition.exclude || [] + }; + } + return typeAcquisition; + } + ts.convertEnableAutoDiscoveryToEnable = convertEnableAutoDiscoveryToEnable; + function getOptionNameMap() { + return optionNameMapCache || (optionNameMapCache = createOptionNameMap(ts.optionDeclarations)); + } + /*@internal*/ + function createOptionNameMap(optionDeclarations) { + var optionNameMap = ts.createMap(); + var shortOptionNames = ts.createMap(); + ts.forEach(optionDeclarations, function (option) { + optionNameMap.set(option.name.toLowerCase(), option); + if (option.shortName) { + shortOptionNames.set(option.shortName, option.name); + } + }); + return { optionNameMap: optionNameMap, shortOptionNames: shortOptionNames }; + } + ts.createOptionNameMap = createOptionNameMap; + /* @internal */ + function createCompilerDiagnosticForInvalidCustomType(opt) { + return createDiagnosticForInvalidCustomType(opt, ts.createCompilerDiagnostic); + } + ts.createCompilerDiagnosticForInvalidCustomType = createCompilerDiagnosticForInvalidCustomType; + function createDiagnosticForInvalidCustomType(opt, createDiagnostic) { + var namesOfType = ts.arrayFrom(opt.type.keys()).map(function (key) { return "'" + key + "'"; }).join(", "); + return createDiagnostic(ts.Diagnostics.Argument_for_0_option_must_be_Colon_1, "--" + opt.name, namesOfType); + } + /* @internal */ + function parseCustomTypeOption(opt, value, errors) { + return convertJsonOptionOfCustomType(opt, trimString(value || ""), errors); + } + ts.parseCustomTypeOption = parseCustomTypeOption; + /* @internal */ + function parseListTypeOption(opt, value, errors) { + if (value === void 0) { value = ""; } + value = trimString(value); + if (ts.startsWith(value, "-")) { + return undefined; + } + if (value === "") { + return []; + } + var values = value.split(","); + switch (opt.element.type) { + case "number": + return ts.map(values, parseInt); + case "string": + return ts.map(values, function (v) { return v || ""; }); + default: + return ts.mapDefined(values, function (v) { return parseCustomTypeOption(opt.element, v, errors); }); + } + } + ts.parseListTypeOption = parseListTypeOption; + function parseCommandLineWorker(getOptionNameMap, _a, commandLine, readFile) { + var unknownOptionDiagnostic = _a[0], optionTypeMismatchDiagnostic = _a[1]; + var options = {}; + var fileNames = []; + var errors = []; + parseStrings(commandLine); + return { + options: options, + fileNames: fileNames, + errors: errors + }; + function parseStrings(args) { + var i = 0; + while (i < args.length) { + var s = args[i]; + i++; + if (s.charCodeAt(0) === 64 /* at */) { + parseResponseFile(s.slice(1)); + } + else if (s.charCodeAt(0) === 45 /* minus */) { + var opt = getOptionDeclarationFromName(getOptionNameMap, s.slice(s.charCodeAt(1) === 45 /* minus */ ? 2 : 1), /*allowShort*/ true); + if (opt) { + if (opt.isTSConfigOnly) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_can_only_be_specified_in_tsconfig_json_file, opt.name)); + } + else { + // Check to see if no argument was provided (e.g. "--locale" is the last command-line argument). + if (!args[i] && opt.type !== "boolean") { + errors.push(ts.createCompilerDiagnostic(optionTypeMismatchDiagnostic, opt.name)); + } + switch (opt.type) { + case "number": + options[opt.name] = parseInt(args[i]); + i++; + break; + case "boolean": + // boolean flag has optional value true, false, others + var optValue = args[i]; + options[opt.name] = optValue !== "false"; + // consume next argument as boolean flag value + if (optValue === "false" || optValue === "true") { + i++; + } + break; + case "string": + options[opt.name] = args[i] || ""; + i++; + break; + case "list": + var result = parseListTypeOption(opt, args[i], errors); + options[opt.name] = result || []; + if (result) { + i++; + } + break; + // If not a primitive, the possible types are specified in what is effectively a map of options. + default: + options[opt.name] = parseCustomTypeOption(opt, args[i], errors); + i++; + break; + } + } + } + else { + errors.push(ts.createCompilerDiagnostic(unknownOptionDiagnostic, s)); + } + } + else { + fileNames.push(s); + } + } + } + function parseResponseFile(fileName) { + var text = readFile ? readFile(fileName) : ts.sys.readFile(fileName); + if (!text) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_not_found, fileName)); + return; + } + var args = []; + var pos = 0; + while (true) { + while (pos < text.length && text.charCodeAt(pos) <= 32 /* space */) + pos++; + if (pos >= text.length) + break; + var start = pos; + if (text.charCodeAt(start) === 34 /* doubleQuote */) { + pos++; + while (pos < text.length && text.charCodeAt(pos) !== 34 /* doubleQuote */) + pos++; + if (pos < text.length) { + args.push(text.substring(start + 1, pos)); + pos++; + } + else { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unterminated_quoted_string_in_response_file_0, fileName)); + } + } + else { + while (text.charCodeAt(pos) > 32 /* space */) + pos++; + args.push(text.substring(start, pos)); + } + } + parseStrings(args); + } + } + function parseCommandLine(commandLine, readFile) { + return parseCommandLineWorker(getOptionNameMap, [ + ts.Diagnostics.Unknown_compiler_option_0, + ts.Diagnostics.Compiler_option_0_expects_an_argument + ], commandLine, readFile); + } + ts.parseCommandLine = parseCommandLine; + /** @internal */ + function getOptionFromName(optionName, allowShort) { + return getOptionDeclarationFromName(getOptionNameMap, optionName, allowShort); + } + ts.getOptionFromName = getOptionFromName; + function getOptionDeclarationFromName(getOptionNameMap, optionName, allowShort) { + if (allowShort === void 0) { allowShort = false; } + optionName = optionName.toLowerCase(); + var _a = getOptionNameMap(), optionNameMap = _a.optionNameMap, shortOptionNames = _a.shortOptionNames; + // Try to translate short option names to their full equivalents. + if (allowShort) { + var short = shortOptionNames.get(optionName); + if (short !== undefined) { + optionName = short; + } + } + return optionNameMap.get(optionName); + } + /*@internal*/ + function parseBuildCommand(args) { + var buildOptionNameMap; + var returnBuildOptionNameMap = function () { return (buildOptionNameMap || (buildOptionNameMap = createOptionNameMap(ts.buildOpts))); }; + var _a = parseCommandLineWorker(returnBuildOptionNameMap, [ + ts.Diagnostics.Unknown_build_option_0, + ts.Diagnostics.Build_option_0_requires_a_value_of_type_1 + ], args), options = _a.options, projects = _a.fileNames, errors = _a.errors; + var buildOptions = options; + if (projects.length === 0) { + // tsc -b invoked with no extra arguments; act as if invoked with "tsc -b ." + projects.push("."); + } + // Nonsensical combinations + if (buildOptions.clean && buildOptions.force) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "force")); + } + if (buildOptions.clean && buildOptions.verbose) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "verbose")); + } + if (buildOptions.clean && buildOptions.watch) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "watch")); + } + if (buildOptions.watch && buildOptions.dry) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "watch", "dry")); + } + return { buildOptions: buildOptions, projects: projects, errors: errors }; + } + ts.parseBuildCommand = parseBuildCommand; + function getDiagnosticText(_message) { + var _args = []; + for (var _i = 1; _i < arguments.length; _i++) { + _args[_i - 1] = arguments[_i]; + } + var diagnostic = ts.createCompilerDiagnostic.apply(undefined, arguments); + return diagnostic.messageText; + } + /* @internal */ + function printVersion() { + ts.sys.write(getDiagnosticText(ts.Diagnostics.Version_0, ts.version) + ts.sys.newLine); + } + ts.printVersion = printVersion; + /* @internal */ + function printHelp(optionsList, syntaxPrefix) { + if (syntaxPrefix === void 0) { syntaxPrefix = ""; } + var output = []; + // We want to align our "syntax" and "examples" commands to a certain margin. + var syntaxLength = getDiagnosticText(ts.Diagnostics.Syntax_Colon_0, "").length; + var examplesLength = getDiagnosticText(ts.Diagnostics.Examples_Colon_0, "").length; + var marginLength = Math.max(syntaxLength, examplesLength); + // Build up the syntactic skeleton. + var syntax = makePadding(marginLength - syntaxLength); + syntax += "tsc " + syntaxPrefix + "[" + getDiagnosticText(ts.Diagnostics.options) + "] [" + getDiagnosticText(ts.Diagnostics.file) + "...]"; + output.push(getDiagnosticText(ts.Diagnostics.Syntax_Colon_0, syntax)); + output.push(ts.sys.newLine + ts.sys.newLine); + // Build up the list of examples. + var padding = makePadding(marginLength); + output.push(getDiagnosticText(ts.Diagnostics.Examples_Colon_0, makePadding(marginLength - examplesLength) + "tsc hello.ts") + ts.sys.newLine); + output.push(padding + "tsc --outFile file.js file.ts" + ts.sys.newLine); + output.push(padding + "tsc @args.txt" + ts.sys.newLine); + output.push(padding + "tsc --build tsconfig.json" + ts.sys.newLine); + output.push(ts.sys.newLine); + output.push(getDiagnosticText(ts.Diagnostics.Options_Colon) + ts.sys.newLine); + // We want our descriptions to align at the same column in our output, + // so we keep track of the longest option usage string. + marginLength = 0; + var usageColumn = []; // Things like "-d, --declaration" go in here. + var descriptionColumn = []; + var optionsDescriptionMap = ts.createMap(); // Map between option.description and list of option.type if it is a kind + for (var _i = 0, optionsList_1 = optionsList; _i < optionsList_1.length; _i++) { + var option = optionsList_1[_i]; + // If an option lacks a description, + // it is not officially supported. + if (!option.description) { + continue; + } + var usageText_1 = " "; + if (option.shortName) { + usageText_1 += "-" + option.shortName; + usageText_1 += getParamType(option); + usageText_1 += ", "; + } + usageText_1 += "--" + option.name; + usageText_1 += getParamType(option); + usageColumn.push(usageText_1); + var description = void 0; + if (option.name === "lib") { + description = getDiagnosticText(option.description); + var element = option.element; + var typeMap = element.type; + optionsDescriptionMap.set(description, ts.arrayFrom(typeMap.keys()).map(function (key) { return "'" + key + "'"; })); + } + else { + description = getDiagnosticText(option.description); + } + descriptionColumn.push(description); + // Set the new margin for the description column if necessary. + marginLength = Math.max(usageText_1.length, marginLength); + } + // Special case that can't fit in the loop. + var usageText = " @<" + getDiagnosticText(ts.Diagnostics.file) + ">"; + usageColumn.push(usageText); + descriptionColumn.push(getDiagnosticText(ts.Diagnostics.Insert_command_line_options_and_files_from_a_file)); + marginLength = Math.max(usageText.length, marginLength); + // Print out each row, aligning all the descriptions on the same column. + for (var i = 0; i < usageColumn.length; i++) { + var usage = usageColumn[i]; + var description = descriptionColumn[i]; + var kindsList = optionsDescriptionMap.get(description); + output.push(usage + makePadding(marginLength - usage.length + 2) + description + ts.sys.newLine); + if (kindsList) { + output.push(makePadding(marginLength + 4)); + for (var _a = 0, kindsList_1 = kindsList; _a < kindsList_1.length; _a++) { + var kind = kindsList_1[_a]; + output.push(kind + " "); + } + output.push(ts.sys.newLine); + } + } + for (var _b = 0, output_1 = output; _b < output_1.length; _b++) { + var line = output_1[_b]; + ts.sys.write(line); + } + return; + function getParamType(option) { + if (option.paramType !== undefined) { + return " " + getDiagnosticText(option.paramType); + } + return ""; + } + function makePadding(paddingLength) { + return Array(paddingLength + 1).join(" "); + } + } + ts.printHelp = printHelp; + /** + * Reads the config file, reports errors if any and exits if the config file cannot be found + */ + function getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host) { + var configFileText; + try { + configFileText = host.readFile(configFileName); + } + catch (e) { + var error = ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, configFileName, e.message); + host.onUnRecoverableConfigFileDiagnostic(error); + return undefined; + } + if (!configFileText) { + var error = ts.createCompilerDiagnostic(ts.Diagnostics.File_0_not_found, configFileName); + host.onUnRecoverableConfigFileDiagnostic(error); + return undefined; + } + var result = ts.parseJsonText(configFileName, configFileText); + var cwd = host.getCurrentDirectory(); + result.path = ts.toPath(configFileName, cwd, ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames)); + result.resolvedPath = result.path; + result.originalFileName = result.fileName; + return parseJsonSourceFileConfigFileContent(result, host, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), cwd), optionsToExtend, ts.getNormalizedAbsolutePath(configFileName, cwd)); + } + ts.getParsedCommandLineOfConfigFile = getParsedCommandLineOfConfigFile; + /** + * Read tsconfig.json file + * @param fileName The path to the config file + */ + function readConfigFile(fileName, readFile) { + var textOrDiagnostic = tryReadFile(fileName, readFile); + return ts.isString(textOrDiagnostic) ? parseConfigFileTextToJson(fileName, textOrDiagnostic) : { config: {}, error: textOrDiagnostic }; + } + ts.readConfigFile = readConfigFile; + /** + * Parse the text of the tsconfig.json file + * @param fileName The path to the config file + * @param jsonText The text of the config file + */ + function parseConfigFileTextToJson(fileName, jsonText) { + var jsonSourceFile = ts.parseJsonText(fileName, jsonText); + return { + config: convertToObject(jsonSourceFile, jsonSourceFile.parseDiagnostics), + error: jsonSourceFile.parseDiagnostics.length ? jsonSourceFile.parseDiagnostics[0] : undefined + }; + } + ts.parseConfigFileTextToJson = parseConfigFileTextToJson; + /** + * Read tsconfig.json file + * @param fileName The path to the config file + */ + function readJsonConfigFile(fileName, readFile) { + var textOrDiagnostic = tryReadFile(fileName, readFile); + return ts.isString(textOrDiagnostic) ? ts.parseJsonText(fileName, textOrDiagnostic) : { parseDiagnostics: [textOrDiagnostic] }; + } + ts.readJsonConfigFile = readJsonConfigFile; + function tryReadFile(fileName, readFile) { + var text; + try { + text = readFile(fileName); + } + catch (e) { + return ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, e.message); + } + return text === undefined ? ts.createCompilerDiagnostic(ts.Diagnostics.The_specified_path_does_not_exist_Colon_0, fileName) : text; + } + function commandLineOptionsToMap(options) { + return ts.arrayToMap(options, function (option) { return option.name; }); + } + var _tsconfigRootOptions; + function getTsconfigRootOptionsMap() { + if (_tsconfigRootOptions === undefined) { + _tsconfigRootOptions = { + name: undefined, + type: "object", + elementOptions: commandLineOptionsToMap([ + { + name: "compilerOptions", + type: "object", + elementOptions: commandLineOptionsToMap(ts.optionDeclarations), + extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_compiler_option_0 + }, + { + name: "typingOptions", + type: "object", + elementOptions: commandLineOptionsToMap(ts.typeAcquisitionDeclarations), + extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_type_acquisition_option_0 + }, + { + name: "typeAcquisition", + type: "object", + elementOptions: commandLineOptionsToMap(ts.typeAcquisitionDeclarations), + extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_type_acquisition_option_0 + }, + { + name: "extends", + type: "string" + }, + { + name: "references", + type: "list", + element: { + name: "references", + type: "object" + } + }, + { + name: "files", + type: "list", + element: { + name: "files", + type: "string" + } + }, + { + name: "include", + type: "list", + element: { + name: "include", + type: "string" + } + }, + { + name: "exclude", + type: "list", + element: { + name: "exclude", + type: "string" + } + }, + ts.compileOnSaveCommandLineOption + ]) + }; + } + return _tsconfigRootOptions; + } + /** + * Convert the json syntax tree into the json value + */ + function convertToObject(sourceFile, errors) { + return convertToObjectWorker(sourceFile, errors, /*returnValue*/ true, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined); + } + ts.convertToObject = convertToObject; + /** + * Convert the json syntax tree into the json value and report errors + * This returns the json value (apart from checking errors) only if returnValue provided is true. + * Otherwise it just checks the errors and returns undefined + */ + /*@internal*/ + function convertToObjectWorker(sourceFile, errors, returnValue, knownRootOptions, jsonConversionNotifier) { + if (!sourceFile.statements.length) { + return returnValue ? {} : undefined; + } + return convertPropertyValueToJson(sourceFile.statements[0].expression, knownRootOptions); + function isRootOptionMap(knownOptions) { + return knownRootOptions && knownRootOptions.elementOptions === knownOptions; + } + function convertObjectLiteralExpressionToJson(node, knownOptions, extraKeyDiagnosticMessage, parentOption) { + var result = returnValue ? {} : undefined; + for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { + var element = _a[_i]; + if (element.kind !== 275 /* PropertyAssignment */) { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element, ts.Diagnostics.Property_assignment_expected)); + continue; + } + if (element.questionToken) { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.questionToken, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, "?")); + } + if (!isDoubleQuotedString(element.name)) { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, ts.Diagnostics.String_literal_with_double_quotes_expected)); + } + var textOfKey = ts.getTextOfPropertyName(element.name); + var keyText = textOfKey && ts.unescapeLeadingUnderscores(textOfKey); + var option = keyText && knownOptions ? knownOptions.get(keyText) : undefined; + if (keyText && extraKeyDiagnosticMessage && !option) { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, extraKeyDiagnosticMessage, keyText)); + } + var value = convertPropertyValueToJson(element.initializer, option); + if (typeof keyText !== "undefined") { + if (returnValue) { + result[keyText] = value; + } + // Notify key value set, if user asked for it + if (jsonConversionNotifier && + // Current callbacks are only on known parent option or if we are setting values in the root + (parentOption || isRootOptionMap(knownOptions))) { + var isValidOptionValue = isCompilerOptionsValue(option, value); + if (parentOption) { + if (isValidOptionValue) { + // Notify option set in the parent if its a valid option value + jsonConversionNotifier.onSetValidOptionKeyValueInParent(parentOption, option, value); + } + } + else if (isRootOptionMap(knownOptions)) { + if (isValidOptionValue) { + // Notify about the valid root key value being set + jsonConversionNotifier.onSetValidOptionKeyValueInRoot(keyText, element.name, value, element.initializer); + } + else if (!option) { + // Notify about the unknown root key value being set + jsonConversionNotifier.onSetUnknownOptionKeyValueInRoot(keyText, element.name, value, element.initializer); + } + } + } + } + } + return result; + } + function convertArrayLiteralExpressionToJson(elements, elementOption) { + if (!returnValue) { + return elements.forEach(function (element) { return convertPropertyValueToJson(element, elementOption); }); + } + // Filter out invalid values + return ts.filter(elements.map(function (element) { return convertPropertyValueToJson(element, elementOption); }), function (v) { return v !== undefined; }); + } + function convertPropertyValueToJson(valueExpression, option) { + switch (valueExpression.kind) { + case 102 /* TrueKeyword */: + reportInvalidOptionValue(option && option.type !== "boolean"); + return true; + case 87 /* FalseKeyword */: + reportInvalidOptionValue(option && option.type !== "boolean"); + return false; + case 96 /* NullKeyword */: + reportInvalidOptionValue(option && option.name === "extends"); // "extends" is the only option we don't allow null/undefined for + return null; // tslint:disable-line:no-null-keyword + case 10 /* StringLiteral */: + if (!isDoubleQuotedString(valueExpression)) { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, ts.Diagnostics.String_literal_with_double_quotes_expected)); + } + reportInvalidOptionValue(option && (ts.isString(option.type) && option.type !== "string")); + var text = valueExpression.text; + if (option && !ts.isString(option.type)) { + var customOption = option; + // Validate custom option type + if (!customOption.type.has(text.toLowerCase())) { + errors.push(createDiagnosticForInvalidCustomType(customOption, function (message, arg0, arg1) { return ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, message, arg0, arg1); })); + } + } + return text; + case 8 /* NumericLiteral */: + reportInvalidOptionValue(option && option.type !== "number"); + return Number(valueExpression.text); + case 202 /* PrefixUnaryExpression */: + if (valueExpression.operator !== 39 /* MinusToken */ || valueExpression.operand.kind !== 8 /* NumericLiteral */) { + break; // not valid JSON syntax + } + reportInvalidOptionValue(option && option.type !== "number"); + return -Number(valueExpression.operand.text); + case 188 /* ObjectLiteralExpression */: + reportInvalidOptionValue(option && option.type !== "object"); + var objectLiteralExpression = valueExpression; + // Currently having element option declaration in the tsconfig with type "object" + // determines if it needs onSetValidOptionKeyValueInParent callback or not + // At moment there are only "compilerOptions", "typeAcquisition" and "typingOptions" + // that satifies it and need it to modify options set in them (for normalizing file paths) + // vs what we set in the json + // If need arises, we can modify this interface and callbacks as needed + if (option) { + var _a = option, elementOptions = _a.elementOptions, extraKeyDiagnosticMessage = _a.extraKeyDiagnosticMessage, optionName = _a.name; + return convertObjectLiteralExpressionToJson(objectLiteralExpression, elementOptions, extraKeyDiagnosticMessage, optionName); + } + else { + return convertObjectLiteralExpressionToJson(objectLiteralExpression, /* knownOptions*/ undefined, + /*extraKeyDiagnosticMessage */ undefined, /*parentOption*/ undefined); + } + case 187 /* ArrayLiteralExpression */: + reportInvalidOptionValue(option && option.type !== "list"); + return convertArrayLiteralExpressionToJson(valueExpression.elements, option && option.element); + } + // Not in expected format + if (option) { + reportInvalidOptionValue(/*isError*/ true); + } + else { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, ts.Diagnostics.Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_literal)); + } + return undefined; + function reportInvalidOptionValue(isError) { + if (isError) { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, option.name, getCompilerOptionValueTypeString(option))); + } + } + } + function isDoubleQuotedString(node) { + return ts.isStringLiteral(node) && ts.isStringDoubleQuoted(node, sourceFile); + } + } + ts.convertToObjectWorker = convertToObjectWorker; + function getCompilerOptionValueTypeString(option) { + return option.type === "list" ? + "Array" : + ts.isString(option.type) ? option.type : "string"; + } + function isCompilerOptionsValue(option, value) { + if (option) { + if (isNullOrUndefined(value)) + return true; // All options are undefinable/nullable + if (option.type === "list") { + return ts.isArray(value); + } + var expectedType = ts.isString(option.type) ? option.type : "string"; + return typeof value === expectedType; + } + return false; + } + /** + * Generate an uncommented, complete tsconfig for use with "--showConfig" + * @param configParseResult options to be generated into tsconfig.json + * @param configFileName name of the parsed config file - output paths will be generated relative to this + * @param host provides current directory and case sensitivity services + */ + /** @internal */ + function convertToTSConfig(configParseResult, configFileName, host) { + var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); + var files = ts.map(ts.filter(configParseResult.fileNames, (!configParseResult.configFileSpecs || !configParseResult.configFileSpecs.validatedIncludeSpecs) ? function (_) { return true; } : matchesSpecs(configFileName, configParseResult.configFileSpecs.validatedIncludeSpecs, configParseResult.configFileSpecs.validatedExcludeSpecs)), function (f) { return ts.getRelativePathFromFile(ts.getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), ts.getNormalizedAbsolutePath(f, host.getCurrentDirectory()), getCanonicalFileName); }); + var optionMap = serializeCompilerOptions(configParseResult.options, { configFilePath: ts.getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), useCaseSensitiveFileNames: host.useCaseSensitiveFileNames }); + var config = __assign({ compilerOptions: __assign({}, ts.arrayFrom(optionMap.entries()).reduce(function (prev, cur) { + var _a; + return (__assign({}, prev, (_a = {}, _a[cur[0]] = cur[1], _a))); + }, {}), { showConfig: undefined, configFile: undefined, configFilePath: undefined, help: undefined, init: undefined, listFiles: undefined, listEmittedFiles: undefined, project: undefined }), references: ts.map(configParseResult.projectReferences, function (r) { return (__assign({}, r, { path: r.originalPath, originalPath: undefined })); }), files: ts.length(files) ? files : undefined }, (configParseResult.configFileSpecs ? { + include: filterSameAsDefaultInclude(configParseResult.configFileSpecs.validatedIncludeSpecs), + exclude: configParseResult.configFileSpecs.validatedExcludeSpecs + } : {}), { compilerOnSave: !!configParseResult.compileOnSave ? true : undefined }); + return config; + } + ts.convertToTSConfig = convertToTSConfig; + function filterSameAsDefaultInclude(specs) { + if (!ts.length(specs)) + return undefined; + if (ts.length(specs) !== 1) + return specs; + if (specs[0] === "**/*") + return undefined; + return specs; + } + function matchesSpecs(path, includeSpecs, excludeSpecs) { + if (!includeSpecs) + return function (_) { return true; }; + var patterns = ts.getFileMatcherPatterns(path, excludeSpecs, includeSpecs, ts.sys.useCaseSensitiveFileNames, ts.sys.getCurrentDirectory()); + var excludeRe = patterns.excludePattern && ts.getRegexFromPattern(patterns.excludePattern, ts.sys.useCaseSensitiveFileNames); + var includeRe = patterns.includeFilePattern && ts.getRegexFromPattern(patterns.includeFilePattern, ts.sys.useCaseSensitiveFileNames); + if (includeRe) { + if (excludeRe) { + return function (path) { return !(includeRe.test(path) && !excludeRe.test(path)); }; + } + return function (path) { return !includeRe.test(path); }; + } + if (excludeRe) { + return function (path) { return excludeRe.test(path); }; + } + return function (_) { return true; }; + } + function getCustomTypeMapOfCommandLineOption(optionDefinition) { + if (optionDefinition.type === "string" || optionDefinition.type === "number" || optionDefinition.type === "boolean") { + // this is of a type CommandLineOptionOfPrimitiveType + return undefined; + } + else if (optionDefinition.type === "list") { + return getCustomTypeMapOfCommandLineOption(optionDefinition.element); + } + else { + return optionDefinition.type; + } + } + function getNameOfCompilerOptionValue(value, customTypeMap) { + // There is a typeMap associated with this command-line option so use it to map value back to its name + return ts.forEachEntry(customTypeMap, function (mapValue, key) { + if (mapValue === value) { + return key; + } + }); + } + function serializeCompilerOptions(options, pathOptions) { + var result = ts.createMap(); + var optionsNameMap = getOptionNameMap().optionNameMap; + var getCanonicalFileName = pathOptions && ts.createGetCanonicalFileName(pathOptions.useCaseSensitiveFileNames); + var _loop_3 = function (name) { + if (ts.hasProperty(options, name)) { + // tsconfig only options cannot be specified via command line, + // so we can assume that only types that can appear here string | number | boolean + if (optionsNameMap.has(name) && optionsNameMap.get(name).category === ts.Diagnostics.Command_line_Options) { + return "continue"; + } + var value = options[name]; + var optionDefinition = optionsNameMap.get(name.toLowerCase()); + if (optionDefinition) { + var customTypeMap_1 = getCustomTypeMapOfCommandLineOption(optionDefinition); + if (!customTypeMap_1) { + // There is no map associated with this compiler option then use the value as-is + // This is the case if the value is expect to be string, number, boolean or list of string + if (pathOptions && optionDefinition.isFilePath) { + result.set(name, ts.getRelativePathFromFile(pathOptions.configFilePath, ts.getNormalizedAbsolutePath(value, ts.getDirectoryPath(pathOptions.configFilePath)), getCanonicalFileName)); + } + else { + result.set(name, value); + } + } + else { + if (optionDefinition.type === "list") { + result.set(name, value.map(function (element) { return getNameOfCompilerOptionValue(element, customTypeMap_1); })); // TODO: GH#18217 + } + else { + // There is a typeMap associated with this command-line option so use it to map value back to its name + result.set(name, getNameOfCompilerOptionValue(value, customTypeMap_1)); + } + } + } + } + }; + for (var name in options) { + _loop_3(name); + } + return result; + } + /** + * Generate tsconfig configuration when running command line "--init" + * @param options commandlineOptions to be generated into tsconfig.json + * @param fileNames array of filenames to be generated into tsconfig.json + */ + /* @internal */ + function generateTSConfig(options, fileNames, newLine) { + var compilerOptions = ts.extend(options, ts.defaultInitCompilerOptions); + var compilerOptionsMap = serializeCompilerOptions(compilerOptions); + return writeConfigurations(); + function getDefaultValueForOption(option) { + switch (option.type) { + case "number": + return 1; + case "boolean": + return true; + case "string": + return option.isFilePath ? "./" : ""; + case "list": + return []; + case "object": + return {}; + default: + return option.type.keys().next().value; + } + } + function makePadding(paddingLength) { + return Array(paddingLength + 1).join(" "); + } + function isAllowedOption(_a) { + var category = _a.category, name = _a.name; + // Skip options which do not have a category or have category `Command_line_Options` + // Exclude all possible `Advanced_Options` in tsconfig.json which were NOT defined in command line + return category !== undefined + && category !== ts.Diagnostics.Command_line_Options + && (category !== ts.Diagnostics.Advanced_Options || compilerOptionsMap.has(name)); + } + function writeConfigurations() { + // Filter applicable options to place in the file + var categorizedOptions = ts.createMultiMap(); + for (var _i = 0, optionDeclarations_1 = ts.optionDeclarations; _i < optionDeclarations_1.length; _i++) { + var option = optionDeclarations_1[_i]; + var category = option.category; + if (isAllowedOption(option)) { + categorizedOptions.add(ts.getLocaleSpecificMessage(category), option); + } + } + // Serialize all options and their descriptions + var marginLength = 0; + var seenKnownKeys = 0; + var nameColumn = []; + var descriptionColumn = []; + categorizedOptions.forEach(function (options, category) { + if (nameColumn.length !== 0) { + nameColumn.push(""); + descriptionColumn.push(""); + } + nameColumn.push("/* " + category + " */"); + descriptionColumn.push(""); + for (var _i = 0, options_1 = options; _i < options_1.length; _i++) { + var option = options_1[_i]; + var optionName = void 0; + if (compilerOptionsMap.has(option.name)) { + optionName = "\"" + option.name + "\": " + JSON.stringify(compilerOptionsMap.get(option.name)) + ((seenKnownKeys += 1) === compilerOptionsMap.size ? "" : ","); + } + else { + optionName = "// \"" + option.name + "\": " + JSON.stringify(getDefaultValueForOption(option)) + ","; + } + nameColumn.push(optionName); + descriptionColumn.push("/* " + (option.description && ts.getLocaleSpecificMessage(option.description) || option.name) + " */"); + marginLength = Math.max(optionName.length, marginLength); + } + }); + // Write the output + var tab = makePadding(2); + var result = []; + result.push("{"); + result.push(tab + "\"compilerOptions\": {"); + // Print out each row, aligning all the descriptions on the same column. + for (var i = 0; i < nameColumn.length; i++) { + var optionName = nameColumn[i]; + var description = descriptionColumn[i]; + result.push(optionName && "" + tab + tab + optionName + (description && (makePadding(marginLength - optionName.length + 2) + description))); + } + if (fileNames.length) { + result.push(tab + "},"); + result.push(tab + "\"files\": ["); + for (var i = 0; i < fileNames.length; i++) { + result.push("" + tab + tab + JSON.stringify(fileNames[i]) + (i === fileNames.length - 1 ? "" : ",")); + } + result.push(tab + "]"); + } + else { + result.push(tab + "}"); + } + result.push("}"); + return result.join(newLine); + } + } + ts.generateTSConfig = generateTSConfig; + /** + * Parse the contents of a config file (tsconfig.json). + * @param json The contents of the config file to parse + * @param host Instance of ParseConfigHost used to enumerate files in folder. + * @param basePath A root directory to resolve relative path entries in the config + * file to. e.g. outDir + */ + function parseJsonConfigFileContent(json, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions) { + return parseJsonConfigFileContentWorker(json, /*sourceFile*/ undefined, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions); + } + ts.parseJsonConfigFileContent = parseJsonConfigFileContent; + /** + * Parse the contents of a config file (tsconfig.json). + * @param jsonNode The contents of the config file to parse + * @param host Instance of ParseConfigHost used to enumerate files in folder. + * @param basePath A root directory to resolve relative path entries in the config + * file to. e.g. outDir + */ + function parseJsonSourceFileConfigFileContent(sourceFile, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions) { + return parseJsonConfigFileContentWorker(/*json*/ undefined, sourceFile, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions); + } + ts.parseJsonSourceFileConfigFileContent = parseJsonSourceFileConfigFileContent; + /*@internal*/ + function setConfigFileInOptions(options, configFile) { + if (configFile) { + Object.defineProperty(options, "configFile", { enumerable: false, writable: false, value: configFile }); + } + } + ts.setConfigFileInOptions = setConfigFileInOptions; + function isNullOrUndefined(x) { + // tslint:disable-next-line:no-null-keyword + return x === undefined || x === null; + } + function directoryOfCombinedPath(fileName, basePath) { + // Use the `getNormalizedAbsolutePath` function to avoid canonicalizing the path, as it must remain noncanonical + // until consistient casing errors are reported + return ts.getDirectoryPath(ts.getNormalizedAbsolutePath(fileName, basePath)); + } + /** + * Parse the contents of a config file from json or json source file (tsconfig.json). + * @param json The contents of the config file to parse + * @param sourceFile sourceFile corresponding to the Json + * @param host Instance of ParseConfigHost used to enumerate files in folder. + * @param basePath A root directory to resolve relative path entries in the config + * file to. e.g. outDir + * @param resolutionStack Only present for backwards-compatibility. Should be empty. + */ + function parseJsonConfigFileContentWorker(json, sourceFile, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions) { + if (existingOptions === void 0) { existingOptions = {}; } + if (resolutionStack === void 0) { resolutionStack = []; } + if (extraFileExtensions === void 0) { extraFileExtensions = []; } + ts.Debug.assert((json === undefined && sourceFile !== undefined) || (json !== undefined && sourceFile === undefined)); + var errors = []; + var parsedConfig = parseConfig(json, sourceFile, host, basePath, configFileName, resolutionStack, errors); + var raw = parsedConfig.raw; + var options = ts.extend(existingOptions, parsedConfig.options || {}); + options.configFilePath = configFileName && ts.normalizeSlashes(configFileName); + setConfigFileInOptions(options, sourceFile); + var projectReferences; + var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories, spec = _a.spec; + return { + options: options, + fileNames: fileNames, + projectReferences: projectReferences, + typeAcquisition: parsedConfig.typeAcquisition || getDefaultTypeAcquisition(), + raw: raw, + errors: errors, + wildcardDirectories: wildcardDirectories, + compileOnSave: !!raw.compileOnSave, + configFileSpecs: spec + }; + function getFileNames() { + var filesSpecs; + if (ts.hasProperty(raw, "files") && !isNullOrUndefined(raw.files)) { + if (ts.isArray(raw.files)) { + filesSpecs = raw.files; + var hasReferences = ts.hasProperty(raw, "references") && !isNullOrUndefined(raw.references); + var hasZeroOrNoReferences = !hasReferences || raw.references.length === 0; + var hasExtends = ts.hasProperty(raw, "extends"); + if (filesSpecs.length === 0 && hasZeroOrNoReferences && !hasExtends) { + if (sourceFile) { + var fileName = configFileName || "tsconfig.json"; + var diagnosticMessage = ts.Diagnostics.The_files_list_in_config_file_0_is_empty; + var nodeValue = ts.firstDefined(ts.getTsConfigPropArray(sourceFile, "files"), function (property) { return property.initializer; }); + var error = nodeValue + ? ts.createDiagnosticForNodeInSourceFile(sourceFile, nodeValue, diagnosticMessage, fileName) + : ts.createCompilerDiagnostic(diagnosticMessage, fileName); + errors.push(error); + } + else { + createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json"); + } + } + } + else { + createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "files", "Array"); + } + } + var includeSpecs; + if (ts.hasProperty(raw, "include") && !isNullOrUndefined(raw.include)) { + if (ts.isArray(raw.include)) { + includeSpecs = raw.include; + } + else { + createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "include", "Array"); + } + } + var excludeSpecs; + if (ts.hasProperty(raw, "exclude") && !isNullOrUndefined(raw.exclude)) { + if (ts.isArray(raw.exclude)) { + excludeSpecs = raw.exclude; + } + else { + createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "exclude", "Array"); + } + } + else if (raw.compilerOptions) { + var outDir = raw.compilerOptions.outDir; + var declarationDir = raw.compilerOptions.declarationDir; + if (outDir || declarationDir) { + excludeSpecs = [outDir, declarationDir].filter(function (d) { return !!d; }); + } + } + if (filesSpecs === undefined && includeSpecs === undefined) { + includeSpecs = ["**/*"]; + } + var result = matchFileNames(filesSpecs, includeSpecs, excludeSpecs, configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath, options, host, errors, extraFileExtensions, sourceFile); + if (shouldReportNoInputFiles(result, canJsonReportNoInutFiles(raw), resolutionStack)) { + errors.push(getErrorForNoInputFiles(result.spec, configFileName)); + } + if (ts.hasProperty(raw, "references") && !isNullOrUndefined(raw.references)) { + if (ts.isArray(raw.references)) { + for (var _i = 0, _a = raw.references; _i < _a.length; _i++) { + var ref = _a[_i]; + if (typeof ref.path !== "string") { + createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "reference.path", "string"); + } + else { + (projectReferences || (projectReferences = [])).push({ + path: ts.getNormalizedAbsolutePath(ref.path, basePath), + originalPath: ref.path, + prepend: ref.prepend, + circular: ref.circular + }); + } + } + } + else { + createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "references", "Array"); + } + } + return result; + } + function createCompilerDiagnosticOnlyIfJson(message, arg0, arg1) { + if (!sourceFile) { + errors.push(ts.createCompilerDiagnostic(message, arg0, arg1)); + } + } + } + function isErrorNoInputFiles(error) { + return error.code === ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2.code; + } + function getErrorForNoInputFiles(_a, configFileName) { + var includeSpecs = _a.includeSpecs, excludeSpecs = _a.excludeSpecs; + return ts.createCompilerDiagnostic(ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2, configFileName || "tsconfig.json", JSON.stringify(includeSpecs || []), JSON.stringify(excludeSpecs || [])); + } + function shouldReportNoInputFiles(result, canJsonReportNoInutFiles, resolutionStack) { + return result.fileNames.length === 0 && canJsonReportNoInutFiles && (!resolutionStack || resolutionStack.length === 0); + } + /*@internal*/ + function canJsonReportNoInutFiles(raw) { + return !ts.hasProperty(raw, "files") && !ts.hasProperty(raw, "references"); + } + ts.canJsonReportNoInutFiles = canJsonReportNoInutFiles; + /*@internal*/ + function updateErrorForNoInputFiles(result, configFileName, configFileSpecs, configParseDiagnostics, canJsonReportNoInutFiles) { + var existingErrors = configParseDiagnostics.length; + if (shouldReportNoInputFiles(result, canJsonReportNoInutFiles)) { + configParseDiagnostics.push(getErrorForNoInputFiles(configFileSpecs, configFileName)); + } + else { + ts.filterMutate(configParseDiagnostics, function (error) { return !isErrorNoInputFiles(error); }); + } + return existingErrors !== configParseDiagnostics.length; + } + ts.updateErrorForNoInputFiles = updateErrorForNoInputFiles; + function isSuccessfulParsedTsconfig(value) { + return !!value.options; + } + /** + * This *just* extracts options/include/exclude/files out of a config file. + * It does *not* resolve the included files. + */ + function parseConfig(json, sourceFile, host, basePath, configFileName, resolutionStack, errors) { + basePath = ts.normalizeSlashes(basePath); + var resolvedPath = ts.getNormalizedAbsolutePath(configFileName || "", basePath); + if (resolutionStack.indexOf(resolvedPath) >= 0) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Circularity_detected_while_resolving_configuration_Colon_0, resolutionStack.concat([resolvedPath]).join(" -> "))); + return { raw: json || convertToObject(sourceFile, errors) }; + } + var ownConfig = json ? + parseOwnConfigOfJson(json, host, basePath, configFileName, errors) : + parseOwnConfigOfJsonSourceFile(sourceFile, host, basePath, configFileName, errors); + if (ownConfig.extendedConfigPath) { + // copy the resolution stack so it is never reused between branches in potential diamond-problem scenarios. + resolutionStack = resolutionStack.concat([resolvedPath]); + var extendedConfig = getExtendedConfig(sourceFile, ownConfig.extendedConfigPath, host, basePath, resolutionStack, errors); + if (extendedConfig && isSuccessfulParsedTsconfig(extendedConfig)) { + var baseRaw_1 = extendedConfig.raw; + var raw_1 = ownConfig.raw; + var setPropertyInRawIfNotUndefined = function (propertyName) { + var value = raw_1[propertyName] || baseRaw_1[propertyName]; + if (value) { + raw_1[propertyName] = value; + } + }; + setPropertyInRawIfNotUndefined("include"); + setPropertyInRawIfNotUndefined("exclude"); + setPropertyInRawIfNotUndefined("files"); + if (raw_1.compileOnSave === undefined) { + raw_1.compileOnSave = baseRaw_1.compileOnSave; + } + ownConfig.options = ts.assign({}, extendedConfig.options, ownConfig.options); + // TODO extend type typeAcquisition + } + } + return ownConfig; + } + function parseOwnConfigOfJson(json, host, basePath, configFileName, errors) { + if (ts.hasProperty(json, "excludes")) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude)); + } + var options = convertCompilerOptionsFromJsonWorker(json.compilerOptions, basePath, errors, configFileName); + // typingOptions has been deprecated and is only supported for backward compatibility purposes. + // It should be removed in future releases - use typeAcquisition instead. + var typeAcquisition = convertTypeAcquisitionFromJsonWorker(json.typeAcquisition || json.typingOptions, basePath, errors, configFileName); + json.compileOnSave = convertCompileOnSaveOptionFromJson(json, basePath, errors); + var extendedConfigPath; + if (json.extends) { + if (!ts.isString(json.extends)) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "extends", "string")); + } + else { + var newBase = configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath; + extendedConfigPath = getExtendsConfigPath(json.extends, host, newBase, errors, ts.createCompilerDiagnostic); + } + } + return { raw: json, options: options, typeAcquisition: typeAcquisition, extendedConfigPath: extendedConfigPath }; + } + function parseOwnConfigOfJsonSourceFile(sourceFile, host, basePath, configFileName, errors) { + var options = getDefaultCompilerOptions(configFileName); + var typeAcquisition, typingOptionstypeAcquisition; + var extendedConfigPath; + var optionsIterator = { + onSetValidOptionKeyValueInParent: function (parentOption, option, value) { + ts.Debug.assert(parentOption === "compilerOptions" || parentOption === "typeAcquisition" || parentOption === "typingOptions"); + var currentOption = parentOption === "compilerOptions" ? + options : + parentOption === "typeAcquisition" ? + (typeAcquisition || (typeAcquisition = getDefaultTypeAcquisition(configFileName))) : + (typingOptionstypeAcquisition || (typingOptionstypeAcquisition = getDefaultTypeAcquisition(configFileName))); + currentOption[option.name] = normalizeOptionValue(option, basePath, value); + }, + onSetValidOptionKeyValueInRoot: function (key, _keyNode, value, valueNode) { + switch (key) { + case "extends": + var newBase = configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath; + extendedConfigPath = getExtendsConfigPath(value, host, newBase, errors, function (message, arg0) { + return ts.createDiagnosticForNodeInSourceFile(sourceFile, valueNode, message, arg0); + }); + return; + } + }, + onSetUnknownOptionKeyValueInRoot: function (key, keyNode, _value, _valueNode) { + if (key === "excludes") { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, keyNode, ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude)); + } + } + }; + var json = convertToObjectWorker(sourceFile, errors, /*returnValue*/ true, getTsconfigRootOptionsMap(), optionsIterator); + if (!typeAcquisition) { + if (typingOptionstypeAcquisition) { + typeAcquisition = (typingOptionstypeAcquisition.enableAutoDiscovery !== undefined) ? + { + enable: typingOptionstypeAcquisition.enableAutoDiscovery, + include: typingOptionstypeAcquisition.include, + exclude: typingOptionstypeAcquisition.exclude + } : + typingOptionstypeAcquisition; + } + else { + typeAcquisition = getDefaultTypeAcquisition(configFileName); + } + } + return { raw: json, options: options, typeAcquisition: typeAcquisition, extendedConfigPath: extendedConfigPath }; + } + function getExtendsConfigPath(extendedConfig, host, basePath, errors, createDiagnostic) { + extendedConfig = ts.normalizeSlashes(extendedConfig); + if (ts.isRootedDiskPath(extendedConfig) || ts.startsWith(extendedConfig, "./") || ts.startsWith(extendedConfig, "../")) { + var extendedConfigPath = ts.getNormalizedAbsolutePath(extendedConfig, basePath); + if (!host.fileExists(extendedConfigPath) && !ts.endsWith(extendedConfigPath, ".json" /* Json */)) { + extendedConfigPath = extendedConfigPath + ".json"; + if (!host.fileExists(extendedConfigPath)) { + errors.push(createDiagnostic(ts.Diagnostics.File_0_does_not_exist, extendedConfig)); + return undefined; + } + } + return extendedConfigPath; + } + // If the path isn't a rooted or relative path, resolve like a module + var resolved = ts.nodeModuleNameResolver(extendedConfig, ts.combinePaths(basePath, "tsconfig.json"), { moduleResolution: ts.ModuleResolutionKind.NodeJs }, host, /*cache*/ undefined, /*projectRefs*/ undefined, /*lookupConfig*/ true); + if (resolved.resolvedModule) { + return resolved.resolvedModule.resolvedFileName; + } + errors.push(createDiagnostic(ts.Diagnostics.File_0_does_not_exist, extendedConfig)); + return undefined; + } + function getExtendedConfig(sourceFile, extendedConfigPath, host, basePath, resolutionStack, errors) { + var _a; + var extendedResult = readJsonConfigFile(extendedConfigPath, function (path) { return host.readFile(path); }); + if (sourceFile) { + sourceFile.extendedSourceFiles = [extendedResult.fileName]; + } + if (extendedResult.parseDiagnostics.length) { + errors.push.apply(errors, extendedResult.parseDiagnostics); + return undefined; + } + var extendedDirname = ts.getDirectoryPath(extendedConfigPath); + var extendedConfig = parseConfig(/*json*/ undefined, extendedResult, host, extendedDirname, ts.getBaseFileName(extendedConfigPath), resolutionStack, errors); + if (sourceFile && extendedResult.extendedSourceFiles) { + (_a = sourceFile.extendedSourceFiles).push.apply(_a, extendedResult.extendedSourceFiles); + } + if (isSuccessfulParsedTsconfig(extendedConfig)) { + // Update the paths to reflect base path + var relativeDifference_1 = ts.convertToRelativePath(extendedDirname, basePath, ts.identity); + var updatePath_1 = function (path) { return ts.isRootedDiskPath(path) ? path : ts.combinePaths(relativeDifference_1, path); }; + var mapPropertiesInRawIfNotUndefined = function (propertyName) { + if (raw_2[propertyName]) { + raw_2[propertyName] = ts.map(raw_2[propertyName], updatePath_1); + } + }; + var raw_2 = extendedConfig.raw; + mapPropertiesInRawIfNotUndefined("include"); + mapPropertiesInRawIfNotUndefined("exclude"); + mapPropertiesInRawIfNotUndefined("files"); + } + return extendedConfig; + } + function convertCompileOnSaveOptionFromJson(jsonOption, basePath, errors) { + if (!ts.hasProperty(jsonOption, ts.compileOnSaveCommandLineOption.name)) { + return false; + } + var result = convertJsonOption(ts.compileOnSaveCommandLineOption, jsonOption.compileOnSave, basePath, errors); + return typeof result === "boolean" && result; + } + function convertCompilerOptionsFromJson(jsonOptions, basePath, configFileName) { + var errors = []; + var options = convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName); + return { options: options, errors: errors }; + } + ts.convertCompilerOptionsFromJson = convertCompilerOptionsFromJson; + function convertTypeAcquisitionFromJson(jsonOptions, basePath, configFileName) { + var errors = []; + var options = convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName); + return { options: options, errors: errors }; + } + ts.convertTypeAcquisitionFromJson = convertTypeAcquisitionFromJson; + function getDefaultCompilerOptions(configFileName) { + var options = configFileName && ts.getBaseFileName(configFileName) === "jsconfig.json" + ? { allowJs: true, maxNodeModuleJsDepth: 2, allowSyntheticDefaultImports: true, skipLibCheck: true, noEmit: true } + : {}; + return options; + } + function convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName) { + var options = getDefaultCompilerOptions(configFileName); + convertOptionsFromJson(ts.optionDeclarations, jsonOptions, basePath, options, ts.Diagnostics.Unknown_compiler_option_0, errors); + if (configFileName) { + options.configFilePath = ts.normalizeSlashes(configFileName); + } + return options; + } + function getDefaultTypeAcquisition(configFileName) { + return { enable: !!configFileName && ts.getBaseFileName(configFileName) === "jsconfig.json", include: [], exclude: [] }; + } + function convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName) { + var options = getDefaultTypeAcquisition(configFileName); + var typeAcquisition = convertEnableAutoDiscoveryToEnable(jsonOptions); + convertOptionsFromJson(ts.typeAcquisitionDeclarations, typeAcquisition, basePath, options, ts.Diagnostics.Unknown_type_acquisition_option_0, errors); + return options; + } + function convertOptionsFromJson(optionDeclarations, jsonOptions, basePath, defaultOptions, diagnosticMessage, errors) { + if (!jsonOptions) { + return; + } + var optionNameMap = commandLineOptionsToMap(optionDeclarations); + for (var id in jsonOptions) { + var opt = optionNameMap.get(id); + if (opt) { + defaultOptions[opt.name] = convertJsonOption(opt, jsonOptions[id], basePath, errors); + } + else { + errors.push(ts.createCompilerDiagnostic(diagnosticMessage, id)); + } + } + } + function convertJsonOption(opt, value, basePath, errors) { + if (isCompilerOptionsValue(opt, value)) { + var optType = opt.type; + if (optType === "list" && ts.isArray(value)) { + return convertJsonOptionOfListType(opt, value, basePath, errors); + } + else if (!ts.isString(optType)) { + return convertJsonOptionOfCustomType(opt, value, errors); + } + return normalizeNonListOptionValue(opt, basePath, value); + } + else { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, opt.name, getCompilerOptionValueTypeString(opt))); + } + } + function normalizeOptionValue(option, basePath, value) { + if (isNullOrUndefined(value)) + return undefined; + if (option.type === "list") { + var listOption_1 = option; + if (listOption_1.element.isFilePath || !ts.isString(listOption_1.element.type)) { + return ts.filter(ts.map(value, function (v) { return normalizeOptionValue(listOption_1.element, basePath, v); }), function (v) { return !!v; }); + } + return value; + } + else if (!ts.isString(option.type)) { + return option.type.get(ts.isString(value) ? value.toLowerCase() : value); + } + return normalizeNonListOptionValue(option, basePath, value); + } + function normalizeNonListOptionValue(option, basePath, value) { + if (option.isFilePath) { + value = ts.normalizePath(ts.combinePaths(basePath, value)); + if (value === "") { + value = "."; + } + } + return value; + } + function convertJsonOptionOfCustomType(opt, value, errors) { + if (isNullOrUndefined(value)) + return undefined; + var key = value.toLowerCase(); + var val = opt.type.get(key); + if (val !== undefined) { + return val; + } + else { + errors.push(createCompilerDiagnosticForInvalidCustomType(opt)); + } + } + function convertJsonOptionOfListType(option, values, basePath, errors) { + return ts.filter(ts.map(values, function (v) { return convertJsonOption(option.element, v, basePath, errors); }), function (v) { return !!v; }); + } + function trimString(s) { + return typeof s.trim === "function" ? s.trim() : s.replace(/^[\s]+|[\s]+$/g, ""); + } + /** + * Tests for a path that ends in a recursive directory wildcard. + * Matches **, \**, **\, and \**\, but not a**b. + * + * NOTE: used \ in place of / above to avoid issues with multiline comments. + * + * Breakdown: + * (^|\/) # matches either the beginning of the string or a directory separator. + * \*\* # matches the recursive directory wildcard "**". + * \/?$ # matches an optional trailing directory separator at the end of the string. + */ + var invalidTrailingRecursionPattern = /(^|\/)\*\*\/?$/; + /** + * Tests for a path where .. appears after a recursive directory wildcard. + * Matches **\..\*, **\a\..\*, and **\.., but not ..\**\* + * + * NOTE: used \ in place of / above to avoid issues with multiline comments. + * + * Breakdown: + * (^|\/) # matches either the beginning of the string or a directory separator. + * \*\*\/ # matches a recursive directory wildcard "**" followed by a directory separator. + * (.*\/)? # optionally matches any number of characters followed by a directory separator. + * \.\. # matches a parent directory path component ".." + * ($|\/) # matches either the end of the string or a directory separator. + */ + var invalidDotDotAfterRecursiveWildcardPattern = /(^|\/)\*\*\/(.*\/)?\.\.($|\/)/; + /** + * Tests for a path containing a wildcard character in a directory component of the path. + * Matches \*\, \?\, and \a*b\, but not \a\ or \a\*. + * + * NOTE: used \ in place of / above to avoid issues with multiline comments. + * + * Breakdown: + * \/ # matches a directory separator. + * [^/]*? # matches any number of characters excluding directory separators (non-greedy). + * [*?] # matches either a wildcard character (* or ?) + * [^/]* # matches any number of characters excluding directory separators (greedy). + * \/ # matches a directory separator. + */ + var watchRecursivePattern = /\/[^/]*?[*?][^/]*\//; + /** + * Matches the portion of a wildcard path that does not contain wildcards. + * Matches \a of \a\*, or \a\b\c of \a\b\c\?\d. + * + * NOTE: used \ in place of / above to avoid issues with multiline comments. + * + * Breakdown: + * ^ # matches the beginning of the string + * [^*?]* # matches any number of non-wildcard characters + * (?=\/[^/]*[*?]) # lookahead that matches a directory separator followed by + * # a path component that contains at least one wildcard character (* or ?). + */ + var wildcardDirectoryPattern = /^[^*?]*(?=\/[^/]*[*?])/; + /** + * Expands an array of file specifications. + * + * @param filesSpecs The literal file names to include. + * @param includeSpecs The wildcard file specifications to include. + * @param excludeSpecs The wildcard file specifications to exclude. + * @param basePath The base path for any relative file specifications. + * @param options Compiler options. + * @param host The host used to resolve files and directories. + * @param errors An array for diagnostic reporting. + */ + function matchFileNames(filesSpecs, includeSpecs, excludeSpecs, basePath, options, host, errors, extraFileExtensions, jsonSourceFile) { + basePath = ts.normalizePath(basePath); + var validatedIncludeSpecs, validatedExcludeSpecs; + // The exclude spec list is converted into a regular expression, which allows us to quickly + // test whether a file or directory should be excluded before recursively traversing the + // file system. + if (includeSpecs) { + validatedIncludeSpecs = validateSpecs(includeSpecs, errors, /*allowTrailingRecursion*/ false, jsonSourceFile, "include"); + } + if (excludeSpecs) { + validatedExcludeSpecs = validateSpecs(excludeSpecs, errors, /*allowTrailingRecursion*/ true, jsonSourceFile, "exclude"); + } + // Wildcard directories (provided as part of a wildcard path) are stored in a + // file map that marks whether it was a regular wildcard match (with a `*` or `?` token), + // or a recursive directory. This information is used by filesystem watchers to monitor for + // new entries in these paths. + var wildcardDirectories = getWildcardDirectories(validatedIncludeSpecs, validatedExcludeSpecs, basePath, host.useCaseSensitiveFileNames); + var spec = { filesSpecs: filesSpecs, includeSpecs: includeSpecs, excludeSpecs: excludeSpecs, validatedIncludeSpecs: validatedIncludeSpecs, validatedExcludeSpecs: validatedExcludeSpecs, wildcardDirectories: wildcardDirectories }; + return getFileNamesFromConfigSpecs(spec, basePath, options, host, extraFileExtensions); + } + /** + * Gets the file names from the provided config file specs that contain, files, include, exclude and + * other properties needed to resolve the file names + * @param spec The config file specs extracted with file names to include, wildcards to include/exclude and other details + * @param basePath The base path for any relative file specifications. + * @param options Compiler options. + * @param host The host used to resolve files and directories. + * @param extraFileExtensions optionaly file extra file extension information from host + */ + /* @internal */ + function getFileNamesFromConfigSpecs(spec, basePath, options, host, extraFileExtensions) { + if (extraFileExtensions === void 0) { extraFileExtensions = []; } + basePath = ts.normalizePath(basePath); + var keyMapper = host.useCaseSensitiveFileNames ? ts.identity : ts.toLowerCase; + // Literal file names (provided via the "files" array in tsconfig.json) are stored in a + // file map with a possibly case insensitive key. We use this map later when when including + // wildcard paths. + var literalFileMap = ts.createMap(); + // Wildcard paths (provided via the "includes" array in tsconfig.json) are stored in a + // file map with a possibly case insensitive key. We use this map to store paths matched + // via wildcard, and to handle extension priority. + var wildcardFileMap = ts.createMap(); + // Wildcard paths of json files (provided via the "includes" array in tsconfig.json) are stored in a + // file map with a possibly case insensitive key. We use this map to store paths matched + // via wildcard of *.json kind + var wildCardJsonFileMap = ts.createMap(); + var filesSpecs = spec.filesSpecs, validatedIncludeSpecs = spec.validatedIncludeSpecs, validatedExcludeSpecs = spec.validatedExcludeSpecs, wildcardDirectories = spec.wildcardDirectories; + // Rather than requery this for each file and filespec, we query the supported extensions + // once and store it on the expansion context. + var supportedExtensions = ts.getSupportedExtensions(options, extraFileExtensions); + var supportedExtensionsWithJsonIfResolveJsonModule = ts.getSuppoertedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions); + // Literal files are always included verbatim. An "include" or "exclude" specification cannot + // remove a literal file. + if (filesSpecs) { + for (var _i = 0, filesSpecs_1 = filesSpecs; _i < filesSpecs_1.length; _i++) { + var fileName = filesSpecs_1[_i]; + var file = ts.getNormalizedAbsolutePath(fileName, basePath); + literalFileMap.set(keyMapper(file), file); + } + } + var jsonOnlyIncludeRegexes; + if (validatedIncludeSpecs && validatedIncludeSpecs.length > 0) { + var _loop_4 = function (file) { + if (ts.fileExtensionIs(file, ".json" /* Json */)) { + // Valid only if *.json specified + if (!jsonOnlyIncludeRegexes) { + var includes = validatedIncludeSpecs.filter(function (s) { return ts.endsWith(s, ".json" /* Json */); }); + var includeFilePatterns = ts.map(ts.getRegularExpressionsForWildcards(includes, basePath, "files"), function (pattern) { return "^" + pattern + "$"; }); + jsonOnlyIncludeRegexes = includeFilePatterns ? includeFilePatterns.map(function (pattern) { return ts.getRegexFromPattern(pattern, host.useCaseSensitiveFileNames); }) : ts.emptyArray; + } + var includeIndex = ts.findIndex(jsonOnlyIncludeRegexes, function (re) { return re.test(file); }); + if (includeIndex !== -1) { + var key_1 = keyMapper(file); + if (!literalFileMap.has(key_1) && !wildCardJsonFileMap.has(key_1)) { + wildCardJsonFileMap.set(key_1, file); + } + } + return "continue"; + } + // If we have already included a literal or wildcard path with a + // higher priority extension, we should skip this file. + // + // This handles cases where we may encounter both .ts and + // .d.ts (or .js if "allowJs" is enabled) in the same + // directory when they are compilation outputs. + if (hasFileWithHigherPriorityExtension(file, literalFileMap, wildcardFileMap, supportedExtensions, keyMapper)) { + return "continue"; + } + // We may have included a wildcard path with a lower priority + // extension due to the user-defined order of entries in the + // "include" array. If there is a lower priority extension in the + // same directory, we should remove it. + removeWildcardFilesWithLowerPriorityExtension(file, wildcardFileMap, supportedExtensions, keyMapper); + var key = keyMapper(file); + if (!literalFileMap.has(key) && !wildcardFileMap.has(key)) { + wildcardFileMap.set(key, file); + } + }; + for (var _a = 0, _b = host.readDirectory(basePath, supportedExtensionsWithJsonIfResolveJsonModule, validatedExcludeSpecs, validatedIncludeSpecs, /*depth*/ undefined); _a < _b.length; _a++) { + var file = _b[_a]; + _loop_4(file); + } + } + var literalFiles = ts.arrayFrom(literalFileMap.values()); + var wildcardFiles = ts.arrayFrom(wildcardFileMap.values()); + return { + fileNames: literalFiles.concat(wildcardFiles, ts.arrayFrom(wildCardJsonFileMap.values())), + wildcardDirectories: wildcardDirectories, + spec: spec + }; + } + ts.getFileNamesFromConfigSpecs = getFileNamesFromConfigSpecs; + function validateSpecs(specs, errors, allowTrailingRecursion, jsonSourceFile, specKey) { + return specs.filter(function (spec) { + var diag = specToDiagnostic(spec, allowTrailingRecursion); + if (diag !== undefined) { + errors.push(createDiagnostic(diag, spec)); + } + return diag === undefined; + }); + function createDiagnostic(message, spec) { + var element = ts.getTsConfigPropArrayElementValue(jsonSourceFile, specKey, spec); + return element ? + ts.createDiagnosticForNodeInSourceFile(jsonSourceFile, element, message, spec) : + ts.createCompilerDiagnostic(message, spec); + } + } + function specToDiagnostic(spec, allowTrailingRecursion) { + if (!allowTrailingRecursion && invalidTrailingRecursionPattern.test(spec)) { + return ts.Diagnostics.File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0; + } + else if (invalidDotDotAfterRecursiveWildcardPattern.test(spec)) { + return ts.Diagnostics.File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0; + } + } + /** + * Gets directories in a set of include patterns that should be watched for changes. + */ + function getWildcardDirectories(include, exclude, path, useCaseSensitiveFileNames) { + // We watch a directory recursively if it contains a wildcard anywhere in a directory segment + // of the pattern: + // + // /a/b/**/d - Watch /a/b recursively to catch changes to any d in any subfolder recursively + // /a/b/*/d - Watch /a/b recursively to catch any d in any immediate subfolder, even if a new subfolder is added + // /a/b - Watch /a/b recursively to catch changes to anything in any recursive subfoler + // + // We watch a directory without recursion if it contains a wildcard in the file segment of + // the pattern: + // + // /a/b/* - Watch /a/b directly to catch any new file + // /a/b/a?z - Watch /a/b directly to catch any new file matching a?z + var rawExcludeRegex = ts.getRegularExpressionForWildcard(exclude, path, "exclude"); + var excludeRegex = rawExcludeRegex && new RegExp(rawExcludeRegex, useCaseSensitiveFileNames ? "" : "i"); + var wildcardDirectories = {}; + if (include !== undefined) { + var recursiveKeys = []; + for (var _i = 0, include_1 = include; _i < include_1.length; _i++) { + var file = include_1[_i]; + var spec = ts.normalizePath(ts.combinePaths(path, file)); + if (excludeRegex && excludeRegex.test(spec)) { + continue; + } + var match = getWildcardDirectoryFromSpec(spec, useCaseSensitiveFileNames); + if (match) { + var key = match.key, flags = match.flags; + var existingFlags = wildcardDirectories[key]; + if (existingFlags === undefined || existingFlags < flags) { + wildcardDirectories[key] = flags; + if (flags === 1 /* Recursive */) { + recursiveKeys.push(key); + } + } + } + } + // Remove any subpaths under an existing recursively watched directory. + for (var key in wildcardDirectories) { + if (ts.hasProperty(wildcardDirectories, key)) { + for (var _a = 0, recursiveKeys_1 = recursiveKeys; _a < recursiveKeys_1.length; _a++) { + var recursiveKey = recursiveKeys_1[_a]; + if (key !== recursiveKey && ts.containsPath(recursiveKey, key, path, !useCaseSensitiveFileNames)) { + delete wildcardDirectories[key]; + } + } + } + } + } + return wildcardDirectories; + } + function getWildcardDirectoryFromSpec(spec, useCaseSensitiveFileNames) { + var match = wildcardDirectoryPattern.exec(spec); + if (match) { + return { + key: useCaseSensitiveFileNames ? match[0] : match[0].toLowerCase(), + flags: watchRecursivePattern.test(spec) ? 1 /* Recursive */ : 0 /* None */ + }; + } + if (ts.isImplicitGlob(spec)) { + return { key: spec, flags: 1 /* Recursive */ }; + } + return undefined; + } + /** + * Determines whether a literal or wildcard file has already been included that has a higher + * extension priority. + * + * @param file The path to the file. + * @param extensionPriority The priority of the extension. + * @param context The expansion context. + */ + function hasFileWithHigherPriorityExtension(file, literalFiles, wildcardFiles, extensions, keyMapper) { + var extensionPriority = ts.getExtensionPriority(file, extensions); + var adjustedExtensionPriority = ts.adjustExtensionPriority(extensionPriority, extensions); + for (var i = 0 /* Highest */; i < adjustedExtensionPriority; i++) { + var higherPriorityExtension = extensions[i]; + var higherPriorityPath = keyMapper(ts.changeExtension(file, higherPriorityExtension)); + if (literalFiles.has(higherPriorityPath) || wildcardFiles.has(higherPriorityPath)) { + return true; + } + } + return false; + } + /** + * Removes files included via wildcard expansion with a lower extension priority that have + * already been included. + * + * @param file The path to the file. + * @param extensionPriority The priority of the extension. + * @param context The expansion context. + */ + function removeWildcardFilesWithLowerPriorityExtension(file, wildcardFiles, extensions, keyMapper) { + var extensionPriority = ts.getExtensionPriority(file, extensions); + var nextExtensionPriority = ts.getNextLowestExtensionPriority(extensionPriority, extensions); + for (var i = nextExtensionPriority; i < extensions.length; i++) { + var lowerPriorityExtension = extensions[i]; + var lowerPriorityPath = keyMapper(ts.changeExtension(file, lowerPriorityExtension)); + wildcardFiles.delete(lowerPriorityPath); + } + } + /** + * Produces a cleaned version of compiler options with personally identifying info (aka, paths) removed. + * Also converts enum values back to strings. + */ + /* @internal */ + function convertCompilerOptionsForTelemetry(opts) { + var out = {}; + for (var key in opts) { + if (opts.hasOwnProperty(key)) { + var type = getOptionFromName(key); + if (type !== undefined) { // Ignore unknown options + out[key] = getOptionValueWithEmptyStrings(opts[key], type); + } + } + } + return out; + } + ts.convertCompilerOptionsForTelemetry = convertCompilerOptionsForTelemetry; + function getOptionValueWithEmptyStrings(value, option) { + switch (option.type) { + case "object": // "paths". Can't get any useful information from the value since we blank out strings, so just return "". + return ""; + case "string": // Could be any arbitrary string -- use empty string instead. + return ""; + case "number": // Allow numbers, but be sure to check it's actually a number. + return typeof value === "number" ? value : ""; + case "boolean": + return typeof value === "boolean" ? value : ""; + case "list": + var elementType_1 = option.element; + return ts.isArray(value) ? value.map(function (v) { return getOptionValueWithEmptyStrings(v, elementType_1); }) : ""; + default: + return ts.forEachEntry(option.type, function (optionEnumValue, optionStringValue) { + if (optionEnumValue === value) { + return optionStringValue; + } + }); // TODO: GH#18217 + } + } +})(ts || (ts = {})); +var ts; +(function (ts) { + function trace(host) { + host.trace(ts.formatMessage.apply(undefined, arguments)); + } + ts.trace = trace; + /* @internal */ + function isTraceEnabled(compilerOptions, host) { + return !!compilerOptions.traceResolution && host.trace !== undefined; + } + ts.isTraceEnabled = isTraceEnabled; + function withPackageId(packageId, r) { + return r && { path: r.path, extension: r.ext, packageId: packageId }; + } + function noPackageId(r) { + return withPackageId(/*packageId*/ undefined, r); + } + function removeIgnoredPackageId(r) { + if (r) { + ts.Debug.assert(r.packageId === undefined); + return { path: r.path, ext: r.extension }; + } + } + /** + * Kinds of file that we are currently looking for. + * Typically there is one pass with Extensions.TypeScript, then a second pass with Extensions.JavaScript. + */ + var Extensions; + (function (Extensions) { + Extensions[Extensions["TypeScript"] = 0] = "TypeScript"; + Extensions[Extensions["JavaScript"] = 1] = "JavaScript"; + Extensions[Extensions["Json"] = 2] = "Json"; + Extensions[Extensions["TSConfig"] = 3] = "TSConfig"; + Extensions[Extensions["DtsOnly"] = 4] = "DtsOnly"; /** Only '.d.ts' */ + })(Extensions || (Extensions = {})); + /** Used with `Extensions.DtsOnly` to extract the path from TypeScript results. */ + function resolvedTypeScriptOnly(resolved) { + if (!resolved) { + return undefined; + } + ts.Debug.assert(ts.extensionIsTS(resolved.extension)); + return { fileName: resolved.path, packageId: resolved.packageId }; + } + function createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations) { + return { + resolvedModule: resolved && { resolvedFileName: resolved.path, originalPath: resolved.originalPath === true ? undefined : resolved.originalPath, extension: resolved.extension, isExternalLibraryImport: isExternalLibraryImport, packageId: resolved.packageId }, + failedLookupLocations: failedLookupLocations + }; + } + function readPackageJsonField(jsonContent, fieldName, typeOfTag, state) { + if (!ts.hasProperty(jsonContent, fieldName)) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_does_not_have_a_0_field, fieldName); + } + return; + } + var value = jsonContent[fieldName]; + if (typeof value !== typeOfTag || value === null) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_1_got_2, fieldName, typeOfTag, value === null ? "null" : typeof value); + } + return; + } + return value; + } + function readPackageJsonPathField(jsonContent, fieldName, baseDirectory, state) { + var fileName = readPackageJsonField(jsonContent, fieldName, "string", state); + if (fileName === undefined) + return; + var path = ts.normalizePath(ts.combinePaths(baseDirectory, fileName)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, fileName, path); + } + return path; + } + function readPackageJsonTypesFields(jsonContent, baseDirectory, state) { + return readPackageJsonPathField(jsonContent, "typings", baseDirectory, state) + || readPackageJsonPathField(jsonContent, "types", baseDirectory, state); + } + function readPackageJsonTSConfigField(jsonContent, baseDirectory, state) { + return readPackageJsonPathField(jsonContent, "tsconfig", baseDirectory, state); + } + function readPackageJsonMainField(jsonContent, baseDirectory, state) { + return readPackageJsonPathField(jsonContent, "main", baseDirectory, state); + } + function readPackageJsonTypesVersionsField(jsonContent, state) { + var typesVersions = readPackageJsonField(jsonContent, "typesVersions", "object", state); + if (typesVersions === undefined) + return; + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_field_with_version_specific_path_mappings); + } + return typesVersions; + } + function readPackageJsonTypesVersionPaths(jsonContent, state) { + var typesVersions = readPackageJsonTypesVersionsField(jsonContent, state); + if (typesVersions === undefined) + return; + if (state.traceEnabled) { + for (var key in typesVersions) { + if (ts.hasProperty(typesVersions, key) && !ts.VersionRange.tryParse(key)) { + trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range, key); + } + } + } + var result = getPackageJsonTypesVersionsPaths(typesVersions); + if (!result) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_does_not_have_a_typesVersions_entry_that_matches_version_0, ts.versionMajorMinor); + } + return; + } + var bestVersionKey = result.version, bestVersionPaths = result.paths; + if (typeof bestVersionPaths !== "object") { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_1_got_2, "typesVersions['" + bestVersionKey + "']", "object", typeof bestVersionPaths); + } + return; + } + return result; + } + var typeScriptVersion; + /* @internal */ + function getPackageJsonTypesVersionsPaths(typesVersions) { + if (!typeScriptVersion) + typeScriptVersion = new ts.Version(ts.version); + for (var key in typesVersions) { + if (!ts.hasProperty(typesVersions, key)) + continue; + var keyRange = ts.VersionRange.tryParse(key); + if (keyRange === undefined) { + continue; + } + // return the first entry whose range matches the current compiler version. + if (keyRange.test(typeScriptVersion)) { + return { version: key, paths: typesVersions[key] }; + } + } + } + ts.getPackageJsonTypesVersionsPaths = getPackageJsonTypesVersionsPaths; + function getEffectiveTypeRoots(options, host) { + if (options.typeRoots) { + return options.typeRoots; + } + var currentDirectory; + if (options.configFilePath) { + currentDirectory = ts.getDirectoryPath(options.configFilePath); + } + else if (host.getCurrentDirectory) { + currentDirectory = host.getCurrentDirectory(); + } + if (currentDirectory !== undefined) { + return getDefaultTypeRoots(currentDirectory, host); + } + } + ts.getEffectiveTypeRoots = getEffectiveTypeRoots; + /** + * Returns the path to every node_modules/@types directory from some ancestor directory. + * Returns undefined if there are none. + */ + function getDefaultTypeRoots(currentDirectory, host) { + if (!host.directoryExists) { + return [ts.combinePaths(currentDirectory, nodeModulesAtTypes)]; + // And if it doesn't exist, tough. + } + var typeRoots; + ts.forEachAncestorDirectory(ts.normalizePath(currentDirectory), function (directory) { + var atTypes = ts.combinePaths(directory, nodeModulesAtTypes); + if (host.directoryExists(atTypes)) { + (typeRoots || (typeRoots = [])).push(atTypes); + } + return undefined; + }); + return typeRoots; + } + var nodeModulesAtTypes = ts.combinePaths("node_modules", "@types"); + /** + * @param {string | undefined} containingFile - file that contains type reference directive, can be undefined if containing file is unknown. + * This is possible in case if resolution is performed for directives specified via 'types' parameter. In this case initial path for secondary lookups + * is assumed to be the same as root directory of the project. + */ + function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host, redirectedReference) { + var traceEnabled = isTraceEnabled(options, host); + if (redirectedReference) { + options = redirectedReference.commandLine.options; + } + var failedLookupLocations = []; + var moduleResolutionState = { compilerOptions: options, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; + var typeRoots = getEffectiveTypeRoots(options, host); + if (traceEnabled) { + if (containingFile === undefined) { + if (typeRoots === undefined) { + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set, typeReferenceDirectiveName); + } + else { + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1, typeReferenceDirectiveName, typeRoots); + } + } + else { + if (typeRoots === undefined) { + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set, typeReferenceDirectiveName, containingFile); + } + else { + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_2, typeReferenceDirectiveName, containingFile, typeRoots); + } + } + if (redirectedReference) { + trace(host, ts.Diagnostics.Using_compiler_options_of_project_reference_redirect_0, redirectedReference.sourceFile.fileName); + } + } + var resolved = primaryLookup(); + var primary = true; + if (!resolved) { + resolved = secondaryLookup(); + primary = false; + } + var resolvedTypeReferenceDirective; + if (resolved) { + var fileName = resolved.fileName, packageId = resolved.packageId; + var resolvedFileName = options.preserveSymlinks ? fileName : realPath(fileName, host, traceEnabled); + if (traceEnabled) { + trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFileName, primary); + } + resolvedTypeReferenceDirective = { primary: primary, resolvedFileName: resolvedFileName, packageId: packageId, isExternalLibraryImport: pathContainsNodeModules(fileName) }; + } + return { resolvedTypeReferenceDirective: resolvedTypeReferenceDirective, failedLookupLocations: failedLookupLocations }; + function primaryLookup() { + // Check primary library paths + if (typeRoots && typeRoots.length) { + if (traceEnabled) { + trace(host, ts.Diagnostics.Resolving_with_primary_search_path_0, typeRoots.join(", ")); + } + return ts.firstDefined(typeRoots, function (typeRoot) { + var candidate = ts.combinePaths(typeRoot, typeReferenceDirectiveName); + var candidateDirectory = ts.getDirectoryPath(candidate); + var directoryExists = ts.directoryProbablyExists(candidateDirectory, host); + if (!directoryExists && traceEnabled) { + trace(host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, candidateDirectory); + } + return resolvedTypeScriptOnly(loadNodeModuleFromDirectory(Extensions.DtsOnly, candidate, !directoryExists, moduleResolutionState)); + }); + } + else { + if (traceEnabled) { + trace(host, ts.Diagnostics.Root_directory_cannot_be_determined_skipping_primary_search_paths); + } + } + } + function secondaryLookup() { + var initialLocationForSecondaryLookup = containingFile && ts.getDirectoryPath(containingFile); + if (initialLocationForSecondaryLookup !== undefined) { + // check secondary locations + if (traceEnabled) { + trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup); + } + var result = void 0; + if (!ts.isExternalModuleNameRelative(typeReferenceDirectiveName)) { + var searchResult = loadModuleFromNearestNodeModulesDirectory(Extensions.DtsOnly, typeReferenceDirectiveName, initialLocationForSecondaryLookup, moduleResolutionState, /*cache*/ undefined, /*redirectedReference*/ undefined); + result = searchResult && searchResult.value; + } + else { + var candidate = ts.normalizePathAndParts(ts.combinePaths(initialLocationForSecondaryLookup, typeReferenceDirectiveName)).path; + result = nodeLoadModuleByRelativeName(Extensions.DtsOnly, candidate, /*onlyRecordFailures*/ false, moduleResolutionState, /*considerPackageJson*/ true); + } + var resolvedFile = resolvedTypeScriptOnly(result); + if (!resolvedFile && traceEnabled) { + trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName); + } + return resolvedFile; + } + else { + if (traceEnabled) { + trace(host, ts.Diagnostics.Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder); + } + } + } + } + ts.resolveTypeReferenceDirective = resolveTypeReferenceDirective; + /** + * Given a set of options, returns the set of type directive names + * that should be included for this program automatically. + * This list could either come from the config file, + * or from enumerating the types root + initial secondary types lookup location. + * More type directives might appear in the program later as a result of loading actual source files; + * this list is only the set of defaults that are implicitly included. + */ + function getAutomaticTypeDirectiveNames(options, host) { + // Use explicit type list from tsconfig.json + if (options.types) { + return options.types; + } + // Walk the primary type lookup locations + var result = []; + if (host.directoryExists && host.getDirectories) { + var typeRoots = getEffectiveTypeRoots(options, host); + if (typeRoots) { + for (var _i = 0, typeRoots_1 = typeRoots; _i < typeRoots_1.length; _i++) { + var root = typeRoots_1[_i]; + if (host.directoryExists(root)) { + for (var _a = 0, _b = host.getDirectories(root); _a < _b.length; _a++) { + var typeDirectivePath = _b[_a]; + var normalized = ts.normalizePath(typeDirectivePath); + var packageJsonPath = ts.combinePaths(root, normalized, "package.json"); + // `types-publisher` sometimes creates packages with `"typings": null` for packages that don't provide their own types. + // See `createNotNeededPackageJSON` in the types-publisher` repo. + // tslint:disable-next-line:no-null-keyword + var isNotNeededPackage = host.fileExists(packageJsonPath) && ts.readJson(packageJsonPath, host).typings === null; + if (!isNotNeededPackage) { + var baseFileName = ts.getBaseFileName(normalized); + // At this stage, skip results with leading dot. + if (baseFileName.charCodeAt(0) !== 46 /* dot */) { + // Return just the type directive names + result.push(baseFileName); + } + } + } + } + } + } + } + return result; + } + ts.getAutomaticTypeDirectiveNames = getAutomaticTypeDirectiveNames; + function createModuleResolutionCache(currentDirectory, getCanonicalFileName) { + return createModuleResolutionCacheWithMaps(createCacheWithRedirects(), createCacheWithRedirects(), currentDirectory, getCanonicalFileName); + } + ts.createModuleResolutionCache = createModuleResolutionCache; + /*@internal*/ + function createCacheWithRedirects() { + var ownMap = ts.createMap(); + var redirectsMap = ts.createMap(); + return { + ownMap: ownMap, + redirectsMap: redirectsMap, + getOrCreateMapOfCacheRedirects: getOrCreateMapOfCacheRedirects, + clear: clear + }; + function getOrCreateMapOfCacheRedirects(redirectedReference) { + if (!redirectedReference) { + return ownMap; + } + var path = redirectedReference.sourceFile.path; + var redirects = redirectsMap.get(path); + if (!redirects) { + redirects = ts.createMap(); + redirectsMap.set(path, redirects); + } + return redirects; + } + function clear() { + ownMap.clear(); + redirectsMap.clear(); + } + } + ts.createCacheWithRedirects = createCacheWithRedirects; + /*@internal*/ + function createModuleResolutionCacheWithMaps(directoryToModuleNameMap, moduleNameToDirectoryMap, currentDirectory, getCanonicalFileName) { + return { getOrCreateCacheForDirectory: getOrCreateCacheForDirectory, getOrCreateCacheForModuleName: getOrCreateCacheForModuleName }; + function getOrCreateCacheForDirectory(directoryName, redirectedReference) { + var path = ts.toPath(directoryName, currentDirectory, getCanonicalFileName); + return getOrCreateCache(directoryToModuleNameMap, redirectedReference, path, ts.createMap); + } + function getOrCreateCacheForModuleName(nonRelativeModuleName, redirectedReference) { + ts.Debug.assert(!ts.isExternalModuleNameRelative(nonRelativeModuleName)); + return getOrCreateCache(moduleNameToDirectoryMap, redirectedReference, nonRelativeModuleName, createPerModuleNameCache); + } + function getOrCreateCache(cacheWithRedirects, redirectedReference, key, create) { + var cache = cacheWithRedirects.getOrCreateMapOfCacheRedirects(redirectedReference); + var result = cache.get(key); + if (!result) { + result = create(); + cache.set(key, result); + } + return result; + } + function createPerModuleNameCache() { + var directoryPathMap = ts.createMap(); + return { get: get, set: set }; + function get(directory) { + return directoryPathMap.get(ts.toPath(directory, currentDirectory, getCanonicalFileName)); + } + /** + * At first this function add entry directory -> module resolution result to the table. + * Then it computes the set of parent folders for 'directory' that should have the same module resolution result + * and for every parent folder in set it adds entry: parent -> module resolution. . + * Lets say we first directory name: /a/b/c/d/e and resolution result is: /a/b/bar.ts. + * Set of parent folders that should have the same result will be: + * [ + * /a/b/c/d, /a/b/c, /a/b + * ] + * this means that request for module resolution from file in any of these folder will be immediately found in cache. + */ + function set(directory, result) { + var path = ts.toPath(directory, currentDirectory, getCanonicalFileName); + // if entry is already in cache do nothing + if (directoryPathMap.has(path)) { + return; + } + directoryPathMap.set(path, result); + var resolvedFileName = result.resolvedModule && + (result.resolvedModule.originalPath || result.resolvedModule.resolvedFileName); + // find common prefix between directory and resolved file name + // this common prefix should be the shortest path that has the same resolution + // directory: /a/b/c/d/e + // resolvedFileName: /a/b/foo.d.ts + // commonPrefix: /a/b + // for failed lookups cache the result for every directory up to root + var commonPrefix = resolvedFileName && getCommonPrefix(path, resolvedFileName); + var current = path; + while (current !== commonPrefix) { + var parent = ts.getDirectoryPath(current); + if (parent === current || directoryPathMap.has(parent)) { + break; + } + directoryPathMap.set(parent, result); + current = parent; + } + } + function getCommonPrefix(directory, resolution) { + var resolutionDirectory = ts.toPath(ts.getDirectoryPath(resolution), currentDirectory, getCanonicalFileName); + // find first position where directory and resolution differs + var i = 0; + var limit = Math.min(directory.length, resolutionDirectory.length); + while (i < limit && directory.charCodeAt(i) === resolutionDirectory.charCodeAt(i)) { + i++; + } + if (i === directory.length && (resolutionDirectory.length === i || resolutionDirectory[i] === ts.directorySeparator)) { + return directory; + } + var rootLength = ts.getRootLength(directory); + if (i < rootLength) { + return undefined; + } + var sep = directory.lastIndexOf(ts.directorySeparator, i - 1); + if (sep === -1) { + return undefined; + } + return directory.substr(0, Math.max(sep, rootLength)); + } + } + } + ts.createModuleResolutionCacheWithMaps = createModuleResolutionCacheWithMaps; + function resolveModuleNameFromCache(moduleName, containingFile, cache) { + var containingDirectory = ts.getDirectoryPath(containingFile); + var perFolderCache = cache && cache.getOrCreateCacheForDirectory(containingDirectory); + return perFolderCache && perFolderCache.get(moduleName); + } + ts.resolveModuleNameFromCache = resolveModuleNameFromCache; + function resolveModuleName(moduleName, containingFile, compilerOptions, host, cache, redirectedReference) { + var traceEnabled = isTraceEnabled(compilerOptions, host); + if (redirectedReference) { + compilerOptions = redirectedReference.commandLine.options; + } + if (traceEnabled) { + trace(host, ts.Diagnostics.Resolving_module_0_from_1, moduleName, containingFile); + if (redirectedReference) { + trace(host, ts.Diagnostics.Using_compiler_options_of_project_reference_redirect_0, redirectedReference.sourceFile.fileName); + } + } + var containingDirectory = ts.getDirectoryPath(containingFile); + var perFolderCache = cache && cache.getOrCreateCacheForDirectory(containingDirectory, redirectedReference); + var result = perFolderCache && perFolderCache.get(moduleName); + if (result) { + if (traceEnabled) { + trace(host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory); + } + } + else { + var moduleResolution = compilerOptions.moduleResolution; + if (moduleResolution === undefined) { + moduleResolution = ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS ? ts.ModuleResolutionKind.NodeJs : ts.ModuleResolutionKind.Classic; + if (traceEnabled) { + trace(host, ts.Diagnostics.Module_resolution_kind_is_not_specified_using_0, ts.ModuleResolutionKind[moduleResolution]); + } + } + else { + if (traceEnabled) { + trace(host, ts.Diagnostics.Explicitly_specified_module_resolution_kind_Colon_0, ts.ModuleResolutionKind[moduleResolution]); + } + } + switch (moduleResolution) { + case ts.ModuleResolutionKind.NodeJs: + result = nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference); + break; + case ts.ModuleResolutionKind.Classic: + result = classicNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference); + break; + default: + return ts.Debug.fail("Unexpected moduleResolution: " + moduleResolution); + } + if (perFolderCache) { + perFolderCache.set(moduleName, result); + if (!ts.isExternalModuleNameRelative(moduleName)) { + // put result in per-module name cache + cache.getOrCreateCacheForModuleName(moduleName, redirectedReference).set(containingDirectory, result); + } + } + } + if (traceEnabled) { + if (result.resolvedModule) { + trace(host, ts.Diagnostics.Module_name_0_was_successfully_resolved_to_1, moduleName, result.resolvedModule.resolvedFileName); + } + else { + trace(host, ts.Diagnostics.Module_name_0_was_not_resolved, moduleName); + } + } + return result; + } + ts.resolveModuleName = resolveModuleName; + /** + * Any module resolution kind can be augmented with optional settings: 'baseUrl', 'paths' and 'rootDirs' - they are used to + * mitigate differences between design time structure of the project and its runtime counterpart so the same import name + * can be resolved successfully by TypeScript compiler and runtime module loader. + * If these settings are set then loading procedure will try to use them to resolve module name and it can of failure it will + * fallback to standard resolution routine. + * + * - baseUrl - this setting controls how non-relative module names are resolved. If this setting is specified then non-relative + * names will be resolved relative to baseUrl: i.e. if baseUrl is '/a/b' then candidate location to resolve module name 'c/d' will + * be '/a/b/c/d' + * - paths - this setting can only be used when baseUrl is specified. allows to tune how non-relative module names + * will be resolved based on the content of the module name. + * Structure of 'paths' compiler options + * 'paths': { + * pattern-1: [...substitutions], + * pattern-2: [...substitutions], + * ... + * pattern-n: [...substitutions] + * } + * Pattern here is a string that can contain zero or one '*' character. During module resolution module name will be matched against + * all patterns in the list. Matching for patterns that don't contain '*' means that module name must be equal to pattern respecting the case. + * If pattern contains '*' then to match pattern "*" module name must start with the and end with . + * denotes part of the module name between and . + * If module name can be matches with multiple patterns then pattern with the longest prefix will be picked. + * After selecting pattern we'll use list of substitutions to get candidate locations of the module and the try to load module + * from the candidate location. + * Substitution is a string that can contain zero or one '*'. To get candidate location from substitution we'll pick every + * substitution in the list and replace '*' with string. If candidate location is not rooted it + * will be converted to absolute using baseUrl. + * For example: + * baseUrl: /a/b/c + * "paths": { + * // match all module names + * "*": [ + * "*", // use matched name as is, + * // will be looked as /a/b/c/ + * + * "folder1/*" // substitution will convert matched name to 'folder1/', + * // since it is not rooted then final candidate location will be /a/b/c/folder1/ + * ], + * // match module names that start with 'components/' + * "components/*": [ "/root/components/*" ] // substitution will convert /components/folder1/ to '/root/components/folder1/', + * // it is rooted so it will be final candidate location + * } + * + * 'rootDirs' allows the project to be spreaded across multiple locations and resolve modules with relative names as if + * they were in the same location. For example lets say there are two files + * '/local/src/content/file1.ts' + * '/shared/components/contracts/src/content/protocols/file2.ts' + * After bundling content of '/shared/components/contracts/src' will be merged with '/local/src' so + * if file1 has the following import 'import {x} from "./protocols/file2"' it will be resolved successfully in runtime. + * 'rootDirs' provides the way to tell compiler that in order to get the whole project it should behave as if content of all + * root dirs were merged together. + * I.e. for the example above 'rootDirs' will have two entries: [ '/local/src', '/shared/components/contracts/src' ]. + * Compiler will first convert './protocols/file2' into absolute path relative to the location of containing file: + * '/local/src/content/protocols/file2' and try to load it - failure. + * Then it will search 'rootDirs' looking for a longest matching prefix of this absolute path and if such prefix is found - absolute path will + * be converted to a path relative to found rootDir entry './content/protocols/file2' (*). As a last step compiler will check all remaining + * entries in 'rootDirs', use them to build absolute path out of (*) and try to resolve module from this location. + */ + function tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, state) { + var resolved = tryLoadModuleUsingPathsIfEligible(extensions, moduleName, loader, state); + if (resolved) + return resolved.value; + if (!ts.isExternalModuleNameRelative(moduleName)) { + return tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, state); + } + else { + return tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, state); + } + } + function tryLoadModuleUsingPathsIfEligible(extensions, moduleName, loader, state) { + var _a = state.compilerOptions, baseUrl = _a.baseUrl, paths = _a.paths; + if (baseUrl && paths && !ts.pathIsRelative(moduleName)) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, baseUrl, moduleName); + trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName); + } + return tryLoadModuleUsingPaths(extensions, moduleName, baseUrl, paths, loader, /*onlyRecordFailures*/ false, state); + } + } + function tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, state) { + if (!state.compilerOptions.rootDirs) { + return undefined; + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0, moduleName); + } + var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); + var matchedRootDir; + var matchedNormalizedPrefix; + for (var _i = 0, _a = state.compilerOptions.rootDirs; _i < _a.length; _i++) { + var rootDir = _a[_i]; + // rootDirs are expected to be absolute + // in case of tsconfig.json this will happen automatically - compiler will expand relative names + // using location of tsconfig.json as base location + var normalizedRoot = ts.normalizePath(rootDir); + if (!ts.endsWith(normalizedRoot, ts.directorySeparator)) { + normalizedRoot += ts.directorySeparator; + } + var isLongestMatchingPrefix = ts.startsWith(candidate, normalizedRoot) && + (matchedNormalizedPrefix === undefined || matchedNormalizedPrefix.length < normalizedRoot.length); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Checking_if_0_is_the_longest_matching_prefix_for_1_2, normalizedRoot, candidate, isLongestMatchingPrefix); + } + if (isLongestMatchingPrefix) { + matchedNormalizedPrefix = normalizedRoot; + matchedRootDir = rootDir; + } + } + if (matchedNormalizedPrefix) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Longest_matching_prefix_for_0_is_1, candidate, matchedNormalizedPrefix); + } + var suffix = candidate.substr(matchedNormalizedPrefix.length); + // first - try to load from a initial location + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, matchedNormalizedPrefix, candidate); + } + var resolvedFileName = loader(extensions, candidate, !ts.directoryProbablyExists(containingDirectory, state.host), state); + if (resolvedFileName) { + return resolvedFileName; + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Trying_other_entries_in_rootDirs); + } + // then try to resolve using remaining entries in rootDirs + for (var _b = 0, _c = state.compilerOptions.rootDirs; _b < _c.length; _b++) { + var rootDir = _c[_b]; + if (rootDir === matchedRootDir) { + // skip the initially matched entry + continue; + } + var candidate_1 = ts.combinePaths(ts.normalizePath(rootDir), suffix); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, rootDir, candidate_1); + } + var baseDirectory = ts.getDirectoryPath(candidate_1); + var resolvedFileName_1 = loader(extensions, candidate_1, !ts.directoryProbablyExists(baseDirectory, state.host), state); + if (resolvedFileName_1) { + return resolvedFileName_1; + } + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Module_resolution_using_rootDirs_has_failed); + } + } + return undefined; + } + function tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, state) { + var baseUrl = state.compilerOptions.baseUrl; + if (!baseUrl) { + return undefined; + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, baseUrl, moduleName); + } + var candidate = ts.normalizePath(ts.combinePaths(baseUrl, moduleName)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, baseUrl, candidate); + } + return loader(extensions, candidate, !ts.directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); + } + /** + * Expose resolution logic to allow us to use Node module resolution logic from arbitrary locations. + * No way to do this with `require()`: https://github.com/nodejs/node/issues/5963 + * Throws an error if the module can't be resolved. + */ + /* @internal */ + function resolveJSModule(moduleName, initialDir, host) { + var _a = tryResolveJSModuleWorker(moduleName, initialDir, host), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; + if (!resolvedModule) { + throw new Error("Could not resolve JS module '" + moduleName + "' starting at '" + initialDir + "'. Looked in: " + failedLookupLocations.join(", ")); + } + return resolvedModule.resolvedFileName; + } + ts.resolveJSModule = resolveJSModule; + /* @internal */ + function tryResolveJSModule(moduleName, initialDir, host) { + var resolvedModule = tryResolveJSModuleWorker(moduleName, initialDir, host).resolvedModule; + return resolvedModule && resolvedModule.resolvedFileName; + } + ts.tryResolveJSModule = tryResolveJSModule; + var jsOnlyExtensions = [Extensions.JavaScript]; + var tsExtensions = [Extensions.TypeScript, Extensions.JavaScript]; + var tsPlusJsonExtensions = tsExtensions.concat([Extensions.Json]); + var tsconfigExtensions = [Extensions.TSConfig]; + function tryResolveJSModuleWorker(moduleName, initialDir, host) { + return nodeModuleNameResolverWorker(moduleName, initialDir, { moduleResolution: ts.ModuleResolutionKind.NodeJs, allowJs: true }, host, /*cache*/ undefined, jsOnlyExtensions, /*redirectedReferences*/ undefined); + } + function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference, lookupConfig) { + return nodeModuleNameResolverWorker(moduleName, ts.getDirectoryPath(containingFile), compilerOptions, host, cache, lookupConfig ? tsconfigExtensions : (compilerOptions.resolveJsonModule ? tsPlusJsonExtensions : tsExtensions), redirectedReference); + } + ts.nodeModuleNameResolver = nodeModuleNameResolver; + function nodeModuleNameResolverWorker(moduleName, containingDirectory, compilerOptions, host, cache, extensions, redirectedReference) { + var traceEnabled = isTraceEnabled(compilerOptions, host); + var failedLookupLocations = []; + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; + var result = ts.forEach(extensions, function (ext) { return tryResolve(ext); }); + if (result && result.value) { + var _a = result.value, resolved = _a.resolved, isExternalLibraryImport = _a.isExternalLibraryImport; + return createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations); + } + return { resolvedModule: undefined, failedLookupLocations: failedLookupLocations }; + function tryResolve(extensions) { + var loader = function (extensions, candidate, onlyRecordFailures, state) { return nodeLoadModuleByRelativeName(extensions, candidate, onlyRecordFailures, state, /*considerPackageJson*/ true); }; + var resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, state); + if (resolved) { + return toSearchResult({ resolved: resolved, isExternalLibraryImport: pathContainsNodeModules(resolved.path) }); + } + if (!ts.isExternalModuleNameRelative(moduleName)) { + if (traceEnabled) { + trace(host, ts.Diagnostics.Loading_module_0_from_node_modules_folder_target_file_type_1, moduleName, Extensions[extensions]); + } + var resolved_1 = loadModuleFromNearestNodeModulesDirectory(extensions, moduleName, containingDirectory, state, cache, redirectedReference); + if (!resolved_1) + return undefined; + var resolvedValue = resolved_1.value; + if (!compilerOptions.preserveSymlinks && resolvedValue && !resolvedValue.originalPath) { + var path = realPath(resolvedValue.path, host, traceEnabled); + var originalPath = path === resolvedValue.path ? undefined : resolvedValue.path; + resolvedValue = __assign({}, resolvedValue, { path: path, originalPath: originalPath }); + } + // For node_modules lookups, get the real path so that multiple accesses to an `npm link`-ed module do not create duplicate files. + return { value: resolvedValue && { resolved: resolvedValue, isExternalLibraryImport: true } }; + } + else { + var _a = ts.normalizePathAndParts(ts.combinePaths(containingDirectory, moduleName)), candidate = _a.path, parts = _a.parts; + var resolved_2 = nodeLoadModuleByRelativeName(extensions, candidate, /*onlyRecordFailures*/ false, state, /*considerPackageJson*/ true); + // Treat explicit "node_modules" import as an external library import. + return resolved_2 && toSearchResult({ resolved: resolved_2, isExternalLibraryImport: ts.contains(parts, "node_modules") }); + } + } + } + function realPath(path, host, traceEnabled) { + if (!host.realpath) { + return path; + } + var real = ts.normalizePath(host.realpath(path)); + if (traceEnabled) { + trace(host, ts.Diagnostics.Resolving_real_path_for_0_result_1, path, real); + } + ts.Debug.assert(host.fileExists(real), path + " linked to nonexistent file " + real); // tslint:disable-line + return real; + } + function nodeLoadModuleByRelativeName(extensions, candidate, onlyRecordFailures, state, considerPackageJson) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1, candidate, Extensions[extensions]); + } + if (!ts.hasTrailingDirectorySeparator(candidate)) { + if (!onlyRecordFailures) { + var parentOfCandidate = ts.getDirectoryPath(candidate); + if (!ts.directoryProbablyExists(parentOfCandidate, state.host)) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, parentOfCandidate); + } + onlyRecordFailures = true; + } + } + var resolvedFromFile = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state); + if (resolvedFromFile) { + var nm = considerPackageJson ? parseNodeModuleFromPath(resolvedFromFile) : undefined; + var packageInfo = nm && getPackageJsonInfo(nm.packageDirectory, nm.subModuleName, /*onlyRecordFailures*/ false, state); + var packageId = packageInfo && packageInfo.packageId; + return withPackageId(packageId, resolvedFromFile); + } + } + if (!onlyRecordFailures) { + var candidateExists = ts.directoryProbablyExists(candidate, state.host); + if (!candidateExists) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, candidate); + } + onlyRecordFailures = true; + } + } + return loadNodeModuleFromDirectory(extensions, candidate, onlyRecordFailures, state, considerPackageJson); + } + /*@internal*/ + ts.nodeModulesPathPart = "/node_modules/"; + /*@internal*/ + function pathContainsNodeModules(path) { + return ts.stringContains(path, ts.nodeModulesPathPart); + } + ts.pathContainsNodeModules = pathContainsNodeModules; + /** + * This will be called on the successfully resolved path from `loadModuleFromFile`. + * (Not neeeded for `loadModuleFromNodeModules` as that looks up the `package.json` as part of resolution.) + * + * packageDirectory is the directory of the package itself. + * subModuleName is the path within the package. + * For `blah/node_modules/foo/index.d.ts` this is { packageDirectory: "foo", subModuleName: "index.d.ts" }. (Part before "/node_modules/" is ignored.) + * For `/node_modules/foo/bar.d.ts` this is { packageDirectory: "foo", subModuleName": "bar/index.d.ts" }. + * For `/node_modules/@types/foo/bar/index.d.ts` this is { packageDirectory: "@types/foo", subModuleName: "bar/index.d.ts" }. + * For `/node_modules/foo/bar/index.d.ts` this is { packageDirectory: "foo", subModuleName": "bar/index.d.ts" }. + */ + function parseNodeModuleFromPath(resolved) { + var path = ts.normalizePath(resolved.path); + var idx = path.lastIndexOf(ts.nodeModulesPathPart); + if (idx === -1) { + return undefined; + } + var indexAfterNodeModules = idx + ts.nodeModulesPathPart.length; + var indexAfterPackageName = moveToNextDirectorySeparatorIfAvailable(path, indexAfterNodeModules); + if (path.charCodeAt(indexAfterNodeModules) === 64 /* at */) { + indexAfterPackageName = moveToNextDirectorySeparatorIfAvailable(path, indexAfterPackageName); + } + var packageDirectory = path.slice(0, indexAfterPackageName); + var subModuleName = ts.removeExtension(path.slice(indexAfterPackageName + 1), resolved.ext) + ".d.ts" /* Dts */; + return { packageDirectory: packageDirectory, subModuleName: subModuleName }; + } + function moveToNextDirectorySeparatorIfAvailable(path, prevSeparatorIndex) { + var nextSeparatorIndex = path.indexOf(ts.directorySeparator, prevSeparatorIndex + 1); + return nextSeparatorIndex === -1 ? prevSeparatorIndex : nextSeparatorIndex; + } + function addExtensionAndIndex(path) { + if (path === "") { + return "index.d.ts"; + } + if (ts.endsWith(path, ".d.ts")) { + return path; + } + if (path === "index" || ts.endsWith(path, "/index")) { + return path + ".d.ts"; + } + return path + "/index.d.ts"; + } + function loadModuleFromFileNoPackageId(extensions, candidate, onlyRecordFailures, state) { + return noPackageId(loadModuleFromFile(extensions, candidate, onlyRecordFailures, state)); + } + /** + * @param {boolean} onlyRecordFailures - if true then function won't try to actually load files but instead record all attempts as failures. This flag is necessary + * in cases when we know upfront that all load attempts will fail (because containing folder does not exists) however we still need to record all failed lookup locations. + */ + function loadModuleFromFile(extensions, candidate, onlyRecordFailures, state) { + if (extensions === Extensions.Json || extensions === Extensions.TSConfig) { + var extensionLess = ts.tryRemoveExtension(candidate, ".json" /* Json */); + return (extensionLess === undefined && extensions === Extensions.Json) ? undefined : tryAddingExtensions(extensionLess || candidate, extensions, onlyRecordFailures, state); + } + // First, try adding an extension. An import of "foo" could be matched by a file "foo.ts", or "foo.js" by "foo.js.ts" + var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, onlyRecordFailures, state); + if (resolvedByAddingExtension) { + return resolvedByAddingExtension; + } + // If that didn't work, try stripping a ".js" or ".jsx" extension and replacing it with a TypeScript one; + // e.g. "./foo.js" can be matched by "./foo.ts" or "./foo.d.ts" + if (ts.hasJSFileExtension(candidate)) { + var extensionless = ts.removeFileExtension(candidate); + if (state.traceEnabled) { + var extension = candidate.substring(extensionless.length); + trace(state.host, ts.Diagnostics.File_name_0_has_a_1_extension_stripping_it, candidate, extension); + } + return tryAddingExtensions(extensionless, extensions, onlyRecordFailures, state); + } + } + /** Try to return an existing file that adds one of the `extensions` to `candidate`. */ + function tryAddingExtensions(candidate, extensions, onlyRecordFailures, state) { + if (!onlyRecordFailures) { + // check if containing folder exists - if it doesn't then just record failures for all supported extensions without disk probing + var directory = ts.getDirectoryPath(candidate); + if (directory) { + onlyRecordFailures = !ts.directoryProbablyExists(directory, state.host); + } + } + switch (extensions) { + case Extensions.DtsOnly: + return tryExtension(".d.ts" /* Dts */); + case Extensions.TypeScript: + return tryExtension(".ts" /* Ts */) || tryExtension(".tsx" /* Tsx */) || tryExtension(".d.ts" /* Dts */); + case Extensions.JavaScript: + return tryExtension(".js" /* Js */) || tryExtension(".jsx" /* Jsx */); + case Extensions.TSConfig: + case Extensions.Json: + return tryExtension(".json" /* Json */); + } + function tryExtension(ext) { + var path = tryFile(candidate + ext, onlyRecordFailures, state); + return path === undefined ? undefined : { path: path, ext: ext }; + } + } + /** Return the file if it exists. */ + function tryFile(fileName, onlyRecordFailures, state) { + if (!onlyRecordFailures) { + if (state.host.fileExists(fileName)) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_exist_use_it_as_a_name_resolution_result, fileName); + } + return fileName; + } + else { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_does_not_exist, fileName); + } + } + } + state.failedLookupLocations.push(fileName); + return undefined; + } + function loadNodeModuleFromDirectory(extensions, candidate, onlyRecordFailures, state, considerPackageJson) { + if (considerPackageJson === void 0) { considerPackageJson = true; } + var packageInfo = considerPackageJson ? getPackageJsonInfo(candidate, "", onlyRecordFailures, state) : undefined; + var packageId = packageInfo && packageInfo.packageId; + var packageJsonContent = packageInfo && packageInfo.packageJsonContent; + var versionPaths = packageJsonContent && readPackageJsonTypesVersionPaths(packageJsonContent, state); + return withPackageId(packageId, loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths)); + } + function getPackageJsonInfo(packageDirectory, subModuleName, onlyRecordFailures, state) { + var host = state.host, traceEnabled = state.traceEnabled; + var directoryExists = !onlyRecordFailures && ts.directoryProbablyExists(packageDirectory, host); + var packageJsonPath = ts.combinePaths(packageDirectory, "package.json"); + if (directoryExists && host.fileExists(packageJsonPath)) { + var packageJsonContent = ts.readJson(packageJsonPath, host); + if (subModuleName === "") { // looking up the root - need to handle types/typings/main redirects for subModuleName + var path = readPackageJsonTypesFields(packageJsonContent, packageDirectory, state); + if (typeof path === "string") { + subModuleName = addExtensionAndIndex(path.substring(packageDirectory.length + 1)); + } + else { + var jsPath = readPackageJsonMainField(packageJsonContent, packageDirectory, state); + if (typeof jsPath === "string" && jsPath.length > packageDirectory.length) { + var potentialSubModule_1 = jsPath.substring(packageDirectory.length + 1); + subModuleName = (ts.forEach(ts.supportedJSExtensions, function (extension) { + return ts.tryRemoveExtension(potentialSubModule_1, extension); + }) || potentialSubModule_1) + ".d.ts" /* Dts */; + } + else { + subModuleName = "index.d.ts"; + } + } + } + if (!ts.endsWith(subModuleName, ".d.ts" /* Dts */)) { + subModuleName = addExtensionAndIndex(subModuleName); + } + var versionPaths = readPackageJsonTypesVersionPaths(packageJsonContent, state); + var packageId = typeof packageJsonContent.name === "string" && typeof packageJsonContent.version === "string" + ? { name: packageJsonContent.name, subModuleName: subModuleName, version: packageJsonContent.version } + : undefined; + if (traceEnabled) { + if (packageId) { + trace(host, ts.Diagnostics.Found_package_json_at_0_Package_ID_is_1, packageJsonPath, ts.packageIdToString(packageId)); + } + else { + trace(host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); + } + } + return { packageJsonContent: packageJsonContent, packageId: packageId, versionPaths: versionPaths }; + } + else { + if (directoryExists && traceEnabled) { + trace(host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath); + } + // record package json as one of failed lookup locations - in the future if this file will appear it will invalidate resolution results + state.failedLookupLocations.push(packageJsonPath); + } + } + function loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, jsonContent, versionPaths) { + var packageFile; + if (jsonContent) { + switch (extensions) { + case Extensions.JavaScript: + case Extensions.Json: + packageFile = readPackageJsonMainField(jsonContent, candidate, state); + break; + case Extensions.TypeScript: + // When resolving typescript modules, try resolving using main field as well + packageFile = readPackageJsonTypesFields(jsonContent, candidate, state) || readPackageJsonMainField(jsonContent, candidate, state); + break; + case Extensions.DtsOnly: + packageFile = readPackageJsonTypesFields(jsonContent, candidate, state); + break; + case Extensions.TSConfig: + packageFile = readPackageJsonTSConfigField(jsonContent, candidate, state); + break; + default: + return ts.Debug.assertNever(extensions); + } + } + var loader = function (extensions, candidate, onlyRecordFailures, state) { + var fromFile = tryFile(candidate, onlyRecordFailures, state); + if (fromFile) { + var resolved = resolvedIfExtensionMatches(extensions, fromFile); + if (resolved) { + return noPackageId(resolved); + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_has_an_unsupported_extension_so_skipping_it, fromFile); + } + } + // Even if extensions is DtsOnly, we can still look up a .ts file as a result of package.json "types" + var nextExtensions = extensions === Extensions.DtsOnly ? Extensions.TypeScript : extensions; + // Don't do package.json lookup recursively, because Node.js' package lookup doesn't. + return nodeLoadModuleByRelativeName(nextExtensions, candidate, onlyRecordFailures, state, /*considerPackageJson*/ false); + }; + var onlyRecordFailuresForPackageFile = packageFile ? !ts.directoryProbablyExists(ts.getDirectoryPath(packageFile), state.host) : undefined; + var onlyRecordFailuresForIndex = onlyRecordFailures || !ts.directoryProbablyExists(candidate, state.host); + var indexPath = ts.combinePaths(candidate, extensions === Extensions.TSConfig ? "tsconfig" : "index"); + if (versionPaths && (!packageFile || ts.containsPath(candidate, packageFile))) { + var moduleName = ts.getRelativePathFromDirectory(candidate, packageFile || indexPath, /*ignoreCase*/ false); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2, versionPaths.version, ts.version, moduleName); + } + var result = tryLoadModuleUsingPaths(extensions, moduleName, candidate, versionPaths.paths, loader, onlyRecordFailuresForPackageFile || onlyRecordFailuresForIndex, state); + if (result) { + return removeIgnoredPackageId(result.value); + } + } + // It won't have a `packageId` set, because we disabled `considerPackageJson`. + var packageFileResult = packageFile && removeIgnoredPackageId(loader(extensions, packageFile, onlyRecordFailuresForPackageFile, state)); + if (packageFileResult) + return packageFileResult; + return loadModuleFromFile(extensions, indexPath, onlyRecordFailuresForIndex, state); + } + /** Resolve from an arbitrarily specified file. Return `undefined` if it has an unsupported extension. */ + function resolvedIfExtensionMatches(extensions, path) { + var ext = ts.tryGetExtensionFromPath(path); + return ext !== undefined && extensionIsOk(extensions, ext) ? { path: path, ext: ext } : undefined; + } + /** True if `extension` is one of the supported `extensions`. */ + function extensionIsOk(extensions, extension) { + switch (extensions) { + case Extensions.JavaScript: + return extension === ".js" /* Js */ || extension === ".jsx" /* Jsx */; + case Extensions.TSConfig: + case Extensions.Json: + return extension === ".json" /* Json */; + case Extensions.TypeScript: + return extension === ".ts" /* Ts */ || extension === ".tsx" /* Tsx */ || extension === ".d.ts" /* Dts */; + case Extensions.DtsOnly: + return extension === ".d.ts" /* Dts */; + } + } + /* @internal */ + function parsePackageName(moduleName) { + var idx = moduleName.indexOf(ts.directorySeparator); + if (moduleName[0] === "@") { + idx = moduleName.indexOf(ts.directorySeparator, idx + 1); + } + return idx === -1 ? { packageName: moduleName, rest: "" } : { packageName: moduleName.slice(0, idx), rest: moduleName.slice(idx + 1) }; + } + ts.parsePackageName = parsePackageName; + function loadModuleFromNearestNodeModulesDirectory(extensions, moduleName, directory, state, cache, redirectedReference) { + return loadModuleFromNearestNodeModulesDirectoryWorker(extensions, moduleName, directory, state, /*typesScopeOnly*/ false, cache, redirectedReference); + } + function loadModuleFromNearestNodeModulesDirectoryTypesScope(moduleName, directory, state) { + // Extensions parameter here doesn't actually matter, because typesOnly ensures we're just doing @types lookup, which is always DtsOnly. + return loadModuleFromNearestNodeModulesDirectoryWorker(Extensions.DtsOnly, moduleName, directory, state, /*typesScopeOnly*/ true, /*cache*/ undefined, /*redirectedReference*/ undefined); + } + function loadModuleFromNearestNodeModulesDirectoryWorker(extensions, moduleName, directory, state, typesScopeOnly, cache, redirectedReference) { + var perModuleNameCache = cache && cache.getOrCreateCacheForModuleName(moduleName, redirectedReference); + return ts.forEachAncestorDirectory(ts.normalizeSlashes(directory), function (ancestorDirectory) { + if (ts.getBaseFileName(ancestorDirectory) !== "node_modules") { + var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, ancestorDirectory, state); + if (resolutionFromCache) { + return resolutionFromCache; + } + return toSearchResult(loadModuleFromImmediateNodeModulesDirectory(extensions, moduleName, ancestorDirectory, state, typesScopeOnly)); + } + }); + } + function loadModuleFromImmediateNodeModulesDirectory(extensions, moduleName, directory, state, typesScopeOnly) { + var nodeModulesFolder = ts.combinePaths(directory, "node_modules"); + var nodeModulesFolderExists = ts.directoryProbablyExists(nodeModulesFolder, state.host); + if (!nodeModulesFolderExists && state.traceEnabled) { + trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, nodeModulesFolder); + } + var packageResult = typesScopeOnly ? undefined : loadModuleFromSpecificNodeModulesDirectory(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, state); + if (packageResult) { + return packageResult; + } + if (extensions === Extensions.TypeScript || extensions === Extensions.DtsOnly) { + var nodeModulesAtTypes_1 = ts.combinePaths(nodeModulesFolder, "@types"); + var nodeModulesAtTypesExists = nodeModulesFolderExists; + if (nodeModulesFolderExists && !ts.directoryProbablyExists(nodeModulesAtTypes_1, state.host)) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, nodeModulesAtTypes_1); + } + nodeModulesAtTypesExists = false; + } + return loadModuleFromSpecificNodeModulesDirectory(Extensions.DtsOnly, mangleScopedPackageNameWithTrace(moduleName, state), nodeModulesAtTypes_1, nodeModulesAtTypesExists, state); + } + } + function loadModuleFromSpecificNodeModulesDirectory(extensions, moduleName, nodeModulesDirectory, nodeModulesDirectoryExists, state) { + var candidate = ts.normalizePath(ts.combinePaths(nodeModulesDirectory, moduleName)); + // First look for a nested package.json, as in `node_modules/foo/bar/package.json`. + var packageJsonContent; + var packageId; + var versionPaths; + var packageInfo = getPackageJsonInfo(candidate, "", !nodeModulesDirectoryExists, state); + if (packageInfo) { + (packageJsonContent = packageInfo.packageJsonContent, packageId = packageInfo.packageId, versionPaths = packageInfo.versionPaths); + var fromFile = loadModuleFromFile(extensions, candidate, !nodeModulesDirectoryExists, state); + if (fromFile) { + return noPackageId(fromFile); + } + var fromDirectory = loadNodeModuleFromDirectoryWorker(extensions, candidate, !nodeModulesDirectoryExists, state, packageJsonContent, versionPaths); + return withPackageId(packageId, fromDirectory); + } + var loader = function (extensions, candidate, onlyRecordFailures, state) { + var pathAndExtension = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state) || + loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths); + return withPackageId(packageId, pathAndExtension); + }; + var _a = parsePackageName(moduleName), packageName = _a.packageName, rest = _a.rest; + if (rest !== "") { // If "rest" is empty, we just did this search above. + var packageDirectory = ts.combinePaths(nodeModulesDirectory, packageName); + // Don't use a "types" or "main" from here because we're not loading the root, but a subdirectory -- just here for the packageId and path mappings. + var packageInfo_1 = getPackageJsonInfo(packageDirectory, rest, !nodeModulesDirectoryExists, state); + if (packageInfo_1) + (packageId = packageInfo_1.packageId, versionPaths = packageInfo_1.versionPaths); + if (versionPaths) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2, versionPaths.version, ts.version, rest); + } + var packageDirectoryExists = nodeModulesDirectoryExists && ts.directoryProbablyExists(packageDirectory, state.host); + var fromPaths = tryLoadModuleUsingPaths(extensions, rest, packageDirectory, versionPaths.paths, loader, !packageDirectoryExists, state); + if (fromPaths) { + return fromPaths.value; + } + } + } + return loader(extensions, candidate, !nodeModulesDirectoryExists, state); + } + function tryLoadModuleUsingPaths(extensions, moduleName, baseDirectory, paths, loader, onlyRecordFailures, state) { + var matchedPattern = ts.matchPatternOrExact(ts.getOwnKeys(paths), moduleName); + if (matchedPattern) { + var matchedStar_1 = ts.isString(matchedPattern) ? undefined : ts.matchedText(matchedPattern, moduleName); + var matchedPatternText = ts.isString(matchedPattern) ? matchedPattern : ts.patternText(matchedPattern); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText); + } + var resolved = ts.forEach(paths[matchedPatternText], function (subst) { + var path = matchedStar_1 ? subst.replace("*", matchedStar_1) : subst; + var candidate = ts.normalizePath(ts.combinePaths(baseDirectory, path)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path); + } + // A path mapping may have an extension, in contrast to an import, which should omit it. + var extension = ts.tryGetExtensionFromPath(candidate); + if (extension !== undefined) { + var path_1 = tryFile(candidate, onlyRecordFailures, state); + if (path_1 !== undefined) { + return noPackageId({ path: path_1, ext: extension }); + } + } + return loader(extensions, candidate, onlyRecordFailures || !ts.directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); + }); + return { value: resolved }; + } + } + /** Double underscores are used in DefinitelyTyped to delimit scoped packages. */ + var mangledScopedPackageSeparator = "__"; + /** For a scoped package, we must look in `@types/foo__bar` instead of `@types/@foo/bar`. */ + function mangleScopedPackageNameWithTrace(packageName, state) { + var mangled = mangleScopedPackageName(packageName); + if (state.traceEnabled && mangled !== packageName) { + trace(state.host, ts.Diagnostics.Scoped_package_detected_looking_in_0, mangled); + } + return mangled; + } + /* @internal */ + function getTypesPackageName(packageName) { + return "@types/" + mangleScopedPackageName(packageName); + } + ts.getTypesPackageName = getTypesPackageName; + /* @internal */ + function mangleScopedPackageName(packageName) { + if (ts.startsWith(packageName, "@")) { + var replaceSlash = packageName.replace(ts.directorySeparator, mangledScopedPackageSeparator); + if (replaceSlash !== packageName) { + return replaceSlash.slice(1); // Take off the "@" + } + } + return packageName; + } + ts.mangleScopedPackageName = mangleScopedPackageName; + /* @internal */ + function getPackageNameFromTypesPackageName(mangledName) { + var withoutAtTypePrefix = ts.removePrefix(mangledName, "@types/"); + if (withoutAtTypePrefix !== mangledName) { + return unmangleScopedPackageName(withoutAtTypePrefix); + } + return mangledName; + } + ts.getPackageNameFromTypesPackageName = getPackageNameFromTypesPackageName; + /* @internal */ + function unmangleScopedPackageName(typesPackageName) { + return ts.stringContains(typesPackageName, mangledScopedPackageSeparator) ? + "@" + typesPackageName.replace(mangledScopedPackageSeparator, ts.directorySeparator) : + typesPackageName; + } + ts.unmangleScopedPackageName = unmangleScopedPackageName; + function tryFindNonRelativeModuleNameInCache(cache, moduleName, containingDirectory, state) { + var _a; + var result = cache && cache.get(containingDirectory); + if (result) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory); + } + (_a = state.failedLookupLocations).push.apply(_a, result.failedLookupLocations); + return { value: result.resolvedModule && { path: result.resolvedModule.resolvedFileName, originalPath: result.resolvedModule.originalPath || true, extension: result.resolvedModule.extension, packageId: result.resolvedModule.packageId } }; + } + } + function classicNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference) { + var traceEnabled = isTraceEnabled(compilerOptions, host); + var failedLookupLocations = []; + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; + var containingDirectory = ts.getDirectoryPath(containingFile); + var resolved = tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript); + // No originalPath because classic resolution doesn't resolve realPath + return createResolvedModuleWithFailedLookupLocations(resolved && resolved.value, /*isExternalLibraryImport*/ false, failedLookupLocations); + function tryResolve(extensions) { + var resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFileNoPackageId, state); + if (resolvedUsingSettings) { + return { value: resolvedUsingSettings }; + } + if (!ts.isExternalModuleNameRelative(moduleName)) { + var perModuleNameCache_1 = cache && cache.getOrCreateCacheForModuleName(moduleName, redirectedReference); + // Climb up parent directories looking for a module. + var resolved_3 = ts.forEachAncestorDirectory(containingDirectory, function (directory) { + var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache_1, moduleName, directory, state); + if (resolutionFromCache) { + return resolutionFromCache; + } + var searchName = ts.normalizePath(ts.combinePaths(directory, moduleName)); + return toSearchResult(loadModuleFromFileNoPackageId(extensions, searchName, /*onlyRecordFailures*/ false, state)); + }); + if (resolved_3) { + return resolved_3; + } + if (extensions === Extensions.TypeScript) { + // If we didn't find the file normally, look it up in @types. + return loadModuleFromNearestNodeModulesDirectoryTypesScope(moduleName, containingDirectory, state); + } + } + else { + var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); + return toSearchResult(loadModuleFromFileNoPackageId(extensions, candidate, /*onlyRecordFailures*/ false, state)); + } + } + } + ts.classicNameResolver = classicNameResolver; + /** + * LSHost may load a module from a global cache of typings. + * This is the minumum code needed to expose that functionality; the rest is in LSHost. + */ + /* @internal */ + function loadModuleFromGlobalCache(moduleName, projectName, compilerOptions, host, globalCache) { + var traceEnabled = isTraceEnabled(compilerOptions, host); + if (traceEnabled) { + trace(host, ts.Diagnostics.Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2, projectName, moduleName, globalCache); + } + var failedLookupLocations = []; + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; + var resolved = loadModuleFromImmediateNodeModulesDirectory(Extensions.DtsOnly, moduleName, globalCache, state, /*typesScopeOnly*/ false); + return createResolvedModuleWithFailedLookupLocations(resolved, /*isExternalLibraryImport*/ true, failedLookupLocations); + } + ts.loadModuleFromGlobalCache = loadModuleFromGlobalCache; + /** + * Wraps value to SearchResult. + * @returns undefined if value is undefined or { value } otherwise + */ + function toSearchResult(value) { + return value !== undefined ? { value: value } : undefined; + } +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var ModuleInstanceState; + (function (ModuleInstanceState) { + ModuleInstanceState[ModuleInstanceState["NonInstantiated"] = 0] = "NonInstantiated"; + ModuleInstanceState[ModuleInstanceState["Instantiated"] = 1] = "Instantiated"; + ModuleInstanceState[ModuleInstanceState["ConstEnumOnly"] = 2] = "ConstEnumOnly"; + })(ModuleInstanceState = ts.ModuleInstanceState || (ts.ModuleInstanceState = {})); + function getModuleInstanceState(node) { + return node.body ? getModuleInstanceStateWorker(node.body) : 1 /* Instantiated */; + } + ts.getModuleInstanceState = getModuleInstanceState; + function getModuleInstanceStateWorker(node) { + // A module is uninstantiated if it contains only + switch (node.kind) { + // 1. interface declarations, type alias declarations + case 241 /* InterfaceDeclaration */: + case 242 /* TypeAliasDeclaration */: + return 0 /* NonInstantiated */; + // 2. const enum declarations + case 243 /* EnumDeclaration */: + if (ts.isEnumConst(node)) { + return 2 /* ConstEnumOnly */; + } + break; + // 3. non-exported import declarations + case 249 /* ImportDeclaration */: + case 248 /* ImportEqualsDeclaration */: + if (!(ts.hasModifier(node, 1 /* Export */))) { + return 0 /* NonInstantiated */; + } + break; + // 4. other uninstantiated module declarations. + case 245 /* ModuleBlock */: { + var state_1 = 0 /* NonInstantiated */; + ts.forEachChild(node, function (n) { + var childState = getModuleInstanceStateWorker(n); + switch (childState) { + case 0 /* NonInstantiated */: + // child is non-instantiated - continue searching + return; + case 2 /* ConstEnumOnly */: + // child is const enum only - record state and continue searching + state_1 = 2 /* ConstEnumOnly */; + return; + case 1 /* Instantiated */: + // child is instantiated - record state and stop + state_1 = 1 /* Instantiated */; + return true; + default: + ts.Debug.assertNever(childState); + } + }); + return state_1; + } + case 244 /* ModuleDeclaration */: + return getModuleInstanceState(node); + case 72 /* Identifier */: + // Only jsdoc typedef definition can exist in jsdoc namespace, and it should + // be considered the same as type alias + if (node.isInJSDocNamespace) { + return 0 /* NonInstantiated */; + } + } + return 1 /* Instantiated */; + } + var ContainerFlags; + (function (ContainerFlags) { + // The current node is not a container, and no container manipulation should happen before + // recursing into it. + ContainerFlags[ContainerFlags["None"] = 0] = "None"; + // The current node is a container. It should be set as the current container (and block- + // container) before recursing into it. The current node does not have locals. Examples: + // + // Classes, ObjectLiterals, TypeLiterals, Interfaces... + ContainerFlags[ContainerFlags["IsContainer"] = 1] = "IsContainer"; + // The current node is a block-scoped-container. It should be set as the current block- + // container before recursing into it. Examples: + // + // Blocks (when not parented by functions), Catch clauses, For/For-in/For-of statements... + ContainerFlags[ContainerFlags["IsBlockScopedContainer"] = 2] = "IsBlockScopedContainer"; + // The current node is the container of a control flow path. The current control flow should + // be saved and restored, and a new control flow initialized within the container. + ContainerFlags[ContainerFlags["IsControlFlowContainer"] = 4] = "IsControlFlowContainer"; + ContainerFlags[ContainerFlags["IsFunctionLike"] = 8] = "IsFunctionLike"; + ContainerFlags[ContainerFlags["IsFunctionExpression"] = 16] = "IsFunctionExpression"; + ContainerFlags[ContainerFlags["HasLocals"] = 32] = "HasLocals"; + ContainerFlags[ContainerFlags["IsInterface"] = 64] = "IsInterface"; + ContainerFlags[ContainerFlags["IsObjectLiteralOrClassExpressionMethod"] = 128] = "IsObjectLiteralOrClassExpressionMethod"; + })(ContainerFlags || (ContainerFlags = {})); + var binder = createBinder(); + function bindSourceFile(file, options) { + ts.performance.mark("beforeBind"); + binder(file, options); + ts.performance.mark("afterBind"); + ts.performance.measure("Bind", "beforeBind", "afterBind"); + } + ts.bindSourceFile = bindSourceFile; + function createBinder() { + var file; + var options; + var languageVersion; + var parent; + var container; + var thisParentContainer; // Container one level up + var blockScopeContainer; + var lastContainer; + var delayedTypeAliases; + var seenThisKeyword; + // state used by control flow analysis + var currentFlow; + var currentBreakTarget; + var currentContinueTarget; + var currentReturnTarget; + var currentTrueTarget; + var currentFalseTarget; + var preSwitchCaseFlow; + var activeLabels; + var hasExplicitReturn; + // state used for emit helpers + var emitFlags; + // If this file is an external module, then it is automatically in strict-mode according to + // ES6. If it is not an external module, then we'll determine if it is in strict mode or + // not depending on if we see "use strict" in certain places or if we hit a class/namespace + // or if compiler options contain alwaysStrict. + var inStrictMode; + var symbolCount = 0; + var Symbol; // tslint:disable-line variable-name + var classifiableNames; + var unreachableFlow = { flags: 1 /* Unreachable */ }; + var reportedUnreachableFlow = { flags: 1 /* Unreachable */ }; + // state used to aggregate transform flags during bind. + var subtreeTransformFlags = 0 /* None */; + var skipTransformFlagAggregation; + /** + * Inside the binder, we may create a diagnostic for an as-yet unbound node (with potentially no parent pointers, implying no accessible source file) + * If so, the node _must_ be in the current file (as that's the only way anything could have traversed to it to yield it as the error node) + * This version of `createDiagnosticForNode` uses the binder's context to account for this, and always yields correct diagnostics even in these situations. + */ + function createDiagnosticForNode(node, message, arg0, arg1, arg2) { + return ts.createDiagnosticForNodeInSourceFile(ts.getSourceFileOfNode(node) || file, node, message, arg0, arg1, arg2); + } + function bindSourceFile(f, opts) { + file = f; + options = opts; + languageVersion = ts.getEmitScriptTarget(options); + inStrictMode = bindInStrictMode(file, opts); + classifiableNames = ts.createUnderscoreEscapedMap(); + symbolCount = 0; + skipTransformFlagAggregation = file.isDeclarationFile; + Symbol = ts.objectAllocator.getSymbolConstructor(); + if (!file.locals) { + bind(file); + file.symbolCount = symbolCount; + file.classifiableNames = classifiableNames; + delayedBindJSDocTypedefTag(); + } + file = undefined; + options = undefined; + languageVersion = undefined; + parent = undefined; + container = undefined; + thisParentContainer = undefined; + blockScopeContainer = undefined; + lastContainer = undefined; + delayedTypeAliases = undefined; + seenThisKeyword = false; + currentFlow = undefined; + currentBreakTarget = undefined; + currentContinueTarget = undefined; + currentReturnTarget = undefined; + currentTrueTarget = undefined; + currentFalseTarget = undefined; + activeLabels = undefined; + hasExplicitReturn = false; + emitFlags = 0 /* None */; + subtreeTransformFlags = 0 /* None */; + } + return bindSourceFile; + function bindInStrictMode(file, opts) { + if (ts.getStrictOptionValue(opts, "alwaysStrict") && !file.isDeclarationFile) { + // bind in strict mode source files with alwaysStrict option + return true; + } + else { + return !!file.externalModuleIndicator; + } + } + function createSymbol(flags, name) { + symbolCount++; + return new Symbol(flags, name); + } + function addDeclarationToSymbol(symbol, node, symbolFlags) { + symbol.flags |= symbolFlags; + node.symbol = symbol; + symbol.declarations = ts.append(symbol.declarations, node); + if (symbolFlags & (32 /* Class */ | 384 /* Enum */ | 1536 /* Module */ | 3 /* Variable */) && !symbol.exports) { + symbol.exports = ts.createSymbolTable(); + } + if (symbolFlags & (32 /* Class */ | 64 /* Interface */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && !symbol.members) { + symbol.members = ts.createSymbolTable(); + } + if (symbolFlags & 67220415 /* Value */) { + setValueDeclaration(symbol, node); + } + } + function setValueDeclaration(symbol, node) { + var valueDeclaration = symbol.valueDeclaration; + if (!valueDeclaration || + (ts.isAssignmentDeclaration(valueDeclaration) && !ts.isAssignmentDeclaration(node)) || + (valueDeclaration.kind !== node.kind && ts.isEffectiveModuleDeclaration(valueDeclaration))) { + // other kinds of value declarations take precedence over modules and assignment declarations + symbol.valueDeclaration = node; + } + } + // Should not be called on a declaration with a computed property name, + // unless it is a well known Symbol. + function getDeclarationName(node) { + if (node.kind === 254 /* ExportAssignment */) { + return node.isExportEquals ? "export=" /* ExportEquals */ : "default" /* Default */; + } + var name = ts.getNameOfDeclaration(node); + if (name) { + if (ts.isAmbientModule(node)) { + var moduleName = ts.getTextOfIdentifierOrLiteral(name); + return (ts.isGlobalScopeAugmentation(node) ? "__global" : "\"" + moduleName + "\""); + } + if (name.kind === 149 /* ComputedPropertyName */) { + var nameExpression = name.expression; + // treat computed property names where expression is string/numeric literal as just string/numeric literal + if (ts.isStringOrNumericLiteralLike(nameExpression)) { + return ts.escapeLeadingUnderscores(nameExpression.text); + } + ts.Debug.assert(ts.isWellKnownSymbolSyntactically(nameExpression)); + return ts.getPropertyNameForKnownSymbolName(ts.idText(nameExpression.name)); + } + return ts.isPropertyNameLiteral(name) ? ts.getEscapedTextOfIdentifierOrLiteral(name) : undefined; + } + switch (node.kind) { + case 157 /* Constructor */: + return "__constructor" /* Constructor */; + case 165 /* FunctionType */: + case 160 /* CallSignature */: + case 293 /* JSDocSignature */: + return "__call" /* Call */; + case 166 /* ConstructorType */: + case 161 /* ConstructSignature */: + return "__new" /* New */; + case 162 /* IndexSignature */: + return "__index" /* Index */; + case 255 /* ExportDeclaration */: + return "__export" /* ExportStar */; + case 279 /* SourceFile */: + // json file should behave as + // module.exports = ... + return "export=" /* ExportEquals */; + case 204 /* BinaryExpression */: + if (ts.getAssignmentDeclarationKind(node) === 2 /* ModuleExports */) { + // module.exports = ... + return "export=" /* ExportEquals */; + } + ts.Debug.fail("Unknown binary declaration kind"); + break; + case 289 /* JSDocFunctionType */: + return (ts.isJSDocConstructSignature(node) ? "__new" /* New */ : "__call" /* Call */); + case 151 /* Parameter */: + // Parameters with names are handled at the top of this function. Parameters + // without names can only come from JSDocFunctionTypes. + ts.Debug.assert(node.parent.kind === 289 /* JSDocFunctionType */, "Impossible parameter parent kind", function () { return "parent is: " + (ts.SyntaxKind ? ts.SyntaxKind[node.parent.kind] : node.parent.kind) + ", expected JSDocFunctionType"; }); + var functionType = node.parent; + var index = functionType.parameters.indexOf(node); + return "arg" + index; + } + } + function getDisplayName(node) { + return ts.isNamedDeclaration(node) ? ts.declarationNameToString(node.name) : ts.unescapeLeadingUnderscores(ts.Debug.assertDefined(getDeclarationName(node))); + } + /** + * Declares a Symbol for the node and adds it to symbols. Reports errors for conflicting identifier names. + * @param symbolTable - The symbol table which node will be added to. + * @param parent - node's parent declaration. + * @param node - The declaration to be added to the symbol table + * @param includes - The SymbolFlags that node has in addition to its declaration type (eg: export, ambient, etc.) + * @param excludes - The flags which node cannot be declared alongside in a symbol table. Used to report forbidden declarations. + */ + function declareSymbol(symbolTable, parent, node, includes, excludes, isReplaceableByMethod) { + ts.Debug.assert(!ts.hasDynamicName(node)); + var isDefaultExport = ts.hasModifier(node, 512 /* Default */); + // The exported symbol for an export default function/class node is always named "default" + var name = isDefaultExport && parent ? "default" /* Default */ : getDeclarationName(node); + var symbol; + if (name === undefined) { + symbol = createSymbol(0 /* None */, "__missing" /* Missing */); + } + else { + // Check and see if the symbol table already has a symbol with this name. If not, + // create a new symbol with this name and add it to the table. Note that we don't + // give the new symbol any flags *yet*. This ensures that it will not conflict + // with the 'excludes' flags we pass in. + // + // If we do get an existing symbol, see if it conflicts with the new symbol we're + // creating. For example, a 'var' symbol and a 'class' symbol will conflict within + // the same symbol table. If we have a conflict, report the issue on each + // declaration we have for this symbol, and then create a new symbol for this + // declaration. + // + // Note that when properties declared in Javascript constructors + // (marked by isReplaceableByMethod) conflict with another symbol, the property loses. + // Always. This allows the common Javascript pattern of overwriting a prototype method + // with an bound instance method of the same type: `this.method = this.method.bind(this)` + // + // If we created a new symbol, either because we didn't have a symbol with this name + // in the symbol table, or we conflicted with an existing symbol, then just add this + // node as the sole declaration of the new symbol. + // + // Otherwise, we'll be merging into a compatible existing symbol (for example when + // you have multiple 'vars' with the same name in the same container). In this case + // just add this node into the declarations list of the symbol. + symbol = symbolTable.get(name); + if (includes & 2885600 /* Classifiable */) { + classifiableNames.set(name, true); + } + if (!symbol) { + symbolTable.set(name, symbol = createSymbol(0 /* None */, name)); + if (isReplaceableByMethod) + symbol.isReplaceableByMethod = true; + } + else if (isReplaceableByMethod && !symbol.isReplaceableByMethod) { + // A symbol already exists, so don't add this as a declaration. + return symbol; + } + else if (symbol.flags & excludes) { + if (symbol.isReplaceableByMethod) { + // Javascript constructor-declared symbols can be discarded in favor of + // prototype symbols like methods. + symbolTable.set(name, symbol = createSymbol(0 /* None */, name)); + } + else if (!(includes & 3 /* Variable */ && symbol.flags & 67108864 /* Assignment */)) { + // Assignment declarations are allowed to merge with variables, no matter what other flags they have. + if (ts.isNamedDeclaration(node)) { + node.name.parent = node; + } + // Report errors every position with duplicate declaration + // Report errors on previous encountered declarations + var message_1 = symbol.flags & 2 /* BlockScopedVariable */ + ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 + : ts.Diagnostics.Duplicate_identifier_0; + var messageNeedsName_1 = true; + if (symbol.flags & 384 /* Enum */ || includes & 384 /* Enum */) { + message_1 = ts.Diagnostics.Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations; + messageNeedsName_1 = false; + } + if (symbol.declarations && symbol.declarations.length) { + // If the current node is a default export of some sort, then check if + // there are any other default exports that we need to error on. + // We'll know whether we have other default exports depending on if `symbol` already has a declaration list set. + if (isDefaultExport) { + message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; + messageNeedsName_1 = false; + } + else { + // This is to properly report an error in the case "export default { }" is after export default of class declaration or function declaration. + // Error on multiple export default in the following case: + // 1. multiple export default of class declaration or function declaration by checking NodeFlags.Default + // 2. multiple export default of export assignment. This one doesn't have NodeFlags.Default on (as export default doesn't considered as modifiers) + if (symbol.declarations && symbol.declarations.length && + (node.kind === 254 /* ExportAssignment */ && !node.isExportEquals)) { + message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; + messageNeedsName_1 = false; + } + } + } + var addError = function (decl) { + file.bindDiagnostics.push(createDiagnosticForNode(ts.getNameOfDeclaration(decl) || decl, message_1, messageNeedsName_1 ? getDisplayName(decl) : undefined)); + }; + ts.forEach(symbol.declarations, addError); + addError(node); + symbol = createSymbol(0 /* None */, name); + } + } + } + addDeclarationToSymbol(symbol, node, includes); + if (symbol.parent) { + ts.Debug.assert(symbol.parent === parent, "Existing symbol parent should match new one"); + } + else { + symbol.parent = parent; + } + return symbol; + } + function declareModuleMember(node, symbolFlags, symbolExcludes) { + var hasExportModifier = ts.getCombinedModifierFlags(node) & 1 /* Export */; + if (symbolFlags & 2097152 /* Alias */) { + if (node.kind === 257 /* ExportSpecifier */ || (node.kind === 248 /* ImportEqualsDeclaration */ && hasExportModifier)) { + return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); + } + else { + return declareSymbol(container.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes); + } + } + else { + // Exported module members are given 2 symbols: A local symbol that is classified with an ExportValue flag, + // and an associated export symbol with all the correct flags set on it. There are 2 main reasons: + // + // 1. We treat locals and exports of the same name as mutually exclusive within a container. + // That means the binder will issue a Duplicate Identifier error if you mix locals and exports + // with the same name in the same container. + // TODO: Make this a more specific error and decouple it from the exclusion logic. + // 2. When we checkIdentifier in the checker, we set its resolved symbol to the local symbol, + // but return the export symbol (by calling getExportSymbolOfValueSymbolIfExported). That way + // when the emitter comes back to it, it knows not to qualify the name if it was found in a containing scope. + // NOTE: Nested ambient modules always should go to to 'locals' table to prevent their automatic merge + // during global merging in the checker. Why? The only case when ambient module is permitted inside another module is module augmentation + // and this case is specially handled. Module augmentations should only be merged with original module definition + // and should never be merged directly with other augmentation, and the latter case would be possible if automatic merge is allowed. + if (ts.isJSDocTypeAlias(node)) + ts.Debug.assert(ts.isInJSFile(node)); // We shouldn't add symbols for JSDoc nodes if not in a JS file. + if ((!ts.isAmbientModule(node) && (hasExportModifier || container.flags & 32 /* ExportContext */)) || ts.isJSDocTypeAlias(node)) { + if (ts.hasModifier(node, 512 /* Default */) && !getDeclarationName(node)) { + return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); // No local symbol for an unnamed default! + } + var exportKind = symbolFlags & 67220415 /* Value */ ? 1048576 /* ExportValue */ : 0; + var local = declareSymbol(container.locals, /*parent*/ undefined, node, exportKind, symbolExcludes); + local.exportSymbol = declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); + node.localSymbol = local; + return local; + } + else { + return declareSymbol(container.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes); + } + } + } + // All container nodes are kept on a linked list in declaration order. This list is used by + // the getLocalNameOfContainer function in the type checker to validate that the local name + // used for a container is unique. + function bindContainer(node, containerFlags) { + // Before we recurse into a node's children, we first save the existing parent, container + // and block-container. Then after we pop out of processing the children, we restore + // these saved values. + var saveContainer = container; + var saveThisParentContainer = thisParentContainer; + var savedBlockScopeContainer = blockScopeContainer; + // Depending on what kind of node this is, we may have to adjust the current container + // and block-container. If the current node is a container, then it is automatically + // considered the current block-container as well. Also, for containers that we know + // may contain locals, we eagerly initialize the .locals field. We do this because + // it's highly likely that the .locals will be needed to place some child in (for example, + // a parameter, or variable declaration). + // + // However, we do not proactively create the .locals for block-containers because it's + // totally normal and common for block-containers to never actually have a block-scoped + // variable in them. We don't want to end up allocating an object for every 'block' we + // run into when most of them won't be necessary. + // + // Finally, if this is a block-container, then we clear out any existing .locals object + // it may contain within it. This happens in incremental scenarios. Because we can be + // reusing a node from a previous compilation, that node may have had 'locals' created + // for it. We must clear this so we don't accidentally move any stale data forward from + // a previous compilation. + if (containerFlags & 1 /* IsContainer */) { + if (node.kind !== 197 /* ArrowFunction */) { + thisParentContainer = container; + } + container = blockScopeContainer = node; + if (containerFlags & 32 /* HasLocals */) { + container.locals = ts.createSymbolTable(); + } + addToContainerChain(container); + } + else if (containerFlags & 2 /* IsBlockScopedContainer */) { + blockScopeContainer = node; + blockScopeContainer.locals = undefined; + } + if (containerFlags & 4 /* IsControlFlowContainer */) { + var saveCurrentFlow = currentFlow; + var saveBreakTarget = currentBreakTarget; + var saveContinueTarget = currentContinueTarget; + var saveReturnTarget = currentReturnTarget; + var saveActiveLabels = activeLabels; + var saveHasExplicitReturn = hasExplicitReturn; + var isIIFE = containerFlags & 16 /* IsFunctionExpression */ && !ts.hasModifier(node, 256 /* Async */) && + !node.asteriskToken && !!ts.getImmediatelyInvokedFunctionExpression(node); + // A non-async, non-generator IIFE is considered part of the containing control flow. Return statements behave + // similarly to break statements that exit to a label just past the statement body. + if (!isIIFE) { + currentFlow = { flags: 2 /* Start */ }; + if (containerFlags & (16 /* IsFunctionExpression */ | 128 /* IsObjectLiteralOrClassExpressionMethod */)) { + currentFlow.container = node; + } + } + // We create a return control flow graph for IIFEs and constructors. For constructors + // we use the return control flow graph in strict property intialization checks. + currentReturnTarget = isIIFE || node.kind === 157 /* Constructor */ ? createBranchLabel() : undefined; + currentBreakTarget = undefined; + currentContinueTarget = undefined; + activeLabels = undefined; + hasExplicitReturn = false; + bindChildren(node); + // Reset all reachability check related flags on node (for incremental scenarios) + node.flags &= ~1408 /* ReachabilityAndEmitFlags */; + if (!(currentFlow.flags & 1 /* Unreachable */) && containerFlags & 8 /* IsFunctionLike */ && ts.nodeIsPresent(node.body)) { + node.flags |= 128 /* HasImplicitReturn */; + if (hasExplicitReturn) + node.flags |= 256 /* HasExplicitReturn */; + } + if (node.kind === 279 /* SourceFile */) { + node.flags |= emitFlags; + } + if (currentReturnTarget) { + addAntecedent(currentReturnTarget, currentFlow); + currentFlow = finishFlowLabel(currentReturnTarget); + if (node.kind === 157 /* Constructor */) { + node.returnFlowNode = currentFlow; + } + } + if (!isIIFE) { + currentFlow = saveCurrentFlow; + } + currentBreakTarget = saveBreakTarget; + currentContinueTarget = saveContinueTarget; + currentReturnTarget = saveReturnTarget; + activeLabels = saveActiveLabels; + hasExplicitReturn = saveHasExplicitReturn; + } + else if (containerFlags & 64 /* IsInterface */) { + seenThisKeyword = false; + bindChildren(node); + node.flags = seenThisKeyword ? node.flags | 64 /* ContainsThis */ : node.flags & ~64 /* ContainsThis */; + } + else { + bindChildren(node); + } + container = saveContainer; + thisParentContainer = saveThisParentContainer; + blockScopeContainer = savedBlockScopeContainer; + } + function bindChildren(node) { + if (skipTransformFlagAggregation) { + bindChildrenWorker(node); + } + else if (node.transformFlags & 536870912 /* HasComputedFlags */) { + skipTransformFlagAggregation = true; + bindChildrenWorker(node); + skipTransformFlagAggregation = false; + subtreeTransformFlags |= node.transformFlags & ~getTransformFlagsSubtreeExclusions(node.kind); + } + else { + var savedSubtreeTransformFlags = subtreeTransformFlags; + subtreeTransformFlags = 0; + bindChildrenWorker(node); + subtreeTransformFlags = savedSubtreeTransformFlags | computeTransformFlagsForNode(node, subtreeTransformFlags); + } + } + function bindEachFunctionsFirst(nodes) { + bindEach(nodes, function (n) { return n.kind === 239 /* FunctionDeclaration */ ? bind(n) : undefined; }); + bindEach(nodes, function (n) { return n.kind !== 239 /* FunctionDeclaration */ ? bind(n) : undefined; }); + } + function bindEach(nodes, bindFunction) { + if (bindFunction === void 0) { bindFunction = bind; } + if (nodes === undefined) { + return; + } + if (skipTransformFlagAggregation) { + ts.forEach(nodes, bindFunction); + } + else { + var savedSubtreeTransformFlags = subtreeTransformFlags; + subtreeTransformFlags = 0 /* None */; + var nodeArrayFlags = 0 /* None */; + for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) { + var node = nodes_2[_i]; + bindFunction(node); + nodeArrayFlags |= node.transformFlags & ~536870912 /* HasComputedFlags */; + } + nodes.transformFlags = nodeArrayFlags | 536870912 /* HasComputedFlags */; + subtreeTransformFlags |= savedSubtreeTransformFlags; + } + } + function bindEachChild(node) { + ts.forEachChild(node, bind, bindEach); + } + function bindChildrenWorker(node) { + if (checkUnreachable(node)) { + bindEachChild(node); + bindJSDoc(node); + return; + } + switch (node.kind) { + case 224 /* WhileStatement */: + bindWhileStatement(node); + break; + case 223 /* DoStatement */: + bindDoStatement(node); + break; + case 225 /* ForStatement */: + bindForStatement(node); + break; + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + bindForInOrForOfStatement(node); + break; + case 222 /* IfStatement */: + bindIfStatement(node); + break; + case 230 /* ReturnStatement */: + case 234 /* ThrowStatement */: + bindReturnOrThrow(node); + break; + case 229 /* BreakStatement */: + case 228 /* ContinueStatement */: + bindBreakOrContinueStatement(node); + break; + case 235 /* TryStatement */: + bindTryStatement(node); + break; + case 232 /* SwitchStatement */: + bindSwitchStatement(node); + break; + case 246 /* CaseBlock */: + bindCaseBlock(node); + break; + case 271 /* CaseClause */: + bindCaseClause(node); + break; + case 233 /* LabeledStatement */: + bindLabeledStatement(node); + break; + case 202 /* PrefixUnaryExpression */: + bindPrefixUnaryExpressionFlow(node); + break; + case 203 /* PostfixUnaryExpression */: + bindPostfixUnaryExpressionFlow(node); + break; + case 204 /* BinaryExpression */: + bindBinaryExpressionFlow(node); + break; + case 198 /* DeleteExpression */: + bindDeleteExpressionFlow(node); + break; + case 205 /* ConditionalExpression */: + bindConditionalExpressionFlow(node); + break; + case 237 /* VariableDeclaration */: + bindVariableDeclarationFlow(node); + break; + case 191 /* CallExpression */: + bindCallExpressionFlow(node); + break; + case 304 /* JSDocTypedefTag */: + case 297 /* JSDocCallbackTag */: + bindJSDocTypeAlias(node); + break; + // In source files and blocks, bind functions first to match hoisting that occurs at runtime + case 279 /* SourceFile */: { + bindEachFunctionsFirst(node.statements); + bind(node.endOfFileToken); + break; + } + case 218 /* Block */: + case 245 /* ModuleBlock */: + bindEachFunctionsFirst(node.statements); + break; + default: + bindEachChild(node); + break; + } + bindJSDoc(node); + } + function isNarrowingExpression(expr) { + switch (expr.kind) { + case 72 /* Identifier */: + case 100 /* ThisKeyword */: + case 189 /* PropertyAccessExpression */: + case 190 /* ElementAccessExpression */: + return isNarrowableReference(expr); + case 191 /* CallExpression */: + return hasNarrowableArgument(expr); + case 195 /* ParenthesizedExpression */: + return isNarrowingExpression(expr.expression); + case 204 /* BinaryExpression */: + return isNarrowingBinaryExpression(expr); + case 202 /* PrefixUnaryExpression */: + return expr.operator === 52 /* ExclamationToken */ && isNarrowingExpression(expr.operand); + case 199 /* TypeOfExpression */: + return isNarrowingExpression(expr.expression); + } + return false; + } + function isNarrowableReference(expr) { + return expr.kind === 72 /* Identifier */ || expr.kind === 100 /* ThisKeyword */ || expr.kind === 98 /* SuperKeyword */ || + ts.isPropertyAccessExpression(expr) && isNarrowableReference(expr.expression) || + ts.isElementAccessExpression(expr) && expr.argumentExpression && + (ts.isStringLiteral(expr.argumentExpression) || ts.isNumericLiteral(expr.argumentExpression)) && + isNarrowableReference(expr.expression); + } + function hasNarrowableArgument(expr) { + if (expr.arguments) { + for (var _i = 0, _a = expr.arguments; _i < _a.length; _i++) { + var argument = _a[_i]; + if (isNarrowableReference(argument)) { + return true; + } + } + } + if (expr.expression.kind === 189 /* PropertyAccessExpression */ && + isNarrowableReference(expr.expression.expression)) { + return true; + } + return false; + } + function isNarrowingTypeofOperands(expr1, expr2) { + return ts.isTypeOfExpression(expr1) && isNarrowableOperand(expr1.expression) && ts.isStringLiteralLike(expr2); + } + function isNarrowableInOperands(left, right) { + return ts.isStringLiteralLike(left) && isNarrowingExpression(right); + } + function isNarrowingBinaryExpression(expr) { + switch (expr.operatorToken.kind) { + case 59 /* EqualsToken */: + return isNarrowableReference(expr.left); + case 33 /* EqualsEqualsToken */: + case 34 /* ExclamationEqualsToken */: + case 35 /* EqualsEqualsEqualsToken */: + case 36 /* ExclamationEqualsEqualsToken */: + return isNarrowableOperand(expr.left) || isNarrowableOperand(expr.right) || + isNarrowingTypeofOperands(expr.right, expr.left) || isNarrowingTypeofOperands(expr.left, expr.right); + case 94 /* InstanceOfKeyword */: + return isNarrowableOperand(expr.left); + case 93 /* InKeyword */: + return isNarrowableInOperands(expr.left, expr.right); + case 27 /* CommaToken */: + return isNarrowingExpression(expr.right); + } + return false; + } + function isNarrowableOperand(expr) { + switch (expr.kind) { + case 195 /* ParenthesizedExpression */: + return isNarrowableOperand(expr.expression); + case 204 /* BinaryExpression */: + switch (expr.operatorToken.kind) { + case 59 /* EqualsToken */: + return isNarrowableOperand(expr.left); + case 27 /* CommaToken */: + return isNarrowableOperand(expr.right); + } + } + return isNarrowableReference(expr); + } + function createBranchLabel() { + return { + flags: 4 /* BranchLabel */, + antecedents: undefined + }; + } + function createLoopLabel() { + return { + flags: 8 /* LoopLabel */, + antecedents: undefined + }; + } + function setFlowNodeReferenced(flow) { + // On first reference we set the Referenced flag, thereafter we set the Shared flag + flow.flags |= flow.flags & 512 /* Referenced */ ? 1024 /* Shared */ : 512 /* Referenced */; + } + function addAntecedent(label, antecedent) { + if (!(antecedent.flags & 1 /* Unreachable */) && !ts.contains(label.antecedents, antecedent)) { + (label.antecedents || (label.antecedents = [])).push(antecedent); + setFlowNodeReferenced(antecedent); + } + } + function createFlowCondition(flags, antecedent, expression) { + if (antecedent.flags & 1 /* Unreachable */) { + return antecedent; + } + if (!expression) { + return flags & 32 /* TrueCondition */ ? antecedent : unreachableFlow; + } + if (expression.kind === 102 /* TrueKeyword */ && flags & 64 /* FalseCondition */ || + expression.kind === 87 /* FalseKeyword */ && flags & 32 /* TrueCondition */) { + return unreachableFlow; + } + if (!isNarrowingExpression(expression)) { + return antecedent; + } + setFlowNodeReferenced(antecedent); + return { flags: flags, expression: expression, antecedent: antecedent }; + } + function createFlowSwitchClause(antecedent, switchStatement, clauseStart, clauseEnd) { + if (!isNarrowingExpression(switchStatement.expression)) { + return antecedent; + } + setFlowNodeReferenced(antecedent); + return { flags: 128 /* SwitchClause */, switchStatement: switchStatement, clauseStart: clauseStart, clauseEnd: clauseEnd, antecedent: antecedent }; + } + function createFlowAssignment(antecedent, node) { + setFlowNodeReferenced(antecedent); + return { flags: 16 /* Assignment */, antecedent: antecedent, node: node }; + } + function createFlowArrayMutation(antecedent, node) { + setFlowNodeReferenced(antecedent); + var res = { flags: 256 /* ArrayMutation */, antecedent: antecedent, node: node }; + return res; + } + function finishFlowLabel(flow) { + var antecedents = flow.antecedents; + if (!antecedents) { + return unreachableFlow; + } + if (antecedents.length === 1) { + return antecedents[0]; + } + return flow; + } + function isStatementCondition(node) { + var parent = node.parent; + switch (parent.kind) { + case 222 /* IfStatement */: + case 224 /* WhileStatement */: + case 223 /* DoStatement */: + return parent.expression === node; + case 225 /* ForStatement */: + case 205 /* ConditionalExpression */: + return parent.condition === node; + } + return false; + } + function isLogicalExpression(node) { + while (true) { + if (node.kind === 195 /* ParenthesizedExpression */) { + node = node.expression; + } + else if (node.kind === 202 /* PrefixUnaryExpression */ && node.operator === 52 /* ExclamationToken */) { + node = node.operand; + } + else { + return node.kind === 204 /* BinaryExpression */ && (node.operatorToken.kind === 54 /* AmpersandAmpersandToken */ || + node.operatorToken.kind === 55 /* BarBarToken */); + } + } + } + function isTopLevelLogicalExpression(node) { + while (node.parent.kind === 195 /* ParenthesizedExpression */ || + node.parent.kind === 202 /* PrefixUnaryExpression */ && + node.parent.operator === 52 /* ExclamationToken */) { + node = node.parent; + } + return !isStatementCondition(node) && !isLogicalExpression(node.parent); + } + function bindCondition(node, trueTarget, falseTarget) { + var saveTrueTarget = currentTrueTarget; + var saveFalseTarget = currentFalseTarget; + currentTrueTarget = trueTarget; + currentFalseTarget = falseTarget; + bind(node); + currentTrueTarget = saveTrueTarget; + currentFalseTarget = saveFalseTarget; + if (!node || !isLogicalExpression(node)) { + addAntecedent(trueTarget, createFlowCondition(32 /* TrueCondition */, currentFlow, node)); + addAntecedent(falseTarget, createFlowCondition(64 /* FalseCondition */, currentFlow, node)); + } + } + function bindIterativeStatement(node, breakTarget, continueTarget) { + var saveBreakTarget = currentBreakTarget; + var saveContinueTarget = currentContinueTarget; + currentBreakTarget = breakTarget; + currentContinueTarget = continueTarget; + bind(node); + currentBreakTarget = saveBreakTarget; + currentContinueTarget = saveContinueTarget; + } + function bindWhileStatement(node) { + var preWhileLabel = createLoopLabel(); + var preBodyLabel = createBranchLabel(); + var postWhileLabel = createBranchLabel(); + addAntecedent(preWhileLabel, currentFlow); + currentFlow = preWhileLabel; + bindCondition(node.expression, preBodyLabel, postWhileLabel); + currentFlow = finishFlowLabel(preBodyLabel); + bindIterativeStatement(node.statement, postWhileLabel, preWhileLabel); + addAntecedent(preWhileLabel, currentFlow); + currentFlow = finishFlowLabel(postWhileLabel); + } + function bindDoStatement(node) { + var preDoLabel = createLoopLabel(); + var enclosingLabeledStatement = node.parent.kind === 233 /* LabeledStatement */ + ? ts.lastOrUndefined(activeLabels) + : undefined; + // if do statement is wrapped in labeled statement then target labels for break/continue with or without + // label should be the same + var preConditionLabel = enclosingLabeledStatement ? enclosingLabeledStatement.continueTarget : createBranchLabel(); + var postDoLabel = enclosingLabeledStatement ? enclosingLabeledStatement.breakTarget : createBranchLabel(); + addAntecedent(preDoLabel, currentFlow); + currentFlow = preDoLabel; + bindIterativeStatement(node.statement, postDoLabel, preConditionLabel); + addAntecedent(preConditionLabel, currentFlow); + currentFlow = finishFlowLabel(preConditionLabel); + bindCondition(node.expression, preDoLabel, postDoLabel); + currentFlow = finishFlowLabel(postDoLabel); + } + function bindForStatement(node) { + var preLoopLabel = createLoopLabel(); + var preBodyLabel = createBranchLabel(); + var postLoopLabel = createBranchLabel(); + bind(node.initializer); + addAntecedent(preLoopLabel, currentFlow); + currentFlow = preLoopLabel; + bindCondition(node.condition, preBodyLabel, postLoopLabel); + currentFlow = finishFlowLabel(preBodyLabel); + bindIterativeStatement(node.statement, postLoopLabel, preLoopLabel); + bind(node.incrementor); + addAntecedent(preLoopLabel, currentFlow); + currentFlow = finishFlowLabel(postLoopLabel); + } + function bindForInOrForOfStatement(node) { + var preLoopLabel = createLoopLabel(); + var postLoopLabel = createBranchLabel(); + addAntecedent(preLoopLabel, currentFlow); + currentFlow = preLoopLabel; + if (node.kind === 227 /* ForOfStatement */) { + bind(node.awaitModifier); + } + bind(node.expression); + addAntecedent(postLoopLabel, currentFlow); + bind(node.initializer); + if (node.initializer.kind !== 238 /* VariableDeclarationList */) { + bindAssignmentTargetFlow(node.initializer); + } + bindIterativeStatement(node.statement, postLoopLabel, preLoopLabel); + addAntecedent(preLoopLabel, currentFlow); + currentFlow = finishFlowLabel(postLoopLabel); + } + function bindIfStatement(node) { + var thenLabel = createBranchLabel(); + var elseLabel = createBranchLabel(); + var postIfLabel = createBranchLabel(); + bindCondition(node.expression, thenLabel, elseLabel); + currentFlow = finishFlowLabel(thenLabel); + bind(node.thenStatement); + addAntecedent(postIfLabel, currentFlow); + currentFlow = finishFlowLabel(elseLabel); + bind(node.elseStatement); + addAntecedent(postIfLabel, currentFlow); + currentFlow = finishFlowLabel(postIfLabel); + } + function bindReturnOrThrow(node) { + bind(node.expression); + if (node.kind === 230 /* ReturnStatement */) { + hasExplicitReturn = true; + if (currentReturnTarget) { + addAntecedent(currentReturnTarget, currentFlow); + } + } + currentFlow = unreachableFlow; + } + function findActiveLabel(name) { + if (activeLabels) { + for (var _i = 0, activeLabels_1 = activeLabels; _i < activeLabels_1.length; _i++) { + var label = activeLabels_1[_i]; + if (label.name === name) { + return label; + } + } + } + return undefined; + } + function bindBreakOrContinueFlow(node, breakTarget, continueTarget) { + var flowLabel = node.kind === 229 /* BreakStatement */ ? breakTarget : continueTarget; + if (flowLabel) { + addAntecedent(flowLabel, currentFlow); + currentFlow = unreachableFlow; + } + } + function bindBreakOrContinueStatement(node) { + bind(node.label); + if (node.label) { + var activeLabel = findActiveLabel(node.label.escapedText); + if (activeLabel) { + activeLabel.referenced = true; + bindBreakOrContinueFlow(node, activeLabel.breakTarget, activeLabel.continueTarget); + } + } + else { + bindBreakOrContinueFlow(node, currentBreakTarget, currentContinueTarget); + } + } + function bindTryStatement(node) { + var preFinallyLabel = createBranchLabel(); + var preTryFlow = currentFlow; + // TODO: Every statement in try block is potentially an exit point! + bind(node.tryBlock); + addAntecedent(preFinallyLabel, currentFlow); + var flowAfterTry = currentFlow; + var flowAfterCatch = unreachableFlow; + if (node.catchClause) { + currentFlow = preTryFlow; + bind(node.catchClause); + addAntecedent(preFinallyLabel, currentFlow); + flowAfterCatch = currentFlow; + } + if (node.finallyBlock) { + // in finally flow is combined from pre-try/flow from try/flow from catch + // pre-flow is necessary to make sure that finally is reachable even if finally flows in both try and finally blocks are unreachable + // also for finally blocks we inject two extra edges into the flow graph. + // first -> edge that connects pre-try flow with the label at the beginning of the finally block, it has lock associated with it + // second -> edge that represents post-finally flow. + // these edges are used in following scenario: + // let a; (1) + // try { a = someOperation(); (2)} + // finally { (3) console.log(a) } (4) + // (5) a + // flow graph for this case looks roughly like this (arrows show ): + // (1-pre-try-flow) <--.. <-- (2-post-try-flow) + // ^ ^ + // |*****(3-pre-finally-label) -----| + // ^ + // |-- ... <-- (4-post-finally-label) <--- (5) + // In case when we walk the flow starting from inside the finally block we want to take edge '*****' into account + // since it ensures that finally is always reachable. However when we start outside the finally block and go through label (5) + // then edge '*****' should be discarded because label 4 is only reachable if post-finally label-4 is reachable + // Simply speaking code inside finally block is treated as reachable as pre-try-flow + // since we conservatively assume that any line in try block can throw or return in which case we'll enter finally. + // However code after finally is reachable only if control flow was not abrupted in try/catch or finally blocks - it should be composed from + // final flows of these blocks without taking pre-try flow into account. + // + // extra edges that we inject allows to control this behavior + // if when walking the flow we step on post-finally edge - we can mark matching pre-finally edge as locked so it will be skipped. + var preFinallyFlow = { flags: 2048 /* PreFinally */, antecedent: preTryFlow, lock: {} }; + addAntecedent(preFinallyLabel, preFinallyFlow); + currentFlow = finishFlowLabel(preFinallyLabel); + bind(node.finallyBlock); + // if flow after finally is unreachable - keep it + // otherwise check if flows after try and after catch are unreachable + // if yes - convert current flow to unreachable + // i.e. + // try { return "1" } finally { console.log(1); } + // console.log(2); // this line should be unreachable even if flow falls out of finally block + if (!(currentFlow.flags & 1 /* Unreachable */)) { + if ((flowAfterTry.flags & 1 /* Unreachable */) && (flowAfterCatch.flags & 1 /* Unreachable */)) { + currentFlow = flowAfterTry === reportedUnreachableFlow || flowAfterCatch === reportedUnreachableFlow + ? reportedUnreachableFlow + : unreachableFlow; + } + } + if (!(currentFlow.flags & 1 /* Unreachable */)) { + var afterFinallyFlow = { flags: 4096 /* AfterFinally */, antecedent: currentFlow }; + preFinallyFlow.lock = afterFinallyFlow; + currentFlow = afterFinallyFlow; + } + } + else { + currentFlow = finishFlowLabel(preFinallyLabel); + } + } + function bindSwitchStatement(node) { + var postSwitchLabel = createBranchLabel(); + bind(node.expression); + var saveBreakTarget = currentBreakTarget; + var savePreSwitchCaseFlow = preSwitchCaseFlow; + currentBreakTarget = postSwitchLabel; + preSwitchCaseFlow = currentFlow; + bind(node.caseBlock); + addAntecedent(postSwitchLabel, currentFlow); + var hasDefault = ts.forEach(node.caseBlock.clauses, function (c) { return c.kind === 272 /* DefaultClause */; }); + // We mark a switch statement as possibly exhaustive if it has no default clause and if all + // case clauses have unreachable end points (e.g. they all return). + node.possiblyExhaustive = !hasDefault && !postSwitchLabel.antecedents; + if (!hasDefault) { + addAntecedent(postSwitchLabel, createFlowSwitchClause(preSwitchCaseFlow, node, 0, 0)); + } + currentBreakTarget = saveBreakTarget; + preSwitchCaseFlow = savePreSwitchCaseFlow; + currentFlow = finishFlowLabel(postSwitchLabel); + } + function bindCaseBlock(node) { + var savedSubtreeTransformFlags = subtreeTransformFlags; + subtreeTransformFlags = 0; + var clauses = node.clauses; + var fallthroughFlow = unreachableFlow; + for (var i = 0; i < clauses.length; i++) { + var clauseStart = i; + while (!clauses[i].statements.length && i + 1 < clauses.length) { + bind(clauses[i]); + i++; + } + var preCaseLabel = createBranchLabel(); + addAntecedent(preCaseLabel, createFlowSwitchClause(preSwitchCaseFlow, node.parent, clauseStart, i + 1)); + addAntecedent(preCaseLabel, fallthroughFlow); + currentFlow = finishFlowLabel(preCaseLabel); + var clause = clauses[i]; + bind(clause); + fallthroughFlow = currentFlow; + if (!(currentFlow.flags & 1 /* Unreachable */) && i !== clauses.length - 1 && options.noFallthroughCasesInSwitch) { + errorOnFirstToken(clause, ts.Diagnostics.Fallthrough_case_in_switch); + } + } + clauses.transformFlags = subtreeTransformFlags | 536870912 /* HasComputedFlags */; + subtreeTransformFlags |= savedSubtreeTransformFlags; + } + function bindCaseClause(node) { + var saveCurrentFlow = currentFlow; + currentFlow = preSwitchCaseFlow; + bind(node.expression); + currentFlow = saveCurrentFlow; + bindEach(node.statements); + } + function pushActiveLabel(name, breakTarget, continueTarget) { + var activeLabel = { + name: name, + breakTarget: breakTarget, + continueTarget: continueTarget, + referenced: false + }; + (activeLabels || (activeLabels = [])).push(activeLabel); + return activeLabel; + } + function popActiveLabel() { + activeLabels.pop(); + } + function bindLabeledStatement(node) { + var preStatementLabel = createLoopLabel(); + var postStatementLabel = createBranchLabel(); + bind(node.label); + addAntecedent(preStatementLabel, currentFlow); + var activeLabel = pushActiveLabel(node.label.escapedText, postStatementLabel, preStatementLabel); + bind(node.statement); + popActiveLabel(); + if (!activeLabel.referenced && !options.allowUnusedLabels) { + errorOrSuggestionOnNode(ts.unusedLabelIsError(options), node.label, ts.Diagnostics.Unused_label); + } + if (!node.statement || node.statement.kind !== 223 /* DoStatement */) { + // do statement sets current flow inside bindDoStatement + addAntecedent(postStatementLabel, currentFlow); + currentFlow = finishFlowLabel(postStatementLabel); + } + } + function bindDestructuringTargetFlow(node) { + if (node.kind === 204 /* BinaryExpression */ && node.operatorToken.kind === 59 /* EqualsToken */) { + bindAssignmentTargetFlow(node.left); + } + else { + bindAssignmentTargetFlow(node); + } + } + function bindAssignmentTargetFlow(node) { + if (isNarrowableReference(node)) { + currentFlow = createFlowAssignment(currentFlow, node); + } + else if (node.kind === 187 /* ArrayLiteralExpression */) { + for (var _i = 0, _a = node.elements; _i < _a.length; _i++) { + var e = _a[_i]; + if (e.kind === 208 /* SpreadElement */) { + bindAssignmentTargetFlow(e.expression); + } + else { + bindDestructuringTargetFlow(e); + } + } + } + else if (node.kind === 188 /* ObjectLiteralExpression */) { + for (var _b = 0, _c = node.properties; _b < _c.length; _b++) { + var p = _c[_b]; + if (p.kind === 275 /* PropertyAssignment */) { + bindDestructuringTargetFlow(p.initializer); + } + else if (p.kind === 276 /* ShorthandPropertyAssignment */) { + bindAssignmentTargetFlow(p.name); + } + else if (p.kind === 277 /* SpreadAssignment */) { + bindAssignmentTargetFlow(p.expression); + } + } + } + } + function bindLogicalExpression(node, trueTarget, falseTarget) { + var preRightLabel = createBranchLabel(); + if (node.operatorToken.kind === 54 /* AmpersandAmpersandToken */) { + bindCondition(node.left, preRightLabel, falseTarget); + } + else { + bindCondition(node.left, trueTarget, preRightLabel); + } + currentFlow = finishFlowLabel(preRightLabel); + bind(node.operatorToken); + bindCondition(node.right, trueTarget, falseTarget); + } + function bindPrefixUnaryExpressionFlow(node) { + if (node.operator === 52 /* ExclamationToken */) { + var saveTrueTarget = currentTrueTarget; + currentTrueTarget = currentFalseTarget; + currentFalseTarget = saveTrueTarget; + bindEachChild(node); + currentFalseTarget = currentTrueTarget; + currentTrueTarget = saveTrueTarget; + } + else { + bindEachChild(node); + if (node.operator === 44 /* PlusPlusToken */ || node.operator === 45 /* MinusMinusToken */) { + bindAssignmentTargetFlow(node.operand); + } + } + } + function bindPostfixUnaryExpressionFlow(node) { + bindEachChild(node); + if (node.operator === 44 /* PlusPlusToken */ || node.operator === 45 /* MinusMinusToken */) { + bindAssignmentTargetFlow(node.operand); + } + } + function bindBinaryExpressionFlow(node) { + var operator = node.operatorToken.kind; + if (operator === 54 /* AmpersandAmpersandToken */ || operator === 55 /* BarBarToken */) { + if (isTopLevelLogicalExpression(node)) { + var postExpressionLabel = createBranchLabel(); + bindLogicalExpression(node, postExpressionLabel, postExpressionLabel); + currentFlow = finishFlowLabel(postExpressionLabel); + } + else { + bindLogicalExpression(node, currentTrueTarget, currentFalseTarget); + } + } + else { + bindEachChild(node); + if (ts.isAssignmentOperator(operator) && !ts.isAssignmentTarget(node)) { + bindAssignmentTargetFlow(node.left); + if (operator === 59 /* EqualsToken */ && node.left.kind === 190 /* ElementAccessExpression */) { + var elementAccess = node.left; + if (isNarrowableOperand(elementAccess.expression)) { + currentFlow = createFlowArrayMutation(currentFlow, node); + } + } + } + } + } + function bindDeleteExpressionFlow(node) { + bindEachChild(node); + if (node.expression.kind === 189 /* PropertyAccessExpression */) { + bindAssignmentTargetFlow(node.expression); + } + } + function bindConditionalExpressionFlow(node) { + var trueLabel = createBranchLabel(); + var falseLabel = createBranchLabel(); + var postExpressionLabel = createBranchLabel(); + bindCondition(node.condition, trueLabel, falseLabel); + currentFlow = finishFlowLabel(trueLabel); + bind(node.questionToken); + bind(node.whenTrue); + addAntecedent(postExpressionLabel, currentFlow); + currentFlow = finishFlowLabel(falseLabel); + bind(node.colonToken); + bind(node.whenFalse); + addAntecedent(postExpressionLabel, currentFlow); + currentFlow = finishFlowLabel(postExpressionLabel); + } + function bindInitializedVariableFlow(node) { + var name = !ts.isOmittedExpression(node) ? node.name : undefined; + if (ts.isBindingPattern(name)) { + for (var _i = 0, _a = name.elements; _i < _a.length; _i++) { + var child = _a[_i]; + bindInitializedVariableFlow(child); + } + } + else { + currentFlow = createFlowAssignment(currentFlow, node); + } + } + function bindVariableDeclarationFlow(node) { + bindEachChild(node); + if (node.initializer || ts.isForInOrOfStatement(node.parent.parent)) { + bindInitializedVariableFlow(node); + } + } + function bindJSDocTypeAlias(node) { + node.tagName.parent = node; + if (node.fullName) { + setParentPointers(node, node.fullName); + } + } + function bindCallExpressionFlow(node) { + // If the target of the call expression is a function expression or arrow function we have + // an immediately invoked function expression (IIFE). Initialize the flowNode property to + // the current control flow (which includes evaluation of the IIFE arguments). + var expr = node.expression; + while (expr.kind === 195 /* ParenthesizedExpression */) { + expr = expr.expression; + } + if (expr.kind === 196 /* FunctionExpression */ || expr.kind === 197 /* ArrowFunction */) { + bindEach(node.typeArguments); + bindEach(node.arguments); + bind(node.expression); + } + else { + bindEachChild(node); + } + if (node.expression.kind === 189 /* PropertyAccessExpression */) { + var propertyAccess = node.expression; + if (isNarrowableOperand(propertyAccess.expression) && ts.isPushOrUnshiftIdentifier(propertyAccess.name)) { + currentFlow = createFlowArrayMutation(currentFlow, node); + } + } + } + function getContainerFlags(node) { + switch (node.kind) { + case 209 /* ClassExpression */: + case 240 /* ClassDeclaration */: + case 243 /* EnumDeclaration */: + case 188 /* ObjectLiteralExpression */: + case 168 /* TypeLiteral */: + case 292 /* JSDocTypeLiteral */: + case 268 /* JsxAttributes */: + return 1 /* IsContainer */; + case 241 /* InterfaceDeclaration */: + return 1 /* IsContainer */ | 64 /* IsInterface */; + case 244 /* ModuleDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 181 /* MappedType */: + return 1 /* IsContainer */ | 32 /* HasLocals */; + case 279 /* SourceFile */: + return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */; + case 156 /* MethodDeclaration */: + if (ts.isObjectLiteralOrClassExpressionMethod(node)) { + return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */ | 128 /* IsObjectLiteralOrClassExpressionMethod */; + } + // falls through + case 157 /* Constructor */: + case 239 /* FunctionDeclaration */: + case 155 /* MethodSignature */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 160 /* CallSignature */: + case 293 /* JSDocSignature */: + case 289 /* JSDocFunctionType */: + case 165 /* FunctionType */: + case 161 /* ConstructSignature */: + case 162 /* IndexSignature */: + case 166 /* ConstructorType */: + return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */; + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */ | 16 /* IsFunctionExpression */; + case 245 /* ModuleBlock */: + return 4 /* IsControlFlowContainer */; + case 154 /* PropertyDeclaration */: + return node.initializer ? 4 /* IsControlFlowContainer */ : 0; + case 274 /* CatchClause */: + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + case 246 /* CaseBlock */: + return 2 /* IsBlockScopedContainer */; + case 218 /* Block */: + // do not treat blocks directly inside a function as a block-scoped-container. + // Locals that reside in this block should go to the function locals. Otherwise 'x' + // would not appear to be a redeclaration of a block scoped local in the following + // example: + // + // function foo() { + // var x; + // let x; + // } + // + // If we placed 'var x' into the function locals and 'let x' into the locals of + // the block, then there would be no collision. + // + // By not creating a new block-scoped-container here, we ensure that both 'var x' + // and 'let x' go into the Function-container's locals, and we do get a collision + // conflict. + return ts.isFunctionLike(node.parent) ? 0 /* None */ : 2 /* IsBlockScopedContainer */; + } + return 0 /* None */; + } + function addToContainerChain(next) { + if (lastContainer) { + lastContainer.nextContainer = next; + } + lastContainer = next; + } + function declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes) { + switch (container.kind) { + // Modules, source files, and classes need specialized handling for how their + // members are declared (for example, a member of a class will go into a specific + // symbol table depending on if it is static or not). We defer to specialized + // handlers to take care of declaring these child members. + case 244 /* ModuleDeclaration */: + return declareModuleMember(node, symbolFlags, symbolExcludes); + case 279 /* SourceFile */: + return declareSourceFileMember(node, symbolFlags, symbolExcludes); + case 209 /* ClassExpression */: + case 240 /* ClassDeclaration */: + return declareClassMember(node, symbolFlags, symbolExcludes); + case 243 /* EnumDeclaration */: + return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); + case 168 /* TypeLiteral */: + case 292 /* JSDocTypeLiteral */: + case 188 /* ObjectLiteralExpression */: + case 241 /* InterfaceDeclaration */: + case 268 /* JsxAttributes */: + // Interface/Object-types always have their children added to the 'members' of + // their container. They are only accessible through an instance of their + // container, and are never in scope otherwise (even inside the body of the + // object / type / interface declaring them). An exception is type parameters, + // which are in scope without qualification (similar to 'locals'). + return declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes); + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 293 /* JSDocSignature */: + case 162 /* IndexSignature */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 289 /* JSDocFunctionType */: + case 304 /* JSDocTypedefTag */: + case 297 /* JSDocCallbackTag */: + case 242 /* TypeAliasDeclaration */: + case 181 /* MappedType */: + // All the children of these container types are never visible through another + // symbol (i.e. through another symbol's 'exports' or 'members'). Instead, + // they're only accessed 'lexically' (i.e. from code that exists underneath + // their container in the tree). To accomplish this, we simply add their declared + // symbol to the 'locals' of the container. These symbols can then be found as + // the type checker walks up the containers, checking them for matching names. + return declareSymbol(container.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes); + } + } + function declareClassMember(node, symbolFlags, symbolExcludes) { + return ts.hasModifier(node, 32 /* Static */) + ? declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes) + : declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes); + } + function declareSourceFileMember(node, symbolFlags, symbolExcludes) { + return ts.isExternalModule(file) + ? declareModuleMember(node, symbolFlags, symbolExcludes) + : declareSymbol(file.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes); + } + function hasExportDeclarations(node) { + var body = node.kind === 279 /* SourceFile */ ? node : node.body; + if (body && (body.kind === 279 /* SourceFile */ || body.kind === 245 /* ModuleBlock */)) { + for (var _i = 0, _a = body.statements; _i < _a.length; _i++) { + var stat = _a[_i]; + if (stat.kind === 255 /* ExportDeclaration */ || stat.kind === 254 /* ExportAssignment */) { + return true; + } + } + } + return false; + } + function setExportContextFlag(node) { + // A declaration source file or ambient module declaration that contains no export declarations (but possibly regular + // declarations with export modifiers) is an export context in which declarations are implicitly exported. + if (node.flags & 4194304 /* Ambient */ && !hasExportDeclarations(node)) { + node.flags |= 32 /* ExportContext */; + } + else { + node.flags &= ~32 /* ExportContext */; + } + } + function bindModuleDeclaration(node) { + setExportContextFlag(node); + if (ts.isAmbientModule(node)) { + if (ts.hasModifier(node, 1 /* Export */)) { + errorOnFirstToken(node, ts.Diagnostics.export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always_visible); + } + if (ts.isModuleAugmentationExternal(node)) { + declareModuleSymbol(node); + } + else { + var pattern = void 0; + if (node.name.kind === 10 /* StringLiteral */) { + var text = node.name.text; + if (ts.hasZeroOrOneAsteriskCharacter(text)) { + pattern = ts.tryParsePattern(text); + } + else { + errorOnFirstToken(node.name, ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, text); + } + } + var symbol = declareSymbolAndAddToSymbolTable(node, 512 /* ValueModule */, 110735 /* ValueModuleExcludes */); + file.patternAmbientModules = ts.append(file.patternAmbientModules, pattern && { pattern: pattern, symbol: symbol }); + } + } + else { + var state = declareModuleSymbol(node); + if (state !== 0 /* NonInstantiated */) { + var symbol = node.symbol; + // if module was already merged with some function, class or non-const enum, treat it as non-const-enum-only + symbol.constEnumOnlyModule = (!(symbol.flags & (16 /* Function */ | 32 /* Class */ | 256 /* RegularEnum */))) + // Current must be `const enum` only + && state === 2 /* ConstEnumOnly */ + // Can't have been set to 'false' in a previous merged symbol. ('undefined' OK) + && symbol.constEnumOnlyModule !== false; + } + } + } + function declareModuleSymbol(node) { + var state = getModuleInstanceState(node); + var instantiated = state !== 0 /* NonInstantiated */; + declareSymbolAndAddToSymbolTable(node, instantiated ? 512 /* ValueModule */ : 1024 /* NamespaceModule */, instantiated ? 110735 /* ValueModuleExcludes */ : 0 /* NamespaceModuleExcludes */); + return state; + } + function bindFunctionOrConstructorType(node) { + // For a given function symbol "<...>(...) => T" we want to generate a symbol identical + // to the one we would get for: { <...>(...): T } + // + // We do that by making an anonymous type literal symbol, and then setting the function + // symbol as its sole member. To the rest of the system, this symbol will be indistinguishable + // from an actual type literal symbol you would have gotten had you used the long form. + var symbol = createSymbol(131072 /* Signature */, getDeclarationName(node)); // TODO: GH#18217 + addDeclarationToSymbol(symbol, node, 131072 /* Signature */); + var typeLiteralSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */); + addDeclarationToSymbol(typeLiteralSymbol, node, 2048 /* TypeLiteral */); + typeLiteralSymbol.members = ts.createSymbolTable(); + typeLiteralSymbol.members.set(symbol.escapedName, symbol); + } + function bindObjectLiteralExpression(node) { + var ElementKind; + (function (ElementKind) { + ElementKind[ElementKind["Property"] = 1] = "Property"; + ElementKind[ElementKind["Accessor"] = 2] = "Accessor"; + })(ElementKind || (ElementKind = {})); + if (inStrictMode) { + var seen = ts.createUnderscoreEscapedMap(); + for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { + var prop = _a[_i]; + if (prop.kind === 277 /* SpreadAssignment */ || prop.name.kind !== 72 /* Identifier */) { + continue; + } + var identifier = prop.name; + // ECMA-262 11.1.5 Object Initializer + // If previous is not undefined then throw a SyntaxError exception if any of the following conditions are true + // a.This production is contained in strict code and IsDataDescriptor(previous) is true and + // IsDataDescriptor(propId.descriptor) is true. + // b.IsDataDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true. + // c.IsAccessorDescriptor(previous) is true and IsDataDescriptor(propId.descriptor) is true. + // d.IsAccessorDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true + // and either both previous and propId.descriptor have[[Get]] fields or both previous and propId.descriptor have[[Set]] fields + var currentKind = prop.kind === 275 /* PropertyAssignment */ || prop.kind === 276 /* ShorthandPropertyAssignment */ || prop.kind === 156 /* MethodDeclaration */ + ? 1 /* Property */ + : 2 /* Accessor */; + var existingKind = seen.get(identifier.escapedText); + if (!existingKind) { + seen.set(identifier.escapedText, currentKind); + continue; + } + if (currentKind === 1 /* Property */ && existingKind === 1 /* Property */) { + var span = ts.getErrorSpanForNode(file, identifier); + file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, ts.Diagnostics.An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode)); + } + } + } + return bindAnonymousDeclaration(node, 4096 /* ObjectLiteral */, "__object" /* Object */); + } + function bindJsxAttributes(node) { + return bindAnonymousDeclaration(node, 4096 /* ObjectLiteral */, "__jsxAttributes" /* JSXAttributes */); + } + function bindJsxAttribute(node, symbolFlags, symbolExcludes) { + return declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes); + } + function bindAnonymousDeclaration(node, symbolFlags, name) { + var symbol = createSymbol(symbolFlags, name); + if (symbolFlags & (8 /* EnumMember */ | 106500 /* ClassMember */)) { + symbol.parent = container.symbol; + } + addDeclarationToSymbol(symbol, node, symbolFlags); + return symbol; + } + function bindBlockScopedDeclaration(node, symbolFlags, symbolExcludes) { + switch (blockScopeContainer.kind) { + case 244 /* ModuleDeclaration */: + declareModuleMember(node, symbolFlags, symbolExcludes); + break; + case 279 /* SourceFile */: + if (ts.isExternalOrCommonJsModule(container)) { + declareModuleMember(node, symbolFlags, symbolExcludes); + break; + } + // falls through + default: + if (!blockScopeContainer.locals) { + blockScopeContainer.locals = ts.createSymbolTable(); + addToContainerChain(blockScopeContainer); + } + declareSymbol(blockScopeContainer.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes); + } + } + function delayedBindJSDocTypedefTag() { + if (!delayedTypeAliases) { + return; + } + var saveContainer = container; + var saveLastContainer = lastContainer; + var saveBlockScopeContainer = blockScopeContainer; + var saveParent = parent; + var saveCurrentFlow = currentFlow; + for (var _i = 0, delayedTypeAliases_1 = delayedTypeAliases; _i < delayedTypeAliases_1.length; _i++) { + var typeAlias = delayedTypeAliases_1[_i]; + var host = ts.getJSDocHost(typeAlias); + container = ts.findAncestor(host.parent, function (n) { return !!(getContainerFlags(n) & 1 /* IsContainer */); }) || file; + blockScopeContainer = ts.getEnclosingBlockScopeContainer(host) || file; + currentFlow = { flags: 2 /* Start */ }; + parent = typeAlias; + bind(typeAlias.typeExpression); + if (!typeAlias.fullName || typeAlias.fullName.kind === 72 /* Identifier */) { + parent = typeAlias.parent; + bindBlockScopedDeclaration(typeAlias, 524288 /* TypeAlias */, 67897832 /* TypeAliasExcludes */); + } + else { + bind(typeAlias.fullName); + } + } + container = saveContainer; + lastContainer = saveLastContainer; + blockScopeContainer = saveBlockScopeContainer; + parent = saveParent; + currentFlow = saveCurrentFlow; + } + // The binder visits every node in the syntax tree so it is a convenient place to perform a single localized + // check for reserved words used as identifiers in strict mode code. + function checkStrictModeIdentifier(node) { + if (inStrictMode && + node.originalKeywordKind >= 109 /* FirstFutureReservedWord */ && + node.originalKeywordKind <= 117 /* LastFutureReservedWord */ && + !ts.isIdentifierName(node) && + !(node.flags & 4194304 /* Ambient */)) { + // Report error only if there are no parse errors in file + if (!file.parseDiagnostics.length) { + file.bindDiagnostics.push(createDiagnosticForNode(node, getStrictModeIdentifierMessage(node), ts.declarationNameToString(node))); + } + } + } + function getStrictModeIdentifierMessage(node) { + // Provide specialized messages to help the user understand why we think they're in + // strict mode. + if (ts.getContainingClass(node)) { + return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode; + } + if (file.externalModuleIndicator) { + return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode; + } + return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode; + } + function checkStrictModeBinaryExpression(node) { + if (inStrictMode && ts.isLeftHandSideExpression(node.left) && ts.isAssignmentOperator(node.operatorToken.kind)) { + // ECMA 262 (Annex C) The identifier eval or arguments may not appear as the LeftHandSideExpression of an + // Assignment operator(11.13) or of a PostfixExpression(11.3) + checkStrictModeEvalOrArguments(node, node.left); + } + } + function checkStrictModeCatchClause(node) { + // It is a SyntaxError if a TryStatement with a Catch occurs within strict code and the Identifier of the + // Catch production is eval or arguments + if (inStrictMode && node.variableDeclaration) { + checkStrictModeEvalOrArguments(node, node.variableDeclaration.name); + } + } + function checkStrictModeDeleteExpression(node) { + // Grammar checking + if (inStrictMode && node.expression.kind === 72 /* Identifier */) { + // When a delete operator occurs within strict mode code, a SyntaxError is thrown if its + // UnaryExpression is a direct reference to a variable, function argument, or function name + var span = ts.getErrorSpanForNode(file, node.expression); + file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, ts.Diagnostics.delete_cannot_be_called_on_an_identifier_in_strict_mode)); + } + } + function isEvalOrArgumentsIdentifier(node) { + return ts.isIdentifier(node) && (node.escapedText === "eval" || node.escapedText === "arguments"); + } + function checkStrictModeEvalOrArguments(contextNode, name) { + if (name && name.kind === 72 /* Identifier */) { + var identifier = name; + if (isEvalOrArgumentsIdentifier(identifier)) { + // We check first if the name is inside class declaration or class expression; if so give explicit message + // otherwise report generic error message. + var span = ts.getErrorSpanForNode(file, name); + file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, getStrictModeEvalOrArgumentsMessage(contextNode), ts.idText(identifier))); + } + } + } + function getStrictModeEvalOrArgumentsMessage(node) { + // Provide specialized messages to help the user understand why we think they're in + // strict mode. + if (ts.getContainingClass(node)) { + return ts.Diagnostics.Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode; + } + if (file.externalModuleIndicator) { + return ts.Diagnostics.Invalid_use_of_0_Modules_are_automatically_in_strict_mode; + } + return ts.Diagnostics.Invalid_use_of_0_in_strict_mode; + } + function checkStrictModeFunctionName(node) { + if (inStrictMode) { + // It is a SyntaxError if the identifier eval or arguments appears within a FormalParameterList of a strict mode FunctionDeclaration or FunctionExpression (13.1)) + checkStrictModeEvalOrArguments(node, node.name); + } + } + function getStrictModeBlockScopeFunctionDeclarationMessage(node) { + // Provide specialized messages to help the user understand why we think they're in + // strict mode. + if (ts.getContainingClass(node)) { + return ts.Diagnostics.Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_definitions_are_automatically_in_strict_mode; + } + if (file.externalModuleIndicator) { + return ts.Diagnostics.Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_are_automatically_in_strict_mode; + } + return ts.Diagnostics.Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5; + } + function checkStrictModeFunctionDeclaration(node) { + if (languageVersion < 2 /* ES2015 */) { + // Report error if function is not top level function declaration + if (blockScopeContainer.kind !== 279 /* SourceFile */ && + blockScopeContainer.kind !== 244 /* ModuleDeclaration */ && + !ts.isFunctionLike(blockScopeContainer)) { + // We check first if the name is inside class declaration or class expression; if so give explicit message + // otherwise report generic error message. + var errorSpan = ts.getErrorSpanForNode(file, node); + file.bindDiagnostics.push(ts.createFileDiagnostic(file, errorSpan.start, errorSpan.length, getStrictModeBlockScopeFunctionDeclarationMessage(node))); + } + } + } + function checkStrictModeNumericLiteral(node) { + if (inStrictMode && node.numericLiteralFlags & 32 /* Octal */) { + file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Octal_literals_are_not_allowed_in_strict_mode)); + } + } + function checkStrictModePostfixUnaryExpression(node) { + // Grammar checking + // The identifier eval or arguments may not appear as the LeftHandSideExpression of an + // Assignment operator(11.13) or of a PostfixExpression(11.3) or as the UnaryExpression + // operated upon by a Prefix Increment(11.4.4) or a Prefix Decrement(11.4.5) operator. + if (inStrictMode) { + checkStrictModeEvalOrArguments(node, node.operand); + } + } + function checkStrictModePrefixUnaryExpression(node) { + // Grammar checking + if (inStrictMode) { + if (node.operator === 44 /* PlusPlusToken */ || node.operator === 45 /* MinusMinusToken */) { + checkStrictModeEvalOrArguments(node, node.operand); + } + } + } + function checkStrictModeWithStatement(node) { + // Grammar checking for withStatement + if (inStrictMode) { + errorOnFirstToken(node, ts.Diagnostics.with_statements_are_not_allowed_in_strict_mode); + } + } + function checkStrictModeLabeledStatement(node) { + // Grammar checking for labeledStatement + if (inStrictMode && options.target >= 2 /* ES2015 */) { + if (ts.isDeclarationStatement(node.statement) || ts.isVariableStatement(node.statement)) { + errorOnFirstToken(node.label, ts.Diagnostics.A_label_is_not_allowed_here); + } + } + } + function errorOnFirstToken(node, message, arg0, arg1, arg2) { + var span = ts.getSpanOfTokenAtPosition(file, node.pos); + file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, message, arg0, arg1, arg2)); + } + function errorOrSuggestionOnNode(isError, node, message) { + errorOrSuggestionOnRange(isError, node, node, message); + } + function errorOrSuggestionOnRange(isError, startNode, endNode, message) { + addErrorOrSuggestionDiagnostic(isError, { pos: ts.getTokenPosOfNode(startNode, file), end: endNode.end }, message); + } + function addErrorOrSuggestionDiagnostic(isError, range, message) { + var diag = ts.createFileDiagnostic(file, range.pos, range.end - range.pos, message); + if (isError) { + file.bindDiagnostics.push(diag); + } + else { + file.bindSuggestionDiagnostics = ts.append(file.bindSuggestionDiagnostics, __assign({}, diag, { category: ts.DiagnosticCategory.Suggestion })); + } + } + function bind(node) { + if (!node) { + return; + } + node.parent = parent; + var saveInStrictMode = inStrictMode; + // Even though in the AST the jsdoc @typedef node belongs to the current node, + // its symbol might be in the same scope with the current node's symbol. Consider: + // + // /** @typedef {string | number} MyType */ + // function foo(); + // + // Here the current node is "foo", which is a container, but the scope of "MyType" should + // not be inside "foo". Therefore we always bind @typedef before bind the parent node, + // and skip binding this tag later when binding all the other jsdoc tags. + // First we bind declaration nodes to a symbol if possible. We'll both create a symbol + // and then potentially add the symbol to an appropriate symbol table. Possible + // destination symbol tables are: + // + // 1) The 'exports' table of the current container's symbol. + // 2) The 'members' table of the current container's symbol. + // 3) The 'locals' table of the current container. + // + // However, not all symbols will end up in any of these tables. 'Anonymous' symbols + // (like TypeLiterals for example) will not be put in any table. + bindWorker(node); + // Then we recurse into the children of the node to bind them as well. For certain + // symbols we do specialized work when we recurse. For example, we'll keep track of + // the current 'container' node when it changes. This helps us know which symbol table + // a local should go into for example. Since terminal nodes are known not to have + // children, as an optimization we don't process those. + if (node.kind > 147 /* LastToken */) { + var saveParent = parent; + parent = node; + var containerFlags = getContainerFlags(node); + if (containerFlags === 0 /* None */) { + bindChildren(node); + } + else { + bindContainer(node, containerFlags); + } + parent = saveParent; + } + else if (!skipTransformFlagAggregation && (node.transformFlags & 536870912 /* HasComputedFlags */) === 0) { + subtreeTransformFlags |= computeTransformFlagsForNode(node, 0); + var saveParent = parent; + if (node.kind === 1 /* EndOfFileToken */) + parent = node; + bindJSDoc(node); + parent = saveParent; + } + inStrictMode = saveInStrictMode; + } + function bindJSDoc(node) { + if (ts.hasJSDocNodes(node)) { + if (ts.isInJSFile(node)) { + for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { + var j = _a[_i]; + bind(j); + } + } + else { + for (var _b = 0, _c = node.jsDoc; _b < _c.length; _b++) { + var j = _c[_b]; + setParentPointers(node, j); + } + } + } + } + function updateStrictModeStatementList(statements) { + if (!inStrictMode) { + for (var _i = 0, statements_1 = statements; _i < statements_1.length; _i++) { + var statement = statements_1[_i]; + if (!ts.isPrologueDirective(statement)) { + return; + } + if (isUseStrictPrologueDirective(statement)) { + inStrictMode = true; + return; + } + } + } + } + /// Should be called only on prologue directives (isPrologueDirective(node) should be true) + function isUseStrictPrologueDirective(node) { + var nodeText = ts.getSourceTextOfNodeFromSourceFile(file, node.expression); + // Note: the node text must be exactly "use strict" or 'use strict'. It is not ok for the + // string to contain unicode escapes (as per ES5). + return nodeText === '"use strict"' || nodeText === "'use strict'"; + } + function bindWorker(node) { + switch (node.kind) { + /* Strict mode checks */ + case 72 /* Identifier */: + // for typedef type names with namespaces, bind the new jsdoc type symbol here + // because it requires all containing namespaces to be in effect, namely the + // current "blockScopeContainer" needs to be set to its immediate namespace parent. + if (node.isInJSDocNamespace) { + var parentNode = node.parent; + while (parentNode && !ts.isJSDocTypeAlias(parentNode)) { + parentNode = parentNode.parent; + } + bindBlockScopedDeclaration(parentNode, 524288 /* TypeAlias */, 67897832 /* TypeAliasExcludes */); + break; + } + // falls through + case 100 /* ThisKeyword */: + if (currentFlow && (ts.isExpression(node) || parent.kind === 276 /* ShorthandPropertyAssignment */)) { + node.flowNode = currentFlow; + } + return checkStrictModeIdentifier(node); + case 189 /* PropertyAccessExpression */: + case 190 /* ElementAccessExpression */: + if (currentFlow && isNarrowableReference(node)) { + node.flowNode = currentFlow; + } + if (ts.isSpecialPropertyDeclaration(node)) { + bindSpecialPropertyDeclaration(node); + } + if (ts.isInJSFile(node) && + file.commonJsModuleIndicator && + ts.isModuleExportsPropertyAccessExpression(node) && + !lookupSymbolForNameWorker(blockScopeContainer, "module")) { + declareSymbol(file.locals, /*parent*/ undefined, node.expression, 1 /* FunctionScopedVariable */ | 134217728 /* ModuleExports */, 67220414 /* FunctionScopedVariableExcludes */); + } + break; + case 204 /* BinaryExpression */: + var specialKind = ts.getAssignmentDeclarationKind(node); + switch (specialKind) { + case 1 /* ExportsProperty */: + bindExportsPropertyAssignment(node); + break; + case 2 /* ModuleExports */: + bindModuleExportsAssignment(node); + break; + case 3 /* PrototypeProperty */: + bindPrototypePropertyAssignment(node.left, node); + break; + case 6 /* Prototype */: + bindPrototypeAssignment(node); + break; + case 4 /* ThisProperty */: + bindThisPropertyAssignment(node); + break; + case 5 /* Property */: + bindSpecialPropertyAssignment(node); + break; + case 0 /* None */: + // Nothing to do + break; + default: + ts.Debug.fail("Unknown binary expression special property assignment kind"); + } + return checkStrictModeBinaryExpression(node); + case 274 /* CatchClause */: + return checkStrictModeCatchClause(node); + case 198 /* DeleteExpression */: + return checkStrictModeDeleteExpression(node); + case 8 /* NumericLiteral */: + return checkStrictModeNumericLiteral(node); + case 203 /* PostfixUnaryExpression */: + return checkStrictModePostfixUnaryExpression(node); + case 202 /* PrefixUnaryExpression */: + return checkStrictModePrefixUnaryExpression(node); + case 231 /* WithStatement */: + return checkStrictModeWithStatement(node); + case 233 /* LabeledStatement */: + return checkStrictModeLabeledStatement(node); + case 178 /* ThisType */: + seenThisKeyword = true; + return; + case 163 /* TypePredicate */: + break; // Binding the children will handle everything + case 150 /* TypeParameter */: + return bindTypeParameter(node); + case 151 /* Parameter */: + return bindParameter(node); + case 237 /* VariableDeclaration */: + return bindVariableDeclarationOrBindingElement(node); + case 186 /* BindingElement */: + node.flowNode = currentFlow; + return bindVariableDeclarationOrBindingElement(node); + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + return bindPropertyWorker(node); + case 275 /* PropertyAssignment */: + case 276 /* ShorthandPropertyAssignment */: + return bindPropertyOrMethodOrAccessor(node, 4 /* Property */, 0 /* PropertyExcludes */); + case 278 /* EnumMember */: + return bindPropertyOrMethodOrAccessor(node, 8 /* EnumMember */, 68008959 /* EnumMemberExcludes */); + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 162 /* IndexSignature */: + return declareSymbolAndAddToSymbolTable(node, 131072 /* Signature */, 0 /* None */); + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + // If this is an ObjectLiteralExpression method, then it sits in the same space + // as other properties in the object literal. So we use SymbolFlags.PropertyExcludes + // so that it will conflict with any other object literal members with the same + // name. + return bindPropertyOrMethodOrAccessor(node, 8192 /* Method */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), ts.isObjectLiteralMethod(node) ? 0 /* PropertyExcludes */ : 67212223 /* MethodExcludes */); + case 239 /* FunctionDeclaration */: + return bindFunctionDeclaration(node); + case 157 /* Constructor */: + return declareSymbolAndAddToSymbolTable(node, 16384 /* Constructor */, /*symbolExcludes:*/ 0 /* None */); + case 158 /* GetAccessor */: + return bindPropertyOrMethodOrAccessor(node, 32768 /* GetAccessor */, 67154879 /* GetAccessorExcludes */); + case 159 /* SetAccessor */: + return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 67187647 /* SetAccessorExcludes */); + case 165 /* FunctionType */: + case 289 /* JSDocFunctionType */: + case 293 /* JSDocSignature */: + case 166 /* ConstructorType */: + return bindFunctionOrConstructorType(node); + case 168 /* TypeLiteral */: + case 292 /* JSDocTypeLiteral */: + case 181 /* MappedType */: + return bindAnonymousTypeWorker(node); + case 188 /* ObjectLiteralExpression */: + return bindObjectLiteralExpression(node); + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + return bindFunctionExpression(node); + case 191 /* CallExpression */: + var assignmentKind = ts.getAssignmentDeclarationKind(node); + switch (assignmentKind) { + case 7 /* ObjectDefinePropertyValue */: + return bindObjectDefinePropertyAssignment(node); + case 8 /* ObjectDefinePropertyExports */: + return bindObjectDefinePropertyExport(node); + case 9 /* ObjectDefinePrototypeProperty */: + return bindObjectDefinePrototypeProperty(node); + case 0 /* None */: + break; // Nothing to do + default: + return ts.Debug.fail("Unknown call expression assignment declaration kind"); + } + if (ts.isInJSFile(node)) { + bindCallExpression(node); + } + break; + // Members of classes, interfaces, and modules + case 209 /* ClassExpression */: + case 240 /* ClassDeclaration */: + // All classes are automatically in strict mode in ES6. + inStrictMode = true; + return bindClassLikeDeclaration(node); + case 241 /* InterfaceDeclaration */: + return bindBlockScopedDeclaration(node, 64 /* Interface */, 67897736 /* InterfaceExcludes */); + case 242 /* TypeAliasDeclaration */: + return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 67897832 /* TypeAliasExcludes */); + case 243 /* EnumDeclaration */: + return bindEnumDeclaration(node); + case 244 /* ModuleDeclaration */: + return bindModuleDeclaration(node); + // Jsx-attributes + case 268 /* JsxAttributes */: + return bindJsxAttributes(node); + case 267 /* JsxAttribute */: + return bindJsxAttribute(node, 4 /* Property */, 0 /* PropertyExcludes */); + // Imports and exports + case 248 /* ImportEqualsDeclaration */: + case 251 /* NamespaceImport */: + case 253 /* ImportSpecifier */: + case 257 /* ExportSpecifier */: + return declareSymbolAndAddToSymbolTable(node, 2097152 /* Alias */, 2097152 /* AliasExcludes */); + case 247 /* NamespaceExportDeclaration */: + return bindNamespaceExportDeclaration(node); + case 250 /* ImportClause */: + return bindImportClause(node); + case 255 /* ExportDeclaration */: + return bindExportDeclaration(node); + case 254 /* ExportAssignment */: + return bindExportAssignment(node); + case 279 /* SourceFile */: + updateStrictModeStatementList(node.statements); + return bindSourceFileIfExternalModule(); + case 218 /* Block */: + if (!ts.isFunctionLike(node.parent)) { + return; + } + // falls through + case 245 /* ModuleBlock */: + return updateStrictModeStatementList(node.statements); + case 299 /* JSDocParameterTag */: + if (node.parent.kind === 293 /* JSDocSignature */) { + return bindParameter(node); + } + if (node.parent.kind !== 292 /* JSDocTypeLiteral */) { + break; + } + // falls through + case 305 /* JSDocPropertyTag */: + var propTag = node; + var flags = propTag.isBracketed || propTag.typeExpression && propTag.typeExpression.type.kind === 288 /* JSDocOptionalType */ ? + 4 /* Property */ | 16777216 /* Optional */ : + 4 /* Property */; + return declareSymbolAndAddToSymbolTable(propTag, flags, 0 /* PropertyExcludes */); + case 304 /* JSDocTypedefTag */: + case 297 /* JSDocCallbackTag */: + return (delayedTypeAliases || (delayedTypeAliases = [])).push(node); + } + } + function bindPropertyWorker(node) { + return bindPropertyOrMethodOrAccessor(node, 4 /* Property */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), 0 /* PropertyExcludes */); + } + function bindAnonymousTypeWorker(node) { + return bindAnonymousDeclaration(node, 2048 /* TypeLiteral */, "__type" /* Type */); + } + function bindSourceFileIfExternalModule() { + setExportContextFlag(file); + if (ts.isExternalModule(file)) { + bindSourceFileAsExternalModule(); + } + else if (ts.isJsonSourceFile(file)) { + bindSourceFileAsExternalModule(); + // Create symbol equivalent for the module.exports = {} + var originalSymbol = file.symbol; + declareSymbol(file.symbol.exports, file.symbol, file, 4 /* Property */, 67108863 /* All */); + file.symbol = originalSymbol; + } + } + function bindSourceFileAsExternalModule() { + bindAnonymousDeclaration(file, 512 /* ValueModule */, "\"" + ts.removeFileExtension(file.fileName) + "\""); + } + function bindExportAssignment(node) { + if (!container.symbol || !container.symbol.exports) { + // Export assignment in some sort of block construct + bindAnonymousDeclaration(node, 2097152 /* Alias */, getDeclarationName(node)); + } + else { + var flags = ts.exportAssignmentIsAlias(node) + // An export default clause with an EntityNameExpression or a class expression exports all meanings of that identifier or expression; + ? 2097152 /* Alias */ + // An export default clause with any other expression exports a value + : 4 /* Property */; + // If there is an `export default x;` alias declaration, can't `export default` anything else. + // (In contrast, you can still have `export default function f() {}` and `export default interface I {}`.) + var symbol = declareSymbol(container.symbol.exports, container.symbol, node, flags, 67108863 /* All */); + if (node.isExportEquals) { + // Will be an error later, since the module already has other exports. Just make sure this has a valueDeclaration set. + setValueDeclaration(symbol, node); + } + } + } + function bindNamespaceExportDeclaration(node) { + if (node.modifiers && node.modifiers.length) { + file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Modifiers_cannot_appear_here)); + } + var diag = !ts.isSourceFile(node.parent) ? ts.Diagnostics.Global_module_exports_may_only_appear_at_top_level + : !ts.isExternalModule(node.parent) ? ts.Diagnostics.Global_module_exports_may_only_appear_in_module_files + : !node.parent.isDeclarationFile ? ts.Diagnostics.Global_module_exports_may_only_appear_in_declaration_files + : undefined; + if (diag) { + file.bindDiagnostics.push(createDiagnosticForNode(node, diag)); + } + else { + file.symbol.globalExports = file.symbol.globalExports || ts.createSymbolTable(); + declareSymbol(file.symbol.globalExports, file.symbol, node, 2097152 /* Alias */, 2097152 /* AliasExcludes */); + } + } + function bindExportDeclaration(node) { + if (!container.symbol || !container.symbol.exports) { + // Export * in some sort of block construct + bindAnonymousDeclaration(node, 8388608 /* ExportStar */, getDeclarationName(node)); + } + else if (!node.exportClause) { + // All export * declarations are collected in an __export symbol + declareSymbol(container.symbol.exports, container.symbol, node, 8388608 /* ExportStar */, 0 /* None */); + } + } + function bindImportClause(node) { + if (node.name) { + declareSymbolAndAddToSymbolTable(node, 2097152 /* Alias */, 2097152 /* AliasExcludes */); + } + } + function setCommonJsModuleIndicator(node) { + if (file.externalModuleIndicator) { + return false; + } + if (!file.commonJsModuleIndicator) { + file.commonJsModuleIndicator = node; + bindSourceFileAsExternalModule(); + } + return true; + } + function bindObjectDefinePropertyExport(node) { + if (!setCommonJsModuleIndicator(node)) { + return; + } + var symbol = forEachIdentifierInEntityName(node.arguments[0], /*parent*/ undefined, function (id, symbol) { + if (symbol) { + addDeclarationToSymbol(symbol, id, 1536 /* Module */ | 67108864 /* Assignment */); + } + return symbol; + }); + if (symbol) { + var flags = 4 /* Property */ | 1048576 /* ExportValue */; + declareSymbol(symbol.exports, symbol, node, flags, 0 /* None */); + } + } + function bindExportsPropertyAssignment(node) { + // When we create a property via 'exports.foo = bar', the 'exports.foo' property access + // expression is the declaration + if (!setCommonJsModuleIndicator(node)) { + return; + } + var lhs = node.left; + var symbol = forEachIdentifierInEntityName(lhs.expression, /*parent*/ undefined, function (id, symbol) { + if (symbol) { + addDeclarationToSymbol(symbol, id, 1536 /* Module */ | 67108864 /* Assignment */); + } + return symbol; + }); + if (symbol) { + var flags = ts.isClassExpression(node.right) ? + 4 /* Property */ | 1048576 /* ExportValue */ | 32 /* Class */ : + 4 /* Property */ | 1048576 /* ExportValue */; + declareSymbol(symbol.exports, symbol, lhs, flags, 0 /* None */); + } + } + function bindModuleExportsAssignment(node) { + // A common practice in node modules is to set 'export = module.exports = {}', this ensures that 'exports' + // is still pointing to 'module.exports'. + // We do not want to consider this as 'export=' since a module can have only one of these. + // Similarly we do not want to treat 'module.exports = exports' as an 'export='. + if (!setCommonJsModuleIndicator(node)) { + return; + } + var assignedExpression = ts.getRightMostAssignedExpression(node.right); + if (ts.isEmptyObjectLiteral(assignedExpression) || container === file && isExportsOrModuleExportsOrAlias(file, assignedExpression)) { + return; + } + // 'module.exports = expr' assignment + var flags = ts.exportAssignmentIsAlias(node) + ? 2097152 /* Alias */ + : 4 /* Property */ | 1048576 /* ExportValue */ | 512 /* ValueModule */; + declareSymbol(file.symbol.exports, file.symbol, node, flags | 67108864 /* Assignment */, 0 /* None */); + } + function bindThisPropertyAssignment(node) { + ts.Debug.assert(ts.isInJSFile(node)); + var thisContainer = ts.getThisContainer(node, /*includeArrowFunctions*/ false); + switch (thisContainer.kind) { + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + var constructorSymbol = thisContainer.symbol; + // For `f.prototype.m = function() { this.x = 0; }`, `this.x = 0` should modify `f`'s members, not the function expression. + if (ts.isBinaryExpression(thisContainer.parent) && thisContainer.parent.operatorToken.kind === 59 /* EqualsToken */) { + var l = thisContainer.parent.left; + if (ts.isPropertyAccessEntityNameExpression(l) && ts.isPrototypeAccess(l.expression)) { + constructorSymbol = lookupSymbolForPropertyAccess(l.expression.expression, thisParentContainer); + } + } + if (constructorSymbol) { + // Declare a 'member' if the container is an ES5 class or ES6 constructor + constructorSymbol.members = constructorSymbol.members || ts.createSymbolTable(); + // It's acceptable for multiple 'this' assignments of the same identifier to occur + declareSymbol(constructorSymbol.members, constructorSymbol, node, 4 /* Property */, 0 /* PropertyExcludes */ & ~4 /* Property */); + } + break; + case 157 /* Constructor */: + case 154 /* PropertyDeclaration */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + // this.foo assignment in a JavaScript class + // Bind this property to the containing class + var containingClass = thisContainer.parent; + var symbolTable = ts.hasModifier(thisContainer, 32 /* Static */) ? containingClass.symbol.exports : containingClass.symbol.members; + declareSymbol(symbolTable, containingClass.symbol, node, 4 /* Property */, 0 /* None */, /*isReplaceableByMethod*/ true); + break; + case 279 /* SourceFile */: + // this.foo assignment in a source file + // Do not bind. It would be nice to support this someday though. + break; + default: + ts.Debug.fail(ts.Debug.showSyntaxKind(thisContainer)); + } + } + function bindSpecialPropertyDeclaration(node) { + if (node.expression.kind === 100 /* ThisKeyword */) { + bindThisPropertyAssignment(node); + } + else if (ts.isPropertyAccessEntityNameExpression(node) && node.parent.parent.kind === 279 /* SourceFile */) { + if (ts.isPrototypeAccess(node.expression)) { + bindPrototypePropertyAssignment(node, node.parent); + } + else { + bindStaticPropertyAssignment(node); + } + } + } + /** For `x.prototype = { p, ... }`, declare members p,... if `x` is function/class/{}, or not declared. */ + function bindPrototypeAssignment(node) { + node.left.parent = node; + node.right.parent = node; + var lhs = node.left; + bindPropertyAssignment(lhs.expression, lhs, /*isPrototypeProperty*/ false); + } + function bindObjectDefinePrototypeProperty(node) { + var namespaceSymbol = lookupSymbolForPropertyAccess(node.arguments[0].expression); + bindPotentiallyNewExpandoMemberToNamespace(node, namespaceSymbol, /*isPrototypeProperty*/ true); + } + /** + * For `x.prototype.y = z`, declare a member `y` on `x` if `x` is a function or class, or not declared. + * Note that jsdoc preceding an ExpressionStatement like `x.prototype.y;` is also treated as a declaration. + */ + function bindPrototypePropertyAssignment(lhs, parent) { + // Look up the function in the local scope, since prototype assignments should + // follow the function declaration + var classPrototype = lhs.expression; + var constructorFunction = classPrototype.expression; + // Fix up parent pointers since we're going to use these nodes before we bind into them + lhs.parent = parent; + constructorFunction.parent = classPrototype; + classPrototype.parent = lhs; + bindPropertyAssignment(constructorFunction, lhs, /*isPrototypeProperty*/ true); + } + function bindObjectDefinePropertyAssignment(node) { + var namespaceSymbol = lookupSymbolForPropertyAccess(node.arguments[0]); + var isToplevel = node.parent.parent.kind === 279 /* SourceFile */; + namespaceSymbol = bindPotentiallyMissingNamespaces(namespaceSymbol, node.arguments[0], isToplevel, /*isPrototypeProperty*/ false); + bindPotentiallyNewExpandoMemberToNamespace(node, namespaceSymbol, /*isPrototypeProperty*/ false); + } + function bindSpecialPropertyAssignment(node) { + var lhs = node.left; + // Class declarations in Typescript do not allow property declarations + var parentSymbol = lookupSymbolForPropertyAccess(lhs.expression); + if (!ts.isInJSFile(node) && !ts.isFunctionSymbol(parentSymbol)) { + return; + } + // Fix up parent pointers since we're going to use these nodes before we bind into them + node.left.parent = node; + node.right.parent = node; + if (ts.isIdentifier(lhs.expression) && container === file && isNameOfExportsOrModuleExportsAliasDeclaration(file, lhs.expression)) { + // This can be an alias for the 'exports' or 'module.exports' names, e.g. + // var util = module.exports; + // util.property = function ... + bindExportsPropertyAssignment(node); + } + else { + bindStaticPropertyAssignment(lhs); + } + } + /** + * For nodes like `x.y = z`, declare a member 'y' on 'x' if x is a function (or IIFE) or class or {}, or not declared. + * Also works for expression statements preceded by JSDoc, like / ** @type number * / x.y; + */ + function bindStaticPropertyAssignment(node) { + node.expression.parent = node; + bindPropertyAssignment(node.expression, node, /*isPrototypeProperty*/ false); + } + function bindPotentiallyMissingNamespaces(namespaceSymbol, entityName, isToplevel, isPrototypeProperty) { + if (isToplevel && !isPrototypeProperty && (!namespaceSymbol || !(namespaceSymbol.flags & 1920 /* Namespace */))) { + // make symbols or add declarations for intermediate containers + var flags_1 = 1536 /* Module */ | 67108864 /* Assignment */; + var excludeFlags_1 = 110735 /* ValueModuleExcludes */ & ~67108864 /* Assignment */; + namespaceSymbol = forEachIdentifierInEntityName(entityName, namespaceSymbol, function (id, symbol, parent) { + if (symbol) { + addDeclarationToSymbol(symbol, id, flags_1); + return symbol; + } + else { + var table = parent ? parent.exports : + file.jsGlobalAugmentations || (file.jsGlobalAugmentations = ts.createSymbolTable()); + return declareSymbol(table, parent, id, flags_1, excludeFlags_1); + } + }); + } + return namespaceSymbol; + } + function bindPotentiallyNewExpandoMemberToNamespace(declaration, namespaceSymbol, isPrototypeProperty) { + if (!namespaceSymbol || !isExpandoSymbol(namespaceSymbol)) { + return; + } + // Set up the members collection if it doesn't exist already + var symbolTable = isPrototypeProperty ? + (namespaceSymbol.members || (namespaceSymbol.members = ts.createSymbolTable())) : + (namespaceSymbol.exports || (namespaceSymbol.exports = ts.createSymbolTable())); + var isMethod = ts.isFunctionLikeDeclaration(ts.getAssignedExpandoInitializer(declaration)); + var includes = isMethod ? 8192 /* Method */ : 4 /* Property */; + var excludes = isMethod ? 67212223 /* MethodExcludes */ : 0 /* PropertyExcludes */; + declareSymbol(symbolTable, namespaceSymbol, declaration, includes | 67108864 /* Assignment */, excludes & ~67108864 /* Assignment */); + } + function bindPropertyAssignment(name, propertyAccess, isPrototypeProperty) { + var namespaceSymbol = lookupSymbolForPropertyAccess(name); + var isToplevel = ts.isBinaryExpression(propertyAccess.parent) + ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 279 /* SourceFile */ + : propertyAccess.parent.parent.kind === 279 /* SourceFile */; + namespaceSymbol = bindPotentiallyMissingNamespaces(namespaceSymbol, propertyAccess.expression, isToplevel, isPrototypeProperty); + bindPotentiallyNewExpandoMemberToNamespace(propertyAccess, namespaceSymbol, isPrototypeProperty); + } + /** + * Javascript expando values are: + * - Functions + * - classes + * - namespaces + * - variables initialized with function expressions + * - with class expressions + * - with empty object literals + * - with non-empty object literals if assigned to the prototype property + */ + function isExpandoSymbol(symbol) { + if (symbol.flags & (16 /* Function */ | 32 /* Class */ | 1024 /* NamespaceModule */)) { + return true; + } + var node = symbol.valueDeclaration; + if (node && ts.isCallExpression(node)) { + return !!ts.getAssignedExpandoInitializer(node); + } + var init = !node ? undefined : + ts.isVariableDeclaration(node) ? node.initializer : + ts.isBinaryExpression(node) ? node.right : + ts.isPropertyAccessExpression(node) && ts.isBinaryExpression(node.parent) ? node.parent.right : + undefined; + init = init && ts.getRightMostAssignedExpression(init); + if (init) { + var isPrototypeAssignment = ts.isPrototypeAccess(ts.isVariableDeclaration(node) ? node.name : ts.isBinaryExpression(node) ? node.left : node); + return !!ts.getExpandoInitializer(ts.isBinaryExpression(init) && init.operatorToken.kind === 55 /* BarBarToken */ ? init.right : init, isPrototypeAssignment); + } + return false; + } + function getParentOfBinaryExpression(expr) { + while (ts.isBinaryExpression(expr.parent)) { + expr = expr.parent; + } + return expr.parent; + } + function lookupSymbolForPropertyAccess(node, lookupContainer) { + if (lookupContainer === void 0) { lookupContainer = container; } + if (ts.isIdentifier(node)) { + return lookupSymbolForNameWorker(lookupContainer, node.escapedText); + } + else { + var symbol = lookupSymbolForPropertyAccess(node.expression); + return symbol && symbol.exports && symbol.exports.get(node.name.escapedText); + } + } + function forEachIdentifierInEntityName(e, parent, action) { + if (isExportsOrModuleExportsOrAlias(file, e)) { + return file.symbol; + } + else if (ts.isIdentifier(e)) { + return action(e, lookupSymbolForPropertyAccess(e), parent); + } + else { + var s = forEachIdentifierInEntityName(e.expression, parent, action); + if (!s || !s.exports) + return ts.Debug.fail(); + return action(e.name, s.exports.get(e.name.escapedText), s); + } + } + function bindCallExpression(node) { + // We're only inspecting call expressions to detect CommonJS modules, so we can skip + // this check if we've already seen the module indicator + if (!file.commonJsModuleIndicator && ts.isRequireCall(node, /*checkArgumentIsStringLiteralLike*/ false)) { + setCommonJsModuleIndicator(node); + } + } + function bindClassLikeDeclaration(node) { + if (node.kind === 240 /* ClassDeclaration */) { + bindBlockScopedDeclaration(node, 32 /* Class */, 68008383 /* ClassExcludes */); + } + else { + var bindingName = node.name ? node.name.escapedText : "__class" /* Class */; + bindAnonymousDeclaration(node, 32 /* Class */, bindingName); + // Add name of class expression into the map for semantic classifier + if (node.name) { + classifiableNames.set(node.name.escapedText, true); + } + } + var symbol = node.symbol; + // TypeScript 1.0 spec (April 2014): 8.4 + // Every class automatically contains a static property member named 'prototype', the + // type of which is an instantiation of the class type with type Any supplied as a type + // argument for each type parameter. It is an error to explicitly declare a static + // property member with the name 'prototype'. + // + // Note: we check for this here because this class may be merging into a module. The + // module might have an exported variable called 'prototype'. We can't allow that as + // that would clash with the built-in 'prototype' for the class. + var prototypeSymbol = createSymbol(4 /* Property */ | 4194304 /* Prototype */, "prototype"); + var symbolExport = symbol.exports.get(prototypeSymbol.escapedName); + if (symbolExport) { + if (node.name) { + node.name.parent = node; + } + file.bindDiagnostics.push(createDiagnosticForNode(symbolExport.declarations[0], ts.Diagnostics.Duplicate_identifier_0, ts.symbolName(prototypeSymbol))); + } + symbol.exports.set(prototypeSymbol.escapedName, prototypeSymbol); + prototypeSymbol.parent = symbol; + } + function bindEnumDeclaration(node) { + return ts.isEnumConst(node) + ? bindBlockScopedDeclaration(node, 128 /* ConstEnum */, 68008831 /* ConstEnumExcludes */) + : bindBlockScopedDeclaration(node, 256 /* RegularEnum */, 68008191 /* RegularEnumExcludes */); + } + function bindVariableDeclarationOrBindingElement(node) { + if (inStrictMode) { + checkStrictModeEvalOrArguments(node, node.name); + } + if (!ts.isBindingPattern(node.name)) { + var isEnum = ts.isInJSFile(node) && !!ts.getJSDocEnumTag(node); + var enumFlags = (isEnum ? 256 /* RegularEnum */ : 0 /* None */); + var enumExcludes = (isEnum ? 68008191 /* RegularEnumExcludes */ : 0 /* None */); + if (ts.isBlockOrCatchScoped(node)) { + bindBlockScopedDeclaration(node, 2 /* BlockScopedVariable */ | enumFlags, 67220415 /* BlockScopedVariableExcludes */ | enumExcludes); + } + else if (ts.isParameterDeclaration(node)) { + // It is safe to walk up parent chain to find whether the node is a destructuring parameter declaration + // because its parent chain has already been set up, since parents are set before descending into children. + // + // If node is a binding element in parameter declaration, we need to use ParameterExcludes. + // Using ParameterExcludes flag allows the compiler to report an error on duplicate identifiers in Parameter Declaration + // For example: + // function foo([a,a]) {} // Duplicate Identifier error + // function bar(a,a) {} // Duplicate Identifier error, parameter declaration in this case is handled in bindParameter + // // which correctly set excluded symbols + declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67220415 /* ParameterExcludes */); + } + else { + declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */ | enumFlags, 67220414 /* FunctionScopedVariableExcludes */ | enumExcludes); + } + } + } + function bindParameter(node) { + if (node.kind === 299 /* JSDocParameterTag */ && container.kind !== 293 /* JSDocSignature */) { + return; + } + if (inStrictMode && !(node.flags & 4194304 /* Ambient */)) { + // It is a SyntaxError if the identifier eval or arguments appears within a FormalParameterList of a + // strict mode FunctionLikeDeclaration or FunctionExpression(13.1) + checkStrictModeEvalOrArguments(node, node.name); + } + if (ts.isBindingPattern(node.name)) { + bindAnonymousDeclaration(node, 1 /* FunctionScopedVariable */, "__" + node.parent.parameters.indexOf(node)); + } + else { + declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67220415 /* ParameterExcludes */); + } + // If this is a property-parameter, then also declare the property symbol into the + // containing class. + if (ts.isParameterPropertyDeclaration(node)) { + var classDeclaration = node.parent.parent; + declareSymbol(classDeclaration.symbol.members, classDeclaration.symbol, node, 4 /* Property */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), 0 /* PropertyExcludes */); + } + } + function bindFunctionDeclaration(node) { + if (!file.isDeclarationFile && !(node.flags & 4194304 /* Ambient */)) { + if (ts.isAsyncFunction(node)) { + emitFlags |= 1024 /* HasAsyncFunctions */; + } + } + checkStrictModeFunctionName(node); + if (inStrictMode) { + checkStrictModeFunctionDeclaration(node); + bindBlockScopedDeclaration(node, 16 /* Function */, 67219887 /* FunctionExcludes */); + } + else { + declareSymbolAndAddToSymbolTable(node, 16 /* Function */, 67219887 /* FunctionExcludes */); + } + } + function bindFunctionExpression(node) { + if (!file.isDeclarationFile && !(node.flags & 4194304 /* Ambient */)) { + if (ts.isAsyncFunction(node)) { + emitFlags |= 1024 /* HasAsyncFunctions */; + } + } + if (currentFlow) { + node.flowNode = currentFlow; + } + checkStrictModeFunctionName(node); + var bindingName = node.name ? node.name.escapedText : "__function" /* Function */; + return bindAnonymousDeclaration(node, 16 /* Function */, bindingName); + } + function bindPropertyOrMethodOrAccessor(node, symbolFlags, symbolExcludes) { + if (!file.isDeclarationFile && !(node.flags & 4194304 /* Ambient */) && ts.isAsyncFunction(node)) { + emitFlags |= 1024 /* HasAsyncFunctions */; + } + if (currentFlow && ts.isObjectLiteralOrClassExpressionMethod(node)) { + node.flowNode = currentFlow; + } + return ts.hasDynamicName(node) + ? bindAnonymousDeclaration(node, symbolFlags, "__computed" /* Computed */) + : declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes); + } + function getInferTypeContainer(node) { + var extendsType = ts.findAncestor(node, function (n) { return n.parent && ts.isConditionalTypeNode(n.parent) && n.parent.extendsType === n; }); + return extendsType && extendsType.parent; + } + function bindTypeParameter(node) { + if (ts.isJSDocTemplateTag(node.parent)) { + var container_1 = ts.find(node.parent.parent.tags, ts.isJSDocTypeAlias) || ts.getHostSignatureFromJSDoc(node.parent); // TODO: GH#18217 + if (container_1) { + if (!container_1.locals) { + container_1.locals = ts.createSymbolTable(); + } + declareSymbol(container_1.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 67635688 /* TypeParameterExcludes */); + } + else { + declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 67635688 /* TypeParameterExcludes */); + } + } + else if (node.parent.kind === 176 /* InferType */) { + var container_2 = getInferTypeContainer(node.parent); + if (container_2) { + if (!container_2.locals) { + container_2.locals = ts.createSymbolTable(); + } + declareSymbol(container_2.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 67635688 /* TypeParameterExcludes */); + } + else { + bindAnonymousDeclaration(node, 262144 /* TypeParameter */, getDeclarationName(node)); // TODO: GH#18217 + } + } + else { + declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 67635688 /* TypeParameterExcludes */); + } + } + // reachability checks + function shouldReportErrorOnModuleDeclaration(node) { + var instanceState = getModuleInstanceState(node); + return instanceState === 1 /* Instantiated */ || (instanceState === 2 /* ConstEnumOnly */ && !!options.preserveConstEnums); + } + function checkUnreachable(node) { + if (!(currentFlow.flags & 1 /* Unreachable */)) { + return false; + } + if (currentFlow === unreachableFlow) { + var reportError = + // report error on all statements except empty ones + (ts.isStatementButNotDeclaration(node) && node.kind !== 220 /* EmptyStatement */) || + // report error on class declarations + node.kind === 240 /* ClassDeclaration */ || + // report error on instantiated modules or const-enums only modules if preserveConstEnums is set + (node.kind === 244 /* ModuleDeclaration */ && shouldReportErrorOnModuleDeclaration(node)); + if (reportError) { + currentFlow = reportedUnreachableFlow; + if (!options.allowUnreachableCode) { + // unreachable code is reported if + // - user has explicitly asked about it AND + // - statement is in not ambient context (statements in ambient context is already an error + // so we should not report extras) AND + // - node is not variable statement OR + // - node is block scoped variable statement OR + // - node is not block scoped variable statement and at least one variable declaration has initializer + // Rationale: we don't want to report errors on non-initialized var's since they are hoisted + // On the other side we do want to report errors on non-initialized 'lets' because of TDZ + var isError_1 = ts.unreachableCodeIsError(options) && + !(node.flags & 4194304 /* Ambient */) && + (!ts.isVariableStatement(node) || + !!(ts.getCombinedNodeFlags(node.declarationList) & 3 /* BlockScoped */) || + node.declarationList.declarations.some(function (d) { return !!d.initializer; })); + eachUnreachableRange(node, function (start, end) { return errorOrSuggestionOnRange(isError_1, start, end, ts.Diagnostics.Unreachable_code_detected); }); + } + } + } + return true; + } + } + function eachUnreachableRange(node, cb) { + if (ts.isStatement(node) && isExecutableStatement(node) && ts.isBlock(node.parent)) { + var statements = node.parent.statements; + var slice_1 = ts.sliceAfter(statements, node); + ts.getRangesWhere(slice_1, isExecutableStatement, function (start, afterEnd) { return cb(slice_1[start], slice_1[afterEnd - 1]); }); + } + else { + cb(node, node); + } + } + // As opposed to a pure declaration like an `interface` + function isExecutableStatement(s) { + // Don't remove statements that can validly be used before they appear. + return !ts.isFunctionDeclaration(s) && !isPurelyTypeDeclaration(s) && !ts.isEnumDeclaration(s) && + // `var x;` may declare a variable used above + !(ts.isVariableStatement(s) && !(ts.getCombinedNodeFlags(s) & (1 /* Let */ | 2 /* Const */)) && s.declarationList.declarations.some(function (d) { return !d.initializer; })); + } + function isPurelyTypeDeclaration(s) { + switch (s.kind) { + case 241 /* InterfaceDeclaration */: + case 242 /* TypeAliasDeclaration */: + return true; + case 244 /* ModuleDeclaration */: + return getModuleInstanceState(s) !== 1 /* Instantiated */; + case 243 /* EnumDeclaration */: + return ts.hasModifier(s, 2048 /* Const */); + default: + return false; + } + } + function isExportsOrModuleExportsOrAlias(sourceFile, node) { + return ts.isExportsIdentifier(node) || + ts.isModuleExportsPropertyAccessExpression(node) || + ts.isIdentifier(node) && isNameOfExportsOrModuleExportsAliasDeclaration(sourceFile, node); + } + ts.isExportsOrModuleExportsOrAlias = isExportsOrModuleExportsOrAlias; + function isNameOfExportsOrModuleExportsAliasDeclaration(sourceFile, node) { + var symbol = lookupSymbolForNameWorker(sourceFile, node.escapedText); + return !!symbol && !!symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && + !!symbol.valueDeclaration.initializer && isExportsOrModuleExportsOrAliasOrAssignment(sourceFile, symbol.valueDeclaration.initializer); + } + function isExportsOrModuleExportsOrAliasOrAssignment(sourceFile, node) { + return isExportsOrModuleExportsOrAlias(sourceFile, node) || + (ts.isAssignmentExpression(node, /*excludeCompoundAssignment*/ true) && (isExportsOrModuleExportsOrAliasOrAssignment(sourceFile, node.left) || isExportsOrModuleExportsOrAliasOrAssignment(sourceFile, node.right))); + } + function lookupSymbolForNameWorker(container, name) { + var local = container.locals && container.locals.get(name); + if (local) { + return local.exportSymbol || local; + } + if (ts.isSourceFile(container) && container.jsGlobalAugmentations && container.jsGlobalAugmentations.has(name)) { + return container.jsGlobalAugmentations.get(name); + } + return container.symbol && container.symbol.exports && container.symbol.exports.get(name); + } + /** + * Computes the transform flags for a node, given the transform flags of its subtree + * + * @param node The node to analyze + * @param subtreeFlags Transform flags computed for this node's subtree + */ + function computeTransformFlagsForNode(node, subtreeFlags) { + var kind = node.kind; + switch (kind) { + case 191 /* CallExpression */: + return computeCallExpression(node, subtreeFlags); + case 192 /* NewExpression */: + return computeNewExpression(node, subtreeFlags); + case 244 /* ModuleDeclaration */: + return computeModuleDeclaration(node, subtreeFlags); + case 195 /* ParenthesizedExpression */: + return computeParenthesizedExpression(node, subtreeFlags); + case 204 /* BinaryExpression */: + return computeBinaryExpression(node, subtreeFlags); + case 221 /* ExpressionStatement */: + return computeExpressionStatement(node, subtreeFlags); + case 151 /* Parameter */: + return computeParameter(node, subtreeFlags); + case 197 /* ArrowFunction */: + return computeArrowFunction(node, subtreeFlags); + case 196 /* FunctionExpression */: + return computeFunctionExpression(node, subtreeFlags); + case 239 /* FunctionDeclaration */: + return computeFunctionDeclaration(node, subtreeFlags); + case 237 /* VariableDeclaration */: + return computeVariableDeclaration(node, subtreeFlags); + case 238 /* VariableDeclarationList */: + return computeVariableDeclarationList(node, subtreeFlags); + case 219 /* VariableStatement */: + return computeVariableStatement(node, subtreeFlags); + case 233 /* LabeledStatement */: + return computeLabeledStatement(node, subtreeFlags); + case 240 /* ClassDeclaration */: + return computeClassDeclaration(node, subtreeFlags); + case 209 /* ClassExpression */: + return computeClassExpression(node, subtreeFlags); + case 273 /* HeritageClause */: + return computeHeritageClause(node, subtreeFlags); + case 274 /* CatchClause */: + return computeCatchClause(node, subtreeFlags); + case 211 /* ExpressionWithTypeArguments */: + return computeExpressionWithTypeArguments(node, subtreeFlags); + case 157 /* Constructor */: + return computeConstructor(node, subtreeFlags); + case 154 /* PropertyDeclaration */: + return computePropertyDeclaration(node, subtreeFlags); + case 156 /* MethodDeclaration */: + return computeMethod(node, subtreeFlags); + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + return computeAccessor(node, subtreeFlags); + case 248 /* ImportEqualsDeclaration */: + return computeImportEquals(node, subtreeFlags); + case 189 /* PropertyAccessExpression */: + return computePropertyAccess(node, subtreeFlags); + case 190 /* ElementAccessExpression */: + return computeElementAccess(node, subtreeFlags); + default: + return computeOther(node, kind, subtreeFlags); + } + } + ts.computeTransformFlagsForNode = computeTransformFlagsForNode; + function computeCallExpression(node, subtreeFlags) { + var transformFlags = subtreeFlags; + var expression = node.expression; + if (node.typeArguments) { + transformFlags |= 3 /* AssertTypeScript */; + } + if (subtreeFlags & 131072 /* ContainsRestOrSpread */ + || (expression.transformFlags & (33554432 /* Super */ | 67108864 /* ContainsSuper */))) { + // If the this node contains a SpreadExpression, or is a super call, then it is an ES6 + // node. + transformFlags |= 192 /* AssertES2015 */; + // super property or element accesses could be inside lambdas, etc, and need a captured `this`, + // while super keyword for super calls (indicated by TransformFlags.Super) does not (since it can only be top-level in a constructor) + if (expression.transformFlags & 67108864 /* ContainsSuper */) { + transformFlags |= 8192 /* ContainsLexicalThis */; + } + } + if (expression.kind === 92 /* ImportKeyword */) { + transformFlags |= 16777216 /* ContainsDynamicImport */; + // A dynamic 'import()' call that contains a lexical 'this' will + // require a captured 'this' when emitting down-level. + if (subtreeFlags & 8192 /* ContainsLexicalThis */) { + transformFlags |= 16384 /* ContainsCapturedLexicalThis */; + } + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~637666625 /* ArrayLiteralOrCallOrNewExcludes */; + } + function computeNewExpression(node, subtreeFlags) { + var transformFlags = subtreeFlags; + if (node.typeArguments) { + transformFlags |= 3 /* AssertTypeScript */; + } + if (subtreeFlags & 131072 /* ContainsRestOrSpread */) { + // If the this node contains a SpreadElementExpression then it is an ES6 + // node. + transformFlags |= 192 /* AssertES2015 */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~637666625 /* ArrayLiteralOrCallOrNewExcludes */; + } + function computeBinaryExpression(node, subtreeFlags) { + var transformFlags = subtreeFlags; + var operatorTokenKind = node.operatorToken.kind; + var leftKind = node.left.kind; + if (operatorTokenKind === 59 /* EqualsToken */ && leftKind === 188 /* ObjectLiteralExpression */) { + // Destructuring object assignments with are ES2015 syntax + // and possibly ESNext if they contain rest + transformFlags |= 8 /* AssertESNext */ | 192 /* AssertES2015 */ | 3072 /* AssertDestructuringAssignment */; + } + else if (operatorTokenKind === 59 /* EqualsToken */ && leftKind === 187 /* ArrayLiteralExpression */) { + // Destructuring assignments are ES2015 syntax. + transformFlags |= 192 /* AssertES2015 */ | 3072 /* AssertDestructuringAssignment */; + } + else if (operatorTokenKind === 41 /* AsteriskAsteriskToken */ + || operatorTokenKind === 63 /* AsteriskAsteriskEqualsToken */) { + // Exponentiation is ES2016 syntax. + transformFlags |= 32 /* AssertES2016 */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~637535553 /* NodeExcludes */; + } + function computeParameter(node, subtreeFlags) { + var transformFlags = subtreeFlags; + var name = node.name; + var initializer = node.initializer; + var dotDotDotToken = node.dotDotDotToken; + // The '?' token, type annotations, decorators, and 'this' parameters are TypeSCript + // syntax. + if (node.questionToken + || node.type + || (subtreeFlags & 4096 /* ContainsTypeScriptClassSyntax */ && ts.some(node.decorators)) + || ts.isThisIdentifier(name)) { + transformFlags |= 3 /* AssertTypeScript */; + } + // If a parameter has an accessibility modifier, then it is TypeScript syntax. + if (ts.hasModifier(node, 92 /* ParameterPropertyModifier */)) { + transformFlags |= 3 /* AssertTypeScript */ | 4096 /* ContainsTypeScriptClassSyntax */; + } + // parameters with object rest destructuring are ES Next syntax + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { + transformFlags |= 8 /* AssertESNext */; + } + // If a parameter has an initializer, a binding pattern or a dotDotDot token, then + // it is ES6 syntax and its container must emit default value assignments or parameter destructuring downlevel. + if (subtreeFlags & 2097152 /* ContainsBindingPattern */ || initializer || dotDotDotToken) { + transformFlags |= 192 /* AssertES2015 */ | 65536 /* ContainsDefaultValueAssignments */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~637535553 /* ParameterExcludes */; + } + function computeParenthesizedExpression(node, subtreeFlags) { + var transformFlags = subtreeFlags; + var expression = node.expression; + var expressionKind = expression.kind; + var expressionTransformFlags = expression.transformFlags; + // If the node is synthesized, it means the emitter put the parentheses there, + // not the user. If we didn't want them, the emitter would not have put them + // there. + if (expressionKind === 212 /* AsExpression */ + || expressionKind === 194 /* TypeAssertionExpression */) { + transformFlags |= 3 /* AssertTypeScript */; + } + // If the expression of a ParenthesizedExpression is a destructuring assignment, + // then the ParenthesizedExpression is a destructuring assignment. + if (expressionTransformFlags & 1024 /* DestructuringAssignment */) { + transformFlags |= 1024 /* DestructuringAssignment */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~536872257 /* OuterExpressionExcludes */; + } + function computeClassDeclaration(node, subtreeFlags) { + var transformFlags; + if (ts.hasModifier(node, 2 /* Ambient */)) { + // An ambient declaration is TypeScript syntax. + transformFlags = 3 /* AssertTypeScript */; + } + else { + // A ClassDeclaration is ES6 syntax. + transformFlags = subtreeFlags | 192 /* AssertES2015 */; + // A class with a parameter property assignment, property initializer, computed property name, or decorator is + // TypeScript syntax. + // An exported declaration may be TypeScript syntax, but is handled by the visitor + // for a namespace declaration. + if ((subtreeFlags & 4096 /* ContainsTypeScriptClassSyntax */) + || node.typeParameters) { + transformFlags |= 3 /* AssertTypeScript */; + } + if (subtreeFlags & 32768 /* ContainsLexicalThisInComputedPropertyName */) { + // A computed property name containing `this` might need to be rewritten, + // so propagate the ContainsLexicalThis flag upward. + transformFlags |= 8192 /* ContainsLexicalThis */; + } + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~638121281 /* ClassExcludes */; + } + function computeClassExpression(node, subtreeFlags) { + // A ClassExpression is ES6 syntax. + var transformFlags = subtreeFlags | 192 /* AssertES2015 */; + // A class with a parameter property assignment, property initializer, or decorator is + // TypeScript syntax. + if (subtreeFlags & 4096 /* ContainsTypeScriptClassSyntax */ + || node.typeParameters) { + transformFlags |= 3 /* AssertTypeScript */; + } + if (subtreeFlags & 32768 /* ContainsLexicalThisInComputedPropertyName */) { + // A computed property name containing `this` might need to be rewritten, + // so propagate the ContainsLexicalThis flag upward. + transformFlags |= 8192 /* ContainsLexicalThis */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~638121281 /* ClassExcludes */; + } + function computeHeritageClause(node, subtreeFlags) { + var transformFlags = subtreeFlags; + switch (node.token) { + case 86 /* ExtendsKeyword */: + // An `extends` HeritageClause is ES6 syntax. + transformFlags |= 192 /* AssertES2015 */; + break; + case 109 /* ImplementsKeyword */: + // An `implements` HeritageClause is TypeScript syntax. + transformFlags |= 3 /* AssertTypeScript */; + break; + default: + ts.Debug.fail("Unexpected token for heritage clause"); + break; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~637535553 /* NodeExcludes */; + } + function computeCatchClause(node, subtreeFlags) { + var transformFlags = subtreeFlags; + if (!node.variableDeclaration) { + transformFlags |= 8 /* AssertESNext */; + } + else if (ts.isBindingPattern(node.variableDeclaration.name)) { + transformFlags |= 192 /* AssertES2015 */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~637797697 /* CatchClauseExcludes */; + } + function computeExpressionWithTypeArguments(node, subtreeFlags) { + // An ExpressionWithTypeArguments is ES6 syntax, as it is used in the + // extends clause of a class. + var transformFlags = subtreeFlags | 192 /* AssertES2015 */; + // If an ExpressionWithTypeArguments contains type arguments, then it + // is TypeScript syntax. + if (node.typeArguments) { + transformFlags |= 3 /* AssertTypeScript */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~637535553 /* NodeExcludes */; + } + function computeConstructor(node, subtreeFlags) { + var transformFlags = subtreeFlags; + // TypeScript-specific modifiers and overloads are TypeScript syntax + if (ts.hasModifier(node, 2270 /* TypeScriptModifier */) + || !node.body) { + transformFlags |= 3 /* AssertTypeScript */; + } + // function declarations with object rest destructuring are ES Next syntax + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { + transformFlags |= 8 /* AssertESNext */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~653616449 /* ConstructorExcludes */; + } + function computeMethod(node, subtreeFlags) { + // A MethodDeclaration is ES6 syntax. + var transformFlags = subtreeFlags | 192 /* AssertES2015 */; + // Decorators, TypeScript-specific modifiers, type parameters, type annotations, and + // overloads are TypeScript syntax. + if (node.decorators + || ts.hasModifier(node, 2270 /* TypeScriptModifier */) + || node.typeParameters + || node.type + || (node.name && ts.isComputedPropertyName(node.name)) // While computed method names aren't typescript, the TS transform must visit them to emit property declarations correctly + || !node.body) { + transformFlags |= 3 /* AssertTypeScript */; + } + // function declarations with object rest destructuring are ES Next syntax + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { + transformFlags |= 8 /* AssertESNext */; + } + // An async method declaration is ES2017 syntax. + if (ts.hasModifier(node, 256 /* Async */)) { + transformFlags |= node.asteriskToken ? 8 /* AssertESNext */ : 16 /* AssertES2017 */; + } + if (node.asteriskToken) { + transformFlags |= 768 /* AssertGenerator */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~653616449 /* MethodOrAccessorExcludes */; + } + function computeAccessor(node, subtreeFlags) { + var transformFlags = subtreeFlags; + // Decorators, TypeScript-specific modifiers, type annotations, and overloads are + // TypeScript syntax. + if (node.decorators + || ts.hasModifier(node, 2270 /* TypeScriptModifier */) + || node.type + || (node.name && ts.isComputedPropertyName(node.name)) // While computed accessor names aren't typescript, the TS transform must visit them to emit property declarations correctly + || !node.body) { + transformFlags |= 3 /* AssertTypeScript */; + } + // function declarations with object rest destructuring are ES Next syntax + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { + transformFlags |= 8 /* AssertESNext */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~653616449 /* MethodOrAccessorExcludes */; + } + function computePropertyDeclaration(node, subtreeFlags) { + // A PropertyDeclaration is TypeScript syntax. + var transformFlags = subtreeFlags | 3 /* AssertTypeScript */; + // If the PropertyDeclaration has an initializer or a computed name, we need to inform its ancestor + // so that it handle the transformation. + if (node.initializer || ts.isComputedPropertyName(node.name)) { + transformFlags |= 4096 /* ContainsTypeScriptClassSyntax */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~637535553 /* NodeExcludes */; + } + function computeFunctionDeclaration(node, subtreeFlags) { + var transformFlags; + var modifierFlags = ts.getModifierFlags(node); + var body = node.body; + if (!body || (modifierFlags & 2 /* Ambient */)) { + // An ambient declaration is TypeScript syntax. + // A FunctionDeclaration without a body is an overload and is TypeScript syntax. + transformFlags = 3 /* AssertTypeScript */; + } + else { + transformFlags = subtreeFlags | 8388608 /* ContainsHoistedDeclarationOrCompletion */; + // TypeScript-specific modifiers, type parameters, and type annotations are TypeScript + // syntax. + if (modifierFlags & 2270 /* TypeScriptModifier */ + || node.typeParameters + || node.type) { + transformFlags |= 3 /* AssertTypeScript */; + } + // An async function declaration is ES2017 syntax. + if (modifierFlags & 256 /* Async */) { + transformFlags |= node.asteriskToken ? 8 /* AssertESNext */ : 16 /* AssertES2017 */; + } + // function declarations with object rest destructuring are ES Next syntax + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { + transformFlags |= 8 /* AssertESNext */; + } + // If a FunctionDeclaration's subtree has marked the container as needing to capture the + // lexical this, or the function contains parameters with initializers, then this node is + // ES6 syntax. + if (subtreeFlags & 81920 /* ES2015FunctionSyntaxMask */) { + transformFlags |= 192 /* AssertES2015 */; + } + // If a FunctionDeclaration is generator function and is the body of a + // transformed async function, then this node can be transformed to a + // down-level generator. + // Currently we do not support transforming any other generator fucntions + // down level. + if (node.asteriskToken) { + transformFlags |= 768 /* AssertGenerator */; + } + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~653620545 /* FunctionExcludes */; + } + function computeFunctionExpression(node, subtreeFlags) { + var transformFlags = subtreeFlags; + // TypeScript-specific modifiers, type parameters, and type annotations are TypeScript + // syntax. + if (ts.hasModifier(node, 2270 /* TypeScriptModifier */) + || node.typeParameters + || node.type) { + transformFlags |= 3 /* AssertTypeScript */; + } + // An async function expression is ES2017 syntax. + if (ts.hasModifier(node, 256 /* Async */)) { + transformFlags |= node.asteriskToken ? 8 /* AssertESNext */ : 16 /* AssertES2017 */; + } + // function expressions with object rest destructuring are ES Next syntax + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { + transformFlags |= 8 /* AssertESNext */; + } + // If a FunctionExpression's subtree has marked the container as needing to capture the + // lexical this, or the function contains parameters with initializers, then this node is + // ES6 syntax. + if (subtreeFlags & 81920 /* ES2015FunctionSyntaxMask */) { + transformFlags |= 192 /* AssertES2015 */; + } + // If a FunctionExpression is generator function and is the body of a + // transformed async function, then this node can be transformed to a + // down-level generator. + if (node.asteriskToken) { + transformFlags |= 768 /* AssertGenerator */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~653620545 /* FunctionExcludes */; + } + function computeArrowFunction(node, subtreeFlags) { + // An ArrowFunction is ES6 syntax, and excludes markers that should not escape the scope of an ArrowFunction. + var transformFlags = subtreeFlags | 192 /* AssertES2015 */; + // TypeScript-specific modifiers, type parameters, and type annotations are TypeScript + // syntax. + if (ts.hasModifier(node, 2270 /* TypeScriptModifier */) + || node.typeParameters + || node.type) { + transformFlags |= 3 /* AssertTypeScript */; + } + // An async arrow function is ES2017 syntax. + if (ts.hasModifier(node, 256 /* Async */)) { + transformFlags |= 16 /* AssertES2017 */; + } + // arrow functions with object rest destructuring are ES Next syntax + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { + transformFlags |= 8 /* AssertESNext */; + } + // If an ArrowFunction contains a lexical this, its container must capture the lexical this. + if (subtreeFlags & 8192 /* ContainsLexicalThis */) { + transformFlags |= 16384 /* ContainsCapturedLexicalThis */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~653604161 /* ArrowFunctionExcludes */; + } + function computePropertyAccess(node, subtreeFlags) { + var transformFlags = subtreeFlags; + // If a PropertyAccessExpression starts with a super keyword, then it is + // ES6 syntax, and requires a lexical `this` binding. + if (transformFlags & 33554432 /* Super */) { + transformFlags ^= 33554432 /* Super */; + // super inside of an async function requires hoisting the super access (ES2017). + // same for super inside of an async generator, which is ESNext. + transformFlags |= 67108864 /* ContainsSuper */ | 16 /* ContainsES2017 */ | 8 /* ContainsESNext */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~570426689 /* PropertyAccessExcludes */; + } + function computeElementAccess(node, subtreeFlags) { + var transformFlags = subtreeFlags; + var expression = node.expression; + var expressionFlags = expression.transformFlags; // We do not want to aggregate flags from the argument expression for super/this capturing + // If an ElementAccessExpression starts with a super keyword, then it is + // ES6 syntax, and requires a lexical `this` binding. + if (expressionFlags & 33554432 /* Super */) { + transformFlags &= ~33554432 /* Super */; + // super inside of an async function requires hoisting the super access (ES2017). + // same for super inside of an async generator, which is ESNext. + transformFlags |= 67108864 /* ContainsSuper */ | 16 /* ContainsES2017 */ | 8 /* ContainsESNext */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~570426689 /* PropertyAccessExcludes */; + } + function computeVariableDeclaration(node, subtreeFlags) { + var transformFlags = subtreeFlags; + transformFlags |= 192 /* AssertES2015 */ | 2097152 /* ContainsBindingPattern */; + // A VariableDeclaration containing ObjectRest is ESNext syntax + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { + transformFlags |= 8 /* AssertESNext */; + } + // Type annotations are TypeScript syntax. + if (node.type) { + transformFlags |= 3 /* AssertTypeScript */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~637535553 /* NodeExcludes */; + } + function computeVariableStatement(node, subtreeFlags) { + var transformFlags; + var declarationListTransformFlags = node.declarationList.transformFlags; + // An ambient declaration is TypeScript syntax. + if (ts.hasModifier(node, 2 /* Ambient */)) { + transformFlags = 3 /* AssertTypeScript */; + } + else { + transformFlags = subtreeFlags; + if (declarationListTransformFlags & 2097152 /* ContainsBindingPattern */) { + transformFlags |= 192 /* AssertES2015 */; + } + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~637535553 /* NodeExcludes */; + } + function computeLabeledStatement(node, subtreeFlags) { + var transformFlags = subtreeFlags; + // A labeled statement containing a block scoped binding *may* need to be transformed from ES6. + if (subtreeFlags & 1048576 /* ContainsBlockScopedBinding */ + && ts.isIterationStatement(node, /*lookInLabeledStatements*/ true)) { + transformFlags |= 192 /* AssertES2015 */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~637535553 /* NodeExcludes */; + } + function computeImportEquals(node, subtreeFlags) { + var transformFlags = subtreeFlags; + // An ImportEqualsDeclaration with a namespace reference is TypeScript. + if (!ts.isExternalModuleImportEqualsDeclaration(node)) { + transformFlags |= 3 /* AssertTypeScript */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~637535553 /* NodeExcludes */; + } + function computeExpressionStatement(node, subtreeFlags) { + var transformFlags = subtreeFlags; + // If the expression of an expression statement is a destructuring assignment, + // then we treat the statement as ES6 so that we can indicate that we do not + // need to hold on to the right-hand side. + if (node.expression.transformFlags & 1024 /* DestructuringAssignment */) { + transformFlags |= 192 /* AssertES2015 */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~637535553 /* NodeExcludes */; + } + function computeModuleDeclaration(node, subtreeFlags) { + var transformFlags = 3 /* AssertTypeScript */; + var modifierFlags = ts.getModifierFlags(node); + if ((modifierFlags & 2 /* Ambient */) === 0) { + transformFlags |= subtreeFlags; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~647001409 /* ModuleExcludes */; + } + function computeVariableDeclarationList(node, subtreeFlags) { + var transformFlags = subtreeFlags | 8388608 /* ContainsHoistedDeclarationOrCompletion */; + if (subtreeFlags & 2097152 /* ContainsBindingPattern */) { + transformFlags |= 192 /* AssertES2015 */; + } + // If a VariableDeclarationList is `let` or `const`, then it is ES6 syntax. + if (node.flags & 3 /* BlockScoped */) { + transformFlags |= 192 /* AssertES2015 */ | 1048576 /* ContainsBlockScopedBinding */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~639894849 /* VariableDeclarationListExcludes */; + } + function computeOther(node, kind, subtreeFlags) { + // Mark transformations needed for each node + var transformFlags = subtreeFlags; + var excludeFlags = 637535553 /* NodeExcludes */; + switch (kind) { + case 121 /* AsyncKeyword */: + case 201 /* AwaitExpression */: + // async/await is ES2017 syntax, but may be ESNext syntax (for async generators) + transformFlags |= 8 /* AssertESNext */ | 16 /* AssertES2017 */; + break; + case 194 /* TypeAssertionExpression */: + case 212 /* AsExpression */: + case 308 /* PartiallyEmittedExpression */: + // These nodes are TypeScript syntax. + transformFlags |= 3 /* AssertTypeScript */; + excludeFlags = 536872257 /* OuterExpressionExcludes */; + break; + case 115 /* PublicKeyword */: + case 113 /* PrivateKeyword */: + case 114 /* ProtectedKeyword */: + case 118 /* AbstractKeyword */: + case 125 /* DeclareKeyword */: + case 77 /* ConstKeyword */: + case 243 /* EnumDeclaration */: + case 278 /* EnumMember */: + case 213 /* NonNullExpression */: + case 133 /* ReadonlyKeyword */: + // These nodes are TypeScript syntax. + transformFlags |= 3 /* AssertTypeScript */; + break; + case 260 /* JsxElement */: + case 261 /* JsxSelfClosingElement */: + case 262 /* JsxOpeningElement */: + case 11 /* JsxText */: + case 263 /* JsxClosingElement */: + case 264 /* JsxFragment */: + case 265 /* JsxOpeningFragment */: + case 266 /* JsxClosingFragment */: + case 267 /* JsxAttribute */: + case 268 /* JsxAttributes */: + case 269 /* JsxSpreadAttribute */: + case 270 /* JsxExpression */: + // These nodes are Jsx syntax. + transformFlags |= 4 /* AssertJsx */; + break; + case 14 /* NoSubstitutionTemplateLiteral */: + case 15 /* TemplateHead */: + case 16 /* TemplateMiddle */: + case 17 /* TemplateTail */: + case 206 /* TemplateExpression */: + case 193 /* TaggedTemplateExpression */: + case 276 /* ShorthandPropertyAssignment */: + case 116 /* StaticKeyword */: + case 214 /* MetaProperty */: + // These nodes are ES6 syntax. + transformFlags |= 192 /* AssertES2015 */; + break; + case 10 /* StringLiteral */: + if (node.hasExtendedUnicodeEscape) { + transformFlags |= 192 /* AssertES2015 */; + } + break; + case 8 /* NumericLiteral */: + if (node.numericLiteralFlags & 384 /* BinaryOrOctalSpecifier */) { + transformFlags |= 192 /* AssertES2015 */; + } + break; + case 9 /* BigIntLiteral */: + transformFlags |= 8 /* AssertESNext */; + break; + case 227 /* ForOfStatement */: + // This node is either ES2015 syntax or ES2017 syntax (if it is a for-await-of). + if (node.awaitModifier) { + transformFlags |= 8 /* AssertESNext */; + } + transformFlags |= 192 /* AssertES2015 */; + break; + case 207 /* YieldExpression */: + // This node is either ES2015 syntax (in a generator) or ES2017 syntax (in an async + // generator). + transformFlags |= 8 /* AssertESNext */ | 192 /* AssertES2015 */ | 4194304 /* ContainsYield */; + break; + case 120 /* AnyKeyword */: + case 135 /* NumberKeyword */: + case 146 /* BigIntKeyword */: + case 132 /* NeverKeyword */: + case 136 /* ObjectKeyword */: + case 138 /* StringKeyword */: + case 123 /* BooleanKeyword */: + case 139 /* SymbolKeyword */: + case 106 /* VoidKeyword */: + case 150 /* TypeParameter */: + case 153 /* PropertySignature */: + case 155 /* MethodSignature */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 162 /* IndexSignature */: + case 163 /* TypePredicate */: + case 164 /* TypeReference */: + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + case 167 /* TypeQuery */: + case 168 /* TypeLiteral */: + case 169 /* ArrayType */: + case 170 /* TupleType */: + case 171 /* OptionalType */: + case 172 /* RestType */: + case 173 /* UnionType */: + case 174 /* IntersectionType */: + case 175 /* ConditionalType */: + case 176 /* InferType */: + case 177 /* ParenthesizedType */: + case 241 /* InterfaceDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 178 /* ThisType */: + case 179 /* TypeOperator */: + case 180 /* IndexedAccessType */: + case 181 /* MappedType */: + case 182 /* LiteralType */: + case 247 /* NamespaceExportDeclaration */: + // Types and signatures are TypeScript syntax, and exclude all other facts. + transformFlags = 3 /* AssertTypeScript */; + excludeFlags = -3 /* TypeExcludes */; + break; + case 149 /* ComputedPropertyName */: + // Even though computed property names are ES6, we don't treat them as such. + // This is so that they can flow through PropertyName transforms unaffected. + // Instead, we mark the container as ES6, so that it can properly handle the transform. + transformFlags |= 524288 /* ContainsComputedPropertyName */; + if (subtreeFlags & 8192 /* ContainsLexicalThis */) { + // A computed method name like `[this.getName()](x: string) { ... }` needs to + // distinguish itself from the normal case of a method body containing `this`: + // `this` inside a method doesn't need to be rewritten (the method provides `this`), + // whereas `this` inside a computed name *might* need to be rewritten if the class/object + // is inside an arrow function: + // `_this = this; () => class K { [_this.getName()]() { ... } }` + // To make this distinction, use ContainsLexicalThisInComputedPropertyName + // instead of ContainsLexicalThis for computed property names + transformFlags |= 32768 /* ContainsLexicalThisInComputedPropertyName */; + } + break; + case 208 /* SpreadElement */: + transformFlags |= 192 /* AssertES2015 */ | 131072 /* ContainsRestOrSpread */; + break; + case 277 /* SpreadAssignment */: + transformFlags |= 8 /* AssertESNext */ | 262144 /* ContainsObjectRestOrSpread */; + break; + case 98 /* SuperKeyword */: + // This node is ES6 syntax. + transformFlags |= 192 /* AssertES2015 */ | 33554432 /* Super */; + excludeFlags = 536872257 /* OuterExpressionExcludes */; // must be set to persist `Super` + break; + case 100 /* ThisKeyword */: + // Mark this node and its ancestors as containing a lexical `this` keyword. + transformFlags |= 8192 /* ContainsLexicalThis */; + break; + case 184 /* ObjectBindingPattern */: + transformFlags |= 192 /* AssertES2015 */ | 2097152 /* ContainsBindingPattern */; + if (subtreeFlags & 131072 /* ContainsRestOrSpread */) { + transformFlags |= 8 /* AssertESNext */ | 262144 /* ContainsObjectRestOrSpread */; + } + excludeFlags = 637666625 /* BindingPatternExcludes */; + break; + case 185 /* ArrayBindingPattern */: + transformFlags |= 192 /* AssertES2015 */ | 2097152 /* ContainsBindingPattern */; + excludeFlags = 637666625 /* BindingPatternExcludes */; + break; + case 186 /* BindingElement */: + transformFlags |= 192 /* AssertES2015 */; + if (node.dotDotDotToken) { + transformFlags |= 131072 /* ContainsRestOrSpread */; + } + break; + case 152 /* Decorator */: + // This node is TypeScript syntax, and marks its container as also being TypeScript syntax. + transformFlags |= 3 /* AssertTypeScript */ | 4096 /* ContainsTypeScriptClassSyntax */; + break; + case 188 /* ObjectLiteralExpression */: + excludeFlags = 638358849 /* ObjectLiteralExcludes */; + if (subtreeFlags & 524288 /* ContainsComputedPropertyName */) { + // If an ObjectLiteralExpression contains a ComputedPropertyName, then it + // is an ES6 node. + transformFlags |= 192 /* AssertES2015 */; + } + if (subtreeFlags & 32768 /* ContainsLexicalThisInComputedPropertyName */) { + // A computed property name containing `this` might need to be rewritten, + // so propagate the ContainsLexicalThis flag upward. + transformFlags |= 8192 /* ContainsLexicalThis */; + } + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { + // If an ObjectLiteralExpression contains a spread element, then it + // is an ES next node. + transformFlags |= 8 /* AssertESNext */; + } + break; + case 187 /* ArrayLiteralExpression */: + case 192 /* NewExpression */: + excludeFlags = 637666625 /* ArrayLiteralOrCallOrNewExcludes */; + if (subtreeFlags & 131072 /* ContainsRestOrSpread */) { + // If the this node contains a SpreadExpression, then it is an ES6 + // node. + transformFlags |= 192 /* AssertES2015 */; + } + break; + case 223 /* DoStatement */: + case 224 /* WhileStatement */: + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + // A loop containing a block scoped binding *may* need to be transformed from ES6. + if (subtreeFlags & 1048576 /* ContainsBlockScopedBinding */) { + transformFlags |= 192 /* AssertES2015 */; + } + break; + case 279 /* SourceFile */: + if (subtreeFlags & 16384 /* ContainsCapturedLexicalThis */) { + transformFlags |= 192 /* AssertES2015 */; + } + break; + case 230 /* ReturnStatement */: + // Return statements may require an `await` in ESNext. + transformFlags |= 8388608 /* ContainsHoistedDeclarationOrCompletion */ | 8 /* AssertESNext */; + break; + case 228 /* ContinueStatement */: + case 229 /* BreakStatement */: + transformFlags |= 8388608 /* ContainsHoistedDeclarationOrCompletion */; + break; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~excludeFlags; + } + /** + * Gets the transform flags to exclude when unioning the transform flags of a subtree. + * + * NOTE: This needs to be kept up-to-date with the exclusions used in `computeTransformFlagsForNode`. + * For performance reasons, `computeTransformFlagsForNode` uses local constant values rather + * than calling this function. + */ + function getTransformFlagsSubtreeExclusions(kind) { + if (kind >= 163 /* FirstTypeNode */ && kind <= 183 /* LastTypeNode */) { + return -3 /* TypeExcludes */; + } + switch (kind) { + case 191 /* CallExpression */: + case 192 /* NewExpression */: + case 187 /* ArrayLiteralExpression */: + return 637666625 /* ArrayLiteralOrCallOrNewExcludes */; + case 244 /* ModuleDeclaration */: + return 647001409 /* ModuleExcludes */; + case 151 /* Parameter */: + return 637535553 /* ParameterExcludes */; + case 197 /* ArrowFunction */: + return 653604161 /* ArrowFunctionExcludes */; + case 196 /* FunctionExpression */: + case 239 /* FunctionDeclaration */: + return 653620545 /* FunctionExcludes */; + case 238 /* VariableDeclarationList */: + return 639894849 /* VariableDeclarationListExcludes */; + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + return 638121281 /* ClassExcludes */; + case 157 /* Constructor */: + return 653616449 /* ConstructorExcludes */; + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + return 653616449 /* MethodOrAccessorExcludes */; + case 120 /* AnyKeyword */: + case 135 /* NumberKeyword */: + case 146 /* BigIntKeyword */: + case 132 /* NeverKeyword */: + case 138 /* StringKeyword */: + case 136 /* ObjectKeyword */: + case 123 /* BooleanKeyword */: + case 139 /* SymbolKeyword */: + case 106 /* VoidKeyword */: + case 150 /* TypeParameter */: + case 153 /* PropertySignature */: + case 155 /* MethodSignature */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 162 /* IndexSignature */: + case 241 /* InterfaceDeclaration */: + case 242 /* TypeAliasDeclaration */: + return -3 /* TypeExcludes */; + case 188 /* ObjectLiteralExpression */: + return 638358849 /* ObjectLiteralExcludes */; + case 274 /* CatchClause */: + return 637797697 /* CatchClauseExcludes */; + case 184 /* ObjectBindingPattern */: + case 185 /* ArrayBindingPattern */: + return 637666625 /* BindingPatternExcludes */; + case 194 /* TypeAssertionExpression */: + case 212 /* AsExpression */: + case 308 /* PartiallyEmittedExpression */: + case 195 /* ParenthesizedExpression */: + case 98 /* SuperKeyword */: + return 536872257 /* OuterExpressionExcludes */; + case 189 /* PropertyAccessExpression */: + case 190 /* ElementAccessExpression */: + return 570426689 /* PropertyAccessExcludes */; + default: + return 637535553 /* NodeExcludes */; + } + } + ts.getTransformFlagsSubtreeExclusions = getTransformFlagsSubtreeExclusions; + /** + * "Binds" JSDoc nodes in TypeScript code. + * Since we will never create symbols for JSDoc, we just set parent pointers instead. + */ + function setParentPointers(parent, child) { + child.parent = parent; + ts.forEachChild(child, function (grandchild) { return setParentPointers(child, grandchild); }); + } +})(ts || (ts = {})); +/** @internal */ +var ts; +(function (ts) { + function createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintOfTypeParameter, getFirstIdentifier) { + return getSymbolWalker; + function getSymbolWalker(accept) { + if (accept === void 0) { accept = function () { return true; }; } + var visitedTypes = []; // Sparse array from id to type + var visitedSymbols = []; // Sparse array from id to symbol + return { + walkType: function (type) { + try { + visitType(type); + return { visitedTypes: ts.getOwnValues(visitedTypes), visitedSymbols: ts.getOwnValues(visitedSymbols) }; + } + finally { + ts.clear(visitedTypes); + ts.clear(visitedSymbols); + } + }, + walkSymbol: function (symbol) { + try { + visitSymbol(symbol); + return { visitedTypes: ts.getOwnValues(visitedTypes), visitedSymbols: ts.getOwnValues(visitedSymbols) }; + } + finally { + ts.clear(visitedTypes); + ts.clear(visitedSymbols); + } + }, + }; + function visitType(type) { + if (!type) { + return; + } + if (visitedTypes[type.id]) { + return; + } + visitedTypes[type.id] = type; + // Reuse visitSymbol to visit the type's symbol, + // but be sure to bail on recuring into the type if accept declines the symbol. + var shouldBail = visitSymbol(type.symbol); + if (shouldBail) + return; + // Visit the type's related types, if any + if (type.flags & 524288 /* Object */) { + var objectType = type; + var objectFlags = objectType.objectFlags; + if (objectFlags & 4 /* Reference */) { + visitTypeReference(type); + } + if (objectFlags & 32 /* Mapped */) { + visitMappedType(type); + } + if (objectFlags & (1 /* Class */ | 2 /* Interface */)) { + visitInterfaceType(type); + } + if (objectFlags & (8 /* Tuple */ | 16 /* Anonymous */)) { + visitObjectType(objectType); + } + } + if (type.flags & 262144 /* TypeParameter */) { + visitTypeParameter(type); + } + if (type.flags & 3145728 /* UnionOrIntersection */) { + visitUnionOrIntersectionType(type); + } + if (type.flags & 4194304 /* Index */) { + visitIndexType(type); + } + if (type.flags & 8388608 /* IndexedAccess */) { + visitIndexedAccessType(type); + } + } + function visitTypeReference(type) { + visitType(type.target); + ts.forEach(type.typeArguments, visitType); + } + function visitTypeParameter(type) { + visitType(getConstraintOfTypeParameter(type)); + } + function visitUnionOrIntersectionType(type) { + ts.forEach(type.types, visitType); + } + function visitIndexType(type) { + visitType(type.type); + } + function visitIndexedAccessType(type) { + visitType(type.objectType); + visitType(type.indexType); + visitType(type.constraint); + } + function visitMappedType(type) { + visitType(type.typeParameter); + visitType(type.constraintType); + visitType(type.templateType); + visitType(type.modifiersType); + } + function visitSignature(signature) { + var typePredicate = getTypePredicateOfSignature(signature); + if (typePredicate) { + visitType(typePredicate.type); + } + ts.forEach(signature.typeParameters, visitType); + for (var _i = 0, _a = signature.parameters; _i < _a.length; _i++) { + var parameter = _a[_i]; + visitSymbol(parameter); + } + visitType(getRestTypeOfSignature(signature)); + visitType(getReturnTypeOfSignature(signature)); + } + function visitInterfaceType(interfaceT) { + visitObjectType(interfaceT); + ts.forEach(interfaceT.typeParameters, visitType); + ts.forEach(getBaseTypes(interfaceT), visitType); + visitType(interfaceT.thisType); + } + function visitObjectType(type) { + var stringIndexType = getIndexTypeOfStructuredType(type, 0 /* String */); + visitType(stringIndexType); + var numberIndexType = getIndexTypeOfStructuredType(type, 1 /* Number */); + visitType(numberIndexType); + // The two checks above *should* have already resolved the type (if needed), so this should be cached + var resolved = resolveStructuredTypeMembers(type); + for (var _i = 0, _a = resolved.callSignatures; _i < _a.length; _i++) { + var signature = _a[_i]; + visitSignature(signature); + } + for (var _b = 0, _c = resolved.constructSignatures; _b < _c.length; _b++) { + var signature = _c[_b]; + visitSignature(signature); + } + for (var _d = 0, _e = resolved.properties; _d < _e.length; _d++) { + var p = _e[_d]; + visitSymbol(p); + } + } + function visitSymbol(symbol) { + if (!symbol) { + return false; + } + var symbolId = ts.getSymbolId(symbol); + if (visitedSymbols[symbolId]) { + return false; + } + visitedSymbols[symbolId] = symbol; + if (!accept(symbol)) { + return true; + } + var t = getTypeOfSymbol(symbol); + visitType(t); // Should handle members on classes and such + if (symbol.exports) { + symbol.exports.forEach(visitSymbol); + } + ts.forEach(symbol.declarations, function (d) { + // Type queries are too far resolved when we just visit the symbol's type + // (their type resolved directly to the member deeply referenced) + // So to get the intervening symbols, we need to check if there's a type + // query node on any of the symbol's declarations and get symbols there + if (d.type && d.type.kind === 167 /* TypeQuery */) { + var query = d.type; + var entity = getResolvedSymbol(getFirstIdentifier(query.exprName)); + visitSymbol(entity); + } + }); + return false; + } + } + } + ts.createGetSymbolWalker = createGetSymbolWalker; +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var ambientModuleSymbolRegex = /^".+"$/; + var nextSymbolId = 1; + var nextNodeId = 1; + var nextMergeId = 1; + var nextFlowId = 1; + function getNodeId(node) { + if (!node.id) { + node.id = nextNodeId; + nextNodeId++; + } + return node.id; + } + ts.getNodeId = getNodeId; + function getSymbolId(symbol) { + if (!symbol.id) { + symbol.id = nextSymbolId; + nextSymbolId++; + } + return symbol.id; + } + ts.getSymbolId = getSymbolId; + function isInstantiatedModule(node, preserveConstEnums) { + var moduleState = ts.getModuleInstanceState(node); + return moduleState === 1 /* Instantiated */ || + (preserveConstEnums && moduleState === 2 /* ConstEnumOnly */); + } + ts.isInstantiatedModule = isInstantiatedModule; + function createTypeChecker(host, produceDiagnostics) { + var getPackagesSet = ts.memoize(function () { + var set = ts.createMap(); + host.getSourceFiles().forEach(function (sf) { + if (!sf.resolvedModules) + return; + ts.forEachEntry(sf.resolvedModules, function (r) { + if (r && r.packageId) + set.set(r.packageId.name, true); + }); + }); + return set; + }); + // Cancellation that controls whether or not we can cancel in the middle of type checking. + // In general cancelling is *not* safe for the type checker. We might be in the middle of + // computing something, and we will leave our internals in an inconsistent state. Callers + // who set the cancellation token should catch if a cancellation exception occurs, and + // should throw away and create a new TypeChecker. + // + // Currently we only support setting the cancellation token when getting diagnostics. This + // is because diagnostics can be quite expensive, and we want to allow hosts to bail out if + // they no longer need the information (for example, if the user started editing again). + var cancellationToken; + var requestedExternalEmitHelpers; + var externalHelpersModule; + // tslint:disable variable-name + var Symbol = ts.objectAllocator.getSymbolConstructor(); + var Type = ts.objectAllocator.getTypeConstructor(); + var Signature = ts.objectAllocator.getSignatureConstructor(); + // tslint:enable variable-name + var typeCount = 0; + var symbolCount = 0; + var enumCount = 0; + var instantiationDepth = 0; + var constraintDepth = 0; + var emptySymbols = ts.createSymbolTable(); + var identityMapper = ts.identity; + var compilerOptions = host.getCompilerOptions(); + var languageVersion = ts.getEmitScriptTarget(compilerOptions); + var moduleKind = ts.getEmitModuleKind(compilerOptions); + var allowSyntheticDefaultImports = ts.getAllowSyntheticDefaultImports(compilerOptions); + var strictNullChecks = ts.getStrictOptionValue(compilerOptions, "strictNullChecks"); + var strictFunctionTypes = ts.getStrictOptionValue(compilerOptions, "strictFunctionTypes"); + var strictBindCallApply = ts.getStrictOptionValue(compilerOptions, "strictBindCallApply"); + var strictPropertyInitialization = ts.getStrictOptionValue(compilerOptions, "strictPropertyInitialization"); + var noImplicitAny = ts.getStrictOptionValue(compilerOptions, "noImplicitAny"); + var noImplicitThis = ts.getStrictOptionValue(compilerOptions, "noImplicitThis"); + var keyofStringsOnly = !!compilerOptions.keyofStringsOnly; + var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 32768 /* FreshLiteral */; + var emitResolver = createResolver(); + var nodeBuilder = createNodeBuilder(); + var undefinedSymbol = createSymbol(4 /* Property */, "undefined"); + undefinedSymbol.declarations = []; + var argumentsSymbol = createSymbol(4 /* Property */, "arguments"); + var requireSymbol = createSymbol(4 /* Property */, "require"); + /** This will be set during calls to `getResolvedSignature` where services determines an apparent number of arguments greater than what is actually provided. */ + var apparentArgumentCount; + // for public members that accept a Node or one of its subtypes, we must guard against + // synthetic nodes created during transformations by calling `getParseTreeNode`. + // for most of these, we perform the guard only on `checker` to avoid any possible + // extra cost of calling `getParseTreeNode` when calling these functions from inside the + // checker. + var checker = { + getNodeCount: function () { return ts.sum(host.getSourceFiles(), "nodeCount"); }, + getIdentifierCount: function () { return ts.sum(host.getSourceFiles(), "identifierCount"); }, + getSymbolCount: function () { return ts.sum(host.getSourceFiles(), "symbolCount") + symbolCount; }, + getTypeCount: function () { return typeCount; }, + isUndefinedSymbol: function (symbol) { return symbol === undefinedSymbol; }, + isArgumentsSymbol: function (symbol) { return symbol === argumentsSymbol; }, + isUnknownSymbol: function (symbol) { return symbol === unknownSymbol; }, + getMergedSymbol: getMergedSymbol, + getDiagnostics: getDiagnostics, + getGlobalDiagnostics: getGlobalDiagnostics, + getTypeOfSymbolAtLocation: function (symbol, location) { + location = ts.getParseTreeNode(location); + return location ? getTypeOfSymbolAtLocation(symbol, location) : errorType; + }, + getSymbolsOfParameterPropertyDeclaration: function (parameterIn, parameterName) { + var parameter = ts.getParseTreeNode(parameterIn, ts.isParameter); + if (parameter === undefined) + return ts.Debug.fail("Cannot get symbols of a synthetic parameter that cannot be resolved to a parse-tree node."); + return getSymbolsOfParameterPropertyDeclaration(parameter, ts.escapeLeadingUnderscores(parameterName)); + }, + getDeclaredTypeOfSymbol: getDeclaredTypeOfSymbol, + getPropertiesOfType: getPropertiesOfType, + getPropertyOfType: function (type, name) { return getPropertyOfType(type, ts.escapeLeadingUnderscores(name)); }, + getTypeOfPropertyOfType: function (type, name) { return getTypeOfPropertyOfType(type, ts.escapeLeadingUnderscores(name)); }, + getIndexInfoOfType: getIndexInfoOfType, + getSignaturesOfType: getSignaturesOfType, + getIndexTypeOfType: getIndexTypeOfType, + getBaseTypes: getBaseTypes, + getBaseTypeOfLiteralType: getBaseTypeOfLiteralType, + getWidenedType: getWidenedType, + getTypeFromTypeNode: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isTypeNode); + return node ? getTypeFromTypeNode(node) : errorType; + }, + getParameterType: getTypeAtPosition, + getPromisedTypeOfPromise: getPromisedTypeOfPromise, + getReturnTypeOfSignature: getReturnTypeOfSignature, + getNullableType: getNullableType, + getNonNullableType: getNonNullableType, + typeToTypeNode: nodeBuilder.typeToTypeNode, + indexInfoToIndexSignatureDeclaration: nodeBuilder.indexInfoToIndexSignatureDeclaration, + signatureToSignatureDeclaration: nodeBuilder.signatureToSignatureDeclaration, + symbolToEntityName: nodeBuilder.symbolToEntityName, + symbolToExpression: nodeBuilder.symbolToExpression, + symbolToTypeParameterDeclarations: nodeBuilder.symbolToTypeParameterDeclarations, + symbolToParameterDeclaration: nodeBuilder.symbolToParameterDeclaration, + typeParameterToDeclaration: nodeBuilder.typeParameterToDeclaration, + getSymbolsInScope: function (location, meaning) { + location = ts.getParseTreeNode(location); + return location ? getSymbolsInScope(location, meaning) : []; + }, + getSymbolAtLocation: function (node) { + node = ts.getParseTreeNode(node); + return node ? getSymbolAtLocation(node) : undefined; + }, + getShorthandAssignmentValueSymbol: function (node) { + node = ts.getParseTreeNode(node); + return node ? getShorthandAssignmentValueSymbol(node) : undefined; + }, + getExportSpecifierLocalTargetSymbol: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isExportSpecifier); + return node ? getExportSpecifierLocalTargetSymbol(node) : undefined; + }, + getExportSymbolOfSymbol: function (symbol) { + return getMergedSymbol(symbol.exportSymbol || symbol); + }, + getTypeAtLocation: function (node) { + node = ts.getParseTreeNode(node); + return node ? getTypeOfNode(node) : errorType; + }, + getPropertySymbolOfDestructuringAssignment: function (locationIn) { + var location = ts.getParseTreeNode(locationIn, ts.isIdentifier); + return location ? getPropertySymbolOfDestructuringAssignment(location) : undefined; + }, + signatureToString: function (signature, enclosingDeclaration, flags, kind) { + return signatureToString(signature, ts.getParseTreeNode(enclosingDeclaration), flags, kind); + }, + typeToString: function (type, enclosingDeclaration, flags) { + return typeToString(type, ts.getParseTreeNode(enclosingDeclaration), flags); + }, + symbolToString: function (symbol, enclosingDeclaration, meaning, flags) { + return symbolToString(symbol, ts.getParseTreeNode(enclosingDeclaration), meaning, flags); + }, + typePredicateToString: function (predicate, enclosingDeclaration, flags) { + return typePredicateToString(predicate, ts.getParseTreeNode(enclosingDeclaration), flags); + }, + writeSignature: function (signature, enclosingDeclaration, flags, kind, writer) { + return signatureToString(signature, ts.getParseTreeNode(enclosingDeclaration), flags, kind, writer); + }, + writeType: function (type, enclosingDeclaration, flags, writer) { + return typeToString(type, ts.getParseTreeNode(enclosingDeclaration), flags, writer); + }, + writeSymbol: function (symbol, enclosingDeclaration, meaning, flags, writer) { + return symbolToString(symbol, ts.getParseTreeNode(enclosingDeclaration), meaning, flags, writer); + }, + writeTypePredicate: function (predicate, enclosingDeclaration, flags, writer) { + return typePredicateToString(predicate, ts.getParseTreeNode(enclosingDeclaration), flags, writer); + }, + getAugmentedPropertiesOfType: getAugmentedPropertiesOfType, + getRootSymbols: getRootSymbols, + getContextualType: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isExpression); + return node ? getContextualType(node) : undefined; + }, + getContextualTypeForObjectLiteralElement: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isObjectLiteralElementLike); + return node ? getContextualTypeForObjectLiteralElement(node) : undefined; + }, + getContextualTypeForArgumentAtIndex: function (nodeIn, argIndex) { + var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression); + return node && getContextualTypeForArgumentAtIndex(node, argIndex); + }, + getContextualTypeForJsxAttribute: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isJsxAttributeLike); + return node && getContextualTypeForJsxAttribute(node); + }, + isContextSensitive: isContextSensitive, + getFullyQualifiedName: getFullyQualifiedName, + getResolvedSignature: function (node, candidatesOutArray, agumentCount) { + return getResolvedSignatureWorker(node, candidatesOutArray, agumentCount, /*isForSignatureHelp*/ false); + }, + getResolvedSignatureForSignatureHelp: function (node, candidatesOutArray, agumentCount) { + return getResolvedSignatureWorker(node, candidatesOutArray, agumentCount, /*isForSignatureHelp*/ true); + }, + getConstantValue: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, canHaveConstantValue); + return node ? getConstantValue(node) : undefined; + }, + isValidPropertyAccess: function (nodeIn, propertyName) { + var node = ts.getParseTreeNode(nodeIn, ts.isPropertyAccessOrQualifiedNameOrImportTypeNode); + return !!node && isValidPropertyAccess(node, ts.escapeLeadingUnderscores(propertyName)); + }, + isValidPropertyAccessForCompletions: function (nodeIn, type, property) { + var node = ts.getParseTreeNode(nodeIn, ts.isPropertyAccessExpression); + return !!node && isValidPropertyAccessForCompletions(node, type, property); + }, + getSignatureFromDeclaration: function (declarationIn) { + var declaration = ts.getParseTreeNode(declarationIn, ts.isFunctionLike); + return declaration ? getSignatureFromDeclaration(declaration) : undefined; + }, + isImplementationOfOverload: function (node) { + var parsed = ts.getParseTreeNode(node, ts.isFunctionLike); + return parsed ? isImplementationOfOverload(parsed) : undefined; + }, + getImmediateAliasedSymbol: getImmediateAliasedSymbol, + getAliasedSymbol: resolveAlias, + getEmitResolver: getEmitResolver, + getExportsOfModule: getExportsOfModuleAsArray, + getExportsAndPropertiesOfModule: getExportsAndPropertiesOfModule, + getSymbolWalker: ts.createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintOfTypeParameter, getFirstIdentifier), + getAmbientModules: getAmbientModules, + getJsxIntrinsicTagNamesAt: getJsxIntrinsicTagNamesAt, + isOptionalParameter: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isParameter); + return node ? isOptionalParameter(node) : false; + }, + tryGetMemberInModuleExports: function (name, symbol) { return tryGetMemberInModuleExports(ts.escapeLeadingUnderscores(name), symbol); }, + tryGetMemberInModuleExportsAndProperties: function (name, symbol) { return tryGetMemberInModuleExportsAndProperties(ts.escapeLeadingUnderscores(name), symbol); }, + tryFindAmbientModuleWithoutAugmentations: function (moduleName) { + // we deliberately exclude augmentations + // since we are only interested in declarations of the module itself + return tryFindAmbientModule(moduleName, /*withAugmentations*/ false); + }, + getApparentType: getApparentType, + getUnionType: getUnionType, + createAnonymousType: createAnonymousType, + createSignature: createSignature, + createSymbol: createSymbol, + createIndexInfo: createIndexInfo, + getAnyType: function () { return anyType; }, + getStringType: function () { return stringType; }, + getNumberType: function () { return numberType; }, + createPromiseType: createPromiseType, + createArrayType: createArrayType, + getElementTypeOfArrayType: getElementTypeOfArrayType, + getBooleanType: function () { return booleanType; }, + getFalseType: function (fresh) { return fresh ? falseType : regularFalseType; }, + getTrueType: function (fresh) { return fresh ? trueType : regularTrueType; }, + getVoidType: function () { return voidType; }, + getUndefinedType: function () { return undefinedType; }, + getNullType: function () { return nullType; }, + getESSymbolType: function () { return esSymbolType; }, + getNeverType: function () { return neverType; }, + isSymbolAccessible: isSymbolAccessible, + getObjectFlags: ts.getObjectFlags, + isArrayLikeType: isArrayLikeType, + isTypeInvalidDueToUnionDiscriminant: isTypeInvalidDueToUnionDiscriminant, + getAllPossiblePropertiesOfTypes: getAllPossiblePropertiesOfTypes, + getSuggestionForNonexistentProperty: function (node, type) { return getSuggestionForNonexistentProperty(node, type); }, + getSuggestionForNonexistentSymbol: function (location, name, meaning) { return getSuggestionForNonexistentSymbol(location, ts.escapeLeadingUnderscores(name), meaning); }, + getSuggestionForNonexistentExport: function (node, target) { return getSuggestionForNonexistentExport(node, target); }, + getBaseConstraintOfType: getBaseConstraintOfType, + getDefaultFromTypeParameter: function (type) { return type && type.flags & 262144 /* TypeParameter */ ? getDefaultFromTypeParameter(type) : undefined; }, + resolveName: function (name, location, meaning, excludeGlobals) { + return resolveName(location, ts.escapeLeadingUnderscores(name), meaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false, excludeGlobals); + }, + getJsxNamespace: function (n) { return ts.unescapeLeadingUnderscores(getJsxNamespace(n)); }, + getAccessibleSymbolChain: getAccessibleSymbolChain, + getTypePredicateOfSignature: getTypePredicateOfSignature, + resolveExternalModuleSymbol: resolveExternalModuleSymbol, + tryGetThisTypeAt: function (node) { + node = ts.getParseTreeNode(node); + return node && tryGetThisTypeAt(node); + }, + getTypeArgumentConstraint: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isTypeNode); + return node && getTypeArgumentConstraint(node); + }, + getSuggestionDiagnostics: function (file, ct) { + if (ts.skipTypeChecking(file, compilerOptions)) { + return ts.emptyArray; + } + var diagnostics; + try { + // Record the cancellation token so it can be checked later on during checkSourceElement. + // Do this in a finally block so we can ensure that it gets reset back to nothing after + // this call is done. + cancellationToken = ct; + // Ensure file is type checked + checkSourceFile(file); + ts.Debug.assert(!!(getNodeLinks(file).flags & 1 /* TypeChecked */)); + diagnostics = ts.addRange(diagnostics, suggestionDiagnostics.get(file.fileName)); + if (!file.isDeclarationFile && (!unusedIsError(0 /* Local */) || !unusedIsError(1 /* Parameter */))) { + addUnusedDiagnostics(); + } + return diagnostics || ts.emptyArray; + } + finally { + cancellationToken = undefined; + } + function addUnusedDiagnostics() { + checkUnusedIdentifiers(getPotentiallyUnusedIdentifiers(file), function (containingNode, kind, diag) { + if (!ts.containsParseError(containingNode) && !unusedIsError(kind)) { + (diagnostics || (diagnostics = [])).push(__assign({}, diag, { category: ts.DiagnosticCategory.Suggestion })); + } + }); + } + }, + runWithCancellationToken: function (token, callback) { + try { + cancellationToken = token; + return callback(checker); + } + finally { + cancellationToken = undefined; + } + }, + getLocalTypeParametersOfClassOrInterfaceOrTypeAlias: getLocalTypeParametersOfClassOrInterfaceOrTypeAlias, + }; + function getResolvedSignatureWorker(nodeIn, candidatesOutArray, argumentCount, isForSignatureHelp) { + var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression); + apparentArgumentCount = argumentCount; + var res = node ? getResolvedSignature(node, candidatesOutArray, isForSignatureHelp) : undefined; + apparentArgumentCount = undefined; + return res; + } + var tupleTypes = ts.createMap(); + var unionTypes = ts.createMap(); + var intersectionTypes = ts.createMap(); + var literalTypes = ts.createMap(); + var indexedAccessTypes = ts.createMap(); + var evolvingArrayTypes = []; + var undefinedProperties = ts.createMap(); + var unknownSymbol = createSymbol(4 /* Property */, "unknown"); + var resolvingSymbol = createSymbol(0, "__resolving__" /* Resolving */); + var anyType = createIntrinsicType(1 /* Any */, "any"); + var autoType = createIntrinsicType(1 /* Any */, "any"); + var wildcardType = createIntrinsicType(1 /* Any */, "any"); + var errorType = createIntrinsicType(1 /* Any */, "error"); + var unknownType = createIntrinsicType(2 /* Unknown */, "unknown"); + var undefinedType = createIntrinsicType(32768 /* Undefined */, "undefined"); + var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(32768 /* Undefined */ | 134217728 /* ContainsWideningType */, "undefined"); + var nullType = createIntrinsicType(65536 /* Null */, "null"); + var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(65536 /* Null */ | 134217728 /* ContainsWideningType */, "null"); + var stringType = createIntrinsicType(4 /* String */, "string"); + var numberType = createIntrinsicType(8 /* Number */, "number"); + var bigintType = createIntrinsicType(64 /* BigInt */, "bigint"); + var falseType = createIntrinsicType(512 /* BooleanLiteral */, "false"); + var regularFalseType = createIntrinsicType(512 /* BooleanLiteral */, "false"); + var trueType = createIntrinsicType(512 /* BooleanLiteral */, "true"); + var regularTrueType = createIntrinsicType(512 /* BooleanLiteral */, "true"); + trueType.regularType = regularTrueType; + trueType.freshType = trueType; + regularTrueType.regularType = regularTrueType; + regularTrueType.freshType = trueType; + falseType.regularType = regularFalseType; + falseType.freshType = falseType; + regularFalseType.regularType = regularFalseType; + regularFalseType.freshType = falseType; + var booleanType = createBooleanType([regularFalseType, regularTrueType]); + // Also mark all combinations of fresh/regular booleans as "Boolean" so they print as `boolean` instead of `true | false` + // (The union is cached, so simply doing the marking here is sufficient) + createBooleanType([regularFalseType, trueType]); + createBooleanType([falseType, regularTrueType]); + createBooleanType([falseType, trueType]); + var esSymbolType = createIntrinsicType(4096 /* ESSymbol */, "symbol"); + var voidType = createIntrinsicType(16384 /* Void */, "void"); + var neverType = createIntrinsicType(131072 /* Never */, "never"); + var silentNeverType = createIntrinsicType(131072 /* Never */, "never"); + var implicitNeverType = createIntrinsicType(131072 /* Never */, "never"); + var nonPrimitiveType = createIntrinsicType(67108864 /* NonPrimitive */, "object"); + var stringNumberSymbolType = getUnionType([stringType, numberType, esSymbolType]); + var keyofConstraintType = keyofStringsOnly ? stringType : stringNumberSymbolType; + var numberOrBigIntType = getUnionType([numberType, bigintType]); + var emptyObjectType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + var emptyJsxObjectType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + emptyJsxObjectType.objectFlags |= 4096 /* JsxAttributes */; + var emptyTypeLiteralSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */); + emptyTypeLiteralSymbol.members = ts.createSymbolTable(); + var emptyTypeLiteralType = createAnonymousType(emptyTypeLiteralSymbol, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + var emptyGenericType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + emptyGenericType.instantiations = ts.createMap(); + var anyFunctionType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + // The anyFunctionType contains the anyFunctionType by definition. The flag is further propagated + // in getPropagatingFlagsOfTypes, and it is checked in inferFromTypes. + anyFunctionType.flags |= 536870912 /* ContainsAnyFunctionType */; + var noConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + var circularConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + var resolvingDefaultType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + var markerSuperType = createType(262144 /* TypeParameter */); + var markerSubType = createType(262144 /* TypeParameter */); + markerSubType.constraint = markerSuperType; + var markerOtherType = createType(262144 /* TypeParameter */); + var noTypePredicate = createIdentifierTypePredicate("<>", 0, anyType); + var anySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + var unknownSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, errorType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + var resolvingSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + var silentNeverSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, silentNeverType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + var enumNumberIndexInfo = createIndexInfo(stringType, /*isReadonly*/ true); + var globals = ts.createSymbolTable(); + /** Key is "/path/to/a.ts|/path/to/b.ts". */ + var amalgamatedDuplicates; + var reverseMappedCache = ts.createMap(); + var ambientModulesCache; + /** + * List of every ambient module with a "*" wildcard. + * Unlike other ambient modules, these can't be stored in `globals` because symbol tables only deal with exact matches. + * This is only used if there is no exact match. + */ + var patternAmbientModules; + var globalObjectType; + var globalFunctionType; + var globalCallableFunctionType; + var globalNewableFunctionType; + var globalArrayType; + var globalReadonlyArrayType; + var globalStringType; + var globalNumberType; + var globalBooleanType; + var globalRegExpType; + var globalThisType; + var anyArrayType; + var autoArrayType; + var anyReadonlyArrayType; + var deferredGlobalNonNullableTypeAlias; + // The library files are only loaded when the feature is used. + // This allows users to just specify library files they want to used through --lib + // and they will not get an error from not having unrelated library files + var deferredGlobalESSymbolConstructorSymbol; + var deferredGlobalESSymbolType; + var deferredGlobalTypedPropertyDescriptorType; + var deferredGlobalPromiseType; + var deferredGlobalPromiseLikeType; + var deferredGlobalPromiseConstructorSymbol; + var deferredGlobalPromiseConstructorLikeType; + var deferredGlobalIterableType; + var deferredGlobalIteratorType; + var deferredGlobalIterableIteratorType; + var deferredGlobalAsyncIterableType; + var deferredGlobalAsyncIteratorType; + var deferredGlobalAsyncIterableIteratorType; + var deferredGlobalTemplateStringsArrayType; + var deferredGlobalImportMetaType; + var deferredGlobalExtractSymbol; + var deferredGlobalExcludeSymbol; + var deferredGlobalPickSymbol; + var deferredGlobalBigIntType; + var allPotentiallyUnusedIdentifiers = ts.createMap(); // key is file name + var flowLoopStart = 0; + var flowLoopCount = 0; + var sharedFlowCount = 0; + var flowAnalysisDisabled = false; + var emptyStringType = getLiteralType(""); + var zeroType = getLiteralType(0); + var zeroBigIntType = getLiteralType({ negative: false, base10Value: "0" }); + var resolutionTargets = []; + var resolutionResults = []; + var resolutionPropertyNames = []; + var suggestionCount = 0; + var maximumSuggestionCount = 10; + var mergedSymbols = []; + var symbolLinks = []; + var nodeLinks = []; + var flowLoopCaches = []; + var flowLoopNodes = []; + var flowLoopKeys = []; + var flowLoopTypes = []; + var sharedFlowNodes = []; + var sharedFlowTypes = []; + var potentialThisCollisions = []; + var potentialNewTargetCollisions = []; + var awaitedTypeStack = []; + var diagnostics = ts.createDiagnosticCollection(); + // Suggestion diagnostics must have a file. Keyed by source file name. + var suggestionDiagnostics = ts.createMultiMap(); + var TypeFacts; + (function (TypeFacts) { + TypeFacts[TypeFacts["None"] = 0] = "None"; + TypeFacts[TypeFacts["TypeofEQString"] = 1] = "TypeofEQString"; + TypeFacts[TypeFacts["TypeofEQNumber"] = 2] = "TypeofEQNumber"; + TypeFacts[TypeFacts["TypeofEQBigInt"] = 4] = "TypeofEQBigInt"; + TypeFacts[TypeFacts["TypeofEQBoolean"] = 8] = "TypeofEQBoolean"; + TypeFacts[TypeFacts["TypeofEQSymbol"] = 16] = "TypeofEQSymbol"; + TypeFacts[TypeFacts["TypeofEQObject"] = 32] = "TypeofEQObject"; + TypeFacts[TypeFacts["TypeofEQFunction"] = 64] = "TypeofEQFunction"; + TypeFacts[TypeFacts["TypeofEQHostObject"] = 128] = "TypeofEQHostObject"; + TypeFacts[TypeFacts["TypeofNEString"] = 256] = "TypeofNEString"; + TypeFacts[TypeFacts["TypeofNENumber"] = 512] = "TypeofNENumber"; + TypeFacts[TypeFacts["TypeofNEBigInt"] = 1024] = "TypeofNEBigInt"; + TypeFacts[TypeFacts["TypeofNEBoolean"] = 2048] = "TypeofNEBoolean"; + TypeFacts[TypeFacts["TypeofNESymbol"] = 4096] = "TypeofNESymbol"; + TypeFacts[TypeFacts["TypeofNEObject"] = 8192] = "TypeofNEObject"; + TypeFacts[TypeFacts["TypeofNEFunction"] = 16384] = "TypeofNEFunction"; + TypeFacts[TypeFacts["TypeofNEHostObject"] = 32768] = "TypeofNEHostObject"; + TypeFacts[TypeFacts["EQUndefined"] = 65536] = "EQUndefined"; + TypeFacts[TypeFacts["EQNull"] = 131072] = "EQNull"; + TypeFacts[TypeFacts["EQUndefinedOrNull"] = 262144] = "EQUndefinedOrNull"; + TypeFacts[TypeFacts["NEUndefined"] = 524288] = "NEUndefined"; + TypeFacts[TypeFacts["NENull"] = 1048576] = "NENull"; + TypeFacts[TypeFacts["NEUndefinedOrNull"] = 2097152] = "NEUndefinedOrNull"; + TypeFacts[TypeFacts["Truthy"] = 4194304] = "Truthy"; + TypeFacts[TypeFacts["Falsy"] = 8388608] = "Falsy"; + TypeFacts[TypeFacts["All"] = 16777215] = "All"; + // The following members encode facts about particular kinds of types for use in the getTypeFacts function. + // The presence of a particular fact means that the given test is true for some (and possibly all) values + // of that kind of type. + TypeFacts[TypeFacts["BaseStringStrictFacts"] = 3735041] = "BaseStringStrictFacts"; + TypeFacts[TypeFacts["BaseStringFacts"] = 12582401] = "BaseStringFacts"; + TypeFacts[TypeFacts["StringStrictFacts"] = 16317953] = "StringStrictFacts"; + TypeFacts[TypeFacts["StringFacts"] = 16776705] = "StringFacts"; + TypeFacts[TypeFacts["EmptyStringStrictFacts"] = 12123649] = "EmptyStringStrictFacts"; + TypeFacts[TypeFacts["EmptyStringFacts"] = 12582401] = "EmptyStringFacts"; + TypeFacts[TypeFacts["NonEmptyStringStrictFacts"] = 7929345] = "NonEmptyStringStrictFacts"; + TypeFacts[TypeFacts["NonEmptyStringFacts"] = 16776705] = "NonEmptyStringFacts"; + TypeFacts[TypeFacts["BaseNumberStrictFacts"] = 3734786] = "BaseNumberStrictFacts"; + TypeFacts[TypeFacts["BaseNumberFacts"] = 12582146] = "BaseNumberFacts"; + TypeFacts[TypeFacts["NumberStrictFacts"] = 16317698] = "NumberStrictFacts"; + TypeFacts[TypeFacts["NumberFacts"] = 16776450] = "NumberFacts"; + TypeFacts[TypeFacts["ZeroNumberStrictFacts"] = 12123394] = "ZeroNumberStrictFacts"; + TypeFacts[TypeFacts["ZeroNumberFacts"] = 12582146] = "ZeroNumberFacts"; + TypeFacts[TypeFacts["NonZeroNumberStrictFacts"] = 7929090] = "NonZeroNumberStrictFacts"; + TypeFacts[TypeFacts["NonZeroNumberFacts"] = 16776450] = "NonZeroNumberFacts"; + TypeFacts[TypeFacts["BaseBigIntStrictFacts"] = 3734276] = "BaseBigIntStrictFacts"; + TypeFacts[TypeFacts["BaseBigIntFacts"] = 12581636] = "BaseBigIntFacts"; + TypeFacts[TypeFacts["BigIntStrictFacts"] = 16317188] = "BigIntStrictFacts"; + TypeFacts[TypeFacts["BigIntFacts"] = 16775940] = "BigIntFacts"; + TypeFacts[TypeFacts["ZeroBigIntStrictFacts"] = 12122884] = "ZeroBigIntStrictFacts"; + TypeFacts[TypeFacts["ZeroBigIntFacts"] = 12581636] = "ZeroBigIntFacts"; + TypeFacts[TypeFacts["NonZeroBigIntStrictFacts"] = 7928580] = "NonZeroBigIntStrictFacts"; + TypeFacts[TypeFacts["NonZeroBigIntFacts"] = 16775940] = "NonZeroBigIntFacts"; + TypeFacts[TypeFacts["BaseBooleanStrictFacts"] = 3733256] = "BaseBooleanStrictFacts"; + TypeFacts[TypeFacts["BaseBooleanFacts"] = 12580616] = "BaseBooleanFacts"; + TypeFacts[TypeFacts["BooleanStrictFacts"] = 16316168] = "BooleanStrictFacts"; + TypeFacts[TypeFacts["BooleanFacts"] = 16774920] = "BooleanFacts"; + TypeFacts[TypeFacts["FalseStrictFacts"] = 12121864] = "FalseStrictFacts"; + TypeFacts[TypeFacts["FalseFacts"] = 12580616] = "FalseFacts"; + TypeFacts[TypeFacts["TrueStrictFacts"] = 7927560] = "TrueStrictFacts"; + TypeFacts[TypeFacts["TrueFacts"] = 16774920] = "TrueFacts"; + TypeFacts[TypeFacts["SymbolStrictFacts"] = 7925520] = "SymbolStrictFacts"; + TypeFacts[TypeFacts["SymbolFacts"] = 16772880] = "SymbolFacts"; + TypeFacts[TypeFacts["ObjectStrictFacts"] = 7888800] = "ObjectStrictFacts"; + TypeFacts[TypeFacts["ObjectFacts"] = 16736160] = "ObjectFacts"; + TypeFacts[TypeFacts["FunctionStrictFacts"] = 7880640] = "FunctionStrictFacts"; + TypeFacts[TypeFacts["FunctionFacts"] = 16728000] = "FunctionFacts"; + TypeFacts[TypeFacts["UndefinedFacts"] = 9830144] = "UndefinedFacts"; + TypeFacts[TypeFacts["NullFacts"] = 9363232] = "NullFacts"; + TypeFacts[TypeFacts["EmptyObjectStrictFacts"] = 16318463] = "EmptyObjectStrictFacts"; + TypeFacts[TypeFacts["EmptyObjectFacts"] = 16777215] = "EmptyObjectFacts"; + })(TypeFacts || (TypeFacts = {})); + var typeofEQFacts = ts.createMapFromTemplate({ + string: 1 /* TypeofEQString */, + number: 2 /* TypeofEQNumber */, + bigint: 4 /* TypeofEQBigInt */, + boolean: 8 /* TypeofEQBoolean */, + symbol: 16 /* TypeofEQSymbol */, + undefined: 65536 /* EQUndefined */, + object: 32 /* TypeofEQObject */, + function: 64 /* TypeofEQFunction */ + }); + var typeofNEFacts = ts.createMapFromTemplate({ + string: 256 /* TypeofNEString */, + number: 512 /* TypeofNENumber */, + bigint: 1024 /* TypeofNEBigInt */, + boolean: 2048 /* TypeofNEBoolean */, + symbol: 4096 /* TypeofNESymbol */, + undefined: 524288 /* NEUndefined */, + object: 8192 /* TypeofNEObject */, + function: 16384 /* TypeofNEFunction */ + }); + var typeofTypesByName = ts.createMapFromTemplate({ + string: stringType, + number: numberType, + bigint: bigintType, + boolean: booleanType, + symbol: esSymbolType, + undefined: undefinedType + }); + var typeofType = createTypeofType(); + var _jsxNamespace; + var _jsxFactoryEntity; + var subtypeRelation = ts.createMap(); + var assignableRelation = ts.createMap(); + var definitelyAssignableRelation = ts.createMap(); + var comparableRelation = ts.createMap(); + var identityRelation = ts.createMap(); + var enumRelation = ts.createMap(); + var TypeSystemPropertyName; + (function (TypeSystemPropertyName) { + TypeSystemPropertyName[TypeSystemPropertyName["Type"] = 0] = "Type"; + TypeSystemPropertyName[TypeSystemPropertyName["ResolvedBaseConstructorType"] = 1] = "ResolvedBaseConstructorType"; + TypeSystemPropertyName[TypeSystemPropertyName["DeclaredType"] = 2] = "DeclaredType"; + TypeSystemPropertyName[TypeSystemPropertyName["ResolvedReturnType"] = 3] = "ResolvedReturnType"; + TypeSystemPropertyName[TypeSystemPropertyName["ImmediateBaseConstraint"] = 4] = "ImmediateBaseConstraint"; + TypeSystemPropertyName[TypeSystemPropertyName["EnumTagType"] = 5] = "EnumTagType"; + TypeSystemPropertyName[TypeSystemPropertyName["JSDocTypeReference"] = 6] = "JSDocTypeReference"; + })(TypeSystemPropertyName || (TypeSystemPropertyName = {})); + var CheckMode; + (function (CheckMode) { + CheckMode[CheckMode["Normal"] = 0] = "Normal"; + CheckMode[CheckMode["SkipContextSensitive"] = 1] = "SkipContextSensitive"; + CheckMode[CheckMode["Inferential"] = 2] = "Inferential"; + CheckMode[CheckMode["Contextual"] = 3] = "Contextual"; + })(CheckMode || (CheckMode = {})); + var CallbackCheck; + (function (CallbackCheck) { + CallbackCheck[CallbackCheck["None"] = 0] = "None"; + CallbackCheck[CallbackCheck["Bivariant"] = 1] = "Bivariant"; + CallbackCheck[CallbackCheck["Strict"] = 2] = "Strict"; + })(CallbackCheck || (CallbackCheck = {})); + var MappedTypeModifiers; + (function (MappedTypeModifiers) { + MappedTypeModifiers[MappedTypeModifiers["IncludeReadonly"] = 1] = "IncludeReadonly"; + MappedTypeModifiers[MappedTypeModifiers["ExcludeReadonly"] = 2] = "ExcludeReadonly"; + MappedTypeModifiers[MappedTypeModifiers["IncludeOptional"] = 4] = "IncludeOptional"; + MappedTypeModifiers[MappedTypeModifiers["ExcludeOptional"] = 8] = "ExcludeOptional"; + })(MappedTypeModifiers || (MappedTypeModifiers = {})); + var ExpandingFlags; + (function (ExpandingFlags) { + ExpandingFlags[ExpandingFlags["None"] = 0] = "None"; + ExpandingFlags[ExpandingFlags["Source"] = 1] = "Source"; + ExpandingFlags[ExpandingFlags["Target"] = 2] = "Target"; + ExpandingFlags[ExpandingFlags["Both"] = 3] = "Both"; + })(ExpandingFlags || (ExpandingFlags = {})); + var MembersOrExportsResolutionKind; + (function (MembersOrExportsResolutionKind) { + MembersOrExportsResolutionKind["resolvedExports"] = "resolvedExports"; + MembersOrExportsResolutionKind["resolvedMembers"] = "resolvedMembers"; + })(MembersOrExportsResolutionKind || (MembersOrExportsResolutionKind = {})); + var UnusedKind; + (function (UnusedKind) { + UnusedKind[UnusedKind["Local"] = 0] = "Local"; + UnusedKind[UnusedKind["Parameter"] = 1] = "Parameter"; + })(UnusedKind || (UnusedKind = {})); + var builtinGlobals = ts.createSymbolTable(); + builtinGlobals.set(undefinedSymbol.escapedName, undefinedSymbol); + var isNotOverloadAndNotAccessor = ts.and(isNotOverload, isNotAccessor); + initializeTypeChecker(); + return checker; + function getJsxNamespace(location) { + if (location) { + var file = ts.getSourceFileOfNode(location); + if (file) { + if (file.localJsxNamespace) { + return file.localJsxNamespace; + } + var jsxPragma = file.pragmas.get("jsx"); + if (jsxPragma) { + var chosenpragma = ts.isArray(jsxPragma) ? jsxPragma[0] : jsxPragma; // TODO: GH#18217 + file.localJsxFactory = ts.parseIsolatedEntityName(chosenpragma.arguments.factory, languageVersion); + if (file.localJsxFactory) { + return file.localJsxNamespace = getFirstIdentifier(file.localJsxFactory).escapedText; + } + } + } + } + if (!_jsxNamespace) { + _jsxNamespace = "React"; + if (compilerOptions.jsxFactory) { + _jsxFactoryEntity = ts.parseIsolatedEntityName(compilerOptions.jsxFactory, languageVersion); + if (_jsxFactoryEntity) { + _jsxNamespace = getFirstIdentifier(_jsxFactoryEntity).escapedText; + } + } + else if (compilerOptions.reactNamespace) { + _jsxNamespace = ts.escapeLeadingUnderscores(compilerOptions.reactNamespace); + } + } + return _jsxNamespace; + } + function getEmitResolver(sourceFile, cancellationToken) { + // Ensure we have all the type information in place for this file so that all the + // emitter questions of this resolver will return the right information. + getDiagnostics(sourceFile, cancellationToken); + return emitResolver; + } + function lookupOrIssueError(location, message, arg0, arg1, arg2, arg3) { + var diagnostic = location + ? ts.createDiagnosticForNode(location, message, arg0, arg1, arg2, arg3) + : ts.createCompilerDiagnostic(message, arg0, arg1, arg2, arg3); + var existing = diagnostics.lookup(diagnostic); + if (existing) { + return existing; + } + else { + diagnostics.add(diagnostic); + return diagnostic; + } + } + function addRelatedInfo(diagnostic) { + var relatedInformation = []; + for (var _i = 1; _i < arguments.length; _i++) { + relatedInformation[_i - 1] = arguments[_i]; + } + var _a; + if (!diagnostic.relatedInformation) { + diagnostic.relatedInformation = []; + } + (_a = diagnostic.relatedInformation).push.apply(_a, relatedInformation); + return diagnostic; + } + function error(location, message, arg0, arg1, arg2, arg3) { + var diagnostic = location + ? ts.createDiagnosticForNode(location, message, arg0, arg1, arg2, arg3) + : ts.createCompilerDiagnostic(message, arg0, arg1, arg2, arg3); + diagnostics.add(diagnostic); + return diagnostic; + } + function addErrorOrSuggestion(isError, diagnostic) { + if (isError) { + diagnostics.add(diagnostic); + } + else { + suggestionDiagnostics.add(diagnostic.file.fileName, __assign({}, diagnostic, { category: ts.DiagnosticCategory.Suggestion })); + } + } + function errorOrSuggestion(isError, location, message, arg0, arg1, arg2, arg3) { + addErrorOrSuggestion(isError, "message" in message ? ts.createDiagnosticForNode(location, message, arg0, arg1, arg2, arg3) : ts.createDiagnosticForNodeFromMessageChain(location, message)); + } + function createSymbol(flags, name, checkFlags) { + symbolCount++; + var symbol = (new Symbol(flags | 33554432 /* Transient */, name)); + symbol.checkFlags = checkFlags || 0; + return symbol; + } + function isTransientSymbol(symbol) { + return (symbol.flags & 33554432 /* Transient */) !== 0; + } + function getExcludedSymbolFlags(flags) { + var result = 0; + if (flags & 2 /* BlockScopedVariable */) + result |= 67220415 /* BlockScopedVariableExcludes */; + if (flags & 1 /* FunctionScopedVariable */) + result |= 67220414 /* FunctionScopedVariableExcludes */; + if (flags & 4 /* Property */) + result |= 0 /* PropertyExcludes */; + if (flags & 8 /* EnumMember */) + result |= 68008959 /* EnumMemberExcludes */; + if (flags & 16 /* Function */) + result |= 67219887 /* FunctionExcludes */; + if (flags & 32 /* Class */) + result |= 68008383 /* ClassExcludes */; + if (flags & 64 /* Interface */) + result |= 67897736 /* InterfaceExcludes */; + if (flags & 256 /* RegularEnum */) + result |= 68008191 /* RegularEnumExcludes */; + if (flags & 128 /* ConstEnum */) + result |= 68008831 /* ConstEnumExcludes */; + if (flags & 512 /* ValueModule */) + result |= 110735 /* ValueModuleExcludes */; + if (flags & 8192 /* Method */) + result |= 67212223 /* MethodExcludes */; + if (flags & 32768 /* GetAccessor */) + result |= 67154879 /* GetAccessorExcludes */; + if (flags & 65536 /* SetAccessor */) + result |= 67187647 /* SetAccessorExcludes */; + if (flags & 262144 /* TypeParameter */) + result |= 67635688 /* TypeParameterExcludes */; + if (flags & 524288 /* TypeAlias */) + result |= 67897832 /* TypeAliasExcludes */; + if (flags & 2097152 /* Alias */) + result |= 2097152 /* AliasExcludes */; + return result; + } + function recordMergedSymbol(target, source) { + if (!source.mergeId) { + source.mergeId = nextMergeId; + nextMergeId++; + } + mergedSymbols[source.mergeId] = target; + } + function cloneSymbol(symbol) { + var result = createSymbol(symbol.flags, symbol.escapedName); + result.declarations = symbol.declarations ? symbol.declarations.slice() : []; + result.parent = symbol.parent; + if (symbol.valueDeclaration) + result.valueDeclaration = symbol.valueDeclaration; + if (symbol.constEnumOnlyModule) + result.constEnumOnlyModule = true; + if (symbol.members) + result.members = ts.cloneMap(symbol.members); + if (symbol.exports) + result.exports = ts.cloneMap(symbol.exports); + recordMergedSymbol(result, symbol); + return result; + } + /** + * Note: if target is transient, then it is mutable, and mergeSymbol with both mutate and return it. + * If target is not transient, mergeSymbol will produce a transient clone, mutate that and return it. + */ + function mergeSymbol(target, source) { + if (!(target.flags & getExcludedSymbolFlags(source.flags)) || + (source.flags | target.flags) & 67108864 /* Assignment */) { + ts.Debug.assert(source !== target); + if (!(target.flags & 33554432 /* Transient */)) { + var resolvedTarget = resolveSymbol(target); + if (resolvedTarget === unknownSymbol) { + return source; + } + target = cloneSymbol(resolvedTarget); + } + // Javascript static-property-assignment declarations always merge, even though they are also values + if (source.flags & 512 /* ValueModule */ && target.flags & 512 /* ValueModule */ && target.constEnumOnlyModule && !source.constEnumOnlyModule) { + // reset flag when merging instantiated module into value module that has only const enums + target.constEnumOnlyModule = false; + } + target.flags |= source.flags; + if (source.valueDeclaration && + (!target.valueDeclaration || + ts.isAssignmentDeclaration(target.valueDeclaration) && !ts.isAssignmentDeclaration(source.valueDeclaration) || + ts.isEffectiveModuleDeclaration(target.valueDeclaration) && !ts.isEffectiveModuleDeclaration(source.valueDeclaration))) { + // other kinds of value declarations take precedence over modules and assignment declarations + target.valueDeclaration = source.valueDeclaration; + } + ts.addRange(target.declarations, source.declarations); + if (source.members) { + if (!target.members) + target.members = ts.createSymbolTable(); + mergeSymbolTable(target.members, source.members); + } + if (source.exports) { + if (!target.exports) + target.exports = ts.createSymbolTable(); + mergeSymbolTable(target.exports, source.exports); + } + recordMergedSymbol(target, source); + } + else if (target.flags & 1024 /* NamespaceModule */) { + error(ts.getNameOfDeclaration(source.declarations[0]), ts.Diagnostics.Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity, symbolToString(target)); + } + else { // error + var isEitherEnum = !!(target.flags & 384 /* Enum */ || source.flags & 384 /* Enum */); + var isEitherBlockScoped_1 = !!(target.flags & 2 /* BlockScopedVariable */ || source.flags & 2 /* BlockScopedVariable */); + var message = isEitherEnum + ? ts.Diagnostics.Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations + : isEitherBlockScoped_1 + ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 + : ts.Diagnostics.Duplicate_identifier_0; + var sourceSymbolFile = source.declarations && ts.getSourceFileOfNode(source.declarations[0]); + var targetSymbolFile = target.declarations && ts.getSourceFileOfNode(target.declarations[0]); + var symbolName_1 = symbolToString(source); + // Collect top-level duplicate identifier errors into one mapping, so we can then merge their diagnostics if there are a bunch + if (sourceSymbolFile && targetSymbolFile && amalgamatedDuplicates && !isEitherEnum && sourceSymbolFile !== targetSymbolFile) { + var firstFile_1 = ts.comparePaths(sourceSymbolFile.path, targetSymbolFile.path) === -1 /* LessThan */ ? sourceSymbolFile : targetSymbolFile; + var secondFile_1 = firstFile_1 === sourceSymbolFile ? targetSymbolFile : sourceSymbolFile; + var filesDuplicates = ts.getOrUpdate(amalgamatedDuplicates, firstFile_1.path + "|" + secondFile_1.path, function () { + return ({ firstFile: firstFile_1, secondFile: secondFile_1, conflictingSymbols: ts.createMap() }); + }); + var conflictingSymbolInfo = ts.getOrUpdate(filesDuplicates.conflictingSymbols, symbolName_1, function () { + return ({ isBlockScoped: isEitherBlockScoped_1, firstFileLocations: [], secondFileLocations: [] }); + }); + addDuplicateLocations(conflictingSymbolInfo.firstFileLocations, source); + addDuplicateLocations(conflictingSymbolInfo.secondFileLocations, target); + } + else { + addDuplicateDeclarationErrorsForSymbols(source, message, symbolName_1, target); + addDuplicateDeclarationErrorsForSymbols(target, message, symbolName_1, source); + } + } + return target; + function addDuplicateLocations(locs, symbol) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + ts.pushIfUnique(locs, (ts.getExpandoInitializer(decl, /*isPrototypeAssignment*/ false) ? ts.getNameOfExpando(decl) : ts.getNameOfDeclaration(decl)) || decl); + } + } + } + function addDuplicateDeclarationErrorsForSymbols(target, message, symbolName, source) { + ts.forEach(target.declarations, function (node) { + var errorNode = (ts.getExpandoInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getNameOfExpando(node) : ts.getNameOfDeclaration(node)) || node; + addDuplicateDeclarationError(errorNode, message, symbolName, source.declarations); + }); + } + function addDuplicateDeclarationError(errorNode, message, symbolName, relatedNodes) { + var err = lookupOrIssueError(errorNode, message, symbolName); + for (var _i = 0, _a = relatedNodes || ts.emptyArray; _i < _a.length; _i++) { + var relatedNode = _a[_i]; + err.relatedInformation = err.relatedInformation || []; + if (ts.length(err.relatedInformation) >= 5) + continue; + addRelatedInfo(err, !ts.length(err.relatedInformation) ? ts.createDiagnosticForNode(relatedNode, ts.Diagnostics._0_was_also_declared_here, symbolName) : ts.createDiagnosticForNode(relatedNode, ts.Diagnostics.and_here)); + } + } + function combineSymbolTables(first, second) { + if (!ts.hasEntries(first)) + return second; + if (!ts.hasEntries(second)) + return first; + var combined = ts.createSymbolTable(); + mergeSymbolTable(combined, first); + mergeSymbolTable(combined, second); + return combined; + } + function mergeSymbolTable(target, source) { + source.forEach(function (sourceSymbol, id) { + var targetSymbol = target.get(id); + target.set(id, targetSymbol ? mergeSymbol(targetSymbol, sourceSymbol) : sourceSymbol); + }); + } + function mergeModuleAugmentation(moduleName) { + var moduleAugmentation = moduleName.parent; + if (moduleAugmentation.symbol.declarations[0] !== moduleAugmentation) { + // this is a combined symbol for multiple augmentations within the same file. + // its symbol already has accumulated information for all declarations + // so we need to add it just once - do the work only for first declaration + ts.Debug.assert(moduleAugmentation.symbol.declarations.length > 1); + return; + } + if (ts.isGlobalScopeAugmentation(moduleAugmentation)) { + mergeSymbolTable(globals, moduleAugmentation.symbol.exports); + } + else { + // find a module that about to be augmented + // do not validate names of augmentations that are defined in ambient context + var moduleNotFoundError = !(moduleName.parent.parent.flags & 4194304 /* Ambient */) + ? ts.Diagnostics.Invalid_module_name_in_augmentation_module_0_cannot_be_found + : undefined; + var mainModule = resolveExternalModuleNameWorker(moduleName, moduleName, moduleNotFoundError, /*isForAugmentation*/ true); + if (!mainModule) { + return; + } + // obtain item referenced by 'export=' + mainModule = resolveExternalModuleSymbol(mainModule); + if (mainModule.flags & 1920 /* Namespace */) { + mainModule = mergeSymbol(mainModule, moduleAugmentation.symbol); + } + else { + // moduleName will be a StringLiteral since this is not `declare global`. + error(moduleName, ts.Diagnostics.Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity, moduleName.text); + } + } + } + function addToSymbolTable(target, source, message) { + source.forEach(function (sourceSymbol, id) { + var targetSymbol = target.get(id); + if (targetSymbol) { + // Error on redeclarations + ts.forEach(targetSymbol.declarations, addDeclarationDiagnostic(ts.unescapeLeadingUnderscores(id), message)); + } + else { + target.set(id, sourceSymbol); + } + }); + function addDeclarationDiagnostic(id, message) { + return function (declaration) { return diagnostics.add(ts.createDiagnosticForNode(declaration, message, id)); }; + } + } + function getSymbolLinks(symbol) { + if (symbol.flags & 33554432 /* Transient */) + return symbol; + var id = getSymbolId(symbol); + return symbolLinks[id] || (symbolLinks[id] = {}); + } + function getNodeLinks(node) { + var nodeId = getNodeId(node); + return nodeLinks[nodeId] || (nodeLinks[nodeId] = { flags: 0 }); + } + function isGlobalSourceFile(node) { + return node.kind === 279 /* SourceFile */ && !ts.isExternalOrCommonJsModule(node); + } + function getSymbol(symbols, name, meaning) { + if (meaning) { + var symbol = symbols.get(name); + if (symbol) { + ts.Debug.assert((ts.getCheckFlags(symbol) & 1 /* Instantiated */) === 0, "Should never get an instantiated symbol here."); + if (symbol.flags & meaning) { + return symbol; + } + if (symbol.flags & 2097152 /* Alias */) { + var target = resolveAlias(symbol); + // Unknown symbol means an error occurred in alias resolution, treat it as positive answer to avoid cascading errors + if (target === unknownSymbol || target.flags & meaning) { + return symbol; + } + } + } + } + // return undefined if we can't find a symbol. + } + /** + * Get symbols that represent parameter-property-declaration as parameter and as property declaration + * @param parameter a parameterDeclaration node + * @param parameterName a name of the parameter to get the symbols for. + * @return a tuple of two symbols + */ + function getSymbolsOfParameterPropertyDeclaration(parameter, parameterName) { + var constructorDeclaration = parameter.parent; + var classDeclaration = parameter.parent.parent; + var parameterSymbol = getSymbol(constructorDeclaration.locals, parameterName, 67220415 /* Value */); + var propertySymbol = getSymbol(getMembersOfSymbol(classDeclaration.symbol), parameterName, 67220415 /* Value */); + if (parameterSymbol && propertySymbol) { + return [parameterSymbol, propertySymbol]; + } + return ts.Debug.fail("There should exist two symbols, one as property declaration and one as parameter declaration"); + } + function isBlockScopedNameDeclaredBeforeUse(declaration, usage) { + var declarationFile = ts.getSourceFileOfNode(declaration); + var useFile = ts.getSourceFileOfNode(usage); + if (declarationFile !== useFile) { + if ((moduleKind && (declarationFile.externalModuleIndicator || useFile.externalModuleIndicator)) || + (!compilerOptions.outFile && !compilerOptions.out) || + isInTypeQuery(usage) || + declaration.flags & 4194304 /* Ambient */) { + // nodes are in different files and order cannot be determined + return true; + } + // declaration is after usage + // can be legal if usage is deferred (i.e. inside function or in initializer of instance property) + if (isUsedInFunctionOrInstanceProperty(usage, declaration)) { + return true; + } + var sourceFiles = host.getSourceFiles(); + return sourceFiles.indexOf(declarationFile) <= sourceFiles.indexOf(useFile); + } + if (declaration.pos <= usage.pos) { + // declaration is before usage + if (declaration.kind === 186 /* BindingElement */) { + // still might be illegal if declaration and usage are both binding elements (eg var [a = b, b = b] = [1, 2]) + var errorBindingElement = ts.getAncestor(usage, 186 /* BindingElement */); + if (errorBindingElement) { + return ts.findAncestor(errorBindingElement, ts.isBindingElement) !== ts.findAncestor(declaration, ts.isBindingElement) || + declaration.pos < errorBindingElement.pos; + } + // or it might be illegal if usage happens before parent variable is declared (eg var [a] = a) + return isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 237 /* VariableDeclaration */), usage); + } + else if (declaration.kind === 237 /* VariableDeclaration */) { + // still might be illegal if usage is in the initializer of the variable declaration (eg var a = a) + return !isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage); + } + else if (ts.isClassDeclaration(declaration)) { + // still might be illegal if the usage is within a computed property name in the class (eg class A { static p = "a"; [A.p]() {} }) + return !ts.findAncestor(usage, function (n) { return ts.isComputedPropertyName(n) && n.parent.parent === declaration; }); + } + return true; + } + // declaration is after usage, but it can still be legal if usage is deferred: + // 1. inside an export specifier + // 2. inside a function + // 3. inside an instance property initializer, a reference to a non-instance property + // 4. inside a static property initializer, a reference to a static method in the same class + // 5. inside a TS export= declaration (since we will move the export statement during emit to avoid TDZ) + // or if usage is in a type context: + // 1. inside a type query (typeof in type position) + // 2. inside a jsdoc comment + if (usage.parent.kind === 257 /* ExportSpecifier */ || (usage.parent.kind === 254 /* ExportAssignment */ && usage.parent.isExportEquals)) { + // export specifiers do not use the variable, they only make it available for use + return true; + } + // When resolving symbols for exports, the `usage` location passed in can be the export site directly + if (usage.kind === 254 /* ExportAssignment */ && usage.isExportEquals) { + return true; + } + var container = ts.getEnclosingBlockScopeContainer(declaration); + return !!(usage.flags & 2097152 /* JSDoc */) || isInTypeQuery(usage) || isUsedInFunctionOrInstanceProperty(usage, declaration, container); + function isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage) { + var container = ts.getEnclosingBlockScopeContainer(declaration); + switch (declaration.parent.parent.kind) { + case 219 /* VariableStatement */: + case 225 /* ForStatement */: + case 227 /* ForOfStatement */: + // variable statement/for/for-of statement case, + // use site should not be inside variable declaration (initializer of declaration or binding element) + if (isSameScopeDescendentOf(usage, declaration, container)) { + return true; + } + break; + } + // ForIn/ForOf case - use site should not be used in expression part + var grandparent = declaration.parent.parent; + return ts.isForInOrOfStatement(grandparent) && isSameScopeDescendentOf(usage, grandparent.expression, container); + } + function isUsedInFunctionOrInstanceProperty(usage, declaration, container) { + return !!ts.findAncestor(usage, function (current) { + if (current === container) { + return "quit"; + } + if (ts.isFunctionLike(current)) { + return true; + } + var initializerOfProperty = current.parent && + current.parent.kind === 154 /* PropertyDeclaration */ && + current.parent.initializer === current; + if (initializerOfProperty) { + if (ts.hasModifier(current.parent, 32 /* Static */)) { + if (declaration.kind === 156 /* MethodDeclaration */) { + return true; + } + } + else { + var isDeclarationInstanceProperty = declaration.kind === 154 /* PropertyDeclaration */ && !ts.hasModifier(declaration, 32 /* Static */); + if (!isDeclarationInstanceProperty || ts.getContainingClass(usage) !== ts.getContainingClass(declaration)) { + return true; + } + } + } + return false; + }); + } + } + /** + * Resolve a given name for a given meaning at a given location. An error is reported if the name was not found and + * the nameNotFoundMessage argument is not undefined. Returns the resolved symbol, or undefined if no symbol with + * the given name can be found. + * + * @param isUse If true, this will count towards --noUnusedLocals / --noUnusedParameters. + */ + function resolveName(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, suggestedNameNotFoundMessage) { + if (excludeGlobals === void 0) { excludeGlobals = false; } + return resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, getSymbol, suggestedNameNotFoundMessage); + } + function resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, lookup, suggestedNameNotFoundMessage) { + var originalLocation = location; // needed for did-you-mean error reporting, which gathers candidates starting from the original location + var result; + var lastLocation; + var lastSelfReferenceLocation; + var propertyWithInvalidInitializer; + var errorLocation = location; + var grandparent; + var isInExternalModule = false; + loop: while (location) { + // Locals of a source file are not in scope (because they get merged into the global symbol table) + if (location.locals && !isGlobalSourceFile(location)) { + if (result = lookup(location.locals, name, meaning)) { + var useResult = true; + if (ts.isFunctionLike(location) && lastLocation && lastLocation !== location.body) { + // symbol lookup restrictions for function-like declarations + // - Type parameters of a function are in scope in the entire function declaration, including the parameter + // list and return type. However, local types are only in scope in the function body. + // - parameters are only in the scope of function body + // This restriction does not apply to JSDoc comment types because they are parented + // at a higher level than type parameters would normally be + if (meaning & result.flags & 67897832 /* Type */ && lastLocation.kind !== 291 /* JSDocComment */) { + useResult = result.flags & 262144 /* TypeParameter */ + // type parameters are visible in parameter list, return type and type parameter list + ? lastLocation === location.type || + lastLocation.kind === 151 /* Parameter */ || + lastLocation.kind === 150 /* TypeParameter */ + // local types not visible outside the function body + : false; + } + if (meaning & result.flags & 3 /* Variable */) { + // expression inside parameter will lookup as normal variable scope when targeting es2015+ + var functionLocation = location; + if (compilerOptions.target && compilerOptions.target >= 2 /* ES2015 */ && ts.isParameter(lastLocation) && + functionLocation.body && result.valueDeclaration.pos >= functionLocation.body.pos && result.valueDeclaration.end <= functionLocation.body.end) { + useResult = false; + } + else if (result.flags & 1 /* FunctionScopedVariable */) { + // parameters are visible only inside function body, parameter list and return type + // technically for parameter list case here we might mix parameters and variables declared in function, + // however it is detected separately when checking initializers of parameters + // to make sure that they reference no variables declared after them. + useResult = + lastLocation.kind === 151 /* Parameter */ || + (lastLocation === location.type && + !!ts.findAncestor(result.valueDeclaration, ts.isParameter)); + } + } + } + else if (location.kind === 175 /* ConditionalType */) { + // A type parameter declared using 'infer T' in a conditional type is visible only in + // the true branch of the conditional type. + useResult = lastLocation === location.trueType; + } + if (useResult) { + break loop; + } + else { + result = undefined; + } + } + } + switch (location.kind) { + case 279 /* SourceFile */: + if (!ts.isExternalOrCommonJsModule(location)) + break; + isInExternalModule = true; + // falls through + case 244 /* ModuleDeclaration */: + var moduleExports = getSymbolOfNode(location).exports; + if (location.kind === 279 /* SourceFile */ || ts.isAmbientModule(location)) { + // It's an external module. First see if the module has an export default and if the local + // name of that export default matches. + if (result = moduleExports.get("default" /* Default */)) { + var localSymbol = ts.getLocalSymbolForExportDefault(result); + if (localSymbol && (result.flags & meaning) && localSymbol.escapedName === name) { + break loop; + } + result = undefined; + } + // Because of module/namespace merging, a module's exports are in scope, + // yet we never want to treat an export specifier as putting a member in scope. + // Therefore, if the name we find is purely an export specifier, it is not actually considered in scope. + // Two things to note about this: + // 1. We have to check this without calling getSymbol. The problem with calling getSymbol + // on an export specifier is that it might find the export specifier itself, and try to + // resolve it as an alias. This will cause the checker to consider the export specifier + // a circular alias reference when it might not be. + // 2. We check === SymbolFlags.Alias in order to check that the symbol is *purely* + // an alias. If we used &, we'd be throwing out symbols that have non alias aspects, + // which is not the desired behavior. + var moduleExport = moduleExports.get(name); + if (moduleExport && + moduleExport.flags === 2097152 /* Alias */ && + ts.getDeclarationOfKind(moduleExport, 257 /* ExportSpecifier */)) { + break; + } + } + // ES6 exports are also visible locally (except for 'default'), but commonjs exports are not (except typedefs) + if (name !== "default" /* Default */ && (result = lookup(moduleExports, name, meaning & 2623475 /* ModuleMember */))) { + if (ts.isSourceFile(location) && location.commonJsModuleIndicator && !result.declarations.some(ts.isJSDocTypeAlias)) { + result = undefined; + } + else { + break loop; + } + } + break; + case 243 /* EnumDeclaration */: + if (result = lookup(getSymbolOfNode(location).exports, name, meaning & 8 /* EnumMember */)) { + break loop; + } + break; + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + // TypeScript 1.0 spec (April 2014): 8.4.1 + // Initializer expressions for instance member variables are evaluated in the scope + // of the class constructor body but are not permitted to reference parameters or + // local variables of the constructor. This effectively means that entities from outer scopes + // by the same name as a constructor parameter or local variable are inaccessible + // in initializer expressions for instance member variables. + if (ts.isClassLike(location.parent) && !ts.hasModifier(location, 32 /* Static */)) { + var ctor = findConstructorDeclaration(location.parent); + if (ctor && ctor.locals) { + if (lookup(ctor.locals, name, meaning & 67220415 /* Value */)) { + // Remember the property node, it will be used later to report appropriate error + propertyWithInvalidInitializer = location; + } + } + } + break; + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 241 /* InterfaceDeclaration */: + // The below is used to lookup type parameters within a class or interface, as they are added to the class/interface locals + // These can never be latebound, so the symbol's raw members are sufficient. `getMembersOfNode` cannot be used, as it would + // trigger resolving late-bound names, which we may already be in the process of doing while we're here! + if (result = lookup(getSymbolOfNode(location).members || emptySymbols, name, meaning & 67897832 /* Type */)) { + if (!isTypeParameterSymbolDeclaredInContainer(result, location)) { + // ignore type parameters not declared in this container + result = undefined; + break; + } + if (lastLocation && ts.hasModifier(lastLocation, 32 /* Static */)) { + // TypeScript 1.0 spec (April 2014): 3.4.1 + // The scope of a type parameter extends over the entire declaration with which the type + // parameter list is associated, with the exception of static member declarations in classes. + error(errorLocation, ts.Diagnostics.Static_members_cannot_reference_class_type_parameters); + return undefined; + } + break loop; + } + if (location.kind === 209 /* ClassExpression */ && meaning & 32 /* Class */) { + var className = location.name; + if (className && name === className.escapedText) { + result = location.symbol; + break loop; + } + } + break; + case 211 /* ExpressionWithTypeArguments */: + // The type parameters of a class are not in scope in the base class expression. + if (lastLocation === location.expression && location.parent.token === 86 /* ExtendsKeyword */) { + var container = location.parent.parent; + if (ts.isClassLike(container) && (result = lookup(getSymbolOfNode(container).members, name, meaning & 67897832 /* Type */))) { + if (nameNotFoundMessage) { + error(errorLocation, ts.Diagnostics.Base_class_expressions_cannot_reference_class_type_parameters); + } + return undefined; + } + } + break; + // It is not legal to reference a class's own type parameters from a computed property name that + // belongs to the class. For example: + // + // function foo() { return '' } + // class C { // <-- Class's own type parameter T + // [foo()]() { } // <-- Reference to T from class's own computed property + // } + // + case 149 /* ComputedPropertyName */: + grandparent = location.parent.parent; + if (ts.isClassLike(grandparent) || grandparent.kind === 241 /* InterfaceDeclaration */) { + // A reference to this grandparent's type parameters would be an error + if (result = lookup(getSymbolOfNode(grandparent).members, name, meaning & 67897832 /* Type */)) { + error(errorLocation, ts.Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type); + return undefined; + } + } + break; + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 239 /* FunctionDeclaration */: + case 197 /* ArrowFunction */: + if (meaning & 3 /* Variable */ && name === "arguments") { + result = argumentsSymbol; + break loop; + } + break; + case 196 /* FunctionExpression */: + if (meaning & 3 /* Variable */ && name === "arguments") { + result = argumentsSymbol; + break loop; + } + if (meaning & 16 /* Function */) { + var functionName = location.name; + if (functionName && name === functionName.escapedText) { + result = location.symbol; + break loop; + } + } + break; + case 152 /* Decorator */: + // Decorators are resolved at the class declaration. Resolving at the parameter + // or member would result in looking up locals in the method. + // + // function y() {} + // class C { + // method(@y x, y) {} // <-- decorator y should be resolved at the class declaration, not the parameter. + // } + // + if (location.parent && location.parent.kind === 151 /* Parameter */) { + location = location.parent; + } + // + // function y() {} + // class C { + // @y method(x, y) {} // <-- decorator y should be resolved at the class declaration, not the method. + // } + // + if (location.parent && ts.isClassElement(location.parent)) { + location = location.parent; + } + break; + case 304 /* JSDocTypedefTag */: + case 297 /* JSDocCallbackTag */: + // js type aliases do not resolve names from their host, so skip past it + location = ts.getJSDocHost(location); + break; + } + if (isSelfReferenceLocation(location)) { + lastSelfReferenceLocation = location; + } + lastLocation = location; + location = location.parent; + } + // We just climbed up parents looking for the name, meaning that we started in a descendant node of `lastLocation`. + // If `result === lastSelfReferenceLocation.symbol`, that means that we are somewhere inside `lastSelfReferenceLocation` looking up a name, and resolving to `lastLocation` itself. + // That means that this is a self-reference of `lastLocation`, and shouldn't count this when considering whether `lastLocation` is used. + if (isUse && result && (!lastSelfReferenceLocation || result !== lastSelfReferenceLocation.symbol)) { + result.isReferenced |= meaning; + } + if (!result) { + if (lastLocation) { + ts.Debug.assert(lastLocation.kind === 279 /* SourceFile */); + if (lastLocation.commonJsModuleIndicator && name === "exports" && meaning & lastLocation.symbol.flags) { + return lastLocation.symbol; + } + } + if (!excludeGlobals) { + result = lookup(globals, name, meaning); + } + } + if (!result) { + if (originalLocation && ts.isInJSFile(originalLocation) && originalLocation.parent) { + if (ts.isRequireCall(originalLocation.parent, /*checkArgumentIsStringLiteralLike*/ false)) { + return requireSymbol; + } + } + } + if (!result) { + if (nameNotFoundMessage) { + if (!errorLocation || + !checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) && // TODO: GH#18217 + !checkAndReportErrorForExtendingInterface(errorLocation) && + !checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) && + !checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) && + !checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning)) { + var suggestion = void 0; + if (suggestedNameNotFoundMessage && suggestionCount < maximumSuggestionCount) { + suggestion = getSuggestedSymbolForNonexistentSymbol(originalLocation, name, meaning); + if (suggestion) { + var suggestionName = symbolToString(suggestion); + var diagnostic = error(errorLocation, suggestedNameNotFoundMessage, diagnosticName(nameArg), suggestionName); + if (suggestion.valueDeclaration) { + addRelatedInfo(diagnostic, ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestionName)); + } + } + } + if (!suggestion) { + error(errorLocation, nameNotFoundMessage, diagnosticName(nameArg)); + } + suggestionCount++; + } + } + return undefined; + } + // Perform extra checks only if error reporting was requested + if (nameNotFoundMessage) { + if (propertyWithInvalidInitializer) { + // We have a match, but the reference occurred within a property initializer and the identifier also binds + // to a local variable in the constructor where the code will be emitted. + var propertyName = propertyWithInvalidInitializer.name; + error(errorLocation, ts.Diagnostics.Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor, ts.declarationNameToString(propertyName), diagnosticName(nameArg)); + return undefined; + } + // Only check for block-scoped variable if we have an error location and are looking for the + // name with variable meaning + // For example, + // declare module foo { + // interface bar {} + // } + // const foo/*1*/: foo/*2*/.bar; + // The foo at /*1*/ and /*2*/ will share same symbol with two meanings: + // block-scoped variable and namespace module. However, only when we + // try to resolve name in /*1*/ which is used in variable position, + // we want to check for block-scoped + if (errorLocation && + (meaning & 2 /* BlockScopedVariable */ || + ((meaning & 32 /* Class */ || meaning & 384 /* Enum */) && (meaning & 67220415 /* Value */) === 67220415 /* Value */))) { + var exportOrLocalSymbol = getExportSymbolOfValueSymbolIfExported(result); + if (exportOrLocalSymbol.flags & 2 /* BlockScopedVariable */ || exportOrLocalSymbol.flags & 32 /* Class */ || exportOrLocalSymbol.flags & 384 /* Enum */) { + checkResolvedBlockScopedVariable(exportOrLocalSymbol, errorLocation); + } + } + // If we're in an external module, we can't reference value symbols created from UMD export declarations + if (result && isInExternalModule && (meaning & 67220415 /* Value */) === 67220415 /* Value */ && !(originalLocation.flags & 2097152 /* JSDoc */)) { + if (ts.some(result.declarations, function (d) { return ts.isNamespaceExportDeclaration(d) || ts.isSourceFile(d) && !!d.symbol.globalExports; })) { + error(errorLocation, ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead, ts.unescapeLeadingUnderscores(name)); // TODO: GH#18217 + } + } + } + return result; + } + function isSelfReferenceLocation(node) { + switch (node.kind) { + case 239 /* FunctionDeclaration */: + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + case 243 /* EnumDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 244 /* ModuleDeclaration */: // For `namespace N { N; }` + return true; + default: + return false; + } + } + function diagnosticName(nameArg) { + return ts.isString(nameArg) ? ts.unescapeLeadingUnderscores(nameArg) : ts.declarationNameToString(nameArg); + } + function isTypeParameterSymbolDeclaredInContainer(symbol, container) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + if (decl.kind === 150 /* TypeParameter */) { + var parent = ts.isJSDocTemplateTag(decl.parent) ? ts.getJSDocHost(decl.parent) : decl.parent; + if (parent === container) { + return !(ts.isJSDocTemplateTag(decl.parent) && ts.find(decl.parent.parent.tags, ts.isJSDocTypeAlias)); // TODO: GH#18217 + } + } + } + return false; + } + function checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) { + if (!ts.isIdentifier(errorLocation) || errorLocation.escapedText !== name || isTypeReferenceIdentifier(errorLocation) || isInTypeQuery(errorLocation)) { + return false; + } + var container = ts.getThisContainer(errorLocation, /*includeArrowFunctions*/ false); + var location = container; + while (location) { + if (ts.isClassLike(location.parent)) { + var classSymbol = getSymbolOfNode(location.parent); + if (!classSymbol) { + break; + } + // Check to see if a static member exists. + var constructorType = getTypeOfSymbol(classSymbol); + if (getPropertyOfType(constructorType, name)) { + error(errorLocation, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_static_member_1_0, diagnosticName(nameArg), symbolToString(classSymbol)); + return true; + } + // No static member is present. + // Check if we're in an instance method and look for a relevant instance member. + if (location === container && !ts.hasModifier(location, 32 /* Static */)) { + var instanceType = getDeclaredTypeOfSymbol(classSymbol).thisType; // TODO: GH#18217 + if (getPropertyOfType(instanceType, name)) { + error(errorLocation, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0, diagnosticName(nameArg)); + return true; + } + } + } + location = location.parent; + } + return false; + } + function checkAndReportErrorForExtendingInterface(errorLocation) { + var expression = getEntityNameForExtendingInterface(errorLocation); + if (expression && resolveEntityName(expression, 64 /* Interface */, /*ignoreErrors*/ true)) { + error(errorLocation, ts.Diagnostics.Cannot_extend_an_interface_0_Did_you_mean_implements, ts.getTextOfNode(expression)); + return true; + } + return false; + } + /** + * Climbs up parents to an ExpressionWithTypeArguments, and returns its expression, + * but returns undefined if that expression is not an EntityNameExpression. + */ + function getEntityNameForExtendingInterface(node) { + switch (node.kind) { + case 72 /* Identifier */: + case 189 /* PropertyAccessExpression */: + return node.parent ? getEntityNameForExtendingInterface(node.parent) : undefined; + case 211 /* ExpressionWithTypeArguments */: + if (ts.isEntityNameExpression(node.expression)) { + return node.expression; + } + // falls through + default: + return undefined; + } + } + function checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) { + var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJSFile(errorLocation) ? 67220415 /* Value */ : 0); + if (meaning === namespaceMeaning) { + var symbol = resolveSymbol(resolveName(errorLocation, name, 67897832 /* Type */ & ~namespaceMeaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + var parent = errorLocation.parent; + if (symbol) { + if (ts.isQualifiedName(parent)) { + ts.Debug.assert(parent.left === errorLocation, "Should only be resolving left side of qualified name as a namespace"); + var propName = parent.right.escapedText; + var propType = getPropertyOfType(getDeclaredTypeOfSymbol(symbol), propName); + if (propType) { + error(parent, ts.Diagnostics.Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_property_1_in_0_with_0_1, ts.unescapeLeadingUnderscores(name), ts.unescapeLeadingUnderscores(propName)); + return true; + } + } + error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here, ts.unescapeLeadingUnderscores(name)); + return true; + } + } + return false; + } + function checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) { + if (meaning & (67220415 /* Value */ & ~1024 /* NamespaceModule */)) { + if (name === "any" || name === "string" || name === "number" || name === "boolean" || name === "never") { + error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, ts.unescapeLeadingUnderscores(name)); + return true; + } + var symbol = resolveSymbol(resolveName(errorLocation, name, 67897832 /* Type */ & ~67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + if (symbol && !(symbol.flags & 1024 /* NamespaceModule */)) { + var message = (name === "Promise" || name === "Symbol") + ? ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later + : ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here; + error(errorLocation, message, ts.unescapeLeadingUnderscores(name)); + return true; + } + } + return false; + } + function checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) { + if (meaning & (67220415 /* Value */ & ~1024 /* NamespaceModule */ & ~67897832 /* Type */)) { + var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 /* NamespaceModule */ & ~67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + if (symbol) { + error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_value, ts.unescapeLeadingUnderscores(name)); + return true; + } + } + else if (meaning & (67897832 /* Type */ & ~1024 /* NamespaceModule */ & ~67220415 /* Value */)) { + var symbol = resolveSymbol(resolveName(errorLocation, name, (512 /* ValueModule */ | 1024 /* NamespaceModule */) & ~67897832 /* Type */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + if (symbol) { + error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_type, ts.unescapeLeadingUnderscores(name)); + return true; + } + } + return false; + } + function checkResolvedBlockScopedVariable(result, errorLocation) { + ts.Debug.assert(!!(result.flags & 2 /* BlockScopedVariable */ || result.flags & 32 /* Class */ || result.flags & 384 /* Enum */)); + // Block-scoped variables cannot be used before their definition + var declaration = ts.find(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) || ts.isClassLike(d) || (d.kind === 243 /* EnumDeclaration */) || ts.isInJSFile(d) && !!ts.getJSDocEnumTag(d); }); + if (declaration === undefined) + return ts.Debug.fail("Declaration to checkResolvedBlockScopedVariable is undefined"); + if (!(declaration.flags & 4194304 /* Ambient */) && !isBlockScopedNameDeclaredBeforeUse(declaration, errorLocation)) { + var diagnosticMessage = void 0; + var declarationName = ts.declarationNameToString(ts.getNameOfDeclaration(declaration)); + if (result.flags & 2 /* BlockScopedVariable */) { + diagnosticMessage = error(errorLocation, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, declarationName); + } + else if (result.flags & 32 /* Class */) { + diagnosticMessage = error(errorLocation, ts.Diagnostics.Class_0_used_before_its_declaration, declarationName); + } + else if (result.flags & 256 /* RegularEnum */) { + diagnosticMessage = error(errorLocation, ts.Diagnostics.Enum_0_used_before_its_declaration, declarationName); + } + else { + ts.Debug.assert(!!(result.flags & 128 /* ConstEnum */)); + if (compilerOptions.preserveConstEnums) { + diagnosticMessage = error(errorLocation, ts.Diagnostics.Class_0_used_before_its_declaration, declarationName); + } + } + if (diagnosticMessage) { + addRelatedInfo(diagnosticMessage, ts.createDiagnosticForNode(declaration, ts.Diagnostics._0_is_declared_here, declarationName)); + } + } + } + /* Starting from 'initial' node walk up the parent chain until 'stopAt' node is reached. + * If at any point current node is equal to 'parent' node - return true. + * Return false if 'stopAt' node is reached or isFunctionLike(current) === true. + */ + function isSameScopeDescendentOf(initial, parent, stopAt) { + return !!parent && !!ts.findAncestor(initial, function (n) { return n === stopAt || ts.isFunctionLike(n) ? "quit" : n === parent; }); + } + function getAnyImportSyntax(node) { + switch (node.kind) { + case 248 /* ImportEqualsDeclaration */: + return node; + case 250 /* ImportClause */: + return node.parent; + case 251 /* NamespaceImport */: + return node.parent.parent; + case 253 /* ImportSpecifier */: + return node.parent.parent.parent; + default: + return undefined; + } + } + function getDeclarationOfAliasSymbol(symbol) { + return ts.find(symbol.declarations, ts.isAliasSymbolDeclaration); + } + function getTargetOfImportEqualsDeclaration(node, dontResolveAlias) { + if (node.moduleReference.kind === 259 /* ExternalModuleReference */) { + return resolveExternalModuleSymbol(resolveExternalModuleName(node, ts.getExternalModuleImportEqualsDeclarationExpression(node))); + } + return getSymbolOfPartOfRightHandSideOfImportEquals(node.moduleReference, dontResolveAlias); + } + function resolveExportByName(moduleSymbol, name, dontResolveAlias) { + var exportValue = moduleSymbol.exports.get("export=" /* ExportEquals */); + return exportValue + ? getPropertyOfType(getTypeOfSymbol(exportValue), name) + : resolveSymbol(moduleSymbol.exports.get(name), dontResolveAlias); + } + function isSyntacticDefault(node) { + return ((ts.isExportAssignment(node) && !node.isExportEquals) || ts.hasModifier(node, 512 /* Default */) || ts.isExportSpecifier(node)); + } + function canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias) { + if (!allowSyntheticDefaultImports) { + return false; + } + // Declaration files (and ambient modules) + if (!file || file.isDeclarationFile) { + // Definitely cannot have a synthetic default if they have a syntactic default member specified + var defaultExportSymbol = resolveExportByName(moduleSymbol, "default" /* Default */, /*dontResolveAlias*/ true); // Dont resolve alias because we want the immediately exported symbol's declaration + if (defaultExportSymbol && ts.some(defaultExportSymbol.declarations, isSyntacticDefault)) { + return false; + } + // It _might_ still be incorrect to assume there is no __esModule marker on the import at runtime, even if there is no `default` member + // So we check a bit more, + if (resolveExportByName(moduleSymbol, ts.escapeLeadingUnderscores("__esModule"), dontResolveAlias)) { + // If there is an `__esModule` specified in the declaration (meaning someone explicitly added it or wrote it in their code), + // it definitely is a module and does not have a synthetic default + return false; + } + // There are _many_ declaration files not written with esmodules in mind that still get compiled into a format with __esModule set + // Meaning there may be no default at runtime - however to be on the permissive side, we allow access to a synthetic default member + // as there is no marker to indicate if the accompanying JS has `__esModule` or not, or is even native esm + return true; + } + // TypeScript files never have a synthetic default (as they are always emitted with an __esModule marker) _unless_ they contain an export= statement + if (!ts.isSourceFileJS(file)) { + return hasExportAssignmentSymbol(moduleSymbol); + } + // JS files have a synthetic default if they do not contain ES2015+ module syntax (export = is not valid in js) _and_ do not have an __esModule marker + return !file.externalModuleIndicator && !resolveExportByName(moduleSymbol, ts.escapeLeadingUnderscores("__esModule"), dontResolveAlias); + } + function getTargetOfImportClause(node, dontResolveAlias) { + var moduleSymbol = resolveExternalModuleName(node, node.parent.moduleSpecifier); + if (moduleSymbol) { + var exportDefaultSymbol = void 0; + if (ts.isShorthandAmbientModuleSymbol(moduleSymbol)) { + exportDefaultSymbol = moduleSymbol; + } + else { + exportDefaultSymbol = resolveExportByName(moduleSymbol, "default" /* Default */, dontResolveAlias); + } + var file = ts.find(moduleSymbol.declarations, ts.isSourceFile); + var hasSyntheticDefault = canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias); + if (!exportDefaultSymbol && !hasSyntheticDefault) { + error(node.name, ts.Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol)); + } + else if (hasSyntheticDefault) { + // per emit behavior, a synthetic default overrides a "real" .default member if `__esModule` is not present + return resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias); + } + return exportDefaultSymbol; + } + } + function getTargetOfNamespaceImport(node, dontResolveAlias) { + var moduleSpecifier = node.parent.parent.moduleSpecifier; + return resolveESModuleSymbol(resolveExternalModuleName(node, moduleSpecifier), moduleSpecifier, dontResolveAlias); + } + // This function creates a synthetic symbol that combines the value side of one symbol with the + // type/namespace side of another symbol. Consider this example: + // + // declare module graphics { + // interface Point { + // x: number; + // y: number; + // } + // } + // declare var graphics: { + // Point: new (x: number, y: number) => graphics.Point; + // } + // declare module "graphics" { + // export = graphics; + // } + // + // An 'import { Point } from "graphics"' needs to create a symbol that combines the value side 'Point' + // property with the type/namespace side interface 'Point'. + function combineValueAndTypeSymbols(valueSymbol, typeSymbol) { + if (valueSymbol === unknownSymbol && typeSymbol === unknownSymbol) { + return unknownSymbol; + } + if (valueSymbol.flags & (67897832 /* Type */ | 1920 /* Namespace */)) { + return valueSymbol; + } + var result = createSymbol(valueSymbol.flags | typeSymbol.flags, valueSymbol.escapedName); + result.declarations = ts.deduplicate(ts.concatenate(valueSymbol.declarations, typeSymbol.declarations), ts.equateValues); + result.parent = valueSymbol.parent || typeSymbol.parent; + if (valueSymbol.valueDeclaration) + result.valueDeclaration = valueSymbol.valueDeclaration; + if (typeSymbol.members) + result.members = typeSymbol.members; + if (valueSymbol.exports) + result.exports = valueSymbol.exports; + return result; + } + function getExportOfModule(symbol, name, dontResolveAlias) { + if (symbol.flags & 1536 /* Module */) { + return resolveSymbol(getExportsOfSymbol(symbol).get(name), dontResolveAlias); + } + } + function getPropertyOfVariable(symbol, name) { + if (symbol.flags & 3 /* Variable */) { + var typeAnnotation = symbol.valueDeclaration.type; + if (typeAnnotation) { + return resolveSymbol(getPropertyOfType(getTypeFromTypeNode(typeAnnotation), name)); + } + } + } + function getExternalModuleMember(node, specifier, dontResolveAlias) { + if (dontResolveAlias === void 0) { dontResolveAlias = false; } + var moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier); // TODO: GH#18217 + var targetSymbol = resolveESModuleSymbol(moduleSymbol, node.moduleSpecifier, dontResolveAlias); + if (targetSymbol) { + var name = specifier.propertyName || specifier.name; + if (name.escapedText) { + if (ts.isShorthandAmbientModuleSymbol(moduleSymbol)) { + return moduleSymbol; + } + var symbolFromVariable = void 0; + // First check if module was specified with "export=". If so, get the member from the resolved type + if (moduleSymbol && moduleSymbol.exports && moduleSymbol.exports.get("export=" /* ExportEquals */)) { + symbolFromVariable = getPropertyOfType(getTypeOfSymbol(targetSymbol), name.escapedText); + } + else { + symbolFromVariable = getPropertyOfVariable(targetSymbol, name.escapedText); + } + // if symbolFromVariable is export - get its final target + symbolFromVariable = resolveSymbol(symbolFromVariable, dontResolveAlias); + var symbolFromModule = getExportOfModule(targetSymbol, name.escapedText, dontResolveAlias); + // If the export member we're looking for is default, and there is no real default but allowSyntheticDefaultImports is on, return the entire module as the default + if (!symbolFromModule && allowSyntheticDefaultImports && name.escapedText === "default" /* Default */) { + symbolFromModule = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias); + } + var symbol = symbolFromModule && symbolFromVariable && symbolFromModule !== symbolFromVariable ? + combineValueAndTypeSymbols(symbolFromVariable, symbolFromModule) : + symbolFromModule || symbolFromVariable; + if (!symbol) { + var moduleName = getFullyQualifiedName(moduleSymbol, node); + var declarationName = ts.declarationNameToString(name); + var suggestion = getSuggestedSymbolForNonexistentModule(name, targetSymbol); + if (suggestion !== undefined) { + var suggestionName = symbolToString(suggestion); + var diagnostic = error(name, ts.Diagnostics.Module_0_has_no_exported_member_1_Did_you_mean_2, moduleName, declarationName, suggestionName); + if (suggestion.valueDeclaration) { + addRelatedInfo(diagnostic, ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestionName)); + } + } + else { + error(name, ts.Diagnostics.Module_0_has_no_exported_member_1, moduleName, declarationName); + } + } + return symbol; + } + } + } + function getTargetOfImportSpecifier(node, dontResolveAlias) { + return getExternalModuleMember(node.parent.parent.parent, node, dontResolveAlias); + } + function getTargetOfNamespaceExportDeclaration(node, dontResolveAlias) { + return resolveExternalModuleSymbol(node.parent.symbol, dontResolveAlias); + } + function getTargetOfExportSpecifier(node, meaning, dontResolveAlias) { + return node.parent.parent.moduleSpecifier ? + getExternalModuleMember(node.parent.parent, node, dontResolveAlias) : + resolveEntityName(node.propertyName || node.name, meaning, /*ignoreErrors*/ false, dontResolveAlias); + } + function getTargetOfExportAssignment(node, dontResolveAlias) { + var expression = (ts.isExportAssignment(node) ? node.expression : node.right); + if (ts.isClassExpression(expression)) { + return checkExpression(expression).symbol; + } + var aliasLike = resolveEntityName(expression, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ true, dontResolveAlias); + if (aliasLike) { + return aliasLike; + } + checkExpression(expression); + return getNodeLinks(expression).resolvedSymbol; + } + function getTargetOfAliasDeclaration(node, dontRecursivelyResolve) { + if (dontRecursivelyResolve === void 0) { dontRecursivelyResolve = false; } + switch (node.kind) { + case 248 /* ImportEqualsDeclaration */: + return getTargetOfImportEqualsDeclaration(node, dontRecursivelyResolve); + case 250 /* ImportClause */: + return getTargetOfImportClause(node, dontRecursivelyResolve); + case 251 /* NamespaceImport */: + return getTargetOfNamespaceImport(node, dontRecursivelyResolve); + case 253 /* ImportSpecifier */: + return getTargetOfImportSpecifier(node, dontRecursivelyResolve); + case 257 /* ExportSpecifier */: + return getTargetOfExportSpecifier(node, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */, dontRecursivelyResolve); + case 254 /* ExportAssignment */: + case 204 /* BinaryExpression */: + return getTargetOfExportAssignment(node, dontRecursivelyResolve); + case 247 /* NamespaceExportDeclaration */: + return getTargetOfNamespaceExportDeclaration(node, dontRecursivelyResolve); + default: + return ts.Debug.fail(); + } + } + /** + * Indicates that a symbol is an alias that does not merge with a local declaration. + * OR Is a JSContainer which may merge an alias with a local declaration + */ + function isNonLocalAlias(symbol, excludes) { + if (excludes === void 0) { excludes = 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */; } + if (!symbol) + return false; + return (symbol.flags & (2097152 /* Alias */ | excludes)) === 2097152 /* Alias */ || !!(symbol.flags & 2097152 /* Alias */ && symbol.flags & 67108864 /* Assignment */); + } + function resolveSymbol(symbol, dontResolveAlias) { + return !dontResolveAlias && isNonLocalAlias(symbol) ? resolveAlias(symbol) : symbol; + } + function resolveAlias(symbol) { + ts.Debug.assert((symbol.flags & 2097152 /* Alias */) !== 0, "Should only get Alias here."); + var links = getSymbolLinks(symbol); + if (!links.target) { + links.target = resolvingSymbol; + var node = getDeclarationOfAliasSymbol(symbol); + if (!node) + return ts.Debug.fail(); + var target = getTargetOfAliasDeclaration(node); + if (links.target === resolvingSymbol) { + links.target = target || unknownSymbol; + } + else { + error(node, ts.Diagnostics.Circular_definition_of_import_alias_0, symbolToString(symbol)); + } + } + else if (links.target === resolvingSymbol) { + links.target = unknownSymbol; + } + return links.target; + } + function markExportAsReferenced(node) { + var symbol = getSymbolOfNode(node); + var target = resolveAlias(symbol); + if (target) { + var markAlias = target === unknownSymbol || + ((target.flags & 67220415 /* Value */) && !isConstEnumOrConstEnumOnlyModule(target)); + if (markAlias) { + markAliasSymbolAsReferenced(symbol); + } + } + } + // When an alias symbol is referenced, we need to mark the entity it references as referenced and in turn repeat that until + // we reach a non-alias or an exported entity (which is always considered referenced). We do this by checking the target of + // the alias as an expression (which recursively takes us back here if the target references another alias). + function markAliasSymbolAsReferenced(symbol) { + var links = getSymbolLinks(symbol); + if (!links.referenced) { + links.referenced = true; + var node = getDeclarationOfAliasSymbol(symbol); + if (!node) + return ts.Debug.fail(); + if (node.kind === 254 /* ExportAssignment */) { + // export default + checkExpressionCached(node.expression); + } + else if (node.kind === 257 /* ExportSpecifier */) { + // export { } or export { as foo } + checkExpressionCached(node.propertyName || node.name); + } + else if (ts.isInternalModuleImportEqualsDeclaration(node)) { + // import foo = + checkExpressionCached(node.moduleReference); + } + } + } + // This function is only for imports with entity names + function getSymbolOfPartOfRightHandSideOfImportEquals(entityName, dontResolveAlias) { + // There are three things we might try to look for. In the following examples, + // the search term is enclosed in |...|: + // + // import a = |b|; // Namespace + // import a = |b.c|; // Value, type, namespace + // import a = |b.c|.d; // Namespace + if (entityName.kind === 72 /* Identifier */ && ts.isRightSideOfQualifiedNameOrPropertyAccess(entityName)) { + entityName = entityName.parent; + } + // Check for case 1 and 3 in the above example + if (entityName.kind === 72 /* Identifier */ || entityName.parent.kind === 148 /* QualifiedName */) { + return resolveEntityName(entityName, 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); + } + else { + // Case 2 in above example + // entityName.kind could be a QualifiedName or a Missing identifier + ts.Debug.assert(entityName.parent.kind === 248 /* ImportEqualsDeclaration */); + return resolveEntityName(entityName, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); + } + } + function getFullyQualifiedName(symbol, containingLocation) { + return symbol.parent ? getFullyQualifiedName(symbol.parent, containingLocation) + "." + symbolToString(symbol) : symbolToString(symbol, containingLocation, /*meaning*/ undefined, 16 /* DoNotIncludeSymbolChain */ | 4 /* AllowAnyNodeKind */); + } + /** + * Resolves a qualified name and any involved aliases. + */ + function resolveEntityName(name, meaning, ignoreErrors, dontResolveAlias, location) { + if (ts.nodeIsMissing(name)) { + return undefined; + } + var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJSFile(name) ? meaning & 67220415 /* Value */ : 0); + var symbol; + if (name.kind === 72 /* Identifier */) { + var message = meaning === namespaceMeaning ? ts.Diagnostics.Cannot_find_namespace_0 : getCannotFindNameDiagnosticForName(getFirstIdentifier(name).escapedText); + var symbolFromJSPrototype = ts.isInJSFile(name) ? resolveEntityNameFromAssignmentDeclaration(name, meaning) : undefined; + symbol = resolveName(location || name, name.escapedText, meaning, ignoreErrors || symbolFromJSPrototype ? undefined : message, name, /*isUse*/ true); + if (!symbol) { + return symbolFromJSPrototype; + } + } + else if (name.kind === 148 /* QualifiedName */ || name.kind === 189 /* PropertyAccessExpression */) { + var left = name.kind === 148 /* QualifiedName */ ? name.left : name.expression; + var right = name.kind === 148 /* QualifiedName */ ? name.right : name.name; + var namespace = resolveEntityName(left, namespaceMeaning, ignoreErrors, /*dontResolveAlias*/ false, location); + if (!namespace || ts.nodeIsMissing(right)) { + return undefined; + } + else if (namespace === unknownSymbol) { + return namespace; + } + if (ts.isInJSFile(name)) { + if (namespace.valueDeclaration && + ts.isVariableDeclaration(namespace.valueDeclaration) && + namespace.valueDeclaration.initializer && + isCommonJsRequire(namespace.valueDeclaration.initializer)) { + var moduleName = namespace.valueDeclaration.initializer.arguments[0]; + var moduleSym = resolveExternalModuleName(moduleName, moduleName); + if (moduleSym) { + var resolvedModuleSymbol = resolveExternalModuleSymbol(moduleSym); + if (resolvedModuleSymbol) { + namespace = resolvedModuleSymbol; + } + } + } + } + symbol = getSymbol(getExportsOfSymbol(namespace), right.escapedText, meaning); + if (!symbol) { + if (!ignoreErrors) { + error(right, ts.Diagnostics.Namespace_0_has_no_exported_member_1, getFullyQualifiedName(namespace), ts.declarationNameToString(right)); + } + return undefined; + } + } + else { + throw ts.Debug.assertNever(name, "Unknown entity name kind."); + } + ts.Debug.assert((ts.getCheckFlags(symbol) & 1 /* Instantiated */) === 0, "Should never get an instantiated symbol here."); + return (symbol.flags & meaning) || dontResolveAlias ? symbol : resolveAlias(symbol); + } + /** + * 1. For prototype-property methods like `A.prototype.m = function () ...`, try to resolve names in the scope of `A` too. + * Note that prototype-property assignment to locations outside the current file (eg globals) doesn't work, so + * name resolution won't work either. + * 2. For property assignments like `{ x: function f () { } }`, try to resolve names in the scope of `f` too. + */ + function resolveEntityNameFromAssignmentDeclaration(name, meaning) { + if (isJSDocTypeReference(name.parent)) { + var secondaryLocation = getAssignmentDeclarationLocation(name.parent); + if (secondaryLocation) { + return resolveName(secondaryLocation, name.escapedText, meaning, /*nameNotFoundMessage*/ undefined, name, /*isUse*/ true); + } + } + } + function getAssignmentDeclarationLocation(node) { + var typeAlias = ts.findAncestor(node, function (node) { return !(ts.isJSDocNode(node) || node.flags & 2097152 /* JSDoc */) ? "quit" : ts.isJSDocTypeAlias(node); }); + if (typeAlias) { + return; + } + var host = ts.getJSDocHost(node); + if (ts.isExpressionStatement(host) && + ts.isBinaryExpression(host.expression) && + ts.getAssignmentDeclarationKind(host.expression) === 3 /* PrototypeProperty */) { + // X.prototype.m = /** @param {K} p */ function () { } <-- look for K on X's declaration + var symbol = getSymbolOfNode(host.expression.left); + if (symbol) { + return getDeclarationOfJSPrototypeContainer(symbol); + } + } + if ((ts.isObjectLiteralMethod(host) || ts.isPropertyAssignment(host)) && + ts.isBinaryExpression(host.parent.parent) && + ts.getAssignmentDeclarationKind(host.parent.parent) === 6 /* Prototype */) { + // X.prototype = { /** @param {K} p */m() { } } <-- look for K on X's declaration + var symbol = getSymbolOfNode(host.parent.parent.left); + if (symbol) { + return getDeclarationOfJSPrototypeContainer(symbol); + } + } + var sig = ts.getHostSignatureFromJSDocHost(host); + if (sig) { + var symbol = getSymbolOfNode(sig); + return symbol && symbol.valueDeclaration; + } + } + function getDeclarationOfJSPrototypeContainer(symbol) { + var decl = symbol.parent.valueDeclaration; + if (!decl) { + return undefined; + } + var initializer = ts.isAssignmentDeclaration(decl) ? ts.getAssignedExpandoInitializer(decl) : + ts.hasOnlyExpressionInitializer(decl) ? ts.getDeclaredExpandoInitializer(decl) : + undefined; + return initializer || decl; + } + function resolveExternalModuleName(location, moduleReferenceExpression, ignoreErrors) { + return resolveExternalModuleNameWorker(location, moduleReferenceExpression, ignoreErrors ? undefined : ts.Diagnostics.Cannot_find_module_0); + } + function resolveExternalModuleNameWorker(location, moduleReferenceExpression, moduleNotFoundError, isForAugmentation) { + if (isForAugmentation === void 0) { isForAugmentation = false; } + return ts.isStringLiteralLike(moduleReferenceExpression) + ? resolveExternalModule(location, moduleReferenceExpression.text, moduleNotFoundError, moduleReferenceExpression, isForAugmentation) + : undefined; + } + function resolveExternalModule(location, moduleReference, moduleNotFoundError, errorNode, isForAugmentation) { + if (isForAugmentation === void 0) { isForAugmentation = false; } + if (moduleReference === undefined) { + return; + } + if (ts.startsWith(moduleReference, "@types/")) { + var diag = ts.Diagnostics.Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1; + var withoutAtTypePrefix = ts.removePrefix(moduleReference, "@types/"); + error(errorNode, diag, withoutAtTypePrefix, moduleReference); + } + var ambientModule = tryFindAmbientModule(moduleReference, /*withAugmentations*/ true); + if (ambientModule) { + return ambientModule; + } + var currentSourceFile = ts.getSourceFileOfNode(location); + var resolvedModule = ts.getResolvedModule(currentSourceFile, moduleReference); // TODO: GH#18217 + var resolutionDiagnostic = resolvedModule && ts.getResolutionDiagnostic(compilerOptions, resolvedModule); + var sourceFile = resolvedModule && !resolutionDiagnostic && host.getSourceFile(resolvedModule.resolvedFileName); + if (sourceFile) { + if (sourceFile.symbol) { + if (resolvedModule.isExternalLibraryImport && !ts.resolutionExtensionIsTSOrJson(resolvedModule.extension)) { + errorOnImplicitAnyModule(/*isError*/ false, errorNode, resolvedModule, moduleReference); + } + // merged symbol is module declaration symbol combined with all augmentations + return getMergedSymbol(sourceFile.symbol); + } + if (moduleNotFoundError) { + // report errors only if it was requested + error(errorNode, ts.Diagnostics.File_0_is_not_a_module, sourceFile.fileName); + } + return undefined; + } + if (patternAmbientModules) { + var pattern = ts.findBestPatternMatch(patternAmbientModules, function (_) { return _.pattern; }, moduleReference); + if (pattern) { + return getMergedSymbol(pattern.symbol); + } + } + // May be an untyped module. If so, ignore resolutionDiagnostic. + if (resolvedModule && !ts.resolutionExtensionIsTSOrJson(resolvedModule.extension) && resolutionDiagnostic === undefined || resolutionDiagnostic === ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type) { + if (isForAugmentation) { + var diag = ts.Diagnostics.Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented; + error(errorNode, diag, moduleReference, resolvedModule.resolvedFileName); + } + else { + errorOnImplicitAnyModule(/*isError*/ noImplicitAny && !!moduleNotFoundError, errorNode, resolvedModule, moduleReference); + } + // Failed imports and untyped modules are both treated in an untyped manner; only difference is whether we give a diagnostic first. + return undefined; + } + if (moduleNotFoundError) { + // For relative paths, see if this was possibly a projectReference redirect + if (ts.pathIsRelative(moduleReference)) { + var sourceFile_1 = ts.getSourceFileOfNode(location); + var redirects = sourceFile_1.redirectedReferences; + if (redirects) { + var normalizedTargetPath = ts.getNormalizedAbsolutePath(moduleReference, ts.getDirectoryPath(sourceFile_1.fileName)); + for (var _i = 0, _a = [".ts" /* Ts */, ".tsx" /* Tsx */]; _i < _a.length; _i++) { + var ext = _a[_i]; + var probePath = normalizedTargetPath + ext; + if (redirects.indexOf(probePath) >= 0) { + error(errorNode, ts.Diagnostics.Output_file_0_has_not_been_built_from_source_file_1, moduleReference, probePath); + return undefined; + } + } + } + } + if (resolutionDiagnostic) { + error(errorNode, resolutionDiagnostic, moduleReference, resolvedModule.resolvedFileName); + } + else { + var tsExtension = ts.tryExtractTSExtension(moduleReference); + if (tsExtension) { + var diag = ts.Diagnostics.An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead; + error(errorNode, diag, tsExtension, ts.removeExtension(moduleReference, tsExtension)); + } + else if (!compilerOptions.resolveJsonModule && + ts.fileExtensionIs(moduleReference, ".json" /* Json */) && + ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs && + ts.hasJsonModuleEmitEnabled(compilerOptions)) { + error(errorNode, ts.Diagnostics.Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension, moduleReference); + } + else { + error(errorNode, moduleNotFoundError, moduleReference); + } + } + } + return undefined; + } + function errorOnImplicitAnyModule(isError, errorNode, _a, moduleReference) { + var packageId = _a.packageId, resolvedFileName = _a.resolvedFileName; + var errorInfo = !ts.isExternalModuleNameRelative(moduleReference) && packageId + ? typesPackageExists(packageId.name) + ? ts.chainDiagnosticMessages( + /*details*/ undefined, ts.Diagnostics.If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1, packageId.name, ts.mangleScopedPackageName(packageId.name)) + : ts.chainDiagnosticMessages( + /*details*/ undefined, ts.Diagnostics.Try_npm_install_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, moduleReference, ts.mangleScopedPackageName(packageId.name)) + : undefined; + errorOrSuggestion(isError, errorNode, ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type, moduleReference, resolvedFileName)); + } + function typesPackageExists(packageName) { + return getPackagesSet().has(ts.getTypesPackageName(packageName)); + } + function resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) { + if (moduleSymbol) { + var exportEquals = resolveSymbol(moduleSymbol.exports.get("export=" /* ExportEquals */), dontResolveAlias); + var exported = getCommonJsExportEquals(exportEquals, moduleSymbol); + return getMergedSymbol(exported) || moduleSymbol; + } + return undefined; + } + function getCommonJsExportEquals(exported, moduleSymbol) { + if (!exported || exported === unknownSymbol || exported === moduleSymbol || moduleSymbol.exports.size === 1 || exported.flags & 2097152 /* Alias */) { + return exported; + } + var merged = cloneSymbol(exported); + if (merged.exports === undefined) { + merged.flags = merged.flags | 512 /* ValueModule */; + merged.exports = ts.createSymbolTable(); + } + moduleSymbol.exports.forEach(function (s, name) { + if (name === "export=" /* ExportEquals */) + return; + merged.exports.set(name, merged.exports.has(name) ? mergeSymbol(merged.exports.get(name), s) : s); + }); + return merged; + } + // An external module with an 'export =' declaration may be referenced as an ES6 module provided the 'export =' + // references a symbol that is at least declared as a module or a variable. The target of the 'export =' may + // combine other declarations with the module or variable (e.g. a class/module, function/module, interface/variable). + function resolveESModuleSymbol(moduleSymbol, referencingLocation, dontResolveAlias) { + var symbol = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias); + if (!dontResolveAlias && symbol) { + if (!(symbol.flags & (1536 /* Module */ | 3 /* Variable */)) && !ts.getDeclarationOfKind(symbol, 279 /* SourceFile */)) { + error(referencingLocation, ts.Diagnostics.Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct, symbolToString(moduleSymbol)); + return symbol; + } + if (compilerOptions.esModuleInterop) { + var referenceParent = referencingLocation.parent; + if ((ts.isImportDeclaration(referenceParent) && ts.getNamespaceDeclarationNode(referenceParent)) || + ts.isImportCall(referenceParent)) { + var type = getTypeOfSymbol(symbol); + var sigs = getSignaturesOfStructuredType(type, 0 /* Call */); + if (!sigs || !sigs.length) { + sigs = getSignaturesOfStructuredType(type, 1 /* Construct */); + } + if (sigs && sigs.length) { + var moduleType = getTypeWithSyntheticDefaultImportType(type, symbol, moduleSymbol); + // Create a new symbol which has the module's type less the call and construct signatures + var result = createSymbol(symbol.flags, symbol.escapedName); + result.declarations = symbol.declarations ? symbol.declarations.slice() : []; + result.parent = symbol.parent; + result.target = symbol; + result.originatingImport = referenceParent; + if (symbol.valueDeclaration) + result.valueDeclaration = symbol.valueDeclaration; + if (symbol.constEnumOnlyModule) + result.constEnumOnlyModule = true; + if (symbol.members) + result.members = ts.cloneMap(symbol.members); + if (symbol.exports) + result.exports = ts.cloneMap(symbol.exports); + var resolvedModuleType = resolveStructuredTypeMembers(moduleType); // Should already be resolved from the signature checks above + result.type = createAnonymousType(result, resolvedModuleType.members, ts.emptyArray, ts.emptyArray, resolvedModuleType.stringIndexInfo, resolvedModuleType.numberIndexInfo); + return result; + } + } + } + } + return symbol; + } + function hasExportAssignmentSymbol(moduleSymbol) { + return moduleSymbol.exports.get("export=" /* ExportEquals */) !== undefined; + } + function getExportsOfModuleAsArray(moduleSymbol) { + return symbolsToArray(getExportsOfModule(moduleSymbol)); + } + function getExportsAndPropertiesOfModule(moduleSymbol) { + var exports = getExportsOfModuleAsArray(moduleSymbol); + var exportEquals = resolveExternalModuleSymbol(moduleSymbol); + if (exportEquals !== moduleSymbol) { + ts.addRange(exports, getPropertiesOfType(getTypeOfSymbol(exportEquals))); + } + return exports; + } + function tryGetMemberInModuleExports(memberName, moduleSymbol) { + var symbolTable = getExportsOfModule(moduleSymbol); + if (symbolTable) { + return symbolTable.get(memberName); + } + } + function tryGetMemberInModuleExportsAndProperties(memberName, moduleSymbol) { + var symbol = tryGetMemberInModuleExports(memberName, moduleSymbol); + if (symbol) { + return symbol; + } + var exportEquals = resolveExternalModuleSymbol(moduleSymbol); + if (exportEquals === moduleSymbol) { + return undefined; + } + var type = getTypeOfSymbol(exportEquals); + return type.flags & 131068 /* Primitive */ ? undefined : getPropertyOfType(type, memberName); + } + function getExportsOfSymbol(symbol) { + return symbol.flags & 32 /* Class */ ? getResolvedMembersOrExportsOfSymbol(symbol, "resolvedExports" /* resolvedExports */) : + symbol.flags & 1536 /* Module */ ? getExportsOfModule(symbol) : + symbol.exports || emptySymbols; + } + function getExportsOfModule(moduleSymbol) { + var links = getSymbolLinks(moduleSymbol); + return links.resolvedExports || (links.resolvedExports = getExportsOfModuleWorker(moduleSymbol)); + } + /** + * Extends one symbol table with another while collecting information on name collisions for error message generation into the `lookupTable` argument + * Not passing `lookupTable` and `exportNode` disables this collection, and just extends the tables + */ + function extendExportSymbols(target, source, lookupTable, exportNode) { + if (!source) + return; + source.forEach(function (sourceSymbol, id) { + if (id === "default" /* Default */) + return; + var targetSymbol = target.get(id); + if (!targetSymbol) { + target.set(id, sourceSymbol); + if (lookupTable && exportNode) { + lookupTable.set(id, { + specifierText: ts.getTextOfNode(exportNode.moduleSpecifier) + }); + } + } + else if (lookupTable && exportNode && targetSymbol && resolveSymbol(targetSymbol) !== resolveSymbol(sourceSymbol)) { + var collisionTracker = lookupTable.get(id); + if (!collisionTracker.exportsWithDuplicate) { + collisionTracker.exportsWithDuplicate = [exportNode]; + } + else { + collisionTracker.exportsWithDuplicate.push(exportNode); + } + } + }); + } + function getExportsOfModuleWorker(moduleSymbol) { + var visitedSymbols = []; + // A module defined by an 'export=' consists of one export that needs to be resolved + moduleSymbol = resolveExternalModuleSymbol(moduleSymbol); + return visit(moduleSymbol) || emptySymbols; + // The ES6 spec permits export * declarations in a module to circularly reference the module itself. For example, + // module 'a' can 'export * from "b"' and 'b' can 'export * from "a"' without error. + function visit(symbol) { + if (!(symbol && symbol.exports && ts.pushIfUnique(visitedSymbols, symbol))) { + return; + } + var symbols = ts.cloneMap(symbol.exports); + // All export * declarations are collected in an __export symbol by the binder + var exportStars = symbol.exports.get("__export" /* ExportStar */); + if (exportStars) { + var nestedSymbols = ts.createSymbolTable(); + var lookupTable_1 = ts.createMap(); + for (var _i = 0, _a = exportStars.declarations; _i < _a.length; _i++) { + var node = _a[_i]; + var resolvedModule = resolveExternalModuleName(node, node.moduleSpecifier); + var exportedSymbols = visit(resolvedModule); + extendExportSymbols(nestedSymbols, exportedSymbols, lookupTable_1, node); + } + lookupTable_1.forEach(function (_a, id) { + var exportsWithDuplicate = _a.exportsWithDuplicate; + // It's not an error if the file with multiple `export *`s with duplicate names exports a member with that name itself + if (id === "export=" || !(exportsWithDuplicate && exportsWithDuplicate.length) || symbols.has(id)) { + return; + } + for (var _i = 0, exportsWithDuplicate_1 = exportsWithDuplicate; _i < exportsWithDuplicate_1.length; _i++) { + var node = exportsWithDuplicate_1[_i]; + diagnostics.add(ts.createDiagnosticForNode(node, ts.Diagnostics.Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambiguity, lookupTable_1.get(id).specifierText, ts.unescapeLeadingUnderscores(id))); + } + }); + extendExportSymbols(symbols, nestedSymbols); + } + return symbols; + } + } + function getMergedSymbol(symbol) { + var merged; + return symbol && symbol.mergeId && (merged = mergedSymbols[symbol.mergeId]) ? merged : symbol; + } + function getSymbolOfNode(node) { + return getMergedSymbol(node.symbol && getLateBoundSymbol(node.symbol)); + } + function getParentOfSymbol(symbol) { + return getMergedSymbol(symbol.parent && getLateBoundSymbol(symbol.parent)); + } + function getAlternativeContainingModules(symbol, enclosingDeclaration) { + var containingFile = ts.getSourceFileOfNode(enclosingDeclaration); + var id = "" + getNodeId(containingFile); + var links = getSymbolLinks(symbol); + var results; + if (links.extendedContainersByFile && (results = links.extendedContainersByFile.get(id))) { + return results; + } + if (containingFile && containingFile.imports) { + // Try to make an import using an import already in the enclosing file, if possible + for (var _i = 0, _a = containingFile.imports; _i < _a.length; _i++) { + var importRef = _a[_i]; + if (ts.nodeIsSynthesized(importRef)) + continue; // Synthetic names can't be resolved by `resolveExternalModuleName` - they'll cause a debug assert if they error + var resolvedModule = resolveExternalModuleName(enclosingDeclaration, importRef, /*ignoreErrors*/ true); + if (!resolvedModule) + continue; + var ref = getAliasForSymbolInContainer(resolvedModule, symbol); + if (!ref) + continue; + results = ts.append(results, resolvedModule); + } + if (ts.length(results)) { + (links.extendedContainersByFile || (links.extendedContainersByFile = ts.createMap())).set(id, results); + return results; + } + } + if (links.extendedContainers) { + return links.extendedContainers; + } + // No results from files already being imported by this file - expand search (expensive, but not location-specific, so cached) + var otherFiles = host.getSourceFiles(); + for (var _b = 0, otherFiles_1 = otherFiles; _b < otherFiles_1.length; _b++) { + var file = otherFiles_1[_b]; + if (!ts.isExternalModule(file)) + continue; + var sym = getSymbolOfNode(file); + var ref = getAliasForSymbolInContainer(sym, symbol); + if (!ref) + continue; + results = ts.append(results, sym); + } + return links.extendedContainers = results || ts.emptyArray; + } + /** + * Attempts to find the symbol corresponding to the container a symbol is in - usually this + * is just its' `.parent`, but for locals, this value is `undefined` + */ + function getContainersOfSymbol(symbol, enclosingDeclaration) { + var container = getParentOfSymbol(symbol); + if (container) { + var additionalContainers = ts.mapDefined(container.declarations, fileSymbolIfFileSymbolExportEqualsContainer); + var reexportContainers = enclosingDeclaration && getAlternativeContainingModules(symbol, enclosingDeclaration); + if (enclosingDeclaration && getAccessibleSymbolChain(container, enclosingDeclaration, 1920 /* Namespace */, /*externalOnly*/ false)) { + return ts.concatenate(ts.concatenate([container], additionalContainers), reexportContainers); // This order expresses a preference for the real container if it is in scope + } + var res = ts.append(additionalContainers, container); + return ts.concatenate(res, reexportContainers); + } + var candidates = ts.mapDefined(symbol.declarations, function (d) { return !ts.isAmbientModule(d) && d.parent && hasNonGlobalAugmentationExternalModuleSymbol(d.parent) ? getSymbolOfNode(d.parent) : undefined; }); + if (!ts.length(candidates)) { + return undefined; + } + return ts.mapDefined(candidates, function (candidate) { return getAliasForSymbolInContainer(candidate, symbol) ? candidate : undefined; }); + function fileSymbolIfFileSymbolExportEqualsContainer(d) { + var fileSymbol = getExternalModuleContainer(d); + var exported = fileSymbol && fileSymbol.exports && fileSymbol.exports.get("export=" /* ExportEquals */); + return resolveSymbol(exported) === resolveSymbol(container) ? fileSymbol : undefined; + } + } + function getAliasForSymbolInContainer(container, symbol) { + if (container === getParentOfSymbol(symbol)) { + // fast path, `symbol` is either already the alias or isn't aliased + return symbol; + } + var exports = getExportsOfSymbol(container); + var quick = exports.get(symbol.escapedName); + if (quick && symbolRefersToTarget(quick)) { + return quick; + } + return ts.forEachEntry(exports, function (exported) { + if (symbolRefersToTarget(exported)) { + return exported; + } + }); + function symbolRefersToTarget(s) { + if (s === symbol || resolveSymbol(s) === symbol || resolveSymbol(s) === resolveSymbol(symbol)) { + return s; + } + } + } + function getExportSymbolOfValueSymbolIfExported(symbol) { + return getMergedSymbol(symbol && (symbol.flags & 1048576 /* ExportValue */) !== 0 ? symbol.exportSymbol : symbol); + } + function symbolIsValue(symbol) { + return !!(symbol.flags & 67220415 /* Value */ || symbol.flags & 2097152 /* Alias */ && resolveAlias(symbol).flags & 67220415 /* Value */); + } + function findConstructorDeclaration(node) { + var members = node.members; + for (var _i = 0, members_2 = members; _i < members_2.length; _i++) { + var member = members_2[_i]; + if (member.kind === 157 /* Constructor */ && ts.nodeIsPresent(member.body)) { + return member; + } + } + } + function createType(flags) { + var result = new Type(checker, flags); + typeCount++; + result.id = typeCount; + return result; + } + function createIntrinsicType(kind, intrinsicName) { + var type = createType(kind); + type.intrinsicName = intrinsicName; + return type; + } + function createBooleanType(trueFalseTypes) { + var type = getUnionType(trueFalseTypes); + type.flags |= 16 /* Boolean */; + type.intrinsicName = "boolean"; + return type; + } + function createObjectType(objectFlags, symbol) { + var type = createType(524288 /* Object */); + type.objectFlags = objectFlags; + type.symbol = symbol; + type.members = undefined; + type.properties = undefined; + type.callSignatures = undefined; + type.constructSignatures = undefined; + type.stringIndexInfo = undefined; + type.numberIndexInfo = undefined; + return type; + } + function createTypeofType() { + return getUnionType(ts.arrayFrom(typeofEQFacts.keys(), getLiteralType)); + } + // A reserved member name starts with two underscores, but the third character cannot be an underscore + // or the @ symbol. A third underscore indicates an escaped form of an identifer that started + // with at least two underscores. The @ character indicates that the name is denoted by a well known ES + // Symbol instance. + function isReservedMemberName(name) { + return name.charCodeAt(0) === 95 /* _ */ && + name.charCodeAt(1) === 95 /* _ */ && + name.charCodeAt(2) !== 95 /* _ */ && + name.charCodeAt(2) !== 64 /* at */; + } + function getNamedMembers(members) { + var result; + members.forEach(function (symbol, id) { + if (!isReservedMemberName(id) && symbolIsValue(symbol)) { + (result || (result = [])).push(symbol); + } + }); + return result || ts.emptyArray; + } + function setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo) { + type.members = members; + type.properties = members === emptySymbols ? ts.emptyArray : getNamedMembers(members); + type.callSignatures = callSignatures; + type.constructSignatures = constructSignatures; + type.stringIndexInfo = stringIndexInfo; + type.numberIndexInfo = numberIndexInfo; + return type; + } + function createAnonymousType(symbol, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo) { + return setStructuredTypeMembers(createObjectType(16 /* Anonymous */, symbol), members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + } + function forEachSymbolTableInScope(enclosingDeclaration, callback) { + var result; + for (var location = enclosingDeclaration; location; location = location.parent) { + // Locals of a source file are not in scope (because they get merged into the global symbol table) + if (location.locals && !isGlobalSourceFile(location)) { + if (result = callback(location.locals)) { + return result; + } + } + switch (location.kind) { + case 279 /* SourceFile */: + if (!ts.isExternalOrCommonJsModule(location)) { + break; + } + // falls through + case 244 /* ModuleDeclaration */: + if (result = callback(getSymbolOfNode(location).exports)) { + return result; + } + break; + } + } + return callback(globals); + } + function getQualifiedLeftMeaning(rightMeaning) { + // If we are looking in value space, the parent meaning is value, other wise it is namespace + return rightMeaning === 67220415 /* Value */ ? 67220415 /* Value */ : 1920 /* Namespace */; + } + function getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, useOnlyExternalAliasing, visitedSymbolTablesMap) { + if (visitedSymbolTablesMap === void 0) { visitedSymbolTablesMap = ts.createMap(); } + if (!(symbol && !isPropertyOrMethodDeclarationSymbol(symbol))) { + return undefined; + } + var id = "" + getSymbolId(symbol); + var visitedSymbolTables = visitedSymbolTablesMap.get(id); + if (!visitedSymbolTables) { + visitedSymbolTablesMap.set(id, visitedSymbolTables = []); + } + return forEachSymbolTableInScope(enclosingDeclaration, getAccessibleSymbolChainFromSymbolTable); + /** + * @param {ignoreQualification} boolean Set when a symbol is being looked for through the exports of another symbol (meaning we have a route to qualify it already) + */ + function getAccessibleSymbolChainFromSymbolTable(symbols, ignoreQualification) { + if (!ts.pushIfUnique(visitedSymbolTables, symbols)) { + return undefined; + } + var result = trySymbolTable(symbols, ignoreQualification); + visitedSymbolTables.pop(); + return result; + } + function canQualifySymbol(symbolFromSymbolTable, meaning) { + // If the symbol is equivalent and doesn't need further qualification, this symbol is accessible + return !needsQualification(symbolFromSymbolTable, enclosingDeclaration, meaning) || + // If symbol needs qualification, make sure that parent is accessible, if it is then this symbol is accessible too + !!getAccessibleSymbolChain(symbolFromSymbolTable.parent, enclosingDeclaration, getQualifiedLeftMeaning(meaning), useOnlyExternalAliasing, visitedSymbolTablesMap); + } + function isAccessible(symbolFromSymbolTable, resolvedAliasSymbol, ignoreQualification) { + return symbol === (resolvedAliasSymbol || symbolFromSymbolTable) && + // if the symbolFromSymbolTable is not external module (it could be if it was determined as ambient external module and would be in globals table) + // and if symbolFromSymbolTable or alias resolution matches the symbol, + // check the symbol can be qualified, it is only then this symbol is accessible + !ts.some(symbolFromSymbolTable.declarations, hasNonGlobalAugmentationExternalModuleSymbol) && + (ignoreQualification || canQualifySymbol(symbolFromSymbolTable, meaning)); + } + function trySymbolTable(symbols, ignoreQualification) { + // If symbol is directly available by its name in the symbol table + if (isAccessible(symbols.get(symbol.escapedName), /*resolvedAliasSymbol*/ undefined, ignoreQualification)) { + return [symbol]; + } + // Check if symbol is any of the alias + return ts.forEachEntry(symbols, function (symbolFromSymbolTable) { + if (symbolFromSymbolTable.flags & 2097152 /* Alias */ + && symbolFromSymbolTable.escapedName !== "export=" /* ExportEquals */ + && symbolFromSymbolTable.escapedName !== "default" /* Default */ + && !(ts.isUMDExportSymbol(symbolFromSymbolTable) && enclosingDeclaration && ts.isExternalModule(ts.getSourceFileOfNode(enclosingDeclaration))) + // If `!useOnlyExternalAliasing`, we can use any type of alias to get the name + && (!useOnlyExternalAliasing || ts.some(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration)) + // While exports are generally considered to be in scope, export-specifier declared symbols are _not_ + // See similar comment in `resolveName` for details + && (ignoreQualification || !ts.getDeclarationOfKind(symbolFromSymbolTable, 257 /* ExportSpecifier */))) { + var resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable); + if (isAccessible(symbolFromSymbolTable, resolvedImportedSymbol, ignoreQualification)) { + return [symbolFromSymbolTable]; + } + // Look in the exported members, if we can find accessibleSymbolChain, symbol is accessible using this chain + // but only if the symbolFromSymbolTable can be qualified + var candidateTable = getExportsOfSymbol(resolvedImportedSymbol); + var accessibleSymbolsFromExports = candidateTable && getAccessibleSymbolChainFromSymbolTable(candidateTable, /*ignoreQualification*/ true); + if (accessibleSymbolsFromExports && canQualifySymbol(symbolFromSymbolTable, getQualifiedLeftMeaning(meaning))) { + return [symbolFromSymbolTable].concat(accessibleSymbolsFromExports); + } + } + if (symbolFromSymbolTable.escapedName === symbol.escapedName && symbolFromSymbolTable.exportSymbol) { + if (isAccessible(getMergedSymbol(symbolFromSymbolTable.exportSymbol), /*aliasSymbol*/ undefined, ignoreQualification)) { + return [symbol]; + } + } + }); + } + } + function needsQualification(symbol, enclosingDeclaration, meaning) { + var qualify = false; + forEachSymbolTableInScope(enclosingDeclaration, function (symbolTable) { + // If symbol of this name is not available in the symbol table we are ok + var symbolFromSymbolTable = getMergedSymbol(symbolTable.get(symbol.escapedName)); + if (!symbolFromSymbolTable) { + // Continue to the next symbol table + return false; + } + // If the symbol with this name is present it should refer to the symbol + if (symbolFromSymbolTable === symbol) { + // No need to qualify + return true; + } + // Qualify if the symbol from symbol table has same meaning as expected + symbolFromSymbolTable = (symbolFromSymbolTable.flags & 2097152 /* Alias */ && !ts.getDeclarationOfKind(symbolFromSymbolTable, 257 /* ExportSpecifier */)) ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable; + if (symbolFromSymbolTable.flags & meaning) { + qualify = true; + return true; + } + // Continue to the next symbol table + return false; + }); + return qualify; + } + function isPropertyOrMethodDeclarationSymbol(symbol) { + if (symbol.declarations && symbol.declarations.length) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + switch (declaration.kind) { + case 154 /* PropertyDeclaration */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + continue; + default: + return false; + } + } + return true; + } + return false; + } + function isTypeSymbolAccessible(typeSymbol, enclosingDeclaration) { + var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67897832 /* Type */, /*shouldComputeAliasesToMakeVisible*/ false); + return access.accessibility === 0 /* Accessible */; + } + function isValueSymbolAccessible(typeSymbol, enclosingDeclaration) { + var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67220415 /* Value */, /*shouldComputeAliasesToMakeVisible*/ false); + return access.accessibility === 0 /* Accessible */; + } + function isAnySymbolAccessible(symbols, enclosingDeclaration, initialSymbol, meaning, shouldComputeAliasesToMakeVisible) { + if (!ts.length(symbols)) + return; + var hadAccessibleChain; + for (var _i = 0, _a = symbols; _i < _a.length; _i++) { + var symbol = _a[_i]; + // Symbol is accessible if it by itself is accessible + var accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, /*useOnlyExternalAliasing*/ false); + if (accessibleSymbolChain) { + hadAccessibleChain = symbol; + var hasAccessibleDeclarations = hasVisibleDeclarations(accessibleSymbolChain[0], shouldComputeAliasesToMakeVisible); + if (hasAccessibleDeclarations) { + return hasAccessibleDeclarations; + } + } + else { + if (ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { + // Any meaning of a module symbol is always accessible via an `import` type + return { + accessibility: 0 /* Accessible */ + }; + } + } + // If we haven't got the accessible symbol, it doesn't mean the symbol is actually inaccessible. + // It could be a qualified symbol and hence verify the path + // e.g.: + // module m { + // export class c { + // } + // } + // const x: typeof m.c + // In the above example when we start with checking if typeof m.c symbol is accessible, + // we are going to see if c can be accessed in scope directly. + // But it can't, hence the accessible is going to be undefined, but that doesn't mean m.c is inaccessible + // It is accessible if the parent m is accessible because then m.c can be accessed through qualification + var containers = getContainersOfSymbol(symbol, enclosingDeclaration); + // If we're trying to reference some object literal in, eg `var a = { x: 1 }`, the symbol for the literal, `__object`, is distinct + // from the symbol of the declaration it is being assigned to. Since we can use the declaration to refer to the literal, however, + // we'd like to make that connection here - potentially causing us to paint the declararation's visibiility, and therefore the literal. + var firstDecl = ts.first(symbol.declarations); + if (!ts.length(containers) && meaning & 67220415 /* Value */ && firstDecl && ts.isObjectLiteralExpression(firstDecl)) { + if (firstDecl.parent && ts.isVariableDeclaration(firstDecl.parent) && firstDecl === firstDecl.parent.initializer) { + containers = [getSymbolOfNode(firstDecl.parent)]; + } + } + var parentResult = isAnySymbolAccessible(containers, enclosingDeclaration, initialSymbol, initialSymbol === symbol ? getQualifiedLeftMeaning(meaning) : meaning, shouldComputeAliasesToMakeVisible); + if (parentResult) { + return parentResult; + } + } + if (hadAccessibleChain) { + return { + accessibility: 1 /* NotAccessible */, + errorSymbolName: symbolToString(initialSymbol, enclosingDeclaration, meaning), + errorModuleName: hadAccessibleChain !== initialSymbol ? symbolToString(hadAccessibleChain, enclosingDeclaration, 1920 /* Namespace */) : undefined, + }; + } + } + /** + * Check if the given symbol in given enclosing declaration is accessible and mark all associated alias to be visible if requested + * + * @param symbol a Symbol to check if accessible + * @param enclosingDeclaration a Node containing reference to the symbol + * @param meaning a SymbolFlags to check if such meaning of the symbol is accessible + * @param shouldComputeAliasToMakeVisible a boolean value to indicate whether to return aliases to be mark visible in case the symbol is accessible + */ + function isSymbolAccessible(symbol, enclosingDeclaration, meaning, shouldComputeAliasesToMakeVisible) { + if (symbol && enclosingDeclaration) { + var result = isAnySymbolAccessible([symbol], enclosingDeclaration, symbol, meaning, shouldComputeAliasesToMakeVisible); + if (result) { + return result; + } + // This could be a symbol that is not exported in the external module + // or it could be a symbol from different external module that is not aliased and hence cannot be named + var symbolExternalModule = ts.forEach(symbol.declarations, getExternalModuleContainer); + if (symbolExternalModule) { + var enclosingExternalModule = getExternalModuleContainer(enclosingDeclaration); + if (symbolExternalModule !== enclosingExternalModule) { + // name from different external module that is not visible + return { + accessibility: 2 /* CannotBeNamed */, + errorSymbolName: symbolToString(symbol, enclosingDeclaration, meaning), + errorModuleName: symbolToString(symbolExternalModule) + }; + } + } + // Just a local name that is not accessible + return { + accessibility: 1 /* NotAccessible */, + errorSymbolName: symbolToString(symbol, enclosingDeclaration, meaning), + }; + } + return { accessibility: 0 /* Accessible */ }; + } + function getExternalModuleContainer(declaration) { + var node = ts.findAncestor(declaration, hasExternalModuleSymbol); + return node && getSymbolOfNode(node); + } + function hasExternalModuleSymbol(declaration) { + return ts.isAmbientModule(declaration) || (declaration.kind === 279 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration)); + } + function hasNonGlobalAugmentationExternalModuleSymbol(declaration) { + return ts.isModuleWithStringLiteralName(declaration) || (declaration.kind === 279 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration)); + } + function hasVisibleDeclarations(symbol, shouldComputeAliasToMakeVisible) { + var aliasesToMakeVisible; + if (!ts.every(symbol.declarations, getIsDeclarationVisible)) { + return undefined; + } + return { accessibility: 0 /* Accessible */, aliasesToMakeVisible: aliasesToMakeVisible }; + function getIsDeclarationVisible(declaration) { + if (!isDeclarationVisible(declaration)) { + // Mark the unexported alias as visible if its parent is visible + // because these kind of aliases can be used to name types in declaration file + var anyImportSyntax = getAnyImportSyntax(declaration); + if (anyImportSyntax && + !ts.hasModifier(anyImportSyntax, 1 /* Export */) && // import clause without export + isDeclarationVisible(anyImportSyntax.parent)) { + return addVisibleAlias(declaration, anyImportSyntax); + } + else if (ts.isVariableDeclaration(declaration) && ts.isVariableStatement(declaration.parent.parent) && + !ts.hasModifier(declaration.parent.parent, 1 /* Export */) && // unexported variable statement + isDeclarationVisible(declaration.parent.parent.parent)) { + return addVisibleAlias(declaration, declaration.parent.parent); + } + else if (ts.isLateVisibilityPaintedStatement(declaration) // unexported top-level statement + && !ts.hasModifier(declaration, 1 /* Export */) + && isDeclarationVisible(declaration.parent)) { + return addVisibleAlias(declaration, declaration); + } + // Declaration is not visible + return false; + } + return true; + } + function addVisibleAlias(declaration, aliasingStatement) { + // In function "buildTypeDisplay" where we decide whether to write type-alias or serialize types, + // we want to just check if type- alias is accessible or not but we don't care about emitting those alias at that time + // since we will do the emitting later in trackSymbol. + if (shouldComputeAliasToMakeVisible) { + getNodeLinks(declaration).isVisible = true; + aliasesToMakeVisible = ts.appendIfUnique(aliasesToMakeVisible, aliasingStatement); + } + return true; + } + } + function isEntityNameVisible(entityName, enclosingDeclaration) { + // get symbol of the first identifier of the entityName + var meaning; + if (entityName.parent.kind === 167 /* TypeQuery */ || + ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent) || + entityName.parent.kind === 149 /* ComputedPropertyName */) { + // Typeof value + meaning = 67220415 /* Value */ | 1048576 /* ExportValue */; + } + else if (entityName.kind === 148 /* QualifiedName */ || entityName.kind === 189 /* PropertyAccessExpression */ || + entityName.parent.kind === 248 /* ImportEqualsDeclaration */) { + // Left identifier from type reference or TypeAlias + // Entity name of the import declaration + meaning = 1920 /* Namespace */; + } + else { + // Type Reference or TypeAlias entity = Identifier + meaning = 67897832 /* Type */; + } + var firstIdentifier = getFirstIdentifier(entityName); + var symbol = resolveName(enclosingDeclaration, firstIdentifier.escapedText, meaning, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); + // Verify if the symbol is accessible + return (symbol && hasVisibleDeclarations(symbol, /*shouldComputeAliasToMakeVisible*/ true)) || { + accessibility: 1 /* NotAccessible */, + errorSymbolName: ts.getTextOfNode(firstIdentifier), + errorNode: firstIdentifier + }; + } + function symbolToString(symbol, enclosingDeclaration, meaning, flags, writer) { + if (flags === void 0) { flags = 4 /* AllowAnyNodeKind */; } + var nodeFlags = 70221824 /* IgnoreErrors */; + if (flags & 2 /* UseOnlyExternalAliasing */) { + nodeFlags |= 128 /* UseOnlyExternalAliasing */; + } + if (flags & 1 /* WriteTypeParametersOrArguments */) { + nodeFlags |= 512 /* WriteTypeParametersInQualifiedName */; + } + if (flags & 8 /* UseAliasDefinedOutsideCurrentScope */) { + nodeFlags |= 16384 /* UseAliasDefinedOutsideCurrentScope */; + } + if (flags & 16 /* DoNotIncludeSymbolChain */) { + nodeFlags |= 134217728 /* DoNotIncludeSymbolChain */; + } + var builder = flags & 4 /* AllowAnyNodeKind */ ? nodeBuilder.symbolToExpression : nodeBuilder.symbolToEntityName; + return writer ? symbolToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(symbolToStringWorker); + function symbolToStringWorker(writer) { + var entity = builder(symbol, meaning, enclosingDeclaration, nodeFlags); // TODO: GH#18217 + var printer = ts.createPrinter({ removeComments: true }); + var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); + printer.writeNode(4 /* Unspecified */, entity, /*sourceFile*/ sourceFile, writer); + return writer; + } + } + function signatureToString(signature, enclosingDeclaration, flags, kind, writer) { + if (flags === void 0) { flags = 0 /* None */; } + return writer ? signatureToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(signatureToStringWorker); + function signatureToStringWorker(writer) { + var sigOutput; + if (flags & 262144 /* WriteArrowStyleSignature */) { + sigOutput = kind === 1 /* Construct */ ? 166 /* ConstructorType */ : 165 /* FunctionType */; + } + else { + sigOutput = kind === 1 /* Construct */ ? 161 /* ConstructSignature */ : 160 /* CallSignature */; + } + var sig = nodeBuilder.signatureToSignatureDeclaration(signature, sigOutput, enclosingDeclaration, toNodeBuilderFlags(flags) | 70221824 /* IgnoreErrors */ | 512 /* WriteTypeParametersInQualifiedName */); + var printer = ts.createPrinter({ removeComments: true, omitTrailingSemicolon: true }); + var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); + printer.writeNode(4 /* Unspecified */, sig, /*sourceFile*/ sourceFile, ts.getTrailingSemicolonOmittingWriter(writer)); // TODO: GH#18217 + return writer; + } + } + function typeToString(type, enclosingDeclaration, flags, writer) { + if (flags === void 0) { flags = 1048576 /* AllowUniqueESSymbolType */ | 16384 /* UseAliasDefinedOutsideCurrentScope */; } + if (writer === void 0) { writer = ts.createTextWriter(""); } + var noTruncation = compilerOptions.noErrorTruncation || flags & 1 /* NoTruncation */; + var typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, toNodeBuilderFlags(flags) | 70221824 /* IgnoreErrors */ | (noTruncation ? 1 /* NoTruncation */ : 0), writer); + if (typeNode === undefined) + return ts.Debug.fail("should always get typenode"); + var options = { removeComments: true }; + var printer = ts.createPrinter(options); + var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); + printer.writeNode(4 /* Unspecified */, typeNode, /*sourceFile*/ sourceFile, writer); + var result = writer.getText(); + var maxLength = noTruncation ? undefined : ts.defaultMaximumTruncationLength * 2; + if (maxLength && result && result.length >= maxLength) { + return result.substr(0, maxLength - "...".length) + "..."; + } + return result; + } + function toNodeBuilderFlags(flags) { + if (flags === void 0) { flags = 0 /* None */; } + return flags & 9469291 /* NodeBuilderFlagsMask */; + } + function createNodeBuilder() { + return { + typeToTypeNode: function (type, enclosingDeclaration, flags, tracker) { + return withContext(enclosingDeclaration, flags, tracker, function (context) { return typeToTypeNodeHelper(type, context); }); + }, + indexInfoToIndexSignatureDeclaration: function (indexInfo, kind, enclosingDeclaration, flags, tracker) { + return withContext(enclosingDeclaration, flags, tracker, function (context) { return indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind, context); }); + }, + signatureToSignatureDeclaration: function (signature, kind, enclosingDeclaration, flags, tracker) { + return withContext(enclosingDeclaration, flags, tracker, function (context) { return signatureToSignatureDeclarationHelper(signature, kind, context); }); + }, + symbolToEntityName: function (symbol, meaning, enclosingDeclaration, flags, tracker) { + return withContext(enclosingDeclaration, flags, tracker, function (context) { return symbolToName(symbol, context, meaning, /*expectsIdentifier*/ false); }); + }, + symbolToExpression: function (symbol, meaning, enclosingDeclaration, flags, tracker) { + return withContext(enclosingDeclaration, flags, tracker, function (context) { return symbolToExpression(symbol, context, meaning); }); + }, + symbolToTypeParameterDeclarations: function (symbol, enclosingDeclaration, flags, tracker) { + return withContext(enclosingDeclaration, flags, tracker, function (context) { return typeParametersToTypeParameterDeclarations(symbol, context); }); + }, + symbolToParameterDeclaration: function (symbol, enclosingDeclaration, flags, tracker) { + return withContext(enclosingDeclaration, flags, tracker, function (context) { return symbolToParameterDeclaration(symbol, context); }); + }, + typeParameterToDeclaration: function (parameter, enclosingDeclaration, flags, tracker) { + return withContext(enclosingDeclaration, flags, tracker, function (context) { return typeParameterToDeclaration(parameter, context); }); + }, + }; + function withContext(enclosingDeclaration, flags, tracker, cb) { + ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8 /* Synthesized */) === 0); + var context = { + enclosingDeclaration: enclosingDeclaration, + flags: flags || 0 /* None */, + // If no full tracker is provided, fake up a dummy one with a basic limited-functionality moduleResolverHost + tracker: tracker && tracker.trackSymbol ? tracker : { trackSymbol: ts.noop, moduleResolverHost: flags & 134217728 /* DoNotIncludeSymbolChain */ ? { + getCommonSourceDirectory: host.getCommonSourceDirectory ? function () { return host.getCommonSourceDirectory(); } : function () { return ""; }, + getSourceFiles: function () { return host.getSourceFiles(); }, + getCurrentDirectory: host.getCurrentDirectory && (function () { return host.getCurrentDirectory(); }) + } : undefined }, + encounteredError: false, + visitedTypes: undefined, + symbolDepth: undefined, + inferTypeParameters: undefined, + approximateLength: 0 + }; + var resultingNode = cb(context); + return context.encounteredError ? undefined : resultingNode; + } + function checkTruncationLength(context) { + if (context.truncating) + return context.truncating; + return context.truncating = !(context.flags & 1 /* NoTruncation */) && context.approximateLength > ts.defaultMaximumTruncationLength; + } + function typeToTypeNodeHelper(type, context) { + if (cancellationToken && cancellationToken.throwIfCancellationRequested) { + cancellationToken.throwIfCancellationRequested(); + } + var inTypeAlias = context.flags & 8388608 /* InTypeAlias */; + context.flags &= ~8388608 /* InTypeAlias */; + if (!type) { + context.encounteredError = true; + return undefined; // TODO: GH#18217 + } + if (type.flags & 1 /* Any */) { + context.approximateLength += 3; + return ts.createKeywordTypeNode(120 /* AnyKeyword */); + } + if (type.flags & 2 /* Unknown */) { + return ts.createKeywordTypeNode(143 /* UnknownKeyword */); + } + if (type.flags & 4 /* String */) { + context.approximateLength += 6; + return ts.createKeywordTypeNode(138 /* StringKeyword */); + } + if (type.flags & 8 /* Number */) { + context.approximateLength += 6; + return ts.createKeywordTypeNode(135 /* NumberKeyword */); + } + if (type.flags & 64 /* BigInt */) { + context.approximateLength += 6; + return ts.createKeywordTypeNode(146 /* BigIntKeyword */); + } + if (type.flags & 16 /* Boolean */) { + context.approximateLength += 7; + return ts.createKeywordTypeNode(123 /* BooleanKeyword */); + } + if (type.flags & 1024 /* EnumLiteral */ && !(type.flags & 1048576 /* Union */)) { + var parentSymbol = getParentOfSymbol(type.symbol); + var parentName = symbolToTypeNode(parentSymbol, context, 67897832 /* Type */); + var enumLiteralName = getDeclaredTypeOfSymbol(parentSymbol) === type + ? parentName + : appendReferenceToType(parentName, ts.createTypeReferenceNode(ts.symbolName(type.symbol), /*typeArguments*/ undefined)); + return enumLiteralName; + } + if (type.flags & 1056 /* EnumLike */) { + return symbolToTypeNode(type.symbol, context, 67897832 /* Type */); + } + if (type.flags & 128 /* StringLiteral */) { + context.approximateLength += (type.value.length + 2); + return ts.createLiteralTypeNode(ts.setEmitFlags(ts.createLiteral(type.value), 16777216 /* NoAsciiEscaping */)); + } + if (type.flags & 256 /* NumberLiteral */) { + context.approximateLength += (("" + type.value).length); + return ts.createLiteralTypeNode((ts.createLiteral(type.value))); + } + if (type.flags & 2048 /* BigIntLiteral */) { + context.approximateLength += (ts.pseudoBigIntToString(type.value).length) + 1; + return ts.createLiteralTypeNode((ts.createLiteral(type.value))); + } + if (type.flags & 512 /* BooleanLiteral */) { + context.approximateLength += type.intrinsicName.length; + return type.intrinsicName === "true" ? ts.createTrue() : ts.createFalse(); + } + if (type.flags & 8192 /* UniqueESSymbol */) { + if (!(context.flags & 1048576 /* AllowUniqueESSymbolType */)) { + if (isValueSymbolAccessible(type.symbol, context.enclosingDeclaration)) { + context.approximateLength += 6; + return symbolToTypeNode(type.symbol, context, 67220415 /* Value */); + } + if (context.tracker.reportInaccessibleUniqueSymbolError) { + context.tracker.reportInaccessibleUniqueSymbolError(); + } + } + context.approximateLength += 13; + return ts.createTypeOperatorNode(142 /* UniqueKeyword */, ts.createKeywordTypeNode(139 /* SymbolKeyword */)); + } + if (type.flags & 16384 /* Void */) { + context.approximateLength += 4; + return ts.createKeywordTypeNode(106 /* VoidKeyword */); + } + if (type.flags & 32768 /* Undefined */) { + context.approximateLength += 9; + return ts.createKeywordTypeNode(141 /* UndefinedKeyword */); + } + if (type.flags & 65536 /* Null */) { + context.approximateLength += 4; + return ts.createKeywordTypeNode(96 /* NullKeyword */); + } + if (type.flags & 131072 /* Never */) { + context.approximateLength += 5; + return ts.createKeywordTypeNode(132 /* NeverKeyword */); + } + if (type.flags & 4096 /* ESSymbol */) { + context.approximateLength += 6; + return ts.createKeywordTypeNode(139 /* SymbolKeyword */); + } + if (type.flags & 67108864 /* NonPrimitive */) { + context.approximateLength += 6; + return ts.createKeywordTypeNode(136 /* ObjectKeyword */); + } + if (type.flags & 262144 /* TypeParameter */ && type.isThisType) { + if (context.flags & 4194304 /* InObjectTypeLiteral */) { + if (!context.encounteredError && !(context.flags & 32768 /* AllowThisInObjectLiteral */)) { + context.encounteredError = true; + } + if (context.tracker.reportInaccessibleThisError) { + context.tracker.reportInaccessibleThisError(); + } + } + context.approximateLength += 4; + return ts.createThis(); + } + var objectFlags = ts.getObjectFlags(type); + if (objectFlags & 4 /* Reference */) { + ts.Debug.assert(!!(type.flags & 524288 /* Object */)); + return typeReferenceToTypeNode(type); + } + if (type.flags & 262144 /* TypeParameter */ || objectFlags & 3 /* ClassOrInterface */) { + if (type.flags & 262144 /* TypeParameter */ && ts.contains(context.inferTypeParameters, type)) { + context.approximateLength += (ts.symbolName(type.symbol).length + 6); + return ts.createInferTypeNode(typeParameterToDeclarationWithConstraint(type, context, /*constraintNode*/ undefined)); + } + if (context.flags & 4 /* GenerateNamesForShadowedTypeParams */ && + type.flags & 262144 /* TypeParameter */ && + ts.length(type.symbol.declarations) && + ts.isTypeParameterDeclaration(type.symbol.declarations[0]) && + typeParameterShadowsNameInScope(type, context) && + !isTypeSymbolAccessible(type.symbol, context.enclosingDeclaration)) { + var name = type.symbol.declarations[0].name; + context.approximateLength += ts.idText(name).length; + return ts.createTypeReferenceNode(ts.getGeneratedNameForNode(name, 16 /* Optimistic */ | 8 /* ReservedInNestedScopes */), /*typeArguments*/ undefined); + } + // Ignore constraint/default when creating a usage (as opposed to declaration) of a type parameter. + return type.symbol + ? symbolToTypeNode(type.symbol, context, 67897832 /* Type */) + : ts.createTypeReferenceNode(ts.createIdentifier("?"), /*typeArguments*/ undefined); + } + if (!inTypeAlias && type.aliasSymbol && (context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */ || isTypeSymbolAccessible(type.aliasSymbol, context.enclosingDeclaration))) { + var typeArgumentNodes = mapToTypeNodes(type.aliasTypeArguments, context); + if (isReservedMemberName(type.aliasSymbol.escapedName) && !(type.aliasSymbol.flags & 32 /* Class */)) + return ts.createTypeReferenceNode(ts.createIdentifier(""), typeArgumentNodes); + return symbolToTypeNode(type.aliasSymbol, context, 67897832 /* Type */, typeArgumentNodes); + } + if (type.flags & (1048576 /* Union */ | 2097152 /* Intersection */)) { + var types = type.flags & 1048576 /* Union */ ? formatUnionTypes(type.types) : type.types; + if (ts.length(types) === 1) { + return typeToTypeNodeHelper(types[0], context); + } + var typeNodes = mapToTypeNodes(types, context, /*isBareList*/ true); + if (typeNodes && typeNodes.length > 0) { + var unionOrIntersectionTypeNode = ts.createUnionOrIntersectionTypeNode(type.flags & 1048576 /* Union */ ? 173 /* UnionType */ : 174 /* IntersectionType */, typeNodes); + return unionOrIntersectionTypeNode; + } + else { + if (!context.encounteredError && !(context.flags & 262144 /* AllowEmptyUnionOrIntersection */)) { + context.encounteredError = true; + } + return undefined; // TODO: GH#18217 + } + } + if (objectFlags & (16 /* Anonymous */ | 32 /* Mapped */)) { + ts.Debug.assert(!!(type.flags & 524288 /* Object */)); + // The type is an object literal type. + return createAnonymousTypeNode(type); + } + if (type.flags & 4194304 /* Index */) { + var indexedType = type.type; + context.approximateLength += 6; + var indexTypeNode = typeToTypeNodeHelper(indexedType, context); + return ts.createTypeOperatorNode(indexTypeNode); + } + if (type.flags & 8388608 /* IndexedAccess */) { + var objectTypeNode = typeToTypeNodeHelper(type.objectType, context); + var indexTypeNode = typeToTypeNodeHelper(type.indexType, context); + context.approximateLength += 2; + return ts.createIndexedAccessTypeNode(objectTypeNode, indexTypeNode); + } + if (type.flags & 16777216 /* Conditional */) { + var checkTypeNode = typeToTypeNodeHelper(type.checkType, context); + var saveInferTypeParameters = context.inferTypeParameters; + context.inferTypeParameters = type.root.inferTypeParameters; + var extendsTypeNode = typeToTypeNodeHelper(type.extendsType, context); + context.inferTypeParameters = saveInferTypeParameters; + var trueTypeNode = typeToTypeNodeHelper(getTrueTypeFromConditionalType(type), context); + var falseTypeNode = typeToTypeNodeHelper(getFalseTypeFromConditionalType(type), context); + context.approximateLength += 15; + return ts.createConditionalTypeNode(checkTypeNode, extendsTypeNode, trueTypeNode, falseTypeNode); + } + if (type.flags & 33554432 /* Substitution */) { + return typeToTypeNodeHelper(type.typeVariable, context); + } + return ts.Debug.fail("Should be unreachable."); + function createMappedTypeNodeFromType(type) { + ts.Debug.assert(!!(type.flags & 524288 /* Object */)); + var readonlyToken = type.declaration.readonlyToken ? ts.createToken(type.declaration.readonlyToken.kind) : undefined; + var questionToken = type.declaration.questionToken ? ts.createToken(type.declaration.questionToken.kind) : undefined; + var appropriateConstraintTypeNode; + if (isMappedTypeWithKeyofConstraintDeclaration(type)) { + // We have a { [P in keyof T]: X } + // We do this to ensure we retain the toplevel keyof-ness of the type which may be lost due to keyof distribution during `getConstraintTypeFromMappedType` + appropriateConstraintTypeNode = ts.createTypeOperatorNode(typeToTypeNodeHelper(getModifiersTypeFromMappedType(type), context)); + } + else { + appropriateConstraintTypeNode = typeToTypeNodeHelper(getConstraintTypeFromMappedType(type), context); + } + var typeParameterNode = typeParameterToDeclarationWithConstraint(getTypeParameterFromMappedType(type), context, appropriateConstraintTypeNode); + var templateTypeNode = typeToTypeNodeHelper(getTemplateTypeFromMappedType(type), context); + var mappedTypeNode = ts.createMappedTypeNode(readonlyToken, typeParameterNode, questionToken, templateTypeNode); + context.approximateLength += 10; + return ts.setEmitFlags(mappedTypeNode, 1 /* SingleLine */); + } + function createAnonymousTypeNode(type) { + var typeId = "" + type.id; + var symbol = type.symbol; + var id; + if (symbol) { + var isConstructorObject = ts.getObjectFlags(type) & 16 /* Anonymous */ && type.symbol && type.symbol.flags & 32 /* Class */; + id = (isConstructorObject ? "+" : "") + getSymbolId(symbol); + if (isJSConstructor(symbol.valueDeclaration)) { + // Instance and static types share the same symbol; only add 'typeof' for the static side. + var isInstanceType = type === getInferredClassType(symbol) ? 67897832 /* Type */ : 67220415 /* Value */; + return symbolToTypeNode(symbol, context, isInstanceType); + } + // Always use 'typeof T' for type of class, enum, and module objects + else if (symbol.flags & 32 /* Class */ && !getBaseTypeVariableOfClass(symbol) && !(symbol.valueDeclaration.kind === 209 /* ClassExpression */ && context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */) || + symbol.flags & (384 /* Enum */ | 512 /* ValueModule */) || + shouldWriteTypeOfFunctionSymbol()) { + return symbolToTypeNode(symbol, context, 67220415 /* Value */); + } + else if (context.visitedTypes && context.visitedTypes.has(typeId)) { + // If type is an anonymous type literal in a type alias declaration, use type alias name + var typeAlias = getTypeAliasForTypeLiteral(type); + if (typeAlias) { + // The specified symbol flags need to be reinterpreted as type flags + return symbolToTypeNode(typeAlias, context, 67897832 /* Type */); + } + else { + return createElidedInformationPlaceholder(context); + } + } + else { + // Since instantiations of the same anonymous type have the same symbol, tracking symbols instead + // of types allows us to catch circular references to instantiations of the same anonymous type + if (!context.visitedTypes) { + context.visitedTypes = ts.createMap(); + } + if (!context.symbolDepth) { + context.symbolDepth = ts.createMap(); + } + var depth = context.symbolDepth.get(id) || 0; + if (depth > 10) { + return createElidedInformationPlaceholder(context); + } + context.symbolDepth.set(id, depth + 1); + context.visitedTypes.set(typeId, true); + var result = createTypeNodeFromObjectType(type); + context.visitedTypes.delete(typeId); + context.symbolDepth.set(id, depth); + return result; + } + } + else { + // Anonymous types without a symbol are never circular. + return createTypeNodeFromObjectType(type); + } + function shouldWriteTypeOfFunctionSymbol() { + var isStaticMethodSymbol = !!(symbol.flags & 8192 /* Method */) && // typeof static method + ts.some(symbol.declarations, function (declaration) { return ts.hasModifier(declaration, 32 /* Static */); }); + var isNonLocalFunctionSymbol = !!(symbol.flags & 16 /* Function */) && + (symbol.parent || // is exported function symbol + ts.forEach(symbol.declarations, function (declaration) { + return declaration.parent.kind === 279 /* SourceFile */ || declaration.parent.kind === 245 /* ModuleBlock */; + })); + if (isStaticMethodSymbol || isNonLocalFunctionSymbol) { + // typeof is allowed only for static/non local functions + return (!!(context.flags & 4096 /* UseTypeOfFunction */) || (context.visitedTypes && context.visitedTypes.has(typeId))) && // it is type of the symbol uses itself recursively + (!(context.flags & 8 /* UseStructuralFallback */) || isValueSymbolAccessible(symbol, context.enclosingDeclaration)); // TODO: GH#18217 // And the build is going to succeed without visibility error or there is no structural fallback allowed + } + } + } + function createTypeNodeFromObjectType(type) { + if (isGenericMappedType(type)) { + return createMappedTypeNodeFromType(type); + } + var resolved = resolveStructuredTypeMembers(type); + if (!resolved.properties.length && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { + if (!resolved.callSignatures.length && !resolved.constructSignatures.length) { + context.approximateLength += 2; + return ts.setEmitFlags(ts.createTypeLiteralNode(/*members*/ undefined), 1 /* SingleLine */); + } + if (resolved.callSignatures.length === 1 && !resolved.constructSignatures.length) { + var signature = resolved.callSignatures[0]; + var signatureNode = signatureToSignatureDeclarationHelper(signature, 165 /* FunctionType */, context); + return signatureNode; + } + if (resolved.constructSignatures.length === 1 && !resolved.callSignatures.length) { + var signature = resolved.constructSignatures[0]; + var signatureNode = signatureToSignatureDeclarationHelper(signature, 166 /* ConstructorType */, context); + return signatureNode; + } + } + var savedFlags = context.flags; + context.flags |= 4194304 /* InObjectTypeLiteral */; + var members = createTypeNodesFromResolvedType(resolved); + context.flags = savedFlags; + var typeLiteralNode = ts.createTypeLiteralNode(members); + context.approximateLength += 2; + return ts.setEmitFlags(typeLiteralNode, (context.flags & 1024 /* MultilineObjectLiterals */) ? 0 : 1 /* SingleLine */); + } + function typeReferenceToTypeNode(type) { + var typeArguments = type.typeArguments || ts.emptyArray; + if (type.target === globalArrayType) { + if (context.flags & 2 /* WriteArrayAsGenericType */) { + var typeArgumentNode = typeToTypeNodeHelper(typeArguments[0], context); + return ts.createTypeReferenceNode("Array", [typeArgumentNode]); + } + var elementType = typeToTypeNodeHelper(typeArguments[0], context); + return ts.createArrayTypeNode(elementType); + } + else if (type.target.objectFlags & 8 /* Tuple */) { + if (typeArguments.length > 0) { + var arity = getTypeReferenceArity(type); + var tupleConstituentNodes = mapToTypeNodes(typeArguments.slice(0, arity), context); + var hasRestElement = type.target.hasRestElement; + if (tupleConstituentNodes) { + for (var i = type.target.minLength; i < Math.min(arity, tupleConstituentNodes.length); i++) { + tupleConstituentNodes[i] = hasRestElement && i === arity - 1 ? + ts.createRestTypeNode(ts.createArrayTypeNode(tupleConstituentNodes[i])) : + ts.createOptionalTypeNode(tupleConstituentNodes[i]); + } + return ts.createTupleTypeNode(tupleConstituentNodes); + } + } + if (context.encounteredError || (context.flags & 524288 /* AllowEmptyTuple */)) { + return ts.createTupleTypeNode([]); + } + context.encounteredError = true; + return undefined; // TODO: GH#18217 + } + else if (context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */ && + type.symbol.valueDeclaration && + ts.isClassLike(type.symbol.valueDeclaration) && + !isValueSymbolAccessible(type.symbol, context.enclosingDeclaration)) { + return createAnonymousTypeNode(type); + } + else { + var outerTypeParameters = type.target.outerTypeParameters; + var i = 0; + var resultType = void 0; + if (outerTypeParameters) { + var length_1 = outerTypeParameters.length; + while (i < length_1) { + // Find group of type arguments for type parameters with the same declaring container. + var start = i; + var parent = getParentSymbolOfTypeParameter(outerTypeParameters[i]); + do { + i++; + } while (i < length_1 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent); + // When type parameters are their own type arguments for the whole group (i.e. we have + // the default outer type arguments), we don't show the group. + if (!ts.rangeEquals(outerTypeParameters, typeArguments, start, i)) { + var typeArgumentSlice = mapToTypeNodes(typeArguments.slice(start, i), context); + var flags_2 = context.flags; + context.flags |= 16 /* ForbidIndexedAccessSymbolReferences */; + var ref = symbolToTypeNode(parent, context, 67897832 /* Type */, typeArgumentSlice); + context.flags = flags_2; + resultType = !resultType ? ref : appendReferenceToType(resultType, ref); + } + } + } + var typeArgumentNodes = void 0; + if (typeArguments.length > 0) { + var typeParameterCount = (type.target.typeParameters || ts.emptyArray).length; + typeArgumentNodes = mapToTypeNodes(typeArguments.slice(i, typeParameterCount), context); + } + var flags = context.flags; + context.flags |= 16 /* ForbidIndexedAccessSymbolReferences */; + var finalRef = symbolToTypeNode(type.symbol, context, 67897832 /* Type */, typeArgumentNodes); + context.flags = flags; + return !resultType ? finalRef : appendReferenceToType(resultType, finalRef); + } + } + function appendReferenceToType(root, ref) { + if (ts.isImportTypeNode(root)) { + // first shift type arguments + var innerParams = root.typeArguments; + if (root.qualifier) { + (ts.isIdentifier(root.qualifier) ? root.qualifier : root.qualifier.right).typeArguments = innerParams; + } + root.typeArguments = ref.typeArguments; + // then move qualifiers + var ids = getAccessStack(ref); + for (var _i = 0, ids_1 = ids; _i < ids_1.length; _i++) { + var id = ids_1[_i]; + root.qualifier = root.qualifier ? ts.createQualifiedName(root.qualifier, id) : id; + } + return root; + } + else { + // first shift type arguments + var innerParams = root.typeArguments; + (ts.isIdentifier(root.typeName) ? root.typeName : root.typeName.right).typeArguments = innerParams; + root.typeArguments = ref.typeArguments; + // then move qualifiers + var ids = getAccessStack(ref); + for (var _a = 0, ids_2 = ids; _a < ids_2.length; _a++) { + var id = ids_2[_a]; + root.typeName = ts.createQualifiedName(root.typeName, id); + } + return root; + } + } + function getAccessStack(ref) { + var state = ref.typeName; + var ids = []; + while (!ts.isIdentifier(state)) { + ids.unshift(state.right); + state = state.left; + } + ids.unshift(state); + return ids; + } + function createTypeNodesFromResolvedType(resolvedType) { + if (checkTruncationLength(context)) { + return [ts.createPropertySignature(/*modifiers*/ undefined, "...", /*questionToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined)]; + } + var typeElements = []; + for (var _i = 0, _a = resolvedType.callSignatures; _i < _a.length; _i++) { + var signature = _a[_i]; + typeElements.push(signatureToSignatureDeclarationHelper(signature, 160 /* CallSignature */, context)); + } + for (var _b = 0, _c = resolvedType.constructSignatures; _b < _c.length; _b++) { + var signature = _c[_b]; + typeElements.push(signatureToSignatureDeclarationHelper(signature, 161 /* ConstructSignature */, context)); + } + if (resolvedType.stringIndexInfo) { + var indexSignature = void 0; + if (resolvedType.objectFlags & 2048 /* ReverseMapped */) { + indexSignature = indexInfoToIndexSignatureDeclarationHelper(createIndexInfo(anyType, resolvedType.stringIndexInfo.isReadonly, resolvedType.stringIndexInfo.declaration), 0 /* String */, context); + indexSignature.type = createElidedInformationPlaceholder(context); + } + else { + indexSignature = indexInfoToIndexSignatureDeclarationHelper(resolvedType.stringIndexInfo, 0 /* String */, context); + } + typeElements.push(indexSignature); + } + if (resolvedType.numberIndexInfo) { + typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.numberIndexInfo, 1 /* Number */, context)); + } + var properties = resolvedType.properties; + if (!properties) { + return typeElements; + } + var i = 0; + for (var _d = 0, properties_1 = properties; _d < properties_1.length; _d++) { + var propertySymbol = properties_1[_d]; + i++; + if (context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */) { + if (propertySymbol.flags & 4194304 /* Prototype */) { + continue; + } + if (ts.getDeclarationModifierFlagsFromSymbol(propertySymbol) & (8 /* Private */ | 16 /* Protected */) && context.tracker.reportPrivateInBaseOfClassExpression) { + context.tracker.reportPrivateInBaseOfClassExpression(ts.unescapeLeadingUnderscores(propertySymbol.escapedName)); + } + } + if (checkTruncationLength(context) && (i + 2 < properties.length - 1)) { + typeElements.push(ts.createPropertySignature(/*modifiers*/ undefined, "... " + (properties.length - i) + " more ...", /*questionToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined)); + addPropertyToElementList(properties[properties.length - 1], context, typeElements); + break; + } + addPropertyToElementList(propertySymbol, context, typeElements); + } + return typeElements.length ? typeElements : undefined; + } + } + function createElidedInformationPlaceholder(context) { + context.approximateLength += 3; + if (!(context.flags & 1 /* NoTruncation */)) { + return ts.createTypeReferenceNode(ts.createIdentifier("..."), /*typeArguments*/ undefined); + } + return ts.createKeywordTypeNode(120 /* AnyKeyword */); + } + function addPropertyToElementList(propertySymbol, context, typeElements) { + var propertyIsReverseMapped = !!(ts.getCheckFlags(propertySymbol) & 2048 /* ReverseMapped */); + var propertyType = propertyIsReverseMapped && context.flags & 33554432 /* InReverseMappedType */ ? + anyType : getTypeOfSymbol(propertySymbol); + var saveEnclosingDeclaration = context.enclosingDeclaration; + context.enclosingDeclaration = undefined; + if (context.tracker.trackSymbol && ts.getCheckFlags(propertySymbol) & 1024 /* Late */) { + var decl = ts.first(propertySymbol.declarations); + if (hasLateBindableName(decl)) { + trackComputedName(decl.name, saveEnclosingDeclaration, context); + } + } + var propertyName = symbolToName(propertySymbol, context, 67220415 /* Value */, /*expectsIdentifier*/ true); + context.approximateLength += (ts.symbolName(propertySymbol).length + 1); + context.enclosingDeclaration = saveEnclosingDeclaration; + var optionalToken = propertySymbol.flags & 16777216 /* Optional */ ? ts.createToken(56 /* QuestionToken */) : undefined; + if (propertySymbol.flags & (16 /* Function */ | 8192 /* Method */) && !getPropertiesOfObjectType(propertyType).length) { + var signatures = getSignaturesOfType(propertyType, 0 /* Call */); + for (var _i = 0, signatures_1 = signatures; _i < signatures_1.length; _i++) { + var signature = signatures_1[_i]; + var methodDeclaration = signatureToSignatureDeclarationHelper(signature, 155 /* MethodSignature */, context); + methodDeclaration.name = propertyName; + methodDeclaration.questionToken = optionalToken; + if (propertySymbol.valueDeclaration) { + // Copy comments to node for declaration emit + ts.setCommentRange(methodDeclaration, propertySymbol.valueDeclaration); + } + typeElements.push(methodDeclaration); + } + } + else { + var savedFlags = context.flags; + context.flags |= propertyIsReverseMapped ? 33554432 /* InReverseMappedType */ : 0; + var propertyTypeNode = void 0; + if (propertyIsReverseMapped && !!(savedFlags & 33554432 /* InReverseMappedType */)) { + propertyTypeNode = createElidedInformationPlaceholder(context); + } + else { + propertyTypeNode = propertyType ? typeToTypeNodeHelper(propertyType, context) : ts.createKeywordTypeNode(120 /* AnyKeyword */); + } + context.flags = savedFlags; + var modifiers = isReadonlySymbol(propertySymbol) ? [ts.createToken(133 /* ReadonlyKeyword */)] : undefined; + if (modifiers) { + context.approximateLength += 9; + } + var propertySignature = ts.createPropertySignature(modifiers, propertyName, optionalToken, propertyTypeNode, + /*initializer*/ undefined); + if (propertySymbol.valueDeclaration) { + // Copy comments to node for declaration emit + ts.setCommentRange(propertySignature, propertySymbol.valueDeclaration); + } + typeElements.push(propertySignature); + } + } + function mapToTypeNodes(types, context, isBareList) { + if (ts.some(types)) { + if (checkTruncationLength(context)) { + if (!isBareList) { + return [ts.createTypeReferenceNode("...", /*typeArguments*/ undefined)]; + } + else if (types.length > 2) { + return [ + typeToTypeNodeHelper(types[0], context), + ts.createTypeReferenceNode("... " + (types.length - 2) + " more ...", /*typeArguments*/ undefined), + typeToTypeNodeHelper(types[types.length - 1], context) + ]; + } + } + var result = []; + var i = 0; + for (var _i = 0, types_1 = types; _i < types_1.length; _i++) { + var type = types_1[_i]; + i++; + if (checkTruncationLength(context) && (i + 2 < types.length - 1)) { + result.push(ts.createTypeReferenceNode("... " + (types.length - i) + " more ...", /*typeArguments*/ undefined)); + var typeNode_1 = typeToTypeNodeHelper(types[types.length - 1], context); + if (typeNode_1) { + result.push(typeNode_1); + } + break; + } + context.approximateLength += 2; // Account for whitespace + separator + var typeNode = typeToTypeNodeHelper(type, context); + if (typeNode) { + result.push(typeNode); + } + } + return result; + } + } + function indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind, context) { + var name = ts.getNameFromIndexInfo(indexInfo) || "x"; + var indexerTypeNode = ts.createKeywordTypeNode(kind === 0 /* String */ ? 138 /* StringKeyword */ : 135 /* NumberKeyword */); + var indexingParameter = ts.createParameter( + /*decorators*/ undefined, + /*modifiers*/ undefined, + /*dotDotDotToken*/ undefined, name, + /*questionToken*/ undefined, indexerTypeNode, + /*initializer*/ undefined); + var typeNode = typeToTypeNodeHelper(indexInfo.type || anyType, context); + if (!indexInfo.type && !(context.flags & 2097152 /* AllowEmptyIndexInfoType */)) { + context.encounteredError = true; + } + context.approximateLength += (name.length + 4); + return ts.createIndexSignature( + /*decorators*/ undefined, indexInfo.isReadonly ? [ts.createToken(133 /* ReadonlyKeyword */)] : undefined, [indexingParameter], typeNode); + } + function signatureToSignatureDeclarationHelper(signature, kind, context) { + var typeParameters; + var typeArguments; + if (context.flags & 32 /* WriteTypeArgumentsOfSignature */ && signature.target && signature.mapper && signature.target.typeParameters) { + typeArguments = signature.target.typeParameters.map(function (parameter) { return typeToTypeNodeHelper(instantiateType(parameter, signature.mapper), context); }); + } + else { + typeParameters = signature.typeParameters && signature.typeParameters.map(function (parameter) { return typeParameterToDeclaration(parameter, context); }); + } + var parameters = getExpandedParameters(signature).map(function (parameter) { return symbolToParameterDeclaration(parameter, context, kind === 157 /* Constructor */); }); + if (signature.thisParameter) { + var thisParameter = symbolToParameterDeclaration(signature.thisParameter, context); + parameters.unshift(thisParameter); + } + var returnTypeNode; + var typePredicate = getTypePredicateOfSignature(signature); + if (typePredicate) { + var parameterName = typePredicate.kind === 1 /* Identifier */ ? + ts.setEmitFlags(ts.createIdentifier(typePredicate.parameterName), 16777216 /* NoAsciiEscaping */) : + ts.createThisTypeNode(); + var typeNode = typeToTypeNodeHelper(typePredicate.type, context); + returnTypeNode = ts.createTypePredicateNode(parameterName, typeNode); + } + else { + var returnType = getReturnTypeOfSignature(signature); + returnTypeNode = returnType && typeToTypeNodeHelper(returnType, context); + } + if (context.flags & 256 /* SuppressAnyReturnType */) { + if (returnTypeNode && returnTypeNode.kind === 120 /* AnyKeyword */) { + returnTypeNode = undefined; + } + } + else if (!returnTypeNode) { + returnTypeNode = ts.createKeywordTypeNode(120 /* AnyKeyword */); + } + context.approximateLength += 3; // Usually a signature contributes a few more characters than this, but 3 is the minimum + return ts.createSignatureDeclaration(kind, typeParameters, parameters, returnTypeNode, typeArguments); + } + function typeParameterShadowsNameInScope(type, context) { + return !!resolveName(context.enclosingDeclaration, type.symbol.escapedName, 67897832 /* Type */, /*nameNotFoundArg*/ undefined, type.symbol.escapedName, /*isUse*/ false); + } + function typeParameterToDeclarationWithConstraint(type, context, constraintNode) { + var savedContextFlags = context.flags; + context.flags &= ~512 /* WriteTypeParametersInQualifiedName */; // Avoids potential infinite loop when building for a claimspace with a generic + var shouldUseGeneratedName = context.flags & 4 /* GenerateNamesForShadowedTypeParams */ && + type.symbol.declarations[0] && + ts.isTypeParameterDeclaration(type.symbol.declarations[0]) && + typeParameterShadowsNameInScope(type, context); + var name = shouldUseGeneratedName + ? ts.getGeneratedNameForNode(type.symbol.declarations[0].name, 16 /* Optimistic */ | 8 /* ReservedInNestedScopes */) + : symbolToName(type.symbol, context, 67897832 /* Type */, /*expectsIdentifier*/ true); + var defaultParameter = getDefaultFromTypeParameter(type); + var defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter, context); + context.flags = savedContextFlags; + return ts.createTypeParameterDeclaration(name, constraintNode, defaultParameterNode); + } + function typeParameterToDeclaration(type, context, constraint) { + if (constraint === void 0) { constraint = getConstraintOfTypeParameter(type); } + var constraintNode = constraint && typeToTypeNodeHelper(constraint, context); + return typeParameterToDeclarationWithConstraint(type, context, constraintNode); + } + function symbolToParameterDeclaration(parameterSymbol, context, preserveModifierFlags) { + var parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 151 /* Parameter */); + if (!parameterDeclaration && !isTransientSymbol(parameterSymbol)) { + parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 299 /* JSDocParameterTag */); + } + var parameterType = getTypeOfSymbol(parameterSymbol); + if (parameterDeclaration && isRequiredInitializedParameter(parameterDeclaration)) { + parameterType = getOptionalType(parameterType); + } + var parameterTypeNode = typeToTypeNodeHelper(parameterType, context); + var modifiers = !(context.flags & 8192 /* OmitParameterModifiers */) && preserveModifierFlags && parameterDeclaration && parameterDeclaration.modifiers ? parameterDeclaration.modifiers.map(ts.getSynthesizedClone) : undefined; + var isRest = parameterDeclaration && ts.isRestParameter(parameterDeclaration) || ts.getCheckFlags(parameterSymbol) & 8192 /* RestParameter */; + var dotDotDotToken = isRest ? ts.createToken(25 /* DotDotDotToken */) : undefined; + var name = parameterDeclaration + ? parameterDeclaration.name ? + parameterDeclaration.name.kind === 72 /* Identifier */ ? ts.setEmitFlags(ts.getSynthesizedClone(parameterDeclaration.name), 16777216 /* NoAsciiEscaping */) : + parameterDeclaration.name.kind === 148 /* QualifiedName */ ? ts.setEmitFlags(ts.getSynthesizedClone(parameterDeclaration.name.right), 16777216 /* NoAsciiEscaping */) : + cloneBindingName(parameterDeclaration.name) : + ts.symbolName(parameterSymbol) + : ts.symbolName(parameterSymbol); + var isOptional = parameterDeclaration && isOptionalParameter(parameterDeclaration) || ts.getCheckFlags(parameterSymbol) & 4096 /* OptionalParameter */; + var questionToken = isOptional ? ts.createToken(56 /* QuestionToken */) : undefined; + var parameterNode = ts.createParameter( + /*decorators*/ undefined, modifiers, dotDotDotToken, name, questionToken, parameterTypeNode, + /*initializer*/ undefined); + context.approximateLength += ts.symbolName(parameterSymbol).length + 3; + return parameterNode; + function cloneBindingName(node) { + return elideInitializerAndSetEmitFlags(node); + function elideInitializerAndSetEmitFlags(node) { + if (context.tracker.trackSymbol && ts.isComputedPropertyName(node) && isLateBindableName(node)) { + trackComputedName(node, context.enclosingDeclaration, context); + } + var visited = ts.visitEachChild(node, elideInitializerAndSetEmitFlags, ts.nullTransformationContext, /*nodesVisitor*/ undefined, elideInitializerAndSetEmitFlags); + var clone = ts.nodeIsSynthesized(visited) ? visited : ts.getSynthesizedClone(visited); + if (clone.kind === 186 /* BindingElement */) { + clone.initializer = undefined; + } + return ts.setEmitFlags(clone, 1 /* SingleLine */ | 16777216 /* NoAsciiEscaping */); + } + } + } + function trackComputedName(node, enclosingDeclaration, context) { + if (!context.tracker.trackSymbol) + return; + // get symbol of the first identifier of the entityName + var firstIdentifier = getFirstIdentifier(node.expression); + var name = resolveName(firstIdentifier, firstIdentifier.escapedText, 67220415 /* Value */ | 1048576 /* ExportValue */, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); + if (name) { + context.tracker.trackSymbol(name, enclosingDeclaration, 67220415 /* Value */); + } + } + function lookupSymbolChain(symbol, context, meaning, yieldModuleSymbol) { + context.tracker.trackSymbol(symbol, context.enclosingDeclaration, meaning); // TODO: GH#18217 + // Try to get qualified name if the symbol is not a type parameter and there is an enclosing declaration. + var chain; + var isTypeParameter = symbol.flags & 262144 /* TypeParameter */; + if (!isTypeParameter && (context.enclosingDeclaration || context.flags & 64 /* UseFullyQualifiedType */) && !(context.flags & 134217728 /* DoNotIncludeSymbolChain */)) { + chain = ts.Debug.assertDefined(getSymbolChain(symbol, meaning, /*endOfChain*/ true)); + ts.Debug.assert(chain && chain.length > 0); + } + else { + chain = [symbol]; + } + return chain; + /** @param endOfChain Set to false for recursive calls; non-recursive calls should always output something. */ + function getSymbolChain(symbol, meaning, endOfChain) { + var accessibleSymbolChain = getAccessibleSymbolChain(symbol, context.enclosingDeclaration, meaning, !!(context.flags & 128 /* UseOnlyExternalAliasing */)); + var parentSpecifiers; + if (!accessibleSymbolChain || + needsQualification(accessibleSymbolChain[0], context.enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) { + // Go up and add our parent. + var parents_1 = getContainersOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol, context.enclosingDeclaration); + if (ts.length(parents_1)) { + parentSpecifiers = parents_1.map(function (symbol) { + return ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol) + ? getSpecifierForModuleSymbol(symbol, context) + : undefined; + }); + var indices = parents_1.map(function (_, i) { return i; }); + indices.sort(sortByBestName); + var sortedParents = indices.map(function (i) { return parents_1[i]; }); + for (var _i = 0, sortedParents_1 = sortedParents; _i < sortedParents_1.length; _i++) { + var parent = sortedParents_1[_i]; + var parentChain = getSymbolChain(parent, getQualifiedLeftMeaning(meaning), /*endOfChain*/ false); + if (parentChain) { + accessibleSymbolChain = parentChain.concat(accessibleSymbolChain || [getAliasForSymbolInContainer(parent, symbol) || symbol]); + break; + } + } + } + } + if (accessibleSymbolChain) { + return accessibleSymbolChain; + } + if ( + // If this is the last part of outputting the symbol, always output. The cases apply only to parent symbols. + endOfChain || + // If a parent symbol is an anonymous type, don't write it. + !(symbol.flags & (2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */))) { + // If a parent symbol is an external module, don't write it. (We prefer just `x` vs `"foo/bar".x`.) + if (!endOfChain && !yieldModuleSymbol && !!ts.forEach(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { + return; + } + return [symbol]; + } + function sortByBestName(a, b) { + var specifierA = parentSpecifiers[a]; + var specifierB = parentSpecifiers[b]; + if (specifierA && specifierB) { + var isBRelative = ts.pathIsRelative(specifierB); + if (ts.pathIsRelative(specifierA) === isBRelative) { + // Both relative or both non-relative, sort by number of parts + return ts.moduleSpecifiers.countPathComponents(specifierA) - ts.moduleSpecifiers.countPathComponents(specifierB); + } + if (isBRelative) { + // A is non-relative, B is relative: prefer A + return -1; + } + // A is relative, B is non-relative: prefer B + return 1; + } + return 0; + } + } + } + function typeParametersToTypeParameterDeclarations(symbol, context) { + var typeParameterNodes; + var targetSymbol = getTargetSymbol(symbol); + if (targetSymbol.flags & (32 /* Class */ | 64 /* Interface */ | 524288 /* TypeAlias */)) { + typeParameterNodes = ts.createNodeArray(ts.map(getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol), function (tp) { return typeParameterToDeclaration(tp, context); })); + } + return typeParameterNodes; + } + function lookupTypeParameterNodes(chain, index, context) { + ts.Debug.assert(chain && 0 <= index && index < chain.length); + var symbol = chain[index]; + var typeParameterNodes; + if (context.flags & 512 /* WriteTypeParametersInQualifiedName */ && index < (chain.length - 1)) { + var parentSymbol = symbol; + var nextSymbol = chain[index + 1]; + if (ts.getCheckFlags(nextSymbol) & 1 /* Instantiated */) { + var params = getTypeParametersOfClassOrInterface(parentSymbol.flags & 2097152 /* Alias */ ? resolveAlias(parentSymbol) : parentSymbol); + typeParameterNodes = mapToTypeNodes(ts.map(params, nextSymbol.mapper), context); + } + else { + typeParameterNodes = typeParametersToTypeParameterDeclarations(symbol, context); + } + } + return typeParameterNodes; + } + /** + * Given A[B][C][D], finds A[B] + */ + function getTopmostIndexedAccessType(top) { + if (ts.isIndexedAccessTypeNode(top.objectType)) { + return getTopmostIndexedAccessType(top.objectType); + } + return top; + } + function getSpecifierForModuleSymbol(symbol, context) { + var file = ts.getDeclarationOfKind(symbol, 279 /* SourceFile */); + if (file && file.moduleName !== undefined) { + // Use the amd name if it is available + return file.moduleName; + } + if (!file) { + if (context.tracker.trackReferencedAmbientModule) { + var ambientDecls = ts.filter(symbol.declarations, ts.isAmbientModule); + if (ts.length(ambientDecls)) { + for (var _i = 0, ambientDecls_1 = ambientDecls; _i < ambientDecls_1.length; _i++) { + var decl = ambientDecls_1[_i]; + context.tracker.trackReferencedAmbientModule(decl, symbol); + } + } + } + if (ambientModuleSymbolRegex.test(symbol.escapedName)) { + return symbol.escapedName.substring(1, symbol.escapedName.length - 1); + } + } + if (!context.enclosingDeclaration || !context.tracker.moduleResolverHost) { + // If there's no context declaration, we can't lookup a non-ambient specifier, so we just use the symbol name + if (ambientModuleSymbolRegex.test(symbol.escapedName)) { + return symbol.escapedName.substring(1, symbol.escapedName.length - 1); + } + return ts.getSourceFileOfNode(ts.getNonAugmentationDeclaration(symbol)).fileName; // A resolver may not be provided for baselines and errors - in those cases we use the fileName in full + } + var contextFile = ts.getSourceFileOfNode(ts.getOriginalNode(context.enclosingDeclaration)); + var links = getSymbolLinks(symbol); + var specifier = links.specifierCache && links.specifierCache.get(contextFile.path); + if (!specifier) { + var isBundle_1 = (compilerOptions.out || compilerOptions.outFile); + // For declaration bundles, we need to generate absolute paths relative to the common source dir for imports, + // just like how the declaration emitter does for the ambient module declarations - we can easily accomplish this + // using the `baseUrl` compiler option (which we would otherwise never use in declaration emit) and a non-relative + // specifier preference + var moduleResolverHost = context.tracker.moduleResolverHost; + var specifierCompilerOptions = isBundle_1 ? __assign({}, compilerOptions, { baseUrl: moduleResolverHost.getCommonSourceDirectory() }) : compilerOptions; + specifier = ts.first(ts.moduleSpecifiers.getModuleSpecifiers(symbol, specifierCompilerOptions, contextFile, moduleResolverHost, host.getSourceFiles(), { importModuleSpecifierPreference: isBundle_1 ? "non-relative" : "relative" }, host.redirectTargetsMap)); + links.specifierCache = links.specifierCache || ts.createMap(); + links.specifierCache.set(contextFile.path, specifier); + } + return specifier; + } + function symbolToTypeNode(symbol, context, meaning, overrideTypeArguments) { + var chain = lookupSymbolChain(symbol, context, meaning, !(context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */)); // If we're using aliases outside the current scope, dont bother with the module + var isTypeOf = meaning === 67220415 /* Value */; + if (ts.some(chain[0].declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { + // module is root, must use `ImportTypeNode` + var nonRootParts = chain.length > 1 ? createAccessFromSymbolChain(chain, chain.length - 1, 1) : undefined; + var typeParameterNodes = overrideTypeArguments || lookupTypeParameterNodes(chain, 0, context); + var specifier = getSpecifierForModuleSymbol(chain[0], context); + if (!(context.flags & 67108864 /* AllowNodeModulesRelativePaths */) && ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs && specifier.indexOf("/node_modules/") >= 0) { + // If ultimately we can only name the symbol with a reference that dives into a `node_modules` folder, we should error + // since declaration files with these kinds of references are liable to fail when published :( + context.encounteredError = true; + if (context.tracker.reportLikelyUnsafeImportRequiredError) { + context.tracker.reportLikelyUnsafeImportRequiredError(specifier); + } + } + var lit = ts.createLiteralTypeNode(ts.createLiteral(specifier)); + if (context.tracker.trackExternalModuleSymbolOfImportTypeNode) + context.tracker.trackExternalModuleSymbolOfImportTypeNode(chain[0]); + context.approximateLength += specifier.length + 10; // specifier + import("") + if (!nonRootParts || ts.isEntityName(nonRootParts)) { + if (nonRootParts) { + var lastId = ts.isIdentifier(nonRootParts) ? nonRootParts : nonRootParts.right; + lastId.typeArguments = undefined; + } + return ts.createImportTypeNode(lit, nonRootParts, typeParameterNodes, isTypeOf); + } + else { + var splitNode = getTopmostIndexedAccessType(nonRootParts); + var qualifier = splitNode.objectType.typeName; + return ts.createIndexedAccessTypeNode(ts.createImportTypeNode(lit, qualifier, typeParameterNodes, isTypeOf), splitNode.indexType); + } + } + var entityName = createAccessFromSymbolChain(chain, chain.length - 1, 0); + if (ts.isIndexedAccessTypeNode(entityName)) { + return entityName; // Indexed accesses can never be `typeof` + } + if (isTypeOf) { + return ts.createTypeQueryNode(entityName); + } + else { + var lastId = ts.isIdentifier(entityName) ? entityName : entityName.right; + var lastTypeArgs = lastId.typeArguments; + lastId.typeArguments = undefined; + return ts.createTypeReferenceNode(entityName, lastTypeArgs); + } + function createAccessFromSymbolChain(chain, index, stopper) { + var typeParameterNodes = index === (chain.length - 1) ? overrideTypeArguments : lookupTypeParameterNodes(chain, index, context); + var symbol = chain[index]; + if (index === 0) { + context.flags |= 16777216 /* InInitialEntityName */; + } + var symbolName = getNameOfSymbolAsWritten(symbol, context); + context.approximateLength += symbolName.length + 1; + if (index === 0) { + context.flags ^= 16777216 /* InInitialEntityName */; + } + var parent = chain[index - 1]; + if (!(context.flags & 16 /* ForbidIndexedAccessSymbolReferences */) && parent && getMembersOfSymbol(parent) && getMembersOfSymbol(parent).get(symbol.escapedName) === symbol) { + // Should use an indexed access + var LHS = createAccessFromSymbolChain(chain, index - 1, stopper); + if (ts.isIndexedAccessTypeNode(LHS)) { + return ts.createIndexedAccessTypeNode(LHS, ts.createLiteralTypeNode(ts.createLiteral(symbolName))); + } + else { + return ts.createIndexedAccessTypeNode(ts.createTypeReferenceNode(LHS, typeParameterNodes), ts.createLiteralTypeNode(ts.createLiteral(symbolName))); + } + } + var identifier = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216 /* NoAsciiEscaping */); + identifier.symbol = symbol; + if (index > stopper) { + var LHS = createAccessFromSymbolChain(chain, index - 1, stopper); + if (!ts.isEntityName(LHS)) { + return ts.Debug.fail("Impossible construct - an export of an indexed access cannot be reachable"); + } + return ts.createQualifiedName(LHS, identifier); + } + return identifier; + } + } + function symbolToName(symbol, context, meaning, expectsIdentifier) { + var chain = lookupSymbolChain(symbol, context, meaning); + if (expectsIdentifier && chain.length !== 1 + && !context.encounteredError + && !(context.flags & 65536 /* AllowQualifedNameInPlaceOfIdentifier */)) { + context.encounteredError = true; + } + return createEntityNameFromSymbolChain(chain, chain.length - 1); + function createEntityNameFromSymbolChain(chain, index) { + var typeParameterNodes = lookupTypeParameterNodes(chain, index, context); + var symbol = chain[index]; + if (index === 0) { + context.flags |= 16777216 /* InInitialEntityName */; + } + var symbolName = getNameOfSymbolAsWritten(symbol, context); + if (index === 0) { + context.flags ^= 16777216 /* InInitialEntityName */; + } + var identifier = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216 /* NoAsciiEscaping */); + identifier.symbol = symbol; + return index > 0 ? ts.createQualifiedName(createEntityNameFromSymbolChain(chain, index - 1), identifier) : identifier; + } + } + function symbolToExpression(symbol, context, meaning) { + var chain = lookupSymbolChain(symbol, context, meaning); + return createExpressionFromSymbolChain(chain, chain.length - 1); + function createExpressionFromSymbolChain(chain, index) { + var typeParameterNodes = lookupTypeParameterNodes(chain, index, context); + var symbol = chain[index]; + if (ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { + return ts.createLiteral(getSpecifierForModuleSymbol(symbol, context)); + } + if (index === 0) { + context.flags |= 16777216 /* InInitialEntityName */; + } + var symbolName = getNameOfSymbolAsWritten(symbol, context); + if (index === 0) { + context.flags ^= 16777216 /* InInitialEntityName */; + } + var firstChar = symbolName.charCodeAt(0); + var canUsePropertyAccess = ts.isIdentifierStart(firstChar, languageVersion); + if (index === 0 || canUsePropertyAccess) { + var identifier = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216 /* NoAsciiEscaping */); + identifier.symbol = symbol; + return index > 0 ? ts.createPropertyAccess(createExpressionFromSymbolChain(chain, index - 1), identifier) : identifier; + } + else { + if (firstChar === 91 /* openBracket */) { + symbolName = symbolName.substring(1, symbolName.length - 1); + firstChar = symbolName.charCodeAt(0); + } + var expression = void 0; + if (ts.isSingleOrDoubleQuote(firstChar)) { + expression = ts.createLiteral(symbolName.substring(1, symbolName.length - 1).replace(/\\./g, function (s) { return s.substring(1); })); + expression.singleQuote = firstChar === 39 /* singleQuote */; + } + else if (("" + +symbolName) === symbolName) { + expression = ts.createLiteral(+symbolName); + } + if (!expression) { + expression = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216 /* NoAsciiEscaping */); + expression.symbol = symbol; + } + return ts.createElementAccess(createExpressionFromSymbolChain(chain, index - 1), expression); + } + } + } + } + function typePredicateToString(typePredicate, enclosingDeclaration, flags, writer) { + if (flags === void 0) { flags = 16384 /* UseAliasDefinedOutsideCurrentScope */; } + return writer ? typePredicateToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(typePredicateToStringWorker); + function typePredicateToStringWorker(writer) { + var predicate = ts.createTypePredicateNode(typePredicate.kind === 1 /* Identifier */ ? ts.createIdentifier(typePredicate.parameterName) : ts.createThisTypeNode(), nodeBuilder.typeToTypeNode(typePredicate.type, enclosingDeclaration, toNodeBuilderFlags(flags) | 70221824 /* IgnoreErrors */ | 512 /* WriteTypeParametersInQualifiedName */)); + var printer = ts.createPrinter({ removeComments: true }); + var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); + printer.writeNode(4 /* Unspecified */, predicate, /*sourceFile*/ sourceFile, writer); + return writer; + } + } + function formatUnionTypes(types) { + var result = []; + var flags = 0; + for (var i = 0; i < types.length; i++) { + var t = types[i]; + flags |= t.flags; + if (!(t.flags & 98304 /* Nullable */)) { + if (t.flags & (512 /* BooleanLiteral */ | 1024 /* EnumLiteral */)) { + var baseType = t.flags & 512 /* BooleanLiteral */ ? booleanType : getBaseTypeOfEnumLiteralType(t); + if (baseType.flags & 1048576 /* Union */) { + var count = baseType.types.length; + if (i + count <= types.length && getRegularTypeOfLiteralType(types[i + count - 1]) === getRegularTypeOfLiteralType(baseType.types[count - 1])) { + result.push(baseType); + i += count - 1; + continue; + } + } + } + result.push(t); + } + } + if (flags & 65536 /* Null */) + result.push(nullType); + if (flags & 32768 /* Undefined */) + result.push(undefinedType); + return result || types; + } + function visibilityToString(flags) { + if (flags === 8 /* Private */) { + return "private"; + } + if (flags === 16 /* Protected */) { + return "protected"; + } + return "public"; + } + function getTypeAliasForTypeLiteral(type) { + if (type.symbol && type.symbol.flags & 2048 /* TypeLiteral */) { + var node = ts.findAncestor(type.symbol.declarations[0].parent, function (n) { return n.kind !== 177 /* ParenthesizedType */; }); + if (node.kind === 242 /* TypeAliasDeclaration */) { + return getSymbolOfNode(node); + } + } + return undefined; + } + function isTopLevelInExternalModuleAugmentation(node) { + return node && node.parent && + node.parent.kind === 245 /* ModuleBlock */ && + ts.isExternalModuleAugmentation(node.parent.parent); + } + function isDefaultBindingContext(location) { + return location.kind === 279 /* SourceFile */ || ts.isAmbientModule(location); + } + /** + * Gets a human-readable name for a symbol. + * Should *not* be used for the right-hand side of a `.` -- use `symbolName(symbol)` for that instead. + * + * Unlike `symbolName(symbol)`, this will include quotes if the name is from a string literal. + * It will also use a representation of a number as written instead of a decimal form, e.g. `0o11` instead of `9`. + */ + function getNameOfSymbolAsWritten(symbol, context) { + if (context && symbol.escapedName === "default" /* Default */ && !(context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */) && + // If it's not the first part of an entity name, it must print as `default` + (!(context.flags & 16777216 /* InInitialEntityName */) || + // if the symbol is synthesized, it will only be referenced externally it must print as `default` + !symbol.declarations || + // if not in the same binding context (source file, module declaration), it must print as `default` + (context.enclosingDeclaration && ts.findAncestor(symbol.declarations[0], isDefaultBindingContext) !== ts.findAncestor(context.enclosingDeclaration, isDefaultBindingContext)))) { + return "default"; + } + if (symbol.declarations && symbol.declarations.length) { + var declaration = symbol.declarations[0]; + var name = ts.getNameOfDeclaration(declaration); + if (name) { + if (ts.isCallExpression(declaration) && ts.isBindableObjectDefinePropertyCall(declaration)) { + return ts.symbolName(symbol); + } + return ts.declarationNameToString(name); + } + if (declaration.parent && declaration.parent.kind === 237 /* VariableDeclaration */) { + return ts.declarationNameToString(declaration.parent.name); + } + switch (declaration.kind) { + case 209 /* ClassExpression */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + if (context && !context.encounteredError && !(context.flags & 131072 /* AllowAnonymousIdentifier */)) { + context.encounteredError = true; + } + return declaration.kind === 209 /* ClassExpression */ ? "(Anonymous class)" : "(Anonymous function)"; + } + } + var nameType = symbol.nameType; + if (nameType) { + if (nameType.flags & 128 /* StringLiteral */ && !ts.isIdentifierText(nameType.value, compilerOptions.target)) { + return "\"" + ts.escapeString(nameType.value, 34 /* doubleQuote */) + "\""; + } + if (nameType && nameType.flags & 8192 /* UniqueESSymbol */) { + return "[" + getNameOfSymbolAsWritten(nameType.symbol, context) + "]"; + } + } + return ts.symbolName(symbol); + } + function isDeclarationVisible(node) { + if (node) { + var links = getNodeLinks(node); + if (links.isVisible === undefined) { + links.isVisible = !!determineIfDeclarationIsVisible(); + } + return links.isVisible; + } + return false; + function determineIfDeclarationIsVisible() { + switch (node.kind) { + case 297 /* JSDocCallbackTag */: + case 304 /* JSDocTypedefTag */: + // Top-level jsdoc type aliases are considered exported + // First parent is comment node, second is hosting declaration or token; we only care about those tokens or declarations whose parent is a source file + return !!(node.parent && node.parent.parent && node.parent.parent.parent && ts.isSourceFile(node.parent.parent.parent)); + case 186 /* BindingElement */: + return isDeclarationVisible(node.parent.parent); + case 237 /* VariableDeclaration */: + if (ts.isBindingPattern(node.name) && + !node.name.elements.length) { + // If the binding pattern is empty, this variable declaration is not visible + return false; + } + // falls through + case 244 /* ModuleDeclaration */: + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 239 /* FunctionDeclaration */: + case 243 /* EnumDeclaration */: + case 248 /* ImportEqualsDeclaration */: + // external module augmentation is always visible + if (ts.isExternalModuleAugmentation(node)) { + return true; + } + var parent = getDeclarationContainer(node); + // If the node is not exported or it is not ambient module element (except import declaration) + if (!(ts.getCombinedModifierFlags(node) & 1 /* Export */) && + !(node.kind !== 248 /* ImportEqualsDeclaration */ && parent.kind !== 279 /* SourceFile */ && parent.flags & 4194304 /* Ambient */)) { + return isGlobalSourceFile(parent); + } + // Exported members/ambient module elements (exception import declaration) are visible if parent is visible + return isDeclarationVisible(parent); + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + if (ts.hasModifier(node, 8 /* Private */ | 16 /* Protected */)) { + // Private/protected properties/methods are not visible + return false; + } + // Public properties/methods are visible if its parents are visible, so: + // falls through + case 157 /* Constructor */: + case 161 /* ConstructSignature */: + case 160 /* CallSignature */: + case 162 /* IndexSignature */: + case 151 /* Parameter */: + case 245 /* ModuleBlock */: + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + case 168 /* TypeLiteral */: + case 164 /* TypeReference */: + case 169 /* ArrayType */: + case 170 /* TupleType */: + case 173 /* UnionType */: + case 174 /* IntersectionType */: + case 177 /* ParenthesizedType */: + return isDeclarationVisible(node.parent); + // Default binding, import specifier and namespace import is visible + // only on demand so by default it is not visible + case 250 /* ImportClause */: + case 251 /* NamespaceImport */: + case 253 /* ImportSpecifier */: + return false; + // Type parameters are always visible + case 150 /* TypeParameter */: + // Source file and namespace export are always visible + case 279 /* SourceFile */: + case 247 /* NamespaceExportDeclaration */: + return true; + // Export assignments do not create name bindings outside the module + case 254 /* ExportAssignment */: + return false; + default: + return false; + } + } + } + function collectLinkedAliases(node, setVisibility) { + var exportSymbol; + if (node.parent && node.parent.kind === 254 /* ExportAssignment */) { + exportSymbol = resolveName(node, node.escapedText, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, node, /*isUse*/ false); + } + else if (node.parent.kind === 257 /* ExportSpecifier */) { + exportSymbol = getTargetOfExportSpecifier(node.parent, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); + } + var result; + if (exportSymbol) { + buildVisibleNodeList(exportSymbol.declarations); + } + return result; + function buildVisibleNodeList(declarations) { + ts.forEach(declarations, function (declaration) { + var resultNode = getAnyImportSyntax(declaration) || declaration; + if (setVisibility) { + getNodeLinks(declaration).isVisible = true; + } + else { + result = result || []; + ts.pushIfUnique(result, resultNode); + } + if (ts.isInternalModuleImportEqualsDeclaration(declaration)) { + // Add the referenced top container visible + var internalModuleReference = declaration.moduleReference; + var firstIdentifier = getFirstIdentifier(internalModuleReference); + var importSymbol = resolveName(declaration, firstIdentifier.escapedText, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */, undefined, undefined, /*isUse*/ false); + if (importSymbol) { + buildVisibleNodeList(importSymbol.declarations); + } + } + }); + } + } + /** + * Push an entry on the type resolution stack. If an entry with the given target and the given property name + * is already on the stack, and no entries in between already have a type, then a circularity has occurred. + * In this case, the result values of the existing entry and all entries pushed after it are changed to false, + * and the value false is returned. Otherwise, the new entry is just pushed onto the stack, and true is returned. + * In order to see if the same query has already been done before, the target object and the propertyName both + * must match the one passed in. + * + * @param target The symbol, type, or signature whose type is being queried + * @param propertyName The property name that should be used to query the target for its type + */ + function pushTypeResolution(target, propertyName) { + var resolutionCycleStartIndex = findResolutionCycleStartIndex(target, propertyName); + if (resolutionCycleStartIndex >= 0) { + // A cycle was found + var length_2 = resolutionTargets.length; + for (var i = resolutionCycleStartIndex; i < length_2; i++) { + resolutionResults[i] = false; + } + return false; + } + resolutionTargets.push(target); + resolutionResults.push(/*items*/ true); + resolutionPropertyNames.push(propertyName); + return true; + } + function findResolutionCycleStartIndex(target, propertyName) { + for (var i = resolutionTargets.length - 1; i >= 0; i--) { + if (hasType(resolutionTargets[i], resolutionPropertyNames[i])) { + return -1; + } + if (resolutionTargets[i] === target && resolutionPropertyNames[i] === propertyName) { + return i; + } + } + return -1; + } + function hasType(target, propertyName) { + switch (propertyName) { + case 0 /* Type */: + return !!getSymbolLinks(target).type; + case 5 /* EnumTagType */: + return !!(getNodeLinks(target).resolvedEnumType); + case 2 /* DeclaredType */: + return !!getSymbolLinks(target).declaredType; + case 1 /* ResolvedBaseConstructorType */: + return !!target.resolvedBaseConstructorType; + case 3 /* ResolvedReturnType */: + return !!target.resolvedReturnType; + case 4 /* ImmediateBaseConstraint */: + return !!target.immediateBaseConstraint; + case 6 /* JSDocTypeReference */: + return !!getSymbolLinks(target).resolvedJSDocType; + } + return ts.Debug.assertNever(propertyName); + } + // Pop an entry from the type resolution stack and return its associated result value. The result value will + // be true if no circularities were detected, or false if a circularity was found. + function popTypeResolution() { + resolutionTargets.pop(); + resolutionPropertyNames.pop(); + return resolutionResults.pop(); + } + function getDeclarationContainer(node) { + return ts.findAncestor(ts.getRootDeclaration(node), function (node) { + switch (node.kind) { + case 237 /* VariableDeclaration */: + case 238 /* VariableDeclarationList */: + case 253 /* ImportSpecifier */: + case 252 /* NamedImports */: + case 251 /* NamespaceImport */: + case 250 /* ImportClause */: + return false; + default: + return true; + } + }).parent; + } + function getTypeOfPrototypeProperty(prototype) { + // TypeScript 1.0 spec (April 2014): 8.4 + // Every class automatically contains a static property member named 'prototype', + // the type of which is an instantiation of the class type with type Any supplied as a type argument for each type parameter. + // It is an error to explicitly declare a static property member with the name 'prototype'. + var classType = getDeclaredTypeOfSymbol(getParentOfSymbol(prototype)); + return classType.typeParameters ? createTypeReference(classType, ts.map(classType.typeParameters, function (_) { return anyType; })) : classType; + } + // Return the type of the given property in the given type, or undefined if no such property exists + function getTypeOfPropertyOfType(type, name) { + var prop = getPropertyOfType(type, name); + return prop ? getTypeOfSymbol(prop) : undefined; + } + function isTypeAny(type) { + return type && (type.flags & 1 /* Any */) !== 0; + } + // Return the type of a binding element parent. We check SymbolLinks first to see if a type has been + // assigned by contextual typing. + function getTypeForBindingElementParent(node) { + var symbol = getSymbolOfNode(node); + return symbol && getSymbolLinks(symbol).type || getTypeForVariableLikeDeclaration(node, /*includeOptionality*/ false); + } + function isComputedNonLiteralName(name) { + return name.kind === 149 /* ComputedPropertyName */ && !ts.isStringOrNumericLiteralLike(name.expression); + } + function getRestType(source, properties, symbol) { + source = filterType(source, function (t) { return !(t.flags & 98304 /* Nullable */); }); + if (source.flags & 131072 /* Never */) { + return emptyObjectType; + } + if (source.flags & 1048576 /* Union */) { + return mapType(source, function (t) { return getRestType(t, properties, symbol); }); + } + var omitKeyType = getUnionType(ts.map(properties, getLiteralTypeFromPropertyName)); + if (isGenericObjectType(source) || isGenericIndexType(omitKeyType)) { + if (omitKeyType.flags & 131072 /* Never */) { + return source; + } + var pickTypeAlias = getGlobalPickSymbol(); + var excludeTypeAlias = getGlobalExcludeSymbol(); + if (!pickTypeAlias || !excludeTypeAlias) { + return errorType; + } + var pickKeys = getTypeAliasInstantiation(excludeTypeAlias, [getIndexType(source), omitKeyType]); + return getTypeAliasInstantiation(pickTypeAlias, [source, pickKeys]); + } + var members = ts.createSymbolTable(); + for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) { + var prop = _a[_i]; + if (!isTypeAssignableTo(getLiteralTypeFromProperty(prop, 8576 /* StringOrNumberLiteralOrUnique */), omitKeyType) + && !(ts.getDeclarationModifierFlagsFromSymbol(prop) & (8 /* Private */ | 16 /* Protected */)) + && isSpreadableProperty(prop)) { + members.set(prop.escapedName, getSpreadSymbol(prop)); + } + } + var stringIndexInfo = getIndexInfoOfType(source, 0 /* String */); + var numberIndexInfo = getIndexInfoOfType(source, 1 /* Number */); + return createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); + } + /** Return the inferred type for a binding element */ + function getTypeForBindingElement(declaration) { + var pattern = declaration.parent; + var parentType = getTypeForBindingElementParent(pattern.parent); + // If parent has the unknown (error) type, then so does this binding element + if (parentType === errorType) { + return errorType; + } + // If no type was specified or inferred for parent, + // infer from the initializer of the binding element if one is present. + // Otherwise, go with the undefined type of the parent. + if (!parentType) { + return declaration.initializer ? checkDeclarationInitializer(declaration) : parentType; + } + if (isTypeAny(parentType)) { + return parentType; + } + // Relax null check on ambient destructuring parameters, since the parameters have no implementation and are just documentation + if (strictNullChecks && declaration.flags & 4194304 /* Ambient */ && ts.isParameterDeclaration(declaration)) { + parentType = getNonNullableType(parentType); + } + var type; + if (pattern.kind === 184 /* ObjectBindingPattern */) { + if (declaration.dotDotDotToken) { + if (parentType.flags & 2 /* Unknown */ || !isValidSpreadType(parentType)) { + error(declaration, ts.Diagnostics.Rest_types_may_only_be_created_from_object_types); + return errorType; + } + var literalMembers = []; + for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (!element.dotDotDotToken) { + literalMembers.push(element.propertyName || element.name); + } + } + type = getRestType(parentType, literalMembers, declaration.symbol); + } + else { + // Use explicitly specified property name ({ p: xxx } form), or otherwise the implied name ({ p } form) + var name = declaration.propertyName || declaration.name; + var exprType = getLiteralTypeFromPropertyName(name); + var declaredType = checkIndexedAccessIndexType(getIndexedAccessType(parentType, exprType, name), name); + type = getFlowTypeOfReference(declaration, getConstraintForLocation(declaredType, declaration.name)); + } + } + else { + // This elementType will be used if the specific property corresponding to this index is not + // present (aka the tuple element property). This call also checks that the parentType is in + // fact an iterable or array (depending on target language). + var elementType = checkIteratedTypeOrElementType(parentType, pattern, /*allowStringInput*/ false, /*allowAsyncIterables*/ false); + var index_1 = pattern.elements.indexOf(declaration); + if (declaration.dotDotDotToken) { + // If the parent is a tuple type, the rest element has a tuple type of the + // remaining tuple element types. Otherwise, the rest element has an array type with same + // element type as the parent type. + type = everyType(parentType, isTupleType) ? + mapType(parentType, function (t) { return sliceTupleType(t, index_1); }) : + createArrayType(elementType); + } + else { + // Use specific property type when parent is a tuple or numeric index type when parent is an array + var index_2 = pattern.elements.indexOf(declaration); + type = everyType(parentType, isTupleLikeType) ? + getTupleElementType(parentType, index_2) || declaration.initializer && checkDeclarationInitializer(declaration) : + elementType; + if (!type) { + if (isTupleType(parentType)) { + error(declaration, ts.Diagnostics.Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2, typeToString(parentType), getTypeReferenceArity(parentType), pattern.elements.length); + } + else { + error(declaration, ts.Diagnostics.Type_0_has_no_property_1, typeToString(parentType), "" + index_2); + } + return errorType; + } + } + } + // In strict null checking mode, if a default value of a non-undefined type is specified, remove + // undefined from the final type. + if (strictNullChecks && declaration.initializer && !(getFalsyFlags(checkDeclarationInitializer(declaration)) & 32768 /* Undefined */)) { + type = getTypeWithFacts(type, 524288 /* NEUndefined */); + } + return declaration.initializer && !ts.getEffectiveTypeAnnotationNode(ts.walkUpBindingElementsAndPatterns(declaration)) ? + getUnionType([type, checkDeclarationInitializer(declaration)], 2 /* Subtype */) : + type; + } + function getTypeForDeclarationFromJSDocComment(declaration) { + var jsdocType = ts.getJSDocType(declaration); + if (jsdocType) { + return getTypeFromTypeNode(jsdocType); + } + return undefined; + } + function isNullOrUndefined(node) { + var expr = ts.skipParentheses(node); + return expr.kind === 96 /* NullKeyword */ || expr.kind === 72 /* Identifier */ && getResolvedSymbol(expr) === undefinedSymbol; + } + function isEmptyArrayLiteral(node) { + var expr = ts.skipParentheses(node); + return expr.kind === 187 /* ArrayLiteralExpression */ && expr.elements.length === 0; + } + function addOptionality(type, optional) { + if (optional === void 0) { optional = true; } + return strictNullChecks && optional ? getOptionalType(type) : type; + } + // Return the inferred type for a variable, parameter, or property declaration + function getTypeForVariableLikeDeclaration(declaration, includeOptionality) { + // A variable declared in a for..in statement is of type string, or of type keyof T when the + // right hand expression is of a type parameter type. + if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 226 /* ForInStatement */) { + var indexType = getIndexType(getNonNullableTypeIfNeeded(checkExpression(declaration.parent.parent.expression))); + return indexType.flags & (262144 /* TypeParameter */ | 4194304 /* Index */) ? getExtractStringType(indexType) : stringType; + } + if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 227 /* ForOfStatement */) { + // checkRightHandSideOfForOf will return undefined if the for-of expression type was + // missing properties/signatures required to get its iteratedType (like + // [Symbol.iterator] or next). This may be because we accessed properties from anyType, + // or it may have led to an error inside getElementTypeOfIterable. + var forOfStatement = declaration.parent.parent; + return checkRightHandSideOfForOf(forOfStatement.expression, forOfStatement.awaitModifier) || anyType; + } + if (ts.isBindingPattern(declaration.parent)) { + return getTypeForBindingElement(declaration); + } + var isOptional = includeOptionality && (ts.isParameter(declaration) && isJSDocOptionalParameter(declaration) + || !ts.isBindingElement(declaration) && !ts.isVariableDeclaration(declaration) && !!declaration.questionToken); + // Use type from type annotation if one is present + var declaredType = tryGetTypeFromEffectiveTypeNode(declaration); + if (declaredType) { + return addOptionality(declaredType, isOptional); + } + if ((noImplicitAny || ts.isInJSFile(declaration)) && + declaration.kind === 237 /* VariableDeclaration */ && !ts.isBindingPattern(declaration.name) && + !(ts.getCombinedModifierFlags(declaration) & 1 /* Export */) && !(declaration.flags & 4194304 /* Ambient */)) { + // If --noImplicitAny is on or the declaration is in a Javascript file, + // use control flow tracked 'any' type for non-ambient, non-exported var or let variables with no + // initializer or a 'null' or 'undefined' initializer. + if (!(ts.getCombinedNodeFlags(declaration) & 2 /* Const */) && (!declaration.initializer || isNullOrUndefined(declaration.initializer))) { + return autoType; + } + // Use control flow tracked 'any[]' type for non-ambient, non-exported variables with an empty array + // literal initializer. + if (declaration.initializer && isEmptyArrayLiteral(declaration.initializer)) { + return autoArrayType; + } + } + if (declaration.kind === 151 /* Parameter */) { + var func = declaration.parent; + // For a parameter of a set accessor, use the type of the get accessor if one is present + if (func.kind === 159 /* SetAccessor */ && !hasNonBindableDynamicName(func)) { + var getter = ts.getDeclarationOfKind(getSymbolOfNode(declaration.parent), 158 /* GetAccessor */); + if (getter) { + var getterSignature = getSignatureFromDeclaration(getter); + var thisParameter = getAccessorThisParameter(func); + if (thisParameter && declaration === thisParameter) { + // Use the type from the *getter* + ts.Debug.assert(!thisParameter.type); + return getTypeOfSymbol(getterSignature.thisParameter); + } + return getReturnTypeOfSignature(getterSignature); + } + } + if (ts.isInJSFile(declaration)) { + var typeTag = ts.getJSDocType(func); + if (typeTag && ts.isFunctionTypeNode(typeTag)) { + return getTypeAtPosition(getSignatureFromDeclaration(typeTag), func.parameters.indexOf(declaration)); + } + } + // Use contextual parameter type if one is available + var type = declaration.symbol.escapedName === "this" /* This */ ? getContextualThisParameterType(func) : getContextuallyTypedParameterType(declaration); + if (type) { + return addOptionality(type, isOptional); + } + } + else if (ts.isInJSFile(declaration)) { + var containerObjectType = getJSContainerObjectType(declaration, getSymbolOfNode(declaration), ts.getDeclaredExpandoInitializer(declaration)); + if (containerObjectType) { + return containerObjectType; + } + } + // Use the type of the initializer expression if one is present + if (declaration.initializer) { + var type = checkDeclarationInitializer(declaration); + return addOptionality(type, isOptional); + } + if (ts.isJsxAttribute(declaration)) { + // if JSX attribute doesn't have initializer, by default the attribute will have boolean value of true. + // I.e is sugar for + return trueType; + } + // If the declaration specifies a binding pattern, use the type implied by the binding pattern + if (ts.isBindingPattern(declaration.name)) { + return getTypeFromBindingPattern(declaration.name, /*includePatternInType*/ false, /*reportErrors*/ true); + } + // No type specified and nothing can be inferred + return undefined; + } + function getWidenedTypeFromAssignmentDeclaration(symbol, resolvedSymbol) { + // function/class/{} initializers are themselves containers, so they won't merge in the same way as other initializers + var container = ts.getAssignedExpandoInitializer(symbol.valueDeclaration); + if (container) { + var tag = ts.getJSDocTypeTag(container); + if (tag && tag.typeExpression) { + return getTypeFromTypeNode(tag.typeExpression); + } + var containerObjectType = getJSContainerObjectType(symbol.valueDeclaration, symbol, container); + return containerObjectType || getWidenedLiteralType(checkExpressionCached(container)); + } + var definedInConstructor = false; + var definedInMethod = false; + var jsdocType; + var types; + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + var expression = (ts.isBinaryExpression(declaration) || ts.isCallExpression(declaration)) ? declaration : + ts.isPropertyAccessExpression(declaration) ? ts.isBinaryExpression(declaration.parent) ? declaration.parent : declaration : + undefined; + if (!expression) { + return errorType; + } + var kind = ts.isPropertyAccessExpression(expression) ? ts.getAssignmentDeclarationPropertyAccessKind(expression) : ts.getAssignmentDeclarationKind(expression); + if (kind === 4 /* ThisProperty */) { + if (isDeclarationInConstructor(expression)) { + definedInConstructor = true; + } + else { + definedInMethod = true; + } + } + if (!ts.isCallExpression(expression)) { + jsdocType = getJSDocTypeFromAssignmentDeclaration(jsdocType, expression, symbol, declaration); + } + if (!jsdocType) { + (types || (types = [])).push((ts.isBinaryExpression(expression) || ts.isCallExpression(expression)) ? getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) : neverType); + } + } + var type = jsdocType; + if (!type) { + var constructorTypes = definedInConstructor ? getConstructorDefinedThisAssignmentTypes(types, symbol.declarations) : undefined; + // use only the constructor types unless they were only assigned null | undefined (including widening variants) + if (definedInMethod) { + var propType = getTypeOfAssignmentDeclarationPropertyOfBaseType(symbol); + if (propType) { + (constructorTypes || (constructorTypes = [])).push(propType); + definedInConstructor = true; + } + } + var sourceTypes = ts.some(constructorTypes, function (t) { return !!(t.flags & ~(98304 /* Nullable */ | 134217728 /* ContainsWideningType */)); }) ? constructorTypes : types; // TODO: GH#18217 + type = getUnionType(sourceTypes, 2 /* Subtype */); + } + var widened = getWidenedType(addOptionality(type, definedInMethod && !definedInConstructor)); + if (filterType(widened, function (t) { return !!(t.flags & ~98304 /* Nullable */); }) === neverType) { + reportImplicitAny(symbol.valueDeclaration, anyType); + return anyType; + } + return widened; + } + function getJSContainerObjectType(decl, symbol, init) { + if (!ts.isInJSFile(decl) || !init || !ts.isObjectLiteralExpression(init) || init.properties.length) { + return undefined; + } + var exports = ts.createSymbolTable(); + while (ts.isBinaryExpression(decl) || ts.isPropertyAccessExpression(decl)) { + var s_1 = getSymbolOfNode(decl); + if (s_1 && ts.hasEntries(s_1.exports)) { + mergeSymbolTable(exports, s_1.exports); + } + decl = ts.isBinaryExpression(decl) ? decl.parent : decl.parent.parent; + } + var s = getSymbolOfNode(decl); + if (s && ts.hasEntries(s.exports)) { + mergeSymbolTable(exports, s.exports); + } + var type = createAnonymousType(symbol, exports, ts.emptyArray, ts.emptyArray, undefined, undefined); + type.objectFlags |= 16384 /* JSLiteral */; + return type; + } + function getJSDocTypeFromAssignmentDeclaration(declaredType, expression, _symbol, declaration) { + var typeNode = ts.getJSDocType(expression.parent); + if (typeNode) { + var type = getWidenedType(getTypeFromTypeNode(typeNode)); + if (!declaredType) { + return type; + } + else if (declaredType !== errorType && type !== errorType && !isTypeIdenticalTo(declaredType, type)) { + errorNextVariableOrPropertyDeclarationMustHaveSameType(declaredType, declaration, type); + } + } + return declaredType; + } + /** If we don't have an explicit JSDoc type, get the type from the initializer. */ + function getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) { + if (ts.isCallExpression(expression)) { + if (resolvedSymbol) { + return getTypeOfSymbol(resolvedSymbol); // This shouldn't happen except under some hopefully forbidden merges of export assignments and object define assignments + } + var objectLitType = checkExpressionCached(expression.arguments[2]); + var valueType = getTypeOfPropertyOfType(objectLitType, "value"); + if (valueType) { + return valueType; + } + var getFunc = getTypeOfPropertyOfType(objectLitType, "get"); + if (getFunc) { + var getSig = getSingleCallSignature(getFunc); + if (getSig) { + return getReturnTypeOfSignature(getSig); + } + } + var setFunc = getTypeOfPropertyOfType(objectLitType, "set"); + if (setFunc) { + var setSig = getSingleCallSignature(setFunc); + if (setSig) { + return getTypeOfFirstParameterOfSignature(setSig); + } + } + return anyType; + } + var type = resolvedSymbol ? getTypeOfSymbol(resolvedSymbol) : getWidenedLiteralType(checkExpressionCached(expression.right)); + if (type.flags & 524288 /* Object */ && + kind === 2 /* ModuleExports */ && + symbol.escapedName === "export=" /* ExportEquals */) { + var exportedType_1 = resolveStructuredTypeMembers(type); + var members_3 = ts.createSymbolTable(); + ts.copyEntries(exportedType_1.members, members_3); + if (resolvedSymbol && !resolvedSymbol.exports) { + resolvedSymbol.exports = ts.createSymbolTable(); + } + (resolvedSymbol || symbol).exports.forEach(function (s, name) { + if (members_3.has(name)) { + var exportedMember = exportedType_1.members.get(name); + var union = createSymbol(s.flags | exportedMember.flags, name); + union.type = getUnionType([getTypeOfSymbol(s), getTypeOfSymbol(exportedMember)]); + members_3.set(name, union); + } + else { + members_3.set(name, s); + } + }); + var result = createAnonymousType(exportedType_1.symbol, members_3, exportedType_1.callSignatures, exportedType_1.constructSignatures, exportedType_1.stringIndexInfo, exportedType_1.numberIndexInfo); + result.objectFlags |= (ts.getObjectFlags(type) & 16384 /* JSLiteral */); // Propagate JSLiteral flag + return result; + } + if (isEmptyArrayLiteralType(type)) { + reportImplicitAny(expression, anyArrayType); + return anyArrayType; + } + return type; + } + function isDeclarationInConstructor(expression) { + var thisContainer = ts.getThisContainer(expression, /*includeArrowFunctions*/ false); + // Properties defined in a constructor (or base constructor, or javascript constructor function) don't get undefined added. + // Function expressions that are assigned to the prototype count as methods. + return thisContainer.kind === 157 /* Constructor */ || + thisContainer.kind === 239 /* FunctionDeclaration */ || + (thisContainer.kind === 196 /* FunctionExpression */ && !ts.isPrototypePropertyAssignment(thisContainer.parent)); + } + function getConstructorDefinedThisAssignmentTypes(types, declarations) { + ts.Debug.assert(types.length === declarations.length); + return types.filter(function (_, i) { + var declaration = declarations[i]; + var expression = ts.isBinaryExpression(declaration) ? declaration : + ts.isBinaryExpression(declaration.parent) ? declaration.parent : undefined; + return expression && isDeclarationInConstructor(expression); + }); + } + /** check for definition in base class if any declaration is in a class */ + function getTypeOfAssignmentDeclarationPropertyOfBaseType(property) { + var parentDeclaration = ts.forEach(property.declarations, function (d) { + var parent = ts.getThisContainer(d, /*includeArrowFunctions*/ false).parent; + return ts.isClassLike(parent) && parent; + }); + if (parentDeclaration) { + var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(parentDeclaration)); + var baseClassType = classType && getBaseTypes(classType)[0]; + if (baseClassType) { + return getTypeOfPropertyOfType(baseClassType, property.escapedName); + } + } + } + // Return the type implied by a binding pattern element. This is the type of the initializer of the element if + // one is present. Otherwise, if the element is itself a binding pattern, it is the type implied by the binding + // pattern. Otherwise, it is the type any. + function getTypeFromBindingElement(element, includePatternInType, reportErrors) { + if (element.initializer) { + return addOptionality(checkDeclarationInitializer(element)); + } + if (ts.isBindingPattern(element.name)) { + return getTypeFromBindingPattern(element.name, includePatternInType, reportErrors); + } + if (reportErrors && !declarationBelongsToPrivateAmbientMember(element)) { + reportImplicitAny(element, anyType); + } + return anyType; + } + // Return the type implied by an object binding pattern + function getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) { + var members = ts.createSymbolTable(); + var stringIndexInfo; + var objectFlags = 128 /* ObjectLiteral */; + ts.forEach(pattern.elements, function (e) { + var name = e.propertyName || e.name; + if (isComputedNonLiteralName(name)) { + // do not include computed properties in the implied type + objectFlags |= 512 /* ObjectLiteralPatternWithComputedProperties */; + return; + } + if (e.dotDotDotToken) { + stringIndexInfo = createIndexInfo(anyType, /*isReadonly*/ false); + return; + } + var text = ts.getTextOfPropertyName(name); + var flags = 4 /* Property */ | (e.initializer ? 16777216 /* Optional */ : 0); + var symbol = createSymbol(flags, text); + symbol.type = getTypeFromBindingElement(e, includePatternInType, reportErrors); + symbol.bindingElement = e; + members.set(symbol.escapedName, symbol); + }); + var result = createAnonymousType(undefined, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, undefined); + result.flags |= 268435456 /* ContainsObjectLiteral */; + result.objectFlags |= objectFlags; + if (includePatternInType) { + result.pattern = pattern; + } + return result; + } + // Return the type implied by an array binding pattern + function getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors) { + var elements = pattern.elements; + var lastElement = ts.lastOrUndefined(elements); + var hasRestElement = !!(lastElement && lastElement.kind === 186 /* BindingElement */ && lastElement.dotDotDotToken); + if (elements.length === 0 || elements.length === 1 && hasRestElement) { + return languageVersion >= 2 /* ES2015 */ ? createIterableType(anyType) : anyArrayType; + } + var elementTypes = ts.map(elements, function (e) { return ts.isOmittedExpression(e) ? anyType : getTypeFromBindingElement(e, includePatternInType, reportErrors); }); + var minLength = ts.findLastIndex(elements, function (e) { return !ts.isOmittedExpression(e) && !hasDefaultValue(e); }, elements.length - (hasRestElement ? 2 : 1)) + 1; + var result = createTupleType(elementTypes, minLength, hasRestElement); + if (includePatternInType) { + result = cloneTypeReference(result); + result.pattern = pattern; + } + return result; + } + // Return the type implied by a binding pattern. This is the type implied purely by the binding pattern itself + // and without regard to its context (i.e. without regard any type annotation or initializer associated with the + // declaration in which the binding pattern is contained). For example, the implied type of [x, y] is [any, any] + // and the implied type of { x, y: z = 1 } is { x: any; y: number; }. The type implied by a binding pattern is + // used as the contextual type of an initializer associated with the binding pattern. Also, for a destructuring + // parameter with no type annotation or initializer, the type implied by the binding pattern becomes the type of + // the parameter. + function getTypeFromBindingPattern(pattern, includePatternInType, reportErrors) { + if (includePatternInType === void 0) { includePatternInType = false; } + if (reportErrors === void 0) { reportErrors = false; } + return pattern.kind === 184 /* ObjectBindingPattern */ + ? getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) + : getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors); + } + // Return the type associated with a variable, parameter, or property declaration. In the simple case this is the type + // specified in a type annotation or inferred from an initializer. However, in the case of a destructuring declaration it + // is a bit more involved. For example: + // + // var [x, s = ""] = [1, "one"]; + // + // Here, the array literal [1, "one"] is contextually typed by the type [any, string], which is the implied type of the + // binding pattern [x, s = ""]. Because the contextual type is a tuple type, the resulting type of [1, "one"] is the + // tuple type [number, string]. Thus, the type inferred for 'x' is number and the type inferred for 's' is string. + function getWidenedTypeForVariableLikeDeclaration(declaration, reportErrors) { + return widenTypeForVariableLikeDeclaration(getTypeForVariableLikeDeclaration(declaration, /*includeOptionality*/ true), declaration, reportErrors); + } + function widenTypeForVariableLikeDeclaration(type, declaration, reportErrors) { + if (type) { + if (reportErrors) { + reportErrorsFromWidening(declaration, type); + } + // always widen a 'unique symbol' type if the type was created for a different declaration. + if (type.flags & 8192 /* UniqueESSymbol */ && (ts.isBindingElement(declaration) || !declaration.type) && type.symbol !== getSymbolOfNode(declaration)) { + type = esSymbolType; + } + return getWidenedType(type); + } + // Rest parameters default to type any[], other parameters default to type any + type = ts.isParameter(declaration) && declaration.dotDotDotToken ? anyArrayType : anyType; + // Report implicit any errors unless this is a private property within an ambient declaration + if (reportErrors) { + if (!declarationBelongsToPrivateAmbientMember(declaration)) { + reportImplicitAny(declaration, type); + } + } + return type; + } + function declarationBelongsToPrivateAmbientMember(declaration) { + var root = ts.getRootDeclaration(declaration); + var memberDeclaration = root.kind === 151 /* Parameter */ ? root.parent : root; + return isPrivateWithinAmbient(memberDeclaration); + } + function tryGetTypeFromEffectiveTypeNode(declaration) { + var typeNode = ts.getEffectiveTypeAnnotationNode(declaration); + if (typeNode) { + return getTypeFromTypeNode(typeNode); + } + } + function getTypeOfVariableOrParameterOrProperty(symbol) { + var links = getSymbolLinks(symbol); + return links.type || (links.type = getTypeOfVariableOrParameterOrPropertyWorker(symbol)); + } + function getTypeOfVariableOrParameterOrPropertyWorker(symbol) { + // Handle prototype property + if (symbol.flags & 4194304 /* Prototype */) { + return getTypeOfPrototypeProperty(symbol); + } + // CommonsJS require and module both have type any. + if (symbol === requireSymbol) { + return anyType; + } + if (symbol.flags & 134217728 /* ModuleExports */) { + var fileSymbol = getSymbolOfNode(ts.getSourceFileOfNode(symbol.valueDeclaration)); + var members = ts.createSymbolTable(); + members.set("exports", fileSymbol); + return createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, undefined, undefined); + } + // Handle catch clause variables + var declaration = symbol.valueDeclaration; + if (ts.isCatchClauseVariableDeclarationOrBindingElement(declaration)) { + return anyType; + } + // Handle export default expressions + if (ts.isSourceFile(declaration)) { + var jsonSourceFile = ts.cast(declaration, ts.isJsonSourceFile); + if (!jsonSourceFile.statements.length) { + return emptyObjectType; + } + var type_1 = getWidenedLiteralType(checkExpression(jsonSourceFile.statements[0].expression)); + if (type_1.flags & 524288 /* Object */) { + return getRegularTypeOfObjectLiteral(type_1); + } + return type_1; + } + if (declaration.kind === 254 /* ExportAssignment */) { + return widenTypeForVariableLikeDeclaration(checkExpressionCached(declaration.expression), declaration); + } + // Handle variable, parameter or property + if (!pushTypeResolution(symbol, 0 /* Type */)) { + return errorType; + } + var type; + if (ts.isInJSFile(declaration) && + (ts.isCallExpression(declaration) || ts.isBinaryExpression(declaration) || ts.isPropertyAccessExpression(declaration) && ts.isBinaryExpression(declaration.parent))) { + type = getWidenedTypeFromAssignmentDeclaration(symbol); + } + else if (ts.isJSDocPropertyLikeTag(declaration) + || ts.isPropertyAccessExpression(declaration) + || ts.isIdentifier(declaration) + || ts.isClassDeclaration(declaration) + || ts.isFunctionDeclaration(declaration) + || (ts.isMethodDeclaration(declaration) && !ts.isObjectLiteralMethod(declaration)) + || ts.isMethodSignature(declaration)) { + // Symbol is property of some kind that is merged with something - should use `getTypeOfFuncClassEnumModule` and not `getTypeOfVariableOrParameterOrProperty` + if (symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 384 /* Enum */ | 512 /* ValueModule */)) { + return getTypeOfFuncClassEnumModule(symbol); + } + type = ts.isBinaryExpression(declaration.parent) ? + getWidenedTypeFromAssignmentDeclaration(symbol) : + tryGetTypeFromEffectiveTypeNode(declaration) || anyType; + } + else if (ts.isPropertyAssignment(declaration)) { + type = tryGetTypeFromEffectiveTypeNode(declaration) || checkPropertyAssignment(declaration); + } + else if (ts.isJsxAttribute(declaration)) { + type = tryGetTypeFromEffectiveTypeNode(declaration) || checkJsxAttribute(declaration); + } + else if (ts.isShorthandPropertyAssignment(declaration)) { + type = tryGetTypeFromEffectiveTypeNode(declaration) || checkExpressionForMutableLocation(declaration.name, 0 /* Normal */); + } + else if (ts.isObjectLiteralMethod(declaration)) { + type = tryGetTypeFromEffectiveTypeNode(declaration) || checkObjectLiteralMethod(declaration, 0 /* Normal */); + } + else if (ts.isParameter(declaration) + || ts.isPropertyDeclaration(declaration) + || ts.isPropertySignature(declaration) + || ts.isVariableDeclaration(declaration) + || ts.isBindingElement(declaration)) { + type = getWidenedTypeForVariableLikeDeclaration(declaration, /*includeOptionality*/ true); + } + // getTypeOfSymbol dispatches some JS merges incorrectly because their symbol flags are not mutually exclusive. + // Re-dispatch based on valueDeclaration.kind instead. + else if (ts.isEnumDeclaration(declaration)) { + type = getTypeOfFuncClassEnumModule(symbol); + } + else if (ts.isEnumMember(declaration)) { + type = getTypeOfEnumMember(symbol); + } + else { + return ts.Debug.fail("Unhandled declaration kind! " + ts.Debug.showSyntaxKind(declaration) + " for " + ts.Debug.showSymbol(symbol)); + } + if (!popTypeResolution()) { + type = reportCircularityError(symbol); + } + return type; + } + function getAnnotatedAccessorTypeNode(accessor) { + if (accessor) { + if (accessor.kind === 158 /* GetAccessor */) { + var getterTypeAnnotation = ts.getEffectiveReturnTypeNode(accessor); + return getterTypeAnnotation; + } + else { + var setterTypeAnnotation = ts.getEffectiveSetAccessorTypeAnnotationNode(accessor); + return setterTypeAnnotation; + } + } + return undefined; + } + function getAnnotatedAccessorType(accessor) { + var node = getAnnotatedAccessorTypeNode(accessor); + return node && getTypeFromTypeNode(node); + } + function getAnnotatedAccessorThisParameter(accessor) { + var parameter = getAccessorThisParameter(accessor); + return parameter && parameter.symbol; + } + function getThisTypeOfDeclaration(declaration) { + return getThisTypeOfSignature(getSignatureFromDeclaration(declaration)); + } + function getTypeOfAccessors(symbol) { + var links = getSymbolLinks(symbol); + return links.type || (links.type = getTypeOfAccessorsWorker(symbol)); + } + function getTypeOfAccessorsWorker(symbol) { + var getter = ts.getDeclarationOfKind(symbol, 158 /* GetAccessor */); + var setter = ts.getDeclarationOfKind(symbol, 159 /* SetAccessor */); + if (getter && ts.isInJSFile(getter)) { + var jsDocType = getTypeForDeclarationFromJSDocComment(getter); + if (jsDocType) { + return jsDocType; + } + } + if (!pushTypeResolution(symbol, 0 /* Type */)) { + return errorType; + } + var type; + // First try to see if the user specified a return type on the get-accessor. + var getterReturnType = getAnnotatedAccessorType(getter); + if (getterReturnType) { + type = getterReturnType; + } + else { + // If the user didn't specify a return type, try to use the set-accessor's parameter type. + var setterParameterType = getAnnotatedAccessorType(setter); + if (setterParameterType) { + type = setterParameterType; + } + else { + // If there are no specified types, try to infer it from the body of the get accessor if it exists. + if (getter && getter.body) { + type = getReturnTypeFromBody(getter); + } + // Otherwise, fall back to 'any'. + else { + if (setter) { + errorOrSuggestion(noImplicitAny, setter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation, symbolToString(symbol)); + } + else { + ts.Debug.assert(!!getter, "there must existed getter as we are current checking either setter or getter in this function"); + errorOrSuggestion(noImplicitAny, getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); + } + type = anyType; + } + } + } + if (!popTypeResolution()) { + type = anyType; + if (noImplicitAny) { + var getter_1 = ts.getDeclarationOfKind(symbol, 158 /* GetAccessor */); + error(getter_1, ts.Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, symbolToString(symbol)); + } + } + return type; + } + function getBaseTypeVariableOfClass(symbol) { + var baseConstructorType = getBaseConstructorTypeOfClass(getDeclaredTypeOfClassOrInterface(symbol)); + return baseConstructorType.flags & 8650752 /* TypeVariable */ ? baseConstructorType : undefined; + } + function getTypeOfFuncClassEnumModule(symbol) { + var links = getSymbolLinks(symbol); + var originalLinks = links; + if (!links.type) { + var jsDeclaration = ts.getDeclarationOfExpando(symbol.valueDeclaration); + if (jsDeclaration) { + var jsSymbol = getSymbolOfNode(jsDeclaration); + if (jsSymbol && (ts.hasEntries(jsSymbol.exports) || ts.hasEntries(jsSymbol.members))) { + symbol = cloneSymbol(symbol); + // note:we overwrite links because we just cloned the symbol + links = symbol; + if (ts.hasEntries(jsSymbol.exports)) { + symbol.exports = symbol.exports || ts.createSymbolTable(); + mergeSymbolTable(symbol.exports, jsSymbol.exports); + } + if (ts.hasEntries(jsSymbol.members)) { + symbol.members = symbol.members || ts.createSymbolTable(); + mergeSymbolTable(symbol.members, jsSymbol.members); + } + } + } + originalLinks.type = links.type = getTypeOfFuncClassEnumModuleWorker(symbol); + } + return links.type; + } + function getTypeOfFuncClassEnumModuleWorker(symbol) { + var declaration = symbol.valueDeclaration; + if (symbol.flags & 1536 /* Module */ && ts.isShorthandAmbientModuleSymbol(symbol)) { + return anyType; + } + else if (declaration.kind === 204 /* BinaryExpression */ || + declaration.kind === 189 /* PropertyAccessExpression */ && declaration.parent.kind === 204 /* BinaryExpression */) { + return getWidenedTypeFromAssignmentDeclaration(symbol); + } + else if (symbol.flags & 512 /* ValueModule */ && declaration && ts.isSourceFile(declaration) && declaration.commonJsModuleIndicator) { + var resolvedModule = resolveExternalModuleSymbol(symbol); + if (resolvedModule !== symbol) { + if (!pushTypeResolution(symbol, 0 /* Type */)) { + return errorType; + } + var exportEquals = getMergedSymbol(symbol.exports.get("export=" /* ExportEquals */)); + var type_2 = getWidenedTypeFromAssignmentDeclaration(exportEquals, exportEquals === resolvedModule ? undefined : resolvedModule); + if (!popTypeResolution()) { + return reportCircularityError(symbol); + } + return type_2; + } + } + var type = createObjectType(16 /* Anonymous */, symbol); + if (symbol.flags & 32 /* Class */) { + var baseTypeVariable = getBaseTypeVariableOfClass(symbol); + return baseTypeVariable ? getIntersectionType([type, baseTypeVariable]) : type; + } + else { + return strictNullChecks && symbol.flags & 16777216 /* Optional */ ? getOptionalType(type) : type; + } + } + function getTypeOfEnumMember(symbol) { + var links = getSymbolLinks(symbol); + return links.type || (links.type = getDeclaredTypeOfEnumMember(symbol)); + } + function getTypeOfAlias(symbol) { + var links = getSymbolLinks(symbol); + if (!links.type) { + var targetSymbol = resolveAlias(symbol); + // It only makes sense to get the type of a value symbol. If the result of resolving + // the alias is not a value, then it has no type. To get the type associated with a + // type symbol, call getDeclaredTypeOfSymbol. + // This check is important because without it, a call to getTypeOfSymbol could end + // up recursively calling getTypeOfAlias, causing a stack overflow. + links.type = targetSymbol.flags & 67220415 /* Value */ + ? getTypeOfSymbol(targetSymbol) + : errorType; + } + return links.type; + } + function getTypeOfInstantiatedSymbol(symbol) { + var links = getSymbolLinks(symbol); + if (!links.type) { + if (!pushTypeResolution(symbol, 0 /* Type */)) { + return links.type = errorType; + } + var type = instantiateType(getTypeOfSymbol(links.target), links.mapper); + if (!popTypeResolution()) { + type = reportCircularityError(symbol); + } + links.type = type; + } + return links.type; + } + function reportCircularityError(symbol) { + // Check if variable has type annotation that circularly references the variable itself + if (ts.getEffectiveTypeAnnotationNode(symbol.valueDeclaration)) { + error(symbol.valueDeclaration, ts.Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_type_annotation, symbolToString(symbol)); + return errorType; + } + // Otherwise variable has initializer that circularly references the variable itself + if (noImplicitAny) { + error(symbol.valueDeclaration, ts.Diagnostics._0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer, symbolToString(symbol)); + } + return anyType; + } + function getTypeOfSymbol(symbol) { + if (ts.getCheckFlags(symbol) & 1 /* Instantiated */) { + return getTypeOfInstantiatedSymbol(symbol); + } + if (ts.getCheckFlags(symbol) & 2048 /* ReverseMapped */) { + return getTypeOfReverseMappedSymbol(symbol); + } + if (symbol.flags & (3 /* Variable */ | 4 /* Property */)) { + return getTypeOfVariableOrParameterOrProperty(symbol); + } + if (symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 384 /* Enum */ | 512 /* ValueModule */)) { + return getTypeOfFuncClassEnumModule(symbol); + } + if (symbol.flags & 8 /* EnumMember */) { + return getTypeOfEnumMember(symbol); + } + if (symbol.flags & 98304 /* Accessor */) { + return getTypeOfAccessors(symbol); + } + if (symbol.flags & 2097152 /* Alias */) { + return getTypeOfAlias(symbol); + } + return errorType; + } + function isReferenceToType(type, target) { + return type !== undefined + && target !== undefined + && (ts.getObjectFlags(type) & 4 /* Reference */) !== 0 + && type.target === target; + } + function getTargetType(type) { + return ts.getObjectFlags(type) & 4 /* Reference */ ? type.target : type; + } + // TODO: GH#18217 If `checkBase` is undefined, we should not call this because this will always return false. + function hasBaseType(type, checkBase) { + return check(type); + function check(type) { + if (ts.getObjectFlags(type) & (3 /* ClassOrInterface */ | 4 /* Reference */)) { + var target = getTargetType(type); + return target === checkBase || ts.some(getBaseTypes(target), check); + } + else if (type.flags & 2097152 /* Intersection */) { + return ts.some(type.types, check); + } + return false; + } + } + // Appends the type parameters given by a list of declarations to a set of type parameters and returns the resulting set. + // The function allocates a new array if the input type parameter set is undefined, but otherwise it modifies the set + // in-place and returns the same array. + function appendTypeParameters(typeParameters, declarations) { + for (var _i = 0, declarations_2 = declarations; _i < declarations_2.length; _i++) { + var declaration = declarations_2[_i]; + typeParameters = ts.appendIfUnique(typeParameters, getDeclaredTypeOfTypeParameter(getSymbolOfNode(declaration))); + } + return typeParameters; + } + // Return the outer type parameters of a node or undefined if the node has no outer type parameters. + function getOuterTypeParameters(node, includeThisTypes) { + while (true) { + node = node.parent; // TODO: GH#18217 Use SourceFile kind check instead + if (!node) { + return undefined; + } + switch (node.kind) { + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 241 /* InterfaceDeclaration */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 155 /* MethodSignature */: + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + case 289 /* JSDocFunctionType */: + case 239 /* FunctionDeclaration */: + case 156 /* MethodDeclaration */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 242 /* TypeAliasDeclaration */: + case 303 /* JSDocTemplateTag */: + case 304 /* JSDocTypedefTag */: + case 297 /* JSDocCallbackTag */: + case 181 /* MappedType */: + case 175 /* ConditionalType */: + var outerTypeParameters = getOuterTypeParameters(node, includeThisTypes); + if (node.kind === 181 /* MappedType */) { + return ts.append(outerTypeParameters, getDeclaredTypeOfTypeParameter(getSymbolOfNode(node.typeParameter))); + } + else if (node.kind === 175 /* ConditionalType */) { + return ts.concatenate(outerTypeParameters, getInferTypeParameters(node)); + } + var outerAndOwnTypeParameters = appendTypeParameters(outerTypeParameters, ts.getEffectiveTypeParameterDeclarations(node)); + var thisType = includeThisTypes && + (node.kind === 240 /* ClassDeclaration */ || node.kind === 209 /* ClassExpression */ || node.kind === 241 /* InterfaceDeclaration */) && + getDeclaredTypeOfClassOrInterface(getSymbolOfNode(node)).thisType; + return thisType ? ts.append(outerAndOwnTypeParameters, thisType) : outerAndOwnTypeParameters; + } + } + } + // The outer type parameters are those defined by enclosing generic classes, methods, or functions. + function getOuterTypeParametersOfClassOrInterface(symbol) { + var declaration = symbol.flags & 32 /* Class */ ? symbol.valueDeclaration : ts.getDeclarationOfKind(symbol, 241 /* InterfaceDeclaration */); + return getOuterTypeParameters(declaration); + } + // The local type parameters are the combined set of type parameters from all declarations of the class, + // interface, or type alias. + function getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) { + var result; + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var node = _a[_i]; + if (node.kind === 241 /* InterfaceDeclaration */ || + node.kind === 240 /* ClassDeclaration */ || + node.kind === 209 /* ClassExpression */ || + ts.isTypeAlias(node)) { + var declaration = node; + result = appendTypeParameters(result, ts.getEffectiveTypeParameterDeclarations(declaration)); + } + } + return result; + } + // The full set of type parameters for a generic class or interface type consists of its outer type parameters plus + // its locally declared type parameters. + function getTypeParametersOfClassOrInterface(symbol) { + return ts.concatenate(getOuterTypeParametersOfClassOrInterface(symbol), getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol)); + } + // A type is a mixin constructor if it has a single construct signature taking no type parameters and a single + // rest parameter of type any[]. + function isMixinConstructorType(type) { + var signatures = getSignaturesOfType(type, 1 /* Construct */); + if (signatures.length === 1) { + var s = signatures[0]; + return !s.typeParameters && s.parameters.length === 1 && s.hasRestParameter && getTypeOfParameter(s.parameters[0]) === anyArrayType; + } + return false; + } + function isConstructorType(type) { + if (isValidBaseType(type) && getSignaturesOfType(type, 1 /* Construct */).length > 0) { + return true; + } + if (type.flags & 8650752 /* TypeVariable */) { + var constraint = getBaseConstraintOfType(type); + return !!constraint && isValidBaseType(constraint) && isMixinConstructorType(constraint); + } + return isJSConstructorType(type); + } + function getBaseTypeNodeOfClass(type) { + return ts.getEffectiveBaseTypeNode(type.symbol.valueDeclaration); + } + function getConstructorsForTypeArguments(type, typeArgumentNodes, location) { + var typeArgCount = ts.length(typeArgumentNodes); + var isJavascript = ts.isInJSFile(location); + return ts.filter(getSignaturesOfType(type, 1 /* Construct */), function (sig) { return (isJavascript || typeArgCount >= getMinTypeArgumentCount(sig.typeParameters)) && typeArgCount <= ts.length(sig.typeParameters); }); + } + function getInstantiatedConstructorsForTypeArguments(type, typeArgumentNodes, location) { + var signatures = getConstructorsForTypeArguments(type, typeArgumentNodes, location); + var typeArguments = ts.map(typeArgumentNodes, getTypeFromTypeNode); + return ts.sameMap(signatures, function (sig) { return ts.some(sig.typeParameters) ? getSignatureInstantiation(sig, typeArguments, ts.isInJSFile(location)) : sig; }); + } + /** + * The base constructor of a class can resolve to + * * undefinedType if the class has no extends clause, + * * unknownType if an error occurred during resolution of the extends expression, + * * nullType if the extends expression is the null value, + * * anyType if the extends expression has type any, or + * * an object type with at least one construct signature. + */ + function getBaseConstructorTypeOfClass(type) { + if (!type.resolvedBaseConstructorType) { + var decl = type.symbol.valueDeclaration; + var extended = ts.getEffectiveBaseTypeNode(decl); + var baseTypeNode = getBaseTypeNodeOfClass(type); + if (!baseTypeNode) { + return type.resolvedBaseConstructorType = undefinedType; + } + if (!pushTypeResolution(type, 1 /* ResolvedBaseConstructorType */)) { + return errorType; + } + var baseConstructorType = checkExpression(baseTypeNode.expression); + if (extended && baseTypeNode !== extended) { + ts.Debug.assert(!extended.typeArguments); // Because this is in a JS file, and baseTypeNode is in an @extends tag + checkExpression(extended.expression); + } + if (baseConstructorType.flags & (524288 /* Object */ | 2097152 /* Intersection */)) { + // Resolving the members of a class requires us to resolve the base class of that class. + // We force resolution here such that we catch circularities now. + resolveStructuredTypeMembers(baseConstructorType); + } + if (!popTypeResolution()) { + error(type.symbol.valueDeclaration, ts.Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_base_expression, symbolToString(type.symbol)); + return type.resolvedBaseConstructorType = errorType; + } + if (!(baseConstructorType.flags & 1 /* Any */) && baseConstructorType !== nullWideningType && !isConstructorType(baseConstructorType)) { + var err = error(baseTypeNode.expression, ts.Diagnostics.Type_0_is_not_a_constructor_function_type, typeToString(baseConstructorType)); + if (baseConstructorType.flags & 262144 /* TypeParameter */) { + var constraint = getConstraintFromTypeParameter(baseConstructorType); + var ctorReturn = unknownType; + if (constraint) { + var ctorSig = getSignaturesOfType(constraint, 1 /* Construct */); + if (ctorSig[0]) { + ctorReturn = getReturnTypeOfSignature(ctorSig[0]); + } + } + addRelatedInfo(err, ts.createDiagnosticForNode(baseConstructorType.symbol.declarations[0], ts.Diagnostics.Did_you_mean_for_0_to_be_constrained_to_type_new_args_Colon_any_1, symbolToString(baseConstructorType.symbol), typeToString(ctorReturn))); + } + return type.resolvedBaseConstructorType = errorType; + } + type.resolvedBaseConstructorType = baseConstructorType; + } + return type.resolvedBaseConstructorType; + } + function getBaseTypes(type) { + if (!type.resolvedBaseTypes) { + if (type.objectFlags & 8 /* Tuple */) { + type.resolvedBaseTypes = [createArrayType(getUnionType(type.typeParameters || ts.emptyArray))]; + } + else if (type.symbol.flags & (32 /* Class */ | 64 /* Interface */)) { + if (type.symbol.flags & 32 /* Class */) { + resolveBaseTypesOfClass(type); + } + if (type.symbol.flags & 64 /* Interface */) { + resolveBaseTypesOfInterface(type); + } + } + else { + ts.Debug.fail("type must be class or interface"); + } + } + return type.resolvedBaseTypes; + } + function resolveBaseTypesOfClass(type) { + type.resolvedBaseTypes = ts.resolvingEmptyArray; + var baseConstructorType = getApparentType(getBaseConstructorTypeOfClass(type)); + if (!(baseConstructorType.flags & (524288 /* Object */ | 2097152 /* Intersection */ | 1 /* Any */))) { + return type.resolvedBaseTypes = ts.emptyArray; + } + var baseTypeNode = getBaseTypeNodeOfClass(type); + var typeArgs = typeArgumentsFromTypeReferenceNode(baseTypeNode); + var baseType; + var originalBaseType = isJSConstructorType(baseConstructorType) ? baseConstructorType : + baseConstructorType.symbol ? getDeclaredTypeOfSymbol(baseConstructorType.symbol) : + undefined; + if (baseConstructorType.symbol && baseConstructorType.symbol.flags & 32 /* Class */ && + areAllOuterTypeParametersApplied(originalBaseType)) { + // When base constructor type is a class with no captured type arguments we know that the constructors all have the same type parameters as the + // class and all return the instance type of the class. There is no need for further checks and we can apply the + // type arguments in the same manner as a type reference to get the same error reporting experience. + baseType = getTypeFromClassOrInterfaceReference(baseTypeNode, baseConstructorType.symbol, typeArgs); + } + else if (baseConstructorType.flags & 1 /* Any */) { + baseType = baseConstructorType; + } + else if (isJSConstructorType(baseConstructorType)) { + baseType = !baseTypeNode.typeArguments && getJSClassType(baseConstructorType.symbol) || anyType; + } + else { + // The class derives from a "class-like" constructor function, check that we have at least one construct signature + // with a matching number of type parameters and use the return type of the first instantiated signature. Elsewhere + // we check that all instantiated signatures return the same type. + var constructors = getInstantiatedConstructorsForTypeArguments(baseConstructorType, baseTypeNode.typeArguments, baseTypeNode); + if (!constructors.length) { + error(baseTypeNode.expression, ts.Diagnostics.No_base_constructor_has_the_specified_number_of_type_arguments); + return type.resolvedBaseTypes = ts.emptyArray; + } + baseType = getReturnTypeOfSignature(constructors[0]); + } + if (baseType === errorType) { + return type.resolvedBaseTypes = ts.emptyArray; + } + if (!isValidBaseType(baseType)) { + error(baseTypeNode.expression, ts.Diagnostics.Base_constructor_return_type_0_is_not_an_object_type_or_intersection_of_object_types_with_statically_known_members, typeToString(baseType)); + return type.resolvedBaseTypes = ts.emptyArray; + } + if (type === baseType || hasBaseType(baseType, type)) { + error(type.symbol.valueDeclaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, /*enclosingDeclaration*/ undefined, 2 /* WriteArrayAsGenericType */)); + return type.resolvedBaseTypes = ts.emptyArray; + } + if (type.resolvedBaseTypes === ts.resolvingEmptyArray) { + // Circular reference, likely through instantiation of default parameters + // (otherwise there'd be an error from hasBaseType) - this is fine, but `.members` should be reset + // as `getIndexedAccessType` via `instantiateType` via `getTypeFromClassOrInterfaceReference` forces a + // partial instantiation of the members without the base types fully resolved + type.members = undefined; + } + return type.resolvedBaseTypes = [baseType]; + } + function areAllOuterTypeParametersApplied(type) { + // An unapplied type parameter has its symbol still the same as the matching argument symbol. + // Since parameters are applied outer-to-inner, only the last outer parameter needs to be checked. + var outerTypeParameters = type.outerTypeParameters; + if (outerTypeParameters) { + var last_1 = outerTypeParameters.length - 1; + var typeArguments = type.typeArguments; + return outerTypeParameters[last_1].symbol !== typeArguments[last_1].symbol; + } + return true; + } + // A valid base type is `any`, any non-generic object type or intersection of non-generic + // object types. + function isValidBaseType(type) { + return !!(type.flags & (524288 /* Object */ | 67108864 /* NonPrimitive */ | 1 /* Any */)) && !isGenericMappedType(type) || + !!(type.flags & 2097152 /* Intersection */) && ts.every(type.types, isValidBaseType); + } + function resolveBaseTypesOfInterface(type) { + type.resolvedBaseTypes = type.resolvedBaseTypes || ts.emptyArray; + for (var _i = 0, _a = type.symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (declaration.kind === 241 /* InterfaceDeclaration */ && ts.getInterfaceBaseTypeNodes(declaration)) { + for (var _b = 0, _c = ts.getInterfaceBaseTypeNodes(declaration); _b < _c.length; _b++) { + var node = _c[_b]; + var baseType = getTypeFromTypeNode(node); + if (baseType !== errorType) { + if (isValidBaseType(baseType)) { + if (type !== baseType && !hasBaseType(baseType, type)) { + if (type.resolvedBaseTypes === ts.emptyArray) { + type.resolvedBaseTypes = [baseType]; + } + else { + type.resolvedBaseTypes.push(baseType); + } + } + else { + error(declaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, /*enclosingDeclaration*/ undefined, 2 /* WriteArrayAsGenericType */)); + } + } + else { + error(node, ts.Diagnostics.An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_members); + } + } + } + } + } + } + /** + * Returns true if the interface given by the symbol is free of "this" references. + * + * Specifically, the result is true if the interface itself contains no references + * to "this" in its body, if all base types are interfaces, + * and if none of the base interfaces have a "this" type. + */ + function isThislessInterface(symbol) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (declaration.kind === 241 /* InterfaceDeclaration */) { + if (declaration.flags & 64 /* ContainsThis */) { + return false; + } + var baseTypeNodes = ts.getInterfaceBaseTypeNodes(declaration); + if (baseTypeNodes) { + for (var _b = 0, baseTypeNodes_1 = baseTypeNodes; _b < baseTypeNodes_1.length; _b++) { + var node = baseTypeNodes_1[_b]; + if (ts.isEntityNameExpression(node.expression)) { + var baseSymbol = resolveEntityName(node.expression, 67897832 /* Type */, /*ignoreErrors*/ true); + if (!baseSymbol || !(baseSymbol.flags & 64 /* Interface */) || getDeclaredTypeOfClassOrInterface(baseSymbol).thisType) { + return false; + } + } + } + } + } + } + return true; + } + function getDeclaredTypeOfClassOrInterface(symbol) { + var links = getSymbolLinks(symbol); + if (!links.declaredType) { + var kind = symbol.flags & 32 /* Class */ ? 1 /* Class */ : 2 /* Interface */; + var type = links.declaredType = createObjectType(kind, symbol); + var outerTypeParameters = getOuterTypeParametersOfClassOrInterface(symbol); + var localTypeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); + // A class or interface is generic if it has type parameters or a "this" type. We always give classes a "this" type + // because it is not feasible to analyze all members to determine if the "this" type escapes the class (in particular, + // property types inferred from initializers and method return types inferred from return statements are very hard + // to exhaustively analyze). We give interfaces a "this" type if we can't definitely determine that they are free of + // "this" references. + if (outerTypeParameters || localTypeParameters || kind === 1 /* Class */ || !isThislessInterface(symbol)) { + type.objectFlags |= 4 /* Reference */; + type.typeParameters = ts.concatenate(outerTypeParameters, localTypeParameters); + type.outerTypeParameters = outerTypeParameters; + type.localTypeParameters = localTypeParameters; + type.instantiations = ts.createMap(); + type.instantiations.set(getTypeListId(type.typeParameters), type); + type.target = type; + type.typeArguments = type.typeParameters; + type.thisType = createType(262144 /* TypeParameter */); + type.thisType.isThisType = true; + type.thisType.symbol = symbol; + type.thisType.constraint = type; + } + } + return links.declaredType; + } + function getDeclaredTypeOfTypeAlias(symbol) { + var links = getSymbolLinks(symbol); + if (!links.declaredType) { + // Note that we use the links object as the target here because the symbol object is used as the unique + // identity for resolution of the 'type' property in SymbolLinks. + if (!pushTypeResolution(symbol, 2 /* DeclaredType */)) { + return errorType; + } + var declaration = ts.find(symbol.declarations, function (d) { + return ts.isJSDocTypeAlias(d) || d.kind === 242 /* TypeAliasDeclaration */; + }); + var typeNode = ts.isJSDocTypeAlias(declaration) ? declaration.typeExpression : declaration.type; + // If typeNode is missing, we will error in checkJSDocTypedefTag. + var type = typeNode ? getTypeFromTypeNode(typeNode) : errorType; + if (popTypeResolution()) { + var typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); + if (typeParameters) { + // Initialize the instantiation cache for generic type aliases. The declared type corresponds to + // an instantiation of the type alias with the type parameters supplied as type arguments. + links.typeParameters = typeParameters; + links.instantiations = ts.createMap(); + links.instantiations.set(getTypeListId(typeParameters), type); + } + } + else { + type = errorType; + error(declaration.name, ts.Diagnostics.Type_alias_0_circularly_references_itself, symbolToString(symbol)); + } + links.declaredType = type; + } + return links.declaredType; + } + function isStringConcatExpression(expr) { + if (expr.kind === 10 /* StringLiteral */) { + return true; + } + else if (expr.kind === 204 /* BinaryExpression */) { + return isStringConcatExpression(expr.left) && isStringConcatExpression(expr.right); + } + return false; + } + function isLiteralEnumMember(member) { + var expr = member.initializer; + if (!expr) { + return !(member.flags & 4194304 /* Ambient */); + } + switch (expr.kind) { + case 10 /* StringLiteral */: + case 8 /* NumericLiteral */: + return true; + case 202 /* PrefixUnaryExpression */: + return expr.operator === 39 /* MinusToken */ && + expr.operand.kind === 8 /* NumericLiteral */; + case 72 /* Identifier */: + return ts.nodeIsMissing(expr) || !!getSymbolOfNode(member.parent).exports.get(expr.escapedText); + case 204 /* BinaryExpression */: + return isStringConcatExpression(expr); + default: + return false; + } + } + function getEnumKind(symbol) { + var links = getSymbolLinks(symbol); + if (links.enumKind !== undefined) { + return links.enumKind; + } + var hasNonLiteralMember = false; + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (declaration.kind === 243 /* EnumDeclaration */) { + for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { + var member = _c[_b]; + if (member.initializer && member.initializer.kind === 10 /* StringLiteral */) { + return links.enumKind = 1 /* Literal */; + } + if (!isLiteralEnumMember(member)) { + hasNonLiteralMember = true; + } + } + } + } + return links.enumKind = hasNonLiteralMember ? 0 /* Numeric */ : 1 /* Literal */; + } + function getBaseTypeOfEnumLiteralType(type) { + return type.flags & 1024 /* EnumLiteral */ && !(type.flags & 1048576 /* Union */) ? getDeclaredTypeOfSymbol(getParentOfSymbol(type.symbol)) : type; + } + function getDeclaredTypeOfEnum(symbol) { + var links = getSymbolLinks(symbol); + if (links.declaredType) { + return links.declaredType; + } + if (getEnumKind(symbol) === 1 /* Literal */) { + enumCount++; + var memberTypeList = []; + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (declaration.kind === 243 /* EnumDeclaration */) { + for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { + var member = _c[_b]; + var memberType = getFreshTypeOfLiteralType(getLiteralType(getEnumMemberValue(member), enumCount, getSymbolOfNode(member))); // TODO: GH#18217 + getSymbolLinks(getSymbolOfNode(member)).declaredType = memberType; + memberTypeList.push(getRegularTypeOfLiteralType(memberType)); + } + } + } + if (memberTypeList.length) { + var enumType_1 = getUnionType(memberTypeList, 1 /* Literal */, symbol, /*aliasTypeArguments*/ undefined); + if (enumType_1.flags & 1048576 /* Union */) { + enumType_1.flags |= 1024 /* EnumLiteral */; + enumType_1.symbol = symbol; + } + return links.declaredType = enumType_1; + } + } + var enumType = createType(32 /* Enum */); + enumType.symbol = symbol; + return links.declaredType = enumType; + } + function getDeclaredTypeOfEnumMember(symbol) { + var links = getSymbolLinks(symbol); + if (!links.declaredType) { + var enumType = getDeclaredTypeOfEnum(getParentOfSymbol(symbol)); + if (!links.declaredType) { + links.declaredType = enumType; + } + } + return links.declaredType; + } + function getDeclaredTypeOfTypeParameter(symbol) { + var links = getSymbolLinks(symbol); + if (!links.declaredType) { + var type = createType(262144 /* TypeParameter */); + type.symbol = symbol; + links.declaredType = type; + } + return links.declaredType; + } + function getDeclaredTypeOfAlias(symbol) { + var links = getSymbolLinks(symbol); + if (!links.declaredType) { + links.declaredType = getDeclaredTypeOfSymbol(resolveAlias(symbol)); + } + return links.declaredType; + } + function getDeclaredTypeOfSymbol(symbol) { + return tryGetDeclaredTypeOfSymbol(symbol) || errorType; + } + function tryGetDeclaredTypeOfSymbol(symbol) { + if (symbol.flags & (32 /* Class */ | 64 /* Interface */)) { + return getDeclaredTypeOfClassOrInterface(symbol); + } + if (symbol.flags & 524288 /* TypeAlias */) { + return getDeclaredTypeOfTypeAlias(symbol); + } + if (symbol.flags & 262144 /* TypeParameter */) { + return getDeclaredTypeOfTypeParameter(symbol); + } + if (symbol.flags & 384 /* Enum */) { + return getDeclaredTypeOfEnum(symbol); + } + if (symbol.flags & 8 /* EnumMember */) { + return getDeclaredTypeOfEnumMember(symbol); + } + if (symbol.flags & 2097152 /* Alias */) { + return getDeclaredTypeOfAlias(symbol); + } + return undefined; + } + /** + * A type is free of this references if it's the any, string, number, boolean, symbol, or void keyword, a string + * literal type, an array with an element type that is free of this references, or a type reference that is + * free of this references. + */ + function isThislessType(node) { + switch (node.kind) { + case 120 /* AnyKeyword */: + case 143 /* UnknownKeyword */: + case 138 /* StringKeyword */: + case 135 /* NumberKeyword */: + case 146 /* BigIntKeyword */: + case 123 /* BooleanKeyword */: + case 139 /* SymbolKeyword */: + case 136 /* ObjectKeyword */: + case 106 /* VoidKeyword */: + case 141 /* UndefinedKeyword */: + case 96 /* NullKeyword */: + case 132 /* NeverKeyword */: + case 182 /* LiteralType */: + return true; + case 169 /* ArrayType */: + return isThislessType(node.elementType); + case 164 /* TypeReference */: + return !node.typeArguments || node.typeArguments.every(isThislessType); + } + return false; + } + /** A type parameter is thisless if its contraint is thisless, or if it has no constraint. */ + function isThislessTypeParameter(node) { + var constraint = ts.getEffectiveConstraintOfTypeParameter(node); + return !constraint || isThislessType(constraint); + } + /** + * A variable-like declaration is free of this references if it has a type annotation + * that is thisless, or if it has no type annotation and no initializer (and is thus of type any). + */ + function isThislessVariableLikeDeclaration(node) { + var typeNode = ts.getEffectiveTypeAnnotationNode(node); + return typeNode ? isThislessType(typeNode) : !ts.hasInitializer(node); + } + /** + * A function-like declaration is considered free of `this` references if it has a return type + * annotation that is free of this references and if each parameter is thisless and if + * each type parameter (if present) is thisless. + */ + function isThislessFunctionLikeDeclaration(node) { + var returnType = ts.getEffectiveReturnTypeNode(node); + var typeParameters = ts.getEffectiveTypeParameterDeclarations(node); + return (node.kind === 157 /* Constructor */ || (!!returnType && isThislessType(returnType))) && + node.parameters.every(isThislessVariableLikeDeclaration) && + typeParameters.every(isThislessTypeParameter); + } + /** + * Returns true if the class or interface member given by the symbol is free of "this" references. The + * function may return false for symbols that are actually free of "this" references because it is not + * feasible to perform a complete analysis in all cases. In particular, property members with types + * inferred from their initializers and function members with inferred return types are conservatively + * assumed not to be free of "this" references. + */ + function isThisless(symbol) { + if (symbol.declarations && symbol.declarations.length === 1) { + var declaration = symbol.declarations[0]; + if (declaration) { + switch (declaration.kind) { + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + return isThislessVariableLikeDeclaration(declaration); + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 157 /* Constructor */: + return isThislessFunctionLikeDeclaration(declaration); + } + } + } + return false; + } + // The mappingThisOnly flag indicates that the only type parameter being mapped is "this". When the flag is true, + // we check symbols to see if we can quickly conclude they are free of "this" references, thus needing no instantiation. + function createInstantiatedSymbolTable(symbols, mapper, mappingThisOnly) { + var result = ts.createSymbolTable(); + for (var _i = 0, symbols_2 = symbols; _i < symbols_2.length; _i++) { + var symbol = symbols_2[_i]; + result.set(symbol.escapedName, mappingThisOnly && isThisless(symbol) ? symbol : instantiateSymbol(symbol, mapper)); + } + return result; + } + function addInheritedMembers(symbols, baseSymbols) { + for (var _i = 0, baseSymbols_1 = baseSymbols; _i < baseSymbols_1.length; _i++) { + var s = baseSymbols_1[_i]; + if (!symbols.has(s.escapedName)) { + symbols.set(s.escapedName, s); + } + } + } + function resolveDeclaredMembers(type) { + if (!type.declaredProperties) { + var symbol = type.symbol; + var members = getMembersOfSymbol(symbol); + type.declaredProperties = getNamedMembers(members); + // Start with signatures at empty array in case of recursive types + type.declaredCallSignatures = ts.emptyArray; + type.declaredConstructSignatures = ts.emptyArray; + type.declaredCallSignatures = getSignaturesOfSymbol(members.get("__call" /* Call */)); + type.declaredConstructSignatures = getSignaturesOfSymbol(members.get("__new" /* New */)); + type.declaredStringIndexInfo = getIndexInfoOfSymbol(symbol, 0 /* String */); + type.declaredNumberIndexInfo = getIndexInfoOfSymbol(symbol, 1 /* Number */); + } + return type; + } + /** + * Indicates whether a type can be used as a late-bound name. + */ + function isTypeUsableAsLateBoundName(type) { + return !!(type.flags & 8576 /* StringOrNumberLiteralOrUnique */); + } + /** + * Indicates whether a declaration name is definitely late-bindable. + * A declaration name is only late-bindable if: + * - It is a `ComputedPropertyName`. + * - Its expression is an `Identifier` or either a `PropertyAccessExpression` an + * `ElementAccessExpression` consisting only of these same three types of nodes. + * - The type of its expression is a string or numeric literal type, or is a `unique symbol` type. + */ + function isLateBindableName(node) { + return ts.isComputedPropertyName(node) + && ts.isEntityNameExpression(node.expression) + && isTypeUsableAsLateBoundName(checkComputedPropertyName(node)); + } + function isLateBoundName(name) { + return name.charCodeAt(0) === 95 /* _ */ && + name.charCodeAt(1) === 95 /* _ */ && + name.charCodeAt(2) === 64 /* at */; + } + /** + * Indicates whether a declaration has a late-bindable dynamic name. + */ + function hasLateBindableName(node) { + var name = ts.getNameOfDeclaration(node); + return !!name && isLateBindableName(name); + } + /** + * Indicates whether a declaration has a dynamic name that cannot be late-bound. + */ + function hasNonBindableDynamicName(node) { + return ts.hasDynamicName(node) && !hasLateBindableName(node); + } + /** + * Indicates whether a declaration name is a dynamic name that cannot be late-bound. + */ + function isNonBindableDynamicName(node) { + return ts.isDynamicName(node) && !isLateBindableName(node); + } + /** + * Gets the symbolic name for a late-bound member from its type. + */ + function getLateBoundNameFromType(type) { + if (type.flags & 8192 /* UniqueESSymbol */) { + return "__@" + type.symbol.escapedName + "@" + getSymbolId(type.symbol); + } + if (type.flags & (128 /* StringLiteral */ | 256 /* NumberLiteral */)) { + return ts.escapeLeadingUnderscores("" + type.value); + } + return ts.Debug.fail(); + } + /** + * Adds a declaration to a late-bound dynamic member. This performs the same function for + * late-bound members that `addDeclarationToSymbol` in binder.ts performs for early-bound + * members. + */ + function addDeclarationToLateBoundSymbol(symbol, member, symbolFlags) { + ts.Debug.assert(!!(ts.getCheckFlags(symbol) & 1024 /* Late */), "Expected a late-bound symbol."); + symbol.flags |= symbolFlags; + getSymbolLinks(member.symbol).lateSymbol = symbol; + if (!symbol.declarations) { + symbol.declarations = [member]; + } + else { + symbol.declarations.push(member); + } + if (symbolFlags & 67220415 /* Value */) { + if (!symbol.valueDeclaration || symbol.valueDeclaration.kind !== member.kind) { + symbol.valueDeclaration = member; + } + } + } + /** + * Performs late-binding of a dynamic member. This performs the same function for + * late-bound members that `declareSymbol` in binder.ts performs for early-bound + * members. + * + * If a symbol is a dynamic name from a computed property, we perform an additional "late" + * binding phase to attempt to resolve the name for the symbol from the type of the computed + * property's expression. If the type of the expression is a string-literal, numeric-literal, + * or unique symbol type, we can use that type as the name of the symbol. + * + * For example, given: + * + * const x = Symbol(); + * + * interface I { + * [x]: number; + * } + * + * The binder gives the property `[x]: number` a special symbol with the name "__computed". + * In the late-binding phase we can type-check the expression `x` and see that it has a + * unique symbol type which we can then use as the name of the member. This allows users + * to define custom symbols that can be used in the members of an object type. + * + * @param parent The containing symbol for the member. + * @param earlySymbols The early-bound symbols of the parent. + * @param lateSymbols The late-bound symbols of the parent. + * @param decl The member to bind. + */ + function lateBindMember(parent, earlySymbols, lateSymbols, decl) { + ts.Debug.assert(!!decl.symbol, "The member is expected to have a symbol."); + var links = getNodeLinks(decl); + if (!links.resolvedSymbol) { + // In the event we attempt to resolve the late-bound name of this member recursively, + // fall back to the early-bound name of this member. + links.resolvedSymbol = decl.symbol; + var type = checkComputedPropertyName(decl.name); + if (isTypeUsableAsLateBoundName(type)) { + var memberName = getLateBoundNameFromType(type); + var symbolFlags = decl.symbol.flags; + // Get or add a late-bound symbol for the member. This allows us to merge late-bound accessor declarations. + var lateSymbol = lateSymbols.get(memberName); + if (!lateSymbol) + lateSymbols.set(memberName, lateSymbol = createSymbol(0 /* None */, memberName, 1024 /* Late */)); + // Report an error if a late-bound member has the same name as an early-bound member, + // or if we have another early-bound symbol declaration with the same name and + // conflicting flags. + var earlySymbol = earlySymbols && earlySymbols.get(memberName); + if (lateSymbol.flags & getExcludedSymbolFlags(symbolFlags) || earlySymbol) { + // If we have an existing early-bound member, combine its declarations so that we can + // report an error at each declaration. + var declarations = earlySymbol ? ts.concatenate(earlySymbol.declarations, lateSymbol.declarations) : lateSymbol.declarations; + var name_2 = ts.declarationNameToString(decl.name); + ts.forEach(declarations, function (declaration) { return error(ts.getNameOfDeclaration(declaration) || declaration, ts.Diagnostics.Duplicate_declaration_0, name_2); }); + error(decl.name || decl, ts.Diagnostics.Duplicate_declaration_0, name_2); + lateSymbol = createSymbol(0 /* None */, memberName, 1024 /* Late */); + } + lateSymbol.nameType = type; + addDeclarationToLateBoundSymbol(lateSymbol, decl, symbolFlags); + if (lateSymbol.parent) { + ts.Debug.assert(lateSymbol.parent === parent, "Existing symbol parent should match new one"); + } + else { + lateSymbol.parent = parent; + } + return links.resolvedSymbol = lateSymbol; + } + } + return links.resolvedSymbol; + } + function getResolvedMembersOrExportsOfSymbol(symbol, resolutionKind) { + var links = getSymbolLinks(symbol); + if (!links[resolutionKind]) { + var isStatic = resolutionKind === "resolvedExports" /* resolvedExports */; + var earlySymbols = !isStatic ? symbol.members : + symbol.flags & 1536 /* Module */ ? getExportsOfModuleWorker(symbol) : + symbol.exports; + // In the event we recursively resolve the members/exports of the symbol, we + // set the initial value of resolvedMembers/resolvedExports to the early-bound + // members/exports of the symbol. + links[resolutionKind] = earlySymbols || emptySymbols; + // fill in any as-yet-unresolved late-bound members. + var lateSymbols = ts.createSymbolTable(); + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + var members = ts.getMembersOfDeclaration(decl); + if (members) { + for (var _b = 0, members_4 = members; _b < members_4.length; _b++) { + var member = members_4[_b]; + if (isStatic === ts.hasStaticModifier(member) && hasLateBindableName(member)) { + lateBindMember(symbol, earlySymbols, lateSymbols, member); + } + } + } + } + links[resolutionKind] = combineSymbolTables(earlySymbols, lateSymbols) || emptySymbols; + } + return links[resolutionKind]; + } + /** + * Gets a SymbolTable containing both the early- and late-bound members of a symbol. + * + * For a description of late-binding, see `lateBindMember`. + */ + function getMembersOfSymbol(symbol) { + return symbol.flags & 6240 /* LateBindingContainer */ + ? getResolvedMembersOrExportsOfSymbol(symbol, "resolvedMembers" /* resolvedMembers */) + : symbol.members || emptySymbols; + } + /** + * If a symbol is the dynamic name of the member of an object type, get the late-bound + * symbol of the member. + * + * For a description of late-binding, see `lateBindMember`. + */ + function getLateBoundSymbol(symbol) { + if (symbol.flags & 106500 /* ClassMember */ && symbol.escapedName === "__computed" /* Computed */) { + var links = getSymbolLinks(symbol); + if (!links.lateSymbol && ts.some(symbol.declarations, hasLateBindableName)) { + // force late binding of members/exports. This will set the late-bound symbol + if (ts.some(symbol.declarations, ts.hasStaticModifier)) { + getExportsOfSymbol(symbol.parent); + } + else { + getMembersOfSymbol(symbol.parent); + } + } + return links.lateSymbol || (links.lateSymbol = symbol); + } + return symbol; + } + function getTypeWithThisArgument(type, thisArgument, needApparentType) { + if (ts.getObjectFlags(type) & 4 /* Reference */) { + var target = type.target; + var typeArguments = type.typeArguments; + if (ts.length(target.typeParameters) === ts.length(typeArguments)) { + var ref = createTypeReference(target, ts.concatenate(typeArguments, [thisArgument || target.thisType])); + return needApparentType ? getApparentType(ref) : ref; + } + } + else if (type.flags & 2097152 /* Intersection */) { + return getIntersectionType(ts.map(type.types, function (t) { return getTypeWithThisArgument(t, thisArgument, needApparentType); })); + } + return needApparentType ? getApparentType(type) : type; + } + function resolveObjectTypeMembers(type, source, typeParameters, typeArguments) { + var mapper; + var members; + var callSignatures; + var constructSignatures; + var stringIndexInfo; + var numberIndexInfo; + if (ts.rangeEquals(typeParameters, typeArguments, 0, typeParameters.length)) { + mapper = identityMapper; + members = source.symbol ? getMembersOfSymbol(source.symbol) : ts.createSymbolTable(source.declaredProperties); + callSignatures = source.declaredCallSignatures; + constructSignatures = source.declaredConstructSignatures; + stringIndexInfo = source.declaredStringIndexInfo; + numberIndexInfo = source.declaredNumberIndexInfo; + } + else { + mapper = createTypeMapper(typeParameters, typeArguments); + members = createInstantiatedSymbolTable(source.declaredProperties, mapper, /*mappingThisOnly*/ typeParameters.length === 1); + callSignatures = instantiateSignatures(source.declaredCallSignatures, mapper); + constructSignatures = instantiateSignatures(source.declaredConstructSignatures, mapper); + stringIndexInfo = instantiateIndexInfo(source.declaredStringIndexInfo, mapper); + numberIndexInfo = instantiateIndexInfo(source.declaredNumberIndexInfo, mapper); + } + var baseTypes = getBaseTypes(source); + if (baseTypes.length) { + if (source.symbol && members === getMembersOfSymbol(source.symbol)) { + members = ts.createSymbolTable(source.declaredProperties); + } + setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + var thisArgument = ts.lastOrUndefined(typeArguments); + for (var _i = 0, baseTypes_1 = baseTypes; _i < baseTypes_1.length; _i++) { + var baseType = baseTypes_1[_i]; + var instantiatedBaseType = thisArgument ? getTypeWithThisArgument(instantiateType(baseType, mapper), thisArgument) : baseType; + addInheritedMembers(members, getPropertiesOfType(instantiatedBaseType)); + callSignatures = ts.concatenate(callSignatures, getSignaturesOfType(instantiatedBaseType, 0 /* Call */)); + constructSignatures = ts.concatenate(constructSignatures, getSignaturesOfType(instantiatedBaseType, 1 /* Construct */)); + if (!stringIndexInfo) { + stringIndexInfo = instantiatedBaseType === anyType ? + createIndexInfo(anyType, /*isReadonly*/ false) : + getIndexInfoOfType(instantiatedBaseType, 0 /* String */); + } + numberIndexInfo = numberIndexInfo || getIndexInfoOfType(instantiatedBaseType, 1 /* Number */); + } + } + setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + } + function resolveClassOrInterfaceMembers(type) { + resolveObjectTypeMembers(type, resolveDeclaredMembers(type), ts.emptyArray, ts.emptyArray); + } + function resolveTypeReferenceMembers(type) { + var source = resolveDeclaredMembers(type.target); + var typeParameters = ts.concatenate(source.typeParameters, [source.thisType]); + var typeArguments = type.typeArguments && type.typeArguments.length === typeParameters.length ? + type.typeArguments : ts.concatenate(type.typeArguments, [type]); + resolveObjectTypeMembers(type, source, typeParameters, typeArguments); + } + function createSignature(declaration, typeParameters, thisParameter, parameters, resolvedReturnType, resolvedTypePredicate, minArgumentCount, hasRestParameter, hasLiteralTypes) { + var sig = new Signature(checker); + sig.declaration = declaration; + sig.typeParameters = typeParameters; + sig.parameters = parameters; + sig.thisParameter = thisParameter; + sig.resolvedReturnType = resolvedReturnType; + sig.resolvedTypePredicate = resolvedTypePredicate; + sig.minArgumentCount = minArgumentCount; + sig.hasRestParameter = hasRestParameter; + sig.hasLiteralTypes = hasLiteralTypes; + sig.target = undefined; + sig.mapper = undefined; + return sig; + } + function cloneSignature(sig) { + return createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, /*resolvedReturnType*/ undefined, + /*resolvedTypePredicate*/ undefined, sig.minArgumentCount, sig.hasRestParameter, sig.hasLiteralTypes); + } + function getExpandedParameters(sig) { + if (sig.hasRestParameter) { + var restIndex_1 = sig.parameters.length - 1; + var restParameter = sig.parameters[restIndex_1]; + var restType = getTypeOfSymbol(restParameter); + if (isTupleType(restType)) { + var elementTypes = restType.typeArguments || ts.emptyArray; + var minLength_1 = restType.target.minLength; + var tupleRestIndex_1 = restType.target.hasRestElement ? elementTypes.length - 1 : -1; + var restParams = ts.map(elementTypes, function (t, i) { + var name = getParameterNameAtPosition(sig, restIndex_1 + i); + var checkFlags = i === tupleRestIndex_1 ? 8192 /* RestParameter */ : + i >= minLength_1 ? 4096 /* OptionalParameter */ : 0; + var symbol = createSymbol(1 /* FunctionScopedVariable */, name, checkFlags); + symbol.type = i === tupleRestIndex_1 ? createArrayType(t) : t; + return symbol; + }); + return ts.concatenate(sig.parameters.slice(0, restIndex_1), restParams); + } + } + return sig.parameters; + } + function getDefaultConstructSignatures(classType) { + var baseConstructorType = getBaseConstructorTypeOfClass(classType); + var baseSignatures = getSignaturesOfType(baseConstructorType, 1 /* Construct */); + if (baseSignatures.length === 0) { + return [createSignature(undefined, classType.localTypeParameters, undefined, ts.emptyArray, classType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false)]; // TODO: GH#18217 + } + var baseTypeNode = getBaseTypeNodeOfClass(classType); + var isJavaScript = ts.isInJSFile(baseTypeNode); + var typeArguments = typeArgumentsFromTypeReferenceNode(baseTypeNode); + var typeArgCount = ts.length(typeArguments); + var result = []; + for (var _i = 0, baseSignatures_1 = baseSignatures; _i < baseSignatures_1.length; _i++) { + var baseSig = baseSignatures_1[_i]; + var minTypeArgumentCount = getMinTypeArgumentCount(baseSig.typeParameters); + var typeParamCount = ts.length(baseSig.typeParameters); + if (isJavaScript || typeArgCount >= minTypeArgumentCount && typeArgCount <= typeParamCount) { + var sig = typeParamCount ? createSignatureInstantiation(baseSig, fillMissingTypeArguments(typeArguments, baseSig.typeParameters, minTypeArgumentCount, isJavaScript)) : cloneSignature(baseSig); + sig.typeParameters = classType.localTypeParameters; + sig.resolvedReturnType = classType; + result.push(sig); + } + } + return result; + } + function findMatchingSignature(signatureList, signature, partialMatch, ignoreThisTypes, ignoreReturnTypes) { + for (var _i = 0, signatureList_1 = signatureList; _i < signatureList_1.length; _i++) { + var s = signatureList_1[_i]; + if (compareSignaturesIdentical(s, signature, partialMatch, ignoreThisTypes, ignoreReturnTypes, partialMatch ? compareTypesSubtypeOf : compareTypesIdentical)) { + return s; + } + } + } + function findMatchingSignatures(signatureLists, signature, listIndex) { + if (signature.typeParameters) { + // We require an exact match for generic signatures, so we only return signatures from the first + // signature list and only if they have exact matches in the other signature lists. + if (listIndex > 0) { + return undefined; + } + for (var i = 1; i < signatureLists.length; i++) { + if (!findMatchingSignature(signatureLists[i], signature, /*partialMatch*/ false, /*ignoreThisTypes*/ false, /*ignoreReturnTypes*/ false)) { + return undefined; + } + } + return [signature]; + } + var result; + for (var i = 0; i < signatureLists.length; i++) { + // Allow matching non-generic signatures to have excess parameters and different return types + var match = i === listIndex ? signature : findMatchingSignature(signatureLists[i], signature, /*partialMatch*/ true, /*ignoreThisTypes*/ true, /*ignoreReturnTypes*/ true); + if (!match) { + return undefined; + } + result = ts.appendIfUnique(result, match); + } + return result; + } + // The signatures of a union type are those signatures that are present in each of the constituent types. + // Generic signatures must match exactly, but non-generic signatures are allowed to have extra optional + // parameters and may differ in return types. When signatures differ in return types, the resulting return + // type is the union of the constituent return types. + function getUnionSignatures(signatureLists) { + var result; + for (var i = 0; i < signatureLists.length; i++) { + for (var _i = 0, _a = signatureLists[i]; _i < _a.length; _i++) { + var signature = _a[_i]; + // Only process signatures with parameter lists that aren't already in the result list + if (!result || !findMatchingSignature(result, signature, /*partialMatch*/ false, /*ignoreThisTypes*/ true, /*ignoreReturnTypes*/ true)) { + var unionSignatures = findMatchingSignatures(signatureLists, signature, i); + if (unionSignatures) { + var s = signature; + // Union the result types when more than one signature matches + if (unionSignatures.length > 1) { + var thisParameter = signature.thisParameter; + if (ts.forEach(unionSignatures, function (sig) { return sig.thisParameter; })) { + // TODO: GH#18217 We tested that *some* has thisParameter and now act as if *all* do + var thisType = getUnionType(ts.map(unionSignatures, function (sig) { return sig.thisParameter ? getTypeOfSymbol(sig.thisParameter) : anyType; }), 2 /* Subtype */); + thisParameter = createSymbolWithType(signature.thisParameter, thisType); + } + s = cloneSignature(signature); + s.thisParameter = thisParameter; + s.unionSignatures = unionSignatures; + } + (result || (result = [])).push(s); + } + } + } + } + return result || ts.emptyArray; + } + function getUnionIndexInfo(types, kind) { + var indexTypes = []; + var isAnyReadonly = false; + for (var _i = 0, types_2 = types; _i < types_2.length; _i++) { + var type = types_2[_i]; + var indexInfo = getIndexInfoOfType(type, kind); + if (!indexInfo) { + return undefined; + } + indexTypes.push(indexInfo.type); + isAnyReadonly = isAnyReadonly || indexInfo.isReadonly; + } + return createIndexInfo(getUnionType(indexTypes, 2 /* Subtype */), isAnyReadonly); + } + function resolveUnionTypeMembers(type) { + // The members and properties collections are empty for union types. To get all properties of a union + // type use getPropertiesOfType (only the language service uses this). + var callSignatures = getUnionSignatures(ts.map(type.types, function (t) { return getSignaturesOfType(t, 0 /* Call */); })); + var constructSignatures = getUnionSignatures(ts.map(type.types, function (t) { return getSignaturesOfType(t, 1 /* Construct */); })); + var stringIndexInfo = getUnionIndexInfo(type.types, 0 /* String */); + var numberIndexInfo = getUnionIndexInfo(type.types, 1 /* Number */); + setStructuredTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + } + function intersectTypes(type1, type2) { + return !type1 ? type2 : !type2 ? type1 : getIntersectionType([type1, type2]); + } + function intersectIndexInfos(info1, info2) { + return !info1 ? info2 : !info2 ? info1 : createIndexInfo(getIntersectionType([info1.type, info2.type]), info1.isReadonly && info2.isReadonly); + } + function unionSpreadIndexInfos(info1, info2) { + return info1 && info2 && createIndexInfo(getUnionType([info1.type, info2.type]), info1.isReadonly || info2.isReadonly); + } + function includeMixinType(type, types, index) { + var mixedTypes = []; + for (var i = 0; i < types.length; i++) { + if (i === index) { + mixedTypes.push(type); + } + else if (isMixinConstructorType(types[i])) { + mixedTypes.push(getReturnTypeOfSignature(getSignaturesOfType(types[i], 1 /* Construct */)[0])); + } + } + return getIntersectionType(mixedTypes); + } + function resolveIntersectionTypeMembers(type) { + // The members and properties collections are empty for intersection types. To get all properties of an + // intersection type use getPropertiesOfType (only the language service uses this). + var callSignatures = ts.emptyArray; + var constructSignatures = ts.emptyArray; + var stringIndexInfo; + var numberIndexInfo; + var types = type.types; + var mixinCount = ts.countWhere(types, isMixinConstructorType); + var _loop_5 = function (i) { + var t = type.types[i]; + // When an intersection type contains mixin constructor types, the construct signatures from + // those types are discarded and their return types are mixed into the return types of all + // other construct signatures in the intersection type. For example, the intersection type + // '{ new(...args: any[]) => A } & { new(s: string) => B }' has a single construct signature + // 'new(s: string) => A & B'. + if (mixinCount === 0 || mixinCount === types.length && i === 0 || !isMixinConstructorType(t)) { + var signatures = getSignaturesOfType(t, 1 /* Construct */); + if (signatures.length && mixinCount > 0) { + signatures = ts.map(signatures, function (s) { + var clone = cloneSignature(s); + clone.resolvedReturnType = includeMixinType(getReturnTypeOfSignature(s), types, i); + return clone; + }); + } + constructSignatures = ts.concatenate(constructSignatures, signatures); + } + callSignatures = ts.concatenate(callSignatures, getSignaturesOfType(t, 0 /* Call */)); + stringIndexInfo = intersectIndexInfos(stringIndexInfo, getIndexInfoOfType(t, 0 /* String */)); + numberIndexInfo = intersectIndexInfos(numberIndexInfo, getIndexInfoOfType(t, 1 /* Number */)); + }; + for (var i = 0; i < types.length; i++) { + _loop_5(i); + } + setStructuredTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + } + /** + * Converts an AnonymousType to a ResolvedType. + */ + function resolveAnonymousTypeMembers(type) { + var symbol = type.symbol; + if (type.target) { + setStructuredTypeMembers(type, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + var members = createInstantiatedSymbolTable(getPropertiesOfObjectType(type.target), type.mapper, /*mappingThisOnly*/ false); + var callSignatures = instantiateSignatures(getSignaturesOfType(type.target, 0 /* Call */), type.mapper); + var constructSignatures = instantiateSignatures(getSignaturesOfType(type.target, 1 /* Construct */), type.mapper); + var stringIndexInfo = instantiateIndexInfo(getIndexInfoOfType(type.target, 0 /* String */), type.mapper); + var numberIndexInfo = instantiateIndexInfo(getIndexInfoOfType(type.target, 1 /* Number */), type.mapper); + setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + } + else if (symbol.flags & 2048 /* TypeLiteral */) { + setStructuredTypeMembers(type, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + var members = getMembersOfSymbol(symbol); + var callSignatures = getSignaturesOfSymbol(members.get("__call" /* Call */)); + var constructSignatures = getSignaturesOfSymbol(members.get("__new" /* New */)); + var stringIndexInfo = getIndexInfoOfSymbol(symbol, 0 /* String */); + var numberIndexInfo = getIndexInfoOfSymbol(symbol, 1 /* Number */); + setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + } + else { + // Combinations of function, class, enum and module + var members = emptySymbols; + var stringIndexInfo = void 0; + if (symbol.exports) { + members = getExportsOfSymbol(symbol); + } + setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, undefined, undefined); + if (symbol.flags & 32 /* Class */) { + var classType = getDeclaredTypeOfClassOrInterface(symbol); + var baseConstructorType = getBaseConstructorTypeOfClass(classType); + if (baseConstructorType.flags & (524288 /* Object */ | 2097152 /* Intersection */ | 8650752 /* TypeVariable */)) { + members = ts.createSymbolTable(getNamedMembers(members)); + addInheritedMembers(members, getPropertiesOfType(baseConstructorType)); + } + else if (baseConstructorType === anyType) { + stringIndexInfo = createIndexInfo(anyType, /*isReadonly*/ false); + } + } + var numberIndexInfo = symbol.flags & 384 /* Enum */ ? enumNumberIndexInfo : undefined; + setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); + // We resolve the members before computing the signatures because a signature may use + // typeof with a qualified name expression that circularly references the type we are + // in the process of resolving (see issue #6072). The temporarily empty signature list + // will never be observed because a qualified name can't reference signatures. + if (symbol.flags & (16 /* Function */ | 8192 /* Method */)) { + type.callSignatures = getSignaturesOfSymbol(symbol); + type.constructSignatures = ts.filter(type.callSignatures, function (sig) { return isJSConstructor(sig.declaration); }); + } + // And likewise for construct signatures for classes + if (symbol.flags & 32 /* Class */) { + var classType = getDeclaredTypeOfClassOrInterface(symbol); + var constructSignatures = getSignaturesOfSymbol(symbol.members.get("__constructor" /* Constructor */)); + if (!constructSignatures.length) { + constructSignatures = getDefaultConstructSignatures(classType); + } + type.constructSignatures = constructSignatures; + } + } + } + function resolveReverseMappedTypeMembers(type) { + var indexInfo = getIndexInfoOfType(type.source, 0 /* String */); + var modifiers = getMappedTypeModifiers(type.mappedType); + var readonlyMask = modifiers & 1 /* IncludeReadonly */ ? false : true; + var optionalMask = modifiers & 4 /* IncludeOptional */ ? 0 : 16777216 /* Optional */; + var stringIndexInfo = indexInfo && createIndexInfo(inferReverseMappedType(indexInfo.type, type.mappedType, type.constraintType), readonlyMask && indexInfo.isReadonly); + var members = ts.createSymbolTable(); + for (var _i = 0, _a = getPropertiesOfType(type.source); _i < _a.length; _i++) { + var prop = _a[_i]; + var checkFlags = 2048 /* ReverseMapped */ | (readonlyMask && isReadonlySymbol(prop) ? 8 /* Readonly */ : 0); + var inferredProp = createSymbol(4 /* Property */ | prop.flags & optionalMask, prop.escapedName, checkFlags); + inferredProp.declarations = prop.declarations; + inferredProp.nameType = prop.nameType; + inferredProp.propertyType = getTypeOfSymbol(prop); + inferredProp.mappedType = type.mappedType; + inferredProp.constraintType = type.constraintType; + members.set(prop.escapedName, inferredProp); + } + setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, undefined); + } + /** Resolve the members of a mapped type { [P in K]: T } */ + function resolveMappedTypeMembers(type) { + var members = ts.createSymbolTable(); + var stringIndexInfo; + var numberIndexInfo; + // Resolve upfront such that recursive references see an empty object type. + setStructuredTypeMembers(type, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + // In { [P in K]: T }, we refer to P as the type parameter type, K as the constraint type, + // and T as the template type. + var typeParameter = getTypeParameterFromMappedType(type); + var constraintType = getConstraintTypeFromMappedType(type); + var templateType = getTemplateTypeFromMappedType(type.target || type); + var modifiersType = getApparentType(getModifiersTypeFromMappedType(type)); // The 'T' in 'keyof T' + var templateModifiers = getMappedTypeModifiers(type); + var include = keyofStringsOnly ? 128 /* StringLiteral */ : 8576 /* StringOrNumberLiteralOrUnique */; + if (isMappedTypeWithKeyofConstraintDeclaration(type)) { + // We have a { [P in keyof T]: X } + for (var _i = 0, _a = getPropertiesOfType(modifiersType); _i < _a.length; _i++) { + var prop = _a[_i]; + addMemberForKeyType(getLiteralTypeFromProperty(prop, include)); + } + if (modifiersType.flags & 1 /* Any */ || getIndexInfoOfType(modifiersType, 0 /* String */)) { + addMemberForKeyType(stringType); + } + if (!keyofStringsOnly && getIndexInfoOfType(modifiersType, 1 /* Number */)) { + addMemberForKeyType(numberType); + } + } + else { + // If the key type is a 'keyof X', obtain 'keyof C' where C is the base constraint of X. + // Then iterate over the constituents of the key type. + var iterationType = constraintType.flags & 4194304 /* Index */ ? getIndexType(getApparentType(constraintType.type)) : constraintType; + forEachType(iterationType, addMemberForKeyType); + } + setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); + function addMemberForKeyType(t) { + // Create a mapper from T to the current iteration type constituent. Then, if the + // mapped type is itself an instantiated type, combine the iteration mapper with the + // instantiation mapper. + var templateMapper = combineTypeMappers(type.mapper, createTypeMapper([typeParameter], [t])); + var propType = instantiateType(templateType, templateMapper); + // If the current iteration type constituent is a string literal type, create a property. + // Otherwise, for type string create a string index signature. + if (t.flags & 8576 /* StringOrNumberLiteralOrUnique */) { + var propName = getLateBoundNameFromType(t); + var modifiersProp = getPropertyOfType(modifiersType, propName); + var isOptional = !!(templateModifiers & 4 /* IncludeOptional */ || + !(templateModifiers & 8 /* ExcludeOptional */) && modifiersProp && modifiersProp.flags & 16777216 /* Optional */); + var isReadonly = !!(templateModifiers & 1 /* IncludeReadonly */ || + !(templateModifiers & 2 /* ExcludeReadonly */) && modifiersProp && isReadonlySymbol(modifiersProp)); + var prop = createSymbol(4 /* Property */ | (isOptional ? 16777216 /* Optional */ : 0), propName, isReadonly ? 8 /* Readonly */ : 0); + // When creating an optional property in strictNullChecks mode, if 'undefined' isn't assignable to the + // type, we include 'undefined' in the type. Similarly, when creating a non-optional property in strictNullChecks + // mode, if the underlying property is optional we remove 'undefined' from the type. + prop.type = strictNullChecks && isOptional && !isTypeAssignableTo(undefinedType, propType) ? getOptionalType(propType) : + strictNullChecks && !isOptional && modifiersProp && modifiersProp.flags & 16777216 /* Optional */ ? getTypeWithFacts(propType, 524288 /* NEUndefined */) : + propType; + if (modifiersProp) { + prop.syntheticOrigin = modifiersProp; + prop.declarations = modifiersProp.declarations; + } + prop.nameType = t; + members.set(propName, prop); + } + else if (t.flags & (1 /* Any */ | 4 /* String */)) { + stringIndexInfo = createIndexInfo(propType, !!(templateModifiers & 1 /* IncludeReadonly */)); + } + else if (t.flags & 8 /* Number */) { + numberIndexInfo = createIndexInfo(propType, !!(templateModifiers & 1 /* IncludeReadonly */)); + } + } + } + function getTypeParameterFromMappedType(type) { + return type.typeParameter || + (type.typeParameter = getDeclaredTypeOfTypeParameter(getSymbolOfNode(type.declaration.typeParameter))); + } + function getConstraintTypeFromMappedType(type) { + return type.constraintType || + (type.constraintType = getConstraintOfTypeParameter(getTypeParameterFromMappedType(type)) || errorType); + } + function getTemplateTypeFromMappedType(type) { + return type.templateType || + (type.templateType = type.declaration.type ? + instantiateType(addOptionality(getTypeFromTypeNode(type.declaration.type), !!(getMappedTypeModifiers(type) & 4 /* IncludeOptional */)), type.mapper || identityMapper) : + errorType); + } + function getConstraintDeclarationForMappedType(type) { + return ts.getEffectiveConstraintOfTypeParameter(type.declaration.typeParameter); + } + function isMappedTypeWithKeyofConstraintDeclaration(type) { + var constraintDeclaration = getConstraintDeclarationForMappedType(type); // TODO: GH#18217 + return constraintDeclaration.kind === 179 /* TypeOperator */ && + constraintDeclaration.operator === 129 /* KeyOfKeyword */; + } + function getModifiersTypeFromMappedType(type) { + if (!type.modifiersType) { + if (isMappedTypeWithKeyofConstraintDeclaration(type)) { + // If the constraint declaration is a 'keyof T' node, the modifiers type is T. We check + // AST nodes here because, when T is a non-generic type, the logic below eagerly resolves + // 'keyof T' to a literal union type and we can't recover T from that type. + type.modifiersType = instantiateType(getTypeFromTypeNode(getConstraintDeclarationForMappedType(type).type), type.mapper || identityMapper); + } + else { + // Otherwise, get the declared constraint type, and if the constraint type is a type parameter, + // get the constraint of that type parameter. If the resulting type is an indexed type 'keyof T', + // the modifiers type is T. Otherwise, the modifiers type is {}. + var declaredType = getTypeFromMappedTypeNode(type.declaration); + var constraint = getConstraintTypeFromMappedType(declaredType); + var extendedConstraint = constraint && constraint.flags & 262144 /* TypeParameter */ ? getConstraintOfTypeParameter(constraint) : constraint; + type.modifiersType = extendedConstraint && extendedConstraint.flags & 4194304 /* Index */ ? instantiateType(extendedConstraint.type, type.mapper || identityMapper) : emptyObjectType; + } + } + return type.modifiersType; + } + function getMappedTypeModifiers(type) { + var declaration = type.declaration; + return (declaration.readonlyToken ? declaration.readonlyToken.kind === 39 /* MinusToken */ ? 2 /* ExcludeReadonly */ : 1 /* IncludeReadonly */ : 0) | + (declaration.questionToken ? declaration.questionToken.kind === 39 /* MinusToken */ ? 8 /* ExcludeOptional */ : 4 /* IncludeOptional */ : 0); + } + function getMappedTypeOptionality(type) { + var modifiers = getMappedTypeModifiers(type); + return modifiers & 8 /* ExcludeOptional */ ? -1 : modifiers & 4 /* IncludeOptional */ ? 1 : 0; + } + function getCombinedMappedTypeOptionality(type) { + var optionality = getMappedTypeOptionality(type); + var modifiersType = getModifiersTypeFromMappedType(type); + return optionality || (isGenericMappedType(modifiersType) ? getMappedTypeOptionality(modifiersType) : 0); + } + function isPartialMappedType(type) { + return !!(ts.getObjectFlags(type) & 32 /* Mapped */ && getMappedTypeModifiers(type) & 4 /* IncludeOptional */); + } + function isGenericMappedType(type) { + return !!(ts.getObjectFlags(type) & 32 /* Mapped */) && isGenericIndexType(getConstraintTypeFromMappedType(type)); + } + function resolveStructuredTypeMembers(type) { + if (!type.members) { + if (type.flags & 524288 /* Object */) { + if (type.objectFlags & 4 /* Reference */) { + resolveTypeReferenceMembers(type); + } + else if (type.objectFlags & 3 /* ClassOrInterface */) { + resolveClassOrInterfaceMembers(type); + } + else if (type.objectFlags & 2048 /* ReverseMapped */) { + resolveReverseMappedTypeMembers(type); + } + else if (type.objectFlags & 16 /* Anonymous */) { + resolveAnonymousTypeMembers(type); + } + else if (type.objectFlags & 32 /* Mapped */) { + resolveMappedTypeMembers(type); + } + } + else if (type.flags & 1048576 /* Union */) { + resolveUnionTypeMembers(type); + } + else if (type.flags & 2097152 /* Intersection */) { + resolveIntersectionTypeMembers(type); + } + } + return type; + } + /** Return properties of an object type or an empty array for other types */ + function getPropertiesOfObjectType(type) { + if (type.flags & 524288 /* Object */) { + return resolveStructuredTypeMembers(type).properties; + } + return ts.emptyArray; + } + /** If the given type is an object type and that type has a property by the given name, + * return the symbol for that property. Otherwise return undefined. + */ + function getPropertyOfObjectType(type, name) { + if (type.flags & 524288 /* Object */) { + var resolved = resolveStructuredTypeMembers(type); + var symbol = resolved.members.get(name); + if (symbol && symbolIsValue(symbol)) { + return symbol; + } + } + } + function getPropertiesOfUnionOrIntersectionType(type) { + if (!type.resolvedProperties) { + var members = ts.createSymbolTable(); + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var current = _a[_i]; + for (var _b = 0, _c = getPropertiesOfType(current); _b < _c.length; _b++) { + var prop = _c[_b]; + if (!members.has(prop.escapedName)) { + var combinedProp = getPropertyOfUnionOrIntersectionType(type, prop.escapedName); + if (combinedProp) { + members.set(prop.escapedName, combinedProp); + } + } + } + // The properties of a union type are those that are present in all constituent types, so + // we only need to check the properties of the first type + if (type.flags & 1048576 /* Union */) { + break; + } + } + type.resolvedProperties = getNamedMembers(members); + } + return type.resolvedProperties; + } + function getPropertiesOfType(type) { + type = getApparentType(type); + return type.flags & 3145728 /* UnionOrIntersection */ ? + getPropertiesOfUnionOrIntersectionType(type) : + getPropertiesOfObjectType(type); + } + function isTypeInvalidDueToUnionDiscriminant(contextualType, obj) { + var list = obj.properties; + return list.some(function (property) { + var name = property.name && ts.getTextOfPropertyName(property.name); + var expected = name === undefined ? undefined : getTypeOfPropertyOfType(contextualType, name); + return !!expected && typeIsLiteralType(expected) && !isTypeIdenticalTo(getTypeOfNode(property), expected); + }); + } + function getAllPossiblePropertiesOfTypes(types) { + var unionType = getUnionType(types); + if (!(unionType.flags & 1048576 /* Union */)) { + return getAugmentedPropertiesOfType(unionType); + } + var props = ts.createSymbolTable(); + for (var _i = 0, types_3 = types; _i < types_3.length; _i++) { + var memberType = types_3[_i]; + for (var _a = 0, _b = getAugmentedPropertiesOfType(memberType); _a < _b.length; _a++) { + var escapedName = _b[_a].escapedName; + if (!props.has(escapedName)) { + var prop = createUnionOrIntersectionProperty(unionType, escapedName); + // May be undefined if the property is private + if (prop) + props.set(escapedName, prop); + } + } + } + return ts.arrayFrom(props.values()); + } + function getConstraintOfType(type) { + return type.flags & 262144 /* TypeParameter */ ? getConstraintOfTypeParameter(type) : + type.flags & 8388608 /* IndexedAccess */ ? getConstraintOfIndexedAccess(type) : + type.flags & 16777216 /* Conditional */ ? getConstraintOfConditionalType(type) : + getBaseConstraintOfType(type); + } + function getConstraintOfTypeParameter(typeParameter) { + return hasNonCircularBaseConstraint(typeParameter) ? getConstraintFromTypeParameter(typeParameter) : undefined; + } + function getConstraintOfIndexedAccess(type) { + var objectType = getConstraintOfType(type.objectType) || type.objectType; + if (objectType !== type.objectType) { + var constraint = getIndexedAccessType(objectType, type.indexType, /*accessNode*/ undefined, errorType); + if (constraint && constraint !== errorType) { + return constraint; + } + } + var baseConstraint = getBaseConstraintOfType(type); + return baseConstraint && baseConstraint !== type ? baseConstraint : undefined; + } + function getDefaultConstraintOfConditionalType(type) { + if (!type.resolvedDefaultConstraint) { + var rootTrueType = type.root.trueType; + var rootTrueConstraint = !(rootTrueType.flags & 33554432 /* Substitution */) + ? rootTrueType + : (rootTrueType.substitute).flags & 3 /* AnyOrUnknown */ + ? rootTrueType.typeVariable + : getIntersectionType([rootTrueType.substitute, rootTrueType.typeVariable]); + type.resolvedDefaultConstraint = getUnionType([instantiateType(rootTrueConstraint, type.combinedMapper || type.mapper), getFalseTypeFromConditionalType(type)]); + } + return type.resolvedDefaultConstraint; + } + function getConstraintOfDistributiveConditionalType(type) { + // Check if we have a conditional type of the form 'T extends U ? X : Y', where T is a constrained + // type parameter. If so, create an instantiation of the conditional type where T is replaced + // with its constraint. We do this because if the constraint is a union type it will be distributed + // over the conditional type and possibly reduced. For example, 'T extends undefined ? never : T' + // removes 'undefined' from T. + if (type.root.isDistributive) { + var simplified = getSimplifiedType(type.checkType); + var constraint = simplified === type.checkType ? getConstraintOfType(simplified) : simplified; + if (constraint) { + var mapper = makeUnaryTypeMapper(type.root.checkType, constraint); + var instantiated = getConditionalTypeInstantiation(type, combineTypeMappers(mapper, type.mapper)); + if (!(instantiated.flags & 131072 /* Never */)) { + return instantiated; + } + } + } + return undefined; + } + function getConstraintOfConditionalType(type) { + return getConstraintOfDistributiveConditionalType(type) || getDefaultConstraintOfConditionalType(type); + } + function getUnionConstraintOfIntersection(type, targetIsUnion) { + var constraints; + var hasDisjointDomainType = false; + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (t.flags & 63176704 /* Instantiable */) { + // We keep following constraints as long as we have an instantiable type that is known + // not to be circular or infinite (hence we stop on index access types). + var constraint = getConstraintOfType(t); + while (constraint && constraint.flags & (262144 /* TypeParameter */ | 4194304 /* Index */ | 16777216 /* Conditional */)) { + constraint = getConstraintOfType(constraint); + } + if (constraint) { + // A constraint that isn't a union type implies that the final type would be a non-union + // type as well. Since non-union constraints are of no interest, we can exit here. + if (!(constraint.flags & 1048576 /* Union */)) { + return undefined; + } + constraints = ts.append(constraints, constraint); + } + } + else if (t.flags & 67238908 /* DisjointDomains */) { + hasDisjointDomainType = true; + } + } + // If the target is a union type or if we are intersecting with types belonging to one of the + // disjoint domans, we may end up producing a constraint that hasn't been examined before. + if (constraints && (targetIsUnion || hasDisjointDomainType)) { + if (hasDisjointDomainType) { + // We add any types belong to one of the disjoint domans because they might cause the final + // intersection operation to reduce the union constraints. + for (var _b = 0, _c = type.types; _b < _c.length; _b++) { + var t = _c[_b]; + if (t.flags & 67238908 /* DisjointDomains */) { + constraints = ts.append(constraints, t); + } + } + } + return getIntersectionType(constraints); + } + return undefined; + } + function getBaseConstraintOfType(type) { + if (type.flags & (58982400 /* InstantiableNonPrimitive */ | 3145728 /* UnionOrIntersection */)) { + var constraint = getResolvedBaseConstraint(type); + return constraint !== noConstraintType && constraint !== circularConstraintType ? constraint : undefined; + } + return type.flags & 4194304 /* Index */ ? keyofConstraintType : undefined; + } + /** + * This is similar to `getBaseConstraintOfType` except it returns the input type if there's no base constraint, instead of `undefined` + * It also doesn't map indexes to `string`, as where this is used this would be unneeded (and likely undesirable) + */ + function getBaseConstraintOrType(type) { + return getBaseConstraintOfType(type) || type; + } + function hasNonCircularBaseConstraint(type) { + return getResolvedBaseConstraint(type) !== circularConstraintType; + } + /** + * Return the resolved base constraint of a type variable. The noConstraintType singleton is returned if the + * type variable has no constraint, and the circularConstraintType singleton is returned if the constraint + * circularly references the type variable. + */ + function getResolvedBaseConstraint(type) { + var nonTerminating = false; + return type.resolvedBaseConstraint || + (type.resolvedBaseConstraint = getTypeWithThisArgument(getImmediateBaseConstraint(type), type)); + function getImmediateBaseConstraint(t) { + if (!t.immediateBaseConstraint) { + if (!pushTypeResolution(t, 4 /* ImmediateBaseConstraint */)) { + return circularConstraintType; + } + if (constraintDepth === 50) { + // We have reached 50 recursive invocations of getImmediateBaseConstraint and there is a + // very high likelyhood we're dealing with an infinite generic type that perpetually generates + // new type identities as we descend into it. We stop the recursion here and mark this type + // and the outer types as having circular constraints. + nonTerminating = true; + return t.immediateBaseConstraint = noConstraintType; + } + constraintDepth++; + var result = computeBaseConstraint(getSimplifiedType(t)); + constraintDepth--; + if (!popTypeResolution() || nonTerminating) { + result = circularConstraintType; + } + t.immediateBaseConstraint = result || noConstraintType; + } + return t.immediateBaseConstraint; + } + function getBaseConstraint(t) { + var c = getImmediateBaseConstraint(t); + return c !== noConstraintType && c !== circularConstraintType ? c : undefined; + } + function computeBaseConstraint(t) { + if (t.flags & 262144 /* TypeParameter */) { + var constraint = getConstraintFromTypeParameter(t); + return t.isThisType || !constraint ? + constraint : + getBaseConstraint(constraint); + } + if (t.flags & 3145728 /* UnionOrIntersection */) { + var types = t.types; + var baseTypes = []; + for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { + var type_3 = types_4[_i]; + var baseType = getBaseConstraint(type_3); + if (baseType) { + baseTypes.push(baseType); + } + } + return t.flags & 1048576 /* Union */ && baseTypes.length === types.length ? getUnionType(baseTypes) : + t.flags & 2097152 /* Intersection */ && baseTypes.length ? getIntersectionType(baseTypes) : + undefined; + } + if (t.flags & 4194304 /* Index */) { + return keyofConstraintType; + } + if (t.flags & 8388608 /* IndexedAccess */) { + var baseObjectType = getBaseConstraint(t.objectType); + var baseIndexType = getBaseConstraint(t.indexType); + var baseIndexedAccess = baseObjectType && baseIndexType ? getIndexedAccessType(baseObjectType, baseIndexType, /*accessNode*/ undefined, errorType) : undefined; + return baseIndexedAccess && baseIndexedAccess !== errorType ? getBaseConstraint(baseIndexedAccess) : undefined; + } + if (t.flags & 16777216 /* Conditional */) { + var constraint = getConstraintOfConditionalType(t); + return constraint && getBaseConstraint(constraint); + } + if (t.flags & 33554432 /* Substitution */) { + return getBaseConstraint(t.substitute); + } + return t; + } + } + function getApparentTypeOfIntersectionType(type) { + return type.resolvedApparentType || (type.resolvedApparentType = getTypeWithThisArgument(type, type, /*apparentType*/ true)); + } + function getResolvedTypeParameterDefault(typeParameter) { + if (!typeParameter.default) { + if (typeParameter.target) { + var targetDefault = getResolvedTypeParameterDefault(typeParameter.target); + typeParameter.default = targetDefault ? instantiateType(targetDefault, typeParameter.mapper) : noConstraintType; + } + else { + // To block recursion, set the initial value to the resolvingDefaultType. + typeParameter.default = resolvingDefaultType; + var defaultDeclaration = typeParameter.symbol && ts.forEach(typeParameter.symbol.declarations, function (decl) { return ts.isTypeParameterDeclaration(decl) && decl.default; }); + var defaultType = defaultDeclaration ? getTypeFromTypeNode(defaultDeclaration) : noConstraintType; + if (typeParameter.default === resolvingDefaultType) { + // If we have not been called recursively, set the correct default type. + typeParameter.default = defaultType; + } + } + } + else if (typeParameter.default === resolvingDefaultType) { + // If we are called recursively for this type parameter, mark the default as circular. + typeParameter.default = circularConstraintType; + } + return typeParameter.default; + } + /** + * Gets the default type for a type parameter. + * + * If the type parameter is the result of an instantiation, this gets the instantiated + * default type of its target. If the type parameter has no default type or the default is + * circular, `undefined` is returned. + */ + function getDefaultFromTypeParameter(typeParameter) { + var defaultType = getResolvedTypeParameterDefault(typeParameter); + return defaultType !== noConstraintType && defaultType !== circularConstraintType ? defaultType : undefined; + } + function hasNonCircularTypeParameterDefault(typeParameter) { + return getResolvedTypeParameterDefault(typeParameter) !== circularConstraintType; + } + /** + * Indicates whether the declaration of a typeParameter has a default type. + */ + function hasTypeParameterDefault(typeParameter) { + return !!(typeParameter.symbol && ts.forEach(typeParameter.symbol.declarations, function (decl) { return ts.isTypeParameterDeclaration(decl) && decl.default; })); + } + function getApparentTypeOfMappedType(type) { + return type.resolvedApparentType || (type.resolvedApparentType = getResolvedApparentTypeOfMappedType(type)); + } + function getResolvedApparentTypeOfMappedType(type) { + var typeVariable = getHomomorphicTypeVariable(type); + if (typeVariable) { + var constraint = getConstraintOfTypeParameter(typeVariable); + if (constraint && (isArrayType(constraint) || isReadonlyArrayType(constraint) || isTupleType(constraint))) { + var mapper = makeUnaryTypeMapper(typeVariable, constraint); + return instantiateType(type, combineTypeMappers(mapper, type.mapper)); + } + } + return type; + } + /** + * For a type parameter, return the base constraint of the type parameter. For the string, number, + * boolean, and symbol primitive types, return the corresponding object types. Otherwise return the + * type itself. Note that the apparent type of a union type is the union type itself. + */ + function getApparentType(type) { + var t = type.flags & 63176704 /* Instantiable */ ? getBaseConstraintOfType(type) || emptyObjectType : type; + return ts.getObjectFlags(t) & 32 /* Mapped */ ? getApparentTypeOfMappedType(t) : + t.flags & 2097152 /* Intersection */ ? getApparentTypeOfIntersectionType(t) : + t.flags & 132 /* StringLike */ ? globalStringType : + t.flags & 296 /* NumberLike */ ? globalNumberType : + t.flags & 2112 /* BigIntLike */ ? getGlobalBigIntType(/*reportErrors*/ languageVersion >= 6 /* ESNext */) : + t.flags & 528 /* BooleanLike */ ? globalBooleanType : + t.flags & 12288 /* ESSymbolLike */ ? getGlobalESSymbolType(/*reportErrors*/ languageVersion >= 2 /* ES2015 */) : + t.flags & 67108864 /* NonPrimitive */ ? emptyObjectType : + t.flags & 4194304 /* Index */ ? keyofConstraintType : + t; + } + function createUnionOrIntersectionProperty(containingType, name) { + var props; + var indexTypes; + var isUnion = containingType.flags & 1048576 /* Union */; + var excludeModifiers = isUnion ? 24 /* NonPublicAccessibilityModifier */ : 0; + // Flags we want to propagate to the result if they exist in all source symbols + var commonFlags = isUnion ? 0 /* None */ : 16777216 /* Optional */; + var syntheticFlag = 4 /* SyntheticMethod */; + var checkFlags = 0; + for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) { + var current = _a[_i]; + var type = getApparentType(current); + if (type !== errorType) { + var prop = getPropertyOfType(type, name); + var modifiers = prop ? ts.getDeclarationModifierFlagsFromSymbol(prop) : 0; + if (prop && !(modifiers & excludeModifiers)) { + commonFlags &= prop.flags; + props = ts.appendIfUnique(props, prop); + checkFlags |= (isReadonlySymbol(prop) ? 8 /* Readonly */ : 0) | + (!(modifiers & 24 /* NonPublicAccessibilityModifier */) ? 64 /* ContainsPublic */ : 0) | + (modifiers & 16 /* Protected */ ? 128 /* ContainsProtected */ : 0) | + (modifiers & 8 /* Private */ ? 256 /* ContainsPrivate */ : 0) | + (modifiers & 32 /* Static */ ? 512 /* ContainsStatic */ : 0); + if (!isPrototypeProperty(prop)) { + syntheticFlag = 2 /* SyntheticProperty */; + } + } + else if (isUnion) { + var indexInfo = !isLateBoundName(name) && (isNumericLiteralName(name) && getIndexInfoOfType(type, 1 /* Number */) || getIndexInfoOfType(type, 0 /* String */)); + if (indexInfo) { + checkFlags |= indexInfo.isReadonly ? 8 /* Readonly */ : 0; + indexTypes = ts.append(indexTypes, isTupleType(type) ? getRestTypeOfTupleType(type) || undefinedType : indexInfo.type); + } + else { + checkFlags |= 16 /* Partial */; + } + } + } + } + if (!props) { + return undefined; + } + if (props.length === 1 && !(checkFlags & 16 /* Partial */) && !indexTypes) { + return props[0]; + } + var declarations; + var commonType; + var nameType; + var propTypes = []; + var first = true; + var commonValueDeclaration; + var hasNonUniformValueDeclaration = false; + for (var _b = 0, props_1 = props; _b < props_1.length; _b++) { + var prop = props_1[_b]; + if (!commonValueDeclaration) { + commonValueDeclaration = prop.valueDeclaration; + } + else if (prop.valueDeclaration !== commonValueDeclaration) { + hasNonUniformValueDeclaration = true; + } + declarations = ts.addRange(declarations, prop.declarations); + var type = getTypeOfSymbol(prop); + if (first) { + commonType = type; + nameType = prop.nameType; + first = false; + } + else { + if (type !== commonType) { + checkFlags |= 32 /* HasNonUniformType */; + } + } + propTypes.push(type); + } + ts.addRange(propTypes, indexTypes); + var result = createSymbol(4 /* Property */ | commonFlags, name, syntheticFlag | checkFlags); + result.containingType = containingType; + if (!hasNonUniformValueDeclaration && commonValueDeclaration) { + result.valueDeclaration = commonValueDeclaration; + } + result.declarations = declarations; + result.nameType = nameType; + result.type = isUnion ? getUnionType(propTypes) : getIntersectionType(propTypes); + return result; + } + // Return the symbol for a given property in a union or intersection type, or undefined if the property + // does not exist in any constituent type. Note that the returned property may only be present in some + // constituents, in which case the isPartial flag is set when the containing type is union type. We need + // these partial properties when identifying discriminant properties, but otherwise they are filtered out + // and do not appear to be present in the union type. + function getUnionOrIntersectionProperty(type, name) { + var properties = type.propertyCache || (type.propertyCache = ts.createSymbolTable()); + var property = properties.get(name); + if (!property) { + property = createUnionOrIntersectionProperty(type, name); + if (property) { + properties.set(name, property); + } + } + return property; + } + function getPropertyOfUnionOrIntersectionType(type, name) { + var property = getUnionOrIntersectionProperty(type, name); + // We need to filter out partial properties in union types + return property && !(ts.getCheckFlags(property) & 16 /* Partial */) ? property : undefined; + } + /** + * Return the symbol for the property with the given name in the given type. Creates synthetic union properties when + * necessary, maps primitive types and type parameters are to their apparent types, and augments with properties from + * Object and Function as appropriate. + * + * @param type a type to look up property from + * @param name a name of property to look up in a given type + */ + function getPropertyOfType(type, name) { + type = getApparentType(type); + if (type.flags & 524288 /* Object */) { + var resolved = resolveStructuredTypeMembers(type); + var symbol = resolved.members.get(name); + if (symbol && symbolIsValue(symbol)) { + return symbol; + } + var functionType = resolved === anyFunctionType ? globalFunctionType : + resolved.callSignatures.length ? globalCallableFunctionType : + resolved.constructSignatures.length ? globalNewableFunctionType : + undefined; + if (functionType) { + var symbol_1 = getPropertyOfObjectType(functionType, name); + if (symbol_1) { + return symbol_1; + } + } + return getPropertyOfObjectType(globalObjectType, name); + } + if (type.flags & 3145728 /* UnionOrIntersection */) { + return getPropertyOfUnionOrIntersectionType(type, name); + } + return undefined; + } + function getSignaturesOfStructuredType(type, kind) { + if (type.flags & 3670016 /* StructuredType */) { + var resolved = resolveStructuredTypeMembers(type); + return kind === 0 /* Call */ ? resolved.callSignatures : resolved.constructSignatures; + } + return ts.emptyArray; + } + /** + * Return the signatures of the given kind in the given type. Creates synthetic union signatures when necessary and + * maps primitive types and type parameters are to their apparent types. + */ + function getSignaturesOfType(type, kind) { + return getSignaturesOfStructuredType(getApparentType(type), kind); + } + function getIndexInfoOfStructuredType(type, kind) { + if (type.flags & 3670016 /* StructuredType */) { + var resolved = resolveStructuredTypeMembers(type); + return kind === 0 /* String */ ? resolved.stringIndexInfo : resolved.numberIndexInfo; + } + } + function getIndexTypeOfStructuredType(type, kind) { + var info = getIndexInfoOfStructuredType(type, kind); + return info && info.type; + } + // Return the indexing info of the given kind in the given type. Creates synthetic union index types when necessary and + // maps primitive types and type parameters are to their apparent types. + function getIndexInfoOfType(type, kind) { + return getIndexInfoOfStructuredType(getApparentType(type), kind); + } + // Return the index type of the given kind in the given type. Creates synthetic union index types when necessary and + // maps primitive types and type parameters are to their apparent types. + function getIndexTypeOfType(type, kind) { + return getIndexTypeOfStructuredType(getApparentType(type), kind); + } + function getImplicitIndexTypeOfType(type, kind) { + if (isObjectTypeWithInferableIndex(type)) { + var propTypes = []; + for (var _i = 0, _a = getPropertiesOfType(type); _i < _a.length; _i++) { + var prop = _a[_i]; + if (kind === 0 /* String */ || isNumericLiteralName(prop.escapedName)) { + propTypes.push(getTypeOfSymbol(prop)); + } + } + if (propTypes.length) { + return getUnionType(propTypes, 2 /* Subtype */); + } + } + return undefined; + } + // Return list of type parameters with duplicates removed (duplicate identifier errors are generated in the actual + // type checking functions). + function getTypeParametersFromDeclaration(declaration) { + var result; + for (var _i = 0, _a = ts.getEffectiveTypeParameterDeclarations(declaration); _i < _a.length; _i++) { + var node = _a[_i]; + result = ts.appendIfUnique(result, getDeclaredTypeOfTypeParameter(node.symbol)); + } + return result; + } + function symbolsToArray(symbols) { + var result = []; + symbols.forEach(function (symbol, id) { + if (!isReservedMemberName(id)) { + result.push(symbol); + } + }); + return result; + } + function isJSDocOptionalParameter(node) { + return ts.isInJSFile(node) && ( + // node.type should only be a JSDocOptionalType when node is a parameter of a JSDocFunctionType + node.type && node.type.kind === 288 /* JSDocOptionalType */ + || ts.getJSDocParameterTags(node).some(function (_a) { + var isBracketed = _a.isBracketed, typeExpression = _a.typeExpression; + return isBracketed || !!typeExpression && typeExpression.type.kind === 288 /* JSDocOptionalType */; + })); + } + function tryFindAmbientModule(moduleName, withAugmentations) { + if (ts.isExternalModuleNameRelative(moduleName)) { + return undefined; + } + var symbol = getSymbol(globals, '"' + moduleName + '"', 512 /* ValueModule */); + // merged symbol is module declaration symbol combined with all augmentations + return symbol && withAugmentations ? getMergedSymbol(symbol) : symbol; + } + function isOptionalParameter(node) { + if (ts.hasQuestionToken(node) || isOptionalJSDocParameterTag(node) || isJSDocOptionalParameter(node)) { + return true; + } + if (node.initializer) { + var signature = getSignatureFromDeclaration(node.parent); + var parameterIndex = node.parent.parameters.indexOf(node); + ts.Debug.assert(parameterIndex >= 0); + return parameterIndex >= getMinArgumentCount(signature); + } + var iife = ts.getImmediatelyInvokedFunctionExpression(node.parent); + if (iife) { + return !node.type && + !node.dotDotDotToken && + node.parent.parameters.indexOf(node) >= iife.arguments.length; + } + return false; + } + function isOptionalJSDocParameterTag(node) { + if (!ts.isJSDocParameterTag(node)) { + return false; + } + var isBracketed = node.isBracketed, typeExpression = node.typeExpression; + return isBracketed || !!typeExpression && typeExpression.type.kind === 288 /* JSDocOptionalType */; + } + function createIdentifierTypePredicate(parameterName, parameterIndex, type) { + return { kind: 1 /* Identifier */, parameterName: parameterName, parameterIndex: parameterIndex, type: type }; + } + function createThisTypePredicate(type) { + return { kind: 0 /* This */, type: type }; + } + /** + * Gets the minimum number of type arguments needed to satisfy all non-optional type + * parameters. + */ + function getMinTypeArgumentCount(typeParameters) { + var minTypeArgumentCount = 0; + if (typeParameters) { + for (var i = 0; i < typeParameters.length; i++) { + if (!hasTypeParameterDefault(typeParameters[i])) { + minTypeArgumentCount = i + 1; + } + } + } + return minTypeArgumentCount; + } + function fillMissingTypeArguments(typeArguments, typeParameters, minTypeArgumentCount, isJavaScriptImplicitAny) { + var numTypeParameters = ts.length(typeParameters); + if (!numTypeParameters) { + return []; + } + var numTypeArguments = ts.length(typeArguments); + if (isJavaScriptImplicitAny || (numTypeArguments >= minTypeArgumentCount && numTypeArguments <= numTypeParameters)) { + var result = typeArguments ? typeArguments.slice() : []; + // Map an unsatisfied type parameter with a default type. + // If a type parameter does not have a default type, or if the default type + // is a forward reference, the empty object type is used. + var baseDefaultType_1 = getDefaultTypeArgumentType(isJavaScriptImplicitAny); + var circularityMapper = createTypeMapper(typeParameters, ts.map(typeParameters, function () { return baseDefaultType_1; })); + for (var i = numTypeArguments; i < numTypeParameters; i++) { + result[i] = instantiateType(getConstraintFromTypeParameter(typeParameters[i]) || baseDefaultType_1, circularityMapper); + } + for (var i = numTypeArguments; i < numTypeParameters; i++) { + var mapper = createTypeMapper(typeParameters, result); + var defaultType = getDefaultFromTypeParameter(typeParameters[i]); + if (isJavaScriptImplicitAny && defaultType && isTypeIdenticalTo(defaultType, emptyObjectType)) { + defaultType = anyType; + } + result[i] = defaultType ? instantiateType(defaultType, mapper) : baseDefaultType_1; + } + result.length = typeParameters.length; + return result; + } + return typeArguments && typeArguments.slice(); + } + function getSignatureFromDeclaration(declaration) { + var links = getNodeLinks(declaration); + if (!links.resolvedSignature) { + var parameters = []; + var hasLiteralTypes = false; + var minArgumentCount = 0; + var thisParameter = void 0; + var hasThisParameter = false; + var iife = ts.getImmediatelyInvokedFunctionExpression(declaration); + var isJSConstructSignature = ts.isJSDocConstructSignature(declaration); + var isUntypedSignatureInJSFile = !iife && + ts.isInJSFile(declaration) && + ts.isValueSignatureDeclaration(declaration) && + !ts.hasJSDocParameterTags(declaration) && + !ts.getJSDocType(declaration); + // If this is a JSDoc construct signature, then skip the first parameter in the + // parameter list. The first parameter represents the return type of the construct + // signature. + for (var i = isJSConstructSignature ? 1 : 0; i < declaration.parameters.length; i++) { + var param = declaration.parameters[i]; + var paramSymbol = param.symbol; + var type = ts.isJSDocParameterTag(param) ? (param.typeExpression && param.typeExpression.type) : param.type; + // Include parameter symbol instead of property symbol in the signature + if (paramSymbol && !!(paramSymbol.flags & 4 /* Property */) && !ts.isBindingPattern(param.name)) { + var resolvedSymbol = resolveName(param, paramSymbol.escapedName, 67220415 /* Value */, undefined, undefined, /*isUse*/ false); + paramSymbol = resolvedSymbol; + } + if (i === 0 && paramSymbol.escapedName === "this" /* This */) { + hasThisParameter = true; + thisParameter = param.symbol; + } + else { + parameters.push(paramSymbol); + } + if (type && type.kind === 182 /* LiteralType */) { + hasLiteralTypes = true; + } + // Record a new minimum argument count if this is not an optional parameter + var isOptionalParameter_1 = isOptionalJSDocParameterTag(param) || + param.initializer || param.questionToken || param.dotDotDotToken || + iife && parameters.length > iife.arguments.length && !type || + isUntypedSignatureInJSFile || + isJSDocOptionalParameter(param); + if (!isOptionalParameter_1) { + minArgumentCount = parameters.length; + } + } + // If only one accessor includes a this-type annotation, the other behaves as if it had the same type annotation + if ((declaration.kind === 158 /* GetAccessor */ || declaration.kind === 159 /* SetAccessor */) && + !hasNonBindableDynamicName(declaration) && + (!hasThisParameter || !thisParameter)) { + var otherKind = declaration.kind === 158 /* GetAccessor */ ? 159 /* SetAccessor */ : 158 /* GetAccessor */; + var other = ts.getDeclarationOfKind(getSymbolOfNode(declaration), otherKind); + if (other) { + thisParameter = getAnnotatedAccessorThisParameter(other); + } + } + var classType = declaration.kind === 157 /* Constructor */ ? + getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)) + : undefined; + var typeParameters = classType ? classType.localTypeParameters : getTypeParametersFromDeclaration(declaration); + var hasRestLikeParameter = ts.hasRestParameter(declaration) || ts.isInJSFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters); + links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, + /*resolvedReturnType*/ undefined, /*resolvedTypePredicate*/ undefined, minArgumentCount, hasRestLikeParameter, hasLiteralTypes); + } + return links.resolvedSignature; + } + /** + * A JS function gets a synthetic rest parameter if it references `arguments` AND: + * 1. It has no parameters but at least one `@param` with a type that starts with `...` + * OR + * 2. It has at least one parameter, and the last parameter has a matching `@param` with a type that starts with `...` + */ + function maybeAddJsSyntheticRestParameter(declaration, parameters) { + if (ts.isJSDocSignature(declaration) || !containsArgumentsReference(declaration)) { + return false; + } + var lastParam = ts.lastOrUndefined(declaration.parameters); + var lastParamTags = lastParam ? ts.getJSDocParameterTags(lastParam) : ts.getJSDocTags(declaration).filter(ts.isJSDocParameterTag); + var lastParamVariadicType = ts.firstDefined(lastParamTags, function (p) { + return p.typeExpression && ts.isJSDocVariadicType(p.typeExpression.type) ? p.typeExpression.type : undefined; + }); + var syntheticArgsSymbol = createSymbol(3 /* Variable */, "args", 8192 /* RestParameter */); + syntheticArgsSymbol.type = lastParamVariadicType ? createArrayType(getTypeFromTypeNode(lastParamVariadicType.type)) : anyArrayType; + if (lastParamVariadicType) { + // Replace the last parameter with a rest parameter. + parameters.pop(); + } + parameters.push(syntheticArgsSymbol); + return true; + } + function getSignatureOfTypeTag(node) { + var typeTag = ts.isInJSFile(node) ? ts.getJSDocTypeTag(node) : undefined; + var signature = typeTag && typeTag.typeExpression && getSingleCallSignature(getTypeFromTypeNode(typeTag.typeExpression)); + return signature && getErasedSignature(signature); + } + function getReturnTypeOfTypeTag(node) { + var signature = getSignatureOfTypeTag(node); + return signature && getReturnTypeOfSignature(signature); + } + function containsArgumentsReference(declaration) { + var links = getNodeLinks(declaration); + if (links.containsArgumentsReference === undefined) { + if (links.flags & 8192 /* CaptureArguments */) { + links.containsArgumentsReference = true; + } + else { + links.containsArgumentsReference = traverse(declaration.body); + } + } + return links.containsArgumentsReference; + function traverse(node) { + if (!node) + return false; + switch (node.kind) { + case 72 /* Identifier */: + return node.escapedText === "arguments" && ts.isExpressionNode(node); + case 154 /* PropertyDeclaration */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + return node.name.kind === 149 /* ComputedPropertyName */ + && traverse(node.name); + default: + return !ts.nodeStartsNewLexicalEnvironment(node) && !ts.isPartOfTypeNode(node) && !!ts.forEachChild(node, traverse); + } + } + } + function getSignaturesOfSymbol(symbol) { + if (!symbol) + return ts.emptyArray; + var result = []; + for (var i = 0; i < symbol.declarations.length; i++) { + var decl = symbol.declarations[i]; + if (!ts.isFunctionLike(decl)) + continue; + // Don't include signature if node is the implementation of an overloaded function. A node is considered + // an implementation node if it has a body and the previous node is of the same kind and immediately + // precedes the implementation node (i.e. has the same parent and ends where the implementation starts). + if (i > 0 && decl.body) { + var previous = symbol.declarations[i - 1]; + if (decl.parent === previous.parent && decl.kind === previous.kind && decl.pos === previous.end) { + continue; + } + } + result.push(getSignatureFromDeclaration(decl)); + } + return result; + } + function resolveExternalModuleTypeByLiteral(name) { + var moduleSym = resolveExternalModuleName(name, name); + if (moduleSym) { + var resolvedModuleSymbol = resolveExternalModuleSymbol(moduleSym); + if (resolvedModuleSymbol) { + return getTypeOfSymbol(resolvedModuleSymbol); + } + } + return anyType; + } + function getThisTypeOfSignature(signature) { + if (signature.thisParameter) { + return getTypeOfSymbol(signature.thisParameter); + } + } + function signatureHasTypePredicate(signature) { + return getTypePredicateOfSignature(signature) !== undefined; + } + function getTypePredicateOfSignature(signature) { + if (!signature.resolvedTypePredicate) { + if (signature.target) { + var targetTypePredicate = getTypePredicateOfSignature(signature.target); + signature.resolvedTypePredicate = targetTypePredicate ? instantiateTypePredicate(targetTypePredicate, signature.mapper) : noTypePredicate; + } + else if (signature.unionSignatures) { + signature.resolvedTypePredicate = getUnionTypePredicate(signature.unionSignatures) || noTypePredicate; + } + else { + var type = signature.declaration && ts.getEffectiveReturnTypeNode(signature.declaration); + var jsdocPredicate = void 0; + if (!type && ts.isInJSFile(signature.declaration)) { + var jsdocSignature = getSignatureOfTypeTag(signature.declaration); + if (jsdocSignature && signature !== jsdocSignature) { + jsdocPredicate = getTypePredicateOfSignature(jsdocSignature); + } + } + signature.resolvedTypePredicate = type && ts.isTypePredicateNode(type) ? + createTypePredicateFromTypePredicateNode(type, signature.declaration) : + jsdocPredicate || noTypePredicate; + } + ts.Debug.assert(!!signature.resolvedTypePredicate); + } + return signature.resolvedTypePredicate === noTypePredicate ? undefined : signature.resolvedTypePredicate; + } + function createTypePredicateFromTypePredicateNode(node, func) { + var parameterName = node.parameterName; + var type = getTypeFromTypeNode(node.type); + if (parameterName.kind === 72 /* Identifier */) { + return createIdentifierTypePredicate(parameterName.escapedText, getTypePredicateParameterIndex(func.parameters, parameterName), type); + } + else { + return createThisTypePredicate(type); + } + } + function getTypePredicateParameterIndex(parameterList, parameter) { + for (var i = 0; i < parameterList.length; i++) { + var param = parameterList[i]; + if (param.name.kind === 72 /* Identifier */ && param.name.escapedText === parameter.escapedText) { + return i; + } + } + return -1; + } + function getReturnTypeOfSignature(signature) { + if (!signature.resolvedReturnType) { + if (!pushTypeResolution(signature, 3 /* ResolvedReturnType */)) { + return errorType; + } + var type = signature.target ? instantiateType(getReturnTypeOfSignature(signature.target), signature.mapper) : + signature.unionSignatures ? getUnionType(ts.map(signature.unionSignatures, getReturnTypeOfSignature), 2 /* Subtype */) : + getReturnTypeFromAnnotation(signature.declaration) || + isJSConstructor(signature.declaration) && getJSClassType(getSymbolOfNode(signature.declaration)) || + (ts.nodeIsMissing(signature.declaration.body) ? anyType : getReturnTypeFromBody(signature.declaration)); + if (!popTypeResolution()) { + if (signature.declaration) { + var typeNode = ts.getEffectiveReturnTypeNode(signature.declaration); + if (typeNode) { + error(typeNode, ts.Diagnostics.Return_type_annotation_circularly_references_itself); + } + else if (noImplicitAny) { + var declaration = signature.declaration; + var name = ts.getNameOfDeclaration(declaration); + if (name) { + error(name, ts.Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, ts.declarationNameToString(name)); + } + else { + error(declaration, ts.Diagnostics.Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions); + } + } + } + type = anyType; + } + signature.resolvedReturnType = type; + } + return signature.resolvedReturnType; + } + function getReturnTypeFromAnnotation(declaration) { + if (declaration.kind === 157 /* Constructor */) { + return getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)); + } + if (ts.isJSDocConstructSignature(declaration)) { + return getTypeFromTypeNode(declaration.parameters[0].type); // TODO: GH#18217 + } + var typeNode = ts.getEffectiveReturnTypeNode(declaration); + if (typeNode) { + return getTypeFromTypeNode(typeNode); + } + if (declaration.kind === 158 /* GetAccessor */ && !hasNonBindableDynamicName(declaration)) { + var jsDocType = ts.isInJSFile(declaration) && getTypeForDeclarationFromJSDocComment(declaration); + if (jsDocType) { + return jsDocType; + } + var setter = ts.getDeclarationOfKind(getSymbolOfNode(declaration), 159 /* SetAccessor */); + var setterType = getAnnotatedAccessorType(setter); + if (setterType) { + return setterType; + } + } + return getReturnTypeOfTypeTag(declaration); + } + function isResolvingReturnTypeOfSignature(signature) { + return !signature.resolvedReturnType && findResolutionCycleStartIndex(signature, 3 /* ResolvedReturnType */) >= 0; + } + function getRestTypeOfSignature(signature) { + return tryGetRestTypeOfSignature(signature) || anyType; + } + function tryGetRestTypeOfSignature(signature) { + if (signature.hasRestParameter) { + var sigRestType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); + var restType = isTupleType(sigRestType) ? getRestTypeOfTupleType(sigRestType) : sigRestType; + return restType && getIndexTypeOfType(restType, 1 /* Number */); + } + return undefined; + } + function getSignatureInstantiation(signature, typeArguments, isJavascript) { + return getSignatureInstantiationWithoutFillingInTypeArguments(signature, fillMissingTypeArguments(typeArguments, signature.typeParameters, getMinTypeArgumentCount(signature.typeParameters), isJavascript)); + } + function getSignatureInstantiationWithoutFillingInTypeArguments(signature, typeArguments) { + var instantiations = signature.instantiations || (signature.instantiations = ts.createMap()); + var id = getTypeListId(typeArguments); + var instantiation = instantiations.get(id); + if (!instantiation) { + instantiations.set(id, instantiation = createSignatureInstantiation(signature, typeArguments)); + } + return instantiation; + } + function createSignatureInstantiation(signature, typeArguments) { + return instantiateSignature(signature, createSignatureTypeMapper(signature, typeArguments), /*eraseTypeParameters*/ true); + } + function createSignatureTypeMapper(signature, typeArguments) { + return createTypeMapper(signature.typeParameters, typeArguments); + } + function getErasedSignature(signature) { + return signature.typeParameters ? + signature.erasedSignatureCache || (signature.erasedSignatureCache = createErasedSignature(signature)) : + signature; + } + function createErasedSignature(signature) { + // Create an instantiation of the signature where all type arguments are the any type. + return instantiateSignature(signature, createTypeEraser(signature.typeParameters), /*eraseTypeParameters*/ true); + } + function getCanonicalSignature(signature) { + return signature.typeParameters ? + signature.canonicalSignatureCache || (signature.canonicalSignatureCache = createCanonicalSignature(signature)) : + signature; + } + function createCanonicalSignature(signature) { + // Create an instantiation of the signature where each unconstrained type parameter is replaced with + // its original. When a generic class or interface is instantiated, each generic method in the class or + // interface is instantiated with a fresh set of cloned type parameters (which we need to handle scenarios + // where different generations of the same type parameter are in scope). This leads to a lot of new type + // identities, and potentially a lot of work comparing those identities, so here we create an instantiation + // that uses the original type identities for all unconstrained type parameters. + return getSignatureInstantiation(signature, ts.map(signature.typeParameters, function (tp) { return tp.target && !getConstraintOfTypeParameter(tp.target) ? tp.target : tp; }), ts.isInJSFile(signature.declaration)); + } + function getBaseSignature(signature) { + var typeParameters = signature.typeParameters; + if (typeParameters) { + var typeEraser_1 = createTypeEraser(typeParameters); + var baseConstraints = ts.map(typeParameters, function (tp) { return instantiateType(getBaseConstraintOfType(tp), typeEraser_1) || emptyObjectType; }); + return instantiateSignature(signature, createTypeMapper(typeParameters, baseConstraints), /*eraseTypeParameters*/ true); + } + return signature; + } + function getOrCreateTypeFromSignature(signature) { + // There are two ways to declare a construct signature, one is by declaring a class constructor + // using the constructor keyword, and the other is declaring a bare construct signature in an + // object type literal or interface (using the new keyword). Each way of declaring a constructor + // will result in a different declaration kind. + if (!signature.isolatedSignatureType) { + var isConstructor = signature.declaration.kind === 157 /* Constructor */ || signature.declaration.kind === 161 /* ConstructSignature */; // TODO: GH#18217 + var type = createObjectType(16 /* Anonymous */); + type.members = emptySymbols; + type.properties = ts.emptyArray; + type.callSignatures = !isConstructor ? [signature] : ts.emptyArray; + type.constructSignatures = isConstructor ? [signature] : ts.emptyArray; + signature.isolatedSignatureType = type; + } + return signature.isolatedSignatureType; + } + function getIndexSymbol(symbol) { + return symbol.members.get("__index" /* Index */); + } + function getIndexDeclarationOfSymbol(symbol, kind) { + var syntaxKind = kind === 1 /* Number */ ? 135 /* NumberKeyword */ : 138 /* StringKeyword */; + var indexSymbol = getIndexSymbol(symbol); + if (indexSymbol) { + for (var _i = 0, _a = indexSymbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + var node = ts.cast(decl, ts.isIndexSignatureDeclaration); + if (node.parameters.length === 1) { + var parameter = node.parameters[0]; + if (parameter.type && parameter.type.kind === syntaxKind) { + return node; + } + } + } + } + return undefined; + } + function createIndexInfo(type, isReadonly, declaration) { + return { type: type, isReadonly: isReadonly, declaration: declaration }; + } + function getIndexInfoOfSymbol(symbol, kind) { + var declaration = getIndexDeclarationOfSymbol(symbol, kind); + if (declaration) { + return createIndexInfo(declaration.type ? getTypeFromTypeNode(declaration.type) : anyType, ts.hasModifier(declaration, 64 /* Readonly */), declaration); + } + return undefined; + } + function getConstraintDeclaration(type) { + var decl = type.symbol && ts.getDeclarationOfKind(type.symbol, 150 /* TypeParameter */); + return decl && ts.getEffectiveConstraintOfTypeParameter(decl); + } + function getInferredTypeParameterConstraint(typeParameter) { + var inferences; + if (typeParameter.symbol) { + for (var _i = 0, _a = typeParameter.symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (declaration.parent.kind === 176 /* InferType */) { + // When an 'infer T' declaration is immediately contained in a type reference node + // (such as 'Foo'), T's constraint is inferred from the constraint of the + // corresponding type parameter in 'Foo'. When multiple 'infer T' declarations are + // present, we form an intersection of the inferred constraint types. + var grandParent = declaration.parent.parent; + if (grandParent.kind === 164 /* TypeReference */) { + var typeReference = grandParent; + var typeParameters = getTypeParametersForTypeReference(typeReference); + if (typeParameters) { + var index = typeReference.typeArguments.indexOf(declaration.parent); + if (index < typeParameters.length) { + var declaredConstraint = getConstraintOfTypeParameter(typeParameters[index]); + if (declaredConstraint) { + // Type parameter constraints can reference other type parameters so + // constraints need to be instantiated. If instantiation produces the + // type parameter itself, we discard that inference. For example, in + // type Foo = [T, U]; + // type Bar = T extends Foo ? Foo : T; + // the instantiated constraint for U is X, so we discard that inference. + var mapper = createTypeMapper(typeParameters, getEffectiveTypeArguments(typeReference, typeParameters)); + var constraint = instantiateType(declaredConstraint, mapper); + if (constraint !== typeParameter) { + inferences = ts.append(inferences, constraint); + } + } + } + } + } + // When an 'infer T' declaration is immediately contained in a rest parameter + // declaration, we infer an 'unknown[]' constraint. + else if (grandParent.kind === 151 /* Parameter */ && grandParent.dotDotDotToken) { + inferences = ts.append(inferences, createArrayType(unknownType)); + } + } + } + } + return inferences && getIntersectionType(inferences); + } + /** This is a worker function. Use getConstraintOfTypeParameter which guards against circular constraints. */ + function getConstraintFromTypeParameter(typeParameter) { + if (!typeParameter.constraint) { + if (typeParameter.target) { + var targetConstraint = getConstraintOfTypeParameter(typeParameter.target); + typeParameter.constraint = targetConstraint ? instantiateType(targetConstraint, typeParameter.mapper) : noConstraintType; + } + else { + var constraintDeclaration = getConstraintDeclaration(typeParameter); + typeParameter.constraint = constraintDeclaration ? getTypeFromTypeNode(constraintDeclaration) : + getInferredTypeParameterConstraint(typeParameter) || noConstraintType; + } + } + return typeParameter.constraint === noConstraintType ? undefined : typeParameter.constraint; + } + function getParentSymbolOfTypeParameter(typeParameter) { + var tp = ts.getDeclarationOfKind(typeParameter.symbol, 150 /* TypeParameter */); + var host = ts.isJSDocTemplateTag(tp.parent) ? ts.getHostSignatureFromJSDoc(tp.parent) : tp.parent; + return host && getSymbolOfNode(host); + } + function getTypeListId(types) { + var result = ""; + if (types) { + var length_3 = types.length; + var i = 0; + while (i < length_3) { + var startId = types[i].id; + var count = 1; + while (i + count < length_3 && types[i + count].id === startId + count) { + count++; + } + if (result.length) { + result += ","; + } + result += startId; + if (count > 1) { + result += ":" + count; + } + i += count; + } + } + return result; + } + // This function is used to propagate certain flags when creating new object type references and union types. + // It is only necessary to do so if a constituent type might be the undefined type, the null type, the type + // of an object literal or the anyFunctionType. This is because there are operations in the type checker + // that care about the presence of such types at arbitrary depth in a containing type. + function getPropagatingFlagsOfTypes(types, excludeKinds) { + var result = 0; + for (var _i = 0, types_5 = types; _i < types_5.length; _i++) { + var type = types_5[_i]; + if (!(type.flags & excludeKinds)) { + result |= type.flags; + } + } + return result & 939524096 /* PropagatingFlags */; + } + function createTypeReference(target, typeArguments) { + var id = getTypeListId(typeArguments); + var type = target.instantiations.get(id); + if (!type) { + type = createObjectType(4 /* Reference */, target.symbol); + target.instantiations.set(id, type); + type.flags |= typeArguments ? getPropagatingFlagsOfTypes(typeArguments, /*excludeKinds*/ 0) : 0; + type.target = target; + type.typeArguments = typeArguments; + } + return type; + } + function cloneTypeReference(source) { + var type = createType(source.flags); + type.symbol = source.symbol; + type.objectFlags = source.objectFlags; + type.target = source.target; + type.typeArguments = source.typeArguments; + return type; + } + function getTypeReferenceArity(type) { + return ts.length(type.target.typeParameters); + } + /** + * Get type from type-reference that reference to class or interface + */ + function getTypeFromClassOrInterfaceReference(node, symbol, typeArgs) { + var type = getDeclaredTypeOfSymbol(getMergedSymbol(symbol)); + var typeParameters = type.localTypeParameters; + if (typeParameters) { + var numTypeArguments = ts.length(node.typeArguments); + var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters); + var isJs = ts.isInJSFile(node); + var isJsImplicitAny = !noImplicitAny && isJs; + if (!isJsImplicitAny && (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length)) { + var missingAugmentsTag = isJs && ts.isExpressionWithTypeArguments(node) && !ts.isJSDocAugmentsTag(node.parent); + var diag = minTypeArgumentCount === typeParameters.length + ? missingAugmentsTag + ? ts.Diagnostics.Expected_0_type_arguments_provide_these_with_an_extends_tag + : ts.Diagnostics.Generic_type_0_requires_1_type_argument_s + : missingAugmentsTag + ? ts.Diagnostics.Expected_0_1_type_arguments_provide_these_with_an_extends_tag + : ts.Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments; + var typeStr = typeToString(type, /*enclosingDeclaration*/ undefined, 2 /* WriteArrayAsGenericType */); + error(node, diag, typeStr, minTypeArgumentCount, typeParameters.length); + if (!isJs) { + // TODO: Adopt same permissive behavior in TS as in JS to reduce follow-on editing experience failures (requires editing fillMissingTypeArguments) + return errorType; + } + } + // In a type reference, the outer type parameters of the referenced class or interface are automatically + // supplied as type arguments and the type reference only specifies arguments for the local type parameters + // of the class or interface. + var typeArguments = ts.concatenate(type.outerTypeParameters, fillMissingTypeArguments(typeArgs, typeParameters, minTypeArgumentCount, isJs)); + return createTypeReference(type, typeArguments); + } + return checkNoTypeArguments(node, symbol) ? type : errorType; + } + function getTypeAliasInstantiation(symbol, typeArguments) { + var type = getDeclaredTypeOfSymbol(symbol); + var links = getSymbolLinks(symbol); + var typeParameters = links.typeParameters; + var id = getTypeListId(typeArguments); + var instantiation = links.instantiations.get(id); + if (!instantiation) { + links.instantiations.set(id, instantiation = instantiateType(type, createTypeMapper(typeParameters, fillMissingTypeArguments(typeArguments, typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJSFile(symbol.valueDeclaration))))); + } + return instantiation; + } + /** + * Get type from reference to type alias. When a type alias is generic, the declared type of the type alias may include + * references to the type parameters of the alias. We replace those with the actual type arguments by instantiating the + * declared type. Instantiations are cached using the type identities of the type arguments as the key. + */ + function getTypeFromTypeAliasReference(node, symbol, typeArguments) { + var type = getDeclaredTypeOfSymbol(symbol); + var typeParameters = getSymbolLinks(symbol).typeParameters; + if (typeParameters) { + var numTypeArguments = ts.length(node.typeArguments); + var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters); + if (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length) { + error(node, minTypeArgumentCount === typeParameters.length + ? ts.Diagnostics.Generic_type_0_requires_1_type_argument_s + : ts.Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments, symbolToString(symbol), minTypeArgumentCount, typeParameters.length); + return errorType; + } + return getTypeAliasInstantiation(symbol, typeArguments); + } + return checkNoTypeArguments(node, symbol) ? type : errorType; + } + function getTypeReferenceName(node) { + switch (node.kind) { + case 164 /* TypeReference */: + return node.typeName; + case 211 /* ExpressionWithTypeArguments */: + // We only support expressions that are simple qualified names. For other + // expressions this produces undefined. + var expr = node.expression; + if (ts.isEntityNameExpression(expr)) { + return expr; + } + // fall through; + } + return undefined; + } + function resolveTypeReferenceName(typeReferenceName, meaning) { + if (!typeReferenceName) { + return unknownSymbol; + } + return resolveEntityName(typeReferenceName, meaning) || unknownSymbol; + } + function getTypeReferenceType(node, symbol) { + var typeArguments = typeArgumentsFromTypeReferenceNode(node); // Do unconditionally so we mark type arguments as referenced. + if (symbol === unknownSymbol) { + return errorType; + } + var type = getTypeReferenceTypeWorker(node, symbol, typeArguments); + if (type) { + return type; + } + // JS enums are 'string' or 'number', not an enum type. + var enumTag = ts.isInJSFile(node) && symbol.valueDeclaration && ts.getJSDocEnumTag(symbol.valueDeclaration); + if (enumTag) { + var links = getNodeLinks(enumTag); + if (!pushTypeResolution(enumTag, 5 /* EnumTagType */)) { + return errorType; + } + var type_4 = enumTag.typeExpression ? getTypeFromTypeNode(enumTag.typeExpression) : errorType; + if (!popTypeResolution()) { + type_4 = errorType; + error(node, ts.Diagnostics.Enum_type_0_circularly_references_itself, symbolToString(symbol)); + } + return (links.resolvedEnumType = type_4); + } + // Get type from reference to named type that cannot be generic (enum or type parameter) + var res = tryGetDeclaredTypeOfSymbol(symbol); + if (res) { + return checkNoTypeArguments(node, symbol) ? + res.flags & 262144 /* TypeParameter */ ? getConstrainedTypeVariable(res, node) : getRegularTypeOfLiteralType(res) : + errorType; + } + if (!(symbol.flags & 67220415 /* Value */ && isJSDocTypeReference(node))) { + return errorType; + } + var jsdocType = getJSDocTypeReference(node, symbol, typeArguments); + if (jsdocType) { + return jsdocType; + } + // Resolve the type reference as a Type for the purpose of reporting errors. + resolveTypeReferenceName(getTypeReferenceName(node), 67897832 /* Type */); + return getTypeOfSymbol(symbol); + } + /** + * A jsdoc TypeReference may have resolved to a value (as opposed to a type). If + * the symbol is a constructor function, return the inferred class type; otherwise, + * the type of this reference is just the type of the value we resolved to. + */ + function getJSDocTypeReference(node, symbol, typeArguments) { + if (!pushTypeResolution(symbol, 6 /* JSDocTypeReference */)) { + return errorType; + } + var assignedType = getAssignedClassType(symbol); + var valueType = getTypeOfSymbol(symbol); + var referenceType = valueType.symbol && valueType.symbol !== symbol && !isInferredClassType(valueType) && getTypeReferenceTypeWorker(node, valueType.symbol, typeArguments); + if (!popTypeResolution()) { + getSymbolLinks(symbol).resolvedJSDocType = errorType; + error(node, ts.Diagnostics.JSDoc_type_0_circularly_references_itself, symbolToString(symbol)); + return errorType; + } + if (referenceType || assignedType) { + // TODO: GH#18217 (should the `|| assignedType` be at a lower precedence?) + var type = (referenceType && assignedType ? getIntersectionType([assignedType, referenceType]) : referenceType || assignedType); + return getSymbolLinks(symbol).resolvedJSDocType = type; + } + } + function getTypeReferenceTypeWorker(node, symbol, typeArguments) { + if (symbol.flags & (32 /* Class */ | 64 /* Interface */)) { + if (symbol.valueDeclaration && ts.isBinaryExpression(symbol.valueDeclaration.parent)) { + var jsdocType = getJSDocTypeReference(node, symbol, typeArguments); + if (jsdocType) { + return jsdocType; + } + } + return getTypeFromClassOrInterfaceReference(node, symbol, typeArguments); + } + if (symbol.flags & 524288 /* TypeAlias */) { + return getTypeFromTypeAliasReference(node, symbol, typeArguments); + } + if (symbol.flags & 16 /* Function */ && + isJSDocTypeReference(node) && + (symbol.members || ts.getJSDocClassTag(symbol.valueDeclaration))) { + return getInferredClassType(symbol); + } + } + function getSubstitutionType(typeVariable, substitute) { + var result = createType(33554432 /* Substitution */); + result.typeVariable = typeVariable; + result.substitute = substitute; + return result; + } + function isUnaryTupleTypeNode(node) { + return node.kind === 170 /* TupleType */ && node.elementTypes.length === 1; + } + function getImpliedConstraint(typeVariable, checkNode, extendsNode) { + return isUnaryTupleTypeNode(checkNode) && isUnaryTupleTypeNode(extendsNode) ? getImpliedConstraint(typeVariable, checkNode.elementTypes[0], extendsNode.elementTypes[0]) : + getActualTypeVariable(getTypeFromTypeNode(checkNode)) === typeVariable ? getTypeFromTypeNode(extendsNode) : + undefined; + } + function getConstrainedTypeVariable(typeVariable, node) { + var constraints; + while (node && !ts.isStatement(node) && node.kind !== 291 /* JSDocComment */) { + var parent = node.parent; + if (parent.kind === 175 /* ConditionalType */ && node === parent.trueType) { + var constraint = getImpliedConstraint(typeVariable, parent.checkType, parent.extendsType); + if (constraint) { + constraints = ts.append(constraints, constraint); + } + } + node = parent; + } + return constraints ? getSubstitutionType(typeVariable, getIntersectionType(ts.append(constraints, typeVariable))) : typeVariable; + } + function isJSDocTypeReference(node) { + return !!(node.flags & 2097152 /* JSDoc */) && (node.kind === 164 /* TypeReference */ || node.kind === 183 /* ImportType */); + } + function checkNoTypeArguments(node, symbol) { + if (node.typeArguments) { + error(node, ts.Diagnostics.Type_0_is_not_generic, symbol ? symbolToString(symbol) : node.typeName ? ts.declarationNameToString(node.typeName) : "(anonymous)"); + return false; + } + return true; + } + function getIntendedTypeFromJSDocTypeReference(node) { + if (ts.isIdentifier(node.typeName)) { + var typeArgs = node.typeArguments; + switch (node.typeName.escapedText) { + case "String": + checkNoTypeArguments(node); + return stringType; + case "Number": + checkNoTypeArguments(node); + return numberType; + case "Boolean": + checkNoTypeArguments(node); + return booleanType; + case "Void": + checkNoTypeArguments(node); + return voidType; + case "Undefined": + checkNoTypeArguments(node); + return undefinedType; + case "Null": + checkNoTypeArguments(node); + return nullType; + case "Function": + case "function": + checkNoTypeArguments(node); + return globalFunctionType; + case "Array": + case "array": + return !typeArgs || !typeArgs.length ? anyArrayType : undefined; + case "Promise": + case "promise": + return !typeArgs || !typeArgs.length ? createPromiseType(anyType) : undefined; + case "Object": + if (typeArgs && typeArgs.length === 2) { + if (ts.isJSDocIndexSignature(node)) { + var indexed = getTypeFromTypeNode(typeArgs[0]); + var target = getTypeFromTypeNode(typeArgs[1]); + var index = createIndexInfo(target, /*isReadonly*/ false); + return createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, indexed === stringType ? index : undefined, indexed === numberType ? index : undefined); + } + return anyType; + } + checkNoTypeArguments(node); + return anyType; + } + } + } + function getTypeFromJSDocNullableTypeNode(node) { + var type = getTypeFromTypeNode(node.type); + return strictNullChecks ? getNullableType(type, 65536 /* Null */) : type; + } + function getTypeFromTypeReference(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + var symbol = void 0; + var type = void 0; + var meaning = 67897832 /* Type */; + if (isJSDocTypeReference(node)) { + type = getIntendedTypeFromJSDocTypeReference(node); + meaning |= 67220415 /* Value */; + } + if (!type) { + symbol = resolveTypeReferenceName(getTypeReferenceName(node), meaning); + type = getTypeReferenceType(node, symbol); + } + // Cache both the resolved symbol and the resolved type. The resolved symbol is needed when we check the + // type reference in checkTypeReferenceNode. + links.resolvedSymbol = symbol; + links.resolvedType = type; + } + return links.resolvedType; + } + function typeArgumentsFromTypeReferenceNode(node) { + return ts.map(node.typeArguments, getTypeFromTypeNode); + } + function getTypeFromTypeQueryNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + // TypeScript 1.0 spec (April 2014): 3.6.3 + // The expression is processed as an identifier expression (section 4.3) + // or property access expression(section 4.10), + // the widened type(section 3.9) of which becomes the result. + links.resolvedType = getRegularTypeOfLiteralType(getWidenedType(checkExpression(node.exprName))); + } + return links.resolvedType; + } + function getTypeOfGlobalSymbol(symbol, arity) { + function getTypeDeclaration(symbol) { + var declarations = symbol.declarations; + for (var _i = 0, declarations_3 = declarations; _i < declarations_3.length; _i++) { + var declaration = declarations_3[_i]; + switch (declaration.kind) { + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + case 243 /* EnumDeclaration */: + return declaration; + } + } + } + if (!symbol) { + return arity ? emptyGenericType : emptyObjectType; + } + var type = getDeclaredTypeOfSymbol(symbol); + if (!(type.flags & 524288 /* Object */)) { + error(getTypeDeclaration(symbol), ts.Diagnostics.Global_type_0_must_be_a_class_or_interface_type, ts.symbolName(symbol)); + return arity ? emptyGenericType : emptyObjectType; + } + if (ts.length(type.typeParameters) !== arity) { + error(getTypeDeclaration(symbol), ts.Diagnostics.Global_type_0_must_have_1_type_parameter_s, ts.symbolName(symbol), arity); + return arity ? emptyGenericType : emptyObjectType; + } + return type; + } + function getGlobalValueSymbol(name, reportErrors) { + return getGlobalSymbol(name, 67220415 /* Value */, reportErrors ? ts.Diagnostics.Cannot_find_global_value_0 : undefined); + } + function getGlobalTypeSymbol(name, reportErrors) { + return getGlobalSymbol(name, 67897832 /* Type */, reportErrors ? ts.Diagnostics.Cannot_find_global_type_0 : undefined); + } + function getGlobalSymbol(name, meaning, diagnostic) { + // Don't track references for global symbols anyway, so value if `isReference` is arbitrary + return resolveName(undefined, name, meaning, diagnostic, name, /*isUse*/ false); + } + function getGlobalType(name, arity, reportErrors) { + var symbol = getGlobalTypeSymbol(name, reportErrors); + return symbol || reportErrors ? getTypeOfGlobalSymbol(symbol, arity) : undefined; + } + function getGlobalTypedPropertyDescriptorType() { + return deferredGlobalTypedPropertyDescriptorType || (deferredGlobalTypedPropertyDescriptorType = getGlobalType("TypedPropertyDescriptor", /*arity*/ 1, /*reportErrors*/ true)) || emptyGenericType; + } + function getGlobalTemplateStringsArrayType() { + return deferredGlobalTemplateStringsArrayType || (deferredGlobalTemplateStringsArrayType = getGlobalType("TemplateStringsArray", /*arity*/ 0, /*reportErrors*/ true)) || emptyObjectType; + } + function getGlobalImportMetaType() { + return deferredGlobalImportMetaType || (deferredGlobalImportMetaType = getGlobalType("ImportMeta", /*arity*/ 0, /*reportErrors*/ true)) || emptyObjectType; + } + function getGlobalESSymbolConstructorSymbol(reportErrors) { + return deferredGlobalESSymbolConstructorSymbol || (deferredGlobalESSymbolConstructorSymbol = getGlobalValueSymbol("Symbol", reportErrors)); + } + function getGlobalESSymbolType(reportErrors) { + return deferredGlobalESSymbolType || (deferredGlobalESSymbolType = getGlobalType("Symbol", /*arity*/ 0, reportErrors)) || emptyObjectType; + } + function getGlobalPromiseType(reportErrors) { + return deferredGlobalPromiseType || (deferredGlobalPromiseType = getGlobalType("Promise", /*arity*/ 1, reportErrors)) || emptyGenericType; + } + function getGlobalPromiseLikeType(reportErrors) { + return deferredGlobalPromiseLikeType || (deferredGlobalPromiseLikeType = getGlobalType("PromiseLike", /*arity*/ 1, reportErrors)) || emptyGenericType; + } + function getGlobalPromiseConstructorSymbol(reportErrors) { + return deferredGlobalPromiseConstructorSymbol || (deferredGlobalPromiseConstructorSymbol = getGlobalValueSymbol("Promise", reportErrors)); + } + function getGlobalPromiseConstructorLikeType(reportErrors) { + return deferredGlobalPromiseConstructorLikeType || (deferredGlobalPromiseConstructorLikeType = getGlobalType("PromiseConstructorLike", /*arity*/ 0, reportErrors)) || emptyObjectType; + } + function getGlobalAsyncIterableType(reportErrors) { + return deferredGlobalAsyncIterableType || (deferredGlobalAsyncIterableType = getGlobalType("AsyncIterable", /*arity*/ 1, reportErrors)) || emptyGenericType; + } + function getGlobalAsyncIteratorType(reportErrors) { + return deferredGlobalAsyncIteratorType || (deferredGlobalAsyncIteratorType = getGlobalType("AsyncIterator", /*arity*/ 1, reportErrors)) || emptyGenericType; + } + function getGlobalAsyncIterableIteratorType(reportErrors) { + return deferredGlobalAsyncIterableIteratorType || (deferredGlobalAsyncIterableIteratorType = getGlobalType("AsyncIterableIterator", /*arity*/ 1, reportErrors)) || emptyGenericType; + } + function getGlobalIterableType(reportErrors) { + return deferredGlobalIterableType || (deferredGlobalIterableType = getGlobalType("Iterable", /*arity*/ 1, reportErrors)) || emptyGenericType; + } + function getGlobalIteratorType(reportErrors) { + return deferredGlobalIteratorType || (deferredGlobalIteratorType = getGlobalType("Iterator", /*arity*/ 1, reportErrors)) || emptyGenericType; + } + function getGlobalIterableIteratorType(reportErrors) { + return deferredGlobalIterableIteratorType || (deferredGlobalIterableIteratorType = getGlobalType("IterableIterator", /*arity*/ 1, reportErrors)) || emptyGenericType; + } + function getGlobalTypeOrUndefined(name, arity) { + if (arity === void 0) { arity = 0; } + var symbol = getGlobalSymbol(name, 67897832 /* Type */, /*diagnostic*/ undefined); + return symbol && getTypeOfGlobalSymbol(symbol, arity); + } + function getGlobalExtractSymbol() { + return deferredGlobalExtractSymbol || (deferredGlobalExtractSymbol = getGlobalSymbol("Extract", 524288 /* TypeAlias */, ts.Diagnostics.Cannot_find_global_type_0)); // TODO: GH#18217 + } + function getGlobalExcludeSymbol() { + return deferredGlobalExcludeSymbol || (deferredGlobalExcludeSymbol = getGlobalSymbol("Exclude", 524288 /* TypeAlias */, ts.Diagnostics.Cannot_find_global_type_0)); // TODO: GH#18217 + } + function getGlobalPickSymbol() { + return deferredGlobalPickSymbol || (deferredGlobalPickSymbol = getGlobalSymbol("Pick", 524288 /* TypeAlias */, ts.Diagnostics.Cannot_find_global_type_0)); // TODO: GH#18217 + } + function getGlobalBigIntType(reportErrors) { + return deferredGlobalBigIntType || (deferredGlobalBigIntType = getGlobalType("BigInt", /*arity*/ 0, reportErrors)) || emptyObjectType; + } + /** + * Instantiates a global type that is generic with some element type, and returns that instantiation. + */ + function createTypeFromGenericGlobalType(genericGlobalType, typeArguments) { + return genericGlobalType !== emptyGenericType ? createTypeReference(genericGlobalType, typeArguments) : emptyObjectType; + } + function createTypedPropertyDescriptorType(propertyType) { + return createTypeFromGenericGlobalType(getGlobalTypedPropertyDescriptorType(), [propertyType]); + } + function createAsyncIterableType(iteratedType) { + return createTypeFromGenericGlobalType(getGlobalAsyncIterableType(/*reportErrors*/ true), [iteratedType]); + } + function createAsyncIterableIteratorType(iteratedType) { + return createTypeFromGenericGlobalType(getGlobalAsyncIterableIteratorType(/*reportErrors*/ true), [iteratedType]); + } + function createIterableType(iteratedType) { + return createTypeFromGenericGlobalType(getGlobalIterableType(/*reportErrors*/ true), [iteratedType]); + } + function createIterableIteratorType(iteratedType) { + return createTypeFromGenericGlobalType(getGlobalIterableIteratorType(/*reportErrors*/ true), [iteratedType]); + } + function createArrayType(elementType) { + return createTypeFromGenericGlobalType(globalArrayType, [elementType]); + } + function createReadonlyArrayType(elementType) { + return createTypeFromGenericGlobalType(globalReadonlyArrayType, [elementType]); + } + function getTypeFromArrayTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + links.resolvedType = createArrayType(getTypeFromTypeNode(node.elementType)); + } + return links.resolvedType; + } + // We represent tuple types as type references to synthesized generic interface types created by + // this function. The types are of the form: + // + // interface Tuple extends Array { 0: T0, 1: T1, 2: T2, ... } + // + // Note that the generic type created by this function has no symbol associated with it. The same + // is true for each of the synthesized type parameters. + function createTupleTypeOfArity(arity, minLength, hasRestElement, associatedNames) { + var typeParameters; + var properties = []; + var maxLength = hasRestElement ? arity - 1 : arity; + if (arity) { + typeParameters = new Array(arity); + for (var i = 0; i < arity; i++) { + var typeParameter = typeParameters[i] = createType(262144 /* TypeParameter */); + if (i < maxLength) { + var property = createSymbol(4 /* Property */ | (i >= minLength ? 16777216 /* Optional */ : 0), "" + i); + property.type = typeParameter; + properties.push(property); + } + } + } + var literalTypes = []; + for (var i = minLength; i <= maxLength; i++) + literalTypes.push(getLiteralType(i)); + var lengthSymbol = createSymbol(4 /* Property */, "length"); + lengthSymbol.type = hasRestElement ? numberType : getUnionType(literalTypes); + properties.push(lengthSymbol); + var type = createObjectType(8 /* Tuple */ | 4 /* Reference */); + type.typeParameters = typeParameters; + type.outerTypeParameters = undefined; + type.localTypeParameters = typeParameters; + type.instantiations = ts.createMap(); + type.instantiations.set(getTypeListId(type.typeParameters), type); + type.target = type; + type.typeArguments = type.typeParameters; + type.thisType = createType(262144 /* TypeParameter */); + type.thisType.isThisType = true; + type.thisType.constraint = type; + type.declaredProperties = properties; + type.declaredCallSignatures = ts.emptyArray; + type.declaredConstructSignatures = ts.emptyArray; + type.declaredStringIndexInfo = undefined; + type.declaredNumberIndexInfo = undefined; + type.minLength = minLength; + type.hasRestElement = hasRestElement; + type.associatedNames = associatedNames; + return type; + } + function getTupleTypeOfArity(arity, minLength, hasRestElement, associatedNames) { + var key = arity + (hasRestElement ? "+" : ",") + minLength + (associatedNames && associatedNames.length ? "," + associatedNames.join(",") : ""); + var type = tupleTypes.get(key); + if (!type) { + tupleTypes.set(key, type = createTupleTypeOfArity(arity, minLength, hasRestElement, associatedNames)); + } + return type; + } + function createTupleType(elementTypes, minLength, hasRestElement, associatedNames) { + if (minLength === void 0) { minLength = elementTypes.length; } + if (hasRestElement === void 0) { hasRestElement = false; } + var arity = elementTypes.length; + if (arity === 1 && hasRestElement) { + return createArrayType(elementTypes[0]); + } + var tupleType = getTupleTypeOfArity(arity, minLength, arity > 0 && hasRestElement, associatedNames); + return elementTypes.length ? createTypeReference(tupleType, elementTypes) : tupleType; + } + function getTypeFromTupleTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + var lastElement = ts.lastOrUndefined(node.elementTypes); + var restElement_1 = lastElement && lastElement.kind === 172 /* RestType */ ? lastElement : undefined; + var minLength = ts.findLastIndex(node.elementTypes, function (n) { return n.kind !== 171 /* OptionalType */ && n !== restElement_1; }) + 1; + var elementTypes = ts.map(node.elementTypes, function (n) { + var type = getTypeFromTypeNode(n); + return n === restElement_1 && getIndexTypeOfType(type, 1 /* Number */) || type; + }); + links.resolvedType = createTupleType(elementTypes, minLength, !!restElement_1); + } + return links.resolvedType; + } + function sliceTupleType(type, index) { + var tuple = type.target; + if (tuple.hasRestElement) { + // don't slice off rest element + index = Math.min(index, getTypeReferenceArity(type) - 1); + } + return createTupleType((type.typeArguments || ts.emptyArray).slice(index), Math.max(0, tuple.minLength - index), tuple.hasRestElement, tuple.associatedNames && tuple.associatedNames.slice(index)); + } + function getTypeFromOptionalTypeNode(node) { + var type = getTypeFromTypeNode(node.type); + return strictNullChecks ? getOptionalType(type) : type; + } + function getTypeId(type) { + return type.id; + } + function containsType(types, type) { + return ts.binarySearch(types, type, getTypeId, ts.compareValues) >= 0; + } + function insertType(types, type) { + var index = ts.binarySearch(types, type, getTypeId, ts.compareValues); + if (index < 0) { + types.splice(~index, 0, type); + return true; + } + return false; + } + // Return true if the given intersection type contains + // more than one unit type or, + // an object type and a nullable type (null or undefined), or + // a string-like type and a type known to be non-string-like, or + // a number-like type and a type known to be non-number-like, or + // a symbol-like type and a type known to be non-symbol-like, or + // a void-like type and a type known to be non-void-like, or + // a non-primitive type and a type known to be primitive. + function isEmptyIntersectionType(type) { + var combined = 0; + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (t.flags & 109440 /* Unit */ && combined & 109440 /* Unit */) { + return true; + } + combined |= t.flags; + if (combined & 98304 /* Nullable */ && combined & (524288 /* Object */ | 67108864 /* NonPrimitive */) || + combined & 67108864 /* NonPrimitive */ && combined & (67238908 /* DisjointDomains */ & ~67108864 /* NonPrimitive */) || + combined & 132 /* StringLike */ && combined & (67238908 /* DisjointDomains */ & ~132 /* StringLike */) || + combined & 296 /* NumberLike */ && combined & (67238908 /* DisjointDomains */ & ~296 /* NumberLike */) || + combined & 2112 /* BigIntLike */ && combined & (67238908 /* DisjointDomains */ & ~2112 /* BigIntLike */) || + combined & 12288 /* ESSymbolLike */ && combined & (67238908 /* DisjointDomains */ & ~12288 /* ESSymbolLike */) || + combined & 49152 /* VoidLike */ && combined & (67238908 /* DisjointDomains */ & ~49152 /* VoidLike */)) { + return true; + } + } + return false; + } + function addTypeToUnion(typeSet, includes, type) { + var flags = type.flags; + if (flags & 1048576 /* Union */) { + return addTypesToUnion(typeSet, includes, type.types); + } + // We ignore 'never' types in unions. Likewise, we ignore intersections of unit types as they are + // another form of 'never' (in that they have an empty value domain). We could in theory turn + // intersections of unit types into 'never' upon construction, but deferring the reduction makes it + // easier to reason about their origin. + if (!(flags & 131072 /* Never */ || flags & 2097152 /* Intersection */ && isEmptyIntersectionType(type))) { + includes |= flags & ~939524096 /* ConstructionFlags */; + if (type === wildcardType) + includes |= 268435456 /* Wildcard */; + if (!strictNullChecks && flags & 98304 /* Nullable */) { + if (!(flags & 134217728 /* ContainsWideningType */)) + includes |= 134217728 /* NonWideningType */; + } + else { + var len = typeSet.length; + var index = len && type.id > typeSet[len - 1].id ? ~len : ts.binarySearch(typeSet, type, getTypeId, ts.compareValues); + if (index < 0) { + typeSet.splice(~index, 0, type); + } + } + } + return includes; + } + // Add the given types to the given type set. Order is preserved, duplicates are removed, + // and nested types of the given kind are flattened into the set. + function addTypesToUnion(typeSet, includes, types) { + for (var _i = 0, types_6 = types; _i < types_6.length; _i++) { + var type = types_6[_i]; + includes = addTypeToUnion(typeSet, includes, type); + } + return includes; + } + function isSubtypeOfAny(source, targets) { + for (var _i = 0, targets_1 = targets; _i < targets_1.length; _i++) { + var target = targets_1[_i]; + if (source !== target && isTypeSubtypeOf(source, target) && (!(ts.getObjectFlags(getTargetType(source)) & 1 /* Class */) || + !(ts.getObjectFlags(getTargetType(target)) & 1 /* Class */) || + isTypeDerivedFrom(source, target))) { + return true; + } + } + return false; + } + function isSetOfLiteralsFromSameEnum(types) { + var first = types[0]; + if (first.flags & 1024 /* EnumLiteral */) { + var firstEnum = getParentOfSymbol(first.symbol); + for (var i = 1; i < types.length; i++) { + var other = types[i]; + if (!(other.flags & 1024 /* EnumLiteral */) || (firstEnum !== getParentOfSymbol(other.symbol))) { + return false; + } + } + return true; + } + return false; + } + function removeSubtypes(types) { + if (types.length === 0 || isSetOfLiteralsFromSameEnum(types)) { + return; + } + var i = types.length; + while (i > 0) { + i--; + if (isSubtypeOfAny(types[i], types)) { + ts.orderedRemoveItemAt(types, i); + } + } + } + function removeRedundantLiteralTypes(types, includes) { + var i = types.length; + while (i > 0) { + i--; + var t = types[i]; + var remove = t.flags & 128 /* StringLiteral */ && includes & 4 /* String */ || + t.flags & 256 /* NumberLiteral */ && includes & 8 /* Number */ || + t.flags & 2048 /* BigIntLiteral */ && includes & 64 /* BigInt */ || + t.flags & 8192 /* UniqueESSymbol */ && includes & 4096 /* ESSymbol */ || + isFreshLiteralType(t) && containsType(types, t.regularType); + if (remove) { + ts.orderedRemoveItemAt(types, i); + } + } + } + // We sort and deduplicate the constituent types based on object identity. If the subtypeReduction + // flag is specified we also reduce the constituent type set to only include types that aren't subtypes + // of other types. Subtype reduction is expensive for large union types and is possible only when union + // types are known not to circularly reference themselves (as is the case with union types created by + // expression constructs such as array literals and the || and ?: operators). Named types can + // circularly reference themselves and therefore cannot be subtype reduced during their declaration. + // For example, "type Item = string | (() => Item" is a named type that circularly references itself. + function getUnionType(types, unionReduction, aliasSymbol, aliasTypeArguments) { + if (unionReduction === void 0) { unionReduction = 1 /* Literal */; } + if (types.length === 0) { + return neverType; + } + if (types.length === 1) { + return types[0]; + } + var typeSet = []; + var includes = addTypesToUnion(typeSet, 0, types); + if (unionReduction !== 0 /* None */) { + if (includes & 3 /* AnyOrUnknown */) { + return includes & 1 /* Any */ ? includes & 268435456 /* Wildcard */ ? wildcardType : anyType : unknownType; + } + switch (unionReduction) { + case 1 /* Literal */: + if (includes & 8576 /* StringOrNumberLiteralOrUnique */ | 512 /* BooleanLiteral */) { + removeRedundantLiteralTypes(typeSet, includes); + } + break; + case 2 /* Subtype */: + removeSubtypes(typeSet); + break; + } + if (typeSet.length === 0) { + return includes & 65536 /* Null */ ? includes & 134217728 /* NonWideningType */ ? nullType : nullWideningType : + includes & 32768 /* Undefined */ ? includes & 134217728 /* NonWideningType */ ? undefinedType : undefinedWideningType : + neverType; + } + } + return getUnionTypeFromSortedList(typeSet, !(includes & 66994211 /* NotPrimitiveUnion */), aliasSymbol, aliasTypeArguments); + } + function getUnionTypePredicate(signatures) { + var first; + var types = []; + for (var _i = 0, signatures_2 = signatures; _i < signatures_2.length; _i++) { + var sig = signatures_2[_i]; + var pred = getTypePredicateOfSignature(sig); + if (!pred) { + continue; + } + if (first) { + if (!typePredicateKindsMatch(first, pred)) { + // No common type predicate. + return undefined; + } + } + else { + first = pred; + } + types.push(pred.type); + } + if (!first) { + // No union signatures had a type predicate. + return undefined; + } + var unionType = getUnionType(types); + return ts.isIdentifierTypePredicate(first) + ? createIdentifierTypePredicate(first.parameterName, first.parameterIndex, unionType) + : createThisTypePredicate(unionType); + } + function typePredicateKindsMatch(a, b) { + return ts.isIdentifierTypePredicate(a) + ? ts.isIdentifierTypePredicate(b) && a.parameterIndex === b.parameterIndex + : !ts.isIdentifierTypePredicate(b); + } + // This function assumes the constituent type list is sorted and deduplicated. + function getUnionTypeFromSortedList(types, primitiveTypesOnly, aliasSymbol, aliasTypeArguments) { + if (types.length === 0) { + return neverType; + } + if (types.length === 1) { + return types[0]; + } + var id = getTypeListId(types); + var type = unionTypes.get(id); + if (!type) { + var propagatedFlags = getPropagatingFlagsOfTypes(types, /*excludeKinds*/ 98304 /* Nullable */); + type = createType(1048576 /* Union */ | propagatedFlags); + unionTypes.set(id, type); + type.types = types; + type.primitiveTypesOnly = primitiveTypesOnly; + /* + Note: This is the alias symbol (or lack thereof) that we see when we first encounter this union type. + For aliases of identical unions, eg `type T = A | B; type U = A | B`, the symbol of the first alias encountered is the aliasSymbol. + (In the language service, the order may depend on the order in which a user takes actions, such as hovering over symbols.) + It's important that we create equivalent union types only once, so that's an unfortunate side effect. + */ + type.aliasSymbol = aliasSymbol; + type.aliasTypeArguments = aliasTypeArguments; + } + return type; + } + function getTypeFromUnionTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + var aliasSymbol = getAliasSymbolForTypeNode(node); + links.resolvedType = getUnionType(ts.map(node.types, getTypeFromTypeNode), 1 /* Literal */, aliasSymbol, getTypeArgumentsForAliasSymbol(aliasSymbol)); + } + return links.resolvedType; + } + function addTypeToIntersection(typeSet, includes, type) { + var flags = type.flags; + if (flags & 2097152 /* Intersection */) { + return addTypesToIntersection(typeSet, includes, type.types); + } + if (isEmptyAnonymousObjectType(type)) { + if (!(includes & 536870912 /* EmptyObject */)) { + includes |= 536870912 /* EmptyObject */; + typeSet.push(type); + } + } + else { + includes |= flags & ~939524096 /* ConstructionFlags */; + if (flags & 3 /* AnyOrUnknown */) { + if (type === wildcardType) + includes |= 268435456 /* Wildcard */; + } + else if ((strictNullChecks || !(flags & 98304 /* Nullable */)) && !ts.contains(typeSet, type)) { + typeSet.push(type); + } + } + return includes; + } + // Add the given types to the given type set. Order is preserved, freshness is removed from literal + // types, duplicates are removed, and nested types of the given kind are flattened into the set. + function addTypesToIntersection(typeSet, includes, types) { + for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { + var type = types_7[_i]; + includes = addTypeToIntersection(typeSet, includes, getRegularTypeOfLiteralType(type)); + } + return includes; + } + function removeRedundantPrimitiveTypes(types, includes) { + var i = types.length; + while (i > 0) { + i--; + var t = types[i]; + var remove = t.flags & 4 /* String */ && includes & 128 /* StringLiteral */ || + t.flags & 8 /* Number */ && includes & 256 /* NumberLiteral */ || + t.flags & 64 /* BigInt */ && includes & 2048 /* BigIntLiteral */ || + t.flags & 4096 /* ESSymbol */ && includes & 8192 /* UniqueESSymbol */; + if (remove) { + ts.orderedRemoveItemAt(types, i); + } + } + } + // Check that the given type has a match in every union. A given type is matched by + // an identical type, and a literal type is additionally matched by its corresponding + // primitive type. + function eachUnionContains(unionTypes, type) { + for (var _i = 0, unionTypes_1 = unionTypes; _i < unionTypes_1.length; _i++) { + var u = unionTypes_1[_i]; + if (!containsType(u.types, type)) { + var primitive = type.flags & 128 /* StringLiteral */ ? stringType : + type.flags & 256 /* NumberLiteral */ ? numberType : + type.flags & 2048 /* BigIntLiteral */ ? bigintType : + type.flags & 8192 /* UniqueESSymbol */ ? esSymbolType : + undefined; + if (!primitive || !containsType(u.types, primitive)) { + return false; + } + } + } + return true; + } + // If the given list of types contains more than one union of primitive types, replace the + // first with a union containing an intersection of those primitive types, then remove the + // other unions and return true. Otherwise, do nothing and return false. + function intersectUnionsOfPrimitiveTypes(types) { + var unionTypes; + var index = ts.findIndex(types, function (t) { return !!(t.flags & 1048576 /* Union */) && t.primitiveTypesOnly; }); + if (index < 0) { + return false; + } + var i = index + 1; + // Remove all but the first union of primitive types and collect them in + // the unionTypes array. + while (i < types.length) { + var t = types[i]; + if (t.flags & 1048576 /* Union */ && t.primitiveTypesOnly) { + (unionTypes || (unionTypes = [types[index]])).push(t); + ts.orderedRemoveItemAt(types, i); + } + else { + i++; + } + } + // Return false if there was only one union of primitive types + if (!unionTypes) { + return false; + } + // We have more than one union of primitive types, now intersect them. For each + // type in each union we check if the type is matched in every union and if so + // we include it in the result. + var checked = []; + var result = []; + for (var _i = 0, unionTypes_2 = unionTypes; _i < unionTypes_2.length; _i++) { + var u = unionTypes_2[_i]; + for (var _a = 0, _b = u.types; _a < _b.length; _a++) { + var t = _b[_a]; + if (insertType(checked, t)) { + if (eachUnionContains(unionTypes, t)) { + insertType(result, t); + } + } + } + } + // Finally replace the first union with the result + types[index] = getUnionTypeFromSortedList(result, /*primitiveTypesOnly*/ true); + return true; + } + // We normalize combinations of intersection and union types based on the distributive property of the '&' + // operator. Specifically, because X & (A | B) is equivalent to X & A | X & B, we can transform intersection + // types with union type constituents into equivalent union types with intersection type constituents and + // effectively ensure that union types are always at the top level in type representations. + // + // We do not perform structural deduplication on intersection types. Intersection types are created only by the & + // type operator and we can't reduce those because we want to support recursive intersection types. For example, + // a type alias of the form "type List = T & { next: List }" cannot be reduced during its declaration. + // Also, unlike union types, the order of the constituent types is preserved in order that overload resolution + // for intersections of types with signatures can be deterministic. + function getIntersectionType(types, aliasSymbol, aliasTypeArguments) { + var typeSet = []; + var includes = addTypesToIntersection(typeSet, 0, types); + if (includes & 131072 /* Never */) { + return neverType; + } + if (includes & 1 /* Any */) { + return includes & 268435456 /* Wildcard */ ? wildcardType : anyType; + } + if (!strictNullChecks && includes & 98304 /* Nullable */) { + return includes & 32768 /* Undefined */ ? undefinedType : nullType; + } + if (includes & 4 /* String */ && includes & 128 /* StringLiteral */ || + includes & 8 /* Number */ && includes & 256 /* NumberLiteral */ || + includes & 64 /* BigInt */ && includes & 2048 /* BigIntLiteral */ || + includes & 4096 /* ESSymbol */ && includes & 8192 /* UniqueESSymbol */) { + removeRedundantPrimitiveTypes(typeSet, includes); + } + if (includes & 536870912 /* EmptyObject */ && includes & 524288 /* Object */) { + ts.orderedRemoveItemAt(typeSet, ts.findIndex(typeSet, isEmptyAnonymousObjectType)); + } + if (typeSet.length === 0) { + return unknownType; + } + if (typeSet.length === 1) { + return typeSet[0]; + } + if (includes & 1048576 /* Union */) { + if (intersectUnionsOfPrimitiveTypes(typeSet)) { + // When the intersection creates a reduced set (which might mean that *all* union types have + // disappeared), we restart the operation to get a new set of combined flags. Once we have + // reduced we'll never reduce again, so this occurs at most once. + return getIntersectionType(typeSet, aliasSymbol, aliasTypeArguments); + } + // We are attempting to construct a type of the form X & (A | B) & Y. Transform this into a type of + // the form X & A & Y | X & B & Y and recursively reduce until no union type constituents remain. + var unionIndex_1 = ts.findIndex(typeSet, function (t) { return (t.flags & 1048576 /* Union */) !== 0; }); + var unionType = typeSet[unionIndex_1]; + return getUnionType(ts.map(unionType.types, function (t) { return getIntersectionType(ts.replaceElement(typeSet, unionIndex_1, t)); }), 1 /* Literal */, aliasSymbol, aliasTypeArguments); + } + var id = getTypeListId(typeSet); + var type = intersectionTypes.get(id); + if (!type) { + var propagatedFlags = getPropagatingFlagsOfTypes(typeSet, /*excludeKinds*/ 98304 /* Nullable */); + type = createType(2097152 /* Intersection */ | propagatedFlags); + intersectionTypes.set(id, type); + type.types = typeSet; + type.aliasSymbol = aliasSymbol; // See comment in `getUnionTypeFromSortedList`. + type.aliasTypeArguments = aliasTypeArguments; + } + return type; + } + function getTypeFromIntersectionTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + var aliasSymbol = getAliasSymbolForTypeNode(node); + links.resolvedType = getIntersectionType(ts.map(node.types, getTypeFromTypeNode), aliasSymbol, getTypeArgumentsForAliasSymbol(aliasSymbol)); + } + return links.resolvedType; + } + function createIndexType(type, stringsOnly) { + var result = createType(4194304 /* Index */); + result.type = type; + result.stringsOnly = stringsOnly; + return result; + } + function getIndexTypeForGenericType(type, stringsOnly) { + return stringsOnly ? + type.resolvedStringIndexType || (type.resolvedStringIndexType = createIndexType(type, /*stringsOnly*/ true)) : + type.resolvedIndexType || (type.resolvedIndexType = createIndexType(type, /*stringsOnly*/ false)); + } + function getLiteralTypeFromPropertyName(name) { + return ts.isIdentifier(name) ? getLiteralType(ts.unescapeLeadingUnderscores(name.escapedText)) : + getRegularTypeOfLiteralType(ts.isComputedPropertyName(name) ? checkComputedPropertyName(name) : checkExpression(name)); + } + function getBigIntLiteralType(node) { + return getLiteralType({ + negative: false, + base10Value: ts.parsePseudoBigInt(node.text) + }); + } + function getLiteralTypeFromProperty(prop, include) { + if (!(ts.getDeclarationModifierFlagsFromSymbol(prop) & 24 /* NonPublicAccessibilityModifier */)) { + var type = getLateBoundSymbol(prop).nameType; + if (!type && !ts.isKnownSymbol(prop)) { + if (prop.escapedName === "default" /* Default */) { + type = getLiteralType("default"); + } + else { + var name = prop.valueDeclaration && ts.getNameOfDeclaration(prop.valueDeclaration); + type = name && getLiteralTypeFromPropertyName(name) || getLiteralType(ts.symbolName(prop)); + } + } + if (type && type.flags & include) { + return type; + } + } + return neverType; + } + function getLiteralTypeFromProperties(type, include) { + return getUnionType(ts.map(getPropertiesOfType(type), function (t) { return getLiteralTypeFromProperty(t, include); })); + } + function getNonEnumNumberIndexInfo(type) { + var numberIndexInfo = getIndexInfoOfType(type, 1 /* Number */); + return numberIndexInfo !== enumNumberIndexInfo ? numberIndexInfo : undefined; + } + function getIndexType(type, stringsOnly) { + if (stringsOnly === void 0) { stringsOnly = keyofStringsOnly; } + return type.flags & 1048576 /* Union */ ? getIntersectionType(ts.map(type.types, function (t) { return getIndexType(t, stringsOnly); })) : + type.flags & 2097152 /* Intersection */ ? getUnionType(ts.map(type.types, function (t) { return getIndexType(t, stringsOnly); })) : + maybeTypeOfKind(type, 58982400 /* InstantiableNonPrimitive */) ? getIndexTypeForGenericType(type, stringsOnly) : + ts.getObjectFlags(type) & 32 /* Mapped */ ? getConstraintTypeFromMappedType(type) : + type === wildcardType ? wildcardType : + type.flags & 1 /* Any */ ? keyofConstraintType : + stringsOnly ? getIndexInfoOfType(type, 0 /* String */) ? stringType : getLiteralTypeFromProperties(type, 128 /* StringLiteral */) : + getIndexInfoOfType(type, 0 /* String */) ? getUnionType([stringType, numberType, getLiteralTypeFromProperties(type, 8192 /* UniqueESSymbol */)]) : + getNonEnumNumberIndexInfo(type) ? getUnionType([numberType, getLiteralTypeFromProperties(type, 128 /* StringLiteral */ | 8192 /* UniqueESSymbol */)]) : + getLiteralTypeFromProperties(type, 8576 /* StringOrNumberLiteralOrUnique */); + } + function getExtractStringType(type) { + if (keyofStringsOnly) { + return type; + } + var extractTypeAlias = getGlobalExtractSymbol(); + return extractTypeAlias ? getTypeAliasInstantiation(extractTypeAlias, [type, stringType]) : stringType; + } + function getIndexTypeOrString(type) { + var indexType = getExtractStringType(getIndexType(type)); + return indexType.flags & 131072 /* Never */ ? stringType : indexType; + } + function getTypeFromTypeOperatorNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + switch (node.operator) { + case 129 /* KeyOfKeyword */: + links.resolvedType = getIndexType(getTypeFromTypeNode(node.type)); + break; + case 142 /* UniqueKeyword */: + links.resolvedType = node.type.kind === 139 /* SymbolKeyword */ + ? getESSymbolLikeTypeForNode(ts.walkUpParenthesizedTypes(node.parent)) + : errorType; + break; + } + } + return links.resolvedType; // TODO: GH#18217 + } + function createIndexedAccessType(objectType, indexType) { + var type = createType(8388608 /* IndexedAccess */); + type.objectType = objectType; + type.indexType = indexType; + return type; + } + /** + * Returns if a type is or consists of a JSLiteral object type + * In addition to objects which are directly literals, + * * unions where every element is a jsliteral + * * intersections where at least one element is a jsliteral + * * and instantiable types constrained to a jsliteral + * Should all count as literals and not print errors on access or assignment of possibly existing properties. + * This mirrors the behavior of the index signature propagation, to which this behaves similarly (but doesn't affect assignability or inference). + */ + function isJSLiteralType(type) { + if (noImplicitAny) { + return false; // Flag is meaningless under `noImplicitAny` mode + } + if (ts.getObjectFlags(type) & 16384 /* JSLiteral */) { + return true; + } + if (type.flags & 1048576 /* Union */) { + return ts.every(type.types, isJSLiteralType); + } + if (type.flags & 2097152 /* Intersection */) { + return ts.some(type.types, isJSLiteralType); + } + if (type.flags & 63176704 /* Instantiable */) { + return isJSLiteralType(getResolvedBaseConstraint(type)); + } + return false; + } + function getPropertyTypeForIndexType(objectType, indexType, accessNode, cacheSymbol, missingType) { + var accessExpression = accessNode && accessNode.kind === 190 /* ElementAccessExpression */ ? accessNode : undefined; + var propName = isTypeUsableAsLateBoundName(indexType) + ? getLateBoundNameFromType(indexType) + : accessExpression && checkThatExpressionIsProperSymbolReference(accessExpression.argumentExpression, indexType, /*reportError*/ false) + ? ts.getPropertyNameForKnownSymbolName(ts.idText(accessExpression.argumentExpression.name)) + : accessNode && ts.isPropertyName(accessNode) + // late bound names are handled in the first branch, so here we only need to handle normal names + ? ts.getPropertyNameForPropertyNameNode(accessNode) + : undefined; + if (propName !== undefined) { + var prop = getPropertyOfType(objectType, propName); + if (prop) { + if (accessExpression) { + markPropertyAsReferenced(prop, accessExpression, /*isThisAccess*/ accessExpression.expression.kind === 100 /* ThisKeyword */); + if (ts.isAssignmentTarget(accessExpression) && (isReferenceToReadonlyEntity(accessExpression, prop) || isReferenceThroughNamespaceImport(accessExpression))) { + error(accessExpression.argumentExpression, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, symbolToString(prop)); + return missingType; + } + if (cacheSymbol) { + getNodeLinks(accessNode).resolvedSymbol = prop; + } + } + var propType = getTypeOfSymbol(prop); + return accessExpression && ts.getAssignmentTargetKind(accessExpression) !== 1 /* Definite */ ? + getFlowTypeOfReference(accessExpression, propType) : + propType; + } + if (everyType(objectType, isTupleType) && isNumericLiteralName(propName) && +propName >= 0) { + if (accessNode && everyType(objectType, function (t) { return !t.target.hasRestElement; })) { + var indexNode = getIndexNodeForAccessExpression(accessNode); + error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(propName), typeToString(objectType)); + } + return mapType(objectType, function (t) { return getRestTypeOfTupleType(t) || undefinedType; }); + } + } + if (!(indexType.flags & 98304 /* Nullable */) && isTypeAssignableToKind(indexType, 132 /* StringLike */ | 296 /* NumberLike */ | 12288 /* ESSymbolLike */)) { + if (objectType.flags & (1 /* Any */ | 131072 /* Never */)) { + return objectType; + } + var indexInfo = isTypeAssignableToKind(indexType, 296 /* NumberLike */) && getIndexInfoOfType(objectType, 1 /* Number */) || + getIndexInfoOfType(objectType, 0 /* String */) || + undefined; + if (indexInfo) { + if (accessNode && !isTypeAssignableToKind(indexType, 4 /* String */ | 8 /* Number */)) { + var indexNode = getIndexNodeForAccessExpression(accessNode); + error(indexNode, ts.Diagnostics.Type_0_cannot_be_used_as_an_index_type, typeToString(indexType)); + } + else if (accessExpression && indexInfo.isReadonly && (ts.isAssignmentTarget(accessExpression) || ts.isDeleteTarget(accessExpression))) { + error(accessExpression, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(objectType)); + } + return indexInfo.type; + } + if (indexType.flags & 131072 /* Never */) { + return neverType; + } + if (isJSLiteralType(objectType)) { + return anyType; + } + if (accessExpression && !isConstEnumObjectType(objectType)) { + if (noImplicitAny && !compilerOptions.suppressImplicitAnyIndexErrors) { + if (propName !== undefined && typeHasStaticProperty(propName, objectType)) { + error(accessExpression, ts.Diagnostics.Property_0_is_a_static_member_of_type_1, propName, typeToString(objectType)); + } + else if (getIndexTypeOfType(objectType, 1 /* Number */)) { + error(accessExpression.argumentExpression, ts.Diagnostics.Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number); + } + else { + var suggestion = void 0; + if (propName !== undefined && (suggestion = getSuggestionForNonexistentProperty(propName, objectType))) { + if (suggestion !== undefined) { + error(accessExpression.argumentExpression, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2, propName, typeToString(objectType), suggestion); + } + } + else { + error(accessExpression, ts.Diagnostics.Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature, typeToString(objectType)); + } + } + } + return missingType; + } + } + if (isJSLiteralType(objectType)) { + return anyType; + } + if (accessNode) { + var indexNode = getIndexNodeForAccessExpression(accessNode); + if (indexType.flags & (128 /* StringLiteral */ | 256 /* NumberLiteral */)) { + error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, "" + indexType.value, typeToString(objectType)); + } + else if (indexType.flags & (4 /* String */ | 8 /* Number */)) { + error(indexNode, ts.Diagnostics.Type_0_has_no_matching_index_signature_for_type_1, typeToString(objectType), typeToString(indexType)); + } + else { + error(indexNode, ts.Diagnostics.Type_0_cannot_be_used_as_an_index_type, typeToString(indexType)); + } + } + if (isTypeAny(indexType)) { + return indexType; + } + return missingType; + } + function getIndexNodeForAccessExpression(accessNode) { + return accessNode.kind === 190 /* ElementAccessExpression */ + ? accessNode.argumentExpression + : accessNode.kind === 180 /* IndexedAccessType */ + ? accessNode.indexType + : accessNode.kind === 149 /* ComputedPropertyName */ + ? accessNode.expression + : accessNode; + } + function isGenericObjectType(type) { + return maybeTypeOfKind(type, 58982400 /* InstantiableNonPrimitive */ | 134217728 /* GenericMappedType */); + } + function isGenericIndexType(type) { + return maybeTypeOfKind(type, 58982400 /* InstantiableNonPrimitive */ | 4194304 /* Index */); + } + function getSimplifiedType(type) { + return type.flags & 8388608 /* IndexedAccess */ ? getSimplifiedIndexedAccessType(type) : type; + } + function distributeIndexOverObjectType(objectType, indexType) { + // (T | U)[K] -> T[K] | U[K] + if (objectType.flags & 1048576 /* Union */) { + return mapType(objectType, function (t) { return getSimplifiedType(getIndexedAccessType(t, indexType)); }); + } + // (T & U)[K] -> T[K] & U[K] + if (objectType.flags & 2097152 /* Intersection */) { + return getIntersectionType(ts.map(objectType.types, function (t) { return getSimplifiedType(getIndexedAccessType(t, indexType)); })); + } + } + // Transform an indexed access to a simpler form, if possible. Return the simpler form, or return + // the type itself if no transformation is possible. + function getSimplifiedIndexedAccessType(type) { + if (type.simplified) { + return type.simplified === circularConstraintType ? type : type.simplified; + } + type.simplified = circularConstraintType; + // We recursively simplify the object type as it may in turn be an indexed access type. For example, with + // '{ [P in T]: { [Q in U]: number } }[T][U]' we want to first simplify the inner indexed access type. + var objectType = getSimplifiedType(type.objectType); + var indexType = getSimplifiedType(type.indexType); + // T[A | B] -> T[A] | T[B] + if (indexType.flags & 1048576 /* Union */) { + return type.simplified = mapType(indexType, function (t) { return getSimplifiedType(getIndexedAccessType(objectType, t)); }); + } + // Only do the inner distributions if the index can no longer be instantiated to cause index distribution again + if (!(indexType.flags & 63176704 /* Instantiable */)) { + var simplified = distributeIndexOverObjectType(objectType, indexType); + if (simplified) { + return type.simplified = simplified; + } + } + // So ultimately: + // ((A & B) | C)[K1 | K2] -> ((A & B) | C)[K1] | ((A & B) | C)[K2] -> (A & B)[K1] | C[K1] | (A & B)[K2] | C[K2] -> (A[K1] & B[K1]) | C[K1] | (A[K2] & B[K2]) | C[K2] + // If the object type is a mapped type { [P in K]: E }, where K is generic, instantiate E using a mapper + // that substitutes the index type for P. For example, for an index access { [P in K]: Box }[X], we + // construct the type Box. We do not further simplify the result because mapped types can be recursive + // and we might never terminate. + if (isGenericMappedType(objectType)) { + return type.simplified = substituteIndexedMappedType(objectType, type); + } + if (objectType.flags & 262144 /* TypeParameter */) { + var constraint = getConstraintOfTypeParameter(objectType); + if (constraint && isGenericMappedType(constraint)) { + return type.simplified = substituteIndexedMappedType(constraint, type); + } + } + return type.simplified = type; + } + function substituteIndexedMappedType(objectType, type) { + var mapper = createTypeMapper([getTypeParameterFromMappedType(objectType)], [type.indexType]); + var templateMapper = combineTypeMappers(objectType.mapper, mapper); + return instantiateType(getTemplateTypeFromMappedType(objectType), templateMapper); + } + function getIndexedAccessType(objectType, indexType, accessNode, missingType) { + if (missingType === void 0) { missingType = accessNode ? errorType : unknownType; } + if (objectType === wildcardType || indexType === wildcardType) { + return wildcardType; + } + // If the index type is generic, or if the object type is generic and doesn't originate in an expression, + // we are performing a higher-order index access where we cannot meaningfully access the properties of the + // object type. Note that for a generic T and a non-generic K, we eagerly resolve T[K] if it originates in + // an expression. This is to preserve backwards compatibility. For example, an element access 'this["foo"]' + // has always been resolved eagerly using the constraint type of 'this' at the given location. + if (isGenericIndexType(indexType) || !(accessNode && accessNode.kind !== 180 /* IndexedAccessType */) && isGenericObjectType(objectType)) { + if (objectType.flags & 3 /* AnyOrUnknown */) { + return objectType; + } + // Defer the operation by creating an indexed access type. + var id = objectType.id + "," + indexType.id; + var type = indexedAccessTypes.get(id); + if (!type) { + indexedAccessTypes.set(id, type = createIndexedAccessType(objectType, indexType)); + } + return type; + } + // In the following we resolve T[K] to the type of the property in T selected by K. + // We treat boolean as different from other unions to improve errors; + // skipping straight to getPropertyTypeForIndexType gives errors with 'boolean' instead of 'true'. + var apparentObjectType = getApparentType(objectType); + if (indexType.flags & 1048576 /* Union */ && !(indexType.flags & 16 /* Boolean */)) { + var propTypes = []; + var wasMissingProp = false; + for (var _i = 0, _a = indexType.types; _i < _a.length; _i++) { + var t = _a[_i]; + var propType = getPropertyTypeForIndexType(apparentObjectType, t, accessNode, /*cacheSymbol*/ false, missingType); + if (propType === missingType) { + if (!accessNode) { + // If there's no error node, we can immeditely stop, since error reporting is off + return missingType; + } + else { + // Otherwise we set a flag and return at the end of the loop so we still mark all errors + wasMissingProp = true; + } + } + propTypes.push(propType); + } + if (wasMissingProp) { + return missingType; + } + return getUnionType(propTypes); + } + return getPropertyTypeForIndexType(apparentObjectType, indexType, accessNode, /*cacheSymbol*/ true, missingType); + } + function getTypeFromIndexedAccessTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + var objectType = getTypeFromTypeNode(node.objectType); + var indexType = getTypeFromTypeNode(node.indexType); + var resolved = getIndexedAccessType(objectType, indexType, node); + links.resolvedType = resolved.flags & 8388608 /* IndexedAccess */ && + resolved.objectType === objectType && + resolved.indexType === indexType ? + getConstrainedTypeVariable(resolved, node) : resolved; + } + return links.resolvedType; + } + function getTypeFromMappedTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + var type = createObjectType(32 /* Mapped */, node.symbol); + type.declaration = node; + type.aliasSymbol = getAliasSymbolForTypeNode(node); + type.aliasTypeArguments = getTypeArgumentsForAliasSymbol(type.aliasSymbol); + links.resolvedType = type; + // Eagerly resolve the constraint type which forces an error if the constraint type circularly + // references itself through one or more type aliases. + getConstraintTypeFromMappedType(type); + } + return links.resolvedType; + } + function getActualTypeVariable(type) { + return type.flags & 33554432 /* Substitution */ ? type.typeVariable : type; + } + function getConditionalType(root, mapper) { + var checkType = instantiateType(root.checkType, mapper); + var extendsType = instantiateType(root.extendsType, mapper); + if (checkType === wildcardType || extendsType === wildcardType) { + return wildcardType; + } + // If this is a distributive conditional type and the check type is generic we need to defer + // resolution of the conditional type such that a later instantiation will properly distribute + // over union types. + var isDeferred = root.isDistributive && maybeTypeOfKind(checkType, 63176704 /* Instantiable */); + var combinedMapper; + if (root.inferTypeParameters) { + var context = createInferenceContext(root.inferTypeParameters, /*signature*/ undefined, 0 /* None */); + if (!isDeferred) { + // We don't want inferences from constraints as they may cause us to eagerly resolve the + // conditional type instead of deferring resolution. Also, we always want strict function + // types rules (i.e. proper contravariance) for inferences. + inferTypes(context.inferences, checkType, extendsType, 32 /* NoConstraints */ | 64 /* AlwaysStrict */); + } + combinedMapper = combineTypeMappers(mapper, context); + } + if (!isDeferred) { + if (extendsType.flags & 3 /* AnyOrUnknown */) { + return instantiateType(root.trueType, mapper); + } + // Return union of trueType and falseType for 'any' since it matches anything + if (checkType.flags & 1 /* Any */) { + return getUnionType([instantiateType(root.trueType, combinedMapper || mapper), instantiateType(root.falseType, mapper)]); + } + // Instantiate the extends type including inferences for 'infer T' type parameters + var inferredExtendsType = combinedMapper ? instantiateType(root.extendsType, combinedMapper) : extendsType; + // Return falseType for a definitely false extends check. We check an instantations of the two + // types with type parameters mapped to the wildcard type, the most permissive instantiations + // possible (the wildcard type is assignable to and from all types). If those are not related, + // then no instatiations will be and we can just return the false branch type. + if (!isTypeAssignableTo(getWildcardInstantiation(checkType), getWildcardInstantiation(inferredExtendsType))) { + return instantiateType(root.falseType, mapper); + } + // Return trueType for a definitely true extends check. The definitely assignable relation excludes + // type variable constraints from consideration. Without the definitely assignable relation, the type + // type Foo = T extends { x: string } ? string : number + // would immediately resolve to 'string' instead of being deferred. + if (checkTypeRelatedTo(checkType, inferredExtendsType, definitelyAssignableRelation, /*errorNode*/ undefined)) { + return instantiateType(root.trueType, combinedMapper || mapper); + } + } + // Return a deferred type for a check that is neither definitely true nor definitely false + var erasedCheckType = getActualTypeVariable(checkType); + var result = createType(16777216 /* Conditional */); + result.root = root; + result.checkType = erasedCheckType; + result.extendsType = extendsType; + result.mapper = mapper; + result.combinedMapper = combinedMapper; + result.aliasSymbol = root.aliasSymbol; + result.aliasTypeArguments = instantiateTypes(root.aliasTypeArguments, mapper); // TODO: GH#18217 + return result; + } + function getTrueTypeFromConditionalType(type) { + return type.resolvedTrueType || (type.resolvedTrueType = instantiateType(type.root.trueType, type.mapper)); + } + function getFalseTypeFromConditionalType(type) { + return type.resolvedFalseType || (type.resolvedFalseType = instantiateType(type.root.falseType, type.mapper)); + } + function getInferTypeParameters(node) { + var result; + if (node.locals) { + node.locals.forEach(function (symbol) { + if (symbol.flags & 262144 /* TypeParameter */) { + result = ts.append(result, getDeclaredTypeOfSymbol(symbol)); + } + }); + } + return result; + } + function isPossiblyReferencedInConditionalType(tp, node) { + if (isTypeParameterPossiblyReferenced(tp, node)) { + return true; + } + while (node) { + if (node.kind === 175 /* ConditionalType */) { + if (isTypeParameterPossiblyReferenced(tp, node.extendsType)) { + return true; + } + } + node = node.parent; + } + return false; + } + function getTypeFromConditionalTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + var checkType = getTypeFromTypeNode(node.checkType); + var aliasSymbol = getAliasSymbolForTypeNode(node); + var aliasTypeArguments = getTypeArgumentsForAliasSymbol(aliasSymbol); + var allOuterTypeParameters = getOuterTypeParameters(node, /*includeThisTypes*/ true); + var outerTypeParameters = aliasTypeArguments ? allOuterTypeParameters : ts.filter(allOuterTypeParameters, function (tp) { return isPossiblyReferencedInConditionalType(tp, node); }); + var root = { + node: node, + checkType: checkType, + extendsType: getTypeFromTypeNode(node.extendsType), + trueType: getTypeFromTypeNode(node.trueType), + falseType: getTypeFromTypeNode(node.falseType), + isDistributive: !!(checkType.flags & 262144 /* TypeParameter */), + inferTypeParameters: getInferTypeParameters(node), + outerTypeParameters: outerTypeParameters, + instantiations: undefined, + aliasSymbol: aliasSymbol, + aliasTypeArguments: aliasTypeArguments + }; + links.resolvedType = getConditionalType(root, /*mapper*/ undefined); + if (outerTypeParameters) { + root.instantiations = ts.createMap(); + root.instantiations.set(getTypeListId(outerTypeParameters), links.resolvedType); + } + } + return links.resolvedType; + } + function getTypeFromInferTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + links.resolvedType = getDeclaredTypeOfTypeParameter(getSymbolOfNode(node.typeParameter)); + } + return links.resolvedType; + } + function getIdentifierChain(node) { + if (ts.isIdentifier(node)) { + return [node]; + } + else { + return ts.append(getIdentifierChain(node.left), node.right); + } + } + function getTypeFromImportTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + if (node.isTypeOf && node.typeArguments) { // Only the non-typeof form can make use of type arguments + error(node, ts.Diagnostics.Type_arguments_cannot_be_used_here); + links.resolvedSymbol = unknownSymbol; + return links.resolvedType = errorType; + } + if (!ts.isLiteralImportTypeNode(node)) { + error(node.argument, ts.Diagnostics.String_literal_expected); + links.resolvedSymbol = unknownSymbol; + return links.resolvedType = errorType; + } + var targetMeaning = node.isTypeOf ? 67220415 /* Value */ : node.flags & 2097152 /* JSDoc */ ? 67220415 /* Value */ | 67897832 /* Type */ : 67897832 /* Type */; + // TODO: Future work: support unions/generics/whatever via a deferred import-type + var innerModuleSymbol = resolveExternalModuleName(node, node.argument.literal); + if (!innerModuleSymbol) { + links.resolvedSymbol = unknownSymbol; + return links.resolvedType = errorType; + } + var moduleSymbol = resolveExternalModuleSymbol(innerModuleSymbol, /*dontResolveAlias*/ false); + if (!ts.nodeIsMissing(node.qualifier)) { + var nameStack = getIdentifierChain(node.qualifier); + var currentNamespace = moduleSymbol; + var current = void 0; + while (current = nameStack.shift()) { + var meaning = nameStack.length ? 1920 /* Namespace */ : targetMeaning; + var next = getSymbol(getExportsOfSymbol(getMergedSymbol(resolveSymbol(currentNamespace))), current.escapedText, meaning); + if (!next) { + error(current, ts.Diagnostics.Namespace_0_has_no_exported_member_1, getFullyQualifiedName(currentNamespace), ts.declarationNameToString(current)); + return links.resolvedType = errorType; + } + getNodeLinks(current).resolvedSymbol = next; + getNodeLinks(current.parent).resolvedSymbol = next; + currentNamespace = next; + } + resolveImportSymbolType(node, links, currentNamespace, targetMeaning); + } + else { + if (moduleSymbol.flags & targetMeaning) { + resolveImportSymbolType(node, links, moduleSymbol, targetMeaning); + } + else { + var errorMessage = targetMeaning === 67220415 /* Value */ + ? ts.Diagnostics.Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here + : ts.Diagnostics.Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0; + error(node, errorMessage, node.argument.literal.text); + links.resolvedSymbol = unknownSymbol; + links.resolvedType = errorType; + } + } + } + return links.resolvedType; // TODO: GH#18217 + } + function resolveImportSymbolType(node, links, symbol, meaning) { + var resolvedSymbol = resolveSymbol(symbol); + links.resolvedSymbol = resolvedSymbol; + if (meaning === 67220415 /* Value */) { + return links.resolvedType = getTypeOfSymbol(symbol); // intentionally doesn't use resolved symbol so type is cached as expected on the alias + } + else { + return links.resolvedType = getTypeReferenceType(node, resolvedSymbol); // getTypeReferenceType doesn't handle aliases - it must get the resolved symbol + } + } + function getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + // Deferred resolution of members is handled by resolveObjectTypeMembers + var aliasSymbol = getAliasSymbolForTypeNode(node); + if (getMembersOfSymbol(node.symbol).size === 0 && !aliasSymbol) { + links.resolvedType = emptyTypeLiteralType; + } + else { + var type = createObjectType(16 /* Anonymous */, node.symbol); + type.aliasSymbol = aliasSymbol; + type.aliasTypeArguments = getTypeArgumentsForAliasSymbol(aliasSymbol); + if (ts.isJSDocTypeLiteral(node) && node.isArrayType) { + type = createArrayType(type); + } + links.resolvedType = type; + } + } + return links.resolvedType; + } + function getAliasSymbolForTypeNode(node) { + return ts.isTypeAlias(node.parent) ? getSymbolOfNode(node.parent) : undefined; + } + function getTypeArgumentsForAliasSymbol(symbol) { + return symbol ? getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) : undefined; + } + function isNonGenericObjectType(type) { + return !!(type.flags & 524288 /* Object */) && !isGenericMappedType(type); + } + /** + * Since the source of spread types are object literals, which are not binary, + * this function should be called in a left folding style, with left = previous result of getSpreadType + * and right = the new element to be spread. + */ + function getSpreadType(left, right, symbol, typeFlags, objectFlags) { + if (left.flags & 1 /* Any */ || right.flags & 1 /* Any */) { + return anyType; + } + if (left.flags & 2 /* Unknown */ || right.flags & 2 /* Unknown */) { + return unknownType; + } + if (left.flags & 131072 /* Never */) { + return right; + } + if (right.flags & 131072 /* Never */) { + return left; + } + if (left.flags & 1048576 /* Union */) { + return mapType(left, function (t) { return getSpreadType(t, right, symbol, typeFlags, objectFlags); }); + } + if (right.flags & 1048576 /* Union */) { + return mapType(right, function (t) { return getSpreadType(left, t, symbol, typeFlags, objectFlags); }); + } + if (right.flags & (528 /* BooleanLike */ | 296 /* NumberLike */ | 2112 /* BigIntLike */ | 132 /* StringLike */ | 1056 /* EnumLike */ | 67108864 /* NonPrimitive */ | 4194304 /* Index */)) { + return left; + } + if (isGenericObjectType(left) || isGenericObjectType(right)) { + if (isEmptyObjectType(left)) { + return right; + } + // When the left type is an intersection, we may need to merge the last constituent of the + // intersection with the right type. For example when the left type is 'T & { a: string }' + // and the right type is '{ b: string }' we produce 'T & { a: string, b: string }'. + if (left.flags & 2097152 /* Intersection */) { + var types = left.types; + var lastLeft = types[types.length - 1]; + if (isNonGenericObjectType(lastLeft) && isNonGenericObjectType(right)) { + return getIntersectionType(ts.concatenate(types.slice(0, types.length - 1), [getSpreadType(lastLeft, right, symbol, typeFlags, objectFlags)])); + } + } + return getIntersectionType([left, right]); + } + var members = ts.createSymbolTable(); + var skippedPrivateMembers = ts.createUnderscoreEscapedMap(); + var stringIndexInfo; + var numberIndexInfo; + if (left === emptyObjectType) { + // for the first spread element, left === emptyObjectType, so take the right's string indexer + stringIndexInfo = getIndexInfoOfType(right, 0 /* String */); + numberIndexInfo = getIndexInfoOfType(right, 1 /* Number */); + } + else { + stringIndexInfo = unionSpreadIndexInfos(getIndexInfoOfType(left, 0 /* String */), getIndexInfoOfType(right, 0 /* String */)); + numberIndexInfo = unionSpreadIndexInfos(getIndexInfoOfType(left, 1 /* Number */), getIndexInfoOfType(right, 1 /* Number */)); + } + for (var _i = 0, _a = getPropertiesOfType(right); _i < _a.length; _i++) { + var rightProp = _a[_i]; + if (ts.getDeclarationModifierFlagsFromSymbol(rightProp) & (8 /* Private */ | 16 /* Protected */)) { + skippedPrivateMembers.set(rightProp.escapedName, true); + } + else if (isSpreadableProperty(rightProp)) { + members.set(rightProp.escapedName, getSpreadSymbol(rightProp)); + } + } + for (var _b = 0, _c = getPropertiesOfType(left); _b < _c.length; _b++) { + var leftProp = _c[_b]; + if (skippedPrivateMembers.has(leftProp.escapedName) || !isSpreadableProperty(leftProp)) { + continue; + } + if (members.has(leftProp.escapedName)) { + var rightProp = members.get(leftProp.escapedName); + var rightType = getTypeOfSymbol(rightProp); + if (rightProp.flags & 16777216 /* Optional */) { + var declarations = ts.concatenate(leftProp.declarations, rightProp.declarations); + var flags = 4 /* Property */ | (leftProp.flags & 16777216 /* Optional */); + var result = createSymbol(flags, leftProp.escapedName); + result.type = getUnionType([getTypeOfSymbol(leftProp), getTypeWithFacts(rightType, 524288 /* NEUndefined */)]); + result.leftSpread = leftProp; + result.rightSpread = rightProp; + result.declarations = declarations; + result.nameType = leftProp.nameType; + members.set(leftProp.escapedName, result); + } + } + else { + members.set(leftProp.escapedName, getSpreadSymbol(leftProp)); + } + } + var spread = createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, getNonReadonlyIndexSignature(stringIndexInfo), getNonReadonlyIndexSignature(numberIndexInfo)); + spread.flags |= 268435456 /* ContainsObjectLiteral */ | typeFlags; + spread.objectFlags |= 128 /* ObjectLiteral */ | 1024 /* ContainsSpread */ | objectFlags; + return spread; + } + /** We approximate own properties as non-methods plus methods that are inside the object literal */ + function isSpreadableProperty(prop) { + return !(prop.flags & (8192 /* Method */ | 32768 /* GetAccessor */ | 65536 /* SetAccessor */)) || + !prop.declarations.some(function (decl) { return ts.isClassLike(decl.parent); }); + } + function getSpreadSymbol(prop) { + var isReadonly = isReadonlySymbol(prop); + var isSetonlyAccessor = prop.flags & 65536 /* SetAccessor */ && !(prop.flags & 32768 /* GetAccessor */); + if (!isReadonly && !isSetonlyAccessor) { + return prop; + } + var flags = 4 /* Property */ | (prop.flags & 16777216 /* Optional */); + var result = createSymbol(flags, prop.escapedName); + result.type = isSetonlyAccessor ? undefinedType : getTypeOfSymbol(prop); + result.declarations = prop.declarations; + result.nameType = prop.nameType; + result.syntheticOrigin = prop; + return result; + } + function getNonReadonlyIndexSignature(index) { + if (index && index.isReadonly) { + return createIndexInfo(index.type, /*isReadonly*/ false, index.declaration); + } + return index; + } + function createLiteralType(flags, value, symbol) { + var type = createType(flags); + type.symbol = symbol; + type.value = value; + return type; + } + function getFreshTypeOfLiteralType(type) { + if (type.flags & 2944 /* Literal */) { + if (!type.freshType) { + var freshType = createLiteralType(type.flags, type.value, type.symbol); + freshType.regularType = type; + freshType.freshType = freshType; + type.freshType = freshType; + } + return type.freshType; + } + return type; + } + function getRegularTypeOfLiteralType(type) { + return type.flags & 2944 /* Literal */ ? type.regularType : + type.flags & 1048576 /* Union */ ? getUnionType(ts.sameMap(type.types, getRegularTypeOfLiteralType)) : + type; + } + function isFreshLiteralType(type) { + return !!(type.flags & 2944 /* Literal */) && type.freshType === type; + } + function getLiteralType(value, enumId, symbol) { + // We store all literal types in a single map with keys of the form '#NNN' and '@SSS', + // where NNN is the text representation of a numeric literal and SSS are the characters + // of a string literal. For literal enum members we use 'EEE#NNN' and 'EEE@SSS', where + // EEE is a unique id for the containing enum type. + var qualifier = typeof value === "number" ? "#" : typeof value === "string" ? "@" : "n"; + var key = (enumId ? enumId : "") + qualifier + (typeof value === "object" ? ts.pseudoBigIntToString(value) : value); + var type = literalTypes.get(key); + if (!type) { + var flags = (typeof value === "number" ? 256 /* NumberLiteral */ : + typeof value === "string" ? 128 /* StringLiteral */ : 2048 /* BigIntLiteral */) | + (enumId ? 1024 /* EnumLiteral */ : 0); + literalTypes.set(key, type = createLiteralType(flags, value, symbol)); + type.regularType = type; + } + return type; + } + function getTypeFromLiteralTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + links.resolvedType = getRegularTypeOfLiteralType(checkExpression(node.literal)); + } + return links.resolvedType; + } + function createUniqueESSymbolType(symbol) { + var type = createType(8192 /* UniqueESSymbol */); + type.symbol = symbol; + return type; + } + function getESSymbolLikeTypeForNode(node) { + if (ts.isValidESSymbolDeclaration(node)) { + var symbol = getSymbolOfNode(node); + var links = getSymbolLinks(symbol); + return links.uniqueESSymbolType || (links.uniqueESSymbolType = createUniqueESSymbolType(symbol)); + } + return esSymbolType; + } + function getThisType(node) { + var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); + var parent = container && container.parent; + if (parent && (ts.isClassLike(parent) || parent.kind === 241 /* InterfaceDeclaration */)) { + if (!ts.hasModifier(container, 32 /* Static */) && + (container.kind !== 157 /* Constructor */ || ts.isNodeDescendantOf(node, container.body))) { + return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(parent)).thisType; + } + } + error(node, ts.Diagnostics.A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface); + return errorType; + } + function getTypeFromThisTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + links.resolvedType = getThisType(node); + } + return links.resolvedType; + } + function getTypeFromTypeNode(node) { + switch (node.kind) { + case 120 /* AnyKeyword */: + case 284 /* JSDocAllType */: + case 285 /* JSDocUnknownType */: + return anyType; + case 143 /* UnknownKeyword */: + return unknownType; + case 138 /* StringKeyword */: + return stringType; + case 135 /* NumberKeyword */: + return numberType; + case 146 /* BigIntKeyword */: + return bigintType; + case 123 /* BooleanKeyword */: + return booleanType; + case 139 /* SymbolKeyword */: + return esSymbolType; + case 106 /* VoidKeyword */: + return voidType; + case 141 /* UndefinedKeyword */: + return undefinedType; + case 96 /* NullKeyword */: + return nullType; + case 132 /* NeverKeyword */: + return neverType; + case 136 /* ObjectKeyword */: + return node.flags & 65536 /* JavaScriptFile */ ? anyType : nonPrimitiveType; + case 178 /* ThisType */: + case 100 /* ThisKeyword */: + return getTypeFromThisTypeNode(node); + case 182 /* LiteralType */: + return getTypeFromLiteralTypeNode(node); + case 164 /* TypeReference */: + return getTypeFromTypeReference(node); + case 163 /* TypePredicate */: + return booleanType; + case 211 /* ExpressionWithTypeArguments */: + return getTypeFromTypeReference(node); + case 167 /* TypeQuery */: + return getTypeFromTypeQueryNode(node); + case 169 /* ArrayType */: + return getTypeFromArrayTypeNode(node); + case 170 /* TupleType */: + return getTypeFromTupleTypeNode(node); + case 171 /* OptionalType */: + return getTypeFromOptionalTypeNode(node); + case 173 /* UnionType */: + return getTypeFromUnionTypeNode(node); + case 174 /* IntersectionType */: + return getTypeFromIntersectionTypeNode(node); + case 286 /* JSDocNullableType */: + return getTypeFromJSDocNullableTypeNode(node); + case 288 /* JSDocOptionalType */: + return addOptionality(getTypeFromTypeNode(node.type)); + case 177 /* ParenthesizedType */: + case 172 /* RestType */: + case 287 /* JSDocNonNullableType */: + case 283 /* JSDocTypeExpression */: + return getTypeFromTypeNode(node.type); + case 290 /* JSDocVariadicType */: + return getTypeFromJSDocVariadicType(node); + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + case 168 /* TypeLiteral */: + case 292 /* JSDocTypeLiteral */: + case 289 /* JSDocFunctionType */: + case 293 /* JSDocSignature */: + return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node); + case 179 /* TypeOperator */: + return getTypeFromTypeOperatorNode(node); + case 180 /* IndexedAccessType */: + return getTypeFromIndexedAccessTypeNode(node); + case 181 /* MappedType */: + return getTypeFromMappedTypeNode(node); + case 175 /* ConditionalType */: + return getTypeFromConditionalTypeNode(node); + case 176 /* InferType */: + return getTypeFromInferTypeNode(node); + case 183 /* ImportType */: + return getTypeFromImportTypeNode(node); + // This function assumes that an identifier or qualified name is a type expression + // Callers should first ensure this by calling isTypeNode + case 72 /* Identifier */: + case 148 /* QualifiedName */: + var symbol = getSymbolAtLocation(node); + return symbol ? getDeclaredTypeOfSymbol(symbol) : errorType; + default: + return errorType; + } + } + function instantiateList(items, mapper, instantiator) { + if (items && items.length) { + for (var i = 0; i < items.length; i++) { + var item = items[i]; + var mapped = instantiator(item, mapper); + if (item !== mapped) { + var result = i === 0 ? [] : items.slice(0, i); + result.push(mapped); + for (i++; i < items.length; i++) { + result.push(instantiator(items[i], mapper)); + } + return result; + } + } + } + return items; + } + function instantiateTypes(types, mapper) { + return instantiateList(types, mapper, instantiateType); + } + function instantiateSignatures(signatures, mapper) { + return instantiateList(signatures, mapper, instantiateSignature); + } + function makeUnaryTypeMapper(source, target) { + return function (t) { return t === source ? target : t; }; + } + function makeBinaryTypeMapper(source1, target1, source2, target2) { + return function (t) { return t === source1 ? target1 : t === source2 ? target2 : t; }; + } + function makeArrayTypeMapper(sources, targets) { + return function (t) { + for (var i = 0; i < sources.length; i++) { + if (t === sources[i]) { + return targets ? targets[i] : anyType; + } + } + return t; + }; + } + function createTypeMapper(sources, targets) { + ts.Debug.assert(targets === undefined || sources.length === targets.length); + return sources.length === 1 ? makeUnaryTypeMapper(sources[0], targets ? targets[0] : anyType) : + sources.length === 2 ? makeBinaryTypeMapper(sources[0], targets ? targets[0] : anyType, sources[1], targets ? targets[1] : anyType) : + makeArrayTypeMapper(sources, targets); + } + function createTypeEraser(sources) { + return createTypeMapper(sources, /*targets*/ undefined); + } + /** + * Maps forward-references to later types parameters to the empty object type. + * This is used during inference when instantiating type parameter defaults. + */ + function createBackreferenceMapper(typeParameters, index) { + return function (t) { return typeParameters.indexOf(t) >= index ? emptyObjectType : t; }; + } + function isInferenceContext(mapper) { + return !!mapper.typeParameters; + } + function cloneTypeMapper(mapper) { + return mapper && isInferenceContext(mapper) ? + createInferenceContext(mapper.typeParameters, mapper.signature, mapper.flags | 1 /* NoDefault */, mapper.compareTypes, mapper.inferences) : + mapper; + } + function combineTypeMappers(mapper1, mapper2) { + if (!mapper1) + return mapper2; + if (!mapper2) + return mapper1; + return function (t) { return instantiateType(mapper1(t), mapper2); }; + } + function createReplacementMapper(source, target, baseMapper) { + return function (t) { return t === source ? target : baseMapper(t); }; + } + function wildcardMapper(type) { + return type.flags & 262144 /* TypeParameter */ ? wildcardType : type; + } + function cloneTypeParameter(typeParameter) { + var result = createType(262144 /* TypeParameter */); + result.symbol = typeParameter.symbol; + result.target = typeParameter; + return result; + } + function instantiateTypePredicate(predicate, mapper) { + if (ts.isIdentifierTypePredicate(predicate)) { + return { + kind: 1 /* Identifier */, + parameterName: predicate.parameterName, + parameterIndex: predicate.parameterIndex, + type: instantiateType(predicate.type, mapper) + }; + } + else { + return { + kind: 0 /* This */, + type: instantiateType(predicate.type, mapper) + }; + } + } + function instantiateSignature(signature, mapper, eraseTypeParameters) { + var freshTypeParameters; + if (signature.typeParameters && !eraseTypeParameters) { + // First create a fresh set of type parameters, then include a mapping from the old to the + // new type parameters in the mapper function. Finally store this mapper in the new type + // parameters such that we can use it when instantiating constraints. + freshTypeParameters = ts.map(signature.typeParameters, cloneTypeParameter); + mapper = combineTypeMappers(createTypeMapper(signature.typeParameters, freshTypeParameters), mapper); + for (var _i = 0, freshTypeParameters_1 = freshTypeParameters; _i < freshTypeParameters_1.length; _i++) { + var tp = freshTypeParameters_1[_i]; + tp.mapper = mapper; + } + } + // Don't compute resolvedReturnType and resolvedTypePredicate now, + // because using `mapper` now could trigger inferences to become fixed. (See `createInferenceContext`.) + // See GH#17600. + var result = createSignature(signature.declaration, freshTypeParameters, signature.thisParameter && instantiateSymbol(signature.thisParameter, mapper), instantiateList(signature.parameters, mapper, instantiateSymbol), + /*resolvedReturnType*/ undefined, + /*resolvedTypePredicate*/ undefined, signature.minArgumentCount, signature.hasRestParameter, signature.hasLiteralTypes); + result.target = signature; + result.mapper = mapper; + return result; + } + function instantiateSymbol(symbol, mapper) { + var links = getSymbolLinks(symbol); + if (links.type && !maybeTypeOfKind(links.type, 524288 /* Object */ | 63176704 /* Instantiable */)) { + // If the type of the symbol is already resolved, and if that type could not possibly + // be affected by instantiation, simply return the symbol itself. + return symbol; + } + if (ts.getCheckFlags(symbol) & 1 /* Instantiated */) { + // If symbol being instantiated is itself a instantiation, fetch the original target and combine the + // type mappers. This ensures that original type identities are properly preserved and that aliases + // always reference a non-aliases. + symbol = links.target; + mapper = combineTypeMappers(links.mapper, mapper); + } + // Keep the flags from the symbol we're instantiating. Mark that is instantiated, and + // also transient so that we can just store data on it directly. + var result = createSymbol(symbol.flags, symbol.escapedName, 1 /* Instantiated */ | ts.getCheckFlags(symbol) & (1024 /* Late */ | 4096 /* OptionalParameter */ | 8192 /* RestParameter */)); + result.declarations = symbol.declarations; + result.parent = symbol.parent; + result.target = symbol; + result.mapper = mapper; + if (symbol.valueDeclaration) { + result.valueDeclaration = symbol.valueDeclaration; + } + if (symbol.nameType) { + result.nameType = symbol.nameType; + } + return result; + } + function getAnonymousTypeInstantiation(type, mapper) { + var target = type.objectFlags & 64 /* Instantiated */ ? type.target : type; + var symbol = target.symbol; + var links = getSymbolLinks(symbol); + var typeParameters = links.outerTypeParameters; + if (!typeParameters) { + // The first time an anonymous type is instantiated we compute and store a list of the type + // parameters that are in scope (and therefore potentially referenced). For type literals that + // aren't the right hand side of a generic type alias declaration we optimize by reducing the + // set of type parameters to those that are possibly referenced in the literal. + var declaration_1 = symbol.declarations[0]; + if (ts.isInJSFile(declaration_1)) { + var paramTag = ts.findAncestor(declaration_1, ts.isJSDocParameterTag); + if (paramTag) { + var paramSymbol = ts.getParameterSymbolFromJSDoc(paramTag); + if (paramSymbol) { + declaration_1 = paramSymbol.valueDeclaration; + } + } + } + var outerTypeParameters = getOuterTypeParameters(declaration_1, /*includeThisTypes*/ true); + if (isJSConstructor(declaration_1)) { + var templateTagParameters = getTypeParametersFromDeclaration(declaration_1); + outerTypeParameters = ts.addRange(outerTypeParameters, templateTagParameters); + } + typeParameters = outerTypeParameters || ts.emptyArray; + typeParameters = symbol.flags & 2048 /* TypeLiteral */ && !target.aliasTypeArguments ? + ts.filter(typeParameters, function (tp) { return isTypeParameterPossiblyReferenced(tp, declaration_1); }) : + typeParameters; + links.outerTypeParameters = typeParameters; + if (typeParameters.length) { + links.instantiations = ts.createMap(); + links.instantiations.set(getTypeListId(typeParameters), target); + } + } + if (typeParameters.length) { + // We are instantiating an anonymous type that has one or more type parameters in scope. Apply the + // mapper to the type parameters to produce the effective list of type arguments, and compute the + // instantiation cache key from the type IDs of the type arguments. + var combinedMapper = type.objectFlags & 64 /* Instantiated */ ? combineTypeMappers(type.mapper, mapper) : mapper; + var typeArguments = ts.map(typeParameters, combinedMapper); + var id = getTypeListId(typeArguments); + var result = links.instantiations.get(id); + if (!result) { + var newMapper = createTypeMapper(typeParameters, typeArguments); + result = target.objectFlags & 32 /* Mapped */ ? instantiateMappedType(target, newMapper) : instantiateAnonymousType(target, newMapper); + links.instantiations.set(id, result); + } + return result; + } + return type; + } + function maybeTypeParameterReference(node) { + return !(node.kind === 148 /* QualifiedName */ || + node.parent.kind === 164 /* TypeReference */ && node.parent.typeArguments && node === node.parent.typeName); + } + function isTypeParameterPossiblyReferenced(tp, node) { + // If the type parameter doesn't have exactly one declaration, if there are invening statement blocks + // between the node and the type parameter declaration, if the node contains actual references to the + // type parameter, or if the node contains type queries, we consider the type parameter possibly referenced. + if (tp.symbol && tp.symbol.declarations && tp.symbol.declarations.length === 1) { + var container_3 = tp.symbol.declarations[0].parent; + if (ts.findAncestor(node, function (n) { return n.kind === 218 /* Block */ ? "quit" : n === container_3; })) { + return !!ts.forEachChild(node, containsReference); + } + } + return true; + function containsReference(node) { + switch (node.kind) { + case 178 /* ThisType */: + return !!tp.isThisType; + case 72 /* Identifier */: + return !tp.isThisType && ts.isPartOfTypeNode(node) && maybeTypeParameterReference(node) && + getTypeFromTypeNode(node) === tp; + case 167 /* TypeQuery */: + return true; + } + return !!ts.forEachChild(node, containsReference); + } + } + function getHomomorphicTypeVariable(type) { + var constraintType = getConstraintTypeFromMappedType(type); + if (constraintType.flags & 4194304 /* Index */) { + var typeVariable = constraintType.type; + if (typeVariable.flags & 262144 /* TypeParameter */) { + return typeVariable; + } + } + return undefined; + } + function instantiateMappedType(type, mapper) { + // For a homomorphic mapped type { [P in keyof T]: X }, where T is some type variable, the mapping + // operation depends on T as follows: + // * If T is a primitive type no mapping is performed and the result is simply T. + // * If T is a union type we distribute the mapped type over the union. + // * If T is an array we map to an array where the element type has been transformed. + // * If T is a tuple we map to a tuple where the element types have been transformed. + // * Otherwise we map to an object type where the type of each property has been transformed. + // For example, when T is instantiated to a union type A | B, we produce { [P in keyof A]: X } | + // { [P in keyof B]: X }, and when when T is instantiated to a union type A | undefined, we produce + // { [P in keyof A]: X } | undefined. + var typeVariable = getHomomorphicTypeVariable(type); + if (typeVariable) { + var mappedTypeVariable = instantiateType(typeVariable, mapper); + if (typeVariable !== mappedTypeVariable) { + // If we are already in the process of creating an instantiation of this mapped type, + // return the error type. This situation only arises if we are instantiating the mapped + // type for an array or tuple type, as we then need to eagerly resolve the (possibly + // circular) element type(s). + if (type.instantiating) { + return errorType; + } + type.instantiating = true; + var result = mapType(mappedTypeVariable, function (t) { + if (t.flags & (3 /* AnyOrUnknown */ | 58982400 /* InstantiableNonPrimitive */ | 524288 /* Object */ | 2097152 /* Intersection */) && t !== wildcardType) { + var replacementMapper = createReplacementMapper(typeVariable, t, mapper); + return isArrayType(t) ? createArrayType(instantiateMappedTypeTemplate(type, numberType, /*isOptional*/ true, replacementMapper)) : + isReadonlyArrayType(t) ? createReadonlyArrayType(instantiateMappedTypeTemplate(type, numberType, /*isOptional*/ true, replacementMapper)) : + isTupleType(t) ? instantiateMappedTupleType(t, type, replacementMapper) : + instantiateAnonymousType(type, replacementMapper); + } + return t; + }); + type.instantiating = false; + return result; + } + } + return instantiateAnonymousType(type, mapper); + } + function instantiateMappedTupleType(tupleType, mappedType, mapper) { + var minLength = tupleType.target.minLength; + var elementTypes = ts.map(tupleType.typeArguments || ts.emptyArray, function (_, i) { + return instantiateMappedTypeTemplate(mappedType, getLiteralType("" + i), i >= minLength, mapper); + }); + var modifiers = getMappedTypeModifiers(mappedType); + var newMinLength = modifiers & 4 /* IncludeOptional */ ? 0 : + modifiers & 8 /* ExcludeOptional */ ? getTypeReferenceArity(tupleType) - (tupleType.target.hasRestElement ? 1 : 0) : + minLength; + return createTupleType(elementTypes, newMinLength, tupleType.target.hasRestElement, tupleType.target.associatedNames); + } + function instantiateMappedTypeTemplate(type, key, isOptional, mapper) { + var templateMapper = combineTypeMappers(mapper, createTypeMapper([getTypeParameterFromMappedType(type)], [key])); + var propType = instantiateType(getTemplateTypeFromMappedType(type.target || type), templateMapper); + var modifiers = getMappedTypeModifiers(type); + return strictNullChecks && modifiers & 4 /* IncludeOptional */ && !isTypeAssignableTo(undefinedType, propType) ? getOptionalType(propType) : + strictNullChecks && modifiers & 8 /* ExcludeOptional */ && isOptional ? getTypeWithFacts(propType, 524288 /* NEUndefined */) : + propType; + } + function instantiateAnonymousType(type, mapper) { + var result = createObjectType(type.objectFlags | 64 /* Instantiated */, type.symbol); + if (type.objectFlags & 32 /* Mapped */) { + result.declaration = type.declaration; + // C.f. instantiateSignature + var origTypeParameter = getTypeParameterFromMappedType(type); + var freshTypeParameter = cloneTypeParameter(origTypeParameter); + result.typeParameter = freshTypeParameter; + mapper = combineTypeMappers(makeUnaryTypeMapper(origTypeParameter, freshTypeParameter), mapper); + freshTypeParameter.mapper = mapper; + } + result.target = type; + result.mapper = mapper; + result.aliasSymbol = type.aliasSymbol; + result.aliasTypeArguments = instantiateTypes(type.aliasTypeArguments, mapper); + return result; + } + function getConditionalTypeInstantiation(type, mapper) { + var root = type.root; + if (root.outerTypeParameters) { + // We are instantiating a conditional type that has one or more type parameters in scope. Apply the + // mapper to the type parameters to produce the effective list of type arguments, and compute the + // instantiation cache key from the type IDs of the type arguments. + var typeArguments = ts.map(root.outerTypeParameters, mapper); + var id = getTypeListId(typeArguments); + var result = root.instantiations.get(id); + if (!result) { + var newMapper = createTypeMapper(root.outerTypeParameters, typeArguments); + result = instantiateConditionalType(root, newMapper); + root.instantiations.set(id, result); + } + return result; + } + return type; + } + function instantiateConditionalType(root, mapper) { + // Check if we have a conditional type where the check type is a naked type parameter. If so, + // the conditional type is distributive over union types and when T is instantiated to a union + // type A | B, we produce (A extends U ? X : Y) | (B extends U ? X : Y). + if (root.isDistributive) { + var checkType_1 = root.checkType; + var instantiatedType = mapper(checkType_1); + if (checkType_1 !== instantiatedType && instantiatedType.flags & (1048576 /* Union */ | 131072 /* Never */)) { + return mapType(instantiatedType, function (t) { return getConditionalType(root, createReplacementMapper(checkType_1, t, mapper)); }); + } + } + return getConditionalType(root, mapper); + } + function instantiateType(type, mapper) { + if (!type || !mapper || mapper === identityMapper) { + return type; + } + if (instantiationDepth === 50) { + // We have reached 50 recursive type instantiations and there is a very high likelyhood we're dealing + // with a combination of infinite generic types that perpetually generate new type identities. We stop + // the recursion here by yielding the error type. + return errorType; + } + instantiationDepth++; + var result = instantiateTypeWorker(type, mapper); + instantiationDepth--; + return result; + } + function instantiateTypeWorker(type, mapper) { + var flags = type.flags; + if (flags & 262144 /* TypeParameter */) { + return mapper(type); + } + if (flags & 524288 /* Object */) { + var objectFlags = type.objectFlags; + if (objectFlags & 16 /* Anonymous */) { + // If the anonymous type originates in a declaration of a function, method, class, or + // interface, in an object type literal, or in an object literal expression, we may need + // to instantiate the type because it might reference a type parameter. + return type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && type.symbol.declarations ? + getAnonymousTypeInstantiation(type, mapper) : type; + } + if (objectFlags & 32 /* Mapped */) { + return getAnonymousTypeInstantiation(type, mapper); + } + if (objectFlags & 4 /* Reference */) { + var typeArguments = type.typeArguments; + var newTypeArguments = instantiateTypes(typeArguments, mapper); + return newTypeArguments !== typeArguments ? createTypeReference(type.target, newTypeArguments) : type; + } + return type; + } + if (flags & 1048576 /* Union */ && !(flags & 131068 /* Primitive */)) { + var types = type.types; + var newTypes = instantiateTypes(types, mapper); + return newTypes !== types ? getUnionType(newTypes, 1 /* Literal */, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type; + } + if (flags & 2097152 /* Intersection */) { + var types = type.types; + var newTypes = instantiateTypes(types, mapper); + return newTypes !== types ? getIntersectionType(newTypes, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type; + } + if (flags & 4194304 /* Index */) { + return getIndexType(instantiateType(type.type, mapper)); + } + if (flags & 8388608 /* IndexedAccess */) { + return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper)); + } + if (flags & 16777216 /* Conditional */) { + return getConditionalTypeInstantiation(type, combineTypeMappers(type.mapper, mapper)); + } + if (flags & 33554432 /* Substitution */) { + return instantiateType(type.typeVariable, mapper); + } + return type; + } + function getWildcardInstantiation(type) { + return type.flags & (131068 /* Primitive */ | 3 /* AnyOrUnknown */ | 131072 /* Never */) ? type : + type.wildcardInstantiation || (type.wildcardInstantiation = instantiateType(type, wildcardMapper)); + } + function instantiateIndexInfo(info, mapper) { + return info && createIndexInfo(instantiateType(info.type, mapper), info.isReadonly, info.declaration); + } + // Returns true if the given expression contains (at any level of nesting) a function or arrow expression + // that is subject to contextual typing. + function isContextSensitive(node) { + ts.Debug.assert(node.kind !== 156 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + switch (node.kind) { + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 156 /* MethodDeclaration */: + return isContextSensitiveFunctionLikeDeclaration(node); + case 188 /* ObjectLiteralExpression */: + return ts.some(node.properties, isContextSensitive); + case 187 /* ArrayLiteralExpression */: + return ts.some(node.elements, isContextSensitive); + case 205 /* ConditionalExpression */: + return isContextSensitive(node.whenTrue) || + isContextSensitive(node.whenFalse); + case 204 /* BinaryExpression */: + return node.operatorToken.kind === 55 /* BarBarToken */ && + (isContextSensitive(node.left) || isContextSensitive(node.right)); + case 275 /* PropertyAssignment */: + return isContextSensitive(node.initializer); + case 195 /* ParenthesizedExpression */: + return isContextSensitive(node.expression); + case 268 /* JsxAttributes */: + return ts.some(node.properties, isContextSensitive) || ts.isJsxOpeningElement(node.parent) && ts.some(node.parent.parent.children, isContextSensitive); + case 267 /* JsxAttribute */: { + // If there is no initializer, JSX attribute has a boolean value of true which is not context sensitive. + var initializer = node.initializer; + return !!initializer && isContextSensitive(initializer); + } + case 270 /* JsxExpression */: { + // It is possible to that node.expression is undefined (e.g
      ) + var expression = node.expression; + return !!expression && isContextSensitive(expression); + } + } + return false; + } + function isContextSensitiveFunctionLikeDeclaration(node) { + // Functions with type parameters are not context sensitive. + if (node.typeParameters) { + return false; + } + // Functions with any parameters that lack type annotations are context sensitive. + if (ts.some(node.parameters, function (p) { return !ts.getEffectiveTypeAnnotationNode(p); })) { + return true; + } + if (node.kind !== 197 /* ArrowFunction */) { + // If the first parameter is not an explicit 'this' parameter, then the function has + // an implicit 'this' parameter which is subject to contextual typing. + var parameter = ts.firstOrUndefined(node.parameters); + if (!(parameter && ts.parameterIsThisKeyword(parameter))) { + return true; + } + } + return hasContextSensitiveReturnExpression(node); + } + function hasContextSensitiveReturnExpression(node) { + // TODO(anhans): A block should be context-sensitive if it has a context-sensitive return value. + var body = node.body; + return body.kind === 218 /* Block */ ? false : isContextSensitive(body); + } + function isContextSensitiveFunctionOrObjectLiteralMethod(func) { + return (ts.isInJSFile(func) && ts.isFunctionDeclaration(func) || isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && + isContextSensitiveFunctionLikeDeclaration(func); + } + function getTypeWithoutSignatures(type) { + if (type.flags & 524288 /* Object */) { + var resolved = resolveStructuredTypeMembers(type); + if (resolved.constructSignatures.length || resolved.callSignatures.length) { + var result = createObjectType(16 /* Anonymous */, type.symbol); + result.members = resolved.members; + result.properties = resolved.properties; + result.callSignatures = ts.emptyArray; + result.constructSignatures = ts.emptyArray; + return result; + } + } + else if (type.flags & 2097152 /* Intersection */) { + return getIntersectionType(ts.map(type.types, getTypeWithoutSignatures)); + } + return type; + } + // TYPE CHECKING + function isTypeIdenticalTo(source, target) { + return isTypeRelatedTo(source, target, identityRelation); + } + function compareTypesIdentical(source, target) { + return isTypeRelatedTo(source, target, identityRelation) ? -1 /* True */ : 0 /* False */; + } + function compareTypesAssignable(source, target) { + return isTypeRelatedTo(source, target, assignableRelation) ? -1 /* True */ : 0 /* False */; + } + function compareTypesSubtypeOf(source, target) { + return isTypeRelatedTo(source, target, subtypeRelation) ? -1 /* True */ : 0 /* False */; + } + function isTypeSubtypeOf(source, target) { + return isTypeRelatedTo(source, target, subtypeRelation); + } + function isTypeAssignableTo(source, target) { + return isTypeRelatedTo(source, target, assignableRelation); + } + // An object type S is considered to be derived from an object type T if + // S is a union type and every constituent of S is derived from T, + // T is a union type and S is derived from at least one constituent of T, or + // S is a type variable with a base constraint that is derived from T, + // T is one of the global types Object and Function and S is a subtype of T, or + // T occurs directly or indirectly in an 'extends' clause of S. + // Note that this check ignores type parameters and only considers the + // inheritance hierarchy. + function isTypeDerivedFrom(source, target) { + return source.flags & 1048576 /* Union */ ? ts.every(source.types, function (t) { return isTypeDerivedFrom(t, target); }) : + target.flags & 1048576 /* Union */ ? ts.some(target.types, function (t) { return isTypeDerivedFrom(source, t); }) : + source.flags & 58982400 /* InstantiableNonPrimitive */ ? isTypeDerivedFrom(getBaseConstraintOfType(source) || emptyObjectType, target) : + target === globalObjectType ? !!(source.flags & (524288 /* Object */ | 67108864 /* NonPrimitive */)) : + target === globalFunctionType ? !!(source.flags & 524288 /* Object */) && isFunctionObjectType(source) : + hasBaseType(source, getTargetType(target)); + } + /** + * This is *not* a bi-directional relationship. + * If one needs to check both directions for comparability, use a second call to this function or 'checkTypeComparableTo'. + * + * A type S is comparable to a type T if some (but not necessarily all) of the possible values of S are also possible values of T. + * It is used to check following cases: + * - the types of the left and right sides of equality/inequality operators (`===`, `!==`, `==`, `!=`). + * - the types of `case` clause expressions and their respective `switch` expressions. + * - the type of an expression in a type assertion with the type being asserted. + */ + function isTypeComparableTo(source, target) { + return isTypeRelatedTo(source, target, comparableRelation); + } + function areTypesComparable(type1, type2) { + return isTypeComparableTo(type1, type2) || isTypeComparableTo(type2, type1); + } + function checkTypeAssignableTo(source, target, errorNode, headMessage, containingMessageChain, errorOutputObject) { + return checkTypeRelatedTo(source, target, assignableRelation, errorNode, headMessage, containingMessageChain, errorOutputObject); + } + /** + * Like `checkTypeAssignableTo`, but if it would issue an error, instead performs structural comparisons of the types using the given expression node to + * attempt to issue more specific errors on, for example, specific object literal properties or tuple members. + */ + function checkTypeAssignableToAndOptionallyElaborate(source, target, errorNode, expr, headMessage, containingMessageChain) { + return checkTypeRelatedToAndOptionallyElaborate(source, target, assignableRelation, errorNode, expr, headMessage, containingMessageChain); + } + function checkTypeRelatedToAndOptionallyElaborate(source, target, relation, errorNode, expr, headMessage, containingMessageChain) { + if (isTypeRelatedTo(source, target, relation)) + return true; + if (!errorNode || !elaborateError(expr, source, target, relation, headMessage)) { + return checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain); + } + return false; + } + function isOrHasGenericConditional(type) { + return !!(type.flags & 16777216 /* Conditional */ || (type.flags & 2097152 /* Intersection */ && ts.some(type.types, isOrHasGenericConditional))); + } + function elaborateError(node, source, target, relation, headMessage) { + if (!node || isOrHasGenericConditional(target)) + return false; + if (!checkTypeRelatedTo(source, target, relation, /*errorNode*/ undefined) && elaborateDidYouMeanToCallOrConstruct(node, source, target, relation, headMessage)) { + return true; + } + switch (node.kind) { + case 270 /* JsxExpression */: + case 195 /* ParenthesizedExpression */: + return elaborateError(node.expression, source, target, relation, headMessage); + case 204 /* BinaryExpression */: + switch (node.operatorToken.kind) { + case 59 /* EqualsToken */: + case 27 /* CommaToken */: + return elaborateError(node.right, source, target, relation, headMessage); + } + break; + case 188 /* ObjectLiteralExpression */: + return elaborateObjectLiteral(node, source, target, relation); + case 187 /* ArrayLiteralExpression */: + return elaborateArrayLiteral(node, source, target, relation); + case 268 /* JsxAttributes */: + return elaborateJsxAttributes(node, source, target, relation); + case 197 /* ArrowFunction */: + return elaborateArrowFunction(node, source, target, relation); + } + return false; + } + function elaborateDidYouMeanToCallOrConstruct(node, source, target, relation, headMessage) { + var callSignatures = getSignaturesOfType(source, 0 /* Call */); + var constructSignatures = getSignaturesOfType(source, 1 /* Construct */); + for (var _i = 0, _a = [constructSignatures, callSignatures]; _i < _a.length; _i++) { + var signatures = _a[_i]; + if (ts.some(signatures, function (s) { + var returnType = getReturnTypeOfSignature(s); + return !(returnType.flags & (1 /* Any */ | 131072 /* Never */)) && checkTypeRelatedTo(returnType, target, relation, /*errorNode*/ undefined); + })) { + var resultObj = {}; + checkTypeAssignableTo(source, target, node, headMessage, /*containingChain*/ undefined, resultObj); + var diagnostic = resultObj.error; + addRelatedInfo(diagnostic, ts.createDiagnosticForNode(node, signatures === constructSignatures ? ts.Diagnostics.Did_you_mean_to_use_new_with_this_expression : ts.Diagnostics.Did_you_mean_to_call_this_expression)); + return true; + } + } + return false; + } + function elaborateArrowFunction(node, source, target, relation) { + // Don't elaborate blocks + if (ts.isBlock(node.body)) { + return false; + } + // Or functions with annotated parameter types + if (ts.some(node.parameters, ts.hasType)) { + return false; + } + var sourceSig = getSingleCallSignature(source); + if (!sourceSig) { + return false; + } + var targetSignatures = getSignaturesOfType(target, 0 /* Call */); + if (!ts.length(targetSignatures)) { + return false; + } + var returnExpression = node.body; + var sourceReturn = getReturnTypeOfSignature(sourceSig); + var targetReturn = getUnionType(ts.map(targetSignatures, getReturnTypeOfSignature)); + if (!checkTypeRelatedTo(sourceReturn, targetReturn, relation, /*errorNode*/ undefined)) { + var elaborated = returnExpression && elaborateError(returnExpression, sourceReturn, targetReturn, relation, /*headMessage*/ undefined); + if (elaborated) { + return elaborated; + } + var resultObj = {}; + checkTypeRelatedTo(sourceReturn, targetReturn, relation, returnExpression, /*message*/ undefined, /*chain*/ undefined, resultObj); + if (resultObj.error) { + if (target.symbol && ts.length(target.symbol.declarations)) { + addRelatedInfo(resultObj.error, ts.createDiagnosticForNode(target.symbol.declarations[0], ts.Diagnostics.The_expected_type_comes_from_the_return_type_of_this_signature)); + } + return true; + } + } + return false; + } + /** + * For every element returned from the iterator, checks that element to issue an error on a property of that element's type + * If that element would issue an error, we first attempt to dive into that element's inner expression and issue a more specific error by recuring into `elaborateError` + * Otherwise, we issue an error on _every_ element which fail the assignability check + */ + function elaborateElementwise(iterator, source, target, relation) { + // Assignability failure - check each prop individually, and if that fails, fall back on the bad error span + var reportedError = false; + for (var status = iterator.next(); !status.done; status = iterator.next()) { + var _a = status.value, prop = _a.errorNode, next = _a.innerExpression, nameType = _a.nameType, errorMessage = _a.errorMessage; + var targetPropType = getIndexedAccessType(target, nameType, /*accessNode*/ undefined, errorType); + if (targetPropType === errorType || targetPropType.flags & 8388608 /* IndexedAccess */) + continue; // Don't elaborate on indexes on generic variables + var sourcePropType = getIndexedAccessType(source, nameType, /*accessNode*/ undefined, errorType); + if (sourcePropType !== errorType && targetPropType !== errorType && !checkTypeRelatedTo(sourcePropType, targetPropType, relation, /*errorNode*/ undefined)) { + var elaborated = next && elaborateError(next, sourcePropType, targetPropType, relation, /*headMessage*/ undefined); + if (elaborated) { + reportedError = true; + } + else { + // Issue error on the prop itself, since the prop couldn't elaborate the error + var resultObj = {}; + // Use the expression type, if available + var specificSource = next ? checkExpressionForMutableLocation(next, 0 /* Normal */, sourcePropType) : sourcePropType; + var result = checkTypeRelatedTo(specificSource, targetPropType, relation, prop, errorMessage, /*containingChain*/ undefined, resultObj); + if (result && specificSource !== sourcePropType) { + // If for whatever reason the expression type doesn't yield an error, make sure we still issue an error on the sourcePropType + checkTypeRelatedTo(sourcePropType, targetPropType, relation, prop, errorMessage, /*containingChain*/ undefined, resultObj); + } + if (resultObj.error) { + var reportedDiag = resultObj.error; + var propertyName = isTypeUsableAsLateBoundName(nameType) ? getLateBoundNameFromType(nameType) : undefined; + var targetProp = propertyName !== undefined ? getPropertyOfType(target, propertyName) : undefined; + var issuedElaboration = false; + if (!targetProp) { + var indexInfo = isTypeAssignableToKind(nameType, 296 /* NumberLike */) && getIndexInfoOfType(target, 1 /* Number */) || + getIndexInfoOfType(target, 0 /* String */) || + undefined; + if (indexInfo && indexInfo.declaration && !ts.getSourceFileOfNode(indexInfo.declaration).hasNoDefaultLib) { + issuedElaboration = true; + addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(indexInfo.declaration, ts.Diagnostics.The_expected_type_comes_from_this_index_signature)); + } + } + if (!issuedElaboration && (targetProp && ts.length(targetProp.declarations) || target.symbol && ts.length(target.symbol.declarations))) { + var targetNode = targetProp && ts.length(targetProp.declarations) ? targetProp.declarations[0] : target.symbol.declarations[0]; + if (!ts.getSourceFileOfNode(targetNode).hasNoDefaultLib) { + addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(targetNode, ts.Diagnostics.The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1, propertyName && !(nameType.flags & 8192 /* UniqueESSymbol */) ? ts.unescapeLeadingUnderscores(propertyName) : typeToString(nameType), typeToString(target))); + } + } + } + reportedError = true; + } + } + } + return reportedError; + } + function generateJsxAttributes(node) { + var _i, _a, prop; + return __generator(this, function (_b) { + switch (_b.label) { + case 0: + if (!ts.length(node.properties)) + return [2 /*return*/]; + _i = 0, _a = node.properties; + _b.label = 1; + case 1: + if (!(_i < _a.length)) return [3 /*break*/, 4]; + prop = _a[_i]; + if (ts.isJsxSpreadAttribute(prop)) + return [3 /*break*/, 3]; + return [4 /*yield*/, { errorNode: prop.name, innerExpression: prop.initializer, nameType: getLiteralType(ts.idText(prop.name)) }]; + case 2: + _b.sent(); + _b.label = 3; + case 3: + _i++; + return [3 /*break*/, 1]; + case 4: return [2 /*return*/]; + } + }); + } + function elaborateJsxAttributes(node, source, target, relation) { + return elaborateElementwise(generateJsxAttributes(node), source, target, relation); + } + function generateLimitedTupleElements(node, target) { + var len, i, elem, nameType; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + len = ts.length(node.elements); + if (!len) + return [2 /*return*/]; + i = 0; + _a.label = 1; + case 1: + if (!(i < len)) return [3 /*break*/, 4]; + // Skip elements which do not exist in the target - a length error on the tuple overall is likely better than an error on a mismatched index signature + if (isTupleLikeType(target) && !getPropertyOfType(target, ("" + i))) + return [3 /*break*/, 3]; + elem = node.elements[i]; + if (ts.isOmittedExpression(elem)) + return [3 /*break*/, 3]; + nameType = getLiteralType(i); + return [4 /*yield*/, { errorNode: elem, innerExpression: elem, nameType: nameType }]; + case 2: + _a.sent(); + _a.label = 3; + case 3: + i++; + return [3 /*break*/, 1]; + case 4: return [2 /*return*/]; + } + }); + } + function elaborateArrayLiteral(node, source, target, relation) { + if (isTupleLikeType(source)) { + return elaborateElementwise(generateLimitedTupleElements(node, target), source, target, relation); + } + // recreate a tuple from the elements, if possible + var tupleizedType = checkArrayLiteral(node, 3 /* Contextual */, /*forceTuple*/ true); + if (isTupleLikeType(tupleizedType)) { + return elaborateElementwise(generateLimitedTupleElements(node, target), tupleizedType, target, relation); + } + return false; + } + function generateObjectLiteralElements(node) { + var _i, _a, prop, type, _b; + return __generator(this, function (_c) { + switch (_c.label) { + case 0: + if (!ts.length(node.properties)) + return [2 /*return*/]; + _i = 0, _a = node.properties; + _c.label = 1; + case 1: + if (!(_i < _a.length)) return [3 /*break*/, 8]; + prop = _a[_i]; + if (ts.isSpreadAssignment(prop)) + return [3 /*break*/, 7]; + type = getLiteralTypeFromProperty(getSymbolOfNode(prop), 8576 /* StringOrNumberLiteralOrUnique */); + if (!type || (type.flags & 131072 /* Never */)) { + return [3 /*break*/, 7]; + } + _b = prop.kind; + switch (_b) { + case 159 /* SetAccessor */: return [3 /*break*/, 2]; + case 158 /* GetAccessor */: return [3 /*break*/, 2]; + case 156 /* MethodDeclaration */: return [3 /*break*/, 2]; + case 276 /* ShorthandPropertyAssignment */: return [3 /*break*/, 2]; + case 275 /* PropertyAssignment */: return [3 /*break*/, 4]; + } + return [3 /*break*/, 6]; + case 2: return [4 /*yield*/, { errorNode: prop.name, innerExpression: undefined, nameType: type }]; + case 3: + _c.sent(); + return [3 /*break*/, 7]; + case 4: return [4 /*yield*/, { errorNode: prop.name, innerExpression: prop.initializer, nameType: type, errorMessage: isComputedNonLiteralName(prop.name) ? ts.Diagnostics.Type_of_computed_property_s_value_is_0_which_is_not_assignable_to_type_1 : undefined }]; + case 5: + _c.sent(); + return [3 /*break*/, 7]; + case 6: + ts.Debug.assertNever(prop); + _c.label = 7; + case 7: + _i++; + return [3 /*break*/, 1]; + case 8: return [2 /*return*/]; + } + }); + } + function elaborateObjectLiteral(node, source, target, relation) { + return elaborateElementwise(generateObjectLiteralElements(node), source, target, relation); + } + /** + * This is *not* a bi-directional relationship. + * If one needs to check both directions for comparability, use a second call to this function or 'isTypeComparableTo'. + */ + function checkTypeComparableTo(source, target, errorNode, headMessage, containingMessageChain) { + return checkTypeRelatedTo(source, target, comparableRelation, errorNode, headMessage, containingMessageChain); + } + function isSignatureAssignableTo(source, target, ignoreReturnTypes) { + return compareSignaturesRelated(source, target, 0 /* None */, ignoreReturnTypes, /*reportErrors*/ false, + /*errorReporter*/ undefined, compareTypesAssignable) !== 0 /* False */; + } + /** + * See signatureRelatedTo, compareSignaturesIdentical + */ + function compareSignaturesRelated(source, target, callbackCheck, ignoreReturnTypes, reportErrors, errorReporter, compareTypes) { + // TODO (drosen): De-duplicate code between related functions. + if (source === target) { + return -1 /* True */; + } + var targetCount = getParameterCount(target); + if (!hasEffectiveRestParameter(target) && getMinArgumentCount(source) > targetCount) { + return 0 /* False */; + } + if (source.typeParameters && source.typeParameters !== target.typeParameters) { + target = getCanonicalSignature(target); + source = instantiateSignatureInContextOf(source, target, /*contextualMapper*/ undefined, compareTypes); + } + var sourceCount = getParameterCount(source); + var sourceRestType = getNonArrayRestType(source); + var targetRestType = getNonArrayRestType(target); + if (sourceRestType && targetRestType && sourceCount !== targetCount) { + // We're not able to relate misaligned complex rest parameters + return 0 /* False */; + } + var kind = target.declaration ? target.declaration.kind : 0 /* Unknown */; + var strictVariance = !callbackCheck && strictFunctionTypes && kind !== 156 /* MethodDeclaration */ && + kind !== 155 /* MethodSignature */ && kind !== 157 /* Constructor */; + var result = -1 /* True */; + var sourceThisType = getThisTypeOfSignature(source); + if (sourceThisType && sourceThisType !== voidType) { + var targetThisType = getThisTypeOfSignature(target); + if (targetThisType) { + // void sources are assignable to anything. + var related = !strictVariance && compareTypes(sourceThisType, targetThisType, /*reportErrors*/ false) + || compareTypes(targetThisType, sourceThisType, reportErrors); + if (!related) { + if (reportErrors) { + errorReporter(ts.Diagnostics.The_this_types_of_each_signature_are_incompatible); + } + return 0 /* False */; + } + result &= related; + } + } + var paramCount = sourceRestType || targetRestType ? Math.min(sourceCount, targetCount) : Math.max(sourceCount, targetCount); + var restIndex = sourceRestType || targetRestType ? paramCount - 1 : -1; + for (var i = 0; i < paramCount; i++) { + var sourceType = i === restIndex ? getRestTypeAtPosition(source, i) : getTypeAtPosition(source, i); + var targetType = i === restIndex ? getRestTypeAtPosition(target, i) : getTypeAtPosition(target, i); + // In order to ensure that any generic type Foo is at least co-variant with respect to T no matter + // how Foo uses T, we need to relate parameters bi-variantly (given that parameters are input positions, + // they naturally relate only contra-variantly). However, if the source and target parameters both have + // function types with a single call signature, we know we are relating two callback parameters. In + // that case it is sufficient to only relate the parameters of the signatures co-variantly because, + // similar to return values, callback parameters are output positions. This means that a Promise, + // where T is used only in callback parameter positions, will be co-variant (as opposed to bi-variant) + // with respect to T. + var sourceSig = callbackCheck ? undefined : getSingleCallSignature(getNonNullableType(sourceType)); + var targetSig = callbackCheck ? undefined : getSingleCallSignature(getNonNullableType(targetType)); + var callbacks = sourceSig && targetSig && !signatureHasTypePredicate(sourceSig) && !signatureHasTypePredicate(targetSig) && + (getFalsyFlags(sourceType) & 98304 /* Nullable */) === (getFalsyFlags(targetType) & 98304 /* Nullable */); + var related = callbacks ? + // TODO: GH#18217 It will work if they're both `undefined`, but not if only one is + compareSignaturesRelated(targetSig, sourceSig, strictVariance ? 2 /* Strict */ : 1 /* Bivariant */, /*ignoreReturnTypes*/ false, reportErrors, errorReporter, compareTypes) : + !callbackCheck && !strictVariance && compareTypes(sourceType, targetType, /*reportErrors*/ false) || compareTypes(targetType, sourceType, reportErrors); + if (!related) { + if (reportErrors) { + errorReporter(ts.Diagnostics.Types_of_parameters_0_and_1_are_incompatible, ts.unescapeLeadingUnderscores(getParameterNameAtPosition(source, i)), ts.unescapeLeadingUnderscores(getParameterNameAtPosition(target, i))); + } + return 0 /* False */; + } + result &= related; + } + if (!ignoreReturnTypes) { + var targetReturnType = (target.declaration && isJSConstructor(target.declaration)) ? + getJSClassType(target.declaration.symbol) : getReturnTypeOfSignature(target); + if (targetReturnType === voidType) { + return result; + } + var sourceReturnType = (source.declaration && isJSConstructor(source.declaration)) ? + getJSClassType(source.declaration.symbol) : getReturnTypeOfSignature(source); + // The following block preserves behavior forbidding boolean returning functions from being assignable to type guard returning functions + var targetTypePredicate = getTypePredicateOfSignature(target); + if (targetTypePredicate) { + var sourceTypePredicate = getTypePredicateOfSignature(source); + if (sourceTypePredicate) { + result &= compareTypePredicateRelatedTo(sourceTypePredicate, targetTypePredicate, source.declaration, target.declaration, reportErrors, errorReporter, compareTypes); // TODO: GH#18217 + } + else if (ts.isIdentifierTypePredicate(targetTypePredicate)) { + if (reportErrors) { + errorReporter(ts.Diagnostics.Signature_0_must_be_a_type_predicate, signatureToString(source)); + } + return 0 /* False */; + } + } + else { + // When relating callback signatures, we still need to relate return types bi-variantly as otherwise + // the containing type wouldn't be co-variant. For example, interface Foo { add(cb: () => T): void } + // wouldn't be co-variant for T without this rule. + result &= callbackCheck === 1 /* Bivariant */ && compareTypes(targetReturnType, sourceReturnType, /*reportErrors*/ false) || + compareTypes(sourceReturnType, targetReturnType, reportErrors); + } + } + return result; + } + function compareTypePredicateRelatedTo(source, target, sourceDeclaration, targetDeclaration, reportErrors, errorReporter, compareTypes) { + if (source.kind !== target.kind) { + if (reportErrors) { + errorReporter(ts.Diagnostics.A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard); + errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target)); + } + return 0 /* False */; + } + if (source.kind === 1 /* Identifier */) { + var targetPredicate = target; + var sourceIndex = source.parameterIndex - (ts.getThisParameter(sourceDeclaration) ? 1 : 0); + var targetIndex = targetPredicate.parameterIndex - (ts.getThisParameter(targetDeclaration) ? 1 : 0); + if (sourceIndex !== targetIndex) { + if (reportErrors) { + errorReporter(ts.Diagnostics.Parameter_0_is_not_in_the_same_position_as_parameter_1, source.parameterName, targetPredicate.parameterName); + errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target)); + } + return 0 /* False */; + } + } + var related = compareTypes(source.type, target.type, reportErrors); + if (related === 0 /* False */ && reportErrors) { + errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target)); + } + return related; + } + function isImplementationCompatibleWithOverload(implementation, overload) { + var erasedSource = getErasedSignature(implementation); + var erasedTarget = getErasedSignature(overload); + // First see if the return types are compatible in either direction. + var sourceReturnType = getReturnTypeOfSignature(erasedSource); + var targetReturnType = getReturnTypeOfSignature(erasedTarget); + if (targetReturnType === voidType + || isTypeRelatedTo(targetReturnType, sourceReturnType, assignableRelation) + || isTypeRelatedTo(sourceReturnType, targetReturnType, assignableRelation)) { + return isSignatureAssignableTo(erasedSource, erasedTarget, /*ignoreReturnTypes*/ true); + } + return false; + } + function isEmptyResolvedType(t) { + return t.properties.length === 0 && + t.callSignatures.length === 0 && + t.constructSignatures.length === 0 && + !t.stringIndexInfo && + !t.numberIndexInfo; + } + function isEmptyObjectType(type) { + return type.flags & 524288 /* Object */ ? isEmptyResolvedType(resolveStructuredTypeMembers(type)) : + type.flags & 67108864 /* NonPrimitive */ ? true : + type.flags & 1048576 /* Union */ ? ts.some(type.types, isEmptyObjectType) : + type.flags & 2097152 /* Intersection */ ? ts.every(type.types, isEmptyObjectType) : + false; + } + function isEmptyAnonymousObjectType(type) { + return !!(ts.getObjectFlags(type) & 16 /* Anonymous */) && isEmptyObjectType(type); + } + function isEnumTypeRelatedTo(sourceSymbol, targetSymbol, errorReporter) { + if (sourceSymbol === targetSymbol) { + return true; + } + var id = getSymbolId(sourceSymbol) + "," + getSymbolId(targetSymbol); + var relation = enumRelation.get(id); + if (relation !== undefined && !(relation === 2 /* Failed */ && errorReporter)) { + return relation === 1 /* Succeeded */; + } + if (sourceSymbol.escapedName !== targetSymbol.escapedName || !(sourceSymbol.flags & 256 /* RegularEnum */) || !(targetSymbol.flags & 256 /* RegularEnum */)) { + enumRelation.set(id, 3 /* FailedAndReported */); + return false; + } + var targetEnumType = getTypeOfSymbol(targetSymbol); + for (var _i = 0, _a = getPropertiesOfType(getTypeOfSymbol(sourceSymbol)); _i < _a.length; _i++) { + var property = _a[_i]; + if (property.flags & 8 /* EnumMember */) { + var targetProperty = getPropertyOfType(targetEnumType, property.escapedName); + if (!targetProperty || !(targetProperty.flags & 8 /* EnumMember */)) { + if (errorReporter) { + errorReporter(ts.Diagnostics.Property_0_is_missing_in_type_1, ts.symbolName(property), typeToString(getDeclaredTypeOfSymbol(targetSymbol), /*enclosingDeclaration*/ undefined, 64 /* UseFullyQualifiedType */)); + enumRelation.set(id, 3 /* FailedAndReported */); + } + else { + enumRelation.set(id, 2 /* Failed */); + } + return false; + } + } + } + enumRelation.set(id, 1 /* Succeeded */); + return true; + } + function isSimpleTypeRelatedTo(source, target, relation, errorReporter) { + var s = source.flags; + var t = target.flags; + if (t & 3 /* AnyOrUnknown */ || s & 131072 /* Never */ || source === wildcardType) + return true; + if (t & 131072 /* Never */) + return false; + if (s & 132 /* StringLike */ && t & 4 /* String */) + return true; + if (s & 128 /* StringLiteral */ && s & 1024 /* EnumLiteral */ && + t & 128 /* StringLiteral */ && !(t & 1024 /* EnumLiteral */) && + source.value === target.value) + return true; + if (s & 296 /* NumberLike */ && t & 8 /* Number */) + return true; + if (s & 256 /* NumberLiteral */ && s & 1024 /* EnumLiteral */ && + t & 256 /* NumberLiteral */ && !(t & 1024 /* EnumLiteral */) && + source.value === target.value) + return true; + if (s & 2112 /* BigIntLike */ && t & 64 /* BigInt */) + return true; + if (s & 528 /* BooleanLike */ && t & 16 /* Boolean */) + return true; + if (s & 12288 /* ESSymbolLike */ && t & 4096 /* ESSymbol */) + return true; + if (s & 32 /* Enum */ && t & 32 /* Enum */ && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) + return true; + if (s & 1024 /* EnumLiteral */ && t & 1024 /* EnumLiteral */) { + if (s & 1048576 /* Union */ && t & 1048576 /* Union */ && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) + return true; + if (s & 2944 /* Literal */ && t & 2944 /* Literal */ && + source.value === target.value && + isEnumTypeRelatedTo(getParentOfSymbol(source.symbol), getParentOfSymbol(target.symbol), errorReporter)) + return true; + } + if (s & 32768 /* Undefined */ && (!strictNullChecks || t & (32768 /* Undefined */ | 16384 /* Void */))) + return true; + if (s & 65536 /* Null */ && (!strictNullChecks || t & 65536 /* Null */)) + return true; + if (s & 524288 /* Object */ && t & 67108864 /* NonPrimitive */) + return true; + if (s & 8192 /* UniqueESSymbol */ || t & 8192 /* UniqueESSymbol */) + return false; + if (relation === assignableRelation || relation === definitelyAssignableRelation || relation === comparableRelation) { + if (s & 1 /* Any */) + return true; + // Type number or any numeric literal type is assignable to any numeric enum type or any + // numeric enum literal type. This rule exists for backwards compatibility reasons because + // bit-flag enum types sometimes look like literal enum types with numeric literal values. + if (s & (8 /* Number */ | 256 /* NumberLiteral */) && !(s & 1024 /* EnumLiteral */) && (t & 32 /* Enum */ || t & 256 /* NumberLiteral */ && t & 1024 /* EnumLiteral */)) + return true; + } + return false; + } + function isTypeRelatedTo(source, target, relation) { + if (isFreshLiteralType(source)) { + source = source.regularType; + } + if (isFreshLiteralType(target)) { + target = target.regularType; + } + if (source === target || + relation === comparableRelation && !(target.flags & 131072 /* Never */) && isSimpleTypeRelatedTo(target, source, relation) || + relation !== identityRelation && isSimpleTypeRelatedTo(source, target, relation)) { + return true; + } + if (source.flags & 524288 /* Object */ && target.flags & 524288 /* Object */) { + var related = relation.get(getRelationKey(source, target, relation)); + if (related !== undefined) { + return related === 1 /* Succeeded */; + } + } + if (source.flags & 66846720 /* StructuredOrInstantiable */ || target.flags & 66846720 /* StructuredOrInstantiable */) { + return checkTypeRelatedTo(source, target, relation, /*errorNode*/ undefined); + } + return false; + } + function isIgnoredJsxProperty(source, sourceProp, targetMemberType) { + return ts.getObjectFlags(source) & 4096 /* JsxAttributes */ && !(isUnhyphenatedJsxName(sourceProp.escapedName) || targetMemberType); + } + /** + * Checks if 'source' is related to 'target' (e.g.: is a assignable to). + * @param source The left-hand-side of the relation. + * @param target The right-hand-side of the relation. + * @param relation The relation considered. One of 'identityRelation', 'subtypeRelation', 'assignableRelation', or 'comparableRelation'. + * Used as both to determine which checks are performed and as a cache of previously computed results. + * @param errorNode The suggested node upon which all errors will be reported, if defined. This may or may not be the actual node used. + * @param headMessage If the error chain should be prepended by a head message, then headMessage will be used. + * @param containingMessageChain A chain of errors to prepend any new errors found. + */ + function checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain, errorOutputContainer) { + var errorInfo; + var relatedInfo; + var maybeKeys; + var sourceStack; + var targetStack; + var maybeCount = 0; + var depth = 0; + var expandingFlags = 0 /* None */; + var overflow = false; + var suppressNextError = false; + ts.Debug.assert(relation !== identityRelation || !errorNode, "no error reporting in identity checking"); + var result = isRelatedTo(source, target, /*reportErrors*/ !!errorNode, headMessage); + if (overflow) { + error(errorNode, ts.Diagnostics.Excessive_stack_depth_comparing_types_0_and_1, typeToString(source), typeToString(target)); + } + else if (errorInfo) { + if (containingMessageChain) { + var chain_1 = containingMessageChain(); + if (chain_1) { + errorInfo = ts.concatenateDiagnosticMessageChains(chain_1, errorInfo); + } + } + var relatedInformation = void 0; + // Check if we should issue an extra diagnostic to produce a quickfix for a slightly incorrect import statement + if (headMessage && errorNode && !result && source.symbol) { + var links = getSymbolLinks(source.symbol); + if (links.originatingImport && !ts.isImportCall(links.originatingImport)) { + var helpfulRetry = checkTypeRelatedTo(getTypeOfSymbol(links.target), target, relation, /*errorNode*/ undefined); + if (helpfulRetry) { + // Likely an incorrect import. Issue a helpful diagnostic to produce a quickfix to change the import + var diag_1 = ts.createDiagnosticForNode(links.originatingImport, ts.Diagnostics.Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_Consider_using_a_default_import_or_import_require_here_instead); + relatedInformation = ts.append(relatedInformation, diag_1); // Cause the error to appear with the error that triggered it + } + } + } + var diag = ts.createDiagnosticForNodeFromMessageChain(errorNode, errorInfo, relatedInformation); + if (relatedInfo) { + addRelatedInfo.apply(void 0, [diag].concat(relatedInfo)); + } + if (errorOutputContainer) { + errorOutputContainer.error = diag; + } + diagnostics.add(diag); // TODO: GH#18217 + } + return result !== 0 /* False */; + function reportError(message, arg0, arg1, arg2, arg3) { + ts.Debug.assert(!!errorNode); + errorInfo = ts.chainDiagnosticMessages(errorInfo, message, arg0, arg1, arg2, arg3); + } + function associateRelatedInfo(info) { + ts.Debug.assert(!!errorInfo); + if (!relatedInfo) { + relatedInfo = [info]; + } + else { + relatedInfo.push(info); + } + } + function reportRelationError(message, source, target) { + var sourceType = typeToString(source); + var targetType = typeToString(target); + if (sourceType === targetType) { + sourceType = typeToString(source, /*enclosingDeclaration*/ undefined, 64 /* UseFullyQualifiedType */); + targetType = typeToString(target, /*enclosingDeclaration*/ undefined, 64 /* UseFullyQualifiedType */); + } + if (!message) { + if (relation === comparableRelation) { + message = ts.Diagnostics.Type_0_is_not_comparable_to_type_1; + } + else if (sourceType === targetType) { + message = ts.Diagnostics.Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated; + } + else { + message = ts.Diagnostics.Type_0_is_not_assignable_to_type_1; + } + } + reportError(message, sourceType, targetType); + } + function tryElaborateErrorsForPrimitivesAndObjects(source, target) { + var sourceType = typeToString(source); + var targetType = typeToString(target); + if ((globalStringType === source && stringType === target) || + (globalNumberType === source && numberType === target) || + (globalBooleanType === source && booleanType === target) || + (getGlobalESSymbolType(/*reportErrors*/ false) === source && esSymbolType === target)) { + reportError(ts.Diagnostics._0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible, targetType, sourceType); + } + } + function isUnionOrIntersectionTypeWithoutNullableConstituents(type) { + if (!(type.flags & 3145728 /* UnionOrIntersection */)) { + return false; + } + // at this point we know that this is union or intersection type possibly with nullable constituents. + // check if we still will have compound type if we ignore nullable components. + var seenNonNullable = false; + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (t.flags & 98304 /* Nullable */) { + continue; + } + if (seenNonNullable) { + return true; + } + seenNonNullable = true; + } + return false; + } + /** + * Compare two types and return + * * Ternary.True if they are related with no assumptions, + * * Ternary.Maybe if they are related with assumptions of other relationships, or + * * Ternary.False if they are not related. + */ + function isRelatedTo(source, target, reportErrors, headMessage, isApparentIntersectionConstituent) { + if (reportErrors === void 0) { reportErrors = false; } + if (isFreshLiteralType(source)) { + source = source.regularType; + } + if (isFreshLiteralType(target)) { + target = target.regularType; + } + if (source.flags & 33554432 /* Substitution */) { + source = relation === definitelyAssignableRelation ? source.typeVariable : source.substitute; + } + if (target.flags & 33554432 /* Substitution */) { + target = target.typeVariable; + } + if (source.flags & 8388608 /* IndexedAccess */) { + source = getSimplifiedType(source); + } + if (target.flags & 8388608 /* IndexedAccess */) { + target = getSimplifiedType(target); + } + // Try to see if we're relating something like `Foo` -> `Bar | null | undefined`. + // If so, reporting the `null` and `undefined` in the type is hardly useful. + // First, see if we're even relating an object type to a union. + // Then see if the target is stripped down to a single non-union type. + // Note + // * We actually want to remove null and undefined naively here (rather than using getNonNullableType), + // since we don't want to end up with a worse error like "`Foo` is not assignable to `NonNullable`" + // when dealing with generics. + // * We also don't deal with primitive source types, since we already halt elaboration below. + if (target.flags & 1048576 /* Union */ && source.flags & 524288 /* Object */ && + target.types.length <= 3 && maybeTypeOfKind(target, 98304 /* Nullable */)) { + var nullStrippedTarget = extractTypesOfKind(target, ~98304 /* Nullable */); + if (!(nullStrippedTarget.flags & (1048576 /* Union */ | 131072 /* Never */))) { + target = nullStrippedTarget; + } + } + // both types are the same - covers 'they are the same primitive type or both are Any' or the same type parameter cases + if (source === target) + return -1 /* True */; + if (relation === identityRelation) { + return isIdenticalTo(source, target); + } + if (relation === comparableRelation && !(target.flags & 131072 /* Never */) && isSimpleTypeRelatedTo(target, source, relation) || + isSimpleTypeRelatedTo(source, target, relation, reportErrors ? reportError : undefined)) + return -1 /* True */; + var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096 /* JsxAttributes */); + if (isObjectLiteralType(source) && ts.getObjectFlags(source) & 32768 /* FreshLiteral */) { + var discriminantType = target.flags & 1048576 /* Union */ ? findMatchingDiscriminantType(source, target) : undefined; + if (hasExcessProperties(source, target, discriminantType, reportErrors)) { + if (reportErrors) { + reportRelationError(headMessage, source, target); + } + return 0 /* False */; + } + // Above we check for excess properties with respect to the entire target type. When union + // and intersection types are further deconstructed on the target side, we don't want to + // make the check again (as it might fail for a partial target type). Therefore we obtain + // the regular source type and proceed with that. + if (isUnionOrIntersectionTypeWithoutNullableConstituents(target) && !discriminantType) { + source = getRegularTypeOfObjectLiteral(source); + } + } + if (relation !== comparableRelation && !isApparentIntersectionConstituent && + source.flags & (131068 /* Primitive */ | 524288 /* Object */ | 2097152 /* Intersection */) && source !== globalObjectType && + target.flags & (524288 /* Object */ | 2097152 /* Intersection */) && isWeakType(target) && + (getPropertiesOfType(source).length > 0 || typeHasCallOrConstructSignatures(source)) && + !hasCommonProperties(source, target, isComparingJsxAttributes)) { + if (reportErrors) { + var calls = getSignaturesOfType(source, 0 /* Call */); + var constructs = getSignaturesOfType(source, 1 /* Construct */); + if (calls.length > 0 && isRelatedTo(getReturnTypeOfSignature(calls[0]), target, /*reportErrors*/ false) || + constructs.length > 0 && isRelatedTo(getReturnTypeOfSignature(constructs[0]), target, /*reportErrors*/ false)) { + reportError(ts.Diagnostics.Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it, typeToString(source), typeToString(target)); + } + else { + reportError(ts.Diagnostics.Type_0_has_no_properties_in_common_with_type_1, typeToString(source), typeToString(target)); + } + } + return 0 /* False */; + } + var result = 0 /* False */; + var saveErrorInfo = errorInfo; + var isIntersectionConstituent = !!isApparentIntersectionConstituent; + // Note that these checks are specifically ordered to produce correct results. In particular, + // we need to deconstruct unions before intersections (because unions are always at the top), + // and we need to handle "each" relations before "some" relations for the same kind of type. + if (source.flags & 1048576 /* Union */) { + result = relation === comparableRelation ? + someTypeRelatedToType(source, target, reportErrors && !(source.flags & 131068 /* Primitive */)) : + eachTypeRelatedToType(source, target, reportErrors && !(source.flags & 131068 /* Primitive */)); + } + else { + if (target.flags & 1048576 /* Union */) { + result = typeRelatedToSomeType(source, target, reportErrors && !(source.flags & 131068 /* Primitive */) && !(target.flags & 131068 /* Primitive */)); + } + else if (target.flags & 2097152 /* Intersection */) { + isIntersectionConstituent = true; // set here to affect the following trio of checks + result = typeRelatedToEachType(source, target, reportErrors); + } + else if (source.flags & 2097152 /* Intersection */) { + // Check to see if any constituents of the intersection are immediately related to the target. + // + // Don't report errors though. Checking whether a constituent is related to the source is not actually + // useful and leads to some confusing error messages. Instead it is better to let the below checks + // take care of this, or to not elaborate at all. For instance, + // + // - For an object type (such as 'C = A & B'), users are usually more interested in structural errors. + // + // - For a union type (such as '(A | B) = (C & D)'), it's better to hold onto the whole intersection + // than to report that 'D' is not assignable to 'A' or 'B'. + // + // - For a primitive type or type parameter (such as 'number = A & B') there is no point in + // breaking the intersection apart. + result = someTypeRelatedToType(source, target, /*reportErrors*/ false); + } + if (!result && (source.flags & 66846720 /* StructuredOrInstantiable */ || target.flags & 66846720 /* StructuredOrInstantiable */)) { + if (result = recursiveTypeRelatedTo(source, target, reportErrors, isIntersectionConstituent)) { + errorInfo = saveErrorInfo; + } + } + } + if (!result && source.flags & 2097152 /* Intersection */) { + // The combined constraint of an intersection type is the intersection of the constraints of + // the constituents. When an intersection type contains instantiable types with union type + // constraints, there are situations where we need to examine the combined constraint. One is + // when the target is a union type. Another is when the intersection contains types belonging + // to one of the disjoint domains. For example, given type variables T and U, each with the + // constraint 'string | number', the combined constraint of 'T & U' is 'string | number' and + // we need to check this constraint against a union on the target side. Also, given a type + // variable V constrained to 'string | number', 'V & number' has a combined constraint of + // 'string & number | number & number' which reduces to just 'number'. + var constraint = getUnionConstraintOfIntersection(source, !!(target.flags & 1048576 /* Union */)); + if (constraint) { + if (result = isRelatedTo(constraint, target, reportErrors, /*headMessage*/ undefined, isIntersectionConstituent)) { + errorInfo = saveErrorInfo; + } + } + } + if (!result && reportErrors) { + var maybeSuppress = suppressNextError; + suppressNextError = false; + if (source.flags & 524288 /* Object */ && target.flags & 131068 /* Primitive */) { + tryElaborateErrorsForPrimitivesAndObjects(source, target); + } + else if (source.symbol && source.flags & 524288 /* Object */ && globalObjectType === source) { + reportError(ts.Diagnostics.The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead); + } + else if (isComparingJsxAttributes && target.flags & 2097152 /* Intersection */) { + var targetTypes = target.types; + var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes, errorNode); + var intrinsicClassAttributes = getJsxType(JsxNames.IntrinsicClassAttributes, errorNode); + if (intrinsicAttributes !== errorType && intrinsicClassAttributes !== errorType && + (ts.contains(targetTypes, intrinsicAttributes) || ts.contains(targetTypes, intrinsicClassAttributes))) { + // do not report top error + return result; + } + } + if (!headMessage && maybeSuppress) { + // Used by, eg, missing property checking to replace the top-level message with a more informative one + return result; + } + reportRelationError(headMessage, source, target); + } + return result; + } + function isIdenticalTo(source, target) { + var result; + var flags = source.flags & target.flags; + if (flags & 524288 /* Object */ || flags & 8388608 /* IndexedAccess */ || flags & 16777216 /* Conditional */ || flags & 4194304 /* Index */ || flags & 33554432 /* Substitution */) { + return recursiveTypeRelatedTo(source, target, /*reportErrors*/ false, /*isIntersectionConstituent*/ false); + } + if (flags & (1048576 /* Union */ | 2097152 /* Intersection */)) { + if (result = eachTypeRelatedToSomeType(source, target)) { + if (result &= eachTypeRelatedToSomeType(target, source)) { + return result; + } + } + } + return 0 /* False */; + } + function hasExcessProperties(source, target, discriminant, reportErrors) { + if (!noImplicitAny && ts.getObjectFlags(target) & 16384 /* JSLiteral */) { + return false; // Disable excess property checks on JS literals to simulate having an implicit "index signature" - but only outside of noImplicitAny + } + if (maybeTypeOfKind(target, 524288 /* Object */) && !(ts.getObjectFlags(target) & 512 /* ObjectLiteralPatternWithComputedProperties */)) { + var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096 /* JsxAttributes */); + if ((relation === assignableRelation || relation === definitelyAssignableRelation || relation === comparableRelation) && + (isTypeSubsetOf(globalObjectType, target) || (!isComparingJsxAttributes && isEmptyObjectType(target)))) { + return false; + } + if (discriminant) { + // check excess properties against discriminant type only, not the entire union + return hasExcessProperties(source, discriminant, /*discriminant*/ undefined, reportErrors); + } + var _loop_6 = function (prop) { + if (shouldCheckAsExcessProperty(prop, source.symbol) && !isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { + if (reportErrors) { + // We know *exactly* where things went wrong when comparing the types. + // Use this property as the error node as this will be more helpful in + // reasoning about what went wrong. + if (!errorNode) + return { value: ts.Debug.fail() }; + if (ts.isJsxAttributes(errorNode) || ts.isJsxOpeningLikeElement(errorNode) || ts.isJsxOpeningLikeElement(errorNode.parent)) { + // JsxAttributes has an object-literal flag and undergo same type-assignablity check as normal object-literal. + // However, using an object-literal error message will be very confusing to the users so we give different a message. + // TODO: Spelling suggestions for excess jsx attributes (needs new diagnostic messages) + reportError(ts.Diagnostics.Property_0_does_not_exist_on_type_1, symbolToString(prop), typeToString(target)); + } + else { + // use the property's value declaration if the property is assigned inside the literal itself + var objectLiteralDeclaration_1 = source.symbol && ts.firstOrUndefined(source.symbol.declarations); + var suggestion = void 0; + if (prop.valueDeclaration && ts.findAncestor(prop.valueDeclaration, function (d) { return d === objectLiteralDeclaration_1; })) { + var propDeclaration = prop.valueDeclaration; + ts.Debug.assertNode(propDeclaration, ts.isObjectLiteralElementLike); + errorNode = propDeclaration; + var name = propDeclaration.name; + if (ts.isIdentifier(name)) { + suggestion = getSuggestionForNonexistentProperty(name, target); + } + } + if (suggestion !== undefined) { + reportError(ts.Diagnostics.Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_write_2, symbolToString(prop), typeToString(target), suggestion); + } + else { + reportError(ts.Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(prop), typeToString(target)); + } + } + } + return { value: true }; + } + }; + for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) { + var prop = _a[_i]; + var state_2 = _loop_6(prop); + if (typeof state_2 === "object") + return state_2.value; + } + } + return false; + } + function shouldCheckAsExcessProperty(prop, container) { + return prop.valueDeclaration && container.valueDeclaration && prop.valueDeclaration.parent === container.valueDeclaration; + } + function eachTypeRelatedToSomeType(source, target) { + var result = -1 /* True */; + var sourceTypes = source.types; + for (var _i = 0, sourceTypes_1 = sourceTypes; _i < sourceTypes_1.length; _i++) { + var sourceType = sourceTypes_1[_i]; + var related = typeRelatedToSomeType(sourceType, target, /*reportErrors*/ false); + if (!related) { + return 0 /* False */; + } + result &= related; + } + return result; + } + function typeRelatedToSomeType(source, target, reportErrors) { + var targetTypes = target.types; + if (target.flags & 1048576 /* Union */ && containsType(targetTypes, source)) { + return -1 /* True */; + } + for (var _i = 0, targetTypes_1 = targetTypes; _i < targetTypes_1.length; _i++) { + var type = targetTypes_1[_i]; + var related = isRelatedTo(source, type, /*reportErrors*/ false); + if (related) { + return related; + } + } + if (reportErrors) { + var bestMatchingType = findMatchingDiscriminantType(source, target) || + findMatchingTypeReferenceOrTypeAliasReference(source, target) || + findBestTypeForObjectLiteral(source, target) || + findBestTypeForInvokable(source, target) || + findMostOverlappyType(source, target); + isRelatedTo(source, bestMatchingType || targetTypes[targetTypes.length - 1], /*reportErrors*/ true); + } + return 0 /* False */; + } + function findMatchingTypeReferenceOrTypeAliasReference(source, unionTarget) { + var sourceObjectFlags = ts.getObjectFlags(source); + if (sourceObjectFlags & (4 /* Reference */ | 16 /* Anonymous */) && unionTarget.flags & 1048576 /* Union */) { + return ts.find(unionTarget.types, function (target) { + if (target.flags & 524288 /* Object */) { + var overlapObjFlags = sourceObjectFlags & ts.getObjectFlags(target); + if (overlapObjFlags & 4 /* Reference */) { + return source.target === target.target; + } + if (overlapObjFlags & 16 /* Anonymous */) { + return !!source.aliasSymbol && source.aliasSymbol === target.aliasSymbol; + } + } + return false; + }); + } + } + function findBestTypeForObjectLiteral(source, unionTarget) { + if (ts.getObjectFlags(source) & 128 /* ObjectLiteral */ && forEachType(unionTarget, isArrayLikeType)) { + return ts.find(unionTarget.types, function (t) { return !isArrayLikeType(t); }); + } + } + function findBestTypeForInvokable(source, unionTarget) { + var signatureKind = 0 /* Call */; + var hasSignatures = getSignaturesOfType(source, signatureKind).length > 0 || + (signatureKind = 1 /* Construct */, getSignaturesOfType(source, signatureKind).length > 0); + if (hasSignatures) { + return ts.find(unionTarget.types, function (t) { return getSignaturesOfType(t, signatureKind).length > 0; }); + } + } + function findMostOverlappyType(source, unionTarget) { + var bestMatch; + var matchingCount = 0; + for (var _i = 0, _a = unionTarget.types; _i < _a.length; _i++) { + var target_1 = _a[_i]; + var overlap = getIntersectionType([getIndexType(source), getIndexType(target_1)]); + if (overlap.flags & 4194304 /* Index */) { + // perfect overlap of keys + bestMatch = target_1; + matchingCount = Infinity; + } + else if (overlap.flags & 1048576 /* Union */) { + // Some subset overlap if we have only string literals. + // If we have a union of index types, it seems likely that we + // needed to elaborate between two generic mapped types anyway. + var len = ts.length(overlap.types); + if (len >= matchingCount) { + bestMatch = target_1; + matchingCount = len; + } + } + else if (!(overlap.flags & 131072 /* Never */) && 1 >= matchingCount) { + bestMatch = target_1; + matchingCount = 1; + } + } + return bestMatch; + } + // Keep this up-to-date with the same logic within `getApparentTypeOfContextualType`, since they should behave similarly + function findMatchingDiscriminantType(source, target) { + if (target.flags & 1048576 /* Union */) { + var sourceProperties = getPropertiesOfObjectType(source); + if (sourceProperties) { + var sourcePropertiesFiltered = findDiscriminantProperties(sourceProperties, target); + if (sourcePropertiesFiltered) { + return discriminateTypeByDiscriminableItems(target, ts.map(sourcePropertiesFiltered, function (p) { return [function () { return getTypeOfSymbol(p); }, p.escapedName]; }), isRelatedTo); + } + } + } + return undefined; + } + function typeRelatedToEachType(source, target, reportErrors) { + var result = -1 /* True */; + var targetTypes = target.types; + for (var _i = 0, targetTypes_2 = targetTypes; _i < targetTypes_2.length; _i++) { + var targetType = targetTypes_2[_i]; + var related = isRelatedTo(source, targetType, reportErrors, /*headMessage*/ undefined, /*isIntersectionConstituent*/ true); + if (!related) { + return 0 /* False */; + } + result &= related; + } + return result; + } + function someTypeRelatedToType(source, target, reportErrors) { + var sourceTypes = source.types; + if (source.flags & 1048576 /* Union */ && containsType(sourceTypes, target)) { + return -1 /* True */; + } + var len = sourceTypes.length; + for (var i = 0; i < len; i++) { + var related = isRelatedTo(sourceTypes[i], target, reportErrors && i === len - 1); + if (related) { + return related; + } + } + return 0 /* False */; + } + function eachTypeRelatedToType(source, target, reportErrors) { + var result = -1 /* True */; + var sourceTypes = source.types; + for (var _i = 0, sourceTypes_2 = sourceTypes; _i < sourceTypes_2.length; _i++) { + var sourceType = sourceTypes_2[_i]; + var related = isRelatedTo(sourceType, target, reportErrors); + if (!related) { + return 0 /* False */; + } + result &= related; + } + return result; + } + function typeArgumentsRelatedTo(sources, targets, variances, reportErrors) { + if (sources === void 0) { sources = ts.emptyArray; } + if (targets === void 0) { targets = ts.emptyArray; } + if (variances === void 0) { variances = ts.emptyArray; } + if (sources.length !== targets.length && relation === identityRelation) { + return 0 /* False */; + } + var length = sources.length <= targets.length ? sources.length : targets.length; + var result = -1 /* True */; + for (var i = 0; i < length; i++) { + // When variance information isn't available we default to covariance. This happens + // in the process of computing variance information for recursive types and when + // comparing 'this' type arguments. + var variance = i < variances.length ? variances[i] : 1 /* Covariant */; + // We ignore arguments for independent type parameters (because they're never witnessed). + if (variance !== 4 /* Independent */) { + var s = sources[i]; + var t = targets[i]; + var related = -1 /* True */; + if (variance === 1 /* Covariant */) { + related = isRelatedTo(s, t, reportErrors); + } + else if (variance === 2 /* Contravariant */) { + related = isRelatedTo(t, s, reportErrors); + } + else if (variance === 3 /* Bivariant */) { + // In the bivariant case we first compare contravariantly without reporting + // errors. Then, if that doesn't succeed, we compare covariantly with error + // reporting. Thus, error elaboration will be based on the the covariant check, + // which is generally easier to reason about. + related = isRelatedTo(t, s, /*reportErrors*/ false); + if (!related) { + related = isRelatedTo(s, t, reportErrors); + } + } + else { + // In the invariant case we first compare covariantly, and only when that + // succeeds do we proceed to compare contravariantly. Thus, error elaboration + // will typically be based on the covariant check. + related = isRelatedTo(s, t, reportErrors); + if (related) { + related &= isRelatedTo(t, s, reportErrors); + } + } + if (!related) { + return 0 /* False */; + } + result &= related; + } + } + return result; + } + // Determine if possibly recursive types are related. First, check if the result is already available in the global cache. + // Second, check if we have already started a comparison of the given two types in which case we assume the result to be true. + // Third, check if both types are part of deeply nested chains of generic type instantiations and if so assume the types are + // equal and infinitely expanding. Fourth, if we have reached a depth of 100 nested comparisons, assume we have runaway recursion + // and issue an error. Otherwise, actually compare the structure of the two types. + function recursiveTypeRelatedTo(source, target, reportErrors, isIntersectionConstituent) { + if (overflow) { + return 0 /* False */; + } + var id = getRelationKey(source, target, relation); + var related = relation.get(id); + if (related !== undefined) { + if (reportErrors && related === 2 /* Failed */) { + // We are elaborating errors and the cached result is an unreported failure. The result will be reported + // as a failure, and should be updated as a reported failure by the bottom of this function. + } + else { + return related === 1 /* Succeeded */ ? -1 /* True */ : 0 /* False */; + } + } + if (!maybeKeys) { + maybeKeys = []; + sourceStack = []; + targetStack = []; + } + else { + for (var i = 0; i < maybeCount; i++) { + // If source and target are already being compared, consider them related with assumptions + if (id === maybeKeys[i]) { + return 1 /* Maybe */; + } + } + if (depth === 100) { + overflow = true; + return 0 /* False */; + } + } + var maybeStart = maybeCount; + maybeKeys[maybeCount] = id; + maybeCount++; + sourceStack[depth] = source; + targetStack[depth] = target; + depth++; + var saveExpandingFlags = expandingFlags; + if (!(expandingFlags & 1 /* Source */) && isDeeplyNestedType(source, sourceStack, depth)) + expandingFlags |= 1 /* Source */; + if (!(expandingFlags & 2 /* Target */) && isDeeplyNestedType(target, targetStack, depth)) + expandingFlags |= 2 /* Target */; + var result = expandingFlags !== 3 /* Both */ ? structuredTypeRelatedTo(source, target, reportErrors, isIntersectionConstituent) : 1 /* Maybe */; + expandingFlags = saveExpandingFlags; + depth--; + if (result) { + if (result === -1 /* True */ || depth === 0) { + // If result is definitely true, record all maybe keys as having succeeded + for (var i = maybeStart; i < maybeCount; i++) { + relation.set(maybeKeys[i], 1 /* Succeeded */); + } + maybeCount = maybeStart; + } + } + else { + // A false result goes straight into global cache (when something is false under + // assumptions it will also be false without assumptions) + relation.set(id, reportErrors ? 3 /* FailedAndReported */ : 2 /* Failed */); + maybeCount = maybeStart; + } + return result; + } + function getConstraintForRelation(type) { + return relation === definitelyAssignableRelation ? undefined : getConstraintOfType(type); + } + function structuredTypeRelatedTo(source, target, reportErrors, isIntersectionConstituent) { + var flags = source.flags & target.flags; + if (relation === identityRelation && !(flags & 524288 /* Object */)) { + if (flags & 4194304 /* Index */) { + return isRelatedTo(source.type, target.type, /*reportErrors*/ false); + } + var result_2 = 0 /* False */; + if (flags & 8388608 /* IndexedAccess */) { + if (result_2 = isRelatedTo(source.objectType, target.objectType, /*reportErrors*/ false)) { + if (result_2 &= isRelatedTo(source.indexType, target.indexType, /*reportErrors*/ false)) { + return result_2; + } + } + } + if (flags & 16777216 /* Conditional */) { + if (source.root.isDistributive === target.root.isDistributive) { + if (result_2 = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) { + if (result_2 &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) { + if (result_2 &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), /*reportErrors*/ false)) { + if (result_2 &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), /*reportErrors*/ false)) { + return result_2; + } + } + } + } + } + } + if (flags & 33554432 /* Substitution */) { + return isRelatedTo(source.substitute, target.substitute, /*reportErrors*/ false); + } + return 0 /* False */; + } + var result; + var originalErrorInfo; + var saveErrorInfo = errorInfo; + // We limit alias variance probing to only object and conditional types since their alias behavior + // is more predictable than other, interned types, which may or may not have an alias depending on + // the order in which things were checked. + if (source.flags & (524288 /* Object */ | 16777216 /* Conditional */) && source.aliasSymbol && + source.aliasTypeArguments && source.aliasSymbol === target.aliasSymbol && + !(source.aliasTypeArgumentsContainsMarker || target.aliasTypeArgumentsContainsMarker)) { + var variances = getAliasVariances(source.aliasSymbol); + if (result = typeArgumentsRelatedTo(source.aliasTypeArguments, target.aliasTypeArguments, variances, reportErrors)) { + return result; + } + originalErrorInfo = errorInfo; + errorInfo = saveErrorInfo; + } + if (target.flags & 262144 /* TypeParameter */) { + // A source type { [P in Q]: X } is related to a target type T if keyof T is related to Q and X is related to T[Q]. + if (ts.getObjectFlags(source) & 32 /* Mapped */ && isRelatedTo(getIndexType(target), getConstraintTypeFromMappedType(source))) { + if (!(getMappedTypeModifiers(source) & 4 /* IncludeOptional */)) { + var templateType = getTemplateTypeFromMappedType(source); + var indexedAccessType = getIndexedAccessType(target, getTypeParameterFromMappedType(source)); + if (result = isRelatedTo(templateType, indexedAccessType, reportErrors)) { + return result; + } + } + } + } + else if (target.flags & 4194304 /* Index */) { + // A keyof S is related to a keyof T if T is related to S. + if (source.flags & 4194304 /* Index */) { + if (result = isRelatedTo(target.type, source.type, /*reportErrors*/ false)) { + return result; + } + } + // A type S is assignable to keyof T if S is assignable to keyof C, where C is the + // simplified form of T or, if T doesn't simplify, the constraint of T. + if (relation !== definitelyAssignableRelation) { + var simplified = getSimplifiedType(target.type); + var constraint = simplified !== target.type ? simplified : getConstraintOfType(target.type); + if (constraint) { + // We require Ternary.True here such that circular constraints don't cause + // false positives. For example, given 'T extends { [K in keyof T]: string }', + // 'keyof T' has itself as its constraint and produces a Ternary.Maybe when + // related to other types. + if (isRelatedTo(source, getIndexType(constraint, target.stringsOnly), reportErrors) === -1 /* True */) { + return -1 /* True */; + } + } + } + } + else if (target.flags & 8388608 /* IndexedAccess */) { + // A type S is related to a type T[K], where T and K aren't both type variables, if S is related to C, + // where C is the base constraint of T[K] + if (relation !== identityRelation && !(isGenericObjectType(target.objectType) && isGenericIndexType(target.indexType))) { + var constraint = getBaseConstraintOfType(target); + if (constraint && constraint !== target) { + if (result = isRelatedTo(source, constraint, reportErrors)) { + return result; + } + } + } + } + else if (isGenericMappedType(target)) { + // A source type T is related to a target type { [P in X]: T[P] } + var template = getTemplateTypeFromMappedType(target); + var modifiers = getMappedTypeModifiers(target); + if (!(modifiers & 8 /* ExcludeOptional */)) { + if (template.flags & 8388608 /* IndexedAccess */ && template.objectType === source && + template.indexType === getTypeParameterFromMappedType(target)) { + return -1 /* True */; + } + // A source type T is related to a target type { [P in Q]: X } if Q is related to keyof T and T[Q] is related to X. + if (!isGenericMappedType(source) && isRelatedTo(getConstraintTypeFromMappedType(target), getIndexType(source))) { + var indexedAccessType = getIndexedAccessType(source, getTypeParameterFromMappedType(target)); + var templateType = getTemplateTypeFromMappedType(target); + if (result = isRelatedTo(indexedAccessType, templateType, reportErrors)) { + return result; + } + } + originalErrorInfo = errorInfo; + errorInfo = saveErrorInfo; + } + } + if (source.flags & 8650752 /* TypeVariable */) { + if (source.flags & 8388608 /* IndexedAccess */ && target.flags & 8388608 /* IndexedAccess */) { + // A type S[K] is related to a type T[J] if S is related to T and K is related to J. + if (result = isRelatedTo(source.objectType, target.objectType, reportErrors)) { + result &= isRelatedTo(source.indexType, target.indexType, reportErrors); + } + if (result) { + errorInfo = saveErrorInfo; + return result; + } + } + var constraint = getConstraintForRelation(source); + if (!constraint || (source.flags & 262144 /* TypeParameter */ && constraint.flags & 3 /* AnyOrUnknown */)) { + // A type variable with no constraint is not related to the non-primitive object type. + if (result = isRelatedTo(emptyObjectType, extractTypesOfKind(target, ~67108864 /* NonPrimitive */))) { + errorInfo = saveErrorInfo; + return result; + } + } + // hi-speed no-this-instantiation check (less accurate, but avoids costly `this`-instantiation when the constraint will suffice), see #28231 for report on why this is needed + else if (result = isRelatedTo(constraint, target, /*reportErrors*/ false, /*headMessage*/ undefined, isIntersectionConstituent)) { + errorInfo = saveErrorInfo; + return result; + } + // slower, fuller, this-instantiated check (necessary when comparing raw `this` types from base classes), see `subclassWithPolymorphicThisIsAssignable.ts` test for example + else if (result = isRelatedTo(getTypeWithThisArgument(constraint, source), target, reportErrors, /*headMessage*/ undefined, isIntersectionConstituent)) { + errorInfo = saveErrorInfo; + return result; + } + } + else if (source.flags & 4194304 /* Index */) { + if (result = isRelatedTo(keyofConstraintType, target, reportErrors)) { + errorInfo = saveErrorInfo; + return result; + } + } + else if (source.flags & 16777216 /* Conditional */) { + if (target.flags & 16777216 /* Conditional */) { + // Two conditional types 'T1 extends U1 ? X1 : Y1' and 'T2 extends U2 ? X2 : Y2' are related if + // one of T1 and T2 is related to the other, U1 and U2 are identical types, X1 is related to X2, + // and Y1 is related to Y2. + if (isTypeIdenticalTo(source.extendsType, target.extendsType) && + (isRelatedTo(source.checkType, target.checkType) || isRelatedTo(target.checkType, source.checkType))) { + if (result = isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), reportErrors)) { + result &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), reportErrors); + } + if (result) { + errorInfo = saveErrorInfo; + return result; + } + } + } + else if (relation !== definitelyAssignableRelation) { + var distributiveConstraint = getConstraintOfDistributiveConditionalType(source); + if (distributiveConstraint) { + if (result = isRelatedTo(distributiveConstraint, target, reportErrors)) { + errorInfo = saveErrorInfo; + return result; + } + } + var defaultConstraint = getDefaultConstraintOfConditionalType(source); + if (defaultConstraint) { + if (result = isRelatedTo(defaultConstraint, target, reportErrors)) { + errorInfo = saveErrorInfo; + return result; + } + } + } + } + else { + // An empty object type is related to any mapped type that includes a '?' modifier. + if (isPartialMappedType(target) && !isGenericMappedType(source) && isEmptyObjectType(source)) { + return -1 /* True */; + } + if (isGenericMappedType(target)) { + if (isGenericMappedType(source)) { + if (result = mappedTypeRelatedTo(source, target, reportErrors)) { + errorInfo = saveErrorInfo; + return result; + } + } + return 0 /* False */; + } + if (relation === definitelyAssignableRelation && isGenericMappedType(source)) { + return 0 /* False */; + } + var sourceIsPrimitive = !!(source.flags & 131068 /* Primitive */); + if (relation !== identityRelation) { + source = getApparentType(source); + } + if (ts.getObjectFlags(source) & 4 /* Reference */ && ts.getObjectFlags(target) & 4 /* Reference */ && source.target === target.target && + !(ts.getObjectFlags(source) & 8192 /* MarkerType */ || ts.getObjectFlags(target) & 8192 /* MarkerType */)) { + // We have type references to the same generic type, and the type references are not marker + // type references (which are intended by be compared structurally). Obtain the variance + // information for the type parameters and relate the type arguments accordingly. + var variances = getVariances(source.target); + if (result = typeArgumentsRelatedTo(source.typeArguments, target.typeArguments, variances, reportErrors)) { + return result; + } + // The type arguments did not relate appropriately, but it may be because we have no variance + // information (in which case typeArgumentsRelatedTo defaulted to covariance for all type + // arguments). It might also be the case that the target type has a 'void' type argument for + // a covariant type parameter that is only used in return positions within the generic type + // (in which case any type argument is permitted on the source side). In those cases we proceed + // with a structural comparison. Otherwise, we know for certain the instantiations aren't + // related and we can return here. + if (variances !== ts.emptyArray && !hasCovariantVoidArgument(target, variances)) { + // In some cases generic types that are covariant in regular type checking mode become + // invariant in --strictFunctionTypes mode because one or more type parameters are used in + // both co- and contravariant positions. In order to make it easier to diagnose *why* such + // types are invariant, if any of the type parameters are invariant we reset the reported + // errors and instead force a structural comparison (which will include elaborations that + // reveal the reason). + if (!(reportErrors && ts.some(variances, function (v) { return v === 0 /* Invariant */; }))) { + return 0 /* False */; + } + // We remember the original error information so we can restore it in case the structural + // comparison unexpectedly succeeds. This can happen when the structural comparison result + // is a Ternary.Maybe for example caused by the recursion depth limiter. + originalErrorInfo = errorInfo; + errorInfo = saveErrorInfo; + } + } + else if (isTupleType(source) && (isArrayType(target) || isReadonlyArrayType(target)) || isArrayType(source) && isReadonlyArrayType(target)) { + return isRelatedTo(getIndexTypeOfType(source, 1 /* Number */) || anyType, getIndexTypeOfType(target, 1 /* Number */) || anyType, reportErrors); + } + // Even if relationship doesn't hold for unions, intersections, or generic type references, + // it may hold in a structural comparison. + // In a check of the form X = A & B, we will have previously checked if A relates to X or B relates + // to X. Failing both of those we want to check if the aggregation of A and B's members structurally + // relates to X. Thus, we include intersection types on the source side here. + if (source.flags & (524288 /* Object */ | 2097152 /* Intersection */) && target.flags & 524288 /* Object */) { + // Report structural errors only if we haven't reported any errors yet + var reportStructuralErrors = reportErrors && errorInfo === saveErrorInfo && !sourceIsPrimitive; + result = propertiesRelatedTo(source, target, reportStructuralErrors); + if (result) { + result &= signaturesRelatedTo(source, target, 0 /* Call */, reportStructuralErrors); + if (result) { + result &= signaturesRelatedTo(source, target, 1 /* Construct */, reportStructuralErrors); + if (result) { + result &= indexTypesRelatedTo(source, target, 0 /* String */, sourceIsPrimitive, reportStructuralErrors); + if (result) { + result &= indexTypesRelatedTo(source, target, 1 /* Number */, sourceIsPrimitive, reportStructuralErrors); + } + } + } + } + if (result) { + if (!originalErrorInfo) { + errorInfo = saveErrorInfo; + return result; + } + errorInfo = originalErrorInfo; + } + } + } + return 0 /* False */; + } + // A type [P in S]: X is related to a type [Q in T]: Y if T is related to S and X' is + // related to Y, where X' is an instantiation of X in which P is replaced with Q. Notice + // that S and T are contra-variant whereas X and Y are co-variant. + function mappedTypeRelatedTo(source, target, reportErrors) { + var modifiersRelated = relation === comparableRelation || (relation === identityRelation ? getMappedTypeModifiers(source) === getMappedTypeModifiers(target) : + getCombinedMappedTypeOptionality(source) <= getCombinedMappedTypeOptionality(target)); + if (modifiersRelated) { + var result_3; + if (result_3 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) { + var mapper = createTypeMapper([getTypeParameterFromMappedType(source)], [getTypeParameterFromMappedType(target)]); + return result_3 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); + } + } + return 0 /* False */; + } + function propertiesRelatedTo(source, target, reportErrors) { + if (relation === identityRelation) { + return propertiesIdenticalTo(source, target); + } + var requireOptionalProperties = relation === subtypeRelation && !isObjectLiteralType(source) && !isEmptyArrayLiteralType(source) && !isTupleType(source); + var unmatchedProperty = getUnmatchedProperty(source, target, requireOptionalProperties); + if (unmatchedProperty) { + if (reportErrors) { + var props = ts.arrayFrom(getUnmatchedProperties(source, target, requireOptionalProperties)); + if (!headMessage || (headMessage.code !== ts.Diagnostics.Class_0_incorrectly_implements_interface_1.code && + headMessage.code !== ts.Diagnostics.Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass.code)) { + suppressNextError = true; // Retain top-level error for interface implementing issues, otherwise omit it + } + if (props.length === 1) { + var propName = symbolToString(unmatchedProperty); + reportError(ts.Diagnostics.Property_0_is_missing_in_type_1_but_required_in_type_2, propName, typeToString(source), typeToString(target)); + if (ts.length(unmatchedProperty.declarations)) { + associateRelatedInfo(ts.createDiagnosticForNode(unmatchedProperty.declarations[0], ts.Diagnostics._0_is_declared_here, propName)); + } + } + else if (props.length > 5) { // arbitrary cutoff for too-long list form + reportError(ts.Diagnostics.Type_0_is_missing_the_following_properties_from_type_1_Colon_2_and_3_more, typeToString(source), typeToString(target), ts.map(props.slice(0, 4), function (p) { return symbolToString(p); }).join(", "), props.length - 4); + } + else { + reportError(ts.Diagnostics.Type_0_is_missing_the_following_properties_from_type_1_Colon_2, typeToString(source), typeToString(target), ts.map(props, function (p) { return symbolToString(p); }).join(", ")); + } + } + return 0 /* False */; + } + if (isObjectLiteralType(target)) { + for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) { + var sourceProp = _a[_i]; + if (!getPropertyOfObjectType(target, sourceProp.escapedName)) { + var sourceType = getTypeOfSymbol(sourceProp); + if (!(sourceType === undefinedType || sourceType === undefinedWideningType)) { + if (reportErrors) { + reportError(ts.Diagnostics.Property_0_does_not_exist_on_type_1, symbolToString(sourceProp), typeToString(target)); + } + return 0 /* False */; + } + } + } + } + var result = -1 /* True */; + if (isTupleType(target)) { + var targetRestType = getRestTypeOfTupleType(target); + if (targetRestType) { + if (!isTupleType(source)) { + return 0 /* False */; + } + var sourceRestType = getRestTypeOfTupleType(source); + if (sourceRestType && !isRelatedTo(sourceRestType, targetRestType, reportErrors)) { + if (reportErrors) { + reportError(ts.Diagnostics.Rest_signatures_are_incompatible); + } + return 0 /* False */; + } + var targetCount = getTypeReferenceArity(target) - 1; + var sourceCount = getTypeReferenceArity(source) - (sourceRestType ? 1 : 0); + for (var i = targetCount; i < sourceCount; i++) { + var related = isRelatedTo(source.typeArguments[i], targetRestType, reportErrors); + if (!related) { + if (reportErrors) { + reportError(ts.Diagnostics.Property_0_is_incompatible_with_rest_element_type, "" + i); + } + return 0 /* False */; + } + result &= related; + } + } + } + var properties = getPropertiesOfObjectType(target); + for (var _b = 0, properties_2 = properties; _b < properties_2.length; _b++) { + var targetProp = properties_2[_b]; + if (!(targetProp.flags & 4194304 /* Prototype */)) { + var sourceProp = getPropertyOfType(source, targetProp.escapedName); + if (sourceProp && sourceProp !== targetProp) { + if (isIgnoredJsxProperty(source, sourceProp, getTypeOfSymbol(targetProp))) { + continue; + } + var sourcePropFlags = ts.getDeclarationModifierFlagsFromSymbol(sourceProp); + var targetPropFlags = ts.getDeclarationModifierFlagsFromSymbol(targetProp); + if (sourcePropFlags & 8 /* Private */ || targetPropFlags & 8 /* Private */) { + var hasDifferingDeclarations = sourceProp.valueDeclaration !== targetProp.valueDeclaration; + if (ts.getCheckFlags(sourceProp) & 256 /* ContainsPrivate */ && hasDifferingDeclarations) { + if (reportErrors) { + reportError(ts.Diagnostics.Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1, symbolToString(sourceProp), typeToString(source)); + } + return 0 /* False */; + } + if (hasDifferingDeclarations) { + if (reportErrors) { + if (sourcePropFlags & 8 /* Private */ && targetPropFlags & 8 /* Private */) { + reportError(ts.Diagnostics.Types_have_separate_declarations_of_a_private_property_0, symbolToString(targetProp)); + } + else { + reportError(ts.Diagnostics.Property_0_is_private_in_type_1_but_not_in_type_2, symbolToString(targetProp), typeToString(sourcePropFlags & 8 /* Private */ ? source : target), typeToString(sourcePropFlags & 8 /* Private */ ? target : source)); + } + } + return 0 /* False */; + } + } + else if (targetPropFlags & 16 /* Protected */) { + if (!isValidOverrideOf(sourceProp, targetProp)) { + if (reportErrors) { + reportError(ts.Diagnostics.Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2, symbolToString(targetProp), typeToString(getDeclaringClass(sourceProp) || source), typeToString(getDeclaringClass(targetProp) || target)); + } + return 0 /* False */; + } + } + else if (sourcePropFlags & 16 /* Protected */) { + if (reportErrors) { + reportError(ts.Diagnostics.Property_0_is_protected_in_type_1_but_public_in_type_2, symbolToString(targetProp), typeToString(source), typeToString(target)); + } + return 0 /* False */; + } + var related = isRelatedTo(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp), reportErrors); + if (!related) { + if (reportErrors) { + reportError(ts.Diagnostics.Types_of_property_0_are_incompatible, symbolToString(targetProp)); + } + return 0 /* False */; + } + result &= related; + // When checking for comparability, be more lenient with optional properties. + if (relation !== comparableRelation && sourceProp.flags & 16777216 /* Optional */ && !(targetProp.flags & 16777216 /* Optional */)) { + // TypeScript 1.0 spec (April 2014): 3.8.3 + // S is a subtype of a type T, and T is a supertype of S if ... + // S' and T are object types and, for each member M in T.. + // M is a property and S' contains a property N where + // if M is a required property, N is also a required property + // (M - property in T) + // (N - property in S) + if (reportErrors) { + reportError(ts.Diagnostics.Property_0_is_optional_in_type_1_but_required_in_type_2, symbolToString(targetProp), typeToString(source), typeToString(target)); + } + return 0 /* False */; + } + } + } + } + return result; + } + function propertiesIdenticalTo(source, target) { + if (!(source.flags & 524288 /* Object */ && target.flags & 524288 /* Object */)) { + return 0 /* False */; + } + var sourceProperties = getPropertiesOfObjectType(source); + var targetProperties = getPropertiesOfObjectType(target); + if (sourceProperties.length !== targetProperties.length) { + return 0 /* False */; + } + var result = -1 /* True */; + for (var _i = 0, sourceProperties_1 = sourceProperties; _i < sourceProperties_1.length; _i++) { + var sourceProp = sourceProperties_1[_i]; + var targetProp = getPropertyOfObjectType(target, sourceProp.escapedName); + if (!targetProp) { + return 0 /* False */; + } + var related = compareProperties(sourceProp, targetProp, isRelatedTo); + if (!related) { + return 0 /* False */; + } + result &= related; + } + return result; + } + function signaturesRelatedTo(source, target, kind, reportErrors) { + if (relation === identityRelation) { + return signaturesIdenticalTo(source, target, kind); + } + if (target === anyFunctionType || source === anyFunctionType) { + return -1 /* True */; + } + var sourceIsJSConstructor = source.symbol && isJSConstructor(source.symbol.valueDeclaration); + var targetIsJSConstructor = target.symbol && isJSConstructor(target.symbol.valueDeclaration); + var sourceSignatures = getSignaturesOfType(source, (sourceIsJSConstructor && kind === 1 /* Construct */) ? + 0 /* Call */ : kind); + var targetSignatures = getSignaturesOfType(target, (targetIsJSConstructor && kind === 1 /* Construct */) ? + 0 /* Call */ : kind); + if (kind === 1 /* Construct */ && sourceSignatures.length && targetSignatures.length) { + if (ts.isAbstractConstructorType(source) && !ts.isAbstractConstructorType(target)) { + // An abstract constructor type is not assignable to a non-abstract constructor type + // as it would otherwise be possible to new an abstract class. Note that the assignability + // check we perform for an extends clause excludes construct signatures from the target, + // so this check never proceeds. + if (reportErrors) { + reportError(ts.Diagnostics.Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type); + } + return 0 /* False */; + } + if (!constructorVisibilitiesAreCompatible(sourceSignatures[0], targetSignatures[0], reportErrors)) { + return 0 /* False */; + } + } + var result = -1 /* True */; + var saveErrorInfo = errorInfo; + if (ts.getObjectFlags(source) & 64 /* Instantiated */ && ts.getObjectFlags(target) & 64 /* Instantiated */ && source.symbol === target.symbol) { + // We have instantiations of the same anonymous type (which typically will be the type of a + // method). Simply do a pairwise comparison of the signatures in the two signature lists instead + // of the much more expensive N * M comparison matrix we explore below. We erase type parameters + // as they are known to always be the same. + for (var i = 0; i < targetSignatures.length; i++) { + var related = signatureRelatedTo(sourceSignatures[i], targetSignatures[i], /*erase*/ true, reportErrors); + if (!related) { + return 0 /* False */; + } + result &= related; + } + } + else if (sourceSignatures.length === 1 && targetSignatures.length === 1) { + // For simple functions (functions with a single signature) we only erase type parameters for + // the comparable relation. Otherwise, if the source signature is generic, we instantiate it + // in the context of the target signature before checking the relationship. Ideally we'd do + // this regardless of the number of signatures, but the potential costs are prohibitive due + // to the quadratic nature of the logic below. + var eraseGenerics = relation === comparableRelation || !!compilerOptions.noStrictGenericChecks; + result = signatureRelatedTo(sourceSignatures[0], targetSignatures[0], eraseGenerics, reportErrors); + } + else { + outer: for (var _i = 0, targetSignatures_1 = targetSignatures; _i < targetSignatures_1.length; _i++) { + var t = targetSignatures_1[_i]; + // Only elaborate errors from the first failure + var shouldElaborateErrors = reportErrors; + for (var _a = 0, sourceSignatures_1 = sourceSignatures; _a < sourceSignatures_1.length; _a++) { + var s = sourceSignatures_1[_a]; + var related = signatureRelatedTo(s, t, /*erase*/ true, shouldElaborateErrors); + if (related) { + result &= related; + errorInfo = saveErrorInfo; + continue outer; + } + shouldElaborateErrors = false; + } + if (shouldElaborateErrors) { + reportError(ts.Diagnostics.Type_0_provides_no_match_for_the_signature_1, typeToString(source), signatureToString(t, /*enclosingDeclaration*/ undefined, /*flags*/ undefined, kind)); + } + return 0 /* False */; + } + } + return result; + } + /** + * See signatureAssignableTo, compareSignaturesIdentical + */ + function signatureRelatedTo(source, target, erase, reportErrors) { + return compareSignaturesRelated(erase ? getErasedSignature(source) : source, erase ? getErasedSignature(target) : target, 0 /* None */, /*ignoreReturnTypes*/ false, reportErrors, reportError, isRelatedTo); + } + function signaturesIdenticalTo(source, target, kind) { + var sourceSignatures = getSignaturesOfType(source, kind); + var targetSignatures = getSignaturesOfType(target, kind); + if (sourceSignatures.length !== targetSignatures.length) { + return 0 /* False */; + } + var result = -1 /* True */; + for (var i = 0; i < sourceSignatures.length; i++) { + var related = compareSignaturesIdentical(sourceSignatures[i], targetSignatures[i], /*partialMatch*/ false, /*ignoreThisTypes*/ false, /*ignoreReturnTypes*/ false, isRelatedTo); + if (!related) { + return 0 /* False */; + } + result &= related; + } + return result; + } + function eachPropertyRelatedTo(source, target, kind, reportErrors) { + var result = -1 /* True */; + for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) { + var prop = _a[_i]; + if (isIgnoredJsxProperty(source, prop, /*targetMemberType*/ undefined)) { + continue; + } + // Skip over symbol-named members + if (prop.nameType && prop.nameType.flags & 8192 /* UniqueESSymbol */) { + continue; + } + if (kind === 0 /* String */ || isNumericLiteralName(prop.escapedName)) { + var related = isRelatedTo(getTypeOfSymbol(prop), target, reportErrors); + if (!related) { + if (reportErrors) { + reportError(ts.Diagnostics.Property_0_is_incompatible_with_index_signature, symbolToString(prop)); + } + return 0 /* False */; + } + result &= related; + } + } + return result; + } + function indexInfoRelatedTo(sourceInfo, targetInfo, reportErrors) { + var related = isRelatedTo(sourceInfo.type, targetInfo.type, reportErrors); + if (!related && reportErrors) { + reportError(ts.Diagnostics.Index_signatures_are_incompatible); + } + return related; + } + function indexTypesRelatedTo(source, target, kind, sourceIsPrimitive, reportErrors) { + if (relation === identityRelation) { + return indexTypesIdenticalTo(source, target, kind); + } + var targetInfo = getIndexInfoOfType(target, kind); + if (!targetInfo || targetInfo.type.flags & 3 /* AnyOrUnknown */ && !sourceIsPrimitive) { + // Index signature of type any permits assignment from everything but primitives + return -1 /* True */; + } + var sourceInfo = getIndexInfoOfType(source, kind) || + kind === 1 /* Number */ && getIndexInfoOfType(source, 0 /* String */); + if (sourceInfo) { + return indexInfoRelatedTo(sourceInfo, targetInfo, reportErrors); + } + if (isGenericMappedType(source)) { + // A generic mapped type { [P in K]: T } is related to an index signature { [x: string]: U } + // if T is related to U. + return (kind === 0 /* String */ && isRelatedTo(getTemplateTypeFromMappedType(source), targetInfo.type, reportErrors)); // TODO: GH#18217 + } + if (isObjectTypeWithInferableIndex(source)) { + var related = -1 /* True */; + if (kind === 0 /* String */) { + var sourceNumberInfo = getIndexInfoOfType(source, 1 /* Number */); + if (sourceNumberInfo) { + related = indexInfoRelatedTo(sourceNumberInfo, targetInfo, reportErrors); + } + } + if (related) { + related &= eachPropertyRelatedTo(source, targetInfo.type, kind, reportErrors); + } + return related; + } + if (reportErrors) { + reportError(ts.Diagnostics.Index_signature_is_missing_in_type_0, typeToString(source)); + } + return 0 /* False */; + } + function indexTypesIdenticalTo(source, target, indexKind) { + var targetInfo = getIndexInfoOfType(target, indexKind); + var sourceInfo = getIndexInfoOfType(source, indexKind); + if (!sourceInfo && !targetInfo) { + return -1 /* True */; + } + if (sourceInfo && targetInfo && sourceInfo.isReadonly === targetInfo.isReadonly) { + return isRelatedTo(sourceInfo.type, targetInfo.type); + } + return 0 /* False */; + } + function constructorVisibilitiesAreCompatible(sourceSignature, targetSignature, reportErrors) { + if (!sourceSignature.declaration || !targetSignature.declaration) { + return true; + } + var sourceAccessibility = ts.getSelectedModifierFlags(sourceSignature.declaration, 24 /* NonPublicAccessibilityModifier */); + var targetAccessibility = ts.getSelectedModifierFlags(targetSignature.declaration, 24 /* NonPublicAccessibilityModifier */); + // A public, protected and private signature is assignable to a private signature. + if (targetAccessibility === 8 /* Private */) { + return true; + } + // A public and protected signature is assignable to a protected signature. + if (targetAccessibility === 16 /* Protected */ && sourceAccessibility !== 8 /* Private */) { + return true; + } + // Only a public signature is assignable to public signature. + if (targetAccessibility !== 16 /* Protected */ && !sourceAccessibility) { + return true; + } + if (reportErrors) { + reportError(ts.Diagnostics.Cannot_assign_a_0_constructor_type_to_a_1_constructor_type, visibilityToString(sourceAccessibility), visibilityToString(targetAccessibility)); + } + return false; + } + } + function discriminateTypeByDiscriminableItems(target, discriminators, related, defaultValue) { + var match; + for (var _i = 0, discriminators_1 = discriminators; _i < discriminators_1.length; _i++) { + var _a = discriminators_1[_i], getDiscriminatingType = _a[0], propertyName = _a[1]; + for (var _b = 0, _c = target.types; _b < _c.length; _b++) { + var type = _c[_b]; + var targetType = getTypeOfPropertyOfType(type, propertyName); + if (targetType && related(getDiscriminatingType(), targetType)) { + if (match) { + if (type === match) + continue; // Finding multiple fields which discriminate to the same type is fine + return defaultValue; + } + match = type; + } + } + } + return match || defaultValue; + } + /** + * A type is 'weak' if it is an object type with at least one optional property + * and no required properties, call/construct signatures or index signatures + */ + function isWeakType(type) { + if (type.flags & 524288 /* Object */) { + var resolved = resolveStructuredTypeMembers(type); + return resolved.callSignatures.length === 0 && resolved.constructSignatures.length === 0 && + !resolved.stringIndexInfo && !resolved.numberIndexInfo && + resolved.properties.length > 0 && + ts.every(resolved.properties, function (p) { return !!(p.flags & 16777216 /* Optional */); }); + } + if (type.flags & 2097152 /* Intersection */) { + return ts.every(type.types, isWeakType); + } + return false; + } + function hasCommonProperties(source, target, isComparingJsxAttributes) { + for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) { + var prop = _a[_i]; + if (isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { + return true; + } + } + return false; + } + // Return a type reference where the source type parameter is replaced with the target marker + // type, and flag the result as a marker type reference. + function getMarkerTypeReference(type, source, target) { + var result = createTypeReference(type, ts.map(type.typeParameters, function (t) { return t === source ? target : t; })); + result.objectFlags |= 8192 /* MarkerType */; + return result; + } + function getAliasVariances(symbol) { + var links = getSymbolLinks(symbol); + return getVariancesWorker(links.typeParameters, links, function (_links, param, marker) { + var type = getTypeAliasInstantiation(symbol, instantiateTypes(links.typeParameters, makeUnaryTypeMapper(param, marker))); + type.aliasTypeArgumentsContainsMarker = true; + return type; + }); + } + // Return an array containing the variance of each type parameter. The variance is effectively + // a digest of the type comparisons that occur for each type argument when instantiations of the + // generic type are structurally compared. We infer the variance information by comparing + // instantiations of the generic type for type arguments with known relations. The function + // returns the emptyArray singleton if we're not in strictFunctionTypes mode or if the function + // has been invoked recursively for the given generic type. + function getVariancesWorker(typeParameters, cache, createMarkerType) { + if (typeParameters === void 0) { typeParameters = ts.emptyArray; } + var variances = cache.variances; + if (!variances) { + // The emptyArray singleton is used to signal a recursive invocation. + cache.variances = ts.emptyArray; + variances = []; + for (var _i = 0, typeParameters_1 = typeParameters; _i < typeParameters_1.length; _i++) { + var tp = typeParameters_1[_i]; + // We first compare instantiations where the type parameter is replaced with + // marker types that have a known subtype relationship. From this we can infer + // invariance, covariance, contravariance or bivariance. + var typeWithSuper = createMarkerType(cache, tp, markerSuperType); + var typeWithSub = createMarkerType(cache, tp, markerSubType); + var variance = (isTypeAssignableTo(typeWithSub, typeWithSuper) ? 1 /* Covariant */ : 0) | + (isTypeAssignableTo(typeWithSuper, typeWithSub) ? 2 /* Contravariant */ : 0); + // If the instantiations appear to be related bivariantly it may be because the + // type parameter is independent (i.e. it isn't witnessed anywhere in the generic + // type). To determine this we compare instantiations where the type parameter is + // replaced with marker types that are known to be unrelated. + if (variance === 3 /* Bivariant */ && isTypeAssignableTo(createMarkerType(cache, tp, markerOtherType), typeWithSuper)) { + variance = 4 /* Independent */; + } + variances.push(variance); + } + cache.variances = variances; + } + return variances; + } + function getVariances(type) { + if (!strictFunctionTypes) { + return ts.emptyArray; + } + if (type === globalArrayType || type === globalReadonlyArrayType) { + // Arrays are known to be covariant, no need to spend time computing this (emptyArray implies covariance for all parameters) + return ts.emptyArray; + } + return getVariancesWorker(type.typeParameters, type, getMarkerTypeReference); + } + // Return true if the given type reference has a 'void' type argument for a covariant type parameter. + // See comment at call in recursiveTypeRelatedTo for when this case matters. + function hasCovariantVoidArgument(type, variances) { + for (var i = 0; i < variances.length; i++) { + if (variances[i] === 1 /* Covariant */ && type.typeArguments[i].flags & 16384 /* Void */) { + return true; + } + } + return false; + } + function isUnconstrainedTypeParameter(type) { + return type.flags & 262144 /* TypeParameter */ && !getConstraintOfTypeParameter(type); + } + function isTypeReferenceWithGenericArguments(type) { + return !!(ts.getObjectFlags(type) & 4 /* Reference */) && ts.some(type.typeArguments, function (t) { return isUnconstrainedTypeParameter(t) || isTypeReferenceWithGenericArguments(t); }); + } + /** + * getTypeReferenceId(A) returns "111=0-12=1" + * where A.id=111 and number.id=12 + */ + function getTypeReferenceId(type, typeParameters, depth) { + if (depth === void 0) { depth = 0; } + var result = "" + type.target.id; + for (var _i = 0, _a = type.typeArguments; _i < _a.length; _i++) { + var t = _a[_i]; + if (isUnconstrainedTypeParameter(t)) { + var index = typeParameters.indexOf(t); + if (index < 0) { + index = typeParameters.length; + typeParameters.push(t); + } + result += "=" + index; + } + else if (depth < 4 && isTypeReferenceWithGenericArguments(t)) { + result += "<" + getTypeReferenceId(t, typeParameters, depth + 1) + ">"; + } + else { + result += "-" + t.id; + } + } + return result; + } + /** + * To improve caching, the relation key for two generic types uses the target's id plus ids of the type parameters. + * For other cases, the types ids are used. + */ + function getRelationKey(source, target, relation) { + if (relation === identityRelation && source.id > target.id) { + var temp = source; + source = target; + target = temp; + } + if (isTypeReferenceWithGenericArguments(source) && isTypeReferenceWithGenericArguments(target)) { + var typeParameters = []; + return getTypeReferenceId(source, typeParameters) + "," + getTypeReferenceId(target, typeParameters); + } + return source.id + "," + target.id; + } + // Invoke the callback for each underlying property symbol of the given symbol and return the first + // value that isn't undefined. + function forEachProperty(prop, callback) { + if (ts.getCheckFlags(prop) & 6 /* Synthetic */) { + for (var _i = 0, _a = prop.containingType.types; _i < _a.length; _i++) { + var t = _a[_i]; + var p = getPropertyOfType(t, prop.escapedName); + var result = p && forEachProperty(p, callback); + if (result) { + return result; + } + } + return undefined; + } + return callback(prop); + } + // Return the declaring class type of a property or undefined if property not declared in class + function getDeclaringClass(prop) { + return prop.parent && prop.parent.flags & 32 /* Class */ ? getDeclaredTypeOfSymbol(getParentOfSymbol(prop)) : undefined; + } + // Return true if some underlying source property is declared in a class that derives + // from the given base class. + function isPropertyInClassDerivedFrom(prop, baseClass) { + return forEachProperty(prop, function (sp) { + var sourceClass = getDeclaringClass(sp); + return sourceClass ? hasBaseType(sourceClass, baseClass) : false; + }); + } + // Return true if source property is a valid override of protected parts of target property. + function isValidOverrideOf(sourceProp, targetProp) { + return !forEachProperty(targetProp, function (tp) { return ts.getDeclarationModifierFlagsFromSymbol(tp) & 16 /* Protected */ ? + !isPropertyInClassDerivedFrom(sourceProp, getDeclaringClass(tp)) : false; }); + } + // Return true if the given class derives from each of the declaring classes of the protected + // constituents of the given property. + function isClassDerivedFromDeclaringClasses(checkClass, prop) { + return forEachProperty(prop, function (p) { return ts.getDeclarationModifierFlagsFromSymbol(p) & 16 /* Protected */ ? + !hasBaseType(checkClass, getDeclaringClass(p)) : false; }) ? undefined : checkClass; + } + // Return true if the given type is deeply nested. We consider this to be the case when structural type comparisons + // for 5 or more occurrences or instantiations of the type have been recorded on the given stack. It is possible, + // though highly unlikely, for this test to be true in a situation where a chain of instantiations is not infinitely + // expanding. Effectively, we will generate a false positive when two types are structurally equal to at least 5 + // levels, but unequal at some level beyond that. + function isDeeplyNestedType(type, stack, depth) { + // We track all object types that have an associated symbol (representing the origin of the type) + if (depth >= 5 && type.flags & 524288 /* Object */) { + var symbol = type.symbol; + if (symbol) { + var count = 0; + for (var i = 0; i < depth; i++) { + var t = stack[i]; + if (t.flags & 524288 /* Object */ && t.symbol === symbol) { + count++; + if (count >= 5) + return true; + } + } + } + } + return false; + } + function isPropertyIdenticalTo(sourceProp, targetProp) { + return compareProperties(sourceProp, targetProp, compareTypesIdentical) !== 0 /* False */; + } + function compareProperties(sourceProp, targetProp, compareTypes) { + // Two members are considered identical when + // - they are public properties with identical names, optionality, and types, + // - they are private or protected properties originating in the same declaration and having identical types + if (sourceProp === targetProp) { + return -1 /* True */; + } + var sourcePropAccessibility = ts.getDeclarationModifierFlagsFromSymbol(sourceProp) & 24 /* NonPublicAccessibilityModifier */; + var targetPropAccessibility = ts.getDeclarationModifierFlagsFromSymbol(targetProp) & 24 /* NonPublicAccessibilityModifier */; + if (sourcePropAccessibility !== targetPropAccessibility) { + return 0 /* False */; + } + if (sourcePropAccessibility) { + if (getTargetSymbol(sourceProp) !== getTargetSymbol(targetProp)) { + return 0 /* False */; + } + } + else { + if ((sourceProp.flags & 16777216 /* Optional */) !== (targetProp.flags & 16777216 /* Optional */)) { + return 0 /* False */; + } + } + if (isReadonlySymbol(sourceProp) !== isReadonlySymbol(targetProp)) { + return 0 /* False */; + } + return compareTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); + } + function isMatchingSignature(source, target, partialMatch) { + var sourceParameterCount = getParameterCount(source); + var targetParameterCount = getParameterCount(target); + var sourceMinArgumentCount = getMinArgumentCount(source); + var targetMinArgumentCount = getMinArgumentCount(target); + var sourceHasRestParameter = hasEffectiveRestParameter(source); + var targetHasRestParameter = hasEffectiveRestParameter(target); + // A source signature matches a target signature if the two signatures have the same number of required, + // optional, and rest parameters. + if (sourceParameterCount === targetParameterCount && + sourceMinArgumentCount === targetMinArgumentCount && + sourceHasRestParameter === targetHasRestParameter) { + return true; + } + // A source signature partially matches a target signature if the target signature has no fewer required + // parameters + if (partialMatch && sourceMinArgumentCount <= targetMinArgumentCount) { + return true; + } + return false; + } + /** + * See signatureRelatedTo, compareSignaturesIdentical + */ + function compareSignaturesIdentical(source, target, partialMatch, ignoreThisTypes, ignoreReturnTypes, compareTypes) { + // TODO (drosen): De-duplicate code between related functions. + if (source === target) { + return -1 /* True */; + } + if (!(isMatchingSignature(source, target, partialMatch))) { + return 0 /* False */; + } + // Check that the two signatures have the same number of type parameters. We might consider + // also checking that any type parameter constraints match, but that would require instantiating + // the constraints with a common set of type arguments to get relatable entities in places where + // type parameters occur in the constraints. The complexity of doing that doesn't seem worthwhile, + // particularly as we're comparing erased versions of the signatures below. + if (ts.length(source.typeParameters) !== ts.length(target.typeParameters)) { + return 0 /* False */; + } + // Spec 1.0 Section 3.8.3 & 3.8.4: + // M and N (the signatures) are instantiated using type Any as the type argument for all type parameters declared by M and N + source = getErasedSignature(source); + target = getErasedSignature(target); + var result = -1 /* True */; + if (!ignoreThisTypes) { + var sourceThisType = getThisTypeOfSignature(source); + if (sourceThisType) { + var targetThisType = getThisTypeOfSignature(target); + if (targetThisType) { + var related = compareTypes(sourceThisType, targetThisType); + if (!related) { + return 0 /* False */; + } + result &= related; + } + } + } + var targetLen = getParameterCount(target); + for (var i = 0; i < targetLen; i++) { + var s = getTypeAtPosition(source, i); + var t = getTypeAtPosition(target, i); + var related = compareTypes(t, s); + if (!related) { + return 0 /* False */; + } + result &= related; + } + if (!ignoreReturnTypes) { + var sourceTypePredicate = getTypePredicateOfSignature(source); + var targetTypePredicate = getTypePredicateOfSignature(target); + result &= sourceTypePredicate !== undefined || targetTypePredicate !== undefined + ? compareTypePredicatesIdentical(sourceTypePredicate, targetTypePredicate, compareTypes) + // If they're both type predicates their return types will both be `boolean`, so no need to compare those. + : compareTypes(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target)); + } + return result; + } + function compareTypePredicatesIdentical(source, target, compareTypes) { + return source === undefined || target === undefined || !typePredicateKindsMatch(source, target) ? 0 /* False */ : compareTypes(source.type, target.type); + } + function literalTypesWithSameBaseType(types) { + var commonBaseType; + for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { + var t = types_8[_i]; + var baseType = getBaseTypeOfLiteralType(t); + if (!commonBaseType) { + commonBaseType = baseType; + } + if (baseType === t || baseType !== commonBaseType) { + return false; + } + } + return true; + } + // When the candidate types are all literal types with the same base type, return a union + // of those literal types. Otherwise, return the leftmost type for which no type to the + // right is a supertype. + function getSupertypeOrUnion(types) { + return literalTypesWithSameBaseType(types) ? + getUnionType(types) : + ts.reduceLeft(types, function (s, t) { return isTypeSubtypeOf(s, t) ? t : s; }); + } + function getCommonSupertype(types) { + if (!strictNullChecks) { + return getSupertypeOrUnion(types); + } + var primaryTypes = ts.filter(types, function (t) { return !(t.flags & 98304 /* Nullable */); }); + return primaryTypes.length ? + getNullableType(getSupertypeOrUnion(primaryTypes), getFalsyFlagsOfTypes(types) & 98304 /* Nullable */) : + getUnionType(types, 2 /* Subtype */); + } + // Return the leftmost type for which no type to the right is a subtype. + function getCommonSubtype(types) { + return ts.reduceLeft(types, function (s, t) { return isTypeSubtypeOf(t, s) ? t : s; }); + } + function isArrayType(type) { + return !!(ts.getObjectFlags(type) & 4 /* Reference */) && type.target === globalArrayType; + } + function isReadonlyArrayType(type) { + return !!(ts.getObjectFlags(type) & 4 /* Reference */) && type.target === globalReadonlyArrayType; + } + function getElementTypeOfArrayType(type) { + return isArrayType(type) && type.typeArguments ? type.typeArguments[0] : undefined; + } + function isArrayLikeType(type) { + // A type is array-like if it is a reference to the global Array or global ReadonlyArray type, + // or if it is not the undefined or null type and if it is assignable to ReadonlyArray + return ts.getObjectFlags(type) & 4 /* Reference */ && (type.target === globalArrayType || type.target === globalReadonlyArrayType) || + !(type.flags & 98304 /* Nullable */) && isTypeAssignableTo(type, anyReadonlyArrayType); + } + function isEmptyArrayLiteralType(type) { + var elementType = isArrayType(type) ? type.typeArguments[0] : undefined; + return elementType === undefinedWideningType || elementType === implicitNeverType; + } + function isTupleLikeType(type) { + return isTupleType(type) || !!getPropertyOfType(type, "0"); + } + function getTupleElementType(type, index) { + var propType = getTypeOfPropertyOfType(type, "" + index); + if (propType) { + return propType; + } + if (everyType(type, isTupleType) && !everyType(type, function (t) { return !t.target.hasRestElement; })) { + return mapType(type, function (t) { return getRestTypeOfTupleType(t) || undefinedType; }); + } + return undefined; + } + function isNeitherUnitTypeNorNever(type) { + return !(type.flags & (109440 /* Unit */ | 131072 /* Never */)); + } + function isUnitType(type) { + return !!(type.flags & 109440 /* Unit */); + } + function isLiteralType(type) { + return type.flags & 16 /* Boolean */ ? true : + type.flags & 1048576 /* Union */ ? type.flags & 1024 /* EnumLiteral */ ? true : ts.every(type.types, isUnitType) : + isUnitType(type); + } + function getBaseTypeOfLiteralType(type) { + return type.flags & 1024 /* EnumLiteral */ ? getBaseTypeOfEnumLiteralType(type) : + type.flags & 128 /* StringLiteral */ ? stringType : + type.flags & 256 /* NumberLiteral */ ? numberType : + type.flags & 2048 /* BigIntLiteral */ ? bigintType : + type.flags & 512 /* BooleanLiteral */ ? booleanType : + type.flags & 1048576 /* Union */ ? getUnionType(ts.sameMap(type.types, getBaseTypeOfLiteralType)) : + type; + } + function getWidenedLiteralType(type) { + return type.flags & 1024 /* EnumLiteral */ && isFreshLiteralType(type) ? getBaseTypeOfEnumLiteralType(type) : + type.flags & 128 /* StringLiteral */ && isFreshLiteralType(type) ? stringType : + type.flags & 256 /* NumberLiteral */ && isFreshLiteralType(type) ? numberType : + type.flags & 2048 /* BigIntLiteral */ && isFreshLiteralType(type) ? bigintType : + type.flags & 512 /* BooleanLiteral */ && isFreshLiteralType(type) ? booleanType : + type.flags & 1048576 /* Union */ ? getUnionType(ts.sameMap(type.types, getWidenedLiteralType)) : + type; + } + function getWidenedUniqueESSymbolType(type) { + return type.flags & 8192 /* UniqueESSymbol */ ? esSymbolType : + type.flags & 1048576 /* Union */ ? getUnionType(ts.sameMap(type.types, getWidenedUniqueESSymbolType)) : + type; + } + function getWidenedLiteralLikeTypeForContextualType(type, contextualType) { + if (!isLiteralOfContextualType(type, contextualType)) { + type = getWidenedUniqueESSymbolType(getWidenedLiteralType(type)); + } + return type; + } + /** + * Check if a Type was written as a tuple type literal. + * Prefer using isTupleLikeType() unless the use of `elementTypes` is required. + */ + function isTupleType(type) { + return !!(ts.getObjectFlags(type) & 4 /* Reference */ && type.target.objectFlags & 8 /* Tuple */); + } + function getRestTypeOfTupleType(type) { + return type.target.hasRestElement ? type.typeArguments[type.target.typeParameters.length - 1] : undefined; + } + function getRestArrayTypeOfTupleType(type) { + var restType = getRestTypeOfTupleType(type); + return restType && createArrayType(restType); + } + function getLengthOfTupleType(type) { + return getTypeReferenceArity(type) - (type.target.hasRestElement ? 1 : 0); + } + function isZeroBigInt(_a) { + var value = _a.value; + return value.base10Value === "0"; + } + function getFalsyFlagsOfTypes(types) { + var result = 0; + for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { + var t = types_9[_i]; + result |= getFalsyFlags(t); + } + return result; + } + // Returns the String, Number, Boolean, StringLiteral, NumberLiteral, BooleanLiteral, Void, Undefined, or Null + // flags for the string, number, boolean, "", 0, false, void, undefined, or null types respectively. Returns + // no flags for all other types (including non-falsy literal types). + function getFalsyFlags(type) { + return type.flags & 1048576 /* Union */ ? getFalsyFlagsOfTypes(type.types) : + type.flags & 128 /* StringLiteral */ ? type.value === "" ? 128 /* StringLiteral */ : 0 : + type.flags & 256 /* NumberLiteral */ ? type.value === 0 ? 256 /* NumberLiteral */ : 0 : + type.flags & 2048 /* BigIntLiteral */ ? isZeroBigInt(type) ? 2048 /* BigIntLiteral */ : 0 : + type.flags & 512 /* BooleanLiteral */ ? (type === falseType || type === regularFalseType) ? 512 /* BooleanLiteral */ : 0 : + type.flags & 117724 /* PossiblyFalsy */; + } + function removeDefinitelyFalsyTypes(type) { + return getFalsyFlags(type) & 117632 /* DefinitelyFalsy */ ? + filterType(type, function (t) { return !(getFalsyFlags(t) & 117632 /* DefinitelyFalsy */); }) : + type; + } + function extractDefinitelyFalsyTypes(type) { + return mapType(type, getDefinitelyFalsyPartOfType); + } + function getDefinitelyFalsyPartOfType(type) { + return type.flags & 4 /* String */ ? emptyStringType : + type.flags & 8 /* Number */ ? zeroType : + type.flags & 64 /* BigInt */ ? zeroBigIntType : + type === regularFalseType || + type === falseType || + type.flags & (16384 /* Void */ | 32768 /* Undefined */ | 65536 /* Null */) || + type.flags & 128 /* StringLiteral */ && type.value === "" || + type.flags & 256 /* NumberLiteral */ && type.value === 0 || + type.flags & 2048 /* BigIntLiteral */ && isZeroBigInt(type) ? type : + neverType; + } + /** + * Add undefined or null or both to a type if they are missing. + * @param type - type to add undefined and/or null to if not present + * @param flags - Either TypeFlags.Undefined or TypeFlags.Null, or both + */ + function getNullableType(type, flags) { + var missing = (flags & ~type.flags) & (32768 /* Undefined */ | 65536 /* Null */); + return missing === 0 ? type : + missing === 32768 /* Undefined */ ? getUnionType([type, undefinedType]) : + missing === 65536 /* Null */ ? getUnionType([type, nullType]) : + getUnionType([type, undefinedType, nullType]); + } + function getOptionalType(type) { + ts.Debug.assert(strictNullChecks); + return type.flags & 32768 /* Undefined */ ? type : getUnionType([type, undefinedType]); + } + function getGlobalNonNullableTypeInstantiation(type) { + if (!deferredGlobalNonNullableTypeAlias) { + deferredGlobalNonNullableTypeAlias = getGlobalSymbol("NonNullable", 524288 /* TypeAlias */, /*diagnostic*/ undefined) || unknownSymbol; + } + // Use NonNullable global type alias if available to improve quick info/declaration emit + if (deferredGlobalNonNullableTypeAlias !== unknownSymbol) { + return getTypeAliasInstantiation(deferredGlobalNonNullableTypeAlias, [type]); + } + return getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */); // Type alias unavailable, fall back to non-higher-order behavior + } + function getNonNullableType(type) { + return strictNullChecks ? getGlobalNonNullableTypeInstantiation(type) : type; + } + /** + * Return true if type was inferred from an object literal, written as an object type literal, or is the shape of a module + * with no call or construct signatures. + */ + function isObjectTypeWithInferableIndex(type) { + return type.symbol && (type.symbol.flags & (4096 /* ObjectLiteral */ | 2048 /* TypeLiteral */ | 512 /* ValueModule */)) !== 0 && + !typeHasCallOrConstructSignatures(type); + } + function createSymbolWithType(source, type) { + var symbol = createSymbol(source.flags, source.escapedName); + symbol.declarations = source.declarations; + symbol.parent = source.parent; + symbol.type = type; + symbol.target = source; + if (source.valueDeclaration) { + symbol.valueDeclaration = source.valueDeclaration; + } + if (source.nameType) { + symbol.nameType = source.nameType; + } + return symbol; + } + function transformTypeOfMembers(type, f) { + var members = ts.createSymbolTable(); + for (var _i = 0, _a = getPropertiesOfObjectType(type); _i < _a.length; _i++) { + var property = _a[_i]; + var original = getTypeOfSymbol(property); + var updated = f(original); + members.set(property.escapedName, updated === original ? property : createSymbolWithType(property, updated)); + } + return members; + } + /** + * If the the provided object literal is subject to the excess properties check, + * create a new that is exempt. Recursively mark object literal members as exempt. + * Leave signatures alone since they are not subject to the check. + */ + function getRegularTypeOfObjectLiteral(type) { + if (!(isObjectLiteralType(type) && ts.getObjectFlags(type) & 32768 /* FreshLiteral */)) { + return type; + } + var regularType = type.regularType; + if (regularType) { + return regularType; + } + var resolved = type; + var members = transformTypeOfMembers(type, getRegularTypeOfObjectLiteral); + var regularNew = createAnonymousType(resolved.symbol, members, resolved.callSignatures, resolved.constructSignatures, resolved.stringIndexInfo, resolved.numberIndexInfo); + regularNew.flags = resolved.flags; + regularNew.objectFlags |= 128 /* ObjectLiteral */ | (ts.getObjectFlags(resolved) & 16384 /* JSLiteral */); + type.regularType = regularNew; + return regularNew; + } + function createWideningContext(parent, propertyName, siblings) { + return { parent: parent, propertyName: propertyName, siblings: siblings, resolvedProperties: undefined }; + } + function getSiblingsOfContext(context) { + if (!context.siblings) { + var siblings_1 = []; + for (var _i = 0, _a = getSiblingsOfContext(context.parent); _i < _a.length; _i++) { + var type = _a[_i]; + if (isObjectLiteralType(type)) { + var prop = getPropertyOfObjectType(type, context.propertyName); + if (prop) { + forEachType(getTypeOfSymbol(prop), function (t) { + siblings_1.push(t); + }); + } + } + } + context.siblings = siblings_1; + } + return context.siblings; + } + function getPropertiesOfContext(context) { + if (!context.resolvedProperties) { + var names = ts.createMap(); + for (var _i = 0, _a = getSiblingsOfContext(context); _i < _a.length; _i++) { + var t = _a[_i]; + if (isObjectLiteralType(t) && !(ts.getObjectFlags(t) & 1024 /* ContainsSpread */)) { + for (var _b = 0, _c = getPropertiesOfType(t); _b < _c.length; _b++) { + var prop = _c[_b]; + names.set(prop.escapedName, prop); + } + } + } + context.resolvedProperties = ts.arrayFrom(names.values()); + } + return context.resolvedProperties; + } + function getWidenedProperty(prop, context) { + if (!(prop.flags & 4 /* Property */)) { + // Since get accessors already widen their return value there is no need to + // widen accessor based properties here. + return prop; + } + var original = getTypeOfSymbol(prop); + var propContext = context && createWideningContext(context, prop.escapedName, /*siblings*/ undefined); + var widened = getWidenedTypeWithContext(original, propContext); + return widened === original ? prop : createSymbolWithType(prop, widened); + } + function getUndefinedProperty(prop) { + var cached = undefinedProperties.get(prop.escapedName); + if (cached) { + return cached; + } + var result = createSymbolWithType(prop, undefinedType); + result.flags |= 16777216 /* Optional */; + undefinedProperties.set(prop.escapedName, result); + return result; + } + function getWidenedTypeOfObjectLiteral(type, context) { + var members = ts.createSymbolTable(); + for (var _i = 0, _a = getPropertiesOfObjectType(type); _i < _a.length; _i++) { + var prop = _a[_i]; + members.set(prop.escapedName, getWidenedProperty(prop, context)); + } + if (context) { + for (var _b = 0, _c = getPropertiesOfContext(context); _b < _c.length; _b++) { + var prop = _c[_b]; + if (!members.has(prop.escapedName)) { + members.set(prop.escapedName, getUndefinedProperty(prop)); + } + } + } + var stringIndexInfo = getIndexInfoOfType(type, 0 /* String */); + var numberIndexInfo = getIndexInfoOfType(type, 1 /* Number */); + var result = createAnonymousType(type.symbol, members, ts.emptyArray, ts.emptyArray, stringIndexInfo && createIndexInfo(getWidenedType(stringIndexInfo.type), stringIndexInfo.isReadonly), numberIndexInfo && createIndexInfo(getWidenedType(numberIndexInfo.type), numberIndexInfo.isReadonly)); + result.objectFlags |= (ts.getObjectFlags(type) & 16384 /* JSLiteral */); // Retain js literal flag through widening + return result; + } + function getWidenedType(type) { + return getWidenedTypeWithContext(type, /*context*/ undefined); + } + function getWidenedTypeWithContext(type, context) { + if (type.flags & 402653184 /* RequiresWidening */) { + if (type.flags & 98304 /* Nullable */) { + return anyType; + } + if (isObjectLiteralType(type)) { + return getWidenedTypeOfObjectLiteral(type, context); + } + if (type.flags & 1048576 /* Union */) { + var unionContext_1 = context || createWideningContext(/*parent*/ undefined, /*propertyName*/ undefined, type.types); + var widenedTypes = ts.sameMap(type.types, function (t) { return t.flags & 98304 /* Nullable */ ? t : getWidenedTypeWithContext(t, unionContext_1); }); + // Widening an empty object literal transitions from a highly restrictive type to + // a highly inclusive one. For that reason we perform subtype reduction here if the + // union includes empty object types (e.g. reducing {} | string to just {}). + return getUnionType(widenedTypes, ts.some(widenedTypes, isEmptyObjectType) ? 2 /* Subtype */ : 1 /* Literal */); + } + if (isArrayType(type) || isTupleType(type)) { + return createTypeReference(type.target, ts.sameMap(type.typeArguments, getWidenedType)); + } + } + return type; + } + /** + * Reports implicit any errors that occur as a result of widening 'null' and 'undefined' + * to 'any'. A call to reportWideningErrorsInType is normally accompanied by a call to + * getWidenedType. But in some cases getWidenedType is called without reporting errors + * (type argument inference is an example). + * + * The return value indicates whether an error was in fact reported. The particular circumstances + * are on a best effort basis. Currently, if the null or undefined that causes widening is inside + * an object literal property (arbitrarily deeply), this function reports an error. If no error is + * reported, reportImplicitAnyError is a suitable fallback to report a general error. + */ + function reportWideningErrorsInType(type) { + var errorReported = false; + if (type.flags & 134217728 /* ContainsWideningType */) { + if (type.flags & 1048576 /* Union */) { + if (ts.some(type.types, isEmptyObjectType)) { + errorReported = true; + } + else { + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (reportWideningErrorsInType(t)) { + errorReported = true; + } + } + } + } + if (isArrayType(type) || isTupleType(type)) { + for (var _b = 0, _c = type.typeArguments; _b < _c.length; _b++) { + var t = _c[_b]; + if (reportWideningErrorsInType(t)) { + errorReported = true; + } + } + } + if (isObjectLiteralType(type)) { + for (var _d = 0, _e = getPropertiesOfObjectType(type); _d < _e.length; _d++) { + var p = _e[_d]; + var t = getTypeOfSymbol(p); + if (t.flags & 134217728 /* ContainsWideningType */) { + if (!reportWideningErrorsInType(t)) { + error(p.valueDeclaration, ts.Diagnostics.Object_literal_s_property_0_implicitly_has_an_1_type, symbolToString(p), typeToString(getWidenedType(t))); + } + errorReported = true; + } + } + } + } + return errorReported; + } + function reportImplicitAny(declaration, type) { + var typeAsString = typeToString(getWidenedType(type)); + if (ts.isInJSFile(declaration) && !ts.isCheckJsEnabledForFile(ts.getSourceFileOfNode(declaration), compilerOptions)) { + // Only report implicit any errors/suggestions in TS and ts-check JS files + return; + } + var diagnostic; + switch (declaration.kind) { + case 204 /* BinaryExpression */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + diagnostic = noImplicitAny ? ts.Diagnostics.Member_0_implicitly_has_an_1_type : ts.Diagnostics.Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage; + break; + case 151 /* Parameter */: + var param = declaration; + if (ts.isIdentifier(param.name) && + (ts.isCallSignatureDeclaration(param.parent) || ts.isMethodSignature(param.parent) || ts.isFunctionTypeNode(param.parent)) && + param.parent.parameters.indexOf(param) > -1 && + (resolveName(param, param.name.escapedText, 67897832 /* Type */, undefined, param.name.escapedText, /*isUse*/ true) || + param.name.originalKeywordKind && ts.isTypeNodeKind(param.name.originalKeywordKind))) { + var newName = "arg" + param.parent.parameters.indexOf(param); + errorOrSuggestion(noImplicitAny, declaration, ts.Diagnostics.Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1, newName, ts.declarationNameToString(param.name)); + return; + } + diagnostic = declaration.dotDotDotToken ? + noImplicitAny ? ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type : ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage : + noImplicitAny ? ts.Diagnostics.Parameter_0_implicitly_has_an_1_type : ts.Diagnostics.Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage; + break; + case 186 /* BindingElement */: + diagnostic = ts.Diagnostics.Binding_element_0_implicitly_has_an_1_type; + break; + case 289 /* JSDocFunctionType */: + error(declaration, ts.Diagnostics.Function_type_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString); + return; + case 239 /* FunctionDeclaration */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + if (noImplicitAny && !declaration.name) { + error(declaration, ts.Diagnostics.Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString); + return; + } + diagnostic = noImplicitAny ? ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type : ts.Diagnostics._0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage; + break; + case 181 /* MappedType */: + if (noImplicitAny) { + error(declaration, ts.Diagnostics.Mapped_object_type_implicitly_has_an_any_template_type); + } + return; + default: + diagnostic = noImplicitAny ? ts.Diagnostics.Variable_0_implicitly_has_an_1_type : ts.Diagnostics.Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage; + } + errorOrSuggestion(noImplicitAny, declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString); + } + function reportErrorsFromWidening(declaration, type) { + if (produceDiagnostics && noImplicitAny && type.flags & 134217728 /* ContainsWideningType */) { + // Report implicit any error within type if possible, otherwise report error on declaration + if (!reportWideningErrorsInType(type)) { + reportImplicitAny(declaration, type); + } + } + } + function forEachMatchingParameterType(source, target, callback) { + var sourceCount = getParameterCount(source); + var targetCount = getParameterCount(target); + var sourceRestType = getEffectiveRestType(source); + var targetRestType = getEffectiveRestType(target); + var targetNonRestCount = targetRestType ? targetCount - 1 : targetCount; + var paramCount = sourceRestType ? targetNonRestCount : Math.min(sourceCount, targetNonRestCount); + var sourceThisType = getThisTypeOfSignature(source); + if (sourceThisType) { + var targetThisType = getThisTypeOfSignature(target); + if (targetThisType) { + callback(sourceThisType, targetThisType); + } + } + for (var i = 0; i < paramCount; i++) { + callback(getTypeAtPosition(source, i), getTypeAtPosition(target, i)); + } + if (targetRestType) { + callback(getRestTypeAtPosition(source, paramCount), targetRestType); + } + } + function createInferenceContext(typeParameters, signature, flags, compareTypes, baseInferences) { + var inferences = baseInferences ? baseInferences.map(cloneInferenceInfo) : typeParameters.map(createInferenceInfo); + var context = mapper; + context.typeParameters = typeParameters; + context.signature = signature; + context.inferences = inferences; + context.flags = flags; + context.compareTypes = compareTypes || compareTypesAssignable; + return context; + function mapper(t) { + for (var i = 0; i < inferences.length; i++) { + if (t === inferences[i].typeParameter) { + inferences[i].isFixed = true; + return getInferredType(context, i); + } + } + return t; + } + } + function createInferenceInfo(typeParameter) { + return { + typeParameter: typeParameter, + candidates: undefined, + contraCandidates: undefined, + inferredType: undefined, + priority: undefined, + topLevel: true, + isFixed: false + }; + } + function cloneInferenceInfo(inference) { + return { + typeParameter: inference.typeParameter, + candidates: inference.candidates && inference.candidates.slice(), + contraCandidates: inference.contraCandidates && inference.contraCandidates.slice(), + inferredType: inference.inferredType, + priority: inference.priority, + topLevel: inference.topLevel, + isFixed: inference.isFixed + }; + } + // Return true if the given type could possibly reference a type parameter for which + // we perform type inference (i.e. a type parameter of a generic function). We cache + // results for union and intersection types for performance reasons. + function couldContainTypeVariables(type) { + var objectFlags = ts.getObjectFlags(type); + return !!(type.flags & 63176704 /* Instantiable */ || + objectFlags & 4 /* Reference */ && ts.forEach(type.typeArguments, couldContainTypeVariables) || + objectFlags & 16 /* Anonymous */ && type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 2048 /* TypeLiteral */ | 32 /* Class */) || + objectFlags & 32 /* Mapped */ || + type.flags & 3145728 /* UnionOrIntersection */ && couldUnionOrIntersectionContainTypeVariables(type)); + } + function couldUnionOrIntersectionContainTypeVariables(type) { + if (type.couldContainTypeVariables === undefined) { + type.couldContainTypeVariables = ts.some(type.types, couldContainTypeVariables); + } + return type.couldContainTypeVariables; + } + function isTypeParameterAtTopLevel(type, typeParameter) { + return type === typeParameter || !!(type.flags & 3145728 /* UnionOrIntersection */) && ts.some(type.types, function (t) { return isTypeParameterAtTopLevel(t, typeParameter); }); + } + /** Create an object with properties named in the string literal type. Every property has type `any` */ + function createEmptyObjectTypeFromStringLiteral(type) { + var members = ts.createSymbolTable(); + forEachType(type, function (t) { + if (!(t.flags & 128 /* StringLiteral */)) { + return; + } + var name = ts.escapeLeadingUnderscores(t.value); + var literalProp = createSymbol(4 /* Property */, name); + literalProp.type = anyType; + if (t.symbol) { + literalProp.declarations = t.symbol.declarations; + literalProp.valueDeclaration = t.symbol.valueDeclaration; + } + members.set(name, literalProp); + }); + var indexInfo = type.flags & 4 /* String */ ? createIndexInfo(emptyObjectType, /*isReadonly*/ false) : undefined; + return createAnonymousType(undefined, members, ts.emptyArray, ts.emptyArray, indexInfo, undefined); + } + /** + * Infer a suitable input type for a homomorphic mapped type { [P in keyof T]: X }. We construct + * an object type with the same set of properties as the source type, where the type of each + * property is computed by inferring from the source property type to X for the type + * variable T[P] (i.e. we treat the type T[P] as the type variable we're inferring for). + */ + function inferTypeForHomomorphicMappedType(source, target, constraint) { + var key = source.id + "," + target.id + "," + constraint.id; + if (reverseMappedCache.has(key)) { + return reverseMappedCache.get(key); + } + reverseMappedCache.set(key, undefined); + var type = createReverseMappedType(source, target, constraint); + reverseMappedCache.set(key, type); + return type; + } + function createReverseMappedType(source, target, constraint) { + var properties = getPropertiesOfType(source); + if (properties.length === 0 && !getIndexInfoOfType(source, 0 /* String */)) { + return undefined; + } + // If any property contains context sensitive functions that have been skipped, the source type + // is incomplete and we can't infer a meaningful input type. + for (var _i = 0, properties_3 = properties; _i < properties_3.length; _i++) { + var prop = properties_3[_i]; + if (getTypeOfSymbol(prop).flags & 536870912 /* ContainsAnyFunctionType */) { + return undefined; + } + } + // For arrays and tuples we infer new arrays and tuples where the reverse mapping has been + // applied to the element type(s). + if (isArrayType(source)) { + return createArrayType(inferReverseMappedType(source.typeArguments[0], target, constraint)); + } + if (isReadonlyArrayType(source)) { + return createReadonlyArrayType(inferReverseMappedType(source.typeArguments[0], target, constraint)); + } + if (isTupleType(source)) { + var elementTypes = ts.map(source.typeArguments || ts.emptyArray, function (t) { return inferReverseMappedType(t, target, constraint); }); + var minLength = getMappedTypeModifiers(target) & 4 /* IncludeOptional */ ? + getTypeReferenceArity(source) - (source.target.hasRestElement ? 1 : 0) : source.target.minLength; + return createTupleType(elementTypes, minLength, source.target.hasRestElement, source.target.associatedNames); + } + // For all other object types we infer a new object type where the reverse mapping has been + // applied to the type of each property. + var reversed = createObjectType(2048 /* ReverseMapped */ | 16 /* Anonymous */, /*symbol*/ undefined); + reversed.source = source; + reversed.mappedType = target; + reversed.constraintType = constraint; + return reversed; + } + function getTypeOfReverseMappedSymbol(symbol) { + return inferReverseMappedType(symbol.propertyType, symbol.mappedType, symbol.constraintType); + } + function inferReverseMappedType(sourceType, target, constraint) { + var typeParameter = getIndexedAccessType(constraint.type, getTypeParameterFromMappedType(target)); + var templateType = getTemplateTypeFromMappedType(target); + var inference = createInferenceInfo(typeParameter); + inferTypes([inference], sourceType, templateType); + return getTypeFromInference(inference); + } + function getUnmatchedProperties(source, target, requireOptionalProperties) { + var properties, _i, properties_4, targetProp, sourceProp; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + properties = target.flags & 2097152 /* Intersection */ ? getPropertiesOfUnionOrIntersectionType(target) : getPropertiesOfObjectType(target); + _i = 0, properties_4 = properties; + _a.label = 1; + case 1: + if (!(_i < properties_4.length)) return [3 /*break*/, 4]; + targetProp = properties_4[_i]; + if (!(requireOptionalProperties || !(targetProp.flags & 16777216 /* Optional */))) return [3 /*break*/, 3]; + sourceProp = getPropertyOfType(source, targetProp.escapedName); + if (!!sourceProp) return [3 /*break*/, 3]; + return [4 /*yield*/, targetProp]; + case 2: + _a.sent(); + _a.label = 3; + case 3: + _i++; + return [3 /*break*/, 1]; + case 4: return [2 /*return*/]; + } + }); + } + function getUnmatchedProperty(source, target, requireOptionalProperties) { + return getUnmatchedProperties(source, target, requireOptionalProperties).next().value; + } + function tupleTypesDefinitelyUnrelated(source, target) { + return target.target.minLength > source.target.minLength || + !getRestTypeOfTupleType(target) && (!!getRestTypeOfTupleType(source) || getLengthOfTupleType(target) < getLengthOfTupleType(source)); + } + function typesDefinitelyUnrelated(source, target) { + // Two tuple types with incompatible arities are definitely unrelated. + // Two object types that each have a property that is unmatched in the other are definitely unrelated. + return isTupleType(source) && isTupleType(target) && tupleTypesDefinitelyUnrelated(source, target) || + !!getUnmatchedProperty(source, target, /*requireOptionalProperties*/ false) && !!getUnmatchedProperty(target, source, /*requireOptionalProperties*/ false); + } + function getTypeFromInference(inference) { + return inference.candidates ? getUnionType(inference.candidates, 2 /* Subtype */) : + inference.contraCandidates ? getIntersectionType(inference.contraCandidates) : + emptyObjectType; + } + function inferTypes(inferences, originalSource, originalTarget, priority) { + if (priority === void 0) { priority = 0; } + var symbolStack; + var visited; + var contravariant = false; + var bivariant = false; + var propagationType; + var allowComplexConstraintInference = true; + inferFromTypes(originalSource, originalTarget); + function inferFromTypes(source, target) { + if (!couldContainTypeVariables(target)) { + return; + } + if (source === wildcardType) { + // We are inferring from an 'any' type. We want to infer this type for every type parameter + // referenced in the target type, so we record it as the propagation type and infer from the + // target to itself. Then, as we find candidates we substitute the propagation type. + var savePropagationType = propagationType; + propagationType = source; + inferFromTypes(target, target); + propagationType = savePropagationType; + return; + } + if (source.aliasSymbol && source.aliasTypeArguments && source.aliasSymbol === target.aliasSymbol) { + // Source and target are types originating in the same generic type alias declaration. + // Simply infer from source type arguments to target type arguments. + var sourceTypes = source.aliasTypeArguments; + var targetTypes = target.aliasTypeArguments; + for (var i = 0; i < sourceTypes.length; i++) { + inferFromTypes(sourceTypes[i], targetTypes[i]); + } + return; + } + if (source.flags & 1048576 /* Union */ && target.flags & 1048576 /* Union */ && !(source.flags & 1024 /* EnumLiteral */ && target.flags & 1024 /* EnumLiteral */) || + source.flags & 2097152 /* Intersection */ && target.flags & 2097152 /* Intersection */) { + // Source and target are both unions or both intersections. If source and target + // are the same type, just relate each constituent type to itself. + if (source === target) { + for (var _i = 0, _a = source.types; _i < _a.length; _i++) { + var t = _a[_i]; + inferFromTypes(t, t); + } + return; + } + // Find each source constituent type that has an identically matching target constituent + // type, and for each such type infer from the type to itself. When inferring from a + // type to itself we effectively find all type parameter occurrences within that type + // and infer themselves as their type arguments. We have special handling for numeric + // and string literals because the number and string types are not represented as unions + // of all their possible values. + var matchingTypes = void 0; + for (var _b = 0, _c = source.types; _b < _c.length; _b++) { + var t = _c[_b]; + if (typeIdenticalToSomeType(t, target.types)) { + (matchingTypes || (matchingTypes = [])).push(t); + inferFromTypes(t, t); + } + else if (t.flags & (256 /* NumberLiteral */ | 128 /* StringLiteral */)) { + var b = getBaseTypeOfLiteralType(t); + if (typeIdenticalToSomeType(b, target.types)) { + (matchingTypes || (matchingTypes = [])).push(t, b); + } + } + } + // Next, to improve the quality of inferences, reduce the source and target types by + // removing the identically matched constituents. For example, when inferring from + // 'string | string[]' to 'string | T' we reduce the types to 'string[]' and 'T'. + if (matchingTypes) { + source = removeTypesFromUnionOrIntersection(source, matchingTypes); + target = removeTypesFromUnionOrIntersection(target, matchingTypes); + } + } + if (target.flags & 8650752 /* TypeVariable */) { + // If target is a type parameter, make an inference, unless the source type contains + // the anyFunctionType (the wildcard type that's used to avoid contextually typing functions). + // Because the anyFunctionType is internal, it should not be exposed to the user by adding + // it as an inference candidate. Hopefully, a better candidate will come along that does + // not contain anyFunctionType when we come back to this argument for its second round + // of inference. Also, we exclude inferences for silentNeverType (which is used as a wildcard + // when constructing types from type parameters that had no inference candidates). + if (source.flags & 536870912 /* ContainsAnyFunctionType */ || source === silentNeverType || (priority & 8 /* ReturnType */ && (source === autoType || source === autoArrayType))) { + return; + } + var inference = getInferenceInfoForType(target); + if (inference) { + if (!inference.isFixed) { + if (inference.priority === undefined || priority < inference.priority) { + inference.candidates = undefined; + inference.contraCandidates = undefined; + inference.priority = priority; + } + if (priority === inference.priority) { + var candidate = propagationType || source; + // We make contravariant inferences only if we are in a pure contravariant position, + // i.e. only if we have not descended into a bivariant position. + if (contravariant && !bivariant) { + inference.contraCandidates = ts.appendIfUnique(inference.contraCandidates, candidate); + } + else { + inference.candidates = ts.appendIfUnique(inference.candidates, candidate); + } + } + if (!(priority & 8 /* ReturnType */) && target.flags & 262144 /* TypeParameter */ && !isTypeParameterAtTopLevel(originalTarget, target)) { + inference.topLevel = false; + } + } + return; + } + else { + // Infer to the simplified version of an indexed access, if possible, to (hopefully) expose more bare type parameters to the inference engine + var simplified = getSimplifiedType(target); + if (simplified !== target) { + inferFromTypesOnce(source, simplified); + } + else if (target.flags & 8388608 /* IndexedAccess */) { + var indexType = getSimplifiedType(target.indexType); + // Generally simplifications of instantiable indexes are avoided to keep relationship checking correct, however if our target is an access, we can consider + // that key of that access to be "instantiated", since we're looking to find the infernce goal in any way we can. + if (indexType.flags & 63176704 /* Instantiable */) { + var simplified_1 = distributeIndexOverObjectType(getSimplifiedType(target.objectType), indexType); + if (simplified_1 && simplified_1 !== target) { + inferFromTypesOnce(source, simplified_1); + } + } + } + } + } + if (ts.getObjectFlags(source) & 4 /* Reference */ && ts.getObjectFlags(target) & 4 /* Reference */ && source.target === target.target) { + // If source and target are references to the same generic type, infer from type arguments + var sourceTypes = source.typeArguments || ts.emptyArray; + var targetTypes = target.typeArguments || ts.emptyArray; + var count = sourceTypes.length < targetTypes.length ? sourceTypes.length : targetTypes.length; + var variances = getVariances(source.target); + for (var i = 0; i < count; i++) { + if (i < variances.length && variances[i] === 2 /* Contravariant */) { + inferFromContravariantTypes(sourceTypes[i], targetTypes[i]); + } + else { + inferFromTypes(sourceTypes[i], targetTypes[i]); + } + } + } + else if (source.flags & 4194304 /* Index */ && target.flags & 4194304 /* Index */) { + contravariant = !contravariant; + inferFromTypes(source.type, target.type); + contravariant = !contravariant; + } + else if ((isLiteralType(source) || source.flags & 4 /* String */) && target.flags & 4194304 /* Index */) { + var empty = createEmptyObjectTypeFromStringLiteral(source); + contravariant = !contravariant; + var savePriority = priority; + priority |= 16 /* LiteralKeyof */; + inferFromTypes(empty, target.type); + priority = savePriority; + contravariant = !contravariant; + } + else if (source.flags & 8388608 /* IndexedAccess */ && target.flags & 8388608 /* IndexedAccess */) { + inferFromTypes(source.objectType, target.objectType); + inferFromTypes(source.indexType, target.indexType); + } + else if (source.flags & 16777216 /* Conditional */ && target.flags & 16777216 /* Conditional */) { + inferFromTypes(source.checkType, target.checkType); + inferFromTypes(source.extendsType, target.extendsType); + inferFromTypes(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target)); + inferFromTypes(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target)); + } + else if (target.flags & 16777216 /* Conditional */) { + inferFromTypes(source, getUnionType([getTrueTypeFromConditionalType(target), getFalseTypeFromConditionalType(target)])); + } + else if (target.flags & 3145728 /* UnionOrIntersection */) { + var targetTypes = target.types; + var typeVariableCount = 0; + var typeVariable = void 0; + // First infer to each type in union or intersection that isn't a type variable + for (var _d = 0, targetTypes_3 = targetTypes; _d < targetTypes_3.length; _d++) { + var t = targetTypes_3[_d]; + if (getInferenceInfoForType(t)) { + typeVariable = t; + typeVariableCount++; + } + else { + inferFromTypes(source, t); + } + } + // Next, if target containings a single naked type variable, make a secondary inference to that type + // variable. This gives meaningful results for union types in co-variant positions and intersection + // types in contra-variant positions (such as callback parameters). + if (typeVariableCount === 1) { + var savePriority = priority; + priority |= 1 /* NakedTypeVariable */; + inferFromTypes(source, typeVariable); + priority = savePriority; + } + } + else if (source.flags & 1048576 /* Union */) { + // Source is a union or intersection type, infer from each constituent type + var sourceTypes = source.types; + for (var _e = 0, sourceTypes_3 = sourceTypes; _e < sourceTypes_3.length; _e++) { + var sourceType = sourceTypes_3[_e]; + inferFromTypes(sourceType, target); + } + } + else { + if (!(priority & 32 /* NoConstraints */ && source.flags & (2097152 /* Intersection */ | 63176704 /* Instantiable */))) { + var apparentSource = getApparentType(source); + // getApparentType can return _any_ type, since an indexed access or conditional may simplify to any other type. + // If that occurs and it doesn't simplify to an object or intersection, we'll need to restart `inferFromTypes` + // with the simplified source. + if (apparentSource !== source && allowComplexConstraintInference && !(apparentSource.flags & (524288 /* Object */ | 2097152 /* Intersection */))) { + // TODO: The `allowComplexConstraintInference` flag is a hack! This forbids inference from complex constraints within constraints! + // This isn't required algorithmically, but rather is used to lower the memory burden caused by performing inference + // that is _too good_ in projects with complicated constraints (eg, fp-ts). In such cases, if we did not limit ourselves + // here, we might produce more valid inferences for types, causing us to do more checks and perform more instantiations + // (in addition to the extra stack depth here) which, in turn, can push the already close process over its limit. + // TL;DR: If we ever become generally more memory efficienct (or our resource budget ever increases), we should just + // remove this `allowComplexConstraintInference` flag. + allowComplexConstraintInference = false; + return inferFromTypes(apparentSource, target); + } + source = apparentSource; + } + if (source.flags & (524288 /* Object */ | 2097152 /* Intersection */)) { + var key = source.id + "," + target.id; + if (visited && visited.get(key)) { + return; + } + (visited || (visited = ts.createMap())).set(key, true); + // If we are already processing another target type with the same associated symbol (such as + // an instantiation of the same generic type), we do not explore this target as it would yield + // no further inferences. We exclude the static side of classes from this check since it shares + // its symbol with the instance side which would lead to false positives. + var isNonConstructorObject = target.flags & 524288 /* Object */ && + !(ts.getObjectFlags(target) & 16 /* Anonymous */ && target.symbol && target.symbol.flags & 32 /* Class */); + var symbol = isNonConstructorObject ? target.symbol : undefined; + if (symbol) { + if (ts.contains(symbolStack, symbol)) { + return; + } + (symbolStack || (symbolStack = [])).push(symbol); + inferFromObjectTypes(source, target); + symbolStack.pop(); + } + else { + inferFromObjectTypes(source, target); + } + } + } + function inferFromTypesOnce(source, target) { + var key = source.id + "," + target.id; + if (!visited || !visited.get(key)) { + (visited || (visited = ts.createMap())).set(key, true); + inferFromTypes(source, target); + } + } + } + function inferFromContravariantTypes(source, target) { + if (strictFunctionTypes || priority & 64 /* AlwaysStrict */) { + contravariant = !contravariant; + inferFromTypes(source, target); + contravariant = !contravariant; + } + else { + inferFromTypes(source, target); + } + } + function getInferenceInfoForType(type) { + if (type.flags & 8650752 /* TypeVariable */) { + for (var _i = 0, inferences_1 = inferences; _i < inferences_1.length; _i++) { + var inference = inferences_1[_i]; + if (type === inference.typeParameter) { + return inference; + } + } + } + return undefined; + } + function inferFromMappedTypeConstraint(source, target, constraintType) { + if (constraintType.flags & 1048576 /* Union */) { + var result = false; + for (var _i = 0, _a = constraintType.types; _i < _a.length; _i++) { + var type = _a[_i]; + result = inferFromMappedTypeConstraint(source, target, type) || result; + } + return result; + } + if (constraintType.flags & 4194304 /* Index */) { + // We're inferring from some source type S to a homomorphic mapped type { [P in keyof T]: X }, + // where T is a type variable. Use inferTypeForHomomorphicMappedType to infer a suitable source + // type and then make a secondary inference from that type to T. We make a secondary inference + // such that direct inferences to T get priority over inferences to Partial, for example. + var inference = getInferenceInfoForType(constraintType.type); + if (inference && !inference.isFixed) { + var inferredType = inferTypeForHomomorphicMappedType(source, target, constraintType); + if (inferredType) { + var savePriority = priority; + priority |= 2 /* HomomorphicMappedType */; + inferFromTypes(inferredType, inference.typeParameter); + priority = savePriority; + } + } + return true; + } + if (constraintType.flags & 262144 /* TypeParameter */) { + // We're inferring from some source type S to a mapped type { [P in T]: X }, where T is a type + // parameter. Infer from 'keyof S' to T and infer from a union of each property type in S to X. + var savePriority = priority; + priority |= 4 /* MappedTypeConstraint */; + inferFromTypes(getIndexType(source), constraintType); + priority = savePriority; + inferFromTypes(getUnionType(ts.map(getPropertiesOfType(source), getTypeOfSymbol)), getTemplateTypeFromMappedType(target)); + return true; + } + return false; + } + function inferFromObjectTypes(source, target) { + if (isGenericMappedType(source) && isGenericMappedType(target)) { + // The source and target types are generic types { [P in S]: X } and { [P in T]: Y }, so we infer + // from S to T and from X to Y. + inferFromTypes(getConstraintTypeFromMappedType(source), getConstraintTypeFromMappedType(target)); + inferFromTypes(getTemplateTypeFromMappedType(source), getTemplateTypeFromMappedType(target)); + } + if (ts.getObjectFlags(target) & 32 /* Mapped */) { + var constraintType = getConstraintTypeFromMappedType(target); + if (inferFromMappedTypeConstraint(source, target, constraintType)) { + return; + } + } + // Infer from the members of source and target only if the two types are possibly related + if (!typesDefinitelyUnrelated(source, target)) { + inferFromProperties(source, target); + inferFromSignatures(source, target, 0 /* Call */); + inferFromSignatures(source, target, 1 /* Construct */); + inferFromIndexTypes(source, target); + } + } + function inferFromProperties(source, target) { + if (isTupleType(source)) { + if (isTupleType(target)) { + var sourceLength = getLengthOfTupleType(source); + var targetLength = getLengthOfTupleType(target); + var sourceRestType = getRestTypeOfTupleType(source); + var targetRestType = getRestTypeOfTupleType(target); + var fixedLength = targetLength < sourceLength || sourceRestType ? targetLength : sourceLength; + for (var i = 0; i < fixedLength; i++) { + inferFromTypes(i < sourceLength ? source.typeArguments[i] : sourceRestType, target.typeArguments[i]); + } + if (targetRestType) { + var types = fixedLength < sourceLength ? source.typeArguments.slice(fixedLength, sourceLength) : []; + if (sourceRestType) { + types.push(sourceRestType); + } + if (types.length) { + inferFromTypes(getUnionType(types), targetRestType); + } + } + return; + } + if (isArrayType(target)) { + inferFromIndexTypes(source, target); + return; + } + } + var properties = getPropertiesOfObjectType(target); + for (var _i = 0, properties_5 = properties; _i < properties_5.length; _i++) { + var targetProp = properties_5[_i]; + var sourceProp = getPropertyOfType(source, targetProp.escapedName); + if (sourceProp) { + inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); + } + } + } + function inferFromSignatures(source, target, kind) { + var sourceSignatures = getSignaturesOfType(source, kind); + var targetSignatures = getSignaturesOfType(target, kind); + var sourceLen = sourceSignatures.length; + var targetLen = targetSignatures.length; + var len = sourceLen < targetLen ? sourceLen : targetLen; + var skipParameters = !!(source.flags & 536870912 /* ContainsAnyFunctionType */); + for (var i = 0; i < len; i++) { + inferFromSignature(getBaseSignature(sourceSignatures[sourceLen - len + i]), getBaseSignature(targetSignatures[targetLen - len + i]), skipParameters); + } + } + function inferFromSignature(source, target, skipParameters) { + if (!skipParameters) { + var saveBivariant = bivariant; + var kind = target.declaration ? target.declaration.kind : 0 /* Unknown */; + // Once we descend into a bivariant signature we remain bivariant for all nested inferences + bivariant = bivariant || kind === 156 /* MethodDeclaration */ || kind === 155 /* MethodSignature */ || kind === 157 /* Constructor */; + forEachMatchingParameterType(source, target, inferFromContravariantTypes); + bivariant = saveBivariant; + } + var sourceTypePredicate = getTypePredicateOfSignature(source); + var targetTypePredicate = getTypePredicateOfSignature(target); + if (sourceTypePredicate && targetTypePredicate && sourceTypePredicate.kind === targetTypePredicate.kind) { + inferFromTypes(sourceTypePredicate.type, targetTypePredicate.type); + } + else { + inferFromTypes(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target)); + } + } + function inferFromIndexTypes(source, target) { + var targetStringIndexType = getIndexTypeOfType(target, 0 /* String */); + if (targetStringIndexType) { + var sourceIndexType = getIndexTypeOfType(source, 0 /* String */) || + getImplicitIndexTypeOfType(source, 0 /* String */); + if (sourceIndexType) { + inferFromTypes(sourceIndexType, targetStringIndexType); + } + } + var targetNumberIndexType = getIndexTypeOfType(target, 1 /* Number */); + if (targetNumberIndexType) { + var sourceIndexType = getIndexTypeOfType(source, 1 /* Number */) || + getIndexTypeOfType(source, 0 /* String */) || + getImplicitIndexTypeOfType(source, 1 /* Number */); + if (sourceIndexType) { + inferFromTypes(sourceIndexType, targetNumberIndexType); + } + } + } + } + function typeIdenticalToSomeType(type, types) { + for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { + var t = types_10[_i]; + if (isTypeIdenticalTo(t, type)) { + return true; + } + } + return false; + } + /** + * Return a new union or intersection type computed by removing a given set of types + * from a given union or intersection type. + */ + function removeTypesFromUnionOrIntersection(type, typesToRemove) { + var reducedTypes = []; + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (!typeIdenticalToSomeType(t, typesToRemove)) { + reducedTypes.push(t); + } + } + return type.flags & 1048576 /* Union */ ? getUnionType(reducedTypes) : getIntersectionType(reducedTypes); + } + function hasPrimitiveConstraint(type) { + var constraint = getConstraintOfTypeParameter(type); + return !!constraint && maybeTypeOfKind(constraint.flags & 16777216 /* Conditional */ ? getDefaultConstraintOfConditionalType(constraint) : constraint, 131068 /* Primitive */ | 4194304 /* Index */); + } + function isObjectLiteralType(type) { + return !!(ts.getObjectFlags(type) & 128 /* ObjectLiteral */); + } + function widenObjectLiteralCandidates(candidates) { + if (candidates.length > 1) { + var objectLiterals = ts.filter(candidates, isObjectLiteralType); + if (objectLiterals.length) { + var objectLiteralsType = getWidenedType(getUnionType(objectLiterals, 2 /* Subtype */)); + return ts.concatenate(ts.filter(candidates, function (t) { return !isObjectLiteralType(t); }), [objectLiteralsType]); + } + } + return candidates; + } + function getContravariantInference(inference) { + return inference.priority & 28 /* PriorityImpliesCombination */ ? getIntersectionType(inference.contraCandidates) : getCommonSubtype(inference.contraCandidates); + } + function getCovariantInference(inference, signature) { + // Extract all object literal types and replace them with a single widened and normalized type. + var candidates = widenObjectLiteralCandidates(inference.candidates); + // We widen inferred literal types if + // all inferences were made to top-level occurrences of the type parameter, and + // the type parameter has no constraint or its constraint includes no primitive or literal types, and + // the type parameter was fixed during inference or does not occur at top-level in the return type. + var primitiveConstraint = hasPrimitiveConstraint(inference.typeParameter); + var widenLiteralTypes = !primitiveConstraint && inference.topLevel && + (inference.isFixed || !isTypeParameterAtTopLevel(getReturnTypeOfSignature(signature), inference.typeParameter)); + var baseCandidates = primitiveConstraint ? ts.sameMap(candidates, getRegularTypeOfLiteralType) : + widenLiteralTypes ? ts.sameMap(candidates, getWidenedLiteralType) : + candidates; + // If all inferences were made from a position that implies a combined result, infer a union type. + // Otherwise, infer a common supertype. + var unwidenedType = inference.priority & 28 /* PriorityImpliesCombination */ ? + getUnionType(baseCandidates, 2 /* Subtype */) : + getCommonSupertype(baseCandidates); + return getWidenedType(unwidenedType); + } + function getInferredType(context, index) { + var inference = context.inferences[index]; + var inferredType = inference.inferredType; + if (!inferredType) { + var signature = context.signature; + if (signature) { + var inferredCovariantType = inference.candidates ? getCovariantInference(inference, signature) : undefined; + if (inference.contraCandidates) { + var inferredContravariantType = getContravariantInference(inference); + // If we have both co- and contra-variant inferences, we prefer the contra-variant inference + // unless the co-variant inference is a subtype and not 'never'. + inferredType = inferredCovariantType && !(inferredCovariantType.flags & 131072 /* Never */) && + isTypeSubtypeOf(inferredCovariantType, inferredContravariantType) ? + inferredCovariantType : inferredContravariantType; + } + else if (inferredCovariantType) { + inferredType = inferredCovariantType; + } + else if (context.flags & 1 /* NoDefault */) { + // We use silentNeverType as the wildcard that signals no inferences. + inferredType = silentNeverType; + } + else { + // Infer either the default or the empty object type when no inferences were + // made. It is important to remember that in this case, inference still + // succeeds, meaning there is no error for not having inference candidates. An + // inference error only occurs when there are *conflicting* candidates, i.e. + // candidates with no common supertype. + var defaultType = getDefaultFromTypeParameter(inference.typeParameter); + if (defaultType) { + // Instantiate the default type. Any forward reference to a type + // parameter should be instantiated to the empty object type. + inferredType = instantiateType(defaultType, combineTypeMappers(createBackreferenceMapper(context.signature.typeParameters, index), context)); + } + else { + inferredType = getDefaultTypeArgumentType(!!(context.flags & 2 /* AnyDefault */)); + } + } + } + else { + inferredType = getTypeFromInference(inference); + } + inference.inferredType = inferredType; + var constraint = getConstraintOfTypeParameter(inference.typeParameter); + if (constraint) { + var instantiatedConstraint = instantiateType(constraint, context); + if (!context.compareTypes(inferredType, getTypeWithThisArgument(instantiatedConstraint, inferredType))) { + inference.inferredType = inferredType = instantiatedConstraint; + } + } + } + return inferredType; + } + function getDefaultTypeArgumentType(isInJavaScriptFile) { + return isInJavaScriptFile ? anyType : emptyObjectType; + } + function getInferredTypes(context) { + var result = []; + for (var i = 0; i < context.inferences.length; i++) { + result.push(getInferredType(context, i)); + } + return result; + } + // EXPRESSION TYPE CHECKING + function getCannotFindNameDiagnosticForName(name) { + switch (name) { + case "document": + case "console": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom; + case "$": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_and_then_add_jquery_to_the_types_field_in_your_tsconfig; + case "describe": + case "suite": + case "it": + case "test": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha_and_then_add_jest_or_mocha_to_the_types_field_in_your_tsconfig; + case "process": + case "require": + case "Buffer": + case "module": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_and_then_add_node_to_the_types_field_in_your_tsconfig; + case "Map": + case "Set": + case "Promise": + case "Symbol": + case "WeakMap": + case "WeakSet": + case "Iterator": + case "AsyncIterator": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later; + default: return ts.Diagnostics.Cannot_find_name_0; + } + } + function getResolvedSymbol(node) { + var links = getNodeLinks(node); + if (!links.resolvedSymbol) { + links.resolvedSymbol = !ts.nodeIsMissing(node) && + resolveName(node, node.escapedText, 67220415 /* Value */ | 1048576 /* ExportValue */, getCannotFindNameDiagnosticForName(node.escapedText), node, !ts.isWriteOnlyAccess(node), + /*excludeGlobals*/ false, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1) || unknownSymbol; + } + return links.resolvedSymbol; + } + function isInTypeQuery(node) { + // TypeScript 1.0 spec (April 2014): 3.6.3 + // A type query consists of the keyword typeof followed by an expression. + // The expression is restricted to a single identifier or a sequence of identifiers separated by periods + return !!ts.findAncestor(node, function (n) { return n.kind === 167 /* TypeQuery */ ? true : n.kind === 72 /* Identifier */ || n.kind === 148 /* QualifiedName */ ? false : "quit"; }); + } + // Return the flow cache key for a "dotted name" (i.e. a sequence of identifiers + // separated by dots). The key consists of the id of the symbol referenced by the + // leftmost identifier followed by zero or more property names separated by dots. + // The result is undefined if the reference isn't a dotted name. We prefix nodes + // occurring in an apparent type position with '@' because the control flow type + // of such nodes may be based on the apparent type instead of the declared type. + function getFlowCacheKey(node) { + if (node.kind === 72 /* Identifier */) { + var symbol = getResolvedSymbol(node); + return symbol !== unknownSymbol ? (isConstraintPosition(node) ? "@" : "") + getSymbolId(symbol) : undefined; + } + if (node.kind === 100 /* ThisKeyword */) { + return "0"; + } + if (node.kind === 189 /* PropertyAccessExpression */) { + var key = getFlowCacheKey(node.expression); + return key && key + "." + ts.idText(node.name); + } + if (node.kind === 186 /* BindingElement */) { + var container = node.parent.parent; + var key = container.kind === 186 /* BindingElement */ ? getFlowCacheKey(container) : (container.initializer && getFlowCacheKey(container.initializer)); + var text = getBindingElementNameText(node); + var result = key && text && (key + "." + text); + return result; + } + return undefined; + } + function getBindingElementNameText(element) { + var parent = element.parent; + if (parent.kind === 184 /* ObjectBindingPattern */) { + var name = element.propertyName || element.name; + switch (name.kind) { + case 72 /* Identifier */: + return ts.idText(name); + case 149 /* ComputedPropertyName */: + return ts.isStringOrNumericLiteralLike(name.expression) ? name.expression.text : undefined; + case 10 /* StringLiteral */: + case 8 /* NumericLiteral */: + return name.text; + default: + // Per types, array and object binding patterns remain, however they should never be present if propertyName is not defined + ts.Debug.fail("Unexpected name kind for binding element name"); + } + } + else { + return "" + parent.elements.indexOf(element); + } + } + function isMatchingReference(source, target) { + switch (source.kind) { + case 72 /* Identifier */: + return target.kind === 72 /* Identifier */ && getResolvedSymbol(source) === getResolvedSymbol(target) || + (target.kind === 237 /* VariableDeclaration */ || target.kind === 186 /* BindingElement */) && + getExportSymbolOfValueSymbolIfExported(getResolvedSymbol(source)) === getSymbolOfNode(target); + case 100 /* ThisKeyword */: + return target.kind === 100 /* ThisKeyword */; + case 98 /* SuperKeyword */: + return target.kind === 98 /* SuperKeyword */; + case 189 /* PropertyAccessExpression */: + case 190 /* ElementAccessExpression */: + return (ts.isPropertyAccessExpression(target) || ts.isElementAccessExpression(target)) && + getAccessedPropertyName(source) === getAccessedPropertyName(target) && + isMatchingReference(source.expression, target.expression); + case 186 /* BindingElement */: + if (target.kind !== 189 /* PropertyAccessExpression */) + return false; + var t = target; + if (t.name.escapedText !== getBindingElementNameText(source)) + return false; + if (source.parent.parent.kind === 186 /* BindingElement */ && isMatchingReference(source.parent.parent, t.expression)) { + return true; + } + if (source.parent.parent.kind === 237 /* VariableDeclaration */) { + var maybeId = source.parent.parent.initializer; + return !!maybeId && isMatchingReference(maybeId, t.expression); + } + } + return false; + } + function getAccessedPropertyName(access) { + return ts.isPropertyAccessExpression(access) ? access.name.escapedText : + ts.isStringLiteral(access.argumentExpression) || ts.isNumericLiteral(access.argumentExpression) ? ts.escapeLeadingUnderscores(access.argumentExpression.text) : + undefined; + } + function containsMatchingReference(source, target) { + while (source.kind === 189 /* PropertyAccessExpression */) { + source = source.expression; + if (isMatchingReference(source, target)) { + return true; + } + } + return false; + } + // Return true if target is a property access xxx.yyy, source is a property access xxx.zzz, the declared + // type of xxx is a union type, and yyy is a property that is possibly a discriminant. We consider a property + // a possible discriminant if its type differs in the constituents of containing union type, and if every + // choice is a unit type or a union of unit types. + function containsMatchingReferenceDiscriminant(source, target) { + return target.kind === 189 /* PropertyAccessExpression */ && + containsMatchingReference(source, target.expression) && + isDiscriminantProperty(getDeclaredTypeOfReference(target.expression), target.name.escapedText); + } + function getDeclaredTypeOfReference(expr) { + if (expr.kind === 72 /* Identifier */) { + return getTypeOfSymbol(getResolvedSymbol(expr)); + } + if (expr.kind === 189 /* PropertyAccessExpression */) { + var type = getDeclaredTypeOfReference(expr.expression); + return type && getTypeOfPropertyOfType(type, expr.name.escapedText); + } + return undefined; + } + function isDiscriminantType(type) { + if (type.flags & 1048576 /* Union */) { + if (type.flags & (16 /* Boolean */ | 1024 /* EnumLiteral */)) { + return true; + } + var combined = 0; + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var t = _a[_i]; + combined |= t.flags; + } + if (combined & 109440 /* Unit */ && !(combined & 63176704 /* Instantiable */)) { + return true; + } + } + return false; + } + function isDiscriminantProperty(type, name) { + if (type && type.flags & 1048576 /* Union */) { + var prop = getUnionOrIntersectionProperty(type, name); + if (prop && ts.getCheckFlags(prop) & 2 /* SyntheticProperty */) { + if (prop.isDiscriminantProperty === undefined) { + prop.isDiscriminantProperty = !!(prop.checkFlags & 32 /* HasNonUniformType */) && isDiscriminantType(getTypeOfSymbol(prop)); + } + return !!prop.isDiscriminantProperty; + } + } + return false; + } + function hasNarrowableDeclaredType(expr) { + var type = getDeclaredTypeOfReference(expr); + return !!(type && type.flags & 1048576 /* Union */); + } + function findDiscriminantProperties(sourceProperties, target) { + var result; + for (var _i = 0, sourceProperties_2 = sourceProperties; _i < sourceProperties_2.length; _i++) { + var sourceProperty = sourceProperties_2[_i]; + if (isDiscriminantProperty(target, sourceProperty.escapedName)) { + if (result) { + result.push(sourceProperty); + continue; + } + result = [sourceProperty]; + } + } + return result; + } + function isOrContainsMatchingReference(source, target) { + return isMatchingReference(source, target) || containsMatchingReference(source, target); + } + function hasMatchingArgument(callExpression, reference) { + if (callExpression.arguments) { + for (var _i = 0, _a = callExpression.arguments; _i < _a.length; _i++) { + var argument = _a[_i]; + if (isOrContainsMatchingReference(reference, argument)) { + return true; + } + } + } + if (callExpression.expression.kind === 189 /* PropertyAccessExpression */ && + isOrContainsMatchingReference(reference, callExpression.expression.expression)) { + return true; + } + return false; + } + function getFlowNodeId(flow) { + if (!flow.id) { + flow.id = nextFlowId; + nextFlowId++; + } + return flow.id; + } + function typeMaybeAssignableTo(source, target) { + if (!(source.flags & 1048576 /* Union */)) { + return isTypeAssignableTo(source, target); + } + for (var _i = 0, _a = source.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (isTypeAssignableTo(t, target)) { + return true; + } + } + return false; + } + // Remove those constituent types of declaredType to which no constituent type of assignedType is assignable. + // For example, when a variable of type number | string | boolean is assigned a value of type number | boolean, + // we remove type string. + function getAssignmentReducedType(declaredType, assignedType) { + if (declaredType !== assignedType) { + if (assignedType.flags & 131072 /* Never */) { + return assignedType; + } + var reducedType = filterType(declaredType, function (t) { return typeMaybeAssignableTo(assignedType, t); }); + if (assignedType.flags & 512 /* BooleanLiteral */ && isFreshLiteralType(assignedType)) { + reducedType = mapType(reducedType, getFreshTypeOfLiteralType); // Ensure that if the assignment is a fresh type, that we narrow to fresh types + } + // Our crude heuristic produces an invalid result in some cases: see GH#26130. + // For now, when that happens, we give up and don't narrow at all. (This also + // means we'll never narrow for erroneous assignments where the assigned type + // is not assignable to the declared type.) + if (isTypeAssignableTo(assignedType, reducedType)) { + return reducedType; + } + } + return declaredType; + } + function getTypeFactsOfTypes(types) { + var result = 0 /* None */; + for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { + var t = types_11[_i]; + result |= getTypeFacts(t); + } + return result; + } + function isFunctionObjectType(type) { + // We do a quick check for a "bind" property before performing the more expensive subtype + // check. This gives us a quicker out in the common case where an object type is not a function. + var resolved = resolveStructuredTypeMembers(type); + return !!(resolved.callSignatures.length || resolved.constructSignatures.length || + resolved.members.get("bind") && isTypeSubtypeOf(type, globalFunctionType)); + } + function getTypeFacts(type) { + var flags = type.flags; + if (flags & 4 /* String */) { + return strictNullChecks ? 16317953 /* StringStrictFacts */ : 16776705 /* StringFacts */; + } + if (flags & 128 /* StringLiteral */) { + var isEmpty = type.value === ""; + return strictNullChecks ? + isEmpty ? 12123649 /* EmptyStringStrictFacts */ : 7929345 /* NonEmptyStringStrictFacts */ : + isEmpty ? 12582401 /* EmptyStringFacts */ : 16776705 /* NonEmptyStringFacts */; + } + if (flags & (8 /* Number */ | 32 /* Enum */)) { + return strictNullChecks ? 16317698 /* NumberStrictFacts */ : 16776450 /* NumberFacts */; + } + if (flags & 256 /* NumberLiteral */) { + var isZero = type.value === 0; + return strictNullChecks ? + isZero ? 12123394 /* ZeroNumberStrictFacts */ : 7929090 /* NonZeroNumberStrictFacts */ : + isZero ? 12582146 /* ZeroNumberFacts */ : 16776450 /* NonZeroNumberFacts */; + } + if (flags & 64 /* BigInt */) { + return strictNullChecks ? 16317188 /* BigIntStrictFacts */ : 16775940 /* BigIntFacts */; + } + if (flags & 2048 /* BigIntLiteral */) { + var isZero = isZeroBigInt(type); + return strictNullChecks ? + isZero ? 12122884 /* ZeroBigIntStrictFacts */ : 7928580 /* NonZeroBigIntStrictFacts */ : + isZero ? 12581636 /* ZeroBigIntFacts */ : 16775940 /* NonZeroBigIntFacts */; + } + if (flags & 16 /* Boolean */) { + return strictNullChecks ? 16316168 /* BooleanStrictFacts */ : 16774920 /* BooleanFacts */; + } + if (flags & 528 /* BooleanLike */) { + return strictNullChecks ? + (type === falseType || type === regularFalseType) ? 12121864 /* FalseStrictFacts */ : 7927560 /* TrueStrictFacts */ : + (type === falseType || type === regularFalseType) ? 12580616 /* FalseFacts */ : 16774920 /* TrueFacts */; + } + if (flags & 524288 /* Object */) { + return ts.getObjectFlags(type) & 16 /* Anonymous */ && isEmptyObjectType(type) ? + strictNullChecks ? 16318463 /* EmptyObjectStrictFacts */ : 16777215 /* EmptyObjectFacts */ : + isFunctionObjectType(type) ? + strictNullChecks ? 7880640 /* FunctionStrictFacts */ : 16728000 /* FunctionFacts */ : + strictNullChecks ? 7888800 /* ObjectStrictFacts */ : 16736160 /* ObjectFacts */; + } + if (flags & (16384 /* Void */ | 32768 /* Undefined */)) { + return 9830144 /* UndefinedFacts */; + } + if (flags & 65536 /* Null */) { + return 9363232 /* NullFacts */; + } + if (flags & 12288 /* ESSymbolLike */) { + return strictNullChecks ? 7925520 /* SymbolStrictFacts */ : 16772880 /* SymbolFacts */; + } + if (flags & 67108864 /* NonPrimitive */) { + return strictNullChecks ? 7888800 /* ObjectStrictFacts */ : 16736160 /* ObjectFacts */; + } + if (flags & 63176704 /* Instantiable */) { + return getTypeFacts(getBaseConstraintOfType(type) || emptyObjectType); + } + if (flags & 3145728 /* UnionOrIntersection */) { + return getTypeFactsOfTypes(type.types); + } + return 16777215 /* All */; + } + function getTypeWithFacts(type, include) { + return filterType(type, function (t) { return (getTypeFacts(t) & include) !== 0; }); + } + function getTypeWithDefault(type, defaultExpression) { + if (defaultExpression) { + var defaultType = getTypeOfExpression(defaultExpression); + return getUnionType([getTypeWithFacts(type, 524288 /* NEUndefined */), defaultType]); + } + return type; + } + function getTypeOfDestructuredProperty(type, name) { + var text = ts.getTextOfPropertyName(name); + return getConstraintForLocation(getTypeOfPropertyOfType(type, text), name) || + isNumericLiteralName(text) && getIndexTypeOfType(type, 1 /* Number */) || + getIndexTypeOfType(type, 0 /* String */) || + errorType; + } + function getTypeOfDestructuredArrayElement(type, index) { + return everyType(type, isTupleLikeType) && getTupleElementType(type, index) || + checkIteratedTypeOrElementType(type, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterables*/ false) || + errorType; + } + function getTypeOfDestructuredSpreadExpression(type) { + return createArrayType(checkIteratedTypeOrElementType(type, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterables*/ false) || errorType); + } + function getAssignedTypeOfBinaryExpression(node) { + var isDestructuringDefaultAssignment = node.parent.kind === 187 /* ArrayLiteralExpression */ && isDestructuringAssignmentTarget(node.parent) || + node.parent.kind === 275 /* PropertyAssignment */ && isDestructuringAssignmentTarget(node.parent.parent); + return isDestructuringDefaultAssignment ? + getTypeWithDefault(getAssignedType(node), node.right) : + getTypeOfExpression(node.right); + } + function isDestructuringAssignmentTarget(parent) { + return parent.parent.kind === 204 /* BinaryExpression */ && parent.parent.left === parent || + parent.parent.kind === 227 /* ForOfStatement */ && parent.parent.initializer === parent; + } + function getAssignedTypeOfArrayLiteralElement(node, element) { + return getTypeOfDestructuredArrayElement(getAssignedType(node), node.elements.indexOf(element)); + } + function getAssignedTypeOfSpreadExpression(node) { + return getTypeOfDestructuredSpreadExpression(getAssignedType(node.parent)); + } + function getAssignedTypeOfPropertyAssignment(node) { + return getTypeOfDestructuredProperty(getAssignedType(node.parent), node.name); + } + function getAssignedTypeOfShorthandPropertyAssignment(node) { + return getTypeWithDefault(getAssignedTypeOfPropertyAssignment(node), node.objectAssignmentInitializer); + } + function getAssignedType(node) { + var parent = node.parent; + switch (parent.kind) { + case 226 /* ForInStatement */: + return stringType; + case 227 /* ForOfStatement */: + return checkRightHandSideOfForOf(parent.expression, parent.awaitModifier) || errorType; + case 204 /* BinaryExpression */: + return getAssignedTypeOfBinaryExpression(parent); + case 198 /* DeleteExpression */: + return undefinedType; + case 187 /* ArrayLiteralExpression */: + return getAssignedTypeOfArrayLiteralElement(parent, node); + case 208 /* SpreadElement */: + return getAssignedTypeOfSpreadExpression(parent); + case 275 /* PropertyAssignment */: + return getAssignedTypeOfPropertyAssignment(parent); + case 276 /* ShorthandPropertyAssignment */: + return getAssignedTypeOfShorthandPropertyAssignment(parent); + } + return errorType; + } + function getInitialTypeOfBindingElement(node) { + var pattern = node.parent; + var parentType = getInitialType(pattern.parent); + var type = pattern.kind === 184 /* ObjectBindingPattern */ ? + getTypeOfDestructuredProperty(parentType, node.propertyName || node.name) : + !node.dotDotDotToken ? + getTypeOfDestructuredArrayElement(parentType, pattern.elements.indexOf(node)) : + getTypeOfDestructuredSpreadExpression(parentType); + return getTypeWithDefault(type, node.initializer); + } + function getTypeOfInitializer(node) { + // Return the cached type if one is available. If the type of the variable was inferred + // from its initializer, we'll already have cached the type. Otherwise we compute it now + // without caching such that transient types are reflected. + var links = getNodeLinks(node); + return links.resolvedType || getTypeOfExpression(node); + } + function getInitialTypeOfVariableDeclaration(node) { + if (node.initializer) { + return getTypeOfInitializer(node.initializer); + } + if (node.parent.parent.kind === 226 /* ForInStatement */) { + return stringType; + } + if (node.parent.parent.kind === 227 /* ForOfStatement */) { + return checkRightHandSideOfForOf(node.parent.parent.expression, node.parent.parent.awaitModifier) || errorType; + } + return errorType; + } + function getInitialType(node) { + return node.kind === 237 /* VariableDeclaration */ ? + getInitialTypeOfVariableDeclaration(node) : + getInitialTypeOfBindingElement(node); + } + function getInitialOrAssignedType(node, reference) { + return getConstraintForLocation(node.kind === 237 /* VariableDeclaration */ || node.kind === 186 /* BindingElement */ ? + getInitialType(node) : + getAssignedType(node), reference); + } + function isEmptyArrayAssignment(node) { + return node.kind === 237 /* VariableDeclaration */ && node.initializer && + isEmptyArrayLiteral(node.initializer) || + node.kind !== 186 /* BindingElement */ && node.parent.kind === 204 /* BinaryExpression */ && + isEmptyArrayLiteral(node.parent.right); + } + function getReferenceCandidate(node) { + switch (node.kind) { + case 195 /* ParenthesizedExpression */: + return getReferenceCandidate(node.expression); + case 204 /* BinaryExpression */: + switch (node.operatorToken.kind) { + case 59 /* EqualsToken */: + return getReferenceCandidate(node.left); + case 27 /* CommaToken */: + return getReferenceCandidate(node.right); + } + } + return node; + } + function getReferenceRoot(node) { + var parent = node.parent; + return parent.kind === 195 /* ParenthesizedExpression */ || + parent.kind === 204 /* BinaryExpression */ && parent.operatorToken.kind === 59 /* EqualsToken */ && parent.left === node || + parent.kind === 204 /* BinaryExpression */ && parent.operatorToken.kind === 27 /* CommaToken */ && parent.right === node ? + getReferenceRoot(parent) : node; + } + function getTypeOfSwitchClause(clause) { + if (clause.kind === 271 /* CaseClause */) { + return getRegularTypeOfLiteralType(getTypeOfExpression(clause.expression)); + } + return neverType; + } + function getSwitchClauseTypes(switchStatement) { + var links = getNodeLinks(switchStatement); + if (!links.switchTypes) { + links.switchTypes = []; + for (var _i = 0, _a = switchStatement.caseBlock.clauses; _i < _a.length; _i++) { + var clause = _a[_i]; + links.switchTypes.push(getTypeOfSwitchClause(clause)); + } + } + return links.switchTypes; + } + // Get the types from all cases in a switch on `typeof`. An + // `undefined` element denotes an explicit `default` clause. + function getSwitchClauseTypeOfWitnesses(switchStatement) { + var witnesses = []; + for (var _i = 0, _a = switchStatement.caseBlock.clauses; _i < _a.length; _i++) { + var clause = _a[_i]; + if (clause.kind === 271 /* CaseClause */) { + if (clause.expression.kind === 10 /* StringLiteral */) { + witnesses.push(clause.expression.text); + continue; + } + return ts.emptyArray; + } + witnesses.push(/*explicitDefaultStatement*/ undefined); + } + return witnesses; + } + function eachTypeContainedIn(source, types) { + return source.flags & 1048576 /* Union */ ? !ts.forEach(source.types, function (t) { return !ts.contains(types, t); }) : ts.contains(types, source); + } + function isTypeSubsetOf(source, target) { + return source === target || target.flags & 1048576 /* Union */ && isTypeSubsetOfUnion(source, target); + } + function isTypeSubsetOfUnion(source, target) { + if (source.flags & 1048576 /* Union */) { + for (var _i = 0, _a = source.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (!containsType(target.types, t)) { + return false; + } + } + return true; + } + if (source.flags & 1024 /* EnumLiteral */ && getBaseTypeOfEnumLiteralType(source) === target) { + return true; + } + return containsType(target.types, source); + } + function forEachType(type, f) { + return type.flags & 1048576 /* Union */ ? ts.forEach(type.types, f) : f(type); + } + function everyType(type, f) { + return type.flags & 1048576 /* Union */ ? ts.every(type.types, f) : f(type); + } + function filterType(type, f) { + if (type.flags & 1048576 /* Union */) { + var types = type.types; + var filtered = ts.filter(types, f); + return filtered === types ? type : getUnionTypeFromSortedList(filtered, type.primitiveTypesOnly); + } + return f(type) ? type : neverType; + } + function mapType(type, mapper, noReductions) { + if (type.flags & 131072 /* Never */) { + return type; + } + if (!(type.flags & 1048576 /* Union */)) { + return mapper(type); + } + var types = type.types; + var mappedType; + var mappedTypes; + for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { + var current = types_12[_i]; + var t = mapper(current); + if (t) { + if (!mappedType) { + mappedType = t; + } + else if (!mappedTypes) { + mappedTypes = [mappedType, t]; + } + else { + mappedTypes.push(t); + } + } + } + return mappedTypes ? getUnionType(mappedTypes, noReductions ? 0 /* None */ : 1 /* Literal */) : mappedType; + } + function extractTypesOfKind(type, kind) { + return filterType(type, function (t) { return (t.flags & kind) !== 0; }); + } + // Return a new type in which occurrences of the string and number primitive types in + // typeWithPrimitives have been replaced with occurrences of string literals and numeric + // literals in typeWithLiterals, respectively. + function replacePrimitivesWithLiterals(typeWithPrimitives, typeWithLiterals) { + if (isTypeSubsetOf(stringType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 128 /* StringLiteral */) || + isTypeSubsetOf(numberType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 256 /* NumberLiteral */) || + isTypeSubsetOf(bigintType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 2048 /* BigIntLiteral */)) { + return mapType(typeWithPrimitives, function (t) { + return t.flags & 4 /* String */ ? extractTypesOfKind(typeWithLiterals, 4 /* String */ | 128 /* StringLiteral */) : + t.flags & 8 /* Number */ ? extractTypesOfKind(typeWithLiterals, 8 /* Number */ | 256 /* NumberLiteral */) : + t.flags & 64 /* BigInt */ ? extractTypesOfKind(typeWithLiterals, 64 /* BigInt */ | 2048 /* BigIntLiteral */) : + t; + }); + } + return typeWithPrimitives; + } + function isIncomplete(flowType) { + return flowType.flags === 0; + } + function getTypeFromFlowType(flowType) { + return flowType.flags === 0 ? flowType.type : flowType; + } + function createFlowType(type, incomplete) { + return incomplete ? { flags: 0, type: type } : type; + } + // An evolving array type tracks the element types that have so far been seen in an + // 'x.push(value)' or 'x[n] = value' operation along the control flow graph. Evolving + // array types are ultimately converted into manifest array types (using getFinalArrayType) + // and never escape the getFlowTypeOfReference function. + function createEvolvingArrayType(elementType) { + var result = createObjectType(256 /* EvolvingArray */); + result.elementType = elementType; + return result; + } + function getEvolvingArrayType(elementType) { + return evolvingArrayTypes[elementType.id] || (evolvingArrayTypes[elementType.id] = createEvolvingArrayType(elementType)); + } + // When adding evolving array element types we do not perform subtype reduction. Instead, + // we defer subtype reduction until the evolving array type is finalized into a manifest + // array type. + function addEvolvingArrayElementType(evolvingArrayType, node) { + var elementType = getBaseTypeOfLiteralType(getContextFreeTypeOfExpression(node)); + return isTypeSubsetOf(elementType, evolvingArrayType.elementType) ? evolvingArrayType : getEvolvingArrayType(getUnionType([evolvingArrayType.elementType, elementType])); + } + function createFinalArrayType(elementType) { + return elementType.flags & 131072 /* Never */ ? + autoArrayType : + createArrayType(elementType.flags & 1048576 /* Union */ ? + getUnionType(elementType.types, 2 /* Subtype */) : + elementType); + } + // We perform subtype reduction upon obtaining the final array type from an evolving array type. + function getFinalArrayType(evolvingArrayType) { + return evolvingArrayType.finalArrayType || (evolvingArrayType.finalArrayType = createFinalArrayType(evolvingArrayType.elementType)); + } + function finalizeEvolvingArrayType(type) { + return ts.getObjectFlags(type) & 256 /* EvolvingArray */ ? getFinalArrayType(type) : type; + } + function getElementTypeOfEvolvingArrayType(type) { + return ts.getObjectFlags(type) & 256 /* EvolvingArray */ ? type.elementType : neverType; + } + function isEvolvingArrayTypeList(types) { + var hasEvolvingArrayType = false; + for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { + var t = types_13[_i]; + if (!(t.flags & 131072 /* Never */)) { + if (!(ts.getObjectFlags(t) & 256 /* EvolvingArray */)) { + return false; + } + hasEvolvingArrayType = true; + } + } + return hasEvolvingArrayType; + } + // At flow control branch or loop junctions, if the type along every antecedent code path + // is an evolving array type, we construct a combined evolving array type. Otherwise we + // finalize all evolving array types. + function getUnionOrEvolvingArrayType(types, subtypeReduction) { + return isEvolvingArrayTypeList(types) ? + getEvolvingArrayType(getUnionType(ts.map(types, getElementTypeOfEvolvingArrayType))) : + getUnionType(ts.sameMap(types, finalizeEvolvingArrayType), subtypeReduction); + } + // Return true if the given node is 'x' in an 'x.length', x.push(value)', 'x.unshift(value)' or + // 'x[n] = value' operation, where 'n' is an expression of type any, undefined, or a number-like type. + function isEvolvingArrayOperationTarget(node) { + var root = getReferenceRoot(node); + var parent = root.parent; + var isLengthPushOrUnshift = parent.kind === 189 /* PropertyAccessExpression */ && (parent.name.escapedText === "length" || + parent.parent.kind === 191 /* CallExpression */ && ts.isPushOrUnshiftIdentifier(parent.name)); + var isElementAssignment = parent.kind === 190 /* ElementAccessExpression */ && + parent.expression === root && + parent.parent.kind === 204 /* BinaryExpression */ && + parent.parent.operatorToken.kind === 59 /* EqualsToken */ && + parent.parent.left === parent && + !ts.isAssignmentTarget(parent.parent) && + isTypeAssignableToKind(getTypeOfExpression(parent.argumentExpression), 296 /* NumberLike */); + return isLengthPushOrUnshift || isElementAssignment; + } + function maybeTypePredicateCall(node) { + var links = getNodeLinks(node); + if (links.maybeTypePredicate === undefined) { + links.maybeTypePredicate = getMaybeTypePredicate(node); + } + return links.maybeTypePredicate; + } + function getMaybeTypePredicate(node) { + if (node.expression.kind !== 98 /* SuperKeyword */) { + var funcType = checkNonNullExpression(node.expression); + if (funcType !== silentNeverType) { + var apparentType = getApparentType(funcType); + return apparentType !== errorType && ts.some(getSignaturesOfType(apparentType, 0 /* Call */), signatureHasTypePredicate); + } + } + return false; + } + function reportFlowControlError(node) { + var block = ts.findAncestor(node, ts.isFunctionOrModuleBlock); + var sourceFile = ts.getSourceFileOfNode(node); + var span = ts.getSpanOfTokenAtPosition(sourceFile, block.statements.pos); + diagnostics.add(ts.createFileDiagnostic(sourceFile, span.start, span.length, ts.Diagnostics.The_containing_function_or_module_body_is_too_large_for_control_flow_analysis)); + } + function getFlowTypeOfReference(reference, declaredType, initialType, flowContainer, couldBeUninitialized) { + if (initialType === void 0) { initialType = declaredType; } + var key; + var flowDepth = 0; + if (flowAnalysisDisabled) { + return errorType; + } + if (!reference.flowNode || !couldBeUninitialized && !(declaredType.flags & 133970943 /* Narrowable */)) { + return declaredType; + } + var sharedFlowStart = sharedFlowCount; + var evolvedType = getTypeFromFlowType(getTypeAtFlowNode(reference.flowNode)); + sharedFlowCount = sharedFlowStart; + // When the reference is 'x' in an 'x.length', 'x.push(value)', 'x.unshift(value)' or x[n] = value' operation, + // we give type 'any[]' to 'x' instead of using the type determined by control flow analysis such that operations + // on empty arrays are possible without implicit any errors and new element types can be inferred without + // type mismatch errors. + var resultType = ts.getObjectFlags(evolvedType) & 256 /* EvolvingArray */ && isEvolvingArrayOperationTarget(reference) ? autoArrayType : finalizeEvolvingArrayType(evolvedType); + if (reference.parent && reference.parent.kind === 213 /* NonNullExpression */ && getTypeWithFacts(resultType, 2097152 /* NEUndefinedOrNull */).flags & 131072 /* Never */) { + return declaredType; + } + return resultType; + function getTypeAtFlowNode(flow) { + if (flowDepth === 2000) { + // We have made 2000 recursive invocations. To avoid overflowing the call stack we report an error + // and disable further control flow analysis in the containing function or module body. + flowAnalysisDisabled = true; + reportFlowControlError(reference); + return errorType; + } + flowDepth++; + while (true) { + var flags = flow.flags; + if (flags & 1024 /* Shared */) { + // We cache results of flow type resolution for shared nodes that were previously visited in + // the same getFlowTypeOfReference invocation. A node is considered shared when it is the + // antecedent of more than one node. + for (var i = sharedFlowStart; i < sharedFlowCount; i++) { + if (sharedFlowNodes[i] === flow) { + flowDepth--; + return sharedFlowTypes[i]; + } + } + } + var type = void 0; + if (flags & 4096 /* AfterFinally */) { + // block flow edge: finally -> pre-try (for larger explanation check comment in binder.ts - bindTryStatement + flow.locked = true; + type = getTypeAtFlowNode(flow.antecedent); + flow.locked = false; + } + else if (flags & 2048 /* PreFinally */) { + // locked pre-finally flows are filtered out in getTypeAtFlowBranchLabel + // so here just redirect to antecedent + flow = flow.antecedent; + continue; + } + else if (flags & 16 /* Assignment */) { + type = getTypeAtFlowAssignment(flow); + if (!type) { + flow = flow.antecedent; + continue; + } + } + else if (flags & 96 /* Condition */) { + type = getTypeAtFlowCondition(flow); + } + else if (flags & 128 /* SwitchClause */) { + type = getTypeAtSwitchClause(flow); + } + else if (flags & 12 /* Label */) { + if (flow.antecedents.length === 1) { + flow = flow.antecedents[0]; + continue; + } + type = flags & 4 /* BranchLabel */ ? + getTypeAtFlowBranchLabel(flow) : + getTypeAtFlowLoopLabel(flow); + } + else if (flags & 256 /* ArrayMutation */) { + type = getTypeAtFlowArrayMutation(flow); + if (!type) { + flow = flow.antecedent; + continue; + } + } + else if (flags & 2 /* Start */) { + // Check if we should continue with the control flow of the containing function. + var container = flow.container; + if (container && container !== flowContainer && + reference.kind !== 189 /* PropertyAccessExpression */ && + reference.kind !== 190 /* ElementAccessExpression */ && + reference.kind !== 100 /* ThisKeyword */) { + flow = container.flowNode; + continue; + } + // At the top of the flow we have the initial type. + type = initialType; + } + else { + // Unreachable code errors are reported in the binding phase. Here we + // simply return the non-auto declared type to reduce follow-on errors. + type = convertAutoToAny(declaredType); + } + if (flags & 1024 /* Shared */) { + // Record visited node and the associated type in the cache. + sharedFlowNodes[sharedFlowCount] = flow; + sharedFlowTypes[sharedFlowCount] = type; + sharedFlowCount++; + } + flowDepth--; + return type; + } + } + function getTypeAtFlowAssignment(flow) { + var node = flow.node; + // Assignments only narrow the computed type if the declared type is a union type. Thus, we + // only need to evaluate the assigned type if the declared type is a union type. + if (isMatchingReference(reference, node)) { + if (ts.getAssignmentTargetKind(node) === 2 /* Compound */) { + var flowType = getTypeAtFlowNode(flow.antecedent); + return createFlowType(getBaseTypeOfLiteralType(getTypeFromFlowType(flowType)), isIncomplete(flowType)); + } + if (declaredType === autoType || declaredType === autoArrayType) { + if (isEmptyArrayAssignment(node)) { + return getEvolvingArrayType(neverType); + } + var assignedType = getBaseTypeOfLiteralType(getInitialOrAssignedType(node, reference)); + return isTypeAssignableTo(assignedType, declaredType) ? assignedType : anyArrayType; + } + if (declaredType.flags & 1048576 /* Union */) { + return getAssignmentReducedType(declaredType, getInitialOrAssignedType(node, reference)); + } + return declaredType; + } + // We didn't have a direct match. However, if the reference is a dotted name, this + // may be an assignment to a left hand part of the reference. For example, for a + // reference 'x.y.z', we may be at an assignment to 'x.y' or 'x'. In that case, + // return the declared type. + if (containsMatchingReference(reference, node)) { + // A matching dotted name might also be an expando property on a function *expression*, + // in which case we continue control flow analysis back to the function's declaration + if (ts.isVariableDeclaration(node) && (ts.isInJSFile(node) || ts.isVarConst(node))) { + var init = ts.getDeclaredExpandoInitializer(node); + if (init && (init.kind === 196 /* FunctionExpression */ || init.kind === 197 /* ArrowFunction */)) { + return getTypeAtFlowNode(flow.antecedent); + } + } + return declaredType; + } + // for (const _ in ref) acts as a nonnull on ref + if (ts.isVariableDeclaration(node) && node.parent.parent.kind === 226 /* ForInStatement */ && isMatchingReference(reference, node.parent.parent.expression)) { + return getNonNullableTypeIfNeeded(getTypeFromFlowType(getTypeAtFlowNode(flow.antecedent))); + } + // Assignment doesn't affect reference + return undefined; + } + function getTypeAtFlowArrayMutation(flow) { + if (declaredType === autoType || declaredType === autoArrayType) { + var node = flow.node; + var expr = node.kind === 191 /* CallExpression */ ? + node.expression.expression : + node.left.expression; + if (isMatchingReference(reference, getReferenceCandidate(expr))) { + var flowType = getTypeAtFlowNode(flow.antecedent); + var type = getTypeFromFlowType(flowType); + if (ts.getObjectFlags(type) & 256 /* EvolvingArray */) { + var evolvedType_1 = type; + if (node.kind === 191 /* CallExpression */) { + for (var _i = 0, _a = node.arguments; _i < _a.length; _i++) { + var arg = _a[_i]; + evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, arg); + } + } + else { + // We must get the context free expression type so as to not recur in an uncached fashion on the LHS (which causes exponential blowup in compile time) + var indexType = getContextFreeTypeOfExpression(node.left.argumentExpression); + if (isTypeAssignableToKind(indexType, 296 /* NumberLike */)) { + evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, node.right); + } + } + return evolvedType_1 === type ? flowType : createFlowType(evolvedType_1, isIncomplete(flowType)); + } + return flowType; + } + } + return undefined; + } + function getTypeAtFlowCondition(flow) { + var flowType = getTypeAtFlowNode(flow.antecedent); + var type = getTypeFromFlowType(flowType); + if (type.flags & 131072 /* Never */) { + return flowType; + } + // If we have an antecedent type (meaning we're reachable in some way), we first + // attempt to narrow the antecedent type. If that produces the never type, and if + // the antecedent type is incomplete (i.e. a transient type in a loop), then we + // take the type guard as an indication that control *could* reach here once we + // have the complete type. We proceed by switching to the silent never type which + // doesn't report errors when operators are applied to it. Note that this is the + // *only* place a silent never type is ever generated. + var assumeTrue = (flow.flags & 32 /* TrueCondition */) !== 0; + var nonEvolvingType = finalizeEvolvingArrayType(type); + var narrowedType = narrowType(nonEvolvingType, flow.expression, assumeTrue); + if (narrowedType === nonEvolvingType) { + return flowType; + } + var incomplete = isIncomplete(flowType); + var resultType = incomplete && narrowedType.flags & 131072 /* Never */ ? silentNeverType : narrowedType; + return createFlowType(resultType, incomplete); + } + function getTypeAtSwitchClause(flow) { + var expr = flow.switchStatement.expression; + if (containsMatchingReferenceDiscriminant(reference, expr)) { + return declaredType; + } + var flowType = getTypeAtFlowNode(flow.antecedent); + var type = getTypeFromFlowType(flowType); + if (isMatchingReference(reference, expr)) { + type = narrowTypeBySwitchOnDiscriminant(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); + } + else if (isMatchingReferenceDiscriminant(expr, type)) { + type = narrowTypeByDiscriminant(type, expr, function (t) { return narrowTypeBySwitchOnDiscriminant(t, flow.switchStatement, flow.clauseStart, flow.clauseEnd); }); + } + else if (expr.kind === 199 /* TypeOfExpression */ && isMatchingReference(reference, expr.expression)) { + type = narrowBySwitchOnTypeOf(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); + } + return createFlowType(type, isIncomplete(flowType)); + } + function getTypeAtFlowBranchLabel(flow) { + var antecedentTypes = []; + var subtypeReduction = false; + var seenIncomplete = false; + for (var _i = 0, _a = flow.antecedents; _i < _a.length; _i++) { + var antecedent = _a[_i]; + if (antecedent.flags & 2048 /* PreFinally */ && antecedent.lock.locked) { + // if flow correspond to branch from pre-try to finally and this branch is locked - this means that + // we initially have started following the flow outside the finally block. + // in this case we should ignore this branch. + continue; + } + var flowType = getTypeAtFlowNode(antecedent); + var type = getTypeFromFlowType(flowType); + // If the type at a particular antecedent path is the declared type and the + // reference is known to always be assigned (i.e. when declared and initial types + // are the same), there is no reason to process more antecedents since the only + // possible outcome is subtypes that will be removed in the final union type anyway. + if (type === declaredType && declaredType === initialType) { + return type; + } + ts.pushIfUnique(antecedentTypes, type); + // If an antecedent type is not a subset of the declared type, we need to perform + // subtype reduction. This happens when a "foreign" type is injected into the control + // flow using the instanceof operator or a user defined type predicate. + if (!isTypeSubsetOf(type, declaredType)) { + subtypeReduction = true; + } + if (isIncomplete(flowType)) { + seenIncomplete = true; + } + } + return createFlowType(getUnionOrEvolvingArrayType(antecedentTypes, subtypeReduction ? 2 /* Subtype */ : 1 /* Literal */), seenIncomplete); + } + function getTypeAtFlowLoopLabel(flow) { + // If we have previously computed the control flow type for the reference at + // this flow loop junction, return the cached type. + var id = getFlowNodeId(flow); + var cache = flowLoopCaches[id] || (flowLoopCaches[id] = ts.createMap()); + if (!key) { + key = getFlowCacheKey(reference); + // No cache key is generated when binding patterns are in unnarrowable situations + if (!key) { + return declaredType; + } + } + var cached = cache.get(key); + if (cached) { + return cached; + } + // If this flow loop junction and reference are already being processed, return + // the union of the types computed for each branch so far, marked as incomplete. + // It is possible to see an empty array in cases where loops are nested and the + // back edge of the outer loop reaches an inner loop that is already being analyzed. + // In such cases we restart the analysis of the inner loop, which will then see + // a non-empty in-process array for the outer loop and eventually terminate because + // the first antecedent of a loop junction is always the non-looping control flow + // path that leads to the top. + for (var i = flowLoopStart; i < flowLoopCount; i++) { + if (flowLoopNodes[i] === flow && flowLoopKeys[i] === key && flowLoopTypes[i].length) { + return createFlowType(getUnionOrEvolvingArrayType(flowLoopTypes[i], 1 /* Literal */), /*incomplete*/ true); + } + } + // Add the flow loop junction and reference to the in-process stack and analyze + // each antecedent code path. + var antecedentTypes = []; + var subtypeReduction = false; + var firstAntecedentType; + flowLoopNodes[flowLoopCount] = flow; + flowLoopKeys[flowLoopCount] = key; + flowLoopTypes[flowLoopCount] = antecedentTypes; + for (var _i = 0, _a = flow.antecedents; _i < _a.length; _i++) { + var antecedent = _a[_i]; + flowLoopCount++; + var flowType = getTypeAtFlowNode(antecedent); + flowLoopCount--; + if (!firstAntecedentType) { + firstAntecedentType = flowType; + } + var type = getTypeFromFlowType(flowType); + // If we see a value appear in the cache it is a sign that control flow analysis + // was restarted and completed by checkExpressionCached. We can simply pick up + // the resulting type and bail out. + var cached_1 = cache.get(key); + if (cached_1) { + return cached_1; + } + ts.pushIfUnique(antecedentTypes, type); + // If an antecedent type is not a subset of the declared type, we need to perform + // subtype reduction. This happens when a "foreign" type is injected into the control + // flow using the instanceof operator or a user defined type predicate. + if (!isTypeSubsetOf(type, declaredType)) { + subtypeReduction = true; + } + // If the type at a particular antecedent path is the declared type there is no + // reason to process more antecedents since the only possible outcome is subtypes + // that will be removed in the final union type anyway. + if (type === declaredType) { + break; + } + } + // The result is incomplete if the first antecedent (the non-looping control flow path) + // is incomplete. + var result = getUnionOrEvolvingArrayType(antecedentTypes, subtypeReduction ? 2 /* Subtype */ : 1 /* Literal */); + if (isIncomplete(firstAntecedentType)) { + return createFlowType(result, /*incomplete*/ true); + } + cache.set(key, result); + return result; + } + function isMatchingReferenceDiscriminant(expr, computedType) { + if (!(computedType.flags & 1048576 /* Union */) || + expr.kind !== 189 /* PropertyAccessExpression */ && expr.kind !== 190 /* ElementAccessExpression */) { + return false; + } + var access = expr; + var name = getAccessedPropertyName(access); + if (!name) { + return false; + } + return isMatchingReference(reference, access.expression) && isDiscriminantProperty(computedType, name); + } + function narrowTypeByDiscriminant(type, access, narrowType) { + var propName = getAccessedPropertyName(access); + if (!propName) { + return type; + } + var propType = getTypeOfPropertyOfType(type, propName); + var narrowedPropType = propType && narrowType(propType); + return propType === narrowedPropType ? type : filterType(type, function (t) { return isTypeComparableTo(getTypeOfPropertyOfType(t, propName), narrowedPropType); }); + } + function narrowTypeByTruthiness(type, expr, assumeTrue) { + if (isMatchingReference(reference, expr)) { + return getTypeWithFacts(type, assumeTrue ? 4194304 /* Truthy */ : 8388608 /* Falsy */); + } + if (isMatchingReferenceDiscriminant(expr, declaredType)) { + return narrowTypeByDiscriminant(type, expr, function (t) { return getTypeWithFacts(t, assumeTrue ? 4194304 /* Truthy */ : 8388608 /* Falsy */); }); + } + if (containsMatchingReferenceDiscriminant(reference, expr)) { + return declaredType; + } + return type; + } + function isTypePresencePossible(type, propName, assumeTrue) { + if (getIndexInfoOfType(type, 0 /* String */)) { + return true; + } + var prop = getPropertyOfType(type, propName); + if (prop) { + return prop.flags & 16777216 /* Optional */ ? true : assumeTrue; + } + return !assumeTrue; + } + function narrowByInKeyword(type, literal, assumeTrue) { + if ((type.flags & (1048576 /* Union */ | 524288 /* Object */)) || (type.flags & 262144 /* TypeParameter */ && type.isThisType)) { + var propName_1 = ts.escapeLeadingUnderscores(literal.text); + return filterType(type, function (t) { return isTypePresencePossible(t, propName_1, assumeTrue); }); + } + return type; + } + function narrowTypeByBinaryExpression(type, expr, assumeTrue) { + switch (expr.operatorToken.kind) { + case 59 /* EqualsToken */: + return narrowTypeByTruthiness(type, expr.left, assumeTrue); + case 33 /* EqualsEqualsToken */: + case 34 /* ExclamationEqualsToken */: + case 35 /* EqualsEqualsEqualsToken */: + case 36 /* ExclamationEqualsEqualsToken */: + var operator_1 = expr.operatorToken.kind; + var left_1 = getReferenceCandidate(expr.left); + var right_1 = getReferenceCandidate(expr.right); + if (left_1.kind === 199 /* TypeOfExpression */ && ts.isStringLiteralLike(right_1)) { + return narrowTypeByTypeof(type, left_1, operator_1, right_1, assumeTrue); + } + if (right_1.kind === 199 /* TypeOfExpression */ && ts.isStringLiteralLike(left_1)) { + return narrowTypeByTypeof(type, right_1, operator_1, left_1, assumeTrue); + } + if (isMatchingReference(reference, left_1)) { + return narrowTypeByEquality(type, operator_1, right_1, assumeTrue); + } + if (isMatchingReference(reference, right_1)) { + return narrowTypeByEquality(type, operator_1, left_1, assumeTrue); + } + if (isMatchingReferenceDiscriminant(left_1, declaredType)) { + return narrowTypeByDiscriminant(type, left_1, function (t) { return narrowTypeByEquality(t, operator_1, right_1, assumeTrue); }); + } + if (isMatchingReferenceDiscriminant(right_1, declaredType)) { + return narrowTypeByDiscriminant(type, right_1, function (t) { return narrowTypeByEquality(t, operator_1, left_1, assumeTrue); }); + } + if (containsMatchingReferenceDiscriminant(reference, left_1) || containsMatchingReferenceDiscriminant(reference, right_1)) { + return declaredType; + } + break; + case 94 /* InstanceOfKeyword */: + return narrowTypeByInstanceof(type, expr, assumeTrue); + case 93 /* InKeyword */: + var target = getReferenceCandidate(expr.right); + if (ts.isStringLiteralLike(expr.left) && isMatchingReference(reference, target)) { + return narrowByInKeyword(type, expr.left, assumeTrue); + } + break; + case 27 /* CommaToken */: + return narrowType(type, expr.right, assumeTrue); + } + return type; + } + function narrowTypeByEquality(type, operator, value, assumeTrue) { + if (type.flags & 1 /* Any */) { + return type; + } + if (operator === 34 /* ExclamationEqualsToken */ || operator === 36 /* ExclamationEqualsEqualsToken */) { + assumeTrue = !assumeTrue; + } + var valueType = getTypeOfExpression(value); + if (valueType.flags & 98304 /* Nullable */) { + if (!strictNullChecks) { + return type; + } + var doubleEquals = operator === 33 /* EqualsEqualsToken */ || operator === 34 /* ExclamationEqualsToken */; + var facts = doubleEquals ? + assumeTrue ? 262144 /* EQUndefinedOrNull */ : 2097152 /* NEUndefinedOrNull */ : + valueType.flags & 65536 /* Null */ ? + assumeTrue ? 131072 /* EQNull */ : 1048576 /* NENull */ : + assumeTrue ? 65536 /* EQUndefined */ : 524288 /* NEUndefined */; + return getTypeWithFacts(type, facts); + } + if (type.flags & 67637251 /* NotUnionOrUnit */) { + return type; + } + if (assumeTrue) { + var narrowedType = filterType(type, function (t) { return areTypesComparable(t, valueType); }); + return narrowedType.flags & 131072 /* Never */ ? type : replacePrimitivesWithLiterals(narrowedType, valueType); + } + if (isUnitType(valueType)) { + var regularType_1 = getRegularTypeOfLiteralType(valueType); + return filterType(type, function (t) { return getRegularTypeOfLiteralType(t) !== regularType_1; }); + } + return type; + } + function narrowTypeByTypeof(type, typeOfExpr, operator, literal, assumeTrue) { + // We have '==', '!=', '====', or !==' operator with 'typeof xxx' and string literal operands + var target = getReferenceCandidate(typeOfExpr.expression); + if (!isMatchingReference(reference, target)) { + // For a reference of the form 'x.y', where 'x' has a narrowable declared type, a + // 'typeof x === ...' type guard resets the narrowed type of 'y' to its declared type. + if (containsMatchingReference(reference, target) && hasNarrowableDeclaredType(target)) { + return declaredType; + } + return type; + } + if (operator === 34 /* ExclamationEqualsToken */ || operator === 36 /* ExclamationEqualsEqualsToken */) { + assumeTrue = !assumeTrue; + } + if (type.flags & 1 /* Any */ && literal.text === "function") { + return type; + } + var facts = assumeTrue ? + typeofEQFacts.get(literal.text) || 128 /* TypeofEQHostObject */ : + typeofNEFacts.get(literal.text) || 32768 /* TypeofNEHostObject */; + return getTypeWithFacts(assumeTrue ? mapType(type, narrowTypeForTypeof) : type, facts); + function narrowTypeForTypeof(type) { + if (type.flags & 2 /* Unknown */ && literal.text === "object") { + return getUnionType([nonPrimitiveType, nullType]); + } + // We narrow a non-union type to an exact primitive type if the non-union type + // is a supertype of that primitive type. For example, type 'any' can be narrowed + // to one of the primitive types. + var targetType = literal.text === "function" ? globalFunctionType : typeofTypesByName.get(literal.text); + if (targetType) { + if (isTypeSubtypeOf(type, targetType)) { + return type; + } + if (isTypeSubtypeOf(targetType, type)) { + return targetType; + } + if (type.flags & 63176704 /* Instantiable */) { + var constraint = getBaseConstraintOfType(type) || anyType; + if (isTypeSubtypeOf(targetType, constraint)) { + return getIntersectionType([type, targetType]); + } + } + } + return type; + } + } + function narrowTypeBySwitchOnDiscriminant(type, switchStatement, clauseStart, clauseEnd) { + // We only narrow if all case expressions specify values with unit types + var switchTypes = getSwitchClauseTypes(switchStatement); + if (!switchTypes.length) { + return type; + } + var clauseTypes = switchTypes.slice(clauseStart, clauseEnd); + var hasDefaultClause = clauseStart === clauseEnd || ts.contains(clauseTypes, neverType); + var discriminantType = getUnionType(clauseTypes); + var caseType = discriminantType.flags & 131072 /* Never */ ? neverType : + replacePrimitivesWithLiterals(filterType(type, function (t) { return areTypesComparable(discriminantType, t); }), discriminantType); + if (!hasDefaultClause) { + return caseType; + } + var defaultType = filterType(type, function (t) { return !(isUnitType(t) && ts.contains(switchTypes, getRegularTypeOfLiteralType(t))); }); + return caseType.flags & 131072 /* Never */ ? defaultType : getUnionType([caseType, defaultType]); + } + function getImpliedTypeFromTypeofCase(type, text) { + switch (text) { + case "function": + return type.flags & 1 /* Any */ ? type : globalFunctionType; + case "object": + return type.flags & 2 /* Unknown */ ? getUnionType([nonPrimitiveType, nullType]) : type; + default: + return typeofTypesByName.get(text) || type; + } + } + function narrowTypeForTypeofSwitch(candidate) { + return function (type) { + if (isTypeSubtypeOf(candidate, type)) { + return candidate; + } + if (type.flags & 63176704 /* Instantiable */) { + var constraint = getBaseConstraintOfType(type) || anyType; + if (isTypeSubtypeOf(candidate, constraint)) { + return getIntersectionType([type, candidate]); + } + } + return type; + }; + } + function narrowBySwitchOnTypeOf(type, switchStatement, clauseStart, clauseEnd) { + var switchWitnesses = getSwitchClauseTypeOfWitnesses(switchStatement); + if (!switchWitnesses.length) { + return type; + } + // Equal start and end denotes implicit fallthrough; undefined marks explicit default clause + var defaultCaseLocation = ts.findIndex(switchWitnesses, function (elem) { return elem === undefined; }); + var hasDefaultClause = clauseStart === clauseEnd || (defaultCaseLocation >= clauseStart && defaultCaseLocation < clauseEnd); + var clauseWitnesses; + var switchFacts; + if (defaultCaseLocation > -1) { + // We no longer need the undefined denoting an + // explicit default case. Remove the undefined and + // fix-up clauseStart and clauseEnd. This means + // that we don't have to worry about undefined + // in the witness array. + var witnesses = switchWitnesses.filter(function (witness) { return witness !== undefined; }); + // The adjusted clause start and end after removing the `default` statement. + var fixedClauseStart = defaultCaseLocation < clauseStart ? clauseStart - 1 : clauseStart; + var fixedClauseEnd = defaultCaseLocation < clauseEnd ? clauseEnd - 1 : clauseEnd; + clauseWitnesses = witnesses.slice(fixedClauseStart, fixedClauseEnd); + switchFacts = getFactsFromTypeofSwitch(fixedClauseStart, fixedClauseEnd, witnesses, hasDefaultClause); + } + else { + clauseWitnesses = switchWitnesses.slice(clauseStart, clauseEnd); + switchFacts = getFactsFromTypeofSwitch(clauseStart, clauseEnd, switchWitnesses, hasDefaultClause); + } + if (hasDefaultClause) { + return filterType(type, function (t) { return (getTypeFacts(t) & switchFacts) === switchFacts; }); + } + /* + The implied type is the raw type suggested by a + value being caught in this clause. + + When the clause contains a default case we ignore + the implied type and try to narrow using any facts + we can learn: see `switchFacts`. + + Example: + switch (typeof x) { + case 'number': + case 'string': break; + default: break; + case 'number': + case 'boolean': break + } + + In the first clause (case `number` and `string`) the + implied type is number | string. + + In the default clause we de not compute an implied type. + + In the third clause (case `number` and `boolean`) + the naive implied type is number | boolean, however + we use the type facts to narrow the implied type to + boolean. We know that number cannot be selected + because it is caught in the first clause. + */ + var impliedType = getTypeWithFacts(getUnionType(clauseWitnesses.map(function (text) { return getImpliedTypeFromTypeofCase(type, text); })), switchFacts); + if (impliedType.flags & 1048576 /* Union */) { + impliedType = getAssignmentReducedType(impliedType, getBaseConstraintOrType(type)); + } + return getTypeWithFacts(mapType(type, narrowTypeForTypeofSwitch(impliedType)), switchFacts); + } + function narrowTypeByInstanceof(type, expr, assumeTrue) { + var left = getReferenceCandidate(expr.left); + if (!isMatchingReference(reference, left)) { + // For a reference of the form 'x.y', where 'x' has a narrowable declared type, an + // 'x instanceof T' type guard resets the narrowed type of 'y' to its declared type. + if (containsMatchingReference(reference, left) && hasNarrowableDeclaredType(left)) { + return declaredType; + } + return type; + } + // Check that right operand is a function type with a prototype property + var rightType = getTypeOfExpression(expr.right); + if (!isTypeDerivedFrom(rightType, globalFunctionType)) { + return type; + } + var targetType; + var prototypeProperty = getPropertyOfType(rightType, "prototype"); + if (prototypeProperty) { + // Target type is type of the prototype property + var prototypePropertyType = getTypeOfSymbol(prototypeProperty); + if (!isTypeAny(prototypePropertyType)) { + targetType = prototypePropertyType; + } + } + // Don't narrow from 'any' if the target type is exactly 'Object' or 'Function' + if (isTypeAny(type) && (targetType === globalObjectType || targetType === globalFunctionType)) { + return type; + } + if (!targetType) { + var constructSignatures = getSignaturesOfType(rightType, 1 /* Construct */); + targetType = constructSignatures.length ? + getUnionType(ts.map(constructSignatures, function (signature) { return getReturnTypeOfSignature(getErasedSignature(signature)); })) : + emptyObjectType; + } + return getNarrowedType(type, targetType, assumeTrue, isTypeDerivedFrom); + } + function getNarrowedType(type, candidate, assumeTrue, isRelated) { + if (!assumeTrue) { + return filterType(type, function (t) { return !isRelated(t, candidate); }); + } + // If the current type is a union type, remove all constituents that couldn't be instances of + // the candidate type. If one or more constituents remain, return a union of those. + if (type.flags & 1048576 /* Union */) { + var assignableType = filterType(type, function (t) { return isRelated(t, candidate); }); + if (!(assignableType.flags & 131072 /* Never */)) { + return assignableType; + } + } + // If the candidate type is a subtype of the target type, narrow to the candidate type. + // Otherwise, if the target type is assignable to the candidate type, keep the target type. + // Otherwise, if the candidate type is assignable to the target type, narrow to the candidate + // type. Otherwise, the types are completely unrelated, so narrow to an intersection of the + // two types. + return isTypeSubtypeOf(candidate, type) ? candidate : + isTypeAssignableTo(type, candidate) ? type : + isTypeAssignableTo(candidate, type) ? candidate : + getIntersectionType([type, candidate]); + } + function narrowTypeByTypePredicate(type, callExpression, assumeTrue) { + if (!hasMatchingArgument(callExpression, reference) || !maybeTypePredicateCall(callExpression)) { + return type; + } + var signature = getResolvedSignature(callExpression); + var predicate = getTypePredicateOfSignature(signature); + if (!predicate) { + return type; + } + // Don't narrow from 'any' if the predicate type is exactly 'Object' or 'Function' + if (isTypeAny(type) && (predicate.type === globalObjectType || predicate.type === globalFunctionType)) { + return type; + } + if (ts.isIdentifierTypePredicate(predicate)) { + var predicateArgument = callExpression.arguments[predicate.parameterIndex - (signature.thisParameter ? 1 : 0)]; + if (predicateArgument) { + if (isMatchingReference(reference, predicateArgument)) { + return getNarrowedType(type, predicate.type, assumeTrue, isTypeSubtypeOf); + } + if (containsMatchingReference(reference, predicateArgument)) { + return declaredType; + } + } + } + else { + var invokedExpression = ts.skipParentheses(callExpression.expression); + if (invokedExpression.kind === 190 /* ElementAccessExpression */ || invokedExpression.kind === 189 /* PropertyAccessExpression */) { + var accessExpression = invokedExpression; + var possibleReference = ts.skipParentheses(accessExpression.expression); + if (isMatchingReference(reference, possibleReference)) { + return getNarrowedType(type, predicate.type, assumeTrue, isTypeSubtypeOf); + } + if (containsMatchingReference(reference, possibleReference)) { + return declaredType; + } + } + } + return type; + } + // Narrow the given type based on the given expression having the assumed boolean value. The returned type + // will be a subtype or the same type as the argument. + function narrowType(type, expr, assumeTrue) { + switch (expr.kind) { + case 72 /* Identifier */: + case 100 /* ThisKeyword */: + case 98 /* SuperKeyword */: + case 189 /* PropertyAccessExpression */: + case 190 /* ElementAccessExpression */: + return narrowTypeByTruthiness(type, expr, assumeTrue); + case 191 /* CallExpression */: + return narrowTypeByTypePredicate(type, expr, assumeTrue); + case 195 /* ParenthesizedExpression */: + return narrowType(type, expr.expression, assumeTrue); + case 204 /* BinaryExpression */: + return narrowTypeByBinaryExpression(type, expr, assumeTrue); + case 202 /* PrefixUnaryExpression */: + if (expr.operator === 52 /* ExclamationToken */) { + return narrowType(type, expr.operand, !assumeTrue); + } + break; + } + return type; + } + } + function getTypeOfSymbolAtLocation(symbol, location) { + symbol = symbol.exportSymbol || symbol; + // If we have an identifier or a property access at the given location, if the location is + // an dotted name expression, and if the location is not an assignment target, obtain the type + // of the expression (which will reflect control flow analysis). If the expression indeed + // resolved to the given symbol, return the narrowed type. + if (location.kind === 72 /* Identifier */) { + if (ts.isRightSideOfQualifiedNameOrPropertyAccess(location)) { + location = location.parent; + } + if (ts.isExpressionNode(location) && !ts.isAssignmentTarget(location)) { + var type = getTypeOfExpression(location); + if (getExportSymbolOfValueSymbolIfExported(getNodeLinks(location).resolvedSymbol) === symbol) { + return type; + } + } + } + // The location isn't a reference to the given symbol, meaning we're being asked + // a hypothetical question of what type the symbol would have if there was a reference + // to it at the given location. Since we have no control flow information for the + // hypothetical reference (control flow information is created and attached by the + // binder), we simply return the declared type of the symbol. + return getTypeOfSymbol(symbol); + } + function getControlFlowContainer(node) { + return ts.findAncestor(node.parent, function (node) { + return ts.isFunctionLike(node) && !ts.getImmediatelyInvokedFunctionExpression(node) || + node.kind === 245 /* ModuleBlock */ || + node.kind === 279 /* SourceFile */ || + node.kind === 154 /* PropertyDeclaration */; + }); + } + // Check if a parameter is assigned anywhere within its declaring function. + function isParameterAssigned(symbol) { + var func = ts.getRootDeclaration(symbol.valueDeclaration).parent; + var links = getNodeLinks(func); + if (!(links.flags & 8388608 /* AssignmentsMarked */)) { + links.flags |= 8388608 /* AssignmentsMarked */; + if (!hasParentWithAssignmentsMarked(func)) { + markParameterAssignments(func); + } + } + return symbol.isAssigned || false; + } + function hasParentWithAssignmentsMarked(node) { + return !!ts.findAncestor(node.parent, function (node) { return ts.isFunctionLike(node) && !!(getNodeLinks(node).flags & 8388608 /* AssignmentsMarked */); }); + } + function markParameterAssignments(node) { + if (node.kind === 72 /* Identifier */) { + if (ts.isAssignmentTarget(node)) { + var symbol = getResolvedSymbol(node); + if (symbol.valueDeclaration && ts.getRootDeclaration(symbol.valueDeclaration).kind === 151 /* Parameter */) { + symbol.isAssigned = true; + } + } + } + else { + ts.forEachChild(node, markParameterAssignments); + } + } + function isConstVariable(symbol) { + return symbol.flags & 3 /* Variable */ && (getDeclarationNodeFlagsFromSymbol(symbol) & 2 /* Const */) !== 0 && getTypeOfSymbol(symbol) !== autoArrayType; + } + /** remove undefined from the annotated type of a parameter when there is an initializer (that doesn't include undefined) */ + function removeOptionalityFromDeclaredType(declaredType, declaration) { + var annotationIncludesUndefined = strictNullChecks && + declaration.kind === 151 /* Parameter */ && + declaration.initializer && + getFalsyFlags(declaredType) & 32768 /* Undefined */ && + !(getFalsyFlags(checkExpression(declaration.initializer)) & 32768 /* Undefined */); + return annotationIncludesUndefined ? getTypeWithFacts(declaredType, 524288 /* NEUndefined */) : declaredType; + } + function isConstraintPosition(node) { + var parent = node.parent; + return parent.kind === 189 /* PropertyAccessExpression */ || + parent.kind === 191 /* CallExpression */ && parent.expression === node || + parent.kind === 190 /* ElementAccessExpression */ && parent.expression === node || + parent.kind === 186 /* BindingElement */ && parent.name === node && !!parent.initializer; + } + function typeHasNullableConstraint(type) { + return type.flags & 58982400 /* InstantiableNonPrimitive */ && maybeTypeOfKind(getBaseConstraintOfType(type) || emptyObjectType, 98304 /* Nullable */); + } + function getConstraintForLocation(type, node) { + // When a node is the left hand expression of a property access, element access, or call expression, + // and the type of the node includes type variables with constraints that are nullable, we fetch the + // apparent type of the node *before* performing control flow analysis such that narrowings apply to + // the constraint type. + if (type && isConstraintPosition(node) && forEachType(type, typeHasNullableConstraint)) { + return mapType(getWidenedType(type), getBaseConstraintOrType); + } + return type; + } + function markAliasReferenced(symbol, location) { + if (isNonLocalAlias(symbol, /*excludes*/ 67220415 /* Value */) && !isInTypeQuery(location) && !isConstEnumOrConstEnumOnlyModule(resolveAlias(symbol))) { + markAliasSymbolAsReferenced(symbol); + } + } + function checkIdentifier(node) { + var symbol = getResolvedSymbol(node); + if (symbol === unknownSymbol) { + return errorType; + } + // As noted in ECMAScript 6 language spec, arrow functions never have an arguments objects. + // Although in down-level emit of arrow function, we emit it using function expression which means that + // arguments objects will be bound to the inner object; emitting arrow function natively in ES6, arguments objects + // will be bound to non-arrow function that contain this arrow function. This results in inconsistent behavior. + // To avoid that we will give an error to users if they use arguments objects in arrow function so that they + // can explicitly bound arguments objects + if (symbol === argumentsSymbol) { + var container = ts.getContainingFunction(node); + if (languageVersion < 2 /* ES2015 */) { + if (container.kind === 197 /* ArrowFunction */) { + error(node, ts.Diagnostics.The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_standard_function_expression); + } + else if (ts.hasModifier(container, 256 /* Async */)) { + error(node, ts.Diagnostics.The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_using_a_standard_function_or_method); + } + } + getNodeLinks(container).flags |= 8192 /* CaptureArguments */; + return getTypeOfSymbol(symbol); + } + // We should only mark aliases as referenced if there isn't a local value declaration + // for the symbol. Also, don't mark any property access expression LHS - checkPropertyAccessExpression will handle that + if (!(node.parent && ts.isPropertyAccessExpression(node.parent) && node.parent.expression === node)) { + markAliasReferenced(symbol, node); + } + var localOrExportSymbol = getExportSymbolOfValueSymbolIfExported(symbol); + var declaration = localOrExportSymbol.valueDeclaration; + if (localOrExportSymbol.flags & 32 /* Class */) { + // Due to the emit for class decorators, any reference to the class from inside of the class body + // must instead be rewritten to point to a temporary variable to avoid issues with the double-bind + // behavior of class names in ES6. + if (declaration.kind === 240 /* ClassDeclaration */ + && ts.nodeIsDecorated(declaration)) { + var container = ts.getContainingClass(node); + while (container !== undefined) { + if (container === declaration && container.name !== node) { + getNodeLinks(declaration).flags |= 16777216 /* ClassWithConstructorReference */; + getNodeLinks(node).flags |= 33554432 /* ConstructorReferenceInClass */; + break; + } + container = ts.getContainingClass(container); + } + } + else if (declaration.kind === 209 /* ClassExpression */) { + // When we emit a class expression with static members that contain a reference + // to the constructor in the initializer, we will need to substitute that + // binding with an alias as the class name is not in scope. + var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); + while (container.kind !== 279 /* SourceFile */) { + if (container.parent === declaration) { + if (container.kind === 154 /* PropertyDeclaration */ && ts.hasModifier(container, 32 /* Static */)) { + getNodeLinks(declaration).flags |= 16777216 /* ClassWithConstructorReference */; + getNodeLinks(node).flags |= 33554432 /* ConstructorReferenceInClass */; + } + break; + } + container = ts.getThisContainer(container, /*includeArrowFunctions*/ false); + } + } + } + checkNestedBlockScopedBinding(node, symbol); + var type = getConstraintForLocation(getTypeOfSymbol(localOrExportSymbol), node); + var assignmentKind = ts.getAssignmentTargetKind(node); + if (assignmentKind) { + if (!(localOrExportSymbol.flags & 3 /* Variable */) && + !(ts.isInJSFile(node) && localOrExportSymbol.flags & 512 /* ValueModule */)) { + error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_not_a_variable, symbolToString(symbol)); + return errorType; + } + if (isReadonlySymbol(localOrExportSymbol)) { + if (localOrExportSymbol.flags & 3 /* Variable */) { + error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant, symbolToString(symbol)); + } + else { + error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, symbolToString(symbol)); + } + return errorType; + } + } + var isAlias = localOrExportSymbol.flags & 2097152 /* Alias */; + // We only narrow variables and parameters occurring in a non-assignment position. For all other + // entities we simply return the declared type. + if (localOrExportSymbol.flags & 3 /* Variable */) { + if (assignmentKind === 1 /* Definite */) { + return type; + } + } + else if (isAlias) { + declaration = ts.find(symbol.declarations, isSomeImportDeclaration); + } + else { + return type; + } + if (!declaration) { + return type; + } + // The declaration container is the innermost function that encloses the declaration of the variable + // or parameter. The flow container is the innermost function starting with which we analyze the control + // flow graph to determine the control flow based type. + var isParameter = ts.getRootDeclaration(declaration).kind === 151 /* Parameter */; + var declarationContainer = getControlFlowContainer(declaration); + var flowContainer = getControlFlowContainer(node); + var isOuterVariable = flowContainer !== declarationContainer; + var isSpreadDestructuringAssignmentTarget = node.parent && node.parent.parent && ts.isSpreadAssignment(node.parent) && isDestructuringAssignmentTarget(node.parent.parent); + var isModuleExports = symbol.flags & 134217728 /* ModuleExports */; + // When the control flow originates in a function expression or arrow function and we are referencing + // a const variable or parameter from an outer function, we extend the origin of the control flow + // analysis to include the immediately enclosing function. + while (flowContainer !== declarationContainer && (flowContainer.kind === 196 /* FunctionExpression */ || + flowContainer.kind === 197 /* ArrowFunction */ || ts.isObjectLiteralOrClassExpressionMethod(flowContainer)) && + (isConstVariable(localOrExportSymbol) || isParameter && !isParameterAssigned(localOrExportSymbol))) { + flowContainer = getControlFlowContainer(flowContainer); + } + // We only look for uninitialized variables in strict null checking mode, and only when we can analyze + // the entire control flow graph from the variable's declaration (i.e. when the flow container and + // declaration container are the same). + var assumeInitialized = isParameter || isAlias || isOuterVariable || isSpreadDestructuringAssignmentTarget || isModuleExports || + type !== autoType && type !== autoArrayType && (!strictNullChecks || (type.flags & 3 /* AnyOrUnknown */) !== 0 || + isInTypeQuery(node) || node.parent.kind === 257 /* ExportSpecifier */) || + node.parent.kind === 213 /* NonNullExpression */ || + declaration.kind === 237 /* VariableDeclaration */ && declaration.exclamationToken || + declaration.flags & 4194304 /* Ambient */; + var initialType = assumeInitialized ? (isParameter ? removeOptionalityFromDeclaredType(type, declaration) : type) : + type === autoType || type === autoArrayType ? undefinedType : + getOptionalType(type); + var flowType = getFlowTypeOfReference(node, type, initialType, flowContainer, !assumeInitialized); + // A variable is considered uninitialized when it is possible to analyze the entire control flow graph + // from declaration to use, and when the variable's declared type doesn't include undefined but the + // control flow based type does include undefined. + if (!isEvolvingArrayOperationTarget(node) && (type === autoType || type === autoArrayType)) { + if (flowType === autoType || flowType === autoArrayType) { + if (noImplicitAny) { + error(ts.getNameOfDeclaration(declaration), ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined, symbolToString(symbol), typeToString(flowType)); + error(node, ts.Diagnostics.Variable_0_implicitly_has_an_1_type, symbolToString(symbol), typeToString(flowType)); + } + return convertAutoToAny(flowType); + } + } + else if (!assumeInitialized && !(getFalsyFlags(type) & 32768 /* Undefined */) && getFalsyFlags(flowType) & 32768 /* Undefined */) { + error(node, ts.Diagnostics.Variable_0_is_used_before_being_assigned, symbolToString(symbol)); + // Return the declared type to reduce follow-on errors + return type; + } + return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType; + } + function isInsideFunction(node, threshold) { + return !!ts.findAncestor(node, function (n) { return n === threshold ? "quit" : ts.isFunctionLike(n); }); + } + function getPartOfForStatementContainingNode(node, container) { + return ts.findAncestor(node, function (n) { return n === container ? "quit" : n === container.initializer || n === container.condition || n === container.incrementor || n === container.statement; }); + } + function checkNestedBlockScopedBinding(node, symbol) { + if (languageVersion >= 2 /* ES2015 */ || + (symbol.flags & (2 /* BlockScopedVariable */ | 32 /* Class */)) === 0 || + symbol.valueDeclaration.parent.kind === 274 /* CatchClause */) { + return; + } + // 1. walk from the use site up to the declaration and check + // if there is anything function like between declaration and use-site (is binding/class is captured in function). + // 2. walk from the declaration up to the boundary of lexical environment and check + // if there is an iteration statement in between declaration and boundary (is binding/class declared inside iteration statement) + var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); + var usedInFunction = isInsideFunction(node.parent, container); + var current = container; + var containedInIterationStatement = false; + while (current && !ts.nodeStartsNewLexicalEnvironment(current)) { + if (ts.isIterationStatement(current, /*lookInLabeledStatements*/ false)) { + containedInIterationStatement = true; + break; + } + current = current.parent; + } + if (containedInIterationStatement) { + if (usedInFunction) { + // mark iteration statement as containing block-scoped binding captured in some function + var capturesBlockScopeBindingInLoopBody = true; + if (ts.isForStatement(container) && + ts.getAncestor(symbol.valueDeclaration, 238 /* VariableDeclarationList */).parent === container) { + var part = getPartOfForStatementContainingNode(node.parent, container); + if (part) { + var links = getNodeLinks(part); + links.flags |= 131072 /* ContainsCapturedBlockScopeBinding */; + var capturedBindings = links.capturedBlockScopeBindings || (links.capturedBlockScopeBindings = []); + ts.pushIfUnique(capturedBindings, symbol); + if (part === container.initializer) { + capturesBlockScopeBindingInLoopBody = false; // Initializer is outside of loop body + } + } + } + if (capturesBlockScopeBindingInLoopBody) { + getNodeLinks(current).flags |= 65536 /* LoopWithCapturedBlockScopedBinding */; + } + } + // mark variables that are declared in loop initializer and reassigned inside the body of ForStatement. + // if body of ForStatement will be converted to function then we'll need a extra machinery to propagate reassigned values back. + if (container.kind === 225 /* ForStatement */ && + ts.getAncestor(symbol.valueDeclaration, 238 /* VariableDeclarationList */).parent === container && + isAssignedInBodyOfForStatement(node, container)) { + getNodeLinks(symbol.valueDeclaration).flags |= 4194304 /* NeedsLoopOutParameter */; + } + // set 'declared inside loop' bit on the block-scoped binding + getNodeLinks(symbol.valueDeclaration).flags |= 524288 /* BlockScopedBindingInLoop */; + } + if (usedInFunction) { + getNodeLinks(symbol.valueDeclaration).flags |= 262144 /* CapturedBlockScopedBinding */; + } + } + function isBindingCapturedByNode(node, decl) { + var links = getNodeLinks(node); + return !!links && ts.contains(links.capturedBlockScopeBindings, getSymbolOfNode(decl)); + } + function isAssignedInBodyOfForStatement(node, container) { + // skip parenthesized nodes + var current = node; + while (current.parent.kind === 195 /* ParenthesizedExpression */) { + current = current.parent; + } + // check if node is used as LHS in some assignment expression + var isAssigned = false; + if (ts.isAssignmentTarget(current)) { + isAssigned = true; + } + else if ((current.parent.kind === 202 /* PrefixUnaryExpression */ || current.parent.kind === 203 /* PostfixUnaryExpression */)) { + var expr = current.parent; + isAssigned = expr.operator === 44 /* PlusPlusToken */ || expr.operator === 45 /* MinusMinusToken */; + } + if (!isAssigned) { + return false; + } + // at this point we know that node is the target of assignment + // now check that modification happens inside the statement part of the ForStatement + return !!ts.findAncestor(current, function (n) { return n === container ? "quit" : n === container.statement; }); + } + function captureLexicalThis(node, container) { + getNodeLinks(node).flags |= 2 /* LexicalThis */; + if (container.kind === 154 /* PropertyDeclaration */ || container.kind === 157 /* Constructor */) { + var classNode = container.parent; + getNodeLinks(classNode).flags |= 4 /* CaptureThis */; + } + else { + getNodeLinks(container).flags |= 4 /* CaptureThis */; + } + } + function findFirstSuperCall(n) { + if (ts.isSuperCall(n)) { + return n; + } + else if (ts.isFunctionLike(n)) { + return undefined; + } + return ts.forEachChild(n, findFirstSuperCall); + } + /** + * Return a cached result if super-statement is already found. + * Otherwise, find a super statement in a given constructor function and cache the result in the node-links of the constructor + * + * @param constructor constructor-function to look for super statement + */ + function getSuperCallInConstructor(constructor) { + var links = getNodeLinks(constructor); + // Only trying to find super-call if we haven't yet tried to find one. Once we try, we will record the result + if (links.hasSuperCall === undefined) { + links.superCall = findFirstSuperCall(constructor.body); + links.hasSuperCall = links.superCall ? true : false; + } + return links.superCall; + } + /** + * Check if the given class-declaration extends null then return true. + * Otherwise, return false + * @param classDecl a class declaration to check if it extends null + */ + function classDeclarationExtendsNull(classDecl) { + var classSymbol = getSymbolOfNode(classDecl); + var classInstanceType = getDeclaredTypeOfSymbol(classSymbol); + var baseConstructorType = getBaseConstructorTypeOfClass(classInstanceType); + return baseConstructorType === nullWideningType; + } + function checkThisBeforeSuper(node, container, diagnosticMessage) { + var containingClassDecl = container.parent; + var baseTypeNode = ts.getEffectiveBaseTypeNode(containingClassDecl); + // If a containing class does not have extends clause or the class extends null + // skip checking whether super statement is called before "this" accessing. + if (baseTypeNode && !classDeclarationExtendsNull(containingClassDecl)) { + var superCall = getSuperCallInConstructor(container); + // We should give an error in the following cases: + // - No super-call + // - "this" is accessing before super-call. + // i.e super(this) + // this.x; super(); + // We want to make sure that super-call is done before accessing "this" so that + // "this" is not accessed as a parameter of the super-call. + if (!superCall || superCall.end > node.pos) { + // In ES6, super inside constructor of class-declaration has to precede "this" accessing + error(node, diagnosticMessage); + } + } + } + function checkThisExpression(node) { + // Stop at the first arrow function so that we can + // tell whether 'this' needs to be captured. + var container = ts.getThisContainer(node, /* includeArrowFunctions */ true); + var capturedByArrowFunction = false; + if (container.kind === 157 /* Constructor */) { + checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class); + } + // Now skip arrow functions to get the "real" owner of 'this'. + if (container.kind === 197 /* ArrowFunction */) { + container = ts.getThisContainer(container, /* includeArrowFunctions */ false); + capturedByArrowFunction = true; + } + switch (container.kind) { + case 244 /* ModuleDeclaration */: + error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_module_or_namespace_body); + // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks + break; + case 243 /* EnumDeclaration */: + error(node, ts.Diagnostics.this_cannot_be_referenced_in_current_location); + // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks + break; + case 157 /* Constructor */: + if (isInConstructorArgumentInitializer(node, container)) { + error(node, ts.Diagnostics.this_cannot_be_referenced_in_constructor_arguments); + // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks + } + break; + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + if (ts.hasModifier(container, 32 /* Static */)) { + error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_static_property_initializer); + // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks + } + break; + case 149 /* ComputedPropertyName */: + error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_computed_property_name); + break; + } + // When targeting es6, mark that we'll need to capture `this` in its lexically bound scope. + if (capturedByArrowFunction && languageVersion < 2 /* ES2015 */) { + captureLexicalThis(node, container); + } + var type = tryGetThisTypeAt(node, container); + if (!type && noImplicitThis) { + // With noImplicitThis, functions may not reference 'this' if it has type 'any' + var diag = error(node, capturedByArrowFunction && container.kind === 279 /* SourceFile */ ? + ts.Diagnostics.The_containing_arrow_function_captures_the_global_value_of_this_which_implicitly_has_type_any : + ts.Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation); + if (!ts.isSourceFile(container)) { + var outsideThis = tryGetThisTypeAt(container); + if (outsideThis) { + addRelatedInfo(diag, ts.createDiagnosticForNode(container, ts.Diagnostics.An_outer_value_of_this_is_shadowed_by_this_container)); + } + } + } + return type || anyType; + } + function tryGetThisTypeAt(node, container) { + if (container === void 0) { container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); } + var isInJS = ts.isInJSFile(node); + if (ts.isFunctionLike(container) && + (!isInParameterInitializerBeforeContainingFunction(node) || ts.getThisParameter(container))) { + // Note: a parameter initializer should refer to class-this unless function-this is explicitly annotated. + // If this is a function in a JS file, it might be a class method. + var className = getClassNameFromPrototypeMethod(container); + if (isInJS && className) { + var classSymbol = checkExpression(className).symbol; + if (classSymbol && classSymbol.members && (classSymbol.flags & 16 /* Function */)) { + var classType = getJSClassType(classSymbol); + if (classType) { + return getFlowTypeOfReference(node, classType); + } + } + } + // Check if it's a constructor definition, can be either a variable decl or function decl + // i.e. + // * /** @constructor */ function [name]() { ... } + // * /** @constructor */ var x = function() { ... } + else if (isInJS && + (container.kind === 196 /* FunctionExpression */ || container.kind === 239 /* FunctionDeclaration */) && + ts.getJSDocClassTag(container)) { + var classType = getJSClassType(container.symbol); + if (classType) { + return getFlowTypeOfReference(node, classType); + } + } + var thisType = getThisTypeOfDeclaration(container) || getContextualThisParameterType(container); + if (thisType) { + return getFlowTypeOfReference(node, thisType); + } + } + if (ts.isClassLike(container.parent)) { + var symbol = getSymbolOfNode(container.parent); + var type = ts.hasModifier(container, 32 /* Static */) ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol).thisType; + return getFlowTypeOfReference(node, type); + } + if (isInJS) { + var type = getTypeForThisExpressionFromJSDoc(container); + if (type && type !== errorType) { + return getFlowTypeOfReference(node, type); + } + } + } + function getClassNameFromPrototypeMethod(container) { + // Check if it's the RHS of a x.prototype.y = function [name]() { .... } + if (container.kind === 196 /* FunctionExpression */ && + ts.isBinaryExpression(container.parent) && + ts.getAssignmentDeclarationKind(container.parent) === 3 /* PrototypeProperty */) { + // Get the 'x' of 'x.prototype.y = container' + return container.parent // x.prototype.y = container + .left // x.prototype.y + .expression // x.prototype + .expression; // x + } + // x.prototype = { method() { } } + else if (container.kind === 156 /* MethodDeclaration */ && + container.parent.kind === 188 /* ObjectLiteralExpression */ && + ts.isBinaryExpression(container.parent.parent) && + ts.getAssignmentDeclarationKind(container.parent.parent) === 6 /* Prototype */) { + return container.parent.parent.left.expression; + } + // x.prototype = { method: function() { } } + else if (container.kind === 196 /* FunctionExpression */ && + container.parent.kind === 275 /* PropertyAssignment */ && + container.parent.parent.kind === 188 /* ObjectLiteralExpression */ && + ts.isBinaryExpression(container.parent.parent.parent) && + ts.getAssignmentDeclarationKind(container.parent.parent.parent) === 6 /* Prototype */) { + return container.parent.parent.parent.left.expression; + } + // Object.defineProperty(x, "method", { value: function() { } }); + // Object.defineProperty(x, "method", { set: (x: () => void) => void }); + // Object.defineProperty(x, "method", { get: () => function() { }) }); + else if (container.kind === 196 /* FunctionExpression */ && + ts.isPropertyAssignment(container.parent) && + ts.isIdentifier(container.parent.name) && + (container.parent.name.escapedText === "value" || container.parent.name.escapedText === "get" || container.parent.name.escapedText === "set") && + ts.isObjectLiteralExpression(container.parent.parent) && + ts.isCallExpression(container.parent.parent.parent) && + container.parent.parent.parent.arguments[2] === container.parent.parent && + ts.getAssignmentDeclarationKind(container.parent.parent.parent) === 9 /* ObjectDefinePrototypeProperty */) { + return container.parent.parent.parent.arguments[0].expression; + } + // Object.defineProperty(x, "method", { value() { } }); + // Object.defineProperty(x, "method", { set(x: () => void) {} }); + // Object.defineProperty(x, "method", { get() { return () => {} } }); + else if (ts.isMethodDeclaration(container) && + ts.isIdentifier(container.name) && + (container.name.escapedText === "value" || container.name.escapedText === "get" || container.name.escapedText === "set") && + ts.isObjectLiteralExpression(container.parent) && + ts.isCallExpression(container.parent.parent) && + container.parent.parent.arguments[2] === container.parent && + ts.getAssignmentDeclarationKind(container.parent.parent) === 9 /* ObjectDefinePrototypeProperty */) { + return container.parent.parent.arguments[0].expression; + } + } + function getTypeForThisExpressionFromJSDoc(node) { + var jsdocType = ts.getJSDocType(node); + if (jsdocType && jsdocType.kind === 289 /* JSDocFunctionType */) { + var jsDocFunctionType = jsdocType; + if (jsDocFunctionType.parameters.length > 0 && + jsDocFunctionType.parameters[0].name && + jsDocFunctionType.parameters[0].name.escapedText === "this" /* This */) { + return getTypeFromTypeNode(jsDocFunctionType.parameters[0].type); + } + } + var thisTag = ts.getJSDocThisTag(node); + if (thisTag && thisTag.typeExpression) { + return getTypeFromTypeNode(thisTag.typeExpression); + } + } + function isInConstructorArgumentInitializer(node, constructorDecl) { + return !!ts.findAncestor(node, function (n) { return n === constructorDecl ? "quit" : n.kind === 151 /* Parameter */; }); + } + function checkSuperExpression(node) { + var isCallExpression = node.parent.kind === 191 /* CallExpression */ && node.parent.expression === node; + var container = ts.getSuperContainer(node, /*stopOnFunctions*/ true); + var needToCaptureLexicalThis = false; + // adjust the container reference in case if super is used inside arrow functions with arbitrarily deep nesting + if (!isCallExpression) { + while (container && container.kind === 197 /* ArrowFunction */) { + container = ts.getSuperContainer(container, /*stopOnFunctions*/ true); + needToCaptureLexicalThis = languageVersion < 2 /* ES2015 */; + } + } + var canUseSuperExpression = isLegalUsageOfSuperExpression(container); + var nodeCheckFlag = 0; + if (!canUseSuperExpression) { + // issue more specific error if super is used in computed property name + // class A { foo() { return "1" }} + // class B { + // [super.foo()]() {} + // } + var current = ts.findAncestor(node, function (n) { return n === container ? "quit" : n.kind === 149 /* ComputedPropertyName */; }); + if (current && current.kind === 149 /* ComputedPropertyName */) { + error(node, ts.Diagnostics.super_cannot_be_referenced_in_a_computed_property_name); + } + else if (isCallExpression) { + error(node, ts.Diagnostics.Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors); + } + else if (!container || !container.parent || !(ts.isClassLike(container.parent) || container.parent.kind === 188 /* ObjectLiteralExpression */)) { + error(node, ts.Diagnostics.super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions); + } + else { + error(node, ts.Diagnostics.super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_derived_class); + } + return errorType; + } + if (!isCallExpression && container.kind === 157 /* Constructor */) { + checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class); + } + if (ts.hasModifier(container, 32 /* Static */) || isCallExpression) { + nodeCheckFlag = 512 /* SuperStatic */; + } + else { + nodeCheckFlag = 256 /* SuperInstance */; + } + getNodeLinks(node).flags |= nodeCheckFlag; + // Due to how we emit async functions, we need to specialize the emit for an async method that contains a `super` reference. + // This is due to the fact that we emit the body of an async function inside of a generator function. As generator + // functions cannot reference `super`, we emit a helper inside of the method body, but outside of the generator. This helper + // uses an arrow function, which is permitted to reference `super`. + // + // There are two primary ways we can access `super` from within an async method. The first is getting the value of a property + // or indexed access on super, either as part of a right-hand-side expression or call expression. The second is when setting the value + // of a property or indexed access, either as part of an assignment expression or destructuring assignment. + // + // The simplest case is reading a value, in which case we will emit something like the following: + // + // // ts + // ... + // async asyncMethod() { + // let x = await super.asyncMethod(); + // return x; + // } + // ... + // + // // js + // ... + // asyncMethod() { + // const _super = Object.create(null, { + // asyncMethod: { get: () => super.asyncMethod }, + // }); + // return __awaiter(this, arguments, Promise, function *() { + // let x = yield _super.asyncMethod.call(this); + // return x; + // }); + // } + // ... + // + // The more complex case is when we wish to assign a value, especially as part of a destructuring assignment. As both cases + // are legal in ES6, but also likely less frequent, we only emit setters if there is an assignment: + // + // // ts + // ... + // async asyncMethod(ar: Promise) { + // [super.a, super.b] = await ar; + // } + // ... + // + // // js + // ... + // asyncMethod(ar) { + // const _super = Object.create(null, { + // a: { get: () => super.a, set: (v) => super.a = v }, + // b: { get: () => super.b, set: (v) => super.b = v } + // }; + // return __awaiter(this, arguments, Promise, function *() { + // [_super.a, _super.b] = yield ar; + // }); + // } + // ... + // + // Creating an object that has getter and setters instead of just an accessor function is required for destructuring assignments + // as a call expression cannot be used as the target of a destructuring assignment while a property access can. + // + // For element access expressions (`super[x]`), we emit a generic helper that forwards the element access in both situations. + if (container.kind === 156 /* MethodDeclaration */ && ts.hasModifier(container, 256 /* Async */)) { + if (ts.isSuperProperty(node.parent) && ts.isAssignmentTarget(node.parent)) { + getNodeLinks(container).flags |= 4096 /* AsyncMethodWithSuperBinding */; + } + else { + getNodeLinks(container).flags |= 2048 /* AsyncMethodWithSuper */; + } + } + if (needToCaptureLexicalThis) { + // call expressions are allowed only in constructors so they should always capture correct 'this' + // super property access expressions can also appear in arrow functions - + // in this case they should also use correct lexical this + captureLexicalThis(node.parent, container); + } + if (container.parent.kind === 188 /* ObjectLiteralExpression */) { + if (languageVersion < 2 /* ES2015 */) { + error(node, ts.Diagnostics.super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_higher); + return errorType; + } + else { + // for object literal assume that type of 'super' is 'any' + return anyType; + } + } + // at this point the only legal case for parent is ClassLikeDeclaration + var classLikeDeclaration = container.parent; + if (!ts.getEffectiveBaseTypeNode(classLikeDeclaration)) { + error(node, ts.Diagnostics.super_can_only_be_referenced_in_a_derived_class); + return errorType; + } + var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(classLikeDeclaration)); + var baseClassType = classType && getBaseTypes(classType)[0]; + if (!baseClassType) { + return errorType; + } + if (container.kind === 157 /* Constructor */ && isInConstructorArgumentInitializer(node, container)) { + // issue custom error message for super property access in constructor arguments (to be aligned with old compiler) + error(node, ts.Diagnostics.super_cannot_be_referenced_in_constructor_arguments); + return errorType; + } + return nodeCheckFlag === 512 /* SuperStatic */ + ? getBaseConstructorTypeOfClass(classType) + : getTypeWithThisArgument(baseClassType, classType.thisType); + function isLegalUsageOfSuperExpression(container) { + if (!container) { + return false; + } + if (isCallExpression) { + // TS 1.0 SPEC (April 2014): 4.8.1 + // Super calls are only permitted in constructors of derived classes + return container.kind === 157 /* Constructor */; + } + else { + // TS 1.0 SPEC (April 2014) + // 'super' property access is allowed + // - In a constructor, instance member function, instance member accessor, or instance member variable initializer where this references a derived class instance + // - In a static member function or static member accessor + // topmost container must be something that is directly nested in the class declaration\object literal expression + if (ts.isClassLike(container.parent) || container.parent.kind === 188 /* ObjectLiteralExpression */) { + if (ts.hasModifier(container, 32 /* Static */)) { + return container.kind === 156 /* MethodDeclaration */ || + container.kind === 155 /* MethodSignature */ || + container.kind === 158 /* GetAccessor */ || + container.kind === 159 /* SetAccessor */; + } + else { + return container.kind === 156 /* MethodDeclaration */ || + container.kind === 155 /* MethodSignature */ || + container.kind === 158 /* GetAccessor */ || + container.kind === 159 /* SetAccessor */ || + container.kind === 154 /* PropertyDeclaration */ || + container.kind === 153 /* PropertySignature */ || + container.kind === 157 /* Constructor */; + } + } + } + return false; + } + } + function getContainingObjectLiteral(func) { + return (func.kind === 156 /* MethodDeclaration */ || + func.kind === 158 /* GetAccessor */ || + func.kind === 159 /* SetAccessor */) && func.parent.kind === 188 /* ObjectLiteralExpression */ ? func.parent : + func.kind === 196 /* FunctionExpression */ && func.parent.kind === 275 /* PropertyAssignment */ ? func.parent.parent : + undefined; + } + function getThisTypeArgument(type) { + return ts.getObjectFlags(type) & 4 /* Reference */ && type.target === globalThisType ? type.typeArguments[0] : undefined; + } + function getThisTypeFromContextualType(type) { + return mapType(type, function (t) { + return t.flags & 2097152 /* Intersection */ ? ts.forEach(t.types, getThisTypeArgument) : getThisTypeArgument(t); + }); + } + function getContextualThisParameterType(func) { + if (func.kind === 197 /* ArrowFunction */) { + return undefined; + } + if (isContextSensitiveFunctionOrObjectLiteralMethod(func)) { + var contextualSignature = getContextualSignature(func); + if (contextualSignature) { + var thisParameter = contextualSignature.thisParameter; + if (thisParameter) { + return getTypeOfSymbol(thisParameter); + } + } + } + var inJs = ts.isInJSFile(func); + if (noImplicitThis || inJs) { + var containingLiteral = getContainingObjectLiteral(func); + if (containingLiteral) { + // We have an object literal method. Check if the containing object literal has a contextual type + // that includes a ThisType. If so, T is the contextual type for 'this'. We continue looking in + // any directly enclosing object literals. + var contextualType = getApparentTypeOfContextualType(containingLiteral); + var literal = containingLiteral; + var type = contextualType; + while (type) { + var thisType = getThisTypeFromContextualType(type); + if (thisType) { + return instantiateType(thisType, getContextualMapper(containingLiteral)); + } + if (literal.parent.kind !== 275 /* PropertyAssignment */) { + break; + } + literal = literal.parent.parent; + type = getApparentTypeOfContextualType(literal); + } + // There was no contextual ThisType for the containing object literal, so the contextual type + // for 'this' is the non-null form of the contextual type for the containing object literal or + // the type of the object literal itself. + return contextualType ? getNonNullableType(contextualType) : checkExpressionCached(containingLiteral); + } + // In an assignment of the form 'obj.xxx = function(...)' or 'obj[xxx] = function(...)', the + // contextual type for 'this' is 'obj'. + var parent = func.parent; + if (parent.kind === 204 /* BinaryExpression */ && parent.operatorToken.kind === 59 /* EqualsToken */) { + var target = parent.left; + if (target.kind === 189 /* PropertyAccessExpression */ || target.kind === 190 /* ElementAccessExpression */) { + var expression = target.expression; + // Don't contextually type `this` as `exports` in `exports.Point = function(x, y) { this.x = x; this.y = y; }` + if (inJs && ts.isIdentifier(expression)) { + var sourceFile = ts.getSourceFileOfNode(parent); + if (sourceFile.commonJsModuleIndicator && getResolvedSymbol(expression) === sourceFile.symbol) { + return undefined; + } + } + return checkExpressionCached(expression); + } + } + } + return undefined; + } + // Return contextual type of parameter or undefined if no contextual type is available + function getContextuallyTypedParameterType(parameter) { + var func = parameter.parent; + if (!isContextSensitiveFunctionOrObjectLiteralMethod(func)) { + return undefined; + } + var iife = ts.getImmediatelyInvokedFunctionExpression(func); + if (iife && iife.arguments) { + var args = getEffectiveCallArguments(iife); + var indexOfParameter = func.parameters.indexOf(parameter); + if (parameter.dotDotDotToken) { + return getSpreadArgumentType(args, indexOfParameter, args.length, anyType, /*context*/ undefined); + } + var links = getNodeLinks(iife); + var cached = links.resolvedSignature; + links.resolvedSignature = anySignature; + var type = indexOfParameter < args.length ? + getWidenedLiteralType(checkExpression(args[indexOfParameter])) : + parameter.initializer ? undefined : undefinedWideningType; + links.resolvedSignature = cached; + return type; + } + var contextualSignature = getContextualSignature(func); + if (contextualSignature) { + var index = func.parameters.indexOf(parameter) - (ts.getThisParameter(func) ? 1 : 0); + return parameter.dotDotDotToken && ts.lastOrUndefined(func.parameters) === parameter ? + getRestTypeAtPosition(contextualSignature, index) : + tryGetTypeAtPosition(contextualSignature, index); + } + } + // In a variable, parameter or property declaration with a type annotation, + // the contextual type of an initializer expression is the type of the variable, parameter or property. + // Otherwise, in a parameter declaration of a contextually typed function expression, + // the contextual type of an initializer expression is the contextual type of the parameter. + // Otherwise, in a variable or parameter declaration with a binding pattern name, + // the contextual type of an initializer expression is the type implied by the binding pattern. + // Otherwise, in a binding pattern inside a variable or parameter declaration, + // the contextual type of an initializer expression is the type annotation of the containing declaration, if present. + function getContextualTypeForInitializerExpression(node) { + var declaration = node.parent; + if (ts.hasInitializer(declaration) && node === declaration.initializer) { + var typeNode = ts.getEffectiveTypeAnnotationNode(declaration); + if (typeNode) { + return getTypeFromTypeNode(typeNode); + } + if (declaration.kind === 151 /* Parameter */) { + var type = getContextuallyTypedParameterType(declaration); + if (type) { + return type; + } + } + if (ts.isBindingPattern(declaration.name)) { + return getTypeFromBindingPattern(declaration.name, /*includePatternInType*/ true, /*reportErrors*/ false); + } + if (ts.isBindingPattern(declaration.parent)) { + var parentDeclaration = declaration.parent.parent; + var name = declaration.propertyName || declaration.name; + if (parentDeclaration.kind !== 186 /* BindingElement */) { + var parentTypeNode = ts.getEffectiveTypeAnnotationNode(parentDeclaration); + if (parentTypeNode && !ts.isBindingPattern(name)) { + var text = ts.getTextOfPropertyName(name); + if (text) { + return getTypeOfPropertyOfType(getTypeFromTypeNode(parentTypeNode), text); + } + } + } + } + } + return undefined; + } + function getContextualTypeForReturnExpression(node) { + var func = ts.getContainingFunction(node); + if (func) { + var functionFlags = ts.getFunctionFlags(func); + if (functionFlags & 1 /* Generator */) { // AsyncGenerator function or Generator function + return undefined; + } + var contextualReturnType = getContextualReturnType(func); + if (contextualReturnType) { + if (functionFlags & 2 /* Async */) { // Async function + var contextualAwaitedType = getAwaitedTypeOfPromise(contextualReturnType); + return contextualAwaitedType && getUnionType([contextualAwaitedType, createPromiseLikeType(contextualAwaitedType)]); + } + return contextualReturnType; // Regular function + } + } + return undefined; + } + function getContextualTypeForAwaitOperand(node) { + var contextualType = getContextualType(node); + if (contextualType) { + var contextualAwaitedType = getAwaitedType(contextualType); + return contextualAwaitedType && getUnionType([contextualAwaitedType, createPromiseLikeType(contextualAwaitedType)]); + } + return undefined; + } + function getContextualTypeForYieldOperand(node) { + var func = ts.getContainingFunction(node); + if (func) { + var functionFlags = ts.getFunctionFlags(func); + var contextualReturnType = getContextualReturnType(func); + if (contextualReturnType) { + return node.asteriskToken + ? contextualReturnType + : getIteratedTypeOfGenerator(contextualReturnType, (functionFlags & 2 /* Async */) !== 0); + } + } + return undefined; + } + function isInParameterInitializerBeforeContainingFunction(node) { + var inBindingInitializer = false; + while (node.parent && !ts.isFunctionLike(node.parent)) { + if (ts.isParameter(node.parent) && (inBindingInitializer || node.parent.initializer === node)) { + return true; + } + if (ts.isBindingElement(node.parent) && node.parent.initializer === node) { + inBindingInitializer = true; + } + node = node.parent; + } + return false; + } + function getContextualReturnType(functionDecl) { + // If the containing function has a return type annotation, is a constructor, or is a get accessor whose + // corresponding set accessor has a type annotation, return statements in the function are contextually typed + var returnType = getReturnTypeFromAnnotation(functionDecl); + if (returnType) { + return returnType; + } + // Otherwise, if the containing function is contextually typed by a function type with exactly one call signature + // and that call signature is non-generic, return statements are contextually typed by the return type of the signature + var signature = getContextualSignatureForFunctionLikeDeclaration(functionDecl); + if (signature && !isResolvingReturnTypeOfSignature(signature)) { + return getReturnTypeOfSignature(signature); + } + return undefined; + } + // In a typed function call, an argument or substitution expression is contextually typed by the type of the corresponding parameter. + function getContextualTypeForArgument(callTarget, arg) { + var args = getEffectiveCallArguments(callTarget); + var argIndex = args.indexOf(arg); // -1 for e.g. the expression of a CallExpression, or the tag of a TaggedTemplateExpression + return argIndex === -1 ? undefined : getContextualTypeForArgumentAtIndex(callTarget, argIndex); + } + function getContextualTypeForArgumentAtIndex(callTarget, argIndex) { + // If we're already in the process of resolving the given signature, don't resolve again as + // that could cause infinite recursion. Instead, return anySignature. + var signature = getNodeLinks(callTarget).resolvedSignature === resolvingSignature ? resolvingSignature : getResolvedSignature(callTarget); + if (ts.isJsxOpeningLikeElement(callTarget) && argIndex === 0) { + return getEffectiveFirstArgumentForJsxSignature(signature, callTarget); + } + return getTypeAtPosition(signature, argIndex); + } + function getContextualTypeForSubstitutionExpression(template, substitutionExpression) { + if (template.parent.kind === 193 /* TaggedTemplateExpression */) { + return getContextualTypeForArgument(template.parent, substitutionExpression); + } + return undefined; + } + function getContextualTypeForBinaryOperand(node) { + var binaryExpression = node.parent; + var left = binaryExpression.left, operatorToken = binaryExpression.operatorToken, right = binaryExpression.right; + switch (operatorToken.kind) { + case 59 /* EqualsToken */: + if (node !== right) { + return undefined; + } + var contextSensitive = getIsContextSensitiveAssignmentOrContextType(binaryExpression); + if (!contextSensitive) { + return undefined; + } + return contextSensitive === true ? getTypeOfExpression(left) : contextSensitive; + case 55 /* BarBarToken */: + // When an || expression has a contextual type, the operands are contextually typed by that type. When an || + // expression has no contextual type, the right operand is contextually typed by the type of the left operand, + // except for the special case of Javascript declarations of the form `namespace.prop = namespace.prop || {}` + var type = getContextualType(binaryExpression); + return !type && node === right && !ts.isDefaultedExpandoInitializer(binaryExpression) ? + getTypeOfExpression(left) : type; + case 54 /* AmpersandAmpersandToken */: + case 27 /* CommaToken */: + return node === right ? getContextualType(binaryExpression) : undefined; + default: + return undefined; + } + } + // In an assignment expression, the right operand is contextually typed by the type of the left operand. + // Don't do this for assignment declarations unless there is a type tag on the assignment, to avoid circularity from checking the right operand. + function getIsContextSensitiveAssignmentOrContextType(binaryExpression) { + var kind = ts.getAssignmentDeclarationKind(binaryExpression); + switch (kind) { + case 0 /* None */: + return true; + case 5 /* Property */: + case 1 /* ExportsProperty */: + case 6 /* Prototype */: + case 3 /* PrototypeProperty */: + // If `binaryExpression.left` was assigned a symbol, then this is a new declaration; otherwise it is an assignment to an existing declaration. + // See `bindStaticPropertyAssignment` in `binder.ts`. + if (!binaryExpression.left.symbol) { + return true; + } + else { + var decl = binaryExpression.left.symbol.valueDeclaration; + if (!decl) { + return false; + } + var lhs = binaryExpression.left; + var overallAnnotation = ts.getEffectiveTypeAnnotationNode(decl); + if (overallAnnotation) { + return getTypeFromTypeNode(overallAnnotation); + } + else if (ts.isIdentifier(lhs.expression)) { + var id = lhs.expression; + var parentSymbol = resolveName(id, id.escapedText, 67220415 /* Value */, undefined, id.escapedText, /*isUse*/ true); + if (parentSymbol) { + var annotated = ts.getEffectiveTypeAnnotationNode(parentSymbol.valueDeclaration); + if (annotated) { + var type = getTypeOfPropertyOfContextualType(getTypeFromTypeNode(annotated), lhs.name.escapedText); + return type || false; + } + return false; + } + } + return !ts.isInJSFile(decl); + } + case 2 /* ModuleExports */: + case 4 /* ThisProperty */: + if (!binaryExpression.symbol) + return true; + if (binaryExpression.symbol.valueDeclaration) { + var annotated = ts.getEffectiveTypeAnnotationNode(binaryExpression.symbol.valueDeclaration); + if (annotated) { + var type = getTypeFromTypeNode(annotated); + if (type) { + return type; + } + } + } + if (kind === 2 /* ModuleExports */) + return false; + var thisAccess = binaryExpression.left; + if (!ts.isObjectLiteralMethod(ts.getThisContainer(thisAccess.expression, /*includeArrowFunctions*/ false))) { + return false; + } + var thisType = checkThisExpression(thisAccess.expression); + return thisType && getTypeOfPropertyOfContextualType(thisType, thisAccess.name.escapedText) || false; + case 7 /* ObjectDefinePropertyValue */: + case 8 /* ObjectDefinePropertyExports */: + case 9 /* ObjectDefinePrototypeProperty */: + return ts.Debug.fail("Does not apply"); + default: + return ts.Debug.assertNever(kind); + } + } + function getTypeOfPropertyOfContextualType(type, name) { + return mapType(type, function (t) { + if (t.flags & 3670016 /* StructuredType */) { + var prop = getPropertyOfType(t, name); + if (prop) { + return getTypeOfSymbol(prop); + } + if (isTupleType(t)) { + var restType = getRestTypeOfTupleType(t); + if (restType && isNumericLiteralName(name) && +name >= 0) { + return restType; + } + } + return isNumericLiteralName(name) && getIndexTypeOfContextualType(t, 1 /* Number */) || + getIndexTypeOfContextualType(t, 0 /* String */); + } + return undefined; + }, /*noReductions*/ true); + } + function getIndexTypeOfContextualType(type, kind) { + return mapType(type, function (t) { return getIndexTypeOfStructuredType(t, kind); }, /*noReductions*/ true); + } + // In an object literal contextually typed by a type T, the contextual type of a property assignment is the type of + // the matching property in T, if one exists. Otherwise, it is the type of the numeric index signature in T, if one + // exists. Otherwise, it is the type of the string index signature in T, if one exists. + function getContextualTypeForObjectLiteralMethod(node) { + ts.Debug.assert(ts.isObjectLiteralMethod(node)); + if (node.flags & 8388608 /* InWithStatement */) { + // We cannot answer semantic questions within a with block, do not proceed any further + return undefined; + } + return getContextualTypeForObjectLiteralElement(node); + } + function getContextualTypeForObjectLiteralElement(element) { + var objectLiteral = element.parent; + var type = getApparentTypeOfContextualType(objectLiteral); + if (type) { + if (!hasNonBindableDynamicName(element)) { + // For a (non-symbol) computed property, there is no reason to look up the name + // in the type. It will just be "__computed", which does not appear in any + // SymbolTable. + var symbolName_2 = getSymbolOfNode(element).escapedName; + var propertyType = getTypeOfPropertyOfContextualType(type, symbolName_2); + if (propertyType) { + return propertyType; + } + } + return isNumericName(element.name) && getIndexTypeOfContextualType(type, 1 /* Number */) || + getIndexTypeOfContextualType(type, 0 /* String */); + } + return undefined; + } + // In an array literal contextually typed by a type T, the contextual type of an element expression at index N is + // the type of the property with the numeric name N in T, if one exists. Otherwise, if T has a numeric index signature, + // it is the type of the numeric index signature in T. Otherwise, in ES6 and higher, the contextual type is the iterated + // type of T. + function getContextualTypeForElementExpression(arrayContextualType, index) { + return arrayContextualType && (getTypeOfPropertyOfContextualType(arrayContextualType, "" + index) + || getIteratedTypeOrElementType(arrayContextualType, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterables*/ false, /*checkAssignability*/ false)); + } + // In a contextually typed conditional expression, the true/false expressions are contextually typed by the same type. + function getContextualTypeForConditionalOperand(node) { + var conditional = node.parent; + return node === conditional.whenTrue || node === conditional.whenFalse ? getContextualType(conditional) : undefined; + } + function getContextualTypeForChildJsxExpression(node) { + var attributesType = getApparentTypeOfContextualType(node.openingElement.tagName); + // JSX expression is in children of JSX Element, we will look for an "children" atttribute (we get the name from JSX.ElementAttributesProperty) + var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(node)); + return attributesType && !isTypeAny(attributesType) && jsxChildrenPropertyName && jsxChildrenPropertyName !== "" ? getTypeOfPropertyOfContextualType(attributesType, jsxChildrenPropertyName) : undefined; + } + function getContextualTypeForJsxExpression(node) { + var exprParent = node.parent; + return ts.isJsxAttributeLike(exprParent) + ? getContextualType(node) + : ts.isJsxElement(exprParent) + ? getContextualTypeForChildJsxExpression(exprParent) + : undefined; + } + function getContextualTypeForJsxAttribute(attribute) { + // When we trying to resolve JsxOpeningLikeElement as a stateless function element, we will already give its attributes a contextual type + // which is a type of the parameter of the signature we are trying out. + // If there is no contextual type (e.g. we are trying to resolve stateful component), get attributes type from resolving element's tagName + if (ts.isJsxAttribute(attribute)) { + var attributesType = getApparentTypeOfContextualType(attribute.parent); + if (!attributesType || isTypeAny(attributesType)) { + return undefined; + } + return getTypeOfPropertyOfContextualType(attributesType, attribute.name.escapedText); + } + else { + return getContextualType(attribute.parent); + } + } + // Return true if the given expression is possibly a discriminant value. We limit the kinds of + // expressions we check to those that don't depend on their contextual type in order not to cause + // recursive (and possibly infinite) invocations of getContextualType. + function isPossiblyDiscriminantValue(node) { + switch (node.kind) { + case 10 /* StringLiteral */: + case 8 /* NumericLiteral */: + case 9 /* BigIntLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: + case 102 /* TrueKeyword */: + case 87 /* FalseKeyword */: + case 96 /* NullKeyword */: + case 72 /* Identifier */: + case 141 /* UndefinedKeyword */: + return true; + case 189 /* PropertyAccessExpression */: + case 195 /* ParenthesizedExpression */: + return isPossiblyDiscriminantValue(node.expression); + case 270 /* JsxExpression */: + return !node.expression || isPossiblyDiscriminantValue(node.expression); + } + return false; + } + function discriminateContextualTypeByObjectMembers(node, contextualType) { + return discriminateTypeByDiscriminableItems(contextualType, ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 275 /* PropertyAssignment */ && isPossiblyDiscriminantValue(p.initializer) && isDiscriminantProperty(contextualType, p.symbol.escapedName); }), function (prop) { return [function () { return checkExpression(prop.initializer); }, prop.symbol.escapedName]; }), isTypeAssignableTo, contextualType); + } + function discriminateContextualTypeByJSXAttributes(node, contextualType) { + return discriminateTypeByDiscriminableItems(contextualType, ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 267 /* JsxAttribute */ && isDiscriminantProperty(contextualType, p.symbol.escapedName) && (!p.initializer || isPossiblyDiscriminantValue(p.initializer)); }), function (prop) { return [!prop.initializer ? (function () { return trueType; }) : (function () { return checkExpression(prop.initializer); }), prop.symbol.escapedName]; }), isTypeAssignableTo, contextualType); + } + // Return the contextual type for a given expression node. During overload resolution, a contextual type may temporarily + // be "pushed" onto a node using the contextualType property. + function getApparentTypeOfContextualType(node) { + var contextualType = getContextualType(node); + contextualType = contextualType && mapType(contextualType, getApparentType); + if (contextualType && contextualType.flags & 1048576 /* Union */) { + if (ts.isObjectLiteralExpression(node)) { + return discriminateContextualTypeByObjectMembers(node, contextualType); + } + else if (ts.isJsxAttributes(node)) { + return discriminateContextualTypeByJSXAttributes(node, contextualType); + } + } + return contextualType; + } + /** + * Woah! Do you really want to use this function? + * + * Unless you're trying to get the *non-apparent* type for a + * value-literal type or you're authoring relevant portions of this algorithm, + * you probably meant to use 'getApparentTypeOfContextualType'. + * Otherwise this may not be very useful. + * + * In cases where you *are* working on this function, you should understand + * when it is appropriate to use 'getContextualType' and 'getApparentTypeOfContextualType'. + * + * - Use 'getContextualType' when you are simply going to propagate the result to the expression. + * - Use 'getApparentTypeOfContextualType' when you're going to need the members of the type. + * + * @param node the expression whose contextual type will be returned. + * @returns the contextual type of an expression. + */ + function getContextualType(node) { + if (node.flags & 8388608 /* InWithStatement */) { + // We cannot answer semantic questions within a with block, do not proceed any further + return undefined; + } + if (node.contextualType) { + return node.contextualType; + } + var parent = node.parent; + switch (parent.kind) { + case 237 /* VariableDeclaration */: + case 151 /* Parameter */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 186 /* BindingElement */: + return getContextualTypeForInitializerExpression(node); + case 197 /* ArrowFunction */: + case 230 /* ReturnStatement */: + return getContextualTypeForReturnExpression(node); + case 207 /* YieldExpression */: + return getContextualTypeForYieldOperand(parent); + case 201 /* AwaitExpression */: + return getContextualTypeForAwaitOperand(parent); + case 191 /* CallExpression */: + case 192 /* NewExpression */: + return getContextualTypeForArgument(parent, node); + case 194 /* TypeAssertionExpression */: + case 212 /* AsExpression */: + return getTypeFromTypeNode(parent.type); + case 204 /* BinaryExpression */: + return getContextualTypeForBinaryOperand(node); + case 275 /* PropertyAssignment */: + case 276 /* ShorthandPropertyAssignment */: + return getContextualTypeForObjectLiteralElement(parent); + case 277 /* SpreadAssignment */: + return getApparentTypeOfContextualType(parent.parent); + case 187 /* ArrayLiteralExpression */: { + var arrayLiteral = parent; + var type = getApparentTypeOfContextualType(arrayLiteral); + return getContextualTypeForElementExpression(type, ts.indexOfNode(arrayLiteral.elements, node)); + } + case 205 /* ConditionalExpression */: + return getContextualTypeForConditionalOperand(node); + case 216 /* TemplateSpan */: + ts.Debug.assert(parent.parent.kind === 206 /* TemplateExpression */); + return getContextualTypeForSubstitutionExpression(parent.parent, node); + case 195 /* ParenthesizedExpression */: { + // Like in `checkParenthesizedExpression`, an `/** @type {xyz} */` comment before a parenthesized expression acts as a type cast. + var tag = ts.isInJSFile(parent) ? ts.getJSDocTypeTag(parent) : undefined; + return tag ? getTypeFromTypeNode(tag.typeExpression.type) : getContextualType(parent); + } + case 270 /* JsxExpression */: + return getContextualTypeForJsxExpression(parent); + case 267 /* JsxAttribute */: + case 269 /* JsxSpreadAttribute */: + return getContextualTypeForJsxAttribute(parent); + case 262 /* JsxOpeningElement */: + case 261 /* JsxSelfClosingElement */: + return getContextualJsxElementAttributesType(parent); + } + return undefined; + } + function getContextualMapper(node) { + var ancestor = ts.findAncestor(node, function (n) { return !!n.contextualMapper; }); + return ancestor ? ancestor.contextualMapper : identityMapper; + } + function getContextualJsxElementAttributesType(node) { + if (ts.isJsxOpeningElement(node) && node.parent.contextualType) { + // Contextually applied type is moved from attributes up to the outer jsx attributes so when walking up from the children they get hit + // _However_ to hit them from the _attributes_ we must look for them here; otherwise we'll used the declared type + // (as below) instead! + return node.parent.contextualType; + } + return getContextualTypeForArgumentAtIndex(node, 0); + } + function getEffectiveFirstArgumentForJsxSignature(signature, node) { + return getJsxReferenceKind(node) !== 0 /* Component */ ? getJsxPropsTypeFromCallSignature(signature, node) : getJsxPropsTypeFromClassType(signature, node); + } + function getJsxPropsTypeFromCallSignature(sig, context) { + var propsType = getTypeOfFirstParameterOfSignatureWithFallback(sig, emptyObjectType); + propsType = getJsxManagedAttributesFromLocatedAttributes(context, getJsxNamespaceAt(context), propsType); + var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes, context); + if (intrinsicAttribs !== errorType) { + propsType = intersectTypes(intrinsicAttribs, propsType); + } + return propsType; + } + function getJsxPropsTypeForSignatureFromMember(sig, forcedLookupLocation) { + var instanceType = getReturnTypeOfSignature(sig); + return isTypeAny(instanceType) ? instanceType : getTypeOfPropertyOfType(instanceType, forcedLookupLocation); + } + function getStaticTypeOfReferencedJsxConstructor(context) { + if (isJsxIntrinsicIdentifier(context.tagName)) { + var result = getIntrinsicAttributesTypeFromJsxOpeningLikeElement(context); + var fakeSignature = createSignatureForJSXIntrinsic(context, result); + return getOrCreateTypeFromSignature(fakeSignature); + } + var tagType = checkExpressionCached(context.tagName); + if (tagType.flags & 128 /* StringLiteral */) { + var result = getIntrinsicAttributesTypeFromStringLiteralType(tagType, context); + if (!result) { + return errorType; + } + var fakeSignature = createSignatureForJSXIntrinsic(context, result); + return getOrCreateTypeFromSignature(fakeSignature); + } + return tagType; + } + function getJsxManagedAttributesFromLocatedAttributes(context, ns, attributesType) { + var managedSym = getJsxLibraryManagedAttributes(ns); + if (managedSym) { + var declaredManagedType = getDeclaredTypeOfSymbol(managedSym); + var ctorType = getStaticTypeOfReferencedJsxConstructor(context); + if (ts.length(declaredManagedType.typeParameters) >= 2) { + var args = fillMissingTypeArguments([ctorType, attributesType], declaredManagedType.typeParameters, 2, ts.isInJSFile(context)); + return createTypeReference(declaredManagedType, args); + } + else if (ts.length(declaredManagedType.aliasTypeArguments) >= 2) { + var args = fillMissingTypeArguments([ctorType, attributesType], declaredManagedType.aliasTypeArguments, 2, ts.isInJSFile(context)); + return getTypeAliasInstantiation(declaredManagedType.aliasSymbol, args); + } + } + return attributesType; + } + function getJsxPropsTypeFromClassType(sig, context) { + var ns = getJsxNamespaceAt(context); + var forcedLookupLocation = getJsxElementPropertiesName(ns); + var attributesType = forcedLookupLocation === undefined + // If there is no type ElementAttributesProperty, return the type of the first parameter of the signature, which should be the props type + ? getTypeOfFirstParameterOfSignatureWithFallback(sig, emptyObjectType) + : forcedLookupLocation === "" + // If there is no e.g. 'props' member in ElementAttributesProperty, use the element class type instead + ? getReturnTypeOfSignature(sig) + // Otherwise get the type of the property on the signature return type + : getJsxPropsTypeForSignatureFromMember(sig, forcedLookupLocation); + if (!attributesType) { + // There is no property named 'props' on this instance type + if (!!forcedLookupLocation && !!ts.length(context.attributes.properties)) { + error(context, ts.Diagnostics.JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property, ts.unescapeLeadingUnderscores(forcedLookupLocation)); + } + return emptyObjectType; + } + attributesType = getJsxManagedAttributesFromLocatedAttributes(context, ns, attributesType); + if (isTypeAny(attributesType)) { + // Props is of type 'any' or unknown + return attributesType; + } + else { + // Normal case -- add in IntrinsicClassElements and IntrinsicElements + var apparentAttributesType = attributesType; + var intrinsicClassAttribs = getJsxType(JsxNames.IntrinsicClassAttributes, context); + if (intrinsicClassAttribs !== errorType) { + var typeParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(intrinsicClassAttribs.symbol); + var hostClassType = getReturnTypeOfSignature(sig); + apparentAttributesType = intersectTypes(typeParams + ? createTypeReference(intrinsicClassAttribs, fillMissingTypeArguments([hostClassType], typeParams, getMinTypeArgumentCount(typeParams), ts.isInJSFile(context))) + : intrinsicClassAttribs, apparentAttributesType); + } + var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes, context); + if (intrinsicAttribs !== errorType) { + apparentAttributesType = intersectTypes(intrinsicAttribs, apparentAttributesType); + } + return apparentAttributesType; + } + } + // If the given type is an object or union type with a single signature, and if that signature has at + // least as many parameters as the given function, return the signature. Otherwise return undefined. + function getContextualCallSignature(type, node) { + var signatures = getSignaturesOfType(type, 0 /* Call */); + if (signatures.length === 1) { + var signature = signatures[0]; + if (!isAritySmaller(signature, node)) { + return signature; + } + } + } + /** If the contextual signature has fewer parameters than the function expression, do not use it */ + function isAritySmaller(signature, target) { + var targetParameterCount = 0; + for (; targetParameterCount < target.parameters.length; targetParameterCount++) { + var param = target.parameters[targetParameterCount]; + if (param.initializer || param.questionToken || param.dotDotDotToken || isJSDocOptionalParameter(param)) { + break; + } + } + if (target.parameters.length && ts.parameterIsThisKeyword(target.parameters[0])) { + targetParameterCount--; + } + return !hasEffectiveRestParameter(signature) && getParameterCount(signature) < targetParameterCount; + } + function isFunctionExpressionOrArrowFunction(node) { + return node.kind === 196 /* FunctionExpression */ || node.kind === 197 /* ArrowFunction */; + } + function getContextualSignatureForFunctionLikeDeclaration(node) { + // Only function expressions, arrow functions, and object literal methods are contextually typed. + return isFunctionExpressionOrArrowFunction(node) || ts.isObjectLiteralMethod(node) + ? getContextualSignature(node) + : undefined; + } + function getContextualTypeForFunctionLikeDeclaration(node) { + return ts.isObjectLiteralMethod(node) ? + getContextualTypeForObjectLiteralMethod(node) : + getApparentTypeOfContextualType(node); + } + // Return the contextual signature for a given expression node. A contextual type provides a + // contextual signature if it has a single call signature and if that call signature is non-generic. + // If the contextual type is a union type, get the signature from each type possible and if they are + // all identical ignoring their return type, the result is same signature but with return type as + // union type of return types from these signatures + function getContextualSignature(node) { + ts.Debug.assert(node.kind !== 156 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + var typeTagSignature = getSignatureOfTypeTag(node); + if (typeTagSignature) { + return typeTagSignature; + } + var type = getContextualTypeForFunctionLikeDeclaration(node); + if (!type) { + return undefined; + } + if (!(type.flags & 1048576 /* Union */)) { + return getContextualCallSignature(type, node); + } + var signatureList; + var types = type.types; + for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { + var current = types_14[_i]; + var signature = getContextualCallSignature(current, node); + if (signature) { + if (!signatureList) { + // This signature will contribute to contextual union signature + signatureList = [signature]; + } + else if (!compareSignaturesIdentical(signatureList[0], signature, /*partialMatch*/ false, /*ignoreThisTypes*/ true, /*ignoreReturnTypes*/ true, compareTypesIdentical)) { + // Signatures aren't identical, do not use + return undefined; + } + else { + // Use this signature for contextual union signature + signatureList.push(signature); + } + } + } + // Result is union of signatures collected (return type is union of return types of this signature set) + var result; + if (signatureList) { + result = cloneSignature(signatureList[0]); + result.unionSignatures = signatureList; + } + return result; + } + function checkSpreadExpression(node, checkMode) { + if (languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) { + checkExternalEmitHelpers(node, 1536 /* SpreadIncludes */); + } + var arrayOrIterableType = checkExpression(node.expression, checkMode); + return checkIteratedTypeOrElementType(arrayOrIterableType, node.expression, /*allowStringInput*/ false, /*allowAsyncIterables*/ false); + } + function hasDefaultValue(node) { + return (node.kind === 186 /* BindingElement */ && !!node.initializer) || + (node.kind === 204 /* BinaryExpression */ && node.operatorToken.kind === 59 /* EqualsToken */); + } + function checkArrayLiteral(node, checkMode, forceTuple) { + var elements = node.elements; + var elementCount = elements.length; + var hasNonEndingSpreadElement = false; + var elementTypes = []; + var inDestructuringPattern = ts.isAssignmentTarget(node); + var contextualType = getApparentTypeOfContextualType(node); + for (var index = 0; index < elementCount; index++) { + var e = elements[index]; + if (inDestructuringPattern && e.kind === 208 /* SpreadElement */) { + // Given the following situation: + // var c: {}; + // [...c] = ["", 0]; + // + // c is represented in the tree as a spread element in an array literal. + // But c really functions as a rest element, and its purpose is to provide + // a contextual type for the right hand side of the assignment. Therefore, + // instead of calling checkExpression on "...c", which will give an error + // if c is not iterable/array-like, we need to act as if we are trying to + // get the contextual element type from it. So we do something similar to + // getContextualTypeForElementExpression, which will crucially not error + // if there is no index type / iterated type. + var restArrayType = checkExpression(e.expression, checkMode, forceTuple); + var restElementType = getIndexTypeOfType(restArrayType, 1 /* Number */) || + getIteratedTypeOrElementType(restArrayType, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterables*/ false, /*checkAssignability*/ false); + if (restElementType) { + elementTypes.push(restElementType); + } + } + else { + var elementContextualType = getContextualTypeForElementExpression(contextualType, index); + var type = checkExpressionForMutableLocation(e, checkMode, elementContextualType, forceTuple); + elementTypes.push(type); + } + if (index < elementCount - 1 && e.kind === 208 /* SpreadElement */) { + hasNonEndingSpreadElement = true; + } + } + if (!hasNonEndingSpreadElement) { + var hasRestElement = elementCount > 0 && elements[elementCount - 1].kind === 208 /* SpreadElement */; + var minLength = elementCount - (hasRestElement ? 1 : 0); + // If array literal is actually a destructuring pattern, mark it as an implied type. We do this such + // that we get the same behavior for "var [x, y] = []" and "[x, y] = []". + var tupleResult = void 0; + if (inDestructuringPattern && minLength > 0) { + var type = cloneTypeReference(createTupleType(elementTypes, minLength, hasRestElement)); + type.pattern = node; + return type; + } + else if (tupleResult = getArrayLiteralTupleTypeIfApplicable(elementTypes, contextualType, hasRestElement, elementCount)) { + return tupleResult; + } + else if (forceTuple) { + return createTupleType(elementTypes, minLength, hasRestElement); + } + } + return getArrayLiteralType(elementTypes, 2 /* Subtype */); + } + function getArrayLiteralTupleTypeIfApplicable(elementTypes, contextualType, hasRestElement, elementCount) { + if (elementCount === void 0) { elementCount = elementTypes.length; } + // Infer a tuple type when the contextual type is or contains a tuple-like type + if (contextualType && forEachType(contextualType, isTupleLikeType)) { + var minLength = elementCount - (hasRestElement ? 1 : 0); + var pattern = contextualType.pattern; + // If array literal is contextually typed by a binding pattern or an assignment pattern, pad the resulting + // tuple type with the corresponding binding or assignment element types to make the lengths equal. + if (!hasRestElement && pattern && (pattern.kind === 185 /* ArrayBindingPattern */ || pattern.kind === 187 /* ArrayLiteralExpression */)) { + var patternElements = pattern.elements; + for (var i = elementCount; i < patternElements.length; i++) { + var e = patternElements[i]; + if (hasDefaultValue(e)) { + elementTypes.push(contextualType.typeArguments[i]); + } + else if (i < patternElements.length - 1 || !(e.kind === 186 /* BindingElement */ && e.dotDotDotToken || e.kind === 208 /* SpreadElement */)) { + if (e.kind !== 210 /* OmittedExpression */) { + error(e, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); + } + elementTypes.push(strictNullChecks ? implicitNeverType : undefinedWideningType); + } + } + } + return createTupleType(elementTypes, minLength, hasRestElement); + } + } + function getArrayLiteralType(elementTypes, unionReduction) { + if (unionReduction === void 0) { unionReduction = 1 /* Literal */; } + return createArrayType(elementTypes.length ? + getUnionType(elementTypes, unionReduction) : + strictNullChecks ? implicitNeverType : undefinedWideningType); + } + function isNumericName(name) { + switch (name.kind) { + case 149 /* ComputedPropertyName */: + return isNumericComputedName(name); + case 72 /* Identifier */: + return isNumericLiteralName(name.escapedText); + case 8 /* NumericLiteral */: + case 10 /* StringLiteral */: + return isNumericLiteralName(name.text); + default: + return false; + } + } + function isNumericComputedName(name) { + // It seems odd to consider an expression of type Any to result in a numeric name, + // but this behavior is consistent with checkIndexedAccess + return isTypeAssignableToKind(checkComputedPropertyName(name), 296 /* NumberLike */); + } + function isInfinityOrNaNString(name) { + return name === "Infinity" || name === "-Infinity" || name === "NaN"; + } + function isNumericLiteralName(name) { + // The intent of numeric names is that + // - they are names with text in a numeric form, and that + // - setting properties/indexing with them is always equivalent to doing so with the numeric literal 'numLit', + // acquired by applying the abstract 'ToNumber' operation on the name's text. + // + // The subtlety is in the latter portion, as we cannot reliably say that anything that looks like a numeric literal is a numeric name. + // In fact, it is the case that the text of the name must be equal to 'ToString(numLit)' for this to hold. + // + // Consider the property name '"0xF00D"'. When one indexes with '0xF00D', they are actually indexing with the value of 'ToString(0xF00D)' + // according to the ECMAScript specification, so it is actually as if the user indexed with the string '"61453"'. + // Thus, the text of all numeric literals equivalent to '61543' such as '0xF00D', '0xf00D', '0170015', etc. are not valid numeric names + // because their 'ToString' representation is not equal to their original text. + // This is motivated by ECMA-262 sections 9.3.1, 9.8.1, 11.1.5, and 11.2.1. + // + // Here, we test whether 'ToString(ToNumber(name))' is exactly equal to 'name'. + // The '+' prefix operator is equivalent here to applying the abstract ToNumber operation. + // Applying the 'toString()' method on a number gives us the abstract ToString operation on a number. + // + // Note that this accepts the values 'Infinity', '-Infinity', and 'NaN', and that this is intentional. + // This is desired behavior, because when indexing with them as numeric entities, you are indexing + // with the strings '"Infinity"', '"-Infinity"', and '"NaN"' respectively. + return (+name).toString() === name; + } + function checkComputedPropertyName(node) { + var links = getNodeLinks(node.expression); + if (!links.resolvedType) { + links.resolvedType = checkExpression(node.expression); + // This will allow types number, string, symbol or any. It will also allow enums, the unknown + // type, and any union of these types (like string | number). + if (links.resolvedType.flags & 98304 /* Nullable */ || + !isTypeAssignableToKind(links.resolvedType, 132 /* StringLike */ | 296 /* NumberLike */ | 12288 /* ESSymbolLike */) && + !isTypeAssignableTo(links.resolvedType, stringNumberSymbolType)) { + error(node, ts.Diagnostics.A_computed_property_name_must_be_of_type_string_number_symbol_or_any); + } + else { + checkThatExpressionIsProperSymbolReference(node.expression, links.resolvedType, /*reportError*/ true); + } + } + return links.resolvedType; + } + function getObjectLiteralIndexInfo(propertyNodes, offset, properties, kind) { + var propTypes = []; + for (var i = 0; i < properties.length; i++) { + if (kind === 0 /* String */ || isNumericName(propertyNodes[i + offset].name)) { + propTypes.push(getTypeOfSymbol(properties[i])); + } + } + var unionType = propTypes.length ? getUnionType(propTypes, 2 /* Subtype */) : undefinedType; + return createIndexInfo(unionType, /*isReadonly*/ false); + } + function getImmediateAliasedSymbol(symbol) { + ts.Debug.assert((symbol.flags & 2097152 /* Alias */) !== 0, "Should only get Alias here."); + var links = getSymbolLinks(symbol); + if (!links.immediateTarget) { + var node = getDeclarationOfAliasSymbol(symbol); + if (!node) + return ts.Debug.fail(); + links.immediateTarget = getTargetOfAliasDeclaration(node, /*dontRecursivelyResolve*/ true); + } + return links.immediateTarget; + } + function checkObjectLiteral(node, checkMode) { + var inDestructuringPattern = ts.isAssignmentTarget(node); + // Grammar checking + checkGrammarObjectLiteralExpression(node, inDestructuringPattern); + var propertiesTable; + var propertiesArray = []; + var spread = emptyObjectType; + var propagatedFlags = 0; + var contextualType = getApparentTypeOfContextualType(node); + var contextualTypeHasPattern = contextualType && contextualType.pattern && + (contextualType.pattern.kind === 184 /* ObjectBindingPattern */ || contextualType.pattern.kind === 188 /* ObjectLiteralExpression */); + var isInJavascript = ts.isInJSFile(node) && !ts.isInJsonFile(node); + var enumTag = ts.getJSDocEnumTag(node); + var isJSObjectLiteral = !contextualType && isInJavascript && !enumTag; + var typeFlags = 0; + var patternWithComputedProperties = false; + var hasComputedStringProperty = false; + var hasComputedNumberProperty = false; + propertiesTable = ts.createSymbolTable(); + var offset = 0; + for (var i = 0; i < node.properties.length; i++) { + var memberDecl = node.properties[i]; + var member = getSymbolOfNode(memberDecl); + var computedNameType = memberDecl.name && memberDecl.name.kind === 149 /* ComputedPropertyName */ && !ts.isWellKnownSymbolSyntactically(memberDecl.name.expression) ? + checkComputedPropertyName(memberDecl.name) : undefined; + if (memberDecl.kind === 275 /* PropertyAssignment */ || + memberDecl.kind === 276 /* ShorthandPropertyAssignment */ || + ts.isObjectLiteralMethod(memberDecl)) { + var type = memberDecl.kind === 275 /* PropertyAssignment */ ? checkPropertyAssignment(memberDecl, checkMode) : + memberDecl.kind === 276 /* ShorthandPropertyAssignment */ ? checkExpressionForMutableLocation(memberDecl.name, checkMode) : + checkObjectLiteralMethod(memberDecl, checkMode); + if (isInJavascript) { + var jsDocType = getTypeForDeclarationFromJSDocComment(memberDecl); + if (jsDocType) { + checkTypeAssignableTo(type, jsDocType, memberDecl); + type = jsDocType; + } + else if (enumTag && enumTag.typeExpression) { + checkTypeAssignableTo(type, getTypeFromTypeNode(enumTag.typeExpression), memberDecl); + } + } + typeFlags |= type.flags; + var nameType = computedNameType && computedNameType.flags & 8576 /* StringOrNumberLiteralOrUnique */ ? + computedNameType : undefined; + var prop = nameType ? + createSymbol(4 /* Property */ | member.flags, getLateBoundNameFromType(nameType), 1024 /* Late */) : + createSymbol(4 /* Property */ | member.flags, member.escapedName); + if (nameType) { + prop.nameType = nameType; + } + if (inDestructuringPattern) { + // If object literal is an assignment pattern and if the assignment pattern specifies a default value + // for the property, make the property optional. + var isOptional = (memberDecl.kind === 275 /* PropertyAssignment */ && hasDefaultValue(memberDecl.initializer)) || + (memberDecl.kind === 276 /* ShorthandPropertyAssignment */ && memberDecl.objectAssignmentInitializer); + if (isOptional) { + prop.flags |= 16777216 /* Optional */; + } + } + else if (contextualTypeHasPattern && !(ts.getObjectFlags(contextualType) & 512 /* ObjectLiteralPatternWithComputedProperties */)) { + // If object literal is contextually typed by the implied type of a binding pattern, and if the + // binding pattern specifies a default value for the property, make the property optional. + var impliedProp = getPropertyOfType(contextualType, member.escapedName); + if (impliedProp) { + prop.flags |= impliedProp.flags & 16777216 /* Optional */; + } + else if (!compilerOptions.suppressExcessPropertyErrors && !getIndexInfoOfType(contextualType, 0 /* String */)) { + error(memberDecl.name, ts.Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(member), typeToString(contextualType)); + } + } + prop.declarations = member.declarations; + prop.parent = member.parent; + if (member.valueDeclaration) { + prop.valueDeclaration = member.valueDeclaration; + } + prop.type = type; + prop.target = member; + member = prop; + } + else if (memberDecl.kind === 277 /* SpreadAssignment */) { + if (languageVersion < 2 /* ES2015 */) { + checkExternalEmitHelpers(memberDecl, 2 /* Assign */); + } + if (propertiesArray.length > 0) { + spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, propagatedFlags, 32768 /* FreshLiteral */); + propertiesArray = []; + propertiesTable = ts.createSymbolTable(); + hasComputedStringProperty = false; + hasComputedNumberProperty = false; + typeFlags = 0; + } + var type = checkExpression(memberDecl.expression); + if (!isValidSpreadType(type)) { + error(memberDecl, ts.Diagnostics.Spread_types_may_only_be_created_from_object_types); + return errorType; + } + spread = getSpreadType(spread, type, node.symbol, propagatedFlags, 32768 /* FreshLiteral */); + offset = i + 1; + continue; + } + else { + // TypeScript 1.0 spec (April 2014) + // A get accessor declaration is processed in the same manner as + // an ordinary function declaration(section 6.1) with no parameters. + // A set accessor declaration is processed in the same manner + // as an ordinary function declaration with a single parameter and a Void return type. + ts.Debug.assert(memberDecl.kind === 158 /* GetAccessor */ || memberDecl.kind === 159 /* SetAccessor */); + checkNodeDeferred(memberDecl); + } + if (computedNameType && !(computedNameType.flags & 8576 /* StringOrNumberLiteralOrUnique */)) { + if (isTypeAssignableTo(computedNameType, stringNumberSymbolType)) { + if (isTypeAssignableTo(computedNameType, numberType)) { + hasComputedNumberProperty = true; + } + else { + hasComputedStringProperty = true; + } + if (inDestructuringPattern) { + patternWithComputedProperties = true; + } + } + } + else { + propertiesTable.set(member.escapedName, member); + } + propertiesArray.push(member); + } + // If object literal is contextually typed by the implied type of a binding pattern, augment the result + // type with those properties for which the binding pattern specifies a default value. + if (contextualTypeHasPattern) { + for (var _i = 0, _a = getPropertiesOfType(contextualType); _i < _a.length; _i++) { + var prop = _a[_i]; + if (!propertiesTable.get(prop.escapedName) && !(spread && getPropertyOfType(spread, prop.escapedName))) { + if (!(prop.flags & 16777216 /* Optional */)) { + error(prop.valueDeclaration || prop.bindingElement, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); + } + propertiesTable.set(prop.escapedName, prop); + propertiesArray.push(prop); + } + } + } + if (spread !== emptyObjectType) { + if (propertiesArray.length > 0) { + spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, propagatedFlags, 32768 /* FreshLiteral */); + } + return spread; + } + return createObjectLiteralType(); + function createObjectLiteralType() { + var stringIndexInfo = hasComputedStringProperty ? getObjectLiteralIndexInfo(node.properties, offset, propertiesArray, 0 /* String */) : undefined; + var numberIndexInfo = hasComputedNumberProperty ? getObjectLiteralIndexInfo(node.properties, offset, propertiesArray, 1 /* Number */) : undefined; + var result = createAnonymousType(node.symbol, propertiesTable, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); + result.flags |= 268435456 /* ContainsObjectLiteral */ | typeFlags & 939524096 /* PropagatingFlags */; + result.objectFlags |= 128 /* ObjectLiteral */ | freshObjectLiteralFlag; + if (isJSObjectLiteral) { + result.objectFlags |= 16384 /* JSLiteral */; + } + if (patternWithComputedProperties) { + result.objectFlags |= 512 /* ObjectLiteralPatternWithComputedProperties */; + } + if (inDestructuringPattern) { + result.pattern = node; + } + propagatedFlags |= result.flags & 939524096 /* PropagatingFlags */; + return result; + } + } + function isValidSpreadType(type) { + return !!(type.flags & (3 /* AnyOrUnknown */ | 67108864 /* NonPrimitive */ | 524288 /* Object */ | 58982400 /* InstantiableNonPrimitive */) || + getFalsyFlags(type) & 117632 /* DefinitelyFalsy */ && isValidSpreadType(removeDefinitelyFalsyTypes(type)) || + type.flags & 3145728 /* UnionOrIntersection */ && ts.every(type.types, isValidSpreadType)); + } + function checkJsxSelfClosingElementDeferred(node) { + checkJsxOpeningLikeElementOrOpeningFragment(node); + } + function checkJsxSelfClosingElement(node, _checkMode) { + checkNodeDeferred(node); + return getJsxElementTypeAt(node) || anyType; + } + function checkJsxElementDeferred(node) { + // Check attributes + checkJsxOpeningLikeElementOrOpeningFragment(node.openingElement); + // Perform resolution on the closing tag so that rename/go to definition/etc work + if (isJsxIntrinsicIdentifier(node.closingElement.tagName)) { + getIntrinsicTagSymbol(node.closingElement); + } + else { + checkExpression(node.closingElement.tagName); + } + checkJsxChildren(node); + } + function checkJsxElement(node, _checkMode) { + checkNodeDeferred(node); + return getJsxElementTypeAt(node) || anyType; + } + function checkJsxFragment(node) { + checkJsxOpeningLikeElementOrOpeningFragment(node.openingFragment); + if (compilerOptions.jsx === 2 /* React */ && (compilerOptions.jsxFactory || ts.getSourceFileOfNode(node).pragmas.has("jsx"))) { + error(node, compilerOptions.jsxFactory + ? ts.Diagnostics.JSX_fragment_is_not_supported_when_using_jsxFactory + : ts.Diagnostics.JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma); + } + checkJsxChildren(node); + return getJsxElementTypeAt(node) || anyType; + } + /** + * Returns true iff the JSX element name would be a valid JS identifier, ignoring restrictions about keywords not being identifiers + */ + function isUnhyphenatedJsxName(name) { + // - is the only character supported in JSX attribute names that isn't valid in JavaScript identifiers + return !ts.stringContains(name, "-"); + } + /** + * Returns true iff React would emit this tag name as a string rather than an identifier or qualified name + */ + function isJsxIntrinsicIdentifier(tagName) { + return tagName.kind === 72 /* Identifier */ && ts.isIntrinsicJsxName(tagName.escapedText); + } + function checkJsxAttribute(node, checkMode) { + return node.initializer + ? checkExpressionForMutableLocation(node.initializer, checkMode) + : trueType; // is sugar for + } + /** + * Get attributes type of the JSX opening-like element. The result is from resolving "attributes" property of the opening-like element. + * + * @param openingLikeElement a JSX opening-like element + * @param filter a function to remove attributes that will not participate in checking whether attributes are assignable + * @return an anonymous type (similar to the one returned by checkObjectLiteral) in which its properties are attributes property. + * @remarks Because this function calls getSpreadType, it needs to use the same checks as checkObjectLiteral, + * which also calls getSpreadType. + */ + function createJsxAttributesTypeFromAttributesProperty(openingLikeElement, checkMode) { + var attributes = openingLikeElement.attributes; + var attributesTable = ts.createSymbolTable(); + var spread = emptyJsxObjectType; + var hasSpreadAnyType = false; + var typeToIntersect; + var explicitlySpecifyChildrenAttribute = false; + var typeFlags = 0; + var objectFlags = 4096 /* JsxAttributes */; + var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(openingLikeElement)); + for (var _i = 0, _a = attributes.properties; _i < _a.length; _i++) { + var attributeDecl = _a[_i]; + var member = attributeDecl.symbol; + if (ts.isJsxAttribute(attributeDecl)) { + var exprType = checkJsxAttribute(attributeDecl, checkMode); + typeFlags |= exprType.flags & 939524096 /* PropagatingFlags */; + var attributeSymbol = createSymbol(4 /* Property */ | 33554432 /* Transient */ | member.flags, member.escapedName); + attributeSymbol.declarations = member.declarations; + attributeSymbol.parent = member.parent; + if (member.valueDeclaration) { + attributeSymbol.valueDeclaration = member.valueDeclaration; + } + attributeSymbol.type = exprType; + attributeSymbol.target = member; + attributesTable.set(attributeSymbol.escapedName, attributeSymbol); + if (attributeDecl.name.escapedText === jsxChildrenPropertyName) { + explicitlySpecifyChildrenAttribute = true; + } + } + else { + ts.Debug.assert(attributeDecl.kind === 269 /* JsxSpreadAttribute */); + if (attributesTable.size > 0) { + spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, typeFlags, objectFlags); + attributesTable = ts.createSymbolTable(); + } + var exprType = checkExpressionCached(attributeDecl.expression, checkMode); + if (isTypeAny(exprType)) { + hasSpreadAnyType = true; + } + if (isValidSpreadType(exprType)) { + spread = getSpreadType(spread, exprType, attributes.symbol, typeFlags, objectFlags); + } + else { + typeToIntersect = typeToIntersect ? getIntersectionType([typeToIntersect, exprType]) : exprType; + } + } + } + if (!hasSpreadAnyType) { + if (attributesTable.size > 0) { + spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, typeFlags, objectFlags); + } + } + // Handle children attribute + var parent = openingLikeElement.parent.kind === 260 /* JsxElement */ ? openingLikeElement.parent : undefined; + // We have to check that openingElement of the parent is the one we are visiting as this may not be true for selfClosingElement + if (parent && parent.openingElement === openingLikeElement && parent.children.length > 0) { + var childrenTypes = checkJsxChildren(parent, checkMode); + if (!hasSpreadAnyType && jsxChildrenPropertyName && jsxChildrenPropertyName !== "") { + // Error if there is a attribute named "children" explicitly specified and children element. + // This is because children element will overwrite the value from attributes. + // Note: we will not warn "children" attribute overwritten if "children" attribute is specified in object spread. + if (explicitlySpecifyChildrenAttribute) { + error(attributes, ts.Diagnostics._0_are_specified_twice_The_attribute_named_0_will_be_overwritten, ts.unescapeLeadingUnderscores(jsxChildrenPropertyName)); + } + var contextualType = getApparentTypeOfContextualType(openingLikeElement.attributes); + var childrenContextualType = contextualType && getTypeOfPropertyOfContextualType(contextualType, jsxChildrenPropertyName); + // If there are children in the body of JSX element, create dummy attribute "children" with the union of children types so that it will pass the attribute checking process + var childrenPropSymbol = createSymbol(4 /* Property */ | 33554432 /* Transient */, jsxChildrenPropertyName); + childrenPropSymbol.type = childrenTypes.length === 1 ? + childrenTypes[0] : + (getArrayLiteralTupleTypeIfApplicable(childrenTypes, childrenContextualType, /*hasRestElement*/ false) || createArrayType(getUnionType(childrenTypes))); + var childPropMap = ts.createSymbolTable(); + childPropMap.set(jsxChildrenPropertyName, childrenPropSymbol); + spread = getSpreadType(spread, createAnonymousType(attributes.symbol, childPropMap, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined), attributes.symbol, typeFlags, objectFlags); + } + } + if (hasSpreadAnyType) { + return anyType; + } + if (typeToIntersect && spread !== emptyJsxObjectType) { + return getIntersectionType([typeToIntersect, spread]); + } + return typeToIntersect || (spread === emptyJsxObjectType ? createJsxAttributesType() : spread); + /** + * Create anonymous type from given attributes symbol table. + * @param symbol a symbol of JsxAttributes containing attributes corresponding to attributesTable + * @param attributesTable a symbol table of attributes property + */ + function createJsxAttributesType() { + objectFlags |= freshObjectLiteralFlag; + var result = createAnonymousType(attributes.symbol, attributesTable, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined); + result.flags |= 268435456 /* ContainsObjectLiteral */ | typeFlags; + result.objectFlags |= 128 /* ObjectLiteral */ | objectFlags; + return result; + } + } + function checkJsxChildren(node, checkMode) { + var childrenTypes = []; + for (var _i = 0, _a = node.children; _i < _a.length; _i++) { + var child = _a[_i]; + // In React, JSX text that contains only whitespaces will be ignored so we don't want to type-check that + // because then type of children property will have constituent of string type. + if (child.kind === 11 /* JsxText */) { + if (!child.containsOnlyWhiteSpaces) { + childrenTypes.push(stringType); + } + } + else { + childrenTypes.push(checkExpressionForMutableLocation(child, checkMode)); + } + } + return childrenTypes; + } + /** + * Check attributes property of opening-like element. This function is called during chooseOverload to get call signature of a JSX opening-like element. + * (See "checkApplicableSignatureForJsxOpeningLikeElement" for how the function is used) + * @param node a JSXAttributes to be resolved of its type + */ + function checkJsxAttributes(node, checkMode) { + return createJsxAttributesTypeFromAttributesProperty(node.parent, checkMode); + } + function getJsxType(name, location) { + var namespace = getJsxNamespaceAt(location); + var exports = namespace && getExportsOfSymbol(namespace); + var typeSymbol = exports && getSymbol(exports, name, 67897832 /* Type */); + return typeSymbol ? getDeclaredTypeOfSymbol(typeSymbol) : errorType; + } + /** + * Looks up an intrinsic tag name and returns a symbol that either points to an intrinsic + * property (in which case nodeLinks.jsxFlags will be IntrinsicNamedElement) or an intrinsic + * string index signature (in which case nodeLinks.jsxFlags will be IntrinsicIndexedElement). + * May also return unknownSymbol if both of these lookups fail. + */ + function getIntrinsicTagSymbol(node) { + var links = getNodeLinks(node); + if (!links.resolvedSymbol) { + var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements, node); + if (intrinsicElementsType !== errorType) { + // Property case + if (!ts.isIdentifier(node.tagName)) + return ts.Debug.fail(); + var intrinsicProp = getPropertyOfType(intrinsicElementsType, node.tagName.escapedText); + if (intrinsicProp) { + links.jsxFlags |= 1 /* IntrinsicNamedElement */; + return links.resolvedSymbol = intrinsicProp; + } + // Intrinsic string indexer case + var indexSignatureType = getIndexTypeOfType(intrinsicElementsType, 0 /* String */); + if (indexSignatureType) { + links.jsxFlags |= 2 /* IntrinsicIndexedElement */; + return links.resolvedSymbol = intrinsicElementsType.symbol; + } + // Wasn't found + error(node, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.idText(node.tagName), "JSX." + JsxNames.IntrinsicElements); + return links.resolvedSymbol = unknownSymbol; + } + else { + if (noImplicitAny) { + error(node, ts.Diagnostics.JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists, ts.unescapeLeadingUnderscores(JsxNames.IntrinsicElements)); + } + return links.resolvedSymbol = unknownSymbol; + } + } + return links.resolvedSymbol; + } + function getJsxNamespaceAt(location) { + var links = location && getNodeLinks(location); + if (links && links.jsxNamespace) { + return links.jsxNamespace; + } + if (!links || links.jsxNamespace !== false) { + var namespaceName = getJsxNamespace(location); + var resolvedNamespace = resolveName(location, namespaceName, 1920 /* Namespace */, /*diagnosticMessage*/ undefined, namespaceName, /*isUse*/ false); + if (resolvedNamespace) { + var candidate = getSymbol(getExportsOfSymbol(resolveSymbol(resolvedNamespace)), JsxNames.JSX, 1920 /* Namespace */); + if (candidate) { + if (links) { + links.jsxNamespace = candidate; + } + return candidate; + } + if (links) { + links.jsxNamespace = false; + } + } + } + // JSX global fallback + return getGlobalSymbol(JsxNames.JSX, 1920 /* Namespace */, /*diagnosticMessage*/ undefined); // TODO: GH#18217 + } + /** + * Look into JSX namespace and then look for container with matching name as nameOfAttribPropContainer. + * Get a single property from that container if existed. Report an error if there are more than one property. + * + * @param nameOfAttribPropContainer a string of value JsxNames.ElementAttributesPropertyNameContainer or JsxNames.ElementChildrenAttributeNameContainer + * if other string is given or the container doesn't exist, return undefined. + */ + function getNameFromJsxElementAttributesContainer(nameOfAttribPropContainer, jsxNamespace) { + // JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute [symbol] + var jsxElementAttribPropInterfaceSym = jsxNamespace && getSymbol(jsxNamespace.exports, nameOfAttribPropContainer, 67897832 /* Type */); + // JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute [type] + var jsxElementAttribPropInterfaceType = jsxElementAttribPropInterfaceSym && getDeclaredTypeOfSymbol(jsxElementAttribPropInterfaceSym); + // The properties of JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute + var propertiesOfJsxElementAttribPropInterface = jsxElementAttribPropInterfaceType && getPropertiesOfType(jsxElementAttribPropInterfaceType); + if (propertiesOfJsxElementAttribPropInterface) { + // Element Attributes has zero properties, so the element attributes type will be the class instance type + if (propertiesOfJsxElementAttribPropInterface.length === 0) { + return ""; + } + // Element Attributes has one property, so the element attributes type will be the type of the corresponding + // property of the class instance type + else if (propertiesOfJsxElementAttribPropInterface.length === 1) { + return propertiesOfJsxElementAttribPropInterface[0].escapedName; + } + else if (propertiesOfJsxElementAttribPropInterface.length > 1) { + // More than one property on ElementAttributesProperty is an error + error(jsxElementAttribPropInterfaceSym.declarations[0], ts.Diagnostics.The_global_type_JSX_0_may_not_have_more_than_one_property, ts.unescapeLeadingUnderscores(nameOfAttribPropContainer)); + } + } + return undefined; + } + function getJsxLibraryManagedAttributes(jsxNamespace) { + // JSX.LibraryManagedAttributes [symbol] + return jsxNamespace && getSymbol(jsxNamespace.exports, JsxNames.LibraryManagedAttributes, 67897832 /* Type */); + } + /// e.g. "props" for React.d.ts, + /// or 'undefined' if ElementAttributesProperty doesn't exist (which means all + /// non-intrinsic elements' attributes type is 'any'), + /// or '' if it has 0 properties (which means every + /// non-intrinsic elements' attributes type is the element instance type) + function getJsxElementPropertiesName(jsxNamespace) { + return getNameFromJsxElementAttributesContainer(JsxNames.ElementAttributesPropertyNameContainer, jsxNamespace); + } + function getJsxElementChildrenPropertyName(jsxNamespace) { + return getNameFromJsxElementAttributesContainer(JsxNames.ElementChildrenAttributeNameContainer, jsxNamespace); + } + function getUninstantiatedJsxSignaturesOfType(elementType, caller) { + if (elementType.flags & 4 /* String */) { + return [anySignature]; + } + else if (elementType.flags & 128 /* StringLiteral */) { + var intrinsicType = getIntrinsicAttributesTypeFromStringLiteralType(elementType, caller); + if (!intrinsicType) { + error(caller, ts.Diagnostics.Property_0_does_not_exist_on_type_1, elementType.value, "JSX." + JsxNames.IntrinsicElements); + return ts.emptyArray; + } + else { + var fakeSignature = createSignatureForJSXIntrinsic(caller, intrinsicType); + return [fakeSignature]; + } + } + var apparentElemType = getApparentType(elementType); + // Resolve the signatures, preferring constructor + var signatures = getSignaturesOfType(apparentElemType, 1 /* Construct */); + if (signatures.length === 0) { + // No construct signatures, try call signatures + signatures = getSignaturesOfType(apparentElemType, 0 /* Call */); + } + if (signatures.length === 0 && apparentElemType.flags & 1048576 /* Union */) { + // If each member has some combination of new/call signatures; make a union signature list for those + signatures = getUnionSignatures(ts.map(apparentElemType.types, function (t) { return getUninstantiatedJsxSignaturesOfType(t, caller); })); + } + return signatures; + } + function getIntrinsicAttributesTypeFromStringLiteralType(type, location) { + // If the elemType is a stringLiteral type, we can then provide a check to make sure that the string literal type is one of the Jsx intrinsic element type + // For example: + // var CustomTag: "h1" = "h1"; + // Hello World + var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements, location); + if (intrinsicElementsType !== errorType) { + var stringLiteralTypeName = type.value; + var intrinsicProp = getPropertyOfType(intrinsicElementsType, ts.escapeLeadingUnderscores(stringLiteralTypeName)); + if (intrinsicProp) { + return getTypeOfSymbol(intrinsicProp); + } + var indexSignatureType = getIndexTypeOfType(intrinsicElementsType, 0 /* String */); + if (indexSignatureType) { + return indexSignatureType; + } + return undefined; + } + // If we need to report an error, we already done so here. So just return any to prevent any more error downstream + return anyType; + } + function checkJsxReturnAssignableToAppropriateBound(refKind, elemInstanceType, openingLikeElement) { + if (refKind === 1 /* Function */) { + var sfcReturnConstraint = getJsxStatelessElementTypeAt(openingLikeElement); + if (sfcReturnConstraint) { + checkTypeRelatedTo(elemInstanceType, sfcReturnConstraint, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); + } + } + else if (refKind === 0 /* Component */) { + var classConstraint = getJsxElementClassTypeAt(openingLikeElement); + if (classConstraint) { + // Issue an error if this return type isn't assignable to JSX.ElementClass or JSX.Element, failing that + checkTypeRelatedTo(elemInstanceType, classConstraint, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); + } + } + else { // Mixed + var sfcReturnConstraint = getJsxStatelessElementTypeAt(openingLikeElement); + var classConstraint = getJsxElementClassTypeAt(openingLikeElement); + if (!sfcReturnConstraint || !classConstraint) { + return; + } + var combined = getUnionType([sfcReturnConstraint, classConstraint]); + checkTypeRelatedTo(elemInstanceType, combined, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); + } + } + /** + * Get attributes type of the given intrinsic opening-like Jsx element by resolving the tag name. + * The function is intended to be called from a function which has checked that the opening element is an intrinsic element. + * @param node an intrinsic JSX opening-like element + */ + function getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node) { + ts.Debug.assert(isJsxIntrinsicIdentifier(node.tagName)); + var links = getNodeLinks(node); + if (!links.resolvedJsxElementAttributesType) { + var symbol = getIntrinsicTagSymbol(node); + if (links.jsxFlags & 1 /* IntrinsicNamedElement */) { + return links.resolvedJsxElementAttributesType = getTypeOfSymbol(symbol); + } + else if (links.jsxFlags & 2 /* IntrinsicIndexedElement */) { + return links.resolvedJsxElementAttributesType = getIndexInfoOfSymbol(symbol, 0 /* String */).type; + } + else { + return links.resolvedJsxElementAttributesType = errorType; + } + } + return links.resolvedJsxElementAttributesType; + } + function getJsxElementClassTypeAt(location) { + var type = getJsxType(JsxNames.ElementClass, location); + if (type === errorType) + return undefined; + return type; + } + function getJsxElementTypeAt(location) { + return getJsxType(JsxNames.Element, location); + } + function getJsxStatelessElementTypeAt(location) { + var jsxElementType = getJsxElementTypeAt(location); + if (jsxElementType) { + return getUnionType([jsxElementType, nullType]); + } + } + /** + * Returns all the properties of the Jsx.IntrinsicElements interface + */ + function getJsxIntrinsicTagNamesAt(location) { + var intrinsics = getJsxType(JsxNames.IntrinsicElements, location); + return intrinsics ? getPropertiesOfType(intrinsics) : ts.emptyArray; + } + function checkJsxPreconditions(errorNode) { + // Preconditions for using JSX + if ((compilerOptions.jsx || 0 /* None */) === 0 /* None */) { + error(errorNode, ts.Diagnostics.Cannot_use_JSX_unless_the_jsx_flag_is_provided); + } + if (getJsxElementTypeAt(errorNode) === undefined) { + if (noImplicitAny) { + error(errorNode, ts.Diagnostics.JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist); + } + } + } + function checkJsxOpeningLikeElementOrOpeningFragment(node) { + var isNodeOpeningLikeElement = ts.isJsxOpeningLikeElement(node); + if (isNodeOpeningLikeElement) { + checkGrammarJsxElement(node); + } + checkJsxPreconditions(node); + // The reactNamespace/jsxFactory's root symbol should be marked as 'used' so we don't incorrectly elide its import. + // And if there is no reactNamespace/jsxFactory's symbol in scope when targeting React emit, we should issue an error. + var reactRefErr = diagnostics && compilerOptions.jsx === 2 /* React */ ? ts.Diagnostics.Cannot_find_name_0 : undefined; + var reactNamespace = getJsxNamespace(node); + var reactLocation = isNodeOpeningLikeElement ? node.tagName : node; + var reactSym = resolveName(reactLocation, reactNamespace, 67220415 /* Value */, reactRefErr, reactNamespace, /*isUse*/ true); + if (reactSym) { + // Mark local symbol as referenced here because it might not have been marked + // if jsx emit was not react as there wont be error being emitted + reactSym.isReferenced = 67108863 /* All */; + // If react symbol is alias, mark it as refereced + if (reactSym.flags & 2097152 /* Alias */ && !isConstEnumOrConstEnumOnlyModule(resolveAlias(reactSym))) { + markAliasSymbolAsReferenced(reactSym); + } + } + if (isNodeOpeningLikeElement) { + var sig = getResolvedSignature(node); + checkJsxReturnAssignableToAppropriateBound(getJsxReferenceKind(node), getReturnTypeOfSignature(sig), node); + } + } + /** + * Check if a property with the given name is known anywhere in the given type. In an object type, a property + * is considered known if + * 1. the object type is empty and the check is for assignability, or + * 2. if the object type has index signatures, or + * 3. if the property is actually declared in the object type + * (this means that 'toString', for example, is not usually a known property). + * 4. In a union or intersection type, + * a property is considered known if it is known in any constituent type. + * @param targetType a type to search a given name in + * @param name a property name to search + * @param isComparingJsxAttributes a boolean flag indicating whether we are searching in JsxAttributesType + */ + function isKnownProperty(targetType, name, isComparingJsxAttributes) { + if (targetType.flags & 524288 /* Object */) { + var resolved = resolveStructuredTypeMembers(targetType); + if (resolved.stringIndexInfo || + resolved.numberIndexInfo && isNumericLiteralName(name) || + getPropertyOfObjectType(targetType, name) || + isComparingJsxAttributes && !isUnhyphenatedJsxName(name)) { + // For JSXAttributes, if the attribute has a hyphenated name, consider that the attribute to be known. + return true; + } + } + else if (targetType.flags & 3145728 /* UnionOrIntersection */) { + for (var _i = 0, _a = targetType.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (isKnownProperty(t, name, isComparingJsxAttributes)) { + return true; + } + } + } + else if (targetType.flags & 16777216 /* Conditional */) { + return isKnownProperty(targetType.root.trueType, name, isComparingJsxAttributes) || + isKnownProperty(targetType.root.falseType, name, isComparingJsxAttributes); + } + return false; + } + function checkJsxExpression(node, checkMode) { + if (node.expression) { + var type = checkExpression(node.expression, checkMode); + if (node.dotDotDotToken && type !== anyType && !isArrayType(type)) { + error(node, ts.Diagnostics.JSX_spread_child_must_be_an_array_type); + } + return type; + } + else { + return errorType; + } + } + function getDeclarationNodeFlagsFromSymbol(s) { + return s.valueDeclaration ? ts.getCombinedNodeFlags(s.valueDeclaration) : 0; + } + /** + * Return whether this symbol is a member of a prototype somewhere + * Note that this is not tracked well within the compiler, so the answer may be incorrect. + */ + function isPrototypeProperty(symbol) { + if (symbol.flags & 8192 /* Method */ || ts.getCheckFlags(symbol) & 4 /* SyntheticMethod */) { + return true; + } + if (ts.isInJSFile(symbol.valueDeclaration)) { + var parent = symbol.valueDeclaration.parent; + return parent && ts.isBinaryExpression(parent) && + ts.getAssignmentDeclarationKind(parent) === 3 /* PrototypeProperty */; + } + } + /** + * Check whether the requested property access is valid. + * Returns true if node is a valid property access, and false otherwise. + * @param node The node to be checked. + * @param isSuper True if the access is from `super.`. + * @param type The type of the object whose property is being accessed. (Not the type of the property.) + * @param prop The symbol for the property being accessed. + */ + function checkPropertyAccessibility(node, isSuper, type, prop) { + var flags = ts.getDeclarationModifierFlagsFromSymbol(prop); + var errorNode = node.kind === 148 /* QualifiedName */ ? node.right : node.kind === 183 /* ImportType */ ? node : node.name; + if (ts.getCheckFlags(prop) & 256 /* ContainsPrivate */) { + // Synthetic property with private constituent property + error(errorNode, ts.Diagnostics.Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1, symbolToString(prop), typeToString(type)); + return false; + } + if (isSuper) { + // TS 1.0 spec (April 2014): 4.8.2 + // - In a constructor, instance member function, instance member accessor, or + // instance member variable initializer where this references a derived class instance, + // a super property access is permitted and must specify a public instance member function of the base class. + // - In a static member function or static member accessor + // where this references the constructor function object of a derived class, + // a super property access is permitted and must specify a public static member function of the base class. + if (languageVersion < 2 /* ES2015 */) { + if (symbolHasNonMethodDeclaration(prop)) { + error(errorNode, ts.Diagnostics.Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword); + return false; + } + } + if (flags & 128 /* Abstract */) { + // A method cannot be accessed in a super property access if the method is abstract. + // This error could mask a private property access error. But, a member + // cannot simultaneously be private and abstract, so this will trigger an + // additional error elsewhere. + error(errorNode, ts.Diagnostics.Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression, symbolToString(prop), typeToString(getDeclaringClass(prop))); + return false; + } + } + // Referencing abstract properties within their own constructors is not allowed + if ((flags & 128 /* Abstract */) && ts.isThisProperty(node) && symbolHasNonMethodDeclaration(prop)) { + var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop)); + if (declaringClassDeclaration && isNodeUsedDuringClassInitialization(node)) { + error(errorNode, ts.Diagnostics.Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor, symbolToString(prop), ts.getTextOfIdentifierOrLiteral(declaringClassDeclaration.name)); // TODO: GH#18217 + return false; + } + } + // Public properties are otherwise accessible. + if (!(flags & 24 /* NonPublicAccessibilityModifier */)) { + return true; + } + // Property is known to be private or protected at this point + // Private property is accessible if the property is within the declaring class + if (flags & 8 /* Private */) { + var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop)); + if (!isNodeWithinClass(node, declaringClassDeclaration)) { + error(errorNode, ts.Diagnostics.Property_0_is_private_and_only_accessible_within_class_1, symbolToString(prop), typeToString(getDeclaringClass(prop))); + return false; + } + return true; + } + // Property is known to be protected at this point + // All protected properties of a supertype are accessible in a super access + if (isSuper) { + return true; + } + // Find the first enclosing class that has the declaring classes of the protected constituents + // of the property as base classes + var enclosingClass = forEachEnclosingClass(node, function (enclosingDeclaration) { + var enclosingClass = getDeclaredTypeOfSymbol(getSymbolOfNode(enclosingDeclaration)); + return isClassDerivedFromDeclaringClasses(enclosingClass, prop) ? enclosingClass : undefined; + }); + // A protected property is accessible if the property is within the declaring class or classes derived from it + if (!enclosingClass) { + // allow PropertyAccessibility if context is in function with this parameter + // static member access is disallow + var thisParameter = void 0; + if (flags & 32 /* Static */ || !(thisParameter = getThisParameterFromNodeContext(node)) || !thisParameter.type) { + error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses, symbolToString(prop), typeToString(getDeclaringClass(prop) || type)); + return false; + } + var thisType = getTypeFromTypeNode(thisParameter.type); + enclosingClass = ((thisType.flags & 262144 /* TypeParameter */) ? getConstraintOfTypeParameter(thisType) : thisType); + } + // No further restrictions for static properties + if (flags & 32 /* Static */) { + return true; + } + if (type.flags & 262144 /* TypeParameter */) { + // get the original type -- represented as the type constraint of the 'this' type + type = type.isThisType ? getConstraintOfTypeParameter(type) : getBaseConstraintOfType(type); // TODO: GH#18217 Use a different variable that's allowed to be undefined + } + if (!type || !hasBaseType(type, enclosingClass)) { + error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1, symbolToString(prop), typeToString(enclosingClass)); + return false; + } + return true; + } + function getThisParameterFromNodeContext(node) { + var thisContainer = ts.getThisContainer(node, /* includeArrowFunctions */ false); + return thisContainer && ts.isFunctionLike(thisContainer) ? ts.getThisParameter(thisContainer) : undefined; + } + function symbolHasNonMethodDeclaration(symbol) { + return !!forEachProperty(symbol, function (prop) { return !(prop.flags & 8192 /* Method */); }); + } + function checkNonNullExpression(node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic) { + return checkNonNullType(checkExpression(node), node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic); + } + function getNonNullableTypeIfNeeded(type) { + var kind = (strictNullChecks ? getFalsyFlags(type) : type.flags) & 98304 /* Nullable */; + if (kind) { + return getNonNullableType(type); + } + return type; + } + function checkNonNullType(type, node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic) { + if (type.flags & 2 /* Unknown */) { + error(node, ts.Diagnostics.Object_is_of_type_unknown); + return errorType; + } + var kind = (strictNullChecks ? getFalsyFlags(type) : type.flags) & 98304 /* Nullable */; + if (kind) { + error(node, kind & 32768 /* Undefined */ ? kind & 65536 /* Null */ ? + (nullOrUndefinedDiagnostic || ts.Diagnostics.Object_is_possibly_null_or_undefined) : + (undefinedDiagnostic || ts.Diagnostics.Object_is_possibly_undefined) : + (nullDiagnostic || ts.Diagnostics.Object_is_possibly_null)); + var t = getNonNullableType(type); + return t.flags & (98304 /* Nullable */ | 131072 /* Never */) ? errorType : t; + } + return type; + } + function checkPropertyAccessExpression(node) { + return checkPropertyAccessExpressionOrQualifiedName(node, node.expression, node.name); + } + function checkQualifiedName(node) { + return checkPropertyAccessExpressionOrQualifiedName(node, node.left, node.right); + } + function checkPropertyAccessExpressionOrQualifiedName(node, left, right) { + var propType; + var leftType = checkNonNullExpression(left); + var parentSymbol = getNodeLinks(left).resolvedSymbol; + var apparentType = getApparentType(getWidenedType(leftType)); + if (isTypeAny(apparentType) || apparentType === silentNeverType) { + if (ts.isIdentifier(left) && parentSymbol) { + markAliasReferenced(parentSymbol, node); + } + return apparentType; + } + var assignmentKind = ts.getAssignmentTargetKind(node); + var prop = getPropertyOfType(apparentType, right.escapedText); + if (ts.isIdentifier(left) && parentSymbol && !(prop && isConstEnumOrConstEnumOnlyModule(prop))) { + markAliasReferenced(parentSymbol, node); + } + if (!prop) { + var indexInfo = getIndexInfoOfType(apparentType, 0 /* String */); + if (!(indexInfo && indexInfo.type)) { + if (isJSLiteralType(leftType)) { + return anyType; + } + if (right.escapedText && !checkAndReportErrorForExtendingInterface(node)) { + reportNonexistentProperty(right, leftType.flags & 262144 /* TypeParameter */ && leftType.isThisType ? apparentType : leftType); + } + return errorType; + } + if (indexInfo.isReadonly && (ts.isAssignmentTarget(node) || ts.isDeleteTarget(node))) { + error(node, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(apparentType)); + } + propType = indexInfo.type; + } + else { + checkPropertyNotUsedBeforeDeclaration(prop, node, right); + markPropertyAsReferenced(prop, node, left.kind === 100 /* ThisKeyword */); + getNodeLinks(node).resolvedSymbol = prop; + checkPropertyAccessibility(node, left.kind === 98 /* SuperKeyword */, apparentType, prop); + if (assignmentKind) { + if (isReferenceToReadonlyEntity(node, prop) || isReferenceThroughNamespaceImport(node)) { + error(right, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, ts.idText(right)); + return errorType; + } + } + propType = getConstraintForLocation(getTypeOfSymbol(prop), node); + } + // Only compute control flow type if this is a property access expression that isn't an + // assignment target, and the referenced property was declared as a variable, property, + // accessor, or optional method. + if (node.kind !== 189 /* PropertyAccessExpression */ || + assignmentKind === 1 /* Definite */ || + prop && !(prop.flags & (3 /* Variable */ | 4 /* Property */ | 98304 /* Accessor */)) && !(prop.flags & 8192 /* Method */ && propType.flags & 1048576 /* Union */)) { + return propType; + } + // If strict null checks and strict property initialization checks are enabled, if we have + // a this.xxx property access, if the property is an instance property without an initializer, + // and if we are in a constructor of the same class as the property declaration, assume that + // the property is uninitialized at the top of the control flow. + var assumeUninitialized = false; + if (strictNullChecks && strictPropertyInitialization && left.kind === 100 /* ThisKeyword */) { + var declaration = prop && prop.valueDeclaration; + if (declaration && isInstancePropertyWithoutInitializer(declaration)) { + var flowContainer = getControlFlowContainer(node); + if (flowContainer.kind === 157 /* Constructor */ && flowContainer.parent === declaration.parent) { + assumeUninitialized = true; + } + } + } + else if (strictNullChecks && prop && prop.valueDeclaration && + ts.isPropertyAccessExpression(prop.valueDeclaration) && + ts.getAssignmentDeclarationPropertyAccessKind(prop.valueDeclaration) && + getControlFlowContainer(node) === getControlFlowContainer(prop.valueDeclaration)) { + assumeUninitialized = true; + } + var flowType = getFlowTypeOfReference(node, propType, assumeUninitialized ? getOptionalType(propType) : propType); + if (assumeUninitialized && !(getFalsyFlags(propType) & 32768 /* Undefined */) && getFalsyFlags(flowType) & 32768 /* Undefined */) { + error(right, ts.Diagnostics.Property_0_is_used_before_being_assigned, symbolToString(prop)); // TODO: GH#18217 + // Return the declared type to reduce follow-on errors + return propType; + } + return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType; + } + function checkPropertyNotUsedBeforeDeclaration(prop, node, right) { + var valueDeclaration = prop.valueDeclaration; + if (!valueDeclaration) { + return; + } + var diagnosticMessage; + var declarationName = ts.idText(right); + if (isInPropertyInitializer(node) && + !isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right) + && !isPropertyDeclaredInAncestorClass(prop)) { + diagnosticMessage = error(right, ts.Diagnostics.Property_0_is_used_before_its_initialization, declarationName); + } + else if (valueDeclaration.kind === 240 /* ClassDeclaration */ && + node.parent.kind !== 164 /* TypeReference */ && + !(valueDeclaration.flags & 4194304 /* Ambient */) && + !isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right)) { + diagnosticMessage = error(right, ts.Diagnostics.Class_0_used_before_its_declaration, declarationName); + } + if (diagnosticMessage) { + addRelatedInfo(diagnosticMessage, ts.createDiagnosticForNode(valueDeclaration, ts.Diagnostics._0_is_declared_here, declarationName)); + } + } + function isInPropertyInitializer(node) { + return !!ts.findAncestor(node, function (node) { + switch (node.kind) { + case 154 /* PropertyDeclaration */: + return true; + case 275 /* PropertyAssignment */: + // We might be in `a = { b: this.b }`, so keep looking. See `tests/cases/compiler/useBeforeDeclaration_propertyAssignment.ts`. + return false; + default: + return ts.isExpressionNode(node) ? false : "quit"; + } + }); + } + /** + * It's possible that "prop.valueDeclaration" is a local declaration, but the property was also declared in a superclass. + * In that case we won't consider it used before its declaration, because it gets its value from the superclass' declaration. + */ + function isPropertyDeclaredInAncestorClass(prop) { + if (!(prop.parent.flags & 32 /* Class */)) { + return false; + } + var classType = getTypeOfSymbol(prop.parent); + while (true) { + classType = classType.symbol && getSuperClass(classType); + if (!classType) { + return false; + } + var superProperty = getPropertyOfType(classType, prop.escapedName); + if (superProperty && superProperty.valueDeclaration) { + return true; + } + } + } + function getSuperClass(classType) { + var x = getBaseTypes(classType); + if (x.length === 0) { + return undefined; + } + return getIntersectionType(x); + } + function reportNonexistentProperty(propNode, containingType) { + var errorInfo; + var relatedInfo; + if (containingType.flags & 1048576 /* Union */ && !(containingType.flags & 131068 /* Primitive */)) { + for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) { + var subtype = _a[_i]; + if (!getPropertyOfType(subtype, propNode.escapedText)) { + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(subtype)); + break; + } + } + } + if (typeHasStaticProperty(propNode.escapedText, containingType)) { + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_is_a_static_member_of_type_1, ts.declarationNameToString(propNode), typeToString(containingType)); + } + else { + var promisedType = getPromisedTypeOfPromise(containingType); + if (promisedType && getPropertyOfType(promisedType, propNode.escapedText)) { + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_forget_to_use_await, ts.declarationNameToString(propNode), typeToString(containingType)); + } + else { + var suggestion = getSuggestedSymbolForNonexistentProperty(propNode, containingType); + if (suggestion !== undefined) { + var suggestedName = ts.symbolName(suggestion); + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2, ts.declarationNameToString(propNode), typeToString(containingType), suggestedName); + relatedInfo = suggestion.valueDeclaration && ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestedName); + } + else { + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(containingType)); + } + } + } + var resultDiagnostic = ts.createDiagnosticForNodeFromMessageChain(propNode, errorInfo); + if (relatedInfo) { + addRelatedInfo(resultDiagnostic, relatedInfo); + } + diagnostics.add(resultDiagnostic); + } + function typeHasStaticProperty(propName, containingType) { + var prop = containingType.symbol && getPropertyOfType(getTypeOfSymbol(containingType.symbol), propName); + return prop !== undefined && prop.valueDeclaration && ts.hasModifier(prop.valueDeclaration, 32 /* Static */); + } + function getSuggestedSymbolForNonexistentProperty(name, containingType) { + return getSpellingSuggestionForName(ts.isString(name) ? name : ts.idText(name), getPropertiesOfType(containingType), 67220415 /* Value */); + } + function getSuggestionForNonexistentProperty(name, containingType) { + var suggestion = getSuggestedSymbolForNonexistentProperty(name, containingType); + return suggestion && ts.symbolName(suggestion); + } + function getSuggestedSymbolForNonexistentSymbol(location, outerName, meaning) { + ts.Debug.assert(outerName !== undefined, "outername should always be defined"); + var result = resolveNameHelper(location, outerName, meaning, /*nameNotFoundMessage*/ undefined, outerName, /*isUse*/ false, /*excludeGlobals*/ false, function (symbols, name, meaning) { + ts.Debug.assertEqual(outerName, name, "name should equal outerName"); + var symbol = getSymbol(symbols, name, meaning); + // Sometimes the symbol is found when location is a return type of a function: `typeof x` and `x` is declared in the body of the function + // So the table *contains* `x` but `x` isn't actually in scope. + // However, resolveNameHelper will continue and call this callback again, so we'll eventually get a correct suggestion. + return symbol || getSpellingSuggestionForName(ts.unescapeLeadingUnderscores(name), ts.arrayFrom(symbols.values()), meaning); + }); + return result; + } + function getSuggestionForNonexistentSymbol(location, outerName, meaning) { + var symbolResult = getSuggestedSymbolForNonexistentSymbol(location, outerName, meaning); + return symbolResult && ts.symbolName(symbolResult); + } + function getSuggestedSymbolForNonexistentModule(name, targetModule) { + return targetModule.exports && getSpellingSuggestionForName(ts.idText(name), getExportsOfModuleAsArray(targetModule), 2623475 /* ModuleMember */); + } + function getSuggestionForNonexistentExport(name, targetModule) { + var suggestion = getSuggestedSymbolForNonexistentModule(name, targetModule); + return suggestion && ts.symbolName(suggestion); + } + /** + * Given a name and a list of symbols whose names are *not* equal to the name, return a spelling suggestion if there is one that is close enough. + * Names less than length 3 only check for case-insensitive equality, not levenshtein distance. + * + * If there is a candidate that's the same except for case, return that. + * If there is a candidate that's within one edit of the name, return that. + * Otherwise, return the candidate with the smallest Levenshtein distance, + * except for candidates: + * * With no name + * * Whose meaning doesn't match the `meaning` parameter. + * * Whose length differs from the target name by more than 0.34 of the length of the name. + * * Whose levenshtein distance is more than 0.4 of the length of the name + * (0.4 allows 1 substitution/transposition for every 5 characters, + * and 1 insertion/deletion at 3 characters) + */ + function getSpellingSuggestionForName(name, symbols, meaning) { + return ts.getSpellingSuggestion(name, symbols, getCandidateName); + function getCandidateName(candidate) { + var candidateName = ts.symbolName(candidate); + return !ts.startsWith(candidateName, "\"") && candidate.flags & meaning ? candidateName : undefined; + } + } + function markPropertyAsReferenced(prop, nodeForCheckWriteOnly, isThisAccess) { + if (!prop || !(prop.flags & 106500 /* ClassMember */) || !prop.valueDeclaration || !ts.hasModifier(prop.valueDeclaration, 8 /* Private */)) { + return; + } + if (nodeForCheckWriteOnly && ts.isWriteOnlyAccess(nodeForCheckWriteOnly) && !(prop.flags & 65536 /* SetAccessor */ && !(prop.flags & 32768 /* GetAccessor */))) { + return; + } + if (isThisAccess) { + // Find any FunctionLikeDeclaration because those create a new 'this' binding. But this should only matter for methods (or getters/setters). + var containingMethod = ts.findAncestor(nodeForCheckWriteOnly, ts.isFunctionLikeDeclaration); + if (containingMethod && containingMethod.symbol === prop) { + return; + } + } + (ts.getCheckFlags(prop) & 1 /* Instantiated */ ? getSymbolLinks(prop).target : prop).isReferenced = 67108863 /* All */; + } + function isValidPropertyAccess(node, propertyName) { + switch (node.kind) { + case 189 /* PropertyAccessExpression */: + return isValidPropertyAccessWithType(node, node.expression.kind === 98 /* SuperKeyword */, propertyName, getWidenedType(checkExpression(node.expression))); + case 148 /* QualifiedName */: + return isValidPropertyAccessWithType(node, /*isSuper*/ false, propertyName, getWidenedType(checkExpression(node.left))); + case 183 /* ImportType */: + return isValidPropertyAccessWithType(node, /*isSuper*/ false, propertyName, getTypeFromTypeNode(node)); + } + } + function isValidPropertyAccessForCompletions(node, type, property) { + return isValidPropertyAccessWithType(node, node.kind !== 183 /* ImportType */ && node.expression.kind === 98 /* SuperKeyword */, property.escapedName, type) + && (!(property.flags & 8192 /* Method */) || isValidMethodAccess(property, type)); + } + function isValidMethodAccess(method, actualThisType) { + var propType = getTypeOfPropertyOfType(actualThisType, method.escapedName); + var signatures = getSignaturesOfType(getNonNullableType(propType), 0 /* Call */); + ts.Debug.assert(signatures.length !== 0); + return signatures.some(function (sig) { + var signatureThisType = getThisTypeOfSignature(sig); + return !signatureThisType || isTypeAssignableTo(actualThisType, getInstantiatedSignatureThisType(sig, signatureThisType, actualThisType)); + }); + } + function getInstantiatedSignatureThisType(sig, signatureThisType, actualThisType) { + if (!sig.typeParameters) { + return signatureThisType; + } + var context = createInferenceContext(sig.typeParameters, sig, 0 /* None */); + inferTypes(context.inferences, actualThisType, signatureThisType); + return instantiateType(signatureThisType, createSignatureTypeMapper(sig, getInferredTypes(context))); + } + function isValidPropertyAccessWithType(node, isSuper, propertyName, type) { + if (type === errorType || isTypeAny(type)) { + return true; + } + var prop = getPropertyOfType(type, propertyName); + return prop ? checkPropertyAccessibility(node, isSuper, type, prop) + // In js files properties of unions are allowed in completion + : ts.isInJSFile(node) && (type.flags & 1048576 /* Union */) !== 0 && type.types.some(function (elementType) { return isValidPropertyAccessWithType(node, isSuper, propertyName, elementType); }); + } + /** + * Return the symbol of the for-in variable declared or referenced by the given for-in statement. + */ + function getForInVariableSymbol(node) { + var initializer = node.initializer; + if (initializer.kind === 238 /* VariableDeclarationList */) { + var variable = initializer.declarations[0]; + if (variable && !ts.isBindingPattern(variable.name)) { + return getSymbolOfNode(variable); + } + } + else if (initializer.kind === 72 /* Identifier */) { + return getResolvedSymbol(initializer); + } + return undefined; + } + /** + * Return true if the given type is considered to have numeric property names. + */ + function hasNumericPropertyNames(type) { + return getIndexTypeOfType(type, 1 /* Number */) && !getIndexTypeOfType(type, 0 /* String */); + } + /** + * Return true if given node is an expression consisting of an identifier (possibly parenthesized) + * that references a for-in variable for an object with numeric property names. + */ + function isForInVariableForNumericPropertyNames(expr) { + var e = ts.skipParentheses(expr); + if (e.kind === 72 /* Identifier */) { + var symbol = getResolvedSymbol(e); + if (symbol.flags & 3 /* Variable */) { + var child = expr; + var node = expr.parent; + while (node) { + if (node.kind === 226 /* ForInStatement */ && + child === node.statement && + getForInVariableSymbol(node) === symbol && + hasNumericPropertyNames(getTypeOfExpression(node.expression))) { + return true; + } + child = node; + node = node.parent; + } + } + } + return false; + } + function checkIndexedAccess(node) { + var objectType = checkNonNullExpression(node.expression); + var indexExpression = node.argumentExpression; + if (!indexExpression) { + var sourceFile = ts.getSourceFileOfNode(node); + if (node.parent.kind === 192 /* NewExpression */ && node.parent.expression === node) { + var start = ts.skipTrivia(sourceFile.text, node.expression.end); + var end = node.end; + grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead); + } + else { + var start = node.end - "]".length; + var end = node.end; + grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.Expression_expected); + } + return errorType; + } + var indexType = checkExpression(indexExpression); + if (objectType === errorType || objectType === silentNeverType) { + return objectType; + } + if (isConstEnumObjectType(objectType) && indexExpression.kind !== 10 /* StringLiteral */) { + error(indexExpression, ts.Diagnostics.A_const_enum_member_can_only_be_accessed_using_a_string_literal); + return errorType; + } + return checkIndexedAccessIndexType(getIndexedAccessType(objectType, isForInVariableForNumericPropertyNames(indexExpression) ? numberType : indexType, node), node); + } + function checkThatExpressionIsProperSymbolReference(expression, expressionType, reportError) { + if (expressionType === errorType) { + // There is already an error, so no need to report one. + return false; + } + if (!ts.isWellKnownSymbolSyntactically(expression)) { + return false; + } + // Make sure the property type is the primitive symbol type + if ((expressionType.flags & 12288 /* ESSymbolLike */) === 0) { + if (reportError) { + error(expression, ts.Diagnostics.A_computed_property_name_of_the_form_0_must_be_of_type_symbol, ts.getTextOfNode(expression)); + } + return false; + } + // The name is Symbol., so make sure Symbol actually resolves to the + // global Symbol object + var leftHandSide = expression.expression; + var leftHandSideSymbol = getResolvedSymbol(leftHandSide); + if (!leftHandSideSymbol) { + return false; + } + var globalESSymbol = getGlobalESSymbolConstructorSymbol(/*reportErrors*/ true); + if (!globalESSymbol) { + // Already errored when we tried to look up the symbol + return false; + } + if (leftHandSideSymbol !== globalESSymbol) { + if (reportError) { + error(leftHandSide, ts.Diagnostics.Symbol_reference_does_not_refer_to_the_global_Symbol_constructor_object); + } + return false; + } + return true; + } + function callLikeExpressionMayHaveTypeArguments(node) { + return ts.isCallOrNewExpression(node) || ts.isTaggedTemplateExpression(node) || ts.isJsxOpeningLikeElement(node); + } + function resolveUntypedCall(node) { + if (callLikeExpressionMayHaveTypeArguments(node)) { + // Check type arguments even though we will give an error that untyped calls may not accept type arguments. + // This gets us diagnostics for the type arguments and marks them as referenced. + ts.forEach(node.typeArguments, checkSourceElement); + } + if (node.kind === 193 /* TaggedTemplateExpression */) { + checkExpression(node.template); + } + else if (ts.isJsxOpeningLikeElement(node)) { + checkExpression(node.attributes); + } + else if (node.kind !== 152 /* Decorator */) { + ts.forEach(node.arguments, function (argument) { + checkExpression(argument); + }); + } + return anySignature; + } + function resolveErrorCall(node) { + resolveUntypedCall(node); + return unknownSignature; + } + // Re-order candidate signatures into the result array. Assumes the result array to be empty. + // The candidate list orders groups in reverse, but within a group signatures are kept in declaration order + // A nit here is that we reorder only signatures that belong to the same symbol, + // so order how inherited signatures are processed is still preserved. + // interface A { (x: string): void } + // interface B extends A { (x: 'foo'): string } + // const b: B; + // b('foo') // <- here overloads should be processed as [(x:'foo'): string, (x: string): void] + function reorderCandidates(signatures, result) { + var lastParent; + var lastSymbol; + var cutoffIndex = 0; + var index; + var specializedIndex = -1; + var spliceIndex; + ts.Debug.assert(!result.length); + for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { + var signature = signatures_3[_i]; + var symbol = signature.declaration && getSymbolOfNode(signature.declaration); + var parent = signature.declaration && signature.declaration.parent; + if (!lastSymbol || symbol === lastSymbol) { + if (lastParent && parent === lastParent) { + index = index + 1; + } + else { + lastParent = parent; + index = cutoffIndex; + } + } + else { + // current declaration belongs to a different symbol + // set cutoffIndex so re-orderings in the future won't change result set from 0 to cutoffIndex + index = cutoffIndex = result.length; + lastParent = parent; + } + lastSymbol = symbol; + // specialized signatures always need to be placed before non-specialized signatures regardless + // of the cutoff position; see GH#1133 + if (signature.hasLiteralTypes) { + specializedIndex++; + spliceIndex = specializedIndex; + // The cutoff index always needs to be greater than or equal to the specialized signature index + // in order to prevent non-specialized signatures from being added before a specialized + // signature. + cutoffIndex++; + } + else { + spliceIndex = index; + } + result.splice(spliceIndex, 0, signature); + } + } + function isSpreadArgument(arg) { + return !!arg && (arg.kind === 208 /* SpreadElement */ || arg.kind === 215 /* SyntheticExpression */ && arg.isSpread); + } + function getSpreadArgumentIndex(args) { + return ts.findIndex(args, isSpreadArgument); + } + function acceptsVoid(t) { + return !!(t.flags & 16384 /* Void */); + } + function hasCorrectArity(node, args, signature, signatureHelpTrailingComma) { + if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; } + var argCount; + var callIsIncomplete = false; // In incomplete call we want to be lenient when we have too few arguments + var effectiveParameterCount = getParameterCount(signature); + var effectiveMinimumArguments = getMinArgumentCount(signature); + if (node.kind === 193 /* TaggedTemplateExpression */) { + argCount = args.length; + if (node.template.kind === 206 /* TemplateExpression */) { + // If a tagged template expression lacks a tail literal, the call is incomplete. + // Specifically, a template only can end in a TemplateTail or a Missing literal. + var lastSpan = ts.last(node.template.templateSpans); // we should always have at least one span. + callIsIncomplete = ts.nodeIsMissing(lastSpan.literal) || !!lastSpan.literal.isUnterminated; + } + else { + // If the template didn't end in a backtick, or its beginning occurred right prior to EOF, + // then this might actually turn out to be a TemplateHead in the future; + // so we consider the call to be incomplete. + var templateLiteral = node.template; + ts.Debug.assert(templateLiteral.kind === 14 /* NoSubstitutionTemplateLiteral */); + callIsIncomplete = !!templateLiteral.isUnterminated; + } + } + else if (node.kind === 152 /* Decorator */) { + argCount = getDecoratorArgumentCount(node, signature); + } + else if (ts.isJsxOpeningLikeElement(node)) { + callIsIncomplete = node.attributes.end === node.end; + if (callIsIncomplete) { + return true; + } + argCount = effectiveMinimumArguments === 0 ? args.length : 1; + effectiveParameterCount = args.length === 0 ? effectiveParameterCount : 1; // class may have argumentless ctor functions - still resolve ctor and compare vs props member type + effectiveMinimumArguments = Math.min(effectiveMinimumArguments, 1); // sfc may specify context argument - handled by framework and not typechecked + } + else { + if (!node.arguments) { + // This only happens when we have something of the form: 'new C' + ts.Debug.assert(node.kind === 192 /* NewExpression */); + return getMinArgumentCount(signature) === 0; + } + argCount = signatureHelpTrailingComma ? args.length + 1 : args.length; + // If we are missing the close parenthesis, the call is incomplete. + callIsIncomplete = node.arguments.end === node.end; + // If a spread argument is present, check that it corresponds to a rest parameter or at least that it's in the valid range. + var spreadArgIndex = getSpreadArgumentIndex(args); + if (spreadArgIndex >= 0) { + return spreadArgIndex >= getMinArgumentCount(signature) && (hasEffectiveRestParameter(signature) || spreadArgIndex < getParameterCount(signature)); + } + } + // Too many arguments implies incorrect arity. + if (!hasEffectiveRestParameter(signature) && argCount > effectiveParameterCount) { + return false; + } + // If the call is incomplete, we should skip the lower bound check. + // JSX signatures can have extra parameters provided by the library which we don't check + if (callIsIncomplete || argCount >= effectiveMinimumArguments) { + return true; + } + for (var i = argCount; i < effectiveMinimumArguments; i++) { + var type = getTypeAtPosition(signature, i); + if (filterType(type, acceptsVoid).flags & 131072 /* Never */) { + return false; + } + } + return true; + } + function hasCorrectTypeArgumentArity(signature, typeArguments) { + // If the user supplied type arguments, but the number of type arguments does not match + // the declared number of type parameters, the call has an incorrect arity. + var numTypeParameters = ts.length(signature.typeParameters); + var minTypeArgumentCount = getMinTypeArgumentCount(signature.typeParameters); + return !typeArguments || + (typeArguments.length >= minTypeArgumentCount && typeArguments.length <= numTypeParameters); + } + // If type has a single call signature and no other members, return that signature. Otherwise, return undefined. + function getSingleCallSignature(type) { + if (type.flags & 524288 /* Object */) { + var resolved = resolveStructuredTypeMembers(type); + if (resolved.callSignatures.length === 1 && resolved.constructSignatures.length === 0 && + resolved.properties.length === 0 && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { + return resolved.callSignatures[0]; + } + } + return undefined; + } + // Instantiate a generic signature in the context of a non-generic signature (section 3.8.5 in TypeScript spec) + function instantiateSignatureInContextOf(signature, contextualSignature, contextualMapper, compareTypes) { + var context = createInferenceContext(signature.typeParameters, signature, 0 /* None */, compareTypes); + var sourceSignature = contextualMapper ? instantiateSignature(contextualSignature, contextualMapper) : contextualSignature; + forEachMatchingParameterType(sourceSignature, signature, function (source, target) { + // Type parameters from outer context referenced by source type are fixed by instantiation of the source type + inferTypes(context.inferences, source, target); + }); + if (!contextualMapper) { + inferTypes(context.inferences, getReturnTypeOfSignature(contextualSignature), getReturnTypeOfSignature(signature), 8 /* ReturnType */); + } + return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJSFile(contextualSignature.declaration)); + } + function inferJsxTypeArguments(node, signature, excludeArgument, context) { + var paramType = getEffectiveFirstArgumentForJsxSignature(signature, node); + var checkAttrType = checkExpressionWithContextualType(node.attributes, paramType, excludeArgument && excludeArgument[0] !== undefined ? identityMapper : context); + inferTypes(context.inferences, checkAttrType, paramType); + return getInferredTypes(context); + } + function inferTypeArguments(node, signature, args, excludeArgument, context) { + // Clear out all the inference results from the last time inferTypeArguments was called on this context + for (var _i = 0, _a = context.inferences; _i < _a.length; _i++) { + var inference = _a[_i]; + // As an optimization, we don't have to clear (and later recompute) inferred types + // for type parameters that have already been fixed on the previous call to inferTypeArguments. + // It would be just as correct to reset all of them. But then we'd be repeating the same work + // for the type parameters that were fixed, namely the work done by getInferredType. + if (!inference.isFixed) { + inference.inferredType = undefined; + } + } + if (ts.isJsxOpeningLikeElement(node)) { + return inferJsxTypeArguments(node, signature, excludeArgument, context); + } + // If a contextual type is available, infer from that type to the return type of the call expression. For + // example, given a 'function wrap(cb: (x: T) => U): (x: T) => U' and a call expression + // 'let f: (x: string) => number = wrap(s => s.length)', we infer from the declared type of 'f' to the + // return type of 'wrap'. + if (node.kind !== 152 /* Decorator */) { + var contextualType = getContextualType(node); + if (contextualType) { + // We clone the contextual mapper to avoid disturbing a resolution in progress for an + // outer call expression. Effectively we just want a snapshot of whatever has been + // inferred for any outer call expression so far. + var instantiatedType = instantiateType(contextualType, cloneTypeMapper(getContextualMapper(node))); + // If the contextual type is a generic function type with a single call signature, we + // instantiate the type with its own type parameters and type arguments. This ensures that + // the type parameters are not erased to type any during type inference such that they can + // be inferred as actual types from the contextual type. For example: + // declare function arrayMap(f: (x: T) => U): (a: T[]) => U[]; + // const boxElements: (a: A[]) => { value: A }[] = arrayMap(value => ({ value })); + // Above, the type of the 'value' parameter is inferred to be 'A'. + var contextualSignature = getSingleCallSignature(instantiatedType); + var inferenceSourceType = contextualSignature && contextualSignature.typeParameters ? + getOrCreateTypeFromSignature(getSignatureInstantiationWithoutFillingInTypeArguments(contextualSignature, contextualSignature.typeParameters)) : + instantiatedType; + var inferenceTargetType = getReturnTypeOfSignature(signature); + // Inferences made from return types have lower priority than all other inferences. + inferTypes(context.inferences, inferenceSourceType, inferenceTargetType, 8 /* ReturnType */); + } + } + var thisType = getThisTypeOfSignature(signature); + if (thisType) { + var thisArgumentNode = getThisArgumentOfCall(node); + var thisArgumentType = thisArgumentNode ? checkExpression(thisArgumentNode) : voidType; + inferTypes(context.inferences, thisArgumentType, thisType); + } + var restType = getNonArrayRestType(signature); + var argCount = restType ? Math.min(getParameterCount(signature) - 1, args.length) : args.length; + for (var i = 0; i < argCount; i++) { + var arg = args[i]; + if (arg.kind !== 210 /* OmittedExpression */) { + var paramType = getTypeAtPosition(signature, i); + // For context sensitive arguments we pass the identityMapper, which is a signal to treat all + // context sensitive function expressions as wildcards + var mapper = excludeArgument && excludeArgument[i] !== undefined ? identityMapper : context; + var argType = checkExpressionWithContextualType(arg, paramType, mapper); + inferTypes(context.inferences, argType, paramType); + } + } + if (restType) { + var spreadType = getSpreadArgumentType(args, argCount, args.length, restType, context); + inferTypes(context.inferences, spreadType, restType); + } + return getInferredTypes(context); + } + function getArrayifiedType(type) { + if (forEachType(type, function (t) { return !(t.flags & (1 /* Any */ | 63176704 /* Instantiable */) || isArrayType(t) || isTupleType(t)); })) { + return createArrayType(getIndexTypeOfType(type, 1 /* Number */) || errorType); + } + return type; + } + function getSpreadArgumentType(args, index, argCount, restType, context) { + if (index >= argCount - 1) { + var arg = args[argCount - 1]; + if (isSpreadArgument(arg)) { + // We are inferring from a spread expression in the last argument position, i.e. both the parameter + // and the argument are ...x forms. + return arg.kind === 215 /* SyntheticExpression */ ? + createArrayType(arg.type) : + getArrayifiedType(checkExpressionWithContextualType(arg.expression, restType, context)); + } + } + var contextualType = getIndexTypeOfType(restType, 1 /* Number */) || anyType; + var hasPrimitiveContextualType = maybeTypeOfKind(contextualType, 131068 /* Primitive */ | 4194304 /* Index */); + var types = []; + var spreadIndex = -1; + for (var i = index; i < argCount; i++) { + var argType = checkExpressionWithContextualType(args[i], contextualType, context); + if (spreadIndex < 0 && isSpreadArgument(args[i])) { + spreadIndex = i - index; + } + types.push(hasPrimitiveContextualType ? getRegularTypeOfLiteralType(argType) : getWidenedLiteralType(argType)); + } + return spreadIndex < 0 ? + createTupleType(types) : + createTupleType(ts.append(types.slice(0, spreadIndex), getUnionType(types.slice(spreadIndex))), spreadIndex, /*hasRestElement*/ true); + } + function checkTypeArguments(signature, typeArgumentNodes, reportErrors, headMessage) { + var isJavascript = ts.isInJSFile(signature.declaration); + var typeParameters = signature.typeParameters; + var typeArgumentTypes = fillMissingTypeArguments(ts.map(typeArgumentNodes, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), isJavascript); + var mapper; + for (var i = 0; i < typeArgumentNodes.length; i++) { + ts.Debug.assert(typeParameters[i] !== undefined, "Should not call checkTypeArguments with too many type arguments"); + var constraint = getConstraintOfTypeParameter(typeParameters[i]); + if (constraint) { + var errorInfo = reportErrors && headMessage ? (function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); }) : undefined; + var typeArgumentHeadMessage = headMessage || ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1; + if (!mapper) { + mapper = createTypeMapper(typeParameters, typeArgumentTypes); + } + var typeArgument = typeArgumentTypes[i]; + if (!checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), reportErrors ? typeArgumentNodes[i] : undefined, typeArgumentHeadMessage, errorInfo)) { + return undefined; + } + } + } + return typeArgumentTypes; + } + function getJsxReferenceKind(node) { + if (isJsxIntrinsicIdentifier(node.tagName)) { + return 2 /* Mixed */; + } + var tagType = getApparentType(checkExpression(node.tagName)); + if (ts.length(getSignaturesOfType(tagType, 1 /* Construct */))) { + return 0 /* Component */; + } + if (ts.length(getSignaturesOfType(tagType, 0 /* Call */))) { + return 1 /* Function */; + } + return 2 /* Mixed */; + } + /** + * Check if the given signature can possibly be a signature called by the JSX opening-like element. + * @param node a JSX opening-like element we are trying to figure its call signature + * @param signature a candidate signature we are trying whether it is a call signature + * @param relation a relationship to check parameter and argument type + * @param excludeArgument + */ + function checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation, excludeArgument, reportErrors) { + // Stateless function components can have maximum of three arguments: "props", "context", and "updater". + // However "context" and "updater" are implicit and can't be specify by users. Only the first parameter, props, + // can be specified by users through attributes property. + var paramType = getEffectiveFirstArgumentForJsxSignature(signature, node); + var attributesType = checkExpressionWithContextualType(node.attributes, paramType, excludeArgument && excludeArgument[0] ? identityMapper : undefined); + return checkTypeRelatedToAndOptionallyElaborate(attributesType, paramType, relation, reportErrors ? node.tagName : undefined, node.attributes); + } + function checkApplicableSignature(node, args, signature, relation, excludeArgument, reportErrors) { + if (ts.isJsxOpeningLikeElement(node)) { + return checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation, excludeArgument, reportErrors); + } + var thisType = getThisTypeOfSignature(signature); + if (thisType && thisType !== voidType && node.kind !== 192 /* NewExpression */) { + // If the called expression is not of the form `x.f` or `x["f"]`, then sourceType = voidType + // If the signature's 'this' type is voidType, then the check is skipped -- anything is compatible. + // If the expression is a new expression, then the check is skipped. + var thisArgumentNode = getThisArgumentOfCall(node); + var thisArgumentType = thisArgumentNode ? checkExpression(thisArgumentNode) : voidType; + var errorNode = reportErrors ? (thisArgumentNode || node) : undefined; + var headMessage_1 = ts.Diagnostics.The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1; + if (!checkTypeRelatedTo(thisArgumentType, thisType, relation, errorNode, headMessage_1)) { + return false; + } + } + var headMessage = ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1; + var restType = getNonArrayRestType(signature); + var argCount = restType ? Math.min(getParameterCount(signature) - 1, args.length) : args.length; + for (var i = 0; i < argCount; i++) { + var arg = args[i]; + if (arg.kind !== 210 /* OmittedExpression */) { + var paramType = getTypeAtPosition(signature, i); + var argType = checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); + // If one or more arguments are still excluded (as indicated by a non-null excludeArgument parameter), + // we obtain the regular type of any object literal arguments because we may not have inferred complete + // parameter types yet and therefore excess property checks may yield false positives (see #17041). + var checkArgType = excludeArgument ? getRegularTypeOfObjectLiteral(argType) : argType; + if (!checkTypeRelatedToAndOptionallyElaborate(checkArgType, paramType, relation, reportErrors ? arg : undefined, arg, headMessage)) { + return false; + } + } + } + if (restType) { + var spreadType = getSpreadArgumentType(args, argCount, args.length, restType, /*context*/ undefined); + var errorNode = reportErrors ? argCount < args.length ? args[argCount] : node : undefined; + return checkTypeRelatedTo(spreadType, restType, relation, errorNode, headMessage); + } + return true; + } + /** + * Returns the this argument in calls like x.f(...) and x[f](...). Undefined otherwise. + */ + function getThisArgumentOfCall(node) { + if (node.kind === 191 /* CallExpression */) { + var callee = ts.skipOuterExpressions(node.expression); + if (callee.kind === 189 /* PropertyAccessExpression */ || callee.kind === 190 /* ElementAccessExpression */) { + return callee.expression; + } + } + } + function createSyntheticExpression(parent, type, isSpread) { + var result = ts.createNode(215 /* SyntheticExpression */, parent.pos, parent.end); + result.parent = parent; + result.type = type; + result.isSpread = isSpread || false; + return result; + } + /** + * Returns the effective arguments for an expression that works like a function invocation. + */ + function getEffectiveCallArguments(node) { + if (node.kind === 193 /* TaggedTemplateExpression */) { + var template = node.template; + var args_4 = [createSyntheticExpression(template, getGlobalTemplateStringsArrayType())]; + if (template.kind === 206 /* TemplateExpression */) { + ts.forEach(template.templateSpans, function (span) { + args_4.push(span.expression); + }); + } + return args_4; + } + if (node.kind === 152 /* Decorator */) { + return getEffectiveDecoratorArguments(node); + } + if (ts.isJsxOpeningLikeElement(node)) { + return node.attributes.properties.length > 0 || (ts.isJsxOpeningElement(node) && node.parent.children.length > 0) ? [node.attributes] : ts.emptyArray; + } + var args = node.arguments || ts.emptyArray; + var length = args.length; + if (length && isSpreadArgument(args[length - 1]) && getSpreadArgumentIndex(args) === length - 1) { + // We have a spread argument in the last position and no other spread arguments. If the type + // of the argument is a tuple type, spread the tuple elements into the argument list. We can + // call checkExpressionCached because spread expressions never have a contextual type. + var spreadArgument_1 = args[length - 1]; + var type = checkExpressionCached(spreadArgument_1.expression); + if (isTupleType(type)) { + var typeArguments = type.typeArguments || ts.emptyArray; + var restIndex_2 = type.target.hasRestElement ? typeArguments.length - 1 : -1; + var syntheticArgs = ts.map(typeArguments, function (t, i) { return createSyntheticExpression(spreadArgument_1, t, /*isSpread*/ i === restIndex_2); }); + return ts.concatenate(args.slice(0, length - 1), syntheticArgs); + } + } + return args; + } + /** + * Returns the synthetic argument list for a decorator invocation. + */ + function getEffectiveDecoratorArguments(node) { + var parent = node.parent; + var expr = node.expression; + switch (parent.kind) { + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + // For a class decorator, the `target` is the type of the class (e.g. the + // "static" or "constructor" side of the class). + return [ + createSyntheticExpression(expr, getTypeOfSymbol(getSymbolOfNode(parent))) + ]; + case 151 /* Parameter */: + // A parameter declaration decorator will have three arguments (see + // `ParameterDecorator` in core.d.ts). + var func = parent.parent; + return [ + createSyntheticExpression(expr, parent.parent.kind === 157 /* Constructor */ ? getTypeOfSymbol(getSymbolOfNode(func)) : errorType), + createSyntheticExpression(expr, anyType), + createSyntheticExpression(expr, numberType) + ]; + case 154 /* PropertyDeclaration */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + // A method or accessor declaration decorator will have two or three arguments (see + // `PropertyDecorator` and `MethodDecorator` in core.d.ts). If we are emitting decorators + // for ES3, we will only pass two arguments. + var hasPropDesc = parent.kind !== 154 /* PropertyDeclaration */ && languageVersion !== 0 /* ES3 */; + return [ + createSyntheticExpression(expr, getParentTypeOfClassElement(parent)), + createSyntheticExpression(expr, getClassElementPropertyKeyType(parent)), + createSyntheticExpression(expr, hasPropDesc ? createTypedPropertyDescriptorType(getTypeOfNode(parent)) : anyType) + ]; + } + return ts.Debug.fail(); + } + /** + * Returns the argument count for a decorator node that works like a function invocation. + */ + function getDecoratorArgumentCount(node, signature) { + switch (node.parent.kind) { + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + return 1; + case 154 /* PropertyDeclaration */: + return 2; + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + // For ES3 or decorators with only two parameters we supply only two arguments + return languageVersion === 0 /* ES3 */ || signature.parameters.length <= 2 ? 2 : 3; + case 151 /* Parameter */: + return 3; + default: + return ts.Debug.fail(); + } + } + function getArgumentArityError(node, signatures, args) { + var min = Number.POSITIVE_INFINITY; + var max = Number.NEGATIVE_INFINITY; + var belowArgCount = Number.NEGATIVE_INFINITY; + var aboveArgCount = Number.POSITIVE_INFINITY; + var argCount = args.length; + var closestSignature; + for (var _i = 0, signatures_4 = signatures; _i < signatures_4.length; _i++) { + var sig = signatures_4[_i]; + var minCount = getMinArgumentCount(sig); + var maxCount = getParameterCount(sig); + if (minCount < argCount && minCount > belowArgCount) + belowArgCount = minCount; + if (argCount < maxCount && maxCount < aboveArgCount) + aboveArgCount = maxCount; + if (minCount < min) { + min = minCount; + closestSignature = sig; + } + max = Math.max(max, maxCount); + } + var hasRestParameter = ts.some(signatures, hasEffectiveRestParameter); + var paramRange = hasRestParameter ? min : + min < max ? min + "-" + max : + min; + var hasSpreadArgument = getSpreadArgumentIndex(args) > -1; + if (argCount <= max && hasSpreadArgument) { + argCount--; + } + var related; + if (closestSignature && getMinArgumentCount(closestSignature) > argCount && closestSignature.declaration) { + var paramDecl = closestSignature.declaration.parameters[closestSignature.thisParameter ? argCount + 1 : argCount]; + if (paramDecl) { + related = ts.createDiagnosticForNode(paramDecl, ts.isBindingPattern(paramDecl.name) ? ts.Diagnostics.An_argument_matching_this_binding_pattern_was_not_provided : ts.Diagnostics.An_argument_for_0_was_not_provided, !paramDecl.name ? argCount : !ts.isBindingPattern(paramDecl.name) ? ts.idText(getFirstIdentifier(paramDecl.name)) : undefined); + } + } + if (hasRestParameter || hasSpreadArgument) { + var error_1 = hasRestParameter && hasSpreadArgument ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1_or_more : + hasRestParameter ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1 : + ts.Diagnostics.Expected_0_arguments_but_got_1_or_more; + var diagnostic_1 = ts.createDiagnosticForNode(node, error_1, paramRange, argCount); + return related ? addRelatedInfo(diagnostic_1, related) : diagnostic_1; + } + if (min < argCount && argCount < max) { + return ts.createDiagnosticForNode(node, ts.Diagnostics.No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments, argCount, belowArgCount, aboveArgCount); + } + var diagnostic = ts.createDiagnosticForNode(node, ts.Diagnostics.Expected_0_arguments_but_got_1, paramRange, argCount); + return related ? addRelatedInfo(diagnostic, related) : diagnostic; + } + function getTypeArgumentArityError(node, signatures, typeArguments) { + var min = Infinity; + var max = -Infinity; + for (var _i = 0, signatures_5 = signatures; _i < signatures_5.length; _i++) { + var sig = signatures_5[_i]; + min = Math.min(min, getMinTypeArgumentCount(sig.typeParameters)); + max = Math.max(max, ts.length(sig.typeParameters)); + } + var paramCount = min === max ? min : min + "-" + max; + return ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), typeArguments, ts.Diagnostics.Expected_0_type_arguments_but_got_1, paramCount, typeArguments.length); + } + function resolveCall(node, signatures, candidatesOutArray, isForSignatureHelp, fallbackError) { + var isTaggedTemplate = node.kind === 193 /* TaggedTemplateExpression */; + var isDecorator = node.kind === 152 /* Decorator */; + var isJsxOpeningOrSelfClosingElement = ts.isJsxOpeningLikeElement(node); + var reportErrors = !candidatesOutArray; + var typeArguments; + if (!isDecorator) { + typeArguments = node.typeArguments; + // We already perform checking on the type arguments on the class declaration itself. + if (isTaggedTemplate || isJsxOpeningOrSelfClosingElement || node.expression.kind !== 98 /* SuperKeyword */) { + ts.forEach(typeArguments, checkSourceElement); + } + } + var candidates = candidatesOutArray || []; + // reorderCandidates fills up the candidates array directly + reorderCandidates(signatures, candidates); + if (!candidates.length) { + if (reportErrors) { + diagnostics.add(ts.createDiagnosticForNode(node, ts.Diagnostics.Call_target_does_not_contain_any_signatures)); + } + return resolveErrorCall(node); + } + var args = getEffectiveCallArguments(node); + // The excludeArgument array contains true for each context sensitive argument (an argument + // is context sensitive it is susceptible to a one-time permanent contextual typing). + // + // The idea is that we will perform type argument inference & assignability checking once + // without using the susceptible parameters that are functions, and once more for those + // parameters, contextually typing each as we go along. + // + // For a tagged template, then the first argument be 'undefined' if necessary because it + // represents a TemplateStringsArray. + // + // For a decorator, no arguments are susceptible to contextual typing due to the fact + // decorators are applied to a declaration by the emitter, and not to an expression. + var isSingleNonGenericCandidate = candidates.length === 1 && !candidates[0].typeParameters; + var excludeArgument = !isDecorator && !isSingleNonGenericCandidate ? getExcludeArgument(args) : undefined; + // The following variables are captured and modified by calls to chooseOverload. + // If overload resolution or type argument inference fails, we want to report the + // best error possible. The best error is one which says that an argument was not + // assignable to a parameter. This implies that everything else about the overload + // was fine. So if there is any overload that is only incorrect because of an + // argument, we will report an error on that one. + // + // function foo(s: string): void; + // function foo(n: number): void; // Report argument error on this overload + // function foo(): void; + // foo(true); + // + // If none of the overloads even made it that far, there are two possibilities. + // There was a problem with type arguments for some overload, in which case + // report an error on that. Or none of the overloads even had correct arity, + // in which case give an arity error. + // + // function foo(x: T): void; // Report type argument error + // function foo(): void; + // foo(0); + // + var candidateForArgumentError; + var candidateForArgumentArityError; + var candidateForTypeArgumentError; + var result; + // If we are in signature help, a trailing comma indicates that we intend to provide another argument, + // so we will only accept overloads with arity at least 1 higher than the current number of provided arguments. + var signatureHelpTrailingComma = isForSignatureHelp && node.kind === 191 /* CallExpression */ && node.arguments.hasTrailingComma; + // Section 4.12.1: + // if the candidate list contains one or more signatures for which the type of each argument + // expression is a subtype of each corresponding parameter type, the return type of the first + // of those signatures becomes the return type of the function call. + // Otherwise, the return type of the first signature in the candidate list becomes the return + // type of the function call. + // + // Whether the call is an error is determined by assignability of the arguments. The subtype pass + // is just important for choosing the best signature. So in the case where there is only one + // signature, the subtype pass is useless. So skipping it is an optimization. + if (candidates.length > 1) { + result = chooseOverload(candidates, subtypeRelation, signatureHelpTrailingComma); + } + if (!result) { + result = chooseOverload(candidates, assignableRelation, signatureHelpTrailingComma); + } + if (result) { + return result; + } + // No signatures were applicable. Now report errors based on the last applicable signature with + // no arguments excluded from assignability checks. + // If candidate is undefined, it means that no candidates had a suitable arity. In that case, + // skip the checkApplicableSignature check. + if (reportErrors) { + if (candidateForArgumentError) { + // excludeArgument is undefined, in this case also equivalent to [undefined, undefined, ...] + // The importance of excludeArgument is to prevent us from typing function expression parameters + // in arguments too early. If possible, we'd like to only type them once we know the correct + // overload. However, this matters for the case where the call is correct. When the call is + // an error, we don't need to exclude any arguments, although it would cause no harm to do so. + checkApplicableSignature(node, args, candidateForArgumentError, assignableRelation, /*excludeArgument*/ undefined, /*reportErrors*/ true); + } + else if (candidateForArgumentArityError) { + diagnostics.add(getArgumentArityError(node, [candidateForArgumentArityError], args)); + } + else if (candidateForTypeArgumentError) { + checkTypeArguments(candidateForTypeArgumentError, node.typeArguments, /*reportErrors*/ true, fallbackError); + } + else { + var signaturesWithCorrectTypeArgumentArity = ts.filter(signatures, function (s) { return hasCorrectTypeArgumentArity(s, typeArguments); }); + if (signaturesWithCorrectTypeArgumentArity.length === 0) { + diagnostics.add(getTypeArgumentArityError(node, signatures, typeArguments)); + } + else if (!isDecorator) { + diagnostics.add(getArgumentArityError(node, signaturesWithCorrectTypeArgumentArity, args)); + } + else if (fallbackError) { + diagnostics.add(ts.createDiagnosticForNode(node, fallbackError)); + } + } + } + return produceDiagnostics || !args ? resolveErrorCall(node) : getCandidateForOverloadFailure(node, candidates, args, !!candidatesOutArray); + function chooseOverload(candidates, relation, signatureHelpTrailingComma) { + if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; } + candidateForArgumentError = undefined; + candidateForArgumentArityError = undefined; + candidateForTypeArgumentError = undefined; + if (isSingleNonGenericCandidate) { + var candidate = candidates[0]; + if (typeArguments || !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) { + return undefined; + } + if (!checkApplicableSignature(node, args, candidate, relation, excludeArgument, /*reportErrors*/ false)) { + candidateForArgumentError = candidate; + return undefined; + } + return candidate; + } + for (var candidateIndex = 0; candidateIndex < candidates.length; candidateIndex++) { + var candidate = candidates[candidateIndex]; + if (!hasCorrectTypeArgumentArity(candidate, typeArguments) || !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) { + continue; + } + var checkCandidate = void 0; + var inferenceContext = void 0; + if (candidate.typeParameters) { + var typeArgumentTypes = void 0; + if (typeArguments) { + typeArgumentTypes = checkTypeArguments(candidate, typeArguments, /*reportErrors*/ false); + if (!typeArgumentTypes) { + candidateForTypeArgumentError = candidate; + continue; + } + } + else { + inferenceContext = createInferenceContext(candidate.typeParameters, candidate, /*flags*/ ts.isInJSFile(node) ? 2 /* AnyDefault */ : 0 /* None */); + typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); + } + checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration)); + // If the original signature has a generic rest type, instantiation may produce a + // signature with different arity and we need to perform another arity check. + if (getNonArrayRestType(candidate) && !hasCorrectArity(node, args, checkCandidate, signatureHelpTrailingComma)) { + candidateForArgumentArityError = checkCandidate; + continue; + } + } + else { + checkCandidate = candidate; + } + if (!checkApplicableSignature(node, args, checkCandidate, relation, excludeArgument, /*reportErrors*/ false)) { + // Give preference to error candidates that have no rest parameters (as they are more specific) + if (!candidateForArgumentError || getEffectiveRestType(candidateForArgumentError) || !getEffectiveRestType(checkCandidate)) { + candidateForArgumentError = checkCandidate; + } + continue; + } + if (excludeArgument) { + // If one or more context sensitive arguments were excluded, we start including + // them now (and keeping do so for any subsequent candidates) and perform a second + // round of type inference and applicability checking for this particular candidate. + excludeArgument = undefined; + if (inferenceContext) { + var typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); + checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration)); + } + if (!checkApplicableSignature(node, args, checkCandidate, relation, excludeArgument, /*reportErrors*/ false)) { + // Give preference to error candidates that have no rest parameters (as they are more specific) + if (!candidateForArgumentError || getEffectiveRestType(candidateForArgumentError) || !getEffectiveRestType(checkCandidate)) { + candidateForArgumentError = checkCandidate; + } + continue; + } + } + candidates[candidateIndex] = checkCandidate; + return checkCandidate; + } + return undefined; + } + } + function getExcludeArgument(args) { + var excludeArgument; + // We do not need to call `getEffectiveArgumentCount` here as it only + // applies when calculating the number of arguments for a decorator. + for (var i = 0; i < args.length; i++) { + if (isContextSensitive(args[i])) { + if (!excludeArgument) { + excludeArgument = new Array(args.length); + } + excludeArgument[i] = true; + } + } + return excludeArgument; + } + // No signature was applicable. We have already reported the errors for the invalid signature. + // If this is a type resolution session, e.g. Language Service, try to get better information than anySignature. + function getCandidateForOverloadFailure(node, candidates, args, hasCandidatesOutArray) { + ts.Debug.assert(candidates.length > 0); // Else should not have called this. + // Normally we will combine overloads. Skip this if they have type parameters since that's hard to combine. + // Don't do this if there is a `candidatesOutArray`, + // because then we want the chosen best candidate to be one of the overloads, not a combination. + return hasCandidatesOutArray || candidates.length === 1 || candidates.some(function (c) { return !!c.typeParameters; }) + ? pickLongestCandidateSignature(node, candidates, args) + : createUnionOfSignaturesForOverloadFailure(candidates); + } + function createUnionOfSignaturesForOverloadFailure(candidates) { + var thisParameters = ts.mapDefined(candidates, function (c) { return c.thisParameter; }); + var thisParameter; + if (thisParameters.length) { + thisParameter = createCombinedSymbolFromTypes(thisParameters, thisParameters.map(getTypeOfParameter)); + } + var _a = ts.minAndMax(candidates, getNumNonRestParameters), minArgumentCount = _a.min, maxNonRestParam = _a.max; + var parameters = []; + var _loop_7 = function (i) { + var symbols = ts.mapDefined(candidates, function (_a) { + var parameters = _a.parameters, hasRestParameter = _a.hasRestParameter; + return hasRestParameter ? + i < parameters.length - 1 ? parameters[i] : ts.last(parameters) : + i < parameters.length ? parameters[i] : undefined; + }); + ts.Debug.assert(symbols.length !== 0); + parameters.push(createCombinedSymbolFromTypes(symbols, ts.mapDefined(candidates, function (candidate) { return tryGetTypeAtPosition(candidate, i); }))); + }; + for (var i = 0; i < maxNonRestParam; i++) { + _loop_7(i); + } + var restParameterSymbols = ts.mapDefined(candidates, function (c) { return c.hasRestParameter ? ts.last(c.parameters) : undefined; }); + var hasRestParameter = restParameterSymbols.length !== 0; + if (hasRestParameter) { + var type = createArrayType(getUnionType(ts.mapDefined(candidates, tryGetRestTypeOfSignature), 2 /* Subtype */)); + parameters.push(createCombinedSymbolForOverloadFailure(restParameterSymbols, type)); + } + return createSignature(candidates[0].declaration, + /*typeParameters*/ undefined, // Before calling this we tested for `!candidates.some(c => !!c.typeParameters)`. + thisParameter, parameters, + /*resolvedReturnType*/ getIntersectionType(candidates.map(getReturnTypeOfSignature)), + /*typePredicate*/ undefined, minArgumentCount, hasRestParameter, + /*hasLiteralTypes*/ candidates.some(function (c) { return c.hasLiteralTypes; })); + } + function getNumNonRestParameters(signature) { + var numParams = signature.parameters.length; + return signature.hasRestParameter ? numParams - 1 : numParams; + } + function createCombinedSymbolFromTypes(sources, types) { + return createCombinedSymbolForOverloadFailure(sources, getUnionType(types, 2 /* Subtype */)); + } + function createCombinedSymbolForOverloadFailure(sources, type) { + // This function is currently only used for erroneous overloads, so it's good enough to just use the first source. + return createSymbolWithType(ts.first(sources), type); + } + function pickLongestCandidateSignature(node, candidates, args) { + // Pick the longest signature. This way we can get a contextual type for cases like: + // declare function f(a: { xa: number; xb: number; }, b: number); + // f({ | + // Also, use explicitly-supplied type arguments if they are provided, so we can get a contextual signature in cases like: + // declare function f(k: keyof T); + // f(" + var bestIndex = getLongestCandidateIndex(candidates, apparentArgumentCount === undefined ? args.length : apparentArgumentCount); + var candidate = candidates[bestIndex]; + var typeParameters = candidate.typeParameters; + if (!typeParameters) { + return candidate; + } + var typeArgumentNodes = callLikeExpressionMayHaveTypeArguments(node) ? node.typeArguments : undefined; + var instantiated = typeArgumentNodes + ? createSignatureInstantiation(candidate, getTypeArgumentsFromNodes(typeArgumentNodes, typeParameters, ts.isInJSFile(node))) + : inferSignatureInstantiationForOverloadFailure(node, typeParameters, candidate, args); + candidates[bestIndex] = instantiated; + return instantiated; + } + function getTypeArgumentsFromNodes(typeArgumentNodes, typeParameters, isJs) { + var typeArguments = typeArgumentNodes.map(getTypeOfNode); + while (typeArguments.length > typeParameters.length) { + typeArguments.pop(); + } + while (typeArguments.length < typeParameters.length) { + typeArguments.push(getConstraintOfTypeParameter(typeParameters[typeArguments.length]) || getDefaultTypeArgumentType(isJs)); + } + return typeArguments; + } + function inferSignatureInstantiationForOverloadFailure(node, typeParameters, candidate, args) { + var inferenceContext = createInferenceContext(typeParameters, candidate, /*flags*/ ts.isInJSFile(node) ? 2 /* AnyDefault */ : 0 /* None */); + var typeArgumentTypes = inferTypeArguments(node, candidate, args, getExcludeArgument(args), inferenceContext); + return createSignatureInstantiation(candidate, typeArgumentTypes); + } + function getLongestCandidateIndex(candidates, argsCount) { + var maxParamsIndex = -1; + var maxParams = -1; + for (var i = 0; i < candidates.length; i++) { + var candidate = candidates[i]; + var paramCount = getParameterCount(candidate); + if (hasEffectiveRestParameter(candidate) || paramCount >= argsCount) { + return i; + } + if (paramCount > maxParams) { + maxParams = paramCount; + maxParamsIndex = i; + } + } + return maxParamsIndex; + } + function resolveCallExpression(node, candidatesOutArray, isForSignatureHelp) { + if (node.expression.kind === 98 /* SuperKeyword */) { + var superType = checkSuperExpression(node.expression); + if (isTypeAny(superType)) { + for (var _i = 0, _a = node.arguments; _i < _a.length; _i++) { + var arg = _a[_i]; + checkExpression(arg); // Still visit arguments so they get marked for visibility, etc + } + return anySignature; + } + if (superType !== errorType) { + // In super call, the candidate signatures are the matching arity signatures of the base constructor function instantiated + // with the type arguments specified in the extends clause. + var baseTypeNode = ts.getEffectiveBaseTypeNode(ts.getContainingClass(node)); + if (baseTypeNode) { + var baseConstructors = getInstantiatedConstructorsForTypeArguments(superType, baseTypeNode.typeArguments, baseTypeNode); + return resolveCall(node, baseConstructors, candidatesOutArray, isForSignatureHelp); + } + } + return resolveUntypedCall(node); + } + var funcType = checkNonNullExpression(node.expression, ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_null, ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_undefined, ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_null_or_undefined); + if (funcType === silentNeverType) { + return silentNeverSignature; + } + var apparentType = getApparentType(funcType); + if (apparentType === errorType) { + // Another error has already been reported + return resolveErrorCall(node); + } + // Technically, this signatures list may be incomplete. We are taking the apparent type, + // but we are not including call signatures that may have been added to the Object or + // Function interface, since they have none by default. This is a bit of a leap of faith + // that the user will not add any. + var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */); + var numConstructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */).length; + // TS 1.0 Spec: 4.12 + // In an untyped function call no TypeArgs are permitted, Args can be any argument list, no contextual + // types are provided for the argument expressions, and the result is always of type Any. + if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, numConstructSignatures)) { + // The unknownType indicates that an error already occurred (and was reported). No + // need to report another error in this case. + if (funcType !== errorType && node.typeArguments) { + error(node, ts.Diagnostics.Untyped_function_calls_may_not_accept_type_arguments); + } + return resolveUntypedCall(node); + } + // If FuncExpr's apparent type(section 3.8.1) is a function type, the call is a typed function call. + // TypeScript employs overload resolution in typed function calls in order to support functions + // with multiple call signatures. + if (!callSignatures.length) { + if (numConstructSignatures) { + error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType)); + } + else { + var relatedInformation = void 0; + if (node.arguments.length === 1) { + var text = ts.getSourceFileOfNode(node).text; + if (ts.isLineBreak(text.charCodeAt(ts.skipTrivia(text, node.expression.end, /* stopAfterLineBreak */ true) - 1))) { + relatedInformation = ts.createDiagnosticForNode(node.expression, ts.Diagnostics.It_is_highly_likely_that_you_are_missing_a_semicolon); + } + } + invocationError(node, apparentType, 0 /* Call */, relatedInformation); + } + return resolveErrorCall(node); + } + // If the function is explicitly marked with `@class`, then it must be constructed. + if (callSignatures.some(function (sig) { return ts.isInJSFile(sig.declaration) && !!ts.getJSDocClassTag(sig.declaration); })) { + error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType)); + return resolveErrorCall(node); + } + return resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp); + } + /** + * TS 1.0 spec: 4.12 + * If FuncExpr is of type Any, or of an object type that has no call or construct signatures + * but is a subtype of the Function interface, the call is an untyped function call. + */ + function isUntypedFunctionCall(funcType, apparentFuncType, numCallSignatures, numConstructSignatures) { + // We exclude union types because we may have a union of function types that happen to have no common signatures. + return isTypeAny(funcType) || isTypeAny(apparentFuncType) && funcType.flags & 262144 /* TypeParameter */ || + !numCallSignatures && !numConstructSignatures && !(apparentFuncType.flags & (1048576 /* Union */ | 131072 /* Never */)) && isTypeAssignableTo(funcType, globalFunctionType); + } + function resolveNewExpression(node, candidatesOutArray, isForSignatureHelp) { + if (node.arguments && languageVersion < 1 /* ES5 */) { + var spreadIndex = getSpreadArgumentIndex(node.arguments); + if (spreadIndex >= 0) { + error(node.arguments[spreadIndex], ts.Diagnostics.Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher); + } + } + var expressionType = checkNonNullExpression(node.expression); + if (expressionType === silentNeverType) { + return silentNeverSignature; + } + // If expressionType's apparent type(section 3.8.1) is an object type with one or + // more construct signatures, the expression is processed in the same manner as a + // function call, but using the construct signatures as the initial set of candidate + // signatures for overload resolution. The result type of the function call becomes + // the result type of the operation. + expressionType = getApparentType(expressionType); + if (expressionType === errorType) { + // Another error has already been reported + return resolveErrorCall(node); + } + // TS 1.0 spec: 4.11 + // If expressionType is of type Any, Args can be any argument + // list and the result of the operation is of type Any. + if (isTypeAny(expressionType)) { + if (node.typeArguments) { + error(node, ts.Diagnostics.Untyped_function_calls_may_not_accept_type_arguments); + } + return resolveUntypedCall(node); + } + // Technically, this signatures list may be incomplete. We are taking the apparent type, + // but we are not including construct signatures that may have been added to the Object or + // Function interface, since they have none by default. This is a bit of a leap of faith + // that the user will not add any. + var constructSignatures = getSignaturesOfType(expressionType, 1 /* Construct */); + if (constructSignatures.length) { + if (!isConstructorAccessible(node, constructSignatures[0])) { + return resolveErrorCall(node); + } + // If the expression is a class of abstract type, then it cannot be instantiated. + // Note, only class declarations can be declared abstract. + // In the case of a merged class-module or class-interface declaration, + // only the class declaration node will have the Abstract flag set. + var valueDecl = expressionType.symbol && ts.getClassLikeDeclarationOfSymbol(expressionType.symbol); + if (valueDecl && ts.hasModifier(valueDecl, 128 /* Abstract */)) { + error(node, ts.Diagnostics.Cannot_create_an_instance_of_an_abstract_class); + return resolveErrorCall(node); + } + return resolveCall(node, constructSignatures, candidatesOutArray, isForSignatureHelp); + } + // If expressionType's apparent type is an object type with no construct signatures but + // one or more call signatures, the expression is processed as a function call. A compile-time + // error occurs if the result of the function call is not Void. The type of the result of the + // operation is Any. It is an error to have a Void this type. + var callSignatures = getSignaturesOfType(expressionType, 0 /* Call */); + if (callSignatures.length) { + var signature = resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp); + if (!noImplicitAny) { + if (signature.declaration && !isJSConstructor(signature.declaration) && getReturnTypeOfSignature(signature) !== voidType) { + error(node, ts.Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword); + } + if (getThisTypeOfSignature(signature) === voidType) { + error(node, ts.Diagnostics.A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void); + } + } + return signature; + } + invocationError(node, expressionType, 1 /* Construct */); + return resolveErrorCall(node); + } + function typeHasProtectedAccessibleBase(target, type) { + var baseTypes = getBaseTypes(type); + if (!ts.length(baseTypes)) { + return false; + } + var firstBase = baseTypes[0]; + if (firstBase.flags & 2097152 /* Intersection */) { + var types = firstBase.types; + var mixinCount = ts.countWhere(types, isMixinConstructorType); + var i = 0; + for (var _i = 0, _a = firstBase.types; _i < _a.length; _i++) { + var intersectionMember = _a[_i]; + i++; + // We want to ignore mixin ctors + if (mixinCount === 0 || mixinCount === types.length && i === 0 || !isMixinConstructorType(intersectionMember)) { + if (ts.getObjectFlags(intersectionMember) & (1 /* Class */ | 2 /* Interface */)) { + if (intersectionMember.symbol === target) { + return true; + } + if (typeHasProtectedAccessibleBase(target, intersectionMember)) { + return true; + } + } + } + } + return false; + } + if (firstBase.symbol === target) { + return true; + } + return typeHasProtectedAccessibleBase(target, firstBase); + } + function isConstructorAccessible(node, signature) { + if (!signature || !signature.declaration) { + return true; + } + var declaration = signature.declaration; + var modifiers = ts.getSelectedModifierFlags(declaration, 24 /* NonPublicAccessibilityModifier */); + // Public constructor is accessible. + if (!modifiers) { + return true; + } + var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(declaration.parent.symbol); + var declaringClass = getDeclaredTypeOfSymbol(declaration.parent.symbol); + // A private or protected constructor can only be instantiated within its own class (or a subclass, for protected) + if (!isNodeWithinClass(node, declaringClassDeclaration)) { + var containingClass = ts.getContainingClass(node); + if (containingClass && modifiers & 16 /* Protected */) { + var containingType = getTypeOfNode(containingClass); + if (typeHasProtectedAccessibleBase(declaration.parent.symbol, containingType)) { + return true; + } + } + if (modifiers & 8 /* Private */) { + error(node, ts.Diagnostics.Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration, typeToString(declaringClass)); + } + if (modifiers & 16 /* Protected */) { + error(node, ts.Diagnostics.Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration, typeToString(declaringClass)); + } + return false; + } + return true; + } + function invocationError(node, apparentType, kind, relatedInformation) { + var diagnostic = error(node, (kind === 0 /* Call */ ? + ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures : + ts.Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature), typeToString(apparentType)); + invocationErrorRecovery(apparentType, kind, relatedInformation ? addRelatedInfo(diagnostic, relatedInformation) : diagnostic); + } + function invocationErrorRecovery(apparentType, kind, diagnostic) { + if (!apparentType.symbol) { + return; + } + var importNode = getSymbolLinks(apparentType.symbol).originatingImport; + // Create a diagnostic on the originating import if possible onto which we can attach a quickfix + // An import call expression cannot be rewritten into another form to correct the error - the only solution is to use `.default` at the use-site + if (importNode && !ts.isImportCall(importNode)) { + var sigs = getSignaturesOfType(getTypeOfSymbol(getSymbolLinks(apparentType.symbol).target), kind); + if (!sigs || !sigs.length) + return; + addRelatedInfo(diagnostic, ts.createDiagnosticForNode(importNode, ts.Diagnostics.Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_Consider_using_a_default_import_or_import_require_here_instead)); + } + } + function resolveTaggedTemplateExpression(node, candidatesOutArray, isForSignatureHelp) { + var tagType = checkExpression(node.tag); + var apparentType = getApparentType(tagType); + if (apparentType === errorType) { + // Another error has already been reported + return resolveErrorCall(node); + } + var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */); + var numConstructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */).length; + if (isUntypedFunctionCall(tagType, apparentType, callSignatures.length, numConstructSignatures)) { + return resolveUntypedCall(node); + } + if (!callSignatures.length) { + invocationError(node, apparentType, 0 /* Call */); + return resolveErrorCall(node); + } + return resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp); + } + /** + * Gets the localized diagnostic head message to use for errors when resolving a decorator as a call expression. + */ + function getDiagnosticHeadMessageForDecoratorResolution(node) { + switch (node.parent.kind) { + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + return ts.Diagnostics.Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression; + case 151 /* Parameter */: + return ts.Diagnostics.Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression; + case 154 /* PropertyDeclaration */: + return ts.Diagnostics.Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression; + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + return ts.Diagnostics.Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression; + default: + return ts.Debug.fail(); + } + } + /** + * Resolves a decorator as if it were a call expression. + */ + function resolveDecorator(node, candidatesOutArray, isForSignatureHelp) { + var funcType = checkExpression(node.expression); + var apparentType = getApparentType(funcType); + if (apparentType === errorType) { + return resolveErrorCall(node); + } + var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */); + var numConstructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */).length; + if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, numConstructSignatures)) { + return resolveUntypedCall(node); + } + if (isPotentiallyUncalledDecorator(node, callSignatures)) { + var nodeStr = ts.getTextOfNode(node.expression, /*includeTrivia*/ false); + error(node, ts.Diagnostics._0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write_0, nodeStr); + return resolveErrorCall(node); + } + var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); + if (!callSignatures.length) { + var errorInfo = ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures, typeToString(apparentType)); + errorInfo = ts.chainDiagnosticMessages(errorInfo, headMessage); + var diag = ts.createDiagnosticForNodeFromMessageChain(node, errorInfo); + diagnostics.add(diag); + invocationErrorRecovery(apparentType, 0 /* Call */, diag); + return resolveErrorCall(node); + } + return resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp, headMessage); + } + function createSignatureForJSXIntrinsic(node, result) { + var namespace = getJsxNamespaceAt(node); + var exports = namespace && getExportsOfSymbol(namespace); + // We fake up a SFC signature for each intrinsic, however a more specific per-element signature drawn from the JSX declaration + // file would probably be preferable. + var typeSymbol = exports && getSymbol(exports, JsxNames.Element, 67897832 /* Type */); + var returnNode = typeSymbol && nodeBuilder.symbolToEntityName(typeSymbol, 67897832 /* Type */, node); + var declaration = ts.createFunctionTypeNode(/*typeParameters*/ undefined, [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotdotdot*/ undefined, "props", /*questionMark*/ undefined, nodeBuilder.typeToTypeNode(result, node))], returnNode ? ts.createTypeReferenceNode(returnNode, /*typeArguments*/ undefined) : ts.createKeywordTypeNode(120 /* AnyKeyword */)); + var parameterSymbol = createSymbol(1 /* FunctionScopedVariable */, "props"); + parameterSymbol.type = result; + return createSignature(declaration, + /*typeParameters*/ undefined, + /*thisParameter*/ undefined, [parameterSymbol], typeSymbol ? getDeclaredTypeOfSymbol(typeSymbol) : errorType, + /*returnTypePredicate*/ undefined, 1, + /*hasRestparameter*/ false, + /*hasLiteralTypes*/ false); + } + function resolveJsxOpeningLikeElement(node, candidatesOutArray, isForSignatureHelp) { + if (isJsxIntrinsicIdentifier(node.tagName)) { + var result = getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node); + var fakeSignature = createSignatureForJSXIntrinsic(node, result); + checkTypeAssignableToAndOptionallyElaborate(checkExpressionWithContextualType(node.attributes, getEffectiveFirstArgumentForJsxSignature(fakeSignature, node), /*mapper*/ undefined), result, node.tagName, node.attributes); + return fakeSignature; + } + var exprTypes = checkExpression(node.tagName); + var apparentType = getApparentType(exprTypes); + if (apparentType === errorType) { + return resolveErrorCall(node); + } + var signatures = getUninstantiatedJsxSignaturesOfType(exprTypes, node); + if (isUntypedFunctionCall(exprTypes, apparentType, signatures.length, /*constructSignatures*/ 0)) { + return resolveUntypedCall(node); + } + if (signatures.length === 0) { + // We found no signatures at all, which is an error + error(node.tagName, ts.Diagnostics.JSX_element_type_0_does_not_have_any_construct_or_call_signatures, ts.getTextOfNode(node.tagName)); + return resolveErrorCall(node); + } + return resolveCall(node, signatures, candidatesOutArray, isForSignatureHelp); + } + /** + * Sometimes, we have a decorator that could accept zero arguments, + * but is receiving too many arguments as part of the decorator invocation. + * In those cases, a user may have meant to *call* the expression before using it as a decorator. + */ + function isPotentiallyUncalledDecorator(decorator, signatures) { + return signatures.length && ts.every(signatures, function (signature) { + return signature.minArgumentCount === 0 && + !signature.hasRestParameter && + signature.parameters.length < getDecoratorArgumentCount(decorator, signature); + }); + } + function resolveSignature(node, candidatesOutArray, isForSignatureHelp) { + switch (node.kind) { + case 191 /* CallExpression */: + return resolveCallExpression(node, candidatesOutArray, isForSignatureHelp); + case 192 /* NewExpression */: + return resolveNewExpression(node, candidatesOutArray, isForSignatureHelp); + case 193 /* TaggedTemplateExpression */: + return resolveTaggedTemplateExpression(node, candidatesOutArray, isForSignatureHelp); + case 152 /* Decorator */: + return resolveDecorator(node, candidatesOutArray, isForSignatureHelp); + case 262 /* JsxOpeningElement */: + case 261 /* JsxSelfClosingElement */: + return resolveJsxOpeningLikeElement(node, candidatesOutArray, isForSignatureHelp); + } + throw ts.Debug.assertNever(node, "Branch in 'resolveSignature' should be unreachable."); + } + /** + * Resolve a signature of a given call-like expression. + * @param node a call-like expression to try resolve a signature for + * @param candidatesOutArray an array of signature to be filled in by the function. It is passed by signature help in the language service; + * the function will fill it up with appropriate candidate signatures + * @return a signature of the call-like expression or undefined if one can't be found + */ + function getResolvedSignature(node, candidatesOutArray, isForSignatureHelp) { + if (isForSignatureHelp === void 0) { isForSignatureHelp = false; } + var links = getNodeLinks(node); + // If getResolvedSignature has already been called, we will have cached the resolvedSignature. + // However, it is possible that either candidatesOutArray was not passed in the first time, + // or that a different candidatesOutArray was passed in. Therefore, we need to redo the work + // to correctly fill the candidatesOutArray. + var cached = links.resolvedSignature; + if (cached && cached !== resolvingSignature && !candidatesOutArray) { + return cached; + } + links.resolvedSignature = resolvingSignature; + var result = resolveSignature(node, candidatesOutArray, isForSignatureHelp); + // If signature resolution originated in control flow type analysis (for example to compute the + // assigned type in a flow assignment) we don't cache the result as it may be based on temporary + // types from the control flow analysis. + links.resolvedSignature = flowLoopStart === flowLoopCount ? result : cached; + return result; + } + /** + * Indicates whether a declaration can be treated as a constructor in a JavaScript + * file. + */ + function isJSConstructor(node) { + if (!node || !ts.isInJSFile(node)) { + return false; + } + var func = ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node) ? node : + ts.isVariableDeclaration(node) && node.initializer && ts.isFunctionExpression(node.initializer) ? node.initializer : + undefined; + if (func) { + // If the node has a @class tag, treat it like a constructor. + if (ts.getJSDocClassTag(node)) + return true; + // If the symbol of the node has members, treat it like a constructor. + var symbol = getSymbolOfNode(func); + return !!symbol && symbol.members !== undefined; + } + return false; + } + function isJSConstructorType(type) { + if (type.flags & 524288 /* Object */) { + var resolved = resolveStructuredTypeMembers(type); + return resolved.callSignatures.length === 1 && isJSConstructor(resolved.callSignatures[0].declaration); + } + return false; + } + function getJSClassType(symbol) { + var inferred; + if (isJSConstructor(symbol.valueDeclaration)) { + inferred = getInferredClassType(symbol); + } + var assigned = getAssignedClassType(symbol); + var valueType = getTypeOfSymbol(symbol); + if (valueType.symbol && !isInferredClassType(valueType) && isJSConstructor(valueType.symbol.valueDeclaration)) { + inferred = getInferredClassType(valueType.symbol); + } + return assigned && inferred ? + getIntersectionType([inferred, assigned]) : + assigned || inferred; + } + function getAssignedClassType(symbol) { + var decl = symbol.valueDeclaration; + var assignmentSymbol = decl && decl.parent && + (ts.isFunctionDeclaration(decl) && getSymbolOfNode(decl) || + ts.isBinaryExpression(decl.parent) && getSymbolOfNode(decl.parent.left) || + ts.isVariableDeclaration(decl.parent) && getSymbolOfNode(decl.parent)); + var prototype = assignmentSymbol && assignmentSymbol.exports && assignmentSymbol.exports.get("prototype"); + var init = prototype && prototype.valueDeclaration && getAssignedJSPrototype(prototype.valueDeclaration); + return init ? checkExpression(init) : undefined; + } + function getAssignedJSPrototype(node) { + if (!node.parent) { + return false; + } + var parent = node.parent; + while (parent && parent.kind === 189 /* PropertyAccessExpression */) { + parent = parent.parent; + } + if (parent && ts.isBinaryExpression(parent) && ts.isPrototypeAccess(parent.left) && parent.operatorToken.kind === 59 /* EqualsToken */) { + var right = ts.getInitializerOfBinaryExpression(parent); + return ts.isObjectLiteralExpression(right) && right; + } + } + function getInferredClassType(symbol) { + var links = getSymbolLinks(symbol); + if (!links.inferredClassType) { + links.inferredClassType = createAnonymousType(symbol, getMembersOfSymbol(symbol) || emptySymbols, ts.emptyArray, ts.emptyArray, /*stringIndexType*/ undefined, /*numberIndexType*/ undefined); + } + return links.inferredClassType; + } + function isInferredClassType(type) { + return type.symbol + && ts.getObjectFlags(type) & 16 /* Anonymous */ + && getSymbolLinks(type.symbol).inferredClassType === type; + } + /** + * Syntactically and semantically checks a call or new expression. + * @param node The call/new expression to be checked. + * @returns On success, the expression's signature's return type. On failure, anyType. + */ + function checkCallExpression(node) { + if (!checkGrammarTypeArguments(node, node.typeArguments)) + checkGrammarArguments(node.arguments); + var signature = getResolvedSignature(node); + if (node.expression.kind === 98 /* SuperKeyword */) { + return voidType; + } + if (node.kind === 192 /* NewExpression */) { + var declaration = signature.declaration; + if (declaration && + declaration.kind !== 157 /* Constructor */ && + declaration.kind !== 161 /* ConstructSignature */ && + declaration.kind !== 166 /* ConstructorType */ && + !ts.isJSDocConstructSignature(declaration)) { + // When resolved signature is a call signature (and not a construct signature) the result type is any, unless + // the declaring function had members created through 'x.prototype.y = expr' or 'this.y = expr' psuedodeclarations + // in a JS file + // Note:JS inferred classes might come from a variable declaration instead of a function declaration. + // In this case, using getResolvedSymbol directly is required to avoid losing the members from the declaration. + var funcSymbol = checkExpression(node.expression).symbol; + if (!funcSymbol && node.expression.kind === 72 /* Identifier */) { + funcSymbol = getResolvedSymbol(node.expression); + } + var type = funcSymbol && getJSClassType(funcSymbol); + if (type) { + return signature.target ? instantiateType(type, signature.mapper) : type; + } + if (noImplicitAny) { + error(node, ts.Diagnostics.new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type); + } + return anyType; + } + } + // In JavaScript files, calls to any identifier 'require' are treated as external module imports + if (ts.isInJSFile(node) && isCommonJsRequire(node)) { + return resolveExternalModuleTypeByLiteral(node.arguments[0]); + } + var returnType = getReturnTypeOfSignature(signature); + // Treat any call to the global 'Symbol' function that is part of a const variable or readonly property + // as a fresh unique symbol literal type. + if (returnType.flags & 12288 /* ESSymbolLike */ && isSymbolOrSymbolForCall(node)) { + return getESSymbolLikeTypeForNode(ts.walkUpParenthesizedExpressions(node.parent)); + } + var jsAssignmentType; + if (ts.isInJSFile(node)) { + var decl = ts.getDeclarationOfExpando(node); + if (decl) { + var jsSymbol = getSymbolOfNode(decl); + if (jsSymbol && ts.hasEntries(jsSymbol.exports)) { + jsAssignmentType = createAnonymousType(jsSymbol, jsSymbol.exports, ts.emptyArray, ts.emptyArray, undefined, undefined); + jsAssignmentType.objectFlags |= 16384 /* JSLiteral */; + } + } + } + return jsAssignmentType ? getIntersectionType([returnType, jsAssignmentType]) : returnType; + } + function isSymbolOrSymbolForCall(node) { + if (!ts.isCallExpression(node)) + return false; + var left = node.expression; + if (ts.isPropertyAccessExpression(left) && left.name.escapedText === "for") { + left = left.expression; + } + if (!ts.isIdentifier(left) || left.escapedText !== "Symbol") { + return false; + } + // make sure `Symbol` is the global symbol + var globalESSymbol = getGlobalESSymbolConstructorSymbol(/*reportErrors*/ false); + if (!globalESSymbol) { + return false; + } + return globalESSymbol === resolveName(left, "Symbol", 67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); + } + function checkImportCallExpression(node) { + // Check grammar of dynamic import + if (!checkGrammarArguments(node.arguments)) + checkGrammarImportCallExpression(node); + if (node.arguments.length === 0) { + return createPromiseReturnType(node, anyType); + } + var specifier = node.arguments[0]; + var specifierType = checkExpressionCached(specifier); + // Even though multiple arguments is grammatically incorrect, type-check extra arguments for completion + for (var i = 1; i < node.arguments.length; ++i) { + checkExpressionCached(node.arguments[i]); + } + if (specifierType.flags & 32768 /* Undefined */ || specifierType.flags & 65536 /* Null */ || !isTypeAssignableTo(specifierType, stringType)) { + error(specifier, ts.Diagnostics.Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0, typeToString(specifierType)); + } + // resolveExternalModuleName will return undefined if the moduleReferenceExpression is not a string literal + var moduleSymbol = resolveExternalModuleName(node, specifier); + if (moduleSymbol) { + var esModuleSymbol = resolveESModuleSymbol(moduleSymbol, specifier, /*dontRecursivelyResolve*/ true); + if (esModuleSymbol) { + return createPromiseReturnType(node, getTypeWithSyntheticDefaultImportType(getTypeOfSymbol(esModuleSymbol), esModuleSymbol, moduleSymbol)); + } + } + return createPromiseReturnType(node, anyType); + } + function getTypeWithSyntheticDefaultImportType(type, symbol, originalSymbol) { + if (allowSyntheticDefaultImports && type && type !== errorType) { + var synthType = type; + if (!synthType.syntheticType) { + var file = ts.find(originalSymbol.declarations, ts.isSourceFile); + var hasSyntheticDefault = canHaveSyntheticDefault(file, originalSymbol, /*dontResolveAlias*/ false); + if (hasSyntheticDefault) { + var memberTable = ts.createSymbolTable(); + var newSymbol = createSymbol(2097152 /* Alias */, "default" /* Default */); + newSymbol.nameType = getLiteralType("default"); + newSymbol.target = resolveSymbol(symbol); + memberTable.set("default" /* Default */, newSymbol); + var anonymousSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */); + var defaultContainingObject = createAnonymousType(anonymousSymbol, memberTable, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined); + anonymousSymbol.type = defaultContainingObject; + synthType.syntheticType = isValidSpreadType(type) ? getSpreadType(type, defaultContainingObject, anonymousSymbol, /*typeFLags*/ 0, /*objectFlags*/ 0) : defaultContainingObject; + } + else { + synthType.syntheticType = type; + } + } + return synthType.syntheticType; + } + return type; + } + function isCommonJsRequire(node) { + if (!ts.isRequireCall(node, /*checkArgumentIsStringLiteralLike*/ true)) { + return false; + } + // Make sure require is not a local function + if (!ts.isIdentifier(node.expression)) + return ts.Debug.fail(); + var resolvedRequire = resolveName(node.expression, node.expression.escapedText, 67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); // TODO: GH#18217 + if (resolvedRequire === requireSymbol) { + return true; + } + // project includes symbol named 'require' - make sure that it is ambient and local non-alias + if (resolvedRequire.flags & 2097152 /* Alias */) { + return false; + } + var targetDeclarationKind = resolvedRequire.flags & 16 /* Function */ + ? 239 /* FunctionDeclaration */ + : resolvedRequire.flags & 3 /* Variable */ + ? 237 /* VariableDeclaration */ + : 0 /* Unknown */; + if (targetDeclarationKind !== 0 /* Unknown */) { + var decl = ts.getDeclarationOfKind(resolvedRequire, targetDeclarationKind); + // function/variable declaration should be ambient + return !!decl && !!(decl.flags & 4194304 /* Ambient */); + } + return false; + } + function checkTaggedTemplateExpression(node) { + checkGrammarTypeArguments(node, node.typeArguments); + if (languageVersion < 2 /* ES2015 */) { + checkExternalEmitHelpers(node, 65536 /* MakeTemplateObject */); + } + return getReturnTypeOfSignature(getResolvedSignature(node)); + } + function checkAssertion(node) { + return checkAssertionWorker(node, node.type, node.expression); + } + function checkAssertionWorker(errNode, type, expression, checkMode) { + var exprType = getRegularTypeOfObjectLiteral(getBaseTypeOfLiteralType(checkExpression(expression, checkMode))); + checkSourceElement(type); + var targetType = getTypeFromTypeNode(type); + if (produceDiagnostics && targetType !== errorType) { + var widenedType = getWidenedType(exprType); + if (!isTypeComparableTo(targetType, widenedType)) { + checkTypeComparableTo(exprType, targetType, errNode, ts.Diagnostics.Conversion_of_type_0_to_type_1_may_be_a_mistake_because_neither_type_sufficiently_overlaps_with_the_other_If_this_was_intentional_convert_the_expression_to_unknown_first); + } + } + return targetType; + } + function checkNonNullAssertion(node) { + return getNonNullableType(checkExpression(node.expression)); + } + function checkMetaProperty(node) { + checkGrammarMetaProperty(node); + if (node.keywordToken === 95 /* NewKeyword */) { + return checkNewTargetMetaProperty(node); + } + if (node.keywordToken === 92 /* ImportKeyword */) { + return checkImportMetaProperty(node); + } + return ts.Debug.assertNever(node.keywordToken); + } + function checkNewTargetMetaProperty(node) { + var container = ts.getNewTargetContainer(node); + if (!container) { + error(node, ts.Diagnostics.Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constructor, "new.target"); + return errorType; + } + else if (container.kind === 157 /* Constructor */) { + var symbol = getSymbolOfNode(container.parent); + return getTypeOfSymbol(symbol); + } + else { + var symbol = getSymbolOfNode(container); + return getTypeOfSymbol(symbol); + } + } + function checkImportMetaProperty(node) { + if (languageVersion < 6 /* ESNext */ || moduleKind < ts.ModuleKind.ESNext) { + error(node, ts.Diagnostics.The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_options); + } + var file = ts.getSourceFileOfNode(node); + ts.Debug.assert(!!(file.flags & 1048576 /* PossiblyContainsImportMeta */), "Containing file is missing import meta node flag."); + ts.Debug.assert(!!file.externalModuleIndicator, "Containing file should be a module."); + return node.name.escapedText === "meta" ? getGlobalImportMetaType() : errorType; + } + function getTypeOfParameter(symbol) { + var type = getTypeOfSymbol(symbol); + if (strictNullChecks) { + var declaration = symbol.valueDeclaration; + if (declaration && ts.hasInitializer(declaration)) { + return getOptionalType(type); + } + } + return type; + } + function getParameterNameAtPosition(signature, pos) { + var paramCount = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); + if (pos < paramCount) { + return signature.parameters[pos].escapedName; + } + var restParameter = signature.parameters[paramCount] || unknownSymbol; + var restType = getTypeOfSymbol(restParameter); + if (isTupleType(restType)) { + var associatedNames = restType.target.associatedNames; + var index = pos - paramCount; + return associatedNames ? associatedNames[index] : restParameter.escapedName + "_" + index; + } + return restParameter.escapedName; + } + function getTypeAtPosition(signature, pos) { + return tryGetTypeAtPosition(signature, pos) || anyType; + } + function tryGetTypeAtPosition(signature, pos) { + var paramCount = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); + if (pos < paramCount) { + return getTypeOfParameter(signature.parameters[pos]); + } + if (signature.hasRestParameter) { + var restType = getTypeOfSymbol(signature.parameters[paramCount]); + if (isTupleType(restType)) { + if (pos - paramCount < getLengthOfTupleType(restType)) { + return restType.typeArguments[pos - paramCount]; + } + return getRestTypeOfTupleType(restType); + } + return getIndexTypeOfType(restType, 1 /* Number */); + } + return undefined; + } + function getRestTypeAtPosition(source, pos) { + var paramCount = getParameterCount(source); + var restType = getEffectiveRestType(source); + if (restType && pos === paramCount - 1) { + return restType; + } + var start = restType ? Math.min(pos, paramCount - 1) : pos; + var types = []; + var names = []; + for (var i = start; i < paramCount; i++) { + types.push(getTypeAtPosition(source, i)); + names.push(getParameterNameAtPosition(source, i)); + } + var minArgumentCount = getMinArgumentCount(source); + var minLength = minArgumentCount < start ? 0 : minArgumentCount - start; + return createTupleType(types, minLength, !!restType, names); + } + function getParameterCount(signature) { + var length = signature.parameters.length; + if (signature.hasRestParameter) { + var restType = getTypeOfSymbol(signature.parameters[length - 1]); + if (isTupleType(restType)) { + return length + (restType.typeArguments || ts.emptyArray).length - 1; + } + } + return length; + } + function getMinArgumentCount(signature) { + if (signature.hasRestParameter) { + var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); + if (isTupleType(restType)) { + var minLength = restType.target.minLength; + if (minLength > 0) { + return signature.parameters.length - 1 + minLength; + } + } + } + return signature.minArgumentCount; + } + function hasEffectiveRestParameter(signature) { + if (signature.hasRestParameter) { + var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); + return !isTupleType(restType) || restType.target.hasRestElement; + } + return false; + } + function getEffectiveRestType(signature) { + if (signature.hasRestParameter) { + var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); + return isTupleType(restType) ? getRestArrayTypeOfTupleType(restType) : restType; + } + return undefined; + } + function getNonArrayRestType(signature) { + var restType = getEffectiveRestType(signature); + return restType && !isArrayType(restType) && !isTypeAny(restType) ? restType : undefined; + } + function getTypeOfFirstParameterOfSignature(signature) { + return getTypeOfFirstParameterOfSignatureWithFallback(signature, neverType); + } + function getTypeOfFirstParameterOfSignatureWithFallback(signature, fallbackType) { + return signature.parameters.length > 0 ? getTypeAtPosition(signature, 0) : fallbackType; + } + function inferFromAnnotatedParameters(signature, context, mapper) { + var len = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); + for (var i = 0; i < len; i++) { + var declaration = signature.parameters[i].valueDeclaration; + if (declaration.type) { + var typeNode = ts.getEffectiveTypeAnnotationNode(declaration); + if (typeNode) { + inferTypes(mapper.inferences, getTypeFromTypeNode(typeNode), getTypeAtPosition(context, i)); + } + } + } + } + function assignContextualParameterTypes(signature, context) { + signature.typeParameters = context.typeParameters; + if (context.thisParameter) { + var parameter = signature.thisParameter; + if (!parameter || parameter.valueDeclaration && !parameter.valueDeclaration.type) { + if (!parameter) { + signature.thisParameter = createSymbolWithType(context.thisParameter, /*type*/ undefined); + } + assignTypeToParameterAndFixTypeParameters(signature.thisParameter, getTypeOfSymbol(context.thisParameter)); + } + } + var len = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); + for (var i = 0; i < len; i++) { + var parameter = signature.parameters[i]; + if (!ts.getEffectiveTypeAnnotationNode(parameter.valueDeclaration)) { + var contextualParameterType = getTypeAtPosition(context, i); + assignTypeToParameterAndFixTypeParameters(parameter, contextualParameterType); + } + } + if (signature.hasRestParameter) { + // parameter might be a transient symbol generated by use of `arguments` in the function body. + var parameter = ts.last(signature.parameters); + if (isTransientSymbol(parameter) || !ts.getEffectiveTypeAnnotationNode(parameter.valueDeclaration)) { + var contextualParameterType = getRestTypeAtPosition(context, len); + assignTypeToParameterAndFixTypeParameters(parameter, contextualParameterType); + } + } + } + // When contextual typing assigns a type to a parameter that contains a binding pattern, we also need to push + // the destructured type into the contained binding elements. + function assignBindingElementTypes(pattern) { + for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (!ts.isOmittedExpression(element)) { + if (element.name.kind === 72 /* Identifier */) { + getSymbolLinks(getSymbolOfNode(element)).type = getTypeForBindingElement(element); + } + else { + assignBindingElementTypes(element.name); + } + } + } + } + function assignTypeToParameterAndFixTypeParameters(parameter, contextualType) { + var links = getSymbolLinks(parameter); + if (!links.type) { + links.type = contextualType; + var decl = parameter.valueDeclaration; + if (decl.name.kind !== 72 /* Identifier */) { + // if inference didn't come up with anything but {}, fall back to the binding pattern if present. + if (links.type === emptyObjectType) { + links.type = getTypeFromBindingPattern(decl.name); + } + assignBindingElementTypes(decl.name); + } + } + } + function createPromiseType(promisedType) { + // creates a `Promise` type where `T` is the promisedType argument + var globalPromiseType = getGlobalPromiseType(/*reportErrors*/ true); + if (globalPromiseType !== emptyGenericType) { + // if the promised type is itself a promise, get the underlying type; otherwise, fallback to the promised type + promisedType = getAwaitedType(promisedType) || emptyObjectType; + return createTypeReference(globalPromiseType, [promisedType]); + } + return emptyObjectType; + } + function createPromiseLikeType(promisedType) { + // creates a `PromiseLike` type where `T` is the promisedType argument + var globalPromiseLikeType = getGlobalPromiseLikeType(/*reportErrors*/ true); + if (globalPromiseLikeType !== emptyGenericType) { + // if the promised type is itself a promise, get the underlying type; otherwise, fallback to the promised type + promisedType = getAwaitedType(promisedType) || emptyObjectType; + return createTypeReference(globalPromiseLikeType, [promisedType]); + } + return emptyObjectType; + } + function createPromiseReturnType(func, promisedType) { + var promiseType = createPromiseType(promisedType); + if (promiseType === emptyObjectType) { + error(func, ts.isImportCall(func) ? + ts.Diagnostics.A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option : + ts.Diagnostics.An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option); + return errorType; + } + else if (!getGlobalPromiseConstructorSymbol(/*reportErrors*/ true)) { + error(func, ts.isImportCall(func) ? + ts.Diagnostics.A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option : + ts.Diagnostics.An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option); + } + return promiseType; + } + function getReturnTypeFromBody(func, checkMode) { + if (!func.body) { + return errorType; + } + var functionFlags = ts.getFunctionFlags(func); + var type; + if (func.body.kind !== 218 /* Block */) { + type = checkExpressionCached(func.body, checkMode); + if (functionFlags & 2 /* Async */) { + // From within an async function you can return either a non-promise value or a promise. Any + // Promise/A+ compatible implementation will always assimilate any foreign promise, so the + // return type of the body should be unwrapped to its awaited type, which we will wrap in + // the native Promise type later in this function. + type = checkAwaitedType(type, /*errorNode*/ func, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); + } + } + else { + var types = checkAndAggregateReturnExpressionTypes(func, checkMode); + if (functionFlags & 1 /* Generator */) { // Generator or AsyncGenerator function + types = ts.concatenate(checkAndAggregateYieldOperandTypes(func, checkMode), types); + if (!types || types.length === 0) { + var iterableIteratorAny = functionFlags & 2 /* Async */ + ? createAsyncIterableIteratorType(anyType) // AsyncGenerator function + : createIterableIteratorType(anyType); // Generator function + if (noImplicitAny) { + error(func.asteriskToken, ts.Diagnostics.Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_type, typeToString(iterableIteratorAny)); + } + return iterableIteratorAny; + } + } + else { + if (!types) { + // For an async function, the return type will not be never, but rather a Promise for never. + return functionFlags & 2 /* Async */ + ? createPromiseReturnType(func, neverType) // Async function + : neverType; // Normal function + } + if (types.length === 0) { + // For an async function, the return type will not be void, but rather a Promise for void. + return functionFlags & 2 /* Async */ + ? createPromiseReturnType(func, voidType) // Async function + : voidType; // Normal function + } + } + // Return a union of the return expression types. + type = getUnionType(types, 2 /* Subtype */); + } + var contextualSignature = getContextualSignatureForFunctionLikeDeclaration(func); + if (!contextualSignature) { + reportErrorsFromWidening(func, type); + } + if (isUnitType(type)) { + var contextualType = !contextualSignature ? undefined : + contextualSignature === getSignatureFromDeclaration(func) ? type : + getReturnTypeOfSignature(contextualSignature); + if (contextualType) { + switch (functionFlags & 3 /* AsyncGenerator */) { + case 3 /* AsyncGenerator */: + contextualType = getIteratedTypeOfGenerator(contextualType, /*isAsyncGenerator*/ true); + break; + case 1 /* Generator */: + contextualType = getIteratedTypeOfGenerator(contextualType, /*isAsyncGenerator*/ false); + break; + case 2 /* Async */: + contextualType = getPromisedTypeOfPromise(contextualType); + break; + } + } + type = getWidenedLiteralLikeTypeForContextualType(type, contextualType); + } + var widenedType = getWidenedType(type); + switch (functionFlags & 3 /* AsyncGenerator */) { + case 3 /* AsyncGenerator */: + return createAsyncIterableIteratorType(widenedType); + case 1 /* Generator */: + return createIterableIteratorType(widenedType); + case 2 /* Async */: + // From within an async function you can return either a non-promise value or a promise. Any + // Promise/A+ compatible implementation will always assimilate any foreign promise, so the + // return type of the body is awaited type of the body, wrapped in a native Promise type. + return createPromiseType(widenedType); + default: + return widenedType; + } + } + function checkAndAggregateYieldOperandTypes(func, checkMode) { + var aggregatedTypes = []; + var isAsync = (ts.getFunctionFlags(func) & 2 /* Async */) !== 0; + ts.forEachYieldExpression(func.body, function (yieldExpression) { + ts.pushIfUnique(aggregatedTypes, getYieldedTypeOfYieldExpression(yieldExpression, isAsync, checkMode)); + }); + return aggregatedTypes; + } + function getYieldedTypeOfYieldExpression(node, isAsync, checkMode) { + var errorNode = node.expression || node; + var expressionType = node.expression ? checkExpression(node.expression, checkMode) : undefinedWideningType; + // A `yield*` expression effectively yields everything that its operand yields + var yieldedType = node.asteriskToken ? checkIteratedTypeOrElementType(expressionType, errorNode, /*allowStringInput*/ false, isAsync) : expressionType; + return !isAsync ? yieldedType : getAwaitedType(yieldedType, errorNode, node.asteriskToken + ? ts.Diagnostics.Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member + : ts.Diagnostics.Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); + } + /** + * Collect the TypeFacts learned from a typeof switch with + * total clauses `witnesses`, and the active clause ranging + * from `start` to `end`. Parameter `hasDefault` denotes + * whether the active clause contains a default clause. + */ + function getFactsFromTypeofSwitch(start, end, witnesses, hasDefault) { + var facts = 0 /* None */; + // When in the default we only collect inequality facts + // because default is 'in theory' a set of infinite + // equalities. + if (hasDefault) { + // Value is not equal to any types after the active clause. + for (var i = end; i < witnesses.length; i++) { + facts |= typeofNEFacts.get(witnesses[i]) || 32768 /* TypeofNEHostObject */; + } + // Remove inequalities for types that appear in the + // active clause because they appear before other + // types collected so far. + for (var i = start; i < end; i++) { + facts &= ~(typeofNEFacts.get(witnesses[i]) || 0); + } + // Add inequalities for types before the active clause unconditionally. + for (var i = 0; i < start; i++) { + facts |= typeofNEFacts.get(witnesses[i]) || 32768 /* TypeofNEHostObject */; + } + } + // When in an active clause without default the set of + // equalities is finite. + else { + // Add equalities for all types in the active clause. + for (var i = start; i < end; i++) { + facts |= typeofEQFacts.get(witnesses[i]) || 128 /* TypeofEQHostObject */; + } + // Remove equalities for types that appear before the + // active clause. + for (var i = 0; i < start; i++) { + facts &= ~(typeofEQFacts.get(witnesses[i]) || 0); + } + } + return facts; + } + function isExhaustiveSwitchStatement(node) { + if (!node.possiblyExhaustive) { + return false; + } + if (node.expression.kind === 199 /* TypeOfExpression */) { + var operandType = getTypeOfExpression(node.expression.expression); + // This cast is safe because the switch is possibly exhaustive and does not contain a default case, so there can be no undefined. + var witnesses = getSwitchClauseTypeOfWitnesses(node); + // notEqualFacts states that the type of the switched value is not equal to every type in the switch. + var notEqualFacts_1 = getFactsFromTypeofSwitch(0, 0, witnesses, /*hasDefault*/ true); + var type_5 = getBaseConstraintOfType(operandType) || operandType; + return !!(filterType(type_5, function (t) { return (getTypeFacts(t) & notEqualFacts_1) === notEqualFacts_1; }).flags & 131072 /* Never */); + } + var type = getTypeOfExpression(node.expression); + if (!isLiteralType(type)) { + return false; + } + var switchTypes = getSwitchClauseTypes(node); + if (!switchTypes.length || ts.some(switchTypes, isNeitherUnitTypeNorNever)) { + return false; + } + return eachTypeContainedIn(mapType(type, getRegularTypeOfLiteralType), switchTypes); + } + function functionHasImplicitReturn(func) { + if (!(func.flags & 128 /* HasImplicitReturn */)) { + return false; + } + if (ts.some(func.body.statements, function (statement) { return statement.kind === 232 /* SwitchStatement */ && isExhaustiveSwitchStatement(statement); })) { + return false; + } + return true; + } + /** NOTE: Return value of `[]` means a different thing than `undefined`. `[]` means func returns `void`, `undefined` means it returns `never`. */ + function checkAndAggregateReturnExpressionTypes(func, checkMode) { + var functionFlags = ts.getFunctionFlags(func); + var aggregatedTypes = []; + var hasReturnWithNoExpression = functionHasImplicitReturn(func); + var hasReturnOfTypeNever = false; + ts.forEachReturnStatement(func.body, function (returnStatement) { + var expr = returnStatement.expression; + if (expr) { + var type = checkExpressionCached(expr, checkMode); + if (functionFlags & 2 /* Async */) { + // From within an async function you can return either a non-promise value or a promise. Any + // Promise/A+ compatible implementation will always assimilate any foreign promise, so the + // return type of the body should be unwrapped to its awaited type, which should be wrapped in + // the native Promise type by the caller. + type = checkAwaitedType(type, func, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); + } + if (type.flags & 131072 /* Never */) { + hasReturnOfTypeNever = true; + } + ts.pushIfUnique(aggregatedTypes, type); + } + else { + hasReturnWithNoExpression = true; + } + }); + if (aggregatedTypes.length === 0 && !hasReturnWithNoExpression && (hasReturnOfTypeNever || mayReturnNever(func))) { + return undefined; + } + if (strictNullChecks && aggregatedTypes.length && hasReturnWithNoExpression && + !(isJSConstructor(func) && aggregatedTypes.some(function (t) { return t.symbol === func.symbol; }))) { + // Javascript "callable constructors", containing eg `if (!(this instanceof A)) return new A()` should not add undefined + ts.pushIfUnique(aggregatedTypes, undefinedType); + } + return aggregatedTypes; + } + function mayReturnNever(func) { + switch (func.kind) { + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + return true; + case 156 /* MethodDeclaration */: + return func.parent.kind === 188 /* ObjectLiteralExpression */; + default: + return false; + } + } + /** + * TypeScript Specification 1.0 (6.3) - July 2014 + * An explicitly typed function whose return type isn't the Void type, + * the Any type, or a union type containing the Void or Any type as a constituent + * must have at least one return statement somewhere in its body. + * An exception to this rule is if the function implementation consists of a single 'throw' statement. + * + * @param returnType - return type of the function, can be undefined if return type is not explicitly specified + */ + function checkAllCodePathsInNonVoidFunctionReturnOrThrow(func, returnType) { + if (!produceDiagnostics) { + return; + } + // Functions with with an explicitly specified 'void' or 'any' return type don't need any return expressions. + if (returnType && maybeTypeOfKind(returnType, 1 /* Any */ | 16384 /* Void */)) { + return; + } + // If all we have is a function signature, or an arrow function with an expression body, then there is nothing to check. + // also if HasImplicitReturn flag is not set this means that all codepaths in function body end with return or throw + if (func.kind === 155 /* MethodSignature */ || ts.nodeIsMissing(func.body) || func.body.kind !== 218 /* Block */ || !functionHasImplicitReturn(func)) { + return; + } + var hasExplicitReturn = func.flags & 256 /* HasExplicitReturn */; + if (returnType && returnType.flags & 131072 /* Never */) { + error(ts.getEffectiveReturnTypeNode(func), ts.Diagnostics.A_function_returning_never_cannot_have_a_reachable_end_point); + } + else if (returnType && !hasExplicitReturn) { + // minimal check: function has syntactic return type annotation and no explicit return statements in the body + // this function does not conform to the specification. + // NOTE: having returnType !== undefined is a precondition for entering this branch so func.type will always be present + error(ts.getEffectiveReturnTypeNode(func), ts.Diagnostics.A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value); + } + else if (returnType && strictNullChecks && !isTypeAssignableTo(undefinedType, returnType)) { + error(ts.getEffectiveReturnTypeNode(func), ts.Diagnostics.Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined); + } + else if (compilerOptions.noImplicitReturns) { + if (!returnType) { + // If return type annotation is omitted check if function has any explicit return statements. + // If it does not have any - its inferred return type is void - don't do any checks. + // Otherwise get inferred return type from function body and report error only if it is not void / anytype + if (!hasExplicitReturn) { + return; + } + var inferredReturnType = getReturnTypeOfSignature(getSignatureFromDeclaration(func)); + if (isUnwrappedReturnTypeVoidOrAny(func, inferredReturnType)) { + return; + } + } + error(ts.getEffectiveReturnTypeNode(func) || func, ts.Diagnostics.Not_all_code_paths_return_a_value); + } + } + function checkFunctionExpressionOrObjectLiteralMethod(node, checkMode) { + ts.Debug.assert(node.kind !== 156 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + checkNodeDeferred(node); + // The identityMapper object is used to indicate that function expressions are wildcards + if (checkMode === 1 /* SkipContextSensitive */ && isContextSensitive(node)) { + // Skip parameters, return signature with return type that retains noncontextual parts so inferences can still be drawn in an early stage + if (!ts.getEffectiveReturnTypeNode(node) && hasContextSensitiveReturnExpression(node)) { + var links_1 = getNodeLinks(node); + if (links_1.contextFreeType) { + return links_1.contextFreeType; + } + var returnType = getReturnTypeFromBody(node, checkMode); + var returnOnlySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, returnType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + var returnOnlyType = createAnonymousType(node.symbol, emptySymbols, [returnOnlySignature], ts.emptyArray, undefined, undefined); + returnOnlyType.flags |= 536870912 /* ContainsAnyFunctionType */; + return links_1.contextFreeType = returnOnlyType; + } + return anyFunctionType; + } + // Grammar checking + var hasGrammarError = checkGrammarFunctionLikeDeclaration(node); + if (!hasGrammarError && node.kind === 196 /* FunctionExpression */) { + checkGrammarForGenerator(node); + } + var links = getNodeLinks(node); + var type = getTypeOfSymbol(getMergedSymbol(node.symbol)); + if (isTypeAny(type)) { + return type; + } + // Check if function expression is contextually typed and assign parameter types if so. + if (!(links.flags & 1024 /* ContextChecked */)) { + var contextualSignature = getContextualSignature(node); + // If a type check is started at a function expression that is an argument of a function call, obtaining the + // contextual type may recursively get back to here during overload resolution of the call. If so, we will have + // already assigned contextual types. + if (!(links.flags & 1024 /* ContextChecked */)) { + links.flags |= 1024 /* ContextChecked */; + if (contextualSignature) { + var signature = getSignaturesOfType(type, 0 /* Call */)[0]; + if (isContextSensitive(node)) { + var contextualMapper = getContextualMapper(node); + if (checkMode === 2 /* Inferential */) { + inferFromAnnotatedParameters(signature, contextualSignature, contextualMapper); + } + var instantiatedContextualSignature = contextualMapper === identityMapper ? + contextualSignature : instantiateSignature(contextualSignature, contextualMapper); + assignContextualParameterTypes(signature, instantiatedContextualSignature); + } + if (!getReturnTypeFromAnnotation(node) && !signature.resolvedReturnType) { + var returnType = getReturnTypeFromBody(node, checkMode); + if (!signature.resolvedReturnType) { + signature.resolvedReturnType = returnType; + } + } + } + checkSignatureDeclaration(node); + } + } + return type; + } + function getReturnOrPromisedType(node, functionFlags) { + var type = getReturnTypeFromAnnotation(node); + return type && ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */) ? + getAwaitedType(type) || errorType : type; + } + function checkFunctionExpressionOrObjectLiteralMethodDeferred(node) { + ts.Debug.assert(node.kind !== 156 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + var functionFlags = ts.getFunctionFlags(node); + var returnOrPromisedType = getReturnOrPromisedType(node, functionFlags); + if ((functionFlags & 1 /* Generator */) === 0) { // Async function or normal function + // return is not necessary in the body of generators + checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnOrPromisedType); + } + if (node.body) { + if (!ts.getEffectiveReturnTypeNode(node)) { + // There are some checks that are only performed in getReturnTypeFromBody, that may produce errors + // we need. An example is the noImplicitAny errors resulting from widening the return expression + // of a function. Because checking of function expression bodies is deferred, there was never an + // appropriate time to do this during the main walk of the file (see the comment at the top of + // checkFunctionExpressionBodies). So it must be done now. + getReturnTypeOfSignature(getSignatureFromDeclaration(node)); + } + if (node.body.kind === 218 /* Block */) { + checkSourceElement(node.body); + } + else { + // From within an async function you can return either a non-promise value or a promise. Any + // Promise/A+ compatible implementation will always assimilate any foreign promise, so we + // should not be checking assignability of a promise to the return type. Instead, we need to + // check assignability of the awaited type of the expression body against the promised type of + // its return type annotation. + var exprType = checkExpression(node.body); + if (returnOrPromisedType) { + if ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */) { // Async function + var awaitedType = checkAwaitedType(exprType, node.body, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); + checkTypeAssignableToAndOptionallyElaborate(awaitedType, returnOrPromisedType, node.body, node.body); + } + else { // Normal function + checkTypeAssignableToAndOptionallyElaborate(exprType, returnOrPromisedType, node.body, node.body); + } + } + } + } + } + function checkArithmeticOperandType(operand, type, diagnostic) { + if (!isTypeAssignableTo(type, numberOrBigIntType)) { + error(operand, diagnostic); + return false; + } + return true; + } + function isReadonlyAssignmentDeclaration(d) { + if (!ts.isCallExpression(d)) { + return false; + } + if (!ts.isBindableObjectDefinePropertyCall(d)) { + return false; + } + var objectLitType = checkExpressionCached(d.arguments[2]); + var valueType = getTypeOfPropertyOfType(objectLitType, "value"); + if (valueType) { + var writableProp = getPropertyOfType(objectLitType, "writable"); + var writableType = writableProp && getTypeOfSymbol(writableProp); + if (!writableType || writableType === falseType || writableType === regularFalseType) { + return true; + } + // We include this definition whereupon we walk back and check the type at the declaration because + // The usual definition of `Object.defineProperty` will _not_ cause literal types to be preserved in the + // argument types, should the type be contextualized by the call itself. + if (writableProp && writableProp.valueDeclaration && ts.isPropertyAssignment(writableProp.valueDeclaration)) { + var initializer = writableProp.valueDeclaration.initializer; + var rawOriginalType = checkExpression(initializer); + if (rawOriginalType === falseType || rawOriginalType === regularFalseType) { + return true; + } + } + return false; + } + var setProp = getPropertyOfType(objectLitType, "set"); + return !setProp; + } + function isReadonlySymbol(symbol) { + // The following symbols are considered read-only: + // Properties with a 'readonly' modifier + // Variables declared with 'const' + // Get accessors without matching set accessors + // Enum members + // Object.defineProperty assignments with writable false or no setter + // Unions and intersections of the above (unions and intersections eagerly set isReadonly on creation) + return !!(ts.getCheckFlags(symbol) & 8 /* Readonly */ || + symbol.flags & 4 /* Property */ && ts.getDeclarationModifierFlagsFromSymbol(symbol) & 64 /* Readonly */ || + symbol.flags & 3 /* Variable */ && getDeclarationNodeFlagsFromSymbol(symbol) & 2 /* Const */ || + symbol.flags & 98304 /* Accessor */ && !(symbol.flags & 65536 /* SetAccessor */) || + symbol.flags & 8 /* EnumMember */ || + ts.some(symbol.declarations, isReadonlyAssignmentDeclaration)); + } + function isReferenceToReadonlyEntity(expr, symbol) { + if (isReadonlySymbol(symbol)) { + // Allow assignments to readonly properties within constructors of the same class declaration. + if (symbol.flags & 4 /* Property */ && + (expr.kind === 189 /* PropertyAccessExpression */ || expr.kind === 190 /* ElementAccessExpression */) && + expr.expression.kind === 100 /* ThisKeyword */) { + // Look for if this is the constructor for the class that `symbol` is a property of. + var func = ts.getContainingFunction(expr); + if (!(func && func.kind === 157 /* Constructor */)) { + return true; + } + // If func.parent is a class and symbol is a (readonly) property of that class, or + // if func is a constructor and symbol is a (readonly) parameter property declared in it, + // then symbol is writeable here. + return !symbol.valueDeclaration || !(func.parent === symbol.valueDeclaration.parent || func === symbol.valueDeclaration.parent); + } + return true; + } + return false; + } + function isReferenceThroughNamespaceImport(expr) { + if (expr.kind === 189 /* PropertyAccessExpression */ || expr.kind === 190 /* ElementAccessExpression */) { + var node = ts.skipParentheses(expr.expression); + if (node.kind === 72 /* Identifier */) { + var symbol = getNodeLinks(node).resolvedSymbol; + if (symbol.flags & 2097152 /* Alias */) { + var declaration = getDeclarationOfAliasSymbol(symbol); + return !!declaration && declaration.kind === 251 /* NamespaceImport */; + } + } + } + return false; + } + function checkReferenceExpression(expr, invalidReferenceMessage) { + // References are combinations of identifiers, parentheses, and property accesses. + var node = ts.skipOuterExpressions(expr, 2 /* Assertions */ | 1 /* Parentheses */); + if (node.kind !== 72 /* Identifier */ && node.kind !== 189 /* PropertyAccessExpression */ && node.kind !== 190 /* ElementAccessExpression */) { + error(expr, invalidReferenceMessage); + return false; + } + return true; + } + function checkDeleteExpression(node) { + checkExpression(node.expression); + var expr = ts.skipParentheses(node.expression); + if (expr.kind !== 189 /* PropertyAccessExpression */ && expr.kind !== 190 /* ElementAccessExpression */) { + error(expr, ts.Diagnostics.The_operand_of_a_delete_operator_must_be_a_property_reference); + return booleanType; + } + var links = getNodeLinks(expr); + var symbol = getExportSymbolOfValueSymbolIfExported(links.resolvedSymbol); + if (symbol && isReadonlySymbol(symbol)) { + error(expr, ts.Diagnostics.The_operand_of_a_delete_operator_cannot_be_a_read_only_property); + } + return booleanType; + } + function checkTypeOfExpression(node) { + checkExpression(node.expression); + return typeofType; + } + function checkVoidExpression(node) { + checkExpression(node.expression); + return undefinedWideningType; + } + function checkAwaitExpression(node) { + // Grammar checking + if (produceDiagnostics) { + if (!(node.flags & 16384 /* AwaitContext */)) { + grammarErrorOnFirstToken(node, ts.Diagnostics.await_expression_is_only_allowed_within_an_async_function); + } + if (isInParameterInitializerBeforeContainingFunction(node)) { + error(node, ts.Diagnostics.await_expressions_cannot_be_used_in_a_parameter_initializer); + } + } + var operandType = checkExpression(node.expression); + return checkAwaitedType(operandType, node, ts.Diagnostics.Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); + } + function checkPrefixUnaryExpression(node) { + var operandType = checkExpression(node.operand); + if (operandType === silentNeverType) { + return silentNeverType; + } + switch (node.operand.kind) { + case 8 /* NumericLiteral */: + switch (node.operator) { + case 39 /* MinusToken */: + return getFreshTypeOfLiteralType(getLiteralType(-node.operand.text)); + case 38 /* PlusToken */: + return getFreshTypeOfLiteralType(getLiteralType(+node.operand.text)); + } + break; + case 9 /* BigIntLiteral */: + if (node.operator === 39 /* MinusToken */) { + return getFreshTypeOfLiteralType(getLiteralType({ + negative: true, + base10Value: ts.parsePseudoBigInt(node.operand.text) + })); + } + } + switch (node.operator) { + case 38 /* PlusToken */: + case 39 /* MinusToken */: + case 53 /* TildeToken */: + checkNonNullType(operandType, node.operand); + if (maybeTypeOfKind(operandType, 12288 /* ESSymbolLike */)) { + error(node.operand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(node.operator)); + } + if (node.operator === 38 /* PlusToken */) { + if (maybeTypeOfKind(operandType, 2112 /* BigIntLike */)) { + error(node.operand, ts.Diagnostics.Operator_0_cannot_be_applied_to_type_1, ts.tokenToString(node.operator), typeToString(operandType)); + } + return numberType; + } + return getUnaryResultType(operandType); + case 52 /* ExclamationToken */: + checkTruthinessExpression(node.operand); + var facts = getTypeFacts(operandType) & (4194304 /* Truthy */ | 8388608 /* Falsy */); + return facts === 4194304 /* Truthy */ ? falseType : + facts === 8388608 /* Falsy */ ? trueType : + booleanType; + case 44 /* PlusPlusToken */: + case 45 /* MinusMinusToken */: + var ok = checkArithmeticOperandType(node.operand, checkNonNullType(operandType, node.operand), ts.Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_bigint_or_an_enum_type); + if (ok) { + // run check only if former checks succeeded to avoid reporting cascading errors + checkReferenceExpression(node.operand, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access); + } + return getUnaryResultType(operandType); + } + return errorType; + } + function checkPostfixUnaryExpression(node) { + var operandType = checkExpression(node.operand); + if (operandType === silentNeverType) { + return silentNeverType; + } + var ok = checkArithmeticOperandType(node.operand, checkNonNullType(operandType, node.operand), ts.Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_bigint_or_an_enum_type); + if (ok) { + // run check only if former checks succeeded to avoid reporting cascading errors + checkReferenceExpression(node.operand, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access); + } + return getUnaryResultType(operandType); + } + function getUnaryResultType(operandType) { + if (maybeTypeOfKind(operandType, 2112 /* BigIntLike */)) { + return isTypeAssignableToKind(operandType, 3 /* AnyOrUnknown */) || maybeTypeOfKind(operandType, 296 /* NumberLike */) + ? numberOrBigIntType + : bigintType; + } + // If it's not a bigint type, implicit coercion will result in a number + return numberType; + } + // Return true if type might be of the given kind. A union or intersection type might be of a given + // kind if at least one constituent type is of the given kind. + function maybeTypeOfKind(type, kind) { + if (type.flags & kind & ~134217728 /* GenericMappedType */ || kind & 134217728 /* GenericMappedType */ && isGenericMappedType(type)) { + return true; + } + if (type.flags & 3145728 /* UnionOrIntersection */) { + var types = type.types; + for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { + var t = types_15[_i]; + if (maybeTypeOfKind(t, kind)) { + return true; + } + } + } + return false; + } + function isTypeAssignableToKind(source, kind, strict) { + if (source.flags & kind) { + return true; + } + if (strict && source.flags & (3 /* AnyOrUnknown */ | 16384 /* Void */ | 32768 /* Undefined */ | 65536 /* Null */)) { + return false; + } + return !!(kind & 296 /* NumberLike */) && isTypeAssignableTo(source, numberType) || + !!(kind & 2112 /* BigIntLike */) && isTypeAssignableTo(source, bigintType) || + !!(kind & 132 /* StringLike */) && isTypeAssignableTo(source, stringType) || + !!(kind & 528 /* BooleanLike */) && isTypeAssignableTo(source, booleanType) || + !!(kind & 16384 /* Void */) && isTypeAssignableTo(source, voidType) || + !!(kind & 131072 /* Never */) && isTypeAssignableTo(source, neverType) || + !!(kind & 65536 /* Null */) && isTypeAssignableTo(source, nullType) || + !!(kind & 32768 /* Undefined */) && isTypeAssignableTo(source, undefinedType) || + !!(kind & 4096 /* ESSymbol */) && isTypeAssignableTo(source, esSymbolType) || + !!(kind & 67108864 /* NonPrimitive */) && isTypeAssignableTo(source, nonPrimitiveType); + } + function allTypesAssignableToKind(source, kind, strict) { + return source.flags & 1048576 /* Union */ ? + ts.every(source.types, function (subType) { return allTypesAssignableToKind(subType, kind, strict); }) : + isTypeAssignableToKind(source, kind, strict); + } + function isConstEnumObjectType(type) { + return !!(ts.getObjectFlags(type) & 16 /* Anonymous */) && !!type.symbol && isConstEnumSymbol(type.symbol); + } + function isConstEnumSymbol(symbol) { + return (symbol.flags & 128 /* ConstEnum */) !== 0; + } + function checkInstanceOfExpression(left, right, leftType, rightType) { + if (leftType === silentNeverType || rightType === silentNeverType) { + return silentNeverType; + } + // TypeScript 1.0 spec (April 2014): 4.15.4 + // The instanceof operator requires the left operand to be of type Any, an object type, or a type parameter type, + // and the right operand to be of type Any, a subtype of the 'Function' interface type, or have a call or construct signature. + // The result is always of the Boolean primitive type. + // NOTE: do not raise error if leftType is unknown as related error was already reported + if (!isTypeAny(leftType) && + allTypesAssignableToKind(leftType, 131068 /* Primitive */)) { + error(left, ts.Diagnostics.The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter); + } + // NOTE: do not raise error if right is unknown as related error was already reported + if (!(isTypeAny(rightType) || typeHasCallOrConstructSignatures(rightType) || isTypeSubtypeOf(rightType, globalFunctionType))) { + error(right, ts.Diagnostics.The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_Function_interface_type); + } + return booleanType; + } + function checkInExpression(left, right, leftType, rightType) { + if (leftType === silentNeverType || rightType === silentNeverType) { + return silentNeverType; + } + leftType = checkNonNullType(leftType, left); + rightType = checkNonNullType(rightType, right); + // TypeScript 1.0 spec (April 2014): 4.15.5 + // The in operator requires the left operand to be of type Any, the String primitive type, or the Number primitive type, + // and the right operand to be of type Any, an object type, or a type parameter type. + // The result is always of the Boolean primitive type. + if (!(isTypeComparableTo(leftType, stringType) || isTypeAssignableToKind(leftType, 296 /* NumberLike */ | 12288 /* ESSymbolLike */))) { + error(left, ts.Diagnostics.The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol); + } + if (!isTypeAssignableToKind(rightType, 67108864 /* NonPrimitive */ | 58982400 /* InstantiableNonPrimitive */)) { + error(right, ts.Diagnostics.The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter); + } + return booleanType; + } + function checkObjectLiteralAssignment(node, sourceType, rightIsThis) { + var properties = node.properties; + if (strictNullChecks && properties.length === 0) { + return checkNonNullType(sourceType, node); + } + for (var _i = 0, properties_6 = properties; _i < properties_6.length; _i++) { + var p = properties_6[_i]; + checkObjectLiteralDestructuringPropertyAssignment(sourceType, p, properties, rightIsThis); + } + return sourceType; + } + /** Note: If property cannot be a SpreadAssignment, then allProperties does not need to be provided */ + function checkObjectLiteralDestructuringPropertyAssignment(objectLiteralType, property, allProperties, rightIsThis) { + if (rightIsThis === void 0) { rightIsThis = false; } + if (property.kind === 275 /* PropertyAssignment */ || property.kind === 276 /* ShorthandPropertyAssignment */) { + var name = property.name; + if (name.kind === 149 /* ComputedPropertyName */) { + checkComputedPropertyName(name); + } + if (isComputedNonLiteralName(name)) { + return undefined; + } + var type = getTypeOfObjectLiteralDestructuringProperty(objectLiteralType, name, property, rightIsThis); + if (type) { + // non-shorthand property assignments should always have initializers + return checkDestructuringAssignment(property.kind === 276 /* ShorthandPropertyAssignment */ ? property : property.initializer, type); + } + else { + error(name, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(objectLiteralType), ts.declarationNameToString(name)); + } + } + else if (property.kind === 277 /* SpreadAssignment */) { + if (languageVersion < 6 /* ESNext */) { + checkExternalEmitHelpers(property, 4 /* Rest */); + } + var nonRestNames = []; + if (allProperties) { + for (var i = 0; i < allProperties.length - 1; i++) { + nonRestNames.push(allProperties[i].name); + } + } + var type = getRestType(objectLiteralType, nonRestNames, objectLiteralType.symbol); + checkGrammarForDisallowedTrailingComma(allProperties, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma); + return checkDestructuringAssignment(property.expression, type); + } + else { + error(property, ts.Diagnostics.Property_assignment_expected); + } + } + function getTypeOfObjectLiteralDestructuringProperty(objectLiteralType, name, property, rightIsThis) { + if (isTypeAny(objectLiteralType)) { + return objectLiteralType; + } + var type; + var text = ts.getTextOfPropertyName(name); + if (text) { // TODO: GH#26379 + var prop = getPropertyOfType(objectLiteralType, text); + if (prop) { + markPropertyAsReferenced(prop, property, rightIsThis); + checkPropertyAccessibility(property, /*isSuper*/ false, objectLiteralType, prop); + type = getTypeOfSymbol(prop); + } + type = type || (isNumericLiteralName(text) ? getIndexTypeOfType(objectLiteralType, 1 /* Number */) : undefined); + } + return type || getIndexTypeOfType(objectLiteralType, 0 /* String */); + } + function checkArrayLiteralAssignment(node, sourceType, checkMode) { + var elements = node.elements; + if (languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) { + checkExternalEmitHelpers(node, 512 /* Read */); + } + // This elementType will be used if the specific property corresponding to this index is not + // present (aka the tuple element property). This call also checks that the parentType is in + // fact an iterable or array (depending on target language). + var elementType = checkIteratedTypeOrElementType(sourceType, node, /*allowStringInput*/ false, /*allowAsyncIterables*/ false) || errorType; + for (var i = 0; i < elements.length; i++) { + checkArrayLiteralDestructuringElementAssignment(node, sourceType, i, elementType, checkMode); + } + return sourceType; + } + function checkArrayLiteralDestructuringElementAssignment(node, sourceType, elementIndex, elementType, checkMode) { + var elements = node.elements; + var element = elements[elementIndex]; + if (element.kind !== 210 /* OmittedExpression */) { + if (element.kind !== 208 /* SpreadElement */) { + var propName = "" + elementIndex; + var type = isTypeAny(sourceType) ? sourceType : + everyType(sourceType, isTupleLikeType) ? getTupleElementType(sourceType, elementIndex) : + elementType; + if (type) { + return checkDestructuringAssignment(element, type, checkMode); + } + // We still need to check element expression here because we may need to set appropriate flag on the expression + // such as NodeCheckFlags.LexicalThis on "this"expression. + checkExpression(element); + if (isTupleType(sourceType)) { + error(element, ts.Diagnostics.Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2, typeToString(sourceType), getTypeReferenceArity(sourceType), elements.length); + } + else { + error(element, ts.Diagnostics.Type_0_has_no_property_1, typeToString(sourceType), propName); + } + } + else { + if (elementIndex < elements.length - 1) { + error(element, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern); + } + else { + var restExpression = element.expression; + if (restExpression.kind === 204 /* BinaryExpression */ && restExpression.operatorToken.kind === 59 /* EqualsToken */) { + error(restExpression.operatorToken, ts.Diagnostics.A_rest_element_cannot_have_an_initializer); + } + else { + checkGrammarForDisallowedTrailingComma(node.elements, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma); + var type = everyType(sourceType, isTupleType) ? + mapType(sourceType, function (t) { return sliceTupleType(t, elementIndex); }) : + createArrayType(elementType); + return checkDestructuringAssignment(restExpression, type, checkMode); + } + } + } + } + return undefined; + } + function checkDestructuringAssignment(exprOrAssignment, sourceType, checkMode, rightIsThis) { + var target; + if (exprOrAssignment.kind === 276 /* ShorthandPropertyAssignment */) { + var prop = exprOrAssignment; + if (prop.objectAssignmentInitializer) { + // In strict null checking mode, if a default value of a non-undefined type is specified, remove + // undefined from the final type. + if (strictNullChecks && + !(getFalsyFlags(checkExpression(prop.objectAssignmentInitializer)) & 32768 /* Undefined */)) { + sourceType = getTypeWithFacts(sourceType, 524288 /* NEUndefined */); + } + checkBinaryLikeExpression(prop.name, prop.equalsToken, prop.objectAssignmentInitializer, checkMode); + } + target = exprOrAssignment.name; + } + else { + target = exprOrAssignment; + } + if (target.kind === 204 /* BinaryExpression */ && target.operatorToken.kind === 59 /* EqualsToken */) { + checkBinaryExpression(target, checkMode); + target = target.left; + } + if (target.kind === 188 /* ObjectLiteralExpression */) { + return checkObjectLiteralAssignment(target, sourceType, rightIsThis); + } + if (target.kind === 187 /* ArrayLiteralExpression */) { + return checkArrayLiteralAssignment(target, sourceType, checkMode); + } + return checkReferenceAssignment(target, sourceType, checkMode); + } + function checkReferenceAssignment(target, sourceType, checkMode) { + var targetType = checkExpression(target, checkMode); + var error = target.parent.kind === 277 /* SpreadAssignment */ ? + ts.Diagnostics.The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access : + ts.Diagnostics.The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access; + if (checkReferenceExpression(target, error)) { + checkTypeAssignableToAndOptionallyElaborate(sourceType, targetType, target, target); + } + return sourceType; + } + /** + * This is a *shallow* check: An expression is side-effect-free if the + * evaluation of the expression *itself* cannot produce side effects. + * For example, x++ / 3 is side-effect free because the / operator + * does not have side effects. + * The intent is to "smell test" an expression for correctness in positions where + * its value is discarded (e.g. the left side of the comma operator). + */ + function isSideEffectFree(node) { + node = ts.skipParentheses(node); + switch (node.kind) { + case 72 /* Identifier */: + case 10 /* StringLiteral */: + case 13 /* RegularExpressionLiteral */: + case 193 /* TaggedTemplateExpression */: + case 206 /* TemplateExpression */: + case 14 /* NoSubstitutionTemplateLiteral */: + case 8 /* NumericLiteral */: + case 9 /* BigIntLiteral */: + case 102 /* TrueKeyword */: + case 87 /* FalseKeyword */: + case 96 /* NullKeyword */: + case 141 /* UndefinedKeyword */: + case 196 /* FunctionExpression */: + case 209 /* ClassExpression */: + case 197 /* ArrowFunction */: + case 187 /* ArrayLiteralExpression */: + case 188 /* ObjectLiteralExpression */: + case 199 /* TypeOfExpression */: + case 213 /* NonNullExpression */: + case 261 /* JsxSelfClosingElement */: + case 260 /* JsxElement */: + return true; + case 205 /* ConditionalExpression */: + return isSideEffectFree(node.whenTrue) && + isSideEffectFree(node.whenFalse); + case 204 /* BinaryExpression */: + if (ts.isAssignmentOperator(node.operatorToken.kind)) { + return false; + } + return isSideEffectFree(node.left) && + isSideEffectFree(node.right); + case 202 /* PrefixUnaryExpression */: + case 203 /* PostfixUnaryExpression */: + // Unary operators ~, !, +, and - have no side effects. + // The rest do. + switch (node.operator) { + case 52 /* ExclamationToken */: + case 38 /* PlusToken */: + case 39 /* MinusToken */: + case 53 /* TildeToken */: + return true; + } + return false; + // Some forms listed here for clarity + case 200 /* VoidExpression */: // Explicit opt-out + case 194 /* TypeAssertionExpression */: // Not SEF, but can produce useful type warnings + case 212 /* AsExpression */: // Not SEF, but can produce useful type warnings + default: + return false; + } + } + function isTypeEqualityComparableTo(source, target) { + return (target.flags & 98304 /* Nullable */) !== 0 || isTypeComparableTo(source, target); + } + function checkBinaryExpression(node, checkMode) { + if (ts.isInJSFile(node) && ts.getAssignedExpandoInitializer(node)) { + return checkExpression(node.right, checkMode); + } + return checkBinaryLikeExpression(node.left, node.operatorToken, node.right, checkMode, node); + } + function checkBinaryLikeExpression(left, operatorToken, right, checkMode, errorNode) { + var operator = operatorToken.kind; + if (operator === 59 /* EqualsToken */ && (left.kind === 188 /* ObjectLiteralExpression */ || left.kind === 187 /* ArrayLiteralExpression */)) { + return checkDestructuringAssignment(left, checkExpression(right, checkMode), checkMode, right.kind === 100 /* ThisKeyword */); + } + var leftType; + if (operator === 54 /* AmpersandAmpersandToken */ || operator === 55 /* BarBarToken */) { + leftType = checkTruthinessExpression(left, checkMode); + } + else { + leftType = checkExpression(left, checkMode); + } + var rightType = checkExpression(right, checkMode); + switch (operator) { + case 40 /* AsteriskToken */: + case 41 /* AsteriskAsteriskToken */: + case 62 /* AsteriskEqualsToken */: + case 63 /* AsteriskAsteriskEqualsToken */: + case 42 /* SlashToken */: + case 64 /* SlashEqualsToken */: + case 43 /* PercentToken */: + case 65 /* PercentEqualsToken */: + case 39 /* MinusToken */: + case 61 /* MinusEqualsToken */: + case 46 /* LessThanLessThanToken */: + case 66 /* LessThanLessThanEqualsToken */: + case 47 /* GreaterThanGreaterThanToken */: + case 67 /* GreaterThanGreaterThanEqualsToken */: + case 48 /* GreaterThanGreaterThanGreaterThanToken */: + case 68 /* GreaterThanGreaterThanGreaterThanEqualsToken */: + case 50 /* BarToken */: + case 70 /* BarEqualsToken */: + case 51 /* CaretToken */: + case 71 /* CaretEqualsToken */: + case 49 /* AmpersandToken */: + case 69 /* AmpersandEqualsToken */: + if (leftType === silentNeverType || rightType === silentNeverType) { + return silentNeverType; + } + leftType = checkNonNullType(leftType, left); + rightType = checkNonNullType(rightType, right); + var suggestedOperator = void 0; + // if a user tries to apply a bitwise operator to 2 boolean operands + // try and return them a helpful suggestion + if ((leftType.flags & 528 /* BooleanLike */) && + (rightType.flags & 528 /* BooleanLike */) && + (suggestedOperator = getSuggestedBooleanOperator(operatorToken.kind)) !== undefined) { + error(errorNode || operatorToken, ts.Diagnostics.The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead, ts.tokenToString(operatorToken.kind), ts.tokenToString(suggestedOperator)); + return numberType; + } + else { + // otherwise just check each operand separately and report errors as normal + var leftOk = checkArithmeticOperandType(left, leftType, ts.Diagnostics.The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type); + var rightOk = checkArithmeticOperandType(right, rightType, ts.Diagnostics.The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type); + var resultType_1; + // If both are any or unknown, allow operation; assume it will resolve to number + if ((isTypeAssignableToKind(leftType, 3 /* AnyOrUnknown */) && isTypeAssignableToKind(rightType, 3 /* AnyOrUnknown */)) || + // Or, if neither could be bigint, implicit coercion results in a number result + !(maybeTypeOfKind(leftType, 2112 /* BigIntLike */) || maybeTypeOfKind(rightType, 2112 /* BigIntLike */))) { + resultType_1 = numberType; + } + // At least one is assignable to bigint, so both should be only assignable to bigint + else if (isTypeAssignableToKind(leftType, 2112 /* BigIntLike */) && isTypeAssignableToKind(rightType, 2112 /* BigIntLike */)) { + switch (operator) { + case 48 /* GreaterThanGreaterThanGreaterThanToken */: + case 68 /* GreaterThanGreaterThanGreaterThanEqualsToken */: + reportOperatorError(); + } + resultType_1 = bigintType; + } + else { + reportOperatorError(); + resultType_1 = errorType; + } + if (leftOk && rightOk) { + checkAssignmentOperator(resultType_1); + } + return resultType_1; + } + case 38 /* PlusToken */: + case 60 /* PlusEqualsToken */: + if (leftType === silentNeverType || rightType === silentNeverType) { + return silentNeverType; + } + if (!isTypeAssignableToKind(leftType, 132 /* StringLike */) && !isTypeAssignableToKind(rightType, 132 /* StringLike */)) { + leftType = checkNonNullType(leftType, left); + rightType = checkNonNullType(rightType, right); + } + var resultType = void 0; + if (isTypeAssignableToKind(leftType, 296 /* NumberLike */, /*strict*/ true) && isTypeAssignableToKind(rightType, 296 /* NumberLike */, /*strict*/ true)) { + // Operands of an enum type are treated as having the primitive type Number. + // If both operands are of the Number primitive type, the result is of the Number primitive type. + resultType = numberType; + } + else if (isTypeAssignableToKind(leftType, 2112 /* BigIntLike */, /*strict*/ true) && isTypeAssignableToKind(rightType, 2112 /* BigIntLike */, /*strict*/ true)) { + // If both operands are of the BigInt primitive type, the result is of the BigInt primitive type. + resultType = bigintType; + } + else if (isTypeAssignableToKind(leftType, 132 /* StringLike */, /*strict*/ true) || isTypeAssignableToKind(rightType, 132 /* StringLike */, /*strict*/ true)) { + // If one or both operands are of the String primitive type, the result is of the String primitive type. + resultType = stringType; + } + else if (isTypeAny(leftType) || isTypeAny(rightType)) { + // Otherwise, the result is of type Any. + // NOTE: unknown type here denotes error type. Old compiler treated this case as any type so do we. + resultType = leftType === errorType || rightType === errorType ? errorType : anyType; + } + // Symbols are not allowed at all in arithmetic expressions + if (resultType && !checkForDisallowedESSymbolOperand(operator)) { + return resultType; + } + if (!resultType) { + reportOperatorError(); + return anyType; + } + if (operator === 60 /* PlusEqualsToken */) { + checkAssignmentOperator(resultType); + } + return resultType; + case 28 /* LessThanToken */: + case 30 /* GreaterThanToken */: + case 31 /* LessThanEqualsToken */: + case 32 /* GreaterThanEqualsToken */: + if (checkForDisallowedESSymbolOperand(operator)) { + leftType = getBaseTypeOfLiteralType(checkNonNullType(leftType, left)); + rightType = getBaseTypeOfLiteralType(checkNonNullType(rightType, right)); + if (!(isTypeComparableTo(leftType, rightType) || isTypeComparableTo(rightType, leftType) || + (isTypeAssignableTo(leftType, numberOrBigIntType) && isTypeAssignableTo(rightType, numberOrBigIntType)))) { + reportOperatorError(); + } + } + return booleanType; + case 33 /* EqualsEqualsToken */: + case 34 /* ExclamationEqualsToken */: + case 35 /* EqualsEqualsEqualsToken */: + case 36 /* ExclamationEqualsEqualsToken */: + var leftIsLiteral = isLiteralType(leftType); + var rightIsLiteral = isLiteralType(rightType); + if (!leftIsLiteral || !rightIsLiteral) { + leftType = leftIsLiteral ? getBaseTypeOfLiteralType(leftType) : leftType; + rightType = rightIsLiteral ? getBaseTypeOfLiteralType(rightType) : rightType; + } + if (!isTypeEqualityComparableTo(leftType, rightType) && !isTypeEqualityComparableTo(rightType, leftType)) { + reportOperatorError(); + } + return booleanType; + case 94 /* InstanceOfKeyword */: + return checkInstanceOfExpression(left, right, leftType, rightType); + case 93 /* InKeyword */: + return checkInExpression(left, right, leftType, rightType); + case 54 /* AmpersandAmpersandToken */: + return getTypeFacts(leftType) & 4194304 /* Truthy */ ? + getUnionType([extractDefinitelyFalsyTypes(strictNullChecks ? leftType : getBaseTypeOfLiteralType(rightType)), rightType]) : + leftType; + case 55 /* BarBarToken */: + return getTypeFacts(leftType) & 8388608 /* Falsy */ ? + getUnionType([removeDefinitelyFalsyTypes(leftType), rightType], 2 /* Subtype */) : + leftType; + case 59 /* EqualsToken */: + var declKind = ts.isBinaryExpression(left.parent) ? ts.getAssignmentDeclarationKind(left.parent) : 0 /* None */; + checkAssignmentDeclaration(declKind, rightType); + if (isAssignmentDeclaration(declKind)) { + if (!(rightType.flags & 524288 /* Object */) || + declKind !== 2 /* ModuleExports */ && + declKind !== 6 /* Prototype */ && + !isEmptyObjectType(rightType) && + !isFunctionObjectType(rightType) && + !(ts.getObjectFlags(rightType) & 1 /* Class */)) { + // don't check assignability of module.exports=, C.prototype=, or expando types because they will necessarily be incomplete + checkAssignmentOperator(rightType); + } + return leftType; + } + else { + checkAssignmentOperator(rightType); + return getRegularTypeOfObjectLiteral(rightType); + } + case 27 /* CommaToken */: + if (!compilerOptions.allowUnreachableCode && isSideEffectFree(left) && !isEvalNode(right)) { + error(left, ts.Diagnostics.Left_side_of_comma_operator_is_unused_and_has_no_side_effects); + } + return rightType; + default: + return ts.Debug.fail(); + } + function checkAssignmentDeclaration(kind, rightType) { + if (kind === 2 /* ModuleExports */) { + for (var _i = 0, _a = getPropertiesOfObjectType(rightType); _i < _a.length; _i++) { + var prop = _a[_i]; + var propType = getTypeOfSymbol(prop); + if (propType.symbol && propType.symbol.flags & 32 /* Class */) { + var name = prop.escapedName; + var symbol = resolveName(prop.valueDeclaration, name, 67897832 /* Type */, undefined, name, /*isUse*/ false); + if (symbol && symbol.declarations.some(ts.isJSDocTypedefTag)) { + grammarErrorOnNode(symbol.declarations[0], ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name)); + return grammarErrorOnNode(prop.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name)); + } + } + } + } + } + function isEvalNode(node) { + return node.kind === 72 /* Identifier */ && node.escapedText === "eval"; + } + // Return true if there was no error, false if there was an error. + function checkForDisallowedESSymbolOperand(operator) { + var offendingSymbolOperand = maybeTypeOfKind(leftType, 12288 /* ESSymbolLike */) ? left : + maybeTypeOfKind(rightType, 12288 /* ESSymbolLike */) ? right : + undefined; + if (offendingSymbolOperand) { + error(offendingSymbolOperand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(operator)); + return false; + } + return true; + } + function getSuggestedBooleanOperator(operator) { + switch (operator) { + case 50 /* BarToken */: + case 70 /* BarEqualsToken */: + return 55 /* BarBarToken */; + case 51 /* CaretToken */: + case 71 /* CaretEqualsToken */: + return 36 /* ExclamationEqualsEqualsToken */; + case 49 /* AmpersandToken */: + case 69 /* AmpersandEqualsToken */: + return 54 /* AmpersandAmpersandToken */; + default: + return undefined; + } + } + function checkAssignmentOperator(valueType) { + if (produceDiagnostics && ts.isAssignmentOperator(operator)) { + // TypeScript 1.0 spec (April 2014): 4.17 + // An assignment of the form + // VarExpr = ValueExpr + // requires VarExpr to be classified as a reference + // A compound assignment furthermore requires VarExpr to be classified as a reference (section 4.1) + // and the type of the non-compound operation to be assignable to the type of VarExpr. + if (checkReferenceExpression(left, ts.Diagnostics.The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access) + && (!ts.isIdentifier(left) || ts.unescapeLeadingUnderscores(left.escapedText) !== "exports")) { + // to avoid cascading errors check assignability only if 'isReference' check succeeded and no errors were reported + checkTypeAssignableToAndOptionallyElaborate(valueType, leftType, left, right); + } + } + } + function isAssignmentDeclaration(kind) { + switch (kind) { + case 2 /* ModuleExports */: + return true; + case 1 /* ExportsProperty */: + case 5 /* Property */: + case 6 /* Prototype */: + case 3 /* PrototypeProperty */: + case 4 /* ThisProperty */: + var symbol = getSymbolOfNode(left); + var init = ts.getAssignedExpandoInitializer(right); + return init && ts.isObjectLiteralExpression(init) && + symbol && ts.hasEntries(symbol.exports); + default: + return false; + } + } + function reportOperatorError() { + var leftStr = typeToString(leftType); + var rightStr = typeToString(rightType); + var errNode = errorNode || operatorToken; + if (!tryGiveBetterPrimaryError(errNode, leftStr, rightStr)) { + error(errNode, ts.Diagnostics.Operator_0_cannot_be_applied_to_types_1_and_2, ts.tokenToString(operatorToken.kind), leftStr, rightStr); + } + } + function tryGiveBetterPrimaryError(errNode, leftStr, rightStr) { + switch (operatorToken.kind) { + case 35 /* EqualsEqualsEqualsToken */: + case 33 /* EqualsEqualsToken */: + return error(errNode, ts.Diagnostics.This_condition_will_always_return_0_since_the_types_1_and_2_have_no_overlap, "false", leftStr, rightStr); + case 36 /* ExclamationEqualsEqualsToken */: + case 34 /* ExclamationEqualsToken */: + return error(errNode, ts.Diagnostics.This_condition_will_always_return_0_since_the_types_1_and_2_have_no_overlap, "true", leftStr, rightStr); + } + return undefined; + } + } + function isYieldExpressionInClass(node) { + var current = node; + var parent = node.parent; + while (parent) { + if (ts.isFunctionLike(parent) && current === parent.body) { + return false; + } + else if (ts.isClassLike(current)) { + return true; + } + current = parent; + parent = parent.parent; + } + return false; + } + function checkYieldExpression(node) { + // Grammar checking + if (produceDiagnostics) { + if (!(node.flags & 4096 /* YieldContext */) || isYieldExpressionInClass(node)) { + grammarErrorOnFirstToken(node, ts.Diagnostics.A_yield_expression_is_only_allowed_in_a_generator_body); + } + if (isInParameterInitializerBeforeContainingFunction(node)) { + error(node, ts.Diagnostics.yield_expressions_cannot_be_used_in_a_parameter_initializer); + } + } + var func = ts.getContainingFunction(node); + if (!func) + return anyType; + var functionFlags = ts.getFunctionFlags(func); + if (!(functionFlags & 1 /* Generator */)) { + // If the user's code is syntactically correct, the func should always have a star. After all, we are in a yield context. + return anyType; + } + if (node.asteriskToken) { + // Async generator functions prior to ESNext require the __await, __asyncDelegator, + // and __asyncValues helpers + if ((functionFlags & 3 /* AsyncGenerator */) === 3 /* AsyncGenerator */ && + languageVersion < 6 /* ESNext */) { + checkExternalEmitHelpers(node, 26624 /* AsyncDelegatorIncludes */); + } + // Generator functions prior to ES2015 require the __values helper + if ((functionFlags & 3 /* AsyncGenerator */) === 1 /* Generator */ && + languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) { + checkExternalEmitHelpers(node, 256 /* Values */); + } + } + var isAsync = (functionFlags & 2 /* Async */) !== 0; + var yieldedType = getYieldedTypeOfYieldExpression(node, isAsync); // TODO: GH#18217 + // There is no point in doing an assignability check if the function + // has no explicit return type because the return type is directly computed + // from the yield expressions. + var returnType = getReturnTypeFromAnnotation(func); + if (returnType) { + var signatureElementType = getIteratedTypeOfGenerator(returnType, isAsync) || anyType; + checkTypeAssignableToAndOptionallyElaborate(yieldedType, signatureElementType, node.expression || node, node.expression); + } + // Both yield and yield* expressions have type 'any' + return anyType; + } + function checkConditionalExpression(node, checkMode) { + checkTruthinessExpression(node.condition); + var type1 = checkExpression(node.whenTrue, checkMode); + var type2 = checkExpression(node.whenFalse, checkMode); + return getUnionType([type1, type2], 2 /* Subtype */); + } + function checkTemplateExpression(node) { + // We just want to check each expressions, but we are unconcerned with + // the type of each expression, as any value may be coerced into a string. + // It is worth asking whether this is what we really want though. + // A place where we actually *are* concerned with the expressions' types are + // in tagged templates. + ts.forEach(node.templateSpans, function (templateSpan) { + if (maybeTypeOfKind(checkExpression(templateSpan.expression), 12288 /* ESSymbolLike */)) { + error(templateSpan.expression, ts.Diagnostics.Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_in_String); + } + }); + return stringType; + } + function getContextNode(node) { + if (node.kind === 268 /* JsxAttributes */ && !ts.isJsxSelfClosingElement(node.parent)) { + return node.parent.parent; // Needs to be the root JsxElement, so it encompasses the attributes _and_ the children (which are essentially part of the attributes) + } + return node; + } + function checkExpressionWithContextualType(node, contextualType, contextualMapper) { + var context = getContextNode(node); + var saveContextualType = context.contextualType; + var saveContextualMapper = context.contextualMapper; + context.contextualType = contextualType; + context.contextualMapper = contextualMapper; + var checkMode = contextualMapper === identityMapper ? 1 /* SkipContextSensitive */ : + contextualMapper ? 2 /* Inferential */ : 3 /* Contextual */; + var result = checkExpression(node, checkMode); + context.contextualType = saveContextualType; + context.contextualMapper = saveContextualMapper; + return result; + } + function checkExpressionCached(node, checkMode) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + if (checkMode) { + return checkExpression(node, checkMode); + } + // When computing a type that we're going to cache, we need to ignore any ongoing control flow + // analysis because variables may have transient types in indeterminable states. Moving flowLoopStart + // to the top of the stack ensures all transient types are computed from a known point. + var saveFlowLoopStart = flowLoopStart; + flowLoopStart = flowLoopCount; + links.resolvedType = checkExpression(node, checkMode); + flowLoopStart = saveFlowLoopStart; + } + return links.resolvedType; + } + function isTypeAssertion(node) { + node = ts.skipParentheses(node); + return node.kind === 194 /* TypeAssertionExpression */ || node.kind === 212 /* AsExpression */; + } + function checkDeclarationInitializer(declaration) { + var initializer = ts.getEffectiveInitializer(declaration); + var type = getTypeOfExpression(initializer, /*cache*/ true); + var widened = ts.getCombinedNodeFlags(declaration) & 2 /* Const */ || + ts.isDeclarationReadonly(declaration) || + isTypeAssertion(initializer) ? type : getWidenedLiteralType(type); + if (ts.isInJSFile(declaration)) { + if (widened.flags & 98304 /* Nullable */) { + reportImplicitAny(declaration, anyType); + return anyType; + } + else if (isEmptyArrayLiteralType(widened)) { + reportImplicitAny(declaration, anyArrayType); + return anyArrayType; + } + } + return widened; + } + function isLiteralOfContextualType(candidateType, contextualType) { + if (contextualType) { + if (contextualType.flags & 3145728 /* UnionOrIntersection */) { + var types = contextualType.types; + return ts.some(types, function (t) { return isLiteralOfContextualType(candidateType, t); }); + } + if (contextualType.flags & 58982400 /* InstantiableNonPrimitive */) { + // If the contextual type is a type variable constrained to a primitive type, consider + // this a literal context for literals of that primitive type. For example, given a + // type parameter 'T extends string', infer string literal types for T. + var constraint = getBaseConstraintOfType(contextualType) || emptyObjectType; + return maybeTypeOfKind(constraint, 4 /* String */) && maybeTypeOfKind(candidateType, 128 /* StringLiteral */) || + maybeTypeOfKind(constraint, 8 /* Number */) && maybeTypeOfKind(candidateType, 256 /* NumberLiteral */) || + maybeTypeOfKind(constraint, 64 /* BigInt */) && maybeTypeOfKind(candidateType, 2048 /* BigIntLiteral */) || + maybeTypeOfKind(constraint, 4096 /* ESSymbol */) && maybeTypeOfKind(candidateType, 8192 /* UniqueESSymbol */) || + isLiteralOfContextualType(candidateType, constraint); + } + // If the contextual type is a literal of a particular primitive type, we consider this a + // literal context for all literals of that primitive type. + return !!(contextualType.flags & (128 /* StringLiteral */ | 4194304 /* Index */) && maybeTypeOfKind(candidateType, 128 /* StringLiteral */) || + contextualType.flags & 256 /* NumberLiteral */ && maybeTypeOfKind(candidateType, 256 /* NumberLiteral */) || + contextualType.flags & 2048 /* BigIntLiteral */ && maybeTypeOfKind(candidateType, 2048 /* BigIntLiteral */) || + contextualType.flags & 512 /* BooleanLiteral */ && maybeTypeOfKind(candidateType, 512 /* BooleanLiteral */) || + contextualType.flags & 8192 /* UniqueESSymbol */ && maybeTypeOfKind(candidateType, 8192 /* UniqueESSymbol */)); + } + return false; + } + function checkExpressionForMutableLocation(node, checkMode, contextualType, forceTuple) { + if (arguments.length === 2) { + contextualType = getContextualType(node); + } + var type = checkExpression(node, checkMode, forceTuple); + return isTypeAssertion(node) ? type : + getWidenedLiteralLikeTypeForContextualType(type, contextualType); + } + function checkPropertyAssignment(node, checkMode) { + // Do not use hasDynamicName here, because that returns false for well known symbols. + // We want to perform checkComputedPropertyName for all computed properties, including + // well known symbols. + if (node.name.kind === 149 /* ComputedPropertyName */) { + checkComputedPropertyName(node.name); + } + return checkExpressionForMutableLocation(node.initializer, checkMode); + } + function checkObjectLiteralMethod(node, checkMode) { + // Grammar checking + checkGrammarMethod(node); + // Do not use hasDynamicName here, because that returns false for well known symbols. + // We want to perform checkComputedPropertyName for all computed properties, including + // well known symbols. + if (node.name.kind === 149 /* ComputedPropertyName */) { + checkComputedPropertyName(node.name); + } + var uninstantiatedType = checkFunctionExpressionOrObjectLiteralMethod(node, checkMode); + return instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode); + } + function instantiateTypeWithSingleGenericCallSignature(node, type, checkMode) { + if (checkMode === 2 /* Inferential */) { + var signature = getSingleCallSignature(type); + if (signature && signature.typeParameters) { + var contextualType = getApparentTypeOfContextualType(node); + if (contextualType) { + var contextualSignature = getSingleCallSignature(getNonNullableType(contextualType)); + if (contextualSignature && !contextualSignature.typeParameters) { + return getOrCreateTypeFromSignature(instantiateSignatureInContextOf(signature, contextualSignature, getContextualMapper(node))); + } + } + } + } + return type; + } + /** + * Returns the type of an expression. Unlike checkExpression, this function is simply concerned + * with computing the type and may not fully check all contained sub-expressions for errors. + * A cache argument of true indicates that if the function performs a full type check, it is ok + * to cache the result. + */ + function getTypeOfExpression(node, cache) { + var expr = ts.skipParentheses(node); + // Optimize for the common case of a call to a function with a single non-generic call + // signature where we can just fetch the return type without checking the arguments. + if (expr.kind === 191 /* CallExpression */ && expr.expression.kind !== 98 /* SuperKeyword */ && !ts.isRequireCall(expr, /*checkArgumentIsStringLiteralLike*/ true) && !isSymbolOrSymbolForCall(expr)) { + var funcType = checkNonNullExpression(expr.expression); + var signature = getSingleCallSignature(funcType); + if (signature && !signature.typeParameters) { + return getReturnTypeOfSignature(signature); + } + } + else if (expr.kind === 194 /* TypeAssertionExpression */ || expr.kind === 212 /* AsExpression */) { + return getTypeFromTypeNode(expr.type); + } + // Otherwise simply call checkExpression. Ideally, the entire family of checkXXX functions + // should have a parameter that indicates whether full error checking is required such that + // we can perform the optimizations locally. + return cache ? checkExpressionCached(node) : checkExpression(node); + } + /** + * Returns the type of an expression. Unlike checkExpression, this function is simply concerned + * with computing the type and may not fully check all contained sub-expressions for errors. + * It is intended for uses where you know there is no contextual type, + * and requesting the contextual type might cause a circularity or other bad behaviour. + * It sets the contextual type of the node to any before calling getTypeOfExpression. + */ + function getContextFreeTypeOfExpression(node) { + var links = getNodeLinks(node); + if (links.contextFreeType) { + return links.contextFreeType; + } + var saveContextualType = node.contextualType; + node.contextualType = anyType; + var type = links.contextFreeType = checkExpression(node, 1 /* SkipContextSensitive */); + node.contextualType = saveContextualType; + return type; + } + // Checks an expression and returns its type. The contextualMapper parameter serves two purposes: When + // contextualMapper is not undefined and not equal to the identityMapper function object it indicates that the + // expression is being inferentially typed (section 4.15.2 in spec) and provides the type mapper to use in + // conjunction with the generic contextual type. When contextualMapper is equal to the identityMapper function + // object, it serves as an indicator that all contained function and arrow expressions should be considered to + // have the wildcard function type; this form of type check is used during overload resolution to exclude + // contextually typed function and arrow expressions in the initial phase. + function checkExpression(node, checkMode, forceTuple) { + var type; + if (node.kind === 148 /* QualifiedName */) { + type = checkQualifiedName(node); + } + else { + var uninstantiatedType = checkExpressionWorker(node, checkMode, forceTuple); + type = instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode); + } + if (isConstEnumObjectType(type)) { + // enum object type for const enums are only permitted in: + // - 'left' in property access + // - 'object' in indexed access + // - target in rhs of import statement + var ok = (node.parent.kind === 189 /* PropertyAccessExpression */ && node.parent.expression === node) || + (node.parent.kind === 190 /* ElementAccessExpression */ && node.parent.expression === node) || + ((node.kind === 72 /* Identifier */ || node.kind === 148 /* QualifiedName */) && isInRightSideOfImportOrExportAssignment(node) || + (node.parent.kind === 167 /* TypeQuery */ && node.parent.exprName === node)); + if (!ok) { + error(node, ts.Diagnostics.const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment_or_type_query); + } + } + return type; + } + function checkParenthesizedExpression(node, checkMode) { + var tag = ts.isInJSFile(node) ? ts.getJSDocTypeTag(node) : undefined; + if (tag) { + return checkAssertionWorker(tag, tag.typeExpression.type, node.expression, checkMode); + } + return checkExpression(node.expression, checkMode); + } + function checkExpressionWorker(node, checkMode, forceTuple) { + switch (node.kind) { + case 72 /* Identifier */: + return checkIdentifier(node); + case 100 /* ThisKeyword */: + return checkThisExpression(node); + case 98 /* SuperKeyword */: + return checkSuperExpression(node); + case 96 /* NullKeyword */: + return nullWideningType; + case 14 /* NoSubstitutionTemplateLiteral */: + case 10 /* StringLiteral */: + return getFreshTypeOfLiteralType(getLiteralType(node.text)); + case 8 /* NumericLiteral */: + checkGrammarNumericLiteral(node); + return getFreshTypeOfLiteralType(getLiteralType(+node.text)); + case 9 /* BigIntLiteral */: + checkGrammarBigIntLiteral(node); + return getFreshTypeOfLiteralType(getBigIntLiteralType(node)); + case 102 /* TrueKeyword */: + return trueType; + case 87 /* FalseKeyword */: + return falseType; + case 206 /* TemplateExpression */: + return checkTemplateExpression(node); + case 13 /* RegularExpressionLiteral */: + return globalRegExpType; + case 187 /* ArrayLiteralExpression */: + return checkArrayLiteral(node, checkMode, forceTuple); + case 188 /* ObjectLiteralExpression */: + return checkObjectLiteral(node, checkMode); + case 189 /* PropertyAccessExpression */: + return checkPropertyAccessExpression(node); + case 190 /* ElementAccessExpression */: + return checkIndexedAccess(node); + case 191 /* CallExpression */: + if (node.expression.kind === 92 /* ImportKeyword */) { + return checkImportCallExpression(node); + } + /* falls through */ + case 192 /* NewExpression */: + return checkCallExpression(node); + case 193 /* TaggedTemplateExpression */: + return checkTaggedTemplateExpression(node); + case 195 /* ParenthesizedExpression */: + return checkParenthesizedExpression(node, checkMode); + case 209 /* ClassExpression */: + return checkClassExpression(node); + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + return checkFunctionExpressionOrObjectLiteralMethod(node, checkMode); + case 199 /* TypeOfExpression */: + return checkTypeOfExpression(node); + case 194 /* TypeAssertionExpression */: + case 212 /* AsExpression */: + return checkAssertion(node); + case 213 /* NonNullExpression */: + return checkNonNullAssertion(node); + case 214 /* MetaProperty */: + return checkMetaProperty(node); + case 198 /* DeleteExpression */: + return checkDeleteExpression(node); + case 200 /* VoidExpression */: + return checkVoidExpression(node); + case 201 /* AwaitExpression */: + return checkAwaitExpression(node); + case 202 /* PrefixUnaryExpression */: + return checkPrefixUnaryExpression(node); + case 203 /* PostfixUnaryExpression */: + return checkPostfixUnaryExpression(node); + case 204 /* BinaryExpression */: + return checkBinaryExpression(node, checkMode); + case 205 /* ConditionalExpression */: + return checkConditionalExpression(node, checkMode); + case 208 /* SpreadElement */: + return checkSpreadExpression(node, checkMode); + case 210 /* OmittedExpression */: + return undefinedWideningType; + case 207 /* YieldExpression */: + return checkYieldExpression(node); + case 215 /* SyntheticExpression */: + return node.type; + case 270 /* JsxExpression */: + return checkJsxExpression(node, checkMode); + case 260 /* JsxElement */: + return checkJsxElement(node, checkMode); + case 261 /* JsxSelfClosingElement */: + return checkJsxSelfClosingElement(node, checkMode); + case 264 /* JsxFragment */: + return checkJsxFragment(node); + case 268 /* JsxAttributes */: + return checkJsxAttributes(node, checkMode); + case 262 /* JsxOpeningElement */: + ts.Debug.fail("Shouldn't ever directly check a JsxOpeningElement"); + } + return errorType; + } + // DECLARATION AND STATEMENT TYPE CHECKING + function checkTypeParameter(node) { + // Grammar Checking + if (node.expression) { + grammarErrorOnFirstToken(node.expression, ts.Diagnostics.Type_expected); + } + checkSourceElement(node.constraint); + checkSourceElement(node.default); + var typeParameter = getDeclaredTypeOfTypeParameter(getSymbolOfNode(node)); + if (!hasNonCircularBaseConstraint(typeParameter)) { + error(ts.getEffectiveConstraintOfTypeParameter(node), ts.Diagnostics.Type_parameter_0_has_a_circular_constraint, typeToString(typeParameter)); + } + if (!hasNonCircularTypeParameterDefault(typeParameter)) { + error(node.default, ts.Diagnostics.Type_parameter_0_has_a_circular_default, typeToString(typeParameter)); + } + var constraintType = getConstraintOfTypeParameter(typeParameter); + var defaultType = getDefaultFromTypeParameter(typeParameter); + if (constraintType && defaultType) { + checkTypeAssignableTo(defaultType, getTypeWithThisArgument(constraintType, defaultType), node.default, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); + } + if (produceDiagnostics) { + checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_parameter_name_cannot_be_0); + } + } + function checkParameter(node) { + // Grammar checking + // It is a SyntaxError if the Identifier "eval" or the Identifier "arguments" occurs as the + // Identifier in a PropertySetParameterList of a PropertyAssignment that is contained in strict code + // or if its FunctionBody is strict code(11.1.5). + checkGrammarDecoratorsAndModifiers(node); + checkVariableLikeDeclaration(node); + var func = ts.getContainingFunction(node); + if (ts.hasModifier(node, 92 /* ParameterPropertyModifier */)) { + if (!(func.kind === 157 /* Constructor */ && ts.nodeIsPresent(func.body))) { + error(node, ts.Diagnostics.A_parameter_property_is_only_allowed_in_a_constructor_implementation); + } + } + if (node.questionToken && ts.isBindingPattern(node.name) && func.body) { + error(node, ts.Diagnostics.A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature); + } + if (node.name && ts.isIdentifier(node.name) && (node.name.escapedText === "this" || node.name.escapedText === "new")) { + if (func.parameters.indexOf(node) !== 0) { + error(node, ts.Diagnostics.A_0_parameter_must_be_the_first_parameter, node.name.escapedText); + } + if (func.kind === 157 /* Constructor */ || func.kind === 161 /* ConstructSignature */ || func.kind === 166 /* ConstructorType */) { + error(node, ts.Diagnostics.A_constructor_cannot_have_a_this_parameter); + } + if (func.kind === 197 /* ArrowFunction */) { + error(node, ts.Diagnostics.An_arrow_function_cannot_have_a_this_parameter); + } + } + // Only check rest parameter type if it's not a binding pattern. Since binding patterns are + // not allowed in a rest parameter, we already have an error from checkGrammarParameterList. + if (node.dotDotDotToken && !ts.isBindingPattern(node.name) && !isTypeAssignableTo(getTypeOfSymbol(node.symbol), anyArrayType)) { + error(node, ts.Diagnostics.A_rest_parameter_must_be_of_an_array_type); + } + } + function checkTypePredicate(node) { + var parent = getTypePredicateParent(node); + if (!parent) { + // The parent must not be valid. + error(node, ts.Diagnostics.A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods); + return; + } + var typePredicate = getTypePredicateOfSignature(getSignatureFromDeclaration(parent)); + if (!typePredicate) { + return; + } + checkSourceElement(node.type); + var parameterName = node.parameterName; + if (ts.isThisTypePredicate(typePredicate)) { + getTypeFromThisTypeNode(parameterName); + } + else { + if (typePredicate.parameterIndex >= 0) { + if (parent.parameters[typePredicate.parameterIndex].dotDotDotToken) { + error(parameterName, ts.Diagnostics.A_type_predicate_cannot_reference_a_rest_parameter); + } + else { + var leadingError = function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type); }; + checkTypeAssignableTo(typePredicate.type, getTypeOfNode(parent.parameters[typePredicate.parameterIndex]), node.type, + /*headMessage*/ undefined, leadingError); + } + } + else if (parameterName) { + var hasReportedError = false; + for (var _i = 0, _a = parent.parameters; _i < _a.length; _i++) { + var name = _a[_i].name; + if (ts.isBindingPattern(name) && + checkIfTypePredicateVariableIsDeclaredInBindingPattern(name, parameterName, typePredicate.parameterName)) { + hasReportedError = true; + break; + } + } + if (!hasReportedError) { + error(node.parameterName, ts.Diagnostics.Cannot_find_parameter_0, typePredicate.parameterName); + } + } + } + } + function getTypePredicateParent(node) { + switch (node.parent.kind) { + case 197 /* ArrowFunction */: + case 160 /* CallSignature */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 165 /* FunctionType */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + var parent = node.parent; + if (node === parent.type) { + return parent; + } + } + } + function checkIfTypePredicateVariableIsDeclaredInBindingPattern(pattern, predicateVariableNode, predicateVariableName) { + for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (ts.isOmittedExpression(element)) { + continue; + } + var name = element.name; + if (name.kind === 72 /* Identifier */ && name.escapedText === predicateVariableName) { + error(predicateVariableNode, ts.Diagnostics.A_type_predicate_cannot_reference_element_0_in_a_binding_pattern, predicateVariableName); + return true; + } + else if (name.kind === 185 /* ArrayBindingPattern */ || name.kind === 184 /* ObjectBindingPattern */) { + if (checkIfTypePredicateVariableIsDeclaredInBindingPattern(name, predicateVariableNode, predicateVariableName)) { + return true; + } + } + } + } + function checkSignatureDeclaration(node) { + // Grammar checking + if (node.kind === 162 /* IndexSignature */) { + checkGrammarIndexSignature(node); + } + // TODO (yuisu): Remove this check in else-if when SyntaxKind.Construct is moved and ambient context is handled + else if (node.kind === 165 /* FunctionType */ || node.kind === 239 /* FunctionDeclaration */ || node.kind === 166 /* ConstructorType */ || + node.kind === 160 /* CallSignature */ || node.kind === 157 /* Constructor */ || + node.kind === 161 /* ConstructSignature */) { + checkGrammarFunctionLikeDeclaration(node); + } + var functionFlags = ts.getFunctionFlags(node); + if (!(functionFlags & 4 /* Invalid */)) { + // Async generators prior to ESNext require the __await and __asyncGenerator helpers + if ((functionFlags & 3 /* AsyncGenerator */) === 3 /* AsyncGenerator */ && languageVersion < 6 /* ESNext */) { + checkExternalEmitHelpers(node, 6144 /* AsyncGeneratorIncludes */); + } + // Async functions prior to ES2017 require the __awaiter helper + if ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */ && languageVersion < 4 /* ES2017 */) { + checkExternalEmitHelpers(node, 64 /* Awaiter */); + } + // Generator functions, Async functions, and Async Generator functions prior to + // ES2015 require the __generator helper + if ((functionFlags & 3 /* AsyncGenerator */) !== 0 /* Normal */ && languageVersion < 2 /* ES2015 */) { + checkExternalEmitHelpers(node, 128 /* Generator */); + } + } + checkTypeParameters(node.typeParameters); + ts.forEach(node.parameters, checkParameter); + // TODO(rbuckton): Should we start checking JSDoc types? + if (node.type) { + checkSourceElement(node.type); + } + if (produceDiagnostics) { + checkCollisionWithArgumentsInGeneratedCode(node); + var returnTypeNode = ts.getEffectiveReturnTypeNode(node); + if (noImplicitAny && !returnTypeNode) { + switch (node.kind) { + case 161 /* ConstructSignature */: + error(node, ts.Diagnostics.Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type); + break; + case 160 /* CallSignature */: + error(node, ts.Diagnostics.Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type); + break; + } + } + if (returnTypeNode) { + var functionFlags_1 = ts.getFunctionFlags(node); + if ((functionFlags_1 & (4 /* Invalid */ | 1 /* Generator */)) === 1 /* Generator */) { + var returnType = getTypeFromTypeNode(returnTypeNode); + if (returnType === voidType) { + error(returnTypeNode, ts.Diagnostics.A_generator_cannot_have_a_void_type_annotation); + } + else { + var generatorElementType = getIteratedTypeOfGenerator(returnType, (functionFlags_1 & 2 /* Async */) !== 0) || anyType; + var iterableIteratorInstantiation = functionFlags_1 & 2 /* Async */ + ? createAsyncIterableIteratorType(generatorElementType) // AsyncGenerator function + : createIterableIteratorType(generatorElementType); // Generator function + // Naively, one could check that IterableIterator is assignable to the return type annotation. + // However, that would not catch the error in the following case. + // + // interface BadGenerator extends Iterable, Iterator { } + // function* g(): BadGenerator { } // Iterable and Iterator have different types! + // + checkTypeAssignableTo(iterableIteratorInstantiation, returnType, returnTypeNode); + } + } + else if ((functionFlags_1 & 3 /* AsyncGenerator */) === 2 /* Async */) { + checkAsyncFunctionReturnType(node, returnTypeNode); + } + } + if (node.kind !== 162 /* IndexSignature */ && node.kind !== 289 /* JSDocFunctionType */) { + registerForUnusedIdentifiersCheck(node); + } + } + } + function checkClassForDuplicateDeclarations(node) { + var Declaration; + (function (Declaration) { + Declaration[Declaration["Getter"] = 1] = "Getter"; + Declaration[Declaration["Setter"] = 2] = "Setter"; + Declaration[Declaration["Method"] = 4] = "Method"; + Declaration[Declaration["Property"] = 3] = "Property"; + })(Declaration || (Declaration = {})); + var instanceNames = ts.createUnderscoreEscapedMap(); + var staticNames = ts.createUnderscoreEscapedMap(); + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + if (member.kind === 157 /* Constructor */) { + for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { + var param = _c[_b]; + if (ts.isParameterPropertyDeclaration(param) && !ts.isBindingPattern(param.name)) { + addName(instanceNames, param.name, param.name.escapedText, 3 /* Property */); + } + } + } + else { + var isStatic = ts.hasModifier(member, 32 /* Static */); + var names = isStatic ? staticNames : instanceNames; + var name = member.name; + var memberName = name && ts.getPropertyNameForPropertyNameNode(name); + if (name && memberName) { + switch (member.kind) { + case 158 /* GetAccessor */: + addName(names, name, memberName, 1 /* Getter */); + break; + case 159 /* SetAccessor */: + addName(names, name, memberName, 2 /* Setter */); + break; + case 154 /* PropertyDeclaration */: + addName(names, name, memberName, 3 /* Property */); + break; + case 156 /* MethodDeclaration */: + addName(names, name, memberName, 4 /* Method */); + break; + } + } + } + } + function addName(names, location, name, meaning) { + var prev = names.get(name); + if (prev) { + if (prev & 4 /* Method */) { + if (meaning !== 4 /* Method */) { + error(location, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(location)); + } + } + else if (prev & meaning) { + error(location, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(location)); + } + else { + names.set(name, prev | meaning); + } + } + else { + names.set(name, meaning); + } + } + } + /** + * Static members being set on a constructor function may conflict with built-in properties + * of Function. Esp. in ECMAScript 5 there are non-configurable and non-writable + * built-in properties. This check issues a transpile error when a class has a static + * member with the same name as a non-writable built-in property. + * + * @see http://www.ecma-international.org/ecma-262/5.1/#sec-15.3.3 + * @see http://www.ecma-international.org/ecma-262/5.1/#sec-15.3.5 + * @see http://www.ecma-international.org/ecma-262/6.0/#sec-properties-of-the-function-constructor + * @see http://www.ecma-international.org/ecma-262/6.0/#sec-function-instances + */ + function checkClassForStaticPropertyNameConflicts(node) { + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + var memberNameNode = member.name; + var isStatic = ts.hasModifier(member, 32 /* Static */); + if (isStatic && memberNameNode) { + var memberName = ts.getPropertyNameForPropertyNameNode(memberNameNode); + switch (memberName) { + case "name": + case "length": + case "caller": + case "arguments": + case "prototype": + var message = ts.Diagnostics.Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1; + var className = getNameOfSymbolAsWritten(getSymbolOfNode(node)); + error(memberNameNode, message, memberName, className); + break; + } + } + } + } + function checkObjectTypeForDuplicateDeclarations(node) { + var names = ts.createMap(); + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + if (member.kind === 153 /* PropertySignature */) { + var memberName = void 0; + var name = member.name; + switch (name.kind) { + case 10 /* StringLiteral */: + case 8 /* NumericLiteral */: + memberName = name.text; + break; + case 72 /* Identifier */: + memberName = ts.idText(name); + break; + default: + continue; + } + if (names.get(memberName)) { + error(ts.getNameOfDeclaration(member.symbol.valueDeclaration), ts.Diagnostics.Duplicate_identifier_0, memberName); + error(member.name, ts.Diagnostics.Duplicate_identifier_0, memberName); + } + else { + names.set(memberName, true); + } + } + } + } + function checkTypeForDuplicateIndexSignatures(node) { + if (node.kind === 241 /* InterfaceDeclaration */) { + var nodeSymbol = getSymbolOfNode(node); + // in case of merging interface declaration it is possible that we'll enter this check procedure several times for every declaration + // to prevent this run check only for the first declaration of a given kind + if (nodeSymbol.declarations.length > 0 && nodeSymbol.declarations[0] !== node) { + return; + } + } + // TypeScript 1.0 spec (April 2014) + // 3.7.4: An object type can contain at most one string index signature and one numeric index signature. + // 8.5: A class declaration can have at most one string index member declaration and one numeric index member declaration + var indexSymbol = getIndexSymbol(getSymbolOfNode(node)); + if (indexSymbol) { + var seenNumericIndexer = false; + var seenStringIndexer = false; + for (var _i = 0, _a = indexSymbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + var declaration = decl; + if (declaration.parameters.length === 1 && declaration.parameters[0].type) { + switch (declaration.parameters[0].type.kind) { + case 138 /* StringKeyword */: + if (!seenStringIndexer) { + seenStringIndexer = true; + } + else { + error(declaration, ts.Diagnostics.Duplicate_string_index_signature); + } + break; + case 135 /* NumberKeyword */: + if (!seenNumericIndexer) { + seenNumericIndexer = true; + } + else { + error(declaration, ts.Diagnostics.Duplicate_number_index_signature); + } + break; + } + } + } + } + } + function checkPropertyDeclaration(node) { + // Grammar checking + if (!checkGrammarDecoratorsAndModifiers(node) && !checkGrammarProperty(node)) + checkGrammarComputedPropertyName(node.name); + checkVariableLikeDeclaration(node); + } + function checkMethodDeclaration(node) { + // Grammar checking + if (!checkGrammarMethod(node)) + checkGrammarComputedPropertyName(node.name); + // Grammar checking for modifiers is done inside the function checkGrammarFunctionLikeDeclaration + checkFunctionOrMethodDeclaration(node); + // Abstract methods cannot have an implementation. + // Extra checks are to avoid reporting multiple errors relating to the "abstractness" of the node. + if (ts.hasModifier(node, 128 /* Abstract */) && node.kind === 156 /* MethodDeclaration */ && node.body) { + error(node, ts.Diagnostics.Method_0_cannot_have_an_implementation_because_it_is_marked_abstract, ts.declarationNameToString(node.name)); + } + } + function checkConstructorDeclaration(node) { + // Grammar check on signature of constructor and modifier of the constructor is done in checkSignatureDeclaration function. + checkSignatureDeclaration(node); + // Grammar check for checking only related to constructorDeclaration + if (!checkGrammarConstructorTypeParameters(node)) + checkGrammarConstructorTypeAnnotation(node); + checkSourceElement(node.body); + var symbol = getSymbolOfNode(node); + var firstDeclaration = ts.getDeclarationOfKind(symbol, node.kind); + // Only type check the symbol once + if (node === firstDeclaration) { + checkFunctionOrConstructorSymbol(symbol); + } + // exit early in the case of signature - super checks are not relevant to them + if (ts.nodeIsMissing(node.body)) { + return; + } + if (!produceDiagnostics) { + return; + } + function isInstancePropertyWithInitializer(n) { + return n.kind === 154 /* PropertyDeclaration */ && + !ts.hasModifier(n, 32 /* Static */) && + !!n.initializer; + } + // TS 1.0 spec (April 2014): 8.3.2 + // Constructors of classes with no extends clause may not contain super calls, whereas + // constructors of derived classes must contain at least one super call somewhere in their function body. + var containingClassDecl = node.parent; + if (ts.getEffectiveBaseTypeNode(containingClassDecl)) { + captureLexicalThis(node.parent, containingClassDecl); + var classExtendsNull = classDeclarationExtendsNull(containingClassDecl); + var superCall = getSuperCallInConstructor(node); + if (superCall) { + if (classExtendsNull) { + error(superCall, ts.Diagnostics.A_constructor_cannot_contain_a_super_call_when_its_class_extends_null); + } + // The first statement in the body of a constructor (excluding prologue directives) must be a super call + // if both of the following are true: + // - The containing class is a derived class. + // - The constructor declares parameter properties + // or the containing class declares instance member variables with initializers. + var superCallShouldBeFirst = ts.some(node.parent.members, isInstancePropertyWithInitializer) || + ts.some(node.parameters, function (p) { return ts.hasModifier(p, 92 /* ParameterPropertyModifier */); }); + // Skip past any prologue directives to find the first statement + // to ensure that it was a super call. + if (superCallShouldBeFirst) { + var statements = node.body.statements; + var superCallStatement = void 0; + for (var _i = 0, statements_2 = statements; _i < statements_2.length; _i++) { + var statement = statements_2[_i]; + if (statement.kind === 221 /* ExpressionStatement */ && ts.isSuperCall(statement.expression)) { + superCallStatement = statement; + break; + } + if (!ts.isPrologueDirective(statement)) { + break; + } + } + if (!superCallStatement) { + error(node, ts.Diagnostics.A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_properties_or_has_parameter_properties); + } + } + } + else if (!classExtendsNull) { + error(node, ts.Diagnostics.Constructors_for_derived_classes_must_contain_a_super_call); + } + } + } + function checkAccessorDeclaration(node) { + if (produceDiagnostics) { + // Grammar checking accessors + if (!checkGrammarFunctionLikeDeclaration(node) && !checkGrammarAccessor(node)) + checkGrammarComputedPropertyName(node.name); + checkDecorators(node); + checkSignatureDeclaration(node); + if (node.kind === 158 /* GetAccessor */) { + if (!(node.flags & 4194304 /* Ambient */) && ts.nodeIsPresent(node.body) && (node.flags & 128 /* HasImplicitReturn */)) { + if (!(node.flags & 256 /* HasExplicitReturn */)) { + error(node.name, ts.Diagnostics.A_get_accessor_must_return_a_value); + } + } + } + // Do not use hasDynamicName here, because that returns false for well known symbols. + // We want to perform checkComputedPropertyName for all computed properties, including + // well known symbols. + if (node.name.kind === 149 /* ComputedPropertyName */) { + checkComputedPropertyName(node.name); + } + if (!hasNonBindableDynamicName(node)) { + // TypeScript 1.0 spec (April 2014): 8.4.3 + // Accessors for the same member name must specify the same accessibility. + var otherKind = node.kind === 158 /* GetAccessor */ ? 159 /* SetAccessor */ : 158 /* GetAccessor */; + var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(node), otherKind); + if (otherAccessor) { + var nodeFlags = ts.getModifierFlags(node); + var otherFlags = ts.getModifierFlags(otherAccessor); + if ((nodeFlags & 28 /* AccessibilityModifier */) !== (otherFlags & 28 /* AccessibilityModifier */)) { + error(node.name, ts.Diagnostics.Getter_and_setter_accessors_do_not_agree_in_visibility); + } + if ((nodeFlags & 128 /* Abstract */) !== (otherFlags & 128 /* Abstract */)) { + error(node.name, ts.Diagnostics.Accessors_must_both_be_abstract_or_non_abstract); + } + // TypeScript 1.0 spec (April 2014): 4.5 + // If both accessors include type annotations, the specified types must be identical. + checkAccessorDeclarationTypesIdentical(node, otherAccessor, getAnnotatedAccessorType, ts.Diagnostics.get_and_set_accessor_must_have_the_same_type); + checkAccessorDeclarationTypesIdentical(node, otherAccessor, getThisTypeOfDeclaration, ts.Diagnostics.get_and_set_accessor_must_have_the_same_this_type); + } + } + var returnType = getTypeOfAccessors(getSymbolOfNode(node)); + if (node.kind === 158 /* GetAccessor */) { + checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnType); + } + } + checkSourceElement(node.body); + } + function checkAccessorDeclarationTypesIdentical(first, second, getAnnotatedType, message) { + var firstType = getAnnotatedType(first); + var secondType = getAnnotatedType(second); + if (firstType && secondType && !isTypeIdenticalTo(firstType, secondType)) { + error(first, message); + } + } + function checkMissingDeclaration(node) { + checkDecorators(node); + } + function getEffectiveTypeArguments(node, typeParameters) { + return fillMissingTypeArguments(ts.map(node.typeArguments, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJSFile(node)); + } + function checkTypeArgumentConstraints(node, typeParameters) { + var typeArguments; + var mapper; + var result = true; + for (var i = 0; i < typeParameters.length; i++) { + var constraint = getConstraintOfTypeParameter(typeParameters[i]); + if (constraint) { + if (!typeArguments) { + typeArguments = getEffectiveTypeArguments(node, typeParameters); + mapper = createTypeMapper(typeParameters, typeArguments); + } + result = result && checkTypeAssignableTo(typeArguments[i], instantiateType(constraint, mapper), node.typeArguments[i], ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); + } + } + return result; + } + function getTypeParametersForTypeReference(node) { + var type = getTypeFromTypeReference(node); + if (type !== errorType) { + var symbol = getNodeLinks(node).resolvedSymbol; + if (symbol) { + return symbol.flags & 524288 /* TypeAlias */ && getSymbolLinks(symbol).typeParameters || + (ts.getObjectFlags(type) & 4 /* Reference */ ? type.target.localTypeParameters : undefined); + } + } + return undefined; + } + function checkTypeReferenceNode(node) { + checkGrammarTypeArguments(node, node.typeArguments); + if (node.kind === 164 /* TypeReference */ && node.typeName.jsdocDotPos !== undefined && !ts.isInJSFile(node) && !ts.isInJSDoc(node)) { + grammarErrorAtPos(node, node.typeName.jsdocDotPos, 1, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments); + } + var type = getTypeFromTypeReference(node); + if (type !== errorType) { + if (node.typeArguments) { + // Do type argument local checks only if referenced type is successfully resolved + ts.forEach(node.typeArguments, checkSourceElement); + if (produceDiagnostics) { + var typeParameters = getTypeParametersForTypeReference(node); + if (typeParameters) { + checkTypeArgumentConstraints(node, typeParameters); + } + } + } + if (type.flags & 32 /* Enum */ && getNodeLinks(node).resolvedSymbol.flags & 8 /* EnumMember */) { + error(node, ts.Diagnostics.Enum_type_0_has_members_with_initializers_that_are_not_literals, typeToString(type)); + } + } + } + function getTypeArgumentConstraint(node) { + var typeReferenceNode = ts.tryCast(node.parent, ts.isTypeReferenceType); + if (!typeReferenceNode) + return undefined; + var typeParameters = getTypeParametersForTypeReference(typeReferenceNode); // TODO: GH#18217 + var constraint = getConstraintOfTypeParameter(typeParameters[typeReferenceNode.typeArguments.indexOf(node)]); + return constraint && instantiateType(constraint, createTypeMapper(typeParameters, getEffectiveTypeArguments(typeReferenceNode, typeParameters))); + } + function checkTypeQuery(node) { + getTypeFromTypeQueryNode(node); + } + function checkTypeLiteral(node) { + ts.forEach(node.members, checkSourceElement); + if (produceDiagnostics) { + var type = getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node); + checkIndexConstraints(type); + checkTypeForDuplicateIndexSignatures(node); + checkObjectTypeForDuplicateDeclarations(node); + } + } + function checkArrayType(node) { + checkSourceElement(node.elementType); + } + function checkTupleType(node) { + var elementTypes = node.elementTypes; + var seenOptionalElement = false; + for (var i = 0; i < elementTypes.length; i++) { + var e = elementTypes[i]; + if (e.kind === 172 /* RestType */) { + if (i !== elementTypes.length - 1) { + grammarErrorOnNode(e, ts.Diagnostics.A_rest_element_must_be_last_in_a_tuple_type); + break; + } + if (!isArrayType(getTypeFromTypeNode(e))) { + error(e, ts.Diagnostics.A_rest_element_type_must_be_an_array_type); + } + } + else if (e.kind === 171 /* OptionalType */) { + seenOptionalElement = true; + } + else if (seenOptionalElement) { + grammarErrorOnNode(e, ts.Diagnostics.A_required_element_cannot_follow_an_optional_element); + break; + } + } + checkGrammarForDisallowedTrailingComma(node.elementTypes); + ts.forEach(node.elementTypes, checkSourceElement); + } + function checkUnionOrIntersectionType(node) { + ts.forEach(node.types, checkSourceElement); + } + function checkIndexedAccessIndexType(type, accessNode) { + if (!(type.flags & 8388608 /* IndexedAccess */)) { + return type; + } + // Check if the index type is assignable to 'keyof T' for the object type. + var objectType = type.objectType; + var indexType = type.indexType; + if (isTypeAssignableTo(indexType, getIndexType(objectType, /*stringsOnly*/ false))) { + if (accessNode.kind === 190 /* ElementAccessExpression */ && ts.isAssignmentTarget(accessNode) && + ts.getObjectFlags(objectType) & 32 /* Mapped */ && getMappedTypeModifiers(objectType) & 1 /* IncludeReadonly */) { + error(accessNode, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(objectType)); + } + return type; + } + // Check if we're indexing with a numeric type and if either object or index types + // is a generic type with a constraint that has a numeric index signature. + if (getIndexInfoOfType(getApparentType(objectType), 1 /* Number */) && isTypeAssignableToKind(indexType, 296 /* NumberLike */)) { + return type; + } + error(accessNode, ts.Diagnostics.Type_0_cannot_be_used_to_index_type_1, typeToString(indexType), typeToString(objectType)); + return type; + } + function checkIndexedAccessType(node) { + checkSourceElement(node.objectType); + checkSourceElement(node.indexType); + checkIndexedAccessIndexType(getTypeFromIndexedAccessTypeNode(node), node); + } + function checkMappedType(node) { + checkSourceElement(node.typeParameter); + checkSourceElement(node.type); + if (!node.type) { + reportImplicitAny(node, anyType); + } + var type = getTypeFromMappedTypeNode(node); + var constraintType = getConstraintTypeFromMappedType(type); + checkTypeAssignableTo(constraintType, keyofConstraintType, ts.getEffectiveConstraintOfTypeParameter(node.typeParameter)); + } + function checkThisType(node) { + getTypeFromThisTypeNode(node); + } + function checkTypeOperator(node) { + checkGrammarTypeOperatorNode(node); + checkSourceElement(node.type); + } + function checkConditionalType(node) { + ts.forEachChild(node, checkSourceElement); + } + function checkInferType(node) { + if (!ts.findAncestor(node, function (n) { return n.parent && n.parent.kind === 175 /* ConditionalType */ && n.parent.extendsType === n; })) { + grammarErrorOnNode(node, ts.Diagnostics.infer_declarations_are_only_permitted_in_the_extends_clause_of_a_conditional_type); + } + checkSourceElement(node.typeParameter); + registerForUnusedIdentifiersCheck(node); + } + function checkImportType(node) { + checkSourceElement(node.argument); + getTypeFromTypeNode(node); + } + function isPrivateWithinAmbient(node) { + return ts.hasModifier(node, 8 /* Private */) && !!(node.flags & 4194304 /* Ambient */); + } + function getEffectiveDeclarationFlags(n, flagsToCheck) { + var flags = ts.getCombinedModifierFlags(n); + // children of classes (even ambient classes) should not be marked as ambient or export + // because those flags have no useful semantics there. + if (n.parent.kind !== 241 /* InterfaceDeclaration */ && + n.parent.kind !== 240 /* ClassDeclaration */ && + n.parent.kind !== 209 /* ClassExpression */ && + n.flags & 4194304 /* Ambient */) { + if (!(flags & 2 /* Ambient */) && !(ts.isModuleBlock(n.parent) && ts.isModuleDeclaration(n.parent.parent) && ts.isGlobalScopeAugmentation(n.parent.parent))) { + // It is nested in an ambient context, which means it is automatically exported + flags |= 1 /* Export */; + } + flags |= 2 /* Ambient */; + } + return flags & flagsToCheck; + } + function checkFunctionOrConstructorSymbol(symbol) { + if (!produceDiagnostics) { + return; + } + function getCanonicalOverload(overloads, implementation) { + // Consider the canonical set of flags to be the flags of the bodyDeclaration or the first declaration + // Error on all deviations from this canonical set of flags + // The caveat is that if some overloads are defined in lib.d.ts, we don't want to + // report the errors on those. To achieve this, we will say that the implementation is + // the canonical signature only if it is in the same container as the first overload + var implementationSharesContainerWithFirstOverload = implementation !== undefined && implementation.parent === overloads[0].parent; + return implementationSharesContainerWithFirstOverload ? implementation : overloads[0]; + } + function checkFlagAgreementBetweenOverloads(overloads, implementation, flagsToCheck, someOverloadFlags, allOverloadFlags) { + // Error if some overloads have a flag that is not shared by all overloads. To find the + // deviations, we XOR someOverloadFlags with allOverloadFlags + var someButNotAllOverloadFlags = someOverloadFlags ^ allOverloadFlags; + if (someButNotAllOverloadFlags !== 0) { + var canonicalFlags_1 = getEffectiveDeclarationFlags(getCanonicalOverload(overloads, implementation), flagsToCheck); + ts.forEach(overloads, function (o) { + var deviation = getEffectiveDeclarationFlags(o, flagsToCheck) ^ canonicalFlags_1; + if (deviation & 1 /* Export */) { + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_exported_or_non_exported); + } + else if (deviation & 2 /* Ambient */) { + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_ambient_or_non_ambient); + } + else if (deviation & (8 /* Private */ | 16 /* Protected */)) { + error(ts.getNameOfDeclaration(o) || o, ts.Diagnostics.Overload_signatures_must_all_be_public_private_or_protected); + } + else if (deviation & 128 /* Abstract */) { + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_abstract_or_non_abstract); + } + }); + } + } + function checkQuestionTokenAgreementBetweenOverloads(overloads, implementation, someHaveQuestionToken, allHaveQuestionToken) { + if (someHaveQuestionToken !== allHaveQuestionToken) { + var canonicalHasQuestionToken_1 = ts.hasQuestionToken(getCanonicalOverload(overloads, implementation)); + ts.forEach(overloads, function (o) { + var deviation = ts.hasQuestionToken(o) !== canonicalHasQuestionToken_1; + if (deviation) { + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_optional_or_required); + } + }); + } + } + var flagsToCheck = 1 /* Export */ | 2 /* Ambient */ | 8 /* Private */ | 16 /* Protected */ | 128 /* Abstract */; + var someNodeFlags = 0 /* None */; + var allNodeFlags = flagsToCheck; + var someHaveQuestionToken = false; + var allHaveQuestionToken = true; + var hasOverloads = false; + var bodyDeclaration; + var lastSeenNonAmbientDeclaration; + var previousDeclaration; + var declarations = symbol.declarations; + var isConstructor = (symbol.flags & 16384 /* Constructor */) !== 0; + function reportImplementationExpectedError(node) { + if (node.name && ts.nodeIsMissing(node.name)) { + return; + } + var seen = false; + var subsequentNode = ts.forEachChild(node.parent, function (c) { + if (seen) { + return c; + } + else { + seen = c === node; + } + }); + // We may be here because of some extra nodes between overloads that could not be parsed into a valid node. + // In this case the subsequent node is not really consecutive (.pos !== node.end), and we must ignore it here. + if (subsequentNode && subsequentNode.pos === node.end) { + if (subsequentNode.kind === node.kind) { + var errorNode_1 = subsequentNode.name || subsequentNode; + // TODO: GH#17345: These are methods, so handle computed name case. (`Always allowing computed property names is *not* the correct behavior!) + var subsequentName = subsequentNode.name; + if (node.name && subsequentName && + (ts.isComputedPropertyName(node.name) && ts.isComputedPropertyName(subsequentName) || + !ts.isComputedPropertyName(node.name) && !ts.isComputedPropertyName(subsequentName) && ts.getEscapedTextOfIdentifierOrLiteral(node.name) === ts.getEscapedTextOfIdentifierOrLiteral(subsequentName))) { + var reportError = (node.kind === 156 /* MethodDeclaration */ || node.kind === 155 /* MethodSignature */) && + ts.hasModifier(node, 32 /* Static */) !== ts.hasModifier(subsequentNode, 32 /* Static */); + // we can get here in two cases + // 1. mixed static and instance class members + // 2. something with the same name was defined before the set of overloads that prevents them from merging + // here we'll report error only for the first case since for second we should already report error in binder + if (reportError) { + var diagnostic = ts.hasModifier(node, 32 /* Static */) ? ts.Diagnostics.Function_overload_must_be_static : ts.Diagnostics.Function_overload_must_not_be_static; + error(errorNode_1, diagnostic); + } + return; + } + else if (ts.nodeIsPresent(subsequentNode.body)) { + error(errorNode_1, ts.Diagnostics.Function_implementation_name_must_be_0, ts.declarationNameToString(node.name)); + return; + } + } + } + var errorNode = node.name || node; + if (isConstructor) { + error(errorNode, ts.Diagnostics.Constructor_implementation_is_missing); + } + else { + // Report different errors regarding non-consecutive blocks of declarations depending on whether + // the node in question is abstract. + if (ts.hasModifier(node, 128 /* Abstract */)) { + error(errorNode, ts.Diagnostics.All_declarations_of_an_abstract_method_must_be_consecutive); + } + else { + error(errorNode, ts.Diagnostics.Function_implementation_is_missing_or_not_immediately_following_the_declaration); + } + } + } + var duplicateFunctionDeclaration = false; + var multipleConstructorImplementation = false; + for (var _i = 0, declarations_4 = declarations; _i < declarations_4.length; _i++) { + var current = declarations_4[_i]; + var node = current; + var inAmbientContext = node.flags & 4194304 /* Ambient */; + var inAmbientContextOrInterface = node.parent.kind === 241 /* InterfaceDeclaration */ || node.parent.kind === 168 /* TypeLiteral */ || inAmbientContext; + if (inAmbientContextOrInterface) { + // check if declarations are consecutive only if they are non-ambient + // 1. ambient declarations can be interleaved + // i.e. this is legal + // declare function foo(); + // declare function bar(); + // declare function foo(); + // 2. mixing ambient and non-ambient declarations is a separate error that will be reported - do not want to report an extra one + previousDeclaration = undefined; + } + if (node.kind === 239 /* FunctionDeclaration */ || node.kind === 156 /* MethodDeclaration */ || node.kind === 155 /* MethodSignature */ || node.kind === 157 /* Constructor */) { + var currentNodeFlags = getEffectiveDeclarationFlags(node, flagsToCheck); + someNodeFlags |= currentNodeFlags; + allNodeFlags &= currentNodeFlags; + someHaveQuestionToken = someHaveQuestionToken || ts.hasQuestionToken(node); + allHaveQuestionToken = allHaveQuestionToken && ts.hasQuestionToken(node); + if (ts.nodeIsPresent(node.body) && bodyDeclaration) { + if (isConstructor) { + multipleConstructorImplementation = true; + } + else { + duplicateFunctionDeclaration = true; + } + } + else if (previousDeclaration && previousDeclaration.parent === node.parent && previousDeclaration.end !== node.pos) { + reportImplementationExpectedError(previousDeclaration); + } + if (ts.nodeIsPresent(node.body)) { + if (!bodyDeclaration) { + bodyDeclaration = node; + } + } + else { + hasOverloads = true; + } + previousDeclaration = node; + if (!inAmbientContextOrInterface) { + lastSeenNonAmbientDeclaration = node; + } + } + } + if (multipleConstructorImplementation) { + ts.forEach(declarations, function (declaration) { + error(declaration, ts.Diagnostics.Multiple_constructor_implementations_are_not_allowed); + }); + } + if (duplicateFunctionDeclaration) { + ts.forEach(declarations, function (declaration) { + error(ts.getNameOfDeclaration(declaration), ts.Diagnostics.Duplicate_function_implementation); + }); + } + // Abstract methods can't have an implementation -- in particular, they don't need one. + if (lastSeenNonAmbientDeclaration && !lastSeenNonAmbientDeclaration.body && + !ts.hasModifier(lastSeenNonAmbientDeclaration, 128 /* Abstract */) && !lastSeenNonAmbientDeclaration.questionToken) { + reportImplementationExpectedError(lastSeenNonAmbientDeclaration); + } + if (hasOverloads) { + checkFlagAgreementBetweenOverloads(declarations, bodyDeclaration, flagsToCheck, someNodeFlags, allNodeFlags); + checkQuestionTokenAgreementBetweenOverloads(declarations, bodyDeclaration, someHaveQuestionToken, allHaveQuestionToken); + if (bodyDeclaration) { + var signatures = getSignaturesOfSymbol(symbol); + var bodySignature = getSignatureFromDeclaration(bodyDeclaration); + for (var _a = 0, signatures_6 = signatures; _a < signatures_6.length; _a++) { + var signature = signatures_6[_a]; + if (!isImplementationCompatibleWithOverload(bodySignature, signature)) { + error(signature.declaration, ts.Diagnostics.Overload_signature_is_not_compatible_with_function_implementation); + break; + } + } + } + } + } + var DeclarationSpaces; + (function (DeclarationSpaces) { + DeclarationSpaces[DeclarationSpaces["None"] = 0] = "None"; + DeclarationSpaces[DeclarationSpaces["ExportValue"] = 1] = "ExportValue"; + DeclarationSpaces[DeclarationSpaces["ExportType"] = 2] = "ExportType"; + DeclarationSpaces[DeclarationSpaces["ExportNamespace"] = 4] = "ExportNamespace"; + })(DeclarationSpaces || (DeclarationSpaces = {})); + function checkExportsOnMergedDeclarations(node) { + if (!produceDiagnostics) { + return; + } + // if localSymbol is defined on node then node itself is exported - check is required + var symbol = node.localSymbol; + if (!symbol) { + // local symbol is undefined => this declaration is non-exported. + // however symbol might contain other declarations that are exported + symbol = getSymbolOfNode(node); + if (!symbol.exportSymbol) { + // this is a pure local symbol (all declarations are non-exported) - no need to check anything + return; + } + } + // run the check only for the first declaration in the list + if (ts.getDeclarationOfKind(symbol, node.kind) !== node) { + return; + } + var exportedDeclarationSpaces = 0 /* None */; + var nonExportedDeclarationSpaces = 0 /* None */; + var defaultExportedDeclarationSpaces = 0 /* None */; + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var d = _a[_i]; + var declarationSpaces = getDeclarationSpaces(d); + var effectiveDeclarationFlags = getEffectiveDeclarationFlags(d, 1 /* Export */ | 512 /* Default */); + if (effectiveDeclarationFlags & 1 /* Export */) { + if (effectiveDeclarationFlags & 512 /* Default */) { + defaultExportedDeclarationSpaces |= declarationSpaces; + } + else { + exportedDeclarationSpaces |= declarationSpaces; + } + } + else { + nonExportedDeclarationSpaces |= declarationSpaces; + } + } + // Spaces for anything not declared a 'default export'. + var nonDefaultExportedDeclarationSpaces = exportedDeclarationSpaces | nonExportedDeclarationSpaces; + var commonDeclarationSpacesForExportsAndLocals = exportedDeclarationSpaces & nonExportedDeclarationSpaces; + var commonDeclarationSpacesForDefaultAndNonDefault = defaultExportedDeclarationSpaces & nonDefaultExportedDeclarationSpaces; + if (commonDeclarationSpacesForExportsAndLocals || commonDeclarationSpacesForDefaultAndNonDefault) { + // declaration spaces for exported and non-exported declarations intersect + for (var _b = 0, _c = symbol.declarations; _b < _c.length; _b++) { + var d = _c[_b]; + var declarationSpaces = getDeclarationSpaces(d); + var name = ts.getNameOfDeclaration(d); + // Only error on the declarations that contributed to the intersecting spaces. + if (declarationSpaces & commonDeclarationSpacesForDefaultAndNonDefault) { + error(name, ts.Diagnostics.Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead, ts.declarationNameToString(name)); + } + else if (declarationSpaces & commonDeclarationSpacesForExportsAndLocals) { + error(name, ts.Diagnostics.Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local, ts.declarationNameToString(name)); + } + } + } + function getDeclarationSpaces(decl) { + var d = decl; + switch (d.kind) { + case 241 /* InterfaceDeclaration */: + case 242 /* TypeAliasDeclaration */: + // A jsdoc typedef and callback are, by definition, type aliases + case 304 /* JSDocTypedefTag */: + case 297 /* JSDocCallbackTag */: + return 2 /* ExportType */; + case 244 /* ModuleDeclaration */: + return ts.isAmbientModule(d) || ts.getModuleInstanceState(d) !== 0 /* NonInstantiated */ + ? 4 /* ExportNamespace */ | 1 /* ExportValue */ + : 4 /* ExportNamespace */; + case 240 /* ClassDeclaration */: + case 243 /* EnumDeclaration */: + return 2 /* ExportType */ | 1 /* ExportValue */; + case 279 /* SourceFile */: + return 2 /* ExportType */ | 1 /* ExportValue */ | 4 /* ExportNamespace */; + case 254 /* ExportAssignment */: + // Export assigned entity name expressions act as aliases and should fall through, otherwise they export values + if (!ts.isEntityNameExpression(d.expression)) { + return 1 /* ExportValue */; + } + d = d.expression; + /* falls through */ + // The below options all declare an Alias, which is allowed to merge with other values within the importing module + case 248 /* ImportEqualsDeclaration */: + case 251 /* NamespaceImport */: + case 250 /* ImportClause */: + var result_4 = 0 /* None */; + var target = resolveAlias(getSymbolOfNode(d)); + ts.forEach(target.declarations, function (d) { result_4 |= getDeclarationSpaces(d); }); + return result_4; + case 237 /* VariableDeclaration */: + case 186 /* BindingElement */: + case 239 /* FunctionDeclaration */: + case 253 /* ImportSpecifier */: // https://github.com/Microsoft/TypeScript/pull/7591 + return 1 /* ExportValue */; + default: + return ts.Debug.fail(ts.Debug.showSyntaxKind(d)); + } + } + } + function getAwaitedTypeOfPromise(type, errorNode, diagnosticMessage) { + var promisedType = getPromisedTypeOfPromise(type, errorNode); + return promisedType && getAwaitedType(promisedType, errorNode, diagnosticMessage); + } + /** + * Gets the "promised type" of a promise. + * @param type The type of the promise. + * @remarks The "promised type" of a type is the type of the "value" parameter of the "onfulfilled" callback. + */ + function getPromisedTypeOfPromise(promise, errorNode) { + // + // { // promise + // then( // thenFunction + // onfulfilled: ( // onfulfilledParameterType + // value: T // valueParameterType + // ) => any + // ): any; + // } + // + if (isTypeAny(promise)) { + return undefined; + } + var typeAsPromise = promise; + if (typeAsPromise.promisedTypeOfPromise) { + return typeAsPromise.promisedTypeOfPromise; + } + if (isReferenceToType(promise, getGlobalPromiseType(/*reportErrors*/ false))) { + return typeAsPromise.promisedTypeOfPromise = promise.typeArguments[0]; + } + var thenFunction = getTypeOfPropertyOfType(promise, "then"); // TODO: GH#18217 + if (isTypeAny(thenFunction)) { + return undefined; + } + var thenSignatures = thenFunction ? getSignaturesOfType(thenFunction, 0 /* Call */) : ts.emptyArray; + if (thenSignatures.length === 0) { + if (errorNode) { + error(errorNode, ts.Diagnostics.A_promise_must_have_a_then_method); + } + return undefined; + } + var onfulfilledParameterType = getTypeWithFacts(getUnionType(ts.map(thenSignatures, getTypeOfFirstParameterOfSignature)), 2097152 /* NEUndefinedOrNull */); + if (isTypeAny(onfulfilledParameterType)) { + return undefined; + } + var onfulfilledParameterSignatures = getSignaturesOfType(onfulfilledParameterType, 0 /* Call */); + if (onfulfilledParameterSignatures.length === 0) { + if (errorNode) { + error(errorNode, ts.Diagnostics.The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback); + } + return undefined; + } + return typeAsPromise.promisedTypeOfPromise = getUnionType(ts.map(onfulfilledParameterSignatures, getTypeOfFirstParameterOfSignature), 2 /* Subtype */); + } + /** + * Gets the "awaited type" of a type. + * @param type The type to await. + * @remarks The "awaited type" of an expression is its "promised type" if the expression is a + * Promise-like type; otherwise, it is the type of the expression. This is used to reflect + * The runtime behavior of the `await` keyword. + */ + function checkAwaitedType(type, errorNode, diagnosticMessage) { + return getAwaitedType(type, errorNode, diagnosticMessage) || errorType; + } + function getAwaitedType(type, errorNode, diagnosticMessage) { + var typeAsAwaitable = type; + if (typeAsAwaitable.awaitedTypeOfType) { + return typeAsAwaitable.awaitedTypeOfType; + } + if (isTypeAny(type)) { + return typeAsAwaitable.awaitedTypeOfType = type; + } + if (type.flags & 1048576 /* Union */) { + var types = void 0; + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var constituentType = _a[_i]; + types = ts.append(types, getAwaitedType(constituentType, errorNode, diagnosticMessage)); + } + if (!types) { + return undefined; + } + return typeAsAwaitable.awaitedTypeOfType = getUnionType(types); + } + var promisedType = getPromisedTypeOfPromise(type); + if (promisedType) { + if (type.id === promisedType.id || awaitedTypeStack.indexOf(promisedType.id) >= 0) { + // Verify that we don't have a bad actor in the form of a promise whose + // promised type is the same as the promise type, or a mutually recursive + // promise. If so, we return undefined as we cannot guess the shape. If this + // were the actual case in the JavaScript, this Promise would never resolve. + // + // An example of a bad actor with a singly-recursive promise type might + // be: + // + // interface BadPromise { + // then( + // onfulfilled: (value: BadPromise) => any, + // onrejected: (error: any) => any): BadPromise; + // } + // The above interface will pass the PromiseLike check, and return a + // promised type of `BadPromise`. Since this is a self reference, we + // don't want to keep recursing ad infinitum. + // + // An example of a bad actor in the form of a mutually-recursive + // promise type might be: + // + // interface BadPromiseA { + // then( + // onfulfilled: (value: BadPromiseB) => any, + // onrejected: (error: any) => any): BadPromiseB; + // } + // + // interface BadPromiseB { + // then( + // onfulfilled: (value: BadPromiseA) => any, + // onrejected: (error: any) => any): BadPromiseA; + // } + // + if (errorNode) { + error(errorNode, ts.Diagnostics.Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method); + } + return undefined; + } + // Keep track of the type we're about to unwrap to avoid bad recursive promise types. + // See the comments above for more information. + awaitedTypeStack.push(type.id); + var awaitedType = getAwaitedType(promisedType, errorNode, diagnosticMessage); + awaitedTypeStack.pop(); + if (!awaitedType) { + return undefined; + } + return typeAsAwaitable.awaitedTypeOfType = awaitedType; + } + // The type was not a promise, so it could not be unwrapped any further. + // As long as the type does not have a callable "then" property, it is + // safe to return the type; otherwise, an error will be reported in + // the call to getNonThenableType and we will return undefined. + // + // An example of a non-promise "thenable" might be: + // + // await { then(): void {} } + // + // The "thenable" does not match the minimal definition for a promise. When + // a Promise/A+-compatible or ES6 promise tries to adopt this value, the promise + // will never settle. We treat this as an error to help flag an early indicator + // of a runtime problem. If the user wants to return this value from an async + // function, they would need to wrap it in some other value. If they want it to + // be treated as a promise, they can cast to . + var thenFunction = getTypeOfPropertyOfType(type, "then"); + if (thenFunction && getSignaturesOfType(thenFunction, 0 /* Call */).length > 0) { + if (errorNode) { + if (!diagnosticMessage) + return ts.Debug.fail(); + error(errorNode, diagnosticMessage); + } + return undefined; + } + return typeAsAwaitable.awaitedTypeOfType = type; + } + /** + * Checks the return type of an async function to ensure it is a compatible + * Promise implementation. + * + * This checks that an async function has a valid Promise-compatible return type. + * An async function has a valid Promise-compatible return type if the resolved value + * of the return type has a construct signature that takes in an `initializer` function + * that in turn supplies a `resolve` function as one of its arguments and results in an + * object with a callable `then` signature. + * + * @param node The signature to check + */ + function checkAsyncFunctionReturnType(node, returnTypeNode) { + // As part of our emit for an async function, we will need to emit the entity name of + // the return type annotation as an expression. To meet the necessary runtime semantics + // for __awaiter, we must also check that the type of the declaration (e.g. the static + // side or "constructor" of the promise type) is compatible `PromiseConstructorLike`. + // + // An example might be (from lib.es6.d.ts): + // + // interface Promise { ... } + // interface PromiseConstructor { + // new (...): Promise; + // } + // declare var Promise: PromiseConstructor; + // + // When an async function declares a return type annotation of `Promise`, we + // need to get the type of the `Promise` variable declaration above, which would + // be `PromiseConstructor`. + // + // The same case applies to a class: + // + // declare class Promise { + // constructor(...); + // then(...): Promise; + // } + // + var returnType = getTypeFromTypeNode(returnTypeNode); + if (languageVersion >= 2 /* ES2015 */) { + if (returnType === errorType) { + return; + } + var globalPromiseType = getGlobalPromiseType(/*reportErrors*/ true); + if (globalPromiseType !== emptyGenericType && !isReferenceToType(returnType, globalPromiseType)) { + // The promise type was not a valid type reference to the global promise type, so we + // report an error and return the unknown type. + error(returnTypeNode, ts.Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type); + return; + } + } + else { + // Always mark the type node as referenced if it points to a value + markTypeNodeAsReferenced(returnTypeNode); + if (returnType === errorType) { + return; + } + var promiseConstructorName = ts.getEntityNameFromTypeNode(returnTypeNode); + if (promiseConstructorName === undefined) { + error(returnTypeNode, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, typeToString(returnType)); + return; + } + var promiseConstructorSymbol = resolveEntityName(promiseConstructorName, 67220415 /* Value */, /*ignoreErrors*/ true); + var promiseConstructorType = promiseConstructorSymbol ? getTypeOfSymbol(promiseConstructorSymbol) : errorType; + if (promiseConstructorType === errorType) { + if (promiseConstructorName.kind === 72 /* Identifier */ && promiseConstructorName.escapedText === "Promise" && getTargetType(returnType) === getGlobalPromiseType(/*reportErrors*/ false)) { + error(returnTypeNode, ts.Diagnostics.An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option); + } + else { + error(returnTypeNode, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, ts.entityNameToString(promiseConstructorName)); + } + return; + } + var globalPromiseConstructorLikeType = getGlobalPromiseConstructorLikeType(/*reportErrors*/ true); + if (globalPromiseConstructorLikeType === emptyObjectType) { + // If we couldn't resolve the global PromiseConstructorLike type we cannot verify + // compatibility with __awaiter. + error(returnTypeNode, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, ts.entityNameToString(promiseConstructorName)); + return; + } + if (!checkTypeAssignableTo(promiseConstructorType, globalPromiseConstructorLikeType, returnTypeNode, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value)) { + return; + } + // Verify there is no local declaration that could collide with the promise constructor. + var rootName = promiseConstructorName && getFirstIdentifier(promiseConstructorName); + var collidingSymbol = getSymbol(node.locals, rootName.escapedText, 67220415 /* Value */); + if (collidingSymbol) { + error(collidingSymbol.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, ts.idText(rootName), ts.entityNameToString(promiseConstructorName)); + return; + } + } + checkAwaitedType(returnType, node, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); + } + /** Check a decorator */ + function checkDecorator(node) { + var signature = getResolvedSignature(node); + var returnType = getReturnTypeOfSignature(signature); + if (returnType.flags & 1 /* Any */) { + return; + } + var expectedReturnType; + var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); + var errorInfo; + switch (node.parent.kind) { + case 240 /* ClassDeclaration */: + var classSymbol = getSymbolOfNode(node.parent); + var classConstructorType = getTypeOfSymbol(classSymbol); + expectedReturnType = getUnionType([classConstructorType, voidType]); + break; + case 151 /* Parameter */: + expectedReturnType = voidType; + errorInfo = ts.chainDiagnosticMessages( + /*details*/ undefined, ts.Diagnostics.The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any); + break; + case 154 /* PropertyDeclaration */: + expectedReturnType = voidType; + errorInfo = ts.chainDiagnosticMessages( + /*details*/ undefined, ts.Diagnostics.The_return_type_of_a_property_decorator_function_must_be_either_void_or_any); + break; + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + var methodType = getTypeOfNode(node.parent); + var descriptorType = createTypedPropertyDescriptorType(methodType); + expectedReturnType = getUnionType([descriptorType, voidType]); + break; + default: + return ts.Debug.fail(); + } + checkTypeAssignableTo(returnType, expectedReturnType, node, headMessage, function () { return errorInfo; }); + } + /** + * If a TypeNode can be resolved to a value symbol imported from an external module, it is + * marked as referenced to prevent import elision. + */ + function markTypeNodeAsReferenced(node) { + markEntityNameOrEntityExpressionAsReference(node && ts.getEntityNameFromTypeNode(node)); + } + function markEntityNameOrEntityExpressionAsReference(typeName) { + if (!typeName) + return; + var rootName = getFirstIdentifier(typeName); + var meaning = (typeName.kind === 72 /* Identifier */ ? 67897832 /* Type */ : 1920 /* Namespace */) | 2097152 /* Alias */; + var rootSymbol = resolveName(rootName, rootName.escapedText, meaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isRefernce*/ true); + if (rootSymbol + && rootSymbol.flags & 2097152 /* Alias */ + && symbolIsValue(rootSymbol) + && !isConstEnumOrConstEnumOnlyModule(resolveAlias(rootSymbol))) { + markAliasSymbolAsReferenced(rootSymbol); + } + } + /** + * This function marks the type used for metadata decorator as referenced if it is import + * from external module. + * This is different from markTypeNodeAsReferenced because it tries to simplify type nodes in + * union and intersection type + * @param node + */ + function markDecoratorMedataDataTypeNodeAsReferenced(node) { + var entityName = getEntityNameForDecoratorMetadata(node); + if (entityName && ts.isEntityName(entityName)) { + markEntityNameOrEntityExpressionAsReference(entityName); + } + } + function getEntityNameForDecoratorMetadata(node) { + if (node) { + switch (node.kind) { + case 174 /* IntersectionType */: + case 173 /* UnionType */: + return getEntityNameForDecoratorMetadataFromTypeList(node.types); + case 175 /* ConditionalType */: + return getEntityNameForDecoratorMetadataFromTypeList([node.trueType, node.falseType]); + case 177 /* ParenthesizedType */: + return getEntityNameForDecoratorMetadata(node.type); + case 164 /* TypeReference */: + return node.typeName; + } + } + } + function getEntityNameForDecoratorMetadataFromTypeList(types) { + var commonEntityName; + for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { + var typeNode = types_16[_i]; + while (typeNode.kind === 177 /* ParenthesizedType */) { + typeNode = typeNode.type; // Skip parens if need be + } + if (typeNode.kind === 132 /* NeverKeyword */) { + continue; // Always elide `never` from the union/intersection if possible + } + if (!strictNullChecks && (typeNode.kind === 96 /* NullKeyword */ || typeNode.kind === 141 /* UndefinedKeyword */)) { + continue; // Elide null and undefined from unions for metadata, just like what we did prior to the implementation of strict null checks + } + var individualEntityName = getEntityNameForDecoratorMetadata(typeNode); + if (!individualEntityName) { + // Individual is something like string number + // So it would be serialized to either that type or object + // Safe to return here + return undefined; + } + if (commonEntityName) { + // Note this is in sync with the transformation that happens for type node. + // Keep this in sync with serializeUnionOrIntersectionType + // Verify if they refer to same entity and is identifier + // return undefined if they dont match because we would emit object + if (!ts.isIdentifier(commonEntityName) || + !ts.isIdentifier(individualEntityName) || + commonEntityName.escapedText !== individualEntityName.escapedText) { + return undefined; + } + } + else { + commonEntityName = individualEntityName; + } + } + return commonEntityName; + } + function getParameterTypeNodeForDecoratorCheck(node) { + var typeNode = ts.getEffectiveTypeAnnotationNode(node); + return ts.isRestParameter(node) ? ts.getRestParameterElementType(typeNode) : typeNode; + } + /** Check the decorators of a node */ + function checkDecorators(node) { + if (!node.decorators) { + return; + } + // skip this check for nodes that cannot have decorators. These should have already had an error reported by + // checkGrammarDecorators. + if (!ts.nodeCanBeDecorated(node, node.parent, node.parent.parent)) { + return; + } + if (!compilerOptions.experimentalDecorators) { + error(node, ts.Diagnostics.Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_to_remove_this_warning); + } + var firstDecorator = node.decorators[0]; + checkExternalEmitHelpers(firstDecorator, 8 /* Decorate */); + if (node.kind === 151 /* Parameter */) { + checkExternalEmitHelpers(firstDecorator, 32 /* Param */); + } + if (compilerOptions.emitDecoratorMetadata) { + checkExternalEmitHelpers(firstDecorator, 16 /* Metadata */); + // we only need to perform these checks if we are emitting serialized type metadata for the target of a decorator. + switch (node.kind) { + case 240 /* ClassDeclaration */: + var constructor = ts.getFirstConstructorWithBody(node); + if (constructor) { + for (var _i = 0, _a = constructor.parameters; _i < _a.length; _i++) { + var parameter = _a[_i]; + markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); + } + } + break; + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + var otherKind = node.kind === 158 /* GetAccessor */ ? 159 /* SetAccessor */ : 158 /* GetAccessor */; + var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(node), otherKind); + markDecoratorMedataDataTypeNodeAsReferenced(getAnnotatedAccessorTypeNode(node) || otherAccessor && getAnnotatedAccessorTypeNode(otherAccessor)); + break; + case 156 /* MethodDeclaration */: + for (var _b = 0, _c = node.parameters; _b < _c.length; _b++) { + var parameter = _c[_b]; + markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); + } + markDecoratorMedataDataTypeNodeAsReferenced(ts.getEffectiveReturnTypeNode(node)); + break; + case 154 /* PropertyDeclaration */: + markDecoratorMedataDataTypeNodeAsReferenced(ts.getEffectiveTypeAnnotationNode(node)); + break; + case 151 /* Parameter */: + markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(node)); + var containingSignature = node.parent; + for (var _d = 0, _e = containingSignature.parameters; _d < _e.length; _d++) { + var parameter = _e[_d]; + markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); + } + break; + } + } + ts.forEach(node.decorators, checkDecorator); + } + function checkFunctionDeclaration(node) { + if (produceDiagnostics) { + checkFunctionOrMethodDeclaration(node); + checkGrammarForGenerator(node); + checkCollisionWithRequireExportsInGeneratedCode(node, node.name); + checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); + } + } + function checkJSDocTypeAliasTag(node) { + if (!node.typeExpression) { + // If the node had `@property` tags, `typeExpression` would have been set to the first property tag. + error(node.name, ts.Diagnostics.JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags); + } + if (node.name) { + checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_alias_name_cannot_be_0); + } + checkSourceElement(node.typeExpression); + } + function checkJSDocTemplateTag(node) { + checkSourceElement(node.constraint); + for (var _i = 0, _a = node.typeParameters; _i < _a.length; _i++) { + var tp = _a[_i]; + checkSourceElement(tp); + } + } + function checkJSDocTypeTag(node) { + checkSourceElement(node.typeExpression); + } + function checkJSDocParameterTag(node) { + checkSourceElement(node.typeExpression); + if (!ts.getParameterSymbolFromJSDoc(node)) { + var decl = ts.getHostSignatureFromJSDoc(node); + // don't issue an error for invalid hosts -- just functions -- + // and give a better error message when the host function mentions `arguments` + // but the tag doesn't have an array type + if (decl) { + var i = ts.getJSDocTags(decl).filter(ts.isJSDocParameterTag).indexOf(node); + if (i > -1 && i < decl.parameters.length && ts.isBindingPattern(decl.parameters[i].name)) { + return; + } + if (!containsArgumentsReference(decl)) { + error(node.name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name, ts.idText(node.name.kind === 148 /* QualifiedName */ ? node.name.right : node.name)); + } + else if (ts.findLast(ts.getJSDocTags(decl), ts.isJSDocParameterTag) === node && + node.typeExpression && node.typeExpression.type && + !isArrayType(getTypeFromTypeNode(node.typeExpression.type))) { + error(node.name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_had_an_array_type, ts.idText(node.name.kind === 148 /* QualifiedName */ ? node.name.right : node.name)); + } + } + } + } + function checkJSDocFunctionType(node) { + if (produceDiagnostics && !node.type && !ts.isJSDocConstructSignature(node)) { + reportImplicitAny(node, anyType); + } + checkSignatureDeclaration(node); + } + function checkJSDocAugmentsTag(node) { + var classLike = ts.getJSDocHost(node); + if (!ts.isClassDeclaration(classLike) && !ts.isClassExpression(classLike)) { + error(classLike, ts.Diagnostics.JSDoc_0_is_not_attached_to_a_class, ts.idText(node.tagName)); + return; + } + var augmentsTags = ts.getJSDocTags(classLike).filter(ts.isJSDocAugmentsTag); + ts.Debug.assert(augmentsTags.length > 0); + if (augmentsTags.length > 1) { + error(augmentsTags[1], ts.Diagnostics.Class_declarations_cannot_have_more_than_one_augments_or_extends_tag); + } + var name = getIdentifierFromEntityNameExpression(node.class.expression); + var extend = ts.getClassExtendsHeritageElement(classLike); + if (extend) { + var className = getIdentifierFromEntityNameExpression(extend.expression); + if (className && name.escapedText !== className.escapedText) { + error(name, ts.Diagnostics.JSDoc_0_1_does_not_match_the_extends_2_clause, ts.idText(node.tagName), ts.idText(name), ts.idText(className)); + } + } + } + function getIdentifierFromEntityNameExpression(node) { + switch (node.kind) { + case 72 /* Identifier */: + return node; + case 189 /* PropertyAccessExpression */: + return node.name; + default: + return undefined; + } + } + function checkFunctionOrMethodDeclaration(node) { + checkDecorators(node); + checkSignatureDeclaration(node); + var functionFlags = ts.getFunctionFlags(node); + // Do not use hasDynamicName here, because that returns false for well known symbols. + // We want to perform checkComputedPropertyName for all computed properties, including + // well known symbols. + if (node.name && node.name.kind === 149 /* ComputedPropertyName */) { + // This check will account for methods in class/interface declarations, + // as well as accessors in classes/object literals + checkComputedPropertyName(node.name); + } + if (!hasNonBindableDynamicName(node)) { + // first we want to check the local symbol that contain this declaration + // - if node.localSymbol !== undefined - this is current declaration is exported and localSymbol points to the local symbol + // - if node.localSymbol === undefined - this node is non-exported so we can just pick the result of getSymbolOfNode + var symbol = getSymbolOfNode(node); + var localSymbol = node.localSymbol || symbol; + // Since the javascript won't do semantic analysis like typescript, + // if the javascript file comes before the typescript file and both contain same name functions, + // checkFunctionOrConstructorSymbol wouldn't be called if we didnt ignore javascript function. + var firstDeclaration = ts.find(localSymbol.declarations, + // Get first non javascript function declaration + function (declaration) { return declaration.kind === node.kind && !(declaration.flags & 65536 /* JavaScriptFile */); }); + // Only type check the symbol once + if (node === firstDeclaration) { + checkFunctionOrConstructorSymbol(localSymbol); + } + if (symbol.parent) { + // run check once for the first declaration + if (ts.getDeclarationOfKind(symbol, node.kind) === node) { + // run check on export symbol to check that modifiers agree across all exported declarations + checkFunctionOrConstructorSymbol(symbol); + } + } + } + var body = node.kind === 155 /* MethodSignature */ ? undefined : node.body; + checkSourceElement(body); + if ((functionFlags & 1 /* Generator */) === 0) { // Async function or normal function + var returnOrPromisedType = getReturnOrPromisedType(node, functionFlags); + checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnOrPromisedType); + } + if (produceDiagnostics && !ts.getEffectiveReturnTypeNode(node)) { + // Report an implicit any error if there is no body, no explicit return type, and node is not a private method + // in an ambient context + if (ts.nodeIsMissing(body) && !isPrivateWithinAmbient(node)) { + reportImplicitAny(node, anyType); + } + if (functionFlags & 1 /* Generator */ && ts.nodeIsPresent(body)) { + // A generator with a body and no type annotation can still cause errors. It can error if the + // yielded values have no common supertype, or it can give an implicit any error if it has no + // yielded values. The only way to trigger these errors is to try checking its return type. + getReturnTypeOfSignature(getSignatureFromDeclaration(node)); + } + } + // A js function declaration can have a @type tag instead of a return type node, but that type must have a call signature + if (ts.isInJSFile(node)) { + var typeTag = ts.getJSDocTypeTag(node); + if (typeTag && typeTag.typeExpression && !getContextualCallSignature(getTypeFromTypeNode(typeTag.typeExpression), node)) { + error(typeTag, ts.Diagnostics.The_type_of_a_function_declaration_must_match_the_function_s_signature); + } + } + } + function registerForUnusedIdentifiersCheck(node) { + // May be in a call such as getTypeOfNode that happened to call this. But potentiallyUnusedIdentifiers is only defined in the scope of `checkSourceFile`. + if (produceDiagnostics && !(node.flags & 4194304 /* Ambient */)) { + var sourceFile = ts.getSourceFileOfNode(node); + var potentiallyUnusedIdentifiers = allPotentiallyUnusedIdentifiers.get(sourceFile.path); + if (!potentiallyUnusedIdentifiers) { + potentiallyUnusedIdentifiers = []; + allPotentiallyUnusedIdentifiers.set(sourceFile.path, potentiallyUnusedIdentifiers); + } + // TODO: GH#22580 + // Debug.assert(addToSeen(seenPotentiallyUnusedIdentifiers, getNodeId(node)), "Adding potentially-unused identifier twice"); + potentiallyUnusedIdentifiers.push(node); + } + } + function checkUnusedIdentifiers(potentiallyUnusedIdentifiers, addDiagnostic) { + for (var _i = 0, potentiallyUnusedIdentifiers_1 = potentiallyUnusedIdentifiers; _i < potentiallyUnusedIdentifiers_1.length; _i++) { + var node = potentiallyUnusedIdentifiers_1[_i]; + switch (node.kind) { + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + checkUnusedClassMembers(node, addDiagnostic); + checkUnusedTypeParameters(node, addDiagnostic); + break; + case 279 /* SourceFile */: + case 244 /* ModuleDeclaration */: + case 218 /* Block */: + case 246 /* CaseBlock */: + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + checkUnusedLocalsAndParameters(node, addDiagnostic); + break; + case 157 /* Constructor */: + case 196 /* FunctionExpression */: + case 239 /* FunctionDeclaration */: + case 197 /* ArrowFunction */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + if (node.body) { // Don't report unused parameters in overloads + checkUnusedLocalsAndParameters(node, addDiagnostic); + } + checkUnusedTypeParameters(node, addDiagnostic); + break; + case 155 /* MethodSignature */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + case 242 /* TypeAliasDeclaration */: + case 241 /* InterfaceDeclaration */: + checkUnusedTypeParameters(node, addDiagnostic); + break; + case 176 /* InferType */: + checkUnusedInferTypeParameter(node, addDiagnostic); + break; + default: + ts.Debug.assertNever(node, "Node should not have been registered for unused identifiers check"); + } + } + } + function errorUnusedLocal(declaration, name, addDiagnostic) { + var node = ts.getNameOfDeclaration(declaration) || declaration; + var message = isTypeDeclaration(declaration) ? ts.Diagnostics._0_is_declared_but_never_used : ts.Diagnostics._0_is_declared_but_its_value_is_never_read; + addDiagnostic(declaration, 0 /* Local */, ts.createDiagnosticForNode(node, message, name)); + } + function isIdentifierThatStartsWithUnderscore(node) { + return ts.isIdentifier(node) && ts.idText(node).charCodeAt(0) === 95 /* _ */; + } + function checkUnusedClassMembers(node, addDiagnostic) { + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + switch (member.kind) { + case 156 /* MethodDeclaration */: + case 154 /* PropertyDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + if (member.kind === 159 /* SetAccessor */ && member.symbol.flags & 32768 /* GetAccessor */) { + // Already would have reported an error on the getter. + break; + } + var symbol = getSymbolOfNode(member); + if (!symbol.isReferenced && ts.hasModifier(member, 8 /* Private */)) { + addDiagnostic(member, 0 /* Local */, ts.createDiagnosticForNode(member.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, symbolToString(symbol))); + } + break; + case 157 /* Constructor */: + for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { + var parameter = _c[_b]; + if (!parameter.symbol.isReferenced && ts.hasModifier(parameter, 8 /* Private */)) { + addDiagnostic(parameter, 0 /* Local */, ts.createDiagnosticForNode(parameter.name, ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read, ts.symbolName(parameter.symbol))); + } + } + break; + case 162 /* IndexSignature */: + case 217 /* SemicolonClassElement */: + // Can't be private + break; + default: + ts.Debug.fail(); + } + } + } + function checkUnusedInferTypeParameter(node, addDiagnostic) { + var typeParameter = node.typeParameter; + if (isTypeParameterUnused(typeParameter)) { + addDiagnostic(node, 1 /* Parameter */, ts.createDiagnosticForNode(node, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(typeParameter.name))); + } + } + function checkUnusedTypeParameters(node, addDiagnostic) { + // Only report errors on the last declaration for the type parameter container; + // this ensures that all uses have been accounted for. + if (ts.last(getSymbolOfNode(node).declarations) !== node) + return; + var typeParameters = ts.getEffectiveTypeParameterDeclarations(node); + var seenParentsWithEveryUnused = new ts.NodeSet(); + for (var _i = 0, typeParameters_2 = typeParameters; _i < typeParameters_2.length; _i++) { + var typeParameter = typeParameters_2[_i]; + if (!isTypeParameterUnused(typeParameter)) + continue; + var name = ts.idText(typeParameter.name); + var parent = typeParameter.parent; + if (parent.kind !== 176 /* InferType */ && parent.typeParameters.every(isTypeParameterUnused)) { + if (seenParentsWithEveryUnused.tryAdd(parent)) { + var range = ts.isJSDocTemplateTag(parent) + // Whole @template tag + ? ts.rangeOfNode(parent) + // Include the `<>` in the error message + : ts.rangeOfTypeParameters(parent.typeParameters); + var only = typeParameters.length === 1; + var message = only ? ts.Diagnostics._0_is_declared_but_its_value_is_never_read : ts.Diagnostics.All_type_parameters_are_unused; + var arg0 = only ? name : undefined; + addDiagnostic(typeParameter, 1 /* Parameter */, ts.createFileDiagnostic(ts.getSourceFileOfNode(parent), range.pos, range.end - range.pos, message, arg0)); + } + } + else { + addDiagnostic(typeParameter, 1 /* Parameter */, ts.createDiagnosticForNode(typeParameter, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, name)); + } + } + } + function isTypeParameterUnused(typeParameter) { + return !(getMergedSymbol(typeParameter.symbol).isReferenced & 262144 /* TypeParameter */) && !isIdentifierThatStartsWithUnderscore(typeParameter.name); + } + function addToGroup(map, key, value, getKey) { + var keyString = String(getKey(key)); + var group = map.get(keyString); + if (group) { + group[1].push(value); + } + else { + map.set(keyString, [key, [value]]); + } + } + function tryGetRootParameterDeclaration(node) { + return ts.tryCast(ts.getRootDeclaration(node), ts.isParameter); + } + function checkUnusedLocalsAndParameters(nodeWithLocals, addDiagnostic) { + if (nodeWithLocals.flags & 4194304 /* Ambient */) + return; + // Ideally we could use the ImportClause directly as a key, but must wait until we have full ES6 maps. So must store key along with value. + var unusedImports = ts.createMap(); + var unusedDestructures = ts.createMap(); + var unusedVariables = ts.createMap(); + nodeWithLocals.locals.forEach(function (local) { + // If it's purely a type parameter, ignore, will be checked in `checkUnusedTypeParameters`. + // If it's a type parameter merged with a parameter, check if the parameter-side is used. + if (local.flags & 262144 /* TypeParameter */ ? !(local.flags & 3 /* Variable */ && !(local.isReferenced & 3 /* Variable */)) : local.isReferenced || local.exportSymbol) { + return; + } + for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (ts.isAmbientModule(declaration) || + (ts.isVariableDeclaration(declaration) && ts.isForInOrOfStatement(declaration.parent.parent) || isImportedDeclaration(declaration)) && isIdentifierThatStartsWithUnderscore(declaration.name)) { + continue; + } + if (isImportedDeclaration(declaration)) { + addToGroup(unusedImports, importClauseFromImported(declaration), declaration, getNodeId); + } + else if (ts.isBindingElement(declaration) && ts.isObjectBindingPattern(declaration.parent)) { + // In `{ a, ...b }, `a` is considered used since it removes a property from `b`. `b` may still be unused though. + var lastElement = ts.last(declaration.parent.elements); + if (declaration === lastElement || !ts.last(declaration.parent.elements).dotDotDotToken) { + addToGroup(unusedDestructures, declaration.parent, declaration, getNodeId); + } + } + else if (ts.isVariableDeclaration(declaration)) { + addToGroup(unusedVariables, declaration.parent, declaration, getNodeId); + } + else { + var parameter = local.valueDeclaration && tryGetRootParameterDeclaration(local.valueDeclaration); + var name = local.valueDeclaration && ts.getNameOfDeclaration(local.valueDeclaration); + if (parameter && name) { + if (!ts.isParameterPropertyDeclaration(parameter) && !ts.parameterIsThisKeyword(parameter) && !isIdentifierThatStartsWithUnderscore(name)) { + addDiagnostic(parameter, 1 /* Parameter */, ts.createDiagnosticForNode(name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.symbolName(local))); + } + } + else { + errorUnusedLocal(declaration, ts.symbolName(local), addDiagnostic); + } + } + } + }); + unusedImports.forEach(function (_a) { + var importClause = _a[0], unuseds = _a[1]; + var importDecl = importClause.parent; + var nDeclarations = (importClause.name ? 1 : 0) + + (importClause.namedBindings ? + (importClause.namedBindings.kind === 251 /* NamespaceImport */ ? 1 : importClause.namedBindings.elements.length) + : 0); + if (nDeclarations === unuseds.length) { + addDiagnostic(importDecl, 0 /* Local */, unuseds.length === 1 + ? ts.createDiagnosticForNode(importDecl, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(ts.first(unuseds).name)) + : ts.createDiagnosticForNode(importDecl, ts.Diagnostics.All_imports_in_import_declaration_are_unused)); + } + else { + for (var _i = 0, unuseds_1 = unuseds; _i < unuseds_1.length; _i++) { + var unused = unuseds_1[_i]; + errorUnusedLocal(unused, ts.idText(unused.name), addDiagnostic); + } + } + }); + unusedDestructures.forEach(function (_a) { + var bindingPattern = _a[0], bindingElements = _a[1]; + var kind = tryGetRootParameterDeclaration(bindingPattern.parent) ? 1 /* Parameter */ : 0 /* Local */; + if (bindingPattern.elements.length === bindingElements.length) { + if (bindingElements.length === 1 && bindingPattern.parent.kind === 237 /* VariableDeclaration */ && bindingPattern.parent.parent.kind === 238 /* VariableDeclarationList */) { + addToGroup(unusedVariables, bindingPattern.parent.parent, bindingPattern.parent, getNodeId); + } + else { + addDiagnostic(bindingPattern, kind, bindingElements.length === 1 + ? ts.createDiagnosticForNode(bindingPattern, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(ts.first(bindingElements).name)) + : ts.createDiagnosticForNode(bindingPattern, ts.Diagnostics.All_destructured_elements_are_unused)); + } + } + else { + for (var _i = 0, bindingElements_1 = bindingElements; _i < bindingElements_1.length; _i++) { + var e = bindingElements_1[_i]; + addDiagnostic(e, kind, ts.createDiagnosticForNode(e, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(e.name))); + } + } + }); + unusedVariables.forEach(function (_a) { + var declarationList = _a[0], declarations = _a[1]; + if (declarationList.declarations.length === declarations.length) { + addDiagnostic(declarationList, 0 /* Local */, declarations.length === 1 + ? ts.createDiagnosticForNode(ts.first(declarations).name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(ts.first(declarations).name)) + : ts.createDiagnosticForNode(declarationList.parent.kind === 219 /* VariableStatement */ ? declarationList.parent : declarationList, ts.Diagnostics.All_variables_are_unused)); + } + else { + for (var _i = 0, declarations_5 = declarations; _i < declarations_5.length; _i++) { + var decl = declarations_5[_i]; + addDiagnostic(decl, 0 /* Local */, ts.createDiagnosticForNode(decl, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(decl.name))); + } + } + }); + } + function bindingNameText(name) { + switch (name.kind) { + case 72 /* Identifier */: + return ts.idText(name); + case 185 /* ArrayBindingPattern */: + case 184 /* ObjectBindingPattern */: + return bindingNameText(ts.cast(ts.first(name.elements), ts.isBindingElement).name); + default: + return ts.Debug.assertNever(name); + } + } + function isImportedDeclaration(node) { + return node.kind === 250 /* ImportClause */ || node.kind === 253 /* ImportSpecifier */ || node.kind === 251 /* NamespaceImport */; + } + function importClauseFromImported(decl) { + return decl.kind === 250 /* ImportClause */ ? decl : decl.kind === 251 /* NamespaceImport */ ? decl.parent : decl.parent.parent; + } + function checkBlock(node) { + // Grammar checking for SyntaxKind.Block + if (node.kind === 218 /* Block */) { + checkGrammarStatementInAmbientContext(node); + } + if (ts.isFunctionOrModuleBlock(node)) { + var saveFlowAnalysisDisabled = flowAnalysisDisabled; + ts.forEach(node.statements, checkSourceElement); + flowAnalysisDisabled = saveFlowAnalysisDisabled; + } + else { + ts.forEach(node.statements, checkSourceElement); + } + if (node.locals) { + registerForUnusedIdentifiersCheck(node); + } + } + function checkCollisionWithArgumentsInGeneratedCode(node) { + // no rest parameters \ declaration context \ overload - no codegen impact + if (languageVersion >= 2 /* ES2015 */ || compilerOptions.noEmit || !ts.hasRestParameter(node) || node.flags & 4194304 /* Ambient */ || ts.nodeIsMissing(node.body)) { + return; + } + ts.forEach(node.parameters, function (p) { + if (p.name && !ts.isBindingPattern(p.name) && p.name.escapedText === argumentsSymbol.escapedName) { + error(p, ts.Diagnostics.Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters); + } + }); + } + function needCollisionCheckForIdentifier(node, identifier, name) { + if (!(identifier && identifier.escapedText === name)) { + return false; + } + if (node.kind === 154 /* PropertyDeclaration */ || + node.kind === 153 /* PropertySignature */ || + node.kind === 156 /* MethodDeclaration */ || + node.kind === 155 /* MethodSignature */ || + node.kind === 158 /* GetAccessor */ || + node.kind === 159 /* SetAccessor */) { + // it is ok to have member named '_super' or '_this' - member access is always qualified + return false; + } + if (node.flags & 4194304 /* Ambient */) { + // ambient context - no codegen impact + return false; + } + var root = ts.getRootDeclaration(node); + if (root.kind === 151 /* Parameter */ && ts.nodeIsMissing(root.parent.body)) { + // just an overload - no codegen impact + return false; + } + return true; + } + // this function will run after checking the source file so 'CaptureThis' is correct for all nodes + function checkIfThisIsCapturedInEnclosingScope(node) { + ts.findAncestor(node, function (current) { + if (getNodeCheckFlags(current) & 4 /* CaptureThis */) { + var isDeclaration_1 = node.kind !== 72 /* Identifier */; + if (isDeclaration_1) { + error(ts.getNameOfDeclaration(node), ts.Diagnostics.Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference); + } + else { + error(node, ts.Diagnostics.Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference); + } + return true; + } + return false; + }); + } + function checkIfNewTargetIsCapturedInEnclosingScope(node) { + ts.findAncestor(node, function (current) { + if (getNodeCheckFlags(current) & 8 /* CaptureNewTarget */) { + var isDeclaration_2 = node.kind !== 72 /* Identifier */; + if (isDeclaration_2) { + error(ts.getNameOfDeclaration(node), ts.Diagnostics.Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference); + } + else { + error(node, ts.Diagnostics.Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta_property_reference); + } + return true; + } + return false; + }); + } + function checkCollisionWithRequireExportsInGeneratedCode(node, name) { + // No need to check for require or exports for ES6 modules and later + if (moduleKind >= ts.ModuleKind.ES2015 || compilerOptions.noEmit) { + return; + } + if (!needCollisionCheckForIdentifier(node, name, "require") && !needCollisionCheckForIdentifier(node, name, "exports")) { + return; + } + // Uninstantiated modules shouldnt do this check + if (ts.isModuleDeclaration(node) && ts.getModuleInstanceState(node) !== 1 /* Instantiated */) { + return; + } + // In case of variable declaration, node.parent is variable statement so look at the variable statement's parent + var parent = getDeclarationContainer(node); + if (parent.kind === 279 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent)) { + // If the declaration happens to be in external module, report error that require and exports are reserved keywords + error(name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module, ts.declarationNameToString(name), ts.declarationNameToString(name)); + } + } + function checkCollisionWithGlobalPromiseInGeneratedCode(node, name) { + if (languageVersion >= 4 /* ES2017 */ || compilerOptions.noEmit || !needCollisionCheckForIdentifier(node, name, "Promise")) { + return; + } + // Uninstantiated modules shouldnt do this check + if (ts.isModuleDeclaration(node) && ts.getModuleInstanceState(node) !== 1 /* Instantiated */) { + return; + } + // In case of variable declaration, node.parent is variable statement so look at the variable statement's parent + var parent = getDeclarationContainer(node); + if (parent.kind === 279 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent) && parent.flags & 1024 /* HasAsyncFunctions */) { + // If the declaration happens to be in external module, report error that Promise is a reserved identifier. + error(name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_functions, ts.declarationNameToString(name), ts.declarationNameToString(name)); + } + } + function checkVarDeclaredNamesNotShadowed(node) { + // - ScriptBody : StatementList + // It is a Syntax Error if any element of the LexicallyDeclaredNames of StatementList + // also occurs in the VarDeclaredNames of StatementList. + // - Block : { StatementList } + // It is a Syntax Error if any element of the LexicallyDeclaredNames of StatementList + // also occurs in the VarDeclaredNames of StatementList. + // Variable declarations are hoisted to the top of their function scope. They can shadow + // block scoped declarations, which bind tighter. this will not be flagged as duplicate definition + // by the binder as the declaration scope is different. + // A non-initialized declaration is a no-op as the block declaration will resolve before the var + // declaration. the problem is if the declaration has an initializer. this will act as a write to the + // block declared value. this is fine for let, but not const. + // Only consider declarations with initializers, uninitialized const declarations will not + // step on a let/const variable. + // Do not consider const and const declarations, as duplicate block-scoped declarations + // are handled by the binder. + // We are only looking for const declarations that step on let\const declarations from a + // different scope. e.g.: + // { + // const x = 0; // localDeclarationSymbol obtained after name resolution will correspond to this declaration + // const x = 0; // symbol for this declaration will be 'symbol' + // } + // skip block-scoped variables and parameters + if ((ts.getCombinedNodeFlags(node) & 3 /* BlockScoped */) !== 0 || ts.isParameterDeclaration(node)) { + return; + } + // skip variable declarations that don't have initializers + // NOTE: in ES6 spec initializer is required in variable declarations where name is binding pattern + // so we'll always treat binding elements as initialized + if (node.kind === 237 /* VariableDeclaration */ && !node.initializer) { + return; + } + var symbol = getSymbolOfNode(node); + if (symbol.flags & 1 /* FunctionScopedVariable */) { + if (!ts.isIdentifier(node.name)) + return ts.Debug.fail(); + var localDeclarationSymbol = resolveName(node, node.name.escapedText, 3 /* Variable */, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); + if (localDeclarationSymbol && + localDeclarationSymbol !== symbol && + localDeclarationSymbol.flags & 2 /* BlockScopedVariable */) { + if (getDeclarationNodeFlagsFromSymbol(localDeclarationSymbol) & 3 /* BlockScoped */) { + var varDeclList = ts.getAncestor(localDeclarationSymbol.valueDeclaration, 238 /* VariableDeclarationList */); + var container = varDeclList.parent.kind === 219 /* VariableStatement */ && varDeclList.parent.parent + ? varDeclList.parent.parent + : undefined; + // names of block-scoped and function scoped variables can collide only + // if block scoped variable is defined in the function\module\source file scope (because of variable hoisting) + var namesShareScope = container && + (container.kind === 218 /* Block */ && ts.isFunctionLike(container.parent) || + container.kind === 245 /* ModuleBlock */ || + container.kind === 244 /* ModuleDeclaration */ || + container.kind === 279 /* SourceFile */); + // here we know that function scoped variable is shadowed by block scoped one + // if they are defined in the same scope - binder has already reported redeclaration error + // otherwise if variable has an initializer - show error that initialization will fail + // since LHS will be block scoped name instead of function scoped + if (!namesShareScope) { + var name = symbolToString(localDeclarationSymbol); + error(node, ts.Diagnostics.Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1, name, name); + } + } + } + } + } + // Check that a parameter initializer contains no references to parameters declared to the right of itself + function checkParameterInitializer(node) { + if (ts.getRootDeclaration(node).kind !== 151 /* Parameter */) { + return; + } + var func = ts.getContainingFunction(node); + visit(node.initializer); + function visit(n) { + if (ts.isTypeNode(n) || ts.isDeclarationName(n)) { + // do not dive in types + // skip declaration names (i.e. in object literal expressions) + return; + } + if (n.kind === 189 /* PropertyAccessExpression */) { + // skip property names in property access expression + return visit(n.expression); + } + else if (n.kind === 72 /* Identifier */) { + // check FunctionLikeDeclaration.locals (stores parameters\function local variable) + // if it contains entry with a specified name + var symbol = resolveName(n, n.escapedText, 67220415 /* Value */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); + if (!symbol || symbol === unknownSymbol || !symbol.valueDeclaration) { + return; + } + if (symbol.valueDeclaration === node) { + error(n, ts.Diagnostics.Parameter_0_cannot_be_referenced_in_its_initializer, ts.declarationNameToString(node.name)); + return; + } + // locals map for function contain both parameters and function locals + // so we need to do a bit of extra work to check if reference is legal + var enclosingContainer = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); + if (enclosingContainer === func) { + if (symbol.valueDeclaration.kind === 151 /* Parameter */ || + symbol.valueDeclaration.kind === 186 /* BindingElement */) { + // it is ok to reference parameter in initializer if either + // - parameter is located strictly on the left of current parameter declaration + if (symbol.valueDeclaration.pos < node.pos) { + return; + } + // - parameter is wrapped in function-like entity + if (ts.findAncestor(n, function (current) { + if (current === node.initializer) { + return "quit"; + } + return ts.isFunctionLike(current.parent) || + // computed property names/initializers in instance property declaration of class like entities + // are executed in constructor and thus deferred + (current.parent.kind === 154 /* PropertyDeclaration */ && + !(ts.hasModifier(current.parent, 32 /* Static */)) && + ts.isClassLike(current.parent.parent)); + })) { + return; + } + // fall through to report error + } + error(n, ts.Diagnostics.Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it, ts.declarationNameToString(node.name), ts.declarationNameToString(n)); + } + } + else { + return ts.forEachChild(n, visit); + } + } + } + function convertAutoToAny(type) { + return type === autoType ? anyType : type === autoArrayType ? anyArrayType : type; + } + // Check variable, parameter, or property declaration + function checkVariableLikeDeclaration(node) { + checkDecorators(node); + if (!ts.isBindingElement(node)) { + checkSourceElement(node.type); + } + // JSDoc `function(string, string): string` syntax results in parameters with no name + if (!node.name) { + return; + } + // For a computed property, just check the initializer and exit + // Do not use hasDynamicName here, because that returns false for well known symbols. + // We want to perform checkComputedPropertyName for all computed properties, including + // well known symbols. + if (node.name.kind === 149 /* ComputedPropertyName */) { + checkComputedPropertyName(node.name); + if (node.initializer) { + checkExpressionCached(node.initializer); + } + } + if (node.kind === 186 /* BindingElement */) { + if (node.parent.kind === 184 /* ObjectBindingPattern */ && languageVersion < 6 /* ESNext */) { + checkExternalEmitHelpers(node, 4 /* Rest */); + } + // check computed properties inside property names of binding elements + if (node.propertyName && node.propertyName.kind === 149 /* ComputedPropertyName */) { + checkComputedPropertyName(node.propertyName); + } + // check private/protected variable access + var parent = node.parent.parent; + var parentType = getTypeForBindingElementParent(parent); + var name = node.propertyName || node.name; + if (!ts.isBindingPattern(name)) { + var nameText = ts.getTextOfPropertyName(name); + if (nameText) { + var property = getPropertyOfType(parentType, nameText); // TODO: GH#18217 + if (property) { + markPropertyAsReferenced(property, /*nodeForCheckWriteOnly*/ undefined, /*isThisAccess*/ false); // A destructuring is never a write-only reference. + checkPropertyAccessibility(parent, !!parent.initializer && parent.initializer.kind === 98 /* SuperKeyword */, parentType, property); + } + } + } + } + // For a binding pattern, check contained binding elements + if (ts.isBindingPattern(node.name)) { + if (node.name.kind === 185 /* ArrayBindingPattern */ && languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) { + checkExternalEmitHelpers(node, 512 /* Read */); + } + ts.forEach(node.name.elements, checkSourceElement); + } + // For a parameter declaration with an initializer, error and exit if the containing function doesn't have a body + if (node.initializer && ts.getRootDeclaration(node).kind === 151 /* Parameter */ && ts.nodeIsMissing(ts.getContainingFunction(node).body)) { + error(node, ts.Diagnostics.A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation); + return; + } + // For a binding pattern, validate the initializer and exit + if (ts.isBindingPattern(node.name)) { + // Don't validate for-in initializer as it is already an error + if (node.initializer && node.parent.parent.kind !== 226 /* ForInStatement */) { + var initializerType = checkExpressionCached(node.initializer); + if (strictNullChecks && node.name.elements.length === 0) { + checkNonNullType(initializerType, node); + } + else { + checkTypeAssignableToAndOptionallyElaborate(initializerType, getWidenedTypeForVariableLikeDeclaration(node), node, node.initializer); + } + checkParameterInitializer(node); + } + return; + } + var symbol = getSymbolOfNode(node); + var type = convertAutoToAny(getTypeOfSymbol(symbol)); + if (node === symbol.valueDeclaration) { + // Node is the primary declaration of the symbol, just validate the initializer + // Don't validate for-in initializer as it is already an error + var initializer = ts.getEffectiveInitializer(node); + if (initializer) { + var isJSObjectLiteralInitializer = ts.isInJSFile(node) && + ts.isObjectLiteralExpression(initializer) && + (initializer.properties.length === 0 || ts.isPrototypeAccess(node.name)) && + ts.hasEntries(symbol.exports); + if (!isJSObjectLiteralInitializer && node.parent.parent.kind !== 226 /* ForInStatement */) { + checkTypeAssignableToAndOptionallyElaborate(checkExpressionCached(initializer), type, node, initializer, /*headMessage*/ undefined); + checkParameterInitializer(node); + } + } + if (symbol.declarations.length > 1) { + if (ts.some(symbol.declarations, function (d) { return d !== node && ts.isVariableLike(d) && !areDeclarationFlagsIdentical(d, node); })) { + error(node.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); + } + } + } + else { + // Node is a secondary declaration, check that type is identical to primary declaration and check that + // initializer is consistent with type associated with the node + var declarationType = convertAutoToAny(getWidenedTypeForVariableLikeDeclaration(node)); + if (type !== errorType && declarationType !== errorType && + !isTypeIdenticalTo(type, declarationType) && + !(symbol.flags & 67108864 /* Assignment */)) { + errorNextVariableOrPropertyDeclarationMustHaveSameType(type, node, declarationType); + } + if (node.initializer) { + checkTypeAssignableToAndOptionallyElaborate(checkExpressionCached(node.initializer), declarationType, node, node.initializer, /*headMessage*/ undefined); + } + if (!areDeclarationFlagsIdentical(node, symbol.valueDeclaration)) { + error(node.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); + } + } + if (node.kind !== 154 /* PropertyDeclaration */ && node.kind !== 153 /* PropertySignature */) { + // We know we don't have a binding pattern or computed name here + checkExportsOnMergedDeclarations(node); + if (node.kind === 237 /* VariableDeclaration */ || node.kind === 186 /* BindingElement */) { + checkVarDeclaredNamesNotShadowed(node); + } + checkCollisionWithRequireExportsInGeneratedCode(node, node.name); + checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); + } + } + function errorNextVariableOrPropertyDeclarationMustHaveSameType(firstType, nextDeclaration, nextType) { + var nextDeclarationName = ts.getNameOfDeclaration(nextDeclaration); + var message = nextDeclaration.kind === 154 /* PropertyDeclaration */ || nextDeclaration.kind === 153 /* PropertySignature */ + ? ts.Diagnostics.Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_type_2 + : ts.Diagnostics.Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2; + error(nextDeclarationName, message, ts.declarationNameToString(nextDeclarationName), typeToString(firstType), typeToString(nextType)); + } + function areDeclarationFlagsIdentical(left, right) { + if ((left.kind === 151 /* Parameter */ && right.kind === 237 /* VariableDeclaration */) || + (left.kind === 237 /* VariableDeclaration */ && right.kind === 151 /* Parameter */)) { + // Differences in optionality between parameters and variables are allowed. + return true; + } + if (ts.hasQuestionToken(left) !== ts.hasQuestionToken(right)) { + return false; + } + var interestingFlags = 8 /* Private */ | + 16 /* Protected */ | + 256 /* Async */ | + 128 /* Abstract */ | + 64 /* Readonly */ | + 32 /* Static */; + return ts.getSelectedModifierFlags(left, interestingFlags) === ts.getSelectedModifierFlags(right, interestingFlags); + } + function checkVariableDeclaration(node) { + checkGrammarVariableDeclaration(node); + return checkVariableLikeDeclaration(node); + } + function checkBindingElement(node) { + checkGrammarBindingElement(node); + return checkVariableLikeDeclaration(node); + } + function checkVariableStatement(node) { + // Grammar checking + if (!checkGrammarDecoratorsAndModifiers(node) && !checkGrammarVariableDeclarationList(node.declarationList)) + checkGrammarForDisallowedLetOrConstStatement(node); + ts.forEach(node.declarationList.declarations, checkSourceElement); + } + function checkExpressionStatement(node) { + // Grammar checking + checkGrammarStatementInAmbientContext(node); + checkExpression(node.expression); + } + function checkIfStatement(node) { + // Grammar checking + checkGrammarStatementInAmbientContext(node); + checkTruthinessExpression(node.expression); + checkSourceElement(node.thenStatement); + if (node.thenStatement.kind === 220 /* EmptyStatement */) { + error(node.thenStatement, ts.Diagnostics.The_body_of_an_if_statement_cannot_be_the_empty_statement); + } + checkSourceElement(node.elseStatement); + } + function checkDoStatement(node) { + // Grammar checking + checkGrammarStatementInAmbientContext(node); + checkSourceElement(node.statement); + checkTruthinessExpression(node.expression); + } + function checkWhileStatement(node) { + // Grammar checking + checkGrammarStatementInAmbientContext(node); + checkTruthinessExpression(node.expression); + checkSourceElement(node.statement); + } + function checkTruthinessExpression(node, checkMode) { + var type = checkExpression(node, checkMode); + if (type.flags & 16384 /* Void */) { + error(node, ts.Diagnostics.An_expression_of_type_void_cannot_be_tested_for_truthiness); + } + return type; + } + function checkForStatement(node) { + // Grammar checking + if (!checkGrammarStatementInAmbientContext(node)) { + if (node.initializer && node.initializer.kind === 238 /* VariableDeclarationList */) { + checkGrammarVariableDeclarationList(node.initializer); + } + } + if (node.initializer) { + if (node.initializer.kind === 238 /* VariableDeclarationList */) { + ts.forEach(node.initializer.declarations, checkVariableDeclaration); + } + else { + checkExpression(node.initializer); + } + } + if (node.condition) + checkTruthinessExpression(node.condition); + if (node.incrementor) + checkExpression(node.incrementor); + checkSourceElement(node.statement); + if (node.locals) { + registerForUnusedIdentifiersCheck(node); + } + } + function checkForOfStatement(node) { + checkGrammarForInOrForOfStatement(node); + if (node.awaitModifier) { + var functionFlags = ts.getFunctionFlags(ts.getContainingFunction(node)); + if ((functionFlags & (4 /* Invalid */ | 2 /* Async */)) === 2 /* Async */ && languageVersion < 6 /* ESNext */) { + // for..await..of in an async function or async generator function prior to ESNext requires the __asyncValues helper + checkExternalEmitHelpers(node, 16384 /* ForAwaitOfIncludes */); + } + } + else if (compilerOptions.downlevelIteration && languageVersion < 2 /* ES2015 */) { + // for..of prior to ES2015 requires the __values helper when downlevelIteration is enabled + checkExternalEmitHelpers(node, 256 /* ForOfIncludes */); + } + // Check the LHS and RHS + // If the LHS is a declaration, just check it as a variable declaration, which will in turn check the RHS + // via checkRightHandSideOfForOf. + // If the LHS is an expression, check the LHS, as a destructuring assignment or as a reference. + // Then check that the RHS is assignable to it. + if (node.initializer.kind === 238 /* VariableDeclarationList */) { + checkForInOrForOfVariableDeclaration(node); + } + else { + var varExpr = node.initializer; + var iteratedType = checkRightHandSideOfForOf(node.expression, node.awaitModifier); + // There may be a destructuring assignment on the left side + if (varExpr.kind === 187 /* ArrayLiteralExpression */ || varExpr.kind === 188 /* ObjectLiteralExpression */) { + // iteratedType may be undefined. In this case, we still want to check the structure of + // varExpr, in particular making sure it's a valid LeftHandSideExpression. But we'd like + // to short circuit the type relation checking as much as possible, so we pass the unknownType. + checkDestructuringAssignment(varExpr, iteratedType || errorType); + } + else { + var leftType = checkExpression(varExpr); + checkReferenceExpression(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access); + // iteratedType will be undefined if the rightType was missing properties/signatures + // required to get its iteratedType (like [Symbol.iterator] or next). This may be + // because we accessed properties from anyType, or it may have led to an error inside + // getElementTypeOfIterable. + if (iteratedType) { + checkTypeAssignableToAndOptionallyElaborate(iteratedType, leftType, varExpr, node.expression); + } + } + } + checkSourceElement(node.statement); + if (node.locals) { + registerForUnusedIdentifiersCheck(node); + } + } + function checkForInStatement(node) { + // Grammar checking + checkGrammarForInOrForOfStatement(node); + var rightType = getNonNullableTypeIfNeeded(checkExpression(node.expression)); + // TypeScript 1.0 spec (April 2014): 5.4 + // In a 'for-in' statement of the form + // for (let VarDecl in Expr) Statement + // VarDecl must be a variable declaration without a type annotation that declares a variable of type Any, + // and Expr must be an expression of type Any, an object type, or a type parameter type. + if (node.initializer.kind === 238 /* VariableDeclarationList */) { + var variable = node.initializer.declarations[0]; + if (variable && ts.isBindingPattern(variable.name)) { + error(variable.name, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern); + } + checkForInOrForOfVariableDeclaration(node); + } + else { + // In a 'for-in' statement of the form + // for (Var in Expr) Statement + // Var must be an expression classified as a reference of type Any or the String primitive type, + // and Expr must be an expression of type Any, an object type, or a type parameter type. + var varExpr = node.initializer; + var leftType = checkExpression(varExpr); + if (varExpr.kind === 187 /* ArrayLiteralExpression */ || varExpr.kind === 188 /* ObjectLiteralExpression */) { + error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern); + } + else if (!isTypeAssignableTo(getIndexTypeOrString(rightType), leftType)) { + error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any); + } + else { + // run check only former check succeeded to avoid cascading errors + checkReferenceExpression(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access); + } + } + // unknownType is returned i.e. if node.expression is identifier whose name cannot be resolved + // in this case error about missing name is already reported - do not report extra one + if (rightType === neverType || !isTypeAssignableToKind(rightType, 67108864 /* NonPrimitive */ | 58982400 /* InstantiableNonPrimitive */)) { + error(node.expression, ts.Diagnostics.The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_but_here_has_type_0, typeToString(rightType)); + } + checkSourceElement(node.statement); + if (node.locals) { + registerForUnusedIdentifiersCheck(node); + } + } + function checkForInOrForOfVariableDeclaration(iterationStatement) { + var variableDeclarationList = iterationStatement.initializer; + // checkGrammarForInOrForOfStatement will check that there is exactly one declaration. + if (variableDeclarationList.declarations.length >= 1) { + var decl = variableDeclarationList.declarations[0]; + checkVariableDeclaration(decl); + } + } + function checkRightHandSideOfForOf(rhsExpression, awaitModifier) { + var expressionType = checkNonNullExpression(rhsExpression); + return checkIteratedTypeOrElementType(expressionType, rhsExpression, /*allowStringInput*/ true, awaitModifier !== undefined); + } + function checkIteratedTypeOrElementType(inputType, errorNode, allowStringInput, allowAsyncIterables) { + if (isTypeAny(inputType)) { + return inputType; + } + return getIteratedTypeOrElementType(inputType, errorNode, allowStringInput, allowAsyncIterables, /*checkAssignability*/ true) || anyType; + } + /** + * When consuming an iterable type in a for..of, spread, or iterator destructuring assignment + * we want to get the iterated type of an iterable for ES2015 or later, or the iterated type + * of a iterable (if defined globally) or element type of an array like for ES2015 or earlier. + */ + function getIteratedTypeOrElementType(inputType, errorNode, allowStringInput, allowAsyncIterables, checkAssignability) { + if (inputType === neverType) { + reportTypeNotIterableError(errorNode, inputType, allowAsyncIterables); // TODO: GH#18217 + return undefined; + } + var uplevelIteration = languageVersion >= 2 /* ES2015 */; + var downlevelIteration = !uplevelIteration && compilerOptions.downlevelIteration; + // Get the iterated type of an `Iterable` or `IterableIterator` only in ES2015 + // or higher, when inside of an async generator or for-await-if, or when + // downlevelIteration is requested. + if (uplevelIteration || downlevelIteration || allowAsyncIterables) { + // We only report errors for an invalid iterable type in ES2015 or higher. + var iteratedType = getIteratedTypeOfIterable(inputType, uplevelIteration ? errorNode : undefined, allowAsyncIterables, /*allowSyncIterables*/ true, checkAssignability); + if (iteratedType || uplevelIteration) { + return iteratedType; + } + } + var arrayType = inputType; + var reportedError = false; + var hasStringConstituent = false; + // If strings are permitted, remove any string-like constituents from the array type. + // This allows us to find other non-string element types from an array unioned with + // a string. + if (allowStringInput) { + if (arrayType.flags & 1048576 /* Union */) { + // After we remove all types that are StringLike, we will know if there was a string constituent + // based on whether the result of filter is a new array. + var arrayTypes = inputType.types; + var filteredTypes = ts.filter(arrayTypes, function (t) { return !(t.flags & 132 /* StringLike */); }); + if (filteredTypes !== arrayTypes) { + arrayType = getUnionType(filteredTypes, 2 /* Subtype */); + } + } + else if (arrayType.flags & 132 /* StringLike */) { + arrayType = neverType; + } + hasStringConstituent = arrayType !== inputType; + if (hasStringConstituent) { + if (languageVersion < 1 /* ES5 */) { + if (errorNode) { + error(errorNode, ts.Diagnostics.Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher); + reportedError = true; + } + } + // Now that we've removed all the StringLike types, if no constituents remain, then the entire + // arrayOrStringType was a string. + if (arrayType.flags & 131072 /* Never */) { + return stringType; + } + } + } + if (!isArrayLikeType(arrayType)) { + if (errorNode && !reportedError) { + // Which error we report depends on whether we allow strings or if there was a + // string constituent. For example, if the input type is number | string, we + // want to say that number is not an array type. But if the input was just + // number and string input is allowed, we want to say that number is not an + // array type or a string type. + var isIterable = !!getIteratedTypeOfIterable(inputType, /* errorNode */ undefined, allowAsyncIterables, /*allowSyncIterables*/ true, checkAssignability); + var diagnostic = !allowStringInput || hasStringConstituent + ? downlevelIteration + ? ts.Diagnostics.Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator + : isIterable + ? ts.Diagnostics.Type_0_is_not_an_array_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators + : ts.Diagnostics.Type_0_is_not_an_array_type + : downlevelIteration + ? ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator + : isIterable + ? ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators + : ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type; + error(errorNode, diagnostic, typeToString(arrayType)); + } + return hasStringConstituent ? stringType : undefined; + } + var arrayElementType = getIndexTypeOfType(arrayType, 1 /* Number */); + if (hasStringConstituent && arrayElementType) { + // This is just an optimization for the case where arrayOrStringType is string | string[] + if (arrayElementType.flags & 132 /* StringLike */) { + return stringType; + } + return getUnionType([arrayElementType, stringType], 2 /* Subtype */); + } + return arrayElementType; + } + /** + * We want to treat type as an iterable, and get the type it is an iterable of. The iterable + * must have the following structure (annotated with the names of the variables below): + * + * { // iterable + * [Symbol.iterator]: { // iteratorMethod + * (): Iterator + * } + * } + * + * For an async iterable, we expect the following structure: + * + * { // iterable + * [Symbol.asyncIterator]: { // iteratorMethod + * (): AsyncIterator + * } + * } + * + * T is the type we are after. At every level that involves analyzing return types + * of signatures, we union the return types of all the signatures. + * + * Another thing to note is that at any step of this process, we could run into a dead end, + * meaning either the property is missing, or we run into the anyType. If either of these things + * happens, we return undefined to signal that we could not find the iterated type. If a property + * is missing, and the previous step did not result in 'any', then we also give an error if the + * caller requested it. Then the caller can decide what to do in the case where there is no iterated + * type. This is different from returning anyType, because that would signify that we have matched the + * whole pattern and that T (above) is 'any'. + * + * For a **for-of** statement, `yield*` (in a normal generator), spread, array + * destructuring, or normal generator we will only ever look for a `[Symbol.iterator]()` + * method. + * + * For an async generator we will only ever look at the `[Symbol.asyncIterator]()` method. + * + * For a **for-await-of** statement or a `yield*` in an async generator we will look for + * the `[Symbol.asyncIterator]()` method first, and then the `[Symbol.iterator]()` method. + */ + function getIteratedTypeOfIterable(type, errorNode, allowAsyncIterables, allowSyncIterables, checkAssignability) { + if (isTypeAny(type)) { + return undefined; + } + return mapType(type, getIteratedType); + function getIteratedType(type) { + var typeAsIterable = type; + if (allowAsyncIterables) { + if (typeAsIterable.iteratedTypeOfAsyncIterable) { + return typeAsIterable.iteratedTypeOfAsyncIterable; + } + // As an optimization, if the type is an instantiation of the global `AsyncIterable` + // or the global `AsyncIterableIterator` then just grab its type argument. + if (isReferenceToType(type, getGlobalAsyncIterableType(/*reportErrors*/ false)) || + isReferenceToType(type, getGlobalAsyncIterableIteratorType(/*reportErrors*/ false))) { + return typeAsIterable.iteratedTypeOfAsyncIterable = type.typeArguments[0]; + } + } + if (allowSyncIterables) { + if (typeAsIterable.iteratedTypeOfIterable) { + return allowAsyncIterables + ? typeAsIterable.iteratedTypeOfAsyncIterable = getAwaitedType(typeAsIterable.iteratedTypeOfIterable) + : typeAsIterable.iteratedTypeOfIterable; + } + // As an optimization, if the type is an instantiation of the global `Iterable` or + // `IterableIterator` then just grab its type argument. + if (isReferenceToType(type, getGlobalIterableType(/*reportErrors*/ false)) || + isReferenceToType(type, getGlobalIterableIteratorType(/*reportErrors*/ false))) { + return allowAsyncIterables + ? typeAsIterable.iteratedTypeOfAsyncIterable = getAwaitedType(type.typeArguments[0]) + : typeAsIterable.iteratedTypeOfIterable = type.typeArguments[0]; + } + } + var asyncMethodType = allowAsyncIterables && getTypeOfPropertyOfType(type, ts.getPropertyNameForKnownSymbolName("asyncIterator")); + var methodType = asyncMethodType || (allowSyncIterables ? getTypeOfPropertyOfType(type, ts.getPropertyNameForKnownSymbolName("iterator")) : undefined); + if (isTypeAny(methodType)) { + return undefined; + } + var signatures = methodType ? getSignaturesOfType(methodType, 0 /* Call */) : undefined; + if (!ts.some(signatures)) { + if (errorNode) { + // only report on the first error + reportTypeNotIterableError(errorNode, type, allowAsyncIterables); + errorNode = undefined; + } + return undefined; + } + var returnType = getUnionType(ts.map(signatures, getReturnTypeOfSignature), 2 /* Subtype */); + var iteratedType = getIteratedTypeOfIterator(returnType, errorNode, /*isAsyncIterator*/ !!asyncMethodType); + if (checkAssignability && errorNode && iteratedType) { + // If `checkAssignability` was specified, we were called from + // `checkIteratedTypeOrElementType`. As such, we need to validate that + // the type passed in is actually an Iterable. + checkTypeAssignableTo(type, asyncMethodType + ? createAsyncIterableType(iteratedType) + : createIterableType(iteratedType), errorNode); + } + if (iteratedType) { + return allowAsyncIterables + ? typeAsIterable.iteratedTypeOfAsyncIterable = asyncMethodType ? iteratedType : getAwaitedType(iteratedType) + : typeAsIterable.iteratedTypeOfIterable = iteratedType; + } + } + } + function reportTypeNotIterableError(errorNode, type, allowAsyncIterables) { + error(errorNode, allowAsyncIterables + ? ts.Diagnostics.Type_0_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator + : ts.Diagnostics.Type_0_must_have_a_Symbol_iterator_method_that_returns_an_iterator, typeToString(type)); + } + /** + * This function has very similar logic as getIteratedTypeOfIterable, except that it operates on + * Iterators instead of Iterables. Here is the structure: + * + * { // iterator + * next: { // nextMethod + * (): { // nextResult + * value: T // nextValue + * } + * } + * } + * + * For an async iterator, we expect the following structure: + * + * { // iterator + * next: { // nextMethod + * (): PromiseLike<{ // nextResult + * value: T // nextValue + * }> + * } + * } + */ + function getIteratedTypeOfIterator(type, errorNode, isAsyncIterator) { + if (isTypeAny(type)) { + return undefined; + } + var typeAsIterator = type; + if (isAsyncIterator ? typeAsIterator.iteratedTypeOfAsyncIterator : typeAsIterator.iteratedTypeOfIterator) { + return isAsyncIterator ? typeAsIterator.iteratedTypeOfAsyncIterator : typeAsIterator.iteratedTypeOfIterator; + } + // As an optimization, if the type is an instantiation of the global `Iterator` (for + // a non-async iterator) or the global `AsyncIterator` (for an async-iterator) then + // just grab its type argument. + var getIteratorType = isAsyncIterator ? getGlobalAsyncIteratorType : getGlobalIteratorType; + if (isReferenceToType(type, getIteratorType(/*reportErrors*/ false))) { + return isAsyncIterator + ? typeAsIterator.iteratedTypeOfAsyncIterator = type.typeArguments[0] + : typeAsIterator.iteratedTypeOfIterator = type.typeArguments[0]; + } + // Both async and non-async iterators must have a `next` method. + var nextMethod = getTypeOfPropertyOfType(type, "next"); + if (isTypeAny(nextMethod)) { + return undefined; + } + var nextMethodSignatures = nextMethod ? getSignaturesOfType(nextMethod, 0 /* Call */) : ts.emptyArray; + if (nextMethodSignatures.length === 0) { + if (errorNode) { + error(errorNode, isAsyncIterator + ? ts.Diagnostics.An_async_iterator_must_have_a_next_method + : ts.Diagnostics.An_iterator_must_have_a_next_method); + } + return undefined; + } + var nextResult = getUnionType(ts.map(nextMethodSignatures, getReturnTypeOfSignature), 2 /* Subtype */); + if (isTypeAny(nextResult)) { + return undefined; + } + // For an async iterator, we must get the awaited type of the return type. + if (isAsyncIterator) { + nextResult = getAwaitedTypeOfPromise(nextResult, errorNode, ts.Diagnostics.The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property); + if (isTypeAny(nextResult)) { + return undefined; + } + } + var nextValue = nextResult && getTypeOfPropertyOfType(nextResult, "value"); + if (!nextValue) { + if (errorNode) { + error(errorNode, isAsyncIterator + ? ts.Diagnostics.The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property + : ts.Diagnostics.The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property); + } + return undefined; + } + return isAsyncIterator + ? typeAsIterator.iteratedTypeOfAsyncIterator = nextValue + : typeAsIterator.iteratedTypeOfIterator = nextValue; + } + /** + * A generator may have a return type of `Iterator`, `Iterable`, or + * `IterableIterator`. An async generator may have a return type of `AsyncIterator`, + * `AsyncIterable`, or `AsyncIterableIterator`. This function can be used to extract + * the iterated type from this return type for contextual typing and verifying signatures. + */ + function getIteratedTypeOfGenerator(returnType, isAsyncGenerator) { + if (isTypeAny(returnType)) { + return undefined; + } + return getIteratedTypeOfIterable(returnType, /*errorNode*/ undefined, /*allowAsyncIterables*/ isAsyncGenerator, /*allowSyncIterables*/ !isAsyncGenerator, /*checkAssignability*/ false) + || getIteratedTypeOfIterator(returnType, /*errorNode*/ undefined, isAsyncGenerator); + } + function checkBreakOrContinueStatement(node) { + // Grammar checking + if (!checkGrammarStatementInAmbientContext(node)) + checkGrammarBreakOrContinueStatement(node); + // TODO: Check that target label is valid + } + function isUnwrappedReturnTypeVoidOrAny(func, returnType) { + var unwrappedReturnType = (ts.getFunctionFlags(func) & 3 /* AsyncGenerator */) === 2 /* Async */ + ? getPromisedTypeOfPromise(returnType) // Async function + : returnType; // AsyncGenerator function, Generator function, or normal function + return !!unwrappedReturnType && maybeTypeOfKind(unwrappedReturnType, 16384 /* Void */ | 3 /* AnyOrUnknown */); + } + function checkReturnStatement(node) { + // Grammar checking + if (checkGrammarStatementInAmbientContext(node)) { + return; + } + var func = ts.getContainingFunction(node); + if (!func) { + grammarErrorOnFirstToken(node, ts.Diagnostics.A_return_statement_can_only_be_used_within_a_function_body); + return; + } + var signature = getSignatureFromDeclaration(func); + var returnType = getReturnTypeOfSignature(signature); + var functionFlags = ts.getFunctionFlags(func); + var isGenerator = functionFlags & 1 /* Generator */; + if (strictNullChecks || node.expression || returnType.flags & 131072 /* Never */) { + var exprType = node.expression ? checkExpressionCached(node.expression) : undefinedType; + if (isGenerator) { // AsyncGenerator function or Generator function + // A generator does not need its return expressions checked against its return type. + // Instead, the yield expressions are checked against the element type. + // TODO: Check return types of generators when return type tracking is added + // for generators. + return; + } + else if (func.kind === 159 /* SetAccessor */) { + if (node.expression) { + error(node, ts.Diagnostics.Setters_cannot_return_a_value); + } + } + else if (func.kind === 157 /* Constructor */) { + if (node.expression && !checkTypeAssignableToAndOptionallyElaborate(exprType, returnType, node, node.expression)) { + error(node, ts.Diagnostics.Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class); + } + } + else if (getReturnTypeFromAnnotation(func)) { + if (functionFlags & 2 /* Async */) { // Async function + var promisedType = getPromisedTypeOfPromise(returnType); + var awaitedType = checkAwaitedType(exprType, node, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); + if (promisedType) { + // If the function has a return type, but promisedType is + // undefined, an error will be reported in checkAsyncFunctionReturnType + // so we don't need to report one here. + checkTypeAssignableTo(awaitedType, promisedType, node); + } + } + else { + checkTypeAssignableToAndOptionallyElaborate(exprType, returnType, node, node.expression); + } + } + } + else if (func.kind !== 157 /* Constructor */ && compilerOptions.noImplicitReturns && !isUnwrappedReturnTypeVoidOrAny(func, returnType) && !isGenerator) { + // The function has a return type, but the return statement doesn't have an expression. + error(node, ts.Diagnostics.Not_all_code_paths_return_a_value); + } + } + function checkWithStatement(node) { + // Grammar checking for withStatement + if (!checkGrammarStatementInAmbientContext(node)) { + if (node.flags & 16384 /* AwaitContext */) { + grammarErrorOnFirstToken(node, ts.Diagnostics.with_statements_are_not_allowed_in_an_async_function_block); + } + } + checkExpression(node.expression); + var sourceFile = ts.getSourceFileOfNode(node); + if (!hasParseDiagnostics(sourceFile)) { + var start = ts.getSpanOfTokenAtPosition(sourceFile, node.pos).start; + var end = node.statement.pos; + grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any); + } + } + function checkSwitchStatement(node) { + // Grammar checking + checkGrammarStatementInAmbientContext(node); + var firstDefaultClause; + var hasDuplicateDefaultClause = false; + var expressionType = checkExpression(node.expression); + var expressionIsLiteral = isLiteralType(expressionType); + ts.forEach(node.caseBlock.clauses, function (clause) { + // Grammar check for duplicate default clauses, skip if we already report duplicate default clause + if (clause.kind === 272 /* DefaultClause */ && !hasDuplicateDefaultClause) { + if (firstDefaultClause === undefined) { + firstDefaultClause = clause; + } + else { + var sourceFile = ts.getSourceFileOfNode(node); + var start = ts.skipTrivia(sourceFile.text, clause.pos); + var end = clause.statements.length > 0 ? clause.statements[0].pos : clause.end; + grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.A_default_clause_cannot_appear_more_than_once_in_a_switch_statement); + hasDuplicateDefaultClause = true; + } + } + if (produceDiagnostics && clause.kind === 271 /* CaseClause */) { + // TypeScript 1.0 spec (April 2014): 5.9 + // In a 'switch' statement, each 'case' expression must be of a type that is comparable + // to or from the type of the 'switch' expression. + var caseType = checkExpression(clause.expression); + var caseIsLiteral = isLiteralType(caseType); + var comparedExpressionType = expressionType; + if (!caseIsLiteral || !expressionIsLiteral) { + caseType = caseIsLiteral ? getBaseTypeOfLiteralType(caseType) : caseType; + comparedExpressionType = getBaseTypeOfLiteralType(expressionType); + } + if (!isTypeEqualityComparableTo(comparedExpressionType, caseType)) { + // expressionType is not comparable to caseType, try the reversed check and report errors if it fails + checkTypeComparableTo(caseType, comparedExpressionType, clause.expression, /*headMessage*/ undefined); + } + } + ts.forEach(clause.statements, checkSourceElement); + }); + if (node.caseBlock.locals) { + registerForUnusedIdentifiersCheck(node.caseBlock); + } + } + function checkLabeledStatement(node) { + // Grammar checking + if (!checkGrammarStatementInAmbientContext(node)) { + ts.findAncestor(node.parent, function (current) { + if (ts.isFunctionLike(current)) { + return "quit"; + } + if (current.kind === 233 /* LabeledStatement */ && current.label.escapedText === node.label.escapedText) { + grammarErrorOnNode(node.label, ts.Diagnostics.Duplicate_label_0, ts.getTextOfNode(node.label)); + return true; + } + return false; + }); + } + // ensure that label is unique + checkSourceElement(node.statement); + } + function checkThrowStatement(node) { + // Grammar checking + if (!checkGrammarStatementInAmbientContext(node)) { + if (node.expression === undefined) { + grammarErrorAfterFirstToken(node, ts.Diagnostics.Line_break_not_permitted_here); + } + } + if (node.expression) { + checkExpression(node.expression); + } + } + function checkTryStatement(node) { + // Grammar checking + checkGrammarStatementInAmbientContext(node); + checkBlock(node.tryBlock); + var catchClause = node.catchClause; + if (catchClause) { + // Grammar checking + if (catchClause.variableDeclaration) { + if (catchClause.variableDeclaration.type) { + grammarErrorOnFirstToken(catchClause.variableDeclaration.type, ts.Diagnostics.Catch_clause_variable_cannot_have_a_type_annotation); + } + else if (catchClause.variableDeclaration.initializer) { + grammarErrorOnFirstToken(catchClause.variableDeclaration.initializer, ts.Diagnostics.Catch_clause_variable_cannot_have_an_initializer); + } + else { + var blockLocals_1 = catchClause.block.locals; + if (blockLocals_1) { + ts.forEachKey(catchClause.locals, function (caughtName) { + var blockLocal = blockLocals_1.get(caughtName); + if (blockLocal && (blockLocal.flags & 2 /* BlockScopedVariable */) !== 0) { + grammarErrorOnNode(blockLocal.valueDeclaration, ts.Diagnostics.Cannot_redeclare_identifier_0_in_catch_clause, caughtName); + } + }); + } + } + } + checkBlock(catchClause.block); + } + if (node.finallyBlock) { + checkBlock(node.finallyBlock); + } + } + function checkIndexConstraints(type) { + var declaredNumberIndexer = getIndexDeclarationOfSymbol(type.symbol, 1 /* Number */); + var declaredStringIndexer = getIndexDeclarationOfSymbol(type.symbol, 0 /* String */); + var stringIndexType = getIndexTypeOfType(type, 0 /* String */); + var numberIndexType = getIndexTypeOfType(type, 1 /* Number */); + if (stringIndexType || numberIndexType) { + ts.forEach(getPropertiesOfObjectType(type), function (prop) { + var propType = getTypeOfSymbol(prop); + checkIndexConstraintForProperty(prop, propType, type, declaredStringIndexer, stringIndexType, 0 /* String */); + checkIndexConstraintForProperty(prop, propType, type, declaredNumberIndexer, numberIndexType, 1 /* Number */); + }); + var classDeclaration = type.symbol.valueDeclaration; + if (ts.getObjectFlags(type) & 1 /* Class */ && ts.isClassLike(classDeclaration)) { + for (var _i = 0, _a = classDeclaration.members; _i < _a.length; _i++) { + var member = _a[_i]; + // Only process instance properties with computed names here. + // Static properties cannot be in conflict with indexers, + // and properties with literal names were already checked. + if (!ts.hasModifier(member, 32 /* Static */) && hasNonBindableDynamicName(member)) { + var symbol = getSymbolOfNode(member); + var propType = getTypeOfSymbol(symbol); + checkIndexConstraintForProperty(symbol, propType, type, declaredStringIndexer, stringIndexType, 0 /* String */); + checkIndexConstraintForProperty(symbol, propType, type, declaredNumberIndexer, numberIndexType, 1 /* Number */); + } + } + } + } + var errorNode; + if (stringIndexType && numberIndexType) { + errorNode = declaredNumberIndexer || declaredStringIndexer; + // condition 'errorNode === undefined' may appear if types does not declare nor string neither number indexer + if (!errorNode && (ts.getObjectFlags(type) & 2 /* Interface */)) { + var someBaseTypeHasBothIndexers = ts.forEach(getBaseTypes(type), function (base) { return getIndexTypeOfType(base, 0 /* String */) && getIndexTypeOfType(base, 1 /* Number */); }); + errorNode = someBaseTypeHasBothIndexers ? undefined : type.symbol.declarations[0]; + } + } + if (errorNode && !isTypeAssignableTo(numberIndexType, stringIndexType)) { // TODO: GH#18217 + error(errorNode, ts.Diagnostics.Numeric_index_type_0_is_not_assignable_to_string_index_type_1, typeToString(numberIndexType), typeToString(stringIndexType)); + } + function checkIndexConstraintForProperty(prop, propertyType, containingType, indexDeclaration, indexType, indexKind) { + // ESSymbol properties apply to neither string nor numeric indexers. + if (!indexType || ts.isKnownSymbol(prop)) { + return; + } + var propDeclaration = prop.valueDeclaration; + var name = propDeclaration && ts.getNameOfDeclaration(propDeclaration); + // index is numeric and property name is not valid numeric literal + if (indexKind === 1 /* Number */ && !(name ? isNumericName(name) : isNumericLiteralName(prop.escapedName))) { + return; + } + // perform property check if property or indexer is declared in 'type' + // this allows us to rule out cases when both property and indexer are inherited from the base class + var errorNode; + if (propDeclaration && name && + (propDeclaration.kind === 204 /* BinaryExpression */ || + name.kind === 149 /* ComputedPropertyName */ || + prop.parent === containingType.symbol)) { + errorNode = propDeclaration; + } + else if (indexDeclaration) { + errorNode = indexDeclaration; + } + else if (ts.getObjectFlags(containingType) & 2 /* Interface */) { + // for interfaces property and indexer might be inherited from different bases + // check if any base class already has both property and indexer. + // check should be performed only if 'type' is the first type that brings property\indexer together + var someBaseClassHasBothPropertyAndIndexer = ts.forEach(getBaseTypes(containingType), function (base) { return getPropertyOfObjectType(base, prop.escapedName) && getIndexTypeOfType(base, indexKind); }); + errorNode = someBaseClassHasBothPropertyAndIndexer ? undefined : containingType.symbol.declarations[0]; + } + if (errorNode && !isTypeAssignableTo(propertyType, indexType)) { + var errorMessage = indexKind === 0 /* String */ + ? ts.Diagnostics.Property_0_of_type_1_is_not_assignable_to_string_index_type_2 + : ts.Diagnostics.Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2; + error(errorNode, errorMessage, symbolToString(prop), typeToString(propertyType), typeToString(indexType)); + } + } + } + function checkTypeNameIsReserved(name, message) { + // TS 1.0 spec (April 2014): 3.6.1 + // The predefined type keywords are reserved and cannot be used as names of user defined types. + switch (name.escapedText) { + case "any": + case "unknown": + case "number": + case "bigint": + case "boolean": + case "string": + case "symbol": + case "void": + case "object": + error(name, message, name.escapedText); + } + } + /** + * The name cannot be used as 'Object' of user defined types with special target. + */ + function checkClassNameCollisionWithObject(name) { + if (languageVersion === 1 /* ES5 */ && name.escapedText === "Object" + && moduleKind !== ts.ModuleKind.ES2015 && moduleKind !== ts.ModuleKind.ESNext) { + error(name, ts.Diagnostics.Class_name_cannot_be_Object_when_targeting_ES5_with_module_0, ts.ModuleKind[moduleKind]); // https://github.com/Microsoft/TypeScript/issues/17494 + } + } + /** + * Check each type parameter and check that type parameters have no duplicate type parameter declarations + */ + function checkTypeParameters(typeParameterDeclarations) { + if (typeParameterDeclarations) { + var seenDefault = false; + for (var i = 0; i < typeParameterDeclarations.length; i++) { + var node = typeParameterDeclarations[i]; + checkTypeParameter(node); + if (produceDiagnostics) { + if (node.default) { + seenDefault = true; + } + else if (seenDefault) { + error(node, ts.Diagnostics.Required_type_parameters_may_not_follow_optional_type_parameters); + } + for (var j = 0; j < i; j++) { + if (typeParameterDeclarations[j].symbol === node.symbol) { + error(node.name, ts.Diagnostics.Duplicate_identifier_0, ts.declarationNameToString(node.name)); + } + } + } + } + } + } + /** Check that type parameter lists are identical across multiple declarations */ + function checkTypeParameterListsIdentical(symbol) { + if (symbol.declarations.length === 1) { + return; + } + var links = getSymbolLinks(symbol); + if (!links.typeParametersChecked) { + links.typeParametersChecked = true; + var declarations = getClassOrInterfaceDeclarationsOfSymbol(symbol); + if (declarations.length <= 1) { + return; + } + var type = getDeclaredTypeOfSymbol(symbol); + if (!areTypeParametersIdentical(declarations, type.localTypeParameters)) { + // Report an error on every conflicting declaration. + var name = symbolToString(symbol); + for (var _i = 0, declarations_6 = declarations; _i < declarations_6.length; _i++) { + var declaration = declarations_6[_i]; + error(declaration.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_type_parameters, name); + } + } + } + } + function areTypeParametersIdentical(declarations, targetParameters) { + var maxTypeArgumentCount = ts.length(targetParameters); + var minTypeArgumentCount = getMinTypeArgumentCount(targetParameters); + for (var _i = 0, declarations_7 = declarations; _i < declarations_7.length; _i++) { + var declaration = declarations_7[_i]; + // If this declaration has too few or too many type parameters, we report an error + var sourceParameters = ts.getEffectiveTypeParameterDeclarations(declaration); + var numTypeParameters = sourceParameters.length; + if (numTypeParameters < minTypeArgumentCount || numTypeParameters > maxTypeArgumentCount) { + return false; + } + for (var i = 0; i < numTypeParameters; i++) { + var source = sourceParameters[i]; + var target = targetParameters[i]; + // If the type parameter node does not have the same as the resolved type + // parameter at this position, we report an error. + if (source.name.escapedText !== target.symbol.escapedName) { + return false; + } + // If the type parameter node does not have an identical constraint as the resolved + // type parameter at this position, we report an error. + var constraint = ts.getEffectiveConstraintOfTypeParameter(source); + var sourceConstraint = constraint && getTypeFromTypeNode(constraint); + var targetConstraint = getConstraintOfTypeParameter(target); + if (sourceConstraint) { + // relax check if later interface augmentation has no constraint + if (!targetConstraint || !isTypeIdenticalTo(sourceConstraint, targetConstraint)) { + return false; + } + } + // If the type parameter node has a default and it is not identical to the default + // for the type parameter at this position, we report an error. + var sourceDefault = source.default && getTypeFromTypeNode(source.default); + var targetDefault = getDefaultFromTypeParameter(target); + if (sourceDefault && targetDefault && !isTypeIdenticalTo(sourceDefault, targetDefault)) { + return false; + } + } + } + return true; + } + function checkClassExpression(node) { + checkClassLikeDeclaration(node); + checkNodeDeferred(node); + return getTypeOfSymbol(getSymbolOfNode(node)); + } + function checkClassExpressionDeferred(node) { + ts.forEach(node.members, checkSourceElement); + registerForUnusedIdentifiersCheck(node); + } + function checkClassDeclaration(node) { + if (!node.name && !ts.hasModifier(node, 512 /* Default */)) { + grammarErrorOnFirstToken(node, ts.Diagnostics.A_class_declaration_without_the_default_modifier_must_have_a_name); + } + checkClassLikeDeclaration(node); + ts.forEach(node.members, checkSourceElement); + registerForUnusedIdentifiersCheck(node); + } + function checkClassLikeDeclaration(node) { + checkGrammarClassLikeDeclaration(node); + checkDecorators(node); + if (node.name) { + checkTypeNameIsReserved(node.name, ts.Diagnostics.Class_name_cannot_be_0); + checkCollisionWithRequireExportsInGeneratedCode(node, node.name); + checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); + if (!(node.flags & 4194304 /* Ambient */)) { + checkClassNameCollisionWithObject(node.name); + } + } + checkTypeParameters(ts.getEffectiveTypeParameterDeclarations(node)); + checkExportsOnMergedDeclarations(node); + var symbol = getSymbolOfNode(node); + var type = getDeclaredTypeOfSymbol(symbol); + var typeWithThis = getTypeWithThisArgument(type); + var staticType = getTypeOfSymbol(symbol); + checkTypeParameterListsIdentical(symbol); + checkClassForDuplicateDeclarations(node); + // Only check for reserved static identifiers on non-ambient context. + if (!(node.flags & 4194304 /* Ambient */)) { + checkClassForStaticPropertyNameConflicts(node); + } + var baseTypeNode = ts.getEffectiveBaseTypeNode(node); + if (baseTypeNode) { + if (languageVersion < 2 /* ES2015 */) { + checkExternalEmitHelpers(baseTypeNode.parent, 1 /* Extends */); + } + var baseTypes = getBaseTypes(type); + if (baseTypes.length && produceDiagnostics) { + var baseType_1 = baseTypes[0]; + var baseConstructorType = getBaseConstructorTypeOfClass(type); + var staticBaseType = getApparentType(baseConstructorType); + checkBaseTypeAccessibility(staticBaseType, baseTypeNode); + checkSourceElement(baseTypeNode.expression); + var extendsNode = ts.getClassExtendsHeritageElement(node); + if (extendsNode && extendsNode !== baseTypeNode) { + checkExpression(extendsNode.expression); + } + if (ts.some(baseTypeNode.typeArguments)) { + ts.forEach(baseTypeNode.typeArguments, checkSourceElement); + for (var _i = 0, _a = getConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments, baseTypeNode); _i < _a.length; _i++) { + var constructor = _a[_i]; + if (!checkTypeArgumentConstraints(baseTypeNode, constructor.typeParameters)) { + break; + } + } + } + var baseWithThis = getTypeWithThisArgument(baseType_1, type.thisType); + if (!checkTypeAssignableTo(typeWithThis, baseWithThis, /*errorNode*/ undefined)) { + issueMemberSpecificError(node, typeWithThis, baseWithThis, ts.Diagnostics.Class_0_incorrectly_extends_base_class_1); + } + else { + // Report static side error only when instance type is assignable + checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, ts.Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1); + } + if (baseConstructorType.flags & 8650752 /* TypeVariable */ && !isMixinConstructorType(staticType)) { + error(node.name || node, ts.Diagnostics.A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any); + } + if (!(staticBaseType.symbol && staticBaseType.symbol.flags & 32 /* Class */) && !(baseConstructorType.flags & 8650752 /* TypeVariable */)) { + // When the static base type is a "class-like" constructor function (but not actually a class), we verify + // that all instantiated base constructor signatures return the same type. We can simply compare the type + // references (as opposed to checking the structure of the types) because elsewhere we have already checked + // that the base type is a class or interface type (and not, for example, an anonymous object type). + // (Javascript constructor functions have this property trivially true since their return type is ignored.) + var constructors = getInstantiatedConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments, baseTypeNode); + if (ts.forEach(constructors, function (sig) { return !isJSConstructor(sig.declaration) && getReturnTypeOfSignature(sig) !== baseType_1; })) { + error(baseTypeNode.expression, ts.Diagnostics.Base_constructors_must_all_have_the_same_return_type); + } + } + checkKindsOfPropertyMemberOverrides(type, baseType_1); + } + } + var implementedTypeNodes = ts.getClassImplementsHeritageClauseElements(node); + if (implementedTypeNodes) { + for (var _b = 0, implementedTypeNodes_1 = implementedTypeNodes; _b < implementedTypeNodes_1.length; _b++) { + var typeRefNode = implementedTypeNodes_1[_b]; + if (!ts.isEntityNameExpression(typeRefNode.expression)) { + error(typeRefNode.expression, ts.Diagnostics.A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments); + } + checkTypeReferenceNode(typeRefNode); + if (produceDiagnostics) { + var t = getTypeFromTypeNode(typeRefNode); + if (t !== errorType) { + if (isValidBaseType(t)) { + var genericDiag = t.symbol && t.symbol.flags & 32 /* Class */ ? + ts.Diagnostics.Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass : + ts.Diagnostics.Class_0_incorrectly_implements_interface_1; + var baseWithThis = getTypeWithThisArgument(t, type.thisType); + if (!checkTypeAssignableTo(typeWithThis, baseWithThis, /*errorNode*/ undefined)) { + issueMemberSpecificError(node, typeWithThis, baseWithThis, genericDiag); + } + } + else { + error(typeRefNode, ts.Diagnostics.A_class_can_only_implement_an_object_type_or_intersection_of_object_types_with_statically_known_members); + } + } + } + } + } + if (produceDiagnostics) { + checkIndexConstraints(type); + checkTypeForDuplicateIndexSignatures(node); + checkPropertyInitialization(node); + } + } + function issueMemberSpecificError(node, typeWithThis, baseWithThis, broadDiag) { + // iterate over all implemented properties and issue errors on each one which isn't compatible, rather than the class as a whole, if possible + var issuedMemberError = false; + var _loop_8 = function (member) { + if (ts.hasStaticModifier(member)) { + return "continue"; + } + var declaredProp = member.name && getSymbolAtLocation(member.name) || getSymbolAtLocation(member); + if (declaredProp) { + var prop = getPropertyOfType(typeWithThis, declaredProp.escapedName); + var baseProp = getPropertyOfType(baseWithThis, declaredProp.escapedName); + if (prop && baseProp) { + var rootChain = function () { return ts.chainDiagnosticMessages( + /*details*/ undefined, ts.Diagnostics.Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2, symbolToString(declaredProp), typeToString(typeWithThis), typeToString(baseWithThis)); }; + if (!checkTypeAssignableTo(getTypeOfSymbol(prop), getTypeOfSymbol(baseProp), member.name || member, /*message*/ undefined, rootChain)) { + issuedMemberError = true; + } + } + } + }; + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + _loop_8(member); + } + if (!issuedMemberError) { + // check again with diagnostics to generate a less-specific error + checkTypeAssignableTo(typeWithThis, baseWithThis, node.name || node, broadDiag); + } + } + function checkBaseTypeAccessibility(type, node) { + var signatures = getSignaturesOfType(type, 1 /* Construct */); + if (signatures.length) { + var declaration = signatures[0].declaration; + if (declaration && ts.hasModifier(declaration, 8 /* Private */)) { + var typeClassDeclaration = ts.getClassLikeDeclarationOfSymbol(type.symbol); + if (!isNodeWithinClass(node, typeClassDeclaration)) { + error(node, ts.Diagnostics.Cannot_extend_a_class_0_Class_constructor_is_marked_as_private, getFullyQualifiedName(type.symbol)); + } + } + } + } + function getTargetSymbol(s) { + // if symbol is instantiated its flags are not copied from the 'target' + // so we'll need to get back original 'target' symbol to work with correct set of flags + return ts.getCheckFlags(s) & 1 /* Instantiated */ ? s.target : s; + } + function getClassOrInterfaceDeclarationsOfSymbol(symbol) { + return ts.filter(symbol.declarations, function (d) { + return d.kind === 240 /* ClassDeclaration */ || d.kind === 241 /* InterfaceDeclaration */; + }); + } + function checkKindsOfPropertyMemberOverrides(type, baseType) { + // TypeScript 1.0 spec (April 2014): 8.2.3 + // A derived class inherits all members from its base class it doesn't override. + // Inheritance means that a derived class implicitly contains all non - overridden members of the base class. + // Both public and private property members are inherited, but only public property members can be overridden. + // A property member in a derived class is said to override a property member in a base class + // when the derived class property member has the same name and kind(instance or static) + // as the base class property member. + // The type of an overriding property member must be assignable(section 3.8.4) + // to the type of the overridden property member, or otherwise a compile - time error occurs. + // Base class instance member functions can be overridden by derived class instance member functions, + // but not by other kinds of members. + // Base class instance member variables and accessors can be overridden by + // derived class instance member variables and accessors, but not by other kinds of members. + // NOTE: assignability is checked in checkClassDeclaration + var baseProperties = getPropertiesOfType(baseType); + for (var _i = 0, baseProperties_1 = baseProperties; _i < baseProperties_1.length; _i++) { + var baseProperty = baseProperties_1[_i]; + var base = getTargetSymbol(baseProperty); + if (base.flags & 4194304 /* Prototype */) { + continue; + } + var derived = getTargetSymbol(getPropertyOfObjectType(type, base.escapedName)); // TODO: GH#18217 + var baseDeclarationFlags = ts.getDeclarationModifierFlagsFromSymbol(base); + ts.Debug.assert(!!derived, "derived should point to something, even if it is the base class' declaration."); + if (derived) { + // In order to resolve whether the inherited method was overridden in the base class or not, + // we compare the Symbols obtained. Since getTargetSymbol returns the symbol on the *uninstantiated* + // type declaration, derived and base resolve to the same symbol even in the case of generic classes. + if (derived === base) { + // derived class inherits base without override/redeclaration + var derivedClassDecl = ts.getClassLikeDeclarationOfSymbol(type.symbol); + // It is an error to inherit an abstract member without implementing it or being declared abstract. + // If there is no declaration for the derived class (as in the case of class expressions), + // then the class cannot be declared abstract. + if (baseDeclarationFlags & 128 /* Abstract */ && (!derivedClassDecl || !ts.hasModifier(derivedClassDecl, 128 /* Abstract */))) { + if (derivedClassDecl.kind === 209 /* ClassExpression */) { + error(derivedClassDecl, ts.Diagnostics.Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1, symbolToString(baseProperty), typeToString(baseType)); + } + else { + error(derivedClassDecl, ts.Diagnostics.Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2, typeToString(type), symbolToString(baseProperty), typeToString(baseType)); + } + } + } + else { + // derived overrides base. + var derivedDeclarationFlags = ts.getDeclarationModifierFlagsFromSymbol(derived); + if (baseDeclarationFlags & 8 /* Private */ || derivedDeclarationFlags & 8 /* Private */) { + // either base or derived property is private - not override, skip it + continue; + } + if (isPrototypeProperty(base) || base.flags & 98308 /* PropertyOrAccessor */ && derived.flags & 98308 /* PropertyOrAccessor */) { + // method is overridden with method or property/accessor is overridden with property/accessor - correct case + continue; + } + var errorMessage = void 0; + if (isPrototypeProperty(base)) { + if (derived.flags & 98304 /* Accessor */) { + errorMessage = ts.Diagnostics.Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor; + } + else { + errorMessage = ts.Diagnostics.Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_property; + } + } + else if (base.flags & 98304 /* Accessor */) { + errorMessage = ts.Diagnostics.Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function; + } + else { + errorMessage = ts.Diagnostics.Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_function; + } + error(ts.getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage, typeToString(baseType), symbolToString(base), typeToString(type)); + } + } + } + } + function checkInheritedPropertiesAreIdentical(type, typeNode) { + var baseTypes = getBaseTypes(type); + if (baseTypes.length < 2) { + return true; + } + var seen = ts.createUnderscoreEscapedMap(); + ts.forEach(resolveDeclaredMembers(type).declaredProperties, function (p) { seen.set(p.escapedName, { prop: p, containingType: type }); }); + var ok = true; + for (var _i = 0, baseTypes_2 = baseTypes; _i < baseTypes_2.length; _i++) { + var base = baseTypes_2[_i]; + var properties = getPropertiesOfType(getTypeWithThisArgument(base, type.thisType)); + for (var _a = 0, properties_7 = properties; _a < properties_7.length; _a++) { + var prop = properties_7[_a]; + var existing = seen.get(prop.escapedName); + if (!existing) { + seen.set(prop.escapedName, { prop: prop, containingType: base }); + } + else { + var isInheritedProperty = existing.containingType !== type; + if (isInheritedProperty && !isPropertyIdenticalTo(existing.prop, prop)) { + ok = false; + var typeName1 = typeToString(existing.containingType); + var typeName2 = typeToString(base); + var errorInfo = ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Named_property_0_of_types_1_and_2_are_not_identical, symbolToString(prop), typeName1, typeName2); + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Interface_0_cannot_simultaneously_extend_types_1_and_2, typeToString(type), typeName1, typeName2); + diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(typeNode, errorInfo)); + } + } + } + } + return ok; + } + function checkPropertyInitialization(node) { + if (!strictNullChecks || !strictPropertyInitialization || node.flags & 4194304 /* Ambient */) { + return; + } + var constructor = findConstructorDeclaration(node); + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + if (isInstancePropertyWithoutInitializer(member)) { + var propName = member.name; + if (ts.isIdentifier(propName)) { + var type = getTypeOfSymbol(getSymbolOfNode(member)); + if (!(type.flags & 3 /* AnyOrUnknown */ || getFalsyFlags(type) & 32768 /* Undefined */)) { + if (!constructor || !isPropertyInitializedInConstructor(propName, type, constructor)) { + error(member.name, ts.Diagnostics.Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor, ts.declarationNameToString(propName)); + } + } + } + } + } + } + function isInstancePropertyWithoutInitializer(node) { + return node.kind === 154 /* PropertyDeclaration */ && + !ts.hasModifier(node, 32 /* Static */ | 128 /* Abstract */) && + !node.exclamationToken && + !node.initializer; + } + function isPropertyInitializedInConstructor(propName, propType, constructor) { + var reference = ts.createPropertyAccess(ts.createThis(), propName); + reference.expression.parent = reference; + reference.parent = constructor; + reference.flowNode = constructor.returnFlowNode; + var flowType = getFlowTypeOfReference(reference, propType, getOptionalType(propType)); + return !(getFalsyFlags(flowType) & 32768 /* Undefined */); + } + function checkInterfaceDeclaration(node) { + // Grammar checking + if (!checkGrammarDecoratorsAndModifiers(node)) + checkGrammarInterfaceDeclaration(node); + checkTypeParameters(node.typeParameters); + if (produceDiagnostics) { + checkTypeNameIsReserved(node.name, ts.Diagnostics.Interface_name_cannot_be_0); + checkExportsOnMergedDeclarations(node); + var symbol = getSymbolOfNode(node); + checkTypeParameterListsIdentical(symbol); + // Only check this symbol once + var firstInterfaceDecl = ts.getDeclarationOfKind(symbol, 241 /* InterfaceDeclaration */); + if (node === firstInterfaceDecl) { + var type = getDeclaredTypeOfSymbol(symbol); + var typeWithThis = getTypeWithThisArgument(type); + // run subsequent checks only if first set succeeded + if (checkInheritedPropertiesAreIdentical(type, node.name)) { + for (var _i = 0, _a = getBaseTypes(type); _i < _a.length; _i++) { + var baseType = _a[_i]; + checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(baseType, type.thisType), node.name, ts.Diagnostics.Interface_0_incorrectly_extends_interface_1); + } + checkIndexConstraints(type); + } + } + checkObjectTypeForDuplicateDeclarations(node); + } + ts.forEach(ts.getInterfaceBaseTypeNodes(node), function (heritageElement) { + if (!ts.isEntityNameExpression(heritageElement.expression)) { + error(heritageElement.expression, ts.Diagnostics.An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments); + } + checkTypeReferenceNode(heritageElement); + }); + ts.forEach(node.members, checkSourceElement); + if (produceDiagnostics) { + checkTypeForDuplicateIndexSignatures(node); + registerForUnusedIdentifiersCheck(node); + } + } + function checkTypeAliasDeclaration(node) { + // Grammar checking + checkGrammarDecoratorsAndModifiers(node); + checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_alias_name_cannot_be_0); + checkTypeParameters(node.typeParameters); + checkSourceElement(node.type); + registerForUnusedIdentifiersCheck(node); + } + function computeEnumMemberValues(node) { + var nodeLinks = getNodeLinks(node); + if (!(nodeLinks.flags & 16384 /* EnumValuesComputed */)) { + nodeLinks.flags |= 16384 /* EnumValuesComputed */; + var autoValue = 0; + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + var value = computeMemberValue(member, autoValue); + getNodeLinks(member).enumMemberValue = value; + autoValue = typeof value === "number" ? value + 1 : undefined; + } + } + } + function computeMemberValue(member, autoValue) { + if (isComputedNonLiteralName(member.name)) { + error(member.name, ts.Diagnostics.Computed_property_names_are_not_allowed_in_enums); + } + else { + var text = ts.getTextOfPropertyName(member.name); + if (isNumericLiteralName(text) && !isInfinityOrNaNString(text)) { + error(member.name, ts.Diagnostics.An_enum_member_cannot_have_a_numeric_name); + } + } + if (member.initializer) { + return computeConstantValue(member); + } + // In ambient enum declarations that specify no const modifier, enum member declarations that omit + // a value are considered computed members (as opposed to having auto-incremented values). + if (member.parent.flags & 4194304 /* Ambient */ && !ts.isEnumConst(member.parent)) { + return undefined; + } + // If the member declaration specifies no value, the member is considered a constant enum member. + // If the member is the first member in the enum declaration, it is assigned the value zero. + // Otherwise, it is assigned the value of the immediately preceding member plus one, and an error + // occurs if the immediately preceding member is not a constant enum member. + if (autoValue !== undefined) { + return autoValue; + } + error(member.name, ts.Diagnostics.Enum_member_must_have_initializer); + return undefined; + } + function computeConstantValue(member) { + var enumKind = getEnumKind(getSymbolOfNode(member.parent)); + var isConstEnum = ts.isEnumConst(member.parent); + var initializer = member.initializer; + var value = enumKind === 1 /* Literal */ && !isLiteralEnumMember(member) ? undefined : evaluate(initializer); + if (value !== undefined) { + if (isConstEnum && typeof value === "number" && !isFinite(value)) { + error(initializer, isNaN(value) ? + ts.Diagnostics.const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN : + ts.Diagnostics.const_enum_member_initializer_was_evaluated_to_a_non_finite_value); + } + } + else if (enumKind === 1 /* Literal */) { + error(initializer, ts.Diagnostics.Computed_values_are_not_permitted_in_an_enum_with_string_valued_members); + return 0; + } + else if (isConstEnum) { + error(initializer, ts.Diagnostics.In_const_enum_declarations_member_initializer_must_be_constant_expression); + } + else if (member.parent.flags & 4194304 /* Ambient */) { + error(initializer, ts.Diagnostics.In_ambient_enum_declarations_member_initializer_must_be_constant_expression); + } + else { + // Only here do we need to check that the initializer is assignable to the enum type. + checkTypeAssignableTo(checkExpression(initializer), getDeclaredTypeOfSymbol(getSymbolOfNode(member.parent)), initializer, /*headMessage*/ undefined); + } + return value; + function evaluate(expr) { + switch (expr.kind) { + case 202 /* PrefixUnaryExpression */: + var value_2 = evaluate(expr.operand); + if (typeof value_2 === "number") { + switch (expr.operator) { + case 38 /* PlusToken */: return value_2; + case 39 /* MinusToken */: return -value_2; + case 53 /* TildeToken */: return ~value_2; + } + } + break; + case 204 /* BinaryExpression */: + var left = evaluate(expr.left); + var right = evaluate(expr.right); + if (typeof left === "number" && typeof right === "number") { + switch (expr.operatorToken.kind) { + case 50 /* BarToken */: return left | right; + case 49 /* AmpersandToken */: return left & right; + case 47 /* GreaterThanGreaterThanToken */: return left >> right; + case 48 /* GreaterThanGreaterThanGreaterThanToken */: return left >>> right; + case 46 /* LessThanLessThanToken */: return left << right; + case 51 /* CaretToken */: return left ^ right; + case 40 /* AsteriskToken */: return left * right; + case 42 /* SlashToken */: return left / right; + case 38 /* PlusToken */: return left + right; + case 39 /* MinusToken */: return left - right; + case 43 /* PercentToken */: return left % right; + case 41 /* AsteriskAsteriskToken */: return Math.pow(left, right); + } + } + else if (typeof left === "string" && typeof right === "string" && expr.operatorToken.kind === 38 /* PlusToken */) { + return left + right; + } + break; + case 10 /* StringLiteral */: + return expr.text; + case 8 /* NumericLiteral */: + checkGrammarNumericLiteral(expr); + return +expr.text; + case 195 /* ParenthesizedExpression */: + return evaluate(expr.expression); + case 72 /* Identifier */: + var identifier = expr; + if (isInfinityOrNaNString(identifier.escapedText)) { + return +(identifier.escapedText); + } + return ts.nodeIsMissing(expr) ? 0 : evaluateEnumMember(expr, getSymbolOfNode(member.parent), identifier.escapedText); + case 190 /* ElementAccessExpression */: + case 189 /* PropertyAccessExpression */: + var ex = expr; + if (isConstantMemberAccess(ex)) { + var type = getTypeOfExpression(ex.expression); + if (type.symbol && type.symbol.flags & 384 /* Enum */) { + var name = void 0; + if (ex.kind === 189 /* PropertyAccessExpression */) { + name = ex.name.escapedText; + } + else { + var argument = ex.argumentExpression; + ts.Debug.assert(ts.isLiteralExpression(argument)); + name = ts.escapeLeadingUnderscores(argument.text); + } + return evaluateEnumMember(expr, type.symbol, name); + } + } + break; + } + return undefined; + } + function evaluateEnumMember(expr, enumSymbol, name) { + var memberSymbol = enumSymbol.exports.get(name); + if (memberSymbol) { + var declaration = memberSymbol.valueDeclaration; + if (declaration !== member) { + if (isBlockScopedNameDeclaredBeforeUse(declaration, member)) { + return getEnumMemberValue(declaration); + } + error(expr, ts.Diagnostics.A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums); + return 0; + } + } + return undefined; + } + } + function isConstantMemberAccess(node) { + return node.kind === 72 /* Identifier */ || + node.kind === 189 /* PropertyAccessExpression */ && isConstantMemberAccess(node.expression) || + node.kind === 190 /* ElementAccessExpression */ && isConstantMemberAccess(node.expression) && + node.argumentExpression.kind === 10 /* StringLiteral */; + } + function checkEnumDeclaration(node) { + if (!produceDiagnostics) { + return; + } + // Grammar checking + checkGrammarDecoratorsAndModifiers(node); + checkTypeNameIsReserved(node.name, ts.Diagnostics.Enum_name_cannot_be_0); + checkCollisionWithRequireExportsInGeneratedCode(node, node.name); + checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); + checkExportsOnMergedDeclarations(node); + computeEnumMemberValues(node); + var enumIsConst = ts.isEnumConst(node); + if (compilerOptions.isolatedModules && enumIsConst && node.flags & 4194304 /* Ambient */) { + error(node.name, ts.Diagnostics.Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided); + } + // Spec 2014 - Section 9.3: + // It isn't possible for one enum declaration to continue the automatic numbering sequence of another, + // and when an enum type has multiple declarations, only one declaration is permitted to omit a value + // for the first member. + // + // Only perform this check once per symbol + var enumSymbol = getSymbolOfNode(node); + var firstDeclaration = ts.getDeclarationOfKind(enumSymbol, node.kind); + if (node === firstDeclaration) { + if (enumSymbol.declarations.length > 1) { + // check that const is placed\omitted on all enum declarations + ts.forEach(enumSymbol.declarations, function (decl) { + if (ts.isEnumDeclaration(decl) && ts.isEnumConst(decl) !== enumIsConst) { + error(ts.getNameOfDeclaration(decl), ts.Diagnostics.Enum_declarations_must_all_be_const_or_non_const); + } + }); + } + var seenEnumMissingInitialInitializer_1 = false; + ts.forEach(enumSymbol.declarations, function (declaration) { + // return true if we hit a violation of the rule, false otherwise + if (declaration.kind !== 243 /* EnumDeclaration */) { + return false; + } + var enumDeclaration = declaration; + if (!enumDeclaration.members.length) { + return false; + } + var firstEnumMember = enumDeclaration.members[0]; + if (!firstEnumMember.initializer) { + if (seenEnumMissingInitialInitializer_1) { + error(firstEnumMember.name, ts.Diagnostics.In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enum_element); + } + else { + seenEnumMissingInitialInitializer_1 = true; + } + } + }); + } + } + function getFirstNonAmbientClassOrFunctionDeclaration(symbol) { + var declarations = symbol.declarations; + for (var _i = 0, declarations_8 = declarations; _i < declarations_8.length; _i++) { + var declaration = declarations_8[_i]; + if ((declaration.kind === 240 /* ClassDeclaration */ || + (declaration.kind === 239 /* FunctionDeclaration */ && ts.nodeIsPresent(declaration.body))) && + !(declaration.flags & 4194304 /* Ambient */)) { + return declaration; + } + } + return undefined; + } + function inSameLexicalScope(node1, node2) { + var container1 = ts.getEnclosingBlockScopeContainer(node1); + var container2 = ts.getEnclosingBlockScopeContainer(node2); + if (isGlobalSourceFile(container1)) { + return isGlobalSourceFile(container2); + } + else if (isGlobalSourceFile(container2)) { + return false; + } + else { + return container1 === container2; + } + } + function checkModuleDeclaration(node) { + if (produceDiagnostics) { + // Grammar checking + var isGlobalAugmentation = ts.isGlobalScopeAugmentation(node); + var inAmbientContext = node.flags & 4194304 /* Ambient */; + if (isGlobalAugmentation && !inAmbientContext) { + error(node.name, ts.Diagnostics.Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambient_context); + } + var isAmbientExternalModule = ts.isAmbientModule(node); + var contextErrorMessage = isAmbientExternalModule + ? ts.Diagnostics.An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file + : ts.Diagnostics.A_namespace_declaration_is_only_allowed_in_a_namespace_or_module; + if (checkGrammarModuleElementContext(node, contextErrorMessage)) { + // If we hit a module declaration in an illegal context, just bail out to avoid cascading errors. + return; + } + if (!checkGrammarDecoratorsAndModifiers(node)) { + if (!inAmbientContext && node.name.kind === 10 /* StringLiteral */) { + grammarErrorOnNode(node.name, ts.Diagnostics.Only_ambient_modules_can_use_quoted_names); + } + } + if (ts.isIdentifier(node.name)) { + checkCollisionWithRequireExportsInGeneratedCode(node, node.name); + checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); + } + checkExportsOnMergedDeclarations(node); + var symbol = getSymbolOfNode(node); + // The following checks only apply on a non-ambient instantiated module declaration. + if (symbol.flags & 512 /* ValueModule */ + && symbol.declarations.length > 1 + && !inAmbientContext + && isInstantiatedModule(node, !!compilerOptions.preserveConstEnums || !!compilerOptions.isolatedModules)) { + var firstNonAmbientClassOrFunc = getFirstNonAmbientClassOrFunctionDeclaration(symbol); + if (firstNonAmbientClassOrFunc) { + if (ts.getSourceFileOfNode(node) !== ts.getSourceFileOfNode(firstNonAmbientClassOrFunc)) { + error(node.name, ts.Diagnostics.A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merged); + } + else if (node.pos < firstNonAmbientClassOrFunc.pos) { + error(node.name, ts.Diagnostics.A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged); + } + } + // if the module merges with a class declaration in the same lexical scope, + // we need to track this to ensure the correct emit. + var mergedClass = ts.getDeclarationOfKind(symbol, 240 /* ClassDeclaration */); + if (mergedClass && + inSameLexicalScope(node, mergedClass)) { + getNodeLinks(node).flags |= 32768 /* LexicalModuleMergesWithClass */; + } + } + if (isAmbientExternalModule) { + if (ts.isExternalModuleAugmentation(node)) { + // body of the augmentation should be checked for consistency only if augmentation was applied to its target (either global scope or module) + // otherwise we'll be swamped in cascading errors. + // We can detect if augmentation was applied using following rules: + // - augmentation for a global scope is always applied + // - augmentation for some external module is applied if symbol for augmentation is merged (it was combined with target module). + var checkBody = isGlobalAugmentation || (getSymbolOfNode(node).flags & 33554432 /* Transient */); + if (checkBody && node.body) { + for (var _i = 0, _a = node.body.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + checkModuleAugmentationElement(statement, isGlobalAugmentation); + } + } + } + else if (isGlobalSourceFile(node.parent)) { + if (isGlobalAugmentation) { + error(node.name, ts.Diagnostics.Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_declarations); + } + else if (ts.isExternalModuleNameRelative(ts.getTextOfIdentifierOrLiteral(node.name))) { + error(node.name, ts.Diagnostics.Ambient_module_declaration_cannot_specify_relative_module_name); + } + } + else { + if (isGlobalAugmentation) { + error(node.name, ts.Diagnostics.Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_declarations); + } + else { + // Node is not an augmentation and is not located on the script level. + // This means that this is declaration of ambient module that is located in other module or namespace which is prohibited. + error(node.name, ts.Diagnostics.Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces); + } + } + } + } + if (node.body) { + checkSourceElement(node.body); + if (!ts.isGlobalScopeAugmentation(node)) { + registerForUnusedIdentifiersCheck(node); + } + } + } + function checkModuleAugmentationElement(node, isGlobalAugmentation) { + switch (node.kind) { + case 219 /* VariableStatement */: + // error each individual name in variable statement instead of marking the entire variable statement + for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + checkModuleAugmentationElement(decl, isGlobalAugmentation); + } + break; + case 254 /* ExportAssignment */: + case 255 /* ExportDeclaration */: + grammarErrorOnFirstToken(node, ts.Diagnostics.Exports_and_export_assignments_are_not_permitted_in_module_augmentations); + break; + case 248 /* ImportEqualsDeclaration */: + case 249 /* ImportDeclaration */: + grammarErrorOnFirstToken(node, ts.Diagnostics.Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_module); + break; + case 186 /* BindingElement */: + case 237 /* VariableDeclaration */: + var name = node.name; + if (ts.isBindingPattern(name)) { + for (var _b = 0, _c = name.elements; _b < _c.length; _b++) { + var el = _c[_b]; + // mark individual names in binding pattern + checkModuleAugmentationElement(el, isGlobalAugmentation); + } + break; + } + // falls through + case 240 /* ClassDeclaration */: + case 243 /* EnumDeclaration */: + case 239 /* FunctionDeclaration */: + case 241 /* InterfaceDeclaration */: + case 244 /* ModuleDeclaration */: + case 242 /* TypeAliasDeclaration */: + if (isGlobalAugmentation) { + return; + } + var symbol = getSymbolOfNode(node); + if (symbol) { + // module augmentations cannot introduce new names on the top level scope of the module + // this is done it two steps + // 1. quick check - if symbol for node is not merged - this is local symbol to this augmentation - report error + // 2. main check - report error if value declaration of the parent symbol is module augmentation) + var reportError = !(symbol.flags & 33554432 /* Transient */); + if (!reportError) { + // symbol should not originate in augmentation + reportError = !!symbol.parent && ts.isExternalModuleAugmentation(symbol.parent.declarations[0]); + } + } + break; + } + } + function getFirstIdentifier(node) { + switch (node.kind) { + case 72 /* Identifier */: + return node; + case 148 /* QualifiedName */: + do { + node = node.left; + } while (node.kind !== 72 /* Identifier */); + return node; + case 189 /* PropertyAccessExpression */: + do { + node = node.expression; + } while (node.kind !== 72 /* Identifier */); + return node; + } + } + function checkExternalImportOrExportDeclaration(node) { + var moduleName = ts.getExternalModuleName(node); + if (!moduleName || ts.nodeIsMissing(moduleName)) { + // Should be a parse error. + return false; + } + if (!ts.isStringLiteral(moduleName)) { + error(moduleName, ts.Diagnostics.String_literal_expected); + return false; + } + var inAmbientExternalModule = node.parent.kind === 245 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent); + if (node.parent.kind !== 279 /* SourceFile */ && !inAmbientExternalModule) { + error(moduleName, node.kind === 255 /* ExportDeclaration */ ? + ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace : + ts.Diagnostics.Import_declarations_in_a_namespace_cannot_reference_a_module); + return false; + } + if (inAmbientExternalModule && ts.isExternalModuleNameRelative(moduleName.text)) { + // we have already reported errors on top level imports\exports in external module augmentations in checkModuleDeclaration + // no need to do this again. + if (!isTopLevelInExternalModuleAugmentation(node)) { + // TypeScript 1.0 spec (April 2013): 12.1.6 + // An ExternalImportDeclaration in an AmbientExternalModuleDeclaration may reference + // other external modules only through top - level external module names. + // Relative external module names are not permitted. + error(node, ts.Diagnostics.Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relative_module_name); + return false; + } + } + return true; + } + function checkAliasSymbol(node) { + var symbol = getSymbolOfNode(node); + var target = resolveAlias(symbol); + if (target !== unknownSymbol) { + // For external modules symbol represent local symbol for an alias. + // This local symbol will merge any other local declarations (excluding other aliases) + // and symbol.flags will contains combined representation for all merged declaration. + // Based on symbol.flags we can compute a set of excluded meanings (meaning that resolved alias should not have, + // otherwise it will conflict with some local declaration). Note that in addition to normal flags we include matching SymbolFlags.Export* + // in order to prevent collisions with declarations that were exported from the current module (they still contribute to local names). + var excludedMeanings = (symbol.flags & (67220415 /* Value */ | 1048576 /* ExportValue */) ? 67220415 /* Value */ : 0) | + (symbol.flags & 67897832 /* Type */ ? 67897832 /* Type */ : 0) | + (symbol.flags & 1920 /* Namespace */ ? 1920 /* Namespace */ : 0); + if (target.flags & excludedMeanings) { + var message = node.kind === 257 /* ExportSpecifier */ ? + ts.Diagnostics.Export_declaration_conflicts_with_exported_declaration_of_0 : + ts.Diagnostics.Import_declaration_conflicts_with_local_declaration_of_0; + error(node, message, symbolToString(symbol)); + } + // Don't allow to re-export something with no value side when `--isolatedModules` is set. + if (compilerOptions.isolatedModules + && node.kind === 257 /* ExportSpecifier */ + && !(target.flags & 67220415 /* Value */) + && !(node.flags & 4194304 /* Ambient */)) { + error(node, ts.Diagnostics.Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided); + } + } + } + function checkImportBinding(node) { + checkCollisionWithRequireExportsInGeneratedCode(node, node.name); + checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); + checkAliasSymbol(node); + } + function checkImportDeclaration(node) { + if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_import_declaration_can_only_be_used_in_a_namespace_or_module)) { + // If we hit an import declaration in an illegal context, just bail out to avoid cascading errors. + return; + } + if (!checkGrammarDecoratorsAndModifiers(node) && ts.hasModifiers(node)) { + grammarErrorOnFirstToken(node, ts.Diagnostics.An_import_declaration_cannot_have_modifiers); + } + if (checkExternalImportOrExportDeclaration(node)) { + var importClause = node.importClause; + if (importClause) { + if (importClause.name) { + checkImportBinding(importClause); + } + if (importClause.namedBindings) { + if (importClause.namedBindings.kind === 251 /* NamespaceImport */) { + checkImportBinding(importClause.namedBindings); + } + else { + var moduleExisted = resolveExternalModuleName(node, node.moduleSpecifier); + if (moduleExisted) { + ts.forEach(importClause.namedBindings.elements, checkImportBinding); + } + } + } + } + } + } + function checkImportEqualsDeclaration(node) { + if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_import_declaration_can_only_be_used_in_a_namespace_or_module)) { + // If we hit an import declaration in an illegal context, just bail out to avoid cascading errors. + return; + } + checkGrammarDecoratorsAndModifiers(node); + if (ts.isInternalModuleImportEqualsDeclaration(node) || checkExternalImportOrExportDeclaration(node)) { + checkImportBinding(node); + if (ts.hasModifier(node, 1 /* Export */)) { + markExportAsReferenced(node); + } + if (node.moduleReference.kind !== 259 /* ExternalModuleReference */) { + var target = resolveAlias(getSymbolOfNode(node)); + if (target !== unknownSymbol) { + if (target.flags & 67220415 /* Value */) { + // Target is a value symbol, check that it is not hidden by a local declaration with the same name + var moduleName = getFirstIdentifier(node.moduleReference); + if (!(resolveEntityName(moduleName, 67220415 /* Value */ | 1920 /* Namespace */).flags & 1920 /* Namespace */)) { + error(moduleName, ts.Diagnostics.Module_0_is_hidden_by_a_local_declaration_with_the_same_name, ts.declarationNameToString(moduleName)); + } + } + if (target.flags & 67897832 /* Type */) { + checkTypeNameIsReserved(node.name, ts.Diagnostics.Import_name_cannot_be_0); + } + } + } + else { + if (moduleKind >= ts.ModuleKind.ES2015 && !(node.flags & 4194304 /* Ambient */)) { + // Import equals declaration is deprecated in es6 or above + grammarErrorOnNode(node, ts.Diagnostics.Import_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_import_Asterisk_as_ns_from_mod_import_a_from_mod_import_d_from_mod_or_another_module_format_instead); + } + } + } + } + function checkExportDeclaration(node) { + if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_export_declaration_can_only_be_used_in_a_module)) { + // If we hit an export in an illegal context, just bail out to avoid cascading errors. + return; + } + if (!checkGrammarDecoratorsAndModifiers(node) && ts.hasModifiers(node)) { + grammarErrorOnFirstToken(node, ts.Diagnostics.An_export_declaration_cannot_have_modifiers); + } + if (!node.moduleSpecifier || checkExternalImportOrExportDeclaration(node)) { + if (node.exportClause) { + // export { x, y } + // export { x, y } from "foo" + ts.forEach(node.exportClause.elements, checkExportSpecifier); + var inAmbientExternalModule = node.parent.kind === 245 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent); + var inAmbientNamespaceDeclaration = !inAmbientExternalModule && node.parent.kind === 245 /* ModuleBlock */ && + !node.moduleSpecifier && node.flags & 4194304 /* Ambient */; + if (node.parent.kind !== 279 /* SourceFile */ && !inAmbientExternalModule && !inAmbientNamespaceDeclaration) { + error(node, ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace); + } + } + else { + // export * from "foo" + var moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier); + if (moduleSymbol && hasExportAssignmentSymbol(moduleSymbol)) { + error(node.moduleSpecifier, ts.Diagnostics.Module_0_uses_export_and_cannot_be_used_with_export_Asterisk, symbolToString(moduleSymbol)); + } + if (moduleKind !== ts.ModuleKind.System && moduleKind !== ts.ModuleKind.ES2015 && moduleKind !== ts.ModuleKind.ESNext) { + checkExternalEmitHelpers(node, 32768 /* ExportStar */); + } + } + } + } + function checkGrammarModuleElementContext(node, errorMessage) { + var isInAppropriateContext = node.parent.kind === 279 /* SourceFile */ || node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 244 /* ModuleDeclaration */; + if (!isInAppropriateContext) { + grammarErrorOnFirstToken(node, errorMessage); + } + return !isInAppropriateContext; + } + function checkExportSpecifier(node) { + checkAliasSymbol(node); + if (ts.getEmitDeclarations(compilerOptions)) { + collectLinkedAliases(node.propertyName || node.name, /*setVisibility*/ true); + } + if (!node.parent.parent.moduleSpecifier) { + var exportedName = node.propertyName || node.name; + // find immediate value referenced by exported name (SymbolFlags.Alias is set so we don't chase down aliases) + var symbol = resolveName(exportedName, exportedName.escapedText, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, + /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); + if (symbol && (symbol === undefinedSymbol || isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { + error(exportedName, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, ts.idText(exportedName)); + } + else { + markExportAsReferenced(node); + } + } + } + function checkExportAssignment(node) { + if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_export_assignment_can_only_be_used_in_a_module)) { + // If we hit an export assignment in an illegal context, just bail out to avoid cascading errors. + return; + } + var container = node.parent.kind === 279 /* SourceFile */ ? node.parent : node.parent.parent; + if (container.kind === 244 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) { + if (node.isExportEquals) { + error(node, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_namespace); + } + else { + error(node, ts.Diagnostics.A_default_export_can_only_be_used_in_an_ECMAScript_style_module); + } + return; + } + // Grammar checking + if (!checkGrammarDecoratorsAndModifiers(node) && ts.hasModifiers(node)) { + grammarErrorOnFirstToken(node, ts.Diagnostics.An_export_assignment_cannot_have_modifiers); + } + if (node.expression.kind === 72 /* Identifier */) { + markExportAsReferenced(node); + if (ts.getEmitDeclarations(compilerOptions)) { + collectLinkedAliases(node.expression, /*setVisibility*/ true); + } + } + else { + checkExpressionCached(node.expression); + } + checkExternalModuleExports(container); + if ((node.flags & 4194304 /* Ambient */) && !ts.isEntityNameExpression(node.expression)) { + grammarErrorOnNode(node.expression, ts.Diagnostics.The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context); + } + if (node.isExportEquals && !(node.flags & 4194304 /* Ambient */)) { + if (moduleKind >= ts.ModuleKind.ES2015) { + // export assignment is not supported in es6 modules + grammarErrorOnNode(node, ts.Diagnostics.Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or_another_module_format_instead); + } + else if (moduleKind === ts.ModuleKind.System) { + // system modules does not support export assignment + grammarErrorOnNode(node, ts.Diagnostics.Export_assignment_is_not_supported_when_module_flag_is_system); + } + } + } + function hasExportedMembers(moduleSymbol) { + return ts.forEachEntry(moduleSymbol.exports, function (_, id) { return id !== "export="; }); + } + function checkExternalModuleExports(node) { + var moduleSymbol = getSymbolOfNode(node); + var links = getSymbolLinks(moduleSymbol); + if (!links.exportsChecked) { + var exportEqualsSymbol = moduleSymbol.exports.get("export="); + if (exportEqualsSymbol && hasExportedMembers(moduleSymbol)) { + var declaration = getDeclarationOfAliasSymbol(exportEqualsSymbol) || exportEqualsSymbol.valueDeclaration; + if (!isTopLevelInExternalModuleAugmentation(declaration) && !ts.isInJSFile(declaration)) { + error(declaration, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements); + } + } + // Checks for export * conflicts + var exports_1 = getExportsOfModule(moduleSymbol); + if (exports_1) { + exports_1.forEach(function (_a, id) { + var declarations = _a.declarations, flags = _a.flags; + if (id === "__export") { + return; + } + // ECMA262: 15.2.1.1 It is a Syntax Error if the ExportedNames of ModuleItemList contains any duplicate entries. + // (TS Exceptions: namespaces, function overloads, enums, and interfaces) + if (flags & (1920 /* Namespace */ | 64 /* Interface */ | 384 /* Enum */)) { + return; + } + var exportedDeclarationsCount = ts.countWhere(declarations, isNotOverloadAndNotAccessor); + if (flags & 524288 /* TypeAlias */ && exportedDeclarationsCount <= 2) { + // it is legal to merge type alias with other values + // so count should be either 1 (just type alias) or 2 (type alias + merged value) + return; + } + if (exportedDeclarationsCount > 1) { + for (var _i = 0, declarations_9 = declarations; _i < declarations_9.length; _i++) { + var declaration = declarations_9[_i]; + if (isNotOverload(declaration)) { + diagnostics.add(ts.createDiagnosticForNode(declaration, ts.Diagnostics.Cannot_redeclare_exported_variable_0, ts.unescapeLeadingUnderscores(id))); + } + } + } + }); + } + links.exportsChecked = true; + } + } + function isNotAccessor(declaration) { + // Accessors check for their own matching duplicates, and in contexts where they are valid, there are already duplicate identifier checks + return !ts.isAccessor(declaration); + } + function isNotOverload(declaration) { + return (declaration.kind !== 239 /* FunctionDeclaration */ && declaration.kind !== 156 /* MethodDeclaration */) || + !!declaration.body; + } + function checkSourceElement(node) { + if (!node) { + return; + } + if (ts.isInJSFile(node)) { + ts.forEach(node.jsDoc, function (_a) { + var tags = _a.tags; + return ts.forEach(tags, checkSourceElement); + }); + } + var kind = node.kind; + if (cancellationToken) { + // Only bother checking on a few construct kinds. We don't want to be excessively + // hitting the cancellation token on every node we check. + switch (kind) { + case 244 /* ModuleDeclaration */: + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + case 239 /* FunctionDeclaration */: + cancellationToken.throwIfCancellationRequested(); + } + } + switch (kind) { + case 150 /* TypeParameter */: + return checkTypeParameter(node); + case 151 /* Parameter */: + return checkParameter(node); + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + return checkPropertyDeclaration(node); + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 162 /* IndexSignature */: + return checkSignatureDeclaration(node); + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + return checkMethodDeclaration(node); + case 157 /* Constructor */: + return checkConstructorDeclaration(node); + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + return checkAccessorDeclaration(node); + case 164 /* TypeReference */: + return checkTypeReferenceNode(node); + case 163 /* TypePredicate */: + return checkTypePredicate(node); + case 167 /* TypeQuery */: + return checkTypeQuery(node); + case 168 /* TypeLiteral */: + return checkTypeLiteral(node); + case 169 /* ArrayType */: + return checkArrayType(node); + case 170 /* TupleType */: + return checkTupleType(node); + case 173 /* UnionType */: + case 174 /* IntersectionType */: + return checkUnionOrIntersectionType(node); + case 177 /* ParenthesizedType */: + case 171 /* OptionalType */: + case 172 /* RestType */: + return checkSourceElement(node.type); + case 178 /* ThisType */: + return checkThisType(node); + case 179 /* TypeOperator */: + return checkTypeOperator(node); + case 175 /* ConditionalType */: + return checkConditionalType(node); + case 176 /* InferType */: + return checkInferType(node); + case 183 /* ImportType */: + return checkImportType(node); + case 295 /* JSDocAugmentsTag */: + return checkJSDocAugmentsTag(node); + case 304 /* JSDocTypedefTag */: + case 297 /* JSDocCallbackTag */: + return checkJSDocTypeAliasTag(node); + case 303 /* JSDocTemplateTag */: + return checkJSDocTemplateTag(node); + case 302 /* JSDocTypeTag */: + return checkJSDocTypeTag(node); + case 299 /* JSDocParameterTag */: + return checkJSDocParameterTag(node); + case 289 /* JSDocFunctionType */: + checkJSDocFunctionType(node); + // falls through + case 287 /* JSDocNonNullableType */: + case 286 /* JSDocNullableType */: + case 284 /* JSDocAllType */: + case 285 /* JSDocUnknownType */: + case 292 /* JSDocTypeLiteral */: + checkJSDocTypeIsInJsFile(node); + ts.forEachChild(node, checkSourceElement); + return; + case 290 /* JSDocVariadicType */: + checkJSDocVariadicType(node); + return; + case 283 /* JSDocTypeExpression */: + return checkSourceElement(node.type); + case 180 /* IndexedAccessType */: + return checkIndexedAccessType(node); + case 181 /* MappedType */: + return checkMappedType(node); + case 239 /* FunctionDeclaration */: + return checkFunctionDeclaration(node); + case 218 /* Block */: + case 245 /* ModuleBlock */: + return checkBlock(node); + case 219 /* VariableStatement */: + return checkVariableStatement(node); + case 221 /* ExpressionStatement */: + return checkExpressionStatement(node); + case 222 /* IfStatement */: + return checkIfStatement(node); + case 223 /* DoStatement */: + return checkDoStatement(node); + case 224 /* WhileStatement */: + return checkWhileStatement(node); + case 225 /* ForStatement */: + return checkForStatement(node); + case 226 /* ForInStatement */: + return checkForInStatement(node); + case 227 /* ForOfStatement */: + return checkForOfStatement(node); + case 228 /* ContinueStatement */: + case 229 /* BreakStatement */: + return checkBreakOrContinueStatement(node); + case 230 /* ReturnStatement */: + return checkReturnStatement(node); + case 231 /* WithStatement */: + return checkWithStatement(node); + case 232 /* SwitchStatement */: + return checkSwitchStatement(node); + case 233 /* LabeledStatement */: + return checkLabeledStatement(node); + case 234 /* ThrowStatement */: + return checkThrowStatement(node); + case 235 /* TryStatement */: + return checkTryStatement(node); + case 237 /* VariableDeclaration */: + return checkVariableDeclaration(node); + case 186 /* BindingElement */: + return checkBindingElement(node); + case 240 /* ClassDeclaration */: + return checkClassDeclaration(node); + case 241 /* InterfaceDeclaration */: + return checkInterfaceDeclaration(node); + case 242 /* TypeAliasDeclaration */: + return checkTypeAliasDeclaration(node); + case 243 /* EnumDeclaration */: + return checkEnumDeclaration(node); + case 244 /* ModuleDeclaration */: + return checkModuleDeclaration(node); + case 249 /* ImportDeclaration */: + return checkImportDeclaration(node); + case 248 /* ImportEqualsDeclaration */: + return checkImportEqualsDeclaration(node); + case 255 /* ExportDeclaration */: + return checkExportDeclaration(node); + case 254 /* ExportAssignment */: + return checkExportAssignment(node); + case 220 /* EmptyStatement */: + case 236 /* DebuggerStatement */: + checkGrammarStatementInAmbientContext(node); + return; + case 258 /* MissingDeclaration */: + return checkMissingDeclaration(node); + } + } + function checkJSDocTypeIsInJsFile(node) { + if (!ts.isInJSFile(node)) { + grammarErrorOnNode(node, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments); + } + } + function checkJSDocVariadicType(node) { + checkJSDocTypeIsInJsFile(node); + checkSourceElement(node.type); + // Only legal location is in the *last* parameter tag or last parameter of a JSDoc function. + var parent = node.parent; + if (ts.isParameter(parent) && ts.isJSDocFunctionType(parent.parent)) { + if (ts.last(parent.parent.parameters) !== parent) { + error(node, ts.Diagnostics.A_rest_parameter_must_be_last_in_a_parameter_list); + } + return; + } + if (!ts.isJSDocTypeExpression(parent)) { + error(node, ts.Diagnostics.JSDoc_may_only_appear_in_the_last_parameter_of_a_signature); + } + var paramTag = node.parent.parent; + if (!ts.isJSDocParameterTag(paramTag)) { + error(node, ts.Diagnostics.JSDoc_may_only_appear_in_the_last_parameter_of_a_signature); + return; + } + var param = ts.getParameterSymbolFromJSDoc(paramTag); + if (!param) { + // We will error in `checkJSDocParameterTag`. + return; + } + var host = ts.getHostSignatureFromJSDoc(paramTag); + if (!host || ts.last(host.parameters).symbol !== param) { + error(node, ts.Diagnostics.A_rest_parameter_must_be_last_in_a_parameter_list); + } + } + function getTypeFromJSDocVariadicType(node) { + var type = getTypeFromTypeNode(node.type); + var parent = node.parent; + var paramTag = node.parent.parent; + if (ts.isJSDocTypeExpression(node.parent) && ts.isJSDocParameterTag(paramTag)) { + // Else we will add a diagnostic, see `checkJSDocVariadicType`. + var host_1 = ts.getHostSignatureFromJSDoc(paramTag); + if (host_1) { + /* + Only return an array type if the corresponding parameter is marked as a rest parameter, or if there are no parameters. + So in the following situation we will not create an array type: + /** @param {...number} a * / + function f(a) {} + Because `a` will just be of type `number | undefined`. A synthetic `...args` will also be added, which *will* get an array type. + */ + var lastParamDeclaration = ts.lastOrUndefined(host_1.parameters); + var symbol = ts.getParameterSymbolFromJSDoc(paramTag); + if (!lastParamDeclaration || + symbol && lastParamDeclaration.symbol === symbol && ts.isRestParameter(lastParamDeclaration)) { + return createArrayType(type); + } + } + } + if (ts.isParameter(parent) && ts.isJSDocFunctionType(parent.parent)) { + return createArrayType(type); + } + return addOptionality(type); + } + // Function and class expression bodies are checked after all statements in the enclosing body. This is + // to ensure constructs like the following are permitted: + // const foo = function () { + // const s = foo(); + // return "hello"; + // } + // Here, performing a full type check of the body of the function expression whilst in the process of + // determining the type of foo would cause foo to be given type any because of the recursive reference. + // Delaying the type check of the body ensures foo has been assigned a type. + function checkNodeDeferred(node) { + var enclosingFile = ts.getSourceFileOfNode(node); + var links = getNodeLinks(enclosingFile); + if (!(links.flags & 1 /* TypeChecked */)) { + links.deferredNodes = links.deferredNodes || ts.createMap(); + var id = "" + getNodeId(node); + links.deferredNodes.set(id, node); + } + } + function checkDeferredNodes(context) { + var links = getNodeLinks(context); + if (!links.deferredNodes) { + return; + } + links.deferredNodes.forEach(function (node) { + switch (node.kind) { + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + checkFunctionExpressionOrObjectLiteralMethodDeferred(node); + break; + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + checkAccessorDeclaration(node); + break; + case 209 /* ClassExpression */: + checkClassExpressionDeferred(node); + break; + case 261 /* JsxSelfClosingElement */: + checkJsxSelfClosingElementDeferred(node); + break; + case 260 /* JsxElement */: + checkJsxElementDeferred(node); + break; + } + }); + } + function checkSourceFile(node) { + ts.performance.mark("beforeCheck"); + checkSourceFileWorker(node); + ts.performance.mark("afterCheck"); + ts.performance.measure("Check", "beforeCheck", "afterCheck"); + } + function unusedIsError(kind) { + switch (kind) { + case 0 /* Local */: + return !!compilerOptions.noUnusedLocals; + case 1 /* Parameter */: + return !!compilerOptions.noUnusedParameters; + default: + return ts.Debug.assertNever(kind); + } + } + function getPotentiallyUnusedIdentifiers(sourceFile) { + return allPotentiallyUnusedIdentifiers.get(sourceFile.path) || ts.emptyArray; + } + // Fully type check a source file and collect the relevant diagnostics. + function checkSourceFileWorker(node) { + var links = getNodeLinks(node); + if (!(links.flags & 1 /* TypeChecked */)) { + if (ts.skipTypeChecking(node, compilerOptions)) { + return; + } + // Grammar checking + checkGrammarSourceFile(node); + ts.clear(potentialThisCollisions); + ts.clear(potentialNewTargetCollisions); + ts.forEach(node.statements, checkSourceElement); + checkSourceElement(node.endOfFileToken); + checkDeferredNodes(node); + if (ts.isExternalOrCommonJsModule(node)) { + registerForUnusedIdentifiersCheck(node); + } + if (!node.isDeclarationFile && (compilerOptions.noUnusedLocals || compilerOptions.noUnusedParameters)) { + checkUnusedIdentifiers(getPotentiallyUnusedIdentifiers(node), function (containingNode, kind, diag) { + if (!ts.containsParseError(containingNode) && unusedIsError(kind)) { + diagnostics.add(diag); + } + }); + } + if (ts.isExternalOrCommonJsModule(node)) { + checkExternalModuleExports(node); + } + if (potentialThisCollisions.length) { + ts.forEach(potentialThisCollisions, checkIfThisIsCapturedInEnclosingScope); + ts.clear(potentialThisCollisions); + } + if (potentialNewTargetCollisions.length) { + ts.forEach(potentialNewTargetCollisions, checkIfNewTargetIsCapturedInEnclosingScope); + ts.clear(potentialNewTargetCollisions); + } + links.flags |= 1 /* TypeChecked */; + } + } + function getDiagnostics(sourceFile, ct) { + try { + // Record the cancellation token so it can be checked later on during checkSourceElement. + // Do this in a finally block so we can ensure that it gets reset back to nothing after + // this call is done. + cancellationToken = ct; + return getDiagnosticsWorker(sourceFile); + } + finally { + cancellationToken = undefined; + } + } + function getDiagnosticsWorker(sourceFile) { + throwIfNonDiagnosticsProducing(); + if (sourceFile) { + // Some global diagnostics are deferred until they are needed and + // may not be reported in the firt call to getGlobalDiagnostics. + // We should catch these changes and report them. + var previousGlobalDiagnostics = diagnostics.getGlobalDiagnostics(); + var previousGlobalDiagnosticsSize = previousGlobalDiagnostics.length; + checkSourceFile(sourceFile); + var semanticDiagnostics = diagnostics.getDiagnostics(sourceFile.fileName); + var currentGlobalDiagnostics = diagnostics.getGlobalDiagnostics(); + if (currentGlobalDiagnostics !== previousGlobalDiagnostics) { + // If the arrays are not the same reference, new diagnostics were added. + var deferredGlobalDiagnostics = ts.relativeComplement(previousGlobalDiagnostics, currentGlobalDiagnostics, ts.compareDiagnostics); + return ts.concatenate(deferredGlobalDiagnostics, semanticDiagnostics); + } + else if (previousGlobalDiagnosticsSize === 0 && currentGlobalDiagnostics.length > 0) { + // If the arrays are the same reference, but the length has changed, a single + // new diagnostic was added as DiagnosticCollection attempts to reuse the + // same array. + return ts.concatenate(currentGlobalDiagnostics, semanticDiagnostics); + } + return semanticDiagnostics; + } + // Global diagnostics are always added when a file is not provided to + // getDiagnostics + ts.forEach(host.getSourceFiles(), checkSourceFile); + return diagnostics.getDiagnostics(); + } + function getGlobalDiagnostics() { + throwIfNonDiagnosticsProducing(); + return diagnostics.getGlobalDiagnostics(); + } + function throwIfNonDiagnosticsProducing() { + if (!produceDiagnostics) { + throw new Error("Trying to get diagnostics from a type checker that does not produce them."); + } + } + // Language service support + function getSymbolsInScope(location, meaning) { + if (location.flags & 8388608 /* InWithStatement */) { + // We cannot answer semantic questions within a with block, do not proceed any further + return []; + } + var symbols = ts.createSymbolTable(); + var isStatic = false; + populateSymbols(); + symbols.delete("this" /* This */); // Not a symbol, a keyword + return symbolsToArray(symbols); + function populateSymbols() { + while (location) { + if (location.locals && !isGlobalSourceFile(location)) { + copySymbols(location.locals, meaning); + } + switch (location.kind) { + case 279 /* SourceFile */: + if (!ts.isExternalOrCommonJsModule(location)) + break; + // falls through + case 244 /* ModuleDeclaration */: + copySymbols(getSymbolOfNode(location).exports, meaning & 2623475 /* ModuleMember */); + break; + case 243 /* EnumDeclaration */: + copySymbols(getSymbolOfNode(location).exports, meaning & 8 /* EnumMember */); + break; + case 209 /* ClassExpression */: + var className = location.name; + if (className) { + copySymbol(location.symbol, meaning); + } + // falls through + // this fall-through is necessary because we would like to handle + // type parameter inside class expression similar to how we handle it in classDeclaration and interface Declaration + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + // If we didn't come from static member of class or interface, + // add the type parameters into the symbol table + // (type parameters of classDeclaration/classExpression and interface are in member property of the symbol. + // Note: that the memberFlags come from previous iteration. + if (!isStatic) { + copySymbols(getMembersOfSymbol(getSymbolOfNode(location)), meaning & 67897832 /* Type */); + } + break; + case 196 /* FunctionExpression */: + var funcName = location.name; + if (funcName) { + copySymbol(location.symbol, meaning); + } + break; + } + if (ts.introducesArgumentsExoticObject(location)) { + copySymbol(argumentsSymbol, meaning); + } + isStatic = ts.hasModifier(location, 32 /* Static */); + location = location.parent; + } + copySymbols(globals, meaning); + } + /** + * Copy the given symbol into symbol tables if the symbol has the given meaning + * and it doesn't already existed in the symbol table + * @param key a key for storing in symbol table; if undefined, use symbol.name + * @param symbol the symbol to be added into symbol table + * @param meaning meaning of symbol to filter by before adding to symbol table + */ + function copySymbol(symbol, meaning) { + if (ts.getCombinedLocalAndExportSymbolFlags(symbol) & meaning) { + var id = symbol.escapedName; + // We will copy all symbol regardless of its reserved name because + // symbolsToArray will check whether the key is a reserved name and + // it will not copy symbol with reserved name to the array + if (!symbols.has(id)) { + symbols.set(id, symbol); + } + } + } + function copySymbols(source, meaning) { + if (meaning) { + source.forEach(function (symbol) { + copySymbol(symbol, meaning); + }); + } + } + } + function isTypeDeclarationName(name) { + return name.kind === 72 /* Identifier */ && + isTypeDeclaration(name.parent) && + name.parent.name === name; + } + function isTypeDeclaration(node) { + switch (node.kind) { + case 150 /* TypeParameter */: + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 243 /* EnumDeclaration */: + return true; + default: + return false; + } + } + // True if the given identifier is part of a type reference + function isTypeReferenceIdentifier(node) { + while (node.parent.kind === 148 /* QualifiedName */) { + node = node.parent; + } + return node.parent.kind === 164 /* TypeReference */; + } + function isHeritageClauseElementIdentifier(node) { + while (node.parent.kind === 189 /* PropertyAccessExpression */) { + node = node.parent; + } + return node.parent.kind === 211 /* ExpressionWithTypeArguments */; + } + function forEachEnclosingClass(node, callback) { + var result; + while (true) { + node = ts.getContainingClass(node); + if (!node) + break; + if (result = callback(node)) + break; + } + return result; + } + function isNodeUsedDuringClassInitialization(node) { + return !!ts.findAncestor(node, function (element) { + if (ts.isConstructorDeclaration(element) && ts.nodeIsPresent(element.body) || ts.isPropertyDeclaration(element)) { + return true; + } + else if (ts.isClassLike(element) || ts.isFunctionLikeDeclaration(element)) { + return "quit"; + } + return false; + }); + } + function isNodeWithinClass(node, classDeclaration) { + return !!forEachEnclosingClass(node, function (n) { return n === classDeclaration; }); + } + function getLeftSideOfImportEqualsOrExportAssignment(nodeOnRightSide) { + while (nodeOnRightSide.parent.kind === 148 /* QualifiedName */) { + nodeOnRightSide = nodeOnRightSide.parent; + } + if (nodeOnRightSide.parent.kind === 248 /* ImportEqualsDeclaration */) { + return nodeOnRightSide.parent.moduleReference === nodeOnRightSide ? nodeOnRightSide.parent : undefined; + } + if (nodeOnRightSide.parent.kind === 254 /* ExportAssignment */) { + return nodeOnRightSide.parent.expression === nodeOnRightSide ? nodeOnRightSide.parent : undefined; + } + return undefined; + } + function isInRightSideOfImportOrExportAssignment(node) { + return getLeftSideOfImportEqualsOrExportAssignment(node) !== undefined; + } + function getSpecialPropertyAssignmentSymbolFromEntityName(entityName) { + var specialPropertyAssignmentKind = ts.getAssignmentDeclarationKind(entityName.parent.parent); + switch (specialPropertyAssignmentKind) { + case 1 /* ExportsProperty */: + case 3 /* PrototypeProperty */: + return getSymbolOfNode(entityName.parent); + case 4 /* ThisProperty */: + case 2 /* ModuleExports */: + case 5 /* Property */: + return getSymbolOfNode(entityName.parent.parent); + } + } + function isImportTypeQualifierPart(node) { + var parent = node.parent; + while (ts.isQualifiedName(parent)) { + node = parent; + parent = parent.parent; + } + if (parent && parent.kind === 183 /* ImportType */ && parent.qualifier === node) { + return parent; + } + return undefined; + } + function getSymbolOfEntityNameOrPropertyAccessExpression(entityName) { + if (ts.isDeclarationName(entityName)) { + return getSymbolOfNode(entityName.parent); + } + if (ts.isInJSFile(entityName) && + entityName.parent.kind === 189 /* PropertyAccessExpression */ && + entityName.parent === entityName.parent.parent.left) { + // Check if this is a special property assignment + var specialPropertyAssignmentSymbol = getSpecialPropertyAssignmentSymbolFromEntityName(entityName); + if (specialPropertyAssignmentSymbol) { + return specialPropertyAssignmentSymbol; + } + } + if (entityName.parent.kind === 254 /* ExportAssignment */ && ts.isEntityNameExpression(entityName)) { + // Even an entity name expression that doesn't resolve as an entityname may still typecheck as a property access expression + var success = resolveEntityName(entityName, + /*all meanings*/ 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*ignoreErrors*/ true); + if (success && success !== unknownSymbol) { + return success; + } + } + else if (!ts.isPropertyAccessExpression(entityName) && isInRightSideOfImportOrExportAssignment(entityName)) { + // Since we already checked for ExportAssignment, this really could only be an Import + var importEqualsDeclaration = ts.getAncestor(entityName, 248 /* ImportEqualsDeclaration */); + ts.Debug.assert(importEqualsDeclaration !== undefined); + return getSymbolOfPartOfRightHandSideOfImportEquals(entityName, /*dontResolveAlias*/ true); + } + if (!ts.isPropertyAccessExpression(entityName)) { + var possibleImportNode = isImportTypeQualifierPart(entityName); + if (possibleImportNode) { + getTypeFromTypeNode(possibleImportNode); + var sym = getNodeLinks(entityName).resolvedSymbol; + return sym === unknownSymbol ? undefined : sym; + } + } + while (ts.isRightSideOfQualifiedNameOrPropertyAccess(entityName)) { + entityName = entityName.parent; + } + if (isHeritageClauseElementIdentifier(entityName)) { + var meaning = 0 /* None */; + // In an interface or class, we're definitely interested in a type. + if (entityName.parent.kind === 211 /* ExpressionWithTypeArguments */) { + meaning = 67897832 /* Type */; + // In a class 'extends' clause we are also looking for a value. + if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent)) { + meaning |= 67220415 /* Value */; + } + } + else { + meaning = 1920 /* Namespace */; + } + meaning |= 2097152 /* Alias */; + var entityNameSymbol = ts.isEntityNameExpression(entityName) ? resolveEntityName(entityName, meaning) : undefined; + if (entityNameSymbol) { + return entityNameSymbol; + } + } + if (entityName.parent.kind === 299 /* JSDocParameterTag */) { + return ts.getParameterSymbolFromJSDoc(entityName.parent); + } + if (entityName.parent.kind === 150 /* TypeParameter */ && entityName.parent.parent.kind === 303 /* JSDocTemplateTag */) { + ts.Debug.assert(!ts.isInJSFile(entityName)); // Otherwise `isDeclarationName` would have been true. + var typeParameter = ts.getTypeParameterFromJsDoc(entityName.parent); + return typeParameter && typeParameter.symbol; + } + if (ts.isExpressionNode(entityName)) { + if (ts.nodeIsMissing(entityName)) { + // Missing entity name. + return undefined; + } + if (entityName.kind === 72 /* Identifier */) { + if (ts.isJSXTagName(entityName) && isJsxIntrinsicIdentifier(entityName)) { + var symbol = getIntrinsicTagSymbol(entityName.parent); + return symbol === unknownSymbol ? undefined : symbol; + } + return resolveEntityName(entityName, 67220415 /* Value */, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); + } + else if (entityName.kind === 189 /* PropertyAccessExpression */ || entityName.kind === 148 /* QualifiedName */) { + var links = getNodeLinks(entityName); + if (links.resolvedSymbol) { + return links.resolvedSymbol; + } + if (entityName.kind === 189 /* PropertyAccessExpression */) { + checkPropertyAccessExpression(entityName); + } + else { + checkQualifiedName(entityName); + } + return links.resolvedSymbol; + } + } + else if (isTypeReferenceIdentifier(entityName)) { + var meaning = entityName.parent.kind === 164 /* TypeReference */ ? 67897832 /* Type */ : 1920 /* Namespace */; + return resolveEntityName(entityName, meaning, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); + } + if (entityName.parent.kind === 163 /* TypePredicate */) { + return resolveEntityName(entityName, /*meaning*/ 1 /* FunctionScopedVariable */); + } + // Do we want to return undefined here? + return undefined; + } + function getSymbolAtLocation(node) { + if (node.kind === 279 /* SourceFile */) { + return ts.isExternalModule(node) ? getMergedSymbol(node.symbol) : undefined; + } + var parent = node.parent; + var grandParent = parent.parent; + if (node.flags & 8388608 /* InWithStatement */) { + // We cannot answer semantic questions within a with block, do not proceed any further + return undefined; + } + if (isDeclarationNameOrImportPropertyName(node)) { + // This is a declaration, call getSymbolOfNode + var parentSymbol = getSymbolOfNode(parent); + return ts.isImportOrExportSpecifier(node.parent) && node.parent.propertyName === node + ? getImmediateAliasedSymbol(parentSymbol) + : parentSymbol; + } + else if (ts.isLiteralComputedPropertyDeclarationName(node)) { + return getSymbolOfNode(parent.parent); + } + if (node.kind === 72 /* Identifier */) { + if (isInRightSideOfImportOrExportAssignment(node)) { + return getSymbolOfEntityNameOrPropertyAccessExpression(node); + } + else if (parent.kind === 186 /* BindingElement */ && + grandParent.kind === 184 /* ObjectBindingPattern */ && + node === parent.propertyName) { + var typeOfPattern = getTypeOfNode(grandParent); + var propertyDeclaration = getPropertyOfType(typeOfPattern, node.escapedText); + if (propertyDeclaration) { + return propertyDeclaration; + } + } + } + switch (node.kind) { + case 72 /* Identifier */: + case 189 /* PropertyAccessExpression */: + case 148 /* QualifiedName */: + return getSymbolOfEntityNameOrPropertyAccessExpression(node); + case 100 /* ThisKeyword */: + var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); + if (ts.isFunctionLike(container)) { + var sig = getSignatureFromDeclaration(container); + if (sig.thisParameter) { + return sig.thisParameter; + } + } + if (ts.isInExpressionContext(node)) { + return checkExpression(node).symbol; + } + // falls through + case 178 /* ThisType */: + return getTypeFromThisTypeNode(node).symbol; + case 98 /* SuperKeyword */: + return checkExpression(node).symbol; + case 124 /* ConstructorKeyword */: + // constructor keyword for an overload, should take us to the definition if it exist + var constructorDeclaration = node.parent; + if (constructorDeclaration && constructorDeclaration.kind === 157 /* Constructor */) { + return constructorDeclaration.parent.symbol; + } + return undefined; + case 10 /* StringLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: + // 1). import x = require("./mo/*gotToDefinitionHere*/d") + // 2). External module name in an import declaration + // 3). Dynamic import call or require in javascript + // 4). type A = import("./f/*gotToDefinitionHere*/oo") + if ((ts.isExternalModuleImportEqualsDeclaration(node.parent.parent) && ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node) || + ((node.parent.kind === 249 /* ImportDeclaration */ || node.parent.kind === 255 /* ExportDeclaration */) && node.parent.moduleSpecifier === node) || + ((ts.isInJSFile(node) && ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteralLike*/ false)) || ts.isImportCall(node.parent)) || + (ts.isLiteralTypeNode(node.parent) && ts.isLiteralImportTypeNode(node.parent.parent) && node.parent.parent.argument === node.parent)) { + return resolveExternalModuleName(node, node); + } + if (ts.isCallExpression(parent) && ts.isBindableObjectDefinePropertyCall(parent) && parent.arguments[1] === node) { + return getSymbolOfNode(parent); + } + // falls through + case 8 /* NumericLiteral */: + // index access + var objectType = ts.isElementAccessExpression(parent) + ? parent.argumentExpression === node ? getTypeOfExpression(parent.expression) : undefined + : ts.isLiteralTypeNode(parent) && ts.isIndexedAccessTypeNode(grandParent) + ? getTypeFromTypeNode(grandParent.objectType) + : undefined; + return objectType && getPropertyOfType(objectType, ts.escapeLeadingUnderscores(node.text)); + case 80 /* DefaultKeyword */: + case 90 /* FunctionKeyword */: + case 37 /* EqualsGreaterThanToken */: + case 76 /* ClassKeyword */: + return getSymbolOfNode(node.parent); + case 183 /* ImportType */: + return ts.isLiteralImportTypeNode(node) ? getSymbolAtLocation(node.argument.literal) : undefined; + case 85 /* ExportKeyword */: + return ts.isExportAssignment(node.parent) ? ts.Debug.assertDefined(node.parent.symbol) : undefined; + default: + return undefined; + } + } + function getShorthandAssignmentValueSymbol(location) { + if (location && location.kind === 276 /* ShorthandPropertyAssignment */) { + return resolveEntityName(location.name, 67220415 /* Value */ | 2097152 /* Alias */); + } + return undefined; + } + /** Returns the target of an export specifier without following aliases */ + function getExportSpecifierLocalTargetSymbol(node) { + return node.parent.parent.moduleSpecifier ? + getExternalModuleMember(node.parent.parent, node) : + resolveEntityName(node.propertyName || node.name, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); + } + function getTypeOfNode(node) { + if (node.flags & 8388608 /* InWithStatement */) { + // We cannot answer semantic questions within a with block, do not proceed any further + return errorType; + } + var classDecl = ts.tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node); + var classType = classDecl && getDeclaredTypeOfClassOrInterface(getSymbolOfNode(classDecl.class)); + if (ts.isPartOfTypeNode(node)) { + var typeFromTypeNode = getTypeFromTypeNode(node); + return classType ? getTypeWithThisArgument(typeFromTypeNode, classType.thisType) : typeFromTypeNode; + } + if (ts.isExpressionNode(node)) { + return getRegularTypeOfExpression(node); + } + if (classType && !classDecl.isImplements) { + // A SyntaxKind.ExpressionWithTypeArguments is considered a type node, except when it occurs in the + // extends clause of a class. We handle that case here. + var baseType = ts.firstOrUndefined(getBaseTypes(classType)); + return baseType ? getTypeWithThisArgument(baseType, classType.thisType) : errorType; + } + if (isTypeDeclaration(node)) { + // In this case, we call getSymbolOfNode instead of getSymbolAtLocation because it is a declaration + var symbol = getSymbolOfNode(node); + return getDeclaredTypeOfSymbol(symbol); + } + if (isTypeDeclarationName(node)) { + var symbol = getSymbolAtLocation(node); + return symbol ? getDeclaredTypeOfSymbol(symbol) : errorType; + } + if (ts.isDeclaration(node)) { + // In this case, we call getSymbolOfNode instead of getSymbolAtLocation because it is a declaration + var symbol = getSymbolOfNode(node); + return getTypeOfSymbol(symbol); + } + if (isDeclarationNameOrImportPropertyName(node)) { + var symbol = getSymbolAtLocation(node); + return symbol ? getTypeOfSymbol(symbol) : errorType; + } + if (ts.isBindingPattern(node)) { + return getTypeForVariableLikeDeclaration(node.parent, /*includeOptionality*/ true) || errorType; + } + if (isInRightSideOfImportOrExportAssignment(node)) { + var symbol = getSymbolAtLocation(node); + if (symbol) { + var declaredType = getDeclaredTypeOfSymbol(symbol); + return declaredType !== errorType ? declaredType : getTypeOfSymbol(symbol); + } + } + return errorType; + } + // Gets the type of object literal or array literal of destructuring assignment. + // { a } from + // for ( { a } of elems) { + // } + // [ a ] from + // [a] = [ some array ...] + function getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr) { + ts.Debug.assert(expr.kind === 188 /* ObjectLiteralExpression */ || expr.kind === 187 /* ArrayLiteralExpression */); + // If this is from "for of" + // for ( { a } of elems) { + // } + if (expr.parent.kind === 227 /* ForOfStatement */) { + var iteratedType = checkRightHandSideOfForOf(expr.parent.expression, expr.parent.awaitModifier); + return checkDestructuringAssignment(expr, iteratedType || errorType); + } + // If this is from "for" initializer + // for ({a } = elems[0];.....) { } + if (expr.parent.kind === 204 /* BinaryExpression */) { + var iteratedType = getTypeOfExpression(expr.parent.right); + return checkDestructuringAssignment(expr, iteratedType || errorType); + } + // If this is from nested object binding pattern + // for ({ skills: { primary, secondary } } = multiRobot, i = 0; i < 1; i++) { + if (expr.parent.kind === 275 /* PropertyAssignment */) { + var typeOfParentObjectLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr.parent.parent); + return checkObjectLiteralDestructuringPropertyAssignment(typeOfParentObjectLiteral || errorType, expr.parent); // TODO: GH#18217 + } + // Array literal assignment - array destructuring pattern + ts.Debug.assert(expr.parent.kind === 187 /* ArrayLiteralExpression */); + // [{ property1: p1, property2 }] = elems; + var typeOfArrayLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr.parent); + var elementType = checkIteratedTypeOrElementType(typeOfArrayLiteral || errorType, expr.parent, /*allowStringInput*/ false, /*allowAsyncIterables*/ false) || errorType; + return checkArrayLiteralDestructuringElementAssignment(expr.parent, typeOfArrayLiteral, expr.parent.elements.indexOf(expr), elementType || errorType); // TODO: GH#18217 + } + // Gets the property symbol corresponding to the property in destructuring assignment + // 'property1' from + // for ( { property1: a } of elems) { + // } + // 'property1' at location 'a' from: + // [a] = [ property1, property2 ] + function getPropertySymbolOfDestructuringAssignment(location) { + // Get the type of the object or array literal and then look for property of given name in the type + var typeOfObjectLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(location.parent.parent); + return typeOfObjectLiteral && getPropertyOfType(typeOfObjectLiteral, location.escapedText); + } + function getRegularTypeOfExpression(expr) { + if (ts.isRightSideOfQualifiedNameOrPropertyAccess(expr)) { + expr = expr.parent; + } + return getRegularTypeOfLiteralType(getTypeOfExpression(expr)); + } + /** + * Gets either the static or instance type of a class element, based on + * whether the element is declared as "static". + */ + function getParentTypeOfClassElement(node) { + var classSymbol = getSymbolOfNode(node.parent); + return ts.hasModifier(node, 32 /* Static */) + ? getTypeOfSymbol(classSymbol) + : getDeclaredTypeOfSymbol(classSymbol); + } + function getClassElementPropertyKeyType(element) { + var name = element.name; + switch (name.kind) { + case 72 /* Identifier */: + return getLiteralType(ts.idText(name)); + case 8 /* NumericLiteral */: + case 10 /* StringLiteral */: + return getLiteralType(name.text); + case 149 /* ComputedPropertyName */: + var nameType = checkComputedPropertyName(name); + return isTypeAssignableToKind(nameType, 12288 /* ESSymbolLike */) ? nameType : stringType; + default: + ts.Debug.fail("Unsupported property name."); + return errorType; + } + } + // Return the list of properties of the given type, augmented with properties from Function + // if the type has call or construct signatures + function getAugmentedPropertiesOfType(type) { + type = getApparentType(type); + var propsByName = ts.createSymbolTable(getPropertiesOfType(type)); + var functionType = getSignaturesOfType(type, 0 /* Call */).length ? globalCallableFunctionType : + getSignaturesOfType(type, 1 /* Construct */).length ? globalNewableFunctionType : + undefined; + if (functionType) { + ts.forEach(getPropertiesOfType(functionType), function (p) { + if (!propsByName.has(p.escapedName)) { + propsByName.set(p.escapedName, p); + } + }); + } + return getNamedMembers(propsByName); + } + function typeHasCallOrConstructSignatures(type) { + return ts.typeHasCallOrConstructSignatures(type, checker); + } + function getRootSymbols(symbol) { + var roots = getImmediateRootSymbols(symbol); + return roots ? ts.flatMap(roots, getRootSymbols) : [symbol]; + } + function getImmediateRootSymbols(symbol) { + if (ts.getCheckFlags(symbol) & 6 /* Synthetic */) { + return ts.mapDefined(getSymbolLinks(symbol).containingType.types, function (type) { return getPropertyOfType(type, symbol.escapedName); }); + } + else if (symbol.flags & 33554432 /* Transient */) { + var _a = symbol, leftSpread = _a.leftSpread, rightSpread = _a.rightSpread, syntheticOrigin = _a.syntheticOrigin; + return leftSpread ? [leftSpread, rightSpread] + : syntheticOrigin ? [syntheticOrigin] + : ts.singleElementArray(tryGetAliasTarget(symbol)); + } + return undefined; + } + function tryGetAliasTarget(symbol) { + var target; + var next = symbol; + while (next = getSymbolLinks(next).target) { + target = next; + } + return target; + } + // Emitter support + function isArgumentsLocalBinding(nodeIn) { + if (!ts.isGeneratedIdentifier(nodeIn)) { + var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier); + if (node) { + var isPropertyName_1 = node.parent.kind === 189 /* PropertyAccessExpression */ && node.parent.name === node; + return !isPropertyName_1 && getReferencedValueSymbol(node) === argumentsSymbol; + } + } + return false; + } + function moduleExportsSomeValue(moduleReferenceExpression) { + var moduleSymbol = resolveExternalModuleName(moduleReferenceExpression.parent, moduleReferenceExpression); + if (!moduleSymbol || ts.isShorthandAmbientModuleSymbol(moduleSymbol)) { + // If the module is not found or is shorthand, assume that it may export a value. + return true; + } + var hasExportAssignment = hasExportAssignmentSymbol(moduleSymbol); + // if module has export assignment then 'resolveExternalModuleSymbol' will return resolved symbol for export assignment + // otherwise it will return moduleSymbol itself + moduleSymbol = resolveExternalModuleSymbol(moduleSymbol); + var symbolLinks = getSymbolLinks(moduleSymbol); + if (symbolLinks.exportsSomeValue === undefined) { + // for export assignments - check if resolved symbol for RHS is itself a value + // otherwise - check if at least one export is value + symbolLinks.exportsSomeValue = hasExportAssignment + ? !!(moduleSymbol.flags & 67220415 /* Value */) + : ts.forEachEntry(getExportsOfModule(moduleSymbol), isValue); + } + return symbolLinks.exportsSomeValue; + function isValue(s) { + s = resolveSymbol(s); + return s && !!(s.flags & 67220415 /* Value */); + } + } + function isNameOfModuleOrEnumDeclaration(node) { + return ts.isModuleOrEnumDeclaration(node.parent) && node === node.parent.name; + } + // When resolved as an expression identifier, if the given node references an exported entity, return the declaration + // node of the exported entity's container. Otherwise, return undefined. + function getReferencedExportContainer(nodeIn, prefixLocals) { + var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier); + if (node) { + // When resolving the export container for the name of a module or enum + // declaration, we need to start resolution at the declaration's container. + // Otherwise, we could incorrectly resolve the export container as the + // declaration if it contains an exported member with the same name. + var symbol = getReferencedValueSymbol(node, /*startInDeclarationContainer*/ isNameOfModuleOrEnumDeclaration(node)); + if (symbol) { + if (symbol.flags & 1048576 /* ExportValue */) { + // If we reference an exported entity within the same module declaration, then whether + // we prefix depends on the kind of entity. SymbolFlags.ExportHasLocal encompasses all the + // kinds that we do NOT prefix. + var exportSymbol = getMergedSymbol(symbol.exportSymbol); + if (!prefixLocals && exportSymbol.flags & 944 /* ExportHasLocal */ && !(exportSymbol.flags & 3 /* Variable */)) { + return undefined; + } + symbol = exportSymbol; + } + var parentSymbol_1 = getParentOfSymbol(symbol); + if (parentSymbol_1) { + if (parentSymbol_1.flags & 512 /* ValueModule */ && parentSymbol_1.valueDeclaration.kind === 279 /* SourceFile */) { + var symbolFile = parentSymbol_1.valueDeclaration; + var referenceFile = ts.getSourceFileOfNode(node); + // If `node` accesses an export and that export isn't in the same file, then symbol is a namespace export, so return undefined. + var symbolIsUmdExport = symbolFile !== referenceFile; + return symbolIsUmdExport ? undefined : symbolFile; + } + return ts.findAncestor(node.parent, function (n) { return ts.isModuleOrEnumDeclaration(n) && getSymbolOfNode(n) === parentSymbol_1; }); + } + } + } + } + // When resolved as an expression identifier, if the given node references an import, return the declaration of + // that import. Otherwise, return undefined. + function getReferencedImportDeclaration(nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier); + if (node) { + var symbol = getReferencedValueSymbol(node); + // We should only get the declaration of an alias if there isn't a local value + // declaration for the symbol + if (isNonLocalAlias(symbol, /*excludes*/ 67220415 /* Value */)) { + return getDeclarationOfAliasSymbol(symbol); + } + } + return undefined; + } + function isSymbolOfDeclarationWithCollidingName(symbol) { + if (symbol.flags & 418 /* BlockScoped */) { + var links = getSymbolLinks(symbol); + if (links.isDeclarationWithCollidingName === undefined) { + var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); + if (ts.isStatementWithLocals(container)) { + var nodeLinks_1 = getNodeLinks(symbol.valueDeclaration); + if (resolveName(container.parent, symbol.escapedName, 67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)) { + // redeclaration - always should be renamed + links.isDeclarationWithCollidingName = true; + } + else if (nodeLinks_1.flags & 262144 /* CapturedBlockScopedBinding */) { + // binding is captured in the function + // should be renamed if: + // - binding is not top level - top level bindings never collide with anything + // AND + // - binding is not declared in loop, should be renamed to avoid name reuse across siblings + // let a, b + // { let x = 1; a = () => x; } + // { let x = 100; b = () => x; } + // console.log(a()); // should print '1' + // console.log(b()); // should print '100' + // OR + // - binding is declared inside loop but not in inside initializer of iteration statement or directly inside loop body + // * variables from initializer are passed to rewritten loop body as parameters so they are not captured directly + // * variables that are declared immediately in loop body will become top level variable after loop is rewritten and thus + // they will not collide with anything + var isDeclaredInLoop = nodeLinks_1.flags & 524288 /* BlockScopedBindingInLoop */; + var inLoopInitializer = ts.isIterationStatement(container, /*lookInLabeledStatements*/ false); + var inLoopBodyBlock = container.kind === 218 /* Block */ && ts.isIterationStatement(container.parent, /*lookInLabeledStatements*/ false); + links.isDeclarationWithCollidingName = !ts.isBlockScopedContainerTopLevel(container) && (!isDeclaredInLoop || (!inLoopInitializer && !inLoopBodyBlock)); + } + else { + links.isDeclarationWithCollidingName = false; + } + } + } + return links.isDeclarationWithCollidingName; + } + return false; + } + // When resolved as an expression identifier, if the given node references a nested block scoped entity with + // a name that either hides an existing name or might hide it when compiled downlevel, + // return the declaration of that entity. Otherwise, return undefined. + function getReferencedDeclarationWithCollidingName(nodeIn) { + if (!ts.isGeneratedIdentifier(nodeIn)) { + var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier); + if (node) { + var symbol = getReferencedValueSymbol(node); + if (symbol && isSymbolOfDeclarationWithCollidingName(symbol)) { + return symbol.valueDeclaration; + } + } + } + return undefined; + } + // Return true if the given node is a declaration of a nested block scoped entity with a name that either hides an + // existing name or might hide a name when compiled downlevel + function isDeclarationWithCollidingName(nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isDeclaration); + if (node) { + var symbol = getSymbolOfNode(node); + if (symbol) { + return isSymbolOfDeclarationWithCollidingName(symbol); + } + } + return false; + } + function isValueAliasDeclaration(node) { + switch (node.kind) { + case 248 /* ImportEqualsDeclaration */: + case 250 /* ImportClause */: + case 251 /* NamespaceImport */: + case 253 /* ImportSpecifier */: + case 257 /* ExportSpecifier */: + return isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol); + case 255 /* ExportDeclaration */: + var exportClause = node.exportClause; + return !!exportClause && ts.some(exportClause.elements, isValueAliasDeclaration); + case 254 /* ExportAssignment */: + return node.expression + && node.expression.kind === 72 /* Identifier */ + ? isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol) + : true; + } + return false; + } + function isTopLevelValueImportEqualsWithEntityName(nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isImportEqualsDeclaration); + if (node === undefined || node.parent.kind !== 279 /* SourceFile */ || !ts.isInternalModuleImportEqualsDeclaration(node)) { + // parent is not source file or it is not reference to internal module + return false; + } + var isValue = isAliasResolvedToValue(getSymbolOfNode(node)); + return isValue && node.moduleReference && !ts.nodeIsMissing(node.moduleReference); + } + function isAliasResolvedToValue(symbol) { + var target = resolveAlias(symbol); + if (target === unknownSymbol) { + return true; + } + // const enums and modules that contain only const enums are not considered values from the emit perspective + // unless 'preserveConstEnums' option is set to true + return !!(target.flags & 67220415 /* Value */) && + (compilerOptions.preserveConstEnums || !isConstEnumOrConstEnumOnlyModule(target)); + } + function isConstEnumOrConstEnumOnlyModule(s) { + return isConstEnumSymbol(s) || !!s.constEnumOnlyModule; + } + function isReferencedAliasDeclaration(node, checkChildren) { + if (ts.isAliasSymbolDeclaration(node)) { + var symbol = getSymbolOfNode(node); + if (symbol && getSymbolLinks(symbol).referenced) { + return true; + } + var target = getSymbolLinks(symbol).target; // TODO: GH#18217 + if (target && ts.getModifierFlags(node) & 1 /* Export */ && + target.flags & 67220415 /* Value */ && (compilerOptions.preserveConstEnums || !isConstEnumOrConstEnumOnlyModule(target))) { + // An `export import ... =` of a value symbol is always considered referenced + return true; + } + } + if (checkChildren) { + return !!ts.forEachChild(node, function (node) { return isReferencedAliasDeclaration(node, checkChildren); }); + } + return false; + } + function isImplementationOfOverload(node) { + if (ts.nodeIsPresent(node.body)) { + if (ts.isGetAccessor(node) || ts.isSetAccessor(node)) + return false; // Get or set accessors can never be overload implementations, but can have up to 2 signatures + var symbol = getSymbolOfNode(node); + var signaturesOfSymbol = getSignaturesOfSymbol(symbol); + // If this function body corresponds to function with multiple signature, it is implementation of overload + // e.g.: function foo(a: string): string; + // function foo(a: number): number; + // function foo(a: any) { // This is implementation of the overloads + // return a; + // } + return signaturesOfSymbol.length > 1 || + // If there is single signature for the symbol, it is overload if that signature isn't coming from the node + // e.g.: function foo(a: string): string; + // function foo(a: any) { // This is implementation of the overloads + // return a; + // } + (signaturesOfSymbol.length === 1 && signaturesOfSymbol[0].declaration !== node); + } + return false; + } + function isRequiredInitializedParameter(parameter) { + return !!strictNullChecks && + !isOptionalParameter(parameter) && + !ts.isJSDocParameterTag(parameter) && + !!parameter.initializer && + !ts.hasModifier(parameter, 92 /* ParameterPropertyModifier */); + } + function isOptionalUninitializedParameterProperty(parameter) { + return strictNullChecks && + isOptionalParameter(parameter) && + !parameter.initializer && + ts.hasModifier(parameter, 92 /* ParameterPropertyModifier */); + } + function isExpandoFunctionDeclaration(node) { + var declaration = ts.getParseTreeNode(node, ts.isFunctionDeclaration); + if (!declaration) { + return false; + } + var symbol = getSymbolOfNode(declaration); + if (!symbol || !(symbol.flags & 16 /* Function */)) { + return false; + } + return !!ts.forEachEntry(getExportsOfSymbol(symbol), function (p) { return p.flags & 67220415 /* Value */ && ts.isPropertyAccessExpression(p.valueDeclaration); }); + } + function getPropertiesOfContainerFunction(node) { + var declaration = ts.getParseTreeNode(node, ts.isFunctionDeclaration); + if (!declaration) { + return ts.emptyArray; + } + var symbol = getSymbolOfNode(declaration); + return symbol && getPropertiesOfType(getTypeOfSymbol(symbol)) || ts.emptyArray; + } + function getNodeCheckFlags(node) { + return getNodeLinks(node).flags || 0; + } + function getEnumMemberValue(node) { + computeEnumMemberValues(node.parent); + return getNodeLinks(node).enumMemberValue; + } + function canHaveConstantValue(node) { + switch (node.kind) { + case 278 /* EnumMember */: + case 189 /* PropertyAccessExpression */: + case 190 /* ElementAccessExpression */: + return true; + } + return false; + } + function getConstantValue(node) { + if (node.kind === 278 /* EnumMember */) { + return getEnumMemberValue(node); + } + var symbol = getNodeLinks(node).resolvedSymbol; + if (symbol && (symbol.flags & 8 /* EnumMember */)) { + // inline property\index accesses only for const enums + var member = symbol.valueDeclaration; + if (ts.isEnumConst(member.parent)) { + return getEnumMemberValue(member); + } + } + return undefined; + } + function isFunctionType(type) { + return !!(type.flags & 524288 /* Object */) && getSignaturesOfType(type, 0 /* Call */).length > 0; + } + function getTypeReferenceSerializationKind(typeNameIn, location) { + // ensure both `typeName` and `location` are parse tree nodes. + var typeName = ts.getParseTreeNode(typeNameIn, ts.isEntityName); + if (!typeName) + return ts.TypeReferenceSerializationKind.Unknown; + if (location) { + location = ts.getParseTreeNode(location); + if (!location) + return ts.TypeReferenceSerializationKind.Unknown; + } + // Resolve the symbol as a value to ensure the type can be reached at runtime during emit. + var valueSymbol = resolveEntityName(typeName, 67220415 /* Value */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location); + // Resolve the symbol as a type so that we can provide a more useful hint for the type serializer. + var typeSymbol = resolveEntityName(typeName, 67897832 /* Type */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location); + if (valueSymbol && valueSymbol === typeSymbol) { + var globalPromiseSymbol = getGlobalPromiseConstructorSymbol(/*reportErrors*/ false); + if (globalPromiseSymbol && valueSymbol === globalPromiseSymbol) { + return ts.TypeReferenceSerializationKind.Promise; + } + var constructorType = getTypeOfSymbol(valueSymbol); + if (constructorType && isConstructorType(constructorType)) { + return ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue; + } + } + // We might not be able to resolve type symbol so use unknown type in that case (eg error case) + if (!typeSymbol) { + return ts.TypeReferenceSerializationKind.Unknown; + } + var type = getDeclaredTypeOfSymbol(typeSymbol); + if (type === errorType) { + return ts.TypeReferenceSerializationKind.Unknown; + } + else if (type.flags & 3 /* AnyOrUnknown */) { + return ts.TypeReferenceSerializationKind.ObjectType; + } + else if (isTypeAssignableToKind(type, 16384 /* Void */ | 98304 /* Nullable */ | 131072 /* Never */)) { + return ts.TypeReferenceSerializationKind.VoidNullableOrNeverType; + } + else if (isTypeAssignableToKind(type, 528 /* BooleanLike */)) { + return ts.TypeReferenceSerializationKind.BooleanType; + } + else if (isTypeAssignableToKind(type, 296 /* NumberLike */)) { + return ts.TypeReferenceSerializationKind.NumberLikeType; + } + else if (isTypeAssignableToKind(type, 2112 /* BigIntLike */)) { + return ts.TypeReferenceSerializationKind.BigIntLikeType; + } + else if (isTypeAssignableToKind(type, 132 /* StringLike */)) { + return ts.TypeReferenceSerializationKind.StringLikeType; + } + else if (isTupleType(type)) { + return ts.TypeReferenceSerializationKind.ArrayLikeType; + } + else if (isTypeAssignableToKind(type, 12288 /* ESSymbolLike */)) { + return ts.TypeReferenceSerializationKind.ESSymbolType; + } + else if (isFunctionType(type)) { + return ts.TypeReferenceSerializationKind.TypeWithCallSignature; + } + else if (isArrayType(type)) { + return ts.TypeReferenceSerializationKind.ArrayLikeType; + } + else { + return ts.TypeReferenceSerializationKind.ObjectType; + } + } + function createTypeOfDeclaration(declarationIn, enclosingDeclaration, flags, tracker, addUndefined) { + var declaration = ts.getParseTreeNode(declarationIn, ts.isVariableLikeOrAccessor); + if (!declaration) { + return ts.createToken(120 /* AnyKeyword */); + } + // Get type of the symbol if this is the valid symbol otherwise get type at location + var symbol = getSymbolOfNode(declaration); + var type = symbol && !(symbol.flags & (2048 /* TypeLiteral */ | 131072 /* Signature */)) + ? getWidenedLiteralType(getTypeOfSymbol(symbol)) + : errorType; + if (type.flags & 8192 /* UniqueESSymbol */ && + type.symbol === symbol) { + flags |= 1048576 /* AllowUniqueESSymbolType */; + } + if (addUndefined) { + type = getOptionalType(type); + } + return nodeBuilder.typeToTypeNode(type, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, tracker); + } + function createReturnTypeOfSignatureDeclaration(signatureDeclarationIn, enclosingDeclaration, flags, tracker) { + var signatureDeclaration = ts.getParseTreeNode(signatureDeclarationIn, ts.isFunctionLike); + if (!signatureDeclaration) { + return ts.createToken(120 /* AnyKeyword */); + } + var signature = getSignatureFromDeclaration(signatureDeclaration); + return nodeBuilder.typeToTypeNode(getReturnTypeOfSignature(signature), enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, tracker); + } + function createTypeOfExpression(exprIn, enclosingDeclaration, flags, tracker) { + var expr = ts.getParseTreeNode(exprIn, ts.isExpression); + if (!expr) { + return ts.createToken(120 /* AnyKeyword */); + } + var type = getWidenedType(getRegularTypeOfExpression(expr)); + return nodeBuilder.typeToTypeNode(type, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, tracker); + } + function hasGlobalName(name) { + return globals.has(ts.escapeLeadingUnderscores(name)); + } + function getReferencedValueSymbol(reference, startInDeclarationContainer) { + var resolvedSymbol = getNodeLinks(reference).resolvedSymbol; + if (resolvedSymbol) { + return resolvedSymbol; + } + var location = reference; + if (startInDeclarationContainer) { + // When resolving the name of a declaration as a value, we need to start resolution + // at a point outside of the declaration. + var parent = reference.parent; + if (ts.isDeclaration(parent) && reference === parent.name) { + location = getDeclarationContainer(parent); + } + } + return resolveName(location, reference.escapedText, 67220415 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */, /*nodeNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); + } + function getReferencedValueDeclaration(referenceIn) { + if (!ts.isGeneratedIdentifier(referenceIn)) { + var reference = ts.getParseTreeNode(referenceIn, ts.isIdentifier); + if (reference) { + var symbol = getReferencedValueSymbol(reference); + if (symbol) { + return getExportSymbolOfValueSymbolIfExported(symbol).valueDeclaration; + } + } + } + return undefined; + } + function isLiteralConstDeclaration(node) { + if (ts.isDeclarationReadonly(node) || ts.isVariableDeclaration(node) && ts.isVarConst(node)) { + return isFreshLiteralType(getTypeOfSymbol(getSymbolOfNode(node))); + } + return false; + } + function literalTypeToNode(type, enclosing, tracker) { + var enumResult = type.flags & 1024 /* EnumLiteral */ ? nodeBuilder.symbolToExpression(type.symbol, 67220415 /* Value */, enclosing, /*flags*/ undefined, tracker) + : type === trueType ? ts.createTrue() : type === falseType && ts.createFalse(); + return enumResult || ts.createLiteral(type.value); + } + function createLiteralConstValue(node, tracker) { + var type = getTypeOfSymbol(getSymbolOfNode(node)); + return literalTypeToNode(type, node, tracker); + } + function createResolver() { + // this variable and functions that use it are deliberately moved here from the outer scope + // to avoid scope pollution + var resolvedTypeReferenceDirectives = host.getResolvedTypeReferenceDirectives(); + var fileToDirective; + if (resolvedTypeReferenceDirectives) { + // populate reverse mapping: file path -> type reference directive that was resolved to this file + fileToDirective = ts.createMap(); + resolvedTypeReferenceDirectives.forEach(function (resolvedDirective, key) { + if (!resolvedDirective || !resolvedDirective.resolvedFileName) { + return; + } + var file = host.getSourceFile(resolvedDirective.resolvedFileName); + fileToDirective.set(file.path, key); + }); + } + return { + getReferencedExportContainer: getReferencedExportContainer, + getReferencedImportDeclaration: getReferencedImportDeclaration, + getReferencedDeclarationWithCollidingName: getReferencedDeclarationWithCollidingName, + isDeclarationWithCollidingName: isDeclarationWithCollidingName, + isValueAliasDeclaration: function (node) { + node = ts.getParseTreeNode(node); + // Synthesized nodes are always treated like values. + return node ? isValueAliasDeclaration(node) : true; + }, + hasGlobalName: hasGlobalName, + isReferencedAliasDeclaration: function (node, checkChildren) { + node = ts.getParseTreeNode(node); + // Synthesized nodes are always treated as referenced. + return node ? isReferencedAliasDeclaration(node, checkChildren) : true; + }, + getNodeCheckFlags: function (node) { + node = ts.getParseTreeNode(node); + return node ? getNodeCheckFlags(node) : 0; + }, + isTopLevelValueImportEqualsWithEntityName: isTopLevelValueImportEqualsWithEntityName, + isDeclarationVisible: isDeclarationVisible, + isImplementationOfOverload: isImplementationOfOverload, + isRequiredInitializedParameter: isRequiredInitializedParameter, + isOptionalUninitializedParameterProperty: isOptionalUninitializedParameterProperty, + isExpandoFunctionDeclaration: isExpandoFunctionDeclaration, + getPropertiesOfContainerFunction: getPropertiesOfContainerFunction, + createTypeOfDeclaration: createTypeOfDeclaration, + createReturnTypeOfSignatureDeclaration: createReturnTypeOfSignatureDeclaration, + createTypeOfExpression: createTypeOfExpression, + createLiteralConstValue: createLiteralConstValue, + isSymbolAccessible: isSymbolAccessible, + isEntityNameVisible: isEntityNameVisible, + getConstantValue: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, canHaveConstantValue); + return node ? getConstantValue(node) : undefined; + }, + collectLinkedAliases: collectLinkedAliases, + getReferencedValueDeclaration: getReferencedValueDeclaration, + getTypeReferenceSerializationKind: getTypeReferenceSerializationKind, + isOptionalParameter: isOptionalParameter, + moduleExportsSomeValue: moduleExportsSomeValue, + isArgumentsLocalBinding: isArgumentsLocalBinding, + getExternalModuleFileFromDeclaration: getExternalModuleFileFromDeclaration, + getTypeReferenceDirectivesForEntityName: getTypeReferenceDirectivesForEntityName, + getTypeReferenceDirectivesForSymbol: getTypeReferenceDirectivesForSymbol, + isLiteralConstDeclaration: isLiteralConstDeclaration, + isLateBound: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isDeclaration); + var symbol = node && getSymbolOfNode(node); + return !!(symbol && ts.getCheckFlags(symbol) & 1024 /* Late */); + }, + getJsxFactoryEntity: function (location) { return location ? (getJsxNamespace(location), (ts.getSourceFileOfNode(location).localJsxFactory || _jsxFactoryEntity)) : _jsxFactoryEntity; }, + getAllAccessorDeclarations: function (accessor) { + accessor = ts.getParseTreeNode(accessor, ts.isGetOrSetAccessorDeclaration); // TODO: GH#18217 + var otherKind = accessor.kind === 159 /* SetAccessor */ ? 158 /* GetAccessor */ : 159 /* SetAccessor */; + var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(accessor), otherKind); + var firstAccessor = otherAccessor && (otherAccessor.pos < accessor.pos) ? otherAccessor : accessor; + var secondAccessor = otherAccessor && (otherAccessor.pos < accessor.pos) ? accessor : otherAccessor; + var setAccessor = accessor.kind === 159 /* SetAccessor */ ? accessor : otherAccessor; + var getAccessor = accessor.kind === 158 /* GetAccessor */ ? accessor : otherAccessor; + return { + firstAccessor: firstAccessor, + secondAccessor: secondAccessor, + setAccessor: setAccessor, + getAccessor: getAccessor + }; + }, + getSymbolOfExternalModuleSpecifier: function (moduleName) { return resolveExternalModuleNameWorker(moduleName, moduleName, /*moduleNotFoundError*/ undefined); }, + isBindingCapturedByNode: function (node, decl) { + var parseNode = ts.getParseTreeNode(node); + var parseDecl = ts.getParseTreeNode(decl); + return !!parseNode && !!parseDecl && (ts.isVariableDeclaration(parseDecl) || ts.isBindingElement(parseDecl)) && isBindingCapturedByNode(parseNode, parseDecl); + } + }; + function isInHeritageClause(node) { + return node.parent && node.parent.kind === 211 /* ExpressionWithTypeArguments */ && node.parent.parent && node.parent.parent.kind === 273 /* HeritageClause */; + } + // defined here to avoid outer scope pollution + function getTypeReferenceDirectivesForEntityName(node) { + // program does not have any files with type reference directives - bail out + if (!fileToDirective) { + return undefined; + } + // property access can only be used as values, or types when within an expression with type arguments inside a heritage clause + // qualified names can only be used as types\namespaces + // identifiers are treated as values only if they appear in type queries + var meaning = 67897832 /* Type */ | 1920 /* Namespace */; + if ((node.kind === 72 /* Identifier */ && isInTypeQuery(node)) || (node.kind === 189 /* PropertyAccessExpression */ && !isInHeritageClause(node))) { + meaning = 67220415 /* Value */ | 1048576 /* ExportValue */; + } + var symbol = resolveEntityName(node, meaning, /*ignoreErrors*/ true); + return symbol && symbol !== unknownSymbol ? getTypeReferenceDirectivesForSymbol(symbol, meaning) : undefined; + } + // defined here to avoid outer scope pollution + function getTypeReferenceDirectivesForSymbol(symbol, meaning) { + // program does not have any files with type reference directives - bail out + if (!fileToDirective) { + return undefined; + } + if (!isSymbolFromTypeDeclarationFile(symbol)) { + return undefined; + } + // check what declarations in the symbol can contribute to the target meaning + var typeReferenceDirectives; + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + // check meaning of the local symbol to see if declaration needs to be analyzed further + if (decl.symbol && decl.symbol.flags & meaning) { + var file = ts.getSourceFileOfNode(decl); + var typeReferenceDirective = fileToDirective.get(file.path); + if (typeReferenceDirective) { + (typeReferenceDirectives || (typeReferenceDirectives = [])).push(typeReferenceDirective); + } + else { + // found at least one entry that does not originate from type reference directive + return undefined; + } + } + } + return typeReferenceDirectives; + } + function isSymbolFromTypeDeclarationFile(symbol) { + // bail out if symbol does not have associated declarations (i.e. this is transient symbol created for property in binding pattern) + if (!symbol.declarations) { + return false; + } + // walk the parent chain for symbols to make sure that top level parent symbol is in the global scope + // external modules cannot define or contribute to type declaration files + var current = symbol; + while (true) { + var parent = getParentOfSymbol(current); + if (parent) { + current = parent; + } + else { + break; + } + } + if (current.valueDeclaration && current.valueDeclaration.kind === 279 /* SourceFile */ && current.flags & 512 /* ValueModule */) { + return false; + } + // check that at least one declaration of top level symbol originates from type declaration file + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + var file = ts.getSourceFileOfNode(decl); + if (fileToDirective.has(file.path)) { + return true; + } + } + return false; + } + } + function getExternalModuleFileFromDeclaration(declaration) { + var specifier = declaration.kind === 244 /* ModuleDeclaration */ ? ts.tryCast(declaration.name, ts.isStringLiteral) : ts.getExternalModuleName(declaration); + var moduleSymbol = resolveExternalModuleNameWorker(specifier, specifier, /*moduleNotFoundError*/ undefined); // TODO: GH#18217 + if (!moduleSymbol) { + return undefined; + } + return ts.getDeclarationOfKind(moduleSymbol, 279 /* SourceFile */); + } + function initializeTypeChecker() { + // Bind all source files and propagate errors + for (var _i = 0, _a = host.getSourceFiles(); _i < _a.length; _i++) { + var file = _a[_i]; + ts.bindSourceFile(file, compilerOptions); + } + amalgamatedDuplicates = ts.createMap(); + // Initialize global symbol table + var augmentations; + for (var _b = 0, _c = host.getSourceFiles(); _b < _c.length; _b++) { + var file = _c[_b]; + if (file.redirectInfo) { + continue; + } + if (!ts.isExternalOrCommonJsModule(file)) { + mergeSymbolTable(globals, file.locals); + } + if (file.jsGlobalAugmentations) { + mergeSymbolTable(globals, file.jsGlobalAugmentations); + } + if (file.patternAmbientModules && file.patternAmbientModules.length) { + patternAmbientModules = ts.concatenate(patternAmbientModules, file.patternAmbientModules); + } + if (file.moduleAugmentations.length) { + (augmentations || (augmentations = [])).push(file.moduleAugmentations); + } + if (file.symbol && file.symbol.globalExports) { + // Merge in UMD exports with first-in-wins semantics (see #9771) + var source = file.symbol.globalExports; + source.forEach(function (sourceSymbol, id) { + if (!globals.has(id)) { + globals.set(id, sourceSymbol); + } + }); + } + } + // We do global augmentations separately from module augmentations (and before creating global types) because they + // 1. Affect global types. We won't have the correct global types until global augmentations are merged. Also, + // 2. Module augmentation instantiation requires creating the type of a module, which, in turn, can require + // checking for an export or property on the module (if export=) which, in turn, can fall back to the + // apparent type of the module - either globalObjectType or globalFunctionType - which wouldn't exist if we + // did module augmentations prior to finalizing the global types. + if (augmentations) { + // merge _global_ module augmentations. + // this needs to be done after global symbol table is initialized to make sure that all ambient modules are indexed + for (var _d = 0, augmentations_1 = augmentations; _d < augmentations_1.length; _d++) { + var list = augmentations_1[_d]; + for (var _e = 0, list_1 = list; _e < list_1.length; _e++) { + var augmentation = list_1[_e]; + if (!ts.isGlobalScopeAugmentation(augmentation.parent)) + continue; + mergeModuleAugmentation(augmentation); + } + } + } + // Setup global builtins + addToSymbolTable(globals, builtinGlobals, ts.Diagnostics.Declaration_name_conflicts_with_built_in_global_identifier_0); + getSymbolLinks(undefinedSymbol).type = undefinedWideningType; + getSymbolLinks(argumentsSymbol).type = getGlobalType("IArguments", /*arity*/ 0, /*reportErrors*/ true); + getSymbolLinks(unknownSymbol).type = errorType; + // Initialize special types + globalArrayType = getGlobalType("Array", /*arity*/ 1, /*reportErrors*/ true); + globalObjectType = getGlobalType("Object", /*arity*/ 0, /*reportErrors*/ true); + globalFunctionType = getGlobalType("Function", /*arity*/ 0, /*reportErrors*/ true); + globalCallableFunctionType = strictBindCallApply && getGlobalType("CallableFunction", /*arity*/ 0, /*reportErrors*/ true) || globalFunctionType; + globalNewableFunctionType = strictBindCallApply && getGlobalType("NewableFunction", /*arity*/ 0, /*reportErrors*/ true) || globalFunctionType; + globalStringType = getGlobalType("String", /*arity*/ 0, /*reportErrors*/ true); + globalNumberType = getGlobalType("Number", /*arity*/ 0, /*reportErrors*/ true); + globalBooleanType = getGlobalType("Boolean", /*arity*/ 0, /*reportErrors*/ true); + globalRegExpType = getGlobalType("RegExp", /*arity*/ 0, /*reportErrors*/ true); + anyArrayType = createArrayType(anyType); + autoArrayType = createArrayType(autoType); + if (autoArrayType === emptyObjectType) { + // autoArrayType is used as a marker, so even if global Array type is not defined, it needs to be a unique type + autoArrayType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + } + globalReadonlyArrayType = getGlobalTypeOrUndefined("ReadonlyArray", /*arity*/ 1); + anyReadonlyArrayType = globalReadonlyArrayType ? createTypeFromGenericGlobalType(globalReadonlyArrayType, [anyType]) : anyArrayType; + globalThisType = getGlobalTypeOrUndefined("ThisType", /*arity*/ 1); + if (augmentations) { + // merge _nonglobal_ module augmentations. + // this needs to be done after global symbol table is initialized to make sure that all ambient modules are indexed + for (var _f = 0, augmentations_2 = augmentations; _f < augmentations_2.length; _f++) { + var list = augmentations_2[_f]; + for (var _g = 0, list_2 = list; _g < list_2.length; _g++) { + var augmentation = list_2[_g]; + if (ts.isGlobalScopeAugmentation(augmentation.parent)) + continue; + mergeModuleAugmentation(augmentation); + } + } + } + amalgamatedDuplicates.forEach(function (_a) { + var firstFile = _a.firstFile, secondFile = _a.secondFile, conflictingSymbols = _a.conflictingSymbols; + // If not many things conflict, issue individual errors + if (conflictingSymbols.size < 8) { + conflictingSymbols.forEach(function (_a, symbolName) { + var isBlockScoped = _a.isBlockScoped, firstFileLocations = _a.firstFileLocations, secondFileLocations = _a.secondFileLocations; + var message = isBlockScoped ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 : ts.Diagnostics.Duplicate_identifier_0; + for (var _i = 0, firstFileLocations_1 = firstFileLocations; _i < firstFileLocations_1.length; _i++) { + var node = firstFileLocations_1[_i]; + addDuplicateDeclarationError(node, message, symbolName, secondFileLocations); + } + for (var _b = 0, secondFileLocations_1 = secondFileLocations; _b < secondFileLocations_1.length; _b++) { + var node = secondFileLocations_1[_b]; + addDuplicateDeclarationError(node, message, symbolName, firstFileLocations); + } + }); + } + else { + // Otherwise issue top-level error since the files appear very identical in terms of what they contain + var list = ts.arrayFrom(conflictingSymbols.keys()).join(", "); + diagnostics.add(addRelatedInfo(ts.createDiagnosticForNode(firstFile, ts.Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list), ts.createDiagnosticForNode(secondFile, ts.Diagnostics.Conflicts_are_in_this_file))); + diagnostics.add(addRelatedInfo(ts.createDiagnosticForNode(secondFile, ts.Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list), ts.createDiagnosticForNode(firstFile, ts.Diagnostics.Conflicts_are_in_this_file))); + } + }); + amalgamatedDuplicates = undefined; + } + function checkExternalEmitHelpers(location, helpers) { + if ((requestedExternalEmitHelpers & helpers) !== helpers && compilerOptions.importHelpers) { + var sourceFile = ts.getSourceFileOfNode(location); + if (ts.isEffectiveExternalModule(sourceFile, compilerOptions) && !(location.flags & 4194304 /* Ambient */)) { + var helpersModule = resolveHelpersModule(sourceFile, location); + if (helpersModule !== unknownSymbol) { + var uncheckedHelpers = helpers & ~requestedExternalEmitHelpers; + for (var helper = 1 /* FirstEmitHelper */; helper <= 65536 /* LastEmitHelper */; helper <<= 1) { + if (uncheckedHelpers & helper) { + var name = getHelperName(helper); + var symbol = getSymbol(helpersModule.exports, ts.escapeLeadingUnderscores(name), 67220415 /* Value */); + if (!symbol) { + error(location, ts.Diagnostics.This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1, ts.externalHelpersModuleNameText, name); + } + } + } + } + requestedExternalEmitHelpers |= helpers; + } + } + } + function getHelperName(helper) { + switch (helper) { + case 1 /* Extends */: return "__extends"; + case 2 /* Assign */: return "__assign"; + case 4 /* Rest */: return "__rest"; + case 8 /* Decorate */: return "__decorate"; + case 16 /* Metadata */: return "__metadata"; + case 32 /* Param */: return "__param"; + case 64 /* Awaiter */: return "__awaiter"; + case 128 /* Generator */: return "__generator"; + case 256 /* Values */: return "__values"; + case 512 /* Read */: return "__read"; + case 1024 /* Spread */: return "__spread"; + case 2048 /* Await */: return "__await"; + case 4096 /* AsyncGenerator */: return "__asyncGenerator"; + case 8192 /* AsyncDelegator */: return "__asyncDelegator"; + case 16384 /* AsyncValues */: return "__asyncValues"; + case 32768 /* ExportStar */: return "__exportStar"; + case 65536 /* MakeTemplateObject */: return "__makeTemplateObject"; + default: return ts.Debug.fail("Unrecognized helper"); + } + } + function resolveHelpersModule(node, errorNode) { + if (!externalHelpersModule) { + externalHelpersModule = resolveExternalModule(node, ts.externalHelpersModuleNameText, ts.Diagnostics.This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found, errorNode) || unknownSymbol; + } + return externalHelpersModule; + } + // GRAMMAR CHECKING + function checkGrammarDecoratorsAndModifiers(node) { + return checkGrammarDecorators(node) || checkGrammarModifiers(node); + } + function checkGrammarDecorators(node) { + if (!node.decorators) { + return false; + } + if (!ts.nodeCanBeDecorated(node, node.parent, node.parent.parent)) { + if (node.kind === 156 /* MethodDeclaration */ && !ts.nodeIsPresent(node.body)) { + return grammarErrorOnFirstToken(node, ts.Diagnostics.A_decorator_can_only_decorate_a_method_implementation_not_an_overload); + } + else { + return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_are_not_valid_here); + } + } + else if (node.kind === 158 /* GetAccessor */ || node.kind === 159 /* SetAccessor */) { + var accessors = ts.getAllAccessorDeclarations(node.parent.members, node); + if (accessors.firstAccessor.decorators && node === accessors.secondAccessor) { + return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name); + } + } + return false; + } + function checkGrammarModifiers(node) { + var quickResult = reportObviousModifierErrors(node); + if (quickResult !== undefined) { + return quickResult; + } + var lastStatic, lastDeclare, lastAsync, lastReadonly; + var flags = 0 /* None */; + for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) { + var modifier = _a[_i]; + if (modifier.kind !== 133 /* ReadonlyKeyword */) { + if (node.kind === 153 /* PropertySignature */ || node.kind === 155 /* MethodSignature */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_type_member, ts.tokenToString(modifier.kind)); + } + if (node.kind === 162 /* IndexSignature */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_an_index_signature, ts.tokenToString(modifier.kind)); + } + } + switch (modifier.kind) { + case 77 /* ConstKeyword */: + if (node.kind !== 243 /* EnumDeclaration */) { + return grammarErrorOnNode(node, ts.Diagnostics.A_class_member_cannot_have_the_0_keyword, ts.tokenToString(77 /* ConstKeyword */)); + } + break; + case 115 /* PublicKeyword */: + case 114 /* ProtectedKeyword */: + case 113 /* PrivateKeyword */: + var text = visibilityToString(ts.modifierToFlag(modifier.kind)); + if (flags & 28 /* AccessibilityModifier */) { + return grammarErrorOnNode(modifier, ts.Diagnostics.Accessibility_modifier_already_seen); + } + else if (flags & 32 /* Static */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "static"); + } + else if (flags & 64 /* Readonly */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "readonly"); + } + else if (flags & 256 /* Async */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "async"); + } + else if (node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 279 /* SourceFile */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, text); + } + else if (flags & 128 /* Abstract */) { + if (modifier.kind === 113 /* PrivateKeyword */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, text, "abstract"); + } + else { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "abstract"); + } + } + flags |= ts.modifierToFlag(modifier.kind); + break; + case 116 /* StaticKeyword */: + if (flags & 32 /* Static */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "static"); + } + else if (flags & 64 /* Readonly */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "readonly"); + } + else if (flags & 256 /* Async */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "async"); + } + else if (node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 279 /* SourceFile */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, "static"); + } + else if (node.kind === 151 /* Parameter */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "static"); + } + else if (flags & 128 /* Abstract */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "abstract"); + } + flags |= 32 /* Static */; + lastStatic = modifier; + break; + case 133 /* ReadonlyKeyword */: + if (flags & 64 /* Readonly */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "readonly"); + } + else if (node.kind !== 154 /* PropertyDeclaration */ && node.kind !== 153 /* PropertySignature */ && node.kind !== 162 /* IndexSignature */ && node.kind !== 151 /* Parameter */) { + // If node.kind === SyntaxKind.Parameter, checkParameter report an error if it's not a parameter property. + return grammarErrorOnNode(modifier, ts.Diagnostics.readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature); + } + flags |= 64 /* Readonly */; + lastReadonly = modifier; + break; + case 85 /* ExportKeyword */: + if (flags & 1 /* Export */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "export"); + } + else if (flags & 2 /* Ambient */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "declare"); + } + else if (flags & 128 /* Abstract */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "abstract"); + } + else if (flags & 256 /* Async */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "async"); + } + else if (node.parent.kind === 240 /* ClassDeclaration */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_class_element, "export"); + } + else if (node.kind === 151 /* Parameter */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "export"); + } + flags |= 1 /* Export */; + break; + case 80 /* DefaultKeyword */: + var container = node.parent.kind === 279 /* SourceFile */ ? node.parent : node.parent.parent; + if (container.kind === 244 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) { + return grammarErrorOnNode(modifier, ts.Diagnostics.A_default_export_can_only_be_used_in_an_ECMAScript_style_module); + } + flags |= 512 /* Default */; + break; + case 125 /* DeclareKeyword */: + if (flags & 2 /* Ambient */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "declare"); + } + else if (flags & 256 /* Async */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async"); + } + else if (node.parent.kind === 240 /* ClassDeclaration */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_class_element, "declare"); + } + else if (node.kind === 151 /* Parameter */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "declare"); + } + else if ((node.parent.flags & 4194304 /* Ambient */) && node.parent.kind === 245 /* ModuleBlock */) { + return grammarErrorOnNode(modifier, ts.Diagnostics.A_declare_modifier_cannot_be_used_in_an_already_ambient_context); + } + flags |= 2 /* Ambient */; + lastDeclare = modifier; + break; + case 118 /* AbstractKeyword */: + if (flags & 128 /* Abstract */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "abstract"); + } + if (node.kind !== 240 /* ClassDeclaration */) { + if (node.kind !== 156 /* MethodDeclaration */ && + node.kind !== 154 /* PropertyDeclaration */ && + node.kind !== 158 /* GetAccessor */ && + node.kind !== 159 /* SetAccessor */) { + return grammarErrorOnNode(modifier, ts.Diagnostics.abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration); + } + if (!(node.parent.kind === 240 /* ClassDeclaration */ && ts.hasModifier(node.parent, 128 /* Abstract */))) { + return grammarErrorOnNode(modifier, ts.Diagnostics.Abstract_methods_can_only_appear_within_an_abstract_class); + } + if (flags & 32 /* Static */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "abstract"); + } + if (flags & 8 /* Private */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "private", "abstract"); + } + } + flags |= 128 /* Abstract */; + break; + case 121 /* AsyncKeyword */: + if (flags & 256 /* Async */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "async"); + } + else if (flags & 2 /* Ambient */ || node.parent.flags & 4194304 /* Ambient */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async"); + } + else if (node.kind === 151 /* Parameter */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "async"); + } + flags |= 256 /* Async */; + lastAsync = modifier; + break; + } + } + if (node.kind === 157 /* Constructor */) { + if (flags & 32 /* Static */) { + return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "static"); + } + if (flags & 128 /* Abstract */) { + return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "abstract"); // TODO: GH#18217 + } + else if (flags & 256 /* Async */) { + return grammarErrorOnNode(lastAsync, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "async"); + } + else if (flags & 64 /* Readonly */) { + return grammarErrorOnNode(lastReadonly, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "readonly"); + } + return false; + } + else if ((node.kind === 249 /* ImportDeclaration */ || node.kind === 248 /* ImportEqualsDeclaration */) && flags & 2 /* Ambient */) { + return grammarErrorOnNode(lastDeclare, ts.Diagnostics.A_0_modifier_cannot_be_used_with_an_import_declaration, "declare"); + } + else if (node.kind === 151 /* Parameter */ && (flags & 92 /* ParameterPropertyModifier */) && ts.isBindingPattern(node.name)) { + return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_may_not_be_declared_using_a_binding_pattern); + } + else if (node.kind === 151 /* Parameter */ && (flags & 92 /* ParameterPropertyModifier */) && node.dotDotDotToken) { + return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_cannot_be_declared_using_a_rest_parameter); + } + if (flags & 256 /* Async */) { + return checkGrammarAsyncModifier(node, lastAsync); + } + return false; + } + /** + * true | false: Early return this value from checkGrammarModifiers. + * undefined: Need to do full checking on the modifiers. + */ + function reportObviousModifierErrors(node) { + return !node.modifiers + ? false + : shouldReportBadModifier(node) + ? grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here) + : undefined; + } + function shouldReportBadModifier(node) { + switch (node.kind) { + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 157 /* Constructor */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 162 /* IndexSignature */: + case 244 /* ModuleDeclaration */: + case 249 /* ImportDeclaration */: + case 248 /* ImportEqualsDeclaration */: + case 255 /* ExportDeclaration */: + case 254 /* ExportAssignment */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 151 /* Parameter */: + return false; + default: + if (node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 279 /* SourceFile */) { + return false; + } + switch (node.kind) { + case 239 /* FunctionDeclaration */: + return nodeHasAnyModifiersExcept(node, 121 /* AsyncKeyword */); + case 240 /* ClassDeclaration */: + return nodeHasAnyModifiersExcept(node, 118 /* AbstractKeyword */); + case 241 /* InterfaceDeclaration */: + case 219 /* VariableStatement */: + case 242 /* TypeAliasDeclaration */: + return true; + case 243 /* EnumDeclaration */: + return nodeHasAnyModifiersExcept(node, 77 /* ConstKeyword */); + default: + ts.Debug.fail(); + return false; + } + } + } + function nodeHasAnyModifiersExcept(node, allowedModifier) { + return node.modifiers.length > 1 || node.modifiers[0].kind !== allowedModifier; + } + function checkGrammarAsyncModifier(node, asyncModifier) { + switch (node.kind) { + case 156 /* MethodDeclaration */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + return false; + } + return grammarErrorOnNode(asyncModifier, ts.Diagnostics._0_modifier_cannot_be_used_here, "async"); + } + function checkGrammarForDisallowedTrailingComma(list, diag) { + if (diag === void 0) { diag = ts.Diagnostics.Trailing_comma_not_allowed; } + if (list && list.hasTrailingComma) { + return grammarErrorAtPos(list[0], list.end - ",".length, ",".length, diag); + } + return false; + } + function checkGrammarTypeParameterList(typeParameters, file) { + if (typeParameters && typeParameters.length === 0) { + var start = typeParameters.pos - "<".length; + var end = ts.skipTrivia(file.text, typeParameters.end) + ">".length; + return grammarErrorAtPos(file, start, end - start, ts.Diagnostics.Type_parameter_list_cannot_be_empty); + } + return false; + } + function checkGrammarParameterList(parameters) { + var seenOptionalParameter = false; + var parameterCount = parameters.length; + for (var i = 0; i < parameterCount; i++) { + var parameter = parameters[i]; + if (parameter.dotDotDotToken) { + if (i !== (parameterCount - 1)) { + return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.A_rest_parameter_must_be_last_in_a_parameter_list); + } + if (!(parameter.flags & 4194304 /* Ambient */)) { // Allow `...foo,` in ambient declarations; see GH#23070 + checkGrammarForDisallowedTrailingComma(parameters, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma); + } + if (ts.isBindingPattern(parameter.name)) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.A_rest_element_cannot_contain_a_binding_pattern); + } + if (parameter.questionToken) { + return grammarErrorOnNode(parameter.questionToken, ts.Diagnostics.A_rest_parameter_cannot_be_optional); + } + if (parameter.initializer) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.A_rest_parameter_cannot_have_an_initializer); + } + } + else if (parameter.questionToken) { + seenOptionalParameter = true; + if (parameter.initializer) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.Parameter_cannot_have_question_mark_and_initializer); + } + } + else if (seenOptionalParameter && !parameter.initializer) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.A_required_parameter_cannot_follow_an_optional_parameter); + } + } + } + function getNonSimpleParameters(parameters) { + return ts.filter(parameters, function (parameter) { return !!parameter.initializer || ts.isBindingPattern(parameter.name) || ts.isRestParameter(parameter); }); + } + function checkGrammarForUseStrictSimpleParameterList(node) { + if (languageVersion >= 3 /* ES2016 */) { + var useStrictDirective_1 = node.body && ts.isBlock(node.body) && ts.findUseStrictPrologue(node.body.statements); + if (useStrictDirective_1) { + var nonSimpleParameters = getNonSimpleParameters(node.parameters); + if (ts.length(nonSimpleParameters)) { + ts.forEach(nonSimpleParameters, function (parameter) { + addRelatedInfo(error(parameter, ts.Diagnostics.This_parameter_is_not_allowed_with_use_strict_directive), ts.createDiagnosticForNode(useStrictDirective_1, ts.Diagnostics.use_strict_directive_used_here)); + }); + var diagnostics_1 = nonSimpleParameters.map(function (parameter, index) { return (index === 0 ? ts.createDiagnosticForNode(parameter, ts.Diagnostics.Non_simple_parameter_declared_here) : ts.createDiagnosticForNode(parameter, ts.Diagnostics.and_here)); }); + addRelatedInfo.apply(void 0, [error(useStrictDirective_1, ts.Diagnostics.use_strict_directive_cannot_be_used_with_non_simple_parameter_list)].concat(diagnostics_1)); + return true; + } + } + } + return false; + } + function checkGrammarFunctionLikeDeclaration(node) { + // Prevent cascading error by short-circuit + var file = ts.getSourceFileOfNode(node); + return checkGrammarDecoratorsAndModifiers(node) || checkGrammarTypeParameterList(node.typeParameters, file) || + checkGrammarParameterList(node.parameters) || checkGrammarArrowFunction(node, file) || + (ts.isFunctionLikeDeclaration(node) && checkGrammarForUseStrictSimpleParameterList(node)); + } + function checkGrammarClassLikeDeclaration(node) { + var file = ts.getSourceFileOfNode(node); + return checkGrammarClassDeclarationHeritageClauses(node) || checkGrammarTypeParameterList(node.typeParameters, file); + } + function checkGrammarArrowFunction(node, file) { + if (!ts.isArrowFunction(node)) { + return false; + } + var equalsGreaterThanToken = node.equalsGreaterThanToken; + var startLine = ts.getLineAndCharacterOfPosition(file, equalsGreaterThanToken.pos).line; + var endLine = ts.getLineAndCharacterOfPosition(file, equalsGreaterThanToken.end).line; + return startLine !== endLine && grammarErrorOnNode(equalsGreaterThanToken, ts.Diagnostics.Line_terminator_not_permitted_before_arrow); + } + function checkGrammarIndexSignatureParameters(node) { + var parameter = node.parameters[0]; + if (node.parameters.length !== 1) { + if (parameter) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_must_have_exactly_one_parameter); + } + else { + return grammarErrorOnNode(node, ts.Diagnostics.An_index_signature_must_have_exactly_one_parameter); + } + } + if (parameter.dotDotDotToken) { + return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.An_index_signature_cannot_have_a_rest_parameter); + } + if (ts.hasModifiers(parameter)) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_cannot_have_an_accessibility_modifier); + } + if (parameter.questionToken) { + return grammarErrorOnNode(parameter.questionToken, ts.Diagnostics.An_index_signature_parameter_cannot_have_a_question_mark); + } + if (parameter.initializer) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_cannot_have_an_initializer); + } + if (!parameter.type) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_must_have_a_type_annotation); + } + if (parameter.type.kind !== 138 /* StringKeyword */ && parameter.type.kind !== 135 /* NumberKeyword */) { + var type = getTypeFromTypeNode(parameter.type); + if (type.flags & 4 /* String */ || type.flags & 8 /* Number */) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead, ts.getTextOfNode(parameter.name), typeToString(type), typeToString(getTypeFromTypeNode(node.type))); + } + if (type.flags & 1048576 /* Union */ && allTypesAssignableToKind(type, 128 /* StringLiteral */, /*strict*/ true)) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead); + } + return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_must_be_string_or_number); + } + if (!node.type) { + return grammarErrorOnNode(node, ts.Diagnostics.An_index_signature_must_have_a_type_annotation); + } + return false; + } + function checkGrammarIndexSignature(node) { + // Prevent cascading error by short-circuit + return checkGrammarDecoratorsAndModifiers(node) || checkGrammarIndexSignatureParameters(node); + } + function checkGrammarForAtLeastOneTypeArgument(node, typeArguments) { + if (typeArguments && typeArguments.length === 0) { + var sourceFile = ts.getSourceFileOfNode(node); + var start = typeArguments.pos - "<".length; + var end = ts.skipTrivia(sourceFile.text, typeArguments.end) + ">".length; + return grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.Type_argument_list_cannot_be_empty); + } + return false; + } + function checkGrammarTypeArguments(node, typeArguments) { + return checkGrammarForDisallowedTrailingComma(typeArguments) || + checkGrammarForAtLeastOneTypeArgument(node, typeArguments); + } + function checkGrammarForOmittedArgument(args) { + if (args) { + for (var _i = 0, args_5 = args; _i < args_5.length; _i++) { + var arg = args_5[_i]; + if (arg.kind === 210 /* OmittedExpression */) { + return grammarErrorAtPos(arg, arg.pos, 0, ts.Diagnostics.Argument_expression_expected); + } + } + } + return false; + } + function checkGrammarArguments(args) { + return checkGrammarForOmittedArgument(args); + } + function checkGrammarHeritageClause(node) { + var types = node.types; + if (checkGrammarForDisallowedTrailingComma(types)) { + return true; + } + if (types && types.length === 0) { + var listType = ts.tokenToString(node.token); + return grammarErrorAtPos(node, types.pos, 0, ts.Diagnostics._0_list_cannot_be_empty, listType); + } + return ts.some(types, checkGrammarExpressionWithTypeArguments); + } + function checkGrammarExpressionWithTypeArguments(node) { + return checkGrammarTypeArguments(node, node.typeArguments); + } + function checkGrammarClassDeclarationHeritageClauses(node) { + var seenExtendsClause = false; + var seenImplementsClause = false; + if (!checkGrammarDecoratorsAndModifiers(node) && node.heritageClauses) { + for (var _i = 0, _a = node.heritageClauses; _i < _a.length; _i++) { + var heritageClause = _a[_i]; + if (heritageClause.token === 86 /* ExtendsKeyword */) { + if (seenExtendsClause) { + return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.extends_clause_already_seen); + } + if (seenImplementsClause) { + return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.extends_clause_must_precede_implements_clause); + } + if (heritageClause.types.length > 1) { + return grammarErrorOnFirstToken(heritageClause.types[1], ts.Diagnostics.Classes_can_only_extend_a_single_class); + } + seenExtendsClause = true; + } + else { + ts.Debug.assert(heritageClause.token === 109 /* ImplementsKeyword */); + if (seenImplementsClause) { + return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.implements_clause_already_seen); + } + seenImplementsClause = true; + } + // Grammar checking heritageClause inside class declaration + checkGrammarHeritageClause(heritageClause); + } + } + } + function checkGrammarInterfaceDeclaration(node) { + var seenExtendsClause = false; + if (node.heritageClauses) { + for (var _i = 0, _a = node.heritageClauses; _i < _a.length; _i++) { + var heritageClause = _a[_i]; + if (heritageClause.token === 86 /* ExtendsKeyword */) { + if (seenExtendsClause) { + return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.extends_clause_already_seen); + } + seenExtendsClause = true; + } + else { + ts.Debug.assert(heritageClause.token === 109 /* ImplementsKeyword */); + return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.Interface_declaration_cannot_have_implements_clause); + } + // Grammar checking heritageClause inside class declaration + checkGrammarHeritageClause(heritageClause); + } + } + return false; + } + function checkGrammarComputedPropertyName(node) { + // If node is not a computedPropertyName, just skip the grammar checking + if (node.kind !== 149 /* ComputedPropertyName */) { + return false; + } + var computedPropertyName = node; + if (computedPropertyName.expression.kind === 204 /* BinaryExpression */ && computedPropertyName.expression.operatorToken.kind === 27 /* CommaToken */) { + return grammarErrorOnNode(computedPropertyName.expression, ts.Diagnostics.A_comma_expression_is_not_allowed_in_a_computed_property_name); + } + return false; + } + function checkGrammarForGenerator(node) { + if (node.asteriskToken) { + ts.Debug.assert(node.kind === 239 /* FunctionDeclaration */ || + node.kind === 196 /* FunctionExpression */ || + node.kind === 156 /* MethodDeclaration */); + if (node.flags & 4194304 /* Ambient */) { + return grammarErrorOnNode(node.asteriskToken, ts.Diagnostics.Generators_are_not_allowed_in_an_ambient_context); + } + if (!node.body) { + return grammarErrorOnNode(node.asteriskToken, ts.Diagnostics.An_overload_signature_cannot_be_declared_as_a_generator); + } + } + } + function checkGrammarForInvalidQuestionMark(questionToken, message) { + return !!questionToken && grammarErrorOnNode(questionToken, message); + } + function checkGrammarForInvalidExclamationToken(exclamationToken, message) { + return !!exclamationToken && grammarErrorOnNode(exclamationToken, message); + } + function checkGrammarObjectLiteralExpression(node, inDestructuring) { + var Flags; + (function (Flags) { + Flags[Flags["Property"] = 1] = "Property"; + Flags[Flags["GetAccessor"] = 2] = "GetAccessor"; + Flags[Flags["SetAccessor"] = 4] = "SetAccessor"; + Flags[Flags["GetOrSetAccessor"] = 6] = "GetOrSetAccessor"; + })(Flags || (Flags = {})); + var seen = ts.createUnderscoreEscapedMap(); + for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { + var prop = _a[_i]; + if (prop.kind === 277 /* SpreadAssignment */) { + continue; + } + var name = prop.name; + if (name.kind === 149 /* ComputedPropertyName */) { + // If the name is not a ComputedPropertyName, the grammar checking will skip it + checkGrammarComputedPropertyName(name); + } + if (prop.kind === 276 /* ShorthandPropertyAssignment */ && !inDestructuring && prop.objectAssignmentInitializer) { + // having objectAssignmentInitializer is only valid in ObjectAssignmentPattern + // outside of destructuring it is a syntax error + return grammarErrorOnNode(prop.equalsToken, ts.Diagnostics.can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment); + } + // Modifiers are never allowed on properties except for 'async' on a method declaration + if (prop.modifiers) { + for (var _b = 0, _c = prop.modifiers; _b < _c.length; _b++) { // TODO: GH#19955 + var mod = _c[_b]; + if (mod.kind !== 121 /* AsyncKeyword */ || prop.kind !== 156 /* MethodDeclaration */) { + grammarErrorOnNode(mod, ts.Diagnostics._0_modifier_cannot_be_used_here, ts.getTextOfNode(mod)); + } + } + } + // ECMA-262 11.1.5 Object Initializer + // If previous is not undefined then throw a SyntaxError exception if any of the following conditions are true + // a.This production is contained in strict code and IsDataDescriptor(previous) is true and + // IsDataDescriptor(propId.descriptor) is true. + // b.IsDataDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true. + // c.IsAccessorDescriptor(previous) is true and IsDataDescriptor(propId.descriptor) is true. + // d.IsAccessorDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true + // and either both previous and propId.descriptor have[[Get]] fields or both previous and propId.descriptor have[[Set]] fields + var currentKind = void 0; + switch (prop.kind) { + case 276 /* ShorthandPropertyAssignment */: + checkGrammarForInvalidExclamationToken(prop.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context); + /* tslint:disable:no-switch-case-fall-through */ + case 275 /* PropertyAssignment */: + // Grammar checking for computedPropertyName and shorthandPropertyAssignment + checkGrammarForInvalidQuestionMark(prop.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional); + if (name.kind === 8 /* NumericLiteral */) { + checkGrammarNumericLiteral(name); + } + // falls through + case 156 /* MethodDeclaration */: + currentKind = 1 /* Property */; + break; + case 158 /* GetAccessor */: + currentKind = 2 /* GetAccessor */; + break; + case 159 /* SetAccessor */: + currentKind = 4 /* SetAccessor */; + break; + default: + throw ts.Debug.assertNever(prop, "Unexpected syntax kind:" + prop.kind); + } + var effectiveName = ts.getPropertyNameForPropertyNameNode(name); + if (effectiveName === undefined) { + continue; + } + var existingKind = seen.get(effectiveName); + if (!existingKind) { + seen.set(effectiveName, currentKind); + } + else { + if (currentKind === 1 /* Property */ && existingKind === 1 /* Property */) { + grammarErrorOnNode(name, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(name)); + } + else if ((currentKind & 6 /* GetOrSetAccessor */) && (existingKind & 6 /* GetOrSetAccessor */)) { + if (existingKind !== 6 /* GetOrSetAccessor */ && currentKind !== existingKind) { + seen.set(effectiveName, currentKind | existingKind); + } + else { + return grammarErrorOnNode(name, ts.Diagnostics.An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name); + } + } + else { + return grammarErrorOnNode(name, ts.Diagnostics.An_object_literal_cannot_have_property_and_accessor_with_the_same_name); + } + } + } + } + function checkGrammarJsxElement(node) { + checkGrammarTypeArguments(node, node.typeArguments); + var seen = ts.createUnderscoreEscapedMap(); + for (var _i = 0, _a = node.attributes.properties; _i < _a.length; _i++) { + var attr = _a[_i]; + if (attr.kind === 269 /* JsxSpreadAttribute */) { + continue; + } + var name = attr.name, initializer = attr.initializer; + if (!seen.get(name.escapedText)) { + seen.set(name.escapedText, true); + } + else { + return grammarErrorOnNode(name, ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name); + } + if (initializer && initializer.kind === 270 /* JsxExpression */ && !initializer.expression) { + return grammarErrorOnNode(initializer, ts.Diagnostics.JSX_attributes_must_only_be_assigned_a_non_empty_expression); + } + } + } + function checkGrammarForInOrForOfStatement(forInOrOfStatement) { + if (checkGrammarStatementInAmbientContext(forInOrOfStatement)) { + return true; + } + if (forInOrOfStatement.kind === 227 /* ForOfStatement */ && forInOrOfStatement.awaitModifier) { + if ((forInOrOfStatement.flags & 16384 /* AwaitContext */) === 0 /* None */) { + return grammarErrorOnNode(forInOrOfStatement.awaitModifier, ts.Diagnostics.A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator); + } + } + if (forInOrOfStatement.initializer.kind === 238 /* VariableDeclarationList */) { + var variableList = forInOrOfStatement.initializer; + if (!checkGrammarVariableDeclarationList(variableList)) { + var declarations = variableList.declarations; + // declarations.length can be zero if there is an error in variable declaration in for-of or for-in + // See http://www.ecma-international.org/ecma-262/6.0/#sec-for-in-and-for-of-statements for details + // For example: + // var let = 10; + // for (let of [1,2,3]) {} // this is invalid ES6 syntax + // for (let in [1,2,3]) {} // this is invalid ES6 syntax + // We will then want to skip on grammar checking on variableList declaration + if (!declarations.length) { + return false; + } + if (declarations.length > 1) { + var diagnostic = forInOrOfStatement.kind === 226 /* ForInStatement */ + ? ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement + : ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement; + return grammarErrorOnFirstToken(variableList.declarations[1], diagnostic); + } + var firstDeclaration = declarations[0]; + if (firstDeclaration.initializer) { + var diagnostic = forInOrOfStatement.kind === 226 /* ForInStatement */ + ? ts.Diagnostics.The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer + : ts.Diagnostics.The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer; + return grammarErrorOnNode(firstDeclaration.name, diagnostic); + } + if (firstDeclaration.type) { + var diagnostic = forInOrOfStatement.kind === 226 /* ForInStatement */ + ? ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation + : ts.Diagnostics.The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation; + return grammarErrorOnNode(firstDeclaration, diagnostic); + } + } + } + return false; + } + function checkGrammarAccessor(accessor) { + var kind = accessor.kind; + if (languageVersion < 1 /* ES5 */) { + return grammarErrorOnNode(accessor.name, ts.Diagnostics.Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher); + } + else if (accessor.flags & 4194304 /* Ambient */) { + return grammarErrorOnNode(accessor.name, ts.Diagnostics.An_accessor_cannot_be_declared_in_an_ambient_context); + } + else if (accessor.body === undefined && !ts.hasModifier(accessor, 128 /* Abstract */)) { + return grammarErrorAtPos(accessor, accessor.end - 1, ";".length, ts.Diagnostics._0_expected, "{"); + } + else if (accessor.body && ts.hasModifier(accessor, 128 /* Abstract */)) { + return grammarErrorOnNode(accessor, ts.Diagnostics.An_abstract_accessor_cannot_have_an_implementation); + } + else if (accessor.typeParameters) { + return grammarErrorOnNode(accessor.name, ts.Diagnostics.An_accessor_cannot_have_type_parameters); + } + else if (!doesAccessorHaveCorrectParameterCount(accessor)) { + return grammarErrorOnNode(accessor.name, kind === 158 /* GetAccessor */ ? + ts.Diagnostics.A_get_accessor_cannot_have_parameters : + ts.Diagnostics.A_set_accessor_must_have_exactly_one_parameter); + } + else if (kind === 159 /* SetAccessor */) { + if (accessor.type) { + return grammarErrorOnNode(accessor.name, ts.Diagnostics.A_set_accessor_cannot_have_a_return_type_annotation); + } + else { + var parameter = accessor.parameters[0]; + if (parameter.dotDotDotToken) { + return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.A_set_accessor_cannot_have_rest_parameter); + } + else if (parameter.questionToken) { + return grammarErrorOnNode(parameter.questionToken, ts.Diagnostics.A_set_accessor_cannot_have_an_optional_parameter); + } + else if (parameter.initializer) { + return grammarErrorOnNode(accessor.name, ts.Diagnostics.A_set_accessor_parameter_cannot_have_an_initializer); + } + } + } + return false; + } + /** Does the accessor have the right number of parameters? + * A get accessor has no parameters or a single `this` parameter. + * A set accessor has one parameter or a `this` parameter and one more parameter. + */ + function doesAccessorHaveCorrectParameterCount(accessor) { + return getAccessorThisParameter(accessor) || accessor.parameters.length === (accessor.kind === 158 /* GetAccessor */ ? 0 : 1); + } + function getAccessorThisParameter(accessor) { + if (accessor.parameters.length === (accessor.kind === 158 /* GetAccessor */ ? 1 : 2)) { + return ts.getThisParameter(accessor); + } + } + function checkGrammarTypeOperatorNode(node) { + if (node.operator === 142 /* UniqueKeyword */) { + if (node.type.kind !== 139 /* SymbolKeyword */) { + return grammarErrorOnNode(node.type, ts.Diagnostics._0_expected, ts.tokenToString(139 /* SymbolKeyword */)); + } + var parent = ts.walkUpParenthesizedTypes(node.parent); + switch (parent.kind) { + case 237 /* VariableDeclaration */: + var decl = parent; + if (decl.name.kind !== 72 /* Identifier */) { + return grammarErrorOnNode(node, ts.Diagnostics.unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name); + } + if (!ts.isVariableDeclarationInVariableStatement(decl)) { + return grammarErrorOnNode(node, ts.Diagnostics.unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement); + } + if (!(decl.parent.flags & 2 /* Const */)) { + return grammarErrorOnNode(parent.name, ts.Diagnostics.A_variable_whose_type_is_a_unique_symbol_type_must_be_const); + } + break; + case 154 /* PropertyDeclaration */: + if (!ts.hasModifier(parent, 32 /* Static */) || + !ts.hasModifier(parent, 64 /* Readonly */)) { + return grammarErrorOnNode(parent.name, ts.Diagnostics.A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly); + } + break; + case 153 /* PropertySignature */: + if (!ts.hasModifier(parent, 64 /* Readonly */)) { + return grammarErrorOnNode(parent.name, ts.Diagnostics.A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly); + } + break; + default: + return grammarErrorOnNode(node, ts.Diagnostics.unique_symbol_types_are_not_allowed_here); + } + } + } + function checkGrammarForInvalidDynamicName(node, message) { + if (isNonBindableDynamicName(node)) { + return grammarErrorOnNode(node, message); + } + } + function checkGrammarMethod(node) { + if (checkGrammarFunctionLikeDeclaration(node)) { + return true; + } + if (node.kind === 156 /* MethodDeclaration */) { + if (node.parent.kind === 188 /* ObjectLiteralExpression */) { + // We only disallow modifier on a method declaration if it is a property of object-literal-expression + if (node.modifiers && !(node.modifiers.length === 1 && ts.first(node.modifiers).kind === 121 /* AsyncKeyword */)) { + return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); + } + else if (checkGrammarForInvalidQuestionMark(node.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional)) { + return true; + } + else if (checkGrammarForInvalidExclamationToken(node.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context)) { + return true; + } + else if (node.body === undefined) { + return grammarErrorAtPos(node, node.end - 1, ";".length, ts.Diagnostics._0_expected, "{"); + } + } + if (checkGrammarForGenerator(node)) { + return true; + } + } + if (ts.isClassLike(node.parent)) { + // Technically, computed properties in ambient contexts is disallowed + // for property declarations and accessors too, not just methods. + // However, property declarations disallow computed names in general, + // and accessors are not allowed in ambient contexts in general, + // so this error only really matters for methods. + if (node.flags & 4194304 /* Ambient */) { + return checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type); + } + else if (node.kind === 156 /* MethodDeclaration */ && !node.body) { + return checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type); + } + } + else if (node.parent.kind === 241 /* InterfaceDeclaration */) { + return checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type); + } + else if (node.parent.kind === 168 /* TypeLiteral */) { + return checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type); + } + } + function checkGrammarBreakOrContinueStatement(node) { + var current = node; + while (current) { + if (ts.isFunctionLike(current)) { + return grammarErrorOnNode(node, ts.Diagnostics.Jump_target_cannot_cross_function_boundary); + } + switch (current.kind) { + case 233 /* LabeledStatement */: + if (node.label && current.label.escapedText === node.label.escapedText) { + // found matching label - verify that label usage is correct + // continue can only target labels that are on iteration statements + var isMisplacedContinueLabel = node.kind === 228 /* ContinueStatement */ + && !ts.isIterationStatement(current.statement, /*lookInLabeledStatement*/ true); + if (isMisplacedContinueLabel) { + return grammarErrorOnNode(node, ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement); + } + return false; + } + break; + case 232 /* SwitchStatement */: + if (node.kind === 229 /* BreakStatement */ && !node.label) { + // unlabeled break within switch statement - ok + return false; + } + break; + default: + if (ts.isIterationStatement(current, /*lookInLabeledStatement*/ false) && !node.label) { + // unlabeled break or continue within iteration statement - ok + return false; + } + break; + } + current = current.parent; + } + if (node.label) { + var message = node.kind === 229 /* BreakStatement */ + ? ts.Diagnostics.A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement + : ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement; + return grammarErrorOnNode(node, message); + } + else { + var message = node.kind === 229 /* BreakStatement */ + ? ts.Diagnostics.A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement + : ts.Diagnostics.A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement; + return grammarErrorOnNode(node, message); + } + } + function checkGrammarBindingElement(node) { + if (node.dotDotDotToken) { + var elements = node.parent.elements; + if (node !== ts.last(elements)) { + return grammarErrorOnNode(node, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern); + } + checkGrammarForDisallowedTrailingComma(elements, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma); + if (node.propertyName) { + return grammarErrorOnNode(node.name, ts.Diagnostics.A_rest_element_cannot_have_a_property_name); + } + if (node.initializer) { + // Error on equals token which immediately precedes the initializer + return grammarErrorAtPos(node, node.initializer.pos - 1, 1, ts.Diagnostics.A_rest_element_cannot_have_an_initializer); + } + } + } + function isStringOrNumberLiteralExpression(expr) { + return expr.kind === 10 /* StringLiteral */ || expr.kind === 8 /* NumericLiteral */ || + expr.kind === 202 /* PrefixUnaryExpression */ && expr.operator === 39 /* MinusToken */ && + expr.operand.kind === 8 /* NumericLiteral */; + } + function isBigIntLiteralExpression(expr) { + return expr.kind === 9 /* BigIntLiteral */ || + expr.kind === 202 /* PrefixUnaryExpression */ && expr.operator === 39 /* MinusToken */ && + expr.operand.kind === 9 /* BigIntLiteral */; + } + function isSimpleLiteralEnumReference(expr) { + if ((ts.isPropertyAccessExpression(expr) || (ts.isElementAccessExpression(expr) && isStringOrNumberLiteralExpression(expr.argumentExpression))) && + ts.isEntityNameExpression(expr.expression)) + return !!(checkExpressionCached(expr).flags & 1024 /* EnumLiteral */); + } + function checkAmbientInitializer(node) { + var initializer = node.initializer; + if (initializer) { + var isInvalidInitializer = !(isStringOrNumberLiteralExpression(initializer) || + isSimpleLiteralEnumReference(initializer) || + initializer.kind === 102 /* TrueKeyword */ || initializer.kind === 87 /* FalseKeyword */ || + isBigIntLiteralExpression(initializer)); + var isConstOrReadonly = ts.isDeclarationReadonly(node) || ts.isVariableDeclaration(node) && ts.isVarConst(node); + if (isConstOrReadonly && !node.type) { + if (isInvalidInitializer) { + return grammarErrorOnNode(initializer, ts.Diagnostics.A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_reference); + } + } + else { + return grammarErrorOnNode(initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); + } + if (!isConstOrReadonly || isInvalidInitializer) { + return grammarErrorOnNode(initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); + } + } + } + function checkGrammarVariableDeclaration(node) { + if (node.parent.parent.kind !== 226 /* ForInStatement */ && node.parent.parent.kind !== 227 /* ForOfStatement */) { + if (node.flags & 4194304 /* Ambient */) { + checkAmbientInitializer(node); + } + else if (!node.initializer) { + if (ts.isBindingPattern(node.name) && !ts.isBindingPattern(node.parent)) { + return grammarErrorOnNode(node, ts.Diagnostics.A_destructuring_declaration_must_have_an_initializer); + } + if (ts.isVarConst(node)) { + return grammarErrorOnNode(node, ts.Diagnostics.const_declarations_must_be_initialized); + } + } + } + if (node.exclamationToken && (node.parent.parent.kind !== 219 /* VariableStatement */ || !node.type || node.initializer || node.flags & 4194304 /* Ambient */)) { + return grammarErrorOnNode(node.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context); + } + if (compilerOptions.module !== ts.ModuleKind.ES2015 && compilerOptions.module !== ts.ModuleKind.ESNext && compilerOptions.module !== ts.ModuleKind.System && !compilerOptions.noEmit && + !(node.parent.parent.flags & 4194304 /* Ambient */) && ts.hasModifier(node.parent.parent, 1 /* Export */)) { + checkESModuleMarker(node.name); + } + var checkLetConstNames = (ts.isLet(node) || ts.isVarConst(node)); + // 1. LexicalDeclaration : LetOrConst BindingList ; + // It is a Syntax Error if the BoundNames of BindingList contains "let". + // 2. ForDeclaration: ForDeclaration : LetOrConst ForBinding + // It is a Syntax Error if the BoundNames of ForDeclaration contains "let". + // It is a SyntaxError if a VariableDeclaration or VariableDeclarationNoIn occurs within strict code + // and its Identifier is eval or arguments + return checkLetConstNames && checkGrammarNameInLetOrConstDeclarations(node.name); + } + function checkESModuleMarker(name) { + if (name.kind === 72 /* Identifier */) { + if (ts.idText(name) === "__esModule") { + return grammarErrorOnNode(name, ts.Diagnostics.Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules); + } + } + else { + var elements = name.elements; + for (var _i = 0, elements_1 = elements; _i < elements_1.length; _i++) { + var element = elements_1[_i]; + if (!ts.isOmittedExpression(element)) { + return checkESModuleMarker(element.name); + } + } + } + return false; + } + function checkGrammarNameInLetOrConstDeclarations(name) { + if (name.kind === 72 /* Identifier */) { + if (name.originalKeywordKind === 111 /* LetKeyword */) { + return grammarErrorOnNode(name, ts.Diagnostics.let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations); + } + } + else { + var elements = name.elements; + for (var _i = 0, elements_2 = elements; _i < elements_2.length; _i++) { + var element = elements_2[_i]; + if (!ts.isOmittedExpression(element)) { + checkGrammarNameInLetOrConstDeclarations(element.name); + } + } + } + return false; + } + function checkGrammarVariableDeclarationList(declarationList) { + var declarations = declarationList.declarations; + if (checkGrammarForDisallowedTrailingComma(declarationList.declarations)) { + return true; + } + if (!declarationList.declarations.length) { + return grammarErrorAtPos(declarationList, declarations.pos, declarations.end - declarations.pos, ts.Diagnostics.Variable_declaration_list_cannot_be_empty); + } + return false; + } + function allowLetAndConstDeclarations(parent) { + switch (parent.kind) { + case 222 /* IfStatement */: + case 223 /* DoStatement */: + case 224 /* WhileStatement */: + case 231 /* WithStatement */: + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + return false; + case 233 /* LabeledStatement */: + return allowLetAndConstDeclarations(parent.parent); + } + return true; + } + function checkGrammarForDisallowedLetOrConstStatement(node) { + if (!allowLetAndConstDeclarations(node.parent)) { + if (ts.isLet(node.declarationList)) { + return grammarErrorOnNode(node, ts.Diagnostics.let_declarations_can_only_be_declared_inside_a_block); + } + else if (ts.isVarConst(node.declarationList)) { + return grammarErrorOnNode(node, ts.Diagnostics.const_declarations_can_only_be_declared_inside_a_block); + } + } + } + function checkGrammarMetaProperty(node) { + var escapedText = node.name.escapedText; + switch (node.keywordToken) { + case 95 /* NewKeyword */: + if (escapedText !== "target") { + return grammarErrorOnNode(node.name, ts.Diagnostics._0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2, node.name.escapedText, ts.tokenToString(node.keywordToken), "target"); + } + break; + case 92 /* ImportKeyword */: + if (escapedText !== "meta") { + return grammarErrorOnNode(node.name, ts.Diagnostics._0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2, node.name.escapedText, ts.tokenToString(node.keywordToken), "meta"); + } + break; + } + } + function hasParseDiagnostics(sourceFile) { + return sourceFile.parseDiagnostics.length > 0; + } + function grammarErrorOnFirstToken(node, message, arg0, arg1, arg2) { + var sourceFile = ts.getSourceFileOfNode(node); + if (!hasParseDiagnostics(sourceFile)) { + var span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos); + diagnostics.add(ts.createFileDiagnostic(sourceFile, span.start, span.length, message, arg0, arg1, arg2)); + return true; + } + return false; + } + function grammarErrorAtPos(nodeForSourceFile, start, length, message, arg0, arg1, arg2) { + var sourceFile = ts.getSourceFileOfNode(nodeForSourceFile); + if (!hasParseDiagnostics(sourceFile)) { + diagnostics.add(ts.createFileDiagnostic(sourceFile, start, length, message, arg0, arg1, arg2)); + return true; + } + return false; + } + function grammarErrorOnNode(node, message, arg0, arg1, arg2) { + var sourceFile = ts.getSourceFileOfNode(node); + if (!hasParseDiagnostics(sourceFile)) { + diagnostics.add(ts.createDiagnosticForNode(node, message, arg0, arg1, arg2)); + return true; + } + return false; + } + function checkGrammarConstructorTypeParameters(node) { + var jsdocTypeParameters = ts.isInJSFile(node) ? ts.getJSDocTypeParameterDeclarations(node) : undefined; + var range = node.typeParameters || jsdocTypeParameters && ts.firstOrUndefined(jsdocTypeParameters); + if (range) { + var pos = range.pos === range.end ? range.pos : ts.skipTrivia(ts.getSourceFileOfNode(node).text, range.pos); + return grammarErrorAtPos(node, pos, range.end - pos, ts.Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration); + } + } + function checkGrammarConstructorTypeAnnotation(node) { + var type = ts.getEffectiveReturnTypeNode(node); + if (type) { + return grammarErrorOnNode(type, ts.Diagnostics.Type_annotation_cannot_appear_on_a_constructor_declaration); + } + } + function checkGrammarProperty(node) { + if (ts.isClassLike(node.parent)) { + if (checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_class_property_declaration_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type)) { + return true; + } + } + else if (node.parent.kind === 241 /* InterfaceDeclaration */) { + if (checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type)) { + return true; + } + if (node.initializer) { + return grammarErrorOnNode(node.initializer, ts.Diagnostics.An_interface_property_cannot_have_an_initializer); + } + } + else if (node.parent.kind === 168 /* TypeLiteral */) { + if (checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type)) { + return true; + } + if (node.initializer) { + return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_type_literal_property_cannot_have_an_initializer); + } + } + if (node.flags & 4194304 /* Ambient */) { + checkAmbientInitializer(node); + } + if (ts.isPropertyDeclaration(node) && node.exclamationToken && (!ts.isClassLike(node.parent) || !node.type || node.initializer || + node.flags & 4194304 /* Ambient */ || ts.hasModifier(node, 32 /* Static */ | 128 /* Abstract */))) { + return grammarErrorOnNode(node.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context); + } + } + function checkGrammarTopLevelElementForRequiredDeclareModifier(node) { + // A declare modifier is required for any top level .d.ts declaration except export=, export default, export as namespace + // interfaces and imports categories: + // + // DeclarationElement: + // ExportAssignment + // export_opt InterfaceDeclaration + // export_opt TypeAliasDeclaration + // export_opt ImportDeclaration + // export_opt ExternalImportDeclaration + // export_opt AmbientDeclaration + // + // TODO: The spec needs to be amended to reflect this grammar. + if (node.kind === 241 /* InterfaceDeclaration */ || + node.kind === 242 /* TypeAliasDeclaration */ || + node.kind === 249 /* ImportDeclaration */ || + node.kind === 248 /* ImportEqualsDeclaration */ || + node.kind === 255 /* ExportDeclaration */ || + node.kind === 254 /* ExportAssignment */ || + node.kind === 247 /* NamespaceExportDeclaration */ || + ts.hasModifier(node, 2 /* Ambient */ | 1 /* Export */ | 512 /* Default */)) { + return false; + } + return grammarErrorOnFirstToken(node, ts.Diagnostics.A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file); + } + function checkGrammarTopLevelElementsForRequiredDeclareModifier(file) { + for (var _i = 0, _a = file.statements; _i < _a.length; _i++) { + var decl = _a[_i]; + if (ts.isDeclaration(decl) || decl.kind === 219 /* VariableStatement */) { + if (checkGrammarTopLevelElementForRequiredDeclareModifier(decl)) { + return true; + } + } + } + return false; + } + function checkGrammarSourceFile(node) { + return !!(node.flags & 4194304 /* Ambient */) && checkGrammarTopLevelElementsForRequiredDeclareModifier(node); + } + function checkGrammarStatementInAmbientContext(node) { + if (node.flags & 4194304 /* Ambient */) { + // An accessors is already reported about the ambient context + if (ts.isAccessor(node.parent)) { + return getNodeLinks(node).hasReportedStatementInAmbientContext = true; + } + // Find containing block which is either Block, ModuleBlock, SourceFile + var links = getNodeLinks(node); + if (!links.hasReportedStatementInAmbientContext && ts.isFunctionLike(node.parent)) { + return getNodeLinks(node).hasReportedStatementInAmbientContext = grammarErrorOnFirstToken(node, ts.Diagnostics.An_implementation_cannot_be_declared_in_ambient_contexts); + } + // We are either parented by another statement, or some sort of block. + // If we're in a block, we only want to really report an error once + // to prevent noisiness. So use a bit on the block to indicate if + // this has already been reported, and don't report if it has. + // + if (node.parent.kind === 218 /* Block */ || node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 279 /* SourceFile */) { + var links_2 = getNodeLinks(node.parent); + // Check if the containing block ever report this error + if (!links_2.hasReportedStatementInAmbientContext) { + return links_2.hasReportedStatementInAmbientContext = grammarErrorOnFirstToken(node, ts.Diagnostics.Statements_are_not_allowed_in_ambient_contexts); + } + } + else { + // We must be parented by a statement. If so, there's no need + // to report the error as our parent will have already done it. + // Debug.assert(isStatement(node.parent)); + } + } + return false; + } + function checkGrammarNumericLiteral(node) { + // Grammar checking + if (node.numericLiteralFlags & 32 /* Octal */) { + var diagnosticMessage = void 0; + if (languageVersion >= 1 /* ES5 */) { + diagnosticMessage = ts.Diagnostics.Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0; + } + else if (ts.isChildOfNodeWithKind(node, 182 /* LiteralType */)) { + diagnosticMessage = ts.Diagnostics.Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0; + } + else if (ts.isChildOfNodeWithKind(node, 278 /* EnumMember */)) { + diagnosticMessage = ts.Diagnostics.Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0; + } + if (diagnosticMessage) { + var withMinus = ts.isPrefixUnaryExpression(node.parent) && node.parent.operator === 39 /* MinusToken */; + var literal = (withMinus ? "-" : "") + "0o" + node.text; + return grammarErrorOnNode(withMinus ? node.parent : node, diagnosticMessage, literal); + } + } + return false; + } + function checkGrammarBigIntLiteral(node) { + var literalType = ts.isLiteralTypeNode(node.parent) || + ts.isPrefixUnaryExpression(node.parent) && ts.isLiteralTypeNode(node.parent.parent); + if (!literalType) { + if (languageVersion < 6 /* ESNext */) { + if (grammarErrorOnNode(node, ts.Diagnostics.BigInt_literals_are_not_available_when_targeting_lower_than_ESNext)) { + return true; + } + } + } + return false; + } + function grammarErrorAfterFirstToken(node, message, arg0, arg1, arg2) { + var sourceFile = ts.getSourceFileOfNode(node); + if (!hasParseDiagnostics(sourceFile)) { + var span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos); + diagnostics.add(ts.createFileDiagnostic(sourceFile, ts.textSpanEnd(span), /*length*/ 0, message, arg0, arg1, arg2)); + return true; + } + return false; + } + function getAmbientModules() { + if (!ambientModulesCache) { + ambientModulesCache = []; + globals.forEach(function (global, sym) { + // No need to `unescapeLeadingUnderscores`, an escaped symbol is never an ambient module. + if (ambientModuleSymbolRegex.test(sym)) { + ambientModulesCache.push(global); + } + }); + } + return ambientModulesCache; + } + function checkGrammarImportCallExpression(node) { + if (moduleKind === ts.ModuleKind.ES2015) { + return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext); + } + if (node.typeArguments) { + return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_import_cannot_have_type_arguments); + } + var nodeArguments = node.arguments; + if (nodeArguments.length !== 1) { + return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_import_must_have_one_specifier_as_an_argument); + } + // see: parseArgumentOrArrayLiteralElement...we use this function which parse arguments of callExpression to parse specifier for dynamic import. + // parseArgumentOrArrayLiteralElement allows spread element to be in an argument list which is not allowed as specifier in dynamic import. + if (ts.isSpreadElement(nodeArguments[0])) { + return grammarErrorOnNode(nodeArguments[0], ts.Diagnostics.Specifier_of_dynamic_import_cannot_be_spread_element); + } + return false; + } + } + ts.createTypeChecker = createTypeChecker; + /** Like 'isDeclarationName', but returns true for LHS of `import { x as y }` or `export { x as y }`. */ + function isDeclarationNameOrImportPropertyName(name) { + switch (name.parent.kind) { + case 253 /* ImportSpecifier */: + case 257 /* ExportSpecifier */: + return ts.isIdentifier(name); + default: + return ts.isDeclarationName(name); + } + } + function isSomeImportDeclaration(decl) { + switch (decl.kind) { + case 250 /* ImportClause */: // For default import + case 248 /* ImportEqualsDeclaration */: + case 251 /* NamespaceImport */: + case 253 /* ImportSpecifier */: // For rename import `x as y` + return true; + case 72 /* Identifier */: + // For regular import, `decl` is an Identifier under the ImportSpecifier. + return decl.parent.kind === 253 /* ImportSpecifier */; + default: + return false; + } + } + var JsxNames; + (function (JsxNames) { + // tslint:disable variable-name + JsxNames.JSX = "JSX"; + JsxNames.IntrinsicElements = "IntrinsicElements"; + JsxNames.ElementClass = "ElementClass"; + JsxNames.ElementAttributesPropertyNameContainer = "ElementAttributesProperty"; // TODO: Deprecate and remove support + JsxNames.ElementChildrenAttributeNameContainer = "ElementChildrenAttribute"; + JsxNames.Element = "Element"; + JsxNames.IntrinsicAttributes = "IntrinsicAttributes"; + JsxNames.IntrinsicClassAttributes = "IntrinsicClassAttributes"; + JsxNames.LibraryManagedAttributes = "LibraryManagedAttributes"; + // tslint:enable variable-name + })(JsxNames || (JsxNames = {})); + function typeIsLiteralType(type) { + return !!(type.flags & 2944 /* Literal */); + } +})(ts || (ts = {})); +var ts; +(function (ts) { + function createSynthesizedNode(kind) { + var node = ts.createNode(kind, -1, -1); + node.flags |= 8 /* Synthesized */; + return node; + } + /* @internal */ + function updateNode(updated, original) { + if (updated !== original) { + setOriginalNode(updated, original); + setTextRange(updated, original); + ts.aggregateTransformFlags(updated); + } + return updated; + } + ts.updateNode = updateNode; + /** + * Make `elements` into a `NodeArray`. If `elements` is `undefined`, returns an empty `NodeArray`. + */ + function createNodeArray(elements, hasTrailingComma) { + if (!elements || elements === ts.emptyArray) { + elements = []; + } + else if (ts.isNodeArray(elements)) { + return elements; + } + var array = elements; + array.pos = -1; + array.end = -1; + array.hasTrailingComma = hasTrailingComma; + return array; + } + ts.createNodeArray = createNodeArray; + /** + * Creates a shallow, memberwise clone of a node with no source map location. + */ + /* @internal */ + function getSynthesizedClone(node) { + // We don't use "clone" from core.ts here, as we need to preserve the prototype chain of + // the original node. We also need to exclude specific properties and only include own- + // properties (to skip members already defined on the shared prototype). + if (node === undefined) { + return node; + } + var clone = createSynthesizedNode(node.kind); + clone.flags |= node.flags; + setOriginalNode(clone, node); + for (var key in node) { + if (clone.hasOwnProperty(key) || !node.hasOwnProperty(key)) { + continue; + } + clone[key] = node[key]; + } + return clone; + } + ts.getSynthesizedClone = getSynthesizedClone; + function createLiteral(value, isSingleQuote) { + if (typeof value === "number") { + return createNumericLiteral(value + ""); + } + if (typeof value === "object" && "base10Value" in value) { // PseudoBigInt + return createBigIntLiteral(ts.pseudoBigIntToString(value) + "n"); + } + if (typeof value === "boolean") { + return value ? createTrue() : createFalse(); + } + if (ts.isString(value)) { + var res = createStringLiteral(value); + if (isSingleQuote) + res.singleQuote = true; + return res; + } + return createLiteralFromNode(value); + } + ts.createLiteral = createLiteral; + function createNumericLiteral(value) { + var node = createSynthesizedNode(8 /* NumericLiteral */); + node.text = value; + node.numericLiteralFlags = 0; + return node; + } + ts.createNumericLiteral = createNumericLiteral; + function createBigIntLiteral(value) { + var node = createSynthesizedNode(9 /* BigIntLiteral */); + node.text = value; + return node; + } + ts.createBigIntLiteral = createBigIntLiteral; + function createStringLiteral(text) { + var node = createSynthesizedNode(10 /* StringLiteral */); + node.text = text; + return node; + } + ts.createStringLiteral = createStringLiteral; + function createRegularExpressionLiteral(text) { + var node = createSynthesizedNode(13 /* RegularExpressionLiteral */); + node.text = text; + return node; + } + ts.createRegularExpressionLiteral = createRegularExpressionLiteral; + function createLiteralFromNode(sourceNode) { + var node = createStringLiteral(ts.getTextOfIdentifierOrLiteral(sourceNode)); + node.textSourceNode = sourceNode; + return node; + } + function createIdentifier(text, typeArguments) { + var node = createSynthesizedNode(72 /* Identifier */); + node.escapedText = ts.escapeLeadingUnderscores(text); + node.originalKeywordKind = text ? ts.stringToToken(text) : 0 /* Unknown */; + node.autoGenerateFlags = 0 /* None */; + node.autoGenerateId = 0; + if (typeArguments) { + node.typeArguments = createNodeArray(typeArguments); + } + return node; + } + ts.createIdentifier = createIdentifier; + function updateIdentifier(node, typeArguments) { + return node.typeArguments !== typeArguments + ? updateNode(createIdentifier(ts.idText(node), typeArguments), node) + : node; + } + ts.updateIdentifier = updateIdentifier; + var nextAutoGenerateId = 0; + function createTempVariable(recordTempVariable, reservedInNestedScopes) { + var name = createIdentifier(""); + name.autoGenerateFlags = 1 /* Auto */; + name.autoGenerateId = nextAutoGenerateId; + nextAutoGenerateId++; + if (recordTempVariable) { + recordTempVariable(name); + } + if (reservedInNestedScopes) { + name.autoGenerateFlags |= 8 /* ReservedInNestedScopes */; + } + return name; + } + ts.createTempVariable = createTempVariable; + /** Create a unique temporary variable for use in a loop. */ + function createLoopVariable() { + var name = createIdentifier(""); + name.autoGenerateFlags = 2 /* Loop */; + name.autoGenerateId = nextAutoGenerateId; + nextAutoGenerateId++; + return name; + } + ts.createLoopVariable = createLoopVariable; + /** Create a unique name based on the supplied text. */ + function createUniqueName(text) { + var name = createIdentifier(text); + name.autoGenerateFlags = 3 /* Unique */; + name.autoGenerateId = nextAutoGenerateId; + nextAutoGenerateId++; + return name; + } + ts.createUniqueName = createUniqueName; + function createOptimisticUniqueName(text) { + var name = createIdentifier(text); + name.autoGenerateFlags = 3 /* Unique */ | 16 /* Optimistic */; + name.autoGenerateId = nextAutoGenerateId; + nextAutoGenerateId++; + return name; + } + ts.createOptimisticUniqueName = createOptimisticUniqueName; + /** Create a unique name based on the supplied text. This does not consider names injected by the transformer. */ + function createFileLevelUniqueName(text) { + var name = createOptimisticUniqueName(text); + name.autoGenerateFlags |= 32 /* FileLevel */; + return name; + } + ts.createFileLevelUniqueName = createFileLevelUniqueName; + function getGeneratedNameForNode(node, flags) { + var name = createIdentifier(node && ts.isIdentifier(node) ? ts.idText(node) : ""); + name.autoGenerateFlags = 4 /* Node */ | flags; + name.autoGenerateId = nextAutoGenerateId; + name.original = node; + nextAutoGenerateId++; + return name; + } + ts.getGeneratedNameForNode = getGeneratedNameForNode; + // Punctuation + function createToken(token) { + return createSynthesizedNode(token); + } + ts.createToken = createToken; + // Reserved words + function createSuper() { + return createSynthesizedNode(98 /* SuperKeyword */); + } + ts.createSuper = createSuper; + function createThis() { + return createSynthesizedNode(100 /* ThisKeyword */); + } + ts.createThis = createThis; + function createNull() { + return createSynthesizedNode(96 /* NullKeyword */); + } + ts.createNull = createNull; + function createTrue() { + return createSynthesizedNode(102 /* TrueKeyword */); + } + ts.createTrue = createTrue; + function createFalse() { + return createSynthesizedNode(87 /* FalseKeyword */); + } + ts.createFalse = createFalse; + // Modifiers + function createModifier(kind) { + return createToken(kind); + } + ts.createModifier = createModifier; + function createModifiersFromModifierFlags(flags) { + var result = []; + if (flags & 1 /* Export */) { + result.push(createModifier(85 /* ExportKeyword */)); + } + if (flags & 2 /* Ambient */) { + result.push(createModifier(125 /* DeclareKeyword */)); + } + if (flags & 512 /* Default */) { + result.push(createModifier(80 /* DefaultKeyword */)); + } + if (flags & 2048 /* Const */) { + result.push(createModifier(77 /* ConstKeyword */)); + } + if (flags & 4 /* Public */) { + result.push(createModifier(115 /* PublicKeyword */)); + } + if (flags & 8 /* Private */) { + result.push(createModifier(113 /* PrivateKeyword */)); + } + if (flags & 16 /* Protected */) { + result.push(createModifier(114 /* ProtectedKeyword */)); + } + if (flags & 128 /* Abstract */) { + result.push(createModifier(118 /* AbstractKeyword */)); + } + if (flags & 32 /* Static */) { + result.push(createModifier(116 /* StaticKeyword */)); + } + if (flags & 64 /* Readonly */) { + result.push(createModifier(133 /* ReadonlyKeyword */)); + } + if (flags & 256 /* Async */) { + result.push(createModifier(121 /* AsyncKeyword */)); + } + return result; + } + ts.createModifiersFromModifierFlags = createModifiersFromModifierFlags; + // Names + function createQualifiedName(left, right) { + var node = createSynthesizedNode(148 /* QualifiedName */); + node.left = left; + node.right = asName(right); + return node; + } + ts.createQualifiedName = createQualifiedName; + function updateQualifiedName(node, left, right) { + return node.left !== left + || node.right !== right + ? updateNode(createQualifiedName(left, right), node) + : node; + } + ts.updateQualifiedName = updateQualifiedName; + function parenthesizeForComputedName(expression) { + return ts.isCommaSequence(expression) + ? createParen(expression) + : expression; + } + function createComputedPropertyName(expression) { + var node = createSynthesizedNode(149 /* ComputedPropertyName */); + node.expression = parenthesizeForComputedName(expression); + return node; + } + ts.createComputedPropertyName = createComputedPropertyName; + function updateComputedPropertyName(node, expression) { + return node.expression !== expression + ? updateNode(createComputedPropertyName(expression), node) + : node; + } + ts.updateComputedPropertyName = updateComputedPropertyName; + // Signature elements + function createTypeParameterDeclaration(name, constraint, defaultType) { + var node = createSynthesizedNode(150 /* TypeParameter */); + node.name = asName(name); + node.constraint = constraint; + node.default = defaultType; + return node; + } + ts.createTypeParameterDeclaration = createTypeParameterDeclaration; + function updateTypeParameterDeclaration(node, name, constraint, defaultType) { + return node.name !== name + || node.constraint !== constraint + || node.default !== defaultType + ? updateNode(createTypeParameterDeclaration(name, constraint, defaultType), node) + : node; + } + ts.updateTypeParameterDeclaration = updateTypeParameterDeclaration; + function createParameter(decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer) { + var node = createSynthesizedNode(151 /* Parameter */); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.dotDotDotToken = dotDotDotToken; + node.name = asName(name); + node.questionToken = questionToken; + node.type = type; + node.initializer = initializer ? ts.parenthesizeExpressionForList(initializer) : undefined; + return node; + } + ts.createParameter = createParameter; + function updateParameter(node, decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.dotDotDotToken !== dotDotDotToken + || node.name !== name + || node.questionToken !== questionToken + || node.type !== type + || node.initializer !== initializer + ? updateNode(createParameter(decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer), node) + : node; + } + ts.updateParameter = updateParameter; + function createDecorator(expression) { + var node = createSynthesizedNode(152 /* Decorator */); + node.expression = ts.parenthesizeForAccess(expression); + return node; + } + ts.createDecorator = createDecorator; + function updateDecorator(node, expression) { + return node.expression !== expression + ? updateNode(createDecorator(expression), node) + : node; + } + ts.updateDecorator = updateDecorator; + // Type Elements + function createPropertySignature(modifiers, name, questionToken, type, initializer) { + var node = createSynthesizedNode(153 /* PropertySignature */); + node.modifiers = asNodeArray(modifiers); + node.name = asName(name); + node.questionToken = questionToken; + node.type = type; + node.initializer = initializer; + return node; + } + ts.createPropertySignature = createPropertySignature; + function updatePropertySignature(node, modifiers, name, questionToken, type, initializer) { + return node.modifiers !== modifiers + || node.name !== name + || node.questionToken !== questionToken + || node.type !== type + || node.initializer !== initializer + ? updateNode(createPropertySignature(modifiers, name, questionToken, type, initializer), node) + : node; + } + ts.updatePropertySignature = updatePropertySignature; + function createProperty(decorators, modifiers, name, questionOrExclamationToken, type, initializer) { + var node = createSynthesizedNode(154 /* PropertyDeclaration */); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.name = asName(name); + node.questionToken = questionOrExclamationToken !== undefined && questionOrExclamationToken.kind === 56 /* QuestionToken */ ? questionOrExclamationToken : undefined; + node.exclamationToken = questionOrExclamationToken !== undefined && questionOrExclamationToken.kind === 52 /* ExclamationToken */ ? questionOrExclamationToken : undefined; + node.type = type; + node.initializer = initializer; + return node; + } + ts.createProperty = createProperty; + function updateProperty(node, decorators, modifiers, name, questionOrExclamationToken, type, initializer) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.name !== name + || node.questionToken !== (questionOrExclamationToken !== undefined && questionOrExclamationToken.kind === 56 /* QuestionToken */ ? questionOrExclamationToken : undefined) + || node.exclamationToken !== (questionOrExclamationToken !== undefined && questionOrExclamationToken.kind === 52 /* ExclamationToken */ ? questionOrExclamationToken : undefined) + || node.type !== type + || node.initializer !== initializer + ? updateNode(createProperty(decorators, modifiers, name, questionOrExclamationToken, type, initializer), node) + : node; + } + ts.updateProperty = updateProperty; + function createMethodSignature(typeParameters, parameters, type, name, questionToken) { + var node = createSignatureDeclaration(155 /* MethodSignature */, typeParameters, parameters, type); + node.name = asName(name); + node.questionToken = questionToken; + return node; + } + ts.createMethodSignature = createMethodSignature; + function updateMethodSignature(node, typeParameters, parameters, type, name, questionToken) { + return node.typeParameters !== typeParameters + || node.parameters !== parameters + || node.type !== type + || node.name !== name + || node.questionToken !== questionToken + ? updateNode(createMethodSignature(typeParameters, parameters, type, name, questionToken), node) + : node; + } + ts.updateMethodSignature = updateMethodSignature; + function createMethod(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { + var node = createSynthesizedNode(156 /* MethodDeclaration */); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.asteriskToken = asteriskToken; + node.name = asName(name); + node.questionToken = questionToken; + node.typeParameters = asNodeArray(typeParameters); + node.parameters = createNodeArray(parameters); + node.type = type; + node.body = body; + return node; + } + ts.createMethod = createMethod; + function updateMethod(node, decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.asteriskToken !== asteriskToken + || node.name !== name + || node.questionToken !== questionToken + || node.typeParameters !== typeParameters + || node.parameters !== parameters + || node.type !== type + || node.body !== body + ? updateNode(createMethod(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body), node) + : node; + } + ts.updateMethod = updateMethod; + function createConstructor(decorators, modifiers, parameters, body) { + var node = createSynthesizedNode(157 /* Constructor */); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.typeParameters = undefined; + node.parameters = createNodeArray(parameters); + node.type = undefined; + node.body = body; + return node; + } + ts.createConstructor = createConstructor; + function updateConstructor(node, decorators, modifiers, parameters, body) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.parameters !== parameters + || node.body !== body + ? updateNode(createConstructor(decorators, modifiers, parameters, body), node) + : node; + } + ts.updateConstructor = updateConstructor; + function createGetAccessor(decorators, modifiers, name, parameters, type, body) { + var node = createSynthesizedNode(158 /* GetAccessor */); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.name = asName(name); + node.typeParameters = undefined; + node.parameters = createNodeArray(parameters); + node.type = type; + node.body = body; + return node; + } + ts.createGetAccessor = createGetAccessor; + function updateGetAccessor(node, decorators, modifiers, name, parameters, type, body) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.name !== name + || node.parameters !== parameters + || node.type !== type + || node.body !== body + ? updateNode(createGetAccessor(decorators, modifiers, name, parameters, type, body), node) + : node; + } + ts.updateGetAccessor = updateGetAccessor; + function createSetAccessor(decorators, modifiers, name, parameters, body) { + var node = createSynthesizedNode(159 /* SetAccessor */); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.name = asName(name); + node.typeParameters = undefined; + node.parameters = createNodeArray(parameters); + node.body = body; + return node; + } + ts.createSetAccessor = createSetAccessor; + function updateSetAccessor(node, decorators, modifiers, name, parameters, body) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.name !== name + || node.parameters !== parameters + || node.body !== body + ? updateNode(createSetAccessor(decorators, modifiers, name, parameters, body), node) + : node; + } + ts.updateSetAccessor = updateSetAccessor; + function createCallSignature(typeParameters, parameters, type) { + return createSignatureDeclaration(160 /* CallSignature */, typeParameters, parameters, type); + } + ts.createCallSignature = createCallSignature; + function updateCallSignature(node, typeParameters, parameters, type) { + return updateSignatureDeclaration(node, typeParameters, parameters, type); + } + ts.updateCallSignature = updateCallSignature; + function createConstructSignature(typeParameters, parameters, type) { + return createSignatureDeclaration(161 /* ConstructSignature */, typeParameters, parameters, type); + } + ts.createConstructSignature = createConstructSignature; + function updateConstructSignature(node, typeParameters, parameters, type) { + return updateSignatureDeclaration(node, typeParameters, parameters, type); + } + ts.updateConstructSignature = updateConstructSignature; + function createIndexSignature(decorators, modifiers, parameters, type) { + var node = createSynthesizedNode(162 /* IndexSignature */); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.parameters = createNodeArray(parameters); + node.type = type; + return node; + } + ts.createIndexSignature = createIndexSignature; + function updateIndexSignature(node, decorators, modifiers, parameters, type) { + return node.parameters !== parameters + || node.type !== type + || node.decorators !== decorators + || node.modifiers !== modifiers + ? updateNode(createIndexSignature(decorators, modifiers, parameters, type), node) + : node; + } + ts.updateIndexSignature = updateIndexSignature; + /* @internal */ + function createSignatureDeclaration(kind, typeParameters, parameters, type, typeArguments) { + var node = createSynthesizedNode(kind); + node.typeParameters = asNodeArray(typeParameters); + node.parameters = asNodeArray(parameters); + node.type = type; + node.typeArguments = asNodeArray(typeArguments); + return node; + } + ts.createSignatureDeclaration = createSignatureDeclaration; + function updateSignatureDeclaration(node, typeParameters, parameters, type) { + return node.typeParameters !== typeParameters + || node.parameters !== parameters + || node.type !== type + ? updateNode(createSignatureDeclaration(node.kind, typeParameters, parameters, type), node) + : node; + } + // Types + function createKeywordTypeNode(kind) { + return createSynthesizedNode(kind); + } + ts.createKeywordTypeNode = createKeywordTypeNode; + function createTypePredicateNode(parameterName, type) { + var node = createSynthesizedNode(163 /* TypePredicate */); + node.parameterName = asName(parameterName); + node.type = type; + return node; + } + ts.createTypePredicateNode = createTypePredicateNode; + function updateTypePredicateNode(node, parameterName, type) { + return node.parameterName !== parameterName + || node.type !== type + ? updateNode(createTypePredicateNode(parameterName, type), node) + : node; + } + ts.updateTypePredicateNode = updateTypePredicateNode; + function createTypeReferenceNode(typeName, typeArguments) { + var node = createSynthesizedNode(164 /* TypeReference */); + node.typeName = asName(typeName); + node.typeArguments = typeArguments && ts.parenthesizeTypeParameters(typeArguments); + return node; + } + ts.createTypeReferenceNode = createTypeReferenceNode; + function updateTypeReferenceNode(node, typeName, typeArguments) { + return node.typeName !== typeName + || node.typeArguments !== typeArguments + ? updateNode(createTypeReferenceNode(typeName, typeArguments), node) + : node; + } + ts.updateTypeReferenceNode = updateTypeReferenceNode; + function createFunctionTypeNode(typeParameters, parameters, type) { + return createSignatureDeclaration(165 /* FunctionType */, typeParameters, parameters, type); + } + ts.createFunctionTypeNode = createFunctionTypeNode; + function updateFunctionTypeNode(node, typeParameters, parameters, type) { + return updateSignatureDeclaration(node, typeParameters, parameters, type); + } + ts.updateFunctionTypeNode = updateFunctionTypeNode; + function createConstructorTypeNode(typeParameters, parameters, type) { + return createSignatureDeclaration(166 /* ConstructorType */, typeParameters, parameters, type); + } + ts.createConstructorTypeNode = createConstructorTypeNode; + function updateConstructorTypeNode(node, typeParameters, parameters, type) { + return updateSignatureDeclaration(node, typeParameters, parameters, type); + } + ts.updateConstructorTypeNode = updateConstructorTypeNode; + function createTypeQueryNode(exprName) { + var node = createSynthesizedNode(167 /* TypeQuery */); + node.exprName = exprName; + return node; + } + ts.createTypeQueryNode = createTypeQueryNode; + function updateTypeQueryNode(node, exprName) { + return node.exprName !== exprName + ? updateNode(createTypeQueryNode(exprName), node) + : node; + } + ts.updateTypeQueryNode = updateTypeQueryNode; + function createTypeLiteralNode(members) { + var node = createSynthesizedNode(168 /* TypeLiteral */); + node.members = createNodeArray(members); + return node; + } + ts.createTypeLiteralNode = createTypeLiteralNode; + function updateTypeLiteralNode(node, members) { + return node.members !== members + ? updateNode(createTypeLiteralNode(members), node) + : node; + } + ts.updateTypeLiteralNode = updateTypeLiteralNode; + function createArrayTypeNode(elementType) { + var node = createSynthesizedNode(169 /* ArrayType */); + node.elementType = ts.parenthesizeArrayTypeMember(elementType); + return node; + } + ts.createArrayTypeNode = createArrayTypeNode; + function updateArrayTypeNode(node, elementType) { + return node.elementType !== elementType + ? updateNode(createArrayTypeNode(elementType), node) + : node; + } + ts.updateArrayTypeNode = updateArrayTypeNode; + function createTupleTypeNode(elementTypes) { + var node = createSynthesizedNode(170 /* TupleType */); + node.elementTypes = createNodeArray(elementTypes); + return node; + } + ts.createTupleTypeNode = createTupleTypeNode; + function updateTupleTypeNode(node, elementTypes) { + return node.elementTypes !== elementTypes + ? updateNode(createTupleTypeNode(elementTypes), node) + : node; + } + ts.updateTupleTypeNode = updateTupleTypeNode; + function createOptionalTypeNode(type) { + var node = createSynthesizedNode(171 /* OptionalType */); + node.type = ts.parenthesizeArrayTypeMember(type); + return node; + } + ts.createOptionalTypeNode = createOptionalTypeNode; + function updateOptionalTypeNode(node, type) { + return node.type !== type + ? updateNode(createOptionalTypeNode(type), node) + : node; + } + ts.updateOptionalTypeNode = updateOptionalTypeNode; + function createRestTypeNode(type) { + var node = createSynthesizedNode(172 /* RestType */); + node.type = type; + return node; + } + ts.createRestTypeNode = createRestTypeNode; + function updateRestTypeNode(node, type) { + return node.type !== type + ? updateNode(createRestTypeNode(type), node) + : node; + } + ts.updateRestTypeNode = updateRestTypeNode; + function createUnionTypeNode(types) { + return createUnionOrIntersectionTypeNode(173 /* UnionType */, types); + } + ts.createUnionTypeNode = createUnionTypeNode; + function updateUnionTypeNode(node, types) { + return updateUnionOrIntersectionTypeNode(node, types); + } + ts.updateUnionTypeNode = updateUnionTypeNode; + function createIntersectionTypeNode(types) { + return createUnionOrIntersectionTypeNode(174 /* IntersectionType */, types); + } + ts.createIntersectionTypeNode = createIntersectionTypeNode; + function updateIntersectionTypeNode(node, types) { + return updateUnionOrIntersectionTypeNode(node, types); + } + ts.updateIntersectionTypeNode = updateIntersectionTypeNode; + function createUnionOrIntersectionTypeNode(kind, types) { + var node = createSynthesizedNode(kind); + node.types = ts.parenthesizeElementTypeMembers(types); + return node; + } + ts.createUnionOrIntersectionTypeNode = createUnionOrIntersectionTypeNode; + function updateUnionOrIntersectionTypeNode(node, types) { + return node.types !== types + ? updateNode(createUnionOrIntersectionTypeNode(node.kind, types), node) + : node; + } + function createConditionalTypeNode(checkType, extendsType, trueType, falseType) { + var node = createSynthesizedNode(175 /* ConditionalType */); + node.checkType = ts.parenthesizeConditionalTypeMember(checkType); + node.extendsType = ts.parenthesizeConditionalTypeMember(extendsType); + node.trueType = trueType; + node.falseType = falseType; + return node; + } + ts.createConditionalTypeNode = createConditionalTypeNode; + function updateConditionalTypeNode(node, checkType, extendsType, trueType, falseType) { + return node.checkType !== checkType + || node.extendsType !== extendsType + || node.trueType !== trueType + || node.falseType !== falseType + ? updateNode(createConditionalTypeNode(checkType, extendsType, trueType, falseType), node) + : node; + } + ts.updateConditionalTypeNode = updateConditionalTypeNode; + function createInferTypeNode(typeParameter) { + var node = createSynthesizedNode(176 /* InferType */); + node.typeParameter = typeParameter; + return node; + } + ts.createInferTypeNode = createInferTypeNode; + function updateInferTypeNode(node, typeParameter) { + return node.typeParameter !== typeParameter + ? updateNode(createInferTypeNode(typeParameter), node) + : node; + } + ts.updateInferTypeNode = updateInferTypeNode; + function createImportTypeNode(argument, qualifier, typeArguments, isTypeOf) { + var node = createSynthesizedNode(183 /* ImportType */); + node.argument = argument; + node.qualifier = qualifier; + node.typeArguments = asNodeArray(typeArguments); + node.isTypeOf = isTypeOf; + return node; + } + ts.createImportTypeNode = createImportTypeNode; + function updateImportTypeNode(node, argument, qualifier, typeArguments, isTypeOf) { + return node.argument !== argument + || node.qualifier !== qualifier + || node.typeArguments !== typeArguments + || node.isTypeOf !== isTypeOf + ? updateNode(createImportTypeNode(argument, qualifier, typeArguments, isTypeOf), node) + : node; + } + ts.updateImportTypeNode = updateImportTypeNode; + function createParenthesizedType(type) { + var node = createSynthesizedNode(177 /* ParenthesizedType */); + node.type = type; + return node; + } + ts.createParenthesizedType = createParenthesizedType; + function updateParenthesizedType(node, type) { + return node.type !== type + ? updateNode(createParenthesizedType(type), node) + : node; + } + ts.updateParenthesizedType = updateParenthesizedType; + function createThisTypeNode() { + return createSynthesizedNode(178 /* ThisType */); + } + ts.createThisTypeNode = createThisTypeNode; + function createTypeOperatorNode(operatorOrType, type) { + var node = createSynthesizedNode(179 /* TypeOperator */); + node.operator = typeof operatorOrType === "number" ? operatorOrType : 129 /* KeyOfKeyword */; + node.type = ts.parenthesizeElementTypeMember(typeof operatorOrType === "number" ? type : operatorOrType); + return node; + } + ts.createTypeOperatorNode = createTypeOperatorNode; + function updateTypeOperatorNode(node, type) { + return node.type !== type ? updateNode(createTypeOperatorNode(node.operator, type), node) : node; + } + ts.updateTypeOperatorNode = updateTypeOperatorNode; + function createIndexedAccessTypeNode(objectType, indexType) { + var node = createSynthesizedNode(180 /* IndexedAccessType */); + node.objectType = ts.parenthesizeElementTypeMember(objectType); + node.indexType = indexType; + return node; + } + ts.createIndexedAccessTypeNode = createIndexedAccessTypeNode; + function updateIndexedAccessTypeNode(node, objectType, indexType) { + return node.objectType !== objectType + || node.indexType !== indexType + ? updateNode(createIndexedAccessTypeNode(objectType, indexType), node) + : node; + } + ts.updateIndexedAccessTypeNode = updateIndexedAccessTypeNode; + function createMappedTypeNode(readonlyToken, typeParameter, questionToken, type) { + var node = createSynthesizedNode(181 /* MappedType */); + node.readonlyToken = readonlyToken; + node.typeParameter = typeParameter; + node.questionToken = questionToken; + node.type = type; + return node; + } + ts.createMappedTypeNode = createMappedTypeNode; + function updateMappedTypeNode(node, readonlyToken, typeParameter, questionToken, type) { + return node.readonlyToken !== readonlyToken + || node.typeParameter !== typeParameter + || node.questionToken !== questionToken + || node.type !== type + ? updateNode(createMappedTypeNode(readonlyToken, typeParameter, questionToken, type), node) + : node; + } + ts.updateMappedTypeNode = updateMappedTypeNode; + function createLiteralTypeNode(literal) { + var node = createSynthesizedNode(182 /* LiteralType */); + node.literal = literal; + return node; + } + ts.createLiteralTypeNode = createLiteralTypeNode; + function updateLiteralTypeNode(node, literal) { + return node.literal !== literal + ? updateNode(createLiteralTypeNode(literal), node) + : node; + } + ts.updateLiteralTypeNode = updateLiteralTypeNode; + // Binding Patterns + function createObjectBindingPattern(elements) { + var node = createSynthesizedNode(184 /* ObjectBindingPattern */); + node.elements = createNodeArray(elements); + return node; + } + ts.createObjectBindingPattern = createObjectBindingPattern; + function updateObjectBindingPattern(node, elements) { + return node.elements !== elements + ? updateNode(createObjectBindingPattern(elements), node) + : node; + } + ts.updateObjectBindingPattern = updateObjectBindingPattern; + function createArrayBindingPattern(elements) { + var node = createSynthesizedNode(185 /* ArrayBindingPattern */); + node.elements = createNodeArray(elements); + return node; + } + ts.createArrayBindingPattern = createArrayBindingPattern; + function updateArrayBindingPattern(node, elements) { + return node.elements !== elements + ? updateNode(createArrayBindingPattern(elements), node) + : node; + } + ts.updateArrayBindingPattern = updateArrayBindingPattern; + function createBindingElement(dotDotDotToken, propertyName, name, initializer) { + var node = createSynthesizedNode(186 /* BindingElement */); + node.dotDotDotToken = dotDotDotToken; + node.propertyName = asName(propertyName); + node.name = asName(name); + node.initializer = initializer; + return node; + } + ts.createBindingElement = createBindingElement; + function updateBindingElement(node, dotDotDotToken, propertyName, name, initializer) { + return node.propertyName !== propertyName + || node.dotDotDotToken !== dotDotDotToken + || node.name !== name + || node.initializer !== initializer + ? updateNode(createBindingElement(dotDotDotToken, propertyName, name, initializer), node) + : node; + } + ts.updateBindingElement = updateBindingElement; + // Expression + function createArrayLiteral(elements, multiLine) { + var node = createSynthesizedNode(187 /* ArrayLiteralExpression */); + node.elements = ts.parenthesizeListElements(createNodeArray(elements)); + if (multiLine) + node.multiLine = true; + return node; + } + ts.createArrayLiteral = createArrayLiteral; + function updateArrayLiteral(node, elements) { + return node.elements !== elements + ? updateNode(createArrayLiteral(elements, node.multiLine), node) + : node; + } + ts.updateArrayLiteral = updateArrayLiteral; + function createObjectLiteral(properties, multiLine) { + var node = createSynthesizedNode(188 /* ObjectLiteralExpression */); + node.properties = createNodeArray(properties); + if (multiLine) + node.multiLine = true; + return node; + } + ts.createObjectLiteral = createObjectLiteral; + function updateObjectLiteral(node, properties) { + return node.properties !== properties + ? updateNode(createObjectLiteral(properties, node.multiLine), node) + : node; + } + ts.updateObjectLiteral = updateObjectLiteral; + function createPropertyAccess(expression, name) { + var node = createSynthesizedNode(189 /* PropertyAccessExpression */); + node.expression = ts.parenthesizeForAccess(expression); + node.name = asName(name); // TODO: GH#18217 + setEmitFlags(node, 131072 /* NoIndentation */); + return node; + } + ts.createPropertyAccess = createPropertyAccess; + function updatePropertyAccess(node, expression, name) { + // Because we are updating existed propertyAccess we want to inherit its emitFlags + // instead of using the default from createPropertyAccess + return node.expression !== expression + || node.name !== name + ? updateNode(setEmitFlags(createPropertyAccess(expression, name), ts.getEmitFlags(node)), node) + : node; + } + ts.updatePropertyAccess = updatePropertyAccess; + function createElementAccess(expression, index) { + var node = createSynthesizedNode(190 /* ElementAccessExpression */); + node.expression = ts.parenthesizeForAccess(expression); + node.argumentExpression = asExpression(index); + return node; + } + ts.createElementAccess = createElementAccess; + function updateElementAccess(node, expression, argumentExpression) { + return node.expression !== expression + || node.argumentExpression !== argumentExpression + ? updateNode(createElementAccess(expression, argumentExpression), node) + : node; + } + ts.updateElementAccess = updateElementAccess; + function createCall(expression, typeArguments, argumentsArray) { + var node = createSynthesizedNode(191 /* CallExpression */); + node.expression = ts.parenthesizeForAccess(expression); + node.typeArguments = asNodeArray(typeArguments); + node.arguments = ts.parenthesizeListElements(createNodeArray(argumentsArray)); + return node; + } + ts.createCall = createCall; + function updateCall(node, expression, typeArguments, argumentsArray) { + return node.expression !== expression + || node.typeArguments !== typeArguments + || node.arguments !== argumentsArray + ? updateNode(createCall(expression, typeArguments, argumentsArray), node) + : node; + } + ts.updateCall = updateCall; + function createNew(expression, typeArguments, argumentsArray) { + var node = createSynthesizedNode(192 /* NewExpression */); + node.expression = ts.parenthesizeForNew(expression); + node.typeArguments = asNodeArray(typeArguments); + node.arguments = argumentsArray ? ts.parenthesizeListElements(createNodeArray(argumentsArray)) : undefined; + return node; + } + ts.createNew = createNew; + function updateNew(node, expression, typeArguments, argumentsArray) { + return node.expression !== expression + || node.typeArguments !== typeArguments + || node.arguments !== argumentsArray + ? updateNode(createNew(expression, typeArguments, argumentsArray), node) + : node; + } + ts.updateNew = updateNew; + function createTaggedTemplate(tag, typeArgumentsOrTemplate, template) { + var node = createSynthesizedNode(193 /* TaggedTemplateExpression */); + node.tag = ts.parenthesizeForAccess(tag); + if (template) { + node.typeArguments = asNodeArray(typeArgumentsOrTemplate); + node.template = template; + } + else { + node.typeArguments = undefined; + node.template = typeArgumentsOrTemplate; + } + return node; + } + ts.createTaggedTemplate = createTaggedTemplate; + function updateTaggedTemplate(node, tag, typeArgumentsOrTemplate, template) { + return node.tag !== tag + || (template + ? node.typeArguments !== typeArgumentsOrTemplate || node.template !== template + : node.typeArguments !== undefined || node.template !== typeArgumentsOrTemplate) + ? updateNode(createTaggedTemplate(tag, typeArgumentsOrTemplate, template), node) + : node; + } + ts.updateTaggedTemplate = updateTaggedTemplate; + function createTypeAssertion(type, expression) { + var node = createSynthesizedNode(194 /* TypeAssertionExpression */); + node.type = type; + node.expression = ts.parenthesizePrefixOperand(expression); + return node; + } + ts.createTypeAssertion = createTypeAssertion; + function updateTypeAssertion(node, type, expression) { + return node.type !== type + || node.expression !== expression + ? updateNode(createTypeAssertion(type, expression), node) + : node; + } + ts.updateTypeAssertion = updateTypeAssertion; + function createParen(expression) { + var node = createSynthesizedNode(195 /* ParenthesizedExpression */); + node.expression = expression; + return node; + } + ts.createParen = createParen; + function updateParen(node, expression) { + return node.expression !== expression + ? updateNode(createParen(expression), node) + : node; + } + ts.updateParen = updateParen; + function createFunctionExpression(modifiers, asteriskToken, name, typeParameters, parameters, type, body) { + var node = createSynthesizedNode(196 /* FunctionExpression */); + node.modifiers = asNodeArray(modifiers); + node.asteriskToken = asteriskToken; + node.name = asName(name); + node.typeParameters = asNodeArray(typeParameters); + node.parameters = createNodeArray(parameters); + node.type = type; + node.body = body; + return node; + } + ts.createFunctionExpression = createFunctionExpression; + function updateFunctionExpression(node, modifiers, asteriskToken, name, typeParameters, parameters, type, body) { + return node.name !== name + || node.modifiers !== modifiers + || node.asteriskToken !== asteriskToken + || node.typeParameters !== typeParameters + || node.parameters !== parameters + || node.type !== type + || node.body !== body + ? updateNode(createFunctionExpression(modifiers, asteriskToken, name, typeParameters, parameters, type, body), node) + : node; + } + ts.updateFunctionExpression = updateFunctionExpression; + function createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body) { + var node = createSynthesizedNode(197 /* ArrowFunction */); + node.modifiers = asNodeArray(modifiers); + node.typeParameters = asNodeArray(typeParameters); + node.parameters = createNodeArray(parameters); + node.type = type; + node.equalsGreaterThanToken = equalsGreaterThanToken || createToken(37 /* EqualsGreaterThanToken */); + node.body = ts.parenthesizeConciseBody(body); + return node; + } + ts.createArrowFunction = createArrowFunction; + function updateArrowFunction(node, modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body) { + return node.modifiers !== modifiers + || node.typeParameters !== typeParameters + || node.parameters !== parameters + || node.type !== type + || node.equalsGreaterThanToken !== equalsGreaterThanToken + || node.body !== body + ? updateNode(createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body), node) + : node; + } + ts.updateArrowFunction = updateArrowFunction; + function createDelete(expression) { + var node = createSynthesizedNode(198 /* DeleteExpression */); + node.expression = ts.parenthesizePrefixOperand(expression); + return node; + } + ts.createDelete = createDelete; + function updateDelete(node, expression) { + return node.expression !== expression + ? updateNode(createDelete(expression), node) + : node; + } + ts.updateDelete = updateDelete; + function createTypeOf(expression) { + var node = createSynthesizedNode(199 /* TypeOfExpression */); + node.expression = ts.parenthesizePrefixOperand(expression); + return node; + } + ts.createTypeOf = createTypeOf; + function updateTypeOf(node, expression) { + return node.expression !== expression + ? updateNode(createTypeOf(expression), node) + : node; + } + ts.updateTypeOf = updateTypeOf; + function createVoid(expression) { + var node = createSynthesizedNode(200 /* VoidExpression */); + node.expression = ts.parenthesizePrefixOperand(expression); + return node; + } + ts.createVoid = createVoid; + function updateVoid(node, expression) { + return node.expression !== expression + ? updateNode(createVoid(expression), node) + : node; + } + ts.updateVoid = updateVoid; + function createAwait(expression) { + var node = createSynthesizedNode(201 /* AwaitExpression */); + node.expression = ts.parenthesizePrefixOperand(expression); + return node; + } + ts.createAwait = createAwait; + function updateAwait(node, expression) { + return node.expression !== expression + ? updateNode(createAwait(expression), node) + : node; + } + ts.updateAwait = updateAwait; + function createPrefix(operator, operand) { + var node = createSynthesizedNode(202 /* PrefixUnaryExpression */); + node.operator = operator; + node.operand = ts.parenthesizePrefixOperand(operand); + return node; + } + ts.createPrefix = createPrefix; + function updatePrefix(node, operand) { + return node.operand !== operand + ? updateNode(createPrefix(node.operator, operand), node) + : node; + } + ts.updatePrefix = updatePrefix; + function createPostfix(operand, operator) { + var node = createSynthesizedNode(203 /* PostfixUnaryExpression */); + node.operand = ts.parenthesizePostfixOperand(operand); + node.operator = operator; + return node; + } + ts.createPostfix = createPostfix; + function updatePostfix(node, operand) { + return node.operand !== operand + ? updateNode(createPostfix(operand, node.operator), node) + : node; + } + ts.updatePostfix = updatePostfix; + function createBinary(left, operator, right) { + var node = createSynthesizedNode(204 /* BinaryExpression */); + var operatorToken = asToken(operator); + var operatorKind = operatorToken.kind; + node.left = ts.parenthesizeBinaryOperand(operatorKind, left, /*isLeftSideOfBinary*/ true, /*leftOperand*/ undefined); + node.operatorToken = operatorToken; + node.right = ts.parenthesizeBinaryOperand(operatorKind, right, /*isLeftSideOfBinary*/ false, node.left); + return node; + } + ts.createBinary = createBinary; + function updateBinary(node, left, right, operator) { + return node.left !== left + || node.right !== right + ? updateNode(createBinary(left, operator || node.operatorToken, right), node) + : node; + } + ts.updateBinary = updateBinary; + function createConditional(condition, questionTokenOrWhenTrue, whenTrueOrWhenFalse, colonToken, whenFalse) { + var node = createSynthesizedNode(205 /* ConditionalExpression */); + node.condition = ts.parenthesizeForConditionalHead(condition); + node.questionToken = whenFalse ? questionTokenOrWhenTrue : createToken(56 /* QuestionToken */); + node.whenTrue = ts.parenthesizeSubexpressionOfConditionalExpression(whenFalse ? whenTrueOrWhenFalse : questionTokenOrWhenTrue); + node.colonToken = whenFalse ? colonToken : createToken(57 /* ColonToken */); + node.whenFalse = ts.parenthesizeSubexpressionOfConditionalExpression(whenFalse ? whenFalse : whenTrueOrWhenFalse); + return node; + } + ts.createConditional = createConditional; + function updateConditional(node, condition, questionToken, whenTrue, colonToken, whenFalse) { + return node.condition !== condition + || node.questionToken !== questionToken + || node.whenTrue !== whenTrue + || node.colonToken !== colonToken + || node.whenFalse !== whenFalse + ? updateNode(createConditional(condition, questionToken, whenTrue, colonToken, whenFalse), node) + : node; + } + ts.updateConditional = updateConditional; + function createTemplateExpression(head, templateSpans) { + var node = createSynthesizedNode(206 /* TemplateExpression */); + node.head = head; + node.templateSpans = createNodeArray(templateSpans); + return node; + } + ts.createTemplateExpression = createTemplateExpression; + function updateTemplateExpression(node, head, templateSpans) { + return node.head !== head + || node.templateSpans !== templateSpans + ? updateNode(createTemplateExpression(head, templateSpans), node) + : node; + } + ts.updateTemplateExpression = updateTemplateExpression; + function createTemplateHead(text) { + var node = createSynthesizedNode(15 /* TemplateHead */); + node.text = text; + return node; + } + ts.createTemplateHead = createTemplateHead; + function createTemplateMiddle(text) { + var node = createSynthesizedNode(16 /* TemplateMiddle */); + node.text = text; + return node; + } + ts.createTemplateMiddle = createTemplateMiddle; + function createTemplateTail(text) { + var node = createSynthesizedNode(17 /* TemplateTail */); + node.text = text; + return node; + } + ts.createTemplateTail = createTemplateTail; + function createNoSubstitutionTemplateLiteral(text) { + var node = createSynthesizedNode(14 /* NoSubstitutionTemplateLiteral */); + node.text = text; + return node; + } + ts.createNoSubstitutionTemplateLiteral = createNoSubstitutionTemplateLiteral; + function createYield(asteriskTokenOrExpression, expression) { + var node = createSynthesizedNode(207 /* YieldExpression */); + node.asteriskToken = asteriskTokenOrExpression && asteriskTokenOrExpression.kind === 40 /* AsteriskToken */ ? asteriskTokenOrExpression : undefined; + node.expression = asteriskTokenOrExpression && asteriskTokenOrExpression.kind !== 40 /* AsteriskToken */ ? asteriskTokenOrExpression : expression; + return node; + } + ts.createYield = createYield; + function updateYield(node, asteriskToken, expression) { + return node.expression !== expression + || node.asteriskToken !== asteriskToken + ? updateNode(createYield(asteriskToken, expression), node) + : node; + } + ts.updateYield = updateYield; + function createSpread(expression) { + var node = createSynthesizedNode(208 /* SpreadElement */); + node.expression = ts.parenthesizeExpressionForList(expression); + return node; + } + ts.createSpread = createSpread; + function updateSpread(node, expression) { + return node.expression !== expression + ? updateNode(createSpread(expression), node) + : node; + } + ts.updateSpread = updateSpread; + function createClassExpression(modifiers, name, typeParameters, heritageClauses, members) { + var node = createSynthesizedNode(209 /* ClassExpression */); + node.decorators = undefined; + node.modifiers = asNodeArray(modifiers); + node.name = asName(name); + node.typeParameters = asNodeArray(typeParameters); + node.heritageClauses = asNodeArray(heritageClauses); + node.members = createNodeArray(members); + return node; + } + ts.createClassExpression = createClassExpression; + function updateClassExpression(node, modifiers, name, typeParameters, heritageClauses, members) { + return node.modifiers !== modifiers + || node.name !== name + || node.typeParameters !== typeParameters + || node.heritageClauses !== heritageClauses + || node.members !== members + ? updateNode(createClassExpression(modifiers, name, typeParameters, heritageClauses, members), node) + : node; + } + ts.updateClassExpression = updateClassExpression; + function createOmittedExpression() { + return createSynthesizedNode(210 /* OmittedExpression */); + } + ts.createOmittedExpression = createOmittedExpression; + function createExpressionWithTypeArguments(typeArguments, expression) { + var node = createSynthesizedNode(211 /* ExpressionWithTypeArguments */); + node.expression = ts.parenthesizeForAccess(expression); + node.typeArguments = asNodeArray(typeArguments); + return node; + } + ts.createExpressionWithTypeArguments = createExpressionWithTypeArguments; + function updateExpressionWithTypeArguments(node, typeArguments, expression) { + return node.typeArguments !== typeArguments + || node.expression !== expression + ? updateNode(createExpressionWithTypeArguments(typeArguments, expression), node) + : node; + } + ts.updateExpressionWithTypeArguments = updateExpressionWithTypeArguments; + function createAsExpression(expression, type) { + var node = createSynthesizedNode(212 /* AsExpression */); + node.expression = expression; + node.type = type; + return node; + } + ts.createAsExpression = createAsExpression; + function updateAsExpression(node, expression, type) { + return node.expression !== expression + || node.type !== type + ? updateNode(createAsExpression(expression, type), node) + : node; + } + ts.updateAsExpression = updateAsExpression; + function createNonNullExpression(expression) { + var node = createSynthesizedNode(213 /* NonNullExpression */); + node.expression = ts.parenthesizeForAccess(expression); + return node; + } + ts.createNonNullExpression = createNonNullExpression; + function updateNonNullExpression(node, expression) { + return node.expression !== expression + ? updateNode(createNonNullExpression(expression), node) + : node; + } + ts.updateNonNullExpression = updateNonNullExpression; + function createMetaProperty(keywordToken, name) { + var node = createSynthesizedNode(214 /* MetaProperty */); + node.keywordToken = keywordToken; + node.name = name; + return node; + } + ts.createMetaProperty = createMetaProperty; + function updateMetaProperty(node, name) { + return node.name !== name + ? updateNode(createMetaProperty(node.keywordToken, name), node) + : node; + } + ts.updateMetaProperty = updateMetaProperty; + // Misc + function createTemplateSpan(expression, literal) { + var node = createSynthesizedNode(216 /* TemplateSpan */); + node.expression = expression; + node.literal = literal; + return node; + } + ts.createTemplateSpan = createTemplateSpan; + function updateTemplateSpan(node, expression, literal) { + return node.expression !== expression + || node.literal !== literal + ? updateNode(createTemplateSpan(expression, literal), node) + : node; + } + ts.updateTemplateSpan = updateTemplateSpan; + function createSemicolonClassElement() { + return createSynthesizedNode(217 /* SemicolonClassElement */); + } + ts.createSemicolonClassElement = createSemicolonClassElement; + // Element + function createBlock(statements, multiLine) { + var block = createSynthesizedNode(218 /* Block */); + block.statements = createNodeArray(statements); + if (multiLine) + block.multiLine = multiLine; + return block; + } + ts.createBlock = createBlock; + function updateBlock(node, statements) { + return node.statements !== statements + ? updateNode(createBlock(statements, node.multiLine), node) + : node; + } + ts.updateBlock = updateBlock; + function createVariableStatement(modifiers, declarationList) { + var node = createSynthesizedNode(219 /* VariableStatement */); + node.decorators = undefined; + node.modifiers = asNodeArray(modifiers); + node.declarationList = ts.isArray(declarationList) ? createVariableDeclarationList(declarationList) : declarationList; + return node; + } + ts.createVariableStatement = createVariableStatement; + function updateVariableStatement(node, modifiers, declarationList) { + return node.modifiers !== modifiers + || node.declarationList !== declarationList + ? updateNode(createVariableStatement(modifiers, declarationList), node) + : node; + } + ts.updateVariableStatement = updateVariableStatement; + function createEmptyStatement() { + return createSynthesizedNode(220 /* EmptyStatement */); + } + ts.createEmptyStatement = createEmptyStatement; + function createExpressionStatement(expression) { + var node = createSynthesizedNode(221 /* ExpressionStatement */); + node.expression = ts.parenthesizeExpressionForExpressionStatement(expression); + return node; + } + ts.createExpressionStatement = createExpressionStatement; + function updateExpressionStatement(node, expression) { + return node.expression !== expression + ? updateNode(createExpressionStatement(expression), node) + : node; + } + ts.updateExpressionStatement = updateExpressionStatement; + /** @deprecated Use `createExpressionStatement` instead. */ + ts.createStatement = createExpressionStatement; + /** @deprecated Use `updateExpressionStatement` instead. */ + ts.updateStatement = updateExpressionStatement; + function createIf(expression, thenStatement, elseStatement) { + var node = createSynthesizedNode(222 /* IfStatement */); + node.expression = expression; + node.thenStatement = thenStatement; + node.elseStatement = elseStatement; + return node; + } + ts.createIf = createIf; + function updateIf(node, expression, thenStatement, elseStatement) { + return node.expression !== expression + || node.thenStatement !== thenStatement + || node.elseStatement !== elseStatement + ? updateNode(createIf(expression, thenStatement, elseStatement), node) + : node; + } + ts.updateIf = updateIf; + function createDo(statement, expression) { + var node = createSynthesizedNode(223 /* DoStatement */); + node.statement = statement; + node.expression = expression; + return node; + } + ts.createDo = createDo; + function updateDo(node, statement, expression) { + return node.statement !== statement + || node.expression !== expression + ? updateNode(createDo(statement, expression), node) + : node; + } + ts.updateDo = updateDo; + function createWhile(expression, statement) { + var node = createSynthesizedNode(224 /* WhileStatement */); + node.expression = expression; + node.statement = statement; + return node; + } + ts.createWhile = createWhile; + function updateWhile(node, expression, statement) { + return node.expression !== expression + || node.statement !== statement + ? updateNode(createWhile(expression, statement), node) + : node; + } + ts.updateWhile = updateWhile; + function createFor(initializer, condition, incrementor, statement) { + var node = createSynthesizedNode(225 /* ForStatement */); + node.initializer = initializer; + node.condition = condition; + node.incrementor = incrementor; + node.statement = statement; + return node; + } + ts.createFor = createFor; + function updateFor(node, initializer, condition, incrementor, statement) { + return node.initializer !== initializer + || node.condition !== condition + || node.incrementor !== incrementor + || node.statement !== statement + ? updateNode(createFor(initializer, condition, incrementor, statement), node) + : node; + } + ts.updateFor = updateFor; + function createForIn(initializer, expression, statement) { + var node = createSynthesizedNode(226 /* ForInStatement */); + node.initializer = initializer; + node.expression = expression; + node.statement = statement; + return node; + } + ts.createForIn = createForIn; + function updateForIn(node, initializer, expression, statement) { + return node.initializer !== initializer + || node.expression !== expression + || node.statement !== statement + ? updateNode(createForIn(initializer, expression, statement), node) + : node; + } + ts.updateForIn = updateForIn; + function createForOf(awaitModifier, initializer, expression, statement) { + var node = createSynthesizedNode(227 /* ForOfStatement */); + node.awaitModifier = awaitModifier; + node.initializer = initializer; + node.expression = expression; + node.statement = statement; + return node; + } + ts.createForOf = createForOf; + function updateForOf(node, awaitModifier, initializer, expression, statement) { + return node.awaitModifier !== awaitModifier + || node.initializer !== initializer + || node.expression !== expression + || node.statement !== statement + ? updateNode(createForOf(awaitModifier, initializer, expression, statement), node) + : node; + } + ts.updateForOf = updateForOf; + function createContinue(label) { + var node = createSynthesizedNode(228 /* ContinueStatement */); + node.label = asName(label); + return node; + } + ts.createContinue = createContinue; + function updateContinue(node, label) { + return node.label !== label + ? updateNode(createContinue(label), node) + : node; + } + ts.updateContinue = updateContinue; + function createBreak(label) { + var node = createSynthesizedNode(229 /* BreakStatement */); + node.label = asName(label); + return node; + } + ts.createBreak = createBreak; + function updateBreak(node, label) { + return node.label !== label + ? updateNode(createBreak(label), node) + : node; + } + ts.updateBreak = updateBreak; + function createReturn(expression) { + var node = createSynthesizedNode(230 /* ReturnStatement */); + node.expression = expression; + return node; + } + ts.createReturn = createReturn; + function updateReturn(node, expression) { + return node.expression !== expression + ? updateNode(createReturn(expression), node) + : node; + } + ts.updateReturn = updateReturn; + function createWith(expression, statement) { + var node = createSynthesizedNode(231 /* WithStatement */); + node.expression = expression; + node.statement = statement; + return node; + } + ts.createWith = createWith; + function updateWith(node, expression, statement) { + return node.expression !== expression + || node.statement !== statement + ? updateNode(createWith(expression, statement), node) + : node; + } + ts.updateWith = updateWith; + function createSwitch(expression, caseBlock) { + var node = createSynthesizedNode(232 /* SwitchStatement */); + node.expression = ts.parenthesizeExpressionForList(expression); + node.caseBlock = caseBlock; + return node; + } + ts.createSwitch = createSwitch; + function updateSwitch(node, expression, caseBlock) { + return node.expression !== expression + || node.caseBlock !== caseBlock + ? updateNode(createSwitch(expression, caseBlock), node) + : node; + } + ts.updateSwitch = updateSwitch; + function createLabel(label, statement) { + var node = createSynthesizedNode(233 /* LabeledStatement */); + node.label = asName(label); + node.statement = statement; + return node; + } + ts.createLabel = createLabel; + function updateLabel(node, label, statement) { + return node.label !== label + || node.statement !== statement + ? updateNode(createLabel(label, statement), node) + : node; + } + ts.updateLabel = updateLabel; + function createThrow(expression) { + var node = createSynthesizedNode(234 /* ThrowStatement */); + node.expression = expression; + return node; + } + ts.createThrow = createThrow; + function updateThrow(node, expression) { + return node.expression !== expression + ? updateNode(createThrow(expression), node) + : node; + } + ts.updateThrow = updateThrow; + function createTry(tryBlock, catchClause, finallyBlock) { + var node = createSynthesizedNode(235 /* TryStatement */); + node.tryBlock = tryBlock; + node.catchClause = catchClause; + node.finallyBlock = finallyBlock; + return node; + } + ts.createTry = createTry; + function updateTry(node, tryBlock, catchClause, finallyBlock) { + return node.tryBlock !== tryBlock + || node.catchClause !== catchClause + || node.finallyBlock !== finallyBlock + ? updateNode(createTry(tryBlock, catchClause, finallyBlock), node) + : node; + } + ts.updateTry = updateTry; + function createDebuggerStatement() { + return createSynthesizedNode(236 /* DebuggerStatement */); + } + ts.createDebuggerStatement = createDebuggerStatement; + function createVariableDeclaration(name, type, initializer) { + var node = createSynthesizedNode(237 /* VariableDeclaration */); + node.name = asName(name); + node.type = type; + node.initializer = initializer !== undefined ? ts.parenthesizeExpressionForList(initializer) : undefined; + return node; + } + ts.createVariableDeclaration = createVariableDeclaration; + function updateVariableDeclaration(node, name, type, initializer) { + return node.name !== name + || node.type !== type + || node.initializer !== initializer + ? updateNode(createVariableDeclaration(name, type, initializer), node) + : node; + } + ts.updateVariableDeclaration = updateVariableDeclaration; + function createVariableDeclarationList(declarations, flags) { + if (flags === void 0) { flags = 0 /* None */; } + var node = createSynthesizedNode(238 /* VariableDeclarationList */); + node.flags |= flags & 3 /* BlockScoped */; + node.declarations = createNodeArray(declarations); + return node; + } + ts.createVariableDeclarationList = createVariableDeclarationList; + function updateVariableDeclarationList(node, declarations) { + return node.declarations !== declarations + ? updateNode(createVariableDeclarationList(declarations, node.flags), node) + : node; + } + ts.updateVariableDeclarationList = updateVariableDeclarationList; + function createFunctionDeclaration(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body) { + var node = createSynthesizedNode(239 /* FunctionDeclaration */); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.asteriskToken = asteriskToken; + node.name = asName(name); + node.typeParameters = asNodeArray(typeParameters); + node.parameters = createNodeArray(parameters); + node.type = type; + node.body = body; + return node; + } + ts.createFunctionDeclaration = createFunctionDeclaration; + function updateFunctionDeclaration(node, decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.asteriskToken !== asteriskToken + || node.name !== name + || node.typeParameters !== typeParameters + || node.parameters !== parameters + || node.type !== type + || node.body !== body + ? updateNode(createFunctionDeclaration(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body), node) + : node; + } + ts.updateFunctionDeclaration = updateFunctionDeclaration; + function createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) { + var node = createSynthesizedNode(240 /* ClassDeclaration */); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.name = asName(name); + node.typeParameters = asNodeArray(typeParameters); + node.heritageClauses = asNodeArray(heritageClauses); + node.members = createNodeArray(members); + return node; + } + ts.createClassDeclaration = createClassDeclaration; + function updateClassDeclaration(node, decorators, modifiers, name, typeParameters, heritageClauses, members) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.name !== name + || node.typeParameters !== typeParameters + || node.heritageClauses !== heritageClauses + || node.members !== members + ? updateNode(createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members), node) + : node; + } + ts.updateClassDeclaration = updateClassDeclaration; + function createInterfaceDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) { + var node = createSynthesizedNode(241 /* InterfaceDeclaration */); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.name = asName(name); + node.typeParameters = asNodeArray(typeParameters); + node.heritageClauses = asNodeArray(heritageClauses); + node.members = createNodeArray(members); + return node; + } + ts.createInterfaceDeclaration = createInterfaceDeclaration; + function updateInterfaceDeclaration(node, decorators, modifiers, name, typeParameters, heritageClauses, members) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.name !== name + || node.typeParameters !== typeParameters + || node.heritageClauses !== heritageClauses + || node.members !== members + ? updateNode(createInterfaceDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members), node) + : node; + } + ts.updateInterfaceDeclaration = updateInterfaceDeclaration; + function createTypeAliasDeclaration(decorators, modifiers, name, typeParameters, type) { + var node = createSynthesizedNode(242 /* TypeAliasDeclaration */); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.name = asName(name); + node.typeParameters = asNodeArray(typeParameters); + node.type = type; + return node; + } + ts.createTypeAliasDeclaration = createTypeAliasDeclaration; + function updateTypeAliasDeclaration(node, decorators, modifiers, name, typeParameters, type) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.name !== name + || node.typeParameters !== typeParameters + || node.type !== type + ? updateNode(createTypeAliasDeclaration(decorators, modifiers, name, typeParameters, type), node) + : node; + } + ts.updateTypeAliasDeclaration = updateTypeAliasDeclaration; + function createEnumDeclaration(decorators, modifiers, name, members) { + var node = createSynthesizedNode(243 /* EnumDeclaration */); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.name = asName(name); + node.members = createNodeArray(members); + return node; + } + ts.createEnumDeclaration = createEnumDeclaration; + function updateEnumDeclaration(node, decorators, modifiers, name, members) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.name !== name + || node.members !== members + ? updateNode(createEnumDeclaration(decorators, modifiers, name, members), node) + : node; + } + ts.updateEnumDeclaration = updateEnumDeclaration; + function createModuleDeclaration(decorators, modifiers, name, body, flags) { + if (flags === void 0) { flags = 0 /* None */; } + var node = createSynthesizedNode(244 /* ModuleDeclaration */); + node.flags |= flags & (16 /* Namespace */ | 4 /* NestedNamespace */ | 512 /* GlobalAugmentation */); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.name = name; + node.body = body; + return node; + } + ts.createModuleDeclaration = createModuleDeclaration; + function updateModuleDeclaration(node, decorators, modifiers, name, body) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.name !== name + || node.body !== body + ? updateNode(createModuleDeclaration(decorators, modifiers, name, body, node.flags), node) + : node; + } + ts.updateModuleDeclaration = updateModuleDeclaration; + function createModuleBlock(statements) { + var node = createSynthesizedNode(245 /* ModuleBlock */); + node.statements = createNodeArray(statements); + return node; + } + ts.createModuleBlock = createModuleBlock; + function updateModuleBlock(node, statements) { + return node.statements !== statements + ? updateNode(createModuleBlock(statements), node) + : node; + } + ts.updateModuleBlock = updateModuleBlock; + function createCaseBlock(clauses) { + var node = createSynthesizedNode(246 /* CaseBlock */); + node.clauses = createNodeArray(clauses); + return node; + } + ts.createCaseBlock = createCaseBlock; + function updateCaseBlock(node, clauses) { + return node.clauses !== clauses + ? updateNode(createCaseBlock(clauses), node) + : node; + } + ts.updateCaseBlock = updateCaseBlock; + function createNamespaceExportDeclaration(name) { + var node = createSynthesizedNode(247 /* NamespaceExportDeclaration */); + node.name = asName(name); + return node; + } + ts.createNamespaceExportDeclaration = createNamespaceExportDeclaration; + function updateNamespaceExportDeclaration(node, name) { + return node.name !== name + ? updateNode(createNamespaceExportDeclaration(name), node) + : node; + } + ts.updateNamespaceExportDeclaration = updateNamespaceExportDeclaration; + function createImportEqualsDeclaration(decorators, modifiers, name, moduleReference) { + var node = createSynthesizedNode(248 /* ImportEqualsDeclaration */); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.name = asName(name); + node.moduleReference = moduleReference; + return node; + } + ts.createImportEqualsDeclaration = createImportEqualsDeclaration; + function updateImportEqualsDeclaration(node, decorators, modifiers, name, moduleReference) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.name !== name + || node.moduleReference !== moduleReference + ? updateNode(createImportEqualsDeclaration(decorators, modifiers, name, moduleReference), node) + : node; + } + ts.updateImportEqualsDeclaration = updateImportEqualsDeclaration; + function createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier) { + var node = createSynthesizedNode(249 /* ImportDeclaration */); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.importClause = importClause; + node.moduleSpecifier = moduleSpecifier; + return node; + } + ts.createImportDeclaration = createImportDeclaration; + function updateImportDeclaration(node, decorators, modifiers, importClause, moduleSpecifier) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.importClause !== importClause + || node.moduleSpecifier !== moduleSpecifier + ? updateNode(createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier), node) + : node; + } + ts.updateImportDeclaration = updateImportDeclaration; + function createImportClause(name, namedBindings) { + var node = createSynthesizedNode(250 /* ImportClause */); + node.name = name; + node.namedBindings = namedBindings; + return node; + } + ts.createImportClause = createImportClause; + function updateImportClause(node, name, namedBindings) { + return node.name !== name + || node.namedBindings !== namedBindings + ? updateNode(createImportClause(name, namedBindings), node) + : node; + } + ts.updateImportClause = updateImportClause; + function createNamespaceImport(name) { + var node = createSynthesizedNode(251 /* NamespaceImport */); + node.name = name; + return node; + } + ts.createNamespaceImport = createNamespaceImport; + function updateNamespaceImport(node, name) { + return node.name !== name + ? updateNode(createNamespaceImport(name), node) + : node; + } + ts.updateNamespaceImport = updateNamespaceImport; + function createNamedImports(elements) { + var node = createSynthesizedNode(252 /* NamedImports */); + node.elements = createNodeArray(elements); + return node; + } + ts.createNamedImports = createNamedImports; + function updateNamedImports(node, elements) { + return node.elements !== elements + ? updateNode(createNamedImports(elements), node) + : node; + } + ts.updateNamedImports = updateNamedImports; + function createImportSpecifier(propertyName, name) { + var node = createSynthesizedNode(253 /* ImportSpecifier */); + node.propertyName = propertyName; + node.name = name; + return node; + } + ts.createImportSpecifier = createImportSpecifier; + function updateImportSpecifier(node, propertyName, name) { + return node.propertyName !== propertyName + || node.name !== name + ? updateNode(createImportSpecifier(propertyName, name), node) + : node; + } + ts.updateImportSpecifier = updateImportSpecifier; + function createExportAssignment(decorators, modifiers, isExportEquals, expression) { + var node = createSynthesizedNode(254 /* ExportAssignment */); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.isExportEquals = isExportEquals; + node.expression = isExportEquals ? ts.parenthesizeBinaryOperand(59 /* EqualsToken */, expression, /*isLeftSideOfBinary*/ false, /*leftOperand*/ undefined) : ts.parenthesizeDefaultExpression(expression); + return node; + } + ts.createExportAssignment = createExportAssignment; + function updateExportAssignment(node, decorators, modifiers, expression) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.expression !== expression + ? updateNode(createExportAssignment(decorators, modifiers, node.isExportEquals, expression), node) + : node; + } + ts.updateExportAssignment = updateExportAssignment; + function createExportDeclaration(decorators, modifiers, exportClause, moduleSpecifier) { + var node = createSynthesizedNode(255 /* ExportDeclaration */); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.exportClause = exportClause; + node.moduleSpecifier = moduleSpecifier; + return node; + } + ts.createExportDeclaration = createExportDeclaration; + function updateExportDeclaration(node, decorators, modifiers, exportClause, moduleSpecifier) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.exportClause !== exportClause + || node.moduleSpecifier !== moduleSpecifier + ? updateNode(createExportDeclaration(decorators, modifiers, exportClause, moduleSpecifier), node) + : node; + } + ts.updateExportDeclaration = updateExportDeclaration; + function createNamedExports(elements) { + var node = createSynthesizedNode(256 /* NamedExports */); + node.elements = createNodeArray(elements); + return node; + } + ts.createNamedExports = createNamedExports; + function updateNamedExports(node, elements) { + return node.elements !== elements + ? updateNode(createNamedExports(elements), node) + : node; + } + ts.updateNamedExports = updateNamedExports; + function createExportSpecifier(propertyName, name) { + var node = createSynthesizedNode(257 /* ExportSpecifier */); + node.propertyName = asName(propertyName); + node.name = asName(name); + return node; + } + ts.createExportSpecifier = createExportSpecifier; + function updateExportSpecifier(node, propertyName, name) { + return node.propertyName !== propertyName + || node.name !== name + ? updateNode(createExportSpecifier(propertyName, name), node) + : node; + } + ts.updateExportSpecifier = updateExportSpecifier; + // Module references + function createExternalModuleReference(expression) { + var node = createSynthesizedNode(259 /* ExternalModuleReference */); + node.expression = expression; + return node; + } + ts.createExternalModuleReference = createExternalModuleReference; + function updateExternalModuleReference(node, expression) { + return node.expression !== expression + ? updateNode(createExternalModuleReference(expression), node) + : node; + } + ts.updateExternalModuleReference = updateExternalModuleReference; + // JSDoc + /* @internal */ + function createJSDocTypeExpression(type) { + var node = createSynthesizedNode(283 /* JSDocTypeExpression */); + node.type = type; + return node; + } + ts.createJSDocTypeExpression = createJSDocTypeExpression; + /* @internal */ + function createJSDocTypeTag(typeExpression, comment) { + var tag = createJSDocTag(302 /* JSDocTypeTag */, "type"); + tag.typeExpression = typeExpression; + tag.comment = comment; + return tag; + } + ts.createJSDocTypeTag = createJSDocTypeTag; + /* @internal */ + function createJSDocReturnTag(typeExpression, comment) { + var tag = createJSDocTag(300 /* JSDocReturnTag */, "returns"); + tag.typeExpression = typeExpression; + tag.comment = comment; + return tag; + } + ts.createJSDocReturnTag = createJSDocReturnTag; + /* @internal */ + function createJSDocParamTag(name, isBracketed, typeExpression, comment) { + var tag = createJSDocTag(299 /* JSDocParameterTag */, "param"); + tag.typeExpression = typeExpression; + tag.name = name; + tag.isBracketed = isBracketed; + tag.comment = comment; + return tag; + } + ts.createJSDocParamTag = createJSDocParamTag; + /* @internal */ + function createJSDocComment(comment, tags) { + var node = createSynthesizedNode(291 /* JSDocComment */); + node.comment = comment; + node.tags = tags; + return node; + } + ts.createJSDocComment = createJSDocComment; + /* @internal */ + function createJSDocTag(kind, tagName) { + var node = createSynthesizedNode(kind); + node.tagName = createIdentifier(tagName); + return node; + } + // JSX + function createJsxElement(openingElement, children, closingElement) { + var node = createSynthesizedNode(260 /* JsxElement */); + node.openingElement = openingElement; + node.children = createNodeArray(children); + node.closingElement = closingElement; + return node; + } + ts.createJsxElement = createJsxElement; + function updateJsxElement(node, openingElement, children, closingElement) { + return node.openingElement !== openingElement + || node.children !== children + || node.closingElement !== closingElement + ? updateNode(createJsxElement(openingElement, children, closingElement), node) + : node; + } + ts.updateJsxElement = updateJsxElement; + function createJsxSelfClosingElement(tagName, typeArguments, attributes) { + var node = createSynthesizedNode(261 /* JsxSelfClosingElement */); + node.tagName = tagName; + node.typeArguments = asNodeArray(typeArguments); + node.attributes = attributes; + return node; + } + ts.createJsxSelfClosingElement = createJsxSelfClosingElement; + function updateJsxSelfClosingElement(node, tagName, typeArguments, attributes) { + return node.tagName !== tagName + || node.typeArguments !== typeArguments + || node.attributes !== attributes + ? updateNode(createJsxSelfClosingElement(tagName, typeArguments, attributes), node) + : node; + } + ts.updateJsxSelfClosingElement = updateJsxSelfClosingElement; + function createJsxOpeningElement(tagName, typeArguments, attributes) { + var node = createSynthesizedNode(262 /* JsxOpeningElement */); + node.tagName = tagName; + node.typeArguments = asNodeArray(typeArguments); + node.attributes = attributes; + return node; + } + ts.createJsxOpeningElement = createJsxOpeningElement; + function updateJsxOpeningElement(node, tagName, typeArguments, attributes) { + return node.tagName !== tagName + || node.typeArguments !== typeArguments + || node.attributes !== attributes + ? updateNode(createJsxOpeningElement(tagName, typeArguments, attributes), node) + : node; + } + ts.updateJsxOpeningElement = updateJsxOpeningElement; + function createJsxClosingElement(tagName) { + var node = createSynthesizedNode(263 /* JsxClosingElement */); + node.tagName = tagName; + return node; + } + ts.createJsxClosingElement = createJsxClosingElement; + function updateJsxClosingElement(node, tagName) { + return node.tagName !== tagName + ? updateNode(createJsxClosingElement(tagName), node) + : node; + } + ts.updateJsxClosingElement = updateJsxClosingElement; + function createJsxFragment(openingFragment, children, closingFragment) { + var node = createSynthesizedNode(264 /* JsxFragment */); + node.openingFragment = openingFragment; + node.children = createNodeArray(children); + node.closingFragment = closingFragment; + return node; + } + ts.createJsxFragment = createJsxFragment; + function updateJsxFragment(node, openingFragment, children, closingFragment) { + return node.openingFragment !== openingFragment + || node.children !== children + || node.closingFragment !== closingFragment + ? updateNode(createJsxFragment(openingFragment, children, closingFragment), node) + : node; + } + ts.updateJsxFragment = updateJsxFragment; + function createJsxAttribute(name, initializer) { + var node = createSynthesizedNode(267 /* JsxAttribute */); + node.name = name; + node.initializer = initializer; + return node; + } + ts.createJsxAttribute = createJsxAttribute; + function updateJsxAttribute(node, name, initializer) { + return node.name !== name + || node.initializer !== initializer + ? updateNode(createJsxAttribute(name, initializer), node) + : node; + } + ts.updateJsxAttribute = updateJsxAttribute; + function createJsxAttributes(properties) { + var node = createSynthesizedNode(268 /* JsxAttributes */); + node.properties = createNodeArray(properties); + return node; + } + ts.createJsxAttributes = createJsxAttributes; + function updateJsxAttributes(node, properties) { + return node.properties !== properties + ? updateNode(createJsxAttributes(properties), node) + : node; + } + ts.updateJsxAttributes = updateJsxAttributes; + function createJsxSpreadAttribute(expression) { + var node = createSynthesizedNode(269 /* JsxSpreadAttribute */); + node.expression = expression; + return node; + } + ts.createJsxSpreadAttribute = createJsxSpreadAttribute; + function updateJsxSpreadAttribute(node, expression) { + return node.expression !== expression + ? updateNode(createJsxSpreadAttribute(expression), node) + : node; + } + ts.updateJsxSpreadAttribute = updateJsxSpreadAttribute; + function createJsxExpression(dotDotDotToken, expression) { + var node = createSynthesizedNode(270 /* JsxExpression */); + node.dotDotDotToken = dotDotDotToken; + node.expression = expression; + return node; + } + ts.createJsxExpression = createJsxExpression; + function updateJsxExpression(node, expression) { + return node.expression !== expression + ? updateNode(createJsxExpression(node.dotDotDotToken, expression), node) + : node; + } + ts.updateJsxExpression = updateJsxExpression; + // Clauses + function createCaseClause(expression, statements) { + var node = createSynthesizedNode(271 /* CaseClause */); + node.expression = ts.parenthesizeExpressionForList(expression); + node.statements = createNodeArray(statements); + return node; + } + ts.createCaseClause = createCaseClause; + function updateCaseClause(node, expression, statements) { + return node.expression !== expression + || node.statements !== statements + ? updateNode(createCaseClause(expression, statements), node) + : node; + } + ts.updateCaseClause = updateCaseClause; + function createDefaultClause(statements) { + var node = createSynthesizedNode(272 /* DefaultClause */); + node.statements = createNodeArray(statements); + return node; + } + ts.createDefaultClause = createDefaultClause; + function updateDefaultClause(node, statements) { + return node.statements !== statements + ? updateNode(createDefaultClause(statements), node) + : node; + } + ts.updateDefaultClause = updateDefaultClause; + function createHeritageClause(token, types) { + var node = createSynthesizedNode(273 /* HeritageClause */); + node.token = token; + node.types = createNodeArray(types); + return node; + } + ts.createHeritageClause = createHeritageClause; + function updateHeritageClause(node, types) { + return node.types !== types + ? updateNode(createHeritageClause(node.token, types), node) + : node; + } + ts.updateHeritageClause = updateHeritageClause; + function createCatchClause(variableDeclaration, block) { + var node = createSynthesizedNode(274 /* CatchClause */); + node.variableDeclaration = ts.isString(variableDeclaration) ? createVariableDeclaration(variableDeclaration) : variableDeclaration; + node.block = block; + return node; + } + ts.createCatchClause = createCatchClause; + function updateCatchClause(node, variableDeclaration, block) { + return node.variableDeclaration !== variableDeclaration + || node.block !== block + ? updateNode(createCatchClause(variableDeclaration, block), node) + : node; + } + ts.updateCatchClause = updateCatchClause; + // Property assignments + function createPropertyAssignment(name, initializer) { + var node = createSynthesizedNode(275 /* PropertyAssignment */); + node.name = asName(name); + node.questionToken = undefined; + node.initializer = ts.parenthesizeExpressionForList(initializer); + return node; + } + ts.createPropertyAssignment = createPropertyAssignment; + function updatePropertyAssignment(node, name, initializer) { + return node.name !== name + || node.initializer !== initializer + ? updateNode(createPropertyAssignment(name, initializer), node) + : node; + } + ts.updatePropertyAssignment = updatePropertyAssignment; + function createShorthandPropertyAssignment(name, objectAssignmentInitializer) { + var node = createSynthesizedNode(276 /* ShorthandPropertyAssignment */); + node.name = asName(name); + node.objectAssignmentInitializer = objectAssignmentInitializer !== undefined ? ts.parenthesizeExpressionForList(objectAssignmentInitializer) : undefined; + return node; + } + ts.createShorthandPropertyAssignment = createShorthandPropertyAssignment; + function updateShorthandPropertyAssignment(node, name, objectAssignmentInitializer) { + return node.name !== name + || node.objectAssignmentInitializer !== objectAssignmentInitializer + ? updateNode(createShorthandPropertyAssignment(name, objectAssignmentInitializer), node) + : node; + } + ts.updateShorthandPropertyAssignment = updateShorthandPropertyAssignment; + function createSpreadAssignment(expression) { + var node = createSynthesizedNode(277 /* SpreadAssignment */); + node.expression = expression !== undefined ? ts.parenthesizeExpressionForList(expression) : undefined; // TODO: GH#18217 + return node; + } + ts.createSpreadAssignment = createSpreadAssignment; + function updateSpreadAssignment(node, expression) { + return node.expression !== expression + ? updateNode(createSpreadAssignment(expression), node) + : node; + } + ts.updateSpreadAssignment = updateSpreadAssignment; + // Enum + function createEnumMember(name, initializer) { + var node = createSynthesizedNode(278 /* EnumMember */); + node.name = asName(name); + node.initializer = initializer && ts.parenthesizeExpressionForList(initializer); + return node; + } + ts.createEnumMember = createEnumMember; + function updateEnumMember(node, name, initializer) { + return node.name !== name + || node.initializer !== initializer + ? updateNode(createEnumMember(name, initializer), node) + : node; + } + ts.updateEnumMember = updateEnumMember; + // Top-level nodes + function updateSourceFileNode(node, statements, isDeclarationFile, referencedFiles, typeReferences, hasNoDefaultLib, libReferences) { + if (node.statements !== statements || + (isDeclarationFile !== undefined && node.isDeclarationFile !== isDeclarationFile) || + (referencedFiles !== undefined && node.referencedFiles !== referencedFiles) || + (typeReferences !== undefined && node.typeReferenceDirectives !== typeReferences) || + (libReferences !== undefined && node.libReferenceDirectives !== libReferences) || + (hasNoDefaultLib !== undefined && node.hasNoDefaultLib !== hasNoDefaultLib)) { + var updated = createSynthesizedNode(279 /* SourceFile */); + updated.flags |= node.flags; + updated.statements = createNodeArray(statements); + updated.endOfFileToken = node.endOfFileToken; + updated.fileName = node.fileName; + updated.path = node.path; + updated.text = node.text; + updated.isDeclarationFile = isDeclarationFile === undefined ? node.isDeclarationFile : isDeclarationFile; + updated.referencedFiles = referencedFiles === undefined ? node.referencedFiles : referencedFiles; + updated.typeReferenceDirectives = typeReferences === undefined ? node.typeReferenceDirectives : typeReferences; + updated.hasNoDefaultLib = hasNoDefaultLib === undefined ? node.hasNoDefaultLib : hasNoDefaultLib; + updated.libReferenceDirectives = libReferences === undefined ? node.libReferenceDirectives : libReferences; + if (node.amdDependencies !== undefined) + updated.amdDependencies = node.amdDependencies; + if (node.moduleName !== undefined) + updated.moduleName = node.moduleName; + if (node.languageVariant !== undefined) + updated.languageVariant = node.languageVariant; + if (node.renamedDependencies !== undefined) + updated.renamedDependencies = node.renamedDependencies; + if (node.languageVersion !== undefined) + updated.languageVersion = node.languageVersion; + if (node.scriptKind !== undefined) + updated.scriptKind = node.scriptKind; + if (node.externalModuleIndicator !== undefined) + updated.externalModuleIndicator = node.externalModuleIndicator; + if (node.commonJsModuleIndicator !== undefined) + updated.commonJsModuleIndicator = node.commonJsModuleIndicator; + if (node.identifiers !== undefined) + updated.identifiers = node.identifiers; + if (node.nodeCount !== undefined) + updated.nodeCount = node.nodeCount; + if (node.identifierCount !== undefined) + updated.identifierCount = node.identifierCount; + if (node.symbolCount !== undefined) + updated.symbolCount = node.symbolCount; + if (node.parseDiagnostics !== undefined) + updated.parseDiagnostics = node.parseDiagnostics; + if (node.bindDiagnostics !== undefined) + updated.bindDiagnostics = node.bindDiagnostics; + if (node.bindSuggestionDiagnostics !== undefined) + updated.bindSuggestionDiagnostics = node.bindSuggestionDiagnostics; + if (node.lineMap !== undefined) + updated.lineMap = node.lineMap; + if (node.classifiableNames !== undefined) + updated.classifiableNames = node.classifiableNames; + if (node.resolvedModules !== undefined) + updated.resolvedModules = node.resolvedModules; + if (node.resolvedTypeReferenceDirectiveNames !== undefined) + updated.resolvedTypeReferenceDirectiveNames = node.resolvedTypeReferenceDirectiveNames; + if (node.imports !== undefined) + updated.imports = node.imports; + if (node.moduleAugmentations !== undefined) + updated.moduleAugmentations = node.moduleAugmentations; + if (node.pragmas !== undefined) + updated.pragmas = node.pragmas; + if (node.localJsxFactory !== undefined) + updated.localJsxFactory = node.localJsxFactory; + if (node.localJsxNamespace !== undefined) + updated.localJsxNamespace = node.localJsxNamespace; + return updateNode(updated, node); + } + return node; + } + ts.updateSourceFileNode = updateSourceFileNode; + /** + * Creates a shallow, memberwise clone of a node for mutation. + */ + function getMutableClone(node) { + var clone = getSynthesizedClone(node); + clone.pos = node.pos; + clone.end = node.end; + clone.parent = node.parent; + return clone; + } + ts.getMutableClone = getMutableClone; + // Transformation nodes + /** + * Creates a synthetic statement to act as a placeholder for a not-emitted statement in + * order to preserve comments. + * + * @param original The original statement. + */ + function createNotEmittedStatement(original) { + var node = createSynthesizedNode(307 /* NotEmittedStatement */); + node.original = original; + setTextRange(node, original); + return node; + } + ts.createNotEmittedStatement = createNotEmittedStatement; + /** + * Creates a synthetic element to act as a placeholder for the end of an emitted declaration in + * order to properly emit exports. + */ + /* @internal */ + function createEndOfDeclarationMarker(original) { + var node = createSynthesizedNode(311 /* EndOfDeclarationMarker */); + node.emitNode = {}; + node.original = original; + return node; + } + ts.createEndOfDeclarationMarker = createEndOfDeclarationMarker; + /** + * Creates a synthetic element to act as a placeholder for the beginning of a merged declaration in + * order to properly emit exports. + */ + /* @internal */ + function createMergeDeclarationMarker(original) { + var node = createSynthesizedNode(310 /* MergeDeclarationMarker */); + node.emitNode = {}; + node.original = original; + return node; + } + ts.createMergeDeclarationMarker = createMergeDeclarationMarker; + /** + * Creates a synthetic expression to act as a placeholder for a not-emitted expression in + * order to preserve comments or sourcemap positions. + * + * @param expression The inner expression to emit. + * @param original The original outer expression. + * @param location The location for the expression. Defaults to the positions from "original" if provided. + */ + function createPartiallyEmittedExpression(expression, original) { + var node = createSynthesizedNode(308 /* PartiallyEmittedExpression */); + node.expression = expression; + node.original = original; + setTextRange(node, original); + return node; + } + ts.createPartiallyEmittedExpression = createPartiallyEmittedExpression; + function updatePartiallyEmittedExpression(node, expression) { + if (node.expression !== expression) { + return updateNode(createPartiallyEmittedExpression(expression, node.original), node); + } + return node; + } + ts.updatePartiallyEmittedExpression = updatePartiallyEmittedExpression; + function flattenCommaElements(node) { + if (ts.nodeIsSynthesized(node) && !ts.isParseTreeNode(node) && !node.original && !node.emitNode && !node.id) { + if (node.kind === 309 /* CommaListExpression */) { + return node.elements; + } + if (ts.isBinaryExpression(node) && node.operatorToken.kind === 27 /* CommaToken */) { + return [node.left, node.right]; + } + } + return node; + } + function createCommaList(elements) { + var node = createSynthesizedNode(309 /* CommaListExpression */); + node.elements = createNodeArray(ts.sameFlatMap(elements, flattenCommaElements)); + return node; + } + ts.createCommaList = createCommaList; + function updateCommaList(node, elements) { + return node.elements !== elements + ? updateNode(createCommaList(elements), node) + : node; + } + ts.updateCommaList = updateCommaList; + function createBundle(sourceFiles, prepends) { + if (prepends === void 0) { prepends = ts.emptyArray; } + var node = ts.createNode(280 /* Bundle */); + node.prepends = prepends; + node.sourceFiles = sourceFiles; + return node; + } + ts.createBundle = createBundle; + function createUnparsedSourceFile(text, mapPath, map) { + var node = ts.createNode(281 /* UnparsedSource */); + node.text = text; + node.sourceMapPath = mapPath; + node.sourceMapText = map; + return node; + } + ts.createUnparsedSourceFile = createUnparsedSourceFile; + function createInputFiles(javascript, declaration, javascriptMapPath, javascriptMapText, declarationMapPath, declarationMapText) { + var node = ts.createNode(282 /* InputFiles */); + node.javascriptText = javascript; + node.javascriptMapPath = javascriptMapPath; + node.javascriptMapText = javascriptMapText; + node.declarationText = declaration; + node.declarationMapPath = declarationMapPath; + node.declarationMapText = declarationMapText; + return node; + } + ts.createInputFiles = createInputFiles; + function updateBundle(node, sourceFiles, prepends) { + if (prepends === void 0) { prepends = ts.emptyArray; } + if (node.sourceFiles !== sourceFiles || node.prepends !== prepends) { + return createBundle(sourceFiles, prepends); + } + return node; + } + ts.updateBundle = updateBundle; + function createImmediatelyInvokedFunctionExpression(statements, param, paramValue) { + return createCall(createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, + /*parameters*/ param ? [param] : [], + /*type*/ undefined, createBlock(statements, /*multiLine*/ true)), + /*typeArguments*/ undefined, + /*argumentsArray*/ paramValue ? [paramValue] : []); + } + ts.createImmediatelyInvokedFunctionExpression = createImmediatelyInvokedFunctionExpression; + function createImmediatelyInvokedArrowFunction(statements, param, paramValue) { + return createCall(createArrowFunction( + /*modifiers*/ undefined, + /*typeParameters*/ undefined, + /*parameters*/ param ? [param] : [], + /*type*/ undefined, + /*equalsGreaterThanToken*/ undefined, createBlock(statements, /*multiLine*/ true)), + /*typeArguments*/ undefined, + /*argumentsArray*/ paramValue ? [paramValue] : []); + } + ts.createImmediatelyInvokedArrowFunction = createImmediatelyInvokedArrowFunction; + function createComma(left, right) { + return createBinary(left, 27 /* CommaToken */, right); + } + ts.createComma = createComma; + function createLessThan(left, right) { + return createBinary(left, 28 /* LessThanToken */, right); + } + ts.createLessThan = createLessThan; + function createAssignment(left, right) { + return createBinary(left, 59 /* EqualsToken */, right); + } + ts.createAssignment = createAssignment; + function createStrictEquality(left, right) { + return createBinary(left, 35 /* EqualsEqualsEqualsToken */, right); + } + ts.createStrictEquality = createStrictEquality; + function createStrictInequality(left, right) { + return createBinary(left, 36 /* ExclamationEqualsEqualsToken */, right); + } + ts.createStrictInequality = createStrictInequality; + function createAdd(left, right) { + return createBinary(left, 38 /* PlusToken */, right); + } + ts.createAdd = createAdd; + function createSubtract(left, right) { + return createBinary(left, 39 /* MinusToken */, right); + } + ts.createSubtract = createSubtract; + function createPostfixIncrement(operand) { + return createPostfix(operand, 44 /* PlusPlusToken */); + } + ts.createPostfixIncrement = createPostfixIncrement; + function createLogicalAnd(left, right) { + return createBinary(left, 54 /* AmpersandAmpersandToken */, right); + } + ts.createLogicalAnd = createLogicalAnd; + function createLogicalOr(left, right) { + return createBinary(left, 55 /* BarBarToken */, right); + } + ts.createLogicalOr = createLogicalOr; + function createLogicalNot(operand) { + return createPrefix(52 /* ExclamationToken */, operand); + } + ts.createLogicalNot = createLogicalNot; + function createVoidZero() { + return createVoid(createLiteral(0)); + } + ts.createVoidZero = createVoidZero; + function createExportDefault(expression) { + return createExportAssignment(/*decorators*/ undefined, /*modifiers*/ undefined, /*isExportEquals*/ false, expression); + } + ts.createExportDefault = createExportDefault; + function createExternalModuleExport(exportName) { + return createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, createNamedExports([createExportSpecifier(/*propertyName*/ undefined, exportName)])); + } + ts.createExternalModuleExport = createExternalModuleExport; + // Utilities + function asName(name) { + return ts.isString(name) ? createIdentifier(name) : name; + } + function asExpression(value) { + return ts.isString(value) || typeof value === "number" ? createLiteral(value) : value; + } + function asNodeArray(array) { + return array ? createNodeArray(array) : undefined; + } + function asToken(value) { + return typeof value === "number" ? createToken(value) : value; + } + /** + * Clears any EmitNode entries from parse-tree nodes. + * @param sourceFile A source file. + */ + function disposeEmitNodes(sourceFile) { + // During transformation we may need to annotate a parse tree node with transient + // transformation properties. As parse tree nodes live longer than transformation + // nodes, we need to make sure we reclaim any memory allocated for custom ranges + // from these nodes to ensure we do not hold onto entire subtrees just for position + // information. We also need to reset these nodes to a pre-transformation state + // for incremental parsing scenarios so that we do not impact later emit. + sourceFile = ts.getSourceFileOfNode(ts.getParseTreeNode(sourceFile)); + var emitNode = sourceFile && sourceFile.emitNode; + var annotatedNodes = emitNode && emitNode.annotatedNodes; + if (annotatedNodes) { + for (var _i = 0, annotatedNodes_1 = annotatedNodes; _i < annotatedNodes_1.length; _i++) { + var node = annotatedNodes_1[_i]; + node.emitNode = undefined; + } + } + } + ts.disposeEmitNodes = disposeEmitNodes; + /** + * Associates a node with the current transformation, initializing + * various transient transformation properties. + */ + /* @internal */ + function getOrCreateEmitNode(node) { + if (!node.emitNode) { + if (ts.isParseTreeNode(node)) { + // To avoid holding onto transformation artifacts, we keep track of any + // parse tree node we are annotating. This allows us to clean them up after + // all transformations have completed. + if (node.kind === 279 /* SourceFile */) { + return node.emitNode = { annotatedNodes: [node] }; + } + var sourceFile = ts.getSourceFileOfNode(node); + getOrCreateEmitNode(sourceFile).annotatedNodes.push(node); + } + node.emitNode = {}; + } + return node.emitNode; + } + ts.getOrCreateEmitNode = getOrCreateEmitNode; + function setTextRange(range, location) { + if (location) { + range.pos = location.pos; + range.end = location.end; + } + return range; + } + ts.setTextRange = setTextRange; + /** + * Sets flags that control emit behavior of a node. + */ + function setEmitFlags(node, emitFlags) { + getOrCreateEmitNode(node).flags = emitFlags; + return node; + } + ts.setEmitFlags = setEmitFlags; + /** + * Sets flags that control emit behavior of a node. + */ + /* @internal */ + function addEmitFlags(node, emitFlags) { + var emitNode = getOrCreateEmitNode(node); + emitNode.flags = emitNode.flags | emitFlags; + return node; + } + ts.addEmitFlags = addEmitFlags; + /** + * Gets a custom text range to use when emitting source maps. + */ + function getSourceMapRange(node) { + var emitNode = node.emitNode; + return (emitNode && emitNode.sourceMapRange) || node; + } + ts.getSourceMapRange = getSourceMapRange; + /** + * Sets a custom text range to use when emitting source maps. + */ + function setSourceMapRange(node, range) { + getOrCreateEmitNode(node).sourceMapRange = range; + return node; + } + ts.setSourceMapRange = setSourceMapRange; + // tslint:disable-next-line variable-name + var SourceMapSource; + /** + * Create an external source map source file reference + */ + function createSourceMapSource(fileName, text, skipTrivia) { + return new (SourceMapSource || (SourceMapSource = ts.objectAllocator.getSourceMapSourceConstructor()))(fileName, text, skipTrivia); + } + ts.createSourceMapSource = createSourceMapSource; + /** + * Gets the TextRange to use for source maps for a token of a node. + */ + function getTokenSourceMapRange(node, token) { + var emitNode = node.emitNode; + var tokenSourceMapRanges = emitNode && emitNode.tokenSourceMapRanges; + return tokenSourceMapRanges && tokenSourceMapRanges[token]; + } + ts.getTokenSourceMapRange = getTokenSourceMapRange; + /** + * Sets the TextRange to use for source maps for a token of a node. + */ + function setTokenSourceMapRange(node, token, range) { + var emitNode = getOrCreateEmitNode(node); + var tokenSourceMapRanges = emitNode.tokenSourceMapRanges || (emitNode.tokenSourceMapRanges = []); + tokenSourceMapRanges[token] = range; + return node; + } + ts.setTokenSourceMapRange = setTokenSourceMapRange; + /** + * Gets a custom text range to use when emitting comments. + */ + /*@internal*/ + function getStartsOnNewLine(node) { + var emitNode = node.emitNode; + return emitNode && emitNode.startsOnNewLine; + } + ts.getStartsOnNewLine = getStartsOnNewLine; + /** + * Sets a custom text range to use when emitting comments. + */ + /*@internal*/ + function setStartsOnNewLine(node, newLine) { + getOrCreateEmitNode(node).startsOnNewLine = newLine; + return node; + } + ts.setStartsOnNewLine = setStartsOnNewLine; + /** + * Gets a custom text range to use when emitting comments. + */ + function getCommentRange(node) { + var emitNode = node.emitNode; + return (emitNode && emitNode.commentRange) || node; + } + ts.getCommentRange = getCommentRange; + /** + * Sets a custom text range to use when emitting comments. + */ + function setCommentRange(node, range) { + getOrCreateEmitNode(node).commentRange = range; + return node; + } + ts.setCommentRange = setCommentRange; + function getSyntheticLeadingComments(node) { + var emitNode = node.emitNode; + return emitNode && emitNode.leadingComments; + } + ts.getSyntheticLeadingComments = getSyntheticLeadingComments; + function setSyntheticLeadingComments(node, comments) { + getOrCreateEmitNode(node).leadingComments = comments; + return node; + } + ts.setSyntheticLeadingComments = setSyntheticLeadingComments; + function addSyntheticLeadingComment(node, kind, text, hasTrailingNewLine) { + return setSyntheticLeadingComments(node, ts.append(getSyntheticLeadingComments(node), { kind: kind, pos: -1, end: -1, hasTrailingNewLine: hasTrailingNewLine, text: text })); + } + ts.addSyntheticLeadingComment = addSyntheticLeadingComment; + function getSyntheticTrailingComments(node) { + var emitNode = node.emitNode; + return emitNode && emitNode.trailingComments; + } + ts.getSyntheticTrailingComments = getSyntheticTrailingComments; + function setSyntheticTrailingComments(node, comments) { + getOrCreateEmitNode(node).trailingComments = comments; + return node; + } + ts.setSyntheticTrailingComments = setSyntheticTrailingComments; + function addSyntheticTrailingComment(node, kind, text, hasTrailingNewLine) { + return setSyntheticTrailingComments(node, ts.append(getSyntheticTrailingComments(node), { kind: kind, pos: -1, end: -1, hasTrailingNewLine: hasTrailingNewLine, text: text })); + } + ts.addSyntheticTrailingComment = addSyntheticTrailingComment; + function moveSyntheticComments(node, original) { + setSyntheticLeadingComments(node, getSyntheticLeadingComments(original)); + setSyntheticTrailingComments(node, getSyntheticTrailingComments(original)); + var emit = getOrCreateEmitNode(original); + emit.leadingComments = undefined; + emit.trailingComments = undefined; + return node; + } + ts.moveSyntheticComments = moveSyntheticComments; + /** + * Gets the constant value to emit for an expression. + */ + function getConstantValue(node) { + var emitNode = node.emitNode; + return emitNode && emitNode.constantValue; + } + ts.getConstantValue = getConstantValue; + /** + * Sets the constant value to emit for an expression. + */ + function setConstantValue(node, value) { + var emitNode = getOrCreateEmitNode(node); + emitNode.constantValue = value; + return node; + } + ts.setConstantValue = setConstantValue; + /** + * Adds an EmitHelper to a node. + */ + function addEmitHelper(node, helper) { + var emitNode = getOrCreateEmitNode(node); + emitNode.helpers = ts.append(emitNode.helpers, helper); + return node; + } + ts.addEmitHelper = addEmitHelper; + /** + * Add EmitHelpers to a node. + */ + function addEmitHelpers(node, helpers) { + if (ts.some(helpers)) { + var emitNode = getOrCreateEmitNode(node); + for (var _i = 0, helpers_1 = helpers; _i < helpers_1.length; _i++) { + var helper = helpers_1[_i]; + emitNode.helpers = ts.appendIfUnique(emitNode.helpers, helper); + } + } + return node; + } + ts.addEmitHelpers = addEmitHelpers; + /** + * Removes an EmitHelper from a node. + */ + function removeEmitHelper(node, helper) { + var emitNode = node.emitNode; + if (emitNode) { + var helpers = emitNode.helpers; + if (helpers) { + return ts.orderedRemoveItem(helpers, helper); + } + } + return false; + } + ts.removeEmitHelper = removeEmitHelper; + /** + * Gets the EmitHelpers of a node. + */ + function getEmitHelpers(node) { + var emitNode = node.emitNode; + return emitNode && emitNode.helpers; + } + ts.getEmitHelpers = getEmitHelpers; + /** + * Moves matching emit helpers from a source node to a target node. + */ + function moveEmitHelpers(source, target, predicate) { + var sourceEmitNode = source.emitNode; + var sourceEmitHelpers = sourceEmitNode && sourceEmitNode.helpers; + if (!ts.some(sourceEmitHelpers)) + return; + var targetEmitNode = getOrCreateEmitNode(target); + var helpersRemoved = 0; + for (var i = 0; i < sourceEmitHelpers.length; i++) { + var helper = sourceEmitHelpers[i]; + if (predicate(helper)) { + helpersRemoved++; + targetEmitNode.helpers = ts.appendIfUnique(targetEmitNode.helpers, helper); + } + else if (helpersRemoved > 0) { + sourceEmitHelpers[i - helpersRemoved] = helper; + } + } + if (helpersRemoved > 0) { + sourceEmitHelpers.length -= helpersRemoved; + } + } + ts.moveEmitHelpers = moveEmitHelpers; + /* @internal */ + function compareEmitHelpers(x, y) { + if (x === y) + return 0 /* EqualTo */; + if (x.priority === y.priority) + return 0 /* EqualTo */; + if (x.priority === undefined) + return 1 /* GreaterThan */; + if (y.priority === undefined) + return -1 /* LessThan */; + return ts.compareValues(x.priority, y.priority); + } + ts.compareEmitHelpers = compareEmitHelpers; + function setOriginalNode(node, original) { + node.original = original; + if (original) { + var emitNode = original.emitNode; + if (emitNode) + node.emitNode = mergeEmitNode(emitNode, node.emitNode); + } + return node; + } + ts.setOriginalNode = setOriginalNode; + function mergeEmitNode(sourceEmitNode, destEmitNode) { + var flags = sourceEmitNode.flags, leadingComments = sourceEmitNode.leadingComments, trailingComments = sourceEmitNode.trailingComments, commentRange = sourceEmitNode.commentRange, sourceMapRange = sourceEmitNode.sourceMapRange, tokenSourceMapRanges = sourceEmitNode.tokenSourceMapRanges, constantValue = sourceEmitNode.constantValue, helpers = sourceEmitNode.helpers, startsOnNewLine = sourceEmitNode.startsOnNewLine; + if (!destEmitNode) + destEmitNode = {}; + // We are using `.slice()` here in case `destEmitNode.leadingComments` is pushed to later. + if (leadingComments) + destEmitNode.leadingComments = ts.addRange(leadingComments.slice(), destEmitNode.leadingComments); + if (trailingComments) + destEmitNode.trailingComments = ts.addRange(trailingComments.slice(), destEmitNode.trailingComments); + if (flags) + destEmitNode.flags = flags; + if (commentRange) + destEmitNode.commentRange = commentRange; + if (sourceMapRange) + destEmitNode.sourceMapRange = sourceMapRange; + if (tokenSourceMapRanges) + destEmitNode.tokenSourceMapRanges = mergeTokenSourceMapRanges(tokenSourceMapRanges, destEmitNode.tokenSourceMapRanges); + if (constantValue !== undefined) + destEmitNode.constantValue = constantValue; + if (helpers) + destEmitNode.helpers = ts.addRange(destEmitNode.helpers, helpers); + if (startsOnNewLine !== undefined) + destEmitNode.startsOnNewLine = startsOnNewLine; + return destEmitNode; + } + function mergeTokenSourceMapRanges(sourceRanges, destRanges) { + if (!destRanges) + destRanges = []; + for (var key in sourceRanges) { + destRanges[key] = sourceRanges[key]; + } + return destRanges; + } +})(ts || (ts = {})); +/* @internal */ +(function (ts) { + ts.nullTransformationContext = { + enableEmitNotification: ts.noop, + enableSubstitution: ts.noop, + endLexicalEnvironment: function () { return undefined; }, + getCompilerOptions: ts.notImplemented, + getEmitHost: ts.notImplemented, + getEmitResolver: ts.notImplemented, + hoistFunctionDeclaration: ts.noop, + hoistVariableDeclaration: ts.noop, + isEmitNotificationEnabled: ts.notImplemented, + isSubstitutionEnabled: ts.notImplemented, + onEmitNode: ts.noop, + onSubstituteNode: ts.notImplemented, + readEmitHelpers: ts.notImplemented, + requestEmitHelper: ts.noop, + resumeLexicalEnvironment: ts.noop, + startLexicalEnvironment: ts.noop, + suspendLexicalEnvironment: ts.noop, + addDiagnostic: ts.noop, + }; + function createTypeCheck(value, tag) { + return tag === "undefined" + ? ts.createStrictEquality(value, ts.createVoidZero()) + : ts.createStrictEquality(ts.createTypeOf(value), ts.createLiteral(tag)); + } + ts.createTypeCheck = createTypeCheck; + function createMemberAccessForPropertyName(target, memberName, location) { + if (ts.isComputedPropertyName(memberName)) { + return ts.setTextRange(ts.createElementAccess(target, memberName.expression), location); + } + else { + var expression = ts.setTextRange(ts.isIdentifier(memberName) + ? ts.createPropertyAccess(target, memberName) + : ts.createElementAccess(target, memberName), memberName); + ts.getOrCreateEmitNode(expression).flags |= 64 /* NoNestedSourceMaps */; + return expression; + } + } + ts.createMemberAccessForPropertyName = createMemberAccessForPropertyName; + function createFunctionCall(func, thisArg, argumentsList, location) { + return ts.setTextRange(ts.createCall(ts.createPropertyAccess(func, "call"), + /*typeArguments*/ undefined, [ + thisArg + ].concat(argumentsList)), location); + } + ts.createFunctionCall = createFunctionCall; + function createFunctionApply(func, thisArg, argumentsExpression, location) { + return ts.setTextRange(ts.createCall(ts.createPropertyAccess(func, "apply"), + /*typeArguments*/ undefined, [ + thisArg, + argumentsExpression + ]), location); + } + ts.createFunctionApply = createFunctionApply; + function createArraySlice(array, start) { + var argumentsList = []; + if (start !== undefined) { + argumentsList.push(typeof start === "number" ? ts.createLiteral(start) : start); + } + return ts.createCall(ts.createPropertyAccess(array, "slice"), /*typeArguments*/ undefined, argumentsList); + } + ts.createArraySlice = createArraySlice; + function createArrayConcat(array, values) { + return ts.createCall(ts.createPropertyAccess(array, "concat"), + /*typeArguments*/ undefined, values); + } + ts.createArrayConcat = createArrayConcat; + function createMathPow(left, right, location) { + return ts.setTextRange(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Math"), "pow"), + /*typeArguments*/ undefined, [left, right]), location); + } + ts.createMathPow = createMathPow; + function createReactNamespace(reactNamespace, parent) { + // To ensure the emit resolver can properly resolve the namespace, we need to + // treat this identifier as if it were a source tree node by clearing the `Synthesized` + // flag and setting a parent node. + var react = ts.createIdentifier(reactNamespace || "React"); + react.flags &= ~8 /* Synthesized */; + // Set the parent that is in parse tree + // this makes sure that parent chain is intact for checker to traverse complete scope tree + react.parent = ts.getParseTreeNode(parent); + return react; + } + function createJsxFactoryExpressionFromEntityName(jsxFactory, parent) { + if (ts.isQualifiedName(jsxFactory)) { + var left = createJsxFactoryExpressionFromEntityName(jsxFactory.left, parent); + var right = ts.createIdentifier(ts.idText(jsxFactory.right)); + right.escapedText = jsxFactory.right.escapedText; + return ts.createPropertyAccess(left, right); + } + else { + return createReactNamespace(ts.idText(jsxFactory), parent); + } + } + function createJsxFactoryExpression(jsxFactoryEntity, reactNamespace, parent) { + return jsxFactoryEntity ? + createJsxFactoryExpressionFromEntityName(jsxFactoryEntity, parent) : + ts.createPropertyAccess(createReactNamespace(reactNamespace, parent), "createElement"); + } + function createExpressionForJsxElement(jsxFactoryEntity, reactNamespace, tagName, props, children, parentElement, location) { + var argumentsList = [tagName]; + if (props) { + argumentsList.push(props); + } + if (children && children.length > 0) { + if (!props) { + argumentsList.push(ts.createNull()); + } + if (children.length > 1) { + for (var _i = 0, children_1 = children; _i < children_1.length; _i++) { + var child = children_1[_i]; + startOnNewLine(child); + argumentsList.push(child); + } + } + else { + argumentsList.push(children[0]); + } + } + return ts.setTextRange(ts.createCall(createJsxFactoryExpression(jsxFactoryEntity, reactNamespace, parentElement), + /*typeArguments*/ undefined, argumentsList), location); + } + ts.createExpressionForJsxElement = createExpressionForJsxElement; + function createExpressionForJsxFragment(jsxFactoryEntity, reactNamespace, children, parentElement, location) { + var tagName = ts.createPropertyAccess(createReactNamespace(reactNamespace, parentElement), "Fragment"); + var argumentsList = [tagName]; + argumentsList.push(ts.createNull()); + if (children && children.length > 0) { + if (children.length > 1) { + for (var _i = 0, children_2 = children; _i < children_2.length; _i++) { + var child = children_2[_i]; + startOnNewLine(child); + argumentsList.push(child); + } + } + else { + argumentsList.push(children[0]); + } + } + return ts.setTextRange(ts.createCall(createJsxFactoryExpression(jsxFactoryEntity, reactNamespace, parentElement), + /*typeArguments*/ undefined, argumentsList), location); + } + ts.createExpressionForJsxFragment = createExpressionForJsxFragment; + // Helpers + function getHelperName(name) { + return ts.setEmitFlags(ts.createIdentifier(name), 4096 /* HelperName */ | 2 /* AdviseOnEmitNode */); + } + ts.getHelperName = getHelperName; + var valuesHelper = { + name: "typescript:values", + scoped: false, + text: "\n var __values = (this && this.__values) || function (o) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator], i = 0;\n if (m) return m.call(o);\n return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n };" + }; + function createValuesHelper(context, expression, location) { + context.requestEmitHelper(valuesHelper); + return ts.setTextRange(ts.createCall(getHelperName("__values"), + /*typeArguments*/ undefined, [expression]), location); + } + ts.createValuesHelper = createValuesHelper; + var readHelper = { + name: "typescript:read", + scoped: false, + text: "\n var __read = (this && this.__read) || function (o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m) return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n }\n catch (error) { e = { error: error }; }\n finally {\n try {\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\n }\n finally { if (e) throw e.error; }\n }\n return ar;\n };" + }; + function createReadHelper(context, iteratorRecord, count, location) { + context.requestEmitHelper(readHelper); + return ts.setTextRange(ts.createCall(getHelperName("__read"), + /*typeArguments*/ undefined, count !== undefined + ? [iteratorRecord, ts.createLiteral(count)] + : [iteratorRecord]), location); + } + ts.createReadHelper = createReadHelper; + var spreadHelper = { + name: "typescript:spread", + scoped: false, + text: "\n var __spread = (this && this.__spread) || function () {\n for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i]));\n return ar;\n };" + }; + function createSpreadHelper(context, argumentList, location) { + context.requestEmitHelper(readHelper); + context.requestEmitHelper(spreadHelper); + return ts.setTextRange(ts.createCall(getHelperName("__spread"), + /*typeArguments*/ undefined, argumentList), location); + } + ts.createSpreadHelper = createSpreadHelper; + // Utilities + function createForOfBindingStatement(node, boundValue) { + if (ts.isVariableDeclarationList(node)) { + var firstDeclaration = ts.first(node.declarations); + var updatedDeclaration = ts.updateVariableDeclaration(firstDeclaration, firstDeclaration.name, + /*typeNode*/ undefined, boundValue); + return ts.setTextRange(ts.createVariableStatement( + /*modifiers*/ undefined, ts.updateVariableDeclarationList(node, [updatedDeclaration])), + /*location*/ node); + } + else { + var updatedExpression = ts.setTextRange(ts.createAssignment(node, boundValue), /*location*/ node); + return ts.setTextRange(ts.createStatement(updatedExpression), /*location*/ node); + } + } + ts.createForOfBindingStatement = createForOfBindingStatement; + function insertLeadingStatement(dest, source) { + if (ts.isBlock(dest)) { + return ts.updateBlock(dest, ts.setTextRange(ts.createNodeArray([source].concat(dest.statements)), dest.statements)); + } + else { + return ts.createBlock(ts.createNodeArray([dest, source]), /*multiLine*/ true); + } + } + ts.insertLeadingStatement = insertLeadingStatement; + function restoreEnclosingLabel(node, outermostLabeledStatement, afterRestoreLabelCallback) { + if (!outermostLabeledStatement) { + return node; + } + var updated = ts.updateLabel(outermostLabeledStatement, outermostLabeledStatement.label, outermostLabeledStatement.statement.kind === 233 /* LabeledStatement */ + ? restoreEnclosingLabel(node, outermostLabeledStatement.statement) + : node); + if (afterRestoreLabelCallback) { + afterRestoreLabelCallback(outermostLabeledStatement); + } + return updated; + } + ts.restoreEnclosingLabel = restoreEnclosingLabel; + function shouldBeCapturedInTempVariable(node, cacheIdentifiers) { + var target = ts.skipParentheses(node); + switch (target.kind) { + case 72 /* Identifier */: + return cacheIdentifiers; + case 100 /* ThisKeyword */: + case 8 /* NumericLiteral */: + case 9 /* BigIntLiteral */: + case 10 /* StringLiteral */: + return false; + case 187 /* ArrayLiteralExpression */: + var elements = target.elements; + if (elements.length === 0) { + return false; + } + return true; + case 188 /* ObjectLiteralExpression */: + return target.properties.length > 0; + default: + return true; + } + } + function createCallBinding(expression, recordTempVariable, languageVersion, cacheIdentifiers) { + if (cacheIdentifiers === void 0) { cacheIdentifiers = false; } + var callee = skipOuterExpressions(expression, 7 /* All */); + var thisArg; + var target; + if (ts.isSuperProperty(callee)) { + thisArg = ts.createThis(); + target = callee; + } + else if (callee.kind === 98 /* SuperKeyword */) { + thisArg = ts.createThis(); + target = languageVersion < 2 /* ES2015 */ + ? ts.setTextRange(ts.createIdentifier("_super"), callee) + : callee; + } + else if (ts.getEmitFlags(callee) & 4096 /* HelperName */) { + thisArg = ts.createVoidZero(); + target = parenthesizeForAccess(callee); + } + else { + switch (callee.kind) { + case 189 /* PropertyAccessExpression */: { + if (shouldBeCapturedInTempVariable(callee.expression, cacheIdentifiers)) { + // for `a.b()` target is `(_a = a).b` and thisArg is `_a` + thisArg = ts.createTempVariable(recordTempVariable); + target = ts.createPropertyAccess(ts.setTextRange(ts.createAssignment(thisArg, callee.expression), callee.expression), callee.name); + ts.setTextRange(target, callee); + } + else { + thisArg = callee.expression; + target = callee; + } + break; + } + case 190 /* ElementAccessExpression */: { + if (shouldBeCapturedInTempVariable(callee.expression, cacheIdentifiers)) { + // for `a[b]()` target is `(_a = a)[b]` and thisArg is `_a` + thisArg = ts.createTempVariable(recordTempVariable); + target = ts.createElementAccess(ts.setTextRange(ts.createAssignment(thisArg, callee.expression), callee.expression), callee.argumentExpression); + ts.setTextRange(target, callee); + } + else { + thisArg = callee.expression; + target = callee; + } + break; + } + default: { + // for `a()` target is `a` and thisArg is `void 0` + thisArg = ts.createVoidZero(); + target = parenthesizeForAccess(expression); + break; + } + } + } + return { target: target, thisArg: thisArg }; + } + ts.createCallBinding = createCallBinding; + function inlineExpressions(expressions) { + // Avoid deeply nested comma expressions as traversing them during emit can result in "Maximum call + // stack size exceeded" errors. + return expressions.length > 10 + ? ts.createCommaList(expressions) + : ts.reduceLeft(expressions, ts.createComma); + } + ts.inlineExpressions = inlineExpressions; + function createExpressionFromEntityName(node) { + if (ts.isQualifiedName(node)) { + var left = createExpressionFromEntityName(node.left); + var right = ts.getMutableClone(node.right); + return ts.setTextRange(ts.createPropertyAccess(left, right), node); + } + else { + return ts.getMutableClone(node); + } + } + ts.createExpressionFromEntityName = createExpressionFromEntityName; + function createExpressionForPropertyName(memberName) { + if (ts.isIdentifier(memberName)) { + return ts.createLiteral(memberName); + } + else if (ts.isComputedPropertyName(memberName)) { + return ts.getMutableClone(memberName.expression); + } + else { + return ts.getMutableClone(memberName); + } + } + ts.createExpressionForPropertyName = createExpressionForPropertyName; + function createExpressionForObjectLiteralElementLike(node, property, receiver) { + switch (property.kind) { + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + return createExpressionForAccessorDeclaration(node.properties, property, receiver, !!node.multiLine); + case 275 /* PropertyAssignment */: + return createExpressionForPropertyAssignment(property, receiver); + case 276 /* ShorthandPropertyAssignment */: + return createExpressionForShorthandPropertyAssignment(property, receiver); + case 156 /* MethodDeclaration */: + return createExpressionForMethodDeclaration(property, receiver); + } + } + ts.createExpressionForObjectLiteralElementLike = createExpressionForObjectLiteralElementLike; + function createExpressionForAccessorDeclaration(properties, property, receiver, multiLine) { + var _a = ts.getAllAccessorDeclarations(properties, property), firstAccessor = _a.firstAccessor, getAccessor = _a.getAccessor, setAccessor = _a.setAccessor; + if (property === firstAccessor) { + var properties_8 = []; + if (getAccessor) { + var getterFunction = ts.createFunctionExpression(getAccessor.modifiers, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, getAccessor.parameters, + /*type*/ undefined, getAccessor.body // TODO: GH#18217 + ); + ts.setTextRange(getterFunction, getAccessor); + ts.setOriginalNode(getterFunction, getAccessor); + var getter = ts.createPropertyAssignment("get", getterFunction); + properties_8.push(getter); + } + if (setAccessor) { + var setterFunction = ts.createFunctionExpression(setAccessor.modifiers, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, setAccessor.parameters, + /*type*/ undefined, setAccessor.body // TODO: GH#18217 + ); + ts.setTextRange(setterFunction, setAccessor); + ts.setOriginalNode(setterFunction, setAccessor); + var setter = ts.createPropertyAssignment("set", setterFunction); + properties_8.push(setter); + } + properties_8.push(ts.createPropertyAssignment("enumerable", ts.createTrue())); + properties_8.push(ts.createPropertyAssignment("configurable", ts.createTrue())); + var expression = ts.setTextRange(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"), + /*typeArguments*/ undefined, [ + receiver, + createExpressionForPropertyName(property.name), + ts.createObjectLiteral(properties_8, multiLine) + ]), + /*location*/ firstAccessor); + return ts.aggregateTransformFlags(expression); + } + return undefined; + } + function createExpressionForPropertyAssignment(property, receiver) { + return ts.aggregateTransformFlags(ts.setOriginalNode(ts.setTextRange(ts.createAssignment(createMemberAccessForPropertyName(receiver, property.name, /*location*/ property.name), property.initializer), property), property)); + } + function createExpressionForShorthandPropertyAssignment(property, receiver) { + return ts.aggregateTransformFlags(ts.setOriginalNode(ts.setTextRange(ts.createAssignment(createMemberAccessForPropertyName(receiver, property.name, /*location*/ property.name), ts.getSynthesizedClone(property.name)), + /*location*/ property), + /*original*/ property)); + } + function createExpressionForMethodDeclaration(method, receiver) { + return ts.aggregateTransformFlags(ts.setOriginalNode(ts.setTextRange(ts.createAssignment(createMemberAccessForPropertyName(receiver, method.name, /*location*/ method.name), ts.setOriginalNode(ts.setTextRange(ts.createFunctionExpression(method.modifiers, method.asteriskToken, + /*name*/ undefined, + /*typeParameters*/ undefined, method.parameters, + /*type*/ undefined, method.body // TODO: GH#18217 + ), + /*location*/ method), + /*original*/ method)), + /*location*/ method), + /*original*/ method)); + } + /** + * Gets the internal name of a declaration. This is primarily used for declarations that can be + * referred to by name in the body of an ES5 class function body. An internal name will *never* + * be prefixed with an module or namespace export modifier like "exports." when emitted as an + * expression. An internal name will also *never* be renamed due to a collision with a block + * scoped variable. + * + * @param node The declaration. + * @param allowComments A value indicating whether comments may be emitted for the name. + * @param allowSourceMaps A value indicating whether source maps may be emitted for the name. + */ + function getInternalName(node, allowComments, allowSourceMaps) { + return getName(node, allowComments, allowSourceMaps, 16384 /* LocalName */ | 32768 /* InternalName */); + } + ts.getInternalName = getInternalName; + /** + * Gets whether an identifier should only be referred to by its internal name. + */ + function isInternalName(node) { + return (ts.getEmitFlags(node) & 32768 /* InternalName */) !== 0; + } + ts.isInternalName = isInternalName; + /** + * Gets the local name of a declaration. This is primarily used for declarations that can be + * referred to by name in the declaration's immediate scope (classes, enums, namespaces). A + * local name will *never* be prefixed with an module or namespace export modifier like + * "exports." when emitted as an expression. + * + * @param node The declaration. + * @param allowComments A value indicating whether comments may be emitted for the name. + * @param allowSourceMaps A value indicating whether source maps may be emitted for the name. + */ + function getLocalName(node, allowComments, allowSourceMaps) { + return getName(node, allowComments, allowSourceMaps, 16384 /* LocalName */); + } + ts.getLocalName = getLocalName; + /** + * Gets whether an identifier should only be referred to by its local name. + */ + function isLocalName(node) { + return (ts.getEmitFlags(node) & 16384 /* LocalName */) !== 0; + } + ts.isLocalName = isLocalName; + /** + * Gets the export name of a declaration. This is primarily used for declarations that can be + * referred to by name in the declaration's immediate scope (classes, enums, namespaces). An + * export name will *always* be prefixed with an module or namespace export modifier like + * `"exports."` when emitted as an expression if the name points to an exported symbol. + * + * @param node The declaration. + * @param allowComments A value indicating whether comments may be emitted for the name. + * @param allowSourceMaps A value indicating whether source maps may be emitted for the name. + */ + function getExportName(node, allowComments, allowSourceMaps) { + return getName(node, allowComments, allowSourceMaps, 8192 /* ExportName */); + } + ts.getExportName = getExportName; + /** + * Gets whether an identifier should only be referred to by its export representation if the + * name points to an exported symbol. + */ + function isExportName(node) { + return (ts.getEmitFlags(node) & 8192 /* ExportName */) !== 0; + } + ts.isExportName = isExportName; + /** + * Gets the name of a declaration for use in declarations. + * + * @param node The declaration. + * @param allowComments A value indicating whether comments may be emitted for the name. + * @param allowSourceMaps A value indicating whether source maps may be emitted for the name. + */ + function getDeclarationName(node, allowComments, allowSourceMaps) { + return getName(node, allowComments, allowSourceMaps); + } + ts.getDeclarationName = getDeclarationName; + function getName(node, allowComments, allowSourceMaps, emitFlags) { + if (emitFlags === void 0) { emitFlags = 0; } + var nodeName = ts.getNameOfDeclaration(node); + if (nodeName && ts.isIdentifier(nodeName) && !ts.isGeneratedIdentifier(nodeName)) { + var name = ts.getMutableClone(nodeName); + emitFlags |= ts.getEmitFlags(nodeName); + if (!allowSourceMaps) + emitFlags |= 48 /* NoSourceMap */; + if (!allowComments) + emitFlags |= 1536 /* NoComments */; + if (emitFlags) + ts.setEmitFlags(name, emitFlags); + return name; + } + return ts.getGeneratedNameForNode(node); + } + /** + * Gets the exported name of a declaration for use in expressions. + * + * An exported name will *always* be prefixed with an module or namespace export modifier like + * "exports." if the name points to an exported symbol. + * + * @param ns The namespace identifier. + * @param node The declaration. + * @param allowComments A value indicating whether comments may be emitted for the name. + * @param allowSourceMaps A value indicating whether source maps may be emitted for the name. + */ + function getExternalModuleOrNamespaceExportName(ns, node, allowComments, allowSourceMaps) { + if (ns && ts.hasModifier(node, 1 /* Export */)) { + return getNamespaceMemberName(ns, getName(node), allowComments, allowSourceMaps); + } + return getExportName(node, allowComments, allowSourceMaps); + } + ts.getExternalModuleOrNamespaceExportName = getExternalModuleOrNamespaceExportName; + /** + * Gets a namespace-qualified name for use in expressions. + * + * @param ns The namespace identifier. + * @param name The name. + * @param allowComments A value indicating whether comments may be emitted for the name. + * @param allowSourceMaps A value indicating whether source maps may be emitted for the name. + */ + function getNamespaceMemberName(ns, name, allowComments, allowSourceMaps) { + var qualifiedName = ts.createPropertyAccess(ns, ts.nodeIsSynthesized(name) ? name : ts.getSynthesizedClone(name)); + ts.setTextRange(qualifiedName, name); + var emitFlags = 0; + if (!allowSourceMaps) + emitFlags |= 48 /* NoSourceMap */; + if (!allowComments) + emitFlags |= 1536 /* NoComments */; + if (emitFlags) + ts.setEmitFlags(qualifiedName, emitFlags); + return qualifiedName; + } + ts.getNamespaceMemberName = getNamespaceMemberName; + function convertToFunctionBody(node, multiLine) { + return ts.isBlock(node) ? node : ts.setTextRange(ts.createBlock([ts.setTextRange(ts.createReturn(node), node)], multiLine), node); + } + ts.convertToFunctionBody = convertToFunctionBody; + function convertFunctionDeclarationToExpression(node) { + if (!node.body) + return ts.Debug.fail(); + var updated = ts.createFunctionExpression(node.modifiers, node.asteriskToken, node.name, node.typeParameters, node.parameters, node.type, node.body); + ts.setOriginalNode(updated, node); + ts.setTextRange(updated, node); + if (ts.getStartsOnNewLine(node)) { + ts.setStartsOnNewLine(updated, /*newLine*/ true); + } + ts.aggregateTransformFlags(updated); + return updated; + } + ts.convertFunctionDeclarationToExpression = convertFunctionDeclarationToExpression; + function isUseStrictPrologue(node) { + return ts.isStringLiteral(node.expression) && node.expression.text === "use strict"; + } + /** + * Add any necessary prologue-directives into target statement-array. + * The function needs to be called during each transformation step. + * This function needs to be called whenever we transform the statement + * list of a source file, namespace, or function-like body. + * + * @param target: result statements array + * @param source: origin statements array + * @param ensureUseStrict: boolean determining whether the function need to add prologue-directives + * @param visitor: Optional callback used to visit any custom prologue directives. + */ + function addPrologue(target, source, ensureUseStrict, visitor) { + var offset = addStandardPrologue(target, source, ensureUseStrict); + return addCustomPrologue(target, source, offset, visitor); + } + ts.addPrologue = addPrologue; + /** + * Add just the standard (string-expression) prologue-directives into target statement-array. + * The function needs to be called during each transformation step. + * This function needs to be called whenever we transform the statement + * list of a source file, namespace, or function-like body. + */ + function addStandardPrologue(target, source, ensureUseStrict) { + ts.Debug.assert(target.length === 0, "Prologue directives should be at the first statement in the target statements array"); + var foundUseStrict = false; + var statementOffset = 0; + var numStatements = source.length; + while (statementOffset < numStatements) { + var statement = source[statementOffset]; + if (ts.isPrologueDirective(statement)) { + if (isUseStrictPrologue(statement)) { + foundUseStrict = true; + } + target.push(statement); + } + else { + break; + } + statementOffset++; + } + if (ensureUseStrict && !foundUseStrict) { + target.push(startOnNewLine(ts.createStatement(ts.createLiteral("use strict")))); + } + return statementOffset; + } + ts.addStandardPrologue = addStandardPrologue; + function addCustomPrologue(target, source, statementOffset, visitor) { + var numStatements = source.length; + while (statementOffset !== undefined && statementOffset < numStatements) { + var statement = source[statementOffset]; + if (ts.getEmitFlags(statement) & 1048576 /* CustomPrologue */) { + ts.append(target, visitor ? ts.visitNode(statement, visitor, ts.isStatement) : statement); + } + else { + break; + } + statementOffset++; + } + return statementOffset; + } + ts.addCustomPrologue = addCustomPrologue; + function findUseStrictPrologue(statements) { + for (var _i = 0, statements_3 = statements; _i < statements_3.length; _i++) { + var statement = statements_3[_i]; + if (ts.isPrologueDirective(statement)) { + if (isUseStrictPrologue(statement)) { + return statement; + } + } + else { + break; + } + } + return undefined; + } + ts.findUseStrictPrologue = findUseStrictPrologue; + function startsWithUseStrict(statements) { + var firstStatement = ts.firstOrUndefined(statements); + return firstStatement !== undefined + && ts.isPrologueDirective(firstStatement) + && isUseStrictPrologue(firstStatement); + } + ts.startsWithUseStrict = startsWithUseStrict; + /** + * Ensures "use strict" directive is added + * + * @param statements An array of statements + */ + function ensureUseStrict(statements) { + var foundUseStrict = findUseStrictPrologue(statements); + if (!foundUseStrict) { + return ts.setTextRange(ts.createNodeArray([ + startOnNewLine(ts.createStatement(ts.createLiteral("use strict"))) + ].concat(statements)), statements); + } + return statements; + } + ts.ensureUseStrict = ensureUseStrict; + /** + * Wraps the operand to a BinaryExpression in parentheses if they are needed to preserve the intended + * order of operations. + * + * @param binaryOperator The operator for the BinaryExpression. + * @param operand The operand for the BinaryExpression. + * @param isLeftSideOfBinary A value indicating whether the operand is the left side of the + * BinaryExpression. + */ + function parenthesizeBinaryOperand(binaryOperator, operand, isLeftSideOfBinary, leftOperand) { + var skipped = ts.skipPartiallyEmittedExpressions(operand); + // If the resulting expression is already parenthesized, we do not need to do any further processing. + if (skipped.kind === 195 /* ParenthesizedExpression */) { + return operand; + } + return binaryOperandNeedsParentheses(binaryOperator, operand, isLeftSideOfBinary, leftOperand) + ? ts.createParen(operand) + : operand; + } + ts.parenthesizeBinaryOperand = parenthesizeBinaryOperand; + /** + * Determines whether the operand to a BinaryExpression needs to be parenthesized. + * + * @param binaryOperator The operator for the BinaryExpression. + * @param operand The operand for the BinaryExpression. + * @param isLeftSideOfBinary A value indicating whether the operand is the left side of the + * BinaryExpression. + */ + function binaryOperandNeedsParentheses(binaryOperator, operand, isLeftSideOfBinary, leftOperand) { + // If the operand has lower precedence, then it needs to be parenthesized to preserve the + // intent of the expression. For example, if the operand is `a + b` and the operator is + // `*`, then we need to parenthesize the operand to preserve the intended order of + // operations: `(a + b) * x`. + // + // If the operand has higher precedence, then it does not need to be parenthesized. For + // example, if the operand is `a * b` and the operator is `+`, then we do not need to + // parenthesize to preserve the intended order of operations: `a * b + x`. + // + // If the operand has the same precedence, then we need to check the associativity of + // the operator based on whether this is the left or right operand of the expression. + // + // For example, if `a / d` is on the right of operator `*`, we need to parenthesize + // to preserve the intended order of operations: `x * (a / d)` + // + // If `a ** d` is on the left of operator `**`, we need to parenthesize to preserve + // the intended order of operations: `(a ** b) ** c` + var binaryOperatorPrecedence = ts.getOperatorPrecedence(204 /* BinaryExpression */, binaryOperator); + var binaryOperatorAssociativity = ts.getOperatorAssociativity(204 /* BinaryExpression */, binaryOperator); + var emittedOperand = ts.skipPartiallyEmittedExpressions(operand); + if (!isLeftSideOfBinary && operand.kind === 197 /* ArrowFunction */ && binaryOperatorPrecedence > 4) { + // We need to parenthesize arrow functions on the right side to avoid it being + // parsed as parenthesized expression: `a && (() => {})` + return true; + } + var operandPrecedence = ts.getExpressionPrecedence(emittedOperand); + switch (ts.compareValues(operandPrecedence, binaryOperatorPrecedence)) { + case -1 /* LessThan */: + // If the operand is the right side of a right-associative binary operation + // and is a yield expression, then we do not need parentheses. + if (!isLeftSideOfBinary + && binaryOperatorAssociativity === 1 /* Right */ + && operand.kind === 207 /* YieldExpression */) { + return false; + } + return true; + case 1 /* GreaterThan */: + return false; + case 0 /* EqualTo */: + if (isLeftSideOfBinary) { + // No need to parenthesize the left operand when the binary operator is + // left associative: + // (a*b)/x -> a*b/x + // (a**b)/x -> a**b/x + // + // Parentheses are needed for the left operand when the binary operator is + // right associative: + // (a/b)**x -> (a/b)**x + // (a**b)**x -> (a**b)**x + return binaryOperatorAssociativity === 1 /* Right */; + } + else { + if (ts.isBinaryExpression(emittedOperand) + && emittedOperand.operatorToken.kind === binaryOperator) { + // No need to parenthesize the right operand when the binary operator and + // operand are the same and one of the following: + // x*(a*b) => x*a*b + // x|(a|b) => x|a|b + // x&(a&b) => x&a&b + // x^(a^b) => x^a^b + if (operatorHasAssociativeProperty(binaryOperator)) { + return false; + } + // No need to parenthesize the right operand when the binary operator + // is plus (+) if both the left and right operands consist solely of either + // literals of the same kind or binary plus (+) expressions for literals of + // the same kind (recursively). + // "a"+(1+2) => "a"+(1+2) + // "a"+("b"+"c") => "a"+"b"+"c" + if (binaryOperator === 38 /* PlusToken */) { + var leftKind = leftOperand ? getLiteralKindOfBinaryPlusOperand(leftOperand) : 0 /* Unknown */; + if (ts.isLiteralKind(leftKind) && leftKind === getLiteralKindOfBinaryPlusOperand(emittedOperand)) { + return false; + } + } + } + // No need to parenthesize the right operand when the operand is right + // associative: + // x/(a**b) -> x/a**b + // x**(a**b) -> x**a**b + // + // Parentheses are needed for the right operand when the operand is left + // associative: + // x/(a*b) -> x/(a*b) + // x**(a/b) -> x**(a/b) + var operandAssociativity = ts.getExpressionAssociativity(emittedOperand); + return operandAssociativity === 0 /* Left */; + } + } + } + /** + * Determines whether a binary operator is mathematically associative. + * + * @param binaryOperator The binary operator. + */ + function operatorHasAssociativeProperty(binaryOperator) { + // The following operators are associative in JavaScript: + // (a*b)*c -> a*(b*c) -> a*b*c + // (a|b)|c -> a|(b|c) -> a|b|c + // (a&b)&c -> a&(b&c) -> a&b&c + // (a^b)^c -> a^(b^c) -> a^b^c + // + // While addition is associative in mathematics, JavaScript's `+` is not + // guaranteed to be associative as it is overloaded with string concatenation. + return binaryOperator === 40 /* AsteriskToken */ + || binaryOperator === 50 /* BarToken */ + || binaryOperator === 49 /* AmpersandToken */ + || binaryOperator === 51 /* CaretToken */; + } + /** + * This function determines whether an expression consists of a homogeneous set of + * literal expressions or binary plus expressions that all share the same literal kind. + * It is used to determine whether the right-hand operand of a binary plus expression can be + * emitted without parentheses. + */ + function getLiteralKindOfBinaryPlusOperand(node) { + node = ts.skipPartiallyEmittedExpressions(node); + if (ts.isLiteralKind(node.kind)) { + return node.kind; + } + if (node.kind === 204 /* BinaryExpression */ && node.operatorToken.kind === 38 /* PlusToken */) { + if (node.cachedLiteralKind !== undefined) { + return node.cachedLiteralKind; + } + var leftKind = getLiteralKindOfBinaryPlusOperand(node.left); + var literalKind = ts.isLiteralKind(leftKind) + && leftKind === getLiteralKindOfBinaryPlusOperand(node.right) + ? leftKind + : 0 /* Unknown */; + node.cachedLiteralKind = literalKind; + return literalKind; + } + return 0 /* Unknown */; + } + function parenthesizeForConditionalHead(condition) { + var conditionalPrecedence = ts.getOperatorPrecedence(205 /* ConditionalExpression */, 56 /* QuestionToken */); + var emittedCondition = ts.skipPartiallyEmittedExpressions(condition); + var conditionPrecedence = ts.getExpressionPrecedence(emittedCondition); + if (ts.compareValues(conditionPrecedence, conditionalPrecedence) === -1 /* LessThan */) { + return ts.createParen(condition); + } + return condition; + } + ts.parenthesizeForConditionalHead = parenthesizeForConditionalHead; + function parenthesizeSubexpressionOfConditionalExpression(e) { + // per ES grammar both 'whenTrue' and 'whenFalse' parts of conditional expression are assignment expressions + // so in case when comma expression is introduced as a part of previous transformations + // if should be wrapped in parens since comma operator has the lowest precedence + var emittedExpression = ts.skipPartiallyEmittedExpressions(e); + return isCommaSequence(emittedExpression) + ? ts.createParen(e) + : e; + } + ts.parenthesizeSubexpressionOfConditionalExpression = parenthesizeSubexpressionOfConditionalExpression; + /** + * [Per the spec](https://tc39.github.io/ecma262/#prod-ExportDeclaration), `export default` accepts _AssigmentExpression_ but + * has a lookahead restriction for `function`, `async function`, and `class`. + * + * Basically, that means we need to parenthesize in the following cases: + * + * - BinaryExpression of CommaToken + * - CommaList (synthetic list of multiple comma expressions) + * - FunctionExpression + * - ClassExpression + */ + function parenthesizeDefaultExpression(e) { + var check = ts.skipPartiallyEmittedExpressions(e); + var needsParens = isCommaSequence(check); + if (!needsParens) { + switch (getLeftmostExpression(check, /*stopAtCallExpression*/ false).kind) { + case 209 /* ClassExpression */: + case 196 /* FunctionExpression */: + needsParens = true; + } + } + return needsParens ? ts.createParen(e) : e; + } + ts.parenthesizeDefaultExpression = parenthesizeDefaultExpression; + /** + * Wraps an expression in parentheses if it is needed in order to use the expression + * as the expression of a NewExpression node. + * + * @param expression The Expression node. + */ + function parenthesizeForNew(expression) { + var leftmostExpr = getLeftmostExpression(expression, /*stopAtCallExpressions*/ true); + switch (leftmostExpr.kind) { + case 191 /* CallExpression */: + return ts.createParen(expression); + case 192 /* NewExpression */: + return !leftmostExpr.arguments + ? ts.createParen(expression) + : expression; + } + return parenthesizeForAccess(expression); + } + ts.parenthesizeForNew = parenthesizeForNew; + /** + * Wraps an expression in parentheses if it is needed in order to use the expression for + * property or element access. + * + * @param expr The expression node. + */ + function parenthesizeForAccess(expression) { + // isLeftHandSideExpression is almost the correct criterion for when it is not necessary + // to parenthesize the expression before a dot. The known exception is: + // + // NewExpression: + // new C.x -> not the same as (new C).x + // + var emittedExpression = ts.skipPartiallyEmittedExpressions(expression); + if (ts.isLeftHandSideExpression(emittedExpression) + && (emittedExpression.kind !== 192 /* NewExpression */ || emittedExpression.arguments)) { + return expression; + } + return ts.setTextRange(ts.createParen(expression), expression); + } + ts.parenthesizeForAccess = parenthesizeForAccess; + function parenthesizePostfixOperand(operand) { + return ts.isLeftHandSideExpression(operand) + ? operand + : ts.setTextRange(ts.createParen(operand), operand); + } + ts.parenthesizePostfixOperand = parenthesizePostfixOperand; + function parenthesizePrefixOperand(operand) { + return ts.isUnaryExpression(operand) + ? operand + : ts.setTextRange(ts.createParen(operand), operand); + } + ts.parenthesizePrefixOperand = parenthesizePrefixOperand; + function parenthesizeListElements(elements) { + var result; + for (var i = 0; i < elements.length; i++) { + var element = parenthesizeExpressionForList(elements[i]); + if (result !== undefined || element !== elements[i]) { + if (result === undefined) { + result = elements.slice(0, i); + } + result.push(element); + } + } + if (result !== undefined) { + return ts.setTextRange(ts.createNodeArray(result, elements.hasTrailingComma), elements); + } + return elements; + } + ts.parenthesizeListElements = parenthesizeListElements; + function parenthesizeExpressionForList(expression) { + var emittedExpression = ts.skipPartiallyEmittedExpressions(expression); + var expressionPrecedence = ts.getExpressionPrecedence(emittedExpression); + var commaPrecedence = ts.getOperatorPrecedence(204 /* BinaryExpression */, 27 /* CommaToken */); + return expressionPrecedence > commaPrecedence + ? expression + : ts.setTextRange(ts.createParen(expression), expression); + } + ts.parenthesizeExpressionForList = parenthesizeExpressionForList; + function parenthesizeExpressionForExpressionStatement(expression) { + var emittedExpression = ts.skipPartiallyEmittedExpressions(expression); + if (ts.isCallExpression(emittedExpression)) { + var callee = emittedExpression.expression; + var kind = ts.skipPartiallyEmittedExpressions(callee).kind; + if (kind === 196 /* FunctionExpression */ || kind === 197 /* ArrowFunction */) { + var mutableCall = ts.getMutableClone(emittedExpression); + mutableCall.expression = ts.setTextRange(ts.createParen(callee), callee); + return recreateOuterExpressions(expression, mutableCall, 4 /* PartiallyEmittedExpressions */); + } + } + var leftmostExpressionKind = getLeftmostExpression(emittedExpression, /*stopAtCallExpressions*/ false).kind; + if (leftmostExpressionKind === 188 /* ObjectLiteralExpression */ || leftmostExpressionKind === 196 /* FunctionExpression */) { + return ts.setTextRange(ts.createParen(expression), expression); + } + return expression; + } + ts.parenthesizeExpressionForExpressionStatement = parenthesizeExpressionForExpressionStatement; + function parenthesizeConditionalTypeMember(member) { + return member.kind === 175 /* ConditionalType */ ? ts.createParenthesizedType(member) : member; + } + ts.parenthesizeConditionalTypeMember = parenthesizeConditionalTypeMember; + function parenthesizeElementTypeMember(member) { + switch (member.kind) { + case 173 /* UnionType */: + case 174 /* IntersectionType */: + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + return ts.createParenthesizedType(member); + } + return parenthesizeConditionalTypeMember(member); + } + ts.parenthesizeElementTypeMember = parenthesizeElementTypeMember; + function parenthesizeArrayTypeMember(member) { + switch (member.kind) { + case 167 /* TypeQuery */: + case 179 /* TypeOperator */: + case 176 /* InferType */: + return ts.createParenthesizedType(member); + } + return parenthesizeElementTypeMember(member); + } + ts.parenthesizeArrayTypeMember = parenthesizeArrayTypeMember; + function parenthesizeElementTypeMembers(members) { + return ts.createNodeArray(ts.sameMap(members, parenthesizeElementTypeMember)); + } + ts.parenthesizeElementTypeMembers = parenthesizeElementTypeMembers; + function parenthesizeTypeParameters(typeParameters) { + if (ts.some(typeParameters)) { + var params = []; + for (var i = 0; i < typeParameters.length; ++i) { + var entry = typeParameters[i]; + params.push(i === 0 && ts.isFunctionOrConstructorTypeNode(entry) && entry.typeParameters ? + ts.createParenthesizedType(entry) : + entry); + } + return ts.createNodeArray(params); + } + } + ts.parenthesizeTypeParameters = parenthesizeTypeParameters; + function getLeftmostExpression(node, stopAtCallExpressions) { + while (true) { + switch (node.kind) { + case 203 /* PostfixUnaryExpression */: + node = node.operand; + continue; + case 204 /* BinaryExpression */: + node = node.left; + continue; + case 205 /* ConditionalExpression */: + node = node.condition; + continue; + case 193 /* TaggedTemplateExpression */: + node = node.tag; + continue; + case 191 /* CallExpression */: + if (stopAtCallExpressions) { + return node; + } + // falls through + case 212 /* AsExpression */: + case 190 /* ElementAccessExpression */: + case 189 /* PropertyAccessExpression */: + case 213 /* NonNullExpression */: + case 308 /* PartiallyEmittedExpression */: + node = node.expression; + continue; + } + return node; + } + } + function parenthesizeConciseBody(body) { + if (!ts.isBlock(body) && (isCommaSequence(body) || getLeftmostExpression(body, /*stopAtCallExpressions*/ false).kind === 188 /* ObjectLiteralExpression */)) { + return ts.setTextRange(ts.createParen(body), body); + } + return body; + } + ts.parenthesizeConciseBody = parenthesizeConciseBody; + function isCommaSequence(node) { + return node.kind === 204 /* BinaryExpression */ && node.operatorToken.kind === 27 /* CommaToken */ || + node.kind === 309 /* CommaListExpression */; + } + ts.isCommaSequence = isCommaSequence; + var OuterExpressionKinds; + (function (OuterExpressionKinds) { + OuterExpressionKinds[OuterExpressionKinds["Parentheses"] = 1] = "Parentheses"; + OuterExpressionKinds[OuterExpressionKinds["Assertions"] = 2] = "Assertions"; + OuterExpressionKinds[OuterExpressionKinds["PartiallyEmittedExpressions"] = 4] = "PartiallyEmittedExpressions"; + OuterExpressionKinds[OuterExpressionKinds["All"] = 7] = "All"; + })(OuterExpressionKinds = ts.OuterExpressionKinds || (ts.OuterExpressionKinds = {})); + function isOuterExpression(node, kinds) { + if (kinds === void 0) { kinds = 7 /* All */; } + switch (node.kind) { + case 195 /* ParenthesizedExpression */: + return (kinds & 1 /* Parentheses */) !== 0; + case 194 /* TypeAssertionExpression */: + case 212 /* AsExpression */: + case 213 /* NonNullExpression */: + return (kinds & 2 /* Assertions */) !== 0; + case 308 /* PartiallyEmittedExpression */: + return (kinds & 4 /* PartiallyEmittedExpressions */) !== 0; + } + return false; + } + ts.isOuterExpression = isOuterExpression; + function skipOuterExpressions(node, kinds) { + if (kinds === void 0) { kinds = 7 /* All */; } + var previousNode; + do { + previousNode = node; + if (kinds & 1 /* Parentheses */) { + node = ts.skipParentheses(node); + } + if (kinds & 2 /* Assertions */) { + node = skipAssertions(node); + } + if (kinds & 4 /* PartiallyEmittedExpressions */) { + node = ts.skipPartiallyEmittedExpressions(node); + } + } while (previousNode !== node); + return node; + } + ts.skipOuterExpressions = skipOuterExpressions; + function skipAssertions(node) { + while (ts.isAssertionExpression(node) || node.kind === 213 /* NonNullExpression */) { + node = node.expression; + } + return node; + } + ts.skipAssertions = skipAssertions; + function updateOuterExpression(outerExpression, expression) { + switch (outerExpression.kind) { + case 195 /* ParenthesizedExpression */: return ts.updateParen(outerExpression, expression); + case 194 /* TypeAssertionExpression */: return ts.updateTypeAssertion(outerExpression, outerExpression.type, expression); + case 212 /* AsExpression */: return ts.updateAsExpression(outerExpression, expression, outerExpression.type); + case 213 /* NonNullExpression */: return ts.updateNonNullExpression(outerExpression, expression); + case 308 /* PartiallyEmittedExpression */: return ts.updatePartiallyEmittedExpression(outerExpression, expression); + } + } + /** + * Determines whether a node is a parenthesized expression that can be ignored when recreating outer expressions. + * + * A parenthesized expression can be ignored when all of the following are true: + * + * - It's `pos` and `end` are not -1 + * - It does not have a custom source map range + * - It does not have a custom comment range + * - It does not have synthetic leading or trailing comments + * + * If an outermost parenthesized expression is ignored, but the containing expression requires a parentheses around + * the expression to maintain precedence, a new parenthesized expression should be created automatically when + * the containing expression is created/updated. + */ + function isIgnorableParen(node) { + return node.kind === 195 /* ParenthesizedExpression */ + && ts.nodeIsSynthesized(node) + && ts.nodeIsSynthesized(ts.getSourceMapRange(node)) + && ts.nodeIsSynthesized(ts.getCommentRange(node)) + && !ts.some(ts.getSyntheticLeadingComments(node)) + && !ts.some(ts.getSyntheticTrailingComments(node)); + } + function recreateOuterExpressions(outerExpression, innerExpression, kinds) { + if (kinds === void 0) { kinds = 7 /* All */; } + if (outerExpression && isOuterExpression(outerExpression, kinds) && !isIgnorableParen(outerExpression)) { + return updateOuterExpression(outerExpression, recreateOuterExpressions(outerExpression.expression, innerExpression)); + } + return innerExpression; + } + ts.recreateOuterExpressions = recreateOuterExpressions; + function startOnNewLine(node) { + return ts.setStartsOnNewLine(node, /*newLine*/ true); + } + ts.startOnNewLine = startOnNewLine; + function getExternalHelpersModuleName(node) { + var parseNode = ts.getOriginalNode(node, ts.isSourceFile); + var emitNode = parseNode && parseNode.emitNode; + return emitNode && emitNode.externalHelpersModuleName; + } + ts.getExternalHelpersModuleName = getExternalHelpersModuleName; + function getOrCreateExternalHelpersModuleNameIfNeeded(node, compilerOptions, hasExportStarsToExportValues, hasImportStarOrImportDefault) { + if (compilerOptions.importHelpers && ts.isEffectiveExternalModule(node, compilerOptions)) { + var externalHelpersModuleName = getExternalHelpersModuleName(node); + if (externalHelpersModuleName) { + return externalHelpersModuleName; + } + var moduleKind = ts.getEmitModuleKind(compilerOptions); + var create = (hasExportStarsToExportValues || (compilerOptions.esModuleInterop && hasImportStarOrImportDefault)) + && moduleKind !== ts.ModuleKind.System + && moduleKind !== ts.ModuleKind.ES2015 + && moduleKind !== ts.ModuleKind.ESNext; + if (!create) { + var helpers = ts.getEmitHelpers(node); + if (helpers) { + for (var _i = 0, helpers_2 = helpers; _i < helpers_2.length; _i++) { + var helper = helpers_2[_i]; + if (!helper.scoped) { + create = true; + break; + } + } + } + } + if (create) { + var parseNode = ts.getOriginalNode(node, ts.isSourceFile); + var emitNode = ts.getOrCreateEmitNode(parseNode); + return emitNode.externalHelpersModuleName || (emitNode.externalHelpersModuleName = ts.createUniqueName(ts.externalHelpersModuleNameText)); + } + } + } + ts.getOrCreateExternalHelpersModuleNameIfNeeded = getOrCreateExternalHelpersModuleNameIfNeeded; + /** + * Get the name of that target module from an import or export declaration + */ + function getLocalNameForExternalImport(node, sourceFile) { + var namespaceDeclaration = ts.getNamespaceDeclarationNode(node); + if (namespaceDeclaration && !ts.isDefaultImport(node)) { + var name = namespaceDeclaration.name; + return ts.isGeneratedIdentifier(name) ? name : ts.createIdentifier(ts.getSourceTextOfNodeFromSourceFile(sourceFile, name) || ts.idText(name)); + } + if (node.kind === 249 /* ImportDeclaration */ && node.importClause) { + return ts.getGeneratedNameForNode(node); + } + if (node.kind === 255 /* ExportDeclaration */ && node.moduleSpecifier) { + return ts.getGeneratedNameForNode(node); + } + return undefined; + } + ts.getLocalNameForExternalImport = getLocalNameForExternalImport; + /** + * Get the name of a target module from an import/export declaration as should be written in the emitted output. + * The emitted output name can be different from the input if: + * 1. The module has a /// + * 2. --out or --outFile is used, making the name relative to the rootDir + * 3- The containing SourceFile has an entry in renamedDependencies for the import as requested by some module loaders (e.g. System). + * Otherwise, a new StringLiteral node representing the module name will be returned. + */ + function getExternalModuleNameLiteral(importNode, sourceFile, host, resolver, compilerOptions) { + var moduleName = ts.getExternalModuleName(importNode); // TODO: GH#18217 + if (moduleName.kind === 10 /* StringLiteral */) { + return tryGetModuleNameFromDeclaration(importNode, host, resolver, compilerOptions) + || tryRenameExternalModule(moduleName, sourceFile) + || ts.getSynthesizedClone(moduleName); + } + return undefined; + } + ts.getExternalModuleNameLiteral = getExternalModuleNameLiteral; + /** + * Some bundlers (SystemJS builder) sometimes want to rename dependencies. + * Here we check if alternative name was provided for a given moduleName and return it if possible. + */ + function tryRenameExternalModule(moduleName, sourceFile) { + var rename = sourceFile.renamedDependencies && sourceFile.renamedDependencies.get(moduleName.text); + return rename && ts.createLiteral(rename); + } + /** + * Get the name of a module as should be written in the emitted output. + * The emitted output name can be different from the input if: + * 1. The module has a /// + * 2. --out or --outFile is used, making the name relative to the rootDir + * Otherwise, a new StringLiteral node representing the module name will be returned. + */ + function tryGetModuleNameFromFile(file, host, options) { + if (!file) { + return undefined; + } + if (file.moduleName) { + return ts.createLiteral(file.moduleName); + } + if (!file.isDeclarationFile && (options.out || options.outFile)) { + return ts.createLiteral(ts.getExternalModuleNameFromPath(host, file.fileName)); + } + return undefined; + } + ts.tryGetModuleNameFromFile = tryGetModuleNameFromFile; + function tryGetModuleNameFromDeclaration(declaration, host, resolver, compilerOptions) { + return tryGetModuleNameFromFile(resolver.getExternalModuleFileFromDeclaration(declaration), host, compilerOptions); + } + /** + * Gets the initializer of an BindingOrAssignmentElement. + */ + function getInitializerOfBindingOrAssignmentElement(bindingElement) { + if (ts.isDeclarationBindingElement(bindingElement)) { + // `1` in `let { a = 1 } = ...` + // `1` in `let { a: b = 1 } = ...` + // `1` in `let { a: {b} = 1 } = ...` + // `1` in `let { a: [b] = 1 } = ...` + // `1` in `let [a = 1] = ...` + // `1` in `let [{a} = 1] = ...` + // `1` in `let [[a] = 1] = ...` + return bindingElement.initializer; + } + if (ts.isPropertyAssignment(bindingElement)) { + // `1` in `({ a: b = 1 } = ...)` + // `1` in `({ a: {b} = 1 } = ...)` + // `1` in `({ a: [b] = 1 } = ...)` + var initializer = bindingElement.initializer; + return ts.isAssignmentExpression(initializer, /*excludeCompoundAssignment*/ true) + ? initializer.right + : undefined; + } + if (ts.isShorthandPropertyAssignment(bindingElement)) { + // `1` in `({ a = 1 } = ...)` + return bindingElement.objectAssignmentInitializer; + } + if (ts.isAssignmentExpression(bindingElement, /*excludeCompoundAssignment*/ true)) { + // `1` in `[a = 1] = ...` + // `1` in `[{a} = 1] = ...` + // `1` in `[[a] = 1] = ...` + return bindingElement.right; + } + if (ts.isSpreadElement(bindingElement)) { + // Recovery consistent with existing emit. + return getInitializerOfBindingOrAssignmentElement(bindingElement.expression); + } + } + ts.getInitializerOfBindingOrAssignmentElement = getInitializerOfBindingOrAssignmentElement; + /** + * Gets the name of an BindingOrAssignmentElement. + */ + function getTargetOfBindingOrAssignmentElement(bindingElement) { + if (ts.isDeclarationBindingElement(bindingElement)) { + // `a` in `let { a } = ...` + // `a` in `let { a = 1 } = ...` + // `b` in `let { a: b } = ...` + // `b` in `let { a: b = 1 } = ...` + // `a` in `let { ...a } = ...` + // `{b}` in `let { a: {b} } = ...` + // `{b}` in `let { a: {b} = 1 } = ...` + // `[b]` in `let { a: [b] } = ...` + // `[b]` in `let { a: [b] = 1 } = ...` + // `a` in `let [a] = ...` + // `a` in `let [a = 1] = ...` + // `a` in `let [...a] = ...` + // `{a}` in `let [{a}] = ...` + // `{a}` in `let [{a} = 1] = ...` + // `[a]` in `let [[a]] = ...` + // `[a]` in `let [[a] = 1] = ...` + return bindingElement.name; + } + if (ts.isObjectLiteralElementLike(bindingElement)) { + switch (bindingElement.kind) { + case 275 /* PropertyAssignment */: + // `b` in `({ a: b } = ...)` + // `b` in `({ a: b = 1 } = ...)` + // `{b}` in `({ a: {b} } = ...)` + // `{b}` in `({ a: {b} = 1 } = ...)` + // `[b]` in `({ a: [b] } = ...)` + // `[b]` in `({ a: [b] = 1 } = ...)` + // `b.c` in `({ a: b.c } = ...)` + // `b.c` in `({ a: b.c = 1 } = ...)` + // `b[0]` in `({ a: b[0] } = ...)` + // `b[0]` in `({ a: b[0] = 1 } = ...)` + return getTargetOfBindingOrAssignmentElement(bindingElement.initializer); + case 276 /* ShorthandPropertyAssignment */: + // `a` in `({ a } = ...)` + // `a` in `({ a = 1 } = ...)` + return bindingElement.name; + case 277 /* SpreadAssignment */: + // `a` in `({ ...a } = ...)` + return getTargetOfBindingOrAssignmentElement(bindingElement.expression); + } + // no target + return undefined; + } + if (ts.isAssignmentExpression(bindingElement, /*excludeCompoundAssignment*/ true)) { + // `a` in `[a = 1] = ...` + // `{a}` in `[{a} = 1] = ...` + // `[a]` in `[[a] = 1] = ...` + // `a.b` in `[a.b = 1] = ...` + // `a[0]` in `[a[0] = 1] = ...` + return getTargetOfBindingOrAssignmentElement(bindingElement.left); + } + if (ts.isSpreadElement(bindingElement)) { + // `a` in `[...a] = ...` + return getTargetOfBindingOrAssignmentElement(bindingElement.expression); + } + // `a` in `[a] = ...` + // `{a}` in `[{a}] = ...` + // `[a]` in `[[a]] = ...` + // `a.b` in `[a.b] = ...` + // `a[0]` in `[a[0]] = ...` + return bindingElement; + } + ts.getTargetOfBindingOrAssignmentElement = getTargetOfBindingOrAssignmentElement; + /** + * Determines whether an BindingOrAssignmentElement is a rest element. + */ + function getRestIndicatorOfBindingOrAssignmentElement(bindingElement) { + switch (bindingElement.kind) { + case 151 /* Parameter */: + case 186 /* BindingElement */: + // `...` in `let [...a] = ...` + return bindingElement.dotDotDotToken; + case 208 /* SpreadElement */: + case 277 /* SpreadAssignment */: + // `...` in `[...a] = ...` + return bindingElement; + } + return undefined; + } + ts.getRestIndicatorOfBindingOrAssignmentElement = getRestIndicatorOfBindingOrAssignmentElement; + /** + * Gets the property name of a BindingOrAssignmentElement + */ + function getPropertyNameOfBindingOrAssignmentElement(bindingElement) { + switch (bindingElement.kind) { + case 186 /* BindingElement */: + // `a` in `let { a: b } = ...` + // `[a]` in `let { [a]: b } = ...` + // `"a"` in `let { "a": b } = ...` + // `1` in `let { 1: b } = ...` + if (bindingElement.propertyName) { + var propertyName = bindingElement.propertyName; + return ts.isComputedPropertyName(propertyName) && isStringOrNumericLiteral(propertyName.expression) + ? propertyName.expression + : propertyName; + } + break; + case 275 /* PropertyAssignment */: + // `a` in `({ a: b } = ...)` + // `[a]` in `({ [a]: b } = ...)` + // `"a"` in `({ "a": b } = ...)` + // `1` in `({ 1: b } = ...)` + if (bindingElement.name) { + var propertyName = bindingElement.name; + return ts.isComputedPropertyName(propertyName) && isStringOrNumericLiteral(propertyName.expression) + ? propertyName.expression + : propertyName; + } + break; + case 277 /* SpreadAssignment */: + // `a` in `({ ...a } = ...)` + return bindingElement.name; + } + var target = getTargetOfBindingOrAssignmentElement(bindingElement); + if (target && ts.isPropertyName(target)) { + return ts.isComputedPropertyName(target) && isStringOrNumericLiteral(target.expression) + ? target.expression + : target; + } + ts.Debug.fail("Invalid property name for binding element."); + } + ts.getPropertyNameOfBindingOrAssignmentElement = getPropertyNameOfBindingOrAssignmentElement; + function isStringOrNumericLiteral(node) { + var kind = node.kind; + return kind === 10 /* StringLiteral */ + || kind === 8 /* NumericLiteral */; + } + /** + * Gets the elements of a BindingOrAssignmentPattern + */ + function getElementsOfBindingOrAssignmentPattern(name) { + switch (name.kind) { + case 184 /* ObjectBindingPattern */: + case 185 /* ArrayBindingPattern */: + case 187 /* ArrayLiteralExpression */: + // `a` in `{a}` + // `a` in `[a]` + return name.elements; + case 188 /* ObjectLiteralExpression */: + // `a` in `{a}` + return name.properties; + } + } + ts.getElementsOfBindingOrAssignmentPattern = getElementsOfBindingOrAssignmentPattern; + function convertToArrayAssignmentElement(element) { + if (ts.isBindingElement(element)) { + if (element.dotDotDotToken) { + ts.Debug.assertNode(element.name, ts.isIdentifier); + return ts.setOriginalNode(ts.setTextRange(ts.createSpread(element.name), element), element); + } + var expression = convertToAssignmentElementTarget(element.name); + return element.initializer + ? ts.setOriginalNode(ts.setTextRange(ts.createAssignment(expression, element.initializer), element), element) + : expression; + } + ts.Debug.assertNode(element, ts.isExpression); + return element; + } + ts.convertToArrayAssignmentElement = convertToArrayAssignmentElement; + function convertToObjectAssignmentElement(element) { + if (ts.isBindingElement(element)) { + if (element.dotDotDotToken) { + ts.Debug.assertNode(element.name, ts.isIdentifier); + return ts.setOriginalNode(ts.setTextRange(ts.createSpreadAssignment(element.name), element), element); + } + if (element.propertyName) { + var expression = convertToAssignmentElementTarget(element.name); + return ts.setOriginalNode(ts.setTextRange(ts.createPropertyAssignment(element.propertyName, element.initializer ? ts.createAssignment(expression, element.initializer) : expression), element), element); + } + ts.Debug.assertNode(element.name, ts.isIdentifier); + return ts.setOriginalNode(ts.setTextRange(ts.createShorthandPropertyAssignment(element.name, element.initializer), element), element); + } + ts.Debug.assertNode(element, ts.isObjectLiteralElementLike); + return element; + } + ts.convertToObjectAssignmentElement = convertToObjectAssignmentElement; + function convertToAssignmentPattern(node) { + switch (node.kind) { + case 185 /* ArrayBindingPattern */: + case 187 /* ArrayLiteralExpression */: + return convertToArrayAssignmentPattern(node); + case 184 /* ObjectBindingPattern */: + case 188 /* ObjectLiteralExpression */: + return convertToObjectAssignmentPattern(node); + } + } + ts.convertToAssignmentPattern = convertToAssignmentPattern; + function convertToObjectAssignmentPattern(node) { + if (ts.isObjectBindingPattern(node)) { + return ts.setOriginalNode(ts.setTextRange(ts.createObjectLiteral(ts.map(node.elements, convertToObjectAssignmentElement)), node), node); + } + ts.Debug.assertNode(node, ts.isObjectLiteralExpression); + return node; + } + ts.convertToObjectAssignmentPattern = convertToObjectAssignmentPattern; + function convertToArrayAssignmentPattern(node) { + if (ts.isArrayBindingPattern(node)) { + return ts.setOriginalNode(ts.setTextRange(ts.createArrayLiteral(ts.map(node.elements, convertToArrayAssignmentElement)), node), node); + } + ts.Debug.assertNode(node, ts.isArrayLiteralExpression); + return node; + } + ts.convertToArrayAssignmentPattern = convertToArrayAssignmentPattern; + function convertToAssignmentElementTarget(node) { + if (ts.isBindingPattern(node)) { + return convertToAssignmentPattern(node); + } + ts.Debug.assertNode(node, ts.isExpression); + return node; + } + ts.convertToAssignmentElementTarget = convertToAssignmentElementTarget; +})(ts || (ts = {})); +var ts; +(function (ts) { + var isTypeNodeOrTypeParameterDeclaration = ts.or(ts.isTypeNode, ts.isTypeParameterDeclaration); + function visitNode(node, visitor, test, lift) { + if (node === undefined || visitor === undefined) { + return node; + } + ts.aggregateTransformFlags(node); + var visited = visitor(node); + if (visited === node) { + return node; + } + var visitedNode; + if (visited === undefined) { + return undefined; + } + else if (ts.isArray(visited)) { + visitedNode = (lift || extractSingleNode)(visited); + } + else { + visitedNode = visited; + } + ts.Debug.assertNode(visitedNode, test); + ts.aggregateTransformFlags(visitedNode); + return visitedNode; + } + ts.visitNode = visitNode; + /** + * Visits a NodeArray using the supplied visitor, possibly returning a new NodeArray in its place. + * + * @param nodes The NodeArray to visit. + * @param visitor The callback used to visit a Node. + * @param test A node test to execute for each node. + * @param start An optional value indicating the starting offset at which to start visiting. + * @param count An optional value indicating the maximum number of nodes to visit. + */ + function visitNodes(nodes, visitor, test, start, count) { + if (nodes === undefined || visitor === undefined) { + return nodes; + } + var updated; + // Ensure start and count have valid values + var length = nodes.length; + if (start === undefined || start < 0) { + start = 0; + } + if (count === undefined || count > length - start) { + count = length - start; + } + if (start > 0 || count < length) { + // If we are not visiting all of the original nodes, we must always create a new array. + // Since this is a fragment of a node array, we do not copy over the previous location + // and will only copy over `hasTrailingComma` if we are including the last element. + updated = ts.createNodeArray([], /*hasTrailingComma*/ nodes.hasTrailingComma && start + count === length); + } + // Visit each original node. + for (var i = 0; i < count; i++) { + var node = nodes[i + start]; + ts.aggregateTransformFlags(node); + var visited = node !== undefined ? visitor(node) : undefined; + if (updated !== undefined || visited === undefined || visited !== node) { + if (updated === undefined) { + // Ensure we have a copy of `nodes`, up to the current index. + updated = ts.createNodeArray(nodes.slice(0, i), nodes.hasTrailingComma); + ts.setTextRange(updated, nodes); + } + if (visited) { + if (ts.isArray(visited)) { + for (var _i = 0, visited_1 = visited; _i < visited_1.length; _i++) { + var visitedNode = visited_1[_i]; + ts.Debug.assertNode(visitedNode, test); + ts.aggregateTransformFlags(visitedNode); + updated.push(visitedNode); + } + } + else { + ts.Debug.assertNode(visited, test); + ts.aggregateTransformFlags(visited); + updated.push(visited); + } + } + } + } + return updated || nodes; + } + ts.visitNodes = visitNodes; + /** + * Starts a new lexical environment and visits a statement list, ending the lexical environment + * and merging hoisted declarations upon completion. + */ + function visitLexicalEnvironment(statements, visitor, context, start, ensureUseStrict) { + context.startLexicalEnvironment(); + statements = visitNodes(statements, visitor, ts.isStatement, start); + if (ensureUseStrict && !ts.startsWithUseStrict(statements)) { + statements = ts.setTextRange(ts.createNodeArray([ts.createExpressionStatement(ts.createLiteral("use strict"))].concat(statements)), statements); + } + var declarations = context.endLexicalEnvironment(); + return ts.setTextRange(ts.createNodeArray(ts.concatenate(declarations, statements)), statements); + } + ts.visitLexicalEnvironment = visitLexicalEnvironment; + /** + * Starts a new lexical environment and visits a parameter list, suspending the lexical + * environment upon completion. + */ + function visitParameterList(nodes, visitor, context, nodesVisitor) { + if (nodesVisitor === void 0) { nodesVisitor = visitNodes; } + context.startLexicalEnvironment(); + var updated = nodesVisitor(nodes, visitor, ts.isParameterDeclaration); + context.suspendLexicalEnvironment(); + return updated; + } + ts.visitParameterList = visitParameterList; + function visitFunctionBody(node, visitor, context) { + context.resumeLexicalEnvironment(); + var updated = visitNode(node, visitor, ts.isConciseBody); + var declarations = context.endLexicalEnvironment(); + if (ts.some(declarations)) { + var block = ts.convertToFunctionBody(updated); + var statements = ts.mergeLexicalEnvironment(block.statements, declarations); + return ts.updateBlock(block, statements); + } + return updated; + } + ts.visitFunctionBody = visitFunctionBody; + function visitEachChild(node, visitor, context, nodesVisitor, tokenVisitor) { + if (nodesVisitor === void 0) { nodesVisitor = visitNodes; } + if (node === undefined) { + return undefined; + } + var kind = node.kind; + // No need to visit nodes with no children. + if ((kind > 0 /* FirstToken */ && kind <= 147 /* LastToken */) || kind === 178 /* ThisType */) { + return node; + } + switch (kind) { + // Names + case 72 /* Identifier */: + return ts.updateIdentifier(node, nodesVisitor(node.typeArguments, visitor, isTypeNodeOrTypeParameterDeclaration)); + case 148 /* QualifiedName */: + return ts.updateQualifiedName(node, visitNode(node.left, visitor, ts.isEntityName), visitNode(node.right, visitor, ts.isIdentifier)); + case 149 /* ComputedPropertyName */: + return ts.updateComputedPropertyName(node, visitNode(node.expression, visitor, ts.isExpression)); + // Signature elements + case 150 /* TypeParameter */: + return ts.updateTypeParameterDeclaration(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.constraint, visitor, ts.isTypeNode), visitNode(node.default, visitor, ts.isTypeNode)); + case 151 /* Parameter */: + return ts.updateParameter(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.dotDotDotToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isBindingName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); + case 152 /* Decorator */: + return ts.updateDecorator(node, visitNode(node.expression, visitor, ts.isExpression)); + // Type elements + case 153 /* PropertySignature */: + return ts.updatePropertySignature(node, nodesVisitor(node.modifiers, visitor, ts.isToken), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); + case 154 /* PropertyDeclaration */: + return ts.updateProperty(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); + case 155 /* MethodSignature */: + return ts.updateMethodSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken)); + case 156 /* MethodDeclaration */: + return ts.updateMethod(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); + case 157 /* Constructor */: + return ts.updateConstructor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context)); + case 158 /* GetAccessor */: + return ts.updateGetAccessor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); + case 159 /* SetAccessor */: + return ts.updateSetAccessor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context)); + case 160 /* CallSignature */: + return ts.updateCallSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); + case 161 /* ConstructSignature */: + return ts.updateConstructSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); + case 162 /* IndexSignature */: + return ts.updateIndexSignature(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); + // Types + case 163 /* TypePredicate */: + return ts.updateTypePredicateNode(node, visitNode(node.parameterName, visitor), visitNode(node.type, visitor, ts.isTypeNode)); + case 164 /* TypeReference */: + return ts.updateTypeReferenceNode(node, visitNode(node.typeName, visitor, ts.isEntityName), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode)); + case 165 /* FunctionType */: + return ts.updateFunctionTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); + case 166 /* ConstructorType */: + return ts.updateConstructorTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); + case 167 /* TypeQuery */: + return ts.updateTypeQueryNode(node, visitNode(node.exprName, visitor, ts.isEntityName)); + case 168 /* TypeLiteral */: + return ts.updateTypeLiteralNode(node, nodesVisitor(node.members, visitor, ts.isTypeElement)); + case 169 /* ArrayType */: + return ts.updateArrayTypeNode(node, visitNode(node.elementType, visitor, ts.isTypeNode)); + case 170 /* TupleType */: + return ts.updateTupleTypeNode(node, nodesVisitor(node.elementTypes, visitor, ts.isTypeNode)); + case 171 /* OptionalType */: + return ts.updateOptionalTypeNode(node, visitNode(node.type, visitor, ts.isTypeNode)); + case 172 /* RestType */: + return ts.updateRestTypeNode(node, visitNode(node.type, visitor, ts.isTypeNode)); + case 173 /* UnionType */: + return ts.updateUnionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode)); + case 174 /* IntersectionType */: + return ts.updateIntersectionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode)); + case 175 /* ConditionalType */: + return ts.updateConditionalTypeNode(node, visitNode(node.checkType, visitor, ts.isTypeNode), visitNode(node.extendsType, visitor, ts.isTypeNode), visitNode(node.trueType, visitor, ts.isTypeNode), visitNode(node.falseType, visitor, ts.isTypeNode)); + case 176 /* InferType */: + return ts.updateInferTypeNode(node, visitNode(node.typeParameter, visitor, ts.isTypeParameterDeclaration)); + case 183 /* ImportType */: + return ts.updateImportTypeNode(node, visitNode(node.argument, visitor, ts.isTypeNode), visitNode(node.qualifier, visitor, ts.isEntityName), visitNodes(node.typeArguments, visitor, ts.isTypeNode), node.isTypeOf); + case 177 /* ParenthesizedType */: + return ts.updateParenthesizedType(node, visitNode(node.type, visitor, ts.isTypeNode)); + case 179 /* TypeOperator */: + return ts.updateTypeOperatorNode(node, visitNode(node.type, visitor, ts.isTypeNode)); + case 180 /* IndexedAccessType */: + return ts.updateIndexedAccessTypeNode(node, visitNode(node.objectType, visitor, ts.isTypeNode), visitNode(node.indexType, visitor, ts.isTypeNode)); + case 181 /* MappedType */: + return ts.updateMappedTypeNode(node, visitNode(node.readonlyToken, tokenVisitor, ts.isToken), visitNode(node.typeParameter, visitor, ts.isTypeParameterDeclaration), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode)); + case 182 /* LiteralType */: + return ts.updateLiteralTypeNode(node, visitNode(node.literal, visitor, ts.isExpression)); + // Binding patterns + case 184 /* ObjectBindingPattern */: + return ts.updateObjectBindingPattern(node, nodesVisitor(node.elements, visitor, ts.isBindingElement)); + case 185 /* ArrayBindingPattern */: + return ts.updateArrayBindingPattern(node, nodesVisitor(node.elements, visitor, ts.isArrayBindingElement)); + case 186 /* BindingElement */: + return ts.updateBindingElement(node, visitNode(node.dotDotDotToken, tokenVisitor, ts.isToken), visitNode(node.propertyName, visitor, ts.isPropertyName), visitNode(node.name, visitor, ts.isBindingName), visitNode(node.initializer, visitor, ts.isExpression)); + // Expression + case 187 /* ArrayLiteralExpression */: + return ts.updateArrayLiteral(node, nodesVisitor(node.elements, visitor, ts.isExpression)); + case 188 /* ObjectLiteralExpression */: + return ts.updateObjectLiteral(node, nodesVisitor(node.properties, visitor, ts.isObjectLiteralElementLike)); + case 189 /* PropertyAccessExpression */: + return ts.updatePropertyAccess(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.name, visitor, ts.isIdentifier)); + case 190 /* ElementAccessExpression */: + return ts.updateElementAccess(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.argumentExpression, visitor, ts.isExpression)); + case 191 /* CallExpression */: + return ts.updateCall(node, visitNode(node.expression, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression)); + case 192 /* NewExpression */: + return ts.updateNew(node, visitNode(node.expression, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression)); + case 193 /* TaggedTemplateExpression */: + return ts.updateTaggedTemplate(node, visitNode(node.tag, visitor, ts.isExpression), visitNodes(node.typeArguments, visitor, ts.isExpression), visitNode(node.template, visitor, ts.isTemplateLiteral)); + case 194 /* TypeAssertionExpression */: + return ts.updateTypeAssertion(node, visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.expression, visitor, ts.isExpression)); + case 195 /* ParenthesizedExpression */: + return ts.updateParen(node, visitNode(node.expression, visitor, ts.isExpression)); + case 196 /* FunctionExpression */: + return ts.updateFunctionExpression(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); + case 197 /* ArrowFunction */: + return ts.updateArrowFunction(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.equalsGreaterThanToken, visitor, ts.isToken), visitFunctionBody(node.body, visitor, context)); + case 198 /* DeleteExpression */: + return ts.updateDelete(node, visitNode(node.expression, visitor, ts.isExpression)); + case 199 /* TypeOfExpression */: + return ts.updateTypeOf(node, visitNode(node.expression, visitor, ts.isExpression)); + case 200 /* VoidExpression */: + return ts.updateVoid(node, visitNode(node.expression, visitor, ts.isExpression)); + case 201 /* AwaitExpression */: + return ts.updateAwait(node, visitNode(node.expression, visitor, ts.isExpression)); + case 202 /* PrefixUnaryExpression */: + return ts.updatePrefix(node, visitNode(node.operand, visitor, ts.isExpression)); + case 203 /* PostfixUnaryExpression */: + return ts.updatePostfix(node, visitNode(node.operand, visitor, ts.isExpression)); + case 204 /* BinaryExpression */: + return ts.updateBinary(node, visitNode(node.left, visitor, ts.isExpression), visitNode(node.right, visitor, ts.isExpression), visitNode(node.operatorToken, visitor, ts.isToken)); + case 205 /* ConditionalExpression */: + return ts.updateConditional(node, visitNode(node.condition, visitor, ts.isExpression), visitNode(node.questionToken, visitor, ts.isToken), visitNode(node.whenTrue, visitor, ts.isExpression), visitNode(node.colonToken, visitor, ts.isToken), visitNode(node.whenFalse, visitor, ts.isExpression)); + case 206 /* TemplateExpression */: + return ts.updateTemplateExpression(node, visitNode(node.head, visitor, ts.isTemplateHead), nodesVisitor(node.templateSpans, visitor, ts.isTemplateSpan)); + case 207 /* YieldExpression */: + return ts.updateYield(node, visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.expression, visitor, ts.isExpression)); + case 208 /* SpreadElement */: + return ts.updateSpread(node, visitNode(node.expression, visitor, ts.isExpression)); + case 209 /* ClassExpression */: + return ts.updateClassExpression(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement)); + case 211 /* ExpressionWithTypeArguments */: + return ts.updateExpressionWithTypeArguments(node, nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), visitNode(node.expression, visitor, ts.isExpression)); + case 212 /* AsExpression */: + return ts.updateAsExpression(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.type, visitor, ts.isTypeNode)); + case 213 /* NonNullExpression */: + return ts.updateNonNullExpression(node, visitNode(node.expression, visitor, ts.isExpression)); + case 214 /* MetaProperty */: + return ts.updateMetaProperty(node, visitNode(node.name, visitor, ts.isIdentifier)); + // Misc + case 216 /* TemplateSpan */: + return ts.updateTemplateSpan(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.literal, visitor, ts.isTemplateMiddleOrTemplateTail)); + // Element + case 218 /* Block */: + return ts.updateBlock(node, nodesVisitor(node.statements, visitor, ts.isStatement)); + case 219 /* VariableStatement */: + return ts.updateVariableStatement(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.declarationList, visitor, ts.isVariableDeclarationList)); + case 221 /* ExpressionStatement */: + return ts.updateExpressionStatement(node, visitNode(node.expression, visitor, ts.isExpression)); + case 222 /* IfStatement */: + return ts.updateIf(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.thenStatement, visitor, ts.isStatement, ts.liftToBlock), visitNode(node.elseStatement, visitor, ts.isStatement, ts.liftToBlock)); + case 223 /* DoStatement */: + return ts.updateDo(node, visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock), visitNode(node.expression, visitor, ts.isExpression)); + case 224 /* WhileStatement */: + return ts.updateWhile(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); + case 225 /* ForStatement */: + return ts.updateFor(node, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.condition, visitor, ts.isExpression), visitNode(node.incrementor, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); + case 226 /* ForInStatement */: + return ts.updateForIn(node, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); + case 227 /* ForOfStatement */: + return ts.updateForOf(node, visitNode(node.awaitModifier, visitor, ts.isToken), visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); + case 228 /* ContinueStatement */: + return ts.updateContinue(node, visitNode(node.label, visitor, ts.isIdentifier)); + case 229 /* BreakStatement */: + return ts.updateBreak(node, visitNode(node.label, visitor, ts.isIdentifier)); + case 230 /* ReturnStatement */: + return ts.updateReturn(node, visitNode(node.expression, visitor, ts.isExpression)); + case 231 /* WithStatement */: + return ts.updateWith(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); + case 232 /* SwitchStatement */: + return ts.updateSwitch(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.caseBlock, visitor, ts.isCaseBlock)); + case 233 /* LabeledStatement */: + return ts.updateLabel(node, visitNode(node.label, visitor, ts.isIdentifier), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); + case 234 /* ThrowStatement */: + return ts.updateThrow(node, visitNode(node.expression, visitor, ts.isExpression)); + case 235 /* TryStatement */: + return ts.updateTry(node, visitNode(node.tryBlock, visitor, ts.isBlock), visitNode(node.catchClause, visitor, ts.isCatchClause), visitNode(node.finallyBlock, visitor, ts.isBlock)); + case 237 /* VariableDeclaration */: + return ts.updateVariableDeclaration(node, visitNode(node.name, visitor, ts.isBindingName), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); + case 238 /* VariableDeclarationList */: + return ts.updateVariableDeclarationList(node, nodesVisitor(node.declarations, visitor, ts.isVariableDeclaration)); + case 239 /* FunctionDeclaration */: + return ts.updateFunctionDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); + case 240 /* ClassDeclaration */: + return ts.updateClassDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement)); + case 241 /* InterfaceDeclaration */: + return ts.updateInterfaceDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isTypeElement)); + case 242 /* TypeAliasDeclaration */: + return ts.updateTypeAliasDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); + case 243 /* EnumDeclaration */: + return ts.updateEnumDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.members, visitor, ts.isEnumMember)); + case 244 /* ModuleDeclaration */: + return ts.updateModuleDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.body, visitor, ts.isModuleBody)); + case 245 /* ModuleBlock */: + return ts.updateModuleBlock(node, nodesVisitor(node.statements, visitor, ts.isStatement)); + case 246 /* CaseBlock */: + return ts.updateCaseBlock(node, nodesVisitor(node.clauses, visitor, ts.isCaseOrDefaultClause)); + case 247 /* NamespaceExportDeclaration */: + return ts.updateNamespaceExportDeclaration(node, visitNode(node.name, visitor, ts.isIdentifier)); + case 248 /* ImportEqualsDeclaration */: + return ts.updateImportEqualsDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.moduleReference, visitor, ts.isModuleReference)); + case 249 /* ImportDeclaration */: + return ts.updateImportDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.importClause, visitor, ts.isImportClause), visitNode(node.moduleSpecifier, visitor, ts.isExpression)); + case 250 /* ImportClause */: + return ts.updateImportClause(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.namedBindings, visitor, ts.isNamedImportBindings)); + case 251 /* NamespaceImport */: + return ts.updateNamespaceImport(node, visitNode(node.name, visitor, ts.isIdentifier)); + case 252 /* NamedImports */: + return ts.updateNamedImports(node, nodesVisitor(node.elements, visitor, ts.isImportSpecifier)); + case 253 /* ImportSpecifier */: + return ts.updateImportSpecifier(node, visitNode(node.propertyName, visitor, ts.isIdentifier), visitNode(node.name, visitor, ts.isIdentifier)); + case 254 /* ExportAssignment */: + return ts.updateExportAssignment(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.expression, visitor, ts.isExpression)); + case 255 /* ExportDeclaration */: + return ts.updateExportDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.exportClause, visitor, ts.isNamedExports), visitNode(node.moduleSpecifier, visitor, ts.isExpression)); + case 256 /* NamedExports */: + return ts.updateNamedExports(node, nodesVisitor(node.elements, visitor, ts.isExportSpecifier)); + case 257 /* ExportSpecifier */: + return ts.updateExportSpecifier(node, visitNode(node.propertyName, visitor, ts.isIdentifier), visitNode(node.name, visitor, ts.isIdentifier)); + // Module references + case 259 /* ExternalModuleReference */: + return ts.updateExternalModuleReference(node, visitNode(node.expression, visitor, ts.isExpression)); + // JSX + case 260 /* JsxElement */: + return ts.updateJsxElement(node, visitNode(node.openingElement, visitor, ts.isJsxOpeningElement), nodesVisitor(node.children, visitor, ts.isJsxChild), visitNode(node.closingElement, visitor, ts.isJsxClosingElement)); + case 261 /* JsxSelfClosingElement */: + return ts.updateJsxSelfClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), visitNode(node.attributes, visitor, ts.isJsxAttributes)); + case 262 /* JsxOpeningElement */: + return ts.updateJsxOpeningElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), visitNode(node.attributes, visitor, ts.isJsxAttributes)); + case 263 /* JsxClosingElement */: + return ts.updateJsxClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression)); + case 264 /* JsxFragment */: + return ts.updateJsxFragment(node, visitNode(node.openingFragment, visitor, ts.isJsxOpeningFragment), nodesVisitor(node.children, visitor, ts.isJsxChild), visitNode(node.closingFragment, visitor, ts.isJsxClosingFragment)); + case 267 /* JsxAttribute */: + return ts.updateJsxAttribute(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.initializer, visitor, ts.isStringLiteralOrJsxExpression)); + case 268 /* JsxAttributes */: + return ts.updateJsxAttributes(node, nodesVisitor(node.properties, visitor, ts.isJsxAttributeLike)); + case 269 /* JsxSpreadAttribute */: + return ts.updateJsxSpreadAttribute(node, visitNode(node.expression, visitor, ts.isExpression)); + case 270 /* JsxExpression */: + return ts.updateJsxExpression(node, visitNode(node.expression, visitor, ts.isExpression)); + // Clauses + case 271 /* CaseClause */: + return ts.updateCaseClause(node, visitNode(node.expression, visitor, ts.isExpression), nodesVisitor(node.statements, visitor, ts.isStatement)); + case 272 /* DefaultClause */: + return ts.updateDefaultClause(node, nodesVisitor(node.statements, visitor, ts.isStatement)); + case 273 /* HeritageClause */: + return ts.updateHeritageClause(node, nodesVisitor(node.types, visitor, ts.isExpressionWithTypeArguments)); + case 274 /* CatchClause */: + return ts.updateCatchClause(node, visitNode(node.variableDeclaration, visitor, ts.isVariableDeclaration), visitNode(node.block, visitor, ts.isBlock)); + // Property assignments + case 275 /* PropertyAssignment */: + return ts.updatePropertyAssignment(node, visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.initializer, visitor, ts.isExpression)); + case 276 /* ShorthandPropertyAssignment */: + return ts.updateShorthandPropertyAssignment(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.objectAssignmentInitializer, visitor, ts.isExpression)); + case 277 /* SpreadAssignment */: + return ts.updateSpreadAssignment(node, visitNode(node.expression, visitor, ts.isExpression)); + // Enum + case 278 /* EnumMember */: + return ts.updateEnumMember(node, visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.initializer, visitor, ts.isExpression)); + // Top-level nodes + case 279 /* SourceFile */: + return ts.updateSourceFileNode(node, visitLexicalEnvironment(node.statements, visitor, context)); + // Transformation nodes + case 308 /* PartiallyEmittedExpression */: + return ts.updatePartiallyEmittedExpression(node, visitNode(node.expression, visitor, ts.isExpression)); + case 309 /* CommaListExpression */: + return ts.updateCommaList(node, nodesVisitor(node.elements, visitor, ts.isExpression)); + default: + // No need to visit nodes with no children. + return node; + } + } + ts.visitEachChild = visitEachChild; + /** + * Extracts the single node from a NodeArray. + * + * @param nodes The NodeArray. + */ + function extractSingleNode(nodes) { + ts.Debug.assert(nodes.length <= 1, "Too many nodes written to output."); + return ts.singleOrUndefined(nodes); + } +})(ts || (ts = {})); +/* @internal */ +(function (ts) { + function reduceNode(node, f, initial) { + return node ? f(initial, node) : initial; + } + function reduceNodeArray(nodes, f, initial) { + return nodes ? f(initial, nodes) : initial; + } + /** + * Similar to `reduceLeft`, performs a reduction against each child of a node. + * NOTE: Unlike `forEachChild`, this does *not* visit every node. + * + * @param node The node containing the children to reduce. + * @param initial The initial value to supply to the reduction. + * @param f The callback function + */ + function reduceEachChild(node, initial, cbNode, cbNodeArray) { + if (node === undefined) { + return initial; + } + var reduceNodes = cbNodeArray ? reduceNodeArray : ts.reduceLeft; + var cbNodes = cbNodeArray || cbNode; + var kind = node.kind; + // No need to visit nodes with no children. + if ((kind > 0 /* FirstToken */ && kind <= 147 /* LastToken */)) { + return initial; + } + // We do not yet support types. + if ((kind >= 163 /* TypePredicate */ && kind <= 182 /* LiteralType */)) { + return initial; + } + var result = initial; + switch (node.kind) { + // Leaf nodes + case 217 /* SemicolonClassElement */: + case 220 /* EmptyStatement */: + case 210 /* OmittedExpression */: + case 236 /* DebuggerStatement */: + case 307 /* NotEmittedStatement */: + // No need to visit nodes with no children. + break; + // Names + case 148 /* QualifiedName */: + result = reduceNode(node.left, cbNode, result); + result = reduceNode(node.right, cbNode, result); + break; + case 149 /* ComputedPropertyName */: + result = reduceNode(node.expression, cbNode, result); + break; + // Signature elements + case 151 /* Parameter */: + result = reduceNodes(node.decorators, cbNodes, result); + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.type, cbNode, result); + result = reduceNode(node.initializer, cbNode, result); + break; + case 152 /* Decorator */: + result = reduceNode(node.expression, cbNode, result); + break; + // Type member + case 153 /* PropertySignature */: + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.questionToken, cbNode, result); + result = reduceNode(node.type, cbNode, result); + result = reduceNode(node.initializer, cbNode, result); + break; + case 154 /* PropertyDeclaration */: + result = reduceNodes(node.decorators, cbNodes, result); + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.type, cbNode, result); + result = reduceNode(node.initializer, cbNode, result); + break; + case 156 /* MethodDeclaration */: + result = reduceNodes(node.decorators, cbNodes, result); + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNodes(node.typeParameters, cbNodes, result); + result = reduceNodes(node.parameters, cbNodes, result); + result = reduceNode(node.type, cbNode, result); + result = reduceNode(node.body, cbNode, result); + break; + case 157 /* Constructor */: + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNodes(node.parameters, cbNodes, result); + result = reduceNode(node.body, cbNode, result); + break; + case 158 /* GetAccessor */: + result = reduceNodes(node.decorators, cbNodes, result); + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNodes(node.parameters, cbNodes, result); + result = reduceNode(node.type, cbNode, result); + result = reduceNode(node.body, cbNode, result); + break; + case 159 /* SetAccessor */: + result = reduceNodes(node.decorators, cbNodes, result); + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNodes(node.parameters, cbNodes, result); + result = reduceNode(node.body, cbNode, result); + break; + // Binding patterns + case 184 /* ObjectBindingPattern */: + case 185 /* ArrayBindingPattern */: + result = reduceNodes(node.elements, cbNodes, result); + break; + case 186 /* BindingElement */: + result = reduceNode(node.propertyName, cbNode, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.initializer, cbNode, result); + break; + // Expression + case 187 /* ArrayLiteralExpression */: + result = reduceNodes(node.elements, cbNodes, result); + break; + case 188 /* ObjectLiteralExpression */: + result = reduceNodes(node.properties, cbNodes, result); + break; + case 189 /* PropertyAccessExpression */: + result = reduceNode(node.expression, cbNode, result); + result = reduceNode(node.name, cbNode, result); + break; + case 190 /* ElementAccessExpression */: + result = reduceNode(node.expression, cbNode, result); + result = reduceNode(node.argumentExpression, cbNode, result); + break; + case 191 /* CallExpression */: + result = reduceNode(node.expression, cbNode, result); + result = reduceNodes(node.typeArguments, cbNodes, result); + result = reduceNodes(node.arguments, cbNodes, result); + break; + case 192 /* NewExpression */: + result = reduceNode(node.expression, cbNode, result); + result = reduceNodes(node.typeArguments, cbNodes, result); + result = reduceNodes(node.arguments, cbNodes, result); + break; + case 193 /* TaggedTemplateExpression */: + result = reduceNode(node.tag, cbNode, result); + result = reduceNodes(node.typeArguments, cbNodes, result); + result = reduceNode(node.template, cbNode, result); + break; + case 194 /* TypeAssertionExpression */: + result = reduceNode(node.type, cbNode, result); + result = reduceNode(node.expression, cbNode, result); + break; + case 196 /* FunctionExpression */: + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNodes(node.typeParameters, cbNodes, result); + result = reduceNodes(node.parameters, cbNodes, result); + result = reduceNode(node.type, cbNode, result); + result = reduceNode(node.body, cbNode, result); + break; + case 197 /* ArrowFunction */: + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNodes(node.typeParameters, cbNodes, result); + result = reduceNodes(node.parameters, cbNodes, result); + result = reduceNode(node.type, cbNode, result); + result = reduceNode(node.body, cbNode, result); + break; + case 195 /* ParenthesizedExpression */: + case 198 /* DeleteExpression */: + case 199 /* TypeOfExpression */: + case 200 /* VoidExpression */: + case 201 /* AwaitExpression */: + case 207 /* YieldExpression */: + case 208 /* SpreadElement */: + case 213 /* NonNullExpression */: + result = reduceNode(node.expression, cbNode, result); + break; + case 202 /* PrefixUnaryExpression */: + case 203 /* PostfixUnaryExpression */: + result = reduceNode(node.operand, cbNode, result); + break; + case 204 /* BinaryExpression */: + result = reduceNode(node.left, cbNode, result); + result = reduceNode(node.right, cbNode, result); + break; + case 205 /* ConditionalExpression */: + result = reduceNode(node.condition, cbNode, result); + result = reduceNode(node.whenTrue, cbNode, result); + result = reduceNode(node.whenFalse, cbNode, result); + break; + case 206 /* TemplateExpression */: + result = reduceNode(node.head, cbNode, result); + result = reduceNodes(node.templateSpans, cbNodes, result); + break; + case 209 /* ClassExpression */: + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNodes(node.typeParameters, cbNodes, result); + result = reduceNodes(node.heritageClauses, cbNodes, result); + result = reduceNodes(node.members, cbNodes, result); + break; + case 211 /* ExpressionWithTypeArguments */: + result = reduceNode(node.expression, cbNode, result); + result = reduceNodes(node.typeArguments, cbNodes, result); + break; + case 212 /* AsExpression */: + result = reduceNode(node.expression, cbNode, result); + result = reduceNode(node.type, cbNode, result); + break; + // Misc + case 216 /* TemplateSpan */: + result = reduceNode(node.expression, cbNode, result); + result = reduceNode(node.literal, cbNode, result); + break; + // Element + case 218 /* Block */: + result = reduceNodes(node.statements, cbNodes, result); + break; + case 219 /* VariableStatement */: + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.declarationList, cbNode, result); + break; + case 221 /* ExpressionStatement */: + result = reduceNode(node.expression, cbNode, result); + break; + case 222 /* IfStatement */: + result = reduceNode(node.expression, cbNode, result); + result = reduceNode(node.thenStatement, cbNode, result); + result = reduceNode(node.elseStatement, cbNode, result); + break; + case 223 /* DoStatement */: + result = reduceNode(node.statement, cbNode, result); + result = reduceNode(node.expression, cbNode, result); + break; + case 224 /* WhileStatement */: + case 231 /* WithStatement */: + result = reduceNode(node.expression, cbNode, result); + result = reduceNode(node.statement, cbNode, result); + break; + case 225 /* ForStatement */: + result = reduceNode(node.initializer, cbNode, result); + result = reduceNode(node.condition, cbNode, result); + result = reduceNode(node.incrementor, cbNode, result); + result = reduceNode(node.statement, cbNode, result); + break; + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + result = reduceNode(node.initializer, cbNode, result); + result = reduceNode(node.expression, cbNode, result); + result = reduceNode(node.statement, cbNode, result); + break; + case 230 /* ReturnStatement */: + case 234 /* ThrowStatement */: + result = reduceNode(node.expression, cbNode, result); + break; + case 232 /* SwitchStatement */: + result = reduceNode(node.expression, cbNode, result); + result = reduceNode(node.caseBlock, cbNode, result); + break; + case 233 /* LabeledStatement */: + result = reduceNode(node.label, cbNode, result); + result = reduceNode(node.statement, cbNode, result); + break; + case 235 /* TryStatement */: + result = reduceNode(node.tryBlock, cbNode, result); + result = reduceNode(node.catchClause, cbNode, result); + result = reduceNode(node.finallyBlock, cbNode, result); + break; + case 237 /* VariableDeclaration */: + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.type, cbNode, result); + result = reduceNode(node.initializer, cbNode, result); + break; + case 238 /* VariableDeclarationList */: + result = reduceNodes(node.declarations, cbNodes, result); + break; + case 239 /* FunctionDeclaration */: + result = reduceNodes(node.decorators, cbNodes, result); + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNodes(node.typeParameters, cbNodes, result); + result = reduceNodes(node.parameters, cbNodes, result); + result = reduceNode(node.type, cbNode, result); + result = reduceNode(node.body, cbNode, result); + break; + case 240 /* ClassDeclaration */: + result = reduceNodes(node.decorators, cbNodes, result); + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNodes(node.typeParameters, cbNodes, result); + result = reduceNodes(node.heritageClauses, cbNodes, result); + result = reduceNodes(node.members, cbNodes, result); + break; + case 243 /* EnumDeclaration */: + result = reduceNodes(node.decorators, cbNodes, result); + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNodes(node.members, cbNodes, result); + break; + case 244 /* ModuleDeclaration */: + result = reduceNodes(node.decorators, cbNodes, result); + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.body, cbNode, result); + break; + case 245 /* ModuleBlock */: + result = reduceNodes(node.statements, cbNodes, result); + break; + case 246 /* CaseBlock */: + result = reduceNodes(node.clauses, cbNodes, result); + break; + case 248 /* ImportEqualsDeclaration */: + result = reduceNodes(node.decorators, cbNodes, result); + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.moduleReference, cbNode, result); + break; + case 249 /* ImportDeclaration */: + result = reduceNodes(node.decorators, cbNodes, result); + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.importClause, cbNode, result); + result = reduceNode(node.moduleSpecifier, cbNode, result); + break; + case 250 /* ImportClause */: + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.namedBindings, cbNode, result); + break; + case 251 /* NamespaceImport */: + result = reduceNode(node.name, cbNode, result); + break; + case 252 /* NamedImports */: + case 256 /* NamedExports */: + result = reduceNodes(node.elements, cbNodes, result); + break; + case 253 /* ImportSpecifier */: + case 257 /* ExportSpecifier */: + result = reduceNode(node.propertyName, cbNode, result); + result = reduceNode(node.name, cbNode, result); + break; + case 254 /* ExportAssignment */: + result = ts.reduceLeft(node.decorators, cbNode, result); + result = ts.reduceLeft(node.modifiers, cbNode, result); + result = reduceNode(node.expression, cbNode, result); + break; + case 255 /* ExportDeclaration */: + result = ts.reduceLeft(node.decorators, cbNode, result); + result = ts.reduceLeft(node.modifiers, cbNode, result); + result = reduceNode(node.exportClause, cbNode, result); + result = reduceNode(node.moduleSpecifier, cbNode, result); + break; + // Module references + case 259 /* ExternalModuleReference */: + result = reduceNode(node.expression, cbNode, result); + break; + // JSX + case 260 /* JsxElement */: + result = reduceNode(node.openingElement, cbNode, result); + result = ts.reduceLeft(node.children, cbNode, result); + result = reduceNode(node.closingElement, cbNode, result); + break; + case 264 /* JsxFragment */: + result = reduceNode(node.openingFragment, cbNode, result); + result = ts.reduceLeft(node.children, cbNode, result); + result = reduceNode(node.closingFragment, cbNode, result); + break; + case 261 /* JsxSelfClosingElement */: + case 262 /* JsxOpeningElement */: + result = reduceNode(node.tagName, cbNode, result); + result = reduceNodes(node.typeArguments, cbNode, result); + result = reduceNode(node.attributes, cbNode, result); + break; + case 268 /* JsxAttributes */: + result = reduceNodes(node.properties, cbNodes, result); + break; + case 263 /* JsxClosingElement */: + result = reduceNode(node.tagName, cbNode, result); + break; + case 267 /* JsxAttribute */: + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.initializer, cbNode, result); + break; + case 269 /* JsxSpreadAttribute */: + result = reduceNode(node.expression, cbNode, result); + break; + case 270 /* JsxExpression */: + result = reduceNode(node.expression, cbNode, result); + break; + // Clauses + case 271 /* CaseClause */: + result = reduceNode(node.expression, cbNode, result); + // falls through + case 272 /* DefaultClause */: + result = reduceNodes(node.statements, cbNodes, result); + break; + case 273 /* HeritageClause */: + result = reduceNodes(node.types, cbNodes, result); + break; + case 274 /* CatchClause */: + result = reduceNode(node.variableDeclaration, cbNode, result); + result = reduceNode(node.block, cbNode, result); + break; + // Property assignments + case 275 /* PropertyAssignment */: + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.initializer, cbNode, result); + break; + case 276 /* ShorthandPropertyAssignment */: + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.objectAssignmentInitializer, cbNode, result); + break; + case 277 /* SpreadAssignment */: + result = reduceNode(node.expression, cbNode, result); + break; + // Enum + case 278 /* EnumMember */: + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.initializer, cbNode, result); + break; + // Top-level nodes + case 279 /* SourceFile */: + result = reduceNodes(node.statements, cbNodes, result); + break; + // Transformation nodes + case 308 /* PartiallyEmittedExpression */: + result = reduceNode(node.expression, cbNode, result); + break; + case 309 /* CommaListExpression */: + result = reduceNodes(node.elements, cbNodes, result); + break; + default: + break; + } + return result; + } + ts.reduceEachChild = reduceEachChild; + function mergeLexicalEnvironment(statements, declarations) { + if (!ts.some(declarations)) { + return statements; + } + return ts.isNodeArray(statements) + ? ts.setTextRange(ts.createNodeArray(ts.addStatementsAfterPrologue(statements.slice(), declarations)), statements) + : ts.addStatementsAfterPrologue(statements, declarations); + } + ts.mergeLexicalEnvironment = mergeLexicalEnvironment; + /** + * Lifts a NodeArray containing only Statement nodes to a block. + * + * @param nodes The NodeArray. + */ + function liftToBlock(nodes) { + Debug.assert(ts.every(nodes, ts.isStatement), "Cannot lift nodes to a Block."); + return ts.singleOrUndefined(nodes) || ts.createBlock(nodes); + } + ts.liftToBlock = liftToBlock; + /** + * Aggregates the TransformFlags for a Node and its subtree. + */ + function aggregateTransformFlags(node) { + aggregateTransformFlagsForNode(node); + return node; + } + ts.aggregateTransformFlags = aggregateTransformFlags; + /** + * Aggregates the TransformFlags for a Node and its subtree. The flags for the subtree are + * computed first, then the transform flags for the current node are computed from the subtree + * flags and the state of the current node. Finally, the transform flags of the node are + * returned, excluding any flags that should not be included in its parent node's subtree + * flags. + */ + function aggregateTransformFlagsForNode(node) { + if (node === undefined) { + return 0 /* None */; + } + if (node.transformFlags & 536870912 /* HasComputedFlags */) { + return node.transformFlags & ~ts.getTransformFlagsSubtreeExclusions(node.kind); + } + var subtreeFlags = aggregateTransformFlagsForSubtree(node); + return ts.computeTransformFlagsForNode(node, subtreeFlags); + } + function aggregateTransformFlagsForNodeArray(nodes) { + if (nodes === undefined) { + return 0 /* None */; + } + var subtreeFlags = 0 /* None */; + var nodeArrayFlags = 0 /* None */; + for (var _i = 0, nodes_3 = nodes; _i < nodes_3.length; _i++) { + var node = nodes_3[_i]; + subtreeFlags |= aggregateTransformFlagsForNode(node); + nodeArrayFlags |= node.transformFlags & ~536870912 /* HasComputedFlags */; + } + nodes.transformFlags = nodeArrayFlags | 536870912 /* HasComputedFlags */; + return subtreeFlags; + } + /** + * Aggregates the transform flags for the subtree of a node. + */ + function aggregateTransformFlagsForSubtree(node) { + // We do not transform ambient declarations or types, so there is no need to + // recursively aggregate transform flags. + if (ts.hasModifier(node, 2 /* Ambient */) || (ts.isTypeNode(node) && node.kind !== 211 /* ExpressionWithTypeArguments */)) { + return 0 /* None */; + } + // Aggregate the transform flags of each child. + return reduceEachChild(node, 0 /* None */, aggregateTransformFlagsForChildNode, aggregateTransformFlagsForChildNodes); + } + /** + * Aggregates the TransformFlags of a child node with the TransformFlags of its + * siblings. + */ + function aggregateTransformFlagsForChildNode(transformFlags, node) { + return transformFlags | aggregateTransformFlagsForNode(node); + } + function aggregateTransformFlagsForChildNodes(transformFlags, nodes) { + return transformFlags | aggregateTransformFlagsForNodeArray(nodes); + } + var Debug; + (function (Debug) { + var isDebugInfoEnabled = false; + function failBadSyntaxKind(node, message) { + return Debug.fail((message || "Unexpected node.") + "\r\nNode " + ts.formatSyntaxKind(node.kind) + " was unexpected.", failBadSyntaxKind); + } + Debug.failBadSyntaxKind = failBadSyntaxKind; + Debug.assertEachNode = Debug.shouldAssert(1 /* Normal */) + ? function (nodes, test, message) { return Debug.assert(test === undefined || ts.every(nodes, test), message || "Unexpected node.", function () { return "Node array did not pass test '" + Debug.getFunctionName(test) + "'."; }, Debug.assertEachNode); } + : ts.noop; + Debug.assertNode = Debug.shouldAssert(1 /* Normal */) + ? function (node, test, message) { return Debug.assert(test === undefined || test(node), message || "Unexpected node.", function () { return "Node " + ts.formatSyntaxKind(node.kind) + " did not pass test '" + Debug.getFunctionName(test) + "'."; }, Debug.assertNode); } + : ts.noop; + Debug.assertOptionalNode = Debug.shouldAssert(1 /* Normal */) + ? function (node, test, message) { return Debug.assert(test === undefined || node === undefined || test(node), message || "Unexpected node.", function () { return "Node " + ts.formatSyntaxKind(node.kind) + " did not pass test '" + Debug.getFunctionName(test) + "'."; }, Debug.assertOptionalNode); } + : ts.noop; + Debug.assertOptionalToken = Debug.shouldAssert(1 /* Normal */) + ? function (node, kind, message) { return Debug.assert(kind === undefined || node === undefined || node.kind === kind, message || "Unexpected node.", function () { return "Node " + ts.formatSyntaxKind(node.kind) + " was not a '" + ts.formatSyntaxKind(kind) + "' token."; }, Debug.assertOptionalToken); } + : ts.noop; + Debug.assertMissingNode = Debug.shouldAssert(1 /* Normal */) + ? function (node, message) { return Debug.assert(node === undefined, message || "Unexpected node.", function () { return "Node " + ts.formatSyntaxKind(node.kind) + " was unexpected'."; }, Debug.assertMissingNode); } + : ts.noop; + /** + * Injects debug information into frequently used types. + */ + function enableDebugInfo() { + if (isDebugInfoEnabled) + return; + // Add additional properties in debug mode to assist with debugging. + Object.defineProperties(ts.objectAllocator.getSymbolConstructor().prototype, { + __debugFlags: { get: function () { return ts.formatSymbolFlags(this.flags); } } + }); + Object.defineProperties(ts.objectAllocator.getTypeConstructor().prototype, { + __debugFlags: { get: function () { return ts.formatTypeFlags(this.flags); } }, + __debugObjectFlags: { get: function () { return this.flags & 524288 /* Object */ ? ts.formatObjectFlags(this.objectFlags) : ""; } }, + __debugTypeToString: { value: function () { return this.checker.typeToString(this); } }, + }); + var nodeConstructors = [ + ts.objectAllocator.getNodeConstructor(), + ts.objectAllocator.getIdentifierConstructor(), + ts.objectAllocator.getTokenConstructor(), + ts.objectAllocator.getSourceFileConstructor() + ]; + for (var _i = 0, nodeConstructors_1 = nodeConstructors; _i < nodeConstructors_1.length; _i++) { + var ctor = nodeConstructors_1[_i]; + if (!ctor.prototype.hasOwnProperty("__debugKind")) { + Object.defineProperties(ctor.prototype, { + __debugKind: { get: function () { return ts.formatSyntaxKind(this.kind); } }, + __debugModifierFlags: { get: function () { return ts.formatModifierFlags(ts.getModifierFlagsNoCache(this)); } }, + __debugTransformFlags: { get: function () { return ts.formatTransformFlags(this.transformFlags); } }, + __debugEmitFlags: { get: function () { return ts.formatEmitFlags(ts.getEmitFlags(this)); } }, + __debugGetText: { + value: function (includeTrivia) { + if (ts.nodeIsSynthesized(this)) + return ""; + var parseNode = ts.getParseTreeNode(this); + var sourceFile = parseNode && ts.getSourceFileOfNode(parseNode); + return sourceFile ? ts.getSourceTextOfNodeFromSourceFile(sourceFile, parseNode, includeTrivia) : ""; + } + } + }); + } + } + isDebugInfoEnabled = true; + } + Debug.enableDebugInfo = enableDebugInfo; + })(Debug = ts.Debug || (ts.Debug = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + function createSourceMapGenerator(host, file, sourceRoot, sourcesDirectoryPath, generatorOptions) { + var _a = generatorOptions.extendedDiagnostics + ? ts.performance.createTimer("Source Map", "beforeSourcemap", "afterSourcemap") + : ts.performance.nullTimer, enter = _a.enter, exit = _a.exit; + // Current source map file and its index in the sources list + var rawSources = []; + var sources = []; + var sourceToSourceIndexMap = ts.createMap(); + var sourcesContent; + var names = []; + var nameToNameIndexMap; + var mappings = ""; + // Last recorded and encoded mappings + var lastGeneratedLine = 0; + var lastGeneratedCharacter = 0; + var lastSourceIndex = 0; + var lastSourceLine = 0; + var lastSourceCharacter = 0; + var lastNameIndex = 0; + var hasLast = false; + var pendingGeneratedLine = 0; + var pendingGeneratedCharacter = 0; + var pendingSourceIndex = 0; + var pendingSourceLine = 0; + var pendingSourceCharacter = 0; + var pendingNameIndex = 0; + var hasPending = false; + var hasPendingSource = false; + var hasPendingName = false; + return { + getSources: function () { return rawSources; }, + addSource: addSource, + setSourceContent: setSourceContent, + addName: addName, + addMapping: addMapping, + appendSourceMap: appendSourceMap, + toJSON: toJSON, + toString: function () { return JSON.stringify(toJSON()); } + }; + function addSource(fileName) { + enter(); + var source = ts.getRelativePathToDirectoryOrUrl(sourcesDirectoryPath, fileName, host.getCurrentDirectory(), host.getCanonicalFileName, + /*isAbsolutePathAnUrl*/ true); + var sourceIndex = sourceToSourceIndexMap.get(source); + if (sourceIndex === undefined) { + sourceIndex = sources.length; + sources.push(source); + rawSources.push(fileName); + sourceToSourceIndexMap.set(source, sourceIndex); + } + exit(); + return sourceIndex; + } + function setSourceContent(sourceIndex, content) { + enter(); + if (content !== null) { + if (!sourcesContent) + sourcesContent = []; + while (sourcesContent.length < sourceIndex) { + // tslint:disable-next-line:no-null-keyword boolean-trivia + sourcesContent.push(null); + } + sourcesContent[sourceIndex] = content; + } + exit(); + } + function addName(name) { + enter(); + if (!nameToNameIndexMap) + nameToNameIndexMap = ts.createMap(); + var nameIndex = nameToNameIndexMap.get(name); + if (nameIndex === undefined) { + nameIndex = names.length; + names.push(name); + nameToNameIndexMap.set(name, nameIndex); + } + exit(); + return nameIndex; + } + function isNewGeneratedPosition(generatedLine, generatedCharacter) { + return !hasPending + || pendingGeneratedLine !== generatedLine + || pendingGeneratedCharacter !== generatedCharacter; + } + function isBacktrackingSourcePosition(sourceIndex, sourceLine, sourceCharacter) { + return sourceIndex !== undefined + && sourceLine !== undefined + && sourceCharacter !== undefined + && pendingSourceIndex === sourceIndex + && (pendingSourceLine > sourceLine + || pendingSourceLine === sourceLine && pendingSourceCharacter > sourceCharacter); + } + function addMapping(generatedLine, generatedCharacter, sourceIndex, sourceLine, sourceCharacter, nameIndex) { + ts.Debug.assert(generatedLine >= pendingGeneratedLine, "generatedLine cannot backtrack"); + ts.Debug.assert(generatedCharacter >= 0, "generatedCharacter cannot be negative"); + ts.Debug.assert(sourceIndex === undefined || sourceIndex >= 0, "sourceIndex cannot be negative"); + ts.Debug.assert(sourceLine === undefined || sourceLine >= 0, "sourceLine cannot be negative"); + ts.Debug.assert(sourceCharacter === undefined || sourceCharacter >= 0, "sourceCharacter cannot be negative"); + enter(); + // If this location wasn't recorded or the location in source is going backwards, record the mapping + if (isNewGeneratedPosition(generatedLine, generatedCharacter) || + isBacktrackingSourcePosition(sourceIndex, sourceLine, sourceCharacter)) { + commitPendingMapping(); + pendingGeneratedLine = generatedLine; + pendingGeneratedCharacter = generatedCharacter; + hasPendingSource = false; + hasPendingName = false; + hasPending = true; + } + if (sourceIndex !== undefined && sourceLine !== undefined && sourceCharacter !== undefined) { + pendingSourceIndex = sourceIndex; + pendingSourceLine = sourceLine; + pendingSourceCharacter = sourceCharacter; + hasPendingSource = true; + if (nameIndex !== undefined) { + pendingNameIndex = nameIndex; + hasPendingName = true; + } + } + exit(); + } + function appendSourceMap(generatedLine, generatedCharacter, map, sourceMapPath) { + var _a; + ts.Debug.assert(generatedLine >= pendingGeneratedLine, "generatedLine cannot backtrack"); + ts.Debug.assert(generatedCharacter >= 0, "generatedCharacter cannot be negative"); + enter(); + // First, decode the old component sourcemap + var sourceIndexToNewSourceIndexMap = []; + var nameIndexToNewNameIndexMap; + var mappingIterator = decodeMappings(map.mappings); + for (var _b = mappingIterator.next(), raw = _b.value, done = _b.done; !done; _a = mappingIterator.next(), raw = _a.value, done = _a.done, _a) { + // Then reencode all the updated mappings into the overall map + var newSourceIndex = void 0; + var newSourceLine = void 0; + var newSourceCharacter = void 0; + var newNameIndex = void 0; + if (raw.sourceIndex !== undefined) { + newSourceIndex = sourceIndexToNewSourceIndexMap[raw.sourceIndex]; + if (newSourceIndex === undefined) { + // Apply offsets to each position and fixup source entries + var rawPath = map.sources[raw.sourceIndex]; + var relativePath = map.sourceRoot ? ts.combinePaths(map.sourceRoot, rawPath) : rawPath; + var combinedPath = ts.combinePaths(ts.getDirectoryPath(sourceMapPath), relativePath); + sourceIndexToNewSourceIndexMap[raw.sourceIndex] = newSourceIndex = addSource(combinedPath); + if (map.sourcesContent && typeof map.sourcesContent[raw.sourceIndex] === "string") { + setSourceContent(newSourceIndex, map.sourcesContent[raw.sourceIndex]); + } + } + newSourceLine = raw.sourceLine; + newSourceCharacter = raw.sourceCharacter; + if (map.names && raw.nameIndex !== undefined) { + if (!nameIndexToNewNameIndexMap) + nameIndexToNewNameIndexMap = []; + newNameIndex = nameIndexToNewNameIndexMap[raw.nameIndex]; + if (newNameIndex === undefined) { + nameIndexToNewNameIndexMap[raw.nameIndex] = newNameIndex = addName(map.names[raw.nameIndex]); + } + } + } + var newGeneratedLine = raw.generatedLine + generatedLine; + var newGeneratedCharacter = raw.generatedLine === 0 ? raw.generatedCharacter + generatedCharacter : raw.generatedCharacter; + addMapping(newGeneratedLine, newGeneratedCharacter, newSourceIndex, newSourceLine, newSourceCharacter, newNameIndex); + } + exit(); + } + function shouldCommitMapping() { + return !hasLast + || lastGeneratedLine !== pendingGeneratedLine + || lastGeneratedCharacter !== pendingGeneratedCharacter + || lastSourceIndex !== pendingSourceIndex + || lastSourceLine !== pendingSourceLine + || lastSourceCharacter !== pendingSourceCharacter + || lastNameIndex !== pendingNameIndex; + } + function commitPendingMapping() { + if (!hasPending || !shouldCommitMapping()) { + return; + } + enter(); + // Line/Comma delimiters + if (lastGeneratedLine < pendingGeneratedLine) { + // Emit line delimiters + do { + mappings += ";"; + lastGeneratedLine++; + lastGeneratedCharacter = 0; + } while (lastGeneratedLine < pendingGeneratedLine); + } + else { + ts.Debug.assertEqual(lastGeneratedLine, pendingGeneratedLine, "generatedLine cannot backtrack"); + // Emit comma to separate the entry + if (hasLast) { + mappings += ","; + } + } + // 1. Relative generated character + mappings += base64VLQFormatEncode(pendingGeneratedCharacter - lastGeneratedCharacter); + lastGeneratedCharacter = pendingGeneratedCharacter; + if (hasPendingSource) { + // 2. Relative sourceIndex + mappings += base64VLQFormatEncode(pendingSourceIndex - lastSourceIndex); + lastSourceIndex = pendingSourceIndex; + // 3. Relative source line + mappings += base64VLQFormatEncode(pendingSourceLine - lastSourceLine); + lastSourceLine = pendingSourceLine; + // 4. Relative source character + mappings += base64VLQFormatEncode(pendingSourceCharacter - lastSourceCharacter); + lastSourceCharacter = pendingSourceCharacter; + if (hasPendingName) { + // 5. Relative nameIndex + mappings += base64VLQFormatEncode(pendingNameIndex - lastNameIndex); + lastNameIndex = pendingNameIndex; + } + } + hasLast = true; + exit(); + } + function toJSON() { + commitPendingMapping(); + return { + version: 3, + file: file, + sourceRoot: sourceRoot, + sources: sources, + names: names, + mappings: mappings, + sourcesContent: sourcesContent, + }; + } + } + ts.createSourceMapGenerator = createSourceMapGenerator; + // Sometimes tools can see the following line as a source mapping url comment, so we mangle it a bit (the [M]) + var sourceMapCommentRegExp = /^\/\/[@#] source[M]appingURL=(.+)\s*$/; + var whitespaceOrMapCommentRegExp = /^\s*(\/\/[@#] .*)?$/; + /** + * Tries to find the sourceMappingURL comment at the end of a file. + * @param text The source text of the file. + * @param lineStarts The line starts of the file. + */ + function tryGetSourceMappingURL(text, lineStarts) { + if (lineStarts === void 0) { lineStarts = ts.computeLineStarts(text); } + for (var index = lineStarts.length - 1; index >= 0; index--) { + var line = text.substring(lineStarts[index], lineStarts[index + 1]); + var comment = sourceMapCommentRegExp.exec(line); + if (comment) { + return comment[1]; + } + // If we see a non-whitespace/map comment-like line, break, to avoid scanning up the entire file + else if (!line.match(whitespaceOrMapCommentRegExp)) { + break; + } + } + } + ts.tryGetSourceMappingURL = tryGetSourceMappingURL; + function isStringOrNull(x) { + // tslint:disable-next-line:no-null-keyword + return typeof x === "string" || x === null; + } + function isRawSourceMap(x) { + // tslint:disable-next-line:no-null-keyword + return x !== null + && typeof x === "object" + && x.version === 3 + && typeof x.file === "string" + && typeof x.mappings === "string" + && ts.isArray(x.sources) && ts.every(x.sources, ts.isString) + && (x.sourceRoot === undefined || x.sourceRoot === null || typeof x.sourceRoot === "string") + && (x.sourcesContent === undefined || x.sourcesContent === null || ts.isArray(x.sourcesContent) && ts.every(x.sourcesContent, isStringOrNull)) + && (x.names === undefined || x.names === null || ts.isArray(x.names) && ts.every(x.names, ts.isString)); + } + ts.isRawSourceMap = isRawSourceMap; + function tryParseRawSourceMap(text) { + try { + var parsed = JSON.parse(text); + if (isRawSourceMap(parsed)) { + return parsed; + } + } + catch (_a) { + // empty + } + return undefined; + } + ts.tryParseRawSourceMap = tryParseRawSourceMap; + function decodeMappings(mappings) { + var done = false; + var pos = 0; + var generatedLine = 0; + var generatedCharacter = 0; + var sourceIndex = 0; + var sourceLine = 0; + var sourceCharacter = 0; + var nameIndex = 0; + var error; + return { + get pos() { return pos; }, + get error() { return error; }, + get state() { return captureMapping(/*hasSource*/ true, /*hasName*/ true); }, + next: function () { + while (!done && pos < mappings.length) { + var ch = mappings.charCodeAt(pos); + if (ch === 59 /* semicolon */) { + // new line + generatedLine++; + generatedCharacter = 0; + pos++; + continue; + } + if (ch === 44 /* comma */) { + // Next entry is on same line - no action needed + pos++; + continue; + } + var hasSource = false; + var hasName = false; + generatedCharacter += base64VLQFormatDecode(); + if (hasReportedError()) + return stopIterating(); + if (generatedCharacter < 0) + return setErrorAndStopIterating("Invalid generatedCharacter found"); + if (!isSourceMappingSegmentEnd()) { + hasSource = true; + sourceIndex += base64VLQFormatDecode(); + if (hasReportedError()) + return stopIterating(); + if (sourceIndex < 0) + return setErrorAndStopIterating("Invalid sourceIndex found"); + if (isSourceMappingSegmentEnd()) + return setErrorAndStopIterating("Unsupported Format: No entries after sourceIndex"); + sourceLine += base64VLQFormatDecode(); + if (hasReportedError()) + return stopIterating(); + if (sourceLine < 0) + return setErrorAndStopIterating("Invalid sourceLine found"); + if (isSourceMappingSegmentEnd()) + return setErrorAndStopIterating("Unsupported Format: No entries after sourceLine"); + sourceCharacter += base64VLQFormatDecode(); + if (hasReportedError()) + return stopIterating(); + if (sourceCharacter < 0) + return setErrorAndStopIterating("Invalid sourceCharacter found"); + if (!isSourceMappingSegmentEnd()) { + hasName = true; + nameIndex += base64VLQFormatDecode(); + if (hasReportedError()) + return stopIterating(); + if (nameIndex < 0) + return setErrorAndStopIterating("Invalid nameIndex found"); + if (!isSourceMappingSegmentEnd()) + return setErrorAndStopIterating("Unsupported Error Format: Entries after nameIndex"); + } + } + return { value: captureMapping(hasSource, hasName), done: done }; + } + return stopIterating(); + } + }; + function captureMapping(hasSource, hasName) { + return { + generatedLine: generatedLine, + generatedCharacter: generatedCharacter, + sourceIndex: hasSource ? sourceIndex : undefined, + sourceLine: hasSource ? sourceLine : undefined, + sourceCharacter: hasSource ? sourceCharacter : undefined, + nameIndex: hasName ? nameIndex : undefined + }; + } + function stopIterating() { + done = true; + return { value: undefined, done: true }; + } + function setError(message) { + if (error === undefined) { + error = message; + } + } + function setErrorAndStopIterating(message) { + setError(message); + return stopIterating(); + } + function hasReportedError() { + return error !== undefined; + } + function isSourceMappingSegmentEnd() { + return (pos === mappings.length || + mappings.charCodeAt(pos) === 44 /* comma */ || + mappings.charCodeAt(pos) === 59 /* semicolon */); + } + function base64VLQFormatDecode() { + var moreDigits = true; + var shiftCount = 0; + var value = 0; + for (; moreDigits; pos++) { + if (pos >= mappings.length) + return setError("Error in decoding base64VLQFormatDecode, past the mapping string"), -1; + // 6 digit number + var currentByte = base64FormatDecode(mappings.charCodeAt(pos)); + if (currentByte === -1) + return setError("Invalid character in VLQ"), -1; + // If msb is set, we still have more bits to continue + moreDigits = (currentByte & 32) !== 0; + // least significant 5 bits are the next msbs in the final value. + value = value | ((currentByte & 31) << shiftCount); + shiftCount += 5; + } + // Least significant bit if 1 represents negative and rest of the msb is actual absolute value + if ((value & 1) === 0) { + // + number + value = value >> 1; + } + else { + // - number + value = value >> 1; + value = -value; + } + return value; + } + } + ts.decodeMappings = decodeMappings; + function sameMapping(left, right) { + return left === right + || left.generatedLine === right.generatedLine + && left.generatedCharacter === right.generatedCharacter + && left.sourceIndex === right.sourceIndex + && left.sourceLine === right.sourceLine + && left.sourceCharacter === right.sourceCharacter + && left.nameIndex === right.nameIndex; + } + ts.sameMapping = sameMapping; + function isSourceMapping(mapping) { + return mapping.sourceIndex !== undefined + && mapping.sourceLine !== undefined + && mapping.sourceCharacter !== undefined; + } + ts.isSourceMapping = isSourceMapping; + function base64FormatEncode(value) { + return value >= 0 && value < 26 ? 65 /* A */ + value : + value >= 26 && value < 52 ? 97 /* a */ + value - 26 : + value >= 52 && value < 62 ? 48 /* _0 */ + value - 52 : + value === 62 ? 43 /* plus */ : + value === 63 ? 47 /* slash */ : + ts.Debug.fail(value + ": not a base64 value"); + } + function base64FormatDecode(ch) { + return ch >= 65 /* A */ && ch <= 90 /* Z */ ? ch - 65 /* A */ : + ch >= 97 /* a */ && ch <= 122 /* z */ ? ch - 97 /* a */ + 26 : + ch >= 48 /* _0 */ && ch <= 57 /* _9 */ ? ch - 48 /* _0 */ + 52 : + ch === 43 /* plus */ ? 62 : + ch === 47 /* slash */ ? 63 : + -1; + } + function base64VLQFormatEncode(inValue) { + // Add a new least significant bit that has the sign of the value. + // if negative number the least significant bit that gets added to the number has value 1 + // else least significant bit value that gets added is 0 + // eg. -1 changes to binary : 01 [1] => 3 + // +1 changes to binary : 01 [0] => 2 + if (inValue < 0) { + inValue = ((-inValue) << 1) + 1; + } + else { + inValue = inValue << 1; + } + // Encode 5 bits at a time starting from least significant bits + var encodedStr = ""; + do { + var currentDigit = inValue & 31; // 11111 + inValue = inValue >> 5; + if (inValue > 0) { + // There are still more digits to decode, set the msb (6th bit) + currentDigit = currentDigit | 32; + } + encodedStr = encodedStr + String.fromCharCode(base64FormatEncode(currentDigit)); + } while (inValue > 0); + return encodedStr; + } + function isSourceMappedPosition(value) { + return value.sourceIndex !== undefined + && value.sourcePosition !== undefined; + } + function sameMappedPosition(left, right) { + return left.generatedPosition === right.generatedPosition + && left.sourceIndex === right.sourceIndex + && left.sourcePosition === right.sourcePosition; + } + function compareSourcePositions(left, right) { + return ts.compareValues(left.sourceIndex, right.sourceIndex); + } + function compareGeneratedPositions(left, right) { + return ts.compareValues(left.generatedPosition, right.generatedPosition); + } + function getSourcePositionOfMapping(value) { + return value.sourcePosition; + } + function getGeneratedPositionOfMapping(value) { + return value.generatedPosition; + } + function createDocumentPositionMapper(host, map, mapPath) { + var mapDirectory = ts.getDirectoryPath(mapPath); + var sourceRoot = map.sourceRoot ? ts.getNormalizedAbsolutePath(map.sourceRoot, mapDirectory) : mapDirectory; + var generatedAbsoluteFilePath = ts.getNormalizedAbsolutePath(map.file, mapDirectory); + var generatedCanonicalFilePath = host.getCanonicalFileName(generatedAbsoluteFilePath); + var generatedFile = host.getSourceFileLike(generatedCanonicalFilePath); + var sourceFileAbsolutePaths = map.sources.map(function (source) { return ts.getNormalizedAbsolutePath(source, sourceRoot); }); + var sourceFileCanonicalPaths = sourceFileAbsolutePaths.map(function (source) { return host.getCanonicalFileName(source); }); + var sourceToSourceIndexMap = ts.createMapFromEntries(sourceFileCanonicalPaths.map(function (source, i) { return [source, i]; })); + var decodedMappings; + var generatedMappings; + var sourceMappings; + return { + getSourcePosition: getSourcePosition, + getGeneratedPosition: getGeneratedPosition + }; + function processMapping(mapping) { + var generatedPosition = generatedFile !== undefined + ? ts.getPositionOfLineAndCharacterWithEdits(generatedFile, mapping.generatedLine, mapping.generatedCharacter) + : -1; + var source; + var sourcePosition; + if (isSourceMapping(mapping)) { + var sourceFilePath = sourceFileCanonicalPaths[mapping.sourceIndex]; + var sourceFile = host.getSourceFileLike(sourceFilePath); + source = map.sources[mapping.sourceIndex]; + sourcePosition = sourceFile !== undefined + ? ts.getPositionOfLineAndCharacterWithEdits(sourceFile, mapping.sourceLine, mapping.sourceCharacter) + : -1; + } + return { + generatedPosition: generatedPosition, + source: source, + sourceIndex: mapping.sourceIndex, + sourcePosition: sourcePosition, + nameIndex: mapping.nameIndex + }; + } + function getDecodedMappings() { + if (decodedMappings === undefined) { + var decoder = decodeMappings(map.mappings); + var mappings = ts.arrayFrom(decoder, processMapping); + if (decoder.error !== undefined) { + if (host.log) { + host.log("Encountered error while decoding sourcemap: " + decoder.error); + } + decodedMappings = ts.emptyArray; + } + else { + decodedMappings = mappings; + } + } + return decodedMappings; + } + function getSourceMappings(sourceIndex) { + if (sourceMappings === undefined) { + var lists = []; + for (var _i = 0, _a = getDecodedMappings(); _i < _a.length; _i++) { + var mapping = _a[_i]; + if (!isSourceMappedPosition(mapping)) + continue; + var list = lists[mapping.sourceIndex]; + if (!list) + lists[mapping.sourceIndex] = list = []; + list.push(mapping); + } + sourceMappings = lists.map(function (list) { return ts.sortAndDeduplicate(list, compareSourcePositions, sameMappedPosition); }); + } + return sourceMappings[sourceIndex]; + } + function getGeneratedMappings() { + if (generatedMappings === undefined) { + var list = []; + for (var _i = 0, _a = getDecodedMappings(); _i < _a.length; _i++) { + var mapping = _a[_i]; + list.push(mapping); + } + generatedMappings = ts.sortAndDeduplicate(list, compareGeneratedPositions, sameMappedPosition); + } + return generatedMappings; + } + function getGeneratedPosition(loc) { + var sourceIndex = sourceToSourceIndexMap.get(host.getCanonicalFileName(loc.fileName)); + if (sourceIndex === undefined) + return loc; + var sourceMappings = getSourceMappings(sourceIndex); + if (!ts.some(sourceMappings)) + return loc; + var targetIndex = ts.binarySearchKey(sourceMappings, loc.pos, getSourcePositionOfMapping, ts.compareValues); + if (targetIndex < 0) { + // if no exact match, closest is 2's complement of result + targetIndex = ~targetIndex; + } + var mapping = sourceMappings[targetIndex]; + if (mapping === undefined || mapping.sourceIndex !== sourceIndex) { + return loc; + } + return { fileName: generatedAbsoluteFilePath, pos: mapping.generatedPosition }; // Closest pos + } + function getSourcePosition(loc) { + var generatedMappings = getGeneratedMappings(); + if (!ts.some(generatedMappings)) + return loc; + var targetIndex = ts.binarySearchKey(generatedMappings, loc.pos, getGeneratedPositionOfMapping, ts.compareValues); + if (targetIndex < 0) { + // if no exact match, closest is 2's complement of result + targetIndex = ~targetIndex; + } + var mapping = generatedMappings[targetIndex]; + if (mapping === undefined || !isSourceMappedPosition(mapping)) { + return loc; + } + return { fileName: sourceFileAbsolutePaths[mapping.sourceIndex], pos: mapping.sourcePosition }; // Closest pos + } + } + ts.createDocumentPositionMapper = createDocumentPositionMapper; + ts.identitySourceMapConsumer = { + getSourcePosition: ts.identity, + getGeneratedPosition: ts.identity + }; +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + function getOriginalNodeId(node) { + node = ts.getOriginalNode(node); + return node ? ts.getNodeId(node) : 0; + } + ts.getOriginalNodeId = getOriginalNodeId; + function containsDefaultReference(node) { + if (!node) + return false; + if (!ts.isNamedImports(node)) + return false; + return ts.some(node.elements, isNamedDefaultReference); + } + function isNamedDefaultReference(e) { + return e.propertyName !== undefined && e.propertyName.escapedText === "default" /* Default */; + } + function chainBundle(transformSourceFile) { + return transformSourceFileOrBundle; + function transformSourceFileOrBundle(node) { + return node.kind === 279 /* SourceFile */ ? transformSourceFile(node) : transformBundle(node); + } + function transformBundle(node) { + return ts.createBundle(ts.map(node.sourceFiles, transformSourceFile), node.prepends); + } + } + ts.chainBundle = chainBundle; + function getImportNeedsImportStarHelper(node) { + if (!!ts.getNamespaceDeclarationNode(node)) { + return true; + } + var bindings = node.importClause && node.importClause.namedBindings; + if (!bindings) { + return false; + } + if (!ts.isNamedImports(bindings)) + return false; + var defaultRefCount = 0; + for (var _i = 0, _a = bindings.elements; _i < _a.length; _i++) { + var binding = _a[_i]; + if (isNamedDefaultReference(binding)) { + defaultRefCount++; + } + } + // Import star is required if there's default named refs mixed with non-default refs, or if theres non-default refs and it has a default import + return (defaultRefCount > 0 && defaultRefCount !== bindings.elements.length) || (!!(bindings.elements.length - defaultRefCount) && ts.isDefaultImport(node)); + } + ts.getImportNeedsImportStarHelper = getImportNeedsImportStarHelper; + function getImportNeedsImportDefaultHelper(node) { + // Import default is needed if there's a default import or a default ref and no other refs (meaning an import star helper wasn't requested) + return !getImportNeedsImportStarHelper(node) && (ts.isDefaultImport(node) || (!!node.importClause && ts.isNamedImports(node.importClause.namedBindings) && containsDefaultReference(node.importClause.namedBindings))); // TODO: GH#18217 + } + ts.getImportNeedsImportDefaultHelper = getImportNeedsImportDefaultHelper; + function collectExternalModuleInfo(sourceFile, resolver, compilerOptions) { + var externalImports = []; + var exportSpecifiers = ts.createMultiMap(); + var exportedBindings = []; + var uniqueExports = ts.createMap(); + var exportedNames; + var hasExportDefault = false; + var exportEquals; + var hasExportStarsToExportValues = false; + var hasImportStarOrImportDefault = false; + for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { + var node = _a[_i]; + switch (node.kind) { + case 249 /* ImportDeclaration */: + // import "mod" + // import x from "mod" + // import * as x from "mod" + // import { x, y } from "mod" + externalImports.push(node); + hasImportStarOrImportDefault = hasImportStarOrImportDefault || getImportNeedsImportStarHelper(node) || getImportNeedsImportDefaultHelper(node); + break; + case 248 /* ImportEqualsDeclaration */: + if (node.moduleReference.kind === 259 /* ExternalModuleReference */) { + // import x = require("mod") + externalImports.push(node); + } + break; + case 255 /* ExportDeclaration */: + if (node.moduleSpecifier) { + if (!node.exportClause) { + // export * from "mod" + externalImports.push(node); + hasExportStarsToExportValues = true; + } + else { + // export { x, y } from "mod" + externalImports.push(node); + } + } + else { + // export { x, y } + for (var _b = 0, _c = node.exportClause.elements; _b < _c.length; _b++) { + var specifier = _c[_b]; + if (!uniqueExports.get(ts.idText(specifier.name))) { + var name = specifier.propertyName || specifier.name; + exportSpecifiers.add(ts.idText(name), specifier); + var decl = resolver.getReferencedImportDeclaration(name) + || resolver.getReferencedValueDeclaration(name); + if (decl) { + multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(decl), specifier.name); + } + uniqueExports.set(ts.idText(specifier.name), true); + exportedNames = ts.append(exportedNames, specifier.name); + } + } + } + break; + case 254 /* ExportAssignment */: + if (node.isExportEquals && !exportEquals) { + // export = x + exportEquals = node; + } + break; + case 219 /* VariableStatement */: + if (ts.hasModifier(node, 1 /* Export */)) { + for (var _d = 0, _e = node.declarationList.declarations; _d < _e.length; _d++) { + var decl = _e[_d]; + exportedNames = collectExportedVariableInfo(decl, uniqueExports, exportedNames); + } + } + break; + case 239 /* FunctionDeclaration */: + if (ts.hasModifier(node, 1 /* Export */)) { + if (ts.hasModifier(node, 512 /* Default */)) { + // export default function() { } + if (!hasExportDefault) { + multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), ts.getDeclarationName(node)); + hasExportDefault = true; + } + } + else { + // export function x() { } + var name = node.name; + if (!uniqueExports.get(ts.idText(name))) { + multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), name); + uniqueExports.set(ts.idText(name), true); + exportedNames = ts.append(exportedNames, name); + } + } + } + break; + case 240 /* ClassDeclaration */: + if (ts.hasModifier(node, 1 /* Export */)) { + if (ts.hasModifier(node, 512 /* Default */)) { + // export default class { } + if (!hasExportDefault) { + multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), ts.getDeclarationName(node)); + hasExportDefault = true; + } + } + else { + // export class x { } + var name = node.name; + if (name && !uniqueExports.get(ts.idText(name))) { + multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), name); + uniqueExports.set(ts.idText(name), true); + exportedNames = ts.append(exportedNames, name); + } + } + } + break; + } + } + var externalHelpersModuleName = ts.getOrCreateExternalHelpersModuleNameIfNeeded(sourceFile, compilerOptions, hasExportStarsToExportValues, hasImportStarOrImportDefault); + var externalHelpersImportDeclaration = externalHelpersModuleName && ts.createImportDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(externalHelpersModuleName)), ts.createLiteral(ts.externalHelpersModuleNameText)); + if (externalHelpersImportDeclaration) { + ts.addEmitFlags(externalHelpersImportDeclaration, 67108864 /* NeverApplyImportHelper */); + externalImports.unshift(externalHelpersImportDeclaration); + } + return { externalImports: externalImports, exportSpecifiers: exportSpecifiers, exportEquals: exportEquals, hasExportStarsToExportValues: hasExportStarsToExportValues, exportedBindings: exportedBindings, exportedNames: exportedNames, externalHelpersImportDeclaration: externalHelpersImportDeclaration }; + } + ts.collectExternalModuleInfo = collectExternalModuleInfo; + function collectExportedVariableInfo(decl, uniqueExports, exportedNames) { + if (ts.isBindingPattern(decl.name)) { + for (var _i = 0, _a = decl.name.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (!ts.isOmittedExpression(element)) { + exportedNames = collectExportedVariableInfo(element, uniqueExports, exportedNames); + } + } + } + else if (!ts.isGeneratedIdentifier(decl.name)) { + var text = ts.idText(decl.name); + if (!uniqueExports.get(text)) { + uniqueExports.set(text, true); + exportedNames = ts.append(exportedNames, decl.name); + } + } + return exportedNames; + } + /** Use a sparse array as a multi-map. */ + function multiMapSparseArrayAdd(map, key, value) { + var values = map[key]; + if (values) { + values.push(value); + } + else { + map[key] = values = [value]; + } + return values; + } + /** + * Used in the module transformer to check if an expression is reasonably without sideeffect, + * and thus better to copy into multiple places rather than to cache in a temporary variable + * - this is mostly subjective beyond the requirement that the expression not be sideeffecting + */ + function isSimpleCopiableExpression(expression) { + return ts.isStringLiteralLike(expression) || + expression.kind === 8 /* NumericLiteral */ || + ts.isKeyword(expression.kind) || + ts.isIdentifier(expression); + } + ts.isSimpleCopiableExpression = isSimpleCopiableExpression; + /** + * @param input Template string input strings + * @param args Names which need to be made file-level unique + */ + function helperString(input) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + return function (uniqueName) { + var result = ""; + for (var i = 0; i < args.length; i++) { + result += input[i]; + result += uniqueName(args[i]); + } + result += input[input.length - 1]; + return result; + }; + } + ts.helperString = helperString; +})(ts || (ts = {})); +/*@internal*/ +var ts; +(function (ts) { + var FlattenLevel; + (function (FlattenLevel) { + FlattenLevel[FlattenLevel["All"] = 0] = "All"; + FlattenLevel[FlattenLevel["ObjectRest"] = 1] = "ObjectRest"; + })(FlattenLevel = ts.FlattenLevel || (ts.FlattenLevel = {})); + /** + * Flattens a DestructuringAssignment or a VariableDeclaration to an expression. + * + * @param node The node to flatten. + * @param visitor An optional visitor used to visit initializers. + * @param context The transformation context. + * @param level Indicates the extent to which flattening should occur. + * @param needsValue An optional value indicating whether the value from the right-hand-side of + * the destructuring assignment is needed as part of a larger expression. + * @param createAssignmentCallback An optional callback used to create the assignment expression. + */ + function flattenDestructuringAssignment(node, visitor, context, level, needsValue, createAssignmentCallback) { + var location = node; + var value; + if (ts.isDestructuringAssignment(node)) { + value = node.right; + while (ts.isEmptyArrayLiteral(node.left) || ts.isEmptyObjectLiteral(node.left)) { + if (ts.isDestructuringAssignment(value)) { + location = node = value; + value = node.right; + } + else { + return ts.visitNode(value, visitor, ts.isExpression); + } + } + } + var expressions; + var flattenContext = { + context: context, + level: level, + downlevelIteration: !!context.getCompilerOptions().downlevelIteration, + hoistTempVariables: true, + emitExpression: emitExpression, + emitBindingOrAssignment: emitBindingOrAssignment, + createArrayBindingOrAssignmentPattern: makeArrayAssignmentPattern, + createObjectBindingOrAssignmentPattern: makeObjectAssignmentPattern, + createArrayBindingOrAssignmentElement: makeAssignmentElement, + visitor: visitor + }; + if (value) { + value = ts.visitNode(value, visitor, ts.isExpression); + if (ts.isIdentifier(value) && bindingOrAssignmentElementAssignsToName(node, value.escapedText)) { + // If the right-hand value of the assignment is also an assignment target then + // we need to cache the right-hand value. + value = ensureIdentifier(flattenContext, value, /*reuseIdentifierExpressions*/ false, location); + } + else if (needsValue) { + // If the right-hand value of the destructuring assignment needs to be preserved (as + // is the case when the destructuring assignment is part of a larger expression), + // then we need to cache the right-hand value. + // + // The source map location for the assignment should point to the entire binary + // expression. + value = ensureIdentifier(flattenContext, value, /*reuseIdentifierExpressions*/ true, location); + } + else if (ts.nodeIsSynthesized(node)) { + // Generally, the source map location for a destructuring assignment is the root + // expression. + // + // However, if the root expression is synthesized (as in the case + // of the initializer when transforming a ForOfStatement), then the source map + // location should point to the right-hand value of the expression. + location = value; + } + } + flattenBindingOrAssignmentElement(flattenContext, node, value, location, /*skipInitializer*/ ts.isDestructuringAssignment(node)); + if (value && needsValue) { + if (!ts.some(expressions)) { + return value; + } + expressions.push(value); + } + return ts.aggregateTransformFlags(ts.inlineExpressions(expressions)) || ts.createOmittedExpression(); + function emitExpression(expression) { + // NOTE: this completely disables source maps, but aligns with the behavior of + // `emitAssignment` in the old emitter. + ts.setEmitFlags(expression, 64 /* NoNestedSourceMaps */); + ts.aggregateTransformFlags(expression); + expressions = ts.append(expressions, expression); + } + function emitBindingOrAssignment(target, value, location, original) { + ts.Debug.assertNode(target, createAssignmentCallback ? ts.isIdentifier : ts.isExpression); + var expression = createAssignmentCallback + ? createAssignmentCallback(target, value, location) + : ts.setTextRange(ts.createAssignment(ts.visitNode(target, visitor, ts.isExpression), value), location); + expression.original = original; + emitExpression(expression); + } + } + ts.flattenDestructuringAssignment = flattenDestructuringAssignment; + function bindingOrAssignmentElementAssignsToName(element, escapedName) { + var target = ts.getTargetOfBindingOrAssignmentElement(element); // TODO: GH#18217 + if (ts.isBindingOrAssignmentPattern(target)) { + return bindingOrAssignmentPatternAssignsToName(target, escapedName); + } + else if (ts.isIdentifier(target)) { + return target.escapedText === escapedName; + } + return false; + } + function bindingOrAssignmentPatternAssignsToName(pattern, escapedName) { + var elements = ts.getElementsOfBindingOrAssignmentPattern(pattern); + for (var _i = 0, elements_3 = elements; _i < elements_3.length; _i++) { + var element = elements_3[_i]; + if (bindingOrAssignmentElementAssignsToName(element, escapedName)) { + return true; + } + } + return false; + } + /** + * Flattens a VariableDeclaration or ParameterDeclaration to one or more variable declarations. + * + * @param node The node to flatten. + * @param visitor An optional visitor used to visit initializers. + * @param context The transformation context. + * @param boundValue The value bound to the declaration. + * @param skipInitializer A value indicating whether to ignore the initializer of `node`. + * @param hoistTempVariables Indicates whether temporary variables should not be recorded in-line. + * @param level Indicates the extent to which flattening should occur. + */ + function flattenDestructuringBinding(node, visitor, context, level, rval, hoistTempVariables, skipInitializer) { + if (hoistTempVariables === void 0) { hoistTempVariables = false; } + var pendingExpressions; + var pendingDeclarations = []; + var declarations = []; + var flattenContext = { + context: context, + level: level, + downlevelIteration: !!context.getCompilerOptions().downlevelIteration, + hoistTempVariables: hoistTempVariables, + emitExpression: emitExpression, + emitBindingOrAssignment: emitBindingOrAssignment, + createArrayBindingOrAssignmentPattern: makeArrayBindingPattern, + createObjectBindingOrAssignmentPattern: makeObjectBindingPattern, + createArrayBindingOrAssignmentElement: makeBindingElement, + visitor: visitor + }; + if (ts.isVariableDeclaration(node)) { + var initializer = ts.getInitializerOfBindingOrAssignmentElement(node); + if (initializer && ts.isIdentifier(initializer) && bindingOrAssignmentElementAssignsToName(node, initializer.escapedText)) { + // If the right-hand value of the assignment is also an assignment target then + // we need to cache the right-hand value. + initializer = ensureIdentifier(flattenContext, initializer, /*reuseIdentifierExpressions*/ false, initializer); + node = ts.updateVariableDeclaration(node, node.name, node.type, initializer); + } + } + flattenBindingOrAssignmentElement(flattenContext, node, rval, node, skipInitializer); + if (pendingExpressions) { + var temp = ts.createTempVariable(/*recordTempVariable*/ undefined); + if (hoistTempVariables) { + var value = ts.inlineExpressions(pendingExpressions); + pendingExpressions = undefined; + emitBindingOrAssignment(temp, value, /*location*/ undefined, /*original*/ undefined); + } + else { + context.hoistVariableDeclaration(temp); + var pendingDeclaration = ts.last(pendingDeclarations); + pendingDeclaration.pendingExpressions = ts.append(pendingDeclaration.pendingExpressions, ts.createAssignment(temp, pendingDeclaration.value)); + ts.addRange(pendingDeclaration.pendingExpressions, pendingExpressions); + pendingDeclaration.value = temp; + } + } + for (var _i = 0, pendingDeclarations_1 = pendingDeclarations; _i < pendingDeclarations_1.length; _i++) { + var _a = pendingDeclarations_1[_i], pendingExpressions_1 = _a.pendingExpressions, name = _a.name, value = _a.value, location = _a.location, original = _a.original; + var variable = ts.createVariableDeclaration(name, + /*type*/ undefined, pendingExpressions_1 ? ts.inlineExpressions(ts.append(pendingExpressions_1, value)) : value); + variable.original = original; + ts.setTextRange(variable, location); + if (ts.isIdentifier(name)) { + ts.setEmitFlags(variable, 64 /* NoNestedSourceMaps */); + } + ts.aggregateTransformFlags(variable); + declarations.push(variable); + } + return declarations; + function emitExpression(value) { + pendingExpressions = ts.append(pendingExpressions, value); + } + function emitBindingOrAssignment(target, value, location, original) { + ts.Debug.assertNode(target, ts.isBindingName); + if (pendingExpressions) { + value = ts.inlineExpressions(ts.append(pendingExpressions, value)); + pendingExpressions = undefined; + } + pendingDeclarations.push({ pendingExpressions: pendingExpressions, name: target, value: value, location: location, original: original }); + } + } + ts.flattenDestructuringBinding = flattenDestructuringBinding; + /** + * Flattens a BindingOrAssignmentElement into zero or more bindings or assignments. + * + * @param flattenContext Options used to control flattening. + * @param element The element to flatten. + * @param value The current RHS value to assign to the element. + * @param location The location to use for source maps and comments. + * @param skipInitializer An optional value indicating whether to include the initializer + * for the element. + */ + function flattenBindingOrAssignmentElement(flattenContext, element, value, location, skipInitializer) { + if (!skipInitializer) { + var initializer = ts.visitNode(ts.getInitializerOfBindingOrAssignmentElement(element), flattenContext.visitor, ts.isExpression); + if (initializer) { + // Combine value and initializer + value = value ? createDefaultValueCheck(flattenContext, value, initializer, location) : initializer; + } + else if (!value) { + // Use 'void 0' in absence of value and initializer + value = ts.createVoidZero(); + } + } + var bindingTarget = ts.getTargetOfBindingOrAssignmentElement(element); // TODO: GH#18217 + if (ts.isObjectBindingOrAssignmentPattern(bindingTarget)) { + flattenObjectBindingOrAssignmentPattern(flattenContext, element, bindingTarget, value, location); + } + else if (ts.isArrayBindingOrAssignmentPattern(bindingTarget)) { + flattenArrayBindingOrAssignmentPattern(flattenContext, element, bindingTarget, value, location); + } + else { + flattenContext.emitBindingOrAssignment(bindingTarget, value, location, /*original*/ element); // TODO: GH#18217 + } + } + /** + * Flattens an ObjectBindingOrAssignmentPattern into zero or more bindings or assignments. + * + * @param flattenContext Options used to control flattening. + * @param parent The parent element of the pattern. + * @param pattern The ObjectBindingOrAssignmentPattern to flatten. + * @param value The current RHS value to assign to the element. + * @param location The location to use for source maps and comments. + */ + function flattenObjectBindingOrAssignmentPattern(flattenContext, parent, pattern, value, location) { + var elements = ts.getElementsOfBindingOrAssignmentPattern(pattern); + var numElements = elements.length; + if (numElements !== 1) { + // For anything other than a single-element destructuring we need to generate a temporary + // to ensure value is evaluated exactly once. Additionally, if we have zero elements + // we need to emit *something* to ensure that in case a 'var' keyword was already emitted, + // so in that case, we'll intentionally create that temporary. + var reuseIdentifierExpressions = !ts.isDeclarationBindingElement(parent) || numElements !== 0; + value = ensureIdentifier(flattenContext, value, reuseIdentifierExpressions, location); + } + var bindingElements; + var computedTempVariables; + for (var i = 0; i < numElements; i++) { + var element = elements[i]; + if (!ts.getRestIndicatorOfBindingOrAssignmentElement(element)) { + var propertyName = ts.getPropertyNameOfBindingOrAssignmentElement(element); + if (flattenContext.level >= 1 /* ObjectRest */ + && !(element.transformFlags & (131072 /* ContainsRestOrSpread */ | 262144 /* ContainsObjectRestOrSpread */)) + && !(ts.getTargetOfBindingOrAssignmentElement(element).transformFlags & (131072 /* ContainsRestOrSpread */ | 262144 /* ContainsObjectRestOrSpread */)) + && !ts.isComputedPropertyName(propertyName)) { + bindingElements = ts.append(bindingElements, element); + } + else { + if (bindingElements) { + flattenContext.emitBindingOrAssignment(flattenContext.createObjectBindingOrAssignmentPattern(bindingElements), value, location, pattern); + bindingElements = undefined; + } + var rhsValue = createDestructuringPropertyAccess(flattenContext, value, propertyName); + if (ts.isComputedPropertyName(propertyName)) { + computedTempVariables = ts.append(computedTempVariables, rhsValue.argumentExpression); + } + flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, /*location*/ element); + } + } + else if (i === numElements - 1) { + if (bindingElements) { + flattenContext.emitBindingOrAssignment(flattenContext.createObjectBindingOrAssignmentPattern(bindingElements), value, location, pattern); + bindingElements = undefined; + } + var rhsValue = createRestCall(flattenContext.context, value, elements, computedTempVariables, pattern); // TODO: GH#18217 + flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, element); + } + } + if (bindingElements) { + flattenContext.emitBindingOrAssignment(flattenContext.createObjectBindingOrAssignmentPattern(bindingElements), value, location, pattern); + } + } + /** + * Flattens an ArrayBindingOrAssignmentPattern into zero or more bindings or assignments. + * + * @param flattenContext Options used to control flattening. + * @param parent The parent element of the pattern. + * @param pattern The ArrayBindingOrAssignmentPattern to flatten. + * @param value The current RHS value to assign to the element. + * @param location The location to use for source maps and comments. + */ + function flattenArrayBindingOrAssignmentPattern(flattenContext, parent, pattern, value, location) { + var elements = ts.getElementsOfBindingOrAssignmentPattern(pattern); + var numElements = elements.length; + if (flattenContext.level < 1 /* ObjectRest */ && flattenContext.downlevelIteration) { + // Read the elements of the iterable into an array + value = ensureIdentifier(flattenContext, ts.createReadHelper(flattenContext.context, value, numElements > 0 && ts.getRestIndicatorOfBindingOrAssignmentElement(elements[numElements - 1]) + ? undefined + : numElements, location), + /*reuseIdentifierExpressions*/ false, location); + } + else if (numElements !== 1 && (flattenContext.level < 1 /* ObjectRest */ || numElements === 0) + || ts.every(elements, ts.isOmittedExpression)) { + // For anything other than a single-element destructuring we need to generate a temporary + // to ensure value is evaluated exactly once. Additionally, if we have zero elements + // we need to emit *something* to ensure that in case a 'var' keyword was already emitted, + // so in that case, we'll intentionally create that temporary. + // Or all the elements of the binding pattern are omitted expression such as "var [,] = [1,2]", + // then we will create temporary variable. + var reuseIdentifierExpressions = !ts.isDeclarationBindingElement(parent) || numElements !== 0; + value = ensureIdentifier(flattenContext, value, reuseIdentifierExpressions, location); + } + var bindingElements; + var restContainingElements; + for (var i = 0; i < numElements; i++) { + var element = elements[i]; + if (flattenContext.level >= 1 /* ObjectRest */) { + // If an array pattern contains an ObjectRest, we must cache the result so that we + // can perform the ObjectRest destructuring in a different declaration + if (element.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { + var temp = ts.createTempVariable(/*recordTempVariable*/ undefined); + if (flattenContext.hoistTempVariables) { + flattenContext.context.hoistVariableDeclaration(temp); + } + restContainingElements = ts.append(restContainingElements, [temp, element]); + bindingElements = ts.append(bindingElements, flattenContext.createArrayBindingOrAssignmentElement(temp)); + } + else { + bindingElements = ts.append(bindingElements, element); + } + } + else if (ts.isOmittedExpression(element)) { + continue; + } + else if (!ts.getRestIndicatorOfBindingOrAssignmentElement(element)) { + var rhsValue = ts.createElementAccess(value, i); + flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, /*location*/ element); + } + else if (i === numElements - 1) { + var rhsValue = ts.createArraySlice(value, i); + flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, /*location*/ element); + } + } + if (bindingElements) { + flattenContext.emitBindingOrAssignment(flattenContext.createArrayBindingOrAssignmentPattern(bindingElements), value, location, pattern); + } + if (restContainingElements) { + for (var _i = 0, restContainingElements_1 = restContainingElements; _i < restContainingElements_1.length; _i++) { + var _a = restContainingElements_1[_i], id = _a[0], element = _a[1]; + flattenBindingOrAssignmentElement(flattenContext, element, id, element); + } + } + } + /** + * Creates an expression used to provide a default value if a value is `undefined` at runtime. + * + * @param flattenContext Options used to control flattening. + * @param value The RHS value to test. + * @param defaultValue The default value to use if `value` is `undefined` at runtime. + * @param location The location to use for source maps and comments. + */ + function createDefaultValueCheck(flattenContext, value, defaultValue, location) { + value = ensureIdentifier(flattenContext, value, /*reuseIdentifierExpressions*/ true, location); + return ts.createConditional(ts.createTypeCheck(value, "undefined"), defaultValue, value); + } + /** + * Creates either a PropertyAccessExpression or an ElementAccessExpression for the + * right-hand side of a transformed destructuring assignment. + * + * @link https://tc39.github.io/ecma262/#sec-runtime-semantics-keyeddestructuringassignmentevaluation + * + * @param flattenContext Options used to control flattening. + * @param value The RHS value that is the source of the property. + * @param propertyName The destructuring property name. + */ + function createDestructuringPropertyAccess(flattenContext, value, propertyName) { + if (ts.isComputedPropertyName(propertyName)) { + var argumentExpression = ensureIdentifier(flattenContext, ts.visitNode(propertyName.expression, flattenContext.visitor), /*reuseIdentifierExpressions*/ false, /*location*/ propertyName); + return ts.createElementAccess(value, argumentExpression); + } + else if (ts.isStringOrNumericLiteralLike(propertyName)) { + var argumentExpression = ts.getSynthesizedClone(propertyName); + argumentExpression.text = argumentExpression.text; + return ts.createElementAccess(value, argumentExpression); + } + else { + var name = ts.createIdentifier(ts.idText(propertyName)); + return ts.createPropertyAccess(value, name); + } + } + /** + * Ensures that there exists a declared identifier whose value holds the given expression. + * This function is useful to ensure that the expression's value can be read from in subsequent expressions. + * Unless 'reuseIdentifierExpressions' is false, 'value' will be returned if it is just an identifier. + * + * @param flattenContext Options used to control flattening. + * @param value the expression whose value needs to be bound. + * @param reuseIdentifierExpressions true if identifier expressions can simply be returned; + * false if it is necessary to always emit an identifier. + * @param location The location to use for source maps and comments. + */ + function ensureIdentifier(flattenContext, value, reuseIdentifierExpressions, location) { + if (ts.isIdentifier(value) && reuseIdentifierExpressions) { + return value; + } + else { + var temp = ts.createTempVariable(/*recordTempVariable*/ undefined); + if (flattenContext.hoistTempVariables) { + flattenContext.context.hoistVariableDeclaration(temp); + flattenContext.emitExpression(ts.setTextRange(ts.createAssignment(temp, value), location)); + } + else { + flattenContext.emitBindingOrAssignment(temp, value, location, /*original*/ undefined); + } + return temp; + } + } + function makeArrayBindingPattern(elements) { + ts.Debug.assertEachNode(elements, ts.isArrayBindingElement); + return ts.createArrayBindingPattern(elements); + } + function makeArrayAssignmentPattern(elements) { + return ts.createArrayLiteral(ts.map(elements, ts.convertToArrayAssignmentElement)); + } + function makeObjectBindingPattern(elements) { + ts.Debug.assertEachNode(elements, ts.isBindingElement); + return ts.createObjectBindingPattern(elements); + } + function makeObjectAssignmentPattern(elements) { + return ts.createObjectLiteral(ts.map(elements, ts.convertToObjectAssignmentElement)); + } + function makeBindingElement(name) { + return ts.createBindingElement(/*dotDotDotToken*/ undefined, /*propertyName*/ undefined, name); + } + function makeAssignmentElement(name) { + return name; + } + var restHelper = { + name: "typescript:rest", + scoped: false, + text: "\n var __rest = (this && this.__rest) || function (s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) if (e.indexOf(p[i]) < 0)\n t[p[i]] = s[p[i]];\n return t;\n };" + }; + /** Given value: o, propName: p, pattern: { a, b, ...p } from the original statement + * `{ a, b, ...p } = o`, create `p = __rest(o, ["a", "b"]);` + */ + function createRestCall(context, value, elements, computedTempVariables, location) { + context.requestEmitHelper(restHelper); + var propertyNames = []; + var computedTempVariableOffset = 0; + for (var i = 0; i < elements.length - 1; i++) { + var propertyName = ts.getPropertyNameOfBindingOrAssignmentElement(elements[i]); + if (propertyName) { + if (ts.isComputedPropertyName(propertyName)) { + var temp = computedTempVariables[computedTempVariableOffset]; + computedTempVariableOffset++; + // typeof _tmp === "symbol" ? _tmp : _tmp + "" + propertyNames.push(ts.createConditional(ts.createTypeCheck(temp, "symbol"), temp, ts.createAdd(temp, ts.createLiteral("")))); + } + else { + propertyNames.push(ts.createLiteral(propertyName)); + } + } + } + return ts.createCall(ts.getHelperName("__rest"), + /*typeArguments*/ undefined, [ + value, + ts.setTextRange(ts.createArrayLiteral(propertyNames), location) + ]); + } +})(ts || (ts = {})); +/*@internal*/ +var ts; +(function (ts) { + /** + * Indicates whether to emit type metadata in the new format. + */ + var USE_NEW_TYPE_METADATA_FORMAT = false; + var TypeScriptSubstitutionFlags; + (function (TypeScriptSubstitutionFlags) { + /** Enables substitutions for decorated classes. */ + TypeScriptSubstitutionFlags[TypeScriptSubstitutionFlags["ClassAliases"] = 1] = "ClassAliases"; + /** Enables substitutions for namespace exports. */ + TypeScriptSubstitutionFlags[TypeScriptSubstitutionFlags["NamespaceExports"] = 2] = "NamespaceExports"; + /* Enables substitutions for unqualified enum members */ + TypeScriptSubstitutionFlags[TypeScriptSubstitutionFlags["NonQualifiedEnumMembers"] = 8] = "NonQualifiedEnumMembers"; + })(TypeScriptSubstitutionFlags || (TypeScriptSubstitutionFlags = {})); + var ClassFacts; + (function (ClassFacts) { + ClassFacts[ClassFacts["None"] = 0] = "None"; + ClassFacts[ClassFacts["HasStaticInitializedProperties"] = 1] = "HasStaticInitializedProperties"; + ClassFacts[ClassFacts["HasConstructorDecorators"] = 2] = "HasConstructorDecorators"; + ClassFacts[ClassFacts["HasMemberDecorators"] = 4] = "HasMemberDecorators"; + ClassFacts[ClassFacts["IsExportOfNamespace"] = 8] = "IsExportOfNamespace"; + ClassFacts[ClassFacts["IsNamedExternalExport"] = 16] = "IsNamedExternalExport"; + ClassFacts[ClassFacts["IsDefaultExternalExport"] = 32] = "IsDefaultExternalExport"; + ClassFacts[ClassFacts["IsDerivedClass"] = 64] = "IsDerivedClass"; + ClassFacts[ClassFacts["UseImmediatelyInvokedFunctionExpression"] = 128] = "UseImmediatelyInvokedFunctionExpression"; + ClassFacts[ClassFacts["HasAnyDecorators"] = 6] = "HasAnyDecorators"; + ClassFacts[ClassFacts["NeedsName"] = 5] = "NeedsName"; + ClassFacts[ClassFacts["MayNeedImmediatelyInvokedFunctionExpression"] = 7] = "MayNeedImmediatelyInvokedFunctionExpression"; + ClassFacts[ClassFacts["IsExported"] = 56] = "IsExported"; + })(ClassFacts || (ClassFacts = {})); + function transformTypeScript(context) { + var startLexicalEnvironment = context.startLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; + var resolver = context.getEmitResolver(); + var compilerOptions = context.getCompilerOptions(); + var strictNullChecks = ts.getStrictOptionValue(compilerOptions, "strictNullChecks"); + var languageVersion = ts.getEmitScriptTarget(compilerOptions); + var moduleKind = ts.getEmitModuleKind(compilerOptions); + // Save the previous transformation hooks. + var previousOnEmitNode = context.onEmitNode; + var previousOnSubstituteNode = context.onSubstituteNode; + // Set new transformation hooks. + context.onEmitNode = onEmitNode; + context.onSubstituteNode = onSubstituteNode; + // Enable substitution for property/element access to emit const enum values. + context.enableSubstitution(189 /* PropertyAccessExpression */); + context.enableSubstitution(190 /* ElementAccessExpression */); + // These variables contain state that changes as we descend into the tree. + var currentSourceFile; + var currentNamespace; + var currentNamespaceContainerName; + var currentLexicalScope; + var currentNameScope; + var currentScopeFirstDeclarationsOfName; + /** + * Keeps track of whether expression substitution has been enabled for specific edge cases. + * They are persisted between each SourceFile transformation and should not be reset. + */ + var enabledSubstitutions; + /** + * A map that keeps track of aliases created for classes with decorators to avoid issues + * with the double-binding behavior of classes. + */ + var classAliases; + /** + * Keeps track of whether we are within any containing namespaces when performing + * just-in-time substitution while printing an expression identifier. + */ + var applicableSubstitutions; + /** + * Tracks what computed name expressions originating from elided names must be inlined + * at the next execution site, in document order + */ + var pendingExpressions; + return transformSourceFileOrBundle; + function transformSourceFileOrBundle(node) { + if (node.kind === 280 /* Bundle */) { + return transformBundle(node); + } + return transformSourceFile(node); + } + function transformBundle(node) { + return ts.createBundle(node.sourceFiles.map(transformSourceFile), ts.mapDefined(node.prepends, function (prepend) { + if (prepend.kind === 282 /* InputFiles */) { + return ts.createUnparsedSourceFile(prepend.javascriptText, prepend.javascriptMapPath, prepend.javascriptMapText); + } + return prepend; + })); + } + /** + * Transform TypeScript-specific syntax in a SourceFile. + * + * @param node A SourceFile node. + */ + function transformSourceFile(node) { + if (node.isDeclarationFile) { + return node; + } + currentSourceFile = node; + var visited = saveStateAndInvoke(node, visitSourceFile); + ts.addEmitHelpers(visited, context.readEmitHelpers()); + currentSourceFile = undefined; + return visited; + } + /** + * Visits a node, saving and restoring state variables on the stack. + * + * @param node The node to visit. + */ + function saveStateAndInvoke(node, f) { + // Save state + var savedCurrentScope = currentLexicalScope; + var savedCurrentNameScope = currentNameScope; + var savedCurrentScopeFirstDeclarationsOfName = currentScopeFirstDeclarationsOfName; + // Handle state changes before visiting a node. + onBeforeVisitNode(node); + var visited = f(node); + // Restore state + if (currentLexicalScope !== savedCurrentScope) { + currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName; + } + currentLexicalScope = savedCurrentScope; + currentNameScope = savedCurrentNameScope; + return visited; + } + /** + * Performs actions that should always occur immediately before visiting a node. + * + * @param node The node to visit. + */ + function onBeforeVisitNode(node) { + switch (node.kind) { + case 279 /* SourceFile */: + case 246 /* CaseBlock */: + case 245 /* ModuleBlock */: + case 218 /* Block */: + currentLexicalScope = node; + currentNameScope = undefined; + currentScopeFirstDeclarationsOfName = undefined; + break; + case 240 /* ClassDeclaration */: + case 239 /* FunctionDeclaration */: + if (ts.hasModifier(node, 2 /* Ambient */)) { + break; + } + // Record these declarations provided that they have a name. + if (node.name) { + recordEmittedDeclarationInScope(node); + } + else { + // These nodes should always have names unless they are default-exports; + // however, class declaration parsing allows for undefined names, so syntactically invalid + // programs may also have an undefined name. + ts.Debug.assert(node.kind === 240 /* ClassDeclaration */ || ts.hasModifier(node, 512 /* Default */)); + } + if (ts.isClassDeclaration(node)) { + // XXX: should probably also cover interfaces and type aliases that can have type variables? + currentNameScope = node; + } + break; + } + } + /** + * General-purpose node visitor. + * + * @param node The node to visit. + */ + function visitor(node) { + return saveStateAndInvoke(node, visitorWorker); + } + /** + * Visits and possibly transforms any node. + * + * @param node The node to visit. + */ + function visitorWorker(node) { + if (node.transformFlags & 1 /* TypeScript */) { + // This node is explicitly marked as TypeScript, so we should transform the node. + return visitTypeScript(node); + } + else if (node.transformFlags & 2 /* ContainsTypeScript */) { + // This node contains TypeScript, so we should visit its children. + return ts.visitEachChild(node, visitor, context); + } + return node; + } + /** + * Specialized visitor that visits the immediate children of a SourceFile. + * + * @param node The node to visit. + */ + function sourceElementVisitor(node) { + return saveStateAndInvoke(node, sourceElementVisitorWorker); + } + /** + * Specialized visitor that visits the immediate children of a SourceFile. + * + * @param node The node to visit. + */ + function sourceElementVisitorWorker(node) { + switch (node.kind) { + case 249 /* ImportDeclaration */: + case 248 /* ImportEqualsDeclaration */: + case 254 /* ExportAssignment */: + case 255 /* ExportDeclaration */: + return visitEllidableStatement(node); + default: + return visitorWorker(node); + } + } + function visitEllidableStatement(node) { + var parsed = ts.getParseTreeNode(node); + if (parsed !== node) { + // If the node has been transformed by a `before` transformer, perform no ellision on it + // As the type information we would attempt to lookup to perform ellision is potentially unavailable for the synthesized nodes + // We do not reuse `visitorWorker`, as the ellidable statement syntax kinds are technically unrecognized by the switch-case in `visitTypeScript`, + // and will trigger debug failures when debug verbosity is turned up + if (node.transformFlags & 2 /* ContainsTypeScript */) { + // This node contains TypeScript, so we should visit its children. + return ts.visitEachChild(node, visitor, context); + } + // Otherwise, we can just return the node + return node; + } + switch (node.kind) { + case 249 /* ImportDeclaration */: + return visitImportDeclaration(node); + case 248 /* ImportEqualsDeclaration */: + return visitImportEqualsDeclaration(node); + case 254 /* ExportAssignment */: + return visitExportAssignment(node); + case 255 /* ExportDeclaration */: + return visitExportDeclaration(node); + default: + ts.Debug.fail("Unhandled ellided statement"); + } + } + /** + * Specialized visitor that visits the immediate children of a namespace. + * + * @param node The node to visit. + */ + function namespaceElementVisitor(node) { + return saveStateAndInvoke(node, namespaceElementVisitorWorker); + } + /** + * Specialized visitor that visits the immediate children of a namespace. + * + * @param node The node to visit. + */ + function namespaceElementVisitorWorker(node) { + if (node.kind === 255 /* ExportDeclaration */ || + node.kind === 249 /* ImportDeclaration */ || + node.kind === 250 /* ImportClause */ || + (node.kind === 248 /* ImportEqualsDeclaration */ && + node.moduleReference.kind === 259 /* ExternalModuleReference */)) { + // do not emit ES6 imports and exports since they are illegal inside a namespace + return undefined; + } + else if (node.transformFlags & 1 /* TypeScript */ || ts.hasModifier(node, 1 /* Export */)) { + // This node is explicitly marked as TypeScript, or is exported at the namespace + // level, so we should transform the node. + return visitTypeScript(node); + } + else if (node.transformFlags & 2 /* ContainsTypeScript */) { + // This node contains TypeScript, so we should visit its children. + return ts.visitEachChild(node, visitor, context); + } + return node; + } + /** + * Specialized visitor that visits the immediate children of a class with TypeScript syntax. + * + * @param node The node to visit. + */ + function classElementVisitor(node) { + return saveStateAndInvoke(node, classElementVisitorWorker); + } + /** + * Specialized visitor that visits the immediate children of a class with TypeScript syntax. + * + * @param node The node to visit. + */ + function classElementVisitorWorker(node) { + switch (node.kind) { + case 157 /* Constructor */: + // TypeScript constructors are transformed in `visitClassDeclaration`. + // We elide them here as `visitorWorker` checks transform flags, which could + // erronously include an ES6 constructor without TypeScript syntax. + return undefined; + case 154 /* PropertyDeclaration */: + case 162 /* IndexSignature */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 156 /* MethodDeclaration */: + // Fallback to the default visit behavior. + return visitorWorker(node); + case 217 /* SemicolonClassElement */: + return node; + default: + return ts.Debug.failBadSyntaxKind(node); + } + } + function modifierVisitor(node) { + if (ts.modifierToFlag(node.kind) & 2270 /* TypeScriptModifier */) { + return undefined; + } + else if (currentNamespace && node.kind === 85 /* ExportKeyword */) { + return undefined; + } + return node; + } + /** + * Branching visitor, visits a TypeScript syntax node. + * + * @param node The node to visit. + */ + function visitTypeScript(node) { + if (ts.hasModifier(node, 2 /* Ambient */) && ts.isStatement(node)) { + // TypeScript ambient declarations are elided, but some comments may be preserved. + // See the implementation of `getLeadingComments` in comments.ts for more details. + return ts.createNotEmittedStatement(node); + } + switch (node.kind) { + case 85 /* ExportKeyword */: + case 80 /* DefaultKeyword */: + // ES6 export and default modifiers are elided when inside a namespace. + return currentNamespace ? undefined : node; + case 115 /* PublicKeyword */: + case 113 /* PrivateKeyword */: + case 114 /* ProtectedKeyword */: + case 118 /* AbstractKeyword */: + case 77 /* ConstKeyword */: + case 125 /* DeclareKeyword */: + case 133 /* ReadonlyKeyword */: + // TypeScript accessibility and readonly modifiers are elided. + case 169 /* ArrayType */: + case 170 /* TupleType */: + case 171 /* OptionalType */: + case 172 /* RestType */: + case 168 /* TypeLiteral */: + case 163 /* TypePredicate */: + case 150 /* TypeParameter */: + case 120 /* AnyKeyword */: + case 143 /* UnknownKeyword */: + case 123 /* BooleanKeyword */: + case 138 /* StringKeyword */: + case 135 /* NumberKeyword */: + case 132 /* NeverKeyword */: + case 106 /* VoidKeyword */: + case 139 /* SymbolKeyword */: + case 166 /* ConstructorType */: + case 165 /* FunctionType */: + case 167 /* TypeQuery */: + case 164 /* TypeReference */: + case 173 /* UnionType */: + case 174 /* IntersectionType */: + case 175 /* ConditionalType */: + case 177 /* ParenthesizedType */: + case 178 /* ThisType */: + case 179 /* TypeOperator */: + case 180 /* IndexedAccessType */: + case 181 /* MappedType */: + case 182 /* LiteralType */: + // TypeScript type nodes are elided. + case 162 /* IndexSignature */: + // TypeScript index signatures are elided. + case 152 /* Decorator */: + // TypeScript decorators are elided. They will be emitted as part of visitClassDeclaration. + case 242 /* TypeAliasDeclaration */: + // TypeScript type-only declarations are elided. + return undefined; + case 154 /* PropertyDeclaration */: + // TypeScript property declarations are elided. However their names are still visited, and can potentially be retained if they could have sideeffects + return visitPropertyDeclaration(node); + case 247 /* NamespaceExportDeclaration */: + // TypeScript namespace export declarations are elided. + return undefined; + case 157 /* Constructor */: + return visitConstructor(node); + case 241 /* InterfaceDeclaration */: + // TypeScript interfaces are elided, but some comments may be preserved. + // See the implementation of `getLeadingComments` in comments.ts for more details. + return ts.createNotEmittedStatement(node); + case 240 /* ClassDeclaration */: + // This is a class declaration with TypeScript syntax extensions. + // + // TypeScript class syntax extensions include: + // - decorators + // - optional `implements` heritage clause + // - parameter property assignments in the constructor + // - property declarations + // - index signatures + // - method overload signatures + return visitClassDeclaration(node); + case 209 /* ClassExpression */: + // This is a class expression with TypeScript syntax extensions. + // + // TypeScript class syntax extensions include: + // - decorators + // - optional `implements` heritage clause + // - parameter property assignments in the constructor + // - property declarations + // - index signatures + // - method overload signatures + return visitClassExpression(node); + case 273 /* HeritageClause */: + // This is a heritage clause with TypeScript syntax extensions. + // + // TypeScript heritage clause extensions include: + // - `implements` clause + return visitHeritageClause(node); + case 211 /* ExpressionWithTypeArguments */: + // TypeScript supports type arguments on an expression in an `extends` heritage clause. + return visitExpressionWithTypeArguments(node); + case 156 /* MethodDeclaration */: + // TypeScript method declarations may have decorators, modifiers + // or type annotations. + return visitMethodDeclaration(node); + case 158 /* GetAccessor */: + // Get Accessors can have TypeScript modifiers, decorators, and type annotations. + return visitGetAccessor(node); + case 159 /* SetAccessor */: + // Set Accessors can have TypeScript modifiers and type annotations. + return visitSetAccessor(node); + case 239 /* FunctionDeclaration */: + // Typescript function declarations can have modifiers, decorators, and type annotations. + return visitFunctionDeclaration(node); + case 196 /* FunctionExpression */: + // TypeScript function expressions can have modifiers and type annotations. + return visitFunctionExpression(node); + case 197 /* ArrowFunction */: + // TypeScript arrow functions can have modifiers and type annotations. + return visitArrowFunction(node); + case 151 /* Parameter */: + // This is a parameter declaration with TypeScript syntax extensions. + // + // TypeScript parameter declaration syntax extensions include: + // - decorators + // - accessibility modifiers + // - the question mark (?) token for optional parameters + // - type annotations + // - this parameters + return visitParameter(node); + case 195 /* ParenthesizedExpression */: + // ParenthesizedExpressions are TypeScript if their expression is a + // TypeAssertion or AsExpression + return visitParenthesizedExpression(node); + case 194 /* TypeAssertionExpression */: + case 212 /* AsExpression */: + // TypeScript type assertions are removed, but their subtrees are preserved. + return visitAssertionExpression(node); + case 191 /* CallExpression */: + return visitCallExpression(node); + case 192 /* NewExpression */: + return visitNewExpression(node); + case 193 /* TaggedTemplateExpression */: + return visitTaggedTemplateExpression(node); + case 213 /* NonNullExpression */: + // TypeScript non-null expressions are removed, but their subtrees are preserved. + return visitNonNullExpression(node); + case 243 /* EnumDeclaration */: + // TypeScript enum declarations do not exist in ES6 and must be rewritten. + return visitEnumDeclaration(node); + case 219 /* VariableStatement */: + // TypeScript namespace exports for variable statements must be transformed. + return visitVariableStatement(node); + case 237 /* VariableDeclaration */: + return visitVariableDeclaration(node); + case 244 /* ModuleDeclaration */: + // TypeScript namespace declarations must be transformed. + return visitModuleDeclaration(node); + case 248 /* ImportEqualsDeclaration */: + // TypeScript namespace or external module import. + return visitImportEqualsDeclaration(node); + default: + return ts.Debug.failBadSyntaxKind(node); + } + } + function visitSourceFile(node) { + var alwaysStrict = ts.getStrictOptionValue(compilerOptions, "alwaysStrict") && + !(ts.isExternalModule(node) && moduleKind >= ts.ModuleKind.ES2015) && + !ts.isJsonSourceFile(node); + return ts.updateSourceFileNode(node, ts.visitLexicalEnvironment(node.statements, sourceElementVisitor, context, /*start*/ 0, alwaysStrict)); + } + /** + * Tests whether we should emit a __decorate call for a class declaration. + */ + function shouldEmitDecorateCallForClass(node) { + if (node.decorators && node.decorators.length > 0) { + return true; + } + var constructor = ts.getFirstConstructorWithBody(node); + if (constructor) { + return ts.forEach(constructor.parameters, shouldEmitDecorateCallForParameter); + } + return false; + } + /** + * Tests whether we should emit a __decorate call for a parameter declaration. + */ + function shouldEmitDecorateCallForParameter(parameter) { + return parameter.decorators !== undefined && parameter.decorators.length > 0; + } + function getClassFacts(node, staticProperties) { + var facts = 0 /* None */; + if (ts.some(staticProperties)) + facts |= 1 /* HasStaticInitializedProperties */; + var extendsClauseElement = ts.getEffectiveBaseTypeNode(node); + if (extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 96 /* NullKeyword */) + facts |= 64 /* IsDerivedClass */; + if (shouldEmitDecorateCallForClass(node)) + facts |= 2 /* HasConstructorDecorators */; + if (ts.childIsDecorated(node)) + facts |= 4 /* HasMemberDecorators */; + if (isExportOfNamespace(node)) + facts |= 8 /* IsExportOfNamespace */; + else if (isDefaultExternalModuleExport(node)) + facts |= 32 /* IsDefaultExternalExport */; + else if (isNamedExternalModuleExport(node)) + facts |= 16 /* IsNamedExternalExport */; + if (languageVersion <= 1 /* ES5 */ && (facts & 7 /* MayNeedImmediatelyInvokedFunctionExpression */)) + facts |= 128 /* UseImmediatelyInvokedFunctionExpression */; + return facts; + } + /** + * Transforms a class declaration with TypeScript syntax into compatible ES6. + * + * This function will only be called when one of the following conditions are met: + * - The class has decorators. + * - The class has property declarations with initializers. + * - The class contains a constructor that contains parameters with accessibility modifiers. + * - The class is an export in a TypeScript namespace. + * + * @param node The node to transform. + */ + function visitClassDeclaration(node) { + var savedPendingExpressions = pendingExpressions; + pendingExpressions = undefined; + var staticProperties = getInitializedProperties(node, /*isStatic*/ true); + var facts = getClassFacts(node, staticProperties); + if (facts & 128 /* UseImmediatelyInvokedFunctionExpression */) { + context.startLexicalEnvironment(); + } + var name = node.name || (facts & 5 /* NeedsName */ ? ts.getGeneratedNameForNode(node) : undefined); + var classStatement = facts & 2 /* HasConstructorDecorators */ + ? createClassDeclarationHeadWithDecorators(node, name, facts) + : createClassDeclarationHeadWithoutDecorators(node, name, facts); + var statements = [classStatement]; + // Write any pending expressions from elided or moved computed property names + if (ts.some(pendingExpressions)) { + statements.push(ts.createExpressionStatement(ts.inlineExpressions(pendingExpressions))); + } + pendingExpressions = savedPendingExpressions; + // Emit static property assignment. Because classDeclaration is lexically evaluated, + // it is safe to emit static property assignment after classDeclaration + // From ES6 specification: + // HasLexicalDeclaration (N) : Determines if the argument identifier has a binding in this environment record that was created using + // a lexical declaration such as a LexicalDeclaration or a ClassDeclaration. + if (facts & 1 /* HasStaticInitializedProperties */) { + addInitializedPropertyStatements(statements, staticProperties, facts & 128 /* UseImmediatelyInvokedFunctionExpression */ ? ts.getInternalName(node) : ts.getLocalName(node)); + } + // Write any decorators of the node. + addClassElementDecorationStatements(statements, node, /*isStatic*/ false); + addClassElementDecorationStatements(statements, node, /*isStatic*/ true); + addConstructorDecorationStatement(statements, node); + if (facts & 128 /* UseImmediatelyInvokedFunctionExpression */) { + // When we emit a TypeScript class down to ES5, we must wrap it in an IIFE so that the + // 'es2015' transformer can properly nest static initializers and decorators. The result + // looks something like: + // + // var C = function () { + // class C { + // } + // C.static_prop = 1; + // return C; + // }(); + // + var closingBraceLocation = ts.createTokenRange(ts.skipTrivia(currentSourceFile.text, node.members.end), 19 /* CloseBraceToken */); + var localName = ts.getInternalName(node); + // The following partially-emitted expression exists purely to align our sourcemap + // emit with the original emitter. + var outer = ts.createPartiallyEmittedExpression(localName); + outer.end = closingBraceLocation.end; + ts.setEmitFlags(outer, 1536 /* NoComments */); + var statement = ts.createReturn(outer); + statement.pos = closingBraceLocation.pos; + ts.setEmitFlags(statement, 1536 /* NoComments */ | 384 /* NoTokenSourceMaps */); + statements.push(statement); + ts.addStatementsAfterPrologue(statements, context.endLexicalEnvironment()); + var iife = ts.createImmediatelyInvokedArrowFunction(statements); + ts.setEmitFlags(iife, 33554432 /* TypeScriptClassWrapper */); + var varStatement = ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ false), + /*type*/ undefined, iife) + ])); + ts.setOriginalNode(varStatement, node); + ts.setCommentRange(varStatement, node); + ts.setSourceMapRange(varStatement, ts.moveRangePastDecorators(node)); + ts.startOnNewLine(varStatement); + statements = [varStatement]; + } + // If the class is exported as part of a TypeScript namespace, emit the namespace export. + // Otherwise, if the class was exported at the top level and was decorated, emit an export + // declaration or export default for the class. + if (facts & 8 /* IsExportOfNamespace */) { + addExportMemberAssignment(statements, node); + } + else if (facts & 128 /* UseImmediatelyInvokedFunctionExpression */ || facts & 2 /* HasConstructorDecorators */) { + if (facts & 32 /* IsDefaultExternalExport */) { + statements.push(ts.createExportDefault(ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true))); + } + else if (facts & 16 /* IsNamedExternalExport */) { + statements.push(ts.createExternalModuleExport(ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true))); + } + } + if (statements.length > 1) { + // Add a DeclarationMarker as a marker for the end of the declaration + statements.push(ts.createEndOfDeclarationMarker(node)); + ts.setEmitFlags(classStatement, ts.getEmitFlags(classStatement) | 4194304 /* HasEndOfDeclarationMarker */); + } + return ts.singleOrMany(statements); + } + /** + * Transforms a non-decorated class declaration and appends the resulting statements. + * + * @param node A ClassDeclaration node. + * @param name The name of the class. + * @param facts Precomputed facts about the class. + */ + function createClassDeclarationHeadWithoutDecorators(node, name, facts) { + // ${modifiers} class ${name} ${heritageClauses} { + // ${members} + // } + // we do not emit modifiers on the declaration if we are emitting an IIFE + var modifiers = !(facts & 128 /* UseImmediatelyInvokedFunctionExpression */) + ? ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier) + : undefined; + var classDeclaration = ts.createClassDeclaration( + /*decorators*/ undefined, modifiers, name, + /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node, (facts & 64 /* IsDerivedClass */) !== 0)); + // To better align with the old emitter, we should not emit a trailing source map + // entry if the class has static properties. + var emitFlags = ts.getEmitFlags(node); + if (facts & 1 /* HasStaticInitializedProperties */) { + emitFlags |= 32 /* NoTrailingSourceMap */; + } + ts.setTextRange(classDeclaration, node); + ts.setOriginalNode(classDeclaration, node); + ts.setEmitFlags(classDeclaration, emitFlags); + return classDeclaration; + } + /** + * Transforms a decorated class declaration and appends the resulting statements. If + * the class requires an alias to avoid issues with double-binding, the alias is returned. + */ + function createClassDeclarationHeadWithDecorators(node, name, facts) { + // When we emit an ES6 class that has a class decorator, we must tailor the + // emit to certain specific cases. + // + // In the simplest case, we emit the class declaration as a let declaration, and + // evaluate decorators after the close of the class body: + // + // [Example 1] + // --------------------------------------------------------------------- + // TypeScript | Javascript + // --------------------------------------------------------------------- + // @dec | let C = class C { + // class C { | } + // } | C = __decorate([dec], C); + // --------------------------------------------------------------------- + // @dec | let C = class C { + // export class C { | } + // } | C = __decorate([dec], C); + // | export { C }; + // --------------------------------------------------------------------- + // + // If a class declaration contains a reference to itself *inside* of the class body, + // this introduces two bindings to the class: One outside of the class body, and one + // inside of the class body. If we apply decorators as in [Example 1] above, there + // is the possibility that the decorator `dec` will return a new value for the + // constructor, which would result in the binding inside of the class no longer + // pointing to the same reference as the binding outside of the class. + // + // As a result, we must instead rewrite all references to the class *inside* of the + // class body to instead point to a local temporary alias for the class: + // + // [Example 2] + // --------------------------------------------------------------------- + // TypeScript | Javascript + // --------------------------------------------------------------------- + // @dec | let C = C_1 = class C { + // class C { | static x() { return C_1.y; } + // static x() { return C.y; } | } + // static y = 1; | C.y = 1; + // } | C = C_1 = __decorate([dec], C); + // | var C_1; + // --------------------------------------------------------------------- + // @dec | let C = class C { + // export class C { | static x() { return C_1.y; } + // static x() { return C.y; } | } + // static y = 1; | C.y = 1; + // } | C = C_1 = __decorate([dec], C); + // | export { C }; + // | var C_1; + // --------------------------------------------------------------------- + // + // If a class declaration is the default export of a module, we instead emit + // the export after the decorated declaration: + // + // [Example 3] + // --------------------------------------------------------------------- + // TypeScript | Javascript + // --------------------------------------------------------------------- + // @dec | let default_1 = class { + // export default class { | } + // } | default_1 = __decorate([dec], default_1); + // | export default default_1; + // --------------------------------------------------------------------- + // @dec | let C = class C { + // export default class C { | } + // } | C = __decorate([dec], C); + // | export default C; + // --------------------------------------------------------------------- + // + // If the class declaration is the default export and a reference to itself + // inside of the class body, we must emit both an alias for the class *and* + // move the export after the declaration: + // + // [Example 4] + // --------------------------------------------------------------------- + // TypeScript | Javascript + // --------------------------------------------------------------------- + // @dec | let C = class C { + // export default class C { | static x() { return C_1.y; } + // static x() { return C.y; } | } + // static y = 1; | C.y = 1; + // } | C = C_1 = __decorate([dec], C); + // | export default C; + // | var C_1; + // --------------------------------------------------------------------- + // + var location = ts.moveRangePastDecorators(node); + var classAlias = getClassAliasIfNeeded(node); + var declName = ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true); + // ... = class ${name} ${heritageClauses} { + // ${members} + // } + var heritageClauses = ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause); + var members = transformClassMembers(node, (facts & 64 /* IsDerivedClass */) !== 0); + var classExpression = ts.createClassExpression(/*modifiers*/ undefined, name, /*typeParameters*/ undefined, heritageClauses, members); + ts.setOriginalNode(classExpression, node); + ts.setTextRange(classExpression, location); + // let ${name} = ${classExpression} where name is either declaredName if the class doesn't contain self-reference + // or decoratedClassAlias if the class contain self-reference. + var statement = ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(declName, + /*type*/ undefined, classAlias ? ts.createAssignment(classAlias, classExpression) : classExpression) + ], 1 /* Let */)); + ts.setOriginalNode(statement, node); + ts.setTextRange(statement, location); + ts.setCommentRange(statement, node); + return statement; + } + /** + * Transforms a class expression with TypeScript syntax into compatible ES6. + * + * This function will only be called when one of the following conditions are met: + * - The class has property declarations with initializers. + * - The class contains a constructor that contains parameters with accessibility modifiers. + * + * @param node The node to transform. + */ + function visitClassExpression(node) { + var savedPendingExpressions = pendingExpressions; + pendingExpressions = undefined; + var staticProperties = getInitializedProperties(node, /*isStatic*/ true); + var heritageClauses = ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause); + var members = transformClassMembers(node, ts.some(heritageClauses, function (c) { return c.token === 86 /* ExtendsKeyword */; })); + var classExpression = ts.createClassExpression( + /*modifiers*/ undefined, node.name, + /*typeParameters*/ undefined, heritageClauses, members); + ts.setOriginalNode(classExpression, node); + ts.setTextRange(classExpression, node); + if (ts.some(staticProperties) || ts.some(pendingExpressions)) { + var expressions = []; + var isClassWithConstructorReference = resolver.getNodeCheckFlags(node) & 16777216 /* ClassWithConstructorReference */; + var temp = ts.createTempVariable(hoistVariableDeclaration, !!isClassWithConstructorReference); + if (isClassWithConstructorReference) { + // record an alias as the class name is not in scope for statics. + enableSubstitutionForClassAliases(); + var alias = ts.getSynthesizedClone(temp); + alias.autoGenerateFlags &= ~8 /* ReservedInNestedScopes */; + classAliases[ts.getOriginalNodeId(node)] = alias; + } + // To preserve the behavior of the old emitter, we explicitly indent + // the body of a class with static initializers. + ts.setEmitFlags(classExpression, 65536 /* Indented */ | ts.getEmitFlags(classExpression)); + expressions.push(ts.startOnNewLine(ts.createAssignment(temp, classExpression))); + // Add any pending expressions leftover from elided or relocated computed property names + ts.addRange(expressions, ts.map(pendingExpressions, ts.startOnNewLine)); + pendingExpressions = savedPendingExpressions; + ts.addRange(expressions, generateInitializedPropertyExpressions(staticProperties, temp)); + expressions.push(ts.startOnNewLine(temp)); + return ts.inlineExpressions(expressions); + } + pendingExpressions = savedPendingExpressions; + return classExpression; + } + /** + * Transforms the members of a class. + * + * @param node The current class. + * @param isDerivedClass A value indicating whether the class has an extends clause that does not extend 'null'. + */ + function transformClassMembers(node, isDerivedClass) { + var members = []; + var constructor = transformConstructor(node, isDerivedClass); + if (constructor) { + members.push(constructor); + } + ts.addRange(members, ts.visitNodes(node.members, classElementVisitor, ts.isClassElement)); + return ts.setTextRange(ts.createNodeArray(members), /*location*/ node.members); + } + /** + * Transforms (or creates) a constructor for a class. + * + * @param node The current class. + * @param isDerivedClass A value indicating whether the class has an extends clause that does not extend 'null'. + */ + function transformConstructor(node, isDerivedClass) { + // Check if we have property assignment inside class declaration. + // If there is a property assignment, we need to emit constructor whether users define it or not + // If there is no property assignment, we can omit constructor if users do not define it + var constructor = ts.getFirstConstructorWithBody(node); + var hasInstancePropertyWithInitializer = ts.forEach(node.members, isInstanceInitializedProperty); + var hasParameterPropertyAssignments = constructor && + constructor.transformFlags & 4096 /* ContainsTypeScriptClassSyntax */ && + ts.forEach(constructor.parameters, isParameterWithPropertyAssignment); + // If the class does not contain nodes that require a synthesized constructor, + // accept the current constructor if it exists. + if (!hasInstancePropertyWithInitializer && !hasParameterPropertyAssignments) { + return ts.visitEachChild(constructor, visitor, context); + } + var parameters = transformConstructorParameters(constructor); + var body = transformConstructorBody(node, constructor, isDerivedClass); + // constructor(${parameters}) { + // ${body} + // } + return ts.startOnNewLine(ts.setOriginalNode(ts.setTextRange(ts.createConstructor( + /*decorators*/ undefined, + /*modifiers*/ undefined, parameters, body), constructor || node), constructor)); + } + /** + * Transforms (or creates) the parameters for the constructor of a class with + * parameter property assignments or instance property initializers. + * + * @param constructor The constructor declaration. + */ + function transformConstructorParameters(constructor) { + // The ES2015 spec specifies in 14.5.14. Runtime Semantics: ClassDefinitionEvaluation: + // If constructor is empty, then + // If ClassHeritag_eopt is present and protoParent is not null, then + // Let constructor be the result of parsing the source text + // constructor(...args) { super (...args);} + // using the syntactic grammar with the goal symbol MethodDefinition[~Yield]. + // Else, + // Let constructor be the result of parsing the source text + // constructor( ){ } + // using the syntactic grammar with the goal symbol MethodDefinition[~Yield]. + // + // While we could emit the '...args' rest parameter, certain later tools in the pipeline might + // downlevel the '...args' portion less efficiently by naively copying the contents of 'arguments' to an array. + // Instead, we'll avoid using a rest parameter and spread into the super call as + // 'super(...arguments)' instead of 'super(...args)', as you can see in "transformConstructorBody". + return ts.visitParameterList(constructor && constructor.parameters, visitor, context) + || []; + } + /** + * Transforms (or creates) a constructor body for a class with parameter property + * assignments or instance property initializers. + * + * @param node The current class. + * @param constructor The current class constructor. + * @param isDerivedClass A value indicating whether the class has an extends clause that does not extend 'null'. + */ + function transformConstructorBody(node, constructor, isDerivedClass) { + var statements = []; + var indexOfFirstStatement = 0; + resumeLexicalEnvironment(); + if (constructor) { + indexOfFirstStatement = addPrologueDirectivesAndInitialSuperCall(constructor, statements); + // Add parameters with property assignments. Transforms this: + // + // constructor (public x, public y) { + // } + // + // Into this: + // + // constructor (x, y) { + // this.x = x; + // this.y = y; + // } + // + var propertyAssignments = getParametersWithPropertyAssignments(constructor); + ts.addRange(statements, ts.map(propertyAssignments, transformParameterWithPropertyAssignment)); + } + else if (isDerivedClass) { + // Add a synthetic `super` call: + // + // super(...arguments); + // + statements.push(ts.createExpressionStatement(ts.createCall(ts.createSuper(), + /*typeArguments*/ undefined, [ts.createSpread(ts.createIdentifier("arguments"))]))); + } + // Add the property initializers. Transforms this: + // + // public x = 1; + // + // Into this: + // + // constructor() { + // this.x = 1; + // } + // + var properties = getInitializedProperties(node, /*isStatic*/ false); + addInitializedPropertyStatements(statements, properties, ts.createThis()); + if (constructor) { + // The class already had a constructor, so we should add the existing statements, skipping the initial super call. + ts.addRange(statements, ts.visitNodes(constructor.body.statements, visitor, ts.isStatement, indexOfFirstStatement)); + } + // End the lexical environment. + statements = ts.mergeLexicalEnvironment(statements, endLexicalEnvironment()); + return ts.setTextRange(ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), + /*location*/ constructor ? constructor.body.statements : node.members), + /*multiLine*/ true), + /*location*/ constructor ? constructor.body : undefined); + } + /** + * Adds super call and preceding prologue directives into the list of statements. + * + * @param ctor The constructor node. + * @returns index of the statement that follows super call + */ + function addPrologueDirectivesAndInitialSuperCall(ctor, result) { + if (ctor.body) { + var statements = ctor.body.statements; + // add prologue directives to the list (if any) + var index = ts.addPrologue(result, statements, /*ensureUseStrict*/ false, visitor); + if (index === statements.length) { + // list contains nothing but prologue directives (or empty) - exit + return index; + } + var statement = statements[index]; + if (statement.kind === 221 /* ExpressionStatement */ && ts.isSuperCall(statement.expression)) { + result.push(ts.visitNode(statement, visitor, ts.isStatement)); + return index + 1; + } + return index; + } + return 0; + } + /** + * Gets all parameters of a constructor that should be transformed into property assignments. + * + * @param node The constructor node. + */ + function getParametersWithPropertyAssignments(node) { + return ts.filter(node.parameters, isParameterWithPropertyAssignment); + } + /** + * Determines whether a parameter should be transformed into a property assignment. + * + * @param parameter The parameter node. + */ + function isParameterWithPropertyAssignment(parameter) { + return ts.hasModifier(parameter, 92 /* ParameterPropertyModifier */) + && ts.isIdentifier(parameter.name); + } + /** + * Transforms a parameter into a property assignment statement. + * + * @param node The parameter declaration. + */ + function transformParameterWithPropertyAssignment(node) { + ts.Debug.assert(ts.isIdentifier(node.name)); + var name = node.name; + var propertyName = ts.getMutableClone(name); + ts.setEmitFlags(propertyName, 1536 /* NoComments */ | 48 /* NoSourceMap */); + var localName = ts.getMutableClone(name); + ts.setEmitFlags(localName, 1536 /* NoComments */); + return ts.startOnNewLine(ts.setEmitFlags(ts.setTextRange(ts.createExpressionStatement(ts.createAssignment(ts.setTextRange(ts.createPropertyAccess(ts.createThis(), propertyName), node.name), localName)), ts.moveRangePos(node, -1)), 1536 /* NoComments */)); + } + /** + * Gets all property declarations with initializers on either the static or instance side of a class. + * + * @param node The class node. + * @param isStatic A value indicating whether to get properties from the static or instance side of the class. + */ + function getInitializedProperties(node, isStatic) { + return ts.filter(node.members, isStatic ? isStaticInitializedProperty : isInstanceInitializedProperty); + } + /** + * Gets a value indicating whether a class element is a static property declaration with an initializer. + * + * @param member The class element node. + */ + function isStaticInitializedProperty(member) { + return isInitializedProperty(member, /*isStatic*/ true); + } + /** + * Gets a value indicating whether a class element is an instance property declaration with an initializer. + * + * @param member The class element node. + */ + function isInstanceInitializedProperty(member) { + return isInitializedProperty(member, /*isStatic*/ false); + } + /** + * Gets a value indicating whether a class element is either a static or an instance property declaration with an initializer. + * + * @param member The class element node. + * @param isStatic A value indicating whether the member should be a static or instance member. + */ + function isInitializedProperty(member, isStatic) { + return member.kind === 154 /* PropertyDeclaration */ + && isStatic === ts.hasModifier(member, 32 /* Static */) + && member.initializer !== undefined; + } + /** + * Generates assignment statements for property initializers. + * + * @param properties An array of property declarations to transform. + * @param receiver The receiver on which each property should be assigned. + */ + function addInitializedPropertyStatements(statements, properties, receiver) { + for (var _i = 0, properties_9 = properties; _i < properties_9.length; _i++) { + var property = properties_9[_i]; + var statement = ts.createExpressionStatement(transformInitializedProperty(property, receiver)); + ts.setSourceMapRange(statement, ts.moveRangePastModifiers(property)); + ts.setCommentRange(statement, property); + ts.setOriginalNode(statement, property); + statements.push(statement); + } + } + /** + * Generates assignment expressions for property initializers. + * + * @param properties An array of property declarations to transform. + * @param receiver The receiver on which each property should be assigned. + */ + function generateInitializedPropertyExpressions(properties, receiver) { + var expressions = []; + for (var _i = 0, properties_10 = properties; _i < properties_10.length; _i++) { + var property = properties_10[_i]; + var expression = transformInitializedProperty(property, receiver); + ts.startOnNewLine(expression); + ts.setSourceMapRange(expression, ts.moveRangePastModifiers(property)); + ts.setCommentRange(expression, property); + ts.setOriginalNode(expression, property); + expressions.push(expression); + } + return expressions; + } + /** + * Transforms a property initializer into an assignment statement. + * + * @param property The property declaration. + * @param receiver The object receiving the property assignment. + */ + function transformInitializedProperty(property, receiver) { + // We generate a name here in order to reuse the value cached by the relocated computed name expression (which uses the same generated name) + var propertyName = ts.isComputedPropertyName(property.name) && !isSimpleInlineableExpression(property.name.expression) + ? ts.updateComputedPropertyName(property.name, ts.getGeneratedNameForNode(property.name)) + : property.name; + var initializer = ts.visitNode(property.initializer, visitor, ts.isExpression); + var memberAccess = ts.createMemberAccessForPropertyName(receiver, propertyName, /*location*/ propertyName); + return ts.createAssignment(memberAccess, initializer); + } + /** + * Gets either the static or instance members of a class that are decorated, or have + * parameters that are decorated. + * + * @param node The class containing the member. + * @param isStatic A value indicating whether to retrieve static or instance members of + * the class. + */ + function getDecoratedClassElements(node, isStatic) { + return ts.filter(node.members, isStatic ? function (m) { return isStaticDecoratedClassElement(m, node); } : function (m) { return isInstanceDecoratedClassElement(m, node); }); + } + /** + * Determines whether a class member is a static member of a class that is decorated, or + * has parameters that are decorated. + * + * @param member The class member. + */ + function isStaticDecoratedClassElement(member, parent) { + return isDecoratedClassElement(member, /*isStatic*/ true, parent); + } + /** + * Determines whether a class member is an instance member of a class that is decorated, + * or has parameters that are decorated. + * + * @param member The class member. + */ + function isInstanceDecoratedClassElement(member, parent) { + return isDecoratedClassElement(member, /*isStatic*/ false, parent); + } + /** + * Determines whether a class member is either a static or an instance member of a class + * that is decorated, or has parameters that are decorated. + * + * @param member The class member. + */ + function isDecoratedClassElement(member, isStatic, parent) { + return ts.nodeOrChildIsDecorated(member, parent) + && isStatic === ts.hasModifier(member, 32 /* Static */); + } + /** + * Gets an array of arrays of decorators for the parameters of a function-like node. + * The offset into the result array should correspond to the offset of the parameter. + * + * @param node The function-like node. + */ + function getDecoratorsOfParameters(node) { + var decorators; + if (node) { + var parameters = node.parameters; + for (var i = 0; i < parameters.length; i++) { + var parameter = parameters[i]; + if (decorators || parameter.decorators) { + if (!decorators) { + decorators = new Array(parameters.length); + } + decorators[i] = parameter.decorators; + } + } + } + return decorators; + } + /** + * Gets an AllDecorators object containing the decorators for the class and the decorators for the + * parameters of the constructor of the class. + * + * @param node The class node. + */ + function getAllDecoratorsOfConstructor(node) { + var decorators = node.decorators; + var parameters = getDecoratorsOfParameters(ts.getFirstConstructorWithBody(node)); + if (!decorators && !parameters) { + return undefined; + } + return { + decorators: decorators, + parameters: parameters + }; + } + /** + * Gets an AllDecorators object containing the decorators for the member and its parameters. + * + * @param node The class node that contains the member. + * @param member The class member. + */ + function getAllDecoratorsOfClassElement(node, member) { + switch (member.kind) { + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + return getAllDecoratorsOfAccessors(node, member); + case 156 /* MethodDeclaration */: + return getAllDecoratorsOfMethod(member); + case 154 /* PropertyDeclaration */: + return getAllDecoratorsOfProperty(member); + default: + return undefined; + } + } + /** + * Gets an AllDecorators object containing the decorators for the accessor and its parameters. + * + * @param node The class node that contains the accessor. + * @param accessor The class accessor member. + */ + function getAllDecoratorsOfAccessors(node, accessor) { + if (!accessor.body) { + return undefined; + } + var _a = ts.getAllAccessorDeclarations(node.members, accessor), firstAccessor = _a.firstAccessor, secondAccessor = _a.secondAccessor, setAccessor = _a.setAccessor; + var firstAccessorWithDecorators = firstAccessor.decorators ? firstAccessor : secondAccessor && secondAccessor.decorators ? secondAccessor : undefined; + if (!firstAccessorWithDecorators || accessor !== firstAccessorWithDecorators) { + return undefined; + } + var decorators = firstAccessorWithDecorators.decorators; + var parameters = getDecoratorsOfParameters(setAccessor); + if (!decorators && !parameters) { + return undefined; + } + return { decorators: decorators, parameters: parameters }; + } + /** + * Gets an AllDecorators object containing the decorators for the method and its parameters. + * + * @param method The class method member. + */ + function getAllDecoratorsOfMethod(method) { + if (!method.body) { + return undefined; + } + var decorators = method.decorators; + var parameters = getDecoratorsOfParameters(method); + if (!decorators && !parameters) { + return undefined; + } + return { decorators: decorators, parameters: parameters }; + } + /** + * Gets an AllDecorators object containing the decorators for the property. + * + * @param property The class property member. + */ + function getAllDecoratorsOfProperty(property) { + var decorators = property.decorators; + if (!decorators) { + return undefined; + } + return { decorators: decorators }; + } + /** + * Transforms all of the decorators for a declaration into an array of expressions. + * + * @param node The declaration node. + * @param allDecorators An object containing all of the decorators for the declaration. + */ + function transformAllDecoratorsOfDeclaration(node, container, allDecorators) { + if (!allDecorators) { + return undefined; + } + var decoratorExpressions = []; + ts.addRange(decoratorExpressions, ts.map(allDecorators.decorators, transformDecorator)); + ts.addRange(decoratorExpressions, ts.flatMap(allDecorators.parameters, transformDecoratorsOfParameter)); + addTypeMetadata(node, container, decoratorExpressions); + return decoratorExpressions; + } + /** + * Generates statements used to apply decorators to either the static or instance members + * of a class. + * + * @param node The class node. + * @param isStatic A value indicating whether to generate statements for static or + * instance members. + */ + function addClassElementDecorationStatements(statements, node, isStatic) { + ts.addRange(statements, ts.map(generateClassElementDecorationExpressions(node, isStatic), expressionToStatement)); + } + /** + * Generates expressions used to apply decorators to either the static or instance members + * of a class. + * + * @param node The class node. + * @param isStatic A value indicating whether to generate expressions for static or + * instance members. + */ + function generateClassElementDecorationExpressions(node, isStatic) { + var members = getDecoratedClassElements(node, isStatic); + var expressions; + for (var _i = 0, members_5 = members; _i < members_5.length; _i++) { + var member = members_5[_i]; + var expression = generateClassElementDecorationExpression(node, member); + if (expression) { + if (!expressions) { + expressions = [expression]; + } + else { + expressions.push(expression); + } + } + } + return expressions; + } + /** + * Generates an expression used to evaluate class element decorators at runtime. + * + * @param node The class node that contains the member. + * @param member The class member. + */ + function generateClassElementDecorationExpression(node, member) { + var allDecorators = getAllDecoratorsOfClassElement(node, member); + var decoratorExpressions = transformAllDecoratorsOfDeclaration(member, node, allDecorators); + if (!decoratorExpressions) { + return undefined; + } + // Emit the call to __decorate. Given the following: + // + // class C { + // @dec method(@dec2 x) {} + // @dec get accessor() {} + // @dec prop; + // } + // + // The emit for a method is: + // + // __decorate([ + // dec, + // __param(0, dec2), + // __metadata("design:type", Function), + // __metadata("design:paramtypes", [Object]), + // __metadata("design:returntype", void 0) + // ], C.prototype, "method", null); + // + // The emit for an accessor is: + // + // __decorate([ + // dec + // ], C.prototype, "accessor", null); + // + // The emit for a property is: + // + // __decorate([ + // dec + // ], C.prototype, "prop"); + // + var prefix = getClassMemberPrefix(node, member); + var memberName = getExpressionForPropertyName(member, /*generateNameForComputedPropertyName*/ true); + var descriptor = languageVersion > 0 /* ES3 */ + ? member.kind === 154 /* PropertyDeclaration */ + // We emit `void 0` here to indicate to `__decorate` that it can invoke `Object.defineProperty` directly, but that it + // should not invoke `Object.getOwnPropertyDescriptor`. + ? ts.createVoidZero() + // We emit `null` here to indicate to `__decorate` that it can invoke `Object.getOwnPropertyDescriptor` directly. + // We have this extra argument here so that we can inject an explicit property descriptor at a later date. + : ts.createNull() + : undefined; + var helper = createDecorateHelper(context, decoratorExpressions, prefix, memberName, descriptor, ts.moveRangePastDecorators(member)); + ts.setEmitFlags(helper, 1536 /* NoComments */); + return helper; + } + /** + * Generates a __decorate helper call for a class constructor. + * + * @param node The class node. + */ + function addConstructorDecorationStatement(statements, node) { + var expression = generateConstructorDecorationExpression(node); + if (expression) { + statements.push(ts.setOriginalNode(ts.createExpressionStatement(expression), node)); + } + } + /** + * Generates a __decorate helper call for a class constructor. + * + * @param node The class node. + */ + function generateConstructorDecorationExpression(node) { + var allDecorators = getAllDecoratorsOfConstructor(node); + var decoratorExpressions = transformAllDecoratorsOfDeclaration(node, node, allDecorators); + if (!decoratorExpressions) { + return undefined; + } + var classAlias = classAliases && classAliases[ts.getOriginalNodeId(node)]; + var localName = ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true); + var decorate = createDecorateHelper(context, decoratorExpressions, localName); + var expression = ts.createAssignment(localName, classAlias ? ts.createAssignment(classAlias, decorate) : decorate); + ts.setEmitFlags(expression, 1536 /* NoComments */); + ts.setSourceMapRange(expression, ts.moveRangePastDecorators(node)); + return expression; + } + /** + * Transforms a decorator into an expression. + * + * @param decorator The decorator node. + */ + function transformDecorator(decorator) { + return ts.visitNode(decorator.expression, visitor, ts.isExpression); + } + /** + * Transforms the decorators of a parameter. + * + * @param decorators The decorators for the parameter at the provided offset. + * @param parameterOffset The offset of the parameter. + */ + function transformDecoratorsOfParameter(decorators, parameterOffset) { + var expressions; + if (decorators) { + expressions = []; + for (var _i = 0, decorators_1 = decorators; _i < decorators_1.length; _i++) { + var decorator = decorators_1[_i]; + var helper = createParamHelper(context, transformDecorator(decorator), parameterOffset, + /*location*/ decorator.expression); + ts.setEmitFlags(helper, 1536 /* NoComments */); + expressions.push(helper); + } + } + return expressions; + } + /** + * Adds optional type metadata for a declaration. + * + * @param node The declaration node. + * @param decoratorExpressions The destination array to which to add new decorator expressions. + */ + function addTypeMetadata(node, container, decoratorExpressions) { + if (USE_NEW_TYPE_METADATA_FORMAT) { + addNewTypeMetadata(node, container, decoratorExpressions); + } + else { + addOldTypeMetadata(node, container, decoratorExpressions); + } + } + function addOldTypeMetadata(node, container, decoratorExpressions) { + if (compilerOptions.emitDecoratorMetadata) { + if (shouldAddTypeMetadata(node)) { + decoratorExpressions.push(createMetadataHelper(context, "design:type", serializeTypeOfNode(node))); + } + if (shouldAddParamTypesMetadata(node)) { + decoratorExpressions.push(createMetadataHelper(context, "design:paramtypes", serializeParameterTypesOfNode(node, container))); + } + if (shouldAddReturnTypeMetadata(node)) { + decoratorExpressions.push(createMetadataHelper(context, "design:returntype", serializeReturnTypeOfNode(node))); + } + } + } + function addNewTypeMetadata(node, container, decoratorExpressions) { + if (compilerOptions.emitDecoratorMetadata) { + var properties = void 0; + if (shouldAddTypeMetadata(node)) { + (properties || (properties = [])).push(ts.createPropertyAssignment("type", ts.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, ts.createToken(37 /* EqualsGreaterThanToken */), serializeTypeOfNode(node)))); + } + if (shouldAddParamTypesMetadata(node)) { + (properties || (properties = [])).push(ts.createPropertyAssignment("paramTypes", ts.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, ts.createToken(37 /* EqualsGreaterThanToken */), serializeParameterTypesOfNode(node, container)))); + } + if (shouldAddReturnTypeMetadata(node)) { + (properties || (properties = [])).push(ts.createPropertyAssignment("returnType", ts.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, ts.createToken(37 /* EqualsGreaterThanToken */), serializeReturnTypeOfNode(node)))); + } + if (properties) { + decoratorExpressions.push(createMetadataHelper(context, "design:typeinfo", ts.createObjectLiteral(properties, /*multiLine*/ true))); + } + } + } + /** + * Determines whether to emit the "design:type" metadata based on the node's kind. + * The caller should have already tested whether the node has decorators and whether the + * emitDecoratorMetadata compiler option is set. + * + * @param node The node to test. + */ + function shouldAddTypeMetadata(node) { + var kind = node.kind; + return kind === 156 /* MethodDeclaration */ + || kind === 158 /* GetAccessor */ + || kind === 159 /* SetAccessor */ + || kind === 154 /* PropertyDeclaration */; + } + /** + * Determines whether to emit the "design:returntype" metadata based on the node's kind. + * The caller should have already tested whether the node has decorators and whether the + * emitDecoratorMetadata compiler option is set. + * + * @param node The node to test. + */ + function shouldAddReturnTypeMetadata(node) { + return node.kind === 156 /* MethodDeclaration */; + } + /** + * Determines whether to emit the "design:paramtypes" metadata based on the node's kind. + * The caller should have already tested whether the node has decorators and whether the + * emitDecoratorMetadata compiler option is set. + * + * @param node The node to test. + */ + function shouldAddParamTypesMetadata(node) { + switch (node.kind) { + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + return ts.getFirstConstructorWithBody(node) !== undefined; + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + return true; + } + return false; + } + function getAccessorTypeNode(node) { + var accessors = resolver.getAllAccessorDeclarations(node); + return accessors.setAccessor && ts.getSetAccessorTypeAnnotationNode(accessors.setAccessor) + || accessors.getAccessor && ts.getEffectiveReturnTypeNode(accessors.getAccessor); + } + /** + * Serializes the type of a node for use with decorator type metadata. + * + * @param node The node that should have its type serialized. + */ + function serializeTypeOfNode(node) { + switch (node.kind) { + case 154 /* PropertyDeclaration */: + case 151 /* Parameter */: + return serializeTypeNode(node.type); + case 159 /* SetAccessor */: + case 158 /* GetAccessor */: + return serializeTypeNode(getAccessorTypeNode(node)); + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 156 /* MethodDeclaration */: + return ts.createIdentifier("Function"); + default: + return ts.createVoidZero(); + } + } + /** + * Serializes the types of the parameters of a node for use with decorator type metadata. + * + * @param node The node that should have its parameter types serialized. + */ + function serializeParameterTypesOfNode(node, container) { + var valueDeclaration = ts.isClassLike(node) + ? ts.getFirstConstructorWithBody(node) + : ts.isFunctionLike(node) && ts.nodeIsPresent(node.body) + ? node + : undefined; + var expressions = []; + if (valueDeclaration) { + var parameters = getParametersOfDecoratedDeclaration(valueDeclaration, container); + var numParameters = parameters.length; + for (var i = 0; i < numParameters; i++) { + var parameter = parameters[i]; + if (i === 0 && ts.isIdentifier(parameter.name) && parameter.name.escapedText === "this") { + continue; + } + if (parameter.dotDotDotToken) { + expressions.push(serializeTypeNode(ts.getRestParameterElementType(parameter.type))); + } + else { + expressions.push(serializeTypeOfNode(parameter)); + } + } + } + return ts.createArrayLiteral(expressions); + } + function getParametersOfDecoratedDeclaration(node, container) { + if (container && node.kind === 158 /* GetAccessor */) { + var setAccessor = ts.getAllAccessorDeclarations(container.members, node).setAccessor; + if (setAccessor) { + return setAccessor.parameters; + } + } + return node.parameters; + } + /** + * Serializes the return type of a node for use with decorator type metadata. + * + * @param node The node that should have its return type serialized. + */ + function serializeReturnTypeOfNode(node) { + if (ts.isFunctionLike(node) && node.type) { + return serializeTypeNode(node.type); + } + else if (ts.isAsyncFunction(node)) { + return ts.createIdentifier("Promise"); + } + return ts.createVoidZero(); + } + /** + * Serializes a type node for use with decorator type metadata. + * + * Types are serialized in the following fashion: + * - Void types point to "undefined" (e.g. "void 0") + * - Function and Constructor types point to the global "Function" constructor. + * - Interface types with a call or construct signature types point to the global + * "Function" constructor. + * - Array and Tuple types point to the global "Array" constructor. + * - Type predicates and booleans point to the global "Boolean" constructor. + * - String literal types and strings point to the global "String" constructor. + * - Enum and number types point to the global "Number" constructor. + * - Symbol types point to the global "Symbol" constructor. + * - Type references to classes (or class-like variables) point to the constructor for the class. + * - Anything else points to the global "Object" constructor. + * + * @param node The type node to serialize. + */ + function serializeTypeNode(node) { + if (node === undefined) { + return ts.createIdentifier("Object"); + } + switch (node.kind) { + case 106 /* VoidKeyword */: + case 141 /* UndefinedKeyword */: + case 96 /* NullKeyword */: + case 132 /* NeverKeyword */: + return ts.createVoidZero(); + case 177 /* ParenthesizedType */: + return serializeTypeNode(node.type); + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + return ts.createIdentifier("Function"); + case 169 /* ArrayType */: + case 170 /* TupleType */: + return ts.createIdentifier("Array"); + case 163 /* TypePredicate */: + case 123 /* BooleanKeyword */: + return ts.createIdentifier("Boolean"); + case 138 /* StringKeyword */: + return ts.createIdentifier("String"); + case 136 /* ObjectKeyword */: + return ts.createIdentifier("Object"); + case 182 /* LiteralType */: + switch (node.literal.kind) { + case 10 /* StringLiteral */: + return ts.createIdentifier("String"); + case 8 /* NumericLiteral */: + return ts.createIdentifier("Number"); + case 9 /* BigIntLiteral */: + return getGlobalBigIntNameWithFallback(); + case 102 /* TrueKeyword */: + case 87 /* FalseKeyword */: + return ts.createIdentifier("Boolean"); + default: + return ts.Debug.failBadSyntaxKind(node.literal); + } + case 135 /* NumberKeyword */: + return ts.createIdentifier("Number"); + case 146 /* BigIntKeyword */: + return getGlobalBigIntNameWithFallback(); + case 139 /* SymbolKeyword */: + return languageVersion < 2 /* ES2015 */ + ? getGlobalSymbolNameWithFallback() + : ts.createIdentifier("Symbol"); + case 164 /* TypeReference */: + return serializeTypeReferenceNode(node); + case 174 /* IntersectionType */: + case 173 /* UnionType */: + return serializeTypeList(node.types); + case 175 /* ConditionalType */: + return serializeTypeList([node.trueType, node.falseType]); + case 167 /* TypeQuery */: + case 179 /* TypeOperator */: + case 180 /* IndexedAccessType */: + case 181 /* MappedType */: + case 168 /* TypeLiteral */: + case 120 /* AnyKeyword */: + case 143 /* UnknownKeyword */: + case 178 /* ThisType */: + case 183 /* ImportType */: + break; + default: + return ts.Debug.failBadSyntaxKind(node); + } + return ts.createIdentifier("Object"); + } + function serializeTypeList(types) { + // Note when updating logic here also update getEntityNameForDecoratorMetadata + // so that aliases can be marked as referenced + var serializedUnion; + for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { + var typeNode = types_17[_i]; + while (typeNode.kind === 177 /* ParenthesizedType */) { + typeNode = typeNode.type; // Skip parens if need be + } + if (typeNode.kind === 132 /* NeverKeyword */) { + continue; // Always elide `never` from the union/intersection if possible + } + if (!strictNullChecks && (typeNode.kind === 96 /* NullKeyword */ || typeNode.kind === 141 /* UndefinedKeyword */)) { + continue; // Elide null and undefined from unions for metadata, just like what we did prior to the implementation of strict null checks + } + var serializedIndividual = serializeTypeNode(typeNode); + if (ts.isIdentifier(serializedIndividual) && serializedIndividual.escapedText === "Object") { + // One of the individual is global object, return immediately + return serializedIndividual; + } + // If there exists union that is not void 0 expression, check if the the common type is identifier. + // anything more complex and we will just default to Object + else if (serializedUnion) { + // Different types + if (!ts.isIdentifier(serializedUnion) || + !ts.isIdentifier(serializedIndividual) || + serializedUnion.escapedText !== serializedIndividual.escapedText) { + return ts.createIdentifier("Object"); + } + } + else { + // Initialize the union type + serializedUnion = serializedIndividual; + } + } + // If we were able to find common type, use it + return serializedUnion || ts.createVoidZero(); // Fallback is only hit if all union constituients are null/undefined/never + } + /** + * Serializes a TypeReferenceNode to an appropriate JS constructor value for use with + * decorator type metadata. + * + * @param node The type reference node. + */ + function serializeTypeReferenceNode(node) { + var kind = resolver.getTypeReferenceSerializationKind(node.typeName, currentNameScope || currentLexicalScope); + switch (kind) { + case ts.TypeReferenceSerializationKind.Unknown: + // From conditional type type reference that cannot be resolved is Similar to any or unknown + if (ts.findAncestor(node, function (n) { return n.parent && ts.isConditionalTypeNode(n.parent) && (n.parent.trueType === n || n.parent.falseType === n); })) { + return ts.createIdentifier("Object"); + } + var serialized = serializeEntityNameAsExpressionFallback(node.typeName); + var temp = ts.createTempVariable(hoistVariableDeclaration); + return ts.createConditional(ts.createTypeCheck(ts.createAssignment(temp, serialized), "function"), temp, ts.createIdentifier("Object")); + case ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue: + return serializeEntityNameAsExpression(node.typeName); + case ts.TypeReferenceSerializationKind.VoidNullableOrNeverType: + return ts.createVoidZero(); + case ts.TypeReferenceSerializationKind.BigIntLikeType: + return getGlobalBigIntNameWithFallback(); + case ts.TypeReferenceSerializationKind.BooleanType: + return ts.createIdentifier("Boolean"); + case ts.TypeReferenceSerializationKind.NumberLikeType: + return ts.createIdentifier("Number"); + case ts.TypeReferenceSerializationKind.StringLikeType: + return ts.createIdentifier("String"); + case ts.TypeReferenceSerializationKind.ArrayLikeType: + return ts.createIdentifier("Array"); + case ts.TypeReferenceSerializationKind.ESSymbolType: + return languageVersion < 2 /* ES2015 */ + ? getGlobalSymbolNameWithFallback() + : ts.createIdentifier("Symbol"); + case ts.TypeReferenceSerializationKind.TypeWithCallSignature: + return ts.createIdentifier("Function"); + case ts.TypeReferenceSerializationKind.Promise: + return ts.createIdentifier("Promise"); + case ts.TypeReferenceSerializationKind.ObjectType: + return ts.createIdentifier("Object"); + default: + return ts.Debug.assertNever(kind); + } + } + function createCheckedValue(left, right) { + return ts.createLogicalAnd(ts.createStrictInequality(ts.createTypeOf(left), ts.createLiteral("undefined")), right); + } + /** + * Serializes an entity name which may not exist at runtime, but whose access shouldn't throw + * + * @param node The entity name to serialize. + */ + function serializeEntityNameAsExpressionFallback(node) { + if (node.kind === 72 /* Identifier */) { + // A -> typeof A !== undefined && A + var copied = serializeEntityNameAsExpression(node); + return createCheckedValue(copied, copied); + } + if (node.left.kind === 72 /* Identifier */) { + // A.B -> typeof A !== undefined && A.B + return createCheckedValue(serializeEntityNameAsExpression(node.left), serializeEntityNameAsExpression(node)); + } + // A.B.C -> typeof A !== undefined && (_a = A.B) !== void 0 && _a.C + var left = serializeEntityNameAsExpressionFallback(node.left); + var temp = ts.createTempVariable(hoistVariableDeclaration); + return ts.createLogicalAnd(ts.createLogicalAnd(left.left, ts.createStrictInequality(ts.createAssignment(temp, left.right), ts.createVoidZero())), ts.createPropertyAccess(temp, node.right)); + } + /** + * Serializes an entity name as an expression for decorator type metadata. + * + * @param node The entity name to serialize. + */ + function serializeEntityNameAsExpression(node) { + switch (node.kind) { + case 72 /* Identifier */: + // Create a clone of the name with a new parent, and treat it as if it were + // a source tree node for the purposes of the checker. + var name = ts.getMutableClone(node); + name.flags &= ~8 /* Synthesized */; + name.original = undefined; + name.parent = ts.getParseTreeNode(currentLexicalScope); // ensure the parent is set to a parse tree node. + return name; + case 148 /* QualifiedName */: + return serializeQualifiedNameAsExpression(node); + } + } + /** + * Serializes an qualified name as an expression for decorator type metadata. + * + * @param node The qualified name to serialize. + * @param useFallback A value indicating whether to use logical operators to test for the + * qualified name at runtime. + */ + function serializeQualifiedNameAsExpression(node) { + return ts.createPropertyAccess(serializeEntityNameAsExpression(node.left), node.right); + } + /** + * Gets an expression that points to the global "Symbol" constructor at runtime if it is + * available. + */ + function getGlobalSymbolNameWithFallback() { + return ts.createConditional(ts.createTypeCheck(ts.createIdentifier("Symbol"), "function"), ts.createIdentifier("Symbol"), ts.createIdentifier("Object")); + } + /** + * Gets an expression that points to the global "BigInt" constructor at runtime if it is + * available. + */ + function getGlobalBigIntNameWithFallback() { + return languageVersion < 6 /* ESNext */ + ? ts.createConditional(ts.createTypeCheck(ts.createIdentifier("BigInt"), "function"), ts.createIdentifier("BigInt"), ts.createIdentifier("Object")) + : ts.createIdentifier("BigInt"); + } + /** + * A simple inlinable expression is an expression which can be copied into multiple locations + * without risk of repeating any sideeffects and whose value could not possibly change between + * any such locations + */ + function isSimpleInlineableExpression(expression) { + return !ts.isIdentifier(expression) && ts.isSimpleCopiableExpression(expression) || + ts.isWellKnownSymbolSyntactically(expression); + } + /** + * Gets an expression that represents a property name. For a computed property, a + * name is generated for the node. + * + * @param member The member whose name should be converted into an expression. + */ + function getExpressionForPropertyName(member, generateNameForComputedPropertyName) { + var name = member.name; + if (ts.isComputedPropertyName(name)) { + return generateNameForComputedPropertyName && !isSimpleInlineableExpression(name.expression) + ? ts.getGeneratedNameForNode(name) + : name.expression; + } + else if (ts.isIdentifier(name)) { + return ts.createLiteral(ts.idText(name)); + } + else { + return ts.getSynthesizedClone(name); + } + } + /** + * If the name is a computed property, this function transforms it, then either returns an expression which caches the + * value of the result or the expression itself if the value is either unused or safe to inline into multiple locations + * @param shouldHoist Does the expression need to be reused? (ie, for an initializer or a decorator) + * @param omitSimple Should expressions with no observable side-effects be elided? (ie, the expression is not hoisted for a decorator or initializer and is a literal) + */ + function getPropertyNameExpressionIfNeeded(name, shouldHoist, omitSimple) { + if (ts.isComputedPropertyName(name)) { + var expression = ts.visitNode(name.expression, visitor, ts.isExpression); + var innerExpression = ts.skipPartiallyEmittedExpressions(expression); + var inlinable = isSimpleInlineableExpression(innerExpression); + if (!inlinable && shouldHoist) { + var generatedName = ts.getGeneratedNameForNode(name); + hoistVariableDeclaration(generatedName); + return ts.createAssignment(generatedName, expression); + } + return (omitSimple && (inlinable || ts.isIdentifier(innerExpression))) ? undefined : expression; + } + } + /** + * Visits the property name of a class element, for use when emitting property + * initializers. For a computed property on a node with decorators, a temporary + * value is stored for later use. + * + * @param member The member whose name should be visited. + */ + function visitPropertyNameOfClassElement(member) { + var name = member.name; + var expr = getPropertyNameExpressionIfNeeded(name, ts.some(member.decorators), /*omitSimple*/ false); + if (expr) { // expr only exists if `name` is a computed property name + // Inline any pending expressions from previous elided or relocated computed property name expressions in order to preserve execution order + if (ts.some(pendingExpressions)) { + expr = ts.inlineExpressions(pendingExpressions.concat([expr])); + pendingExpressions.length = 0; + } + return ts.updateComputedPropertyName(name, expr); + } + else { + return name; + } + } + /** + * Transforms a HeritageClause with TypeScript syntax. + * + * This function will only be called when one of the following conditions are met: + * - The node is a non-`extends` heritage clause that should be elided. + * - The node is an `extends` heritage clause that should be visited, but only allow a single type. + * + * @param node The HeritageClause to transform. + */ + function visitHeritageClause(node) { + if (node.token === 86 /* ExtendsKeyword */) { + var types = ts.visitNodes(node.types, visitor, ts.isExpressionWithTypeArguments, 0, 1); + return ts.setTextRange(ts.createHeritageClause(86 /* ExtendsKeyword */, types), node); + } + return undefined; + } + /** + * Transforms an ExpressionWithTypeArguments with TypeScript syntax. + * + * This function will only be called when one of the following conditions are met: + * - The node contains type arguments that should be elided. + * + * @param node The ExpressionWithTypeArguments to transform. + */ + function visitExpressionWithTypeArguments(node) { + return ts.updateExpressionWithTypeArguments(node, + /*typeArguments*/ undefined, ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression)); + } + /** + * Determines whether to emit a function-like declaration. We should not emit the + * declaration if it does not have a body. + * + * @param node The declaration node. + */ + function shouldEmitFunctionLikeDeclaration(node) { + return !ts.nodeIsMissing(node.body); + } + function visitPropertyDeclaration(node) { + var expr = getPropertyNameExpressionIfNeeded(node.name, ts.some(node.decorators) || !!node.initializer, /*omitSimple*/ true); + if (expr && !isSimpleInlineableExpression(expr)) { + (pendingExpressions || (pendingExpressions = [])).push(expr); + } + return undefined; + } + function visitConstructor(node) { + if (!shouldEmitFunctionLikeDeclaration(node)) { + return undefined; + } + return ts.updateConstructor(node, ts.visitNodes(node.decorators, visitor, ts.isDecorator), ts.visitNodes(node.modifiers, visitor, ts.isModifier), ts.visitParameterList(node.parameters, visitor, context), ts.visitFunctionBody(node.body, visitor, context)); + } + /** + * Visits a method declaration of a class. + * + * This function will be called when one of the following conditions are met: + * - The node is an overload + * - The node is marked as abstract, public, private, protected, or readonly + * - The node has a computed property name + * + * @param node The method node. + */ + function visitMethodDeclaration(node) { + if (!shouldEmitFunctionLikeDeclaration(node)) { + return undefined; + } + var updated = ts.updateMethod(node, + /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, visitPropertyNameOfClassElement(node), + /*questionToken*/ undefined, + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context)); + if (updated !== node) { + // While we emit the source map for the node after skipping decorators and modifiers, + // we need to emit the comments for the original range. + ts.setCommentRange(updated, node); + ts.setSourceMapRange(updated, ts.moveRangePastDecorators(node)); + } + return updated; + } + /** + * Determines whether to emit an accessor declaration. We should not emit the + * declaration if it does not have a body and is abstract. + * + * @param node The declaration node. + */ + function shouldEmitAccessorDeclaration(node) { + return !(ts.nodeIsMissing(node.body) && ts.hasModifier(node, 128 /* Abstract */)); + } + /** + * Visits a get accessor declaration of a class. + * + * This function will be called when one of the following conditions are met: + * - The node is marked as abstract, public, private, or protected + * - The node has a computed property name + * + * @param node The get accessor node. + */ + function visitGetAccessor(node) { + if (!shouldEmitAccessorDeclaration(node)) { + return undefined; + } + var updated = ts.updateGetAccessor(node, + /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), visitPropertyNameOfClassElement(node), ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context) || ts.createBlock([])); + if (updated !== node) { + // While we emit the source map for the node after skipping decorators and modifiers, + // we need to emit the comments for the original range. + ts.setCommentRange(updated, node); + ts.setSourceMapRange(updated, ts.moveRangePastDecorators(node)); + } + return updated; + } + /** + * Visits a set accessor declaration of a class. + * + * This function will be called when one of the following conditions are met: + * - The node is marked as abstract, public, private, or protected + * - The node has a computed property name + * + * @param node The set accessor node. + */ + function visitSetAccessor(node) { + if (!shouldEmitAccessorDeclaration(node)) { + return undefined; + } + var updated = ts.updateSetAccessor(node, + /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), visitPropertyNameOfClassElement(node), ts.visitParameterList(node.parameters, visitor, context), ts.visitFunctionBody(node.body, visitor, context) || ts.createBlock([])); + if (updated !== node) { + // While we emit the source map for the node after skipping decorators and modifiers, + // we need to emit the comments for the original range. + ts.setCommentRange(updated, node); + ts.setSourceMapRange(updated, ts.moveRangePastDecorators(node)); + } + return updated; + } + /** + * Visits a function declaration. + * + * This function will be called when one of the following conditions are met: + * - The node is an overload + * - The node is exported from a TypeScript namespace + * - The node has decorators + * + * @param node The function node. + */ + function visitFunctionDeclaration(node) { + if (!shouldEmitFunctionLikeDeclaration(node)) { + return ts.createNotEmittedStatement(node); + } + var updated = ts.updateFunctionDeclaration(node, + /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, node.name, + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context) || ts.createBlock([])); + if (isExportOfNamespace(node)) { + var statements = [updated]; + addExportMemberAssignment(statements, node); + return statements; + } + return updated; + } + /** + * Visits a function expression node. + * + * This function will be called when one of the following conditions are met: + * - The node has type annotations + * + * @param node The function expression node. + */ + function visitFunctionExpression(node) { + if (!shouldEmitFunctionLikeDeclaration(node)) { + return ts.createOmittedExpression(); + } + var updated = ts.updateFunctionExpression(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, node.name, + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context) || ts.createBlock([])); + return updated; + } + /** + * @remarks + * This function will be called when one of the following conditions are met: + * - The node has type annotations + */ + function visitArrowFunction(node) { + var updated = ts.updateArrowFunction(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, node.equalsGreaterThanToken, ts.visitFunctionBody(node.body, visitor, context)); + return updated; + } + /** + * Visits a parameter declaration node. + * + * This function will be called when one of the following conditions are met: + * - The node has an accessibility modifier. + * - The node has a questionToken. + * - The node's kind is ThisKeyword. + * + * @param node The parameter declaration node. + */ + function visitParameter(node) { + if (ts.parameterIsThisKeyword(node)) { + return undefined; + } + var parameter = ts.createParameter( + /*decorators*/ undefined, + /*modifiers*/ undefined, node.dotDotDotToken, ts.visitNode(node.name, visitor, ts.isBindingName), + /*questionToken*/ undefined, + /*type*/ undefined, ts.visitNode(node.initializer, visitor, ts.isExpression)); + // While we emit the source map for the node after skipping decorators and modifiers, + // we need to emit the comments for the original range. + ts.setOriginalNode(parameter, node); + ts.setTextRange(parameter, ts.moveRangePastModifiers(node)); + ts.setCommentRange(parameter, node); + ts.setSourceMapRange(parameter, ts.moveRangePastModifiers(node)); + ts.setEmitFlags(parameter.name, 32 /* NoTrailingSourceMap */); + return parameter; + } + /** + * Visits a variable statement in a namespace. + * + * This function will be called when one of the following conditions are met: + * - The node is exported from a TypeScript namespace. + */ + function visitVariableStatement(node) { + if (isExportOfNamespace(node)) { + var variables = ts.getInitializedVariables(node.declarationList); + if (variables.length === 0) { + // elide statement if there are no initialized variables. + return undefined; + } + return ts.setTextRange(ts.createExpressionStatement(ts.inlineExpressions(ts.map(variables, transformInitializedVariable))), node); + } + else { + return ts.visitEachChild(node, visitor, context); + } + } + function transformInitializedVariable(node) { + var name = node.name; + if (ts.isBindingPattern(name)) { + return ts.flattenDestructuringAssignment(node, visitor, context, 0 /* All */, + /*needsValue*/ false, createNamespaceExportExpression); + } + else { + return ts.setTextRange(ts.createAssignment(getNamespaceMemberNameWithSourceMapsAndWithoutComments(name), ts.visitNode(node.initializer, visitor, ts.isExpression)), + /*location*/ node); + } + } + function visitVariableDeclaration(node) { + return ts.updateVariableDeclaration(node, ts.visitNode(node.name, visitor, ts.isBindingName), + /*type*/ undefined, ts.visitNode(node.initializer, visitor, ts.isExpression)); + } + /** + * Visits a parenthesized expression that contains either a type assertion or an `as` + * expression. + * + * @param node The parenthesized expression node. + */ + function visitParenthesizedExpression(node) { + var innerExpression = ts.skipOuterExpressions(node.expression, ~2 /* Assertions */); + if (ts.isAssertionExpression(innerExpression)) { + // Make sure we consider all nested cast expressions, e.g.: + // (-A).x; + var expression = ts.visitNode(node.expression, visitor, ts.isExpression); + // We have an expression of the form: (SubExpr). Emitting this as (SubExpr) + // is really not desirable. We would like to emit the subexpression as-is. Omitting + // the parentheses, however, could cause change in the semantics of the generated + // code if the casted expression has a lower precedence than the rest of the + // expression. + // + // To preserve comments, we return a "PartiallyEmittedExpression" here which will + // preserve the position information of the original expression. + // + // Due to the auto-parenthesization rules used by the visitor and factory functions + // we can safely elide the parentheses here, as a new synthetic + // ParenthesizedExpression will be inserted if we remove parentheses too + // aggressively. + // HOWEVER - if there are leading comments on the expression itself, to handle ASI + // correctly for return and throw, we must keep the parenthesis + if (ts.length(ts.getLeadingCommentRangesOfNode(expression, currentSourceFile))) { + return ts.updateParen(node, expression); + } + return ts.createPartiallyEmittedExpression(expression, node); + } + return ts.visitEachChild(node, visitor, context); + } + function visitAssertionExpression(node) { + var expression = ts.visitNode(node.expression, visitor, ts.isExpression); + return ts.createPartiallyEmittedExpression(expression, node); + } + function visitNonNullExpression(node) { + var expression = ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression); + return ts.createPartiallyEmittedExpression(expression, node); + } + function visitCallExpression(node) { + return ts.updateCall(node, ts.visitNode(node.expression, visitor, ts.isExpression), + /*typeArguments*/ undefined, ts.visitNodes(node.arguments, visitor, ts.isExpression)); + } + function visitNewExpression(node) { + return ts.updateNew(node, ts.visitNode(node.expression, visitor, ts.isExpression), + /*typeArguments*/ undefined, ts.visitNodes(node.arguments, visitor, ts.isExpression)); + } + function visitTaggedTemplateExpression(node) { + return ts.updateTaggedTemplate(node, ts.visitNode(node.tag, visitor, ts.isExpression), + /*typeArguments*/ undefined, ts.visitNode(node.template, visitor, ts.isExpression)); + } + /** + * Determines whether to emit an enum declaration. + * + * @param node The enum declaration node. + */ + function shouldEmitEnumDeclaration(node) { + return !ts.isEnumConst(node) + || compilerOptions.preserveConstEnums + || compilerOptions.isolatedModules; + } + /** + * Visits an enum declaration. + * + * This function will be called any time a TypeScript enum is encountered. + * + * @param node The enum declaration node. + */ + function visitEnumDeclaration(node) { + if (!shouldEmitEnumDeclaration(node)) { + return undefined; + } + var statements = []; + // We request to be advised when the printer is about to print this node. This allows + // us to set up the correct state for later substitutions. + var emitFlags = 2 /* AdviseOnEmitNode */; + // If needed, we should emit a variable declaration for the enum. If we emit + // a leading variable declaration, we should not emit leading comments for the + // enum body. + var varAdded = addVarForEnumOrModuleDeclaration(statements, node); + if (varAdded) { + // We should still emit the comments if we are emitting a system module. + if (moduleKind !== ts.ModuleKind.System || currentLexicalScope !== currentSourceFile) { + emitFlags |= 512 /* NoLeadingComments */; + } + } + // `parameterName` is the declaration name used inside of the enum. + var parameterName = getNamespaceParameterName(node); + // `containerName` is the expression used inside of the enum for assignments. + var containerName = getNamespaceContainerName(node); + // `exportName` is the expression used within this node's container for any exported references. + var exportName = ts.hasModifier(node, 1 /* Export */) + ? ts.getExternalModuleOrNamespaceExportName(currentNamespaceContainerName, node, /*allowComments*/ false, /*allowSourceMaps*/ true) + : ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true); + // x || (x = {}) + // exports.x || (exports.x = {}) + var moduleArg = ts.createLogicalOr(exportName, ts.createAssignment(exportName, ts.createObjectLiteral())); + if (hasNamespaceQualifiedExportName(node)) { + // `localName` is the expression used within this node's containing scope for any local references. + var localName = ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true); + // x = (exports.x || (exports.x = {})) + moduleArg = ts.createAssignment(localName, moduleArg); + } + // (function (x) { + // x[x["y"] = 0] = "y"; + // ... + // })(x || (x = {})); + var enumStatement = ts.createExpressionStatement(ts.createCall(ts.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, parameterName)], + /*type*/ undefined, transformEnumBody(node, containerName)), + /*typeArguments*/ undefined, [moduleArg])); + ts.setOriginalNode(enumStatement, node); + if (varAdded) { + // If a variable was added, synthetic comments are emitted on it, not on the moduleStatement. + ts.setSyntheticLeadingComments(enumStatement, undefined); + ts.setSyntheticTrailingComments(enumStatement, undefined); + } + ts.setTextRange(enumStatement, node); + ts.addEmitFlags(enumStatement, emitFlags); + statements.push(enumStatement); + // Add a DeclarationMarker for the enum to preserve trailing comments and mark + // the end of the declaration. + statements.push(ts.createEndOfDeclarationMarker(node)); + return statements; + } + /** + * Transforms the body of an enum declaration. + * + * @param node The enum declaration node. + */ + function transformEnumBody(node, localName) { + var savedCurrentNamespaceLocalName = currentNamespaceContainerName; + currentNamespaceContainerName = localName; + var statements = []; + startLexicalEnvironment(); + var members = ts.map(node.members, transformEnumMember); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + ts.addRange(statements, members); + currentNamespaceContainerName = savedCurrentNamespaceLocalName; + return ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), /*location*/ node.members), + /*multiLine*/ true); + } + /** + * Transforms an enum member into a statement. + * + * @param member The enum member node. + */ + function transformEnumMember(member) { + // enums don't support computed properties + // we pass false as 'generateNameForComputedPropertyName' for a backward compatibility purposes + // old emitter always generate 'expression' part of the name as-is. + var name = getExpressionForPropertyName(member, /*generateNameForComputedPropertyName*/ false); + var valueExpression = transformEnumMemberDeclarationValue(member); + var innerAssignment = ts.createAssignment(ts.createElementAccess(currentNamespaceContainerName, name), valueExpression); + var outerAssignment = valueExpression.kind === 10 /* StringLiteral */ ? + innerAssignment : + ts.createAssignment(ts.createElementAccess(currentNamespaceContainerName, innerAssignment), name); + return ts.setTextRange(ts.createExpressionStatement(ts.setTextRange(outerAssignment, member)), member); + } + /** + * Transforms the value of an enum member. + * + * @param member The enum member node. + */ + function transformEnumMemberDeclarationValue(member) { + var value = resolver.getConstantValue(member); + if (value !== undefined) { + return ts.createLiteral(value); + } + else { + enableSubstitutionForNonQualifiedEnumMembers(); + if (member.initializer) { + return ts.visitNode(member.initializer, visitor, ts.isExpression); + } + else { + return ts.createVoidZero(); + } + } + } + /** + * Determines whether to elide a module declaration. + * + * @param node The module declaration node. + */ + function shouldEmitModuleDeclaration(node) { + return ts.isInstantiatedModule(node, !!compilerOptions.preserveConstEnums || !!compilerOptions.isolatedModules); + } + /** + * Determines whether an exported declaration will have a qualified export name (e.g. `f.x` + * or `exports.x`). + */ + function hasNamespaceQualifiedExportName(node) { + return isExportOfNamespace(node) + || (isExternalModuleExport(node) + && moduleKind !== ts.ModuleKind.ES2015 + && moduleKind !== ts.ModuleKind.ESNext + && moduleKind !== ts.ModuleKind.System); + } + /** + * Records that a declaration was emitted in the current scope, if it was the first + * declaration for the provided symbol. + */ + function recordEmittedDeclarationInScope(node) { + if (!currentScopeFirstDeclarationsOfName) { + currentScopeFirstDeclarationsOfName = ts.createUnderscoreEscapedMap(); + } + var name = declaredNameInScope(node); + if (!currentScopeFirstDeclarationsOfName.has(name)) { + currentScopeFirstDeclarationsOfName.set(name, node); + } + } + /** + * Determines whether a declaration is the first declaration with + * the same name emitted in the current scope. + */ + function isFirstEmittedDeclarationInScope(node) { + if (currentScopeFirstDeclarationsOfName) { + var name = declaredNameInScope(node); + return currentScopeFirstDeclarationsOfName.get(name) === node; + } + return true; + } + function declaredNameInScope(node) { + ts.Debug.assertNode(node.name, ts.isIdentifier); + return node.name.escapedText; + } + /** + * Adds a leading VariableStatement for a enum or module declaration. + */ + function addVarForEnumOrModuleDeclaration(statements, node) { + // Emit a variable statement for the module. We emit top-level enums as a `var` + // declaration to avoid static errors in global scripts scripts due to redeclaration. + // enums in any other scope are emitted as a `let` declaration. + var statement = ts.createVariableStatement(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.createVariableDeclarationList([ + ts.createVariableDeclaration(ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true)) + ], currentLexicalScope.kind === 279 /* SourceFile */ ? 0 /* None */ : 1 /* Let */)); + ts.setOriginalNode(statement, node); + recordEmittedDeclarationInScope(node); + if (isFirstEmittedDeclarationInScope(node)) { + // Adjust the source map emit to match the old emitter. + if (node.kind === 243 /* EnumDeclaration */) { + ts.setSourceMapRange(statement.declarationList, node); + } + else { + ts.setSourceMapRange(statement, node); + } + // Trailing comments for module declaration should be emitted after the function closure + // instead of the variable statement: + // + // /** Module comment*/ + // module m1 { + // function foo4Export() { + // } + // } // trailing comment module + // + // Should emit: + // + // /** Module comment*/ + // var m1; + // (function (m1) { + // function foo4Export() { + // } + // })(m1 || (m1 = {})); // trailing comment module + // + ts.setCommentRange(statement, node); + ts.addEmitFlags(statement, 1024 /* NoTrailingComments */ | 4194304 /* HasEndOfDeclarationMarker */); + statements.push(statement); + return true; + } + else { + // For an EnumDeclaration or ModuleDeclaration that merges with a preceeding + // declaration we do not emit a leading variable declaration. To preserve the + // begin/end semantics of the declararation and to properly handle exports + // we wrap the leading variable declaration in a `MergeDeclarationMarker`. + var mergeMarker = ts.createMergeDeclarationMarker(statement); + ts.setEmitFlags(mergeMarker, 1536 /* NoComments */ | 4194304 /* HasEndOfDeclarationMarker */); + statements.push(mergeMarker); + return false; + } + } + /** + * Visits a module declaration node. + * + * This function will be called any time a TypeScript namespace (ModuleDeclaration) is encountered. + * + * @param node The module declaration node. + */ + function visitModuleDeclaration(node) { + if (!shouldEmitModuleDeclaration(node)) { + return ts.createNotEmittedStatement(node); + } + ts.Debug.assertNode(node.name, ts.isIdentifier, "A TypeScript namespace should have an Identifier name."); + enableSubstitutionForNamespaceExports(); + var statements = []; + // We request to be advised when the printer is about to print this node. This allows + // us to set up the correct state for later substitutions. + var emitFlags = 2 /* AdviseOnEmitNode */; + // If needed, we should emit a variable declaration for the module. If we emit + // a leading variable declaration, we should not emit leading comments for the + // module body. + var varAdded = addVarForEnumOrModuleDeclaration(statements, node); + if (varAdded) { + // We should still emit the comments if we are emitting a system module. + if (moduleKind !== ts.ModuleKind.System || currentLexicalScope !== currentSourceFile) { + emitFlags |= 512 /* NoLeadingComments */; + } + } + // `parameterName` is the declaration name used inside of the namespace. + var parameterName = getNamespaceParameterName(node); + // `containerName` is the expression used inside of the namespace for exports. + var containerName = getNamespaceContainerName(node); + // `exportName` is the expression used within this node's container for any exported references. + var exportName = ts.hasModifier(node, 1 /* Export */) + ? ts.getExternalModuleOrNamespaceExportName(currentNamespaceContainerName, node, /*allowComments*/ false, /*allowSourceMaps*/ true) + : ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true); + // x || (x = {}) + // exports.x || (exports.x = {}) + var moduleArg = ts.createLogicalOr(exportName, ts.createAssignment(exportName, ts.createObjectLiteral())); + if (hasNamespaceQualifiedExportName(node)) { + // `localName` is the expression used within this node's containing scope for any local references. + var localName = ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true); + // x = (exports.x || (exports.x = {})) + moduleArg = ts.createAssignment(localName, moduleArg); + } + // (function (x_1) { + // x_1.y = ...; + // })(x || (x = {})); + var moduleStatement = ts.createExpressionStatement(ts.createCall(ts.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, parameterName)], + /*type*/ undefined, transformModuleBody(node, containerName)), + /*typeArguments*/ undefined, [moduleArg])); + ts.setOriginalNode(moduleStatement, node); + if (varAdded) { + // If a variable was added, synthetic comments are emitted on it, not on the moduleStatement. + ts.setSyntheticLeadingComments(moduleStatement, undefined); + ts.setSyntheticTrailingComments(moduleStatement, undefined); + } + ts.setTextRange(moduleStatement, node); + ts.addEmitFlags(moduleStatement, emitFlags); + statements.push(moduleStatement); + // Add a DeclarationMarker for the namespace to preserve trailing comments and mark + // the end of the declaration. + statements.push(ts.createEndOfDeclarationMarker(node)); + return statements; + } + /** + * Transforms the body of a module declaration. + * + * @param node The module declaration node. + */ + function transformModuleBody(node, namespaceLocalName) { + var savedCurrentNamespaceContainerName = currentNamespaceContainerName; + var savedCurrentNamespace = currentNamespace; + var savedCurrentScopeFirstDeclarationsOfName = currentScopeFirstDeclarationsOfName; + currentNamespaceContainerName = namespaceLocalName; + currentNamespace = node; + currentScopeFirstDeclarationsOfName = undefined; + var statements = []; + startLexicalEnvironment(); + var statementsLocation; + var blockLocation; + var body = node.body; + if (body.kind === 245 /* ModuleBlock */) { + saveStateAndInvoke(body, function (body) { return ts.addRange(statements, ts.visitNodes(body.statements, namespaceElementVisitor, ts.isStatement)); }); + statementsLocation = body.statements; + blockLocation = body; + } + else { + var result = visitModuleDeclaration(body); + if (result) { + if (ts.isArray(result)) { + ts.addRange(statements, result); + } + else { + statements.push(result); + } + } + var moduleBlock = getInnerMostModuleDeclarationFromDottedModule(node).body; + statementsLocation = ts.moveRangePos(moduleBlock.statements, -1); + } + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + currentNamespaceContainerName = savedCurrentNamespaceContainerName; + currentNamespace = savedCurrentNamespace; + currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName; + var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), + /*location*/ statementsLocation), + /*multiLine*/ true); + ts.setTextRange(block, blockLocation); + // namespace hello.hi.world { + // function foo() {} + // + // // TODO, blah + // } + // + // should be emitted as + // + // var hello; + // (function (hello) { + // var hi; + // (function (hi) { + // var world; + // (function (world) { + // function foo() { } + // // TODO, blah + // })(world = hi.world || (hi.world = {})); + // })(hi = hello.hi || (hello.hi = {})); + // })(hello || (hello = {})); + // We only want to emit comment on the namespace which contains block body itself, not the containing namespaces. + if (body.kind !== 245 /* ModuleBlock */) { + ts.setEmitFlags(block, ts.getEmitFlags(block) | 1536 /* NoComments */); + } + return block; + } + function getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration) { + if (moduleDeclaration.body.kind === 244 /* ModuleDeclaration */) { + var recursiveInnerModule = getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration.body); + return recursiveInnerModule || moduleDeclaration.body; + } + } + /** + * Visits an import declaration, eliding it if it is not referenced. + * + * @param node The import declaration node. + */ + function visitImportDeclaration(node) { + if (!node.importClause) { + // Do not elide a side-effect only import declaration. + // import "foo"; + return node; + } + // Elide the declaration if the import clause was elided. + var importClause = ts.visitNode(node.importClause, visitImportClause, ts.isImportClause); + return importClause + ? ts.updateImportDeclaration(node, + /*decorators*/ undefined, + /*modifiers*/ undefined, importClause, node.moduleSpecifier) + : undefined; + } + /** + * Visits an import clause, eliding it if it is not referenced. + * + * @param node The import clause node. + */ + function visitImportClause(node) { + // Elide the import clause if we elide both its name and its named bindings. + var name = resolver.isReferencedAliasDeclaration(node) ? node.name : undefined; + var namedBindings = ts.visitNode(node.namedBindings, visitNamedImportBindings, ts.isNamedImportBindings); + return (name || namedBindings) ? ts.updateImportClause(node, name, namedBindings) : undefined; + } + /** + * Visits named import bindings, eliding it if it is not referenced. + * + * @param node The named import bindings node. + */ + function visitNamedImportBindings(node) { + if (node.kind === 251 /* NamespaceImport */) { + // Elide a namespace import if it is not referenced. + return resolver.isReferencedAliasDeclaration(node) ? node : undefined; + } + else { + // Elide named imports if all of its import specifiers are elided. + var elements = ts.visitNodes(node.elements, visitImportSpecifier, ts.isImportSpecifier); + return ts.some(elements) ? ts.updateNamedImports(node, elements) : undefined; + } + } + /** + * Visits an import specifier, eliding it if it is not referenced. + * + * @param node The import specifier node. + */ + function visitImportSpecifier(node) { + // Elide an import specifier if it is not referenced. + return resolver.isReferencedAliasDeclaration(node) ? node : undefined; + } + /** + * Visits an export assignment, eliding it if it does not contain a clause that resolves + * to a value. + * + * @param node The export assignment node. + */ + function visitExportAssignment(node) { + // Elide the export assignment if it does not reference a value. + return resolver.isValueAliasDeclaration(node) + ? ts.visitEachChild(node, visitor, context) + : undefined; + } + /** + * Visits an export declaration, eliding it if it does not contain a clause that resolves + * to a value. + * + * @param node The export declaration node. + */ + function visitExportDeclaration(node) { + if (!node.exportClause) { + // Elide a star export if the module it references does not export a value. + return compilerOptions.isolatedModules || resolver.moduleExportsSomeValue(node.moduleSpecifier) ? node : undefined; + } + if (!resolver.isValueAliasDeclaration(node)) { + // Elide the export declaration if it does not export a value. + return undefined; + } + // Elide the export declaration if all of its named exports are elided. + var exportClause = ts.visitNode(node.exportClause, visitNamedExports, ts.isNamedExports); + return exportClause + ? ts.updateExportDeclaration(node, + /*decorators*/ undefined, + /*modifiers*/ undefined, exportClause, node.moduleSpecifier) + : undefined; + } + /** + * Visits named exports, eliding it if it does not contain an export specifier that + * resolves to a value. + * + * @param node The named exports node. + */ + function visitNamedExports(node) { + // Elide the named exports if all of its export specifiers were elided. + var elements = ts.visitNodes(node.elements, visitExportSpecifier, ts.isExportSpecifier); + return ts.some(elements) ? ts.updateNamedExports(node, elements) : undefined; + } + /** + * Visits an export specifier, eliding it if it does not resolve to a value. + * + * @param node The export specifier node. + */ + function visitExportSpecifier(node) { + // Elide an export specifier if it does not reference a value. + return resolver.isValueAliasDeclaration(node) ? node : undefined; + } + /** + * Determines whether to emit an import equals declaration. + * + * @param node The import equals declaration node. + */ + function shouldEmitImportEqualsDeclaration(node) { + // preserve old compiler's behavior: emit 'var' for import declaration (even if we do not consider them referenced) when + // - current file is not external module + // - import declaration is top level and target is value imported by entity name + return resolver.isReferencedAliasDeclaration(node) + || (!ts.isExternalModule(currentSourceFile) + && resolver.isTopLevelValueImportEqualsWithEntityName(node)); + } + /** + * Visits an import equals declaration. + * + * @param node The import equals declaration node. + */ + function visitImportEqualsDeclaration(node) { + if (ts.isExternalModuleImportEqualsDeclaration(node)) { + // Elide external module `import=` if it is not referenced. + return resolver.isReferencedAliasDeclaration(node) + ? ts.visitEachChild(node, visitor, context) + : undefined; + } + if (!shouldEmitImportEqualsDeclaration(node)) { + return undefined; + } + var moduleReference = ts.createExpressionFromEntityName(node.moduleReference); + ts.setEmitFlags(moduleReference, 1536 /* NoComments */ | 2048 /* NoNestedComments */); + if (isNamedExternalModuleExport(node) || !isExportOfNamespace(node)) { + // export var ${name} = ${moduleReference}; + // var ${name} = ${moduleReference}; + return ts.setOriginalNode(ts.setTextRange(ts.createVariableStatement(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.createVariableDeclarationList([ + ts.setOriginalNode(ts.createVariableDeclaration(node.name, + /*type*/ undefined, moduleReference), node) + ])), node), node); + } + else { + // exports.${name} = ${moduleReference}; + return ts.setOriginalNode(createNamespaceExport(node.name, moduleReference, node), node); + } + } + /** + * Gets a value indicating whether the node is exported from a namespace. + * + * @param node The node to test. + */ + function isExportOfNamespace(node) { + return currentNamespace !== undefined && ts.hasModifier(node, 1 /* Export */); + } + /** + * Gets a value indicating whether the node is exported from an external module. + * + * @param node The node to test. + */ + function isExternalModuleExport(node) { + return currentNamespace === undefined && ts.hasModifier(node, 1 /* Export */); + } + /** + * Gets a value indicating whether the node is a named export from an external module. + * + * @param node The node to test. + */ + function isNamedExternalModuleExport(node) { + return isExternalModuleExport(node) + && !ts.hasModifier(node, 512 /* Default */); + } + /** + * Gets a value indicating whether the node is the default export of an external module. + * + * @param node The node to test. + */ + function isDefaultExternalModuleExport(node) { + return isExternalModuleExport(node) + && ts.hasModifier(node, 512 /* Default */); + } + /** + * Creates a statement for the provided expression. This is used in calls to `map`. + */ + function expressionToStatement(expression) { + return ts.createExpressionStatement(expression); + } + function addExportMemberAssignment(statements, node) { + var expression = ts.createAssignment(ts.getExternalModuleOrNamespaceExportName(currentNamespaceContainerName, node, /*allowComments*/ false, /*allowSourceMaps*/ true), ts.getLocalName(node)); + ts.setSourceMapRange(expression, ts.createRange(node.name ? node.name.pos : node.pos, node.end)); + var statement = ts.createExpressionStatement(expression); + ts.setSourceMapRange(statement, ts.createRange(-1, node.end)); + statements.push(statement); + } + function createNamespaceExport(exportName, exportValue, location) { + return ts.setTextRange(ts.createExpressionStatement(ts.createAssignment(ts.getNamespaceMemberName(currentNamespaceContainerName, exportName, /*allowComments*/ false, /*allowSourceMaps*/ true), exportValue)), location); + } + function createNamespaceExportExpression(exportName, exportValue, location) { + return ts.setTextRange(ts.createAssignment(getNamespaceMemberNameWithSourceMapsAndWithoutComments(exportName), exportValue), location); + } + function getNamespaceMemberNameWithSourceMapsAndWithoutComments(name) { + return ts.getNamespaceMemberName(currentNamespaceContainerName, name, /*allowComments*/ false, /*allowSourceMaps*/ true); + } + /** + * Gets the declaration name used inside of a namespace or enum. + */ + function getNamespaceParameterName(node) { + var name = ts.getGeneratedNameForNode(node); + ts.setSourceMapRange(name, node.name); + return name; + } + /** + * Gets the expression used to refer to a namespace or enum within the body + * of its declaration. + */ + function getNamespaceContainerName(node) { + return ts.getGeneratedNameForNode(node); + } + /** + * Gets a local alias for a class declaration if it is a decorated class with an internal + * reference to the static side of the class. This is necessary to avoid issues with + * double-binding semantics for the class name. + */ + function getClassAliasIfNeeded(node) { + if (resolver.getNodeCheckFlags(node) & 16777216 /* ClassWithConstructorReference */) { + enableSubstitutionForClassAliases(); + var classAlias = ts.createUniqueName(node.name && !ts.isGeneratedIdentifier(node.name) ? ts.idText(node.name) : "default"); + classAliases[ts.getOriginalNodeId(node)] = classAlias; + hoistVariableDeclaration(classAlias); + return classAlias; + } + } + function getClassPrototype(node) { + return ts.createPropertyAccess(ts.getDeclarationName(node), "prototype"); + } + function getClassMemberPrefix(node, member) { + return ts.hasModifier(member, 32 /* Static */) + ? ts.getDeclarationName(node) + : getClassPrototype(node); + } + function enableSubstitutionForNonQualifiedEnumMembers() { + if ((enabledSubstitutions & 8 /* NonQualifiedEnumMembers */) === 0) { + enabledSubstitutions |= 8 /* NonQualifiedEnumMembers */; + context.enableSubstitution(72 /* Identifier */); + } + } + function enableSubstitutionForClassAliases() { + if ((enabledSubstitutions & 1 /* ClassAliases */) === 0) { + enabledSubstitutions |= 1 /* ClassAliases */; + // We need to enable substitutions for identifiers. This allows us to + // substitute class names inside of a class declaration. + context.enableSubstitution(72 /* Identifier */); + // Keep track of class aliases. + classAliases = []; + } + } + function enableSubstitutionForNamespaceExports() { + if ((enabledSubstitutions & 2 /* NamespaceExports */) === 0) { + enabledSubstitutions |= 2 /* NamespaceExports */; + // We need to enable substitutions for identifiers and shorthand property assignments. This allows us to + // substitute the names of exported members of a namespace. + context.enableSubstitution(72 /* Identifier */); + context.enableSubstitution(276 /* ShorthandPropertyAssignment */); + // We need to be notified when entering and exiting namespaces. + context.enableEmitNotification(244 /* ModuleDeclaration */); + } + } + function isTransformedModuleDeclaration(node) { + return ts.getOriginalNode(node).kind === 244 /* ModuleDeclaration */; + } + function isTransformedEnumDeclaration(node) { + return ts.getOriginalNode(node).kind === 243 /* EnumDeclaration */; + } + /** + * Hook for node emit. + * + * @param hint A hint as to the intended usage of the node. + * @param node The node to emit. + * @param emit A callback used to emit the node in the printer. + */ + function onEmitNode(hint, node, emitCallback) { + var savedApplicableSubstitutions = applicableSubstitutions; + var savedCurrentSourceFile = currentSourceFile; + if (ts.isSourceFile(node)) { + currentSourceFile = node; + } + if (enabledSubstitutions & 2 /* NamespaceExports */ && isTransformedModuleDeclaration(node)) { + applicableSubstitutions |= 2 /* NamespaceExports */; + } + if (enabledSubstitutions & 8 /* NonQualifiedEnumMembers */ && isTransformedEnumDeclaration(node)) { + applicableSubstitutions |= 8 /* NonQualifiedEnumMembers */; + } + previousOnEmitNode(hint, node, emitCallback); + applicableSubstitutions = savedApplicableSubstitutions; + currentSourceFile = savedCurrentSourceFile; + } + /** + * Hooks node substitutions. + * + * @param hint A hint as to the intended usage of the node. + * @param node The node to substitute. + */ + function onSubstituteNode(hint, node) { + node = previousOnSubstituteNode(hint, node); + if (hint === 1 /* Expression */) { + return substituteExpression(node); + } + else if (ts.isShorthandPropertyAssignment(node)) { + return substituteShorthandPropertyAssignment(node); + } + return node; + } + function substituteShorthandPropertyAssignment(node) { + if (enabledSubstitutions & 2 /* NamespaceExports */) { + var name = node.name; + var exportedName = trySubstituteNamespaceExportedName(name); + if (exportedName) { + // A shorthand property with an assignment initializer is probably part of a + // destructuring assignment + if (node.objectAssignmentInitializer) { + var initializer = ts.createAssignment(exportedName, node.objectAssignmentInitializer); + return ts.setTextRange(ts.createPropertyAssignment(name, initializer), node); + } + return ts.setTextRange(ts.createPropertyAssignment(name, exportedName), node); + } + } + return node; + } + function substituteExpression(node) { + switch (node.kind) { + case 72 /* Identifier */: + return substituteExpressionIdentifier(node); + case 189 /* PropertyAccessExpression */: + return substitutePropertyAccessExpression(node); + case 190 /* ElementAccessExpression */: + return substituteElementAccessExpression(node); + } + return node; + } + function substituteExpressionIdentifier(node) { + return trySubstituteClassAlias(node) + || trySubstituteNamespaceExportedName(node) + || node; + } + function trySubstituteClassAlias(node) { + if (enabledSubstitutions & 1 /* ClassAliases */) { + if (resolver.getNodeCheckFlags(node) & 33554432 /* ConstructorReferenceInClass */) { + // Due to the emit for class decorators, any reference to the class from inside of the class body + // must instead be rewritten to point to a temporary variable to avoid issues with the double-bind + // behavior of class names in ES6. + // Also, when emitting statics for class expressions, we must substitute a class alias for + // constructor references in static property initializers. + var declaration = resolver.getReferencedValueDeclaration(node); + if (declaration) { + var classAlias = classAliases[declaration.id]; // TODO: GH#18217 + if (classAlias) { + var clone_1 = ts.getSynthesizedClone(classAlias); + ts.setSourceMapRange(clone_1, node); + ts.setCommentRange(clone_1, node); + return clone_1; + } + } + } + } + return undefined; + } + function trySubstituteNamespaceExportedName(node) { + // If this is explicitly a local name, do not substitute. + if (enabledSubstitutions & applicableSubstitutions && !ts.isGeneratedIdentifier(node) && !ts.isLocalName(node)) { + // If we are nested within a namespace declaration, we may need to qualifiy + // an identifier that is exported from a merged namespace. + var container = resolver.getReferencedExportContainer(node, /*prefixLocals*/ false); + if (container && container.kind !== 279 /* SourceFile */) { + var substitute = (applicableSubstitutions & 2 /* NamespaceExports */ && container.kind === 244 /* ModuleDeclaration */) || + (applicableSubstitutions & 8 /* NonQualifiedEnumMembers */ && container.kind === 243 /* EnumDeclaration */); + if (substitute) { + return ts.setTextRange(ts.createPropertyAccess(ts.getGeneratedNameForNode(container), node), + /*location*/ node); + } + } + } + return undefined; + } + function substitutePropertyAccessExpression(node) { + return substituteConstantValue(node); + } + function substituteElementAccessExpression(node) { + return substituteConstantValue(node); + } + function substituteConstantValue(node) { + var constantValue = tryGetConstEnumValue(node); + if (constantValue !== undefined) { + // track the constant value on the node for the printer in needsDotDotForPropertyAccess + ts.setConstantValue(node, constantValue); + var substitute = ts.createLiteral(constantValue); + if (!compilerOptions.removeComments) { + var propertyName = ts.isPropertyAccessExpression(node) + ? ts.declarationNameToString(node.name) + : ts.getTextOfNode(node.argumentExpression); + ts.addSyntheticTrailingComment(substitute, 3 /* MultiLineCommentTrivia */, " " + propertyName + " "); + } + return substitute; + } + return node; + } + function tryGetConstEnumValue(node) { + if (compilerOptions.isolatedModules) { + return undefined; + } + return ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node) ? resolver.getConstantValue(node) : undefined; + } + } + ts.transformTypeScript = transformTypeScript; + function createDecorateHelper(context, decoratorExpressions, target, memberName, descriptor, location) { + var argumentsArray = []; + argumentsArray.push(ts.createArrayLiteral(decoratorExpressions, /*multiLine*/ true)); + argumentsArray.push(target); + if (memberName) { + argumentsArray.push(memberName); + if (descriptor) { + argumentsArray.push(descriptor); + } + } + context.requestEmitHelper(decorateHelper); + return ts.setTextRange(ts.createCall(ts.getHelperName("__decorate"), + /*typeArguments*/ undefined, argumentsArray), location); + } + var decorateHelper = { + name: "typescript:decorate", + scoped: false, + priority: 2, + text: "\n var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n };" + }; + function createMetadataHelper(context, metadataKey, metadataValue) { + context.requestEmitHelper(metadataHelper); + return ts.createCall(ts.getHelperName("__metadata"), + /*typeArguments*/ undefined, [ + ts.createLiteral(metadataKey), + metadataValue + ]); + } + var metadataHelper = { + name: "typescript:metadata", + scoped: false, + priority: 3, + text: "\n var __metadata = (this && this.__metadata) || function (k, v) {\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(k, v);\n };" + }; + function createParamHelper(context, expression, parameterOffset, location) { + context.requestEmitHelper(paramHelper); + return ts.setTextRange(ts.createCall(ts.getHelperName("__param"), + /*typeArguments*/ undefined, [ + ts.createLiteral(parameterOffset), + expression + ]), location); + } + var paramHelper = { + name: "typescript:param", + scoped: false, + priority: 4, + text: "\n var __param = (this && this.__param) || function (paramIndex, decorator) {\n return function (target, key) { decorator(target, key, paramIndex); }\n };" + }; +})(ts || (ts = {})); +/*@internal*/ +var ts; +(function (ts) { + var ES2017SubstitutionFlags; + (function (ES2017SubstitutionFlags) { + /** Enables substitutions for async methods with `super` calls. */ + ES2017SubstitutionFlags[ES2017SubstitutionFlags["AsyncMethodsWithSuper"] = 1] = "AsyncMethodsWithSuper"; + })(ES2017SubstitutionFlags || (ES2017SubstitutionFlags = {})); + function transformES2017(context) { + var resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; + var resolver = context.getEmitResolver(); + var compilerOptions = context.getCompilerOptions(); + var languageVersion = ts.getEmitScriptTarget(compilerOptions); + /** + * Keeps track of whether expression substitution has been enabled for specific edge cases. + * They are persisted between each SourceFile transformation and should not be reset. + */ + var enabledSubstitutions; + /** + * This keeps track of containers where `super` is valid, for use with + * just-in-time substitution for `super` expressions inside of async methods. + */ + var enclosingSuperContainerFlags = 0; + var enclosingFunctionParameterNames; + /** + * Keeps track of property names accessed on super (`super.x`) within async functions. + */ + var capturedSuperProperties; + /** Whether the async function contains an element access on super (`super[x]`). */ + var hasSuperElementAccess; + /** A set of node IDs for generated super accessors (variable statements). */ + var substitutedSuperAccessors = []; + // Save the previous transformation hooks. + var previousOnEmitNode = context.onEmitNode; + var previousOnSubstituteNode = context.onSubstituteNode; + // Set new transformation hooks. + context.onEmitNode = onEmitNode; + context.onSubstituteNode = onSubstituteNode; + return ts.chainBundle(transformSourceFile); + function transformSourceFile(node) { + if (node.isDeclarationFile) { + return node; + } + var visited = ts.visitEachChild(node, visitor, context); + ts.addEmitHelpers(visited, context.readEmitHelpers()); + return visited; + } + function visitor(node) { + if ((node.transformFlags & 16 /* ContainsES2017 */) === 0) { + return node; + } + switch (node.kind) { + case 121 /* AsyncKeyword */: + // ES2017 async modifier should be elided for targets < ES2017 + return undefined; + case 201 /* AwaitExpression */: + return visitAwaitExpression(node); + case 156 /* MethodDeclaration */: + return visitMethodDeclaration(node); + case 239 /* FunctionDeclaration */: + return visitFunctionDeclaration(node); + case 196 /* FunctionExpression */: + return visitFunctionExpression(node); + case 197 /* ArrowFunction */: + return visitArrowFunction(node); + case 189 /* PropertyAccessExpression */: + if (capturedSuperProperties && ts.isPropertyAccessExpression(node) && node.expression.kind === 98 /* SuperKeyword */) { + capturedSuperProperties.set(node.name.escapedText, true); + } + return ts.visitEachChild(node, visitor, context); + case 190 /* ElementAccessExpression */: + if (capturedSuperProperties && node.expression.kind === 98 /* SuperKeyword */) { + hasSuperElementAccess = true; + } + return ts.visitEachChild(node, visitor, context); + default: + return ts.visitEachChild(node, visitor, context); + } + } + function asyncBodyVisitor(node) { + if (ts.isNodeWithPossibleHoistedDeclaration(node)) { + switch (node.kind) { + case 219 /* VariableStatement */: + return visitVariableStatementInAsyncBody(node); + case 225 /* ForStatement */: + return visitForStatementInAsyncBody(node); + case 226 /* ForInStatement */: + return visitForInStatementInAsyncBody(node); + case 227 /* ForOfStatement */: + return visitForOfStatementInAsyncBody(node); + case 274 /* CatchClause */: + return visitCatchClauseInAsyncBody(node); + case 218 /* Block */: + case 232 /* SwitchStatement */: + case 246 /* CaseBlock */: + case 271 /* CaseClause */: + case 272 /* DefaultClause */: + case 235 /* TryStatement */: + case 223 /* DoStatement */: + case 224 /* WhileStatement */: + case 222 /* IfStatement */: + case 231 /* WithStatement */: + case 233 /* LabeledStatement */: + return ts.visitEachChild(node, asyncBodyVisitor, context); + default: + return ts.Debug.assertNever(node, "Unhandled node."); + } + } + return visitor(node); + } + function visitCatchClauseInAsyncBody(node) { + var catchClauseNames = ts.createUnderscoreEscapedMap(); + recordDeclarationName(node.variableDeclaration, catchClauseNames); // TODO: GH#18217 + // names declared in a catch variable are block scoped + var catchClauseUnshadowedNames; + catchClauseNames.forEach(function (_, escapedName) { + if (enclosingFunctionParameterNames.has(escapedName)) { + if (!catchClauseUnshadowedNames) { + catchClauseUnshadowedNames = ts.cloneMap(enclosingFunctionParameterNames); + } + catchClauseUnshadowedNames.delete(escapedName); + } + }); + if (catchClauseUnshadowedNames) { + var savedEnclosingFunctionParameterNames = enclosingFunctionParameterNames; + enclosingFunctionParameterNames = catchClauseUnshadowedNames; + var result = ts.visitEachChild(node, asyncBodyVisitor, context); + enclosingFunctionParameterNames = savedEnclosingFunctionParameterNames; + return result; + } + else { + return ts.visitEachChild(node, asyncBodyVisitor, context); + } + } + function visitVariableStatementInAsyncBody(node) { + if (isVariableDeclarationListWithCollidingName(node.declarationList)) { + var expression = visitVariableDeclarationListWithCollidingNames(node.declarationList, /*hasReceiver*/ false); + return expression ? ts.createExpressionStatement(expression) : undefined; + } + return ts.visitEachChild(node, visitor, context); + } + function visitForInStatementInAsyncBody(node) { + return ts.updateForIn(node, isVariableDeclarationListWithCollidingName(node.initializer) + ? visitVariableDeclarationListWithCollidingNames(node.initializer, /*hasReceiver*/ true) + : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitNode(node.statement, asyncBodyVisitor, ts.isStatement, ts.liftToBlock)); + } + function visitForOfStatementInAsyncBody(node) { + return ts.updateForOf(node, ts.visitNode(node.awaitModifier, visitor, ts.isToken), isVariableDeclarationListWithCollidingName(node.initializer) + ? visitVariableDeclarationListWithCollidingNames(node.initializer, /*hasReceiver*/ true) + : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitNode(node.statement, asyncBodyVisitor, ts.isStatement, ts.liftToBlock)); + } + function visitForStatementInAsyncBody(node) { + var initializer = node.initializer; // TODO: GH#18217 + return ts.updateFor(node, isVariableDeclarationListWithCollidingName(initializer) + ? visitVariableDeclarationListWithCollidingNames(initializer, /*hasReceiver*/ false) + : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.condition, visitor, ts.isExpression), ts.visitNode(node.incrementor, visitor, ts.isExpression), ts.visitNode(node.statement, asyncBodyVisitor, ts.isStatement, ts.liftToBlock)); + } + /** + * Visits an AwaitExpression node. + * + * This function will be called any time a ES2017 await expression is encountered. + * + * @param node The node to visit. + */ + function visitAwaitExpression(node) { + return ts.setOriginalNode(ts.setTextRange(ts.createYield( + /*asteriskToken*/ undefined, ts.visitNode(node.expression, visitor, ts.isExpression)), node), node); + } + /** + * Visits a MethodDeclaration node. + * + * This function will be called when one of the following conditions are met: + * - The node is marked as async + * + * @param node The node to visit. + */ + function visitMethodDeclaration(node) { + return ts.updateMethod(node, + /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, node.name, + /*questionToken*/ undefined, + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, ts.getFunctionFlags(node) & 2 /* Async */ + ? transformAsyncFunctionBody(node) + : ts.visitFunctionBody(node.body, visitor, context)); + } + /** + * Visits a FunctionDeclaration node. + * + * This function will be called when one of the following conditions are met: + * - The node is marked async + * + * @param node The node to visit. + */ + function visitFunctionDeclaration(node) { + return ts.updateFunctionDeclaration(node, + /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, node.name, + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, ts.getFunctionFlags(node) & 2 /* Async */ + ? transformAsyncFunctionBody(node) + : ts.visitFunctionBody(node.body, visitor, context)); + } + /** + * Visits a FunctionExpression node. + * + * This function will be called when one of the following conditions are met: + * - The node is marked async + * + * @param node The node to visit. + */ + function visitFunctionExpression(node) { + return ts.updateFunctionExpression(node, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, node.name, + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, ts.getFunctionFlags(node) & 2 /* Async */ + ? transformAsyncFunctionBody(node) + : ts.visitFunctionBody(node.body, visitor, context)); + } + /** + * Visits an ArrowFunction. + * + * This function will be called when one of the following conditions are met: + * - The node is marked async + * + * @param node The node to visit. + */ + function visitArrowFunction(node) { + return ts.updateArrowFunction(node, ts.visitNodes(node.modifiers, visitor, ts.isModifier), + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, node.equalsGreaterThanToken, ts.getFunctionFlags(node) & 2 /* Async */ + ? transformAsyncFunctionBody(node) + : ts.visitFunctionBody(node.body, visitor, context)); + } + function recordDeclarationName(_a, names) { + var name = _a.name; + if (ts.isIdentifier(name)) { + names.set(name.escapedText, true); + } + else { + for (var _i = 0, _b = name.elements; _i < _b.length; _i++) { + var element = _b[_i]; + if (!ts.isOmittedExpression(element)) { + recordDeclarationName(element, names); + } + } + } + } + function isVariableDeclarationListWithCollidingName(node) { + return !!node + && ts.isVariableDeclarationList(node) + && !(node.flags & 3 /* BlockScoped */) + && node.declarations.some(collidesWithParameterName); + } + function visitVariableDeclarationListWithCollidingNames(node, hasReceiver) { + hoistVariableDeclarationList(node); + var variables = ts.getInitializedVariables(node); + if (variables.length === 0) { + if (hasReceiver) { + return ts.visitNode(ts.convertToAssignmentElementTarget(node.declarations[0].name), visitor, ts.isExpression); + } + return undefined; + } + return ts.inlineExpressions(ts.map(variables, transformInitializedVariable)); + } + function hoistVariableDeclarationList(node) { + ts.forEach(node.declarations, hoistVariable); + } + function hoistVariable(_a) { + var name = _a.name; + if (ts.isIdentifier(name)) { + hoistVariableDeclaration(name); + } + else { + for (var _i = 0, _b = name.elements; _i < _b.length; _i++) { + var element = _b[_i]; + if (!ts.isOmittedExpression(element)) { + hoistVariable(element); + } + } + } + } + function transformInitializedVariable(node) { + var converted = ts.setSourceMapRange(ts.createAssignment(ts.convertToAssignmentElementTarget(node.name), node.initializer), node); + return ts.visitNode(converted, visitor, ts.isExpression); + } + function collidesWithParameterName(_a) { + var name = _a.name; + if (ts.isIdentifier(name)) { + return enclosingFunctionParameterNames.has(name.escapedText); + } + else { + for (var _i = 0, _b = name.elements; _i < _b.length; _i++) { + var element = _b[_i]; + if (!ts.isOmittedExpression(element) && collidesWithParameterName(element)) { + return true; + } + } + } + return false; + } + function transformAsyncFunctionBody(node) { + resumeLexicalEnvironment(); + var original = ts.getOriginalNode(node, ts.isFunctionLike); + var nodeType = original.type; + var promiseConstructor = languageVersion < 2 /* ES2015 */ ? getPromiseConstructor(nodeType) : undefined; + var isArrowFunction = node.kind === 197 /* ArrowFunction */; + var hasLexicalArguments = (resolver.getNodeCheckFlags(node) & 8192 /* CaptureArguments */) !== 0; + // An async function is emit as an outer function that calls an inner + // generator function. To preserve lexical bindings, we pass the current + // `this` and `arguments` objects to `__awaiter`. The generator function + // passed to `__awaiter` is executed inside of the callback to the + // promise constructor. + var savedEnclosingFunctionParameterNames = enclosingFunctionParameterNames; + enclosingFunctionParameterNames = ts.createUnderscoreEscapedMap(); + for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { + var parameter = _a[_i]; + recordDeclarationName(parameter, enclosingFunctionParameterNames); + } + var savedCapturedSuperProperties = capturedSuperProperties; + var savedHasSuperElementAccess = hasSuperElementAccess; + capturedSuperProperties = ts.createUnderscoreEscapedMap(); + hasSuperElementAccess = false; + var result; + if (!isArrowFunction) { + var statements = []; + var statementOffset = ts.addPrologue(statements, node.body.statements, /*ensureUseStrict*/ false, visitor); + statements.push(ts.createReturn(createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, transformAsyncFunctionBodyWorker(node.body, statementOffset)))); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + // Minor optimization, emit `_super` helper to capture `super` access in an arrow. + // This step isn't needed if we eventually transform this to ES5. + var emitSuperHelpers = languageVersion >= 2 /* ES2015 */ && resolver.getNodeCheckFlags(node) & (4096 /* AsyncMethodWithSuperBinding */ | 2048 /* AsyncMethodWithSuper */); + if (emitSuperHelpers) { + enableSubstitutionForAsyncMethodsWithSuper(); + var variableStatement = createSuperAccessVariableStatement(resolver, node, capturedSuperProperties); + substitutedSuperAccessors[ts.getNodeId(variableStatement)] = true; + ts.addStatementsAfterPrologue(statements, [variableStatement]); + } + var block = ts.createBlock(statements, /*multiLine*/ true); + ts.setTextRange(block, node.body); + if (emitSuperHelpers && hasSuperElementAccess) { + // Emit helpers for super element access expressions (`super[x]`). + if (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) { + ts.addEmitHelper(block, ts.advancedAsyncSuperHelper); + } + else if (resolver.getNodeCheckFlags(node) & 2048 /* AsyncMethodWithSuper */) { + ts.addEmitHelper(block, ts.asyncSuperHelper); + } + } + result = block; + } + else { + var expression = createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, transformAsyncFunctionBodyWorker(node.body)); + var declarations = endLexicalEnvironment(); + if (ts.some(declarations)) { + var block = ts.convertToFunctionBody(expression); + result = ts.updateBlock(block, ts.setTextRange(ts.createNodeArray(ts.concatenate(declarations, block.statements)), block.statements)); + } + else { + result = expression; + } + } + enclosingFunctionParameterNames = savedEnclosingFunctionParameterNames; + capturedSuperProperties = savedCapturedSuperProperties; + hasSuperElementAccess = savedHasSuperElementAccess; + return result; + } + function transformAsyncFunctionBodyWorker(body, start) { + if (ts.isBlock(body)) { + return ts.updateBlock(body, ts.visitNodes(body.statements, asyncBodyVisitor, ts.isStatement, start)); + } + else { + return ts.convertToFunctionBody(ts.visitNode(body, asyncBodyVisitor, ts.isConciseBody)); + } + } + function getPromiseConstructor(type) { + var typeName = type && ts.getEntityNameFromTypeNode(type); + if (typeName && ts.isEntityName(typeName)) { + var serializationKind = resolver.getTypeReferenceSerializationKind(typeName); + if (serializationKind === ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue + || serializationKind === ts.TypeReferenceSerializationKind.Unknown) { + return typeName; + } + } + return undefined; + } + function enableSubstitutionForAsyncMethodsWithSuper() { + if ((enabledSubstitutions & 1 /* AsyncMethodsWithSuper */) === 0) { + enabledSubstitutions |= 1 /* AsyncMethodsWithSuper */; + // We need to enable substitutions for call, property access, and element access + // if we need to rewrite super calls. + context.enableSubstitution(191 /* CallExpression */); + context.enableSubstitution(189 /* PropertyAccessExpression */); + context.enableSubstitution(190 /* ElementAccessExpression */); + // We need to be notified when entering and exiting declarations that bind super. + context.enableEmitNotification(240 /* ClassDeclaration */); + context.enableEmitNotification(156 /* MethodDeclaration */); + context.enableEmitNotification(158 /* GetAccessor */); + context.enableEmitNotification(159 /* SetAccessor */); + context.enableEmitNotification(157 /* Constructor */); + // We need to be notified when entering the generated accessor arrow functions. + context.enableEmitNotification(219 /* VariableStatement */); + } + } + /** + * Hook for node emit. + * + * @param hint A hint as to the intended usage of the node. + * @param node The node to emit. + * @param emit A callback used to emit the node in the printer. + */ + function onEmitNode(hint, node, emitCallback) { + // If we need to support substitutions for `super` in an async method, + // we should track it here. + if (enabledSubstitutions & 1 /* AsyncMethodsWithSuper */ && isSuperContainer(node)) { + var superContainerFlags = resolver.getNodeCheckFlags(node) & (2048 /* AsyncMethodWithSuper */ | 4096 /* AsyncMethodWithSuperBinding */); + if (superContainerFlags !== enclosingSuperContainerFlags) { + var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags; + enclosingSuperContainerFlags = superContainerFlags; + previousOnEmitNode(hint, node, emitCallback); + enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags; + return; + } + } + // Disable substitution in the generated super accessor itself. + else if (enabledSubstitutions && substitutedSuperAccessors[ts.getNodeId(node)]) { + var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags; + enclosingSuperContainerFlags = 0; + previousOnEmitNode(hint, node, emitCallback); + enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags; + return; + } + previousOnEmitNode(hint, node, emitCallback); + } + /** + * Hooks node substitutions. + * + * @param hint A hint as to the intended usage of the node. + * @param node The node to substitute. + */ + function onSubstituteNode(hint, node) { + node = previousOnSubstituteNode(hint, node); + if (hint === 1 /* Expression */ && enclosingSuperContainerFlags) { + return substituteExpression(node); + } + return node; + } + function substituteExpression(node) { + switch (node.kind) { + case 189 /* PropertyAccessExpression */: + return substitutePropertyAccessExpression(node); + case 190 /* ElementAccessExpression */: + return substituteElementAccessExpression(node); + case 191 /* CallExpression */: + return substituteCallExpression(node); + } + return node; + } + function substitutePropertyAccessExpression(node) { + if (node.expression.kind === 98 /* SuperKeyword */) { + return ts.setTextRange(ts.createPropertyAccess(ts.createFileLevelUniqueName("_super"), node.name), node); + } + return node; + } + function substituteElementAccessExpression(node) { + if (node.expression.kind === 98 /* SuperKeyword */) { + return createSuperElementAccessInAsyncMethod(node.argumentExpression, node); + } + return node; + } + function substituteCallExpression(node) { + var expression = node.expression; + if (ts.isSuperProperty(expression)) { + var argumentExpression = ts.isPropertyAccessExpression(expression) + ? substitutePropertyAccessExpression(expression) + : substituteElementAccessExpression(expression); + return ts.createCall(ts.createPropertyAccess(argumentExpression, "call"), + /*typeArguments*/ undefined, [ + ts.createThis() + ].concat(node.arguments)); + } + return node; + } + function isSuperContainer(node) { + var kind = node.kind; + return kind === 240 /* ClassDeclaration */ + || kind === 157 /* Constructor */ + || kind === 156 /* MethodDeclaration */ + || kind === 158 /* GetAccessor */ + || kind === 159 /* SetAccessor */; + } + function createSuperElementAccessInAsyncMethod(argumentExpression, location) { + if (enclosingSuperContainerFlags & 4096 /* AsyncMethodWithSuperBinding */) { + return ts.setTextRange(ts.createPropertyAccess(ts.createCall(ts.createFileLevelUniqueName("_superIndex"), + /*typeArguments*/ undefined, [argumentExpression]), "value"), location); + } + else { + return ts.setTextRange(ts.createCall(ts.createFileLevelUniqueName("_superIndex"), + /*typeArguments*/ undefined, [argumentExpression]), location); + } + } + } + ts.transformES2017 = transformES2017; + /** Creates a variable named `_super` with accessor properties for the given property names. */ + function createSuperAccessVariableStatement(resolver, node, names) { + // Create a variable declaration with a getter/setter (if binding) definition for each name: + // const _super = Object.create(null, { x: { get: () => super.x, set: (v) => super.x = v }, ... }); + var hasBinding = (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) !== 0; + var accessors = []; + names.forEach(function (_, key) { + var name = ts.unescapeLeadingUnderscores(key); + var getterAndSetter = []; + getterAndSetter.push(ts.createPropertyAssignment("get", ts.createArrowFunction( + /* modifiers */ undefined, + /* typeParameters */ undefined, + /* parameters */ [], + /* type */ undefined, + /* equalsGreaterThanToken */ undefined, ts.createPropertyAccess(ts.createSuper(), name)))); + if (hasBinding) { + getterAndSetter.push(ts.createPropertyAssignment("set", ts.createArrowFunction( + /* modifiers */ undefined, + /* typeParameters */ undefined, + /* parameters */ [ + ts.createParameter( + /* decorators */ undefined, + /* modifiers */ undefined, + /* dotDotDotToken */ undefined, "v", + /* questionToken */ undefined, + /* type */ undefined, + /* initializer */ undefined) + ], + /* type */ undefined, + /* equalsGreaterThanToken */ undefined, ts.createAssignment(ts.createPropertyAccess(ts.createSuper(), name), ts.createIdentifier("v"))))); + } + accessors.push(ts.createPropertyAssignment(name, ts.createObjectLiteral(getterAndSetter))); + }); + return ts.createVariableStatement( + /* modifiers */ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(ts.createFileLevelUniqueName("_super"), + /* type */ undefined, ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "create"), + /* typeArguments */ undefined, [ + ts.createNull(), + ts.createObjectLiteral(accessors, /* multiline */ true) + ])) + ], 2 /* Const */)); + } + ts.createSuperAccessVariableStatement = createSuperAccessVariableStatement; + var awaiterHelper = { + name: "typescript:awaiter", + scoped: false, + priority: 5, + text: "\n var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n };" + }; + function createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, body) { + context.requestEmitHelper(awaiterHelper); + var generatorFunc = ts.createFunctionExpression( + /*modifiers*/ undefined, ts.createToken(40 /* AsteriskToken */), + /*name*/ undefined, + /*typeParameters*/ undefined, + /*parameters*/ [], + /*type*/ undefined, body); + // Mark this node as originally an async function + (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 262144 /* AsyncFunctionBody */ | 524288 /* ReuseTempVariableScope */; + return ts.createCall(ts.getHelperName("__awaiter"), + /*typeArguments*/ undefined, [ + ts.createThis(), + hasLexicalArguments ? ts.createIdentifier("arguments") : ts.createVoidZero(), + promiseConstructor ? ts.createExpressionFromEntityName(promiseConstructor) : ts.createVoidZero(), + generatorFunc + ]); + } + ts.asyncSuperHelper = { + name: "typescript:async-super", + scoped: true, + text: ts.helperString(__makeTemplateObject(["\n const ", " = name => super[name];"], ["\n const ", " = name => super[name];"]), "_superIndex") + }; + ts.advancedAsyncSuperHelper = { + name: "typescript:advanced-async-super", + scoped: true, + text: ts.helperString(__makeTemplateObject(["\n const ", " = (function (geti, seti) {\n const cache = Object.create(null);\n return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } });\n })(name => super[name], (name, value) => super[name] = value);"], ["\n const ", " = (function (geti, seti) {\n const cache = Object.create(null);\n return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } });\n })(name => super[name], (name, value) => super[name] = value);"]), "_superIndex") + }; +})(ts || (ts = {})); +/*@internal*/ +var ts; +(function (ts) { + var ESNextSubstitutionFlags; + (function (ESNextSubstitutionFlags) { + /** Enables substitutions for async methods with `super` calls. */ + ESNextSubstitutionFlags[ESNextSubstitutionFlags["AsyncMethodsWithSuper"] = 1] = "AsyncMethodsWithSuper"; + })(ESNextSubstitutionFlags || (ESNextSubstitutionFlags = {})); + function transformESNext(context) { + var resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; + var resolver = context.getEmitResolver(); + var compilerOptions = context.getCompilerOptions(); + var languageVersion = ts.getEmitScriptTarget(compilerOptions); + var previousOnEmitNode = context.onEmitNode; + context.onEmitNode = onEmitNode; + var previousOnSubstituteNode = context.onSubstituteNode; + context.onSubstituteNode = onSubstituteNode; + var enabledSubstitutions; + var enclosingFunctionFlags; + var enclosingSuperContainerFlags = 0; + /** Keeps track of property names accessed on super (`super.x`) within async functions. */ + var capturedSuperProperties; + /** Whether the async function contains an element access on super (`super[x]`). */ + var hasSuperElementAccess; + /** A set of node IDs for generated super accessors. */ + var substitutedSuperAccessors = []; + return ts.chainBundle(transformSourceFile); + function transformSourceFile(node) { + if (node.isDeclarationFile) { + return node; + } + var visited = ts.visitEachChild(node, visitor, context); + ts.addEmitHelpers(visited, context.readEmitHelpers()); + return visited; + } + function visitor(node) { + return visitorWorker(node, /*noDestructuringValue*/ false); + } + function visitorNoDestructuringValue(node) { + return visitorWorker(node, /*noDestructuringValue*/ true); + } + function visitorNoAsyncModifier(node) { + if (node.kind === 121 /* AsyncKeyword */) { + return undefined; + } + return node; + } + function visitorWorker(node, noDestructuringValue) { + if ((node.transformFlags & 8 /* ContainsESNext */) === 0) { + return node; + } + switch (node.kind) { + case 201 /* AwaitExpression */: + return visitAwaitExpression(node); + case 207 /* YieldExpression */: + return visitYieldExpression(node); + case 230 /* ReturnStatement */: + return visitReturnStatement(node); + case 233 /* LabeledStatement */: + return visitLabeledStatement(node); + case 188 /* ObjectLiteralExpression */: + return visitObjectLiteralExpression(node); + case 204 /* BinaryExpression */: + return visitBinaryExpression(node, noDestructuringValue); + case 237 /* VariableDeclaration */: + return visitVariableDeclaration(node); + case 227 /* ForOfStatement */: + return visitForOfStatement(node, /*outermostLabeledStatement*/ undefined); + case 225 /* ForStatement */: + return visitForStatement(node); + case 200 /* VoidExpression */: + return visitVoidExpression(node); + case 157 /* Constructor */: + return visitConstructorDeclaration(node); + case 156 /* MethodDeclaration */: + return visitMethodDeclaration(node); + case 158 /* GetAccessor */: + return visitGetAccessorDeclaration(node); + case 159 /* SetAccessor */: + return visitSetAccessorDeclaration(node); + case 239 /* FunctionDeclaration */: + return visitFunctionDeclaration(node); + case 196 /* FunctionExpression */: + return visitFunctionExpression(node); + case 197 /* ArrowFunction */: + return visitArrowFunction(node); + case 151 /* Parameter */: + return visitParameter(node); + case 221 /* ExpressionStatement */: + return visitExpressionStatement(node); + case 195 /* ParenthesizedExpression */: + return visitParenthesizedExpression(node, noDestructuringValue); + case 274 /* CatchClause */: + return visitCatchClause(node); + case 189 /* PropertyAccessExpression */: + if (capturedSuperProperties && ts.isPropertyAccessExpression(node) && node.expression.kind === 98 /* SuperKeyword */) { + capturedSuperProperties.set(node.name.escapedText, true); + } + return ts.visitEachChild(node, visitor, context); + case 190 /* ElementAccessExpression */: + if (capturedSuperProperties && node.expression.kind === 98 /* SuperKeyword */) { + hasSuperElementAccess = true; + } + return ts.visitEachChild(node, visitor, context); + default: + return ts.visitEachChild(node, visitor, context); + } + } + function visitAwaitExpression(node) { + if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */) { + return ts.setOriginalNode(ts.setTextRange(ts.createYield(createAwaitHelper(context, ts.visitNode(node.expression, visitor, ts.isExpression))), + /*location*/ node), node); + } + return ts.visitEachChild(node, visitor, context); + } + function visitYieldExpression(node) { + if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */) { + if (node.asteriskToken) { + var expression = ts.visitNode(node.expression, visitor, ts.isExpression); + return ts.setOriginalNode(ts.setTextRange(ts.createYield(createAwaitHelper(context, ts.updateYield(node, node.asteriskToken, createAsyncDelegatorHelper(context, createAsyncValuesHelper(context, expression, expression), expression)))), node), node); + } + return ts.setOriginalNode(ts.setTextRange(ts.createYield(createDownlevelAwait(node.expression + ? ts.visitNode(node.expression, visitor, ts.isExpression) + : ts.createVoidZero())), node), node); + } + return ts.visitEachChild(node, visitor, context); + } + function visitReturnStatement(node) { + if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */) { + return ts.updateReturn(node, createDownlevelAwait(node.expression ? ts.visitNode(node.expression, visitor, ts.isExpression) : ts.createVoidZero())); + } + return ts.visitEachChild(node, visitor, context); + } + function visitLabeledStatement(node) { + if (enclosingFunctionFlags & 2 /* Async */) { + var statement = ts.unwrapInnermostStatementOfLabel(node); + if (statement.kind === 227 /* ForOfStatement */ && statement.awaitModifier) { + return visitForOfStatement(statement, node); + } + return ts.restoreEnclosingLabel(ts.visitEachChild(statement, visitor, context), node); + } + return ts.visitEachChild(node, visitor, context); + } + function chunkObjectLiteralElements(elements) { + var chunkObject; + var objects = []; + for (var _i = 0, elements_4 = elements; _i < elements_4.length; _i++) { + var e = elements_4[_i]; + if (e.kind === 277 /* SpreadAssignment */) { + if (chunkObject) { + objects.push(ts.createObjectLiteral(chunkObject)); + chunkObject = undefined; + } + var target = e.expression; + objects.push(ts.visitNode(target, visitor, ts.isExpression)); + } + else { + chunkObject = ts.append(chunkObject, e.kind === 275 /* PropertyAssignment */ + ? ts.createPropertyAssignment(e.name, ts.visitNode(e.initializer, visitor, ts.isExpression)) + : ts.visitNode(e, visitor, ts.isObjectLiteralElementLike)); + } + } + if (chunkObject) { + objects.push(ts.createObjectLiteral(chunkObject)); + } + return objects; + } + function visitObjectLiteralExpression(node) { + if (node.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { + // spread elements emit like so: + // non-spread elements are chunked together into object literals, and then all are passed to __assign: + // { a, ...o, b } => __assign({a}, o, {b}); + // If the first element is a spread element, then the first argument to __assign is {}: + // { ...o, a, b, ...o2 } => __assign({}, o, {a, b}, o2) + var objects = chunkObjectLiteralElements(node.properties); + if (objects.length && objects[0].kind !== 188 /* ObjectLiteralExpression */) { + objects.unshift(ts.createObjectLiteral()); + } + return createAssignHelper(context, objects); + } + return ts.visitEachChild(node, visitor, context); + } + function visitExpressionStatement(node) { + return ts.visitEachChild(node, visitorNoDestructuringValue, context); + } + function visitParenthesizedExpression(node, noDestructuringValue) { + return ts.visitEachChild(node, noDestructuringValue ? visitorNoDestructuringValue : visitor, context); + } + function visitCatchClause(node) { + if (!node.variableDeclaration) { + return ts.updateCatchClause(node, ts.createVariableDeclaration(ts.createTempVariable(/*recordTempVariable*/ undefined)), ts.visitNode(node.block, visitor, ts.isBlock)); + } + return ts.visitEachChild(node, visitor, context); + } + /** + * Visits a BinaryExpression that contains a destructuring assignment. + * + * @param node A BinaryExpression node. + */ + function visitBinaryExpression(node, noDestructuringValue) { + if (ts.isDestructuringAssignment(node) && node.left.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { + return ts.flattenDestructuringAssignment(node, visitor, context, 1 /* ObjectRest */, !noDestructuringValue); + } + else if (node.operatorToken.kind === 27 /* CommaToken */) { + return ts.updateBinary(node, ts.visitNode(node.left, visitorNoDestructuringValue, ts.isExpression), ts.visitNode(node.right, noDestructuringValue ? visitorNoDestructuringValue : visitor, ts.isExpression)); + } + return ts.visitEachChild(node, visitor, context); + } + /** + * Visits a VariableDeclaration node with a binding pattern. + * + * @param node A VariableDeclaration node. + */ + function visitVariableDeclaration(node) { + // If we are here it is because the name contains a binding pattern with a rest somewhere in it. + if (ts.isBindingPattern(node.name) && node.name.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { + return ts.flattenDestructuringBinding(node, visitor, context, 1 /* ObjectRest */); + } + return ts.visitEachChild(node, visitor, context); + } + function visitForStatement(node) { + return ts.updateFor(node, ts.visitNode(node.initializer, visitorNoDestructuringValue, ts.isForInitializer), ts.visitNode(node.condition, visitor, ts.isExpression), ts.visitNode(node.incrementor, visitor, ts.isExpression), ts.visitNode(node.statement, visitor, ts.isStatement)); + } + function visitVoidExpression(node) { + return ts.visitEachChild(node, visitorNoDestructuringValue, context); + } + /** + * Visits a ForOfStatement and converts it into a ES2015-compatible ForOfStatement. + * + * @param node A ForOfStatement. + */ + function visitForOfStatement(node, outermostLabeledStatement) { + if (node.initializer.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { + node = transformForOfStatementWithObjectRest(node); + } + if (node.awaitModifier) { + return transformForAwaitOfStatement(node, outermostLabeledStatement); + } + else { + return ts.restoreEnclosingLabel(ts.visitEachChild(node, visitor, context), outermostLabeledStatement); + } + } + function transformForOfStatementWithObjectRest(node) { + var initializerWithoutParens = ts.skipParentheses(node.initializer); + if (ts.isVariableDeclarationList(initializerWithoutParens) || ts.isAssignmentPattern(initializerWithoutParens)) { + var bodyLocation = void 0; + var statementsLocation = void 0; + var temp = ts.createTempVariable(/*recordTempVariable*/ undefined); + var statements = [ts.createForOfBindingStatement(initializerWithoutParens, temp)]; + if (ts.isBlock(node.statement)) { + ts.addRange(statements, node.statement.statements); + bodyLocation = node.statement; + statementsLocation = node.statement.statements; + } + else if (node.statement) { + ts.append(statements, node.statement); + bodyLocation = node.statement; + statementsLocation = node.statement; + } + return ts.updateForOf(node, node.awaitModifier, ts.setTextRange(ts.createVariableDeclarationList([ + ts.setTextRange(ts.createVariableDeclaration(temp), node.initializer) + ], 1 /* Let */), node.initializer), node.expression, ts.setTextRange(ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), statementsLocation), + /*multiLine*/ true), bodyLocation)); + } + return node; + } + function convertForOfStatementHead(node, boundValue) { + var binding = ts.createForOfBindingStatement(node.initializer, boundValue); + var bodyLocation; + var statementsLocation; + var statements = [ts.visitNode(binding, visitor, ts.isStatement)]; + var statement = ts.visitNode(node.statement, visitor, ts.isStatement); + if (ts.isBlock(statement)) { + ts.addRange(statements, statement.statements); + bodyLocation = statement; + statementsLocation = statement.statements; + } + else { + statements.push(statement); + } + return ts.setEmitFlags(ts.setTextRange(ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), statementsLocation), + /*multiLine*/ true), bodyLocation), 48 /* NoSourceMap */ | 384 /* NoTokenSourceMaps */); + } + function createDownlevelAwait(expression) { + return enclosingFunctionFlags & 1 /* Generator */ + ? ts.createYield(/*asteriskToken*/ undefined, createAwaitHelper(context, expression)) + : ts.createAwait(expression); + } + function transformForAwaitOfStatement(node, outermostLabeledStatement) { + var expression = ts.visitNode(node.expression, visitor, ts.isExpression); + var iterator = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(expression) : ts.createTempVariable(/*recordTempVariable*/ undefined); + var result = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(iterator) : ts.createTempVariable(/*recordTempVariable*/ undefined); + var errorRecord = ts.createUniqueName("e"); + var catchVariable = ts.getGeneratedNameForNode(errorRecord); + var returnMethod = ts.createTempVariable(/*recordTempVariable*/ undefined); + var callValues = createAsyncValuesHelper(context, expression, /*location*/ node.expression); + var callNext = ts.createCall(ts.createPropertyAccess(iterator, "next"), /*typeArguments*/ undefined, []); + var getDone = ts.createPropertyAccess(result, "done"); + var getValue = ts.createPropertyAccess(result, "value"); + var callReturn = ts.createFunctionCall(returnMethod, iterator, []); + hoistVariableDeclaration(errorRecord); + hoistVariableDeclaration(returnMethod); + var forStatement = ts.setEmitFlags(ts.setTextRange(ts.createFor( + /*initializer*/ ts.setEmitFlags(ts.setTextRange(ts.createVariableDeclarationList([ + ts.setTextRange(ts.createVariableDeclaration(iterator, /*type*/ undefined, callValues), node.expression), + ts.createVariableDeclaration(result) + ]), node.expression), 2097152 /* NoHoisting */), + /*condition*/ ts.createComma(ts.createAssignment(result, createDownlevelAwait(callNext)), ts.createLogicalNot(getDone)), + /*incrementor*/ undefined, + /*statement*/ convertForOfStatementHead(node, getValue)), + /*location*/ node), 256 /* NoTokenTrailingSourceMaps */); + return ts.createTry(ts.createBlock([ + ts.restoreEnclosingLabel(forStatement, outermostLabeledStatement) + ]), ts.createCatchClause(ts.createVariableDeclaration(catchVariable), ts.setEmitFlags(ts.createBlock([ + ts.createExpressionStatement(ts.createAssignment(errorRecord, ts.createObjectLiteral([ + ts.createPropertyAssignment("error", catchVariable) + ]))) + ]), 1 /* SingleLine */)), ts.createBlock([ + ts.createTry( + /*tryBlock*/ ts.createBlock([ + ts.setEmitFlags(ts.createIf(ts.createLogicalAnd(ts.createLogicalAnd(result, ts.createLogicalNot(getDone)), ts.createAssignment(returnMethod, ts.createPropertyAccess(iterator, "return"))), ts.createExpressionStatement(createDownlevelAwait(callReturn))), 1 /* SingleLine */) + ]), + /*catchClause*/ undefined, + /*finallyBlock*/ ts.setEmitFlags(ts.createBlock([ + ts.setEmitFlags(ts.createIf(errorRecord, ts.createThrow(ts.createPropertyAccess(errorRecord, "error"))), 1 /* SingleLine */) + ]), 1 /* SingleLine */)) + ])); + } + function visitParameter(node) { + if (node.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { + // Binding patterns are converted into a generated name and are + // evaluated inside the function body. + return ts.updateParameter(node, + /*decorators*/ undefined, + /*modifiers*/ undefined, node.dotDotDotToken, ts.getGeneratedNameForNode(node), + /*questionToken*/ undefined, + /*type*/ undefined, ts.visitNode(node.initializer, visitor, ts.isExpression)); + } + return ts.visitEachChild(node, visitor, context); + } + function visitConstructorDeclaration(node) { + var savedEnclosingFunctionFlags = enclosingFunctionFlags; + enclosingFunctionFlags = 0 /* Normal */; + var updated = ts.updateConstructor(node, + /*decorators*/ undefined, node.modifiers, ts.visitParameterList(node.parameters, visitor, context), transformFunctionBody(node)); + enclosingFunctionFlags = savedEnclosingFunctionFlags; + return updated; + } + function visitGetAccessorDeclaration(node) { + var savedEnclosingFunctionFlags = enclosingFunctionFlags; + enclosingFunctionFlags = 0 /* Normal */; + var updated = ts.updateGetAccessor(node, + /*decorators*/ undefined, node.modifiers, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, transformFunctionBody(node)); + enclosingFunctionFlags = savedEnclosingFunctionFlags; + return updated; + } + function visitSetAccessorDeclaration(node) { + var savedEnclosingFunctionFlags = enclosingFunctionFlags; + enclosingFunctionFlags = 0 /* Normal */; + var updated = ts.updateSetAccessor(node, + /*decorators*/ undefined, node.modifiers, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitParameterList(node.parameters, visitor, context), transformFunctionBody(node)); + enclosingFunctionFlags = savedEnclosingFunctionFlags; + return updated; + } + function visitMethodDeclaration(node) { + var savedEnclosingFunctionFlags = enclosingFunctionFlags; + enclosingFunctionFlags = ts.getFunctionFlags(node); + var updated = ts.updateMethod(node, + /*decorators*/ undefined, enclosingFunctionFlags & 1 /* Generator */ + ? ts.visitNodes(node.modifiers, visitorNoAsyncModifier, ts.isModifier) + : node.modifiers, enclosingFunctionFlags & 2 /* Async */ + ? undefined + : node.asteriskToken, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitNode(/*questionToken*/ undefined, visitor, ts.isToken), + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */ + ? transformAsyncGeneratorFunctionBody(node) + : transformFunctionBody(node)); + enclosingFunctionFlags = savedEnclosingFunctionFlags; + return updated; + } + function visitFunctionDeclaration(node) { + var savedEnclosingFunctionFlags = enclosingFunctionFlags; + enclosingFunctionFlags = ts.getFunctionFlags(node); + var updated = ts.updateFunctionDeclaration(node, + /*decorators*/ undefined, enclosingFunctionFlags & 1 /* Generator */ + ? ts.visitNodes(node.modifiers, visitorNoAsyncModifier, ts.isModifier) + : node.modifiers, enclosingFunctionFlags & 2 /* Async */ + ? undefined + : node.asteriskToken, node.name, + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */ + ? transformAsyncGeneratorFunctionBody(node) + : transformFunctionBody(node)); + enclosingFunctionFlags = savedEnclosingFunctionFlags; + return updated; + } + function visitArrowFunction(node) { + var savedEnclosingFunctionFlags = enclosingFunctionFlags; + enclosingFunctionFlags = ts.getFunctionFlags(node); + var updated = ts.updateArrowFunction(node, node.modifiers, + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, node.equalsGreaterThanToken, transformFunctionBody(node)); + enclosingFunctionFlags = savedEnclosingFunctionFlags; + return updated; + } + function visitFunctionExpression(node) { + var savedEnclosingFunctionFlags = enclosingFunctionFlags; + enclosingFunctionFlags = ts.getFunctionFlags(node); + var updated = ts.updateFunctionExpression(node, enclosingFunctionFlags & 1 /* Generator */ + ? ts.visitNodes(node.modifiers, visitorNoAsyncModifier, ts.isModifier) + : node.modifiers, enclosingFunctionFlags & 2 /* Async */ + ? undefined + : node.asteriskToken, node.name, + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */ + ? transformAsyncGeneratorFunctionBody(node) + : transformFunctionBody(node)); + enclosingFunctionFlags = savedEnclosingFunctionFlags; + return updated; + } + function transformAsyncGeneratorFunctionBody(node) { + resumeLexicalEnvironment(); + var statements = []; + var statementOffset = ts.addPrologue(statements, node.body.statements, /*ensureUseStrict*/ false, visitor); + appendObjectRestAssignmentsIfNeeded(statements, node); + var savedCapturedSuperProperties = capturedSuperProperties; + var savedHasSuperElementAccess = hasSuperElementAccess; + capturedSuperProperties = ts.createUnderscoreEscapedMap(); + hasSuperElementAccess = false; + var returnStatement = ts.createReturn(createAsyncGeneratorHelper(context, ts.createFunctionExpression( + /*modifiers*/ undefined, ts.createToken(40 /* AsteriskToken */), node.name && ts.getGeneratedNameForNode(node.name), + /*typeParameters*/ undefined, + /*parameters*/ [], + /*type*/ undefined, ts.updateBlock(node.body, ts.visitLexicalEnvironment(node.body.statements, visitor, context, statementOffset))))); + // Minor optimization, emit `_super` helper to capture `super` access in an arrow. + // This step isn't needed if we eventually transform this to ES5. + var emitSuperHelpers = languageVersion >= 2 /* ES2015 */ && resolver.getNodeCheckFlags(node) & (4096 /* AsyncMethodWithSuperBinding */ | 2048 /* AsyncMethodWithSuper */); + if (emitSuperHelpers) { + enableSubstitutionForAsyncMethodsWithSuper(); + var variableStatement = ts.createSuperAccessVariableStatement(resolver, node, capturedSuperProperties); + substitutedSuperAccessors[ts.getNodeId(variableStatement)] = true; + ts.addStatementsAfterPrologue(statements, [variableStatement]); + } + statements.push(returnStatement); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + var block = ts.updateBlock(node.body, statements); + if (emitSuperHelpers && hasSuperElementAccess) { + if (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) { + ts.addEmitHelper(block, ts.advancedAsyncSuperHelper); + } + else if (resolver.getNodeCheckFlags(node) & 2048 /* AsyncMethodWithSuper */) { + ts.addEmitHelper(block, ts.asyncSuperHelper); + } + } + capturedSuperProperties = savedCapturedSuperProperties; + hasSuperElementAccess = savedHasSuperElementAccess; + return block; + } + function transformFunctionBody(node) { + resumeLexicalEnvironment(); + var statementOffset = 0; + var statements = []; + var body = ts.visitNode(node.body, visitor, ts.isConciseBody); + if (ts.isBlock(body)) { + statementOffset = ts.addPrologue(statements, body.statements, /*ensureUseStrict*/ false, visitor); + } + ts.addRange(statements, appendObjectRestAssignmentsIfNeeded(/*statements*/ undefined, node)); + var leadingStatements = endLexicalEnvironment(); + if (statementOffset > 0 || ts.some(statements) || ts.some(leadingStatements)) { + var block = ts.convertToFunctionBody(body, /*multiLine*/ true); + ts.addStatementsAfterPrologue(statements, leadingStatements); + ts.addRange(statements, block.statements.slice(statementOffset)); + return ts.updateBlock(block, ts.setTextRange(ts.createNodeArray(statements), block.statements)); + } + return body; + } + function appendObjectRestAssignmentsIfNeeded(statements, node) { + for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { + var parameter = _a[_i]; + if (parameter.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { + var temp = ts.getGeneratedNameForNode(parameter); + var declarations = ts.flattenDestructuringBinding(parameter, visitor, context, 1 /* ObjectRest */, temp, + /*doNotRecordTempVariablesInLine*/ false, + /*skipInitializer*/ true); + if (ts.some(declarations)) { + var statement = ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList(declarations)); + ts.setEmitFlags(statement, 1048576 /* CustomPrologue */); + statements = ts.append(statements, statement); + } + } + } + return statements; + } + function enableSubstitutionForAsyncMethodsWithSuper() { + if ((enabledSubstitutions & 1 /* AsyncMethodsWithSuper */) === 0) { + enabledSubstitutions |= 1 /* AsyncMethodsWithSuper */; + // We need to enable substitutions for call, property access, and element access + // if we need to rewrite super calls. + context.enableSubstitution(191 /* CallExpression */); + context.enableSubstitution(189 /* PropertyAccessExpression */); + context.enableSubstitution(190 /* ElementAccessExpression */); + // We need to be notified when entering and exiting declarations that bind super. + context.enableEmitNotification(240 /* ClassDeclaration */); + context.enableEmitNotification(156 /* MethodDeclaration */); + context.enableEmitNotification(158 /* GetAccessor */); + context.enableEmitNotification(159 /* SetAccessor */); + context.enableEmitNotification(157 /* Constructor */); + // We need to be notified when entering the generated accessor arrow functions. + context.enableEmitNotification(219 /* VariableStatement */); + } + } + /** + * Called by the printer just before a node is printed. + * + * @param hint A hint as to the intended usage of the node. + * @param node The node to be printed. + * @param emitCallback The callback used to emit the node. + */ + function onEmitNode(hint, node, emitCallback) { + // If we need to support substitutions for `super` in an async method, + // we should track it here. + if (enabledSubstitutions & 1 /* AsyncMethodsWithSuper */ && isSuperContainer(node)) { + var superContainerFlags = resolver.getNodeCheckFlags(node) & (2048 /* AsyncMethodWithSuper */ | 4096 /* AsyncMethodWithSuperBinding */); + if (superContainerFlags !== enclosingSuperContainerFlags) { + var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags; + enclosingSuperContainerFlags = superContainerFlags; + previousOnEmitNode(hint, node, emitCallback); + enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags; + return; + } + } + // Disable substitution in the generated super accessor itself. + else if (enabledSubstitutions && substitutedSuperAccessors[ts.getNodeId(node)]) { + var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags; + enclosingSuperContainerFlags = 0; + previousOnEmitNode(hint, node, emitCallback); + enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags; + return; + } + previousOnEmitNode(hint, node, emitCallback); + } + /** + * Hooks node substitutions. + * + * @param hint The context for the emitter. + * @param node The node to substitute. + */ + function onSubstituteNode(hint, node) { + node = previousOnSubstituteNode(hint, node); + if (hint === 1 /* Expression */ && enclosingSuperContainerFlags) { + return substituteExpression(node); + } + return node; + } + function substituteExpression(node) { + switch (node.kind) { + case 189 /* PropertyAccessExpression */: + return substitutePropertyAccessExpression(node); + case 190 /* ElementAccessExpression */: + return substituteElementAccessExpression(node); + case 191 /* CallExpression */: + return substituteCallExpression(node); + } + return node; + } + function substitutePropertyAccessExpression(node) { + if (node.expression.kind === 98 /* SuperKeyword */) { + return ts.setTextRange(ts.createPropertyAccess(ts.createFileLevelUniqueName("_super"), node.name), node); + } + return node; + } + function substituteElementAccessExpression(node) { + if (node.expression.kind === 98 /* SuperKeyword */) { + return createSuperElementAccessInAsyncMethod(node.argumentExpression, node); + } + return node; + } + function substituteCallExpression(node) { + var expression = node.expression; + if (ts.isSuperProperty(expression)) { + var argumentExpression = ts.isPropertyAccessExpression(expression) + ? substitutePropertyAccessExpression(expression) + : substituteElementAccessExpression(expression); + return ts.createCall(ts.createPropertyAccess(argumentExpression, "call"), + /*typeArguments*/ undefined, [ + ts.createThis() + ].concat(node.arguments)); + } + return node; + } + function isSuperContainer(node) { + var kind = node.kind; + return kind === 240 /* ClassDeclaration */ + || kind === 157 /* Constructor */ + || kind === 156 /* MethodDeclaration */ + || kind === 158 /* GetAccessor */ + || kind === 159 /* SetAccessor */; + } + function createSuperElementAccessInAsyncMethod(argumentExpression, location) { + if (enclosingSuperContainerFlags & 4096 /* AsyncMethodWithSuperBinding */) { + return ts.setTextRange(ts.createPropertyAccess(ts.createCall(ts.createIdentifier("_superIndex"), + /*typeArguments*/ undefined, [argumentExpression]), "value"), location); + } + else { + return ts.setTextRange(ts.createCall(ts.createIdentifier("_superIndex"), + /*typeArguments*/ undefined, [argumentExpression]), location); + } + } + } + ts.transformESNext = transformESNext; + var assignHelper = { + name: "typescript:assign", + scoped: false, + priority: 1, + text: "\n var __assign = (this && this.__assign) || function () {\n __assign = Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n };\n return __assign.apply(this, arguments);\n };" + }; + function createAssignHelper(context, attributesSegments) { + if (context.getCompilerOptions().target >= 2 /* ES2015 */) { + return ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "assign"), + /*typeArguments*/ undefined, attributesSegments); + } + context.requestEmitHelper(assignHelper); + return ts.createCall(ts.getHelperName("__assign"), + /*typeArguments*/ undefined, attributesSegments); + } + ts.createAssignHelper = createAssignHelper; + var awaitHelper = { + name: "typescript:await", + scoped: false, + text: "\n var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }" + }; + function createAwaitHelper(context, expression) { + context.requestEmitHelper(awaitHelper); + return ts.createCall(ts.getHelperName("__await"), /*typeArguments*/ undefined, [expression]); + } + var asyncGeneratorHelper = { + name: "typescript:asyncGenerator", + scoped: false, + text: "\n var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\n function fulfill(value) { resume(\"next\", value); }\n function reject(value) { resume(\"throw\", value); }\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\n };" + }; + function createAsyncGeneratorHelper(context, generatorFunc) { + context.requestEmitHelper(awaitHelper); + context.requestEmitHelper(asyncGeneratorHelper); + // Mark this node as originally an async function + (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 262144 /* AsyncFunctionBody */; + return ts.createCall(ts.getHelperName("__asyncGenerator"), + /*typeArguments*/ undefined, [ + ts.createThis(), + ts.createIdentifier("arguments"), + generatorFunc + ]); + } + var asyncDelegator = { + name: "typescript:asyncDelegator", + scoped: false, + text: "\n var __asyncDelegator = (this && this.__asyncDelegator) || function (o) {\n var i, p;\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; } : f; }\n };" + }; + function createAsyncDelegatorHelper(context, expression, location) { + context.requestEmitHelper(awaitHelper); + context.requestEmitHelper(asyncDelegator); + return ts.setTextRange(ts.createCall(ts.getHelperName("__asyncDelegator"), + /*typeArguments*/ undefined, [expression]), location); + } + var asyncValues = { + name: "typescript:asyncValues", + scoped: false, + text: "\n var __asyncValues = (this && this.__asyncValues) || function (o) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var m = o[Symbol.asyncIterator], i;\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\n };" + }; + function createAsyncValuesHelper(context, expression, location) { + context.requestEmitHelper(asyncValues); + return ts.setTextRange(ts.createCall(ts.getHelperName("__asyncValues"), + /*typeArguments*/ undefined, [expression]), location); + } +})(ts || (ts = {})); +/*@internal*/ +var ts; +(function (ts) { + function transformJsx(context) { + var compilerOptions = context.getCompilerOptions(); + var currentSourceFile; + return ts.chainBundle(transformSourceFile); + /** + * Transform JSX-specific syntax in a SourceFile. + * + * @param node A SourceFile node. + */ + function transformSourceFile(node) { + if (node.isDeclarationFile) { + return node; + } + currentSourceFile = node; + var visited = ts.visitEachChild(node, visitor, context); + ts.addEmitHelpers(visited, context.readEmitHelpers()); + return visited; + } + function visitor(node) { + if (node.transformFlags & 4 /* ContainsJsx */) { + return visitorWorker(node); + } + else { + return node; + } + } + function visitorWorker(node) { + switch (node.kind) { + case 260 /* JsxElement */: + return visitJsxElement(node, /*isChild*/ false); + case 261 /* JsxSelfClosingElement */: + return visitJsxSelfClosingElement(node, /*isChild*/ false); + case 264 /* JsxFragment */: + return visitJsxFragment(node, /*isChild*/ false); + case 270 /* JsxExpression */: + return visitJsxExpression(node); + default: + return ts.visitEachChild(node, visitor, context); + } + } + function transformJsxChildToExpression(node) { + switch (node.kind) { + case 11 /* JsxText */: + return visitJsxText(node); + case 270 /* JsxExpression */: + return visitJsxExpression(node); + case 260 /* JsxElement */: + return visitJsxElement(node, /*isChild*/ true); + case 261 /* JsxSelfClosingElement */: + return visitJsxSelfClosingElement(node, /*isChild*/ true); + case 264 /* JsxFragment */: + return visitJsxFragment(node, /*isChild*/ true); + default: + return ts.Debug.failBadSyntaxKind(node); + } + } + function visitJsxElement(node, isChild) { + return visitJsxOpeningLikeElement(node.openingElement, node.children, isChild, /*location*/ node); + } + function visitJsxSelfClosingElement(node, isChild) { + return visitJsxOpeningLikeElement(node, /*children*/ undefined, isChild, /*location*/ node); + } + function visitJsxFragment(node, isChild) { + return visitJsxOpeningFragment(node.openingFragment, node.children, isChild, /*location*/ node); + } + function visitJsxOpeningLikeElement(node, children, isChild, location) { + var tagName = getTagName(node); + var objectProperties; + var attrs = node.attributes.properties; + if (attrs.length === 0) { + // When there are no attributes, React wants "null" + objectProperties = ts.createNull(); + } + else { + // Map spans of JsxAttribute nodes into object literals and spans + // of JsxSpreadAttribute nodes into expressions. + var segments = ts.flatten(ts.spanMap(attrs, ts.isJsxSpreadAttribute, function (attrs, isSpread) { return isSpread + ? ts.map(attrs, transformJsxSpreadAttributeToExpression) + : ts.createObjectLiteral(ts.map(attrs, transformJsxAttributeToObjectLiteralElement)); })); + if (ts.isJsxSpreadAttribute(attrs[0])) { + // We must always emit at least one object literal before a spread + // argument. + segments.unshift(ts.createObjectLiteral()); + } + // Either emit one big object literal (no spread attribs), or + // a call to the __assign helper. + objectProperties = ts.singleOrUndefined(segments); + if (!objectProperties) { + objectProperties = ts.createAssignHelper(context, segments); + } + } + var element = ts.createExpressionForJsxElement(context.getEmitResolver().getJsxFactoryEntity(currentSourceFile), compilerOptions.reactNamespace, // TODO: GH#18217 + tagName, objectProperties, ts.mapDefined(children, transformJsxChildToExpression), node, location); + if (isChild) { + ts.startOnNewLine(element); + } + return element; + } + function visitJsxOpeningFragment(node, children, isChild, location) { + var element = ts.createExpressionForJsxFragment(context.getEmitResolver().getJsxFactoryEntity(currentSourceFile), compilerOptions.reactNamespace, // TODO: GH#18217 + ts.mapDefined(children, transformJsxChildToExpression), node, location); + if (isChild) { + ts.startOnNewLine(element); + } + return element; + } + function transformJsxSpreadAttributeToExpression(node) { + return ts.visitNode(node.expression, visitor, ts.isExpression); + } + function transformJsxAttributeToObjectLiteralElement(node) { + var name = getAttributeName(node); + var expression = transformJsxAttributeInitializer(node.initializer); + return ts.createPropertyAssignment(name, expression); + } + function transformJsxAttributeInitializer(node) { + if (node === undefined) { + return ts.createTrue(); + } + else if (node.kind === 10 /* StringLiteral */) { + // Always recreate the literal to escape any escape sequences or newlines which may be in the original jsx string and which + // Need to be escaped to be handled correctly in a normal string + var literal = ts.createLiteral(tryDecodeEntities(node.text) || node.text); + literal.singleQuote = node.singleQuote !== undefined ? node.singleQuote : !ts.isStringDoubleQuoted(node, currentSourceFile); + return ts.setTextRange(literal, node); + } + else if (node.kind === 270 /* JsxExpression */) { + if (node.expression === undefined) { + return ts.createTrue(); + } + return visitJsxExpression(node); + } + else { + return ts.Debug.failBadSyntaxKind(node); + } + } + function visitJsxText(node) { + var fixed = fixupWhitespaceAndDecodeEntities(ts.getTextOfNode(node, /*includeTrivia*/ true)); + return fixed === undefined ? undefined : ts.createLiteral(fixed); + } + /** + * JSX trims whitespace at the end and beginning of lines, except that the + * start/end of a tag is considered a start/end of a line only if that line is + * on the same line as the closing tag. See examples in + * tests/cases/conformance/jsx/tsxReactEmitWhitespace.tsx + * See also https://www.w3.org/TR/html4/struct/text.html#h-9.1 and https://www.w3.org/TR/CSS2/text.html#white-space-model + * + * An equivalent algorithm would be: + * - If there is only one line, return it. + * - If there is only whitespace (but multiple lines), return `undefined`. + * - Split the text into lines. + * - 'trimRight' the first line, 'trimLeft' the last line, 'trim' middle lines. + * - Decode entities on each line (individually). + * - Remove empty lines and join the rest with " ". + */ + function fixupWhitespaceAndDecodeEntities(text) { + var acc; + // First non-whitespace character on this line. + var firstNonWhitespace = 0; + // Last non-whitespace character on this line. + var lastNonWhitespace = -1; + // These initial values are special because the first line is: + // firstNonWhitespace = 0 to indicate that we want leading whitsepace, + // but lastNonWhitespace = -1 as a special flag to indicate that we *don't* include the line if it's all whitespace. + for (var i = 0; i < text.length; i++) { + var c = text.charCodeAt(i); + if (ts.isLineBreak(c)) { + // If we've seen any non-whitespace characters on this line, add the 'trim' of the line. + // (lastNonWhitespace === -1 is a special flag to detect whether the first line is all whitespace.) + if (firstNonWhitespace !== -1 && lastNonWhitespace !== -1) { + acc = addLineOfJsxText(acc, text.substr(firstNonWhitespace, lastNonWhitespace - firstNonWhitespace + 1)); + } + // Reset firstNonWhitespace for the next line. + // Don't bother to reset lastNonWhitespace because we ignore it if firstNonWhitespace = -1. + firstNonWhitespace = -1; + } + else if (!ts.isWhiteSpaceSingleLine(c)) { + lastNonWhitespace = i; + if (firstNonWhitespace === -1) { + firstNonWhitespace = i; + } + } + } + return firstNonWhitespace !== -1 + // Last line had a non-whitespace character. Emit the 'trimLeft', meaning keep trailing whitespace. + ? addLineOfJsxText(acc, text.substr(firstNonWhitespace)) + // Last line was all whitespace, so ignore it + : acc; + } + function addLineOfJsxText(acc, trimmedLine) { + // We do not escape the string here as that is handled by the printer + // when it emits the literal. We do, however, need to decode JSX entities. + var decoded = decodeEntities(trimmedLine); + return acc === undefined ? decoded : acc + " " + decoded; + } + /** + * Replace entities like " ", "{", and "�" with the characters they encode. + * See https://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references + */ + function decodeEntities(text) { + return text.replace(/&((#((\d+)|x([\da-fA-F]+)))|(\w+));/g, function (match, _all, _number, _digits, decimal, hex, word) { + if (decimal) { + return String.fromCharCode(parseInt(decimal, 10)); + } + else if (hex) { + return String.fromCharCode(parseInt(hex, 16)); + } + else { + var ch = entities.get(word); + // If this is not a valid entity, then just use `match` (replace it with itself, i.e. don't replace) + return ch ? String.fromCharCode(ch) : match; + } + }); + } + /** Like `decodeEntities` but returns `undefined` if there were no entities to decode. */ + function tryDecodeEntities(text) { + var decoded = decodeEntities(text); + return decoded === text ? undefined : decoded; + } + function getTagName(node) { + if (node.kind === 260 /* JsxElement */) { + return getTagName(node.openingElement); + } + else { + var name = node.tagName; + if (ts.isIdentifier(name) && ts.isIntrinsicJsxName(name.escapedText)) { + return ts.createLiteral(ts.idText(name)); + } + else { + return ts.createExpressionFromEntityName(name); + } + } + } + /** + * Emit an attribute name, which is quoted if it needs to be quoted. Because + * these emit into an object literal property name, we don't need to be worried + * about keywords, just non-identifier characters + */ + function getAttributeName(node) { + var name = node.name; + var text = ts.idText(name); + if (/^[A-Za-z_]\w*$/.test(text)) { + return name; + } + else { + return ts.createLiteral(text); + } + } + function visitJsxExpression(node) { + return ts.visitNode(node.expression, visitor, ts.isExpression); + } + } + ts.transformJsx = transformJsx; + var entities = ts.createMapFromTemplate({ + quot: 0x0022, + amp: 0x0026, + apos: 0x0027, + lt: 0x003C, + gt: 0x003E, + nbsp: 0x00A0, + iexcl: 0x00A1, + cent: 0x00A2, + pound: 0x00A3, + curren: 0x00A4, + yen: 0x00A5, + brvbar: 0x00A6, + sect: 0x00A7, + uml: 0x00A8, + copy: 0x00A9, + ordf: 0x00AA, + laquo: 0x00AB, + not: 0x00AC, + shy: 0x00AD, + reg: 0x00AE, + macr: 0x00AF, + deg: 0x00B0, + plusmn: 0x00B1, + sup2: 0x00B2, + sup3: 0x00B3, + acute: 0x00B4, + micro: 0x00B5, + para: 0x00B6, + middot: 0x00B7, + cedil: 0x00B8, + sup1: 0x00B9, + ordm: 0x00BA, + raquo: 0x00BB, + frac14: 0x00BC, + frac12: 0x00BD, + frac34: 0x00BE, + iquest: 0x00BF, + Agrave: 0x00C0, + Aacute: 0x00C1, + Acirc: 0x00C2, + Atilde: 0x00C3, + Auml: 0x00C4, + Aring: 0x00C5, + AElig: 0x00C6, + Ccedil: 0x00C7, + Egrave: 0x00C8, + Eacute: 0x00C9, + Ecirc: 0x00CA, + Euml: 0x00CB, + Igrave: 0x00CC, + Iacute: 0x00CD, + Icirc: 0x00CE, + Iuml: 0x00CF, + ETH: 0x00D0, + Ntilde: 0x00D1, + Ograve: 0x00D2, + Oacute: 0x00D3, + Ocirc: 0x00D4, + Otilde: 0x00D5, + Ouml: 0x00D6, + times: 0x00D7, + Oslash: 0x00D8, + Ugrave: 0x00D9, + Uacute: 0x00DA, + Ucirc: 0x00DB, + Uuml: 0x00DC, + Yacute: 0x00DD, + THORN: 0x00DE, + szlig: 0x00DF, + agrave: 0x00E0, + aacute: 0x00E1, + acirc: 0x00E2, + atilde: 0x00E3, + auml: 0x00E4, + aring: 0x00E5, + aelig: 0x00E6, + ccedil: 0x00E7, + egrave: 0x00E8, + eacute: 0x00E9, + ecirc: 0x00EA, + euml: 0x00EB, + igrave: 0x00EC, + iacute: 0x00ED, + icirc: 0x00EE, + iuml: 0x00EF, + eth: 0x00F0, + ntilde: 0x00F1, + ograve: 0x00F2, + oacute: 0x00F3, + ocirc: 0x00F4, + otilde: 0x00F5, + ouml: 0x00F6, + divide: 0x00F7, + oslash: 0x00F8, + ugrave: 0x00F9, + uacute: 0x00FA, + ucirc: 0x00FB, + uuml: 0x00FC, + yacute: 0x00FD, + thorn: 0x00FE, + yuml: 0x00FF, + OElig: 0x0152, + oelig: 0x0153, + Scaron: 0x0160, + scaron: 0x0161, + Yuml: 0x0178, + fnof: 0x0192, + circ: 0x02C6, + tilde: 0x02DC, + Alpha: 0x0391, + Beta: 0x0392, + Gamma: 0x0393, + Delta: 0x0394, + Epsilon: 0x0395, + Zeta: 0x0396, + Eta: 0x0397, + Theta: 0x0398, + Iota: 0x0399, + Kappa: 0x039A, + Lambda: 0x039B, + Mu: 0x039C, + Nu: 0x039D, + Xi: 0x039E, + Omicron: 0x039F, + Pi: 0x03A0, + Rho: 0x03A1, + Sigma: 0x03A3, + Tau: 0x03A4, + Upsilon: 0x03A5, + Phi: 0x03A6, + Chi: 0x03A7, + Psi: 0x03A8, + Omega: 0x03A9, + alpha: 0x03B1, + beta: 0x03B2, + gamma: 0x03B3, + delta: 0x03B4, + epsilon: 0x03B5, + zeta: 0x03B6, + eta: 0x03B7, + theta: 0x03B8, + iota: 0x03B9, + kappa: 0x03BA, + lambda: 0x03BB, + mu: 0x03BC, + nu: 0x03BD, + xi: 0x03BE, + omicron: 0x03BF, + pi: 0x03C0, + rho: 0x03C1, + sigmaf: 0x03C2, + sigma: 0x03C3, + tau: 0x03C4, + upsilon: 0x03C5, + phi: 0x03C6, + chi: 0x03C7, + psi: 0x03C8, + omega: 0x03C9, + thetasym: 0x03D1, + upsih: 0x03D2, + piv: 0x03D6, + ensp: 0x2002, + emsp: 0x2003, + thinsp: 0x2009, + zwnj: 0x200C, + zwj: 0x200D, + lrm: 0x200E, + rlm: 0x200F, + ndash: 0x2013, + mdash: 0x2014, + lsquo: 0x2018, + rsquo: 0x2019, + sbquo: 0x201A, + ldquo: 0x201C, + rdquo: 0x201D, + bdquo: 0x201E, + dagger: 0x2020, + Dagger: 0x2021, + bull: 0x2022, + hellip: 0x2026, + permil: 0x2030, + prime: 0x2032, + Prime: 0x2033, + lsaquo: 0x2039, + rsaquo: 0x203A, + oline: 0x203E, + frasl: 0x2044, + euro: 0x20AC, + image: 0x2111, + weierp: 0x2118, + real: 0x211C, + trade: 0x2122, + alefsym: 0x2135, + larr: 0x2190, + uarr: 0x2191, + rarr: 0x2192, + darr: 0x2193, + harr: 0x2194, + crarr: 0x21B5, + lArr: 0x21D0, + uArr: 0x21D1, + rArr: 0x21D2, + dArr: 0x21D3, + hArr: 0x21D4, + forall: 0x2200, + part: 0x2202, + exist: 0x2203, + empty: 0x2205, + nabla: 0x2207, + isin: 0x2208, + notin: 0x2209, + ni: 0x220B, + prod: 0x220F, + sum: 0x2211, + minus: 0x2212, + lowast: 0x2217, + radic: 0x221A, + prop: 0x221D, + infin: 0x221E, + ang: 0x2220, + and: 0x2227, + or: 0x2228, + cap: 0x2229, + cup: 0x222A, + int: 0x222B, + there4: 0x2234, + sim: 0x223C, + cong: 0x2245, + asymp: 0x2248, + ne: 0x2260, + equiv: 0x2261, + le: 0x2264, + ge: 0x2265, + sub: 0x2282, + sup: 0x2283, + nsub: 0x2284, + sube: 0x2286, + supe: 0x2287, + oplus: 0x2295, + otimes: 0x2297, + perp: 0x22A5, + sdot: 0x22C5, + lceil: 0x2308, + rceil: 0x2309, + lfloor: 0x230A, + rfloor: 0x230B, + lang: 0x2329, + rang: 0x232A, + loz: 0x25CA, + spades: 0x2660, + clubs: 0x2663, + hearts: 0x2665, + diams: 0x2666 + }); +})(ts || (ts = {})); +/*@internal*/ +var ts; +(function (ts) { + function transformES2016(context) { + var hoistVariableDeclaration = context.hoistVariableDeclaration; + return ts.chainBundle(transformSourceFile); + function transformSourceFile(node) { + if (node.isDeclarationFile) { + return node; + } + return ts.visitEachChild(node, visitor, context); + } + function visitor(node) { + if ((node.transformFlags & 32 /* ContainsES2016 */) === 0) { + return node; + } + switch (node.kind) { + case 204 /* BinaryExpression */: + return visitBinaryExpression(node); + default: + return ts.visitEachChild(node, visitor, context); + } + } + function visitBinaryExpression(node) { + switch (node.operatorToken.kind) { + case 63 /* AsteriskAsteriskEqualsToken */: + return visitExponentiationAssignmentExpression(node); + case 41 /* AsteriskAsteriskToken */: + return visitExponentiationExpression(node); + default: + return ts.visitEachChild(node, visitor, context); + } + } + function visitExponentiationAssignmentExpression(node) { + var target; + var value; + var left = ts.visitNode(node.left, visitor, ts.isExpression); + var right = ts.visitNode(node.right, visitor, ts.isExpression); + if (ts.isElementAccessExpression(left)) { + // Transforms `a[x] **= b` into `(_a = a)[_x = x] = Math.pow(_a[_x], b)` + var expressionTemp = ts.createTempVariable(hoistVariableDeclaration); + var argumentExpressionTemp = ts.createTempVariable(hoistVariableDeclaration); + target = ts.setTextRange(ts.createElementAccess(ts.setTextRange(ts.createAssignment(expressionTemp, left.expression), left.expression), ts.setTextRange(ts.createAssignment(argumentExpressionTemp, left.argumentExpression), left.argumentExpression)), left); + value = ts.setTextRange(ts.createElementAccess(expressionTemp, argumentExpressionTemp), left); + } + else if (ts.isPropertyAccessExpression(left)) { + // Transforms `a.x **= b` into `(_a = a).x = Math.pow(_a.x, b)` + var expressionTemp = ts.createTempVariable(hoistVariableDeclaration); + target = ts.setTextRange(ts.createPropertyAccess(ts.setTextRange(ts.createAssignment(expressionTemp, left.expression), left.expression), left.name), left); + value = ts.setTextRange(ts.createPropertyAccess(expressionTemp, left.name), left); + } + else { + // Transforms `a **= b` into `a = Math.pow(a, b)` + target = left; + value = left; + } + return ts.setTextRange(ts.createAssignment(target, ts.createMathPow(value, right, /*location*/ node)), node); + } + function visitExponentiationExpression(node) { + // Transforms `a ** b` into `Math.pow(a, b)` + var left = ts.visitNode(node.left, visitor, ts.isExpression); + var right = ts.visitNode(node.right, visitor, ts.isExpression); + return ts.createMathPow(left, right, /*location*/ node); + } + } + ts.transformES2016 = transformES2016; +})(ts || (ts = {})); +/*@internal*/ +var ts; +(function (ts) { + var ES2015SubstitutionFlags; + (function (ES2015SubstitutionFlags) { + /** Enables substitutions for captured `this` */ + ES2015SubstitutionFlags[ES2015SubstitutionFlags["CapturedThis"] = 1] = "CapturedThis"; + /** Enables substitutions for block-scoped bindings. */ + ES2015SubstitutionFlags[ES2015SubstitutionFlags["BlockScopedBindings"] = 2] = "BlockScopedBindings"; + })(ES2015SubstitutionFlags || (ES2015SubstitutionFlags = {})); + var LoopOutParameterFlags; + (function (LoopOutParameterFlags) { + LoopOutParameterFlags[LoopOutParameterFlags["Body"] = 1] = "Body"; + LoopOutParameterFlags[LoopOutParameterFlags["Initializer"] = 2] = "Initializer"; + })(LoopOutParameterFlags || (LoopOutParameterFlags = {})); + var CopyDirection; + (function (CopyDirection) { + CopyDirection[CopyDirection["ToOriginal"] = 0] = "ToOriginal"; + CopyDirection[CopyDirection["ToOutParameter"] = 1] = "ToOutParameter"; + })(CopyDirection || (CopyDirection = {})); + var Jump; + (function (Jump) { + Jump[Jump["Break"] = 2] = "Break"; + Jump[Jump["Continue"] = 4] = "Continue"; + Jump[Jump["Return"] = 8] = "Return"; + })(Jump || (Jump = {})); + var SuperCaptureResult; + (function (SuperCaptureResult) { + /** + * A capture may have been added for calls to 'super', but + * the caller should emit subsequent statements normally. + */ + SuperCaptureResult[SuperCaptureResult["NoReplacement"] = 0] = "NoReplacement"; + /** + * A call to 'super()' got replaced with a capturing statement like: + * + * var _this = _super.call(...) || this; + * + * Callers should skip the current statement. + */ + SuperCaptureResult[SuperCaptureResult["ReplaceSuperCapture"] = 1] = "ReplaceSuperCapture"; + /** + * A call to 'super()' got replaced with a capturing statement like: + * + * return _super.call(...) || this; + * + * Callers should skip the current statement and avoid any returns of '_this'. + */ + SuperCaptureResult[SuperCaptureResult["ReplaceWithReturn"] = 2] = "ReplaceWithReturn"; + })(SuperCaptureResult || (SuperCaptureResult = {})); + // Facts we track as we traverse the tree + var HierarchyFacts; + (function (HierarchyFacts) { + HierarchyFacts[HierarchyFacts["None"] = 0] = "None"; + // + // Ancestor facts + // + HierarchyFacts[HierarchyFacts["Function"] = 1] = "Function"; + HierarchyFacts[HierarchyFacts["ArrowFunction"] = 2] = "ArrowFunction"; + HierarchyFacts[HierarchyFacts["AsyncFunctionBody"] = 4] = "AsyncFunctionBody"; + HierarchyFacts[HierarchyFacts["NonStaticClassElement"] = 8] = "NonStaticClassElement"; + HierarchyFacts[HierarchyFacts["CapturesThis"] = 16] = "CapturesThis"; + HierarchyFacts[HierarchyFacts["ExportedVariableStatement"] = 32] = "ExportedVariableStatement"; + HierarchyFacts[HierarchyFacts["TopLevel"] = 64] = "TopLevel"; + HierarchyFacts[HierarchyFacts["Block"] = 128] = "Block"; + HierarchyFacts[HierarchyFacts["IterationStatement"] = 256] = "IterationStatement"; + HierarchyFacts[HierarchyFacts["IterationStatementBlock"] = 512] = "IterationStatementBlock"; + HierarchyFacts[HierarchyFacts["ForStatement"] = 1024] = "ForStatement"; + HierarchyFacts[HierarchyFacts["ForInOrForOfStatement"] = 2048] = "ForInOrForOfStatement"; + HierarchyFacts[HierarchyFacts["ConstructorWithCapturedSuper"] = 4096] = "ConstructorWithCapturedSuper"; + HierarchyFacts[HierarchyFacts["ComputedPropertyName"] = 8192] = "ComputedPropertyName"; + // NOTE: do not add more ancestor flags without also updating AncestorFactsMask below. + // + // Ancestor masks + // + HierarchyFacts[HierarchyFacts["AncestorFactsMask"] = 16383] = "AncestorFactsMask"; + // We are always in *some* kind of block scope, but only specific block-scope containers are + // top-level or Blocks. + HierarchyFacts[HierarchyFacts["BlockScopeIncludes"] = 0] = "BlockScopeIncludes"; + HierarchyFacts[HierarchyFacts["BlockScopeExcludes"] = 4032] = "BlockScopeExcludes"; + // A source file is a top-level block scope. + HierarchyFacts[HierarchyFacts["SourceFileIncludes"] = 64] = "SourceFileIncludes"; + HierarchyFacts[HierarchyFacts["SourceFileExcludes"] = 3968] = "SourceFileExcludes"; + // Functions, methods, and accessors are both new lexical scopes and new block scopes. + HierarchyFacts[HierarchyFacts["FunctionIncludes"] = 65] = "FunctionIncludes"; + HierarchyFacts[HierarchyFacts["FunctionExcludes"] = 16286] = "FunctionExcludes"; + HierarchyFacts[HierarchyFacts["AsyncFunctionBodyIncludes"] = 69] = "AsyncFunctionBodyIncludes"; + HierarchyFacts[HierarchyFacts["AsyncFunctionBodyExcludes"] = 16278] = "AsyncFunctionBodyExcludes"; + // Arrow functions are lexically scoped to their container, but are new block scopes. + HierarchyFacts[HierarchyFacts["ArrowFunctionIncludes"] = 66] = "ArrowFunctionIncludes"; + HierarchyFacts[HierarchyFacts["ArrowFunctionExcludes"] = 16256] = "ArrowFunctionExcludes"; + // Constructors are both new lexical scopes and new block scopes. Constructors are also + // always considered non-static members of a class. + HierarchyFacts[HierarchyFacts["ConstructorIncludes"] = 73] = "ConstructorIncludes"; + HierarchyFacts[HierarchyFacts["ConstructorExcludes"] = 16278] = "ConstructorExcludes"; + // 'do' and 'while' statements are not block scopes. We track that the subtree is contained + // within an IterationStatement to indicate whether the embedded statement is an + // IterationStatementBlock. + HierarchyFacts[HierarchyFacts["DoOrWhileStatementIncludes"] = 256] = "DoOrWhileStatementIncludes"; + HierarchyFacts[HierarchyFacts["DoOrWhileStatementExcludes"] = 0] = "DoOrWhileStatementExcludes"; + // 'for' statements are new block scopes and have special handling for 'let' declarations. + HierarchyFacts[HierarchyFacts["ForStatementIncludes"] = 1280] = "ForStatementIncludes"; + HierarchyFacts[HierarchyFacts["ForStatementExcludes"] = 3008] = "ForStatementExcludes"; + // 'for-in' and 'for-of' statements are new block scopes and have special handling for + // 'let' declarations. + HierarchyFacts[HierarchyFacts["ForInOrForOfStatementIncludes"] = 2304] = "ForInOrForOfStatementIncludes"; + HierarchyFacts[HierarchyFacts["ForInOrForOfStatementExcludes"] = 1984] = "ForInOrForOfStatementExcludes"; + // Blocks (other than function bodies) are new block scopes. + HierarchyFacts[HierarchyFacts["BlockIncludes"] = 128] = "BlockIncludes"; + HierarchyFacts[HierarchyFacts["BlockExcludes"] = 3904] = "BlockExcludes"; + HierarchyFacts[HierarchyFacts["IterationStatementBlockIncludes"] = 512] = "IterationStatementBlockIncludes"; + HierarchyFacts[HierarchyFacts["IterationStatementBlockExcludes"] = 4032] = "IterationStatementBlockExcludes"; + // Computed property names track subtree flags differently than their containing members. + HierarchyFacts[HierarchyFacts["ComputedPropertyNameIncludes"] = 8192] = "ComputedPropertyNameIncludes"; + HierarchyFacts[HierarchyFacts["ComputedPropertyNameExcludes"] = 0] = "ComputedPropertyNameExcludes"; + // + // Subtree facts + // + HierarchyFacts[HierarchyFacts["NewTarget"] = 16384] = "NewTarget"; + HierarchyFacts[HierarchyFacts["NewTargetInComputedPropertyName"] = 32768] = "NewTargetInComputedPropertyName"; + // + // Subtree masks + // + HierarchyFacts[HierarchyFacts["SubtreeFactsMask"] = -16384] = "SubtreeFactsMask"; + HierarchyFacts[HierarchyFacts["PropagateNewTargetMask"] = 49152] = "PropagateNewTargetMask"; + })(HierarchyFacts || (HierarchyFacts = {})); + function transformES2015(context) { + var startLexicalEnvironment = context.startLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; + var compilerOptions = context.getCompilerOptions(); + var resolver = context.getEmitResolver(); + var previousOnSubstituteNode = context.onSubstituteNode; + var previousOnEmitNode = context.onEmitNode; + context.onEmitNode = onEmitNode; + context.onSubstituteNode = onSubstituteNode; + var currentSourceFile; + var currentText; + var hierarchyFacts; + var taggedTemplateStringDeclarations; + function recordTaggedTemplateString(temp) { + taggedTemplateStringDeclarations = ts.append(taggedTemplateStringDeclarations, ts.createVariableDeclaration(temp)); + } + /** + * Used to track if we are emitting body of the converted loop + */ + var convertedLoopState; + /** + * Keeps track of whether substitutions have been enabled for specific cases. + * They are persisted between each SourceFile transformation and should not + * be reset. + */ + var enabledSubstitutions; + return ts.chainBundle(transformSourceFile); + function transformSourceFile(node) { + if (node.isDeclarationFile) { + return node; + } + currentSourceFile = node; + currentText = node.text; + var visited = visitSourceFile(node); + ts.addEmitHelpers(visited, context.readEmitHelpers()); + currentSourceFile = undefined; + currentText = undefined; + taggedTemplateStringDeclarations = undefined; + hierarchyFacts = 0 /* None */; + return visited; + } + /** + * Sets the `HierarchyFacts` for this node prior to visiting this node's subtree, returning the facts set prior to modification. + * @param excludeFacts The existing `HierarchyFacts` to reset before visiting the subtree. + * @param includeFacts The new `HierarchyFacts` to set before visiting the subtree. + */ + function enterSubtree(excludeFacts, includeFacts) { + var ancestorFacts = hierarchyFacts; + hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & 16383 /* AncestorFactsMask */; + return ancestorFacts; + } + /** + * Restores the `HierarchyFacts` for this node's ancestor after visiting this node's + * subtree, propagating specific facts from the subtree. + * @param ancestorFacts The `HierarchyFacts` of the ancestor to restore after visiting the subtree. + * @param excludeFacts The existing `HierarchyFacts` of the subtree that should not be propagated. + * @param includeFacts The new `HierarchyFacts` of the subtree that should be propagated. + */ + function exitSubtree(ancestorFacts, excludeFacts, includeFacts) { + hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & -16384 /* SubtreeFactsMask */ | ancestorFacts; + } + function isReturnVoidStatementInConstructorWithCapturedSuper(node) { + return (hierarchyFacts & 4096 /* ConstructorWithCapturedSuper */) !== 0 + && node.kind === 230 /* ReturnStatement */ + && !node.expression; + } + function shouldVisitNode(node) { + return (node.transformFlags & 128 /* ContainsES2015 */) !== 0 + || convertedLoopState !== undefined + || (hierarchyFacts & 4096 /* ConstructorWithCapturedSuper */ && (ts.isStatement(node) || (node.kind === 218 /* Block */))) + || (ts.isIterationStatement(node, /*lookInLabeledStatements*/ false) && shouldConvertIterationStatement(node)) + || (ts.getEmitFlags(node) & 33554432 /* TypeScriptClassWrapper */) !== 0; + } + function visitor(node) { + if (shouldVisitNode(node)) { + return visitJavaScript(node); + } + else { + return node; + } + } + function functionBodyVisitor(node) { + if (shouldVisitNode(node)) { + return visitBlock(node, /*isFunctionBody*/ true); + } + return node; + } + function callExpressionVisitor(node) { + if (node.kind === 98 /* SuperKeyword */) { + return visitSuperKeyword(/*isExpressionOfCall*/ true); + } + return visitor(node); + } + function visitJavaScript(node) { + switch (node.kind) { + case 116 /* StaticKeyword */: + return undefined; // elide static keyword + case 240 /* ClassDeclaration */: + return visitClassDeclaration(node); + case 209 /* ClassExpression */: + return visitClassExpression(node); + case 151 /* Parameter */: + return visitParameter(node); + case 239 /* FunctionDeclaration */: + return visitFunctionDeclaration(node); + case 197 /* ArrowFunction */: + return visitArrowFunction(node); + case 196 /* FunctionExpression */: + return visitFunctionExpression(node); + case 237 /* VariableDeclaration */: + return visitVariableDeclaration(node); + case 72 /* Identifier */: + return visitIdentifier(node); + case 238 /* VariableDeclarationList */: + return visitVariableDeclarationList(node); + case 232 /* SwitchStatement */: + return visitSwitchStatement(node); + case 246 /* CaseBlock */: + return visitCaseBlock(node); + case 218 /* Block */: + return visitBlock(node, /*isFunctionBody*/ false); + case 229 /* BreakStatement */: + case 228 /* ContinueStatement */: + return visitBreakOrContinueStatement(node); + case 233 /* LabeledStatement */: + return visitLabeledStatement(node); + case 223 /* DoStatement */: + case 224 /* WhileStatement */: + return visitDoOrWhileStatement(node, /*outermostLabeledStatement*/ undefined); + case 225 /* ForStatement */: + return visitForStatement(node, /*outermostLabeledStatement*/ undefined); + case 226 /* ForInStatement */: + return visitForInStatement(node, /*outermostLabeledStatement*/ undefined); + case 227 /* ForOfStatement */: + return visitForOfStatement(node, /*outermostLabeledStatement*/ undefined); + case 221 /* ExpressionStatement */: + return visitExpressionStatement(node); + case 188 /* ObjectLiteralExpression */: + return visitObjectLiteralExpression(node); + case 274 /* CatchClause */: + return visitCatchClause(node); + case 276 /* ShorthandPropertyAssignment */: + return visitShorthandPropertyAssignment(node); + case 149 /* ComputedPropertyName */: + return visitComputedPropertyName(node); + case 187 /* ArrayLiteralExpression */: + return visitArrayLiteralExpression(node); + case 191 /* CallExpression */: + return visitCallExpression(node); + case 192 /* NewExpression */: + return visitNewExpression(node); + case 195 /* ParenthesizedExpression */: + return visitParenthesizedExpression(node, /*needsDestructuringValue*/ true); + case 204 /* BinaryExpression */: + return visitBinaryExpression(node, /*needsDestructuringValue*/ true); + case 14 /* NoSubstitutionTemplateLiteral */: + case 15 /* TemplateHead */: + case 16 /* TemplateMiddle */: + case 17 /* TemplateTail */: + return visitTemplateLiteral(node); + case 10 /* StringLiteral */: + return visitStringLiteral(node); + case 8 /* NumericLiteral */: + return visitNumericLiteral(node); + case 193 /* TaggedTemplateExpression */: + return visitTaggedTemplateExpression(node); + case 206 /* TemplateExpression */: + return visitTemplateExpression(node); + case 207 /* YieldExpression */: + return visitYieldExpression(node); + case 208 /* SpreadElement */: + return visitSpreadElement(node); + case 98 /* SuperKeyword */: + return visitSuperKeyword(/*isExpressionOfCall*/ false); + case 100 /* ThisKeyword */: + return visitThisKeyword(node); + case 214 /* MetaProperty */: + return visitMetaProperty(node); + case 156 /* MethodDeclaration */: + return visitMethodDeclaration(node); + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + return visitAccessorDeclaration(node); + case 219 /* VariableStatement */: + return visitVariableStatement(node); + case 230 /* ReturnStatement */: + return visitReturnStatement(node); + default: + return ts.visitEachChild(node, visitor, context); + } + } + function visitSourceFile(node) { + var ancestorFacts = enterSubtree(3968 /* SourceFileExcludes */, 64 /* SourceFileIncludes */); + var statements = []; + startLexicalEnvironment(); + var statementOffset = ts.addStandardPrologue(statements, node.statements, /*ensureUseStrict*/ false); + addCaptureThisForNodeIfNeeded(statements, node); + statementOffset = ts.addCustomPrologue(statements, node.statements, statementOffset, visitor); + ts.addRange(statements, ts.visitNodes(node.statements, visitor, ts.isStatement, statementOffset)); + if (taggedTemplateStringDeclarations) { + statements.push(ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList(taggedTemplateStringDeclarations))); + } + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */); + return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements)); + } + function visitSwitchStatement(node) { + if (convertedLoopState !== undefined) { + var savedAllowedNonLabeledJumps = convertedLoopState.allowedNonLabeledJumps; + // for switch statement allow only non-labeled break + convertedLoopState.allowedNonLabeledJumps |= 2 /* Break */; + var result = ts.visitEachChild(node, visitor, context); + convertedLoopState.allowedNonLabeledJumps = savedAllowedNonLabeledJumps; + return result; + } + return ts.visitEachChild(node, visitor, context); + } + function visitCaseBlock(node) { + var ancestorFacts = enterSubtree(4032 /* BlockScopeExcludes */, 0 /* BlockScopeIncludes */); + var updated = ts.visitEachChild(node, visitor, context); + exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */); + return updated; + } + function returnCapturedThis(node) { + return ts.setOriginalNode(ts.createReturn(ts.createFileLevelUniqueName("_this")), node); + } + function visitReturnStatement(node) { + if (convertedLoopState) { + convertedLoopState.nonLocalJumps |= 8 /* Return */; + if (isReturnVoidStatementInConstructorWithCapturedSuper(node)) { + node = returnCapturedThis(node); + } + return ts.createReturn(ts.createObjectLiteral([ + ts.createPropertyAssignment(ts.createIdentifier("value"), node.expression + ? ts.visitNode(node.expression, visitor, ts.isExpression) + : ts.createVoidZero()) + ])); + } + else if (isReturnVoidStatementInConstructorWithCapturedSuper(node)) { + return returnCapturedThis(node); + } + return ts.visitEachChild(node, visitor, context); + } + function visitThisKeyword(node) { + if (convertedLoopState) { + if (hierarchyFacts & 2 /* ArrowFunction */) { + // if the enclosing function is an ArrowFunction then we use the captured 'this' keyword. + convertedLoopState.containsLexicalThis = true; + return node; + } + return convertedLoopState.thisName || (convertedLoopState.thisName = ts.createUniqueName("this")); + } + return node; + } + function visitIdentifier(node) { + if (!convertedLoopState) { + return node; + } + if (ts.isGeneratedIdentifier(node)) { + return node; + } + if (node.escapedText !== "arguments" || !resolver.isArgumentsLocalBinding(node)) { + return node; + } + return convertedLoopState.argumentsName || (convertedLoopState.argumentsName = ts.createUniqueName("arguments")); + } + function visitBreakOrContinueStatement(node) { + if (convertedLoopState) { + // check if we can emit break/continue as is + // it is possible if either + // - break/continue is labeled and label is located inside the converted loop + // - break/continue is non-labeled and located in non-converted loop/switch statement + var jump = node.kind === 229 /* BreakStatement */ ? 2 /* Break */ : 4 /* Continue */; + var canUseBreakOrContinue = (node.label && convertedLoopState.labels && convertedLoopState.labels.get(ts.idText(node.label))) || + (!node.label && (convertedLoopState.allowedNonLabeledJumps & jump)); + if (!canUseBreakOrContinue) { + var labelMarker = void 0; + var label = node.label; + if (!label) { + if (node.kind === 229 /* BreakStatement */) { + convertedLoopState.nonLocalJumps |= 2 /* Break */; + labelMarker = "break"; + } + else { + convertedLoopState.nonLocalJumps |= 4 /* Continue */; + // note: return value is emitted only to simplify debugging, call to converted loop body does not do any dispatching on it. + labelMarker = "continue"; + } + } + else { + if (node.kind === 229 /* BreakStatement */) { + labelMarker = "break-" + label.escapedText; + setLabeledJump(convertedLoopState, /*isBreak*/ true, ts.idText(label), labelMarker); + } + else { + labelMarker = "continue-" + label.escapedText; + setLabeledJump(convertedLoopState, /*isBreak*/ false, ts.idText(label), labelMarker); + } + } + var returnExpression = ts.createLiteral(labelMarker); + if (convertedLoopState.loopOutParameters.length) { + var outParams = convertedLoopState.loopOutParameters; + var expr = void 0; + for (var i = 0; i < outParams.length; i++) { + var copyExpr = copyOutParameter(outParams[i], 1 /* ToOutParameter */); + if (i === 0) { + expr = copyExpr; + } + else { + expr = ts.createBinary(expr, 27 /* CommaToken */, copyExpr); + } + } + returnExpression = ts.createBinary(expr, 27 /* CommaToken */, returnExpression); + } + return ts.createReturn(returnExpression); + } + } + return ts.visitEachChild(node, visitor, context); + } + /** + * Visits a ClassDeclaration and transforms it into a variable statement. + * + * @param node A ClassDeclaration node. + */ + function visitClassDeclaration(node) { + // [source] + // class C { } + // + // [output] + // var C = (function () { + // function C() { + // } + // return C; + // }()); + var variable = ts.createVariableDeclaration(ts.getLocalName(node, /*allowComments*/ true), + /*type*/ undefined, transformClassLikeDeclarationToExpression(node)); + ts.setOriginalNode(variable, node); + var statements = []; + var statement = ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([variable])); + ts.setOriginalNode(statement, node); + ts.setTextRange(statement, node); + ts.startOnNewLine(statement); + statements.push(statement); + // Add an `export default` statement for default exports (for `--target es5 --module es6`) + if (ts.hasModifier(node, 1 /* Export */)) { + var exportStatement = ts.hasModifier(node, 512 /* Default */) + ? ts.createExportDefault(ts.getLocalName(node)) + : ts.createExternalModuleExport(ts.getLocalName(node)); + ts.setOriginalNode(exportStatement, statement); + statements.push(exportStatement); + } + var emitFlags = ts.getEmitFlags(node); + if ((emitFlags & 4194304 /* HasEndOfDeclarationMarker */) === 0) { + // Add a DeclarationMarker as a marker for the end of the declaration + statements.push(ts.createEndOfDeclarationMarker(node)); + ts.setEmitFlags(statement, emitFlags | 4194304 /* HasEndOfDeclarationMarker */); + } + return ts.singleOrMany(statements); + } + /** + * Visits a ClassExpression and transforms it into an expression. + * + * @param node A ClassExpression node. + */ + function visitClassExpression(node) { + // [source] + // C = class { } + // + // [output] + // C = (function () { + // function class_1() { + // } + // return class_1; + // }()) + return transformClassLikeDeclarationToExpression(node); + } + /** + * Transforms a ClassExpression or ClassDeclaration into an expression. + * + * @param node A ClassExpression or ClassDeclaration node. + */ + function transformClassLikeDeclarationToExpression(node) { + // [source] + // class C extends D { + // constructor() {} + // method() {} + // get prop() {} + // set prop(v) {} + // } + // + // [output] + // (function (_super) { + // __extends(C, _super); + // function C() { + // } + // C.prototype.method = function () {} + // Object.defineProperty(C.prototype, "prop", { + // get: function() {}, + // set: function() {}, + // enumerable: true, + // configurable: true + // }); + // return C; + // }(D)) + if (node.name) { + enableSubstitutionsForBlockScopedBindings(); + } + var extendsClauseElement = ts.getEffectiveBaseTypeNode(node); + var classFunction = ts.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, extendsClauseElement ? [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, ts.createFileLevelUniqueName("_super"))] : [], + /*type*/ undefined, transformClassBody(node, extendsClauseElement)); + // To preserve the behavior of the old emitter, we explicitly indent + // the body of the function here if it was requested in an earlier + // transformation. + ts.setEmitFlags(classFunction, (ts.getEmitFlags(node) & 65536 /* Indented */) | 524288 /* ReuseTempVariableScope */); + // "inner" and "outer" below are added purely to preserve source map locations from + // the old emitter + var inner = ts.createPartiallyEmittedExpression(classFunction); + inner.end = node.end; + ts.setEmitFlags(inner, 1536 /* NoComments */); + var outer = ts.createPartiallyEmittedExpression(inner); + outer.end = ts.skipTrivia(currentText, node.pos); + ts.setEmitFlags(outer, 1536 /* NoComments */); + var result = ts.createParen(ts.createCall(outer, + /*typeArguments*/ undefined, extendsClauseElement + ? [ts.visitNode(extendsClauseElement.expression, visitor, ts.isExpression)] + : [])); + ts.addSyntheticLeadingComment(result, 3 /* MultiLineCommentTrivia */, "* @class "); + return result; + } + /** + * Transforms a ClassExpression or ClassDeclaration into a function body. + * + * @param node A ClassExpression or ClassDeclaration node. + * @param extendsClauseElement The expression for the class `extends` clause. + */ + function transformClassBody(node, extendsClauseElement) { + var statements = []; + startLexicalEnvironment(); + addExtendsHelperIfNeeded(statements, node, extendsClauseElement); + addConstructor(statements, node, extendsClauseElement); + addClassMembers(statements, node); + // Create a synthetic text range for the return statement. + var closingBraceLocation = ts.createTokenRange(ts.skipTrivia(currentText, node.members.end), 19 /* CloseBraceToken */); + var localName = ts.getInternalName(node); + // The following partially-emitted expression exists purely to align our sourcemap + // emit with the original emitter. + var outer = ts.createPartiallyEmittedExpression(localName); + outer.end = closingBraceLocation.end; + ts.setEmitFlags(outer, 1536 /* NoComments */); + var statement = ts.createReturn(outer); + statement.pos = closingBraceLocation.pos; + ts.setEmitFlags(statement, 1536 /* NoComments */ | 384 /* NoTokenSourceMaps */); + statements.push(statement); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), /*location*/ node.members), /*multiLine*/ true); + ts.setEmitFlags(block, 1536 /* NoComments */); + return block; + } + /** + * Adds a call to the `__extends` helper if needed for a class. + * + * @param statements The statements of the class body function. + * @param node The ClassExpression or ClassDeclaration node. + * @param extendsClauseElement The expression for the class `extends` clause. + */ + function addExtendsHelperIfNeeded(statements, node, extendsClauseElement) { + if (extendsClauseElement) { + statements.push(ts.setTextRange(ts.createExpressionStatement(createExtendsHelper(context, ts.getInternalName(node))), + /*location*/ extendsClauseElement)); + } + } + /** + * Adds the constructor of the class to a class body function. + * + * @param statements The statements of the class body function. + * @param node The ClassExpression or ClassDeclaration node. + * @param extendsClauseElement The expression for the class `extends` clause. + */ + function addConstructor(statements, node, extendsClauseElement) { + var savedConvertedLoopState = convertedLoopState; + convertedLoopState = undefined; + var ancestorFacts = enterSubtree(16278 /* ConstructorExcludes */, 73 /* ConstructorIncludes */); + var constructor = ts.getFirstConstructorWithBody(node); + var hasSynthesizedSuper = hasSynthesizedDefaultSuperCall(constructor, extendsClauseElement !== undefined); + var constructorFunction = ts.createFunctionDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, ts.getInternalName(node), + /*typeParameters*/ undefined, transformConstructorParameters(constructor, hasSynthesizedSuper), + /*type*/ undefined, transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper)); + ts.setTextRange(constructorFunction, constructor || node); + if (extendsClauseElement) { + ts.setEmitFlags(constructorFunction, 8 /* CapturesThis */); + } + statements.push(constructorFunction); + exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, 0 /* None */); + convertedLoopState = savedConvertedLoopState; + } + /** + * Transforms the parameters of the constructor declaration of a class. + * + * @param constructor The constructor for the class. + * @param hasSynthesizedSuper A value indicating whether the constructor starts with a + * synthesized `super` call. + */ + function transformConstructorParameters(constructor, hasSynthesizedSuper) { + // If the TypeScript transformer needed to synthesize a constructor for property + // initializers, it would have also added a synthetic `...args` parameter and + // `super` call. + // If this is the case, we do not include the synthetic `...args` parameter and + // will instead use the `arguments` object in ES5/3. + return ts.visitParameterList(constructor && !hasSynthesizedSuper ? constructor.parameters : undefined, visitor, context) + || []; + } + /** + * Transforms the body of a constructor declaration of a class. + * + * @param constructor The constructor for the class. + * @param node The node which contains the constructor. + * @param extendsClauseElement The expression for the class `extends` clause. + * @param hasSynthesizedSuper A value indicating whether the constructor starts with a + * synthesized `super` call. + */ + function transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper) { + var statements = []; + resumeLexicalEnvironment(); + var statementOffset = -1; + if (hasSynthesizedSuper) { + // If a super call has already been synthesized, + // we're going to assume that we should just transform everything after that. + // The assumption is that no prior step in the pipeline has added any prologue directives. + statementOffset = 0; + } + else if (constructor) { + statementOffset = ts.addStandardPrologue(statements, constructor.body.statements, /*ensureUseStrict*/ false); + } + if (constructor) { + addDefaultValueAssignmentsIfNeeded(statements, constructor); + addRestParameterIfNeeded(statements, constructor, hasSynthesizedSuper); + if (!hasSynthesizedSuper) { + // If no super call has been synthesized, emit custom prologue directives. + statementOffset = ts.addCustomPrologue(statements, constructor.body.statements, statementOffset, visitor); + } + ts.Debug.assert(statementOffset >= 0, "statementOffset not initialized correctly!"); + } + // determine whether the class is known syntactically to be a derived class (e.g. a + // class that extends a value that is not syntactically known to be `null`). + var isDerivedClass = !!extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 96 /* NullKeyword */; + var superCaptureStatus = declareOrCaptureOrReturnThisForConstructorIfNeeded(statements, constructor, isDerivedClass, hasSynthesizedSuper, statementOffset); + // The last statement expression was replaced. Skip it. + if (superCaptureStatus === 1 /* ReplaceSuperCapture */ || superCaptureStatus === 2 /* ReplaceWithReturn */) { + statementOffset++; + } + if (constructor) { + if (superCaptureStatus === 1 /* ReplaceSuperCapture */) { + hierarchyFacts |= 4096 /* ConstructorWithCapturedSuper */; + } + ts.addRange(statements, ts.visitNodes(constructor.body.statements, visitor, ts.isStatement, /*start*/ statementOffset)); + } + // Return `_this` unless we're sure enough that it would be pointless to add a return statement. + // If there's a constructor that we can tell returns in enough places, then we *do not* want to add a return. + if (isDerivedClass + && superCaptureStatus !== 2 /* ReplaceWithReturn */ + && !(constructor && isSufficientlyCoveredByReturnStatements(constructor.body))) { + statements.push(ts.createReturn(ts.createFileLevelUniqueName("_this"))); + } + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + if (constructor) { + prependCaptureNewTargetIfNeeded(statements, constructor, /*copyOnWrite*/ false); + } + var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), + /*location*/ constructor ? constructor.body.statements : node.members), + /*multiLine*/ true); + ts.setTextRange(block, constructor ? constructor.body : node); + if (!constructor) { + ts.setEmitFlags(block, 1536 /* NoComments */); + } + return block; + } + /** + * We want to try to avoid emitting a return statement in certain cases if a user already returned something. + * It would generate obviously dead code, so we'll try to make things a little bit prettier + * by doing a minimal check on whether some common patterns always explicitly return. + */ + function isSufficientlyCoveredByReturnStatements(statement) { + // A return statement is considered covered. + if (statement.kind === 230 /* ReturnStatement */) { + return true; + } + // An if-statement with two covered branches is covered. + else if (statement.kind === 222 /* IfStatement */) { + var ifStatement = statement; + if (ifStatement.elseStatement) { + return isSufficientlyCoveredByReturnStatements(ifStatement.thenStatement) && + isSufficientlyCoveredByReturnStatements(ifStatement.elseStatement); + } + } + // A block is covered if it has a last statement which is covered. + else if (statement.kind === 218 /* Block */) { + var lastStatement = ts.lastOrUndefined(statement.statements); + if (lastStatement && isSufficientlyCoveredByReturnStatements(lastStatement)) { + return true; + } + } + return false; + } + /** + * Declares a `_this` variable for derived classes and for when arrow functions capture `this`. + * + * @returns The new statement offset into the `statements` array. + */ + function declareOrCaptureOrReturnThisForConstructorIfNeeded(statements, ctor, isDerivedClass, hasSynthesizedSuper, statementOffset) { + // If this isn't a derived class, just capture 'this' for arrow functions if necessary. + if (!isDerivedClass) { + if (ctor) { + addCaptureThisForNodeIfNeeded(statements, ctor); + } + return 0 /* NoReplacement */; + } + // We must be here because the user didn't write a constructor + // but we needed to call 'super(...args)' anyway as per 14.5.14 of the ES2016 spec. + // If that's the case we can just immediately return the result of a 'super()' call. + if (!ctor) { + statements.push(ts.createReturn(createDefaultSuperCallOrThis())); + return 2 /* ReplaceWithReturn */; + } + // The constructor exists, but it and the 'super()' call it contains were generated + // for something like property initializers. + // Create a captured '_this' variable and assume it will subsequently be used. + if (hasSynthesizedSuper) { + captureThisForNode(statements, ctor, createDefaultSuperCallOrThis()); + enableSubstitutionsForCapturedThis(); + return 1 /* ReplaceSuperCapture */; + } + // Most of the time, a 'super' call will be the first real statement in a constructor body. + // In these cases, we'd like to transform these into a *single* statement instead of a declaration + // followed by an assignment statement for '_this'. For instance, if we emitted without an initializer, + // we'd get: + // + // var _this; + // _this = _super.call(...) || this; + // + // instead of + // + // var _this = _super.call(...) || this; + // + // Additionally, if the 'super()' call is the last statement, we should just avoid capturing + // entirely and immediately return the result like so: + // + // return _super.call(...) || this; + // + var firstStatement; + var superCallExpression; + var ctorStatements = ctor.body.statements; + if (statementOffset < ctorStatements.length) { + firstStatement = ctorStatements[statementOffset]; + if (firstStatement.kind === 221 /* ExpressionStatement */ && ts.isSuperCall(firstStatement.expression)) { + superCallExpression = visitImmediateSuperCallInBody(firstStatement.expression); + } + } + // Return the result if we have an immediate super() call on the last statement, + // but only if the constructor itself doesn't use 'this' elsewhere. + if (superCallExpression + && statementOffset === ctorStatements.length - 1 + && !(ctor.transformFlags & (8192 /* ContainsLexicalThis */ | 16384 /* ContainsCapturedLexicalThis */))) { + var returnStatement = ts.createReturn(superCallExpression); + if (superCallExpression.kind !== 204 /* BinaryExpression */ + || superCallExpression.left.kind !== 191 /* CallExpression */) { + ts.Debug.fail("Assumed generated super call would have form 'super.call(...) || this'."); + } + // Shift comments from the original super call to the return statement. + ts.setCommentRange(returnStatement, ts.getCommentRange(ts.setEmitFlags(superCallExpression.left, 1536 /* NoComments */))); + statements.push(returnStatement); + return 2 /* ReplaceWithReturn */; + } + // Perform the capture. + captureThisForNode(statements, ctor, superCallExpression || createActualThis()); + // If we're actually replacing the original statement, we need to signal this to the caller. + if (superCallExpression) { + return 1 /* ReplaceSuperCapture */; + } + return 0 /* NoReplacement */; + } + function createActualThis() { + return ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */); + } + function createDefaultSuperCallOrThis() { + return ts.createLogicalOr(ts.createLogicalAnd(ts.createStrictInequality(ts.createFileLevelUniqueName("_super"), ts.createNull()), ts.createFunctionApply(ts.createFileLevelUniqueName("_super"), createActualThis(), ts.createIdentifier("arguments"))), createActualThis()); + } + /** + * Visits a parameter declaration. + * + * @param node A ParameterDeclaration node. + */ + function visitParameter(node) { + if (node.dotDotDotToken) { + // rest parameters are elided + return undefined; + } + else if (ts.isBindingPattern(node.name)) { + // Binding patterns are converted into a generated name and are + // evaluated inside the function body. + return ts.setOriginalNode(ts.setTextRange(ts.createParameter( + /*decorators*/ undefined, + /*modifiers*/ undefined, + /*dotDotDotToken*/ undefined, ts.getGeneratedNameForNode(node), + /*questionToken*/ undefined, + /*type*/ undefined, + /*initializer*/ undefined), + /*location*/ node), + /*original*/ node); + } + else if (node.initializer) { + // Initializers are elided + return ts.setOriginalNode(ts.setTextRange(ts.createParameter( + /*decorators*/ undefined, + /*modifiers*/ undefined, + /*dotDotDotToken*/ undefined, node.name, + /*questionToken*/ undefined, + /*type*/ undefined, + /*initializer*/ undefined), + /*location*/ node), + /*original*/ node); + } + else { + return node; + } + } + /** + * Gets a value indicating whether we need to add default value assignments for a + * function-like node. + * + * @param node A function-like node. + */ + function shouldAddDefaultValueAssignments(node) { + return (node.transformFlags & 65536 /* ContainsDefaultValueAssignments */) !== 0; + } + /** + * Adds statements to the body of a function-like node if it contains parameters with + * binding patterns or initializers. + * + * @param statements The statements for the new function body. + * @param node A function-like node. + */ + function addDefaultValueAssignmentsIfNeeded(statements, node) { + if (!shouldAddDefaultValueAssignments(node)) { + return; + } + for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { + var parameter = _a[_i]; + var name = parameter.name, initializer = parameter.initializer, dotDotDotToken = parameter.dotDotDotToken; + // A rest parameter cannot have a binding pattern or an initializer, + // so let's just ignore it. + if (dotDotDotToken) { + continue; + } + if (ts.isBindingPattern(name)) { + addDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer); + } + else if (initializer) { + addDefaultValueAssignmentForInitializer(statements, parameter, name, initializer); + } + } + } + /** + * Adds statements to the body of a function-like node for parameters with binding patterns + * + * @param statements The statements for the new function body. + * @param parameter The parameter for the function. + * @param name The name of the parameter. + * @param initializer The initializer for the parameter. + */ + function addDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer) { + var temp = ts.getGeneratedNameForNode(parameter); + // In cases where a binding pattern is simply '[]' or '{}', + // we usually don't want to emit a var declaration; however, in the presence + // of an initializer, we must emit that expression to preserve side effects. + if (name.elements.length > 0) { + statements.push(ts.setEmitFlags(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList(ts.flattenDestructuringBinding(parameter, visitor, context, 0 /* All */, temp))), 1048576 /* CustomPrologue */)); + } + else if (initializer) { + statements.push(ts.setEmitFlags(ts.createExpressionStatement(ts.createAssignment(temp, ts.visitNode(initializer, visitor, ts.isExpression))), 1048576 /* CustomPrologue */)); + } + } + /** + * Adds statements to the body of a function-like node for parameters with initializers. + * + * @param statements The statements for the new function body. + * @param parameter The parameter for the function. + * @param name The name of the parameter. + * @param initializer The initializer for the parameter. + */ + function addDefaultValueAssignmentForInitializer(statements, parameter, name, initializer) { + initializer = ts.visitNode(initializer, visitor, ts.isExpression); + var statement = ts.createIf(ts.createTypeCheck(ts.getSynthesizedClone(name), "undefined"), ts.setEmitFlags(ts.setTextRange(ts.createBlock([ + ts.createExpressionStatement(ts.setEmitFlags(ts.setTextRange(ts.createAssignment(ts.setEmitFlags(ts.getMutableClone(name), 48 /* NoSourceMap */), ts.setEmitFlags(initializer, 48 /* NoSourceMap */ | ts.getEmitFlags(initializer) | 1536 /* NoComments */)), parameter), 1536 /* NoComments */)) + ]), parameter), 1 /* SingleLine */ | 32 /* NoTrailingSourceMap */ | 384 /* NoTokenSourceMaps */ | 1536 /* NoComments */)); + ts.startOnNewLine(statement); + ts.setTextRange(statement, parameter); + ts.setEmitFlags(statement, 384 /* NoTokenSourceMaps */ | 32 /* NoTrailingSourceMap */ | 1048576 /* CustomPrologue */ | 1536 /* NoComments */); + statements.push(statement); + } + /** + * Gets a value indicating whether we need to add statements to handle a rest parameter. + * + * @param node A ParameterDeclaration node. + * @param inConstructorWithSynthesizedSuper A value indicating whether the parameter is + * part of a constructor declaration with a + * synthesized call to `super` + */ + function shouldAddRestParameter(node, inConstructorWithSynthesizedSuper) { + return node && node.dotDotDotToken && node.name.kind === 72 /* Identifier */ && !inConstructorWithSynthesizedSuper; + } + /** + * Adds statements to the body of a function-like node if it contains a rest parameter. + * + * @param statements The statements for the new function body. + * @param node A function-like node. + * @param inConstructorWithSynthesizedSuper A value indicating whether the parameter is + * part of a constructor declaration with a + * synthesized call to `super` + */ + function addRestParameterIfNeeded(statements, node, inConstructorWithSynthesizedSuper) { + var parameter = ts.lastOrUndefined(node.parameters); + if (!shouldAddRestParameter(parameter, inConstructorWithSynthesizedSuper)) { + return; + } + // `declarationName` is the name of the local declaration for the parameter. + var declarationName = ts.getMutableClone(parameter.name); + ts.setEmitFlags(declarationName, 48 /* NoSourceMap */); + // `expressionName` is the name of the parameter used in expressions. + var expressionName = ts.getSynthesizedClone(parameter.name); + var restIndex = node.parameters.length - 1; + var temp = ts.createLoopVariable(); + // var param = []; + statements.push(ts.setEmitFlags(ts.setTextRange(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(declarationName, + /*type*/ undefined, ts.createArrayLiteral([])) + ])), + /*location*/ parameter), 1048576 /* CustomPrologue */)); + // for (var _i = restIndex; _i < arguments.length; _i++) { + // param[_i - restIndex] = arguments[_i]; + // } + var forStatement = ts.createFor(ts.setTextRange(ts.createVariableDeclarationList([ + ts.createVariableDeclaration(temp, /*type*/ undefined, ts.createLiteral(restIndex)) + ]), parameter), ts.setTextRange(ts.createLessThan(temp, ts.createPropertyAccess(ts.createIdentifier("arguments"), "length")), parameter), ts.setTextRange(ts.createPostfixIncrement(temp), parameter), ts.createBlock([ + ts.startOnNewLine(ts.setTextRange(ts.createExpressionStatement(ts.createAssignment(ts.createElementAccess(expressionName, restIndex === 0 + ? temp + : ts.createSubtract(temp, ts.createLiteral(restIndex))), ts.createElementAccess(ts.createIdentifier("arguments"), temp))), + /*location*/ parameter)) + ])); + ts.setEmitFlags(forStatement, 1048576 /* CustomPrologue */); + ts.startOnNewLine(forStatement); + statements.push(forStatement); + } + /** + * Adds a statement to capture the `this` of a function declaration if it is needed. + * + * @param statements The statements for the new function body. + * @param node A node. + */ + function addCaptureThisForNodeIfNeeded(statements, node) { + if (node.transformFlags & 16384 /* ContainsCapturedLexicalThis */ && node.kind !== 197 /* ArrowFunction */) { + captureThisForNode(statements, node, ts.createThis()); + } + } + function captureThisForNode(statements, node, initializer) { + enableSubstitutionsForCapturedThis(); + var captureThisStatement = ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(ts.createFileLevelUniqueName("_this"), + /*type*/ undefined, initializer) + ])); + ts.setEmitFlags(captureThisStatement, 1536 /* NoComments */ | 1048576 /* CustomPrologue */); + ts.setSourceMapRange(captureThisStatement, node); + statements.push(captureThisStatement); + } + function prependCaptureNewTargetIfNeeded(statements, node, copyOnWrite) { + if (hierarchyFacts & 16384 /* NewTarget */) { + var newTarget = void 0; + switch (node.kind) { + case 197 /* ArrowFunction */: + return statements; + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + // Methods and accessors cannot be constructors, so 'new.target' will + // always return 'undefined'. + newTarget = ts.createVoidZero(); + break; + case 157 /* Constructor */: + // Class constructors can only be called with `new`, so `this.constructor` + // should be relatively safe to use. + newTarget = ts.createPropertyAccess(ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */), "constructor"); + break; + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + // Functions can be called or constructed, and may have a `this` due to + // being a member or when calling an imported function via `other_1.f()`. + newTarget = ts.createConditional(ts.createLogicalAnd(ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */), ts.createBinary(ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */), 94 /* InstanceOfKeyword */, ts.getLocalName(node))), ts.createPropertyAccess(ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */), "constructor"), ts.createVoidZero()); + break; + default: + return ts.Debug.failBadSyntaxKind(node); + } + var captureNewTargetStatement = ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(ts.createFileLevelUniqueName("_newTarget"), + /*type*/ undefined, newTarget) + ])); + if (copyOnWrite) { + return [captureNewTargetStatement].concat(statements); + } + statements.unshift(captureNewTargetStatement); + } + return statements; + } + /** + * Adds statements to the class body function for a class to define the members of the + * class. + * + * @param statements The statements for the class body function. + * @param node The ClassExpression or ClassDeclaration node. + */ + function addClassMembers(statements, node) { + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + switch (member.kind) { + case 217 /* SemicolonClassElement */: + statements.push(transformSemicolonClassElementToStatement(member)); + break; + case 156 /* MethodDeclaration */: + statements.push(transformClassMethodDeclarationToStatement(getClassMemberPrefix(node, member), member, node)); + break; + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + var accessors = ts.getAllAccessorDeclarations(node.members, member); + if (member === accessors.firstAccessor) { + statements.push(transformAccessorsToStatement(getClassMemberPrefix(node, member), accessors, node)); + } + break; + case 157 /* Constructor */: + // Constructors are handled in visitClassExpression/visitClassDeclaration + break; + default: + ts.Debug.failBadSyntaxKind(node); + break; + } + } + } + /** + * Transforms a SemicolonClassElement into a statement for a class body function. + * + * @param member The SemicolonClassElement node. + */ + function transformSemicolonClassElementToStatement(member) { + return ts.setTextRange(ts.createEmptyStatement(), member); + } + /** + * Transforms a MethodDeclaration into a statement for a class body function. + * + * @param receiver The receiver for the member. + * @param member The MethodDeclaration node. + */ + function transformClassMethodDeclarationToStatement(receiver, member, container) { + var ancestorFacts = enterSubtree(0 /* None */, 0 /* None */); + var commentRange = ts.getCommentRange(member); + var sourceMapRange = ts.getSourceMapRange(member); + var memberName = ts.createMemberAccessForPropertyName(receiver, ts.visitNode(member.name, visitor, ts.isPropertyName), /*location*/ member.name); + var memberFunction = transformFunctionLikeToExpression(member, /*location*/ member, /*name*/ undefined, container); + ts.setEmitFlags(memberFunction, 1536 /* NoComments */); + ts.setSourceMapRange(memberFunction, sourceMapRange); + var statement = ts.setTextRange(ts.createExpressionStatement(ts.createAssignment(memberName, memberFunction)), + /*location*/ member); + ts.setOriginalNode(statement, member); + ts.setCommentRange(statement, commentRange); + // The location for the statement is used to emit comments only. + // No source map should be emitted for this statement to align with the + // old emitter. + ts.setEmitFlags(statement, 48 /* NoSourceMap */); + exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, hierarchyFacts & 49152 /* PropagateNewTargetMask */ ? 16384 /* NewTarget */ : 0 /* None */); + return statement; + } + /** + * Transforms a set of related of get/set accessors into a statement for a class body function. + * + * @param receiver The receiver for the member. + * @param accessors The set of related get/set accessors. + */ + function transformAccessorsToStatement(receiver, accessors, container) { + var statement = ts.createExpressionStatement(transformAccessorsToExpression(receiver, accessors, container, /*startsOnNewLine*/ false)); + // The location for the statement is used to emit source maps only. + // No comments should be emitted for this statement to align with the + // old emitter. + ts.setEmitFlags(statement, 1536 /* NoComments */); + ts.setSourceMapRange(statement, ts.getSourceMapRange(accessors.firstAccessor)); + return statement; + } + /** + * Transforms a set of related get/set accessors into an expression for either a class + * body function or an ObjectLiteralExpression with computed properties. + * + * @param receiver The receiver for the member. + */ + function transformAccessorsToExpression(receiver, _a, container, startsOnNewLine) { + var firstAccessor = _a.firstAccessor, getAccessor = _a.getAccessor, setAccessor = _a.setAccessor; + var ancestorFacts = enterSubtree(0 /* None */, 0 /* None */); + // To align with source maps in the old emitter, the receiver and property name + // arguments are both mapped contiguously to the accessor name. + var target = ts.getMutableClone(receiver); + ts.setEmitFlags(target, 1536 /* NoComments */ | 32 /* NoTrailingSourceMap */); + ts.setSourceMapRange(target, firstAccessor.name); // TODO: GH#18217 + var propertyName = ts.createExpressionForPropertyName(ts.visitNode(firstAccessor.name, visitor, ts.isPropertyName)); + ts.setEmitFlags(propertyName, 1536 /* NoComments */ | 16 /* NoLeadingSourceMap */); + ts.setSourceMapRange(propertyName, firstAccessor.name); + var properties = []; + if (getAccessor) { + var getterFunction = transformFunctionLikeToExpression(getAccessor, /*location*/ undefined, /*name*/ undefined, container); + ts.setSourceMapRange(getterFunction, ts.getSourceMapRange(getAccessor)); + ts.setEmitFlags(getterFunction, 512 /* NoLeadingComments */); + var getter = ts.createPropertyAssignment("get", getterFunction); + ts.setCommentRange(getter, ts.getCommentRange(getAccessor)); + properties.push(getter); + } + if (setAccessor) { + var setterFunction = transformFunctionLikeToExpression(setAccessor, /*location*/ undefined, /*name*/ undefined, container); + ts.setSourceMapRange(setterFunction, ts.getSourceMapRange(setAccessor)); + ts.setEmitFlags(setterFunction, 512 /* NoLeadingComments */); + var setter = ts.createPropertyAssignment("set", setterFunction); + ts.setCommentRange(setter, ts.getCommentRange(setAccessor)); + properties.push(setter); + } + properties.push(ts.createPropertyAssignment("enumerable", ts.createTrue()), ts.createPropertyAssignment("configurable", ts.createTrue())); + var call = ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"), + /*typeArguments*/ undefined, [ + target, + propertyName, + ts.createObjectLiteral(properties, /*multiLine*/ true) + ]); + if (startsOnNewLine) { + ts.startOnNewLine(call); + } + exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, hierarchyFacts & 49152 /* PropagateNewTargetMask */ ? 16384 /* NewTarget */ : 0 /* None */); + return call; + } + /** + * Visits an ArrowFunction and transforms it into a FunctionExpression. + * + * @param node An ArrowFunction node. + */ + function visitArrowFunction(node) { + if (node.transformFlags & 8192 /* ContainsLexicalThis */) { + enableSubstitutionsForCapturedThis(); + } + var savedConvertedLoopState = convertedLoopState; + convertedLoopState = undefined; + var ancestorFacts = enterSubtree(16256 /* ArrowFunctionExcludes */, 66 /* ArrowFunctionIncludes */); + var func = ts.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, transformFunctionBody(node)); + ts.setTextRange(func, node); + ts.setOriginalNode(func, node); + ts.setEmitFlags(func, 8 /* CapturesThis */); + exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */); + convertedLoopState = savedConvertedLoopState; + return func; + } + /** + * Visits a FunctionExpression node. + * + * @param node a FunctionExpression node. + */ + function visitFunctionExpression(node) { + var ancestorFacts = ts.getEmitFlags(node) & 262144 /* AsyncFunctionBody */ + ? enterSubtree(16278 /* AsyncFunctionBodyExcludes */, 69 /* AsyncFunctionBodyIncludes */) + : enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */); + var savedConvertedLoopState = convertedLoopState; + convertedLoopState = undefined; + var parameters = ts.visitParameterList(node.parameters, visitor, context); + var body = node.transformFlags & 64 /* ES2015 */ + ? transformFunctionBody(node) + : visitFunctionBodyDownLevel(node); + var name = hierarchyFacts & 16384 /* NewTarget */ + ? ts.getLocalName(node) + : node.name; + exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, 0 /* None */); + convertedLoopState = savedConvertedLoopState; + return ts.updateFunctionExpression(node, + /*modifiers*/ undefined, node.asteriskToken, name, + /*typeParameters*/ undefined, parameters, + /*type*/ undefined, body); + } + /** + * Visits a FunctionDeclaration node. + * + * @param node a FunctionDeclaration node. + */ + function visitFunctionDeclaration(node) { + var savedConvertedLoopState = convertedLoopState; + convertedLoopState = undefined; + var ancestorFacts = enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */); + var parameters = ts.visitParameterList(node.parameters, visitor, context); + var body = node.transformFlags & 64 /* ES2015 */ + ? transformFunctionBody(node) + : visitFunctionBodyDownLevel(node); + var name = hierarchyFacts & 16384 /* NewTarget */ + ? ts.getLocalName(node) + : node.name; + exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, 0 /* None */); + convertedLoopState = savedConvertedLoopState; + return ts.updateFunctionDeclaration(node, + /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, name, + /*typeParameters*/ undefined, parameters, + /*type*/ undefined, body); + } + /** + * Transforms a function-like node into a FunctionExpression. + * + * @param node The function-like node to transform. + * @param location The source-map location for the new FunctionExpression. + * @param name The name of the new FunctionExpression. + */ + function transformFunctionLikeToExpression(node, location, name, container) { + var savedConvertedLoopState = convertedLoopState; + convertedLoopState = undefined; + var ancestorFacts = container && ts.isClassLike(container) && !ts.hasModifier(node, 32 /* Static */) + ? enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */ | 8 /* NonStaticClassElement */) + : enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */); + var parameters = ts.visitParameterList(node.parameters, visitor, context); + var body = transformFunctionBody(node); + if (hierarchyFacts & 16384 /* NewTarget */ && !name && (node.kind === 239 /* FunctionDeclaration */ || node.kind === 196 /* FunctionExpression */)) { + name = ts.getGeneratedNameForNode(node); + } + exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, 0 /* None */); + convertedLoopState = savedConvertedLoopState; + return ts.setOriginalNode(ts.setTextRange(ts.createFunctionExpression( + /*modifiers*/ undefined, node.asteriskToken, name, + /*typeParameters*/ undefined, parameters, + /*type*/ undefined, body), location), + /*original*/ node); + } + /** + * Transforms the body of a function-like node. + * + * @param node A function-like node. + */ + function transformFunctionBody(node) { + var multiLine = false; // indicates whether the block *must* be emitted as multiple lines + var singleLine = false; // indicates whether the block *may* be emitted as a single line + var statementsLocation; + var closeBraceLocation; + var leadingStatements = []; + var statements = []; + var body = node.body; + var statementOffset; + resumeLexicalEnvironment(); + if (ts.isBlock(body)) { + // ensureUseStrict is false because no new prologue-directive should be added. + // addStandardPrologue will put already-existing directives at the beginning of the target statement-array + statementOffset = ts.addStandardPrologue(leadingStatements, body.statements, /*ensureUseStrict*/ false); + } + addCaptureThisForNodeIfNeeded(leadingStatements, node); + addDefaultValueAssignmentsIfNeeded(leadingStatements, node); + addRestParameterIfNeeded(leadingStatements, node, /*inConstructorWithSynthesizedSuper*/ false); + if (ts.isBlock(body)) { + // addCustomPrologue puts already-existing directives at the beginning of the target statement-array + statementOffset = ts.addCustomPrologue(leadingStatements, body.statements, statementOffset, visitor); + statementsLocation = body.statements; + ts.addRange(statements, ts.visitNodes(body.statements, visitor, ts.isStatement, statementOffset)); + // If the original body was a multi-line block, this must be a multi-line block. + if (!multiLine && body.multiLine) { + multiLine = true; + } + } + else { + ts.Debug.assert(node.kind === 197 /* ArrowFunction */); + // To align with the old emitter, we use a synthetic end position on the location + // for the statement list we synthesize when we down-level an arrow function with + // an expression function body. This prevents both comments and source maps from + // being emitted for the end position only. + statementsLocation = ts.moveRangeEnd(body, -1); + var equalsGreaterThanToken = node.equalsGreaterThanToken; + if (!ts.nodeIsSynthesized(equalsGreaterThanToken) && !ts.nodeIsSynthesized(body)) { + if (ts.rangeEndIsOnSameLineAsRangeStart(equalsGreaterThanToken, body, currentSourceFile)) { + singleLine = true; + } + else { + multiLine = true; + } + } + var expression = ts.visitNode(body, visitor, ts.isExpression); + var returnStatement = ts.createReturn(expression); + ts.setTextRange(returnStatement, body); + ts.moveSyntheticComments(returnStatement, body); + ts.setEmitFlags(returnStatement, 384 /* NoTokenSourceMaps */ | 32 /* NoTrailingSourceMap */ | 1024 /* NoTrailingComments */); + statements.push(returnStatement); + // To align with the source map emit for the old emitter, we set a custom + // source map location for the close brace. + closeBraceLocation = body; + } + var lexicalEnvironment = context.endLexicalEnvironment(); + ts.addStatementsAfterPrologue(statements, lexicalEnvironment); + prependCaptureNewTargetIfNeeded(statements, node, /*copyOnWrite*/ false); + // If we added any final generated statements, this must be a multi-line block + if (ts.some(leadingStatements) || ts.some(lexicalEnvironment)) { + multiLine = true; + } + var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(leadingStatements.concat(statements)), statementsLocation), multiLine); + ts.setTextRange(block, node.body); + if (!multiLine && singleLine) { + ts.setEmitFlags(block, 1 /* SingleLine */); + } + if (closeBraceLocation) { + ts.setTokenSourceMapRange(block, 19 /* CloseBraceToken */, closeBraceLocation); + } + ts.setOriginalNode(block, node.body); + return block; + } + function visitFunctionBodyDownLevel(node) { + var updated = ts.visitFunctionBody(node.body, functionBodyVisitor, context); + return ts.updateBlock(updated, ts.setTextRange(ts.createNodeArray(prependCaptureNewTargetIfNeeded(updated.statements, node, /*copyOnWrite*/ true)), + /*location*/ updated.statements)); + } + function visitBlock(node, isFunctionBody) { + if (isFunctionBody) { + // A function body is not a block scope. + return ts.visitEachChild(node, visitor, context); + } + var ancestorFacts = hierarchyFacts & 256 /* IterationStatement */ + ? enterSubtree(4032 /* IterationStatementBlockExcludes */, 512 /* IterationStatementBlockIncludes */) + : enterSubtree(3904 /* BlockExcludes */, 128 /* BlockIncludes */); + var updated = ts.visitEachChild(node, visitor, context); + exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */); + return updated; + } + /** + * Visits an ExpressionStatement that contains a destructuring assignment. + * + * @param node An ExpressionStatement node. + */ + function visitExpressionStatement(node) { + // If we are here it is most likely because our expression is a destructuring assignment. + switch (node.expression.kind) { + case 195 /* ParenthesizedExpression */: + return ts.updateExpressionStatement(node, visitParenthesizedExpression(node.expression, /*needsDestructuringValue*/ false)); + case 204 /* BinaryExpression */: + return ts.updateExpressionStatement(node, visitBinaryExpression(node.expression, /*needsDestructuringValue*/ false)); + } + return ts.visitEachChild(node, visitor, context); + } + /** + * Visits a ParenthesizedExpression that may contain a destructuring assignment. + * + * @param node A ParenthesizedExpression node. + * @param needsDestructuringValue A value indicating whether we need to hold onto the rhs + * of a destructuring assignment. + */ + function visitParenthesizedExpression(node, needsDestructuringValue) { + // If we are here it is most likely because our expression is a destructuring assignment. + if (!needsDestructuringValue) { + // By default we always emit the RHS at the end of a flattened destructuring + // expression. If we are in a state where we do not need the destructuring value, + // we pass that information along to the children that care about it. + switch (node.expression.kind) { + case 195 /* ParenthesizedExpression */: + return ts.updateParen(node, visitParenthesizedExpression(node.expression, /*needsDestructuringValue*/ false)); + case 204 /* BinaryExpression */: + return ts.updateParen(node, visitBinaryExpression(node.expression, /*needsDestructuringValue*/ false)); + } + } + return ts.visitEachChild(node, visitor, context); + } + /** + * Visits a BinaryExpression that contains a destructuring assignment. + * + * @param node A BinaryExpression node. + * @param needsDestructuringValue A value indicating whether we need to hold onto the rhs + * of a destructuring assignment. + */ + function visitBinaryExpression(node, needsDestructuringValue) { + // If we are here it is because this is a destructuring assignment. + if (ts.isDestructuringAssignment(node)) { + return ts.flattenDestructuringAssignment(node, visitor, context, 0 /* All */, needsDestructuringValue); + } + return ts.visitEachChild(node, visitor, context); + } + function visitVariableStatement(node) { + var ancestorFacts = enterSubtree(0 /* None */, ts.hasModifier(node, 1 /* Export */) ? 32 /* ExportedVariableStatement */ : 0 /* None */); + var updated; + if (convertedLoopState && (node.declarationList.flags & 3 /* BlockScoped */) === 0) { + // we are inside a converted loop - hoist variable declarations + var assignments = void 0; + for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + hoistVariableDeclarationDeclaredInConvertedLoop(convertedLoopState, decl); + if (decl.initializer) { + var assignment = void 0; + if (ts.isBindingPattern(decl.name)) { + assignment = ts.flattenDestructuringAssignment(decl, visitor, context, 0 /* All */); + } + else { + assignment = ts.createBinary(decl.name, 59 /* EqualsToken */, ts.visitNode(decl.initializer, visitor, ts.isExpression)); + ts.setTextRange(assignment, decl); + } + assignments = ts.append(assignments, assignment); + } + } + if (assignments) { + updated = ts.setTextRange(ts.createExpressionStatement(ts.inlineExpressions(assignments)), node); + } + else { + // none of declarations has initializer - the entire variable statement can be deleted + updated = undefined; + } + } + else { + updated = ts.visitEachChild(node, visitor, context); + } + exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */); + return updated; + } + /** + * Visits a VariableDeclarationList that is block scoped (e.g. `let` or `const`). + * + * @param node A VariableDeclarationList node. + */ + function visitVariableDeclarationList(node) { + if (node.transformFlags & 64 /* ES2015 */) { + if (node.flags & 3 /* BlockScoped */) { + enableSubstitutionsForBlockScopedBindings(); + } + var declarations = ts.flatMap(node.declarations, node.flags & 1 /* Let */ + ? visitVariableDeclarationInLetDeclarationList + : visitVariableDeclaration); + var declarationList = ts.createVariableDeclarationList(declarations); + ts.setOriginalNode(declarationList, node); + ts.setTextRange(declarationList, node); + ts.setCommentRange(declarationList, node); + // If the first or last declaration is a binding pattern, we need to modify + // the source map range for the declaration list. + if (node.transformFlags & 2097152 /* ContainsBindingPattern */ + && (ts.isBindingPattern(node.declarations[0].name) || ts.isBindingPattern(ts.last(node.declarations).name))) { + ts.setSourceMapRange(declarationList, getRangeUnion(declarations)); + } + return declarationList; + } + return ts.visitEachChild(node, visitor, context); + } + function getRangeUnion(declarations) { + // declarations may not be sorted by position. + // pos should be the minimum* position over all nodes (that's not -1), end should be the maximum end over all nodes. + var pos = -1, end = -1; + for (var _i = 0, declarations_10 = declarations; _i < declarations_10.length; _i++) { + var node = declarations_10[_i]; + pos = pos === -1 ? node.pos : node.pos === -1 ? pos : Math.min(pos, node.pos); + end = Math.max(end, node.end); + } + return ts.createRange(pos, end); + } + /** + * Gets a value indicating whether we should emit an explicit initializer for a variable + * declaration in a `let` declaration list. + * + * @param node A VariableDeclaration node. + */ + function shouldEmitExplicitInitializerForLetDeclaration(node) { + // Nested let bindings might need to be initialized explicitly to preserve + // ES6 semantic: + // + // { let x = 1; } + // { let x; } // x here should be undefined. not 1 + // + // Top level bindings never collide with anything and thus don't require + // explicit initialization. As for nested let bindings there are two cases: + // + // - Nested let bindings that were not renamed definitely should be + // initialized explicitly: + // + // { let x = 1; } + // { let x; if (some-condition) { x = 1}; if (x) { /*1*/ } } + // + // Without explicit initialization code in /*1*/ can be executed even if + // some-condition is evaluated to false. + // + // - Renaming introduces fresh name that should not collide with any + // existing names, however renamed bindings sometimes also should be + // explicitly initialized. One particular case: non-captured binding + // declared inside loop body (but not in loop initializer): + // + // let x; + // for (;;) { + // let x; + // } + // + // In downlevel codegen inner 'x' will be renamed so it won't collide + // with outer 'x' however it will should be reset on every iteration as + // if it was declared anew. + // + // * Why non-captured binding? + // - Because if loop contains block scoped binding captured in some + // function then loop body will be rewritten to have a fresh scope + // on every iteration so everything will just work. + // + // * Why loop initializer is excluded? + // - Since we've introduced a fresh name it already will be undefined. + var flags = resolver.getNodeCheckFlags(node); + var isCapturedInFunction = flags & 262144 /* CapturedBlockScopedBinding */; + var isDeclaredInLoop = flags & 524288 /* BlockScopedBindingInLoop */; + var emittedAsTopLevel = (hierarchyFacts & 64 /* TopLevel */) !== 0 + || (isCapturedInFunction + && isDeclaredInLoop + && (hierarchyFacts & 512 /* IterationStatementBlock */) !== 0); + var emitExplicitInitializer = !emittedAsTopLevel + && (hierarchyFacts & 2048 /* ForInOrForOfStatement */) === 0 + && (!resolver.isDeclarationWithCollidingName(node) + || (isDeclaredInLoop + && !isCapturedInFunction + && (hierarchyFacts & (1024 /* ForStatement */ | 2048 /* ForInOrForOfStatement */)) === 0)); + return emitExplicitInitializer; + } + /** + * Visits a VariableDeclaration in a `let` declaration list. + * + * @param node A VariableDeclaration node. + */ + function visitVariableDeclarationInLetDeclarationList(node) { + // For binding pattern names that lack initializers there is no point to emit + // explicit initializer since downlevel codegen for destructuring will fail + // in the absence of initializer so all binding elements will say uninitialized + var name = node.name; + if (ts.isBindingPattern(name)) { + return visitVariableDeclaration(node); + } + if (!node.initializer && shouldEmitExplicitInitializerForLetDeclaration(node)) { + var clone_2 = ts.getMutableClone(node); + clone_2.initializer = ts.createVoidZero(); + return clone_2; + } + return ts.visitEachChild(node, visitor, context); + } + /** + * Visits a VariableDeclaration node with a binding pattern. + * + * @param node A VariableDeclaration node. + */ + function visitVariableDeclaration(node) { + var ancestorFacts = enterSubtree(32 /* ExportedVariableStatement */, 0 /* None */); + var updated; + if (ts.isBindingPattern(node.name)) { + updated = ts.flattenDestructuringBinding(node, visitor, context, 0 /* All */, + /*value*/ undefined, (ancestorFacts & 32 /* ExportedVariableStatement */) !== 0); + } + else { + updated = ts.visitEachChild(node, visitor, context); + } + exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */); + return updated; + } + function recordLabel(node) { + convertedLoopState.labels.set(ts.idText(node.label), true); + } + function resetLabel(node) { + convertedLoopState.labels.set(ts.idText(node.label), false); + } + function visitLabeledStatement(node) { + if (convertedLoopState && !convertedLoopState.labels) { + convertedLoopState.labels = ts.createMap(); + } + var statement = ts.unwrapInnermostStatementOfLabel(node, convertedLoopState && recordLabel); + return ts.isIterationStatement(statement, /*lookInLabeledStatements*/ false) + ? visitIterationStatement(statement, /*outermostLabeledStatement*/ node) + : ts.restoreEnclosingLabel(ts.visitNode(statement, visitor, ts.isStatement, ts.liftToBlock), node, convertedLoopState && resetLabel); + } + function visitIterationStatement(node, outermostLabeledStatement) { + switch (node.kind) { + case 223 /* DoStatement */: + case 224 /* WhileStatement */: + return visitDoOrWhileStatement(node, outermostLabeledStatement); + case 225 /* ForStatement */: + return visitForStatement(node, outermostLabeledStatement); + case 226 /* ForInStatement */: + return visitForInStatement(node, outermostLabeledStatement); + case 227 /* ForOfStatement */: + return visitForOfStatement(node, outermostLabeledStatement); + } + } + function visitIterationStatementWithFacts(excludeFacts, includeFacts, node, outermostLabeledStatement, convert) { + var ancestorFacts = enterSubtree(excludeFacts, includeFacts); + var updated = convertIterationStatementBodyIfNecessary(node, outermostLabeledStatement, convert); + exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */); + return updated; + } + function visitDoOrWhileStatement(node, outermostLabeledStatement) { + return visitIterationStatementWithFacts(0 /* DoOrWhileStatementExcludes */, 256 /* DoOrWhileStatementIncludes */, node, outermostLabeledStatement); + } + function visitForStatement(node, outermostLabeledStatement) { + return visitIterationStatementWithFacts(3008 /* ForStatementExcludes */, 1280 /* ForStatementIncludes */, node, outermostLabeledStatement); + } + function visitForInStatement(node, outermostLabeledStatement) { + return visitIterationStatementWithFacts(1984 /* ForInOrForOfStatementExcludes */, 2304 /* ForInOrForOfStatementIncludes */, node, outermostLabeledStatement); + } + function visitForOfStatement(node, outermostLabeledStatement) { + return visitIterationStatementWithFacts(1984 /* ForInOrForOfStatementExcludes */, 2304 /* ForInOrForOfStatementIncludes */, node, outermostLabeledStatement, compilerOptions.downlevelIteration ? convertForOfStatementForIterable : convertForOfStatementForArray); + } + function convertForOfStatementHead(node, boundValue, convertedLoopBodyStatements) { + var statements = []; + var initializer = node.initializer; + if (ts.isVariableDeclarationList(initializer)) { + if (node.initializer.flags & 3 /* BlockScoped */) { + enableSubstitutionsForBlockScopedBindings(); + } + var firstOriginalDeclaration = ts.firstOrUndefined(initializer.declarations); + if (firstOriginalDeclaration && ts.isBindingPattern(firstOriginalDeclaration.name)) { + // This works whether the declaration is a var, let, or const. + // It will use rhsIterationValue _a[_i] as the initializer. + var declarations = ts.flattenDestructuringBinding(firstOriginalDeclaration, visitor, context, 0 /* All */, boundValue); + var declarationList = ts.setTextRange(ts.createVariableDeclarationList(declarations), node.initializer); + ts.setOriginalNode(declarationList, node.initializer); + // Adjust the source map range for the first declaration to align with the old + // emitter. + ts.setSourceMapRange(declarationList, ts.createRange(declarations[0].pos, ts.last(declarations).end)); + statements.push(ts.createVariableStatement( + /*modifiers*/ undefined, declarationList)); + } + else { + // The following call does not include the initializer, so we have + // to emit it separately. + statements.push(ts.setTextRange(ts.createVariableStatement( + /*modifiers*/ undefined, ts.setOriginalNode(ts.setTextRange(ts.createVariableDeclarationList([ + ts.createVariableDeclaration(firstOriginalDeclaration ? firstOriginalDeclaration.name : ts.createTempVariable(/*recordTempVariable*/ undefined), + /*type*/ undefined, boundValue) + ]), ts.moveRangePos(initializer, -1)), initializer)), ts.moveRangeEnd(initializer, -1))); + } + } + else { + // Initializer is an expression. Emit the expression in the body, so that it's + // evaluated on every iteration. + var assignment = ts.createAssignment(initializer, boundValue); + if (ts.isDestructuringAssignment(assignment)) { + ts.aggregateTransformFlags(assignment); + statements.push(ts.createExpressionStatement(visitBinaryExpression(assignment, /*needsDestructuringValue*/ false))); + } + else { + assignment.end = initializer.end; + statements.push(ts.setTextRange(ts.createExpressionStatement(ts.visitNode(assignment, visitor, ts.isExpression)), ts.moveRangeEnd(initializer, -1))); + } + } + if (convertedLoopBodyStatements) { + return createSyntheticBlockForConvertedStatements(ts.addRange(statements, convertedLoopBodyStatements)); + } + else { + var statement = ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock); + if (ts.isBlock(statement)) { + return ts.updateBlock(statement, ts.setTextRange(ts.createNodeArray(ts.concatenate(statements, statement.statements)), statement.statements)); + } + else { + statements.push(statement); + return createSyntheticBlockForConvertedStatements(statements); + } + } + } + function createSyntheticBlockForConvertedStatements(statements) { + return ts.setEmitFlags(ts.createBlock(ts.createNodeArray(statements), + /*multiLine*/ true), 48 /* NoSourceMap */ | 384 /* NoTokenSourceMaps */); + } + function convertForOfStatementForArray(node, outermostLabeledStatement, convertedLoopBodyStatements) { + // The following ES6 code: + // + // for (let v of expr) { } + // + // should be emitted as + // + // for (var _i = 0, _a = expr; _i < _a.length; _i++) { + // var v = _a[_i]; + // } + // + // where _a and _i are temps emitted to capture the RHS and the counter, + // respectively. + // When the left hand side is an expression instead of a let declaration, + // the "let v" is not emitted. + // When the left hand side is a let/const, the v is renamed if there is + // another v in scope. + // Note that all assignments to the LHS are emitted in the body, including + // all destructuring. + // Note also that because an extra statement is needed to assign to the LHS, + // for-of bodies are always emitted as blocks. + var expression = ts.visitNode(node.expression, visitor, ts.isExpression); + // In the case where the user wrote an identifier as the RHS, like this: + // + // for (let v of arr) { } + // + // we don't want to emit a temporary variable for the RHS, just use it directly. + var counter = ts.createLoopVariable(); + var rhsReference = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(expression) : ts.createTempVariable(/*recordTempVariable*/ undefined); + // The old emitter does not emit source maps for the expression + ts.setEmitFlags(expression, 48 /* NoSourceMap */ | ts.getEmitFlags(expression)); + var forStatement = ts.setTextRange(ts.createFor( + /*initializer*/ ts.setEmitFlags(ts.setTextRange(ts.createVariableDeclarationList([ + ts.setTextRange(ts.createVariableDeclaration(counter, /*type*/ undefined, ts.createLiteral(0)), ts.moveRangePos(node.expression, -1)), + ts.setTextRange(ts.createVariableDeclaration(rhsReference, /*type*/ undefined, expression), node.expression) + ]), node.expression), 2097152 /* NoHoisting */), + /*condition*/ ts.setTextRange(ts.createLessThan(counter, ts.createPropertyAccess(rhsReference, "length")), node.expression), + /*incrementor*/ ts.setTextRange(ts.createPostfixIncrement(counter), node.expression), + /*statement*/ convertForOfStatementHead(node, ts.createElementAccess(rhsReference, counter), convertedLoopBodyStatements)), + /*location*/ node); + // Disable trailing source maps for the OpenParenToken to align source map emit with the old emitter. + ts.setEmitFlags(forStatement, 256 /* NoTokenTrailingSourceMaps */); + ts.setTextRange(forStatement, node); + return ts.restoreEnclosingLabel(forStatement, outermostLabeledStatement, convertedLoopState && resetLabel); + } + function convertForOfStatementForIterable(node, outermostLabeledStatement, convertedLoopBodyStatements) { + var expression = ts.visitNode(node.expression, visitor, ts.isExpression); + var iterator = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(expression) : ts.createTempVariable(/*recordTempVariable*/ undefined); + var result = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(iterator) : ts.createTempVariable(/*recordTempVariable*/ undefined); + var errorRecord = ts.createUniqueName("e"); + var catchVariable = ts.getGeneratedNameForNode(errorRecord); + var returnMethod = ts.createTempVariable(/*recordTempVariable*/ undefined); + var values = ts.createValuesHelper(context, expression, node.expression); + var next = ts.createCall(ts.createPropertyAccess(iterator, "next"), /*typeArguments*/ undefined, []); + hoistVariableDeclaration(errorRecord); + hoistVariableDeclaration(returnMethod); + var forStatement = ts.setEmitFlags(ts.setTextRange(ts.createFor( + /*initializer*/ ts.setEmitFlags(ts.setTextRange(ts.createVariableDeclarationList([ + ts.setTextRange(ts.createVariableDeclaration(iterator, /*type*/ undefined, values), node.expression), + ts.createVariableDeclaration(result, /*type*/ undefined, next) + ]), node.expression), 2097152 /* NoHoisting */), + /*condition*/ ts.createLogicalNot(ts.createPropertyAccess(result, "done")), + /*incrementor*/ ts.createAssignment(result, next), + /*statement*/ convertForOfStatementHead(node, ts.createPropertyAccess(result, "value"), convertedLoopBodyStatements)), + /*location*/ node), 256 /* NoTokenTrailingSourceMaps */); + return ts.createTry(ts.createBlock([ + ts.restoreEnclosingLabel(forStatement, outermostLabeledStatement, convertedLoopState && resetLabel) + ]), ts.createCatchClause(ts.createVariableDeclaration(catchVariable), ts.setEmitFlags(ts.createBlock([ + ts.createExpressionStatement(ts.createAssignment(errorRecord, ts.createObjectLiteral([ + ts.createPropertyAssignment("error", catchVariable) + ]))) + ]), 1 /* SingleLine */)), ts.createBlock([ + ts.createTry( + /*tryBlock*/ ts.createBlock([ + ts.setEmitFlags(ts.createIf(ts.createLogicalAnd(ts.createLogicalAnd(result, ts.createLogicalNot(ts.createPropertyAccess(result, "done"))), ts.createAssignment(returnMethod, ts.createPropertyAccess(iterator, "return"))), ts.createExpressionStatement(ts.createFunctionCall(returnMethod, iterator, []))), 1 /* SingleLine */), + ]), + /*catchClause*/ undefined, + /*finallyBlock*/ ts.setEmitFlags(ts.createBlock([ + ts.setEmitFlags(ts.createIf(errorRecord, ts.createThrow(ts.createPropertyAccess(errorRecord, "error"))), 1 /* SingleLine */) + ]), 1 /* SingleLine */)) + ])); + } + /** + * Visits an ObjectLiteralExpression with computed property names. + * + * @param node An ObjectLiteralExpression node. + */ + function visitObjectLiteralExpression(node) { + // We are here because a ComputedPropertyName was used somewhere in the expression. + var properties = node.properties; + var numProperties = properties.length; + // Find the first computed property. + // Everything until that point can be emitted as part of the initial object literal. + var numInitialProperties = numProperties; + var numInitialPropertiesWithoutYield = numProperties; + for (var i = 0; i < numProperties; i++) { + var property = properties[i]; + if ((property.transformFlags & 4194304 /* ContainsYield */ && hierarchyFacts & 4 /* AsyncFunctionBody */) + && i < numInitialPropertiesWithoutYield) { + numInitialPropertiesWithoutYield = i; + } + if (property.name.kind === 149 /* ComputedPropertyName */) { + numInitialProperties = i; + break; + } + } + if (numInitialProperties !== numProperties) { + if (numInitialPropertiesWithoutYield < numInitialProperties) { + numInitialProperties = numInitialPropertiesWithoutYield; + } + // For computed properties, we need to create a unique handle to the object + // literal so we can modify it without risking internal assignments tainting the object. + var temp = ts.createTempVariable(hoistVariableDeclaration); + // Write out the first non-computed properties, then emit the rest through indexing on the temp variable. + var expressions = []; + var assignment = ts.createAssignment(temp, ts.setEmitFlags(ts.createObjectLiteral(ts.visitNodes(properties, visitor, ts.isObjectLiteralElementLike, 0, numInitialProperties), node.multiLine), 65536 /* Indented */)); + if (node.multiLine) { + ts.startOnNewLine(assignment); + } + expressions.push(assignment); + addObjectLiteralMembers(expressions, node, temp, numInitialProperties); + // We need to clone the temporary identifier so that we can write it on a + // new line + expressions.push(node.multiLine ? ts.startOnNewLine(ts.getMutableClone(temp)) : temp); + return ts.inlineExpressions(expressions); + } + return ts.visitEachChild(node, visitor, context); + } + function shouldConvertPartOfIterationStatement(node) { + return (resolver.getNodeCheckFlags(node) & 131072 /* ContainsCapturedBlockScopeBinding */) !== 0; + } + function shouldConvertInitializerOfForStatement(node) { + return ts.isForStatement(node) && !!node.initializer && shouldConvertPartOfIterationStatement(node.initializer); + } + function shouldConvertConditionOfForStatement(node) { + return ts.isForStatement(node) && !!node.condition && shouldConvertPartOfIterationStatement(node.condition); + } + function shouldConvertIncrementorOfForStatement(node) { + return ts.isForStatement(node) && !!node.incrementor && shouldConvertPartOfIterationStatement(node.incrementor); + } + function shouldConvertIterationStatement(node) { + return shouldConvertBodyOfIterationStatement(node) + || shouldConvertInitializerOfForStatement(node); + } + function shouldConvertBodyOfIterationStatement(node) { + return (resolver.getNodeCheckFlags(node) & 65536 /* LoopWithCapturedBlockScopedBinding */) !== 0; + } + /** + * Records constituents of name for the given variable to be hoisted in the outer scope. + */ + function hoistVariableDeclarationDeclaredInConvertedLoop(state, node) { + if (!state.hoistedLocalVariables) { + state.hoistedLocalVariables = []; + } + visit(node.name); + function visit(node) { + if (node.kind === 72 /* Identifier */) { + state.hoistedLocalVariables.push(node); + } + else { + for (var _i = 0, _a = node.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (!ts.isOmittedExpression(element)) { + visit(element.name); + } + } + } + } + } + function convertIterationStatementBodyIfNecessary(node, outermostLabeledStatement, convert) { + if (!shouldConvertIterationStatement(node)) { + var saveAllowedNonLabeledJumps = void 0; + if (convertedLoopState) { + // we get here if we are trying to emit normal loop loop inside converted loop + // set allowedNonLabeledJumps to Break | Continue to mark that break\continue inside the loop should be emitted as is + saveAllowedNonLabeledJumps = convertedLoopState.allowedNonLabeledJumps; + convertedLoopState.allowedNonLabeledJumps = 2 /* Break */ | 4 /* Continue */; + } + var result = convert + ? convert(node, outermostLabeledStatement, /*convertedLoopBodyStatements*/ undefined) + : ts.restoreEnclosingLabel(ts.visitEachChild(node, visitor, context), outermostLabeledStatement, convertedLoopState && resetLabel); + if (convertedLoopState) { + convertedLoopState.allowedNonLabeledJumps = saveAllowedNonLabeledJumps; + } + return result; + } + var currentState = createConvertedLoopState(node); + var statements = []; + var outerConvertedLoopState = convertedLoopState; + convertedLoopState = currentState; + var initializerFunction = shouldConvertInitializerOfForStatement(node) ? createFunctionForInitializerOfForStatement(node, currentState) : undefined; + var bodyFunction = shouldConvertBodyOfIterationStatement(node) ? createFunctionForBodyOfIterationStatement(node, currentState, outerConvertedLoopState) : undefined; + convertedLoopState = outerConvertedLoopState; + if (initializerFunction) + statements.push(initializerFunction.functionDeclaration); + if (bodyFunction) + statements.push(bodyFunction.functionDeclaration); + addExtraDeclarationsForConvertedLoop(statements, currentState, outerConvertedLoopState); + if (initializerFunction) { + statements.push(generateCallToConvertedLoopInitializer(initializerFunction.functionName, initializerFunction.containsYield)); + } + var loop; + if (bodyFunction) { + if (convert) { + loop = convert(node, outermostLabeledStatement, bodyFunction.part); + } + else { + var clone_3 = convertIterationStatementCore(node, initializerFunction, ts.createBlock(bodyFunction.part, /*multiLine*/ true)); + ts.aggregateTransformFlags(clone_3); + loop = ts.restoreEnclosingLabel(clone_3, outermostLabeledStatement, convertedLoopState && resetLabel); + } + } + else { + var clone_4 = convertIterationStatementCore(node, initializerFunction, ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); + ts.aggregateTransformFlags(clone_4); + loop = ts.restoreEnclosingLabel(clone_4, outermostLabeledStatement, convertedLoopState && resetLabel); + } + statements.push(loop); + return statements; + } + function convertIterationStatementCore(node, initializerFunction, convertedLoopBody) { + switch (node.kind) { + case 225 /* ForStatement */: return convertForStatement(node, initializerFunction, convertedLoopBody); + case 226 /* ForInStatement */: return convertForInStatement(node, convertedLoopBody); + case 227 /* ForOfStatement */: return convertForOfStatement(node, convertedLoopBody); + case 223 /* DoStatement */: return convertDoStatement(node, convertedLoopBody); + case 224 /* WhileStatement */: return convertWhileStatement(node, convertedLoopBody); + default: return ts.Debug.failBadSyntaxKind(node, "IterationStatement expected"); + } + } + function convertForStatement(node, initializerFunction, convertedLoopBody) { + var shouldConvertCondition = node.condition && shouldConvertPartOfIterationStatement(node.condition); + var shouldConvertIncrementor = shouldConvertCondition || node.incrementor && shouldConvertPartOfIterationStatement(node.incrementor); + return ts.updateFor(node, ts.visitNode(initializerFunction ? initializerFunction.part : node.initializer, visitor, ts.isForInitializer), ts.visitNode(shouldConvertCondition ? undefined : node.condition, visitor, ts.isExpression), ts.visitNode(shouldConvertIncrementor ? undefined : node.incrementor, visitor, ts.isExpression), convertedLoopBody); + } + function convertForOfStatement(node, convertedLoopBody) { + return ts.updateForOf(node, + /*awaitModifier*/ undefined, ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), convertedLoopBody); + } + function convertForInStatement(node, convertedLoopBody) { + return ts.updateForIn(node, ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), convertedLoopBody); + } + function convertDoStatement(node, convertedLoopBody) { + return ts.updateDo(node, convertedLoopBody, ts.visitNode(node.expression, visitor, ts.isExpression)); + } + function convertWhileStatement(node, convertedLoopBody) { + return ts.updateWhile(node, ts.visitNode(node.expression, visitor, ts.isExpression), convertedLoopBody); + } + function createConvertedLoopState(node) { + var loopInitializer; + switch (node.kind) { + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + var initializer = node.initializer; + if (initializer && initializer.kind === 238 /* VariableDeclarationList */) { + loopInitializer = initializer; + } + break; + } + // variables that will be passed to the loop as parameters + var loopParameters = []; + // variables declared in the loop initializer that will be changed inside the loop + var loopOutParameters = []; + if (loopInitializer && (ts.getCombinedNodeFlags(loopInitializer) & 3 /* BlockScoped */)) { + var hasCapturedBindingsInForInitializer = shouldConvertInitializerOfForStatement(node); + for (var _i = 0, _a = loopInitializer.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + processLoopVariableDeclaration(node, decl, loopParameters, loopOutParameters, hasCapturedBindingsInForInitializer); + } + } + var currentState = { loopParameters: loopParameters, loopOutParameters: loopOutParameters }; + if (convertedLoopState) { + // convertedOuterLoopState !== undefined means that this converted loop is nested in another converted loop. + // if outer converted loop has already accumulated some state - pass it through + if (convertedLoopState.argumentsName) { + // outer loop has already used 'arguments' so we've already have some name to alias it + // use the same name in all nested loops + currentState.argumentsName = convertedLoopState.argumentsName; + } + if (convertedLoopState.thisName) { + // outer loop has already used 'this' so we've already have some name to alias it + // use the same name in all nested loops + currentState.thisName = convertedLoopState.thisName; + } + if (convertedLoopState.hoistedLocalVariables) { + // we've already collected some non-block scoped variable declarations in enclosing loop + // use the same storage in nested loop + currentState.hoistedLocalVariables = convertedLoopState.hoistedLocalVariables; + } + } + return currentState; + } + function addExtraDeclarationsForConvertedLoop(statements, state, outerState) { + var extraVariableDeclarations; + // propagate state from the inner loop to the outer loop if necessary + if (state.argumentsName) { + // if alias for arguments is set + if (outerState) { + // pass it to outer converted loop + outerState.argumentsName = state.argumentsName; + } + else { + // this is top level converted loop and we need to create an alias for 'arguments' object + (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(state.argumentsName, + /*type*/ undefined, ts.createIdentifier("arguments"))); + } + } + if (state.thisName) { + // if alias for this is set + if (outerState) { + // pass it to outer converted loop + outerState.thisName = state.thisName; + } + else { + // this is top level converted loop so we need to create an alias for 'this' here + // NOTE: + // if converted loops were all nested in arrow function then we'll always emit '_this' so convertedLoopState.thisName will not be set. + // If it is set this means that all nested loops are not nested in arrow function and it is safe to capture 'this'. + (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(state.thisName, + /*type*/ undefined, ts.createIdentifier("this"))); + } + } + if (state.hoistedLocalVariables) { + // if hoistedLocalVariables !== undefined this means that we've possibly collected some variable declarations to be hoisted later + if (outerState) { + // pass them to outer converted loop + outerState.hoistedLocalVariables = state.hoistedLocalVariables; + } + else { + if (!extraVariableDeclarations) { + extraVariableDeclarations = []; + } + // hoist collected variable declarations + for (var _i = 0, _a = state.hoistedLocalVariables; _i < _a.length; _i++) { + var identifier = _a[_i]; + extraVariableDeclarations.push(ts.createVariableDeclaration(identifier)); + } + } + } + // add extra variables to hold out parameters if necessary + if (state.loopOutParameters.length) { + if (!extraVariableDeclarations) { + extraVariableDeclarations = []; + } + for (var _b = 0, _c = state.loopOutParameters; _b < _c.length; _b++) { + var outParam = _c[_b]; + extraVariableDeclarations.push(ts.createVariableDeclaration(outParam.outParamName)); + } + } + if (state.conditionVariable) { + if (!extraVariableDeclarations) { + extraVariableDeclarations = []; + } + extraVariableDeclarations.push(ts.createVariableDeclaration(state.conditionVariable, /*type*/ undefined, ts.createFalse())); + } + // create variable statement to hold all introduced variable declarations + if (extraVariableDeclarations) { + statements.push(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList(extraVariableDeclarations))); + } + } + function createOutVariable(p) { + return ts.createVariableDeclaration(p.originalName, /*type*/ undefined, p.outParamName); + } + /** + * Creates a `_loop_init` function for a `ForStatement` with a block-scoped initializer + * that is captured in a closure inside of the initializer. The `_loop_init` function is + * used to preserve the per-iteration environment semantics of + * [13.7.4.8 RS: ForBodyEvaluation](https://tc39.github.io/ecma262/#sec-forbodyevaluation). + */ + function createFunctionForInitializerOfForStatement(node, currentState) { + var functionName = ts.createUniqueName("_loop_init"); + var containsYield = (node.initializer.transformFlags & 4194304 /* ContainsYield */) !== 0; + var emitFlags = 0 /* None */; + if (currentState.containsLexicalThis) + emitFlags |= 8 /* CapturesThis */; + if (containsYield && hierarchyFacts & 4 /* AsyncFunctionBody */) + emitFlags |= 262144 /* AsyncFunctionBody */; + var statements = []; + statements.push(ts.createVariableStatement(/*modifiers*/ undefined, node.initializer)); + copyOutParameters(currentState.loopOutParameters, 2 /* Initializer */, 1 /* ToOutParameter */, statements); + // This transforms the following ES2015 syntax: + // + // for (let i = (setImmediate(() => console.log(i)), 0); i < 2; i++) { + // // loop body + // } + // + // Into the following ES5 syntax: + // + // var _loop_init_1 = function () { + // var i = (setImmediate(() => console.log(i)), 0); + // out_i_1 = i; + // }; + // var out_i_1; + // _loop_init_1(); + // for (var i = out_i_1; i < 2; i++) { + // // loop body + // } + // + // Which prevents mutations to `i` in the per-iteration environment of the body + // from affecting the initial value for `i` outside of the per-iteration environment. + var functionDeclaration = ts.createVariableStatement( + /*modifiers*/ undefined, ts.setEmitFlags(ts.createVariableDeclarationList([ + ts.createVariableDeclaration(functionName, + /*type*/ undefined, ts.setEmitFlags(ts.createFunctionExpression( + /*modifiers*/ undefined, containsYield ? ts.createToken(40 /* AsteriskToken */) : undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, + /*parameters*/ undefined, + /*type*/ undefined, ts.visitNode(ts.createBlock(statements, /*multiLine*/ true), visitor, ts.isBlock)), emitFlags)) + ]), 2097152 /* NoHoisting */)); + var part = ts.createVariableDeclarationList(ts.map(currentState.loopOutParameters, createOutVariable)); + return { functionName: functionName, containsYield: containsYield, functionDeclaration: functionDeclaration, part: part }; + } + /** + * Creates a `_loop` function for an `IterationStatement` with a block-scoped initializer + * that is captured in a closure inside of the loop body. The `_loop` function is used to + * preserve the per-iteration environment semantics of + * [13.7.4.8 RS: ForBodyEvaluation](https://tc39.github.io/ecma262/#sec-forbodyevaluation). + */ + function createFunctionForBodyOfIterationStatement(node, currentState, outerState) { + var functionName = ts.createUniqueName("_loop"); + startLexicalEnvironment(); + var statement = ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock); + var lexicalEnvironment = endLexicalEnvironment(); + var statements = []; + if (shouldConvertConditionOfForStatement(node) || shouldConvertIncrementorOfForStatement(node)) { + // If a block-scoped variable declared in the initializer of `node` is captured in + // the condition or incrementor, we must move the condition and incrementor into + // the body of the for loop. + // + // This transforms the following ES2015 syntax: + // + // for (let i = 0; setImmediate(() => console.log(i)), i < 2; setImmediate(() => console.log(i)), i++) { + // // loop body + // } + // + // Into the following ES5 syntax: + // + // var _loop_1 = function (i) { + // if (inc_1) + // setImmediate(() => console.log(i)), i++; + // else + // inc_1 = true; + // if (!(setImmediate(() => console.log(i)), i < 2)) + // return out_i_1 = i, "break"; + // // loop body + // out_i_1 = i; + // } + // var out_i_1, inc_1 = false; + // for (var i = 0;;) { + // var state_1 = _loop_1(i); + // i = out_i_1; + // if (state_1 === "break") + // break; + // } + // + // Which prevents mutations to `i` in the per-iteration environment of the body + // from affecting the value of `i` in the previous per-iteration environment. + // + // Note that the incrementor of a `for` loop is evaluated in a *new* per-iteration + // environment that is carried over to the next iteration of the loop. As a result, + // we must indicate whether this is the first evaluation of the loop body so that + // we only evaluate the incrementor on subsequent evaluations. + currentState.conditionVariable = ts.createUniqueName("inc"); + statements.push(ts.createIf(currentState.conditionVariable, ts.createStatement(ts.visitNode(node.incrementor, visitor, ts.isExpression)), ts.createStatement(ts.createAssignment(currentState.conditionVariable, ts.createTrue())))); + if (shouldConvertConditionOfForStatement(node)) { + statements.push(ts.createIf(ts.createPrefix(52 /* ExclamationToken */, ts.visitNode(node.condition, visitor, ts.isExpression)), ts.visitNode(ts.createBreak(), visitor, ts.isStatement))); + } + } + if (ts.isBlock(statement)) { + ts.addRange(statements, statement.statements); + } + else { + statements.push(statement); + } + copyOutParameters(currentState.loopOutParameters, 1 /* Body */, 1 /* ToOutParameter */, statements); + ts.addStatementsAfterPrologue(statements, lexicalEnvironment); + var loopBody = ts.createBlock(statements, /*multiLine*/ true); + if (ts.isBlock(statement)) + ts.setOriginalNode(loopBody, statement); + var containsYield = (node.statement.transformFlags & 4194304 /* ContainsYield */) !== 0; + var emitFlags = 0; + if (currentState.containsLexicalThis) + emitFlags |= 8 /* CapturesThis */; + if (containsYield && (hierarchyFacts & 4 /* AsyncFunctionBody */) !== 0) + emitFlags |= 262144 /* AsyncFunctionBody */; + // This transforms the following ES2015 syntax (in addition to other variations): + // + // for (let i = 0; i < 2; i++) { + // setImmediate(() => console.log(i)); + // } + // + // Into the following ES5 syntax: + // + // var _loop_1 = function (i) { + // setImmediate(() => console.log(i)); + // }; + // for (var i = 0; i < 2; i++) { + // _loop_1(i); + // } + var functionDeclaration = ts.createVariableStatement( + /*modifiers*/ undefined, ts.setEmitFlags(ts.createVariableDeclarationList([ + ts.createVariableDeclaration(functionName, + /*type*/ undefined, ts.setEmitFlags(ts.createFunctionExpression( + /*modifiers*/ undefined, containsYield ? ts.createToken(40 /* AsteriskToken */) : undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, currentState.loopParameters, + /*type*/ undefined, loopBody), emitFlags)) + ]), 2097152 /* NoHoisting */)); + var part = generateCallToConvertedLoop(functionName, currentState, outerState, containsYield); + return { functionName: functionName, containsYield: containsYield, functionDeclaration: functionDeclaration, part: part }; + } + function copyOutParameter(outParam, copyDirection) { + var source = copyDirection === 0 /* ToOriginal */ ? outParam.outParamName : outParam.originalName; + var target = copyDirection === 0 /* ToOriginal */ ? outParam.originalName : outParam.outParamName; + return ts.createBinary(target, 59 /* EqualsToken */, source); + } + function copyOutParameters(outParams, partFlags, copyDirection, statements) { + for (var _i = 0, outParams_1 = outParams; _i < outParams_1.length; _i++) { + var outParam = outParams_1[_i]; + if (outParam.flags & partFlags) { + statements.push(ts.createExpressionStatement(copyOutParameter(outParam, copyDirection))); + } + } + } + function generateCallToConvertedLoopInitializer(initFunctionExpressionName, containsYield) { + var call = ts.createCall(initFunctionExpressionName, /*typeArguments*/ undefined, []); + var callResult = containsYield + ? ts.createYield(ts.createToken(40 /* AsteriskToken */), ts.setEmitFlags(call, 8388608 /* Iterator */)) + : call; + return ts.createStatement(callResult); + } + function generateCallToConvertedLoop(loopFunctionExpressionName, state, outerState, containsYield) { + var statements = []; + // loop is considered simple if it does not have any return statements or break\continue that transfer control outside of the loop + // simple loops are emitted as just 'loop()'; + // NOTE: if loop uses only 'continue' it still will be emitted as simple loop + var isSimpleLoop = !(state.nonLocalJumps & ~4 /* Continue */) && + !state.labeledNonLocalBreaks && + !state.labeledNonLocalContinues; + var call = ts.createCall(loopFunctionExpressionName, /*typeArguments*/ undefined, ts.map(state.loopParameters, function (p) { return p.name; })); + var callResult = containsYield + ? ts.createYield(ts.createToken(40 /* AsteriskToken */), ts.setEmitFlags(call, 8388608 /* Iterator */)) + : call; + if (isSimpleLoop) { + statements.push(ts.createExpressionStatement(callResult)); + copyOutParameters(state.loopOutParameters, 1 /* Body */, 0 /* ToOriginal */, statements); + } + else { + var loopResultName = ts.createUniqueName("state"); + var stateVariable = ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(loopResultName, /*type*/ undefined, callResult)])); + statements.push(stateVariable); + copyOutParameters(state.loopOutParameters, 1 /* Body */, 0 /* ToOriginal */, statements); + if (state.nonLocalJumps & 8 /* Return */) { + var returnStatement = void 0; + if (outerState) { + outerState.nonLocalJumps |= 8 /* Return */; + returnStatement = ts.createReturn(loopResultName); + } + else { + returnStatement = ts.createReturn(ts.createPropertyAccess(loopResultName, "value")); + } + statements.push(ts.createIf(ts.createBinary(ts.createTypeOf(loopResultName), 35 /* EqualsEqualsEqualsToken */, ts.createLiteral("object")), returnStatement)); + } + if (state.nonLocalJumps & 2 /* Break */) { + statements.push(ts.createIf(ts.createBinary(loopResultName, 35 /* EqualsEqualsEqualsToken */, ts.createLiteral("break")), ts.createBreak())); + } + if (state.labeledNonLocalBreaks || state.labeledNonLocalContinues) { + var caseClauses = []; + processLabeledJumps(state.labeledNonLocalBreaks, /*isBreak*/ true, loopResultName, outerState, caseClauses); + processLabeledJumps(state.labeledNonLocalContinues, /*isBreak*/ false, loopResultName, outerState, caseClauses); + statements.push(ts.createSwitch(loopResultName, ts.createCaseBlock(caseClauses))); + } + } + return statements; + } + function setLabeledJump(state, isBreak, labelText, labelMarker) { + if (isBreak) { + if (!state.labeledNonLocalBreaks) { + state.labeledNonLocalBreaks = ts.createMap(); + } + state.labeledNonLocalBreaks.set(labelText, labelMarker); + } + else { + if (!state.labeledNonLocalContinues) { + state.labeledNonLocalContinues = ts.createMap(); + } + state.labeledNonLocalContinues.set(labelText, labelMarker); + } + } + function processLabeledJumps(table, isBreak, loopResultName, outerLoop, caseClauses) { + if (!table) { + return; + } + table.forEach(function (labelMarker, labelText) { + var statements = []; + // if there are no outer converted loop or outer label in question is located inside outer converted loop + // then emit labeled break\continue + // otherwise propagate pair 'label -> marker' to outer converted loop and emit 'return labelMarker' so outer loop can later decide what to do + if (!outerLoop || (outerLoop.labels && outerLoop.labels.get(labelText))) { + var label = ts.createIdentifier(labelText); + statements.push(isBreak ? ts.createBreak(label) : ts.createContinue(label)); + } + else { + setLabeledJump(outerLoop, isBreak, labelText, labelMarker); + statements.push(ts.createReturn(loopResultName)); + } + caseClauses.push(ts.createCaseClause(ts.createLiteral(labelMarker), statements)); + }); + } + function processLoopVariableDeclaration(container, decl, loopParameters, loopOutParameters, hasCapturedBindingsInForInitializer) { + var name = decl.name; + if (ts.isBindingPattern(name)) { + for (var _i = 0, _a = name.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (!ts.isOmittedExpression(element)) { + processLoopVariableDeclaration(container, element, loopParameters, loopOutParameters, hasCapturedBindingsInForInitializer); + } + } + } + else { + loopParameters.push(ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, name)); + var checkFlags = resolver.getNodeCheckFlags(decl); + if (checkFlags & 4194304 /* NeedsLoopOutParameter */ || hasCapturedBindingsInForInitializer) { + var outParamName = ts.createUniqueName("out_" + ts.idText(name)); + var flags = 0; + if (checkFlags & 4194304 /* NeedsLoopOutParameter */) { + flags |= 1 /* Body */; + } + if (ts.isForStatement(container) && container.initializer && resolver.isBindingCapturedByNode(container.initializer, decl)) { + flags |= 2 /* Initializer */; + } + loopOutParameters.push({ flags: flags, originalName: name, outParamName: outParamName }); + } + } + } + /** + * Adds the members of an object literal to an array of expressions. + * + * @param expressions An array of expressions. + * @param node An ObjectLiteralExpression node. + * @param receiver The receiver for members of the ObjectLiteralExpression. + * @param numInitialNonComputedProperties The number of initial properties without + * computed property names. + */ + function addObjectLiteralMembers(expressions, node, receiver, start) { + var properties = node.properties; + var numProperties = properties.length; + for (var i = start; i < numProperties; i++) { + var property = properties[i]; + switch (property.kind) { + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + var accessors = ts.getAllAccessorDeclarations(node.properties, property); + if (property === accessors.firstAccessor) { + expressions.push(transformAccessorsToExpression(receiver, accessors, node, !!node.multiLine)); + } + break; + case 156 /* MethodDeclaration */: + expressions.push(transformObjectLiteralMethodDeclarationToExpression(property, receiver, node, node.multiLine)); + break; + case 275 /* PropertyAssignment */: + expressions.push(transformPropertyAssignmentToExpression(property, receiver, node.multiLine)); + break; + case 276 /* ShorthandPropertyAssignment */: + expressions.push(transformShorthandPropertyAssignmentToExpression(property, receiver, node.multiLine)); + break; + default: + ts.Debug.failBadSyntaxKind(node); + break; + } + } + } + /** + * Transforms a PropertyAssignment node into an expression. + * + * @param node The ObjectLiteralExpression that contains the PropertyAssignment. + * @param property The PropertyAssignment node. + * @param receiver The receiver for the assignment. + */ + function transformPropertyAssignmentToExpression(property, receiver, startsOnNewLine) { + var expression = ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(property.name, visitor, ts.isPropertyName)), ts.visitNode(property.initializer, visitor, ts.isExpression)); + ts.setTextRange(expression, property); + if (startsOnNewLine) { + ts.startOnNewLine(expression); + } + return expression; + } + /** + * Transforms a ShorthandPropertyAssignment node into an expression. + * + * @param node The ObjectLiteralExpression that contains the ShorthandPropertyAssignment. + * @param property The ShorthandPropertyAssignment node. + * @param receiver The receiver for the assignment. + */ + function transformShorthandPropertyAssignmentToExpression(property, receiver, startsOnNewLine) { + var expression = ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(property.name, visitor, ts.isPropertyName)), ts.getSynthesizedClone(property.name)); + ts.setTextRange(expression, property); + if (startsOnNewLine) { + ts.startOnNewLine(expression); + } + return expression; + } + /** + * Transforms a MethodDeclaration of an ObjectLiteralExpression into an expression. + * + * @param node The ObjectLiteralExpression that contains the MethodDeclaration. + * @param method The MethodDeclaration node. + * @param receiver The receiver for the assignment. + */ + function transformObjectLiteralMethodDeclarationToExpression(method, receiver, container, startsOnNewLine) { + var ancestorFacts = enterSubtree(0 /* None */, 0 /* None */); + var expression = ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(method.name, visitor, ts.isPropertyName)), transformFunctionLikeToExpression(method, /*location*/ method, /*name*/ undefined, container)); + ts.setTextRange(expression, method); + if (startsOnNewLine) { + ts.startOnNewLine(expression); + } + exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, hierarchyFacts & 49152 /* PropagateNewTargetMask */ ? 16384 /* NewTarget */ : 0 /* None */); + return expression; + } + function visitCatchClause(node) { + var ancestorFacts = enterSubtree(4032 /* BlockScopeExcludes */, 0 /* BlockScopeIncludes */); + var updated; + ts.Debug.assert(!!node.variableDeclaration, "Catch clause variable should always be present when downleveling ES2015."); + if (ts.isBindingPattern(node.variableDeclaration.name)) { + var temp = ts.createTempVariable(/*recordTempVariable*/ undefined); + var newVariableDeclaration = ts.createVariableDeclaration(temp); + ts.setTextRange(newVariableDeclaration, node.variableDeclaration); + var vars = ts.flattenDestructuringBinding(node.variableDeclaration, visitor, context, 0 /* All */, temp); + var list = ts.createVariableDeclarationList(vars); + ts.setTextRange(list, node.variableDeclaration); + var destructure = ts.createVariableStatement(/*modifiers*/ undefined, list); + updated = ts.updateCatchClause(node, newVariableDeclaration, addStatementToStartOfBlock(node.block, destructure)); + } + else { + updated = ts.visitEachChild(node, visitor, context); + } + exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */); + return updated; + } + function addStatementToStartOfBlock(block, statement) { + var transformedStatements = ts.visitNodes(block.statements, visitor, ts.isStatement); + return ts.updateBlock(block, [statement].concat(transformedStatements)); + } + /** + * Visits a MethodDeclaration of an ObjectLiteralExpression and transforms it into a + * PropertyAssignment. + * + * @param node A MethodDeclaration node. + */ + function visitMethodDeclaration(node) { + // We should only get here for methods on an object literal with regular identifier names. + // Methods on classes are handled in visitClassDeclaration/visitClassExpression. + // Methods with computed property names are handled in visitObjectLiteralExpression. + ts.Debug.assert(!ts.isComputedPropertyName(node.name)); + var functionExpression = transformFunctionLikeToExpression(node, /*location*/ ts.moveRangePos(node, -1), /*name*/ undefined, /*container*/ undefined); + ts.setEmitFlags(functionExpression, 512 /* NoLeadingComments */ | ts.getEmitFlags(functionExpression)); + return ts.setTextRange(ts.createPropertyAssignment(node.name, functionExpression), + /*location*/ node); + } + /** + * Visits an AccessorDeclaration of an ObjectLiteralExpression. + * + * @param node An AccessorDeclaration node. + */ + function visitAccessorDeclaration(node) { + ts.Debug.assert(!ts.isComputedPropertyName(node.name)); + var savedConvertedLoopState = convertedLoopState; + convertedLoopState = undefined; + var ancestorFacts = enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */); + var updated; + var parameters = ts.visitParameterList(node.parameters, visitor, context); + var body = node.transformFlags & (16384 /* ContainsCapturedLexicalThis */ | 128 /* ContainsES2015 */) + ? transformFunctionBody(node) + : visitFunctionBodyDownLevel(node); + if (node.kind === 158 /* GetAccessor */) { + updated = ts.updateGetAccessor(node, node.decorators, node.modifiers, node.name, parameters, node.type, body); + } + else { + updated = ts.updateSetAccessor(node, node.decorators, node.modifiers, node.name, parameters, body); + } + exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, 0 /* None */); + convertedLoopState = savedConvertedLoopState; + return updated; + } + /** + * Visits a ShorthandPropertyAssignment and transforms it into a PropertyAssignment. + * + * @param node A ShorthandPropertyAssignment node. + */ + function visitShorthandPropertyAssignment(node) { + return ts.setTextRange(ts.createPropertyAssignment(node.name, ts.getSynthesizedClone(node.name)), + /*location*/ node); + } + function visitComputedPropertyName(node) { + var ancestorFacts = enterSubtree(0 /* ComputedPropertyNameExcludes */, 8192 /* ComputedPropertyNameIncludes */); + var updated = ts.visitEachChild(node, visitor, context); + exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, hierarchyFacts & 49152 /* PropagateNewTargetMask */ ? 32768 /* NewTargetInComputedPropertyName */ : 0 /* None */); + return updated; + } + /** + * Visits a YieldExpression node. + * + * @param node A YieldExpression node. + */ + function visitYieldExpression(node) { + // `yield` expressions are transformed using the generators transformer. + return ts.visitEachChild(node, visitor, context); + } + /** + * Visits an ArrayLiteralExpression that contains a spread element. + * + * @param node An ArrayLiteralExpression node. + */ + function visitArrayLiteralExpression(node) { + if (node.transformFlags & 64 /* ES2015 */) { + // We are here because we contain a SpreadElementExpression. + return transformAndSpreadElements(node.elements, /*needsUniqueCopy*/ true, !!node.multiLine, /*hasTrailingComma*/ !!node.elements.hasTrailingComma); + } + return ts.visitEachChild(node, visitor, context); + } + /** + * Visits a CallExpression that contains either a spread element or `super`. + * + * @param node a CallExpression. + */ + function visitCallExpression(node) { + if (ts.getEmitFlags(node) & 33554432 /* TypeScriptClassWrapper */) { + return visitTypeScriptClassWrapper(node); + } + if (node.transformFlags & 64 /* ES2015 */) { + return visitCallExpressionWithPotentialCapturedThisAssignment(node, /*assignToCapturedThis*/ true); + } + return ts.updateCall(node, ts.visitNode(node.expression, callExpressionVisitor, ts.isExpression), + /*typeArguments*/ undefined, ts.visitNodes(node.arguments, visitor, ts.isExpression)); + } + function visitTypeScriptClassWrapper(node) { + // This is a call to a class wrapper function (an IIFE) created by the 'ts' transformer. + // The wrapper has a form similar to: + // + // (function() { + // class C { // 1 + // } + // C.x = 1; // 2 + // return C; + // }()) + // + // When we transform the class, we end up with something like this: + // + // (function () { + // var C = (function () { // 3 + // function C() { + // } + // return C; // 4 + // }()); + // C.x = 1; + // return C; + // }()) + // + // We want to simplify the two nested IIFEs to end up with something like this: + // + // (function () { + // function C() { + // } + // C.x = 1; + // return C; + // }()) + // We skip any outer expressions in a number of places to get to the innermost + // expression, but we will restore them later to preserve comments and source maps. + var body = ts.cast(ts.cast(ts.skipOuterExpressions(node.expression), ts.isArrowFunction).body, ts.isBlock); + // The class statements are the statements generated by visiting the first statement with initializer of the + // body (1), while all other statements are added to remainingStatements (2) + var isVariableStatementWithInitializer = function (stmt) { return ts.isVariableStatement(stmt) && !!ts.first(stmt.declarationList.declarations).initializer; }; + var bodyStatements = ts.visitNodes(body.statements, visitor, ts.isStatement); + var classStatements = ts.filter(bodyStatements, isVariableStatementWithInitializer); + var remainingStatements = ts.filter(bodyStatements, function (stmt) { return !isVariableStatementWithInitializer(stmt); }); + var varStatement = ts.cast(ts.first(classStatements), ts.isVariableStatement); + // We know there is only one variable declaration here as we verified this in an + // earlier call to isTypeScriptClassWrapper + var variable = varStatement.declarationList.declarations[0]; + var initializer = ts.skipOuterExpressions(variable.initializer); + // Under certain conditions, the 'ts' transformer may introduce a class alias, which + // we see as an assignment, for example: + // + // (function () { + // var C_1; + // var C = C_1 = (function () { + // function C() { + // } + // C.x = function () { return C_1; } + // return C; + // }()); + // C = C_1 = __decorate([dec], C); + // return C; + // }()) + // + var aliasAssignment = ts.tryCast(initializer, ts.isAssignmentExpression); + // The underlying call (3) is another IIFE that may contain a '_super' argument. + var call = ts.cast(aliasAssignment ? ts.skipOuterExpressions(aliasAssignment.right) : initializer, ts.isCallExpression); + var func = ts.cast(ts.skipOuterExpressions(call.expression), ts.isFunctionExpression); + var funcStatements = func.body.statements; + var classBodyStart = 0; + var classBodyEnd = -1; + var statements = []; + if (aliasAssignment) { + // If we have a class alias assignment, we need to move it to the down-level constructor + // function we generated for the class. + var extendsCall = ts.tryCast(funcStatements[classBodyStart], ts.isExpressionStatement); + if (extendsCall) { + statements.push(extendsCall); + classBodyStart++; + } + // The next statement is the function declaration. + statements.push(funcStatements[classBodyStart]); + classBodyStart++; + // Add the class alias following the declaration. + statements.push(ts.createExpressionStatement(ts.createAssignment(aliasAssignment.left, ts.cast(variable.name, ts.isIdentifier)))); + } + // Find the trailing 'return' statement (4) + while (!ts.isReturnStatement(ts.elementAt(funcStatements, classBodyEnd))) { + classBodyEnd--; + } + // When we extract the statements of the inner IIFE, we exclude the 'return' statement (4) + // as we already have one that has been introduced by the 'ts' transformer. + ts.addRange(statements, funcStatements, classBodyStart, classBodyEnd); + if (classBodyEnd < -1) { + // If there were any hoisted declarations following the return statement, we should + // append them. + ts.addRange(statements, funcStatements, classBodyEnd + 1); + } + // Add the remaining statements of the outer wrapper. + ts.addRange(statements, remainingStatements); + // The 'es2015' class transform may add an end-of-declaration marker. If so we will add it + // after the remaining statements from the 'ts' transformer. + ts.addRange(statements, classStatements, /*start*/ 1); + // Recreate any outer parentheses or partially-emitted expressions to preserve source map + // and comment locations. + return ts.recreateOuterExpressions(node.expression, ts.recreateOuterExpressions(variable.initializer, ts.recreateOuterExpressions(aliasAssignment && aliasAssignment.right, ts.updateCall(call, ts.recreateOuterExpressions(call.expression, ts.updateFunctionExpression(func, + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, func.parameters, + /*type*/ undefined, ts.updateBlock(func.body, statements))), + /*typeArguments*/ undefined, call.arguments)))); + } + function visitImmediateSuperCallInBody(node) { + return visitCallExpressionWithPotentialCapturedThisAssignment(node, /*assignToCapturedThis*/ false); + } + function visitCallExpressionWithPotentialCapturedThisAssignment(node, assignToCapturedThis) { + // We are here either because SuperKeyword was used somewhere in the expression, or + // because we contain a SpreadElementExpression. + if (node.transformFlags & 131072 /* ContainsRestOrSpread */ || + node.expression.kind === 98 /* SuperKeyword */ || + ts.isSuperProperty(ts.skipOuterExpressions(node.expression))) { + var _a = ts.createCallBinding(node.expression, hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg; + if (node.expression.kind === 98 /* SuperKeyword */) { + ts.setEmitFlags(thisArg, 4 /* NoSubstitution */); + } + var resultingCall = void 0; + if (node.transformFlags & 131072 /* ContainsRestOrSpread */) { + // [source] + // f(...a, b) + // x.m(...a, b) + // super(...a, b) + // super.m(...a, b) // in static + // super.m(...a, b) // in instance + // + // [output] + // f.apply(void 0, a.concat([b])) + // (_a = x).m.apply(_a, a.concat([b])) + // _super.apply(this, a.concat([b])) + // _super.m.apply(this, a.concat([b])) + // _super.prototype.m.apply(this, a.concat([b])) + resultingCall = ts.createFunctionApply(ts.visitNode(target, callExpressionVisitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), transformAndSpreadElements(node.arguments, /*needsUniqueCopy*/ false, /*multiLine*/ false, /*hasTrailingComma*/ false)); + } + else { + // [source] + // super(a) + // super.m(a) // in static + // super.m(a) // in instance + // + // [output] + // _super.call(this, a) + // _super.m.call(this, a) + // _super.prototype.m.call(this, a) + resultingCall = ts.createFunctionCall(ts.visitNode(target, callExpressionVisitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), ts.visitNodes(node.arguments, visitor, ts.isExpression), + /*location*/ node); + } + if (node.expression.kind === 98 /* SuperKeyword */) { + var actualThis = ts.createThis(); + ts.setEmitFlags(actualThis, 4 /* NoSubstitution */); + var initializer = ts.createLogicalOr(resultingCall, actualThis); + resultingCall = assignToCapturedThis + ? ts.createAssignment(ts.createFileLevelUniqueName("_this"), initializer) + : initializer; + } + return ts.setOriginalNode(resultingCall, node); + } + return ts.visitEachChild(node, visitor, context); + } + /** + * Visits a NewExpression that contains a spread element. + * + * @param node A NewExpression node. + */ + function visitNewExpression(node) { + if (node.transformFlags & 131072 /* ContainsRestOrSpread */) { + // We are here because we contain a SpreadElementExpression. + // [source] + // new C(...a) + // + // [output] + // new ((_a = C).bind.apply(_a, [void 0].concat(a)))() + var _a = ts.createCallBinding(ts.createPropertyAccess(node.expression, "bind"), hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg; + return ts.createNew(ts.createFunctionApply(ts.visitNode(target, visitor, ts.isExpression), thisArg, transformAndSpreadElements(ts.createNodeArray([ts.createVoidZero()].concat(node.arguments)), /*needsUniqueCopy*/ false, /*multiLine*/ false, /*hasTrailingComma*/ false)), + /*typeArguments*/ undefined, []); + } + return ts.visitEachChild(node, visitor, context); + } + /** + * Transforms an array of Expression nodes that contains a SpreadExpression. + * + * @param elements The array of Expression nodes. + * @param needsUniqueCopy A value indicating whether to ensure that the result is a fresh array. + * @param multiLine A value indicating whether the result should be emitted on multiple lines. + */ + function transformAndSpreadElements(elements, needsUniqueCopy, multiLine, hasTrailingComma) { + // [source] + // [a, ...b, c] + // + // [output] + // [a].concat(b, [c]) + // Map spans of spread expressions into their expressions and spans of other + // expressions into an array literal. + var numElements = elements.length; + var segments = ts.flatten(ts.spanMap(elements, partitionSpread, function (partition, visitPartition, _start, end) { + return visitPartition(partition, multiLine, hasTrailingComma && end === numElements); + })); + if (compilerOptions.downlevelIteration) { + if (segments.length === 1) { + var firstSegment = segments[0]; + if (ts.isCallExpression(firstSegment) + && ts.isIdentifier(firstSegment.expression) + && (ts.getEmitFlags(firstSegment.expression) & 4096 /* HelperName */) + && firstSegment.expression.escapedText === "___spread") { + return segments[0]; + } + } + return ts.createSpreadHelper(context, segments); + } + else { + if (segments.length === 1) { + var firstElement = elements[0]; + return needsUniqueCopy && ts.isSpreadElement(firstElement) && firstElement.expression.kind !== 187 /* ArrayLiteralExpression */ + ? ts.createArraySlice(segments[0]) + : segments[0]; + } + // Rewrite using the pattern .concat(, , ...) + return ts.createArrayConcat(segments.shift(), segments); + } + } + function partitionSpread(node) { + return ts.isSpreadElement(node) + ? visitSpanOfSpreads + : visitSpanOfNonSpreads; + } + function visitSpanOfSpreads(chunk) { + return ts.map(chunk, visitExpressionOfSpread); + } + function visitSpanOfNonSpreads(chunk, multiLine, hasTrailingComma) { + return ts.createArrayLiteral(ts.visitNodes(ts.createNodeArray(chunk, hasTrailingComma), visitor, ts.isExpression), multiLine); + } + function visitSpreadElement(node) { + return ts.visitNode(node.expression, visitor, ts.isExpression); + } + /** + * Transforms the expression of a SpreadExpression node. + * + * @param node A SpreadExpression node. + */ + function visitExpressionOfSpread(node) { + return ts.visitNode(node.expression, visitor, ts.isExpression); + } + /** + * Visits a template literal. + * + * @param node A template literal. + */ + function visitTemplateLiteral(node) { + return ts.setTextRange(ts.createLiteral(node.text), node); + } + /** + * Visits a string literal with an extended unicode escape. + * + * @param node A string literal. + */ + function visitStringLiteral(node) { + if (node.hasExtendedUnicodeEscape) { + return ts.setTextRange(ts.createLiteral(node.text), node); + } + return node; + } + /** + * Visits a binary or octal (ES6) numeric literal. + * + * @param node A string literal. + */ + function visitNumericLiteral(node) { + if (node.numericLiteralFlags & 384 /* BinaryOrOctalSpecifier */) { + return ts.setTextRange(ts.createNumericLiteral(node.text), node); + } + return node; + } + /** + * Visits a TaggedTemplateExpression node. + * + * @param node A TaggedTemplateExpression node. + */ + function visitTaggedTemplateExpression(node) { + // Visit the tag expression + var tag = ts.visitNode(node.tag, visitor, ts.isExpression); + // Build up the template arguments and the raw and cooked strings for the template. + // We start out with 'undefined' for the first argument and revisit later + // to avoid walking over the template string twice and shifting all our arguments over after the fact. + var templateArguments = [undefined]; + var cookedStrings = []; + var rawStrings = []; + var template = node.template; + if (ts.isNoSubstitutionTemplateLiteral(template)) { + cookedStrings.push(ts.createLiteral(template.text)); + rawStrings.push(getRawLiteral(template)); + } + else { + cookedStrings.push(ts.createLiteral(template.head.text)); + rawStrings.push(getRawLiteral(template.head)); + for (var _i = 0, _a = template.templateSpans; _i < _a.length; _i++) { + var templateSpan = _a[_i]; + cookedStrings.push(ts.createLiteral(templateSpan.literal.text)); + rawStrings.push(getRawLiteral(templateSpan.literal)); + templateArguments.push(ts.visitNode(templateSpan.expression, visitor, ts.isExpression)); + } + } + var helperCall = createTemplateObjectHelper(context, ts.createArrayLiteral(cookedStrings), ts.createArrayLiteral(rawStrings)); + // Create a variable to cache the template object if we're in a module. + // Do not do this in the global scope, as any variable we currently generate could conflict with + // variables from outside of the current compilation. In the future, we can revisit this behavior. + if (ts.isExternalModule(currentSourceFile)) { + var tempVar = ts.createUniqueName("templateObject"); + recordTaggedTemplateString(tempVar); + templateArguments[0] = ts.createLogicalOr(tempVar, ts.createAssignment(tempVar, helperCall)); + } + else { + templateArguments[0] = helperCall; + } + return ts.createCall(tag, /*typeArguments*/ undefined, templateArguments); + } + /** + * Creates an ES5 compatible literal from an ES6 template literal. + * + * @param node The ES6 template literal. + */ + function getRawLiteral(node) { + // Find original source text, since we need to emit the raw strings of the tagged template. + // The raw strings contain the (escaped) strings of what the user wrote. + // Examples: `\n` is converted to "\\n", a template string with a newline to "\n". + var text = ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node); + // text contains the original source, it will also contain quotes ("`"), dolar signs and braces ("${" and "}"), + // thus we need to remove those characters. + // First template piece starts with "`", others with "}" + // Last template piece ends with "`", others with "${" + var isLast = node.kind === 14 /* NoSubstitutionTemplateLiteral */ || node.kind === 17 /* TemplateTail */; + text = text.substring(1, text.length - (isLast ? 1 : 2)); + // Newline normalization: + // ES6 Spec 11.8.6.1 - Static Semantics of TV's and TRV's + // and LineTerminatorSequences are normalized to for both TV and TRV. + text = text.replace(/\r\n?/g, "\n"); + return ts.setTextRange(ts.createLiteral(text), node); + } + /** + * Visits a TemplateExpression node. + * + * @param node A TemplateExpression node. + */ + function visitTemplateExpression(node) { + var expressions = []; + addTemplateHead(expressions, node); + addTemplateSpans(expressions, node); + // createAdd will check if each expression binds less closely than binary '+'. + // If it does, it wraps the expression in parentheses. Otherwise, something like + // `abc${ 1 << 2 }` + // becomes + // "abc" + 1 << 2 + "" + // which is really + // ("abc" + 1) << (2 + "") + // rather than + // "abc" + (1 << 2) + "" + var expression = ts.reduceLeft(expressions, ts.createAdd); + if (ts.nodeIsSynthesized(expression)) { + expression.pos = node.pos; + expression.end = node.end; + } + return expression; + } + /** + * Gets a value indicating whether we need to include the head of a TemplateExpression. + * + * @param node A TemplateExpression node. + */ + function shouldAddTemplateHead(node) { + // If this expression has an empty head literal and the first template span has a non-empty + // literal, then emitting the empty head literal is not necessary. + // `${ foo } and ${ bar }` + // can be emitted as + // foo + " and " + bar + // This is because it is only required that one of the first two operands in the emit + // output must be a string literal, so that the other operand and all following operands + // are forced into strings. + // + // If the first template span has an empty literal, then the head must still be emitted. + // `${ foo }${ bar }` + // must still be emitted as + // "" + foo + bar + // There is always atleast one templateSpan in this code path, since + // NoSubstitutionTemplateLiterals are directly emitted via emitLiteral() + ts.Debug.assert(node.templateSpans.length !== 0); + return node.head.text.length !== 0 || node.templateSpans[0].literal.text.length === 0; + } + /** + * Adds the head of a TemplateExpression to an array of expressions. + * + * @param expressions An array of expressions. + * @param node A TemplateExpression node. + */ + function addTemplateHead(expressions, node) { + if (!shouldAddTemplateHead(node)) { + return; + } + expressions.push(ts.createLiteral(node.head.text)); + } + /** + * Visits and adds the template spans of a TemplateExpression to an array of expressions. + * + * @param expressions An array of expressions. + * @param node A TemplateExpression node. + */ + function addTemplateSpans(expressions, node) { + for (var _i = 0, _a = node.templateSpans; _i < _a.length; _i++) { + var span = _a[_i]; + expressions.push(ts.visitNode(span.expression, visitor, ts.isExpression)); + // Only emit if the literal is non-empty. + // The binary '+' operator is left-associative, so the first string concatenation + // with the head will force the result up to this point to be a string. + // Emitting a '+ ""' has no semantic effect for middles and tails. + if (span.literal.text.length !== 0) { + expressions.push(ts.createLiteral(span.literal.text)); + } + } + } + /** + * Visits the `super` keyword + */ + function visitSuperKeyword(isExpressionOfCall) { + return hierarchyFacts & 8 /* NonStaticClassElement */ + && !isExpressionOfCall + ? ts.createPropertyAccess(ts.createFileLevelUniqueName("_super"), "prototype") + : ts.createFileLevelUniqueName("_super"); + } + function visitMetaProperty(node) { + if (node.keywordToken === 95 /* NewKeyword */ && node.name.escapedText === "target") { + if (hierarchyFacts & 8192 /* ComputedPropertyName */) { + hierarchyFacts |= 32768 /* NewTargetInComputedPropertyName */; + } + else { + hierarchyFacts |= 16384 /* NewTarget */; + } + return ts.createFileLevelUniqueName("_newTarget"); + } + return node; + } + /** + * Called by the printer just before a node is printed. + * + * @param hint A hint as to the intended usage of the node. + * @param node The node to be printed. + * @param emitCallback The callback used to emit the node. + */ + function onEmitNode(hint, node, emitCallback) { + if (enabledSubstitutions & 1 /* CapturedThis */ && ts.isFunctionLike(node)) { + // If we are tracking a captured `this`, keep track of the enclosing function. + var ancestorFacts = enterSubtree(16286 /* FunctionExcludes */, ts.getEmitFlags(node) & 8 /* CapturesThis */ + ? 65 /* FunctionIncludes */ | 16 /* CapturesThis */ + : 65 /* FunctionIncludes */); + previousOnEmitNode(hint, node, emitCallback); + exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */); + return; + } + previousOnEmitNode(hint, node, emitCallback); + } + /** + * Enables a more costly code path for substitutions when we determine a source file + * contains block-scoped bindings (e.g. `let` or `const`). + */ + function enableSubstitutionsForBlockScopedBindings() { + if ((enabledSubstitutions & 2 /* BlockScopedBindings */) === 0) { + enabledSubstitutions |= 2 /* BlockScopedBindings */; + context.enableSubstitution(72 /* Identifier */); + } + } + /** + * Enables a more costly code path for substitutions when we determine a source file + * contains a captured `this`. + */ + function enableSubstitutionsForCapturedThis() { + if ((enabledSubstitutions & 1 /* CapturedThis */) === 0) { + enabledSubstitutions |= 1 /* CapturedThis */; + context.enableSubstitution(100 /* ThisKeyword */); + context.enableEmitNotification(157 /* Constructor */); + context.enableEmitNotification(156 /* MethodDeclaration */); + context.enableEmitNotification(158 /* GetAccessor */); + context.enableEmitNotification(159 /* SetAccessor */); + context.enableEmitNotification(197 /* ArrowFunction */); + context.enableEmitNotification(196 /* FunctionExpression */); + context.enableEmitNotification(239 /* FunctionDeclaration */); + } + } + /** + * Hooks node substitutions. + * + * @param hint The context for the emitter. + * @param node The node to substitute. + */ + function onSubstituteNode(hint, node) { + node = previousOnSubstituteNode(hint, node); + if (hint === 1 /* Expression */) { + return substituteExpression(node); + } + if (ts.isIdentifier(node)) { + return substituteIdentifier(node); + } + return node; + } + /** + * Hooks substitutions for non-expression identifiers. + */ + function substituteIdentifier(node) { + // Only substitute the identifier if we have enabled substitutions for block-scoped + // bindings. + if (enabledSubstitutions & 2 /* BlockScopedBindings */ && !ts.isInternalName(node)) { + var original = ts.getParseTreeNode(node, ts.isIdentifier); + if (original && isNameOfDeclarationWithCollidingName(original)) { + return ts.setTextRange(ts.getGeneratedNameForNode(original), node); + } + } + return node; + } + /** + * Determines whether a name is the name of a declaration with a colliding name. + * NOTE: This function expects to be called with an original source tree node. + * + * @param node An original source tree node. + */ + function isNameOfDeclarationWithCollidingName(node) { + switch (node.parent.kind) { + case 186 /* BindingElement */: + case 240 /* ClassDeclaration */: + case 243 /* EnumDeclaration */: + case 237 /* VariableDeclaration */: + return node.parent.name === node + && resolver.isDeclarationWithCollidingName(node.parent); + } + return false; + } + /** + * Substitutes an expression. + * + * @param node An Expression node. + */ + function substituteExpression(node) { + switch (node.kind) { + case 72 /* Identifier */: + return substituteExpressionIdentifier(node); + case 100 /* ThisKeyword */: + return substituteThisKeyword(node); + } + return node; + } + /** + * Substitutes an expression identifier. + * + * @param node An Identifier node. + */ + function substituteExpressionIdentifier(node) { + if (enabledSubstitutions & 2 /* BlockScopedBindings */ && !ts.isInternalName(node)) { + var declaration = resolver.getReferencedDeclarationWithCollidingName(node); + if (declaration && !(ts.isClassLike(declaration) && isPartOfClassBody(declaration, node))) { + return ts.setTextRange(ts.getGeneratedNameForNode(ts.getNameOfDeclaration(declaration)), node); + } + } + return node; + } + function isPartOfClassBody(declaration, node) { + var currentNode = ts.getParseTreeNode(node); + if (!currentNode || currentNode === declaration || currentNode.end <= declaration.pos || currentNode.pos >= declaration.end) { + // if the node has no correlation to a parse tree node, its definitely not + // part of the body. + // if the node is outside of the document range of the declaration, its + // definitely not part of the body. + return false; + } + var blockScope = ts.getEnclosingBlockScopeContainer(declaration); + while (currentNode) { + if (currentNode === blockScope || currentNode === declaration) { + // if we are in the enclosing block scope of the declaration, we are definitely + // not inside the class body. + return false; + } + if (ts.isClassElement(currentNode) && currentNode.parent === declaration) { + return true; + } + currentNode = currentNode.parent; + } + return false; + } + /** + * Substitutes `this` when contained within an arrow function. + * + * @param node The ThisKeyword node. + */ + function substituteThisKeyword(node) { + if (enabledSubstitutions & 1 /* CapturedThis */ + && hierarchyFacts & 16 /* CapturesThis */) { + return ts.setTextRange(ts.createFileLevelUniqueName("_this"), node); + } + return node; + } + function getClassMemberPrefix(node, member) { + return ts.hasModifier(member, 32 /* Static */) + ? ts.getInternalName(node) + : ts.createPropertyAccess(ts.getInternalName(node), "prototype"); + } + function hasSynthesizedDefaultSuperCall(constructor, hasExtendsClause) { + if (!constructor || !hasExtendsClause) { + return false; + } + if (ts.some(constructor.parameters)) { + return false; + } + var statement = ts.firstOrUndefined(constructor.body.statements); + if (!statement || !ts.nodeIsSynthesized(statement) || statement.kind !== 221 /* ExpressionStatement */) { + return false; + } + var statementExpression = statement.expression; + if (!ts.nodeIsSynthesized(statementExpression) || statementExpression.kind !== 191 /* CallExpression */) { + return false; + } + var callTarget = statementExpression.expression; + if (!ts.nodeIsSynthesized(callTarget) || callTarget.kind !== 98 /* SuperKeyword */) { + return false; + } + var callArgument = ts.singleOrUndefined(statementExpression.arguments); + if (!callArgument || !ts.nodeIsSynthesized(callArgument) || callArgument.kind !== 208 /* SpreadElement */) { + return false; + } + var expression = callArgument.expression; + return ts.isIdentifier(expression) && expression.escapedText === "arguments"; + } + } + ts.transformES2015 = transformES2015; + function createExtendsHelper(context, name) { + context.requestEmitHelper(extendsHelper); + return ts.createCall(ts.getHelperName("__extends"), + /*typeArguments*/ undefined, [ + name, + ts.createFileLevelUniqueName("_super") + ]); + } + function createTemplateObjectHelper(context, cooked, raw) { + context.requestEmitHelper(templateObjectHelper); + return ts.createCall(ts.getHelperName("__makeTemplateObject"), + /*typeArguments*/ undefined, [ + cooked, + raw + ]); + } + var extendsHelper = { + name: "typescript:extends", + scoped: false, + priority: 0, + text: "\n var __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return extendStatics(d, b);\n };\n\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n })();" + }; + var templateObjectHelper = { + name: "typescript:makeTemplateObject", + scoped: false, + priority: 0, + text: "\n var __makeTemplateObject = (this && this.__makeTemplateObject) || function (cooked, raw) {\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\n return cooked;\n };" + }; +})(ts || (ts = {})); +/*@internal*/ +var ts; +(function (ts) { + /** + * Transforms ES5 syntax into ES3 syntax. + * + * @param context Context and state information for the transformation. + */ + function transformES5(context) { + var compilerOptions = context.getCompilerOptions(); + // enable emit notification only if using --jsx preserve or react-native + var previousOnEmitNode; + var noSubstitution; + if (compilerOptions.jsx === 1 /* Preserve */ || compilerOptions.jsx === 3 /* ReactNative */) { + previousOnEmitNode = context.onEmitNode; + context.onEmitNode = onEmitNode; + context.enableEmitNotification(262 /* JsxOpeningElement */); + context.enableEmitNotification(263 /* JsxClosingElement */); + context.enableEmitNotification(261 /* JsxSelfClosingElement */); + noSubstitution = []; + } + var previousOnSubstituteNode = context.onSubstituteNode; + context.onSubstituteNode = onSubstituteNode; + context.enableSubstitution(189 /* PropertyAccessExpression */); + context.enableSubstitution(275 /* PropertyAssignment */); + return ts.chainBundle(transformSourceFile); + /** + * Transforms an ES5 source file to ES3. + * + * @param node A SourceFile + */ + function transformSourceFile(node) { + return node; + } + /** + * Called by the printer just before a node is printed. + * + * @param hint A hint as to the intended usage of the node. + * @param node The node to emit. + * @param emitCallback A callback used to emit the node. + */ + function onEmitNode(hint, node, emitCallback) { + switch (node.kind) { + case 262 /* JsxOpeningElement */: + case 263 /* JsxClosingElement */: + case 261 /* JsxSelfClosingElement */: + var tagName = node.tagName; + noSubstitution[ts.getOriginalNodeId(tagName)] = true; + break; + } + previousOnEmitNode(hint, node, emitCallback); + } + /** + * Hooks node substitutions. + * + * @param hint A hint as to the intended usage of the node. + * @param node The node to substitute. + */ + function onSubstituteNode(hint, node) { + if (node.id && noSubstitution && noSubstitution[node.id]) { + return previousOnSubstituteNode(hint, node); + } + node = previousOnSubstituteNode(hint, node); + if (ts.isPropertyAccessExpression(node)) { + return substitutePropertyAccessExpression(node); + } + else if (ts.isPropertyAssignment(node)) { + return substitutePropertyAssignment(node); + } + return node; + } + /** + * Substitutes a PropertyAccessExpression whose name is a reserved word. + * + * @param node A PropertyAccessExpression + */ + function substitutePropertyAccessExpression(node) { + var literalName = trySubstituteReservedName(node.name); + if (literalName) { + return ts.setTextRange(ts.createElementAccess(node.expression, literalName), node); + } + return node; + } + /** + * Substitutes a PropertyAssignment whose name is a reserved word. + * + * @param node A PropertyAssignment + */ + function substitutePropertyAssignment(node) { + var literalName = ts.isIdentifier(node.name) && trySubstituteReservedName(node.name); + if (literalName) { + return ts.updatePropertyAssignment(node, literalName, node.initializer); + } + return node; + } + /** + * If an identifier name is a reserved word, returns a string literal for the name. + * + * @param name An Identifier + */ + function trySubstituteReservedName(name) { + var token = name.originalKeywordKind || (ts.nodeIsSynthesized(name) ? ts.stringToToken(ts.idText(name)) : undefined); + if (token !== undefined && token >= 73 /* FirstReservedWord */ && token <= 108 /* LastReservedWord */) { + return ts.setTextRange(ts.createLiteral(name), name); + } + return undefined; + } + } + ts.transformES5 = transformES5; +})(ts || (ts = {})); +// Transforms generator functions into a compatible ES5 representation with similar runtime +// semantics. This is accomplished by first transforming the body of each generator +// function into an intermediate representation that is the compiled into a JavaScript +// switch statement. +// +// Many functions in this transformer will contain comments indicating the expected +// intermediate representation. For illustrative purposes, the following intermediate +// language is used to define this intermediate representation: +// +// .nop - Performs no operation. +// .local NAME, ... - Define local variable declarations. +// .mark LABEL - Mark the location of a label. +// .br LABEL - Jump to a label. If jumping out of a protected +// region, all .finally blocks are executed. +// .brtrue LABEL, (x) - Jump to a label IIF the expression `x` is truthy. +// If jumping out of a protected region, all .finally +// blocks are executed. +// .brfalse LABEL, (x) - Jump to a label IIF the expression `x` is falsey. +// If jumping out of a protected region, all .finally +// blocks are executed. +// .yield (x) - Yield the value of the optional expression `x`. +// Resume at the next label. +// .yieldstar (x) - Delegate yield to the value of the optional +// expression `x`. Resume at the next label. +// NOTE: `x` must be an Iterator, not an Iterable. +// .loop CONTINUE, BREAK - Marks the beginning of a loop. Any "continue" or +// "break" abrupt completions jump to the CONTINUE or +// BREAK labels, respectively. +// .endloop - Marks the end of a loop. +// .with (x) - Marks the beginning of a WithStatement block, using +// the supplied expression. +// .endwith - Marks the end of a WithStatement. +// .switch - Marks the beginning of a SwitchStatement. +// .endswitch - Marks the end of a SwitchStatement. +// .labeled NAME - Marks the beginning of a LabeledStatement with the +// supplied name. +// .endlabeled - Marks the end of a LabeledStatement. +// .try TRY, CATCH, FINALLY, END - Marks the beginning of a protected region, and the +// labels for each block. +// .catch (x) - Marks the beginning of a catch block. +// .finally - Marks the beginning of a finally block. +// .endfinally - Marks the end of a finally block. +// .endtry - Marks the end of a protected region. +// .throw (x) - Throws the value of the expression `x`. +// .return (x) - Returns the value of the expression `x`. +// +// In addition, the illustrative intermediate representation introduces some special +// variables: +// +// %sent% - Either returns the next value sent to the generator, +// returns the result of a delegated yield, or throws +// the exception sent to the generator. +// %error% - Returns the value of the current exception in a +// catch block. +// +// This intermediate representation is then compiled into JavaScript syntax. The resulting +// compilation output looks something like the following: +// +// function f() { +// var /*locals*/; +// /*functions*/ +// return __generator(function (state) { +// switch (state.label) { +// /*cases per label*/ +// } +// }); +// } +// +// Each of the above instructions corresponds to JavaScript emit similar to the following: +// +// .local NAME | var NAME; +// -------------------------------|---------------------------------------------- +// .mark LABEL | case LABEL: +// -------------------------------|---------------------------------------------- +// .br LABEL | return [3 /*break*/, LABEL]; +// -------------------------------|---------------------------------------------- +// .brtrue LABEL, (x) | if (x) return [3 /*break*/, LABEL]; +// -------------------------------|---------------------------------------------- +// .brfalse LABEL, (x) | if (!(x)) return [3, /*break*/, LABEL]; +// -------------------------------|---------------------------------------------- +// .yield (x) | return [4 /*yield*/, x]; +// .mark RESUME | case RESUME: +// a = %sent%; | a = state.sent(); +// -------------------------------|---------------------------------------------- +// .yieldstar (x) | return [5 /*yield**/, x]; +// .mark RESUME | case RESUME: +// a = %sent%; | a = state.sent(); +// -------------------------------|---------------------------------------------- +// .with (_a) | with (_a) { +// a(); | a(); +// | } +// | state.label = LABEL; +// .mark LABEL | case LABEL: +// | with (_a) { +// b(); | b(); +// | } +// .endwith | +// -------------------------------|---------------------------------------------- +// | case 0: +// | state.trys = []; +// | ... +// .try TRY, CATCH, FINALLY, END | +// .mark TRY | case TRY: +// | state.trys.push([TRY, CATCH, FINALLY, END]); +// .nop | +// a(); | a(); +// .br END | return [3 /*break*/, END]; +// .catch (e) | +// .mark CATCH | case CATCH: +// | e = state.sent(); +// b(); | b(); +// .br END | return [3 /*break*/, END]; +// .finally | +// .mark FINALLY | case FINALLY: +// c(); | c(); +// .endfinally | return [7 /*endfinally*/]; +// .endtry | +// .mark END | case END: +/*@internal*/ +var ts; +(function (ts) { + var OpCode; + (function (OpCode) { + OpCode[OpCode["Nop"] = 0] = "Nop"; + OpCode[OpCode["Statement"] = 1] = "Statement"; + OpCode[OpCode["Assign"] = 2] = "Assign"; + OpCode[OpCode["Break"] = 3] = "Break"; + OpCode[OpCode["BreakWhenTrue"] = 4] = "BreakWhenTrue"; + OpCode[OpCode["BreakWhenFalse"] = 5] = "BreakWhenFalse"; + OpCode[OpCode["Yield"] = 6] = "Yield"; + OpCode[OpCode["YieldStar"] = 7] = "YieldStar"; + OpCode[OpCode["Return"] = 8] = "Return"; + OpCode[OpCode["Throw"] = 9] = "Throw"; + OpCode[OpCode["Endfinally"] = 10] = "Endfinally"; // Marks the end of a `finally` block + })(OpCode || (OpCode = {})); + // whether a generated code block is opening or closing at the current operation for a FunctionBuilder + var BlockAction; + (function (BlockAction) { + BlockAction[BlockAction["Open"] = 0] = "Open"; + BlockAction[BlockAction["Close"] = 1] = "Close"; + })(BlockAction || (BlockAction = {})); + // the kind for a generated code block in a FunctionBuilder + var CodeBlockKind; + (function (CodeBlockKind) { + CodeBlockKind[CodeBlockKind["Exception"] = 0] = "Exception"; + CodeBlockKind[CodeBlockKind["With"] = 1] = "With"; + CodeBlockKind[CodeBlockKind["Switch"] = 2] = "Switch"; + CodeBlockKind[CodeBlockKind["Loop"] = 3] = "Loop"; + CodeBlockKind[CodeBlockKind["Labeled"] = 4] = "Labeled"; + })(CodeBlockKind || (CodeBlockKind = {})); + // the state for a generated code exception block + var ExceptionBlockState; + (function (ExceptionBlockState) { + ExceptionBlockState[ExceptionBlockState["Try"] = 0] = "Try"; + ExceptionBlockState[ExceptionBlockState["Catch"] = 1] = "Catch"; + ExceptionBlockState[ExceptionBlockState["Finally"] = 2] = "Finally"; + ExceptionBlockState[ExceptionBlockState["Done"] = 3] = "Done"; + })(ExceptionBlockState || (ExceptionBlockState = {})); + // NOTE: changes to this enum should be reflected in the __generator helper. + var Instruction; + (function (Instruction) { + Instruction[Instruction["Next"] = 0] = "Next"; + Instruction[Instruction["Throw"] = 1] = "Throw"; + Instruction[Instruction["Return"] = 2] = "Return"; + Instruction[Instruction["Break"] = 3] = "Break"; + Instruction[Instruction["Yield"] = 4] = "Yield"; + Instruction[Instruction["YieldStar"] = 5] = "YieldStar"; + Instruction[Instruction["Catch"] = 6] = "Catch"; + Instruction[Instruction["Endfinally"] = 7] = "Endfinally"; + })(Instruction || (Instruction = {})); + function getInstructionName(instruction) { + switch (instruction) { + case 2 /* Return */: return "return"; + case 3 /* Break */: return "break"; + case 4 /* Yield */: return "yield"; + case 5 /* YieldStar */: return "yield*"; + case 7 /* Endfinally */: return "endfinally"; + default: return undefined; // TODO: GH#18217 + } + } + function transformGenerators(context) { + var resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistFunctionDeclaration = context.hoistFunctionDeclaration, hoistVariableDeclaration = context.hoistVariableDeclaration; + var compilerOptions = context.getCompilerOptions(); + var languageVersion = ts.getEmitScriptTarget(compilerOptions); + var resolver = context.getEmitResolver(); + var previousOnSubstituteNode = context.onSubstituteNode; + context.onSubstituteNode = onSubstituteNode; + var renamedCatchVariables; + var renamedCatchVariableDeclarations; + var inGeneratorFunctionBody; + var inStatementContainingYield; + // The following three arrays store information about generated code blocks. + // All three arrays are correlated by their index. This approach is used over allocating + // objects to store the same information to avoid GC overhead. + // + var blocks; // Information about the code block + var blockOffsets; // The operation offset at which a code block begins or ends + var blockActions; // Whether the code block is opened or closed + var blockStack; // A stack of currently open code blocks + // Labels are used to mark locations in the code that can be the target of a Break (jump) + // operation. These are translated into case clauses in a switch statement. + // The following two arrays are correlated by their index. This approach is used over + // allocating objects to store the same information to avoid GC overhead. + // + var labelOffsets; // The operation offset at which the label is defined. + var labelExpressions; // The NumericLiteral nodes bound to each label. + var nextLabelId = 1; // The next label id to use. + // Operations store information about generated code for the function body. This + // Includes things like statements, assignments, breaks (jumps), and yields. + // The following three arrays are correlated by their index. This approach is used over + // allocating objects to store the same information to avoid GC overhead. + // + var operations; // The operation to perform. + var operationArguments; // The arguments to the operation. + var operationLocations; // The source map location for the operation. + var state; // The name of the state object used by the generator at runtime. + // The following variables store information used by the `build` function: + // + var blockIndex = 0; // The index of the current block. + var labelNumber = 0; // The current label number. + var labelNumbers; + var lastOperationWasAbrupt; // Indicates whether the last operation was abrupt (break/continue). + var lastOperationWasCompletion; // Indicates whether the last operation was a completion (return/throw). + var clauses; // The case clauses generated for labels. + var statements; // The statements for the current label. + var exceptionBlockStack; // A stack of containing exception blocks. + var currentExceptionBlock; // The current exception block. + var withBlockStack; // A stack containing `with` blocks. + return ts.chainBundle(transformSourceFile); + function transformSourceFile(node) { + if (node.isDeclarationFile || (node.transformFlags & 512 /* ContainsGenerator */) === 0) { + return node; + } + var visited = ts.visitEachChild(node, visitor, context); + ts.addEmitHelpers(visited, context.readEmitHelpers()); + return visited; + } + /** + * Visits a node. + * + * @param node The node to visit. + */ + function visitor(node) { + var transformFlags = node.transformFlags; + if (inStatementContainingYield) { + return visitJavaScriptInStatementContainingYield(node); + } + else if (inGeneratorFunctionBody) { + return visitJavaScriptInGeneratorFunctionBody(node); + } + else if (transformFlags & 256 /* Generator */) { + return visitGenerator(node); + } + else if (transformFlags & 512 /* ContainsGenerator */) { + return ts.visitEachChild(node, visitor, context); + } + else { + return node; + } + } + /** + * Visits a node that is contained within a statement that contains yield. + * + * @param node The node to visit. + */ + function visitJavaScriptInStatementContainingYield(node) { + switch (node.kind) { + case 223 /* DoStatement */: + return visitDoStatement(node); + case 224 /* WhileStatement */: + return visitWhileStatement(node); + case 232 /* SwitchStatement */: + return visitSwitchStatement(node); + case 233 /* LabeledStatement */: + return visitLabeledStatement(node); + default: + return visitJavaScriptInGeneratorFunctionBody(node); + } + } + /** + * Visits a node that is contained within a generator function. + * + * @param node The node to visit. + */ + function visitJavaScriptInGeneratorFunctionBody(node) { + switch (node.kind) { + case 239 /* FunctionDeclaration */: + return visitFunctionDeclaration(node); + case 196 /* FunctionExpression */: + return visitFunctionExpression(node); + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + return visitAccessorDeclaration(node); + case 219 /* VariableStatement */: + return visitVariableStatement(node); + case 225 /* ForStatement */: + return visitForStatement(node); + case 226 /* ForInStatement */: + return visitForInStatement(node); + case 229 /* BreakStatement */: + return visitBreakStatement(node); + case 228 /* ContinueStatement */: + return visitContinueStatement(node); + case 230 /* ReturnStatement */: + return visitReturnStatement(node); + default: + if (node.transformFlags & 4194304 /* ContainsYield */) { + return visitJavaScriptContainingYield(node); + } + else if (node.transformFlags & (512 /* ContainsGenerator */ | 8388608 /* ContainsHoistedDeclarationOrCompletion */)) { + return ts.visitEachChild(node, visitor, context); + } + else { + return node; + } + } + } + /** + * Visits a node that contains a YieldExpression. + * + * @param node The node to visit. + */ + function visitJavaScriptContainingYield(node) { + switch (node.kind) { + case 204 /* BinaryExpression */: + return visitBinaryExpression(node); + case 205 /* ConditionalExpression */: + return visitConditionalExpression(node); + case 207 /* YieldExpression */: + return visitYieldExpression(node); + case 187 /* ArrayLiteralExpression */: + return visitArrayLiteralExpression(node); + case 188 /* ObjectLiteralExpression */: + return visitObjectLiteralExpression(node); + case 190 /* ElementAccessExpression */: + return visitElementAccessExpression(node); + case 191 /* CallExpression */: + return visitCallExpression(node); + case 192 /* NewExpression */: + return visitNewExpression(node); + default: + return ts.visitEachChild(node, visitor, context); + } + } + /** + * Visits a generator function. + * + * @param node The node to visit. + */ + function visitGenerator(node) { + switch (node.kind) { + case 239 /* FunctionDeclaration */: + return visitFunctionDeclaration(node); + case 196 /* FunctionExpression */: + return visitFunctionExpression(node); + default: + return ts.Debug.failBadSyntaxKind(node); + } + } + /** + * Visits a function declaration. + * + * This will be called when one of the following conditions are met: + * - The function declaration is a generator function. + * - The function declaration is contained within the body of a generator function. + * + * @param node The node to visit. + */ + function visitFunctionDeclaration(node) { + // Currently, we only support generators that were originally async functions. + if (node.asteriskToken) { + node = ts.setOriginalNode(ts.setTextRange(ts.createFunctionDeclaration( + /*decorators*/ undefined, node.modifiers, + /*asteriskToken*/ undefined, node.name, + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, transformGeneratorFunctionBody(node.body)), + /*location*/ node), node); + } + else { + var savedInGeneratorFunctionBody = inGeneratorFunctionBody; + var savedInStatementContainingYield = inStatementContainingYield; + inGeneratorFunctionBody = false; + inStatementContainingYield = false; + node = ts.visitEachChild(node, visitor, context); + inGeneratorFunctionBody = savedInGeneratorFunctionBody; + inStatementContainingYield = savedInStatementContainingYield; + } + if (inGeneratorFunctionBody) { + // Function declarations in a generator function body are hoisted + // to the top of the lexical scope and elided from the current statement. + hoistFunctionDeclaration(node); + return undefined; + } + else { + return node; + } + } + /** + * Visits a function expression. + * + * This will be called when one of the following conditions are met: + * - The function expression is a generator function. + * - The function expression is contained within the body of a generator function. + * + * @param node The node to visit. + */ + function visitFunctionExpression(node) { + // Currently, we only support generators that were originally async functions. + if (node.asteriskToken) { + node = ts.setOriginalNode(ts.setTextRange(ts.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, node.name, + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, transformGeneratorFunctionBody(node.body)), + /*location*/ node), node); + } + else { + var savedInGeneratorFunctionBody = inGeneratorFunctionBody; + var savedInStatementContainingYield = inStatementContainingYield; + inGeneratorFunctionBody = false; + inStatementContainingYield = false; + node = ts.visitEachChild(node, visitor, context); + inGeneratorFunctionBody = savedInGeneratorFunctionBody; + inStatementContainingYield = savedInStatementContainingYield; + } + return node; + } + /** + * Visits a get or set accessor declaration. + * + * This will be called when one of the following conditions are met: + * - The accessor is contained within the body of a generator function. + * + * @param node The node to visit. + */ + function visitAccessorDeclaration(node) { + var savedInGeneratorFunctionBody = inGeneratorFunctionBody; + var savedInStatementContainingYield = inStatementContainingYield; + inGeneratorFunctionBody = false; + inStatementContainingYield = false; + node = ts.visitEachChild(node, visitor, context); + inGeneratorFunctionBody = savedInGeneratorFunctionBody; + inStatementContainingYield = savedInStatementContainingYield; + return node; + } + /** + * Transforms the body of a generator function declaration. + * + * @param node The function body to transform. + */ + function transformGeneratorFunctionBody(body) { + // Save existing generator state + var statements = []; + var savedInGeneratorFunctionBody = inGeneratorFunctionBody; + var savedInStatementContainingYield = inStatementContainingYield; + var savedBlocks = blocks; + var savedBlockOffsets = blockOffsets; + var savedBlockActions = blockActions; + var savedBlockStack = blockStack; + var savedLabelOffsets = labelOffsets; + var savedLabelExpressions = labelExpressions; + var savedNextLabelId = nextLabelId; + var savedOperations = operations; + var savedOperationArguments = operationArguments; + var savedOperationLocations = operationLocations; + var savedState = state; + // Initialize generator state + inGeneratorFunctionBody = true; + inStatementContainingYield = false; + blocks = undefined; + blockOffsets = undefined; + blockActions = undefined; + blockStack = undefined; + labelOffsets = undefined; + labelExpressions = undefined; + nextLabelId = 1; + operations = undefined; + operationArguments = undefined; + operationLocations = undefined; + state = ts.createTempVariable(/*recordTempVariable*/ undefined); + // Build the generator + resumeLexicalEnvironment(); + var statementOffset = ts.addPrologue(statements, body.statements, /*ensureUseStrict*/ false, visitor); + transformAndEmitStatements(body.statements, statementOffset); + var buildResult = build(); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + statements.push(ts.createReturn(buildResult)); + // Restore previous generator state + inGeneratorFunctionBody = savedInGeneratorFunctionBody; + inStatementContainingYield = savedInStatementContainingYield; + blocks = savedBlocks; + blockOffsets = savedBlockOffsets; + blockActions = savedBlockActions; + blockStack = savedBlockStack; + labelOffsets = savedLabelOffsets; + labelExpressions = savedLabelExpressions; + nextLabelId = savedNextLabelId; + operations = savedOperations; + operationArguments = savedOperationArguments; + operationLocations = savedOperationLocations; + state = savedState; + return ts.setTextRange(ts.createBlock(statements, body.multiLine), body); + } + /** + * Visits a variable statement. + * + * This will be called when one of the following conditions are met: + * - The variable statement is contained within the body of a generator function. + * + * @param node The node to visit. + */ + function visitVariableStatement(node) { + if (node.transformFlags & 4194304 /* ContainsYield */) { + transformAndEmitVariableDeclarationList(node.declarationList); + return undefined; + } + else { + // Do not hoist custom prologues. + if (ts.getEmitFlags(node) & 1048576 /* CustomPrologue */) { + return node; + } + for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { + var variable = _a[_i]; + hoistVariableDeclaration(variable.name); + } + var variables = ts.getInitializedVariables(node.declarationList); + if (variables.length === 0) { + return undefined; + } + return ts.setSourceMapRange(ts.createExpressionStatement(ts.inlineExpressions(ts.map(variables, transformInitializedVariable))), node); + } + } + /** + * Visits a binary expression. + * + * This will be called when one of the following conditions are met: + * - The node contains a YieldExpression. + * + * @param node The node to visit. + */ + function visitBinaryExpression(node) { + var assoc = ts.getExpressionAssociativity(node); + switch (assoc) { + case 0 /* Left */: + return visitLeftAssociativeBinaryExpression(node); + case 1 /* Right */: + return visitRightAssociativeBinaryExpression(node); + default: + return ts.Debug.assertNever(assoc); + } + } + function isCompoundAssignment(kind) { + return kind >= 60 /* FirstCompoundAssignment */ + && kind <= 71 /* LastCompoundAssignment */; + } + function getOperatorForCompoundAssignment(kind) { + switch (kind) { + case 60 /* PlusEqualsToken */: return 38 /* PlusToken */; + case 61 /* MinusEqualsToken */: return 39 /* MinusToken */; + case 62 /* AsteriskEqualsToken */: return 40 /* AsteriskToken */; + case 63 /* AsteriskAsteriskEqualsToken */: return 41 /* AsteriskAsteriskToken */; + case 64 /* SlashEqualsToken */: return 42 /* SlashToken */; + case 65 /* PercentEqualsToken */: return 43 /* PercentToken */; + case 66 /* LessThanLessThanEqualsToken */: return 46 /* LessThanLessThanToken */; + case 67 /* GreaterThanGreaterThanEqualsToken */: return 47 /* GreaterThanGreaterThanToken */; + case 68 /* GreaterThanGreaterThanGreaterThanEqualsToken */: return 48 /* GreaterThanGreaterThanGreaterThanToken */; + case 69 /* AmpersandEqualsToken */: return 49 /* AmpersandToken */; + case 70 /* BarEqualsToken */: return 50 /* BarToken */; + case 71 /* CaretEqualsToken */: return 51 /* CaretToken */; + } + } + /** + * Visits a right-associative binary expression containing `yield`. + * + * @param node The node to visit. + */ + function visitRightAssociativeBinaryExpression(node) { + var left = node.left, right = node.right; + if (containsYield(right)) { + var target = void 0; + switch (left.kind) { + case 189 /* PropertyAccessExpression */: + // [source] + // a.b = yield; + // + // [intermediate] + // .local _a + // _a = a; + // .yield resumeLabel + // .mark resumeLabel + // _a.b = %sent%; + target = ts.updatePropertyAccess(left, cacheExpression(ts.visitNode(left.expression, visitor, ts.isLeftHandSideExpression)), left.name); + break; + case 190 /* ElementAccessExpression */: + // [source] + // a[b] = yield; + // + // [intermediate] + // .local _a, _b + // _a = a; + // _b = b; + // .yield resumeLabel + // .mark resumeLabel + // _a[_b] = %sent%; + target = ts.updateElementAccess(left, cacheExpression(ts.visitNode(left.expression, visitor, ts.isLeftHandSideExpression)), cacheExpression(ts.visitNode(left.argumentExpression, visitor, ts.isExpression))); + break; + default: + target = ts.visitNode(left, visitor, ts.isExpression); + break; + } + var operator = node.operatorToken.kind; + if (isCompoundAssignment(operator)) { + return ts.setTextRange(ts.createAssignment(target, ts.setTextRange(ts.createBinary(cacheExpression(target), getOperatorForCompoundAssignment(operator), ts.visitNode(right, visitor, ts.isExpression)), node)), node); + } + else { + return ts.updateBinary(node, target, ts.visitNode(right, visitor, ts.isExpression)); + } + } + return ts.visitEachChild(node, visitor, context); + } + function visitLeftAssociativeBinaryExpression(node) { + if (containsYield(node.right)) { + if (ts.isLogicalOperator(node.operatorToken.kind)) { + return visitLogicalBinaryExpression(node); + } + else if (node.operatorToken.kind === 27 /* CommaToken */) { + return visitCommaExpression(node); + } + // [source] + // a() + (yield) + c() + // + // [intermediate] + // .local _a + // _a = a(); + // .yield resumeLabel + // _a + %sent% + c() + var clone_5 = ts.getMutableClone(node); + clone_5.left = cacheExpression(ts.visitNode(node.left, visitor, ts.isExpression)); + clone_5.right = ts.visitNode(node.right, visitor, ts.isExpression); + return clone_5; + } + return ts.visitEachChild(node, visitor, context); + } + /** + * Visits a logical binary expression containing `yield`. + * + * @param node A node to visit. + */ + function visitLogicalBinaryExpression(node) { + // Logical binary expressions (`&&` and `||`) are shortcutting expressions and need + // to be transformed as such: + // + // [source] + // x = a() && yield; + // + // [intermediate] + // .local _a + // _a = a(); + // .brfalse resultLabel, (_a) + // .yield resumeLabel + // .mark resumeLabel + // _a = %sent%; + // .mark resultLabel + // x = _a; + // + // [source] + // x = a() || yield; + // + // [intermediate] + // .local _a + // _a = a(); + // .brtrue resultLabel, (_a) + // .yield resumeLabel + // .mark resumeLabel + // _a = %sent%; + // .mark resultLabel + // x = _a; + var resultLabel = defineLabel(); + var resultLocal = declareLocal(); + emitAssignment(resultLocal, ts.visitNode(node.left, visitor, ts.isExpression), /*location*/ node.left); + if (node.operatorToken.kind === 54 /* AmpersandAmpersandToken */) { + // Logical `&&` shortcuts when the left-hand operand is falsey. + emitBreakWhenFalse(resultLabel, resultLocal, /*location*/ node.left); + } + else { + // Logical `||` shortcuts when the left-hand operand is truthy. + emitBreakWhenTrue(resultLabel, resultLocal, /*location*/ node.left); + } + emitAssignment(resultLocal, ts.visitNode(node.right, visitor, ts.isExpression), /*location*/ node.right); + markLabel(resultLabel); + return resultLocal; + } + /** + * Visits a comma expression containing `yield`. + * + * @param node The node to visit. + */ + function visitCommaExpression(node) { + // [source] + // x = a(), yield, b(); + // + // [intermediate] + // a(); + // .yield resumeLabel + // .mark resumeLabel + // x = %sent%, b(); + var pendingExpressions = []; + visit(node.left); + visit(node.right); + return ts.inlineExpressions(pendingExpressions); + function visit(node) { + if (ts.isBinaryExpression(node) && node.operatorToken.kind === 27 /* CommaToken */) { + visit(node.left); + visit(node.right); + } + else { + if (containsYield(node) && pendingExpressions.length > 0) { + emitWorker(1 /* Statement */, [ts.createExpressionStatement(ts.inlineExpressions(pendingExpressions))]); + pendingExpressions = []; + } + pendingExpressions.push(ts.visitNode(node, visitor, ts.isExpression)); + } + } + } + /** + * Visits a conditional expression containing `yield`. + * + * @param node The node to visit. + */ + function visitConditionalExpression(node) { + // [source] + // x = a() ? yield : b(); + // + // [intermediate] + // .local _a + // .brfalse whenFalseLabel, (a()) + // .yield resumeLabel + // .mark resumeLabel + // _a = %sent%; + // .br resultLabel + // .mark whenFalseLabel + // _a = b(); + // .mark resultLabel + // x = _a; + // We only need to perform a specific transformation if a `yield` expression exists + // in either the `whenTrue` or `whenFalse` branches. + // A `yield` in the condition will be handled by the normal visitor. + if (containsYield(node.whenTrue) || containsYield(node.whenFalse)) { + var whenFalseLabel = defineLabel(); + var resultLabel = defineLabel(); + var resultLocal = declareLocal(); + emitBreakWhenFalse(whenFalseLabel, ts.visitNode(node.condition, visitor, ts.isExpression), /*location*/ node.condition); + emitAssignment(resultLocal, ts.visitNode(node.whenTrue, visitor, ts.isExpression), /*location*/ node.whenTrue); + emitBreak(resultLabel); + markLabel(whenFalseLabel); + emitAssignment(resultLocal, ts.visitNode(node.whenFalse, visitor, ts.isExpression), /*location*/ node.whenFalse); + markLabel(resultLabel); + return resultLocal; + } + return ts.visitEachChild(node, visitor, context); + } + /** + * Visits a `yield` expression. + * + * @param node The node to visit. + */ + function visitYieldExpression(node) { + // [source] + // x = yield a(); + // + // [intermediate] + // .yield resumeLabel, (a()) + // .mark resumeLabel + // x = %sent%; + var resumeLabel = defineLabel(); + var expression = ts.visitNode(node.expression, visitor, ts.isExpression); + if (node.asteriskToken) { + var iterator = (ts.getEmitFlags(node.expression) & 8388608 /* Iterator */) === 0 + ? ts.createValuesHelper(context, expression, /*location*/ node) + : expression; + emitYieldStar(iterator, /*location*/ node); + } + else { + emitYield(expression, /*location*/ node); + } + markLabel(resumeLabel); + return createGeneratorResume(/*location*/ node); + } + /** + * Visits an ArrayLiteralExpression that contains a YieldExpression. + * + * @param node The node to visit. + */ + function visitArrayLiteralExpression(node) { + return visitElements(node.elements, /*leadingElement*/ undefined, /*location*/ undefined, node.multiLine); + } + /** + * Visits an array of expressions containing one or more YieldExpression nodes + * and returns an expression for the resulting value. + * + * @param elements The elements to visit. + * @param multiLine Whether array literals created should be emitted on multiple lines. + */ + function visitElements(elements, leadingElement, location, multiLine) { + // [source] + // ar = [1, yield, 2]; + // + // [intermediate] + // .local _a + // _a = [1]; + // .yield resumeLabel + // .mark resumeLabel + // ar = _a.concat([%sent%, 2]); + var numInitialElements = countInitialNodesWithoutYield(elements); + var temp; + if (numInitialElements > 0) { + temp = declareLocal(); + var initialElements = ts.visitNodes(elements, visitor, ts.isExpression, 0, numInitialElements); + emitAssignment(temp, ts.createArrayLiteral(leadingElement + ? [leadingElement].concat(initialElements) : initialElements)); + leadingElement = undefined; + } + var expressions = ts.reduceLeft(elements, reduceElement, [], numInitialElements); + return temp + ? ts.createArrayConcat(temp, [ts.createArrayLiteral(expressions, multiLine)]) + : ts.setTextRange(ts.createArrayLiteral(leadingElement ? [leadingElement].concat(expressions) : expressions, multiLine), location); + function reduceElement(expressions, element) { + if (containsYield(element) && expressions.length > 0) { + var hasAssignedTemp = temp !== undefined; + if (!temp) { + temp = declareLocal(); + } + emitAssignment(temp, hasAssignedTemp + ? ts.createArrayConcat(temp, [ts.createArrayLiteral(expressions, multiLine)]) + : ts.createArrayLiteral(leadingElement ? [leadingElement].concat(expressions) : expressions, multiLine)); + leadingElement = undefined; + expressions = []; + } + expressions.push(ts.visitNode(element, visitor, ts.isExpression)); + return expressions; + } + } + function visitObjectLiteralExpression(node) { + // [source] + // o = { + // a: 1, + // b: yield, + // c: 2 + // }; + // + // [intermediate] + // .local _a + // _a = { + // a: 1 + // }; + // .yield resumeLabel + // .mark resumeLabel + // o = (_a.b = %sent%, + // _a.c = 2, + // _a); + var properties = node.properties; + var multiLine = node.multiLine; + var numInitialProperties = countInitialNodesWithoutYield(properties); + var temp = declareLocal(); + emitAssignment(temp, ts.createObjectLiteral(ts.visitNodes(properties, visitor, ts.isObjectLiteralElementLike, 0, numInitialProperties), multiLine)); + var expressions = ts.reduceLeft(properties, reduceProperty, [], numInitialProperties); + expressions.push(multiLine ? ts.startOnNewLine(ts.getMutableClone(temp)) : temp); + return ts.inlineExpressions(expressions); + function reduceProperty(expressions, property) { + if (containsYield(property) && expressions.length > 0) { + emitStatement(ts.createExpressionStatement(ts.inlineExpressions(expressions))); + expressions = []; + } + var expression = ts.createExpressionForObjectLiteralElementLike(node, property, temp); + var visited = ts.visitNode(expression, visitor, ts.isExpression); + if (visited) { + if (multiLine) { + ts.startOnNewLine(visited); + } + expressions.push(visited); + } + return expressions; + } + } + /** + * Visits an ElementAccessExpression that contains a YieldExpression. + * + * @param node The node to visit. + */ + function visitElementAccessExpression(node) { + if (containsYield(node.argumentExpression)) { + // [source] + // a = x[yield]; + // + // [intermediate] + // .local _a + // _a = x; + // .yield resumeLabel + // .mark resumeLabel + // a = _a[%sent%] + var clone_6 = ts.getMutableClone(node); + clone_6.expression = cacheExpression(ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression)); + clone_6.argumentExpression = ts.visitNode(node.argumentExpression, visitor, ts.isExpression); + return clone_6; + } + return ts.visitEachChild(node, visitor, context); + } + function visitCallExpression(node) { + if (!ts.isImportCall(node) && ts.forEach(node.arguments, containsYield)) { + // [source] + // a.b(1, yield, 2); + // + // [intermediate] + // .local _a, _b, _c + // _b = (_a = a).b; + // _c = [1]; + // .yield resumeLabel + // .mark resumeLabel + // _b.apply(_a, _c.concat([%sent%, 2])); + var _a = ts.createCallBinding(node.expression, hoistVariableDeclaration, languageVersion, /*cacheIdentifiers*/ true), target = _a.target, thisArg = _a.thisArg; + return ts.setOriginalNode(ts.createFunctionApply(cacheExpression(ts.visitNode(target, visitor, ts.isLeftHandSideExpression)), thisArg, visitElements(node.arguments), + /*location*/ node), node); + } + return ts.visitEachChild(node, visitor, context); + } + function visitNewExpression(node) { + if (ts.forEach(node.arguments, containsYield)) { + // [source] + // new a.b(1, yield, 2); + // + // [intermediate] + // .local _a, _b, _c + // _b = (_a = a.b).bind; + // _c = [1]; + // .yield resumeLabel + // .mark resumeLabel + // new (_b.apply(_a, _c.concat([%sent%, 2]))); + var _a = ts.createCallBinding(ts.createPropertyAccess(node.expression, "bind"), hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg; + return ts.setOriginalNode(ts.setTextRange(ts.createNew(ts.createFunctionApply(cacheExpression(ts.visitNode(target, visitor, ts.isExpression)), thisArg, visitElements(node.arguments, + /*leadingElement*/ ts.createVoidZero())), + /*typeArguments*/ undefined, []), node), node); + } + return ts.visitEachChild(node, visitor, context); + } + function transformAndEmitStatements(statements, start) { + if (start === void 0) { start = 0; } + var numStatements = statements.length; + for (var i = start; i < numStatements; i++) { + transformAndEmitStatement(statements[i]); + } + } + function transformAndEmitEmbeddedStatement(node) { + if (ts.isBlock(node)) { + transformAndEmitStatements(node.statements); + } + else { + transformAndEmitStatement(node); + } + } + function transformAndEmitStatement(node) { + var savedInStatementContainingYield = inStatementContainingYield; + if (!inStatementContainingYield) { + inStatementContainingYield = containsYield(node); + } + transformAndEmitStatementWorker(node); + inStatementContainingYield = savedInStatementContainingYield; + } + function transformAndEmitStatementWorker(node) { + switch (node.kind) { + case 218 /* Block */: + return transformAndEmitBlock(node); + case 221 /* ExpressionStatement */: + return transformAndEmitExpressionStatement(node); + case 222 /* IfStatement */: + return transformAndEmitIfStatement(node); + case 223 /* DoStatement */: + return transformAndEmitDoStatement(node); + case 224 /* WhileStatement */: + return transformAndEmitWhileStatement(node); + case 225 /* ForStatement */: + return transformAndEmitForStatement(node); + case 226 /* ForInStatement */: + return transformAndEmitForInStatement(node); + case 228 /* ContinueStatement */: + return transformAndEmitContinueStatement(node); + case 229 /* BreakStatement */: + return transformAndEmitBreakStatement(node); + case 230 /* ReturnStatement */: + return transformAndEmitReturnStatement(node); + case 231 /* WithStatement */: + return transformAndEmitWithStatement(node); + case 232 /* SwitchStatement */: + return transformAndEmitSwitchStatement(node); + case 233 /* LabeledStatement */: + return transformAndEmitLabeledStatement(node); + case 234 /* ThrowStatement */: + return transformAndEmitThrowStatement(node); + case 235 /* TryStatement */: + return transformAndEmitTryStatement(node); + default: + return emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + } + function transformAndEmitBlock(node) { + if (containsYield(node)) { + transformAndEmitStatements(node.statements); + } + else { + emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + } + function transformAndEmitExpressionStatement(node) { + emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + function transformAndEmitVariableDeclarationList(node) { + for (var _i = 0, _a = node.declarations; _i < _a.length; _i++) { + var variable = _a[_i]; + var name = ts.getSynthesizedClone(variable.name); + ts.setCommentRange(name, variable.name); + hoistVariableDeclaration(name); + } + var variables = ts.getInitializedVariables(node); + var numVariables = variables.length; + var variablesWritten = 0; + var pendingExpressions = []; + while (variablesWritten < numVariables) { + for (var i = variablesWritten; i < numVariables; i++) { + var variable = variables[i]; + if (containsYield(variable.initializer) && pendingExpressions.length > 0) { + break; + } + pendingExpressions.push(transformInitializedVariable(variable)); + } + if (pendingExpressions.length) { + emitStatement(ts.createExpressionStatement(ts.inlineExpressions(pendingExpressions))); + variablesWritten += pendingExpressions.length; + pendingExpressions = []; + } + } + return undefined; + } + function transformInitializedVariable(node) { + return ts.setSourceMapRange(ts.createAssignment(ts.setSourceMapRange(ts.getSynthesizedClone(node.name), node.name), ts.visitNode(node.initializer, visitor, ts.isExpression)), node); + } + function transformAndEmitIfStatement(node) { + if (containsYield(node)) { + // [source] + // if (x) + // /*thenStatement*/ + // else + // /*elseStatement*/ + // + // [intermediate] + // .brfalse elseLabel, (x) + // /*thenStatement*/ + // .br endLabel + // .mark elseLabel + // /*elseStatement*/ + // .mark endLabel + if (containsYield(node.thenStatement) || containsYield(node.elseStatement)) { + var endLabel = defineLabel(); + var elseLabel = node.elseStatement ? defineLabel() : undefined; + emitBreakWhenFalse(node.elseStatement ? elseLabel : endLabel, ts.visitNode(node.expression, visitor, ts.isExpression), /*location*/ node.expression); + transformAndEmitEmbeddedStatement(node.thenStatement); + if (node.elseStatement) { + emitBreak(endLabel); + markLabel(elseLabel); + transformAndEmitEmbeddedStatement(node.elseStatement); + } + markLabel(endLabel); + } + else { + emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + } + else { + emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + } + function transformAndEmitDoStatement(node) { + if (containsYield(node)) { + // [source] + // do { + // /*body*/ + // } + // while (i < 10); + // + // [intermediate] + // .loop conditionLabel, endLabel + // .mark loopLabel + // /*body*/ + // .mark conditionLabel + // .brtrue loopLabel, (i < 10) + // .endloop + // .mark endLabel + var conditionLabel = defineLabel(); + var loopLabel = defineLabel(); + beginLoopBlock(/*continueLabel*/ conditionLabel); + markLabel(loopLabel); + transformAndEmitEmbeddedStatement(node.statement); + markLabel(conditionLabel); + emitBreakWhenTrue(loopLabel, ts.visitNode(node.expression, visitor, ts.isExpression)); + endLoopBlock(); + } + else { + emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + } + function visitDoStatement(node) { + if (inStatementContainingYield) { + beginScriptLoopBlock(); + node = ts.visitEachChild(node, visitor, context); + endLoopBlock(); + return node; + } + else { + return ts.visitEachChild(node, visitor, context); + } + } + function transformAndEmitWhileStatement(node) { + if (containsYield(node)) { + // [source] + // while (i < 10) { + // /*body*/ + // } + // + // [intermediate] + // .loop loopLabel, endLabel + // .mark loopLabel + // .brfalse endLabel, (i < 10) + // /*body*/ + // .br loopLabel + // .endloop + // .mark endLabel + var loopLabel = defineLabel(); + var endLabel = beginLoopBlock(loopLabel); + markLabel(loopLabel); + emitBreakWhenFalse(endLabel, ts.visitNode(node.expression, visitor, ts.isExpression)); + transformAndEmitEmbeddedStatement(node.statement); + emitBreak(loopLabel); + endLoopBlock(); + } + else { + emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + } + function visitWhileStatement(node) { + if (inStatementContainingYield) { + beginScriptLoopBlock(); + node = ts.visitEachChild(node, visitor, context); + endLoopBlock(); + return node; + } + else { + return ts.visitEachChild(node, visitor, context); + } + } + function transformAndEmitForStatement(node) { + if (containsYield(node)) { + // [source] + // for (var i = 0; i < 10; i++) { + // /*body*/ + // } + // + // [intermediate] + // .local i + // i = 0; + // .loop incrementLabel, endLoopLabel + // .mark conditionLabel + // .brfalse endLoopLabel, (i < 10) + // /*body*/ + // .mark incrementLabel + // i++; + // .br conditionLabel + // .endloop + // .mark endLoopLabel + var conditionLabel = defineLabel(); + var incrementLabel = defineLabel(); + var endLabel = beginLoopBlock(incrementLabel); + if (node.initializer) { + var initializer = node.initializer; + if (ts.isVariableDeclarationList(initializer)) { + transformAndEmitVariableDeclarationList(initializer); + } + else { + emitStatement(ts.setTextRange(ts.createExpressionStatement(ts.visitNode(initializer, visitor, ts.isExpression)), initializer)); + } + } + markLabel(conditionLabel); + if (node.condition) { + emitBreakWhenFalse(endLabel, ts.visitNode(node.condition, visitor, ts.isExpression)); + } + transformAndEmitEmbeddedStatement(node.statement); + markLabel(incrementLabel); + if (node.incrementor) { + emitStatement(ts.setTextRange(ts.createExpressionStatement(ts.visitNode(node.incrementor, visitor, ts.isExpression)), node.incrementor)); + } + emitBreak(conditionLabel); + endLoopBlock(); + } + else { + emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + } + function visitForStatement(node) { + if (inStatementContainingYield) { + beginScriptLoopBlock(); + } + var initializer = node.initializer; + if (initializer && ts.isVariableDeclarationList(initializer)) { + for (var _i = 0, _a = initializer.declarations; _i < _a.length; _i++) { + var variable = _a[_i]; + hoistVariableDeclaration(variable.name); + } + var variables = ts.getInitializedVariables(initializer); + node = ts.updateFor(node, variables.length > 0 + ? ts.inlineExpressions(ts.map(variables, transformInitializedVariable)) + : undefined, ts.visitNode(node.condition, visitor, ts.isExpression), ts.visitNode(node.incrementor, visitor, ts.isExpression), ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); + } + else { + node = ts.visitEachChild(node, visitor, context); + } + if (inStatementContainingYield) { + endLoopBlock(); + } + return node; + } + function transformAndEmitForInStatement(node) { + // TODO(rbuckton): Source map locations + if (containsYield(node)) { + // [source] + // for (var p in o) { + // /*body*/ + // } + // + // [intermediate] + // .local _a, _b, _i + // _a = []; + // for (_b in o) _a.push(_b); + // _i = 0; + // .loop incrementLabel, endLoopLabel + // .mark conditionLabel + // .brfalse endLoopLabel, (_i < _a.length) + // p = _a[_i]; + // /*body*/ + // .mark incrementLabel + // _b++; + // .br conditionLabel + // .endloop + // .mark endLoopLabel + var keysArray = declareLocal(); // _a + var key = declareLocal(); // _b + var keysIndex = ts.createLoopVariable(); // _i + var initializer = node.initializer; + hoistVariableDeclaration(keysIndex); + emitAssignment(keysArray, ts.createArrayLiteral()); + emitStatement(ts.createForIn(key, ts.visitNode(node.expression, visitor, ts.isExpression), ts.createExpressionStatement(ts.createCall(ts.createPropertyAccess(keysArray, "push"), + /*typeArguments*/ undefined, [key])))); + emitAssignment(keysIndex, ts.createLiteral(0)); + var conditionLabel = defineLabel(); + var incrementLabel = defineLabel(); + var endLabel = beginLoopBlock(incrementLabel); + markLabel(conditionLabel); + emitBreakWhenFalse(endLabel, ts.createLessThan(keysIndex, ts.createPropertyAccess(keysArray, "length"))); + var variable = void 0; + if (ts.isVariableDeclarationList(initializer)) { + for (var _i = 0, _a = initializer.declarations; _i < _a.length; _i++) { + var variable_1 = _a[_i]; + hoistVariableDeclaration(variable_1.name); + } + variable = ts.getSynthesizedClone(initializer.declarations[0].name); + } + else { + variable = ts.visitNode(initializer, visitor, ts.isExpression); + ts.Debug.assert(ts.isLeftHandSideExpression(variable)); + } + emitAssignment(variable, ts.createElementAccess(keysArray, keysIndex)); + transformAndEmitEmbeddedStatement(node.statement); + markLabel(incrementLabel); + emitStatement(ts.createExpressionStatement(ts.createPostfixIncrement(keysIndex))); + emitBreak(conditionLabel); + endLoopBlock(); + } + else { + emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + } + function visitForInStatement(node) { + // [source] + // for (var x in a) { + // /*body*/ + // } + // + // [intermediate] + // .local x + // .loop + // for (x in a) { + // /*body*/ + // } + // .endloop + if (inStatementContainingYield) { + beginScriptLoopBlock(); + } + var initializer = node.initializer; + if (ts.isVariableDeclarationList(initializer)) { + for (var _i = 0, _a = initializer.declarations; _i < _a.length; _i++) { + var variable = _a[_i]; + hoistVariableDeclaration(variable.name); + } + node = ts.updateForIn(node, initializer.declarations[0].name, ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); + } + else { + node = ts.visitEachChild(node, visitor, context); + } + if (inStatementContainingYield) { + endLoopBlock(); + } + return node; + } + function transformAndEmitContinueStatement(node) { + var label = findContinueTarget(node.label ? ts.idText(node.label) : undefined); + if (label > 0) { + emitBreak(label, /*location*/ node); + } + else { + // invalid continue without a containing loop. Leave the node as is, per #17875. + emitStatement(node); + } + } + function visitContinueStatement(node) { + if (inStatementContainingYield) { + var label = findContinueTarget(node.label && ts.idText(node.label)); + if (label > 0) { + return createInlineBreak(label, /*location*/ node); + } + } + return ts.visitEachChild(node, visitor, context); + } + function transformAndEmitBreakStatement(node) { + var label = findBreakTarget(node.label ? ts.idText(node.label) : undefined); + if (label > 0) { + emitBreak(label, /*location*/ node); + } + else { + // invalid break without a containing loop, switch, or labeled statement. Leave the node as is, per #17875. + emitStatement(node); + } + } + function visitBreakStatement(node) { + if (inStatementContainingYield) { + var label = findBreakTarget(node.label && ts.idText(node.label)); + if (label > 0) { + return createInlineBreak(label, /*location*/ node); + } + } + return ts.visitEachChild(node, visitor, context); + } + function transformAndEmitReturnStatement(node) { + emitReturn(ts.visitNode(node.expression, visitor, ts.isExpression), + /*location*/ node); + } + function visitReturnStatement(node) { + return createInlineReturn(ts.visitNode(node.expression, visitor, ts.isExpression), + /*location*/ node); + } + function transformAndEmitWithStatement(node) { + if (containsYield(node)) { + // [source] + // with (x) { + // /*body*/ + // } + // + // [intermediate] + // .with (x) + // /*body*/ + // .endwith + beginWithBlock(cacheExpression(ts.visitNode(node.expression, visitor, ts.isExpression))); + transformAndEmitEmbeddedStatement(node.statement); + endWithBlock(); + } + else { + emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + } + function transformAndEmitSwitchStatement(node) { + if (containsYield(node.caseBlock)) { + // [source] + // switch (x) { + // case a: + // /*caseStatements*/ + // case b: + // /*caseStatements*/ + // default: + // /*defaultStatements*/ + // } + // + // [intermediate] + // .local _a + // .switch endLabel + // _a = x; + // switch (_a) { + // case a: + // .br clauseLabels[0] + // } + // switch (_a) { + // case b: + // .br clauseLabels[1] + // } + // .br clauseLabels[2] + // .mark clauseLabels[0] + // /*caseStatements*/ + // .mark clauseLabels[1] + // /*caseStatements*/ + // .mark clauseLabels[2] + // /*caseStatements*/ + // .endswitch + // .mark endLabel + var caseBlock = node.caseBlock; + var numClauses = caseBlock.clauses.length; + var endLabel = beginSwitchBlock(); + var expression = cacheExpression(ts.visitNode(node.expression, visitor, ts.isExpression)); + // Create labels for each clause and find the index of the first default clause. + var clauseLabels = []; + var defaultClauseIndex = -1; + for (var i = 0; i < numClauses; i++) { + var clause = caseBlock.clauses[i]; + clauseLabels.push(defineLabel()); + if (clause.kind === 272 /* DefaultClause */ && defaultClauseIndex === -1) { + defaultClauseIndex = i; + } + } + // Emit switch statements for each run of case clauses either from the first case + // clause or the next case clause with a `yield` in its expression, up to the next + // case clause with a `yield` in its expression. + var clausesWritten = 0; + var pendingClauses = []; + while (clausesWritten < numClauses) { + var defaultClausesSkipped = 0; + for (var i = clausesWritten; i < numClauses; i++) { + var clause = caseBlock.clauses[i]; + if (clause.kind === 271 /* CaseClause */) { + if (containsYield(clause.expression) && pendingClauses.length > 0) { + break; + } + pendingClauses.push(ts.createCaseClause(ts.visitNode(clause.expression, visitor, ts.isExpression), [ + createInlineBreak(clauseLabels[i], /*location*/ clause.expression) + ])); + } + else { + defaultClausesSkipped++; + } + } + if (pendingClauses.length) { + emitStatement(ts.createSwitch(expression, ts.createCaseBlock(pendingClauses))); + clausesWritten += pendingClauses.length; + pendingClauses = []; + } + if (defaultClausesSkipped > 0) { + clausesWritten += defaultClausesSkipped; + defaultClausesSkipped = 0; + } + } + if (defaultClauseIndex >= 0) { + emitBreak(clauseLabels[defaultClauseIndex]); + } + else { + emitBreak(endLabel); + } + for (var i = 0; i < numClauses; i++) { + markLabel(clauseLabels[i]); + transformAndEmitStatements(caseBlock.clauses[i].statements); + } + endSwitchBlock(); + } + else { + emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + } + function visitSwitchStatement(node) { + if (inStatementContainingYield) { + beginScriptSwitchBlock(); + } + node = ts.visitEachChild(node, visitor, context); + if (inStatementContainingYield) { + endSwitchBlock(); + } + return node; + } + function transformAndEmitLabeledStatement(node) { + if (containsYield(node)) { + // [source] + // x: { + // /*body*/ + // } + // + // [intermediate] + // .labeled "x", endLabel + // /*body*/ + // .endlabeled + // .mark endLabel + beginLabeledBlock(ts.idText(node.label)); + transformAndEmitEmbeddedStatement(node.statement); + endLabeledBlock(); + } + else { + emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + } + function visitLabeledStatement(node) { + if (inStatementContainingYield) { + beginScriptLabeledBlock(ts.idText(node.label)); + } + node = ts.visitEachChild(node, visitor, context); + if (inStatementContainingYield) { + endLabeledBlock(); + } + return node; + } + function transformAndEmitThrowStatement(node) { + emitThrow(ts.visitNode(node.expression, visitor, ts.isExpression), + /*location*/ node); + } + function transformAndEmitTryStatement(node) { + if (containsYield(node)) { + // [source] + // try { + // /*tryBlock*/ + // } + // catch (e) { + // /*catchBlock*/ + // } + // finally { + // /*finallyBlock*/ + // } + // + // [intermediate] + // .local _a + // .try tryLabel, catchLabel, finallyLabel, endLabel + // .mark tryLabel + // .nop + // /*tryBlock*/ + // .br endLabel + // .catch + // .mark catchLabel + // _a = %error%; + // /*catchBlock*/ + // .br endLabel + // .finally + // .mark finallyLabel + // /*finallyBlock*/ + // .endfinally + // .endtry + // .mark endLabel + beginExceptionBlock(); + transformAndEmitEmbeddedStatement(node.tryBlock); + if (node.catchClause) { + beginCatchBlock(node.catchClause.variableDeclaration); // TODO: GH#18217 + transformAndEmitEmbeddedStatement(node.catchClause.block); + } + if (node.finallyBlock) { + beginFinallyBlock(); + transformAndEmitEmbeddedStatement(node.finallyBlock); + } + endExceptionBlock(); + } + else { + emitStatement(ts.visitEachChild(node, visitor, context)); + } + } + function containsYield(node) { + return !!node && (node.transformFlags & 4194304 /* ContainsYield */) !== 0; + } + function countInitialNodesWithoutYield(nodes) { + var numNodes = nodes.length; + for (var i = 0; i < numNodes; i++) { + if (containsYield(nodes[i])) { + return i; + } + } + return -1; + } + function onSubstituteNode(hint, node) { + node = previousOnSubstituteNode(hint, node); + if (hint === 1 /* Expression */) { + return substituteExpression(node); + } + return node; + } + function substituteExpression(node) { + if (ts.isIdentifier(node)) { + return substituteExpressionIdentifier(node); + } + return node; + } + function substituteExpressionIdentifier(node) { + if (!ts.isGeneratedIdentifier(node) && renamedCatchVariables && renamedCatchVariables.has(ts.idText(node))) { + var original = ts.getOriginalNode(node); + if (ts.isIdentifier(original) && original.parent) { + var declaration = resolver.getReferencedValueDeclaration(original); + if (declaration) { + var name = renamedCatchVariableDeclarations[ts.getOriginalNodeId(declaration)]; + if (name) { + var clone_7 = ts.getMutableClone(name); + ts.setSourceMapRange(clone_7, node); + ts.setCommentRange(clone_7, node); + return clone_7; + } + } + } + } + return node; + } + function cacheExpression(node) { + var temp; + if (ts.isGeneratedIdentifier(node) || ts.getEmitFlags(node) & 4096 /* HelperName */) { + return node; + } + temp = ts.createTempVariable(hoistVariableDeclaration); + emitAssignment(temp, node, /*location*/ node); + return temp; + } + function declareLocal(name) { + var temp = name + ? ts.createUniqueName(name) + : ts.createTempVariable(/*recordTempVariable*/ undefined); + hoistVariableDeclaration(temp); + return temp; + } + /** + * Defines a label, uses as the target of a Break operation. + */ + function defineLabel() { + if (!labelOffsets) { + labelOffsets = []; + } + var label = nextLabelId; + nextLabelId++; + labelOffsets[label] = -1; + return label; + } + /** + * Marks the current operation with the specified label. + */ + function markLabel(label) { + ts.Debug.assert(labelOffsets !== undefined, "No labels were defined."); + labelOffsets[label] = operations ? operations.length : 0; + } + /** + * Begins a block operation (With, Break/Continue, Try/Catch/Finally) + * + * @param block Information about the block. + */ + function beginBlock(block) { + if (!blocks) { + blocks = []; + blockActions = []; + blockOffsets = []; + blockStack = []; + } + var index = blockActions.length; + blockActions[index] = 0 /* Open */; + blockOffsets[index] = operations ? operations.length : 0; + blocks[index] = block; + blockStack.push(block); + return index; + } + /** + * Ends the current block operation. + */ + function endBlock() { + var block = peekBlock(); + if (block === undefined) + return ts.Debug.fail("beginBlock was never called."); + var index = blockActions.length; + blockActions[index] = 1 /* Close */; + blockOffsets[index] = operations ? operations.length : 0; + blocks[index] = block; + blockStack.pop(); + return block; + } + /** + * Gets the current open block. + */ + function peekBlock() { + return ts.lastOrUndefined(blockStack); + } + /** + * Gets the kind of the current open block. + */ + function peekBlockKind() { + var block = peekBlock(); + return block && block.kind; + } + /** + * Begins a code block for a generated `with` statement. + * + * @param expression An identifier representing expression for the `with` block. + */ + function beginWithBlock(expression) { + var startLabel = defineLabel(); + var endLabel = defineLabel(); + markLabel(startLabel); + beginBlock({ + kind: 1 /* With */, + expression: expression, + startLabel: startLabel, + endLabel: endLabel + }); + } + /** + * Ends a code block for a generated `with` statement. + */ + function endWithBlock() { + ts.Debug.assert(peekBlockKind() === 1 /* With */); + var block = endBlock(); + markLabel(block.endLabel); + } + /** + * Begins a code block for a generated `try` statement. + */ + function beginExceptionBlock() { + var startLabel = defineLabel(); + var endLabel = defineLabel(); + markLabel(startLabel); + beginBlock({ + kind: 0 /* Exception */, + state: 0 /* Try */, + startLabel: startLabel, + endLabel: endLabel + }); + emitNop(); + return endLabel; + } + /** + * Enters the `catch` clause of a generated `try` statement. + * + * @param variable The catch variable. + */ + function beginCatchBlock(variable) { + ts.Debug.assert(peekBlockKind() === 0 /* Exception */); + // generated identifiers should already be unique within a file + var name; + if (ts.isGeneratedIdentifier(variable.name)) { + name = variable.name; + hoistVariableDeclaration(variable.name); + } + else { + var text = ts.idText(variable.name); + name = declareLocal(text); + if (!renamedCatchVariables) { + renamedCatchVariables = ts.createMap(); + renamedCatchVariableDeclarations = []; + context.enableSubstitution(72 /* Identifier */); + } + renamedCatchVariables.set(text, true); + renamedCatchVariableDeclarations[ts.getOriginalNodeId(variable)] = name; + } + var exception = peekBlock(); + ts.Debug.assert(exception.state < 1 /* Catch */); + var endLabel = exception.endLabel; + emitBreak(endLabel); + var catchLabel = defineLabel(); + markLabel(catchLabel); + exception.state = 1 /* Catch */; + exception.catchVariable = name; + exception.catchLabel = catchLabel; + emitAssignment(name, ts.createCall(ts.createPropertyAccess(state, "sent"), /*typeArguments*/ undefined, [])); + emitNop(); + } + /** + * Enters the `finally` block of a generated `try` statement. + */ + function beginFinallyBlock() { + ts.Debug.assert(peekBlockKind() === 0 /* Exception */); + var exception = peekBlock(); + ts.Debug.assert(exception.state < 2 /* Finally */); + var endLabel = exception.endLabel; + emitBreak(endLabel); + var finallyLabel = defineLabel(); + markLabel(finallyLabel); + exception.state = 2 /* Finally */; + exception.finallyLabel = finallyLabel; + } + /** + * Ends the code block for a generated `try` statement. + */ + function endExceptionBlock() { + ts.Debug.assert(peekBlockKind() === 0 /* Exception */); + var exception = endBlock(); + var state = exception.state; + if (state < 2 /* Finally */) { + emitBreak(exception.endLabel); + } + else { + emitEndfinally(); + } + markLabel(exception.endLabel); + emitNop(); + exception.state = 3 /* Done */; + } + /** + * Begins a code block that supports `break` or `continue` statements that are defined in + * the source tree and not from generated code. + * + * @param labelText Names from containing labeled statements. + */ + function beginScriptLoopBlock() { + beginBlock({ + kind: 3 /* Loop */, + isScript: true, + breakLabel: -1, + continueLabel: -1 + }); + } + /** + * Begins a code block that supports `break` or `continue` statements that are defined in + * generated code. Returns a label used to mark the operation to which to jump when a + * `break` statement targets this block. + * + * @param continueLabel A Label used to mark the operation to which to jump when a + * `continue` statement targets this block. + */ + function beginLoopBlock(continueLabel) { + var breakLabel = defineLabel(); + beginBlock({ + kind: 3 /* Loop */, + isScript: false, + breakLabel: breakLabel, + continueLabel: continueLabel, + }); + return breakLabel; + } + /** + * Ends a code block that supports `break` or `continue` statements that are defined in + * generated code or in the source tree. + */ + function endLoopBlock() { + ts.Debug.assert(peekBlockKind() === 3 /* Loop */); + var block = endBlock(); + var breakLabel = block.breakLabel; + if (!block.isScript) { + markLabel(breakLabel); + } + } + /** + * Begins a code block that supports `break` statements that are defined in the source + * tree and not from generated code. + * + */ + function beginScriptSwitchBlock() { + beginBlock({ + kind: 2 /* Switch */, + isScript: true, + breakLabel: -1 + }); + } + /** + * Begins a code block that supports `break` statements that are defined in generated code. + * Returns a label used to mark the operation to which to jump when a `break` statement + * targets this block. + */ + function beginSwitchBlock() { + var breakLabel = defineLabel(); + beginBlock({ + kind: 2 /* Switch */, + isScript: false, + breakLabel: breakLabel, + }); + return breakLabel; + } + /** + * Ends a code block that supports `break` statements that are defined in generated code. + */ + function endSwitchBlock() { + ts.Debug.assert(peekBlockKind() === 2 /* Switch */); + var block = endBlock(); + var breakLabel = block.breakLabel; + if (!block.isScript) { + markLabel(breakLabel); + } + } + function beginScriptLabeledBlock(labelText) { + beginBlock({ + kind: 4 /* Labeled */, + isScript: true, + labelText: labelText, + breakLabel: -1 + }); + } + function beginLabeledBlock(labelText) { + var breakLabel = defineLabel(); + beginBlock({ + kind: 4 /* Labeled */, + isScript: false, + labelText: labelText, + breakLabel: breakLabel + }); + } + function endLabeledBlock() { + ts.Debug.assert(peekBlockKind() === 4 /* Labeled */); + var block = endBlock(); + if (!block.isScript) { + markLabel(block.breakLabel); + } + } + /** + * Indicates whether the provided block supports `break` statements. + * + * @param block A code block. + */ + function supportsUnlabeledBreak(block) { + return block.kind === 2 /* Switch */ + || block.kind === 3 /* Loop */; + } + /** + * Indicates whether the provided block supports `break` statements with labels. + * + * @param block A code block. + */ + function supportsLabeledBreakOrContinue(block) { + return block.kind === 4 /* Labeled */; + } + /** + * Indicates whether the provided block supports `continue` statements. + * + * @param block A code block. + */ + function supportsUnlabeledContinue(block) { + return block.kind === 3 /* Loop */; + } + function hasImmediateContainingLabeledBlock(labelText, start) { + for (var j = start; j >= 0; j--) { + var containingBlock = blockStack[j]; + if (supportsLabeledBreakOrContinue(containingBlock)) { + if (containingBlock.labelText === labelText) { + return true; + } + } + else { + break; + } + } + return false; + } + /** + * Finds the label that is the target for a `break` statement. + * + * @param labelText An optional name of a containing labeled statement. + */ + function findBreakTarget(labelText) { + if (blockStack) { + if (labelText) { + for (var i = blockStack.length - 1; i >= 0; i--) { + var block = blockStack[i]; + if (supportsLabeledBreakOrContinue(block) && block.labelText === labelText) { + return block.breakLabel; + } + else if (supportsUnlabeledBreak(block) && hasImmediateContainingLabeledBlock(labelText, i - 1)) { + return block.breakLabel; + } + } + } + else { + for (var i = blockStack.length - 1; i >= 0; i--) { + var block = blockStack[i]; + if (supportsUnlabeledBreak(block)) { + return block.breakLabel; + } + } + } + } + return 0; + } + /** + * Finds the label that is the target for a `continue` statement. + * + * @param labelText An optional name of a containing labeled statement. + */ + function findContinueTarget(labelText) { + if (blockStack) { + if (labelText) { + for (var i = blockStack.length - 1; i >= 0; i--) { + var block = blockStack[i]; + if (supportsUnlabeledContinue(block) && hasImmediateContainingLabeledBlock(labelText, i - 1)) { + return block.continueLabel; + } + } + } + else { + for (var i = blockStack.length - 1; i >= 0; i--) { + var block = blockStack[i]; + if (supportsUnlabeledContinue(block)) { + return block.continueLabel; + } + } + } + } + return 0; + } + /** + * Creates an expression that can be used to indicate the value for a label. + * + * @param label A label. + */ + function createLabel(label) { + if (label !== undefined && label > 0) { + if (labelExpressions === undefined) { + labelExpressions = []; + } + var expression = ts.createLiteral(-1); + if (labelExpressions[label] === undefined) { + labelExpressions[label] = [expression]; + } + else { + labelExpressions[label].push(expression); + } + return expression; + } + return ts.createOmittedExpression(); + } + /** + * Creates a numeric literal for the provided instruction. + */ + function createInstruction(instruction) { + var literal = ts.createLiteral(instruction); + ts.addSyntheticTrailingComment(literal, 3 /* MultiLineCommentTrivia */, getInstructionName(instruction)); + return literal; + } + /** + * Creates a statement that can be used indicate a Break operation to the provided label. + * + * @param label A label. + * @param location An optional source map location for the statement. + */ + function createInlineBreak(label, location) { + ts.Debug.assertLessThan(0, label, "Invalid label"); + return ts.setTextRange(ts.createReturn(ts.createArrayLiteral([ + createInstruction(3 /* Break */), + createLabel(label) + ])), location); + } + /** + * Creates a statement that can be used indicate a Return operation. + * + * @param expression The expression for the return statement. + * @param location An optional source map location for the statement. + */ + function createInlineReturn(expression, location) { + return ts.setTextRange(ts.createReturn(ts.createArrayLiteral(expression + ? [createInstruction(2 /* Return */), expression] + : [createInstruction(2 /* Return */)])), location); + } + /** + * Creates an expression that can be used to resume from a Yield operation. + */ + function createGeneratorResume(location) { + return ts.setTextRange(ts.createCall(ts.createPropertyAccess(state, "sent"), + /*typeArguments*/ undefined, []), location); + } + /** + * Emits an empty instruction. + */ + function emitNop() { + emitWorker(0 /* Nop */); + } + /** + * Emits a Statement. + * + * @param node A statement. + */ + function emitStatement(node) { + if (node) { + emitWorker(1 /* Statement */, [node]); + } + else { + emitNop(); + } + } + /** + * Emits an Assignment operation. + * + * @param left The left-hand side of the assignment. + * @param right The right-hand side of the assignment. + * @param location An optional source map location for the assignment. + */ + function emitAssignment(left, right, location) { + emitWorker(2 /* Assign */, [left, right], location); + } + /** + * Emits a Break operation to the specified label. + * + * @param label A label. + * @param location An optional source map location for the assignment. + */ + function emitBreak(label, location) { + emitWorker(3 /* Break */, [label], location); + } + /** + * Emits a Break operation to the specified label when a condition evaluates to a truthy + * value at runtime. + * + * @param label A label. + * @param condition The condition. + * @param location An optional source map location for the assignment. + */ + function emitBreakWhenTrue(label, condition, location) { + emitWorker(4 /* BreakWhenTrue */, [label, condition], location); + } + /** + * Emits a Break to the specified label when a condition evaluates to a falsey value at + * runtime. + * + * @param label A label. + * @param condition The condition. + * @param location An optional source map location for the assignment. + */ + function emitBreakWhenFalse(label, condition, location) { + emitWorker(5 /* BreakWhenFalse */, [label, condition], location); + } + /** + * Emits a YieldStar operation for the provided expression. + * + * @param expression An optional value for the yield operation. + * @param location An optional source map location for the assignment. + */ + function emitYieldStar(expression, location) { + emitWorker(7 /* YieldStar */, [expression], location); + } + /** + * Emits a Yield operation for the provided expression. + * + * @param expression An optional value for the yield operation. + * @param location An optional source map location for the assignment. + */ + function emitYield(expression, location) { + emitWorker(6 /* Yield */, [expression], location); + } + /** + * Emits a Return operation for the provided expression. + * + * @param expression An optional value for the operation. + * @param location An optional source map location for the assignment. + */ + function emitReturn(expression, location) { + emitWorker(8 /* Return */, [expression], location); + } + /** + * Emits a Throw operation for the provided expression. + * + * @param expression A value for the operation. + * @param location An optional source map location for the assignment. + */ + function emitThrow(expression, location) { + emitWorker(9 /* Throw */, [expression], location); + } + /** + * Emits an Endfinally operation. This is used to handle `finally` block semantics. + */ + function emitEndfinally() { + emitWorker(10 /* Endfinally */); + } + /** + * Emits an operation. + * + * @param code The OpCode for the operation. + * @param args The optional arguments for the operation. + */ + function emitWorker(code, args, location) { + if (operations === undefined) { + operations = []; + operationArguments = []; + operationLocations = []; + } + if (labelOffsets === undefined) { + // mark entry point + markLabel(defineLabel()); + } + var operationIndex = operations.length; + operations[operationIndex] = code; + operationArguments[operationIndex] = args; + operationLocations[operationIndex] = location; + } + /** + * Builds the generator function body. + */ + function build() { + blockIndex = 0; + labelNumber = 0; + labelNumbers = undefined; + lastOperationWasAbrupt = false; + lastOperationWasCompletion = false; + clauses = undefined; + statements = undefined; + exceptionBlockStack = undefined; + currentExceptionBlock = undefined; + withBlockStack = undefined; + var buildResult = buildStatements(); + return createGeneratorHelper(context, ts.setEmitFlags(ts.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, state)], + /*type*/ undefined, ts.createBlock(buildResult, + /*multiLine*/ buildResult.length > 0)), 524288 /* ReuseTempVariableScope */)); + } + /** + * Builds the statements for the generator function body. + */ + function buildStatements() { + if (operations) { + for (var operationIndex = 0; operationIndex < operations.length; operationIndex++) { + writeOperation(operationIndex); + } + flushFinalLabel(operations.length); + } + else { + flushFinalLabel(0); + } + if (clauses) { + var labelExpression = ts.createPropertyAccess(state, "label"); + var switchStatement = ts.createSwitch(labelExpression, ts.createCaseBlock(clauses)); + return [ts.startOnNewLine(switchStatement)]; + } + if (statements) { + return statements; + } + return []; + } + /** + * Flush the current label and advance to a new label. + */ + function flushLabel() { + if (!statements) { + return; + } + appendLabel(/*markLabelEnd*/ !lastOperationWasAbrupt); + lastOperationWasAbrupt = false; + lastOperationWasCompletion = false; + labelNumber++; + } + /** + * Flush the final label of the generator function body. + */ + function flushFinalLabel(operationIndex) { + if (isFinalLabelReachable(operationIndex)) { + tryEnterLabel(operationIndex); + withBlockStack = undefined; + writeReturn(/*expression*/ undefined, /*operationLocation*/ undefined); + } + if (statements && clauses) { + appendLabel(/*markLabelEnd*/ false); + } + updateLabelExpressions(); + } + /** + * Tests whether the final label of the generator function body + * is reachable by user code. + */ + function isFinalLabelReachable(operationIndex) { + // if the last operation was *not* a completion (return/throw) then + // the final label is reachable. + if (!lastOperationWasCompletion) { + return true; + } + // if there are no labels defined or referenced, then the final label is + // not reachable. + if (!labelOffsets || !labelExpressions) { + return false; + } + // if the label for this offset is referenced, then the final label + // is reachable. + for (var label = 0; label < labelOffsets.length; label++) { + if (labelOffsets[label] === operationIndex && labelExpressions[label]) { + return true; + } + } + return false; + } + /** + * Appends a case clause for the last label and sets the new label. + * + * @param markLabelEnd Indicates that the transition between labels was a fall-through + * from a previous case clause and the change in labels should be + * reflected on the `state` object. + */ + function appendLabel(markLabelEnd) { + if (!clauses) { + clauses = []; + } + if (statements) { + if (withBlockStack) { + // The previous label was nested inside one or more `with` blocks, so we + // surround the statements in generated `with` blocks to create the same environment. + for (var i = withBlockStack.length - 1; i >= 0; i--) { + var withBlock = withBlockStack[i]; + statements = [ts.createWith(withBlock.expression, ts.createBlock(statements))]; + } + } + if (currentExceptionBlock) { + // The previous label was nested inside of an exception block, so we must + // indicate entry into a protected region by pushing the label numbers + // for each block in the protected region. + var startLabel = currentExceptionBlock.startLabel, catchLabel = currentExceptionBlock.catchLabel, finallyLabel = currentExceptionBlock.finallyLabel, endLabel = currentExceptionBlock.endLabel; + statements.unshift(ts.createExpressionStatement(ts.createCall(ts.createPropertyAccess(ts.createPropertyAccess(state, "trys"), "push"), + /*typeArguments*/ undefined, [ + ts.createArrayLiteral([ + createLabel(startLabel), + createLabel(catchLabel), + createLabel(finallyLabel), + createLabel(endLabel) + ]) + ]))); + currentExceptionBlock = undefined; + } + if (markLabelEnd) { + // The case clause for the last label falls through to this label, so we + // add an assignment statement to reflect the change in labels. + statements.push(ts.createExpressionStatement(ts.createAssignment(ts.createPropertyAccess(state, "label"), ts.createLiteral(labelNumber + 1)))); + } + } + clauses.push(ts.createCaseClause(ts.createLiteral(labelNumber), statements || [])); + statements = undefined; + } + /** + * Tries to enter into a new label at the current operation index. + */ + function tryEnterLabel(operationIndex) { + if (!labelOffsets) { + return; + } + for (var label = 0; label < labelOffsets.length; label++) { + if (labelOffsets[label] === operationIndex) { + flushLabel(); + if (labelNumbers === undefined) { + labelNumbers = []; + } + if (labelNumbers[labelNumber] === undefined) { + labelNumbers[labelNumber] = [label]; + } + else { + labelNumbers[labelNumber].push(label); + } + } + } + } + /** + * Updates literal expressions for labels with actual label numbers. + */ + function updateLabelExpressions() { + if (labelExpressions !== undefined && labelNumbers !== undefined) { + for (var labelNumber_1 = 0; labelNumber_1 < labelNumbers.length; labelNumber_1++) { + var labels = labelNumbers[labelNumber_1]; + if (labels !== undefined) { + for (var _i = 0, labels_1 = labels; _i < labels_1.length; _i++) { + var label = labels_1[_i]; + var expressions = labelExpressions[label]; + if (expressions !== undefined) { + for (var _a = 0, expressions_1 = expressions; _a < expressions_1.length; _a++) { + var expression = expressions_1[_a]; + expression.text = String(labelNumber_1); + } + } + } + } + } + } + } + /** + * Tries to enter or leave a code block. + */ + function tryEnterOrLeaveBlock(operationIndex) { + if (blocks) { + for (; blockIndex < blockActions.length && blockOffsets[blockIndex] <= operationIndex; blockIndex++) { + var block = blocks[blockIndex]; + var blockAction = blockActions[blockIndex]; + switch (block.kind) { + case 0 /* Exception */: + if (blockAction === 0 /* Open */) { + if (!exceptionBlockStack) { + exceptionBlockStack = []; + } + if (!statements) { + statements = []; + } + exceptionBlockStack.push(currentExceptionBlock); + currentExceptionBlock = block; + } + else if (blockAction === 1 /* Close */) { + currentExceptionBlock = exceptionBlockStack.pop(); + } + break; + case 1 /* With */: + if (blockAction === 0 /* Open */) { + if (!withBlockStack) { + withBlockStack = []; + } + withBlockStack.push(block); + } + else if (blockAction === 1 /* Close */) { + withBlockStack.pop(); + } + break; + // default: do nothing + } + } + } + } + /** + * Writes an operation as a statement to the current label's statement list. + * + * @param operation The OpCode of the operation + */ + function writeOperation(operationIndex) { + tryEnterLabel(operationIndex); + tryEnterOrLeaveBlock(operationIndex); + // early termination, nothing else to process in this label + if (lastOperationWasAbrupt) { + return; + } + lastOperationWasAbrupt = false; + lastOperationWasCompletion = false; + var opcode = operations[operationIndex]; + if (opcode === 0 /* Nop */) { + return; + } + else if (opcode === 10 /* Endfinally */) { + return writeEndfinally(); + } + var args = operationArguments[operationIndex]; + if (opcode === 1 /* Statement */) { + return writeStatement(args[0]); + } + var location = operationLocations[operationIndex]; + switch (opcode) { + case 2 /* Assign */: + return writeAssign(args[0], args[1], location); + case 3 /* Break */: + return writeBreak(args[0], location); + case 4 /* BreakWhenTrue */: + return writeBreakWhenTrue(args[0], args[1], location); + case 5 /* BreakWhenFalse */: + return writeBreakWhenFalse(args[0], args[1], location); + case 6 /* Yield */: + return writeYield(args[0], location); + case 7 /* YieldStar */: + return writeYieldStar(args[0], location); + case 8 /* Return */: + return writeReturn(args[0], location); + case 9 /* Throw */: + return writeThrow(args[0], location); + } + } + /** + * Writes a statement to the current label's statement list. + * + * @param statement A statement to write. + */ + function writeStatement(statement) { + if (statement) { + if (!statements) { + statements = [statement]; + } + else { + statements.push(statement); + } + } + } + /** + * Writes an Assign operation to the current label's statement list. + * + * @param left The left-hand side of the assignment. + * @param right The right-hand side of the assignment. + * @param operationLocation The source map location for the operation. + */ + function writeAssign(left, right, operationLocation) { + writeStatement(ts.setTextRange(ts.createExpressionStatement(ts.createAssignment(left, right)), operationLocation)); + } + /** + * Writes a Throw operation to the current label's statement list. + * + * @param expression The value to throw. + * @param operationLocation The source map location for the operation. + */ + function writeThrow(expression, operationLocation) { + lastOperationWasAbrupt = true; + lastOperationWasCompletion = true; + writeStatement(ts.setTextRange(ts.createThrow(expression), operationLocation)); + } + /** + * Writes a Return operation to the current label's statement list. + * + * @param expression The value to return. + * @param operationLocation The source map location for the operation. + */ + function writeReturn(expression, operationLocation) { + lastOperationWasAbrupt = true; + lastOperationWasCompletion = true; + writeStatement(ts.setEmitFlags(ts.setTextRange(ts.createReturn(ts.createArrayLiteral(expression + ? [createInstruction(2 /* Return */), expression] + : [createInstruction(2 /* Return */)])), operationLocation), 384 /* NoTokenSourceMaps */)); + } + /** + * Writes a Break operation to the current label's statement list. + * + * @param label The label for the Break. + * @param operationLocation The source map location for the operation. + */ + function writeBreak(label, operationLocation) { + lastOperationWasAbrupt = true; + writeStatement(ts.setEmitFlags(ts.setTextRange(ts.createReturn(ts.createArrayLiteral([ + createInstruction(3 /* Break */), + createLabel(label) + ])), operationLocation), 384 /* NoTokenSourceMaps */)); + } + /** + * Writes a BreakWhenTrue operation to the current label's statement list. + * + * @param label The label for the Break. + * @param condition The condition for the Break. + * @param operationLocation The source map location for the operation. + */ + function writeBreakWhenTrue(label, condition, operationLocation) { + writeStatement(ts.setEmitFlags(ts.createIf(condition, ts.setEmitFlags(ts.setTextRange(ts.createReturn(ts.createArrayLiteral([ + createInstruction(3 /* Break */), + createLabel(label) + ])), operationLocation), 384 /* NoTokenSourceMaps */)), 1 /* SingleLine */)); + } + /** + * Writes a BreakWhenFalse operation to the current label's statement list. + * + * @param label The label for the Break. + * @param condition The condition for the Break. + * @param operationLocation The source map location for the operation. + */ + function writeBreakWhenFalse(label, condition, operationLocation) { + writeStatement(ts.setEmitFlags(ts.createIf(ts.createLogicalNot(condition), ts.setEmitFlags(ts.setTextRange(ts.createReturn(ts.createArrayLiteral([ + createInstruction(3 /* Break */), + createLabel(label) + ])), operationLocation), 384 /* NoTokenSourceMaps */)), 1 /* SingleLine */)); + } + /** + * Writes a Yield operation to the current label's statement list. + * + * @param expression The expression to yield. + * @param operationLocation The source map location for the operation. + */ + function writeYield(expression, operationLocation) { + lastOperationWasAbrupt = true; + writeStatement(ts.setEmitFlags(ts.setTextRange(ts.createReturn(ts.createArrayLiteral(expression + ? [createInstruction(4 /* Yield */), expression] + : [createInstruction(4 /* Yield */)])), operationLocation), 384 /* NoTokenSourceMaps */)); + } + /** + * Writes a YieldStar instruction to the current label's statement list. + * + * @param expression The expression to yield. + * @param operationLocation The source map location for the operation. + */ + function writeYieldStar(expression, operationLocation) { + lastOperationWasAbrupt = true; + writeStatement(ts.setEmitFlags(ts.setTextRange(ts.createReturn(ts.createArrayLiteral([ + createInstruction(5 /* YieldStar */), + expression + ])), operationLocation), 384 /* NoTokenSourceMaps */)); + } + /** + * Writes an Endfinally instruction to the current label's statement list. + */ + function writeEndfinally() { + lastOperationWasAbrupt = true; + writeStatement(ts.createReturn(ts.createArrayLiteral([ + createInstruction(7 /* Endfinally */) + ]))); + } + } + ts.transformGenerators = transformGenerators; + function createGeneratorHelper(context, body) { + context.requestEmitHelper(generatorHelper); + return ts.createCall(ts.getHelperName("__generator"), + /*typeArguments*/ undefined, [ts.createThis(), body]); + } + // The __generator helper is used by down-level transformations to emulate the runtime + // semantics of an ES2015 generator function. When called, this helper returns an + // object that implements the Iterator protocol, in that it has `next`, `return`, and + // `throw` methods that step through the generator when invoked. + // + // parameters: + // @param thisArg The value to use as the `this` binding for the transformed generator body. + // @param body A function that acts as the transformed generator body. + // + // variables: + // _ Persistent state for the generator that is shared between the helper and the + // generator body. The state object has the following members: + // sent() - A method that returns or throws the current completion value. + // label - The next point at which to resume evaluation of the generator body. + // trys - A stack of protected regions (try/catch/finally blocks). + // ops - A stack of pending instructions when inside of a finally block. + // f A value indicating whether the generator is executing. + // y An iterator to delegate for a yield*. + // t A temporary variable that holds one of the following values (note that these + // cases do not overlap): + // - The completion value when resuming from a `yield` or `yield*`. + // - The error value for a catch block. + // - The current protected region (array of try/catch/finally/end labels). + // - The verb (`next`, `throw`, or `return` method) to delegate to the expression + // of a `yield*`. + // - The result of evaluating the verb delegated to the expression of a `yield*`. + // + // functions: + // verb(n) Creates a bound callback to the `step` function for opcode `n`. + // step(op) Evaluates opcodes in a generator body until execution is suspended or + // completed. + // + // The __generator helper understands a limited set of instructions: + // 0: next(value?) - Start or resume the generator with the specified value. + // 1: throw(error) - Resume the generator with an exception. If the generator is + // suspended inside of one or more protected regions, evaluates + // any intervening finally blocks between the current label and + // the nearest catch block or function boundary. If uncaught, the + // exception is thrown to the caller. + // 2: return(value?) - Resume the generator as if with a return. If the generator is + // suspended inside of one or more protected regions, evaluates any + // intervening finally blocks. + // 3: break(label) - Jump to the specified label. If the label is outside of the + // current protected region, evaluates any intervening finally + // blocks. + // 4: yield(value?) - Yield execution to the caller with an optional value. When + // resumed, the generator will continue at the next label. + // 5: yield*(value) - Delegates evaluation to the supplied iterator. When + // delegation completes, the generator will continue at the next + // label. + // 6: catch(error) - Handles an exception thrown from within the generator body. If + // the current label is inside of one or more protected regions, + // evaluates any intervening finally blocks between the current + // label and the nearest catch block or function boundary. If + // uncaught, the exception is thrown to the caller. + // 7: endfinally - Ends a finally block, resuming the last instruction prior to + // entering a finally block. + // + // For examples of how these are used, see the comments in ./transformers/generators.ts + var generatorHelper = { + name: "typescript:generator", + scoped: false, + priority: 6, + text: "\n var __generator = (this && this.__generator) || function (thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (_) try {\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [op[0] & 2, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n };" + }; +})(ts || (ts = {})); +/*@internal*/ +var ts; +(function (ts) { + function transformModule(context) { + function getTransformModuleDelegate(moduleKind) { + switch (moduleKind) { + case ts.ModuleKind.AMD: return transformAMDModule; + case ts.ModuleKind.UMD: return transformUMDModule; + default: return transformCommonJSModule; + } + } + var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; + var compilerOptions = context.getCompilerOptions(); + var resolver = context.getEmitResolver(); + var host = context.getEmitHost(); + var languageVersion = ts.getEmitScriptTarget(compilerOptions); + var moduleKind = ts.getEmitModuleKind(compilerOptions); + var previousOnSubstituteNode = context.onSubstituteNode; + var previousOnEmitNode = context.onEmitNode; + context.onSubstituteNode = onSubstituteNode; + context.onEmitNode = onEmitNode; + context.enableSubstitution(72 /* Identifier */); // Substitutes expression identifiers with imported/exported symbols. + context.enableSubstitution(204 /* BinaryExpression */); // Substitutes assignments to exported symbols. + context.enableSubstitution(202 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols. + context.enableSubstitution(203 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols. + context.enableSubstitution(276 /* ShorthandPropertyAssignment */); // Substitutes shorthand property assignments for imported/exported symbols. + context.enableEmitNotification(279 /* SourceFile */); // Restore state when substituting nodes in a file. + var moduleInfoMap = []; // The ExternalModuleInfo for each file. + var deferredExports = []; // Exports to defer until an EndOfDeclarationMarker is found. + var currentSourceFile; // The current file. + var currentModuleInfo; // The ExternalModuleInfo for the current file. + var noSubstitution; // Set of nodes for which substitution rules should be ignored. + var needUMDDynamicImportHelper; + return ts.chainBundle(transformSourceFile); + /** + * Transforms the module aspects of a SourceFile. + * + * @param node The SourceFile node. + */ + function transformSourceFile(node) { + if (node.isDeclarationFile || + !(ts.isEffectiveExternalModule(node, compilerOptions) || + node.transformFlags & 16777216 /* ContainsDynamicImport */ || + (ts.isJsonSourceFile(node) && ts.hasJsonModuleEmitEnabled(compilerOptions) && (compilerOptions.out || compilerOptions.outFile)))) { + return node; + } + currentSourceFile = node; + currentModuleInfo = ts.collectExternalModuleInfo(node, resolver, compilerOptions); + moduleInfoMap[ts.getOriginalNodeId(node)] = currentModuleInfo; + // Perform the transformation. + var transformModule = getTransformModuleDelegate(moduleKind); + var updated = transformModule(node); + currentSourceFile = undefined; + currentModuleInfo = undefined; + needUMDDynamicImportHelper = false; + return ts.aggregateTransformFlags(updated); + } + function shouldEmitUnderscoreUnderscoreESModule() { + if (!currentModuleInfo.exportEquals && ts.isExternalModule(currentSourceFile)) { + return true; + } + return false; + } + /** + * Transforms a SourceFile into a CommonJS module. + * + * @param node The SourceFile node. + */ + function transformCommonJSModule(node) { + startLexicalEnvironment(); + var statements = []; + var ensureUseStrict = ts.getStrictOptionValue(compilerOptions, "alwaysStrict") || (!compilerOptions.noImplicitUseStrict && ts.isExternalModule(currentSourceFile)); + var statementOffset = ts.addPrologue(statements, node.statements, ensureUseStrict, sourceElementVisitor); + if (shouldEmitUnderscoreUnderscoreESModule()) { + ts.append(statements, createUnderscoreUnderscoreESModule()); + } + ts.append(statements, ts.visitNode(currentModuleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement)); + ts.addRange(statements, ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset)); + addExportEqualsIfNeeded(statements, /*emitAsReturn*/ false); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + var updated = ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements)); + if (currentModuleInfo.hasExportStarsToExportValues && !compilerOptions.importHelpers) { + // If we have any `export * from ...` declarations + // we need to inform the emitter to add the __export helper. + ts.addEmitHelper(updated, exportStarHelper); + } + ts.addEmitHelpers(updated, context.readEmitHelpers()); + return updated; + } + /** + * Transforms a SourceFile into an AMD module. + * + * @param node The SourceFile node. + */ + function transformAMDModule(node) { + var define = ts.createIdentifier("define"); + var moduleName = ts.tryGetModuleNameFromFile(node, host, compilerOptions); + var jsonSourceFile = ts.isJsonSourceFile(node) && node; + // An AMD define function has the following shape: + // + // define(id?, dependencies?, factory); + // + // This has the shape of the following: + // + // define(name, ["module1", "module2"], function (module1Alias) { ... } + // + // The location of the alias in the parameter list in the factory function needs to + // match the position of the module name in the dependency list. + // + // To ensure this is true in cases of modules with no aliases, e.g.: + // + // import "module" + // + // or + // + // /// + // + // we need to add modules without alias names to the end of the dependencies list + var _a = collectAsynchronousDependencies(node, /*includeNonAmdDependencies*/ true), aliasedModuleNames = _a.aliasedModuleNames, unaliasedModuleNames = _a.unaliasedModuleNames, importAliasNames = _a.importAliasNames; + // Create an updated SourceFile: + // + // define(moduleName?, ["module1", "module2"], function ... + var updated = ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray([ + ts.createExpressionStatement(ts.createCall(define, + /*typeArguments*/ undefined, (moduleName ? [moduleName] : []).concat([ + // Add the dependency array argument: + // + // ["require", "exports", module1", "module2", ...] + ts.createArrayLiteral(jsonSourceFile ? ts.emptyArray : [ + ts.createLiteral("require"), + ts.createLiteral("exports") + ].concat(aliasedModuleNames, unaliasedModuleNames)), + // Add the module body function argument: + // + // function (require, exports, module1, module2) ... + jsonSourceFile ? + jsonSourceFile.statements.length ? jsonSourceFile.statements[0].expression : ts.createObjectLiteral() : + ts.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, [ + ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "require"), + ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "exports") + ].concat(importAliasNames), + /*type*/ undefined, transformAsynchronousModuleBody(node)) + ]))) + ]), + /*location*/ node.statements)); + ts.addEmitHelpers(updated, context.readEmitHelpers()); + return updated; + } + /** + * Transforms a SourceFile into a UMD module. + * + * @param node The SourceFile node. + */ + function transformUMDModule(node) { + var _a = collectAsynchronousDependencies(node, /*includeNonAmdDependencies*/ false), aliasedModuleNames = _a.aliasedModuleNames, unaliasedModuleNames = _a.unaliasedModuleNames, importAliasNames = _a.importAliasNames; + var moduleName = ts.tryGetModuleNameFromFile(node, host, compilerOptions); + var umdHeader = ts.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "factory")], + /*type*/ undefined, ts.setTextRange(ts.createBlock([ + ts.createIf(ts.createLogicalAnd(ts.createTypeCheck(ts.createIdentifier("module"), "object"), ts.createTypeCheck(ts.createPropertyAccess(ts.createIdentifier("module"), "exports"), "object")), ts.createBlock([ + ts.createVariableStatement( + /*modifiers*/ undefined, [ + ts.createVariableDeclaration("v", + /*type*/ undefined, ts.createCall(ts.createIdentifier("factory"), + /*typeArguments*/ undefined, [ + ts.createIdentifier("require"), + ts.createIdentifier("exports") + ])) + ]), + ts.setEmitFlags(ts.createIf(ts.createStrictInequality(ts.createIdentifier("v"), ts.createIdentifier("undefined")), ts.createExpressionStatement(ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier("module"), "exports"), ts.createIdentifier("v")))), 1 /* SingleLine */) + ]), ts.createIf(ts.createLogicalAnd(ts.createTypeCheck(ts.createIdentifier("define"), "function"), ts.createPropertyAccess(ts.createIdentifier("define"), "amd")), ts.createBlock([ + ts.createExpressionStatement(ts.createCall(ts.createIdentifier("define"), + /*typeArguments*/ undefined, (moduleName ? [moduleName] : []).concat([ + ts.createArrayLiteral([ + ts.createLiteral("require"), + ts.createLiteral("exports") + ].concat(aliasedModuleNames, unaliasedModuleNames)), + ts.createIdentifier("factory") + ]))) + ]))) + ], + /*multiLine*/ true), + /*location*/ undefined)); + // Create an updated SourceFile: + // + // (function (factory) { + // if (typeof module === "object" && typeof module.exports === "object") { + // var v = factory(require, exports); + // if (v !== undefined) module.exports = v; + // } + // else if (typeof define === 'function' && define.amd) { + // define(["require", "exports"], factory); + // } + // })(function ...) + var updated = ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray([ + ts.createExpressionStatement(ts.createCall(umdHeader, + /*typeArguments*/ undefined, [ + // Add the module body function argument: + // + // function (require, exports) ... + ts.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, [ + ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "require"), + ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "exports") + ].concat(importAliasNames), + /*type*/ undefined, transformAsynchronousModuleBody(node)) + ])) + ]), + /*location*/ node.statements)); + ts.addEmitHelpers(updated, context.readEmitHelpers()); + return updated; + } + /** + * Collect the additional asynchronous dependencies for the module. + * + * @param node The source file. + * @param includeNonAmdDependencies A value indicating whether to include non-AMD dependencies. + */ + function collectAsynchronousDependencies(node, includeNonAmdDependencies) { + // names of modules with corresponding parameter in the factory function + var aliasedModuleNames = []; + // names of modules with no corresponding parameters in factory function + var unaliasedModuleNames = []; + // names of the parameters in the factory function; these + // parameters need to match the indexes of the corresponding + // module names in aliasedModuleNames. + var importAliasNames = []; + // Fill in amd-dependency tags + for (var _i = 0, _a = node.amdDependencies; _i < _a.length; _i++) { + var amdDependency = _a[_i]; + if (amdDependency.name) { + aliasedModuleNames.push(ts.createLiteral(amdDependency.path)); + importAliasNames.push(ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, amdDependency.name)); + } + else { + unaliasedModuleNames.push(ts.createLiteral(amdDependency.path)); + } + } + for (var _b = 0, _c = currentModuleInfo.externalImports; _b < _c.length; _b++) { + var importNode = _c[_b]; + // Find the name of the external module + var externalModuleName = ts.getExternalModuleNameLiteral(importNode, currentSourceFile, host, resolver, compilerOptions); + // Find the name of the module alias, if there is one + var importAliasName = ts.getLocalNameForExternalImport(importNode, currentSourceFile); + // It is possible that externalModuleName is undefined if it is not string literal. + // This can happen in the invalid import syntax. + // E.g : "import * from alias from 'someLib';" + if (externalModuleName) { + if (includeNonAmdDependencies && importAliasName) { + // Set emitFlags on the name of the classDeclaration + // This is so that when printer will not substitute the identifier + ts.setEmitFlags(importAliasName, 4 /* NoSubstitution */); + aliasedModuleNames.push(externalModuleName); + importAliasNames.push(ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, importAliasName)); + } + else { + unaliasedModuleNames.push(externalModuleName); + } + } + } + return { aliasedModuleNames: aliasedModuleNames, unaliasedModuleNames: unaliasedModuleNames, importAliasNames: importAliasNames }; + } + function getAMDImportExpressionForImport(node) { + if (ts.isImportEqualsDeclaration(node) || ts.isExportDeclaration(node) || !ts.getExternalModuleNameLiteral(node, currentSourceFile, host, resolver, compilerOptions)) { + return undefined; + } + var name = ts.getLocalNameForExternalImport(node, currentSourceFile); // TODO: GH#18217 + var expr = getHelperExpressionForImport(node, name); + if (expr === name) { + return undefined; + } + return ts.createExpressionStatement(ts.createAssignment(name, expr)); + } + /** + * Transforms a SourceFile into an AMD or UMD module body. + * + * @param node The SourceFile node. + */ + function transformAsynchronousModuleBody(node) { + startLexicalEnvironment(); + var statements = []; + var statementOffset = ts.addPrologue(statements, node.statements, /*ensureUseStrict*/ !compilerOptions.noImplicitUseStrict, sourceElementVisitor); + if (shouldEmitUnderscoreUnderscoreESModule()) { + ts.append(statements, createUnderscoreUnderscoreESModule()); + } + // Visit each statement of the module body. + ts.append(statements, ts.visitNode(currentModuleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement)); + if (moduleKind === ts.ModuleKind.AMD) { + ts.addRange(statements, ts.mapDefined(currentModuleInfo.externalImports, getAMDImportExpressionForImport)); + } + ts.addRange(statements, ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset)); + // Append the 'export =' statement if provided. + addExportEqualsIfNeeded(statements, /*emitAsReturn*/ true); + // End the lexical environment for the module body + // and merge any new lexical declarations. + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + var body = ts.createBlock(statements, /*multiLine*/ true); + if (currentModuleInfo.hasExportStarsToExportValues && !compilerOptions.importHelpers) { + // If we have any `export * from ...` declarations + // we need to inform the emitter to add the __export helper. + ts.addEmitHelper(body, exportStarHelper); + } + if (needUMDDynamicImportHelper) { + ts.addEmitHelper(body, dynamicImportUMDHelper); + } + return body; + } + /** + * Adds the down-level representation of `export=` to the statement list if one exists + * in the source file. + * + * @param statements The Statement list to modify. + * @param emitAsReturn A value indicating whether to emit the `export=` statement as a + * return statement. + */ + function addExportEqualsIfNeeded(statements, emitAsReturn) { + if (currentModuleInfo.exportEquals) { + var expressionResult = ts.visitNode(currentModuleInfo.exportEquals.expression, moduleExpressionElementVisitor); + if (expressionResult) { + if (emitAsReturn) { + var statement = ts.createReturn(expressionResult); + ts.setTextRange(statement, currentModuleInfo.exportEquals); + ts.setEmitFlags(statement, 384 /* NoTokenSourceMaps */ | 1536 /* NoComments */); + statements.push(statement); + } + else { + var statement = ts.createExpressionStatement(ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier("module"), "exports"), expressionResult)); + ts.setTextRange(statement, currentModuleInfo.exportEquals); + ts.setEmitFlags(statement, 1536 /* NoComments */); + statements.push(statement); + } + } + } + } + // + // Top-Level Source Element Visitors + // + /** + * Visits a node at the top level of the source file. + * + * @param node The node to visit. + */ + function sourceElementVisitor(node) { + switch (node.kind) { + case 249 /* ImportDeclaration */: + return visitImportDeclaration(node); + case 248 /* ImportEqualsDeclaration */: + return visitImportEqualsDeclaration(node); + case 255 /* ExportDeclaration */: + return visitExportDeclaration(node); + case 254 /* ExportAssignment */: + return visitExportAssignment(node); + case 219 /* VariableStatement */: + return visitVariableStatement(node); + case 239 /* FunctionDeclaration */: + return visitFunctionDeclaration(node); + case 240 /* ClassDeclaration */: + return visitClassDeclaration(node); + case 310 /* MergeDeclarationMarker */: + return visitMergeDeclarationMarker(node); + case 311 /* EndOfDeclarationMarker */: + return visitEndOfDeclarationMarker(node); + default: + return ts.visitEachChild(node, moduleExpressionElementVisitor, context); + } + } + function moduleExpressionElementVisitor(node) { + // This visitor does not need to descend into the tree if there is no dynamic import or destructuring assignment, + // as export/import statements are only transformed at the top level of a file. + if (!(node.transformFlags & 16777216 /* ContainsDynamicImport */) && !(node.transformFlags & 2048 /* ContainsDestructuringAssignment */)) { + return node; + } + if (ts.isImportCall(node)) { + return visitImportCallExpression(node); + } + else if (node.transformFlags & 1024 /* DestructuringAssignment */ && ts.isBinaryExpression(node)) { + return visitDestructuringAssignment(node); + } + else { + return ts.visitEachChild(node, moduleExpressionElementVisitor, context); + } + } + function destructuringNeedsFlattening(node) { + if (ts.isObjectLiteralExpression(node)) { + for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { + var elem = _a[_i]; + switch (elem.kind) { + case 275 /* PropertyAssignment */: + if (destructuringNeedsFlattening(elem.initializer)) { + return true; + } + break; + case 276 /* ShorthandPropertyAssignment */: + if (destructuringNeedsFlattening(elem.name)) { + return true; + } + break; + case 277 /* SpreadAssignment */: + if (destructuringNeedsFlattening(elem.expression)) { + return true; + } + break; + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + return false; + default: ts.Debug.assertNever(elem, "Unhandled object member kind"); + } + } + } + else if (ts.isArrayLiteralExpression(node)) { + for (var _b = 0, _c = node.elements; _b < _c.length; _b++) { + var elem = _c[_b]; + if (ts.isSpreadElement(elem)) { + if (destructuringNeedsFlattening(elem.expression)) { + return true; + } + } + else if (destructuringNeedsFlattening(elem)) { + return true; + } + } + } + else if (ts.isIdentifier(node)) { + return ts.length(getExports(node)) > (ts.isExportName(node) ? 1 : 0); + } + return false; + } + function visitDestructuringAssignment(node) { + if (destructuringNeedsFlattening(node.left)) { + return ts.flattenDestructuringAssignment(node, moduleExpressionElementVisitor, context, 0 /* All */, /*needsValue*/ false, createAllExportExpressions); + } + return ts.visitEachChild(node, moduleExpressionElementVisitor, context); + } + function visitImportCallExpression(node) { + var argument = ts.visitNode(ts.firstOrUndefined(node.arguments), moduleExpressionElementVisitor); + var containsLexicalThis = !!(node.transformFlags & 8192 /* ContainsLexicalThis */); + switch (compilerOptions.module) { + case ts.ModuleKind.AMD: + return createImportCallExpressionAMD(argument, containsLexicalThis); + case ts.ModuleKind.UMD: + return createImportCallExpressionUMD(argument, containsLexicalThis); + case ts.ModuleKind.CommonJS: + default: + return createImportCallExpressionCommonJS(argument, containsLexicalThis); + } + } + function createImportCallExpressionUMD(arg, containsLexicalThis) { + // (function (factory) { + // ... (regular UMD) + // } + // })(function (require, exports, useSyncRequire) { + // "use strict"; + // Object.defineProperty(exports, "__esModule", { value: true }); + // var __syncRequire = typeof module === "object" && typeof module.exports === "object"; + // var __resolved = new Promise(function (resolve) { resolve(); }); + // ..... + // __syncRequire + // ? __resolved.then(function () { return require(x); }) /*CommonJs Require*/ + // : new Promise(function (_a, _b) { require([x], _a, _b); }); /*Amd Require*/ + // }); + needUMDDynamicImportHelper = true; + if (ts.isSimpleCopiableExpression(arg)) { + var argClone = ts.isGeneratedIdentifier(arg) ? arg : ts.isStringLiteral(arg) ? ts.createLiteral(arg) : ts.setEmitFlags(ts.setTextRange(ts.getSynthesizedClone(arg), arg), 1536 /* NoComments */); + return ts.createConditional( + /*condition*/ ts.createIdentifier("__syncRequire"), + /*whenTrue*/ createImportCallExpressionCommonJS(arg, containsLexicalThis), + /*whenFalse*/ createImportCallExpressionAMD(argClone, containsLexicalThis)); + } + else { + var temp = ts.createTempVariable(hoistVariableDeclaration); + return ts.createComma(ts.createAssignment(temp, arg), ts.createConditional( + /*condition*/ ts.createIdentifier("__syncRequire"), + /*whenTrue*/ createImportCallExpressionCommonJS(temp, containsLexicalThis), + /*whenFalse*/ createImportCallExpressionAMD(temp, containsLexicalThis))); + } + } + function createImportCallExpressionAMD(arg, containsLexicalThis) { + // improt("./blah") + // emit as + // define(["require", "exports", "blah"], function (require, exports) { + // ... + // new Promise(function (_a, _b) { require([x], _a, _b); }); /*Amd Require*/ + // }); + var resolve = ts.createUniqueName("resolve"); + var reject = ts.createUniqueName("reject"); + var parameters = [ + ts.createParameter(/*decorator*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, /*name*/ resolve), + ts.createParameter(/*decorator*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, /*name*/ reject) + ]; + var body = ts.createBlock([ + ts.createExpressionStatement(ts.createCall(ts.createIdentifier("require"), + /*typeArguments*/ undefined, [ts.createArrayLiteral([arg || ts.createOmittedExpression()]), resolve, reject])) + ]); + var func; + if (languageVersion >= 2 /* ES2015 */) { + func = ts.createArrowFunction( + /*modifiers*/ undefined, + /*typeParameters*/ undefined, parameters, + /*type*/ undefined, + /*equalsGreaterThanToken*/ undefined, body); + } + else { + func = ts.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, parameters, + /*type*/ undefined, body); + // if there is a lexical 'this' in the import call arguments, ensure we indicate + // that this new function expression indicates it captures 'this' so that the + // es2015 transformer will properly substitute 'this' with '_this'. + if (containsLexicalThis) { + ts.setEmitFlags(func, 8 /* CapturesThis */); + } + } + var promise = ts.createNew(ts.createIdentifier("Promise"), /*typeArguments*/ undefined, [func]); + if (compilerOptions.esModuleInterop) { + context.requestEmitHelper(importStarHelper); + return ts.createCall(ts.createPropertyAccess(promise, ts.createIdentifier("then")), /*typeArguments*/ undefined, [ts.getHelperName("__importStar")]); + } + return promise; + } + function createImportCallExpressionCommonJS(arg, containsLexicalThis) { + // import("./blah") + // emit as + // Promise.resolve().then(function () { return require(x); }) /*CommonJs Require*/ + // We have to wrap require in then callback so that require is done in asynchronously + // if we simply do require in resolve callback in Promise constructor. We will execute the loading immediately + var promiseResolveCall = ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Promise"), "resolve"), /*typeArguments*/ undefined, /*argumentsArray*/ []); + var requireCall = ts.createCall(ts.createIdentifier("require"), /*typeArguments*/ undefined, arg ? [arg] : []); + if (compilerOptions.esModuleInterop) { + context.requestEmitHelper(importStarHelper); + requireCall = ts.createCall(ts.getHelperName("__importStar"), /*typeArguments*/ undefined, [requireCall]); + } + var func; + if (languageVersion >= 2 /* ES2015 */) { + func = ts.createArrowFunction( + /*modifiers*/ undefined, + /*typeParameters*/ undefined, + /*parameters*/ [], + /*type*/ undefined, + /*equalsGreaterThanToken*/ undefined, requireCall); + } + else { + func = ts.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, + /*parameters*/ [], + /*type*/ undefined, ts.createBlock([ts.createReturn(requireCall)])); + // if there is a lexical 'this' in the import call arguments, ensure we indicate + // that this new function expression indicates it captures 'this' so that the + // es2015 transformer will properly substitute 'this' with '_this'. + if (containsLexicalThis) { + ts.setEmitFlags(func, 8 /* CapturesThis */); + } + } + return ts.createCall(ts.createPropertyAccess(promiseResolveCall, "then"), /*typeArguments*/ undefined, [func]); + } + function getHelperExpressionForImport(node, innerExpr) { + if (!compilerOptions.esModuleInterop || ts.getEmitFlags(node) & 67108864 /* NeverApplyImportHelper */) { + return innerExpr; + } + if (ts.getImportNeedsImportStarHelper(node)) { + context.requestEmitHelper(importStarHelper); + return ts.createCall(ts.getHelperName("__importStar"), /*typeArguments*/ undefined, [innerExpr]); + } + if (ts.getImportNeedsImportDefaultHelper(node)) { + context.requestEmitHelper(importDefaultHelper); + return ts.createCall(ts.getHelperName("__importDefault"), /*typeArguments*/ undefined, [innerExpr]); + } + return innerExpr; + } + /** + * Visits an ImportDeclaration node. + * + * @param node The node to visit. + */ + function visitImportDeclaration(node) { + var statements; + var namespaceDeclaration = ts.getNamespaceDeclarationNode(node); + if (moduleKind !== ts.ModuleKind.AMD) { + if (!node.importClause) { + // import "mod"; + return ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(createRequireCall(node)), node), node); + } + else { + var variables = []; + if (namespaceDeclaration && !ts.isDefaultImport(node)) { + // import * as n from "mod"; + variables.push(ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name), + /*type*/ undefined, getHelperExpressionForImport(node, createRequireCall(node)))); + } + else { + // import d from "mod"; + // import { x, y } from "mod"; + // import d, { x, y } from "mod"; + // import d, * as n from "mod"; + variables.push(ts.createVariableDeclaration(ts.getGeneratedNameForNode(node), + /*type*/ undefined, getHelperExpressionForImport(node, createRequireCall(node)))); + if (namespaceDeclaration && ts.isDefaultImport(node)) { + variables.push(ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name), + /*type*/ undefined, ts.getGeneratedNameForNode(node))); + } + } + statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList(variables, languageVersion >= 2 /* ES2015 */ ? 2 /* Const */ : 0 /* None */)), + /*location*/ node), + /*original*/ node)); + } + } + else if (namespaceDeclaration && ts.isDefaultImport(node)) { + // import d, * as n from "mod"; + statements = ts.append(statements, ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ + ts.setOriginalNode(ts.setTextRange(ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name), + /*type*/ undefined, ts.getGeneratedNameForNode(node)), + /*location*/ node), + /*original*/ node) + ], languageVersion >= 2 /* ES2015 */ ? 2 /* Const */ : 0 /* None */))); + } + if (hasAssociatedEndOfDeclarationMarker(node)) { + // Defer exports until we encounter an EndOfDeclarationMarker node + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportsOfImportDeclaration(deferredExports[id], node); + } + else { + statements = appendExportsOfImportDeclaration(statements, node); + } + return ts.singleOrMany(statements); + } + /** + * Creates a `require()` call to import an external module. + * + * @param importNode The declararation to import. + */ + function createRequireCall(importNode) { + var moduleName = ts.getExternalModuleNameLiteral(importNode, currentSourceFile, host, resolver, compilerOptions); + var args = []; + if (moduleName) { + args.push(moduleName); + } + return ts.createCall(ts.createIdentifier("require"), /*typeArguments*/ undefined, args); + } + /** + * Visits an ImportEqualsDeclaration node. + * + * @param node The node to visit. + */ + function visitImportEqualsDeclaration(node) { + ts.Debug.assert(ts.isExternalModuleImportEqualsDeclaration(node), "import= for internal module references should be handled in an earlier transformer."); + var statements; + if (moduleKind !== ts.ModuleKind.AMD) { + if (ts.hasModifier(node, 1 /* Export */)) { + statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(createExportExpression(node.name, createRequireCall(node))), node), node)); + } + else { + statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(ts.getSynthesizedClone(node.name), + /*type*/ undefined, createRequireCall(node)) + ], + /*flags*/ languageVersion >= 2 /* ES2015 */ ? 2 /* Const */ : 0 /* None */)), node), node)); + } + } + else { + if (ts.hasModifier(node, 1 /* Export */)) { + statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(createExportExpression(ts.getExportName(node), ts.getLocalName(node))), node), node)); + } + } + if (hasAssociatedEndOfDeclarationMarker(node)) { + // Defer exports until we encounter an EndOfDeclarationMarker node + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportsOfImportEqualsDeclaration(deferredExports[id], node); + } + else { + statements = appendExportsOfImportEqualsDeclaration(statements, node); + } + return ts.singleOrMany(statements); + } + /** + * Visits an ExportDeclaration node. + * + * @param The node to visit. + */ + function visitExportDeclaration(node) { + if (!node.moduleSpecifier) { + // Elide export declarations with no module specifier as they are handled + // elsewhere. + return undefined; + } + var generatedName = ts.getGeneratedNameForNode(node); + if (node.exportClause) { + var statements = []; + // export { x, y } from "mod"; + if (moduleKind !== ts.ModuleKind.AMD) { + statements.push(ts.setOriginalNode(ts.setTextRange(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(generatedName, + /*type*/ undefined, createRequireCall(node)) + ])), + /*location*/ node), + /* original */ node)); + } + for (var _i = 0, _a = node.exportClause.elements; _i < _a.length; _i++) { + var specifier = _a[_i]; + var exportedValue = ts.createPropertyAccess(generatedName, specifier.propertyName || specifier.name); + statements.push(ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(createExportExpression(ts.getExportName(specifier), exportedValue)), specifier), specifier)); + } + return ts.singleOrMany(statements); + } + else { + // export * from "mod"; + return ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(createExportStarHelper(context, moduleKind !== ts.ModuleKind.AMD ? createRequireCall(node) : generatedName)), node), node); + } + } + /** + * Visits an ExportAssignment node. + * + * @param node The node to visit. + */ + function visitExportAssignment(node) { + if (node.isExportEquals) { + return undefined; + } + var statements; + var original = node.original; + if (original && hasAssociatedEndOfDeclarationMarker(original)) { + // Defer exports until we encounter an EndOfDeclarationMarker node + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportStatement(deferredExports[id], ts.createIdentifier("default"), ts.visitNode(node.expression, moduleExpressionElementVisitor), /*location*/ node, /*allowComments*/ true); + } + else { + statements = appendExportStatement(statements, ts.createIdentifier("default"), ts.visitNode(node.expression, moduleExpressionElementVisitor), /*location*/ node, /*allowComments*/ true); + } + return ts.singleOrMany(statements); + } + /** + * Visits a FunctionDeclaration node. + * + * @param node The node to visit. + */ + function visitFunctionDeclaration(node) { + var statements; + if (ts.hasModifier(node, 1 /* Export */)) { + statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createFunctionDeclaration( + /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, ts.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true), + /*typeParameters*/ undefined, ts.visitNodes(node.parameters, moduleExpressionElementVisitor), + /*type*/ undefined, ts.visitEachChild(node.body, moduleExpressionElementVisitor, context)), + /*location*/ node), + /*original*/ node)); + } + else { + statements = ts.append(statements, ts.visitEachChild(node, moduleExpressionElementVisitor, context)); + } + if (hasAssociatedEndOfDeclarationMarker(node)) { + // Defer exports until we encounter an EndOfDeclarationMarker node + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node); + } + else { + statements = appendExportsOfHoistedDeclaration(statements, node); + } + return ts.singleOrMany(statements); + } + /** + * Visits a ClassDeclaration node. + * + * @param node The node to visit. + */ + function visitClassDeclaration(node) { + var statements; + if (ts.hasModifier(node, 1 /* Export */)) { + statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createClassDeclaration( + /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true), + /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, moduleExpressionElementVisitor), ts.visitNodes(node.members, moduleExpressionElementVisitor)), node), node)); + } + else { + statements = ts.append(statements, ts.visitEachChild(node, moduleExpressionElementVisitor, context)); + } + if (hasAssociatedEndOfDeclarationMarker(node)) { + // Defer exports until we encounter an EndOfDeclarationMarker node + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node); + } + else { + statements = appendExportsOfHoistedDeclaration(statements, node); + } + return ts.singleOrMany(statements); + } + /** + * Visits a VariableStatement node. + * + * @param node The node to visit. + */ + function visitVariableStatement(node) { + var statements; + var variables; + var expressions; + if (ts.hasModifier(node, 1 /* Export */)) { + var modifiers = void 0; + // If we're exporting these variables, then these just become assignments to 'exports.x'. + // We only want to emit assignments for variables with initializers. + for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { + var variable = _a[_i]; + if (ts.isIdentifier(variable.name) && ts.isLocalName(variable.name)) { + if (!modifiers) { + modifiers = ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier); + } + variables = ts.append(variables, variable); + } + else if (variable.initializer) { + expressions = ts.append(expressions, transformInitializedVariable(variable)); + } + } + if (variables) { + statements = ts.append(statements, ts.updateVariableStatement(node, modifiers, ts.updateVariableDeclarationList(node.declarationList, variables))); + } + if (expressions) { + statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(ts.inlineExpressions(expressions)), node), node)); + } + } + else { + statements = ts.append(statements, ts.visitEachChild(node, moduleExpressionElementVisitor, context)); + } + if (hasAssociatedEndOfDeclarationMarker(node)) { + // Defer exports until we encounter an EndOfDeclarationMarker node + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node); + } + else { + statements = appendExportsOfVariableStatement(statements, node); + } + return ts.singleOrMany(statements); + } + function createAllExportExpressions(name, value, location) { + var exportedNames = getExports(name); + if (exportedNames) { + // For each additional export of the declaration, apply an export assignment. + var expression = ts.isExportName(name) ? value : ts.createAssignment(name, value); + for (var _i = 0, exportedNames_1 = exportedNames; _i < exportedNames_1.length; _i++) { + var exportName = exportedNames_1[_i]; + // Mark the node to prevent triggering substitution. + ts.setEmitFlags(expression, 4 /* NoSubstitution */); + expression = createExportExpression(exportName, expression, /*location*/ location); + } + return expression; + } + return ts.createAssignment(name, value); + } + /** + * Transforms an exported variable with an initializer into an expression. + * + * @param node The node to transform. + */ + function transformInitializedVariable(node) { + if (ts.isBindingPattern(node.name)) { + return ts.flattenDestructuringAssignment(ts.visitNode(node, moduleExpressionElementVisitor), + /*visitor*/ undefined, context, 0 /* All */, + /*needsValue*/ false, createAllExportExpressions); + } + else { + return ts.createAssignment(ts.setTextRange(ts.createPropertyAccess(ts.createIdentifier("exports"), node.name), + /*location*/ node.name), ts.visitNode(node.initializer, moduleExpressionElementVisitor)); + } + } + /** + * Visits a MergeDeclarationMarker used as a placeholder for the beginning of a merged + * and transformed declaration. + * + * @param node The node to visit. + */ + function visitMergeDeclarationMarker(node) { + // For an EnumDeclaration or ModuleDeclaration that merges with a preceeding + // declaration we do not emit a leading variable declaration. To preserve the + // begin/end semantics of the declararation and to properly handle exports + // we wrapped the leading variable declaration in a `MergeDeclarationMarker`. + // + // To balance the declaration, add the exports of the elided variable + // statement. + if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 219 /* VariableStatement */) { + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node.original); + } + return node; + } + /** + * Determines whether a node has an associated EndOfDeclarationMarker. + * + * @param node The node to test. + */ + function hasAssociatedEndOfDeclarationMarker(node) { + return (ts.getEmitFlags(node) & 4194304 /* HasEndOfDeclarationMarker */) !== 0; + } + /** + * Visits a DeclarationMarker used as a placeholder for the end of a transformed + * declaration. + * + * @param node The node to visit. + */ + function visitEndOfDeclarationMarker(node) { + // For some transformations we emit an `EndOfDeclarationMarker` to mark the actual + // end of the transformed declaration. We use this marker to emit any deferred exports + // of the declaration. + var id = ts.getOriginalNodeId(node); + var statements = deferredExports[id]; + if (statements) { + delete deferredExports[id]; + return ts.append(statements, node); + } + return node; + } + /** + * Appends the exports of an ImportDeclaration to a statement list, returning the + * statement list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param decl The declaration whose exports are to be recorded. + */ + function appendExportsOfImportDeclaration(statements, decl) { + if (currentModuleInfo.exportEquals) { + return statements; + } + var importClause = decl.importClause; + if (!importClause) { + return statements; + } + if (importClause.name) { + statements = appendExportsOfDeclaration(statements, importClause); + } + var namedBindings = importClause.namedBindings; + if (namedBindings) { + switch (namedBindings.kind) { + case 251 /* NamespaceImport */: + statements = appendExportsOfDeclaration(statements, namedBindings); + break; + case 252 /* NamedImports */: + for (var _i = 0, _a = namedBindings.elements; _i < _a.length; _i++) { + var importBinding = _a[_i]; + statements = appendExportsOfDeclaration(statements, importBinding); + } + break; + } + } + return statements; + } + /** + * Appends the exports of an ImportEqualsDeclaration to a statement list, returning the + * statement list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param decl The declaration whose exports are to be recorded. + */ + function appendExportsOfImportEqualsDeclaration(statements, decl) { + if (currentModuleInfo.exportEquals) { + return statements; + } + return appendExportsOfDeclaration(statements, decl); + } + /** + * Appends the exports of a VariableStatement to a statement list, returning the statement + * list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param node The VariableStatement whose exports are to be recorded. + */ + function appendExportsOfVariableStatement(statements, node) { + if (currentModuleInfo.exportEquals) { + return statements; + } + for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + statements = appendExportsOfBindingElement(statements, decl); + } + return statements; + } + /** + * Appends the exports of a VariableDeclaration or BindingElement to a statement list, + * returning the statement list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param decl The declaration whose exports are to be recorded. + */ + function appendExportsOfBindingElement(statements, decl) { + if (currentModuleInfo.exportEquals) { + return statements; + } + if (ts.isBindingPattern(decl.name)) { + for (var _i = 0, _a = decl.name.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (!ts.isOmittedExpression(element)) { + statements = appendExportsOfBindingElement(statements, element); + } + } + } + else if (!ts.isGeneratedIdentifier(decl.name)) { + statements = appendExportsOfDeclaration(statements, decl); + } + return statements; + } + /** + * Appends the exports of a ClassDeclaration or FunctionDeclaration to a statement list, + * returning the statement list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param decl The declaration whose exports are to be recorded. + */ + function appendExportsOfHoistedDeclaration(statements, decl) { + if (currentModuleInfo.exportEquals) { + return statements; + } + if (ts.hasModifier(decl, 1 /* Export */)) { + var exportName = ts.hasModifier(decl, 512 /* Default */) ? ts.createIdentifier("default") : ts.getDeclarationName(decl); + statements = appendExportStatement(statements, exportName, ts.getLocalName(decl), /*location*/ decl); + } + if (decl.name) { + statements = appendExportsOfDeclaration(statements, decl); + } + return statements; + } + /** + * Appends the exports of a declaration to a statement list, returning the statement list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param decl The declaration to export. + */ + function appendExportsOfDeclaration(statements, decl) { + var name = ts.getDeclarationName(decl); + var exportSpecifiers = currentModuleInfo.exportSpecifiers.get(ts.idText(name)); + if (exportSpecifiers) { + for (var _i = 0, exportSpecifiers_1 = exportSpecifiers; _i < exportSpecifiers_1.length; _i++) { + var exportSpecifier = exportSpecifiers_1[_i]; + statements = appendExportStatement(statements, exportSpecifier.name, name, /*location*/ exportSpecifier.name); + } + } + return statements; + } + /** + * Appends the down-level representation of an export to a statement list, returning the + * statement list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param exportName The name of the export. + * @param expression The expression to export. + * @param location The location to use for source maps and comments for the export. + * @param allowComments Whether to allow comments on the export. + */ + function appendExportStatement(statements, exportName, expression, location, allowComments) { + statements = ts.append(statements, createExportStatement(exportName, expression, location, allowComments)); + return statements; + } + function createUnderscoreUnderscoreESModule() { + var statement; + if (languageVersion === 0 /* ES3 */) { + statement = ts.createExpressionStatement(createExportExpression(ts.createIdentifier("__esModule"), ts.createLiteral(/*value*/ true))); + } + else { + statement = ts.createExpressionStatement(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"), + /*typeArguments*/ undefined, [ + ts.createIdentifier("exports"), + ts.createLiteral("__esModule"), + ts.createObjectLiteral([ + ts.createPropertyAssignment("value", ts.createLiteral(/*value*/ true)) + ]) + ])); + } + ts.setEmitFlags(statement, 1048576 /* CustomPrologue */); + return statement; + } + /** + * Creates a call to the current file's export function to export a value. + * + * @param name The bound name of the export. + * @param value The exported value. + * @param location The location to use for source maps and comments for the export. + * @param allowComments An optional value indicating whether to emit comments for the statement. + */ + function createExportStatement(name, value, location, allowComments) { + var statement = ts.setTextRange(ts.createExpressionStatement(createExportExpression(name, value)), location); + ts.startOnNewLine(statement); + if (!allowComments) { + ts.setEmitFlags(statement, 1536 /* NoComments */); + } + return statement; + } + /** + * Creates a call to the current file's export function to export a value. + * + * @param name The bound name of the export. + * @param value The exported value. + * @param location The location to use for source maps and comments for the export. + */ + function createExportExpression(name, value, location) { + return ts.setTextRange(ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier("exports"), ts.getSynthesizedClone(name)), value), location); + } + // + // Modifier Visitors + // + /** + * Visit nodes to elide module-specific modifiers. + * + * @param node The node to visit. + */ + function modifierVisitor(node) { + // Elide module-specific modifiers. + switch (node.kind) { + case 85 /* ExportKeyword */: + case 80 /* DefaultKeyword */: + return undefined; + } + return node; + } + // + // Emit Notification + // + /** + * Hook for node emit notifications. + * + * @param hint A hint as to the intended usage of the node. + * @param node The node to emit. + * @param emit A callback used to emit the node in the printer. + */ + function onEmitNode(hint, node, emitCallback) { + if (node.kind === 279 /* SourceFile */) { + currentSourceFile = node; + currentModuleInfo = moduleInfoMap[ts.getOriginalNodeId(currentSourceFile)]; + noSubstitution = []; + previousOnEmitNode(hint, node, emitCallback); + currentSourceFile = undefined; + currentModuleInfo = undefined; + noSubstitution = undefined; + } + else { + previousOnEmitNode(hint, node, emitCallback); + } + } + // + // Substitutions + // + /** + * Hooks node substitutions. + * + * @param hint A hint as to the intended usage of the node. + * @param node The node to substitute. + */ + function onSubstituteNode(hint, node) { + node = previousOnSubstituteNode(hint, node); + if (node.id && noSubstitution[node.id]) { + return node; + } + if (hint === 1 /* Expression */) { + return substituteExpression(node); + } + else if (ts.isShorthandPropertyAssignment(node)) { + return substituteShorthandPropertyAssignment(node); + } + return node; + } + /** + * Substitution for a ShorthandPropertyAssignment whose declaration name is an imported + * or exported symbol. + * + * @param node The node to substitute. + */ + function substituteShorthandPropertyAssignment(node) { + var name = node.name; + var exportedOrImportedName = substituteExpressionIdentifier(name); + if (exportedOrImportedName !== name) { + // A shorthand property with an assignment initializer is probably part of a + // destructuring assignment + if (node.objectAssignmentInitializer) { + var initializer = ts.createAssignment(exportedOrImportedName, node.objectAssignmentInitializer); + return ts.setTextRange(ts.createPropertyAssignment(name, initializer), node); + } + return ts.setTextRange(ts.createPropertyAssignment(name, exportedOrImportedName), node); + } + return node; + } + /** + * Substitution for an Expression that may contain an imported or exported symbol. + * + * @param node The node to substitute. + */ + function substituteExpression(node) { + switch (node.kind) { + case 72 /* Identifier */: + return substituteExpressionIdentifier(node); + case 204 /* BinaryExpression */: + return substituteBinaryExpression(node); + case 203 /* PostfixUnaryExpression */: + case 202 /* PrefixUnaryExpression */: + return substituteUnaryExpression(node); + } + return node; + } + /** + * Substitution for an Identifier expression that may contain an imported or exported + * symbol. + * + * @param node The node to substitute. + */ + function substituteExpressionIdentifier(node) { + if (ts.getEmitFlags(node) & 4096 /* HelperName */) { + var externalHelpersModuleName = ts.getExternalHelpersModuleName(currentSourceFile); + if (externalHelpersModuleName) { + return ts.createPropertyAccess(externalHelpersModuleName, node); + } + return node; + } + if (!ts.isGeneratedIdentifier(node) && !ts.isLocalName(node)) { + var exportContainer = resolver.getReferencedExportContainer(node, ts.isExportName(node)); + if (exportContainer && exportContainer.kind === 279 /* SourceFile */) { + return ts.setTextRange(ts.createPropertyAccess(ts.createIdentifier("exports"), ts.getSynthesizedClone(node)), + /*location*/ node); + } + var importDeclaration = resolver.getReferencedImportDeclaration(node); + if (importDeclaration) { + if (ts.isImportClause(importDeclaration)) { + return ts.setTextRange(ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent), ts.createIdentifier("default")), + /*location*/ node); + } + else if (ts.isImportSpecifier(importDeclaration)) { + var name = importDeclaration.propertyName || importDeclaration.name; + return ts.setTextRange(ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent.parent.parent), ts.getSynthesizedClone(name)), + /*location*/ node); + } + } + } + return node; + } + /** + * Substitution for a BinaryExpression that may contain an imported or exported symbol. + * + * @param node The node to substitute. + */ + function substituteBinaryExpression(node) { + // When we see an assignment expression whose left-hand side is an exported symbol, + // we should ensure all exports of that symbol are updated with the correct value. + // + // - We do not substitute generated identifiers for any reason. + // - We do not substitute identifiers tagged with the LocalName flag. + // - We do not substitute identifiers that were originally the name of an enum or + // namespace due to how they are transformed in TypeScript. + // - We only substitute identifiers that are exported at the top level. + if (ts.isAssignmentOperator(node.operatorToken.kind) + && ts.isIdentifier(node.left) + && !ts.isGeneratedIdentifier(node.left) + && !ts.isLocalName(node.left) + && !ts.isDeclarationNameOfEnumOrNamespace(node.left)) { + var exportedNames = getExports(node.left); + if (exportedNames) { + // For each additional export of the declaration, apply an export assignment. + var expression = node; + for (var _i = 0, exportedNames_2 = exportedNames; _i < exportedNames_2.length; _i++) { + var exportName = exportedNames_2[_i]; + // Mark the node to prevent triggering this rule again. + noSubstitution[ts.getNodeId(expression)] = true; + expression = createExportExpression(exportName, expression, /*location*/ node); + } + return expression; + } + } + return node; + } + /** + * Substitution for a UnaryExpression that may contain an imported or exported symbol. + * + * @param node The node to substitute. + */ + function substituteUnaryExpression(node) { + // When we see a prefix or postfix increment expression whose operand is an exported + // symbol, we should ensure all exports of that symbol are updated with the correct + // value. + // + // - We do not substitute generated identifiers for any reason. + // - We do not substitute identifiers tagged with the LocalName flag. + // - We do not substitute identifiers that were originally the name of an enum or + // namespace due to how they are transformed in TypeScript. + // - We only substitute identifiers that are exported at the top level. + if ((node.operator === 44 /* PlusPlusToken */ || node.operator === 45 /* MinusMinusToken */) + && ts.isIdentifier(node.operand) + && !ts.isGeneratedIdentifier(node.operand) + && !ts.isLocalName(node.operand) + && !ts.isDeclarationNameOfEnumOrNamespace(node.operand)) { + var exportedNames = getExports(node.operand); + if (exportedNames) { + var expression = node.kind === 203 /* PostfixUnaryExpression */ + ? ts.setTextRange(ts.createBinary(node.operand, ts.createToken(node.operator === 44 /* PlusPlusToken */ ? 60 /* PlusEqualsToken */ : 61 /* MinusEqualsToken */), ts.createLiteral(1)), + /*location*/ node) + : node; + for (var _i = 0, exportedNames_3 = exportedNames; _i < exportedNames_3.length; _i++) { + var exportName = exportedNames_3[_i]; + // Mark the node to prevent triggering this rule again. + noSubstitution[ts.getNodeId(expression)] = true; + expression = createExportExpression(exportName, expression); + } + return expression; + } + } + return node; + } + /** + * Gets the additional exports of a name. + * + * @param name The name. + */ + function getExports(name) { + if (!ts.isGeneratedIdentifier(name)) { + var valueDeclaration = resolver.getReferencedImportDeclaration(name) + || resolver.getReferencedValueDeclaration(name); + if (valueDeclaration) { + return currentModuleInfo + && currentModuleInfo.exportedBindings[ts.getOriginalNodeId(valueDeclaration)]; + } + } + } + } + ts.transformModule = transformModule; + // emit output for the __export helper function + var exportStarHelper = { + name: "typescript:export-star", + scoped: true, + text: "\n function __export(m) {\n for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\n }" + }; + function createExportStarHelper(context, module) { + var compilerOptions = context.getCompilerOptions(); + return compilerOptions.importHelpers + ? ts.createCall(ts.getHelperName("__exportStar"), /*typeArguments*/ undefined, [module, ts.createIdentifier("exports")]) + : ts.createCall(ts.createIdentifier("__export"), /*typeArguments*/ undefined, [module]); + } + // emit helper for dynamic import + var dynamicImportUMDHelper = { + name: "typescript:dynamicimport-sync-require", + scoped: true, + text: "\n var __syncRequire = typeof module === \"object\" && typeof module.exports === \"object\";" + }; + // emit helper for `import * as Name from "foo"` + var importStarHelper = { + name: "typescript:commonjsimportstar", + scoped: false, + text: "\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];\n result[\"default\"] = mod;\n return result;\n};" + }; + // emit helper for `import Name from "foo"` + var importDefaultHelper = { + name: "typescript:commonjsimportdefault", + scoped: false, + text: "\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};" + }; +})(ts || (ts = {})); +/*@internal*/ +var ts; +(function (ts) { + function transformSystemModule(context) { + var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; + var compilerOptions = context.getCompilerOptions(); + var resolver = context.getEmitResolver(); + var host = context.getEmitHost(); + var previousOnSubstituteNode = context.onSubstituteNode; + var previousOnEmitNode = context.onEmitNode; + context.onSubstituteNode = onSubstituteNode; + context.onEmitNode = onEmitNode; + context.enableSubstitution(72 /* Identifier */); // Substitutes expression identifiers for imported symbols. + context.enableSubstitution(276 /* ShorthandPropertyAssignment */); // Substitutes expression identifiers for imported symbols + context.enableSubstitution(204 /* BinaryExpression */); // Substitutes assignments to exported symbols. + context.enableSubstitution(202 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols. + context.enableSubstitution(203 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols. + context.enableEmitNotification(279 /* SourceFile */); // Restore state when substituting nodes in a file. + var moduleInfoMap = []; // The ExternalModuleInfo for each file. + var deferredExports = []; // Exports to defer until an EndOfDeclarationMarker is found. + var exportFunctionsMap = []; // The export function associated with a source file. + var noSubstitutionMap = []; // Set of nodes for which substitution rules should be ignored for each file. + var currentSourceFile; // The current file. + var moduleInfo; // ExternalModuleInfo for the current file. + var exportFunction; // The export function for the current file. + var contextObject; // The context object for the current file. + var hoistedStatements; + var enclosingBlockScopedContainer; + var noSubstitution; // Set of nodes for which substitution rules should be ignored. + return ts.chainBundle(transformSourceFile); + /** + * Transforms the module aspects of a SourceFile. + * + * @param node The SourceFile node. + */ + function transformSourceFile(node) { + if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 16777216 /* ContainsDynamicImport */)) { + return node; + } + var id = ts.getOriginalNodeId(node); + currentSourceFile = node; + enclosingBlockScopedContainer = node; + // System modules have the following shape: + // + // System.register(['dep-1', ... 'dep-n'], function(exports) {/* module body function */}) + // + // The parameter 'exports' here is a callback '(name: string, value: T) => T' that + // is used to publish exported values. 'exports' returns its 'value' argument so in + // most cases expressions that mutate exported values can be rewritten as: + // + // expr -> exports('name', expr) + // + // The only exception in this rule is postfix unary operators, + // see comment to 'substitutePostfixUnaryExpression' for more details + // Collect information about the external module and dependency groups. + moduleInfo = moduleInfoMap[id] = ts.collectExternalModuleInfo(node, resolver, compilerOptions); + // Make sure that the name of the 'exports' function does not conflict with + // existing identifiers. + exportFunction = ts.createUniqueName("exports"); + exportFunctionsMap[id] = exportFunction; + contextObject = ts.createUniqueName("context"); + // Add the body of the module. + var dependencyGroups = collectDependencyGroups(moduleInfo.externalImports); + var moduleBodyBlock = createSystemModuleBody(node, dependencyGroups); + var moduleBodyFunction = ts.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, [ + ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, exportFunction), + ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, contextObject) + ], + /*type*/ undefined, moduleBodyBlock); + // Write the call to `System.register` + // Clear the emit-helpers flag for later passes since we'll have already used it in the module body + // So the helper will be emit at the correct position instead of at the top of the source-file + var moduleName = ts.tryGetModuleNameFromFile(node, host, compilerOptions); + var dependencies = ts.createArrayLiteral(ts.map(dependencyGroups, function (dependencyGroup) { return dependencyGroup.name; })); + var updated = ts.setEmitFlags(ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray([ + ts.createExpressionStatement(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("System"), "register"), + /*typeArguments*/ undefined, moduleName + ? [moduleName, dependencies, moduleBodyFunction] + : [dependencies, moduleBodyFunction])) + ]), node.statements)), 1024 /* NoTrailingComments */); + if (!(compilerOptions.outFile || compilerOptions.out)) { + ts.moveEmitHelpers(updated, moduleBodyBlock, function (helper) { return !helper.scoped; }); + } + if (noSubstitution) { + noSubstitutionMap[id] = noSubstitution; + noSubstitution = undefined; + } + currentSourceFile = undefined; + moduleInfo = undefined; + exportFunction = undefined; + contextObject = undefined; + hoistedStatements = undefined; + enclosingBlockScopedContainer = undefined; + return ts.aggregateTransformFlags(updated); + } + /** + * Collects the dependency groups for this files imports. + * + * @param externalImports The imports for the file. + */ + function collectDependencyGroups(externalImports) { + var groupIndices = ts.createMap(); + var dependencyGroups = []; + for (var _i = 0, externalImports_1 = externalImports; _i < externalImports_1.length; _i++) { + var externalImport = externalImports_1[_i]; + var externalModuleName = ts.getExternalModuleNameLiteral(externalImport, currentSourceFile, host, resolver, compilerOptions); + if (externalModuleName) { + var text = externalModuleName.text; + var groupIndex = groupIndices.get(text); + if (groupIndex !== undefined) { + // deduplicate/group entries in dependency list by the dependency name + dependencyGroups[groupIndex].externalImports.push(externalImport); + } + else { + groupIndices.set(text, dependencyGroups.length); + dependencyGroups.push({ + name: externalModuleName, + externalImports: [externalImport] + }); + } + } + } + return dependencyGroups; + } + /** + * Adds the statements for the module body function for the source file. + * + * @param node The source file for the module. + * @param dependencyGroups The grouped dependencies of the module. + */ + function createSystemModuleBody(node, dependencyGroups) { + // Shape of the body in system modules: + // + // function (exports) { + // + // + // + // return { + // setters: [ + // + // ], + // execute: function() { + // + // } + // } + // + // } + // + // i.e: + // + // import {x} from 'file1' + // var y = 1; + // export function foo() { return y + x(); } + // console.log(y); + // + // Will be transformed to: + // + // function(exports) { + // function foo() { return y + file_1.x(); } + // exports("foo", foo); + // var file_1, y; + // return { + // setters: [ + // function(v) { file_1 = v } + // ], + // execute(): function() { + // y = 1; + // console.log(y); + // } + // }; + // } + var statements = []; + // We start a new lexical environment in this function body, but *not* in the + // body of the execute function. This allows us to emit temporary declarations + // only in the outer module body and not in the inner one. + startLexicalEnvironment(); + // Add any prologue directives. + var ensureUseStrict = ts.getStrictOptionValue(compilerOptions, "alwaysStrict") || (!compilerOptions.noImplicitUseStrict && ts.isExternalModule(currentSourceFile)); + var statementOffset = ts.addPrologue(statements, node.statements, ensureUseStrict, sourceElementVisitor); + // var __moduleName = context_1 && context_1.id; + statements.push(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration("__moduleName", + /*type*/ undefined, ts.createLogicalAnd(contextObject, ts.createPropertyAccess(contextObject, "id"))) + ]))); + // Visit the synthetic external helpers import declaration if present + ts.visitNode(moduleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement); + // Visit the statements of the source file, emitting any transformations into + // the `executeStatements` array. We do this *before* we fill the `setters` array + // as we both emit transformations as well as aggregate some data used when creating + // setters. This allows us to reduce the number of times we need to loop through the + // statements of the source file. + var executeStatements = ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset); + // Emit early exports for function declarations. + ts.addRange(statements, hoistedStatements); + // We emit hoisted variables early to align roughly with our previous emit output. + // Two key differences in this approach are: + // - Temporary variables will appear at the top rather than at the bottom of the file + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + var exportStarFunction = addExportStarIfNeeded(statements); // TODO: GH#18217 + var moduleObject = ts.createObjectLiteral([ + ts.createPropertyAssignment("setters", createSettersArray(exportStarFunction, dependencyGroups)), + ts.createPropertyAssignment("execute", ts.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, + /*parameters*/ [], + /*type*/ undefined, ts.createBlock(executeStatements, /*multiLine*/ true))) + ]); + moduleObject.multiLine = true; + statements.push(ts.createReturn(moduleObject)); + return ts.createBlock(statements, /*multiLine*/ true); + } + /** + * Adds an exportStar function to a statement list if it is needed for the file. + * + * @param statements A statement list. + */ + function addExportStarIfNeeded(statements) { + if (!moduleInfo.hasExportStarsToExportValues) { + return; + } + // when resolving exports local exported entries/indirect exported entries in the module + // should always win over entries with similar names that were added via star exports + // to support this we store names of local/indirect exported entries in a set. + // this set is used to filter names brought by star expors. + // local names set should only be added if we have anything exported + if (!moduleInfo.exportedNames && moduleInfo.exportSpecifiers.size === 0) { + // no exported declarations (export var ...) or export specifiers (export {x}) + // check if we have any non star export declarations. + var hasExportDeclarationWithExportClause = false; + for (var _i = 0, _a = moduleInfo.externalImports; _i < _a.length; _i++) { + var externalImport = _a[_i]; + if (externalImport.kind === 255 /* ExportDeclaration */ && externalImport.exportClause) { + hasExportDeclarationWithExportClause = true; + break; + } + } + if (!hasExportDeclarationWithExportClause) { + // we still need to emit exportStar helper + var exportStarFunction_1 = createExportStarFunction(/*localNames*/ undefined); + statements.push(exportStarFunction_1); + return exportStarFunction_1.name; + } + } + var exportedNames = []; + if (moduleInfo.exportedNames) { + for (var _b = 0, _c = moduleInfo.exportedNames; _b < _c.length; _b++) { + var exportedLocalName = _c[_b]; + if (exportedLocalName.escapedText === "default") { + continue; + } + // write name of exported declaration, i.e 'export var x...' + exportedNames.push(ts.createPropertyAssignment(ts.createLiteral(exportedLocalName), ts.createTrue())); + } + } + for (var _d = 0, _e = moduleInfo.externalImports; _d < _e.length; _d++) { + var externalImport = _e[_d]; + if (externalImport.kind !== 255 /* ExportDeclaration */) { + continue; + } + if (!externalImport.exportClause) { + // export * from ... + continue; + } + for (var _f = 0, _g = externalImport.exportClause.elements; _f < _g.length; _f++) { + var element = _g[_f]; + // write name of indirectly exported entry, i.e. 'export {x} from ...' + exportedNames.push(ts.createPropertyAssignment(ts.createLiteral(ts.idText(element.name || element.propertyName)), ts.createTrue())); + } + } + var exportedNamesStorageRef = ts.createUniqueName("exportedNames"); + statements.push(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(exportedNamesStorageRef, + /*type*/ undefined, ts.createObjectLiteral(exportedNames, /*multiline*/ true)) + ]))); + var exportStarFunction = createExportStarFunction(exportedNamesStorageRef); + statements.push(exportStarFunction); + return exportStarFunction.name; + } + /** + * Creates an exportStar function for the file, with an optional set of excluded local + * names. + * + * @param localNames An optional reference to an object containing a set of excluded local + * names. + */ + function createExportStarFunction(localNames) { + var exportStarFunction = ts.createUniqueName("exportStar"); + var m = ts.createIdentifier("m"); + var n = ts.createIdentifier("n"); + var exports = ts.createIdentifier("exports"); + var condition = ts.createStrictInequality(n, ts.createLiteral("default")); + if (localNames) { + condition = ts.createLogicalAnd(condition, ts.createLogicalNot(ts.createCall(ts.createPropertyAccess(localNames, "hasOwnProperty"), + /*typeArguments*/ undefined, [n]))); + } + return ts.createFunctionDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, exportStarFunction, + /*typeParameters*/ undefined, [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, m)], + /*type*/ undefined, ts.createBlock([ + ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(exports, + /*type*/ undefined, ts.createObjectLiteral([])) + ])), + ts.createForIn(ts.createVariableDeclarationList([ + ts.createVariableDeclaration(n, /*type*/ undefined) + ]), m, ts.createBlock([ + ts.setEmitFlags(ts.createIf(condition, ts.createExpressionStatement(ts.createAssignment(ts.createElementAccess(exports, n), ts.createElementAccess(m, n)))), 1 /* SingleLine */) + ])), + ts.createExpressionStatement(ts.createCall(exportFunction, + /*typeArguments*/ undefined, [exports])) + ], /*multiline*/ true)); + } + /** + * Creates an array setter callbacks for each dependency group. + * + * @param exportStarFunction A reference to an exportStarFunction for the file. + * @param dependencyGroups An array of grouped dependencies. + */ + function createSettersArray(exportStarFunction, dependencyGroups) { + var setters = []; + for (var _i = 0, dependencyGroups_1 = dependencyGroups; _i < dependencyGroups_1.length; _i++) { + var group_1 = dependencyGroups_1[_i]; + // derive a unique name for parameter from the first named entry in the group + var localName = ts.forEach(group_1.externalImports, function (i) { return ts.getLocalNameForExternalImport(i, currentSourceFile); }); + var parameterName = localName ? ts.getGeneratedNameForNode(localName) : ts.createUniqueName(""); + var statements = []; + for (var _a = 0, _b = group_1.externalImports; _a < _b.length; _a++) { + var entry = _b[_a]; + var importVariableName = ts.getLocalNameForExternalImport(entry, currentSourceFile); // TODO: GH#18217 + switch (entry.kind) { + case 249 /* ImportDeclaration */: + if (!entry.importClause) { + // 'import "..."' case + // module is imported only for side-effects, no emit required + break; + } + // falls through + case 248 /* ImportEqualsDeclaration */: + ts.Debug.assert(importVariableName !== undefined); + // save import into the local + statements.push(ts.createExpressionStatement(ts.createAssignment(importVariableName, parameterName))); + break; + case 255 /* ExportDeclaration */: + ts.Debug.assert(importVariableName !== undefined); + if (entry.exportClause) { + // export {a, b as c} from 'foo' + // + // emit as: + // + // exports_({ + // "a": _["a"], + // "c": _["b"] + // }); + var properties = []; + for (var _c = 0, _d = entry.exportClause.elements; _c < _d.length; _c++) { + var e = _d[_c]; + properties.push(ts.createPropertyAssignment(ts.createLiteral(ts.idText(e.name)), ts.createElementAccess(parameterName, ts.createLiteral(ts.idText(e.propertyName || e.name))))); + } + statements.push(ts.createExpressionStatement(ts.createCall(exportFunction, + /*typeArguments*/ undefined, [ts.createObjectLiteral(properties, /*multiline*/ true)]))); + } + else { + // export * from 'foo' + // + // emit as: + // + // exportStar(foo_1_1); + statements.push(ts.createExpressionStatement(ts.createCall(exportStarFunction, + /*typeArguments*/ undefined, [parameterName]))); + } + break; + } + } + setters.push(ts.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, parameterName)], + /*type*/ undefined, ts.createBlock(statements, /*multiLine*/ true))); + } + return ts.createArrayLiteral(setters, /*multiLine*/ true); + } + // + // Top-level Source Element Visitors + // + /** + * Visit source elements at the top-level of a module. + * + * @param node The node to visit. + */ + function sourceElementVisitor(node) { + switch (node.kind) { + case 249 /* ImportDeclaration */: + return visitImportDeclaration(node); + case 248 /* ImportEqualsDeclaration */: + return visitImportEqualsDeclaration(node); + case 255 /* ExportDeclaration */: + // ExportDeclarations are elided as they are handled via + // `appendExportsOfDeclaration`. + return undefined; + case 254 /* ExportAssignment */: + return visitExportAssignment(node); + default: + return nestedElementVisitor(node); + } + } + /** + * Visits an ImportDeclaration node. + * + * @param node The node to visit. + */ + function visitImportDeclaration(node) { + var statements; + if (node.importClause) { + hoistVariableDeclaration(ts.getLocalNameForExternalImport(node, currentSourceFile)); // TODO: GH#18217 + } + if (hasAssociatedEndOfDeclarationMarker(node)) { + // Defer exports until we encounter an EndOfDeclarationMarker node + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportsOfImportDeclaration(deferredExports[id], node); + } + else { + statements = appendExportsOfImportDeclaration(statements, node); + } + return ts.singleOrMany(statements); + } + /** + * Visits an ImportEqualsDeclaration node. + * + * @param node The node to visit. + */ + function visitImportEqualsDeclaration(node) { + ts.Debug.assert(ts.isExternalModuleImportEqualsDeclaration(node), "import= for internal module references should be handled in an earlier transformer."); + var statements; + hoistVariableDeclaration(ts.getLocalNameForExternalImport(node, currentSourceFile)); // TODO: GH#18217 + if (hasAssociatedEndOfDeclarationMarker(node)) { + // Defer exports until we encounter an EndOfDeclarationMarker node + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportsOfImportEqualsDeclaration(deferredExports[id], node); + } + else { + statements = appendExportsOfImportEqualsDeclaration(statements, node); + } + return ts.singleOrMany(statements); + } + /** + * Visits an ExportAssignment node. + * + * @param node The node to visit. + */ + function visitExportAssignment(node) { + if (node.isExportEquals) { + // Elide `export=` as it is illegal in a SystemJS module. + return undefined; + } + var expression = ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression); + var original = node.original; + if (original && hasAssociatedEndOfDeclarationMarker(original)) { + // Defer exports until we encounter an EndOfDeclarationMarker node + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportStatement(deferredExports[id], ts.createIdentifier("default"), expression, /*allowComments*/ true); + } + else { + return createExportStatement(ts.createIdentifier("default"), expression, /*allowComments*/ true); + } + } + /** + * Visits a FunctionDeclaration, hoisting it to the outer module body function. + * + * @param node The node to visit. + */ + function visitFunctionDeclaration(node) { + if (ts.hasModifier(node, 1 /* Export */)) { + hoistedStatements = ts.append(hoistedStatements, ts.updateFunctionDeclaration(node, node.decorators, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, ts.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true), + /*typeParameters*/ undefined, ts.visitNodes(node.parameters, destructuringAndImportCallVisitor, ts.isParameterDeclaration), + /*type*/ undefined, ts.visitNode(node.body, destructuringAndImportCallVisitor, ts.isBlock))); + } + else { + hoistedStatements = ts.append(hoistedStatements, ts.visitEachChild(node, destructuringAndImportCallVisitor, context)); + } + if (hasAssociatedEndOfDeclarationMarker(node)) { + // Defer exports until we encounter an EndOfDeclarationMarker node + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node); + } + else { + hoistedStatements = appendExportsOfHoistedDeclaration(hoistedStatements, node); + } + return undefined; + } + /** + * Visits a ClassDeclaration, hoisting its name to the outer module body function. + * + * @param node The node to visit. + */ + function visitClassDeclaration(node) { + var statements; + // Hoist the name of the class declaration to the outer module body function. + var name = ts.getLocalName(node); + hoistVariableDeclaration(name); + // Rewrite the class declaration into an assignment of a class expression. + statements = ts.append(statements, ts.setTextRange(ts.createExpressionStatement(ts.createAssignment(name, ts.setTextRange(ts.createClassExpression( + /*modifiers*/ undefined, node.name, + /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, destructuringAndImportCallVisitor, ts.isHeritageClause), ts.visitNodes(node.members, destructuringAndImportCallVisitor, ts.isClassElement)), node))), node)); + if (hasAssociatedEndOfDeclarationMarker(node)) { + // Defer exports until we encounter an EndOfDeclarationMarker node + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node); + } + else { + statements = appendExportsOfHoistedDeclaration(statements, node); + } + return ts.singleOrMany(statements); + } + /** + * Visits a variable statement, hoisting declared names to the top-level module body. + * Each declaration is rewritten into an assignment expression. + * + * @param node The node to visit. + */ + function visitVariableStatement(node) { + if (!shouldHoistVariableDeclarationList(node.declarationList)) { + return ts.visitNode(node, destructuringAndImportCallVisitor, ts.isStatement); + } + var expressions; + var isExportedDeclaration = ts.hasModifier(node, 1 /* Export */); + var isMarkedDeclaration = hasAssociatedEndOfDeclarationMarker(node); + for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { + var variable = _a[_i]; + if (variable.initializer) { + expressions = ts.append(expressions, transformInitializedVariable(variable, isExportedDeclaration && !isMarkedDeclaration)); + } + else { + hoistBindingElement(variable); + } + } + var statements; + if (expressions) { + statements = ts.append(statements, ts.setTextRange(ts.createExpressionStatement(ts.inlineExpressions(expressions)), node)); + } + if (isMarkedDeclaration) { + // Defer exports until we encounter an EndOfDeclarationMarker node + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node, isExportedDeclaration); + } + else { + statements = appendExportsOfVariableStatement(statements, node, /*exportSelf*/ false); + } + return ts.singleOrMany(statements); + } + /** + * Hoists the declared names of a VariableDeclaration or BindingElement. + * + * @param node The declaration to hoist. + */ + function hoistBindingElement(node) { + if (ts.isBindingPattern(node.name)) { + for (var _i = 0, _a = node.name.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (!ts.isOmittedExpression(element)) { + hoistBindingElement(element); + } + } + } + else { + hoistVariableDeclaration(ts.getSynthesizedClone(node.name)); + } + } + /** + * Determines whether a VariableDeclarationList should be hoisted. + * + * @param node The node to test. + */ + function shouldHoistVariableDeclarationList(node) { + // hoist only non-block scoped declarations or block scoped declarations parented by source file + return (ts.getEmitFlags(node) & 2097152 /* NoHoisting */) === 0 + && (enclosingBlockScopedContainer.kind === 279 /* SourceFile */ + || (ts.getOriginalNode(node).flags & 3 /* BlockScoped */) === 0); + } + /** + * Transform an initialized variable declaration into an expression. + * + * @param node The node to transform. + * @param isExportedDeclaration A value indicating whether the variable is exported. + */ + function transformInitializedVariable(node, isExportedDeclaration) { + var createAssignment = isExportedDeclaration ? createExportedVariableAssignment : createNonExportedVariableAssignment; + return ts.isBindingPattern(node.name) + ? ts.flattenDestructuringAssignment(node, destructuringAndImportCallVisitor, context, 0 /* All */, + /*needsValue*/ false, createAssignment) + : node.initializer ? createAssignment(node.name, ts.visitNode(node.initializer, destructuringAndImportCallVisitor, ts.isExpression)) : node.name; + } + /** + * Creates an assignment expression for an exported variable declaration. + * + * @param name The name of the variable. + * @param value The value of the variable's initializer. + * @param location The source map location for the assignment. + */ + function createExportedVariableAssignment(name, value, location) { + return createVariableAssignment(name, value, location, /*isExportedDeclaration*/ true); + } + /** + * Creates an assignment expression for a non-exported variable declaration. + * + * @param name The name of the variable. + * @param value The value of the variable's initializer. + * @param location The source map location for the assignment. + */ + function createNonExportedVariableAssignment(name, value, location) { + return createVariableAssignment(name, value, location, /*isExportedDeclaration*/ false); + } + /** + * Creates an assignment expression for a variable declaration. + * + * @param name The name of the variable. + * @param value The value of the variable's initializer. + * @param location The source map location for the assignment. + * @param isExportedDeclaration A value indicating whether the variable is exported. + */ + function createVariableAssignment(name, value, location, isExportedDeclaration) { + hoistVariableDeclaration(ts.getSynthesizedClone(name)); + return isExportedDeclaration + ? createExportExpression(name, preventSubstitution(ts.setTextRange(ts.createAssignment(name, value), location))) + : preventSubstitution(ts.setTextRange(ts.createAssignment(name, value), location)); + } + /** + * Visits a MergeDeclarationMarker used as a placeholder for the beginning of a merged + * and transformed declaration. + * + * @param node The node to visit. + */ + function visitMergeDeclarationMarker(node) { + // For an EnumDeclaration or ModuleDeclaration that merges with a preceeding + // declaration we do not emit a leading variable declaration. To preserve the + // begin/end semantics of the declararation and to properly handle exports + // we wrapped the leading variable declaration in a `MergeDeclarationMarker`. + // + // To balance the declaration, we defer the exports of the elided variable + // statement until we visit this declaration's `EndOfDeclarationMarker`. + if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 219 /* VariableStatement */) { + var id = ts.getOriginalNodeId(node); + var isExportedDeclaration = ts.hasModifier(node.original, 1 /* Export */); + deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node.original, isExportedDeclaration); + } + return node; + } + /** + * Determines whether a node has an associated EndOfDeclarationMarker. + * + * @param node The node to test. + */ + function hasAssociatedEndOfDeclarationMarker(node) { + return (ts.getEmitFlags(node) & 4194304 /* HasEndOfDeclarationMarker */) !== 0; + } + /** + * Visits a DeclarationMarker used as a placeholder for the end of a transformed + * declaration. + * + * @param node The node to visit. + */ + function visitEndOfDeclarationMarker(node) { + // For some transformations we emit an `EndOfDeclarationMarker` to mark the actual + // end of the transformed declaration. We use this marker to emit any deferred exports + // of the declaration. + var id = ts.getOriginalNodeId(node); + var statements = deferredExports[id]; + if (statements) { + delete deferredExports[id]; + return ts.append(statements, node); + } + else { + var original = ts.getOriginalNode(node); + if (ts.isModuleOrEnumDeclaration(original)) { + return ts.append(appendExportsOfDeclaration(statements, original), node); + } + } + return node; + } + /** + * Appends the exports of an ImportDeclaration to a statement list, returning the + * statement list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param decl The declaration whose exports are to be recorded. + */ + function appendExportsOfImportDeclaration(statements, decl) { + if (moduleInfo.exportEquals) { + return statements; + } + var importClause = decl.importClause; + if (!importClause) { + return statements; + } + if (importClause.name) { + statements = appendExportsOfDeclaration(statements, importClause); + } + var namedBindings = importClause.namedBindings; + if (namedBindings) { + switch (namedBindings.kind) { + case 251 /* NamespaceImport */: + statements = appendExportsOfDeclaration(statements, namedBindings); + break; + case 252 /* NamedImports */: + for (var _i = 0, _a = namedBindings.elements; _i < _a.length; _i++) { + var importBinding = _a[_i]; + statements = appendExportsOfDeclaration(statements, importBinding); + } + break; + } + } + return statements; + } + /** + * Appends the export of an ImportEqualsDeclaration to a statement list, returning the + * statement list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param decl The declaration whose exports are to be recorded. + */ + function appendExportsOfImportEqualsDeclaration(statements, decl) { + if (moduleInfo.exportEquals) { + return statements; + } + return appendExportsOfDeclaration(statements, decl); + } + /** + * Appends the exports of a VariableStatement to a statement list, returning the statement + * list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param node The VariableStatement whose exports are to be recorded. + * @param exportSelf A value indicating whether to also export each VariableDeclaration of + * `nodes` declaration list. + */ + function appendExportsOfVariableStatement(statements, node, exportSelf) { + if (moduleInfo.exportEquals) { + return statements; + } + for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + if (decl.initializer || exportSelf) { + statements = appendExportsOfBindingElement(statements, decl, exportSelf); + } + } + return statements; + } + /** + * Appends the exports of a VariableDeclaration or BindingElement to a statement list, + * returning the statement list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param decl The declaration whose exports are to be recorded. + * @param exportSelf A value indicating whether to also export the declaration itself. + */ + function appendExportsOfBindingElement(statements, decl, exportSelf) { + if (moduleInfo.exportEquals) { + return statements; + } + if (ts.isBindingPattern(decl.name)) { + for (var _i = 0, _a = decl.name.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (!ts.isOmittedExpression(element)) { + statements = appendExportsOfBindingElement(statements, element, exportSelf); + } + } + } + else if (!ts.isGeneratedIdentifier(decl.name)) { + var excludeName = void 0; + if (exportSelf) { + statements = appendExportStatement(statements, decl.name, ts.getLocalName(decl)); + excludeName = ts.idText(decl.name); + } + statements = appendExportsOfDeclaration(statements, decl, excludeName); + } + return statements; + } + /** + * Appends the exports of a ClassDeclaration or FunctionDeclaration to a statement list, + * returning the statement list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param decl The declaration whose exports are to be recorded. + */ + function appendExportsOfHoistedDeclaration(statements, decl) { + if (moduleInfo.exportEquals) { + return statements; + } + var excludeName; + if (ts.hasModifier(decl, 1 /* Export */)) { + var exportName = ts.hasModifier(decl, 512 /* Default */) ? ts.createLiteral("default") : decl.name; + statements = appendExportStatement(statements, exportName, ts.getLocalName(decl)); + excludeName = ts.getTextOfIdentifierOrLiteral(exportName); + } + if (decl.name) { + statements = appendExportsOfDeclaration(statements, decl, excludeName); + } + return statements; + } + /** + * Appends the exports of a declaration to a statement list, returning the statement list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param decl The declaration to export. + * @param excludeName An optional name to exclude from exports. + */ + function appendExportsOfDeclaration(statements, decl, excludeName) { + if (moduleInfo.exportEquals) { + return statements; + } + var name = ts.getDeclarationName(decl); + var exportSpecifiers = moduleInfo.exportSpecifiers.get(ts.idText(name)); + if (exportSpecifiers) { + for (var _i = 0, exportSpecifiers_2 = exportSpecifiers; _i < exportSpecifiers_2.length; _i++) { + var exportSpecifier = exportSpecifiers_2[_i]; + if (exportSpecifier.name.escapedText !== excludeName) { + statements = appendExportStatement(statements, exportSpecifier.name, name); + } + } + } + return statements; + } + /** + * Appends the down-level representation of an export to a statement list, returning the + * statement list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param exportName The name of the export. + * @param expression The expression to export. + * @param allowComments Whether to allow comments on the export. + */ + function appendExportStatement(statements, exportName, expression, allowComments) { + statements = ts.append(statements, createExportStatement(exportName, expression, allowComments)); + return statements; + } + /** + * Creates a call to the current file's export function to export a value. + * + * @param name The bound name of the export. + * @param value The exported value. + * @param allowComments An optional value indicating whether to emit comments for the statement. + */ + function createExportStatement(name, value, allowComments) { + var statement = ts.createExpressionStatement(createExportExpression(name, value)); + ts.startOnNewLine(statement); + if (!allowComments) { + ts.setEmitFlags(statement, 1536 /* NoComments */); + } + return statement; + } + /** + * Creates a call to the current file's export function to export a value. + * + * @param name The bound name of the export. + * @param value The exported value. + */ + function createExportExpression(name, value) { + var exportName = ts.isIdentifier(name) ? ts.createLiteral(name) : name; + ts.setEmitFlags(value, ts.getEmitFlags(value) | 1536 /* NoComments */); + return ts.setCommentRange(ts.createCall(exportFunction, /*typeArguments*/ undefined, [exportName, value]), value); + } + // + // Top-Level or Nested Source Element Visitors + // + /** + * Visit nested elements at the top-level of a module. + * + * @param node The node to visit. + */ + function nestedElementVisitor(node) { + switch (node.kind) { + case 219 /* VariableStatement */: + return visitVariableStatement(node); + case 239 /* FunctionDeclaration */: + return visitFunctionDeclaration(node); + case 240 /* ClassDeclaration */: + return visitClassDeclaration(node); + case 225 /* ForStatement */: + return visitForStatement(node); + case 226 /* ForInStatement */: + return visitForInStatement(node); + case 227 /* ForOfStatement */: + return visitForOfStatement(node); + case 223 /* DoStatement */: + return visitDoStatement(node); + case 224 /* WhileStatement */: + return visitWhileStatement(node); + case 233 /* LabeledStatement */: + return visitLabeledStatement(node); + case 231 /* WithStatement */: + return visitWithStatement(node); + case 232 /* SwitchStatement */: + return visitSwitchStatement(node); + case 246 /* CaseBlock */: + return visitCaseBlock(node); + case 271 /* CaseClause */: + return visitCaseClause(node); + case 272 /* DefaultClause */: + return visitDefaultClause(node); + case 235 /* TryStatement */: + return visitTryStatement(node); + case 274 /* CatchClause */: + return visitCatchClause(node); + case 218 /* Block */: + return visitBlock(node); + case 310 /* MergeDeclarationMarker */: + return visitMergeDeclarationMarker(node); + case 311 /* EndOfDeclarationMarker */: + return visitEndOfDeclarationMarker(node); + default: + return destructuringAndImportCallVisitor(node); + } + } + /** + * Visits the body of a ForStatement to hoist declarations. + * + * @param node The node to visit. + */ + function visitForStatement(node) { + var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; + enclosingBlockScopedContainer = node; + node = ts.updateFor(node, node.initializer && visitForInitializer(node.initializer), ts.visitNode(node.condition, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.incrementor, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement)); + enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; + return node; + } + /** + * Visits the body of a ForInStatement to hoist declarations. + * + * @param node The node to visit. + */ + function visitForInStatement(node) { + var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; + enclosingBlockScopedContainer = node; + node = ts.updateForIn(node, visitForInitializer(node.initializer), ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock)); + enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; + return node; + } + /** + * Visits the body of a ForOfStatement to hoist declarations. + * + * @param node The node to visit. + */ + function visitForOfStatement(node) { + var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; + enclosingBlockScopedContainer = node; + node = ts.updateForOf(node, node.awaitModifier, visitForInitializer(node.initializer), ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock)); + enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; + return node; + } + /** + * Determines whether to hoist the initializer of a ForStatement, ForInStatement, or + * ForOfStatement. + * + * @param node The node to test. + */ + function shouldHoistForInitializer(node) { + return ts.isVariableDeclarationList(node) + && shouldHoistVariableDeclarationList(node); + } + /** + * Visits the initializer of a ForStatement, ForInStatement, or ForOfStatement + * + * @param node The node to visit. + */ + function visitForInitializer(node) { + if (shouldHoistForInitializer(node)) { + var expressions = void 0; + for (var _i = 0, _a = node.declarations; _i < _a.length; _i++) { + var variable = _a[_i]; + expressions = ts.append(expressions, transformInitializedVariable(variable, /*isExportedDeclaration*/ false)); + if (!variable.initializer) { + hoistBindingElement(variable); + } + } + return expressions ? ts.inlineExpressions(expressions) : ts.createOmittedExpression(); + } + else { + return ts.visitEachChild(node, nestedElementVisitor, context); + } + } + /** + * Visits the body of a DoStatement to hoist declarations. + * + * @param node The node to visit. + */ + function visitDoStatement(node) { + return ts.updateDo(node, ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock), ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression)); + } + /** + * Visits the body of a WhileStatement to hoist declarations. + * + * @param node The node to visit. + */ + function visitWhileStatement(node) { + return ts.updateWhile(node, ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock)); + } + /** + * Visits the body of a LabeledStatement to hoist declarations. + * + * @param node The node to visit. + */ + function visitLabeledStatement(node) { + return ts.updateLabel(node, node.label, ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock)); + } + /** + * Visits the body of a WithStatement to hoist declarations. + * + * @param node The node to visit. + */ + function visitWithStatement(node) { + return ts.updateWith(node, ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock)); + } + /** + * Visits the body of a SwitchStatement to hoist declarations. + * + * @param node The node to visit. + */ + function visitSwitchStatement(node) { + return ts.updateSwitch(node, ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.caseBlock, nestedElementVisitor, ts.isCaseBlock)); + } + /** + * Visits the body of a CaseBlock to hoist declarations. + * + * @param node The node to visit. + */ + function visitCaseBlock(node) { + var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; + enclosingBlockScopedContainer = node; + node = ts.updateCaseBlock(node, ts.visitNodes(node.clauses, nestedElementVisitor, ts.isCaseOrDefaultClause)); + enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; + return node; + } + /** + * Visits the body of a CaseClause to hoist declarations. + * + * @param node The node to visit. + */ + function visitCaseClause(node) { + return ts.updateCaseClause(node, ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNodes(node.statements, nestedElementVisitor, ts.isStatement)); + } + /** + * Visits the body of a DefaultClause to hoist declarations. + * + * @param node The node to visit. + */ + function visitDefaultClause(node) { + return ts.visitEachChild(node, nestedElementVisitor, context); + } + /** + * Visits the body of a TryStatement to hoist declarations. + * + * @param node The node to visit. + */ + function visitTryStatement(node) { + return ts.visitEachChild(node, nestedElementVisitor, context); + } + /** + * Visits the body of a CatchClause to hoist declarations. + * + * @param node The node to visit. + */ + function visitCatchClause(node) { + var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; + enclosingBlockScopedContainer = node; + node = ts.updateCatchClause(node, node.variableDeclaration, ts.visitNode(node.block, nestedElementVisitor, ts.isBlock)); + enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; + return node; + } + /** + * Visits the body of a Block to hoist declarations. + * + * @param node The node to visit. + */ + function visitBlock(node) { + var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; + enclosingBlockScopedContainer = node; + node = ts.visitEachChild(node, nestedElementVisitor, context); + enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; + return node; + } + // + // Destructuring Assignment Visitors + // + /** + * Visit nodes to flatten destructuring assignments to exported symbols. + * + * @param node The node to visit. + */ + function destructuringAndImportCallVisitor(node) { + if (node.transformFlags & 1024 /* DestructuringAssignment */ + && node.kind === 204 /* BinaryExpression */) { + return visitDestructuringAssignment(node); + } + else if (ts.isImportCall(node)) { + return visitImportCallExpression(node); + } + else if ((node.transformFlags & 2048 /* ContainsDestructuringAssignment */) || (node.transformFlags & 16777216 /* ContainsDynamicImport */)) { + return ts.visitEachChild(node, destructuringAndImportCallVisitor, context); + } + else { + return node; + } + } + function visitImportCallExpression(node) { + // import("./blah") + // emit as + // System.register([], function (_export, _context) { + // return { + // setters: [], + // execute: () => { + // _context.import('./blah'); + // } + // }; + // }); + return ts.createCall(ts.createPropertyAccess(contextObject, ts.createIdentifier("import")), + /*typeArguments*/ undefined, ts.some(node.arguments) ? [ts.visitNode(node.arguments[0], destructuringAndImportCallVisitor)] : []); + } + /** + * Visits a DestructuringAssignment to flatten destructuring to exported symbols. + * + * @param node The node to visit. + */ + function visitDestructuringAssignment(node) { + if (hasExportedReferenceInDestructuringTarget(node.left)) { + return ts.flattenDestructuringAssignment(node, destructuringAndImportCallVisitor, context, 0 /* All */, + /*needsValue*/ true); + } + return ts.visitEachChild(node, destructuringAndImportCallVisitor, context); + } + /** + * Determines whether the target of a destructuring assigment refers to an exported symbol. + * + * @param node The destructuring target. + */ + function hasExportedReferenceInDestructuringTarget(node) { + if (ts.isAssignmentExpression(node, /*excludeCompoundAssignment*/ true)) { + return hasExportedReferenceInDestructuringTarget(node.left); + } + else if (ts.isSpreadElement(node)) { + return hasExportedReferenceInDestructuringTarget(node.expression); + } + else if (ts.isObjectLiteralExpression(node)) { + return ts.some(node.properties, hasExportedReferenceInDestructuringTarget); + } + else if (ts.isArrayLiteralExpression(node)) { + return ts.some(node.elements, hasExportedReferenceInDestructuringTarget); + } + else if (ts.isShorthandPropertyAssignment(node)) { + return hasExportedReferenceInDestructuringTarget(node.name); + } + else if (ts.isPropertyAssignment(node)) { + return hasExportedReferenceInDestructuringTarget(node.initializer); + } + else if (ts.isIdentifier(node)) { + var container = resolver.getReferencedExportContainer(node); + return container !== undefined && container.kind === 279 /* SourceFile */; + } + else { + return false; + } + } + // + // Modifier Visitors + // + /** + * Visit nodes to elide module-specific modifiers. + * + * @param node The node to visit. + */ + function modifierVisitor(node) { + switch (node.kind) { + case 85 /* ExportKeyword */: + case 80 /* DefaultKeyword */: + return undefined; + } + return node; + } + // + // Emit Notification + // + /** + * Hook for node emit notifications. + * + * @param hint A hint as to the intended usage of the node. + * @param node The node to emit. + * @param emitCallback A callback used to emit the node in the printer. + */ + function onEmitNode(hint, node, emitCallback) { + if (node.kind === 279 /* SourceFile */) { + var id = ts.getOriginalNodeId(node); + currentSourceFile = node; + moduleInfo = moduleInfoMap[id]; + exportFunction = exportFunctionsMap[id]; + noSubstitution = noSubstitutionMap[id]; + if (noSubstitution) { + delete noSubstitutionMap[id]; + } + previousOnEmitNode(hint, node, emitCallback); + currentSourceFile = undefined; + moduleInfo = undefined; + exportFunction = undefined; + noSubstitution = undefined; + } + else { + previousOnEmitNode(hint, node, emitCallback); + } + } + // + // Substitutions + // + /** + * Hooks node substitutions. + * + * @param hint A hint as to the intended usage of the node. + * @param node The node to substitute. + */ + function onSubstituteNode(hint, node) { + node = previousOnSubstituteNode(hint, node); + if (isSubstitutionPrevented(node)) { + return node; + } + if (hint === 1 /* Expression */) { + return substituteExpression(node); + } + else if (hint === 4 /* Unspecified */) { + return substituteUnspecified(node); + } + return node; + } + /** + * Substitute the node, if necessary. + * + * @param node The node to substitute. + */ + function substituteUnspecified(node) { + switch (node.kind) { + case 276 /* ShorthandPropertyAssignment */: + return substituteShorthandPropertyAssignment(node); + } + return node; + } + /** + * Substitution for a ShorthandPropertyAssignment whose name that may contain an imported or exported symbol. + * + * @param node The node to substitute. + */ + function substituteShorthandPropertyAssignment(node) { + var name = node.name; + if (!ts.isGeneratedIdentifier(name) && !ts.isLocalName(name)) { + var importDeclaration = resolver.getReferencedImportDeclaration(name); + if (importDeclaration) { + if (ts.isImportClause(importDeclaration)) { + return ts.setTextRange(ts.createPropertyAssignment(ts.getSynthesizedClone(name), ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent), ts.createIdentifier("default"))), + /*location*/ node); + } + else if (ts.isImportSpecifier(importDeclaration)) { + return ts.setTextRange(ts.createPropertyAssignment(ts.getSynthesizedClone(name), ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent.parent.parent), ts.getSynthesizedClone(importDeclaration.propertyName || importDeclaration.name))), + /*location*/ node); + } + } + } + return node; + } + /** + * Substitute the expression, if necessary. + * + * @param node The node to substitute. + */ + function substituteExpression(node) { + switch (node.kind) { + case 72 /* Identifier */: + return substituteExpressionIdentifier(node); + case 204 /* BinaryExpression */: + return substituteBinaryExpression(node); + case 202 /* PrefixUnaryExpression */: + case 203 /* PostfixUnaryExpression */: + return substituteUnaryExpression(node); + } + return node; + } + /** + * Substitution for an Identifier expression that may contain an imported or exported symbol. + * + * @param node The node to substitute. + */ + function substituteExpressionIdentifier(node) { + if (ts.getEmitFlags(node) & 4096 /* HelperName */) { + var externalHelpersModuleName = ts.getExternalHelpersModuleName(currentSourceFile); + if (externalHelpersModuleName) { + return ts.createPropertyAccess(externalHelpersModuleName, node); + } + return node; + } + // When we see an identifier in an expression position that + // points to an imported symbol, we should substitute a qualified + // reference to the imported symbol if one is needed. + // + // - We do not substitute generated identifiers for any reason. + // - We do not substitute identifiers tagged with the LocalName flag. + if (!ts.isGeneratedIdentifier(node) && !ts.isLocalName(node)) { + var importDeclaration = resolver.getReferencedImportDeclaration(node); + if (importDeclaration) { + if (ts.isImportClause(importDeclaration)) { + return ts.setTextRange(ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent), ts.createIdentifier("default")), + /*location*/ node); + } + else if (ts.isImportSpecifier(importDeclaration)) { + return ts.setTextRange(ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent.parent.parent), ts.getSynthesizedClone(importDeclaration.propertyName || importDeclaration.name)), + /*location*/ node); + } + } + } + return node; + } + /** + * Substitution for a BinaryExpression that may contain an imported or exported symbol. + * + * @param node The node to substitute. + */ + function substituteBinaryExpression(node) { + // When we see an assignment expression whose left-hand side is an exported symbol, + // we should ensure all exports of that symbol are updated with the correct value. + // + // - We do not substitute generated identifiers for any reason. + // - We do not substitute identifiers tagged with the LocalName flag. + // - We do not substitute identifiers that were originally the name of an enum or + // namespace due to how they are transformed in TypeScript. + // - We only substitute identifiers that are exported at the top level. + if (ts.isAssignmentOperator(node.operatorToken.kind) + && ts.isIdentifier(node.left) + && !ts.isGeneratedIdentifier(node.left) + && !ts.isLocalName(node.left) + && !ts.isDeclarationNameOfEnumOrNamespace(node.left)) { + var exportedNames = getExports(node.left); + if (exportedNames) { + // For each additional export of the declaration, apply an export assignment. + var expression = node; + for (var _i = 0, exportedNames_4 = exportedNames; _i < exportedNames_4.length; _i++) { + var exportName = exportedNames_4[_i]; + expression = createExportExpression(exportName, preventSubstitution(expression)); + } + return expression; + } + } + return node; + } + /** + * Substitution for a UnaryExpression that may contain an imported or exported symbol. + * + * @param node The node to substitute. + */ + function substituteUnaryExpression(node) { + // When we see a prefix or postfix increment expression whose operand is an exported + // symbol, we should ensure all exports of that symbol are updated with the correct + // value. + // + // - We do not substitute generated identifiers for any reason. + // - We do not substitute identifiers tagged with the LocalName flag. + // - We do not substitute identifiers that were originally the name of an enum or + // namespace due to how they are transformed in TypeScript. + // - We only substitute identifiers that are exported at the top level. + if ((node.operator === 44 /* PlusPlusToken */ || node.operator === 45 /* MinusMinusToken */) + && ts.isIdentifier(node.operand) + && !ts.isGeneratedIdentifier(node.operand) + && !ts.isLocalName(node.operand) + && !ts.isDeclarationNameOfEnumOrNamespace(node.operand)) { + var exportedNames = getExports(node.operand); + if (exportedNames) { + var expression = node.kind === 203 /* PostfixUnaryExpression */ + ? ts.setTextRange(ts.createPrefix(node.operator, node.operand), node) + : node; + for (var _i = 0, exportedNames_5 = exportedNames; _i < exportedNames_5.length; _i++) { + var exportName = exportedNames_5[_i]; + expression = createExportExpression(exportName, preventSubstitution(expression)); + } + if (node.kind === 203 /* PostfixUnaryExpression */) { + expression = node.operator === 44 /* PlusPlusToken */ + ? ts.createSubtract(preventSubstitution(expression), ts.createLiteral(1)) + : ts.createAdd(preventSubstitution(expression), ts.createLiteral(1)); + } + return expression; + } + } + return node; + } + /** + * Gets the exports of a name. + * + * @param name The name. + */ + function getExports(name) { + var exportedNames; + if (!ts.isGeneratedIdentifier(name)) { + var valueDeclaration = resolver.getReferencedImportDeclaration(name) + || resolver.getReferencedValueDeclaration(name); + if (valueDeclaration) { + var exportContainer = resolver.getReferencedExportContainer(name, /*prefixLocals*/ false); + if (exportContainer && exportContainer.kind === 279 /* SourceFile */) { + exportedNames = ts.append(exportedNames, ts.getDeclarationName(valueDeclaration)); + } + exportedNames = ts.addRange(exportedNames, moduleInfo && moduleInfo.exportedBindings[ts.getOriginalNodeId(valueDeclaration)]); + } + } + return exportedNames; + } + /** + * Prevent substitution of a node for this transformer. + * + * @param node The node which should not be substituted. + */ + function preventSubstitution(node) { + if (noSubstitution === undefined) + noSubstitution = []; + noSubstitution[ts.getNodeId(node)] = true; + return node; + } + /** + * Determines whether a node should not be substituted. + * + * @param node The node to test. + */ + function isSubstitutionPrevented(node) { + return noSubstitution && node.id && noSubstitution[node.id]; + } + } + ts.transformSystemModule = transformSystemModule; +})(ts || (ts = {})); +/*@internal*/ +var ts; +(function (ts) { + function transformES2015Module(context) { + var compilerOptions = context.getCompilerOptions(); + var previousOnEmitNode = context.onEmitNode; + var previousOnSubstituteNode = context.onSubstituteNode; + context.onEmitNode = onEmitNode; + context.onSubstituteNode = onSubstituteNode; + context.enableEmitNotification(279 /* SourceFile */); + context.enableSubstitution(72 /* Identifier */); + var currentSourceFile; + return ts.chainBundle(transformSourceFile); + function transformSourceFile(node) { + if (node.isDeclarationFile) { + return node; + } + if (ts.isExternalModule(node) || compilerOptions.isolatedModules) { + var externalHelpersModuleName = ts.getOrCreateExternalHelpersModuleNameIfNeeded(node, compilerOptions); + if (externalHelpersModuleName) { + var statements = []; + var statementOffset = ts.addPrologue(statements, node.statements); + var tslibImport = ts.createImportDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(externalHelpersModuleName)), ts.createLiteral(ts.externalHelpersModuleNameText)); + ts.addEmitFlags(tslibImport, 67108864 /* NeverApplyImportHelper */); + ts.append(statements, tslibImport); + ts.addRange(statements, ts.visitNodes(node.statements, visitor, ts.isStatement, statementOffset)); + return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements)); + } + else { + return ts.visitEachChild(node, visitor, context); + } + } + return node; + } + function visitor(node) { + switch (node.kind) { + case 248 /* ImportEqualsDeclaration */: + // Elide `import=` as it is not legal with --module ES6 + return undefined; + case 254 /* ExportAssignment */: + return visitExportAssignment(node); + } + return node; + } + function visitExportAssignment(node) { + // Elide `export=` as it is not legal with --module ES6 + return node.isExportEquals ? undefined : node; + } + // + // Emit Notification + // + /** + * Hook for node emit. + * + * @param hint A hint as to the intended usage of the node. + * @param node The node to emit. + * @param emit A callback used to emit the node in the printer. + */ + function onEmitNode(hint, node, emitCallback) { + if (ts.isSourceFile(node)) { + currentSourceFile = node; + previousOnEmitNode(hint, node, emitCallback); + currentSourceFile = undefined; + } + else { + previousOnEmitNode(hint, node, emitCallback); + } + } + // + // Substitutions + // + /** + * Hooks node substitutions. + * + * @param hint A hint as to the intended usage of the node. + * @param node The node to substitute. + */ + function onSubstituteNode(hint, node) { + node = previousOnSubstituteNode(hint, node); + if (ts.isIdentifier(node) && hint === 1 /* Expression */) { + return substituteExpressionIdentifier(node); + } + return node; + } + function substituteExpressionIdentifier(node) { + if (ts.getEmitFlags(node) & 4096 /* HelperName */) { + var externalHelpersModuleName = ts.getExternalHelpersModuleName(currentSourceFile); + if (externalHelpersModuleName) { + return ts.createPropertyAccess(externalHelpersModuleName, node); + } + } + return node; + } + } + ts.transformES2015Module = transformES2015Module; +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + function canProduceDiagnostics(node) { + return ts.isVariableDeclaration(node) || + ts.isPropertyDeclaration(node) || + ts.isPropertySignature(node) || + ts.isBindingElement(node) || + ts.isSetAccessor(node) || + ts.isGetAccessor(node) || + ts.isConstructSignatureDeclaration(node) || + ts.isCallSignatureDeclaration(node) || + ts.isMethodDeclaration(node) || + ts.isMethodSignature(node) || + ts.isFunctionDeclaration(node) || + ts.isParameter(node) || + ts.isTypeParameterDeclaration(node) || + ts.isExpressionWithTypeArguments(node) || + ts.isImportEqualsDeclaration(node) || + ts.isTypeAliasDeclaration(node) || + ts.isConstructorDeclaration(node) || + ts.isIndexSignatureDeclaration(node); + } + ts.canProduceDiagnostics = canProduceDiagnostics; + function createGetSymbolAccessibilityDiagnosticForNodeName(node) { + if (ts.isSetAccessor(node) || ts.isGetAccessor(node)) { + return getAccessorNameVisibilityError; + } + else if (ts.isMethodSignature(node) || ts.isMethodDeclaration(node)) { + return getMethodNameVisibilityError; + } + else { + return createGetSymbolAccessibilityDiagnosticForNode(node); + } + function getAccessorNameVisibilityError(symbolAccessibilityResult) { + var diagnosticMessage = getAccessorNameVisibilityDiagnosticMessage(symbolAccessibilityResult); + return diagnosticMessage !== undefined ? { + diagnosticMessage: diagnosticMessage, + errorNode: node, + typeName: node.name + } : undefined; + } + function getAccessorNameVisibilityDiagnosticMessage(symbolAccessibilityResult) { + if (ts.hasModifier(node, 32 /* Static */)) { + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1; + } + else if (node.parent.kind === 240 /* ClassDeclaration */) { + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_private_name_1; + } + else { + return symbolAccessibilityResult.errorModuleName ? + ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_private_name_1; + } + } + function getMethodNameVisibilityError(symbolAccessibilityResult) { + var diagnosticMessage = getMethodNameVisibilityDiagnosticMessage(symbolAccessibilityResult); + return diagnosticMessage !== undefined ? { + diagnosticMessage: diagnosticMessage, + errorNode: node, + typeName: node.name + } : undefined; + } + function getMethodNameVisibilityDiagnosticMessage(symbolAccessibilityResult) { + if (ts.hasModifier(node, 32 /* Static */)) { + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_private_name_1; + } + else if (node.parent.kind === 240 /* ClassDeclaration */) { + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Public_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Public_method_0_of_exported_class_has_or_is_using_private_name_1; + } + else { + return symbolAccessibilityResult.errorModuleName ? + ts.Diagnostics.Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Method_0_of_exported_interface_has_or_is_using_private_name_1; + } + } + } + ts.createGetSymbolAccessibilityDiagnosticForNodeName = createGetSymbolAccessibilityDiagnosticForNodeName; + function createGetSymbolAccessibilityDiagnosticForNode(node) { + if (ts.isVariableDeclaration(node) || ts.isPropertyDeclaration(node) || ts.isPropertySignature(node) || ts.isBindingElement(node) || ts.isConstructorDeclaration(node)) { + return getVariableDeclarationTypeVisibilityError; + } + else if (ts.isSetAccessor(node) || ts.isGetAccessor(node)) { + return getAccessorDeclarationTypeVisibilityError; + } + else if (ts.isConstructSignatureDeclaration(node) || ts.isCallSignatureDeclaration(node) || ts.isMethodDeclaration(node) || ts.isMethodSignature(node) || ts.isFunctionDeclaration(node) || ts.isIndexSignatureDeclaration(node)) { + return getReturnTypeVisibilityError; + } + else if (ts.isParameter(node)) { + if (ts.isParameterPropertyDeclaration(node) && ts.hasModifier(node.parent, 8 /* Private */)) { + return getVariableDeclarationTypeVisibilityError; + } + return getParameterDeclarationTypeVisibilityError; + } + else if (ts.isTypeParameterDeclaration(node)) { + return getTypeParameterConstraintVisibilityError; + } + else if (ts.isExpressionWithTypeArguments(node)) { + return getHeritageClauseVisibilityError; + } + else if (ts.isImportEqualsDeclaration(node)) { + return getImportEntityNameVisibilityError; + } + else if (ts.isTypeAliasDeclaration(node)) { + return getTypeAliasDeclarationVisibilityError; + } + else { + return ts.Debug.assertNever(node, "Attempted to set a declaration diagnostic context for unhandled node kind: " + ts.SyntaxKind[node.kind]); + } + function getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) { + if (node.kind === 237 /* VariableDeclaration */ || node.kind === 186 /* BindingElement */) { + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Exported_variable_0_has_or_is_using_private_name_1; + } + // This check is to ensure we don't report error on constructor parameter property as that error would be reported during parameter emit + // The only exception here is if the constructor was marked as private. we are not emitting the constructor parameters at all. + else if (node.kind === 154 /* PropertyDeclaration */ || node.kind === 153 /* PropertySignature */ || + (node.kind === 151 /* Parameter */ && ts.hasModifier(node.parent, 8 /* Private */))) { + // TODO(jfreeman): Deal with computed properties in error reporting. + if (ts.hasModifier(node, 32 /* Static */)) { + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1; + } + else if (node.parent.kind === 240 /* ClassDeclaration */ || node.kind === 151 /* Parameter */) { + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_private_name_1; + } + else { + // Interfaces cannot have types that cannot be named + return symbolAccessibilityResult.errorModuleName ? + ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_private_name_1; + } + } + } + function getVariableDeclarationTypeVisibilityError(symbolAccessibilityResult) { + var diagnosticMessage = getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult); + return diagnosticMessage !== undefined ? { + diagnosticMessage: diagnosticMessage, + errorNode: node, + typeName: node.name + } : undefined; + } + function getAccessorDeclarationTypeVisibilityError(symbolAccessibilityResult) { + var diagnosticMessage; + if (node.kind === 159 /* SetAccessor */) { + // Getters can infer the return type from the returned expression, but setters cannot, so the + // "_from_external_module_1_but_cannot_be_named" case cannot occur. + if (ts.hasModifier(node, 32 /* Static */)) { + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + ts.Diagnostics.Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1; + } + else { + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + ts.Diagnostics.Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_private_name_1; + } + } + else { + if (ts.hasModifier(node, 32 /* Static */)) { + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_private_name_1; + } + else { + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Return_type_of_public_getter_0_from_exported_class_has_or_is_using_private_name_1; + } + } + return { + diagnosticMessage: diagnosticMessage, + errorNode: node.name, + typeName: node.name + }; + } + function getReturnTypeVisibilityError(symbolAccessibilityResult) { + var diagnosticMessage; + switch (node.kind) { + case 161 /* ConstructSignature */: + // Interfaces cannot have return types that cannot be named + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + ts.Diagnostics.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : + ts.Diagnostics.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0; + break; + case 160 /* CallSignature */: + // Interfaces cannot have return types that cannot be named + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + ts.Diagnostics.Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : + ts.Diagnostics.Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0; + break; + case 162 /* IndexSignature */: + // Interfaces cannot have return types that cannot be named + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + ts.Diagnostics.Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : + ts.Diagnostics.Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0; + break; + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + if (ts.hasModifier(node, 32 /* Static */)) { + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : + ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1 : + ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0; + } + else if (node.parent.kind === 240 /* ClassDeclaration */) { + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : + ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1 : + ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0; + } + else { + // Interfaces cannot have return types that cannot be named + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + ts.Diagnostics.Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : + ts.Diagnostics.Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0; + } + break; + case 239 /* FunctionDeclaration */: + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : + ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1 : + ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_private_name_0; + break; + default: + return ts.Debug.fail("This is unknown kind for signature: " + node.kind); + } + return { + diagnosticMessage: diagnosticMessage, + errorNode: node.name || node + }; + } + function getParameterDeclarationTypeVisibilityError(symbolAccessibilityResult) { + var diagnosticMessage = getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult); + return diagnosticMessage !== undefined ? { + diagnosticMessage: diagnosticMessage, + errorNode: node, + typeName: node.name + } : undefined; + } + function getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) { + switch (node.parent.kind) { + case 157 /* Constructor */: + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1; + case 161 /* ConstructSignature */: + case 166 /* ConstructorType */: + // Interfaces cannot have parameter types that cannot be named + return symbolAccessibilityResult.errorModuleName ? + ts.Diagnostics.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1; + case 160 /* CallSignature */: + // Interfaces cannot have parameter types that cannot be named + return symbolAccessibilityResult.errorModuleName ? + ts.Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1; + case 162 /* IndexSignature */: + // Interfaces cannot have parameter types that cannot be named + return symbolAccessibilityResult.errorModuleName ? + ts.Diagnostics.Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1; + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + if (ts.hasModifier(node.parent, 32 /* Static */)) { + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1; + } + else if (node.parent.parent.kind === 240 /* ClassDeclaration */) { + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1; + } + else { + // Interfaces cannot have parameter types that cannot be named + return symbolAccessibilityResult.errorModuleName ? + ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1; + } + case 239 /* FunctionDeclaration */: + case 165 /* FunctionType */: + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_private_name_1; + default: + return ts.Debug.fail("Unknown parent for parameter: " + ts.SyntaxKind[node.parent.kind]); + } + } + function getTypeParameterConstraintVisibilityError() { + // Type parameter constraints are named by user so we should always be able to name it + var diagnosticMessage; + switch (node.parent.kind) { + case 240 /* ClassDeclaration */: + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_class_has_or_is_using_private_name_1; + break; + case 241 /* InterfaceDeclaration */: + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1; + break; + case 161 /* ConstructSignature */: + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1; + break; + case 160 /* CallSignature */: + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1; + break; + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + if (ts.hasModifier(node.parent, 32 /* Static */)) { + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1; + } + else if (node.parent.parent.kind === 240 /* ClassDeclaration */) { + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1; + } + else { + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1; + } + break; + case 239 /* FunctionDeclaration */: + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_function_has_or_is_using_private_name_1; + break; + case 242 /* TypeAliasDeclaration */: + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1; + break; + default: + return ts.Debug.fail("This is unknown parent for type parameter: " + node.parent.kind); + } + return { + diagnosticMessage: diagnosticMessage, + errorNode: node, + typeName: node.name + }; + } + function getHeritageClauseVisibilityError() { + var diagnosticMessage; + // Heritage clause is written by user so it can always be named + if (node.parent.parent.kind === 240 /* ClassDeclaration */) { + // Class or Interface implemented/extended is inaccessible + diagnosticMessage = ts.isHeritageClause(node.parent) && node.parent.token === 109 /* ImplementsKeyword */ ? + ts.Diagnostics.Implements_clause_of_exported_class_0_has_or_is_using_private_name_1 : + ts.Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1; + } + else { + // interface is inaccessible + diagnosticMessage = ts.Diagnostics.extends_clause_of_exported_interface_0_has_or_is_using_private_name_1; + } + return { + diagnosticMessage: diagnosticMessage, + errorNode: node, + typeName: ts.getNameOfDeclaration(node.parent.parent) + }; + } + function getImportEntityNameVisibilityError() { + return { + diagnosticMessage: ts.Diagnostics.Import_declaration_0_is_using_private_name_1, + errorNode: node, + typeName: node.name + }; + } + function getTypeAliasDeclarationVisibilityError() { + return { + diagnosticMessage: ts.Diagnostics.Exported_type_alias_0_has_or_is_using_private_name_1, + errorNode: node.type, + typeName: node.name + }; + } + } + ts.createGetSymbolAccessibilityDiagnosticForNode = createGetSymbolAccessibilityDiagnosticForNode; +})(ts || (ts = {})); +/*@internal*/ +var ts; +(function (ts) { + function getDeclarationDiagnostics(host, resolver, file) { + if (file && ts.isSourceFileJS(file)) { + return []; // No declaration diagnostics for js for now + } + var compilerOptions = host.getCompilerOptions(); + var result = ts.transformNodes(resolver, host, compilerOptions, file ? [file] : ts.filter(host.getSourceFiles(), ts.isSourceFileNotJS), [transformDeclarations], /*allowDtsFiles*/ false); + return result.diagnostics; + } + ts.getDeclarationDiagnostics = getDeclarationDiagnostics; + var declarationEmitNodeBuilderFlags = 1024 /* MultilineObjectLiterals */ | + 2048 /* WriteClassExpressionAsTypeLiteral */ | + 4096 /* UseTypeOfFunction */ | + 8 /* UseStructuralFallback */ | + 524288 /* AllowEmptyTuple */ | + 4 /* GenerateNamesForShadowedTypeParams */ | + 1 /* NoTruncation */; + /** + * Transforms a ts file into a .d.ts file + * This process requires type information, which is retrieved through the emit resolver. Because of this, + * in many places this transformer assumes it will be operating on parse tree nodes directly. + * This means that _no transforms should be allowed to occur before this one_. + */ + function transformDeclarations(context) { + var throwDiagnostic = function () { return ts.Debug.fail("Diagnostic emitted without context"); }; + var getSymbolAccessibilityDiagnostic = throwDiagnostic; + var needsDeclare = true; + var isBundledEmit = false; + var resultHasExternalModuleIndicator = false; + var needsScopeFixMarker = false; + var resultHasScopeMarker = false; + var enclosingDeclaration; + var necessaryTypeReferences; + var lateMarkedStatements; + var lateStatementReplacementMap; + var suppressNewDiagnosticContexts; + var exportedModulesFromDeclarationEmit; + var host = context.getEmitHost(); + var symbolTracker = { + trackSymbol: trackSymbol, + reportInaccessibleThisError: reportInaccessibleThisError, + reportInaccessibleUniqueSymbolError: reportInaccessibleUniqueSymbolError, + reportPrivateInBaseOfClassExpression: reportPrivateInBaseOfClassExpression, + reportLikelyUnsafeImportRequiredError: reportLikelyUnsafeImportRequiredError, + moduleResolverHost: host, + trackReferencedAmbientModule: trackReferencedAmbientModule, + trackExternalModuleSymbolOfImportTypeNode: trackExternalModuleSymbolOfImportTypeNode + }; + var errorNameNode; + var currentSourceFile; + var refs; + var libs; + var resolver = context.getEmitResolver(); + var options = context.getCompilerOptions(); + var newLine = ts.getNewLineCharacter(options); + var noResolve = options.noResolve, stripInternal = options.stripInternal; + return transformRoot; + function recordTypeReferenceDirectivesIfNecessary(typeReferenceDirectives) { + if (!typeReferenceDirectives) { + return; + } + necessaryTypeReferences = necessaryTypeReferences || ts.createMap(); + for (var _i = 0, typeReferenceDirectives_2 = typeReferenceDirectives; _i < typeReferenceDirectives_2.length; _i++) { + var ref = typeReferenceDirectives_2[_i]; + necessaryTypeReferences.set(ref, true); + } + } + function trackReferencedAmbientModule(node, symbol) { + // If it is visible via `// `, then we should just use that + var directives = resolver.getTypeReferenceDirectivesForSymbol(symbol, 67108863 /* All */); + if (ts.length(directives)) { + return recordTypeReferenceDirectivesIfNecessary(directives); + } + // Otherwise we should emit a path-based reference + var container = ts.getSourceFileOfNode(node); + refs.set("" + ts.getOriginalNodeId(container), container); + } + function handleSymbolAccessibilityError(symbolAccessibilityResult) { + if (symbolAccessibilityResult.accessibility === 0 /* Accessible */) { + // Add aliases back onto the possible imports list if they're not there so we can try them again with updated visibility info + if (symbolAccessibilityResult && symbolAccessibilityResult.aliasesToMakeVisible) { + if (!lateMarkedStatements) { + lateMarkedStatements = symbolAccessibilityResult.aliasesToMakeVisible; + } + else { + for (var _i = 0, _a = symbolAccessibilityResult.aliasesToMakeVisible; _i < _a.length; _i++) { + var ref = _a[_i]; + ts.pushIfUnique(lateMarkedStatements, ref); + } + } + } + // TODO: Do all these accessibility checks inside/after the first pass in the checker when declarations are enabled, if possible + } + else { + // Report error + var errorInfo = getSymbolAccessibilityDiagnostic(symbolAccessibilityResult); + if (errorInfo) { + if (errorInfo.typeName) { + context.addDiagnostic(ts.createDiagnosticForNode(symbolAccessibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, ts.getTextOfNode(errorInfo.typeName), symbolAccessibilityResult.errorSymbolName, symbolAccessibilityResult.errorModuleName)); + } + else { + context.addDiagnostic(ts.createDiagnosticForNode(symbolAccessibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, symbolAccessibilityResult.errorSymbolName, symbolAccessibilityResult.errorModuleName)); + } + } + } + } + function trackExternalModuleSymbolOfImportTypeNode(symbol) { + if (!isBundledEmit) { + (exportedModulesFromDeclarationEmit || (exportedModulesFromDeclarationEmit = [])).push(symbol); + } + } + function trackSymbol(symbol, enclosingDeclaration, meaning) { + if (symbol.flags & 262144 /* TypeParameter */) + return; + handleSymbolAccessibilityError(resolver.isSymbolAccessible(symbol, enclosingDeclaration, meaning, /*shouldComputeAliasesToMakeVisible*/ true)); + recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForSymbol(symbol, meaning)); + } + function reportPrivateInBaseOfClassExpression(propertyName) { + if (errorNameNode) { + context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.Property_0_of_exported_class_expression_may_not_be_private_or_protected, propertyName)); + } + } + function reportInaccessibleUniqueSymbolError() { + if (errorNameNode) { + context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary, ts.declarationNameToString(errorNameNode), "unique symbol")); + } + } + function reportInaccessibleThisError() { + if (errorNameNode) { + context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary, ts.declarationNameToString(errorNameNode), "this")); + } + } + function reportLikelyUnsafeImportRequiredError(specifier) { + if (errorNameNode) { + context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_annotation_is_necessary, ts.declarationNameToString(errorNameNode), specifier)); + } + } + function transformRoot(node) { + if (node.kind === 279 /* SourceFile */ && (node.isDeclarationFile || ts.isSourceFileJS(node))) { + return node; + } + if (node.kind === 280 /* Bundle */) { + isBundledEmit = true; + refs = ts.createMap(); + libs = ts.createMap(); + var hasNoDefaultLib_1 = false; + var bundle = ts.createBundle(ts.map(node.sourceFiles, function (sourceFile) { + if (sourceFile.isDeclarationFile || ts.isSourceFileJS(sourceFile)) + return undefined; // Omit declaration files from bundle results, too // TODO: GH#18217 + hasNoDefaultLib_1 = hasNoDefaultLib_1 || sourceFile.hasNoDefaultLib; + currentSourceFile = sourceFile; + enclosingDeclaration = sourceFile; + lateMarkedStatements = undefined; + suppressNewDiagnosticContexts = false; + lateStatementReplacementMap = ts.createMap(); + getSymbolAccessibilityDiagnostic = throwDiagnostic; + needsScopeFixMarker = false; + resultHasScopeMarker = false; + collectReferences(sourceFile, refs); + collectLibs(sourceFile, libs); + if (ts.isExternalModule(sourceFile)) { + resultHasExternalModuleIndicator = false; // unused in external module bundle emit (all external modules are within module blocks, therefore are known to be modules) + needsDeclare = false; + var statements_4 = ts.visitNodes(sourceFile.statements, visitDeclarationStatements); + var newFile = ts.updateSourceFileNode(sourceFile, [ts.createModuleDeclaration([], [ts.createModifier(125 /* DeclareKeyword */)], ts.createLiteral(ts.getResolvedExternalModuleName(context.getEmitHost(), sourceFile)), ts.createModuleBlock(ts.setTextRange(ts.createNodeArray(transformAndReplaceLatePaintedStatements(statements_4)), sourceFile.statements)))], /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false, /*libReferences*/ []); + return newFile; + } + needsDeclare = true; + var updated = ts.visitNodes(sourceFile.statements, visitDeclarationStatements); + return ts.updateSourceFileNode(sourceFile, transformAndReplaceLatePaintedStatements(updated), /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false, /*libReferences*/ []); + }), ts.mapDefined(node.prepends, function (prepend) { + if (prepend.kind === 282 /* InputFiles */) { + return ts.createUnparsedSourceFile(prepend.declarationText, prepend.declarationMapPath, prepend.declarationMapText); + } + })); + bundle.syntheticFileReferences = []; + bundle.syntheticTypeReferences = getFileReferencesForUsedTypeReferences(); + bundle.syntheticLibReferences = getLibReferences(); + bundle.hasNoDefaultLib = hasNoDefaultLib_1; + var outputFilePath_1 = ts.getDirectoryPath(ts.normalizeSlashes(ts.getOutputPathsFor(node, host, /*forceDtsPaths*/ true).declarationFilePath)); + var referenceVisitor_1 = mapReferencesIntoArray(bundle.syntheticFileReferences, outputFilePath_1); + refs.forEach(referenceVisitor_1); + return bundle; + } + // Single source file + needsDeclare = true; + needsScopeFixMarker = false; + resultHasScopeMarker = false; + enclosingDeclaration = node; + currentSourceFile = node; + getSymbolAccessibilityDiagnostic = throwDiagnostic; + isBundledEmit = false; + resultHasExternalModuleIndicator = false; + suppressNewDiagnosticContexts = false; + lateMarkedStatements = undefined; + lateStatementReplacementMap = ts.createMap(); + necessaryTypeReferences = undefined; + refs = collectReferences(currentSourceFile, ts.createMap()); + libs = collectLibs(currentSourceFile, ts.createMap()); + var references = []; + var outputFilePath = ts.getDirectoryPath(ts.normalizeSlashes(ts.getOutputPathsFor(node, host, /*forceDtsPaths*/ true).declarationFilePath)); + var referenceVisitor = mapReferencesIntoArray(references, outputFilePath); + var statements = ts.visitNodes(node.statements, visitDeclarationStatements); + var combinedStatements = ts.setTextRange(ts.createNodeArray(transformAndReplaceLatePaintedStatements(statements)), node.statements); + refs.forEach(referenceVisitor); + var emittedImports = ts.filter(combinedStatements, ts.isAnyImportSyntax); + if (ts.isExternalModule(node) && (!resultHasExternalModuleIndicator || (needsScopeFixMarker && !resultHasScopeMarker))) { + combinedStatements = ts.setTextRange(ts.createNodeArray(combinedStatements.concat([ts.createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createNamedExports([]), /*moduleSpecifier*/ undefined)])), combinedStatements); + } + var updated = ts.updateSourceFileNode(node, combinedStatements, /*isDeclarationFile*/ true, references, getFileReferencesForUsedTypeReferences(), node.hasNoDefaultLib, getLibReferences()); + updated.exportedModulesFromDeclarationEmit = exportedModulesFromDeclarationEmit; + return updated; + function getLibReferences() { + return ts.map(ts.arrayFrom(libs.keys()), function (lib) { return ({ fileName: lib, pos: -1, end: -1 }); }); + } + function getFileReferencesForUsedTypeReferences() { + return necessaryTypeReferences ? ts.mapDefined(ts.arrayFrom(necessaryTypeReferences.keys()), getFileReferenceForTypeName) : []; + } + function getFileReferenceForTypeName(typeName) { + // Elide type references for which we have imports + if (emittedImports) { + for (var _i = 0, emittedImports_1 = emittedImports; _i < emittedImports_1.length; _i++) { + var importStatement = emittedImports_1[_i]; + if (ts.isImportEqualsDeclaration(importStatement) && ts.isExternalModuleReference(importStatement.moduleReference)) { + var expr = importStatement.moduleReference.expression; + if (ts.isStringLiteralLike(expr) && expr.text === typeName) { + return undefined; + } + } + else if (ts.isImportDeclaration(importStatement) && ts.isStringLiteral(importStatement.moduleSpecifier) && importStatement.moduleSpecifier.text === typeName) { + return undefined; + } + } + } + return { fileName: typeName, pos: -1, end: -1 }; + } + function mapReferencesIntoArray(references, outputFilePath) { + return function (file) { + var declFileName; + if (file.isDeclarationFile) { // Neither decl files or js should have their refs changed + declFileName = file.fileName; + } + else { + if (isBundledEmit && ts.contains(node.sourceFiles, file)) + return; // Omit references to files which are being merged + var paths = ts.getOutputPathsFor(file, host, /*forceDtsPaths*/ true); + declFileName = paths.declarationFilePath || paths.jsFilePath || file.fileName; + } + if (declFileName) { + var fileName = ts.getRelativePathToDirectoryOrUrl(outputFilePath, declFileName, host.getCurrentDirectory(), host.getCanonicalFileName, + /*isAbsolutePathAnUrl*/ false); + if (ts.startsWith(fileName, "./") && ts.hasExtension(fileName)) { + fileName = fileName.substring(2); + } + // omit references to files from node_modules (npm may disambiguate module + // references when installing this package, making the path is unreliable). + if (ts.startsWith(fileName, "node_modules/") || fileName.indexOf("/node_modules/") !== -1) { + return; + } + references.push({ pos: -1, end: -1, fileName: fileName }); + } + }; + } + } + function collectReferences(sourceFile, ret) { + if (noResolve || ts.isSourceFileJS(sourceFile)) + return ret; + ts.forEach(sourceFile.referencedFiles, function (f) { + var elem = ts.tryResolveScriptReference(host, sourceFile, f); + if (elem) { + ret.set("" + ts.getOriginalNodeId(elem), elem); + } + }); + return ret; + } + function collectLibs(sourceFile, ret) { + ts.forEach(sourceFile.libReferenceDirectives, function (ref) { + var lib = host.getLibFileFromReference(ref); + if (lib) { + ret.set(ref.fileName.toLocaleLowerCase(), true); + } + }); + return ret; + } + function filterBindingPatternInitializers(name) { + if (name.kind === 72 /* Identifier */) { + return name; + } + else { + if (name.kind === 185 /* ArrayBindingPattern */) { + return ts.updateArrayBindingPattern(name, ts.visitNodes(name.elements, visitBindingElement)); + } + else { + return ts.updateObjectBindingPattern(name, ts.visitNodes(name.elements, visitBindingElement)); + } + } + function visitBindingElement(elem) { + if (elem.kind === 210 /* OmittedExpression */) { + return elem; + } + return ts.updateBindingElement(elem, elem.dotDotDotToken, elem.propertyName, filterBindingPatternInitializers(elem.name), shouldPrintWithInitializer(elem) ? elem.initializer : undefined); + } + } + function ensureParameter(p, modifierMask) { + var oldDiag; + if (!suppressNewDiagnosticContexts) { + oldDiag = getSymbolAccessibilityDiagnostic; + getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(p); + } + var newParam = ts.updateParameter(p, + /*decorators*/ undefined, maskModifiers(p, modifierMask), p.dotDotDotToken, filterBindingPatternInitializers(p.name), resolver.isOptionalParameter(p) ? (p.questionToken || ts.createToken(56 /* QuestionToken */)) : undefined, ensureType(p, p.type, /*ignorePrivate*/ true), // Ignore private param props, since this type is going straight back into a param + ensureNoInitializer(p)); + if (!suppressNewDiagnosticContexts) { + getSymbolAccessibilityDiagnostic = oldDiag; + } + return newParam; + } + function shouldPrintWithInitializer(node) { + return canHaveLiteralInitializer(node) && resolver.isLiteralConstDeclaration(ts.getParseTreeNode(node)); // TODO: Make safe + } + function ensureNoInitializer(node) { + if (shouldPrintWithInitializer(node)) { + return resolver.createLiteralConstValue(ts.getParseTreeNode(node), symbolTracker); // TODO: Make safe + } + return undefined; + } + function ensureType(node, type, ignorePrivate) { + if (!ignorePrivate && ts.hasModifier(node, 8 /* Private */)) { + // Private nodes emit no types (except private parameter properties, whose parameter types are actually visible) + return; + } + if (shouldPrintWithInitializer(node)) { + // Literal const declarations will have an initializer ensured rather than a type + return; + } + var shouldUseResolverType = node.kind === 151 /* Parameter */ && + (resolver.isRequiredInitializedParameter(node) || + resolver.isOptionalUninitializedParameterProperty(node)); + if (type && !shouldUseResolverType) { + return ts.visitNode(type, visitDeclarationSubtree); + } + if (!ts.getParseTreeNode(node)) { + return type ? ts.visitNode(type, visitDeclarationSubtree) : ts.createKeywordTypeNode(120 /* AnyKeyword */); + } + if (node.kind === 159 /* SetAccessor */) { + // Set accessors with no associated type node (from it's param or get accessor return) are `any` since they are never contextually typed right now + // (The inferred type here will be void, but the old declaration emitter printed `any`, so this replicates that) + return ts.createKeywordTypeNode(120 /* AnyKeyword */); + } + errorNameNode = node.name; + var oldDiag; + if (!suppressNewDiagnosticContexts) { + oldDiag = getSymbolAccessibilityDiagnostic; + getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(node); + } + if (node.kind === 237 /* VariableDeclaration */ || node.kind === 186 /* BindingElement */) { + return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker)); + } + if (node.kind === 151 /* Parameter */ + || node.kind === 154 /* PropertyDeclaration */ + || node.kind === 153 /* PropertySignature */) { + if (!node.initializer) + return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker, shouldUseResolverType)); + return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker, shouldUseResolverType) || resolver.createTypeOfExpression(node.initializer, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker)); + } + return cleanup(resolver.createReturnTypeOfSignatureDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker)); + function cleanup(returnValue) { + errorNameNode = undefined; + if (!suppressNewDiagnosticContexts) { + getSymbolAccessibilityDiagnostic = oldDiag; + } + return returnValue || ts.createKeywordTypeNode(120 /* AnyKeyword */); + } + } + function isDeclarationAndNotVisible(node) { + node = ts.getParseTreeNode(node); + switch (node.kind) { + case 239 /* FunctionDeclaration */: + case 244 /* ModuleDeclaration */: + case 241 /* InterfaceDeclaration */: + case 240 /* ClassDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 243 /* EnumDeclaration */: + return !resolver.isDeclarationVisible(node); + // The following should be doing their own visibility checks based on filtering their members + case 237 /* VariableDeclaration */: + return !getBindingNameVisible(node); + case 248 /* ImportEqualsDeclaration */: + case 249 /* ImportDeclaration */: + case 255 /* ExportDeclaration */: + case 254 /* ExportAssignment */: + return false; + } + return false; + } + function getBindingNameVisible(elem) { + if (ts.isOmittedExpression(elem)) { + return false; + } + if (ts.isBindingPattern(elem.name)) { + // If any child binding pattern element has been marked visible (usually by collect linked aliases), then this is visible + return ts.some(elem.name.elements, getBindingNameVisible); + } + else { + return resolver.isDeclarationVisible(elem); + } + } + function updateParamsList(node, params, modifierMask) { + if (ts.hasModifier(node, 8 /* Private */)) { + return undefined; // TODO: GH#18217 + } + var newParams = ts.map(params, function (p) { return ensureParameter(p, modifierMask); }); + if (!newParams) { + return undefined; // TODO: GH#18217 + } + return ts.createNodeArray(newParams, params.hasTrailingComma); + } + function ensureTypeParams(node, params) { + return ts.hasModifier(node, 8 /* Private */) ? undefined : ts.visitNodes(params, visitDeclarationSubtree); + } + function isEnclosingDeclaration(node) { + return ts.isSourceFile(node) + || ts.isTypeAliasDeclaration(node) + || ts.isModuleDeclaration(node) + || ts.isClassDeclaration(node) + || ts.isInterfaceDeclaration(node) + || ts.isFunctionLike(node) + || ts.isIndexSignatureDeclaration(node) + || ts.isMappedTypeNode(node); + } + function checkEntityNameVisibility(entityName, enclosingDeclaration) { + var visibilityResult = resolver.isEntityNameVisible(entityName, enclosingDeclaration); + handleSymbolAccessibilityError(visibilityResult); + recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForEntityName(entityName)); + } + function preserveJsDoc(updated, original) { + if (ts.hasJSDocNodes(updated) && ts.hasJSDocNodes(original)) { + updated.jsDoc = original.jsDoc; + } + return ts.setCommentRange(updated, ts.getCommentRange(original)); + } + function rewriteModuleSpecifier(parent, input) { + if (!input) + return undefined; // TODO: GH#18217 + resultHasExternalModuleIndicator = resultHasExternalModuleIndicator || (parent.kind !== 244 /* ModuleDeclaration */ && parent.kind !== 183 /* ImportType */); + if (ts.isStringLiteralLike(input)) { + if (isBundledEmit) { + var newName = ts.getExternalModuleNameFromDeclaration(context.getEmitHost(), resolver, parent); + if (newName) { + return ts.createLiteral(newName); + } + } + else { + var symbol = resolver.getSymbolOfExternalModuleSpecifier(input); + if (symbol) { + (exportedModulesFromDeclarationEmit || (exportedModulesFromDeclarationEmit = [])).push(symbol); + } + } + } + return input; + } + function transformImportEqualsDeclaration(decl) { + if (!resolver.isDeclarationVisible(decl)) + return; + if (decl.moduleReference.kind === 259 /* ExternalModuleReference */) { + // Rewrite external module names if necessary + var specifier = ts.getExternalModuleImportEqualsDeclarationExpression(decl); + return ts.updateImportEqualsDeclaration(decl, + /*decorators*/ undefined, decl.modifiers, decl.name, ts.updateExternalModuleReference(decl.moduleReference, rewriteModuleSpecifier(decl, specifier))); + } + else { + var oldDiag = getSymbolAccessibilityDiagnostic; + getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(decl); + checkEntityNameVisibility(decl.moduleReference, enclosingDeclaration); + getSymbolAccessibilityDiagnostic = oldDiag; + return decl; + } + } + function transformImportDeclaration(decl) { + if (!decl.importClause) { + // import "mod" - possibly needed for side effects? (global interface patches, module augmentations, etc) + return ts.updateImportDeclaration(decl, + /*decorators*/ undefined, decl.modifiers, decl.importClause, rewriteModuleSpecifier(decl, decl.moduleSpecifier)); + } + // The `importClause` visibility corresponds to the default's visibility. + var visibleDefaultBinding = decl.importClause && decl.importClause.name && resolver.isDeclarationVisible(decl.importClause) ? decl.importClause.name : undefined; + if (!decl.importClause.namedBindings) { + // No named bindings (either namespace or list), meaning the import is just default or should be elided + return visibleDefaultBinding && ts.updateImportDeclaration(decl, /*decorators*/ undefined, decl.modifiers, ts.updateImportClause(decl.importClause, visibleDefaultBinding, + /*namedBindings*/ undefined), rewriteModuleSpecifier(decl, decl.moduleSpecifier)); + } + if (decl.importClause.namedBindings.kind === 251 /* NamespaceImport */) { + // Namespace import (optionally with visible default) + var namedBindings = resolver.isDeclarationVisible(decl.importClause.namedBindings) ? decl.importClause.namedBindings : /*namedBindings*/ undefined; + return visibleDefaultBinding || namedBindings ? ts.updateImportDeclaration(decl, /*decorators*/ undefined, decl.modifiers, ts.updateImportClause(decl.importClause, visibleDefaultBinding, namedBindings), rewriteModuleSpecifier(decl, decl.moduleSpecifier)) : undefined; + } + // Named imports (optionally with visible default) + var bindingList = ts.mapDefined(decl.importClause.namedBindings.elements, function (b) { return resolver.isDeclarationVisible(b) ? b : undefined; }); + if ((bindingList && bindingList.length) || visibleDefaultBinding) { + return ts.updateImportDeclaration(decl, + /*decorators*/ undefined, decl.modifiers, ts.updateImportClause(decl.importClause, visibleDefaultBinding, bindingList && bindingList.length ? ts.updateNamedImports(decl.importClause.namedBindings, bindingList) : undefined), rewriteModuleSpecifier(decl, decl.moduleSpecifier)); + } + // Nothing visible + } + function transformAndReplaceLatePaintedStatements(statements) { + // This is a `while` loop because `handleSymbolAccessibilityError` can see additional import aliases marked as visible during + // error handling which must now be included in the output and themselves checked for errors. + // For example: + // ``` + // module A { + // export module Q {} + // import B = Q; + // import C = B; + // export import D = C; + // } + // ``` + // In such a scenario, only Q and D are initially visible, but we don't consider imports as private names - instead we say they if they are referenced they must + // be recorded. So while checking D's visibility we mark C as visible, then we must check C which in turn marks B, completing the chain of + // dependent imports and allowing a valid declaration file output. Today, this dependent alias marking only happens for internal import aliases. + while (ts.length(lateMarkedStatements)) { + var i = lateMarkedStatements.shift(); + if (!ts.isLateVisibilityPaintedStatement(i)) { + return ts.Debug.fail("Late replaced statement was found which is not handled by the declaration transformer!: " + (ts.SyntaxKind ? ts.SyntaxKind[i.kind] : i.kind)); + } + var result = transformTopLevelDeclaration(i, /*privateDeclaration*/ true); + lateStatementReplacementMap.set("" + ts.getOriginalNodeId(i), result); + } + // And lastly, we need to get the final form of all those indetermine import declarations from before and add them to the output list + // (and remove them from the set to examine for outter declarations) + return ts.visitNodes(statements, visitLateVisibilityMarkedStatements); + function visitLateVisibilityMarkedStatements(statement) { + if (ts.isLateVisibilityPaintedStatement(statement)) { + var key = "" + ts.getOriginalNodeId(statement); + if (lateStatementReplacementMap.has(key)) { + var result = lateStatementReplacementMap.get(key); + lateStatementReplacementMap.delete(key); + if (result && ts.isSourceFile(statement.parent)) { + if (ts.isArray(result) ? ts.some(result, needsScopeMarker) : needsScopeMarker(result)) { + // Top-level declarations in .d.ts files are always considered exported even without a modifier unless there's an export assignment or specifier + needsScopeFixMarker = true; + } + if (ts.isArray(result) ? ts.some(result, isExternalModuleIndicator) : isExternalModuleIndicator(result)) { + resultHasExternalModuleIndicator = true; + } + } + return result; + } + } + return statement; + } + } + function isExternalModuleIndicator(result) { + // Exported top-level member indicates moduleness + return ts.isAnyImportOrReExport(result) || ts.isExportAssignment(result) || ts.hasModifier(result, 1 /* Export */); + } + function needsScopeMarker(result) { + return !ts.isAnyImportOrReExport(result) && !ts.isExportAssignment(result) && !ts.hasModifier(result, 1 /* Export */) && !ts.isAmbientModule(result); + } + function visitDeclarationSubtree(input) { + if (shouldStripInternal(input)) + return; + if (ts.isDeclaration(input)) { + if (isDeclarationAndNotVisible(input)) + return; + if (ts.hasDynamicName(input) && !resolver.isLateBound(ts.getParseTreeNode(input))) { + return; + } + } + // Elide implementation signatures from overload sets + if (ts.isFunctionLike(input) && resolver.isImplementationOfOverload(input)) + return; + // Elide semicolon class statements + if (ts.isSemicolonClassElement(input)) + return; + var previousEnclosingDeclaration; + if (isEnclosingDeclaration(input)) { + previousEnclosingDeclaration = enclosingDeclaration; + enclosingDeclaration = input; + } + var oldDiag = getSymbolAccessibilityDiagnostic; + // Emit methods which are private as properties with no type information + if (ts.isMethodDeclaration(input) || ts.isMethodSignature(input)) { + if (ts.hasModifier(input, 8 /* Private */)) { + if (input.symbol && input.symbol.declarations && input.symbol.declarations[0] !== input) + return; // Elide all but the first overload + return cleanup(ts.createProperty(/*decorators*/ undefined, ensureModifiers(input), input.name, /*questionToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined)); + } + } + var canProdiceDiagnostic = ts.canProduceDiagnostics(input); + if (canProdiceDiagnostic && !suppressNewDiagnosticContexts) { + getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(input); + } + if (ts.isTypeQueryNode(input)) { + checkEntityNameVisibility(input.exprName, enclosingDeclaration); + } + var oldWithinObjectLiteralType = suppressNewDiagnosticContexts; + var shouldEnterSuppressNewDiagnosticsContextContext = ((input.kind === 168 /* TypeLiteral */ || input.kind === 181 /* MappedType */) && input.parent.kind !== 242 /* TypeAliasDeclaration */); + if (shouldEnterSuppressNewDiagnosticsContextContext) { + // We stop making new diagnostic contexts within object literal types. Unless it's an object type on the RHS of a type alias declaration. Then we do. + suppressNewDiagnosticContexts = true; + } + if (isProcessedComponent(input)) { + switch (input.kind) { + case 211 /* ExpressionWithTypeArguments */: { + if ((ts.isEntityName(input.expression) || ts.isEntityNameExpression(input.expression))) { + checkEntityNameVisibility(input.expression, enclosingDeclaration); + } + var node = ts.visitEachChild(input, visitDeclarationSubtree, context); + return cleanup(ts.updateExpressionWithTypeArguments(node, ts.parenthesizeTypeParameters(node.typeArguments), node.expression)); + } + case 164 /* TypeReference */: { + checkEntityNameVisibility(input.typeName, enclosingDeclaration); + var node = ts.visitEachChild(input, visitDeclarationSubtree, context); + return cleanup(ts.updateTypeReferenceNode(node, node.typeName, ts.parenthesizeTypeParameters(node.typeArguments))); + } + case 161 /* ConstructSignature */: + return cleanup(ts.updateConstructSignature(input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type))); + case 157 /* Constructor */: { + var isPrivate = ts.hasModifier(input, 8 /* Private */); + // A constructor declaration may not have a type annotation + var ctor = ts.createSignatureDeclaration(157 /* Constructor */, isPrivate ? undefined : ensureTypeParams(input, input.typeParameters), + // TODO: GH#18217 + isPrivate ? undefined : updateParamsList(input, input.parameters, 0 /* None */), + /*type*/ undefined); + ctor.modifiers = ts.createNodeArray(ensureModifiers(input)); + return cleanup(ctor); + } + case 156 /* MethodDeclaration */: { + var sig = ts.createSignatureDeclaration(155 /* MethodSignature */, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type)); + sig.name = input.name; + sig.modifiers = ts.createNodeArray(ensureModifiers(input)); + sig.questionToken = input.questionToken; + return cleanup(sig); + } + case 158 /* GetAccessor */: { + var newNode = ensureAccessor(input); + return cleanup(newNode); + } + case 159 /* SetAccessor */: { + var newNode = ensureAccessor(input); + return cleanup(newNode); + } + case 154 /* PropertyDeclaration */: + return cleanup(ts.updateProperty(input, + /*decorators*/ undefined, ensureModifiers(input), input.name, input.questionToken, !ts.hasModifier(input, 8 /* Private */) ? ensureType(input, input.type) : undefined, ensureNoInitializer(input))); + case 153 /* PropertySignature */: + return cleanup(ts.updatePropertySignature(input, ensureModifiers(input), input.name, input.questionToken, !ts.hasModifier(input, 8 /* Private */) ? ensureType(input, input.type) : undefined, ensureNoInitializer(input))); + case 155 /* MethodSignature */: { + return cleanup(ts.updateMethodSignature(input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type), input.name, input.questionToken)); + } + case 160 /* CallSignature */: { + return cleanup(ts.updateCallSignature(input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type))); + } + case 162 /* IndexSignature */: { + return cleanup(ts.updateIndexSignature(input, + /*decorators*/ undefined, ensureModifiers(input), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree) || ts.createKeywordTypeNode(120 /* AnyKeyword */))); + } + case 237 /* VariableDeclaration */: { + if (ts.isBindingPattern(input.name)) { + return recreateBindingPattern(input.name); + } + shouldEnterSuppressNewDiagnosticsContextContext = true; + suppressNewDiagnosticContexts = true; // Variable declaration types also suppress new diagnostic contexts, provided the contexts wouldn't be made for binding pattern types + return cleanup(ts.updateVariableDeclaration(input, input.name, ensureType(input, input.type), ensureNoInitializer(input))); + } + case 150 /* TypeParameter */: { + if (isPrivateMethodTypeParameter(input) && (input.default || input.constraint)) { + return cleanup(ts.updateTypeParameterDeclaration(input, input.name, /*constraint*/ undefined, /*defaultType*/ undefined)); + } + return cleanup(ts.visitEachChild(input, visitDeclarationSubtree, context)); + } + case 175 /* ConditionalType */: { + // We have to process conditional types in a special way because for visibility purposes we need to push a new enclosingDeclaration + // just for the `infer` types in the true branch. It's an implicit declaration scope that only applies to _part_ of the type. + var checkType = ts.visitNode(input.checkType, visitDeclarationSubtree); + var extendsType = ts.visitNode(input.extendsType, visitDeclarationSubtree); + var oldEnclosingDecl = enclosingDeclaration; + enclosingDeclaration = input.trueType; + var trueType = ts.visitNode(input.trueType, visitDeclarationSubtree); + enclosingDeclaration = oldEnclosingDecl; + var falseType = ts.visitNode(input.falseType, visitDeclarationSubtree); + return cleanup(ts.updateConditionalTypeNode(input, checkType, extendsType, trueType, falseType)); + } + case 165 /* FunctionType */: { + return cleanup(ts.updateFunctionTypeNode(input, ts.visitNodes(input.typeParameters, visitDeclarationSubtree), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree))); + } + case 166 /* ConstructorType */: { + return cleanup(ts.updateConstructorTypeNode(input, ts.visitNodes(input.typeParameters, visitDeclarationSubtree), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree))); + } + case 183 /* ImportType */: { + if (!ts.isLiteralImportTypeNode(input)) + return cleanup(input); + return cleanup(ts.updateImportTypeNode(input, ts.updateLiteralTypeNode(input.argument, rewriteModuleSpecifier(input, input.argument.literal)), input.qualifier, ts.visitNodes(input.typeArguments, visitDeclarationSubtree, ts.isTypeNode), input.isTypeOf)); + } + default: ts.Debug.assertNever(input, "Attempted to process unhandled node kind: " + ts.SyntaxKind[input.kind]); + } + } + return cleanup(ts.visitEachChild(input, visitDeclarationSubtree, context)); + function cleanup(returnValue) { + if (returnValue && canProdiceDiagnostic && ts.hasDynamicName(input)) { + checkName(input); + } + if (isEnclosingDeclaration(input)) { + enclosingDeclaration = previousEnclosingDeclaration; + } + if (canProdiceDiagnostic && !suppressNewDiagnosticContexts) { + getSymbolAccessibilityDiagnostic = oldDiag; + } + if (shouldEnterSuppressNewDiagnosticsContextContext) { + suppressNewDiagnosticContexts = oldWithinObjectLiteralType; + } + if (returnValue === input) { + return returnValue; + } + return returnValue && ts.setOriginalNode(preserveJsDoc(returnValue, input), input); + } + } + function isPrivateMethodTypeParameter(node) { + return node.parent.kind === 156 /* MethodDeclaration */ && ts.hasModifier(node.parent, 8 /* Private */); + } + function visitDeclarationStatements(input) { + if (!isPreservedDeclarationStatement(input)) { + // return undefined for unmatched kinds to omit them from the tree + return; + } + if (shouldStripInternal(input)) + return; + switch (input.kind) { + case 255 /* ExportDeclaration */: { + if (ts.isSourceFile(input.parent)) { + resultHasExternalModuleIndicator = true; + resultHasScopeMarker = true; + } + // Always visible if the parent node isn't dropped for being not visible + // Rewrite external module names if necessary + return ts.updateExportDeclaration(input, /*decorators*/ undefined, input.modifiers, input.exportClause, rewriteModuleSpecifier(input, input.moduleSpecifier)); + } + case 254 /* ExportAssignment */: { + // Always visible if the parent node isn't dropped for being not visible + if (ts.isSourceFile(input.parent)) { + resultHasExternalModuleIndicator = true; + resultHasScopeMarker = true; + } + if (input.expression.kind === 72 /* Identifier */) { + return input; + } + else { + var newId = ts.createOptimisticUniqueName("_default"); + getSymbolAccessibilityDiagnostic = function () { return ({ + diagnosticMessage: ts.Diagnostics.Default_export_of_the_module_has_or_is_using_private_name_0, + errorNode: input + }); }; + var varDecl = ts.createVariableDeclaration(newId, resolver.createTypeOfExpression(input.expression, input, declarationEmitNodeBuilderFlags, symbolTracker), /*initializer*/ undefined); + var statement = ts.createVariableStatement(needsDeclare ? [ts.createModifier(125 /* DeclareKeyword */)] : [], ts.createVariableDeclarationList([varDecl], 2 /* Const */)); + return [statement, ts.updateExportAssignment(input, input.decorators, input.modifiers, newId)]; + } + } + } + var result = transformTopLevelDeclaration(input); + // Don't actually transform yet; just leave as original node - will be elided/swapped by late pass + lateStatementReplacementMap.set("" + ts.getOriginalNodeId(input), result); + return input; + } + function transformTopLevelDeclaration(input, isPrivate) { + if (shouldStripInternal(input)) + return; + switch (input.kind) { + case 248 /* ImportEqualsDeclaration */: { + return transformImportEqualsDeclaration(input); + } + case 249 /* ImportDeclaration */: { + return transformImportDeclaration(input); + } + } + if (ts.isDeclaration(input) && isDeclarationAndNotVisible(input)) + return; + // Elide implementation signatures from overload sets + if (ts.isFunctionLike(input) && resolver.isImplementationOfOverload(input)) + return; + var previousEnclosingDeclaration; + if (isEnclosingDeclaration(input)) { + previousEnclosingDeclaration = enclosingDeclaration; + enclosingDeclaration = input; + } + var canProdiceDiagnostic = ts.canProduceDiagnostics(input); + var oldDiag = getSymbolAccessibilityDiagnostic; + if (canProdiceDiagnostic) { + getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(input); + } + var previousNeedsDeclare = needsDeclare; + switch (input.kind) { + case 242 /* TypeAliasDeclaration */: // Type aliases get `declare`d if need be (for legacy support), but that's all + return cleanup(ts.updateTypeAliasDeclaration(input, + /*decorators*/ undefined, ensureModifiers(input, isPrivate), input.name, ts.visitNodes(input.typeParameters, visitDeclarationSubtree, ts.isTypeParameterDeclaration), ts.visitNode(input.type, visitDeclarationSubtree, ts.isTypeNode))); + case 241 /* InterfaceDeclaration */: { + return cleanup(ts.updateInterfaceDeclaration(input, + /*decorators*/ undefined, ensureModifiers(input, isPrivate), input.name, ensureTypeParams(input, input.typeParameters), transformHeritageClauses(input.heritageClauses), ts.visitNodes(input.members, visitDeclarationSubtree))); + } + case 239 /* FunctionDeclaration */: { + // Generators lose their generator-ness, excepting their return type + var clean = cleanup(ts.updateFunctionDeclaration(input, + /*decorators*/ undefined, ensureModifiers(input, isPrivate), + /*asteriskToken*/ undefined, input.name, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type), + /*body*/ undefined)); + if (clean && resolver.isExpandoFunctionDeclaration(input)) { + var declarations = ts.mapDefined(resolver.getPropertiesOfContainerFunction(input), function (p) { + if (!ts.isPropertyAccessExpression(p.valueDeclaration)) { + return undefined; + } + var type = resolver.createTypeOfDeclaration(p.valueDeclaration, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker); + var varDecl = ts.createVariableDeclaration(ts.unescapeLeadingUnderscores(p.escapedName), type, /*initializer*/ undefined); + return ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([varDecl])); + }); + var namespaceDecl = ts.createModuleDeclaration(/*decorators*/ undefined, ensureModifiers(input, isPrivate), input.name, ts.createModuleBlock(declarations), 16 /* Namespace */); + return [clean, namespaceDecl]; + } + else { + return clean; + } + } + case 244 /* ModuleDeclaration */: { + needsDeclare = false; + var inner = input.body; + if (inner && inner.kind === 245 /* ModuleBlock */) { + var statements = ts.visitNodes(inner.statements, visitDeclarationStatements); + var body = ts.updateModuleBlock(inner, transformAndReplaceLatePaintedStatements(statements)); + needsDeclare = previousNeedsDeclare; + var mods = ensureModifiers(input, isPrivate); + return cleanup(ts.updateModuleDeclaration(input, + /*decorators*/ undefined, mods, ts.isExternalModuleAugmentation(input) ? rewriteModuleSpecifier(input, input.name) : input.name, body)); + } + else { + needsDeclare = previousNeedsDeclare; + var mods = ensureModifiers(input, isPrivate); + needsDeclare = false; + ts.visitNode(inner, visitDeclarationStatements); + // eagerly transform nested namespaces (the nesting doesn't need any elision or painting done) + var id = "" + ts.getOriginalNodeId(inner); // TODO: GH#18217 + var body = lateStatementReplacementMap.get(id); + lateStatementReplacementMap.delete(id); + return cleanup(ts.updateModuleDeclaration(input, + /*decorators*/ undefined, mods, input.name, body)); + } + } + case 240 /* ClassDeclaration */: { + var modifiers = ts.createNodeArray(ensureModifiers(input, isPrivate)); + var typeParameters = ensureTypeParams(input, input.typeParameters); + var ctor = ts.getFirstConstructorWithBody(input); + var parameterProperties = void 0; + if (ctor) { + var oldDiag_1 = getSymbolAccessibilityDiagnostic; + parameterProperties = ts.compact(ts.flatMap(ctor.parameters, function (param) { + if (!ts.hasModifier(param, 92 /* ParameterPropertyModifier */)) + return; + getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(param); + if (param.name.kind === 72 /* Identifier */) { + return preserveJsDoc(ts.createProperty( + /*decorators*/ undefined, ensureModifiers(param), param.name, param.questionToken, ensureType(param, param.type), ensureNoInitializer(param)), param); + } + else { + // Pattern - this is currently an error, but we emit declarations for it somewhat correctly + return walkBindingPattern(param.name); + } + function walkBindingPattern(pattern) { + var elems; + for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) { + var elem = _a[_i]; + if (ts.isOmittedExpression(elem)) + continue; + if (ts.isBindingPattern(elem.name)) { + elems = ts.concatenate(elems, walkBindingPattern(elem.name)); + } + elems = elems || []; + elems.push(ts.createProperty( + /*decorators*/ undefined, ensureModifiers(param), elem.name, + /*questionToken*/ undefined, ensureType(elem, /*type*/ undefined), + /*initializer*/ undefined)); + } + return elems; + } + })); + getSymbolAccessibilityDiagnostic = oldDiag_1; + } + var members = ts.createNodeArray(ts.concatenate(parameterProperties, ts.visitNodes(input.members, visitDeclarationSubtree))); + var extendsClause_1 = ts.getEffectiveBaseTypeNode(input); + if (extendsClause_1 && !ts.isEntityNameExpression(extendsClause_1.expression) && extendsClause_1.expression.kind !== 96 /* NullKeyword */) { + // We must add a temporary declaration for the extends clause expression + var newId_1 = ts.createOptimisticUniqueName(ts.unescapeLeadingUnderscores(input.name.escapedText) + "_base"); // TODO: GH#18217 + getSymbolAccessibilityDiagnostic = function () { return ({ + diagnosticMessage: ts.Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1, + errorNode: extendsClause_1, + typeName: input.name + }); }; + var varDecl = ts.createVariableDeclaration(newId_1, resolver.createTypeOfExpression(extendsClause_1.expression, input, declarationEmitNodeBuilderFlags, symbolTracker), /*initializer*/ undefined); + var statement = ts.createVariableStatement(needsDeclare ? [ts.createModifier(125 /* DeclareKeyword */)] : [], ts.createVariableDeclarationList([varDecl], 2 /* Const */)); + var heritageClauses = ts.createNodeArray(ts.map(input.heritageClauses, function (clause) { + if (clause.token === 86 /* ExtendsKeyword */) { + var oldDiag_2 = getSymbolAccessibilityDiagnostic; + getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(clause.types[0]); + var newClause = ts.updateHeritageClause(clause, ts.map(clause.types, function (t) { return ts.updateExpressionWithTypeArguments(t, ts.visitNodes(t.typeArguments, visitDeclarationSubtree), newId_1); })); + getSymbolAccessibilityDiagnostic = oldDiag_2; + return newClause; + } + return ts.updateHeritageClause(clause, ts.visitNodes(ts.createNodeArray(ts.filter(clause.types, function (t) { return ts.isEntityNameExpression(t.expression) || t.expression.kind === 96 /* NullKeyword */; })), visitDeclarationSubtree)); + })); + return [statement, cleanup(ts.updateClassDeclaration(input, + /*decorators*/ undefined, modifiers, input.name, typeParameters, heritageClauses, members))]; // TODO: GH#18217 + } + else { + var heritageClauses = transformHeritageClauses(input.heritageClauses); + return cleanup(ts.updateClassDeclaration(input, + /*decorators*/ undefined, modifiers, input.name, typeParameters, heritageClauses, members)); + } + } + case 219 /* VariableStatement */: { + return cleanup(transformVariableStatement(input, isPrivate)); + } + case 243 /* EnumDeclaration */: { + return cleanup(ts.updateEnumDeclaration(input, /*decorators*/ undefined, ts.createNodeArray(ensureModifiers(input, isPrivate)), input.name, ts.createNodeArray(ts.mapDefined(input.members, function (m) { + if (shouldStripInternal(m)) + return; + // Rewrite enum values to their constants, if available + var constValue = resolver.getConstantValue(m); + return preserveJsDoc(ts.updateEnumMember(m, m.name, constValue !== undefined ? ts.createLiteral(constValue) : undefined), m); + })))); + } + } + // Anything left unhandled is an error, so this should be unreachable + return ts.Debug.assertNever(input, "Unhandled top-level node in declaration emit: " + ts.SyntaxKind[input.kind]); + function cleanup(node) { + if (isEnclosingDeclaration(input)) { + enclosingDeclaration = previousEnclosingDeclaration; + } + if (canProdiceDiagnostic) { + getSymbolAccessibilityDiagnostic = oldDiag; + } + if (input.kind === 244 /* ModuleDeclaration */) { + needsDeclare = previousNeedsDeclare; + } + if (node === input) { + return node; + } + return node && ts.setOriginalNode(preserveJsDoc(node, input), input); + } + } + function transformVariableStatement(input, privateDeclaration) { + if (!ts.forEach(input.declarationList.declarations, getBindingNameVisible)) + return; + var nodes = ts.visitNodes(input.declarationList.declarations, visitDeclarationSubtree); + if (!ts.length(nodes)) + return; + return ts.updateVariableStatement(input, ts.createNodeArray(ensureModifiers(input, privateDeclaration)), ts.updateVariableDeclarationList(input.declarationList, nodes)); + } + function recreateBindingPattern(d) { + return ts.flatten(ts.mapDefined(d.elements, function (e) { return recreateBindingElement(e); })); + } + function recreateBindingElement(e) { + if (e.kind === 210 /* OmittedExpression */) { + return; + } + if (e.name) { + if (!getBindingNameVisible(e)) + return; + if (ts.isBindingPattern(e.name)) { + return recreateBindingPattern(e.name); + } + else { + return ts.createVariableDeclaration(e.name, ensureType(e, /*type*/ undefined), /*initializer*/ undefined); + } + } + } + function checkName(node) { + var oldDiag; + if (!suppressNewDiagnosticContexts) { + oldDiag = getSymbolAccessibilityDiagnostic; + getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNodeName(node); + } + errorNameNode = node.name; + ts.Debug.assert(resolver.isLateBound(ts.getParseTreeNode(node))); // Should only be called with dynamic names + var decl = node; + var entityName = decl.name.expression; + checkEntityNameVisibility(entityName, enclosingDeclaration); + if (!suppressNewDiagnosticContexts) { + getSymbolAccessibilityDiagnostic = oldDiag; + } + errorNameNode = undefined; + } + function hasInternalAnnotation(range) { + var comment = currentSourceFile.text.substring(range.pos, range.end); + return ts.stringContains(comment, "@internal"); + } + function shouldStripInternal(node) { + if (stripInternal && node) { + var leadingCommentRanges = ts.getLeadingCommentRangesOfNode(ts.getParseTreeNode(node), currentSourceFile); + if (ts.forEach(leadingCommentRanges, hasInternalAnnotation)) { + return true; + } + } + return false; + } + function isScopeMarker(node) { + return ts.isExportAssignment(node) || ts.isExportDeclaration(node); + } + function hasScopeMarker(node) { + if (ts.isModuleBlock(node)) { + return ts.some(node.statements, isScopeMarker); + } + return false; + } + function ensureModifiers(node, privateDeclaration) { + var currentFlags = ts.getModifierFlags(node); + var newFlags = ensureModifierFlags(node, privateDeclaration); + if (currentFlags === newFlags) { + return node.modifiers; + } + return ts.createModifiersFromModifierFlags(newFlags); + } + function ensureModifierFlags(node, privateDeclaration) { + var mask = 3071 /* All */ ^ (4 /* Public */ | 256 /* Async */); // No async modifiers in declaration files + var additions = (needsDeclare && !isAlwaysType(node)) ? 2 /* Ambient */ : 0 /* None */; + var parentIsFile = node.parent.kind === 279 /* SourceFile */; + if (!parentIsFile || (isBundledEmit && parentIsFile && ts.isExternalModule(node.parent))) { + mask ^= ((privateDeclaration || (isBundledEmit && parentIsFile) || hasScopeMarker(node.parent) ? 0 : 1 /* Export */) | 2 /* Ambient */); + additions = 0 /* None */; + } + return maskModifierFlags(node, mask, additions); + } + function ensureAccessor(node) { + var accessors = resolver.getAllAccessorDeclarations(node); + if (node.kind !== accessors.firstAccessor.kind) { + return; + } + var accessorType = getTypeAnnotationFromAccessor(node); + if (!accessorType && accessors.secondAccessor) { + accessorType = getTypeAnnotationFromAccessor(accessors.secondAccessor); + // If we end up pulling the type from the second accessor, we also need to change the diagnostic context to get the expected error message + getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(accessors.secondAccessor); + } + var prop = ts.createProperty(/*decorators*/ undefined, maskModifiers(node, /*mask*/ undefined, (!accessors.setAccessor) ? 64 /* Readonly */ : 0 /* None */), node.name, node.questionToken, ensureType(node, accessorType), /*initializer*/ undefined); + var leadingsSyntheticCommentRanges = accessors.secondAccessor && ts.getLeadingCommentRangesOfNode(accessors.secondAccessor, currentSourceFile); + if (leadingsSyntheticCommentRanges) { + var _loop_9 = function (range) { + if (range.kind === 3 /* MultiLineCommentTrivia */) { + var text = currentSourceFile.text.slice(range.pos + 2, range.end - 2); + var lines = text.split(/\r\n?|\n/g); + if (lines.length > 1) { + var lastLines = lines.slice(1); + var indentation_1 = ts.guessIndentation(lastLines); + text = [lines[0]].concat(ts.map(lastLines, function (l) { return l.slice(indentation_1); })).join(newLine); + } + ts.addSyntheticLeadingComment(prop, range.kind, text, range.hasTrailingNewLine); + } + }; + for (var _i = 0, leadingsSyntheticCommentRanges_1 = leadingsSyntheticCommentRanges; _i < leadingsSyntheticCommentRanges_1.length; _i++) { + var range = leadingsSyntheticCommentRanges_1[_i]; + _loop_9(range); + } + } + return prop; + } + function transformHeritageClauses(nodes) { + return ts.createNodeArray(ts.filter(ts.map(nodes, function (clause) { return ts.updateHeritageClause(clause, ts.visitNodes(ts.createNodeArray(ts.filter(clause.types, function (t) { + return ts.isEntityNameExpression(t.expression) || (clause.token === 86 /* ExtendsKeyword */ && t.expression.kind === 96 /* NullKeyword */); + })), visitDeclarationSubtree)); }), function (clause) { return clause.types && !!clause.types.length; })); + } + } + ts.transformDeclarations = transformDeclarations; + function isAlwaysType(node) { + if (node.kind === 241 /* InterfaceDeclaration */) { + return true; + } + return false; + } + // Elide "public" modifier, as it is the default + function maskModifiers(node, modifierMask, modifierAdditions) { + return ts.createModifiersFromModifierFlags(maskModifierFlags(node, modifierMask, modifierAdditions)); + } + function maskModifierFlags(node, modifierMask, modifierAdditions) { + if (modifierMask === void 0) { modifierMask = 3071 /* All */ ^ 4 /* Public */; } + if (modifierAdditions === void 0) { modifierAdditions = 0 /* None */; } + var flags = (ts.getModifierFlags(node) & modifierMask) | modifierAdditions; + if (flags & 512 /* Default */ && !(flags & 1 /* Export */)) { + // A non-exported default is a nonsequitor - we usually try to remove all export modifiers + // from statements in ambient declarations; but a default export must retain its export modifier to be syntactically valid + flags ^= 1 /* Export */; + } + if (flags & 512 /* Default */ && flags & 2 /* Ambient */) { + flags ^= 2 /* Ambient */; // `declare` is never required alongside `default` (and would be an error if printed) + } + return flags; + } + function getTypeAnnotationFromAccessor(accessor) { + if (accessor) { + return accessor.kind === 158 /* GetAccessor */ + ? accessor.type // Getter - return type + : accessor.parameters.length > 0 + ? accessor.parameters[0].type // Setter parameter type + : undefined; + } + } + function canHaveLiteralInitializer(node) { + switch (node.kind) { + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + return !ts.hasModifier(node, 8 /* Private */); + case 151 /* Parameter */: + case 237 /* VariableDeclaration */: + return true; + } + return false; + } + function isPreservedDeclarationStatement(node) { + switch (node.kind) { + case 239 /* FunctionDeclaration */: + case 244 /* ModuleDeclaration */: + case 248 /* ImportEqualsDeclaration */: + case 241 /* InterfaceDeclaration */: + case 240 /* ClassDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 243 /* EnumDeclaration */: + case 219 /* VariableStatement */: + case 249 /* ImportDeclaration */: + case 255 /* ExportDeclaration */: + case 254 /* ExportAssignment */: + return true; + } + return false; + } + function isProcessedComponent(node) { + switch (node.kind) { + case 161 /* ConstructSignature */: + case 157 /* Constructor */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 155 /* MethodSignature */: + case 160 /* CallSignature */: + case 162 /* IndexSignature */: + case 237 /* VariableDeclaration */: + case 150 /* TypeParameter */: + case 211 /* ExpressionWithTypeArguments */: + case 164 /* TypeReference */: + case 175 /* ConditionalType */: + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + case 183 /* ImportType */: + return true; + } + return false; + } +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + function getModuleTransformer(moduleKind) { + switch (moduleKind) { + case ts.ModuleKind.ESNext: + case ts.ModuleKind.ES2015: + return ts.transformES2015Module; + case ts.ModuleKind.System: + return ts.transformSystemModule; + default: + return ts.transformModule; + } + } + var TransformationState; + (function (TransformationState) { + TransformationState[TransformationState["Uninitialized"] = 0] = "Uninitialized"; + TransformationState[TransformationState["Initialized"] = 1] = "Initialized"; + TransformationState[TransformationState["Completed"] = 2] = "Completed"; + TransformationState[TransformationState["Disposed"] = 3] = "Disposed"; + })(TransformationState || (TransformationState = {})); + var SyntaxKindFeatureFlags; + (function (SyntaxKindFeatureFlags) { + SyntaxKindFeatureFlags[SyntaxKindFeatureFlags["Substitution"] = 1] = "Substitution"; + SyntaxKindFeatureFlags[SyntaxKindFeatureFlags["EmitNotifications"] = 2] = "EmitNotifications"; + })(SyntaxKindFeatureFlags || (SyntaxKindFeatureFlags = {})); + function getTransformers(compilerOptions, customTransformers) { + var jsx = compilerOptions.jsx; + var languageVersion = ts.getEmitScriptTarget(compilerOptions); + var moduleKind = ts.getEmitModuleKind(compilerOptions); + var transformers = []; + ts.addRange(transformers, customTransformers && customTransformers.before); + transformers.push(ts.transformTypeScript); + if (jsx === 2 /* React */) { + transformers.push(ts.transformJsx); + } + if (languageVersion < 6 /* ESNext */) { + transformers.push(ts.transformESNext); + } + if (languageVersion < 4 /* ES2017 */) { + transformers.push(ts.transformES2017); + } + if (languageVersion < 3 /* ES2016 */) { + transformers.push(ts.transformES2016); + } + if (languageVersion < 2 /* ES2015 */) { + transformers.push(ts.transformES2015); + transformers.push(ts.transformGenerators); + } + transformers.push(getModuleTransformer(moduleKind)); + // The ES5 transformer is last so that it can substitute expressions like `exports.default` + // for ES3. + if (languageVersion < 1 /* ES5 */) { + transformers.push(ts.transformES5); + } + ts.addRange(transformers, customTransformers && customTransformers.after); + return transformers; + } + ts.getTransformers = getTransformers; + function noEmitSubstitution(_hint, node) { + return node; + } + ts.noEmitSubstitution = noEmitSubstitution; + function noEmitNotification(hint, node, callback) { + callback(hint, node); + } + ts.noEmitNotification = noEmitNotification; + /** + * Transforms an array of SourceFiles by passing them through each transformer. + * + * @param resolver The emit resolver provided by the checker. + * @param host The emit host object used to interact with the file system. + * @param options Compiler options to surface in the `TransformationContext`. + * @param nodes An array of nodes to transform. + * @param transforms An array of `TransformerFactory` callbacks. + * @param allowDtsFiles A value indicating whether to allow the transformation of .d.ts files. + */ + function transformNodes(resolver, host, options, nodes, transformers, allowDtsFiles) { + var enabledSyntaxKindFeatures = new Array(312 /* Count */); + var lexicalEnvironmentVariableDeclarations; + var lexicalEnvironmentFunctionDeclarations; + var lexicalEnvironmentVariableDeclarationsStack = []; + var lexicalEnvironmentFunctionDeclarationsStack = []; + var lexicalEnvironmentStackOffset = 0; + var lexicalEnvironmentSuspended = false; + var emitHelpers; + var onSubstituteNode = noEmitSubstitution; + var onEmitNode = noEmitNotification; + var state = 0 /* Uninitialized */; + var diagnostics = []; + // The transformation context is provided to each transformer as part of transformer + // initialization. + var context = { + getCompilerOptions: function () { return options; }, + getEmitResolver: function () { return resolver; }, + getEmitHost: function () { return host; }, + startLexicalEnvironment: startLexicalEnvironment, + suspendLexicalEnvironment: suspendLexicalEnvironment, + resumeLexicalEnvironment: resumeLexicalEnvironment, + endLexicalEnvironment: endLexicalEnvironment, + hoistVariableDeclaration: hoistVariableDeclaration, + hoistFunctionDeclaration: hoistFunctionDeclaration, + requestEmitHelper: requestEmitHelper, + readEmitHelpers: readEmitHelpers, + enableSubstitution: enableSubstitution, + enableEmitNotification: enableEmitNotification, + isSubstitutionEnabled: isSubstitutionEnabled, + isEmitNotificationEnabled: isEmitNotificationEnabled, + get onSubstituteNode() { return onSubstituteNode; }, + set onSubstituteNode(value) { + ts.Debug.assert(state < 1 /* Initialized */, "Cannot modify transformation hooks after initialization has completed."); + ts.Debug.assert(value !== undefined, "Value must not be 'undefined'"); + onSubstituteNode = value; + }, + get onEmitNode() { return onEmitNode; }, + set onEmitNode(value) { + ts.Debug.assert(state < 1 /* Initialized */, "Cannot modify transformation hooks after initialization has completed."); + ts.Debug.assert(value !== undefined, "Value must not be 'undefined'"); + onEmitNode = value; + }, + addDiagnostic: function (diag) { + diagnostics.push(diag); + } + }; + // Ensure the parse tree is clean before applying transformations + for (var _i = 0, nodes_4 = nodes; _i < nodes_4.length; _i++) { + var node = nodes_4[_i]; + ts.disposeEmitNodes(ts.getSourceFileOfNode(ts.getParseTreeNode(node))); + } + ts.performance.mark("beforeTransform"); + // Chain together and initialize each transformer. + var transformation = ts.chain.apply(void 0, transformers)(context); + // prevent modification of transformation hooks. + state = 1 /* Initialized */; + // Transform each node. + var transformed = ts.map(nodes, allowDtsFiles ? transformation : transformRoot); + // prevent modification of the lexical environment. + state = 2 /* Completed */; + ts.performance.mark("afterTransform"); + ts.performance.measure("transformTime", "beforeTransform", "afterTransform"); + return { + transformed: transformed, + substituteNode: substituteNode, + emitNodeWithNotification: emitNodeWithNotification, + dispose: dispose, + diagnostics: diagnostics + }; + function transformRoot(node) { + return node && (!ts.isSourceFile(node) || !node.isDeclarationFile) ? transformation(node) : node; + } + /** + * Enables expression substitutions in the pretty printer for the provided SyntaxKind. + */ + function enableSubstitution(kind) { + ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the transformation context after transformation has completed."); + enabledSyntaxKindFeatures[kind] |= 1 /* Substitution */; + } + /** + * Determines whether expression substitutions are enabled for the provided node. + */ + function isSubstitutionEnabled(node) { + return (enabledSyntaxKindFeatures[node.kind] & 1 /* Substitution */) !== 0 + && (ts.getEmitFlags(node) & 4 /* NoSubstitution */) === 0; + } + /** + * Emits a node with possible substitution. + * + * @param hint A hint as to the intended usage of the node. + * @param node The node to emit. + * @param emitCallback The callback used to emit the node or its substitute. + */ + function substituteNode(hint, node) { + ts.Debug.assert(state < 3 /* Disposed */, "Cannot substitute a node after the result is disposed."); + return node && isSubstitutionEnabled(node) && onSubstituteNode(hint, node) || node; + } + /** + * Enables before/after emit notifications in the pretty printer for the provided SyntaxKind. + */ + function enableEmitNotification(kind) { + ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the transformation context after transformation has completed."); + enabledSyntaxKindFeatures[kind] |= 2 /* EmitNotifications */; + } + /** + * Determines whether before/after emit notifications should be raised in the pretty + * printer when it emits a node. + */ + function isEmitNotificationEnabled(node) { + return (enabledSyntaxKindFeatures[node.kind] & 2 /* EmitNotifications */) !== 0 + || (ts.getEmitFlags(node) & 2 /* AdviseOnEmitNode */) !== 0; + } + /** + * Emits a node with possible emit notification. + * + * @param hint A hint as to the intended usage of the node. + * @param node The node to emit. + * @param emitCallback The callback used to emit the node. + */ + function emitNodeWithNotification(hint, node, emitCallback) { + ts.Debug.assert(state < 3 /* Disposed */, "Cannot invoke TransformationResult callbacks after the result is disposed."); + if (node) { + if (isEmitNotificationEnabled(node)) { + onEmitNode(hint, node, emitCallback); + } + else { + emitCallback(hint, node); + } + } + } + /** + * Records a hoisted variable declaration for the provided name within a lexical environment. + */ + function hoistVariableDeclaration(name) { + ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization."); + ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed."); + var decl = ts.setEmitFlags(ts.createVariableDeclaration(name), 64 /* NoNestedSourceMaps */); + if (!lexicalEnvironmentVariableDeclarations) { + lexicalEnvironmentVariableDeclarations = [decl]; + } + else { + lexicalEnvironmentVariableDeclarations.push(decl); + } + } + /** + * Records a hoisted function declaration within a lexical environment. + */ + function hoistFunctionDeclaration(func) { + ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization."); + ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed."); + if (!lexicalEnvironmentFunctionDeclarations) { + lexicalEnvironmentFunctionDeclarations = [func]; + } + else { + lexicalEnvironmentFunctionDeclarations.push(func); + } + } + /** + * Starts a new lexical environment. Any existing hoisted variable or function declarations + * are pushed onto a stack, and the related storage variables are reset. + */ + function startLexicalEnvironment() { + ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization."); + ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed."); + ts.Debug.assert(!lexicalEnvironmentSuspended, "Lexical environment is suspended."); + // Save the current lexical environment. Rather than resizing the array we adjust the + // stack size variable. This allows us to reuse existing array slots we've + // already allocated between transformations to avoid allocation and GC overhead during + // transformation. + lexicalEnvironmentVariableDeclarationsStack[lexicalEnvironmentStackOffset] = lexicalEnvironmentVariableDeclarations; + lexicalEnvironmentFunctionDeclarationsStack[lexicalEnvironmentStackOffset] = lexicalEnvironmentFunctionDeclarations; + lexicalEnvironmentStackOffset++; + lexicalEnvironmentVariableDeclarations = undefined; + lexicalEnvironmentFunctionDeclarations = undefined; + } + /** Suspends the current lexical environment, usually after visiting a parameter list. */ + function suspendLexicalEnvironment() { + ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization."); + ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed."); + ts.Debug.assert(!lexicalEnvironmentSuspended, "Lexical environment is already suspended."); + lexicalEnvironmentSuspended = true; + } + /** Resumes a suspended lexical environment, usually before visiting a function body. */ + function resumeLexicalEnvironment() { + ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization."); + ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed."); + ts.Debug.assert(lexicalEnvironmentSuspended, "Lexical environment is not suspended."); + lexicalEnvironmentSuspended = false; + } + /** + * Ends a lexical environment. The previous set of hoisted declarations are restored and + * any hoisted declarations added in this environment are returned. + */ + function endLexicalEnvironment() { + ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization."); + ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed."); + ts.Debug.assert(!lexicalEnvironmentSuspended, "Lexical environment is suspended."); + var statements; + if (lexicalEnvironmentVariableDeclarations || lexicalEnvironmentFunctionDeclarations) { + if (lexicalEnvironmentFunctionDeclarations) { + statements = lexicalEnvironmentFunctionDeclarations.slice(); + } + if (lexicalEnvironmentVariableDeclarations) { + var statement = ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList(lexicalEnvironmentVariableDeclarations)); + if (!statements) { + statements = [statement]; + } + else { + statements.push(statement); + } + } + } + // Restore the previous lexical environment. + lexicalEnvironmentStackOffset--; + lexicalEnvironmentVariableDeclarations = lexicalEnvironmentVariableDeclarationsStack[lexicalEnvironmentStackOffset]; + lexicalEnvironmentFunctionDeclarations = lexicalEnvironmentFunctionDeclarationsStack[lexicalEnvironmentStackOffset]; + if (lexicalEnvironmentStackOffset === 0) { + lexicalEnvironmentVariableDeclarationsStack = []; + lexicalEnvironmentFunctionDeclarationsStack = []; + } + return statements; + } + function requestEmitHelper(helper) { + ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the transformation context during initialization."); + ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the transformation context after transformation has completed."); + ts.Debug.assert(!helper.scoped, "Cannot request a scoped emit helper."); + emitHelpers = ts.append(emitHelpers, helper); + } + function readEmitHelpers() { + ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the transformation context during initialization."); + ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the transformation context after transformation has completed."); + var helpers = emitHelpers; + emitHelpers = undefined; + return helpers; + } + function dispose() { + if (state < 3 /* Disposed */) { + // Clean up emit nodes on parse tree + for (var _i = 0, nodes_5 = nodes; _i < nodes_5.length; _i++) { + var node = nodes_5[_i]; + ts.disposeEmitNodes(ts.getSourceFileOfNode(ts.getParseTreeNode(node))); + } + // Release references to external entries for GC purposes. + lexicalEnvironmentVariableDeclarations = undefined; + lexicalEnvironmentVariableDeclarationsStack = undefined; + lexicalEnvironmentFunctionDeclarations = undefined; + lexicalEnvironmentFunctionDeclarationsStack = undefined; + onSubstituteNode = undefined; + onEmitNode = undefined; + emitHelpers = undefined; + // Prevent further use of the transformation result. + state = 3 /* Disposed */; + } + } + } + ts.transformNodes = transformNodes; +})(ts || (ts = {})); +var ts; +(function (ts) { + var infoExtension = ".tsbundleinfo"; + var brackets = createBracketsMap(); + var syntheticParent = { pos: -1, end: -1 }; + /*@internal*/ + /** + * Iterates over the source files that are expected to have an emit output. + * + * @param host An EmitHost. + * @param action The action to execute. + * @param sourceFilesOrTargetSourceFile + * If an array, the full list of source files to emit. + * Else, calls `getSourceFilesToEmit` with the (optional) target source file to determine the list of source files to emit. + */ + function forEachEmittedFile(host, action, sourceFilesOrTargetSourceFile, emitOnlyDtsFiles) { + if (emitOnlyDtsFiles === void 0) { emitOnlyDtsFiles = false; } + var sourceFiles = ts.isArray(sourceFilesOrTargetSourceFile) ? sourceFilesOrTargetSourceFile : ts.getSourceFilesToEmit(host, sourceFilesOrTargetSourceFile); + var options = host.getCompilerOptions(); + if (options.outFile || options.out) { + if (sourceFiles.length) { + var bundle = ts.createBundle(sourceFiles, host.getPrependNodes()); + var result = action(getOutputPathsFor(bundle, host, emitOnlyDtsFiles), bundle); + if (result) { + return result; + } + } + } + else { + for (var _a = 0, sourceFiles_1 = sourceFiles; _a < sourceFiles_1.length; _a++) { + var sourceFile = sourceFiles_1[_a]; + var result = action(getOutputPathsFor(sourceFile, host, emitOnlyDtsFiles), sourceFile); + if (result) { + return result; + } + } + } + } + ts.forEachEmittedFile = forEachEmittedFile; + /*@internal*/ + function getOutputPathsFor(sourceFile, host, forceDtsPaths) { + var options = host.getCompilerOptions(); + if (sourceFile.kind === 280 /* Bundle */) { + var outPath = options.outFile || options.out; + var jsFilePath = options.emitDeclarationOnly ? undefined : outPath; + var sourceMapFilePath = jsFilePath && getSourceMapFilePath(jsFilePath, options); + var declarationFilePath = (forceDtsPaths || ts.getEmitDeclarations(options)) ? ts.removeFileExtension(outPath) + ".d.ts" /* Dts */ : undefined; + var declarationMapPath = declarationFilePath && ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; + var bundleInfoPath = options.references && jsFilePath ? (ts.removeFileExtension(jsFilePath) + infoExtension) : undefined; + return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, bundleInfoPath: bundleInfoPath }; + } + else { + var ownOutputFilePath = ts.getOwnEmitOutputFilePath(sourceFile.fileName, host, getOutputExtension(sourceFile, options)); + // If json file emits to the same location skip writing it, if emitDeclarationOnly skip writing it + var isJsonEmittedToSameLocation = ts.isJsonSourceFile(sourceFile) && + ts.comparePaths(sourceFile.fileName, ownOutputFilePath, host.getCurrentDirectory(), !host.useCaseSensitiveFileNames()) === 0 /* EqualTo */; + var jsFilePath = options.emitDeclarationOnly || isJsonEmittedToSameLocation ? undefined : ownOutputFilePath; + var sourceMapFilePath = !jsFilePath || ts.isJsonSourceFile(sourceFile) ? undefined : getSourceMapFilePath(jsFilePath, options); + // For legacy reasons (ie, we have baselines capturing the behavior), js files don't report a .d.ts output path - this would only matter if `declaration` and `allowJs` were both on, which is currently an error + var isJs = ts.isSourceFileJS(sourceFile); + var declarationFilePath = ((forceDtsPaths || ts.getEmitDeclarations(options)) && !isJs) ? ts.getDeclarationEmitOutputFilePath(sourceFile.fileName, host) : undefined; + var declarationMapPath = declarationFilePath && ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; + return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, bundleInfoPath: undefined }; + } + } + ts.getOutputPathsFor = getOutputPathsFor; + function getSourceMapFilePath(jsFilePath, options) { + return (options.sourceMap && !options.inlineSourceMap) ? jsFilePath + ".map" : undefined; + } + function createDefaultBundleInfo() { + return { + originalOffset: -1, + totalLength: -1 + }; + } + // JavaScript files are always LanguageVariant.JSX, as JSX syntax is allowed in .js files also. + // So for JavaScript files, '.jsx' is only emitted if the input was '.jsx', and JsxEmit.Preserve. + // For TypeScript, the only time to emit with a '.jsx' extension, is on JSX input, and JsxEmit.Preserve + /* @internal */ + function getOutputExtension(sourceFile, options) { + if (ts.isJsonSourceFile(sourceFile)) { + return ".json" /* Json */; + } + if (options.jsx === 1 /* Preserve */) { + if (ts.isSourceFileJS(sourceFile)) { + if (ts.fileExtensionIs(sourceFile.fileName, ".jsx" /* Jsx */)) { + return ".jsx" /* Jsx */; + } + } + else if (sourceFile.languageVariant === 1 /* JSX */) { + // TypeScript source file preserving JSX syntax + return ".jsx" /* Jsx */; + } + } + return ".js" /* Js */; + } + ts.getOutputExtension = getOutputExtension; + /*@internal*/ + // targetSourceFile is when users only want one file in entire project to be emitted. This is used in compileOnSave feature + function emitFiles(resolver, host, targetSourceFile, emitOnlyDtsFiles, transformers, declarationTransformers) { + var compilerOptions = host.getCompilerOptions(); + var sourceMapDataList = (compilerOptions.sourceMap || compilerOptions.inlineSourceMap || ts.getAreDeclarationMapsEnabled(compilerOptions)) ? [] : undefined; + var emittedFilesList = compilerOptions.listEmittedFiles ? [] : undefined; + var emitterDiagnostics = ts.createDiagnosticCollection(); + var newLine = ts.getNewLineCharacter(compilerOptions, function () { return host.getNewLine(); }); + var writer = ts.createTextWriter(newLine); + var _a = ts.performance.createTimer("printTime", "beforePrint", "afterPrint"), enter = _a.enter, exit = _a.exit; + var bundleInfo = createDefaultBundleInfo(); + var emitSkipped = false; + var exportedModulesFromDeclarationEmit; + // Emit each output file + enter(); + forEachEmittedFile(host, emitSourceFileOrBundle, ts.getSourceFilesToEmit(host, targetSourceFile), emitOnlyDtsFiles); + exit(); + return { + emitSkipped: emitSkipped, + diagnostics: emitterDiagnostics.getDiagnostics(), + emittedFiles: emittedFilesList, + sourceMaps: sourceMapDataList, + exportedModulesFromDeclarationEmit: exportedModulesFromDeclarationEmit + }; + function emitSourceFileOrBundle(_a, sourceFileOrBundle) { + var jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, bundleInfoPath = _a.bundleInfoPath; + emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, bundleInfoPath); + emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath); + if (!emitSkipped && emittedFilesList) { + if (!emitOnlyDtsFiles) { + if (jsFilePath) { + emittedFilesList.push(jsFilePath); + } + if (sourceMapFilePath) { + emittedFilesList.push(sourceMapFilePath); + } + if (bundleInfoPath) { + emittedFilesList.push(bundleInfoPath); + } + } + if (declarationFilePath) { + emittedFilesList.push(declarationFilePath); + } + if (declarationMapPath) { + emittedFilesList.push(declarationMapPath); + } + } + } + function emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, bundleInfoPath) { + if (emitOnlyDtsFiles || !jsFilePath) { + return; + } + // Make sure not to write js file and source map file if any of them cannot be written + if ((jsFilePath && host.isEmitBlocked(jsFilePath)) || compilerOptions.noEmit) { + emitSkipped = true; + return; + } + // Transform the source files + var transform = ts.transformNodes(resolver, host, compilerOptions, [sourceFileOrBundle], transformers, /*allowDtsFiles*/ false); + var printerOptions = { + removeComments: compilerOptions.removeComments, + newLine: compilerOptions.newLine, + noEmitHelpers: compilerOptions.noEmitHelpers, + module: compilerOptions.module, + target: compilerOptions.target, + sourceMap: compilerOptions.sourceMap, + inlineSourceMap: compilerOptions.inlineSourceMap, + inlineSources: compilerOptions.inlineSources, + extendedDiagnostics: compilerOptions.extendedDiagnostics, + }; + // Create a printer to print the nodes + var printer = createPrinter(printerOptions, { + // resolver hooks + hasGlobalName: resolver.hasGlobalName, + // transform hooks + onEmitNode: transform.emitNodeWithNotification, + substituteNode: transform.substituteNode, + }); + ts.Debug.assert(transform.transformed.length === 1, "Should only see one output from the transform"); + printSourceFileOrBundle(jsFilePath, sourceMapFilePath, transform.transformed[0], bundleInfoPath, printer, compilerOptions); + // Clean up emit nodes on parse tree + transform.dispose(); + } + function emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath) { + if (!(declarationFilePath && !ts.isInJSFile(sourceFileOrBundle))) { + return; + } + var sourceFiles = ts.isSourceFile(sourceFileOrBundle) ? [sourceFileOrBundle] : sourceFileOrBundle.sourceFiles; + // Setup and perform the transformation to retrieve declarations from the input files + var nonJsFiles = ts.filter(sourceFiles, ts.isSourceFileNotJS); + var inputListOrBundle = (compilerOptions.outFile || compilerOptions.out) ? [ts.createBundle(nonJsFiles, !ts.isSourceFile(sourceFileOrBundle) ? sourceFileOrBundle.prepends : undefined)] : nonJsFiles; + if (emitOnlyDtsFiles && !ts.getEmitDeclarations(compilerOptions)) { + // Checker wont collect the linked aliases since thats only done when declaration is enabled. + // Do that here when emitting only dts files + nonJsFiles.forEach(collectLinkedAliases); + } + var declarationTransform = ts.transformNodes(resolver, host, compilerOptions, inputListOrBundle, ts.concatenate([ts.transformDeclarations], declarationTransformers), /*allowDtsFiles*/ false); + if (ts.length(declarationTransform.diagnostics)) { + for (var _a = 0, _b = declarationTransform.diagnostics; _a < _b.length; _a++) { + var diagnostic = _b[_a]; + emitterDiagnostics.add(diagnostic); + } + } + var printerOptions = { + removeComments: compilerOptions.removeComments, + newLine: compilerOptions.newLine, + noEmitHelpers: true, + module: compilerOptions.module, + target: compilerOptions.target, + sourceMap: compilerOptions.sourceMap, + inlineSourceMap: compilerOptions.inlineSourceMap, + extendedDiagnostics: compilerOptions.extendedDiagnostics, + onlyPrintJsDocStyle: true, + }; + var declarationPrinter = createPrinter(printerOptions, { + // resolver hooks + hasGlobalName: resolver.hasGlobalName, + // transform hooks + onEmitNode: declarationTransform.emitNodeWithNotification, + substituteNode: declarationTransform.substituteNode, + }); + var declBlocked = (!!declarationTransform.diagnostics && !!declarationTransform.diagnostics.length) || !!host.isEmitBlocked(declarationFilePath) || !!compilerOptions.noEmit; + emitSkipped = emitSkipped || declBlocked; + if (!declBlocked || emitOnlyDtsFiles) { + ts.Debug.assert(declarationTransform.transformed.length === 1, "Should only see one output from the decl transform"); + printSourceFileOrBundle(declarationFilePath, declarationMapPath, declarationTransform.transformed[0], /* bundleInfopath*/ undefined, declarationPrinter, { + sourceMap: compilerOptions.declarationMap, + sourceRoot: compilerOptions.sourceRoot, + mapRoot: compilerOptions.mapRoot, + extendedDiagnostics: compilerOptions.extendedDiagnostics, + }); + if (emitOnlyDtsFiles && declarationTransform.transformed[0].kind === 279 /* SourceFile */) { + var sourceFile = declarationTransform.transformed[0]; + exportedModulesFromDeclarationEmit = sourceFile.exportedModulesFromDeclarationEmit; + } + } + declarationTransform.dispose(); + } + function collectLinkedAliases(node) { + if (ts.isExportAssignment(node)) { + if (node.expression.kind === 72 /* Identifier */) { + resolver.collectLinkedAliases(node.expression, /*setVisibility*/ true); + } + return; + } + else if (ts.isExportSpecifier(node)) { + resolver.collectLinkedAliases(node.propertyName || node.name, /*setVisibility*/ true); + return; + } + ts.forEachChild(node, collectLinkedAliases); + } + function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle, bundleInfoPath, printer, mapOptions) { + var bundle = sourceFileOrBundle.kind === 280 /* Bundle */ ? sourceFileOrBundle : undefined; + var sourceFile = sourceFileOrBundle.kind === 279 /* SourceFile */ ? sourceFileOrBundle : undefined; + var sourceFiles = bundle ? bundle.sourceFiles : [sourceFile]; + var sourceMapGenerator; + if (shouldEmitSourceMaps(mapOptions, sourceFileOrBundle)) { + sourceMapGenerator = ts.createSourceMapGenerator(host, ts.getBaseFileName(ts.normalizeSlashes(jsFilePath)), getSourceRoot(mapOptions), getSourceMapDirectory(mapOptions, jsFilePath, sourceFile), mapOptions); + } + if (bundle) { + printer.writeBundle(bundle, bundleInfo, writer, sourceMapGenerator); + } + else { + printer.writeFile(sourceFile, writer, sourceMapGenerator); + } + if (sourceMapGenerator) { + if (sourceMapDataList) { + sourceMapDataList.push({ + inputSourceFileNames: sourceMapGenerator.getSources(), + sourceMap: sourceMapGenerator.toJSON() + }); + } + var sourceMappingURL = getSourceMappingURL(mapOptions, sourceMapGenerator, jsFilePath, sourceMapFilePath, sourceFile); + if (sourceMappingURL) { + if (!writer.isAtStartOfLine()) + writer.rawWrite(newLine); + writer.writeComment("//# " + "sourceMappingURL" + "=" + sourceMappingURL); // Tools can sometimes see this line as a source mapping url comment + } + // Write the source map + if (sourceMapFilePath) { + var sourceMap = sourceMapGenerator.toString(); + ts.writeFile(host, emitterDiagnostics, sourceMapFilePath, sourceMap, /*writeByteOrderMark*/ false, sourceFiles); + } + } + else { + writer.writeLine(); + } + // Write the output file + ts.writeFile(host, emitterDiagnostics, jsFilePath, writer.getText(), !!compilerOptions.emitBOM, sourceFiles); + // Write bundled offset information if applicable + if (bundleInfoPath) { + bundleInfo.totalLength = writer.getTextPos(); + ts.writeFile(host, emitterDiagnostics, bundleInfoPath, JSON.stringify(bundleInfo, undefined, 2), /*writeByteOrderMark*/ false); + } + // Reset state + writer.clear(); + bundleInfo = createDefaultBundleInfo(); + } + function shouldEmitSourceMaps(mapOptions, sourceFileOrBundle) { + return (mapOptions.sourceMap || mapOptions.inlineSourceMap) + && (sourceFileOrBundle.kind !== 279 /* SourceFile */ || !ts.fileExtensionIs(sourceFileOrBundle.fileName, ".json" /* Json */)); + } + function getSourceRoot(mapOptions) { + // Normalize source root and make sure it has trailing "/" so that it can be used to combine paths with the + // relative paths of the sources list in the sourcemap + var sourceRoot = ts.normalizeSlashes(mapOptions.sourceRoot || ""); + return sourceRoot ? ts.ensureTrailingDirectorySeparator(sourceRoot) : sourceRoot; + } + function getSourceMapDirectory(mapOptions, filePath, sourceFile) { + if (mapOptions.sourceRoot) + return host.getCommonSourceDirectory(); + if (mapOptions.mapRoot) { + var sourceMapDir = ts.normalizeSlashes(mapOptions.mapRoot); + if (sourceFile) { + // For modules or multiple emit files the mapRoot will have directory structure like the sources + // So if src\a.ts and src\lib\b.ts are compiled together user would be moving the maps into mapRoot\a.js.map and mapRoot\lib\b.js.map + sourceMapDir = ts.getDirectoryPath(ts.getSourceFilePathInNewDir(sourceFile.fileName, host, sourceMapDir)); + } + if (ts.getRootLength(sourceMapDir) === 0) { + // The relative paths are relative to the common directory + sourceMapDir = ts.combinePaths(host.getCommonSourceDirectory(), sourceMapDir); + } + return sourceMapDir; + } + return ts.getDirectoryPath(ts.normalizePath(filePath)); + } + function getSourceMappingURL(mapOptions, sourceMapGenerator, filePath, sourceMapFilePath, sourceFile) { + if (mapOptions.inlineSourceMap) { + // Encode the sourceMap into the sourceMap url + var sourceMapText = sourceMapGenerator.toString(); + var base64SourceMapText = ts.base64encode(ts.sys, sourceMapText); + return "data:application/json;base64," + base64SourceMapText; + } + var sourceMapFile = ts.getBaseFileName(ts.normalizeSlashes(ts.Debug.assertDefined(sourceMapFilePath))); + if (mapOptions.mapRoot) { + var sourceMapDir = ts.normalizeSlashes(mapOptions.mapRoot); + if (sourceFile) { + // For modules or multiple emit files the mapRoot will have directory structure like the sources + // So if src\a.ts and src\lib\b.ts are compiled together user would be moving the maps into mapRoot\a.js.map and mapRoot\lib\b.js.map + sourceMapDir = ts.getDirectoryPath(ts.getSourceFilePathInNewDir(sourceFile.fileName, host, sourceMapDir)); + } + if (ts.getRootLength(sourceMapDir) === 0) { + // The relative paths are relative to the common directory + sourceMapDir = ts.combinePaths(host.getCommonSourceDirectory(), sourceMapDir); + return ts.getRelativePathToDirectoryOrUrl(ts.getDirectoryPath(ts.normalizePath(filePath)), // get the relative sourceMapDir path based on jsFilePath + ts.combinePaths(sourceMapDir, sourceMapFile), // this is where user expects to see sourceMap + host.getCurrentDirectory(), host.getCanonicalFileName, + /*isAbsolutePathAnUrl*/ true); + } + else { + return ts.combinePaths(sourceMapDir, sourceMapFile); + } + } + return sourceMapFile; + } + } + ts.emitFiles = emitFiles; + var PipelinePhase; + (function (PipelinePhase) { + PipelinePhase[PipelinePhase["Notification"] = 0] = "Notification"; + PipelinePhase[PipelinePhase["Substitution"] = 1] = "Substitution"; + PipelinePhase[PipelinePhase["Comments"] = 2] = "Comments"; + PipelinePhase[PipelinePhase["SourceMaps"] = 3] = "SourceMaps"; + PipelinePhase[PipelinePhase["Emit"] = 4] = "Emit"; + })(PipelinePhase || (PipelinePhase = {})); + function createPrinter(printerOptions, handlers) { + if (printerOptions === void 0) { printerOptions = {}; } + if (handlers === void 0) { handlers = {}; } + var hasGlobalName = handlers.hasGlobalName, _a = handlers.onEmitNode, onEmitNode = _a === void 0 ? ts.noEmitNotification : _a, _b = handlers.substituteNode, substituteNode = _b === void 0 ? ts.noEmitSubstitution : _b, onBeforeEmitNodeArray = handlers.onBeforeEmitNodeArray, onAfterEmitNodeArray = handlers.onAfterEmitNodeArray, onBeforeEmitToken = handlers.onBeforeEmitToken, onAfterEmitToken = handlers.onAfterEmitToken; + var extendedDiagnostics = !!printerOptions.extendedDiagnostics; + var newLine = ts.getNewLineCharacter(printerOptions); + var moduleKind = ts.getEmitModuleKind(printerOptions); + var bundledHelpers = ts.createMap(); + var currentSourceFile; + var nodeIdToGeneratedName; // Map of generated names for specific nodes. + var autoGeneratedIdToGeneratedName; // Map of generated names for temp and loop variables. + var generatedNames; // Set of names generated by the NameGenerator. + var tempFlagsStack; // Stack of enclosing name generation scopes. + var tempFlags; // TempFlags for the current name generation scope. + var reservedNamesStack; // Stack of TempFlags reserved in enclosing name generation scopes. + var reservedNames; // TempFlags to reserve in nested name generation scopes. + var writer; + var ownWriter; // Reusable `EmitTextWriter` for basic printing. + var write = writeBase; + var isOwnFileEmit; + // Source Maps + var sourceMapsDisabled = true; + var sourceMapGenerator; + var sourceMapSource; + var sourceMapSourceIndex = -1; + // Comments + var containerPos = -1; + var containerEnd = -1; + var declarationListContainerEnd = -1; + var currentLineMap; + var detachedCommentsInfo; + var hasWrittenComment = false; + var commentsDisabled = !!printerOptions.removeComments; + var _c = ts.performance.createTimerIf(extendedDiagnostics, "commentTime", "beforeComment", "afterComment"), enterComment = _c.enter, exitComment = _c.exit; + reset(); + return { + // public API + printNode: printNode, + printList: printList, + printFile: printFile, + printBundle: printBundle, + // internal API + writeNode: writeNode, + writeList: writeList, + writeFile: writeFile, + writeBundle: writeBundle + }; + function printNode(hint, node, sourceFile) { + switch (hint) { + case 0 /* SourceFile */: + ts.Debug.assert(ts.isSourceFile(node), "Expected a SourceFile node."); + break; + case 2 /* IdentifierName */: + ts.Debug.assert(ts.isIdentifier(node), "Expected an Identifier node."); + break; + case 1 /* Expression */: + ts.Debug.assert(ts.isExpression(node), "Expected an Expression node."); + break; + } + switch (node.kind) { + case 279 /* SourceFile */: return printFile(node); + case 280 /* Bundle */: return printBundle(node); + case 281 /* UnparsedSource */: return printUnparsedSource(node); + } + writeNode(hint, node, sourceFile, beginPrint()); + return endPrint(); + } + function printList(format, nodes, sourceFile) { + writeList(format, nodes, sourceFile, beginPrint()); + return endPrint(); + } + function printBundle(bundle) { + writeBundle(bundle, /*bundleInfo*/ undefined, beginPrint(), /*sourceMapEmitter*/ undefined); + return endPrint(); + } + function printFile(sourceFile) { + writeFile(sourceFile, beginPrint(), /*sourceMapEmitter*/ undefined); + return endPrint(); + } + function printUnparsedSource(unparsed) { + writeUnparsedSource(unparsed, beginPrint()); + return endPrint(); + } + function writeNode(hint, node, sourceFile, output) { + var previousWriter = writer; + setWriter(output, /*_sourceMapGenerator*/ undefined); + print(hint, node, sourceFile); + reset(); + writer = previousWriter; + } + function writeList(format, nodes, sourceFile, output) { + var previousWriter = writer; + setWriter(output, /*_sourceMapGenerator*/ undefined); + if (sourceFile) { + setSourceFile(sourceFile); + } + emitList(syntheticParent, nodes, format); + reset(); + writer = previousWriter; + } + function writeBundle(bundle, bundleInfo, output, sourceMapGenerator) { + isOwnFileEmit = false; + var previousWriter = writer; + setWriter(output, sourceMapGenerator); + emitShebangIfNeeded(bundle); + emitPrologueDirectivesIfNeeded(bundle); + emitHelpers(bundle); + emitSyntheticTripleSlashReferencesIfNeeded(bundle); + for (var _a = 0, _b = bundle.prepends; _a < _b.length; _a++) { + var prepend = _b[_a]; + writeLine(); + print(4 /* Unspecified */, prepend, /*sourceFile*/ undefined); + } + if (bundleInfo) { + bundleInfo.originalOffset = writer.getTextPos(); + } + for (var _c = 0, _d = bundle.sourceFiles; _c < _d.length; _c++) { + var sourceFile = _d[_c]; + print(0 /* SourceFile */, sourceFile, sourceFile); + } + reset(); + writer = previousWriter; + } + function writeUnparsedSource(unparsed, output) { + var previousWriter = writer; + setWriter(output, /*_sourceMapGenerator*/ undefined); + print(4 /* Unspecified */, unparsed, /*sourceFile*/ undefined); + reset(); + writer = previousWriter; + } + function writeFile(sourceFile, output, sourceMapGenerator) { + isOwnFileEmit = true; + var previousWriter = writer; + setWriter(output, sourceMapGenerator); + emitShebangIfNeeded(sourceFile); + emitPrologueDirectivesIfNeeded(sourceFile); + print(0 /* SourceFile */, sourceFile, sourceFile); + reset(); + writer = previousWriter; + } + function beginPrint() { + return ownWriter || (ownWriter = ts.createTextWriter(newLine)); + } + function endPrint() { + var text = ownWriter.getText(); + ownWriter.clear(); + return text; + } + function print(hint, node, sourceFile) { + if (sourceFile) { + setSourceFile(sourceFile); + } + var pipelinePhase = getPipelinePhase(0 /* Notification */, node); + pipelinePhase(hint, node); + } + function setSourceFile(sourceFile) { + currentSourceFile = sourceFile; + currentLineMap = undefined; + detachedCommentsInfo = undefined; + if (sourceFile) { + setSourceMapSource(sourceFile); + } + } + function setWriter(_writer, _sourceMapGenerator) { + if (_writer && printerOptions.omitTrailingSemicolon) { + _writer = ts.getTrailingSemicolonOmittingWriter(_writer); + } + writer = _writer; // TODO: GH#18217 + sourceMapGenerator = _sourceMapGenerator; + sourceMapsDisabled = !writer || !sourceMapGenerator; + } + function reset() { + nodeIdToGeneratedName = []; + autoGeneratedIdToGeneratedName = []; + generatedNames = ts.createMap(); + tempFlagsStack = []; + tempFlags = 0 /* Auto */; + reservedNamesStack = []; + currentSourceFile = undefined; + currentLineMap = undefined; + detachedCommentsInfo = undefined; + setWriter(/*output*/ undefined, /*_sourceMapGenerator*/ undefined); + } + function getCurrentLineMap() { + return currentLineMap || (currentLineMap = ts.getLineStarts(currentSourceFile)); + } + function emit(node) { + if (node === undefined) + return; + var pipelinePhase = getPipelinePhase(0 /* Notification */, node); + pipelinePhase(4 /* Unspecified */, node); + } + function emitIdentifierName(node) { + if (node === undefined) + return; + var pipelinePhase = getPipelinePhase(0 /* Notification */, node); + pipelinePhase(2 /* IdentifierName */, node); + } + function emitExpression(node) { + if (node === undefined) + return; + var pipelinePhase = getPipelinePhase(0 /* Notification */, node); + pipelinePhase(1 /* Expression */, node); + } + function getPipelinePhase(phase, node) { + switch (phase) { + case 0 /* Notification */: + if (onEmitNode !== ts.noEmitNotification) { + return pipelineEmitWithNotification; + } + // falls through + case 1 /* Substitution */: + if (substituteNode !== ts.noEmitSubstitution) { + return pipelineEmitWithSubstitution; + } + // falls through + case 2 /* Comments */: + if (!commentsDisabled && node.kind !== 279 /* SourceFile */) { + return pipelineEmitWithComments; + } + // falls through + case 3 /* SourceMaps */: + if (!sourceMapsDisabled && node.kind !== 279 /* SourceFile */ && !ts.isInJsonFile(node)) { + return pipelineEmitWithSourceMap; + } + // falls through + case 4 /* Emit */: + return pipelineEmitWithHint; + default: + return ts.Debug.assertNever(phase); + } + } + function getNextPipelinePhase(currentPhase, node) { + return getPipelinePhase(currentPhase + 1, node); + } + function pipelineEmitWithNotification(hint, node) { + var pipelinePhase = getNextPipelinePhase(0 /* Notification */, node); + onEmitNode(hint, node, pipelinePhase); + } + function pipelineEmitWithHint(hint, node) { + if (hint === 0 /* SourceFile */) + return emitSourceFile(ts.cast(node, ts.isSourceFile)); + if (hint === 2 /* IdentifierName */) + return emitIdentifier(ts.cast(node, ts.isIdentifier)); + if (hint === 3 /* MappedTypeParameter */) + return emitMappedTypeParameter(ts.cast(node, ts.isTypeParameterDeclaration)); + if (hint === 5 /* EmbeddedStatement */) { + ts.Debug.assertNode(node, ts.isEmptyStatement); + return emitEmptyStatement(/*isEmbeddedStatement*/ true); + } + if (hint === 4 /* Unspecified */) { + if (ts.isKeyword(node.kind)) + return writeTokenNode(node, writeKeyword); + switch (node.kind) { + // Pseudo-literals + case 15 /* TemplateHead */: + case 16 /* TemplateMiddle */: + case 17 /* TemplateTail */: + return emitLiteral(node); + case 281 /* UnparsedSource */: + return emitUnparsedSource(node); + // Identifiers + case 72 /* Identifier */: + return emitIdentifier(node); + // Parse tree nodes + // Names + case 148 /* QualifiedName */: + return emitQualifiedName(node); + case 149 /* ComputedPropertyName */: + return emitComputedPropertyName(node); + // Signature elements + case 150 /* TypeParameter */: + return emitTypeParameter(node); + case 151 /* Parameter */: + return emitParameter(node); + case 152 /* Decorator */: + return emitDecorator(node); + // Type members + case 153 /* PropertySignature */: + return emitPropertySignature(node); + case 154 /* PropertyDeclaration */: + return emitPropertyDeclaration(node); + case 155 /* MethodSignature */: + return emitMethodSignature(node); + case 156 /* MethodDeclaration */: + return emitMethodDeclaration(node); + case 157 /* Constructor */: + return emitConstructor(node); + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + return emitAccessorDeclaration(node); + case 160 /* CallSignature */: + return emitCallSignature(node); + case 161 /* ConstructSignature */: + return emitConstructSignature(node); + case 162 /* IndexSignature */: + return emitIndexSignature(node); + // Types + case 163 /* TypePredicate */: + return emitTypePredicate(node); + case 164 /* TypeReference */: + return emitTypeReference(node); + case 165 /* FunctionType */: + return emitFunctionType(node); + case 289 /* JSDocFunctionType */: + return emitJSDocFunctionType(node); + case 166 /* ConstructorType */: + return emitConstructorType(node); + case 167 /* TypeQuery */: + return emitTypeQuery(node); + case 168 /* TypeLiteral */: + return emitTypeLiteral(node); + case 169 /* ArrayType */: + return emitArrayType(node); + case 170 /* TupleType */: + return emitTupleType(node); + case 171 /* OptionalType */: + return emitOptionalType(node); + case 173 /* UnionType */: + return emitUnionType(node); + case 174 /* IntersectionType */: + return emitIntersectionType(node); + case 175 /* ConditionalType */: + return emitConditionalType(node); + case 176 /* InferType */: + return emitInferType(node); + case 177 /* ParenthesizedType */: + return emitParenthesizedType(node); + case 211 /* ExpressionWithTypeArguments */: + return emitExpressionWithTypeArguments(node); + case 178 /* ThisType */: + return emitThisType(); + case 179 /* TypeOperator */: + return emitTypeOperator(node); + case 180 /* IndexedAccessType */: + return emitIndexedAccessType(node); + case 181 /* MappedType */: + return emitMappedType(node); + case 182 /* LiteralType */: + return emitLiteralType(node); + case 183 /* ImportType */: + return emitImportTypeNode(node); + case 284 /* JSDocAllType */: + writePunctuation("*"); + return; + case 285 /* JSDocUnknownType */: + writePunctuation("?"); + return; + case 286 /* JSDocNullableType */: + return emitJSDocNullableType(node); + case 287 /* JSDocNonNullableType */: + return emitJSDocNonNullableType(node); + case 288 /* JSDocOptionalType */: + return emitJSDocOptionalType(node); + case 172 /* RestType */: + case 290 /* JSDocVariadicType */: + return emitRestOrJSDocVariadicType(node); + // Binding patterns + case 184 /* ObjectBindingPattern */: + return emitObjectBindingPattern(node); + case 185 /* ArrayBindingPattern */: + return emitArrayBindingPattern(node); + case 186 /* BindingElement */: + return emitBindingElement(node); + // Misc + case 216 /* TemplateSpan */: + return emitTemplateSpan(node); + case 217 /* SemicolonClassElement */: + return emitSemicolonClassElement(); + // Statements + case 218 /* Block */: + return emitBlock(node); + case 219 /* VariableStatement */: + return emitVariableStatement(node); + case 220 /* EmptyStatement */: + return emitEmptyStatement(/*isEmbeddedStatement*/ false); + case 221 /* ExpressionStatement */: + return emitExpressionStatement(node); + case 222 /* IfStatement */: + return emitIfStatement(node); + case 223 /* DoStatement */: + return emitDoStatement(node); + case 224 /* WhileStatement */: + return emitWhileStatement(node); + case 225 /* ForStatement */: + return emitForStatement(node); + case 226 /* ForInStatement */: + return emitForInStatement(node); + case 227 /* ForOfStatement */: + return emitForOfStatement(node); + case 228 /* ContinueStatement */: + return emitContinueStatement(node); + case 229 /* BreakStatement */: + return emitBreakStatement(node); + case 230 /* ReturnStatement */: + return emitReturnStatement(node); + case 231 /* WithStatement */: + return emitWithStatement(node); + case 232 /* SwitchStatement */: + return emitSwitchStatement(node); + case 233 /* LabeledStatement */: + return emitLabeledStatement(node); + case 234 /* ThrowStatement */: + return emitThrowStatement(node); + case 235 /* TryStatement */: + return emitTryStatement(node); + case 236 /* DebuggerStatement */: + return emitDebuggerStatement(node); + // Declarations + case 237 /* VariableDeclaration */: + return emitVariableDeclaration(node); + case 238 /* VariableDeclarationList */: + return emitVariableDeclarationList(node); + case 239 /* FunctionDeclaration */: + return emitFunctionDeclaration(node); + case 240 /* ClassDeclaration */: + return emitClassDeclaration(node); + case 241 /* InterfaceDeclaration */: + return emitInterfaceDeclaration(node); + case 242 /* TypeAliasDeclaration */: + return emitTypeAliasDeclaration(node); + case 243 /* EnumDeclaration */: + return emitEnumDeclaration(node); + case 244 /* ModuleDeclaration */: + return emitModuleDeclaration(node); + case 245 /* ModuleBlock */: + return emitModuleBlock(node); + case 246 /* CaseBlock */: + return emitCaseBlock(node); + case 247 /* NamespaceExportDeclaration */: + return emitNamespaceExportDeclaration(node); + case 248 /* ImportEqualsDeclaration */: + return emitImportEqualsDeclaration(node); + case 249 /* ImportDeclaration */: + return emitImportDeclaration(node); + case 250 /* ImportClause */: + return emitImportClause(node); + case 251 /* NamespaceImport */: + return emitNamespaceImport(node); + case 252 /* NamedImports */: + return emitNamedImports(node); + case 253 /* ImportSpecifier */: + return emitImportSpecifier(node); + case 254 /* ExportAssignment */: + return emitExportAssignment(node); + case 255 /* ExportDeclaration */: + return emitExportDeclaration(node); + case 256 /* NamedExports */: + return emitNamedExports(node); + case 257 /* ExportSpecifier */: + return emitExportSpecifier(node); + case 258 /* MissingDeclaration */: + return; + // Module references + case 259 /* ExternalModuleReference */: + return emitExternalModuleReference(node); + // JSX (non-expression) + case 11 /* JsxText */: + return emitJsxText(node); + case 262 /* JsxOpeningElement */: + case 265 /* JsxOpeningFragment */: + return emitJsxOpeningElementOrFragment(node); + case 263 /* JsxClosingElement */: + case 266 /* JsxClosingFragment */: + return emitJsxClosingElementOrFragment(node); + case 267 /* JsxAttribute */: + return emitJsxAttribute(node); + case 268 /* JsxAttributes */: + return emitJsxAttributes(node); + case 269 /* JsxSpreadAttribute */: + return emitJsxSpreadAttribute(node); + case 270 /* JsxExpression */: + return emitJsxExpression(node); + // Clauses + case 271 /* CaseClause */: + return emitCaseClause(node); + case 272 /* DefaultClause */: + return emitDefaultClause(node); + case 273 /* HeritageClause */: + return emitHeritageClause(node); + case 274 /* CatchClause */: + return emitCatchClause(node); + // Property assignments + case 275 /* PropertyAssignment */: + return emitPropertyAssignment(node); + case 276 /* ShorthandPropertyAssignment */: + return emitShorthandPropertyAssignment(node); + case 277 /* SpreadAssignment */: + return emitSpreadAssignment(node); + // Enum + case 278 /* EnumMember */: + return emitEnumMember(node); + // JSDoc nodes (only used in codefixes currently) + case 299 /* JSDocParameterTag */: + case 305 /* JSDocPropertyTag */: + return emitJSDocPropertyLikeTag(node); + case 300 /* JSDocReturnTag */: + case 302 /* JSDocTypeTag */: + case 301 /* JSDocThisTag */: + case 298 /* JSDocEnumTag */: + return emitJSDocSimpleTypedTag(node); + case 295 /* JSDocAugmentsTag */: + return emitJSDocAugmentsTag(node); + case 303 /* JSDocTemplateTag */: + return emitJSDocTemplateTag(node); + case 304 /* JSDocTypedefTag */: + return emitJSDocTypedefTag(node); + case 297 /* JSDocCallbackTag */: + return emitJSDocCallbackTag(node); + case 293 /* JSDocSignature */: + return emitJSDocSignature(node); + case 292 /* JSDocTypeLiteral */: + return emitJSDocTypeLiteral(node); + case 296 /* JSDocClassTag */: + case 294 /* JSDocTag */: + return emitJSDocSimpleTag(node); + case 291 /* JSDocComment */: + return emitJSDoc(node); + // Transformation nodes (ignored) + } + if (ts.isExpression(node)) { + hint = 1 /* Expression */; + if (substituteNode !== ts.noEmitSubstitution) { + node = substituteNode(hint, node); + } + } + else if (ts.isToken(node)) { + return writeTokenNode(node, writePunctuation); + } + } + if (hint === 1 /* Expression */) { + switch (node.kind) { + // Literals + case 8 /* NumericLiteral */: + case 9 /* BigIntLiteral */: + return emitNumericOrBigIntLiteral(node); + case 10 /* StringLiteral */: + case 13 /* RegularExpressionLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: + return emitLiteral(node); + // Identifiers + case 72 /* Identifier */: + return emitIdentifier(node); + // Reserved words + case 87 /* FalseKeyword */: + case 96 /* NullKeyword */: + case 98 /* SuperKeyword */: + case 102 /* TrueKeyword */: + case 100 /* ThisKeyword */: + case 92 /* ImportKeyword */: + writeTokenNode(node, writeKeyword); + return; + // Expressions + case 187 /* ArrayLiteralExpression */: + return emitArrayLiteralExpression(node); + case 188 /* ObjectLiteralExpression */: + return emitObjectLiteralExpression(node); + case 189 /* PropertyAccessExpression */: + return emitPropertyAccessExpression(node); + case 190 /* ElementAccessExpression */: + return emitElementAccessExpression(node); + case 191 /* CallExpression */: + return emitCallExpression(node); + case 192 /* NewExpression */: + return emitNewExpression(node); + case 193 /* TaggedTemplateExpression */: + return emitTaggedTemplateExpression(node); + case 194 /* TypeAssertionExpression */: + return emitTypeAssertionExpression(node); + case 195 /* ParenthesizedExpression */: + return emitParenthesizedExpression(node); + case 196 /* FunctionExpression */: + return emitFunctionExpression(node); + case 197 /* ArrowFunction */: + return emitArrowFunction(node); + case 198 /* DeleteExpression */: + return emitDeleteExpression(node); + case 199 /* TypeOfExpression */: + return emitTypeOfExpression(node); + case 200 /* VoidExpression */: + return emitVoidExpression(node); + case 201 /* AwaitExpression */: + return emitAwaitExpression(node); + case 202 /* PrefixUnaryExpression */: + return emitPrefixUnaryExpression(node); + case 203 /* PostfixUnaryExpression */: + return emitPostfixUnaryExpression(node); + case 204 /* BinaryExpression */: + return emitBinaryExpression(node); + case 205 /* ConditionalExpression */: + return emitConditionalExpression(node); + case 206 /* TemplateExpression */: + return emitTemplateExpression(node); + case 207 /* YieldExpression */: + return emitYieldExpression(node); + case 208 /* SpreadElement */: + return emitSpreadExpression(node); + case 209 /* ClassExpression */: + return emitClassExpression(node); + case 210 /* OmittedExpression */: + return; + case 212 /* AsExpression */: + return emitAsExpression(node); + case 213 /* NonNullExpression */: + return emitNonNullExpression(node); + case 214 /* MetaProperty */: + return emitMetaProperty(node); + // JSX + case 260 /* JsxElement */: + return emitJsxElement(node); + case 261 /* JsxSelfClosingElement */: + return emitJsxSelfClosingElement(node); + case 264 /* JsxFragment */: + return emitJsxFragment(node); + // Transformation nodes + case 308 /* PartiallyEmittedExpression */: + return emitPartiallyEmittedExpression(node); + case 309 /* CommaListExpression */: + return emitCommaList(node); + } + } + } + function emitMappedTypeParameter(node) { + emit(node.name); + writeSpace(); + writeKeyword("in"); + writeSpace(); + emit(node.constraint); + } + function pipelineEmitWithSubstitution(hint, node) { + var pipelinePhase = getNextPipelinePhase(1 /* Substitution */, node); + pipelinePhase(hint, substituteNode(hint, node)); + } + function emitHelpers(node) { + var helpersEmitted = false; + var bundle = node.kind === 280 /* Bundle */ ? node : undefined; + if (bundle && moduleKind === ts.ModuleKind.None) { + return; + } + var numNodes = bundle ? bundle.sourceFiles.length : 1; + for (var i = 0; i < numNodes; i++) { + var currentNode = bundle ? bundle.sourceFiles[i] : node; + var sourceFile = ts.isSourceFile(currentNode) ? currentNode : currentSourceFile; + var shouldSkip = printerOptions.noEmitHelpers || ts.getExternalHelpersModuleName(sourceFile) !== undefined; + var shouldBundle = ts.isSourceFile(currentNode) && !isOwnFileEmit; + var helpers = ts.getEmitHelpers(currentNode); + if (helpers) { + for (var _a = 0, _b = ts.stableSort(helpers, ts.compareEmitHelpers); _a < _b.length; _a++) { + var helper = _b[_a]; + if (!helper.scoped) { + // Skip the helper if it can be skipped and the noEmitHelpers compiler + // option is set, or if it can be imported and the importHelpers compiler + // option is set. + if (shouldSkip) + continue; + // Skip the helper if it can be bundled but hasn't already been emitted and we + // are emitting a bundled module. + if (shouldBundle) { + if (bundledHelpers.get(helper.name)) { + continue; + } + bundledHelpers.set(helper.name, true); + } + } + else if (bundle) { + // Skip the helper if it is scoped and we are emitting bundled helpers + continue; + } + if (typeof helper.text === "string") { + writeLines(helper.text); + } + else { + writeLines(helper.text(makeFileLevelOptimisticUniqueName)); + } + helpersEmitted = true; + } + } + } + return helpersEmitted; + } + // + // Literals/Pseudo-literals + // + // SyntaxKind.NumericLiteral + // SyntaxKind.BigIntLiteral + function emitNumericOrBigIntLiteral(node) { + emitLiteral(node); + } + // SyntaxKind.StringLiteral + // SyntaxKind.RegularExpressionLiteral + // SyntaxKind.NoSubstitutionTemplateLiteral + // SyntaxKind.TemplateHead + // SyntaxKind.TemplateMiddle + // SyntaxKind.TemplateTail + function emitLiteral(node) { + var text = getLiteralTextOfNode(node, printerOptions.neverAsciiEscape); + if ((printerOptions.sourceMap || printerOptions.inlineSourceMap) + && (node.kind === 10 /* StringLiteral */ || ts.isTemplateLiteralKind(node.kind))) { + writeLiteral(text); + } + else { + // Quick info expects all literals to be called with writeStringLiteral, as there's no specific type for numberLiterals + writeStringLiteral(text); + } + } + // SyntaxKind.UnparsedSource + function emitUnparsedSource(unparsed) { + writer.rawWrite(unparsed.text); + } + // + // Identifiers + // + function emitIdentifier(node) { + var writeText = node.symbol ? writeSymbol : write; + writeText(getTextOfNode(node, /*includeTrivia*/ false), node.symbol); + emitList(node, node.typeArguments, 53776 /* TypeParameters */); // Call emitList directly since it could be an array of TypeParameterDeclarations _or_ type arguments + } + // + // Names + // + function emitQualifiedName(node) { + emitEntityName(node.left); + writePunctuation("."); + emit(node.right); + } + function emitEntityName(node) { + if (node.kind === 72 /* Identifier */) { + emitExpression(node); + } + else { + emit(node); + } + } + function emitComputedPropertyName(node) { + writePunctuation("["); + emitExpression(node.expression); + writePunctuation("]"); + } + // + // Signature elements + // + function emitTypeParameter(node) { + emit(node.name); + if (node.constraint) { + writeSpace(); + writeKeyword("extends"); + writeSpace(); + emit(node.constraint); + } + if (node.default) { + writeSpace(); + writeOperator("="); + writeSpace(); + emit(node.default); + } + } + function emitParameter(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + emit(node.dotDotDotToken); + emitNodeWithWriter(node.name, writeParameter); + emit(node.questionToken); + if (node.parent && node.parent.kind === 289 /* JSDocFunctionType */ && !node.name) { + emit(node.type); + } + else { + emitTypeAnnotation(node.type); + } + // The comment position has to fallback to any present node within the parameterdeclaration because as it turns out, the parser can make parameter declarations with _just_ an initializer. + emitInitializer(node.initializer, node.type ? node.type.end : node.questionToken ? node.questionToken.end : node.name ? node.name.end : node.modifiers ? node.modifiers.end : node.decorators ? node.decorators.end : node.pos, node); + } + function emitDecorator(decorator) { + writePunctuation("@"); + emitExpression(decorator.expression); + } + // + // Type members + // + function emitPropertySignature(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + emitNodeWithWriter(node.name, writeProperty); + emit(node.questionToken); + emitTypeAnnotation(node.type); + writeTrailingSemicolon(); + } + function emitPropertyDeclaration(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + emit(node.name); + emit(node.questionToken); + emit(node.exclamationToken); + emitTypeAnnotation(node.type); + emitInitializer(node.initializer, node.type ? node.type.end : node.questionToken ? node.questionToken.end : node.name.end, node); + writeTrailingSemicolon(); + } + function emitMethodSignature(node) { + pushNameGenerationScope(node); + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + emit(node.name); + emit(node.questionToken); + emitTypeParameters(node, node.typeParameters); + emitParameters(node, node.parameters); + emitTypeAnnotation(node.type); + writeTrailingSemicolon(); + popNameGenerationScope(node); + } + function emitMethodDeclaration(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + emit(node.asteriskToken); + emit(node.name); + emit(node.questionToken); + emitSignatureAndBody(node, emitSignatureHead); + } + function emitConstructor(node) { + emitModifiers(node, node.modifiers); + writeKeyword("constructor"); + emitSignatureAndBody(node, emitSignatureHead); + } + function emitAccessorDeclaration(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + writeKeyword(node.kind === 158 /* GetAccessor */ ? "get" : "set"); + writeSpace(); + emit(node.name); + emitSignatureAndBody(node, emitSignatureHead); + } + function emitCallSignature(node) { + pushNameGenerationScope(node); + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + emitTypeParameters(node, node.typeParameters); + emitParameters(node, node.parameters); + emitTypeAnnotation(node.type); + writeTrailingSemicolon(); + popNameGenerationScope(node); + } + function emitConstructSignature(node) { + pushNameGenerationScope(node); + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + writeKeyword("new"); + writeSpace(); + emitTypeParameters(node, node.typeParameters); + emitParameters(node, node.parameters); + emitTypeAnnotation(node.type); + writeTrailingSemicolon(); + popNameGenerationScope(node); + } + function emitIndexSignature(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + emitParametersForIndexSignature(node, node.parameters); + emitTypeAnnotation(node.type); + writeTrailingSemicolon(); + } + function emitSemicolonClassElement() { + writeTrailingSemicolon(); + } + // + // Types + // + function emitTypePredicate(node) { + emit(node.parameterName); + writeSpace(); + writeKeyword("is"); + writeSpace(); + emit(node.type); + } + function emitTypeReference(node) { + emit(node.typeName); + emitTypeArguments(node, node.typeArguments); + } + function emitFunctionType(node) { + pushNameGenerationScope(node); + emitTypeParameters(node, node.typeParameters); + emitParametersForArrow(node, node.parameters); + writeSpace(); + writePunctuation("=>"); + writeSpace(); + emit(node.type); + popNameGenerationScope(node); + } + function emitJSDocFunctionType(node) { + writeKeyword("function"); + emitParameters(node, node.parameters); + writePunctuation(":"); + emit(node.type); + } + function emitJSDocNullableType(node) { + writePunctuation("?"); + emit(node.type); + } + function emitJSDocNonNullableType(node) { + writePunctuation("!"); + emit(node.type); + } + function emitJSDocOptionalType(node) { + emit(node.type); + writePunctuation("="); + } + function emitConstructorType(node) { + pushNameGenerationScope(node); + writeKeyword("new"); + writeSpace(); + emitTypeParameters(node, node.typeParameters); + emitParameters(node, node.parameters); + writeSpace(); + writePunctuation("=>"); + writeSpace(); + emit(node.type); + popNameGenerationScope(node); + } + function emitTypeQuery(node) { + writeKeyword("typeof"); + writeSpace(); + emit(node.exprName); + } + function emitTypeLiteral(node) { + writePunctuation("{"); + var flags = ts.getEmitFlags(node) & 1 /* SingleLine */ ? 768 /* SingleLineTypeLiteralMembers */ : 32897 /* MultiLineTypeLiteralMembers */; + emitList(node, node.members, flags | 524288 /* NoSpaceIfEmpty */); + writePunctuation("}"); + } + function emitArrayType(node) { + emit(node.elementType); + writePunctuation("["); + writePunctuation("]"); + } + function emitRestOrJSDocVariadicType(node) { + writePunctuation("..."); + emit(node.type); + } + function emitTupleType(node) { + writePunctuation("["); + emitList(node, node.elementTypes, 528 /* TupleTypeElements */); + writePunctuation("]"); + } + function emitOptionalType(node) { + emit(node.type); + writePunctuation("?"); + } + function emitUnionType(node) { + emitList(node, node.types, 516 /* UnionTypeConstituents */); + } + function emitIntersectionType(node) { + emitList(node, node.types, 520 /* IntersectionTypeConstituents */); + } + function emitConditionalType(node) { + emit(node.checkType); + writeSpace(); + writeKeyword("extends"); + writeSpace(); + emit(node.extendsType); + writeSpace(); + writePunctuation("?"); + writeSpace(); + emit(node.trueType); + writeSpace(); + writePunctuation(":"); + writeSpace(); + emit(node.falseType); + } + function emitInferType(node) { + writeKeyword("infer"); + writeSpace(); + emit(node.typeParameter); + } + function emitParenthesizedType(node) { + writePunctuation("("); + emit(node.type); + writePunctuation(")"); + } + function emitThisType() { + writeKeyword("this"); + } + function emitTypeOperator(node) { + writeTokenText(node.operator, writeKeyword); + writeSpace(); + emit(node.type); + } + function emitIndexedAccessType(node) { + emit(node.objectType); + writePunctuation("["); + emit(node.indexType); + writePunctuation("]"); + } + function emitMappedType(node) { + var emitFlags = ts.getEmitFlags(node); + writePunctuation("{"); + if (emitFlags & 1 /* SingleLine */) { + writeSpace(); + } + else { + writeLine(); + increaseIndent(); + } + if (node.readonlyToken) { + emit(node.readonlyToken); + if (node.readonlyToken.kind !== 133 /* ReadonlyKeyword */) { + writeKeyword("readonly"); + } + writeSpace(); + } + writePunctuation("["); + var pipelinePhase = getPipelinePhase(0 /* Notification */, node.typeParameter); + pipelinePhase(3 /* MappedTypeParameter */, node.typeParameter); + writePunctuation("]"); + if (node.questionToken) { + emit(node.questionToken); + if (node.questionToken.kind !== 56 /* QuestionToken */) { + writePunctuation("?"); + } + } + writePunctuation(":"); + writeSpace(); + emit(node.type); + writeTrailingSemicolon(); + if (emitFlags & 1 /* SingleLine */) { + writeSpace(); + } + else { + writeLine(); + decreaseIndent(); + } + writePunctuation("}"); + } + function emitLiteralType(node) { + emitExpression(node.literal); + } + function emitImportTypeNode(node) { + if (node.isTypeOf) { + writeKeyword("typeof"); + writeSpace(); + } + writeKeyword("import"); + writePunctuation("("); + emit(node.argument); + writePunctuation(")"); + if (node.qualifier) { + writePunctuation("."); + emit(node.qualifier); + } + emitTypeArguments(node, node.typeArguments); + } + // + // Binding patterns + // + function emitObjectBindingPattern(node) { + writePunctuation("{"); + emitList(node, node.elements, 525136 /* ObjectBindingPatternElements */); + writePunctuation("}"); + } + function emitArrayBindingPattern(node) { + writePunctuation("["); + emitList(node, node.elements, 524880 /* ArrayBindingPatternElements */); + writePunctuation("]"); + } + function emitBindingElement(node) { + emit(node.dotDotDotToken); + if (node.propertyName) { + emit(node.propertyName); + writePunctuation(":"); + writeSpace(); + } + emit(node.name); + emitInitializer(node.initializer, node.name.end, node); + } + // + // Expressions + // + function emitArrayLiteralExpression(node) { + var elements = node.elements; + var preferNewLine = node.multiLine ? 65536 /* PreferNewLine */ : 0 /* None */; + emitExpressionList(node, elements, 8914 /* ArrayLiteralExpressionElements */ | preferNewLine); + } + function emitObjectLiteralExpression(node) { + ts.forEach(node.properties, generateMemberNames); + var indentedFlag = ts.getEmitFlags(node) & 65536 /* Indented */; + if (indentedFlag) { + increaseIndent(); + } + var preferNewLine = node.multiLine ? 65536 /* PreferNewLine */ : 0 /* None */; + var allowTrailingComma = currentSourceFile.languageVersion >= 1 /* ES5 */ && !ts.isJsonSourceFile(currentSourceFile) ? 64 /* AllowTrailingComma */ : 0 /* None */; + emitList(node, node.properties, 526226 /* ObjectLiteralExpressionProperties */ | allowTrailingComma | preferNewLine); + if (indentedFlag) { + decreaseIndent(); + } + } + function emitPropertyAccessExpression(node) { + var indentBeforeDot = false; + var indentAfterDot = false; + if (!(ts.getEmitFlags(node) & 131072 /* NoIndentation */)) { + var dotRangeStart = node.expression.end; + var dotRangeEnd = ts.skipTrivia(currentSourceFile.text, node.expression.end) + 1; + var dotToken = ts.createToken(24 /* DotToken */); + dotToken.pos = dotRangeStart; + dotToken.end = dotRangeEnd; + indentBeforeDot = needsIndentation(node, node.expression, dotToken); + indentAfterDot = needsIndentation(node, dotToken, node.name); + } + emitExpression(node.expression); + increaseIndentIf(indentBeforeDot, /*writeSpaceIfNotIndenting*/ false); + var shouldEmitDotDot = !indentBeforeDot && needsDotDotForPropertyAccess(node.expression); + if (shouldEmitDotDot) { + writePunctuation("."); + } + emitTokenWithComment(24 /* DotToken */, node.expression.end, writePunctuation, node); + increaseIndentIf(indentAfterDot, /*writeSpaceIfNotIndenting*/ false); + emit(node.name); + decreaseIndentIf(indentBeforeDot, indentAfterDot); + } + // 1..toString is a valid property access, emit a dot after the literal + // Also emit a dot if expression is a integer const enum value - it will appear in generated code as numeric literal + function needsDotDotForPropertyAccess(expression) { + expression = ts.skipPartiallyEmittedExpressions(expression); + if (ts.isNumericLiteral(expression)) { + // check if numeric literal is a decimal literal that was originally written with a dot + var text = getLiteralTextOfNode(expression, /*neverAsciiEscape*/ true); + return !expression.numericLiteralFlags + && !ts.stringContains(text, ts.tokenToString(24 /* DotToken */)); + } + else if (ts.isPropertyAccessExpression(expression) || ts.isElementAccessExpression(expression)) { + // check if constant enum value is integer + var constantValue = ts.getConstantValue(expression); + // isFinite handles cases when constantValue is undefined + return typeof constantValue === "number" && isFinite(constantValue) + && Math.floor(constantValue) === constantValue + && printerOptions.removeComments; + } + } + function emitElementAccessExpression(node) { + emitExpression(node.expression); + emitTokenWithComment(22 /* OpenBracketToken */, node.expression.end, writePunctuation, node); + emitExpression(node.argumentExpression); + emitTokenWithComment(23 /* CloseBracketToken */, node.argumentExpression.end, writePunctuation, node); + } + function emitCallExpression(node) { + emitExpression(node.expression); + emitTypeArguments(node, node.typeArguments); + emitExpressionList(node, node.arguments, 2576 /* CallExpressionArguments */); + } + function emitNewExpression(node) { + emitTokenWithComment(95 /* NewKeyword */, node.pos, writeKeyword, node); + writeSpace(); + emitExpression(node.expression); + emitTypeArguments(node, node.typeArguments); + emitExpressionList(node, node.arguments, 18960 /* NewExpressionArguments */); + } + function emitTaggedTemplateExpression(node) { + emitExpression(node.tag); + emitTypeArguments(node, node.typeArguments); + writeSpace(); + emitExpression(node.template); + } + function emitTypeAssertionExpression(node) { + writePunctuation("<"); + emit(node.type); + writePunctuation(">"); + emitExpression(node.expression); + } + function emitParenthesizedExpression(node) { + var openParenPos = emitTokenWithComment(20 /* OpenParenToken */, node.pos, writePunctuation, node); + emitExpression(node.expression); + emitTokenWithComment(21 /* CloseParenToken */, node.expression ? node.expression.end : openParenPos, writePunctuation, node); + } + function emitFunctionExpression(node) { + generateNameIfNeeded(node.name); + emitFunctionDeclarationOrExpression(node); + } + function emitArrowFunction(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + emitSignatureAndBody(node, emitArrowFunctionHead); + } + function emitArrowFunctionHead(node) { + emitTypeParameters(node, node.typeParameters); + emitParametersForArrow(node, node.parameters); + emitTypeAnnotation(node.type); + writeSpace(); + emit(node.equalsGreaterThanToken); + } + function emitDeleteExpression(node) { + emitTokenWithComment(81 /* DeleteKeyword */, node.pos, writeKeyword, node); + writeSpace(); + emitExpression(node.expression); + } + function emitTypeOfExpression(node) { + emitTokenWithComment(104 /* TypeOfKeyword */, node.pos, writeKeyword, node); + writeSpace(); + emitExpression(node.expression); + } + function emitVoidExpression(node) { + emitTokenWithComment(106 /* VoidKeyword */, node.pos, writeKeyword, node); + writeSpace(); + emitExpression(node.expression); + } + function emitAwaitExpression(node) { + emitTokenWithComment(122 /* AwaitKeyword */, node.pos, writeKeyword, node); + writeSpace(); + emitExpression(node.expression); + } + function emitPrefixUnaryExpression(node) { + writeTokenText(node.operator, writeOperator); + if (shouldEmitWhitespaceBeforeOperand(node)) { + writeSpace(); + } + emitExpression(node.operand); + } + function shouldEmitWhitespaceBeforeOperand(node) { + // In some cases, we need to emit a space between the operator and the operand. One obvious case + // is when the operator is an identifier, like delete or typeof. We also need to do this for plus + // and minus expressions in certain cases. Specifically, consider the following two cases (parens + // are just for clarity of exposition, and not part of the source code): + // + // (+(+1)) + // (+(++1)) + // + // We need to emit a space in both cases. In the first case, the absence of a space will make + // the resulting expression a prefix increment operation. And in the second, it will make the resulting + // expression a prefix increment whose operand is a plus expression - (++(+x)) + // The same is true of minus of course. + var operand = node.operand; + return operand.kind === 202 /* PrefixUnaryExpression */ + && ((node.operator === 38 /* PlusToken */ && (operand.operator === 38 /* PlusToken */ || operand.operator === 44 /* PlusPlusToken */)) + || (node.operator === 39 /* MinusToken */ && (operand.operator === 39 /* MinusToken */ || operand.operator === 45 /* MinusMinusToken */))); + } + function emitPostfixUnaryExpression(node) { + emitExpression(node.operand); + writeTokenText(node.operator, writeOperator); + } + function emitBinaryExpression(node) { + var isCommaOperator = node.operatorToken.kind !== 27 /* CommaToken */; + var indentBeforeOperator = needsIndentation(node, node.left, node.operatorToken); + var indentAfterOperator = needsIndentation(node, node.operatorToken, node.right); + emitExpression(node.left); + increaseIndentIf(indentBeforeOperator, isCommaOperator); + emitLeadingCommentsOfPosition(node.operatorToken.pos); + writeTokenNode(node.operatorToken, node.operatorToken.kind === 93 /* InKeyword */ ? writeKeyword : writeOperator); + emitTrailingCommentsOfPosition(node.operatorToken.end, /*prefixSpace*/ true); // Binary operators should have a space before the comment starts + increaseIndentIf(indentAfterOperator, /*writeSpaceIfNotIndenting*/ true); + emitExpression(node.right); + decreaseIndentIf(indentBeforeOperator, indentAfterOperator); + } + function emitConditionalExpression(node) { + var indentBeforeQuestion = needsIndentation(node, node.condition, node.questionToken); + var indentAfterQuestion = needsIndentation(node, node.questionToken, node.whenTrue); + var indentBeforeColon = needsIndentation(node, node.whenTrue, node.colonToken); + var indentAfterColon = needsIndentation(node, node.colonToken, node.whenFalse); + emitExpression(node.condition); + increaseIndentIf(indentBeforeQuestion, /*writeSpaceIfNotIndenting*/ true); + emit(node.questionToken); + increaseIndentIf(indentAfterQuestion, /*writeSpaceIfNotIndenting*/ true); + emitExpression(node.whenTrue); + decreaseIndentIf(indentBeforeQuestion, indentAfterQuestion); + increaseIndentIf(indentBeforeColon, /*writeSpaceIfNotIndenting*/ true); + emit(node.colonToken); + increaseIndentIf(indentAfterColon, /*writeSpaceIfNotIndenting*/ true); + emitExpression(node.whenFalse); + decreaseIndentIf(indentBeforeColon, indentAfterColon); + } + function emitTemplateExpression(node) { + emit(node.head); + emitList(node, node.templateSpans, 262144 /* TemplateExpressionSpans */); + } + function emitYieldExpression(node) { + emitTokenWithComment(117 /* YieldKeyword */, node.pos, writeKeyword, node); + emit(node.asteriskToken); + emitExpressionWithLeadingSpace(node.expression); + } + function emitSpreadExpression(node) { + emitTokenWithComment(25 /* DotDotDotToken */, node.pos, writePunctuation, node); + emitExpression(node.expression); + } + function emitClassExpression(node) { + generateNameIfNeeded(node.name); + emitClassDeclarationOrExpression(node); + } + function emitExpressionWithTypeArguments(node) { + emitExpression(node.expression); + emitTypeArguments(node, node.typeArguments); + } + function emitAsExpression(node) { + emitExpression(node.expression); + if (node.type) { + writeSpace(); + writeKeyword("as"); + writeSpace(); + emit(node.type); + } + } + function emitNonNullExpression(node) { + emitExpression(node.expression); + writeOperator("!"); + } + function emitMetaProperty(node) { + writeToken(node.keywordToken, node.pos, writePunctuation); + writePunctuation("."); + emit(node.name); + } + // + // Misc + // + function emitTemplateSpan(node) { + emitExpression(node.expression); + emit(node.literal); + } + // + // Statements + // + function emitBlock(node) { + emitBlockStatements(node, /*forceSingleLine*/ !node.multiLine && isEmptyBlock(node)); + } + function emitBlockStatements(node, forceSingleLine) { + emitTokenWithComment(18 /* OpenBraceToken */, node.pos, writePunctuation, /*contextNode*/ node); + var format = forceSingleLine || ts.getEmitFlags(node) & 1 /* SingleLine */ ? 768 /* SingleLineBlockStatements */ : 129 /* MultiLineBlockStatements */; + emitList(node, node.statements, format); + emitTokenWithComment(19 /* CloseBraceToken */, node.statements.end, writePunctuation, /*contextNode*/ node, /*indentLeading*/ !!(format & 1 /* MultiLine */)); + } + function emitVariableStatement(node) { + emitModifiers(node, node.modifiers); + emit(node.declarationList); + writeTrailingSemicolon(); + } + function emitEmptyStatement(isEmbeddedStatement) { + // While most trailing semicolons are possibly insignificant, an embedded "empty" + // statement is significant and cannot be elided by a trailing-semicolon-omitting writer. + if (isEmbeddedStatement) { + writePunctuation(";"); + } + else { + writeTrailingSemicolon(); + } + } + function emitExpressionStatement(node) { + emitExpression(node.expression); + // Emit semicolon in non json files + // or if json file that created synthesized expression(eg.define expression statement when --out and amd code generation) + if (!ts.isJsonSourceFile(currentSourceFile) || ts.nodeIsSynthesized(node.expression)) { + writeTrailingSemicolon(); + } + } + function emitIfStatement(node) { + var openParenPos = emitTokenWithComment(91 /* IfKeyword */, node.pos, writeKeyword, node); + writeSpace(); + emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node); + emitExpression(node.expression); + emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node); + emitEmbeddedStatement(node, node.thenStatement); + if (node.elseStatement) { + writeLineOrSpace(node); + emitTokenWithComment(83 /* ElseKeyword */, node.thenStatement.end, writeKeyword, node); + if (node.elseStatement.kind === 222 /* IfStatement */) { + writeSpace(); + emit(node.elseStatement); + } + else { + emitEmbeddedStatement(node, node.elseStatement); + } + } + } + function emitWhileClause(node, startPos) { + var openParenPos = emitTokenWithComment(107 /* WhileKeyword */, startPos, writeKeyword, node); + writeSpace(); + emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node); + emitExpression(node.expression); + emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node); + } + function emitDoStatement(node) { + emitTokenWithComment(82 /* DoKeyword */, node.pos, writeKeyword, node); + emitEmbeddedStatement(node, node.statement); + if (ts.isBlock(node.statement)) { + writeSpace(); + } + else { + writeLineOrSpace(node); + } + emitWhileClause(node, node.statement.end); + writePunctuation(";"); + } + function emitWhileStatement(node) { + emitWhileClause(node, node.pos); + emitEmbeddedStatement(node, node.statement); + } + function emitForStatement(node) { + var openParenPos = emitTokenWithComment(89 /* ForKeyword */, node.pos, writeKeyword, node); + writeSpace(); + var pos = emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, /*contextNode*/ node); + emitForBinding(node.initializer); + pos = emitTokenWithComment(26 /* SemicolonToken */, node.initializer ? node.initializer.end : pos, writePunctuation, node); + emitExpressionWithLeadingSpace(node.condition); + pos = emitTokenWithComment(26 /* SemicolonToken */, node.condition ? node.condition.end : pos, writePunctuation, node); + emitExpressionWithLeadingSpace(node.incrementor); + emitTokenWithComment(21 /* CloseParenToken */, node.incrementor ? node.incrementor.end : pos, writePunctuation, node); + emitEmbeddedStatement(node, node.statement); + } + function emitForInStatement(node) { + var openParenPos = emitTokenWithComment(89 /* ForKeyword */, node.pos, writeKeyword, node); + writeSpace(); + emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node); + emitForBinding(node.initializer); + writeSpace(); + emitTokenWithComment(93 /* InKeyword */, node.initializer.end, writeKeyword, node); + writeSpace(); + emitExpression(node.expression); + emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node); + emitEmbeddedStatement(node, node.statement); + } + function emitForOfStatement(node) { + var openParenPos = emitTokenWithComment(89 /* ForKeyword */, node.pos, writeKeyword, node); + writeSpace(); + emitWithTrailingSpace(node.awaitModifier); + emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node); + emitForBinding(node.initializer); + writeSpace(); + emitTokenWithComment(147 /* OfKeyword */, node.initializer.end, writeKeyword, node); + writeSpace(); + emitExpression(node.expression); + emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node); + emitEmbeddedStatement(node, node.statement); + } + function emitForBinding(node) { + if (node !== undefined) { + if (node.kind === 238 /* VariableDeclarationList */) { + emit(node); + } + else { + emitExpression(node); + } + } + } + function emitContinueStatement(node) { + emitTokenWithComment(78 /* ContinueKeyword */, node.pos, writeKeyword, node); + emitWithLeadingSpace(node.label); + writeTrailingSemicolon(); + } + function emitBreakStatement(node) { + emitTokenWithComment(73 /* BreakKeyword */, node.pos, writeKeyword, node); + emitWithLeadingSpace(node.label); + writeTrailingSemicolon(); + } + function emitTokenWithComment(token, pos, writer, contextNode, indentLeading) { + var node = ts.getParseTreeNode(contextNode); + var isSimilarNode = node && node.kind === contextNode.kind; + var startPos = pos; + if (isSimilarNode) { + pos = ts.skipTrivia(currentSourceFile.text, pos); + } + if (emitLeadingCommentsOfPosition && isSimilarNode && contextNode.pos !== startPos) { + var needsIndent = indentLeading && !ts.positionsAreOnSameLine(startPos, pos, currentSourceFile); + if (needsIndent) { + increaseIndent(); + } + emitLeadingCommentsOfPosition(startPos); + if (needsIndent) { + decreaseIndent(); + } + } + pos = writeTokenText(token, writer, pos); + if (emitTrailingCommentsOfPosition && isSimilarNode && contextNode.end !== pos) { + emitTrailingCommentsOfPosition(pos, /*prefixSpace*/ true); + } + return pos; + } + function emitReturnStatement(node) { + emitTokenWithComment(97 /* ReturnKeyword */, node.pos, writeKeyword, /*contextNode*/ node); + emitExpressionWithLeadingSpace(node.expression); + writeTrailingSemicolon(); + } + function emitWithStatement(node) { + var openParenPos = emitTokenWithComment(108 /* WithKeyword */, node.pos, writeKeyword, node); + writeSpace(); + emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node); + emitExpression(node.expression); + emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node); + emitEmbeddedStatement(node, node.statement); + } + function emitSwitchStatement(node) { + var openParenPos = emitTokenWithComment(99 /* SwitchKeyword */, node.pos, writeKeyword, node); + writeSpace(); + emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node); + emitExpression(node.expression); + emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node); + writeSpace(); + emit(node.caseBlock); + } + function emitLabeledStatement(node) { + emit(node.label); + emitTokenWithComment(57 /* ColonToken */, node.label.end, writePunctuation, node); + writeSpace(); + emit(node.statement); + } + function emitThrowStatement(node) { + emitTokenWithComment(101 /* ThrowKeyword */, node.pos, writeKeyword, node); + emitExpressionWithLeadingSpace(node.expression); + writeTrailingSemicolon(); + } + function emitTryStatement(node) { + emitTokenWithComment(103 /* TryKeyword */, node.pos, writeKeyword, node); + writeSpace(); + emit(node.tryBlock); + if (node.catchClause) { + writeLineOrSpace(node); + emit(node.catchClause); + } + if (node.finallyBlock) { + writeLineOrSpace(node); + emitTokenWithComment(88 /* FinallyKeyword */, (node.catchClause || node.tryBlock).end, writeKeyword, node); + writeSpace(); + emit(node.finallyBlock); + } + } + function emitDebuggerStatement(node) { + writeToken(79 /* DebuggerKeyword */, node.pos, writeKeyword); + writeTrailingSemicolon(); + } + // + // Declarations + // + function emitVariableDeclaration(node) { + emit(node.name); + emitTypeAnnotation(node.type); + emitInitializer(node.initializer, node.type ? node.type.end : node.name.end, node); + } + function emitVariableDeclarationList(node) { + writeKeyword(ts.isLet(node) ? "let" : ts.isVarConst(node) ? "const" : "var"); + writeSpace(); + emitList(node, node.declarations, 528 /* VariableDeclarationList */); + } + function emitFunctionDeclaration(node) { + emitFunctionDeclarationOrExpression(node); + } + function emitFunctionDeclarationOrExpression(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + writeKeyword("function"); + emit(node.asteriskToken); + writeSpace(); + emitIdentifierName(node.name); // TODO: GH#18217 + emitSignatureAndBody(node, emitSignatureHead); + } + function emitBlockCallback(_hint, body) { + emitBlockFunctionBody(body); + } + function emitSignatureAndBody(node, emitSignatureHead) { + var body = node.body; + if (body) { + if (ts.isBlock(body)) { + var indentedFlag = ts.getEmitFlags(node) & 65536 /* Indented */; + if (indentedFlag) { + increaseIndent(); + } + pushNameGenerationScope(node); + ts.forEach(node.parameters, generateNames); + generateNames(node.body); + emitSignatureHead(node); + if (onEmitNode) { + onEmitNode(4 /* Unspecified */, body, emitBlockCallback); + } + else { + emitBlockFunctionBody(body); + } + popNameGenerationScope(node); + if (indentedFlag) { + decreaseIndent(); + } + } + else { + emitSignatureHead(node); + writeSpace(); + emitExpression(body); + } + } + else { + emitSignatureHead(node); + writeTrailingSemicolon(); + } + } + function emitSignatureHead(node) { + emitTypeParameters(node, node.typeParameters); + emitParameters(node, node.parameters); + emitTypeAnnotation(node.type); + } + function shouldEmitBlockFunctionBodyOnSingleLine(body) { + // We must emit a function body as a single-line body in the following case: + // * The body has NodeEmitFlags.SingleLine specified. + // We must emit a function body as a multi-line body in the following cases: + // * The body is explicitly marked as multi-line. + // * A non-synthesized body's start and end position are on different lines. + // * Any statement in the body starts on a new line. + if (ts.getEmitFlags(body) & 1 /* SingleLine */) { + return true; + } + if (body.multiLine) { + return false; + } + if (!ts.nodeIsSynthesized(body) && !ts.rangeIsOnSingleLine(body, currentSourceFile)) { + return false; + } + if (shouldWriteLeadingLineTerminator(body, body.statements, 2 /* PreserveLines */) + || shouldWriteClosingLineTerminator(body, body.statements, 2 /* PreserveLines */)) { + return false; + } + var previousStatement; + for (var _a = 0, _b = body.statements; _a < _b.length; _a++) { + var statement = _b[_a]; + if (shouldWriteSeparatingLineTerminator(previousStatement, statement, 2 /* PreserveLines */)) { + return false; + } + previousStatement = statement; + } + return true; + } + function emitBlockFunctionBody(body) { + writeSpace(); + writePunctuation("{"); + increaseIndent(); + var emitBlockFunctionBody = shouldEmitBlockFunctionBodyOnSingleLine(body) + ? emitBlockFunctionBodyOnSingleLine + : emitBlockFunctionBodyWorker; + if (emitBodyWithDetachedComments) { + emitBodyWithDetachedComments(body, body.statements, emitBlockFunctionBody); + } + else { + emitBlockFunctionBody(body); + } + decreaseIndent(); + writeToken(19 /* CloseBraceToken */, body.statements.end, writePunctuation, body); + } + function emitBlockFunctionBodyOnSingleLine(body) { + emitBlockFunctionBodyWorker(body, /*emitBlockFunctionBodyOnSingleLine*/ true); + } + function emitBlockFunctionBodyWorker(body, emitBlockFunctionBodyOnSingleLine) { + // Emit all the prologue directives (like "use strict"). + var statementOffset = emitPrologueDirectives(body.statements, /*startWithNewLine*/ true); + var pos = writer.getTextPos(); + emitHelpers(body); + if (statementOffset === 0 && pos === writer.getTextPos() && emitBlockFunctionBodyOnSingleLine) { + decreaseIndent(); + emitList(body, body.statements, 768 /* SingleLineFunctionBodyStatements */); + increaseIndent(); + } + else { + emitList(body, body.statements, 1 /* MultiLineFunctionBodyStatements */, statementOffset); + } + } + function emitClassDeclaration(node) { + emitClassDeclarationOrExpression(node); + } + function emitClassDeclarationOrExpression(node) { + ts.forEach(node.members, generateMemberNames); + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + writeKeyword("class"); + if (node.name) { + writeSpace(); + emitIdentifierName(node.name); + } + var indentedFlag = ts.getEmitFlags(node) & 65536 /* Indented */; + if (indentedFlag) { + increaseIndent(); + } + emitTypeParameters(node, node.typeParameters); + emitList(node, node.heritageClauses, 0 /* ClassHeritageClauses */); + writeSpace(); + writePunctuation("{"); + emitList(node, node.members, 129 /* ClassMembers */); + writePunctuation("}"); + if (indentedFlag) { + decreaseIndent(); + } + } + function emitInterfaceDeclaration(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + writeKeyword("interface"); + writeSpace(); + emit(node.name); + emitTypeParameters(node, node.typeParameters); + emitList(node, node.heritageClauses, 512 /* HeritageClauses */); + writeSpace(); + writePunctuation("{"); + emitList(node, node.members, 129 /* InterfaceMembers */); + writePunctuation("}"); + } + function emitTypeAliasDeclaration(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + writeKeyword("type"); + writeSpace(); + emit(node.name); + emitTypeParameters(node, node.typeParameters); + writeSpace(); + writePunctuation("="); + writeSpace(); + emit(node.type); + writeTrailingSemicolon(); + } + function emitEnumDeclaration(node) { + emitModifiers(node, node.modifiers); + writeKeyword("enum"); + writeSpace(); + emit(node.name); + writeSpace(); + writePunctuation("{"); + emitList(node, node.members, 145 /* EnumMembers */); + writePunctuation("}"); + } + function emitModuleDeclaration(node) { + emitModifiers(node, node.modifiers); + if (~node.flags & 512 /* GlobalAugmentation */) { + writeKeyword(node.flags & 16 /* Namespace */ ? "namespace" : "module"); + writeSpace(); + } + emit(node.name); + var body = node.body; + if (!body) + return writeTrailingSemicolon(); + while (body.kind === 244 /* ModuleDeclaration */) { + writePunctuation("."); + emit(body.name); + body = body.body; + } + writeSpace(); + emit(body); + } + function emitModuleBlock(node) { + pushNameGenerationScope(node); + ts.forEach(node.statements, generateNames); + emitBlockStatements(node, /*forceSingleLine*/ isEmptyBlock(node)); + popNameGenerationScope(node); + } + function emitCaseBlock(node) { + emitTokenWithComment(18 /* OpenBraceToken */, node.pos, writePunctuation, node); + emitList(node, node.clauses, 129 /* CaseBlockClauses */); + emitTokenWithComment(19 /* CloseBraceToken */, node.clauses.end, writePunctuation, node, /*indentLeading*/ true); + } + function emitImportEqualsDeclaration(node) { + emitModifiers(node, node.modifiers); + emitTokenWithComment(92 /* ImportKeyword */, node.modifiers ? node.modifiers.end : node.pos, writeKeyword, node); + writeSpace(); + emit(node.name); + writeSpace(); + emitTokenWithComment(59 /* EqualsToken */, node.name.end, writePunctuation, node); + writeSpace(); + emitModuleReference(node.moduleReference); + writeTrailingSemicolon(); + } + function emitModuleReference(node) { + if (node.kind === 72 /* Identifier */) { + emitExpression(node); + } + else { + emit(node); + } + } + function emitImportDeclaration(node) { + emitModifiers(node, node.modifiers); + emitTokenWithComment(92 /* ImportKeyword */, node.modifiers ? node.modifiers.end : node.pos, writeKeyword, node); + writeSpace(); + if (node.importClause) { + emit(node.importClause); + writeSpace(); + emitTokenWithComment(144 /* FromKeyword */, node.importClause.end, writeKeyword, node); + writeSpace(); + } + emitExpression(node.moduleSpecifier); + writeTrailingSemicolon(); + } + function emitImportClause(node) { + emit(node.name); + if (node.name && node.namedBindings) { + emitTokenWithComment(27 /* CommaToken */, node.name.end, writePunctuation, node); + writeSpace(); + } + emit(node.namedBindings); + } + function emitNamespaceImport(node) { + var asPos = emitTokenWithComment(40 /* AsteriskToken */, node.pos, writePunctuation, node); + writeSpace(); + emitTokenWithComment(119 /* AsKeyword */, asPos, writeKeyword, node); + writeSpace(); + emit(node.name); + } + function emitNamedImports(node) { + emitNamedImportsOrExports(node); + } + function emitImportSpecifier(node) { + emitImportOrExportSpecifier(node); + } + function emitExportAssignment(node) { + var nextPos = emitTokenWithComment(85 /* ExportKeyword */, node.pos, writeKeyword, node); + writeSpace(); + if (node.isExportEquals) { + emitTokenWithComment(59 /* EqualsToken */, nextPos, writeOperator, node); + } + else { + emitTokenWithComment(80 /* DefaultKeyword */, nextPos, writeKeyword, node); + } + writeSpace(); + emitExpression(node.expression); + writeTrailingSemicolon(); + } + function emitExportDeclaration(node) { + var nextPos = emitTokenWithComment(85 /* ExportKeyword */, node.pos, writeKeyword, node); + writeSpace(); + if (node.exportClause) { + emit(node.exportClause); + } + else { + nextPos = emitTokenWithComment(40 /* AsteriskToken */, nextPos, writePunctuation, node); + } + if (node.moduleSpecifier) { + writeSpace(); + var fromPos = node.exportClause ? node.exportClause.end : nextPos; + emitTokenWithComment(144 /* FromKeyword */, fromPos, writeKeyword, node); + writeSpace(); + emitExpression(node.moduleSpecifier); + } + writeTrailingSemicolon(); + } + function emitNamespaceExportDeclaration(node) { + var nextPos = emitTokenWithComment(85 /* ExportKeyword */, node.pos, writeKeyword, node); + writeSpace(); + nextPos = emitTokenWithComment(119 /* AsKeyword */, nextPos, writeKeyword, node); + writeSpace(); + nextPos = emitTokenWithComment(131 /* NamespaceKeyword */, nextPos, writeKeyword, node); + writeSpace(); + emit(node.name); + writeTrailingSemicolon(); + } + function emitNamedExports(node) { + emitNamedImportsOrExports(node); + } + function emitExportSpecifier(node) { + emitImportOrExportSpecifier(node); + } + function emitNamedImportsOrExports(node) { + writePunctuation("{"); + emitList(node, node.elements, 525136 /* NamedImportsOrExportsElements */); + writePunctuation("}"); + } + function emitImportOrExportSpecifier(node) { + if (node.propertyName) { + emit(node.propertyName); + writeSpace(); + emitTokenWithComment(119 /* AsKeyword */, node.propertyName.end, writeKeyword, node); + writeSpace(); + } + emit(node.name); + } + // + // Module references + // + function emitExternalModuleReference(node) { + writeKeyword("require"); + writePunctuation("("); + emitExpression(node.expression); + writePunctuation(")"); + } + // + // JSX + // + function emitJsxElement(node) { + emit(node.openingElement); + emitList(node, node.children, 262144 /* JsxElementOrFragmentChildren */); + emit(node.closingElement); + } + function emitJsxSelfClosingElement(node) { + writePunctuation("<"); + emitJsxTagName(node.tagName); + writeSpace(); + emit(node.attributes); + writePunctuation("/>"); + } + function emitJsxFragment(node) { + emit(node.openingFragment); + emitList(node, node.children, 262144 /* JsxElementOrFragmentChildren */); + emit(node.closingFragment); + } + function emitJsxOpeningElementOrFragment(node) { + writePunctuation("<"); + if (ts.isJsxOpeningElement(node)) { + emitJsxTagName(node.tagName); + if (node.attributes.properties && node.attributes.properties.length > 0) { + writeSpace(); + } + emit(node.attributes); + } + writePunctuation(">"); + } + function emitJsxText(node) { + writer.writeLiteral(getTextOfNode(node, /*includeTrivia*/ true)); + } + function emitJsxClosingElementOrFragment(node) { + writePunctuation(""); + } + function emitJsxAttributes(node) { + emitList(node, node.properties, 262656 /* JsxElementAttributes */); + } + function emitJsxAttribute(node) { + emit(node.name); + emitNodeWithPrefix("=", writePunctuation, node.initializer, emit); // TODO: GH#18217 + } + function emitJsxSpreadAttribute(node) { + writePunctuation("{..."); + emitExpression(node.expression); + writePunctuation("}"); + } + function emitJsxExpression(node) { + if (node.expression) { + writePunctuation("{"); + emit(node.dotDotDotToken); + emitExpression(node.expression); + writePunctuation("}"); + } + } + function emitJsxTagName(node) { + if (node.kind === 72 /* Identifier */) { + emitExpression(node); + } + else { + emit(node); + } + } + // + // Clauses + // + function emitCaseClause(node) { + emitTokenWithComment(74 /* CaseKeyword */, node.pos, writeKeyword, node); + writeSpace(); + emitExpression(node.expression); + emitCaseOrDefaultClauseRest(node, node.statements, node.expression.end); + } + function emitDefaultClause(node) { + var pos = emitTokenWithComment(80 /* DefaultKeyword */, node.pos, writeKeyword, node); + emitCaseOrDefaultClauseRest(node, node.statements, pos); + } + function emitCaseOrDefaultClauseRest(parentNode, statements, colonPos) { + var emitAsSingleStatement = statements.length === 1 && + ( + // treat synthesized nodes as located on the same line for emit purposes + ts.nodeIsSynthesized(parentNode) || + ts.nodeIsSynthesized(statements[0]) || + ts.rangeStartPositionsAreOnSameLine(parentNode, statements[0], currentSourceFile)); + var format = 163969 /* CaseOrDefaultClauseStatements */; + if (emitAsSingleStatement) { + writeToken(57 /* ColonToken */, colonPos, writePunctuation, parentNode); + writeSpace(); + format &= ~(1 /* MultiLine */ | 128 /* Indented */); + } + else { + emitTokenWithComment(57 /* ColonToken */, colonPos, writePunctuation, parentNode); + } + emitList(parentNode, statements, format); + } + function emitHeritageClause(node) { + writeSpace(); + writeTokenText(node.token, writeKeyword); + writeSpace(); + emitList(node, node.types, 528 /* HeritageClauseTypes */); + } + function emitCatchClause(node) { + var openParenPos = emitTokenWithComment(75 /* CatchKeyword */, node.pos, writeKeyword, node); + writeSpace(); + if (node.variableDeclaration) { + emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node); + emit(node.variableDeclaration); + emitTokenWithComment(21 /* CloseParenToken */, node.variableDeclaration.end, writePunctuation, node); + writeSpace(); + } + emit(node.block); + } + // + // Property assignments + // + function emitPropertyAssignment(node) { + emit(node.name); + writePunctuation(":"); + writeSpace(); + // This is to ensure that we emit comment in the following case: + // For example: + // obj = { + // id: /*comment1*/ ()=>void + // } + // "comment1" is not considered to be leading comment for node.initializer + // but rather a trailing comment on the previous node. + var initializer = node.initializer; + if (emitTrailingCommentsOfPosition && (ts.getEmitFlags(initializer) & 512 /* NoLeadingComments */) === 0) { + var commentRange = ts.getCommentRange(initializer); + emitTrailingCommentsOfPosition(commentRange.pos); + } + emitExpression(initializer); + } + function emitShorthandPropertyAssignment(node) { + emit(node.name); + if (node.objectAssignmentInitializer) { + writeSpace(); + writePunctuation("="); + writeSpace(); + emitExpression(node.objectAssignmentInitializer); + } + } + function emitSpreadAssignment(node) { + if (node.expression) { + emitTokenWithComment(25 /* DotDotDotToken */, node.pos, writePunctuation, node); + emitExpression(node.expression); + } + } + // + // Enum + // + function emitEnumMember(node) { + emit(node.name); + emitInitializer(node.initializer, node.name.end, node); + } + // + // JSDoc + // + function emitJSDoc(node) { + write("/**"); + if (node.comment) { + var lines = node.comment.split(/\r\n?|\n/g); + for (var _a = 0, lines_2 = lines; _a < lines_2.length; _a++) { + var line = lines_2[_a]; + writeLine(); + writeSpace(); + writePunctuation("*"); + writeSpace(); + write(line); + } + } + if (node.tags) { + if (node.tags.length === 1 && node.tags[0].kind === 302 /* JSDocTypeTag */ && !node.comment) { + writeSpace(); + emit(node.tags[0]); + } + else { + emitList(node, node.tags, 33 /* JSDocComment */); + } + } + writeSpace(); + write("*/"); + } + function emitJSDocSimpleTypedTag(tag) { + emitJSDocTagName(tag.tagName); + emitJSDocTypeExpression(tag.typeExpression); + emitJSDocComment(tag.comment); + } + function emitJSDocAugmentsTag(tag) { + emitJSDocTagName(tag.tagName); + writeSpace(); + writePunctuation("{"); + emit(tag.class); + writePunctuation("}"); + emitJSDocComment(tag.comment); + } + function emitJSDocTemplateTag(tag) { + emitJSDocTagName(tag.tagName); + emitJSDocTypeExpression(tag.constraint); + writeSpace(); + emitList(tag, tag.typeParameters, 528 /* CommaListElements */); + emitJSDocComment(tag.comment); + } + function emitJSDocTypedefTag(tag) { + emitJSDocTagName(tag.tagName); + if (tag.typeExpression) { + if (tag.typeExpression.kind === 283 /* JSDocTypeExpression */) { + emitJSDocTypeExpression(tag.typeExpression); + } + else { + writeSpace(); + writePunctuation("{"); + write("Object"); + if (tag.typeExpression.isArrayType) { + writePunctuation("["); + writePunctuation("]"); + } + writePunctuation("}"); + } + } + if (tag.fullName) { + writeSpace(); + emit(tag.fullName); + } + emitJSDocComment(tag.comment); + if (tag.typeExpression && tag.typeExpression.kind === 292 /* JSDocTypeLiteral */) { + emitJSDocTypeLiteral(tag.typeExpression); + } + } + function emitJSDocCallbackTag(tag) { + emitJSDocTagName(tag.tagName); + if (tag.name) { + writeSpace(); + emit(tag.name); + } + emitJSDocComment(tag.comment); + emitJSDocSignature(tag.typeExpression); + } + function emitJSDocSimpleTag(tag) { + emitJSDocTagName(tag.tagName); + emitJSDocComment(tag.comment); + } + function emitJSDocTypeLiteral(lit) { + emitList(lit, ts.createNodeArray(lit.jsDocPropertyTags), 33 /* JSDocComment */); + } + function emitJSDocSignature(sig) { + if (sig.typeParameters) { + emitList(sig, ts.createNodeArray(sig.typeParameters), 33 /* JSDocComment */); + } + if (sig.parameters) { + emitList(sig, ts.createNodeArray(sig.parameters), 33 /* JSDocComment */); + } + if (sig.type) { + writeLine(); + writeSpace(); + writePunctuation("*"); + writeSpace(); + emit(sig.type); + } + } + function emitJSDocPropertyLikeTag(param) { + emitJSDocTagName(param.tagName); + emitJSDocTypeExpression(param.typeExpression); + writeSpace(); + if (param.isBracketed) { + writePunctuation("["); + } + emit(param.name); + if (param.isBracketed) { + writePunctuation("]"); + } + emitJSDocComment(param.comment); + } + function emitJSDocTagName(tagName) { + writePunctuation("@"); + emit(tagName); + } + function emitJSDocComment(comment) { + if (comment) { + writeSpace(); + write(comment); + } + } + function emitJSDocTypeExpression(typeExpression) { + if (typeExpression) { + writeSpace(); + writePunctuation("{"); + emit(typeExpression.type); + writePunctuation("}"); + } + } + // + // Top-level nodes + // + function emitSourceFile(node) { + writeLine(); + var statements = node.statements; + if (emitBodyWithDetachedComments) { + // Emit detached comment if there are no prologue directives or if the first node is synthesized. + // The synthesized node will have no leading comment so some comments may be missed. + var shouldEmitDetachedComment = statements.length === 0 || + !ts.isPrologueDirective(statements[0]) || + ts.nodeIsSynthesized(statements[0]); + if (shouldEmitDetachedComment) { + emitBodyWithDetachedComments(node, statements, emitSourceFileWorker); + return; + } + } + emitSourceFileWorker(node); + } + function emitSyntheticTripleSlashReferencesIfNeeded(node) { + emitTripleSlashDirectives(!!node.hasNoDefaultLib, node.syntheticFileReferences || [], node.syntheticTypeReferences || [], node.syntheticLibReferences || []); + } + function emitTripleSlashDirectivesIfNeeded(node) { + if (node.isDeclarationFile) + emitTripleSlashDirectives(node.hasNoDefaultLib, node.referencedFiles, node.typeReferenceDirectives, node.libReferenceDirectives); + } + function emitTripleSlashDirectives(hasNoDefaultLib, files, types, libs) { + if (hasNoDefaultLib) { + writeComment("/// "); + writeLine(); + } + if (currentSourceFile && currentSourceFile.moduleName) { + writeComment("/// "); + writeLine(); + } + if (currentSourceFile && currentSourceFile.amdDependencies) { + for (var _a = 0, _b = currentSourceFile.amdDependencies; _a < _b.length; _a++) { + var dep = _b[_a]; + if (dep.name) { + writeComment("/// "); + } + else { + writeComment("/// "); + } + writeLine(); + } + } + for (var _c = 0, files_1 = files; _c < files_1.length; _c++) { + var directive = files_1[_c]; + writeComment("/// "); + writeLine(); + } + for (var _d = 0, types_18 = types; _d < types_18.length; _d++) { + var directive = types_18[_d]; + writeComment("/// "); + writeLine(); + } + for (var _e = 0, libs_1 = libs; _e < libs_1.length; _e++) { + var directive = libs_1[_e]; + writeComment("/// "); + writeLine(); + } + } + function emitSourceFileWorker(node) { + var statements = node.statements; + pushNameGenerationScope(node); + ts.forEach(node.statements, generateNames); + emitHelpers(node); + var index = ts.findIndex(statements, function (statement) { return !ts.isPrologueDirective(statement); }); + emitTripleSlashDirectivesIfNeeded(node); + emitList(node, statements, 1 /* MultiLine */, index === -1 ? statements.length : index); + popNameGenerationScope(node); + } + // Transformation nodes + function emitPartiallyEmittedExpression(node) { + emitExpression(node.expression); + } + function emitCommaList(node) { + emitExpressionList(node, node.elements, 528 /* CommaListElements */); + } + /** + * Emits any prologue directives at the start of a Statement list, returning the + * number of prologue directives written to the output. + */ + function emitPrologueDirectives(statements, startWithNewLine, seenPrologueDirectives) { + for (var i = 0; i < statements.length; i++) { + var statement = statements[i]; + if (ts.isPrologueDirective(statement)) { + var shouldEmitPrologueDirective = seenPrologueDirectives ? !seenPrologueDirectives.has(statement.expression.text) : true; + if (shouldEmitPrologueDirective) { + if (startWithNewLine || i > 0) { + writeLine(); + } + emit(statement); + if (seenPrologueDirectives) { + seenPrologueDirectives.set(statement.expression.text, true); + } + } + } + else { + // return index of the first non prologue directive + return i; + } + } + return statements.length; + } + function emitPrologueDirectivesIfNeeded(sourceFileOrBundle) { + if (ts.isSourceFile(sourceFileOrBundle)) { + setSourceFile(sourceFileOrBundle); + emitPrologueDirectives(sourceFileOrBundle.statements); + } + else { + var seenPrologueDirectives = ts.createMap(); + for (var _a = 0, _b = sourceFileOrBundle.sourceFiles; _a < _b.length; _a++) { + var sourceFile = _b[_a]; + setSourceFile(sourceFile); + emitPrologueDirectives(sourceFile.statements, /*startWithNewLine*/ true, seenPrologueDirectives); + } + setSourceFile(undefined); + } + } + function emitShebangIfNeeded(sourceFileOrBundle) { + if (ts.isSourceFile(sourceFileOrBundle)) { + var shebang = ts.getShebang(sourceFileOrBundle.text); + if (shebang) { + writeComment(shebang); + writeLine(); + return true; + } + } + else { + for (var _a = 0, _b = sourceFileOrBundle.sourceFiles; _a < _b.length; _a++) { + var sourceFile = _b[_a]; + // Emit only the first encountered shebang + if (emitShebangIfNeeded(sourceFile)) { + break; + } + } + } + } + // + // Helpers + // + function emitNodeWithWriter(node, writer) { + if (!node) + return; + var savedWrite = write; + write = writer; + emit(node); + write = savedWrite; + } + function emitModifiers(node, modifiers) { + if (modifiers && modifiers.length) { + emitList(node, modifiers, 262656 /* Modifiers */); + writeSpace(); + } + } + function emitTypeAnnotation(node) { + if (node) { + writePunctuation(":"); + writeSpace(); + emit(node); + } + } + function emitInitializer(node, equalCommentStartPos, container) { + if (node) { + writeSpace(); + emitTokenWithComment(59 /* EqualsToken */, equalCommentStartPos, writeOperator, container); + writeSpace(); + emitExpression(node); + } + } + function emitNodeWithPrefix(prefix, prefixWriter, node, emit) { + if (node) { + prefixWriter(prefix); + emit(node); + } + } + function emitWithLeadingSpace(node) { + if (node) { + writeSpace(); + emit(node); + } + } + function emitExpressionWithLeadingSpace(node) { + if (node) { + writeSpace(); + emitExpression(node); + } + } + function emitWithTrailingSpace(node) { + if (node) { + emit(node); + writeSpace(); + } + } + function emitEmbeddedStatement(parent, node) { + if (ts.isBlock(node) || ts.getEmitFlags(parent) & 1 /* SingleLine */) { + writeSpace(); + emit(node); + } + else { + writeLine(); + increaseIndent(); + if (ts.isEmptyStatement(node)) { + var pipelinePhase = getPipelinePhase(0 /* Notification */, node); + pipelinePhase(5 /* EmbeddedStatement */, node); + } + else { + emit(node); + } + decreaseIndent(); + } + } + function emitDecorators(parentNode, decorators) { + emitList(parentNode, decorators, 49153 /* Decorators */); + } + function emitTypeArguments(parentNode, typeArguments) { + emitList(parentNode, typeArguments, 53776 /* TypeArguments */); + } + function emitTypeParameters(parentNode, typeParameters) { + if (ts.isFunctionLike(parentNode) && parentNode.typeArguments) { // Quick info uses type arguments in place of type parameters on instantiated signatures + return emitTypeArguments(parentNode, parentNode.typeArguments); + } + emitList(parentNode, typeParameters, 53776 /* TypeParameters */); + } + function emitParameters(parentNode, parameters) { + emitList(parentNode, parameters, 2576 /* Parameters */); + } + function canEmitSimpleArrowHead(parentNode, parameters) { + var parameter = ts.singleOrUndefined(parameters); + return parameter + && parameter.pos === parentNode.pos // may not have parsed tokens between parent and parameter + && ts.isArrowFunction(parentNode) // only arrow functions may have simple arrow head + && !parentNode.type // arrow function may not have return type annotation + && !ts.some(parentNode.decorators) // parent may not have decorators + && !ts.some(parentNode.modifiers) // parent may not have modifiers + && !ts.some(parentNode.typeParameters) // parent may not have type parameters + && !ts.some(parameter.decorators) // parameter may not have decorators + && !ts.some(parameter.modifiers) // parameter may not have modifiers + && !parameter.dotDotDotToken // parameter may not be rest + && !parameter.questionToken // parameter may not be optional + && !parameter.type // parameter may not have a type annotation + && !parameter.initializer // parameter may not have an initializer + && ts.isIdentifier(parameter.name); // parameter name must be identifier + } + function emitParametersForArrow(parentNode, parameters) { + if (canEmitSimpleArrowHead(parentNode, parameters)) { + emitList(parentNode, parameters, 2576 /* Parameters */ & ~2048 /* Parenthesis */); + } + else { + emitParameters(parentNode, parameters); + } + } + function emitParametersForIndexSignature(parentNode, parameters) { + emitList(parentNode, parameters, 8848 /* IndexSignatureParameters */); + } + function emitList(parentNode, children, format, start, count) { + emitNodeList(emit, parentNode, children, format, start, count); + } + function emitExpressionList(parentNode, children, format, start, count) { + emitNodeList(emitExpression, parentNode, children, format, start, count); // TODO: GH#18217 + } + function writeDelimiter(format) { + switch (format & 60 /* DelimitersMask */) { + case 0 /* None */: + break; + case 16 /* CommaDelimited */: + writePunctuation(","); + break; + case 4 /* BarDelimited */: + writeSpace(); + writePunctuation("|"); + break; + case 32 /* AsteriskDelimited */: + writeSpace(); + writePunctuation("*"); + writeSpace(); + break; + case 8 /* AmpersandDelimited */: + writeSpace(); + writePunctuation("&"); + break; + } + } + function emitNodeList(emit, parentNode, children, format, start, count) { + if (start === void 0) { start = 0; } + if (count === void 0) { count = children ? children.length - start : 0; } + var isUndefined = children === undefined; + if (isUndefined && format & 16384 /* OptionalIfUndefined */) { + return; + } + var isEmpty = children === undefined || start >= children.length || count === 0; + if (isEmpty && format & 32768 /* OptionalIfEmpty */) { + if (onBeforeEmitNodeArray) { + onBeforeEmitNodeArray(children); + } + if (onAfterEmitNodeArray) { + onAfterEmitNodeArray(children); + } + return; + } + if (format & 15360 /* BracketsMask */) { + writePunctuation(getOpeningBracket(format)); + if (isEmpty && !isUndefined) { + // TODO: GH#18217 + emitTrailingCommentsOfPosition(children.pos, /*prefixSpace*/ true); // Emit comments within empty bracketed lists + } + } + if (onBeforeEmitNodeArray) { + onBeforeEmitNodeArray(children); + } + if (isEmpty) { + // Write a line terminator if the parent node was multi-line + if (format & 1 /* MultiLine */) { + writeLine(); + } + else if (format & 256 /* SpaceBetweenBraces */ && !(format & 524288 /* NoSpaceIfEmpty */)) { + writeSpace(); + } + } + else { + // Write the opening line terminator or leading whitespace. + var mayEmitInterveningComments = (format & 262144 /* NoInterveningComments */) === 0; + var shouldEmitInterveningComments = mayEmitInterveningComments; + if (shouldWriteLeadingLineTerminator(parentNode, children, format)) { // TODO: GH#18217 + writeLine(); + shouldEmitInterveningComments = false; + } + else if (format & 256 /* SpaceBetweenBraces */) { + writeSpace(); + } + // Increase the indent, if requested. + if (format & 128 /* Indented */) { + increaseIndent(); + } + // Emit each child. + var previousSibling = void 0; + var shouldDecreaseIndentAfterEmit = false; + for (var i = 0; i < count; i++) { + var child = children[start + i]; + // Write the delimiter if this is not the first node. + if (format & 32 /* AsteriskDelimited */) { + // always write JSDoc in the format "\n *" + writeLine(); + writeDelimiter(format); + } + else if (previousSibling) { + // i.e + // function commentedParameters( + // /* Parameter a */ + // a + // /* End of parameter a */ -> this comment isn't considered to be trailing comment of parameter "a" due to newline + // , + if (format & 60 /* DelimitersMask */ && previousSibling.end !== parentNode.end) { + emitLeadingCommentsOfPosition(previousSibling.end); + } + writeDelimiter(format); + // Write either a line terminator or whitespace to separate the elements. + if (shouldWriteSeparatingLineTerminator(previousSibling, child, format)) { + // If a synthesized node in a single-line list starts on a new + // line, we should increase the indent. + if ((format & (3 /* LinesMask */ | 128 /* Indented */)) === 0 /* SingleLine */) { + increaseIndent(); + shouldDecreaseIndentAfterEmit = true; + } + writeLine(); + shouldEmitInterveningComments = false; + } + else if (previousSibling && format & 512 /* SpaceBetweenSiblings */) { + writeSpace(); + } + } + // Emit this child. + if (shouldEmitInterveningComments) { + if (emitTrailingCommentsOfPosition) { + var commentRange = ts.getCommentRange(child); + emitTrailingCommentsOfPosition(commentRange.pos); + } + } + else { + shouldEmitInterveningComments = mayEmitInterveningComments; + } + emit(child); + if (shouldDecreaseIndentAfterEmit) { + decreaseIndent(); + shouldDecreaseIndentAfterEmit = false; + } + previousSibling = child; + } + // Write a trailing comma, if requested. + var hasTrailingComma = (format & 64 /* AllowTrailingComma */) && children.hasTrailingComma; + if (format & 16 /* CommaDelimited */ && hasTrailingComma) { + writePunctuation(","); + } + // Emit any trailing comment of the last element in the list + // i.e + // var array = [... + // 2 + // /* end of element 2 */ + // ]; + if (previousSibling && format & 60 /* DelimitersMask */ && previousSibling.end !== parentNode.end && !(ts.getEmitFlags(previousSibling) & 1024 /* NoTrailingComments */)) { + emitLeadingCommentsOfPosition(previousSibling.end); + } + // Decrease the indent, if requested. + if (format & 128 /* Indented */) { + decreaseIndent(); + } + // Write the closing line terminator or closing whitespace. + if (shouldWriteClosingLineTerminator(parentNode, children, format)) { + writeLine(); + } + else if (format & 256 /* SpaceBetweenBraces */) { + writeSpace(); + } + } + if (onAfterEmitNodeArray) { + onAfterEmitNodeArray(children); + } + if (format & 15360 /* BracketsMask */) { + if (isEmpty && !isUndefined) { + // TODO: GH#18217 + emitLeadingCommentsOfPosition(children.end); // Emit leading comments within empty lists + } + writePunctuation(getClosingBracket(format)); + } + } + // Writers + function writeLiteral(s) { + writer.writeLiteral(s); + } + function writeStringLiteral(s) { + writer.writeStringLiteral(s); + } + function writeBase(s) { + writer.write(s); + } + function writeSymbol(s, sym) { + writer.writeSymbol(s, sym); + } + function writePunctuation(s) { + writer.writePunctuation(s); + } + function writeTrailingSemicolon() { + writer.writeTrailingSemicolon(";"); + } + function writeKeyword(s) { + writer.writeKeyword(s); + } + function writeOperator(s) { + writer.writeOperator(s); + } + function writeParameter(s) { + writer.writeParameter(s); + } + function writeComment(s) { + writer.writeComment(s); + } + function writeSpace() { + writer.writeSpace(" "); + } + function writeProperty(s) { + writer.writeProperty(s); + } + function writeLine() { + writer.writeLine(); + } + function increaseIndent() { + writer.increaseIndent(); + } + function decreaseIndent() { + writer.decreaseIndent(); + } + function writeToken(token, pos, writer, contextNode) { + return !sourceMapsDisabled + ? emitTokenWithSourceMap(contextNode, token, writer, pos, writeTokenText) + : writeTokenText(token, writer, pos); + } + function writeTokenNode(node, writer) { + if (onBeforeEmitToken) { + onBeforeEmitToken(node); + } + writer(ts.tokenToString(node.kind)); + if (onAfterEmitToken) { + onAfterEmitToken(node); + } + } + function writeTokenText(token, writer, pos) { + var tokenString = ts.tokenToString(token); + writer(tokenString); + return pos < 0 ? pos : pos + tokenString.length; + } + function writeLineOrSpace(node) { + if (ts.getEmitFlags(node) & 1 /* SingleLine */) { + writeSpace(); + } + else { + writeLine(); + } + } + function writeLines(text) { + var lines = text.split(/\r\n?|\n/g); + var indentation = ts.guessIndentation(lines); + for (var _a = 0, lines_3 = lines; _a < lines_3.length; _a++) { + var lineText = lines_3[_a]; + var line = indentation ? lineText.slice(indentation) : lineText; + if (line.length) { + writeLine(); + write(line); + writer.rawWrite(newLine); + } + } + } + function increaseIndentIf(value, writeSpaceIfNotIndenting) { + if (value) { + increaseIndent(); + writeLine(); + } + else if (writeSpaceIfNotIndenting) { + writeSpace(); + } + } + // Helper function to decrease the indent if we previously indented. Allows multiple + // previous indent values to be considered at a time. This also allows caller to just + // call this once, passing in all their appropriate indent values, instead of needing + // to call this helper function multiple times. + function decreaseIndentIf(value1, value2) { + if (value1) { + decreaseIndent(); + } + if (value2) { + decreaseIndent(); + } + } + function shouldWriteLeadingLineTerminator(parentNode, children, format) { + if (format & 1 /* MultiLine */) { + return true; + } + if (format & 2 /* PreserveLines */) { + if (format & 65536 /* PreferNewLine */) { + return true; + } + var firstChild = children[0]; + if (firstChild === undefined) { + return !ts.rangeIsOnSingleLine(parentNode, currentSourceFile); + } + else if (ts.positionIsSynthesized(parentNode.pos) || ts.nodeIsSynthesized(firstChild)) { + return synthesizedNodeStartsOnNewLine(firstChild, format); + } + else { + return !ts.rangeStartPositionsAreOnSameLine(parentNode, firstChild, currentSourceFile); + } + } + else { + return false; + } + } + function shouldWriteSeparatingLineTerminator(previousNode, nextNode, format) { + if (format & 1 /* MultiLine */) { + return true; + } + else if (format & 2 /* PreserveLines */) { + if (previousNode === undefined || nextNode === undefined) { + return false; + } + else if (ts.nodeIsSynthesized(previousNode) || ts.nodeIsSynthesized(nextNode)) { + return synthesizedNodeStartsOnNewLine(previousNode, format) || synthesizedNodeStartsOnNewLine(nextNode, format); + } + else { + return !ts.rangeEndIsOnSameLineAsRangeStart(previousNode, nextNode, currentSourceFile); + } + } + else { + return ts.getStartsOnNewLine(nextNode); + } + } + function shouldWriteClosingLineTerminator(parentNode, children, format) { + if (format & 1 /* MultiLine */) { + return (format & 131072 /* NoTrailingNewLine */) === 0; + } + else if (format & 2 /* PreserveLines */) { + if (format & 65536 /* PreferNewLine */) { + return true; + } + var lastChild = ts.lastOrUndefined(children); + if (lastChild === undefined) { + return !ts.rangeIsOnSingleLine(parentNode, currentSourceFile); + } + else if (ts.positionIsSynthesized(parentNode.pos) || ts.nodeIsSynthesized(lastChild)) { + return synthesizedNodeStartsOnNewLine(lastChild, format); + } + else { + return !ts.rangeEndPositionsAreOnSameLine(parentNode, lastChild, currentSourceFile); + } + } + else { + return false; + } + } + function synthesizedNodeStartsOnNewLine(node, format) { + if (ts.nodeIsSynthesized(node)) { + var startsOnNewLine = ts.getStartsOnNewLine(node); + if (startsOnNewLine === undefined) { + return (format & 65536 /* PreferNewLine */) !== 0; + } + return startsOnNewLine; + } + return (format & 65536 /* PreferNewLine */) !== 0; + } + function needsIndentation(parent, node1, node2) { + parent = skipSynthesizedParentheses(parent); + node1 = skipSynthesizedParentheses(node1); + node2 = skipSynthesizedParentheses(node2); + // Always use a newline for synthesized code if the synthesizer desires it. + if (ts.getStartsOnNewLine(node2)) { + return true; + } + return !ts.nodeIsSynthesized(parent) + && !ts.nodeIsSynthesized(node1) + && !ts.nodeIsSynthesized(node2) + && !ts.rangeEndIsOnSameLineAsRangeStart(node1, node2, currentSourceFile); + } + function isEmptyBlock(block) { + return block.statements.length === 0 + && ts.rangeEndIsOnSameLineAsRangeStart(block, block, currentSourceFile); + } + function skipSynthesizedParentheses(node) { + while (node.kind === 195 /* ParenthesizedExpression */ && ts.nodeIsSynthesized(node)) { + node = node.expression; + } + return node; + } + function getTextOfNode(node, includeTrivia) { + if (ts.isGeneratedIdentifier(node)) { + return generateName(node); + } + else if (ts.isIdentifier(node) && (ts.nodeIsSynthesized(node) || !node.parent || !currentSourceFile || (node.parent && currentSourceFile && ts.getSourceFileOfNode(node) !== ts.getOriginalNode(currentSourceFile)))) { + return ts.idText(node); + } + else if (node.kind === 10 /* StringLiteral */ && node.textSourceNode) { + return getTextOfNode(node.textSourceNode, includeTrivia); + } + else if (ts.isLiteralExpression(node) && (ts.nodeIsSynthesized(node) || !node.parent)) { + return node.text; + } + return ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node, includeTrivia); + } + function getLiteralTextOfNode(node, neverAsciiEscape) { + if (node.kind === 10 /* StringLiteral */ && node.textSourceNode) { + var textSourceNode = node.textSourceNode; + if (ts.isIdentifier(textSourceNode)) { + return neverAsciiEscape || (ts.getEmitFlags(node) & 16777216 /* NoAsciiEscaping */) ? + "\"" + ts.escapeString(getTextOfNode(textSourceNode)) + "\"" : + "\"" + ts.escapeNonAsciiString(getTextOfNode(textSourceNode)) + "\""; + } + else { + return getLiteralTextOfNode(textSourceNode, neverAsciiEscape); + } + } + return ts.getLiteralText(node, currentSourceFile, neverAsciiEscape); + } + /** + * Push a new name generation scope. + */ + function pushNameGenerationScope(node) { + if (node && ts.getEmitFlags(node) & 524288 /* ReuseTempVariableScope */) { + return; + } + tempFlagsStack.push(tempFlags); + tempFlags = 0; + reservedNamesStack.push(reservedNames); + } + /** + * Pop the current name generation scope. + */ + function popNameGenerationScope(node) { + if (node && ts.getEmitFlags(node) & 524288 /* ReuseTempVariableScope */) { + return; + } + tempFlags = tempFlagsStack.pop(); + reservedNames = reservedNamesStack.pop(); + } + function reserveNameInNestedScopes(name) { + if (!reservedNames || reservedNames === ts.lastOrUndefined(reservedNamesStack)) { + reservedNames = ts.createMap(); + } + reservedNames.set(name, true); + } + function generateNames(node) { + if (!node) + return; + switch (node.kind) { + case 218 /* Block */: + ts.forEach(node.statements, generateNames); + break; + case 233 /* LabeledStatement */: + case 231 /* WithStatement */: + case 223 /* DoStatement */: + case 224 /* WhileStatement */: + generateNames(node.statement); + break; + case 222 /* IfStatement */: + generateNames(node.thenStatement); + generateNames(node.elseStatement); + break; + case 225 /* ForStatement */: + case 227 /* ForOfStatement */: + case 226 /* ForInStatement */: + generateNames(node.initializer); + generateNames(node.statement); + break; + case 232 /* SwitchStatement */: + generateNames(node.caseBlock); + break; + case 246 /* CaseBlock */: + ts.forEach(node.clauses, generateNames); + break; + case 271 /* CaseClause */: + case 272 /* DefaultClause */: + ts.forEach(node.statements, generateNames); + break; + case 235 /* TryStatement */: + generateNames(node.tryBlock); + generateNames(node.catchClause); + generateNames(node.finallyBlock); + break; + case 274 /* CatchClause */: + generateNames(node.variableDeclaration); + generateNames(node.block); + break; + case 219 /* VariableStatement */: + generateNames(node.declarationList); + break; + case 238 /* VariableDeclarationList */: + ts.forEach(node.declarations, generateNames); + break; + case 237 /* VariableDeclaration */: + case 151 /* Parameter */: + case 186 /* BindingElement */: + case 240 /* ClassDeclaration */: + generateNameIfNeeded(node.name); + break; + case 239 /* FunctionDeclaration */: + generateNameIfNeeded(node.name); + if (ts.getEmitFlags(node) & 524288 /* ReuseTempVariableScope */) { + ts.forEach(node.parameters, generateNames); + generateNames(node.body); + } + break; + case 184 /* ObjectBindingPattern */: + case 185 /* ArrayBindingPattern */: + ts.forEach(node.elements, generateNames); + break; + case 249 /* ImportDeclaration */: + generateNames(node.importClause); + break; + case 250 /* ImportClause */: + generateNameIfNeeded(node.name); + generateNames(node.namedBindings); + break; + case 251 /* NamespaceImport */: + generateNameIfNeeded(node.name); + break; + case 252 /* NamedImports */: + ts.forEach(node.elements, generateNames); + break; + case 253 /* ImportSpecifier */: + generateNameIfNeeded(node.propertyName || node.name); + break; + } + } + function generateMemberNames(node) { + if (!node) + return; + switch (node.kind) { + case 275 /* PropertyAssignment */: + case 276 /* ShorthandPropertyAssignment */: + case 154 /* PropertyDeclaration */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + generateNameIfNeeded(node.name); + break; + } + } + function generateNameIfNeeded(name) { + if (name) { + if (ts.isGeneratedIdentifier(name)) { + generateName(name); + } + else if (ts.isBindingPattern(name)) { + generateNames(name); + } + } + } + /** + * Generate the text for a generated identifier. + */ + function generateName(name) { + if ((name.autoGenerateFlags & 7 /* KindMask */) === 4 /* Node */) { + // Node names generate unique names based on their original node + // and are cached based on that node's id. + return generateNameCached(getNodeForGeneratedName(name), name.autoGenerateFlags); + } + else { + // Auto, Loop, and Unique names are cached based on their unique + // autoGenerateId. + var autoGenerateId = name.autoGenerateId; + return autoGeneratedIdToGeneratedName[autoGenerateId] || (autoGeneratedIdToGeneratedName[autoGenerateId] = makeName(name)); + } + } + function generateNameCached(node, flags) { + var nodeId = ts.getNodeId(node); + return nodeIdToGeneratedName[nodeId] || (nodeIdToGeneratedName[nodeId] = generateNameForNode(node, flags)); + } + /** + * Returns a value indicating whether a name is unique globally, within the current file, + * or within the NameGenerator. + */ + function isUniqueName(name) { + return isFileLevelUniqueName(name) + && !generatedNames.has(name) + && !(reservedNames && reservedNames.has(name)); + } + /** + * Returns a value indicating whether a name is unique globally or within the current file. + */ + function isFileLevelUniqueName(name) { + return currentSourceFile ? ts.isFileLevelUniqueName(currentSourceFile, name, hasGlobalName) : true; + } + /** + * Returns a value indicating whether a name is unique within a container. + */ + function isUniqueLocalName(name, container) { + for (var node = container; ts.isNodeDescendantOf(node, container); node = node.nextContainer) { + if (node.locals) { + var local = node.locals.get(ts.escapeLeadingUnderscores(name)); + // We conservatively include alias symbols to cover cases where they're emitted as locals + if (local && local.flags & (67220415 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */)) { + return false; + } + } + } + return true; + } + /** + * Return the next available name in the pattern _a ... _z, _0, _1, ... + * TempFlags._i or TempFlags._n may be used to express a preference for that dedicated name. + * Note that names generated by makeTempVariableName and makeUniqueName will never conflict. + */ + function makeTempVariableName(flags, reservedInNestedScopes) { + if (flags && !(tempFlags & flags)) { + var name = flags === 268435456 /* _i */ ? "_i" : "_n"; + if (isUniqueName(name)) { + tempFlags |= flags; + if (reservedInNestedScopes) { + reserveNameInNestedScopes(name); + } + return name; + } + } + while (true) { + var count = tempFlags & 268435455 /* CountMask */; + tempFlags++; + // Skip over 'i' and 'n' + if (count !== 8 && count !== 13) { + var name = count < 26 + ? "_" + String.fromCharCode(97 /* a */ + count) + : "_" + (count - 26); + if (isUniqueName(name)) { + if (reservedInNestedScopes) { + reserveNameInNestedScopes(name); + } + return name; + } + } + } + } + /** + * Generate a name that is unique within the current file and doesn't conflict with any names + * in global scope. The name is formed by adding an '_n' suffix to the specified base name, + * where n is a positive integer. Note that names generated by makeTempVariableName and + * makeUniqueName are guaranteed to never conflict. + * If `optimistic` is set, the first instance will use 'baseName' verbatim instead of 'baseName_1' + */ + function makeUniqueName(baseName, checkFn, optimistic, scoped) { + if (checkFn === void 0) { checkFn = isUniqueName; } + if (optimistic) { + if (checkFn(baseName)) { + if (scoped) { + reserveNameInNestedScopes(baseName); + } + else { + generatedNames.set(baseName, true); + } + return baseName; + } + } + // Find the first unique 'name_n', where n is a positive number + if (baseName.charCodeAt(baseName.length - 1) !== 95 /* _ */) { + baseName += "_"; + } + var i = 1; + while (true) { + var generatedName = baseName + i; + if (checkFn(generatedName)) { + if (scoped) { + reserveNameInNestedScopes(generatedName); + } + else { + generatedNames.set(generatedName, true); + } + return generatedName; + } + i++; + } + } + function makeFileLevelOptimisticUniqueName(name) { + return makeUniqueName(name, isFileLevelUniqueName, /*optimistic*/ true); + } + /** + * Generates a unique name for a ModuleDeclaration or EnumDeclaration. + */ + function generateNameForModuleOrEnum(node) { + var name = getTextOfNode(node.name); + // Use module/enum name itself if it is unique, otherwise make a unique variation + return isUniqueLocalName(name, node) ? name : makeUniqueName(name); + } + /** + * Generates a unique name for an ImportDeclaration or ExportDeclaration. + */ + function generateNameForImportOrExportDeclaration(node) { + var expr = ts.getExternalModuleName(node); // TODO: GH#18217 + var baseName = ts.isStringLiteral(expr) ? + ts.makeIdentifierFromModuleName(expr.text) : "module"; + return makeUniqueName(baseName); + } + /** + * Generates a unique name for a default export. + */ + function generateNameForExportDefault() { + return makeUniqueName("default"); + } + /** + * Generates a unique name for a class expression. + */ + function generateNameForClassExpression() { + return makeUniqueName("class"); + } + function generateNameForMethodOrAccessor(node) { + if (ts.isIdentifier(node.name)) { + return generateNameCached(node.name); + } + return makeTempVariableName(0 /* Auto */); + } + /** + * Generates a unique name from a node. + */ + function generateNameForNode(node, flags) { + switch (node.kind) { + case 72 /* Identifier */: + return makeUniqueName(getTextOfNode(node), isUniqueName, !!(flags & 16 /* Optimistic */), !!(flags & 8 /* ReservedInNestedScopes */)); + case 244 /* ModuleDeclaration */: + case 243 /* EnumDeclaration */: + return generateNameForModuleOrEnum(node); + case 249 /* ImportDeclaration */: + case 255 /* ExportDeclaration */: + return generateNameForImportOrExportDeclaration(node); + case 239 /* FunctionDeclaration */: + case 240 /* ClassDeclaration */: + case 254 /* ExportAssignment */: + return generateNameForExportDefault(); + case 209 /* ClassExpression */: + return generateNameForClassExpression(); + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + return generateNameForMethodOrAccessor(node); + default: + return makeTempVariableName(0 /* Auto */); + } + } + /** + * Generates a unique identifier for a node. + */ + function makeName(name) { + switch (name.autoGenerateFlags & 7 /* KindMask */) { + case 1 /* Auto */: + return makeTempVariableName(0 /* Auto */, !!(name.autoGenerateFlags & 8 /* ReservedInNestedScopes */)); + case 2 /* Loop */: + return makeTempVariableName(268435456 /* _i */, !!(name.autoGenerateFlags & 8 /* ReservedInNestedScopes */)); + case 3 /* Unique */: + return makeUniqueName(ts.idText(name), (name.autoGenerateFlags & 32 /* FileLevel */) ? isFileLevelUniqueName : isUniqueName, !!(name.autoGenerateFlags & 16 /* Optimistic */), !!(name.autoGenerateFlags & 8 /* ReservedInNestedScopes */)); + } + return ts.Debug.fail("Unsupported GeneratedIdentifierKind."); + } + /** + * Gets the node from which a name should be generated. + */ + function getNodeForGeneratedName(name) { + var autoGenerateId = name.autoGenerateId; + var node = name; + var original = node.original; + while (original) { + node = original; + // if "node" is a different generated name (having a different + // "autoGenerateId"), use it and stop traversing. + if (ts.isIdentifier(node) + && !!(node.autoGenerateFlags & 4 /* Node */) + && node.autoGenerateId !== autoGenerateId) { + break; + } + original = node.original; + } + // otherwise, return the original node for the source; + return node; + } + // Comments + function pipelineEmitWithComments(hint, node) { + enterComment(); + hasWrittenComment = false; + var emitFlags = ts.getEmitFlags(node); + var _a = ts.getCommentRange(node), pos = _a.pos, end = _a.end; + var isEmittedNode = node.kind !== 307 /* NotEmittedStatement */; + // We have to explicitly check that the node is JsxText because if the compilerOptions.jsx is "preserve" we will not do any transformation. + // It is expensive to walk entire tree just to set one kind of node to have no comments. + var skipLeadingComments = pos < 0 || (emitFlags & 512 /* NoLeadingComments */) !== 0 || node.kind === 11 /* JsxText */; + var skipTrailingComments = end < 0 || (emitFlags & 1024 /* NoTrailingComments */) !== 0 || node.kind === 11 /* JsxText */; + // Save current container state on the stack. + var savedContainerPos = containerPos; + var savedContainerEnd = containerEnd; + var savedDeclarationListContainerEnd = declarationListContainerEnd; + if ((pos > 0 || end > 0) && pos !== end) { + // Emit leading comments if the position is not synthesized and the node + // has not opted out from emitting leading comments. + if (!skipLeadingComments) { + emitLeadingComments(pos, isEmittedNode); + } + if (!skipLeadingComments || (pos >= 0 && (emitFlags & 512 /* NoLeadingComments */) !== 0)) { + // Advance the container position if comments get emitted or if they've been disabled explicitly using NoLeadingComments. + containerPos = pos; + } + if (!skipTrailingComments || (end >= 0 && (emitFlags & 1024 /* NoTrailingComments */) !== 0)) { + // As above. + containerEnd = end; + // To avoid invalid comment emit in a down-level binding pattern, we + // keep track of the last declaration list container's end + if (node.kind === 238 /* VariableDeclarationList */) { + declarationListContainerEnd = end; + } + } + } + ts.forEach(ts.getSyntheticLeadingComments(node), emitLeadingSynthesizedComment); + exitComment(); + var pipelinePhase = getNextPipelinePhase(2 /* Comments */, node); + if (emitFlags & 2048 /* NoNestedComments */) { + commentsDisabled = true; + pipelinePhase(hint, node); + commentsDisabled = false; + } + else { + pipelinePhase(hint, node); + } + enterComment(); + ts.forEach(ts.getSyntheticTrailingComments(node), emitTrailingSynthesizedComment); + if ((pos > 0 || end > 0) && pos !== end) { + // Restore previous container state. + containerPos = savedContainerPos; + containerEnd = savedContainerEnd; + declarationListContainerEnd = savedDeclarationListContainerEnd; + // Emit trailing comments if the position is not synthesized and the node + // has not opted out from emitting leading comments and is an emitted node. + if (!skipTrailingComments && isEmittedNode) { + emitTrailingComments(end); + } + } + exitComment(); + } + function emitLeadingSynthesizedComment(comment) { + if (comment.kind === 2 /* SingleLineCommentTrivia */) { + writer.writeLine(); + } + writeSynthesizedComment(comment); + if (comment.hasTrailingNewLine || comment.kind === 2 /* SingleLineCommentTrivia */) { + writer.writeLine(); + } + else { + writer.writeSpace(" "); + } + } + function emitTrailingSynthesizedComment(comment) { + if (!writer.isAtStartOfLine()) { + writer.writeSpace(" "); + } + writeSynthesizedComment(comment); + if (comment.hasTrailingNewLine) { + writer.writeLine(); + } + } + function writeSynthesizedComment(comment) { + var text = formatSynthesizedComment(comment); + var lineMap = comment.kind === 3 /* MultiLineCommentTrivia */ ? ts.computeLineStarts(text) : undefined; + ts.writeCommentRange(text, lineMap, writer, 0, text.length, newLine); + } + function formatSynthesizedComment(comment) { + return comment.kind === 3 /* MultiLineCommentTrivia */ + ? "/*" + comment.text + "*/" + : "//" + comment.text; + } + function emitBodyWithDetachedComments(node, detachedRange, emitCallback) { + enterComment(); + var pos = detachedRange.pos, end = detachedRange.end; + var emitFlags = ts.getEmitFlags(node); + var skipLeadingComments = pos < 0 || (emitFlags & 512 /* NoLeadingComments */) !== 0; + var skipTrailingComments = commentsDisabled || end < 0 || (emitFlags & 1024 /* NoTrailingComments */) !== 0; + if (!skipLeadingComments) { + emitDetachedCommentsAndUpdateCommentsInfo(detachedRange); + } + exitComment(); + if (emitFlags & 2048 /* NoNestedComments */ && !commentsDisabled) { + commentsDisabled = true; + emitCallback(node); + commentsDisabled = false; + } + else { + emitCallback(node); + } + enterComment(); + if (!skipTrailingComments) { + emitLeadingComments(detachedRange.end, /*isEmittedNode*/ true); + if (hasWrittenComment && !writer.isAtStartOfLine()) { + writer.writeLine(); + } + } + exitComment(); + } + function emitLeadingComments(pos, isEmittedNode) { + hasWrittenComment = false; + if (isEmittedNode) { + forEachLeadingCommentToEmit(pos, emitLeadingComment); + } + else if (pos === 0) { + // If the node will not be emitted in JS, remove all the comments(normal, pinned and ///) associated with the node, + // unless it is a triple slash comment at the top of the file. + // For Example: + // /// + // declare var x; + // /// + // interface F {} + // The first /// will NOT be removed while the second one will be removed even though both node will not be emitted + forEachLeadingCommentToEmit(pos, emitTripleSlashLeadingComment); + } + } + function emitTripleSlashLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos) { + if (isTripleSlashComment(commentPos, commentEnd)) { + emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos); + } + } + function shouldWriteComment(text, pos) { + if (printerOptions.onlyPrintJsDocStyle) { + return (ts.isJSDocLikeText(text, pos) || ts.isPinnedComment(text, pos)); + } + return true; + } + function emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos) { + if (!shouldWriteComment(currentSourceFile.text, commentPos)) + return; + if (!hasWrittenComment) { + ts.emitNewLineBeforeLeadingCommentOfPosition(getCurrentLineMap(), writer, rangePos, commentPos); + hasWrittenComment = true; + } + // Leading comments are emitted at /*leading comment1 */space/*leading comment*/space + emitPos(commentPos); + ts.writeCommentRange(currentSourceFile.text, getCurrentLineMap(), writer, commentPos, commentEnd, newLine); + emitPos(commentEnd); + if (hasTrailingNewLine) { + writer.writeLine(); + } + else if (kind === 3 /* MultiLineCommentTrivia */) { + writer.writeSpace(" "); + } + } + function emitLeadingCommentsOfPosition(pos) { + if (commentsDisabled || pos === -1) { + return; + } + emitLeadingComments(pos, /*isEmittedNode*/ true); + } + function emitTrailingComments(pos) { + forEachTrailingCommentToEmit(pos, emitTrailingComment); + } + function emitTrailingComment(commentPos, commentEnd, _kind, hasTrailingNewLine) { + if (!shouldWriteComment(currentSourceFile.text, commentPos)) + return; + // trailing comments are emitted at space/*trailing comment1 */space/*trailing comment2*/ + if (!writer.isAtStartOfLine()) { + writer.writeSpace(" "); + } + emitPos(commentPos); + ts.writeCommentRange(currentSourceFile.text, getCurrentLineMap(), writer, commentPos, commentEnd, newLine); + emitPos(commentEnd); + if (hasTrailingNewLine) { + writer.writeLine(); + } + } + function emitTrailingCommentsOfPosition(pos, prefixSpace) { + if (commentsDisabled) { + return; + } + enterComment(); + forEachTrailingCommentToEmit(pos, prefixSpace ? emitTrailingComment : emitTrailingCommentOfPosition); + exitComment(); + } + function emitTrailingCommentOfPosition(commentPos, commentEnd, _kind, hasTrailingNewLine) { + // trailing comments of a position are emitted at /*trailing comment1 */space/*trailing comment*/space + emitPos(commentPos); + ts.writeCommentRange(currentSourceFile.text, getCurrentLineMap(), writer, commentPos, commentEnd, newLine); + emitPos(commentEnd); + if (hasTrailingNewLine) { + writer.writeLine(); + } + else { + writer.writeSpace(" "); + } + } + function forEachLeadingCommentToEmit(pos, cb) { + // Emit the leading comments only if the container's pos doesn't match because the container should take care of emitting these comments + if (currentSourceFile && (containerPos === -1 || pos !== containerPos)) { + if (hasDetachedComments(pos)) { + forEachLeadingCommentWithoutDetachedComments(cb); + } + else { + ts.forEachLeadingCommentRange(currentSourceFile.text, pos, cb, /*state*/ pos); + } + } + } + function forEachTrailingCommentToEmit(end, cb) { + // Emit the trailing comments only if the container's end doesn't match because the container should take care of emitting these comments + if (currentSourceFile && (containerEnd === -1 || (end !== containerEnd && end !== declarationListContainerEnd))) { + ts.forEachTrailingCommentRange(currentSourceFile.text, end, cb); + } + } + function hasDetachedComments(pos) { + return detachedCommentsInfo !== undefined && ts.last(detachedCommentsInfo).nodePos === pos; + } + function forEachLeadingCommentWithoutDetachedComments(cb) { + // get the leading comments from detachedPos + var pos = ts.last(detachedCommentsInfo).detachedCommentEndPos; + if (detachedCommentsInfo.length - 1) { + detachedCommentsInfo.pop(); + } + else { + detachedCommentsInfo = undefined; + } + ts.forEachLeadingCommentRange(currentSourceFile.text, pos, cb, /*state*/ pos); + } + function emitDetachedCommentsAndUpdateCommentsInfo(range) { + var currentDetachedCommentInfo = ts.emitDetachedComments(currentSourceFile.text, getCurrentLineMap(), writer, emitComment, range, newLine, commentsDisabled); + if (currentDetachedCommentInfo) { + if (detachedCommentsInfo) { + detachedCommentsInfo.push(currentDetachedCommentInfo); + } + else { + detachedCommentsInfo = [currentDetachedCommentInfo]; + } + } + } + function emitComment(text, lineMap, writer, commentPos, commentEnd, newLine) { + if (!shouldWriteComment(currentSourceFile.text, commentPos)) + return; + emitPos(commentPos); + ts.writeCommentRange(text, lineMap, writer, commentPos, commentEnd, newLine); + emitPos(commentEnd); + } + /** + * Determine if the given comment is a triple-slash + * + * @return true if the comment is a triple-slash comment else false + */ + function isTripleSlashComment(commentPos, commentEnd) { + return ts.isRecognizedTripleSlashComment(currentSourceFile.text, commentPos, commentEnd); + } + // Source Maps + function pipelineEmitWithSourceMap(hint, node) { + var pipelinePhase = getNextPipelinePhase(3 /* SourceMaps */, node); + if (ts.isUnparsedSource(node) && node.sourceMapText !== undefined) { + var parsed = ts.tryParseRawSourceMap(node.sourceMapText); + if (parsed) { + sourceMapGenerator.appendSourceMap(writer.getLine(), writer.getColumn(), parsed, node.sourceMapPath); + } + pipelinePhase(hint, node); + } + else { + var _a = ts.getSourceMapRange(node), pos = _a.pos, end = _a.end, _b = _a.source, source = _b === void 0 ? sourceMapSource : _b; + var emitFlags = ts.getEmitFlags(node); + if (node.kind !== 307 /* NotEmittedStatement */ + && (emitFlags & 16 /* NoLeadingSourceMap */) === 0 + && pos >= 0) { + emitSourcePos(source, skipSourceTrivia(source, pos)); + } + if (emitFlags & 64 /* NoNestedSourceMaps */) { + sourceMapsDisabled = true; + pipelinePhase(hint, node); + sourceMapsDisabled = false; + } + else { + pipelinePhase(hint, node); + } + if (node.kind !== 307 /* NotEmittedStatement */ + && (emitFlags & 32 /* NoTrailingSourceMap */) === 0 + && end >= 0) { + emitSourcePos(source, end); + } + } + } + /** + * Skips trivia such as comments and white-space that can optionally overriden by the source map source + */ + function skipSourceTrivia(source, pos) { + return source.skipTrivia ? source.skipTrivia(pos) : ts.skipTrivia(sourceMapSource.text, pos); + } + /** + * Emits a mapping. + * + * If the position is synthetic (undefined or a negative value), no mapping will be + * created. + * + * @param pos The position. + */ + function emitPos(pos) { + if (sourceMapsDisabled || ts.positionIsSynthesized(pos) || isJsonSourceMapSource(sourceMapSource)) { + return; + } + var _a = ts.getLineAndCharacterOfPosition(currentSourceFile, pos), sourceLine = _a.line, sourceCharacter = _a.character; + sourceMapGenerator.addMapping(writer.getLine(), writer.getColumn(), sourceMapSourceIndex, sourceLine, sourceCharacter, + /*nameIndex*/ undefined); + } + function emitSourcePos(source, pos) { + if (source !== sourceMapSource) { + var savedSourceMapSource = sourceMapSource; + setSourceMapSource(source); + emitPos(pos); + setSourceMapSource(savedSourceMapSource); + } + else { + emitPos(pos); + } + } + /** + * Emits a token of a node with possible leading and trailing source maps. + * + * @param node The node containing the token. + * @param token The token to emit. + * @param tokenStartPos The start pos of the token. + * @param emitCallback The callback used to emit the token. + */ + function emitTokenWithSourceMap(node, token, writer, tokenPos, emitCallback) { + if (sourceMapsDisabled || node && ts.isInJsonFile(node)) { + return emitCallback(token, writer, tokenPos); + } + var emitNode = node && node.emitNode; + var emitFlags = emitNode && emitNode.flags || 0 /* None */; + var range = emitNode && emitNode.tokenSourceMapRanges && emitNode.tokenSourceMapRanges[token]; + var source = range && range.source || sourceMapSource; + tokenPos = skipSourceTrivia(source, range ? range.pos : tokenPos); + if ((emitFlags & 128 /* NoTokenLeadingSourceMaps */) === 0 && tokenPos >= 0) { + emitSourcePos(source, tokenPos); + } + tokenPos = emitCallback(token, writer, tokenPos); + if (range) + tokenPos = range.end; + if ((emitFlags & 256 /* NoTokenTrailingSourceMaps */) === 0 && tokenPos >= 0) { + emitSourcePos(source, tokenPos); + } + return tokenPos; + } + function setSourceMapSource(source) { + if (sourceMapsDisabled) { + return; + } + sourceMapSource = source; + if (isJsonSourceMapSource(source)) { + return; + } + sourceMapSourceIndex = sourceMapGenerator.addSource(source.fileName); + if (printerOptions.inlineSources) { + sourceMapGenerator.setSourceContent(sourceMapSourceIndex, source.text); + } + } + function isJsonSourceMapSource(sourceFile) { + return ts.fileExtensionIs(sourceFile.fileName, ".json" /* Json */); + } + } + ts.createPrinter = createPrinter; + function createBracketsMap() { + var brackets = []; + brackets[1024 /* Braces */] = ["{", "}"]; + brackets[2048 /* Parenthesis */] = ["(", ")"]; + brackets[4096 /* AngleBrackets */] = ["<", ">"]; + brackets[8192 /* SquareBrackets */] = ["[", "]"]; + return brackets; + } + function getOpeningBracket(format) { + return brackets[format & 15360 /* BracketsMask */][0]; + } + function getClosingBracket(format) { + return brackets[format & 15360 /* BracketsMask */][1]; + } + // Flags enum to track count of temp variables and a few dedicated names + var TempFlags; + (function (TempFlags) { + TempFlags[TempFlags["Auto"] = 0] = "Auto"; + TempFlags[TempFlags["CountMask"] = 268435455] = "CountMask"; + TempFlags[TempFlags["_i"] = 268435456] = "_i"; + })(TempFlags || (TempFlags = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + function createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensitiveFileNames) { + if (!host.getDirectories || !host.readDirectory) { + return undefined; + } + var cachedReadDirectoryResult = ts.createMap(); + var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); + return { + useCaseSensitiveFileNames: useCaseSensitiveFileNames, + fileExists: fileExists, + readFile: function (path, encoding) { return host.readFile(path, encoding); }, + directoryExists: host.directoryExists && directoryExists, + getDirectories: getDirectories, + readDirectory: readDirectory, + createDirectory: host.createDirectory && createDirectory, + writeFile: host.writeFile && writeFile, + addOrDeleteFileOrDirectory: addOrDeleteFileOrDirectory, + addOrDeleteFile: addOrDeleteFile, + clearCache: clearCache + }; + function toPath(fileName) { + return ts.toPath(fileName, currentDirectory, getCanonicalFileName); + } + function getCachedFileSystemEntries(rootDirPath) { + return cachedReadDirectoryResult.get(ts.ensureTrailingDirectorySeparator(rootDirPath)); + } + function getCachedFileSystemEntriesForBaseDir(path) { + return getCachedFileSystemEntries(ts.getDirectoryPath(path)); + } + function getBaseNameOfFileName(fileName) { + return ts.getBaseFileName(ts.normalizePath(fileName)); + } + function createCachedFileSystemEntries(rootDir, rootDirPath) { + var resultFromHost = { + files: ts.map(host.readDirectory(rootDir, /*extensions*/ undefined, /*exclude*/ undefined, /*include*/ ["*.*"]), getBaseNameOfFileName) || [], + directories: host.getDirectories(rootDir) || [] + }; + cachedReadDirectoryResult.set(ts.ensureTrailingDirectorySeparator(rootDirPath), resultFromHost); + return resultFromHost; + } + /** + * If the readDirectory result was already cached, it returns that + * Otherwise gets result from host and caches it. + * The host request is done under try catch block to avoid caching incorrect result + */ + function tryReadDirectory(rootDir, rootDirPath) { + rootDirPath = ts.ensureTrailingDirectorySeparator(rootDirPath); + var cachedResult = getCachedFileSystemEntries(rootDirPath); + if (cachedResult) { + return cachedResult; + } + try { + return createCachedFileSystemEntries(rootDir, rootDirPath); + } + catch (_e) { + // If there is exception to read directories, dont cache the result and direct the calls to host + ts.Debug.assert(!cachedReadDirectoryResult.has(ts.ensureTrailingDirectorySeparator(rootDirPath))); + return undefined; + } + } + function fileNameEqual(name1, name2) { + return getCanonicalFileName(name1) === getCanonicalFileName(name2); + } + function hasEntry(entries, name) { + return ts.some(entries, function (file) { return fileNameEqual(file, name); }); + } + function updateFileSystemEntry(entries, baseName, isValid) { + if (hasEntry(entries, baseName)) { + if (!isValid) { + return ts.filterMutate(entries, function (entry) { return !fileNameEqual(entry, baseName); }); + } + } + else if (isValid) { + return entries.push(baseName); + } + } + function writeFile(fileName, data, writeByteOrderMark) { + var path = toPath(fileName); + var result = getCachedFileSystemEntriesForBaseDir(path); + if (result) { + updateFilesOfFileSystemEntry(result, getBaseNameOfFileName(fileName), /*fileExists*/ true); + } + return host.writeFile(fileName, data, writeByteOrderMark); + } + function fileExists(fileName) { + var path = toPath(fileName); + var result = getCachedFileSystemEntriesForBaseDir(path); + return result && hasEntry(result.files, getBaseNameOfFileName(fileName)) || + host.fileExists(fileName); + } + function directoryExists(dirPath) { + var path = toPath(dirPath); + return cachedReadDirectoryResult.has(ts.ensureTrailingDirectorySeparator(path)) || host.directoryExists(dirPath); + } + function createDirectory(dirPath) { + var path = toPath(dirPath); + var result = getCachedFileSystemEntriesForBaseDir(path); + var baseFileName = getBaseNameOfFileName(dirPath); + if (result) { + updateFileSystemEntry(result.directories, baseFileName, /*isValid*/ true); + } + host.createDirectory(dirPath); + } + function getDirectories(rootDir) { + var rootDirPath = toPath(rootDir); + var result = tryReadDirectory(rootDir, rootDirPath); + if (result) { + return result.directories.slice(); + } + return host.getDirectories(rootDir); + } + function readDirectory(rootDir, extensions, excludes, includes, depth) { + var rootDirPath = toPath(rootDir); + var result = tryReadDirectory(rootDir, rootDirPath); + if (result) { + return ts.matchFiles(rootDir, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries); + } + return host.readDirectory(rootDir, extensions, excludes, includes, depth); + function getFileSystemEntries(dir) { + var path = toPath(dir); + if (path === rootDirPath) { + return result; + } + return tryReadDirectory(dir, path) || ts.emptyFileSystemEntries; + } + } + function addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath) { + var existingResult = getCachedFileSystemEntries(fileOrDirectoryPath); + if (existingResult) { + // Just clear the cache for now + // For now just clear the cache, since this could mean that multiple level entries might need to be re-evaluated + clearCache(); + return undefined; + } + var parentResult = getCachedFileSystemEntriesForBaseDir(fileOrDirectoryPath); + if (!parentResult) { + return undefined; + } + // This was earlier a file (hence not in cached directory contents) + // or we never cached the directory containing it + if (!host.directoryExists) { + // Since host doesnt support directory exists, clear the cache as otherwise it might not be same + clearCache(); + return undefined; + } + var baseName = getBaseNameOfFileName(fileOrDirectory); + var fsQueryResult = { + fileExists: host.fileExists(fileOrDirectoryPath), + directoryExists: host.directoryExists(fileOrDirectoryPath) + }; + if (fsQueryResult.directoryExists || hasEntry(parentResult.directories, baseName)) { + // Folder added or removed, clear the cache instead of updating the folder and its structure + clearCache(); + } + else { + // No need to update the directory structure, just files + updateFilesOfFileSystemEntry(parentResult, baseName, fsQueryResult.fileExists); + } + return fsQueryResult; + } + function addOrDeleteFile(fileName, filePath, eventKind) { + if (eventKind === ts.FileWatcherEventKind.Changed) { + return; + } + var parentResult = getCachedFileSystemEntriesForBaseDir(filePath); + if (parentResult) { + updateFilesOfFileSystemEntry(parentResult, getBaseNameOfFileName(fileName), eventKind === ts.FileWatcherEventKind.Created); + } + } + function updateFilesOfFileSystemEntry(parentResult, baseName, fileExists) { + updateFileSystemEntry(parentResult.files, baseName, fileExists); + } + function clearCache() { + cachedReadDirectoryResult.clear(); + } + } + ts.createCachedDirectoryStructureHost = createCachedDirectoryStructureHost; + var ConfigFileProgramReloadLevel; + (function (ConfigFileProgramReloadLevel) { + ConfigFileProgramReloadLevel[ConfigFileProgramReloadLevel["None"] = 0] = "None"; + /** Update the file name list from the disk */ + ConfigFileProgramReloadLevel[ConfigFileProgramReloadLevel["Partial"] = 1] = "Partial"; + /** Reload completely by re-reading contents of config file from disk and updating program */ + ConfigFileProgramReloadLevel[ConfigFileProgramReloadLevel["Full"] = 2] = "Full"; + })(ConfigFileProgramReloadLevel = ts.ConfigFileProgramReloadLevel || (ts.ConfigFileProgramReloadLevel = {})); + /** + * Updates the existing missing file watches with the new set of missing files after new program is created + */ + function updateMissingFilePathsWatch(program, missingFileWatches, createMissingFileWatch) { + var missingFilePaths = program.getMissingFilePaths(); + var newMissingFilePathMap = ts.arrayToSet(missingFilePaths); + // Update the missing file paths watcher + ts.mutateMap(missingFileWatches, newMissingFilePathMap, { + // Watch the missing files + createNewValue: createMissingFileWatch, + // Files that are no longer missing (e.g. because they are no longer required) + // should no longer be watched. + onDeleteValue: ts.closeFileWatcher + }); + } + ts.updateMissingFilePathsWatch = updateMissingFilePathsWatch; + /** + * Updates the existing wild card directory watches with the new set of wild card directories from the config file + * after new program is created because the config file was reloaded or program was created first time from the config file + * Note that there is no need to call this function when the program is updated with additional files without reloading config files, + * as wildcard directories wont change unless reloading config file + */ + function updateWatchingWildcardDirectories(existingWatchedForWildcards, wildcardDirectories, watchDirectory) { + ts.mutateMap(existingWatchedForWildcards, wildcardDirectories, { + // Create new watch and recursive info + createNewValue: createWildcardDirectoryWatcher, + // Close existing watch thats not needed any more + onDeleteValue: closeFileWatcherOf, + // Close existing watch that doesnt match in the flags + onExistingValue: updateWildcardDirectoryWatcher + }); + function createWildcardDirectoryWatcher(directory, flags) { + // Create new watch and recursive info + return { + watcher: watchDirectory(directory, flags), + flags: flags + }; + } + function updateWildcardDirectoryWatcher(existingWatcher, flags, directory) { + // Watcher needs to be updated if the recursive flags dont match + if (existingWatcher.flags === flags) { + return; + } + existingWatcher.watcher.close(); + existingWatchedForWildcards.set(directory, createWildcardDirectoryWatcher(directory, flags)); + } + } + ts.updateWatchingWildcardDirectories = updateWatchingWildcardDirectories; + function isEmittedFileOfProgram(program, file) { + if (!program) { + return false; + } + return program.isEmittedFile(file); + } + ts.isEmittedFileOfProgram = isEmittedFileOfProgram; + var WatchLogLevel; + (function (WatchLogLevel) { + WatchLogLevel[WatchLogLevel["None"] = 0] = "None"; + WatchLogLevel[WatchLogLevel["TriggerOnly"] = 1] = "TriggerOnly"; + WatchLogLevel[WatchLogLevel["Verbose"] = 2] = "Verbose"; + })(WatchLogLevel = ts.WatchLogLevel || (ts.WatchLogLevel = {})); + function getWatchFactory(watchLogLevel, log, getDetailWatchInfo) { + return getWatchFactoryWith(watchLogLevel, log, getDetailWatchInfo, watchFile, watchDirectory); + } + ts.getWatchFactory = getWatchFactory; + function getWatchFactoryWith(watchLogLevel, log, getDetailWatchInfo, watchFile, watchDirectory) { + var createFileWatcher = getCreateFileWatcher(watchLogLevel, watchFile); + var createFilePathWatcher = watchLogLevel === WatchLogLevel.None ? watchFilePath : createFileWatcher; + var createDirectoryWatcher = getCreateFileWatcher(watchLogLevel, watchDirectory); + return { + watchFile: function (host, file, callback, pollingInterval, detailInfo1, detailInfo2) { + return createFileWatcher(host, file, callback, pollingInterval, /*passThrough*/ undefined, detailInfo1, detailInfo2, watchFile, log, "FileWatcher", getDetailWatchInfo); + }, + watchFilePath: function (host, file, callback, pollingInterval, path, detailInfo1, detailInfo2) { + return createFilePathWatcher(host, file, callback, pollingInterval, path, detailInfo1, detailInfo2, watchFile, log, "FileWatcher", getDetailWatchInfo); + }, + watchDirectory: function (host, directory, callback, flags, detailInfo1, detailInfo2) { + return createDirectoryWatcher(host, directory, callback, flags, /*passThrough*/ undefined, detailInfo1, detailInfo2, watchDirectory, log, "DirectoryWatcher", getDetailWatchInfo); + } + }; + function watchFilePath(host, file, callback, pollingInterval, path) { + return watchFile(host, file, function (fileName, eventKind) { return callback(fileName, eventKind, path); }, pollingInterval); + } + } + function watchFile(host, file, callback, pollingInterval) { + return host.watchFile(file, callback, pollingInterval); + } + function watchDirectory(host, directory, callback, flags) { + return host.watchDirectory(directory, callback, (flags & 1 /* Recursive */) !== 0); + } + function getCreateFileWatcher(watchLogLevel, addWatch) { + switch (watchLogLevel) { + case WatchLogLevel.None: + return addWatch; + case WatchLogLevel.TriggerOnly: + return createFileWatcherWithTriggerLogging; + case WatchLogLevel.Verbose: + return addWatch === watchDirectory ? createDirectoryWatcherWithLogging : createFileWatcherWithLogging; + } + } + function createFileWatcherWithLogging(host, file, cb, flags, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo) { + log(watchCaption + ":: Added:: " + getWatchInfo(file, flags, detailInfo1, detailInfo2, getDetailWatchInfo)); + var watcher = createFileWatcherWithTriggerLogging(host, file, cb, flags, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo); + return { + close: function () { + log(watchCaption + ":: Close:: " + getWatchInfo(file, flags, detailInfo1, detailInfo2, getDetailWatchInfo)); + watcher.close(); + } + }; + } + function createDirectoryWatcherWithLogging(host, file, cb, flags, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo) { + var watchInfo = watchCaption + ":: Added:: " + getWatchInfo(file, flags, detailInfo1, detailInfo2, getDetailWatchInfo); + log(watchInfo); + var start = ts.timestamp(); + var watcher = createFileWatcherWithTriggerLogging(host, file, cb, flags, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo); + var elapsed = ts.timestamp() - start; + log("Elapsed:: " + elapsed + "ms " + watchInfo); + return { + close: function () { + var watchInfo = watchCaption + ":: Close:: " + getWatchInfo(file, flags, detailInfo1, detailInfo2, getDetailWatchInfo); + log(watchInfo); + var start = ts.timestamp(); + watcher.close(); + var elapsed = ts.timestamp() - start; + log("Elapsed:: " + elapsed + "ms " + watchInfo); + } + }; + } + function createFileWatcherWithTriggerLogging(host, file, cb, flags, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo) { + return addWatch(host, file, function (fileName, cbOptional) { + var triggerredInfo = watchCaption + ":: Triggered with " + fileName + " " + (cbOptional !== undefined ? cbOptional : "") + ":: " + getWatchInfo(file, flags, detailInfo1, detailInfo2, getDetailWatchInfo); + log(triggerredInfo); + var start = ts.timestamp(); + cb(fileName, cbOptional, passThrough); + var elapsed = ts.timestamp() - start; + log("Elapsed:: " + elapsed + "ms " + triggerredInfo); + }, flags); + } + function getWatchInfo(file, flags, detailInfo1, detailInfo2, getDetailWatchInfo) { + return "WatchInfo: " + file + " " + flags + " " + (getDetailWatchInfo ? getDetailWatchInfo(detailInfo1, detailInfo2) : detailInfo1); + } + function closeFileWatcherOf(objWithWatcher) { + objWithWatcher.watcher.close(); + } + ts.closeFileWatcherOf = closeFileWatcherOf; +})(ts || (ts = {})); +var ts; +(function (ts) { + var ignoreDiagnosticCommentRegEx = /(^\s*$)|(^\s*\/\/\/?\s*(@ts-ignore)?)/; + function findConfigFile(searchPath, fileExists, configName) { + if (configName === void 0) { configName = "tsconfig.json"; } + return ts.forEachAncestorDirectory(searchPath, function (ancestor) { + var fileName = ts.combinePaths(ancestor, configName); + return fileExists(fileName) ? fileName : undefined; + }); + } + ts.findConfigFile = findConfigFile; + function resolveTripleslashReference(moduleName, containingFile) { + var basePath = ts.getDirectoryPath(containingFile); + var referencedFileName = ts.isRootedDiskPath(moduleName) ? moduleName : ts.combinePaths(basePath, moduleName); + return ts.normalizePath(referencedFileName); + } + ts.resolveTripleslashReference = resolveTripleslashReference; + /* @internal */ + function computeCommonSourceDirectoryOfFilenames(fileNames, currentDirectory, getCanonicalFileName) { + var commonPathComponents; + var failed = ts.forEach(fileNames, function (sourceFile) { + // Each file contributes into common source file path + var sourcePathComponents = ts.getNormalizedPathComponents(sourceFile, currentDirectory); + sourcePathComponents.pop(); // The base file name is not part of the common directory path + if (!commonPathComponents) { + // first file + commonPathComponents = sourcePathComponents; + return; + } + var n = Math.min(commonPathComponents.length, sourcePathComponents.length); + for (var i = 0; i < n; i++) { + if (getCanonicalFileName(commonPathComponents[i]) !== getCanonicalFileName(sourcePathComponents[i])) { + if (i === 0) { + // Failed to find any common path component + return true; + } + // New common path found that is 0 -> i-1 + commonPathComponents.length = i; + break; + } + } + // If the sourcePathComponents was shorter than the commonPathComponents, truncate to the sourcePathComponents + if (sourcePathComponents.length < commonPathComponents.length) { + commonPathComponents.length = sourcePathComponents.length; + } + }); + // A common path can not be found when paths span multiple drives on windows, for example + if (failed) { + return ""; + } + if (!commonPathComponents) { // Can happen when all input files are .d.ts files + return currentDirectory; + } + return ts.getPathFromPathComponents(commonPathComponents); + } + ts.computeCommonSourceDirectoryOfFilenames = computeCommonSourceDirectoryOfFilenames; + function createCompilerHost(options, setParentNodes) { + return createCompilerHostWorker(options, setParentNodes); + } + ts.createCompilerHost = createCompilerHost; + /*@internal*/ + // TODO(shkamat): update this after reworking ts build API + function createCompilerHostWorker(options, setParentNodes, system) { + if (system === void 0) { system = ts.sys; } + var existingDirectories = ts.createMap(); + function getCanonicalFileName(fileName) { + // if underlying system can distinguish between two files whose names differs only in cases then file name already in canonical form. + // otherwise use toLowerCase as a canonical form. + return system.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); + } + function getSourceFile(fileName, languageVersion, onError) { + var text; + try { + ts.performance.mark("beforeIORead"); + text = compilerHost.readFile(fileName); + ts.performance.mark("afterIORead"); + ts.performance.measure("I/O Read", "beforeIORead", "afterIORead"); + } + catch (e) { + if (onError) { + onError(e.message); + } + text = ""; + } + return text !== undefined ? ts.createSourceFile(fileName, text, languageVersion, setParentNodes) : undefined; + } + function directoryExists(directoryPath) { + if (existingDirectories.has(directoryPath)) { + return true; + } + if (system.directoryExists(directoryPath)) { + existingDirectories.set(directoryPath, true); + return true; + } + return false; + } + function ensureDirectoriesExist(directoryPath) { + if (directoryPath.length > ts.getRootLength(directoryPath) && !directoryExists(directoryPath)) { + var parentDirectory = ts.getDirectoryPath(directoryPath); + ensureDirectoriesExist(parentDirectory); + if (compilerHost.createDirectory) { + compilerHost.createDirectory(directoryPath); + } + else { + system.createDirectory(directoryPath); + } + } + } + var outputFingerprints; + function writeFileIfUpdated(fileName, data, writeByteOrderMark) { + if (!outputFingerprints) { + outputFingerprints = ts.createMap(); + } + var hash = system.createHash(data); // TODO: GH#18217 + var mtimeBefore = system.getModifiedTime(fileName); // TODO: GH#18217 + if (mtimeBefore) { + var fingerprint = outputFingerprints.get(fileName); + // If output has not been changed, and the file has no external modification + if (fingerprint && + fingerprint.byteOrderMark === writeByteOrderMark && + fingerprint.hash === hash && + fingerprint.mtime.getTime() === mtimeBefore.getTime()) { + return; + } + } + system.writeFile(fileName, data, writeByteOrderMark); + var mtimeAfter = system.getModifiedTime(fileName) || ts.missingFileModifiedTime; // TODO: GH#18217 + outputFingerprints.set(fileName, { + hash: hash, + byteOrderMark: writeByteOrderMark, + mtime: mtimeAfter + }); + } + function writeFile(fileName, data, writeByteOrderMark, onError) { + try { + ts.performance.mark("beforeIOWrite"); + ensureDirectoriesExist(ts.getDirectoryPath(ts.normalizePath(fileName))); + if (ts.isWatchSet(options) && system.createHash && system.getModifiedTime) { + writeFileIfUpdated(fileName, data, writeByteOrderMark); + } + else { + system.writeFile(fileName, data, writeByteOrderMark); + } + ts.performance.mark("afterIOWrite"); + ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite"); + } + catch (e) { + if (onError) { + onError(e.message); + } + } + } + function getDefaultLibLocation() { + return ts.getDirectoryPath(ts.normalizePath(system.getExecutingFilePath())); + } + var newLine = ts.getNewLineCharacter(options, function () { return system.newLine; }); + var realpath = system.realpath && (function (path) { return system.realpath(path); }); + var compilerHost = { + getSourceFile: getSourceFile, + getDefaultLibLocation: getDefaultLibLocation, + getDefaultLibFileName: function (options) { return ts.combinePaths(getDefaultLibLocation(), ts.getDefaultLibFileName(options)); }, + writeFile: writeFile, + getCurrentDirectory: ts.memoize(function () { return system.getCurrentDirectory(); }), + useCaseSensitiveFileNames: function () { return system.useCaseSensitiveFileNames; }, + getCanonicalFileName: getCanonicalFileName, + getNewLine: function () { return newLine; }, + fileExists: function (fileName) { return system.fileExists(fileName); }, + readFile: function (fileName) { return system.readFile(fileName); }, + trace: function (s) { return system.write(s + newLine); }, + directoryExists: function (directoryName) { return system.directoryExists(directoryName); }, + getEnvironmentVariable: function (name) { return system.getEnvironmentVariable ? system.getEnvironmentVariable(name) : ""; }, + getDirectories: function (path) { return system.getDirectories(path); }, + realpath: realpath, + readDirectory: function (path, extensions, include, exclude, depth) { return system.readDirectory(path, extensions, include, exclude, depth); }, + createDirectory: function (d) { return system.createDirectory(d); } + }; + return compilerHost; + } + ts.createCompilerHostWorker = createCompilerHostWorker; + /*@internal*/ + function changeCompilerHostToUseCache(host, toPath, useCacheForSourceFile) { + var originalReadFile = host.readFile; + var originalFileExists = host.fileExists; + var originalDirectoryExists = host.directoryExists; + var originalCreateDirectory = host.createDirectory; + var originalWriteFile = host.writeFile; + var originalGetSourceFile = host.getSourceFile; + var readFileCache = ts.createMap(); + var fileExistsCache = ts.createMap(); + var directoryExistsCache = ts.createMap(); + var sourceFileCache = ts.createMap(); + var readFileWithCache = function (fileName) { + var key = toPath(fileName); + var value = readFileCache.get(key); + if (value !== undefined) + return value || undefined; + return setReadFileCache(key, fileName); + }; + var setReadFileCache = function (key, fileName) { + var newValue = originalReadFile.call(host, fileName); + readFileCache.set(key, newValue || false); + return newValue; + }; + host.readFile = function (fileName) { + var key = toPath(fileName); + var value = readFileCache.get(key); + if (value !== undefined) + return value; // could be .d.ts from output + if (!ts.fileExtensionIs(fileName, ".json" /* Json */)) { + return originalReadFile.call(host, fileName); + } + return setReadFileCache(key, fileName); + }; + if (useCacheForSourceFile) { + host.getSourceFile = function (fileName, languageVersion, onError, shouldCreateNewSourceFile) { + var key = toPath(fileName); + var value = sourceFileCache.get(key); + if (value) + return value; + var sourceFile = originalGetSourceFile.call(host, fileName, languageVersion, onError, shouldCreateNewSourceFile); + if (sourceFile && (ts.isDeclarationFileName(fileName) || ts.fileExtensionIs(fileName, ".json" /* Json */))) { + sourceFileCache.set(key, sourceFile); + } + return sourceFile; + }; + } + // fileExists for any kind of extension + host.fileExists = function (fileName) { + var key = toPath(fileName); + var value = fileExistsCache.get(key); + if (value !== undefined) + return value; + var newValue = originalFileExists.call(host, fileName); + fileExistsCache.set(key, !!newValue); + return newValue; + }; + host.writeFile = function (fileName, data, writeByteOrderMark, onError, sourceFiles) { + var key = toPath(fileName); + fileExistsCache.delete(key); + var value = readFileCache.get(key); + if (value && value !== data) { + readFileCache.delete(key); + sourceFileCache.delete(key); + } + else if (useCacheForSourceFile) { + var sourceFile = sourceFileCache.get(key); + if (sourceFile && sourceFile.text !== data) { + sourceFileCache.delete(key); + } + } + originalWriteFile.call(host, fileName, data, writeByteOrderMark, onError, sourceFiles); + }; + // directoryExists + if (originalDirectoryExists && originalCreateDirectory) { + host.directoryExists = function (directory) { + var key = toPath(directory); + var value = directoryExistsCache.get(key); + if (value !== undefined) + return value; + var newValue = originalDirectoryExists.call(host, directory); + directoryExistsCache.set(key, !!newValue); + return newValue; + }; + host.createDirectory = function (directory) { + var key = toPath(directory); + directoryExistsCache.delete(key); + originalCreateDirectory.call(host, directory); + }; + } + return { + originalReadFile: originalReadFile, + originalFileExists: originalFileExists, + originalDirectoryExists: originalDirectoryExists, + originalCreateDirectory: originalCreateDirectory, + originalWriteFile: originalWriteFile, + originalGetSourceFile: originalGetSourceFile, + readFileWithCache: readFileWithCache + }; + } + ts.changeCompilerHostToUseCache = changeCompilerHostToUseCache; + function getPreEmitDiagnostics(program, sourceFile, cancellationToken) { + var diagnostics = program.getConfigFileParsingDiagnostics().concat(program.getOptionsDiagnostics(cancellationToken), program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken)); + if (ts.getEmitDeclarations(program.getCompilerOptions())) { + ts.addRange(diagnostics, program.getDeclarationDiagnostics(sourceFile, cancellationToken)); + } + return ts.sortAndDeduplicateDiagnostics(diagnostics); + } + ts.getPreEmitDiagnostics = getPreEmitDiagnostics; + function formatDiagnostics(diagnostics, host) { + var output = ""; + for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { + var diagnostic = diagnostics_2[_i]; + output += formatDiagnostic(diagnostic, host); + } + return output; + } + ts.formatDiagnostics = formatDiagnostics; + function formatDiagnostic(diagnostic, host) { + var errorMessage = ts.diagnosticCategoryName(diagnostic) + " TS" + diagnostic.code + ": " + flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine()) + host.getNewLine(); + if (diagnostic.file) { + var _a = ts.getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start), line = _a.line, character = _a.character; // TODO: GH#18217 + var fileName = diagnostic.file.fileName; + var relativeFileName = ts.convertToRelativePath(fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); }); + return relativeFileName + "(" + (line + 1) + "," + (character + 1) + "): " + errorMessage; + } + return errorMessage; + } + ts.formatDiagnostic = formatDiagnostic; + /** @internal */ + var ForegroundColorEscapeSequences; + (function (ForegroundColorEscapeSequences) { + ForegroundColorEscapeSequences["Grey"] = "\u001B[90m"; + ForegroundColorEscapeSequences["Red"] = "\u001B[91m"; + ForegroundColorEscapeSequences["Yellow"] = "\u001B[93m"; + ForegroundColorEscapeSequences["Blue"] = "\u001B[94m"; + ForegroundColorEscapeSequences["Cyan"] = "\u001B[96m"; + })(ForegroundColorEscapeSequences = ts.ForegroundColorEscapeSequences || (ts.ForegroundColorEscapeSequences = {})); + var gutterStyleSequence = "\u001b[7m"; + var gutterSeparator = " "; + var resetEscapeSequence = "\u001b[0m"; + var ellipsis = "..."; + var halfIndent = " "; + var indent = " "; + function getCategoryFormat(category) { + switch (category) { + case ts.DiagnosticCategory.Error: return ForegroundColorEscapeSequences.Red; + case ts.DiagnosticCategory.Warning: return ForegroundColorEscapeSequences.Yellow; + case ts.DiagnosticCategory.Suggestion: return ts.Debug.fail("Should never get an Info diagnostic on the command line."); + case ts.DiagnosticCategory.Message: return ForegroundColorEscapeSequences.Blue; + } + } + /** @internal */ + function formatColorAndReset(text, formatStyle) { + return formatStyle + text + resetEscapeSequence; + } + ts.formatColorAndReset = formatColorAndReset; + function padLeft(s, length) { + while (s.length < length) { + s = " " + s; + } + return s; + } + function formatCodeSpan(file, start, length, indent, squiggleColor, host) { + var _a = ts.getLineAndCharacterOfPosition(file, start), firstLine = _a.line, firstLineChar = _a.character; + var _b = ts.getLineAndCharacterOfPosition(file, start + length), lastLine = _b.line, lastLineChar = _b.character; + var lastLineInFile = ts.getLineAndCharacterOfPosition(file, file.text.length).line; + var hasMoreThanFiveLines = (lastLine - firstLine) >= 4; + var gutterWidth = (lastLine + 1 + "").length; + if (hasMoreThanFiveLines) { + gutterWidth = Math.max(ellipsis.length, gutterWidth); + } + var context = ""; + for (var i = firstLine; i <= lastLine; i++) { + context += host.getNewLine(); + // If the error spans over 5 lines, we'll only show the first 2 and last 2 lines, + // so we'll skip ahead to the second-to-last line. + if (hasMoreThanFiveLines && firstLine + 1 < i && i < lastLine - 1) { + context += indent + formatColorAndReset(padLeft(ellipsis, gutterWidth), gutterStyleSequence) + gutterSeparator + host.getNewLine(); + i = lastLine - 1; + } + var lineStart = ts.getPositionOfLineAndCharacter(file, i, 0); + var lineEnd = i < lastLineInFile ? ts.getPositionOfLineAndCharacter(file, i + 1, 0) : file.text.length; + var lineContent = file.text.slice(lineStart, lineEnd); + lineContent = lineContent.replace(/\s+$/g, ""); // trim from end + lineContent = lineContent.replace("\t", " "); // convert tabs to single spaces + // Output the gutter and the actual contents of the line. + context += indent + formatColorAndReset(padLeft(i + 1 + "", gutterWidth), gutterStyleSequence) + gutterSeparator; + context += lineContent + host.getNewLine(); + // Output the gutter and the error span for the line using tildes. + context += indent + formatColorAndReset(padLeft("", gutterWidth), gutterStyleSequence) + gutterSeparator; + context += squiggleColor; + if (i === firstLine) { + // If we're on the last line, then limit it to the last character of the last line. + // Otherwise, we'll just squiggle the rest of the line, giving 'slice' no end position. + var lastCharForLine = i === lastLine ? lastLineChar : undefined; + context += lineContent.slice(0, firstLineChar).replace(/\S/g, " "); + context += lineContent.slice(firstLineChar, lastCharForLine).replace(/./g, "~"); + } + else if (i === lastLine) { + context += lineContent.slice(0, lastLineChar).replace(/./g, "~"); + } + else { + // Squiggle the entire line. + context += lineContent.replace(/./g, "~"); + } + context += resetEscapeSequence; + } + return context; + } + /* @internal */ + function formatLocation(file, start, host, color) { + if (color === void 0) { color = formatColorAndReset; } + var _a = ts.getLineAndCharacterOfPosition(file, start), firstLine = _a.line, firstLineChar = _a.character; // TODO: GH#18217 + var relativeFileName = host ? ts.convertToRelativePath(file.fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); }) : file.fileName; + var output = ""; + output += color(relativeFileName, ForegroundColorEscapeSequences.Cyan); + output += ":"; + output += color("" + (firstLine + 1), ForegroundColorEscapeSequences.Yellow); + output += ":"; + output += color("" + (firstLineChar + 1), ForegroundColorEscapeSequences.Yellow); + return output; + } + ts.formatLocation = formatLocation; + function formatDiagnosticsWithColorAndContext(diagnostics, host) { + var output = ""; + for (var _i = 0, diagnostics_3 = diagnostics; _i < diagnostics_3.length; _i++) { + var diagnostic = diagnostics_3[_i]; + if (diagnostic.file) { + var file = diagnostic.file, start = diagnostic.start; + output += formatLocation(file, start, host); // TODO: GH#18217 + output += " - "; + } + output += formatColorAndReset(ts.diagnosticCategoryName(diagnostic), getCategoryFormat(diagnostic.category)); + output += formatColorAndReset(" TS" + diagnostic.code + ": ", ForegroundColorEscapeSequences.Grey); + output += flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine()); + if (diagnostic.file) { + output += host.getNewLine(); + output += formatCodeSpan(diagnostic.file, diagnostic.start, diagnostic.length, "", getCategoryFormat(diagnostic.category), host); // TODO: GH#18217 + if (diagnostic.relatedInformation) { + output += host.getNewLine(); + for (var _a = 0, _b = diagnostic.relatedInformation; _a < _b.length; _a++) { + var _c = _b[_a], file = _c.file, start = _c.start, length_4 = _c.length, messageText = _c.messageText; + if (file) { + output += host.getNewLine(); + output += halfIndent + formatLocation(file, start, host); // TODO: GH#18217 + output += formatCodeSpan(file, start, length_4, indent, ForegroundColorEscapeSequences.Cyan, host); // TODO: GH#18217 + } + output += host.getNewLine(); + output += indent + flattenDiagnosticMessageText(messageText, host.getNewLine()); + } + } + } + output += host.getNewLine(); + } + return output; + } + ts.formatDiagnosticsWithColorAndContext = formatDiagnosticsWithColorAndContext; + function flattenDiagnosticMessageText(messageText, newLine) { + if (ts.isString(messageText)) { + return messageText; + } + else { + var diagnosticChain = messageText; + var result = ""; + var indent_1 = 0; + while (diagnosticChain) { + if (indent_1) { + result += newLine; + for (var i = 0; i < indent_1; i++) { + result += " "; + } + } + result += diagnosticChain.messageText; + indent_1++; + diagnosticChain = diagnosticChain.next; + } + return result; + } + } + ts.flattenDiagnosticMessageText = flattenDiagnosticMessageText; + function loadWithLocalCache(names, containingFile, redirectedReference, loader) { + if (names.length === 0) { + return []; + } + var resolutions = []; + var cache = ts.createMap(); + for (var _i = 0, names_1 = names; _i < names_1.length; _i++) { + var name = names_1[_i]; + var result = void 0; + if (cache.has(name)) { + result = cache.get(name); + } + else { + cache.set(name, result = loader(name, containingFile, redirectedReference)); + } + resolutions.push(result); + } + return resolutions; + } + /** + * Determines if program structure is upto date or needs to be recreated + */ + /* @internal */ + function isProgramUptoDate(program, rootFileNames, newOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, projectReferences) { + // If we haven't created a program yet or have changed automatic type directives, then it is not up-to-date + if (!program || hasChangedAutomaticTypeDirectiveNames) { + return false; + } + // If number of files in the program do not match, it is not up-to-date + if (program.getRootFileNames().length !== rootFileNames.length) { + return false; + } + var seenResolvedRefs; + // If project references dont match + if (!ts.arrayIsEqualTo(program.getProjectReferences(), projectReferences, projectReferenceUptoDate)) { + return false; + } + // If any file is not up-to-date, then the whole program is not up-to-date + if (program.getSourceFiles().some(sourceFileNotUptoDate)) { + return false; + } + // If any of the missing file paths are now created + if (program.getMissingFilePaths().some(fileExists)) { + return false; + } + var currentOptions = program.getCompilerOptions(); + // If the compilation settings do no match, then the program is not up-to-date + if (!ts.compareDataObjects(currentOptions, newOptions)) { + return false; + } + // If everything matches but the text of config file is changed, + // error locations can change for program options, so update the program + if (currentOptions.configFile && newOptions.configFile) { + return currentOptions.configFile.text === newOptions.configFile.text; + } + return true; + function sourceFileNotUptoDate(sourceFile) { + return !sourceFileVersionUptoDate(sourceFile) || + hasInvalidatedResolution(sourceFile.path); + } + function sourceFileVersionUptoDate(sourceFile) { + return sourceFile.version === getSourceVersion(sourceFile.resolvedPath); + } + function projectReferenceUptoDate(oldRef, newRef, index) { + if (!ts.projectReferenceIsEqualTo(oldRef, newRef)) { + return false; + } + return resolvedProjectReferenceUptoDate(program.getResolvedProjectReferences()[index], oldRef); + } + function resolvedProjectReferenceUptoDate(oldResolvedRef, oldRef) { + if (oldResolvedRef) { + if (ts.contains(seenResolvedRefs, oldResolvedRef)) { + // Assume true + return true; + } + // If sourceFile for the oldResolvedRef existed, check the version for uptodate + if (!sourceFileVersionUptoDate(oldResolvedRef.sourceFile)) { + return false; + } + // Add to seen before checking the referenced paths of this config file + (seenResolvedRefs || (seenResolvedRefs = [])).push(oldResolvedRef); + // If child project references are upto date, this project reference is uptodate + return !ts.forEach(oldResolvedRef.references, function (childResolvedRef, index) { + return !resolvedProjectReferenceUptoDate(childResolvedRef, oldResolvedRef.commandLine.projectReferences[index]); + }); + } + // In old program, not able to resolve project reference path, + // so if config file doesnt exist, it is uptodate. + return !fileExists(resolveProjectReferencePath(oldRef)); + } + } + ts.isProgramUptoDate = isProgramUptoDate; + function getConfigFileParsingDiagnostics(configFileParseResult) { + return configFileParseResult.options.configFile ? configFileParseResult.options.configFile.parseDiagnostics.concat(configFileParseResult.errors) : + configFileParseResult.errors; + } + ts.getConfigFileParsingDiagnostics = getConfigFileParsingDiagnostics; + /** + * Determine if source file needs to be re-created even if its text hasn't changed + */ + function shouldProgramCreateNewSourceFiles(program, newOptions) { + if (!program) + return false; + // If any compiler options change, we can't reuse old source file even if version match + // The change in options like these could result in change in syntax tree or `sourceFile.bindDiagnostics`. + var oldOptions = program.getCompilerOptions(); + return !!ts.sourceFileAffectingCompilerOptions.some(function (option) { + return !ts.isJsonEqual(ts.getCompilerOptionValue(oldOptions, option), ts.getCompilerOptionValue(newOptions, option)); + }); + } + function createCreateProgramOptions(rootNames, options, host, oldProgram, configFileParsingDiagnostics) { + return { + rootNames: rootNames, + options: options, + host: host, + oldProgram: oldProgram, + configFileParsingDiagnostics: configFileParsingDiagnostics + }; + } + function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _configFileParsingDiagnostics) { + var createProgramOptions = ts.isArray(rootNamesOrOptions) ? createCreateProgramOptions(rootNamesOrOptions, _options, _host, _oldProgram, _configFileParsingDiagnostics) : rootNamesOrOptions; // TODO: GH#18217 + var rootNames = createProgramOptions.rootNames, options = createProgramOptions.options, configFileParsingDiagnostics = createProgramOptions.configFileParsingDiagnostics, projectReferences = createProgramOptions.projectReferences; + var oldProgram = createProgramOptions.oldProgram; + var program; + var processingDefaultLibFiles; + var processingOtherFiles; + var files; + var commonSourceDirectory; + var diagnosticsProducingTypeChecker; + var noDiagnosticsTypeChecker; + var classifiableNames; + var ambientModuleNameToUnmodifiedFileName = ts.createMap(); + var cachedSemanticDiagnosticsForFile = {}; + var cachedDeclarationDiagnosticsForFile = {}; + var resolvedTypeReferenceDirectives = ts.createMap(); + var fileProcessingDiagnostics = ts.createDiagnosticCollection(); + // The below settings are to track if a .js file should be add to the program if loaded via searching under node_modules. + // This works as imported modules are discovered recursively in a depth first manner, specifically: + // - For each root file, findSourceFile is called. + // - This calls processImportedModules for each module imported in the source file. + // - This calls resolveModuleNames, and then calls findSourceFile for each resolved module. + // As all these operations happen - and are nested - within the createProgram call, they close over the below variables. + // The current resolution depth is tracked by incrementing/decrementing as the depth first search progresses. + var maxNodeModuleJsDepth = typeof options.maxNodeModuleJsDepth === "number" ? options.maxNodeModuleJsDepth : 0; + var currentNodeModulesDepth = 0; + // If a module has some of its imports skipped due to being at the depth limit under node_modules, then track + // this, as it may be imported at a shallower depth later, and then it will need its skipped imports processed. + var modulesWithElidedImports = ts.createMap(); + // Track source files that are source files found by searching under node_modules, as these shouldn't be compiled. + var sourceFilesFoundSearchingNodeModules = ts.createMap(); + ts.performance.mark("beforeProgram"); + var host = createProgramOptions.host || createCompilerHost(options); + var configParsingHost = parseConfigHostFromCompilerHost(host); + var skipDefaultLib = options.noLib; + var getDefaultLibraryFileName = ts.memoize(function () { return host.getDefaultLibFileName(options); }); + var defaultLibraryPath = host.getDefaultLibLocation ? host.getDefaultLibLocation() : ts.getDirectoryPath(getDefaultLibraryFileName()); + var programDiagnostics = ts.createDiagnosticCollection(); + var currentDirectory = host.getCurrentDirectory(); + var supportedExtensions = ts.getSupportedExtensions(options); + var supportedExtensionsWithJsonIfResolveJsonModule = ts.getSuppoertedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions); + // Map storing if there is emit blocking diagnostics for given input + var hasEmitBlockingDiagnostics = ts.createMap(); + var _compilerOptionsObjectLiteralSyntax; + var moduleResolutionCache; + var resolveModuleNamesWorker; + var hasInvalidatedResolution = host.hasInvalidatedResolution || ts.returnFalse; + if (host.resolveModuleNames) { + resolveModuleNamesWorker = function (moduleNames, containingFile, reusedNames, redirectedReference) { return host.resolveModuleNames(ts.Debug.assertEachDefined(moduleNames), containingFile, reusedNames, redirectedReference).map(function (resolved) { + // An older host may have omitted extension, in which case we should infer it from the file extension of resolvedFileName. + if (!resolved || resolved.extension !== undefined) { + return resolved; + } + var withExtension = ts.clone(resolved); + withExtension.extension = ts.extensionFromPath(resolved.resolvedFileName); + return withExtension; + }); }; + } + else { + moduleResolutionCache = ts.createModuleResolutionCache(currentDirectory, function (x) { return host.getCanonicalFileName(x); }); + var loader_1 = function (moduleName, containingFile, redirectedReference) { return ts.resolveModuleName(moduleName, containingFile, options, host, moduleResolutionCache, redirectedReference).resolvedModule; }; // TODO: GH#18217 + resolveModuleNamesWorker = function (moduleNames, containingFile, _reusedNames, redirectedReference) { return loadWithLocalCache(ts.Debug.assertEachDefined(moduleNames), containingFile, redirectedReference, loader_1); }; + } + var resolveTypeReferenceDirectiveNamesWorker; + if (host.resolveTypeReferenceDirectives) { + resolveTypeReferenceDirectiveNamesWorker = function (typeDirectiveNames, containingFile, redirectedReference) { return host.resolveTypeReferenceDirectives(ts.Debug.assertEachDefined(typeDirectiveNames), containingFile, redirectedReference); }; + } + else { + var loader_2 = function (typesRef, containingFile, redirectedReference) { return ts.resolveTypeReferenceDirective(typesRef, containingFile, options, host, redirectedReference).resolvedTypeReferenceDirective; }; // TODO: GH#18217 + resolveTypeReferenceDirectiveNamesWorker = function (typeReferenceDirectiveNames, containingFile, redirectedReference) { return loadWithLocalCache(ts.Debug.assertEachDefined(typeReferenceDirectiveNames), containingFile, redirectedReference, loader_2); }; + } + // Map from a stringified PackageId to the source file with that id. + // Only one source file may have a given packageId. Others become redirects (see createRedirectSourceFile). + // `packageIdToSourceFile` is only used while building the program, while `sourceFileToPackageName` and `isSourceFileTargetOfRedirect` are kept around. + var packageIdToSourceFile = ts.createMap(); + // Maps from a SourceFile's `.path` to the name of the package it was imported with. + var sourceFileToPackageName = ts.createMap(); + // Key is a file name. Value is the (non-empty, or undefined) list of files that redirect to it. + var redirectTargetsMap = ts.createMultiMap(); + var filesByName = ts.createMap(); + var missingFilePaths; + // stores 'filename -> file association' ignoring case + // used to track cases when two file names differ only in casing + var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createMap() : undefined; + // A parallel array to projectReferences storing the results of reading in the referenced tsconfig files + var resolvedProjectReferences; + var projectReferenceRedirects; + var mapFromFileToProjectReferenceRedirects; + var shouldCreateNewSourceFile = shouldProgramCreateNewSourceFiles(oldProgram, options); + var structuralIsReused = tryReuseStructureFromOldProgram(); + if (structuralIsReused !== 2 /* Completely */) { + processingDefaultLibFiles = []; + processingOtherFiles = []; + if (projectReferences) { + if (!resolvedProjectReferences) { + resolvedProjectReferences = projectReferences.map(parseProjectReferenceConfigFile); + } + if (rootNames.length) { + for (var _i = 0, resolvedProjectReferences_1 = resolvedProjectReferences; _i < resolvedProjectReferences_1.length; _i++) { + var parsedRef = resolvedProjectReferences_1[_i]; + if (parsedRef) { + var out = parsedRef.commandLine.options.outFile || parsedRef.commandLine.options.out; + if (out) { + var dtsOutfile = ts.changeExtension(out, ".d.ts"); + processSourceFile(dtsOutfile, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined); + } + } + } + } + } + ts.forEach(rootNames, function (name) { return processRootFile(name, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false); }); + // load type declarations specified via 'types' argument or implicitly from types/ and node_modules/@types folders + var typeReferences = rootNames.length ? ts.getAutomaticTypeDirectiveNames(options, host) : ts.emptyArray; + if (typeReferences.length) { + // This containingFilename needs to match with the one used in managed-side + var containingDirectory = options.configFilePath ? ts.getDirectoryPath(options.configFilePath) : host.getCurrentDirectory(); + var containingFilename = ts.combinePaths(containingDirectory, "__inferred type names__.ts"); + var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeReferences, containingFilename); + for (var i = 0; i < typeReferences.length; i++) { + processTypeReferenceDirective(typeReferences[i], resolutions[i]); + } + } + // Do not process the default library if: + // - The '--noLib' flag is used. + // - A 'no-default-lib' reference comment is encountered in + // processing the root files. + if (rootNames.length && !skipDefaultLib) { + // If '--lib' is not specified, include default library file according to '--target' + // otherwise, using options specified in '--lib' instead of '--target' default library file + var defaultLibraryFileName = getDefaultLibraryFileName(); + if (!options.lib && defaultLibraryFileName) { + processRootFile(defaultLibraryFileName, /*isDefaultLib*/ true, /*ignoreNoDefaultLib*/ false); + } + else { + ts.forEach(options.lib, function (libFileName) { + processRootFile(ts.combinePaths(defaultLibraryPath, libFileName), /*isDefaultLib*/ true, /*ignoreNoDefaultLib*/ false); + }); + } + } + missingFilePaths = ts.arrayFrom(filesByName.keys(), function (p) { return p; }).filter(function (p) { return !filesByName.get(p); }); + files = ts.stableSort(processingDefaultLibFiles, compareDefaultLibFiles).concat(processingOtherFiles); + processingDefaultLibFiles = undefined; + processingOtherFiles = undefined; + } + ts.Debug.assert(!!missingFilePaths); + // Release any files we have acquired in the old program but are + // not part of the new program. + if (oldProgram && host.onReleaseOldSourceFile) { + var oldSourceFiles = oldProgram.getSourceFiles(); + for (var _a = 0, oldSourceFiles_1 = oldSourceFiles; _a < oldSourceFiles_1.length; _a++) { + var oldSourceFile = oldSourceFiles_1[_a]; + var newFile = getSourceFileByPath(oldSourceFile.resolvedPath); + if (shouldCreateNewSourceFile || !newFile || + // old file wasnt redirect but new file is + (oldSourceFile.resolvedPath === oldSourceFile.path && newFile.resolvedPath !== oldSourceFile.path)) { + host.onReleaseOldSourceFile(oldSourceFile, oldProgram.getCompilerOptions(), !!getSourceFileByPath(oldSourceFile.path)); + } + } + oldProgram.forEachResolvedProjectReference(function (resolvedProjectReference, resolvedProjectReferencePath) { + if (resolvedProjectReference && !getResolvedProjectReferenceByPath(resolvedProjectReferencePath)) { + host.onReleaseOldSourceFile(resolvedProjectReference.sourceFile, oldProgram.getCompilerOptions(), /*hasSourceFileByPath*/ false); + } + }); + } + // unconditionally set oldProgram to undefined to prevent it from being captured in closure + oldProgram = undefined; + program = { + getRootFileNames: function () { return rootNames; }, + getSourceFile: getSourceFile, + getSourceFileByPath: getSourceFileByPath, + getSourceFiles: function () { return files; }, + getMissingFilePaths: function () { return missingFilePaths; }, + getCompilerOptions: function () { return options; }, + getSyntacticDiagnostics: getSyntacticDiagnostics, + getOptionsDiagnostics: getOptionsDiagnostics, + getGlobalDiagnostics: getGlobalDiagnostics, + getSemanticDiagnostics: getSemanticDiagnostics, + getSuggestionDiagnostics: getSuggestionDiagnostics, + getDeclarationDiagnostics: getDeclarationDiagnostics, + getTypeChecker: getTypeChecker, + getClassifiableNames: getClassifiableNames, + getDiagnosticsProducingTypeChecker: getDiagnosticsProducingTypeChecker, + getCommonSourceDirectory: getCommonSourceDirectory, + emit: emit, + getCurrentDirectory: function () { return currentDirectory; }, + getNodeCount: function () { return getDiagnosticsProducingTypeChecker().getNodeCount(); }, + getIdentifierCount: function () { return getDiagnosticsProducingTypeChecker().getIdentifierCount(); }, + getSymbolCount: function () { return getDiagnosticsProducingTypeChecker().getSymbolCount(); }, + getTypeCount: function () { return getDiagnosticsProducingTypeChecker().getTypeCount(); }, + getFileProcessingDiagnostics: function () { return fileProcessingDiagnostics; }, + getResolvedTypeReferenceDirectives: function () { return resolvedTypeReferenceDirectives; }, + isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary, + isSourceFileDefaultLibrary: isSourceFileDefaultLibrary, + dropDiagnosticsProducingTypeChecker: dropDiagnosticsProducingTypeChecker, + getSourceFileFromReference: getSourceFileFromReference, + getLibFileFromReference: getLibFileFromReference, + sourceFileToPackageName: sourceFileToPackageName, + redirectTargetsMap: redirectTargetsMap, + isEmittedFile: isEmittedFile, + getConfigFileParsingDiagnostics: getConfigFileParsingDiagnostics, + getResolvedModuleWithFailedLookupLocationsFromCache: getResolvedModuleWithFailedLookupLocationsFromCache, + getProjectReferences: getProjectReferences, + getResolvedProjectReferences: getResolvedProjectReferences, + getProjectReferenceRedirect: getProjectReferenceRedirect, + getResolvedProjectReferenceToRedirect: getResolvedProjectReferenceToRedirect, + getResolvedProjectReferenceByPath: getResolvedProjectReferenceByPath, + forEachResolvedProjectReference: forEachResolvedProjectReference + }; + verifyCompilerOptions(); + ts.performance.mark("afterProgram"); + ts.performance.measure("Program", "beforeProgram", "afterProgram"); + return program; + function compareDefaultLibFiles(a, b) { + return ts.compareValues(getDefaultLibFilePriority(a), getDefaultLibFilePriority(b)); + } + function getDefaultLibFilePriority(a) { + if (ts.containsPath(defaultLibraryPath, a.fileName, /*ignoreCase*/ false)) { + var basename = ts.getBaseFileName(a.fileName); + if (basename === "lib.d.ts" || basename === "lib.es6.d.ts") + return 0; + var name = ts.removeSuffix(ts.removePrefix(basename, "lib."), ".d.ts"); + var index = ts.libs.indexOf(name); + if (index !== -1) + return index + 1; + } + return ts.libs.length + 2; + } + function getResolvedModuleWithFailedLookupLocationsFromCache(moduleName, containingFile) { + return moduleResolutionCache && ts.resolveModuleNameFromCache(moduleName, containingFile, moduleResolutionCache); + } + function toPath(fileName) { + return ts.toPath(fileName, currentDirectory, getCanonicalFileName); + } + function getCommonSourceDirectory() { + if (commonSourceDirectory === undefined) { + var emittedFiles = ts.filter(files, function (file) { return ts.sourceFileMayBeEmitted(file, options, isSourceFileFromExternalLibrary); }); + if (options.rootDir && checkSourceFilesBelongToPath(emittedFiles, options.rootDir)) { + // If a rootDir is specified use it as the commonSourceDirectory + commonSourceDirectory = ts.getNormalizedAbsolutePath(options.rootDir, currentDirectory); + } + else if (options.composite && options.configFilePath) { + // Project compilations never infer their root from the input source paths + commonSourceDirectory = ts.getDirectoryPath(ts.normalizeSlashes(options.configFilePath)); + checkSourceFilesBelongToPath(emittedFiles, commonSourceDirectory); + } + else { + commonSourceDirectory = computeCommonSourceDirectory(emittedFiles); + } + if (commonSourceDirectory && commonSourceDirectory[commonSourceDirectory.length - 1] !== ts.directorySeparator) { + // Make sure directory path ends with directory separator so this string can directly + // used to replace with "" to get the relative path of the source file and the relative path doesn't + // start with / making it rooted path + commonSourceDirectory += ts.directorySeparator; + } + } + return commonSourceDirectory; + } + function getClassifiableNames() { + if (!classifiableNames) { + // Initialize a checker so that all our files are bound. + getTypeChecker(); + classifiableNames = ts.createUnderscoreEscapedMap(); + for (var _i = 0, files_2 = files; _i < files_2.length; _i++) { + var sourceFile = files_2[_i]; + ts.copyEntries(sourceFile.classifiableNames, classifiableNames); + } + } + return classifiableNames; + } + function resolveModuleNamesReusingOldState(moduleNames, containingFile, file) { + if (structuralIsReused === 0 /* Not */ && !file.ambientModuleNames.length) { + // If the old program state does not permit reusing resolutions and `file` does not contain locally defined ambient modules, + // the best we can do is fallback to the default logic. + return resolveModuleNamesWorker(moduleNames, containingFile, /*reusedNames*/ undefined, getResolvedProjectReferenceToRedirect(file.originalFileName)); + } + var oldSourceFile = oldProgram && oldProgram.getSourceFile(containingFile); + if (oldSourceFile !== file && file.resolvedModules) { + // `file` was created for the new program. + // + // We only set `file.resolvedModules` via work from the current function, + // so it is defined iff we already called the current function on `file`. + // That call happened no later than the creation of the `file` object, + // which per above occurred during the current program creation. + // Since we assume the filesystem does not change during program creation, + // it is safe to reuse resolutions from the earlier call. + var result_5 = []; + for (var _i = 0, moduleNames_1 = moduleNames; _i < moduleNames_1.length; _i++) { + var moduleName = moduleNames_1[_i]; + var resolvedModule = file.resolvedModules.get(moduleName); + result_5.push(resolvedModule); + } + return result_5; + } + // At this point, we know at least one of the following hold: + // - file has local declarations for ambient modules + // - old program state is available + // With this information, we can infer some module resolutions without performing resolution. + /** An ordered list of module names for which we cannot recover the resolution. */ + var unknownModuleNames; + /** + * The indexing of elements in this list matches that of `moduleNames`. + * + * Before combining results, result[i] is in one of the following states: + * * undefined: needs to be recomputed, + * * predictedToResolveToAmbientModuleMarker: known to be an ambient module. + * Needs to be reset to undefined before returning, + * * ResolvedModuleFull instance: can be reused. + */ + var result; + var reusedNames; + /** A transient placeholder used to mark predicted resolution in the result list. */ + var predictedToResolveToAmbientModuleMarker = {}; + for (var i = 0; i < moduleNames.length; i++) { + var moduleName = moduleNames[i]; + // If the source file is unchanged and doesnt have invalidated resolution, reuse the module resolutions + if (file === oldSourceFile && !hasInvalidatedResolution(oldSourceFile.path)) { + var oldResolvedModule = oldSourceFile && oldSourceFile.resolvedModules.get(moduleName); + if (oldResolvedModule) { + if (ts.isTraceEnabled(options, host)) { + ts.trace(host, ts.Diagnostics.Reusing_resolution_of_module_0_to_file_1_from_old_program, moduleName, containingFile); + } + (result || (result = new Array(moduleNames.length)))[i] = oldResolvedModule; + (reusedNames || (reusedNames = [])).push(moduleName); + continue; + } + } + // We know moduleName resolves to an ambient module provided that moduleName: + // - is in the list of ambient modules locally declared in the current source file. + // - resolved to an ambient module in the old program whose declaration is in an unmodified file + // (so the same module declaration will land in the new program) + var resolvesToAmbientModuleInNonModifiedFile = false; + if (ts.contains(file.ambientModuleNames, moduleName)) { + resolvesToAmbientModuleInNonModifiedFile = true; + if (ts.isTraceEnabled(options, host)) { + ts.trace(host, ts.Diagnostics.Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1, moduleName, containingFile); + } + } + else { + resolvesToAmbientModuleInNonModifiedFile = moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName); + } + if (resolvesToAmbientModuleInNonModifiedFile) { + (result || (result = new Array(moduleNames.length)))[i] = predictedToResolveToAmbientModuleMarker; + } + else { + // Resolution failed in the old program, or resolved to an ambient module for which we can't reuse the result. + (unknownModuleNames || (unknownModuleNames = [])).push(moduleName); + } + } + var resolutions = unknownModuleNames && unknownModuleNames.length + ? resolveModuleNamesWorker(unknownModuleNames, containingFile, reusedNames, getResolvedProjectReferenceToRedirect(file.originalFileName)) + : ts.emptyArray; + // Combine results of resolutions and predicted results + if (!result) { + // There were no unresolved/ambient resolutions. + ts.Debug.assert(resolutions.length === moduleNames.length); + return resolutions; + } + var j = 0; + for (var i = 0; i < result.length; i++) { + if (result[i]) { + // `result[i]` is either a `ResolvedModuleFull` or a marker. + // If it is the former, we can leave it as is. + if (result[i] === predictedToResolveToAmbientModuleMarker) { + result[i] = undefined; // TODO: GH#18217 + } + } + else { + result[i] = resolutions[j]; + j++; + } + } + ts.Debug.assert(j === resolutions.length); + return result; + // If we change our policy of rechecking failed lookups on each program create, + // we should adjust the value returned here. + function moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName) { + var resolutionToFile = ts.getResolvedModule(oldSourceFile, moduleName); + var resolvedFile = resolutionToFile && oldProgram.getSourceFile(resolutionToFile.resolvedFileName); + if (resolutionToFile && resolvedFile && !resolvedFile.externalModuleIndicator) { + // In the old program, we resolved to an ambient module that was in the same + // place as we expected to find an actual module file. + // We actually need to return 'false' here even though this seems like a 'true' case + // because the normal module resolution algorithm will find this anyway. + return false; + } + // at least one of declarations should come from non-modified source file + var unmodifiedFile = ambientModuleNameToUnmodifiedFileName.get(moduleName); + if (!unmodifiedFile) { + return false; + } + if (ts.isTraceEnabled(options, host)) { + ts.trace(host, ts.Diagnostics.Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified, moduleName, unmodifiedFile); + } + return true; + } + } + function canReuseProjectReferences() { + return !forEachProjectReference(oldProgram.getProjectReferences(), oldProgram.getResolvedProjectReferences(), function (oldResolvedRef, index, parent) { + var newRef = (parent ? parent.commandLine.projectReferences : projectReferences)[index]; + var newResolvedRef = parseProjectReferenceConfigFile(newRef); + if (oldResolvedRef) { + // Resolved project reference has gone missing or changed + return !newResolvedRef || newResolvedRef.sourceFile !== oldResolvedRef.sourceFile; + } + else { + // A previously-unresolved reference may be resolved now + return newResolvedRef !== undefined; + } + }, function (oldProjectReferences, parent) { + // If array of references is changed, we cant resue old program + var newReferences = parent ? getResolvedProjectReferenceByPath(parent.sourceFile.path).commandLine.projectReferences : projectReferences; + return !ts.arrayIsEqualTo(oldProjectReferences, newReferences, ts.projectReferenceIsEqualTo); + }); + } + function tryReuseStructureFromOldProgram() { + if (!oldProgram) { + return 0 /* Not */; + } + // check properties that can affect structure of the program or module resolution strategy + // if any of these properties has changed - structure cannot be reused + var oldOptions = oldProgram.getCompilerOptions(); + if (ts.changesAffectModuleResolution(oldOptions, options)) { + return oldProgram.structureIsReused = 0 /* Not */; + } + ts.Debug.assert(!(oldProgram.structureIsReused & (2 /* Completely */ | 1 /* SafeModules */))); + // there is an old program, check if we can reuse its structure + var oldRootNames = oldProgram.getRootFileNames(); + if (!ts.arrayIsEqualTo(oldRootNames, rootNames)) { + return oldProgram.structureIsReused = 0 /* Not */; + } + if (!ts.arrayIsEqualTo(options.types, oldOptions.types)) { + return oldProgram.structureIsReused = 0 /* Not */; + } + // Check if any referenced project tsconfig files are different + if (!canReuseProjectReferences()) { + return oldProgram.structureIsReused = 0 /* Not */; + } + if (projectReferences) { + resolvedProjectReferences = projectReferences.map(parseProjectReferenceConfigFile); + } + // check if program source files has changed in the way that can affect structure of the program + var newSourceFiles = []; + var modifiedSourceFiles = []; + oldProgram.structureIsReused = 2 /* Completely */; + // If the missing file paths are now present, it can change the progam structure, + // and hence cant reuse the structure. + // This is same as how we dont reuse the structure if one of the file from old program is now missing + if (oldProgram.getMissingFilePaths().some(function (missingFilePath) { return host.fileExists(missingFilePath); })) { + return oldProgram.structureIsReused = 0 /* Not */; + } + var oldSourceFiles = oldProgram.getSourceFiles(); + var SeenPackageName; + (function (SeenPackageName) { + SeenPackageName[SeenPackageName["Exists"] = 0] = "Exists"; + SeenPackageName[SeenPackageName["Modified"] = 1] = "Modified"; + })(SeenPackageName || (SeenPackageName = {})); + var seenPackageNames = ts.createMap(); + for (var _i = 0, oldSourceFiles_2 = oldSourceFiles; _i < oldSourceFiles_2.length; _i++) { + var oldSourceFile = oldSourceFiles_2[_i]; + var newSourceFile = host.getSourceFileByPath + ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.resolvedPath, options.target, /*onError*/ undefined, shouldCreateNewSourceFile) + : host.getSourceFile(oldSourceFile.fileName, options.target, /*onError*/ undefined, shouldCreateNewSourceFile); // TODO: GH#18217 + if (!newSourceFile) { + return oldProgram.structureIsReused = 0 /* Not */; + } + ts.Debug.assert(!newSourceFile.redirectInfo, "Host should not return a redirect source file from `getSourceFile`"); + var fileChanged = void 0; + if (oldSourceFile.redirectInfo) { + // We got `newSourceFile` by path, so it is actually for the unredirected file. + // This lets us know if the unredirected file has changed. If it has we should break the redirect. + if (newSourceFile !== oldSourceFile.redirectInfo.unredirected) { + // Underlying file has changed. Might not redirect anymore. Must rebuild program. + return oldProgram.structureIsReused = 0 /* Not */; + } + fileChanged = false; + newSourceFile = oldSourceFile; // Use the redirect. + } + else if (oldProgram.redirectTargetsMap.has(oldSourceFile.path)) { + // If a redirected-to source file changes, the redirect may be broken. + if (newSourceFile !== oldSourceFile) { + return oldProgram.structureIsReused = 0 /* Not */; + } + fileChanged = false; + } + else { + fileChanged = newSourceFile !== oldSourceFile; + } + // Since the project references havent changed, its right to set originalFileName and resolvedPath here + newSourceFile.path = oldSourceFile.path; + newSourceFile.originalFileName = oldSourceFile.originalFileName; + newSourceFile.resolvedPath = oldSourceFile.resolvedPath; + newSourceFile.fileName = oldSourceFile.fileName; + var packageName = oldProgram.sourceFileToPackageName.get(oldSourceFile.path); + if (packageName !== undefined) { + // If there are 2 different source files for the same package name and at least one of them changes, + // they might become redirects. So we must rebuild the program. + var prevKind = seenPackageNames.get(packageName); + var newKind = fileChanged ? 1 /* Modified */ : 0 /* Exists */; + if ((prevKind !== undefined && newKind === 1 /* Modified */) || prevKind === 1 /* Modified */) { + return oldProgram.structureIsReused = 0 /* Not */; + } + seenPackageNames.set(packageName, newKind); + } + if (fileChanged) { + // The `newSourceFile` object was created for the new program. + if (!ts.arrayIsEqualTo(oldSourceFile.libReferenceDirectives, newSourceFile.libReferenceDirectives, fileReferenceIsEqualTo)) { + // 'lib' references has changed. Matches behavior in changesAffectModuleResolution + return oldProgram.structureIsReused = 0 /* Not */; + } + if (oldSourceFile.hasNoDefaultLib !== newSourceFile.hasNoDefaultLib) { + // value of no-default-lib has changed + // this will affect if default library is injected into the list of files + oldProgram.structureIsReused = 1 /* SafeModules */; + } + // check tripleslash references + if (!ts.arrayIsEqualTo(oldSourceFile.referencedFiles, newSourceFile.referencedFiles, fileReferenceIsEqualTo)) { + // tripleslash references has changed + oldProgram.structureIsReused = 1 /* SafeModules */; + } + // check imports and module augmentations + collectExternalModuleReferences(newSourceFile); + if (!ts.arrayIsEqualTo(oldSourceFile.imports, newSourceFile.imports, moduleNameIsEqualTo)) { + // imports has changed + oldProgram.structureIsReused = 1 /* SafeModules */; + } + if (!ts.arrayIsEqualTo(oldSourceFile.moduleAugmentations, newSourceFile.moduleAugmentations, moduleNameIsEqualTo)) { + // moduleAugmentations has changed + oldProgram.structureIsReused = 1 /* SafeModules */; + } + if ((oldSourceFile.flags & 1572864 /* PermanentlySetIncrementalFlags */) !== (newSourceFile.flags & 1572864 /* PermanentlySetIncrementalFlags */)) { + // dynamicImport has changed + oldProgram.structureIsReused = 1 /* SafeModules */; + } + if (!ts.arrayIsEqualTo(oldSourceFile.typeReferenceDirectives, newSourceFile.typeReferenceDirectives, fileReferenceIsEqualTo)) { + // 'types' references has changed + oldProgram.structureIsReused = 1 /* SafeModules */; + } + // tentatively approve the file + modifiedSourceFiles.push({ oldFile: oldSourceFile, newFile: newSourceFile }); + } + else if (hasInvalidatedResolution(oldSourceFile.path)) { + // 'module/types' references could have changed + oldProgram.structureIsReused = 1 /* SafeModules */; + // add file to the modified list so that we will resolve it later + modifiedSourceFiles.push({ oldFile: oldSourceFile, newFile: newSourceFile }); + } + // if file has passed all checks it should be safe to reuse it + newSourceFiles.push(newSourceFile); + } + if (oldProgram.structureIsReused !== 2 /* Completely */) { + return oldProgram.structureIsReused; + } + var modifiedFiles = modifiedSourceFiles.map(function (f) { return f.oldFile; }); + for (var _a = 0, oldSourceFiles_3 = oldSourceFiles; _a < oldSourceFiles_3.length; _a++) { + var oldFile = oldSourceFiles_3[_a]; + if (!ts.contains(modifiedFiles, oldFile)) { + for (var _b = 0, _c = oldFile.ambientModuleNames; _b < _c.length; _b++) { + var moduleName = _c[_b]; + ambientModuleNameToUnmodifiedFileName.set(moduleName, oldFile.fileName); + } + } + } + // try to verify results of module resolution + for (var _d = 0, modifiedSourceFiles_1 = modifiedSourceFiles; _d < modifiedSourceFiles_1.length; _d++) { + var _e = modifiedSourceFiles_1[_d], oldSourceFile = _e.oldFile, newSourceFile = _e.newFile; + var newSourceFilePath = ts.getNormalizedAbsolutePath(newSourceFile.originalFileName, currentDirectory); + if (resolveModuleNamesWorker) { + var moduleNames = getModuleNames(newSourceFile); + var resolutions = resolveModuleNamesReusingOldState(moduleNames, newSourceFilePath, newSourceFile); + // ensure that module resolution results are still correct + var resolutionsChanged = ts.hasChangesInResolutions(moduleNames, resolutions, oldSourceFile.resolvedModules, ts.moduleResolutionIsEqualTo); + if (resolutionsChanged) { + oldProgram.structureIsReused = 1 /* SafeModules */; + newSourceFile.resolvedModules = ts.zipToMap(moduleNames, resolutions); + } + else { + newSourceFile.resolvedModules = oldSourceFile.resolvedModules; + } + } + if (resolveTypeReferenceDirectiveNamesWorker) { + // We lower-case all type references because npm automatically lowercases all packages. See GH#9824. + var typesReferenceDirectives = ts.map(newSourceFile.typeReferenceDirectives, function (ref) { return ref.fileName.toLocaleLowerCase(); }); + var resolutions = resolveTypeReferenceDirectiveNamesWorker(typesReferenceDirectives, newSourceFilePath, getResolvedProjectReferenceToRedirect(newSourceFile.originalFileName)); + // ensure that types resolutions are still correct + var resolutionsChanged = ts.hasChangesInResolutions(typesReferenceDirectives, resolutions, oldSourceFile.resolvedTypeReferenceDirectiveNames, ts.typeDirectiveIsEqualTo); + if (resolutionsChanged) { + oldProgram.structureIsReused = 1 /* SafeModules */; + newSourceFile.resolvedTypeReferenceDirectiveNames = ts.zipToMap(typesReferenceDirectives, resolutions); + } + else { + newSourceFile.resolvedTypeReferenceDirectiveNames = oldSourceFile.resolvedTypeReferenceDirectiveNames; + } + } + } + if (oldProgram.structureIsReused !== 2 /* Completely */) { + return oldProgram.structureIsReused; + } + if (host.hasChangedAutomaticTypeDirectiveNames) { + return oldProgram.structureIsReused = 1 /* SafeModules */; + } + missingFilePaths = oldProgram.getMissingFilePaths(); + // update fileName -> file mapping + for (var _f = 0, newSourceFiles_1 = newSourceFiles; _f < newSourceFiles_1.length; _f++) { + var newSourceFile = newSourceFiles_1[_f]; + var filePath = newSourceFile.path; + addFileToFilesByName(newSourceFile, filePath, newSourceFile.resolvedPath); + // Set the file as found during node modules search if it was found that way in old progra, + if (oldProgram.isSourceFileFromExternalLibrary(oldProgram.getSourceFileByPath(filePath))) { + sourceFilesFoundSearchingNodeModules.set(filePath, true); + } + } + files = newSourceFiles; + fileProcessingDiagnostics = oldProgram.getFileProcessingDiagnostics(); + for (var _g = 0, modifiedSourceFiles_2 = modifiedSourceFiles; _g < modifiedSourceFiles_2.length; _g++) { + var modifiedFile = modifiedSourceFiles_2[_g]; + fileProcessingDiagnostics.reattachFileDiagnostics(modifiedFile.newFile); + } + resolvedTypeReferenceDirectives = oldProgram.getResolvedTypeReferenceDirectives(); + sourceFileToPackageName = oldProgram.sourceFileToPackageName; + redirectTargetsMap = oldProgram.redirectTargetsMap; + return oldProgram.structureIsReused = 2 /* Completely */; + } + function getEmitHost(writeFileCallback) { + return __assign({ getPrependNodes: getPrependNodes, + getCanonicalFileName: getCanonicalFileName, getCommonSourceDirectory: program.getCommonSourceDirectory, getCompilerOptions: program.getCompilerOptions, getCurrentDirectory: function () { return currentDirectory; }, getNewLine: function () { return host.getNewLine(); }, getSourceFile: program.getSourceFile, getSourceFileByPath: program.getSourceFileByPath, getSourceFiles: program.getSourceFiles, getLibFileFromReference: program.getLibFileFromReference, isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary, writeFile: writeFileCallback || (function (fileName, data, writeByteOrderMark, onError, sourceFiles) { return host.writeFile(fileName, data, writeByteOrderMark, onError, sourceFiles); }), isEmitBlocked: isEmitBlocked, readFile: function (f) { return host.readFile(f); }, fileExists: function (f) { + // Use local caches + var path = toPath(f); + if (getSourceFileByPath(path)) + return true; + if (ts.contains(missingFilePaths, path)) + return false; + // Before falling back to the host + return host.fileExists(f); + } }, (host.directoryExists ? { directoryExists: function (f) { return host.directoryExists(f); } } : {}), { useCaseSensitiveFileNames: function () { return host.useCaseSensitiveFileNames(); } }); + } + function getResolvedProjectReferences() { + return resolvedProjectReferences; + } + function getProjectReferences() { + return projectReferences; + } + function getPrependNodes() { + if (!projectReferences) { + return ts.emptyArray; + } + var nodes = []; + for (var i = 0; i < projectReferences.length; i++) { + var ref = projectReferences[i]; + var resolvedRefOpts = resolvedProjectReferences[i].commandLine; + if (ref.prepend && resolvedRefOpts && resolvedRefOpts.options) { + var out = resolvedRefOpts.options.outFile || resolvedRefOpts.options.out; + // Upstream project didn't have outFile set -- skip (error will have been issued earlier) + if (!out) + continue; + var dtsFilename = ts.changeExtension(out, ".d.ts"); + var js = host.readFile(out) || "/* Input file " + out + " was missing */\r\n"; + var jsMapPath = out + ".map"; // TODO: try to read sourceMappingUrl comment from the file + var jsMap = host.readFile(jsMapPath); + var dts = host.readFile(dtsFilename) || "/* Input file " + dtsFilename + " was missing */\r\n"; + var dtsMapPath = dtsFilename + ".map"; + var dtsMap = host.readFile(dtsMapPath); + var node = ts.createInputFiles(js, dts, jsMap && jsMapPath, jsMap, dtsMap && dtsMapPath, dtsMap); + nodes.push(node); + } + } + return nodes; + } + function isSourceFileFromExternalLibrary(file) { + return !!sourceFilesFoundSearchingNodeModules.get(file.path); + } + function isSourceFileDefaultLibrary(file) { + if (file.hasNoDefaultLib) { + return true; + } + if (!options.noLib) { + return false; + } + // If '--lib' is not specified, include default library file according to '--target' + // otherwise, using options specified in '--lib' instead of '--target' default library file + var equalityComparer = host.useCaseSensitiveFileNames() ? ts.equateStringsCaseSensitive : ts.equateStringsCaseInsensitive; + if (!options.lib) { + return equalityComparer(file.fileName, getDefaultLibraryFileName()); + } + else { + return ts.some(options.lib, function (libFileName) { return equalityComparer(file.fileName, ts.combinePaths(defaultLibraryPath, libFileName)); }); + } + } + function getDiagnosticsProducingTypeChecker() { + return diagnosticsProducingTypeChecker || (diagnosticsProducingTypeChecker = ts.createTypeChecker(program, /*produceDiagnostics:*/ true)); + } + function dropDiagnosticsProducingTypeChecker() { + diagnosticsProducingTypeChecker = undefined; + } + function getTypeChecker() { + return noDiagnosticsTypeChecker || (noDiagnosticsTypeChecker = ts.createTypeChecker(program, /*produceDiagnostics:*/ false)); + } + function emit(sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles, transformers) { + return runWithCancellationToken(function () { return emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles, transformers); }); + } + function isEmitBlocked(emitFileName) { + return hasEmitBlockingDiagnostics.has(toPath(emitFileName)); + } + function emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles, customTransformers) { + var declarationDiagnostics = []; + if (!emitOnlyDtsFiles) { + if (options.noEmit) { + return { diagnostics: declarationDiagnostics, sourceMaps: undefined, emittedFiles: undefined, emitSkipped: true }; + } + // If the noEmitOnError flag is set, then check if we have any errors so far. If so, + // immediately bail out. Note that we pass 'undefined' for 'sourceFile' so that we + // get any preEmit diagnostics, not just the ones + if (options.noEmitOnError) { + var diagnostics = program.getOptionsDiagnostics(cancellationToken).concat(program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken)); + if (diagnostics.length === 0 && ts.getEmitDeclarations(program.getCompilerOptions())) { + declarationDiagnostics = program.getDeclarationDiagnostics(/*sourceFile*/ undefined, cancellationToken); + } + if (diagnostics.length > 0 || declarationDiagnostics.length > 0) { + return { + diagnostics: ts.concatenate(diagnostics, declarationDiagnostics), + sourceMaps: undefined, + emittedFiles: undefined, + emitSkipped: true + }; + } + } + } + // Create the emit resolver outside of the "emitTime" tracking code below. That way + // any cost associated with it (like type checking) are appropriate associated with + // the type-checking counter. + // + // If the -out option is specified, we should not pass the source file to getEmitResolver. + // This is because in the -out scenario all files need to be emitted, and therefore all + // files need to be type checked. And the way to specify that all files need to be type + // checked is to not pass the file to getEmitResolver. + var emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile, cancellationToken); + ts.performance.mark("beforeEmit"); + var transformers = emitOnlyDtsFiles ? [] : ts.getTransformers(options, customTransformers); + var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile, // TODO: GH#18217 + emitOnlyDtsFiles, transformers, customTransformers && customTransformers.afterDeclarations); + ts.performance.mark("afterEmit"); + ts.performance.measure("Emit", "beforeEmit", "afterEmit"); + return emitResult; + } + function getSourceFile(fileName) { + return getSourceFileByPath(toPath(fileName)); + } + function getSourceFileByPath(path) { + return filesByName.get(path); + } + function getDiagnosticsHelper(sourceFile, getDiagnostics, cancellationToken) { + if (sourceFile) { + return getDiagnostics(sourceFile, cancellationToken); + } + return ts.sortAndDeduplicateDiagnostics(ts.flatMap(program.getSourceFiles(), function (sourceFile) { + if (cancellationToken) { + cancellationToken.throwIfCancellationRequested(); + } + return getDiagnostics(sourceFile, cancellationToken); + })); + } + function getSyntacticDiagnostics(sourceFile, cancellationToken) { + return getDiagnosticsHelper(sourceFile, getSyntacticDiagnosticsForFile, cancellationToken); + } + function getSemanticDiagnostics(sourceFile, cancellationToken) { + return getDiagnosticsHelper(sourceFile, getSemanticDiagnosticsForFile, cancellationToken); + } + function getDeclarationDiagnostics(sourceFile, cancellationToken) { + var options = program.getCompilerOptions(); + // collect diagnostics from the program only once if either no source file was specified or out/outFile is set (bundled emit) + if (!sourceFile || options.out || options.outFile) { + return getDeclarationDiagnosticsWorker(sourceFile, cancellationToken); + } + else { + return getDiagnosticsHelper(sourceFile, getDeclarationDiagnosticsForFile, cancellationToken); + } + } + function getSyntacticDiagnosticsForFile(sourceFile) { + // For JavaScript files, we report semantic errors for using TypeScript-only + // constructs from within a JavaScript file as syntactic errors. + if (ts.isSourceFileJS(sourceFile)) { + if (!sourceFile.additionalSyntacticDiagnostics) { + sourceFile.additionalSyntacticDiagnostics = getJSSyntacticDiagnosticsForFile(sourceFile); + } + return ts.concatenate(sourceFile.additionalSyntacticDiagnostics, sourceFile.parseDiagnostics); + } + return sourceFile.parseDiagnostics; + } + function runWithCancellationToken(func) { + try { + return func(); + } + catch (e) { + if (e instanceof ts.OperationCanceledException) { + // We were canceled while performing the operation. Because our type checker + // might be a bad state, we need to throw it away. + // + // Note: we are overly aggressive here. We do not actually *have* to throw away + // the "noDiagnosticsTypeChecker". However, for simplicity, i'd like to keep + // the lifetimes of these two TypeCheckers the same. Also, we generally only + // cancel when the user has made a change anyways. And, in that case, we (the + // program instance) will get thrown away anyways. So trying to keep one of + // these type checkers alive doesn't serve much purpose. + noDiagnosticsTypeChecker = undefined; + diagnosticsProducingTypeChecker = undefined; + } + throw e; + } + } + function getSemanticDiagnosticsForFile(sourceFile, cancellationToken) { + return getAndCacheDiagnostics(sourceFile, cancellationToken, cachedSemanticDiagnosticsForFile, getSemanticDiagnosticsForFileNoCache); + } + function getSemanticDiagnosticsForFileNoCache(sourceFile, cancellationToken) { + return runWithCancellationToken(function () { + if (ts.skipTypeChecking(sourceFile, options)) { + return ts.emptyArray; + } + var typeChecker = getDiagnosticsProducingTypeChecker(); + ts.Debug.assert(!!sourceFile.bindDiagnostics); + var isCheckJs = ts.isCheckJsEnabledForFile(sourceFile, options); + // By default, only type-check .ts, .tsx, 'Deferred' and 'External' files (external files are added by plugins) + var includeBindAndCheckDiagnostics = sourceFile.scriptKind === 3 /* TS */ || sourceFile.scriptKind === 4 /* TSX */ || + sourceFile.scriptKind === 5 /* External */ || isCheckJs || sourceFile.scriptKind === 7 /* Deferred */; + var bindDiagnostics = includeBindAndCheckDiagnostics ? sourceFile.bindDiagnostics : ts.emptyArray; + var checkDiagnostics = includeBindAndCheckDiagnostics ? typeChecker.getDiagnostics(sourceFile, cancellationToken) : ts.emptyArray; + var fileProcessingDiagnosticsInFile = fileProcessingDiagnostics.getDiagnostics(sourceFile.fileName); + var programDiagnosticsInFile = programDiagnostics.getDiagnostics(sourceFile.fileName); + var diagnostics; + for (var _i = 0, _a = [bindDiagnostics, checkDiagnostics, fileProcessingDiagnosticsInFile, programDiagnosticsInFile, isCheckJs ? sourceFile.jsDocDiagnostics : undefined]; _i < _a.length; _i++) { + var diags = _a[_i]; + if (diags) { + for (var _b = 0, diags_1 = diags; _b < diags_1.length; _b++) { + var diag = diags_1[_b]; + if (shouldReportDiagnostic(diag)) { + diagnostics = ts.append(diagnostics, diag); + } + } + } + } + return diagnostics; + }); + } + function getSuggestionDiagnostics(sourceFile, cancellationToken) { + return runWithCancellationToken(function () { + return getDiagnosticsProducingTypeChecker().getSuggestionDiagnostics(sourceFile, cancellationToken); + }); + } + /** + * Skip errors if previous line start with '// @ts-ignore' comment, not counting non-empty non-comment lines + */ + function shouldReportDiagnostic(diagnostic) { + var file = diagnostic.file, start = diagnostic.start; + if (file) { + var lineStarts = ts.getLineStarts(file); + var line = ts.computeLineAndCharacterOfPosition(lineStarts, start).line; // TODO: GH#18217 + while (line > 0) { + var previousLineText = file.text.slice(lineStarts[line - 1], lineStarts[line]); + var result = ignoreDiagnosticCommentRegEx.exec(previousLineText); + if (!result) { + // non-empty line + return true; + } + if (result[3]) { + // @ts-ignore + return false; + } + line--; + } + } + return true; + } + function getJSSyntacticDiagnosticsForFile(sourceFile) { + return runWithCancellationToken(function () { + var diagnostics = []; + var parent = sourceFile; + walk(sourceFile); + return diagnostics; + function walk(node) { + // Return directly from the case if the given node doesnt want to visit each child + // Otherwise break to visit each child + switch (parent.kind) { + case 151 /* Parameter */: + case 154 /* PropertyDeclaration */: + if (parent.questionToken === node) { + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, "?")); + return; + } + // falls through + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 196 /* FunctionExpression */: + case 239 /* FunctionDeclaration */: + case 197 /* ArrowFunction */: + case 237 /* VariableDeclaration */: + // type annotation + if (parent.type === node) { + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.types_can_only_be_used_in_a_ts_file)); + return; + } + } + switch (node.kind) { + case 248 /* ImportEqualsDeclaration */: + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.import_can_only_be_used_in_a_ts_file)); + return; + case 254 /* ExportAssignment */: + if (node.isExportEquals) { + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.export_can_only_be_used_in_a_ts_file)); + return; + } + break; + case 273 /* HeritageClause */: + var heritageClause = node; + if (heritageClause.token === 109 /* ImplementsKeyword */) { + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.implements_clauses_can_only_be_used_in_a_ts_file)); + return; + } + break; + case 241 /* InterfaceDeclaration */: + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.interface_declarations_can_only_be_used_in_a_ts_file)); + return; + case 244 /* ModuleDeclaration */: + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.module_declarations_can_only_be_used_in_a_ts_file)); + return; + case 242 /* TypeAliasDeclaration */: + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.type_aliases_can_only_be_used_in_a_ts_file)); + return; + case 243 /* EnumDeclaration */: + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.enum_declarations_can_only_be_used_in_a_ts_file)); + return; + case 213 /* NonNullExpression */: + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.non_null_assertions_can_only_be_used_in_a_ts_file)); + return; + case 212 /* AsExpression */: + diagnostics.push(createDiagnosticForNode(node.type, ts.Diagnostics.type_assertion_expressions_can_only_be_used_in_a_ts_file)); + return; + case 194 /* TypeAssertionExpression */: + ts.Debug.fail(); // Won't parse these in a JS file anyway, as they are interpreted as JSX. + } + var prevParent = parent; + parent = node; + ts.forEachChild(node, walk, walkArray); + parent = prevParent; + } + function walkArray(nodes) { + if (parent.decorators === nodes && !options.experimentalDecorators) { + diagnostics.push(createDiagnosticForNode(parent, ts.Diagnostics.Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_to_remove_this_warning)); + } + switch (parent.kind) { + case 240 /* ClassDeclaration */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 196 /* FunctionExpression */: + case 239 /* FunctionDeclaration */: + case 197 /* ArrowFunction */: + // Check type parameters + if (nodes === parent.typeParameters) { + diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.type_parameter_declarations_can_only_be_used_in_a_ts_file)); + return; + } + // falls through + case 219 /* VariableStatement */: + // Check modifiers + if (nodes === parent.modifiers) { + return checkModifiers(nodes, parent.kind === 219 /* VariableStatement */); + } + break; + case 154 /* PropertyDeclaration */: + // Check modifiers of property declaration + if (nodes === parent.modifiers) { + for (var _i = 0, _a = nodes; _i < _a.length; _i++) { + var modifier = _a[_i]; + if (modifier.kind !== 116 /* StaticKeyword */) { + diagnostics.push(createDiagnosticForNode(modifier, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, ts.tokenToString(modifier.kind))); + } + } + return; + } + break; + case 151 /* Parameter */: + // Check modifiers of parameter declaration + if (nodes === parent.modifiers) { + diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.parameter_modifiers_can_only_be_used_in_a_ts_file)); + return; + } + break; + case 191 /* CallExpression */: + case 192 /* NewExpression */: + case 211 /* ExpressionWithTypeArguments */: + case 261 /* JsxSelfClosingElement */: + case 262 /* JsxOpeningElement */: + // Check type arguments + if (nodes === parent.typeArguments) { + diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.type_arguments_can_only_be_used_in_a_ts_file)); + return; + } + break; + } + for (var _b = 0, nodes_6 = nodes; _b < nodes_6.length; _b++) { + var node = nodes_6[_b]; + walk(node); + } + } + function checkModifiers(modifiers, isConstValid) { + for (var _i = 0, modifiers_1 = modifiers; _i < modifiers_1.length; _i++) { + var modifier = modifiers_1[_i]; + switch (modifier.kind) { + case 77 /* ConstKeyword */: + if (isConstValid) { + continue; + } + // to report error, + // falls through + case 115 /* PublicKeyword */: + case 113 /* PrivateKeyword */: + case 114 /* ProtectedKeyword */: + case 133 /* ReadonlyKeyword */: + case 125 /* DeclareKeyword */: + case 118 /* AbstractKeyword */: + diagnostics.push(createDiagnosticForNode(modifier, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, ts.tokenToString(modifier.kind))); + break; + // These are all legal modifiers. + case 116 /* StaticKeyword */: + case 85 /* ExportKeyword */: + case 80 /* DefaultKeyword */: + } + } + } + function createDiagnosticForNodeArray(nodes, message, arg0, arg1, arg2) { + var start = nodes.pos; + return ts.createFileDiagnostic(sourceFile, start, nodes.end - start, message, arg0, arg1, arg2); + } + // Since these are syntactic diagnostics, parent might not have been set + // this means the sourceFile cannot be infered from the node + function createDiagnosticForNode(node, message, arg0, arg1, arg2) { + return ts.createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2); + } + }); + } + function getDeclarationDiagnosticsWorker(sourceFile, cancellationToken) { + return getAndCacheDiagnostics(sourceFile, cancellationToken, cachedDeclarationDiagnosticsForFile, getDeclarationDiagnosticsForFileNoCache); + } + function getDeclarationDiagnosticsForFileNoCache(sourceFile, cancellationToken) { + return runWithCancellationToken(function () { + var resolver = getDiagnosticsProducingTypeChecker().getEmitResolver(sourceFile, cancellationToken); + // Don't actually write any files since we're just getting diagnostics. + return ts.getDeclarationDiagnostics(getEmitHost(ts.noop), resolver, sourceFile); + }); + } + function getAndCacheDiagnostics(sourceFile, cancellationToken, cache, getDiagnostics) { + var cachedResult = sourceFile + ? cache.perFile && cache.perFile.get(sourceFile.path) + : cache.allDiagnostics; + if (cachedResult) { + return cachedResult; + } + var result = getDiagnostics(sourceFile, cancellationToken) || ts.emptyArray; // TODO: GH#18217 + if (sourceFile) { + if (!cache.perFile) { + cache.perFile = ts.createMap(); + } + cache.perFile.set(sourceFile.path, result); + } + else { + cache.allDiagnostics = result; + } + return result; + } + function getDeclarationDiagnosticsForFile(sourceFile, cancellationToken) { + return sourceFile.isDeclarationFile ? [] : getDeclarationDiagnosticsWorker(sourceFile, cancellationToken); + } + function getOptionsDiagnostics() { + return ts.sortAndDeduplicateDiagnostics(ts.concatenate(fileProcessingDiagnostics.getGlobalDiagnostics(), ts.concatenate(programDiagnostics.getGlobalDiagnostics(), getOptionsDiagnosticsOfConfigFile()))); + } + function getOptionsDiagnosticsOfConfigFile() { + if (!options.configFile) { + return ts.emptyArray; + } + var diagnostics = programDiagnostics.getDiagnostics(options.configFile.fileName); + forEachResolvedProjectReference(function (resolvedRef) { + if (resolvedRef) { + diagnostics = ts.concatenate(diagnostics, programDiagnostics.getDiagnostics(resolvedRef.sourceFile.fileName)); + } + }); + return diagnostics; + } + function getGlobalDiagnostics() { + return rootNames.length ? ts.sortAndDeduplicateDiagnostics(getDiagnosticsProducingTypeChecker().getGlobalDiagnostics().slice()) : ts.emptyArray; + } + function getConfigFileParsingDiagnostics() { + return configFileParsingDiagnostics || ts.emptyArray; + } + function processRootFile(fileName, isDefaultLib, ignoreNoDefaultLib) { + processSourceFile(ts.normalizePath(fileName), isDefaultLib, ignoreNoDefaultLib, /*packageId*/ undefined); + } + function fileReferenceIsEqualTo(a, b) { + return a.fileName === b.fileName; + } + function moduleNameIsEqualTo(a, b) { + return a.kind === 72 /* Identifier */ + ? b.kind === 72 /* Identifier */ && a.escapedText === b.escapedText + : b.kind === 10 /* StringLiteral */ && a.text === b.text; + } + function collectExternalModuleReferences(file) { + if (file.imports) { + return; + } + var isJavaScriptFile = ts.isSourceFileJS(file); + var isExternalModuleFile = ts.isExternalModule(file); + // file.imports may not be undefined if there exists dynamic import + var imports; + var moduleAugmentations; + var ambientModules; + // If we are importing helpers, we need to add a synthetic reference to resolve the + // helpers library. + if (options.importHelpers + && (options.isolatedModules || isExternalModuleFile) + && !file.isDeclarationFile) { + // synthesize 'import "tslib"' declaration + var externalHelpersModuleReference = ts.createLiteral(ts.externalHelpersModuleNameText); + var importDecl = ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*importClause*/ undefined, externalHelpersModuleReference); + ts.addEmitFlags(importDecl, 67108864 /* NeverApplyImportHelper */); + externalHelpersModuleReference.parent = importDecl; + importDecl.parent = file; + imports = [externalHelpersModuleReference]; + } + for (var _i = 0, _a = file.statements; _i < _a.length; _i++) { + var node = _a[_i]; + collectModuleReferences(node, /*inAmbientModule*/ false); + } + if ((file.flags & 524288 /* PossiblyContainsDynamicImport */) || isJavaScriptFile) { + collectDynamicImportOrRequireCalls(file); + } + file.imports = imports || ts.emptyArray; + file.moduleAugmentations = moduleAugmentations || ts.emptyArray; + file.ambientModuleNames = ambientModules || ts.emptyArray; + return; + function collectModuleReferences(node, inAmbientModule) { + if (ts.isAnyImportOrReExport(node)) { + var moduleNameExpr = ts.getExternalModuleName(node); + // TypeScript 1.0 spec (April 2014): 12.1.6 + // An ExternalImportDeclaration in an AmbientExternalModuleDeclaration may reference other external modules + // only through top - level external module names. Relative external module names are not permitted. + if (moduleNameExpr && ts.isStringLiteral(moduleNameExpr) && moduleNameExpr.text && (!inAmbientModule || !ts.isExternalModuleNameRelative(moduleNameExpr.text))) { + imports = ts.append(imports, moduleNameExpr); + } + } + else if (ts.isModuleDeclaration(node)) { + if (ts.isAmbientModule(node) && (inAmbientModule || ts.hasModifier(node, 2 /* Ambient */) || file.isDeclarationFile)) { + var nameText = ts.getTextOfIdentifierOrLiteral(node.name); + // Ambient module declarations can be interpreted as augmentations for some existing external modules. + // This will happen in two cases: + // - if current file is external module then module augmentation is a ambient module declaration defined in the top level scope + // - if current file is not external module then module augmentation is an ambient module declaration with non-relative module name + // immediately nested in top level ambient module declaration . + if (isExternalModuleFile || (inAmbientModule && !ts.isExternalModuleNameRelative(nameText))) { + (moduleAugmentations || (moduleAugmentations = [])).push(node.name); + } + else if (!inAmbientModule) { + if (file.isDeclarationFile) { + // for global .d.ts files record name of ambient module + (ambientModules || (ambientModules = [])).push(nameText); + } + // An AmbientExternalModuleDeclaration declares an external module. + // This type of declaration is permitted only in the global module. + // The StringLiteral must specify a top - level external module name. + // Relative external module names are not permitted + // NOTE: body of ambient module is always a module block, if it exists + var body = node.body; + if (body) { + for (var _i = 0, _a = body.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + collectModuleReferences(statement, /*inAmbientModule*/ true); + } + } + } + } + } + } + function collectDynamicImportOrRequireCalls(file) { + var r = /import|require/g; + while (r.exec(file.text) !== null) { + var node = getNodeAtPosition(file, r.lastIndex); + if (ts.isRequireCall(node, /*checkArgumentIsStringLiteralLike*/ true)) { + imports = ts.append(imports, node.arguments[0]); + } + // we have to check the argument list has length of 1. We will still have to process these even though we have parsing error. + else if (ts.isImportCall(node) && node.arguments.length === 1 && ts.isStringLiteralLike(node.arguments[0])) { + imports = ts.append(imports, node.arguments[0]); + } + else if (ts.isLiteralImportTypeNode(node)) { + imports = ts.append(imports, node.argument.literal); + } + } + } + /** Returns a token if position is in [start-of-leading-trivia, end), includes JSDoc only in JS files */ + function getNodeAtPosition(sourceFile, position) { + var current = sourceFile; + var getContainingChild = function (child) { + if (child.pos <= position && (position < child.end || (position === child.end && (child.kind === 1 /* EndOfFileToken */)))) { + return child; + } + }; + while (true) { + var child = isJavaScriptFile && ts.hasJSDocNodes(current) && ts.forEach(current.jsDoc, getContainingChild) || ts.forEachChild(current, getContainingChild); + if (!child) { + return current; + } + current = child; + } + } + } + function getLibFileFromReference(ref) { + var libName = ref.fileName.toLocaleLowerCase(); + var libFileName = ts.libMap.get(libName); + if (libFileName) { + return getSourceFile(ts.combinePaths(defaultLibraryPath, libFileName)); + } + } + /** This should have similar behavior to 'processSourceFile' without diagnostics or mutation. */ + function getSourceFileFromReference(referencingFile, ref) { + return getSourceFileFromReferenceWorker(resolveTripleslashReference(ref.fileName, referencingFile.fileName), function (fileName) { return filesByName.get(toPath(fileName)); }); + } + function getSourceFileFromReferenceWorker(fileName, getSourceFile, fail, refFile) { + if (ts.hasExtension(fileName)) { + if (!options.allowNonTsExtensions && !ts.forEach(supportedExtensionsWithJsonIfResolveJsonModule, function (extension) { return ts.fileExtensionIs(host.getCanonicalFileName(fileName), extension); })) { + if (fail) + fail(ts.Diagnostics.File_0_has_unsupported_extension_The_only_supported_extensions_are_1, fileName, "'" + supportedExtensions.join("', '") + "'"); + return undefined; + } + var sourceFile = getSourceFile(fileName); + if (fail) { + if (!sourceFile) { + var redirect = getProjectReferenceRedirect(fileName); + if (redirect) { + fail(ts.Diagnostics.Output_file_0_has_not_been_built_from_source_file_1, redirect, fileName); + } + else { + fail(ts.Diagnostics.File_0_not_found, fileName); + } + } + else if (refFile && host.getCanonicalFileName(fileName) === host.getCanonicalFileName(refFile.fileName)) { + fail(ts.Diagnostics.A_file_cannot_have_a_reference_to_itself); + } + } + return sourceFile; + } + else { + var sourceFileNoExtension = options.allowNonTsExtensions && getSourceFile(fileName); + if (sourceFileNoExtension) + return sourceFileNoExtension; + if (fail && options.allowNonTsExtensions) { + fail(ts.Diagnostics.File_0_not_found, fileName); + return undefined; + } + var sourceFileWithAddedExtension = ts.forEach(supportedExtensions, function (extension) { return getSourceFile(fileName + extension); }); + if (fail && !sourceFileWithAddedExtension) + fail(ts.Diagnostics.File_0_not_found, fileName + ".ts" /* Ts */); + return sourceFileWithAddedExtension; + } + } + /** This has side effects through `findSourceFile`. */ + function processSourceFile(fileName, isDefaultLib, ignoreNoDefaultLib, packageId, refFile, refPos, refEnd) { + getSourceFileFromReferenceWorker(fileName, function (fileName) { return findSourceFile(fileName, toPath(fileName), isDefaultLib, ignoreNoDefaultLib, refFile, refPos, refEnd, packageId); }, // TODO: GH#18217 + function (diagnostic) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + fileProcessingDiagnostics.add(refFile !== undefined && refEnd !== undefined && refPos !== undefined + ? ts.createFileDiagnostic.apply(void 0, [refFile, refPos, refEnd - refPos, diagnostic].concat(args)) : ts.createCompilerDiagnostic.apply(void 0, [diagnostic].concat(args))); + }, refFile); + } + function reportFileNamesDifferOnlyInCasingError(fileName, existingFileName, refFile, refPos, refEnd) { + if (refFile !== undefined && refPos !== undefined && refEnd !== undefined) { + fileProcessingDiagnostics.add(ts.createFileDiagnostic(refFile, refPos, refEnd - refPos, ts.Diagnostics.File_name_0_differs_from_already_included_file_name_1_only_in_casing, fileName, existingFileName)); + } + else { + fileProcessingDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_name_0_differs_from_already_included_file_name_1_only_in_casing, fileName, existingFileName)); + } + } + function createRedirectSourceFile(redirectTarget, unredirected, fileName, path, resolvedPath, originalFileName) { + var redirect = Object.create(redirectTarget); + redirect.fileName = fileName; + redirect.path = path; + redirect.resolvedPath = resolvedPath; + redirect.originalFileName = originalFileName; + redirect.redirectInfo = { redirectTarget: redirectTarget, unredirected: unredirected }; + sourceFilesFoundSearchingNodeModules.set(path, currentNodeModulesDepth > 0); + Object.defineProperties(redirect, { + id: { + get: function () { return this.redirectInfo.redirectTarget.id; }, + set: function (value) { this.redirectInfo.redirectTarget.id = value; }, + }, + symbol: { + get: function () { return this.redirectInfo.redirectTarget.symbol; }, + set: function (value) { this.redirectInfo.redirectTarget.symbol = value; }, + }, + }); + return redirect; + } + // Get source file from normalized fileName + function findSourceFile(fileName, path, isDefaultLib, ignoreNoDefaultLib, refFile, refPos, refEnd, packageId) { + var originalFileName = fileName; + if (filesByName.has(path)) { + var file_1 = filesByName.get(path); + // try to check if we've already seen this file but with a different casing in path + // NOTE: this only makes sense for case-insensitive file systems, and only on files which are not redirected + if (file_1 && options.forceConsistentCasingInFileNames) { + var inputName = fileName; + var checkedName = file_1.fileName; + var isRedirect = toPath(checkedName) !== toPath(inputName); + if (isRedirect) { + inputName = getProjectReferenceRedirect(fileName) || fileName; + } + if (ts.getNormalizedAbsolutePath(checkedName, currentDirectory) !== ts.getNormalizedAbsolutePath(inputName, currentDirectory)) { + reportFileNamesDifferOnlyInCasingError(inputName, checkedName, refFile, refPos, refEnd); + } + } + // If the file was previously found via a node_modules search, but is now being processed as a root file, + // then everything it sucks in may also be marked incorrectly, and needs to be checked again. + if (file_1 && sourceFilesFoundSearchingNodeModules.get(file_1.path) && currentNodeModulesDepth === 0) { + sourceFilesFoundSearchingNodeModules.set(file_1.path, false); + if (!options.noResolve) { + processReferencedFiles(file_1, isDefaultLib); + processTypeReferenceDirectives(file_1); + } + processLibReferenceDirectives(file_1); + modulesWithElidedImports.set(file_1.path, false); + processImportedModules(file_1); + } + // See if we need to reprocess the imports due to prior skipped imports + else if (file_1 && modulesWithElidedImports.get(file_1.path)) { + if (currentNodeModulesDepth < maxNodeModuleJsDepth) { + modulesWithElidedImports.set(file_1.path, false); + processImportedModules(file_1); + } + } + return file_1; + } + var redirectedPath; + if (refFile) { + var redirect = getProjectReferenceRedirect(fileName); + if (redirect) { + (refFile.redirectedReferences || (refFile.redirectedReferences = [])).push(fileName); + fileName = redirect; + // Once we start redirecting to a file, we can potentially come back to it + // via a back-reference from another file in the .d.ts folder. If that happens we'll + // end up trying to add it to the program *again* because we were tracking it via its + // original (un-redirected) name. So we have to map both the original path and the redirected path + // to the source file we're about to find/create + redirectedPath = toPath(redirect); + } + } + // We haven't looked for this file, do so now and cache result + var file = host.getSourceFile(fileName, options.target, function (hostErrorMessage) { + if (refFile !== undefined && refPos !== undefined && refEnd !== undefined) { + fileProcessingDiagnostics.add(ts.createFileDiagnostic(refFile, refPos, refEnd - refPos, ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, hostErrorMessage)); + } + else { + fileProcessingDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, hostErrorMessage)); + } + }, shouldCreateNewSourceFile); + if (packageId) { + var packageIdKey = ts.packageIdToString(packageId); + var fileFromPackageId = packageIdToSourceFile.get(packageIdKey); + if (fileFromPackageId) { + // Some other SourceFile already exists with this package name and version. + // Instead of creating a duplicate, just redirect to the existing one. + var dupFile = createRedirectSourceFile(fileFromPackageId, file, fileName, path, toPath(fileName), originalFileName); // TODO: GH#18217 + redirectTargetsMap.add(fileFromPackageId.path, fileName); + addFileToFilesByName(dupFile, path, redirectedPath); + sourceFileToPackageName.set(path, packageId.name); + processingOtherFiles.push(dupFile); + return dupFile; + } + else if (file) { + // This is the first source file to have this packageId. + packageIdToSourceFile.set(packageIdKey, file); + sourceFileToPackageName.set(path, packageId.name); + } + } + addFileToFilesByName(file, path, redirectedPath); + if (file) { + sourceFilesFoundSearchingNodeModules.set(path, currentNodeModulesDepth > 0); + file.path = path; + file.resolvedPath = toPath(fileName); + file.originalFileName = originalFileName; + if (host.useCaseSensitiveFileNames()) { + var pathLowerCase = path.toLowerCase(); + // for case-sensitive file systems check if we've already seen some file with similar filename ignoring case + var existingFile = filesByNameIgnoreCase.get(pathLowerCase); + if (existingFile) { + reportFileNamesDifferOnlyInCasingError(fileName, existingFile.fileName, refFile, refPos, refEnd); + } + else { + filesByNameIgnoreCase.set(pathLowerCase, file); + } + } + skipDefaultLib = skipDefaultLib || (file.hasNoDefaultLib && !ignoreNoDefaultLib); + if (!options.noResolve) { + processReferencedFiles(file, isDefaultLib); + processTypeReferenceDirectives(file); + } + processLibReferenceDirectives(file); + // always process imported modules to record module name resolutions + processImportedModules(file); + if (isDefaultLib) { + processingDefaultLibFiles.push(file); + } + else { + processingOtherFiles.push(file); + } + } + return file; + } + function addFileToFilesByName(file, path, redirectedPath) { + filesByName.set(path, file); + if (redirectedPath) { + filesByName.set(redirectedPath, file); + } + } + function getProjectReferenceRedirect(fileName) { + // Ignore dts or any of the non ts files + if (!resolvedProjectReferences || !resolvedProjectReferences.length || ts.fileExtensionIs(fileName, ".d.ts" /* Dts */) || !ts.fileExtensionIsOneOf(fileName, ts.supportedTSExtensions)) { + return undefined; + } + // If this file is produced by a referenced project, we need to rewrite it to + // look in the output folder of the referenced project rather than the input + var referencedProject = getResolvedProjectReferenceToRedirect(fileName); + if (!referencedProject) { + return undefined; + } + var out = referencedProject.commandLine.options.outFile || referencedProject.commandLine.options.out; + return out ? + ts.changeExtension(out, ".d.ts" /* Dts */) : + ts.getOutputDeclarationFileName(fileName, referencedProject.commandLine); + } + /** + * Get the referenced project if the file is input file from that reference project + */ + function getResolvedProjectReferenceToRedirect(fileName) { + if (mapFromFileToProjectReferenceRedirects === undefined) { + mapFromFileToProjectReferenceRedirects = ts.createMap(); + forEachResolvedProjectReference(function (referencedProject, referenceProjectPath) { + // not input file from the referenced project, ignore + if (referencedProject && + toPath(options.configFilePath) !== referenceProjectPath) { + referencedProject.commandLine.fileNames.forEach(function (f) { + return mapFromFileToProjectReferenceRedirects.set(toPath(f), referenceProjectPath); + }); + } + }); + } + var referencedProjectPath = mapFromFileToProjectReferenceRedirects.get(toPath(fileName)); + return referencedProjectPath && getResolvedProjectReferenceByPath(referencedProjectPath); + } + function forEachResolvedProjectReference(cb) { + return forEachProjectReference(projectReferences, resolvedProjectReferences, function (resolvedRef, index, parent) { + var ref = (parent ? parent.commandLine.projectReferences : projectReferences)[index]; + var resolvedRefPath = toPath(resolveProjectReferencePath(ref)); + return cb(resolvedRef, resolvedRefPath); + }); + } + function forEachProjectReference(projectReferences, resolvedProjectReferences, cbResolvedRef, cbRef) { + var seenResolvedRefs; + return worker(projectReferences, resolvedProjectReferences, /*parent*/ undefined, cbResolvedRef, cbRef); + function worker(projectReferences, resolvedProjectReferences, parent, cbResolvedRef, cbRef) { + // Visit project references first + if (cbRef) { + var result = cbRef(projectReferences, parent); + if (result) { + return result; + } + } + return ts.forEach(resolvedProjectReferences, function (resolvedRef, index) { + if (ts.contains(seenResolvedRefs, resolvedRef)) { + // ignore recursives + return undefined; + } + var result = cbResolvedRef(resolvedRef, index, parent); + if (result) { + return result; + } + if (!resolvedRef) + return undefined; + (seenResolvedRefs || (seenResolvedRefs = [])).push(resolvedRef); + return worker(resolvedRef.commandLine.projectReferences, resolvedRef.references, resolvedRef, cbResolvedRef, cbRef); + }); + } + } + function getResolvedProjectReferenceByPath(projectReferencePath) { + if (!projectReferenceRedirects) { + return undefined; + } + return projectReferenceRedirects.get(projectReferencePath) || undefined; + } + function processReferencedFiles(file, isDefaultLib) { + ts.forEach(file.referencedFiles, function (ref) { + var referencedFileName = resolveTripleslashReference(ref.fileName, file.originalFileName); + processSourceFile(referencedFileName, isDefaultLib, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined, file, ref.pos, ref.end); + }); + } + function processTypeReferenceDirectives(file) { + // We lower-case all type references because npm automatically lowercases all packages. See GH#9824. + var typeDirectives = ts.map(file.typeReferenceDirectives, function (ref) { return ref.fileName.toLocaleLowerCase(); }); + if (!typeDirectives) { + return; + } + var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeDirectives, file.originalFileName, getResolvedProjectReferenceToRedirect(file.originalFileName)); + for (var i = 0; i < typeDirectives.length; i++) { + var ref = file.typeReferenceDirectives[i]; + var resolvedTypeReferenceDirective = resolutions[i]; + // store resolved type directive on the file + var fileName = ref.fileName.toLocaleLowerCase(); + ts.setResolvedTypeReferenceDirective(file, fileName, resolvedTypeReferenceDirective); + processTypeReferenceDirective(fileName, resolvedTypeReferenceDirective, file, ref.pos, ref.end); + } + } + function processTypeReferenceDirective(typeReferenceDirective, resolvedTypeReferenceDirective, refFile, refPos, refEnd) { + // If we already found this library as a primary reference - nothing to do + var previousResolution = resolvedTypeReferenceDirectives.get(typeReferenceDirective); + if (previousResolution && previousResolution.primary) { + return; + } + var saveResolution = true; + if (resolvedTypeReferenceDirective) { + if (resolvedTypeReferenceDirective.isExternalLibraryImport) + currentNodeModulesDepth++; + if (resolvedTypeReferenceDirective.primary) { + // resolved from the primary path + processSourceFile(resolvedTypeReferenceDirective.resolvedFileName, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, resolvedTypeReferenceDirective.packageId, refFile, refPos, refEnd); // TODO: GH#18217 + } + else { + // If we already resolved to this file, it must have been a secondary reference. Check file contents + // for sameness and possibly issue an error + if (previousResolution) { + // Don't bother reading the file again if it's the same file. + if (resolvedTypeReferenceDirective.resolvedFileName !== previousResolution.resolvedFileName) { + var otherFileText = host.readFile(resolvedTypeReferenceDirective.resolvedFileName); + if (otherFileText !== getSourceFile(previousResolution.resolvedFileName).text) { + fileProcessingDiagnostics.add(createDiagnostic(refFile, refPos, refEnd, // TODO: GH#18217 + ts.Diagnostics.Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict, typeReferenceDirective, resolvedTypeReferenceDirective.resolvedFileName, previousResolution.resolvedFileName)); + } + } + // don't overwrite previous resolution result + saveResolution = false; + } + else { + // First resolution of this library + processSourceFile(resolvedTypeReferenceDirective.resolvedFileName, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, resolvedTypeReferenceDirective.packageId, refFile, refPos, refEnd); + } + } + if (resolvedTypeReferenceDirective.isExternalLibraryImport) + currentNodeModulesDepth--; + } + else { + fileProcessingDiagnostics.add(createDiagnostic(refFile, refPos, refEnd, ts.Diagnostics.Cannot_find_type_definition_file_for_0, typeReferenceDirective)); // TODO: GH#18217 + } + if (saveResolution) { + resolvedTypeReferenceDirectives.set(typeReferenceDirective, resolvedTypeReferenceDirective); + } + } + function processLibReferenceDirectives(file) { + ts.forEach(file.libReferenceDirectives, function (libReference) { + var libName = libReference.fileName.toLocaleLowerCase(); + var libFileName = ts.libMap.get(libName); + if (libFileName) { + // we ignore any 'no-default-lib' reference set on this file. + processRootFile(ts.combinePaths(defaultLibraryPath, libFileName), /*isDefaultLib*/ true, /*ignoreNoDefaultLib*/ true); + } + else { + var unqualifiedLibName = ts.removeSuffix(ts.removePrefix(libName, "lib."), ".d.ts"); + var suggestion = ts.getSpellingSuggestion(unqualifiedLibName, ts.libs, ts.identity); + var message = suggestion ? ts.Diagnostics.Cannot_find_lib_definition_for_0_Did_you_mean_1 : ts.Diagnostics.Cannot_find_lib_definition_for_0; + fileProcessingDiagnostics.add(createDiagnostic(file, libReference.pos, libReference.end, message, libName, suggestion)); + } + }); + } + function createDiagnostic(refFile, refPos, refEnd, message) { + var args = []; + for (var _i = 4; _i < arguments.length; _i++) { + args[_i - 4] = arguments[_i]; + } + if (refFile === undefined || refPos === undefined || refEnd === undefined) { + return ts.createCompilerDiagnostic.apply(void 0, [message].concat(args)); + } + else { + return ts.createFileDiagnostic.apply(void 0, [refFile, refPos, refEnd - refPos, message].concat(args)); + } + } + function getCanonicalFileName(fileName) { + return host.getCanonicalFileName(fileName); + } + function processImportedModules(file) { + collectExternalModuleReferences(file); + if (file.imports.length || file.moduleAugmentations.length) { + // Because global augmentation doesn't have string literal name, we can check for global augmentation as such. + var moduleNames = getModuleNames(file); + var resolutions = resolveModuleNamesReusingOldState(moduleNames, ts.getNormalizedAbsolutePath(file.originalFileName, currentDirectory), file); + ts.Debug.assert(resolutions.length === moduleNames.length); + for (var i = 0; i < moduleNames.length; i++) { + var resolution = resolutions[i]; + ts.setResolvedModule(file, moduleNames[i], resolution); + if (!resolution) { + continue; + } + var isFromNodeModulesSearch = resolution.isExternalLibraryImport; + var isJsFile = !ts.resolutionExtensionIsTSOrJson(resolution.extension); + var isJsFileFromNodeModules = isFromNodeModulesSearch && isJsFile; + var resolvedFileName = resolution.resolvedFileName; + if (isFromNodeModulesSearch) { + currentNodeModulesDepth++; + } + // add file to program only if: + // - resolution was successful + // - noResolve is falsy + // - module name comes from the list of imports + // - it's not a top level JavaScript module that exceeded the search max + var elideImport = isJsFileFromNodeModules && currentNodeModulesDepth > maxNodeModuleJsDepth; + // Don't add the file if it has a bad extension (e.g. 'tsx' if we don't have '--allowJs') + // This may still end up being an untyped module -- the file won't be included but imports will be allowed. + var shouldAddFile = resolvedFileName + && !getResolutionDiagnostic(options, resolution) + && !options.noResolve + && i < file.imports.length + && !elideImport + && !(isJsFile && !options.allowJs) + && (ts.isInJSFile(file.imports[i]) || !(file.imports[i].flags & 2097152 /* JSDoc */)); + if (elideImport) { + modulesWithElidedImports.set(file.path, true); + } + else if (shouldAddFile) { + var path = toPath(resolvedFileName); + var pos = ts.skipTrivia(file.text, file.imports[i].pos); + findSourceFile(resolvedFileName, path, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, file, pos, file.imports[i].end, resolution.packageId); + } + if (isFromNodeModulesSearch) { + currentNodeModulesDepth--; + } + } + } + else { + // no imports - drop cached module resolutions + file.resolvedModules = undefined; + } + } + function computeCommonSourceDirectory(sourceFiles) { + var fileNames = ts.mapDefined(sourceFiles, function (file) { return file.isDeclarationFile ? undefined : file.fileName; }); + return computeCommonSourceDirectoryOfFilenames(fileNames, currentDirectory, getCanonicalFileName); + } + function checkSourceFilesBelongToPath(sourceFiles, rootDirectory) { + var allFilesBelongToPath = true; + var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory)); + for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) { + var sourceFile = sourceFiles_2[_i]; + if (!sourceFile.isDeclarationFile) { + var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); + if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, sourceFile.fileName, rootDirectory)); + allFilesBelongToPath = false; + } + } + } + return allFilesBelongToPath; + } + function parseProjectReferenceConfigFile(ref) { + if (!projectReferenceRedirects) { + projectReferenceRedirects = ts.createMap(); + } + // The actual filename (i.e. add "/tsconfig.json" if necessary) + var refPath = resolveProjectReferencePath(ref); + var sourceFilePath = toPath(refPath); + var fromCache = projectReferenceRedirects.get(sourceFilePath); + if (fromCache !== undefined) { + return fromCache || undefined; + } + // An absolute path pointing to the containing directory of the config file + var basePath = ts.getNormalizedAbsolutePath(ts.getDirectoryPath(refPath), host.getCurrentDirectory()); + var sourceFile = host.getSourceFile(refPath, 100 /* JSON */); + addFileToFilesByName(sourceFile, sourceFilePath, /*redirectedPath*/ undefined); + if (sourceFile === undefined) { + projectReferenceRedirects.set(sourceFilePath, false); + return undefined; + } + sourceFile.path = sourceFilePath; + sourceFile.resolvedPath = sourceFilePath; + sourceFile.originalFileName = refPath; + var commandLine = ts.parseJsonSourceFileConfigFileContent(sourceFile, configParsingHost, basePath, /*existingOptions*/ undefined, refPath); + var resolvedRef = { commandLine: commandLine, sourceFile: sourceFile }; + projectReferenceRedirects.set(sourceFilePath, resolvedRef); + if (commandLine.projectReferences) { + resolvedRef.references = commandLine.projectReferences.map(parseProjectReferenceConfigFile); + } + return resolvedRef; + } + function verifyCompilerOptions() { + if (options.strictPropertyInitialization && !ts.getStrictOptionValue(options, "strictNullChecks")) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "strictPropertyInitialization", "strictNullChecks"); + } + if (options.isolatedModules) { + if (ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, getEmitDeclarationOptionName(options), "isolatedModules"); + } + if (options.noEmitOnError) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmitOnError", "isolatedModules"); + } + if (options.out) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "out", "isolatedModules"); + } + if (options.outFile) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "outFile", "isolatedModules"); + } + } + if (options.inlineSourceMap) { + if (options.sourceMap) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "sourceMap", "inlineSourceMap"); + } + if (options.mapRoot) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "mapRoot", "inlineSourceMap"); + } + } + if (options.paths && options.baseUrl === undefined) { + createDiagnosticForOptionName(ts.Diagnostics.Option_paths_cannot_be_used_without_specifying_baseUrl_option, "paths"); + } + if (options.composite) { + if (options.declaration === false) { + createDiagnosticForOptionName(ts.Diagnostics.Composite_projects_may_not_disable_declaration_emit, "declaration"); + } + } + verifyProjectReferences(); + // List of collected files is complete; validate exhautiveness if this is a project with a file list + if (options.composite) { + var sourceFiles = files.filter(function (f) { return !f.isDeclarationFile; }); + if (rootNames.length < sourceFiles.length) { + var normalizedRootNames = rootNames.map(function (r) { return ts.normalizePath(r).toLowerCase(); }); + for (var _i = 0, _a = sourceFiles.map(function (f) { return ts.normalizePath(f.path).toLowerCase(); }); _i < _a.length; _i++) { + var file = _a[_i]; + if (normalizedRootNames.indexOf(file) === -1) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern, file)); + } + } + } + } + if (options.paths) { + for (var key in options.paths) { + if (!ts.hasProperty(options.paths, key)) { + continue; + } + if (!ts.hasZeroOrOneAsteriskCharacter(key)) { + createDiagnosticForOptionPaths(/*onKey*/ true, key, ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, key); + } + if (ts.isArray(options.paths[key])) { + var len = options.paths[key].length; + if (len === 0) { + createDiagnosticForOptionPaths(/*onKey*/ false, key, ts.Diagnostics.Substitutions_for_pattern_0_shouldn_t_be_an_empty_array, key); + } + for (var i = 0; i < len; i++) { + var subst = options.paths[key][i]; + var typeOfSubst = typeof subst; + if (typeOfSubst === "string") { + if (!ts.hasZeroOrOneAsteriskCharacter(subst)) { + createDiagnosticForOptionPathKeyValue(key, i, ts.Diagnostics.Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character, subst, key); + } + } + else { + createDiagnosticForOptionPathKeyValue(key, i, ts.Diagnostics.Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2, subst, key, typeOfSubst); + } + } + } + else { + createDiagnosticForOptionPaths(/*onKey*/ false, key, ts.Diagnostics.Substitutions_for_pattern_0_should_be_an_array, key); + } + } + } + if (!options.sourceMap && !options.inlineSourceMap) { + if (options.inlineSources) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided, "inlineSources"); + } + if (options.sourceRoot) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided, "sourceRoot"); + } + } + if (options.out && options.outFile) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "out", "outFile"); + } + if (options.mapRoot && !(options.sourceMap || options.declarationMap)) { + // Error to specify --mapRoot without --sourcemap + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "mapRoot", "sourceMap", "declarationMap"); + } + if (options.declarationDir) { + if (!ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "declarationDir", "declaration", "composite"); + } + if (options.out || options.outFile) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "declarationDir", options.out ? "out" : "outFile"); + } + } + if (options.declarationMap && !ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "declarationMap", "declaration", "composite"); + } + if (options.lib && options.noLib) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "lib", "noLib"); + } + if (options.noImplicitUseStrict && ts.getStrictOptionValue(options, "alwaysStrict")) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noImplicitUseStrict", "alwaysStrict"); + } + var languageVersion = options.target || 0 /* ES3 */; + var outFile = options.outFile || options.out; + var firstNonAmbientExternalModuleSourceFile = ts.find(files, function (f) { return ts.isExternalModule(f) && !f.isDeclarationFile; }); + if (options.isolatedModules) { + if (options.module === ts.ModuleKind.None && languageVersion < 2 /* ES2015 */) { + createDiagnosticForOptionName(ts.Diagnostics.Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher, "isolatedModules", "target"); + } + var firstNonExternalModuleSourceFile = ts.find(files, function (f) { return !ts.isExternalModule(f) && !f.isDeclarationFile && f.scriptKind !== 6 /* JSON */; }); + if (firstNonExternalModuleSourceFile) { + var span = ts.getErrorSpanForNode(firstNonExternalModuleSourceFile, firstNonExternalModuleSourceFile); + programDiagnostics.add(ts.createFileDiagnostic(firstNonExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided)); + } + } + else if (firstNonAmbientExternalModuleSourceFile && languageVersion < 2 /* ES2015 */ && options.module === ts.ModuleKind.None) { + // We cannot use createDiagnosticFromNode because nodes do not have parents yet + var span = ts.getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, firstNonAmbientExternalModuleSourceFile.externalModuleIndicator); + programDiagnostics.add(ts.createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_use_imports_exports_or_module_augmentations_when_module_is_none)); + } + // Cannot specify module gen that isn't amd or system with --out + if (outFile && !options.emitDeclarationOnly) { + if (options.module && !(options.module === ts.ModuleKind.AMD || options.module === ts.ModuleKind.System)) { + createDiagnosticForOptionName(ts.Diagnostics.Only_amd_and_system_modules_are_supported_alongside_0, options.out ? "out" : "outFile", "module"); + } + else if (options.module === undefined && firstNonAmbientExternalModuleSourceFile) { + var span = ts.getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, firstNonAmbientExternalModuleSourceFile.externalModuleIndicator); + programDiagnostics.add(ts.createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system, options.out ? "out" : "outFile")); + } + } + if (options.resolveJsonModule) { + if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { + createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy, "resolveJsonModule"); + } + // Any emit other than common js, amd, es2015 or esnext is error + else if (!ts.hasJsonModuleEmitEnabled(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_esNext, "resolveJsonModule", "module"); + } + } + // there has to be common source directory if user specified --outdir || --sourceRoot + // if user specified --mapRoot, there needs to be common source directory if there would be multiple files being emitted + if (options.outDir || // there is --outDir specified + options.sourceRoot || // there is --sourceRoot specified + options.mapRoot) { // there is --mapRoot specified + // Precalculate and cache the common source directory + var dir = getCommonSourceDirectory(); + // If we failed to find a good common directory, but outDir is specified and at least one of our files is on a windows drive/URL/other resource, add a failure + if (options.outDir && dir === "" && files.some(function (file) { return ts.getRootLength(file.fileName) > 1; })) { + createDiagnosticForOptionName(ts.Diagnostics.Cannot_find_the_common_subdirectory_path_for_the_input_files, "outDir"); + } + } + if (!options.noEmit && options.allowJs && ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "allowJs", getEmitDeclarationOptionName(options)); + } + if (options.checkJs && !options.allowJs) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "checkJs", "allowJs")); + } + if (options.emitDeclarationOnly) { + if (!ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "emitDeclarationOnly", "declaration", "composite"); + } + if (options.noEmit) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "emitDeclarationOnly", "noEmit"); + } + } + if (options.emitDecoratorMetadata && + !options.experimentalDecorators) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDecoratorMetadata", "experimentalDecorators"); + } + if (options.jsxFactory) { + if (options.reactNamespace) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "reactNamespace", "jsxFactory"); + } + if (!ts.parseIsolatedEntityName(options.jsxFactory, languageVersion)) { + createOptionValueDiagnostic("jsxFactory", ts.Diagnostics.Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name, options.jsxFactory); + } + } + else if (options.reactNamespace && !ts.isIdentifierText(options.reactNamespace, languageVersion)) { + createOptionValueDiagnostic("reactNamespace", ts.Diagnostics.Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier, options.reactNamespace); + } + // If the emit is enabled make sure that every output file is unique and not overwriting any of the input files + if (!options.noEmit && !options.suppressOutputPathCheck) { + var emitHost = getEmitHost(); + var emitFilesSeen_1 = ts.createMap(); + ts.forEachEmittedFile(emitHost, function (emitFileNames) { + if (!options.emitDeclarationOnly) { + verifyEmitFilePath(emitFileNames.jsFilePath, emitFilesSeen_1); + } + verifyEmitFilePath(emitFileNames.declarationFilePath, emitFilesSeen_1); + }); + } + // Verify that all the emit files are unique and don't overwrite input files + function verifyEmitFilePath(emitFileName, emitFilesSeen) { + if (emitFileName) { + var emitFilePath = toPath(emitFileName); + // Report error if the output overwrites input file + if (filesByName.has(emitFilePath)) { + var chain_2; + if (!options.configFilePath) { + // The program is from either an inferred project or an external project + chain_2 = ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig); + } + chain_2 = ts.chainDiagnosticMessages(chain_2, ts.Diagnostics.Cannot_write_file_0_because_it_would_overwrite_input_file, emitFileName); + blockEmittingOfFile(emitFileName, ts.createCompilerDiagnosticFromMessageChain(chain_2)); + } + var emitFileKey = !host.useCaseSensitiveFileNames() ? emitFilePath.toLocaleLowerCase() : emitFilePath; + // Report error if multiple files write into same file + if (emitFilesSeen.has(emitFileKey)) { + // Already seen the same emit file - report error + blockEmittingOfFile(emitFileName, ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files, emitFileName)); + } + else { + emitFilesSeen.set(emitFileKey, true); + } + } + } + } + function verifyProjectReferences() { + forEachProjectReference(projectReferences, resolvedProjectReferences, function (resolvedRef, index, parent) { + var ref = (parent ? parent.commandLine.projectReferences : projectReferences)[index]; + var parentFile = parent && parent.sourceFile; + if (!resolvedRef) { + createDiagnosticForReference(parentFile, index, ts.Diagnostics.File_0_not_found, ref.path); + return; + } + var options = resolvedRef.commandLine.options; + if (!options.composite) { + // ok to not have composite if the current program is container only + var inputs = parent ? parent.commandLine.fileNames : rootNames; + if (inputs.length) { + createDiagnosticForReference(parentFile, index, ts.Diagnostics.Referenced_project_0_must_have_setting_composite_Colon_true, ref.path); + } + } + if (ref.prepend) { + var out = options.outFile || options.out; + if (out) { + if (!host.fileExists(out)) { + createDiagnosticForReference(parentFile, index, ts.Diagnostics.Output_file_0_from_project_1_does_not_exist, out, ref.path); + } + } + else { + createDiagnosticForReference(parentFile, index, ts.Diagnostics.Cannot_prepend_project_0_because_it_does_not_have_outFile_set, ref.path); + } + } + }); + } + function createDiagnosticForOptionPathKeyValue(key, valueIndex, message, arg0, arg1, arg2) { + var needCompilerDiagnostic = true; + var pathsSyntax = getOptionPathsSyntax(); + for (var _i = 0, pathsSyntax_1 = pathsSyntax; _i < pathsSyntax_1.length; _i++) { + var pathProp = pathsSyntax_1[_i]; + if (ts.isObjectLiteralExpression(pathProp.initializer)) { + for (var _a = 0, _b = ts.getPropertyAssignment(pathProp.initializer, key); _a < _b.length; _a++) { + var keyProps = _b[_a]; + var initializer = keyProps.initializer; + if (ts.isArrayLiteralExpression(initializer) && initializer.elements.length > valueIndex) { + programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(options.configFile, initializer.elements[valueIndex], message, arg0, arg1, arg2)); + needCompilerDiagnostic = false; + } + } + } + } + if (needCompilerDiagnostic) { + programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1, arg2)); + } + } + function createDiagnosticForOptionPaths(onKey, key, message, arg0) { + var needCompilerDiagnostic = true; + var pathsSyntax = getOptionPathsSyntax(); + for (var _i = 0, pathsSyntax_2 = pathsSyntax; _i < pathsSyntax_2.length; _i++) { + var pathProp = pathsSyntax_2[_i]; + if (ts.isObjectLiteralExpression(pathProp.initializer) && + createOptionDiagnosticInObjectLiteralSyntax(pathProp.initializer, onKey, key, /*key2*/ undefined, message, arg0)) { + needCompilerDiagnostic = false; + } + } + if (needCompilerDiagnostic) { + programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0)); + } + } + function getOptionsSyntaxByName(name) { + var compilerOptionsObjectLiteralSyntax = getCompilerOptionsObjectLiteralSyntax(); + if (compilerOptionsObjectLiteralSyntax) { + return ts.getPropertyAssignment(compilerOptionsObjectLiteralSyntax, name); + } + return undefined; + } + function getOptionPathsSyntax() { + return getOptionsSyntaxByName("paths") || ts.emptyArray; + } + function createDiagnosticForOptionName(message, option1, option2, option3) { + createDiagnosticForOption(/*onKey*/ true, option1, option2, message, option1, option2, option3); + } + function createOptionValueDiagnostic(option1, message, arg0) { + createDiagnosticForOption(/*onKey*/ false, option1, /*option2*/ undefined, message, arg0); + } + function createDiagnosticForReference(sourceFile, index, message, arg0, arg1) { + var referencesSyntax = ts.firstDefined(ts.getTsConfigPropArray(sourceFile || options.configFile, "references"), function (property) { return ts.isArrayLiteralExpression(property.initializer) ? property.initializer : undefined; }); + if (referencesSyntax && referencesSyntax.elements.length > index) { + programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(sourceFile || options.configFile, referencesSyntax.elements[index], message, arg0, arg1)); + } + else { + programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1)); + } + } + function createDiagnosticForOption(onKey, option1, option2, message, arg0, arg1, arg2) { + var compilerOptionsObjectLiteralSyntax = getCompilerOptionsObjectLiteralSyntax(); + var needCompilerDiagnostic = !compilerOptionsObjectLiteralSyntax || + !createOptionDiagnosticInObjectLiteralSyntax(compilerOptionsObjectLiteralSyntax, onKey, option1, option2, message, arg0, arg1, arg2); + if (needCompilerDiagnostic) { + programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1, arg2)); + } + } + function getCompilerOptionsObjectLiteralSyntax() { + if (_compilerOptionsObjectLiteralSyntax === undefined) { + _compilerOptionsObjectLiteralSyntax = null; // tslint:disable-line:no-null-keyword + var jsonObjectLiteral = ts.getTsConfigObjectLiteralExpression(options.configFile); + if (jsonObjectLiteral) { + for (var _i = 0, _a = ts.getPropertyAssignment(jsonObjectLiteral, "compilerOptions"); _i < _a.length; _i++) { + var prop = _a[_i]; + if (ts.isObjectLiteralExpression(prop.initializer)) { + _compilerOptionsObjectLiteralSyntax = prop.initializer; + break; + } + } + } + } + return _compilerOptionsObjectLiteralSyntax; + } + function createOptionDiagnosticInObjectLiteralSyntax(objectLiteral, onKey, key1, key2, message, arg0, arg1, arg2) { + var props = ts.getPropertyAssignment(objectLiteral, key1, key2); + for (var _i = 0, props_2 = props; _i < props_2.length; _i++) { + var prop = props_2[_i]; + programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(options.configFile, onKey ? prop.name : prop.initializer, message, arg0, arg1, arg2)); + } + return !!props.length; + } + function blockEmittingOfFile(emitFileName, diag) { + hasEmitBlockingDiagnostics.set(toPath(emitFileName), true); + programDiagnostics.add(diag); + } + function isEmittedFile(file) { + if (options.noEmit) { + return false; + } + // If this is source file, its not emitted file + var filePath = toPath(file); + if (getSourceFileByPath(filePath)) { + return false; + } + // If options have --outFile or --out just check that + var out = options.outFile || options.out; + if (out) { + return isSameFile(filePath, out) || isSameFile(filePath, ts.removeFileExtension(out) + ".d.ts" /* Dts */); + } + // If declarationDir is specified, return if its a file in that directory + if (options.declarationDir && ts.containsPath(options.declarationDir, filePath, currentDirectory, !host.useCaseSensitiveFileNames())) { + return true; + } + // If --outDir, check if file is in that directory + if (options.outDir) { + return ts.containsPath(options.outDir, filePath, currentDirectory, !host.useCaseSensitiveFileNames()); + } + if (ts.fileExtensionIsOneOf(filePath, ts.supportedJSExtensions) || ts.fileExtensionIs(filePath, ".d.ts" /* Dts */)) { + // Otherwise just check if sourceFile with the name exists + var filePathWithoutExtension = ts.removeFileExtension(filePath); + return !!getSourceFileByPath((filePathWithoutExtension + ".ts" /* Ts */)) || + !!getSourceFileByPath((filePathWithoutExtension + ".tsx" /* Tsx */)); + } + return false; + } + function isSameFile(file1, file2) { + return ts.comparePaths(file1, file2, currentDirectory, !host.useCaseSensitiveFileNames()) === 0 /* EqualTo */; + } + } + ts.createProgram = createProgram; + /* @internal */ + function parseConfigHostFromCompilerHost(host) { + return { + fileExists: function (f) { return host.fileExists(f); }, + readDirectory: function (root, extensions, excludes, includes, depth) { + ts.Debug.assertDefined(host.readDirectory, "'CompilerHost.readDirectory' must be implemented to correctly process 'projectReferences'"); + return host.readDirectory(root, extensions, excludes, includes, depth); + }, + readFile: function (f) { return host.readFile(f); }, + useCaseSensitiveFileNames: host.useCaseSensitiveFileNames(), + getCurrentDirectory: function () { return host.getCurrentDirectory(); }, + onUnRecoverableConfigFileDiagnostic: function () { return undefined; }, + trace: host.trace ? function (s) { return host.trace(s); } : undefined + }; + } + ts.parseConfigHostFromCompilerHost = parseConfigHostFromCompilerHost; + function resolveProjectReferencePath(hostOrRef, ref) { + var passedInRef = ref ? ref : hostOrRef; + return ts.resolveConfigFileProjectName(passedInRef.path); + } + ts.resolveProjectReferencePath = resolveProjectReferencePath; + function getEmitDeclarationOptionName(options) { + return options.declaration ? "declaration" : "composite"; + } + /* @internal */ + /** + * Returns a DiagnosticMessage if we won't include a resolved module due to its extension. + * The DiagnosticMessage's parameters are the imported module name, and the filename it resolved to. + * This returns a diagnostic even if the module will be an untyped module. + */ + function getResolutionDiagnostic(options, _a) { + var extension = _a.extension; + switch (extension) { + case ".ts" /* Ts */: + case ".d.ts" /* Dts */: + // These are always allowed. + return undefined; + case ".tsx" /* Tsx */: + return needJsx(); + case ".jsx" /* Jsx */: + return needJsx() || needAllowJs(); + case ".js" /* Js */: + return needAllowJs(); + case ".json" /* Json */: + return needResolveJsonModule(); + } + function needJsx() { + return options.jsx ? undefined : ts.Diagnostics.Module_0_was_resolved_to_1_but_jsx_is_not_set; + } + function needAllowJs() { + return options.allowJs || !ts.getStrictOptionValue(options, "noImplicitAny") ? undefined : ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type; + } + function needResolveJsonModule() { + return options.resolveJsonModule ? undefined : ts.Diagnostics.Module_0_was_resolved_to_1_but_resolveJsonModule_is_not_used; + } + } + ts.getResolutionDiagnostic = getResolutionDiagnostic; + function getModuleNames(_a) { + var imports = _a.imports, moduleAugmentations = _a.moduleAugmentations; + var res = imports.map(function (i) { return i.text; }); + for (var _i = 0, moduleAugmentations_1 = moduleAugmentations; _i < moduleAugmentations_1.length; _i++) { + var aug = moduleAugmentations_1[_i]; + if (aug.kind === 10 /* StringLiteral */) { + res.push(aug.text); + } + // Do nothing if it's an Identifier; we don't need to do module resolution for `declare global`. + } + return res; + } +})(ts || (ts = {})); +/*@internal*/ +var ts; +(function (ts) { + function getFileEmitOutput(program, sourceFile, emitOnlyDtsFiles, cancellationToken, customTransformers) { + var outputFiles = []; + var emitResult = program.emit(sourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); + return { outputFiles: outputFiles, emitSkipped: emitResult.emitSkipped, exportedModulesFromDeclarationEmit: emitResult.exportedModulesFromDeclarationEmit }; + function writeFile(fileName, text, writeByteOrderMark) { + outputFiles.push({ name: fileName, writeByteOrderMark: writeByteOrderMark, text: text }); + } + } + ts.getFileEmitOutput = getFileEmitOutput; +})(ts || (ts = {})); +/*@internal*/ +(function (ts) { + var BuilderState; + (function (BuilderState) { + /** + * Get the referencedFile from the imported module symbol + */ + function getReferencedFileFromImportedModuleSymbol(symbol) { + if (symbol.declarations && symbol.declarations[0]) { + var declarationSourceFile = ts.getSourceFileOfNode(symbol.declarations[0]); + return declarationSourceFile && declarationSourceFile.resolvedPath; + } + } + /** + * Get the referencedFile from the import name node from file + */ + function getReferencedFileFromImportLiteral(checker, importName) { + var symbol = checker.getSymbolAtLocation(importName); + return symbol && getReferencedFileFromImportedModuleSymbol(symbol); + } + /** + * Gets the path to reference file from file name, it could be resolvedPath if present otherwise path + */ + function getReferencedFileFromFileName(program, fileName, sourceFileDirectory, getCanonicalFileName) { + return ts.toPath(program.getProjectReferenceRedirect(fileName) || fileName, sourceFileDirectory, getCanonicalFileName); + } + /** + * Gets the referenced files for a file from the program with values for the keys as referenced file's path to be true + */ + function getReferencedFiles(program, sourceFile, getCanonicalFileName) { + var referencedFiles; + // We need to use a set here since the code can contain the same import twice, + // but that will only be one dependency. + // To avoid invernal conversion, the key of the referencedFiles map must be of type Path + if (sourceFile.imports && sourceFile.imports.length > 0) { + var checker = program.getTypeChecker(); + for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { + var importName = _a[_i]; + var declarationSourceFilePath = getReferencedFileFromImportLiteral(checker, importName); + if (declarationSourceFilePath) { + addReferencedFile(declarationSourceFilePath); + } + } + } + var sourceFileDirectory = ts.getDirectoryPath(sourceFile.path); + // Handle triple slash references + if (sourceFile.referencedFiles && sourceFile.referencedFiles.length > 0) { + for (var _b = 0, _c = sourceFile.referencedFiles; _b < _c.length; _b++) { + var referencedFile = _c[_b]; + var referencedPath = getReferencedFileFromFileName(program, referencedFile.fileName, sourceFileDirectory, getCanonicalFileName); + addReferencedFile(referencedPath); + } + } + // Handle type reference directives + if (sourceFile.resolvedTypeReferenceDirectiveNames) { + sourceFile.resolvedTypeReferenceDirectiveNames.forEach(function (resolvedTypeReferenceDirective) { + if (!resolvedTypeReferenceDirective) { + return; + } + var fileName = resolvedTypeReferenceDirective.resolvedFileName; // TODO: GH#18217 + var typeFilePath = getReferencedFileFromFileName(program, fileName, sourceFileDirectory, getCanonicalFileName); + addReferencedFile(typeFilePath); + }); + } + // Add module augmentation as references + if (sourceFile.moduleAugmentations.length) { + var checker = program.getTypeChecker(); + for (var _d = 0, _e = sourceFile.moduleAugmentations; _d < _e.length; _d++) { + var moduleName = _e[_d]; + if (!ts.isStringLiteral(moduleName)) { + continue; + } + var symbol = checker.getSymbolAtLocation(moduleName); + if (!symbol) { + continue; + } + // Add any file other than our own as reference + addReferenceFromAmbientModule(symbol); + } + } + // From ambient modules + for (var _f = 0, _g = program.getTypeChecker().getAmbientModules(); _f < _g.length; _f++) { + var ambientModule = _g[_f]; + if (ambientModule.declarations.length > 1) { + addReferenceFromAmbientModule(ambientModule); + } + } + return referencedFiles; + function addReferenceFromAmbientModule(symbol) { + // Add any file other than our own as reference + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + var declarationSourceFile = ts.getSourceFileOfNode(declaration); + if (declarationSourceFile && + declarationSourceFile !== sourceFile) { + addReferencedFile(declarationSourceFile.resolvedPath); + } + } + } + function addReferencedFile(referencedPath) { + if (!referencedFiles) { + referencedFiles = ts.createMap(); + } + referencedFiles.set(referencedPath, true); + } + } + /** + * Returns true if oldState is reusable, that is the emitKind = module/non module has not changed + */ + function canReuseOldState(newReferencedMap, oldState) { + return oldState && !oldState.referencedMap === !newReferencedMap; + } + BuilderState.canReuseOldState = canReuseOldState; + /** + * Creates the state of file references and signature for the new program from oldState if it is safe + */ + function create(newProgram, getCanonicalFileName, oldState) { + var fileInfos = ts.createMap(); + var referencedMap = newProgram.getCompilerOptions().module !== ts.ModuleKind.None ? ts.createMap() : undefined; + var exportedModulesMap = referencedMap ? ts.createMap() : undefined; + var hasCalledUpdateShapeSignature = ts.createMap(); + var useOldState = canReuseOldState(referencedMap, oldState); + // Create the reference map, and set the file infos + for (var _i = 0, _a = newProgram.getSourceFiles(); _i < _a.length; _i++) { + var sourceFile = _a[_i]; + var version_1 = sourceFile.version; + var oldInfo = useOldState ? oldState.fileInfos.get(sourceFile.path) : undefined; + if (referencedMap) { + var newReferences = getReferencedFiles(newProgram, sourceFile, getCanonicalFileName); + if (newReferences) { + referencedMap.set(sourceFile.path, newReferences); + } + // Copy old visible to outside files map + if (useOldState) { + var exportedModules = oldState.exportedModulesMap.get(sourceFile.path); + if (exportedModules) { + exportedModulesMap.set(sourceFile.path, exportedModules); + } + } + } + fileInfos.set(sourceFile.path, { version: version_1, signature: oldInfo && oldInfo.signature }); + } + return { + fileInfos: fileInfos, + referencedMap: referencedMap, + exportedModulesMap: exportedModulesMap, + hasCalledUpdateShapeSignature: hasCalledUpdateShapeSignature, + allFilesExcludingDefaultLibraryFile: undefined, + allFileNames: undefined + }; + } + BuilderState.create = create; + /** + * Gets the files affected by the path from the program + */ + function getFilesAffectedBy(state, programOfThisState, path, cancellationToken, computeHash, cacheToUpdateSignature, exportedModulesMapCache) { + // Since the operation could be cancelled, the signatures are always stored in the cache + // They will be commited once it is safe to use them + // eg when calling this api from tsserver, if there is no cancellation of the operation + // In the other cases the affected files signatures are commited only after the iteration through the result is complete + var signatureCache = cacheToUpdateSignature || ts.createMap(); + var sourceFile = programOfThisState.getSourceFileByPath(path); + if (!sourceFile) { + return ts.emptyArray; + } + if (!updateShapeSignature(state, programOfThisState, sourceFile, signatureCache, cancellationToken, computeHash, exportedModulesMapCache)) { + return [sourceFile]; + } + var result = (state.referencedMap ? getFilesAffectedByUpdatedShapeWhenModuleEmit : getFilesAffectedByUpdatedShapeWhenNonModuleEmit)(state, programOfThisState, sourceFile, signatureCache, cancellationToken, computeHash, exportedModulesMapCache); + if (!cacheToUpdateSignature) { + // Commit all the signatures in the signature cache + updateSignaturesFromCache(state, signatureCache); + } + return result; + } + BuilderState.getFilesAffectedBy = getFilesAffectedBy; + /** + * Updates the signatures from the cache into state's fileinfo signatures + * This should be called whenever it is safe to commit the state of the builder + */ + function updateSignaturesFromCache(state, signatureCache) { + signatureCache.forEach(function (signature, path) { + state.fileInfos.get(path).signature = signature; + state.hasCalledUpdateShapeSignature.set(path, true); + }); + } + BuilderState.updateSignaturesFromCache = updateSignaturesFromCache; + /** + * Returns if the shape of the signature has changed since last emit + */ + function updateShapeSignature(state, programOfThisState, sourceFile, cacheToUpdateSignature, cancellationToken, computeHash, exportedModulesMapCache) { + ts.Debug.assert(!!sourceFile); + ts.Debug.assert(!exportedModulesMapCache || !!state.exportedModulesMap, "Compute visible to outside map only if visibleToOutsideReferencedMap present in the state"); + // If we have cached the result for this file, that means hence forth we should assume file shape is uptodate + if (state.hasCalledUpdateShapeSignature.has(sourceFile.path) || cacheToUpdateSignature.has(sourceFile.path)) { + return false; + } + var info = state.fileInfos.get(sourceFile.path); + if (!info) + return ts.Debug.fail(); + var prevSignature = info.signature; + var latestSignature; + if (sourceFile.isDeclarationFile) { + latestSignature = sourceFile.version; + if (exportedModulesMapCache && latestSignature !== prevSignature) { + // All the references in this file are exported + var references = state.referencedMap ? state.referencedMap.get(sourceFile.path) : undefined; + exportedModulesMapCache.set(sourceFile.path, references || false); + } + } + else { + var emitOutput = ts.getFileEmitOutput(programOfThisState, sourceFile, /*emitOnlyDtsFiles*/ true, cancellationToken); + if (emitOutput.outputFiles && emitOutput.outputFiles.length > 0) { + latestSignature = computeHash(emitOutput.outputFiles[0].text); + if (exportedModulesMapCache && latestSignature !== prevSignature) { + updateExportedModules(sourceFile, emitOutput.exportedModulesFromDeclarationEmit, exportedModulesMapCache); + } + } + else { + latestSignature = prevSignature; // TODO: GH#18217 + } + } + cacheToUpdateSignature.set(sourceFile.path, latestSignature); + return !prevSignature || latestSignature !== prevSignature; + } + /** + * Coverts the declaration emit result into exported modules map + */ + function updateExportedModules(sourceFile, exportedModulesFromDeclarationEmit, exportedModulesMapCache) { + if (!exportedModulesFromDeclarationEmit) { + exportedModulesMapCache.set(sourceFile.path, false); + return; + } + var exportedModules; + exportedModulesFromDeclarationEmit.forEach(function (symbol) { return addExportedModule(getReferencedFileFromImportedModuleSymbol(symbol)); }); + exportedModulesMapCache.set(sourceFile.path, exportedModules || false); + function addExportedModule(exportedModulePath) { + if (exportedModulePath) { + if (!exportedModules) { + exportedModules = ts.createMap(); + } + exportedModules.set(exportedModulePath, true); + } + } + } + /** + * Updates the exported modules from cache into state's exported modules map + * This should be called whenever it is safe to commit the state of the builder + */ + function updateExportedFilesMapFromCache(state, exportedModulesMapCache) { + if (exportedModulesMapCache) { + ts.Debug.assert(!!state.exportedModulesMap); + exportedModulesMapCache.forEach(function (exportedModules, path) { + if (exportedModules) { + state.exportedModulesMap.set(path, exportedModules); + } + else { + state.exportedModulesMap.delete(path); + } + }); + } + } + BuilderState.updateExportedFilesMapFromCache = updateExportedFilesMapFromCache; + /** + * Get all the dependencies of the sourceFile + */ + function getAllDependencies(state, programOfThisState, sourceFile) { + var _a; + var compilerOptions = programOfThisState.getCompilerOptions(); + // With --out or --outFile all outputs go into single file, all files depend on each other + if (compilerOptions.outFile || compilerOptions.out) { + return getAllFileNames(state, programOfThisState); + } + // If this is non module emit, or its a global file, it depends on all the source files + if (!state.referencedMap || isFileAffectingGlobalScope(sourceFile)) { + return getAllFileNames(state, programOfThisState); + } + // Get the references, traversing deep from the referenceMap + var seenMap = ts.createMap(); + var queue = [sourceFile.path]; + while (queue.length) { + var path = queue.pop(); + if (!seenMap.has(path)) { + seenMap.set(path, true); + var references = state.referencedMap.get(path); + if (references) { + var iterator = references.keys(); + for (var _b = iterator.next(), value = _b.value, done = _b.done; !done; _a = iterator.next(), value = _a.value, done = _a.done, _a) { + queue.push(value); + } + } + } + } + return ts.arrayFrom(ts.mapDefinedIterator(seenMap.keys(), function (path) { + var file = programOfThisState.getSourceFileByPath(path); + return file ? file.fileName : path; + })); + } + BuilderState.getAllDependencies = getAllDependencies; + /** + * Gets the names of all files from the program + */ + function getAllFileNames(state, programOfThisState) { + if (!state.allFileNames) { + var sourceFiles = programOfThisState.getSourceFiles(); + state.allFileNames = sourceFiles === ts.emptyArray ? ts.emptyArray : sourceFiles.map(function (file) { return file.fileName; }); + } + return state.allFileNames; + } + /** + * Gets the files referenced by the the file path + */ + function getReferencedByPaths(state, referencedFilePath) { + return ts.arrayFrom(ts.mapDefinedIterator(state.referencedMap.entries(), function (_a) { + var filePath = _a[0], referencesInFile = _a[1]; + return referencesInFile.has(referencedFilePath) ? filePath : undefined; + })); + } + /** + * For script files that contains only ambient external modules, although they are not actually external module files, + * they can only be consumed via importing elements from them. Regular script files cannot consume them. Therefore, + * there are no point to rebuild all script files if these special files have changed. However, if any statement + * in the file is not ambient external module, we treat it as a regular script file. + */ + function containsOnlyAmbientModules(sourceFile) { + for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + if (!ts.isModuleWithStringLiteralName(statement)) { + return false; + } + } + return true; + } + /** + * Return true if file contains anything that augments to global scope we need to build them as if + * they are global files as well as module + */ + function containsGlobalScopeAugmentation(sourceFile) { + return ts.some(sourceFile.moduleAugmentations, function (augmentation) { return ts.isGlobalScopeAugmentation(augmentation.parent); }); + } + /** + * Return true if the file will invalidate all files because it affectes global scope + */ + function isFileAffectingGlobalScope(sourceFile) { + return containsGlobalScopeAugmentation(sourceFile) || + !ts.isExternalModule(sourceFile) && !containsOnlyAmbientModules(sourceFile); + } + /** + * Gets all files of the program excluding the default library file + */ + function getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, firstSourceFile) { + // Use cached result + if (state.allFilesExcludingDefaultLibraryFile) { + return state.allFilesExcludingDefaultLibraryFile; + } + var result; + addSourceFile(firstSourceFile); + for (var _i = 0, _a = programOfThisState.getSourceFiles(); _i < _a.length; _i++) { + var sourceFile = _a[_i]; + if (sourceFile !== firstSourceFile) { + addSourceFile(sourceFile); + } + } + state.allFilesExcludingDefaultLibraryFile = result || ts.emptyArray; + return state.allFilesExcludingDefaultLibraryFile; + function addSourceFile(sourceFile) { + if (!programOfThisState.isSourceFileDefaultLibrary(sourceFile)) { + (result || (result = [])).push(sourceFile); + } + } + } + /** + * When program emits non modular code, gets the files affected by the sourceFile whose shape has changed + */ + function getFilesAffectedByUpdatedShapeWhenNonModuleEmit(state, programOfThisState, sourceFileWithUpdatedShape) { + var compilerOptions = programOfThisState.getCompilerOptions(); + // If `--out` or `--outFile` is specified, any new emit will result in re-emitting the entire project, + // so returning the file itself is good enough. + if (compilerOptions && (compilerOptions.out || compilerOptions.outFile)) { + return [sourceFileWithUpdatedShape]; + } + return getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, sourceFileWithUpdatedShape); + } + /** + * When program emits modular code, gets the files affected by the sourceFile whose shape has changed + */ + function getFilesAffectedByUpdatedShapeWhenModuleEmit(state, programOfThisState, sourceFileWithUpdatedShape, cacheToUpdateSignature, cancellationToken, computeHash, exportedModulesMapCache) { + if (isFileAffectingGlobalScope(sourceFileWithUpdatedShape)) { + return getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, sourceFileWithUpdatedShape); + } + var compilerOptions = programOfThisState.getCompilerOptions(); + if (compilerOptions && (compilerOptions.isolatedModules || compilerOptions.out || compilerOptions.outFile)) { + return [sourceFileWithUpdatedShape]; + } + // Now we need to if each file in the referencedBy list has a shape change as well. + // Because if so, its own referencedBy files need to be saved as well to make the + // emitting result consistent with files on disk. + var seenFileNamesMap = ts.createMap(); + // Start with the paths this file was referenced by + seenFileNamesMap.set(sourceFileWithUpdatedShape.path, sourceFileWithUpdatedShape); + var queue = getReferencedByPaths(state, sourceFileWithUpdatedShape.path); + while (queue.length > 0) { + var currentPath = queue.pop(); + if (!seenFileNamesMap.has(currentPath)) { + var currentSourceFile = programOfThisState.getSourceFileByPath(currentPath); + seenFileNamesMap.set(currentPath, currentSourceFile); + if (currentSourceFile && updateShapeSignature(state, programOfThisState, currentSourceFile, cacheToUpdateSignature, cancellationToken, computeHash, exportedModulesMapCache)) { // TODO: GH#18217 + queue.push.apply(// TODO: GH#18217 + queue, getReferencedByPaths(state, currentPath)); + } + } + } + // Return array of values that needs emit + // Return array of values that needs emit + return ts.arrayFrom(ts.mapDefinedIterator(seenFileNamesMap.values(), function (value) { return value; })); + } + })(BuilderState = ts.BuilderState || (ts.BuilderState = {})); +})(ts || (ts = {})); +/*@internal*/ +var ts; +(function (ts) { + function hasSameKeys(map1, map2) { + // Has same size and every key is present in both maps + return map1 === map2 || map1 !== undefined && map2 !== undefined && map1.size === map2.size && !ts.forEachKey(map1, function (key) { return !map2.has(key); }); + } + /** + * Create the state so that we can iterate on changedFiles/affected files + */ + function createBuilderProgramState(newProgram, getCanonicalFileName, oldState) { + var state = ts.BuilderState.create(newProgram, getCanonicalFileName, oldState); + state.program = newProgram; + var compilerOptions = newProgram.getCompilerOptions(); + if (!compilerOptions.outFile && !compilerOptions.out) { + state.semanticDiagnosticsPerFile = ts.createMap(); + } + state.changedFilesSet = ts.createMap(); + var useOldState = ts.BuilderState.canReuseOldState(state.referencedMap, oldState); + var oldCompilerOptions = useOldState ? oldState.program.getCompilerOptions() : undefined; + var canCopySemanticDiagnostics = useOldState && oldState.semanticDiagnosticsPerFile && !!state.semanticDiagnosticsPerFile && + !ts.compilerOptionsAffectSemanticDiagnostics(compilerOptions, oldCompilerOptions); + if (useOldState) { + // Verify the sanity of old state + if (!oldState.currentChangedFilePath) { + ts.Debug.assert(!oldState.affectedFiles && (!oldState.currentAffectedFilesSignatures || !oldState.currentAffectedFilesSignatures.size), "Cannot reuse if only few affected files of currentChangedFile were iterated"); + } + if (canCopySemanticDiagnostics) { + ts.Debug.assert(!ts.forEachKey(oldState.changedFilesSet, function (path) { return oldState.semanticDiagnosticsPerFile.has(path); }), "Semantic diagnostics shouldnt be available for changed files"); + } + // Copy old state's changed files set + ts.copyEntries(oldState.changedFilesSet, state.changedFilesSet); + } + // Update changed files and copy semantic diagnostics if we can + var referencedMap = state.referencedMap; + var oldReferencedMap = useOldState ? oldState.referencedMap : undefined; + var copyDeclarationFileDiagnostics = canCopySemanticDiagnostics && !compilerOptions.skipLibCheck === !oldCompilerOptions.skipLibCheck; + var copyLibFileDiagnostics = copyDeclarationFileDiagnostics && !compilerOptions.skipDefaultLibCheck === !oldCompilerOptions.skipDefaultLibCheck; + state.fileInfos.forEach(function (info, sourceFilePath) { + var oldInfo; + var newReferences; + // if not using old state, every file is changed + if (!useOldState || + // File wasnt present in old state + !(oldInfo = oldState.fileInfos.get(sourceFilePath)) || + // versions dont match + oldInfo.version !== info.version || + // Referenced files changed + !hasSameKeys(newReferences = referencedMap && referencedMap.get(sourceFilePath), oldReferencedMap && oldReferencedMap.get(sourceFilePath)) || + // Referenced file was deleted in the new program + newReferences && ts.forEachKey(newReferences, function (path) { return !state.fileInfos.has(path) && oldState.fileInfos.has(path); })) { + // Register file as changed file and do not copy semantic diagnostics, since all changed files need to be re-evaluated + state.changedFilesSet.set(sourceFilePath, true); + } + else if (canCopySemanticDiagnostics) { + var sourceFile = state.program.getSourceFileByPath(sourceFilePath); + if (sourceFile.isDeclarationFile && !copyDeclarationFileDiagnostics) { + return; + } + if (sourceFile.hasNoDefaultLib && !copyLibFileDiagnostics) { + return; + } + // Unchanged file copy diagnostics + var diagnostics = oldState.semanticDiagnosticsPerFile.get(sourceFilePath); + if (diagnostics) { + state.semanticDiagnosticsPerFile.set(sourceFilePath, diagnostics); + if (!state.semanticDiagnosticsFromOldState) { + state.semanticDiagnosticsFromOldState = ts.createMap(); + } + state.semanticDiagnosticsFromOldState.set(sourceFilePath, true); + } + } + }); + return state; + } + /** + * Verifies that source file is ok to be used in calls that arent handled by next + */ + function assertSourceFileOkWithoutNextAffectedCall(state, sourceFile) { + ts.Debug.assert(!sourceFile || !state.affectedFiles || state.affectedFiles[state.affectedFilesIndex - 1] !== sourceFile || !state.semanticDiagnosticsPerFile.has(sourceFile.path)); + } + /** + * This function returns the next affected file to be processed. + * Note that until doneAffected is called it would keep reporting same result + * This is to allow the callers to be able to actually remove affected file only when the operation is complete + * eg. if during diagnostics check cancellation token ends up cancelling the request, the affected file should be retained + */ + function getNextAffectedFile(state, cancellationToken, computeHash) { + while (true) { + var affectedFiles = state.affectedFiles; + if (affectedFiles) { + var seenAffectedFiles = state.seenAffectedFiles; + var affectedFilesIndex = state.affectedFilesIndex; // TODO: GH#18217 + while (affectedFilesIndex < affectedFiles.length) { + var affectedFile = affectedFiles[affectedFilesIndex]; + if (!seenAffectedFiles.has(affectedFile.path)) { + // Set the next affected file as seen and remove the cached semantic diagnostics + state.affectedFilesIndex = affectedFilesIndex; + cleanSemanticDiagnosticsOfAffectedFile(state, affectedFile); + return affectedFile; + } + seenAffectedFiles.set(affectedFile.path, true); + affectedFilesIndex++; + } + // Remove the changed file from the change set + state.changedFilesSet.delete(state.currentChangedFilePath); + state.currentChangedFilePath = undefined; + // Commit the changes in file signature + ts.BuilderState.updateSignaturesFromCache(state, state.currentAffectedFilesSignatures); + state.currentAffectedFilesSignatures.clear(); + ts.BuilderState.updateExportedFilesMapFromCache(state, state.currentAffectedFilesExportedModulesMap); + state.affectedFiles = undefined; + } + // Get next changed file + var nextKey = state.changedFilesSet.keys().next(); + if (nextKey.done) { + // Done + return undefined; + } + // With --out or --outFile all outputs go into single file + // so operations are performed directly on program, return program + var compilerOptions = state.program.getCompilerOptions(); + if (compilerOptions.outFile || compilerOptions.out) { + ts.Debug.assert(!state.semanticDiagnosticsPerFile); + return state.program; + } + // Get next batch of affected files + state.currentAffectedFilesSignatures = state.currentAffectedFilesSignatures || ts.createMap(); + if (state.exportedModulesMap) { + state.currentAffectedFilesExportedModulesMap = state.currentAffectedFilesExportedModulesMap || ts.createMap(); + } + state.affectedFiles = ts.BuilderState.getFilesAffectedBy(state, state.program, nextKey.value, cancellationToken, computeHash, state.currentAffectedFilesSignatures, state.currentAffectedFilesExportedModulesMap); + state.currentChangedFilePath = nextKey.value; + state.affectedFilesIndex = 0; + state.seenAffectedFiles = state.seenAffectedFiles || ts.createMap(); + } + } + /** + * Remove the semantic diagnostics cached from old state for affected File and the files that are referencing modules that export entities from affected file + */ + function cleanSemanticDiagnosticsOfAffectedFile(state, affectedFile) { + if (removeSemanticDiagnosticsOf(state, affectedFile.path)) { + // If there are no more diagnostics from old cache, done + return; + } + // Clean lib file diagnostics if its all files excluding default files to emit + if (state.allFilesExcludingDefaultLibraryFile === state.affectedFiles && !state.cleanedDiagnosticsOfLibFiles) { + state.cleanedDiagnosticsOfLibFiles = true; + var options_2 = state.program.getCompilerOptions(); + if (ts.forEach(state.program.getSourceFiles(), function (f) { + return state.program.isSourceFileDefaultLibrary(f) && + !ts.skipTypeChecking(f, options_2) && + removeSemanticDiagnosticsOf(state, f.path); + })) { + return; + } + } + // If there was change in signature for the changed file, + // then delete the semantic diagnostics for files that are affected by using exports of this module + if (!state.exportedModulesMap || state.affectedFiles.length === 1 || !state.changedFilesSet.has(affectedFile.path)) { + return; + } + ts.Debug.assert(!!state.currentAffectedFilesExportedModulesMap); + var seenFileAndExportsOfFile = ts.createMap(); + // Go through exported modules from cache first + // If exported modules has path, all files referencing file exported from are affected + if (ts.forEachEntry(state.currentAffectedFilesExportedModulesMap, function (exportedModules, exportedFromPath) { + return exportedModules && + exportedModules.has(affectedFile.path) && + removeSemanticDiagnosticsOfFilesReferencingPath(state, exportedFromPath, seenFileAndExportsOfFile); + })) { + return; + } + // If exported from path is not from cache and exported modules has path, all files referencing file exported from are affected + ts.forEachEntry(state.exportedModulesMap, function (exportedModules, exportedFromPath) { + return !state.currentAffectedFilesExportedModulesMap.has(exportedFromPath) && // If we already iterated this through cache, ignore it + exportedModules.has(affectedFile.path) && + removeSemanticDiagnosticsOfFilesReferencingPath(state, exportedFromPath, seenFileAndExportsOfFile); + }); + } + /** + * removes the semantic diagnostics of files referencing referencedPath and + * returns true if there are no more semantic diagnostics from old state + */ + function removeSemanticDiagnosticsOfFilesReferencingPath(state, referencedPath, seenFileAndExportsOfFile) { + return ts.forEachEntry(state.referencedMap, function (referencesInFile, filePath) { + return referencesInFile.has(referencedPath) && removeSemanticDiagnosticsOfFileAndExportsOfFile(state, filePath, seenFileAndExportsOfFile); + }); + } + /** + * Removes semantic diagnostics of file and anything that exports this file + */ + function removeSemanticDiagnosticsOfFileAndExportsOfFile(state, filePath, seenFileAndExportsOfFile) { + if (!ts.addToSeen(seenFileAndExportsOfFile, filePath)) { + return false; + } + if (removeSemanticDiagnosticsOf(state, filePath)) { + // If there are no more diagnostics from old cache, done + return true; + } + ts.Debug.assert(!!state.currentAffectedFilesExportedModulesMap); + // Go through exported modules from cache first + // If exported modules has path, all files referencing file exported from are affected + if (ts.forEachEntry(state.currentAffectedFilesExportedModulesMap, function (exportedModules, exportedFromPath) { + return exportedModules && + exportedModules.has(filePath) && + removeSemanticDiagnosticsOfFileAndExportsOfFile(state, exportedFromPath, seenFileAndExportsOfFile); + })) { + return true; + } + // If exported from path is not from cache and exported modules has path, all files referencing file exported from are affected + return !!ts.forEachEntry(state.exportedModulesMap, function (exportedModules, exportedFromPath) { + return !state.currentAffectedFilesExportedModulesMap.has(exportedFromPath) && // If we already iterated this through cache, ignore it + exportedModules.has(filePath) && + removeSemanticDiagnosticsOfFileAndExportsOfFile(state, exportedFromPath, seenFileAndExportsOfFile); + }); + } + /** + * Removes semantic diagnostics for path and + * returns true if there are no more semantic diagnostics from the old state + */ + function removeSemanticDiagnosticsOf(state, path) { + if (!state.semanticDiagnosticsFromOldState) { + return true; + } + state.semanticDiagnosticsFromOldState.delete(path); + state.semanticDiagnosticsPerFile.delete(path); + return !state.semanticDiagnosticsFromOldState.size; + } + /** + * This is called after completing operation on the next affected file. + * The operations here are postponed to ensure that cancellation during the iteration is handled correctly + */ + function doneWithAffectedFile(state, affected) { + if (affected === state.program) { + state.changedFilesSet.clear(); + } + else { + state.seenAffectedFiles.set(affected.path, true); + state.affectedFilesIndex++; + } + } + /** + * Returns the result with affected file + */ + function toAffectedFileResult(state, result, affected) { + doneWithAffectedFile(state, affected); + return { result: result, affected: affected }; + } + /** + * Gets the semantic diagnostics either from cache if present, or otherwise from program and caches it + * Note that it is assumed that the when asked about semantic diagnostics, the file has been taken out of affected files/changed file set + */ + function getSemanticDiagnosticsOfFile(state, sourceFile, cancellationToken) { + var path = sourceFile.path; + var cachedDiagnostics = state.semanticDiagnosticsPerFile.get(path); + // Report the semantic diagnostics from the cache if we already have those diagnostics present + if (cachedDiagnostics) { + return cachedDiagnostics; + } + // Diagnostics werent cached, get them from program, and cache the result + var diagnostics = state.program.getSemanticDiagnostics(sourceFile, cancellationToken); + state.semanticDiagnosticsPerFile.set(path, diagnostics); + return diagnostics; + } + var BuilderProgramKind; + (function (BuilderProgramKind) { + BuilderProgramKind[BuilderProgramKind["SemanticDiagnosticsBuilderProgram"] = 0] = "SemanticDiagnosticsBuilderProgram"; + BuilderProgramKind[BuilderProgramKind["EmitAndSemanticDiagnosticsBuilderProgram"] = 1] = "EmitAndSemanticDiagnosticsBuilderProgram"; + })(BuilderProgramKind = ts.BuilderProgramKind || (ts.BuilderProgramKind = {})); + function getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { + var host; + var newProgram; + var oldProgram; + if (newProgramOrRootNames === undefined) { + ts.Debug.assert(hostOrOptions === undefined); + host = oldProgramOrHost; + oldProgram = configFileParsingDiagnosticsOrOldProgram; + ts.Debug.assert(!!oldProgram); + newProgram = oldProgram.getProgram(); + } + else if (ts.isArray(newProgramOrRootNames)) { + oldProgram = configFileParsingDiagnosticsOrOldProgram; + newProgram = ts.createProgram({ + rootNames: newProgramOrRootNames, + options: hostOrOptions, + host: oldProgramOrHost, + oldProgram: oldProgram && oldProgram.getProgram(), + configFileParsingDiagnostics: configFileParsingDiagnostics, + projectReferences: projectReferences + }); + host = oldProgramOrHost; + } + else { + newProgram = newProgramOrRootNames; + host = hostOrOptions; + oldProgram = oldProgramOrHost; + configFileParsingDiagnostics = configFileParsingDiagnosticsOrOldProgram; + } + return { host: host, newProgram: newProgram, oldProgram: oldProgram, configFileParsingDiagnostics: configFileParsingDiagnostics || ts.emptyArray }; + } + ts.getBuilderCreationParameters = getBuilderCreationParameters; + function createBuilderProgram(kind, _a) { + var newProgram = _a.newProgram, host = _a.host, oldProgram = _a.oldProgram, configFileParsingDiagnostics = _a.configFileParsingDiagnostics; + // Return same program if underlying program doesnt change + var oldState = oldProgram && oldProgram.getState(); + if (oldState && newProgram === oldState.program && configFileParsingDiagnostics === newProgram.getConfigFileParsingDiagnostics()) { + newProgram = undefined; // TODO: GH#18217 + oldState = undefined; + return oldProgram; + } + /** + * Create the canonical file name for identity + */ + var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames()); + /** + * Computing hash to for signature verification + */ + var computeHash = host.createHash || ts.identity; + var state = createBuilderProgramState(newProgram, getCanonicalFileName, oldState); + // To ensure that we arent storing any references to old program or new program without state + newProgram = undefined; // TODO: GH#18217 + oldProgram = undefined; + oldState = undefined; + var result = { + getState: function () { return state; }, + getProgram: function () { return state.program; }, + getCompilerOptions: function () { return state.program.getCompilerOptions(); }, + getSourceFile: function (fileName) { return state.program.getSourceFile(fileName); }, + getSourceFiles: function () { return state.program.getSourceFiles(); }, + getOptionsDiagnostics: function (cancellationToken) { return state.program.getOptionsDiagnostics(cancellationToken); }, + getGlobalDiagnostics: function (cancellationToken) { return state.program.getGlobalDiagnostics(cancellationToken); }, + getConfigFileParsingDiagnostics: function () { return configFileParsingDiagnostics || state.program.getConfigFileParsingDiagnostics(); }, + getSyntacticDiagnostics: function (sourceFile, cancellationToken) { return state.program.getSyntacticDiagnostics(sourceFile, cancellationToken); }, + getSemanticDiagnostics: getSemanticDiagnostics, + emit: emit, + getAllDependencies: function (sourceFile) { return ts.BuilderState.getAllDependencies(state, state.program, sourceFile); }, + getCurrentDirectory: function () { return state.program.getCurrentDirectory(); } + }; + if (kind === BuilderProgramKind.SemanticDiagnosticsBuilderProgram) { + result.getSemanticDiagnosticsOfNextAffectedFile = getSemanticDiagnosticsOfNextAffectedFile; + } + else if (kind === BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram) { + result.emitNextAffectedFile = emitNextAffectedFile; + } + else { + ts.notImplemented(); + } + return result; + /** + * Emits the next affected file's emit result (EmitResult and sourceFiles emitted) or returns undefined if iteration is complete + * The first of writeFile if provided, writeFile of BuilderProgramHost if provided, writeFile of compiler host + * in that order would be used to write the files + */ + function emitNextAffectedFile(writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) { + var affected = getNextAffectedFile(state, cancellationToken, computeHash); + if (!affected) { + // Done + return undefined; + } + return toAffectedFileResult(state, + // When whole program is affected, do emit only once (eg when --out or --outFile is specified) + // Otherwise just affected file + state.program.emit(affected === state.program ? undefined : affected, writeFile || host.writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers), affected); + } + /** + * Emits the JavaScript and declaration files. + * When targetSource file is specified, emits the files corresponding to that source file, + * otherwise for the whole program. + * In case of EmitAndSemanticDiagnosticsBuilderProgram, when targetSourceFile is specified, + * it is assumed that that file is handled from affected file list. If targetSourceFile is not specified, + * it will only emit all the affected files instead of whole program + * + * The first of writeFile if provided, writeFile of BuilderProgramHost if provided, writeFile of compiler host + * in that order would be used to write the files + */ + function emit(targetSourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) { + if (kind === BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram) { + assertSourceFileOkWithoutNextAffectedCall(state, targetSourceFile); + if (!targetSourceFile) { + // Emit and report any errors we ran into. + var sourceMaps = []; + var emitSkipped = false; + var diagnostics = void 0; + var emittedFiles = []; + var affectedEmitResult = void 0; + while (affectedEmitResult = emitNextAffectedFile(writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers)) { + emitSkipped = emitSkipped || affectedEmitResult.result.emitSkipped; + diagnostics = ts.addRange(diagnostics, affectedEmitResult.result.diagnostics); + emittedFiles = ts.addRange(emittedFiles, affectedEmitResult.result.emittedFiles); + sourceMaps = ts.addRange(sourceMaps, affectedEmitResult.result.sourceMaps); + } + return { + emitSkipped: emitSkipped, + diagnostics: diagnostics || ts.emptyArray, + emittedFiles: emittedFiles, + sourceMaps: sourceMaps + }; + } + } + return state.program.emit(targetSourceFile, writeFile || host.writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); + } + /** + * Return the semantic diagnostics for the next affected file or undefined if iteration is complete + * If provided ignoreSourceFile would be called before getting the diagnostics and would ignore the sourceFile if the returned value was true + */ + function getSemanticDiagnosticsOfNextAffectedFile(cancellationToken, ignoreSourceFile) { + while (true) { + var affected = getNextAffectedFile(state, cancellationToken, computeHash); + if (!affected) { + // Done + return undefined; + } + else if (affected === state.program) { + // When whole program is affected, get all semantic diagnostics (eg when --out or --outFile is specified) + return toAffectedFileResult(state, state.program.getSemanticDiagnostics(/*targetSourceFile*/ undefined, cancellationToken), affected); + } + // Get diagnostics for the affected file if its not ignored + if (ignoreSourceFile && ignoreSourceFile(affected)) { + // Get next affected file + doneWithAffectedFile(state, affected); + continue; + } + return toAffectedFileResult(state, getSemanticDiagnosticsOfFile(state, affected, cancellationToken), affected); + } + } + /** + * Gets the semantic diagnostics from the program corresponding to this state of file (if provided) or whole program + * The semantic diagnostics are cached and managed here + * Note that it is assumed that when asked about semantic diagnostics through this API, + * the file has been taken out of affected files so it is safe to use cache or get from program and cache the diagnostics + * In case of SemanticDiagnosticsBuilderProgram if the source file is not provided, + * it will iterate through all the affected files, to ensure that cache stays valid and yet provide a way to get all semantic diagnostics + */ + function getSemanticDiagnostics(sourceFile, cancellationToken) { + assertSourceFileOkWithoutNextAffectedCall(state, sourceFile); + var compilerOptions = state.program.getCompilerOptions(); + if (compilerOptions.outFile || compilerOptions.out) { + ts.Debug.assert(!state.semanticDiagnosticsPerFile); + // We dont need to cache the diagnostics just return them from program + return state.program.getSemanticDiagnostics(sourceFile, cancellationToken); + } + if (sourceFile) { + return getSemanticDiagnosticsOfFile(state, sourceFile, cancellationToken); + } + if (kind === BuilderProgramKind.SemanticDiagnosticsBuilderProgram) { + // When semantic builder asks for diagnostics of the whole program, + // ensure that all the affected files are handled + var affected = void 0; + while (affected = getNextAffectedFile(state, cancellationToken, computeHash)) { + doneWithAffectedFile(state, affected); + } + } + var diagnostics; + for (var _i = 0, _a = state.program.getSourceFiles(); _i < _a.length; _i++) { + var sourceFile_2 = _a[_i]; + diagnostics = ts.addRange(diagnostics, getSemanticDiagnosticsOfFile(state, sourceFile_2, cancellationToken)); + } + return diagnostics || ts.emptyArray; + } + } + ts.createBuilderProgram = createBuilderProgram; +})(ts || (ts = {})); +(function (ts) { + function createSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { + return ts.createBuilderProgram(ts.BuilderProgramKind.SemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences)); + } + ts.createSemanticDiagnosticsBuilderProgram = createSemanticDiagnosticsBuilderProgram; + function createEmitAndSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { + return ts.createBuilderProgram(ts.BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences)); + } + ts.createEmitAndSemanticDiagnosticsBuilderProgram = createEmitAndSemanticDiagnosticsBuilderProgram; + function createAbstractBuilder(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { + var program = ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences).newProgram; + return { + // Only return program, all other methods are not implemented + getProgram: function () { return program; }, + getState: ts.notImplemented, + getCompilerOptions: ts.notImplemented, + getSourceFile: ts.notImplemented, + getSourceFiles: ts.notImplemented, + getOptionsDiagnostics: ts.notImplemented, + getGlobalDiagnostics: ts.notImplemented, + getConfigFileParsingDiagnostics: ts.notImplemented, + getSyntacticDiagnostics: ts.notImplemented, + getSemanticDiagnostics: ts.notImplemented, + emit: ts.notImplemented, + getAllDependencies: ts.notImplemented, + getCurrentDirectory: ts.notImplemented + }; + } + ts.createAbstractBuilder = createAbstractBuilder; +})(ts || (ts = {})); +/*@internal*/ +var ts; +(function (ts) { + function isPathInNodeModulesStartingWithDot(path) { + return ts.stringContains(path, "/node_modules/."); + } + ts.isPathInNodeModulesStartingWithDot = isPathInNodeModulesStartingWithDot; + ts.maxNumberOfFilesToIterateForInvalidation = 256; + function createResolutionCache(resolutionHost, rootDirForResolution, logChangesWhenResolvingModule) { + var filesWithChangedSetOfUnresolvedImports; + var filesWithInvalidatedResolutions; + var filesWithInvalidatedNonRelativeUnresolvedImports; + var allFilesHaveInvalidatedResolution = false; + var nonRelativeExternalModuleResolutions = ts.createMultiMap(); + var getCurrentDirectory = ts.memoize(function () { return resolutionHost.getCurrentDirectory(); }); // TODO: GH#18217 + var cachedDirectoryStructureHost = resolutionHost.getCachedDirectoryStructureHost(); + // The resolvedModuleNames and resolvedTypeReferenceDirectives are the cache of resolutions per file. + // The key in the map is source file's path. + // The values are Map of resolutions with key being name lookedup. + var resolvedModuleNames = ts.createMap(); + var perDirectoryResolvedModuleNames = ts.createCacheWithRedirects(); + var nonRelativeModuleNameCache = ts.createCacheWithRedirects(); + var moduleResolutionCache = ts.createModuleResolutionCacheWithMaps(perDirectoryResolvedModuleNames, nonRelativeModuleNameCache, getCurrentDirectory(), resolutionHost.getCanonicalFileName); + var resolvedTypeReferenceDirectives = ts.createMap(); + var perDirectoryResolvedTypeReferenceDirectives = ts.createCacheWithRedirects(); + /** + * These are the extensions that failed lookup files will have by default, + * any other extension of failed lookup will be store that path in custom failed lookup path + * This helps in not having to comb through all resolutions when files are added/removed + * Note that .d.ts file also has .d.ts extension hence will be part of default extensions + */ + var failedLookupDefaultExtensions = [".ts" /* Ts */, ".tsx" /* Tsx */, ".js" /* Js */, ".jsx" /* Jsx */, ".json" /* Json */]; + var customFailedLookupPaths = ts.createMap(); + var directoryWatchesOfFailedLookups = ts.createMap(); + var rootDir = rootDirForResolution && ts.removeTrailingDirectorySeparator(ts.getNormalizedAbsolutePath(rootDirForResolution, getCurrentDirectory())); + var rootPath = (rootDir && resolutionHost.toPath(rootDir)); // TODO: GH#18217 + // TypeRoot watches for the types that get added as part of getAutomaticTypeDirectiveNames + var typeRootsWatches = ts.createMap(); + return { + startRecordingFilesWithChangedResolutions: startRecordingFilesWithChangedResolutions, + finishRecordingFilesWithChangedResolutions: finishRecordingFilesWithChangedResolutions, + // perDirectoryResolvedModuleNames and perDirectoryResolvedTypeReferenceDirectives could be non empty if there was exception during program update + // (between startCachingPerDirectoryResolution and finishCachingPerDirectoryResolution) + startCachingPerDirectoryResolution: clearPerDirectoryResolutions, + finishCachingPerDirectoryResolution: finishCachingPerDirectoryResolution, + resolveModuleNames: resolveModuleNames, + getResolvedModuleWithFailedLookupLocationsFromCache: getResolvedModuleWithFailedLookupLocationsFromCache, + resolveTypeReferenceDirectives: resolveTypeReferenceDirectives, + removeResolutionsFromProjectReferenceRedirects: removeResolutionsFromProjectReferenceRedirects, + removeResolutionsOfFile: removeResolutionsOfFile, + invalidateResolutionOfFile: invalidateResolutionOfFile, + setFilesWithInvalidatedNonRelativeUnresolvedImports: setFilesWithInvalidatedNonRelativeUnresolvedImports, + createHasInvalidatedResolution: createHasInvalidatedResolution, + updateTypeRootsWatch: updateTypeRootsWatch, + closeTypeRootsWatch: closeTypeRootsWatch, + clear: clear + }; + function getResolvedModule(resolution) { + return resolution.resolvedModule; + } + function getResolvedTypeReferenceDirective(resolution) { + return resolution.resolvedTypeReferenceDirective; + } + function isInDirectoryPath(dir, file) { + if (dir === undefined || file.length <= dir.length) { + return false; + } + return ts.startsWith(file, dir) && file[dir.length] === ts.directorySeparator; + } + function clear() { + ts.clearMap(directoryWatchesOfFailedLookups, ts.closeFileWatcherOf); + customFailedLookupPaths.clear(); + nonRelativeExternalModuleResolutions.clear(); + closeTypeRootsWatch(); + resolvedModuleNames.clear(); + resolvedTypeReferenceDirectives.clear(); + allFilesHaveInvalidatedResolution = false; + // perDirectoryResolvedModuleNames and perDirectoryResolvedTypeReferenceDirectives could be non empty if there was exception during program update + // (between startCachingPerDirectoryResolution and finishCachingPerDirectoryResolution) + clearPerDirectoryResolutions(); + } + function startRecordingFilesWithChangedResolutions() { + filesWithChangedSetOfUnresolvedImports = []; + } + function finishRecordingFilesWithChangedResolutions() { + var collected = filesWithChangedSetOfUnresolvedImports; + filesWithChangedSetOfUnresolvedImports = undefined; + return collected; + } + function isFileWithInvalidatedNonRelativeUnresolvedImports(path) { + if (!filesWithInvalidatedNonRelativeUnresolvedImports) { + return false; + } + // Invalidated if file has unresolved imports + var value = filesWithInvalidatedNonRelativeUnresolvedImports.get(path); + return !!value && !!value.length; + } + function createHasInvalidatedResolution(forceAllFilesAsInvalidated) { + if (allFilesHaveInvalidatedResolution || forceAllFilesAsInvalidated) { + // Any file asked would have invalidated resolution + filesWithInvalidatedResolutions = undefined; + return ts.returnTrue; + } + var collected = filesWithInvalidatedResolutions; + filesWithInvalidatedResolutions = undefined; + return function (path) { return (!!collected && collected.has(path)) || + isFileWithInvalidatedNonRelativeUnresolvedImports(path); }; + } + function clearPerDirectoryResolutions() { + perDirectoryResolvedModuleNames.clear(); + nonRelativeModuleNameCache.clear(); + perDirectoryResolvedTypeReferenceDirectives.clear(); + nonRelativeExternalModuleResolutions.forEach(watchFailedLookupLocationOfNonRelativeModuleResolutions); + nonRelativeExternalModuleResolutions.clear(); + } + function finishCachingPerDirectoryResolution() { + allFilesHaveInvalidatedResolution = false; + filesWithInvalidatedNonRelativeUnresolvedImports = undefined; + clearPerDirectoryResolutions(); + directoryWatchesOfFailedLookups.forEach(function (watcher, path) { + if (watcher.refCount === 0) { + directoryWatchesOfFailedLookups.delete(path); + watcher.watcher.close(); + } + }); + } + function resolveModuleName(moduleName, containingFile, compilerOptions, host, redirectedReference) { + var primaryResult = ts.resolveModuleName(moduleName, containingFile, compilerOptions, host, moduleResolutionCache, redirectedReference); + // return result immediately only if global cache support is not enabled or if it is .ts, .tsx or .d.ts + if (!resolutionHost.getGlobalCache) { + return primaryResult; + } + // otherwise try to load typings from @types + var globalCache = resolutionHost.getGlobalCache(); + if (globalCache !== undefined && !ts.isExternalModuleNameRelative(moduleName) && !(primaryResult.resolvedModule && ts.extensionIsTS(primaryResult.resolvedModule.extension))) { + // create different collection of failed lookup locations for second pass + // if it will fail and we've already found something during the first pass - we don't want to pollute its results + var _a = ts.loadModuleFromGlobalCache(moduleName, resolutionHost.projectName, compilerOptions, host, globalCache), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; + if (resolvedModule) { + return { resolvedModule: resolvedModule, failedLookupLocations: ts.addRange(primaryResult.failedLookupLocations, failedLookupLocations) }; + } + } + // Default return the result from the first pass + return primaryResult; + } + function resolveNamesWithLocalCache(names, containingFile, redirectedReference, cache, perDirectoryCacheWithRedirects, loader, getResolutionWithResolvedFileName, shouldRetryResolution, reusedNames, logChanges) { + var path = resolutionHost.toPath(containingFile); + var resolutionsInFile = cache.get(path) || cache.set(path, ts.createMap()).get(path); + var dirPath = ts.getDirectoryPath(path); + var perDirectoryCache = perDirectoryCacheWithRedirects.getOrCreateMapOfCacheRedirects(redirectedReference); + var perDirectoryResolution = perDirectoryCache.get(dirPath); + if (!perDirectoryResolution) { + perDirectoryResolution = ts.createMap(); + perDirectoryCache.set(dirPath, perDirectoryResolution); + } + var resolvedModules = []; + var compilerOptions = resolutionHost.getCompilationSettings(); + var hasInvalidatedNonRelativeUnresolvedImport = logChanges && isFileWithInvalidatedNonRelativeUnresolvedImports(path); + // All the resolutions in this file are invalidated if this file wasnt resolved using same redirect + var program = resolutionHost.getCurrentProgram(); + var oldRedirect = program && program.getResolvedProjectReferenceToRedirect(containingFile); + var unmatchedRedirects = oldRedirect ? + !redirectedReference || redirectedReference.sourceFile.path !== oldRedirect.sourceFile.path : + !!redirectedReference; + var seenNamesInFile = ts.createMap(); + for (var _i = 0, names_2 = names; _i < names_2.length; _i++) { + var name = names_2[_i]; + var resolution = resolutionsInFile.get(name); + // Resolution is valid if it is present and not invalidated + if (!seenNamesInFile.has(name) && + allFilesHaveInvalidatedResolution || unmatchedRedirects || !resolution || resolution.isInvalidated || + // If the name is unresolved import that was invalidated, recalculate + (hasInvalidatedNonRelativeUnresolvedImport && !ts.isExternalModuleNameRelative(name) && shouldRetryResolution(resolution))) { + var existingResolution = resolution; + var resolutionInDirectory = perDirectoryResolution.get(name); + if (resolutionInDirectory) { + resolution = resolutionInDirectory; + } + else { + resolution = loader(name, containingFile, compilerOptions, resolutionHost, redirectedReference); + perDirectoryResolution.set(name, resolution); + } + resolutionsInFile.set(name, resolution); + watchFailedLookupLocationsOfExternalModuleResolutions(name, resolution); + if (existingResolution) { + stopWatchFailedLookupLocationOfResolution(existingResolution); + } + if (logChanges && filesWithChangedSetOfUnresolvedImports && !resolutionIsEqualTo(existingResolution, resolution)) { + filesWithChangedSetOfUnresolvedImports.push(path); + // reset log changes to avoid recording the same file multiple times + logChanges = false; + } + } + ts.Debug.assert(resolution !== undefined && !resolution.isInvalidated); + seenNamesInFile.set(name, true); + resolvedModules.push(getResolutionWithResolvedFileName(resolution)); + } + // Stop watching and remove the unused name + resolutionsInFile.forEach(function (resolution, name) { + if (!seenNamesInFile.has(name) && !ts.contains(reusedNames, name)) { + stopWatchFailedLookupLocationOfResolution(resolution); + resolutionsInFile.delete(name); + } + }); + return resolvedModules; + function resolutionIsEqualTo(oldResolution, newResolution) { + if (oldResolution === newResolution) { + return true; + } + if (!oldResolution || !newResolution) { + return false; + } + var oldResult = getResolutionWithResolvedFileName(oldResolution); + var newResult = getResolutionWithResolvedFileName(newResolution); + if (oldResult === newResult) { + return true; + } + if (!oldResult || !newResult) { + return false; + } + return oldResult.resolvedFileName === newResult.resolvedFileName; + } + } + function resolveTypeReferenceDirectives(typeDirectiveNames, containingFile, redirectedReference) { + return resolveNamesWithLocalCache(typeDirectiveNames, containingFile, redirectedReference, resolvedTypeReferenceDirectives, perDirectoryResolvedTypeReferenceDirectives, ts.resolveTypeReferenceDirective, getResolvedTypeReferenceDirective, + /*shouldRetryResolution*/ function (resolution) { return resolution.resolvedTypeReferenceDirective === undefined; }, + /*reusedNames*/ undefined, /*logChanges*/ false); + } + function resolveModuleNames(moduleNames, containingFile, reusedNames, redirectedReference) { + return resolveNamesWithLocalCache(moduleNames, containingFile, redirectedReference, resolvedModuleNames, perDirectoryResolvedModuleNames, resolveModuleName, getResolvedModule, + /*shouldRetryResolution*/ function (resolution) { return !resolution.resolvedModule || !ts.resolutionExtensionIsTSOrJson(resolution.resolvedModule.extension); }, reusedNames, logChangesWhenResolvingModule); + } + function getResolvedModuleWithFailedLookupLocationsFromCache(moduleName, containingFile) { + var cache = resolvedModuleNames.get(resolutionHost.toPath(containingFile)); + return cache && cache.get(moduleName); + } + function isNodeModulesDirectory(dirPath) { + return ts.endsWith(dirPath, "/node_modules"); + } + function isNodeModulesAtTypesDirectory(dirPath) { + return ts.endsWith(dirPath, "/node_modules/@types"); + } + /** + * Filter out paths like + * "/", "/user", "/user/username", "/user/username/folderAtRoot", + * "c:/", "c:/users", "c:/users/username", "c:/users/username/folderAtRoot", "c:/folderAtRoot" + * @param dirPath + */ + function canWatchDirectory(dirPath) { + var rootLength = ts.getRootLength(dirPath); + if (dirPath.length === rootLength) { + // Ignore "/", "c:/" + return false; + } + var nextDirectorySeparator = dirPath.indexOf(ts.directorySeparator, rootLength); + if (nextDirectorySeparator === -1) { + // ignore "/user", "c:/users" or "c:/folderAtRoot" + return false; + } + if (dirPath.charCodeAt(0) !== 47 /* slash */ && + dirPath.substr(rootLength, nextDirectorySeparator).search(/users/i) === -1) { + // Paths like c:/folderAtRoot/subFolder are allowed + return true; + } + for (var searchIndex = nextDirectorySeparator + 1, searchLevels = 2; searchLevels > 0; searchLevels--) { + searchIndex = dirPath.indexOf(ts.directorySeparator, searchIndex) + 1; + if (searchIndex === 0) { + // Folder isnt at expected minimun levels + return false; + } + } + return true; + } + function getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath) { + if (isInDirectoryPath(rootPath, failedLookupLocationPath)) { + // Ensure failed look up is normalized path + failedLookupLocation = ts.isRootedDiskPath(failedLookupLocation) ? ts.normalizePath(failedLookupLocation) : ts.getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory()); + ts.Debug.assert(failedLookupLocation.length === failedLookupLocationPath.length, "FailedLookup: " + failedLookupLocation + " failedLookupLocationPath: " + failedLookupLocationPath); // tslint:disable-line + var subDirectoryInRoot = failedLookupLocationPath.indexOf(ts.directorySeparator, rootPath.length + 1); + if (subDirectoryInRoot !== -1) { + // Instead of watching root, watch directory in root to avoid watching excluded directories not needed for module resolution + return { dir: failedLookupLocation.substr(0, subDirectoryInRoot), dirPath: failedLookupLocationPath.substr(0, subDirectoryInRoot) }; + } + else { + // Always watch root directory non recursively + return { dir: rootDir, dirPath: rootPath, nonRecursive: false }; // TODO: GH#18217 + } + } + return getDirectoryToWatchFromFailedLookupLocationDirectory(ts.getDirectoryPath(ts.getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory())), ts.getDirectoryPath(failedLookupLocationPath)); + } + function getDirectoryToWatchFromFailedLookupLocationDirectory(dir, dirPath) { + // If directory path contains node module, get the most parent node_modules directory for watching + while (ts.pathContainsNodeModules(dirPath)) { + dir = ts.getDirectoryPath(dir); + dirPath = ts.getDirectoryPath(dirPath); + } + // If the directory is node_modules use it to watch, always watch it recursively + if (isNodeModulesDirectory(dirPath)) { + return canWatchDirectory(ts.getDirectoryPath(dirPath)) ? { dir: dir, dirPath: dirPath } : undefined; + } + var nonRecursive = true; + // Use some ancestor of the root directory + var subDirectoryPath, subDirectory; + if (rootPath !== undefined) { + while (!isInDirectoryPath(dirPath, rootPath)) { + var parentPath = ts.getDirectoryPath(dirPath); + if (parentPath === dirPath) { + break; + } + nonRecursive = false; + subDirectoryPath = dirPath; + subDirectory = dir; + dirPath = parentPath; + dir = ts.getDirectoryPath(dir); + } + } + return canWatchDirectory(dirPath) ? { dir: subDirectory || dir, dirPath: subDirectoryPath || dirPath, nonRecursive: nonRecursive } : undefined; + } + function isPathWithDefaultFailedLookupExtension(path) { + return ts.fileExtensionIsOneOf(path, failedLookupDefaultExtensions); + } + function watchFailedLookupLocationsOfExternalModuleResolutions(name, resolution) { + // No need to set the resolution refCount + if (resolution.failedLookupLocations && resolution.failedLookupLocations.length) { + if (resolution.refCount) { + resolution.refCount++; + } + else { + resolution.refCount = 1; + if (ts.isExternalModuleNameRelative(name)) { + watchFailedLookupLocationOfResolution(resolution); + } + else { + nonRelativeExternalModuleResolutions.add(name, resolution); + } + } + } + } + function watchFailedLookupLocationOfResolution(resolution) { + ts.Debug.assert(!!resolution.refCount); + var failedLookupLocations = resolution.failedLookupLocations; + var setAtRoot = false; + for (var _i = 0, failedLookupLocations_1 = failedLookupLocations; _i < failedLookupLocations_1.length; _i++) { + var failedLookupLocation = failedLookupLocations_1[_i]; + var failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation); + var toWatch = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath); + if (toWatch) { + var dir = toWatch.dir, dirPath = toWatch.dirPath, nonRecursive = toWatch.nonRecursive; + // If the failed lookup location path is not one of the supported extensions, + // store it in the custom path + if (!isPathWithDefaultFailedLookupExtension(failedLookupLocationPath)) { + var refCount = customFailedLookupPaths.get(failedLookupLocationPath) || 0; + customFailedLookupPaths.set(failedLookupLocationPath, refCount + 1); + } + if (dirPath === rootPath) { + ts.Debug.assert(!nonRecursive); + setAtRoot = true; + } + else { + setDirectoryWatcher(dir, dirPath, nonRecursive); + } + } + } + if (setAtRoot) { + // This is always non recursive + setDirectoryWatcher(rootDir, rootPath, /*nonRecursive*/ true); // TODO: GH#18217 + } + } + function setRefCountToUndefined(resolution) { + resolution.refCount = undefined; + } + function watchFailedLookupLocationOfNonRelativeModuleResolutions(resolutions, name) { + var program = resolutionHost.getCurrentProgram(); + var updateResolution = program && program.getTypeChecker().tryFindAmbientModuleWithoutAugmentations(name) ? + setRefCountToUndefined : watchFailedLookupLocationOfResolution; + resolutions.forEach(updateResolution); + } + function setDirectoryWatcher(dir, dirPath, nonRecursive) { + var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath); + if (dirWatcher) { + ts.Debug.assert(!!nonRecursive === !!dirWatcher.nonRecursive); + dirWatcher.refCount++; + } + else { + directoryWatchesOfFailedLookups.set(dirPath, { watcher: createDirectoryWatcher(dir, dirPath, nonRecursive), refCount: 1, nonRecursive: nonRecursive }); + } + } + function stopWatchFailedLookupLocationOfResolution(resolution) { + if (!resolution.refCount) { + return; + } + resolution.refCount--; + if (resolution.refCount) { + return; + } + var failedLookupLocations = resolution.failedLookupLocations; + var removeAtRoot = false; + for (var _i = 0, failedLookupLocations_2 = failedLookupLocations; _i < failedLookupLocations_2.length; _i++) { + var failedLookupLocation = failedLookupLocations_2[_i]; + var failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation); + var toWatch = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath); + if (toWatch) { + var dirPath = toWatch.dirPath; + var refCount = customFailedLookupPaths.get(failedLookupLocationPath); + if (refCount) { + if (refCount === 1) { + customFailedLookupPaths.delete(failedLookupLocationPath); + } + else { + ts.Debug.assert(refCount > 1); + customFailedLookupPaths.set(failedLookupLocationPath, refCount - 1); + } + } + if (dirPath === rootPath) { + removeAtRoot = true; + } + else { + removeDirectoryWatcher(dirPath); + } + } + } + if (removeAtRoot) { + removeDirectoryWatcher(rootPath); + } + } + function removeDirectoryWatcher(dirPath) { + var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath); + // Do not close the watcher yet since it might be needed by other failed lookup locations. + dirWatcher.refCount--; + } + function createDirectoryWatcher(directory, dirPath, nonRecursive) { + return resolutionHost.watchDirectoryOfFailedLookupLocation(directory, function (fileOrDirectory) { + var fileOrDirectoryPath = resolutionHost.toPath(fileOrDirectory); + if (cachedDirectoryStructureHost) { + // Since the file existence changed, update the sourceFiles cache + cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); + } + if (!allFilesHaveInvalidatedResolution && invalidateResolutionOfFailedLookupLocation(fileOrDirectoryPath, dirPath === fileOrDirectoryPath)) { + resolutionHost.onInvalidatedResolution(); + } + }, nonRecursive ? 0 /* None */ : 1 /* Recursive */); + } + function removeResolutionsOfFileFromCache(cache, filePath) { + // Deleted file, stop watching failed lookups for all the resolutions in the file + var resolutions = cache.get(filePath); + if (resolutions) { + resolutions.forEach(stopWatchFailedLookupLocationOfResolution); + cache.delete(filePath); + } + } + function removeResolutionsFromProjectReferenceRedirects(filePath) { + if (!ts.fileExtensionIs(filePath, ".json" /* Json */)) { + return; + } + var program = resolutionHost.getCurrentProgram(); + if (!program) { + return; + } + // If this file is input file for the referenced project, get it + var resolvedProjectReference = program.getResolvedProjectReferenceByPath(filePath); + if (!resolvedProjectReference) { + return; + } + // filePath is for the projectReference and the containing file is from this project reference, invalidate the resolution + resolvedProjectReference.commandLine.fileNames.forEach(function (f) { return removeResolutionsOfFile(resolutionHost.toPath(f)); }); + } + function removeResolutionsOfFile(filePath) { + removeResolutionsOfFileFromCache(resolvedModuleNames, filePath); + removeResolutionsOfFileFromCache(resolvedTypeReferenceDirectives, filePath); + } + function invalidateResolutionCache(cache, isInvalidatedResolution, getResolutionWithResolvedFileName) { + var seen = ts.createMap(); + cache.forEach(function (resolutions, containingFilePath) { + var dirPath = ts.getDirectoryPath(containingFilePath); + var seenInDir = seen.get(dirPath); + if (!seenInDir) { + seenInDir = ts.createMap(); + seen.set(dirPath, seenInDir); + } + resolutions.forEach(function (resolution, name) { + if (seenInDir.has(name)) { + return; + } + seenInDir.set(name, true); + if (!resolution.isInvalidated && isInvalidatedResolution(resolution, getResolutionWithResolvedFileName)) { + // Mark the file as needing re-evaluation of module resolution instead of using it blindly. + resolution.isInvalidated = true; + (filesWithInvalidatedResolutions || (filesWithInvalidatedResolutions = ts.createMap())).set(containingFilePath, true); + } + }); + }); + } + function hasReachedResolutionIterationLimit() { + var maxSize = resolutionHost.maxNumberOfFilesToIterateForInvalidation || ts.maxNumberOfFilesToIterateForInvalidation; + return resolvedModuleNames.size > maxSize || resolvedTypeReferenceDirectives.size > maxSize; + } + function invalidateResolutions(isInvalidatedResolution) { + // If more than maxNumberOfFilesToIterateForInvalidation present, + // just invalidated all files and recalculate the resolutions for files instead + if (hasReachedResolutionIterationLimit()) { + allFilesHaveInvalidatedResolution = true; + return; + } + invalidateResolutionCache(resolvedModuleNames, isInvalidatedResolution, getResolvedModule); + invalidateResolutionCache(resolvedTypeReferenceDirectives, isInvalidatedResolution, getResolvedTypeReferenceDirective); + } + function invalidateResolutionOfFile(filePath) { + removeResolutionsOfFile(filePath); + invalidateResolutions( + // Resolution is invalidated if the resulting file name is same as the deleted file path + function (resolution, getResolutionWithResolvedFileName) { + var result = getResolutionWithResolvedFileName(resolution); + return !!result && resolutionHost.toPath(result.resolvedFileName) === filePath; // TODO: GH#18217 + }); + } + function setFilesWithInvalidatedNonRelativeUnresolvedImports(filesMap) { + ts.Debug.assert(filesWithInvalidatedNonRelativeUnresolvedImports === filesMap || filesWithInvalidatedNonRelativeUnresolvedImports === undefined); + filesWithInvalidatedNonRelativeUnresolvedImports = filesMap; + } + function invalidateResolutionOfFailedLookupLocation(fileOrDirectoryPath, isCreatingWatchedDirectory) { + var isChangedFailedLookupLocation; + if (isCreatingWatchedDirectory) { + // Watching directory is created + // Invalidate any resolution has failed lookup in this directory + isChangedFailedLookupLocation = function (location) { return isInDirectoryPath(fileOrDirectoryPath, resolutionHost.toPath(location)); }; + } + else { + // If something to do with folder/file starting with "." in node_modules folder, skip it + if (isPathInNodeModulesStartingWithDot(fileOrDirectoryPath)) + return false; + // Some file or directory in the watching directory is created + // Return early if it does not have any of the watching extension or not the custom failed lookup path + var dirOfFileOrDirectory = ts.getDirectoryPath(fileOrDirectoryPath); + if (isNodeModulesAtTypesDirectory(fileOrDirectoryPath) || isNodeModulesDirectory(fileOrDirectoryPath) || + isNodeModulesAtTypesDirectory(dirOfFileOrDirectory) || isNodeModulesDirectory(dirOfFileOrDirectory)) { + // Invalidate any resolution from this directory + isChangedFailedLookupLocation = function (location) { + var locationPath = resolutionHost.toPath(location); + return locationPath === fileOrDirectoryPath || ts.startsWith(resolutionHost.toPath(location), fileOrDirectoryPath); + }; + } + else { + if (!isPathWithDefaultFailedLookupExtension(fileOrDirectoryPath) && !customFailedLookupPaths.has(fileOrDirectoryPath)) { + return false; + } + // Ignore emits from the program + if (ts.isEmittedFileOfProgram(resolutionHost.getCurrentProgram(), fileOrDirectoryPath)) { + return false; + } + // Resolution need to be invalidated if failed lookup location is same as the file or directory getting created + isChangedFailedLookupLocation = function (location) { return resolutionHost.toPath(location) === fileOrDirectoryPath; }; + } + } + var hasChangedFailedLookupLocation = function (resolution) { return ts.some(resolution.failedLookupLocations, isChangedFailedLookupLocation); }; + var invalidatedFilesCount = filesWithInvalidatedResolutions && filesWithInvalidatedResolutions.size; + invalidateResolutions( + // Resolution is invalidated if the resulting file name is same as the deleted file path + hasChangedFailedLookupLocation); + return allFilesHaveInvalidatedResolution || filesWithInvalidatedResolutions && filesWithInvalidatedResolutions.size !== invalidatedFilesCount; + } + function closeTypeRootsWatch() { + ts.clearMap(typeRootsWatches, ts.closeFileWatcher); + } + function getDirectoryToWatchFailedLookupLocationFromTypeRoot(typeRoot, typeRootPath) { + if (allFilesHaveInvalidatedResolution) { + return undefined; + } + if (isInDirectoryPath(rootPath, typeRootPath)) { + return rootPath; + } + var toWatch = getDirectoryToWatchFromFailedLookupLocationDirectory(typeRoot, typeRootPath); + return toWatch && directoryWatchesOfFailedLookups.has(toWatch.dirPath) ? toWatch.dirPath : undefined; + } + function createTypeRootsWatch(typeRootPath, typeRoot) { + // Create new watch and recursive info + return resolutionHost.watchTypeRootsDirectory(typeRoot, function (fileOrDirectory) { + var fileOrDirectoryPath = resolutionHost.toPath(fileOrDirectory); + if (cachedDirectoryStructureHost) { + // Since the file existence changed, update the sourceFiles cache + cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); + } + // For now just recompile + // We could potentially store more data here about whether it was/would be really be used or not + // and with that determine to trigger compilation but for now this is enough + resolutionHost.onChangedAutomaticTypeDirectiveNames(); + // Since directory watchers invoked are flaky, the failed lookup location events might not be triggered + // So handle to failed lookup locations here as well to ensure we are invalidating resolutions + var dirPath = getDirectoryToWatchFailedLookupLocationFromTypeRoot(typeRoot, typeRootPath); + if (dirPath && invalidateResolutionOfFailedLookupLocation(fileOrDirectoryPath, dirPath === fileOrDirectoryPath)) { + resolutionHost.onInvalidatedResolution(); + } + }, 1 /* Recursive */); + } + /** + * Watches the types that would get added as part of getAutomaticTypeDirectiveNames + * To be called when compiler options change + */ + function updateTypeRootsWatch() { + var options = resolutionHost.getCompilationSettings(); + if (options.types) { + // No need to do any watch since resolution cache is going to handle the failed lookups + // for the types added by this + closeTypeRootsWatch(); + return; + } + // we need to assume the directories exist to ensure that we can get all the type root directories that get included + // But filter directories that are at root level to say directory doesnt exist, so that we arent watching them + var typeRoots = ts.getEffectiveTypeRoots(options, { directoryExists: directoryExistsForTypeRootWatch, getCurrentDirectory: getCurrentDirectory }); + if (typeRoots) { + ts.mutateMap(typeRootsWatches, ts.arrayToMap(typeRoots, function (tr) { return resolutionHost.toPath(tr); }), { + createNewValue: createTypeRootsWatch, + onDeleteValue: ts.closeFileWatcher + }); + } + else { + closeTypeRootsWatch(); + } + } + /** + * Use this function to return if directory exists to get type roots to watch + * If we return directory exists then only the paths will be added to type roots + * Hence return true for all directories except root directories which are filtered from watching + */ + function directoryExistsForTypeRootWatch(nodeTypesDirectory) { + var dir = ts.getDirectoryPath(ts.getDirectoryPath(nodeTypesDirectory)); + var dirPath = resolutionHost.toPath(dir); + return dirPath === rootPath || canWatchDirectory(dirPath); + } + } + ts.createResolutionCache = createResolutionCache; +})(ts || (ts = {})); +// Used by importFixes, getEditsForFileRename, and declaration emit to synthesize import module specifiers. +/* @internal */ +var ts; +(function (ts) { + var moduleSpecifiers; + (function (moduleSpecifiers) { + var RelativePreference; + (function (RelativePreference) { + RelativePreference[RelativePreference["Relative"] = 0] = "Relative"; + RelativePreference[RelativePreference["NonRelative"] = 1] = "NonRelative"; + RelativePreference[RelativePreference["Auto"] = 2] = "Auto"; + })(RelativePreference || (RelativePreference = {})); + // See UserPreferences#importPathEnding + var Ending; + (function (Ending) { + Ending[Ending["Minimal"] = 0] = "Minimal"; + Ending[Ending["Index"] = 1] = "Index"; + Ending[Ending["JsExtension"] = 2] = "JsExtension"; + })(Ending || (Ending = {})); + function getPreferences(_a, compilerOptions, importingSourceFile) { + var importModuleSpecifierPreference = _a.importModuleSpecifierPreference, importModuleSpecifierEnding = _a.importModuleSpecifierEnding; + return { + relativePreference: importModuleSpecifierPreference === "relative" ? 0 /* Relative */ : importModuleSpecifierPreference === "non-relative" ? 1 /* NonRelative */ : 2 /* Auto */, + ending: getEnding(), + }; + function getEnding() { + switch (importModuleSpecifierEnding) { + case "minimal": return 0 /* Minimal */; + case "index": return 1 /* Index */; + case "js": return 2 /* JsExtension */; + default: return usesJsExtensionOnImports(importingSourceFile) ? 2 /* JsExtension */ + : ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.NodeJs ? 1 /* Index */ : 0 /* Minimal */; + } + } + } + function getPreferencesForUpdate(compilerOptions, oldImportSpecifier) { + return { + relativePreference: ts.isExternalModuleNameRelative(oldImportSpecifier) ? 0 /* Relative */ : 1 /* NonRelative */, + ending: ts.hasJSOrJsonFileExtension(oldImportSpecifier) ? 2 /* JsExtension */ + : ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.NodeJs || ts.endsWith(oldImportSpecifier, "index") ? 1 /* Index */ : 0 /* Minimal */, + }; + } + function updateModuleSpecifier(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, oldImportSpecifier) { + var res = getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, getPreferencesForUpdate(compilerOptions, oldImportSpecifier)); + if (res === oldImportSpecifier) + return undefined; + return res; + } + moduleSpecifiers.updateModuleSpecifier = updateModuleSpecifier; + // Note: importingSourceFile is just for usesJsExtensionOnImports + function getModuleSpecifier(compilerOptions, importingSourceFile, importingSourceFileName, toFileName, host, files, preferences, redirectTargetsMap) { + if (preferences === void 0) { preferences = {}; } + return getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, getPreferences(preferences, compilerOptions, importingSourceFile)); + } + moduleSpecifiers.getModuleSpecifier = getModuleSpecifier; + function getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, preferences) { + var info = getInfo(importingSourceFileName, host); + var modulePaths = getAllModulePaths(files, importingSourceFileName, toFileName, info.getCanonicalFileName, host, redirectTargetsMap); + return ts.firstDefined(modulePaths, function (moduleFileName) { return tryGetModuleNameAsNodeModule(moduleFileName, info, host, compilerOptions); }) || + getLocalModuleSpecifier(toFileName, info, compilerOptions, preferences); + } + // Returns an import for each symlink and for the realpath. + function getModuleSpecifiers(moduleSymbol, compilerOptions, importingSourceFile, host, files, userPreferences, redirectTargetsMap) { + var ambient = tryGetModuleNameFromAmbientModule(moduleSymbol); + if (ambient) + return [ambient]; + var info = getInfo(importingSourceFile.path, host); + var moduleSourceFile = ts.getSourceFileOfNode(moduleSymbol.valueDeclaration || ts.getNonAugmentationDeclaration(moduleSymbol)); + var modulePaths = getAllModulePaths(files, importingSourceFile.path, moduleSourceFile.fileName, info.getCanonicalFileName, host, redirectTargetsMap); + var preferences = getPreferences(userPreferences, compilerOptions, importingSourceFile); + var global = ts.mapDefined(modulePaths, function (moduleFileName) { return tryGetModuleNameAsNodeModule(moduleFileName, info, host, compilerOptions); }); + return global.length ? global : modulePaths.map(function (moduleFileName) { return getLocalModuleSpecifier(moduleFileName, info, compilerOptions, preferences); }); + } + moduleSpecifiers.getModuleSpecifiers = getModuleSpecifiers; + // importingSourceFileName is separate because getEditsForFileRename may need to specify an updated path + function getInfo(importingSourceFileName, host) { + var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames ? host.useCaseSensitiveFileNames() : true); + var sourceDirectory = ts.getDirectoryPath(importingSourceFileName); + return { getCanonicalFileName: getCanonicalFileName, sourceDirectory: sourceDirectory }; + } + function getLocalModuleSpecifier(moduleFileName, _a, compilerOptions, _b) { + var getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory; + var ending = _b.ending, relativePreference = _b.relativePreference; + var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths, rootDirs = compilerOptions.rootDirs; + var relativePath = rootDirs && tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName) || + removeExtensionAndIndexPostFix(ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, moduleFileName, getCanonicalFileName)), ending, compilerOptions); + if (!baseUrl || relativePreference === 0 /* Relative */) { + return relativePath; + } + var relativeToBaseUrl = getRelativePathIfInDirectory(moduleFileName, baseUrl, getCanonicalFileName); + if (!relativeToBaseUrl) { + return relativePath; + } + var importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, ending, compilerOptions); + var fromPaths = paths && tryGetModuleNameFromPaths(ts.removeFileExtension(relativeToBaseUrl), importRelativeToBaseUrl, paths); + var nonRelative = fromPaths === undefined ? importRelativeToBaseUrl : fromPaths; + if (relativePreference === 1 /* NonRelative */) { + return nonRelative; + } + if (relativePreference !== 2 /* Auto */) + ts.Debug.assertNever(relativePreference); + // Prefer a relative import over a baseUrl import if it has fewer components. + return isPathRelativeToParent(nonRelative) || countPathComponents(relativePath) < countPathComponents(nonRelative) ? relativePath : nonRelative; + } + function countPathComponents(path) { + var count = 0; + for (var i = ts.startsWith(path, "./") ? 2 : 0; i < path.length; i++) { + if (path.charCodeAt(i) === 47 /* slash */) + count++; + } + return count; + } + moduleSpecifiers.countPathComponents = countPathComponents; + function usesJsExtensionOnImports(_a) { + var imports = _a.imports; + return ts.firstDefined(imports, function (_a) { + var text = _a.text; + return ts.pathIsRelative(text) ? ts.hasJSOrJsonFileExtension(text) : undefined; + }) || false; + } + function stringsEqual(a, b, getCanonicalFileName) { + return getCanonicalFileName(a) === getCanonicalFileName(b); + } + // KLUDGE: Don't assume one 'node_modules' links to another. More likely a single directory inside the node_modules is the symlink. + // ALso, don't assume that an `@foo` directory is linked. More likely the contents of that are linked. + function isNodeModulesOrScopedPackageDirectory(s, getCanonicalFileName) { + return getCanonicalFileName(s) === "node_modules" || ts.startsWith(s, "@"); + } + function guessDirectorySymlink(a, b, cwd, getCanonicalFileName) { + var aParts = ts.getPathComponents(ts.toPath(a, cwd, getCanonicalFileName)); + var bParts = ts.getPathComponents(ts.toPath(b, cwd, getCanonicalFileName)); + while (!isNodeModulesOrScopedPackageDirectory(aParts[aParts.length - 2], getCanonicalFileName) && + !isNodeModulesOrScopedPackageDirectory(bParts[bParts.length - 2], getCanonicalFileName) && + stringsEqual(aParts[aParts.length - 1], bParts[bParts.length - 1], getCanonicalFileName)) { + aParts.pop(); + bParts.pop(); + } + return [ts.getPathFromPathComponents(aParts), ts.getPathFromPathComponents(bParts)]; + } + function discoverProbableSymlinks(files, getCanonicalFileName, cwd) { + var result = ts.createMap(); + var symlinks = ts.mapDefined(files, function (sf) { + return sf.resolvedModules && ts.firstDefinedIterator(sf.resolvedModules.values(), function (res) { + return res && res.originalPath && res.resolvedFileName !== res.originalPath ? [res.resolvedFileName, res.originalPath] : undefined; + }); + }); + for (var _i = 0, symlinks_1 = symlinks; _i < symlinks_1.length; _i++) { + var _a = symlinks_1[_i], resolvedPath = _a[0], originalPath = _a[1]; + var _b = guessDirectorySymlink(resolvedPath, originalPath, cwd, getCanonicalFileName), commonResolved = _b[0], commonOriginal = _b[1]; + result.set(commonOriginal, commonResolved); + } + return result; + } + /** + * Looks for existing imports that use symlinks to this module. + * Symlinks will be returned first so they are preferred over the real path. + */ + function getAllModulePaths(files, importingFileName, importedFileName, getCanonicalFileName, host, redirectTargetsMap) { + var redirects = redirectTargetsMap.get(importedFileName); + var importedFileNames = redirects ? redirects.concat([importedFileName]) : [importedFileName]; + var cwd = host.getCurrentDirectory ? host.getCurrentDirectory() : ""; + var targets = importedFileNames.map(function (f) { return ts.getNormalizedAbsolutePath(f, cwd); }); + var links = discoverProbableSymlinks(files, getCanonicalFileName, cwd); + var result = []; + var compareStrings = (!host.useCaseSensitiveFileNames || host.useCaseSensitiveFileNames()) ? ts.compareStringsCaseSensitive : ts.compareStringsCaseInsensitive; + links.forEach(function (resolved, path) { + if (ts.startsWithDirectory(importingFileName, resolved, getCanonicalFileName)) { + return; // Don't want to a package to globally import from itself + } + var target = targets.find(function (t) { return compareStrings(t.slice(0, resolved.length + 1), resolved + "/") === 0 /* EqualTo */; }); + if (target === undefined) + return; + var relative = ts.getRelativePathFromDirectory(resolved, target, getCanonicalFileName); + var option = ts.resolvePath(path, relative); + if (!host.fileExists || host.fileExists(option)) { + result.push(option); + } + }); + result.push.apply(result, targets); + return result; + } + function tryGetModuleNameFromAmbientModule(moduleSymbol) { + var decl = ts.find(moduleSymbol.declarations, function (d) { return ts.isNonGlobalAmbientModule(d) && (!ts.isExternalModuleAugmentation(d) || !ts.isExternalModuleNameRelative(ts.getTextOfIdentifierOrLiteral(d.name))); }); + if (decl) { + return decl.name.text; + } + } + function tryGetModuleNameFromPaths(relativeToBaseUrlWithIndex, relativeToBaseUrl, paths) { + for (var key in paths) { + for (var _i = 0, _a = paths[key]; _i < _a.length; _i++) { + var patternText_1 = _a[_i]; + var pattern = ts.removeFileExtension(ts.normalizePath(patternText_1)); + var indexOfStar = pattern.indexOf("*"); + if (indexOfStar !== -1) { + var prefix = pattern.substr(0, indexOfStar); + var suffix = pattern.substr(indexOfStar + 1); + if (relativeToBaseUrl.length >= prefix.length + suffix.length && + ts.startsWith(relativeToBaseUrl, prefix) && + ts.endsWith(relativeToBaseUrl, suffix) || + !suffix && relativeToBaseUrl === ts.removeTrailingDirectorySeparator(prefix)) { + var matchedStar = relativeToBaseUrl.substr(prefix.length, relativeToBaseUrl.length - suffix.length); + return key.replace("*", matchedStar); + } + } + else if (pattern === relativeToBaseUrl || pattern === relativeToBaseUrlWithIndex) { + return key; + } + } + } + } + function tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName) { + var normalizedTargetPath = getPathRelativeToRootDirs(moduleFileName, rootDirs, getCanonicalFileName); + if (normalizedTargetPath === undefined) { + return undefined; + } + var normalizedSourcePath = getPathRelativeToRootDirs(sourceDirectory, rootDirs, getCanonicalFileName); + var relativePath = normalizedSourcePath !== undefined ? ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(normalizedSourcePath, normalizedTargetPath, getCanonicalFileName)) : normalizedTargetPath; + return ts.removeFileExtension(relativePath); + } + function tryGetModuleNameAsNodeModule(moduleFileName, _a, host, options) { + var getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory; + if (!host.fileExists || !host.readFile) { + return undefined; + } + var parts = getNodeModulePathParts(moduleFileName); + if (!parts) { + return undefined; + } + var packageRootPath = moduleFileName.substring(0, parts.packageRootIndex); + var packageJsonPath = ts.combinePaths(packageRootPath, "package.json"); + var packageJsonContent = host.fileExists(packageJsonPath) + ? JSON.parse(host.readFile(packageJsonPath)) + : undefined; + var versionPaths = packageJsonContent && packageJsonContent.typesVersions + ? ts.getPackageJsonTypesVersionsPaths(packageJsonContent.typesVersions) + : undefined; + if (versionPaths) { + var subModuleName = moduleFileName.slice(parts.packageRootIndex + 1); + var fromPaths = tryGetModuleNameFromPaths(ts.removeFileExtension(subModuleName), removeExtensionAndIndexPostFix(subModuleName, 0 /* Minimal */, options), versionPaths.paths); + if (fromPaths !== undefined) { + moduleFileName = ts.combinePaths(moduleFileName.slice(0, parts.packageRootIndex), fromPaths); + } + } + // Simplify the full file path to something that can be resolved by Node. + // If the module could be imported by a directory name, use that directory's name + var moduleSpecifier = getDirectoryOrExtensionlessFileName(moduleFileName); + // Get a path that's relative to node_modules or the importing file's path + // if node_modules folder is in this folder or any of its parent folders, no need to keep it. + if (!ts.startsWith(sourceDirectory, getCanonicalFileName(moduleSpecifier.substring(0, parts.topLevelNodeModulesIndex)))) + return undefined; + // If the module was found in @types, get the actual Node package name + var nodeModulesDirectoryName = moduleSpecifier.substring(parts.topLevelPackageNameIndex + 1); + var packageName = ts.getPackageNameFromTypesPackageName(nodeModulesDirectoryName); + // For classic resolution, only allow importing from node_modules/@types, not other node_modules + return ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs && packageName === nodeModulesDirectoryName ? undefined : packageName; + function getDirectoryOrExtensionlessFileName(path) { + // If the file is the main module, it can be imported by the package name + if (packageJsonContent) { + var mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main; + if (mainFileRelative) { + var mainExportFile = ts.toPath(mainFileRelative, packageRootPath, getCanonicalFileName); + if (ts.removeFileExtension(mainExportFile) === ts.removeFileExtension(getCanonicalFileName(path))) { + return packageRootPath; + } + } + } + // We still have a file name - remove the extension + var fullModulePathWithoutExtension = ts.removeFileExtension(path); + // If the file is /index, it can be imported by its directory name + // IFF there is not _also_ a file by the same name + if (getCanonicalFileName(fullModulePathWithoutExtension.substring(parts.fileNameIndex)) === "/index" && !tryGetAnyFileFromPath(host, fullModulePathWithoutExtension.substring(0, parts.fileNameIndex))) { + return fullModulePathWithoutExtension.substring(0, parts.fileNameIndex); + } + return fullModulePathWithoutExtension; + } + } + function tryGetAnyFileFromPath(host, path) { + if (!host.fileExists) + return; + // We check all js, `node` and `json` extensions in addition to TS, since node module resolution would also choose those over the directory + var extensions = ts.getSupportedExtensions({ allowJs: true }, [{ extension: "node", isMixedContent: false }, { extension: "json", isMixedContent: false, scriptKind: 6 /* JSON */ }]); + for (var _i = 0, extensions_3 = extensions; _i < extensions_3.length; _i++) { + var e = extensions_3[_i]; + var fullPath = path + e; + if (host.fileExists(fullPath)) { + return fullPath; + } + } + } + function getNodeModulePathParts(fullPath) { + // If fullPath can't be valid module file within node_modules, returns undefined. + // Example of expected pattern: /base/path/node_modules/[@scope/otherpackage/@otherscope/node_modules/]package/[subdirectory/]file.js + // Returns indices: ^ ^ ^ ^ + var topLevelNodeModulesIndex = 0; + var topLevelPackageNameIndex = 0; + var packageRootIndex = 0; + var fileNameIndex = 0; + var States; + (function (States) { + States[States["BeforeNodeModules"] = 0] = "BeforeNodeModules"; + States[States["NodeModules"] = 1] = "NodeModules"; + States[States["Scope"] = 2] = "Scope"; + States[States["PackageContent"] = 3] = "PackageContent"; + })(States || (States = {})); + var partStart = 0; + var partEnd = 0; + var state = 0 /* BeforeNodeModules */; + while (partEnd >= 0) { + partStart = partEnd; + partEnd = fullPath.indexOf("/", partStart + 1); + switch (state) { + case 0 /* BeforeNodeModules */: + if (fullPath.indexOf(ts.nodeModulesPathPart, partStart) === partStart) { + topLevelNodeModulesIndex = partStart; + topLevelPackageNameIndex = partEnd; + state = 1 /* NodeModules */; + } + break; + case 1 /* NodeModules */: + case 2 /* Scope */: + if (state === 1 /* NodeModules */ && fullPath.charAt(partStart + 1) === "@") { + state = 2 /* Scope */; + } + else { + packageRootIndex = partEnd; + state = 3 /* PackageContent */; + } + break; + case 3 /* PackageContent */: + if (fullPath.indexOf(ts.nodeModulesPathPart, partStart) === partStart) { + state = 1 /* NodeModules */; + } + else { + state = 3 /* PackageContent */; + } + break; + } + } + fileNameIndex = partStart; + return state > 1 /* NodeModules */ ? { topLevelNodeModulesIndex: topLevelNodeModulesIndex, topLevelPackageNameIndex: topLevelPackageNameIndex, packageRootIndex: packageRootIndex, fileNameIndex: fileNameIndex } : undefined; + } + function getPathRelativeToRootDirs(path, rootDirs, getCanonicalFileName) { + return ts.firstDefined(rootDirs, function (rootDir) { + var relativePath = getRelativePathIfInDirectory(path, rootDir, getCanonicalFileName); // TODO: GH#18217 + return isPathRelativeToParent(relativePath) ? undefined : relativePath; + }); + } + function removeExtensionAndIndexPostFix(fileName, ending, options) { + if (ts.fileExtensionIs(fileName, ".json" /* Json */)) + return fileName; + var noExtension = ts.removeFileExtension(fileName); + switch (ending) { + case 0 /* Minimal */: + return ts.removeSuffix(noExtension, "/index"); + case 1 /* Index */: + return noExtension; + case 2 /* JsExtension */: + return noExtension + getJSExtensionForFile(fileName, options); + default: + return ts.Debug.assertNever(ending); + } + } + function getJSExtensionForFile(fileName, options) { + var ext = ts.extensionFromPath(fileName); + switch (ext) { + case ".ts" /* Ts */: + case ".d.ts" /* Dts */: + return ".js" /* Js */; + case ".tsx" /* Tsx */: + return options.jsx === 1 /* Preserve */ ? ".jsx" /* Jsx */ : ".js" /* Js */; + case ".js" /* Js */: + case ".jsx" /* Jsx */: + case ".json" /* Json */: + return ext; + default: + return ts.Debug.assertNever(ext); + } + } + function getRelativePathIfInDirectory(path, directoryPath, getCanonicalFileName) { + var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); + return ts.isRootedDiskPath(relativePath) ? undefined : relativePath; + } + function isPathRelativeToParent(path) { + return ts.startsWith(path, ".."); + } + })(moduleSpecifiers = ts.moduleSpecifiers || (ts.moduleSpecifiers = {})); +})(ts || (ts = {})); +/*@internal*/ +var ts; +(function (ts) { + var sysFormatDiagnosticsHost = ts.sys ? { + getCurrentDirectory: function () { return ts.sys.getCurrentDirectory(); }, + getNewLine: function () { return ts.sys.newLine; }, + getCanonicalFileName: ts.createGetCanonicalFileName(ts.sys.useCaseSensitiveFileNames) + } : undefined; // TODO: GH#18217 + /** + * Create a function that reports error by writing to the system and handles the formating of the diagnostic + */ + function createDiagnosticReporter(system, pretty) { + var host = system === ts.sys ? sysFormatDiagnosticsHost : { + getCurrentDirectory: function () { return system.getCurrentDirectory(); }, + getNewLine: function () { return system.newLine; }, + getCanonicalFileName: ts.createGetCanonicalFileName(system.useCaseSensitiveFileNames), + }; + if (!pretty) { + return function (diagnostic) { return system.write(ts.formatDiagnostic(diagnostic, host)); }; + } + var diagnostics = new Array(1); + return function (diagnostic) { + diagnostics[0] = diagnostic; + system.write(ts.formatDiagnosticsWithColorAndContext(diagnostics, host) + host.getNewLine()); + diagnostics[0] = undefined; // TODO: GH#18217 + }; + } + ts.createDiagnosticReporter = createDiagnosticReporter; + /** + * @returns Whether the screen was cleared. + */ + function clearScreenIfNotWatchingForFileChanges(system, diagnostic, options) { + if (system.clearScreen && + !options.preserveWatchOutput && + !options.extendedDiagnostics && + !options.diagnostics && + ts.contains(ts.screenStartingMessageCodes, diagnostic.code)) { + system.clearScreen(); + return true; + } + return false; + } + ts.screenStartingMessageCodes = [ + ts.Diagnostics.Starting_compilation_in_watch_mode.code, + ts.Diagnostics.File_change_detected_Starting_incremental_compilation.code, + ]; + function getPlainDiagnosticFollowingNewLines(diagnostic, newLine) { + return ts.contains(ts.screenStartingMessageCodes, diagnostic.code) + ? newLine + newLine + : newLine; + } + /** + * Create a function that reports watch status by writing to the system and handles the formating of the diagnostic + */ + function createWatchStatusReporter(system, pretty) { + return pretty ? + function (diagnostic, newLine, options) { + clearScreenIfNotWatchingForFileChanges(system, diagnostic, options); + var output = "[" + ts.formatColorAndReset(new Date().toLocaleTimeString(), ts.ForegroundColorEscapeSequences.Grey) + "] "; + output += "" + ts.flattenDiagnosticMessageText(diagnostic.messageText, system.newLine) + (newLine + newLine); + system.write(output); + } : + function (diagnostic, newLine, options) { + var output = ""; + if (!clearScreenIfNotWatchingForFileChanges(system, diagnostic, options)) { + output += newLine; + } + output += new Date().toLocaleTimeString() + " - "; + output += "" + ts.flattenDiagnosticMessageText(diagnostic.messageText, system.newLine) + getPlainDiagnosticFollowingNewLines(diagnostic, newLine); + system.write(output); + }; + } + ts.createWatchStatusReporter = createWatchStatusReporter; + /** Parses config file using System interface */ + function parseConfigFileWithSystem(configFileName, optionsToExtend, system, reportDiagnostic) { + var host = system; + host.onUnRecoverableConfigFileDiagnostic = function (diagnostic) { return reportUnrecoverableDiagnostic(ts.sys, reportDiagnostic, diagnostic); }; + var result = ts.getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host); + host.onUnRecoverableConfigFileDiagnostic = undefined; // TODO: GH#18217 + return result; + } + ts.parseConfigFileWithSystem = parseConfigFileWithSystem; + function getErrorCountForSummary(diagnostics) { + return ts.countWhere(diagnostics, function (diagnostic) { return diagnostic.category === ts.DiagnosticCategory.Error; }); + } + ts.getErrorCountForSummary = getErrorCountForSummary; + function getWatchErrorSummaryDiagnosticMessage(errorCount) { + return errorCount === 1 ? + ts.Diagnostics.Found_1_error_Watching_for_file_changes : + ts.Diagnostics.Found_0_errors_Watching_for_file_changes; + } + ts.getWatchErrorSummaryDiagnosticMessage = getWatchErrorSummaryDiagnosticMessage; + function getErrorSummaryText(errorCount, newLine) { + if (errorCount === 0) + return ""; + var d = ts.createCompilerDiagnostic(errorCount === 1 ? ts.Diagnostics.Found_1_error : ts.Diagnostics.Found_0_errors, errorCount); + return "" + newLine + ts.flattenDiagnosticMessageText(d.messageText, newLine) + newLine + newLine; + } + ts.getErrorSummaryText = getErrorSummaryText; + /** + * Helper that emit files, report diagnostics and lists emitted and/or source files depending on compiler options + */ + function emitFilesAndReportErrors(program, reportDiagnostic, writeFileName, reportSummary, writeFile) { + // First get and report any syntactic errors. + var diagnostics = program.getConfigFileParsingDiagnostics().slice(); + var configFileParsingDiagnosticsLength = diagnostics.length; + ts.addRange(diagnostics, program.getSyntacticDiagnostics()); + var reportSemanticDiagnostics = false; + // If we didn't have any syntactic errors, then also try getting the global and + // semantic errors. + if (diagnostics.length === configFileParsingDiagnosticsLength) { + ts.addRange(diagnostics, program.getOptionsDiagnostics()); + ts.addRange(diagnostics, program.getGlobalDiagnostics()); + if (diagnostics.length === configFileParsingDiagnosticsLength) { + reportSemanticDiagnostics = true; + } + } + // Emit and report any errors we ran into. + var _a = program.emit(/*targetSourceFile*/ undefined, writeFile), emittedFiles = _a.emittedFiles, emitSkipped = _a.emitSkipped, emitDiagnostics = _a.diagnostics; + ts.addRange(diagnostics, emitDiagnostics); + if (reportSemanticDiagnostics) { + ts.addRange(diagnostics, program.getSemanticDiagnostics()); + } + ts.sortAndDeduplicateDiagnostics(diagnostics).forEach(reportDiagnostic); + if (writeFileName) { + var currentDir_1 = program.getCurrentDirectory(); + ts.forEach(emittedFiles, function (file) { + var filepath = ts.getNormalizedAbsolutePath(file, currentDir_1); + writeFileName("TSFILE: " + filepath); + }); + if (program.getCompilerOptions().listFiles) { + ts.forEach(program.getSourceFiles(), function (file) { + writeFileName(file.fileName); + }); + } + } + if (reportSummary) { + reportSummary(getErrorCountForSummary(diagnostics)); + } + if (emitSkipped && diagnostics.length > 0) { + // If the emitter didn't emit anything, then pass that value along. + return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; + } + else if (diagnostics.length > 0) { + // The emitter emitted something, inform the caller if that happened in the presence + // of diagnostics or not. + return ts.ExitStatus.DiagnosticsPresent_OutputsGenerated; + } + return ts.ExitStatus.Success; + } + ts.emitFilesAndReportErrors = emitFilesAndReportErrors; + var noopFileWatcher = { close: ts.noop }; + function createWatchHost(system, reportWatchStatus) { + if (system === void 0) { system = ts.sys; } + var onWatchStatusChange = reportWatchStatus || createWatchStatusReporter(system); + return { + onWatchStatusChange: onWatchStatusChange, + watchFile: system.watchFile ? (function (path, callback, pollingInterval) { return system.watchFile(path, callback, pollingInterval); }) : function () { return noopFileWatcher; }, + watchDirectory: system.watchDirectory ? (function (path, callback, recursive) { return system.watchDirectory(path, callback, recursive); }) : function () { return noopFileWatcher; }, + setTimeout: system.setTimeout ? (function (callback, ms) { + var args = []; + for (var _i = 2; _i < arguments.length; _i++) { + args[_i - 2] = arguments[_i]; + } + var _a; + return (_a = system.setTimeout).call.apply(_a, [system, callback, ms].concat(args)); + }) : ts.noop, + clearTimeout: system.clearTimeout ? (function (timeoutId) { return system.clearTimeout(timeoutId); }) : ts.noop + }; + } + ts.createWatchHost = createWatchHost; + /** + * Creates the watch compiler host that can be extended with config file or root file names and options host + */ + function createWatchCompilerHost(system, createProgram, reportDiagnostic, reportWatchStatus) { + if (system === void 0) { system = ts.sys; } + if (!createProgram) { + createProgram = ts.createEmitAndSemanticDiagnosticsBuilderProgram; + } + var host = system; + host; // tslint:disable-line no-unused-expression (TODO: `host` is unused!) + var useCaseSensitiveFileNames = function () { return system.useCaseSensitiveFileNames; }; + var writeFileName = function (s) { return system.write(s + system.newLine); }; + var _a = createWatchHost(system, reportWatchStatus), onWatchStatusChange = _a.onWatchStatusChange, watchFile = _a.watchFile, watchDirectory = _a.watchDirectory, setTimeout = _a.setTimeout, clearTimeout = _a.clearTimeout; + return { + useCaseSensitiveFileNames: useCaseSensitiveFileNames, + getNewLine: function () { return system.newLine; }, + getCurrentDirectory: function () { return system.getCurrentDirectory(); }, + getDefaultLibLocation: getDefaultLibLocation, + getDefaultLibFileName: function (options) { return ts.combinePaths(getDefaultLibLocation(), ts.getDefaultLibFileName(options)); }, + fileExists: function (path) { return system.fileExists(path); }, + readFile: function (path, encoding) { return system.readFile(path, encoding); }, + directoryExists: function (path) { return system.directoryExists(path); }, + getDirectories: function (path) { return system.getDirectories(path); }, + readDirectory: function (path, extensions, exclude, include, depth) { return system.readDirectory(path, extensions, exclude, include, depth); }, + realpath: system.realpath && (function (path) { return system.realpath(path); }), + getEnvironmentVariable: system.getEnvironmentVariable && (function (name) { return system.getEnvironmentVariable(name); }), + watchFile: watchFile, + watchDirectory: watchDirectory, + setTimeout: setTimeout, + clearTimeout: clearTimeout, + trace: function (s) { return system.write(s); }, + onWatchStatusChange: onWatchStatusChange, + createDirectory: function (path) { return system.createDirectory(path); }, + writeFile: function (path, data, writeByteOrderMark) { return system.writeFile(path, data, writeByteOrderMark); }, + onCachedDirectoryStructureHostCreate: function (cacheHost) { return host = cacheHost || system; }, + createHash: system.createHash && (function (s) { return system.createHash(s); }), + createProgram: createProgram, + afterProgramCreate: emitFilesAndReportErrorUsingBuilder + }; + function getDefaultLibLocation() { + return ts.getDirectoryPath(ts.normalizePath(system.getExecutingFilePath())); + } + function emitFilesAndReportErrorUsingBuilder(builderProgram) { + var compilerOptions = builderProgram.getCompilerOptions(); + var newLine = ts.getNewLineCharacter(compilerOptions, function () { return system.newLine; }); + emitFilesAndReportErrors(builderProgram, reportDiagnostic, writeFileName, function (errorCount) { return onWatchStatusChange(ts.createCompilerDiagnostic(getWatchErrorSummaryDiagnosticMessage(errorCount), errorCount), newLine, compilerOptions); }); + } + } + /** + * Report error and exit + */ + function reportUnrecoverableDiagnostic(system, reportDiagnostic, diagnostic) { + reportDiagnostic(diagnostic); + system.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); + } + /** + * Creates the watch compiler host from system for config file in watch mode + */ + function createWatchCompilerHostOfConfigFile(configFileName, optionsToExtend, system, createProgram, reportDiagnostic, reportWatchStatus) { + var diagnosticReporter = reportDiagnostic || createDiagnosticReporter(system); + var host = createWatchCompilerHost(system, createProgram, diagnosticReporter, reportWatchStatus); + host.onUnRecoverableConfigFileDiagnostic = function (diagnostic) { return reportUnrecoverableDiagnostic(system, diagnosticReporter, diagnostic); }; + host.configFileName = configFileName; + host.optionsToExtend = optionsToExtend; + return host; + } + ts.createWatchCompilerHostOfConfigFile = createWatchCompilerHostOfConfigFile; + /** + * Creates the watch compiler host from system for compiling root files and options in watch mode + */ + function createWatchCompilerHostOfFilesAndCompilerOptions(rootFiles, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences) { + var host = createWatchCompilerHost(system, createProgram, reportDiagnostic || createDiagnosticReporter(system), reportWatchStatus); + host.rootFiles = rootFiles; + host.options = options; + host.projectReferences = projectReferences; + return host; + } + ts.createWatchCompilerHostOfFilesAndCompilerOptions = createWatchCompilerHostOfFilesAndCompilerOptions; +})(ts || (ts = {})); +(function (ts) { + function createWatchCompilerHost(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences) { + if (ts.isArray(rootFilesOrConfigFileName)) { + return ts.createWatchCompilerHostOfFilesAndCompilerOptions(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences); // TODO: GH#18217 + } + else { + return ts.createWatchCompilerHostOfConfigFile(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus); + } + } + ts.createWatchCompilerHost = createWatchCompilerHost; + var initialVersion = 1; + function createWatchProgram(host) { + var builderProgram; + var reloadLevel; // level to indicate if the program needs to be reloaded from config file/just filenames etc + var missingFilesMap; // Map of file watchers for the missing files + var watchedWildcardDirectories; // map of watchers for the wild card directories in the config file + var timerToUpdateProgram; // timer callback to recompile the program + var sourceFilesCache = ts.createMap(); // Cache that stores the source file and version info + var missingFilePathsRequestedForRelease; // These paths are held temparirly so that we can remove the entry from source file cache if the file is not tracked by missing files + var hasChangedCompilerOptions = false; // True if the compiler options have changed between compilations + var hasChangedAutomaticTypeDirectiveNames = false; // True if the automatic type directives have changed + var useCaseSensitiveFileNames = host.useCaseSensitiveFileNames(); + var currentDirectory = host.getCurrentDirectory(); + var getCurrentDirectory = function () { return currentDirectory; }; + var readFile = function (path, encoding) { return host.readFile(path, encoding); }; + var configFileName = host.configFileName, _a = host.optionsToExtend, optionsToExtendForConfigFile = _a === void 0 ? {} : _a, createProgram = host.createProgram; + var rootFileNames = host.rootFiles, compilerOptions = host.options, projectReferences = host.projectReferences; + var configFileSpecs; + var configFileParsingDiagnostics; + var canConfigFileJsonReportNoInputFiles = false; + var hasChangedConfigFileParsingErrors = false; + var cachedDirectoryStructureHost = configFileName === undefined ? undefined : ts.createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensitiveFileNames); + if (cachedDirectoryStructureHost && host.onCachedDirectoryStructureHostCreate) { + host.onCachedDirectoryStructureHostCreate(cachedDirectoryStructureHost); + } + var directoryStructureHost = cachedDirectoryStructureHost || host; + var parseConfigFileHost = { + useCaseSensitiveFileNames: useCaseSensitiveFileNames, + readDirectory: function (path, extensions, exclude, include, depth) { return directoryStructureHost.readDirectory(path, extensions, exclude, include, depth); }, + fileExists: function (path) { return host.fileExists(path); }, + readFile: readFile, + getCurrentDirectory: getCurrentDirectory, + onUnRecoverableConfigFileDiagnostic: host.onUnRecoverableConfigFileDiagnostic, + trace: host.trace ? function (s) { return host.trace(s); } : undefined + }; + // From tsc we want to get already parsed result and hence check for rootFileNames + var newLine = updateNewLine(); + if (configFileName && host.configFileParsingResult) { + setConfigFileParsingResult(host.configFileParsingResult); + newLine = updateNewLine(); + } + reportWatchDiagnostic(ts.Diagnostics.Starting_compilation_in_watch_mode); + if (configFileName && !host.configFileParsingResult) { + newLine = ts.getNewLineCharacter(optionsToExtendForConfigFile, function () { return host.getNewLine(); }); + ts.Debug.assert(!rootFileNames); + parseConfigFile(); + newLine = updateNewLine(); + } + var trace = host.trace && (function (s) { host.trace(s + newLine); }); + var watchLogLevel = trace ? compilerOptions.extendedDiagnostics ? ts.WatchLogLevel.Verbose : + compilerOptions.diagnostics ? ts.WatchLogLevel.TriggerOnly : ts.WatchLogLevel.None : ts.WatchLogLevel.None; + var writeLog = watchLogLevel !== ts.WatchLogLevel.None ? trace : ts.noop; // TODO: GH#18217 + var _b = ts.getWatchFactory(watchLogLevel, writeLog), watchFile = _b.watchFile, watchFilePath = _b.watchFilePath, watchDirectory = _b.watchDirectory; + var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); + writeLog("Current directory: " + currentDirectory + " CaseSensitiveFileNames: " + useCaseSensitiveFileNames); + if (configFileName) { + watchFile(host, configFileName, scheduleProgramReload, ts.PollingInterval.High, "Config file"); + } + var compilerHost = { + // Members for CompilerHost + getSourceFile: function (fileName, languageVersion, onError, shouldCreateNewSourceFile) { return getVersionedSourceFileByPath(fileName, toPath(fileName), languageVersion, onError, shouldCreateNewSourceFile); }, + getSourceFileByPath: getVersionedSourceFileByPath, + getDefaultLibLocation: host.getDefaultLibLocation && (function () { return host.getDefaultLibLocation(); }), + getDefaultLibFileName: function (options) { return host.getDefaultLibFileName(options); }, + writeFile: writeFile, + getCurrentDirectory: getCurrentDirectory, + useCaseSensitiveFileNames: function () { return useCaseSensitiveFileNames; }, + getCanonicalFileName: getCanonicalFileName, + getNewLine: function () { return newLine; }, + fileExists: fileExists, + readFile: readFile, + trace: trace, + directoryExists: directoryStructureHost.directoryExists && (function (path) { return directoryStructureHost.directoryExists(path); }), + getDirectories: (directoryStructureHost.getDirectories && (function (path) { return directoryStructureHost.getDirectories(path); })), + realpath: host.realpath && (function (s) { return host.realpath(s); }), + getEnvironmentVariable: host.getEnvironmentVariable ? (function (name) { return host.getEnvironmentVariable(name); }) : (function () { return ""; }), + onReleaseOldSourceFile: onReleaseOldSourceFile, + createHash: host.createHash && (function (data) { return host.createHash(data); }), + // Members for ResolutionCacheHost + toPath: toPath, + getCompilationSettings: function () { return compilerOptions; }, + watchDirectoryOfFailedLookupLocation: function (dir, cb, flags) { return watchDirectory(host, dir, cb, flags, "Failed Lookup Locations"); }, + watchTypeRootsDirectory: function (dir, cb, flags) { return watchDirectory(host, dir, cb, flags, "Type roots"); }, + getCachedDirectoryStructureHost: function () { return cachedDirectoryStructureHost; }, + onInvalidatedResolution: scheduleProgramUpdate, + onChangedAutomaticTypeDirectiveNames: function () { + hasChangedAutomaticTypeDirectiveNames = true; + scheduleProgramUpdate(); + }, + maxNumberOfFilesToIterateForInvalidation: host.maxNumberOfFilesToIterateForInvalidation, + getCurrentProgram: getCurrentProgram, + writeLog: writeLog, + readDirectory: function (path, extensions, exclude, include, depth) { return directoryStructureHost.readDirectory(path, extensions, exclude, include, depth); }, + }; + // Cache for the module resolution + var resolutionCache = ts.createResolutionCache(compilerHost, configFileName ? + ts.getDirectoryPath(ts.getNormalizedAbsolutePath(configFileName, currentDirectory)) : + currentDirectory, + /*logChangesWhenResolvingModule*/ false); + // Resolve module using host module resolution strategy if provided otherwise use resolution cache to resolve module names + compilerHost.resolveModuleNames = host.resolveModuleNames ? + (function (moduleNames, containingFile, reusedNames, redirectedReference) { return host.resolveModuleNames(moduleNames, containingFile, reusedNames, redirectedReference); }) : + (function (moduleNames, containingFile, reusedNames, redirectedReference) { return resolutionCache.resolveModuleNames(moduleNames, containingFile, reusedNames, redirectedReference); }); + compilerHost.resolveTypeReferenceDirectives = host.resolveTypeReferenceDirectives ? + (function (typeDirectiveNames, containingFile, redirectedReference) { return host.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile, redirectedReference); }) : + (function (typeDirectiveNames, containingFile, redirectedReference) { return resolutionCache.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile, redirectedReference); }); + var userProvidedResolution = !!host.resolveModuleNames || !!host.resolveTypeReferenceDirectives; + synchronizeProgram(); + // Update the wild card directory watch + watchConfigFileWildCardDirectories(); + return configFileName ? + { getCurrentProgram: getCurrentBuilderProgram, getProgram: synchronizeProgram } : + { getCurrentProgram: getCurrentBuilderProgram, getProgram: synchronizeProgram, updateRootFileNames: updateRootFileNames }; + function getCurrentBuilderProgram() { + return builderProgram; + } + function getCurrentProgram() { + return builderProgram && builderProgram.getProgram(); + } + function synchronizeProgram() { + writeLog("Synchronizing program"); + var program = getCurrentProgram(); + if (hasChangedCompilerOptions) { + newLine = updateNewLine(); + if (program && ts.changesAffectModuleResolution(program.getCompilerOptions(), compilerOptions)) { + resolutionCache.clear(); + } + } + // All resolutions are invalid if user provided resolutions + var hasInvalidatedResolution = resolutionCache.createHasInvalidatedResolution(userProvidedResolution); + if (ts.isProgramUptoDate(getCurrentProgram(), rootFileNames, compilerOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, projectReferences)) { + if (hasChangedConfigFileParsingErrors) { + builderProgram = createProgram(/*rootNames*/ undefined, /*options*/ undefined, compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences); + hasChangedConfigFileParsingErrors = false; + } + } + else { + createNewProgram(program, hasInvalidatedResolution); + } + if (host.afterProgramCreate) { + host.afterProgramCreate(builderProgram); + } + return builderProgram; + } + function createNewProgram(program, hasInvalidatedResolution) { + // Compile the program + if (watchLogLevel !== ts.WatchLogLevel.None) { + writeLog("CreatingProgramWith::"); + writeLog(" roots: " + JSON.stringify(rootFileNames)); + writeLog(" options: " + JSON.stringify(compilerOptions)); + } + var needsUpdateInTypeRootWatch = hasChangedCompilerOptions || !program; + hasChangedCompilerOptions = false; + hasChangedConfigFileParsingErrors = false; + resolutionCache.startCachingPerDirectoryResolution(); + compilerHost.hasInvalidatedResolution = hasInvalidatedResolution; + compilerHost.hasChangedAutomaticTypeDirectiveNames = hasChangedAutomaticTypeDirectiveNames; + builderProgram = createProgram(rootFileNames, compilerOptions, compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences); + resolutionCache.finishCachingPerDirectoryResolution(); + // Update watches + ts.updateMissingFilePathsWatch(builderProgram.getProgram(), missingFilesMap || (missingFilesMap = ts.createMap()), watchMissingFilePath); + if (needsUpdateInTypeRootWatch) { + resolutionCache.updateTypeRootsWatch(); + } + if (missingFilePathsRequestedForRelease) { + // These are the paths that program creater told us as not in use any more but were missing on the disk. + // We didnt remove the entry for them from sourceFiles cache so that we dont have to do File IO, + // if there is already watcher for it (for missing files) + // At this point our watches were updated, hence now we know that these paths are not tracked and need to be removed + // so that at later time we have correct result of their presence + for (var _i = 0, missingFilePathsRequestedForRelease_1 = missingFilePathsRequestedForRelease; _i < missingFilePathsRequestedForRelease_1.length; _i++) { + var missingFilePath = missingFilePathsRequestedForRelease_1[_i]; + if (!missingFilesMap.has(missingFilePath)) { + sourceFilesCache.delete(missingFilePath); + } + } + missingFilePathsRequestedForRelease = undefined; + } + } + function updateRootFileNames(files) { + ts.Debug.assert(!configFileName, "Cannot update root file names with config file watch mode"); + rootFileNames = files; + scheduleProgramUpdate(); + } + function updateNewLine() { + return ts.getNewLineCharacter(compilerOptions || optionsToExtendForConfigFile, function () { return host.getNewLine(); }); + } + function toPath(fileName) { + return ts.toPath(fileName, currentDirectory, getCanonicalFileName); + } + function isFileMissingOnHost(hostSourceFile) { + return typeof hostSourceFile === "number"; + } + function isFilePresentOnHost(hostSourceFile) { + return !!hostSourceFile.sourceFile; + } + function fileExists(fileName) { + var path = toPath(fileName); + // If file is missing on host from cache, we can definitely say file doesnt exist + // otherwise we need to ensure from the disk + if (isFileMissingOnHost(sourceFilesCache.get(path))) { + return true; + } + return directoryStructureHost.fileExists(fileName); + } + function getVersionedSourceFileByPath(fileName, path, languageVersion, onError, shouldCreateNewSourceFile) { + var hostSourceFile = sourceFilesCache.get(path); + // No source file on the host + if (isFileMissingOnHost(hostSourceFile)) { + return undefined; + } + // Create new source file if requested or the versions dont match + if (!hostSourceFile || shouldCreateNewSourceFile || !isFilePresentOnHost(hostSourceFile) || hostSourceFile.version.toString() !== hostSourceFile.sourceFile.version) { + var sourceFile = getNewSourceFile(); + if (hostSourceFile) { + if (shouldCreateNewSourceFile) { + hostSourceFile.version++; + } + if (sourceFile) { + // Set the source file and create file watcher now that file was present on the disk + hostSourceFile.sourceFile = sourceFile; + sourceFile.version = hostSourceFile.version.toString(); + if (!hostSourceFile.fileWatcher) { + hostSourceFile.fileWatcher = watchFilePath(host, fileName, onSourceFileChange, ts.PollingInterval.Low, path, "Source file"); + } + } + else { + // There is no source file on host any more, close the watch, missing file paths will track it + if (isFilePresentOnHost(hostSourceFile)) { + hostSourceFile.fileWatcher.close(); + } + sourceFilesCache.set(path, hostSourceFile.version); + } + } + else { + if (sourceFile) { + sourceFile.version = initialVersion.toString(); + var fileWatcher = watchFilePath(host, fileName, onSourceFileChange, ts.PollingInterval.Low, path, "Source file"); + sourceFilesCache.set(path, { sourceFile: sourceFile, version: initialVersion, fileWatcher: fileWatcher }); + } + else { + sourceFilesCache.set(path, initialVersion); + } + } + return sourceFile; + } + return hostSourceFile.sourceFile; + function getNewSourceFile() { + var text; + try { + ts.performance.mark("beforeIORead"); + text = host.readFile(fileName, compilerOptions.charset); + ts.performance.mark("afterIORead"); + ts.performance.measure("I/O Read", "beforeIORead", "afterIORead"); + } + catch (e) { + if (onError) { + onError(e.message); + } + } + return text !== undefined ? ts.createSourceFile(fileName, text, languageVersion) : undefined; + } + } + function nextSourceFileVersion(path) { + var hostSourceFile = sourceFilesCache.get(path); + if (hostSourceFile !== undefined) { + if (isFileMissingOnHost(hostSourceFile)) { + // The next version, lets set it as presence unknown file + sourceFilesCache.set(path, { version: Number(hostSourceFile) + 1 }); + } + else { + hostSourceFile.version++; + } + } + } + function getSourceVersion(path) { + var hostSourceFile = sourceFilesCache.get(path); + return !hostSourceFile || isFileMissingOnHost(hostSourceFile) ? undefined : hostSourceFile.version.toString(); + } + function onReleaseOldSourceFile(oldSourceFile, _oldOptions, hasSourceFileByPath) { + var hostSourceFileInfo = sourceFilesCache.get(oldSourceFile.resolvedPath); + // If this is the source file thats in the cache and new program doesnt need it, + // remove the cached entry. + // Note we arent deleting entry if file became missing in new program or + // there was version update and new source file was created. + if (hostSourceFileInfo) { + // record the missing file paths so they can be removed later if watchers arent tracking them + if (isFileMissingOnHost(hostSourceFileInfo)) { + (missingFilePathsRequestedForRelease || (missingFilePathsRequestedForRelease = [])).push(oldSourceFile.path); + } + else if (hostSourceFileInfo.sourceFile === oldSourceFile) { + if (hostSourceFileInfo.fileWatcher) { + hostSourceFileInfo.fileWatcher.close(); + } + sourceFilesCache.delete(oldSourceFile.resolvedPath); + if (!hasSourceFileByPath) { + resolutionCache.removeResolutionsOfFile(oldSourceFile.path); + } + } + } + } + function reportWatchDiagnostic(message) { + if (host.onWatchStatusChange) { + host.onWatchStatusChange(ts.createCompilerDiagnostic(message), newLine, compilerOptions || optionsToExtendForConfigFile); + } + } + // Upon detecting a file change, wait for 250ms and then perform a recompilation. This gives batch + // operations (such as saving all modified files in an editor) a chance to complete before we kick + // off a new compilation. + function scheduleProgramUpdate() { + if (!host.setTimeout || !host.clearTimeout) { + return; + } + if (timerToUpdateProgram) { + host.clearTimeout(timerToUpdateProgram); + } + writeLog("Scheduling update"); + timerToUpdateProgram = host.setTimeout(updateProgram, 250); + } + function scheduleProgramReload() { + ts.Debug.assert(!!configFileName); + reloadLevel = ts.ConfigFileProgramReloadLevel.Full; + scheduleProgramUpdate(); + } + function updateProgram() { + timerToUpdateProgram = undefined; + reportWatchDiagnostic(ts.Diagnostics.File_change_detected_Starting_incremental_compilation); + switch (reloadLevel) { + case ts.ConfigFileProgramReloadLevel.Partial: + return reloadFileNamesFromConfigFile(); + case ts.ConfigFileProgramReloadLevel.Full: + return reloadConfigFile(); + default: + synchronizeProgram(); + return; + } + } + function reloadFileNamesFromConfigFile() { + writeLog("Reloading new file names and options"); + var result = ts.getFileNamesFromConfigSpecs(configFileSpecs, ts.getDirectoryPath(configFileName), compilerOptions, parseConfigFileHost); + if (ts.updateErrorForNoInputFiles(result, configFileName, configFileSpecs, configFileParsingDiagnostics, canConfigFileJsonReportNoInputFiles)) { + hasChangedConfigFileParsingErrors = true; + } + rootFileNames = result.fileNames; + // Update the program + synchronizeProgram(); + } + function reloadConfigFile() { + writeLog("Reloading config file: " + configFileName); + reloadLevel = ts.ConfigFileProgramReloadLevel.None; + if (cachedDirectoryStructureHost) { + cachedDirectoryStructureHost.clearCache(); + } + parseConfigFile(); + hasChangedCompilerOptions = true; + synchronizeProgram(); + // Update the wild card directory watch + watchConfigFileWildCardDirectories(); + } + function parseConfigFile() { + setConfigFileParsingResult(ts.getParsedCommandLineOfConfigFile(configFileName, optionsToExtendForConfigFile, parseConfigFileHost)); // TODO: GH#18217 + } + function setConfigFileParsingResult(configFileParseResult) { + rootFileNames = configFileParseResult.fileNames; + compilerOptions = configFileParseResult.options; + configFileSpecs = configFileParseResult.configFileSpecs; // TODO: GH#18217 + projectReferences = configFileParseResult.projectReferences; + configFileParsingDiagnostics = ts.getConfigFileParsingDiagnostics(configFileParseResult).slice(); + canConfigFileJsonReportNoInputFiles = ts.canJsonReportNoInutFiles(configFileParseResult.raw); + hasChangedConfigFileParsingErrors = true; + } + function onSourceFileChange(fileName, eventKind, path) { + updateCachedSystemWithFile(fileName, path, eventKind); + // Update the source file cache + if (eventKind === ts.FileWatcherEventKind.Deleted && sourceFilesCache.get(path)) { + resolutionCache.invalidateResolutionOfFile(path); + } + resolutionCache.removeResolutionsFromProjectReferenceRedirects(path); + nextSourceFileVersion(path); + // Update the program + scheduleProgramUpdate(); + } + function updateCachedSystemWithFile(fileName, path, eventKind) { + if (cachedDirectoryStructureHost) { + cachedDirectoryStructureHost.addOrDeleteFile(fileName, path, eventKind); + } + } + function watchMissingFilePath(missingFilePath) { + return watchFilePath(host, missingFilePath, onMissingFileChange, ts.PollingInterval.Medium, missingFilePath, "Missing file"); + } + function onMissingFileChange(fileName, eventKind, missingFilePath) { + updateCachedSystemWithFile(fileName, missingFilePath, eventKind); + if (eventKind === ts.FileWatcherEventKind.Created && missingFilesMap.has(missingFilePath)) { + missingFilesMap.get(missingFilePath).close(); + missingFilesMap.delete(missingFilePath); + // Delete the entry in the source files cache so that new source file is created + nextSourceFileVersion(missingFilePath); + // When a missing file is created, we should update the graph. + scheduleProgramUpdate(); + } + } + function watchConfigFileWildCardDirectories() { + if (configFileSpecs) { + ts.updateWatchingWildcardDirectories(watchedWildcardDirectories || (watchedWildcardDirectories = ts.createMap()), ts.createMapFromTemplate(configFileSpecs.wildcardDirectories), watchWildcardDirectory); + } + else if (watchedWildcardDirectories) { + ts.clearMap(watchedWildcardDirectories, ts.closeFileWatcherOf); + } + } + function watchWildcardDirectory(directory, flags) { + return watchDirectory(host, directory, function (fileOrDirectory) { + ts.Debug.assert(!!configFileName); + var fileOrDirectoryPath = toPath(fileOrDirectory); + // Since the file existance changed, update the sourceFiles cache + if (cachedDirectoryStructureHost) { + cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); + } + nextSourceFileVersion(fileOrDirectoryPath); + if (ts.isPathInNodeModulesStartingWithDot(fileOrDirectoryPath)) + return; + // If the the added or created file or directory is not supported file name, ignore the file + // But when watched directory is added/removed, we need to reload the file list + if (fileOrDirectoryPath !== directory && ts.hasExtension(fileOrDirectoryPath) && !ts.isSupportedSourceFileName(fileOrDirectory, compilerOptions)) { + writeLog("Project: " + configFileName + " Detected file add/remove of non supported extension: " + fileOrDirectory); + return; + } + // Reload is pending, do the reload + if (reloadLevel !== ts.ConfigFileProgramReloadLevel.Full) { + reloadLevel = ts.ConfigFileProgramReloadLevel.Partial; + // Schedule Update the program + scheduleProgramUpdate(); + } + }, flags, "Wild card directories"); + } + function ensureDirectoriesExist(directoryPath) { + if (directoryPath.length > ts.getRootLength(directoryPath) && !host.directoryExists(directoryPath)) { + var parentDirectory = ts.getDirectoryPath(directoryPath); + ensureDirectoriesExist(parentDirectory); + host.createDirectory(directoryPath); + } + } + function writeFile(fileName, text, writeByteOrderMark, onError) { + try { + ts.performance.mark("beforeIOWrite"); + ensureDirectoriesExist(ts.getDirectoryPath(ts.normalizePath(fileName))); + host.writeFile(fileName, text, writeByteOrderMark); + ts.performance.mark("afterIOWrite"); + ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite"); + } + catch (e) { + if (onError) { + onError(e.message); + } + } + } + } + ts.createWatchProgram = createWatchProgram; +})(ts || (ts = {})); +// Currently we do not want to expose API for build, we should work out the API, and then expose it just like we did for builder/watch +/*@internal*/ +var ts; +(function (ts) { + var minimumDate = new Date(-8640000000000000); + var maximumDate = new Date(8640000000000000); + var BuildResultFlags; + (function (BuildResultFlags) { + BuildResultFlags[BuildResultFlags["None"] = 0] = "None"; + /** + * No errors of any kind occurred during build + */ + BuildResultFlags[BuildResultFlags["Success"] = 1] = "Success"; + /** + * None of the .d.ts files emitted by this build were + * different from the existing files on disk + */ + BuildResultFlags[BuildResultFlags["DeclarationOutputUnchanged"] = 2] = "DeclarationOutputUnchanged"; + BuildResultFlags[BuildResultFlags["ConfigFileErrors"] = 4] = "ConfigFileErrors"; + BuildResultFlags[BuildResultFlags["SyntaxErrors"] = 8] = "SyntaxErrors"; + BuildResultFlags[BuildResultFlags["TypeErrors"] = 16] = "TypeErrors"; + BuildResultFlags[BuildResultFlags["DeclarationEmitErrors"] = 32] = "DeclarationEmitErrors"; + BuildResultFlags[BuildResultFlags["EmitErrors"] = 64] = "EmitErrors"; + BuildResultFlags[BuildResultFlags["AnyErrors"] = 124] = "AnyErrors"; + })(BuildResultFlags || (BuildResultFlags = {})); + var UpToDateStatusType; + (function (UpToDateStatusType) { + UpToDateStatusType[UpToDateStatusType["Unbuildable"] = 0] = "Unbuildable"; + UpToDateStatusType[UpToDateStatusType["UpToDate"] = 1] = "UpToDate"; + /** + * The project appears out of date because its upstream inputs are newer than its outputs, + * but all of its outputs are actually newer than the previous identical outputs of its (.d.ts) inputs. + * This means we can Pseudo-build (just touch timestamps), as if we had actually built this project. + */ + UpToDateStatusType[UpToDateStatusType["UpToDateWithUpstreamTypes"] = 2] = "UpToDateWithUpstreamTypes"; + UpToDateStatusType[UpToDateStatusType["OutputMissing"] = 3] = "OutputMissing"; + UpToDateStatusType[UpToDateStatusType["OutOfDateWithSelf"] = 4] = "OutOfDateWithSelf"; + UpToDateStatusType[UpToDateStatusType["OutOfDateWithUpstream"] = 5] = "OutOfDateWithUpstream"; + UpToDateStatusType[UpToDateStatusType["UpstreamOutOfDate"] = 6] = "UpstreamOutOfDate"; + UpToDateStatusType[UpToDateStatusType["UpstreamBlocked"] = 7] = "UpstreamBlocked"; + UpToDateStatusType[UpToDateStatusType["ComputingUpstream"] = 8] = "ComputingUpstream"; + /** + * Projects with no outputs (i.e. "solution" files) + */ + UpToDateStatusType[UpToDateStatusType["ContainerOnly"] = 9] = "ContainerOnly"; + })(UpToDateStatusType = ts.UpToDateStatusType || (ts.UpToDateStatusType = {})); + function createFileMap(toPath) { + // tslint:disable-next-line:no-null-keyword + var lookup = ts.createMap(); + return { + setValue: setValue, + getValue: getValue, + removeKey: removeKey, + forEach: forEach, + hasKey: hasKey, + getSize: getSize, + clear: clear + }; + function forEach(action) { + lookup.forEach(action); + } + function hasKey(fileName) { + return lookup.has(toPath(fileName)); + } + function removeKey(fileName) { + lookup.delete(toPath(fileName)); + } + function setValue(fileName, value) { + lookup.set(toPath(fileName), value); + } + function getValue(fileName) { + return lookup.get(toPath(fileName)); + } + function getSize() { + return lookup.size; + } + function clear() { + lookup.clear(); + } + } + function getOrCreateValueFromConfigFileMap(configFileMap, resolved, createT) { + var existingValue = configFileMap.getValue(resolved); + var newValue; + if (!existingValue) { + newValue = createT(); + configFileMap.setValue(resolved, newValue); + } + return existingValue || newValue; + } + function getOrCreateValueMapFromConfigFileMap(configFileMap, resolved) { + return getOrCreateValueFromConfigFileMap(configFileMap, resolved, ts.createMap); + } + function getOutputDeclarationFileName(inputFileName, configFile) { + var relativePath = ts.getRelativePathFromDirectory(rootDirOfOptions(configFile.options, configFile.options.configFilePath), inputFileName, /*ignoreCase*/ true); + var outputPath = ts.resolvePath(configFile.options.declarationDir || configFile.options.outDir || ts.getDirectoryPath(configFile.options.configFilePath), relativePath); + return ts.changeExtension(outputPath, ".d.ts" /* Dts */); + } + ts.getOutputDeclarationFileName = getOutputDeclarationFileName; + function getOutputJSFileName(inputFileName, configFile) { + var relativePath = ts.getRelativePathFromDirectory(rootDirOfOptions(configFile.options, configFile.options.configFilePath), inputFileName, /*ignoreCase*/ true); + var outputPath = ts.resolvePath(configFile.options.outDir || ts.getDirectoryPath(configFile.options.configFilePath), relativePath); + var newExtension = ts.fileExtensionIs(inputFileName, ".json" /* Json */) ? ".json" /* Json */ : + ts.fileExtensionIs(inputFileName, ".tsx" /* Tsx */) && configFile.options.jsx === 1 /* Preserve */ ? ".jsx" /* Jsx */ : ".js" /* Js */; + return ts.changeExtension(outputPath, newExtension); + } + function getOutputFileNames(inputFileName, configFile) { + // outFile is handled elsewhere; .d.ts files don't generate outputs + if (configFile.options.outFile || configFile.options.out || ts.fileExtensionIs(inputFileName, ".d.ts" /* Dts */)) { + return ts.emptyArray; + } + var outputs = []; + var js = getOutputJSFileName(inputFileName, configFile); + outputs.push(js); + if (configFile.options.sourceMap) { + outputs.push(js + ".map"); + } + if (ts.getEmitDeclarations(configFile.options) && !ts.fileExtensionIs(inputFileName, ".json" /* Json */)) { + var dts = getOutputDeclarationFileName(inputFileName, configFile); + outputs.push(dts); + if (configFile.options.declarationMap) { + outputs.push(dts + ".map"); + } + } + return outputs; + } + function getOutFileOutputs(project) { + var out = project.options.outFile || project.options.out; + if (!out) { + return ts.Debug.fail("outFile must be set"); + } + var outputs = []; + outputs.push(out); + if (project.options.sourceMap) { + outputs.push(out + ".map"); + } + if (ts.getEmitDeclarations(project.options)) { + var dts = ts.changeExtension(out, ".d.ts" /* Dts */); + outputs.push(dts); + if (project.options.declarationMap) { + outputs.push(dts + ".map"); + } + } + return outputs; + } + function rootDirOfOptions(opts, configFileName) { + return opts.rootDir || ts.getDirectoryPath(configFileName); + } + function newer(date1, date2) { + return date2 > date1 ? date2 : date1; + } + function isDeclarationFile(fileName) { + return ts.fileExtensionIs(fileName, ".d.ts" /* Dts */); + } + /** + * Create a function that reports watch status by writing to the system and handles the formating of the diagnostic + */ + function createBuilderStatusReporter(system, pretty) { + return function (diagnostic) { + var output = pretty ? "[" + ts.formatColorAndReset(new Date().toLocaleTimeString(), ts.ForegroundColorEscapeSequences.Grey) + "] " : new Date().toLocaleTimeString() + " - "; + output += "" + ts.flattenDiagnosticMessageText(diagnostic.messageText, system.newLine) + (system.newLine + system.newLine); + system.write(output); + }; + } + ts.createBuilderStatusReporter = createBuilderStatusReporter; + function createSolutionBuilderHostBase(system, reportDiagnostic, reportSolutionBuilderStatus) { + if (system === void 0) { system = ts.sys; } + var host = ts.createCompilerHostWorker({}, /*setParentNodes*/ undefined, system); + host.getModifiedTime = system.getModifiedTime ? function (path) { return system.getModifiedTime(path); } : function () { return undefined; }; + host.setModifiedTime = system.setModifiedTime ? function (path, date) { return system.setModifiedTime(path, date); } : ts.noop; + host.deleteFile = system.deleteFile ? function (path) { return system.deleteFile(path); } : ts.noop; + host.reportDiagnostic = reportDiagnostic || ts.createDiagnosticReporter(system); + host.reportSolutionBuilderStatus = reportSolutionBuilderStatus || createBuilderStatusReporter(system); + return host; + } + function createSolutionBuilderHost(system, reportDiagnostic, reportSolutionBuilderStatus, reportErrorSummary) { + if (system === void 0) { system = ts.sys; } + var host = createSolutionBuilderHostBase(system, reportDiagnostic, reportSolutionBuilderStatus); + host.reportErrorSummary = reportErrorSummary; + return host; + } + ts.createSolutionBuilderHost = createSolutionBuilderHost; + function createSolutionBuilderWithWatchHost(system, reportDiagnostic, reportSolutionBuilderStatus, reportWatchStatus) { + var host = createSolutionBuilderHostBase(system, reportDiagnostic, reportSolutionBuilderStatus); + var watchHost = ts.createWatchHost(system, reportWatchStatus); + host.onWatchStatusChange = watchHost.onWatchStatusChange; + host.watchFile = watchHost.watchFile; + host.watchDirectory = watchHost.watchDirectory; + host.setTimeout = watchHost.setTimeout; + host.clearTimeout = watchHost.clearTimeout; + return host; + } + ts.createSolutionBuilderWithWatchHost = createSolutionBuilderWithWatchHost; + function getCompilerOptionsOfBuildOptions(buildOptions) { + var result = {}; + ts.commonOptionsWithBuild.forEach(function (option) { + result[option.name] = buildOptions[option.name]; + }); + return result; + } + function createSolutionBuilder(host, rootNames, defaultOptions) { + var hostWithWatch = host; + var currentDirectory = host.getCurrentDirectory(); + var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames()); + var parseConfigFileHost = ts.parseConfigHostFromCompilerHost(host); + // State of the solution + var options = defaultOptions; + var baseCompilerOptions = getCompilerOptionsOfBuildOptions(options); + var configFileCache = createFileMap(toPath); + /** Map from output file name to its pre-build timestamp */ + var unchangedOutputs = createFileMap(toPath); + /** Map from config file name to up-to-date status */ + var projectStatus = createFileMap(toPath); + var missingRoots = ts.createMap(); + var globalDependencyGraph; + var writeFileName = function (s) { return host.trace && host.trace(s); }; + var readFileWithCache = function (f) { return host.readFile(f); }; + // Watch state + var diagnostics = createFileMap(toPath); + var projectPendingBuild = createFileMap(toPath); + var projectErrorsReported = createFileMap(toPath); + var invalidatedProjectQueue = []; + var nextProjectToBuild = 0; + var timerToBuildInvalidatedProject; + var reportFileChangeDetected = false; + // Watches for the solution + var allWatchedWildcardDirectories = createFileMap(toPath); + var allWatchedInputFiles = createFileMap(toPath); + var allWatchedConfigFiles = createFileMap(toPath); + return { + buildAllProjects: buildAllProjects, + getUpToDateStatusOfFile: getUpToDateStatusOfFile, + cleanAllProjects: cleanAllProjects, + resetBuildContext: resetBuildContext, + getBuildGraph: getBuildGraph, + invalidateProject: invalidateProject, + buildInvalidatedProject: buildInvalidatedProject, + resolveProjectName: resolveProjectName, + startWatching: startWatching + }; + function toPath(fileName) { + return ts.toPath(fileName, currentDirectory, getCanonicalFileName); + } + function resetBuildContext(opts) { + if (opts === void 0) { opts = defaultOptions; } + options = opts; + baseCompilerOptions = getCompilerOptionsOfBuildOptions(options); + configFileCache.clear(); + unchangedOutputs.clear(); + projectStatus.clear(); + missingRoots.clear(); + globalDependencyGraph = undefined; + diagnostics.clear(); + projectPendingBuild.clear(); + projectErrorsReported.clear(); + invalidatedProjectQueue.length = 0; + nextProjectToBuild = 0; + if (timerToBuildInvalidatedProject) { + clearTimeout(timerToBuildInvalidatedProject); + timerToBuildInvalidatedProject = undefined; + } + reportFileChangeDetected = false; + ts.clearMap(allWatchedWildcardDirectories, function (wildCardWatches) { return ts.clearMap(wildCardWatches, ts.closeFileWatcherOf); }); + ts.clearMap(allWatchedInputFiles, function (inputFileWatches) { return ts.clearMap(inputFileWatches, ts.closeFileWatcher); }); + ts.clearMap(allWatchedConfigFiles, ts.closeFileWatcher); + } + function isParsedCommandLine(entry) { + return !!entry.options; + } + function parseConfigFile(configFilePath) { + var value = configFileCache.getValue(configFilePath); + if (value) { + return isParsedCommandLine(value) ? value : undefined; + } + var diagnostic; + parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = function (d) { return diagnostic = d; }; + var parsed = ts.getParsedCommandLineOfConfigFile(configFilePath, baseCompilerOptions, parseConfigFileHost); + parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = ts.noop; + configFileCache.setValue(configFilePath, parsed || diagnostic); + return parsed; + } + function reportStatus(message) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + host.reportSolutionBuilderStatus(ts.createCompilerDiagnostic.apply(void 0, [message].concat(args))); + } + function reportWatchStatus(message) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + if (hostWithWatch.onWatchStatusChange) { + hostWithWatch.onWatchStatusChange(ts.createCompilerDiagnostic.apply(void 0, [message].concat(args)), host.getNewLine(), baseCompilerOptions); + } + } + function startWatching() { + var graph = getGlobalDependencyGraph(); + for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { + var resolved = _a[_i]; + // Watch this file + watchConfigFile(resolved); + var cfg = parseConfigFile(resolved); + if (cfg) { + // Update watchers for wildcard directories + watchWildCardDirectories(resolved, cfg); + // Watch input files + watchInputFiles(resolved, cfg); + } + } + } + function watchConfigFile(resolved) { + if (options.watch && !allWatchedConfigFiles.hasKey(resolved)) { + allWatchedConfigFiles.setValue(resolved, hostWithWatch.watchFile(resolved, function () { + invalidateProjectAndScheduleBuilds(resolved, ts.ConfigFileProgramReloadLevel.Full); + })); + } + } + function watchWildCardDirectories(resolved, parsed) { + if (!options.watch) + return; + ts.updateWatchingWildcardDirectories(getOrCreateValueMapFromConfigFileMap(allWatchedWildcardDirectories, resolved), ts.createMapFromTemplate(parsed.configFileSpecs.wildcardDirectories), function (dir, flags) { + return hostWithWatch.watchDirectory(dir, function (fileOrDirectory) { + var fileOrDirectoryPath = toPath(fileOrDirectory); + if (fileOrDirectoryPath !== toPath(dir) && ts.hasExtension(fileOrDirectoryPath) && !ts.isSupportedSourceFileName(fileOrDirectory, parsed.options)) { + // writeLog(`Project: ${configFileName} Detected file add/remove of non supported extension: ${fileOrDirectory}`); + return; + } + if (isOutputFile(fileOrDirectory, parsed)) { + // writeLog(`${fileOrDirectory} is output file`); + return; + } + invalidateProjectAndScheduleBuilds(resolved, ts.ConfigFileProgramReloadLevel.Partial); + }, !!(flags & 1 /* Recursive */)); + }); + } + function watchInputFiles(resolved, parsed) { + if (!options.watch) + return; + ts.mutateMap(getOrCreateValueMapFromConfigFileMap(allWatchedInputFiles, resolved), ts.arrayToMap(parsed.fileNames, toPath), { + createNewValue: function (_key, input) { return hostWithWatch.watchFile(input, function () { + invalidateProjectAndScheduleBuilds(resolved, ts.ConfigFileProgramReloadLevel.None); + }); }, + onDeleteValue: ts.closeFileWatcher, + }); + } + function isOutputFile(fileName, configFile) { + if (configFile.options.noEmit) + return false; + // ts or tsx files are not output + if (!ts.fileExtensionIs(fileName, ".d.ts" /* Dts */) && + (ts.fileExtensionIs(fileName, ".ts" /* Ts */) || ts.fileExtensionIs(fileName, ".tsx" /* Tsx */))) { + return false; + } + // If options have --outFile or --out, check if its that + var out = configFile.options.outFile || configFile.options.out; + if (out && (isSameFile(fileName, out) || isSameFile(fileName, ts.removeFileExtension(out) + ".d.ts" /* Dts */))) { + return true; + } + // If declarationDir is specified, return if its a file in that directory + if (configFile.options.declarationDir && ts.containsPath(configFile.options.declarationDir, fileName, currentDirectory, !host.useCaseSensitiveFileNames())) { + return true; + } + // If --outDir, check if file is in that directory + if (configFile.options.outDir && ts.containsPath(configFile.options.outDir, fileName, currentDirectory, !host.useCaseSensitiveFileNames())) { + return true; + } + return !ts.forEach(configFile.fileNames, function (inputFile) { return isSameFile(fileName, inputFile); }); + } + function isSameFile(file1, file2) { + return ts.comparePaths(file1, file2, currentDirectory, !host.useCaseSensitiveFileNames()) === 0 /* EqualTo */; + } + function invalidateProjectAndScheduleBuilds(resolved, reloadLevel) { + reportFileChangeDetected = true; + invalidateResolvedProject(resolved, reloadLevel); + scheduleBuildInvalidatedProject(); + } + function getUpToDateStatusOfFile(configFileName) { + return getUpToDateStatus(parseConfigFile(configFileName)); + } + function getBuildGraph(configFileNames) { + return createDependencyGraph(resolveProjectNames(configFileNames)); + } + function getGlobalDependencyGraph() { + return globalDependencyGraph || (globalDependencyGraph = getBuildGraph(rootNames)); + } + function getUpToDateStatus(project) { + if (project === undefined) { + return { type: UpToDateStatusType.Unbuildable, reason: "File deleted mid-build" }; + } + var prior = projectStatus.getValue(project.options.configFilePath); + if (prior !== undefined) { + return prior; + } + var actual = getUpToDateStatusWorker(project); + projectStatus.setValue(project.options.configFilePath, actual); + return actual; + } + function getUpToDateStatusWorker(project) { + var newestInputFileName = undefined; + var newestInputFileTime = minimumDate; + // Get timestamps of input files + for (var _i = 0, _a = project.fileNames; _i < _a.length; _i++) { + var inputFile = _a[_i]; + if (!host.fileExists(inputFile)) { + return { + type: UpToDateStatusType.Unbuildable, + reason: inputFile + " does not exist" + }; + } + var inputTime = host.getModifiedTime(inputFile) || ts.missingFileModifiedTime; + if (inputTime > newestInputFileTime) { + newestInputFileName = inputFile; + newestInputFileTime = inputTime; + } + } + // Collect the expected outputs of this project + var outputs = getAllProjectOutputs(project); + if (outputs.length === 0) { + return { + type: UpToDateStatusType.ContainerOnly + }; + } + // Now see if all outputs are newer than the newest input + var oldestOutputFileName = "(none)"; + var oldestOutputFileTime = maximumDate; + var newestOutputFileName = "(none)"; + var newestOutputFileTime = minimumDate; + var missingOutputFileName; + var newestDeclarationFileContentChangedTime = minimumDate; + var isOutOfDateWithInputs = false; + for (var _b = 0, outputs_1 = outputs; _b < outputs_1.length; _b++) { + var output = outputs_1[_b]; + // Output is missing; can stop checking + // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status + if (!host.fileExists(output)) { + missingOutputFileName = output; + break; + } + var outputTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; + if (outputTime < oldestOutputFileTime) { + oldestOutputFileTime = outputTime; + oldestOutputFileName = output; + } + // If an output is older than the newest input, we can stop checking + // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status + if (outputTime < newestInputFileTime) { + isOutOfDateWithInputs = true; + break; + } + if (outputTime > newestOutputFileTime) { + newestOutputFileTime = outputTime; + newestOutputFileName = output; + } + // Keep track of when the most recent time a .d.ts file was changed. + // In addition to file timestamps, we also keep track of when a .d.ts file + // had its file touched but not had its contents changed - this allows us + // to skip a downstream typecheck + if (isDeclarationFile(output)) { + var unchangedTime = unchangedOutputs.getValue(output); + if (unchangedTime !== undefined) { + newestDeclarationFileContentChangedTime = newer(unchangedTime, newestDeclarationFileContentChangedTime); + } + else { + var outputModifiedTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; + newestDeclarationFileContentChangedTime = newer(newestDeclarationFileContentChangedTime, outputModifiedTime); + } + } + } + var pseudoUpToDate = false; + var usesPrepend = false; + var upstreamChangedProject; + if (project.projectReferences) { + projectStatus.setValue(project.options.configFilePath, { type: UpToDateStatusType.ComputingUpstream }); + for (var _c = 0, _d = project.projectReferences; _c < _d.length; _c++) { + var ref = _d[_c]; + usesPrepend = usesPrepend || !!(ref.prepend); + var resolvedRef = ts.resolveProjectReferencePath(ref); + var refStatus = getUpToDateStatus(parseConfigFile(resolvedRef)); + // Its a circular reference ignore the status of this project + if (refStatus.type === UpToDateStatusType.ComputingUpstream) { + continue; + } + // An upstream project is blocked + if (refStatus.type === UpToDateStatusType.Unbuildable) { + return { + type: UpToDateStatusType.UpstreamBlocked, + upstreamProjectName: ref.path + }; + } + // If the upstream project is out of date, then so are we (someone shouldn't have asked, though?) + if (refStatus.type !== UpToDateStatusType.UpToDate) { + return { + type: UpToDateStatusType.UpstreamOutOfDate, + upstreamProjectName: ref.path + }; + } + // If the upstream project's newest file is older than our oldest output, we + // can't be out of date because of it + if (refStatus.newestInputFileTime && refStatus.newestInputFileTime <= oldestOutputFileTime) { + continue; + } + // If the upstream project has only change .d.ts files, and we've built + // *after* those files, then we're "psuedo up to date" and eligible for a fast rebuild + if (refStatus.newestDeclarationFileContentChangedTime && refStatus.newestDeclarationFileContentChangedTime <= oldestOutputFileTime) { + pseudoUpToDate = true; + upstreamChangedProject = ref.path; + continue; + } + // We have an output older than an upstream output - we are out of date + ts.Debug.assert(oldestOutputFileName !== undefined, "Should have an oldest output filename here"); + return { + type: UpToDateStatusType.OutOfDateWithUpstream, + outOfDateOutputFileName: oldestOutputFileName, + newerProjectName: ref.path + }; + } + } + if (missingOutputFileName !== undefined) { + return { + type: UpToDateStatusType.OutputMissing, + missingOutputFileName: missingOutputFileName + }; + } + if (isOutOfDateWithInputs) { + return { + type: UpToDateStatusType.OutOfDateWithSelf, + outOfDateOutputFileName: oldestOutputFileName, + newerInputFileName: newestInputFileName + }; + } + if (usesPrepend && pseudoUpToDate) { + return { + type: UpToDateStatusType.OutOfDateWithUpstream, + outOfDateOutputFileName: oldestOutputFileName, + newerProjectName: upstreamChangedProject + }; + } + // Up to date + return { + type: pseudoUpToDate ? UpToDateStatusType.UpToDateWithUpstreamTypes : UpToDateStatusType.UpToDate, + newestDeclarationFileContentChangedTime: newestDeclarationFileContentChangedTime, + newestInputFileTime: newestInputFileTime, + newestOutputFileTime: newestOutputFileTime, + newestInputFileName: newestInputFileName, + newestOutputFileName: newestOutputFileName, + oldestOutputFileName: oldestOutputFileName + }; + } + function invalidateProject(configFileName, reloadLevel) { + invalidateResolvedProject(resolveProjectName(configFileName), reloadLevel); + } + function invalidateResolvedProject(resolved, reloadLevel) { + if (reloadLevel === ts.ConfigFileProgramReloadLevel.Full) { + configFileCache.removeKey(resolved); + globalDependencyGraph = undefined; + } + projectStatus.removeKey(resolved); + diagnostics.removeKey(resolved); + addProjToQueue(resolved, reloadLevel); + } + /** + * return true if new addition + */ + function addProjToQueue(proj, reloadLevel) { + var value = projectPendingBuild.getValue(proj); + if (value === undefined) { + projectPendingBuild.setValue(proj, reloadLevel || ts.ConfigFileProgramReloadLevel.None); + invalidatedProjectQueue.push(proj); + } + else if (value < (reloadLevel || ts.ConfigFileProgramReloadLevel.None)) { + projectPendingBuild.setValue(proj, reloadLevel || ts.ConfigFileProgramReloadLevel.None); + } + } + function getNextInvalidatedProject() { + if (nextProjectToBuild < invalidatedProjectQueue.length) { + var project = invalidatedProjectQueue[nextProjectToBuild]; + nextProjectToBuild++; + var reloadLevel = projectPendingBuild.getValue(project); + projectPendingBuild.removeKey(project); + if (!projectPendingBuild.getSize()) { + invalidatedProjectQueue.length = 0; + nextProjectToBuild = 0; + } + return { project: project, reloadLevel: reloadLevel }; + } + } + function hasPendingInvalidatedProjects() { + return !!projectPendingBuild.getSize(); + } + function scheduleBuildInvalidatedProject() { + if (!hostWithWatch.setTimeout || !hostWithWatch.clearTimeout) { + return; + } + if (timerToBuildInvalidatedProject) { + hostWithWatch.clearTimeout(timerToBuildInvalidatedProject); + } + timerToBuildInvalidatedProject = hostWithWatch.setTimeout(buildInvalidatedProject, 250); + } + function buildInvalidatedProject() { + timerToBuildInvalidatedProject = undefined; + if (reportFileChangeDetected) { + reportFileChangeDetected = false; + projectErrorsReported.clear(); + reportWatchStatus(ts.Diagnostics.File_change_detected_Starting_incremental_compilation); + } + var buildProject = getNextInvalidatedProject(); + if (buildProject) { + buildSingleInvalidatedProject(buildProject.project, buildProject.reloadLevel); + if (hasPendingInvalidatedProjects()) { + if (options.watch && !timerToBuildInvalidatedProject) { + scheduleBuildInvalidatedProject(); + } + } + else { + reportErrorSummary(); + } + } + } + function reportErrorSummary() { + if (options.watch || host.reportErrorSummary) { + // Report errors from the other projects + getGlobalDependencyGraph().buildQueue.forEach(function (project) { + if (!projectErrorsReported.hasKey(project)) { + reportErrors(diagnostics.getValue(project) || ts.emptyArray); + } + }); + var totalErrors_1 = 0; + diagnostics.forEach(function (singleProjectErrors) { return totalErrors_1 += ts.getErrorCountForSummary(singleProjectErrors); }); + if (options.watch) { + reportWatchStatus(ts.getWatchErrorSummaryDiagnosticMessage(totalErrors_1), totalErrors_1); + } + else { + host.reportErrorSummary(totalErrors_1); + } + } + } + function buildSingleInvalidatedProject(resolved, reloadLevel) { + var proj = parseConfigFile(resolved); + if (!proj) { + reportParseConfigFileDiagnostic(resolved); + return; + } + if (reloadLevel === ts.ConfigFileProgramReloadLevel.Full) { + watchConfigFile(resolved); + watchWildCardDirectories(resolved, proj); + watchInputFiles(resolved, proj); + } + else if (reloadLevel === ts.ConfigFileProgramReloadLevel.Partial) { + // Update file names + var result = ts.getFileNamesFromConfigSpecs(proj.configFileSpecs, ts.getDirectoryPath(resolved), proj.options, parseConfigFileHost); + ts.updateErrorForNoInputFiles(result, resolved, proj.configFileSpecs, proj.errors, ts.canJsonReportNoInutFiles(proj.raw)); + proj.fileNames = result.fileNames; + watchInputFiles(resolved, proj); + } + var status = getUpToDateStatus(proj); + verboseReportProjectStatus(resolved, status); + if (status.type === UpToDateStatusType.UpstreamBlocked) { + if (options.verbose) + reportStatus(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, resolved, status.upstreamProjectName); + return; + } + var buildResult = buildSingleProject(resolved); + var dependencyGraph = getGlobalDependencyGraph(); + var referencingProjects = dependencyGraph.referencingProjectsMap.getValue(resolved); + if (!referencingProjects) + return; + // Always use build order to queue projects + for (var _i = 0, _a = dependencyGraph.buildQueue; _i < _a.length; _i++) { + var project = _a[_i]; + var prepend = referencingProjects.getValue(project); + // If the project is referenced with prepend, always build downstream projectm, + // otherwise queue it only if declaration output changed + if (prepend || (prepend !== undefined && !(buildResult & BuildResultFlags.DeclarationOutputUnchanged))) { + addProjToQueue(project); + } + } + } + function createDependencyGraph(roots) { + var temporaryMarks = createFileMap(toPath); + var permanentMarks = createFileMap(toPath); + var circularityReportStack = []; + var buildOrder = []; + var referencingProjectsMap = createFileMap(toPath); + for (var _i = 0, roots_1 = roots; _i < roots_1.length; _i++) { + var root = roots_1[_i]; + visit(root); + } + return { + buildQueue: buildOrder, + referencingProjectsMap: referencingProjectsMap + }; + function visit(projPath, inCircularContext) { + // Already visited + if (permanentMarks.hasKey(projPath)) + return; + // Circular + if (temporaryMarks.hasKey(projPath)) { + if (!inCircularContext) { + // TODO:: Do we report this as error? + reportStatus(ts.Diagnostics.Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0, circularityReportStack.join("\r\n")); + } + return; + } + temporaryMarks.setValue(projPath, true); + circularityReportStack.push(projPath); + var parsed = parseConfigFile(projPath); + if (parsed && parsed.projectReferences) { + for (var _i = 0, _a = parsed.projectReferences; _i < _a.length; _i++) { + var ref = _a[_i]; + var resolvedRefPath = resolveProjectName(ref.path); + visit(resolvedRefPath, inCircularContext || ref.circular); + // Get projects referencing resolvedRefPath and add projPath to it + var referencingProjects = getOrCreateValueFromConfigFileMap(referencingProjectsMap, resolvedRefPath, function () { return createFileMap(toPath); }); + referencingProjects.setValue(projPath, !!ref.prepend); + } + } + circularityReportStack.pop(); + permanentMarks.setValue(projPath, true); + buildOrder.push(projPath); + } + } + function buildSingleProject(proj) { + if (options.dry) { + reportStatus(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj); + return BuildResultFlags.Success; + } + if (options.verbose) + reportStatus(ts.Diagnostics.Building_project_0, proj); + var resultFlags = BuildResultFlags.None; + resultFlags |= BuildResultFlags.DeclarationOutputUnchanged; + var configFile = parseConfigFile(proj); + if (!configFile) { + // Failed to read the config file + resultFlags |= BuildResultFlags.ConfigFileErrors; + reportParseConfigFileDiagnostic(proj); + projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Config file errors" }); + return resultFlags; + } + if (configFile.fileNames.length === 0) { + reportAndStoreErrors(proj, configFile.errors); + // Nothing to build - must be a solution file, basically + return BuildResultFlags.None; + } + var programOptions = { + projectReferences: configFile.projectReferences, + host: host, + rootNames: configFile.fileNames, + options: configFile.options, + configFileParsingDiagnostics: configFile.errors + }; + if (host.beforeCreateProgram) { + host.beforeCreateProgram(options); + } + var program = ts.createProgram(programOptions); + // Don't emit anything in the presence of syntactic errors or options diagnostics + var syntaxDiagnostics = program.getOptionsDiagnostics().concat(program.getConfigFileParsingDiagnostics(), program.getSyntacticDiagnostics()); + if (syntaxDiagnostics.length) { + return buildErrors(syntaxDiagnostics, BuildResultFlags.SyntaxErrors, "Syntactic"); + } + // Same as above but now for semantic diagnostics + var semanticDiagnostics = program.getSemanticDiagnostics(); + if (semanticDiagnostics.length) { + return buildErrors(semanticDiagnostics, BuildResultFlags.TypeErrors, "Semantic"); + } + var newestDeclarationFileContentChangedTime = minimumDate; + var anyDtsChanged = false; + var declDiagnostics; + var reportDeclarationDiagnostics = function (d) { return (declDiagnostics || (declDiagnostics = [])).push(d); }; + var outputFiles = []; + ts.emitFilesAndReportErrors(program, reportDeclarationDiagnostics, writeFileName, /*reportSummary*/ undefined, function (name, text, writeByteOrderMark) { return outputFiles.push({ name: name, text: text, writeByteOrderMark: writeByteOrderMark }); }); + // Don't emit .d.ts if there are decl file errors + if (declDiagnostics) { + return buildErrors(declDiagnostics, BuildResultFlags.DeclarationEmitErrors, "Declaration file"); + } + // Actual Emit + var emitterDiagnostics = ts.createDiagnosticCollection(); + outputFiles.forEach(function (_a) { + var name = _a.name, text = _a.text, writeByteOrderMark = _a.writeByteOrderMark; + var priorChangeTime; + if (!anyDtsChanged && isDeclarationFile(name)) { + // Check for unchanged .d.ts files + if (host.fileExists(name) && readFileWithCache(name) === text) { + priorChangeTime = host.getModifiedTime(name); + } + else { + resultFlags &= ~BuildResultFlags.DeclarationOutputUnchanged; + anyDtsChanged = true; + } + } + ts.writeFile(host, emitterDiagnostics, name, text, writeByteOrderMark); + if (priorChangeTime !== undefined) { + newestDeclarationFileContentChangedTime = newer(priorChangeTime, newestDeclarationFileContentChangedTime); + unchangedOutputs.setValue(name, priorChangeTime); + } + }); + var emitDiagnostics = emitterDiagnostics.getDiagnostics(); + if (emitDiagnostics.length) { + return buildErrors(emitDiagnostics, BuildResultFlags.EmitErrors, "Emit"); + } + var status = { + type: UpToDateStatusType.UpToDate, + newestDeclarationFileContentChangedTime: anyDtsChanged ? maximumDate : newestDeclarationFileContentChangedTime + }; + diagnostics.removeKey(proj); + projectStatus.setValue(proj, status); + if (host.afterProgramEmitAndDiagnostics) { + host.afterProgramEmitAndDiagnostics(program); + } + return resultFlags; + function buildErrors(diagnostics, errorFlags, errorType) { + resultFlags |= errorFlags; + reportAndStoreErrors(proj, diagnostics); + projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: errorType + " errors" }); + if (host.afterProgramEmitAndDiagnostics) { + host.afterProgramEmitAndDiagnostics(program); + } + return resultFlags; + } + } + function updateOutputTimestamps(proj) { + if (options.dry) { + return reportStatus(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj.options.configFilePath); + } + if (options.verbose) { + reportStatus(ts.Diagnostics.Updating_output_timestamps_of_project_0, proj.options.configFilePath); + } + var now = new Date(); + var outputs = getAllProjectOutputs(proj); + var priorNewestUpdateTime = minimumDate; + for (var _i = 0, outputs_2 = outputs; _i < outputs_2.length; _i++) { + var file = outputs_2[_i]; + if (isDeclarationFile(file)) { + priorNewestUpdateTime = newer(priorNewestUpdateTime, host.getModifiedTime(file) || ts.missingFileModifiedTime); + } + host.setModifiedTime(file, now); + } + projectStatus.setValue(proj.options.configFilePath, { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: priorNewestUpdateTime }); + } + function getFilesToClean() { + // Get the same graph for cleaning we'd use for building + var graph = getGlobalDependencyGraph(); + var filesToDelete = []; + for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { + var proj = _a[_i]; + var parsed = parseConfigFile(proj); + if (parsed === undefined) { + // File has gone missing; fine to ignore here + reportParseConfigFileDiagnostic(proj); + continue; + } + var outputs = getAllProjectOutputs(parsed); + for (var _b = 0, outputs_3 = outputs; _b < outputs_3.length; _b++) { + var output = outputs_3[_b]; + if (host.fileExists(output)) { + filesToDelete.push(output); + } + } + } + return filesToDelete; + } + function cleanAllProjects() { + var filesToDelete = getFilesToClean(); + if (options.dry) { + reportStatus(ts.Diagnostics.A_non_dry_build_would_delete_the_following_files_Colon_0, filesToDelete.map(function (f) { return "\r\n * " + f; }).join("")); + return ts.ExitStatus.Success; + } + for (var _i = 0, filesToDelete_1 = filesToDelete; _i < filesToDelete_1.length; _i++) { + var output = filesToDelete_1[_i]; + host.deleteFile(output); + } + return ts.ExitStatus.Success; + } + function resolveProjectName(name) { + return resolveConfigFileProjectName(ts.resolvePath(host.getCurrentDirectory(), name)); + } + function resolveProjectNames(configFileNames) { + return configFileNames.map(resolveProjectName); + } + function buildAllProjects() { + if (options.watch) { + reportWatchStatus(ts.Diagnostics.Starting_compilation_in_watch_mode); + } + // TODO:: In watch mode as well to use caches for incremental build once we can invalidate caches correctly and have right api + // Override readFile for json files and output .d.ts to cache the text + var _a = ts.changeCompilerHostToUseCache(host, toPath, /*useCacheForSourceFile*/ true), originalReadFile = _a.originalReadFile, originalFileExists = _a.originalFileExists, originalDirectoryExists = _a.originalDirectoryExists, originalCreateDirectory = _a.originalCreateDirectory, originalWriteFile = _a.originalWriteFile, originalGetSourceFile = _a.originalGetSourceFile, newReadFileWithCache = _a.readFileWithCache; + var savedReadFileWithCache = readFileWithCache; + readFileWithCache = newReadFileWithCache; + var graph = getGlobalDependencyGraph(); + reportBuildQueue(graph); + var anyFailed = false; + for (var _i = 0, _b = graph.buildQueue; _i < _b.length; _i++) { + var next = _b[_i]; + var proj = parseConfigFile(next); + if (proj === undefined) { + reportParseConfigFileDiagnostic(next); + anyFailed = true; + break; + } + // report errors early when using continue or break statements + var errors = proj.errors; + var status = getUpToDateStatus(proj); + verboseReportProjectStatus(next, status); + var projName = proj.options.configFilePath; + if (status.type === UpToDateStatusType.UpToDate && !options.force) { + reportAndStoreErrors(next, errors); + // Up to date, skip + if (defaultOptions.dry) { + // In a dry build, inform the user of this fact + reportStatus(ts.Diagnostics.Project_0_is_up_to_date, projName); + } + continue; + } + if (status.type === UpToDateStatusType.UpToDateWithUpstreamTypes && !options.force) { + reportAndStoreErrors(next, errors); + // Fake build + updateOutputTimestamps(proj); + continue; + } + if (status.type === UpToDateStatusType.UpstreamBlocked) { + reportAndStoreErrors(next, errors); + if (options.verbose) + reportStatus(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, projName, status.upstreamProjectName); + continue; + } + if (status.type === UpToDateStatusType.ContainerOnly) { + reportAndStoreErrors(next, errors); + // Do nothing + continue; + } + var buildResult = buildSingleProject(next); + anyFailed = anyFailed || !!(buildResult & BuildResultFlags.AnyErrors); + } + reportErrorSummary(); + host.readFile = originalReadFile; + host.fileExists = originalFileExists; + host.directoryExists = originalDirectoryExists; + host.createDirectory = originalCreateDirectory; + host.writeFile = originalWriteFile; + readFileWithCache = savedReadFileWithCache; + host.getSourceFile = originalGetSourceFile; + return anyFailed ? ts.ExitStatus.DiagnosticsPresent_OutputsSkipped : ts.ExitStatus.Success; + } + function reportParseConfigFileDiagnostic(proj) { + reportAndStoreErrors(proj, [configFileCache.getValue(proj)]); + } + function reportAndStoreErrors(proj, errors) { + reportErrors(errors); + projectErrorsReported.setValue(proj, true); + diagnostics.setValue(proj, errors); + } + function reportErrors(errors) { + errors.forEach(function (err) { return host.reportDiagnostic(err); }); + } + /** + * Report the build ordering inferred from the current project graph if we're in verbose mode + */ + function reportBuildQueue(graph) { + if (options.verbose) { + reportStatus(ts.Diagnostics.Projects_in_this_build_Colon_0, graph.buildQueue.map(function (s) { return "\r\n * " + relName(s); }).join("")); + } + } + function relName(path) { + return ts.convertToRelativePath(path, host.getCurrentDirectory(), function (f) { return host.getCanonicalFileName(f); }); + } + /** + * Report the up-to-date status of a project if we're in verbose mode + */ + function verboseReportProjectStatus(configFileName, status) { + if (!options.verbose) + return; + return formatUpToDateStatus(configFileName, status, relName, reportStatus); + } + } + ts.createSolutionBuilder = createSolutionBuilder; + function resolveConfigFileProjectName(project) { + if (ts.fileExtensionIs(project, ".json" /* Json */)) { + return project; + } + return ts.combinePaths(project, "tsconfig.json"); + } + ts.resolveConfigFileProjectName = resolveConfigFileProjectName; + function getAllProjectOutputs(project) { + if (project.options.outFile || project.options.out) { + return getOutFileOutputs(project); + } + else { + var outputs = []; + for (var _i = 0, _a = project.fileNames; _i < _a.length; _i++) { + var inputFile = _a[_i]; + outputs.push.apply(outputs, getOutputFileNames(inputFile, project)); + } + return outputs; + } + } + ts.getAllProjectOutputs = getAllProjectOutputs; + function formatUpToDateStatus(configFileName, status, relName, formatMessage) { + switch (status.type) { + case UpToDateStatusType.OutOfDateWithSelf: + return formatMessage(ts.Diagnostics.Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2, relName(configFileName), relName(status.outOfDateOutputFileName), relName(status.newerInputFileName)); + case UpToDateStatusType.OutOfDateWithUpstream: + return formatMessage(ts.Diagnostics.Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2, relName(configFileName), relName(status.outOfDateOutputFileName), relName(status.newerProjectName)); + case UpToDateStatusType.OutputMissing: + return formatMessage(ts.Diagnostics.Project_0_is_out_of_date_because_output_file_1_does_not_exist, relName(configFileName), relName(status.missingOutputFileName)); + case UpToDateStatusType.UpToDate: + if (status.newestInputFileTime !== undefined) { + return formatMessage(ts.Diagnostics.Project_0_is_up_to_date_because_newest_input_1_is_older_than_oldest_output_2, relName(configFileName), relName(status.newestInputFileName || ""), relName(status.oldestOutputFileName || "")); + } + // Don't report anything for "up to date because it was already built" -- too verbose + break; + case UpToDateStatusType.UpToDateWithUpstreamTypes: + return formatMessage(ts.Diagnostics.Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies, relName(configFileName)); + case UpToDateStatusType.UpstreamOutOfDate: + return formatMessage(ts.Diagnostics.Project_0_is_out_of_date_because_its_dependency_1_is_out_of_date, relName(configFileName), relName(status.upstreamProjectName)); + case UpToDateStatusType.UpstreamBlocked: + return formatMessage(ts.Diagnostics.Project_0_can_t_be_built_because_its_dependency_1_has_errors, relName(configFileName), relName(status.upstreamProjectName)); + case UpToDateStatusType.Unbuildable: + return formatMessage(ts.Diagnostics.Failed_to_parse_file_0_Colon_1, relName(configFileName), status.reason); + case UpToDateStatusType.ContainerOnly: + // Don't report status on "solution" projects + case UpToDateStatusType.ComputingUpstream: + // Should never leak from getUptoDateStatusWorker + break; + default: + ts.assertType(status); + } + } + ts.formatUpToDateStatus = formatUpToDateStatus; +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var ValueKind; + (function (ValueKind) { + ValueKind[ValueKind["Const"] = 0] = "Const"; + ValueKind[ValueKind["Array"] = 1] = "Array"; + ValueKind[ValueKind["FunctionOrClass"] = 2] = "FunctionOrClass"; + ValueKind[ValueKind["Object"] = 3] = "Object"; + })(ValueKind = ts.ValueKind || (ts.ValueKind = {})); + function inspectModule(fileNameToRequire) { + return inspectValue(ts.removeFileExtension(ts.getBaseFileName(fileNameToRequire)), tryRequire(fileNameToRequire)); + } + ts.inspectModule = inspectModule; + function inspectValue(name, value) { + return getValueInfo(name, value, getRecurser()); + } + ts.inspectValue = inspectValue; + function getRecurser() { + var seen = new Set(); + var nameStack = []; + return function (obj, name, cbOk, cbFail) { + if (seen.has(obj) || nameStack.length > 4) { + return cbFail(seen.has(obj), nameStack); + } + seen.add(obj); + nameStack.push(name); + var res = cbOk(); + nameStack.pop(); + seen.delete(obj); + return res; + }; + } + function getValueInfo(name, value, recurser) { + return recurser(value, name, function () { + if (typeof value === "function") + return getFunctionOrClassInfo(value, name, recurser); + if (typeof value === "object") { + var builtin = getBuiltinType(name, value, recurser); + if (builtin !== undefined) + return builtin; + var entries = getEntriesOfObject(value); + var hasNontrivialPrototype = Object.getPrototypeOf(value) !== Object.prototype; + var members = ts.flatMap(entries, function (_a) { + var key = _a.key, value = _a.value; + return getValueInfo(key, value, recurser); + }); + return { kind: 3 /* Object */, name: name, hasNontrivialPrototype: hasNontrivialPrototype, members: members }; + } + return { kind: 0 /* Const */, name: name, typeName: isNullOrUndefined(value) ? "any" : typeof value }; + }, function (isCircularReference, keyStack) { return anyValue(name, " " + (isCircularReference ? "Circular reference" : "Too-deep object hierarchy") + " from " + keyStack.join(".")); }); + } + function getFunctionOrClassInfo(fn, name, recurser) { + var prototypeMembers = getPrototypeMembers(fn, recurser); + var namespaceMembers = ts.flatMap(getEntriesOfObject(fn), function (_a) { + var key = _a.key, value = _a.value; + return getValueInfo(key, value, recurser); + }); + var toString = ts.cast(Function.prototype.toString.call(fn), ts.isString); + var source = ts.stringContains(toString, "{ [native code] }") ? getFunctionLength(fn) : toString; + return { kind: 2 /* FunctionOrClass */, name: name, source: source, namespaceMembers: namespaceMembers, prototypeMembers: prototypeMembers }; + } + var builtins = ts.memoize(function () { + var map = ts.createMap(); + for (var _i = 0, _a = getEntriesOfObject(global); _i < _a.length; _i++) { + var _b = _a[_i], key = _b.key, value = _b.value; + if (typeof value === "function" && typeof value.prototype === "object" && value !== Object) { + map.set(key, value); + } + } + return map; + }); + function getBuiltinType(name, value, recurser) { + return ts.isArray(value) + ? { name: name, kind: 1 /* Array */, inner: value.length && getValueInfo("element", ts.first(value), recurser) || anyValue(name) } + : ts.forEachEntry(builtins(), function (builtin, builtinName) { + return value instanceof builtin ? { kind: 0 /* Const */, name: name, typeName: builtinName } : undefined; + }); + } + function getPrototypeMembers(fn, recurser) { + var prototype = fn.prototype; + // tslint:disable-next-line no-unnecessary-type-assertion (TODO: update LKG and it will really be unnecessary) + return typeof prototype !== "object" || prototype === null ? ts.emptyArray : ts.mapDefined(getEntriesOfObject(prototype), function (_a) { + var key = _a.key, value = _a.value; + return key === "constructor" ? undefined : getValueInfo(key, value, recurser); + }); + } + var ignoredProperties = new Set(["arguments", "caller", "constructor", "eval", "super_"]); + var reservedFunctionProperties = new Set(Object.getOwnPropertyNames(ts.noop)); + function getEntriesOfObject(obj) { + var seen = ts.createMap(); + var entries = []; + var chain = obj; + while (!isNullOrUndefined(chain) && chain !== Object.prototype && chain !== Function.prototype) { + for (var _i = 0, _a = Object.getOwnPropertyNames(chain); _i < _a.length; _i++) { + var key = _a[_i]; + if (!isJsPrivate(key) && + !ignoredProperties.has(key) && + (typeof obj !== "function" || !reservedFunctionProperties.has(key)) && + // Don't add property from a higher prototype if it already exists in a lower one + ts.addToSeen(seen, key)) { + var value = safeGetPropertyOfObject(chain, key); + // Don't repeat "toString" that matches signature from Object.prototype + if (!(key === "toString" && typeof value === "function" && value.length === 0)) { + entries.push({ key: key, value: value }); + } + } + } + chain = Object.getPrototypeOf(chain); + } + return entries.sort(function (e1, e2) { return ts.compareStringsCaseSensitive(e1.key, e2.key); }); + } + function getFunctionLength(fn) { + return ts.tryCast(safeGetPropertyOfObject(fn, "length"), ts.isNumber) || 0; + } + function safeGetPropertyOfObject(obj, key) { + var desc = Object.getOwnPropertyDescriptor(obj, key); + return desc && desc.value; + } + function isNullOrUndefined(value) { + return value == null; // tslint:disable-line + } + function anyValue(name, comment) { + return { kind: 0 /* Const */, name: name, typeName: "any", comment: comment }; + } + function isJsPrivate(name) { + return name.startsWith("_"); + } + ts.isJsPrivate = isJsPrivate; + function tryRequire(fileNameToRequire) { + try { + return require(fileNameToRequire); + } + catch (_a) { + return undefined; + } + } +})(ts || (ts = {})); +//# sourceMappingURL=compiler.js.map +"use strict"; +/* @internal */ +var ts; +(function (ts) { + var server; + (function (server) { + // tslint:disable variable-name + server.ActionSet = "action::set"; + server.ActionInvalidate = "action::invalidate"; + server.ActionPackageInstalled = "action::packageInstalled"; + server.ActionValueInspected = "action::valueInspected"; + server.EventTypesRegistry = "event::typesRegistry"; + server.EventBeginInstallTypes = "event::beginInstallTypes"; + server.EventEndInstallTypes = "event::endInstallTypes"; + server.EventInitializationFailed = "event::initializationFailed"; + var Arguments; + (function (Arguments) { + Arguments.GlobalCacheLocation = "--globalTypingsCacheLocation"; + Arguments.LogFile = "--logFile"; + Arguments.EnableTelemetry = "--enableTelemetry"; + Arguments.TypingSafeListLocation = "--typingSafeListLocation"; + Arguments.TypesMapLocation = "--typesMapLocation"; + /** + * This argument specifies the location of the NPM executable. + * typingsInstaller will run the command with `${npmLocation} install ...`. + */ + Arguments.NpmLocation = "--npmLocation"; + })(Arguments = server.Arguments || (server.Arguments = {})); + function hasArgument(argumentName) { + return ts.sys.args.indexOf(argumentName) >= 0; + } + server.hasArgument = hasArgument; + function findArgument(argumentName) { + var index = ts.sys.args.indexOf(argumentName); + return index >= 0 && index < ts.sys.args.length - 1 + ? ts.sys.args[index + 1] + : undefined; + } + server.findArgument = findArgument; + function nowString() { + // E.g. "12:34:56.789" + var d = new Date(); + return d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds() + "." + d.getMilliseconds(); + } + server.nowString = nowString; + })(server = ts.server || (ts.server = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var JsTyping; + (function (JsTyping) { + function isTypingUpToDate(cachedTyping, availableTypingVersions) { + var availableVersion = new ts.Version(ts.getProperty(availableTypingVersions, "ts" + ts.versionMajorMinor) || ts.getProperty(availableTypingVersions, "latest")); + return availableVersion.compareTo(cachedTyping.version) <= 0; + } + JsTyping.isTypingUpToDate = isTypingUpToDate; + JsTyping.nodeCoreModuleList = [ + "assert", + "async_hooks", + "buffer", + "child_process", + "cluster", + "console", + "constants", + "crypto", + "dgram", + "dns", + "domain", + "events", + "fs", + "http", + "https", + "http2", + "inspector", + "net", + "os", + "path", + "perf_hooks", + "process", + "punycode", + "querystring", + "readline", + "repl", + "stream", + "string_decoder", + "timers", + "tls", + "tty", + "url", + "util", + "v8", + "vm", + "zlib" + ]; + JsTyping.nodeCoreModules = ts.arrayToSet(JsTyping.nodeCoreModuleList); + function loadSafeList(host, safeListPath) { + var result = ts.readConfigFile(safeListPath, function (path) { return host.readFile(path); }); + return ts.createMapFromTemplate(result.config); + } + JsTyping.loadSafeList = loadSafeList; + function loadTypesMap(host, typesMapPath) { + var result = ts.readConfigFile(typesMapPath, function (path) { return host.readFile(path); }); + if (result.config) { + return ts.createMapFromTemplate(result.config.simpleMap); + } + return undefined; + } + JsTyping.loadTypesMap = loadTypesMap; + /** + * @param host is the object providing I/O related operations. + * @param fileNames are the file names that belong to the same project + * @param projectRootPath is the path to the project root directory + * @param safeListPath is the path used to retrieve the safe list + * @param packageNameToTypingLocation is the map of package names to their cached typing locations and installed versions + * @param typeAcquisition is used to customize the typing acquisition process + * @param compilerOptions are used as a source for typing inference + */ + function discoverTypings(host, log, fileNames, projectRootPath, safeList, packageNameToTypingLocation, typeAcquisition, unresolvedImports, typesRegistry) { + if (!typeAcquisition || !typeAcquisition.enable) { + return { cachedTypingPaths: [], newTypingNames: [], filesToWatch: [] }; + } + // A typing name to typing file path mapping + var inferredTypings = ts.createMap(); + // Only infer typings for .js and .jsx files + fileNames = ts.mapDefined(fileNames, function (fileName) { + var path = ts.normalizePath(fileName); + if (ts.hasJSFileExtension(path)) { + return path; + } + }); + var filesToWatch = []; + if (typeAcquisition.include) + addInferredTypings(typeAcquisition.include, "Explicitly included types"); + var exclude = typeAcquisition.exclude || []; + // Directories to search for package.json, bower.json and other typing information + var possibleSearchDirs = ts.arrayToSet(fileNames, ts.getDirectoryPath); + possibleSearchDirs.set(projectRootPath, true); + possibleSearchDirs.forEach(function (_true, searchDir) { + var packageJsonPath = ts.combinePaths(searchDir, "package.json"); + getTypingNamesFromJson(packageJsonPath, filesToWatch); + var bowerJsonPath = ts.combinePaths(searchDir, "bower.json"); + getTypingNamesFromJson(bowerJsonPath, filesToWatch); + var bowerComponentsPath = ts.combinePaths(searchDir, "bower_components"); + getTypingNamesFromPackagesFolder(bowerComponentsPath, filesToWatch); + var nodeModulesPath = ts.combinePaths(searchDir, "node_modules"); + getTypingNamesFromPackagesFolder(nodeModulesPath, filesToWatch); + }); + getTypingNamesFromSourceFileNames(fileNames); + // add typings for unresolved imports + if (unresolvedImports) { + var module_1 = ts.deduplicate(unresolvedImports.map(function (moduleId) { return JsTyping.nodeCoreModules.has(moduleId) ? "node" : moduleId; }), ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive); + addInferredTypings(module_1, "Inferred typings from unresolved imports"); + } + // Add the cached typing locations for inferred typings that are already installed + packageNameToTypingLocation.forEach(function (typing, name) { + var registryEntry = typesRegistry.get(name); + if (inferredTypings.has(name) && inferredTypings.get(name) === undefined && registryEntry !== undefined && isTypingUpToDate(typing, registryEntry)) { + inferredTypings.set(name, typing.typingLocation); + } + }); + // Remove typings that the user has added to the exclude list + for (var _i = 0, exclude_1 = exclude; _i < exclude_1.length; _i++) { + var excludeTypingName = exclude_1[_i]; + var didDelete = inferredTypings.delete(excludeTypingName); + if (didDelete && log) + log("Typing for " + excludeTypingName + " is in exclude list, will be ignored."); + } + var newTypingNames = []; + var cachedTypingPaths = []; + inferredTypings.forEach(function (inferred, typing) { + if (inferred !== undefined) { + cachedTypingPaths.push(inferred); + } + else { + newTypingNames.push(typing); + } + }); + var result = { cachedTypingPaths: cachedTypingPaths, newTypingNames: newTypingNames, filesToWatch: filesToWatch }; + if (log) + log("Result: " + JSON.stringify(result)); + return result; + function addInferredTyping(typingName) { + if (!inferredTypings.has(typingName)) { + inferredTypings.set(typingName, undefined); // TODO: GH#18217 + } + } + function addInferredTypings(typingNames, message) { + if (log) + log(message + ": " + JSON.stringify(typingNames)); + ts.forEach(typingNames, addInferredTyping); + } + /** + * Get the typing info from common package manager json files like package.json or bower.json + */ + function getTypingNamesFromJson(jsonPath, filesToWatch) { + if (!host.fileExists(jsonPath)) { + return; + } + filesToWatch.push(jsonPath); + var jsonConfig = ts.readConfigFile(jsonPath, function (path) { return host.readFile(path); }).config; + var jsonTypingNames = ts.flatMap([jsonConfig.dependencies, jsonConfig.devDependencies, jsonConfig.optionalDependencies, jsonConfig.peerDependencies], ts.getOwnKeys); + addInferredTypings(jsonTypingNames, "Typing names in '" + jsonPath + "' dependencies"); + } + /** + * Infer typing names from given file names. For example, the file name "jquery-min.2.3.4.js" + * should be inferred to the 'jquery' typing name; and "angular-route.1.2.3.js" should be inferred + * to the 'angular-route' typing name. + * @param fileNames are the names for source files in the project + */ + function getTypingNamesFromSourceFileNames(fileNames) { + var fromFileNames = ts.mapDefined(fileNames, function (j) { + if (!ts.hasJSFileExtension(j)) + return undefined; + var inferredTypingName = ts.removeFileExtension(ts.getBaseFileName(j.toLowerCase())); + var cleanedTypingName = ts.removeMinAndVersionNumbers(inferredTypingName); + return safeList.get(cleanedTypingName); + }); + if (fromFileNames.length) { + addInferredTypings(fromFileNames, "Inferred typings from file names"); + } + var hasJsxFile = ts.some(fileNames, function (f) { return ts.fileExtensionIs(f, ".jsx" /* Jsx */); }); + if (hasJsxFile) { + if (log) + log("Inferred 'react' typings due to presence of '.jsx' extension"); + addInferredTyping("react"); + } + } + /** + * Infer typing names from packages folder (ex: node_module, bower_components) + * @param packagesFolderPath is the path to the packages folder + */ + function getTypingNamesFromPackagesFolder(packagesFolderPath, filesToWatch) { + filesToWatch.push(packagesFolderPath); + // Todo: add support for ModuleResolutionHost too + if (!host.directoryExists(packagesFolderPath)) { + return; + } + // depth of 2, so we access `node_modules/foo` but not `node_modules/foo/bar` + var fileNames = host.readDirectory(packagesFolderPath, [".json" /* Json */], /*excludes*/ undefined, /*includes*/ undefined, /*depth*/ 2); + if (log) + log("Searching for typing names in " + packagesFolderPath + "; all files: " + JSON.stringify(fileNames)); + var packageNames = []; + for (var _i = 0, fileNames_1 = fileNames; _i < fileNames_1.length; _i++) { + var fileName = fileNames_1[_i]; + var normalizedFileName = ts.normalizePath(fileName); + var baseFileName = ts.getBaseFileName(normalizedFileName); + if (baseFileName !== "package.json" && baseFileName !== "bower.json") { + continue; + } + var result_1 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); }); + var packageJson = result_1.config; + // npm 3's package.json contains a "_requiredBy" field + // we should include all the top level module names for npm 2, and only module names whose + // "_requiredBy" field starts with "#" or equals "/" for npm 3. + if (baseFileName === "package.json" && packageJson._requiredBy && + ts.filter(packageJson._requiredBy, function (r) { return r[0] === "#" || r === "/"; }).length === 0) { + continue; + } + // If the package has its own d.ts typings, those will take precedence. Otherwise the package name will be used + // to download d.ts files from DefinitelyTyped + if (!packageJson.name) { + continue; + } + var ownTypes = packageJson.types || packageJson.typings; + if (ownTypes) { + var absolutePath = ts.getNormalizedAbsolutePath(ownTypes, ts.getDirectoryPath(normalizedFileName)); + if (log) + log(" Package '" + packageJson.name + "' provides its own types."); + inferredTypings.set(packageJson.name, absolutePath); + } + else { + packageNames.push(packageJson.name); + } + } + addInferredTypings(packageNames, " Found package names"); + } + } + JsTyping.discoverTypings = discoverTypings; + var PackageNameValidationResult; + (function (PackageNameValidationResult) { + PackageNameValidationResult[PackageNameValidationResult["Ok"] = 0] = "Ok"; + PackageNameValidationResult[PackageNameValidationResult["ScopedPackagesNotSupported"] = 1] = "ScopedPackagesNotSupported"; + PackageNameValidationResult[PackageNameValidationResult["EmptyName"] = 2] = "EmptyName"; + PackageNameValidationResult[PackageNameValidationResult["NameTooLong"] = 3] = "NameTooLong"; + PackageNameValidationResult[PackageNameValidationResult["NameStartsWithDot"] = 4] = "NameStartsWithDot"; + PackageNameValidationResult[PackageNameValidationResult["NameStartsWithUnderscore"] = 5] = "NameStartsWithUnderscore"; + PackageNameValidationResult[PackageNameValidationResult["NameContainsNonURISafeCharacters"] = 6] = "NameContainsNonURISafeCharacters"; + })(PackageNameValidationResult = JsTyping.PackageNameValidationResult || (JsTyping.PackageNameValidationResult = {})); + var maxPackageNameLength = 214; + /** + * Validates package name using rules defined at https://docs.npmjs.com/files/package.json + */ + function validatePackageName(packageName) { + if (!packageName) { + return 2 /* EmptyName */; + } + if (packageName.length > maxPackageNameLength) { + return 3 /* NameTooLong */; + } + if (packageName.charCodeAt(0) === 46 /* dot */) { + return 4 /* NameStartsWithDot */; + } + if (packageName.charCodeAt(0) === 95 /* _ */) { + return 5 /* NameStartsWithUnderscore */; + } + // check if name is scope package like: starts with @ and has one '/' in the middle + // scoped packages are not currently supported + // TODO: when support will be added we'll need to split and check both scope and package name + if (/^@[^/]+\/[^/]+$/.test(packageName)) { + return 1 /* ScopedPackagesNotSupported */; + } + if (encodeURIComponent(packageName) !== packageName) { + return 6 /* NameContainsNonURISafeCharacters */; + } + return 0 /* Ok */; + } + JsTyping.validatePackageName = validatePackageName; + function renderPackageNameValidationFailure(result, typing) { + switch (result) { + case 2 /* EmptyName */: + return "Package name '" + typing + "' cannot be empty"; + case 3 /* NameTooLong */: + return "Package name '" + typing + "' should be less than " + maxPackageNameLength + " characters"; + case 4 /* NameStartsWithDot */: + return "Package name '" + typing + "' cannot start with '.'"; + case 5 /* NameStartsWithUnderscore */: + return "Package name '" + typing + "' cannot start with '_'"; + case 1 /* ScopedPackagesNotSupported */: + return "Package '" + typing + "' is scoped and currently is not supported"; + case 6 /* NameContainsNonURISafeCharacters */: + return "Package name '" + typing + "' contains non URI safe characters"; + case 0 /* Ok */: + return ts.Debug.fail(); // Shouldn't have called this. + default: + throw ts.Debug.assertNever(result); + } + } + JsTyping.renderPackageNameValidationFailure = renderPackageNameValidationFailure; + })(JsTyping = ts.JsTyping || (ts.JsTyping = {})); +})(ts || (ts = {})); +//# sourceMappingURL=jsTyping.js.map +"use strict"; +var ts; +(function (ts) { + var server; + (function (server) { + var typingsInstaller; + (function (typingsInstaller) { + var nullLog = { + isEnabled: function () { return false; }, + writeLine: ts.noop + }; + function typingToFileName(cachePath, packageName, installTypingHost, log) { + try { + var result = ts.resolveModuleName(packageName, ts.combinePaths(cachePath, "index.d.ts"), { moduleResolution: ts.ModuleResolutionKind.NodeJs }, installTypingHost); + return result.resolvedModule && result.resolvedModule.resolvedFileName; + } + catch (e) { + if (log.isEnabled()) { + log.writeLine("Failed to resolve " + packageName + " in folder '" + cachePath + "': " + e.message); + } + return undefined; + } + } + /*@internal*/ + function installNpmPackages(npmPath, tsVersion, packageNames, install) { + var hasError = false; + for (var remaining = packageNames.length; remaining > 0;) { + var result = getNpmCommandForInstallation(npmPath, tsVersion, packageNames, remaining); + remaining = result.remaining; + hasError = install(result.command) || hasError; + } + return hasError; + } + typingsInstaller.installNpmPackages = installNpmPackages; + /*@internal*/ + function getNpmCommandForInstallation(npmPath, tsVersion, packageNames, remaining) { + var sliceStart = packageNames.length - remaining; + var command, toSlice = remaining; + while (true) { + command = npmPath + " install --ignore-scripts " + (toSlice === packageNames.length ? packageNames : packageNames.slice(sliceStart, sliceStart + toSlice)).join(" ") + " --save-dev --user-agent=\"typesInstaller/" + tsVersion + "\""; + if (command.length < 8000) { + break; + } + toSlice = toSlice - Math.floor(toSlice / 2); + } + return { command: command, remaining: remaining - toSlice }; + } + typingsInstaller.getNpmCommandForInstallation = getNpmCommandForInstallation; + function endsWith(str, suffix, caseSensitive) { + var expectedPos = str.length - suffix.length; + return expectedPos >= 0 && + (str.indexOf(suffix, expectedPos) === expectedPos || + (!caseSensitive && ts.compareStringsCaseInsensitive(str.substr(expectedPos), suffix) === 0 /* EqualTo */)); + } + function isPackageOrBowerJson(fileName, caseSensitive) { + return endsWith(fileName, "/package.json", caseSensitive) || endsWith(fileName, "/bower.json", caseSensitive); + } + function sameFiles(a, b, caseSensitive) { + return a === b || (!caseSensitive && ts.compareStringsCaseInsensitive(a, b) === 0 /* EqualTo */); + } + var ProjectWatcherType; + (function (ProjectWatcherType) { + ProjectWatcherType["FileWatcher"] = "FileWatcher"; + ProjectWatcherType["DirectoryWatcher"] = "DirectoryWatcher"; + })(ProjectWatcherType || (ProjectWatcherType = {})); + var TypingsInstaller = /** @class */ (function () { + function TypingsInstaller(installTypingHost, globalCachePath, safeListPath, typesMapLocation, throttleLimit, log) { + if (log === void 0) { log = nullLog; } + this.installTypingHost = installTypingHost; + this.globalCachePath = globalCachePath; + this.safeListPath = safeListPath; + this.typesMapLocation = typesMapLocation; + this.throttleLimit = throttleLimit; + this.log = log; + this.packageNameToTypingLocation = ts.createMap(); + this.missingTypingsSet = ts.createMap(); + this.knownCachesSet = ts.createMap(); + this.projectWatchers = ts.createMap(); + this.pendingRunRequests = []; + this.installRunCount = 1; + this.inFlightRequestCount = 0; + this.latestDistTag = "latest"; + this.toCanonicalFileName = ts.createGetCanonicalFileName(installTypingHost.useCaseSensitiveFileNames); + this.globalCachePackageJsonPath = ts.combinePaths(globalCachePath, "package.json"); + if (this.log.isEnabled()) { + this.log.writeLine("Global cache location '" + globalCachePath + "', safe file path '" + safeListPath + "', types map path " + typesMapLocation); + } + this.processCacheLocation(this.globalCachePath); + } + TypingsInstaller.prototype.closeProject = function (req) { + this.closeWatchers(req.projectName); + }; + TypingsInstaller.prototype.closeWatchers = function (projectName) { + if (this.log.isEnabled()) { + this.log.writeLine("Closing file watchers for project '" + projectName + "'"); + } + var watchers = this.projectWatchers.get(projectName); + if (!watchers) { + if (this.log.isEnabled()) { + this.log.writeLine("No watchers are registered for project '" + projectName + "'"); + } + return; + } + ts.clearMap(watchers, ts.closeFileWatcher); + this.projectWatchers.delete(projectName); + if (this.log.isEnabled()) { + this.log.writeLine("Closing file watchers for project '" + projectName + "' - done."); + } + }; + TypingsInstaller.prototype.install = function (req) { + var _this = this; + if (this.log.isEnabled()) { + this.log.writeLine("Got install request " + JSON.stringify(req)); + } + // load existing typing information from the cache + if (req.cachePath) { + if (this.log.isEnabled()) { + this.log.writeLine("Request specifies cache path '" + req.cachePath + "', loading cached information..."); + } + this.processCacheLocation(req.cachePath); + } + if (this.safeList === undefined) { + this.initializeSafeList(); + } + var discoverTypingsResult = ts.JsTyping.discoverTypings(this.installTypingHost, this.log.isEnabled() ? (function (s) { return _this.log.writeLine(s); }) : undefined, req.fileNames, req.projectRootPath, this.safeList, this.packageNameToTypingLocation, req.typeAcquisition, req.unresolvedImports, this.typesRegistry); + if (this.log.isEnabled()) { + this.log.writeLine("Finished typings discovery: " + JSON.stringify(discoverTypingsResult)); + } + // start watching files + this.watchFiles(req.projectName, discoverTypingsResult.filesToWatch, req.projectRootPath); + // install typings + if (discoverTypingsResult.newTypingNames.length) { + this.installTypings(req, req.cachePath || this.globalCachePath, discoverTypingsResult.cachedTypingPaths, discoverTypingsResult.newTypingNames); + } + else { + this.sendResponse(this.createSetTypings(req, discoverTypingsResult.cachedTypingPaths)); + if (this.log.isEnabled()) { + this.log.writeLine("No new typings were requested as a result of typings discovery"); + } + } + }; + TypingsInstaller.prototype.initializeSafeList = function () { + // Prefer the safe list from the types map if it exists + if (this.typesMapLocation) { + var safeListFromMap = ts.JsTyping.loadTypesMap(this.installTypingHost, this.typesMapLocation); + if (safeListFromMap) { + this.log.writeLine("Loaded safelist from types map file '" + this.typesMapLocation + "'"); + this.safeList = safeListFromMap; + return; + } + this.log.writeLine("Failed to load safelist from types map file '" + this.typesMapLocation + "'"); + } + this.safeList = ts.JsTyping.loadSafeList(this.installTypingHost, this.safeListPath); + }; + TypingsInstaller.prototype.processCacheLocation = function (cacheLocation) { + if (this.log.isEnabled()) { + this.log.writeLine("Processing cache location '" + cacheLocation + "'"); + } + if (this.knownCachesSet.has(cacheLocation)) { + if (this.log.isEnabled()) { + this.log.writeLine("Cache location was already processed..."); + } + return; + } + var packageJson = ts.combinePaths(cacheLocation, "package.json"); + var packageLockJson = ts.combinePaths(cacheLocation, "package-lock.json"); + if (this.log.isEnabled()) { + this.log.writeLine("Trying to find '" + packageJson + "'..."); + } + if (this.installTypingHost.fileExists(packageJson) && this.installTypingHost.fileExists(packageLockJson)) { + var npmConfig = JSON.parse(this.installTypingHost.readFile(packageJson)); // TODO: GH#18217 + var npmLock = JSON.parse(this.installTypingHost.readFile(packageLockJson)); // TODO: GH#18217 + if (this.log.isEnabled()) { + this.log.writeLine("Loaded content of '" + packageJson + "': " + JSON.stringify(npmConfig)); + this.log.writeLine("Loaded content of '" + packageLockJson + "'"); + } + if (npmConfig.devDependencies && npmLock.dependencies) { + for (var key in npmConfig.devDependencies) { + if (!ts.hasProperty(npmLock.dependencies, key)) { + // if package in package.json but not package-lock.json, skip adding to cache so it is reinstalled on next use + continue; + } + // key is @types/ + var packageName = ts.getBaseFileName(key); + if (!packageName) { + continue; + } + var typingFile = typingToFileName(cacheLocation, packageName, this.installTypingHost, this.log); + if (!typingFile) { + this.missingTypingsSet.set(packageName, true); + continue; + } + var existingTypingFile = this.packageNameToTypingLocation.get(packageName); + if (existingTypingFile) { + if (existingTypingFile.typingLocation === typingFile) { + continue; + } + if (this.log.isEnabled()) { + this.log.writeLine("New typing for package " + packageName + " from '" + typingFile + "' conflicts with existing typing file '" + existingTypingFile + "'"); + } + } + if (this.log.isEnabled()) { + this.log.writeLine("Adding entry into typings cache: '" + packageName + "' => '" + typingFile + "'"); + } + var info = ts.getProperty(npmLock.dependencies, key); + var version_1 = info && info.version; + if (!version_1) { + continue; + } + var newTyping = { typingLocation: typingFile, version: new ts.Version(version_1) }; + this.packageNameToTypingLocation.set(packageName, newTyping); + } + } + } + if (this.log.isEnabled()) { + this.log.writeLine("Finished processing cache location '" + cacheLocation + "'"); + } + this.knownCachesSet.set(cacheLocation, true); + }; + TypingsInstaller.prototype.filterTypings = function (typingsToInstall) { + var _this = this; + return typingsToInstall.filter(function (typing) { + if (_this.missingTypingsSet.get(typing)) { + if (_this.log.isEnabled()) + _this.log.writeLine("'" + typing + "' is in missingTypingsSet - skipping..."); + return false; + } + var validationResult = ts.JsTyping.validatePackageName(typing); + if (validationResult !== 0 /* Ok */) { + // add typing name to missing set so we won't process it again + _this.missingTypingsSet.set(typing, true); + if (_this.log.isEnabled()) + _this.log.writeLine(ts.JsTyping.renderPackageNameValidationFailure(validationResult, typing)); + return false; + } + if (!_this.typesRegistry.has(typing)) { + if (_this.log.isEnabled()) + _this.log.writeLine("Entry for package '" + typing + "' does not exist in local types registry - skipping..."); + return false; + } + if (_this.packageNameToTypingLocation.get(typing) && ts.JsTyping.isTypingUpToDate(_this.packageNameToTypingLocation.get(typing), _this.typesRegistry.get(typing))) { + if (_this.log.isEnabled()) + _this.log.writeLine("'" + typing + "' already has an up-to-date typing - skipping..."); + return false; + } + return true; + }); + }; + TypingsInstaller.prototype.ensurePackageDirectoryExists = function (directory) { + var npmConfigPath = ts.combinePaths(directory, "package.json"); + if (this.log.isEnabled()) { + this.log.writeLine("Npm config file: " + npmConfigPath); + } + if (!this.installTypingHost.fileExists(npmConfigPath)) { + if (this.log.isEnabled()) { + this.log.writeLine("Npm config file: '" + npmConfigPath + "' is missing, creating new one..."); + } + this.ensureDirectoryExists(directory, this.installTypingHost); + this.installTypingHost.writeFile(npmConfigPath, '{ "private": true }'); + } + }; + TypingsInstaller.prototype.installTypings = function (req, cachePath, currentlyCachedTypings, typingsToInstall) { + var _this = this; + if (this.log.isEnabled()) { + this.log.writeLine("Installing typings " + JSON.stringify(typingsToInstall)); + } + var filteredTypings = this.filterTypings(typingsToInstall); + if (filteredTypings.length === 0) { + if (this.log.isEnabled()) { + this.log.writeLine("All typings are known to be missing or invalid - no need to install more typings"); + } + this.sendResponse(this.createSetTypings(req, currentlyCachedTypings)); + return; + } + this.ensurePackageDirectoryExists(cachePath); + var requestId = this.installRunCount; + this.installRunCount++; + // send progress event + this.sendResponse({ + kind: server.EventBeginInstallTypes, + eventId: requestId, + typingsInstallerVersion: ts.version, + projectName: req.projectName + }); + var scopedTypings = filteredTypings.map(typingsName); + this.installTypingsAsync(requestId, scopedTypings, cachePath, function (ok) { + try { + if (!ok) { + if (_this.log.isEnabled()) { + _this.log.writeLine("install request failed, marking packages as missing to prevent repeated requests: " + JSON.stringify(filteredTypings)); + } + for (var _i = 0, filteredTypings_1 = filteredTypings; _i < filteredTypings_1.length; _i++) { + var typing = filteredTypings_1[_i]; + _this.missingTypingsSet.set(typing, true); + } + return; + } + // TODO: watch project directory + if (_this.log.isEnabled()) { + _this.log.writeLine("Installed typings " + JSON.stringify(scopedTypings)); + } + var installedTypingFiles = []; + for (var _a = 0, filteredTypings_2 = filteredTypings; _a < filteredTypings_2.length; _a++) { + var packageName = filteredTypings_2[_a]; + var typingFile = typingToFileName(cachePath, packageName, _this.installTypingHost, _this.log); + if (!typingFile) { + _this.missingTypingsSet.set(packageName, true); + continue; + } + // packageName is guaranteed to exist in typesRegistry by filterTypings + var distTags = _this.typesRegistry.get(packageName); + var newVersion = new ts.Version(distTags["ts" + ts.versionMajorMinor] || distTags[_this.latestDistTag]); + var newTyping = { typingLocation: typingFile, version: newVersion }; + _this.packageNameToTypingLocation.set(packageName, newTyping); + installedTypingFiles.push(typingFile); + } + if (_this.log.isEnabled()) { + _this.log.writeLine("Installed typing files " + JSON.stringify(installedTypingFiles)); + } + _this.sendResponse(_this.createSetTypings(req, currentlyCachedTypings.concat(installedTypingFiles))); + } + finally { + var response = { + kind: server.EventEndInstallTypes, + eventId: requestId, + projectName: req.projectName, + packagesToInstall: scopedTypings, + installSuccess: ok, + typingsInstallerVersion: ts.version // tslint:disable-line no-unnecessary-qualifier (qualified explicitly to prevent occasional shadowing) + }; + _this.sendResponse(response); + } + }); + }; + TypingsInstaller.prototype.ensureDirectoryExists = function (directory, host) { + var directoryName = ts.getDirectoryPath(directory); + if (!host.directoryExists(directoryName)) { + this.ensureDirectoryExists(directoryName, host); + } + if (!host.directoryExists(directory)) { + host.createDirectory(directory); + } + }; + TypingsInstaller.prototype.watchFiles = function (projectName, files, projectRootPath) { + var _this = this; + if (!files.length) { + // shut down existing watchers + this.closeWatchers(projectName); + return; + } + var watchers = this.projectWatchers.get(projectName); + var toRemove = ts.createMap(); + if (!watchers) { + watchers = ts.createMap(); + this.projectWatchers.set(projectName, watchers); + } + else { + ts.copyEntries(watchers, toRemove); + } + // handler should be invoked once for the entire set of files since it will trigger full rediscovery of typings + watchers.isInvoked = false; + var isLoggingEnabled = this.log.isEnabled(); + var createProjectWatcher = function (path, projectWatcherType) { + var canonicalPath = _this.toCanonicalFileName(path); + toRemove.delete(canonicalPath); + if (watchers.has(canonicalPath)) { + return; + } + if (isLoggingEnabled) { + _this.log.writeLine(projectWatcherType + ":: Added:: WatchInfo: " + path); + } + var watcher = projectWatcherType === "FileWatcher" /* FileWatcher */ ? + _this.installTypingHost.watchFile(path, function (f, eventKind) { + if (isLoggingEnabled) { + _this.log.writeLine("FileWatcher:: Triggered with " + f + " eventKind: " + ts.FileWatcherEventKind[eventKind] + ":: WatchInfo: " + path + ":: handler is already invoked '" + watchers.isInvoked + "'"); + } + if (!watchers.isInvoked) { + watchers.isInvoked = true; + _this.sendResponse({ projectName: projectName, kind: server.ActionInvalidate }); + } + }, /*pollingInterval*/ 2000) : + _this.installTypingHost.watchDirectory(path, function (f) { + if (isLoggingEnabled) { + _this.log.writeLine("DirectoryWatcher:: Triggered with " + f + " :: WatchInfo: " + path + " recursive :: handler is already invoked '" + watchers.isInvoked + "'"); + } + if (watchers.isInvoked || !ts.fileExtensionIs(f, ".json" /* Json */)) { + return; + } + if (isPackageOrBowerJson(f, _this.installTypingHost.useCaseSensitiveFileNames) && + !sameFiles(f, _this.globalCachePackageJsonPath, _this.installTypingHost.useCaseSensitiveFileNames)) { + watchers.isInvoked = true; + _this.sendResponse({ projectName: projectName, kind: server.ActionInvalidate }); + } + }, /*recursive*/ true); + watchers.set(canonicalPath, isLoggingEnabled ? { + close: function () { + _this.log.writeLine(projectWatcherType + ":: Closed:: WatchInfo: " + path); + watcher.close(); + } + } : watcher); + }; + // Create watches from list of files + for (var _i = 0, files_1 = files; _i < files_1.length; _i++) { + var file = files_1[_i]; + if (file.endsWith("/package.json") || file.endsWith("/bower.json")) { + // package.json or bower.json exists, watch the file to detect changes and update typings + createProjectWatcher(file, "FileWatcher" /* FileWatcher */); + continue; + } + // path in projectRoot, watch project root + if (ts.containsPath(projectRootPath, file, projectRootPath, !this.installTypingHost.useCaseSensitiveFileNames)) { + var subDirectory = file.indexOf(ts.directorySeparator, projectRootPath.length + 1); + if (subDirectory !== -1) { + // Watch subDirectory + createProjectWatcher(file.substr(0, subDirectory), "DirectoryWatcher" /* DirectoryWatcher */); + } + else { + // Watch the directory itself + createProjectWatcher(file, "DirectoryWatcher" /* DirectoryWatcher */); + } + continue; + } + // path in global cache, watch global cache + if (ts.containsPath(this.globalCachePath, file, projectRootPath, !this.installTypingHost.useCaseSensitiveFileNames)) { + createProjectWatcher(this.globalCachePath, "DirectoryWatcher" /* DirectoryWatcher */); + continue; + } + // watch node_modules or bower_components + createProjectWatcher(file, "DirectoryWatcher" /* DirectoryWatcher */); + } + // Remove unused watches + toRemove.forEach(function (watch, path) { + watch.close(); + watchers.delete(path); + }); + }; + TypingsInstaller.prototype.createSetTypings = function (request, typings) { + return { + projectName: request.projectName, + typeAcquisition: request.typeAcquisition, + compilerOptions: request.compilerOptions, + typings: typings, + unresolvedImports: request.unresolvedImports, + kind: server.ActionSet + }; + }; + TypingsInstaller.prototype.installTypingsAsync = function (requestId, packageNames, cwd, onRequestCompleted) { + this.pendingRunRequests.unshift({ requestId: requestId, packageNames: packageNames, cwd: cwd, onRequestCompleted: onRequestCompleted }); + this.executeWithThrottling(); + }; + TypingsInstaller.prototype.executeWithThrottling = function () { + var _this = this; + var _loop_1 = function () { + this_1.inFlightRequestCount++; + var request = this_1.pendingRunRequests.pop(); + this_1.installWorker(request.requestId, request.packageNames, request.cwd, function (ok) { + _this.inFlightRequestCount--; + request.onRequestCompleted(ok); + _this.executeWithThrottling(); + }); + }; + var this_1 = this; + while (this.inFlightRequestCount < this.throttleLimit && this.pendingRunRequests.length) { + _loop_1(); + } + }; + return TypingsInstaller; + }()); + typingsInstaller.TypingsInstaller = TypingsInstaller; + /* @internal */ + function typingsName(packageName) { + return "@types/" + packageName + "@ts" + ts.versionMajorMinor; + } + typingsInstaller.typingsName = typingsName; + })(typingsInstaller = server.typingsInstaller || (server.typingsInstaller = {})); + })(server = ts.server || (ts.server = {})); +})(ts || (ts = {})); +//# sourceMappingURL=typingsInstallerCore.js.map +var ts; +(function (ts) { + var server; + (function (server) { + var typingsInstaller; + (function (typingsInstaller) { + var fs = require("fs"); + var path = require("path"); + var FileLog = (function () { + function FileLog(logFile) { + var _this = this; + this.logFile = logFile; + this.isEnabled = function () { + return typeof _this.logFile === "string"; + }; + this.writeLine = function (text) { + if (typeof _this.logFile !== "string") + return; + try { + fs.appendFileSync(_this.logFile, "[" + server.nowString() + "] " + text + ts.sys.newLine); + } + catch (e) { + _this.logFile = undefined; + } + }; + } + return FileLog; + }()); + function getDefaultNPMLocation(processName) { + if (path.basename(processName).indexOf("node") === 0) { + return "\"" + path.join(path.dirname(process.argv[0]), "npm") + "\""; + } + else { + return "npm"; + } + } + function loadTypesRegistryFile(typesRegistryFilePath, host, log) { + if (!host.fileExists(typesRegistryFilePath)) { + if (log.isEnabled()) { + log.writeLine("Types registry file '" + typesRegistryFilePath + "' does not exist"); + } + return ts.createMap(); + } + try { + var content = JSON.parse(host.readFile(typesRegistryFilePath)); + return ts.createMapFromTemplate(content.entries); + } + catch (e) { + if (log.isEnabled()) { + log.writeLine("Error when loading types registry file '" + typesRegistryFilePath + "': " + e.message + ", " + e.stack); + } + return ts.createMap(); + } + } + var typesRegistryPackageName = "types-registry"; + function getTypesRegistryFileLocation(globalTypingsCacheLocation) { + return ts.combinePaths(ts.normalizeSlashes(globalTypingsCacheLocation), "node_modules/" + typesRegistryPackageName + "/index.json"); + } + var NodeTypingsInstaller = (function (_super) { + __extends(NodeTypingsInstaller, _super); + function NodeTypingsInstaller(globalTypingsCacheLocation, typingSafeListLocation, typesMapLocation, npmLocation, throttleLimit, log) { + var _this = _super.call(this, ts.sys, globalTypingsCacheLocation, typingSafeListLocation ? ts.toPath(typingSafeListLocation, "", ts.createGetCanonicalFileName(ts.sys.useCaseSensitiveFileNames)) : ts.toPath("typingSafeList.json", __dirname, ts.createGetCanonicalFileName(ts.sys.useCaseSensitiveFileNames)), typesMapLocation ? ts.toPath(typesMapLocation, "", ts.createGetCanonicalFileName(ts.sys.useCaseSensitiveFileNames)) : ts.toPath("typesMap.json", __dirname, ts.createGetCanonicalFileName(ts.sys.useCaseSensitiveFileNames)), throttleLimit, log) || this; + _this.npmPath = npmLocation !== undefined ? npmLocation : getDefaultNPMLocation(process.argv[0]); + if (ts.stringContains(_this.npmPath, " ") && _this.npmPath[0] !== "\"") { + _this.npmPath = "\"" + _this.npmPath + "\""; + } + if (_this.log.isEnabled()) { + _this.log.writeLine("Process id: " + process.pid); + _this.log.writeLine("NPM location: " + _this.npmPath + " (explicit '" + server.Arguments.NpmLocation + "' " + (npmLocation === undefined ? "not " : "") + " provided)"); + } + (_this.nodeExecSync = require("child_process").execSync); + _this.ensurePackageDirectoryExists(globalTypingsCacheLocation); + try { + if (_this.log.isEnabled()) { + _this.log.writeLine("Updating " + typesRegistryPackageName + " npm package..."); + } + _this.execSyncAndLog(_this.npmPath + " install --ignore-scripts " + typesRegistryPackageName + "@" + _this.latestDistTag, { cwd: globalTypingsCacheLocation }); + if (_this.log.isEnabled()) { + _this.log.writeLine("Updated " + typesRegistryPackageName + " npm package"); + } + } + catch (e) { + if (_this.log.isEnabled()) { + _this.log.writeLine("Error updating " + typesRegistryPackageName + " package: " + e.message); + } + _this.delayedInitializationError = { + kind: "event::initializationFailed", + message: e.message + }; + } + _this.typesRegistry = loadTypesRegistryFile(getTypesRegistryFileLocation(globalTypingsCacheLocation), _this.installTypingHost, _this.log); + return _this; + } + NodeTypingsInstaller.prototype.listen = function () { + var _this = this; + process.on("message", function (req) { + if (_this.delayedInitializationError) { + _this.sendResponse(_this.delayedInitializationError); + _this.delayedInitializationError = undefined; + } + switch (req.kind) { + case "discover": + _this.install(req); + break; + case "closeProject": + _this.closeProject(req); + break; + case "typesRegistry": { + var typesRegistry_1 = {}; + _this.typesRegistry.forEach(function (value, key) { + typesRegistry_1[key] = value; + }); + var response = { kind: server.EventTypesRegistry, typesRegistry: typesRegistry_1 }; + _this.sendResponse(response); + break; + } + case "installPackage": { + var fileName = req.fileName, packageName_1 = req.packageName, projectName_1 = req.projectName, projectRootPath = req.projectRootPath; + var cwd = getDirectoryOfPackageJson(fileName, _this.installTypingHost) || projectRootPath; + if (cwd) { + _this.installWorker(-1, [packageName_1], cwd, function (success) { + var message = success ? "Package " + packageName_1 + " installed." : "There was an error installing " + packageName_1 + "."; + var response = { kind: server.ActionPackageInstalled, projectName: projectName_1, success: success, message: message }; + _this.sendResponse(response); + }); + } + else { + var response = { kind: server.ActionPackageInstalled, projectName: projectName_1, success: false, message: "Could not determine a project root path." }; + _this.sendResponse(response); + } + break; + } + case "inspectValue": { + var response = { kind: server.ActionValueInspected, result: ts.inspectModule(req.options.fileNameToRequire) }; + _this.sendResponse(response); + break; + } + default: + ts.Debug.assertNever(req); + } + }); + }; + NodeTypingsInstaller.prototype.sendResponse = function (response) { + if (this.log.isEnabled()) { + this.log.writeLine("Sending response:\n " + JSON.stringify(response)); + } + process.send(response); + if (this.log.isEnabled()) { + this.log.writeLine("Response has been sent."); + } + }; + NodeTypingsInstaller.prototype.installWorker = function (requestId, packageNames, cwd, onRequestCompleted) { + var _this = this; + if (this.log.isEnabled()) { + this.log.writeLine("#" + requestId + " with arguments'" + JSON.stringify(packageNames) + "'."); + } + var start = Date.now(); + var hasError = typingsInstaller.installNpmPackages(this.npmPath, ts.version, packageNames, function (command) { return _this.execSyncAndLog(command, { cwd: cwd }); }); + if (this.log.isEnabled()) { + this.log.writeLine("npm install #" + requestId + " took: " + (Date.now() - start) + " ms"); + } + onRequestCompleted(!hasError); + }; + NodeTypingsInstaller.prototype.execSyncAndLog = function (command, options) { + if (this.log.isEnabled()) { + this.log.writeLine("Exec: " + command); + } + try { + var stdout = this.nodeExecSync(command, __assign({}, options, { encoding: "utf-8" })); + if (this.log.isEnabled()) { + this.log.writeLine(" Succeeded. stdout:" + indent(ts.sys.newLine, stdout)); + } + return false; + } + catch (error) { + var stdout = error.stdout, stderr = error.stderr; + this.log.writeLine(" Failed. stdout:" + indent(ts.sys.newLine, stdout) + ts.sys.newLine + " stderr:" + indent(ts.sys.newLine, stderr)); + return true; + } + }; + return NodeTypingsInstaller; + }(typingsInstaller.TypingsInstaller)); + typingsInstaller.NodeTypingsInstaller = NodeTypingsInstaller; + function getDirectoryOfPackageJson(fileName, host) { + return ts.forEachAncestorDirectory(ts.getDirectoryPath(fileName), function (directory) { + if (host.fileExists(ts.combinePaths(directory, "package.json"))) { + return directory; + } + }); + } + var logFilePath = server.findArgument(server.Arguments.LogFile); + var globalTypingsCacheLocation = server.findArgument(server.Arguments.GlobalCacheLocation); + var typingSafeListLocation = server.findArgument(server.Arguments.TypingSafeListLocation); + var typesMapLocation = server.findArgument(server.Arguments.TypesMapLocation); + var npmLocation = server.findArgument(server.Arguments.NpmLocation); + var log = new FileLog(logFilePath); + if (log.isEnabled()) { + process.on("uncaughtException", function (e) { + log.writeLine("Unhandled exception: " + e + " at " + e.stack); + }); + } + process.on("disconnect", function () { + if (log.isEnabled()) { + log.writeLine("Parent process has exited, shutting down..."); + } + process.exit(0); + }); + var installer = new NodeTypingsInstaller(globalTypingsCacheLocation, typingSafeListLocation, typesMapLocation, npmLocation, 5, log); + installer.listen(); + function indent(newline, str) { + return newline + " " + str.replace(/\r?\n/, newline + " "); + } + })(typingsInstaller = server.typingsInstaller || (server.typingsInstaller = {})); + })(server = ts.server || (ts.server = {})); +})(ts || (ts = {})); +//# sourceMappingURL=typingsInstaller.js.map \ No newline at end of file diff --git a/node_modules/typescript/lib/watchGuard.js b/node_modules/typescript/lib/watchGuard.js new file mode 100644 index 0000000..bea0a0e --- /dev/null +++ b/node_modules/typescript/lib/watchGuard.js @@ -0,0 +1,29 @@ +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + + +"use strict"; +if (process.argv.length < 3) { + process.exit(1); +} +var directoryName = process.argv[2]; +var fs = require("fs"); +try { + var watcher = fs.watch(directoryName, { recursive: true }, function () { return ({}); }); + watcher.close(); +} +catch (_a) { } +process.exit(0); +//# sourceMappingURL=watchGuard.js.map \ No newline at end of file diff --git a/node_modules/typescript/lib/zh-cn/diagnosticMessages.generated.json b/node_modules/typescript/lib/zh-cn/diagnosticMessages.generated.json new file mode 100644 index 0000000..23d0bae --- /dev/null +++ b/node_modules/typescript/lib/zh-cn/diagnosticMessages.generated.json @@ -0,0 +1,1101 @@ +{ + "A_0_modifier_cannot_be_used_with_an_import_declaration_1079": "“{0}”修饰符不能与导入声明一起使用。", + "A_0_modifier_cannot_be_used_with_an_interface_declaration_1045": "“{0}”修饰符不能与接口声明一起使用。", + "A_0_parameter_must_be_the_first_parameter_2680": "“{0}”参数必须是第一个参数。", + "A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature_2463": "绑定模式参数在实现签名中不能为可选参数。", + "A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement_1105": "\"break\" 语句只能在封闭迭代或 switch 语句内使用。", + "A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement_1116": "\"break\" 语句只能跳转到封闭语句的标签。", + "A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments_2500": "类只能实现具有可选类型参数的标识符/限定名称。", + "A_class_declaration_without_the_default_modifier_must_have_a_name_1211": "不带 \"default\" 修饰符的类声明必须具有名称。", + "A_class_may_only_extend_another_class_2311": "类只能扩展其他类。", + "A_class_may_only_implement_another_class_or_interface_2422": "类只能实现其他类或接口。", + "A_class_member_cannot_have_the_0_keyword_1248": "类成员不可具有“{0}”关键字。", + "A_comma_expression_is_not_allowed_in_a_computed_property_name_1171": "计算属性名中不允许逗号表达式。", + "A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type_2467": "计算属性名无法从其包含的类型引用类型参数。", + "A_computed_property_name_in_a_class_property_declaration_must_refer_to_an_expression_whose_type_is_a_1166": "类属性声明中的计算属性名称必须引用类型为文本类型或 \"unique symbol\" 类型的表达式。", + "A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_ty_1168": "方法重载中的计算属性名称必须引用文本类型或 \"unique symbol\" 类型的表达式。", + "A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type__1170": "类型文本中的计算属性名称必须引用类型为文本类型或 \"unique symbol\" 类型的表达式。", + "A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_t_1165": "环境上下文中的计算属性名称必须引用类型为文本类型或 \"unique symbol\" 类型的表达式。", + "A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_1169": "接口中的计算属性名称必须引用必须引用类型为文本类型或 \"unique symbol\" 的表达式。", + "A_computed_property_name_must_be_of_type_string_number_symbol_or_any_2464": "计算属性名的类型必须为 \"string\"、\"number\"、\"symbol\" 或 \"any\"。", + "A_computed_property_name_of_the_form_0_must_be_of_type_symbol_2471": "窗体“{0}”的计算属性名必须是 \"symbol\" 类型。", + "A_const_enum_member_can_only_be_accessed_using_a_string_literal_2476": "只有使用字符串文本才能访问常数枚举成员。", + "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_1254": "环境上下文中的 \"const\" 初始化表达式必须为字符串或数字参数。", + "A_constructor_cannot_contain_a_super_call_when_its_class_extends_null_17005": "当构造函数的类扩展 \"null\" 时,它不能包含 \"super\" 调用。", + "A_constructor_cannot_have_a_this_parameter_2681": "构造函数不可具有 \"this\" 参数。", + "A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement_1104": "\"continue\" 语句只能在封闭迭代语句内使用。", + "A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement_1115": "\"continue\" 语句只能跳转到封闭迭代语句的标签。", + "A_declare_modifier_cannot_be_used_in_an_already_ambient_context_1038": "不能在已有的环境上下文中使用 \"declare\" 修饰符。", + "A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file_1046": "在 .d.ts 文件中的顶层声明需要 \"declare\" 修饰符。", + "A_decorator_can_only_decorate_a_method_implementation_not_an_overload_1249": "修饰器仅可修饰方法实现,而不可修饰重载。", + "A_default_clause_cannot_appear_more_than_once_in_a_switch_statement_1113": "\"default\" 子句在 \"switch\" 语句中只能出现一次。", + "A_default_export_can_only_be_used_in_an_ECMAScript_style_module_1319": "默认导出只能在 ECMAScript-style 模块中使用。", + "A_definite_assignment_assertion_is_not_permitted_in_this_context_1255": "此上下文中不允许明确的赋值断言 \"!\"。", + "A_destructuring_declaration_must_have_an_initializer_1182": "析构声明必须具有初始化表达式。", + "A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declarat_2712": "ES5/ES3 中的动态导入调用需要 \"Promise\" 构造函数。确保对 \"Promise\" 构造函数进行了声明或在 \"--lib\" 选项中包含了 \"ES2015\"。", + "A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES20_2711": "动态导入调用返回 \"Promise\"。请确保具有对 \"Promise\" 的声明或在 `--lib` 选项中包括 \"ES2015\"。", + "A_file_cannot_have_a_reference_to_itself_1006": "文件不能引用自身。", + "A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator_1103": "仅异步函数或异步生成器中允许 \"for-await-of\" 语句。", + "A_function_returning_never_cannot_have_a_reachable_end_point_2534": "返回“从不”的函数不能具有可访问的终结点。", + "A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void_2679": "使用 \"new\" 关键字调用的函数不可具有“失效”的 \"this\" 类型。", + "A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value_2355": "其声明类型不为 \"void\" 或 \"any\" 的函数必须返回值。", + "A_generator_cannot_have_a_void_type_annotation_2505": "生成器不能具有 \"void\" 类型批注。", + "A_get_accessor_cannot_have_parameters_1054": "\"get\" 访问器不能具有参数。", + "A_get_accessor_must_return_a_value_2378": "\"get\" 访问器必须返回值。", + "A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_memb_2651": "枚举声明中的成员初始化表达式不能引用在其后声明的成员(包括在其他枚举中定义的成员)。", + "A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any_2545": "mixin 类必须具有单个 rest 参数为类型 \"any[]\" 的构造函数。", + "A_module_cannot_have_multiple_default_exports_2528": "一个模块不能具有多个默认导出。", + "A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merg_2433": "命名空间声明必须位于与之合并的类或函数所在的相同文件内。", + "A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged_2434": "命名空间声明不能位于与之合并的类或函数前", + "A_namespace_declaration_is_only_allowed_in_a_namespace_or_module_1235": "只允许在命名空间或模块中使用命名空间声明。", + "A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_7038": "命名空间样式导入不能调用或构造,并将在运行时导致失败。", + "A_non_dry_build_would_build_project_0_6357": "非 -dry 生成将生成项目“{0}”", + "A_non_dry_build_would_delete_the_following_files_Colon_0_6356": "非 -dry 生成将删除以下文件: {0}", + "A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation_2371": "只允许在函数或构造函数实现中使用参数初始化表达式。", + "A_parameter_property_cannot_be_declared_using_a_rest_parameter_1317": "不能使用 rest 参数声明参数属性。", + "A_parameter_property_is_only_allowed_in_a_constructor_implementation_2369": "只允许在构造函数实现中使用参数属性。", + "A_parameter_property_may_not_be_declared_using_a_binding_pattern_1187": "不能使用绑定模式声明参数属性。", + "A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not_18001": "“扩展”选项中的路径必须为相对路径或根路径,但“{0}”不是。", + "A_promise_must_have_a_then_method_1059": "承诺必须具有 \"then\" 方法。", + "A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly_1331": "类型为 \"unique symbol\" 的类的属性必须同时为 \"static\" 和 \"readonly\"。", + "A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly_1330": "类型为 \"unique symbol\" 的接口或类型文本的属性必须为 \"readonly\"。", + "A_required_parameter_cannot_follow_an_optional_parameter_1016": "必选参数不能位于可选参数后。", + "A_rest_element_cannot_contain_a_binding_pattern_2501": "rest 元素不能包含绑定模式。", + "A_rest_element_cannot_have_a_property_name_2566": "其余元素不能具有属性名。", + "A_rest_element_cannot_have_an_initializer_1186": "rest 元素不能具有初始化表达式。", + "A_rest_element_must_be_last_in_a_destructuring_pattern_2462": "rest 元素必须在析构模式中位于最末。", + "A_rest_parameter_cannot_be_optional_1047": "rest 参数不能为可选参数。", + "A_rest_parameter_cannot_have_an_initializer_1048": "rest 参数不能具有初始化表达式。", + "A_rest_parameter_must_be_last_in_a_parameter_list_1014": "rest 参数必须是参数列表中的最后一个参数。", + "A_rest_parameter_must_be_of_an_array_type_2370": "rest 参数必须是数组类型。", + "A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma_1013": "Rest 参数或绑定模式不可带尾随逗号。", + "A_return_statement_can_only_be_used_within_a_function_body_1108": "\"return\" 语句只能在函数体中使用。", + "A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl_6167": "一系列条目,这些条目将重新映射导入内容,以查找与 \"baseUrl\" 有关的位置。", + "A_set_accessor_cannot_have_a_return_type_annotation_1095": "\"set\" 访问器不能具有返回类型批注。", + "A_set_accessor_cannot_have_an_optional_parameter_1051": "\"set\" 访问器不能具有可选参数。", + "A_set_accessor_cannot_have_rest_parameter_1053": "\"set\" 访问器不能具有 rest 参数。", + "A_set_accessor_must_have_exactly_one_parameter_1049": "\"set\" 访问器必须正好具有一个参数。", + "A_set_accessor_parameter_cannot_have_an_initializer_1052": "\"set\" 访问器参数不能包含初始化表达式。", + "A_signature_with_an_implementation_cannot_use_a_string_literal_type_2381": "具有实现的签名不能使用字符串文本类型。", + "A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_proper_2376": "当类包含初始化的属性或参数属性时,\"super\" 调用必须是构造函数中的第一个语句。", + "A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard_2518": "基于 \"this\" 的类型防护与基于参数的类型防护不兼容。", + "A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface_2526": "\"this\" 类型仅在类或接口的非静态成员中可用。", + "A_tsconfig_json_file_is_already_defined_at_Colon_0_5054": "已在“{0}”中定义了 \"tsconfig.json\" 文件。", + "A_tuple_type_element_list_cannot_be_empty_1122": "元组类型元素列表不能为空。", + "A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Con_17007": "乘方表达式的左侧不允许出现类型断言表达式。请考虑用括号将表达式括起。", + "A_type_literal_property_cannot_have_an_initializer_1247": "类型文字数据不可具有初始化表达式。", + "A_type_predicate_cannot_reference_a_rest_parameter_1229": "类型谓词无法引用 rest 参数。", + "A_type_predicate_cannot_reference_element_0_in_a_binding_pattern_1230": "类型谓词无法在绑定模式中引用元素“{0}”。", + "A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods_1228": "只允许在函数和方法的返回类型位置使用类型谓词。", + "A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type_2677": "类型谓词的类型不可赋给其参数的类型。", + "A_variable_whose_type_is_a_unique_symbol_type_must_be_const_1332": "类型为 \"unique symbol\" 的变量必须为 \"const\"。", + "A_yield_expression_is_only_allowed_in_a_generator_body_1163": "只允许在生成器正文中使用 \"yield\" 表达式。", + "Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression_2513": "无法通过 super 表达式访问“{1}”类中的“{0}”抽象方法。", + "Abstract_methods_can_only_appear_within_an_abstract_class_1244": "抽象方法只能出现在抽象类中。", + "Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor_2715": "不能在构造函数中访问类“{1}”中的抽象属性“{0}”。", + "Accessibility_modifier_already_seen_1028": "已看到可访问性修饰符。", + "Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher_1056": "访问器仅在面向 ECMAScript 5 和更高版本时可用。", + "Accessors_must_both_be_abstract_or_non_abstract_2676": "两个取值函数必须都是抽象的或都是非抽象的。", + "Add_0_to_existing_import_declaration_from_1_90015": "将“{0}”从“{1}”添加到现有导入声明", + "Add_0_to_unresolved_variable_90008": "将“{0}.”添加到未解析的变量", + "Add_all_missing_async_modifiers_95041": "添加所有缺失的 \"async\" 修饰符", + "Add_all_missing_members_95022": "添加所有缺少的成员", + "Add_all_missing_super_calls_95039": "添加所有缺失的超级调用", + "Add_async_modifier_to_containing_function_90029": "将异步修饰符添加到包含函数", + "Add_braces_to_arrow_function_95059": "向箭头函数添加大括号", + "Add_definite_assignment_assertion_to_property_0_95020": "向属性“{0}”添加明确的赋值断言", + "Add_definite_assignment_assertions_to_all_uninitialized_properties_95028": "将明确赋值断言添加到未初始化的所有属性", + "Add_index_signature_for_property_0_90017": "为属性“{0}”添加索引签名", + "Add_initializer_to_property_0_95019": "向属性“{0}”添加初始值设定项", + "Add_initializers_to_all_uninitialized_properties_95027": "将初始化表达式添加到未初始化的所有属性", + "Add_missing_super_call_90001": "添加缺失的 \"super()\" 调用", + "Add_missing_typeof_95052": "添加缺少的 \"typeof\"", + "Add_or_remove_braces_in_an_arrow_function_95058": "添加或删除箭头函数中的大括号", + "Add_qualifier_to_all_unresolved_variables_matching_a_member_name_95037": "将限定符添加到匹配成员名称的所有未解析变量", + "Add_to_all_uncalled_decorators_95044": "将 \"()\" 添加到所有未调用的修饰器", + "Add_ts_ignore_to_all_error_messages_95042": "将 \"@ts-ignore\" 添加到所有错误消息", + "Add_undefined_type_to_all_uninitialized_properties_95029": "将未定义的类型添加到未初始化的所有属性", + "Add_undefined_type_to_property_0_95018": "向属性“{0}”添加“未定义”类型", + "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068": "添加 tsconfig.json 文件有助于组织包含 TypeScript 和 JavaScript 文件的项目。有关详细信息,请访问 https://aka.ms/tsconfig。", + "Additional_Checks_6176": "其他检查", + "Advanced_Options_6178": "高级选项", + "All_declarations_of_0_must_have_identical_modifiers_2687": "“{0}”的所有声明必须具有相同的修饰符。", + "All_declarations_of_0_must_have_identical_type_parameters_2428": "“{0}”的所有声明都必须具有相同的类型参数。", + "All_declarations_of_an_abstract_method_must_be_consecutive_2516": "抽象方法的所有声明必须是连续的。", + "All_destructured_elements_are_unused_6198": "未取消使用任何解构元素。", + "All_imports_in_import_declaration_are_unused_6192": "未使用导入声明中的所有导入。", + "All_variables_are_unused_6199": "所有变量均未使用。", + "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011": "允许从不带默认输出的模块中默认输入。这不会影响代码发出,只是类型检查。", + "Allow_javascript_files_to_be_compiled_6102": "允许编译 JavaScript 文件。", + "Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided_1209": "提供 \"--isolatedModules\" 标志的情况下不允许使用环境常数枚举。", + "Ambient_module_declaration_cannot_specify_relative_module_name_2436": "环境模块声明无法指定相对模块名。", + "Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces_2435": "环境模块不能嵌套在其他模块或命名空间中。", + "An_AMD_module_cannot_have_multiple_name_assignments_2458": "AMD 模块无法拥有多个名称分配。", + "An_abstract_accessor_cannot_have_an_implementation_1318": "抽象访问器不能有实现。", + "An_accessor_cannot_be_declared_in_an_ambient_context_1086": "不能在环境上下文中声明访问器。", + "An_accessor_cannot_have_type_parameters_1094": "访问器不能具有类型参数。", + "An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file_1234": "只允许在文件的顶层中使用环境模块声明。", + "An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type_2356": "算术操作数必须为类型 \"any\"、\"number\" 或枚举类型。", + "An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_de_2705": "ES5/ES3 中的异步函数或方法需要 \"Promise\" 构造函数。确保对 \"Promise\" 构造函数进行了声明或在 \"--lib\" 选项中包含了 \"ES2015\"。", + "An_async_function_or_method_must_have_a_valid_awaitable_return_type_1057": "异步函数或方法必须具有有效的可等待返回类型。", + "An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_in_2697": "异步函数或方法必须返回 \"Promise\"。请确保具有对 \"Promise\" 的声明或在 `--lib` 选项中包括 \"ES2015\"。", + "An_async_iterator_must_have_a_next_method_2519": "异步迭代器必须具有 \"next()\" 方法。", + "An_element_access_expression_should_take_an_argument_1011": "元素访问表达式应采用参数。", + "An_enum_member_cannot_have_a_numeric_name_2452": "枚举成员不能具有数值名。", + "An_export_assignment_can_only_be_used_in_a_module_1231": "导出分配只能在模块中使用。", + "An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements_2309": "不能在具有其他导出元素的模块中使用导出分配。", + "An_export_assignment_cannot_be_used_in_a_namespace_1063": "不能在命名空间中使用导出分配。", + "An_export_assignment_cannot_have_modifiers_1120": "导出分配不能具有修饰符。", + "An_export_declaration_can_only_be_used_in_a_module_1233": "导出声明只能在模块中使用。", + "An_export_declaration_cannot_have_modifiers_1193": "导出声明不能有修饰符。", + "An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive_1198": "扩展的 Unicode 转义值必须介于(含) 0x0 和 0x10FFFF 之间。", + "An_implementation_cannot_be_declared_in_ambient_contexts_1183": "不能在环境上下文中声明实现。", + "An_import_declaration_can_only_be_used_in_a_namespace_or_module_1232": "导入声明只能在命名空间或模块中使用。", + "An_import_declaration_cannot_have_modifiers_1191": "导入声明不能有修饰符。", + "An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead_2691": "导入路径不能以“{0}”扩展名结束。考虑改为导入“{1}”。", + "An_index_expression_argument_must_be_of_type_string_number_symbol_or_any_2342": "索引表达式参数必须为 \"string\"、\"number\"、\"symbol\" 或 \"any\" 类型。", + "An_index_signature_cannot_have_a_rest_parameter_1017": "索引签名不能包含 rest 参数。", + "An_index_signature_must_have_a_type_annotation_1021": "索引签名必须具有类型批注。", + "An_index_signature_must_have_exactly_one_parameter_1096": "索引签名必须正好具有一个参数。", + "An_index_signature_parameter_cannot_have_a_question_mark_1019": "索引签名参数不能包含问号。", + "An_index_signature_parameter_cannot_have_an_accessibility_modifier_1018": "索引签名参数不能具有可访问性修饰符。", + "An_index_signature_parameter_cannot_have_an_initializer_1020": "索引签名参数不能具有初始化表达式。", + "An_index_signature_parameter_must_have_a_type_annotation_1022": "索引签名参数必须具有类型批注。", + "An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead_1336": "索引签名参数类型不能为类型别名。请考虑改为编写“[{0}: {1}]:{2}”。", + "An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead_1337": "索引签名参数类型不能为联合类型。请考虑改用映射的对象类型。", + "An_index_signature_parameter_type_must_be_string_or_number_1023": "索引签名参数类型必须为 \"string\" 或 \"number\"。", + "An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments_2499": "接口只能扩展具有可选类型参数的标识符/限定名称。", + "An_interface_may_only_extend_a_class_or_another_interface_2312": "接口只能扩展类或其他接口。", + "An_interface_property_cannot_have_an_initializer_1246": "接口函数不能具有初始化表达式。", + "An_iterator_must_have_a_next_method_2489": "迭代器必须具有 \"next()\" 方法。", + "An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name_1118": "对象文字不能具有多个具有相同名称的 get/set 访问器。", + "An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode_1117": "严格模式下,对象文字不能包含多个具有相同名称的属性。", + "An_object_literal_cannot_have_property_and_accessor_with_the_same_name_1119": "对象文字不能包含具有相同名称的属性和访问器。", + "An_object_member_cannot_be_declared_optional_1162": "对象成员无法声明为可选。", + "An_overload_signature_cannot_be_declared_as_a_generator_1222": "重载签名无法声明为生成器。", + "An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_ex_17006": "乘方表达式的左侧不允许存在具有“{0}”运算符的一元表达式。请考虑用括号将表达式括起。", + "Annotate_everything_with_types_from_JSDoc_95043": "使用 JSDoc 中的类型批注所有内容", + "Annotate_with_type_from_JSDoc_95009": "通过 JSDoc 类型批注", + "Annotate_with_types_from_JSDoc_95010": "使用 JSDoc 中的类型批注", + "Argument_expression_expected_1135": "应为参数表达式。", + "Argument_for_0_option_must_be_Colon_1_6046": "“{0}”选项的参数必须为 {1}。", + "Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_2345": "类型“{0}”的参数不能赋给类型“{1}”的参数。", + "Array_element_destructuring_pattern_expected_1181": "应为数组元素析构模式。", + "Asterisk_Slash_expected_1010": "应为 \"*/\"。", + "Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_2669": "全局范围的扩大仅可直接嵌套在外部模块中或环境模块声明中。", + "Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambien_2670": "全局范围的扩大应具有 \"declare\" 修饰符,除非它们显示在已有的环境上下文中。", + "Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using__6140": "项目“{0}”中启用了键入内容的自动发现。使用缓存位置“{2}”运行模块“{1}”的额外解决传递。", + "Base_class_expressions_cannot_reference_class_type_parameters_2562": "基类表达式无法引用类类型参数。", + "Base_constructor_return_type_0_is_not_a_class_or_interface_type_2509": "基构造函数返回类型“{0}”不是类或接口类型。", + "Base_constructors_must_all_have_the_same_return_type_2510": "所有的基构造函数必须具有相同的返回类型。", + "Base_directory_to_resolve_non_absolute_module_names_6083": "用于解析非绝对模块名的基目录。", + "Basic_Options_6172": "基本选项", + "Binary_digit_expected_1177": "需要二进制数字。", + "Binding_element_0_implicitly_has_an_1_type_7031": "绑定元素“{0}”隐式具有“{1}”类型。", + "Block_scoped_variable_0_used_before_its_declaration_2448": "声明之前已使用的块范围变量“{0}”。", + "Build_all_projects_including_those_that_appear_to_be_up_to_date_6368": "生成所有项目,包括那些似乎已是最新的项目", + "Build_one_or_more_projects_and_their_dependencies_if_out_of_date_6364": "生成一个或多个项目及其依赖项(如果已过期)", + "Building_project_0_6358": "正在生成项目“{0}”...", + "Call_decorator_expression_90028": "调用修饰器表达式", + "Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7020": "缺少返回类型批注的调用签名隐式具有返回类型 \"any\"。", + "Call_target_does_not_contain_any_signatures_2346": "调用目标不包含任何签名。", + "Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_p_2713": "无法访问“{0}.{1}”,因为“{0}”是类型,不是命名空间。是否要使用“{0}[\"{1}\"]”检索“{0}”中“{1}”属性的类型?", + "Cannot_assign_a_0_constructor_type_to_a_1_constructor_type_2672": "不可将“{0}”构造函数类型分配给“{1}”构造函数类型。", + "Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type_2517": "无法将抽象构造函数类型分配给非抽象构造函数类型。", + "Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property_2540": "无法分配到“{0}”,因为它是常数或只读属性。", + "Cannot_assign_to_0_because_it_is_not_a_variable_2539": "无法分配到“{0}”,因为它不是变量。", + "Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity_2671": "无法扩大模块“{0}”,因为它解析为非模块实体。", + "Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity_2649": "无法扩充具有值导出的模块“{0}”,因为它解析为一个非模块的实体。", + "Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system_6131": "无法使用选项“{0}”来编译模块,除非 \"--module\" 标记为 \"amd\" 或 \"system\"。", + "Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided_1208": "提供 \"--isolatedModules\" 标志时无法编译命名空间。", + "Cannot_create_an_instance_of_an_abstract_class_2511": "无法创建抽象类的实例。", + "Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module_2661": "无法导出“{0}”。仅可从模块中导出本地声明。", + "Cannot_extend_a_class_0_Class_constructor_is_marked_as_private_2675": "无法扩展类“{0}”。类构造函数标记为私有。", + "Cannot_extend_an_interface_0_Did_you_mean_implements_2689": "无法扩展接口‘{0}’。您的意思是‘实施’吗?", + "Cannot_find_a_tsconfig_json_file_at_the_specified_directory_Colon_0_5057": "无法在指定目录找到 tsconfig.json 文件:“{0}”。", + "Cannot_find_global_type_0_2318": "找不到全局类型“{0}”。", + "Cannot_find_global_value_0_2468": "找不到全局值“{0}”。", + "Cannot_find_lib_definition_for_0_2726": "找不到“{0}”的 LIB 定义。", + "Cannot_find_lib_definition_for_0_Did_you_mean_1_2727": "找不到“{0}”的 LIB 定义。你是指“{1}”?", + "Cannot_find_module_0_2307": "找不到模块“{0}”。", + "Cannot_find_name_0_2304": "找不到名称“{0}”。", + "Cannot_find_name_0_Did_you_mean_1_2552": "找不到名称“{0}”。你是否指的是“{1}”?", + "Cannot_find_name_0_Did_you_mean_the_instance_member_this_0_2663": "找不到名称“{0}”。你的意思是实例成员“this.{0}”?", + "Cannot_find_name_0_Did_you_mean_the_static_member_1_0_2662": "找不到名称“{0}”。你的意思是静态成员“{1}.{0}”?", + "Cannot_find_namespace_0_2503": "找不到命名空间“{0}”。", + "Cannot_find_parameter_0_1225": "找不到参数“{0}”。", + "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009": "找不到输入文件的公共子目录路径。", + "Cannot_find_type_definition_file_for_0_2688": "找不到“{0}”的类型定义文件。", + "Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1_6137": "无法导入类型声明文件。请考虑导入“{0}”,而不是“{1}”。", + "Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1_2481": "无法在块范围声明“{1}”所在的范围内初始化外部范围变量“{0}”。", + "Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatur_2349": "无法调用类型缺少调用签名的表达式。类型“{0}”没有兼容的调用签名。", + "Cannot_invoke_an_object_which_is_possibly_null_2721": "不能调用可能是 \"null\" 的对象。", + "Cannot_invoke_an_object_which_is_possibly_null_or_undefined_2723": "不能调用可能是 \"null\" 或“未定义”的对象。", + "Cannot_invoke_an_object_which_is_possibly_undefined_2722": "不能调用可能是“未定义”的对象。", + "Cannot_prepend_project_0_because_it_does_not_have_outFile_set_6308": "无法为项目“{0}”添加前缀,因为它未设置 \"outFile\"", + "Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205": "提供 \"--isolatedModules\" 标记时无法重新导出类型。", + "Cannot_read_file_0_Colon_1_5012": "无法读取文件“{0}”: {1}。", + "Cannot_redeclare_block_scoped_variable_0_2451": "无法重新声明块范围变量“{0}”。", + "Cannot_redeclare_exported_variable_0_2323": "无法重新声明导出的变量“{0}”。", + "Cannot_redeclare_identifier_0_in_catch_clause_2492": "无法在 catch 子句中重新声明标识符“{0}”。", + "Cannot_use_JSX_unless_the_jsx_flag_is_provided_17004": "无法使用 JSX,除非提供了 \"--jsx\" 标志。", + "Cannot_use_imports_exports_or_module_augmentations_when_module_is_none_1148": "当 \"--module\" 为 \"none\" 时无法使用导入、导出或模块扩大。", + "Cannot_use_namespace_0_as_a_type_2709": "不能将命名空间“{0}”用作类型。", + "Cannot_use_namespace_0_as_a_value_2708": "不能将命名空间“{0}”用作值。", + "Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature_2351": "其类型缺少调用或构造签名的表达式无法使用 \"new\"。", + "Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files_5056": "无法写入文件“{0}”,因为它会被多个输入文件覆盖。", + "Cannot_write_file_0_because_it_would_overwrite_input_file_5055": "无法写入文件“{0}”,因为它会覆盖输入文件。", + "Catch_clause_variable_cannot_have_a_type_annotation_1196": "Catch 子句变量不能有类型批注。", + "Catch_clause_variable_cannot_have_an_initializer_1197": "Catch 子句变量不能有初始化表达式。", + "Change_0_to_1_90014": "将“{0}”更改为“{1}”", + "Change_all_extended_interfaces_to_implements_95038": "将所有扩展接口都更改为 \"implements\"", + "Change_all_jsdoc_style_types_to_TypeScript_95030": "将所有 jsdoc 样式类型都更改为 TypeScript", + "Change_all_jsdoc_style_types_to_TypeScript_and_add_undefined_to_nullable_types_95031": "将所有 jsdoc 样式类型都更改为 TypeScript (并将 \"| undefined\" 添加到可以为 null 的类型)", + "Change_extends_to_implements_90003": "将 \"extends\" 改为 \"implements\"", + "Change_spelling_to_0_90022": "将拼写更改为“{0}”", + "Checking_if_0_is_the_longest_matching_prefix_for_1_2_6104": "检查“{0}”是否是“{1}”-“{2}”的最长匹配前缀。", + "Circular_definition_of_import_alias_0_2303": "导入别名“{0}”的循环定义。", + "Circularity_detected_while_resolving_configuration_Colon_0_18000": "解析配置时检测到循环: {0}", + "Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_functi_2426": "类“{0}”将“{1}”定义为实例成员访问器,但扩展类“{2}”将其定义为实例成员函数。", + "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_access_2423": "类“{0}”将“{1}”定义为实例成员函数,但扩展类“{2}”将其定义为实例成员访问器。", + "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_proper_2424": "类“{0}”将“{1}”定义为实例成员函数,但扩展类“{2}”将其定义为实例成员属性。", + "Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_functi_2425": "类“{0}”将“{1}”定义为实例成员属性,但扩展类“{2}”将其定义为实例成员函数。", + "Class_0_incorrectly_extends_base_class_1_2415": "类“{0}”错误扩展基类“{1}”。", + "Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclas_2720": "类“{0}”错误实现类“{1}”。你是想扩展“{1}”并将其成员作为子类继承吗?", + "Class_0_incorrectly_implements_interface_1_2420": "类“{0}”错误实现接口“{1}”。", + "Class_0_used_before_its_declaration_2449": "类“{0}”用于其声明前。", + "Class_declarations_cannot_have_more_than_one_augments_or_extends_tag_8025": "类声明不能有多个 \"@augments\" 或 \"@extends\" 标记。", + "Class_name_cannot_be_0_2414": "类名不能为“{0}”。", + "Class_name_cannot_be_Object_when_targeting_ES5_with_module_0_2725": "使用模块 {0} 将目标设置为 ES5 时,类名称不能为 \"Object\"。", + "Class_static_side_0_incorrectly_extends_base_class_static_side_1_2417": "类静态侧“{0}”错误扩展基类静态侧“{1}”。", + "Classes_can_only_extend_a_single_class_1174": "类只能扩展一个类。", + "Classes_containing_abstract_methods_must_be_marked_abstract_2514": "包含抽象方法的类必须标记为抽象。", + "Command_line_Options_6171": "命令行选项", + "Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json_6020": "编译给定了其配置文件路径或带 \"tsconfig.json\" 的文件夹路径的项目。", + "Compiler_option_0_expects_an_argument_6044": "编译器选项“{0}”需要参数。", + "Compiler_option_0_requires_a_value_of_type_1_5024": "编译器选项“{0}”需要类型 {1} 的值。", + "Composite_projects_may_not_disable_declaration_emit_6304": "复合项目可能不会禁用声明发出。", + "Computed_property_names_are_not_allowed_in_enums_1164": "枚举中不允许计算属性名。", + "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553": "含字符串值成员的枚举中不允许使用计算值。", + "Concatenate_and_emit_output_to_single_file_6001": "连接输出并将其发出到单个文件。", + "Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_librar_4090": "“{1}”和“{2}”处找到的“{0}”的定义具有冲突。考虑安装此库的特定版本以解决冲突。", + "Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7013": "缺少返回类型批注的构造签名隐式具有返回类型 \"any\"。", + "Constructor_implementation_is_missing_2390": "缺少构造函数实现。", + "Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration_2673": "类“{0}”的构造函数是私有的,仅可在类声明中访问。", + "Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration_2674": "类“{0}”的构造函数是受保护的,仅可在类声明中访问。", + "Constructors_for_derived_classes_must_contain_a_super_call_2377": "派生类的构造函数必须包含 \"super\" 调用。", + "Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126": "未指定包含文件,并且无法确定根目录,正在跳过在 \"node_modules\" 文件夹中查找。", + "Convert_0_to_mapped_object_type_95055": "将“{0}”转换为映射对象类型", + "Convert_all_constructor_functions_to_classes_95045": "将所有构造函数都转换为类", + "Convert_all_require_to_import_95048": "将所有 \"require\" 转换为 \"import\"", + "Convert_all_to_default_imports_95035": "全部转换为默认导入", + "Convert_function_0_to_class_95002": "将函数“{0}”转换为类", + "Convert_function_to_an_ES2015_class_95001": "将函数转换为 ES2015 类", + "Convert_named_imports_to_namespace_import_95057": "将命名导入转换为命名空间导入", + "Convert_namespace_import_to_named_imports_95056": "将命名空间导入转换为命名导入", + "Convert_require_to_import_95047": "将 \"require\" 转换为 \"import\"", + "Convert_to_ES6_module_95017": "转换为 ES6 模块", + "Convert_to_default_import_95013": "转换为默认导入", + "Corrupted_locale_file_0_6051": "区域设置文件 {0} 已损坏。", + "Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type_7016": "无法找到模块“{0}”的声明文件。“{1}”隐式拥有 \"any\" 类型。", + "Could_not_write_file_0_Colon_1_5033": "无法写入文件“{0}”: {1}。", + "DIRECTORY_6038": "目录", + "Declaration_expected_1146": "应为声明。", + "Declaration_name_conflicts_with_built_in_global_identifier_0_2397": "声明名称与内置全局标识符“{0}”冲突。", + "Declaration_or_statement_expected_1128": "应为声明或语句。", + "Declare_method_0_90023": "声明方法“{0}”", + "Declare_property_0_90016": "声明属性“{0}”", + "Declare_static_method_0_90024": "声明静态方法“{0}”", + "Declare_static_property_0_90027": "声明静态属性“{0}”", + "Decorators_are_not_valid_here_1206": "修饰器在此处无效。", + "Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name_1207": "不能向多个同名的 get/set 访问器应用修饰器。", + "Default_export_of_the_module_has_or_is_using_private_name_0_4082": "模块的默认导出具有或正在使用专用名称“{0}”。", + "Delete_all_unused_declarations_95024": "删除未使用的所有声明", + "Delete_the_outputs_of_all_projects_6365": "删除所有项目的输出", + "Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react__6084": "[已弃用] 请改用 \"--jsxFactory\"。已 \"react\" JSX 发出设为目标时,请指定要为 createElement 调用的对象", + "Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file_6170": "[已弃用] 请改用 \"--outFile\"。连接并发出到单个文件的输出", + "Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files_6160": "[已弃用] 请改用 \"--skipLibCheck\"。请跳过默认库声明文件的类型检查。", + "Digit_expected_1124": "应为数字。", + "Directory_0_does_not_exist_skipping_all_lookups_in_it_6148": "目录“{0}”不存在,正在跳过该目录中的所有查找。", + "Disable_checking_for_this_file_90018": "禁用检查此文件", + "Disable_size_limitations_on_JavaScript_projects_6162": "禁用对 JavaScript 项目的大小限制。", + "Disable_strict_checking_of_generic_signatures_in_function_types_6185": "禁止严格检查函数类型中的通用签名。", + "Disallow_inconsistently_cased_references_to_the_same_file_6078": "不允许对同一文件采用大小不一致的引用。", + "Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files_6159": "请勿将三斜杠引用或导入的模块添加到已编译文件列表中。", + "Do_not_emit_comments_to_output_6009": "请勿将注释发出到输出。", + "Do_not_emit_declarations_for_code_that_has_an_internal_annotation_6056": "请勿对具有 \"@internal\" 注释的代码发出声明。", + "Do_not_emit_outputs_6010": "请勿发出输出。", + "Do_not_emit_outputs_if_any_errors_were_reported_6008": "如果报告了任何错误,请不要发出输出。", + "Do_not_emit_use_strict_directives_in_module_output_6112": "不要在模块输出中发出 \"use strict\" 指令。", + "Do_not_erase_const_enum_declarations_in_generated_code_6007": "请勿清除生成代码中的常数枚举声明。", + "Do_not_generate_custom_helper_functions_like_extends_in_compiled_output_6157": "请勿在已编译输出中生成自定义帮助程序函数,例如 \"__extends\"。", + "Do_not_include_the_default_library_file_lib_d_ts_6158": "请勿包括默认库文件(lib.d.ts)。", + "Do_not_report_errors_on_unreachable_code_6077": "不报告有关不可访问的代码的错误。", + "Do_not_report_errors_on_unused_labels_6074": "不报告有关未使用的标签的错误。", + "Do_not_resolve_the_real_path_of_symlinks_6013": "不要解析 symlink 的真实路径。", + "Do_not_truncate_error_messages_6165": "请勿删除错误消息。", + "Duplicate_declaration_0_2718": "重复声明“{0}”。", + "Duplicate_function_implementation_2393": "函数实现重复。", + "Duplicate_identifier_0_2300": "标识符“{0}”重复。", + "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_2441": "标识符“{0}”重复。编译器在模块的顶层范围中保留名称“{1}”。", + "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_func_2529": "标识符“{0}”重复。编译器在包含异步函数的模块的顶层范围中保留名称“{1}”。", + "Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions_2520": "标识符“{0}”重复。编译器使用“{1}”声明来支持异步函数。", + "Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters_2396": "标识符 \"arguments\" 重复。编译器使用 \"arguments\" 初始化 rest 参数。", + "Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_me_2543": "标识符 \"_newTarget\" 重复。编译器使用变量声明 \"_newTarget\" 来捕获 \"new.target\" 元属性引用。", + "Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference_2401": "标识符 \"_super\" 重复。编译器使用 \"_super\" 获取基类引用。", + "Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference_2399": "标识符 \"_this\" 重复。编译器使用变量声明 \"_this\" 来捕获 \"this\" 引用。", + "Duplicate_label_0_1114": "标签“{0}”重复。", + "Duplicate_number_index_signature_2375": "数字索引签名重复。", + "Duplicate_string_index_signature_2374": "字符串索引签名重复。", + "Dynamic_import_cannot_have_type_arguments_1326": "动态导入不能含有类型参数", + "Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext_1323": "仅当 \"--module\" 标志为 \"commonjs\" 或 \"esNext\" 时,才支持动态导入。", + "Dynamic_import_must_have_one_specifier_as_an_argument_1324": "动态导入必须具有一个说明符作为参数。", + "Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036": "动态导入的说明符类型必须是 \"string\",但此处类型是 \"{0}\"。", + "Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015": "元素隐式具有 \"any\" 类型,因为索引表达式的类型不为 \"number\"。", + "Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature_7017": "元素隐式具有 \"any\" 类型,因为类型“{0}”没有索引签名。", + "Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files_6164": "在输出文件的开头发出一个 UTF-8 字节顺序标记(BOM)。", + "Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file_6151": "发出包含源映射而非包含单独文件的单个文件。", + "Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap__6152": "在单个文件内发出源以及源映射;需要设置 \"--inlineSourceMap\" 或 \"--sourceMap\"。", + "Enable_all_strict_type_checking_options_6180": "启用所有严格类型检查选项。", + "Enable_project_compilation_6302": "启用项目编译", + "Enable_strict_checking_of_function_types_6186": "对函数类型启用严格检查。", + "Enable_strict_checking_of_property_initialization_in_classes_6187": "启用类中属性初始化的严格检查。", + "Enable_strict_null_checks_6113": "启用严格的 NULL 检查。", + "Enable_tracing_of_the_name_resolution_process_6085": "启用名称解析过程的跟踪。", + "Enable_verbose_logging_6366": "启用详细日志记录", + "Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for__7037": "通过为所有导入创建命名空间对象来启用 CommonJS 和 ES 模块之间的发出互操作性。表示 \"allowSyntheticDefaultImports\"。", + "Enables_experimental_support_for_ES7_async_functions_6068": "对 ES7 异步函数启用实验支持。", + "Enables_experimental_support_for_ES7_decorators_6065": "对 ES7 修饰器启用实验支持。", + "Enables_experimental_support_for_emitting_type_metadata_for_decorators_6066": "对发出修饰器的类型元数据启用实验支持。", + "Enum_0_used_before_its_declaration_2450": "枚举“{0}”用于其声明前。", + "Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations_2567": "枚举声明只能与命名空间或其他枚举声明合并。", + "Enum_declarations_must_all_be_const_or_non_const_2473": "枚举声明必须全为常数或非常数。", + "Enum_member_expected_1132": "应为枚举成员。", + "Enum_member_must_have_initializer_1061": "枚举成员必须具有初始化表达式。", + "Enum_name_cannot_be_0_2431": "枚举名不能为“{0}”。", + "Enum_type_0_has_members_with_initializers_that_are_not_literals_2535": "枚举类型“{0}”包含具有不是文本的初始值设定项的成员。", + "Examples_Colon_0_6026": "示例: {0}", + "Excessive_stack_depth_comparing_types_0_and_1_2321": "与类型“{0}”和“{1}”相比,堆栈深度过高。", + "Expected_0_1_type_arguments_provide_these_with_an_extends_tag_8027": "应为 {0}-{1} 类型参数;请为这些参数添加 \"@extends\" 标记。", + "Expected_0_arguments_but_got_1_2554": "应有 {0} 个参数,但获得 {1} 个。", + "Expected_0_arguments_but_got_1_or_more_2556": "应有 {0} 个参数,但获得的数量大于等于 {1}。", + "Expected_0_type_arguments_but_got_1_2558": "应有 {0} 个类型参数,但获得 {1} 个。", + "Expected_0_type_arguments_provide_these_with_an_extends_tag_8026": "应为 {0} 类型参数;请为这些参数添加 \"@extends\" 标记。", + "Expected_at_least_0_arguments_but_got_1_2555": "应有至少 {0} 个参数,但获得 {1} 个。", + "Expected_at_least_0_arguments_but_got_1_or_more_2557": "应有至少 {0} 个参数,但获得的数量大于等于 {1}。", + "Expected_corresponding_JSX_closing_tag_for_0_17002": "“{0}”预期的相应 JSX 结束标记。", + "Expected_corresponding_closing_tag_for_JSX_fragment_17015": "预期的 JSX 片段的相应结束标记。", + "Expected_type_of_0_field_in_package_json_to_be_string_got_1_6105": "\"package.json\" 中“{0}”字段的类型应为 \"string\",但实际为“{1}”。", + "Experimental_Options_6177": "实验性选项", + "Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_t_1219": "对修饰器的实验支持是一项将在将来版本中更改的功能。设置 \"experimentalDecorators\" 选项以删除此警告。", + "Explicitly_specified_module_resolution_kind_Colon_0_6087": "显示指定了模块解析类型:“{0}”。", + "Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or__1203": "面向 ECMAScript 模块时,不能使用导出分配。请考虑改用 \"export default\" 或另一种模块格式。", + "Export_assignment_is_not_supported_when_module_flag_is_system_1218": "当 \"--module\" 标志是 \"system\" 时不支持导出分配。", + "Export_declaration_conflicts_with_exported_declaration_of_0_2484": "导出声明与“{0}”的导出声明冲突。", + "Export_declarations_are_not_permitted_in_a_namespace_1194": "命名空间中不允许有导出声明。", + "Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_2656": "导出的外部包键入文件“{0}”不是一个模块。请与包作者联系或更新包定义。", + "Exported_external_package_typings_file_cannot_contain_tripleslash_references_Please_contact_the_pack_2654": "导出的外部包键入文件不能包含三斜线引用。请与包作者联系或更新包定义。", + "Exported_type_alias_0_has_or_is_using_private_name_1_4081": "导出的类型别名“{0}”已经或正在使用专用名称“{1}”。", + "Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4023": "导出的变量“{0}”具有或正在使用外部模块“{2}”中的名称“{1}”,但不能为其命名。", + "Exported_variable_0_has_or_is_using_name_1_from_private_module_2_4024": "导出的变量“{0}”具有或正在使用私有模块“{2}”中的名称“{1}”。", + "Exported_variable_0_has_or_is_using_private_name_1_4025": "导出的变量“{0}”具有或正在使用专用名称“{1}”。", + "Exports_and_export_assignments_are_not_permitted_in_module_augmentations_2666": "模块扩大中不允许导出和导出分配。", + "Expression_expected_1109": "应为表达式。", + "Expression_or_comma_expected_1137": "应为表达式或逗号。", + "Expression_resolves_to_super_that_compiler_uses_to_capture_base_class_reference_2402": "表达式解析为 \"_super\",编译器使用 \"_super\" 获取基类引用。", + "Expression_resolves_to_variable_declaration_0_that_compiler_uses_to_support_async_functions_2521": "表达式解析为编译器用于支持异步函数的变量声明“{0}”。", + "Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta__2544": "表达式解析为编辑器用于捕获 \"new.target\" 元属性引用的变量声明 \"_newTarget\"。", + "Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference_2400": "表达式解析为编译器用于捕获 \"this\" 引用的变量声明 \"_this\"。", + "Extract_constant_95006": "提取常数", + "Extract_function_95005": "提取函数", + "Extract_to_0_in_1_95004": "提取到 {1} 中的 {0}", + "Extract_to_0_in_1_scope_95008": "提取到 {1} 范围中的 {0}", + "Extract_to_0_in_enclosing_scope_95007": "提取到封闭范围中的 {0}", + "FILE_6035": "文件", + "FILE_OR_DIRECTORY_6040": "文件或目录", + "Failed_to_parse_file_0_Colon_1_5014": "未能分析文件“{0}”: {1}。", + "Fallthrough_case_in_switch_7029": "switch 语句中的 Fallthrough 情况。", + "File_0_does_not_exist_6096": "文件“{0}”不存在。", + "File_0_exist_use_it_as_a_name_resolution_result_6097": "文件“{0}”存在 - 将其用作名称解析结果。", + "File_0_has_an_unsupported_extension_so_skipping_it_6081": "文件“{0}”的扩展名不受支持,正在跳过。", + "File_0_has_unsupported_extension_The_only_supported_extensions_are_1_6054": "不支持文件“{0}”的扩展名。唯一支持的扩展名为 {1}。", + "File_0_is_not_a_module_2306": "文件“{0}”不是模块。", + "File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern_6307": "文件“{0}”不在项目文件列表中。项目必须列出的所有文件,或使用“包含”模式。", + "File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files_6059": "文件“{0}”不在 \"rootDir\"“{1}”下。\"rootDir\" 应包含所有源文件。", + "File_0_not_found_6053": "找不到文件“{0}”。", + "File_change_detected_Starting_incremental_compilation_6032": "检测到文件更改。正在启动增量编译...", + "File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module_80001": "文件是 CommonJS 模块;它可能会转换为 ES6 模块。", + "File_name_0_differs_from_already_included_file_name_1_only_in_casing_1149": "文件名“{0}”仅在大小写方面与包含的文件名“{1}”不同。", + "File_name_0_has_a_1_extension_stripping_it_6132": "文件名“{0}”的扩展名为“{1}”,请去除它。", + "File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildca_5065": "文件规范不能包含出现在递归目录通配符(\"*\"): “{0}”后的父目录(\"..\")。", + "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010": "文件规范不能以递归目录通配符结尾(\"**\"):“{0}”。", + "Fix_all_detected_spelling_errors_95026": "修复检测到的所有拼写错误", + "Found_0_errors_Watching_for_file_changes_6194": "找到 {0} 个错误。注意文件更改。", + "Found_1_error_Watching_for_file_changes_6193": "找到 1 个错误。注意文件更改。", + "Found_package_json_at_0_6099": "在“{0}”处找到了 \"package.json\"。", + "Found_package_json_at_0_Package_ID_is_1_6190": "在“{0}”找到了 \"package.json\"。包 ID 为“{1}”。", + "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_1250": "面向 \"ES3\" 或 \"ES5\" 时,在严格模式下,块内不允许函数声明。", + "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_d_1251": "面向 \"ES3\" 或 \"ES5\" 时,在严格模式下,块内不允许函数声明。类定义自动处于严格模式。", + "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_1252": "面向 \"ES3\" 或 \"ES5\" 时,在严格模式下,块内不允许函数声明。模块自动处于严格模式。", + "Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type_7011": "缺少返回类型批注的函数表达式隐式具有“{0}”返回类型。", + "Function_implementation_is_missing_or_not_immediately_following_the_declaration_2391": "函数实现缺失或未立即出现在声明之后。", + "Function_implementation_name_must_be_0_2389": "函数实现名称必须为“{0}”。", + "Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_ref_7024": "由于函数不具有返回类型批注并且在它的一个返回表达式中得到直接或间接引用,因此它隐式具有返回类型 \"any\"。", + "Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined_2366": "函数缺少结束返回语句,返回类型不包括 \"undefined\"。", + "Function_overload_must_be_static_2387": "函数重载必须为静态。", + "Function_overload_must_not_be_static_2388": "函数重载不能为静态。", + "Generate_get_and_set_accessors_95046": "生成 \"get\" 和 \"set\" 访问器", + "Generates_a_sourcemap_for_each_corresponding_d_ts_file_6000": "为每个相应的 \".d.ts\" 文件生成 sourcemap。", + "Generates_corresponding_d_ts_file_6002": "生成相应的 \".d.ts\" 文件。", + "Generates_corresponding_map_file_6043": "生成相应的 \".map\" 文件。", + "Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_typ_7025": "生成器隐式具有类型“{0}”,因为它不生成任何值。请考虑提供一个返回类型。", + "Generators_are_not_allowed_in_an_ambient_context_1221": "不允许在环境上下文中使用生成器。", + "Generators_are_only_available_when_targeting_ECMAScript_2015_or_higher_1220": "仅当面向 ECMAScript 2015 或更高版本时,生成器才可用。", + "Generic_type_0_requires_1_type_argument_s_2314": "泛型类型“{0}”需要 {1} 个类型参数。", + "Generic_type_0_requires_between_1_and_2_type_arguments_2707": "泛型类型“{0}”需要介于 {1} 和 {2} 类型参数之间。", + "Generic_type_instantiation_is_excessively_deep_and_possibly_infinite_2550": "泛型类型实例化过深,且可能无限。", + "Getter_and_setter_accessors_do_not_agree_in_visibility_2379": "Getter 和 Setter 访问器在可见性上不一致。", + "Global_module_exports_may_only_appear_at_top_level_1316": "全局模块导出仅可出现在顶层级别中。", + "Global_module_exports_may_only_appear_in_declaration_files_1315": "全局模块导出仅可出现声明文件中。", + "Global_module_exports_may_only_appear_in_module_files_1314": "全局模块导出仅可出现模块文件中。", + "Global_type_0_must_be_a_class_or_interface_type_2316": "全局类型“{0}”必须为类或接口类型。", + "Global_type_0_must_have_1_type_parameter_s_2317": "全局类型“{0}”必须具有 {1} 个类型参数。", + "Hexadecimal_digit_expected_1125": "应为十六进制数字。", + "Identifier_expected_0_is_a_reserved_word_in_strict_mode_1212": "应为标识符。“{0}”在严格模式下是保留字。", + "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_stric_1213": "应为标识符。“{0}”在严格模式下是保留字。类定义自动处于严格模式。", + "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode_1214": "应为标识符。“{0}”是严格模式下的保留字。模块自动处于严格模式。", + "Identifier_expected_1003": "应为标识符。", + "Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules_1216": "应为标识符。转换 ECMAScript 模块时,\"__esModule\" 保留为导出标记。", + "Ignore_this_error_message_90019": "忽略此错误信息", + "Implement_all_inherited_abstract_classes_95040": "实现继承的所有抽象类", + "Implement_all_unimplemented_interfaces_95032": "实现未实现的所有接口", + "Implement_inherited_abstract_class_90007": "实现已继承的抽象类", + "Implement_interface_0_90006": "实现接口“{0}”", + "Implements_clause_of_exported_class_0_has_or_is_using_private_name_1_4019": "导出的类“{0}”的 Implements 子句具有或正在使用专用名称“{1}”。", + "Import_0_from_module_1_90013": "从模块“{1}”导入“{0}”", + "Import_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_import_Asterisk_as_1202": "面向 ECMAScript 模块时,不能使用导入分配。请考虑改用 \"import * as ns from \"mod\"\"、\"import {a} from \"mod\"\"、\"import d from \"mod\"\" 或另一种模块格式。", + "Import_declaration_0_is_using_private_name_1_4000": "导入声明“{0}”使用的是专用名称“{1}”。", + "Import_declaration_conflicts_with_local_declaration_of_0_2440": "导入声明与“{0}”的局部声明冲突。", + "Import_declarations_in_a_namespace_cannot_reference_a_module_1147": "命名空间中的导入声明不能引用模块。", + "Import_emit_helpers_from_tslib_6139": "从 \"tslib\" 导入发出帮助程序。", + "Import_may_be_converted_to_a_default_import_80003": "导入可能会转换为默认导入。", + "Import_name_cannot_be_0_2438": "导入名称不能为“{0}”。", + "Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relati_2439": "环境模块声明中的导入或导出声明不能通过相对模块名引用模块。", + "Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_mod_2667": "模块扩大中不允许导入。请考虑将它们移动到封闭的外部模块。", + "In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066": "在环境枚举声明中,成员初始化表达式必须是常数表达式。", + "In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enu_2432": "在包含多个声明的枚举中,只有一个声明可以省略其第一个枚举元素的初始化表达式。", + "In_const_enum_declarations_member_initializer_must_be_constant_expression_2474": "在 \"const\" 枚举声明中,成员初始化表达式必须是常数表达式。", + "Include_modules_imported_with_json_extension_6197": "包括通过 \".json\" 扩展导入的模块", + "Index_signature_in_type_0_only_permits_reading_2542": "类型“{0}”中的索引签名仅允许读取。", + "Index_signature_is_missing_in_type_0_2329": "类型“{0}”中缺少索引签名。", + "Index_signatures_are_incompatible_2330": "索引签名不兼容。", + "Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local_2395": "合并声明“{0}”中的单独声明必须全为导出或全为局部声明。", + "Infer_all_types_from_usage_95023": "从使用情况推导所有类型", + "Infer_parameter_types_from_usage_95012": "根据使用情况推断参数类型", + "Infer_type_of_0_from_usage_95011": "根据使用情况推断“{0}”的类型", + "Initialize_property_0_in_the_constructor_90020": "初始化构造函数中的属性“{0}”", + "Initialize_static_property_0_90021": "初始化静态属性“{0}”", + "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301": "实例成员变量“{0}”的初始化表达式不能引用构造函数中声明的标识符“{1}”。", + "Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it_2373": "参数“{0}”的初始化表达式不能引用在它之后声明的标识符“{1}”。", + "Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value_2525": "初始化表达式没有为此绑定元素提供此任何值,且该绑定元素没有默认值。", + "Initializers_are_not_allowed_in_ambient_contexts_1039": "不允许在环境上下文中使用初始化表达式。", + "Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file_6070": "初始化 TypeScript 项目并创建 tsconfig.json 文件。", + "Insert_command_line_options_and_files_from_a_file_6030": "从文件插入命令行选项和文件。", + "Install_0_95014": "安装“{0}”", + "Install_all_missing_types_packages_95033": "安装缺少的所有类型包", + "Interface_0_cannot_simultaneously_extend_types_1_and_2_2320": "接口“{0}”不能同时扩展类型“{1}”和“{2}”。", + "Interface_0_incorrectly_extends_interface_1_2430": "接口“{0}”错误扩展接口“{1}”。", + "Interface_declaration_cannot_have_implements_clause_1176": "接口声明不能有 \"implements\" 子句。", + "Interface_name_cannot_be_0_2427": "接口名称不能为“{0}”。", + "Invalid_character_1127": "无效的字符。", + "Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augm_2665": "扩大中的模块名称无效。模块“{0}”解析到位于“{1}”处的非类型化模块,其无法扩大。", + "Invalid_module_name_in_augmentation_module_0_cannot_be_found_2664": "扩大中的模块名无效,找不到模块“{0}”。", + "Invalid_reference_directive_syntax_1084": "\"reference\" 指令语法无效。", + "Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode_1210": "“{0}”的使用无效。类定义自动处于严格模式。", + "Invalid_use_of_0_Modules_are_automatically_in_strict_mode_1215": "“{0}”的使用无效。模块自动处于严格模式。", + "Invalid_use_of_0_in_strict_mode_1100": "严格模式下“{0}”的使用无效。", + "Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name_5067": "\"jsxFactory\" 的值无效。“{0}”不是有效的标识符或限定名称。", + "Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier_5059": "\"--reactNamespace\" 的值无效。“{0}”不是有效的标识符。", + "JSDoc_0_1_does_not_match_the_extends_2_clause_8023": "JSDoc \"@{0} {1}\" 不匹配 \"extends {2}\" 子句。", + "JSDoc_0_is_not_attached_to_a_class_8022": "JSDoc \"@{0}\" 未附加到类。", + "JSDoc_may_only_appear_in_the_last_parameter_of_a_signature_8028": "JSDoc \"...\" 可能仅出现在签名的最后一个参数中。", + "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_8024": "JSDoc \"@param\" 标记具有名称 \"{0}\",但不存在具有该名称的参数。", + "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_h_8029": "JSDoc \"@param\" 标记的名称为“{0}”,但该名称没有参数。如果它为数组类型,将匹配 \"arguments\"。", + "JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags_8021": "JSDoc \"@typedef\" 标记应具有类型注释,或其后跟有 \"@property\" 或 \"@member\" 标记。", + "JSDoc_types_can_only_be_used_inside_documentation_comments_8020": "JSDoc 类型只能在文档注释内部使用。", + "JSDoc_types_may_be_moved_to_TypeScript_types_80004": "JSDoc 类型可能会移到 TypeScript 类型。", + "JSX_attribute_expected_17003": "需要 JSX 属性。", + "JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000": "只能为 JSX 属性分配非空“表达式”。", + "JSX_element_0_has_no_corresponding_closing_tag_17008": "JSX 元素“{0}”没有相应的结束标记。", + "JSX_element_attributes_type_0_may_not_be_a_union_type_2600": "JSX 元素属性类型“{0}”可能不是联合类型。", + "JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property_2607": "JSX 元素类不支持特性,因为它不具有“{0}”属性。", + "JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists_7026": "JSX 元素隐式具有类型 \"any\",因为不存在接口 \"JSX.{0}\"。", + "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602": "JSX 元素隐式具有类型 \"any\",因为不存在全局类型 \"JSX.Element\"。", + "JSX_element_type_0_does_not_have_any_construct_or_call_signatures_2604": "JSX 元素类型“{0}”不具有任何构造签名或调用签名。", + "JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements_2605": "JSX 元素类型“{0}”不是 JSX 元素的构造函数。", + "JSX_elements_cannot_have_multiple_attributes_with_the_same_name_17001": "JSX 元素不能具有多个名称相同的特性。", + "JSX_expressions_must_have_one_parent_element_2657": "JSX 表达式必须具有一个父元素。", + "JSX_fragment_has_no_corresponding_closing_tag_17014": "JSX 片段没有相应的结束标记。", + "JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma_17017": "使用内联 JSX 工厂杂注时,不支持 JSX 片段", + "JSX_fragment_is_not_supported_when_using_jsxFactory_17016": "使用 --jsxFactory 时不支持 JSX 片段", + "JSX_spread_child_must_be_an_array_type_2609": "JSX 扩展子属性必须为数组类型。", + "Jump_target_cannot_cross_function_boundary_1107": "跳转目标不能跨越函数边界。", + "KIND_6034": "种类", + "LOCATION_6037": "位置", + "Language_service_is_disabled_9004": "语言服务已禁用。", + "Left_side_of_comma_operator_is_unused_and_has_no_side_effects_2695": "逗号运算符的左侧未使用,没有任何副作用。", + "Line_break_not_permitted_here_1142": "不允许在此处换行。", + "Line_terminator_not_permitted_before_arrow_1200": "箭头前不允许有行终止符。", + "List_of_folders_to_include_type_definitions_from_6161": "包含类型定义来源的文件夹列表。", + "List_of_language_service_plugins_6181": "语言服务插件列表。", + "List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime_6168": "根文件夹列表,其组合内容表示在运行时的项目结构。", + "Loading_0_from_the_root_dir_1_candidate_location_2_6109": "正在从根目录“{1}”加载“{0}”,候选位置“{2}”。", + "Loading_module_0_from_node_modules_folder_target_file_type_1_6098": "正在从 \"node_modules\" 文件夹加载模块“{0}”,目标文件类型“{1}”。", + "Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1_6095": "正在将模块作为文件/文件夹进行加载,候选模块位置“{0}”,目标文件类型“{1}”。", + "Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1_6048": "区域设置必须采用 <语言> 或 <语言>-<区域> 形式。例如“{0}”或“{1}”。", + "Longest_matching_prefix_for_0_is_1_6108": "“{0}”的最长匹配前缀为“{1}”。", + "Looking_up_in_node_modules_folder_initial_location_0_6125": "正在在 \"node_modules\" 文件夹中查找,初始位置“{0}”。", + "Make_all_super_calls_the_first_statement_in_their_constructor_95036": "让所有 \"super()\" 调用成为构造函数中的第一个语句", + "Make_super_call_the_first_statement_in_the_constructor_90002": "在构造函数中,使 \"super()\" 调用第一个语句", + "Mapped_object_type_implicitly_has_an_any_template_type_7039": "映射的对象类型隐式地含有 \"any\" 模板类型。", + "Member_0_implicitly_has_an_1_type_7008": "成员“{0}”隐式包含类型“{1}”。", + "Merge_conflict_marker_encountered_1185": "遇到合并冲突标记。", + "Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_d_2652": "合并声明“{0}”不能包含默认导出声明。请考虑改为添加一个独立的“导出默认 {0}”声明。", + "Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constru_17013": "元属性“{0}”只能在函数声明、函数表达式或构造函数的主体中使用。", + "Method_0_cannot_have_an_implementation_because_it_is_marked_abstract_1245": "方法“{0}”不能具有实现,因为它标记为抽象。", + "Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4101": "导出接口的方法“{0}”具有或正在使用私有模块“{2}”中的名称“{1}”。", + "Method_0_of_exported_interface_has_or_is_using_private_name_1_4102": "导出接口的方法“{0}”具有或正在使用专用名称“{1}”。", + "Modifiers_cannot_appear_here_1184": "修饰符不能出现在此处。", + "Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_1340": "模块“{0}”不引用类型,但在此处用作类型。", + "Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here_1339": "模块“{0}”不引用值,但在此处用作值。", + "Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambig_2308": "模块 {0} 已导出一个名为“{1}”的成员。请考虑重新显式导出以解决歧义。", + "Module_0_has_no_default_export_1192": "模块“{0}”没有默认导出。", + "Module_0_has_no_exported_member_1_2305": "模块“{0}”没有导出的成员“{1}”。", + "Module_0_has_no_exported_member_1_Did_you_mean_2_2724": "模块“{0}”没有导出的成员“{1}”。你是否指的是“{2}”?", + "Module_0_is_hidden_by_a_local_declaration_with_the_same_name_2437": "模块“{0}”被具有相同名称的局部声明隐藏。", + "Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct_2497": "模块“{0}”解析为非模块实体,且不能使用此构造导入。", + "Module_0_uses_export_and_cannot_be_used_with_export_Asterisk_2498": "模块“{0}”使用 \"export =\" 且无法与 \"export *\" 一起使用。", + "Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified_6145": "模块“{0}”解析为“{1}”中声明的环境模块,因为未修改此文件。", + "Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1_6144": "模块“{0}”解析为文件“{1}”中本地声明的环境模块。", + "Module_0_was_resolved_to_1_but_jsx_is_not_set_6142": "模块“{0}”已解析为“{1}”,但尚未设置 \"--jsx\"。", + "Module_Resolution_Options_6174": "模块分辨率选项", + "Module_name_0_matched_pattern_1_6092": "模块名“{0}”,匹配的模式“{1}”。", + "Module_name_0_was_not_resolved_6090": "======== 未解析模块名“{0}”。========", + "Module_name_0_was_successfully_resolved_to_1_6089": "======== 模块名“{0}”已成功解析为“{1}”。========", + "Module_resolution_kind_is_not_specified_using_0_6088": "未指定模块解析类型,正在使用“{0}”。", + "Module_resolution_using_rootDirs_has_failed_6111": "使用 \"rootDirs\" 的模块解析失败。", + "Move_to_a_new_file_95049": "移动到新的文件", + "Multiple_consecutive_numeric_separators_are_not_permitted_6189": "不允许使用多个连续的数字分隔符。", + "Multiple_constructor_implementations_are_not_allowed_2392": "不允许存在多个构造函数实现。", + "NEWLINE_6061": "换行符", + "Named_property_0_of_types_1_and_2_are_not_identical_2319": "“{1}”和“{2}”类型的命名属性“{0}”不完全相同。", + "Namespace_0_has_no_exported_member_1_2694": "命名空间“{0}”没有已导出的成员“{1}”。", + "No_base_constructor_has_the_specified_number_of_type_arguments_2508": "没有任何基构造函数具有指定数量的类型参数。", + "No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2_18003": "在配置文件“{0}”中找不到任何输入。指定的 \"include\" 路径为“{1}”,\"exclude\" 路径为“{2}”。", + "Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2_2515": "非抽象类“{0}”不会实现继承自“{2}”类的抽象成员“{1}”。", + "Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1_2653": "非抽象类表达式不会实现继承自“{1}”类的抽象成员“{0}”。", + "Not_all_code_paths_return_a_value_7030": "并非所有代码路径都返回值。", + "Numeric_index_type_0_is_not_assignable_to_string_index_type_1_2413": "数字索引类型“{0}”不能赋给字符串索引类型“{1}”。", + "Numeric_separators_are_not_allowed_here_6188": "此处不允许使用数字分隔符。", + "Object_is_of_type_unknown_2571": "对象的类型为 \"unknown\"。", + "Object_is_possibly_null_2531": "对象可能为 \"null\"。", + "Object_is_possibly_null_or_undefined_2533": "对象可能为 \"null\" 或“未定义”。", + "Object_is_possibly_undefined_2532": "对象可能为“未定义”。", + "Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1_2353": "对象文字可以只指定已知属性,并且“{0}”不在类型“{1}”中。", + "Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_writ_2561": "对象文字只能指定已知的属性,但“{0}”中不存在类型“{1}”。是否要写入 {2}?", + "Object_literal_s_property_0_implicitly_has_an_1_type_7018": "对象文字的属性“{0}”隐式含有“{1}”类型。", + "Octal_digit_expected_1178": "需要八进制数字。", + "Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0_8017": "八进制文本类型必须使用 ES2015 语法。请使用语法“{0}”。", + "Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0_8018": "枚举成员初始值设定项中不允许有八进制文本。请使用语法“{0}”。", + "Octal_literals_are_not_allowed_in_strict_mode_1121": "严格模式下不允许使用八进制文本。", + "Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0_1085": "当面向 ECMAScript 5 及更高版本时,不能使用八进制文本。请使用语法“{0}”。", + "Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement_1091": "\"for...in\" 语句中只允许单个变量声明。", + "Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement_1188": "\"for...of\" 语句中只允许单个变量声明。", + "Only_a_void_function_can_be_called_with_the_new_keyword_2350": "使用 \"new\" 关键字只能调用 void 函数。", + "Only_ambient_modules_can_use_quoted_names_1035": "仅环境模块可使用带引号的名称。", + "Only_amd_and_system_modules_are_supported_alongside_0_6082": "--{0} 旁仅支持 \"amd\" 和 \"system\" 模块。", + "Only_emit_d_ts_declaration_files_6014": "仅发出 \".d.ts\" 声明文件。 ", + "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002": "类 \"extends\" 子句当前仅支持具有可选类型参数的标识符/限定名称。", + "Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword_2340": "通过 \"super\" 关键字只能访问基类的公共方法和受保护方法。", + "Operator_0_cannot_be_applied_to_types_1_and_2_2365": "运算符“{0}”不能应用于类型“{1}”和“{2}”。", + "Option_0_can_only_be_specified_in_tsconfig_json_file_6064": "仅可在 \"tsconfig.json\" 文件中指定选项“{0}”。", + "Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided_5051": "仅当提供了选项 \"--inlineSourceMap\" 或选项 \"--sourceMap\" 时,才能使用选项“{0}”。", + "Option_0_cannot_be_specified_with_option_1_5053": "选项“{0}”不能与选项“{1}”同时指定。", + "Option_0_cannot_be_specified_without_specifying_option_1_5052": "无法在不指定选项“{1}”的情况下指定选项“{0}”。", + "Option_0_cannot_be_specified_without_specifying_option_1_or_option_2_5069": "无法在不指定选项 {1} 或选项 {2} 的情况下指定选项 {0}。", + "Option_0_should_have_array_of_strings_as_a_value_6103": "选项“{0}”应将字符串数组作为一个值。", + "Option_build_must_be_the_first_command_line_argument_6369": "选项 '--build' 必须是第一个命令行参数。", + "Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES_5047": "选项 \"isolatedModules\" 只可在提供了选项 \"--module\" 或者选项 \"target\" 是 \"ES2015\" 或更高版本时使用。", + "Option_paths_cannot_be_used_without_specifying_baseUrl_option_5060": "在未指定 \"--baseUrl\" 选项的情况下,无法使用选项 \"paths\"。", + "Option_project_cannot_be_mixed_with_source_files_on_a_command_line_5042": "选项 \"project\" 在命令行上不能与源文件混合使用。", + "Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070": "在没有 \"node\" 模块解析策略的情况下,无法指定选项 \"-resolveJsonModule\"。", + "Options_0_and_1_cannot_be_combined_6370": "选项“{0}”与“{1}”不能组合在一起。", + "Options_Colon_6027": "选项:", + "Output_directory_for_generated_declaration_files_6166": "已生成声明文件的输出目录。", + "Output_file_0_from_project_1_does_not_exist_6309": "来自项目“{1}”的输出文件“{0}”不存在", + "Output_file_0_has_not_been_built_from_source_file_1_6305": "未从源文件“{1}”生成输出文件“{0}”。", + "Overload_signature_is_not_compatible_with_function_implementation_2394": "重载签名与函数实现不兼容。", + "Overload_signatures_must_all_be_abstract_or_non_abstract_2512": "重载签名必须都是抽象的或都是非抽象的。", + "Overload_signatures_must_all_be_ambient_or_non_ambient_2384": "重载签名必须全部为环境签名或非环境签名。", + "Overload_signatures_must_all_be_exported_or_non_exported_2383": "重载签名必须均导出或均不导出。", + "Overload_signatures_must_all_be_optional_or_required_2386": "重载签名必须全部为可选签名或必需签名。", + "Overload_signatures_must_all_be_public_private_or_protected_2385": "重载签名必须全部是公共签名、私有签名或受保护签名。", + "Parameter_0_cannot_be_referenced_in_its_initializer_2372": "参数“{0}”的初始化表达式中不能引用该参数自身。", + "Parameter_0_implicitly_has_an_1_type_7006": "参数“{0}”隐式具有“{1}”类型。", + "Parameter_0_is_not_in_the_same_position_as_parameter_1_1227": "参数“{0}”和参数“{1}”的位置不一样。", + "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4066": "导出接口中的调用签名的参数“{0}”具有或正在使用私有模块“{2}”中的名称“{1}”。", + "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4067": "导出接口中的调用签名的参数“{0}”具有或正在使用专用名称“{1}”。", + "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_can_4061": "导出类中的构造函数的参数“{0}”具有或正在使用外部模块“{2}”中的名称“{1}”,但不能为其命名。", + "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2_4062": "导出类中的构造函数的参数“{0}”具有或正在使用私有模块“{2}”中的名称“{1}”。", + "Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1_4063": "导出类中的构造函数的参数“{0}”具有或正在使用专用名称“{1}”。", + "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_mod_4064": "导出接口中的构造函数签名的参数“{0}”具有或正在使用私有模块“{2}”中的名称“{1}”。", + "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4065": "导出接口中的构造函数签名的参数“{0}”具有或正在使用专用名称“{1}”。", + "Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4076": "导出函数的参数“{0}”具有或正在使用外部模块 {2} 中的名称“{1}”,但不能为其命名。", + "Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2_4077": "导出函数的参数“{0}”具有或正在使用私有模块“{2}”中的名称“{1}”。", + "Parameter_0_of_exported_function_has_or_is_using_private_name_1_4078": "导出函数的参数“{0}”具有或正在使用专用名称“{1}”。", + "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4091": "来自导出接口的索引签名的参数“{0}”具有或正在使用来自私有模块“{2}”的名称“{1}”。", + "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1_4092": "来自导出接口的索引签名的参数“{0}”具有或正在使用专用名称“{1}”。", + "Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4074": "导出接口中的方法的参数“{0}”具有或正在使用私有模块“{2}”中的名称“{1}”。", + "Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4075": "导出接口中的方法的参数“{0}”具有或正在使用专用名称“{1}”。", + "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_c_4071": "导出类中的公共方法的参数“{0}”具有或正在使用外部模块“{2}”中的名称“{1}”,但不能为其命名。", + "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4072": "导出类中的公共方法的参数“{0}”具有或正在使用私有模块“{2}”中的名称“{1}”。", + "Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4073": "导出类中的公共方法的参数“{0}”具有或正在使用专用名称“{1}”。", + "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module__4068": "导出类中的公共静态方法的参数“{0}”具有或正在使用外部模块“{2}”中的名称“{1}”,但不能为其命名。", + "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4069": "导出类中的公共静态方法的参数“{0}”具有或正在使用私有模块“{2}”中的名称“{1}”。", + "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4070": "导出类中的公共静态方法的参数“{0}”具有或正在使用专用名称“{1}”。", + "Parameter_cannot_have_question_mark_and_initializer_1015": "参数不能包含问号和初始化表达式。", + "Parameter_declaration_expected_1138": "应为参数声明。", + "Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2_4036": "导出类中的公共 setter“{0}”的参数类型具有或正在使用私有模块“{2}”中的名称“{1}”。", + "Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_private_name_1_4037": "导出类中的公共 setter“{0}”的参数类型具有或正在使用专用名称“{1}”。", + "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_name_1_from_private_mod_4034": "导出类中的公共静态 setter“{0}”的参数类型具有或正在使用私有模块“{2}”中的名称“{1}”。", + "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1_4035": "导出类中的公共静态 setter“{0}”的参数类型具有或正在使用专用名称“{1}”。", + "Parse_in_strict_mode_and_emit_use_strict_for_each_source_file_6141": "以严格模式进行分析,并为每个源文件发出 \"use strict\" 指令。", + "Pattern_0_can_have_at_most_one_Asterisk_character_5061": "模式“{0}”最多只可具有一个 \"*\" 字符。", + "Prefix_0_with_an_underscore_90025": "带下划线的前缀“{0}”", + "Prefix_all_unused_declarations_with_where_possible_95025": "尽可能在所有未使用的声明前添加前缀 \"_\"", + "Print_names_of_files_part_of_the_compilation_6155": "属于编译一部分的文件的打印名称。", + "Print_names_of_generated_files_part_of_the_compilation_6154": "属于编译一部分的已生成文件的打印名称。", + "Print_the_compiler_s_version_6019": "打印编译器的版本。", + "Print_this_message_6017": "打印此消息。", + "Project_0_can_t_be_built_because_its_dependency_1_has_errors_6363": "无法生成项目“{0}”,因为其依赖项“{1}”有错误", + "Project_0_is_out_of_date_because_its_dependency_1_is_out_of_date_6353": "项目“{0}”已过期,因为其依赖项“{1}”已过期", + "Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2_6350": "项目“{0}”已过期,因为最早的输出“{1}”早于最新的输入“{2}”", + "Project_0_is_out_of_date_because_output_file_1_does_not_exist_6352": "项目“{0}”已过期,因为输出文件“{1}”不存在", + "Project_0_is_up_to_date_6361": "“{0}”项目已是最新", + "Project_0_is_up_to_date_because_newest_input_1_is_older_than_oldest_output_2_6351": "项目“{0}”已是最新,因为最新的输入“{1}”早于最早的输出“{2}”", + "Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies_6354": "项目“{0}”已是最新,拥有来自其依赖项的 .d.ts 文件", + "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202": "项目引用不能形成环形图。检测到循环: {0}", + "Projects_in_this_build_Colon_0_6355": "此生成中的项目: {0}", + "Projects_to_reference_6300": "要引用的项目", + "Property_0_does_not_exist_on_const_enum_1_2479": "\"const\" 枚举“{1}”上不存在属性“{0}”。", + "Property_0_does_not_exist_on_type_1_2339": "类型“{1}”上不存在属性“{0}”。", + "Property_0_does_not_exist_on_type_1_Did_you_forget_to_use_await_2570": "类型“{1}”上不存在属性“{0}”。是否忘记使用 \"await\"?", + "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551": "属性“{0}”在类型“{1}”上不存在。你是否指的是“{2}”?", + "Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1_2546": "属性“{0}”的声明发生冲突,并且在类型“{1}”中不可访问此属性。", + "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor_2564": "属性“{0}”没有初始化表达式,且未在构造函数中明确赋值。", + "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033": "属性“{0}”隐式具有类型 \"any\",因为其 get 访问器缺少返回类型批注。", + "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032": "属性“{0}”隐式具有类型 \"any\",因为其 set 访问器缺少参数类型批注。", + "Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2_2416": "类型“{1}”中的属性“{0}”不可分配给基类型“{2}”中的同一属性。", + "Property_0_in_type_1_is_not_assignable_to_type_2_2603": "类型“{1}”中的属性“{0}”不可分配给类型“{2}”。", + "Property_0_is_declared_but_its_value_is_never_read_6138": "已声明属性“{0}”,但从未读取其值。", + "Property_0_is_incompatible_with_index_signature_2530": "属性“{0}”与索引签名不兼容。", + "Property_0_is_missing_in_type_1_2324": "类型“{1}”中缺少属性“{0}”。", + "Property_0_is_optional_in_type_1_but_required_in_type_2_2327": "属性“{0}”在类型“{1}”中为可选,但在类型“{2}”中为必选。", + "Property_0_is_private_and_only_accessible_within_class_1_2341": "属性“{0}”为私有属性,只能在类“{1}”中访问。", + "Property_0_is_private_in_type_1_but_not_in_type_2_2325": "属性“{0}”在类型“{1}”中是私有属性,但在类型“{2}”中不是。", + "Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1_2446": "属性“{0}”受保护,只能通过类“{1}”的实例访问。", + "Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses_2445": "属性“{0}”受保护,只能在类“{1}”及其子类中访问。", + "Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2_2443": "属性“{0}”受保护,但类型“{1}”并不是从“{2}”派生的类。", + "Property_0_is_protected_in_type_1_but_public_in_type_2_2444": "属性“{0}”在类型“{1}”中受保护,但在类型“{2}”中为公共属性。", + "Property_0_is_used_before_being_assigned_2565": "在赋值前使用了属性“{0}”。", + "Property_0_of_JSX_spread_attribute_is_not_assignable_to_target_property_2606": "JSX 展开特性的“{0}”属性不能分配给目标属性。", + "Property_0_of_exported_class_expression_may_not_be_private_or_protected_4094": "导出类表达式的属性“{0}”可能不是私密或受保护的属性。", + "Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4032": "导出接口的属性“{0}”具有或正在使用私有模块“{2}”中的名称“{1}”。", + "Property_0_of_exported_interface_has_or_is_using_private_name_1_4033": "导出接口的属性“{0}”具有或正在使用专用名称“{1}”。", + "Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2_2412": "类型“{1}”的属性“{0}”不能赋给数值索引类型“{2}”。", + "Property_0_of_type_1_is_not_assignable_to_string_index_type_2_2411": "类型“{1}”的属性“{0}”不能赋给字符串索引类型“{2}”。", + "Property_assignment_expected_1136": "应为属性分配。", + "Property_destructuring_pattern_expected_1180": "应为属性析构模式。", + "Property_or_signature_expected_1131": "应为属性或签名。", + "Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_li_1328": "属性值只能是字符串文本、数字文本、\"true\"、\"false\"、\"null\"、对象文字或数组文本。", + "Provide_full_support_for_iterables_in_for_of_spread_and_destructuring_when_targeting_ES5_or_ES3_6179": "以 \"ES5\" 或 \"ES3\" 设为目标时,对 \"for-of\"、传播和析构中的可迭代项提供完全支持。", + "Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4098": "导出类的公共方法“{0}”具有或正在使用外部模块“{2}”中的名称“{1}”,但不能为其命名。", + "Public_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4099": "导出类的公共方法“{0}”具有或正在使用私有模块“{2}”中的名称“{1}”。", + "Public_method_0_of_exported_class_has_or_is_using_private_name_1_4100": "导出类的公共方法“{0}”具有或正在使用专用名称“{1}”。", + "Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_name_4029": "导出类的公共属性“{0}”具有或正在使用外部模块“{2}”中的名称“{1}”,但不能为其命名。", + "Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4030": "导出类的公共属性“{0}”具有或正在使用私有模块“{2}”中的名称“{1}”。", + "Public_property_0_of_exported_class_has_or_is_using_private_name_1_4031": "导出类的公共属性“{0}”具有或正在使用专用名称“{1}”。", + "Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_4095": "导出类的公共静态方法“{0}”具有或正在使用外部模块“{2}”中的名称“{1}”,但不能为其命名。", + "Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4096": "导出类的公共静态方法“{0}”具有或正在使用私有模块“{2}”中的名称“{1}”。", + "Public_static_method_0_of_exported_class_has_or_is_using_private_name_1_4097": "导出类的公共静态方法“{0}”具有或正在使用专用名称“{1}”。", + "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot__4026": "导出类的公共静态属性“{0}”具有或正在使用外部模块“{2}”中的名称“{1}”,但不能为其命名。", + "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4027": "导出类的公共静态属性“{0}”具有或正在使用外部模块“{2}”中的名称“{1}”。", + "Public_static_property_0_of_exported_class_has_or_is_using_private_name_1_4028": "导出类的公共静态属性“{0}”具有或正在使用专用名称“{1}”。", + "Raise_error_on_expressions_and_declarations_with_an_implied_any_type_6052": "对具有隐式 \"any\" 类型的表达式和声明引发错误。", + "Raise_error_on_this_expressions_with_an_implied_any_type_6115": "在带隐式“any\" 类型的 \"this\" 表达式上引发错误。", + "Redirect_output_structure_to_the_directory_6006": "将输出结构重定向到目录。", + "Referenced_project_0_must_have_setting_composite_Colon_true_6306": "引用的项目“{0}”必须拥有设置 \"composite\": true。", + "Remove_all_unreachable_code_95051": "删除所有无法访问的代码", + "Remove_all_unused_labels_95054": "删除所有未使用的标签", + "Remove_braces_from_arrow_function_95060": "从箭头函数中删除大括号", + "Remove_declaration_for_Colon_0_90004": "删除“{0}”的声明", + "Remove_destructuring_90009": "删除解构", + "Remove_import_from_0_90005": "从“{0}”删除导入", + "Remove_unreachable_code_95050": "删除无法访问的代码", + "Remove_unused_label_95053": "删除未使用的标签", + "Remove_variable_statement_90010": "删除变量语句", + "Replace_import_with_0_95015": "用“{0}”替换导入。", + "Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "在函数中的所有代码路径并非都返回值时报告错误。", + "Report_errors_for_fallthrough_cases_in_switch_statement_6076": "报告 switch 语句中遇到 fallthrough 情况的错误。", + "Report_errors_in_js_files_8019": ".js 文件中的报表出错。", + "Report_errors_on_unused_locals_6134": "报告未使用的局部变量上的错误。", + "Report_errors_on_unused_parameters_6135": "报告未使用的参数上的错误。", + "Required_type_parameters_may_not_follow_optional_type_parameters_2706": "所需的类型参数可能不遵循可选类型参数。", + "Resolution_for_module_0_was_found_in_cache_from_location_1_6147": "在位置“{1}”的缓存中找到模块“{0}”的解析。", + "Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols_6195": "只将 \"keyof\" 解析为字符串值的属性名称(不含数字或符号)。", + "Resolving_from_node_modules_folder_6118": "正在从 node_modules 文件夹解析...", + "Resolving_module_0_from_1_6086": "======== 正在从“{1}”解析模块“{0}”。========", + "Resolving_module_name_0_relative_to_base_url_1_2_6094": "正在相对于基 URL“{1}”-“{2}”解析模块名“{0}”。", + "Resolving_real_path_for_0_result_1_6130": "正在解析“{0}”的真实路径,结果为“{1}”。", + "Resolving_type_reference_directive_0_containing_file_1_root_directory_2_6116": "======== 正在解析类型引用指令“{0}”,包含文件“{1}”,根目录“{2}”。========", + "Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set_6123": "======== 正在解析类型引用指令“{0}”,包含文件“{1}”,未设置根目录。========", + "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1_6127": "======== 正在解析类型引用指令“{0}”,未设置包含文件,根目录“{1}”。========", + "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set_6128": "======== 正在解析类型引用指令“{0}”,未设置包含文件,未设置根目录。========", + "Resolving_using_primary_search_paths_6117": "正在使用主搜索路径解析...", + "Resolving_with_primary_search_path_0_6121": "正在使用主搜索路径“{0}”解析。", + "Rest_parameter_0_implicitly_has_an_any_type_7019": "Rest 参数“{0}”隐式具有 \"any[]\" 类型。", + "Rest_types_may_only_be_created_from_object_types_2700": "rest 类型只能从对象类型创建。", + "Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4046": "导出接口中的调用签名的返回类型具有或正在使用私有模块“{1}”中的名称“{0}”。", + "Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0_4047": "导出接口中的调用签名的返回类型具有或正在使用专用名称“{0}”。", + "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_mod_4044": "导出接口中的构造函数签名的返回类型具有或正在使用私有模块“{1}”中的名称“{0}”。", + "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0_4045": "导出接口中的构造函数签名的返回类型具有或正在使用专用名称“{0}”。", + "Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class_2409": "构造函数签名的返回类型必须可赋给类的实例类型。", + "Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named_4058": "导出函数的返回类型具有或正在使用外部模块“{1}”中的名称“{0}”,但不能为其命名。", + "Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1_4059": "导出函数的返回类型具有或正在使用私有模块“{1}”中的名称“{0}”。", + "Return_type_of_exported_function_has_or_is_using_private_name_0_4060": "导出函数的返回类型具有或正在使用专用名称“{0}”。", + "Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4048": "导出接口中的索引签名的返回类型具有或正在使用私有模块“{1}”中的名称“{0}”。", + "Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0_4049": "导出接口中的索引签名的返回类型具有或正在使用专用名称“{0}”。", + "Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4056": "导出接口中的方法的返回类型具有或正在使用私有模块“{1}”中的名称“{0}”。", + "Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0_4057": "导出接口中的方法的返回类型具有或正在使用专用名称“{0}”。", + "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_4041": "导出类中的公共 getter“{0}”的返回类型具有或正在使用外部模块“{2}”中的名称“{1}”,但不能为其命名。", + "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2_4042": "导出类中的公共 getter“{0}”的返回类型具有或正在使用私有模块“{2}”中的名称“{1}”。", + "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_private_name_1_4043": "导出类中的公共 getter“{0}”的返回类型具有或正在使用专用名称“{1}”。", + "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_c_4053": "导出类中的公共方法的返回类型具有或正在使用外部模块“{1}”中的名称“{0}”,但不能为其命名。", + "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4054": "导出类中的公共方法的返回类型具有或正在使用私有模块“{1}”中的名称“{0}”。", + "Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0_4055": "导出类中的公共方法的返回类型具有或正在使用专用名称“{0}”。", + "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_external_modul_4038": "导出类中的公共静态 getter“{0}”的返回类型具有或正在使用外部模块“{2}”中的名称“{1}”,但不能为其命名。", + "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_4039": "导出类中的公共静态 getter“{0}”的返回类型具有或正在使用私有模块“{2}”中的名称“{1}”。", + "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_private_name_1_4040": "导出类中的公共静态 getter“{0}”的返回类型具有或正在使用专用名称“{1}”。", + "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module__4050": "导出类中的公共静态方法的返回类型具有或正在使用外部模块“{1}”中的名称“{0}”,但不能为其命名。", + "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4051": "导出类中的公共静态方法的返回类型具有或正在使用私有模块“{1}”中的名称“{0}”。", + "Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0_4052": "导出类中的公共静态方法的返回类型具有或正在使用专用名称“{0}”。", + "Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program_6184": "重用源自“{0}”的模块解析,因为解析在旧程序中未更改。", + "Reusing_resolution_of_module_0_to_file_1_from_old_program_6183": "对文件“{1}”重用旧程序中模块 “{0}”的解析。", + "Rewrite_all_as_indexed_access_types_95034": "全部重写为索引访问类型", + "Rewrite_as_the_indexed_access_type_0_90026": "重写为索引访问类型“{0}”", + "Root_directory_cannot_be_determined_skipping_primary_search_paths_6122": "无法确定根目录,正在跳过主搜索路径。", + "STRATEGY_6039": "策略", + "Scoped_package_detected_looking_in_0_6182": "检测到范围包,请在“{0}”中查看", + "Setters_cannot_return_a_value_2408": "Setter 不能返回值。", + "Show_all_compiler_options_6169": "显示所有编译器选项。", + "Show_diagnostic_information_6149": "显示诊断信息。", + "Show_verbose_diagnostic_information_6150": "显示详细的诊断信息。", + "Show_what_would_be_built_or_deleted_if_specified_with_clean_6367": "显示将生成(如果指定有 '--clean',则删除)什么", + "Signature_0_must_be_a_type_predicate_1224": "签名“{0}”必须为类型谓词。", + "Skip_type_checking_of_declaration_files_6012": "跳过声明文件的类型检查。", + "Skipping_build_of_project_0_because_its_dependency_1_has_errors_6362": "正在跳过项目“{0}”的生成,因为其依赖项“{1}”有错误", + "Skipping_clean_because_not_all_projects_could_be_located_6371": "正在跳过清理,因为并非所有项目都可找到", + "Source_Map_Options_6175": "源映射选项", + "Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature_2382": "指定的重载签名不可分配给任何非专用化签名。", + "Specifier_of_dynamic_import_cannot_be_spread_element_1325": "动态导入的说明符不能是扩散元素。", + "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_or_ESNEXT_6015": "指定 ECMAScript 目标版本: \"ES3\" (默认)、\"ES5\"、\"ES2015\"、\"ES2016\"、\"ES2017\"、\"ES2018\" 或 \"ESNEXT\"。", + "Specify_JSX_code_generation_Colon_preserve_react_native_or_react_6080": "指定 JSX 代码生成: \"preserve\"、\"react-native\" 或 \"react\"。", + "Specify_library_files_to_be_included_in_the_compilation_6079": "指定要在编译中包括的库文件。", + "Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext_6016": "指定模块代码生成: \"none\"、\"commonjs\"、\"amd\"、\"system\"、\"umd\"、\"es2015\"或 \"ESNext\"。", + "Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6_6069": "指定模块解析策略: \"node\" (Node.js)或 \"classic\" (TypeScript pre-1.6)。", + "Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h_6146": "指定在设定 \"react\" JSX 发出目标时要使用的 JSX 工厂函数,例如 \"react.createElement\" 或 \"h\"。", + "Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix_6060": "指定发出文件时要使用的行序列结尾: \"CRLF\" (dos)或 \"LF\" (unix)。", + "Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations_6004": "指定调试调试程序应将 TypeScript 文件放置到的位置而不是源位置。", + "Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations_6003": "指定调试程序应将映射文件放置到的位置而不是生成的位置。", + "Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir_6058": "指定输入文件的根目录。与 --outDir 一起用于控制输出目录结构。", + "Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher_2472": "仅当面向 ECMAScript 5 和更高版本时,\"new\" 表达式中的展开运算符才可用。", + "Spread_types_may_only_be_created_from_object_types_2698": "spread 类型只能从对象类型创建。", + "Starting_compilation_in_watch_mode_6031": "在监视模式下开始编译...", + "Statement_expected_1129": "应为语句。", + "Statements_are_not_allowed_in_ambient_contexts_1036": "不允许在环境上下文中使用语句。", + "Static_members_cannot_reference_class_type_parameters_2302": "静态成员不能引用类类型参数。", + "Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1_2699": "静态属性“{0}”与构造函数“{1}”的内置属性函数“{0}”冲突。", + "Strict_Type_Checking_Options_6173": "严格类型检查选项", + "String_literal_expected_1141": "应为字符串文本。", + "String_literal_with_double_quotes_expected_1327": "应为带双引号的字符串文字。", + "Stylize_errors_and_messages_using_color_and_context_experimental_6073": "使用颜色和上下文风格化错误和消息(实验)。", + "Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_t_2717": "后续属性声明必须属于同一类型。属性“{0}”的类型必须为“{1}”,但此处却为类型“{2}”。", + "Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_t_2403": "后续变量声明必须属于同一类型。变量“{0}”必须属于类型“{1}”,但此处却为类型“{2}”。", + "Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2_5064": "模式“{1}”的替换“{0}”类型不正确,应为 \"string\",实际为“{2}”。", + "Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character_5062": "模式“{1}”中的替换“{0}”最多只可具有一个 \"*\" 字符。", + "Substitutions_for_pattern_0_should_be_an_array_5063": "模式“{0}”的替代应为数组。", + "Substitutions_for_pattern_0_shouldn_t_be_an_empty_array_5066": "模式“{0}”的替换模式不应为空数组。", + "Successfully_created_a_tsconfig_json_file_6071": "已成功创建 tsconfig.json 文件。", + "Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors_2337": "不允许在构造函数外部或在构造函数内的嵌套函数中进行 Super 调用。", + "Suppress_excess_property_checks_for_object_literals_6072": "取消对象文字的多余属性检查。", + "Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures_6055": "抑制缺少索引签名的索引对象的 noImplicitAny 错误。", + "Symbol_reference_does_not_refer_to_the_global_Symbol_constructor_object_2470": "\"Symbol\" 引用不是指全局符号构造函数对象。", + "Syntax_Colon_0_6023": "语法: {0}", + "The_0_operator_cannot_be_applied_to_type_symbol_2469": "“{0}”运算符不能应用于类型 \"symbol\"。", + "The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead_2447": "“{0}”运算符不允许用于布尔类型。请考虑改用“{1}”。", + "The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead_2696": "\"Object\" 类型可分配给极少数其他类型。是否想要改用“任意”类型?", + "The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_stand_2496": "ES3 和 ES5 中的箭头函数不能引用 \"arguments\" 对象。请考虑使用标准函数表达式。", + "The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_usi_2522": "ES3 和 ES5 中的异步函数或方法不能引用“参数”对象。请考虑使用标准函数或方法。", + "The_body_of_an_if_statement_cannot_be_the_empty_statement_1313": "\"if\" 语句的正文不能为空语句。", + "The_character_set_of_the_input_files_6163": "输入文件的字符集。", + "The_containing_function_or_module_body_is_too_large_for_control_flow_analysis_2563": "包含函数或模块体对于控制流分析而言太大。", + "The_current_host_does_not_support_the_0_option_5001": "当前主机不支持“{0}”选项。", + "The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context_2714": "导出分配的表达式必须是环境上下文中的标识符或限定的名称。", + "The_files_list_in_config_file_0_is_empty_18002": "配置文件“{0}”中的 \"files\" 列表为空。", + "The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback_1060": "承诺的 \"then\" 方法的第一个参数必须是回调。", + "The_global_type_JSX_0_may_not_have_more_than_one_property_2608": "全局类型 \"JSX.{0}\" 不可具有多个属性。", + "The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_option_1343": "\"import.meta\" 元属性仅允许对 \"target\" 和 \"module\" 编译器选项使用 \"ESNext\"。", + "The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary_2527": "“{0}”的推断类型引用不可访问的“{1}”类型。需要类型批注。", + "The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern_2491": "\"for...in\" 语句的左侧不能为析构模式。", + "The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation_2404": "\"for...in\" 语句的左侧不能使用类型批注。", + "The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access_2406": "\"for...in\" 语句的左侧必须是变量或属性访问。", + "The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any_2405": "\"for...in\" 语句的左侧必须是 \"string\" 或 \"any\" 类型。", + "The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation_2483": "\"for...of\" 语句的左侧不能使用类型批注。", + "The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access_2487": "\"for...of\" 语句的左侧必须是变量或属性访问。", + "The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type_2362": "算术运算左侧必须是 \"any\"、\"number\" 或枚举类型。", + "The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access_2364": "赋值表达式的左侧必须是变量或属性访问。", + "The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol_2360": "\"in\" 表达式左侧的类型必须为 \"any\"、\"string\"、\"number\" 或 \"symbol\"。", + "The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_paramete_2358": "\"instanceof\" 表达式左侧必须是 \"any\" 类型、对象类型或类型参数。", + "The_locale_used_when_displaying_messages_to_the_user_e_g_en_us_6156": "向用户显示消息时所用的区域设置(例如,\"en-us\")", + "The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files_6136": "用于搜索 node_modules 和加载 JavaScript 文件的最大依赖项深度。", + "The_operand_of_a_delete_operator_cannot_be_a_read_only_property_2704": "删除运算符的操作数不能是只读属性。", + "The_operand_of_a_delete_operator_must_be_a_property_reference_2703": "删除运算符的操作数必须是属性引用。", + "The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access_2357": "递增或递减运算符的操作数必须是变量或属性访问。", + "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601": "JSX 元素构造函数的返回类型必须返回对象类型。", + "The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any_1237": "参数修饰器函数的返回类型必须为 \"void\" 或 \"any\"。", + "The_return_type_of_a_property_decorator_function_must_be_either_void_or_any_1236": "属性修饰器函数的返回类型必须为 \"void\" 或 \"any\"。", + "The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_t_1058": "异步函数的返回类型必须是有效承诺,或不得包含可调用的 \"then\" 成员。 ", + "The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_1064": "异步函数或方法的返回类型必须为全局 Promise 类型。", + "The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_but_2407": "\"for...in\" 语句右侧必须是 \"any\" 类型、对象类型或类型参数,但此处的类型为“{0}”。", + "The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type_2363": "算术运算右侧必须是 \"any\"、\"number\" 或枚举类型。", + "The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter_2361": "\"in\" 表达式的右侧必须是 \"any\" 类型、对象类型或类型参数。", + "The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_F_2359": "\"instanceof\" 表达式的右侧必须属于类型 \"any\",或属于可分配给 \"Function\" 接口类型的类型。", + "The_specified_path_does_not_exist_Colon_0_5058": "指定的路径不存在:“{0}”。", + "The_target_of_an_assignment_must_be_a_variable_or_a_property_access_2541": "赋值的目标必须是变量或属性访问。", + "The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access_2701": "对象 rest 分配的目标必须是变量或属性访问。", + "The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1_2684": "类型为“{0}”的 \"this\" 上下文不能分配给类型为“{1}”的方法的 \"this\"。", + "The_this_types_of_each_signature_are_incompatible_2685": "每个签名的 \"this\" 类型不兼容。", + "The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_typ_2453": "无法从用法推断类型形参“{0}”的类型实参。可以考虑显式指定类型实参。", + "The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value__2547": "异步迭代器的 \"next()\" 方法返回的类型必须是具有 \"value\" 属性的类型的承诺。", + "The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property_2490": "迭代器的 \"next()\" 方法返回的类型必须具有 \"value\" 属性。", + "The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer_1189": "\"for...in\" 语句的变量声明不能有初始化表达式。", + "The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer_1190": "\"for...of\" 语句的变量声明不能有初始化表达式。", + "The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any_2410": "不支持 \"with\" 语句。\"with\" 程序块中的所有符号都将具有类型 \"any\"。", + "This_constructor_function_may_be_converted_to_a_class_declaration_80002": "此构造函数可能会转换为类声明。", + "This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found_2354": "此语法需要一个导入的帮助程序,但找不到模块“{0}”。", + "This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1_2343": "此语法需要一个名为“{1}”的导入帮助程序,但模块“{0}”没有导出的成员“{1}”。", + "Trailing_comma_not_allowed_1009": "不允许使用尾随逗号。", + "Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule_6153": "将每个文件转换为单独的模块(类似 \"ts.transpileModule\")。", + "Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_mod_7035": "尝试 \"npm install @types/{0}\" (如果存在),或者添加一个包含“声明模块‘{0}’”的新声明文件(.d.ts);", + "Trying_other_entries_in_rootDirs_6110": "正在尝试 \"rootDirs\" 中的其他条目。", + "Trying_substitution_0_candidate_module_location_Colon_1_6093": "正在尝试替换“{0}”,候选模块位置:“{1}”。", + "Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2_2493": "不能将长度为“{1}”的元组类型“{0}”分配给长度为“{2}”的元组。", + "Type_0_cannot_be_converted_to_type_1_2352": "类型“{0}”不可转换为类型“{1}”。", + "Type_0_cannot_be_used_as_an_index_type_2538": "类型“{0}”不能作为索引类型使用。", + "Type_0_cannot_be_used_to_index_type_1_2536": "类型“{0}”无法用于索引类型“{1}”。", + "Type_0_does_not_satisfy_the_constraint_1_2344": "类型“{0}”不满足约束“{1}”。", + "Type_0_has_no_matching_index_signature_for_type_1_2537": "类型“{0}”没有匹配的类型“{1}”的索引签名。", + "Type_0_has_no_properties_in_common_with_type_1_2559": "类型“{0}”与类型“{1}”不具有相同的属性。", + "Type_0_has_no_property_1_2460": "类型“{0}”不具有属性“{1}”。", + "Type_0_has_no_property_1_and_no_string_index_signature_2459": "类型“{0}”不具有属性“{1}”和字符串索引签名。", + "Type_0_is_not_a_constructor_function_type_2507": "类型“{0}”不是构造函数类型。", + "Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Prom_1055": "类型“{0}”不是 ES5/ES3 中的有效异步函数返回类型,因为其未引用与 Promise 相符的构造函数值。", + "Type_0_is_not_an_array_type_2461": "类型“{0}”不是数组类型。", + "Type_0_is_not_an_array_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators_2568": "类型“{0}”不是数组类型。请使用编译器选项 \"--downlevelIteration\" 允许迭代器进行迭代。", + "Type_0_is_not_an_array_type_or_a_string_type_2495": "类型“{0}”不是数组类型或字符串类型。", + "Type_0_is_not_an_array_type_or_a_string_type_Use_compiler_option_downlevelIteration_to_allow_iterati_2569": "类型“{0}”不是数组类型或字符串类型。请使用编译器选项 \"--downlevelIteration\" 允许迭代器进行迭代。", + "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549": "类型“{0}”不是数组类型或字符串类型,或者没有返回迭代器的 \"[Symbol.iterator]()\" 方法。", + "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548": "类型“{0}”不是数组类型,或者没有返回迭代器的 \"[Symbol.iterator]()\" 方法。", + "Type_0_is_not_assignable_to_type_1_2322": "不能将类型“{0}”分配给类型“{1}”。", + "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_2719": "类型“{0}”无法分配给类型“{1}”。存在具有此名称的两种不同类型,但它们是不相关的。", + "Type_0_is_not_comparable_to_type_1_2678": "类型“{0}”不可与类型“{1}”进行比较。", + "Type_0_is_not_generic_2315": "类型“{0}”不是泛型类型。", + "Type_0_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator_2504": "类型“{0}”必须具有返回异步迭代器的 \"[Symbol.asyncIterator]()\" 方法。", + "Type_0_must_have_a_Symbol_iterator_method_that_returns_an_iterator_2488": "类型“{0}”必须具有返回迭代器的 \"[Symbol.iterator]()\" 方法。", + "Type_0_provides_no_match_for_the_signature_1_2658": "类型“{0}”提供的内容与签名“{1}”不匹配。", + "Type_0_recursively_references_itself_as_a_base_type_2310": "类型“{0}”以递归方式将自身引用为基类。", + "Type_alias_0_circularly_references_itself_2456": "类型别名“{0}”循环引用自身。", + "Type_alias_name_cannot_be_0_2457": "类型别名不能为“{0}”。", + "Type_annotation_cannot_appear_on_a_constructor_declaration_1093": "类型批注不能出现在构造函数声明中。", + "Type_argument_candidate_1_is_not_a_valid_type_argument_because_it_is_not_a_supertype_of_candidate_0_2455": "候选类型参数“{1}”不是有效的类型参数,因为它不是候选“{0}”的超类型。", + "Type_argument_expected_1140": "应为类型参数。", + "Type_argument_list_cannot_be_empty_1099": "类型参数列表不能为空。", + "Type_arguments_cannot_be_used_here_1342": "无法在此处使用类型参数。", + "Type_declaration_files_to_be_included_in_compilation_6124": "要包含在编译中类型声明文件。", + "Type_expected_1110": "应为类型。", + "Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method_1062": "类型在其自身的 \"then\" 方法的 fulfillment 回调中被直接或间接引用。", + "Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member_1320": "\"await\" 操作数的类型必须是有效承诺,或不得包含可调用的 \"then\" 成员。", + "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322": "\"yield*\" 操作数的迭代元素的类型必须是有效承诺,或不得包含可调用的 \"then\" 成员。", + "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321": "异步生成器中 \"yield\" 操作数的类型必须是有效承诺,或不得包含可调用的 \"then\" 成员。", + "Type_parameter_0_has_a_circular_constraint_2313": "类型参数“{0}”具有循环约束。", + "Type_parameter_0_has_a_circular_default_2716": "类型参数“{0}”具有循环默认值。", + "Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4008": "导出接口中的调用签名的类型参数“{0}”具有或正在使用专用名称“{1}”。", + "Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4006": "导出接口中的构造函数签名的类型参数“{0}”具有或正在使用专用名称“{1}”。", + "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002": "导出类的类型参数“{0}”具有或正在使用专用名称“{1}”。", + "Type_parameter_0_of_exported_function_has_or_is_using_private_name_1_4016": "导出函数的类型参数“{0}”具有或正在使用专用名称“{1}”。", + "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004": "导出接口的类型参数“{0}”具有或正在使用专用名称“{1}”。", + "Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1_4083": "已导出类型别名的类型参数“{0}”具有或正使用专用名称“{1}”。", + "Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4014": "导出接口中的方法的类型参数“{0}”具有或正在使用专用名称“{1}”。", + "Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4012": "导出类中的公共方法的类型参数“{0}”具有或正在使用专用名称“{1}”。", + "Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4010": "导出类中的公共静态方法的类型参数“{0}”具有或正在使用专用名称“{1}”。", + "Type_parameter_declaration_expected_1139": "应为类型参数声明。", + "Type_parameter_list_cannot_be_empty_1098": "类型参数列表不能为空。", + "Type_parameter_name_cannot_be_0_2368": "类型参数名称不能为“{0}”。", + "Type_parameters_cannot_appear_on_a_constructor_declaration_1092": "类型参数不能出现在构造函数声明中。", + "Type_predicate_0_is_not_assignable_to_1_1226": "类型谓词“{0}”不可分配给“{1}”。", + "Type_reference_directive_0_was_not_resolved_6120": "======== 未解析类型引用指令“{0}”。========", + "Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2_6119": "======== 类型引用指令“{0}”已成功解析为“{1}”,主要: {2}。========", + "Types_have_separate_declarations_of_a_private_property_0_2442": "类型具有私有属性“{0}”的单独声明。", + "Types_of_parameters_0_and_1_are_incompatible_2328": "参数“{0}”和“{1}” 的类型不兼容。", + "Types_of_property_0_are_incompatible_2326": "属性“{0}”的类型不兼容。", + "Unable_to_open_file_0_6050": "无法打开文件“{0}”。", + "Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression_1238": "作为表达式调用时,无法解析类修饰器的签名。", + "Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression_1241": "作为表达式调用时,无法解析方法修饰器的签名。", + "Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression_1239": "作为表达式调用时,无法解析参数修饰器的签名。", + "Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression_1240": "作为表达式调用时,无法解析属性修饰器的签名。", + "Unexpected_end_of_text_1126": "文本意外结束。", + "Unexpected_token_1012": "意外的标记。", + "Unexpected_token_A_constructor_method_accessor_or_property_was_expected_1068": "意外的标记。应为构造函数、方法、访问器或属性。", + "Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces_1069": "意外的标记。类型参数名不应包含大括号。", + "Unexpected_token_expected_1179": "意外标记。应为 \"{\"。", + "Unknown_compiler_option_0_5023": "未知的编译器选项“{0}”。", + "Unknown_option_excludes_Did_you_mean_exclude_6114": "未知的 \"excludes\" 选项。你的意思是 \"exclude\"?", + "Unknown_type_acquisition_option_0_17010": "未知类型获取选项“{0}”。", + "Unreachable_code_detected_7027": "检测到无法访问的代码。", + "Unsupported_locale_0_6049": "区域设置“{0}”不受支持。", + "Unterminated_Unicode_escape_sequence_1199": "未终止的 Unicode 转义序列。", + "Unterminated_quoted_string_in_response_file_0_6045": "响应文件“{0}”中引号不配对。", + "Unterminated_regular_expression_literal_1161": "未终止的正则表达式文本。", + "Unterminated_string_literal_1002": "未终止的字符串文本。", + "Unterminated_template_literal_1160": "未终止的模板文本。", + "Untyped_function_calls_may_not_accept_type_arguments_2347": "非类型化函数调用不能接受类型参数。", + "Unused_label_7028": "未使用的标签。", + "Updating_output_timestamps_of_project_0_6359": "正在更新项目“{0}”的输出时间戳...", + "Use_synthetic_default_member_95016": "使用综合的“默认”成员。", + "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494": "仅 ECMAScript 5 和更高版本支持在 \"for...of\" 语句中使用字符串。", + "VERSION_6036": "版本", + "Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it_2560": "类型“{0}”的值没有与类型“{1}”相同的属性。你是想调用它吗?", + "Value_of_type_0_is_not_callable_Did_you_mean_to_include_new_2348": "类型“{0}”的值不可调用。是否希望包括 \"new\"?", + "Variable_0_implicitly_has_an_1_type_7005": "变量“{0}”隐式具有“{1}”类型。", + "Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined_7034": "变量“{0}”在某些无法确定其类型的位置处隐式具有类型“{1}”。", + "Variable_0_is_used_before_being_assigned_2454": "在赋值前使用了变量“{0}”。", + "Variable_declaration_expected_1134": "应为变量声明。", + "Variable_declaration_list_cannot_be_empty_1123": "变量声明列表不能为空。", + "Version_0_6029": "版本 {0}", + "Watch_input_files_6005": "监视输入文件。", + "Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen_6191": "是否在监视模式下保留过时的控制台输出,而不是清除屏幕。", + "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001": "不能重命名标准 TypeScript 库中定义的元素。", + "You_cannot_rename_this_element_8000": "无法重命名此元素。", + "_0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write__1329": "“{0}”收到的参数过少,无法在此处充当修饰器。你是要先调用它,然后再写入 \"@{0}()\" 吗?", + "_0_are_specified_twice_The_attribute_named_0_will_be_overwritten_2710": "“{0}”被指定了两次。将覆盖名为“{0}”的特性。", + "_0_can_only_be_used_in_a_ts_file_8009": "“{0}”只能在 .ts 文件中使用。", + "_0_expected_1005": "应为“{0}”。", + "_0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_reference_7023": "由于“{0}'”不具有返回类型批注并且在它的一个返回表达式中得到直接或间接引用,因此它隐式具有返回类型 \"any\"。", + "_0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or__7022": "“{0}”隐式具有类型 \"any\",因为它不具有类型批注,且在其自身的初始化表达式中得到直接或间接引用。", + "_0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible_2692": "“{0}”是基元,但“{1}”是包装器对象。如可能首选使用“{0}”。", + "_0_is_declared_but_its_value_is_never_read_6133": "已声明“{0}”,但从未读取其值。", + "_0_is_declared_but_never_used_6196": "“{0}”已声明,但从未使用过。", + "_0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2_17012": "“{0}”不是关键字“{1}”的有效元属性。是否是指“{2}”?", + "_0_is_referenced_directly_or_indirectly_in_its_own_base_expression_2506": "“{0}”在其自身的基表达式中得到直接或间接引用。", + "_0_is_referenced_directly_or_indirectly_in_its_own_type_annotation_2502": "“{0}”在其自身的类型批注中得到直接或间接引用。", + "_0_list_cannot_be_empty_1097": "“{0}”列表不能为空。", + "_0_modifier_already_seen_1030": "已看到“{0}”修饰符。", + "_0_modifier_cannot_appear_on_a_class_element_1031": "“{0}”修饰符不能出现在类元素上。", + "_0_modifier_cannot_appear_on_a_constructor_declaration_1089": "“{0}”修饰符不能出现在构造函数声明中。", + "_0_modifier_cannot_appear_on_a_data_property_1043": "“{0}”修饰符不能出现在数据属性上。", + "_0_modifier_cannot_appear_on_a_module_or_namespace_element_1044": "“{0}”修饰符不可出现在模块或命名空间元素上。", + "_0_modifier_cannot_appear_on_a_parameter_1090": "“{0}”修饰符不能出现在参数中。", + "_0_modifier_cannot_appear_on_a_type_member_1070": "“{0}”修饰符不可出现在类型成员上。", + "_0_modifier_cannot_appear_on_an_index_signature_1071": "“{0}”修饰符不可出现在索引签名上。", + "_0_modifier_cannot_be_used_here_1042": "“{0}”修饰符不能在此处使用。", + "_0_modifier_cannot_be_used_in_an_ambient_context_1040": "“{0}”修饰符不能在环境上下文中使用。", + "_0_modifier_cannot_be_used_with_1_modifier_1243": "“{0}”修饰符不能与“{1}”修饰符一起使用。", + "_0_modifier_cannot_be_used_with_a_class_declaration_1041": "“{0}”修饰符不能与类声明一起使用。", + "_0_modifier_must_precede_1_modifier_1029": "“{0}”修饰符必须位于“{1}”修饰符之前。", + "_0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here_2702": "“{0}”仅指类型,但在此用作命名空间。", + "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_2693": "“{0}”仅表示类型,但在此处却作为值使用。", + "_0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead_2686": "“{0}”指 UMD 全局,但当前文件是模块。请考虑改为添加导入。", + "_0_tag_already_specified_1223": "已指定“{0}”标记。", + "_0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag_1253": "“{0}”标记无法单独用作顶级 JSDoc 标记。", + "_0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type_7010": "缺少返回类型批注的“{0}”隐式具有“{1}”返回类型。", + "abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration_1242": "\"abstract\" 修饰符仅可出现在类、方法或属性声明中。", + "await_expression_is_only_allowed_within_an_async_function_1308": "只允许在异步函数中使用 \"await\" 表达式。", + "await_expressions_cannot_be_used_in_a_parameter_initializer_2524": "不能在参数初始化表达式中使用 \"await\" 表达式。", + "baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1_6106": "\"baseUrl\" 选项设置为“{0}”,可使用此值解析非相关模块名称“{1}”。", + "can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment_1312": "\"=\" 只可在重构赋值内部的对象文字属性中使用。", + "case_or_default_expected_1130": "应为 \"case\" 或 \"default\"。", + "class_expressions_are_not_currently_supported_9003": "当前不支持 \"class\" 表达式。", + "const_declarations_can_only_be_declared_inside_a_block_1156": "\"const\" 声明只能在块的内部声明。", + "const_declarations_must_be_initialized_1155": "必须初始化 \"const\" 声明。", + "const_enum_member_initializer_was_evaluated_to_a_non_finite_value_2477": "\"const\" 枚举成员初始化表达式的求值结果为非有限值。", + "const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN_2478": "\"const\" 枚举成员初始化表达式的求值结果为不允许使用的值 \"NaN\"。", + "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475": "\"const\" 枚举仅可在属性、索引访问表达式、导入声明的右侧、导出分配或类型查询中使用。", + "delete_cannot_be_called_on_an_identifier_in_strict_mode_1102": "在严格模式下,无法对标识符调用 \"delete\"。", + "delete_this_Project_0_is_up_to_date_because_it_was_previously_built_6360": "删除此 - 项目“{0}”已是最新,因为它是以前生成的", + "enum_declarations_can_only_be_used_in_a_ts_file_8015": "\"enum declarations\" 只能在 .ts 文件中使用。", + "export_can_only_be_used_in_a_ts_file_8003": "\"export=\" 只能在 .ts 文件中使用。", + "export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always__2668": "\"export\" 修饰符不可用于环境模块和模块扩大,因为它们始终可见。", + "extends_clause_already_seen_1172": "已看到 \"extends\" 子句。", + "extends_clause_must_precede_implements_clause_1173": "\"extends\" 子句必须位于 \"implements\" 子句之前。", + "extends_clause_of_exported_class_0_has_or_is_using_private_name_1_4020": "导出的类“{0}”的 \"extends\" 子句具有或正在使用专用名称“{1}”。", + "extends_clause_of_exported_interface_0_has_or_is_using_private_name_1_4022": "导出接口“{0}”的 \"extends\" 子句具有或正在使用专用名称“{1}”。", + "file_6025": "文件", + "get_and_set_accessor_must_have_the_same_this_type_2682": "\"get\" 和 \"set\" 访问器必须拥有相同的 \"this\" 类型。", + "get_and_set_accessor_must_have_the_same_type_2380": "\"get\" 和 \"set\" 访问器必须属于同一类型。", + "implements_clause_already_seen_1175": "已看到 \"implements\" 子句。", + "implements_clauses_can_only_be_used_in_a_ts_file_8005": "\"implements clauses\" 只能在 .ts 文件中使用。", + "import_can_only_be_used_in_a_ts_file_8002": "\"import ... =\" 只能在 .ts 文件中使用。", + "infer_declarations_are_only_permitted_in_the_extends_clause_of_a_conditional_type_1338": "仅条件类型的 \"extends\" 子句中才允许 \"infer\" 声明。", + "interface_declarations_can_only_be_used_in_a_ts_file_8006": "\"interface declarations\" 只能在 .ts 文件中使用。", + "let_declarations_can_only_be_declared_inside_a_block_1157": "\"let\" 声明只能在块的内部声明。", + "let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations_2480": "\"let\" 不能用作 \"let\" 或 \"const\" 声明中的名称。", + "module_declarations_can_only_be_used_in_a_ts_file_8007": "\"module declarations\" 只能在 .ts 文件中使用。", + "new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead_1150": "\"new T[]\" 不能用于创建数组。请改用 \"new Array()\"。", + "new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type_7009": "其目标缺少构造签名的 \"new\" 表达式隐式具有 \"any\" 类型。", + "non_null_assertions_can_only_be_used_in_a_ts_file_8013": "\"non-null assertions\" 只能在 .ts 文件中使用。", + "options_6024": "选项", + "or_expected_1144": "应为 \"{\" 或 \";\"。", + "package_json_does_not_have_a_0_field_6100": "\"package.json\" 没有“{0}”字段。", + "package_json_has_0_field_1_that_references_2_6101": "\"package.json\" 具有引用“{2}”的“{0}”字段“{1}”。", + "parameter_modifiers_can_only_be_used_in_a_ts_file_8012": "\"parameter modifiers\" 只能在 .ts 文件中使用。", + "paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0_6091": "指定了 \"paths“ 选项,正在查找模式以匹配模块名“{0}”。", + "readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024": "\"readonly\" 修饰符仅可出现在属性声明或索引签名中。", + "require_call_may_be_converted_to_an_import_80005": "可将“要求”调用转换为导入。", + "rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107": "设置了 \"rootDirs\" 选项,可将其用于解析相对模块名称“{0}”。", + "super_can_only_be_referenced_in_a_derived_class_2335": "只能在派生类中引用 \"super\"。", + "super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions_2660": "仅可在派生类或对象文字表达式的成员中引用 \"super\"。", + "super_cannot_be_referenced_in_a_computed_property_name_2466": "不能在计算属性名中引用 \"super\"。", + "super_cannot_be_referenced_in_constructor_arguments_2336": "不能在构造函数参数中引用 \"super\"。", + "super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_highe_2659": "\"target\" 选项为 \"ES2015\" 或更高版本时,仅对象文字表达式的成员中允许 \"super\"。", + "super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class_17011": "访问派生类构造函数中的 \"super\" 属性前,必须调用 \"super\"。", + "super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class_17009": "访问派生类的构造函数中的 \"this\" 前,必须调用 \"super\"。", + "super_must_be_followed_by_an_argument_list_or_member_access_1034": "\"super\" 的后面必须是参数列表或成员访问。", + "super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_der_2338": "只有构造函数、成员函数或派生类的成员访问器中才允许 \"super\" 属性访问。", + "this_cannot_be_referenced_in_a_computed_property_name_2465": "不能在计算属性名中引用 \"this\"。", + "this_cannot_be_referenced_in_a_module_or_namespace_body_2331": "不能在模块或命名空间体中引用 \"this\"。", + "this_cannot_be_referenced_in_a_static_property_initializer_2334": "不能在静态属性初始化表达式中引用 \"this\"。", + "this_cannot_be_referenced_in_constructor_arguments_2333": "不能在构造函数参数中引用 \"this\"。", + "this_cannot_be_referenced_in_current_location_2332": "不能在当前位置引用 \"this\"。", + "this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_2683": "\"this\" 隐式具有类型 \"any\",因为它没有类型注释。", + "type_aliases_can_only_be_used_in_a_ts_file_8008": "\"type aliases\" 只能在 .ts 文件中使用。", + "type_arguments_can_only_be_used_in_a_ts_file_8011": "\"type arguments\" 只能在 .ts 文件中使用。", + "type_assertion_expressions_can_only_be_used_in_a_ts_file_8016": "\"type assertion expressions\" 只能在 .ts 文件中使用。", + "type_parameter_declarations_can_only_be_used_in_a_ts_file_8004": "\"type parameter declarations\" 只能在 .ts 文件中使用。", + "types_can_only_be_used_in_a_ts_file_8010": "\"types\" 只能在 .ts 文件中使用。", + "unique_symbol_types_are_not_allowed_here_1335": "此处不允许使用 \"unique symbol\" 类型。", + "unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement_1334": "\"unique symbol\" 类型仅可用于变量语句中的变量。", + "unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name_1333": "不可在具有绑定名称的变量声明中使用 \"unique symbol\" 类型。", + "with_statements_are_not_allowed_in_an_async_function_block_1300": "不允许在异步函数块中使用 \"with\" 语句。", + "with_statements_are_not_allowed_in_strict_mode_1101": "严格模式下不允许使用 \"with\" 语句。", + "yield_expressions_cannot_be_used_in_a_parameter_initializer_2523": "不能在参数初始化表达式中使用 \"yield\" 表达式。" +} \ No newline at end of file diff --git a/node_modules/typescript/lib/zh-tw/diagnosticMessages.generated.json b/node_modules/typescript/lib/zh-tw/diagnosticMessages.generated.json new file mode 100644 index 0000000..bc7bc2f --- /dev/null +++ b/node_modules/typescript/lib/zh-tw/diagnosticMessages.generated.json @@ -0,0 +1,1101 @@ +{ + "A_0_modifier_cannot_be_used_with_an_import_declaration_1079": "'{0}' 修飾詞無法與匯入宣告並用。", + "A_0_modifier_cannot_be_used_with_an_interface_declaration_1045": "'{0}' 修飾詞無法與介面宣告並用。", + "A_0_parameter_must_be_the_first_parameter_2680": "'{0}' 參數必須為第一個參數。", + "A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature_2463": "實作簽章中不得省略繫結模式參數。", + "A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement_1105": "'break' 陳述式只可在封入的反覆項目或 switch 陳述式內使用。", + "A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement_1116": "'break' 陳述式只可跳至封入之陳述式的標籤。", + "A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments_2500": "類別只能實作具有選擇性型別引數的識別碼/限定名稱。", + "A_class_declaration_without_the_default_modifier_must_have_a_name_1211": "不具 'default' 修飾詞的類別宣告必須要有名稱。", + "A_class_may_only_extend_another_class_2311": "每個類別只可擴充另一個類別。", + "A_class_may_only_implement_another_class_or_interface_2422": "每個類別只可實作另一個類別或介面。", + "A_class_member_cannot_have_the_0_keyword_1248": "類別成員不能含有 '{0}' 關鍵字。", + "A_comma_expression_is_not_allowed_in_a_computed_property_name_1171": "計算的屬性名稱中不可有逗點運算式。", + "A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type_2467": "計算的屬性名稱不得參考其包含類型中的型別參數。", + "A_computed_property_name_in_a_class_property_declaration_must_refer_to_an_expression_whose_type_is_a_1166": "類別屬性宣告中的計算屬性名稱,必須參考類型為常值型別或 'unique symbol' 類型的運算式。", + "A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_ty_1168": "方法多載中的計算屬性名稱必須參考型別為常值型別或 'unique symbol' 型別的運算式。", + "A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type__1170": "常值型別中的計算屬性名稱,必須參考類型為常值型別或 'unique symbol' 類型的運算式。", + "A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_t_1165": "環境內容中的計算屬性名稱必須參考型別為常值型別或 'unique symbol' 型別的運算式。", + "A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_1169": "介面中的計算屬性名稱必須參考型別為常值型別或 'unique symbol' 型別的運算式。", + "A_computed_property_name_must_be_of_type_string_number_symbol_or_any_2464": "計算的屬性名稱必須是 'string'、'number'、'symbol' 或 'any' 類型。", + "A_computed_property_name_of_the_form_0_must_be_of_type_symbol_2471": "格式為 '{0}' 之計算的屬性名稱必須是 'symbol' 類型。", + "A_const_enum_member_can_only_be_accessed_using_a_string_literal_2476": "若要存取常數列舉成員,必須透過字串常值。", + "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_1254": "環境內容中的 'const' 初始設定式必須為字串或數字常值。", + "A_constructor_cannot_contain_a_super_call_when_its_class_extends_null_17005": "當建構函式的類別擴充為 'null' 時,不得包含 'super' 呼叫。", + "A_constructor_cannot_have_a_this_parameter_2681": "建構函式不能含有 'this' 參數。", + "A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement_1104": "'continue' 陳述式只可在封入的反覆項目陳述式內使用。", + "A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement_1115": "'continue' 陳述式只可跳至封入之反覆項目陳述式的標籤。", + "A_declare_modifier_cannot_be_used_in_an_already_ambient_context_1038": "不得在現有環境內容中使用 'declare' 修飾詞。", + "A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file_1046": ".d.ts 檔案中的最上層宣告需要 'declare' 修飾詞。", + "A_decorator_can_only_decorate_a_method_implementation_not_an_overload_1249": "一個裝飾項目只能裝飾一項方法實作,而不能多載。", + "A_default_clause_cannot_appear_more_than_once_in_a_switch_statement_1113": "'default' 子句在 'switch' 陳述式中不得出現一次以上。", + "A_default_export_can_only_be_used_in_an_ECMAScript_style_module_1319": "預設匯出只能在 ECMAScript 樣式的模組中使用。", + "A_definite_assignment_assertion_is_not_permitted_in_this_context_1255": "此內容不允許明確的指派判斷提示 '!'。", + "A_destructuring_declaration_must_have_an_initializer_1182": "解構宣告中必須包含初始設定式。", + "A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declarat_2712": "ES5/ES3 中的動態匯入呼叫需要 'Promise' 建構函式。請確認您有 'Promise' 建構函式的宣告,或在 `--lib` 選項中納入 'ES2015'。", + "A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES20_2711": "動態匯入呼叫傳回 'Promise'。請確認您有 'Promise' 的宣告,或在 `--lib` 選項中納入 'ES2015'。", + "A_file_cannot_have_a_reference_to_itself_1006": "檔案不得參考自己。", + "A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator_1103": "只在非同步函式或非同步產生器中才允許 'for-await-of' 陳述式。", + "A_function_returning_never_cannot_have_a_reachable_end_point_2534": "會傳回 'never' 的功能不得具有可聯繫的端點。", + "A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void_2679": "透過 'new' 關鍵字呼叫的函式不能含有為 'viod' 的 'this' 類型。", + "A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value_2355": "若函式的宣告類型既不是 'void' 也不是 'any',則必須傳回值。", + "A_generator_cannot_have_a_void_type_annotation_2505": "產生器不得有 'void' 類型註釋。", + "A_get_accessor_cannot_have_parameters_1054": "'get' 存取子不得有參數。", + "A_get_accessor_must_return_a_value_2378": "'get' 存取子必須傳回值。", + "A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_memb_2651": "列舉宣告中的成員初始設定式,不得參考在它之後宣告的成員,包括在其他列舉中所定義的成員。", + "A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any_2545": "mixin 類別必須具備建構函式,且該建構函式必須指定一個類型為 'any[]' 的 rest 參數。", + "A_module_cannot_have_multiple_default_exports_2528": "一個模組不得有多個預設匯出。", + "A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merg_2433": "命名空間宣告的所在檔案位置,不得與其要合併的類別或函式不同。", + "A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged_2434": "命名空間宣告的位置不得先於其要合併的類別或函式。", + "A_namespace_declaration_is_only_allowed_in_a_namespace_or_module_1235": "只有命名空間或模組才允許命名空間宣告。", + "A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_7038": "命名空間樣式的匯入無法加以呼叫或建構,而且會導致執行階段失敗。", + "A_non_dry_build_would_build_project_0_6357": "非 -dry 組建會建置專案 '{0}'", + "A_non_dry_build_would_delete_the_following_files_Colon_0_6356": "非 -dry 組建會刪除下列檔案: {0}", + "A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation_2371": "只有函式或建構函式實作才可使用參數初始設定式。", + "A_parameter_property_cannot_be_declared_using_a_rest_parameter_1317": "無法使用剩餘參數宣告參數屬性。", + "A_parameter_property_is_only_allowed_in_a_constructor_implementation_2369": "建構函式實作中只可有一個參數屬性。", + "A_parameter_property_may_not_be_declared_using_a_binding_pattern_1187": "無法使用繫結模式宣告參數屬性。", + "A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not_18001": "[擴充] 選項中的路徑必須為相對或根路徑,但 '{0}' 並不是。", + "A_promise_must_have_a_then_method_1059": "Promise 必須有 'then' 方法。", + "A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly_1331": "類型為 'unique symbol' 類型的類別屬性,必須為 'static' 和 'readonly'。", + "A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly_1330": "類型為 'unique symbol' 類型之介面或常值型別的屬性,必須是 'readonly'。", + "A_required_parameter_cannot_follow_an_optional_parameter_1016": "必要參數不得接在選擇性參數之後。", + "A_rest_element_cannot_contain_a_binding_pattern_2501": "剩餘項目不得包含繫結模式。", + "A_rest_element_cannot_have_a_property_name_2566": "REST 元素不得有屬性名稱。", + "A_rest_element_cannot_have_an_initializer_1186": "剩餘項目不得有初始設定式。", + "A_rest_element_must_be_last_in_a_destructuring_pattern_2462": "Rest 項目必須保持在解構模式。", + "A_rest_parameter_cannot_be_optional_1047": "剩餘參數不得為選擇性參數。", + "A_rest_parameter_cannot_have_an_initializer_1048": "剩餘參數不得有初始設定式。", + "A_rest_parameter_must_be_last_in_a_parameter_list_1014": "剩餘參數必須是參數清單中的最後一個參數。", + "A_rest_parameter_must_be_of_an_array_type_2370": "剩餘參數必須為陣列類型。", + "A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma_1013": "REST 參數或繫結模式的結尾不得為逗點。", + "A_return_statement_can_only_be_used_within_a_function_body_1108": "'return' 陳述式只可在函式主體內使用。", + "A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl_6167": "一系列由重新對應匯入到 'baseUrl' 之相對查詢位置的項目。", + "A_set_accessor_cannot_have_a_return_type_annotation_1095": "'set' 存取子不得有傳回型別註解。", + "A_set_accessor_cannot_have_an_optional_parameter_1051": "'set' 存取子不得有選擇性參數。", + "A_set_accessor_cannot_have_rest_parameter_1053": "'set' 存取子不得有剩餘參數。", + "A_set_accessor_must_have_exactly_one_parameter_1049": "'set' 存取子只可有一個參數。", + "A_set_accessor_parameter_cannot_have_an_initializer_1052": "'set' 存取子參數不得有初始設定式。", + "A_signature_with_an_implementation_cannot_use_a_string_literal_type_2381": "包含實作的簽章不得使用字串常值類型。", + "A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_proper_2376": "當類別包含已初始化的屬性或參數屬性時,'super' 呼叫必須是建構函式中的第一個陳述式。", + "A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard_2518": "以 'this' 為基礎的類型成立條件,和以參數為基礎的類型成立條件不相容。", + "A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface_2526": "'this' 類型只適用於類別或介面的非靜態成員。", + "A_tsconfig_json_file_is_already_defined_at_Colon_0_5054": "'tsconfig.json' 檔案已定義於: '{0}'。", + "A_tuple_type_element_list_cannot_be_empty_1122": "元組類型項目清單不得為空白。", + "A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Con_17007": "乘冪運算式左邊不允許類型宣告運算式。請考慮以括弧括住運算式。", + "A_type_literal_property_cannot_have_an_initializer_1247": "類型常值屬性不得有初始設定式。", + "A_type_predicate_cannot_reference_a_rest_parameter_1229": "型別述詞不得參考剩餘參數。", + "A_type_predicate_cannot_reference_element_0_in_a_binding_pattern_1230": "型別述詞不得參考繫結模式的項目 '{0}'。", + "A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods_1228": "只有函式及方法的傳回型別位置才允許型別述詞。", + "A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type_2677": "類型述詞的類型必須可指派給其參數的類型。", + "A_variable_whose_type_is_a_unique_symbol_type_must_be_const_1332": "型別為 'unique symbol' 型別的變數必須是 'const'。", + "A_yield_expression_is_only_allowed_in_a_generator_body_1163": "只有產生器主體才允許 'yield' 運算式。", + "Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression_2513": "無法透過 super 運算式存取類別 '{1}' 中的抽象方法 '{0}'。", + "Abstract_methods_can_only_appear_within_an_abstract_class_1244": "抽象方法只可出現在抽象類別中。", + "Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor_2715": "無法從建構函式存取類別 '{1}' 中的抽象屬性 '{0}'。", + "Accessibility_modifier_already_seen_1028": "已有存取範圍修飾詞。", + "Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher_1056": "只有當目標為 ECMAScript 5 及更高版本時,才可使用存取子。", + "Accessors_must_both_be_abstract_or_non_abstract_2676": "存取子必須兩者均為抽象或非抽象。", + "Add_0_to_existing_import_declaration_from_1_90015": "從 \"{1}\" 將 '{0}' 新增至現有的匯入宣告", + "Add_0_to_unresolved_variable_90008": "對未解析的變數新增 '{0}.'", + "Add_all_missing_async_modifiers_95041": "新增缺少的所有 'async' 修飾詞", + "Add_all_missing_members_95022": "新增遺漏的所有成員", + "Add_all_missing_super_calls_95039": "新增缺少的所有 super 呼叫", + "Add_async_modifier_to_containing_function_90029": "將 async 修飾詞新增至包含的函式", + "Add_braces_to_arrow_function_95059": "將大括號新增至箭號函式", + "Add_definite_assignment_assertion_to_property_0_95020": "將明確指派判斷提示新增至屬性 '{0}'", + "Add_definite_assignment_assertions_to_all_uninitialized_properties_95028": "為所有未初始化的屬性新增明確的指派判斷提示", + "Add_index_signature_for_property_0_90017": "為屬性 '{0}' 新增索引簽章", + "Add_initializer_to_property_0_95019": "將初始設定式新增至屬性 '{0}'", + "Add_initializers_to_all_uninitialized_properties_95027": "為所有未初始化的屬性新增初始設定式", + "Add_missing_super_call_90001": "新增遺漏的 'super()' 呼叫", + "Add_missing_typeof_95052": "新增遺漏的 'typeof'", + "Add_or_remove_braces_in_an_arrow_function_95058": "在箭號函式中新增或移除大括號", + "Add_qualifier_to_all_unresolved_variables_matching_a_member_name_95037": "對所有比對成員名稱的未解析變數新增限定詞", + "Add_to_all_uncalled_decorators_95044": "為所有未呼叫的裝飾項目新增 '()'", + "Add_ts_ignore_to_all_error_messages_95042": "為所有錯誤訊息新增 '@ts-ignore'", + "Add_undefined_type_to_all_uninitialized_properties_95029": "為所有未初始化的屬性新增未定義的類型", + "Add_undefined_type_to_property_0_95018": "將 'undefined' 類型新增至屬性 '{0}'", + "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068": "新增 tsconfig.json 檔案有助於組織同時包含 TypeScript 及 JavaScript 檔案的專案。若要深入了解,請前往 https://aka.ms/tsconfig。", + "Additional_Checks_6176": "其他檢查", + "Advanced_Options_6178": "進階選項", + "All_declarations_of_0_must_have_identical_modifiers_2687": "'{0}' 的所有宣告都必須有相同修飾詞。", + "All_declarations_of_0_must_have_identical_type_parameters_2428": "'{0}' 的所有宣告都必須具有相同的類型參數。", + "All_declarations_of_an_abstract_method_must_be_consecutive_2516": "抽象方法的所有宣告必須連續。", + "All_destructured_elements_are_unused_6198": "不會使用所有未經結構化的項目。", + "All_imports_in_import_declaration_are_unused_6192": "匯入宣告中的所有匯入皆未使用。", + "All_variables_are_unused_6199": "所有變數都未使用。", + "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011": "允許從沒有預設匯出的模組進行預設匯入。這不會影響程式碼發出,僅為類型檢查。", + "Allow_javascript_files_to_be_compiled_6102": "允許編譯 JavaScript 檔案。", + "Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided_1209": "提供 '--isolatedModules' 旗標時,不可使用環境常數列舉。", + "Ambient_module_declaration_cannot_specify_relative_module_name_2436": "環境模組宣告不可指定相對模組名稱。", + "Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces_2435": "環境模組不得以巢狀方式置於其他模組或命名空間中。", + "An_AMD_module_cannot_have_multiple_name_assignments_2458": "AMD 模組不能有多個名稱指派。", + "An_abstract_accessor_cannot_have_an_implementation_1318": "抽象存取子無法實作。", + "An_accessor_cannot_be_declared_in_an_ambient_context_1086": "不得在環境內容中宣告存取子", + "An_accessor_cannot_have_type_parameters_1094": "存取子不得有類型參數。", + "An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file_1234": "環境模組宣告只可出現在檔案的最上層。", + "An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type_2356": "算術運算元必須是 'any'、'number' 或列舉類型。", + "An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_de_2705": "ES5/ES3 中的非同步函式或方法需要 'Promise' 建構函式。請確認您有 'Promise' 建構函式的宣告,或在 `--lib` 選項中納入 'ES2015'。", + "An_async_function_or_method_must_have_a_valid_awaitable_return_type_1057": "非同步函式或方法必須包含有效可等候的傳回型別。", + "An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_in_2697": "非同步函式或方法必須傳回 'Promise'。請確定您有 'Promise' 的宣告或將 'ES2015' 納入您的 '-lib' 選項。", + "An_async_iterator_must_have_a_next_method_2519": "非同步迭代器必須有 'next()' 方法。", + "An_element_access_expression_should_take_an_argument_1011": "項目存取運算式應接受一個引數。", + "An_enum_member_cannot_have_a_numeric_name_2452": "列舉成員不得有數值名稱。", + "An_export_assignment_can_only_be_used_in_a_module_1231": "匯出指派只可用於模組中。", + "An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements_2309": "匯出指派不得用於具有其他匯出項目的模組中。", + "An_export_assignment_cannot_be_used_in_a_namespace_1063": "命名空間中不可使用匯出指派。", + "An_export_assignment_cannot_have_modifiers_1120": "匯出指派不得有修飾詞。", + "An_export_declaration_can_only_be_used_in_a_module_1233": "匯出宣告只可用於模組中。", + "An_export_declaration_cannot_have_modifiers_1193": "匯出宣告不得有修飾詞。", + "An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive_1198": "擴充的 Unicode 逸出值必須介於 0x0 與 0x10FFFF (不含) 之間。", + "An_implementation_cannot_be_declared_in_ambient_contexts_1183": "不得在環境內容中宣告實作。", + "An_import_declaration_can_only_be_used_in_a_namespace_or_module_1232": "匯入宣告只可用於命名空間或模組中。", + "An_import_declaration_cannot_have_modifiers_1191": "匯入宣告不得有修飾詞。", + "An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead_2691": "匯入路徑的結尾不得為 '{0}' 副檔名。請考慮改為匯入 '{1}'。", + "An_index_expression_argument_must_be_of_type_string_number_symbol_or_any_2342": "索引運算式引數必須是 'string'、'number'、'symbol' 或 'any' 類型。", + "An_index_signature_cannot_have_a_rest_parameter_1017": "索引簽章不得有剩餘參數。", + "An_index_signature_must_have_a_type_annotation_1021": "索引簽章必須有類型註釋。", + "An_index_signature_must_have_exactly_one_parameter_1096": "索引簽章只可有一個參數。", + "An_index_signature_parameter_cannot_have_a_question_mark_1019": "索引簽章參數不得有問號。", + "An_index_signature_parameter_cannot_have_an_accessibility_modifier_1018": "索引簽章參數不得有存取範圍修飾詞。", + "An_index_signature_parameter_cannot_have_an_initializer_1020": "索引簽章參數不得有初始設定式。", + "An_index_signature_parameter_must_have_a_type_annotation_1022": "索引簽章參數必須有類型註釋。", + "An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead_1336": "索引簽章參數類型不能是類型別名。請考慮改為撰寫 '[{0}: {1}]: {2}'。", + "An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead_1337": "索引簽章參數類型不能是等位型別。請考慮改用對應的物件類型。", + "An_index_signature_parameter_type_must_be_string_or_number_1023": "索引簽章參數類型必須是 'string' 或 'number'。", + "An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments_2499": "介面只能擴充具有選擇性型別引數的識別碼/限定名稱。", + "An_interface_may_only_extend_a_class_or_another_interface_2312": "每個介面只可擴充一個類別或另一個介面。", + "An_interface_property_cannot_have_an_initializer_1246": "介面屬性不得有初始設定式。", + "An_iterator_must_have_a_next_method_2489": "迭代器必須要有 'next()' 方法。", + "An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name_1118": "物件常值不得有多個同名的 get/set 存取子。", + "An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode_1117": "在 strict 模式中,物件常值不得有多個同名的屬性。", + "An_object_literal_cannot_have_property_and_accessor_with_the_same_name_1119": "物件常值不得有同名的屬性與存取子。", + "An_object_member_cannot_be_declared_optional_1162": "不得將物件成員宣告為選擇性。", + "An_overload_signature_cannot_be_declared_as_a_generator_1222": "不可將多載簽章宣告為產生器。", + "An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_ex_17006": "乘冪運算式左邊不允許具 '{0}' 運算子的一元運算式。請考慮以括弧括住運算式。", + "Annotate_everything_with_types_from_JSDoc_95043": "標註具備 JSDoc 之類型的所有項目 ", + "Annotate_with_type_from_JSDoc_95009": "為來自 JSDoc 的類型標註", + "Annotate_with_types_from_JSDoc_95010": "為來自 JSDoc 的類型標註", + "Argument_expression_expected_1135": "必須是引數運算式。", + "Argument_for_0_option_must_be_Colon_1_6046": "'{0}' 選項的引數必須是: {1}。", + "Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_2345": "類型 '{0}' 的引數不可指派給類型 '{1}' 的參數。", + "Array_element_destructuring_pattern_expected_1181": "必須是陣列項目解構模式。", + "Asterisk_Slash_expected_1010": "必須是 '*/'。", + "Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_2669": "全域範圍的增強指定只能在外部模組宣告或環境模組宣告直接巢狀。", + "Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambien_2670": "除非全域範圍的增強指定已顯示在環境內容中,否則應含有 'declare' 修飾詞。", + "Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using__6140": "專案 '{0}' 中已啟用鍵入的自動探索。正在使用快取位置 '{2}' 執行模組 '{1}' 的額外解析傳遞。", + "Base_class_expressions_cannot_reference_class_type_parameters_2562": "基底類別運算式無法參考類別型別參數。", + "Base_constructor_return_type_0_is_not_a_class_or_interface_type_2509": "基底建構函式傳回型別 '{0}' 不是類別或介面類型。", + "Base_constructors_must_all_have_the_same_return_type_2510": "基底建構函式的傳回型別必須全部相同。", + "Base_directory_to_resolve_non_absolute_module_names_6083": "要解析非絕對模組名稱的基底目錄。", + "Basic_Options_6172": "基本選項", + "Binary_digit_expected_1177": "必須是二進位數字。", + "Binding_element_0_implicitly_has_an_1_type_7031": "繫結元素 '{0}' 隱含擁有 '{1}' 類型。", + "Block_scoped_variable_0_used_before_its_declaration_2448": "已在其宣告之前使用區塊範圍變數 '{0}'。", + "Build_all_projects_including_those_that_appear_to_be_up_to_date_6368": "建置包括似乎已是最新狀態的所有專案", + "Build_one_or_more_projects_and_their_dependencies_if_out_of_date_6364": "若已過期,則建置一或多個專案及其相依性", + "Building_project_0_6358": "正在建置專案 '{0}'...", + "Call_decorator_expression_90028": "呼叫裝飾項目運算式", + "Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7020": "缺少傳回型別註解的呼叫簽章隱含了 'any' 傳回型別。", + "Call_target_does_not_contain_any_signatures_2346": "呼叫目標未包含任何特徵標記。", + "Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_p_2713": "因為 '{0}' 是類型而非命名空間,所以無法存取 '{0}.{1}'。您要在 '{0}' 中使用 '{0}[\"{1}\"]' 擷取屬性 '{1}' 的類型嗎?", + "Cannot_assign_a_0_constructor_type_to_a_1_constructor_type_2672": "無法將 '{0}' 建構函式類型指派至 '{1}' 建構函式類型。", + "Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type_2517": "無法將抽象建構函式類型指派給非抽象建構函式類型。", + "Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property_2540": "無法指派至 '{0}',因為它是常數或唯讀屬性。", + "Cannot_assign_to_0_because_it_is_not_a_variable_2539": "無法指派至 '{0}',因為它不是變數。", + "Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity_2671": "因為模組 '{0}' 會解析為非模組實體,所以無法加以增強。", + "Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity_2649": "無法使用值匯出擴充模組 '{0}',因為其會解析為非模組實體。", + "Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system_6131": "除非 '--module' 旗標為 'amd' 或 'system',否則無法使用選項 '{0}' 編譯模組。", + "Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided_1208": "提供 '--isolatedModules' 旗標時,無法編譯命名空間。", + "Cannot_create_an_instance_of_an_abstract_class_2511": "無法建立抽象類別的執行個體。", + "Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module_2661": "無法匯出 '{0}'。只有區域宣告可以從模組匯出。", + "Cannot_extend_a_class_0_Class_constructor_is_marked_as_private_2675": "無法延伸類別 '{0}'。類別建構函式已標記為私用。", + "Cannot_extend_an_interface_0_Did_you_mean_implements_2689": "無法擴充介面 '{0}',您意指「實作」嗎?", + "Cannot_find_a_tsconfig_json_file_at_the_specified_directory_Colon_0_5057": "在指定的目錄 '{0}' 中找不到 tsconfig.json 檔案。", + "Cannot_find_global_type_0_2318": "找不到全域類型 '{0}'。", + "Cannot_find_global_value_0_2468": "找不到全域值 '{0}'。", + "Cannot_find_lib_definition_for_0_2726": "找不到 '{0}' 的 lib 定義。", + "Cannot_find_lib_definition_for_0_Did_you_mean_1_2727": "找不到 '{0}' 的 lib 定義。您是指 '{1}' 嗎?", + "Cannot_find_module_0_2307": "找不到模組 '{0}'。", + "Cannot_find_name_0_2304": "找不到名稱 '{0}'。", + "Cannot_find_name_0_Did_you_mean_1_2552": "找不到名稱 '{0}'。您指的是 '{1}' 嗎?", + "Cannot_find_name_0_Did_you_mean_the_instance_member_this_0_2663": "找不到名稱 '{0}'。您要找的是此執行個體成員 'this.{0}' 嗎?", + "Cannot_find_name_0_Did_you_mean_the_static_member_1_0_2662": "找不到名稱 '{0}'。您要找的是此靜態成員 '{1}.{0}' 嗎?", + "Cannot_find_namespace_0_2503": "找不到命名空間 '{0}'。", + "Cannot_find_parameter_0_1225": "找不到參數 '{0}'。", + "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009": "找不到輸入檔案的一般子目錄路徑。", + "Cannot_find_type_definition_file_for_0_2688": "找不到 '{0}' 的類型定義檔案。", + "Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1_6137": "無法匯入型別宣告檔案。請考慮匯入 '{0}' 而不是 '{1}'。", + "Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1_2481": "無法初始化區塊範圍宣告 '{1}' 之同一範圍中的外部範圍變數 '{0}'。", + "Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatur_2349": "無法叫用類型缺少呼叫簽章的運算式。類型 '{0}' 不含相容的呼叫簽章。", + "Cannot_invoke_an_object_which_is_possibly_null_2721": "無法叫用可能為 'null' 的物件。", + "Cannot_invoke_an_object_which_is_possibly_null_or_undefined_2723": "無法叫用可能為 'null' 或 'undefined' 的物件。", + "Cannot_invoke_an_object_which_is_possibly_undefined_2722": "無法叫用可能為 'undefined' 的物件。", + "Cannot_prepend_project_0_because_it_does_not_have_outFile_set_6308": "因為專案 '{0}' 未設定 'outFile',所以無法於其前面加上任何內容", + "Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205": "如有提供 '--isolatedModules' 旗標,即無法重新匯出類型。", + "Cannot_read_file_0_Colon_1_5012": "無法讀取檔案 '{0}': {1}。", + "Cannot_redeclare_block_scoped_variable_0_2451": "無法重新宣告區塊範圍變數 '{0}'。", + "Cannot_redeclare_exported_variable_0_2323": "無法重新宣告匯出的變數 '{0}'。", + "Cannot_redeclare_identifier_0_in_catch_clause_2492": "無法在 Catch 子句中重新宣告識別碼 '{0}'。", + "Cannot_use_JSX_unless_the_jsx_flag_is_provided_17004": "除非有提供 '--jsx' 旗標,否則無法使用 JSX。", + "Cannot_use_imports_exports_or_module_augmentations_when_module_is_none_1148": "當 '--module' 為 'none' 時,無法使用匯入、匯出或模組增強指定。", + "Cannot_use_namespace_0_as_a_type_2709": "不得使用命名空間 '{0}' 作為類型。", + "Cannot_use_namespace_0_as_a_value_2708": "不得使用命名空間 '{0}' 作為值。", + "Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature_2351": "類型缺少呼叫或建構簽章的運算式,不得與 'new' 一起使用。", + "Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files_5056": "無法寫入檔案 '{0}',原因是其會由多個輸入檔覆寫。", + "Cannot_write_file_0_because_it_would_overwrite_input_file_5055": "無法寫入檔案 '{0}',原因是其會覆寫輸入檔。", + "Catch_clause_variable_cannot_have_a_type_annotation_1196": "Catch 子句變數不得有類型註釋。", + "Catch_clause_variable_cannot_have_an_initializer_1197": "Catch 子句變數不得有初始設定式。", + "Change_0_to_1_90014": "將 '{0}' 變更為 '{1}'", + "Change_all_extended_interfaces_to_implements_95038": "將所有延伸介面變更為 'implements'", + "Change_all_jsdoc_style_types_to_TypeScript_95030": "將所有 jsdoc 樣式的類型變更為 TypeScript", + "Change_all_jsdoc_style_types_to_TypeScript_and_add_undefined_to_nullable_types_95031": "將所有 jsdoc 樣式的類型變更為 TypeScript (並為 null 類型新增 '| undefined')", + "Change_extends_to_implements_90003": "將 [延伸] 變更至 [實作]5D;", + "Change_spelling_to_0_90022": "將拼字變更為 '{0}'", + "Checking_if_0_is_the_longest_matching_prefix_for_1_2_6104": "檢查 '{0}' 是否為 '{1}' - '{2}' 的最長相符前置詞。", + "Circular_definition_of_import_alias_0_2303": "匯入別名 '{0}' 的循環定義。", + "Circularity_detected_while_resolving_configuration_Colon_0_18000": "解析組態時偵測到循環性: {0}", + "Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_functi_2426": "類別 '{0}' 已定義執行個體成員存取子 '{1}',但是擴充類別 '{2}' 卻將其定義為執行個體成員函式。", + "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_access_2423": "類別 '{0}' 已定義執行個體成員函式 '{1}',但是擴充類別 '{2}' 卻將其定義為執行個體成員存取子。", + "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_proper_2424": "類別 '{0}' 已定義執行個體成員函式 '{1}',但是擴充類別 '{2}' 卻將其定義為執行個體成員屬性。", + "Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_functi_2425": "類別 '{0}' 已定義執行個體成員屬性 '{1}',但是擴充類別 '{2}' 卻將其定義為執行個體成員函式。", + "Class_0_incorrectly_extends_base_class_1_2415": "類別 '{0}' 不正確地擴充基底類別 '{1}'。", + "Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclas_2720": "類別 '{0}' 不當實作類別 '{1}'。您是否要擴充 '{1}',並繼承其成員以成為子類別?", + "Class_0_incorrectly_implements_interface_1_2420": "類別 '{0}' 不正確地實作介面 '{1}'。", + "Class_0_used_before_its_declaration_2449": "類別 '{0}' 的位置在其宣告之前。", + "Class_declarations_cannot_have_more_than_one_augments_or_extends_tag_8025": "類別宣告只可有一個 '@augments' 或 '@extends' 標記。", + "Class_name_cannot_be_0_2414": "類別名稱不得為 '{0}'。", + "Class_name_cannot_be_Object_when_targeting_ES5_with_module_0_2725": "當目標為具有模組 {0} 的 ES5 時,類別名稱不可為 'Object'。", + "Class_static_side_0_incorrectly_extends_base_class_static_side_1_2417": "類別靜態端 '{0}' 不正確地擴充基底類別靜態端 '{1}'。", + "Classes_can_only_extend_a_single_class_1174": "類別只能擴充一個類別。", + "Classes_containing_abstract_methods_must_be_marked_abstract_2514": "包含抽象方法的類別必須標記為抽象。", + "Command_line_Options_6171": "命令列選項", + "Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json_6020": "當路徑為專案組態檔或為 'tsconfig.json' 所在的資料夾時編譯專案。", + "Compiler_option_0_expects_an_argument_6044": "編譯器選項 '{0}' 必須要有一個引數。", + "Compiler_option_0_requires_a_value_of_type_1_5024": "編譯器選項 '{0}' 需要類型 {1} 的值。", + "Composite_projects_may_not_disable_declaration_emit_6304": "複合式專案可能未停用宣告發出。", + "Computed_property_names_are_not_allowed_in_enums_1164": "列舉中不能有計算的屬性名稱。", + "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553": "具有字串值成員的列舉中不允許計算值。", + "Concatenate_and_emit_output_to_single_file_6001": "串連並發出輸出至單一檔案。", + "Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_librar_4090": "在 '{1}' 和 '{2}' 找到衝突的 '{0}' 定義。請考慮安裝此程式庫的特定版本以解決衝突。", + "Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7013": "缺少傳回型別註解的建構簽章,隱含有 'any' 傳回型別。", + "Constructor_implementation_is_missing_2390": "缺少建構函式實作。", + "Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration_2673": "類別 '{0}' 的建構函式為私用,並且只能在類別宣告內存取。", + "Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration_2674": "類別 '{0}' 的建構函式受到保護,並且只能在類別宣告內存取。", + "Constructors_for_derived_classes_must_contain_a_super_call_2377": "衍生類別的建構函式必須包含 'super' 呼叫。", + "Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126": "未指定包含檔案,因此無法決定根目錄,而將略過 'node_modules' 中的查閱。", + "Convert_0_to_mapped_object_type_95055": "將 '{0}' 轉換為對應的物件類型", + "Convert_all_constructor_functions_to_classes_95045": "將所有建構函式轉換為類別", + "Convert_all_require_to_import_95048": "將所有 'require' 轉換至 'import'", + "Convert_all_to_default_imports_95035": "全部轉換為預設匯入", + "Convert_function_0_to_class_95002": "將函式 '{0}' 轉換為類別", + "Convert_function_to_an_ES2015_class_95001": "將函式轉換為 ES2015 類別", + "Convert_named_imports_to_namespace_import_95057": "將具名匯入轉換為命名空間匯入", + "Convert_namespace_import_to_named_imports_95056": "將命名空間匯入轉換為具名匯入", + "Convert_require_to_import_95047": "將 'require' 轉換至 'import'", + "Convert_to_ES6_module_95017": "轉換為 ES6 模組", + "Convert_to_default_import_95013": "轉換為預設匯入", + "Corrupted_locale_file_0_6051": "地區設定檔 {0} 已損毀。", + "Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type_7016": "找不到模組 '{0}' 的宣告檔案。'{1}' 隱含具有 'any' 類型。", + "Could_not_write_file_0_Colon_1_5033": "無法編寫檔案 '{0}': {1}。", + "DIRECTORY_6038": "目錄", + "Declaration_expected_1146": "必須是宣告。", + "Declaration_name_conflicts_with_built_in_global_identifier_0_2397": "宣告名稱與內建全域識別碼 '{0}' 衝突。", + "Declaration_or_statement_expected_1128": "必須是宣告或陳述式。", + "Declare_method_0_90023": "宣告方法 '{0}'", + "Declare_property_0_90016": "宣告屬性 '{0}'", + "Declare_static_method_0_90024": "宣告靜態方法 '{0}'", + "Declare_static_property_0_90027": "宣告靜態屬性 '{0}'", + "Decorators_are_not_valid_here_1206": "裝飾項目在此處無效。", + "Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name_1207": "無法將裝飾項目套用至多個同名的 get/set 存取子。", + "Default_export_of_the_module_has_or_is_using_private_name_0_4082": "模組的預設匯出具有或正在使用私用名稱 '{0}'。", + "Delete_all_unused_declarations_95024": "刪除所有未使用的宣告", + "Delete_the_outputs_of_all_projects_6365": "刪除所有專案的輸出", + "Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react__6084": "[即將淘汰] 請改用 '--jsxFactory'。當目標為 'react' JSX 發出時,為 createElement 指定所叫用的物件", + "Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file_6170": "[即將淘汰] 請改用 '--outFile'。 串連輸出並將其發出到單一檔案", + "Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files_6160": "[即將淘汰] 請改用 '--skipLibCheck'。跳過預設程式庫宣告檔案的類型檢查。", + "Digit_expected_1124": "必須是數字。", + "Directory_0_does_not_exist_skipping_all_lookups_in_it_6148": "目錄 '{0}' 不存在,將會跳過其中所有查閱。", + "Disable_checking_for_this_file_90018": "停用此檔案的檢查", + "Disable_size_limitations_on_JavaScript_projects_6162": "停用 JavaScript 專案的大小限制。", + "Disable_strict_checking_of_generic_signatures_in_function_types_6185": "停用函式類型中一般簽章的 Strict 檢查。", + "Disallow_inconsistently_cased_references_to_the_same_file_6078": "不允許相同檔案大小寫不一致的參考。", + "Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files_6159": "不要在編譯後的檔案清單中新增三道斜線的參考或匯入的模組。", + "Do_not_emit_comments_to_output_6009": "請勿將註解發出到輸出。", + "Do_not_emit_declarations_for_code_that_has_an_internal_annotation_6056": "請勿發出包含 '@internal' 註釋的程式碼宣告。", + "Do_not_emit_outputs_6010": "請勿發出輸出。", + "Do_not_emit_outputs_if_any_errors_were_reported_6008": "如果回報了任何錯誤,即不發出輸出。", + "Do_not_emit_use_strict_directives_in_module_output_6112": "請勿在模組輸出中發出 'use strict' 指示詞。", + "Do_not_erase_const_enum_declarations_in_generated_code_6007": "請勿清除產生之程式碼中的 const 列舉宣告。", + "Do_not_generate_custom_helper_functions_like_extends_in_compiled_output_6157": "不要在編譯後的輸出中產生自訂的協助程式函式,例如 '__extends'。", + "Do_not_include_the_default_library_file_lib_d_ts_6158": "不要包含預設程式庫檔案 (lib.d.ts)。", + "Do_not_report_errors_on_unreachable_code_6077": "請勿回報無法執行到之程式碼的錯誤。", + "Do_not_report_errors_on_unused_labels_6074": "請勿回報未使用之標籤的錯誤。", + "Do_not_resolve_the_real_path_of_symlinks_6013": "請勿解析符號連結的真實路徑。", + "Do_not_truncate_error_messages_6165": "不要截斷錯誤訊息。", + "Duplicate_declaration_0_2718": "重複宣告 '{0}'。", + "Duplicate_function_implementation_2393": "函式實作重複。", + "Duplicate_identifier_0_2300": "識別碼 '{0}' 重複。", + "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_2441": "識別碼 '{0}' 重複。編譯器會將名稱 '{1}' 保留在模組的最上層範圍中。", + "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_func_2529": "識別碼 '{0}' 重複。編譯器會將名稱 '{1}' 保留在含有非同步函式模組的最上層範圍中。", + "Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions_2520": "識別碼 '{0}' 重複。編譯器會使用宣告 '{1}' 支援非同步函式。", + "Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters_2396": "識別碼 'arguments'' 重複。編譯器會使用 'arguments' 來初始化剩餘參數。", + "Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_me_2543": "識別碼 '_newTarget' 重複。編譯器使用變數宣告 '_newTarget' 擷取 'new.target' 中繼屬性參考。", + "Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference_2401": "識別碼 '_super' 重複。編譯器會使用 '_super' 來擷取基底類別參考。", + "Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference_2399": "識別碼 '_this' 重複。編譯器會使用變數宣告 '_this' 來擷取 'this' 參考。", + "Duplicate_label_0_1114": "標籤 '{0}' 重複。", + "Duplicate_number_index_signature_2375": "數字索引簽章重複。", + "Duplicate_string_index_signature_2374": "字串索引簽章重複。", + "Dynamic_import_cannot_have_type_arguments_1326": "動態匯入不能有型別引數", + "Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext_1323": "只有當 '--module' 旗標是 'commonjs' 或 'esNext' 時,才支援動態匯入。", + "Dynamic_import_must_have_one_specifier_as_an_argument_1324": "動態匯入必須有一個指定名稱作為引數。", + "Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036": "動態匯入的指定名稱必須屬於類型 'string',但這裡的類型為 '{0}'。", + "Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015": "因為索引運算式不屬於類型 'number',所以元素具有隱含 'any' 類型。", + "Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature_7017": "元素隱含地擁有 'any' 類型,因為類型 '{0}' 不具索引簽章。", + "Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files_6164": "在輸出檔的開頭發出 UTF-8 位元組順序標記 (BOM)。", + "Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file_6151": "發出單一檔案包含來源對應,而不要使用個別的檔案。", + "Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap__6152": "使用單一檔案發出來源與來源對應。必須設定 '--inlineSourceMap' 或 '--sourceMap'。", + "Enable_all_strict_type_checking_options_6180": "啟用所有 Strict 類型檢查選項。", + "Enable_project_compilation_6302": "啟用專案編譯", + "Enable_strict_checking_of_function_types_6186": "啟用嚴格檢查函式類型。", + "Enable_strict_checking_of_property_initialization_in_classes_6187": "啟用類別中屬性初始化的 strict 檢查。", + "Enable_strict_null_checks_6113": "啟用嚴格 null 檢查。", + "Enable_tracing_of_the_name_resolution_process_6085": "啟用名稱解析流程的追蹤。", + "Enable_verbose_logging_6366": "啟用詳細資訊記錄", + "Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for__7037": "透過為所有匯入建立命名空間物件,讓 CommonJS 和 ES 模組之間的產出有互通性。意指 'allowSyntheticDefaultImports'。", + "Enables_experimental_support_for_ES7_async_functions_6068": "啟用 ES7 非同步函式的實驗支援。", + "Enables_experimental_support_for_ES7_decorators_6065": "啟用 ES7 裝飾項目的實驗支援。", + "Enables_experimental_support_for_emitting_type_metadata_for_decorators_6066": "啟用實驗支援以發出裝飾項目類型的中繼資料。", + "Enum_0_used_before_its_declaration_2450": "列舉 '{0}' 的位置在其宣告之前。", + "Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations_2567": "列舉宣告只能與命名空間或其他列舉宣告合併。", + "Enum_declarations_must_all_be_const_or_non_const_2473": "列舉宣告必須都是 const 或非 const。", + "Enum_member_expected_1132": "必須是列舉成員。", + "Enum_member_must_have_initializer_1061": "列舉成員必須有初始設定式。", + "Enum_name_cannot_be_0_2431": "列舉名稱不得為 '{0}'。", + "Enum_type_0_has_members_with_initializers_that_are_not_literals_2535": "列舉類型 '{0}' 有初始設定式非常值的成員。", + "Examples_Colon_0_6026": "範例: {0}", + "Excessive_stack_depth_comparing_types_0_and_1_2321": "比較類型 '{0}' 與 '{1}' 的堆疊深度過深。", + "Expected_0_1_type_arguments_provide_these_with_an_extends_tag_8027": "必須是 {0}-{1} 型別引數; 請提供有 '@ extends' 標記的這類型引數。", + "Expected_0_arguments_but_got_1_2554": "應有 {0} 個引數,但得到 {1} 個。", + "Expected_0_arguments_but_got_1_or_more_2556": "應有 {0} 個引數,但得到 {1} 個或更多。", + "Expected_0_type_arguments_but_got_1_2558": "應有 {0} 個型別引數,但得到 {1} 個。", + "Expected_0_type_arguments_provide_these_with_an_extends_tag_8026": "必須是 {0} 型別引數; 請提供有 '@ extends' 標記的這類引數。", + "Expected_at_least_0_arguments_but_got_1_2555": "至少應有 {0} 個引數,但得到 {1} 個。", + "Expected_at_least_0_arguments_but_got_1_or_more_2557": "應有至少 {0} 個引數,但得到 {1} 個或更多。", + "Expected_corresponding_JSX_closing_tag_for_0_17002": "'{0}' 需要對應的 JSX 結尾標記。", + "Expected_corresponding_closing_tag_for_JSX_fragment_17015": "JSX 片段必須有對應的結尾標記。", + "Expected_type_of_0_field_in_package_json_to_be_string_got_1_6105": "在 'package.json' 中 '{0}' 欄位的類型必須為 'string',但得到 '{1}'。", + "Experimental_Options_6177": "實驗性選項", + "Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_t_1219": "裝飾項目的實驗性支援這項功能可能在未來版本中變更。設定 'experimentalDecorators' 選項可移除此警告。", + "Explicitly_specified_module_resolution_kind_Colon_0_6087": "明確指定的模組解析種類: '{0}'。", + "Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or__1203": "當目標為 ECMAScript 模組時,無法使用匯出指派。請考慮改用 'export default' 或其他模組格式。", + "Export_assignment_is_not_supported_when_module_flag_is_system_1218": "當 '--module' 旗標為 'system' 時,不支援匯出指派。", + "Export_declaration_conflicts_with_exported_declaration_of_0_2484": "匯出宣告與匯出的 '{0}' 宣告相衝突。", + "Export_declarations_are_not_permitted_in_a_namespace_1194": "在命名空間中不可使用匯出宣告。", + "Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_2656": "匯出的外部封裝類型檔案 '{0}' 不是模組。請連絡封裝作者以更新封裝定義。", + "Exported_external_package_typings_file_cannot_contain_tripleslash_references_Please_contact_the_pack_2654": "匯出的外部封裝類型檔案不得包含三斜線的參考。請連絡封裝作者以更新封裝定義。", + "Exported_type_alias_0_has_or_is_using_private_name_1_4081": "匯出的類型別名 '{0}' 具有或使用私用名稱 '{1}'。", + "Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4023": "匯出的變數 '{0}' 具有或使用外部模組 {2} 中的名稱 '{1}',但無法命名。", + "Exported_variable_0_has_or_is_using_name_1_from_private_module_2_4024": "匯出的變數 '{0}' 具有或使用私用模組 {2} 中的名稱 '{1}'。", + "Exported_variable_0_has_or_is_using_private_name_1_4025": "匯出的變數 '{0}' 具有或使用私用名稱 '{1}'。", + "Exports_and_export_assignments_are_not_permitted_in_module_augmentations_2666": "模組增強指定中不允許匯出及匯出指派。", + "Expression_expected_1109": "必須是運算式。", + "Expression_or_comma_expected_1137": "必須是運算式或逗號。", + "Expression_resolves_to_super_that_compiler_uses_to_capture_base_class_reference_2402": "運算式會解析成 '_super',而編譯器會使用其來擷取基底類別參考。", + "Expression_resolves_to_variable_declaration_0_that_compiler_uses_to_support_async_functions_2521": "運算式會解析成變數宣告 '{0}',而編譯器會使用此宣告支援非同步函式。", + "Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta__2544": "運算式將解析成變數宣告 '_newTarget',而供編譯器用來擷取 'new.target' 中繼屬性參考。", + "Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference_2400": "運算式會解析成變數宣告 '_this',而編譯器會使用此宣告來擷取 'this' 參考 。", + "Extract_constant_95006": "擷取常數", + "Extract_function_95005": "擷取函式", + "Extract_to_0_in_1_95004": "擷取至 {1} 中的 {0}", + "Extract_to_0_in_1_scope_95008": "擷取至 {1} 範圍中的 {0}", + "Extract_to_0_in_enclosing_scope_95007": "擷取至封閉式範圍中的 {0}", + "FILE_6035": "檔案", + "FILE_OR_DIRECTORY_6040": "檔案或目錄", + "Failed_to_parse_file_0_Colon_1_5014": "無法剖析檔案 '{0}': {1}。", + "Fallthrough_case_in_switch_7029": "參數中的 fallthrough 案例。", + "File_0_does_not_exist_6096": "檔案 '{0}' 不存在。", + "File_0_exist_use_it_as_a_name_resolution_result_6097": "檔案 '{0}' 存在 - 將其作為名稱解析結果使用。", + "File_0_has_an_unsupported_extension_so_skipping_it_6081": "因為不支援檔案 '{0}' 的副檔名,所以將其跳過。", + "File_0_has_unsupported_extension_The_only_supported_extensions_are_1_6054": "檔案 '{0}' 的附檔名不受支援。僅支援副檔名 {1}。", + "File_0_is_not_a_module_2306": "檔案 '{0}' 不是模組。", + "File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern_6307": "檔案 '{0}' 不在專案檔案清單內。專案必須列出所有檔案,或使用 'include' 模式。", + "File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files_6059": "檔案 '{0}' 不在 'rootDir' '{1}' 之下。'rootDir' 必須包含所有原始程式檔。", + "File_0_not_found_6053": "找不到檔案 '{0}'。", + "File_change_detected_Starting_incremental_compilation_6032": "偵測到檔案變更。正在啟動累加編譯...", + "File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module_80001": "檔案為 CommonJS 模組; 其可轉換為 ES6 模組。", + "File_name_0_differs_from_already_included_file_name_1_only_in_casing_1149": "檔案名稱 '{0}' 與包含的檔案名稱 '{1}' 只差在大小寫。", + "File_name_0_has_a_1_extension_stripping_it_6132": "檔案名稱 '{0}' 的副檔名為 '{1}'。正予以移除。", + "File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildca_5065": "檔案規格不得包含出現在遞迴目錄萬用字元 ('**') 之後的父目錄 ('..'): '{0}'。", + "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010": "檔案規格不能以遞迴目錄萬用字元 ('**') 結尾: '{0}'。", + "Fix_all_detected_spelling_errors_95026": "修正偵測到的所有拼字錯誤", + "Found_0_errors_Watching_for_file_changes_6194": "找到 {0} 個錯誤。正在監看檔案變更。", + "Found_1_error_Watching_for_file_changes_6193": "找到 1 個錯誤。正在監看檔案變更。", + "Found_package_json_at_0_6099": "在 '{0}' 找到 'package.json'。", + "Found_package_json_at_0_Package_ID_is_1_6190": "於 '{0}' 找到 'package.json'。套件識別碼為 '{1}'。", + "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_1250": "以 'ES3' 或 'ES5' 為目標時,strict 模式下的區塊中不允許函式宣告。", + "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_d_1251": "以 'ES3' 或 'ES5' 為目標時,strict 模式下的區塊中不允許函式宣告。類別定義會自動進入 strict 模式。", + "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_1252": "以 'ES3' 或 'ES5' 為目標時,strict 模式下的區塊中不允許函式宣告。模組會自動進入 strict 模式。", + "Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type_7011": "缺少傳回型別註解的函式運算式隱含了 '{0}' 傳回型別。", + "Function_implementation_is_missing_or_not_immediately_following_the_declaration_2391": "遺漏函式實作,或函式實作未緊接在宣告之後。", + "Function_implementation_name_must_be_0_2389": "函式實作名稱必須是 '{0}'。", + "Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_ref_7024": "函式因為沒有傳回型別註解,並在其中一個傳回運算式中直接或間接參考了自己,所以隱含了傳回型別 'any'。", + "Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined_2366": "函式缺少結束傳回陳述式,且傳回類型不包括 'undefined'。", + "Function_overload_must_be_static_2387": "函式多載必須為靜態。", + "Function_overload_must_not_be_static_2388": "函式多載不可為靜態。", + "Generate_get_and_set_accessors_95046": "產生 'get' 與 'set' 存取子", + "Generates_a_sourcemap_for_each_corresponding_d_ts_file_6000": "為每個相對應的 '.d.ts' 檔案產生 sourcemap。", + "Generates_corresponding_d_ts_file_6002": "產生對應的 '.d.ts' 檔案。", + "Generates_corresponding_map_file_6043": "產生對應的 '.map' 檔案。", + "Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_typ_7025": "產生器因為沒有產生任何值,所以隱含有類型 '{0}'。請考慮提供傳回型別。", + "Generators_are_not_allowed_in_an_ambient_context_1221": "環境內容中不允許產生器。", + "Generators_are_only_available_when_targeting_ECMAScript_2015_or_higher_1220": "只有在目標為 ECMAScript 2015 或更高版本時,才可使用產生器。", + "Generic_type_0_requires_1_type_argument_s_2314": "泛型類型 '{0}' 需要 {1} 個型別引數。", + "Generic_type_0_requires_between_1_and_2_type_arguments_2707": "泛型型別 '{0}' 需要介於 {1} 和 {2} 之間的型別引數。", + "Generic_type_instantiation_is_excessively_deep_and_possibly_infinite_2550": "泛型類型具現化的深度過深,而且可能是無限深。", + "Getter_and_setter_accessors_do_not_agree_in_visibility_2379": "getter 和 setter 存取子的可視性不符。", + "Global_module_exports_may_only_appear_at_top_level_1316": "全域模組匯出只能顯示在最上層。", + "Global_module_exports_may_only_appear_in_declaration_files_1315": "全域模組匯出只能顯示在宣告檔案中。", + "Global_module_exports_may_only_appear_in_module_files_1314": "全域模組匯出只能顯示在模組檔案中。", + "Global_type_0_must_be_a_class_or_interface_type_2316": "全域類型 '{0}' 必須是類別或介面類型。", + "Global_type_0_must_have_1_type_parameter_s_2317": "全域類型 '{0}' 必須要有 {1} 個型別參數。", + "Hexadecimal_digit_expected_1125": "必須適十六進位數字。", + "Identifier_expected_0_is_a_reserved_word_in_strict_mode_1212": "必須是識別碼。'{0}' 在 strict 模式中為保留字。", + "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_stric_1213": "必須是識別碼。'{0}' 是 strict 模式中的保留字。類別定義會自動採用 strict 模式。", + "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode_1214": "需要識別碼。'{0}' 是 strict 模式中的保留字。模組會自動採用 strict 模式。", + "Identifier_expected_1003": "必須是識別碼。", + "Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules_1216": "必須有識別碼。'__esModule' 已保留為轉換 ECMAScript 模組時匯出的標記。", + "Ignore_this_error_message_90019": "略過此錯誤訊息", + "Implement_all_inherited_abstract_classes_95040": "實作所有繼承的抽象類別", + "Implement_all_unimplemented_interfaces_95032": "實作所有未實作的介面", + "Implement_inherited_abstract_class_90007": "實作已繼承的抽象類別", + "Implement_interface_0_90006": "實作介面 '{0}'", + "Implements_clause_of_exported_class_0_has_or_is_using_private_name_1_4019": "匯出類別 '{0}' 的 Implements 子句具有或使用私用名稱 '{1}'。", + "Import_0_from_module_1_90013": "從模組 \"{1}\" 匯入 '{0}'", + "Import_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_import_Asterisk_as_1202": "當目標為 ECMAScript 模組時,無法使用匯入指派。請考慮改用 'import * as ns from \"mod\"'、'import {a} from \"mod\"'、'import d from \"mod\"' 或其他模組格式。", + "Import_declaration_0_is_using_private_name_1_4000": "匯入宣告 '{0}' 使用私用名稱 '{1}'。", + "Import_declaration_conflicts_with_local_declaration_of_0_2440": "匯入宣告與 '{0}' 的區域宣告衝突。", + "Import_declarations_in_a_namespace_cannot_reference_a_module_1147": "命名空間中的匯入宣告不得參考模組。", + "Import_emit_helpers_from_tslib_6139": "從 'tslib' 匯入發出協助程式。", + "Import_may_be_converted_to_a_default_import_80003": "匯入可轉換成預設匯入。", + "Import_name_cannot_be_0_2438": "匯入名稱不得為 '{0}'。", + "Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relati_2439": "環境模組宣告中的匯入或匯出宣告,不得透過相對模組名稱參考模組。", + "Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_mod_2667": "模組增強指定中不允許匯入。請考慮將其移至封入外部模組。", + "In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066": "在環境列舉宣告中,成員初始設定式必須是常數運算式。", + "In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enu_2432": "在具有多個宣告的列舉中,只有一個宣告可以在其第一個列舉項目中省略初始設定式。", + "In_const_enum_declarations_member_initializer_must_be_constant_expression_2474": "在 'const' 列舉宣告中,成員初始設定式必須是常數運算式。", + "Include_modules_imported_with_json_extension_6197": "包含匯入有 '.json' 延伸模組的模組", + "Index_signature_in_type_0_only_permits_reading_2542": "類型 '{0}' 中的索引簽章只允許讀取。", + "Index_signature_is_missing_in_type_0_2329": "類型 '{0}' 中遺漏索引簽章。", + "Index_signatures_are_incompatible_2330": "索引簽章不相容。", + "Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local_2395": "合併宣告 '{0}' 中的個別宣告必須全部匯出或全在本機上。", + "Infer_all_types_from_usage_95023": "從用法推斷所有類型", + "Infer_parameter_types_from_usage_95012": "從使用方式推斷參數類型", + "Infer_type_of_0_from_usage_95011": "從使用方式推斷 '{0}' 的類型", + "Initialize_property_0_in_the_constructor_90020": "將建構函式中的屬性 '{0}' 初始化", + "Initialize_static_property_0_90021": "將靜態屬性 '{0}' 初始化", + "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301": "執行個體成員變數 '{0}' 的初始設定式不得參考建構函式中所宣告的識別碼 '{1}'。", + "Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it_2373": "參數 '{0}' 的初始設定式不得參考在其之後宣告的識別碼 '{1}'。", + "Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value_2525": "初始設定式未提供任何值給這個繫結項目,且該繫結項目沒有預設值。", + "Initializers_are_not_allowed_in_ambient_contexts_1039": "環境內容中不得有初始設定式。", + "Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file_6070": "初始化 TypeScript 專案並建立 tsconfig.json 檔案。", + "Insert_command_line_options_and_files_from_a_file_6030": "從檔案插入命令列選項與檔案。", + "Install_0_95014": "安裝 '{0}'", + "Install_all_missing_types_packages_95033": "安裝缺少的所有類型套件", + "Interface_0_cannot_simultaneously_extend_types_1_and_2_2320": "介面 '{0}' 不能同時擴充類型 '{1}' 和 '{2}'。", + "Interface_0_incorrectly_extends_interface_1_2430": "介面 '{0}' 不正確地擴充介面 '{1}'。", + "Interface_declaration_cannot_have_implements_clause_1176": "介面宣告不能有 'implements' 子句。", + "Interface_name_cannot_be_0_2427": "介面名稱不得為 '{0}'。", + "Invalid_character_1127": "無效的字元。", + "Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augm_2665": "增強中的模組名稱無效。模組 '{0}' 於 '{1}' 解析至不具類型的模組,其無法擴增。", + "Invalid_module_name_in_augmentation_module_0_cannot_be_found_2664": "增強指定中的模組名稱無效,找不到模組 '{0}'。", + "Invalid_reference_directive_syntax_1084": "無效的 'reference' 指示詞語法。", + "Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode_1210": "不當使用 '{0}'。類別定義會自動採用 strict 模式。", + "Invalid_use_of_0_Modules_are_automatically_in_strict_mode_1215": "'{0}' 的用法無效。模組會自動採用 strict 模式。", + "Invalid_use_of_0_in_strict_mode_1100": "在 strict 模式中使用 '{0}' 無效。", + "Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name_5067": "'jsxFactory' 的值無效。'{0}' 不是有效的識別碼或限定名稱。", + "Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier_5059": "'--reactNamespace' 的值無效。'{0}' 不是有效的識別碼。", + "JSDoc_0_1_does_not_match_the_extends_2_clause_8023": "JSDoc '@{0} {1}' 不符合 'extends {2}' 子句。", + "JSDoc_0_is_not_attached_to_a_class_8022": "JSDoc ''@{0}' 未連結到類別。", + "JSDoc_may_only_appear_in_the_last_parameter_of_a_signature_8028": "JSDoc '...' 只能出現在特徵標記的最後一個參數中。", + "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_8024": "JSDoc '@param' 標記的名稱為 '{0}',但沒有為該名稱的參數。", + "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_h_8029": "JSDoc '@param' 標籤的名稱為 '{0}',但沒有任何參數使用該名稱。如有陣列類型,則會與 'arguments' 相符。", + "JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags_8021": "JSDoc '@typedef' 標記應具有類型註解,或者其後接著 '@property' 或 '@member' 標記。", + "JSDoc_types_can_only_be_used_inside_documentation_comments_8020": "JSDoc 類型只能在文件註解中使用。", + "JSDoc_types_may_be_moved_to_TypeScript_types_80004": "JSDoc 類型可移為 TypeScript 類型。", + "JSX_attribute_expected_17003": "必須是 JSX 屬性。", + "JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000": "只能將非空白的 'expression' 指派給 JSX 屬性。", + "JSX_element_0_has_no_corresponding_closing_tag_17008": "JSX 元素 '{0}' 沒有對應的結尾標記。", + "JSX_element_attributes_type_0_may_not_be_a_union_type_2600": "JSX 元素的屬性類型 '{0}' 不得為等位型別。", + "JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property_2607": "因為 JSX 項目類別沒有 '{0}' 屬性 (property),所以不支援屬性 (attribute)。", + "JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists_7026": "因為沒有介面 'JSX.{0}',表示 JSX 項目隱含了類型 'any'。", + "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602": "因為全域類型 'JSX.Element' 不存在,所以 JSX 項目隱含有類型 'any'。", + "JSX_element_type_0_does_not_have_any_construct_or_call_signatures_2604": "JSX 項目類型 '{0}' 沒有任何建構或呼叫簽章。", + "JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements_2605": "JSX 項目類型 '{0}' 不是 JSX 項目的建構函式。", + "JSX_elements_cannot_have_multiple_attributes_with_the_same_name_17001": "JSX 項目不得有多個同名的屬性。", + "JSX_expressions_must_have_one_parent_element_2657": "JSX 運算式必須具有一個父元素。", + "JSX_fragment_has_no_corresponding_closing_tag_17014": "JSX 片段沒有對應的結尾標記。", + "JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma_17017": "使用內嵌 JSX 處理站 pragma 時,不支援 JSX 片段", + "JSX_fragment_is_not_supported_when_using_jsxFactory_17016": "使用 --jsxFactory 時,不支援 JSX 片段", + "JSX_spread_child_must_be_an_array_type_2609": "JSX 擴張子系必須為陣列類型。", + "Jump_target_cannot_cross_function_boundary_1107": "跳躍目標不得跨越函式界限。", + "KIND_6034": "類型", + "LOCATION_6037": "位置", + "Language_service_is_disabled_9004": "已停用語言服務。", + "Left_side_of_comma_operator_is_unused_and_has_no_side_effects_2695": "逗號運算子左側未使用,而且沒有任何不良影響。", + "Line_break_not_permitted_here_1142": "這裡不可使用分行符號。", + "Line_terminator_not_permitted_before_arrow_1200": "箭號前不得有行結束字元。", + "List_of_folders_to_include_type_definitions_from_6161": "要包含之類型定義所屬資料夾的清單。", + "List_of_language_service_plugins_6181": "語言服務外掛程式清單。", + "List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime_6168": "資料夾的清單。這些資料夾內所含的合併內容代表了專案在執行階段時的結果。", + "Loading_0_from_the_root_dir_1_candidate_location_2_6109": "正在從根目錄 '{1}',候選位置 '{2}' 載入 '{0}'。", + "Loading_module_0_from_node_modules_folder_target_file_type_1_6098": "正在從 'node_modules' 資料夾載入模組 '{0}',目標檔案類型 '{1}'。", + "Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1_6095": "正在將模組載入為檔案/資料夾,候選模組位置 '{0}',目標檔案類型 '{1}'。", + "Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1_6048": "地區設定的格式必須是 <語言> 或 <語言>-<國家/地區>。例如 '{0}' 或 '{1}'。", + "Longest_matching_prefix_for_0_is_1_6108": "符合 '{0}' 的前置詞最長為 '{1}'。", + "Looking_up_in_node_modules_folder_initial_location_0_6125": "目前正在 'node_modules' 資料夾中查詢,初始位置為 '{0}'。", + "Make_all_super_calls_the_first_statement_in_their_constructor_95036": "在其建構函式的第一個陳述式中呼叫所有的 'super()'", + "Make_super_call_the_first_statement_in_the_constructor_90002": "使 'super()' 呼叫成為建構函式中的第一個陳述式", + "Mapped_object_type_implicitly_has_an_any_template_type_7039": "對應的物件類型隱含具有 'any' 範本類型。", + "Member_0_implicitly_has_an_1_type_7008": "成員 '{0}' 隱含了 '{1}' 類型。", + "Merge_conflict_marker_encountered_1185": "偵測到合併衝突標記。", + "Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_d_2652": "合併宣告 '{0}' 不得包含預設匯出宣告。請考慮改為加入獨立型 'export default {0}' 宣告。", + "Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constru_17013": "只有函式宣告、函式運算式或建構函式的主體中允許中繼屬性 '{0}'。", + "Method_0_cannot_have_an_implementation_because_it_is_marked_abstract_1245": "因為方法 '{0}' 已標記為抽象,所以不可具有實作。", + "Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4101": "匯出介面的方法 '{0}' 具有或使用私用模組 '{2}' 的名稱 '{1}'。", + "Method_0_of_exported_interface_has_or_is_using_private_name_1_4102": "匯出介面的方法 '{0}' 具有或使用私用名稱 '{1}'。", + "Modifiers_cannot_appear_here_1184": "此處不得出現修飾詞。", + "Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_1340": "模組 '{0}' 未參考任何類型,但在此用為類型。", + "Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here_1339": "模組 '{0}' 未參考任何值,但在此用為值。", + "Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambig_2308": "模組 {0} 已匯出名為 '{1}' 的成員。請考慮明確重新匯出項目以解決模稜兩可的情形。", + "Module_0_has_no_default_export_1192": "模組 '{0}' 沒有預設匯出。", + "Module_0_has_no_exported_member_1_2305": "模組 '{0}' 沒有匯出的成員 '{1}'。", + "Module_0_has_no_exported_member_1_Did_you_mean_2_2724": "模組 '{0}' 沒有任何匯出的成員 '{1}'。您是否指的是 '{2}'?", + "Module_0_is_hidden_by_a_local_declaration_with_the_same_name_2437": "同名的區域宣告隱藏了模組 '{0}'。", + "Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct_2497": "模組 '{0}' 會解析成非模組實體,且不可使用這個建構加以匯入。", + "Module_0_uses_export_and_cannot_be_used_with_export_Asterisk_2498": "模組 '{0}' 使用 'export =',因而無法以 'export *' 的方式使用。", + "Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified_6145": "此檔案未修改,因此模組 '{0}' 已解析為在 '{1}' 中所宣告的環境模組。", + "Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1_6144": "模組 '{0}' 在檔案 '{1}' 中已解析為本機宣告的環境模組。", + "Module_0_was_resolved_to_1_but_jsx_is_not_set_6142": "模組 '{0}' 已解析為 '{1}',但未設定 '--jsx'。", + "Module_Resolution_Options_6174": "模組解析選項", + "Module_name_0_matched_pattern_1_6092": "模組名稱 '{0}',符合的模式 '{1}'。", + "Module_name_0_was_not_resolved_6090": "======== 模組名稱 '{0}' 未解析。========", + "Module_name_0_was_successfully_resolved_to_1_6089": "======== 模組名稱 '{0}' 已成功解析為 '{1}'。========", + "Module_resolution_kind_is_not_specified_using_0_6088": "未指定模組解析種類,將使用 '{0}'。", + "Module_resolution_using_rootDirs_has_failed_6111": "使用 'rootDirs' 解析模組失敗。", + "Move_to_a_new_file_95049": "移至新檔", + "Multiple_consecutive_numeric_separators_are_not_permitted_6189": "不允許多個連續的數字分隔符號。", + "Multiple_constructor_implementations_are_not_allowed_2392": "不允許多個建構函式實作。", + "NEWLINE_6061": "新行", + "Named_property_0_of_types_1_and_2_are_not_identical_2319": "類型 '{1}' 及 '{2}' 的具名屬性 '{0}' 不一致。", + "Namespace_0_has_no_exported_member_1_2694": "命名空間 '{0}' 沒有匯出的成員 '{1}'。", + "No_base_constructor_has_the_specified_number_of_type_arguments_2508": "沒有任何基底建構函式具有指定的類型引數數量。", + "No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2_18003": "在設定檔 '{0}' 中找不到任何輸入。指定的 'include' 路徑為 '{1}','exclude' 路徑為 '{2}'。", + "Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2_2515": "非抽象類別 '{0}' 未實作從類別 '{2}' 繼承而來的抽象成員 '{1}'。", + "Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1_2653": "非抽象類別運算式未實作從類別 '{1}' 繼承而來的抽象成員 '{0}'。", + "Not_all_code_paths_return_a_value_7030": "部分程式碼路徑並未傳回值。", + "Numeric_index_type_0_is_not_assignable_to_string_index_type_1_2413": "數值索引類型 '{0}' 不可指派給字串索引類型 '{1}'。", + "Numeric_separators_are_not_allowed_here_6188": "這裡不允許數字分隔符號。", + "Object_is_of_type_unknown_2571": "物件的類型為 '未知'。", + "Object_is_possibly_null_2531": "物件可能為「null」。", + "Object_is_possibly_null_or_undefined_2533": "物件可能為「null」或「未定義」。", + "Object_is_possibly_undefined_2532": "物件可能為「未定義」。", + "Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1_2353": "物件常值只可指定已知的屬性,且類型 '{1}' 中沒有 '{0}'。", + "Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_writ_2561": "物件常值只會指定已知的屬性,但類型 '{1}' 中沒有 '{0}'。您是否想要寫入 '{2}'?", + "Object_literal_s_property_0_implicitly_has_an_1_type_7018": "物件常值的屬性 '{0}' 隱含了 '{1}' 類型。", + "Octal_digit_expected_1178": "必須是八進位數字。", + "Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0_8017": "八進位的常值類型必須使用 ES2015 語法。請使用語法 '{0}'。", + "Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0_8018": "列舉成員初始設定式中不允許八進位常值。請使用語法 '{0}'。", + "Octal_literals_are_not_allowed_in_strict_mode_1121": "strict 模式中不允許八進位常值。", + "Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0_1085": "當目標為 ECMAScript 5 及更高版本時,不可使用八進位的常值。請使用語法 '{0}'。", + "Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement_1091": "'for...in' 陳述式中只可包含一個變數宣告。", + "Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement_1188": "'for...of' 陳述式只能包含一個變數宣告。", + "Only_a_void_function_can_be_called_with_the_new_keyword_2350": "只有 void 函式可以使用 'new' 關鍵字進行呼叫。", + "Only_ambient_modules_can_use_quoted_names_1035": "只有環境模組可以使用括以引號的名稱。", + "Only_amd_and_system_modules_are_supported_alongside_0_6082": "只有 'amd' 與 'system' 模組連同受支援 --{0}。", + "Only_emit_d_ts_declaration_files_6014": "只發出 '.d.ts' 宣告檔案。", + "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002": "類別 'extends' 子句中,目前只支援具有選擇性型別引數的識別碼/限定名稱。", + "Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword_2340": "只有基底類別之公開且受保護的方法,才可透過 'super' 關鍵字存取。", + "Operator_0_cannot_be_applied_to_types_1_and_2_2365": "無法將運算子 '{0}' 套用至類型 '{1}' 和 '{2}'。", + "Option_0_can_only_be_specified_in_tsconfig_json_file_6064": "只能在 'tsconfig.json' 檔案中指定選項 '{0}'。", + "Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided_5051": "只有在已提供選項 '--inlineSourceMap' 或選項 '--sourceMap' 時,才可使用選項 '{0}'。", + "Option_0_cannot_be_specified_with_option_1_5053": "不得同時指定選項 '{0}' 與選項 '{1}'。", + "Option_0_cannot_be_specified_without_specifying_option_1_5052": "必須指定選項 '{1}' 才可指定選項 '{0}'。", + "Option_0_cannot_be_specified_without_specifying_option_1_or_option_2_5069": "指定選項 '{0}' 時,必須指定選項 '{1}' 或選項 '{2}'。", + "Option_0_should_have_array_of_strings_as_a_value_6103": "選項 '{0}' 應以字串陣列作為值。", + "Option_build_must_be_the_first_command_line_argument_6369": "選項 '--build' 必須是第一個命令列引數。", + "Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES_5047": "只有在提供選項 '--module' 或是 'target' 為 'ES2015' 或更高項目時,才可使用選項 'isolatedModules'。", + "Option_paths_cannot_be_used_without_specifying_baseUrl_option_5060": "必須指定 '--baseUrl' 選項才能使用選項 'paths'。", + "Option_project_cannot_be_mixed_with_source_files_on_a_command_line_5042": "在命令列上,'project' 選項不得與原始程式檔並用。", + "Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070": "指定選項 '-resolveJsonModule' 時,不可沒有 'node' 模組解析策略。", + "Options_0_and_1_cannot_be_combined_6370": "無法合併選項 '{0}' 與 '{1}'。", + "Options_Colon_6027": "選項:", + "Output_directory_for_generated_declaration_files_6166": "所產生之宣告檔案的輸出目錄。", + "Output_file_0_from_project_1_does_not_exist_6309": "沒有來自專案 '{1}' 的輸出檔 '{0}'", + "Output_file_0_has_not_been_built_from_source_file_1_6305": "輸出檔 '{0}' 並非從原始程式檔 '{1}' 建置。", + "Overload_signature_is_not_compatible_with_function_implementation_2394": "多載簽章與函式實作不相容。", + "Overload_signatures_must_all_be_abstract_or_non_abstract_2512": "多載簽章必須全為抽象或非抽象。", + "Overload_signatures_must_all_be_ambient_or_non_ambient_2384": "多載簽章都必須是環境或非環境簽章。", + "Overload_signatures_must_all_be_exported_or_non_exported_2383": "多載簽章必須全部匯出或不匯出。", + "Overload_signatures_must_all_be_optional_or_required_2386": "多載簽章都必須是選擇性或必要簽章。", + "Overload_signatures_must_all_be_public_private_or_protected_2385": "多載簽章必須是公用、私用或受保護。", + "Parameter_0_cannot_be_referenced_in_its_initializer_2372": "無法在參數 '{0}' 的初始設定式中參考此參數。", + "Parameter_0_implicitly_has_an_1_type_7006": "參數 '{0}' 隱含了 '{1}' 類型。", + "Parameter_0_is_not_in_the_same_position_as_parameter_1_1227": "參數 '{0}' 與參數 '{1}' 不在同一個位置。", + "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4066": "匯出介面之呼叫簽章的參數 '{0}' 具有或使用私用模組 '{2}' 中的名稱 '{1}'。", + "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4067": "匯出介面之呼叫簽章的參數 '{0}' 具有或使用私用名稱 '{1}'。", + "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_can_4061": "匯出類別中建構函式的參數 '{0}' 具有或使用外部模組 {2} 中的名稱 '{1}',但無法命名。", + "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2_4062": "匯出類別中建構函式的參數 '{0}' 具有或使用私用模組 '{2}' 中的名稱 '{1}'。", + "Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1_4063": "匯出類別中建構函式的參數 '{0}' 具有或使用私用名稱 '{1}'。", + "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_mod_4064": "匯出介面中建構函式簽章的參數 '{0}' 具有或使用私用模組 '{2}' 中的名稱 '{1}'。", + "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4065": "匯出介面中建構函式簽章的參數 '{0}' 具有或使用私用名稱 '{1}'。", + "Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4076": "匯出函式的參數 '{0}' 具有或使用外部模組 {2} 中的名稱 '{1}',但無法命名。", + "Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2_4077": "匯出函式的參數 '{0}' 具有或使用私用模組 '{2}' 中的名稱 '{1}'。", + "Parameter_0_of_exported_function_has_or_is_using_private_name_1_4078": "匯出函式的參數 '{0}' 具有或使用私用名稱 '{1}'。", + "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4091": "匯出介面的索引簽章參數 '{0}' 具有或使用私用模組 '{2}' 中的名稱 '{1}'。", + "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1_4092": "匯出介面的索引簽章參數 '{0}' 具有或使用私用名稱 '{1}'。", + "Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4074": "匯出介面中方法的參數 '{0}' 具有或使用私用模組 '{2}' 中的名稱 '{1}'。", + "Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4075": "匯出介面中方法的參數 '{0}' 具有或使用私用名稱 '{1}'。", + "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_c_4071": "匯出類別中公用方法的參數 '{0}' 具有或使用外部模組 {2} 中的名稱 '{1}',但無法命名。", + "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4072": "匯出類別中公用方法的參數 '{0}' 具有或使用私用模組 '{2}' 中的名稱 '{1}'。", + "Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4073": "匯出類別中公用方法的參數 '{0}' 具有或使用私用名稱 '{1}'。", + "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module__4068": "匯出類別中公用靜態方法的參數 '{0}' 具有或使用外部模組 {2} 中的名稱 '{1}',但無法命名。", + "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4069": "匯出類別中公用靜態方法的參數 '{0}' 具有或使用私用模組 '{2}' 中的名稱 '{1}'。", + "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4070": "匯出類別中公用靜態方法的參數 '{0}' 具有或使用私用名稱 '{1}'。", + "Parameter_cannot_have_question_mark_and_initializer_1015": "參數不得有問號及初始設定式。", + "Parameter_declaration_expected_1138": "必須是參數宣告。", + "Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2_4036": "匯出類別中公用 setter '{0}' 的參數類型具有或是正在使用私用模組 '{2}' 中的名稱 '{1}'。", + "Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_private_name_1_4037": "匯出類別中公用 setter '{0}' 的參數類型具有或正在使用私用名稱 '{1}'。", + "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_name_1_from_private_mod_4034": "匯出類別中公用靜態 setter '{0}' 的參數類型具有或正在使用私用模組 '{2}' 中的名稱 '{1}'。", + "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1_4035": "匯出類別中公用靜態 setter '{0}' 的參數類型具有或正在使用私用名稱 '{1}'。", + "Parse_in_strict_mode_and_emit_use_strict_for_each_source_file_6141": "在 strict 模式中進行剖析,並為每個來源檔案發出 \"use strict\"。", + "Pattern_0_can_have_at_most_one_Asterisk_character_5061": "模式 '{0}' 最多只可有一個 '*' 字元。", + "Prefix_0_with_an_underscore_90025": "具有底線的前置詞 '{0}'", + "Prefix_all_unused_declarations_with_where_possible_95025": "若可行,為所有未使用的宣告加上前置詞 '_'", + "Print_names_of_files_part_of_the_compilation_6155": "列印編譯時檔案部分的名稱。", + "Print_names_of_generated_files_part_of_the_compilation_6154": "列印編譯時所產生之檔案部分的名稱。", + "Print_the_compiler_s_version_6019": "列印編譯器的版本。", + "Print_this_message_6017": "列印這則訊息。", + "Project_0_can_t_be_built_because_its_dependency_1_has_errors_6363": "因為專案 '{0}' 的相依性 '{1}' 發生錯誤,所以無法建置該專案", + "Project_0_is_out_of_date_because_its_dependency_1_is_out_of_date_6353": "因為專案 '{0}' 的相依性 '{1}' 已過期,所以該專案已過期", + "Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2_6350": "因為最舊的輸出 '{1}' 早於最新的輸入 '{2}',所以專案 '{0}' 已過期", + "Project_0_is_out_of_date_because_output_file_1_does_not_exist_6352": "因為輸出檔案 '{1}' 不存在,所以專案 '{0}' 已過期", + "Project_0_is_up_to_date_6361": "專案 '{0}' 為最新狀態", + "Project_0_is_up_to_date_because_newest_input_1_is_older_than_oldest_output_2_6351": "因為最新的輸入 '{1}' 早於最舊的輸出 '{2}',所以專案 '{0}' 為最新狀態", + "Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies_6354": "專案 '{0}' 為最新狀態,且有來自其相依性的 .d.ts 檔案", + "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202": "專案參考不會形成循環圖。但偵測到循環: {0}", + "Projects_in_this_build_Colon_0_6355": "此組建中的專案: {0}", + "Projects_to_reference_6300": "專案至參考", + "Property_0_does_not_exist_on_const_enum_1_2479": "'const' 列舉 '{1}' 上並沒有屬性 '{0}'。", + "Property_0_does_not_exist_on_type_1_2339": "類型 '{1}' 沒有屬性 '{0}'。", + "Property_0_does_not_exist_on_type_1_Did_you_forget_to_use_await_2570": "類型 '{1}' 不存在屬性 '{0}'。是否忘記要使用 'await'?", + "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551": "類型 '{1}' 沒有屬性 '{0}'。您指的是 '{2}' 嗎?", + "Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1_2546": "屬性 '{0}' 有衝突的宣告,在類型 '{1}' 中無法存取。", + "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor_2564": "屬性 '{0}' 沒有初始設定式,且未在建構函式中明確指派。", + "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033": "因為屬性 '{0}' 的 get 存取子沒有傳回類型註釋,致使該屬性意味著類型 'any'。", + "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032": "因為屬性 '{0}' 的 set 存取子沒有參數類型註釋,致使該屬性意味著類型 'any'。", + "Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2_2416": "類型 '{1}' 中的屬性 '{0}' 無法指派給基底類型 '{2}' 中的相同屬性。", + "Property_0_in_type_1_is_not_assignable_to_type_2_2603": "不得將類型 '{1}' 的屬性 '{0}' 指派給類型 '{2}'。", + "Property_0_is_declared_but_its_value_is_never_read_6138": "屬性 '{0}' 已宣告但從未讀取其值。", + "Property_0_is_incompatible_with_index_signature_2530": "屬性 '{0}' 和索引簽章不相容。", + "Property_0_is_missing_in_type_1_2324": "類型 '{1}' 遺漏屬性 '{0}'。", + "Property_0_is_optional_in_type_1_but_required_in_type_2_2327": "在類型 '{1}' 中,'{0}' 是選擇性屬性,但在類型 '{2}' 中則為必要屬性。", + "Property_0_is_private_and_only_accessible_within_class_1_2341": "'{0}' 是私用屬性,只可從類別 '{1}' 中存取。", + "Property_0_is_private_in_type_1_but_not_in_type_2_2325": "在類型 '{1}' 中,'{0}' 是私用屬性,但在類型 '{2}' 中不是。", + "Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1_2446": "'{0}' 是受保護屬性,只能透過類別 '{1}' 的執行個體進行存取。", + "Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses_2445": "'{0}' 是受保護屬性,只可從類別 '{1}' 及其子類別中存取。", + "Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2_2443": "'{0}' 是受保護屬性,但類型 '{1}' 不是衍生自 '{2}' 的類別。", + "Property_0_is_protected_in_type_1_but_public_in_type_2_2444": "在類型 '{1}' 中,'{0}' 是受保護屬性,但在類型 '{2}' 中是公用屬性。", + "Property_0_is_used_before_being_assigned_2565": "屬性 '{0}' 已在指派之前使用。", + "Property_0_of_JSX_spread_attribute_is_not_assignable_to_target_property_2606": "JSX 擴張屬性 (Attribute) 的屬性 (Property) '{0}' 不可指派給目標屬性 (Property)。", + "Property_0_of_exported_class_expression_may_not_be_private_or_protected_4094": "匯出之類別運算式的屬性 '{0}' 可能為私人或受保護。", + "Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4032": "匯出介面的屬性 '{0}' 具有或使用私用模組 '{2}' 中的名稱 '{1}'。", + "Property_0_of_exported_interface_has_or_is_using_private_name_1_4033": "匯出介面的屬性 '{0}' 具有或使用私用名稱 '{1}'。", + "Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2_2412": "類型 '{1}' 的屬性 '{0}' 不可指派給數值索引類型 '{2}'。", + "Property_0_of_type_1_is_not_assignable_to_string_index_type_2_2411": "類型 '{1}' 的屬性 '{0}' 不可指派給字串索引類型 '{2}'。", + "Property_assignment_expected_1136": "必須是屬性指派。", + "Property_destructuring_pattern_expected_1180": "必須是屬性解構模式。", + "Property_or_signature_expected_1131": "必須是屬性或簽章。", + "Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_li_1328": "屬性值僅能為字串常值、數值常值、'true'、'false'、'null'、物件常值或陣列常值。", + "Provide_full_support_for_iterables_in_for_of_spread_and_destructuring_when_targeting_ES5_or_ES3_6179": "當目標為 'ES5' 或 'ES3' 時,為 'for-of'、擴張及解構提供完整的支援。", + "Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4098": "匯出類別的公用方法 '{0}' 具有或使用外部模組 {2} 的名稱 '{1}',但無法命名。", + "Public_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4099": "匯出類別的公用方法 '{0}' 具有或使用私用模組 '{2}' 的名稱 '{1}'。", + "Public_method_0_of_exported_class_has_or_is_using_private_name_1_4100": "匯出類別的公用方法 '{0}' 具有或使用私用名稱 '{1}'。", + "Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_name_4029": "匯出類別的公用屬性 '{0}' 具有或使用外部模組 {2} 中的名稱 '{1}',但無法命名。", + "Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4030": "匯出類別的公用屬性 '{0}' 具有或使用私用模組 '{2}' 中的名稱 '{1}'。", + "Public_property_0_of_exported_class_has_or_is_using_private_name_1_4031": "匯出類別的公用屬性 '{0}' 具有或使用私用名稱 '{1}'。", + "Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_4095": "匯出類別的公用靜態方法 '{0}' 具有或使用外部模組 {2} 的名稱 '{1}',但無法命名。", + "Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4096": "匯出類別的公用靜態方法 '{0}' 具有或使用私用模組 '{2}' 的名稱 '{1}'。", + "Public_static_method_0_of_exported_class_has_or_is_using_private_name_1_4097": "匯出類別的公用靜態方法 '{0}' 具有或使用私用名稱 '{1}'。", + "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot__4026": "匯出類別的公用靜態屬性 '{0}' 具有或使用外部模組 {2} 中的名稱 '{1}',但無法命名。", + "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4027": "匯出類別的公用靜態屬性 '{0}' 具有或使用私用模組 '{2}' 中的名稱 '{1}'。", + "Public_static_property_0_of_exported_class_has_or_is_using_private_name_1_4028": "匯出類別的公用靜態屬性 '{0}' 具有或使用私用名稱 '{1}'。", + "Raise_error_on_expressions_and_declarations_with_an_implied_any_type_6052": "當運算式及宣告包含隱含的 'any' 類型時顯示錯誤。", + "Raise_error_on_this_expressions_with_an_implied_any_type_6115": "對具有隱含 'any' 類型的 'this' 運算式引發錯誤。", + "Redirect_output_structure_to_the_directory_6006": "將輸出結構重新導向至目錄。", + "Referenced_project_0_must_have_setting_composite_Colon_true_6306": "參考的專案 '{0}' 之設定 \"composite\" 必須為 true。", + "Remove_all_unreachable_code_95051": "移除所有無法連線的程式碼", + "Remove_all_unused_labels_95054": "移除所有未使用的標籤", + "Remove_braces_from_arrow_function_95060": "從箭號函式移除大括號", + "Remove_declaration_for_Colon_0_90004": "移除 '{0}' 的宣告", + "Remove_destructuring_90009": "移除解構", + "Remove_import_from_0_90005": "從 '{0}' 移除匯入", + "Remove_unreachable_code_95050": "移除無法連線的程式碼", + "Remove_unused_label_95053": "移除未使用的標籤", + "Remove_variable_statement_90010": "移除變數陳述式", + "Replace_import_with_0_95015": "以 '{0}' 取代匯入。", + "Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "當函式中的部分程式碼路徑並未傳回值時回報錯誤。", + "Report_errors_for_fallthrough_cases_in_switch_statement_6076": "回報 switch 陳述式內 fallthrough 案例的錯誤。", + "Report_errors_in_js_files_8019": "報告 .js 檔案中的錯誤。", + "Report_errors_on_unused_locals_6134": "回報未使用之區域變數的錯誤。", + "Report_errors_on_unused_parameters_6135": "回報未使用之參數的錯誤。", + "Required_type_parameters_may_not_follow_optional_type_parameters_2706": "必要型別參數可能未遵循選擇性型別參數。", + "Resolution_for_module_0_was_found_in_cache_from_location_1_6147": "從位置 '{1}' 的快取中找到模組 '{0}' 的解析。", + "Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols_6195": "只將 'keyof' 解析為字串值的屬性名稱 (無任何數字或符號)。", + "Resolving_from_node_modules_folder_6118": "正在從 node_modules 資料夾解析...", + "Resolving_module_0_from_1_6086": "======== 正在從 '{1}' 解析模組 '{0}'。========", + "Resolving_module_name_0_relative_to_base_url_1_2_6094": "正在解析與基底 URL '{1}' 相對的模組名稱 '{0}' - '{2}'。", + "Resolving_real_path_for_0_result_1_6130": "正在解析 '{0}' 的真實路徑,結果 '{1}'。", + "Resolving_type_reference_directive_0_containing_file_1_root_directory_2_6116": "======== 正在解析類型參考指示詞 '{0}',包含檔案 '{1}',根目錄 '{2}'。========", + "Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set_6123": "======== 正在解析類型參考指示詞 '{0}',包含檔案 '{1}',未設定根目錄。========", + "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1_6127": "======== 正在解析類型參考指示詞 '{0}',未設定包含檔案,根目錄 '{1}'。========", + "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set_6128": "======== 正在解析類型參考指示詞 '{0}',未設定包含檔案,未設定根目錄。 ========", + "Resolving_using_primary_search_paths_6117": "正在使用主要搜尋路徑進行解析...", + "Resolving_with_primary_search_path_0_6121": "正在解析主要搜尋路徑 '{0}'。", + "Rest_parameter_0_implicitly_has_an_any_type_7019": "剩餘參數 '{0}' 隱含了 'any[]' 類型。", + "Rest_types_may_only_be_created_from_object_types_2700": "Rest 類型只能從物件類型建立。", + "Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4046": "匯出介面中呼叫簽章的傳回型別具有或使用私用模組 '{1}' 中的名稱 '{0}'。", + "Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0_4047": "匯出介面中呼叫簽章的傳回型別具有或使用私用名稱 '{0}'。", + "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_mod_4044": "匯出介面中建構函式簽章的傳回型別具有或使用私用模組 '{1}' 中的名稱 '{0}'。", + "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0_4045": "匯出介面中建構函式簽章的傳回型別具有或使用私用名稱 '{0}'。", + "Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class_2409": "建構函式簽章的傳回類型必須能夠指派給類別的執行個體類型。", + "Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named_4058": "匯出函式的傳回型別具有或使用外部模組 {1} 中的名稱 '{0}',但無法命名。", + "Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1_4059": "匯出函式的傳回型別具有或使用私用模組 '{1}' 中的名稱 '{0}'。", + "Return_type_of_exported_function_has_or_is_using_private_name_0_4060": "匯出函式的傳回型別具有或使用私用名稱 '{0}'。", + "Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4048": "匯出介面中索引簽章的傳回型別具有或使用私用模組 '{1}' 中的名稱 '{0}'。", + "Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0_4049": "匯出介面中索引簽章的傳回型別具有或使用私用名稱 '{0}'。", + "Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4056": "匯出介面中方法的傳回型別具有或使用私用模組 '{1}' 中的名稱 '{0}'。", + "Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0_4057": "匯出介面中方法的傳回型別具有或使用私用名稱 '{0}'。", + "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_4041": "匯出類別中公用 getter '{0}' 的傳回型別具有或正在使用外部模組 {2} 中的名稱 '{1}',但無法命名。", + "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2_4042": "匯出類別中公用 getter '{0}' 的傳回型別具有或正在使用私用模組 {2} 中的名稱 '{1}'。", + "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_private_name_1_4043": "匯出類別中公用 getter '{0}' 的傳回型別具有或正在使用私用名稱 '{1}'。", + "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_c_4053": "匯出類別中公用方法的傳回型別具有或使用外部模組 {1} 中的名稱 '{0}',但無法命名。", + "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4054": "匯出類別中公用方法的傳回型別具有或使用私用模組 '{1}' 中的名稱 '{0}'。", + "Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0_4055": "匯出類別中公用方法的傳回型別具有或使用私用名稱 '{0}'。", + "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_external_modul_4038": "匯出類別中公用靜態 getter '{0}' 的傳回型別具有或正在使用外部模組 {2} 中的名稱 '{1}',但無法命名。", + "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_4039": "匯出類別中公用靜態 getter '{0}' 的傳回型別具有或正在使用私用模組 '{2}' 中的名稱 '{1}'。", + "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_private_name_1_4040": "匯出類別中公用靜態 getter '{0}' 的傳回型別具有或正在使用私用名稱 '{1}'。", + "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module__4050": "匯出類別中公用靜態方法的傳回型別具有或使用外部模組 {1} 中的名稱 '{0}',但無法命名。", + "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4051": "匯出類別中公用靜態方法的傳回型別具有或使用私用模組 '{1}' 中的名稱 '{0}'。", + "Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0_4052": "匯出類別中公用靜態方法的傳回型別具有或使用私用名稱 '{0}'。", + "Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program_6184": "因為舊程式中的解決方案並無任何變更,所以會重複使用 '{0}' 中的模組解決方案。", + "Reusing_resolution_of_module_0_to_file_1_from_old_program_6183": "對檔案 '{1}' 重複用舊程式中模組 '{0}' 的解決方案。", + "Rewrite_all_as_indexed_access_types_95034": "將全部重寫為經過編製索引的存取類型", + "Rewrite_as_the_indexed_access_type_0_90026": "重寫為索引存取類型 '{0}'", + "Root_directory_cannot_be_determined_skipping_primary_search_paths_6122": "無法判斷根目錄,將略過主要搜尋路徑。", + "STRATEGY_6039": "策略", + "Scoped_package_detected_looking_in_0_6182": "偵測到範圍套件,正於 '{0}' 尋找", + "Setters_cannot_return_a_value_2408": "setter 無法傳回值。", + "Show_all_compiler_options_6169": "顯示所有的編譯器選項。", + "Show_diagnostic_information_6149": "顯示診斷資訊。", + "Show_verbose_diagnostic_information_6150": "顯示詳細診斷資訊。", + "Show_what_would_be_built_or_deleted_if_specified_with_clean_6367": "顯示將會建置 (或刪除 - 若是指定有 '--clean') 的內容", + "Signature_0_must_be_a_type_predicate_1224": "簽章 '{0}' 必須是型別述詞。", + "Skip_type_checking_of_declaration_files_6012": "跳過宣告檔案的類型檢查。", + "Skipping_build_of_project_0_because_its_dependency_1_has_errors_6362": "因為專案 '{0}' 的相依性 '{1}' 發生錯誤,所以跳過建置該專案", + "Skipping_clean_because_not_all_projects_could_be_located_6371": "因為並非所有專案都可找到,所以跳過清理", + "Source_Map_Options_6175": "來源對應選項", + "Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature_2382": "特製化的多載簽章不可指派給任何非特製化的簽章。", + "Specifier_of_dynamic_import_cannot_be_spread_element_1325": "動態匯入的指定名稱不能是展開元素。", + "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_or_ESNEXT_6015": "指定 ECMAScript 目標版本: 'ES3' (預設)、'ES5'、'ES2015'、'ES2016'、'ES2017'、'ES2018' 或 'ESNEXT'。", + "Specify_JSX_code_generation_Colon_preserve_react_native_or_react_6080": "指定 JSX 程式碼產生: 'preserve'、'react-native' 或 'react'。", + "Specify_library_files_to_be_included_in_the_compilation_6079": "請指定要併入編譯中的程式庫檔案。", + "Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext_6016": "指定模組程式碼產生: 'none'、'commonjs'、'amd'、'system'、'umd'、'es2015' 或 'ESNext'。", + "Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6_6069": "指定模組解決方案策略: 'node' (Node.js) 或 'classic' (TypeScript 1.6 前)。", + "Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h_6146": "請指定要在以 'react' JSX 發出為目標時使用的 JSX factory 函式。例如 'React.createElement' 或 'h'。", + "Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix_6060": "指定發出檔案時要用的行尾順序: 'CRLF' (DOS) 或 'LF' (UNIX)。", + "Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations_6004": "指定偵錯工具尋找 TypeScript 檔案的位置,而非原始檔位置。", + "Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations_6003": "指定偵錯工具尋找對應檔的位置,而非產生的位置。", + "Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir_6058": "指定輸入檔案的根目錄。用以控制具有 --outDir 的輸出目錄結構。", + "Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher_2472": "只有當目標為 ECMAScript 5 及更高版本時,才可使用 'new' 運算式中的擴張運算子。", + "Spread_types_may_only_be_created_from_object_types_2698": "Spread 類型只能從物件類型建立。", + "Starting_compilation_in_watch_mode_6031": "在監看模式中開始編譯...", + "Statement_expected_1129": "必須是陳述式。", + "Statements_are_not_allowed_in_ambient_contexts_1036": "環境內容中不得有陳述式。", + "Static_members_cannot_reference_class_type_parameters_2302": "靜態成員不得參考類別類型參數。", + "Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1_2699": "靜態屬性 '{0}' 與建構函式 '{1}' 的內建屬性 'Function.{0}' 相衝突。", + "Strict_Type_Checking_Options_6173": "Strict 類型檢查選項", + "String_literal_expected_1141": "必須是字串常值。", + "String_literal_with_double_quotes_expected_1327": "應有具雙引號的字串常值。", + "Stylize_errors_and_messages_using_color_and_context_experimental_6073": "使用色彩及內容來設計錯誤與訊息的風格 (實驗)。", + "Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_t_2717": "後續的屬性宣告必須具有相同的類型。屬性 '{0}' 的類型必須是 '{1}',但此處卻是類型 '{2}'。", + "Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_t_2403": "後續的變數宣告必須具有相同的類型。變數 '{0}' 的類型必須是 '{1}' 但卻是 '{2}'。", + "Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2_5064": "模式 '{1}' 的替代 '{0}' 類型不正確,必須為 'string',但得到 '{2}'。", + "Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character_5062": "模式 '{1}' 中的替代 '{0}' 最多只可有一個 '*' 字元。", + "Substitutions_for_pattern_0_should_be_an_array_5063": "模式 '{0}' 的替代應為陣列。", + "Substitutions_for_pattern_0_shouldn_t_be_an_empty_array_5066": "模式 '{0}' 的替代項目不應為空陣列。", + "Successfully_created_a_tsconfig_json_file_6071": "已成功建立 tsconfig.json 檔案。", + "Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors_2337": "建構函式外部或建構函式內的巢狀函式中不允許 super 呼叫。", + "Suppress_excess_property_checks_for_object_literals_6072": "不對物件常值進行多餘的屬性檢查。", + "Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures_6055": "針對缺少索引簽章的索引物件隱藏 noImplicitAny 錯誤。", + "Symbol_reference_does_not_refer_to_the_global_Symbol_constructor_object_2470": "'Symbol' 參考不是參考全域 Symbol 建構函式物件。", + "Syntax_Colon_0_6023": "語法: {0}", + "The_0_operator_cannot_be_applied_to_type_symbol_2469": "無法將 '{0}' 運算子套用至類型 'symbol'。", + "The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead_2447": "布林類型不允許有 '{0}' 運算子。請考慮改用 '{1}'。", + "The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead_2696": "'Object' 類型可指派給極少數的其他類型。要改用 'any' 類型嗎?", + "The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_stand_2496": "無法在 ES3 和 ES5 的箭號函式中參考 'arguments' 物件。請考慮使用標準函式運算式。", + "The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_usi_2522": "在 ES3 與 ES5 的非同步函式或方法中,無法參考 'arguments' 物件。請考慮使用標準函式或方法。", + "The_body_of_an_if_statement_cannot_be_the_empty_statement_1313": "'if' 陳述式的主體不能是空白陳述式。", + "The_character_set_of_the_input_files_6163": "輸入檔的字元集。", + "The_containing_function_or_module_body_is_too_large_for_control_flow_analysis_2563": "內含的函式或模組主體對控制流程分析而言過大。", + "The_current_host_does_not_support_the_0_option_5001": "目前的主機不支援 '{0}' 選項。", + "The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context_2714": "匯出指派的運算式必須是環境內容中的識別碼或完整名稱。", + "The_files_list_in_config_file_0_is_empty_18002": "設定檔 '{0}' 中的 'files' 清單是空的。", + "The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback_1060": "Promise 的 'then' 方法第一個參數必須為回撥。", + "The_global_type_JSX_0_may_not_have_more_than_one_property_2608": "全域類型 'JSX.{0}' 的屬性不得超過一個。", + "The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_option_1343": "只有在為 'target' 及 'module' 編譯器選項使用 'ESNext' 時,才允許 'import.meta' 中繼屬性。", + "The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary_2527": "'{0}' 的推斷型別參考了無法存取的 '{1}' 型別。必須有型別註解。", + "The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern_2491": "'for...in' 陳述式的左側不得為解構模式。", + "The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation_2404": "'for...in' 陳述式左側不得使用類型註釋。", + "The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access_2406": "'for...in' 陳述式的左邊必須是變數或屬性存取。", + "The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any_2405": "'for...in' 陳述式的左側必須是類型 'string' 或 'any'。", + "The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation_2483": "'for...of' 陳述式的左側不得使用類型註釋。", + "The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access_2487": "'for...of' 陳述式的左邊必須是變數或屬性存取。", + "The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type_2362": "算術運算的左側必須是類型 'any'、'number' 或列舉類型。", + "The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access_2364": "指派運算式的左邊必須是變數或屬性存取。", + "The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol_2360": "'in' 運算式的左側必須是 'any'、'string'、'number' 或 'symbol' 類型。", + "The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_paramete_2358": "'instanceof' 運算式左側必須是類型 'any'、物件類型或型別參數。", + "The_locale_used_when_displaying_messages_to_the_user_e_g_en_us_6156": "對使用者顯示訊息時所使用的地區設定 (例如 'zh-tw')", + "The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files_6136": "在 node_modules 及載入 JavaScript 檔案下搜尋時的最大相依性深度。", + "The_operand_of_a_delete_operator_cannot_be_a_read_only_property_2704": "刪除運算子的運算元不得為唯讀屬性。", + "The_operand_of_a_delete_operator_must_be_a_property_reference_2703": "刪除運算子的運算元必須是屬性參考。", + "The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access_2357": "遞增或遞減運算子的運算元必須是變數或屬性存取。", + "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601": "JSX 項目建構函式的傳回型別必須傳回物件類型。", + "The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any_1237": "參數裝飾項目函式的傳回型別必須是 'void' 或 'any'。", + "The_return_type_of_a_property_decorator_function_must_be_either_void_or_any_1236": "屬性裝飾項目函式的傳回型別必須是 'void' 或 'any'。", + "The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_t_1058": "非同步函式的傳回型別必須是有效的 Promise,或不得包含可呼叫的 'then' 成員。", + "The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_1064": "非同步函式或方法的傳回類型必須為全域 Promise 類型。", + "The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_but_2407": "'for...in' 陳述式的右方必須是類型 'any'、物件類型或型別參數,但此處為類型 '{0}'。", + "The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type_2363": "算術運算的右側必須是 'any'、'number' 或列舉類型。", + "The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter_2361": "'in' 運算式的右側必須是類型 'any'、物件類型或型別參數。", + "The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_F_2359": "'instanceof' 運算式的右側必須是 'any' 類型,或是可指派給 'Function' 介面類型的類型。", + "The_specified_path_does_not_exist_Colon_0_5058": "指定的路徑不存在: '{0}'。", + "The_target_of_an_assignment_must_be_a_variable_or_a_property_access_2541": "指派的目標必須是變數或屬性存取。", + "The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access_2701": "物件剩餘指派的目標必須為變數或屬性存取。", + "The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1_2684": "類型 '{0}' 的 'this' 內容無法指派給方法之類型 '{1}' 的 'this'。", + "The_this_types_of_each_signature_are_incompatible_2685": "各個簽章的 'this' 類型不相容。", + "The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_typ_2453": "無法從使用方式推斷型別參數 '{0}' 的型別引數。請考慮明確地指定型別引數。", + "The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value__2547": "非同步迭代器的 'next()' 方法傳回的類型,對具有 'value' 屬性的類型必須為 Promise。", + "The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property_2490": "迭代器之 'next()' 方法傳回的類型必須具有 'value' 屬性。", + "The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer_1189": "'for...in' 陳述式的變數宣告不得有初始設定式。", + "The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer_1190": "'for...of' 陳述式的變數宣告不得有初始設定式。", + "The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any_2410": "不支援 'with' 陳述式。'with' 區塊中的所有符號都會有類型 'any'。", + "This_constructor_function_may_be_converted_to_a_class_declaration_80002": "此建構函式可轉換為類別宣告。", + "This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found_2354": "此語法需要已匯入的協助程式,但找不到模組 '{0}'。", + "This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1_2343": "此語法需要名為 '{1}' 的已匯入協助程式,但模組 '{0}' 沒有匯出的成員 '{1}'。", + "Trailing_comma_not_allowed_1009": "尾端不得為逗號。", + "Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule_6153": "以個別模組的形式轉換每個檔案的語言 (類似於 'ts.transpileModule')。", + "Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_mod_7035": "如有 'npm install @types/{0}',請試用,否則請新增內含 'declare module '{0}';' 的宣告 (.d.ts) 檔案", + "Trying_other_entries_in_rootDirs_6110": "正在嘗試 'rootDirs' 中的其他項目。", + "Trying_substitution_0_candidate_module_location_Colon_1_6093": "正在嘗試替代 '{0}',候選模組位置: '{1}'。", + "Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2_2493": "無法將長度為 '{1}' 的元組類型 '{0}' 指派給長度為 '{2}' 的元組。", + "Type_0_cannot_be_converted_to_type_1_2352": "類型 '{0}' 無法轉換為類型 '{1}'。", + "Type_0_cannot_be_used_as_an_index_type_2538": "類型 '{0}' 無法作為索引類型。", + "Type_0_cannot_be_used_to_index_type_1_2536": "類型 '{0}' 無法用來為類型 '{1}' 編制索引。", + "Type_0_does_not_satisfy_the_constraint_1_2344": "類型 '{0}' 不符合條件約束 '{1}'。", + "Type_0_has_no_matching_index_signature_for_type_1_2537": "類型 '{0}' 沒有與類型 '{1}' 相符的索引簽章。", + "Type_0_has_no_properties_in_common_with_type_1_2559": "類型 '{0}' 與類型 '{1}' 沒有任何共通的屬性。", + "Type_0_has_no_property_1_2460": "類型 '{0}' 沒有屬性 '{1}'。", + "Type_0_has_no_property_1_and_no_string_index_signature_2459": "類型 '{0}' 沒有屬性 '{1}',也沒有字串索引簽章。", + "Type_0_is_not_a_constructor_function_type_2507": "類型 '{0}' 不是建構函式類型。", + "Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Prom_1055": "類型 '{0}' 不是 ES5/ES3 中的有效非同步函式傳回型別,因為它不是指與 Promise 相容的建構函式值。", + "Type_0_is_not_an_array_type_2461": "類型 '{0}' 不是陣列類型。", + "Type_0_is_not_an_array_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators_2568": "類型 '{0}' 不是陣列類型。請使用編譯器選項 '-downlevelIteration' 允許逐一查看迭代器。", + "Type_0_is_not_an_array_type_or_a_string_type_2495": "類型 '{0}' 不是陣列類型或字串類型。", + "Type_0_is_not_an_array_type_or_a_string_type_Use_compiler_option_downlevelIteration_to_allow_iterati_2569": "類型 '{0}' 不是陣列類型或字串類型。請使用編譯器選項 '-downlevelIteration' 允許逐一查看迭代器。", + "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549": "類型 '{0}' 不是陣列類型或字串類型,或沒有會傳回迭代器的 '[Symbol.iterator]()' 方法。", + "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548": "類型 '{0}' 不是陣列類型,或沒有會傳回迭代器的 '[Symbol.iterator]()' 方法。", + "Type_0_is_not_assignable_to_type_1_2322": "類型 '{0}' 不可指派給類型 '{1}'。", + "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_2719": "無法將類型 '{0}' 指派給類型 '{1}'。有兩種使用此名稱的不同類型存在,但彼此並不相關。", + "Type_0_is_not_comparable_to_type_1_2678": "類型 '{0}' 無法和類型 '{1}' 比較。", + "Type_0_is_not_generic_2315": "'{0}' 不是泛型類型。", + "Type_0_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator_2504": "類型 '{0}' 必須具備會傳回非同步迭代器的 '[Symbol.asyncIterator]()' 方法。", + "Type_0_must_have_a_Symbol_iterator_method_that_returns_an_iterator_2488": "類型 '{0}' 必須具備會傳回迭代器的 '[Symbol.iterator]()' 方法。", + "Type_0_provides_no_match_for_the_signature_1_2658": "類型 '{0}' 沒有符合特徵標記 '{1}' 的項目。", + "Type_0_recursively_references_itself_as_a_base_type_2310": "類型 '{0}' 將自己當做基底類型遞迴參考。", + "Type_alias_0_circularly_references_itself_2456": "類型別名 '{0}' 會循環參考自己。", + "Type_alias_name_cannot_be_0_2457": "類型別名不得為 '{0}'。", + "Type_annotation_cannot_appear_on_a_constructor_declaration_1093": "建構函式宣告不得有類型註釋。", + "Type_argument_candidate_1_is_not_a_valid_type_argument_because_it_is_not_a_supertype_of_candidate_0_2455": "因為型別引數候選項 '{1}' 不是候選項 '{0}' 的超級類型,所以不是有效的型別引數。", + "Type_argument_expected_1140": "必須是型別引數。", + "Type_argument_list_cannot_be_empty_1099": "型別引數清單不得為空白。", + "Type_arguments_cannot_be_used_here_1342": "此處不得使用型別引數。", + "Type_declaration_files_to_be_included_in_compilation_6124": "要包含在編譯內的類型宣告檔案。", + "Type_expected_1110": "必須是類型。", + "Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method_1062": "類型在其本身 'then' 方法的完成回撥中直接或間接受到參考。", + "Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member_1320": "'await' 運算元類型必須是有效的 Promise,或不得包含可呼叫的 'then' 成員。", + "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322": "'yield*' 運算元的反覆項目類型必須是有效的 Promise,或不得包含可呼叫的 'then' 成員。", + "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321": "非同步產生器中的 'yield' 運算元類型必須是有效的 Promise,或不得包含可呼叫的 'then' 成員。", + "Type_parameter_0_has_a_circular_constraint_2313": "類型參數 '{0}' 具有循環條件約束。", + "Type_parameter_0_has_a_circular_default_2716": "型別參數 '{0}' 包含循環的預設值。", + "Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4008": "匯出介面中呼叫簽章的型別參數 '{0}' 具有或使用私用名稱 '{1}'。", + "Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4006": "匯出介面中建構函式簽章的型別參數 '{0}' 具有或使用私用名稱 '{1}'。", + "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002": "匯出類別的型別參數 '{0}' 具有或使用私用名稱 '{1}'。", + "Type_parameter_0_of_exported_function_has_or_is_using_private_name_1_4016": "匯出函式的型別參數 '{0}' 具有或使用私用名稱 '{1}'。", + "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004": "匯出介面的型別參數 '{0}' 具有或使用私用名稱 '{1}'。", + "Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1_4083": "匯出類型別名的型別參數 '{0}' 具有或正在使用私人名稱 '{1}'。", + "Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4014": "匯出介面中方法的型別參數 '{0}' 具有或使用私用名稱 '{1}'。", + "Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4012": "匯出類別中公用方法的型別參數 '{0}' 具有或使用私用名稱 '{1}'。", + "Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4010": "匯出類別中公用靜態方法的型別參數 '{0}' 具有或使用私用名稱 '{1}'。", + "Type_parameter_declaration_expected_1139": "必須是型別參數宣告。", + "Type_parameter_list_cannot_be_empty_1098": "型別參數清單不得為空白。", + "Type_parameter_name_cannot_be_0_2368": "型別參數名稱不得為 '{0}'。", + "Type_parameters_cannot_appear_on_a_constructor_declaration_1092": "建構函式宣告不得有類型參數。", + "Type_predicate_0_is_not_assignable_to_1_1226": "型別述詞 '{0}' 不可指派給 '{1}'。", + "Type_reference_directive_0_was_not_resolved_6120": "======== 類型參考指示詞 '{0}' 未解析。========", + "Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2_6119": "======== 類型參考指示詞 '{0}' 已成功解析為 '{1}',主要: {2}。========", + "Types_have_separate_declarations_of_a_private_property_0_2442": "類型具有私用屬性 '{0}' 的個別宣告。", + "Types_of_parameters_0_and_1_are_incompatible_2328": "參數 '{0}' 和 '{1}' 的類型不相容。", + "Types_of_property_0_are_incompatible_2326": "屬性 '{0}' 的類型不相容。", + "Unable_to_open_file_0_6050": "無法開啟檔案 '{0}'。", + "Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression_1238": "無法解析以運算式形式呼叫之類別裝飾項目的簽章。", + "Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression_1241": "無法解析以運算式形式呼叫之方法裝飾項目的簽章。", + "Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression_1239": "無法解析以運算式形式呼叫之參數裝飾項目的簽章。", + "Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression_1240": "無法解析以運算式形式呼叫之屬性裝飾項目的簽章。", + "Unexpected_end_of_text_1126": "未預期的文字結尾。", + "Unexpected_token_1012": "未預期的語彙基元。", + "Unexpected_token_A_constructor_method_accessor_or_property_was_expected_1068": "未預期的語彙基元。必須是建構函式、方法、存取子或屬性。", + "Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces_1069": "權杖錯誤。類型參數名稱不應有大括號。", + "Unexpected_token_expected_1179": "未預期的語彙基元。必須是 '{'。", + "Unknown_compiler_option_0_5023": "不明的編譯器選項 '{0}'。", + "Unknown_option_excludes_Did_you_mean_exclude_6114": "選項 'excludes' 未知。您是指 'exclude' 嗎?", + "Unknown_type_acquisition_option_0_17010": "未知的類型取得選項 '{0}'。", + "Unreachable_code_detected_7027": "偵測到無法執行到的程式碼。", + "Unsupported_locale_0_6049": "不支援的地區設定 '{0}'。", + "Unterminated_Unicode_escape_sequence_1199": "未結束的 Unicode 逸出序列。", + "Unterminated_quoted_string_in_response_file_0_6045": "回應檔 '{0}' 中有未結束的括號字串。", + "Unterminated_regular_expression_literal_1161": "未結束的規則運算式常值。", + "Unterminated_string_literal_1002": "未結束的字串常值。", + "Unterminated_template_literal_1160": "未結束的樣板常值。", + "Untyped_function_calls_may_not_accept_type_arguments_2347": "不具類型的函式呼叫無法接受類型引數。", + "Unused_label_7028": "未使用的標籤。", + "Updating_output_timestamps_of_project_0_6359": "正在更新專案 '{0}' 的輸出時間戳記...", + "Use_synthetic_default_member_95016": "使用綜合 'default' 成員。", + "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494": "只有在 ECMAScript 5 及更高版本中,才可在 'for...of' 陳述式中使用字串。", + "VERSION_6036": "版本", + "Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it_2560": "類型為 '{0}' 的值與類型 '{1}' 沒有任何共通的屬性。確定要呼叫嗎?", + "Value_of_type_0_is_not_callable_Did_you_mean_to_include_new_2348": "無法呼叫類型 '{0}' 的值。您要包含 'new' 嗎?", + "Variable_0_implicitly_has_an_1_type_7005": "變數 '{0}' 隱含有 '{1}' 類型。", + "Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined_7034": "變數 '{0}' 在某些其類型無法判斷的位置隱含地擁有類型 '{1}'。", + "Variable_0_is_used_before_being_assigned_2454": "變數 '{0}' 已在指派之前使用。", + "Variable_declaration_expected_1134": "必須是變數宣告。", + "Variable_declaration_list_cannot_be_empty_1123": "變數宣告清單不得為空白。", + "Version_0_6029": "版本 {0}", + "Watch_input_files_6005": "監看輸入檔案。", + "Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen_6191": "是否要將已過期的主控台輸出,維持在監看模式下,而非清除螢幕。", + "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001": "您無法重新命名標準 TypeScript 程式庫中所定義的項目。", + "You_cannot_rename_this_element_8000": "您無法重新命名這個項目。", + "_0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write__1329": "'{0}' 在此只接受極少數的引數用為裝飾項目。要先呼叫此項目,然後再寫入 '@{0}()' 嗎?", + "_0_are_specified_twice_The_attribute_named_0_will_be_overwritten_2710": "'{0}' 指定了兩次。將會覆寫名為 '{0}' 的屬性。", + "_0_can_only_be_used_in_a_ts_file_8009": "'{0}' 只可用於 .ts 檔案中。", + "_0_expected_1005": "必須是 '{0}'。", + "_0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_reference_7023": "'{0}' 因為沒有傳回型別註解,且在其中一個傳回運算式中直接或間接參考了自己,所以隱含了傳回型別 'any'。", + "_0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or__7022": "'{0}' 因為沒有類型註釋,且在其本身的初始設定式中直接或間接參考了自己,所以隱含有類型 'any'。", + "_0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible_2692": "'{0}' 為基元,但 '{1}' 為包裝函式物件。建議盡可能使用 '{0}'。", + "_0_is_declared_but_its_value_is_never_read_6133": "'{0}' 已宣告但從未讀取其值。", + "_0_is_declared_but_never_used_6196": "宣告了 '{0}',但從未使用過。", + "_0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2_17012": "'{0}' 對關鍵字 '{1}' 而言不是有效的中繼屬性。您是指 '{2}' 嗎?", + "_0_is_referenced_directly_or_indirectly_in_its_own_base_expression_2506": "'{0}' 在其本身的基底運算式中直接或間接受到參考。", + "_0_is_referenced_directly_or_indirectly_in_its_own_type_annotation_2502": "'{0}' 在其本身的類型註釋中直接或間接受到參考。", + "_0_list_cannot_be_empty_1097": "'{0}' 清單不得為空白。", + "_0_modifier_already_seen_1030": "已有 '{0}' 修飾詞。", + "_0_modifier_cannot_appear_on_a_class_element_1031": "類別項目不得有 '{0}' 修飾詞。", + "_0_modifier_cannot_appear_on_a_constructor_declaration_1089": "建構函式宣告不得有 '{0}' 修飾詞。", + "_0_modifier_cannot_appear_on_a_data_property_1043": "資料屬性不得有 '{0}' 修飾詞。", + "_0_modifier_cannot_appear_on_a_module_or_namespace_element_1044": "模組或命名空間元素不能有 '{0}' 修飾詞。", + "_0_modifier_cannot_appear_on_a_parameter_1090": "參數不得有 '{0}' 修飾詞。", + "_0_modifier_cannot_appear_on_a_type_member_1070": "類型成員不能有 '{0}' 修飾詞。", + "_0_modifier_cannot_appear_on_an_index_signature_1071": "索引簽章不能有 '{0}' 修飾詞。", + "_0_modifier_cannot_be_used_here_1042": "無法在此處使用 '{0}' 修飾詞。", + "_0_modifier_cannot_be_used_in_an_ambient_context_1040": "無法在環境內容中使用 '{0}' 修飾詞。", + "_0_modifier_cannot_be_used_with_1_modifier_1243": "'{0}' 修飾詞無法與 '{1}' 修飾詞並用。", + "_0_modifier_cannot_be_used_with_a_class_declaration_1041": "'{0}' 修飾詞無法與類別宣告並用。", + "_0_modifier_must_precede_1_modifier_1029": "'{0}' 修飾詞必須在 '{1}' 修飾詞之前。", + "_0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here_2702": "'{0}' 只參考類型,但在這裡用作命名空間。", + "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_2693": "'{0}' 只會參考類型,但此處將其用為值。", + "_0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead_2686": "'{0}' 指的是全域的 UMD,但目前的檔案為模組。請考慮改為新增匯入。", + "_0_tag_already_specified_1223": "已指定 '{0}' 標記。", + "_0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag_1253": "'{0}' 標記不得獨立用作頂層 JSDoc 標記。", + "_0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type_7010": "缺少傳回型別註解的 '{0}' 隱含了 '{1}' 傳回型別。", + "abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration_1242": "'abstract' 修飾詞只能出現在類別宣告、方法宣告或屬性宣告。", + "await_expression_is_only_allowed_within_an_async_function_1308": "只有非同步函式才允許 'await' 運算式。", + "await_expressions_cannot_be_used_in_a_parameter_initializer_2524": "'await' 運算式不得用於參數初始設定式。", + "baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1_6106": "'baseUrl' 選項已設為 '{0}'。此值將用於解析非相對的模組名稱 '{1}'。", + "can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment_1312": "'=' 僅能在解構指派內的物件常值屬性中使用。", + "case_or_default_expected_1130": "必須是 'case' 或 'default'。", + "class_expressions_are_not_currently_supported_9003": "目前不支援 'class' 運算式。", + "const_declarations_can_only_be_declared_inside_a_block_1156": "只能在區塊內宣告 'const' 宣告。", + "const_declarations_must_be_initialized_1155": "'const' 宣告必須初始化。", + "const_enum_member_initializer_was_evaluated_to_a_non_finite_value_2477": "'const' 列舉成員初始設定式已評估為非有限值。", + "const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN_2478": "'const' 列舉成員初始設定式已評估為不允許的值 'NaN'。", + "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475": "'const' 列舉只可用於屬性或索引存取運算式中,或用於匯入宣告、匯出指派或類型查詢的右側。", + "delete_cannot_be_called_on_an_identifier_in_strict_mode_1102": "不得在 strict 模式中對識別碼呼叫 'delete'。", + "delete_this_Project_0_is_up_to_date_because_it_was_previously_built_6360": "刪除此項目 - 因為先前已建置專案 '{0}',所以其為最新狀態", + "enum_declarations_can_only_be_used_in_a_ts_file_8015": "「列舉宣告」只可用於 .ts 檔案中。", + "export_can_only_be_used_in_a_ts_file_8003": "'export=' 只可用於 .ts 檔案中。", + "export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always__2668": "'export' 修飾詞無法套用至環境模組或模組增強指定,原因是這二者永遠會顯示。", + "extends_clause_already_seen_1172": "已經有 'extends' 子句。", + "extends_clause_must_precede_implements_clause_1173": "'extends' 子句必須在 'implements' 子句之前。", + "extends_clause_of_exported_class_0_has_or_is_using_private_name_1_4020": "匯出類別 '{0}' 的 'extends' 子句具有或使用私用名稱 '{1}'。", + "extends_clause_of_exported_interface_0_has_or_is_using_private_name_1_4022": "匯出介面 '{0}' 的 'extends' 子句具有或使用私用名稱 '{1}'。", + "file_6025": "檔案", + "get_and_set_accessor_must_have_the_same_this_type_2682": "'get' 和 'set' 存取子必須有相同的 'this' 類型。", + "get_and_set_accessor_must_have_the_same_type_2380": "get' 和 'set' 存取子的類型必須相同。", + "implements_clause_already_seen_1175": "已經有 'implements' 子句。", + "implements_clauses_can_only_be_used_in_a_ts_file_8005": "'implements clauses' 只可用於 .ts 檔案中。", + "import_can_only_be_used_in_a_ts_file_8002": "'import ... =' 只可用於 .ts 檔案中。", + "infer_declarations_are_only_permitted_in_the_extends_clause_of_a_conditional_type_1338": "只允許在條件式類型的 'extends' 子句中使用 'infer' 宣告。", + "interface_declarations_can_only_be_used_in_a_ts_file_8006": "'interface declarations' 只可用於 .ts 檔案中。", + "let_declarations_can_only_be_declared_inside_a_block_1157": "只能在區塊內宣告 'let' 宣告。", + "let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations_2480": "'let' 或 'const' 宣告中不得使用 'let' 作為名稱。", + "module_declarations_can_only_be_used_in_a_ts_file_8007": "'module declarations' 只可用於 .ts 檔案中。", + "new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead_1150": "new T[]' 不能用來建立陣列。請改用 'new Array()'。", + "new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type_7009": "目標缺少建構簽章的 'new' 運算式隱含了 'any' 類型。", + "non_null_assertions_can_only_be_used_in_a_ts_file_8013": "'non-null assertions' 只可用於 .ts 檔案中。", + "options_6024": "選項", + "or_expected_1144": "必須是 '{' 或 ';'。", + "package_json_does_not_have_a_0_field_6100": "'package.json' 沒有 '{0}' 欄位。", + "package_json_has_0_field_1_that_references_2_6101": "'package.json' 有參考 '{2}' 的 '{0}' 欄位 '{1}'。", + "parameter_modifiers_can_only_be_used_in_a_ts_file_8012": "'parameter modifiers' 只可用於 .ts 檔案中。", + "paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0_6091": "'paths' 選項已指定,將尋找符合模組名稱 '{0}' 的模式。", + "readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024": "'readonly' 修飾詞只能出現在屬性宣告或索引簽章。", + "require_call_may_be_converted_to_an_import_80005": "'require' 呼叫可能會轉換為匯入。", + "rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107": "'rootDirs' 選項已設定。該選項將用於解析相對的模組名稱 '{0}'。", + "super_can_only_be_referenced_in_a_derived_class_2335": "只有衍生類別中才可參考 'super'。", + "super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions_2660": "只有在衍生類別或物件常值運算式的成員中才可參考 'super'。", + "super_cannot_be_referenced_in_a_computed_property_name_2466": "計算的屬性名稱中不得參考 'super'。", + "super_cannot_be_referenced_in_constructor_arguments_2336": "建構函式引數中不得參考 'super'。", + "super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_highe_2659": "當選項 'target' 為 'ES2015' 或更高時,只有在物件常值運算式的成員中才允許 'super'。", + "super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class_17011": "必須先呼叫 'super' 才能存取衍生類別建構函式中 'super' 的屬性。", + "super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class_17009": "必須先呼叫 'super' 才能存取衍生類別中建構函式的 'this'。", + "super_must_be_followed_by_an_argument_list_or_member_access_1034": "'super' 之後必須接引數清單或成員存取。", + "super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_der_2338": "只有在建構函式、成員函式或衍生類別的成員存取子中,才能存取 'super' 屬性。", + "this_cannot_be_referenced_in_a_computed_property_name_2465": "計算的屬性名稱中不得參考 'this'。", + "this_cannot_be_referenced_in_a_module_or_namespace_body_2331": "模組或命名空間主體中不得參考 'this'。", + "this_cannot_be_referenced_in_a_static_property_initializer_2334": "靜態屬性初始設定式中不得參考 'this'。", + "this_cannot_be_referenced_in_constructor_arguments_2333": "建構函式引數中不得參考 'this'。", + "this_cannot_be_referenced_in_current_location_2332": "目前的位置中不得參考 'this'。", + "this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_2683": "因為 'this' 沒有型別註解,所以隱含具有類型 'any'。", + "type_aliases_can_only_be_used_in_a_ts_file_8008": "'type aliases' 只可用於 .ts 檔案中。", + "type_arguments_can_only_be_used_in_a_ts_file_8011": "'type arguments' 只可用於 .ts 檔案中。", + "type_assertion_expressions_can_only_be_used_in_a_ts_file_8016": "'type assertion expressions' 只可用於 .ts 檔案中。", + "type_parameter_declarations_can_only_be_used_in_a_ts_file_8004": "'type parameter declarations' 只可用於 .ts 檔案中。", + "types_can_only_be_used_in_a_ts_file_8010": "'types' 只可用於 .ts 檔案中。", + "unique_symbol_types_are_not_allowed_here_1335": "這裡不允許 'unique symbol' 型別。", + "unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement_1334": "只有變數陳述式中的變數允許 'unique symbol' 型別。", + "unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name_1333": "'unique symbol' 型別無法用在具有繫結名稱的變數宣告上。", + "with_statements_are_not_allowed_in_an_async_function_block_1300": "非同步函式區塊中不允許 'with' 陳述式。", + "with_statements_are_not_allowed_in_strict_mode_1101": "不得在 strict 模式中使用 'with' 陳述式。", + "yield_expressions_cannot_be_used_in_a_parameter_initializer_2523": "'yield' 運算式不得用於參數初始設定式。" +} \ No newline at end of file diff --git a/node_modules/typescript/package.json b/node_modules/typescript/package.json new file mode 100644 index 0000000..82883ee --- /dev/null +++ b/node_modules/typescript/package.json @@ -0,0 +1,145 @@ +{ + "_from": "typescript", + "_id": "typescript@3.2.2", + "_inBundle": false, + "_integrity": "sha512-VCj5UiSyHBjwfYacmDuc/NOk4QQixbE+Wn7MFJuS0nRuPQbof132Pw4u53dm264O8LPc2MVsc7RJNml5szurkg==", + "_location": "/typescript", + "_phantomChildren": {}, + "_requested": { + "type": "tag", + "registry": true, + "raw": "typescript", + "name": "typescript", + "escapedName": "typescript", + "rawSpec": "", + "saveSpec": null, + "fetchSpec": "latest" + }, + "_requiredBy": [ + "#DEV:/", + "#USER" + ], + "_resolved": "https://registry.npmjs.org/typescript/-/typescript-3.2.2.tgz", + "_shasum": "fe8101c46aa123f8353523ebdcf5730c2ae493e5", + "_spec": "typescript", + "_where": "/Users/jessitron/code/jessitron/stringify-tree", + "author": { + "name": "Microsoft Corp." + }, + "bin": { + "tsc": "./bin/tsc", + "tsserver": "./bin/tsserver" + }, + "browser": { + "fs": false, + "os": false, + "path": false + }, + "bugs": { + "url": "https://github.com/Microsoft/TypeScript/issues" + }, + "bundleDependencies": false, + "dependencies": {}, + "deprecated": false, + "description": "TypeScript is a language for application scale JavaScript development", + "devDependencies": { + "@octokit/rest": "latest", + "@types/browserify": "latest", + "@types/chai": "latest", + "@types/convert-source-map": "latest", + "@types/del": "latest", + "@types/glob": "latest", + "@types/gulp": "3.X", + "@types/gulp-concat": "latest", + "@types/gulp-help": "latest", + "@types/gulp-if": "0.0.33", + "@types/gulp-newer": "latest", + "@types/gulp-rename": "0.0.33", + "@types/gulp-sourcemaps": "0.0.32", + "@types/jake": "latest", + "@types/merge2": "latest", + "@types/minimatch": "latest", + "@types/minimist": "latest", + "@types/mkdirp": "latest", + "@types/mocha": "latest", + "@types/node": "8.5.5", + "@types/q": "latest", + "@types/run-sequence": "latest", + "@types/source-map-support": "latest", + "@types/through2": "latest", + "@types/travis-fold": "latest", + "@types/xml2js": "^0.4.0", + "browser-resolve": "^1.11.2", + "browserify": "latest", + "chai": "latest", + "chalk": "latest", + "convert-source-map": "latest", + "del": "latest", + "fancy-log": "latest", + "fs-extra": "^6.0.1", + "gulp": "3.X", + "gulp-clone": "latest", + "gulp-concat": "latest", + "gulp-help": "latest", + "gulp-if": "latest", + "gulp-insert": "latest", + "gulp-newer": "latest", + "gulp-rename": "latest", + "gulp-sourcemaps": "latest", + "gulp-typescript": "latest", + "istanbul": "latest", + "jake": "latest", + "lodash": "4.17.10", + "merge2": "latest", + "minimist": "latest", + "mkdirp": "latest", + "mocha": "latest", + "mocha-fivemat-progress-reporter": "latest", + "plugin-error": "latest", + "prex": "^0.4.3", + "q": "latest", + "remove-internal": "^2.9.2", + "run-sequence": "latest", + "source-map-support": "latest", + "through2": "latest", + "travis-fold": "latest", + "tslint": "latest", + "typescript": "next", + "vinyl": "latest", + "vinyl-sourcemaps-apply": "latest", + "xml2js": "^0.4.19" + }, + "engines": { + "node": ">=4.2.0" + }, + "homepage": "https://www.typescriptlang.org/", + "keywords": [ + "TypeScript", + "Microsoft", + "compiler", + "language", + "javascript" + ], + "license": "Apache-2.0", + "main": "./lib/typescript.js", + "name": "typescript", + "repository": { + "type": "git", + "url": "git+https://github.com/Microsoft/TypeScript.git" + }, + "scripts": { + "build": "npm run build:compiler && npm run build:tests", + "build:compiler": "jake local", + "build:tests": "jake tests", + "clean": "jake clean", + "gulp": "gulp", + "jake": "jake", + "lint": "jake lint", + "pretest": "jake tests", + "setup-hooks": "node scripts/link-hooks.js", + "start": "node lib/tsc", + "test": "jake runtests-parallel light=false" + }, + "typings": "./lib/typescript.d.ts", + "version": "3.2.2" +} diff --git a/node_modules/wrappy/LICENSE b/node_modules/wrappy/LICENSE new file mode 100644 index 0000000..19129e3 --- /dev/null +++ b/node_modules/wrappy/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/wrappy/README.md b/node_modules/wrappy/README.md new file mode 100644 index 0000000..98eab25 --- /dev/null +++ b/node_modules/wrappy/README.md @@ -0,0 +1,36 @@ +# wrappy + +Callback wrapping utility + +## USAGE + +```javascript +var wrappy = require("wrappy") + +// var wrapper = wrappy(wrapperFunction) + +// make sure a cb is called only once +// See also: http://npm.im/once for this specific use case +var once = wrappy(function (cb) { + var called = false + return function () { + if (called) return + called = true + return cb.apply(this, arguments) + } +}) + +function printBoo () { + console.log('boo') +} +// has some rando property +printBoo.iAmBooPrinter = true + +var onlyPrintOnce = once(printBoo) + +onlyPrintOnce() // prints 'boo' +onlyPrintOnce() // does nothing + +// random property is retained! +assert.equal(onlyPrintOnce.iAmBooPrinter, true) +``` diff --git a/node_modules/wrappy/package.json b/node_modules/wrappy/package.json new file mode 100644 index 0000000..3f9c63f --- /dev/null +++ b/node_modules/wrappy/package.json @@ -0,0 +1,59 @@ +{ + "_from": "wrappy@1", + "_id": "wrappy@1.0.2", + "_inBundle": false, + "_integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=", + "_location": "/wrappy", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "wrappy@1", + "name": "wrappy", + "escapedName": "wrappy", + "rawSpec": "1", + "saveSpec": null, + "fetchSpec": "1" + }, + "_requiredBy": [ + "/inflight", + "/once" + ], + "_resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "_shasum": "b5243d8f3ec1aa35f1364605bc0d1036e30ab69f", + "_spec": "wrappy@1", + "_where": "/Users/jessitron/code/jessitron/stringify-tree/node_modules/inflight", + "author": { + "name": "Isaac Z. Schlueter", + "email": "i@izs.me", + "url": "http://blog.izs.me/" + }, + "bugs": { + "url": "https://github.com/npm/wrappy/issues" + }, + "bundleDependencies": false, + "dependencies": {}, + "deprecated": false, + "description": "Callback wrapping utility", + "devDependencies": { + "tap": "^2.3.1" + }, + "directories": { + "test": "test" + }, + "files": [ + "wrappy.js" + ], + "homepage": "https://github.com/npm/wrappy", + "license": "ISC", + "main": "wrappy.js", + "name": "wrappy", + "repository": { + "type": "git", + "url": "git+https://github.com/npm/wrappy.git" + }, + "scripts": { + "test": "tap --coverage test/*.js" + }, + "version": "1.0.2" +} diff --git a/node_modules/wrappy/wrappy.js b/node_modules/wrappy/wrappy.js new file mode 100644 index 0000000..bb7e7d6 --- /dev/null +++ b/node_modules/wrappy/wrappy.js @@ -0,0 +1,33 @@ +// Returns a wrapper function that returns a wrapped callback +// The wrapper function should do some stuff, and return a +// presumably different callback function. +// This makes sure that own properties are retained, so that +// decorations and such are not lost along the way. +module.exports = wrappy +function wrappy (fn, cb) { + if (fn && cb) return wrappy(fn)(cb) + + if (typeof fn !== 'function') + throw new TypeError('need wrapper function') + + Object.keys(fn).forEach(function (k) { + wrapper[k] = fn[k] + }) + + return wrapper + + function wrapper() { + var args = new Array(arguments.length) + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i] + } + var ret = fn.apply(this, args) + var cb = args[args.length-1] + if (typeof ret === 'function' && ret !== cb) { + Object.keys(cb).forEach(function (k) { + ret[k] = cb[k] + }) + } + return ret + } +} diff --git a/node_modules/yn/index.js b/node_modules/yn/index.js new file mode 100644 index 0000000..0b2a1c2 --- /dev/null +++ b/node_modules/yn/index.js @@ -0,0 +1,28 @@ +'use strict'; +const lenient = require('./lenient'); + +module.exports = (val, opts) => { + val = String(val).trim(); + opts = Object.assign({ + lenient: false, + default: null + }, opts); + + if (opts.default !== null && typeof opts.default !== 'boolean') { + throw new TypeError(`Expected the \`default\` option to be of type \`boolean\`, got \`${typeof opts.default}\``); + } + + if (/^(?:y|yes|true|1)$/i.test(val)) { + return true; + } + + if (/^(?:n|no|false|0)$/i.test(val)) { + return false; + } + + if (opts.lenient === true) { + return lenient(val, opts); + } + + return opts.default; +}; diff --git a/node_modules/yn/lenient.js b/node_modules/yn/lenient.js new file mode 100644 index 0000000..0a50c43 --- /dev/null +++ b/node_modules/yn/lenient.js @@ -0,0 +1,108 @@ +'use strict'; + +const YES_MATCH_SCORE_THRESHOLD = 2; +const NO_MATCH_SCORE_THRESHOLD = 1.25; + +const yMatch = new Map([ + [5, 0.25], + [6, 0.25], + [7, 0.25], + ['t', 0.75], + ['y', 1], + ['u', 0.75], + ['g', 0.25], + ['h', 0.25], + ['k', 0.25] +]); + +const eMatch = new Map([ + [2, 0.25], + [3, 0.25], + [4, 0.25], + ['w', 0.75], + ['e', 1], + ['r', 0.75], + ['s', 0.25], + ['d', 0.25], + ['f', 0.25] +]); + +const sMatch = new Map([ + ['q', 0.25], + ['w', 0.25], + ['e', 0.25], + ['a', 0.75], + ['s', 1], + ['d', 0.75], + ['z', 0.25], + ['x', 0.25], + ['c', 0.25] +]); + +const nMatch = new Map([ + ['h', 0.25], + ['j', 0.25], + ['k', 0.25], + ['b', 0.75], + ['n', 1], + ['m', 0.75] +]); + +const oMatch = new Map([ + [9, 0.25], + [0, 0.25], + ['i', 0.75], + ['o', 1], + ['p', 0.75], + ['k', 0.25], + ['l', 0.25] +]); + +function getYesMatchScore(val) { + let score = 0; + const y = val[0]; + const e = val[1]; + const s = val[2]; + + if (yMatch.has(y)) { + score += yMatch.get(y); + } + + if (eMatch.has(e)) { + score += eMatch.get(e); + } + + if (sMatch.has(s)) { + score += sMatch.get(s); + } + + return score; +} + +function getNoMatchScore(val) { + let score = 0; + const n = val[0]; + const o = val[1]; + + if (nMatch.has(n)) { + score += nMatch.get(n); + } + + if (oMatch.has(o)) { + score += oMatch.get(o); + } + + return score; +} + +module.exports = (val, opts) => { + if (getYesMatchScore(val) >= YES_MATCH_SCORE_THRESHOLD) { + return true; + } + + if (getNoMatchScore(val) >= NO_MATCH_SCORE_THRESHOLD) { + return false; + } + + return opts.default; +}; diff --git a/node_modules/yn/license b/node_modules/yn/license new file mode 100644 index 0000000..654d0bf --- /dev/null +++ b/node_modules/yn/license @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/yn/package.json b/node_modules/yn/package.json new file mode 100644 index 0000000..00b352f --- /dev/null +++ b/node_modules/yn/package.json @@ -0,0 +1,82 @@ +{ + "_from": "yn@^2.0.0", + "_id": "yn@2.0.0", + "_inBundle": false, + "_integrity": "sha1-5a2ryKz0CPY4X8dklWhMiOavaJo=", + "_location": "/yn", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "yn@^2.0.0", + "name": "yn", + "escapedName": "yn", + "rawSpec": "^2.0.0", + "saveSpec": null, + "fetchSpec": "^2.0.0" + }, + "_requiredBy": [ + "/ts-node" + ], + "_resolved": "https://registry.npmjs.org/yn/-/yn-2.0.0.tgz", + "_shasum": "e5adabc8acf408f6385fc76495684c88e6af689a", + "_spec": "yn@^2.0.0", + "_where": "/Users/jessitron/code/jessitron/stringify-tree/node_modules/ts-node", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "bugs": { + "url": "https://github.com/sindresorhus/yn/issues" + }, + "bundleDependencies": false, + "contributors": [ + { + "name": "Justin Woo", + "email": "moomoowoo@gmail.com" + }, + { + "name": "Mark Stosberg", + "email": "mark@rideamigos.com" + } + ], + "deprecated": false, + "description": "Parse yes/no like values", + "devDependencies": { + "ava": "*", + "xo": "*" + }, + "engines": { + "node": ">=4" + }, + "files": [ + "index.js", + "lenient.js" + ], + "homepage": "https://github.com/sindresorhus/yn#readme", + "keywords": [ + "yn", + "yes", + "no", + "cli", + "prompt", + "validate", + "input", + "answer", + "true", + "false", + "parse", + "lenient" + ], + "license": "MIT", + "name": "yn", + "repository": { + "type": "git", + "url": "git+https://github.com/sindresorhus/yn.git" + }, + "scripts": { + "test": "xo && ava" + }, + "version": "2.0.0" +} diff --git a/node_modules/yn/readme.md b/node_modules/yn/readme.md new file mode 100644 index 0000000..e6a4a42 --- /dev/null +++ b/node_modules/yn/readme.md @@ -0,0 +1,83 @@ +# yn [![Build Status](https://travis-ci.org/sindresorhus/yn.svg?branch=master)](https://travis-ci.org/sindresorhus/yn) + +> Parse yes/no like values + +Useful for validating answers of a CLI prompt. + +- + +The following case-insensitive values are recognized: + +```js +'y', 'yes', 'true', true, '1', 1, 'n', 'no', 'false', false, '0', 0 +``` + +*Enable lenient mode to gracefully handle typos.* + + +## Install + +``` +$ npm install --save yn +``` + + +## Usage + +```js +const yn = require('yn'); + +yn('y'); +//=> true + +yn('NO'); +//=> false + +yn(true); +//=> true + +yn('abomasum'); +//=> null + +yn('abomasum', {default: false}); +//=> false + +yn('mo', {lenient: true}); +//=> false +``` + +Unrecognized values return `null`. + + +## API + +### yn(input, [options]) + +#### input + +Type: `any` + +Value that should be converted. + +#### options + +Type: `object` + +##### lenient + +Type: `boolean`
      +Default: `false` + +Use a key distance-based score to leniently accept typos of `yes` and `no`. + +##### default + +Type: `boolean`
      +Default: `null` + +Default value if no match was found. + + +## License + +MIT © [Sindre Sorhus](http://sindresorhus.com) diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..40bbadf --- /dev/null +++ b/package-lock.json @@ -0,0 +1,298 @@ +{ + "name": "stringify-tree", + "version": "1.0.0", + "lockfileVersion": 1, + "requires": true, + "dependencies": { + "@types/lodash": { + "version": "4.14.119", + "resolved": "https://registry.npmjs.org/@types/lodash/-/lodash-4.14.119.tgz", + "integrity": "sha512-Z3TNyBL8Vd/M9D9Ms2S3LmFq2sSMzahodD6rCS9V2N44HUMINb75jNkSuwAx7eo2ufqTdfOdtGQpNbieUjPQmw==", + "dev": true + }, + "@types/lodash.flatten": { + "version": "4.4.4", + "resolved": "https://registry.npmjs.org/@types/lodash.flatten/-/lodash.flatten-4.4.4.tgz", + "integrity": "sha512-F106FV2hmztEtMHozFMfS41u+58vjMEv2SJljMlXmPCn13yWS+/B1r0KjQuaZpsPE857req0BunDwzgpqQ2Ydg==", + "dev": true, + "requires": { + "@types/lodash": "*" + } + }, + "@types/mocha": { + "version": "5.2.5", + "resolved": "https://registry.npmjs.org/@types/mocha/-/mocha-5.2.5.tgz", + "integrity": "sha512-lAVp+Kj54ui/vLUFxsJTMtWvZraZxum3w3Nwkble2dNuV5VnPA+Mi2oGX9XYJAaIvZi3tn3cbjS/qcJXRb6Bww==", + "dev": true + }, + "@types/node": { + "version": "10.12.18", + "resolved": "https://registry.npmjs.org/@types/node/-/node-10.12.18.tgz", + "integrity": "sha512-fh+pAqt4xRzPfqA6eh3Z2y6fyZavRIumvjhaCL753+TVkGKGhpPeyrJG2JftD0T9q4GF00KjefsQ+PQNDdWQaQ==", + "dev": true + }, + "arrify": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/arrify/-/arrify-1.0.1.tgz", + "integrity": "sha1-iYUI2iIm84DfkEcoRWhJwVAaSw0=", + "dev": true + }, + "balanced-match": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.0.tgz", + "integrity": "sha1-ibTRmasr7kneFk6gK4nORi1xt2c=", + "dev": true + }, + "brace-expansion": { + "version": "1.1.11", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", + "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", + "dev": true, + "requires": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "browser-stdout": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/browser-stdout/-/browser-stdout-1.3.1.tgz", + "integrity": "sha512-qhAVI1+Av2X7qelOfAIYwXONood6XlZE/fXaBSmW/T5SzLAmCgzi+eiWE7fUvbHaeNBQH13UftjpXxsfLkMpgw==", + "dev": true + }, + "buffer-from": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.1.tgz", + "integrity": "sha512-MQcXEUbCKtEo7bhqEs6560Hyd4XaovZlO/k9V3hjVUF/zwW7KBVdSK4gIt/bzwS9MbR5qob+F5jusZsb0YQK2A==", + "dev": true + }, + "commander": { + "version": "2.15.1", + "resolved": "http://registry.npmjs.org/commander/-/commander-2.15.1.tgz", + "integrity": "sha512-VlfT9F3V0v+jr4yxPc5gg9s62/fIVWsd2Bk2iD435um1NlGMYdVCq+MjcXnhYq2icNOizHr1kK+5TI6H0Hy0ag==", + "dev": true + }, + "concat-map": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", + "integrity": "sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=", + "dev": true + }, + "debug": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/debug/-/debug-3.1.0.tgz", + "integrity": "sha512-OX8XqP7/1a9cqkxYw2yXss15f26NKWBpDXQd0/uK/KPqdQhxbPa994hnzjcE2VqQpDslf55723cKPUOGSmMY3g==", + "dev": true, + "requires": { + "ms": "2.0.0" + } + }, + "diff": { + "version": "3.5.0", + "resolved": "https://registry.npmjs.org/diff/-/diff-3.5.0.tgz", + "integrity": "sha512-A46qtFgd+g7pDZinpnwiRJtxbC1hpgf0uzP3iG89scHk0AUC7A1TGxf5OiiOUv/JMZR8GOt8hL900hV0bOy5xA==", + "dev": true + }, + "escape-string-regexp": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", + "integrity": "sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=", + "dev": true + }, + "fs.realpath": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", + "integrity": "sha1-FQStJSMVjKpA20onh8sBQRmU6k8=", + "dev": true + }, + "glob": { + "version": "7.1.2", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.2.tgz", + "integrity": "sha512-MJTUg1kjuLeQCJ+ccE4Vpa6kKVXkPYJ2mOCQyUuKLcLQsdrMCpBPUi8qVE6+YuaJkozeA9NusTAw3hLr8Xe5EQ==", + "dev": true, + "requires": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.0.4", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + } + }, + "growl": { + "version": "1.10.5", + "resolved": "https://registry.npmjs.org/growl/-/growl-1.10.5.tgz", + "integrity": "sha512-qBr4OuELkhPenW6goKVXiv47US3clb3/IbuWF9KNKEijAy9oeHxU9IgzjvJhHkUzhaj7rOUD7+YGWqUjLp5oSA==", + "dev": true + }, + "has-flag": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", + "integrity": "sha1-tdRU3CGZriJWmfNGfloH87lVuv0=", + "dev": true + }, + "he": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/he/-/he-1.1.1.tgz", + "integrity": "sha1-k0EP0hsAlzUVH4howvJx80J+I/0=", + "dev": true + }, + "inflight": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", + "integrity": "sha1-Sb1jMdfQLQwJvJEKEHW6gWW1bfk=", + "dev": true, + "requires": { + "once": "^1.3.0", + "wrappy": "1" + } + }, + "inherits": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.3.tgz", + "integrity": "sha1-Yzwsg+PaQqUC9SRmAiSA9CCCYd4=", + "dev": true + }, + "lodash.flatten": { + "version": "4.4.0", + "resolved": "https://registry.npmjs.org/lodash.flatten/-/lodash.flatten-4.4.0.tgz", + "integrity": "sha1-8xwiIlqWMtK7+OSt2+8kCqdlph8=" + }, + "make-error": { + "version": "1.3.5", + "resolved": "https://registry.npmjs.org/make-error/-/make-error-1.3.5.tgz", + "integrity": "sha512-c3sIjNUow0+8swNwVpqoH4YCShKNFkMaw6oH1mNS2haDZQqkeZFlHS3dhoeEbKKmJB4vXpJucU6oH75aDYeE9g==", + "dev": true + }, + "minimatch": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.0.4.tgz", + "integrity": "sha512-yJHVQEhyqPLUTgt9B83PXu6W3rx4MvvHvSUvToogpwoGDOUQ+yDrR0HRot+yOCdCO7u4hX3pWft6kWBBcqh0UA==", + "dev": true, + "requires": { + "brace-expansion": "^1.1.7" + } + }, + "minimist": { + "version": "0.0.8", + "resolved": "http://registry.npmjs.org/minimist/-/minimist-0.0.8.tgz", + "integrity": "sha1-hX/Kv8M5fSYluCKCYuhqp6ARsF0=", + "dev": true + }, + "mkdirp": { + "version": "0.5.1", + "resolved": "http://registry.npmjs.org/mkdirp/-/mkdirp-0.5.1.tgz", + "integrity": "sha1-MAV0OOrGz3+MR2fzhkjWaX11yQM=", + "dev": true, + "requires": { + "minimist": "0.0.8" + } + }, + "mocha": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/mocha/-/mocha-5.2.0.tgz", + "integrity": "sha512-2IUgKDhc3J7Uug+FxMXuqIyYzH7gJjXECKe/w43IGgQHTSj3InJi+yAA7T24L9bQMRKiUEHxEX37G5JpVUGLcQ==", + "dev": true, + "requires": { + "browser-stdout": "1.3.1", + "commander": "2.15.1", + "debug": "3.1.0", + "diff": "3.5.0", + "escape-string-regexp": "1.0.5", + "glob": "7.1.2", + "growl": "1.10.5", + "he": "1.1.1", + "minimatch": "3.0.4", + "mkdirp": "0.5.1", + "supports-color": "5.4.0" + } + }, + "ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", + "dev": true + }, + "once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha1-WDsap3WWHUsROsF9nFC6753Xa9E=", + "dev": true, + "requires": { + "wrappy": "1" + } + }, + "path-is-absolute": { + "version": "1.0.1", + "resolved": "http://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", + "integrity": "sha1-F0uSaHNVNP+8es5r9TpanhtcX18=", + "dev": true + }, + "source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", + "dev": true + }, + "source-map-support": { + "version": "0.5.9", + "resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.5.9.tgz", + "integrity": "sha512-gR6Rw4MvUlYy83vP0vxoVNzM6t8MUXqNuRsuBmBHQDu1Fh6X015FrLdgoDKcNdkwGubozq0P4N0Q37UyFVr1EA==", + "dev": true, + "requires": { + "buffer-from": "^1.0.0", + "source-map": "^0.6.0" + } + }, + "supports-color": { + "version": "5.4.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.4.0.tgz", + "integrity": "sha512-zjaXglF5nnWpsq470jSv6P9DwPvgLkuapYmfDm3JWOm0vkNTVF2tI4UrN2r6jH1qM/uc/WtxYY1hYoA2dOKj5w==", + "dev": true, + "requires": { + "has-flag": "^3.0.0" + } + }, + "ts-node": { + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/ts-node/-/ts-node-7.0.1.tgz", + "integrity": "sha512-BVwVbPJRspzNh2yfslyT1PSbl5uIk03EZlb493RKHN4qej/D06n1cEhjlOJG69oFsE7OT8XjpTUcYf6pKTLMhw==", + "dev": true, + "requires": { + "arrify": "^1.0.0", + "buffer-from": "^1.1.0", + "diff": "^3.1.0", + "make-error": "^1.1.1", + "minimist": "^1.2.0", + "mkdirp": "^0.5.1", + "source-map-support": "^0.5.6", + "yn": "^2.0.0" + }, + "dependencies": { + "minimist": { + "version": "1.2.0", + "resolved": "http://registry.npmjs.org/minimist/-/minimist-1.2.0.tgz", + "integrity": "sha1-o1AIsg9BOD7sH7kU9M1d95omQoQ=", + "dev": true + } + } + }, + "typescript": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-3.2.2.tgz", + "integrity": "sha512-VCj5UiSyHBjwfYacmDuc/NOk4QQixbE+Wn7MFJuS0nRuPQbof132Pw4u53dm264O8LPc2MVsc7RJNml5szurkg==", + "dev": true + }, + "wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=", + "dev": true + }, + "yn": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/yn/-/yn-2.0.0.tgz", + "integrity": "sha1-5a2ryKz0CPY4X8dklWhMiOavaJo=", + "dev": true + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..763a1a7 --- /dev/null +++ b/package.json @@ -0,0 +1,34 @@ +{ + "name": "stringify-tree", + "version": "1.0.0", + "description": "Turn a tree structure into an ascii tree", + "main": "index.js", + "dependencies": { + "lodash.flatten": "^4.4.0" + }, + "devDependencies": { + "@types/lodash.flatten": "^4.4.4", + "@types/mocha": "^5.2.5", + "@types/node": "^10.12.18", + "mocha": "^5.2.0", + "ts-node": "^7.0.1", + "typescript": "^3.2.2" + }, + "scripts": { + "test": "mocha --require ts-node/register test/**/*.test.ts" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/jessitron/stringify-tree.git" + }, + "keywords": [ + "ascii", + "stringify" + ], + "author": "Jessica Kerr", + "license": "ISC", + "bugs": { + "url": "https://github.com/jessitron/stringify-tree/issues" + }, + "homepage": "https://github.com/jessitron/stringify-tree#readme" +} diff --git a/test/stringifyTree.test.ts b/test/stringifyTree.test.ts new file mode 100644 index 0000000..167bdf7 --- /dev/null +++ b/test/stringifyTree.test.ts @@ -0,0 +1,129 @@ +import assert from "assert"; +import { stringifyTree } from ".."; + +describe("stringify", () => { + it("prints one tree", () => { + const tree = { + name: "hi", children: [], + }; + const result = stringifyTree(tree, t => t.name, t => t.children); + console.log("tree:\n" + result); + assert.deepEqual(result, "─ hi"); + }); + it("prints a tree with a child", () => { + const tree = { + name: "hi", children: [ + { name: "child1", children: [] }, + ], + }; + const result = stringifyTree(tree, t => t.name, t => t.children); + console.log("tree:\n" + result); + assert.deepEqual(result, `┬ hi +└── child1`); + }); + it("prints a tree with two children", () => { + const tree = { + name: "hi", children: [ + { name: "child1", children: [] }, + { name: "child2", children: [] }, + ], + }; + const result = stringifyTree(tree, t => t.name, t => t.children); + console.log("tree:\n" + result); + assert.deepEqual(result, `┬ hi +├── child1 +└── child2`); + }); + it("prints a tree with great-grandchildren", () => { + const tree = { + name: "Grandmarti", children: [ + { + name: "Cyndi", children: [ + { + name: "Jess", children: [ + { name: "Evelyn", children: [] }, + { name: "Linda", children: [] }, + ], + }, + ], + }, + { name: "Celia", children: [] }, + ], + }; + const result = stringifyTree(tree, t => t.name, t => t.children); + console.log("tree:\n" + result); + assert.deepEqual(result, `┬ Grandmarti +├─┬ Cyndi +│ └─┬ Jess +│ ├── Evelyn +│ └── Linda +└── Celia`); + }); + + it("prints a tree with two grandchildren", () => { + const tree = { + name: "Grandmarti", children: [ + { + name: "Cyndi", children: [ + { name: "Jess", children: [] } + , { name: "Josh", children: [] }, + ], + }, + { name: "Celia", children: [] }, + ], + }; + const result = stringifyTree(tree, t => t.name, t => t.children); + console.log("tree:\n" + result); + assert.deepEqual(result, `┬ Grandmarti +├─┬ Cyndi +│ ├── Jess +│ └── Josh +└── Celia`); + }); + + it("prints the whole family", () => { + const tree = { + name: "Grandmarti", children: [ + { + name: "Cyndi", children: [ + { + name: "Jess", children: [ + { name: "Evelyn", children: [] }, + { name: "Linda", children: [] }, + ], + }, + { name: "Josh", children: [] }, + { name: "Rachel", children: [] }, + ], + }, + { + name: "Celia", children: [ + { name: "Faith", children: [] }, + { name: "Ellie", children: [] }, + ] + }, + { + name: "Cheri", children: [ + { name: "Liz", children: [] }, + { name: "Nick", children: [] }, + ] + } + ], + }; + const result = stringifyTree(tree, t => t.name, t => t.children); + console.log("tree:\n" + result); + assert.deepEqual(result, `┬ Grandmarti +├─┬ Cyndi +│ ├─┬ Jess +│ │ ├── Evelyn +│ │ └── Linda +│ ├── Josh +│ └── Rachel +├─┬ Celia +│ ├── Faith +│ └── Ellie +└─┬ Cheri + ├── Liz + └── Nick`); + }); +}); diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 0000000..261cdca --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,59 @@ +{ + "compilerOptions": { + /* Basic Options */ + "target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. */ + "module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */ + // "lib": [], /* Specify library files to be included in the compilation. */ + // "allowJs": true, /* Allow javascript files to be compiled. */ + // "checkJs": true, /* Report errors in .js files. */ + // "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */ + // "declaration": true, /* Generates corresponding '.d.ts' file. */ + // "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */ + // "sourceMap": true, /* Generates corresponding '.map' file. */ + // "outFile": "./", /* Concatenate and emit output to single file. */ + // "outDir": "./", /* Redirect output structure to the directory. */ + // "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */ + // "composite": true, /* Enable project compilation */ + // "removeComments": true, /* Do not emit comments to output. */ + // "noEmit": true, /* Do not emit outputs. */ + // "importHelpers": true, /* Import emit helpers from 'tslib'. */ + // "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */ + // "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */ + + /* Strict Type-Checking Options */ + "strict": true, /* Enable all strict type-checking options. */ + // "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */ + // "strictNullChecks": true, /* Enable strict null checks. */ + // "strictFunctionTypes": true, /* Enable strict checking of function types. */ + // "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */ + // "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */ + // "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */ + + /* Additional Checks */ + // "noUnusedLocals": true, /* Report errors on unused locals. */ + // "noUnusedParameters": true, /* Report errors on unused parameters. */ + // "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */ + // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */ + + /* Module Resolution Options */ + // "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */ + // "baseUrl": "./", /* Base directory to resolve non-absolute module names. */ + // "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */ + // "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */ + // "typeRoots": [], /* List of folders to include type definitions from. */ + // "types": [], /* Type declaration files to be included in compilation. */ + // "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */ + "esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */ + // "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */ + + /* Source Map Options */ + // "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */ + // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ + // "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */ + // "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */ + + /* Experimental Options */ + // "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */ + // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */ + } +} \ No newline at end of file